commit 3126f289ff69d967c18613c1d0d5f0e386eb8c67 Author: poka Date: Wed Jan 4 04:02:19 2023 +0100 first diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c20c2ab --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +__pycache__ + diff --git a/data/stackoverflow.csv b/data/stackoverflow.csv new file mode 100644 index 0000000..59c65af --- /dev/null +++ b/data/stackoverflow.csv @@ -0,0 +1,48977 @@ +,Text,Tags +2,aspnet site maps has anyone got experience creating sqlbased aspnet sitemap providersi have got the default xml file websitemap working properly with my menu and sitemappath controls but i will need a way for the users of my site to create and modify pages dynamicallyi need to tie page viewing permissions into the standard aspnet membership system as well,"['sql', 'asp.net']" +4,adding scripting functionality to net applications i have a little game written in c it uses a database as backend it is a trading card game and i wanted to implement the function of the cards as a scriptwhat i mean is that i essentially have an interface icard which a card class implements public class card056 icard and which contains function that are called by the gamenow to make the thing maintainablemoddable i would like to have the class for each card as source code in the database and essentially compile it on first use so when i have to addchange a card i will just add it to the database and tell my application to refresh without needing any assembly deployment especially since we would be talking about 1 assembly per card which means hundreds of assembliesis that possible register a class from a source file and then instantiate it etcicard cardscurrent new mygamecardlibrarycard056cardscurrentonenterplayref currentgamestatethe language is c but extra bonus if it is possible to write the script in any net language,"['c#', '.net']" +5,should i use nested classes in this case i am working on a collection of classes used for video playback and recording i have one main class which acts like the public interface with methods like play stop pause record etc then i have workhorse classes which do the video decoding and video encoding i just learned about the existence of nested classes in c and i am curious to know what programmers think about using them i am a little wary and not really sure what the benefitsdrawbacks are but they seem according to the book i am reading to be used in cases such as minethe book suggests that in a scenario like mine a good solution would be to nest the workhorse classes inside the interface class so there are no separate files for classes the client is not meant to use and to avoid any possible naming conflicts i do not know about these justifications nested classes are a new concept to me just want to see what programmers think about the issue,['c++'] +6,homegrown consumption of web services i have been writing a few web services for a net app now i am ready to consume them i have seen numerous examples where there is homegrown code for consuming the service as opposed to using the auto generated methods visual studio creates when adding the web reference is there some advantage to this,['.net'] +8,automatically update version number i would like the version property of my application to be incremented for each build but i am not sure on how to enable this functionality in visual studio 20052008 i have tried to specify the assemblyversion as 10 but it does not get me exactly what i want i am also using a settings file and in earlier attempts when the assembly version changed my settings got reset to the default since the application looked for the settings file in another directory i would like to be able to thisplay a version number in the form of 1138 so when a user finds a problem i can log the version they are using as well as tell them to upgrade if they have an old releasea short explanation of how the versioning works would also be appreciated when does the build and revision number get incremented,['c#'] +10,how do i connect to a database and loop over a recordset in c whats the simplest way to connect and query a database for a set of records in c,['c#'] +11,how to get the value of built encoded viewstate i need to grab the base64encoded representation of the viewstate obviously this would not be available until fairly late in the request lifecycle which is okfor example if the output of the page includesinput typehidden name viewstate id viewstate valuewepdwujodu0njc5md i need a way on the server side to get the value wepdwujodu0njc5mdto clarify i need this value when the page is being rendered not on postback eg i need to know the viewstate value that is being sent to the client not the viewstate i am getting back from them,"['c#', 'asp.net']" +12,how do i delete a file which is locked by another process in c i am looking for a way to delete a file which is locked by another process using c i suspect the method must be able to find which process is locking the file perhaps by tracking the handles although i am not sure how to do this in c then close that process before being able to complete the file delete using filedelete,['c#'] +16,is nant still supported and suitable for net 35vs2008 i am using msbuild to build my stuff i want to use cruisecontrolnet as by build servernow ccnet refers nant a lot but it looks as if ccnet can do most of the stuff nant could do through the project configuration and msbuild also nant seems a bit unsupported with a beta release that is almost a year old nowin short i am actually quite happy with msbuild especially since it is the official compiler front end and a bit uncomfortable with nant but i do not want to judge prematurelywhat would be reasons to use nant over msbuild especially with ccnet which seems to overlap a bit with nant in terms of features and adding the automated build related stuff,['.net'] +20,net unit testing packages getting back into a bit more net after a fewyears of not using it fulltime and wondering what the good unit testing packages are these daysi am familiar with nunit a few years ago and have played briefly around with ironruby with the goal of getting something like rspec going but do not know much beyond thati realize i could google for this and call it a day but i believe i am likely to get a better and more informed response from asking a question here suggestions,"['c#', '.net']" +22,what language do you use for postgresql triggers and stored procedures postgresql is interesting in that it supports several languages for writing stored procedures which one do you use and why,['sql'] +23,convert hashbytes to varchar i want to get the md5 hash of a string value in sql server 2005 i do this with the following commandselect hashbytesmd5 helloworldhowever this returns a varbinary instead of a varchar value if i attempt to convert 0x68e109f0f40ca72a15e05cc22786f8e6 into a varchar i get ha aa aa aa a a instead of 68e109f0f40ca72a15e05cc22786f8e6is there any sqlbased solutionyes,['sql'] +24,datatable vs dataset i currently use a datatable to get results from a database which i can use in my codehowever many example on the web show using a dataset instead and accessing the tables through the collections methodis there any advantage performance wise or otherwise of using datasets or datatables as a storage method for sql results,['c#'] +26,how do you thisable browser autocomplete on web form field input tag how do you thisable autocomplete in the major browsers for a specific input or form field,['html'] +27,good stllike library for c what are good libraries for c with datastructures like vectors deques stacks hashmaps treemaps sets etc plain c please and platformindependent,['c'] +28,what are effective options for embedding video in an aspnet web site a quick glance at the presentday internet would seem to indicate that adobe flash is the obvious choice for embedding video in a web page is this accurate or are they other effective choices does the choice of aspnet as a platform influence this decision,['asp.net'] +32,converting arbg to rgb with alpha blending let us say that we have an argb colorcolor argb colorfromargb127 69 12 255 light urplewhen this is painted on top of an existing color the colors will blend so when it is blended with white the resulting color is colorfromargb255 162 133 255the solution should work like thiscolor blend colorwhite color argb colorfromargb127 69 12 255 light urple color rgb torgbargb blend same as colorfromargb255 162 133 255what is torgbs implementation,['c#'] +33,paging sql server 2005 results how do i page results in sql server 2005i tried it in sql server 20 but there was no reliable way to do this i am now wondering if sql server 2005 has any built in methodwhat i mean by paging is for example if i list users by their username i want to be able to only return the first 10 records then the next 10 records and so onany help would be much appreciated,['sql'] +34,mysqlapache error in php mysql query i am getting the following erroraccess denied for user apachelocalhost using password nowhen using the following codephpincludeincludesconnectphpquery select from storyresult mysql queryquery or diemysql errorecho h1delete storyh1if mysql num rowsresult 0 whilerow mysql fetch rowresult echo brow1bspan alignrighta hrefprocessdelete storyphpidrow0deleteaspan echo br irow2i else echo no stories availablethe connectphp file contains my mysql connect calls that are working fine with my insert queries in another portion of the software if i comment out the result mysql query line then it goes through to the else statement so it is that line or the content in the ifi have been searching the net for any solutions and most seem to be related to too many mysql connections or that the user i am logging into mysql as does not have permission i have checked both i can still perform my other queries elsewhere in the software and i have verified that the account has the correct permissions,"['php', 'mysql']" +36,how to set up unit testing for visual studio c i am having trouble figuring out how to get the testing framework set up and usable in visual studio 2008 for c presumably with the builtin unit testing suiteany links or tutorials would be appreciated,['c++'] +38,how do you pack a visual studio c project for release i am wondering how to make a release build that includes all necessary dll files into the exe so the program can be run on a nondevelopment machine without it having to install the microsoft rethistributable on the target machinewithout doing this you get the error message that the application configuration is not correct and to reinstall,['c++'] +43,how do i run rake tasks within a ruby script i have a rakefile with a rake task that i would normally call from the command linerake blogpost titlei would like to write a ruby script that calls that rake task multiple times but the only solution i see is shelling out using backticks or systemwhats the right way to do this,['ruby'] +45,what code analysis tools do you use for your java projects what code analysis tools do you use on your java projectsi am interested in all kindsstatic code analysis tools findbugs pmd and any otherscode coverage tools cobertura emma and any othersany other instrumentationbased tools anything else if i am missing somethingif applicable also state what build tools you use and how well these tools integrate with both your ides and build tools if a tool is only available a specific way as an ide plugin or say a build tool plugin that information is also worth noting,['java'] +46,what program can i use to generate diagrams of sql viewtable structure i have been tasked with redesigning part of a mssql database structure which currently involves a lot of views some of which contain joins to other views anyway i wonder if anyone here could recommend a utility to automatically generate diagrams to help me visualise the whole structurewhats the best program youve used for such problems,['sql'] +48,the difference between a datagrid and a gridview in aspnet i have been doing aspnet development for a little while now and i have used both the gridview and the datagrid controls before for various things but i never could find a really good reason to use one or the other i would like to knowwhat is the difference between these 2 aspnet controls what are the advantages or thisadvantages of both is one any faster newer easier to maintainthe intellisense summary for the controls does not seem to describe any difference between the two they both can view edit and sort data and automatically generate columns at runtimeedit visual studio 2008 no longer lists datagrid as an available control in the toolbox it is still available for legacy support i assume if you type it in by hand though,['asp.net'] +50,how to easily consume a web service from php is there available any tool for php which can be used to generate code for consuming a web service based on its wsdl something comparable to clicking add web reference in visual studio or the eclipse plugin which does the same thing for java,['php'] +51,how can i create prototype methods like javascript in cnet how is it possible to make prototype methods in cnetin javascript i can do the following to create a trim method for the string objectstringprototypetrim function return thisreplacessghow can i go about doing this in cnet,"['c#', '.net']" +52,how can i java webstart multiple dependent native libraries example i have two shared objects same should apply to dlls the first shared object is from a thirdparty library well call it libaso i have wrapped some of this with jni and created my own library libbso now libb depends on libawhen webstarting both libraries are places in some webstart working area my java code attempts to load libb at this point the system loader will attempt to load liba which is not in the system library path javalibrarypath would not help this the end result is that libb has an unsatisfied link and cannot be used i have tried loading liba before libb but that still does not work seems the os wants to do that loading for me is there any way i can make this work other than statically compiling,['java'] +54,c and arrow keys i am new to c and am doing some work in an existing application i have a directx viewport that has components in it that i want to be able to position using arrow keyscurrently i am overriding processcmdkey and catching arrow input and send an onkeypress event this works but i want to be able to use modifiersaltctrlshift as soon as i am holding a modifier and press an arrow no events are triggered that i am listening todoes anyone have any ideas or suggestions on where i should go with this,['c#'] +57,is a confirm email input good practice when user changes email address my organization has a form to allow users to update their email address with usit is suggested that we have two input boxes for email the second as an email confirmationi always copypaste my email address when faced with the confirmationi am assuming most of our users are not so savvyregardless is this considered a good practicei cannot stand it personally but i also realize it probably is not meant for meif someone screws up their email they cannot login and they must call to sort things out,['html'] +58,how to reference to multiple version assembly i am developing a sharepoint application and use net ajaxcontroltoolkit library we are adding a custom aspx page to the sharepoint sharepoint 2007 run in quirks mode so i have made some modification to the ajax library to make it behave like it normally should the problem is the other team already use ajax library and it is a different version with mine this cause conflict because there could be only one dll in the bin folder with the same namefrom what i know net should be able to handle this situation easily i have tried using strong name and gac to solve it but it still refer to the dll in the bin folder if there is no ajaxcontroltoolkitdll in the bin folder the application will simply fail to load the assembly if i use complete assembly information on my like this register tagprefixajaxcontroltoolkit namespaceajaxcontroltoolkit assemblyajaxcontroltoolkit version1029918064 publickeytoken12345678abcdefgh cultureneutralit gives me compiler error cs0433can someone help me on how to use multiple version of assembly in an application,"['c#', '.net']" +69,multiple foreign keys i have got a table that is supposed to track days and costs for shipping product from one vendor to another we brilliantly p stored both the shipping vendors fedex ups with the product handling vendors think dunder mifflin in a vendor table so i have three columns in my shipping details table that all reference vendorno for some reason mysql is not letting me define all three as foreign keys any ideascreate table shipping grid id int not null auto increment primary key comment unique id for each row shipping vendor no int6 not null comment foreign key to vendorno for the shipping vendor vendors type must be 3 start vendor no int6 not null comment foreign key to vendorno for the vendor being shipped from end vendor no int6 not null comment foreign key to the vendorno for the vendor being shipped to shipment duration int1 default 1 comment duration in whole days shipment will take price float55 not null comment price in us dollars per shipment lbs down to 5 decimal places is flat rate tinyint1 default 0 comment 1 if is flat rate regardless of weight 0 if price is by lbs index shipping vendor no index start vendor no index end vendor no foreign key shipping vendor no references vendor no foreign key start vendor no references vendor no foreign key end vendor no references vendor no type innodbedited to remove double primary key definitionyeah unfortunately that did not fix it though now i am gettingcannot create table removed my db nameshipping gridfrm errno 150doing a phpinfo tells me this for mysqlclient api version 5045yes the vendorno is type int6,"['sql', 'mysql']" +71,net 35 rethistributable 200 mb other options i have been using a lot of new net 35 features in the work that i have been doing lately the application that i am building is intended for thistribution among consumers who will probably not have the latest version or perhaps any version of the net framework on their machinesi went to go download the net 35 rethistributable package only to find out that it is almost 200 mb this is unacceptable for my application because it is supposed to be a quick and painless consumer application that installs quickly and keeps a low profile on the users machine for users that have net 35 already installed our binary downloads have been instantaneous so far this 200 mb gorilla will more than quadruple the size of the download is there any other option than this rethistributable package that i can use to make sure the framework is on the machine that would not take the user out of our quick and painless workflow our target time from beginning of download to finalizing the install is less than two minutes is it just not possible for someone who does not already have net installed,['.net'] +72,where should i put my log file for an aspnet application i have a aspnet application that weve written our own logging module formy question is where is the standard place to write a log file to ie the website will be running as the anonymous user identity eg iusr on iis7 and i need a place where i know it will have permission to write tocheers,['asp.net'] +79,some kind of task manager for javascript in firefox 3 recently i have been having issues with firefox 3 on ubuntu hardy heroni will click on a link and it will hang for a while i do not know if its a bug in firefox 3 or a page running too much client side javascript but i would like to try and debug it a bitso my question is is there a way to have some kind of process explorer or task manager sort of thing for firefox 3i would like to be able to see what tabs are using what percent of my processor via the javascript on that page or anything in the page that is causing cpumemory usage does anybody know of a plugin that does this or something similar has anyone else done this kind of inspection another wayi know about firebug but i cannot imagine how i would use it to finger which tab is using a lot of resourcesany suggestions or insights,['javascript'] +80,packaging java apps for the windowslinux desktop i am writing an application in java for the desktop using the eclipse swt library for gui rendering i think swt helps java get over the biggest hurdle for acceptance on the desktop namely providing a java application with a consistent responsive interface that looks like that belonging to any other app on your desktop however i feel that packaging an application is still an issue os x natively provides an easy mechanism for wrapping java apps in native application bundles but producing an app for windowslinux that does not require the user to run an ugly batch file or click on a jar is still a hassle possibly that is not such an issue on linux where the user is likely to be a little more techsavvy but on windows i would like to have a regular exe for himher to runhas anyone had any experience with any of the exe generation tools for java that are out there i have tried jsmooth but had various issues with it is there a better solution before i crack out visual studio and roll my ownedit i should perhaps mention that i am unable to spend a lot of money on a commercial solution,['java'] +81,how do you open a file in c i want to open a file for reading the c way i need to be able to do it fortext files which would involve some sort of read line functionbinary files which would provide a way to read raw data into a char buffer,['c++'] +82,how important is w3c xhtmlcss validation when finalizing work even though i always strive for complete validation these days i often wonder if it is a waste of time if the code runs and it looks the same in all browsers i use browsershotsorg to verify then do i need to take it any further or am i just being overly analwhat level do you hold your code to when you create it fora yourselfb your clientsps jeff and company why does not stack overflow validate edit some good insights i think that since i have been so validobsessed for so long i program knowing what will cause problems and what would not so i am in a better position than people who create a site first and then go back and fix the validation problemsi think i may post another question on stack overflow do you validate as you go or do you finish and then go back and validate as that seems to be where this question is going,['css'] +83,printing from a net service i am working on a project right now that involves receiving a message from another application formatting the contents of that message and sending it to a printer technology of choice is c windows service the output could be called a report i suppose but a reporting engine is not necessary a simple templating engine like stringtemplate or even xslt outputting html would be fine the problem i am having is finding a free way to print this kind of output from a service since it seems that it will work i am working on a prototype using microsofts rdlc populating a local report and then rendering it as an image to a memory stream which i will then print issues with that aremultipage printing will be a big headachestill have to use printdocument to print the memory stream which is unsupported in a windows service though it may work have not gotten that far with the prototype yetif the data coming across changes i have to change the dataset and the class that the data is being deserialized into bad bad badhas anyone had to do anything remotely like this any advice i already posed a question about printing html without user input and after wasting about 3 days on that i have come to the conclusion that it cannot be done at least not with any freely available toolall help is appreciatededit we are on version 20 of the net framework,"['c#', '.net']" +87,best implementation for key value pair data structure so i have been poking around with c a bit lately and all the generic collections have me a little confused say i wanted to represent a data structure where the head of a tree was a key value pair and then there is one optional list of key value pairs below that but no more levels than these would this be suitablepublic class tokentree public tokentree i must admit to not fully understanding this i got it from msdn as far as i can tell idictionary is an interface and dictionary is the default implementation of that interface right subpairs new dictionarystring string public string key public string value public idictionarystring string subpairsit is only really a simple shunt for passing around data,['c#'] +92,accessing isight programatically is it possible to access the isight camera on a macbook programatically by this i mean i would like to be able to just grab still frames from the isight camera on command and then do something with them if so is it only accessible using objective c or could other languages be used as well,['objective-c'] +94,how do you pass a function as a parameter in c i want to create a function that performs a function passed by parameter on a set of data how do you pass a function as a parameter in c,['c'] +98,how to return a page of results from sql many applications have grids that thisplay data from a database table one page at a time many of them also let the user pick the number of records per page sort by any column and navigate back and forth through the resultswhats a good algorithm to implement this pattern without bringing the entire table to the client and then filtering the data on the client how do you bring just the records you want to thisplay to the userdoes linq simplify the solution,"['.net', 'sql']" +100,what are the useful new aspnet features in the net framework 35 i have kept up to date with new features in the c language as it is moved from version 1 through version 3 i have not done such a good job keeping up to date with aspnet i feel like some of the post version 1 features are not so good eg the ajax framework or are just not that useful to me eg the membership framework can anyone recommend any new killer aspnet features that might have gone unnoticed,['asp.net'] +105,asynchronous remoting calls we have a remoting singleton server running in a separate windows service let us call her remotingservice the clients of the remotingservice are aspnet instances many manycurrently the clients remoting call remotingservice and blocks while the remotingservice call is serviced however the remoting service is getting complicated enough with more rpc calls and complex algorithms that the aspnet worker threads are blocked for a significantly long time 45 secondsaccording to this msdn article doing this will not scale well because an aspnet worker thread is blocked for each remoting rpc it advises switching to async handlers to free up aspnet worker threadsthe purpose of an asynchronous handler is to free up an aspnet thread pool thread to service additional requests while the handler is processing the original requestthis seems fine except the remoting call still takes up a thread from the thread poolis this the same thread pool as the aspnet worker threads how should i go about turning my remoting singleton server into an async system such that i free up my aspnet worker threadsi have probably missed out some important information please let me know if there is anything else you need to know to answer the question,['c#'] +106,is there a difference between the on exit and atexit functions is there any difference between int on exitvoid functionint void void argand int atexitvoid functionvoidother than the fact that the function used by on exit gets the exit statusthat is if i do not care about the exit status is there any reason to use one or the otheredit many of the answers warned against on exit because it is nonstandard if i am developing an app that is for internal corporate use and guaranteed to run on specific configurations should i worry about this,['c'] +108,data layer best practices i am in the middle of a thiscussion with a colleague about the best way to implement the data layer in a new applicationone viewpoint is that the data layer should be aware of business objects our own classes that represent an entity and be able to work with that object natively the opposing viewpoint is that the data layer should be objectagnostic and purely handle simple data types strings bools dates etci can see that both approaches may be valid but my own viewpoint is that i prefer the former that way if the data storage medium changes the business layer does not necessarily have to change to accommodate the new data layer it would therefore be a trivial thing to change from a sql data store to a serialized xml filesystem storemy colleagues point of view is that the data layer should not have to know about object definitions and that as long as the data is passed about appropriately that is enough now i know that this is one of those questions that has the potential to start a religious war but i would appreciate any feedback from the community on how you approach such things tia,['.net'] +110,any good advice on using emacs for c project i am looking for a good article on using emacs as cc idesomething like steve yegges effective emacs,['c++'] +111,ikvm and licensing i have been looking into ikvming apache is fop project to use with our net app it is a commercial product and looking into licensing ikvm runs into some sticky areas because of its use of gnu classpath from what i have seen no one can say for sure if this stuff can be used in a commercial product has anyone used ikvm or an ikvmd product in a commercial product heres what i have found so farikvm license page which notes that one dll contains code from other projects their license gplv2 classpath exceptionsaxon for net is generated with ikvm but released under the apache licenseanyone have experience with this,"['java', '.net']" +112,what are the proper permissions for an upload folder with phpapache sorry for the basic question i am a net developer and do not have much experience with lamp setupsi have a php site that will allow uploads to a specific folder i have been told that this folder needs to be owned by the webserver user for the upload process to work so i created the folder and then set permissions as suchchown apacheapache r uploadschmod 755 r uploadsthe only problem now is that the ftp user can not modify the uploaded files at allis there a permission setting that will allow me to still upload files and then modify them later as a user other than the webserver user,['php'] +113,how should i unit test a codegenerator this is a difficult and openended question i know but i thought i would throw it to the floor and see if anyone had any interesting suggestionsi have developed a codegenerator that takes our python interface to our c code generated via swig and generates code needed to expose this as webservices when i developed this code i did it using tdd but i have found my tests to be brittle as hell because each test essentially wanted to verify that for a given bit of input code which happens to be a c header i would get a given bit of outputted code i wrote a small engine that reads test definitions from xml input files and generates test cases from these expectationsthe problem is i dread going in to modify the code at all that and the fact that the unit tests themselves are a complex and b brittleso i am trying to think of alternative approaches to this problem and it strikes me i am perhaps tackling it the wrong way maybe i need to focus more on the outcome ie does the code i generate actually run and do what i want it to rather than does the code look the way i want it tohas anyone got any experiences of something similar to this they would care to share,"['c++', 'python']" +115,passing more parameters in c function pointers let us say i am creating a chess program i have a functionvoid foreachmove void actionchess move chess game gamewhich will call the function pointer action on each valid move this is all well and good but what if i need to pass more parameters to the action function for examplechess move getnextmovechess game game int depth for each valid move determine how good the move is foreachmovemovehandler gamevoid movehandlerchess move move uh oh now i need the variables game and depth from the above functionredefining the function pointer is not the optimal solution the foreachmove function is versatile and many different places in the code reference it it does not make sense for each one of those references to have to update their function to include parameters that they do not needhow can i pass extra parameters to a function that i am calling through a pointer,['c'] +118,speeding up an aspnet web site or application i have an ajaxnet enabled aspnet 20 web site hosting for both the site and the database are out of my control as is the databases schema in testing on hardware i do control the site performs well however on the clients hardware there are noticeable delays when reloading or changing pages what i would like to do is make my application as compact and speedy as possible when i deliver it one idea is to set expiration dates for all of the sites static resources so they are not recalled on page loads by resources i mean images linked style sheets and javascript source files is there an easy way to do thiswhat other ways are there to optimize a net web siteupdate i have run yslow on the site and the areas where i am getting hit the hardest are in the number of javascript and style sheets being loaded 23 js files and 5 style sheets all but one the main style sheet has been inserted by ajaxnet and asp why so many,['asp.net'] +126,how can i determine the ip of my routergateway in java how can i determine the ip of my routergateway in java i can get my ip easily enough i can get my internet ip using a service on a website but how can i determine my gateways ipthis is somewhat easy in net if you know your way around but how do you do it in java,['java'] +127,how do you log errors exceptions in your aspnet apps i am looking for the best way to log errors in an aspnet applicationi want to be able to receive emails when errors occurs in my application with detailed information about the exception and the current requestin my company we used to have our own errormailer catching everything in the globalasax application error it was ok but not very flexible nor configurablewe swithed recently to nlog it is much more configurable we can define different targets for the errors filter them buffer them not tried yet it is a very good improvementbut i thiscovered lately that there is a whole namespace in the net framework for this purpose systemwebmanagement and it can be configured in the healthmonitoring section of webconfighave you ever worked with net health monitoring what is your solution for error loggingthanksvincent,['asp.net'] +129,considering n2 cms but worried about performance is this justified hy does anyone worked with n2 content management systemif yes how does it perform performance wiseunder heavy loadit seems pretty simple and easy to useadrian,['asp.net'] +132,arrays of arrays in java this is a nasty one for me i am a php guy working in java on a jsp project i know how to do what i am attempting through too much code and a complete lack of finesse i would prefer to do it right here is the situationi am writing a small thisplay to show customers what days they can water their lawns based on their watering group abcde and what time of year it is our seasons look like thissummer 51 to 831 spring 31 to 430 fall 91 to 1031winter 1 to 228 an example might beif i am in group a here would be my allowed timeswinter mondays onlyspring tues thurs satsummer any dayfall tues thurs satif i was writing this in php i would use arrays like thismmondayttuesdaytthursday etcscheduleawintermscheduleaspringttsscheduleasummeranyscheduleafallttsschedulebwinterti could make the days arrays arraytuesdaythursdaysaturday etc but it is not necessary for what i am really trying to accomplishi will also need to setup arrays to determine what season i am inseasonssummerstart0501seasonssummerend0801can anyone suggest a really cool way to do this i will have todays date and the group letter i will need to get out of my function a day m or a series of days tts anythanks folks,"['java', 'php']" +134,what is a good way to denormalize a mysql database i have a large database of normalized order data that is becoming very slow to query for reporting many of the queries that i use in reports join five or six tables and are having to examine tens or hundreds of thousands of linesthere are lots of queries and most have been optimized as much as possible to reduce server load and increase speed i think it is time to start keeping a copy of the data in a denormalized formatany ideas on an approach should i start with a couple of my worst queries and go from there,['mysql'] +136,what do ref val and out mean on method parameters i am looking for a clear concise and accurate answer ideally as the actual answer although links to good explanations welcomethis also applies to vbnet but the keywords are different byref and byval,"['c#', '.net']" +138,a threadstateexception occures when trying to restart a thread from time to time i get a systemthreadingthreadstateexception when attempting to restart a thread the code in question is as follows make sure the thread is done stoppingwhile thismthreadthreadstate threadstaterunning threadsleep0 respawn a thread if the current one is stopped or does not existif thismthread null thismthreadthreadstate threadstatestopped thismthread new threadnew parameterizedthreadstartmonitor start the threadif check thismthreadstart60 else thismthreadstart0 so two questions is this the correct way of doing things and it is is there a way to prevent the error from occurring,"['c#', '.net']" +143,insert update stored proc on sql server i have written a stored proc that will do an update if a record exists otherwise it will do an insert it looks something like thisupdate mytable set col1col1 col2col2 where ididif rowcount 0insert into mytable col1 col2 values col1 col2my logic behind writing it in this way is that the update will perform an implicit select using the where clause and if that returns 0 then the insert will take placethe alternative to doing it this way would be to do a select and then based on the number of rows returned either do an update or insert this i considered inefficient because if you are to do an update it will cause 2 selects the first explicit select call and the second implicit in the where of the update if the proc were to do an insert then there would be no difference in efficiencyis my logic sound hereis this how you would combine an insert and update into a stored proc,['sql'] +145,speed difference in using inline strings vs concatenation in php5 assume php5 considerphp foo some words case 1 print these are foo case 2 print these are foo case 3 print these are foois there much of a difference between 1 and 2if not what about between 12 and 3,['php'] +156,how best to use file version and assembly version in net there are two version numbers available when building a project file version and assembly version how are you using these numbers keeping them the same autoincrementing one but manually changing the otheralso what about the assemblyinformationalversion attributei would found this support microsoft knowledge base kb article that provided some help how to use assembly version and assembly file version,['.net'] +159,how do you create a debug only function that takes a variable argument list like printf i would like to make a debug logging function with the same parameters as printf but one that can be removed by the preprocessor during optimized buildsfor exampledebug printwarning value d 3n valuei have looked at variadic macros but those are not available on all platforms gcc supports them msvc does not,"['c++', 'c']" +161,best practices for managing and deploying large javascript apps what are some standard practices for managing a mediumlarge javascript application my concerns are both speed for browser download and ease and maintainability of developmentour javascript code is roughly namespaced asvar client var1 var2 accounts 100s of functions and variables orders 100s of functions and variables and subsections etc etc for a couple hundred kb at the moment we have one unpacked unstripped highly readable javascript file to handle all the business logic on the web application in addition there is jquery and several jquery extensions the problem we face is that it takes forever to find anything in the javascript code and the browser still has a dozen files to downloadis it common to have a handful of source javascript files that gets compiled into one final compressed javascript file any other handy hints or best practices,['javascript'] +163,how do you begin designing a large system it is been mentioned to me that i will be the sole developer behind a large new system among other things i will be designing a ui and database schemai am sure i will receive some guidance but i would like to be able to knock their socks off what can i do in the meantime to prepare and what will i need to keep in mind when i sit down at my computer with the speca few things to keep in mind i am a college student at my first real programming job i will be using java we already have scm set up with automated testing etcso tools are not an issue,['java'] +165,read from msg files i need to read from outlook msg file in net without using com api for outlook cos it will not be installed on the machines that my app will run are there any free 3rd party libraries to do that i want to extract from to cc and bcc fields sentreceive date fields would be good if they are also stored in msg files,['c#'] +167,how do i convert a string to an enum in c whats the best way to convert a string to an enumeration value in ci have an html select tag containing the values of an enumeration when the page is posted i want to pick up the value which will be in the form of a string and convert it to the enumeration valuein an ideal world i could do something like thisstatusenum mystatus statusenumparseactivebut that is not valid code,['c#'] +169,whats the best way to get started with osgi what makes a moduleservicebit of application functionality a particularly good candidate for an osgi module i am interested in using osgi in my applications were a java shop and we use spring pretty extensively so i am leaning toward using spring dynamic modules for osgitm service platforms i am looking for a good way to incorporate a little bit of osgi into an application as a trial has anyone here used this or a similar osgi technology are there any pitfalls nicolas thanks i have seen that one it is a good tutorial but i am looking more for ideas on how to do my first real osgi bundle as opposed to a hello world exampledavid thanks for the link ideally with a greenfield app i would design the whole thing to be dynamic what i am looking for right now though is to introduce it in a small piece of an existing application assuming i can pick any piece of the app what are some factors to consider that would make that piece better or worse as an osgi guinea pig,['java'] +172,how do i generate a hashcode from a byte array in c say i have an object that stores a byte array and i want to be able to efficiently generate a hashcode for it i have used the cryptographic hash functions for this in the past because they are easy to implement but they are doing a lot more work than they should to be cryptographically oneway and i do not care about that i am just using the hashcode as a key into a hashtableheres what i have todaystruct somedata iequatablesomedata private readonly byte data public somedatabyte data if null data datalength 0 throw new argumentexceptiondata thisdata new bytedatalength arraycopydata thisdata datalength public override bool equalsobject obj return obj is somedata equalssomedataobj public bool equalssomedata other if otherdatalength datalength return false for int i 0 i datalength i if datai otherdatai return false return true public override int gethashcode return bitconvertertoint32new md5cryptoserviceprovidercomputehashdata 0 any thoughtsdp you are right that i missed a check in equals i have updated it using the existing hashcode from the byte array will result in reference equality or at least that same concept translated to hashcodesfor examplebyte b1 new byte 1 byte b2 new byte 1 int h1 b1gethashcodeint h2 b2gethashcodewith that code despite the two byte arrays having the same values within them they are referring to different parts of memory and will result in probably different hash codes i need the hash codes for two byte arrays with the same contents to be equal,['c#'] +174,best net build tool possible duplicatenant or msbuild which one to choose and when what is the best build tool for neti currently use nant but only because i have experience with ant is msbuild preferred,['.net'] +175,how do you deal with transportlevel errors in sqlconnection every now and then in a high volume net application you might see this exception when you try to execute a querysystemdatasqlclientsqlexception a transportlevel error has occurred when sending the request to the serveraccording to my research this is something that just happens and not much can be done to prevent it it does not happen as a result of a bad query and generally cannot be duplicated it just crops up maybe once every few days in a busy oltp system when the tcp connection to the database goes bad for some reasoni am forced to detect this error by parsing the exception message and then retrying the entire operation from scratch to include using a new connection none of that is prettyanybody have any alternate solutions,['c#'] +182,how do you spawn another process in c how do you run an external program and pass it command line parameters using c if you have to use operating system api include a solution for windows mac and linux,['c'] +183,when to use ilist and when to use list i know that ilist is the interface and list is the concrete type but i still do not know when to use each one what i am doing now is if i do not need the sort or findall methods i use the interface am i right is there a better way to decide when to use the interface or the concrete type,"['c#', '.net']" +184,create an encrypted zip file in python i am creating an zip file with zipfile in python 25 it works ok so farimport zipfile oslocfile testtxtloczip ospathsplitext locfile0 zipzip zipfilezipfile loczip wzipwrite locfilezipclosebut i could not find how to encrypt the files in the zip filei could use system and call pkzip s but i suppose there must be a more pythonic way i am looking for an open source solution,['python'] +192,select where or is there a way to select data where any one of multiple conditions occur on the same fieldexample i would typically write a statement such asselect from table where field 1 or field 2 or field 3is there a way to instead say something likeselect from table where field 1 2 3any help is appreciated,['mysql'] +199,how do you secure databaseyml within ruby on rails applications databaseyml is a plain text file that stores database credentialswhen i deploy my rails applications i have an after deploy callback in my capistrano recipe that creates a symbolic link within the applications config directory to the databaseyml file the file itself is stored in a separate directory that is outside the standard capistrano releases directory structure i chmod 400 the file so it is only readable by the user who created itis this sufficient to lock it down if not what else do you dois anyone encrypting their databaseyml files,['ruby-on-rails'] +200,is mono ready for prime time has anyone used mono the open source net implementation on a large or medium sized project i am wondering if it is ready for real world production environments is it stable fast compatible enough to use does it take a lot of effort to port projects to the mono runtime or is it really really compatible enough to just take of and run already written code for microsofts runtime,['.net'] +205,code to ask yesno question in javascript i could only find the function confirm that gives okcancel buttons is there any way to give yesno buttons,['javascript'] +206,thisplay rows in multiple columns in aspnet gridview by default each row of a gridview maps to each row in a datatable or dataset attached to its datasource but what if i want to thisplay these rows in multiple columns for example if it has 10 rows 5 rows each should be thisplayed in 2 columns side by side also can i do this with the infragistics grid is this possible,['asp.net'] +209,any resharper equivalent for xcode i am a complete xcodeobjectiveccocoa newbie but i am learning fast and really starting to enjoy getting to grips with a new language platform and paradigmone thing is though having been using visual studio with r for so long i have kind of been spoiled with the coding tools such as refactorings and completion etc and as far as i can tell xcode has some fairly limited built in support for this stuffon that note does anyone know if any addins or whatever are available for the xcode environment which add coding helpers such as automatically generating implementation skeletons from a class interface definition etc i suspect there are not but i suppose it cannot help to ask,['objective-c'] +210,cleaning up rtf text i would like to take some rtf input and clean it to remove all rtf formatting except ul b i to paste it into word with minor format informationthe command used to paste into word will be something likeowordactivedocumentactivewindowselectionpasteandformat0 with some rtf text already in the clipboardrtf1ansideff0fonttblf0fnilfcharset0 courier newcolortbl red255green255blue140viewkind4uc1pardhighlight1lang3084f0fs18 the company is a global leader in responsible tourism and was ul the first major hotel chain in north americaulnone to embrace environmental stewardship within its daily operationshighlight0pardo you have any idea on how i can clean up the rtf safely with some regular expressions or something i am using vbnet to do the processing but any net language sample will do,['.net'] +214,java jpanel redraw issues i have a java swing application with a panel that contains three jcomboboxes that do not draw properlythe combox boxes just show up as the down arrow on the right side but without the label of the currently selected valuethe boxes will redraw correctly if the window is resized either bigger or smaller by even one pixelall of my googling has pointed to calling revalidate on the jpanel to fix this but that has not worked for mecalling updateui on the jpanel has changed it from always thisplaying incorrectly to thisplaying incorrectly half of the time has anyone else seen this and found a different way to force a redraw of the combo boxes,['java'] +215,silverlight vs flex my company develops several types of applications a lot of our business comes from doing multimediatype apps typically done in flash however now that side of the house is starting to migrate towards doing flex developmentmost of our other development is done using net i am trying to make a push towards doing silverlight development instead since it would take better advantage of the net developers on staff i prefer the silverlight platform over the flex platform for the simple fact that silverlight is all net code we have more net developers on staff than flashflex developers and most of our flashflex developers are graphic artists not real programmers only reason they push towards flex right now is because it seems like the logical step from flashi have done development using both and i honestly believe silverlight is easier to work with but i am trying to convince people who are only flash developers so heres my question if i am going to go into a meeting to praise silverlight why would a company want to go with silverlight instead of flex other than the obvious not everyone has silverlight what are the pros and cons for each,['.net'] +217,am i missing something about linq i seem to be missing something about linq to me it looks like it is taking some of the elements of sql that i like the least and moving them into the c language and using them for other thingsi mean i could see the benefit of using sqllike statements on things other than databases but if i wanted to write sql well why not just write sql and keep it out of c what am i missing here,"['c#', 'sql']" +220,net get protocol host and port is there a simple way in net to quickly get the current protocol host and port for example if i am on the following urli need to returni know i can use requesturlabsoluteuri to get the complete url and i know i can use requesturlauthority to get the host and port but i am not sure of the best way to get the protocol without parsing out the url stringany suggestions,"['.net', 'asp.net']" +223,table cells larger than they are meant to be i have created a map system for a game that runs on the principle of drawing the picture of the map from tiles there are many reasons for this which i would not go into here but if you really want to know then i am sure you can find out how to contact me i have made the latest version live so you can see exactly where the problem lies and the source the issue is the line between the top 2 tiles and the bottom 2 tiles i cannot figure out why it is gone like this and any help would be appreciatedin the source is a marker called stackoverflow if you search for stackoverflow when viewing source then it should take you to the table in questioni have also uploaded an image of the issue,"['html', 'css']" +225,wcf push to client through firewall see also how does a wcf server inform a wcf client about changes better solution then simple polling eg coment or long pollingi need to use pushtechnology with wcf through client firewalls this must be a common problem and i know for a fact it works in theory see links below but i have failed to get it working and i have not been able to find a code sample that demonstrates itrequirements wcfclients connects to server through tcp port 80 nettcpbindingserver pushes back information at irregular intervals 1 min to several hoursusers should not have to configure their firewalls server pushes must pass through firewalls that have all inbound ports closed tcp duplex on the same connection is needed for this a dual binding does not work since a port has to be opened on the client firewallclients sends heartbeats to server at regular intervals perhaps every 15 mins so server knows client is still aliveserver is iis7 with wasthe solution seems to be duplex nettcpbinding based on this informationwcf through firewalls and natskeeping connections open in iisbut i have yet to find a code sample that works i have tried combining the duplex and tcpactivation samples from microsofts wcf samples without any luck please can someone point me to example code that works or build a small sample app thanks a lot,['.net'] +226,what are the major differences between ansi c and kr c the wikipedia article on ansi c saysone of the aims of the ansi c standardization process was to produce a superset of kr c the first published standard incorporating many of the unofficial features subsequently introduced however the standards committee also included several new features such as function prototypes borrowed from the c programming language and a more capable preprocessor the syntax for parameter declarations was also changed to reflect the c stylethat makes me think that there are differences however i did not see a comparison between kr c and ansi c is there such a document if not what are the major differencesedit i believe the kr book says ansi c on the cover at least i believe the version that i have at home does so perhaps there is not a difference anymore,['c'] +227,whats a good way to check if two datetimes are on the same calendar day in tsql here is the issue i am having i have a large query that needs to compare datetimes in the where clause to see if two dates are on the same day my current solution which sucks is to send the datetimes into a udf to convert them to midnight of the same day and then check those dates for equality when it comes to the query plan this is a thisaster as are almost all udfs in joins or where clauses this is one of the only places in my application that i have not been able to root out the functions and give the query optimizer something it can actually use to locate the best indexin this case merging the function code back into the query seems impracticali think i am missing something simple hereheres the function for referenceif not exists select from dbosysobjects where id object idndbof makedate and type in nfn nif ntf nfs nft execcreate function dbof makedate returns int as begin declare retval int return retval endgoalter function dbof makedate day datetime hour int minute intreturns datetimeascreates a datetime using the yearmonthday portion of day and the hour and minute providedbegindeclare retval datetimeset retval cast castdatepartm day as varchar2 castdatepartd day as varchar2 castdateparty day as varchar4 casthour as varchar2 castminute as varchar2 as datetimereturn retvalendgoto complicate matters i am joining on time zone tables to check the date against the local time which could be different for every rowwhere dbof makedatedateaddhh tzoffset case when dslocaltimezone is not null then 1 else 0 end tthedateineedtocheck 0 0 activitydatemidnightediti am incorporating todds suggestionwhere datediffday dateaddhh tzoffset case when dslocaltimezone is not null then 1 else 0 end tthedateineedtocheck activitydate 0my misconception about how datediff works the same day of year in consecutive years yields 366 not 0 as i expected caused me to waste a lot of effortbut the query plan did not change i think i need to go back to the drawing board with the whole thing,['sql'] +231,actsasreadable rails plugin issue i am using intrideas acts as readable rails plugin for a messaging system i am currently buildingi have defined my message class accordinglyclass post activerecordbase actsasreadableendand everything seems to be working according to plan but when trying to execute to show unread messages in my message view i am running into problemstheir example i have changed underscores to hyphens due to formatting issuesbob userfind by namebobbobreadings postfind unread bybob post 1post 2post 3postfind read bybob postfind1read bybob falsepostfind1read bybob reading 1postfind1read bybob truepostfind1users who read user bobpostfind unread bybob post 2post 3postfind read bybob post 1bobreadings reading 1so it seems as though if i wanted to list the number of unread messages sitting in a mailbox for example inbox 39 i should be able to do something like postfind unread bycurrentusercount but to no avail i always seem to get stuck on the simple view issues after everythings setany ideas,"['ruby-on-rails', 'ruby']" +233,when do you use the this keyword i was curious about how other people use the this keyword i tend to use it in constructors but i may also use it throughout the class in other methods some examplesin a constructorpublic lightvector v thisdir new vectorvelsewherepublic void somemethod vector vec new vector double d vec vec thisradius thisradius,['c#'] +244,how do i marshal a lambda proc in ruby joe van dyk asked the ruby mailing listhiin ruby i guess you cannot marshal a lambdaproc object right is that possible in lisp or other languageswhat i was trying to dol lamda bjsubmit pathtorubyprogram stdin marshaldumplso i am sending backgroundjob a lambda object which contains the contextcode for what to do but guess that was not possible i ended up marshaling a normal ruby object that contained instructions for what to do after the program ranjoe,['ruby'] +246,classes vs 2d arrays which is better to use in php a 2d array or a class i have included an example of what i mean by this using a classclass someclass public name public height public weight function constructname height weight this name name this height height this weight weight classarray1 new someclassbob 10 20classarray2 new someclassfred 15 10classarray3 new someclassned 25 30 using a 2d arraynormalarray1name bobnormalarray1height 10normalarray1weight 20normalarray2name frednormalarray2height 15normalarray2weight 10normalarray3name nednormalarray3height 25normalarray3weight 30assuming that somebody does not come out and show that classes are too slow it looks like class winsi have not idea which answer i should accept to i have just upvoted all of themand i have now written two near identical pages one using the 2d array written before this question was posted and now one using a class and i must say that the class produces much nicer code i have no idea how much overhead is going to be generated but i doubt it will rival the improvement to the code itselfthank you for helping to make me a better programmer,['php'] +247,whats the fastest way to bulk insert a lot of data in sql server c client i am hitting some performance bottlenecks with my c client inserting bulk data into a sql server 2005 database and i am looking for ways in which to speed up the processi am already using the sqlclientsqlbulkcopy which is based on tds to speed up the data transfer across the wire which helped a lot but i am still looking for morei have a simple table that looks like this create table bulkdata containerid int not null binid smallint not null sequence smallint not null itemid int not null left smallint not null top smallint not null right smallint not null bottom smallint not null constraint pkbulkdata primary key clustered containeridid asc binid asc sequence asci am inserting data in chunks that average about 300 rows where containerid and binid are constant in each chunk and the sequence value is 0n and the values are presorted based on the primary key the thisk time performance counter spends a lot of time at 100 so it is clear that thisk io is the main issue but the speeds i am getting are several orders of magnitude below a raw file copydoes it help any if idrop the primary key while i am doing the inserting and recreate it laterdo inserts into a temporary table with the same schema and periodically transfer them into the main table to keep the size of the table where insertions are happening smallanything elsebased on the responses i have gotten let me clarify a little bitportman i am using a clustered index because when the data is all imported i will need to access data sequentially in that order i do not particularly need the index to be there while importing the data is there any advantage to having a nonclustered pk index while doing the inserts as opposed to dropping the constraint entirely for importchopeen the data is being generated remotely on many other machines my sql server can only handle about 10 currently but i would love to be able to add more it is not practical to run the entire process on the local machine because it would then have to process 50 times as much input data to generate the outputjason i am not doing any concurrent queries against the table during the import process i will try dropping the primary key and see if that helps,"['c#', 'sql']" +249,programming a simple irc internetrelaychat client i started using irc at a young age and i have always been fascinated with it as a language exercise i was thinking about programming a simple irc client in ruby with shoes as a graphical frontend my question to you kindsirs what do i need to become familiar with to start on this great adventure besides shoes and ruby of course i imagine there is somesort of specification on irc protocol any pointers,['ruby'] +259,abstraction away from css let me make something quite cleari hate cssit is a neverending nightmare every minor layout change feels like a hack solutions to problems seem to often involve jiggering numbers around like some chef trying to work out exactly how much nutmeg to put in his soontobe famous rice pudding then comes the multiple browser issue the multiple resolution issues to cut a long story short it is a pain a pita if you willmany frameworks seek to abstract away from html custom tags jsfs component system in an effort to make dealing with that particular kettle of fish easieris there anything you folks have used that has a similar concept applied to css something that does a bunch of crossbrowser magic for you supports like variables why do i have to type 3c5c8d every time i want that colour supports caclulated fields which are compiled into css and js etcalternatively am i even thinking about this correctly am i trying to push a very square block through a very round hole,['css'] +261,best method to run a java application as a nix daemon or windows service i am looking for the best method to run a java application as a nix daemon or a windows service i have looked in to the java service wrapper the apache commons project jsvc and the apache commons project procrun so far the java service wrapper looks like it is the best option but i am wondering if there are any other open source friendly licensed products out there,['java'] +263,what is the best free memory leak detector for a cc program and its plugin dlls i have a exe and many plugin dll modules that the exe loads i have source for both a crossplatform with source solution would be ideal but the platform can be narrowed to winxp and visual studio 712003 in my casethe builtin vs leak detector only gives the line where newmalloc was called from but i have a wrapper for allocations so a full symbolic stack trace would be bestthe detector would also be able to detect for a leak in both the exe and its accompanying plugin dll modules,"['c++', 'c']" +264,ruby performance i am pretty keen to develop my first ruby app as my company has finally blessed its use internallyin everything i have read about ruby up to v18 there is never anything positive said about performance but i have found nothing about version 19 the last figures i saw about 18 had it drastically slower than just about everything out there so i am hoping this was addressed in 19has performance drastically improved are there some concrete things that can be done with ruby apps or things to avoid to keep performance at the best possible level,['ruby'] +265,what is the best way to connect and use a sqlite database from c i have done this before in c by including sqliteh but is there a similarly easy way in c,['c#'] +267,aspnet website first start is very slow the first time i load the website in the production web server it start very slow subsequent pages load very quickly included the home pagei precompiled the site but nothing changes i do not have any code at application starti do not have cached itemsany ideas how can i find out what is happening,['asp.net'] +269,sizeof equivalent for reference types i am looking for a way to get the size of an instance of a reference type sizeof is only for value types is this possible,"['c#', '.net']" +270,how to set encoding in getjson jquery in my web app i submit some form fields with jquery getjson method i am having some problems with the encoding the characterset of my app is charsetiso88591 but i think these fields are submitted with utf8 does anyone know how i can set encoding in getjson calls,['jquery'] +272,parse string to timespan i have some strings of xxhyym format where xx is hours and yy is minutes like 05h30m what is an elegant way to convert a string of this type to timespan,['c#'] +273,xpath and selecting a single node i am using xpath in net to parse an xml document along the lines ofxmlnodelist lotsostuff docselectnodesstuforeach xmlnode stuff in lotsostuff xmlnode stuffchild stuffselectsinglenodestuffchild etcthe issue is that the xpath query for stuffchild is always returning the child of the first stuff element never the rest can xpath not be used to query against an individual xmlelement,['.net'] +276,comparing arrays of objects in javascript i want to compare 2 arrays of objects in javascript code the objects have 8 total properties but each object will not have a value for each and the arrays are never going to be any larger than 8 items each so maybe the brute force method of traversing each and then looking at the values of the 8 properties is the easiest way to do what i want to do but before implementing i wanted to see if anyone had a more elegant solution any thoughts,['javascript'] +277,how to convert stdstring to lpcwstr in c unicode i am looking for a method or a code snippet for converting stdstring to lpcwstr,['c++'] +278,why are not enumerations iterable in java 5 and above you have the foreach loop which works magically on anything that implements iterablefor object o list dostuffohowever enumerable still does not implement iterable meaning that to iterate over an enumeration you must do the followingfor ehasmoreelements dostuffenextelementdoes anyone know if there is a reason why enumeration still does not implement iterableedit as a clarification i am not talking about the language concept of an enum i am talking a javaspecific class in the java api called enumeration,['java'] +279,find number of files with a specific extension in all subdirectories is there a way to find the number of files of a specific type without having to loop through all results inn a directorygetfiles or similar method i am looking for something like thisint componentcount magicfindfilecountcwindowssystem32 dlli know that i can make a recursive function to call directorygetfiles but it would be much cleaner if i could do this without all the iteratingedit if it is not possible to do this without recursing and iterating yourself what would be the best way to do it,['c#'] +280,how to add simple tracing in c i want to introduce some tracing to a c application i am writing sadly i can never really remember how it works and would like a tutorial with reference qualities to check up on every now and then it should includeappconfig webconfig stuff to add for registering tracelistenershow to set it up in the calling applicationdo you know the uber tutorial that we should link toedit glenn slaven pointed me in the right direction add this to your appconfigwebconfig inside configurationsystemdiagnostics trace autoflushtrue listeners add typesystemdiagnosticstextwritertracelistener nametextwriter initializedatatracelog listeners tracesystemdiagnosticsthis will add a textwritertracelistener that will catch everything you send to with tracewriteline etcedit danesparza pointed out that you should use tracetraceinformation tracetracewarning and tracetraceerror instead of tracewriteline as they allow you to format messages the same way as stringformattip if you do not add any listeners then you can still see the trace output with the sysinternals program debugview dbgviewexe,['c#'] +281,integrating qt into legacy mfc applications we currently maintain a suit of mfc applications that are fairly well designed however the user interface is beginning to look tired and a lot of the code is in need quite a bit of refactoring to tidy up some duplication andor performance problems we make use of quite a few custom controls that handle all their own drawing all written using mfcrecently i have been doing more research into qt and the benefits it provides crossplatform and supports what you might call a more professional looking framework for ui developmentmy question is what would be the best approach to perhaps moving to the qt framework does qt play nice with mfc would it be better to start porting some of our custom controls to qt and gradually integrate more and more into our existing mfc apps is this possibleany advice or previous experience is appreciated,['c++'] +286,how bad is dynamic casting we often hearread that one should avoid dynamic casting i was wondering what would be good use examples of it according to youedityes i am aware of that other thread it is indeed when reading one of the first answers there that i asked my question,['c++'] +288,create an attribute to break the build ok this kind of follows on from my previous questionwhat i would really like to do is create some sort of attribute which allows me to decorate a method that will break the build much like the obsoletereason true attribute but without falsely identifying obsolete codeto clarify i dont want it to break the build on any f6 build press i only want it to break the build if a method decorated with the attribute is called somewhere else in the code like i said similar to obsolete but not the samei know i am not alone in this since other users want to use it for other reasons i have never created custom attributes before so it is all new to me,['.net'] +289,multiple classes in a header file vs a single header file per class for whatever reason our company has a coding guideline that stateseach class shall have it is own header and implementation fileso if we wrote a class called mystring we would need an associated mystringhh and mystringcxxdoes anyone else do this has anyone seen any compiling performance repercussions as a result does 50 classes in 10 files compile just as quickly as 50 classes in 2500 files if not is the difference noticeablewe code c and use gcc 344 as our everyday compiler,['c++'] +291,proxy which requires authentication with android emulator has anybody managed to get the android emulator working behind a proxy which requires authenticationi have tried setting the httpproxy argument to httpdomainusernamepasswordipportbut am having no success i have tried following the docs to no avail i have also tried the verboseproxy setting but this no longer seems to existany pointers,['android'] +306,can someone point me to some guides for wpf i am having trouble finding good guides for wpfi have experience in c and net but i do not know anything about wpf except for the regular marketingish description of the technology as a wholecan anyone point me to a good beginners tutorialguide on wpf,['.net'] +311,how to get your own local ipaddress from an udpsocket cc you have multiple network adaptersbind a udp socket to an local port without specifying an addressreceive packets on one of the adaptershow do you get the local ip address of the adapter which received the packetthe question is what is the ip address from the receiver adapter not the address from the sender which we get in the receive from senderaddr call,['c++'] +313,how to know if a line intersects a plane in c basic 2d geometry my school maths are very rusty and i think this is a good opportunity to take advance of this community di have two points a line and a rectangle i would like to know how to calculate if the line intersects the rectangle my first approach had so many if statements that the compiler sent me a link to this sitethanks for your time,['c#'] +315,avoiding repeated constants in css are there any useful techniques for reducing the repetition of constants in a css filefor example a bunch of different selectors which should all apply the same colour or the same font size,['css'] +318,moving from visual studio 2005 to 2008 and net 20 i am currently using vs2005 profesional and net 20 and since our project is rather large 25 projects in the solution i would like to try vs 2008 since its theoretically faster with larger projects before doing such thing i would like to know if what i have read is true can i use vs2008 in net 20 mode i do not want my customers to install net 30 or 35 i just want to install vs2008 open my solution and start working from there is this possiblepd the solution is a c window forms project,"['c#', '.net']" +319,what does this javascript error mean permission denied to call method to locationtostring this error just started popping up all over our sitepermission denied to call method to locationtostringi am seeing google posts that suggest that this is related to flash and our crossdomainxml what caused this to occur and how do you fix,['javascript'] +320,mysql binary log replication can it be set to ignore errors i am running a masterslave mysql binary log replication system phew that for some data is not in sync meaning the master holds more data than the slave but the slave stops very frequently on the slightest mysql error can this be thisabled perhaps a mycnf setting for the replicating slave ignorereplicatingerrors or some of the sort this is what happens every now and then when the slave tries to replicate an item that does not exist the slave just dies a quick check at show slave status g gives slaveiorunning yes slavesqlrunning no replicatedodb lasterrno 1062 lasterror error duplicate entry 15218 for key 1 on query default database db query insert into dbtable fields values values which i promptly fix once i realize that the slave has been stopped by doing the followingstop slavereset slavestart slave lately this has been getting kind of tiresome and before i spit out some sort of php which does this for me i was wondering if there is some mycnf entry which will not kill the slave on the first errorcheersmp,['mysql'] +326,what control is this open button with drop down the open button on the open file dialog used in certain windows applications includes a dropdown arrow with a list of additional options namely open with i have not seen this in every windows application so you may have to try a few to get it but sql server management studio and visual studio 2005 will both show the button that way if you go to the menu and choose fileopenfilei want to use a button like this with a builtin list in one of my applications but i cannot find the control they are using anywhere in visual studio i should clarify that i am looking for that specific button not the entire dialog any thoughts,['.net'] +330,profile a rails controller action what is the best way to profile a controller action in ruby on rails currently i am using the bruteforce method of throwing in puts timenow calls between what i think will be a bottleneck but that feels really really dirty there has got to be a better way,"['ruby-on-rails', 'ruby']" +331,how do threads work in python and what are common pythonthreading specific pitfalls i have been trying to wrap my head around how threads work in python and it is hard to find good information on how they operate i may just be missing a link or something but it seems like the official documentation is not very thorough on the subject and i have not been able to find a good writeupfrom what i can tell only one thread can be running at once and the active thread switches every 10 instructions or sowhere is there a good explanation or can you provide one it would also be very nice to be aware of common problems that you run into while using threads with python,['python'] +334,how stable is wpf how stable is wpf not in terms of stability of a wpf program but in terms of the stability of the api itself let me explain microsoft is notorious for changing its whole methodology around with new technology like with the move from silverlight 1 to silverlight 2 with wpf i know that ms changed a bunch of stuff with the release of the net service pack i do not know how much they changed things around so the bottom line is in your opinion are they going to revamp the system again with the next release or do you think that it is stable enough now that they would not change the bulk of the system i hate to have to unlearn stuff with every release i hope that the question was not too long winded,['.net'] +335,do indexes work with in clause if i have a query likeselect employeeid from employee where employeetypeid in 123and i have an index on the employeetypeid field does sql server still use that index,['sql'] +338,java logging vs log4j is it still worth to add the log4j library to a java 5 project just to loglet us say some exceptions to a file with some nice rollover settingsor will the standard utillogging facility do the job as wellwhat do you think,['java'] +341,c sqlclient simplest insert i am basically trying to figure out the simplest way to perform your basic insert operation in cnet using the sqlclient namespace i am using sqlconnection for my db link i have already had success executing some reads and i want to know the simplest way to insert data i am finding what seem to be pretty verbose methods when i google,"['c#', 'sql']" +344,what is the simplest sql query to find the second largest value what is the simplest sql query to find the second largest integer value in a specific column there are maybe duplicate values in the column,['sql'] +345,sending email in net through gmail instead of relying on my host to send email i was thinking of sending the messages though my gmail account the emails are personalized emails to the bands i play on my show is it possible to do,"['c#', '.net']" +346,passing null to a method i am in the middle of reading the excellent clean codeone thiscussion is regarding passing nulls into a methodpublic class metricscalculator public double xprojectionpoint p1 point p2 return p2x p1x 15 calculatorxprojectionnull new point1213it represents different ways of handling thispublic double xprojectionpoint p1 point p2 if p1 null p2 null throw new illegalargumentexceptioninvalid argument for xprojection return p2x p1x 15public double xprojectionpoint p1 point p2 assert p1 null p1 should not be null assert p2 null p2 should not be null return p2x p1x 15i prefer the assertions approach but i do not like the fact that assertions are turned off by defaultthe book finally statesin most programming languages there is no good way to deal with a null that is passed by a caller accidentally because this is the case the rational approach is to forbid passing null by defaultit does not really go into how you would enforce this restrictiondo any of you have strong opinions either way,['java'] +347,11 foreign key constraints how do you specify that a foreign key constraint should be a 11 relationship in transact sql is declaring the column unique enough below is my existing codecreate table dbomytable mytablekey int identity11 not for replication not null othertablekey int not null unique constraint fk mytable othertable foreign key references dboothertableothertablekey constraint pk mytable primary key clustered mytablekey asc with pad index off statistics norecompute off ignore dup key off allow row locks on allow page locks on on primary on primarygo,['sql'] +349,alternative architectural approaches to javascript client code how is your javascript code organized does it follow patterns like mvc or something else i have been working on a side project for some time now and the further i get the more my webpage has turned into a fullfeatured application right now i am sticking with jquery however the logic on the page is growing to a point where some organization or dare i say it architecture is needed my first approach is mvcishthe model is a json tree that gets extended with helpersthe view is the dom plus classes that tweak itthe controller is the object where i connect events handling and kick off view or model manipulationi am very interested however in how other people have built more substantial javascript apps i am not interested in gwt or other serveroriented approaches just in the approach of javascript generic web servicey thingy herenote earlier i said javascript is not really oo not really functional this i think thistracted everyone let us put it this way because javascript is unique in many ways and i am coming from a stronglytyped background i do not want to force paradigms i know but were developed in very different languages,['javascript'] +355,alternatives to systemexit1 for various reasons calling systemexit is frowned upon when writing java applications so how can i notify the calling process that not everything is going according to planedit the 1 is a standin for any nonzero exit code,['java'] +356,what is a good dvd burning component for windows or net i would like to add dvd burning functionality to my net app running on windows server 2003 are there any good components available i have used the nerocom sdk that used to come with nero but they no longer support the sdk in the latest versions of nero i learned that microsoft has created an imapi2 upgrade for windows xp2003 and there is an example project at codeproject but not having used it myself i cannot say how easyreliable it is to usei am not really worried about burning audiovideo to dvd as this is for file backup purposes only,['.net'] +357,setting the height of a div dynamically in a web application i have a page that contains a div that has an autowidth depending on the width of the browser windowi need an autoheight for the object the div starts about 300px from the top screen and it is height should make it stretch to the bottom of the browser screen i have a max height for the container div so there would have to be minimumheight for the div i believe i can just restrict that in css and use javascript to handle the resizing of the divmy javascript is not nearly as good as it should be is there an easy script i could write that would do this for meedit the div houses a control that does it is own overflow handling implements its own scroll bar,"['javascript', 'html', 'css']" +368,how do you get the ethernet address using java i would like to retrieve the ethernet address of the network interface that is used to access a particular websitehow can this be done in javasolution note that the accepted solution of gethardwareaddress is only available in java 6 there does not seem to be a solution for java 5 aside from executing ifpconfing,['java'] +370,are python threads buggy a reliable coder friend told me that pythons current multithreading implementation is seriously buggy enough to avoid using altogether what can said about this rumor,['python'] +371,html scraping in php i have been doing some html scraping in php using regular expressions this works but the result is finicky and fragile has anyone used any packages that provide a more robust solution a config driven solution would be ideal but i am not picky,"['php', 'html']" +374,how to make user controls know about css classes in aspnet since there are no header sections for user controls in aspnet user controls have no way of knowing about stylesheet files so css classes in the user controls are not recognized by visual studio and produces warnings how can i make a user control know that it will relate to a css class so if it is warning me about a nonexisting css class it means that the class really do not existedit or should i go for a different design like exposing css classes as properties like headerstylecssclass of gridview,"['asp.net', 'css']" +375,how do i create a sha1 hash in ruby sha hash functions,['ruby'] +377,what is the best quickread python book out there i am taking a class that requires python we will review the language in class next week and i am a quick study on new languages but i was wondering if there are any really great python books i can grab while i am struggling through the basics of setting up my ide server environment and all those other gotchas that come with a new programming language suggestions,['python'] +379,duplicating jquery datepicker the datepicker function only works on the first input box that is createdi am trying to duplicate a datepicker by cloning the div that is containing ita href iddupmeclickadiv idtemplateinputtext input typetext valuetext1 idtxt date time picker input typetext idexample valueadd date divto initialize the datepicker according to the jquery ui documentation i only have to do exampledatepicker and it does work but only on the first datepicker that is createdthe code to duplicate the div is the followingadupmeclickfunctionevent eventpreventdefault i var a templateclonetrueinsertbeforetemplatehidefadein10 afindinputtxtattrvalue i afindinputexampledatepickerthe strangest thing is that on the documentready i havetemplate exampledatepickertemplate txtclickfunction alertthisval and if i click on the txt it always works,"['javascript', 'jquery']" +385,retrieving http status code from loaded iframe with javascript i used the jquery form plugin for asynchronous form submission for forms that contain files it copies the form to a hidden iframe submits it and copies back the iframes contents the problem is that i cannot figure out how to find what http status code was returned by the server for example if the server returns 404 the data from the iframe will be copied as normal and treated as a regular responsei have tried poking around in the iframe objects looking for some sort of status code attribute but have not been able to find anything like thatthe ajax function cannot be used because it does not support uploading files the only way to asynchronously upload files that i know of is using the hidden iframe method,['jquery'] +389,are there static analysis tools for python i am starting to use python specifically because of django and i would like to remove the burden for exhaustive testing by performing some static analysis what toolsparametersetc exist to detect issues at compile time that would otherwise show up during runtime type errors are probably the most obvious case of this but undefined variables are another big one that could be avoided with an indepth analysis of the astobviously testing is important and i do not imply that tests can be obviated entirely however there are many runtime errors in python that are not possible in other languages that perform stricter runtime checking i am hoping that there are tools to bring at least some of these capabilities to python as well,['python'] +395,writing crossplatform apps in c what things should be kept most in mind when writing crossplatform applications in c targeted platforms 32bit intel based pc mac and linux i am especially looking for the type of versatility that jungle thisk has in their usb desktop edition what are tips and gotchas for this type of development,['c'] +402,how to pass a single object to a params object i have a method which takes params object such asvoid fooparams object items consolewritelineitems0when i pass two object arrays to this method it works finefoonew object object1 object2 new object object3 object4 output systemobjectbut when i pass a single object it does not take my object as the first param instead it takes its all elements like i wanted to pass them one by onefoonew object object1 object2 output 1 expected systemobjecthow do i pass a single object as a first argument to a params array,['c#'] +403,what are the important ruby commands i am not sure of all of them but what are the commands to do things like update ruby download a new gem or update an existing gem what other important things are theresince it might matter i am running windows,['ruby'] +405,sql query count with 0 count i have three tables page attachment pageattachmenti have data like thispageid name1 first page2 second page3 third page4 fourth pageattachmentid name1 fooword2 testxsl3 mmpptpageattachmentid pageid attachmentid1 2 12 2 23 3 3i would like to get the number of attachments per page also when that number is 0 i have tried with select pagename countpageattachmentid as attachmentsnumber from page inner join pageattachment on pageidpageid group by pageidi am getting this output name attachmentsnumbersecond page 2third page 1i would like to get this outputname attachmentsnumberfirst page 0second page 2third page 1fourth page 0how do i get the 0 part,['sql'] +410,checking the results of a factory in a unit test i have developed some classes with similar behavior they all implement the same interface i implemented a factory that creates the appropriate object and returns the interface i am writing a unit test for the factory all you get back is an interface to the objectwhat is the best way to test that the factory has worked correctlyi would like to know the answer in java but if there is a solution that crosses languages i would like to know itnumber 2 in the answer would be done like the other answer if so i will mark the other answer accepted as well and reword my question to adress both a factory where an interface is returned and you have no clue what type of concrete class implemented the interface and the case where you do know what concrete class was used,['java'] +413,how to implement a file download in aspnet what is the best way to implement from a web page a download action using aspnet 20log files for a action are created in a directory called application rootlogs i have the full path and want to provide a button that when clicked will download the log file from the iis server to the users local pc,['asp.net'] +417,best net wrapper for google maps or yahoo maps i need to do a quick demo app using google maps or yahoo maps or any similar service so far i have not had much luck finding net wrappers for any of these servicesany suggestions or pointersi am not opposed to using the native javascript api to do this but i assumed someone would have already written a wrapper to easily integrate this into an aspnet application,['asp.net'] +420,how do i read a thisk directly with net is is possible to read a thisk directly with net by directly i mean via the device bypassing the file system i think i would go about this by opening the device some way deviceideidedevicep2t0l01 for example if i cannot open the device with a net api knowing which win32 api to use would be helpful,['.net'] +425,aspnet controls cannot be referenced in codebehind in visual studio 2008 ok so my visual studio is broken i say this not prematurely as it was my first response to see where i had messed up in my code when i add controls to the page i cannot reference all of them in the code behind some of them i can it seems that the first few i put on a page work then it just stops i first thought it may be the type of control as initially i was trying to reference a repeater inside an update panel i know i am correctly referencing the code behind in my aspx page but just in case it was a screw up on my part i started to recreate the page from scratch and this time got a few more controls down before vs stopped recognizing my controlsafter creating my page twice and getting stuck i thought maybe it was still the type of controls i created a new page and just threw some labels on it no dice build fails when referencing the control from the code behind in a possibly unrelated note when i switch to the dreaded design mode of the aspx pages vs 2008 errors out and restarts i have already put a trouble ticket in to microsoft i uninstalled all addins i reinstalled visual studio anyone that wants to see my code just ask but i am using the straight wysiwyg visual studio new aspx page nothing fancyi doubt anyone has run into this but have you has anyone had success trouble shooting these things with microsoft any way to expedite this ticket without paying i have been talking to a rep from microsoft for days with no luck yet and i am dead in the water thank you jon limjap i edited the title to both make it clear and descriptive and make sure that nobody sees it as offensive foobarred does not exactly constitute a proper question title although your question is clearly a valid one,"['c#', 'asp.net']" +432,how to find out if a file exists in c net i would like to test a string containing a path to a file for existence of that file something like the e test in perl or the ospathexists in python in c,"['c#', '.net']" +438,javascript locals in python one can get a dictionary of all local and global variables in the current scope with the builtin functions locals and globals is there some equivalent way of doing this in javascript for instance i would like to do something like the followingvar foo function alertfoo var bar function alertbar var s foolocalss alerts foois this at all possible or should i just be using a local object for the lookup,"['javascript', 'python']" +439,is overloading the only way to have default function arguments in c is it true that the only way to handle default function arguments is through function overloadingfor example in php i can do thisfunction foox y0would the best way to handle it in c be thisvoid fooint x foox 0void fooint x int yexample lifted from hereeditmade the c example into actual c thanks blair conrad,['c#'] +441,is java passbyreference or passbyvalue i always thought java was passbyreference however i have seen a couple of blog posts for example this blog that claim it is not i do not think i understand the thistinction they are making what is the explanation,['java'] +443,how do i get the full url of the page i am on in c i need to be able to get at the full url of the page i am on from a user control is it just a matter of concatenating a bunch of request variables together if so which ones or is there a more simpiler way,"['c#', 'asp.net']" +444,how do you give a c autoproperty a default value how do you give a c autoproperty a default value i either use the constructor or revert to the old syntax using the constructorclass person public person name default name public string name get set using normal property syntax with a default valueprivate string name default namepublic string name get return name set name value is there a better way,['c#'] +447,where do you store your database connectionstring i usually store my connectionstring in webconfig or in the application settings of my visual studio project the application i am currently working on makes a lot of trips to the database which means it will look up the connectionstring every time should i be putting the connectionstring in the cache or should i be looking at storing the whole sqlconnection object in the cache to eliminate the need to open and close them all the timeupdate seems like the consensus is to store the connection string in a configuration file and leave the caching in the trusting hand of adonet,['asp.net'] +448,is there a best net algorithm for credit card encryption the net systemsecuritycryptography namespace has a rather bewildering collection of algorithms that i could use for encryption of credit card details which is the bestit clearly needs to be secure for a relatively short string edit i am in the uk where i understand were ok storing encrypted credit card details so long as the threedigit cvv number is never stored and thanks all for the great responses,['.net'] +449,file access strategy in a multithreaded environment web app i have a file which is an xml representation of some data that is taken from a web service and cached locally within a web application the idea being is that this data is very static but just might change so i have set it up to cache to a file and stuck a monitor against it to check if it has been deleted once deleted the file will be refreshed from its source and rebuilti am now running in to problems though because obviously in a multithreaded environment it falls over as it is trying to access the data when it is still readingwriting the filethis is confusing me because i added a object to lock against and this is always locked during readwrite it was my understanding that attempted access from other threads would be told to wait until the lock was releasedjust to let you know i am real new to multithreaded development so i am totally willing to accept this is a screw up on my part am i missing somethingwhat is the best file access strategy in a multithreaded environmenteditsorry i should have said this is using aspnet 20,['asp.net'] +453,how to wrap a function with variable length arguments i am looking to do this in cci came across variable length arguments but this suggests a solution with python c using libffinow if i want to wrap printf function with myprintfwhat i do is like belowvoid myprintfchar fmt va list args va startargsfmt printffmtargs va endargsint tmainint argc tchar argv int a 9 int b 10 char v c myprintfthis is a number d and nthis is a character c and and another number dna v b return 0but the results are not as expectedthis is a number 1244780 andthis is a character h andanother number 29953463any point where did i miss,"['c++', 'c']" +456,how do you properly use namespaces in c i come from a java background where packages are used not namespaces i am used to putting classes that work together to form a complete object into packages and then reusing them later from that package but now i am working in chow do you use namespaces in c do you create a single namespace for the entire application or do you create namespaces for the major components if so how do you create objects from classes in other namespaces,['c++'] +461,how can i unit test a windows service net framework 20preferred language ci am new to tdd test driven developmentfirst of all is it even possible to unit test windows servicewindows service class is derived from servicebase which has overridable methods onstart onstophow can i trigger those methods to be called as if unit test is an actual service that calls those methods in proper orderat this point am i even doing a unit testing or an integration testi have looked at wcf service question but it did not make any sense to me since i have never dealt with wcf service,"['c#', '.net']" +463,custom titlebarschrome in a winforms app i am almost certain i know the answer to this question but i am hoping there is something i have overlookedcertain applications seem to have the vista aero look and feel to their caption bars and buttons even when running on windows xp google chrome and windows live photo gallery come to mind as examples i know that one way to accomplish this from winforms would be to create a borderless form and draw the caption barbuttons yourself then overriding wndproc to make sure moving resizing and button clicks do what they are supposed to do i am not clear on the specifics but could probably pull it off given a day to read documentation i am curious if there is a different easier way that i am overlooking perhaps some api calls or window styles i have overlookedi believe google has answered it for me by using the rollyourownwindow approach with chrome i will leave the question open for another day in case someone has new information but i believe i have answered the question myself,['.net'] +467,sql server views blessing or curse i once worked with an architect who banned the use of sql views his main reason was that views made it too easy for a thoughtless coder to needlessly involve joined tables which if that coder tried harder could be avoided altogether implicitly he was encouraging code reuse via copyandpaste instead of encapsulation in viewsthe database had nearly 600 tables and was highly normalised so most of the useful sql was necessarily verboseseveral years later i can see at least one bad outcome from the ban we have many hundreds of dense lengthy stored procs that verge on unmaintainablein hindsight i would say it was a bad decision but what are your experiences with sql views have you found them bad for performance any other thoughts on when they are or are not appropriate,['sql'] +470,what is wcf in simple terms what is wcf in simple termsit is hard to thistill the meaning from the wikipedia page,['.net'] +471,writingusing c libraries i am looking for basic examplestutorials onhow to writecompile libraries in c so files for linux dll files for windowshow to import and use those libraries in other code,['c++'] +473,get last day of the month in python is there a way using pythons standard library to easily determine ie one function call the last day of a given monthif the standard library does not support that does the dateutil package support this,['python'] +475,regex to match against something that is not a specific substring i am looking for a regex that will match a string that starts with one substring and does not end with a certain substringexample updated to be correct thanks apocalispfoobarshould match anything that starts with foo and does not end with bar i know about the syntax but i cannot find anything that will do that for a string instead of single characters i am specifically trying to do this for javas regex but i have run into this before so answers for other regex engines would be great too thanks to kibbee for verifying that this works in c as well,"['c#', 'java']" +477,how to generate urls in django in djangos template language you can use url viewname args to generate a url to a specific view with parameters how can you programatically do the same in python codewhat i need is to create a list of menu items where each item has name url and an active flag whether it is the current page or not this is because it will be a lot cleaner to do this in python than the template language,['python'] +478,nhibernate isession flush where and when to use it and why one of the things that get me thoroughly confused is the use of sessionflushin conjunction with sessioncommit and sessionclosesometimes sessionclose works eg it commits all the changes that i need i know i need to use commit when i have a transaction or a unit of work with several createsupdatesdeletes so that i can choose to rollback if an error occursbut sometimes i really get stymied by the logic behind sessionflush i have seen examples where you have a sessionsaveorupdate followed by a flush but when i remove flush it works fine anyway sometimes i run into errors on the flush statement saying that the session timed out and removing it made sure that i did not run into that errordoes anyone have a good guideline as to where or when to use a flush i have checked out the nhibernate documentation for this but i still cannot find a straightforward answer,['.net'] +479,is there a standard html layout with multiple css styles available when it comes to webdesign i am horrible at producing anything remotely good looking thankfully there are a lot of free sources for design templates however a problem with these designs is that they just cover a single page and not many use cases if you take a look at css zen gardens they have 1 single html file and can radically style it differently by just changing the css filenow i am wondering if there is a standard html layout tags and ids that covers alot of use cases and can be generically themed with different css files like zen garden what i am imagining is a set of rules off how you write your html and what boxes lists menus and styles you are supposed to use a set of standard test pages covering the various uses can be created and a new css file while have to support all the different pages in a nice viewis there any projects that covers anything similar to what i am describing,"['html', 'css']" +481,is there a builtin method to compare collections in c i would like to compare the contents of a couple of collections in my equals method i have a dictionary and an ilist is there a builtin method to do thiseditedi want to compare two dictionaries and two ilists so i think what equality means is clear if the two dictionaries contain the same keys mapped to the same values then they are equal,"['c#', '.net']" +482,how to find the mime type of a file in python let us say you want to save a bunch of files somewhere for instance in blobs let us say you want to thish these files out via a web page and have the client automatically open the correct applicationviewerassumption the browser figures out which applicationviewer to use by the mimetype contenttype header in the http responsebased on that assumption in addition to the bytes of the file you also want to save the mime typehow would you find the mime type of a file i am currently on a mac but this should also work on windows does the browser add this information when posting the file to the web pageis there a neat python library for finding this information a webservice or even better a downloadable database,['python'] +483,how to concatenate strings of a string field in a postgresql group by query i am looking for a way to concatenate the strings of a field within a group by query so for example i have a tableid company id employee1 1 anna2 1 bill3 2 carol4 2 daveand i wanted to group by company id to get something likecompany id employee1 anna bill2 carol davethere is a builtin function in mysql to do this group concat,['sql'] +492,difference between foreach and for loops over an ienumerable class in c i have been told that there is a performance difference between the following code blocksforeach entity e in entitylist and for int i0 ientitylistcount i entity e entityentitylisti wherelistentity entitylisti am no clr expect but from what i can tell they should boil down to basically the same code does anybody have concrete heck i would take packed dirt evidence one way or the other,['c#'] +501,learning cil does anybody know any good resources for learning how to program cil with indepth descriptions of commands etc i have looked around but not found anything particularly good,['.net'] +502,how can i programmatically determine if my workstation is locked i am writing up some productivitymetrics tools for myself to help monitor my focus throughout the day recently i have noticed that i tend to get off track more than usual and feel the need to get up and go for walksdrinksetc and i am concerned that i am wasting too much timesince i always lock my computer when i go anywhere and i unlock it as soon as i return even if i am just reading at my desk etc i was wondering how i can determine in code how long the machine is lockedi am writing this in c if that helps but i am open to other ideasi like the windows service idea and have accepted it for simplicity and cleanliness but unfortunately i do not think it will work for me in this particular case i wanted to run this on my workstation at work rather than home or in addition to home i suppose but it is locked down pretty hard courtesy of the dod that is part of the reason i am rolling my own actuallyi will write it up anyway and see if it works thanks everyone,['c#'] +503,how to parse a string into a nullable int i am wanting to parse a string into a nullable int in c ie i want to get back either the int value of the string or null if it cannot be parsedi was kind of hoping that this would workint val stringval as intbut that would not work so the way i am doing it now is i have written this extension methodpublic static int parsenullableintthis string valueif value null valuetrim stringemptyreturn nullelsetryreturn intparsevaluecatchreturn nullis there a better way of doing thisedit thanks for the tryparse suggestions i did know about that but it worked out about the same i am more interested in knowing if there is a builtin framework method that will parse directly into a nullable int,"['c#', '.net']" +506,friendly urls for aspnet python frameworks always provide ways to handle urls that convey the data of the request in an elegant way like for example i want you to notice the ending path userid123424how do you do this in aspnet,['asp.net'] +509,wacom tablet python interface if possible i want to catch pressure sensitive input from a wacom tablet in python are there any python libraries available that can do this,['python'] +510,how can i call a net dll from an inno setup script i want to call a function from a net dll coded in c from an inno setup scripti havemarked the register for com interop option in the project propertieschanged the comvisible setting in the assemblyinfocs fileadded these lines to the iss scriptfilessource ctemp1mydlldll flags dontcopycodefunction myfunction stringexternal myfunctionfilesmydlldll stdcall setuponlybut i still get the following errorruntime error at 10cannot import dllcdocume1foolocals1tempislrl3etmpmydlldllwhat am i doing wrong,['.net'] +512,a issue with the jquery dialog when using the themeroller css the demos for the jquery ui dialog all use the flora theme i wanted a customized theme so i used the themeroller to generate a css file when i used it everything seemed to be working fine but later i found that i cannot control any input element contained in the dialog ie cannot type into a text field cannot check checkboxes further investigation revealed that this happens if i set the dialog attribute modal to true this does not happen when i use the flora theme here is the js filetopmenu init function my buttonbindclick function service03 dlgdialogopen somethingfocus service03 dlgdialog autoopen false modal true resizable false title my title overlay opacity 05 background black buttons ok function alerthi cancel function thisdialogclose close function somethingval documentreadytopmenuinithere is the html that uses the flora themedoctype html public w3cdtd html 401en htmlheadmeta httpequivcontenttype contenttexthtml charsetshift jistitlesampletitlescript srcjquery126minjs languagejavascriptscriptlink relstylesheet hrefflorafloraallcss typetextcscript srcjqueryuipersonalized152minjs languagejavascriptscriptscript srctopmenujs languagejavascriptscriptheadbodyinput typebutton valueclick me idmy buttondiv idservice03 dlg classfloraplease enter somethingbrbrlabel forsomethingsomthinglabelnbspinput namesomething idsomething typetext maxlength20 size24divbodyhtmlhere is the html that uses the downloaded themeroller themedoctype html public w3cdtd html 401en htmlheadmeta httpequivcontenttype contenttexthtml charsetshift jistitlesampletitlescript srcjquery126minjs languagejavascriptscriptlink relstylesheet hrefjqueryuithemerollercss typetextcscript srcjqueryuipersonalized152minjs languagejavascriptscriptscript srctopmenujs languagejavascriptscriptheadbodyinput typebutton valueclick me idmy buttondiv idservice03 dlg classuidialogplease enter somethingbrbrlabel forsomethingsomthinglabelnbspinput namesomething idsomething typetext maxlength20 size24divbodyhtmlas you can see only the referenced css file and class names are differentanybody have a clue as to what could be wrongdavid i tried it and it does not seem to work neither on ff or ie i tried inline cstylezindex50and i have also tried it referencing an external css fileservice03 dlgzindex50but neither of these work am i missing something in what you suggestededitsolve by brostbeefsince i was originally using flora i had mistakenly assumed that i have to specify a class attribute turns out this is only true when you actually use the flora theme as in the samples if you use the customized theme specifying a class attribute causes that strange behaviour,"['javascript', 'jquery']" +515,c force form focus so i did search google and so prior to asking this question basically i have a dll that has a form compiled into it the form will be used to thisplay information to the screen eventually it will be asynchronous and expose a lot of customization in the dll for now i just want it to thisplay properly the problem that i am having is that i use the dll by loading it in a powershell session so when i try to thisplay the form and get it to come to the top and have focus it has no problem with thisplaying over all the other apps but i cannot for the life of me get it to thisplay over the powershell window here is the code that i am currently using to try and get it to thisplay i am sure that the majority of it would not be required once i figure it out this just represents all the things that i found via googleclass blah dllimportuser32dll entrypoint systemparametersinfo public static extern bool systemparametersinfouint uiaction uint uiparam uint pvparam uint fwinini dllimportuser32dll entrypoint setforegroundwindow public static extern bool setforegroundwindowintptr hwnd dllimportuser32dll entrypoint showwindowasync private static extern bool showwindowasyncintptr hwnd int cmdshow private const int ws shownormal 1 public void showmessagestring msg messageform msgfrm new messageform msgfrmlblmessagetext foo msgfrmshowdialog msgfrmbringtofront msgfrmtopmost true msgfrmactivate systemparametersinfouint0x2001 0 0 0x02 0x01 showwindowasyncmsgfrmhandle ws shownormal setforegroundwindowmsgfrmhandle systemparametersinfouint0x2001 20 20 0x02 0x01 as i say i am sure that most of that is either not needed or even flat out wrong i just wanted to show the things that i had tried also as i mentioned i plan to have this be asynchronously thisplayed at some point which i suspect will wind up requiring a separate thread would splitting the form out into it is own thread make it easier to cause it to get focus over the powershell session joel thanks for the info here is what i tried based on your suggestionmsgfrmshowdialogmsgfrmbringtofrontmsgfrmfocusapplicationdoeventsthe form still comes up under the powershell session i will proceed with working out the threading i have spawned threads before but never where the parent thread needed to talk to the child thread so well see how it goesthnks for all the ideas so far folksok threading it took care of the problem quarrelsome i did try both of those neither nor both together worked i am curious as to what is evil about using threading i am not using applicationrun and i have yet to have a problem i am using a mediator class that both the parent thread and the child thread have access to in that object i am using a readerwriterlock to lock one property that represents the message that i want thisplayed on the form that the child thread creates the parent locks the property then writes what should be thisplayed the child thread locks the property and reads what it should change the label on the form to the child has to do this on a polling interval i default it to 500ms which i am not real happy about but i could not find an event driven way to let the child thread know that the proerty had changed so i am stuck with polling,['c#'] +519,iphone app crashing with nsunknownkeyexception setvalueforundefinedkey i am writing my first iphone app so i have not gotten around to figuring out much in the way of debuggingessentially my app thisplays an image and when touched plays a short soundwhen compiling and building the project in xcode everything builds successfully but when the app is run in the iphone simulator it crashesi get the following errorapplication specific informationiphone simulator 10 70 iphone os 20 5a331 terminating app due to uncaught exception nsunknownkeyexception reason uiview 0x34efd0 setvalueforundefinedkey this class is not key value codingcompliant for the key kramerimagekramerimage here is the image i am using for the backgroundi am not sure what nsunknownkeyexception means or why the class is not key value codingcompliant for the key,['iphone'] +521,center a block of content when you do not know its width in advance after lots of attempts and search i have never found a satisfactory way to do it with css2a simple way to accomplish it is to wrap it into a handy table as shown in the sample below do you know how to do it avoiding table layouts and also avoiding quirky tricksdoctype html public w3cdtd html 401enhtmlhead style typetextcss table margin0px auto 0 auto stylehead body table tr tdtestbrtesttd tr table bodyhtmlwhat i want to know is how to do it without a fixed width and also being a block,"['html', 'css']" +522,why does not oracle tell you which table or view does not exist if youve used oracle youve probably gotten the helpful message ora00942 table or view does not exist is there a legitimate technical reason the message does not include the name of the missing object arguments about this being due to security sound like they were crafted by the tsa if i am an attacker i would know what table i just attempted to exploit and be able to interpret this unhelpful message easily if i am a developer working with a complex join through several layers of application code it is often very difficult to tellmy guess is that when this error was originally implemented someone neglected to add the object name and now people are afraid it will break compatibility to fix it code doing silly things like parsing the error message will be confused if it changesis there a developerfriendly as opposed to recruiting your dba way to determine the name of the missing tablealthough i have accepted an answer which is relevant to the topic it does not really answer my question why is not the name part of the error message if anyone can come up with the real answer i will be happy to change my vote,['sql'] +523,showing a hint for a c winforms edit control i am working on a c winforms application vsnet 2008 net 35 sp 1 i have a search field on a form and rather than have a label next to the search field i would like to show some grey text in the background of the search field itself search terms for example when the user starts entering text in the search field the text should thisappear how can i achieve this,['c#'] +530,what are the most useful custom code snippets for c what are the best code snippets for c using visual studio vb has a lot that are predefined but there are only a handful for c do you have any really useful ones for canyone want to post a good custom one you created yourselfanyone bueller,['c#'] +531,deciphering c template error messages i am really beginning to understand what people mean when they say that cs error messages are pretty terrible in regards to templates i have seen horrendously long errors for things as simple as a function not matching its prototypeare there any tricks to deciphering these errorsedit i am using both gcc and msvc they both seem to be pretty terrible,['c++'] +532,moving viewstate out of the page we are trying to lighten our page load as much as possible since viewstate can sometimes swell up to 100k of the page i would love to completely eliminate iti would love to hear some techniques other people have used to move viewstate to a custom providerthat said a few caveatswe serve on average 2 million unique visitors per hourbecause of this database reads have been a serious issue in performance so i do not want to store viewstate in the databasewe also are behind a load balancer so any solution has to work with the user bouncing from machine to machine per postbackideas,['asp.net'] +536,best ruby on rails social networking framework i am planning on creating a social networking mp3 lecture downloading browsing commenting thiscovery website using ruby on rails partially for fun and also as a means to learn some ruby on rails i am looking for a social networking framework that i can use as a basis for my site i do not want to reinvent the wheel searching the web i found three such frameworks which of these three would you recommend using and why,"['ruby-on-rails', 'ruby']" +540,how do i publish a aspnet web application using msbuild i am trying to publish an aspnet mvc web application locally using the nant and msbuild this is what i am using for my nant targettarget namepublishartifactstobuild msbuild projectmysolutionsln targetpublish property nameconfiguration valuedebug property nameoutdir valuebuilds arg linem2 tv35 msbuildtargetand all i get is this as a responsemsbuild skipping unpublishable projectis it possible to publish web applications via the command line in this way,"['asp.net', '.net']" +541,something like a callback delegate function in php i would like to implement something similar to a c delegate method in php a quick word to explain what i am trying to do overall i am trying to implement some asynchronous functionality basically some resourceintensive calls that get queued cached and thispatched when the underlying system gets around to it when the asynchronous call finally receives a response i would like a callback event to be raisedi am having some problems coming up with a mechanism to do callbacks in php i have come up with a method that works for now but i am unhappy with it basically it involves passing a reference to the object and the name of the method on it that will serve as the callback taking the response as an argument and then use eval to call the method when need be this is suboptimal for a variety of reasons is there a better way of doing this that anyone knows of,['php'] +542,winforms c set focus to first child control of tabpage say i have a textbox nested within a tabcontrol when the form loads i would like to focus on that textbox by default the focus is set to the tabcontrolsimply calling textbox1focus in the load event of the form does not appear to work i have been able to focus it by doing the following private void frmmainloadobject sender eventargs e foreach tabpage tab in thistabcontrol1tabpages thistabcontrol1selectedtab tab my question isis there a more elegant way to do this,"['c#', '.net']" +552,how do you set your cocoa application as the default web browser how do you set your cocoa application as the default web browseri want to create an application that is launched by default when the user clicks on an http or https link in other applications mail ichat etc,['objective-c'] +553,64 bit tools like boundschecker purify for many years i have used two great tools boundschecker purify but the developers of these applications have let me down they no longer put effort into maintaining them or developing them we have corporate accounts with both companies and they both tell me that they have no intention of producing versions to support 64 bit applicationscan anyone recommend either open source or commercial alternatives that support 64 bit native cmfc applications,['c++'] +555,in html what should happen to a selected thisabled option element in my specific example i am dealing with a dropdown egselect namefoo idbar option thisabledthisabled selectedselectedselect an itemoption optionan itemoption optionanother itemoptionselectof course that is pretty nonsensical but i am wondering whether any strict behaviour is defined opera effectively rejects the selected attribute and selects the next item in the list all other browsers appear to allow it and it remains selectedupdate to clarify i am specifically interested in the initial selection i am dealing with one of those select an itemtype dropdowns in which case the first option is really a label and an action occurs onchange this is fairly well progressively enhanced in that a submit button is present and only removed via javascript if the select option were removed whatever then were to become the first item would not be selectable are we just ruling out onchange drop downs altogether or should the select option be selectable just with no effect,['html'] +556,i understand threading in theory but not in practice in net i have a basic csmajor understanding of multithreading but have never had to do anything beyond simple timers in an application does anyone know of a good resource that will give me a tour how to work with multithreaded applications explaining the basics and maybe posing some of the more difficult stuff,['.net'] +558,is there a way to generalize an apache ant target we have an apache ant script to build our application then check in the resulting jar file into version control vss in this case however now we have a change that requires us to build 2 jar files for this project then check both into vssthe current target that checks the original jar file into vss thiscovers the name of the jar file through some property is there an easy way to generalize this target so that i can reuse it to check in a jar file with any name in a normal language this would obviously call for a function parameter but to my knowledge there really is not an equivalent concept in ant,['java'] +559,garbage collection is it necessary to set large objects to null in a thispose method is it necessary to set large objects to null when implementing a thispose method,['.net'] +566,css placement of a div in the lower lefthand corner i wish i were a css smarty how can you place a div container in the lower lefthand corner of the web page taking into account the users scrollposition,"['css', 'html']" +571,best way to detect a release build from a debug build net so i have about 10 short css files that i use with mvc appthere are likeerrorcsslogincssetcjust some really short css files that make updating and editing easy at least for me what i want is something that will optimize the if else branch and not incorporate it within the final bits i want to do something like thisifdebugmodelink relstylesheet typetextcss hreferrorcss link relstylesheet typetextcss hreflogincss link relstylesheet typetextcss hrefmenucss link relstylesheet typetextcss hrefpagecss else link relstylesheet typetextcss hrefsitecss i will have a msbuild task that will combine all the css files minimize them and all that good stuff i just need to know if there is a way to remove the if else branch in the final bits,['.net'] +572,what is the simplest way to find the difference between 2 times in python i have 2 time values which have the type datetimetime i want to find their difference the obvious thing to do is t1 t2 but this does not work it works for objects of type datetimedatetime but not for datetimetime so what is the best way to do this,['python'] +579,find all drive letters in java for a project i am working on i need to look for an executable on the filesystem for unix derivatives i assume the user has the file in the mighty path variable but there is no such thing on windowsi can safely assume the file is at most 2 levels deep into the filesystem but i do not know on what drive it will be i have to try all drives but i cannot figure out how to list all available drives which have a letter assigned to itany helpedit i know there is a path variable but it is not as integrated as in unix systems for instance the application i am looking for is openoffice such software would not be in path typically,['java'] +580,when can datainputstreamskipbytesn not skip and bytes the sun documentation for datainputskipbytes states that it makes an attempt to skip over and bytes of data from the input stream thiscarding the skipped bytes however it may skip over some smaller number of bytes possibly zero this may result from any of a number of conditions reaching end of file before and bytes have been skipped is only one possibilityother than reaching end of file why might skipbytes not skip the right number of bytes the datainputstream i am using will either be wrapping a fileinputstream or a pipedinputstreamif i definitely want to skip and bytes and throw an eofexception if this causes me to go to the end of the file should i use readfully and ignore the resulting byte array or is there a better way,['java'] +581,where did all the java applets go when java was young people were excited about writing applets they were cool and popular for a little while now i never see them anymore instead we have flash javascript and a plethora of other web appbuilding technologieswhy do not sites use java applets anymorei am also curious historically why do you think this occurred what could have been done differently to keep java applets alive,['java'] +583,how do i reset a sequence in oracle in postgresql i can do something like thisalter sequence serial restart with 0is there an oracle equivalent,['sql'] +585,how to get an absolute file path in python given a path such as mydirmyfiletxt how do i find the absolute filepath relative to the current working directory in python eg on windows i might end up withcexamplecwdmydirmyfiletxt,['python'] +587,determine how much memory a class uses i am trying to find a way to determine at runtime how much memory a given class is using in net using marshalsizeof is out as it only works on value types is there a way to check exactly how much memory a class uses,['.net'] +592,how to force my aspnet 20 app to recompile i have a aspnet 20 app and i have made some changes the the source file cs files i uploaded the changes with the belief that it would autorecompile i also have the compiled dll in my appbin i checked it and noticed that it did not recompile please understand i am new to this,['asp.net'] +593,how do i allow assembly unit testing one to access internal properties of another assembly i would like my core assembly to not expose a certain class and i would still like to be able to test it how can i do that,['.net'] +598,how can you determine what versions of net are running on a system what are the different ways programmatically and otherwise to determine what versions of net are running on a system,['.net'] +603,what does the comma operator do in c what does the operator do in c,['c'] +604,what does the pdb get me while debugging and how do i know it is working i have to use a thirdparty component without source code i have the release dll and release pdb file let us call it corporatecomponentdll my own code creates objects from this dll and calls methods on these objectscorpobject o new corpobjectint32 result odosomethinglousywhile debugging the method dosomethinglousy throws an exception what does the pdb file do for me if it does something nice how can i be sure i am making use of it,['.net'] +609,examples for coding against the paypal api in net 20 can anyone point me to a good introduction to coding against the paypal api,"['.net', 'asp.net']" +615,fuzzy text sentencestitles matching in c hey i am using levenshteins algorithm to get thistance between source and target stringalso i have method which returns value from 0 to 1 summary gets the similarity between two strings all relation scores are in the 0 1 range which means that if the score gets a maximum value equal to 1 then the two string are absolutely similar summary param namestring1the string1param param namestring2the string2param returnsreturnspublic static float calculatesimilaritystring s1 string s2 if s1 null s2 null return 00f float this levenshteinthistancecomputes1 s2 float maxlen s1length if maxlen s2length maxlen s2length if maxlen 00f return 10f else return 10f this maxlenbut this for me is not enough because i need more complex way to match two sentencesfor example i want automatically tag some music i have original song names and i have songs with trash like super quality years like 2007 2008 etcetc also some files have just httptrashthashsong name mp3mp3 other are normal i want to create an algorithm which will work just more perfect than mine now maybe anyone can help mehere is my current algo summary if we need to ignore this target summary param nametargetstringthe target stringparam returnsreturnsprivate bool doignorestring targetstring if targetstring null targetstring stringempty for int i 0 i ignorewordslistlength i if we found ignore word or target string matching some some special cases like years regex if targetstring ignorewordslisti ismatchinspecialcasestargetstring return true return false summary removes the duplicates summary param namelistthe listparamprivate void removeduplicatesliststring list if list null listcount 0 for int i 0 i listcount 1 i if listi listi 1 listremoveati i summary does the fuzzy match summary param nametargettitlethe target titleparam returnsreturnsprivate titlematchresult dofuzzymatchstring targettitle titlematchresult matchresult null if targettitle null targettitle stringempty try change target title string to lower case targettitle targettitletolower scores we will select higher score at the end dictionarytitle float scores new dictionarytitle float do split special chars liststring targetkeywords new liststringtargettitlesplitignorecharslist stringsplitoptionsremoveemptyentries remove all trash from keywords like super quality etc targetkeywordsremovealldelegatestring x return doignorex sort keywords targetkeywordssort remove some duplicates removeduplicatestargetkeywords go through all original titles foreach title sourcetitle in titles float tempscore 0f split orig title to keywords list liststring sourcekeywords new liststringsourcetitlenamesplitignorecharslist stringsplitoptionsremoveemptyentries sourcekeywordssort removeduplicatessourcekeywords go through all source ttl keywords foreach string keyw1 in sourcekeywords float max floatminvalue foreach string keyw2 in targetkeywords float currentscore stringmatchingstringmatchingcalculatesimilaritykeyw1tolower keyw2 if currentscore max max currentscore tempscore max calculate average score float averagescore tempscore mathmaxtargetkeywordscount sourcekeywordscount if average score is bigger than minimal score and target title is not in this source title ignore list if averagescore minimalscore sourcetitledoignoretargettitle add score scoresaddsourcetitle averagescore choose biggest score float maxi floatminvalue foreach keyvaluepairtitle float kvp in scores if kvpvalue maxi maxi kvpvalue matchresult new titlematchresultmaxi kvpkey matchtechniquefuzzylogic catch return resultreturn matchresultthis works normally but just in some cases a lot of titles which should match does not match i think i need some kind of formula to play with weights and etc but i cannot think of one ideas suggestions algosby the way i already know this topic my colleague already posted it but we cannot come with a proper solution for this problem,['c#'] +620,how do you get the logged in windows domain account from an aspnet application we have an aspnet application that manages it is own user roles and permission database and we have recently added a field to the user table to hold the windows domain account i would like to make it so that the user does not have to physically log in to our application but rather would be automatically logged in based on the currently logged in windows domain account domainusername we want to authenticate the windows domain account against our own user table this is a piece of cake to do in windows forms is it possible to do this in web formsi do not want the user to be prompted with a windows challenge screen i want our system to handle the log inclarification we are using our own custom principal objectclarification not sure if it makes a difference or not but we are using iis7,['asp.net'] +622,cakephp acl database setup aro aco structure i am struggling to implement acl in cakephp after reading the documentation in the cake manual as well as several other tutorials blog posts etc i found aran johnsons excellent tutorial which has helped fill in many of the gaps his examples seem to conflict with others i have seen though in a few places specifically in the aro tree structure he usesin his examples his user groups are set up as a cascading tree with the most general user type being at the top of the tree and its children branching off for each more restricted access type elsewhere i have usually seen each user type as a child of the same generic user type how do you set up your aros and acos in cakephp any and all tips appreciated,['php'] +623,problem rolling out adonet data service application to iis i am adding a adonet data service lookup feature to an existing web page everything works great when running from visual studio but when i roll it out to iis i get the following errorrequest errorthe server encountered an error processing the request see server logs for more detailsi get this even when trying to thisplay the default page iehttpserverfflookupsvci have 35 sp1 installed on the serverwhat am i missing and which server logs is it refering to i cannot find any further error messagesthere is nothing in the event viewer logs system or application and nothing in the iis logs other than the get20080910 152019 10713171 get fflookupsvc 8082 10713186 mozilla50windowsuwindowsnt51enusapplewebkit52513khtmllikegeckochrome0214929safari52513 401 2 2148074254there is no stack trace returned the only response i get is the request error as noted abovethankspatrick,['.net'] +631,php function argument error suppression empty isset emulation i am pretty sure the answer to this question is no but in case there is some php guruis it possible to write a function in a way where invalid arguments or non existent variables can be passed in and php will not error without the use of much like empty and isset do you can pass in a variable you just made up and it would not errorexemptysomebogusvar no errormyhappyfunctionsomebogusvar php warning notice,['php'] +634,in python how can you easily retrieve sorted items from a dictionary dictionaries unlike lists are not ordered and do not have the sort attribute therefore you can not rely on getting the items in the same order when first added what is the easiest way to loop through a dictionary containing strings as the key value and retrieving them in ascending order by keyfor example you had thisd b this is b a this is a c this is ci want to print the associated values in the following sequence sorted by keythis is athis is bthis is c,['python'] +643,when do functionlevel static variables get allocatedinitialized i am quite confident that globally declared variables get allocated and initialized if applicable at program start timeint globalgarbageunsigned int anumber 42but what about static ones defined within a functionvoid dosomething static bool globalish true when is the space for globalish allocated i am guessing when the program starts but does it get initialized then too or is it initialized when dosomething is first called,"['c++', 'c']" +645,find out where your php code is slowing down performance issue heres my first question at soi have a internal application for my company which i have been recently ask to maintain the applications is built in php and its fairly well coded oo db abstraction smarty nothing wtfish the problem is the applications is very slowhow do i go about finding out whats slowing the application down i have optimized the code to make very few db queries so i know that it is the php code which is taking a while to execute i need to get some tools which can help me with this and need to devise a strategy for checking my codei can do the checkingstrategy work myself but i need more php tools to figure out where my app is crapping up thoughts,"['php', 'mysql']" +646,why cannot i delete this cookie okay here is the 411 i have the following event handler in my globalasaxcs fileprivate void global postrequesthandlerexecuteobject sender eventargs e if logic that determines that this is an ajax call we want to set a cookie responsecookiesaddnew httpcookiemycookie true that handler will run during ajax requests as a result of the ajax framework i am using as well as at other times the condition of the if statement filters out nonajax events and works just fine it is not relevant here so i did not include it for brevitys sakeit suffices us to say that this works just fine the cookie is set i am able to read it on the client and all is well up to that pointnow for the part that drives me nutshere is the javascript function i am using to delete the cookiefunction deletecookiename var cookiedate new date cookiedatesettimecookiedategettime 1 documentcookie name expires cookiedatetogmtstringso of course at some point after the cookie is set i delete it like sodeletecookiemycookieonly that does not do the job the cookie still exists so anyone know why,"['c#', 'asp.net', 'javascript']" +655,how do i start threads in plain c i have used fork in c to start another process how do i start a new thread,['c'] +656,round in python does not seem to be rounding properly the documentation for the round function states that you pass it a number and the positions past the decimal to round thus it should do thisn 559roundn 1 56but in actuality good old floating point weirdness creeps in and you get5596for the purposes of ui i need to thisplay 56 i poked around the internet and found some documentation that this is dependent on my implementation of python unfortunately this occurs on both my windows dev machine and each linux server i have tried see here alsoshort of creating my own round library is there any way around this,['python'] +659,best way to reduce sequences in an array of strings please now that i have rewritten the question and before it suffers from further fastgun answers or premature closure by eager editors let me point out that this is not a duplicate of this question i know how to remove duplicates from an arraythis question is about removing sequences from an array not duplicates in the strict senseconsider this sequence of elements in an array0 a1 a2 b3 c4 c5 a6 c7 d8 c9 din this example i want to obtain the following0 a1 b2 c3 a4 c5 dnotice that duplicate elements are retained but that sequences of the same element have been reduced to a single instance of that elementfurther notice that when two lines repeat they should be reduced to one set of two lines0 c1 d2 c3 dreduces to0 c1 di am coding in c but algorithms in any language appreciated,"['c#', '.net']" +660,which net collection for adding multiple objects at once and getting notified was considering the systemcollectionsobjectmodel observablecollectiont class this one is strange because it has an add method which takes one item only no addrange or equivalent the notification event arguments has a newitems property which is a ilist of objects not tmy need here is to add a batch of objects to a collection and the listener also gets the batch as part of the notification am i missing something with observablecollection is there another class that meets my specupdate do not want to roll my own as far as feasible i would have to build in addremovechange etc a whole lot of stuffrelated q,['c#'] +661,is there any thisadvantage to returning this instead of void say instead of returning void a method you returned a reference to the class even if it did not make any particular semantic sense it seems to me like it would give you more options on how the methods are called allowing you to use it in a fluentinterfacelike style and i cannot really think of any thisadvantages since you do not have to do anything with the return value even store itso suppose youre in a situation where you want to update an object and then return its current valueinstead of saying myobjupdatevar val myobjgetcurrentvalueyou will be able to combine the two lines to sayvar val myobjupdategetcurrentvalueedit i asked the below on a whim in retrospect i agree that its likely to be unnecessary and complicating however my question regarding returning this rather than void standson a related note what do you guys think of having the language include a new bit of syntactic sugarvar val myobjupdategetcurrentvaluethis operator would have a low order of precedence so myobjupdate would execute first and then call getcurrentvalue on myobj instead of the void return of updateessentially i am imagining an operator that will say call the method on the righthand side of the operator on the first valid object on the left any thoughts,['.net'] +663,how do i get the current users local settings folder path in c i want to point a file dialog at a particular folder in the current users local settings folder on windows what is the shortcut to get this path,"['c#', '.net']" +671,how to attach debugger to step into native c code from a managed c wrapper i have a wrapper around a c function call which i call from c code how do i attach a debugger in visual studio to step into the native c codethis is the wrapper that i have which calls getdata defined in a c file dllimportunmanageddll callingconventioncallingconventioncdecl entrypoint getdata bestfitmapping false public static extern string getdatastring urlthe code is crashing and i want to investigate the root causethanksnikhil,"['c#', 'c++']" +676,are clr stored procedures preferred over tsql stored procedures in sql 2005 my current view is no prefer transact sql stored procedures because they are a lighter weight and possibly higher performing option while clr procedures allow developers to get up to all sorts of mischiefhowever recently i have needed to debug some very poorly written tsql stored procs as usual i found many of the problems due to the original developer developer having no real tsql experience they were aspnet c focusedso using clr procedures would firstly provide a much more familiar toolset to this type of developer and secondly the debugging and testing facilities are more powerful ie visual studio instead of sql management studio i would be very interested in hearing your experience as it is seems it is not a simple choice,['.net'] +677,rendering graphics in c are there any other way to render graphics in c beyond gdi and xna for the development of a tile map editor,['c#'] +678,unhandledexception handler in a net windows service is it possible to use an unhandledexception handler in a windows servicenormally i would use a custom built exception handling component that does logging phone home etc this component adds a handler to systemappdomaincurrentdomainunhandledexception but as far as i can tell this doesnat achieve anything win a windows service so i end up with this pattern in my 2 or 4 service entry points protected overrides sub onstartbyval args as string add code here to start your service this method should set things in motion so your service can do its work try myservicecomponentstart catch ex as exception call into our exception handler myexceptionhandlingcomponentmanuallyhandleexception ex zero is the default exitcode for a successfull exit so if we set it to nonzero exitcode 1 so we use environmentexit it seems to be the most appropriate thing to use we pass an exit code here as well just in case systemenvironmentexit1 end try end subis there a way my custom exception handling component can deal with this better so i do not have to fill my onstart with messy exception handling plumbing,['.net'] +680,how to test a wpf user interface using win forms with an mvcmvp architecture i would normally use a class to wrap a view to test the ui while using mocks for the model and controllerpresenter the wrapper class would make most everything in the ui an observable property for the test runner through properties and eventswould this be a viable approach to testing a wpf app is there a better way are there any gotchas to watch out for,['.net'] +681,avoiding first chance exception messages when the exception is safely handled the following bit of code catches the eos exceptionusing var reader new binaryreaderhttprequestbodystream try while true bodybytelistaddreaderreadbyte catch endofstreamexception so why do i still receive firstchance exceptions in my console a first chance exception of type systemioendofstreamexception occurred in mscorlibdllis there a way to hide these first chance exception messages,"['c#', '.net']" +682,using net how can you find the mime type of a file based on the file signature not the extension i am looking for a simple way to get a mime type where the file extension is incorrect or not given something similar to this question only in net,['c#'] +686,quotedprintable line longer than 76 chars warning when sending html email i have written some code in my vbnet application to send an html email in this case a lost password reminderwhen i test the email it gets eaten by my spam filter one of the things that it is scoring badly on is because of the following problemmime qp long line raw quotedprintable line longer than 76 charsi have been through the source of the email and i have broken each line longer than 76 characters into two lines with a crlf in between but that has not fixed the problemcan anyone point me in the right directionthanks,"['.net', 'html']" +688,open source pdf library for cc application i want to be able to generate pdf ouput from my native c windows application are there any freeopen source libraries available to do thisi looked at the answers to this question but they mostly relate to net,"['c++', 'c']" +690,converting svg to png using c i have been trying to convert svg images to png using c without having to write too much code can anyone recommend a library or example code for doing this,"['c#', '.net']" +691,access to result sets from within stored procedures transactsql sql server i am using sql server 2005 and i would like to know how to access different result sets from within transactsql the following stored procedure returns two result sets how do i access them from for example another stored procedurecreate procedure getorder orderid as numeric asbegin select order address order number from order table where order id orderid select item number of items cost from order line where order id orderidendi need to be able to iterate through both result sets individuallyedit just to clarify the question i want to test the stored procedures i have a set of stored procedures which are used from a vbnet client which return multiple result sets these are not going to be changed to a table valued function i cannot in fact change the procedures at all changing the procedure is not an optionthe result sets returned by the procedures are not the same data types or number of columns,['sql'] +695,what do i need to know to globalize an aspnet application i am writing an aspnet application that will need to be localized to several regions other than north america what do i need to do to prepare for this globalization what are your top 1 to 2 resources for learning how to write a world ready application,['asp.net'] +703,lock keyword in c i understand the main function of the lock key word from msdnlock statement c referencethe lock keyword marks a statement block as a critical section by obtaining the mutualexclusion lock for a given object executing a statement and then releasing the lockwhen should the lock be used for instance it makes sense with multithreaded applications because it protects the data but is it necessary when the application does not spin off any other threadsis there performance issues with using locki have just inherited an application that is using lock everywhere and it is single threaded and i want to know should i leave them in are they even necessaryplease note this is more of a general knowledge question the application speed is fine i want to know if that is a good design pattern to follow in the future or should this be avoided unless absolutely needed,['c#'] +704,how to get rid of deprecated conversion from string constant to achara warnings in gcc so i am working on an exceedingly large codebase and recently upgraded to gcc 43 which now triggers this warningwarning deprecated conversion from string constant to acharaobviously the correct way to fix this is to find every declaration likechar s constant stringor function call likevoid foochar sfooconstant stringand make them const char pointers however that would mean touching 564 files minimum which is not a task i wish to perform at this point in time the problem right now is that i am running with werror so i need some way to stifle these warnings how can i do that,['c++'] +708,how do i create a spring bean for a java double primitive i would like to create a spring bean that holds the value of a double something likebean iddoublevalue value37,['java'] +709,are stored procedures more efficient in general than inline statements on modern rdbmss conventional wisdom states that stored procedures are always faster so since they are always faster use them all the timei am pretty sure this is grounded in some historical context where this was once the case now i am not advocating that stored procs are not needed but i want to know in what cases stored procs are necessary in modern databases such as mysql sqlserver oracle or is it overkill to have all access through stored procs,['sql'] +710,c inheritance and member function pointers in c can member function pointers be used to point to derived or even base class members edit perhaps an example will help suppose we have a hierarchy of three classes x y z in order of inheritance y therefore has a base class x and a derived class znow we can define a member function pointer p for class y this is written asvoid ypfor simplicity i will assume were only interested in functions with the signature void f this pointer p can now be used to point to member functions of class ythis question two questions really is thencan p be used to point to a function in the derived class zcan p be used to point to a function in the base class x,['c++'] +711,how do you resize an ie browser window to 1024 x 768 in firefox you can enter the following into the awesome bar and hit enterjavascriptselfresizeto1024768how do you do the same thing in ie,['javascript'] +714,how to escape text for regular expression in java does java have a builtin way to escape arbitrary text so that it can be included in a regular expression for example if my users enter 5 i would like to match that exactly rather than a 5 after the end of input,['java'] +720,why should the pimpl idiom be used backgrounderthe pimpl idiom pointer to implementation is a technique for implementation hiding in which a public class wraps a structure or class that cannot be seen outside the library the public class is part ofthis hides internal implementation details and data from the user of the librarywhen implementing this idiom why would you place the public methods on the pimpl class and not the public class since the public classes method implementations would be compiled into the library and the user only has the header fileto illustrate this code puts the purr implementation on the impl class and wraps it as wellwhy not implement purr directly on the public class header fileclass cat private class catimpl not defined here catimpl cat handle public cat constructor cat destructor other operations purr cpp fileinclude cathclass catcatimpl purr the actual implementation can be anythingcatcat cat new catimplcatcat delete cat catpurr cat purr catimplpurr printfpur,['c++'] +721,best way to initiate a download on a phpbased web site i want to send users a download package after they have filled out a short form the siteinitiated download should be similar to sites like downloadcom which say your download will begin in a momenta couple of possible approaches i know about and browser compatibility based on a quick test1 do a windowopen pointing to the new file firefox 3 blocks this ie6 blocks this ie7 blocks this2 create an iframe pointing to the new file firefox 3 seems to think this is ok maybe it is because i already accepted it once ie6 blocks this ie7 blocks thishow can i do this so that at least these three browsers will not object bonus is there a method that does not require browserconditional statements i believe that downloadcom employs both methods conditionally but i cannot get either one to workresponses and clarificationsq why not point the current window to the file a that might work but in this particular case i want to show them some other content while their download starts for example would you like to donate to this projectupdate i have abandoned this approach see my answer below for reasons,"['php', 'javascript']" +722,getting started with silverlight development how does one start development in silverlightdoes one need a new ide or visual studio will support,['.net'] +723,aspnet is it possible to trigger a postback from server code is it possible to to programmatically trigger a postback from server code in aspnet i know that it is possible to do a responseredirect or servertransfer to redirect to a page but is there a way to trigger a postback to the same page in server code ie without using javascript trickery to submit a form,['asp.net'] +724,how do i write a python http server to listen on multiple ports i am writing a small web server in python using basehttpserver and a custom subclass of basehttpserverbasehttprequesthandler is it possible to make this listen on more than one portwhat i am doing nowclass myrequesthandlerbasehttpserverbasehttprequesthandler def doget class threadinghttpserverthreadingmixin httpserver paserver threadinghttpserverlocalhost 80 myrequesthandlerserverserve forever,['python'] +726,which jquery plugin should be used to fix the ie6 png transparency issue is there an ie6png fix that is officially developed by the jquery teamif not which of the available plugins should i use,['jquery'] +728,find out how much memory is being used by an object in c does anyone know of a way to find out how much memory an instance of an object is takingfor example if i have an instance of the following objecttestclass tc new testclassis there a way to find out how much memory the instance tc is takingthe reason for asking is that although c has built in memory management i often run into issues with not clearing an instance of an object eg a list that keeps track of somethingthere are couple of reasonably good memory profilers eg ants profiler but in a multithreaded environment is pretty hard to figure out what belongs where even with those tools,['c#'] +729,what is wrong with using inline functions while it would be very convenient to use inline functions at some situationsare there any drawbacks with inline functionsconclusionapparently there is nothing wrong with using inline functionsbut it is worth noting the following pointsoveruse of inlining can actually make programs slower depending on a functions size inlining it can cause the code size to increase or decrease inlining a very small accessor function will usually decrease code size while inlining a very large function can dramatically increase code size on modern processors smaller code usually runs faster due to better use of the instruction cache google guidelinesthe speed benefits of inline functions tend to diminish as the function grows in size at some point the overhead of the function call becomes small compared to the execution of the function body and the benefit is lost sourcethere are few situations where an inline function may not workfor a function returning values if a return statement existsfor a function not returning any values if a loop switch or goto statement exists if a function is recursive sourcethe inline keyword causes a function to be inlined only if you specify the optimize option if optimize is specified whether or not inline is honored depends on the setting of the inline optimizer option by default the inline option is in effect whenever the optimizer is run if you specify optimize you must also specify the noinline option if you want the inline keyword to be ignored source,['c++'] +734,how to save the output of a console application i need advice on how to have my c console application thisplay text to the user through the standard output while still being able access it later on the actual feature i would like to implement is to dump the entire output buffer to a text file at the end of program executionthe workaround i use while i do not find a cleaner approach is to subclass textwriter overriding the writing methods so they would both write to a file and call the original stdout writer something like thispublic class dirtyworkaround private class dirtywriter textwriter private textwriter stdoutwriter private streamwriter filewriter public dirtywriterstring path textwriter stdoutwriter thisstdoutwriter stdoutwriter thisfilewriter new streamwriterpath override public void writestring s stdoutwriterwrites filewriterwrites filewriterflush same as above for writeline and writelinestring plus whatever methods i need to override to inherit from textwriter encodingget i guess public static void mainstring args using dirtywriter dw new dirtywriterpath consoleout consolesetoutdw teh codez see that it writes to and flushes the file all the time i would love to do it only at the end of the execution but i could not find any way to access to the output bufferalso excuse inaccuracies with the above code had to write it ad hoc sorry,"['c#', '.net']" +735,mocking static blocks in java my motto for java is just because java has static blocks it does not mean that you should be using them jokes aside there are a lot of tricks in java that make testing a nightmare two of the most i hate are anonymous classes and static blocks we have a lot of legacy code that make use of static blocks and these are one of the annoying points in our push in writing unit tests our goal is to be able to write unit tests for classes that depend on this static initialization with minimal code changes so far my suggestion to my colleagues is to move the body of the static block into a private static method and call it staticinit this method can then be called from within the static block for unit testing another class that depends on this class could easily mock staticinit with jmockit to not do anything let us see this in examplepublic class classwithstaticinit static systemoutprintlnstatic initializer will be changed topublic class classwithstaticinit static staticinit private static void staticinit systemoutprintlnstatic initialized so that we can do the following in a junitpublic class dependentclasstest public static class mockclasswithstaticinit public static void staticinit beforeclass public static void setupbeforeclass mockitredefinemethodsclasswithstaticinitclass mockclasswithstaticinitclass however this solution also comes with its own problems you cannot run dependentclasstest and classwithstaticinittest on the same jvm since you actually want the static block to run for classwithstaticinittestwhat would be your way of accomplishing this task or any better nonjmockit based solutions that you think would work cleaner,['java'] +737,is there a good free wysiwyg editor for creating html using a django template i am interested to get a free wysiwyg html editor that is compatible with django template any ideasthanks lainmhbut i afraid fckeditor is used in web app for the purpose of editing html what i want is an editor that allows me to write html that is django compatible hope this clarifies the issue,['html'] +738,divs vs tables or css vs being stupid i know that tables are for tabular data but it is so tempting to use them for layout i can handle divs to get a three column layout but when you got 4 nested divs it get tricky is there a tutorialreference out there to persuade me to use divs for layouti want to use divs but i refuse to spend an hour to position my divspan where i want itgaryf blueprint css has to be the cs best kept secretgreat tool blueprint grid css generator,['css'] +741,how can i access the backing variable of an autoimplemented property in the past we declared properties like thispublic class myclass private int age public int age get return age set age value now we can dopublic class myclass public int age get set my question is how can i access the private variable that is created automatically using this notation i would rather access the private variable and not the public accessor age is there a default notation to access the private variable or it is just not possible,['c#'] +743,how to work around a very large 2d array in c i need to create a 2d int array of size 800x800 but doing so creates a stack overflow ha hai am new to c so should i do something like a vector of vectors and just encapsulate the 2d array into a claspecifically this array is my zbuffer in a graphics program i need to store a z value for every pixel on the screen hence the large size of 800x800thanks,['c++'] +752,how can i get axis 14 to not generate several prefixes for the same xml namespace i am receiving soap requests from a client that uses the axis 14 libraries the requests have the following formsoapenvenvelope xmlnssoapenv xmlnsxsd xmlnsxsi soapenvbody placeorderrequest xmlns order ns1requestparameter xmlnsns1 ns1orderingsystemwithdomain ns1orderingsysteminternetns1orderingsystem ns1domainsign2ns1domainsign ns1orderingsystemwithdomain ns1requestparameter ns2directdeliveryaddress ns2addresstype0 ns2index1 xmlnsns2 ns3address xmlnsns3 ns4zipcode xmlnsns412345ns4zipcode ns5city xmlnsns5cityns5city ns6street xmlnsns6streetns6street ns7housenum xmlnsns71ns7housenum ns8country xmlnsns8xxns8country ns3addressas you can see several prefixes are defined for the same namespace eg the namespace has the prefixes ns4 ns5 ns6 ns7 and ns8 some long requests define several hundred prefixes for the same namespacethis causes a problem with the saxon xslt processor that i use to transform the requests saxon limits the the number of different prefixes for the same namespace to 255 and throws an exception when you define more prefixescan axis 14 be configured to define smarter prefixes so that there is only one prefix for each namespace,['java'] +755,saving java object graphs as xml file whats the simplesttouse techonlogy available to save an arbitrary java object graph as an xml file and to be able to rehydrate the objects later,['java'] +764,whats the best way to build a string of delimited items in java while working in a java app i recently needed to assemble a commadelimited list of values to pass to another web service without knowing how many elements there would be in advance the best i could come up with off the top of my head was something like thispublic string appendwithdelimiter string original string addition string delimiter if originalequals return addition else return original delimiter addition string parameterstring if condition parameterstring appendwithdelimiter parameterstring elementname if anothercondition parameterstring appendwithdelimiter parameterstring anotherelementname i realize this is not particularly efficient since there are strings being created all over the place but i was going for clarity more than optimizationin ruby i can do something like this instead which feels much more elegantparameterarray parameterarray elementname if conditionparameterarray anotherelementname if anotherconditionparameterstring parameterarrayjoinbut since java lacks a join command i could not figure out anything equivalentso whats the best way to do this in java,['java'] +775,game programming and event handlers i have not programmed games for about 10 years my last experience was djgpp allegro but i thought i would check out xna over the weekend to see how it was shaping upi am fairly impressed however as i continue to piece together a game engine i have a probably basic questionhow much should you rely on cs delegates and events to drive the game as an application programmer i use delegates and events heavily but i do not know if there is a significant overhead to doing soin my game engine i have designed a chase cam of sorts that can be attached to an object and then recalculates its position relative to the object when the object moves there are two ways to update the chase camhave an updatecameras method in the main game loopuse an event handler and have the chase cam subscribe to objectonmovedi am using the latter because it allows me to chain events together and nicely automate large parts of the engine suddenly what would be huge and complex get dropped down to a handful of 35 line event handlersits a beautyhowever if event handlers firing every nanosecond turn out to be a major slowdown i will remove it and go with the loop approachideas,['c#'] +777,how does one record audio from a javascript based webapp i am trying to write a webapp that records wav files eg from the users microphone i know javascript alone can not do this but i am interested in the least proprietary method to augment my javascript with my targeted browsers are firefox for pc and mac so no activex please share your experiences with this i gather it can be done with flash but not as a wav formated file i gather it can be done with java but not without codesigning are these the only optionsdominicmazzoni i would like to record the file as a wav because because the purpose of the webapp will be to assemble a library of good quality short soundbites i estimate upload will be 50 mb which is well worth it for the quality the app will only be used on our intranetupdate there is now an alternate solution thanks to jetpacks upcoming audio api see,"['java', 'javascript']" +779,how do i call mysql stored procedures from perl how do i call mysql stored procedures from perl stored procedure functionality is fairly new to mysql and the mysql modules for perl do not seem to have caught up yet,['mysql'] +783,how can i write an iphone app entirely in javascript without making it just a web app i do not want to take the time to learn objc i have spent 7 years doing web application programming should not there be a way to use the webview and just write the whole app in javascript pulling the files right from the resources of the project,"['javascript', 'iphone', 'objective-c']" +784,explode that does not return empty strings phps explode function returns an array of strings split on some provided substring it will return empty strings like thisvar dumpexplode 123array5 0 string1 1 1 string1 2 2 string0 3 string1 3 4 string0 is there some different function or option or anything that would return everything except the empty stringsvar dumpdifferent explode 123array3 0 string1 1 1 string1 2 2 string1 3,['php'] +786,should html coexist with code in a web application is it acceptable to use html in your code nonscripted languages java netthere are two major sub questionsshould you use code to print html or otherwise directly create html that is thisplayedshould you mix code within your html pages,['html'] +788,how to implement shortcut key combination of ctrl or shift through javascript aspnet 20 web application how to implement shortcut key combination of ctrl preferably through javascript to make web application ergonomically better how to capture multiplekey keyboard events through javascript,['javascript'] +790,is gcj gnu compiler for java a viable tool for publishing a webapp is it really viable to use gcj to publish serverside applications webapps my boss is convinced that compiling our my webapp into a binary executable is a brilliant idea then again he likes nice small simple things with blinky lights that he can understand he instinctively sees no issues with this while i only see an endless series of problems and degradations once i start talking to him about the complexity of our platform and more in depth specifics of byte code jvms libraries differences between operating systems processor architectures etcwellhis eyes glaze over he smiles and he has made it clear he thinks i am being chilthishly resistivewhy does he want a single magic executable he sees a couple of benefitsif it is a binary executable then it is hard to reverse engineer and circumvent any licensing management lives in constant fear that this is happening even though we sell into larger corporates who generally do not do cheat with server software there is that vision of downloading this magic executable running it and everything works no more sending me out to do customer installations which is not that frequentso i have done my obligatory 20 minutes of googling and now i am here a bit of background on my application what it is made fromjava 6 suns jvmaspectj 16tomcat 6hibernate 3spring 2another two dozen supporting jar fileswhat it doesa streaming media cmsperformance sensitivedeployed on linux solaris windows and developed on a macas you can probably gather i am highly skeptical of this compiling java to native code thing it sound like where mono vb on linux was back in 20 but am i being overly pessimistic is it viable should i actually spend the time days if not weeks to try this outthere is one other similar thread java compiler options to produce exe files but it is a bit too simple the links dated and not really geared towards a serverside questionyour informed opinions will be highly cherished my dear sopedians tia,['java'] +793,java open source workflow engines what is the best open source java workflow framework eg osworkflow jbpm xflow etc,['java'] +794,how to get name associated with open handle whats the easiest way to get the filename associated with an open handle in win32,['c'] +795,how do you crash a jvm i was reading a book on programming skills wherein the author asks the interviewee how do you crash a jvm i thought that you could do so by writing an infinite forloop that would eventually use up all the memoryanybody has any idea,['java'] +796,convert a doc or pdf to an image and thisplay a thumbnail in ruby convert a doc or pdf to an image and thisplay a thumbnail in rubydoes anyone know how to generate document thumbnails in ruby or c python,['ruby'] +797,apache axis configurationexception i am using apache axis to connect my java app to a web server i used wsdl2java to create the stubs for me but when i try to use the stubs i get the following exceptionorgapacheaxisconfigurationexception no service named web service name is availableany idea,['java'] +800,whats the best html wysisyg editor available to web developers and why there are many different flavored html wysiwyg editors from javascript to aspnet web controls but all too often the features are the same does anyone have a favorite html editor they like to use in projects why,"['asp.net', 'javascript', 'html']" +801,unit testing c code i worked on an embedded system this summer written in straight c it was an existing project that the company i work for had taken over i have become quite accustomed to writing unit tests in java using junit but was at a loss as to the best way to write unit tests for existing code which needed refactoring as well as new code added to the systemare there any projects out there that make unit testing plain c code as easy as unit testing java code with junit any insight that would apply specifically to embedded development crosscompiling to armlinux platform would be greatly appreciated,['c'] +805,anyone know of a list of delegates already built into the framework i find myself writing delegates occasionally for really simple functions take no arguments and return void for example and am wondering if anyone knows someplace that has compiled a list of all the predefined delegates already available in the net framework so i can reuse themto be clear i am looking for something like thisvoid systemasynccallbacksystemiasyncresultint systemcomparisont x t yvoid systemioerroreventhandlerobject systemioerroreventargsand so onif not sounds like a good idea for a blog article,['.net'] +808,how do you launch the javascript debugger in google chrome when using google chrome i want to debug some javascript code how can i do that,['javascript'] +809,when does systemgc do anything i know that garbage collection is automated in java but i understood that if you write systemgc in your code the java vm may or may not decide at runtime to do a garbage collection at that point how does this work precisely on what basisparameters exactly does the vm decide to do or not do a gc when it sees a systemgc are there maybe examples in which case it is a good idea to put this in your code,['java'] +810,how can i create a site in php and have it generate a static version for a particular project i have no server side code is allowed how can i create the web site in php with includes conditionals etc and then have that converted into a static html site that i can give to the clientupdate thanks to everyone who suggested wget that is what i used i should have specified that i was on a pc so i grabbed the windows version from here,"['php', 'html']" +812,how do i create a new signal in pygtk i have created a python object but i want to send signals on it i made it inherit from gobjectgobject but there does not seem to be any way to create a new signal on my object,['python'] +814,why is rspec so slow under rails whenever i run rspec tests for my rails application it takes forever and a day of overhead before it actually starts running tests why is rspec so slow is there a way to speed up rails initial load or single out the part of my rails app i need eg activerecord stuff only so it does not load absolutely everything to run a few tests,"['ruby-on-rails', 'ruby']" +818,how do i run a program as nobody i want a userprivileged not root process to launch new processes as user nobody i have tried a straight call to setuid that fails with 1 eperm on ubuntu 804include systypeshinclude unistdhint main setuid65534 while 1 return 0how should i do this instead,['c'] +824,dynamically create a generic type for template i am programming wcf using the channelfactory which expects a type in order to call the createchannel method for example iproxy proxy channelfactoryiproxycreatechannelin my case i am doing routing so i do not know what type my channel factory will be using i can parse a message header to determine the type but i hit a brick wall there because even if i have an instance of type i cannot pass that where channelfactory expects a generic type another way of restating this problem in very simple terms would be that i am attempting to do something like thisstring listtype consolereadline say systemint32type t typegettype listtypelistt myintegers new list does not compile expects a typelisttypeoft myintegers new listtypeoft interesting type must resolve at compile timeis there an approach to this i can leverage within c,['c#'] +826,other than xcode are there any full functioned ides for objectivec i know and have xcode but i was wondering if there were any other complete development environments that support objectivec i am not looking for solutions with vim or emacs nor editors like bbedit that support syntax highlighting but a full fledged ide withcode completioncompilationdebuggingrefactoringextra points for being cross platform supporting vi key bindings and supporting other languagesnotei have updated and accepted my answer below as jetbrains has released early access for appcode their new objectivec ide since this has been a fairly popular question i thought it worthwhile to update the information,['objective-c'] +830,how to debug a jsp tomcat service using eclipse i would like to debug my separately running jspstrutstomcathibernate application stack using the eclipse ide debugger how do i setup the java jvm and eclipse so that i can set breakpoints monitor variable values and see the code that is currently executing,['java'] +831,whats the best way to hash a url in ruby i am writing a web app that points to external links i am looking to create a nonsequential nonguessable id for each document that i can use in the url i did the obvious thing treating the url as a string and strcrypt on it but that seems to choke on any nonalphanumberic characters like the slashes dots and underscoresany suggestions on the best way to solve this problemthanks,['ruby'] +839,are tuples more efficient than lists in python is there any performance difference between tuples and lists when it comes to instantiation and retrieval of elements,['python'] +840,can you have a class in a struct is it possible in c to have a struct with a member variable which is a class type if so where does the information get stored on the stack the heap or both,['c#'] +841,how do you write a c extension method for a generically typed class this should hopefully be a simple onei would like to add an extension method to the systemwebmvcviewpage t classhow should this extension method lookmy first intuitive thought is something like thisnamespace systemwebmvc public static class viewpageextensions public static string getdefaultpagetitlethis viewpagetype v return solutionthe general solution is this answerthe specific solution to extending the systemwebmvcviewpage class is my answer below which started from the general solutionthe difference is in the specific case you need both a generically typed method declaration and a statement to enforce the generic type as a reference type,['c#'] +846,why does a cc program often have optimization turned off in debug mode in most c or c environments there is a debug mode and a release mode compilationlooking at the difference between the two you find that the debug mode adds the debug symbols often the g option on lots of compilers but it also thisables most optimizationsin release mode you usually have all sorts of optimizations turned onwhy the difference,"['c++', 'c']" +848,is there a way to make text unselectable on an html page i am building an html ui with some text elements such as tab names which look bad when selected unfortunately it is very easy for a user to doubleclick a tab name which selects it by default in many browsersi might be able to solve this with a javascript trick i would like to see those answers too but i am really hoping there is something in csshtml directly that works across all browsers,"['javascript', 'html', 'css']" +849,what safarispecific pure css hacks are out there i am wondering if there is any way to write css specifically for safari using only css i know there has to be something out there but i have not found it yet,['css'] +857,what attributes help runtime net performance i am looking for attributes i can use to ensure the best runtime performance for my net application by giving hints to the loader jit compiler or ngenfor example we have debuggableattribute which should be set to not debug and not thisable optimization for optimal performancedebuggablefalse falseare there any others i should know about,['.net'] +864,deleting a buffer through a different type of pointer say i have the following cchar p new charcbsome struct pss some struct pdelete pssis this safe according to the c standard do i need to cast back to a char and then use delete i know it will work in most c compilers because it is plainordinarydata with no destructors is it guaranteed to be safe,['c++'] +867,can i add maven repositories in the command line i am aware i can add maven repositories for fetching dependencies in m2settingsxml but is it possible to add a repository using command line something likemvn install dmavenrepositorythe reason i want to do this is because i am using a continuous integration tool where i have full control over the command line options it uses to call maven but managing the settingsxml for the user that runs the integration tool is a bit of a hassle,['java'] +875,how to implement a digglike algorithm how to implement a website with a recommendation system similar to stackoverflowdiggreddit ie users submit content and the website needs to calculate some sort of hotness according to how popular the item is the flow is as followsusers submit contentother users view and vote on the content assume 90 of the users only views content and 10 actively votes up or down on contentnew content is continuously submittedhow do i implement an algorithm that calculates the hotness of a submitted item preferably in realtime are there any bestpractices or design patternsi would assume that the algorithm takes the following into considerationwhen an item was submittedwhen each vote was castwhen the item was viewedeg an item that gets a constant trickle of votes would stay somewhat hot constantly while an item that receives a burst of votes when it is first submitted will jump to the top of the hotnesslist but then fall down as the votes stop coming ini am using a mysqlphp but i am interested in general design patterns,['sql'] +877,c overload resolution given the following example why do i have to explicitly use the statement badosomething rather than just bdosomethingshould not the compilers overload resolution figure out which method i am talking abouti am using microsoft vs 2005 note using virtual does not help in this caseclass a public int dosomething return 0class b public a public int dosomethingint x return 1int main b b new b badosomething why this bdosomething why not this gives compiler error delete b return 0,['c++'] +879,how to implement dom ready event in a greasemonkey script i am trying to modify my greasemonkey script from firing on windowonload to windowdomcontentloaded but this event never firesi am using firefox 20016 greasemonkey 0820080609this is the full script that i am trying to modify changingwindowaddeventlistener load dostuff falsetowindowaddeventlistener domcontentloaded dostuff false,['javascript'] +886,making a cwinform application crossplatform should i use air mono or something else i have an app that i have written in cwinforms my little app to make it crossplatform i am thinking of redoing it in adobe air are there any arguments in favor of winforms as a crossplatform app is there a crossplatform future for winforms eg mono etc suggestions for crossplatform ui developmentby crossplatform i mean currently mac osx windows and linuxthis question was asked again and answered with better success,['c#'] +893,how do i send an smtp message from java possible duplicatehow do you send email from a java app using gmail how do i send an smtp message from java,['java'] +896,combine pdfs c how can i combine multiple pdfs into one pdf without a 3rd party component,['c#'] +897,dropdownlist width in ie in ie the dropdownlist takes the same width as the dropbox i hope i am making sense whereas in firefox the dropdownlists width varies according to the content this basically means that i have to make sure that the dropbox is wide enough to thisplay the longest selection possible this makes my page look very ugly is there any workaround for this problem how can i use css to set different widths for dropbox and the dropdownlist,"['javascript', 'html']" +902,random in python 25 not working i am trying to use the import random statement in python but it does not appear to have any methods in it to useam i missing something,['python'] +908,delegating a task in and getting notified when it completes in c conceptually i would like to accomplish the following but have had trouble understand how to code it properly in csomemethod member of aclass dosomething start workermethod from bclass in another thread dosomethingelsethen when workermethod is complete run thisvoid someothermethod also member of aclass can anyone please give an example of that,['c#'] +909,how do i add a namespace reference to a soap response with apache axis2 and wsdl2java i am looking at the soap output from a web service i am developing and i noticed something curioussoapenvenvelope xmlnssoapenv soapenvbody ns1createentitytypesresponse xmlnsns1 newkeys value1234value newkeys newkeys value2345value newkeys newkeys value3456value newkeys newkeys xsinil1 xmlnsxsi newkeys xsinil1 xmlnsxsi errorserror1errors errorserror2errors ns1createentitytypesresponse soapenvbodysoapenvenvelopei have two newkeys elements that are nil and both elements insert a namespace reference for xsi i would like to include that namespace in the soapenvenvelope element so that the namespace reference is only sent oncei am using wsdl2java to generate the service skeleton so i do not directly have access to the axis2 api,['java'] +910,how to thisplay a dynamically allocated array in the visual studio debugger if you have a statically allocated array the visual studio debugger can easily thisplay all of the array elements however if you have an array allocated dynamically and pointed to by a pointer it will only thisplay the first element of the array when you click the to expand it is there an easy way to tell the debugger show me this data as an array of type foo and size x,"['c++', 'c']" +915,how do i get the name of a python class as a string what method do i call to get the name of a class,['python'] +918,jpa multiple transaction managers i have one applicationcontextxml file and it has two orgspringframeworkormjpajpatransactionmanager each with its own persistence unit different databases configured in a spring middleware custom applicationi want to use annotation based transactions transactional to not mess around with transactionstatus commit save and rollbacka coworker mentioned that something gets confused doing this when there are multiple transaction managers even though the context file is set configured correctly the references go to the correct persistence unitanyone ever see an issuein your config would you have two transaction managerswould you have txmanager1 and txmanager2that is what i have with jpa two different spring beans that are transaction managers,['java'] +919,when are you supposed to use escape instead of encodeuri encodeuricomponent when encoding a query string to be sent to a web server when do you use escape and when do you use encodeuri or encodeuricomponentuse escapeescape oruse encodeuri encodeuricomponentencodeurivar2value2encodeuricomponentvar1value1var2value2,['javascript'] +923,freecheap powerdesigner alternative we are using powerdesigner at work for database modelling but there is a hell of a price tag on that piece of software and frankly all i use is physical diagrams for ms sql which is about 1 of what pd knowsare there any good alternatives i know about visio and ms sql diagrams but looking for other options,['sql'] +929,is there a way to dynamically load a properties file in nant i want to load a different properties file based upon one variablebasically if doing a dev build use this properties file if doing a test build use this other properties file and if doing a production build use yet a third properties file,['.net'] +936,what to put in a session variable i recently came across a asp 11 web application that put a whole heap of stuff in the session variable including all the db data objects and even the db connection object it ends up being huge when the web session times out four hours after the user has finished using the application sometimes their database transactions get rolled back i am assuming this is because the db connection is not being closed properly when iis kills the sessionanyway my question is what should be in the session variable clearly some things need to be in there the user selects which plan they want to edit on the main screen so the plan id goes into the session variable is it better to try and reduce the load on the db by storing all the details about the user and their manager etc and the plan they are editing in the session variable or should i try to minimise the stuff in the session variable and query the db for everything i need in the page load event,['asp.net'] +941,python reportlab use of splitfirstsplitlast i am trying to use python with reportlab 22 to create a pdf reportaccording to the user guidespecial tablestyle indeces sicin any style command the first row index may be set to one of the special strings splitlast or splitfirst to indicate that the style should be used only for the last row of a split table or the first row of a continuation this allows splitting tables with nicer effects around the spliti have tried using several style elements includingtextcolor 0 splitfirst 1 splitfirst colorsblack textcolor 0 splitfirst 1 0 colorsblack textcolor 0 splitfirst 1 1 colorsblackand none of these seems to work the first generates a typeerror with the message typeerror cannot concatenate str and int objectsand the latter two generate typeerrors with the messagetypeerror an integer is requiredis this functionality simply broken or am i doing something wrong if the latter what am i doing wrong,['python'] +948,best c ide for nix what is the best c ide for a nix envirnoment i have heard the cc module of eclipse is decent as well as notepad but beyond these two i have no real idea any thoughts or comments,['c++'] +952,parsing http headers i have had a new found interest in building a small efficient web server in c and have had some trouble parsing post methods from the http header would anyone have any advice as to how to handle retrieving the namevalue pairs from the posted datapost test http11host testdomaincom7017useragent mozilla50 windows u windows nt 51 enus rv1901 gecko2008070208 firefox301accept texthtmlapplicationxhtmlxmlapplicationxmlq09q08acceptlanguage enusenq05acceptencoding gzipdeflateacceptcharset iso88591utf8q07q07keepalive 300connection keepalivereferer cookie utma4316624121741329912207263141221171690122120018116 utmz43166241122072631411utmccndirectutmcsrdirectutmcmdnonecachecontrol maxage0contenttype applicationxwformurlencodedcontentlength 25field1asfdfield2a3f3f3 thisi see no tangible way to retrieve the bottom line as a whole and ensure that it works every time i am not a fan of hardcoding in anything,['c'] +953,how do you design data models for bigtabledatastore gae since the google app engine datastore is based on bigtable and we know that is not a relational database how do you design a database schemadata model for applications that use this type of database system,['python'] +955,how to truncate a string in php to the word closest to a certain number of characters i have a code snippet written in php that pulls a block of text from a database and sends it out to a widget on a webpage the original block of text can be a lengthy article or a short sentence or two but for this widget i cannot thisplay more than say 200 characters i could use substr to chop off the text at 200 chars but the result would be cutting off in the middle of words what i really want is to chop the text at the end of the last word before 200 chars,['php'] +963,phantom referenced objects phantom references serve for postmortem operationsthe java specification states that a phantom referenced object will not be deallocated until the phantomreference itself is cleanedmy question is what purpose does this feature object not deallocated servethe only idea i came up with is to allow native code to do postmortem cleanup on the object but it is not much convincing,['java'] +968,best way to tackle global hotkey processing in c possible duplicatehow can i register a global hot key to say ctrlshiftletter using wpf and net 35 i would like to have multiple global hotkeys in my new app to control the app from anywhere in windows and all of the given sourcessolutions i found on the web seem to provide with a sort of a limping solution either solutions only for one ghotkey or solutions that while running create annoying mouse delays on the screendoes anyone here know of a resource that can help me achive this that i can learn fromanythingthanks,['c#'] +969,autogenerating unittests for legacy javacode what is the best preferably freeopen source tool for autogenerating java unittests i know the unittests cannot really serve the same purpose as normal tdd unittests which document and drive the design of the system however autogenerated unittests can be useful if you have a huge legacy codebase and want to know whether the changes you are required to make will have unwanted obscure sideeffects,['java'] +970,how to get the file path from html input form in firefox 3 we have simple html form with input typefile like shown belowform label forattachmentattachmentlabel input typefile nameattachment idattachment input typesubmitformin ie7 and probably all famous browsers including old firefox 2 if we submit a file like server1pathtofilefilename it works properly and gives the full path to thefile and the filenamein firefox 3 it returns only filename because of their new security feature to truncate the path as explained in firefox bug tracking system bugcgiid143220i have no clue how to overcome this new feature because it causes all upload forms in my webapp to stop working on firefox 3can anyone help to find a single solution to get the file path both on firefox 3 and ie7,['html'] +971,easiest way to merge a release into one jar file is there a tool or script which easily merges a bunch of jar files into one jar file a bonus would be to easily set the mainfile manifest and make it executablethe concrete case is a java restructured text tool i would like to run it with something likejava jar rstjaras far as i can tell it has no dependencies which indicates that it should not be an easy singlefile tool but the downloaded zip file contains a lot of libraries 0 113007 1001 jrst081 922 113007 0953 jrst081jrstbat 898 113007 0953 jrst081jrstsh 2675 113007 0942 jrst081readmeentxt 108821 113007 0959 jrst081jrst081jar 2675 113007 0942 jrst081readmetxt 0 113007 1001 jrst081lib 81508 113007 0949 jrst081libbatikutil161jar2450757 113007 0949 jrst081libicu4j261jar 559366 113007 0949 jrst081libcommonscollections31jar 83613 113007 0949 jrst081libcommonsio131jar 207723 113007 0949 jrst081libcommonslang21jar 52915 113007 0949 jrst081libcommonslogging11jar 260172 113007 0949 jrst081libcommonsprimitives10jar 313898 113007 0949 jrst081libdom4j161jar1994150 113007 0949 jrst081libfop093jdk15jar 55147 113007 0949 jrst081libactivation102jar 355030 113007 0949 jrst081libmail133jar 77977 113007 0949 jrst081libservletapi23jar 226915 113007 0949 jrst081libjaxen1jar 153253 113007 0949 jrst081libjdom10jar 50789 113007 0949 jrst081libjewelcli041jar 324952 113007 0949 jrst081liblooks122jar 121070 113007 0949 jrst081libjunit381jar 358085 113007 0949 jrst081liblog4j1212jar 72150 113007 0949 jrst081liblogkit101jar 342897 113007 0949 jrst081liblutinwidget09jar2160934 113007 0949 jrst081libdocbookxslnwalsh1711jar 301249 113007 0949 jrst081libxmlgraphicscommons11jar 68610 113007 0949 jrst081libsdoc050betajar3149655 113007 0949 jrst081libxalan260jar1010675 113007 0949 jrst081libxercesimpl262jar 194205 113007 0949 jrst081libxmlapis1302jar 78440 113007 0949 jrst081libxmlparserapis202jar 86249 113007 0949 jrst081libxmlunit11jar 108874 113007 0949 jrst081libxom10jar 63966 113007 0949 jrst081libavalonframework413jar 138228 113007 0949 jrst081libbatikguiutil161jar 216394 113007 0949 jrst081libl2fprodcommon01jar 121689 113007 0949 jrst081liblutinutil026jar 76687 113007 0949 jrst081libbatikext161jar 124724 113007 0949 jrst081libxmlparserapis262jaras you can see it is somewhat desirable to not need to do this manuallyso far i have only tried autojar and proguard both of which were fairly easy to get running it appears that there is some issue with the constant pool in the jar filesapparently jrst is slightly broken so i will make a go of fixing it the maven pomxml file was apparently broken too so i will have to fix that before fixing jrst i feel like a bugmagnet update i never got around to fixing this application but i checked out eclipses runnable jar export wizard which is based on a fat jar i found this very easy to use for deploying my own codesome of the other excellent suggestions might be better for builds in a noneclipse environment oss probably should make a nice build using ant maven so far has just given me pain but others love it,['java'] +975,how do you add a javascript widget to a wordpresscom hosted blog i have got a site that provides blogfriendly widgets via javascript these work fine in most circumstances including selfhosted wordpress blogs with blogs hosted at wordpresscom however javascript is not allowed in sidebar text modules has anyone seen a workaround for this limitation,['javascript'] +978,what prevents a thread in c from being collected in net after this code what mechanism stops the thread object from being garbage collectednew threadfoostartgccollectyes it is safe to assume something has a reference to the thread i was just wandering what exactly for some reason reflector does not show me systemthreading so i cannot dig it myself i know ms released the source code for the net framework i just do not have it handy,['.net'] +980,rails or grails grails vs rails which has better support and which one is a better choice to develop medium size apps with most importantly which one has more plugins,"['ruby-on-rails', 'ruby']" +981,is it possible to print a variables type in standard c for exampleint a 12cout typeofa endlexpected outputint,['c++'] +986,best way to handle urls in a multilingual site in aspnet i need to do a multilingual website with urls likewdomaincomenhomeaspx for englishwdomaincomeshomeaspx for spanishin the past i would set up two virtual directories in iis and then detect the url in globalaspx and change the language according to the urlsub application beginrequestbyval sender as object byval e as eventargs dim lang as string if httpcontextcurrentrequestpathcontainsen then lang en else lang es end if threadcurrentthreadcurrentuiculture cultureinfogetcultureinfolang threadcurrentthreadcurrentculture cultureinfocreatespecificculturelangend subthe solution is more like a hack i am thinking about using routing for a new website do you know a better or more elegant way to do itedit the question is about the url handling not about resources etc,['asp.net'] +988,boost serialization specifying a template class version i have a template class that i serialize call it c for which i want to specify a version for boost serialization as boost class version does not work for template classes i tried thisnamespace boost namespace serialization template typename t typename you struct version ctu typedef mplint 1 type typedef mplintegral c tag tag boost static constantunsigned int value versiontypevalue but it does not compile under vc8 a subsequent call to boost class version gives this errorerror c2913 explicit specialization boostserializationversion is not a specialization of a class templatewhat is the correct way to do it,['c++'] +991,connecting to oracle using php i am a php developer but i am confused on how to connect to a remote oracle database instance from php i simply need to query a read only database and get some data do i need to have the oracle instant client or the extension is enough thanks,['php'] +1000,is there a functional programming library for net for example in java there is functional java and higherorder java both essentially give a small api for manipulating higherorder curried functions and perhaps a few new data types tuples immutable lists,"['c#', '.net']" +1001,is it the filename or the whole url used as a key in browser caches it is common to want browsers to cache resources javascript css images etc until there is a new version available and then ensure that the browser fetches and caches the new version insteadone solution is to embed a version number in the resources filename but will placing the resources to be managed in this way in a directory with a revision number in it do the same thing is the whole url to the file used as a key in the browsers cache or is it just the filename itself and some metadataif my code changes from fetching r20examplejs to r21examplejs can i be sure that revision 20 of examplejs was cached but now revision 21 has been fetched instead and it is now cached,['javascript'] +1003,getting a full list of the urls in a rails application how do i get a a complete list of all the urls that my rails application could generate i do not want the routes that i get get form rake routes instead i want to get the actul urls corrosponding to all the dynmically generated pages in my applicationis this even possiblebackground i am doing this because i want a complete list of urls for some load testing i want to do which has to cover the entire breadth of the application,['ruby-on-rails'] +1005,mysql create table if not exists else truncate here is the updated questionthe current query is doing something likesql1 truncate table fubarsql2 create temporary table if not exists fubar select id name from barfuthe first time the method containing this is run it generates an error message on the truncate since the table does not exist yetis my only option to do the create table run the truncate table and then fill the table 3 separate queriesoriginal question wasi have been having a hard time trying to figure out if the following is possible in mysql without having to write block sqlcreate table fubar if not exists else truncate table fubarif i run truncate separately before the create table and the table does not exist then i get an error message i am trying to eliminate that error message without having to add any more queriesthis code will be executed using php,['mysql'] +1006,why learn perl python ruby if the company is using c c or java as the application language i wonder why would a c c java developer want to learn a dynamic languageassuming the company would not switch its main development language from ccjava to a dynamic one what use is there for a dynamic languagewhat helper tasks can be done by the dynamic languages faster or better after only a few days of learning than with the static language that you have been using for several yearsupdateafter seeing the first few responses it is clear that there are two issuesmy main interest would be something that is justifiable to the employer as an expensethat is i am looking for justifications for the employer to finance the learning of a dynamic language aside from the obvious that the employee will have broader view theemployers are usually looking for some real benefit,"['c#', 'java', 'python', 'ruby']" +1008,how do you authenticate against an active directory server using spring security i am writing a spring web application that requires users to login my company has an active directory server that i would like to make use of for this purpose however i am having trouble using spring security to connect to the serveri am using spring 255 and spring security 203 along with java 16if i change the ldap url to the wrong ip address it does not throw an exception or anything so i am wondering if it is even trying to connect to the server to begin withalthough the web application starts up just fine any information i enter into the login page is rejected i had previously used an inmemorydaoimpl which worked fine so the rest of my application seems to be configured correctlyhere are my securityrelated beans beansbean idldapauthprovider classorgspringframeworksecurityprovidersldapldapauthenticationprovider beansconstructorarg beansbean classorgspringframeworksecurityprovidersldapauthenticatorbindauthenticator beansconstructorarg refinitialdircontextfactory beansproperty nameuserdnpatterns beanslist beansvaluecn0ousbsusersouusersoumybusinessdcacmedccombeansvalue beanslist beansproperty beansbean beansconstructorarg beansbean beansbean iduserdetailsservice classorgspringframeworksecurityuserdetailsldapldapuserdetailsmanager beansconstructorarg refinitialdircontextfactory beansbean beansbean idinitialdircontextfactory classorgspringframeworksecurityldapdefaultinitialdircontextfactory beansconstructorarg valueldap192168123456389dcacmedccom beansbean,['java'] +1011,how to communicate with a windows service from an application that interacts with the desktop with net what is the best way to interact with a service ie how do most trayapps communicate with their servers it would be preferred if this method would be crossplatform as well working in mono so i guess remoting is outeditforgot to mention we still have to support windows 20 machines in the field so wcf and anything above net 20 would not fly,"['c#', '.net']" +1015,how does the java for each loop work liststring somelist new arrayliststring add monkey donkey skeleton key to somelistfor string item somelist systemoutprintlnitemwhat would the equivalent for loop look like without using the for each syntax,['java'] +1031,how to check if a string contains another string in a case insensitive manner in java say i have two stringsstring s1 abbaccastring s2 baci want to perform a check returning that s2 is contained within s1 i can do this withreturn s1containss2i am pretty sure that contains is case sensitive however i cannot determine this for sure from reading the documentation if it is then i suppose my best method would be something likereturn s1tolowercasecontainss2tolowercaseall this aside is there another possibly better way to accomplish this without caring about casesensitivity,['java'] +1035,where to find java 6 jssejce source code where can i download the jsse and jce source code for the latest release of java the source build available at does not include the javaxcrypto jce packages nor the comsunnetsslinternal jsse packagesnot being able to debug these classes makes solving ssl issues incredibly difficult,['java'] +1040,how does gcc implement stack unrolling for c exceptions on linux how does gcc implement stack unrolling for c exceptions on linux in particular how does it know which destructors to call when unrolling a frame ie what kind of information is stored and where is it stored,['c++'] +1047,automated integration testing a c app with a database i am introducing automated integration testing to a mature application that until now has only been manually testedthe app is windows based and talks to a mysql databasewhat is the best way including details of any tools recommended to keep tests independent of each other in terms of the database transactions that will occur modifications to the app source for this particular purpose are not an option,['c++'] +1055,throwing exceptions in aspnet c is there a difference between just saying throw and throw ex assuming ex is the exception youre catching,"['c#', '.net']" +1058,how do i restore from a drop database command using a mysql binary log how can i restore a mysql database that was dropped using a drop database command i have access to binary logs which should make this type of rollback possible,['mysql'] +1060,is there any reason to not ship the pdbs with your application since you can use reflector to reverseengineer a net app is there any reason to not ship the pdb files with the app if you do ship them with it then your stack trace will include the line number with the problem which is useful if it crashesplease only enter 1 reason per comment for voting,"['c#', '.net']" +1066,app code folder issues so i am having a really weird issue with my app code folder on a new website i am designing i have a basic class inside of a namespace in the app code folder everything works fine in the ide when i setup the namespace and make an object from the class it brings up the class summary on hover and when you click on go to deffinition it goes to the class fileand it also works fine localyhowever when i load the site onto my server i get this error message when i access that page line 10 using systemwebuiwebcontrolsline 11 using systemwebuiwebcontrolswebpartsline 12 using xcompiler error message cs0246 the type or namespace name x could not be found are you missing a using directive or an assembly referencei know for a fact that the class file is there anyone have any idea of whats going oneditsjohn yes it is a 20 site,"['c#', 'asp.net']" +1068,how do you pass arguments to define method i would like to pass an arguments to a method being defined using define method how would i do that,['ruby'] +1077,what is your session management strategy for nhibernate in desktop applications i find it much more difficult to manage your session in a desktop application because you cannot take advantage of such a clear bondary like httpcontextso how do you manage your session lifetime to take advantage of lazy loading but without having one session open for the entire application,['.net'] +1078,good aspnet c apps any suggestions for good open source aspnet c apps out there which meet as many of the followingdesigned well and multi tieredclean commented codegood use of several design patternsweb pages thisplay properly in all common browsersproduces valid html and has good use of cssuse of css themes prefer usage of css than tablesnot dependent on third party components grids menus trees etchas good unit testsweb pages are not simplistic and look professionaluses newer technologies like mvc linq not importantanything else that matters which i could not think of right now,"['c#', 'asp.net', 'css']" +1083,optional parameters in mysql stored procedures how do i create an optional parameter in a mysql stored procedure,['mysql'] +1084,how do i best convert a dbtype to systemtype how do i best convert a systemdatadbtype enumeration value to the corresponding or at least one of the possible corresponding systemtype valuesfor exampledbtypestringfixedlength systemstring dbtypestring systemstringdbtypeint32 systemint32i have only seen very dirty solutions but nothing really cleanyes it is a follow up to a different question of mine but it made more sense as two seperate questions,['.net'] +1089,how to calculate the sum of values in a tree using sql i need to sum points on each level earned by a tree of users level 1 is the sum of users points of the users 1 level below the user level 2 is the level 1 points of the users 2 levels below the user etcthe calculation happens once a month on a non production server no worries about performancewhat would the sql look like to do itif youre confused do not worry i am as welluser tableid parentid points1 0 2302 1 1503 0 804 1 1105 4 546 4 342tree01 3 2 4 5 6output should beid points level1 level21 230 150110 150110543422 1503 804 110 543425 546 342sql server syntax and functions preferably,['sql'] +1094,is there a pretty printer for python data working with python interactively it is sometimes necessary to thisplay a result which is some arbitrarily complex data structure like lists with embedded lists etcthe default way to thisplay them is just one massive linear dump which just wraps over and over and you have to parse carefully to read itis there something that will take any python object and thisplay it in a more rational manner eg0 1 a b c 2 3 4instead of0 1 a b c 2 3 4i know that is not a very good example but i think you get the idea,['python'] +1096,reading quicken data files looking for an open source library for c java c or python for reading the data from quicken qdf filesswati quicken qif format is for transfer only and is not kept up to date by the application like the qdf file is,"['c#', 'java', 'python']" +1098,python beyond the basics i have gotten to grips with the basics of python and i have got a small holiday which i want to use some of to learn a little more python the problem is that i have no idea what to learn or where to start i am primarily web development but in this case i do not know how much difference it will make,['python'] +1101,save and restore form position and size in a winforms 20 c application what is the typical method used for saving and restoring form position and size in an applicationrelated is it possible to add new user scoped application settings at runtime i totally see how to add settings at design time that is not a problem but what if i want to create one at runtimemore detailsmy application is a conversion of an existing visual foxpro application i have been trying to read as much as i can about application settings user settings etc and get myself clear on the net way of doing things but there are still several things i am confused onin the fox app saved settings are stored in the registry my forms are subclassed and i have base class code that automatically saves the form position and size in the registry keyed on the form name whenever i create a new form i do not have to do anything special to get this behavior it is built in to the base class my net forms are also subclassed that part is working wellin net i get the impression i am supposed to use user scoped settings for things like user preferences size and location of a form definitely seem like a user preference but i cannot see any way to automatically add these settings to the project in other words every time i add a new form to my project and their are 100s of forms i have to remember to add a user scoped application setting and be sure to give it the same name as the form ie formmyspecialsizeposition to hold the size and position i would rather not have to remember to do that is this just tough luck or am i totally barking up the wrong tree by trying to use user scoped settings do i need to create my own xml file to hold settings so that i can do whatever i want ie add a new setting at runtime or something elsesurely this is a very common and somebody can tell the right way to do it thanks in advance,['.net'] +1102,python sockets suddenly timing out i came back today to an old script i had for logging into gmail via ssl the script worked fine last time i ran it several months ago but now it dies immediately withurlopen error the read operation timed outif i set the timeout no matter how long it dies even more immediately withurlopen error the connect operation timed outthe latter is reproducible withimport socketsocketsetdefaulttimeout30sock socketsocketsockconnectwgooglecom 443ssl socketsslsockreturningsocketsslerror the connect operation timed outbut i cannot seem to reproduce the former and after much stepping thru the code i have no clue whats causing any of this,['python'] +1103,jqueryjavascript to replace broken images i have a web page that includes a bunch of images sometimes the image is not available so a broken image is thisplayed in the clients browserhow do i use jquery to get the set of images filter it to broken images then replace the srci thought it would be easier to do this with jquery but it turned out much easier to just use a pure javascript solution that is the one provided by prestaul,"['javascript', 'jquery', 'html']" +1109,a free tool to check cc source code against a set of coding standards it looks quite easy to find such a tool for java checkstyle jcsc but i cannot seem to find one for cc i am not looking for a lintlike static code analyzer i only would like to check against coding standards like variable naming capitalization spacing identation bracket placement and so on,"['c++', 'c']" +1114,apply stroke to a textblock in wpf how do you apply stroke outline around text to a textblock in xaml in wpf,['.net'] +1115,whats the easiest nonmemory intensive way to output xml from python basically something similar to systemxmlxmlwriter a streaming xml writer that does not incur much of a memory overhead so that rules out xmldom and xmldomminidom suggestions,['python'] +1117,eefileloadexception when using c classes in cwin32 app for deployment reasons i am trying to use ijw to wrap a c assembly in c instead of using a com callable wrapper i have done it on other projects but on this one i am getting an eefileloadexception any help would be appreciatedmanaged c wrapper code this is in a dllextern c declspecdllexport imyobject createmyobjectvoid this class references c in the constructor return new cmywrapper extern c declspecdllexport void deletemyobjectimyobject pconfigfile delete pconfigfileextern c declspecdllexport void testfunctionvoid messageboxnull tmy message box ttest mb oktest code this is an exetypedef void createobjectptrtypedef void testfunctionptrint tmain testwrapperint argc tchar argv tchar envp hmodule hmodule loadlibrary tmywrapper asserthmodule null pvoid pfunc1 getprocaddresshmodule testfunction assertpfunc1 null testfunctionptr ptest testfunctionptrpfunc1 pvoid pfunc2 getprocaddresshmodule createmyobject assertpfunc2 null createobjectptr pcreateobjectfunc createobjectptrpfunc2 ptest this successfully pops up a message box pcreateobjectfunc this tosses an eefileloadexception return 0for what it is worth the event log reports the followingnet runtime version 2050727143 fatal execution engine error 79f97075 80131506unfortunately microsoft has no information on that error,['c#'] +1120,what python gui apis are out there simple questionwhat python gui apis are out there and what are the advantages of any given apii am not looking for a religious war here i am just wanting to get a good handle on all that is out there in terms of python gui apis,['python'] +1122,windsor interceptors aop caching i am considering using castle windsors interceptors to cache data for helping scale an aspnet sitedoes anyone have any thoughtsexperience with doing thisminor clarificationmy intention was to use windsor to intercept expensive calls and delegate to memcached or velocity or another thistributed cache for the caching itself,['.net'] +1124,how do i read selected files from a remote zip archive over http using python i need to read selected files matching on the file name from a remote zip archive using python i do not want to save the full zip to a temporary file it is not that large so i can handle everything in memoryi have already written the code and it works and i am answering this myself so i can search for it later but since evidence suggests that i am one of the dumber participants on stackoverflow i am sure there is room for improvement,['python'] +1129,fetch one row per account id from list i have a table with game scores allowing multiple rows per account id scores id score accountid i want a list of the top 10 scorer ids and their scorescan you provide an sql statement to select the top 10 scores but only one score per account id thanks,"['sql', 'mysql']" +1131,can this macro be converted to a function while refactoring code and ridding myself of all those defines that were now taught to hate i came across this beauty used to calculate the number of elements in a structuredefine structsizes sizeofs sizeofsvery useful as it is but can it be converted into an inline function or templateok arraysize would be a better name but this is legacy code no idea where it came from it is at least 15 years old so i pasted it as is,['c++'] +1133,jquery error option in ajax utility the documentation indicates that the error option function will make available xhr instance a status message string in this case always error and an optional exception object returned from the xhr instance book jquery in actionusing the following in the ajax call i was able to determine i had a parsererror and a timeout since i added the timeout option errorerror functionrequest errorwhat are other things you evaluate in the error option do you include the optional exception objectedit one of the answers indicates all the return errorslearning more about what is of value for debugging in the xhr instance and exception object would be helpfulthis is a complete ajax callajax type post url httpmyservercgibinbroker datatype text data service myservice program myprogram start start end end beforesend function loadingremoveclasshide timeout 50 error functionrequesterror loadingaddclasshide if error timeout errorappendthe request timed out please resubmit else errorappenderror error success functionrequest loadingaddclasshide var t eval request end success end ajax methodthanks for the input,['jquery'] +1139,what is a variables linkage and storage specifier when someone talks about a variables storage class specifier what are they talking aboutthey also often talk about variable linkage in the same context what is that,"['c++', 'c']" +1140,find a private field with reflection given this classclass foo want to find bar with reflection someattribute private string bar public string bigbar get return this bar i want to find the private item bar that i will mark with a attribute is that possible i have done this with properties where i have looked for an attribute but never a private member fieldwhat are the binding flags that i need to set to get the private fields,"['c#', '.net']" +1147,writing post data from one java servlet to another i am trying to write a servlet that will send a xml file xml formatted string to another servlet via a postnon essential xml generating code replaced with hello there stringbuilder sb new stringbuilder sbappendhello there url url new urltheservlet us url httpurlconnection connection httpurlconnectionurlopenconnection connectionsetrequestmethodpost connectionsetrequestpropertycontentlength sblength outputstreamwriter outputwriter new outputstreamwriterconnectiongetoutputstream outputwriterwritesbtostring outputwriterflush outputwriterclosethis is causing a server error and the second servlet is never invoked,['java'] +1151,is there anything wrong with returning default constructed values suppose i have the following codeclass some clasome class some function return some classthis seems to work pretty well and saves me the trouble of having to declare a variable just to make a return value but i do not think i have ever seen this in any kind of tutorial or reference is this a compilerspecific thing visual c or is this doing something wrong,['c++'] +1156,stdmap insert or stdmap find assuming a map where you want to preserve existing entries 20 of the time the entry you are inserting is new data is there an advantage to doing stdmapfind then stdmapinsert using that returned iterator or is it quicker to attempt the insert and then act based on whether or not the iterator indicates the record was or was not inserted,['c++'] +1163,force maven2 to copy dependencies into targetlib how do i get my projects runtime dependencies copied into the targetlib folder as it is right now after mvn clean install the target folder contains only my projects jar but none of the runtime dependencies,['java'] +1170,what is your favorite hotkey in eclipse i have been using visual studio with resharper for the past few years and have recently taken a gig at a java shop where we use eclipse googling for eclipse hotkeys has returned a bunch of top 10 hotkey posts but that is about it what are your favorite hotkeys and which are essential,['java'] +1172,does having many unused beans in a spring bean context waste significant resources my model layer is being used by a handful of different projects and i would like to use a single xml spring configuration file for the model regardless of which project is using itmy question is since not all beans are used in all projects am i wasting resources to any significant amount if there not being instantiated i am not too sure how lazy spring is about loading them since it is never been an issue until nowany ideas,['java'] +1173,what are the common undefinedunspecified behavior for c that you run into an example of unspecified behavior in the c language is the order of evaluation of arguments to a function it might be left to right or right to left you just do not know this would affect how fooc c or fooc c gets evaluatedwhat other unspecified behavior is there that can surprise the unaware programmer,['c'] +1176,what is the strict aliasing rule when asking about common undefined behavior in c souls more enlightened than i referred to the strict aliasing rulewhat are they talking about,['c'] +1180,how do i have a socket accept connections only from the localhost in java i have a java app not running in any application container which listens on a serversocket for connections i would like it to only accept connections which come from localhost currently after a connection is accepted it checks the peer ip and rejects it if it is not the loopback address but i know that peer ip addresses can be spoofed so if possible i would prefer to bind to a socket that only listens on the loopback interface is this possiblei have tried a few different things such as specifying 127001 as the local address when calling bind with no luck thanks in advancethank you all for your help i am embarrassed to admit that this was all my mistake our application listens on two different ports and i was binding one to the loopback interface but testing against the other when i actually try to telnet to the correct port everything works fine ie binding to 127001 does exactly what it is supposed toas for spoofing the loopback address you guys are right i should not have made it sound like the primary concern really the desired behavior is to only take local connections and binding to only the local interface is a more direct way of achieving that than accepting all connections and then closing nonlocal ones,['java'] +1181,passing php associative arrays to and from xml is there an easy way to marshal a php associative array to and from xml for example i have the following arrayitems array1 2 array item31 31 item32 32 isawesome true how would i turn it into something similar to the following xml in as few lines as possible then back againitems item1item item2item item item3 131item3 1 item3 232item3 2 isawesometrueisawesome itemitemsi do not really care if i have to change the array structure a bit or if the xml that comes out is different to the above example i have been trying to work with phps xmlreader and xmlwriter but the documentation is so poor and the code i have produced as a consequence looks nothing like what i feel it should look likexml somexmlwriterwritearraytoxmlitemsarray somexmlwriterwritexmltoarrayxmldoes it really have to be any harder than that to get a basic raw xml dump of a php array without writing my own custom classi try to avoid pear in addition to the configuration headaches i have had with it i have never stuck with any of the packages i have ever used from it,['php'] +1183,does several levels of base classes slow down a clastruct in c does having several levels of base classes slow down a class a derives b derives c derives d derives f derives g does multiple inheritance slow down a class,['c++'] +1187,is it safe to add delegates to events with keyword new one thing i am concerned with is that i thiscovered two ways of registering delegates to eventsonstuff thishandle onstuff new stuffeventhandlerthishandlethe first one is clean and it makes sense doing onstuff thishandle to unregister from the event but with the latter case should i do onstuff new stuffeventhandlerthishandle it feels like i am not removing anything at all since i am throwing in another stuffeventhandler reference does the event compare the delegate by reference i am concerned i could start a nasty memory pool here get me i do not have the reference to the new stuffeventhandler i previously registeredwhat is the downside of doing 1what is benefit of doing 2,"['c#', '.net']" +1193,what is the standard way to add and seconds to datetimetime in python given a datetimetime value in python is there a standard way to add an integer number of seconds to it so that 113459 3 113502 for examplethese obvious ideas do not work datetimetime11 34 59 3typeerror unsupported operand types for datetimetime and int datetimetime11 34 59 datetimetimedelta0 3typeerror unsupported operand types for datetimetime and datetimetimedelta datetimetime11 34 59 datetimetime0 0 3typeerror unsupported operand types for datetimetime and datetimetimein the end i have written functions like thisdef add secs to timetimeval secs to add secs timevalhour 3600 timevalminute 60 timevalsecond secs secs to add return datetimetimesecs 3600 secs 3600 60 secs 60i cannot help thinking that i am missing an easier way to do this thoughrelatedpython time timedelta equivalent,['python'] +1199,how do you bind in xaml to a dynamic xpath i have a list box that thisplays items based on an xpath querythis xpath query changes depending on the users selection elsewhere in the guithe xpath always refers to the same documentat the moment i use some c code behind to change the binding of the control to a new xpath expressioni would like instead to bind in xaml to an xpath then change the value of that xpath as requiredhow would i do that,['.net'] +1207,csv api for java can anyone recommend a simple api that will allow me to use read a csv input file do some simple transformations and then write ita quick google has found which looks promisingi just wanted to check what others are using before i couple myself to this api,['java'] +1209,which is the best net xmlrpc library i need to communicate with an xmlrpc server from a net 20 client can you recommend any librariesedit having tried xmlrpcnet i like the way it generates dynamic proxies it is very neat unfortunately as always things are not so simple i am accessing an xmlrpc service which uses the unorthodox technique of having object names in the names of the methods like soobject1object2somemethodstring1this means i cannot use the attributes to set the names of my methods as they are not known until runtime if you start trying to get closer to the raw calls xmlrpcnet starts to get pretty messyso anyone know of a simple and straightforward xmlrpc library thatll just let me do pseudocodex new xmlrpchost portxmakecallmethodname arg1i had a look at a thing by michael somebody on codeproject but there are no unit tests and the code looks pretty direunless someone has a better idea looks like i am going to have to start an open source project myself,['.net'] +1215,php getdata automatically being declared as variables take this codephpif isset postaction empty postaction action postactionif action echo actionelse echo no variableand then access the file with actiontestis there any way of preventing action from automatically being declared by the get other than of course adding isset getactionwhy would i want the variable to be declared for me,['php'] +1218,farseer physics tutorials help files is there a tutotial or help file suitable for a beginner c programmer to use,['c#'] +1224,css margin collapsing so essentially does margin collapsing occur when you do not set any margin or padding or border to a given div element,['css'] +1225,how does c figure out the hash code for an object this question comes out of the thiscussion on tuplesi started thinking about the hash code that a tuple should have what if we will accept keyvaluepair class as a tuple it does not override the gethashcode method so probably it would not be aware of the hash codes of it is children so runtime will call objectgethashcode which is not aware of the real object structurethen we can make two instances of some reference type which are actually equal because of the overloaded gethashcode and equals and use them as children in tuples to cheat the dictionarybut it does not work runtime somehow figures out the structure of our tuple and calls the overloaded gethashcode of our classhow does it work whats the analysis made by objectgethashcode can it affect the performance in some bad scenario when we use some complicated keys probably impossible scenario but stillconsider this code as an examplenamespace csharp tricks class program class myclass int keyvalue int someinfo public myclassint key int info keyvalue key someinfo info public override bool equalsobject obj myclass other obj as myclass if other null return false return keyvalueequalsotherkeyvalue public override int gethashcode return keyvaluegethashcode static void mainstring args dictionaryobject object dict new dictionaryobject object dictaddnew keyvaluepairmyclassobjectnew myclass1 1 1 1 here we get the exception an item with the same key was already added but how did it figure out the hash code dictaddnew keyvaluepairmyclassobjectnew myclass1 2 1 1 return update i think i have found an explanation for this as stated below in my answer the main outcomes of it arebe careful with your keys and their hash codes for complicated dictionary keys you must override equals and gethashcode correctly,['c#'] +1236,iphone programming impressions opinions i have been programming in c and a few other languages for many years mainly for windows and linux but also embedded platforms recently started to do some iphone programming as a side project so i am using apple platforms for the first time since my apple ii days i am wondering what other developers that are coming to mac osx xcode and iphone sdk think here are my impressions so farmac osx very confusing i tend to end up with too many open windows and do not know whats where luckily there is the birds eye view without it i would be lost with the shell at least there is all the familiar stuff so that helps me a lotxcode does not feel as good as visualstudio or eclipse the two environments i am familiar with i think i could get used to it but i am wondering if apple wouldnt be better off with eclipse before i found the setting where all the windows are stuck together i hated it now i can tolerate itiphone sdk strange indeed i understand apples desire to control their environment but in this day and age it just seems a little sleazy and they are missing out on so much by destroying developer goodwillobjectivec i have known about it for years but never even took a look at it the syntax is offputting but i am actually very intrigued by the language i think it is an interesting third leg between c and c both of which i like a lot is there any chance objc will break out of the mac sandbox due to the uptick in the popularity of apple technologycurious to read your thoughtsandrew,"['c#', 'c++', 'iphone', 'objective-c']" +1238,jquery menu and aspnet sitemap is it possible to use an aspnet websitemap with a jquery superfish menu if not are there any standards based browser agnostic plugins available that work with the websitemap file,"['asp.net', 'jquery']" +1244,how to generate all permutations of a list in python how do you generate all the permutations of a list in python independently of the type of elements in that listfor examplepermutationspermutations11permutations1 21 22 1permutations1 2 31 2 31 3 22 1 32 3 13 1 23 2 1editeliben pointed to a solution that is similar to mine although simpler so i am choosing it as the accepted answer although python 26 has a builtin solution in the itertools moduleimport itertoolsitertoolspermutations1 2 3,['python'] +1248,any good sql anywhere database schema comparison tools are there any good database schema comparison tools out there that support sybase sql anywhere version 10 i have seen a litany of them for sql server a few for mysql and oracle but nothing that supports sql anywhere correctly i tried using db solo but it turned all my nonunique indexes into unique ones and i did not see any options to change that,['sql'] +1250,c test if string is a guid without throwing exceptions i want to try to convert a string to a guid but i do not want to rely on catching exceptions for performance reasons exceptions are expensivefor usability reasons the debugger pops up for design reasons the expected is not exceptionalin other words the codepublic static boolean trystrtoguidstring s out guid value try value new guids return true catch formatexception value guidempty return false is not suitablei would try using regex but since the guid can be parenthesis wrapped brace wrapped none wrapped makes it hard additionally i thought certain guid values are invalidupdate 1christiank had a good idea to catch only formatexception rather than all changed the questions code sample to include suggestionupdate 2why worry about thrown exceptions am i really expecting invalid guids all that often the answer is yes that is why i am using trystrtoguid i am expecting bad dataexample 1 namespace extensions can be specified by appending a guid to a folder name i might be parsing folder names checking to see if the text after the final is a guidcprogram filescprogram filesoldcuserscusersoldcusermanagerce7f5aa5683243febae180d14cd8f6cwindowscwindowsoldexample 2 i might be running a heavily used webserver wants to check the validity of some posted back data i do not want invalid data tying up resources 23 orders of magnitude higher than it needs to beexample 3 i might be parsing a search expression entered by a user if they enter guids i want to process them specially such as specifically searching for that object or highlight and format that specific search term in the response textupdate 3 performance benchmarkstest converting 10 good guids and 10 bad guidscatch formatexception 10 good 63668 ticks 10 bad 6435609 ticksregex prescreen with trycatch 10 good 637633 ticks 10 bad 717894 tickscom interop clsidfromstring 10 good 126120 ticks 10 bad 23134 ticksps i should not have to justify a question,['c#'] +1260,what are indexes and how can i use them to optimize queries in my database i am maintaining a pretty sizable application and database and am noticing some poor database performance in a few of our stored proceduresi always hear that adding an index can be done to help performance i am certainly no dba and i do not understand what indexes are why they help and how to create themi basically need an indexes 101 can anyone give me resources so that i can learn,['sql'] +1265,net stringformat to add commas in thousands place for a number i want to add a comma in the thousands place for a number stringformat,"['c#', '.net']" +1271,what is your favorite visual studio addinsetting what addinsetting in visual studio can you not live without which one improves your productivity or fixes something you cannot stand in visual studio why is it your favoritemy favorite is aspx edit helper because it does really improve my productivity when working with aspnet applications what it does is provide a quick way to type out server side controls it automatically fills in runatserver and id and puts your cursor in between the quotes of id so you can type it inhere is a summarized list of all the plugins thiscussed so faraspx edit helper snippets for editing aspnetresharper fast refactoringpower commandsreflectorghostdoc generates xml commentsvisual assist xrock scrolltestdrivennetncoverankhsvn svn integrationviemu vim emulationvisualsvn svn integrationtheme generatorskype addinxml explorerresource refactoringlinq2sql debugger visualizer easily debug linq2sqlvisual studio file explorervisual studio window managertfs powertoysexpression tree visualizerstylecopregions managerregioneratecode keep manage code snippets from anywherecr documentordxcore community pluginsnunitcoderush xpressjslintnunit for vs nunit integrationinstant gratification tells you how awesome your code isentrian source search a code search addin find in files on steroidsgoanna static analysis for ccstudiotoolsusysware dpack code browser fast code navigation,['.net'] +1276,standard concise way to copy a file in java it has always bothered me that the only way to copy a file in java involves opening streams declaring a buffer reading in one file looping through it and writing it out to the other steam the web is littered with similar yet still slightly different implementations of this type of solutionis there a better way that stays within the bounds of the java language meaning does not involve execing os specific commands perhaps in some reliable open source utility package that would at least obscure this underlying implementation and provide a one line solution,['java'] +1280,internalsvisibleto attribute is not working i am trying to use the internalsvisibleto assembly attribute to make my internal classes in a net class library visible to my unit test project for some reason i keep getting an error message that saysmyclassname is inaccessible due to its protection levelboth assemblies are signed and i have the correct key listed in the attribute declaration any ideas,['.net'] +1281,how can i get source and variable values in ruby tracebacks heres the last few frames of a typical ruby on rails tracebackand here are the last few frames of a typical nevow traceback in pythonit is not just the web environment either you can make similar comparisons between ipython and irb how can i get more of these sorts of details in ruby,['ruby'] +1282,aspnet treeview and selecting the selected node how do i capture the event of the clicking the selected node of a treeviewit does not fire the selectednodechanged since the selection has obviously not changed but then what event can i catch so i know that the selected node was clickedupdatewhen i have some time i am going to have to dive into the bowels of the treeview control and dig out what and where it handles the click events and subclass the treeview to expose a new event onselectednodeclickedi will probably do this over the christmas holidays and i will report back with the resultsupdatei have come up with a solution below that subclasses the treeview control,['asp.net'] +1291,best way to extract a timezone from a mail date header in java i need to store the timezone an email was sent from which is the best way to extract it from the emails date header an rfc822 date and what is the recommended format to store it in the database i am using hibernate,['java'] +1294,best way to get started in setting up mono for aspnet on mac i have recently gained access to a mac i am wondering if anyone has any tipsadvice for setting up mono on a mac for development and execution of aspnet most resources point to linux implementations which tend to differ a lot from the way macs do things any tips or advice would be helpful,['asp.net'] +1300,how to simulate memory allocation errors my c application uses 3rd libraries which do their own memory managementin order to be robust my application has code to deal with failures of library functions due to lack of free memoryi would like to test this code and for this i need to simulate failures due to lack of memorywhat tools are recommended for thismy environment is linuxgcc,['c'] +1302,php gd imagecreatefromstring how to get the image dimensions normally i use imagecreatefromjpeg and then getimagesize but with firefox 3 i need to go round this different so now im using imagecreatefromstring but how do i retreive the image dimensions now,['php'] +1304,in aspnet how you get the physcial file path when httpcontextcurrent is null i am working with dotnetnukes scheduler to schedule tasks and i am looking to get the physical file path of a email template that i created the problem is that httpcontext is null because the scheduled task is on a different thread and there is not http request how would you go about getting the files physical path,"['.net', 'asp.net']" +1306,rails and gmail smtp how to use a custom from address i have got my rails 21 app setup to send email via gmail however whenever i send an email no matter what i set the from address to in my actionmailer the emails always come as if sent from my gmail email address is this a security restriction they have put in place at gmail to stop spammers using their smtpnote i have tried both of the following methods within my actionmailer just in casefrom from,['ruby-on-rails'] +1308,what are the bigger hurdles to overcome migrating from winforms to wpf i have been developing winforms applications in c for a few years now and have been interested in moving future development toward wpf mainly because of the positive things i have been hearing about it but i am wondering what sort of hurdles others have had to overcome as they migrated to wpf was there a significant hit to your productivity or any particular issues which you found challenging,['c#'] +1322,developing ms word addin anyone knows of a good tool for developing addins for word in nethopefully something that supports both office 2003 and 2007thanks,['.net'] +1325,should domain objects and simple javabeans be unit tested should simple javabeans that have only simple getters and setters be unit tested what about beans with some logic in getters and setters,['java'] +1326,how to configure aspnet process to run under a domain account i would like to configure aspnet process to run under an account with domain credentialsmy requirement is to access some files on a network sharewhat are the steps for this is there any builtin account i can use,"['.net', 'asp.net']" +1327,how can i detect using php if the machine has oracle oci8 andor pdo oci installed how can i detect using php if the machine has oracle oci8 andor pdo oci installedi am working on a php project where some developers such as myself have it installed but there is little need for the themers to have it how can i write a quick function to use in the code so that my themers are able to work on the look of the site without having it crash on them,['php'] +1333,phpini smtp how do you pass username password my isp account requires that i send a username password for outbound smtp mail how do i get php to use this when executing phpmail the phpini file only contains entries for the server smtp and from sendmail from,['php'] +1334,is static metaprogramming possible in java i am a fan of static metaprogramming in c i know java now has generics does this mean that static metaprogramming ie compiletime program execution is possible in java if so can anyone recommend any good resources where one can learn more about it,['java'] +1342,python when to use file vs open whats the difference between file and open in python when should i use which one say i am in 25,['python'] +1344,what is the cost of using a pointer to member function vs a switch i have the following situationclass apublic aint whichfoo int foo1 int foo2 int foo3 int callfoo cals one of the foos depending on the value of whichfooin my current implementation i save the value of whichfoo in a data member in the constructor and use a switch in callfoo to decide which of the foos to call alternatively i can use a switch in the constructor to save a pointer to the right foon to be called in callfoo my question is which way is more efficient if an object of class a is only constructed once while callfoo is called a very large number of times so in the first case we have multiple executions of a switch statement while in the second there is only one switch and multiple calls of a member function using the pointer to it i know that calling a member function using a pointer is slower than just calling it directly does anybody know if this overhead is more or less than the cost of a switchclarification i realize that you never really know which approach gives better performance until you try it and time it however in this case i already have approach 1 implemented and i wanted to find out if approach 2 can be more efficient at least in principle it appears that it can be and now it makes sense for me to bother to implement it and try it oh and i also like approach 2 better for aesthetic reasons i guess i am looking for a justification to implement it,['c++'] +1346,thisplaying code in blog posts what libraries andor packages have you used to create blog posts with code blocks having a javascript library that would support line numbers and indentation is ideal,['javascript'] +1347,which css tag creates a box like this with title i want to create a box like this with titlecan any one please let me know if there is a default css tag to do this or do i need to create my custom style,"['html', 'css']" +1350,javascript curry what are the practical applications i do not think i have grokked currying yet i understand what it does and how to do it i just cannot think of a situation i would use itwhere are you using currying in javascript or where are the main libraries using it dom manipulation or general application development examples welcomeedit one of the answers mentions animation functions like slideup fadein take an element as an arguments and are normally a curried function returning the high order function with the default animation function builtin why is that better than just applying the higherup function with some defaultsoh and are there any drawbacks to using itcheersedit as requested here are some good resources on javascript curryingcrockford douglas 2008 javascript the good parts javascripttakes a detour into ml so skip the whole section from a crash course in ml and start again at how to write curried javascript closures for dummieshow do javascript closures work mr resig on the money as per usuali will add more as they crop up in the commentseditthanks for the answersso currying and partial application in general are convenience techniquesif you are frequently refining a highlevel function by calling it with same configuration you can curry or use resigs partial the higherlevel function to create simple concise helper methodscheers,['javascript'] +1351,performance penalty for working with interfaces in c is there a runtime performance penalty when using interfaces abstract base classes in c,['c++'] +1353,get performance counter instance name w3wpxx from aspnet worker process id i would like to thisplay some memory statistics working set gcs etc on a web page using the netprocess performance counters unfortunately if there are multiple application pools on that server they are differentiated using an index 1 2 etc but i do not know how to match a process id which i have to that xx index is there a programmatic way from an aspnet web page,['asp.net'] +1354,create anonymous object by reflection in c is there any way to create c 30 anonymous object via reflection at runtime in net 35 i would like to support them in my serialization scheme so i need a way to manipulate them programmaticallyedited later to clarify the use casean extra constraint is that i will be running all of it inside a silverlight app so extra runtimes are not an option and not sure how generating code on the fly will work,['c#'] +1355,pointer vs reference what would be better practice when giving a function the original variable to work withunsigned long x 4void func1unsigned long val val 5 func1xorvoid func2unsigned long val val 5func2xiow is there any reason to pick one over another,['c++'] +1358,simple web live chat software lamp stack that integrates with jabberaim i have looked for this a few times in the past to no avail i would like a simple phpajax web chat interface that and this is the critical part will interface with my im client pidgin via jabber or aim plugoo is almost what i want except it is hosted and flash based flashbased would be ok if not ideal but hosted is not note that i do not just need notifications but i want a user of the website who clicks live chat to get a chat interface and my im client allows me to interact with them this is super handy for those of us that want to provide live support to clients who do not use im,['php'] +1359,is a python dictionary an example of a hash table one of the basic data structures in python is the dictionary which allows one to record keys for looking up values of any type is this implemented internally as a hash table if not what is it,['python'] +1360,what is the best way to pack javascript code without getting perfomance flaws i am searching for a way to compress javascript code for the iphone is there a way to avoid using a lot of cpu time on the small and rather slow device,"['javascript', 'iphone']" +1367,how do you specify a port range for java sockets in java you can give the number zero as a single parameter for the socket or datagramsocket constructor java binds that socket to a free port then is it possible to limit the port lookup to a specific rangethanks in advanceroland,['java'] +1373,location of my pictures how do i programatically using c find out what the path is of my my pictures folder does this work on xp and vista,['c#'] +1374,how do i kill a process using vbnet or c i have a scenario where i have to check whether user has already opened microsoft word if he has then i have to kill the winwordexe process and continue to execute my code does any one have any straightforward code for killing a process using vbnet or c,['c#'] +1379,low java single process thread limit in red hat linux i am experiencing an issue on a test machine running red hat linux kernel version is 242137elsmp using java 16 160 02 or 160 04 the problem is once a certain number of threads are created in a single thread group the operating system is unwilling or unable to create any morethis seems to be specific to java creating threads as the c threadlimit program was able to create about 15k threads additionally this does not happen with a java 14 jvm it can create over 14k threads though they are obviously being handled differently with respect to the osin this case the number of threads it is cutting off at is a mere 29 threads this is testable with a simple java program that just creates threads until it gets an error and then prints the number of threads it created the error is a javalangoutofmemoryerror unable to create new native threadthis seems to be unaffected by things such as the number of threads in use by other processes or users or the total amount of memory the system is using at the time jvm settings like xms xmx and xss do not seem to change anything either which is expected considering the issue seems to be with native os thread creationthe output of ulimit a is as followscore file size blocks c 0data seg size kbytes d unlimitedfile size blocks f unlimitedmax locked memory kbytes l 4max memory size kbytes m unlimitedopen files n 1024pipe size 512 bytes p 8stack size kbytes s 10240cpu time seconds t unlimitedmax user processes u 7168virtual memory kbytes v unlimitedthe user process limit does not seem to be the issue searching for information on what could be wrong has not turned up much but this post seems to indicate that at least some red hat kernels limit a process to 300 mb of memory allocated for stack and at 10 mb per thread for stack it seems like the issue could be there though it seems strange and unlikely as welli have tried changing the stack size with ulimit s to test this but any value other than 10240 and the jvm does not start with an error oferror occurred during initialization of vmcannot create vm thread out of system resourcesi can generally get around linux but i really do not know much about system configuration and i have not been able to find anything specifically addressing this kind of situation any ideas on what system or jvm settings could be causing this would be appreciatededits running the threadlimit program mentioned by plinth there was no failure until it tried to create the 1529th threadthe issue also did not occur using a 14 jvm does occur with 160 02 and 160 04 jvms cannot test with a 15 jvm at the momentthe code for the thread test i am using is as followspublic class threadtest public static void mainstring pargs throws exception try keep spawning new threads forever while true new testthreadstart when out of memory error is reached print out the number of successful threads spawned and exit catch outofmemoryerror e systemoutprintlntestthreadcreate count systemexit1 static class testthread extends thread private static int create count 0 public testthread create count make the thread wait for eternity after being spawned public void run try sleepintegermax value even if there is an interruption dont do anything catch interruptedexception e if you run this with a 14 jvm it will hang when it cannot create any more threads and require a kill 9 at least it did for memore editit turns out that the system that is having the problem is using the linuxthreads threading model while another system that works fine is using the nptl model,['java'] +1380,curl equivalent in java i am tasked with writing an authentication component for an open source java app we have an inhouse authentication widget that uses https i have some example php code that accesses the widget which uses curl to handle the transfer my question is whether or not there is a port of curl to java or better yet what base package will get me close enough to handle the task updatethis is in a nutshell the code i would like to replicate in javacp curl initmy url https auth server authauthenticateasppt1unamept2passpt4fullcurl setoptcp curlopt url my urlcurl setoptcp curlopt returntransfer 1result curl execcpcurl closecpheath i think youre on the right track i think i am going to end up using httpsurlconnection and then picking out what i need from the response,"['java', 'php']" +1384,is there an anonymous generic tag in c like in java in java one can declare a variable parameterised by an unknown generic type which looks like thisfoo xis there an equivalent construct to this questionmark in c,['c#'] +1388,how do i get a decimal value when using the division operator in python for example the standard division symbol rounds to zero 4 10however i want it to return 004 what do i use,['python'] +1392,wait until any of future is done i have few asynchronous tasks running and i need to wait until at least one of them is finished in the future probably i will need to wait util m out of and tasks are finishedcurrently they are presented as future so i need something like blocks current thread until one of specified futures is done and returns it public static t futuret waitforanycollectionfuturet futures throws allfuturesfailedexceptionis there anything like this or anything similar not necessary for future currently i loop through collection of futures check if one is finished then sleep for some time and check again this looks like not the best solution because if i sleep for long period then unwanted delay is added if i sleep for short period then it can affect performancei could try using new countdownlatch1and decrease countdown when task is complete and do countdownawait but i found it possible only if i control future creation it is possible but requires system redesign because currently logic of tasks creation sending callable to executorservice is separated from decision to wait for which future i could also override t runnablefuturet abstractexecutorservicenewtaskforcallablet callableand create custom implementation of runnablefuture with ability to attach listener to be notified when task is finished then attach such listener to needed tasks and use countdownlatch but that means i have to override newtaskfor for every executorservice i use and potentially there will be implementation which do not extend abstractexecutorservice i could also try wrapping given executorservice for same purpose but then i have to decorate all methods producing futuresall these solutions may work but seem very unnatural it looks like i am missing something simple like waithandlewaitanywaithandle waithandlesin c are there any well known solutions for such kind of problemupdateoriginally i did not have access to future creation at all so there were no elegant solution after redesigning system i got access to future creation and was able to add countdownlatchcountdown to execution process then i can countdownlatchawait and everything works finethanks for other answers i did not know about executorcompletionservice and it indeed can be helpful in similar tasks but in this particular case it could not be used because some futures are created without any executor actual task is sent to another server via network completes remotely and completion notification is received,['java'] +1394,upload files directly to amazon s3 from aspnet application my aspnet mvc application will take a lot of bandwidth and storage space how can i setup an aspnet upload page so the file the user uploaded will go straight to amazon s3 without using my web servers storage and bandwidth,['asp.net'] +1403,c why would not a fullscreen winform app always cover the taskbar i am using windows vista and cnet 35 but i had my friend run the program on xp and has the same problemso i have a c program that i have running in the background with an icon in the systemtray i have a low level keyboard hook so when i press two keys ctrwindows in this case it will pull of the applications main form the form is set to be full screen in the combo key press even handlerthisformborderstyle formborderstylenonethiswindowstate formwindowstatemaximizedso it basically works when i hit ctrwindows it brings up the form no matter what program i have given focus to but sometimes the taskbar will still show up over the form which i do not want i want it to always be full screen when i hit that key comboi figure it has something to do with what application has focus originally but even when i click on my main form the taskbar sometimes stays there so i wonder if focus really is the problem it just seems like sometimes the taskbar is being stubborn and does not want to sit behind my programanyone have any ideas how i can fix thisedit more detailsi am trying to achieve the same effect that a web browser has when you put it into fullscreen mode or when you put powerpoint into presentation modein a windows form you do that by putting the border style to none and maximizing the window but sometimes the window would not cover the taskbar for some reason half the time it willif i have the main window topmost the others will fall behind it when i click on it which i do not want if the taskbar is hidden,"['c#', '.net']" +1404,how do i ignore ampersands in a sql script running from sql plus i have a sql script that creates a package with a comment containing an ampersand when i run the script from sql plus i am prompted to enter a substitute value for the string starting with how do i thisable this feature so that sql plus ignores the ampersand,['sql'] +1405,how to start idle python editor without using the shortcut on windows vista i am trying to teach komodo to fire up idle when i hit the right keystrokes i can use the exact path of the shortcut in start menu in the windows explorer location bar to launch idle so i was hoping komodo would be able to use it as well but giving this path to komodo causes it to say that 1 is returned this appears to be a failure as idle does not start upi thought i would avoid the shortcut and just use the exact path i go to the start menu find the shortcut for idle right click to look at the properties the target is grayed out but says python 252 the start in is set to cpython25 the open file location button is also grayed outhow do i find out where this shortcut is really pointing i have tried starting pythonexe and pythonwexe both in cpython25 but neither starts up idle,['python'] +1409,how do you use the ellipsis slicing syntax in python this came up in hidden features of python but i cannot see good documentation or examples that explain how the feature works,['python'] +1421,what is the difference between events with delegate handlers and those without what is the difference between thisthisbtnokclick new systemeventhandlerthisbtnok clickand thisthisbtnokclick thisbtnok clickthey both work the former is what visual studio defaults to when you use the snippets but it seems like it only ads extra verbiage or am i missing something,['c#'] +1426,how do i sort a varchar column in sql server that contains numbers i have a varchar column in a sql server 20 database that can contain either letters or numbers it depends on how the application is configured on the frontend for the customer when it does contain numbers i want it to be sorted numerically eg as 1 2 10 instead of 1 10 2 fields containing just letters or letters and numbers such as a1 can be sorted alphabetically as normal for example this would be an acceptable sort order1210abb1what is the best way to achieve this,['sql'] +1429,detect via javascript whether silverlight is installed is there a javascript function i can use to detect whether a specific silverlight version is installed in the current browseri am particularly interested in the silverlight 2 beta 2 version i do not want to use the default method of having an image behind the silverlight control which is just shown if the silverlight plugin does not loadedit from link provided in accepted answerinclude silverlightjs from silverlight sdksilverlightisinstalled20,['javascript'] +1432,how to do query autocompletionsuggestions in lucene i am looking for a way to do query autocompletionsuggestions in lucene i have googled around a bit and played around a bit but all of the examples i have seen seem to be setting up filters in solr we do not use solr and are not planning to move to using solr in the near future and solr is obviously just wrapping around lucene anyway so i imagine there must be a way to do iti have looked into using edgengramfilter and i realise that i would have to run the filter on the index fields and get the tokens out and then compare them against the inputted query i am just struggling to make the connection between the two into a bit of code so help is much appreciatedto be clear on what i am looking for i realised i was not being overly clear sorry i am looking for a solution where when searching for a term it would return a list of suggested queries when typing inter into the search field it will come back with a list of suggested queries such as internet international etc,['java'] +1434,short integers in python python allocates integers automatically based on the underlying system architecture unfortunately i have a huge dataset which needs to be fully loaded into memory so is there a way to force python to use only 2 bytes for some integers equivalent of c short,['python'] +1435,irretrievably destroying data in java is there anyway in java to delete data eg a variable value object and be sure it cannot be recovered from memory does assigning null to a variable in java delete the value from memory any ideas answers applicable to other languages are also acceptable,['java'] +1443,how to do saturating addition in c what is the best cleanest most efficient way to write saturating addition in cthe function or macro should add two unsigned inputs need both 16 and 32bit versions and return allbitsone 0xf or 0xf if the sum overflowstarget is x86 and arm using gcc 412 and visual studio for simulation only so a fallback implementation is ok there,['c'] +1447,whats the difference between int and int in c i am 90 sure i saw this answer on stackoverflow before in fact i had never seen the int syntax before seeing it here but no matter how i search i cannot find the previous post and it is driving me crazyit is possible that i have been eating the funny mushrooms by accident but if i am not can someone please point out the previous post if they can find it or reexplain it my stackoverflow searchfu is apparently too low,['c#'] +1450,is there a way to get jadclipse working with eclipse 34 i am a big fan of the jadclipse plugin and i would really like to upgrade to eclipse 34 but the plugin currently does not work are there any other programs out there that let you use jad to view source of code you navigate to from eclipse very useful when delving into ambiguous code in stack traces,['java'] +1451,is there an easy way to attach source in eclipse i am a big fan of the way visual studio will give you the comment documentation parameter names when completing code that you have written and also code that you are referencing various librariesassembliesis there an easy way to get inline javadocparameter names in eclipse when doing code complete or hovering over methods via plugin via some setting it is extremely annoying to use a lot of libraries as happens often in java and then have to go to the website or local javadoc location to lookup information when you have it in the source jars right there,['java'] +1453,what is the linq way to implodejoin a string array i have the following string arrayvar sa new string yabbadabbadooi can convert it to yabba dabba doo it using stringjoin but what is the supercool linq way of doing it the join extension method seems promising but for a novice like me very confusing,['.net'] +1458,naming a core assembly i know that this is somewhat subjective but i wonder if there is a generally accepted standard for naming assemblies which contain some core functionslet us say you got a larger projects with assemblies likecompanyproductwebcontrolsdllcompanyproductnetdllcompanyproductuserpagesdlland you have a bunch of core classes like the global error handler the global logging functionality etchow would such an assembly generally named here are some things i had in mindcompanyproductdllcompanyproductcoredllcompanyproductglobaldllcompanyproductadministrationdllnow while just pick one and go on will not cause armageddon i would still like to know if there is an accepted way to name those assemblies,['.net'] +1462,modifying existing net assemblies is there a way to modify existing net assemblies without resorting to 3rd party tools i know that postsharp makes this possible but i find it incredibly wasteful that the developler of postsharp basically had to rewrite the functionality of the whole systemreflection namespace in order to make existing assemblies modifiablesystemreflectionemit only allows the creation of new dynamic assemblies however all the builder classes used here inherit from the basic reflection classes eg typebuilder inherits from systemtype unfortunately there does not seem to be a way to coerce an existing dynamically loaded type into a type builder at least there is no official supported wayso what about unsupported does anyone know of backdoors that allow to load existing assemblies or types into such builder classesmind i am not searching for ways to modify the current assembly this may even be an unreasonable request but just to modify existing assemblies loaded from thisc i fear there is no such thing but i would like to ask anywayin the worst case one would have to resort to ildasmexe to thisassemble the code and then to ilasmexe for reassembly but there is no toolchain read il reader contained in net to work with il data or is thereediti have got no specific use case i am just interested in a generalpurpose solution because patching existing assemblies is a quite common task take obfuscators for example or profilers or aop libraries yes the latter can be implemented differently as i have said it seems incredibly wasteful to be forced to rewrite large parts of the already existing infrastructure in systemreflectionwedgeyoure right however there is no specific use case here i have modified the original question to reflect this my interest was sparked by another question where the asker wanted to know how he could inject the instructions pop and ret at the end of every method in order to keep lutz roeders reflector from reengineering the vb or c source codenow this scenario can be realized with a number of tools eg postsharp mentioned above and the reflexil plugin for reflector that in turn uses the cecil libraryall in all i am just not satisfied with the net frameworkjoelyes i am aware of this limitation thanks anyway for pointing it out since it is importantmarxidadthis seems like the only feasible approach however this would mean that youd still have to recreate the complete assembly using the builder classes right ie youd have to walk over the whole assembly manuallyhmm i will look into that,['.net'] +1463,what clrnet bytecode tools exist i am well aware of java tools for manipulating generating decompiling jvm bytecode asm cglib jad etc what similar tools exist for the clr bytecode do people do bytecode manipulation for the clr,['.net'] +1466,is mef a replacement for systemaddin possible duplicatechoosing between mef and maf systemaddin is the managed extensibility framework a replacement for systemaddin or are they complementary,['.net'] +1468,best practices of test driven development using c and rhinomocks in order to help my team write testable code i came up with this simple list of best practices for making our c code base more testable some of the points refer to limitations of rhino mocks a mocking framework for c but the rules may apply more generally as well does anyone have any best practices that they followto maximize the testability of code follow these ruleswrite the test first then the code reason this ensures that you write testable code and that every line of code gets tests written for itdesign classes using dependency injection reason you cannot mock or test what cannot be seenseparate ui code from its behavior using modelviewcontroller or modelviewpresenter reason allows the business logic to be tested while the parts that cannot be tested the ui is minimizeddo not write static methods or classes reason static methods are difficult or impossible to isolate and rhino mocks is unable to mock themprogram off interfaces not classes reason using interfaces clarifies the relationships between objects an interface should define a service that an object needs from its environment also interfaces can be easily mocked using rhino mocks and other mocking frameworksisolate external dependencies reason unresolved external dependencies cannot be testedmark as virtual the methods you intend to mock reason rhino mocks is unable to mock nonvirtual methods,['c#'] +1469,mysql results in php arrays or objects been using phpmysql for a little while now and i am wondering if there are any specific advantages performance or otherwise to using mysql fetch object vs mysql fetch assoc mysql fetch array,"['php', 'mysql']" +1470,how to do a rolling restart of a cluster of mongrels anybody know a nice way to restart a mongrel cluster via capistrano in a rolling style eg one mongrel at a time would be great to have a bit of wait time in there as well for each to let the mongrel load the rails app up as well i have done some searching and have not found too much so looking for help before i dive into the mongrel cluster gem myselfthanks,['ruby-on-rails'] +1472,what is the best way to run asynchronous jobs in a rails application i know there are several plugins that do asynchronous processing which one is the best one and whythe ones i know about arebackgroundrb,['ruby-on-rails'] +1474,turn an array of pixels into an image object with javas imageio i am currently turning an array of pixel values originally created with a javaawtimagepixelgrabber object into an image object using the following codepublic image getimagefromarrayint pixels int width int height memoryimagesource mis new memoryimagesourcewidth height pixels 0 width toolkit tk toolkitgetdefaulttoolkit return tkcreateimagemisis it possible to achieve the same result using classes from the imageio packages so i do not have to use the awt toolkittoolkitgetdefaulttoolkit does not seem to be 100 reliable and will sometimes throw an awterror whereas the imageio classes should always be available which is why i am interested in changing my method,['java'] +1477,is it possible to prevent stack allocation of an object and only allow it to be instantiated with new is it possible to prevent stack allocation of an object and only allow it to be instiated with new on the heap,['c++'] +1479,freeopen source test generator for java are there any libraries for java that can generate unit tests or unit test skeletons for existing code i am looking for something similar to pythoscope ideally it would generate code that follows junit4 or testng conventionsit looks like agitar does something like this but i am looking for something free,['java'] +1481,mysql search and replace some text in a field what mysql query will do a text search and replace in one particular field in a tableie search for foo and replace with bar so a record with a field with the value hello foo becomes hello bar,['mysql'] +1482,generic linq query predicate not sure if this is possible or if i am expressing correctly what i am looking for but i have the following piece of code in my library repeatedly and would like to practice some dry i have set of sql server tables that i am querying based on a simple usersupplied search field ala google i am using linq to compose the final query based on whats in the search string i am looking for a way to use generics and passed in lambda functions to create a reusable routine out of this string arrayofqueryterms getsthearrayvar somequery from q in datacontextmytable select qif arrayofquerytermslength 1 somequery somequerywheremytableentity e efieldnamestartswitharrayofqueryterms0else foreachstring queryterm in arrayofqueryterms if stringisnulloremptyqueryterm somequery somequery wheremytableentity e efieldnamecontainsqueryterm i was hoping to create a generic method with signature that looks something likeprivate iqueryablet getquery t mytableentity string arrayofqueryterms funct bool predicatei am using the same search strategy across all my tables so the only thing that really differs from usage to usage is the mytable mytableentity searched and the fieldname searched does this make sense is there a way with linq to dynamically pass in the name of the field to query in the where clause or can i pass in this as a predicate lambdae efieldnamecontainsquerytermi realize there a million and a half ways to do this in sql probably easier but i would love to keep everything in the linq family for this one also i feel that generics should be handy for a problem like this any ideas,"['c#', '.net', 'sql']" +1486,what are the advantages of using the c boost libraries so i have been reading through and it appears that the boost libraries get used a lot in practice not at my shop though why is this and what makes it so wonderful,['c++'] +1492,can anyone recommend a c stdmap replacement container maps are great to get things done easily but they are memory hogs and suffer from caching issues and when you have a map in a critical loop that can be badso i was wondering if anyone can recommend another container that has the same api but uses lets say a vector or hash implementation instead of a tree implementation my goal here is to swap the containers and not have to rewrite all the user code that relies on the mapupdate performance wise the best solution would be a tested map facade on a stdvector,['c++'] +1495,how to efficiently count the number of keysproperties of an object in javascript whats the fastest way to count the number of keysproperties of an object it it possible to do this without iterating over the object ie without doingvar count 0for k in myobj if myobjhasownpropertyk countfirefox did provide a magic count property but this was removed somewhere around version 4,['javascript'] +1497,resources and guides to ui virtualization in wpf ui virtualization is an awkward terminology that describes wpf ui controls that load and and thispose child elements on demand based on their visibility to reduce memory footprint listbox and listview use a class called virtualizingstackpanel by default to achieve higher performance i found this control which is really helpful a virtualized canvas which produces a scrollable canvas object that manages its children with a quadtree it produces some great results and can easily be tweaked to your needsare there any other guides or sample wpf controls that deal with this issue maybe generic ones that deal with dynamic memory allocation of gui objects in other languages and toolkits,['.net'] +1498,objections against java webstart since the release of adobe air i am wondering why java web start has not gained more attention in the past as to me it seems to be very similar but web start is available for a much longer timeis it mainly because of bad marketing from sun or are there more technical concerns other than the need of having the right jvm installed do you have bad experiences using web start if yes which what are you recommendations when using web start for thistributing applications,['java'] +1505,algorithm for counting the number of unique colors in an image looking for one that is fast enough and still graceful with memory the image is a 24bpp systemdrawingbitmap,['c#'] +1516,is it possible to subclass a c struct in c and use pointers to the struct in c code is there a side effect in doing thisc codestruct foo int kint ret fooconst struct foo f return fk c codeclass bar public foo int my bar return ret foo foothis there is an extern c around the c code and each code is inside its own compilation unitis this portable across compilers,"['c++', 'c']" +1521,is there a good tool for mysql that will help me optimise my queries and index settings i use mysql in a fairly complex web site php drivenideally there would be a tool i could use that would help me test the sql queries i am using and suggest better table indexes that will improve performance and avoid table scansfailing that something that will tell me exactly what each query is up to so i can perform the optimisation myselfedit a simple guide to understanding the output from explain would also be usefulthank you,['mysql'] +1528,best practices for reusing code between controllers in ruby on rails i have some controller methods i would like to share what is the best practice for doing this in ruby on rails should i create an abstract class that my controllers extend or should i create module and add it in to each controller below are the controller methods i want to sharedef driving directions address to paramsaddress to address from paramsaddress from map center paramsmap center start if we were not given a center point to start our map on let us create one if map center address to map center geokitgeocodersmultigeocodergeocodeaddress toll elsif map center address from map center geokitgeocodersmultigeocodergeocodeaddress fromll endenddef printer friendly starting point paramsstarting pointsplitcollecteeto f ne paramsnesplitcollecteeto f sw paramsswsplitcollecteeto f size paramssizesplitcollecteeto f address paramsaddress markers retrieve pointsneswsizefalse map initialize mapsw0sw1ne0ne1starting point0starting point1falsemarkerstrue address string addressend,"['ruby-on-rails', 'ruby']" +1531,when do i use the php constant php eol when is it a good idea to use php eoli sometimes see this in code samples of php does this handle dosmacunix endline issues,['php'] +1533,parsing xml with namespaces using jquery find i am trying to get the contents of a xml document element but the element has a colon in it is namethis line works for every element but the ones with a colon in the namethisfindgeolattexti assume that the colon needs escaping how do i fix this,"['javascript', 'jquery']" +1538,absolute url from base relative url in c i have a base url and a relative one otherpathhow to get the absolute url from this it is pretty straighforward using string manipulation but i would like to do this in a secure way using the uri class or something similarit is for a standard a c app not an aspnet one,"['c#', '.net']" +1544,is it a bad idea to reload routes dynamically in rails i have an application i am writing where i am allowing the administrators to add aliases for pages categories etc and i would like to use a different controlleraction depending on the alias without redirecting and i have found that render does not actually call the method i just renders the template i have tried a catch all route but i am not crazy about causing and catching a doublerender exception that gets thrown everytimethe solution for this i have come up with is dynamically generated routes when the server is started and using callbacks from the alias model to reload routes when an alias is createdupdateddestroyed here is the code from my routesrbaliasfindalleach do alias to addmapconnect alias to addname controller alias to addpage typecontroller action alias to addpage typeactionnavigation node id alias to addnavigation nodeidendi am using callbacks in my alias model as followsafter save rebuild routesafter destroy rebuild routesdef rebuild routesactioncontrollerroutingroutesreloadendis this against rails best practices is there a better solution,"['ruby-on-rails', 'ruby']" +1545,sql server real datatype what is the c equivalent what is the c equivalent to the sql server 2005 real type,['c#'] +1551,dropdownlist control with s for aspnet webforms can anyone recommend a dropdownlist control for aspnet 35 that can render option groups thanks,['asp.net'] +1561,gdi systemdrawingbitmap gives error parameter is not valid intermittently i have some c code in an aspnet application that does thisbitmap bmp new bitmap1184 1900and occasionally it throws an exception parameter is not valid now i have been googling around and apparently gdi is infamous for throwing random exceptions and lots of people have had this problem but nobody has a solution to it i have checked the system and it has plenty of both ram and swap spacenow in the past if i do an iisreset then the problem goes away but it comes back in a few days but i am not convinced i have caused a memory leak because as i say above there is plenty of ramswap freeanyone have any solutions,"['c#', 'asp.net']" +1564,migrations for java i use both ruby on rails and java i really enjoy using migrations when i am working on a rails project so i am wondering is there a migrations like tool for java if there is no such tool is it a good idea to use migrations as a tool to control a database used by a java project,"['java', 'ruby-on-rails']" +1570,how can i programmatically manipulate windows desktop icon locations several years back i innocently tried to write a little app to save my tactically placed desktop icons because i was sick of dragging them back to their locations when some event reset them i gave up after buring way too much time having failed to find a way to query much less save and reset my icons desktop positionanyone know where windows persists this info and if there is an api to set themthanksrichard,['c#'] +1582,can a web service return a stream i have been writing a little application that will let people upload download files to me i have added a web service to this applciation to provide the uploaddownload functionality that way but i am not too sure on how well my implementation is going to cope with large filesat the moment the definitions of the upload download methods look like this written using apache cxfboolean uploadfilewebparamname username string username webparamname password string password webparamname filename string filename webparamname filecontents byte filecontents throws uploadexception loginexceptionbyte downloadfilewebparamname username string username webparamname password string password webparamname filename string filename throws downloadexception loginexceptionso the file gets uploaded and downloaded as a byte array but if i have a file of some stupid size eg 1gb surely this will try and put all that information into memory and crash my serviceso my question is is it possible to return some kind of stream instead i would imagine this is not going to be terribly os independent though although i know the theory behind web services the practical side is something that i still need to pick up a bit of information oncheers for any inputlee,['java'] +1583,how do you retrieve a list of loggedinconnected users in net heres the scenarioyou have a windows server that users remotely connect to via rdp you want your program which runs as a service to know who is currently connected this may or may not include an interactive console sessionplease note that this is the not the same as just retrieving the current interactive useri am guessing that there is some sort of api access to terminal services to get this info,"['c#', '.net']" +1586,deterministic thispose of threadstatic objects the threadstatic attribute declares a static variable as uniqueperthreaddo you know an easy pattern to correctly thispose such variableswhat we used before threadstatic is a threadcontextmanager every thread was allocated a threadcontext which retained all threadspecific information we spawned some threads and let them work then when they all finished we thisposed of the threadcontentmanager which in turn thisposed all the contexts if they were ithisposablei do not see an immediate way to translate this pattern to threadstatic objects the objects will be thisposed of eventualy because the threads die and so nothing reference them however we prefer deterministic thispose whenever possibleupdatei do not really control the threads directly i am using microsoft ccr which has a threadpool that does tasks when all the tasks are done i am thisposing the thispatcher which holds the threadpool the thing is i do not get a chance to do anything at the end of a threads main function so i cannot thispose things manually at the end of a threads run can i access the threads static objects from outside the thread somehow,"['c#', '.net']" +1588,why does castle windsor hold onto transient objects recently i noticed my application appears to be eating memory that never gets released after profiling with clrprofiler i have found that the castle windsor container i am using is holding onto objects these objects are declared with the lifestyletransient attribute in the config xmli have found if i put an explicit call to iwindsorcontainerreleasehangingobject that it will drop its referencesthis is causing a problem though i was not expecting that with a transient lifestyle object castlewindsor would keep a reference and effectively create a leak it is going to be a rather mundane and error prone task going around inserting explicit release calls in all the appropriate placeshave you seen this problem and do you have any suggestions for how to get around it,['c#'] +1589,illustrating usage of the volatile keyword in c i would like to code a little program which visually illustrates the behavior of the volatile keyword ideally it should be a program which performs concurrent access to a non volatile static field and which gets incorrect behavior because of that adding the volatile keyword in the same program should fix the problemthat something i did not manage to achieve even trying several times enabling optimization etc i always get a correct behavior without the volatile keyworddo you have any idea about this topic do you know how to simulate such a problem in a simple demo app does it depend on hardware,"['c#', '.net']" +1590,how can i get jquery to perform a synchronous rather than asynchronous ajax request i have a javascript widget which provides standard extension points one of them is the beforecreate function it should return false to prevent an item from being created i have added an ajax call into this function using jquerybeforecreate function node targetnode type to jqueryget targetnodeid name encodetoinp0value function result if resultisok false alertresultmessage but i want to prevent my widget from creating the item so i should return false in the motherfunction not in the callback is there a way to perform a synchronized ajax request using jquery or any other api,"['javascript', 'jquery']" +1598,how can i access a mapped network drive with systemiodirectoryinfo i need to create a directory on a mapped network drive i am using a codedirectoryinfo targetdirectory new directoryinfopathif targetdirectory null targetdirectorycreateif i specify the path like servernamedirectory it all goes ok if i map the servernamedirectory as say drive z and specify the path like z it failsafter the creating the targetdirectory object vs shows in the debug mode that targetdirectoryexists false and trying to do targetdirectorycreate throws an exceptionsystemiodirectorynotfoundexception could not find a part of the path zhowever the same code works well with local directories eg cthe application is a windows service winxp pro sp2 net 2 running under the same account as the user that mapped the drive qwinsta replies that the users session is the session 0 so it is the same session as the services,"['c#', '.net']" +1602,why should not helpers have html in them i have heard that it is best not to actually have any html in your helpers my question is why not and furthermore if you were trying to generate an html list or something like that how can i avoid actual tagsthanksfrew,"['ruby-on-rails', 'ruby']" +1603,running subversion under apache and mod python my apache server runs on some nondefault notroot account when it tries to run a python script which in turn executes a subversion checkout command svn checkout fails with the following error messagesvn cannot open file rootsubversionservers permission deniedat the same time running that python script with subversion checkout command inside from command line under the same user account goes on perfectly wellapache server 226 with mod python 328 runs on fedora core 6 machinecan anybody help me out thanks a lot,['python'] +1616,how to prevent blank xmlns attributes in output from nets xmldocument when generating xml from xmldocument in net a blank xmlns attribute appears the first time an element without an associated namespace is inserted how can this be preventedexamplexmldocument xml new xmldocumentxmlappendchildxmlcreateelementroot whatevernamespace10xmldocumentelementappendchildxmlcreateelementlonerconsolewritelinexmlouterxmloutputroot xmlnswhatevernamespace10loner xmlns rootdesired outputroot xmlnswhatevernamespace10loner rootis there a solution applicable to the xmldocument code not something that occurs after converting the document to a string with outerxmlmy reasoning for doing this is to see if i can match the standard xml of a particular protocol using xmldocumentgenerated xml the blank xmlns attribute may not break or confuse a parser but it is also not present in any usage that i have seen of this protocol,"['c#', '.net']" +1618,advantages to using private static methods when creating a class that has internal private methods usually to reduce code duplication that do not require the use of any instance fields are there performance or memory advantages to declaring the method as staticexampleforeach xmlelement element in xmldocdocumentelementselectnodessample string first getinnerxmlelement first string second getinnerxmlelement second string third getinnerxmlelement thirdprivate static string getinnerxmlxmlelement element string nodename return getinnerxmlelement nodename nullprivate static string getinnerxmlxmlelement element string nodename string defaultvalue xmlnode node elementselectsinglenodenodename return node null defaultvalue nodeinnerxmlis there any advantage to declaring the getinnerxml methods as static no opinion responses please i have an opinion,['c#'] +1619,semantic merge tool background in my job we use svn c and visualstudio part of my task regularly involves global renames often i end up with a broken build after renaming something and then merging in changesthe question is there a solution out there that can look at my changes notice the global rename and then apply that to the edit that others have made while merging them inanother way to get much the same effect would be some sort of refactor log and then apply that to the incoming editsthe tool need not be perfect even if it just noted any references in their edits that referred to something that i have edited would be valuableedit i am aware of vss refactor tools what i am looking for is something that will allow me to after i have refactored my working copy apply the same refactorings to other peoples edits that i now need to merge inthe ideal solution would be to make sure there are no outstanding edits when i do the refactoring but that would prevent anyone else from getting anything done for the next week or more because they would have to sync every half hour or so for the next week,['c#'] +1621,will my index be used if all columns are not used i have an index on columns a b c d of table ti have a query that pulls from t with a b c in the where clausewill the index be used or will a separate index be needed that only includes a b c,['sql'] +1624,structure of projects in version control net specific this post is similar to this previously asked question i really want to set up my svn repository in ttb format but when creating a project in visual studio 2008 aspnetvbnet the structure created tends to be incompatible when considering the solution file project files folders for projects multiple projects within solutions etc does anyone have a script or procedure to take a newly created aspnet project and move it to a ttb format as painlessly as possiblelet me be more specific suppose i have a project that i am creating called stackoverflowisawesome i can put that into my local folder structure let us say that it is cworking when i create it vs creates cworkingstackoverflowisawesome and a whole bunch of subfolders bin app data etc but i want my repository structure to look likestackoverflowisawesome trunk bin app data tags branchesso is there a clean way to do this consistently or do i need to resort to constantly movingmodifying files and folders to make this work,"['.net', 'asp.net']" +1625,what are the different types of indexes what are the benefits of each what are the different types of indexes what are the benefits of eachi heard of covering and clustered indexes are there more where would you use them,['sql'] +1628,how to configure tomcat juli logging to roll log files i have a several webapps which use javautillogging tomcat 55 is configured to use the juli logger so that each webapp has its own log file the problem is that juli does not have properties for maximum file size and file count using juli the files will grow unbounded and only roll at the end of the day also an unlimited number of log files are retainedyou can see the filehandler properties on this page apache tomcat 55 documentationthere is no limit or count property the following lines do nothingorgapachejulifilehandlerlimit102400orgapachejulifilehandlercount5without changing the webapps is there a way to get unique log files for each application with some type of bounds on the log file sizesupdatethe solution i found was not use the juli logger at alljavautilloggingfilehandlerlimit102400javautilloggingfilehandlercount5 thanksgreg,['java'] +1629,does xslt have a split function i have a string in a node and i would like to split the string on and return the last item in the arrayfor example in the block belowa xslattribute namehref newpageaspxxslvalueof selectsomenode xslattribute link textai would like to split the somenode valueedit heres the vbnet that i use to load the xsl for my aspnet pagedim xsldocpath as string httpcontextcurrentservermappathapp datasomexsltxsldim myxsltsettings as new xsltsettingsdim myxmlresolver as new xmlurlresolvermyxsltsettingsenablescript truemyxsltsettingsenabledocumentfunction truemyxsldoc new xslcompiledtransformfalsemyxsldocloadxsldocpath myxsltsettings myxmlresolverdim mystringbuilder as new stringbuilderdim myxmlwriter as xmlwriter nothingdim myxmlwritersettings as new xmlwritersettingsmyxmlwritersettingsconformancelevel conformancelevelautomyxmlwritersettingsindent truemyxmlwritersettingsomitxmldeclaration truemyxmlwriter xmlwritercreatemystringbuilder myxmlwritersettingsmyxsldoctransformxmldoc argumentlist myxmlwriterreturn mystringbuildertostringupdate heres an example of splitting xml on a particular node,['.net'] +1630,how to have a label inherite a composites gc in swt i am writing an app and our designers want to use gradients for some of the backgrounds on a few of our composites i wrote the following codecompositeaddlistener swtpaint new listener public void handleevent event e gc gc egc rectangle rect compositegetclientarea color color1 new color thisplay 0 0 0 color color2 new color thisplay 255 255 255 gcsetforegroundcolor1 gcsetbackgroundcolor2 gcfillgradientrectangle rectx recty rectwidth rectheight true this draws the gradient fine on the composite but we have labelclabels canvases and links on top of the composite in these areas the background is just the plain gray you get when drawing an empty canvas i have tried forcing the labels to inherit the background like solabelsetbackgroundmodeswtinherit default swtinherit force does not work eitherbut this leaves me with the same default gray and no gradient behind the components on top of the composite any suggestions for getting the gradient to be the background of each elementi wouldnt be opposed to drawing the gradient onto a gc with an image supplied and then setting the background to that image however that method just has not been working at all composite or any of its elements also it is not possible for me to set the gradient individually to my knowledge we want the whole composite to be one uniform flowing gradient edit i uploaded an example upto twitpic herethanksbrian gianforcaro,['java'] +1633,sell me on const correctness so why exactly is it that it is always recommended to use const as often as possible it seems to me that using const can be more of a pain than a help in c but then again i am coming at this from the python perspective if you do not want something to be changed do not change it so with that said here are a few questionsit seems like every time i mark something as const i get an error and have to change some other function somewhere to be const too then this causes me to have to change another function somewhere else is this something that just gets easier with experienceare the benefits of using const really enough to compensate for the trouble if you do not intend on changing an object why not just not write code that does not change iti should note that at this point in time i am most focused on the benefits of using const for correctness and maintainability purposes although it is also nice to have an idea of the performance implicationsedit i am told that the correct term is const correctness so that is what the title is now,['c++'] +1635,whats the best way to read and parse a large text file over the network i have a problem which requires me to parse several log files from a remote machinethere are a few complications1 the file may be in use2 the files can be quite large 100mb3 each entry may be multilineto solve the inuse issue i need to copy it first i am currently copying it directly from the remote machine to the local machine and parsing it there that leads to issue 2 since the files are quite large copying it locally can take quite a whileto enhance parsing time i would like to make the parser multithreaded but that makes dealing with multilined entries a bit trickier the two main issues are1 how do i speed up the file transfer compression is transferring locally even neccessary can i read an in use file some other way2 how do i deal with multiline entries when splitting up the lines among threadsupdate the reason i didnt do the obvious parse on the server reason is that i want to have as little cpu impact as possible i do not want to affect the performance of the system im testing,"['c#', '.net']" +1636,too many pattern suffixes design smell i just found myself creating a class called instructionbuilderfactorymapfactory that is 4 pattern suffixes on one class it immediately reminded me of this design pattern facade patternis this a design smell should i impose a limit on this number i know some programmers have similar rules for other things eg no more than and levels of pointer indirection in call the classes seem necessary to me i have a fixed map from strings to factories something i do all the time the list is getting long and i want to move it out of the constructor of the class that uses the builders that are created by the factories that are obtained from the map and as usual i am avoiding singletons,['java'] +1639,what are the dangers of making a method virtual i have been doing some mocking with rhinomocks and it requires that mocked methods be made virtual this is fine except we have a custom framework which contains the methods that i want to mock which are currently not marked as virtuali cannot forsee any problem with making these methods virtual but i was wondering what are some potential dangers of making methods virtual that i should look out for,['c#'] +1643,whats the difference between a worker thread and an io thread looking at the processmodel element in the webconfig there are two attributesmaxworkerthreads25 maxiothreads25what is the difference between worker threads and io threads,['asp.net'] +1648,encapsulating sql in a named scope i was wondering if there was a way to use find by sql within a named scope i would like to treat custom sql as named scope so i can chain it to my existing named scopes it would also be good for optimizing a sql snippet i use frequently,"['sql', 'ruby-on-rails']" +1649,where does consolewriteline go in aspnet in a j2ee application like one running in websphere when i use systemoutprintln my text goes to standard out which is mapped to a file by the websphere admin consolein an aspnet application like one running in iis where does the output of consolewriteline go the iis process must have a stdin stdout and stderr but is stdout mapped to the windows version of devnull or am i missing a key concept herei am not asking if i should log there i use log4net but where does the output go my best info came from this thiscussion where they say consolesetout can change the textwriter but it still did not answer the question on what the initial value of the console is or how to set it in configoutside of runtime code,['asp.net'] +1650,which thistro of linux is best suited for java web apps there are so many linux thistributions to choose from what is the best linux flavor for a web hosting environment running primarilyapache http tomcat or jboss mysql and alfresco not necessarily all in the same instanceare there any significant differences in terms of ease of administration and configuration performance and stability for such applications etcwhat would you recommendthanksmike,"['java', 'mysql']" +1654,how can you automate firefox from c application start with the simplest task of capturing the url in firefox from a c application it appears using user32dll windows api functions will not work as is the approach for capturing the url within ie,['c#'] +1660,how can i read the rgb value of a given pixel in python if i open an image with openimagejpg how can i get the rgb values of a pixel if i have the coordinates of the pixelthen how can i do the reverse of this starting with a blank graphic write a pixel with a certain rgb valueit would be so much better if i did not have to download any additional libraries,['python'] +1664,initializing a static stdmap in c what is the right way of initializing a static map do we need a static function that will initialize it,['c++'] +1665,how unique is the php session id how unique is the php session id i got the impression from various things that i have read that i should not rely on two users never getting the same sessionid is not it a guid,['php'] +1666,vim extension via python is it possible to extend vim functionality via custom extension preferably written in pythonwhat i need ideally is custom command when in command mode egescdo thisdo that,['python'] +1668,div with overflowauto and a 100 wide table i hope someone might be able to help me here i have tried to simplify my example as best i cani have an absolutely positioned div which for this example i have made fill the browser window this div has the overflowauto attribute to provide scroll bars when the content is too big for the div to thisplaywithin the div i have a table to present some data and it is width is 100when the content becomes too large vertically i expect the vertical scroll bar to appear and the table to shrink horizontally slightly to accommodate the scroll bar however in ie7 what happens is the horizontal scroll bar also appears despite there still being enough space horizontally for all the content in the divthis is ie specific firefox works perfectlyfull source below any help greatly appreciatedtonydoctype html public w3cdtd xhtml 10 transitionalen html xmlnshead runatserver titletable sizing bugtitle style maxsize position absolute left 5px right 5px top 5px bottom 5px border 5px solid silver overflow auto styleheadbody form idform1 runatserver div idmaxsize pthis will be fine until such time as the vertical size forces a vertical scroll bar at this point i would expect the table to resize to now take into account of the new vertical scroll bar instead ie7 keeps the table the full size and introduces a horizontal scroll bar p table width100 cellspacing0 cellpadding0 border1 tbody tr tdatd tdbtd tdctd tddtd tdetd tdftd tdgtd tdhtd tditd tdjtd tdktd tdltd tdmtd tdntd tdotd tdptd tdqtd tdrtd tr tbody table presize the browser window vertically so this content does not fit any morep phellopphellopphellopphellopphellop phellopphellopphellopphellopphellop div formbodyhtmladded 031610 thought it might be interesting to point out that gwts source code points to this question in a comment q22hack20to20account20for20the20scrollpanelsancd1ctrcl48,['html'] +1669,how to resolve a lnk in c i need to find out the filedirectory name that a lnk is pointing to using cwhat is the simplest way to do thisthanks,"['c#', '.net']" +1672,listing all functions in a python module i have a python module installed on my system and i would like to be able to see what functionsclassesmethods are available in it i want to call the doc function on each one in ruby i can do something like classnamemethods to get a list of all the methods available on that class is there something similar in pythoneg something likefrom somemodule import fooprint foomethods or whatever is the correct method to call,['python'] +1673,writing xml files using xmltextwriter with iso88591 encoding i am having a problem writing norwegian characters into an xml file using c i have a string variable containing some norwegian text with letters like aa a i am writing the xml using an xmltextwriter writing the contents to a memorystream like thismemorystream stream new memorystreamxmltextwriter xmltextwriter new xmltextwriterstream encodinggetencodingiso88591xmltextwriterformatting formattingindentedxmltextwriterwritestartdocument start docthen i add my norwegian text like thisxmltextwriterwritecdatamynorwegiantextthen i write the file to thisk like thisfilestream myfile new filestreammypath filemodecreatestreamwriter sw new streamwritermyfilestreamposition 0streamreader sr new streamreaderstreamstring content srreadtoendswwritecontentswflushmyfileflushmyfileclosenow the problem is that in the file on this all the norwegian characters look funnyi am probably doing the above in some stupid way any suggestions on how to fix it,"['c#', '.net']" +1675,whats the difference between truncate and delete in sql i wrote up an answer to this question by mistake in response to a question about the difference between drop and truncate but i thought that it is a shame not to share so i will post my own answer to my own question is that even ethical edit if your answer is platform specific can you please indicate that,['sql'] +1677,data in a table with carriage return in sql server is it possible to store data with carriage return in a table and then retrieve it back again with carriage returneginsert into table values test1 test2test3test4when i retrieve it i get the message in a line test1 test2 test3 test4the carriage return is treated as a single characteris there way to get the carriage returns or its just the way its going to be storedthanks for the help guysedit i should have explained this before i get the data from the web development asp net and i just insert it into the table i might not be doing any data manipulation just inserti return the data to the app development c and may be some data or report vieweri do not want to manipulate on the data,['sql'] +1681,possible causes of java vm exception access violation when a java vm crashes with an exception access violation and produces an hs err pidxlog file what does that indicate the error itself is basically a null pointer exception is it always caused by a bug in the jvm or are there other causes like malfunctioning hardware or software conflictsedit there is a native component this is an swt application on win32,['java'] +1683,clientjs framework for unsaved data protection we have a typical web application that is essentially a data entry application with lots of screens some of which have some degree of complexity we need to provide that standard capability on making sure if the user forgets to click the save button before navigating away or closing their browser they get a warning and can cancel but only when there is unsaved or dirty datai know the basics of what i have got to do in fact i am sure i have done it all before over the years tie in to onbeforeunload track the dirty state of the page etc but before i embark on coding this yet again does anyone have some suggestions for libraries already out there free or otherwise that will help out,['javascript'] +1684,base constructor in c which gets called first which gets called first the base constructor or other stuff herepublic class myexceptionclass exception public myexceptionclastring message string extrainfo basemessage other stuff here,"['c#', '.net', 'asp.net']" +1689,is it possible to compile net il code to machine code i would like to thistribute my net programs without the net framework is it possible to compile a net program to machine code,['.net'] +1690,how do i test if another installation is already in progress assuming i am trying to automate the installation of something on windows and i want to try to test whether another installation is in progress before attempting install i do not have control over the installer and have to do this in the automation framework is there a better way to do this some win32 api than just testing if msiexec is runningupdate 2improved the previous code i had been using to just access the mutex directly this is a lot more reliableusing systemthreading summary wait up to a timeout for the msi installer service to become free summary returns returns true for a successful wait when the installer service has become free returns false when waiting for the installer service has exceeded the timeout returnspublic static bool waitforinstallerservicetobefreetimespan maxwaittime the msiexecute mutex is used by the msi installer service to serialize installations and prevent multiple msi based installations happening at the same time for more info vs85aspx const string installerservicemutexname global msiexecute try mutex msiexecutemutex mutexopenexistinginstallerservicemutexname systemsecurityaccesscontrolmutexrightssynchronize bool waitsuccess msiexecutemutexwaitonemaxwaittime false msiexecutemutexreleasemutex return waitsuccess catch waithandlecannotbeopenedexception mutex does not exist do nothing catch objectthisposedexception mutex was thisposed between opening it and attempting to wait on it do nothing return true,['c#'] +1693,why does java not have blockscoped variable declarations the following method does not work because the inner block declares a variable of the same name as one in the outer block apparently variables belong to the method or class in which they are declared not to the block in which they are declared so i therefore cannot write a short little temporary block for debugging that happens to push a variable in the outer scope off into shadow just for a momentvoid methodname int i 7 for int j 0 j 10 j int i j 2 almost every blockscoped language i have ever used supported this including trivial little languages that i wrote interpreters and compilers for in school perl can do this as can scheme and even c even plsql supports thiswhats the rationale for this design decision for javaedit as somebody pointed out java does have blockscoping whats the name for the concept i am asking about i wish i could remember more from those languagedesign classes,['java'] +1696,inotifypropertychanged property name hardcode vs reflection what is the best way to specify a property name when using inotifypropertychanged most examples hardcode the property name as an argument on the propertychanged event i was thinking about using methodbasegetcurrentmethodnamesubstring4 but am a little uneasy about the reflection overhead,['.net'] +1698,visual studio 2008 source control for small teams i work on a small web team where i am the only net developer currently using visual studio 2008 professional to build and maintain a few web applications i am about to start training another member of our team so we purchased him a copy of visual studio 2008 professional i have looked into visual source safe but i am dubious i do not like that is file system based ideally the system would work with sql server 2005 and plug into visual studio windows based solutions are the best because of the it environment of the organization i work forwhat are my options for a source control systemforgive me if the answer exists in another thread,['.net'] +1699,should trycatch go inside or outside a loop i have a loop that looks something like thisfor int i 0 i max i string mystring float mynum floatparsefloatmystring myfloatsi mynumthis is the main content of a method whose sole purpose is to return the array of floats i want this method to return null if there is an error so i put the loop inside a trycatch block like thistry for int i 0 i max i string mystring float mynum floatparsefloatmystring myfloatsi mynum catch numberformatexception ex return nullbut then i also thought of putting the trycatch block inside the loop like thisfor int i 0 i max i string mystring try float mynum floatparsefloatmystring catch numberformatexception ex return null myfloatsi mynumis there any reason performance or otherwise to prefer one over the otheredit the consensus seems to be that it is cleaner to put the loop inside the trycatch possibly inside its own method however there is still debate on which is faster can someone test this and come back with a unified answer,['java'] +1703,how do you compare structs for equality in c how do you compare two instances of structs for equality in standard c,['c'] +1708,jquery override form submit not working when submit called by javascript on a element i have got a page with a normal form with a submit button and some jquery which binds to the form submit event and overrides it with epreventdefault and runs an ajax command this works fine when the submit button is clicked but when a link with onclickdocumentformnamesubmit is clicked the event is not caught by the ajax form submit event handler any ideas why not or how to get this working without binding to all the a elements,"['javascript', 'jquery']" +1710,c lambda expressions or delegates as a properties or arguments i am looking to create an validationrule class that validates properties on an entity type object i would really like to set the name of the property to inspect and then give the class a delegate or a lambda expression that will be evaluated at runtime when the object runs its isvalid method does anyone have a snippet of something like this or any ideas on how to pass an anonymous method as an argument or propertyalso i am not sure if i am explaining what i am trying to accomplish so please ask questions if i am not being clear,['c#'] +1714,how do you version your projects i understand that microsoft uses this template when versioning their products majorminorbuildrevision major is changed when the developers want to show that there is a big change in the software and backward compatibility cannot be assumed maybe a major rewrite of the code is done minor number represents a significant enhancement with the intention of backward compatibility build number is a small change for example a recompilation of the same source revision is used to fix a security hole and should be fully interchangeable both build and revision are optional this information is based on msdn version class how do you version your projects and why do you version them this way,['.net'] +1716,java enum parameter in method i have a method lets sayprivate static string drawcellvalue int maxcelength string cellvalue string align and as you can notice i have a parameter called align inside this method i am going to have some if condition on whether the value is a left or right setting the parameter as string obviously i can pass any string value i would like to know if it is possible to have an enum value as a method parameter and if so howjust in case someone thinks about this i thought about using a boolean value but i do not really fancy it first how to associate truefalse with leftright ok i can use comments but i still find it dirty and secondly i might decide to add a new value like justify so if i have more than 2 possible values boolean type is definitely not possible to useany ideas,['java'] +1722,design time viewing for user control events i have create a winforms control that inherits from systemwindowsformsusercontroli have got some custom events on the control that i would like the consumer of my control to be able to see i am unable to actually get my events to show up in the events tab of the properties window during design time this means the only way to assign the events is to programmatically write myusercontrolmycustomevent new myusercontrolmycustomeventhandlereventhandlerfunctionthis is fine for me i guess but when someone else comes to use my usercontrol they are not going to know that these events exist unless they read the library docoyeah right i know the event will show up using intellisense but it would be great if it could show in the properties window too,['c#'] +1728,create cronjob with zend framework i am trying to write a cronjob controller so i can call one website and have all modules cronjobphp executed now my problem is how do i do thatwould curl be an option so i also can count the errors and successesupdatei guess i have not explained it enough what i want to do is have one file which i can call like from httpservercronjob and then make it execute every applicationmodulescontrollercronjobcontrollerphp or have another way of doing it so all the cronjobs are not at one place but at the same place the module is located this would offer me the advantage that if a module does not exist it does not try to run its cronjobnow my question is how would you execute all the modules cronjobcontroller or would you do it a completly different way so it still stays modularand i want to be able to giveout how many cronjobs ran successfully and how many did not,['php'] +1729,java text to speech engines overview i am now in search for a java text to speech tts framework during my investigations i have found several jsapi10partiallycompatible frameworks listed on jsapi implementations page as well as a pair of java tts frameworks which do not appear to follow jsapi spec mary sayitnow i have also noted that currently no reference implementation exists for jsapibrief tests i have done for freetts first one listed in jsapi impls page show that it is far from reading simple and obvious words examples abc blackboard other tests are currently in progressand here goes the question 6 actuallywhich of the javabased tts frameworks have you usedwhich ones by your opinion are capable of reading the largest wordbasewhat about their voice qualitywhat about their performancewhich nonjava frameworks with java bindings are there on the scenewhich of them would you recommendthank you in advance for your comments and suggestions,['java'] +1732,where can i find open source 2d bin packing algorithms i am looking for open source preferably c algorithms for 2d bin packing of rectangular and or irregular shapes i have found several papers on the subject but no code,['c++'] +1734,mysql and data file encryption is there a way to encrypt the data file that mysql uses i have a mysql server on an open machine and i would like to encrypt the data file so even if someone copies the data files they cannot read the datathanks,['mysql'] +1740,how to get the rgb values for a pixel on an image on the iphone i am writing an iphone application and need to essentially implement something equivalent to the eyedropper tool in photoshop where you can touch a point on the image and capture the rgb values for the pixel in question to determine and match its color getting the uiimage is the easy part but is there a way to convert the uiimage data into a bitmap representation in which i could extract this information for a given pixel a working code sample would be most appreciated and note that i am not concerned with the alpha value,['iphone'] +1743,or equals why use one over the other,['c#'] +1750,jquery get textarea text recently i have started playing with jquery and have been following a couple of tutorials now i feel slightly competent with using it it is pretty easy and i thought it would be cool if i were able to make a console on my webpage as in you press the key like you do in fps games etc and then have it ajax itself back to the server inorder to do stuffi originally thought the best way would be to just get the text inside the textarea and then split it or should i use the keyup event convert the keycode returned to an ascii character append the character to a string and send the string to the server then empty the stringi could not find any information on getting text from a textarea all i got was keyup information also how can i convert the keycode returned to an ascii character,"['javascript', 'jquery']" +1753,implementing multithreading in c code review greetingsi am trying to implement some multithreaded code in an application the purpose of this code is to validate items that the database gives it validation can take quite a while a few hundred ms to a few seconds so this process needs to be forked off into its own thread for each itemthe database may give it 20 or 30 items a second in the beginning but that begins to decline rapidly eventually reaching about 65k items over 24 hours at which point the application exitsi would like it if anyone more knowledgeable could take a peek at my code and see if there is any obvious problems no one i work with knows multithreading so i am really just on my own on this oneheres the code it is kinda long but should be pretty clear let me know if you have any feedback or advice thankspublic class itemvalidationservice summary the object to lock on in this class for multithreading purposes summary private static object locker new object summaryitems that have been validatedsummary private hashsetint validateditems summaryitems that are currently being validatedsummary private hashsetint validatingitems summaryremove an item from the index if its links are badsummary param nameidthe id of the itemparam public void validateitemint id lock locker if thisvalidateditemscontainsid thisvalidatingitemscontainsid threadpoolqueueuserworkitemsender thisvalidateid method private void validateint itemid lock locker thisvalidatingitemsadditemid timeconsuming routine to validate an item lock locker thisvalidatingitemsremoveitemid thisvalidateditemsadditemid method class,['c#'] +1756,c performance vs javac my understanding is that cc produces native code to run on a particular machine architecture conversely languages like java and c run on top of a virtual machine which abstracts away the native architecture logically it would seem impossible for java or c to match the speed of c because of this intermediate step however i have been told that the latest compilers hot spot can attain this speed or even exceed itperhaps this is more of a compiler question than a language question but can anyone explain in plain english how it is possible for one of these virtual machine languages to perform better than a native language,"['c#', 'java', 'c++']" +1758,calling cc from python what would be the quickest way to construct a python binding to a c or c libraryusing windows if this matters,"['c++', 'python', 'c']" +1760,how do i dictate the destination folder of a clickonce application how do i dictate the destination folder of a clickonce application,['c#'] +1763,why stackoverflow binds user actions dynamically with javascript checking the html source of a question i see for instancea idcommentslinkx classcommentslinkadd commentanoscriptnbspjavascript is needed to access commentsnoscriptand then in the javascript source setup our click eventsreadyfunction aidcommentslinkclickfunction commentsshowthisattridsubstrcommentslinklength it seems that all the user click events are binded this waythe downsides of this approach are obvious for people browsing the site with no javascript but what are the advantages of adding events dynamically whith javascript over declaring them directly,"['javascript', 'jquery']" +1765,existing standard style and coding standard documents the following have been proposed for an upcoming c projectc coding standards by sutter and alexandrescujsf air vehicle c coding standardsthe elements of c styleeffective c 3rd edition by scott meyersare there other choices or is the list above what be should used on a c projectsome related links,['c++'] +1771,making eclipse behave like visual studio i am doing some android dev and i much prefer visual studio but i will have to use eclipse for thishas anyone made a tool that switches eclipse to look and behave more like visual studio i mainly cannot stand its clippyesqe suggestions on how i should program yes i know i have not yet used that private field thanks eclipse or its incredibly lousy intellisensefor example in eclipse if i do not type this first its intellisense would not realize i want to look for locally scoped members also the tab to complete vs convention is drilled into my head and eclipse is enter to complete i could switch everything by hand but that would take hours and i was hoping someone had some sort of theme or something that has already done it,"['java', 'android']" +1783,c versus d is the d language a credible alternative to java and c what will it take to become a credible alternative should i bother learning it does it deserve evangelizingthe main reason i ask is that with the new c standard c0x almost here its clear to me that the language has gone well past the point of no return with respect to anyone ever understanding it i know that cc will never die but at some point we need to move on even cobol had its day and java has in many respects undone c so whats next does d fill the bill,"['java', 'c++', 'c']" +1788,are there any free ways to turn an html page into an image with net i want to take html including the text and images and turn it into one image containing everything is there a free way to do itthis is using net 35see alsoserver generated web screenshotswhat is the best way to create a web page thumbnail,"['.net', 'html']" +1789,why does not c have a garbage collector i am not asking this question because of the merits of garbage collection first of all my main reason for asking this is that i do know that bjarne stroustrup has said that c will have a garbage collector at some point in timewith that said why has not it been added there are already some garbage collectors for c is this just one of those easier said than done type things or are there other reasons it has not been added and would not be added in c11cross linksgarbage collectors for cedit just to clarify i understand the reasons why c did not have a garbage collector when it was first created i am wondering why the collector cannot be added in,['c++'] +1791,ruby isprime method 1 n 1on the net i found this piece of ruby code that works for and 0 that determines whether or not and is a prime from what i can tell it looks like play with regex but i have no idea how it works could someone tell me how it works,['ruby'] +1795,is it possible to include one css file in another is it possible to include one css file in another,['css'] +1797,debug pylons application through eclipse i have eclipse setup with pydev and love being able to debug my scriptsapps i have just started playing around with pylons and was wondering if there is a way to start up the paster server through eclipse so i can debug my webapp,['python'] +1801,can you create collapsible region like scopes in c within vs 2008 i miss it so much used it a lot in c can you do it in c,['c++'] +1804,how do i peek at the first two bytes in an inputstream should be pretty simple i have an inputstream where i want to peek at not read the first two bytes ie i want the current position of the inputstream to stil be at 0 after my peeking what is the best and safest way to do thisanswer as i had suspected the solution was to wrap it in a bufferedinputstream which offers markability thanks rasmus,['java'] +1809,creating my own iterators i am trying to learn c so forgive me if this question demonstrates a lack of basic knowledge you see the fact is i have a lack of basic knowledgei want some help working out how to create an iterator for a class i have createdi have a class shape which has a container of points i have a class piece which references a shape and defines a position for the shapepiece does not have a shape it just references a shapei want it to seem like piece is a container of points which are the same as those of the shape it references but with the offset of the pieces position addedi want to be able to iterate through the pieces points just as if piece was a container itself i have done a little reading around and have not found anything which has helped me i would be very grateful for any pointers,['c++'] +1810,using precompiled headers with cmake i have seen a few old posts on the net about hacking together some support for precompiled headers in cmake they all seem a bit allover the place and everyone has their own way of doing it what is the best way of doing it currently,['c++'] +1811,why is the fact that microsoft decided to support jquery such a big deal i do not see what all this fuss is about microsofts decision to support jquery within aspnet mvcthere were signs that openminded people are starting to have some say in the matters of marketing for a while now and even the way ms does business has started to change but at it is core it is still acting in response to customers requestsi for one do not know what to make of it except that it brings back to microsofts sphere of influence a very visible product,"['jquery', 'asp.net']" +1815,requesturlreferrer null in an aspx cnet page i am running framework v35 i need to know where the user came from since they cannot view pages without logging in if i have page a the page the user wants to view redirect to page b the login page the requesturlreferrer object is null background if a user is not logged in i redirect to the login page b in this scenario after login i would like to return them to the page they were requesting before they were forced to log inupdatea nice quick solution seems to beif user not logged in responseredirectmyloginpageaspxreturnurl requestservervariablesscript namethen just look at querystring on login page you forced them to and put the user where they were after successful login,"['c#', '.net']" +1819,dynamic sorting within sql stored procedures this is an issue that i have spent hours researching in the past it seems to me to be something that should have been addressed by modern rdbms solutions but as yet i have not found anything that really addresses what i see to be an incredibly common need in any web or windows application with a database backendi speak of dynamic sorting in my fantasy world it should be as simple as something likeorder by sortcol1 sortcol2this is the canonical example given by newbie sql and stored procedure developers all over forums across the internet why is not this possible they ask invariably somebody eventually comes along to lecture them about the compiled nature of stored procedures of execution plans in general and all sorts of other reasons why it is not possible to put a parameter directly into an order by clausei know what some of you are already thinking let the client do the sorting then naturally this offloads the work from your database in our case though our database servers are not even breaking a sweat 99 of the time and they are not even multicore yet or any of the other myriad improvements to system architecture that happen every 6 months for this reason alone having our databases handle sorting wouldnt be a problem additionally databases are very good at sorting they are optimized for it and have had years to get it right the language for doing it is incredibly flexible intuitive and simple and above all any beginner sql writer knows how to do it and even more importantly they know how to edit it make changes do maintenance etc when your databases are far from being taxed and you just want to simplify and shorten development time this seems like an obvious choicethen there is the web issue i have played around with javascript that will do clientside sorting of html tables but they inevitably are not flexible enough for my needs and again since my databases are not overly taxed and can do sorting really really easily i have a hard time justifying the time it would take to rewrite or rollmyown javascript sorter the same generally goes for serverside sorting though it is already probably much preferred over javascript i am not one that particularly likes the overhead of datasets so sue mebut this brings back the point that it is not possible or rather not easily i have done with prior systems an incredibly hack way of getting dynamic sorting it was not pretty nor intuitive simple or flexible and a beginner sql writer would be lost within seconds already this is looking to be not so much a solution but a complicationthe following examples are not meant to expose any sort of best practices or good coding style or anything nor are they indicative of my abilities as a tsql programmer they are what they are and i fully admit they are confusing bad form and just plain hackwe pass an integer value as a parameter to a stored procedure let us call the parameter just sort and from that we determine a bunch of other variables for example let us say sort is 1 or the defaultdeclare sortcol1 as varchar20declare sortcol2 as varchar20declare dir1 as varchar20declare dir2 as varchar20declare col1 as varchar20declare col2 as varchar20set col1 storagedatetimeset col2 vehicleidif sort 1 default sortbegin set sortcol1 col1 set dir1 asc set sortcol2 col2 set dir2 ascendelse if sort 2 reversed order default sortbegin set sortcol1 col1 set dir1 desc set sortcol2 col2 set dir2 descendyou can already see how if i declared more colx variables to define other columns i could really get creative with the columns to sort on based on the value of sort to use it it usually ends up looking like the following incredibly messy clauseorder by case dir1 when desc then case sortcol1 when col1 then storagedatetime when col2 then vehicleid end end desc case dir1 when asc then case sortcol1 when col1 then storagedatetime when col2 then vehicleid end end case dir2 when desc then case sortcol2 when col1 then storagedatetime when col2 then vehicleid end end desc case dir2 when asc then case sortcol2 when col1 then storagedatetime when col2 then vehicleid end endobviously this is a very stripped down example the real stuff since we usually have four or five columns to support sorting on each with possible secondary or even a third column to sort on in addition to that for example date descending then sorted secondarily by name ascending and each supporting bidirectional sorting which effectively doubles the number of cases yeah it gets hairy really quickthe idea is that one could easily change the sort cases such that vehicleid gets sorted before the storagedatetime but the pseudoflexibility at least in this simple example really ends there essentially each case that fails a test because our sort method does not apply to it this time around renders a null value and thus you end up with a clause that functions like the followingorder by null desc null storagedatetime desc blah blahyou get the idea it works because sql server effectively ignores null values in order by clauses this is incredibly hard to maintain as anyone with any basic working knowledge of sql can probably see if i have lost any of you do not feel bad it took us a long time to get it working and we still get confused trying to edit it or create new ones like it thankfully it does not need changing often otherwise it would quickly become not worth the troubleyet it did workmy question is then is there a better wayi am okay with solutions other than stored procedure ones as i realize it may just not be the way to go preferably i would like to know if anyone can do it better within the stored procedure but if not how do you all handle letting the user dynamically sort tables of data bidirectionally too with aspnetand thank you for reading or at least skimming such a long questionps be glad i did not show my example of a stored procedure that supports dynamic sorting dynamic filteringtextsearching of columns pagination via rownumber over and trycatch with transaction rollbacking on errors behemothsized does not even begin to describe themupdatei would like to avoid dynamic sql parsing a string together and running an exec on it defeats a lot of the purpose of having a stored procedure in the first place sometimes i wonder though if the cons of doing such a thing wouldnt be worth it at least in these special dynamic sorting cases still i always feel dirty whenever i do dynamic sql strings like that like i am still living in the classic asp worlda lot of the reason we want stored procedures in the first place is for security i do not get to make the call on security concerns only suggest solutions with sql server 2005 we can set permissions on a peruser basis if need be at the schema level on individual stored procedures and then deny any queries against the tables directly critiquing the pros and cons of this approach is perhaps for another question but again it is not my decision i am just the lead code monkey,['sql'] +1821,what does the comma operator do what does the following code do in ccif blah 5 do something,"['c++', 'c']" +1823,continuations in ruby has anyone ever done work to get ruby to do continuations like seaside on smalltalk,['ruby'] +1824,php code formatter beautifier and php beautification in general do you know any good tools for nicely formatting messy php code preferably a script for aptanaeclipse but a standalone tool will do too,['php'] +1825,search for text between delimiters in mysql i am trying to extract a certain part of a column that is between delimiterseg find foo in the followingtest esf foo barso in the above i would want to return foo but all the regexp functions only return truefalseis there a way to do this in mysql,['mysql'] +1826,interlocked equivalent on linux in a c linux app what is the simplest way to get the functionality that the interlocked functions on win32 provide specifically a lightweight way to atomically increment or add 32 or 64 bit integers,['c++'] +1828,how to prevent fgets blocks when file stream has no new data i have a popen function which executes tail f sometextfile aslong as there is data in the filestream obviously i can get the data through fgets now if no new data comes from tail fgets hangs i tried ferror and feof to no avail how can i make sure fgets does not try to read data when nothing new is in the file stream one of the suggestion was select since this is for windows platform select does not seem to work as anonymous pipes do not seem to work for it see this post,['c'] +1832,whileclause in tsql that loops forever i was recently tasked with debugging a strange problem within an ecommerce application after an application upgrade the site started to hang from time to time and i was sent in to debug after checking the event log i found that the sqlserver wrote 200 0 events in a couple of minutes with the message saying that a constraint had failed after much debugging and some tracing i found the culprit i have removed some unnecessary code and cleaned it up a bit but essentially this is itwhile exists select from shoppingcartitem where shoppingcartitempurchid purchidbeginselect top 1 tmpgfsid shoppingcartitemgfsid tmpquantity shoppingcartitemquantitytmpshoppingcartitemid shoppingcartitemshoppingcartitemidfromshoppingcartitem inner join goodsforsale on shoppingcartitemgfsid goodsforsalegfsidwhere shoppingcartitempurchid purchidexec errorcode spgoodsforsale reversereservations tmpgfsid tmpquantityif errorcode 0begingoto cleanupenddelete from shoppingcartitem where shoppingcartitemshoppingcartitemid tmpshoppingcartitemid rowcount is 1 after thisendfactsthere is only one or two records matching the first selectclauserowcount from the delete statement indicates that it has been removedthe whileclause will loop foreverthe procedure has been rewritten to select the rows that should be deleted into a temporary inmemory table instead so the immediate problem is solved but this really sparked my curiositywhy does it loop foreverclarification the delete does not fail rowcount is 1 after the delete stmt when debuggedclarification 2 it should not matter whether or not the select top clause is ordered by any specific field since the record with the returned id will be deleted so in the next loop it should get another recordupdate after checking the subversion logs i found the culprit commit that made this stored procedure to go haywire the only real difference that i can find is that there previously was no join in the select top 1 statement ie without that join it worked without any transaction statements surrounding the delete it appears to be the introduction of the join that made sql server more pickyupdate clarification brien pointed out that there is no need for the join but we actually do use some fields from the goodsforsale table but i have removed them to keep the code simply so that we can concentrate on the problem at hand,['sql'] +1837,hashset vs list performance it is clear that a search performance of the generic hashsett class is higher than of the generic listt class just compare the hashbased key with the linear approach in the listt classhowever calculating a hash key may itself take some cpu cycles so for a small amount of items the linear search can be a real alternative to the hashsettmy question where is the breakevento simplify the scenario and to be fair let us assume that the listt class uses the elements equals method to identify an item,['.net'] +1842,how do i call controllerview methods from the console in rails when i load scriptconsole some times i want play with the output of a controller or a view helper methodare there ways tosimulate a requestcall methods from a controller instance on said requesttest helper methods either via said controller instance or another way,['ruby-on-rails'] +1848,ides for c development on linux what are my options i tried monodevelop over a year ago but it was extremely buggy is the latest version a stable development environment,['c#'] +1849,should i provide a deep clone when implementing icloneable it is unclear to me from the msdn documentation if i should provide a deep or a shallow clone when implementing icloneable what is the preferred option,['.net'] +1850,how to detect a remote side socket close how do you detect if socketclose has been called on a socket on the remote side,['java'] +1851,can i trust php destruct method to be called in php5 is the destruct method guaranteed to be called for each object instance can exceptions in the program prevent this from happening,['php'] +1858,are there any open source projects using d domain driven design i am trying to understand the concepts behind d but i find it hard to understand just by reading books as they tend to thiscuss the topic in a rather abstract way i would like to see some good implementations of d in code preferably in care there any good examples of projects practicing d in the open source world,['c#'] +1861,java stringbuffer concatenation i am using stringbuffer in java to concat strings together like sostringbuffer str new stringbufferstrappendstring valuei would like to know if there is a method although i did not find anything from a quick glance at the documentation or some other way to add paddinglet me explain every time i append something to the string i want to add a space in the end like sostring foo string valuestrappendfoo and i have several calls to append and every time i want to add a space is there a way to set the object so that it will add a space automatically after each appendedit string inputstringbuffer query new stringbufferscanner scanner new scannersysteminscannerusedelimiterndo systemoutprintlnsql input scannernext if emptyinput queryappendinput if querytostringtrimendswith run query while inputequalsignorecaseexiti will use stringbuilder though as grom suggested but that is how the code looks right now,['java'] +1863,get class property name i have my winform application gathering data using databinding everything looks fine except that i have to link the property with the textedit using a stringmetextedit4databindingsaddnew systemwindowsformsbindingeditvalue memyclassbindingsource myclassproperty truethis works fine but if i change the class property name the compiler obviously will not warn me i would like to be able to get the property name by reflection but i do not know how to specify the name of the property i want i only know how to iterate among all the properties of the class any idea,['.net'] +1864,whats the canonical way to check for type in python what is the best way to check whether a given object is of a given type how about checking whether the object inherits from a given typelet us say i have an object o how do i check whether it is a str,['python'] +1868,are there any good free net network libraries ftp sftp ssh etc i am a bit surprised i have not found a good open source library for performing common network tasks there are a few very good commercial libraries but they are too expensive to use on an open source project anyone know of any,['.net'] +1872,is it feasible to create a rest client with flex i am starting a project using a restful architecture implemented in java using the new jaxrs standardwe are planning to develop the gui with a flex application i have already found some problems with this implementation using the httpservice component the response error codes headers accessany of you guys have some experience in a similar project is it feasible,['java'] +1873,add to right click application menu in taskbar in net most applications only have restore move size minimize maximize and close however ms sql offers extra options help customize view along those lines is it possible to add to the right click menu of an application in the task bar note i am not referring to an icon in the notification area next to the clock,['.net'] +1876,printing leading 0s in c i am trying to find a good way to print leading 0s such as 01001 for a zipcode while the number would be stored as 1001 what is a good way to do iti thought of using either case statementsif then to figure out how many digits the number is and then convert it to an char array with extra 0s for printing but i cannot help but think there may be a way to do this with the printf format syntax that is eluding me,['c'] +1884,persistent storage of encrypted data using net i need to store encrypted data few small strings between application runs i do not want the user to provide a passphrase every time she launches the application ie after all it goes down to storing securely the encryption keysi was looking into rsacryptoserviceprovider and using persistentkeyincsp but i am not sure how it works is the key container persistent between application runs or machine restarts if yes is it user specific or machine specific ie if i store my encrypted data in users roaming profile can i decrypt the data if the user logs on a different machineif the above does not work what are my options i need to deal with roaming profiles,['c#'] +1885,recommended gcc warning options for c other than wall what other warnings have people found useful,['c'] +1887,capturing video out of an opengl window in windows i am supposed to provide my users a really simple way of capturing video clips out of my opengl applications main window i am thinking of adding buttons andor keyboard shortcuts for starting and stopping the capture when starting i could ask for a filename and other options if any it has to run in windows xpvista but i also wouldnt like to close the linux door which i have so far been able to keep openthe application uses opengl fragment and shader programs the effects due to which i absolutely need to have in the eventual videosit looks to me like there might be even several different approaches that could potentially fulfill my requirements but i do not really know where i should startan encoding library with functions like startrecordingfilename stoprecording and captureframe i could call captureframe after every frame rendered or every secondthirdwhatever if doing so makes my program run slower it is not really a problema standalone external program that can be programmatically controlled from my application after all a standalone program that can not be controlled almost does what i need but as said it should be really simple for the users to operate and i would appreciate seamlessness as well my application typically runs fullscreen additionally it should be possible to thistribute as part of the installation package for my application which i currently prepare using nsisuse the windows api to capture screenshots framebyframe then employ for example one of the libraries mentioned here it seems to be easy enough to find examples of how to capture screenshots in windows however i would love a solution which does not really force me to get my hands superdirty on the winapi leveluse opengl to render into an offscreen target then use a library to produce the video i do not know if this is even possible and i am afraid it might not be the path of least pain anyway in particular i would not like the actual rendering to take a different execution path depending on whether video is being captured or not additionally i would avoid anything that might decrease the frame rate in the normal noncapture modeif the solution were free in either sense of the word then that would be great but it is not really an absolute requirement in general the less bloat there is the better on the other hand for reasons beyond this question i cannot link in any gplonly code unfortunatelyregarding the file format i cannot expect my users to start googling for any codecs but as long as also thisplaying the videos is easy enough for a basiclevel windows user i do not really care what the format is however it would be great if it were possible to control the compression quality of the outputjust to clarify i do not need to capture video from an external device like camcorder nor am i really interested in mouse movements even though getting them does not harm either there are no requirements regarding audio the application makes no noise whatsoeveri write c using visual studio 2008 for this very application also taking benefit of glut and glui i have a solid understanding regarding c and linking in libraries and that sort of stuff but on the other hand opengl is quite new for me so far i have really only learnt the necessary bits to actually get my job donei do not need a solution superurgently so feel free to take your time,['c++'] +1896,what is the syntax within c i have been learning about the basics of c but have not come across a good explanation of what this isvar l new liststringi do not know what the string is doing or if it is the list that is doing the magic i have also seen objects been thrown within the tagscan someone explain this to me with examples please,"['c#', '.net']" +1902,how do i specify the exit code of a console application in net i have a trivial console application in net it is just a test part of a larger application i would like to specify the exit code of my console application how do i do this,"['c#', '.net']" +1905,safehandle in c what is safehandle how does it differ from intptr when should i use one what are its advantages,"['c#', '.net']" +1908,php session data not being saved i have one of those i swear i did not touch the server situations i honestly did not touch any of the php scripts the problem i am having is that php data is not being saved across different pages or page refreshes i know a new session is being created correctly because i can set a session variable eg sessionfoo foo and print it back out on the same page just fine but when i try to use that same variable on another page it is not set is there any php functions or information i can use on my hosts server to see what is going onhere is an example script that does not work on my hosts server as of right nowphpsession startifisset sessionviews sessionviews sessionviews 1else sessionviews 1echo views sessionviewsecho pa hrefpage1phprefreshapthe views variable never gets incremented after doing a page refresh i am thinking this is a problem on their side but i wanted to make sure i am not a complete idiot firsthere is the phpinfo for my hosts server php version 447,['php'] +1911,python dependency injection framework is there a framework equivalent to guice for python,['python'] +1913,get timer ticks in python i am just trying to time a piece of code the pseudocode looks likestart get ticksdo long codeprint it took get ticks start secondshow does this look in pythonmore specifically how do i get the number of ticks since midnight or however python organizes that timing,['python'] +1914,get all items from thread queue i have one thread that writes results into a queuein another thread gui i periodically in the idle event check if there are results in the queue like thisdef queue get allq items while 1 try itemsappendqget nowait except empty e break return itemsis this a good way to do it editi am asking because sometimes the waiting thread gets stuck for a few seconds without taking out new resultsthe stuck problem turned out to be because i was doing the processing in the idle event handler without making sure that such events are actually generated by calling wxwakeupidle as is recommended,['python'] +1916,how to write an excel workbook to a memorystream in net how do i write an excel workbook to a memorystream without first saving it to the file systemall options within the microsoftofficeinteropexcelworkbook save options take a filename,['.net'] +1932,whats the best way to loop through a set of elements in javascript in the past and with most my current projects i tend to use a for loop like thisvar elements documentgetelementsbytagnamedivfor var i0 ielementslength i dosomethingelementsii have heard that using a reverse while loop is quicker but i have no real way to confirm thisvar elements documentgetelementsbytagnamediv length elementslengthwhilelength dosomethingelementslengthwhat is considered as best practice when it comes to looping though elements in javascript or any array for that matter,['javascript'] +1933,dynamically instantiate a ruby class similar to java how can this line in java be translated to ruby string classname javautilvector object o classfornameclassnamenewinstance thanks,"['java', 'ruby']" +1936,table column formatting i am trying to format a column in a table using a col element i can set backgroundcolor width etc but cannot set the fontweight why does not it worktable col stylefontweightbold backgroundcolorc col tr td1td td2td tr tr td3td td4td trtable,['css'] +1938,how to position one element relative to another with jquery i have a hidden div which contains a toolbarlike menui have a number of divs which are enabled to show the menu div when the mouse hovers over themis there a builtin function which will move the menu div to the top right of the active mouse hover div i am looking for something like menupositiontopright targetel,['jquery'] +1939,mathieremainder returns negative results why the net framework includes mathieremainderx y in addition to the standard mod operator what is this function really doing i dont understand the negative numbers that this producesexamplemathieremainder0 2 0mathieremainder1 2 1mathieremainder2 2 0mathieremainder3 2 1,['.net'] +1949,can you combine multiple images into a single one using javascript i am wondering if there is a way to combine multiple images into a single image using only javascript is this something that canvas will be able to do the effect can be done with positing but can you combine them into a single image for downloadupdate oct 1 2008thanks for the advice i was helping someone work on a jscss only site with jquery and they were looking to have some macos docklike image effects with multiple images that overlay each other the solution we came up with was just absolute positioning and using the effect on a parent div relatively positioned it would have been much easier to combine the images and create the effect on that single imageit then got me thinking about online image editors like picnik and wondering if there could be a browser based image editor with photoshop capabilities written only in javascript i guess that is not a possibility maybe in the future,['javascript'] +1956,raii vs exceptions the more we use raii in c the more we find ourselves with destructors that do nontrivial deallocation now deallocation finalization however you want to call it can fail in which case exceptions are really the only way to let anybody upstairs know of our deallocation problem but then again throwingdestructors are a bad idea because of the possibility of exceptions being thrown during stack unwinding stduncaught exception lets you know when that happens but not much more so aside from letting you log a message before termination there is not much you can do unless youre willing to leave your program in an undefined state where some stuff is deallocatedfinalized and some notone approach is to have nothrow destructors but in many cases that just hides a real error our destructor might for example be closing some raiimanaged db connections as a result of some exception being thrown and those db connections might fail to close this does not necessarily mean were ok with the program terminating at this point on the other hand logging and tracing these errors is not really a solution for every case otherwise we would have had no need for exceptions to begin with with nothrow destructors we also find ourselves having to create reset functions that are supposed to be called before destruction but that just defeats the whole purpose of raiianother approach is just to let the program terminate as it is the most predictable thing you can dosome people suggest chaining exceptions so that more than one error can be handled at a time but i honestly never actually seen that done in c and i have no idea how to implement such a thingso it is either raii or exceptions is not it i am leaning toward nothrow destructors mainly because it keeps things simpler but i really hope there is a better solution because as i said the more we use raii the more we find ourselves using dtors that do nontrivial thingsappendixi am adding links to interesting ontopic articles and thiscussions i have foundthrowing destructorsstackoverflow thiscussion on the problems with sehstackoverflow thiscussion on throwingdestructors thanks martin yorkjoel on exceptionsseh considered harmful clr exception handling which also touches on exception chainingherb sutter on stduncaught exception and why it is not as useful as you thinkhistorical thiscussion on the matter with interesting participants longstroustrup explaining raiiandrei alexandrescus scope guard,['c++'] +1957,do ocunit and ocmock work on the iphone sdk i simply could not make it work and i am wondering if i am wasting my time or if i am simply stupidsorry i do not have the exact error i have right now but i just want to know if it work or not,"['iphone', 'objective-c']" +1961,what is the best client side browser library to upload multiple files over http what is the best client side http library to upload multiple files if it can handle directories that is a huge bonus i am looking for something that is open source or free i am looking for something like ftp but that works over http through the browser uploading multiple files through a normal html 4x form is a bit of a hassle when it comes to uploading more than 56 filesfeel free to share your personal experiences,['html'] +1962,what is the naming convention in python for variable and function names coming from a c background the naming convention for variables and method names are usually either camelcase or pascal case c examplestring thisismyvariable apublic void thisismymethodin python i have seen the above but i have also seen underscores being used python examplethis is my variable adef this is my functionis there a more preferable definitive coding style for python,['python'] +1965,what is the difference between ruby and python versions ofself i have done some python but have just now starting to use rubyi could use a good explanation of the difference between self in these two languages obvious on first glanceself is not a keyword in python but there is a selflike value no matter what you call itpython methods receive self as an explicit argument whereas ruby does notruby sometimes has methods explicitly defined as part of self using dot notationinitial googling reveals selfhtml,"['python', 'ruby']" +1971,zip code us postal code validation i thought people would be working on little code projects together but i do not see them so heres an easy onecode that validates a valid us zip code i know there are zip code databases out there but there are still uses like web pages quick validation and also the fact that zip codes keep getting issued so you might want to use weak validationi wrote a little bit about zip codes in a side project on my wikiblogthere is also a new weird type of zip code i can do the javascript code but it would be interesting to see how many languages we can get here,['javascript'] +1974,generating random numbers in objectivec i am a java head mainly and i want a way to generate a pseudorandom number between 0 and 74 in java i would use the methodrandomnextint74i am not interested in a thiscussion about seeds or true randomness just how you accomplish the same task in objectivec i have scoured google and there just seems to be lots of different and conflicting bits of information,['objective-c'] +1975,how do i check if an integer is even or odd how can i check if a given number is even or odd in c,['c'] +1976,error initializer element is not computable at load time i have in a function that takes a struct and i am trying to store its variables in an array but i get this when i run gcc wall ansi pedanticerrors werrorint detect prmparam prm int prm arr prmfield1 prmfield2 prmfield3 return 0i get error initializer element is not computable at load time when i try to compile the above it looks fine to me whats wrong,['c'] +1977,how do i invoke a java method when given the method name as a string if i have two variablesobject objstring methodname getnamewithout knowing the class of obj how can i call the method identified by methodname on itthe method being called has no parameters and a string return value it is a getter for a java bean,['java'] +1980,how do i determine the file and line of a c method from a symbols pdb file pdb files contain symbol information for net assemblies i would like to read a pdb file in order to correlate methods with their file location the data is contained within it but i cannot seem to find a good description of how to get it outi know about mdbg but that is very heavy i thinkhope for what i want,"['c#', '.net']" +1981,ftp file upload with http proxy is there a way to upload a file to a ftp server when behind an http proxy it seems that uploading a file is not supported behind an http proxy using net webclient if there is no workaround if not do you know a good and free ftp library i can use edit unfortunately i do not have any ftp proxy to connect to,['c#'] +1985,pass parameter by reference in ruby in ruby is it possible to pass by reference a parameter with valuetype semantics eg a fixnumi am looking for something similar to cs ref keywordexampledef funcx x 1enda 5funca this should be something like funcref aputs a should read 6btw i know i could just usea funca,['ruby'] +1988,initialize a const array in a class initializer in c i have the following class in cclass a const int b2 other stuff follows and heres the constructor avoidthe question is how do i initialize b in the initialization list given that i cannot initialize it inside the body of the function of the constructor because b is constthis does not workaavoid b23 other initialization stuffedit the case in point is when i can have different values for b for different instances but the values are known to be constant for the lifetime of the instance,['c++'] +1990,if i stop a long running query does it rollback a query that is used to loop through 17 millions records to remove duplicates has been running now for about 16 hours and i wanted to know if the query is stopped right now if it will finalize the delete statements or if it has been deleting while running this query indeed if i do stop it does it finalize the deletes or rolls backi have found that when i do a select count from mytablethat the rows that it returns while doing this query is about 5 less than what the starting row count was obviously the server resources are extremely poor so does that mean that this process has taken 16 hours to find 5 duplicates when there are actually thousands and this could be running for daysthis query took 6 seconds on 20 rows of test data and it works great on that set of data so i figured it would take 15 hours for the complete setany ideasbelow is the querydeclare the looping variabledeclare loopvar char10 declare set private variables that will be used throughout long decimal lat decimal phonenumber char10 businessname varchar64 winner char10 set loopvar select minrecordid from mytable while loopvar is not null begin initialize the private variables essentially this is a ctor select long null lat null businessname null phonenumber null winner null load data from the row declared when setting loopvar select long longitude lat latitude businessname businessname phonenumber phone from mytable where recordid loopvar find the winning row with that data the winning row means select top 1 winner recordid from mytable where long longitude and lat latitude and businessname businessname and phonenumber phone order by case when webaddress is not null then 1 else 2 end case when caption1 is not null then 1 else 2 end case when caption2 is not null then 1 else 2 end recordid delete any losers delete from mytable where long longitude and lat latitude and businessname businessname and phonenumber phone and winner recordid prep the next loop value to go ahead and perform the next duplicate query set loopvar select minrecordid from mytable where loopvar recordid end,['sql'] +1992,what is the role of spring in struts spring hibernate what role is spring taking in struts spring hibernate,['java'] +1993,const int vs int const as function parameter in c and c quick question int testfunc1 const int a return aint testfunc2 int const a return aare these two functions the same in every aspect or is there a difference i am interested in an answer for the clanguage but if there is something interested in the c case i would like to know as well,"['c++', 'c']" +1997,rendered pixel width data for each character in a browsers font i have a table column that needs to be limited to a certain width say 100 pixels at times the text in that column is wider than this and contains no spaces for examplea really long string of text like this with no line breaks makes the table unhappyi would like to calculate the width of text serverside and add an ellipsis after the correct number of characters the problem is that i do not have data about the rendered size of the textfor example assuming the browser was firefox 3 and the font was 12px arial what would be the width of the letter a the width of the letter b etcdo you have data showing the pixel width of each character or a program to generate iti think a clever onetime javascript script could do the trick but i do not want to spend time reinventing the wheel if someone else has already done this i am surely not the first person to come up against this problem,"['javascript', 'jquery', 'html', 'css']" +1998,how do you log the machine name via log4net i am using log4net with the adonetappender to log messages from a simple systray application into a sql server 2005 databasei want to log the machine name along with the log message because this application will be running on multiple machines and i need to know on which one the message originatedbut i cannot find a way to expose this information via the log4netlayoutpatternlayout that i am using with the appenderis there a way to log the machine name via log4net in this manner,"['c#', '.net']" +2001,regular expression to match urls in java i use regexbuddy while working with regular expressions from its library i copied the regular expression to match urls i tested successfully within regexbuddy however when i copied it as java string flavor and pasted it into java code it does not work the following class prints false public class regexfoo public static void mainstring args string regex bhttpsftpfileaz09 az09 string text systemoutprintlnismatchtextregex private static boolean ismatchstring s string pattern try pattern patt patterncompilepattern matcher matcher pattmatchers return matchermatches catch runtimeexception e return false does anyone know what i am doing wrong,['java'] +2004,is there a maximum number of characters that can be written using a streamwriter is there a maximum number of characters that can be written to a file using a streamwriter or is there a maximum number of characters that writeline can output i am trying to write some data to a file but all of the data does not seem to make it this is the current state of my codestreamwriter sw new streamwriterpathtofileforeach gridviewrow record in gv recordsrows string recordinfo recordinformation swwritelinerecordinfo,"['c#', '.net']" +2005,ajax and the browser back button i run a browser based game at wdarknovagamescom recently i have been working on reformatting the site with css trying to get all of its pages to verify according to the html standardi have been toying with this idea of having the navigation menu on the left ajax the pages in rather than taking the user to a separate page each time requiring a reload of the title and nav bar which almost never change and i know that if i do so i will probably break the forwardback buttons in the browser my question i guess is should i go ahead and ajax the site thus requiring the user to use the sites navigation to play the game or should i leave the site as it currently stands and use standard hyperlinks and things for navigationthe reason i ask i guess is that i built a forums system into the site and a lot of times i would want to link say to a particular topic within the forumsi am also open to suggestions is there a standard preferably without traditional frames way to make only the body area of the site reload while still changing the url so that users can bookmark and forwardback etc that could potentially solve my problem as well i am just asking for the best solution here not an answer to a specific question thanks,"['javascript', 'html']" +2014,programmatically launching standalone adobe flashplayer on linuxx11 the standalone flashplayer takes no arguments other than a swf file when you launch it from the command line i need the player to go full screen no window borders and such this can be accomplished by hitting ctrlf once the program has started i want to do this programmatically as i need it to launch into full screen without any human interactionmy guess is that i need to some how get a handle to the window and then send it an event that looks like the ctrlf keystroke if it makes any difference it looks like flashplayer is a gtk application and i have python with pygtk installedupdate the solution i used thanks to ypnos answerflashplayer sleep 3 xsendkey window adobe flash player 10 controlf,['python'] +2015,to nest or not to nest premiseusually during preparation of a new ruby on rails app i draw out models and relations regarding user navigations usually i hit a place where i need to ask myself whether or not i should go beyond the usual rule of thumb of nesting no more 1 level deep sometimes i feel the need to nest rather than creating another namespace route and duplicating work heres an examplemodels user company location user has and belongs to many companies many to many user has and belongs to many locations many to many company has and belongs to many locations many to many routes1 level nesting usersuser idcompanies list all companies related to a userusersuser idlocations list all locations related to a usermore than 1 level nestingusersuser idcompaniescompany idlocations list all companylocations of a userso my question is whether or not it is appropriate to nest more than 1 level deep in ror yes or no and why,"['ruby-on-rails', 'ruby']" +2016,how can i see my applications threads while debugging in visual studio i would like to see the threads currently active in my application while debugging ithow can i do this using visual studio,['.net'] +2023,in ruby on rails how do i format a date with the th suffix as in sun oct 5th i want to thisplay dates in the format short day of week short month day of month without leading zero but including th st nd or rd suffixfor example the day this question was asked would thisplay thu oct 2ndi am using ruby 187 and timestrftime just does not seem to do this i would prefer a standard library if one exists,"['ruby-on-rails', 'ruby']" +2024,how to add a tooltip to a td with jquery i need to add a tooltipalt to a td element inside of my tables with jquerycan someone help me outi triedvar ttip hello worldthisattronmouseover tipttipwhere i have verified that i am using the td as thisediti am able to capture the td element through using the alert command and it worked so for some reason the tip function does not work anyone know why this would be,"['jquery', 'html']" +2028,whats the nicest way to do observerobservable in objectivec iphone version i am used to coding java swing uis and in those if you have some properties that change and you want your ui to update you would implement the observerobservable pattern in java you do this normally by having your class maintain a list of listeners that it notifies of different eventsi have played with objectivec on the mac and that has kvc and binding which seems to work very nicely and requires less code the iphone sdk does not seem to have this functionality though so my question isif i have a class that holds data that changes whats the best way for me to register a ui component with that class so that it can be notified of changes in the data that it needs to thisplay,"['iphone', 'objective-c']" +2032,how can i scale the content of an iframe how can i scale the content of an iframe in my example it is an html page and is not a popup in a page of my web sitefor example i want to thisplay the content that appears in the iframe at 80 of the original size,"['html', 'css']" +2037,write a password protected zip file in java i need to zip and passwordprotect a file is there a good free library for thisthis needs to be opened by a third party so the password protection needs to work with standard tools,['java'] +2039,what deployment directories do you use for rails applications deploying to a debian box i wonder whats the best deployment directory for rails apps some developers use directories such as uappsappname are there any advantages when using uappsappname instead of varwappname or other os default directoriesobviously i want to pick the directory with the best security properties and the least friction for setting up the server environmenthow do you deploy your rails apps why are you using a specific directory do you think it really matters anyway,"['ruby-on-rails', 'ruby']" +2043,how to repeat a string a variable number of times in c i want to insert n spaces or any string at the beginning of a string in c is there any direct way to do this using either stdstrings or char stringseg in python you could simply do 5 lolcatlolcat,['c++'] +2046,rspec stories and specs when to use what so i want to start using rspec stories but i am not sure where writing controller model and view specs fit in for example you have the story logging in with user provides wrong password scenario do not you end up testing the same stuff than controllermodel specs responseshould render usershould be nil etcso my question is for those who are used to doing bdd or story dd with ror do you still write modelcontroller specs if so how is the workflow you follow first story then narrow to specific specs,"['ruby-on-rails', 'ruby']" +2052,possible memory leak in number of loaded classes in java application i recently began profiling an osgi java application that i am writing using visualvm one thing i have noticed is that when the application starts sending data to a client over jms the number of loaded classes starts increasing at a steady rate the heap size and the permgen size remains constant however the number of classes never falls even after it stops sending data is this a memory leak i think it is because the loaded classes have to be stored somewhere however the heap and permgen never increase even after i run the application for several hoursfor the screenshot of my profiling application go here,['java'] +2058,do net applications run on linux do net applications run on linux are there any freepaid interop libraries available,['.net'] +2060,how do i show an embedded excel file in a webpage i want to allow an excel report to be viewed embedded in a webpage is there a wayi do not want to use an activex or owc office web components i just want to open an existing file from the internet explorer applicationi do not want users to download and then open itusing an iframe wouldnt be a problem but my preliminary tests werent successfulany ideas is it at all possible,"['asp.net', 'html']" +2061,how do you add a link that will add an event to your iphone calendar from safari this seems like it should be simple but after a couple hours of googling i have not figured it out i know i can add ical links using ics files but this does not work on the iphonebtw when i say iphone i would like it to work on the touch also anyone have any luck with this,"['iphone', 'html']" +2063,thisplay a tooltip over a button using windows forms how can i thisplay a tooltip over a button using windows forms,['.net'] +2065,can you get a windows ad username in php i have a php web application on an intranet that can extract the ip and host name of the current user on that page but i was wondering if there is a way to getextract their active directorywindows username as well is this possible,['php'] +2068,python how do i write a decorator that restores the cwd how do i write a decorator that restores the current working directory to what it was before the decorated function was called in other words if i use the decorator on a function that does an oschdir the cwd will not be changed after the function is called,['python'] +2072,what is the best way to do keep alive socket checking in net i am looking for a way to do a keep alive check in net the scenario is for both udp and tcpcurrently in tcp what i do is that one side connects and when there is no data to send it sends a keep alive every x secondsi want the other side to check for data and if non was received in x seconds to raise an event or soone way i tried to do was do a blocking receive and set the sockets recievetimeout to x seconds but the problem was whenever the timeout happened the sockets receive would throw an socketexeception and the socket on this side would close is this the correct behaviour why does the socket closedie after the timeout instead of just going on a check if there is data and sleep is not acceptable since i might be lagging on receiving data while sleepingso what is the best way to go about this and why is the method i described on the other side failing,['.net'] +2073,initializing c autoproperties i am used to writing classes like thispublic class foo private string mbar bar public string bar get return mbar set mbar value other methods no constructor converting bar to an autoproperty seems convenient and concise but how can i retain the initialization without adding a constructor and putting the initialization in therepublic class foo2therevengeoffoo private string mbar bar public string bar get set other methods no constructor behavior has changedyou could see that adding a constructor is not inline with the effort savings i am supposed to be getting from autopropertiessomething like this would make more sense to mepublic string bar get set bar,['c#'] +2075,simple way to programmatically get all stored procedures is there a way to get stored procedures from a sql server 2005 express database using c i would like to export all of this data in the same manner that you can script it our using sql server management studio without having to install the guii have seen some references to do thing via the powershell but in the end a c console app is what i really wantto clarifyi would like to script out the stored procedures the list via the select from sysprocedures is helpful but in the end i need to script out each of these,['c#'] +2076,open source cad drawing dwg library in c anyone knows of an open source dwg autocad drawing library in c,['c#'] +2081,how can i detect a held down mouse button over a picturebox i need to fire an event when the mouse is above a picturebox with the mouse button already clicked and held downproblems the mousedown and mouseenter event handlers do not work together very wellfor instance once a mouse button is clicked and held down c will fire the mousedown event handler but when the cursor moves over the picturebox the mouseenter event does not fire until the mouse button is realeased,['c#'] +2084,2d animation in python i am writing a simulator in python and am curious about options and opinions regarding basic 2d animations by animation i am referring to rendering on the fly not thisplaying prerendered imagesi am currently using matplotlib wxagg backend and it is possible that i will be able to continue using it but i suspect it would not be able to sufficiently scale in terms of performance or capabilitiesrequirements arecrossplatform linux macos xwindowslow complexity overheadplays well with wxpython at least would not step on each others toes undulyinteractivity detect when objects are clicked on moused over etc note that high performance is not on the list but the ability to handle 100 bitmap objects on the screen would be goodyour thoughts,['python'] +2088,looping over elements in jquery i want to loop over the elements of an html form and store the values of the input fields in an object the following code does not work thoughfunction config frmmainchildrenmapfunction var child this if childischeckbox thischildattrname childattrchecked if childisradio checked thischildattrname childval if childistext thischildattrname childval return null neither does the following inspired by jobscrys answerfunction config frmmainchildreneachfunction var child this alertchildlength if childischeckbox thischildattrname childattrchecked if childisradio checked thischildattrname childval if childistext thischildattrname childval the alert always shows that childlength 0 manually selecting the elements works frmmainchildrenobject length42 frmmainchildrenfiltercheckboxobject length3any hints on how to do the loop correctly,"['javascript', 'jquery']" +2093,unix socket implementation for java i realize that since unix sockets are platformspecific there has to be some nonjava code involved specifically were interested in using jdbc to connect to a mysql instance which only has unix domain sockets enabled it does not look like this is supported but from what i have read it should be at least possible to write a socketfactory for jdbc based on unix sockets if we can find a decent implementation of unix sockets for java has anyone tried this does anyone know of such an implementation,['java'] +2097,embedding hwnd into external process using setparent i am trying to embed a window from my process into the window of an external process using the setparent function and have encountered a few problems that i am hoping someone can help me out with first off here is an outline of what i am currently doing to embed my window into the applicationhwnd mywindow handle to my application windowhwnd externalwindow handle to external application windowsetparentmywindowexternalwindowremove ws popup style and add ws child styledword style getwindowlongmywindowgwl stylestyle style ws popupstyle style ws childsetwindowlongmywindowgwl stylestylethis code works and my window appears in the other application but introduces the following issueswhen my window gains input focus the main application window of the external process loses focus ie title bar changes colorkeyboard shortcut commands of the main application do not work while my window has focusdoes anybody know a workaround for this i would like my window to be treated as just another child window of the main application,['c'] +2099,how can i avoid duplicate content in aspnet mvc due to caseinsensitive urls and defaults edit now i need to solve this problem for real i did a little more investigation and came up with a number of things to reduce duplicate content i posted detailed code samples on my blog reducing duplicate content with aspnet mvcfirst post go easy if i have marked this up wrong or tagged it badly pin microsofts new aspnet mvc framework it seems there are two things that could cause your content to be served up at multiple urls something which google penalize for and will cause your pagerank to be split across themcaseinsensitive urlsdefault urlyou can set the default controlleraction to serve up for requests to the root of your domain let us say we choose homecontrollerindex we end up with the following urls serving up the same contentmydomaincommydomaincomhomeindexnow if people start linking to both of these then pagerank would be split google would also consider it duplicate content and penalize one of them to avoid duplicates in their resultson top of this the urls are not case sensitive so we actually get the same content for these urls toomydomaincomhomeindexmydomaincomhomeindexmydomaincomhomeindexmydomaincomhomeindexthe list goes onso the question how do i avoid these penalties i would likeall requests for the default action to be redirected 301 status to the same urlall urls to be case sensitivepossible,"['c#', 'asp.net']" +2101,how do i make an onclientclick post back using jquery aspnet i need help i want to recreate the the update panel postback without using a update panel to do the postback what is the generic method for doing thisfor example on stackoverflow when you vote up or down on a question it does a postback to update the database and i would bet they did not use an update panelwhat do i havei have a table with table data when i click on the td item as a whole column i want to do a update to the database and also update a gridview on the page it self the gridview shows all the currently clicked items in the table because it was updated via our methodplease help looking for a good generic method i could use for a lot of async postbacks without update panellooking for a good tutorial of some sortsthanks guysscott,"['asp.net', 'javascript', 'jquery']" +2106,which is fastest in php mysql or mysqli i would like to know if anyone has any firsthand experience with this dichotomy a few blogs say the mysql extension is faster than mysqli is this trueand i am only asking about speed i know mysqli has features that are not present in the older extension,"['php', 'mysql']" +2108,getting 256 colors out of rubyncurses i have got 256 colors working great in my terminal test scripts here but it stops working when i use ncurses via rubyncurses printing the escape sequences given on that page works fine but when i initialize ncurses puts stops working and i cannot output the colors with any of the various ncurses color changingstring output functions i have found what gives,['ruby'] +2118,how can i find the method that called the current method when logging in c how can i learn the name of the method that called the current method i know all about systemreflectionmethodbasegetcurrentmethod but i want to go one step beneath this in the stack trace i have considered parsing the stack trace but i am hoping to find a cleaner more explicit way something like assemblygetcallingassembly but for methods,"['c#', '.net']" +2119,how do you develop against openid locally i am developing a website in django that uses openid to authenticate users as i am currently only running on my local machine i cannot authenticate using one of the openid providers on the web so i figure i need to run a local openid server that simply lets me type in a username and then passes that back to my main appdoes such an openid dev server exist is this the best way to go about it,['python'] +2128,typing generic values c when i try this with a generic class where thisvalue is tif thisvaluegettype typeofint intthisvalueelse throw new invalidoperationexception t must be an int to perform this operationi get a compiletime error cannot convert type t to intwhat should i do to perform an integral operation on thisvalue when it is an intnote that this is just an example the code does type conversions with generics and int is just an example of one type for t,['c#'] +2129,speeding up python this is really two questions but they are so similar and to keep it simple i figured i would just roll them togetherfirstly given an established python project what are some decent ways to speed it up beyond just plain incode optimizationsecondly when writing a program from scratch in python what are some good ways to greatly improve performancefor the first question imagine you are handed a decently written project and you need to improve performance but you cannot seem to get much of a gain through refactoringoptimization what would you do to speed it up in this case short of rewriting it in something like c,['python'] +2132,29 5 i heard that you could rightshift a number by 5 instead of using mathfloor i decided to check its limits to make sure that it was a suitable replacement so i checked the following values and got the following results in google chrome25 5 229 5 229 5 2 15 9s29 5 3 16 9safter some fiddling i found out that the highest possible value of two which when rightshifted by 5 would yield 2 is 297955395074968691915273638183593749a with the 9 repeating in chrome and firefox the number is 2979a in iemy question is what is the significance of the number 0795539507496869191527363818359374 it is a very strange number and it really piqued my curiosityi have been trying to find an answer or at least some kind of pattern but i think my problem lies in the fact that i really do not understand the bitwise operation i understand the idea in principle but shifting a bit sequence by 5 does not make any sense at all to me any help is appreciatedfor the record the weird digit sequence changes with 2x the highest possible values of the following numbers that still truncate properlyfor 0 0948487687421729788184165954589843749a for 1 198977697537484345957636833190917968749a for 23 x97955395074968691915273638183593749a for 47 x959107901499373838305473327636718749a for 815 x91821580299874767661094665527343749a and so forth,['javascript'] +2133,c net 3035 features in 20 using visual studio 2008 what are some of the new features that can be used in net 20 that are specific to c 3035 after upgrading to visual studio 2008 also what are some of the features that are not availableavailablelambdasextension methods by declaring an empty systemruntimecompilerservicesextensionattributeautomatic propertiesobject initializerscollection initializerslinq to objects by implementing ienumerable extension methods see linqbridgenot availableexpression treeswpfsilverlight libraries,"['c#', '.net']" +2135,python dictionary update method i have a list string tagi am trying to initialize a dictionary with the key as the tag string and values as the array indexfor i ithtag in enumeratetag tagdictupdateithtagithe above returns me ithtag 608 608 is the 608th indexmy problem is that while the i is being interpreted as a variable python is treating the ithtag as a string instead of a variablei am confused it is kind of hard to google these kind of specific questions i hope i worded the title of this question correctlythanks,['python'] +2136,how to check if php array is associative or sequential php treats all arrays as associative so there are not any built in functions can anyone recommend a fairly efficient way to check if an array contains only numeric keysbasically i want to be able to differentiate between thissequentialarray arrayapple orange tomato carrotand thisassocarray arrayfruit1 apple fruit2 orange veg1 tomato veg2 carrot,['php'] +2140,why is there no raii in net being primarily a c developer the absence of raii resource acquisition is initialization in java and net has always bothered me the fact that the onus of cleaning up is moved from the class writer to its consumer by means of try finally or nets using construct seems to be markedly inferiori see why in java there is no support for raii since all objects are located on the heap and the garbage collector inherently does not support deterministic destruction but in net with the introduction of valuetypes struct we have the seemingly perfect candidate for raii a value type that is created on the stack has a well defined scope and c destructor semantics can be used however the clr does not permit a valuetype to have a destructormy random searches found one argument that if a valuetype is boxed it falls under the jurisdiction of the garbage collector and therefore its destruction becomes nondeterministic i feel that this argument is not strong enough the benefits of raii are big enough to say that a valuetype with a destructor cannot be boxed or used as a class memberto cut a long story short my question is are there any other reasons value types can not be used in order to introduce raii to net or do you think my argument about raiis obvious advantages are flawededit i must have not phrased the question clearly since the first four answers have missed the point i know about finalize and its nondeterministic characteristics i know about the using construct and i feel these two options are inferior to raii using is one more thing the consumer of a class must remember how many people forgot to put a streamreader in a using block my question is a philosophical one about the language design why is it the way it is and can it be improvedfor instance with a generic deterministically destructible valuetype i can make the using and lock keywords redundant achievable by library classes public struct thisposert where t ithisposable t val public thisposert t val t public t value get return val thisposer currently illegal if val defaultt valthispose i cannot help but end with a apropos quotation which i once saw but cannot currently find its originyou can take my deterministic destruction when my cold dead hand goes out of scope anon,['.net'] +2141,what ways are there of drawing 3d trees using java and opengl i know how to draw basic objects using jogl or lwjgl to connect to opengl what i would like is something that can generate some kind of geometry for trees similar to what speedtree is famous for obviously i do not expect the same quality as speedtreei want the trees to not look repetitive speed is not a concern i do not expect to need more than 100 trees on screen at one time are there free treedrawing libraries available in java or sample code or demosis there anything in other languages which i could port or learn from,"['java', 'c++', 'c']" +2146,incorporating shareware restrictions in c software i wish to implement my software on a shareware basis so that the user isgiven a maximum trial period of say 30 days with which to try out the software on purchase i intend the user to be given a randomlygenerated key which when enteredenables the software againi have never been down this route before so any advice or feedback or pointers to standard ways of how this is done would be much appreciatedi do not anticipate users cheating by changing the system date or anything like that though this is probably worth considering apologies if this topic has appeared before,['c++'] +2149,python py2exe cannot build exe using the email module py2exe does not work with the standard email modulehello i am trying to use py2exe for converting a script into an exe the build process shows thisthe following modules appear to be missingemailencoders emailgenerator emailiterators emailmimebase emailmimemultipart emailmimetext emailutils emailbase64mimethe executable does not work the referenced modules are not included i researched this on the internet and i found out that py2exe has a problem with the lazy import used in the standard lib email module unfortunately i have not succeeded in finding a workaround for this problem can anyone helpthank youpsimports in the script look like thiscode select all import stringtimesysossmtplib from emailmimemultipart import mimemultipart from emailmimebase import mimebase from emailmimetext import mimetext from email import encoders,['python'] +2158,what is the best way to validate a credit card in php given a credit card number and no additional information what is the best way in php to determine whether or not it is a valid numberright now i need something that will work with american express thiscover mastercard and visa but it might be helpful if it will also work with other types,['php'] +2160,how can i convert html to textile i am scraping a static html site and moving the content into a databasebacked cms i would like to use textile in the cms is there a tool out there that converts html into textile so i can scrape the existing site convert the html to textile and insert that data into the database,['html'] +2162,how to output cdata using elementtree i have thiscovered that celementtree is about 30 times faster than xmldomminidom and i am rewriting my xml encodingdecoding code however i need to output xml that contains cdata sections and there does not seem to be a way to do that with elementtreecan it be done,['python'] +2166,how do i convert a files format from unicode to ascii using python i use a 3rd party tool that outputs a file in unicode format however i prefer it to be in ascii the tool does not have settings to change the file formatwhat is the best way to convert the entire file format using python,['python'] +2174,irregular shaped windows form c what is the easiest way to do this is it possible with managed codethanks for your time,"['c#', '.net']" +2178,java 15 to 14 what is the best way to convert existing jar without source written in java 15 into java 14x,['java'] +2181,ruby and duck typing design by contract impossible method signature in javapublic liststring getfilesinlistfile directoriessimilar one in rubydef get files indirectoriesin the case of java the type system gives me information about what the method expects and delivers in rubys case i have no clue what i am supposed to pass in or what i will expect to receivein java the object must formally implement the interface in ruby the object being passed in must respond to whatever methods are called in the method defined here this seems highly problematiceven with 100 accurate uptodate documentation the ruby code has to essentially expose its implementation breaking encapsulation oo purity aside this would seem to be a maintenance nightmarethe ruby code gives me no clue whats being returned i would have to essentially experiment or read the code to find out what methods the returned object would respond tonot looking to debate static typing vs duck typing but looking to understand how you maintain a production system where you have almost no ability to design by contractupdateno one has really addressed the exposure of a methods internal implementation via documentation that this approach requires since there are no interfaces if i am not expecting a particular type do not i have to itemize every method i might call so that the caller knows what can be passed in or is this just an edge case that does not really come up,"['java', 'ruby']" +2182,design pattern for implementing plugins in your application what is the standard way for allowing and implementing a plugin system for your applicationin my last application i made a simple interface for all plugins that they must implement i then load all assemblies in the apps directory and toss out any that do not implement that interfaceone of the methods in the interface is a dowork method that periodically gets called on all loaded assemblies to perform any actions the plugins may havewhat is the proper way to do a plugin system do you just create an interface for plugins should you periodically call a particular method in all plugins is there a more sophisticated wayeditthank you matt hamilton for the reference to the systemaddin namespace this will most likely be the way i implement my plugins however i am still curious about plugin architecture in general and wouldnt mind some background on the best way they should be designed implmemented how you should call on them once loaded etc,['.net'] +2183,skipping the compressresources build step for xcode iphone apps is it possible to set an iphone xcode project to skip the compressresources build stepspecifically i want to skip the stage where it runs pngcrush on all of my png files many of which do not survive the experience in a form which my app can readedit the version of pngcrush used creates png files which contain a nonstandard mandatory private chunk which explicitly prevents decoding i have modified my png reader to handle these files but i would still like a perproject method of skipping this step one of the other side effects of pngcrush is that it does not save the colour value of transparent pixels so alphaed textures show fringing at smaller mip levelsthe iphone png format is described here png images in shortskip the cgbi chunkskip the zlib headersswap bgr to rgb channel orderedit it appears it also premultiplies the alpha sodivide by alpha,['iphone'] +2195,is there a way to get datetime value from timestamp type column i need a select from table which does not have column that tells when row was inserted only timestamp column values like 0x0530278 some data was imported to the table yesterday and now i need to find out what exactly was imported is there a way to do it using only timestamp info here i found thattimestamp is a 8 bytes sequential hex number that has nothing to do with neither the date nor the timeto get the current value of timestamp use dbtsperhaps there is a way to find what was timestamp value around specific time that would help to form a select or maybe there is a well known solution,['sql'] +2209,generic annotationdriven event notification frameworks while simple interfacedriven event notification frameworks in java have been around since precambrian times eg javabeanspropertychangesupport it is becoming increasingly popular for frameworks to use annotationdriven event notification instead for an example see jbosscache 22 the listener class has its listener methods annotated rather than conforming to a rigid interface this is rather easier to program to and easier to read since you do not have to write empty implementations of listener callbacks that youre not interested in and yes i know about listener adapter superclassesheres a sample from the jbosscache docscachelistenerpublic class mylistener cachestarted cachestopped public void cachestartstopeventevent e switch egettype case eventtypecache started systemoutprintlncache has started break case eventtypecache stopped systemoutprintlncache has stopped break nodecreated noderemoved nodevisited nodemodified nodemoved public void lognodeeventnodeevent ne logan event on node negetfqn has occured the problem with this is that it is very much more of an involved process writing the framework to support this sort of thing due to the annotationreflection nature of itso before i charge off down the road of writing a generic framework i was hoping someone had done it already has anyone come across such a thing,['java'] +2215,correct behavior for interface methods that cannot be implemented if i have a class that needs to implement an interface but one or more of the methods on that interface do not make sense in the context of this particular class what should i dofor example lets say i am implementing an adapter pattern where i want to create a wrapper class that implements javautilmap by wrapping some immutable object and exposing it is data as keyvalue pairs in this case the methods put and putall do not make sense as i have no way to modify the underlying object so the question is what should those methods do,['java'] +2217,is not saying cc wrong i have seen a lot of questions around that use improperly the expression ccthe reasons in my opinion are newbie c and c programmers probably do not understand the difference between the two languagespeople do not really care about it since they want a generic quick and dirty answerwhile cc could sometimes be interpreted as either c or c i think it is a big error c and c offer different approaches to programming and even if c code can be easily implemented into c programs i think that referring to two separate languages with that single expression cc is wrongit is true that some questions can be considered either as c or c ones anyway what do you think about it,"['c++', 'c']" +2218,css is there a way to get rid of the selection rectangle after clicking a link is there a way to get rid of the selection rectangle when clicking a link which does not refresh the current page entirely,['css'] +2221,get the name of a class as a string in c is there a way to take a class name and convert it to a string in c as part of the entity framework the include method takes in a dotdelimited list of strings to join on when performing a query i have the class model of what i want to join and for reasons of refactoring and future code maintenance i want to be able to have compiletime safety when referencing this classthus is there a way that i could do thisclass footblbarinclude foogettypetostring i do not think i can do gettype without an instance any ideas,['c#'] +2225,convert utcgmt time to local time we are developing a c application for a webservice client this will run on windows xp pcsone of the fields returned by the web service is a datetime field the server returns a field in gmt format ie with a z at the endhowever we found that net seems to do some kind of implicit conversion and the time was always 12 hours outthe following code sample resolves this to some extent in that the 12 hour difference has gone but it makes no allowance for nz daylight savingcultureinfo ci new cultureinfoennzstring date web service datetostringr cidatetime converteddate datetimeparsedate as per this date siteutcgmt offset standard time zone utcgmt 12 hours daylight saving time 1 hour current time zone offset utcgmt 13 hours how do we adjust for the extra hour can this be done programmatically or is this some kind of setting on the pcs,"['c#', '.net']" +2226,how can i find out when a picture was actually taken in c running on vista in windows xp fileinfolastwritetime will return the date a picture is taken regardless of how many times the file is moved around in the filesystemin vista it instead returns the date that the picture is copied from the camerahow can i find out when a picture is taken in vista in windows explorer this field is referred to as date taken,['c#'] +2229,what are the limits of ruby on rails i have a memory of talking to people who have got so far in using ruby on rails and then had to abandon it when they have hit limits or found it was ultimately too rigid i forget the details but it may have had to do with using more than one databaseso what i would like is to know is what featuresrequirements fall outside of ruby on rails or at least requires such contortions that it is better to use another more flexible framework even though you may have to lose some elegance or write extra boilerplate code,"['ruby-on-rails', 'ruby']" +2230,are c templates just macros in thisguise i have been programming in c for a few years and i have used stl quite a bit and have created my own template classes a few times to see how it is donenow i am trying to integrate templates deeper into my oo design and a nagging thought keeps coming back to me they are just a macros really you could implement rather ugly auto ptrs using defines if you really wanted tothis way of thinking about templates helps me understand how my code will actually work but i feel that i must be missing the point somehow macros are meant evil incarnate yet template metaprogramming is all the rageso what are the real thistinctions and how can templates avoid the dangers that define leads you into likeinscrutable compiler errors inplaces where you do not expect themcode bloat difficulty in tracing codesetting debugger breakpoints,['c++'] +2231,obtain file path of c save dialog box i have got a save dialog box which pops up when i press a button however i dont want to save a file at that point i want to take the name and place it in the text box next to the button for the name to be used later can anybody tell me how to obtain the file path from the save dialog box to use it later,['c#'] +2232,how to thisplay datetime with an abbreviated time zone i am aware of the systemtimezone class as well as the many uses of the datetimetostring method what i have not been able to find is a way to convert a datetime to a string that in addition to the time and date info contains the threeletter time zone abbreviation in fact much the same way stackoverflows tooltips for relative time thisplay worksto make an example easy for everyone to follow as well as consume let us continue with the stackoverflow example if you look at the tooltip that thisplays on relative times it thisplays with the full date the time including seconds in twelvehour format an ampm designation and then the threeletter time zone abbreviation in their case coordinated universal time i realize i could easily get gmt or utc by using the builtin methods but what i really want is the time as it is locally in this case on a web serverif our web server is running windows server 2k3 and has it is time zone set to cst or until daylight saving switches back cdt is it i would like our aspnet web app to thisplay datetimes relative to that time zone as well as formatted to thisplay a cst on the end i realize i could easily hardcode this but in the interest of robustness i would really prefer a solution based on the server running the codes os environment settingsright now i have everything but the time zone abbreviation using the following codemydatetimetostringmmddy hhmmss ttwhich thisplays10072008 034031 pmall i want and it is not much promise is for it to say10072008 034031 pm cdti can use systemtimezonecurrenttimezone and use it to correctly thisplay central daylight time but that is a bit too long for brevitys sake am i then stuck writing a string manipulation routine to strip out whitespace and any nonuppercase letters while that might work that seems incredibly hack to megoogling and looking around on here did not produce anything applicable to my specific question,['.net'] +2234,how do you deal with connection strings when deploying an aspnet site right now our test and production databases are on the same server but with different names deploying has meant editing webconfig to change all the connection strings for the correct database a step which i forget all too frequently weve finally created a new database server for testing and i am moving the databases over but now the server will be different and well still need to deal with connection string issues i was thinking of managing it via a hosts file but the thought of switching that on my desktop machine whenever i need to test against production data seems cumbersome at bestso i am just wondering if there is a better way out there something that would build with a production web config for deployment would be ideal,['asp.net'] +2242,what is the best encryption library in cc what is the best encryption library in cc in terms of entropy quality ease of usereadabilityportability performancewhats your favorite and why do you like it,"['c++', 'c']" +2245,can you allocate a very large single chunk of memory 4gb in c or c with very large amounts of ram these days i was wondering it is possible to allocate a single chunk of memory that is larger than 4gb or would i need to allocate a bunch of smaller chunks and handle switching between themwhyi am working on processing some openstreetmap xml data and these files are huge i am currently streaming them in since i cannot load them all in one chunk but i just got curious about the upper limits on malloc or new,"['c++', 'c']" +2246,best way to add full web search to my site i need to add full web search to my site i need something like google custom search but with no ads and it has to be free any recommendation of a web service or open source project that can index my site and allow me to search it will be helpfulmy site is made in ruby on rails if that helpsi will make this question communitywiki so you can edit my bad english i think many people can benefit from this question,"['ruby-on-rails', 'ruby']" +2247,how can i cache a calculated column in rails i have a tree of active record objects something likeclass part activerecordbase has many sub parts class name part def complicated calculation if sub partssize 0 return selfsub partsinject0 sum current sum currentcomplicated calculation else sleep1 return rand10 end endendit is too costly to recalculate the complicated calculation each time so i need a way to cache the value however if any part is changed it needs to invalidate its cache and the cache of its parent and grandparent etcas a rough draft i created a column to hold the cached calculation in the parts table but this smells a little rotten it seems like there should be a cleaner way to cache the calculated values without stuffing them along side the real columns,"['ruby-on-rails', 'ruby']" +2252,python style multipleline conditions in ifs sometimes i break long conditions in ifs to several lines the most obvious way to do this is if cond1 val1 and cond2 val2 and cond3 val3 and cond4 val4 do somethingis not very very appealing visually because the action blends with the conditions however it is the natural way using correct python indentation of 4 spacesfor the moment i am using if cond1 val1 and cond2 val2 and cond3 val3 and cond4 val4 do somethingbut this is not very pretty can you recommend an alternative way,['python'] +2253,whats a good and stable c tree implementation i am wondering if anyone can recommend a good c tree implementation hopefully one that is stl compatible if at all possiblefor the record i have written tree algorithms many times before and i know it can be fun but i want to be pragmatic and lazy if at all possible so an actual link to a working solution is the goal herenote i am looking for a generic tree not a balanced tree or a mapset the structure itself and the connectivity of the tree is important in this case not only the data withinso each branch needs to be able to hold arbitrary amounts of data and each branch should be separately iterateable,['c++'] +2255,is there a documented way to set the iphone orientation i have an app where i would like to support device rotation in certain views but other do not particularly make sense in landscape mode so as i swapping the views out i would like to force the rotation to be set to portraitthere is an undocumented property setter on uidevice that does the trick but obviously generates a compiler warning and could thisappear with a future revision of the sdkuidevice currentdevice setorientationuiinterfaceorientationportraitare there any documented ways to force the orientationupdate i thought i would provide an example as i am not looking for shouldautorotatetointerfaceorientation as i have already implemented thati want my app to support landscape and portrait in view 1 but only portrait in view 2 i have already implemented shouldautorotatetointerfaceorientation for all views but if the user is in landscape mode in view 1 and then switches to view 2 i want to force the phone to rotate back to portrait,"['iphone', 'objective-c']" +2263,programmatically access currency exchange rates i am setting up an online ordering system but i am in australia and for international customers i would like to show prices in us dollars or euros so they do not have to make the mental effort to convert from australian dollarsdoes anyone know if i can pull up to date exchange rates off the net somewhere in an easytoparse format i can access from my php script update i have now written a php class which implements this you can get the code from my website,['php'] +2265,where in array of ids i have webservice which is passed an array of intsi would like to do the select statement as follows but keep getting errors do i need to change the array to a stringwebmethodpublic minievent getadmineventsint buildingid datetime startdate commandcommandtext select id startdatetime enddatetime from tb bookings where buildingid in buildingids and startdatetime fromdate sqlparameter buildid new sqlparameterbuildingids buildingids,['c#'] +2271,how to json decode array elements in javascript i have a javascript array that among others contains a url if i try to simply put the url in the page the array is in a project involving the yahoo maps api it shows the url as it should bebut if i try to do a redirect or simply do an alert on the link array element i get functionreturn jsonencodethisas far as i see it this is because the browser does an jsonencode when it renders the page thus the link is thisplayed ok i have tried several methods to make it redirect that is what i want to do with the link correctly including the usage of eval but with no luckafter following some suggestions i have run eval jsonobject but it still returns the same outputso how does this done,['javascript'] +2273,what is the best php libclass to generate rssatom i have to produce rssatom feed in various applications and i want to know a good libclass wich is able to produce both and which already handle all common problemsfor example the one i used for year does not put the right format for date so my feed is not well handled by several aggregatorsthanks cadricupdate why i am looking for a lib because the one i used for years which i had hacked a few have a little problem maybe a specification is not correctly followed,['php'] +2275,jquery tips and tricks syntaxshorthand for the readyevent by roosteronacidline breaks and chainability by roosteronacidnesting filters by nathan longcache a collection and execute commands on the same line by roosteronacidcontains selector by roosteronaciddefining properties at element creation by roosteronacidaccess jquery functions as you would an array by roosteronacidthe noconflict function freeing up the variable by oliisolate the variable in noconflict mode by nickfnoconflict mode by roosteronaciddata storagethe data function bind data to elements by tenebrousxhtml5 data attributes support on steroids by roosteronacidthe jquery metadata plugin by filip dupanoviaoptimizationoptimize performance of complex selectors by roosteronacidthe context parameter by lupefiascosave and reuse searches by nathan longcreating an html element and keeping a reference checking if an element exists writing your own selectors by andreas grechmiscellaneouscheck the index of an element in a collection by redsquarelive event handlers by tmreplace anonymous functions with named functions by kenmicrosoft ajax framework and jquery bridge by slacejquery tutorials by egyamadoremove elements from a collection and preserve chainability by roosteronaciddeclare this at the beginning of anonymous functions by benfirebug lite hotbox plugin tell when an image has been loaded and google cdn by colour blendjudicious use of thirdparty jquery scripts by harriyothe each function by jan zichform extensions plugin by chris sasynchronous each function by onenerdthe jquery template plugin implementing complex logic using renderfunctions by roosteronacid,"['javascript', 'jquery']" +2279,determine highest net framework version i need to determine the highest net framework version installed on a desktop machine from cc code looks like i can iterate the folders under systemrootmicrosoftnetframework but that seems kind of error prone is there a better way perhaps a registry key i can inspect thanks,"['.net', 'c++', 'c']" +2283,is this the best way to get unique version of filename w python still diving in to python and want to make sure i am not overlooking something i wrote a script that extracts files from several zip files and saves the extracted files together in one directory to prevent duplicate filenames from being overwritten i wrote this little function and i am just wondering if there is a better way to do thisthanksdef unique filenamefile namecounter 1file name parts ospathsplitextfile name returns pathfile extwhile ospathisfilefile name file name file name parts0 strcounter file name parts1 counter 1return file namei really do require the files to be in a single directory and numbering duplicates is definitely acceptable in my case so i am not looking for a more robust method tho i suppose any pointers are welcome but just to make sure that what this accomplishes is getting done the right way,['python'] +2286,organization of junit tests in projects what would you consider best practice for organizing junit tests in a project and why for example do you keep your tests next to the classes they test do you put them in a separate but parallel package structure do you use a different organization strategy entirely,['java'] +2288,add scriptmanager to page programmatically i am developing a webpart it will be used in a sharepoint environment although it does not use the object model that i want to expose ajax functionality in because of the nature of the environment adding the script manager directly to the page is not an option and so must be added programmatically i have attempted to add the scriptmanager control to the page in my webpart codeprotected override void createchildcontrols if scriptmanagergetcurrentpage null scriptmanager smgr new scriptmanager ensure the scriptmanager is the first control pageformcontrolsaddat0 smgr however when this code is executed i get the following error messagethe control collection cannot be modified during databind init load prerender or unload phasesis there another way to add the scriptmanager to the page from a webpart or am i going to have to just add the scriptmanager to each page or master page that will use the webpart,['c#'] +2290,java application installers i am not looking for javawebstart i am looking for a thickclient application installation toolkit i have got a standalone application that consists of several files jar files data files etc and would need to do some pretty standard installation tasks like asking the user for target directories have them locate some parts of their system choose some of the permachine or peruser configuration options and possibly try to detect some of the machine settings for themi am looking for something which is like the msi or other wizard driven installation applications whats a good installer for java it would be ideal if it were crossplatform capable linux mac osx and windows,['java'] +2293,what do i need to do to upgrade an application to the latest rails version i am currently using rails 210 and want to upgrade to rails 211 after issuing the following command gem update railsi suppose that i need to change this line rails gem version 210 unless defined rails gem versionin environmentrbwhat other actions should i take to ensure that my application is using the latest version are there some other files that need an update,['ruby-on-rails'] +2294,how to monitor mysql space i downloaded a vm image of a web application that uses mysqlhow can i monitor its space consumption and know when additional space must be added,['mysql'] +2297,has and belongs to many relationship with multiple databases i have a situation where i have two models companies and permissions where companies is in a separate database from my permissions database this is a has and belongs to many relationship because each company can have many permissions and each permission can belong to many companiesthe reason the two databases are split is because the company database runs a high demand production application and the permissions database controls the permissions for another applicationwith rails it looks for the join table in the same database as the primary table for instance if i do companypermissions it looks in the company database for company permissions if i do permissioncompanies it looks in the permissions databasewhat is the best solution to using a has and belongs to many relationship with multiple databases,"['ruby-on-rails', 'ruby']" +2301,which facebook net library is the best to use there is a list of projects here mainly the facebook developer toolkit and facebooknet however i have seen a lot of negative feedback about the toolkit and it seems like facebooknet has not been upgraded to the latest facebook api are either of these worth using any other good libraries out therespecifically i am looking to use the library in a aspnet mvc applicationthanks,"['.net', 'asp.net']" +2312,how can i concatenate regex literals in javascript is it possible to do something like thisvar pattern some regex segment comment here another segmentor do i have to use new regexp syntax and concatenate a string i would prefer to use the literal as the code is both more selfevident and concise,['javascript'] +2313,convert month number to month name function in sql i have months stored in sql server as 123412 i would like to thisplay them as januaryfebruary etc is there a function in sql server like monthname1 january i am trying to avoid a case statement if possible,['sql'] +2317,modifying nsdate to represent 1 month from today i am adding repeating events to a cocoa app i am working on i have repeat every day and week fine because i can define these mathematically 3600247 1 week i use the following code to modify the datensdate datewithtimeintervalsincenow3600247weeksi know how many months have passed since the event was repeated but i cannot figure out how to make an nsdate object that represents 1 month3 months6 months9 months into the future ideally i want the user to say repeat monthly starting oct 14 and it will repeat the 14th of every month,['objective-c'] +2325,is it possible to specify proxy credentials in your webconfig i need to configure a website to access a webservice on another machine via a proxy i can configure the website to use a proxy but i cannot find a way of specifying the credentials that the proxy requires is that possible here is my current configurationdefaultproxy usedefaultcredentialsfalse proxy usesystemdefaulttrue proxyaddressproxy address bypassonlocaltrue defaultproxyi know you can do this via code but the software the website is running is a closedsource cms so i cannot do thisis there any way to do this msdn is not helping me much,['c#'] +2328,what resharper 4 live templates for c do you use what resharper 40 templates for c do you uselet us share these in the following formattitleoptional description shortcut shortcutavailable in availabilitysetting resharper template code snippet comes heremacros properties if presentmacro1 value editableoccurencemacro2 value editableoccurenceone macro per answer pleasehere are some samples for nunit test fixture and standalone nunit test case that describe live templates in the suggested format,['c#'] +2334,why use ruby instead of smalltalk ruby is becoming popular largely from the influence ruby on rails but it feels like it is currently struggling through its adolescence there are a lot of similarities between ruby and smalltalk maglev is a testament to that despite having a more unusual syntax smalltalk has all if not more of the objectoriented beauty of ruby from what i have read smalltalk seems to have ruby beat onmaturity developed in the 1970sstabilitycommercial supportthistributed source control understands structure of code not just text diffingseveral implementations of the vmcrossplatform supportthe seaside web framework as a strong alternative to rails it seems like ruby is just reinventing the wheel so why do not ruby developers use smalltalk what does ruby have the smalltalk does not for the record i am a ruby guy with little to no experience in smalltalk but i am starting to wonder whyedit i think the easeofscripting issue has been addressed by gnu smalltalk as i understand it this allows you to write smalltalk in regular old text files and you no longer need to be in the smalltalk ide you can then run your scripts withgst smalltalk file,"['ruby-on-rails', 'ruby']" +2335,preprocessing source code as a part of a maven build i have a lot of java source code that requires custom preprocessing i would like rid of it but that is not feasible right now so i am stuck with it given that i have an unfortunate problem that should not have existed in the first place how do i solve it using maven for the full story i am replacing a pythonbased build system with a maven one so one improvement at a time please fixing the nonstandard source code is harder and will come lateris it possible using any existing maven plugins to actually alter the source files during compile time obviously leaving the original unprocessed code aloneto be clear by preprocessing i mean preprocessing in the same sense as antenna or a c compiler would preprocess the code and by custom i mean that it is completely proprietary and looks nothing at all like c or antenna preprocessing,['java'] +2338,default parameters with c constructors is it good practice to have a class constructor that uses default parameters or should i use separate overloaded constructors for example use thisclass foo private stdstring name unsigned int age public fooconst stdstring name const unsigned int age 0 name name age age or thisclass foo private stdstring name unsigned int age public foo name age 0fooconst stdstring name const unsigned int age name name age age either version seems to work egfoo f1foo f2name 30which style do you prefer or recommend and why,['c++'] +2339,copy tables from one database to another in sql server i have a database called foo and a database called bar i have a table in foo called tblfoobar that i want to move data and all to database bar from database foo what is the sql statement to do this,['sql'] +2345,can i specify my explicit type comparator inline so net 3035 provides us with lots of new ways to query sort and manipulate data thanks to all the neat functions supplied with linq sometimes i need to compare userdefined types that do not have a builtin comparison operator in many cases the comparison is really simple something like foo1key foo2key rather than creating a new iequalitycomparer for the type can i simply specify the comparison inline using anonymous delegateslambda functions something likevar f1 f2 var f3 f1except f2 new iequalitycomparer foo a foo b akeycomparetobkey i am pretty sure the above does not actually work i just do not want to have to make something as heavy as a whole class just to tell the program how to compare apples to apples,"['c#', '.net']" +2348,how do you execute a stored procedure using castle activerecord i believe there is a thiscussion on this very topic somewhere on the net but i lost the url and i am unable to find it via googlingwhat i might try right now would beisessionfactoryholder factoryholder activerecordmediatorentityclassgetsessionfactoryholderisession session factoryholdercreatesessiontypeofentityclasstry idbcommand cmd sessionconnectioncreatecommand cmdcommandtext spname cmdexecutenonquerycatchexception exfinally factoryholderreleasesessionsessionhowever i am not quite sure if this is the correct way to do this or if perhaps a better way exists,"['c#', '.net']" +2351,how to format a string as a telephone number in c i have a string 124 it is a telephone number i want to format as 124 before i store it in a file it is on a datarecord and i would prefer to be able to do this without assigning a new variablei was thinkingstringformat0 imyphonetostring but that does not seem to do the trick update ok i went with this solutionconverttoint64icustomer phonetostring now its gets messed up when the extension is less than 4 digits it will fill in the numbers from the right so124 3 becomes11221244 34any ideas,['c#'] +2355,how to use c to sanitize input on an html page is there a library or acceptable method for sanitizing the input to an html pagein this case i have a form with just a name phone number and email address code must be cfor examplescript srcbobsjsjohn doescript should become john doe,['c#'] +2360,problem using sqlite memory with nhibernate i use nhibernate for my dataacess and for awhile not i have been using sqlite for local integration tests i have been using a file but i thought i would out the memory option when i fire up any of the integration tests the database seems to be created nhibernate spits out the table creation sql but interfacting with the database causes an errorhas anyone every gotten nhibernate working with an in memory database is it even possible the connection string i am using is thisdata sourcememoryversion3newtrue,['c#'] +2361,detect gcc compiletime flags of a binary is there a way to find out what gcc flags a particular binary was compiled with,"['c++', 'c']" +2363,detect that the internet connection is offline how to detect that the internet connection is offline in javascript,['javascript'] +2367,database localization i am looking for opinions if the following problem maybe has a betterdifferentcommon solutioni have a database for products which contains the names of the products in english the default language of this application and i need translations of the names if availablecurrently i have this setupa product tablecreate table products id serial not null name character varying255 not null constraint products pkey primary key idand a product localization tablecreate table products l10n product id serial not null language character2 not null name character varying255 not null constraint products l10n pkey primary key product id language constraint products l10n product id fkey foreign key product id references products id match simple on update cascade on delete cascadeand i use the following query to retrieve a list of localized products german in this case with fallback to the default english namesselect pid coalesceplname pname from products p left join products l10n pl on pid plproduct id and language dethe sql code is in postgres dialect data is stored as utf8,['sql'] +2371,what is the javascript mime type for the type attribute of a script tag what is the mime type of javascript more specifically what is the right thing to put in the type attribute of a script tag applicationxjavascript and textjavascript seem to be the main contenders,['javascript'] +2372,daemon threads explanation in the python documentationit saysa thread can be flagged as a daemon thread the significance of this flag is that the entire python program exits when only daemon threads are left the initial value is inherited from the creating threaddoes anyone have a clearer explanation of what that means or a practical example showing where you would want to set threads as daemonicto clarify for meso the only time you wouldnt set threads as daemonic is if you wanted them to continue running after the main thread exits,['python'] +2381,jquery animate backgroundcolor i am trying to animate a change in backgroundcolor using jquery on mouseoveri have checked some example and i seem to have it right it works with other properties like fontsize but with backgroundcolor i get and invalid property js errorthe element i am working with is a divusercontentmouseoverfunction thisanimate backgroundcolor olive slowany ideas,"['javascript', 'jquery']" +2382,does ruby have a builtin do while ruby has a wealth of conditional constructs including ifunless whileuntil etcthe while block from cwhile condition can be directly translated to rubywhile condition endhowever i cannot seem to find a builtin equivalent in ruby for a clike do while block in which the block contents are executed at least oncedo while conditionany suggestions,['ruby'] +2383,setting ruby hash default to a list i thought i understood what the default method does to a hash give a default value for a key if it does not existirbmain0010 a irbmain0020 adefault 4 4irbmain0030 a8 4irbmain0040 a9 1 5irbmain0050 a 95all goodbut if i set the default to be a empty list or empty hash i do not understand it is behaviour at allirbmain0010 a irbmain0020 adefault irbmain0030 a8 9 9 greatirbmain0040 a would have expected 89irbmain0050 a8 9 awesomeirbmain0060 a9 9 unawesome should not this be i was hopingexpecting the same behaviour as if i had used the operatorirbmain0010 a irbmain0020 a8 irbmain0030 a8 9 9irbmain0040 a 89irbmain0050 a9 nilcan anyone explain what is going on,['ruby'] +2386,order of tags in does it matter at all what order the link or script or meta tags are in in the headheaddaft question but one of those things i have never given any thought to until now,['html'] +2388,how to get a complete list of objects methods and attributes dirrecompilepattern does not return pattern as one of the listss elements namely it returns copy deepcopy findall finditer match scanner search split sub subnaccording to the manual it is supposed to contain the objects attributes names the names of its clas attributes and recursively of the attributes of its clas base classesit says also thatthe list is not necessarily completeis there a way to get the complete list i always assumed that dir returns a complete list but apparently it does notalso is there a way to list only attributes or only methodsedit this is actually a bug in python supposedly it is fixed in the 30 branch and perhaps also in 26,['python'] +2389,qdockwidget initial width how do i set the initial width of a qdockwidgeti have implemented the sizehint function but what next,['c++'] +2398,get null null in sql i wish to search a database table on a nullable column sometimes the value i am search for is itself null since null is equal to nothing even null sayingwhere mycolumnsearchvaluewill fail right now i have to resort towhere mycolumnsearchvalue or mycolumn is null and searchvalue is nullis there a simpler way of saying thati am using oracle if that matters,['sql'] +2399,strange linq exception index out of bounds i have a table well call users this table has a single primary key defined in sql server an autoincrement int idsometimes my linq queries against this table fail with an index was outside the range error even the most simplest of queries the query itself does not use any indexersfor example user userstake1orienumerableusers userstolistboth of the queries threw the same error using the debugger visualizer to look at the generated query i copy and paste the query in sql and it works fine i also click execute on the visualizer and it works fine but executing the code by itself throws this error i do not implement any of the partial methods on the class so nothing is happening there if i restart my debugger the problem goes away only to rear it is head again randomly a few hours later more critically i see this bug in my error logs from the app running in production i do a ton of linq in my app against a dozen or so different entities in my database but i only see this problem on queries related to a specific entity in my table some googling has suggested that this problem might be related to an incorrect relationship specified between my model and another entity but i do not have any relationships with this object it seems to be working 95 of the time it is just the other 5 that faili have completely deleted the object from the designer and readded it from a refreshed server browser and that did not fix the problemany ideas whats going on hereheres the full error message and stack traceindex was out of range must be nonnegative and less than the size of the collection parameter name index at systemdatalinqsqlclientsqlproviderexecuteexpression query queryinfo queryinfo iobjectreaderfactory factory object parentargs object userargs icompiledsubquery subqueries object lastresult at systemdatalinqsqlclientsqlproviderexecuteallexpression query queryinfo queryinfos iobjectreaderfactory factory object userarguments icompiledsubquery subqueries at systemdatalinqsqlclientsqlprovidersystemdatalinqprovideriproviderexecuteexpression query at systemdatalinqtable1systemlinqiqueryproviderexecutetresultexpression expression at systemlinqqueryablefirstordefaulttsourceiqueryable1 source expression1 predicate at myprojectfinduserbytypestring typeidedit as requested below is a copy of the table schemacreate table dbocontainerid int identity11 not nullmarketcode varcharmax collate sql latin1 general cp1 ci as not nulldescription varcharmax collate sql latin1 general cp1 ci as not nullcapacity int not nullvolume float not null constraint pk container primary key clustered id ascwith pad index off statistics norecompute off ignore dup key off allow row locks on allow page locks on on primary on primaryedit the stack trace shows firstordefault but i duplicated the error using both take and tolist the stack trace is identical between all of these simply interchangnig firstordefaulttaketolist the move down the stack to sqlproviderexecute is in fact identical,['c#'] +2402,c generics would not allow delegate type constraints is it possible to define a class in c such thatclass genericcollectiont somebasecollectiont where t delegatei could not for the life of me accomplish this last night in net 35 i tried usingdelegate delegate actiont and funct tit seems to me that this should be allowable in some way i am trying to implement my own eventqueuei ended up just doing this primitive approximation mind youinternal delegate void dworkclass eventqueue private queuedwork eventqbut then i lose the ability to reuse the same definition for different types of functionsthoughts,['c#'] +2405,in an mfc application whats the easiest way to copy a file from one directory to another should i create two cfile objects and copy one into the other character by character or is there something in the library that will do this for me,['c++'] +2410,what is the most efficientelegant way to parse a flat table into a tree assume you have a flat table that stores an ordered tree hierarchyid name parentid order 1 node 1 0 10 2 node 11 1 10 3 node 2 0 20 4 node 1 2 10 5 node 21 3 10 6 node 12 1 20heres a diagram where we have id name root node 0 is fictional 0 root 1 node 1 3 node 2 2 node 11 6 node 12 5 node 21 4 node 1what minimalistic approach would you use to output that to html or text for that matter as a correctly ordered correctly indented tree assume further you only have basic data structures arrays and hashmaps no fancy objects with parentchildren references no orm no framework just your two hands the table is represented as a result set which can be accessed randomly pseudo code or plain english is okay this is purely a conceptional questionbonus question is there a fundamentally better way to store a tree structure like this in a rdbmsedits and additionsto answer one commenters mark besseys question a root node is not necessary because it is never going to be thisplayed anyway parentid 0 is the convention to express these are top level the order column defines how nodes with the same parent are going to be sortedthe result set i spoke of can be pictured as an array of hashmaps to stay in that terminology for my example was meant to be already there some answers go the extra mile and construct it first but thats okaythe tree can be arbitrarily deep each node can have and children i did not exactly have a millions of entries tree in mind thoughdo not mistake my choice of node naming node 1 for something to rely on the nodes could equally well be called frank or bob no naming structure is implied this was merely to make it readablei have posted my own solution so you guys can pull it to pieces,['sql'] +2412,firefox error loading script loading google analytics in ff2 the project i am working on uses a windowonerror event handler to report user problems i have noticed a single user that just cannot seem to load the google analytics script our site does not see a lot of traffic so i am not sure how widespread this is but so far it seems to just effect one user his user agent is mozilla50 windows u windows nt 51 enus rv18117 gecko20080829 firefox20017the error message firefox gives is error loading scriptadditional note the site references several other javascript files however the analytics reference is the only one to an external domain and the only script reference at the bottom of the page just before the closing body taghas anybody else run across this or have any idea what could be the issue thanks,['javascript'] +2414,wait cursor over entire html page is it possible to set the cursor to wait on the entire html page in a simple way the idea is to show the user that something is going on while an ajax call is being completed the code below shows a simplified version of what i tried and also demonstrate the problems i run intoif an element id1 has a cursor style set it will ignore the one set on body obviously some elements have a default cursor style a and will not show the wait cursor on hover the body element has a certain height depending on the content and if the page is short the cursor will not show below the footerthe testhtml head style typetextcss id1 backgroundcolor 06f cursor pointer id2 backgroundcolor f60 style head body div idid1cursor pointerdiv div idid2no cursordiv a href onclickdocumentbodystylecursor wait return falsedo somethinga bodyhtmllater editit worked in firefox and ie with divmask thisplay none cursor wait zindex 9 position absolute top 0 left 0 height 100 width 100 backgroundcolor f opacity 0 filter alphaopacity 0a href onclickdocumentgetelementbyidmaskstylethisplay block return falsedo somethingathe problem with or feature of this solution is that it will prevent clicks because of the overlapping div thanks kibbeelater later edita simpler solution from dorwardwait wait cursor wait important and then a href onclickdocumentbodyclassname wait return falsedo somethingathis solution only shows the wait cursor but allows clicks,"['javascript', 'html', 'css']" +2415,generating a globally unique identifier in java summary i am developing a persistent java web application and i need to make sure that all resources i persist have globally unique identifiers to prevent duplicatesthe fine printi am not using an rdbms so i do not have any fancy sequence generators such as the one provided by oraclei would like it to be fast preferably all in memory i would rather not have to open up a file and increment some valueit needs to be thread safe i am anticipating that only one jvm at a time will need to generate idsthere needs to be consistency across instantiations of the jvm if the server shuts down and starts up the id generator should not regenerate the same ids it generated in previous instantiations or at least the chance has to be really really slim i anticipate many millions of presisted resourcesi have seen the examples in the ejb unique id pattern article they would not work for me i would rather not rely solely on systemcurrenttimemillis because well be persisting multiple resources per millisecondi have looked at the answers proposed in this question my concern about them is what is the chance that i will get a duplicate id over time i am intrigued by the suggestion to use javautiluuid for a uuid but again the chances of a duplicate need to be infinitesimally smalli am using jdk6,['java'] +2418,boiler plate code replacement is there anything bad about this code i have recently created these two unrelated methods to replace lots of boilerplate code in my winforms application as far as i can tell they work ok but i need some reassuranceadvice on whether there are some problems i might be missingfrom memorystatic class safeinvoker utility to avoid boilerplate invokerequired code usage safeinvokerinvokemyctrl myctrlenabled false public static void invokecontrol ctrl action cmd if ctrlinvokerequired ctrlbegininvokenew methodinvokercmd else cmd replaces onmyeventraised boilerplate code usage safeinvokerraiseeventthis myeventraised public static void raiseeventobject sender eventhandler evnt var handler evnt if handler null handlersender eventargsempty edit see related question hereupdatefollowing on from deadlock problems related in this question i have switched from invoke to begininvoke see an explanation hereanother updateregarding the second snippet i am increasingly inclined to use the empty delegate pattern which fixes this problem at source by declaring the event directly with an empty handler like soevent eventhandler myeventraised delegate,['c#'] +2431,how to find all the tables in mysql with specific column names in them i have 23 different column names that i want to look up in the entire db and list out all tables which have those columns any easy script,['mysql'] +2436,suggest feature for textboxes in a rails app i am looking for an easiest way how to implement the suggest feature for a text entry field in a rails application the idea is to complete names stored in a database column giving the user a dropdown menu of possible matches as he typesthanks for any suggestions,"['javascript', 'ruby-on-rails']" +2439,2d javascript array simply put is there a way to create a 2d javascript array using similar syntax to thisvar newarray 0 1 2 3 4 5 6 7 8,['javascript'] +2443,how do i use linq containsstring instead of containsstring i got one big questioni got a linq query to put it simply looks like thisfrom xx in tablewhere xxuidtostringcontainsstringselect xxthe values of the string array would be numbers like 1452010etcthe default for contains is containsstringi need it to do this instead containsstringedit one user suggested writing an extension class for string i would like to learn how but any one willing to point me in the right directionedit the uid would also be a number that is why it is converted to a stringhelp anyone,['c#'] +2445,what is the best way to use javadoc to document a java enum i have just started using javas enums in my own projects i have to use jdk 14 at work and i am confused as to the best practice of using javadoc for an enumi have found that this method works but the resultant code is a little unrefined doc for enumpublic enum something first thingfirst thing second thingsecond thingcould continue with moreis there any way i could break up the enum declarations on their own lines without chaining them by commas or is this the best approach for using javadoc for an enum,['java'] +2446,what is the quickest way to detect an unreachable host in java i would like the fastest and most accurate function boolean isreachablestring host int port that passes the following junit tests under the conditions below timeout values are specified by the junit test itself and may be considered unreachableplease note all answers must be platformindependent this means that inetaddressisreachableint timeout is not going to work since it relies on port 7 to do a ping on windows icmp ping being an undocumented function on windows and this port is blocked in this setuplan setupthismachine 1921680100othermachine 1921680200no machine is called nomachine or has the ip 19216802 always unreachableboth machines are running apache tomcat on port 8080 all other ports are unreachable including port 7examplecom 20877188166 is running a webserver on port 80 and is only reachable when the lan is connected to the internetoccasionally the lan is thisconnected from the internet in which case only local machines called by ip address are reachable all others are unreachable there is no dnsall tests are run on thismachinetesttimeout1600 320ms per call should be possible to do betterpublic void testlocalhost we can always reach ourselves asserttrueisreachablelocalhost 8080 asserttrueisreachable127001 8080 asserttrueisreachablethismachine 8080 even if there is no dns asserttrueisreachable1921680100 8080 assertfalseisreachablelocalhost 80 nothing on that porttesttimeout5500 1867ms per call should be able to do betterpublic void testlan asserttrueisreachable1921680200 8080 always connected to the lan assertfalseisreachable19216802 8080 no such a machineassertfalseisreachablenomachine 8080 no such machinethe following test is only run when the lan is thisconnected from the internettesttimeout5600 1867ms per call reasonablepublic void testnodns assertfalseisreachableothermachine 8080 no dns assertfalseisreachableexamplecom 80 no dns no internet assertfalseisreachable20877188166 80 no internetthe following test is only run when the lan is connected to the internettesttimeout5600 1867ms per call reasonablepublic void testhavedns asserttrueisreachableothermachine 8080 dns resolves local names asserttrueisreachableexamplecom 80 dns available asserttrueisreachable20877188166 80 internet available,['java'] +2449,professional jquery based combobox control are there any professional combobox controls dropdown list with autosuggestion based on the jquery libraryit should be able to handle large datasets and have some skinning options a multicolumn result list would be great too i am working with aspnet but it is a not a problem if i had to write a wrapper for iti am already using a thirdparty control but i ran into some compatibilty issues between two vendors controls well i want to get rid of this kind of dependencies,"['javascript', 'jquery']" +2452,transactionscope bug in net more information i have read or perhaps heard from a colleague that in net transactionscope can hit its timeout and then votecommit as opposed to voterollback is this accurate or hearsay i could not track down information on the web that talked about this issue if it is an issue so i wonder if anyone has any direct experience with it and can shed some light,"['c#', '.net']" +2459,how do you do relative time in rails i am writing a rails application but cannot seem to find how to do relative time ie if given a certain time class it can calculate 30 seconds ago or 2 days ago or if it is longer than a month 912008 etc,"['ruby-on-rails', 'ruby']" +2460,test driven design for iphone native apps i am experimenting with the iphone sdk and doing some tdd ala dr nics rbiphonetest project i am wondering how many if any have been successful using this or any other testing framework for iphonecocoa more important i would like to know how to best assert a proprietary binary requestresponse protocol the idea is to send a binary request over the network and receive a binary response requests and responses are created using byte anding and oring i am using the golden copy pattern to test my request heres what i have so far do not laugh as i am new to btoh objective c and rubyrequire filedirname file test helperrequire fileutilsrequire iorequire mymodelbundleosxns import mymodelmodule mytestextensions def is absolute pathpath return matchpath end def parent directoryfile dir file if is absolute pathdir dir fileexpand pathdir end dir filedirnamedir assert is absolute pathdir expecting an absolute path with dir return dir end def assert nsdata contains bytes from filefile data assert not nil data data should not be nil assert databytes data should have bytes datalengthtimes i expected filegetc assert not nil expected expected only i bytes actual data contains more actual databytesint8 ati assert equal expected actual bytes should be equal at offset i expected expectedchr but was actualchr expected filegetc raise assertionfailederror expecting expectedchr at offset datalength unless expected nil endendclass testmymodel testunittestcaseinclude osxinclude mytestextensions def this files dir return parent directory file end def setup expectedreq filenewthis files direxpectedmyreq expectedreq filenewthis files dirhellotxt assert fileexistthis files direxpectedmyreq the file expectedreqpath should exist end def test my model class exists mymodel end def test can init instance assert mymodelinstancesrespondtoselectorinit mymodel should define init end def test my model can request my datamymodel mymodelallocinitdata mymodelrequestmydata some query textassert nsdata contains bytes from file expectedreq data endend,"['iphone', 'objective-c', 'ruby']" +2461,what are the main differences between xhtml and html what are the main differences between xhtml and html which one is better in your opinion and why do most browsers support both,['html'] +2471,php best way to extract text within parenthesis whats the bestmost efficient way to extract text set between parenthesis say i wanted to get the string text from the string ignore everything except this text in the most efficient manner possibleso far the best i have come up with is thisfullstring ignore everything except this textstart strpos fullstringend strlenfullstring strpos fullstringshortstring substrfullstring start endis there a better way to do this i know in general using regex tends to be less efficient but unless i can reduce the number of function calls perhaps this would be the best approach thoughts,['php'] +2474,how to add nunit in visual studio i need to write test cases for my application i have chosen nunit please let me know how to add nunit to my visual studio ide where can i download them,['asp.net'] +2476,what is the easiestbestmost correct way to iterate through the characters of a string in java stringtokenizer convert the string to a char and iterate over that something else,['java'] +2477,drop down list with wpf menu controls i am looking for a way to add a drop down list in wpf to a menu this used to be really easy in winforms and so i am expecting you experts to know just now to do it in wpf thankssorry if this is a bad question it is late and i do not want to think,"['c#', '.net']" +2478,java2d performance issues i am having performance oddities with java2d i know of the sunjava2dopengl vm parameter to enable 3d acceleration for 2d but even using that has some weird issues here are results of tests i randrawing a 25x18 map with 32x32 pixel tiles on a jcomponentimage 1 bmp format image 2 a png formatwithout dsunjava2dopengltrue120 fps using bmp image 113 fps using png image 2with dsunjava2dopengltrue12 fps using bmp image 1700 fps using png image 2without acceleration i am assuming some kind of transformation is taking place with every drawimage i do in software and is pulling down the fps considerably in the case of png why though with acceleration would the results switch and png actually performs incredibly faster crazinessbmp image 1 is translated to an image type of type int rgb png image 2 is translated to an image type of type custom in order to get consistent speed with and without opengl acceleration i have to create a new bufferedimage with an image type of type int argb and draw image 1 or image 2 to this new image here are the results running with thatwithout dsunjava2dopengltrue120 fps using bmp image 1120 fps using png image 2with dsunjava2dopengltrue700 fps using bmp image 1700 fps using png image 2my real question is can i assume that type int argb will be the native image type for all systems and platforms i am assuming this value could be different is there some way for me to get the native value so that i can always create new bufferedimages for maximum performance thanks in advance,['java'] +2480,how to check if os is vista in python how in the simplest possible way thistinguish between windows xp and windows vista using python and pywin32 or wxpythonessentially i need a function that called will return true iff current os is vista iswindowsvistatrue,['python'] +2481,can you list the keyword arguments a python function receives i have a dict which i need to pass keyvalues as keyword arguments for exampled args kw1 value1 kw2 value2exampled argsthis works fine but if there are values in the d args dict that are not accepted by the example function it obviously dies say if the example function is defined as def examplekw2this is a problem since i do not control either the generation of the d args or the example function they both come from external modules and example only accepts some of the keywordarguments from the dictideally i would just doparsed kwargs feedparserparsethe urlvalid kwargs get valid kwargsparsed kwargs valid for pyrss2genrss2pyrss2genrss2valid kwargsi will probably just filter the dict from a list of valid keywordarguments but i was wondering is there a way to programatically list the keyword arguments the a specific function takes,['python'] +2482,can anyone recommend a java rich text editor the rich text editor must be implemented in java provide swing support and preferably be open sourcei am looking to integrate it into an existing javaswing application thanks,['java'] +2486,how do you optimise your javascript well simple question right but with no so simple answersin firefox i use firebug console profile but what to do in other browsers like internet explorer opera safari on windows,['javascript'] +2488,why cannot i use a type argument in a type parameter with multiple bounds so i understand that the following does not work but why does not it workinterface adaptere class adaptulatori e a extends i adaptere void addclasse extl classa intl addadapterfactorynew adapterfactorye aextl intl the add method gives me a compile error cannot specify any additional bound adaptere when first bound is a type parameter in eclipse or type parameter cannot be followed by other bounds in idea take your pickclearly youre just not allowed to use the type parameter i there before the and that is that and before you ask it does not work if you switch em because there is no guarantee that i is not a concrete class but why not i have looked through angelika langers faq and cannot find an answergenerally when some generics limitation seems arbitrary it is because youve created a situation where the type system cannot actually enforce correctness but i do not see what case would break what i am trying to do here i would say maybe it has something to do with method thispatch after type erasure but there is only one add method so it is not like there is any ambiguitycan someone demonstrate the problem for me,['java'] +2498,are there problems with rendering wpf over remote desktop under windows xp i have heard that wpf primitives will not be supported by remote desktop on windows xp the implication of this is that if you run a wpf application on a vista machine and thisplay it on an xp machine via remote desktop the thisplay will be sent as a compressed bitmapthis issue is resolved in vistavista comunication via directx 11 but this will not be made available on xp there is obviously a performance hit here i would like to understand it before making any inroads into developing applications to wpfsome information on this topic can be found heresee comment from the above link quoteto spongejims question this is done by the mil media integration layer which is the underlying core of wpf that handles composition on a vistavista remote desktop connection the mil primitives are remoted and then reconstituted on other combinations eg 2003xp what gets remoted is bitmaps which is obviously far more bandwidthintensive more depth on this topic can be found on greg schechters blog and in this entry in particular schechterarchive20060609623566aspxdoes anyone have any experience or more up to date information on this issue,"['c#', '.net']" +2501,silverlight hosted in winforms i would like to host a silverlight control in winforms via a winforms browser but for it to work i need some way for the forms to talk to the silverlight and also the other way around would it be possible to somehow have the two interact with each other using javascript as a middleman ie have the form speak to the browsers javascript and have that speak to the silverlight control is there a better way or even a way at all other than compiling the code as silverlight and wpf,"['c#', 'javascript']" +2502,how to get a random number in ruby how do i generate a random number between 0 and n,['ruby'] +2506,jquery select box and loop help thanks for reading i am a bit new to jquery and am trying to make a script i can include in all my websites to solve a problem that always drives me crazythe problemselect boxes with long options get cut off in internet explorer for example these select boxesin firefox they are fine but in ie the options are cut off to the width of the select when they drop downthe solutionwhat i am looking to do is create a script that i can include in any page that will do the followingloop through all the selects on the pagefor each selecta loop through its optionsb find the width of the longest optionc bind a function to expand the select to that width on focus or maybe clickd bind a function to shrink to it is original width on bluri have managed to do most of step 2 for one select boxi found that getting the options width was a problem especially in ie so i looped through and copied the text of each option to a span measured the span width and used the longest one as the width the select will be expanded to perhaps somebody has a better ideahere is the codescript typetextjavascript function this function will 1 create a data store for the select called resizetowidth 2 populate it with the width of the longest option as approximated by span width the data store can then be used make a temporary span to hold the text of the options bodyappendspan idcurrentoptwidthspan theselect optioneachfunctioni if this is the first time through zero out resizetowidth or it will end up nan if isnan thisparentdataresizetowidth thisparentdata originalwidth thisparentwidth thisparentdataresizetowidth 0 currentoptwidthcssfontfamily thiscssfontfamily currentoptwidthcssfontsize thiscssfontsize currentoptwidthcssfontweight thiscssfontweight put the text of the current option into the span currentoptwidthtext thistext set resizetowidth to the longer of a the current opt width or b itself so it will hold the width of the longest option when we are done resizetowidth mathmax currentoptwidthwidth thisparentdataresizetowidth update parent resizetowidth data thisparentdataresizetowidth resizetowidth remove the temporary span currentoptwidthremove theselectfocusfunction thiswidth thisdataresizetowidth theselectblurfunction thiswidth thisdataoriginalwidth alert theselectdataoriginalwidth alert theselectdataresizetowidth scriptand the selectselect idtheselect stylewidth50px option value1oneoption option value2twooption option value3threeoption option value42693748756fortytwo billion sixhundred and ninetythree million sevenhundredfortysomeodd option option value5fiveoption option value6sixoption option value7sevenoptionselecthopefully this will run for you if you want to run it or you can see it in action here what i need help withthis needs a bit of polish but seems to work ok if you specify the select boxhowever i do not seem to be able to figure out how to apply it to all select boxes on the page with a loop so far i have thisselecteach functioni select get the options for the select here can i use selecteach also is there a better way to get the length of the longest option for each select the span is close but not very exact the problem is that ie returns zero for the option widths of the actual selectsany ideas are very welcome both for the questions asked and any other improvements to my codethanks,"['javascript', 'jquery']" +2511,is it possible to initialize a const struct without using a function i have a fairly simple const struct in some c code that simply holds a few pointers and would like to initialize it statically if possible can i and if so how,['c'] +2512,how to detect what net framework versions and service packs are installed a similar question was asked here but it was specific to net 35 specifically i am looking for the followingwhat is the correct way to determine which net framework versions and service packs are installed is there a list of registry keys that can be usedare there any dependencies between framework versions,['.net'] +2514,is there any way to get python omnicomplete to work with nonsystem modules in vim the only thing i can get python omnicomplete to work with are system modules i get nothing for help with modules in my sitepackages or modules that i am currently working on,['python'] +2517,whats the main difference between intparse and converttoint32 i am using cand wanted to know the main difference between the two and which one is preferred to use while coding,['c#'] +2520,get last answer in many symbolic math systems such as matlab or mathematica you can use a variable like ans or to retrieve the last computed value is there a similar facility in the python shell,['python'] +2522,how do you convert a c string to an int possible duplicatehow to parse a string to an int in c how do you convert a c string to an intassume you are expecting the string to have actual numbers in it 1 345 38944 for examplealso let us assume you do not have boost and you really want to do it the c way not the crufty old c way,['c++'] +2525,can you use an alias in the where clause in mysql i need to use an alias in the where clause but it keeps telling me that its an unknown column is there any way to get around this issue i need to select records that have a rating higher than x rating is calculated as the following aliassumreviewsrev ratingcountreviewsrev id as avg rating,['mysql'] +2527,what is the technical term for c or java type languages this is probably a very simple question but what is the technical term for this class of language they use an intermediate assembly type language which is sent through the jvm or clr they both are object oriented and they both depend on an intermediary such as the java virtual machine or the common language runtime to compile into native machine laguage unlike asmcc they do not compile directly into native machine language and require intensive memory allocation knowledge they both use garbage collection is there a technical term which seperates java and c from c,"['c#', 'java']" +2535,are php short tags acceptable to use heres the information according to the official documentationthere are four different pairs of opening and closing tags which can be used in php two of those php and script languagephp script are always available the other two are short tags and asp style tags and can be turned on and off from the phpini configuration file as such while some people find short tags and asp style tags convenient they are less portable and generally not recommendedin my experience most servers do have short tags enabled typingis far more convenient than typingphp echo the programmers convenience is an important factor so why are they not recommended,['php'] +2543,how to decode a csr file i ran accross a csr file certificate signing request and i need to extract some information from itthere is a way to decode it using net framework,['.net'] +2544,be notified when visuallogical child addedremoved i am currently looking for a way to be notified when a child is added to the visual or logical childreni am aware of the visualonvisualchildrenchanged method but it does not apply to me since i cannot always inherit and override this function i am looking for an eventso is there a way for the owner of a frameworkelementvisual to be notified when a child is added,['.net'] +2549,visual studio debugger tips tricks for net i have been working for years with vss debugger but every now and then i come across a feature i have never noticed before and think damn how could i have missed that it is so usefulthisclaimer these tips work in vs 2005 on a c project no guarantees for older incarnations of vs or other languages keep track of object instancesworking with multiple instances of a given class how can you tell them apartin pregarbage collection programming days it was easy to keep track of references just look at the memory address with net you cannot do that objects can get moved aroundfortunately the watches view lets you rightclick on a watch and select make object id this appends a 1 2 etc after the instances value effectively giving the instance a unique label it looks like this the label is persisted for the lifetime of that objectmeaningful values for watched variablesby default a watched variables value is it is type if you want to see its fields you have to expand it and this could take a long time or even timeout if there are many fields or they do something complicatedhowever some predefined types show more meaningful information strings show their actual contentslists and dictionaries show their elements count etcwouldnt it be nice to have that for my own types hmm some quality time with net reflector shows how easily this can be accomplished with the debuggerthisplay attribute on my custom typesystemdiagnosticsdebuggerthisplayemployee namepublic class employee public string name get rerun andthere is a lot more info on the subject here msdnbreak on all exceptions even the ones that are handled in codei know i am such a n00b for not knowing about this ever since i was born but here it goes anyway maybe this will help someone somedayyou can force a debugged process to break into debug mode each time an exception is thrown ever went on a bug hunt for hours only to come across a piece of code like thistry runstrangecontraption catchexception ex todo will handle this error later catching all exceptions is really handy in these casesthis can be enabled from debug exceptions ctrlalte tick the boxes in the thrown column for each type of exception you needthose were a few foreheadslapping moments for me would you care to share yours,['.net'] +2551,how should i add multiple identical elements to a div with jquery i need to add multiple empty divs to a container element using jqueryat the moment i am generating a string containing the empty html using a loopdivstr divdivdivdivdivdivand then injecting that into my containercontainerhtmldivstris there a more elegant way to insert multiple identical elementsi am hoping to find something that wouldnt break chaining but wouldnt bring the browser to its knees a chainable repeat plugin,"['javascript', 'jquery']" +2556,where can i find examples of element heavy web forms i would like to look at some examples of some good form layouts webbased that have a lot of input fields i do a lot of web application development and a lot of my forms are input element heavy so i am always looking for good ideas on how to thisplay my forms for example i have a few list boxes and a lot of text boxes and some drop downs on a page along with thisplaying history of changes to the form,['css'] +2566,is there a convenient way to wrap stdpair as a new type often times i find myself using stdpair to define logical groupings of two related quantities as function argumentsreturn values some examples rowcol tagvalue etcoften times i should really be rolling my own class instead of just using stdpair it is pretty easy to see when things start breaking down when the code becomes littered with make pair first and second its very hard to remember what is what an stdpairint int conveys less meaning than a type positionwhat have you found are the best ways to wrap the functionality of stdpair in a type that conveys real meaninghere are some things i have consideredtypedef stdpairint int positionthis at least gives the type a meaningful name when passing it around but the type is not enforced its still really just a pair and most of the same problems still exist this is however very simple to writestruct position public stdpairint int typedef stdpairint int base position base positionconst position x basex positionint a int b basea b int row return first const int row const return first int col return second const int col const return second this is better since we can access the variables via a reasonably descriptive name the problem here is that you can still access first and second so its easy for the abstraction to leak also accessing simple variables via functions makes the syntax annoyingthe obvious next step is to make the inheritance privatestruct position private stdpairint int typedef stdpairint int base position positionconst position x basex positionint a int b basea b int row return first const int row const return first int col return second const int col const return second bool operatorconst position x const return basethis basex other forwarding operators as neededso now at least we have gotten rid of the access to first and second but now a new problem pops up when we want to store the type in an stdset we now do not have access to the operator overload since we do not have access to first and second this means we have to define a forwarding function for each operator overload we want for me this is usually and but there could be others that i would want yes i know i probably should not overload operator just to stick it in an associative container but it makes everything so darn simple and defining these operators for each new type is a pain and we still have to access via functions we can fix thatstruct position position positionconst position x rowxrow colxcol positionint row int col rowrow colcol int row colbool operatorconst position a const position b return arow brow brow arow acol bcol more overloads as neededso now we have simple variable access but now defining overloaded operators is even more of a pain because instead of just forwarding them to the pairs implementation we actually have to reimplement them each timeare there any solutions i have overlooked that make this easy without the drawbacks if there are not which would you tend to prefer,['c++'] +2568,how hard is it to incorporate full text search with sql server i am building a caspnet app with an sql backend i am on deadline and finishing up my pages out of left field one of my designers incorporated a full text search on one of my pages my searches up until this point have been filters being able to narrow a result set by certain factors and column values being that i am on deadline you know 3 hours sleep a night at the point where i am looking like something the cat ate and threw up i was expecting this page to be very similar to be others and i am trying to decide whether or not to make a stink i have never done a full text search on a page before is this a mountain to climb or is there a simple solutionthank you,"['c#', 'asp.net', 'sql']" +2571,when should i write static methods so i understand what a static method or field is i am just wondering when to use them that is when writing code what design lends itself to using static methods and fields one common pattern is to use static methods as a static factory but this could just as easily be done by overloading a constructor correct for examplevar bmp systemdrawingbitmaploadfromfileimage01jpgas for static fields is creating singeltonobjects their best use,['c#'] +2582,best way to list files in java sorted by date modified i want to get a list of files in a directory but i want to sort it such that the oldest files are first my solution was to call filelistfiles and just resort the list based on filelastmodified but i was wondering if there was a better wayedit my current solution as suggested is to use an anonymous comparatorfile files directorylistfilesarrayssortfiles new comparatorfile public int comparefile f1 file f2 return longvalueoff1lastmodifiedcomparetof2lastmodified,['java'] +2586,compiling only part of the source tree with ant say i have my sources in my src tree and possibly in my test tree say i would like to compile only part of that tree the reasons why i might want to do that are various just as an example i might want to create the smallest possible jar without including certain classes or i might want the fastest compile time for what i am compiling i absolutely want to compile all the dependencies thoughthis can be easily achieved from the command line withjavac d build cp whatever sourcepath src srcpathtomyclassjavanow how can you do that with ant the javac ant task compiles everythingthe source and destination directory will be recursively scanned for java source files to compileone can use the excludes and includes parameters but they are problematic for this purpose in fact it seems that one has to explicitly setup all the includes not automatic dependency lookup and even worst that excludes has priority on includeswhen both inclusion and exclusion are used only filesdirectories that match at least one of the include patterns and do not match any of the exclude patterns are usedthus you cannot use javac srcdirsrcdir destdirbuilddir classpathrefclasspath excludesjava includessrcpathtomyclassjava because it will not compile anything is there any way of achieving that simple command line javac with antedited thank you for your answer sadie i am accepting it because it does work in the way i was wondering in this question but i have a couple of comments too long to be in the comment field of your answer1 i did read the documentation see links above but it is unclear that with just includes you are actually also excluding everything else2 when you just includes ant logs something likejavac compiling 1 source file to mypathtobuildeven if the dependencies make it compiling much more than just one source file,['java'] +2588,jquery current wellformatted printable documentation i am looking for a current 12 wellformatted printable version of the jquery documentation i have checked the alternative resources page and see the pdf versions from cf and java but both are out of datethe jquery site has the api browser with printable version in the toolbox but it prints terribly and i do not really want to print one page or tab at a timei have a hard time believing that there is no print doc for a tool this popular all i want is a simple listing with descriptions and examples on paperam i missing somethingi can buy one of the books if i need to but not sure which is for the current versionthanksupdatei can see that somebody voted this down i know it is a pretty basic question but it is not asked lightly or frivolously i have made a pretty solid effort to find this on my own and am pretty good at finding information when i need itperhaps the person who thought the question not worth asking knows where to find the print doc,['jquery'] +2595,creating sine or square wave in c how do i generate an audio sine or square wave of a given frequencyi am hoping to do this to calibrate equipment so how precise would these waves be,['c#'] +2601,moving items in dual listboxes how can i move items from one list box control to another listbox control using javascript in aspnet,"['asp.net', 'javascript']" +2603,spreadsheetlike control for a web application a client of mine is looking to convert a critical application based on multiple very complex spreadsheets into a web app as part of this they would like some of the web pages they use to entermodel data to resemble a spreadsheet as much as possiblei would be interested to know if anyone has any experiencerecommendations for embeddable controls that could do this better than standard htmljavascriptajax code although suggestions for javascript frameworks that could do this are welcome too i am thinking mainly of activex flex java or similar controls commercial or open source are finethe coding languages to be used and platform is still open to debate so aspnet against ie or phpflex against firefox or some other combination is fine this will be driven by the business requirement not the platform functionality is of course the main driving force but it is always useful to have nice looking eye candy so skinable and cool is a plus with reference to javascript frameworks ive previously used dojo and mootools but i would prefer something with a bit more snap,"['java', 'asp.net', 'javascript']" +2605,whats the term for design ala objectmethod1method2method3 whats the term for this designobjectmethod1method2method3when all methods return thisi found the term for this a while ago but lost it meanwhilei have no clue how to search for this on google also if anyone can think of a better title for the question feel free to change itthanksupdategishu after reading about it i feel that your question is misleading wrt code snippet provided feel free to rollbackmethod chainingobjectmethod1method2method3fluent interfacesprivate void makefluentcustomer customer customerneworder with6 tal with5 hpkskippable with3 lgv priorityrush,['c++'] +2613,are threads reused between requests in aspnet i am just wondering if the same thread is used for each session or if its dangerous to count on a particular thread between requests what i am getting at is can i use thread static storage,['asp.net'] +2614,best serverside net pdf editing library whats the best net pdf editing library available and whyit needs to be used on an iis webserverspecifically i need to edit a pdf which was generated by reporting servicesfactors i am interested inspeedmemory consumptionpricequality of documentationlibrary stabilitysize of librarywhatever else you think is important,"['c#', '.net', 'asp.net']" +2623,how to print a pdf from the browser in a web application is it possible to force a pdf file to be printed on the client if the browser is configured to open the pdf inside the window i guess that calling windowprint will work but some browsers like mine are configured to open the pdf externally,"['javascript', 'html']" +2624,select from same table as an insert or update clearly the following is incorrectinsert into atable ab valuesselect maxa from atable2namei get the valuesql query insert into atable a b values select maxa from atable 2 namemysql said1093 you cannot specify target table atable for update in from clause so i am trying to make a bitmap table each row corresponds to one bit and has a map valueto insert in the table i do not want to do two queries i want to do onehow should i do thisno one commented on this but since i am trying to make a bitmap it should be 2 not 2 my mistake please note that is why the comments often say 2 it was an error in the version that the commenters read,"['mysql', 'sql']" +2632,using ext js in aspnet i donat have advanced knowledge in javascript and i am trying to learn how to use ext js framework in aspnet c or vbnet environment iave got couple of samples but was unable get the project working is there such as website or book so i can go a read up about ext js in more details and how can i include this into my website,"['c#', 'asp.net']" +2634,windows automatic software updates what are some good solutions for handling automatic web based software updates for windows forms projects i am aware of microsoft oneclick but am not interested in it at this time,['.net'] +2645,index varchar on ms sql server 2005 i need to index a varchar field on my table in ms sql server 2005 but it is not clear to me how to do so if i try to add a nonclustered index on the field it says column x in table mytable is of a type that is invalid for use as a key column in an indexmy table has an autoincrement int id that is set as the primary key on the table if i set this property as the index and then add my varchar column as an included column the index goes through but i am not sure that is what i want i want to be able to search the table based on the varchar field alone and my understanding of indexes was that all indexed elements had to be provided to actually see a speedup in the query but i do not want to have to included the int id because i do not know what it is at the time of this given queryam i trying to do this incorrectly would the id my varchar as an included column accomplish what i am looking for,['sql'] +2649,best javascript date parser formatter since i have started to use jquery i have been doing a lot more javascript developmenti have the need to parse different date formats and then to thisplay them into another formatdo you know of any good tool to do thiswhich one would you recommend,"['javascript', 'jquery']" +2650,how do i prevent andor handle a stackoverflowexception i would like to either prevent or handle a stackoverflowexception that i am getting from a call to the xslcompiledtransformtransform method within an xsl editor i am writing the problem seems to be that the user can write an xsl script that is infinitely recursive and it just blows up on the call to the transform method that is the problem is not just the typical programmatic error which is usually the cause of such an exceptionis there a way to detect andor limit how many recursions are allowed or any other ideas to keep this code from just blowing up on me,"['c#', '.net']" +2651,printing to a client printer from a web app if i have a printer hooked directly to a pc a kiosk with a printer how would i go about creating the ability for a web page net web app to print a jpg to the kiosks printer with no user intervention other than clicking a button on the page,"['c#', '.net', 'asp.net', 'javascript']" +2655,python difference between class and instance attributes is there any meaningful thistinction betweenclass aobject foo 5 some default valuevsclass bobject def init self foo5 selffoo fooif youre creating a lot of instances is there any difference in performance or space requirements for the two styles when you read the code do you consider the meaning of the two styles to be significantly different,['python'] +2658,sql server string to date conversion i want to convert a string like this10152008 100632 pminto the equivalent datetime value in sql serverin oracle i would say thisto date10152008 100632 pmddy hhmiss amthis question implies that i must parse the string into one of the standard formats and then convert using one of those codes that seems ludicrous for such a mundane operation is there an easier way,['sql'] +2667,computing a crossbrowser iframe height one of the most difficult problems in my javascript experience has been the correct that is crossbrowser computing of a iframe heightin my applications i have a lot of dynamically generated iframe and i want them all do a sort of autoresize at the end of the load event to adjust their height and widthin the case of height computing my best solution is the following with the help of jqueryfunction getdocumentheightdoc var mdoc doc document if mdoccompatmodecss1compat return mdocbodyoffsetheight else if browsermsie return mdocbodyscrollheight else return mathmaxmdocheight mdocbodyheight i searched the internet without success i also tested yahoo library that has some methods for document and viewport dimensions but it is not satisfactorymy solution works decently but sometimes it calculates a taller heighti have studied and tested tons of properties regarding document height in firefoxiesafari documentelementclientheight documentelementoffsetheight documentelementscrollheight bodyoffsetheight bodyscrollheight also jquery does not have a coherent behavior in various browser with the calls documentbodyheight html docheight windowheighti call the above function not only at the end of load event but also in the case of dynamically inserted dom elements or elements hidden or shown this is a case that sometimes breaks the code that works only in the load eventdoes someone have a real crossbrowser at least firefoxiesafari solution some tips or hints,"['javascript', 'jquery']" +2680,naming of id columns in database tables i was wondering peoples opinions on the naming of id columns in database tablesif i have a table called invoices with a primary key of an identity column i would call that column invoiceid so that i would not conflict with other tables and it is obvious what it iswhere i am workind current they have called all id columns idso they would do the followingselect iid ilid from invoices i left join invoicelines il on iid ilinvoiceidnow i see a few problems here1 you would need to alias the columns on the select2 id invoiceid does not fit in my brain3 if you did not alias the tables and referred to invoiceid is it obvious what table it is onwhat are other peoples thoughts on the topic,['sql'] +2686,nullable type as a generic parameter possible i want to do something like this myyear recordgetvalueornullintmyyearnotice the nullable type as the generic parameter since the getvalueornull function could return null my first attempt was this public static t getvalueornulltthis dbdatarecord reader string columnname where t class object columnvalue readercolumnname if columnvalue is dbnull return tcolumnvalue return nullbut the error i am getting now isthe type int must be a reference type in order to use it as parameter t in the generic type or methodright nullableint is a struct so i tried changing the class constraint to a struct constraint and as a side effect cannot return null any morepublic static t getvalueornulltthis dbdatarecord reader string columnname where t structnow the assignmentmyyear recordgetvalueornullintmyyeargives the following errorthe type int must be a nonnullable value type in order to use it as parameter t in the generic type or methodis specifying a nullable type as a generic parameter at all possible,['c#'] +2687,how much does it cost to develop an iphone application how much can a developer charge for an iphone app like twitterrifici want to know this because i need such an application with the same functionality for a new community website i can do ruby but have no experience with objectivec so it would be interesting for me if i should start reading books about iphone programming or outsource the work to a iphone programmer,"['iphone', 'objective-c']" +2689,can i use python as a bash replacement i currently do my textfile manipulation through a bunch of badly remembered awk sed bash and a tiny bit of perli have seen mentioned a few places that python is good for this kind of thing i know a little and i would like to know more is python a good choice for this and is there a good book or guide to learning how to use python to replace shell scripting awk sed and friends,['python'] +2694,map two lists into a dictionary in python imagine that you havekeys name age foodvalues monty 42 spamwhat is the simplest way to produce the following dictionary dict name monty age 42 food spamthis code works but i am not really proud of it dict junk maplambda k v dictupdatek v keys values,['python'] +2697,how can i give each its own bullet image i have triedul idcontact list li idphonelocal 6045li li idi18l phonetollfree 18005liulwithcontact list liststyle thisc none insidecontact list phone liststyleimage urlimagessmall wood phonepngcontact list i18l phone liststyleimage urlimagesi18l wood phonepngto no avail only a thisc appears if i want each individual list item to have it is own bullet how can i accomplish this with css without using background imagesedit i have thiscovered that despite what firebug tells me the liststyleimage rule is being overridden somehow if i inline the rule like so li idphone styleliststyleimage urlimagessmall wood phonepnglocal 6045lithen all is well since i have no other rules in the test case i am running that contains ul or li in the selector i am not sure why inlining gives a different result,['css'] +2702,how do i attach the debugger to iis instead of aspnet development server i have an aspnet website and when i press f5 it automatically attaches to the aspnet development server how do i attach to iis worker process instead when i press f5,['asp.net'] +2708,why does scanf need lf for doubles when printf is okay with just f why is it that scanf needs the l in lf when reading a double when printf can use f regardless of whether its argument is a double or a floatexample codedouble dscanflf dprintff d,['c'] +2710,validate image from file in c i am loading an image from a file and i want to know how to validate the image before it is fully read from the filestring filepath imagejpgimage newimage imagefromfilefilepaththe problem occurs when imagejpg is not really a jpg for example if i create an empty text file and rename it to imagejpg an outofmemory exception will be thrown when imagejpg is loadedi am looking for a function that will validate an image given a stream or a file path of the imageexample function prototypebool isvalidimagestring filenamebool isvalidimagestream imagestream,"['c#', '.net']" +2713,pythons import does not work as expected when using import with a dotted name something like somepackagesomemodule the module returned is not somemodule whatever is returned seems to be mostly empty whats going on here,['python'] +2714,python inverse of a matrix how do i get the inverse of a matrix in python i have implemented it myself but it is pure python and i suspect there are faster modules out there to do it,['python'] +2719,lightweight messaging async invocations in java i am looking for lightweight messaging framework in java my task is to process events in a sedaas manner i know that some stages of the processing could be completed quickly and others not and would like to decouple these stages of processingletas say i have components a and b and processing engine be this container or whatever else invokes component a which in turn invokes component b i do not care if execution time of component b will be 2s but i do care if execution time of component a is below 50ms for example therefore it seems most reasonable for component a to submit a message to b which b will process at the desired timei am aware of different jms implementations and apache activemq they are too heavyweight for this i searched for some lightweight messaging with really basic features like messages serialization and simplest routing to no availdo you have anything to recommend in this issue,['java'] +2721,is it possible to change the properties of a webreference in runtime i am trying to come up with such a solution that the user is going to enter the url of a webservice and it is going to be testedalthough what i want is a url change i guarantee the service description is always going to be the same except the wsdlservice tag of course which contains the soapaddress i just want to test different customers running the same service,['c#'] +2722,why globalasax application error method does not catch exceptions thrown by asmx service and how to fix it i would like to log every thrown exception for maintenance purpose,['asp.net'] +2733,which annotation should i use idclass or embeddedid the jpa java persistence api specification has 2 different ways to specify entity composite keys idclass and embeddedid i am using both annotations on my mapped entities but it turns out to be a big mess to people who are not very familiar with jpa i want to adopt only one way to specify composite keys which one is really the best why,['java'] +2736,what is the easiest way to encrypt a password when i save it to the registry currently i am writing it in clear text oops it is an in house program so it is not that bad but i would like to do it right how should i go about encrypting this when writing to the registry and how do i decrypt itourkeysetvaluepassword textboxpasswordtext,['c#'] +2737,a script on this page is causing ie to run slowly the problem is in the title ie is misbehaving and is saying that there is a script running slowly ff and chrome do not have this problemhow can i find the problem there is a lot of js on that page checking by hand is not a good ideeaedit it is a page from a project i am working on but i need a tool to find the problemend it turned out to be the updatepanel somehow it would get confused and would take too long to process something i just threw it out the window will only use jquery from now on dand i am selecting remy sharps answere because i really did not know about the tool and it seems pretty cool,['javascript'] +2739,advantages of antlr versus say lexyaccbison i have used lex and yacc more usually bison in the past for various projects usually translators such as a subset of edif streamed into an eda app additionally i have had to support code based on lexyacc grammars dating back decades so i know my way around the tools though i am no experti have seen positive comments about antlr in various fora in the past and i am curious as to what i may be missing so if youve used both please tell me whats better or more advanced in antlr my current constraints are that i work in a c shop and any product we ship will not include java so the resulting parsers would have to follow that rule,['c++'] +2744,selenium rc run tests in multiple browsers automatically so i have started to create some ruby unit tests that use selenium rc to test my web app directly in the browser i am using the selenumclient for ruby i have created a base class for all my other selenium tests to inherit fromthis creates numerous seleniumdriver instances and all the methods that are missing are called on each instance this essentially runs the tests in parallelhow have other people automated thisthis is my implementationclass seleniumtest testunittestcase def setup seleniums wfirefox iexploremap do browser puts creating browser browser seleniumseleniumdrivernewlocalhost 4 browser httplocalhost3003 10 end start open start address end def teardown stop end subclasses should override this if they want to change it def start address httplocalhost3003 end overrides standard open method def openaddr method missing open addr end overrides standard type method def typeinputlocator value method missing type inputlocator value end overrides standard select method def selectinputlocator optionlocator method missing select inputlocator optionlocator end def method missingmethod name args seleniumseach do selenium driver if argsempty selenium driversend method name else selenium driversend method name args end end endendthis works but if one browser fails the whole test fails and there is no way to know which browser it failed on,"['ruby-on-rails', 'ruby']" +2745,boost like libraries in c can you recommend peer reviewed libraries that i can use in c environment something like boost for c something that provides hash thread interprocess communications lists smart memory managementthe environment is embedded system not a very minimal system but also not a pcthanks amit,['c'] +2746,bring a console window to front in c how can i bring a console application window to front in c especially when running the visual studio debugger,['c#'] +2748,multiple rows with jcarousel i am trying to use jcarousel to build a container with multiple rows i have tried a few things but have had no luck can anyone make any suggestions on how to create it,"['javascript', 'jquery']" +2749,gradient colors in internet explorer i know that internet explorer has some proprietary extensions so that you can do things like create divs with a gradient background i cannot remember the element name or it is usage does anyone have some examples or links,"['html', 'css']" +2755,how selfdocumenting can code be without being annoying i am not sure what the best practices are here but i often see abbreviated variable names especially when the scope is small so to use simple ruby examples instead of def add locationname coordinates i see things like def add locname coordaand i might even see something like def add locn x y i imagine that longer names might tire a person out whose used to seeing abbreviationsdoes verbosity help readability or does it just hurt everyones eyesado people prefer abbreviations and shortened names over longer names,['ruby'] +2757,vs vs iostreamh when including a header file in c whats the difference between1 including the h versus not including the h when wrapping it in signsinclude iostream vs include iostreamh2 wrapping the header name in double quotes versus wrapping it in signs include iostreamh vs include iostreamhthanks in advance,['c++'] +2759,linq fluent and query expression is there any benefits of one over other linq is one of the greatest improvements to net since generics and it saves me tons of time and lines of code however the fluent syntax seems to come much more natural to me than the query expression syntaxvar title entrieswheree eapproved orderbye eratingselecte etitle firstordefaultvar query from e in entries where eapproved orderby erating select etitlefirstordefaultis there any difference between the two or is there any particular benefit of one over other,['c#'] +2760,parsing atom rss in rubyrails i am looking for something that will let me parse atom and rss in ruby and rails i have looked at the standard rss library but is there one library that will autodetect whatever type of feed it is and parse it for me,"['ruby-on-rails', 'ruby']" +2767,scatter plots in c what is the best way to graph scatter plots in c do you write data to a file and use another tool is there a library like matplotlib in python,['c++'] +2769,available iphone web application javascript ui libraryframeworks i am starting a web application that will target mobile safari on iphoneipod touch i am evaluating the available clientside javascriptcss librariesframeworks that are currently out therethese are the ones i am currenlty aware ofiuiciuiuiuikitwebappnetiwebkitapples dashcode application not really a standalone libraryframework but it providesgenerates javascript css and images that conform to the native iphone ui metaphorsare there any others out there i want to make sure i am not missing any before i make a decision i am only looking for clientside javascriptcss solutions and building one from scratch is not an option because of time constraints no serverside php ruby python java etc solutionsi am aware of the iphone web applications templates frameworks question that was asked but this only mentioned iui and uiuikitthank you,"['javascript', 'iphone']" +2771,c coding guideline 102 if you were allowed to add another coding guideline to the 101 guidelines of the c coding standards herb sutter and andrei alexandrescu which would you add,['c++'] +2772,whats the difference between a parent and a reference property in google app engine from what i understand the parent attribute of a dbmodel typically definedpassed in the constructor call allows you to define hierarchies in your data models as a result this increases the size of the entity group however it is not very clear to me why we would want to do that is this strictly for acid compliance i would like to see scenarios where each is best suited or more appropriate,['python'] +2773,how to load text of ms word document in c net how do i load ms word document doc and docx to memory variable without doing thiswordappdocumentsopen i do not want to open ms word i just want that text inside you gave me answer for docx but what about doc i want free and high performance solution not to open 120 instances of word to process all of them aspose is commercial product and 900 is a way too much for what i do,"['c#', '.net']" +2776,how do i create a temporary file with cocoa years ago when i was working with c i could easily create a temporary file and get its name with this functionpathgettempfilenamethis function would create a file with a unique name in the temporary directory and return the full path to that file in the cocoa apis the closest thing i can find isnstemporarydirectoryam i missing something obvious or is there no built in way to do this,['objective-c'] +2789,extern inline i understand that inline by itself is a suggestion to the compiler and at its descretion it may or may not inline the function and it will also produce linkable object codei think that static inline does the same may or may not inline but will not produce linkable object code when inlined since no other module could link to itwhere does extern inline fit into the pictureassume i want to replace a preprocessor macro by an inline function and require that this function gets inlined eg because it uses the file and line macros which should resolve for the caller but not this called function that is i want to see a compiler or linker error in case the function does not get inlined does extern inline do this i assume that if it does not there is no way to achieve this behavior other than sticking with a macroare there differences between c and care there differences between different compiler vendors and versions,"['c++', 'c']" +2792,whats the best way to get the last inserted id using sqlite from java whats the best way to get the last inserted id using sqlite from java google is giving me different answerssome say select the lastinsertrowid others say call statementgetgeneratedkeys whats the best route to take i just want to return the id not use it for other inserts or anything,['java'] +2799,how do i add query parameters to a getmethod using java commonshttpclient using apache is commonshttpclient for java whats the best way to add query parameters to a getmethod instance if i am using postmethod it is very straightforwardpostmethod method new postmethodmethodaddparameterkey valuegetmethod does not have an addparameter method though i have thiscovered that this worksgetmethod method new getmethodmethodsetquerystringnew namevaluepair new namevaluepairkey valuehowever most of the examples i have seen either hardcode the parameters directly into the url eggetmethod method new getmethodor hardcode the query string eggetmethod method new getmethodmethodsetquerystringkeyvalueis one of these patterns to be preferred and why the api thiscrepancy between postmethod and getmethod and what are all those other httpmethodparams methods intended to be used for,['java'] +2802,ideal php session size i have a php form mortgage app that is about 400 fields traffic on the site will be lowwhat is the ideal session size for 400 fields going into a mysql dbin phpini what do i setanything i should set that i am missing,['php'] +2805,using c to thisplay powerpoint is there any good way to use a windows application written in c to thisplaycontrol a powerpoint slideshow ultimately i would like to show thumbnails in a form and clicking these thumbnails would advance the slides shown on a second monitor similar to using powerpoint itself to show a slideshow on a second monitori would like to be able to use powerpoint viewer if powerpoint is not installedthere seems to be some activexcontrols that allows integration of powerpoint in a form but most of these seem to cost money does anyone have experience using one of these controlsedit i know that there is an object model accessable by adding a reference to microsoftofficeinteroppowerpoint but i want to be able to thistribute the resulting program without having microsoft office as a prerequisite that was why i mentioned powerpoint viewer because it can be thistributed freely,"['c#', '.net']" +2808,how can i create a friendly url in aspnet mvc how do i generate friendly urls within the aspnet mvc framework for example weve got a url that looks like thishttpsitecataloguebrowsebystylelevel1the 1 is id of the study level higher in this case to browse but il like to reformat the url in the same way stackoverflow does itfor example these two urls will take you to the same placeedit the friendly part of the url is referred to as a slug,['c#'] +2809,c little endian or big endian in the documentation of hardware that allows us to control it via udpipi found the following fragmentin this communication protocol dword is a 4 bytes data word is a 2 bytes data byte is a single byte data the storage format is little endian namely 4 bytes 32bits data is stored as d7d0 d15d8 d23d16 d31d24 double bytes 16bits data is stored as d7d0 d15d8i am wondering how this translates to cdo i have to convert stuff before sending it overfor example if i want to send over a 32 bit integer or a 4 character string,['c#'] +2810,random gaussian variables is there a class in the standard library of net that gives me the functionality to create random variables that follow gaussian thistribution,"['c#', '.net']" +2814,which builtin net exceptions can i throw from my application if i need to throw an exception from within my application which of the builtin net exception classes can i use are they all fair game when should i derive my own,"['c#', '.net']" +2817,does java connectionclose rollback does java connectionclose rollback into a finally blocki know net sqlconnectionclose does itwith this i could make tryfinally blocks without catchexampletry connsetautocommitfalse resultset rs executequeryconn executenonqueryconn conncommit finally connclose,['java'] +2821,can i test if a regex is valid in c without throwing exception i allow users to enter a regular expression to match ip addresses for doing an ip filtration in a related system i would like to validate if the entered regular expressions are valid as a lot of userse will mess op with good intentions thoughi can of course do a regexismatch inside a trycatch and see if it blows up that way but are there any smarter ways of doing it speed is not an issue as such i just prefer to avoid throwing exceptions for no reason,['c#'] +2822,how do you keep parents of floated elements from collapsing although elements like divs normally grow to fit their contents using the float property can cause a startling problem for css newbies if floated elements have nonfloated parent elements the parent will collapsefor examplediv div stylefloat leftdiv 1div div stylefloat leftdiv 2divdivthe parent div in this example will not expand to contain its floated children it will appear to have height 0how do you solve this problemi would like to create an exhaustive list of solutions here if youre aware of crossbrowser compatibility issues please point them out solution 1float the parentdiv stylefloat left div stylefloat leftdiv 1div div stylefloat leftdiv 2divdivpros semantic codecons you may not always want the parent floated even if you do do you float the parents parent and so on must you float every ancestor elementsolution 2give the parent an explicit heightdiv styleheight 300px div stylefloat leftdiv 1div div stylefloat leftdiv 2div divpros semantic codecons not flexible if the content changes or the browser is resized the layout will breaksolution 3append a spacer element inside the parent element like thisdiv div stylefloat leftdiv 1div div stylefloat leftdiv 2div div claspacer styleclear bothdivdivpros straightforward to codecons not semantic the spacer div exists only as a layout hacksolution 4set parent to overflow autodiv styleoverflow auto div stylefloat leftdiv 1div div stylefloat leftdiv 2div divpros does not require extra divcons seems like a hack that is not the overflow propertys stated purposecomments other suggestions,"['html', 'css']" +2825,how python web frameworks wsgi and cgi fit together i have a bluehost account where i can run python scripts as cgi i guess it is the simplest cgi because to run i have to define the following in htaccessoptions execcgiaddtype texthtml pyaddhandler cgiscript pynow whenever i look up web programming with python i hear a lot about wsgi and how most frameworks use it but i just do not understand how it all fits together especially when my web server is given apache running at a hosts machine and not something i can really play with except defining htaccess commandshow are wsgi cgi and the frameworks all connected what do i need to know install and do if i want to run a web framework say webpy or cherrypy on my basic cgi configuration how to install wsgi support,['python'] +2830,how would you improve this algorithm c string reversal working through some programming interview challenges i found online i had to write an algorithm to reverse a const char and return a pointer to a new char i think i have it but to make it work properly i had to do some wonky stuff basically having to account for the nullterminating character myself somehow i feel this is wrong but i am stumped and i was wondering if someone could help me outchar reverseconst char str int length strlenstr char reversed string new charlength1 forint i 0 i length i reversed stringi strlength1 i need to null terminate the string reversed stringlength 0 return reversed stringint mainint argc char argv char rev str reversetesting cout your string reversed is this rev str endl delete rev str rev str 0 return 0,['c++'] +2832,crossplatform way of creating safari webarchives i have been searching around and have not found any reference to tools that can create safaris webarchive formatdoes anyone have pointers to code for creating this format or at least a format reference documentationideally i would like to build a tool that takes a directory and splits out a webarchive for loading into a iphone,"['ios', 'iphone']" +2836,dealing with c initialized but not referenced warning for destruction of scope helpers in visual studio i often use objects only for raii purposes for examplescopeguard close guard makeguard close file file the whole purpose of close guard is to make sure that the file will be close on function exit it is not used anywhere else however visual studio gives me a warning that a local variable is initialized but not referenced i want to turn this warning off for this specific casehow do you deal with this kind of situation visual studio thinks that this object is useless but this is wrong since it has a nontrivial destructori wouldnt want to use a pragma warning directive for this since it would turn off this warning even for legitimate reasons,['c++'] +2843,how do i enable doublebuffering of a control using c windows forms how do i enable doublebuffering of a control using c windows formsi have a panel control which i am drawing stuff into and also an ownerdrawn tab control both suffer from flicker so how can i enable doublebuffering,"['c#', '.net']" +2844,a good java library for network math i am looking for a java library that is geared towards network math and already tested nothing particularly fancy just something to hold ips and subnets and do things like print a subnet mask or calculate whether an ip is within a given subnet should i roll my own or is there already a robust library for this,['java'] +2845,in c why cannot a conditional operator implicitly cast to a nullable type i am curious as to why an implicit cast fails inint somevalue somecondition resultofsomecalc nulland why i have to perform an explicit cast insteadint somevalue somecondition resultofsomecalc intnullit seems to me that the compiler has all the information it need to make an implicit casting decision no,['c#'] +2846,how do i check sql replication status via tsql i want to be able to check the status of a publication and subscription in sql server 2008 tsql i want to be able to determine if its okay when was the last successful sync etc is this possible,['sql'] +2847,how to avoid screen flickering when showing form with user drawn controls so the transparent background problem is solved now every time i show the form or have to have it repainted i get a lot of flickering is there any way i can not update the screen until the paint event is complete or any other way to stop the 12 second of flickering and flashing while all the objects are being paintedanswer double buffering is the way to go i was already double buffering on the control but it has to be set on the form i though double buffering only worked when you were subclassing onpaint yourself,"['c#', '.net']" +2854,how to share custom data between iphone applications if i make two iphone applications how canshould i share custom data not contacts and stuff like that among themthanks,['iphone'] +2864,standard file naming conventions in ruby for a file containing the given class somecoolclass what would be the proper or standard filename 1 somecoolclassrb 2 some cool classrb 3 somecoolclassrb 4 somecoolclassrbor some other variationi noticed in the ruby stdlib versions 1 2 and 3 are used,['ruby'] +2868,why matches 127001 i do not understand why does the following regular expressionmatch the string 127001 using regexismatch127001 using expresso it does not match which is also what i would expect using the expression does match the string which i would also expecttechnically should match the beginning of a stringline any number of times followed by the ending of the stringline it seems is implicitly treated as a what am i missingeditrun the following to see an example of the problemusing systemusing systemtextregularexpressionsnamespace regexfubar class program static void mainstring args consolewritelineregexismatch127001 consoleread i do not wish to have match my string i am wondering why it does match it i would think that the expression should result in an exception being thrown or at least a nonmatchedit2to clear up any confusion i did not write this regex with the intention of having it match 127001 a user of our application entered the expression and wondered why it matched the string when it should not after looking at it i could not come up with an explanation for why it matched especially not since expresso and net seems to handle it differentlyi guess the question is answered by it being due to the net implementation avoiding throwing an exception even thought it is technically an incorrect expression but is this really what we want,['c#'] +2870,what code highlighting libs are there for java i would like them to be easy to bundle with few dependencies and easy to use,['java'] +2872,are there any good javascript graphics libraries after staring at this 3d cube and these triangles for a while i started wondering if there is any good reliable javascript graphics library with basic 3d supportany suggestion,['javascript'] +2875,set bufferedimage alpha mask in java i have two bufferedimages i loaded in from pngs the first contains an image the second an alpha mask for the imagei want to create a combined image from the two by applying the alpha mask my googlefu fails mei know how to loadsave the images i just need the bit where i go from two bufferedimages to one bufferedimage with the right alpha channel,['java'] +2878,how do i create 7zip archives with net how can i create 7zip archives from my c console application i need to be able to extract the archives using the regular widely available 7zip programhere are my results with the examples provided as answers to this questionshelling out to 7zexe this is the simplest and most effective approach and i can confirm that it works nicely as workmad3 mentions i just need to guarantee that 7zexe is installed on all target machines which is something i can guarantee7zip in memory compression this refers to compressing cookies inmemory before sending to the client this method seems somewhat promising the wrapper methods wrapping the lzma sdk return type byte when i write the byte array to a file i cannot extract it using 7zip file7z is not supported archive7zsharp wrapper found on codeplex this wraps the 7z exelzma sdk i referenced the project from my app and it successfully created some archive files but i was unable to extract the files using the regular 7zip program file7z is not supported archive7zip sdk aka lzma sdk i guess i am not smart enough to figure out how to use this which is why i posted here any working code examples that demonstrate creating a 7zip archive that is able to be extracted by the regular 7zip programcodeproject c net interface for 7zip archive dlls only supports extracting from 7zip archives i need to create themsharpziplib according to their faq sharpziplib does not support 7zip,"['c#', '.net']" +2882,in php how can i correct missing keys in an array after using array unique an array without the duplicate values is removed however it appears that the keys are also removed which leaves gaps in an array with numerical indexes although is fine for an associative array if i iterate using a for loop i have to account for the missing indexes and just copy the keys to a new array but that seems clumsy,['php'] +2885,option strict on and net for vb6 programmers i am preparing a class on visual basic 2005 targeting visual basic 6 programmers migrating to the net platformi would like a word of advice about whether to recommend them to always enable option strict or noti have worked exclusively with cstyle programming languages mostly java and c so for me explicit casting is something i always expect i have to do since it is never been an optionhowever i recognize the value of working with a language that has builtin support for latebinding because not having to be excessively explicit about types in the code indeed saves time this is further proved by the popular diffusion of dynamic typed languages even on the net platform with the dynamic language runtimewith this in mind should someone who is approaching net for the first time using vbnet and with a vb6 background be encouraged to get into the mindset of having to work with compiletime type checking because that is the best practice in the clr or is it ok to continue enjoying the benefits of latebinding,['.net'] +2887,how to script visual studio 2008 from python i would like to write python scripts that drive visual studio 2008 and visual c 2008 all the examples i have found so far use win32comclientthispatch this works fine for excel 2007 and word 2007 but fails for visual studio 2008import win32comclientapp1 win32comclientthispatch excelapplication okapp2 win32comclientthispatch wordapplication okapp3 win32comclientthispatch msdevapplication errorany ideas does visual studio 2008 use a different string to identify itself is the above method outdated,['python'] +2888,effective copying multiple files i have to copy quite a lot of files from one folder to another currently i am doing it in this waystring files directorygetfilesrootfolder xmlforeach string file in files string otherfile pathcombineotherfolder pathgetfilenamefile filecopyfile otherfileis that the most efficient way seems to take agesedit i am really asking if there is a faster way to do a batch copy instead of copying individual files but i guess the answer is no,"['c#', '.net']" +2892,how to get the new value of an html input after a keypress has modified it i have an html input boxinput typetext idfoo valuebari have attached a handler for the keyup event but if i retrieve the current value of the input box during the event handler i get the value as it was and not as it will bei have tried picking up keypress and change events same problem i am sure this is simple to solve but at present i think the only solution is for me to use a short timeout to trigger some code a few milliseconds in the futureis there anyway to obtain the current value during those eventsedit looks like i had a caching problem with my js file as i checked the same code later on and it worked just fine i would delete the question but not sure if that loses rep for the kind folk who posted ideas,"['javascript', 'html']" +2897,how do you get the height of the titlebar using java swing i am getting a mouseevent in java the getpoint method is adding the height of the title bar into the y portion of the coordinatei was wondering how i can find the height of the title bar of the current window in order to offset the y value by the correct amount,['java'] +2908,html encode user input when storing or when thisplaying simple question that keeps bugging meshould i html encode user input right away and store the encoded contents in the database or should i store the raw values and html encode when thisplayingstoring encoded data greatly reduces the risk of a developer forgetting to encode the data when it is being thisplayed however storing the encoded data will make datamining somewhat more cumbersome and it will take up a bit more space even though that is usually a nonissue,['html'] +2911,java generics returning subtype of declared type from method my class is implementing a superclass method which which returns listjcomponent the list being returned is readonlypublic abstract class superclass public abstract listjcomponent getcomponentsin my class i want to return a field which is declared as list ie a sublistpublic class subclass extends superclass private listjbutton buttons public listjcomponent getcomponents return buttons this generates a compiler error as listjbutton is not a subtype of listjcomponenti can understand why it does not compile as it should not be allowed to add a jtextfield to a list of jbuttonshowever as the list is readonly then conceptually this should be allowed but of course the compiler does not know that it is readonlyis there any way to achieve what i want to achieve without changing the method declaration in the superclass and the field declaration in the subclassthankscalum,['java'] +2912,c optimising binary serialization for multidimensional generic arrays i have a class that i need to binary serialize the class contains one field as belowprivate t m datathese multidimensional arrays can be fairly large hundreds of thousands of elements and of any primitive type when i tried standard net serialization on an object the file written to thisk was large and i think net is storing a lot of repeated data about element types and possibly not as efficiently as could be donei have looked around for custom serializers but have not seen any that deal with multidimensional generic arrays i have also experimented with builtin net compression on a byte array of the memory stream following serializing with some success but not as quick compressed as i had hopedmy question is should i try and write a custom serializer to optimally serialize this array for the appropriate type this seems a little daunting or should i use standard net serialization and add compressionany advice on the best approach would be most appreciated or links to resources showing how to tackle serialization of a multidimensional generic array as mentioned existing examples i have found do not support such structures,"['c#', '.net']" +2913,how do net sites hide aspx extension of their files i am pretty sure stackoverflowcom is created with aspnet but no matter where i click i see no aspx extension in the address barhow it is done and is there a particular reason for this,['asp.net'] +2914,how can i relax phps open basedir restriction open basedir limits the files that can be opened by php within a directorytreei am storing several class libraries and configuration files outside of my web root directory this way the web server does not make them publicly accessible however when i try to include them from my application i get an open basedir restriction error like thiswarning realpath functionrealpath open basedir restriction in effect filevarwvhostsdomaintldzendapplication is not within the allowed paths varwvhostsdomaintldhttpdocstmp in varwvhostsdomaintldhttpdocsindexphp on line 5my web root is herevarwvhostsdomaintldhttpdocsmy libraries and configuration directory are herevarwvhostsdomaintldzendwhat would be the best workaround to relax the open basedir restriction so that the the directory tree under the domain folder becomes available to my application i have a number of domains that i want to do this with and i am also obviously wary of creating security vulnerabilitiesnote i am using centos apache plesk and i have root ssh access to the server and though this does not apply to zend framework directly i am using it in this instance so here is the inclusion from zends bootstrapdefineapplication path realpathdirname file zendapplicationset include pathapplication path zendlibrary path separator get include path,['php'] +2915,how much javascript do you let rails generate ruby on rails has a lot of ways to generate javascript particularly when it comes to ajax unfortunately there are a few problems that i often see with the javascript that it generates rails typically uses inline event handlinga onclicksomejavascript return false this is generally frowned upon as it is mixing behavior in with the xhtml the generated javascript also relies heavily on prototype personally i prefer jquery in my experience the attitude with a lot of rails developers has been to write as much of the code in ruby as possible the final step being to generate some very procedural and repetitive javascript often this code ends up being very inflexible and difficult to debugso my question is how much javascript do you write manually for your projects and how much of it is generated server side with railsruby or is there a happy medium where you get the benefits of both with a subquestion if you write a lot of the javascript manually what techniques do you use to fit it into the mvc model,"['javascript', 'ruby-on-rails', 'ruby']" +2917,how do i perform query filtering in django templates i need to perform a filtered query from within a django template to get a set of objects equivalent to python code within a viewqueryset modelclassobjectsfiltersomekeyfooin my template i would like to do for object in datasomekey setfilter but i just cannot seem to find out how to write filter,['python'] +2923,log4net with aspnet 35 problems i am having some trouble getting log4net to work from aspnet 35 this is the first time i have tried to use log4net i feel like i am missing a piece of the puzzlemy project references the log4net assembly and as far as i can tell it is being deployed successfully on my servermy webconfig contains the following configsections section namelog4net typelog4netconfiglog4netconfigurationsectionhandler log4net requirepermissionfalse configsections log4net appender nameinfoappender typelog4netappenderfileappender file valuelogsinfologhtml appendtofile valuetrue layout typelog4netlayoutpatternlayout conversionpattern valued t 5p c x mn layout appender logger name default level valueinfo appenderref refinfoappender logger log4neti am using the following code to test the loggerusing log4netusing log4netconfigpublic partial class default systemwebuipage private static readonly ilog log logmanagergetlogger default protected void page loadobject sender eventargs e loginfohello logging world in my globalasax i am doing the followingvoid application startobject sender eventargs e log4netconfigxmlconfiguratorconfigureat this point i cannot think of what else i might be doing wrong the directory i am trying to store the log in is writable and even if i try different directories i get the same result no file no logsany suggestions edit i have tried several different formats for the path name of the log file some of which include infologhtml infologhtml logsinfologhtml etc just in case someone is wondering if that is the problemedit i have added the root logger node back into the log4net section i ommitted that on accident when copying from the samples the root logger node looks like thisroot level valueinfo appenderref refinfoappender rooteven with it however i am still having no luck,['asp.net'] +2927,how does edit and continue work in visual studio i have always found this to be a very useful feature in visual studio for those who do not know about it it allows you to edit code while you are debugging a running process recompile the code while the binary is still running and continue using the application seamlessly with the new code without the need to restart ithow is this feature implemented if the code i am modifying is in a dll loaded by the application does the application simply unload the dll and reload it again this would seem to me like it would be prone to instability issues so i assume it would be smarter than this any ideas,['c++'] +2930,tips for writing fluent interfaces in c 3 i am after some good tips for fluent interfaces in c i am just learning about it myself but keen to hear what others think outside of the articles i am reading in particular i am afterwhen is fluent too muchare there any fluent patternswhat is in c that makes fluent interfaces more fluent eg extension methodsis a complex fluent interface still a fluent onerefactoring to arrive at a fluent interface or refactoring an existing fluent interfaceany good examples out there that you have worked with or could recommendif you could post one tip or thought or whatever per post i want to see how they get voted on toothank you in advance,['c#'] +2931,how can i pass arguments to anonymous functions in javascript i am trying to figure out how to pass arguments to an anonymous function in javascriptcheck out this sample code and i think you will see what i meaninput typebutton valueclick me idmybutton script typetextjavascript var mybutton documentgetelementbyidmybutton var mymessage it is working mybuttononclick functionmymessage alertmymessage scriptwhen clicking the button the message it is working should appear however the mymessage variable inside the anonymous function is nulljquery uses a lot of anonymous functions what is the best way to pass that argument,"['javascript', 'jquery']" +2934,how to stop ie asking which debugger to choose when trying to debug when debugging in internet explorer i first get an alert box with extremely limited if not useless information sorry ie and choice to debug it after selecting yes i get another option every time to chose between new instance of microsoft script debugger and new instance of visual studio i am fed up of having to click the yes button again after having clicking it once already on the alert boxupdate i found that you can thisable the microsoft script debugger from within its own options just thisabling the jit debugger from tools options and jit this stops it appearing on the menu but now i get the dialog box asking me which one to choose and it only thisplays the one visual studio why if there is only one option and youve already asked me if i want to debug why ask again blehcan you tell i am getting sick of clicking yes twice lol,['javascript'] +2938,are there any pitfalls things you need to know when changing from myisam to innodb one of my projects use the myisam engine in mysql but i am considering changing it to innodb as i need transaction support here and therewhat should i look at or consider before doing this can i just change the engine or should the data be prepared for it,['mysql'] +2939,removing duplicate images we have a collection of photo images sizing a few hundred gigs a large number of the photos are visually duplicates but with differing filesizes resolution compression etc is it possible to use any specific image processing methods to search out and remove these duplicate images,['c#'] +2940,how to generate empty definitions given a header file i have a 3rdparty library which for various reasons i do not wish to link against yet i do not want to butcher my code though to remove all reference to its api so i would like to generate a dummy implementation of itis there any tool i can use which spits out empty definitions of classes given their header files it is fine to return nulls false and 0 by default i do not want to do anything onthefly or anything clever the mock object libraries i have looked at appear quite heavyweight ideally i want something to use like generatedefinition my headerh dummy implemtationcppi am using linux gcc41,['c++'] +2941,how to load a net assembly for reflection operations and subsequently unload it i am writing a tool to report information about net applications deployed across environments and regions within my clients systemsi would like to read the values of assembly attributes in these assembliesthis can be achieved using assemblyreflectiononlyload however even this approach keeps the assembly loaded the issue here is that i cannot load two assemblies that have the same name from different paths so naturally i cannot compare the same application deployed in different systemsat this point i am assuming the solution will involve using temporary appdomainscan someone detail how to load an assembly into another appdomain read the attributes from it and then unload the appdomainthis needs to work for assemblies on the file system as well as those at url addresses,['.net'] +2948,is it good to include title within your links i am developing a website and for the main navigation i was thinking it would be a good idea to include the title attributea hrefresults titleresultsresultsais this a good thing to do also is it good for seo and accessibility,['html'] +2952,syntax highlighting when pasting into emails im in the situation that i often send small codesnippets and xmlsnippets to coworkers and partners via my outlook has anyone got a good idea or tool that i can use to have my pastes syntaxhighlighted before i paste them into an emaili was thinking of an intermediate paste to fancytool and then i would have something to copy that will htmlified so i can copy paste it into the compose email windoweditmoreinfoim pasting from windows within a vmware virtual machine it might be eclipse xmlspy logfiles and other programsevenmoreinfoi have seen this link how to do it from vim unfortunately it seldom from vim im copying code and my email machine hasnt got any vim the vmware machines has gvim but i was hoping for an easier way that pasting to vim saving to file opening in internetexplorer and then copypaste,['html'] +2955,how do i specify values in a properties file so they can be retrieved using resourcebundlegetstringarray i am trying to use resourcebundlegetstringarray to retrieve a string from a properties file the description of this method in the documentation readsgets a string array for the given key from this resource bundle or one of its parentshowever i have attempted to store the values in the properties file as multiple individual keyvalue pairskeyvalue1keyvalue2keyvalue3and as a commadelimited listkeyvalue1value2value3but neither of these is retrievable using resourcebundlegetstringarrayhow do you represent a set of keyvalue pairs in a properties file such that they can be retrieved using resourcebundlegetstringarray,['java'] +2962,c attribute to trigger an event on invoking a method is there a way in c or net in general to create an attribute on a method which triggers an event when a method is invoked ideally i would be able to run custom actions before and after the invocation of the methodi mean something like thistriggersmycustomactionpublic void dosomestuffi am totally clueless how to do it or if it possible at all but systemdiagnosticconditionalattribute might do a similar thing in the background i am not sure thoughedit i forgot to mention that due to the circumstances of my specific case performance is not really an issue,"['c#', '.net']" +2964,django forms how to use prefix parameter say i have a form likeclass generalformformsform field1 formsintegerfieldrequiredfalse field2 forms integerfieldrequiredfalseand i want to show it twice on a page within one form tag each time with a different prefix egrest of page form generalformdataprefixform1as tablegeneralformdataprefixform2as tableinput typesubmit formrest of page when the user submits this how do i get the submitted form back into two separate forms to do validation and rethisplay itthis was the only documentation i could find and it is peckish,"['python', 'html']" +2965,what is the best tool for build automation for a oneman software shop i am building windows apps for a few clients i read joel on software and took the joel test and realized i do not quite measure up one place i am lacking is automated builds what should i use to have automated builds i have windows apps that use net 11 20 and 35 also i need to be able to build my vdproj to create msis i am looking for something that is free and would work well for a oneman team,['.net'] +2971,how to sanity check a date in java i find it curious that the most obvious way to create date objects in java has been deprecated and appears to have been substituted with not so obvious to use lenient calendar sohow do you check that a date given as a combination of day month and year is a valid date for instance a date 20080231 as in ymmdd would be invalid date,['java'] +2976,c speech recognition is this what the user said i have need to write an application which uses a speech recognition engine either the built in vista one or a third party one that can thisplay a word or phrase and recognise when the user reads it or an approximation of it i also need to be able to switch quickly between languages without changing the language of the operating systemthe users will be using the system for very short periods the application needs to work without the requirement of first training the recognition engine to the users voicesit would also be fantastic if this could work on windows xp or lesser versions of windows vistaoptionally the system needs to be able to read information on the screen back to the user in the users selected language i can work around this specification using prerecorded voiceovers but the preferred method would be to use a texttospeech enginecan anyone recommend something for me,['c#'] +2979,software protection by encryption for our software we use hardware dongles to protect the software no protection is perfect but this commercial solution is affordable and keeps honest people honest as mentioned in another thread the advantage is the 128 bit key that is stored unreadable on the hardware dongle we want to remove this hardware dongle and start using software protection basically we can use a commercial product but on the other hand that would not be unbreakable either i do not know much about encryption and that is why i am posting this how do i store a key on a windows computer that will not be possible to read by using reflector or something else however i should be able to access the key for testing the license codei would just like a simple solution that cannot be hacked by simply using reflectoror am i asking a very stupid questionthank you all for your very fast and useful replies i do not want to use licensing over the internet since the application is running not always on computers that are connected i will then get probably more problems then solving them we will now most probably go for a commercial solution it seems that protection is not that trivial thanks a lot,['.net'] +2984,jstl beans and method calls i am working on a jsp where i need to call methods on object that come from a bean the previous version of the page does not use jstl and it works properly my new version has a set up like thisjspusebean idpagebean scoperequest typecomepicentricpagewebsitepagebean cset varpagedividers value pagebeangetpagedividers cset varnumcolumns valuepagedividerssize the variable pagedividers is a list objecti am encountering this issue when i ask for pagedividers size an exception is thrown i know this is a simple jtsl error what am i doing wrongthe error message isthe function size must be used with a prefix when a default namespace is not specifiedhow do i correctly access or call the methods of my pagedividers object,['java'] +2986,unique identifier for an iphone app for an iphone app that submits images to a server i need somehow to tie all the images from a particular phone together with every submit i would like to send some unique phone id looked at uidevice maindevice uniqueidentifierand nsuserdefaults standarddefaults stringforkeysbformattedphonenumberbut getting errors in the simulatoris there an apple sanctioned way of doing this,['iphone'] +2989,passing a list while retaining the original so i am teaching myself python and i am having an issue with lists i want to pass my function a list and pop items off it while retaining the original list how do i make python instance the passed list rather that passing a pointer to the original oneexampledef burninateb c for i in range3 cappendbpop return ca range6d burninateaprint a doutput 0 1 2 5 4 3desired output 0 1 2 3 4 5 5 4 3thanks,['python'] +2991,programatic accent reduction in javascript aka text normalization or unaccenting i need to compare 2 strings as equal such as theselubeck la14beckin javascriptwhy well i have an autocompletion field that is going out to a java service using lucene where place names are stored naturally as la14beck but also indexed as normalized text import suntextnormalizerodocsetnamelc normalizernormalizeolocname normalizerdecomp 0 tolowercasereplaceallpasciithis way someone who does not know to type ma xico can type mexico and get a match which returns ma xico among a lot of other possible hits like cafa ma xico dubai uaenow the thing is i do not have the ability to change the service to do any highlighting on the server side therefore i am highlighting on the client javascript side with something likereturn resultreplace inputreplaceaeioug b1bit is a little more fancy because i am escaping special regex characters in the input this is fine for simple one word matches at the beginning of a hit but it really breaks down if you suddenly wish to support multiword matches like london cafeinput inputstriptolowercase fyi prototypes strip is like trimre new regexinputreplaceaeiougreplacesggireturn resultreplacere b1bthis does not work for say london ca was typing london cafe because it would mark jack london cabin dawson city canada as jabckb blondonb bcabbin dawson bcibty bcabnada note the ck and ci particularlytherefore i am sort of looking for something that is not as crazy asinput inputstriptolowercaseinput inputreplaceagaa ainput inputreplaceegaa a ditto for i o u y c n maybe also d g h j k l r s t w z re new regexinputreplacesggireturn resultreplacere b1bis there a compiled table i can refer to mapping a range of characters which are accented versions of an other character to that character by which i do not mean the plain unicode chart and if so could i avoid using weird possibly slow regex statementsabout the bountybefore i started a bounty there were two answers the one pointing me to doing it in ruby and the one that mizzardx wrote which was a completion of the basic form i would put in my question now do not get me wrong i really appreciate working it out as completely as he did but i just wished that there might be another way it seems so far that everyone whos dropped by to look at the question and answer has decided that mizzardx covers it just fine or that they have no different approach i would be interested in a different approach and if it simply is not available before the bounty closes mizzardx will win the bounty though in a cruel twist his edits mad it a community wiki answer so i am not sure if he will get the bounty,['javascript'] +2999,garbage collection in c why i keep hearing people complaining that c does not have garbage collection i also hear that the c standards committee is looking at adding it to the language i am afraid i just do not see the point to it using raii with smart pointers eliminates the need for it rightmy only experience with garbage collection was on a couple of cheap eighties home computers where it meant that the system would freeze up for a few seconds every so often i am sure it has improved since then but as you can guess that did not leave me with a high opinion of itwhat advantages could garbage collection offer an experienced c developer,['c++'] +3001,how do i iterate through a string in python as an example lets say i wanted to list the frequency of each letter of the alphabet in a string what would be the easiest way to do itthis is an example of what i am thinking of the question is how to make alltheletters equal to said letters without something like alltheletters abcdefgxyz in many other languages i could just do letter and increment my way through the alphabet but thus far i have not come across a way to do that in pythondef alphcounttext lowertext textlower for letter in alltheletters print letter lowertextcountletter,['python'] +3003,jquery resize not working at firefox chrome and safari dvmydivbindresize function alertresizedordvmydivresizefunction alertresizedthe questionswhy is this not working at firefox chrome and safarican this be considered a jquery bug since the resize is not handled for other browserscould the only workaround be calling a settimeout function checking the clientheight and clientwidthany workarounds using jquery,['jquery'] +3004,class methods as event handlers in javascript is there a bestpractice or common way in javascript to have class members as event handlersconsider the following simple examplehead script languagejavascript typetextjavascript clickcounter functionbuttonid this clickcount 0 documentgetelementbyidbuttonidonclick thisbuttonclicked clickcounterprototype buttonclicked function this clickcount alertthe button was clicked this clickcount times scriptheadbody input typebutton idbtn1 valueclick me script languagejavascript typetextjavascript var btn1counter new clickcounterbtn1 scriptbodythe event handler buttonclicked gets called but the clickcount member is inaccessible or this points to some other objectany good tipsarticlesresources about this kind of problems,"['javascript', 'html']" +3016,php syntax highlighting i am searching for a php syntax highlighting engine that can be customized ie i can provide my own tokenizers for new languages and that can handle several languages simultaneously ie on the same output page this engine has to work well together with css classes ie it should format the output by inserting span elements that are adorned with class attributes bonus points for an extensible schemai do not search for a clientside syntax highlighting script javascriptso far i am stuck with geshi unfortunately geshi fails abysmally for several reasons the main reason is that the different language files define completely different inconsistent styles i have worked hours trying to refactor the different language definitions down to a common denominator but since most definition files are in themselves quite bad i would finally like to switchideally i would like to have an api similar to coderay pygments or the javascript dpsyntaxhighlighterclarificationi am looking for a code highlighting software written in php not for php since i need to use it from inside php,['php'] +3026,has anyone used or written an ant task to compile rhino javascript to java bytecode i would like to use the rhino javascript compiler to compile some javascript to class bytecode files for use in a project it seems like this should already exist since there are groovyc netrexxc and jythonc tasks for groovy netrexx and jython respectively has anyone used or written such an ant task or can anyone provide some tips on how to write oneideally it would have some way to resolve dependencies among javascript or java classes,"['java', 'javascript']" +3031,what does a type followed by t underscoret represent this seems like a simple question but i cannot find it with the stack overflow search or google what does a type followed by a t mean such asint t aninti see it a lot in c code meant to deal closely with hardwareai cannot help but think that they are related,['c'] +3032,net compact framework and activesync is there a way that my net cf app running on a windows ce device can know when the device is dockedsynced with the pc,['.net'] +3036,c parent class calling a child virtual function i want a pure virtual parent class to call a child implementation of a function like soclass parent public void read read stuff virtual void process 0 parent read process class child public parent public virtual void process process stuff child parent int main child cthis should work but i get an unlinked error this is using vc 2k3or should not it work am i wrong,['c++'] +3047,cannot import sqlite with python 26 i am running python 26 on unix and when i run the interactive prompt sqlite is supposed to be preinstalled i getrootidev htdocs pythonpython 26 r26714 oct 23 2008 162534gcc 322 200302 red hat linux 3225 on linux2type help copyright credits or license for more information import sqlitetraceback most recent call lastfile stdin line 1 in moduleimporterror no module named sqlitehow do i resolve this,['python'] +3054,colorize logs in eclipse console is there a way to colorize parts of logs in the eclipse console i know i could send to error and standard streams and color them differently but i am more looking someting in the lines of ansi escape codes or anyother html where i could embed the colors in the string to have it colored in the logsit sure would help making the important bits stand out without resorting to weird layout rather keep the layout to the log4j setups here is an example of what i am looking for info the grid is complete falsewhere the bold parts would be in blue this coloring can be controlled by the application to an extent like so tags are conceptual and arbitrary but you get the idealoginfostringformatthe grid is complete bluesblue iscomplete on a more general note it is the ability to embed meta information in the logs to help the presentation of these logs much like we tag web pages content to help the presentation of the information by css,['java'] +3056,how can i create a copy of an oracle table without copying the data i know the statementcreate table xyz new as select from xyzwhich copies the structure and the data but what if i just want the structure,['sql'] +3061,can anyone explain servlet mapping i am trying to write a web application using springmvc normally i would just map some madeup file extension to springs front controller and live happily but this time i am going for restlike urls with no filename extensionsmapping everything under my context path to the front controller let us call it app means i should take care of static files also something i would rather not do why reinvent yet another weel so some combination with tomcats default servlet let us call it tomcat appears to be the way to goi got the thing to work doing something like servletmapping servletnameappservletname urlpatternurlpatternservletmappingservletmapping servletnametomcatservletname urlpatternexturlpatternservletmappingand repeating the latter for each one of the file extensions of my static content i am just wondering why the following setups which to me are equivalent to the one above do not work failed attempt 1 servletmapping servletnameappservletname urlpatternurlpatternservletmappingservletmapping servletnametomcatservletname urlpatternexturlpatternservletmapping failed attempt 2 servletmapping servletnameappservletname urlpatternurlpatternservletmappingservletmapping servletnametomcatservletname urlpatternsomestaticcontentfolderurlpatternservletmappingcan anyone shed some light,['java'] +3063,bindingflags for typegetmethods excluding property accesors suppose i have got the following programnamespace reflectiontest public class example private string field public void methodone public void methodtwo public string property get return field set thisfield value class program static void mainstring args iteratetypeofexample consolereadline public static void iteratetype type methodinfo methods typegetmethods bindingflagsdeclaredonly bindingflagsinstance bindingflagspublic foreach methodinfo mi in methods consolewritelineminame when i run the program i am getting the following outputmethodonemethodtwoget propertyset propertyi want to skip the property accesor methods i have tried with different bindingflags for instance bindingflagssetproperty but with no luck at the moment the only way i have found to skip those methods is rewriting the iterate function topublic static void iteratetype type methodinfo methods typegetmethods bindingflagsdeclaredonly bindingflagsinstance bindingflagspublic foreach methodinfo mi in methods if miisspecialname continue consolewritelineminame do you know what bindingflags should i usethank you very muchupdatewell i should have explained that the project is actually for building automatically templates for unit testing so i can skip all the special methods thanks for the additional information on isspecialname linq really wow anyway this project is net 20 so linq is sadly not an option,['.net'] +3067,can i use classnewinstance with constructor arguments i would like to use classnewinstance but the class i am instantiating does not have a nullary constructor therefore i need to be able to pass in constructor arguments is there a way to do this,['java'] +3071,whats the uitableview index magnifying glass character in apples iphone apps like contacts they have a nice magnifying glass icon at the top of the table view index since the table view index api is characterbased i assume that this magnifying glass is a unicode character so far i have resorted to placing a question mark character there but that looks lamecan anyone tell me what character the magnifying glass is,['iphone'] +3073,what are the benefits of maintaining a clean list of using directives in c i know vs2008 has the remove and sort function for cleaning up using directives as does resharper apart from your code being clean and removing the problem of referencing namespaces which might not exist in the future what are the benefits of maintaining a clean list of using directivesless codefaster compilation times,['c#'] +3075,what is the scope of a function in javascriptecmascript today i had a thiscussion with a colleague about nested functions in javascriptfunction a function b alertboo var c bound to local call object d bound to global objectin this example trials point out that b is not reachable outside the body of a much like c is however d is after executing a looking for the exact definition of this behaviour in the ecmascript v3 standard i did not find the exact wording i was looking for what sec13 p71 does not say is which object the function object created by the function declaration statement is to be bound to am i missing something,['javascript'] +3089,php script version checkingnotification how can i check the version of my script against an online file to see if it is the latest versionfor clarification i am talking about a script i wrote not the version of php i would like to incorporate a way for the end user to tell when i have updated the script,['php'] +3092,any smalltalk on net are there any usable implementations of smalltalk for the net runtime,['.net'] +3093,using the typical get set properties in c with parameters i would like to do the same in c is there anyway of using properties in c with parameters in the same way i have done with the parameter key in this vbnet exampleprivate shared m dictionary as idictionaryof string object new dictionaryof string objectpublic shared property dictionaryelementbyval key as string as object get if m dictionarycontainskeykey then return m dictionarykey else return stringempty end if end get setbyval value as object if m dictionarycontainskeykey then m dictionarykey value else m dictionaryaddkey value end if end setend propertythanks,['c#'] +3101,how can i change the animation style of a modal uiviewcontroller i am currently thisplaying a uiviewcontroller like thisself navigationcontroller presentmodalviewcontrollermodalviewcontroller animatedyesand hiding it like thisselfnavigationcontroller thismissmodalviewcontrolleranimatedyesthe animation is slide up from the bottom then slide back down how can i change the animation style can i made it fade inoutcheers,['iphone'] +3102,how to solve var out of scope within settimeout call i am trying to call a settimeout from within a setinterval callbackfunction callback assign myvar var myvar documentgetelementbyidgivenid now wait 2 secs then call some code that uses myvar settimeoutmyvarinnerhtml test 20setintervalcallback 10setinterval works as expected but settimeout call is failing i guess the problem is related to the fact that i am referencing a variable myvar that is not in scopewhats the best way to solve this,['javascript'] +3103,does stdsize t make sense in c in some code i have inherited i see frequent use of size t with the std namespace qualifier for examplestdsize t and sizeof long it compiles and runs fine of course but it seems like bad practice to me perhaps carried over from cis not it true that size t is built into c and therefore in the global namespace is a header file include needed to use size t in canother way to ask this question is would the following program with no includes be expected to compile on all c compilerssize t foo return sizeof long,['c++'] +3105,fulltext search relevance is measured in i am making a quiz system and when quizmakers insert questions into the question bank i am to check the db for duplicate very highly similar questionstesting mysqls match against the highest relevance i get is 30 when i test against a 100 similar stringso what exactly is the relevance to quote the manualrelevance values are nonnegative floatingpoint numbers zero relevance means no similarity relevance is computed based on the number of words in the row the number of unique words in that row the total number of words in the collection and the number of documents rows that contain a particular word my problem is how to test the relevance value if a string is a duplicate if it is 100 duplicate prevent it from being inserter into question bank but if it is only so similar prompt the quizmaker to verify insert or not so how do i do that 30 for 100 identical string is not percentage so i am stumpthanks in advance,['mysql'] +3106,how do i do inline assembly on the iphone how is it done what steps do i need to take and what pitfalls and gotchas are there to consider,['iphone'] +3115,how can i support wildcards in userdefined search strings in python is there a simple way to support wildcards when searching strings without using regexusers are supposed to enter search terms using wildcards but should not have to deal with the complexity of regexfoo strstartswithfoofoo strendswithfoofoo foo in strit gets more complicated when there are multiple search terms though eg foobarbazthis seems like a common issue so i wonder whether there is a readymade solution for itany help would be greatly appreciated,['python'] +3116,how do i associate a nib xib file with a uiview i have a subclass s of uiview i want to put some buttons and labels on s how do i associate my uiview subclass with a nib file,['iphone'] +3118,difference of two uint when you attempt to declare an unsigned variable in cnet with a value outside its value range it is flagged as a compiler error but if you produce a negative value at runtime and assign it to that variable at runtime the value wrapsuint z 1 will not compileuint a 5uint b 6uint c a b will result in uintmaxvalueis there a good reason why unsigned variables wrap in such a situation instead of throwing an exceptionthanks,"['c#', '.net']" +3123,how do i calculate the elapsed time of an event in java whats a simpleeasy way to access the system clock using java so that i can calculate the elapsed time of an event,['java'] +3124,how to change the name of an ios app i began an iphone project the other day with a silly development code name and now i want to change the name of the project since it is nearly finished but i am not sure how to do this with xcode trying the obvious of changing the applications name in the infoplist file causes the signing process to go wrong i think and my app would not launch giving me a launcher errori guess i could make a new project and copy paste everything over but it seems so primitive that i am hoping for a more civilized solution,['ios'] +3125,how can i call a dll from a scripting language i have a thirdparty product a terminal emulator which provides a dll that can be linked to a c program to basically automate the driving of this product send keystrokes detect whats on the screen and so forthi want to drive it from a scripting language i am comfortable with python and slightly less so with perl so that we do not have to compile and send out executables to our customers whenever there is a problem foundwe also want the customers to be able to write their own scripts using ours as baselines and they would not entertain the idea of writing and compiling c codewhats a good way of getting pythonperl to interface to a windows dll my first thought was to write a server program and have a python script communicate with it via tcp but there is got to be an easier solution,['python'] +3128,which is the best alternative for java serialization i am currently working on a project which needs to persist any kind of object of which implementation we do not have any control so these objects could be recovered afterwards we cannot implement an orm because we cannot restrict the users of our library at development timeour first alternative was to serialize it with the java default serialization but we had a lot of trouble recovering the objects when the users started to pass different versions of the same object attributes changed types names we have tried with the xmlencoder class transforms an object into a xml but we have found that there is a lack of functionality does not support enums for example finally we also tried jaxb but this impose our users to annotate their classesany good alternative,['java'] +3134,when should i use primitives instead of wrapping objects actually here is a similar topic with little practical valueas far as i understand primitives perform better and should be used everywhere except for the cases where objectrelated features eg null check are needed right,['java'] +3140,how can i wrap a method so that i can kill its execution if it exceeds a specified timeout i have a method that i would like to call however i am looking for a clean simple way to kill it or force it to return if it is taking too long to executei am using javato illustrateloggerinfosequentially executing all batchesfor testexecutor executor buildergetexecutors loggerinfoexecuting batchexecutorexecutei figure the testexecutor class should implement callable and continue in that directionbut all i want to be able to do is stop executorexecute if it is taking too longsuggestionseditmany of the suggestions received assume that the method being executed that takes a long time contains some kind of loop and that a variable could periodically be checkedhowever this is not the case so something that would not necessarily be clean and that will just stop the execution whereever it is is acceptable,['java'] +3142,transfer variables between php pages i want to get user input in one page store that in a php variable and use it in another php page i have tried using sessions but it does not seem to be working is there another safe alternative this information is likely to be usernames and passwords,['php'] +3143,convert a string to gregoriancalendar i have a string from an email header like date mon 27 oct 2008 083329 0700 what i need is an instance of gregoriancalendar that will represent the same moment as easy as that how do i do itand for the fastest ones this is not going to work properlysimpledateformat format whatever you wantdate date formatparsemystringgregoriancalendar calendar new gregoriancalendarcalendarsettimedatebecause it will normalize the timezone to utc or your local machine time depending on java version what i need is calendargettimezonegetrawoffset to return 7 milisinanhour,['java'] +3144,in php how do you change the key of an array element i have an associative array in the form key value where key is a numerical value however it is not a sequential numerical value the key is actually an id number and the value is a count this is fine for most instances however i want a function that gets the humanreadable name of the array and uses that for the key without changing the valuei did not see a function that does this but i am assuming i need to provide the old key and new key both of which i have and transform the array is there an efficient way of doing this,['php'] +3146,aspnet usercontrol loadcontrol issue i am having an issue when using loadcontrol type params let me explaini have a super simple user control ascx control languagec autoeventwireuptrue inheritserrorthisplay codebehinderrorthisplayascxcs enableviewstatefalse asplabel runatserver idlbltitle asplabel runatserver idlbldescription with code c behind ofpublic partial class errorthisplay systemwebuiusercontrol private message errormessage public errorthisplay public errorthisplaymessage errormessage errormessage errormessage protected override void onprerendereventargs e baseonprerendere if errormessage null lbltitletext errormessagemessage lbldescriptiontext errormessagedescription elsewhere in my web application i am adding an instance of the usercontrol to the page using the following codedivvalidationissuescontrolsaddloadcontroltypeoferrorthisplay new object messagedetails i am using the overloaded version of loadcontrol because i want to pass the message parameter to the constructor all this appears to work okhowever when the onprerender is fired on the errorthisplay usercontrol the lbltitle and lbldescription variables are both null despite them having a markup equivalent the message variable has been correctly populatedcan anyone shed any light on why this may be happeningthankseditjust for clarity i will also add that the code which is programatically adding the usercontrol to the page is running in response to a button press so the hosting page has progressed through init page load and is now processing the event handlersi cannot add the usercontrols at an earlier asp lifecycle stage as they are being created in response to a button click event,['asp.net'] +3150,how to manually drop down a datagridviewcomboboxcolumn i have a datagridview with one datagridviewcomboboxcolumn in my winforms application i need to drop down open this datagridviewcomboboxcolumn manually let us say after a button is clickedthe reason i need this is i have set selectionmode to fullrowselect and i need to click 23 times to open the combo box i want to click on the combobox cell and it should drop down immediately i want to do this with cellclick event or is there any other wayi am searching in google and vs help but i have not found any information yetcan anybody help please,['.net'] +3154,single table inheritance in django is there explicit support for single table inheritance in django last i heard the feature was still under development and debate are there librarieshacks i can use in the meantime to capture the basic behavior i have a hierarchy that mixes different objects the canonical example of a corporation structure with an employee class subclasses for types of employees and a manager id parent id would be a good approximation of the problem i am solving in my case i would like to represent the idea that an employee can manage other employees while being managed by a different employee there are not separate classes for manager and worker which makes this hard to spread across tables subclasses would represent types of employeesprogrammers accountants sales etc and would be independent of who supervises who ok i guess it is no longer a typical corporation in some respect,['python'] +3159,auto start print html page using javascript is there anyway to automatically run javascriptwindowprint when the page finishes loading,"['javascript', 'html']" +3170,copying content from a hidden or clipped window in xp i need to copy the content of a window bitblt which is hidden to another window the problem is that once i hide the source window the device context i got is not painted anymore,['c'] +3177,how to set the pythonpath in emacs emacs does not recognize my correct python path i think it is a general problem with emacs not recognizing my environment variables i have gnu emacs 2211 i386appledarwin891 carbon version 160 of 20070617 installedi have set the pythonpath in my bashrc maybe i should set it somewhere else,['python'] +3181,what are some useful php idioms i am looking to improve my php coding and am wondering what phpspecific techniques other programmers use to improve productivity or workaround php limitationssome examplesclass naming convention to handle namespaces part1 part2 classname maps to file part1part2classnamephpif countarrayname handles arrayname being unset or emptyvariable function names eg func foo funcbar calls foobar,['php'] +3182,oracle plsql query order by issue with thistinct does anyone know what is wrong with this query select thistinct ccn as claimnumber aitemdate as billreceiveddate cdtn as doctracknumber from itemdata a itemdatapage b keygroupdata c where aitemtypenum in 112 113 116 172 189 and aitemnum bitemnum and bitemnum citemnum order by adatestored desci have done tsql most of my career and this looks correct to me however this query is for an oracle database and toad just places the cursor on the adatestored in the order by section i am sure this is elementary for anyone doing plsqlthanksedit for future reference the error given by sqlplus was ora01791 not a selected expression,['sql'] +3192,creating a systemwebcachingcache object in a unit test i am trying to implement a unit test for a function in a project that does not have unit tests and this function requires a systemwebcachingcache object as a parameter i have been trying to create this object by using code such assystemwebcachingcache cache new systemwebcachingcachecacheaddand then passing the cache in as a parameter but the add function is causing a nullreferenceexception my best guess so far is that i cannot create this cache object in a unit test and need to retrieve it from the httpcontextcurrentcache which i obviously do not have access to in a unit testhow do you unit test a function that requires a systemwebcachingcache object as a parameter,"['c#', 'asp.net']" +3200,what do parentheses in a c variable declaration mean can someone explain what this meansint data22,['c'] +3202,ajax console window with ansivt100 support i am planning to write gateway web application which would need terminal window with vt100ansi escape code support are there any ajax based alternatives for such a taski am thinking something like this my preferred backend for the system is pythontwistedpylons but since i am just planning i will explore every option,['python'] +3206,variable limit clause in mysql i am writing a stored procedure where i have an input parameter called my size that is an int i want to be able to use in a limit clause in a select statement apparently this is not supported is there a way to work around this i want something likeselect from some table limit my size instead of hardcoding a permanent limitselect from some table limit 100,['mysql'] +3211,which variables should i typecast when doing math operations in cc for example when i am dividing two ints and want a float returned i superstitiously write something like thisint a 2 b 3float c floata floatbif i do not cast a and b to floats it will do integer division and return an intsimilarly if i want to multiply a signed 8bit number with an unsigned 8bit number i will cast them to signed 16bit numbers before multiplying for fear of overflowu8 a 255s8 b 127s16 s16a s16bhow exactly does the compiler behave in these situations when not casting at all or when only casting one of the variables do i really need to explicitly cast all of the variables or just the one on the left or the one on the right,"['c++', 'c']" +3225,detect when javascript is thisabled in aspnet in the render method of an aspnet webcontrol i need to alter the output of the html based on whether javascript is enabled or thisabled on the clients browserdoes anyone know the right incantation to figure that out,"['asp.net', 'javascript']" +3226,how do i find a users active directory thisplay name in a c web application i am writing a web application which uses windows authentication and i can happily get the users login name using something like string login useridentitynametostringbut i do not need their login name i want their thisplayname i have been banging my head for a couple hours nowcan i access my organisations ad via a web application,['c#'] +3228,how to implement a singleton in c how do i implement the singleton pattern in c i want to put my constants and some basic functions in it as i use those everywhere in my project i want to have them global and not need to manually bind them every object i create,"['c#', '.net']" +3236,how to debug ora01775 looping chain of synonyms i am familiar with the issue behind ora01775 looping chain of synonyms but is there any trick to debugging it or do i just have to create or replace my way out of it is there a way to query the schema or whatever to find out what the current definition of a public synonym is even more awesome would be a graphical tool but at this point anything would be helpful,['sql'] +3237,looking for suggestions for building a secure rest api within ruby on rails i am getting started on building a rest api for a project i am working on and it led me to do a little research as to the best way to build an api using ror i find out pretty quickly that by default models are open to the world and can be called via url by simply putting a xml at the end of the url and passing appropriate parametersso then the next question came how do i secure my app to prevent unauthorized changes in doing some research i found a couple articles talking about attr accessible and attr protected and how they can be used the particular url i found talking about these was posted back in may of 07 here as with all things ruby i am sure that things have evolved since then so my question is is this still the best way to secure a rest api within rorif not what do you suggest in either a new project or an existing projectscenario,"['ruby-on-rails', 'ruby']" +3245,retrieving python module path i want to detect whether module has changed now using inotify is simple you just need to know the directory you want to get notifications fromhow do i retrieve a modules path in python,['python'] +3246,override default constructor of partial class with another partial class i do not think this is possible but if is then i need it i have a autogenerated proxy file from the wsdlexe command line tool by visual studio 2008the proxy output is partial classes i want to override the default constructor that is generated i would rather not modify the code since it is autogeneratedi tried making another partial class and redefining the default constructor but that does not work i then tried using the override and new keywords but that does not worki know i could inherit from the partial class but that would mean i would have to change all of our source code to point to the new parent class i would rather not have to do thisany ideas work arounds or hacks autogenerated classnamespace mynamespace public partial class mywebservice systemwebservicesprotocolssoaphttpclientprotocol public mywebservice string mystring autogenerated constructor other code manually created class in order to override the default constructornamespace mynamespace public partial class mywebservice systemwebservicesprotocolssoaphttpclientprotocol public override mywebservice this does not work string mystring overridden constructor other code,['c#'] +3249,using this with jquery selectors i have some html that looks like thisul classfaq li classopen a classquestion hrefthis is my questiona pof course you can it will be awesome p liulusing css i am setting the p tag to thisplaynone i want to use jquery to thisplay or hide the p tag when the anchor is clicked but i am having some troubles with the sibling selector just trying to get the selector working i triedaquestionclickfunction this pcssbackgroundcolor redto test it out seemingly the sibling selector cannot really be used like that and as i am completely new to jquery i do not know the appropriate means to make that happen thanks in advance,"['javascript', 'jquery']" +3250,config values in db or file i have some configuration values for an aspnet web app they will be maintained by a system admin once the system goes live should i store these values in the database or in a config file is there a best practice for this sort of thing,['asp.net'] +3260,python using a recursive algorithm as a generator recently i wrote a function to generate certain sequences with nontrivial constraints the problem came with a natural recursive solution now it happens that even for relatively small input the sequences are several thousands thus i would prefer to use my algorithm as a generator instead of using it to fill a list with all the sequenceshere is an example suppose we want to compute all the permutations of a string with a recursive function the following naive algorithm takes an extra argument storage and appends a permutation to it whenever it finds onedef getpermutationsstring storage prefix if lenstring 1 storageappendprefix string else for i in rangelenstring getpermutationsstringistringi1 storage prefixstringistorage getpermutationsabcd storagefor permutation in storage print permutationplease do not care about inefficiency this is only an examplenow i want to turn my function into a generator ie to yield a permutation instead of appending it to the storage listdef getpermutationsstring prefix if lenstring 1 yield prefix string else for i in rangelenstring getpermutationsstringistringi1 prefixstringifor permutation in getpermutationsabcd print permutationthis code does not work the function behaves like an empty generatoram i missing somethingis there a way to turn the above recursive algorithm into a generator without replacing it with an iterative one,['python'] +3263,how do i make uitableviewcellaccessorythisclosureindicator visible in black background cellaccessorytype uitableviewcellaccessorythisclosureindicatorin this method uitableviewcell tableviewuitableview tableview cellforrowatindexpathnsindexpath indexpathbut i can only see it when i select that cell otherwise it is not visibleand it work perfectly when background is whitei am sure that i need to set a property but i do not know which property i need to change to make this thing workthanks in advancecheers,['iphone'] +3264,django arbitrary number of unnamed urlspy parameters i have a django model with a large number of fields and 20 table rows to facilitate human readable urls and the ability to break down the large list into arbitrary sublists i would like to have a url that looks like thisbrowsename1value1name2value2 etc where name maps to a model attribute and value is the search criteria for that attribute each name will be treated like a category to return subsets of the model instances where the categories matchnow this could be handled with get parameters but i prefer more readable urls for both the users sake and the search engines these urls subsets will be embedded on each page that thisplays this model so it seems worth the effort to make pretty urlsideally each namevalue pair will be passed to the view function as a parameter named name1 name2 etc however i do not believe it is possible to defined named patterns via a regexs matched text am i wrong thereso it seems i need to do something like thisurlpatterns patterns urlrbrowseww appviewsview namemodel browseit seems this should match any sets of two namevalue pairs while it matches it successfully it only passes the last namevalue pair as parameters to the view function my guess is that each match is overwriting the previous match under the guess that the containing is causing it i tried a simple repeating pattern insteadurlpatterns patterns urlrbrowsew appviewsview namemodel browse and got the same problem but this time args only includes the last matched patternis this a limitation of djangos url thispatcher andor pythons regex support it seems either of these methods should work is there a way to achieve this without hardcoding each possible model attribute in the url as an optional pattern,['python'] +3266,what is the best net micro framework dev board for under 300 i am looking for a relativity cheap net micro framework development board for use on a personal robotics project i would do not need much for io but i want at least one serial port and one ethernet port i would prefer not to have to spend more than 300 on the board but if there is an obvious reason to get a better one i am flexible currently i am looking at this device from sjj embedded micro solutions has anyone had experience with this device,['.net'] +3273,how to present credentials in order to open file how do i specify the username and password in order for my program to opena file for readingthe program that needs to access the file is running from an account thatdoes not have read access to the folder the file is inprogram is written in c and net 2 running under xp and file is on a windows server 2003 machine,"['c#', '.net']" +3277,how to convert a unix timestamp to datetime and vice versa there is this example code but then it starts talking about millisecond nanosecond problemsthe same question is on msdn seconds since the unix epoch in cthis is what i have got so farpublic double createdepoch get datetime epoch new datetime1970 1 1 0 0 0 0tolocaltime timespan span thiscreatedtolocaltime epoch return spantotalseconds set datetime epoch new datetime1970 1 1 0 0 0 0tolocaltime thiscreated epochaddsecondsvalue,['c#'] +3282,is aspnet session information stored in a cookie if i write sessionasdf 234in my aspnet web app does this mean the client will have a cookie stored on their browser,['asp.net'] +3303,invoking javascript code in an iframe from the parent page basically i have an iframe embedded in a page and the iframe has some javascript routines i need to invoke from the parent pagenow the opposite is quite simple as you only need to call parentfunctionname but unfortunately i need exactly the opposite of thatplease note that my problem is not changing the source url of the iframe but invoking a function defined in the iframe,"['javascript', 'html']" +3308,is there a way to separate long running eg stress tests out so they are not run by default in maven 2 weve had an ongoing need here that i cannot figure out how to address using the stock maven 2 tools and documentationsome of our developers have some very long running junit tests usually stress tests that under no circumstances should be run as a regular part of the build process nightly buildof course we can use the surefire plugins exclusion mechanism and just punt them from the build but ideally wed love something that would allow the developer to run them at will through maven 2,['java'] +3320,why should we typedef a struct so often in c i have seen many programs consisting of structures like the one belowtypedef struct int i char k elemelem userwhy is it needed so often any specific reason or applicable area,['c'] +3325,tips for using vim as a java ide i am addicted to vim it is now my de facto way of editing text filesbeing that it is mainly a text editor and not an ide has anyone got tricks for me to make it easier when developing java appssome questions i havehow do i invoke a maven task without leaving vican i get code completionhow does the syntax highlightinganything else other than do not do it that i should know about,['java'] +3330,what is the practical use of dynamic variable in c 40 what is their use if when you call the method it might not existdoes that mean that you would be able to dynamically create a method on a dynamic objectwhat are the practical use of this,"['c#', '.net']" +3338,converting audio to caf format for playback on iphone using openal i am using the soundengine sample code from apple in the crashlanding sample to play back multiple audio files using the sample caf files included with crashlanding everything works fine but when i try and use my own samplesconverted to caf using afconvert all i get is a stony silence does anyone have settings for afconvert that will produce a caf file capable of being played back through openal,['iphone'] +3343,in python is there a concise way of comparing whether the contents of two text files are the same i do not care what the differences are i just want to know whether the contents are different,['python'] +3351,markdown and image alignment i am helping out a friend with a nonprofit site that publishes articles in issues each month they are mostly straightforward and i think using a markdown editor like the wmd one here in so would be perfect however they do need the ability to have images rightaligned in a given paragraph i cannot see any way to do that with the current system is it possible,"['html', 'css']" +3353,automating unit tests junit for eclipse plugin development i am developing eclipse plugins and i need to be able to automate the building and execution of the test suite for each plugin using junittest are working within eclipse and i can break the plugins into the actual plugin and a fragment plugin for unit testing as described here here and in a couple places herehowever each of the approaches above results in the same issue the java ant taskcommandline command that issues the build or should trigger the test generates no observable side effects and returns the value 13 i have tried everything i can find and i have learned a fair bit about how eclipse starts up eg since v33 you can no longer use startupjar it does not exist but you should use orgeclipseequinoxlauncher unfortunately while that is apparently necessary information it is far from sufficienti am working with eclipse 34 junit 431 the orgjunit4 bundle but i would much rather use junit 44 see hereso my question is how exactly do you automate the build and testing of eclipse plugins edit to clarify i want to use something like ant cruise control but i cannot even get the unit tests to run at all outside of eclipse i say something like because there are other technologies that accomplish the same thing and i am not so picky as to thiscard a solution that works just because it is using say maven or buckminster if those technologies make this substantially easieredit2 the java result 13 mentioned above seems to be caused by the inability to find the coretestrunner from the logjavalangruntimeexception application orgeclipsetestcoretestapplication could not be found in the registry the applications available are orgeclipseequinoxapperror comrcpquickstarthelloworldapplication at orgeclipseequinoxinternalappeclipseappcontainerstartdefaultappeclipseappcontainerjava242 at orgeclipseequinoxinternalappmainapplicationlauncherrunmainapplicationlauncherjava29 at orgeclipsecoreruntimeinternaladaptoreclipseapplauncherrunapplicationeclipseapplauncherjava110 at orgeclipsecoreruntimeinternaladaptoreclipseapplauncherstarteclipseapplauncherjava79 at orgeclipsecoreruntimeadaptoreclipsestarterruneclipsestarterjava382 at orgeclipsecoreruntimeadaptoreclipsestarterruneclipsestarterjava179 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava39 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava25 at javalangreflectmethodinvokemethodjava597 at orgeclipseequinoxlaunchermaininvokeframeworkmainjava549 at orgeclipseequinoxlaunchermainbasicrunmainjava504 at orgeclipseequinoxlaunchermainrunmainjava1236 at orgeclipseequinoxlaunchermainmainmainjava1212 at orgeclipsecorelaunchermainmainmainjava30entry orgeclipseosgi 2 0 20081104 210210514message the following is a complete list of bundles which are not resolved see the prior log entry for the root cause if it existssubentry 1 orgeclipseosgi 2 0 20081104 210210515message bundle updatepluginsorgeclipsetest 320 34 was not resolvedsubentry 2 orgeclipsetest 2 0 20081104 210210516message missing required bundle orgapacheant 0subentry 2 orgeclipsetest 2 0 20081104 210210516message missing required bundle orgeclipseuiideapplication 0subentry 1 orgeclipseosgi 2 0 20081104 210210518message bundle updatepluginsorgeclipseantoptionaljunit 32100jar 60 was not resolvedsubentry 2 orgeclipseantoptionaljunit 2 0 20081104 210210519message missing host orgapacheant 165200subentry 2 orgeclipseantoptionaljunit 2 0 20081104 210210519message missing required bundle orgeclipsecoreruntimecompatibility 0,['java'] +3354,serializing namevalue pairs in a custom object via web service this is a very complicated question concerning how to serialize data via a web service call when the data is notstrongly typed i will try to lay it out as best possiblesample storage objectserializablepublic class storageobject public string name get set public string birthday get set public listnamevaluepairs otherinfo get set serializable public class namevaluepairs public string name get set public string value get set sample usewebmethod public liststorageobject getstorageobjects liststorageobject o new liststorageobject new storageobject name matthew birthday jan 1st 2008 otherinfo new listnamevaluepairs new namevaluepairs name hobbies value programming new namevaluepairs name website value stackoverflowcom new storageobject name joe birthday jan 10th 2008 otherinfo new listnamevaluepairs new namevaluepairs name hobbies value programming new namevaluepairs name website value stackoverflowcom return o return value from web servicestorageobject namematthewname birthdayjan 1st 2008birthday otherinfo namevaluepairs namehobbiesname valueprogrammingvalue namevaluepairs namevaluepairs namewebsitename valuestackoverflowcomvalue namevaluepairs otherinfostorageobjectwhat i wantotherinfo hobbiesprogramminghobbies websitestackoverflowcomwebsiteotherinfothe reason other stufirst i am sorry for the length of the post but i wanted to give reproducible code as well i want it in this format because i am consuming the web services from php i want to easily go this is imporantin php resultstorageobjectotherinfohobbiesif it is in the other format then there would be no way for me to accomplish that at all additionally in c if i am consuming the service i would also like to be able to do the following this is imporantin c var m serviceresult0otherinfohobbiesunfortunately i am not sure how to accomplish this i was able to get it this way by building a custom dictionary that implemented ixmlserializer see stackoverflow ixmlserializer dictionary however it blew the wsdl schema out of the water it is also much too complicated and produced horrible results in my winformstester applicationis there any way to accomplish this what type of objects do i need to create is there any way to do this other than by making a strongly typed collection obviously if i make it strongly typed like thispublic class otherinfo public string hobbies get set public string favoritewebsite get set then it would work perfectly i would have no wsdl issues i would be able to easily access it from php and c otherinfohobbies however i would completely lose the point of nvps in that i would have to know in advance what the list is and it would be un,"['c#', 'php']" +3355,what are the different doctypes in html and what do they mean as the title describes what are the different doctypes available and what do they mean i notice that the layout looks a little different in ie7 when i switch from doctype html public w3cdtd html 40 transitionalen todoctype html public w3cdtd xhtml 10 transitionalen are there any others and what are the effects or ramificationsthanks,['html'] +3357,how to implement google suggest in your own web application eg using python in my website users have the possibility to store linksduring typing the internet address into the designated field i would like to thisplay a suggestautocomplete box similar to google suggest or the chrome omnibarexampleuser is typing as urlsuggestions which would be thisplayedhow can i achieve this while not reinventing the wheel,['python'] +3364,is there an easy way to plot polyline area ie service coverage area and also check to see if visitors address lies within that area using google maps api and php i am the owner of a business that is building a new website application my partner is the programmer who is doing the development and neither one of us has any real indepth experience with google map api or it is polylinepolygon area capabilitieswe need an easy way to capture inputs within our user admin area where our locations can enter their service coverage area info ie 1st street north of jones blvd or a 5 mile radius from the location address etc and have the google map api plot the polyline bordersthen visitors to our site need to be able to see this info when they view the google map for one of our locations and also see if their service address falls within that service area or not we then need to set a flag somehow to trigger a notification to the visitor that their address is not eligible for service or deliveryif anyone can assist us with this example php code to interface with the suggested apis would be preferred and ideal as we simply do not understand the complexities of the google api the polyline coordinate capture tool etc it would be greatly appreciated as we have struggled to figure out how to create this in php and more importantly how to integrate it into our existing sitethank you in advance for your replies and assistancesincerely larry dmanaging directorsunmark venturesupdate thank you for your answer codemeithow do recommend we capture these longlats in our sql databaseie what is the field format or type and do we need to have separate fields for long and lat and how can we standardize for all locations ie how many long and lats are needed to create a polygon area as we want to be able to have our location managers input this info for their own locations from their user login areasthank you in advance for your assistancegreatly appreciated,"['php', 'sql']" +3365,nsstring indexof in objectivec are there anything similar to an indexof function in the nsstring objects,['objective-c'] +3374,change journal operations in net i am looking for the netc way of performing change journal operations without importing unmanaged codeany hints or rtfmlinks,['.net'] +3377,what is the simplest jquery way to have a positionfixed always at top div i am relatively new to jquery but so far what i have seen i like what i want is for a div or any element to be across the top of the page as if position fixed worked in every browseri do not want something complicated i do not want giant css hacks i would prefer if just using jquery version 126 is good enough but if i need jqueryuicore then that is fine tooi have tried topbarscrollfollow but that goes slow i want something to appear really fixed,"['jquery', 'css']" +3379,nsdata and uiimage i am trying to load uiimage object from nsdata and the sample code was to nsimage i guess they should be the same but just now loading the image i am wondering whats the best to troubleshoot the uiimage loading nsdata issue,"['ios', 'iphone']" +3382,python vs groovy vs ruby based on criteria listed in question considering the criteria listed below which of python groovy or ruby would you usecriteria importance out of 10 10 being most importantrichness of apilibraries available eg maths plotting networking 9ability to embed in desktop javac applications 8ease of deployment 8ability to interface with dllsshared libraries 7ability to generate guis 7communityuser support 6portability 6database manipulation 3languagesemantics 2,"['python', 'ruby']" +3387,how to convert cstring and stdstring stdwstring to each other cstring is quite handy while stdstring is more compatible with stl containeri am using hash map however hash map does not support cstring as key so i want to convert cstring into stdstringwriting a cstring hash function seems to take a lot of timecstring stdstringhow can i do thisstdstring cstringinline cstring tocstringstdstring const str return cstringstrc str am i rightedithere are more questionshow can i convert wstring cstring to each otherwstring cstringstdwstring srccstring resultsrcc strcstringwstring cstring srcstdwstring dessrcgetstringis there any problemhow can i convert stdwstring stdstring to each other,['c++'] +3388,what is the memory consumption of an object in java is the memory space consumed by one object with 100 attributes the same as that of 100 objects with one attribute eachhow much memory is allocated for an objecthow much additional space is used when adding an attribute,['java'] +3402,how to serialize an object to xml without getting xmlns is there a way for me to serialize an object in net without the xml namespaces automatically serializing also it seems that by default net believes the xsi and xsd namespaces should be included but i do not want them there,['.net'] +3403,phone number normalization any preexisting libraries i have a system which is using phone numbers as unique identifiers for this reason i want to format all phone numbers as they come in using a normalized format because i have no control over my source data i need to parse out these numbers myself and format them before adding them to my dbi am about to write a parser that can read phone numbers in and output a normalized phone format but before i do i was wondering if anyone knew of any preexisting libraries i could use to format phone numbersif there are no preexisting libraries out there what things should i be keeping in mind when creating this feature that may not be obviousalthough my system is only dealing with us numbers right now i plan to try to include support for international numbers just in case since there is a chance it will be needededit i forgot to mention i am using cnet 20,"['c#', '.net']" +3405,scanning java annotations at runtime what is the best way of searching the whole classpath for an annotated classi am doing a library and i want to allow the users to annotate their classes so when the web application starts i need to scan the whole classpath for certain annotationdo you know a library or a java facility to do thisedit i am thinking about something like the new functionality for java ee 5 web services or ejbs you annotate your class with webservice or ejb and the system finds these classes while loading so they are accessible remotely,['java'] +3408,iterator adapter to iterate just the values in a map i am just getting back into c after a couple of years of doing a lot of c and recently objective cone thing i have done before is to roll my own iterator adapter for stdmap that will deref to just the value part rather than the keyvalue pair this is quite a common and natural thing to do c provides this facility with its keys and values properties of its dictionary class objectivecs nsdictionary similarly has allkeys and allvaluessince i have been away boost has acquired the range and foreach libraries which i am now using extensively i wondered if between the two there was some facility to do the same but i have not been able to find anythingi am thinking of knocking something up using boosts iterator adapters but before i go down that route i thought i would ask here if anyone knows of such a facility in boost or somewhere else ready made,['c++'] +3411,what do you use to test the handheld css on your website i have been adding css support for handheld to my website but have not been able to find a good tool for testing i tried using the webdeveloper plugin for firefox but it does not work for me maybe that is because all my css is in the html and not a seperate css fileare there any other testing tools available aside from going out and buying a handheld device,"['html', 'css']" +3414,using nullable types in c i am just interested in peoples opinions when using nullable types in c what is the best practice way to test for nullbool isnull i nullorbool isnull ihasvaluealso when assigning to a nonnull type is thislong i 1long j longibetter thanlong i 1long j ivalue,['c#'] +3420,is there a built in net exception that indicates an illegal object state what exception should i throw if i encounter an illegal state for instance an initialization method that should only be called once being called a second time i do not really see any builtin exception that makes sense this seems like something that should be in the framework am i not poking in the right spot,"['c#', '.net']" +3435,thisplay html in an actionscript 3 project folksi am pulling all my flash pure as3 project not flash cs3 content from a drupal backend for seo purposes this works great except the html rendering built into the textfield object leaves a lot to be desired could anyone recommend any libraries that would allow me to thisplay html elements at this stage commercial or opensource libraries are welcomethanksmarcus,['html'] +3437,are nonpure virtual functions with parameters bad practice i have a base class with an optional virtual functionclass base virtual void onlyimplementthissometimesint x when i compile this i get a warning about the unused param x is there some other way i should have implemented the virtual function i have rewritten it like thisclass base virtual void onlyimplementthissometimesint x x 0 i also have the problem that if i am not careful the subclass i make can implement the wrong function and then i do not notice because of overloading egclass derived public base void onlyimplementthissometimesint x int y some code derived dbase b dynamic castbase dbonlyimplementthissometimesx calls the method in the base classthe base class method was called because i implemented the derived function with an int y param but there is no warning about this are these just common pitfalls in c or have i misunderstood virtual functions,['c++'] +3439,required field validator not firing i am having an issue with a standard aspnet page that has a textbox and a requiredfieldvalidator the steps to reproduce are quite simpleplace a textbox on a pageplace a requiredfieldvalidator on the pagepoint the requiredfieldvalidator at the textboxrun the apptab away from the textbox the requiredfieldvalidator does not showenter text then delete the text and then tab away the requiredfieldvalidator does showthe requiredfieldvalidator works fine in both cases after a postback however it seems the clientside code is not firing until something is entered into the textbox and then deleteddoes anyone have a solution to this without hacking away at javascript myself,['asp.net'] +3441,conditional formating in rails partials i am rendering a rails partial and i want to alternate the background color when it renders the partial i know that is not super clear so here is an example of what i want to dorow one grey backgroundrow two yellow backgroundrow three grey backgroundrow four yellow backgroundsorry stackoverflow seams to prevent the background colors from being shown but i think this makes my idea clearthis is the view code that i am using table render partial row collection rows tablethe rowhtmlerb partial looks like thistr bgcolora td rowname tdtrthe problem is i do not know how to change the background color for every other row is there away to do this,"['ruby-on-rails', 'ruby']" +3448,how to build python c extension modules with autotools most of the documentation available for building python extension modulesuses thistutils but i would like to achieve this by using the appropriatepython autoconf automake macros insteadi would like to know if there is an open source project out there that doesexactly this most of the ones i have found end up relying on a setuppy fileusing that approach works but unfortunately ends up rebuilding the entiresource tree any time i make a modification to the module source files,"['c++', 'python', 'c']" +3451,how do i set an image for some but not all nodes in a treeview i have a treeview windows forms control with an imagelist and i want some of the nodes to thisplay images but the others to not have imagesi do not want a blank space where the image should be i do not want an image that looks like the lines that the treeview would draw if it did not have an imagelist how do i get it to draw images for some items and not others without resorting to clumsy hacks like that,"['c#', '.net']" +3454,aspnet removing an item from session which method is preferredsessionremovefoosessionfoo nullis there a difference,"['c#', 'asp.net', '.net']" +3455,best algorithm to check whether a vector is sorted what would be the best way to check that a stdvector is sorted is there something faster than a loop checking that vivi1 is it fastercleaner with iterators or is it actually better to just call sort every time though the v is already sorted case is quite commonwe can safely assume the vector only contains pods usually floats and sometimes doubles and intsthe size of the vector is nontrivial usually a few thousands items but not extreme not gigabytesizedin some instances well sort the vector immediately afterwards however there are other instances where we do not it is an error case of our algorithmwe already use a flag issorted whenever possible,['c++'] +3457,addicted to linq ok the more i use linq the more i like it i recently found myself working in some legacy code at work it is your classic dataset and datatable rich application well when adding a bit of functionality i found myself really wanting to just query the rows of a datatable for the results i was looking forlet me repeat that instead of looping and adding to a temp collection i just wanted to ask the rows collection for what i needed no looping no temp variables just give me what i wantvar customerorderids tablerowscastdatarow wherex stringxcustomer id customerid selectx stringxcustomer order id thistinctmy question is whether or not this is a good thing or am getting carried away with linq it does seem to me that this declarative style of pulling a subset of data out of a collection is a good thing and more readable in the end but then again maybe i am just smitten,['.net'] +3460,how can i know if a process is running when i get a reference to a systemdiagnosticsprocess how can i know if a process is currently running,"['c#', '.net']" +3464,why is using to build a view bad why is using to build a view bad suppose that you have a complex join and all fields may be used somewherethen you just have to chose fields neededselect field1 field2 from aview where the view aview could be select table1 table2 from table1 inner join table2 we have a problem if 2 fields have the same name in table1 and table2is this only the reason why using in a view is badwith you may use the view in a different context because the information is therewhat am i missing regards,['sql'] +3470,javascript onhover event is there a canonical way to set up a js onhover event with the existing onmouseover onmouseout and some kind of timers or just any method to fire an arbitrary function if and only if user has hovered over element for certain amount of time,['javascript'] +3475,range for integer values of chars in c i am reading the c programming language and in it stroustrup states that the int value of a char can range from 0 to 255 or 127 to 127 depending on implementation is this correct it seems like it should be from 128 to 127 if not why are their only 255 possible values in the second implementation possibility not 256,['c++'] +3476,showing too much skin detection in software i am building an aspnet web site where the users may upload photos of themselves there could be thousands of photos uploaded every day one thing my boss has asked a few time is if there is any way we could detect if any of the photos are showing too much skin and automatically move flag these as adults only before the editors make the final decision,['asp.net'] +3477,what is the best algorithm for an overridden systemobjectgethashcode in net systemobjectgethashcode method is used in a lot of places throughout the net base class libraries especially when finding items in a collection fast or to determine equality is there a standard algorithm best practice on how to implement the gethashcode override for my custom classes so i do not degrade performance,['.net'] +3492,how do i make http post request for getting json object in response for iphone application i have a web service running on server which return data either in xml format or json formati wanted to request a json format but using http post methodany help greatly appreciatedthanks in advance,['iphone'] +3496,is there an alternative for sleep in c in traditional embedded programming we will give a delay function like sofori0i255i forj0j255jin the microprocessors view is this how the sleep function worksis there an alternative for the sleep function in c,['c'] +3498,how can i get a list of the differences between two javascript object graphs i want to be able to get a list of all differences between two javascript object graphs with the property names and values where the deltas occur for what it is worth these objects are usually retrieved from the server as json and typically are no more than a handful of layers deep ie it may be an array of objects that themselves have data and then arrays with other data objectsi want to not only see the changes to basic properties but differences in the number of members of an array etc etcif i do not get an answer i will probably end up writing this myself but hope someone has already done this work or know of someone who hasedit these objects will typically be very close in structure to one another so we are not talking about objects that are utterly different from one another but may have 3 or 4 deltas,['javascript'] +3499,converting plist to binary plist apple strongly recommends using the binary plist format when reading large xmlbased data sets into iphone apps among their reasoning is the fact that xml parsing is very taxing on the iphone however this requires that files residing on the remote web server be converted firstfor frequentlychanging content it is not acceptable to do this manually if at all possible i would like to avoid having a web based app call the command line to perform the conversion ie plutil are there publicly available algorithms to perform this conversion,"['objective-c', 'iphone']" +3500,php removing a character in a string my php is weak and i am trying to change this stringmindextcareto bemindextcareremoving the after the on backendphp any ideas on the best way to do thisthanks,['php'] +3504,how can i create an editable dropdownlist in html i would like to create a text field with a dropdown list that lets the user choose some predefined values the user should also be able to type a new value or select a predefined one from a dropdown list i know that i can use two widgets for that but in my app it would be more ergonomnic if it was unified in a one widgetis there a standard widget or do i have to use a third party javascripthow about browser portability,['html'] +3505,best way to automagically migrate tests from junit 3 to junit 4 i have a bunch of junit 3 classes which extend testcase and would like to automatically migrate them to be junit4 tests with annotations such as before after test etcany tool out there to do this in a big batch run,['java'] +3507,is it worth switching from visual studio 2005 to visual studio 2008 as a team we are using visual studio 2005 with framework 30 i am thinking if it will be nice for us to switch to visual studio 2008 with framework 35 is it worth it thanks,['.net'] +3510,have you tried spring workflow already spring workflow has now been publishedhave you tried it yet for what kind of scenariowhat is your impression how do you find it stacks up against other workflow libsfound any good docs or tutorials,['java'] +3523,generating pdfs with php i have a php application and a need to generate a pdf with the result of query the easiest way a found to do this was to use the dompdf to generate the pdf for me so a made a function that generates the html for me then a pass this to dompdf in the development and testing enviroment everything was fine but on production enviroment i had some problems with memory usageso i would like to know if my strategy was the best one or if there is a better and easy way to do thishow would you do that,['php'] +3526,best way to strip punctuation from a string in python it seems like there should be a simpler way thanimport strings string with punctuation sample string out stranslatestringmaketrans stringpunctuationis there,['python'] +3531,how do i unit test jdbc code in java i would like to write some unit tests for some code that connects to a database runs one or more queries and then processes the resultswithout actually using a databaseanother developer here wrote our own datasource connection statement preparedstatement and resultset implementation that will return the corresponding objects based on an xml configuration file we could use the bogus datasource and just run tests against the result sets it returnsare we reinventing the wheel here does something like this exist already for unit testingare there other better ways to test jdbc code,['java'] +3532,modern for loop for primitive array is there any performance difference between the for loops on a primitive array assumedouble doublearray new double30for double var doublearray somecomplexcalculationvaror for int i 0 y doublearraylength i y i somecomplexcalculationdoublearrayitest resulti actually profiled ittotal timeused for modern loop 13269mstotal timeused for old loop 15370msso the modern loop actually runs faster at least on my mac osx jvm 15,['java'] +3535,why is a char and a bool the same size in c i am reading the c programming language in it stroustrup states that sizeofchar 1 and 1 sizeofbool the specifics depend on the implementation why would such a simple value as a boolean take the same space as a char,['c++'] +3536,why does not msbuild copy as i would expect i am needing to script my build i am using msbuild because of it is integration with vsnet i am trying to copy some files from the build environment to the deployment folder i am using the copy task of msbuild but instead of copying the directory tree as i would expect it copies all the contents into a single folder i repeat all the files from the directory tree end up in one folder i need it to copy the tree of folders and directories into the destination folder is there something i am missinghere is the relavant parts of my build scriptpropertygroup targetframeworkversionv20targetframeworkversion sourceoutputfoldersource destenvxdestenv deploypathnetworkpathdestenvdeploypathpropertygroupitemgroup targetdir includedeploypath excludewebconfigtargetdir sourcedir includesource itemgroup target nameclean clean detail targettarget namemigrate dependsontargetsclean copy destinationfolderdeploypath sourcefilessourcedir target,['.net'] +3539,what is the operation aborted error in internet explorer i recently added jquerys datepicker control to a project in internet exploder i get the following error messageinternet explorer cannot open the internet sitehttplocalhostoperation abortedwhat is causing this problem,['javascript'] +3553,to check whether the string value has numeric value or not in c i am having an string like thisstring str dfdsfdsf8fdfdfd9dfdfd4i need to check whether the string contains number by looping through the array,['asp.net'] +3560,jquery documentcreateelement equivalent i am refactoring some old javascript code and there is a lot of dom manipulation going onvar d documentvar odv dcreateelementdivodvstylethisplay nonethisouterdiv odvvar t dcreateelementtabletcellspacing 0tclassname textodvappendchildti would like to know if there is a better way to do this using jquery i have been experimenting withvar odv createdivappendodv and many morebut i am not sure if this is any better,"['javascript', 'jquery', 'html']" +3573,how to determine which child page is being thisplayed from master page i am writing code on the master page and i need to know which child content page is being thisplayed how can i do this programmatically,"['c#', 'asp.net']" +3574,is there a python library function which attempts to guess the characterencoding of some bytes i am writing some mailprocessing software in python that is encountering strange bytes in header fields i suspect this is just malformed mail the message itself claims to be usascii so i do not think there is a true encoding but i would like to get out a unicode string approximating the original one without throwing a unicodedecodeerror so i am looking for a function that takes a str and optionally some hints and does its darndest to give me back a unicode i could write one of course but if such a function exists its author has probably thought a bit deeper about the best way to go about thisi also know that pythons design prefers explicit to implicit and that the standard library is designed to avoid implicit magic in decoding text i just want to explicitly say go ahead and guess,['python'] +3579,opening an application inside a form c or vbnet i am writing an application and i would like to be able to thisplay another application inside it think like a windows form with a small box or a tab that is thisplaying a totally seperate applicationis that something that can be done if so can anyone give some direction on how to go about doing it i am looking for something in the c or vbnet worldthanks,['c#'] +3589,tests projects in solution in net should you place unit test projects in with the rest of the solution or should there be a test solution that houses all the test projectswe have all the test projects in with our code base solutionit seems a bit cumbersome what do you usually do,['.net'] +3594,or what is the difference between having evalstate in your aspx page versus having databinderevalcontainerdataitem state in your aspx page,['asp.net'] +3607,why does hibernatejdbcmysql drop connections after a day or so i have several server processes that once in a while respond to messages from the clients and perform readonly transactionsafter about a few days that the servers are running they stop working correctly and when i check it turns out that there is a whole bunch of messages about the connection being closedwhen i checked it out it turned out that hibernate by default works in some sort of development mode where connections are dropped after a few hours and i started using c3po for connection pooling however even with c3po i get that problem about 24 hours or so after the servers are startedhas anyone encountered that problem and knows how to address it i am not familiar enough with the intricacies of configuring hibernate,['mysql'] +3612,linkedlist remove method what is a doubly linked lists remove method,['java'] +3615,ruby on rails plugin for showing line numbers in log for sql queries does anybody know any plugin that can show line numbers for sql queries in rails logs something like thisuser load 03154 select from users where usersid 1 userrb line 24thanks,"['sql', 'ruby-on-rails']" +3619,gzipstream and deflatestream will not decompress all bytes i was in need of a way to compress images in net so i looked into using the net gzipstream class or deflatestream however i found that decompression was not always successful sometimes the images would decompress fine and other times i would get a gdi error that something is corruptedafter investigating the issue i found that the decompression was not giving back all the bytes it compressed so if i compressed 2257974 bytes i would sometimes get back only 2257870 bytes real numbersthe most funny thing is that sometimes it would work so i created this little test method that compresses only 10 bytes and now i do not get back anything at alli tried it with both compression classes gzipstream and deflatestream and i double checked my code for possible errors i even tried positioning the stream to 0 and flushing all the streams but with no luckhere is my code public static void testcompression byte test new byte 0 1 2 3 4 5 6 7 8 9 byte result decompresscompresstest this will fail resultlength is 0 debugassertresultlength testlength public static byte compressbyte data var compressedstream new memorystream var zipstream new gzipstreamcompressedstream compressionmodecompress zipstreamwritedata 0 datalength return compressedstreamtoarray public static byte decompressbyte data var compressedstream new memorystreamdata var zipstream new gzipstreamcompressedstream compressionmodedecompress var resultstream new memorystream var buffer new byte4096 int read while read zipstreamreadbuffer 0 bufferlength 0 resultstreamwritebuffer 0 read return resultstreamtoarray,['c#'] +3625,captured variable in a loop in c i met an interesting issue about c i have code like belowlistfuncint actions new listfuncintint variable 0while variable 5 actionsadd variable 2 variableforeach var act in actions consolewritelineactinvokei expect it to output 0 2 4 6 8 however it actually outputs five 10sit seems that it is due to all actions referring to one captured variable as a result when they get invoked they all have same outputis there a way to work round this limit to have each action instance have its own captured variable,['c#'] +3628,crossreferences and garbage collection there is an application with an extensive object graph this graph mainly consists of a set of subgraphs which are connected to the rest of the graph through the only reference but internally each such subgraph has some number of crossreferences among objects once in a while such a sub graph needs to be thrown away would it be enough just to set to null the only referece which points to that subgraph to make it eligible for garbage collectionmy concern is that internal crossreferences may protect the entire subgraph from garbage collection in other words is the garbage collector wise enough to figure out that all references in a subgraph do not leave the boundaries of the subgraph and therefore entire subgraph can be purged,['java'] +3631,strategy for offlineonline data synchronization my requirement is i have server j2ee web application and client j2ee web application sometimes client can go offline when client comes online he should be able to synchronize changes to and fro also i should be able to control which rowstables need to be synchronized based on some filtersrules is there any existing java frameworks for doing it if i need to implement on my own what are the different strategies that you can suggestone solution in my mind is maintaining sql logs and executing same statements at other side during synchronization do you see any problems with this strategy,['java'] +3634,collection versus list what should you use on your interfaces the code looks like belownamespace test public interface imyclass listimyclass getlist public class myclass imyclass public listimyclass getlist return new listimyclass when i run code analysis i get the following recommendationwarning 3 ca1002 microsoftdesign change list in imyclassgetlist to use collection readonlycollection or keyedcollectionhow should i fix this and what is good practice here,"['c#', '.net']" +3635,how to select maximum 3 items per users in mysql i run a website where users can post items eg pictures the items are stored in a mysql database i want to query for the last ten posted items but with the constraint of a maximum of 3 items can come from any single user what is the best way of doing it my preferred solution is a constraint that is put on the sql query requesting the last ten items but ideas on how to set up the database design is very welcomethanks in advancebr,"['mysql', 'sql']" +3640,searching for the best php nested sets class pear class excluded i am looking for a php with mysql nested sets class with all needed functionsfor examplecreateleftnode createrightnodecreaterootnode createsubnodedeletenode and movetree not only 1 left 1 right 1 up and 1 down but also a part of a tree in a nother treethanks,['php'] +3644,sql statement indentation good practice what is the accepted practice for indenting sql statements for example consider the following sql statementselect column1 column2from table1where column3 inselect top1 column4from table2inner join table3on table2column1 table3column1how should this be indented many thanks,['sql'] +3647,does opacity0 have exactly the same effect as visibilityhidden if so does it effectively deprecate the visibility propertyi realize that internet explorer does not yet support this css2 propertycomparisons of layout enginessee also what is the difference between visibilityhidden and thisplaynone,"['html', 'css']" +3651,wcf javascript proxy not found when endpoint address is not blank i am trying to setup a wcf service with multiple endpoints with one of the endpoints using the enablewebscript endpoint behavior so that a javascript proxy will be created on the client jsdebugjswhen adding the service reference to my ajax scriptmanager the jsdebug file is not found unless the address of the endpoint is blank the scriptmanager proxy seems to always generate a path of myservicesvcjsdebug to look for the file even though my service has an address of ajax the proxy should generate the path as myservicesvcajaxjsdebugis there a setting to get the proxy generated with the right path my service is at the root of my websiteworksendpoint address behaviorconfigurationajaxbehavior bindingwebhttpbinding bindingconfigurationwebbinding contractmytestwebicustomerservice want this does not workendpoint addressajax behaviorconfigurationajaxbehavior bindingwebhttpbinding bindingconfigurationwebbinding contractmytestwebicustomerservice,['.net'] +3653,do i have to learn objectivec for professional mac development do i really have to learn objectivec to develop solid mac appsas mac users tend to use only applications that have a nice native gui i do not think that mono and gtk or any java gui swing will fit their needsthere are projects like cocoa pyobjc and rubycocoa but are they ready for primetimeso do i really have to learn objectivec i would prefer a dynamic language,['objective-c'] +3655,kill a blocked boostthread i am writing an application which blocks on input from two istreamsreading from either istream is a synchronous blocking call so i decided to create two boostthreads to do the readingeither one of these threads can get to the end based on some input received and once the end is reached both input streams stop receiving unfortunately i cannot know which will do sothus i cannot join on both threads because only one thread cannot be predetermined which one will actually return unblocki must somehow force the other to exit but it is blocked waiting for input so it cannot itself decide it is time to return condition variables or what notis their a way to eithersend a signal a boostthread orforce an istream to fail orkill a boostthreadnoteone of the istreams is cini am trying to restart the process so i cannot close the input streams in a way that prohibits reseting themediti do know when the end is reached and i do know which thread has successfully finished and which needs to be killed its the killing i need to figure out or a different strategy for reading from an istreami need both threads to exit and cleanup properly thanks,['c++'] +3658,undefined reference to static class member can anyone explain why following code would not compile at least on g 424and more interesting why it will compile when i cast member to intinclude vectorclass foo public static const int member 1 int main vectorint v vpush back foomember undefined reference to foomember vpush back int foomember ok return 0,['c++'] +3659,in java when does a url connection close when does java let go of a connections to a url i do not see a close method on either url or urlconnection so does it free up the connection as soon as the request finishes i am mainly asking to see if i need to do any clean up in an exception handlertry url url new url urlconnection conn urlopenconnection use the connectioncatch exception e any clean up here,['java'] +3660,whats in and out of opengles porting from opengl it seems that all of the documentation i can find about opengles says something to the effect of opengles is just like opengl but without a lot of stuff for example there is no glbegin or glendok that is great so what else is not there any of or is there a list of whats in or maybe a porting guidespecifically i am trying to move an existing gl app to the iphone although i do not want to necessarily limit my q to the iphone,['iphone'] +3668,iphone detecting user inactivityidle time since last screen touch has anybody implemented a feature where if the user has not touched the screen for a certain time period you take a certain action i am trying to figure out the best way to do thatthere is this somewhatrelated method in uiapplicationuiapplication sharedapplicationidletimerthisabledit would be nice if you instead had something like thisnstimeinterval timeelapsed uiapplication sharedapplicationidletimeelapsedthen i could set up a timer and periodically check this value and take some action when it exceeds a thresholdhopefully that explains what i am looking for has anyone tackled this issue already or have any thoughts on how you would do it thanks,"['iphone', 'objective-c']" +3673,if i use explicit constructor do i need to put the keyword in both h and cpp files actually my question is all in the titleanywayi have a class and i use explicit constructorhclass myclass public explicit myclassconst string s querys private string queryis it obligatory or not to put explicit keyword in implementationcpp file,['c++'] +3675,singleton destructors should singleton objects that do not use instancereference counters be considered memory leaks in cwithout a counter that calls for explicit deletion of the singleton instance when the count is zero how does the object get deleted is it cleaned up by the os when the application is terminated what if that singleton had allocated memory on the heapin a nutshell do i have to call a singeltons destructor or can i rely on it getting cleaned up when the application terminates,['c++'] +3682,checking if an instances class implements an interface given a class instance is it possible to determine if it implements a particular interface as far as i know there is not a builtin function to do this directly what options do i have if any,['php'] +3690,how can i call perl from java i have a perl module that i would like to use from java is there a way to call this code using either activestate perl on windows or the generic perl that comes with linux i have found references to jpl but it doesnat appear to be maintained anymore,['java'] +3694,java how do i know which jar file to use given a class name given a class orgeclipseuiviewsnavigatorresourcenavigator for example how do i find out which jar file to use i know it is in orgeclipseuiide but how would i find that outedit thank you to all of you who answered like many things there seems to be several ways to skin this cat i wish javadoc contained this info so far here are the different methodswithout internet eclipse or netbeansfor f in find name jar do echo f jar tvf f grep i 1 doneif you want to find out locally using eclipsejar class finder pluginclass locator pluginif you want to find out from internet or you do not have the jar yetjarfinder,['java'] +3697,regex for names just starting to explore the wonders of regex being someone who learns from trial and error i am really struggling because my trials are throwing up a thisproportionate amount of errors my experiments are in php using ereganyway i work with first and last names separately but for now using the same regex so far i haveazazaz any length string that starts with a capital and has only letters capital or not for the rest but where i fall apart is dealing with the special situations that can pretty much occur anywherehyphenated names worthingtonsmythe names with apostophies dangelo names with spaces van der humpton capitals in the middle which may or may not be required is way beyond my interest at this stagejoint names ben jerrymaybe there is some other way a name can be that i am no thinking of but i suspect if i can get my head around this i can add to it i am pretty sure there will be instances where more than one of these situations comes up in one nameso i think the bottom line is to have my regex also accept a space hyphens ampersands and apostrophes but not at the start or end of the name to be technically correct,['php'] +3718,is there an openid 20 plugin for symfony i am using sfopenid plugin for symfony which does not support openid 20 that means for example that people using yahoo openid cannot login to my sitethere is an openid 20 plugin that works with sfguard but i am not using nor planning to use sfguard plus it requires to install zend framework too which is an overkill in my scenarioso i have got two questions reallyis there another openid plugin for symfony supporting openid 20what would be the hack required to make sfopenid support openid 20i suppose i could study openid specs and hack it myself but then i am a lazy programmer,['php'] +3719,is there a way to measure parse time in php optimization of php code via runtime benchmarking is straight forward keep track of start and end times via microtime around a code block i am not looking for an answer that involves microtime usagewhat i would like to do is measure the time it takes php to get prepared to run it is code codeparseopcodetreebuilding time my reasoning is that while it is easy to just include every class that you might need for every page that you have on a site the cpu overhead cannot be free i would like to know how expensive parse time really isi am assuming that an opcode cache such as apc is not part of the scenariowould i be correct that measurement of parse time in php is something that would have to take place in mod phpedit if possible taking into account serverdocument root usage in code would be helpful command solutions might take a bit of tinkering to do this but still be valuable answers,['php'] +3726,how can i override the onbeforeunload dialog and replace it with my own i need to warn users about unsaved changes before they leave a page a pretty common problem windowonbeforeunloadhandlerthis works but it raises a default dialog with an irritating standard message that wraps my own text i need to either completely replace the standard message so my text is clear or even better replace the entire dialog with a modal dialog using jqueryso far i have failed and i have not found anyone else who seems to have an answer is it even possiblejavascript in my pagescript typetextjavascript windowonbeforeunloadcloseitscriptthe closeit functionfunction closeit if changes true files true return here you can append a custom message to the default dialog using jquery and jqmodal i have tried this kind of thing using a custom confirm dialogwindowbeforeunloadfunction confirmnew message thishref thishref return false which also does not work i cannot seem to bind to the beforeunload event,"['javascript', 'jquery']" +3732,what are the benefits to marking a field as readonly in c what are the benefits of having a member variable declared as read only is it just protecting against someone changing during the lifecycle of the class or are there any compiler speed improvements due to this keyword,['c#'] +3734,define an extension method for ienumerable which returns ienumerable how do i define an extension method for ienumerablet which returns ienumerabletthe goal is to make the extension method available for all ienumerable and ienumerablet where t can be an anonymous type,"['c#', '.net']" +3735,is there a good python gui shell i saw this the other day scroll all the way down to see some of the clever stuff and wondered whether something like this exists for pythonso is there a good python gui shell that can do stuff like that c shell can doedit here are links to screenshots from the article showing what i am interested in doingan example of the type of things i am interested they are able to add hooks to produce gui elements like the plot or even do silly things likei do not think this is possible with any of the console shells i have tried the regular python shell ipythonedit i am not looking for an ide if you look at the link youll get an idea of what i want,['python'] +3737,what is the best way to transfer a file using java i am writing code for uploading a file from a client to my server and the performance is not as fast as i think it should bei have the current code snippet that is doing the file transfer and i was wondering how i could speed up the transfersorry about all of the codeinputstream fileiteminputstream outputstream savefilestreamint bufferwhile fileiteminputstreamavailable 0 buffer utilgetbytesfromstreamfileiteminputstream utilwriteintarrtostreamsavefilestream buffersavefilestreamclosefileiteminputstreamclosethe util methods are as followspublic static int getbytesfromstreaminputstream in int size throws ioexception int b new intsize int count 0 while count size bcount inread return bandpublic static void writeintarrtostreamoutputstream out int arrtowrite throws ioexception for int i 0 i arrtowritelength i outwritearrtowritei,['java'] +3740,mysql myisam vs inno db what are the differences between myisam and inno db types in mysql,['mysql'] +3744,hibernate jpa sequence nonid is it possible to use a db sequence for some column that is not the identifieris not part of a composite identifier i am using hibernate as jpa provider and i have a table that has some columns that are generated values using a sequence although they are not part of the identifierwhat i want is to use a sequence to create a new value for an entity where the column for the sequence is not part of the primary keyentitytablename mytablepublic class myentity id etc public long getid return id note no id here but this does not work generatedvaluestrategy generationtypeauto generator mygen sequencegeneratorname mygen sequencename my sequence columnname seq val unique false nullable false insertable true updatable true public long getmysequencedvalue return myval then when i do thisempersistnew myentitythe id will be generated but the mysequenceval property will be also generated by my jpa providerjust to make things clear i want hibernate to generate the value for the mysequencedvalue property i know hibernate can handle databasegenerated values but i do not want to use a trigger or any other thing other than hibernate itself to generate the value for my property if hibernate can generate values for primary keys why cannot it generate for a simple property,['java'] +3750,how can i run sql server stored procedures in parallel i want to do something likeexec sproc1 and sproc2 at the same timewhen they are both finished exec sproc3i can do this in dtsis there a way to do it in transact sqlor is there a way to do it with a batch script eg vbs or powershell,['sql'] +3758,dropdownlist with linqdatasource and an empty option is there some elegant way to add an empty option to a dropdownlist bound with a linqdatasource,['asp.net'] +3764,script minification and continuous integration with msbuild on a recent project i have been working on in caspnet i have some fairly complicated javascript files and some nifty style sheets as these script resources grow in size it is advisable to minify the resources and keep your web pages as light as possible of course i know many developers who handfeed their javascript resources into compressors after debugging and then deploy their applicationswhen it comes to source control and automated builds in the satisfying world of continuous integration thank you cruisecontrolnet hand compression will simply not do the only way to maintain source control and offer compressed resources is to keep jscss source their minified brethren in a separate directory structure then register only one set of resources or the other in codebehind however if a developer makes a change to jscss source and then fails to recompact it and check in both versions then youare codeline is now out of sync not to mention ineleganti am thinking that it would be nice to write a custom executable if one does not exist yet for the ccnet task block which would find and compress all javascript and css resources in the target directory after the build action but before the aspnet publish to target this way developers would only work on js and css source and users would only get the minified resourcesis there an application that already performs this task and if not what kind of resources should i look to install on the build server to have ccnet executethe closest question i could find here to this one required nant which is not an option in my caseeditdave ward now has a great article on how to automatically minify in visual studio at his site,['javascript'] +3767,vertical text with jquery i am looking to vertically align text by adding br tags between characters with jquerydiv idfoolabelvertical textlabeldiv would look like thisverticaltext,['jquery'] +3771,utf8 all the way through i am setting up a new server and want to support utf8 fully in my web application i have tried in the past on existing servers and always seem to end up having to fall back to iso88591where exactly do i need to set the encodingcharsets i am aware that i need to configure apache mysql and php to do this is there some standard checklist i can follow or perhaps troubleshoot where the mismatches occurthis is for a new linux server running mysql 5 php 5 and apache 2,"['php', 'mysql']" +3772,how can i get a collection of all the colors in systemdrawingcolor how can i extract the list of colors in the systemdrawingcolor struct into a collection or arrayis there a more efficient way of getting a collection of colors than using this struct as a base,['.net'] +3775,which style of ruby string quoting do you favour which style of ruby string quoting do you favour up until now i have always used single quotes unless the string contains certain escape sequences or interpolation in which case i obviously have to use double quoteshowever is there really any reason not to just use double quoted strings everywhere,['ruby'] +3783,how do i get projects to place their build output into the same directory with scons backgroundi am trying out scons by setting up a basic c sample project that has two subprojects prj1 is an exe that depends on prj2prj2 is a dll that exports some functionsthe problem i am running into is that the library builds its obj pdb lib dll etc files in the same directory as it is sconscript file while the exe builds its files in the same directory as its sconscript the application successfully builds both the prj2 dependency and itself however you cannot run the resulting exe because it cannot find the library it needs because it is in the other directoryquestionhow can i get multiple projects that have dependences to output their binaries and debug information into a common directory so that they can be executed and debuggedpotential solutionsthis is what i have thought of so fari tried using variantdir previously called builddir however this does not seem to work perhaps i am messing something up herei could potentially tell the compiler and the linker explicitly via fofd for example where to drop their files is this the best or only solutionexecute a copy command on the resulting binaries this seems like a hack and quite a pain to managemaintainupdatei updated the file structure and file contents below to reflect the working solution in it is entirety thanks to grieve for his insightcommandwith this configuration you must unfortunately execute the build by cding to the build directory and then running the command below i need to get a properly working alias setup to get around thisbuild scons binproject1exefile structure sconssample bin release debug build sconstruct scons helperpy prj1 sconscript include src maincpp prj2 sconscript include functionsh src functionscppsconstructimport ospathbin dir binobj dir obj cxxtest optionscxxtest dir externcxxtestcxxtestlatestperl perl wtests htestgen perl cxxtest dir cxxtestgenplcxxtestgen flags runnerparenprinter abortonfail haveeh optionssetoption implicit cache 1 command line optionsopts optionsoptsaddoptionsenumoption debug debug version useful for developers only no allowed values yes no map ignorecase 1 environmentenv environment options opts linker options libpath externwxwidgetswxwidgetslatestlibvc dll libs wxmsw28d corelib wxbase28dlib wxbase28d odbclib wxbase28d netlib kernel32lib user32lib gdi32lib winspoollib comdlg32lib advapi32lib shell32lib ole32lib oleaut32lib uuidlib odbc32lib odbccp32lib linkflags nologo subsystemconsole incrementalyes debug machinei386 compiler options cpath include externwxwidgetswxwidgetslatestinclude externwxwidgetswxwidgetslatestvc dllmswd cppdefines win32 debug console mbcs wxusingdll wxdebug ccflags w4 ehsc rtc1 mdd nologo zi tp errorreportpromptenvdecider md5timestamp for speed use timestamps for change followed by md5export env bin dir export this environment for use by the sconscript files builderssconscript prj1sconscript sconscript prj2sconscript default prj1 scons helperpyimport ospath functions prepends the full path information to the output directory so that the build files are dropped into the directory specified by trgt rather than in the same directory as the sconscript file parameters env the environment to assign the program value for outdir the relative path to the location you want the program binary to be placed trgt the target application name without extension srcs the list of source files ref credit grieve and his local scons guru for this def prefixprogramenv outdir trgt srcs envprogramtarget ospathjoinoutdir trgt source srcs similar to prefixprogram above except for sharedlibrarydef prefixsharedlibraryenv outdir trgt srcs envsharedlibrarytarget ospathjoinoutdir trgt source srcsdef prefixfilenamefilename extensions return filename ext for ext in extensions prefix the source files names with the source directorydef prefixsourcessrcdir srcs return ospathjoinsrcdir x for x in srcssconscript for prj1import ospathimport syssyspathappend build from scons helper import import env bin dir import the common environmentprj1 env envclone clone it so we do not make changes to the global one project optionsprog project1 header filesinc dir prj2include headers source filessrc dir srcsources maincpp prefix the source files names with the source directorysources prefixsources src dir sources compiler and linker overridesprj1 envappend cpath inc dir libs project2 libpath bin dir microsoft visual studio specific pdb ospathjoin bin dir prog pdb buildersprefixprogram prj1 env bin dir prog sources sconscript for prj2import ospath import syssyspathappend build from scons helper import import env bin dir import the common environmentprj2 env envclone clone it so we do not make changes to the global one project optionsprog project2 header filesinc dir headers functionsh source filessrc dir srcsources functionscpp prefix the source files names with the source directorysources prefixsources src dir sources compiler and linker overrides update the environment with the project specific informationprj2 envappend cpath inc dir microsoft visual studio specific pdb ospathjoin bin dir prog pdb buildersprefixsharedlibrary prj2 env bin dir prog sources,['c++'] +3792,alternative to httplistener i am developing an application that is so far using httplistener to provide a small standalone http server however i have recently thiscovered that httplistener needs to be run as administrator which is not always going to be possiblewhat would the best alternative be i need http get and post both of which are not simply readingwriting files on the filesystem they need to run custom net codemy research so far has brought up cassini but as far as i can tell i would have to write a custom version is there anything else in partiular something with the same interface as httplistener but that does not require administrator privileges would be amazing,['.net'] +3794,calling a c function with a varargs argument dynamically i am programming in c against a third party library in hpmercury loadrunner that allows a varargsstyle variable size argument list for one of it is functions i want to call this function but i do not know up front how many arguments i will have there is a function made by one of my predecessors that serves somewhat but the problem here is that this function assumes the worst case scenario over 30 arguments and handcodes for thatto illuminate heres the beginning of the code the function we call is web submit data it will http post a set of form data this implementation came about when dealing with dynamically generated forms with an arbitrary number of fieldscleaned up a fair bit from the original which hand coded indexes by hand as wellweb submit data buffer gazillion items const char buffername const char buffervalue const int size 129 int i 0 int j 11 web submit databuffernamei size some formbuffernamei size actionbuffernamei size methodpostbuffernamei size targetframebuffernamei size reccontenttypetexthtmlbuffernamei size refererbuffernamei size snapshott1infbuffernamei size modehtmlitemdata missing in action indexes 8 through 10buffernamej sizebuffervaluej size enditem buffernamej sizebuffervaluej size enditem buffernamej sizebuffervaluej size enditem repeat the last 3 lines ad nauseumbuffernamej sizebuffervaluej size enditembuffernamej size now i have found an external library that might work but i would much rather not a be completely processor dependant and b attempt to teach loadrunner about linking in external sourcesedit the original function used hardcoded indexes instead of using a variable can still revert to that if it turns out to be too unpredictable however as i am unlikely to run this with a different compiler or hardware os i doubt that really is worth italso i do not have control over the implementation of web submit data so just pushing the problem down one level is not going to cut itanother thing to note the spec for web submit data uses a constant called last to mark the end of the argument list the original implementation does not use it presumably the callsite does,['c'] +3811,how do i get a humanreadable file size in bytes abbreviation using net how do i get a humanreadable file size in bytes abbreviation using netexampletake input 7326629 and thisplay 698 mb,"['c#', '.net']" +3818,how do i write unit tests in php i have read everywhere about how great they are but for some reason i cannot seem to figure out how exactly i am supposed to test something could someone perhaps post a piece of example code and how they would test it if it is not too much trouble,['php'] +3826,easiest way to sort dom nodes if i have a list like thisul idmylist li idlistitem1text 1li li idlistitem2text 2li li idlistitem3text 3li li idlistitem4text 4liulwhats the easiest way to rearrange the dom nodes to my preference this needs to happen automatically when the page loads the listorder preference is gained from a cookieegul idmylist li idlistitem3text 3li li idlistitem4text 4li li idlistitem2text 2li li idlistitem1text 1liul,['javascript'] +3828,ld duplicate symbol i am working on a school project and i am getting some weird errors from xcode i am using textmates commandr function to compile the project compilation seems to work okay but linking fails with an error message i do not understand ld outputld duplicate symbol text fieldstdbasic istream in pathfinalbuildfinalbuildreleasefinalbuildobjectsnormalppcgenericso and pathfinalbuildfinalbuildreleasefinalbuildobjectsnormalppcmaino collect2 ld returned 1 exit statusbelow is my file io functionscpp this is the only declaration of text field in the entire project include stringinclude iostreaminclude iomanipusing namespace stdifndef endfdefine endf define endr nreads one field from a given input streamusage var text fieldinstring text fieldistream instring sgetlinein s endfreturn s long long fieldistream inreturn atoltext fieldinc str int int fieldistream inreturn atoitext fieldinc str double double fieldistream inreturn atoftext fieldinc str endifwhat is going wrong for a number of reasons i do not want to post my projects entire source,['c++'] +3830,c odd compile error error changes meaning of object from class object i do not even know where to go with this google was not very helpful as with my previous question i am using textmates commandr to compile the project gameh16error declaration of aplayer halfsetplayer constaplayersh11error changes meaning of aplayera from aclass playeragameh21error aplayera is not a typeplayerh file partialifndef players hdefine players husing namespace stdinclude stringinclude vectorinclude istreaminclude iomanipinclude genericshclass player line 11publicgetterslong id conststring firstname conststring lastname conststring country constsettersvoid setidlong idvoid setfirstnamestring svoid setlastnamestring svoid setcountrystring sserializing functionsvoid thisplayostream outvoid readistream invoid writeostream outinitalizersplayerplayeristream inplayerstring firstname string lastnameplayerstring firstname string lastname string countryplayerlong id string firstname string lastname string countryplayerprivatelong idstring firstnamestring lastnamestring countrygameh file partialifndef game hdefine game hinclude genericshinclude playershinclude stringinclude vectorinclude istreaminclude iomanipusing namespace stdclass halfsetpublicgettersplayer player const line 16int gameswon constint totalpoints constint errors constsettersvoid setplayerplayer pvoid setgameswonint gamesvoid settotalpointsint pointsvoid seterrorsint errorsserializationvoid thisplayostream out constvoid readistream in constvoid writeostream out constinitalizershalfsethalfsetprivateplayer playerint gameswonint pointsint errorswhat is going on here,['c++'] +3840,how do you organise your stl headers i am working on a large project that uses the stl and have a question about your preferred way to organise your stl includesdo you prefer to include each header in the source file it is used for example if both foocpp and barcpp require stdstring then both will include stringdo you prefer to have a single header file that includes all the stl headers your project uses ie add them to the ms stdafxh precompiled headerthe advantage of the first method is that the cpp file is an independent unit and can be used in a different project without having to worry that youre missing a include the advantages of the second method is that you can take use your compilers precompiled header support plus you can wrap stl includes in pragmas that thisable some warnings for example some boost headers will cause warnings when compiling at level 4which do you prefer to use,['c++'] +3841,error microsoftodbc driver manager data source name not found and no default driver specified while connecting net to sybase server i got this error messagemicrosoftodbc driver manager data source name not found and no default driver specifiedthis has worked properly before system dsn with same details work and data connection through vsnet also worki am using vsnet 2005any suggestions,['.net'] +3847,include another msi file in my setup project i am trying to make a setup program for an aspnet web site i need to make sure the target machine has sqlxml installedi must verify the target machine has the software installed and if not launch a msi file either before or after the main installationi am a complete newbie with setup projects so maybe this is obvious but after several hours browsing the web i have not found a satisfactory solution i have been reading about wix etc but i am looking if possible for a simple solutionthank you bothi understand an installer cannot run another one i was thinking in a functionality similar to prerequisites in project properties there i can check a component and it will be automatically installed if it is not i do not need to do anything else but the most important thing for me is that the installation would not run if it is not neededi also tried the msm solution but i could not find any maybe i can make one myself i have not tried it yet though,['asp.net'] +3857,how to share config settings between mutiple applications i have a project where there are multiple applications that have some common configuration values i would like to have a shared config file that is available to all of the applications using the net configuration object model each application would also have its own appconfig filehow can this best be done i would rather avoid using the registry as much as possible in looking through the documentation the openexeconfigurationstring exepath method seems promising for accessing a specified config file is this a reasonable approach any other suggestions,['.net'] +3866,how can i insert strings with quotes into perl dbi queries what is the preferred way to insert strings that can contain both single and double quotes into mysql using dbi for example val1 and val2 can contain quotesmy dbh dbiconnect my sql insert into tbl namecol onecol two valuesval1 val2my sth dbhpreparesqlsthexecute,['mysql'] +3870,how do you read a byte array from a datarow in c i have a dataset with a datatable that correctly fills a single datarow through a tableadapteri am able to pull data from the datarow with code like thisdatafileid intthisdatafiledatarowdatafileiddatafilename stringthisdatafiledatarowdatafilenamedatafiledate datetimethisdatafiledatarowdatafiledatei have another column called datafile of type varbinarymaxwhen i try to pull that columns data from the same datarow as above i get nothingbyte filefromdatabase bytethisdatafiledatarowdatafileif i put a break point at this location i can look into the datafiledatarow look into the itemarray property and see that the binary data is sitting at position 5 in the itemarrayi have tried access the itemarray directly using its index but the byte array is not being copied to the filefromdatabase variable i have also noticed that adding filefromdatabase to my watch produces this error the name filefromdatabase does not exist in the current contextthe execution is still in the same block as the definition of filefromdatabase so i do not understand how it would be out of contexti had visual studios configuration set to release instead of debug this was causing me to not see the real time debugging information i was looking for when trying to examine filefromdatabase after switching from release to debug i am able to see the variable in the watch now and can verify that the code above is working correctly,['c#'] +3871,upload large files in net i have done a good bit of research to find an upload component for net that i can use to upload large files has a progress bar and can resume the upload of large files i have come across some components like ajaxuploader slickupload and powupload to name a few each of these options cost money and only powupload does the resumable upload but it does it with a java applet i am willing to pay for a component that does those things well but if i could write it myself that would be besti have two questionsis it possible to resume a file upload on the client without using flashjavasilverlightdoes anyone have some code or a link to an article that explains how to write a net httphandler that will allow streaming upload and an ajax progress barthank youaustinediti realized i do need to be able to do resumable file uploads for my project any suggestions for components that can do that,['asp.net'] +3873,can boost spirit be used to parse byte stream data can spirit part of boost c library be used to parse out binary data coming from a stream for example can it be used to parse data coming from a socket into structures bytes and individual bit flags thanks,['c++'] +3881,representing monetary values in java i understand that bigdecimal is recommended best practice for representing monetary values in java what do you use is there a better library that you prefer to use instead,['java'] +3885,how to spawn a process and capture its stdout in net i need to spawn a child process that is a console application and capture its outputi wrote up the following code for a methodstring retmessage stringemptyprocestartinfo startinfo new procestartinfoprocess p new procestartinfocreatenowindow truestartinforedirectstandardoutput truestartinforedirectstandardinput truestartinfouseshellexecute falsestartinfoarguments commandstartinfofilename execpstartinfo startinfopstartpoutputdatareceived new datareceivedeventhandler delegateobject sender datareceivedeventargs e using streamreader output pstandardoutput retmessage outputreadtoend pwaitforexitreturn retmessagehowever this does not return anything i do not believe the outputdatareceived event is being called back or the waitforexit command may be blocking the thread so it will never callbackany adviceedit looks like i was trying too hard with the callback doingreturn pstandardoutputreadtoend appears to work fine,"['c#', '.net']" +3886,irritating select behaviour in c while x timeouttv sectimeout timeouttv usec0 fd zeroset fd setsdset switch selectfd setsizesetnullnulltimeout xworks fine howeverfd zeroset fd setsdsetwhile x timeouttv sectimeout timeouttv usec0 switch selectfd setsizesetnullnulltimeout xdoes not it works the first time around but the next time it runs through the while loop it gets a timeout even if the sd socket receives data it seems to me to be a waste of resources to have to empty and fill set every timeanybody have a good explanation why this is and even better perhaps a suggestion how to avoid it,['c'] +3887,how can i programmatically test an http connection using java how can i test that a url is contactable and returns a valid response,['java'] +3888,how to avoid that urlequals needs access to the internet in java the equals method of the url class in the java class library makes a dns request to get the ip for the hostname to check the two ips for equality this happens even for urls that are created from the same string is there a way to avoid this internet access,['java'] +3889,parse html via xpath in net i found this great library htmlagilitypack that allows you to easily parse nonwellformed html using xpath i have used this for a couple years in my net sites but i have had to settle for more painful libraries for my python ruby and other projects is anyone aware of similar libraries for other languages,"['python', 'html', 'ruby']" +3890,what do i need to change to allow my iis7 aspnet 35 application to create an event source and log events to windows eventlog aspnet 35 running under iis 7 does not seem to allow this out of the box if eventlogsourceexistsmyapplog eventlogcreateeventsourcemyapplog application eventlog mylog new eventlog mylogsource myapplog mylogwriteentrymessage,['asp.net'] +3891,stack overflow exploit in c the question is actually about stack overflows in c i have an assigment that i can not get done for the life of me i have looked at everything in the gdb and i just cant figure itthe question is the followingint invoid confused printfwho called me exit0void shell callchar c printf now calling s shell command nc systemc exit0void victim func int a4 printf8xn a8 printfenter n scanfdn printfenter d hex values nn fori0ini scanfxai printfdone reading junk numbersnint main printfls736c ps 7370 cal 6c6163n printflocation of confused x n confused printflocation of shell call x n shell call victim func printfdone thank younok so i managed to get the first question correctly which is to arbitrarily call one of the two functions not explicitly called in the main path by the way this has to be done while running the program without any modificationsi did this by running the program setting n to 7 which gets me to the function pointer of the victim func frame i write a7 with the memory address of confused or shell call and it works i have a 64 bit machine thats why i have to get it to 7 since the ebi pointer is 2 ints wide instead of 1my question is the following how could i control which argument gets passed to the shell code funcion ie how do i write a string to char cthe whole point is executing unix commands like ps etc by running only the programi figured writing the ebi pointer with the hex representation of ps and setting the arg list of shell call to that but that did not work i also tried inputing argsv arguments and setting the arg list of shell call to the arg list of main but did not work either i think the second version should work but i believe i am not setting the arg list of the new stack frame correctly i did it by writing a8 to 0 since its the first part of the function pointer and writing a9736c and a10 but its probably not right since those are the parameters of victim func so how do i access the parameters of shell call,['c'] +3893,alternative to stylecop for visual studio i like stylecops static code analysis and rules enforcement however it is severely lacking in several key departments adding new rules is not officially supported and from what i hear pretty difficultautomatic fixing of trivial rules violations would be nice perhaps not with variable naming but with method ordering static etc this would be a huge time savermicrosofts onesizefitsall approach to stylecop is kind of restrictive i would like to have a custom set of rules for our inhouse standardsis there such a commercial product out there,['.net'] +3895,is there a time when andalso does not matter over and if i am evaluating two variables and not two method calls does it matter weather i use or some logic that sets bool valuesboolean x trueboolean y trueif x y perform some operationif x y perform some operationfurther a book i am using for c 30 net 35 only makes reference to the operator is the operator going away,['c#'] +3896,how to password protect streaming videos with php what is the best way to password protect quicktime streaming videos using phphtaccess they are being streamed using rtsp but i can use other formats if necessaryi know how to do authentication with php but i am not sure how to setup authentication so that will protect the streaming files urls so that a user cannot just copy the url and share itor am i overthinking this and i can just use a normal authentication scheme and place the files in a protected directory,['php'] +3908,reference path re javascript intellisense i am trying to get intellisense in vs2008 in a js file foojs from another js libraryfile i have written but cannot figure out the reference path syntaxstringthe library is in a file called commonjs which is in the same folder as foojs i am working onheres the paths i have tried reference pathscriptscommonjs reference pathscriptscommonjs reference pathscriptscommonjs reference pathscriptscommonjs reference pathscriptscommonjs reference pathcommonjs reference pathcommonjs reference pathcommonjs reference pathcommonjswhats the secret path syntaxstring that i am missingfwiw the top path is what is set in the master page of this mvc applike so script typetextjavascript srcscriptscommonjsscriptthanks greg,['javascript'] +3911,how do you change a hashed password using aspnet membership provider if you do not know the current password problem there is no methodbool changepasswordstring newpasswordyou have to know the current password which is probably hashed and forgotten,['asp.net'] +3916,how do i precache images for quick viewing with javascript i have a webpage where i want the user to see a new image when they put thier mouse over a certain part of the image i used an image mapimg srcpicjpg usemappicmap map idpicmap namepicmaparea shaperect coords 10203040onmouseovermouse on writemouse is on spotonmouseoutmouse offmouse is off spothrefhttpwhtml target blank mapp iddescpwhere in the header i defined these functions script typetextjavascript function mouse offtxt documentgetelementbyiddescinnerhtmltxt documentp1srcpicjpg function mouse on writetxt documentgetelementbyiddescinnerhtmltxt documentp1srcpic2jpg scriptit works but it is slow when the mouse is put over the second image it takes some few seconds to appear my temporary solution was to drastically reduce the size of the images because they were huge at 25mb they switch fast now but still not seamless how can i make the image switching more seamless without reduction in picture quality on second thought i realize that i could also just have both images thisplayed at a small and a large scale and on mouse over they would switch places how would i do this would this reduce lag,"['javascript', 'html']" +3921,how does one without inheritance override a class method and call the original from within the new method i found one source which successfully overrode timestrftime like thisclass time alias old strftime strftime def strftime do something old strftime endendthe trouble is strftime is an instance method i need to override timenow a class method in such away that any caller gets my new method while the new method still calls the original now method i have looked at alias method and have met with no success,['ruby'] +3924,prime number calculation fun were having a bit of fun here at work it all started with one of the guys setting up a hackintosh and we were wondering whether it was faster than a windows box of nearly same specs that we have so we decided to write a little test for it just a simple prime number calculator it is written in java and tells us the time it takes to calculate the first and prime numbersoptimised version below now takes 66secspublic class primes public static void mainstring args int topprime 150 int current 2 int count 0 int lastprime 2 long start systemcurrenttimemillis while count topprime boolean prime true int top intmathsqrtcurrent 1 for int i 2 i top i if current i 0 prime false break if prime count lastprime current if current 2 current else current current 2 systemoutprintlnlast prime lastprime systemoutprintlntotal time doublesystemcurrenttimemillis start 10 weve pretty much lost the plot of the whole hackintosh vs pc thing and are just having some fun with optimising it first attempt with no optimisations the above code has a couple ran around 526min to find the first 150 prime numbers this optimisation is running around 472minsif you want to have a go and post your results then stick em upspecs for the pc i am running it on are pentium d 28ghz 2gb ram running ubuntu 804best optimisation so far has been the square root of current first mentioned by jason z,['java'] +3927,application end globalasax can anybody tell me when application end is triggered in a lifecycle of an application when all sessions are ended will application end be triggered automatically are there any other reasons why application end could be triggered,['asp.net'] +3935,what good tools are available for generating erd from a sql server database i am trying to generate an entity relationship diagram from an existing ms sqlserver 2005 database what tools are available specificallyi am not only interested in erds more directly i am looking for a tool to help quickly learning and analysing a medium size schema wise not really row wise database structure,['sql'] +3936,why does this regular expression kill the java regex engine i have this naive regex s excluding the quotation marks it seems sostraightforward but it is indeed evil when it works against the below html text it sends the java regular expression engine to an infinite loop i have another regex which does somewhat the same thing but it does not kill anything do you know why this happensscript languagejavascript typetextjavascript var numdivs layername layername lnavlayer catlinkname category numdivs 2 function togglelayerlayerid if navigatorappname netscape navigatorappversionsubstr0 1 5 thislayer documentgetelementbyidlayername layerid categorylink documentgetelementbyidcatlinkname layerid closethem if thislayerclassname subnavdefault thislayerclassname subnavtoggled categorylinkclassname leftnavlinkselectedsection function closethem forx 0 x numdivs x thelayer documentgetelementbyidlayername x 1 thecategorylink documentgetelementbyidcatlinkname x 1 thelayerclassname subnavdefault thecategorylinkclassname leftnavlink var flag 0 var lastclicked 0 scriptit even keeps looping with an online java regex tool such as wfileformatinfotoolregexhtm or a utility like regexbuddy,['java'] +3938,how to return json from a 20 asmx web service i am using net framework 20 jquery to make an ajax call to a 20 web service no matter what i set the contenttype to in the ajax call the service always returns xml i want it to return jsonhere is the call documentreadyfunction ajax type post url donationsserviceasmxgetdate data contenttype applicationjson charsetutf8 datatype json success functionmsg hide the fake progress indicator graphic rsscontentremoveclassloading insert the returned html into the div rsscontenthtmlmsgd here is what the request header looks like in fiddlerpost donationsserviceasmxgetdate http11xrequestedwith xmlhttprequestacceptlanguage enusreferer httplocalhost1238texthtmaccept applicationjson textjavascript contenttype applicationjson charsetutf8acceptencoding gzip deflateuseragent mozilla40 compatible msie 60 windows nt 51 sv1 net clr 114322 emusic dlm4 net clr 2050727host localhost1238contentlength 2connection keepalivepragma nocachei have tried setting the contenttype to textjson and get the same resultshere is the web service methodwebmethod public function getdate as string just playing around with newtonsoftjson dim sb as new stringbuilder dim sw as new iostringwritersb dim strout as string stringempty using jw as new jsontextwritersw with jw writestartobject writepropertynamedatetime writevaluedatetimenowtostring writeendobject end with strout swtostring end using return stroutend functionand here is what it returnsxml version10 encodingutf8string xmlnsdatetime132008 60422 pmstringdoes anyone know how to force the web service to return json when i ask for jsonplease do not tell me to upgrade to net framework 35 or anything like that i am not that stupid i need a 20 solution,"['jquery', '.net', 'asp.net']" +3940,c list sort by x then y similar to list orderby alphabetical order we want to sort by one element then another we want to achieve the functional equivalent of select from table order by x y we have a class that contains a number of sorting functions and we have no issues sorting by one elementfor example public class myclass public int x public int y listmyclass mylistpublic void sortlist mylistsort mysortingfunction and we have the following in the list unsorted sortedx desired id x y id x y id x y0 0 1 2 0 2 0 0 11 1 1 0 0 1 2 0 22 0 2 1 1 1 1 1 13 1 2 3 1 2 3 1 2stable sort would be preferable but not required solution that works for net 20 is welcome,"['c#', '.net']" +3946,problem deallocing memory used by uiimageviews with fairly large image in an uiscrollview i have a large uiscrollview into which i am placing 34 rather large 320x1500 pixels or so uiimageview image tiles i am adding these uiimageviews to the scroll view inside of my nib files i have one outlet on my controller and that is to the uiscrollview i am using a property nonatomic retain for this and sythesizing itmy question is this when i observe this in memory monitor i can see that the memory used goes up quite a bit when the view with all these images is loaded as expected but when i leave the view it and its controller are deallocd but do not seem to give up anywhere near the memory they had taken up when i cut one of these views there are several in my app down to just 13 images that were 320x460 and left everything else the same it recaptures the memory just fineis there some issue with using images this large am i doing something wrong in this code pasted belowthis is a snippet from the viewcontroller that is causing problems cgfloatfindheight uiimageview imageview nil nsarray subviews selfscrollview subviews cgfloat maxyloc 0 for imageview in subviews if imageview iskindofclassuiimageview class cgrect frame imageviewframe if frameoriginy framesizeheight maxyloc maxyloc frameoriginy maxyloc framesizeheight return maxyloc voidviewdidload super viewdidload selfscrollview setcontentsizecgsizemake320 self findheight selfscrollview setcancancelcontenttouchesno selfscrollviewindicatorstyle uiscrollviewindicatorstylewhite selfscrollviewclipstobounds yes selfscrollviewscrollenabled yes selfscrollviewpagingenabled no voiddealloc nslogday controller deallocd selfscrollview nil super deallocupdate i have noticed another weird phenomenon if i do not use the scroll on the view it seems to be hanging on to the memory but if i scroll around a bunch and ensure that all of the uiimageviews became visible at one point it will free up and regain most of the memory it lostupdate2 the reason i am asking this is my app is actually crashing due to low memory i wouldnt mind if it were just caching and using up extra memory but it does not seem to ever release it even in didreceivemmorywarning conditions,"['iphone', 'objective-c']" +3949,cannot get regular expression work correctly with multiline i have a quite big xml output from an application i need to process it with my program and then feed it back to the original program there are pieces in this xml which needs to be filled out our replaced the interesting part looks like thissyscustomtag syssid1 systypeprocesstart systagvaluesystag here are some other tags systagvaluesystagsyscustomtag syssid1 systypeprocesend and the document contains several pieces like thisi need to get all xml pieces inside these tags to be able to make modifications on it i wrote a regular expression to get those pieces but it does not workxmldocument xmldoc new xmldocumentxmldocloadoutputxmlregex regexp new regexsyscustomtagprocesstartsyscustomtag procesend regexoptionsmultiline regexoptionsignorepatternwhitespace regexoptionscultureinvariantmatchcollection matches regexpmatchesxmldocinnerxmlif i leave the whole stuff in one line and call this regexp without the multiline option it does find every occurences by leaving the file as it is and set the multiline option it does not work what is the problem what should i change or is there any easier way to get the xml parts between these tags without regexp,['c#'] +3955,where can i find the maven installation directory in eclipse 34 i have installed m2eclipse plugin from now i want to use that as a standalone build tool but i am unable to find the installation directory can anyone help me in this,['java'] +3960,is there a delegate available for properties in c given the following class class testclass public void setvalueint value value value public int value get set i can do testclass tc new testclassactionint setaction tcsetvaluesetactioninvoke12which is all good is it possible to do the same thing using the property instead of the method preferably with something built in to net,"['c#', '.net']" +3981,windows forms error a stronglynamed assembly is required i have a windows forms project vs 2005 net 20 the solution has references to 9 projects everything works and compiles fine on one of my computers when i move it to a second computer 8 out of the 9 project compile with no problem when i try to compile the 9th project the main project for the application produces the exe file to execute the application i get the following error error 3 a stronglynamed assembly is required exception from hresult 0x80131044the file location for the error is is listed as cpathtoapplc i have checked in the project properties and all of the projects are set to build in debug mode none of them are supposed to be signed in the project that is failing the only assembly that it references that is not in any of the other projects is microsoftvisualbasic a net 20 assembly so i am at a loss to find what ids causing this error the file referenced above in the error message lc does not exist anyone know how i can force the project to accept all unsigned assemblies or to determine which assembly is the culpritthe only meaningful difference between the dev environments between the dev environment where this worked and the current one is that the first was xp and this is vista64 however a colleague of mine who is using xp is getting the same errorthirdparty assemblies being usedcomponentfactorykryptontoolkitcomponentfactorykryptonnavigatorvistadbnet20all of these are referenced in other projects in the solution which build with no problems so it does not look like these are the problemso far i have tried deleting the suo file rebuild all unloading and reloading projects from the solution removing and readding referenced assemblies nothing has worked,['.net'] +3987,mark parameters as not nullable in cnet is there a simple attribute or data contract that i can assign to a function parameter that prevents null from being passed in cnet ideally this would also check at compile time to make sure the literal null is not being used anywhere for it and at runtime throw argumentnullexceptioncurrently i write something like if null arg throw new argumentnullexceptionarg for every argument that i expect to not be nullon the same note is there an opposite to nullable whereby the following would failnonnullablestring s null throw some kind of exception,"['c#', '.net']" +3990,how to assign date parameters to hibernate query for current timezone when you assign a date to a named sql parameter hibernate automatically converts it to gmt time how do you make it use the current server timezone for all dateslets say you have a queryquery q sessioncreatequeryfrom table where date field nowqsetdatenow new javautildatenow will be set to gmt time while new date gets your current server timethanks,['java'] +3991,how do i split a huge text file in python i have a huge text file 1gb and sadly the text editor i use would not read such a large file however if i can just split it into two or three parts i will be fine so as an exercise i wanted to write a program in python to do it what i think i want the program to do is to find the size of a file divide that number into parts and for each part read up to that point in chunks writing to a filenamen output file then read upto the next linebreak and write that then close the output file etc obviously the last output file just copies to the end of the input filecan you help me with the key filesystem related parts filesize reading and writing in chunks and reading to a linebreaki will be writing this code testfirst so there is no need to give me a complete answer unless its a oneliner,['python'] +3998,how wrong is it to have a unique and normal index on the same column i have the following table structurecreate table table id int11 not null auto increment date expired datetime not null user id int11 not null foreign id int11 not null primary key id unique key date expired date expireduser idforeign id key user id user id enginemyisam default charsetutf8 collateutf8 unicode cias youll notice i have duplicate indexes on user id date expired user id i of course want the unique index because i want to ensure the data is uniquethe reason for the duplicate indexes is because without the user id index my main search query takes 4 seconds with the extra index it takes 1 second the query is joining the table on user id and checking date expiredthe table only has 275 recordshow bad is it to have a unique and normal index on the same fieldhow bad is it to have larger indexes than data when the table is purely ids,['mysql'] +4008,how to correctly unregister an event handler in a code review i stumbled over this simplified code fragment to unregister an event handler fire new mydelegateonfirei thought that this does not unregister the event handler because it creates a new delegate which had never been registered before but searching msdn i found several code samples which use this idiomso i started an experimentinternal class program public delegate void mydelegatestring msg public static event mydelegate fire private static void mainstring args fire new mydelegateonfire fire new mydelegateonfire firehello 1 fire new mydelegateonfire firehello 2 fire new mydelegateonfire firehello 3 private static void onfirestring msg consolewritelineonfire 0 msg to my surprise the following happenedfirehello 1 produced two messages as expectedfirehello 2 produced one messagethis convinced me that unregistering new delegates worksfirehello 3 threw a nullreferenceexception debugging the code showed that fire is null after unregistering the eventi know that for event handlers and delegate the compiler generates a lot of code behind the scene but i still do not understand why my reasoning is wrongwhat am i missingadditional question from the fact that fire is null when there are no events registered i conclude that everywhere an event is fired a check against null is required,"['c#', '.net']" +4028,how to use castle windsor with aspnet web forms i am trying to wire up dependency injection with windsor to standard aspnet web forms i think i have achieved this using a httpmodule and a customattribute code shown below although the solution seems a little clunky and was wondering if there is a better supported solution out of the box with windsorthere are several files all shown together here indexaspxcs public partial class indexpage systemwebuipage protected void page loadobject sender eventargs e loggerwritepage loading inject public ilogger logger get set windsorhttpmodulecs public class windsorhttpmodule ihttpmodule private httpapplication application private iocprovider iocprovider public void inithttpapplication context application context iocprovider context as iocprovider if iocprovider null throw new invalidoperationexceptionapplication must implement iocprovider applicationprerequesthandlerexecute initiatewindsor private void initiatewindsorobject sender systemeventargs e page currentpage applicationcontextcurrenthandler as page ifcurrentpage null injectpropertiesoncurrentpage currentpageinitcomplete delegate injectusercontrolscurrentpage private void injectusercontrolscontrol parent ifparentcontrols null foreach control control in parentcontrols ifcontrol is usercontrol injectpropertiesoncontrol injectusercontrolscontrol private void injectpropertiesonobject currentpage propertyinfo properties currentpagegettypegetproperties foreachpropertyinfo property in properties object attributes propertygetcustomattributestypeof injectattribute false ifattributes null attributeslength 0 object valuetoinject iocprovidercontainerresolvepropertypropertytype propertysetvaluecurrentpage valuetoinject null globalasaxcs public class global systemwebhttpapplication iocprovider private iwindsorcontainer container public override void init baseinit initializeioc private void initializeioc container new windsorcontainer containeraddcomponentilogger logger public iwindsorcontainer container get return container public interface iocprovider iwindsorcontainer container get,['asp.net'] +4029,what is the difference between cil and msil il are these two terms interchangeable,['.net'] +4032,how to expand select option width after the user wants to select an option maybe this is an easy question maybe not i have a select box where i hardcode with width say 120pxselect stylewidth 120px optionabcoption optionreally long text really long text really long textoptionselecti want to be able to show the second option so that the user can see the full length of the textlike everything else this works fine in firefox but does not work with internet explorer6,['css'] +4035,dragging an image in wpf i am trying to create a wpf application where i can drag an image aroundcurrently i have an image placed in the center of the window and i am thinking of using the three mouseevents mousedown mousemove and mouseup to calculate the new position when dragging the imageare there any other good ideas on how to do this i am totally new to wpf so my mindset is still in the windows forms worldas far as i can see i need to use a in order to have absolute positioning available,['.net'] +4036,how do i retrieve an html elements actual width and height suppose that i have a div that i wish to center in the browsers thisplay viewport to do so i need to calculate the width and height of the div element what should i use please include information on browser compatibility,"['javascript', 'html']" +4037,how do you call a constructor for global objects for arrays of objects and for objects inside classesstructs how would you call the constructor of the following class in these three situations global objects arrays of objects and objects contained in another clastructthe class with the constructor used in all three examplesclass foo public fooint a b a private int band here are my attempts at calling this constructorglobal objectsfoo global foo3 works but i cannot control when the constructor is calledint main arrays of objectsint main array on stack foo array of foos303 does not work array on heap foo pointer to another array new foo3 30 does not workthere i am attempting to call the constructor for all elements of the arrays but i would also like to know how to call it on individual elementsobjects contained in classesstructsclass bar foo foo3 does not workint main bar bar,['c++'] +4040,how do i find userid by login python under nix i need to set my process to run under nobody i have found ossetuid but how do i find uid if i have logini have found out that uids are in etcpasswd but maybe there is a more pythonic way than scanning etcpasswd anybody,['python'] +4045,how do you show animated gifs with net compact framework i would like to thisplay an animated gif on a net compact formcurrently i use a picturebox control and toggle between visible true and visible falseafter visible true the gif is shown however it is not animated how can i get the net compact framework to animate iti already tried this but it does not work,['.net'] +4052,c mark as deprecated i have a method in an interface that i want to deprecate with portable cwhen i googled for this all i got was a microsoft specific solution pragma deprecated and declspecdeprecateda second prize solution would be to ifdef a msvc and a gcc solutionthanks,['c++'] +4058,what is a partial class what is and how can it be used in ccan you use the same concept in pythonperl,"['c#', 'python']" +4064,systemrandom keeps on returning the same value i am using a systemrandom object which is instantiated with a fixed seed all thoughout the application i am calling the nextdouble method and after some time passed i am getting 00 as resultis there any remedy to this has anyone else encountered this edit i have one seed for the whole run which is set to 10 for convience sake the randomnextdouble is called several hundred thousand times it is an optimizer application and could run for couple hours but this actually happens after 100 mins of execution i have recently added little bit more random calls to the app,['.net'] +4066,how can i abort a running jdbc transaction is there a way to prematurely abort a transaction say i have sent a command to the database which runs five minutes and after four i want to abort itdoes jdbc define a way to send a stop whatever you are doing on this connection signal to the db,['java'] +4069,how can i lock the first row and first column of a table when scrolling possibly using javascript and css how can i create a table that has its first row and first column both locked as in excel when you activate freeze panes i need the table to both scroll horizontally and vertically a lot of solutions for this exist but only allow vertical scrollingso when you scroll down in the table the first row will stay put since it will have the column headings this may end up being in a thead or it may not whatever makes the solution easierwhen you scroll right the first column stays put since it holds the labels for the rowsi am pretty certain this is impossible with css alone but can anyone point me toward a javascript solution it needs to work in all major browsers,"['javascript', 'css']" +4079,performance comparison of thrift protocol buffers json ejb other were looking into transportprotocol solutions and were about to do various performance tests so i thought i would check with the community if they have already done thishas anyone done server performance tests for simple echo services as well as serializationdeserialization for various messages sizes comparing ejb3 thrift and protocol buffers on linuxprimarily languages will be java cc python and phpupdate i am still very interested in this if anyone has done any further benchmarks please let me know also very interesting benchmark showing compressed json performing similar better than thrift protocol buffers so i am throwing json into this question as well,"['java', 'python']" +4080,thisappearing foreign keys in phpmyadmin i am creating a new table inside mysql and i am trying to add a foreign key constraint to one of the fieldscreate table onlineorder receiptid varchar10 not null default delivereddate date default null cid int10 not null card int10 default null expire date default null primary key receiptid foreign key receiptid references purchase enginemyisam default charsetlatin1however after it creates it i go into phpmyadmin and export the table and it seems like the foreign key constraint has thisappearedcreate table onlineorder receiptid varchar10 not null default delivereddate date default null cid int10 not null card int10 default null expire date default null primary key receiptid enginemyisam default charsetlatin1does phpmyadmin get rid of foreign keys or am i doing something wrong here,['mysql'] +4085,how do you get the current time of day how do you get the current time not date and timeexample 54212 pm,['c#'] +4087,how to generate sound effects in java i am looking for java code that can be used to generate sound at runtime not playback of existing sound filesfor example whats the best code for generating a sawtooth waveform at 440 hz for a duration of 2 milliseconds source code appreciatedi remember my commodore 128 had a simple sound command that took as parameters voice frequency waveform and duration to define a sound that worked great in a lot of simple cases quick and dirty games experiments with sound etci am looking specifically for soundeffect like sounds not music or midi which the jfugue library covers quite well,['java'] +4095,list of email addresses that can be used to test a javascript validation script does anyone have a list of email addresses that i can use to test my js address validation script i am looking for as complete of a list as is reasonable to test the most common edge cases if not all cases,['javascript'] +4100,creating a selector from a method name with parameters i have a code sample that gets a sel from the current object sel callback selectormymethodparameter2and i have a method like voidmymethodidv1 parameter2nsstringv2 now i need to move mymethod to another object say mydelegatei have triedsel callback selectormydelegate mymethodparameter2but it would not compile,['objective-c'] +4115,how to get the current directory in a c program i am making a c program where i need to get the directory that the program is started from this program is written for unix computers i have been looking at opendir and telldir but telldir returns a off t long int so it really does not help me how can i get the current path in a string char array,['c'] +4117,getting xml schema from ms sql database is it possible to generate a xml schema of a database programatically with net and c i want to look into ndbunit but for big databases it would not really be feasible to make a schema manually,['.net'] +4118,how do i select text nodes with jquery i would like to get all descendant text nodes of an element as a jquery collection what is the best way to do that,"['javascript', 'jquery']" +4121,split string containing commandline parameters into string in c i have a single string that contains the commandline parameters to be passed to another executable and i need to extract the string containing the individual parameters in the same way that c would if the commands had been specified on the commandline the string will be used when executing another assemblies entrypoint via reflectionis there a standard function for this or is there a preferred method regex for splitting the parameters correctly it must handle delimited strings that may contain spaces correctly so i cannot just split on example stringstring parameterstring srcctmpsome foldersub folder users taskssometasksome other task someparam fooexample resultstring parameterarray new string srcctmpsome foldersub folder users taskssometasksome other task someparam fooi do not need a commandline parsing library just a way to get the string that should be generatedupdate i had to change the expected result to match what is actually generated by c removed the extra s in the split strings,['c#'] +4132,web service or dll i am creating an app that needs to be accessed by both a web front end hosted on an internal network and also run as a scheduled task nothing will need to be accessed outside of our internal systems and once the app is up and running we do not envision anything changing for some timemy initial thought is to create a dll encapsulating the bulk of the necessary functionality and then call it via both a web forms interface for manual execution and a console app running as an automated daily scheduled taskanother suggestion has been to expose a web service for the core functionality instead but as the app will never need to be called by an external resource i think the extra effort required in implementing a web service might not be worth the hassle the dll solution should also be substantially fastermy question is which route would you choose are there any proscons that i have not covered any glaring omissionsthisclaimer i am new to net but due to one of our developers being involved in a serious accident i have been asked to step up to the plate,['.net'] +4138,how can i send an array to php through ajax i want to send an array constructed in javascript with the selected values of a multiple select is there a way to send this array to a php script using ajax,['php'] +4142,simple oracle sql date syntax question i am trying to convert a working ms access query to run on an oracle database being accessed via vb script asp this is the last section of the where clausesql sql where uathbmb mode a and uathbprint date sd and uathbprint date ed the variable sd ie start date is a text string that can contain a value such as 12008 the same goes for the variable ed ie end datehowever the dates do not work does oracle require a special way to use datesdo the dates have to be converted do i surround them with the keyword like you would in ms access,['sql'] +4143,how to center an image horizontally and align it to the bottom of the container how can i center an image horizontally and aligned to the bottom of the container at the same time i have been able to center the image horizontally by its self i have also been able to align the bottom of the container by its self but i have not been able to do both at the same time here is what i haveimage block width 175px height 175px position relative margin 0 autoimage block a img position absolutebottom 0div classimage block a hrefimg src border0adivthat code aligns the image to the bottom of the div what do i need to addchange to make it also center the image horizontally inside the div the image size is not known before hand but it will be 175x175 or less,['css'] +4144,how should i set the default proxy to use default credentials the following code works for mevar webproxy webproxygetdefaultproxywebproxyusedefaultcredentials truewebrequestdefaultwebproxy webproxyunfortunately webproxygetdefaultproxy is deprecated what else should i be doingusing appconfig to set the defaultproxy settings is not allowed in my deployment,['.net'] +4151,how to prevent text in a table cell from wrapping does anyone know how i can prevent the text in a table cell from wrapping this is for the header of a table and the heading is a lot longer than the data under it but i need it to thisplay on only one line it is okay if the column is very widethe html of my simplified table looks like thistable thead tr th divreally long column headingdiv th th divreally long column headingdiv th th divreally long column headingdiv th th divreally long column headingdiv th th divreally long column headingdiv th th divreally long column headingdiv th th divreally long column headingdiv th tr thead tbody tr td divdatadiv td td divdatadiv td td divdatadiv td td divdatadiv td td divdatadiv td td divdatadiv td td divdatadiv td tr tbodytablethe heading itself is wrapped in a div inside the th tag for reasons pertaining to the javascript on the page the table is coming out with the headings wrapping onto multiple lines this seems to only happen when the table is sufficiently wide as the browser is trying to avoid horizontal scrolling in my case though i want horizontal scrollingany ideas,"['html', 'css']" +4155,force php integer overflow we have some integer arithmetic which for historical reasons has to work the same on php as it does in a few statically typed languages since we last upgraded php the behavior for overflowing integers has changed basically we are using following formulafunction fx1 x2 x3 x4 return x1 x2 x3 x4however even with conversionsfunction fx1 x2 x3 x4 return intvalintvalintvalx1 x2 x3 x4i am still ending up with the completely wrong numberfor example with x1 1580033017 x2 2072974554 x3 1170476976 and x4 1007518822 i end up with 30512150 in php and 1617621783 in cjust adding together x1 and x2 i cannot get the right answerin c i get1580033017 2072974554 641959725in phpintvalintval1580033017 intval2072974554 2147483648which is the same asintval1580033017 2072974554 2147483648i do not mind writing a integeroverflowadd function or something but i cannot quite figure out how 1580033017 2072974554 equals 641959725 i do recognize that it is 2147483648 2 231 but 2147483648 231 is 1505523923 which is greater than intmin so why is do you add 2231 and not 231any help would be appreciated,"['c#', 'php']" +4160,what are the differences between various threading synchronization options in c can someone explain the difference betweenlock someobject using mutexusing semaphoreusing monitorusing other net synchronization classesi just cannot figure it out it seems to me the first two are the same,['c#'] +4162,whats a php framework and whats a good one i am running a site about php frameworks but i cannot find a exact definition for it and i am always thinking a question how to make out a good php framework features manual efficiency or something,['php'] +4164,how can io priority of a process be increased i want to increase the io priority of a process answers for both net and windows vista would be nice processexplorer is ok as well,['.net'] +4165,determine if type is a pointer in a template function if i have a template function for example like thistemplatetypename tvoid funcconst stdvectort vis there any way i can determine within the function whether t is a pointer or would i have to use another template function for this ietemplatetypename tvoid funcconst stdvectort vthanks,['c++'] +4178,what causes an application pool in iis to recycle i have been searching for info on this to no avail the context of why i need this is another question i asked here more specifically does creatingupdatingdeleting files in app data cause a pool recycleif someone could provide a detailed list of what causes a recycle that would be greatupdate as two users already noticed i would also be happy to an answer specifying reasons for recycling the appdomain only and not the whole pool,['asp.net'] +4182,java collections lifo structure i am looking in the collections framework of java for a lifo structure stack without any success basically i want a really simple stack my perfect option would be a deque but i am in java 15i would like not to have to add another class to my structure but i am wondering if that is possibleis there any class in the collections framework 15 that does the jobif not is there any way to turn a queue in a lifo queue aka stack without reimplementationif not which interface or class should i extend for this task i guess that keep the way that the guys of sun have made with the deque is a good startthanks a lotedit i forgot to say about the stack class i have my doubts about this class when i saw that it implements the vector class and the vector class is a little bit obsolete is not it,['java'] +4190,net 35 chart controls exception error executing child request for chartimgaxd anyone getting this error when using the new free chart controls ms bought from dundaserror executing child request for chartimgaxdon the msdn forum they suggested it was my webconfig msdn forum postso far that has not fixed the problem though any other ideas,['.net'] +4195,how do i removedelete a folder that is not empty with python i am getting an access is denied error when i attempt to delete a folder that is not empty i used the following command in my attempt osremovefolder name what is the most effective way of removingdeleting a folderdirectory that is not empty,['python'] +4199,setting avisited link to same state as alink and ahover i am working on a idea where my alink have one state blue no underline etc with a ahover being white i want my visited links to have the same state as alink and ahover is this possible supported in most common browsers,['css'] +4203,is there a javascript alert that does not pause the script i am looking for something like alert but that does not pause the scripti want to thisplay an alert and allow the next command a form submit to continue so the page will be changing after the alert is thisplayed but it would not wait till the user has clicked okis there something like this or is it just one of those impossible things,['javascript'] +4206,whats the best way to parse a body of text against multiple 15 regexes on each line i have a body of text that i have to scan and each line contains at least 2 and sometimes four parts of information the problem is that each line can be 1 out of 1520 different actionsin ruby the current code looks somewhat like thistextsplitneach do line around 20 times expressionsactionseach do pat reg around 20 timesthis obviously is the problemi did manage to make it faster in c by a 50 margin by combining all the regexen into one but that is still not the speed i require i need to parse thousands of these files fastright now i match them with regexes however this is intolerably slow i started with ruby and hopped over to c in hopes that i would get a speed boost and it just is not happeningi have casually read on pegs and grammar based parsing but it looks somewhat difficult to implement is this the direction i should head or are there different routesbasically i am parsing poker hand histories and each line of the hand history usually contains 23 bits of information that i need to collectwho the player was how much money or what cards the action entailed etcsample text that needs to be parsedburiedtens posts 5the button is in seat 4 hole cards dealt to mayhem 31337 8s adsherwin7 foldsonemike foldssyhg99 calls 5buriedtens raises to 10after i collect this information each action is turned into an xml noderight now my ruby implementation of this is much faster than my c one but that is prob just cause i have not written in c code for well over 45 yearsupdatei do not want to post all the code here but so far my handssecond look like the following588 handssecond boostspirit in c60 handssecond 1 very long and complicated regex in c all the regexen put together33 handssecond normal regex style in rubyi am currently testing antlr to see if we can go any further but as of right now i am very very happy with spirit is resultsrelated question efficiently querying one string against multiple regexes,['ruby'] +4214,how to pass a parameter to a dynamically set javascript function ok i have one javascript that creates rows in a table like this function addrowtextrowid var tbl documentgetelementbyidtblnotepanel var row tblinsertrowtblrowslength var cell rowinsertcell var textnode documentcreatetextnodetext cellid rowid cellstylebackgroundcolor gold cellonclick clicktest cellappendchildtextnode in the above function i set the cells onclick function to call another javascript function called clicktest my question is when i assign the onclick event to call clicktest how do i set parameter information to be sent when the clicktest method is called on the cells onclick event or how do i access the cells id in the clicktest functionthanksjeff,['javascript'] +4215,why does aspnet webforms need the runatserver attribute why do i have to specify runatserver on all my aspnet controls when it is a mandatory attribute and server is the only option available in my limited knowledge of aspnet and i get an error if i do not use iti do understand that i can optionally use it on my html tags and i do understand the clientserver paradigm and what it is actually specifyingis it a redundant tag that could just be implied by the control being an aspnet control or is there an underlying reason,['asp.net'] +4226,does using delegates slow down my net programs does using delegates slow down my programs i have been avoiding them because i really have no clue if they make my programs any slower i know if i cause a catch exception that uses quite a bit of cpu power but i do not know about delegates and events and what net does to them,['.net'] +4228,enabling auditing feature in sqlserver 2005 did you ever use sql server auditing features on a production dbhow did that impact on performances and are there differences you noticed between different versions of sql serveralso how we need to enable the audit features,['asp.net'] +4231,how to choose returned column name in a select for xml query ms sql has a convenient workaround for concatenating a column value from multiple rows into one valueselect col1 from table1 where col2 x order by col3 for xml pathand that returns a nice recordsetxml f52e2b6118a1d1b10500805f49916b col1foocol1col1barcol1only the column name in the returned recordset is rather nastythe column name seems to include random elements or a guid and hence i am reluctant to use it in my application different instances or different servers might have another guid unfortunately i cannot use to select the value and due to the restrictions in the existing application i cannot iterate through returned columns eitheris there a way to force the column name in the returned recordset to something more sensible,['sql'] +4235,which is the best maven eclipse plugin there is two available eclipse plugins for maven eclipse iam old name is q4em2eclipsem2eclipse seems to be the oldest but the more robust is there any key differences between the two which one should be chosen for a project starting today and why update m2eclipse is moving to eclipseorg and will be included in the indigo release train eclipse 37 see m2e at eclipse what will this mean for you and m2eclipse is moving to eclipseorg the accepted answer is thus even more correct,['java'] +4238,how to determine if a string is a number in c i am working on a tool where i need to convert string values to their proper object types eg convert a string like 20081120t163321z to a datetime value numeric values like 42 and 4242 must be converted to an int32 value and a double value respectively what is the best and most efficient approach to detect if a string is an integer or a number are int32tryparse or doubletryparse the way to go,"['c#', '.net']" +4242,how would you construct and interact with a grid like a sudoku board what do you think is the best way to implement an interactive grid similar to a sudoku board for a native iphone application i did not see an object to fill this need in the sdkshould i make a custom control for an individual cell then initialize as many of them as i need in a grid formany and all comments are welcomethanks,"['iphone', 'objective-c']" +4243,accessing environment variables from windows services i am attempting to write a windows service in c i need to find the path to a certain file which is stored in an environment variable in a regular c console application i can achieve that with the following linestring t systemenvironmentgetenvironmentvariabletip homeif i write that to the console i see that it was successfulnow if i try that same code in a windows service the string t is emptyany idea why,['c#'] +4244,hibernate annotation placement question i have got what i think is a simple question i have seen examples both ways the question is why cannot i place my annotations on the field let me give you an exampleentitytablenamewidgetpublic class widget private integer id id generatedvaluestrategygenerationtypeauto public integer getid return thisid public integer setidinteger id thisid idthe above code works fine assuming there is not a typo in there when the annotation is placed on the getter of the property everything is perfecthowever that seems awkward to me in my mind it is cleaner to place the annotation on the field like so entitytablenamewidgetpublic class widget id generatedvaluestrategygenerationtypeauto private integer id public integer getid return thisid public integer setidinteger id thisid idi have seen examples of both ways however when i run this second example i get the followingjavalangnullpointerexception at comwidgetutilhibernatehibernatesessionfactorythreadlocalsessioninitialvaluehibernatesessionfactoryjava25 at comwidgetutilhibernatehibernatesessionfactorythreadlocalsessioninitialvaluehibernatesessionfactoryjava1 at javalangthreadlocalthreadlocalmapgetaftermissunknown source at javalangthreadlocalthreadlocalmapgetunknown source at javalangthreadlocalthreadlocalmapaccess0unknown source at javalangthreadlocalgetunknown source at comwidgetutilhibernatehibernatesessionfactorygethibernatesessionfactoryjava33 at comwidgetdbdaoabstractdaoabstractdaojava12 at comwidgetdbdaowidgetdaowidgetdaojava9 at comwidgetdbdaotestwidgetdaotestfindbyidwidgetdaotestjava17 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokeunknown source at sunreflectdelegatingmethodaccessorimplinvokeunknown source at javalangreflectmethodinvokeunknown source heres the skeleton of hibernatesessionfactory line 25 is marked protected session initialvalue sessionfactory sessionfactory nulltry configuration cfg new annotationconfigurationconfigurestring url systemgetpropertyjdbcurlif url null cfgsetpropertyhibernateconnectionurl urlsessionfactory cfgbuildsessionfactorycatch exception e session session sessionfactoryopensession line 25return sessionanyone have an idea whats going on here,['java'] +4249,python decorator makes function forget that it belongs to a class i am trying to write a decorator to do loggingdef loggermyfunc def newargs keyargs print entering ss myfuncim class name myfunc name return myfuncargs keyargs return newclass cobject logger def f passcfi would like this to printentering cfbut instead i get this error messageattributeerror function object has no attribute im classpresumably this is something to do with the scope of myfunc inside logger but i have no idea what,['python'] +4251,how do i randomly select an item from a list using python assume i have the following listfoo a b c d ewhat is the simplest way to retrieve an item at random from this list,['python'] +4255,search for a regexp in a java arraylist arraylist string list new arraylist listaddbeholdlistaddbendlistaddbetlistaddbearlistaddbeatlistaddbecomelistaddbeginthere is a way to search for the regexp bea and get the indexes like in arraylistindexof edit returning the items is fine but i need something with more performance than a linear search,['java'] +4260,how do you spawn a child process in ruby i want to offload a block of code in my main process to child process to make it run concurrently i also want to have the pid of the spawned child process so i can monitor and kill it if necessary,['ruby'] +4268,how do i select a single element in jquery i have a table structure that looks liketable tr idrow1 td divrow 1 content1div td td divrow 1 content2div td td divrow 1 content3div td tr tr idrow2 td divrow 2 content1div td td divrow 2 content2div td td divrow 2 content3div td tr tr idrow3 td divrow 3 content1div td td divrow 3 content2div td td divrow 3 content3div td trtableusing jquery i am trying to select the div in the second cell of the third row i tried the following amongst other thingsvar d row3childreneq1childreneq0what i get back is an array with a single element the div i am after and i have to then access using d0 why is jquery returning a single element array i thought using the selector above would return the div element directlyshog9 duhok a light just switched on in my brain i get it now cheers,"['javascript', 'jquery']" +4270,how do exceptions work behind the scenes in c i keep seeing people say that exceptions are slow but i never see any proof so instead of asking if they are i will ask how do exceptions work behind the scene so i can make a decisions of when to use them and if they are slowfrom what i know exceptions are the same thing as doing a bunch of return but it also checks when it needs to stop doing the return how does it check when to do stop i am taking a guess and saying there is a second stack which holds the type of exception and stack location then does returns until it gets there i am also guessing the only time that stack is touch is on a throw and every trycatch afaict implementing a similar behaviour with return code would take the same amount of time but this is all a guess so i want to knowhow do exceptions really work,['c++'] +4272,how to remove duplicate values from an array in php how can i remove duplicate values from an array in php,['php'] +4275,complex builds in visual studio i have a few things that i cannot find a good way to perform in visual studioprebuild step invokes a code generator that generates some source files which are later compiled this can be solved to a limited extent by adding blank files to the project which are later replaced with real generated files but it does not work if i do not know names andor the number of autogenerated source files i can easily solve it in gnu make using wildcard generatedc how can i do something similar with visual studiocan i prevent prebuildpostbuild event running if the files do not need to be modified make behaviour the current workaround is to write a wrapper script that will check timestamps for me which works but is a bit clunkywhat is a good way to locate external libraries and headers installed outside of vs in nix case they would normally be installed in the system paths or located with autoconf i suppose i can specify paths with userdefined macros in project settings but where is a good place to put these macros so they can be easily found and adjustedjust to be clear i am aware that better windows build systems exist cmake scons but they usually generate vs project files themselves and i need to integrate this project into existing vs build system so it is desirable that i have just plain vs project files not generated ones,"['c++', 'c']" +4280,convert a string to a date in c i know this may be simple but being c i doubt it will be how do i convert a string in the form 01012008 to a date so i can manipulate it i am happy to break the string into the day month year constituents also happy if solution is windows only,['c++'] +4281,netbeans or eclipse for c i am currently working on a pet project and need to do c development on windows mac linux and solaris and i have narrowed it down to netbeans and eclipse so i was wonderig which is more solid as a c editor i just need solid editing good autocompletion for templated code ad external libraries and project file management the build tools are external so thats irrelevant here for my comparisonthus which is a better choicenote i know i should be using emacs or vim but the issue is my theory at least that i am left handed so i use my right side designcreativity of the brain more than the left side logic memory so i just simply cannot use emacs or vim my brain simply is not compatible i tried them many times too even used emacs for a few months but it drove me crazythanks,['c++'] +4300,declareandthrow vs throwwithoutbeingdeclared exceptions in java what is the difference between the twin methodspublic void methoda throws anexception do something throw new anexceptionpublic void methoda do the same thing throw new anexceptioni have a intuition that it has something to do with being a welldesigned method because i put methoda in an interface declared it the way methoda does in its implementation and received a warning from java that a cannot override a because a does not throw anexception is this speculation correct is there any other subtle connotations in the two ways of doing things,['java'] +4302,custom view transition in opengl es i am trying to create a custom transition to serve as a replacement for a default transition you would get here for exampleselfnavigationcontroller pushviewcontrollersomecontroller animatedyesi have prepared an openglbased view that performs an effect on some static texture mapped to a plane let us say it is a copy of the flip effect in core animation what i do not know how to do isgrab current view content and make a texture out of it i remember seeing a function that does just that but cannot find ithow to do the same for the view that is currently offscreen and is going to replace current view are there some apis i can hook to in order to make my transition class as native as possible make it a kind of core animation effectany thoughts or links are greatly appreciatedupdatejeffrey forbess answer works great as a solution to capture the content of a view what i have not figured out yet is how to capture the content of the view i want to transition to which should be invisible until the transition is donealso which method should i use to present the opengl viewfor demonstration purposes i used pushviewcontroller that affects the navbar though which i actually want to go one item back with animation check this vid for explanationanother option would be to go with presentviewcontroller but that shows fullscreendo you think maybe creating another window or view could be useful,['iphone'] +4308,passing interface in a wcf service i am experimenting with wcf services and have come across a problem with passing interfacesthis worksservicecontractpublic interface ihomeservice operationcontract string getstringbut this does notservicecontractpublic interface ihomeservice operationcontract idevice getinterfacewhen i try to compile the client it fails on the getinterface method i get an exception saying that it cannot convert object to ideviceon the clientside the ihomeservice class correctly implements getstring with a string as it is returntype but the getinterface has a returntype of object why is not it idevice,"['c#', '.net']" +4314,decode gzipped web page retrieved via curl in php i am retrieving a gzipped web page via curl but when i output the retrieved content to the browser i just get the raw gzipped data how can i decode the data in phpone method i found was to write the content to a tmp file and then f gzopenfilenamercontent gzreadfilename250gzclosef but man there is got to be a better wayedit this is not a file but a gzipped html page returned by a web server,['php'] +4316,meaning of exception in c app not a legal oleaut date does anyone know what this means getting this in c winforms applicationsnot a legal oleaut date,['c#'] +4320,use of prototype vs this in javascript whats the difference betweenvar a function thisx function do something andvar a function aprototypex function do something,['javascript'] +4336,how do i sum a list of arrays i have a list int mylist where i know that all the int arrays are the same length for the sake of argument let us say i have 500 arrays each is 2048 elements long i would like to sum all 500 of these arrays to give me a single array 2048 elements long where each element is the sum of all the same positions in all the other arraysobviously this is trivial in imperative codeint sums new intmylist0lengthforeachint array in mylist forint i 0 i sumslength i sumsi arrayi but i was wondering if there was a nice linq or enumerablex technique,['c#'] +4343,how do i get a div to float to the bottom of its container i have floated images and inset boxes at the top of a container using floatright or left many times recently i hit a need to float a div at the bottom right corner of another div with the normal text wrap that you get with float text wrapped above and to the left onlyi thought this must be relatively easy even though float has no bottom value but i have not been able to do it using a number of techniques and searching the web has not come up with anything other than using absolute positioning but this does not give the correct word wrap behaviouri had thought this would be a very common design but apparently it is not if nobody has a suggestion i will have to break my text up into separate boxes and align the div manually but that is rather precarious and i would hate to have to do it on every page that needs it,"['html', 'css']" +4346,where should a script block with jquery code be placed on an aspnet mvc master page getting started with jquery and having trouble getting hello world type example going for aspnet mvc i get a runtime error object expected when trying to load a page with this script a where should script tags be placed in a master pageb what might i be doing wrong there are definitely a elements in my pagescript srcscriptsjquery126minjs typetextjavascriptscript script srcscriptsjquerycornerjs typetextjavascriptscript script typetextjavascript documentreadyfunction aclickfunctionevent alertthanks for visiting script,['jquery'] +4349,catch the program stopped working on vista on vista i got a problem with the application crash handler basically if something unexpected occurs which cannot be captured by seh i get this popup window with the application stopped working blablabla close programdebug program that is after i thisable the error reporting using the system control panel with error reporting enabled you would get a task dialog with search for solution online close debugthis is not so funny if it happens in automated tools and i wonder whether there is a way to get rid of it totally read if my app crashes it just crashes to the command line or thisappears but does not bring up a dialog,['c'] +4353,what are some of the drawbacks to using cstyle strings i know that buffer overruns are one potential hazard to using cstyle strings char arrays if i know my data will fit in my buffer is it okay to use them anyway are there other drawbacks inherent to cstyle strings that i need to be aware ofedit heres an example close to what i am working onchar buffer1024char line nullwhile line fgetsfp null this would not compile but that is not the issue parse one line of command output herethis code is taking data from a file pointer that was created using a popendf command i am trying to run linux commands and parse their output to get information about the operating system is there anything wrong or dangerous with setting the buffer to some arbitrary size this way,"['c++', 'c']" +4355,actionscript3 to javascript communication best practices on a more abstract level then a previous question in my experience there are 3 ways to call a javascript function on an html page from an embedded swf using as3 externalinterface fscommand and navigatetourllet us compare and contrast these methods and maybe others i have not listed and talk about the pros and cons of each right now externalinterface seems like the way to go in terms of flexibility but is it right for all situations are there concrete benefits in terms of execution speed or anything like that i am curious what do we think,['javascript'] +4358,png transparency with php hey having some trouble trying to maintain transparency on a png when i create a thumbnail from it anyone any experience with this any help would be great heres what i am currently doingfilename jsajaxuploadteesfilenamelistwidth height getimagesizefilenamenewwidth 257newheight 197thumb imagecreatetruecolornewwidth newheightimagealphablendingthumb truesource imagecreatefrompngfilenameimagealphablendingsource trueimagecopyresizedthumb source 0 0 0 0 newwidth newheight width heightimagesavealphathumb trueimagepngthumbnewfilename,['php'] +4362,nsinvocation for dummies how exactly does nsinvocation work is there a good introductioniam specifically having issues understanding how the following code from cocoa programming for mac os x 3rd edition works but then also be able to apply the concepts independently of the tutorial sample the code voidinsertobjectperson p inemployeesatindexintindex nslogadding to p employees add inverse of this operation to undo stack nsundomanager undo self undomanager undo preparewithinvocationtargetself removeobjectfromemployeesatindexindex if undo isundoing undo setactionnameinsert person finally add person to the array employees insertobjectp atindexindex voidremoveobjectfromemployeesatindexintindex person p employees objectatindexindex nslogremoving from p employees add inverse of this operation to undo stack nsundomanager undo self undomanager undo preparewithinvocationtargetself insertobjectp inemployeesatindexindex if undo isundoing undo setactionnamedelete person finally remove person from array employees removeobjectatindexindexi get what itas trying to do btw employees is an nsarray of a custom person classbeing a net guy i try to associate unfamiliar objc and cocoa concepts to roughly analogous net concepts is this similar to netas delegate concept but untyped this isnat 100 clear from the book so iam looking for something supplemental from real cocoaobjc experts again with the goal that i understand the fundamental concept beneath the simpleish example i am really looking to be able to independently apply the knowledge up until chapter 9 i was having no difficulty doing that but now thanks in advance,['objective-c'] +4365,is a good idea to enable jmx lambda probe on a production server we are experiencing some slowdowns on our webapp deployed on a tomcat 5517 running on a sun vm 150 06b05 and our hosting company does not gives enough data to find the problemwe are considering installing lambda probe on the production server but it requires to enable jmx comsunmanagementjmxremote in order to obtain memory and cpu statisticsdoes enabling jmx incur a serious performance penaltyif we enable jmx are we opening any security flaw do i need to setup secure authentication if we are only enabling local acces to jmxis anyone using the same tomcat lambda probe without problems on productionupdatelooking at the answers it seems that enabling jmx alone does not incur significant overhead to the vm the extra work may come if the monitoring application attached to the vm be it jconsole lambda probe or any other is polling with excessive dedication,['java'] +4371,how to convert stdstring to lower case i want to convert a stdstring to lowercase i am aware of the function tolower however in the past i have had issues with this function and it is hardly ideal anyway as use with a string would require iterating over each characteris there an alternative which works 100 of the time,['c++'] +4373,something better than toarray to force enumeration of linq output i am working with linq to objects and have a function where in some cases i need to modify the underlying collection before calling aggregate and then return it to its original state before the funciton returns the results of aggregate my current code looks something like thisbool collectionmodified falseifcollectionneedsmodification modifycollection collectionmodified truevar aggregationresult from a in from b in collection where bsatisfyscondition aggregateaggregationfunction select aneededvalueifcollectionmodified modifycollectionreturn aggregationresulthowever as written if i modify the collection i will get the wrong result because i am putting the collection back in its original state before aggregationresult is enumerated and linq results are lazyevaluated my current solution is to use toarray on my linq query like thisvar aggregationresult from a in from b in collection where bsatisfyscondition aggregateaggregationfunction select aneededvaluetoarraythe size of the resulting array will always be small 100 items so memory processing time is not a concern is this the best way to handle my problem or is there a better way to force the evaluation of a linq query,['c#'] +4378,when are api methods marked deprecated actually going to go away i am code reviewing a change one of my coworkers just did and he added a bunch of calls to datetomonth datetoyear and other deprecated date methods all these methods were deprecated in jdk 11 but he insists that it is ok to use them because they have not gone away yet were using jdk 15 and i am saying they might go away any day now and he should use calendar methods has sun actually said when these things are going away or does deprecated just mean you lose style points,['java'] +4380,how do i perform a unit test using threads executive summary when assertion errors are thrown in the threads the unit test does not die this makes sense since one thread should not be allowed to crash another thread the question is how do i either 1 make the whole test fail when the first of the helper threads crashes or 2 loop through and determine the state of each thread after they have all completed see code below one way of doing the latter is by having a per thread status variable eg boolean statuses and have statusesi false mean that the thread failed this could be extended to capture more information however that is not what i want i want it to fail just like any other unit test when the assertion errors are thrown is this even possible is it desirablei got bored and i decided to spawn a bunch of threads in my unit test and then have them call a service method just for the heck of it the code looks approximately likethread threads new threadmax threadsfor int i 0 i threadslength i threadsi new thread new runnable private final int id threadidsequencenumber public void run try resultrefsid runtest integertostring id returns an object catch throwable t this code is evil it catches even errors do not copy it more on this below final string message error testing thread with id id loggerdebug message t throw new illegalstateexception message t need to wrap throwable in a run time exception so it will compile after this we will loop through the array of threads and start each one after that we will wait for them all to finish finally we will perform some checks on the result referencesfor thread thread threads threadstartloggerdebug waiting for threads to finish boolean done falsewhile done done true for thread thread threads if threadisalive done falsefor int i 0 i resultrefslength i asserttrue youve got the world messed dawg myconditionresultrefsi heres the problem did you notice that nasty trycatchthrowable block i just added that as a temporary hack so i could see what was going on in runtest string a few assertions are made eg assertnotnull null but since it is in a different thread it does not cause the unit test to failmy guess is that we will need to somehow iterate over the threads array check the status of each and manually cause an assertion error if the thread terminated in a nasty way whats the name of the method that gives this information the stack trace of the dead thread,['java'] +4382,flash media serverphp application i need help finding resources that would help me or at least point me in the right direction in building a flash media serverphp application i basically want to improve my current application by instead of progressive download using flash media server so that the videos will not only stream well but they cannot be downloaded by the end userwhat the current application does is show a login form on the homepage and then when logged in the user can then navigate the site by choosing videos from a particular video category or video uploaded by a specific user all this is done with php the video page uses progressive download to thisplay the video after the video id has been passed using phpi need to know how php and flash media server work together are there any resources out there where i can find a good application example really simple that demonstrates how php and flash media server can be used to stream videos dynamically such that php checks for the login video id video channels and video category information while the flash media server streams the video,['php'] +4384,best way to define true false unset state if you have a situation where you need to know where a boolean value was not set for example if that unset value should inherit from a parent value the java boolean primitive and the equivalent in other languages is clearly not adequatewhats the best practice to achieve this define a new simple class that is capable of expressing all three states or use the java boolean class and use null to indicate the unset state,['java'] +4397,what is the best way to determine the number of days in a month with javascript i have been using this function but i would like to know whats the most efficient and accurate way to get itfunction daysinmonthimonth iyear return 32 new dateiyear imonth 32getdate,['javascript'] +4400,rails model without database i want to create a rails 21 and 22 model with activerecord validations but without a database table what is the most widely used approach i have found some plugins that claim to offer this functionality but many of them do not appear to be widely used or maintained what does the community recommend i do right now i am leaning toward coming up with my own solution based on this blog post,"['ruby-on-rails', 'ruby']" +4403,which c library for cgi programming i am looking at doing some work for fun in a compiled language to run some simple tests and benchmarks against phpbasically i would like to see what other people use for c cgi programming including backend database like mysql or something else,['c++'] +4407,how safe is greasemonkey i have never actually used greasemonkey but i was considering using itconsidering that greasemonkey allows you to let random people on the internet change the behavior of your favorite websites how safe can it becan they steal my passwords look at my private data do things i did not want to dohow safe is greasemonkeythanks,['javascript'] +4409,is there a good numpy clone for jython i am a relatively new convert to python i have written some code to grabgraph data from various sources to automate some weekly reports and forecasts i have been intrigued by the jython concept and would like to port some python code that i have written to jython in order to do this quickly i need a numpy clone for jython or java is there anything like this out there,"['java', 'python']" +4412,what is the meaning of in c i saw this signature on the listview classpublic listviewlistviewitemcollection items get when i saw that whati searched dot dot colon colon dot and on google with no result,['c#'] +4420,dragndrop one or more mails from outlook to c wpf application i am working on a windows client written in wpf with c on net 35 sp1 where a requirement is that data from emails received by clients can be stored in the database right now the easiest way to handle this is to copy and paste the text subject contact information and time received manually using an arthritisinducing amount of ctrlcctrlvi thought that a simple way to handle this would be to allow the user to drag one or more emails from outlook they are all using outlook 2007 currently into the window allowing my app to extract the necessary information and send it to the backend system for storagehowever a few hours googling for information on this seem to indicate a shocking lack of information about this seemingly basic task i would think that something like this would be useful in a lot of different settings but all i have been able to find so far have been halfbacked nonsolutions does anyone have any advice on how to do this since i am just going to read the mails and not send anything out or do anything evil it would be nice with a solution that did not involve the hated security pop ups but anything beats not being able to do it at allbasically if i could get a list of all the mail items that were selected dragged and dropped from outlook i will be able to handle the rest myselfthanksrune,['c#'] +4422,javascript how do i determine if a link targets the same domain as the page it resides on for the purposes of tracking nonhtml documents via google analytics i need the mentioned algorithm it shouldnot hardcode the domainignore the protocol ie httphttpsnot worry about the presenceabsence of w any absolute links will prefix with w and all pages will be served via wthis is complicated by the fact that i need to access it via a function called from the ieonly attacheventupdate sorry i have worded this question really badly the real problem is getting this to work via an event since ie has its own madeup world of event handling take the followingfunction add eventobj if objaddeventlistener objaddeventlistenerclick track file true else if objattachevent objattacheventon click track filefunction track fileobj it seems as if the obj in track file is not the same across browsers how can i refer to what was clicked in ie,['javascript'] +4424,how can i change html attribute names with jquery i would like to change all the names of the attributes where classtestingcase throughout all my whole html documenteg changea classtestingcase href titlename of testing caseblabla classtestingcase href titlename of another testing caseblooato this a classtestingcase href newtitlenamename of testing caseblabla classtestingcase href newtitlenamename of another testing caseblooai was thinking of a find and replace but that seems a lot of code for something so easy is there a jquery function for this or a simple methodthank youice,"['jquery', 'html']" +4428,why override operator in the boost signals library they are overloading the operatoris this a convention in c for callbacks etci have seen this in code of a coworker who happens to be a big boost fan of all the boost goodness out there this has only led to confusion for meany insight as to the reason for this overload,['c++'] +4432,how to get url hash from server side i know on client side javascript you can use windowslocationhash but could not find anyway to access from the server side,['asp.net'] +4437,what is the difference between the keycode and keydata properties on the net winforms key event argument objects the two key event argument classes keyeventargs and previewkeydowneventargs each have two properties keycode and keydata which are both of the enumeration type keyswhat is the difference between these two properties do the values in them ever differ from each other if so when and why,['.net'] +4446,objectoriented or sequential i am refactoring a 500lines of c code in main for solving a differential equation i would like to encapsulate the big ideas of our solver into smaller functions ie solvepotential instead of 50 lines of numerics code should i code this sequentially with a bunch of functions taking very long parameters lists such asint mainint argc void argv interpolatexyz x interp y interp z interp potential newpotential compute fluxxyz flux compute energyxyz eng 10 other highlevel function calls with long parameter lists return 0or should i create a solvepotential class that would be called like soint mainint argc void argv potential solvepotentialnx ny nz norder potentialsolve return 0where i would define functions in solvepotential that uses member variables rather than long parameter lists such assolverpotentialsolve solvepotentialinterpolate solverpotentialcompute flux solverpotentialcompute energy 10 other highlevel function calls with no parameter lists just use private member variablesin either case i doubt i will reuse the code very much really i am just refactoring to help with code clarity down the roadmaybe this is like arguing is it 12 or one dozen but what do you think,['c++'] +4447,get real image width and height with javascript in safarichrome i am creating a jquery pluginhow do i get real image width and height with javascript in safarifollowing works with firefox 3 ie7 and opera 9var pic img need to remove these in of case imgelement has set width and heightpicremoveattrwidth picremoveattrheightvar pic real width picwidthvar pic real height picheightbut in webkit browsers like safari and google chrome values are 0doing this on server side is not an option,"['javascript', 'jquery']" +4451,private module methods in ruby i have a two part questionbestpracticei have an algorithm that performs some operation on a data structure using the public interfaceit is currently a module with numerous static methods all private except for the one public interface methodthere is one instance variable that needs to be shared among all the methodsthese are the options i can see which is the bestmodule with static module in ruby methods class with static methodsmixin module for inclusion into the data structurerefactor out the part of the algorithm that modifies that data structure very small and make that a mixin that calls the static methods of the algorithm moduletechnical partis there any way to make a private module methodmodule thing def selfpub puts public method end private def selfpriv puts private method endendthe private in there does not seem to have any effect i can still call thingpriv without issue,['ruby'] +4452,is there an easy way to determine the type of a file without knowing the files extension i have a table with a binary column which stores files of a number of different possible filetypes pdf bmp jpeg wav mp3 doc mpeg avi etc but no columns that store either the name or the type of the original file is there any easy way for me to process these rows and determine the type of each file stored in the binary column preferably it would be a utility that only reads the file headers so that i do not have to fully extract each file to determine its typeclarification i know that the approach here involves reading just the beginning of each file i am looking for a good resource aka links that can do this for me without too much fuss thanksalso just cnet on windows please i am not using linux and cannot use cygwin does not work on windows ce among other reasons,"['c#', '.net']" +4457,how do you use linq with sqlite would someone explain how to get linq working with sqlite,"['c#', '.net']" +4469,integer division rounding with negatives in c suppose a and b are both of type int and b is nonzero consider the result of performing ab in the following casesa and b are both nonnegativea and b are both negativeexactly one of them is negativein case 1 the result is rounded down to the nearest integer but what does the standard say about cases 2 and 3 an old draft i found floating on the internet indicates that it is implementation dependent yes even case 2 but the committee is leaning toward making it always round toward zero does anyone know what the latest standard says please answer only based on the standard not what makes sense or what particular compilers do,['c++'] +4477,which is better apply two conditions in nested if or using single with and nested if or single if with and operator which is better approachsingle if with and if txtpackagetext stringempty txtpackagetext abc nested if if txtpackagetext stringempty if txtpackagetext abc,['c#'] +4479,viewing contents of a jar file what would be the easiest way to view classes methods properties etc inside a jar filei am looking for something equivalent to the very useful lutz roeder net reflector for java,['java'] +4486,steps in the memory allocation process for java objects what happens in the memory when a class instantiates the following object public class someobject private string strsomeproperty public someobjectstring strsomeproperty thisstrsomeproperty strsomeproperty public void setsomepropertystring strsomeproperty thisstrsomeproperty strsomeproperty public string getsomeproperty return thisstrsomeproperty in class someclass1someobject so1 new someobjectsome property valuein class someclass2someobject so2 new someobjectanother property valuehow is memory allocated to the newly instantiated object and its properties,['java'] +4489,how do i test databaserelated code with nunit i want to write unit tests with nunit that hit the database i would like to have the database in a consistent state for each test i thought transactions would allow me to undo each test so i searched around and found several articles from 200405 on the topicthese seem to resolve around implementing a custom attribute for nunit which builds in the ability to rollback db operations after each test executesthat is great but does this functionality exists somewhere in nunit nativelyhas this technique been improved upon in the last 4 years is this still the best way to test databaserelated codeedit it is not that i want to test my dal specifically it is more that i want to test pieces of my code that interact with the database for these tests to be notouch and repeatable it would be awesome if i could reset the database after each onefurther i want to ease this into an existing project that has no testing place at the moment for that reason i cannot practically script up a database and data from scratch for each test,['c#'] +4493,how can i convert a hex string to a byte array possible duplicatehow do you convert byte array to hexadecimal string and vice versa in c can we convert a hex string to a byte array using a builtin function in c or do i have to make a custom method for this,['c#'] +4495,how do i set a field value in an c expression tree givenfieldinfo field some valid string field on type tparameterexpression targetexp expressionparametertypeoft targetparameterexpression valueexp expressionparametertypeofstring valuehow do i compile a lambda expression to set the field on the target parameter to value,['c#'] +4506,which tomcat 5 context file takes precedence tomcat documentation says the locations for context descriptors arecatalina homeconfenginenamehostnamecontextxmlcatalina homewebappswebappnamemetainfcontextxmlon my server i have at least 3 files floating around1 tomcatconfcontextxml2 tomcatcatalinalocalhostmyappxml3 tomcatwebappsmyappmetainfcontextxmlwhat is the order of precedence,['java'] +4508,how do i examine the contents of an stdvector in gdb using the icc compiler i want to examine the contents of a stdvector in gdb but i do not have access to m impl because i am using icc not gcc how do i do it let us say it is a stdvector for the sake of simplicitythere is a very nice answer here but this does not work if i use icc the error message is there is no member or method named m impl there appears to be a nice debug toolset here but it also relies on m impl,['c++'] +4510,can i invoke an instance method on a ruby module without including it backgroundi have a module which declares a number of instance methodsmodule usefulthings def get file def delete file def format textx endand i want to call some of these methods from within a class how you normally do this in ruby is like thisclass usefulworker include usefulthings def do work format textabc endendprobleminclude usefulthings brings in all of the methods from usefulthings in this case i only want format text and explicitly do not want get file and delete filei can see several possible solutions to this somehow invoke the method directly on the module without including it anywherei do not know howif this can be done hence this questionsomehow include usefulthings and only bring in some of it is methodsi also do not know howif this can be donecreate a proxy class include usefulthings in that then delegate format text to that proxy instancethis would work but anonymous proxy classes are a hack yucksplit up the module into 2 or more smaller modulesthis would also work and is probably the best solution i can think of but i would prefer to avoid it as i would end up with a proliferation of dozens and dozens of modules managing this would be burdensomewhy are there lots of unrelated functions in a single module it is applicationhelper from a rails app which our team has defacto decided on as the dumping ground for anything not specific enough to belong anywhere else mostly standalone utility methods that get used everywhere i could break it up into seperate helpers but there would be 30 of them all with 1 method each this seems unproductive,['ruby'] +4517,systembadimageformatexception could not load file or assembly from installutilexe i am trying to install a windows service using installutilexe and am getting the error messagesystembadimageformatexception could not load file or assembly xexe or one of its dependencies an attempt was made to load a program with an incorrect formatwhat givesedit not by op full message extracted from dup getting way more hits for googleabilitycwindowsmicrosoftnetframework64v4030319installutilexe cxexe microsoft r net framework installation utility version 40303191 copyright c microsoft corporation all rights reservedexception occurred while initializing the installation systembadimageformatexception could not load file or assembly filecxexe or one of its dependencies an attempt was made to load a program with an incorrect format,['.net'] +4529,can i convert a c string value to an escaped string literal in c can i convert a string value to a string literal the way i would see it in code i would like to replace tabs newlines etc with their escape sequencesif this codeconsolewritelinesomestringproduceshelloworldi want this codeconsolewritelinetoliteralsomestringto producethellorntworldrn,['c#'] +4533,how to access previousnext element while for looping is there a way to access a listor tuple or other iterables next or previous element while looping through with for loopl123for item in l if item2 get previouslitem,['python'] +4534,autotools how to set global compilation flag i have a project with several sources directories srca b cin each the makefileam contains am cxxflags fpic wall wextrahow can avoid repeating this in each source folder i tried to modifiy srcmakefileam and the configurein but without success i thought i could use ac prog cxx to set the compilation flags globally but cannot find much documentation on how to use those macro do you have any pointer to such a documentation thanks in advance,['c++'] +4542,http headers encodingdecoding in java a custom http header is being passed to a servlet application for authentication purposes the header value must be able to contain accents and other nonascii characters so must be in a certain encoding ideally utf8i am provided with this piece of java code by the developers who control the authentication environmentstring firstname requestgetheadermycustomheader string decodedfirstname new stringfirstnamegetbytesutf8but this code does not look right to me it presupposes the encoding of the header value when it seemed to me that there was a proper way of specifying an encoding for header values from mime i believehere is my question what is the right way tm of dealing with custom header values that need to support a utf8 encodingon the wire how the header looks like over the wirefrom the decoding point of view how to decode it using the java servlet api and can we assume that requestgetheader already properly does the decodinghere is an environment independent code sample to treat headers as utf8 in case you cannot change your servicestring valueasiso requestgetheadermycustomheader string valueasutf8 new stringfirstnamegetbytesiso88591utf8,['java'] +4544,how can i customize the text color of the back button in a uinavigationcontroller header view i am using a custom tintcolor on my uinavigationcontrollers navigation bar and because the color is so light i need to use dark colored text it is relatively easy to swap out the title view and the custom buttons i have added on the right hand side but i cannot seem to get a custom view to stick on the back button this is what i am trying right nowuilabel backlabel uilabel alloc initwithframecgrectzerobacklabel setfontuifont fontwithnameuifont fontnamesforfamilynamearial rounded mt bold objectatindex0 size240backlabel settextcoloruicolor blackcolorbacklabel setshadowcoloruicolor clearcolorbacklabel settextacategory thisplaynamebacklabel sizetofitbacklabel setbackgroundcoloruicolor clearcoloruibarbuttonitem temporarybarbuttonitemuibarbuttonitem alloc initwithcustomviewbacklabeltemporarybarbuttonitemcustomview backlabelbacklabel releaseselfnavigationitembackbarbuttonitem temporarybarbuttonitemtemporarybarbuttonitem releasethe custom view does not stick though and i do not see any obviously easy way to get at the actual text inside the default button and start changing its style,['iphone'] +4554,aspectoriented programming in java what is the best tool for java for aspectoriented programming the requirements for a tool are of course ide support expressiveness and proper documentation,['java'] +4557,what is the constant value of the underline font in java what is the constant value of the underline font in java fontbold bold fontfontitalic italic fontwhat is the underline font constant i try all the available constants but it did not work,['java'] +4561,variabletostring vs converttostringvariable let us say i have an integer that i need to convert to a string i might be thisplaying the value to the user by means of a textbox for exampleshould i prefer tostring or converttostring they both do the same thing do not theyint somevalue 4 you can do thistxtsomevaluetext somevaluetostring or thistxtsomevaluetext converttostringsomevalueassuming that there is no runtime difference between the two then my reasons come down to aesthetics and consistency recently i have been favouring converttostring as to me it says hey i want the value of this thing as a string however i know that this is not strictly true,"['c#', '.net']" +4565,how do i create a java string from the contents of a file i have been using the idiom below for some time now and it seems to be the most widespread at least on the sites i have visitedis there a betterdifferent way to read a file into a string in javaprivate string readfilestring file throws ioexception bufferedreader reader new bufferedreadernew filereader file string line null stringbuilder stringbuilder new stringbuilder string ls systemgetpropertylineseparator try whileline readerreadline null stringbuilderappendline stringbuilderappendls return stringbuildertostring finally readerclose,['java'] +4570,vertically align text within input field of fixedheight without thisplay table or padding the lineheight property usually takes care of vertical alignment but not with inputs is there a way to automatically center text without playing around with padding,['css'] +4581,dynamic logical expression parsingevaluation in php i have a need to evaluate userdefined logical expressions of arbitrary complexity on some php pages assuming that form fields are the primary variables it would need tosubstitutevaribles for formfields valueshandle comparison operatorsminimally and bysymbol name eg eq lt le ge gtrespectivelyhandle boolean operators not and or andpossibly xor by name symbol eg and respectivelyhandle literal values for stringsand numbersbe plaintext not xml eg firstname or lastname andbe reasonably performantnow in years gone by i have written recursive descent parsers that could build an expression tree and do this kind of thing but thats not a task i am relishing in php so i am hoping there are things out there that will at least get me some of the way theresuggestions,['php'] +4584,how can i make some items in a listbox bold in visual c express edition is it possible to make some but not all items in a listbox bold i cannot find any sort of option for this in the api,"['c#', '.net']" +4600,how do you do a sql style in statement in linq to entities entity framework if contains is not supported i am using linq to entities not linq to sql and i am having trouble creating an in style query here is my query at the momentvar items dbinventoryitem includekind includepropertyvalues includepropertyvalueskindproperty whereitm valueidscontainsitmidtolistinventoryitemwhen i do this however the following exception is thrownlinq to entities does not recognize the method boolean containsint64 method and this method cannot be translated into a store expressiondoes anyone have a workaround or another solution for this,['c#'] +4603,idictionary versus dictionary what is the value of using idictionary here,['c#'] +4605,c the definitive truth about rand random and arc4random there is a lot of conflicting information about this topic so let us try to agree on a definitive answerwhich one of these random number generator in c create better randomness rand random or arc4randomnote just to make the question clear this is not a question about true randomness it is only a clash between those 3as pointed out this question does not make much sense as this is not about c but about a specific implementation in my case cocoa more specifically the iphone sdk but my guess is they are the same as far as these functions go still there is some useful information here i concluded by implementing arc4random mostly because of its ease of use no seeding needed which is an important factor that no one pointed outi am closing the question and adding the cocoa tag for cocoa developers looking for information on rngs many thanks for those who contributed and sorry for the confusion,['c'] +4615,can you enable authorize for controller but thisable it for a single action i would like to use authorize for every action in my admin controller except the login action authorize roles administratorpublic class admincontroller controller what can i place here to thisable authorize public actionresult login return view,['c#'] +4621,rationale behind return 0 as default value in cc is there a reason why zero is used as a default function return value i noticed that several functions from the stdlib and almost everywhere else when not returning a proper number eg pow strcpy or an error negative numbers simply return zeroi just became curious after seeing several tests performed with negated logic very confusingwhy not return 1 or 0xff or any positive number for that matter,"['c++', 'c']" +4623,list selectors for objectivec object i have an object and i want to list all the selectors to which it responds it feels like this should be perfectly possible but i am having trouble finding the apis,['objective-c'] +4624,problem using nsurlrequest to post data to server i create an nsurlrequest to post my data in the iphone application to a server to proceed the php script my php script is look like thisphp name postname email postemail link mysql connectlocalhost fasfdasnfdsafafs or die unable to connect to database mysql select dbmuradsbi mydatabase or die unable to select database sqlstatement insert into dbname nameemail values nameemail newquery mysql querysqlstatement link echo thanks for your registerand my nsurlrequst is created like belownsstring myrequeststring namehello20worldemailohai2unsdata myrequestdata nsdata datawithbytes myrequeststring utf8string length myrequeststring lengthnsmutableurlrequest request nsmutableurlrequest alloc initwithurl nsurl urlwithstring request sethttpmethod postrequest sethttpbody myrequestdatansdata returndata nsurlconnection sendsynchronousrequest request returningresponse nil error nilhowever this site is unable to get the data from this application and save it to the database but i know it was connected succussfully because my application is able to get the response data from the server i do not know whether my variable name is declared in the wrong way or others issues how can i fix it,['iphone'] +4627,how to get username without domain in an aspx page i get the windows username with the function requestlogonuseridentityname this function returns a string in the format domainuseris there some function to only get the username without resorting to the indexof and substring like thispublic static string stripdomainstring username int pos usernameindexof return pos 1 usernamesubstringpos 1 username,['asp.net'] +4630,why is itemstatechanged on jcombobox is called twice when changed i am using a jcombobox with an itemlistener on it when the value is changed the itemstatechanged event is called twice the first call the itemevent is showing the original item selected on the second time it is showing the item that has been just selected by the user heres some tester codepublic tester jcombobox box new jcombobox boxadditemone boxadditemtwo boxadditemthree boxadditemfour boxadditemlistenernew itemlistener public void itemstatechangeditemevent e systemoutprintlnegetitem jframe frame new jframe framegetcontentpaneaddbox framepack framesetvisibletrueso when i changed the combo box once from one to three the console showsonethreeis there a way i can tell using the itemevent maybe that it is the second item ie the user selected item and if someone can explain why it gets called twice that would be nice toothanks,['java'] +4633,comparing infinities in java what does the following expression return in javamathmaxfloatpositive infinity doublepositive infinityi saw this question in a website and the answer is doublepositive infinity i am not sure about this answer as how can we compare 2 infinities can someone clarify this thanks,['java'] +4637,how to quickly parse a list of strings if i want to split a list of words separated by a delimiter character i can use abcfoobarsplitabc foo barbut how to easily and quickly do the same thing if i also want to handle quotedstrings which can contain the delimiter character in abca string with a commaanother oneout abc a string with a comma another onerelated question how can i parse a comma delimited string into a list caveat,['python'] +4639,localize images in aspnet a couple of years ago we had a graphic designer revamp our website his results looked great but he unfortunately introduced a new unsupported font by the web browser at first i was like what since most of our content is dynamic and there was no real way to premake all of the images there was also the issue of multiple languages since we knew spanish was on the horizonanyway i decided to create some classes to autogenerate images via gdi and programatically cache them as needed this solved most of our initial problems however now that our load has increased dramatically there has been a drain on our ui servernow to the question i am looking to replace most of the dynamic gdi images with a standard web browser font i am thinking of keeping some of the rendered gdi images and putting them in a resx file but plan to replace most of them with tahoma or arial fonts via asplabels which have you found to be a better localized image solution embedding images into the resxonly adding the image url into the resxsome other solutionmy main concern is to limit the processing on the ui server if that is the case would adding the image url to the resx be a better solution compared to actually embedding the image into the resx,['asp.net'] +4648,how to fix referenced assembly does not have a strong name error i have added a weakly named assembly to my visual studio 2005 project which is strongly named i am now getting the errorreferenced assembly x does not have a strong namedo i need to sign this thirdparty assembly,['c#'] +4651,using unicode in c source code what is the standard encoding of c source code does the c standard even say something about this can i write c source in unicodefor example can i use nonascii characters such as chinese characters in comments if so is full unicode allowed or just a subset of unicode eg that 16bit first page or whatever it is calledfurthermore can i use unicode for strings for examplewstring strlstrange chars aa a a aa,['c++'] +4654,when should static cast dynamic cast const cast and reinterpret cast be used what are the proper uses ofstatic castdynamic castconst castreinterpret castcstyle cast typevaluefunctionstyle cast typevaluehow does one decide which to use in which specific cases,['c++'] +4659,is there a real performance difference between int and varchar primary keys is there a measurable performance difference between using int vs varchar as a primary key in mysql i would like to use varchar as the primary key for reference lists think us states country codes and a coworker would not budge on the int auto increment as a primary key for all tables my argument as detailed here is that the performance difference between int and varchar is negligible since every int foreign key reference will require a join to make sense of the reference a varchar key will directly present the informationso does anyone have experience with this particular usecase and the performance concerns associated with it,['mysql'] +4660,how do you organize c code in to files in c the questions of what types to create what members they should have and what namespaces should hold them are questions of oo design they are not the questions i am interested in hereinstead i want to ask how you store these in thisk artifacts here are some example rulesput all of an assemblys types in a single source file one friend who did this said files are an archiac code organization tool today i use classview and collapse to definitions to browse my codeput all your code in one assembly makes deployment versioning simplerdirectory structure reflects namespace structure each namespace gets its own assemblyeach type goes in its own assembly listed as an extreme exampleeach type gets its own source file each member gets its own file each type gets its own directory listed as an extreme example,['c#'] +4661,is it possible to serialize a linq object i would like to serialize some linq generated objects and store them in a table as a binary field never you mind why i would like to be able to write some code that looks something like thisserialtestdatacontext db new serialtestdatacontextrelation table row dbrelation tablesfirstmemorystream memstream new memorystreambinaryformatter bin new binaryformatterbinserializememstream rowconsolewritelineserilized successfullytesttable tt new testtablettdata new systemdatalinqbinarymemstreamtoarraydbtesttablesinsertonsubmitdbsubmitchangesconsolewritelineinserted successfullycurrently that fails even though i have marked the generated classes as serializable because one of the linq inherited classes is not is it even possible to do this,['c#'] +4666,atomically changing a systemthreadingtimer let us say i have an existing systemthreadingtimer instance and i would like to call change on it to push it is firing time backvar timer new timerdelaycallback null 10 timeoutinfinite sometime later but before delaycallback has executedtimerchange20 timeoutinfinitei am using this timer to perform an idle callback after a period of no activity idle and no activity are applicationdefined conditions in this casethe specifics are not terribly important every time i perform an action i want to reset the timer so that it is always set to fire 10 seconds after thathowever there is an inherent race condition because when i call change i cannot tell if the timer has already fired based on its old settings i can of course tell if my callback has happened but i cannot tell if the clrs internal timer thread has queued my callback to the threadpool and its execution is imminentnow i know i can call thispose on the timer instance and recreate it each time i need to push it back but this seems less efficient than just changing the existing timer of course it may not bei will run some microbenchmarks in a bit and let you all knowalternatively i can always keep track of the expected firing time via datetimenowaddseconds10 and if the original timer fires ignore it by checking datetimenow in the callback i have a nagging concern that this may not be 100 reliable on account of the timer using timespan and my check using datetimethis may not be an issue but i am not completely comfortable with it for some reasonmy questions areis there a good way for me to call timerchange and be able to know whether i managed to change it before the callback was queued to the threadpool i do not think so but it does not hurt to askhas anyone else implemented what i term a pushback timer like this if so i would love to hear how you tackled the problemthis question is somewhat hypothetical in nature since i already have a couple of working solutions based on thispose and based on datetimenowi am mainly interested in hearing performancerelated suggestions as i will be pushing back the timer very frequentlythanks,"['c#', '.net']" +4667,simple linq to sql has no supported translation to sql i have this in my blogrepositorypublic iqueryablesubnusmvcdatamodelpost getposts var query from p in dbposts let categories getcategoriesbypostidppostid let comments getcommentsbypostidppostid select new subnusmvcdatamodelpost categories new lazylistcategorycategories comments new lazylistcommentcomments postid ppostid slug pslug title ptitle createdby pcreatedby createdon pcreatedon body pbody return query and public iqueryablesubnusmvcdatamodelcomment getcommentsbypostidint postid var query from c in dbcomments where cpostid postid select new subnusmvcdatamodelcomment body cbody email cemail date ccreatedon website cwebsite name cname return query private iqueryablesubnusmvcdatamodelcategory getcategoriesbypostidint postid var query from c in dbcategories join pcm in dbpost category maps on ccategoryid equals pcmcategoryid where pcmpostid postid select new subnusmvcdatamodelcategory categoryid ccategoryid name cname return query and when i aplly this filter namespace subnusmvcdata public static class blogfilters public static iqueryablepost wherepublicisthis iqueryablepost qrybool state return from p in qry where pispublic state select p all this is in the same namespace if that help namespace subnusmvcdatawhen i try to do this public class blogservice iblogservice public ilistpost getpublicposts return repositorygetpostswherepublicistruetolist that is in the namespace subnusmvcserviceit throws the error method systemlinqiqueryable1subnusmvcdatamodelcomment getcommentsbypostidint32 has no supported translation to sql,['.net'] +4671,vbnet extension methods when i apply the tag above my methods i get the error type systemruntimecompilerservicesextension is not definedhere is my samplesystemruntimecompilerservicesextension public sub testend subwhere am i going wrongedit straight from the msdn article here the same errorimports systemruntimecompilerservicesmodule stringextensions public sub printbyval astring as string consolewritelineastring end subend modulei am using visual studio 2008 and 35 framework in my projectsolution the project was on 20 framework changed to 35 and it works,['.net'] +4675,build tar file from directory in php without execpassthru so i have a client whos current host does not allow me to use tar via execpassthruect and i need to backup the site periodicly and programmaticly so is there a solutionthis is a linux server,['php'] +4677,parallelization what causes java threads to block other than synchronization io short version is in the titlelong versioni am working on a program for scientific optimization using java the workload of the program can be divided into parallel and serial phases parallel phases meaning that highly parallelizable work is being performed to speed up the program it runs for hoursdays i create a number of threads equal to the number of cpu cores on the machine i am using typically 4 or 8 and divide the work between them i then start these threads and join them before proceeding to a serial phaseso far so good whats bothering me is that the cpu utilization and speedup of the parallel phases is nowhere near the theoretical maximum eg if i have 4 cores i expect to see somewhere between 350400 utilization as reported by top but instead it bounces around between 180 and about 310 using only a single thread i get 100 cpu utilizationthe only reasons i know of for threads not to run at full speed are blocking due to io blocking due to synchronizationno io whatsoever is going on in my parallel threads nor any synchronization the only data structures shared by the threads are readonly and are either basic types or nonconcurrent collections so i am looking for other explanations one possibility would be that several threads are repeatedly blocking for garbage collection but that would only seem to make sense in a situation with memory pressure and i am allocating well above the required maximum heap space any suggestions would be appreciatedupdate just in case anyone is curious after some more investigation i tweaked the code for general performance and am seeing better utilization even though nothing i changed has to do with synchronization however some of the changes should have resulted in fewer new heap allocations in particular i got rid of some use of iterators and termporary boxed numbers the cern colt library for highperformance java computing was useful here it provides collections like intarraylist doublearraylist etc for basic types so i think garbage collection was probably the culprit,['java'] +4679,how to design a simple c object factory in my application there are 1020 classes that are instantiated once heres an exampleclass someothermanagerclass somemanagerclass public somemanagerclasomeothermanager virtual void somemethod1 virtual void somemethod2instances of the classes are contained in one objectclass themanager public virtual somemanagerclass somemanagerclass const virtual someothermanager someothermanager const more objects up to 1020 currently themanager uses the new operator in order to create objects my intention is to be able to replace using plugins the somemanagerclass or any other class implementation with another one in order to replace the implementation 2 steps are neededdefine a class derivedsomemanagerclass which inherits somemanagerclass plugincreate the new class derivedsomemanagerclass instead of the default somemanagerclass applicationi guess i need some kind of object factory but it should be fairly simple since there is always only one type to create the default implementation or the user implementationany idea about how to design a simple factory like i just described consider the fact that there might be more classes in the future so it should be easy to extend i do not care if it happens more than onceedit please note that there are more than two objects that are contained in themanager,['c++'] +4681,best practice for designing user roles and permission system i need to add user roles and permission system into my web application built using phpmysql i want to have this functionality one root user can create subroots groups rules and normal users all privileges subroots can create only rules permissions and users for hisher own group no groupsa user can access either content created by him or his group based on the permission assigned to him by group rooti need the system to be flexible enough so that new roles and permissions are assigned to contenti have a users table storing group key along with other information currently i am using two feilds in each content table ie createdby and createdbygroup and using that as the point whether a certain user has permissions but its not flexible enough because for every new content i have to go throug all data updates and permission updates please help me by thiscussing your best practices for schema design,['mysql'] +4683,any easy rest tutorials for java every tutorial or explanation of rest just goes too complicated too quickly the learning curve rises so fast after the initial explanation of crud and the supposed simplicity over soap why cannot people write decent tutorials anymorei am looking at restlet and its not the best there are things missing in the tutorial and the languagegrammar is a bit confusing and unclear it has took me hours to untangle their first steps tutorial with the help of another java programmerrestlet tutorial commentsoverall i am not sure exactly who the tutorial was aimed at because there is a fair degree of assumed knowledge all round so coming into rest and restlet framework cold leaves you with a lot of catchup work to do and rereading paragraphs over and over againwe had difficulty working out that the jars had to be in copied into the correct lib folder problems with webxml creating a http status 500 error the server encountered an internal error that prevented it from fulfilling this request the tutorial says create a new servlet web application as usual add a comfirststepsservlet package and put the resource and application classes inthis means that your fully qualified name for your class firststepsapplication is comfirststepsservletfirststepsapplication so we had to alter webxml to refer to the correct class egoriginalparamvalue firststepsservletfirststepsapplicationparamvalueshould beparamvalue comfirststepsservletfirststepsapplicationparamvalueconclusioni was under the impression that the concepts of rest were supposed to be much simpler than soap but it seems just as bad if not more complicated do not get it at all grany good links much appreciated,['java'] +4690,mysql how to show processlist only with current users processes is there a way in mysql 5 to show only the current users processesqueriesthe user has the process privilege therefore show processlist thisplays running processes of all users according to the documentation show processlist does not allow any kind of where syntax nor did i manage to make it into a subqueryof course i could simply send the query eg in a php script and go through the results in a loop thiscarding everything that is not mine but it seems rather inefficient changing the user privileges is not feasibleare there any other ways thanks in advance,['mysql'] +4695,opening a folder in explorer and selecting a file i am trying to open a folder in explorer with a file selectedthe following code produces a file not found exception systemdiagnosticsprocestart explorerexe select listview1selecteditems0subitems1text listview1selecteditems0texthow can i get this command to execute in c,['c#'] +4698,are goto and destructors compatible this code leads to undefined behaviorvoid some func goto undefined t x t undefined the constructor is not called but what about this code will the destructor of x be called i think it will be but i want to be sure void some func t x t goto out out,['c++'] +4701,c how to replace microsofts smart quotes with straight quotation marks my post below asked what the curly quotation marks were and why my app wouldnt work with them my question now is how can i replace them when my program comes across them how can i do this in c are they special characterscurlyquotationmarksvssquarequotationmarkswhatgivesthanks,['c#'] +4702,in c what is the recommended way of passing data between 2 threads i have my main gui thread and a second thread running inside it is own applicationcontext to keep it alive even when there is no work to be done i want to call a method on my 2nd thread from my gui thread but if i just call threadmethod it seems to be running on my main gui thread and causes my gui to become unresponsive what is the best way to call methods on different threadsupdatewhat i am really looking to do here is communicate between 2 threads not communicate with a gui the gui just happens to be one of the threads that will need to communicate with my 2nd threadupdate 2ok i must really be missing something i created an event and a delegate and had my worker thread subscribe to the event but when i call invokemyevent from my gui thread the work that the worker thread does ends up being on the gui thread and hangs the gui thread until it is done processing is what i am trying to do even possible without polling on a static object,['c#'] +4703,linq with foxpro is there a reasonable way to access foxpro databases using linq,"['c#', '.net']" +4711,porting vbnet winforms application to c are there any good resources for porting a vbnet winforms application to c i am sure there are is software that just translates the code but i am looking to refactor the code at the same time keeping it in its current form is problematic since it uses some of the bad design practices that vbnet allows and would further complicate future maintanence has anyone here gone through that process and how did you go about doing it did you use a translaterefactor approach did you just use the end product to recreate functionality without looking at the current codebase for most of it what would you collectively recommendupdateas i was telling grauenwolf keeping it in its current language presents the following issuesnot being able to readily add features vbnet is not a language i am rock solid in i do appreciate the irony of learning the language to port it over but future maintenance will need to account for someone who does not know vbnetthe rest of the application has been ported to c a long time ago in fact all features that wed like to add depend on decoupling the app right now it is very tightly coupled my choices are to either refactor it in a language i am not too familiar with or to refactor it in a language i understand to anyone who voted the question down i am not really sure why you did the concern is not whether i should leave it in vbnet the concern is what is the future cost of not porting it over now if i am going to spare great expense in fixing it why not go the extra step and make it maintainable for a future programmerauthors note i had not looked at this question in ages there was a recent response so i moved my answer into the question and deleted the answer since it was not really an answer,"['c#', '.net']" +4713,using boostshared ptr in a librarys public interface we have a c library that we provide to several different clients recently we made the switch from using raw pointers in the public interface to using boostsharedptr instead this has provided an enormous benefit as you might guess in that now the clients no longer have to worry about who needs to delete what and when when we made the switch i believed it was the right thing to do but it bothered me that we had to include something from a thirdparty library in our public interface generally you avoid that kind of thing if you can i rationalized it that boost was practically part of the c language now and our use case requires that both the client code and the library hold pointers to the objects however recently one of our clients has asked us if we could switch to using a neutral smart pointer class in the interface because our library is essentially forcing them to a particular version of boost a point which i certainly understand and appreciate so now i am wondering what the best course of action might be i have thought about it a little bit and wondered about creating a simple smart pointer class that simply held a real boost smart pointer but then the clients would probably immediately stuff one of those into their flavor of boostsharedptr and then wed be three shared pointers deep which might be a problem or it might not anyway i would love to hear some opinions from the community about the best way to solve this problemedit i originally said transfer of ownership but i should have specified that code on both sides of the api boundary need to hold a pointer to the object,['c++'] +4718,is net mvc must learn technology is it here to stay or is this something just pushed out quickly as a me too offering in response to the rails communityis it necessary to go through the learning curve and will the framework move to only working this way without the page behind modelif so wheres the best place to pick up mvc essentials for net,['ruby-on-rails'] +4719,how do you detect that monkey patching has occurred in ruby how do you check that monkey patching has been done to a specific class in ruby if that is possible is it also possible to get the previous implementations of the attribute that is been patched,['ruby'] +4721,collision detection between two images in java i have two characters thisplayed in a game i am writing the player and the enemy defined as suchpublic void playergraphics g gdrawimageplimg x y thispublic void enemygraphics g gdrawimageenemy 200 200 thisthen called withplayergenemygi am able to move player around with the keyboard but i am at a loss when trying to detect a collision between the two a lot of people have said to use rectangles but being a beginner i cannot see how i would link this into my existing code can anyone offer some advice for me,['java'] +4726,thiscarding the output of a function that needs an output iterator suppose therea s a template function in c that does some useful work but also outputs a sequence of values via an output iterator now suppose that that sequence of values sometimes is interesting but at others is not useful is there a readytouse iterator class in the stl that can be instantiated and passed to the function and will ignore any values the function tries to assign to the output iterator to put in another way send all data to devnull,['c++'] +4735,explicit script end tag always converted to selfclosing i am using xslt to transform xml to an aspx file in the xslt i have a script tag to include a jqueryjs file to get it to work with ie the script tag must have an explicit closing tag for some reason this does not work with xslt belowxml version10 encodingutf8xslstylesheet version10 xmlns xmlnsxsl xmlnsmsxslurnschemasmicrosoftcomxslt excluderesultprefixesmsxsl xmlnsaspremove xsloutput methodhtml xsltemplate match html xmlns head titletesttitle script typetextjavascript srcjquery126jsscriptbut if i change the script tag as shown below it works script typetextjavascript srcjquery126js cdata scripti thought that the xsloutput methodhtml would do the trick but it does not seem to workjonas,['javascript'] +4741,how to write your own net obfuscator i am very curious as to how people write their own obfuscatorhow hard would it be to simply do the followingrename all public methods with guid type nameswhere would i start how would i go about reading the net dll assemby pulling the public methods out and renaming them,['.net'] +4744,javascript marquee to replace tags i am hopeless at javascript this is what i havescript typetextjavascript function beginrefresh set the id of the target object var marquee documentgetelementbyidmarquee text ifmarqueescroleft marqueescrollwidth parseintmarqueestylewidth marqueescroleft 0 marqueescroleft 1 set the delay ms bigger delay slower movement settimeoutbeginrefresh 10 scriptit scrolls to the left but i need it to repeat relatively seamlessly at the moment it just jumps back to the beginning it might not be possible the way i have done it if not anyone have a better method,"['javascript', 'html']" +4745,is it worth it to code different functionality for users with javascript thisabled i am currently building a project and i would like to make use of some simple javascript i know some people have it thisabled to prevent xss and other things should ia use the simple javascript those users with it thisabled are missing outb do not use the simple javascript users with it enabled have to click a little morec code both javascriptenabled and javascriptthisabled functionalityi am not really sure as the web is always changing what do you recommend,['javascript'] +4748,create an array of the last 30 days using php i am trying to create an array starting with today and going back the last 30 days with php and i am having trouble i can estimate but i donat know a good way of doing it and taking into account the number of days in the previous month etc does anyone have a good solution i canat get close but i need to make sure it is 100 accurate,['php'] +4751,avoiding a javascript race condition heres the scenariomy users are presented a grid basically a stripped down version of a spreadsheet there are textboxes in each row in the grid when they change a value in a textbox i am performing validation on their input updating the collection that is driving the grid and redrawing the subtotals on the page this is all handled by the onchange event of each textboxwhen they click the save button i am using the buttons onclick event to perform some final validation on the amounts and then send their entire input to a web service saving itat least that is what happens if they tab through the form to the submit buttonthe problem is if they enter a value then immediately click the save button saveform starts executing before userinputchanged completes a race condition my code does not use settimeout but i am using it to simulate the sluggish userinputchanged validation code snip script var amount null var currentcontrol null function userinputchangedcontrol currentcontrol control use settimeout to simulate slow validation code production code does not use settimeout settimeoutvalidateamount 100 function saveform call web service to save value documentgetelementbyidsavedamountinnerhtml amount function validateamount various validationey functions here amount currentcontrolvalue save value to collection documentgetelementbyidsubtotalinnerhtml amount update subtotals script snip amount input typetext iduserinputvalue onchangeuserinputchangedthis br subtotal span idsubtotalspan br input typebutton onclicksaveform valuesave br br saved amount span idsavedamountspan snip i do not think i can speed up the validation code it is pretty lightweight but apparently slow enough that code tries to call the web service before the validation is completeon my machine 95ms is the magic number between whether the validation code executes before the save code begins this may be higher or lower depending on the users computer speed does anyone have any ideas how to handle this condition a coworker suggested using a semaphore while the validation code is running and a busy loop in the save code to wait until the semaphore unlocks but i would like to avoid using any sort of busy loop in my code,['javascript'] +4752,suggest a good php wiki engine i am looking for a small wiki engine that is easy to embed into an existing php application or perhaps a set of libraries to handle all the typical wiki functionscurrently i am using erfurtwiki but it is starting to show its age it has not been updated since 2005 and several of the pages on sourceforge appear to have been hackedi will be including it with a gplv2 application so a gpl compatible license is importanteditto update mostly i am just looking for text formattingparser functionality i want to deal with the storage security rev history etc on my own,['php'] +4758,how do i find the type of the object instance of the caller of the current function currently i have the function createlog for creating a a log4net log with name after the constructing instances class typically used as inclass messagereceiver protected ilog log utilcreatelog if we remove lots of error handling the implementation boils down toedit please read the longer version of createlog further on in this postpublic ilog createlog systemdiagnosticsstackframe stackframe new systemdiagnosticsstackframe1 systemreflectionmethodbase method stackframegetmethod return createlogwithnamemethoddeclaringtypefullnameproblem is that if we inheirit messagereceiver into sub classes the log will still take its name from messagereceiver since this is the declaring class of the method constructor which calls createlogclass imreceiver messagereceiver class emailreceiver messagereceiver instances of both these classes would get logs with name messagereceiver while i would like them to be given names imreceiver and emailreceiveri know this can easily be done and is done by passing a reference to the object in creation when calling createlog since the gettype method on object does what i wantthere are some minor reasons to prefer not adding the parameter and personally i feel thisturbed by not finding a solution with no extra argumentis there anyone who can show me how to implement a zero argument createlog that gets the name from the subclass and not the declaring classeditthe createlog function does more than mentioned above the reason for having one log per instance is to be able to differ between different instances in the logfile this is enforced by the createlogcreatelogwithname pairexpanding on the functionality of createlog to motivate its existencepublic ilog createlog systemdiagnosticsstackframe stackframe new systemdiagnosticsstackframe1 systemreflectionmethodbase method stackframegetmethod type type methoddeclaringtype if methodisstatic return createlogwithnametypefullname else return createlogwithnametypefullname getandinstancecountfortype also i prefer writing ilog log utilcreatelog rather than copying in some long cryptic line from an other file whenever i write a new class i am aware that the reflection used in utilcreatelog is not guaranteed to work though is systemreflectionmethodbasegetcurrentmethod guaranteed to work,"['c#', '.net']" +4762,what is the managed c equivalent to the c using statement how would one code the following c code in managed cvoid foo using sqlconnection con new sqlconnectionconnectionstringgoeshere do stuff clarificatonfor managed objects,['.net'] +4765,how do i render a partial of a different format in rails i am trying to generate a json response that includes some html thus i have appviewsfoobarjsonerb somekey some value somehtml h renderpartial foobaz i want it to render appviewsfoo bazhtmlerb but it will only render appviewsfoo bazjsonerb passing format html does not help,['ruby-on-rails'] +4770,yet another divs vs tables issue forms metanote i was browsing the question page getting really tired of divs vs tables when to use tables vs divs are divs better than tables tables versus css and all the questions that ask the same thing omg people but i would like to see all the ways people tackle the translation of the canonical example of why you should give up and use tablestable tr td name td td input td tr tr td social security number td td input td trtable question how to best semantically simply robustly fluidly portably implement the above without tables for starters i guess a naive implementation uses a fixed column width for the first column but that can have iffy results for dynamically generated content including strengthsweaknesses of your approach in the answer would be niceps another one i wonder about a lot is vertical centering but the hack for that is covered pretty well at jakpsatwebczedit scunlife brings up a good example of why i did not think out the problem that carefully tables can align multiple columns simultaneously the question still stands i would like to see different css techniques used for alignmentlayout although solutions that can handle his more involved example definitely are preferred,"['html', 'css']" +4776,does javascript fire an event for unhandleduncaught exceptions i am looking to log unhandled javascript exceptions is there an event that fires when an exception is not caught i am looking to catch the exceptions before they cause javascript errors in the browser but i would rather not run my entire application inside of a trycatch any help would be appreciated thanksupdate tvanfosson pointed out onerror as a possibility it is not part of a spec and is only available in ie or gecko based browsersfor more information pgpa386lpgpa386dqsafarionerrorjavascriptsourcewebotsgqagbpunjgsigibctoqs0ah eazsbwlga9v5flyoppa387m1onerror support table mozillas documentation webkit bug report bugcgiid8519,['javascript'] +4779,looking for an example of using lucenenet with aspnet how do you implement the search capabilities of lucenenet in aspnet if possible please include links or example code,['asp.net'] +4783,mysql how to use index in where x in i am using this query to get all employees of clients with name starting with lowercase aselect from employees where client id in select id from clients where name like acolumn employeesclient id is an int with index client id index id the subquery should imho return a list of ids which is then used in the where clausewhen i explain the query the primary query uses no indexes typeall but when i explain a list taken from the subquery eg select where client id in 121184501 the explain switches to typerange and this query gets faster by 50how can i make the query use the index for the data returned by subquery or is there a more efficient way of retrieving this data retrieving the idlist to application server joining it and sending a second query is even more expensive herethanks in advance,['mysql'] +4792,create empty c event handlers automatically it is not possible to fire an event in c that has no handlers attached to it so before each call it is necessary to check if the event is nullif myevent null myevent param1 param2 i would like to keep my code as clean as possible and get rid of those null checks i do not think it will affect performance very much at least not in my casemyevent param1 param2 right now i solve this by adding an empty inline handler to each event manually this is error prone since i need to remember to do that etcvoid initialize myevent new myevent p1p2 is there a way to generate empty handlers for all events of a given class automatically using reflection and some clr magic,['c#'] +4808,how to use libapt or libept in debianlike system to list packages and get their infos somebody used libapt or libept to list packages and get informations about package in a debianlike systemlibapt is not welldocumented at all and i have found few examples and tutorials about libept can someone explain me best methods toget a list of every packages in the aptsystemget informations about single packages like name version dependences description etcget list of files installed by a single packagework directly with apt internal files is quite simple but i want to use a library to respect apt specifications,['c++'] +4810,on windows when should you use the filename prefix i came across a c library for opening files given a unicode filename before opening the file it first converts the filename to a path by prepending is there any reason to do this other than to increase the maximum number of characters allowed in the path per this msdn article it looks like these paths require the unicode versions of the windows api and standard library,['c++'] +4812,how can i determine the element type of a matched element in jquery i am matching aspnet generated elements by id name but i have some elements which may render as text boxes or labels depending on the page context i need to figure out whether the match is to a textbox or label in order to know whether to get the contents by val or by htmlid endofidtomatch eachfunction determine whether this is a textbox or label do stuffi found a solution that does not work it just returns undefinedid endofidtomatch eachfunction alertthistagnamewhat am i missing,"['asp.net', 'javascript', 'jquery', 'html']" +4813,implementing and enforcing coding standards my team of which i am the newest and most junior member has increased in size from 3 to 9 developers in just about 1 year our primary product has increased in complexity and we are about to undertake a year long portrewrite to silverlight in the past there has been no specific stylestandard enforcedi suggested to my boss that now would be a good time to implement such standards i passed on idesigns document to him and he likes the idea he has 2 concernsthis is a big document to absorb my thought here is to develop a slimmed down cheatsheet for the most common items that were likely to run into with the understanding that the idesign standard is the master and anything not covered in the slimmed down version should be looked up in the master documentwhat is the best way to enforce this it is not a question of trying to dictate it is a matter of trying to get folks used to developing to a particular standard there are at least 2 folks on the team that have been developing to the current nonstandard for several years now in order to address this concern i would like to see if there is a tool that can be configured to enforce these standards or at a minimum warn of violations of the standard at either compiletime or designtime i found microsoftd stylecop but from what i have been able to determine it is not configurable and is set up to follow microsofts standard which does not completely mesh with idesigns any input on tools or the approach i am looking at would be appreciated,['c#'] +4831,create java console inside a gui panel how can i create an instance of the java console inside of a gui panel,['java'] +4835,what happened to the python bindings for cgal i found the computational geometry algorithms library in my search for an algorithm to decompose a concave polygon into the minimum number of convex components links off the site and numerous google results indicate there are python bindings for it which would be really handy but all the links are dead what happened to it where can i get it now,['python'] +4846,how to determine total size of aspnet cache i am using the aspnet cache in a web project and i am writing a status page for it which shows the items in the cache and as many statistics about the cache as i can find is there any way that i can get the total size in bytes of the cached data the size of each item would be even better i want to thisplay this on a web page so i do not think i can use a performance counter,"['c#', 'asp.net']" +4850,why is january month 0 in java calendar in javautilcalendar january is defined as month 0 not month 1 is there any specific reason to that i have seen many people getting confused about that,['java'] +4853,how to get which page threw an exception to application error in aspx i have a general exception handler application error in my globalasax where i am trying to isolate all the uncaught exceptions on all my many pages i do not want to use page error to catch exception because it is inefficient to call that on so many pages so where in the exception can i find what page actually caused the exception,"['c#', 'asp.net']" +4874,should enums have uninitialized values we were having a debate if enums should have uninitialized values for example we have public enum timeofdaytype morning afternoon eveningor public enum timeofdaytype none morning afternoon eveningi think that there should not be any none but then you have to default to some valid value on initialization but others thought there should be some indication of uniitized state by having another enum that is none or notsetthoughts,['c#'] +4879,read file object as string in python i am using urllib2 to read in a page i need to do a quick regex on the source and pull out a few variables but urllib2 presents as a file object rather than a stringi am new to python so i am struggling to see how i use a file object to do this is there a quick way to convert this into a string,['python'] +4880,in ruby can you perform string interpolation on data read from a file in ruby you can reference variables inside strings and they are interpolated at runtime for example if you declare a variable foo equals ted and you declare a string hello foo it interpolates to hello ted i have not been able to figure out how to perform the magic interpolation on data read from a file in pseudo code it might look something like thisinterpolated string filenewmyfiletxtreadinterpolatebut that last interpolate method does not exist,['ruby'] +4882,what are unit tests and why should i care okay i develop web applications in php and javascript and a lot of times here on stack overflow i have seen the word unit test passing by but nowhere on the website have i been able to found a satisfactory answer to what exactly a unit test is so what are unit tests and should i as a php and javascript programmer care or are they only for real programming languages,"['php', 'javascript']" +4885,how to work with pointer to pointer to structure in c i want to change member of structure under double pointer do you know howexample codetypedef struct int member ttypevoid changememberttype foo i dont know how to do it maybe foomember 1,['c'] +4888,dealing with timezones in php some issues with timezones in php have been in the back of my mind for a while now and i was wondering if there are better ways to handle it than what i am currently doingall of the issues revolve around reformating database stored dateswhen dealing with a site that has to support multiple timezones for users to normalize the timezone offest of stored timestamps i always store it with the server timezone using the current timestamp attribute or the now function this way i do not have to consider what timezone was set for php when the timestamp was entered since php time functions are timezone aware for each user according to his preference i set the timezone somewhere in my bootstrap file usingdate default timezone settimezonewhen i am looking to format dates with the php date function some form of conversion has to take place since mysql currently stores timestamp in the format ymd his with no regard to timezone you could simply rundate dateformatstrtotimedbtimestampthe problem with this is that date and strtotime are both timezone aware functions meaning that if the php timezone is set differently from the server timezone the timezone offset will apply twice instead of once as we would liketo deal with this i usually retrieve mysql timestamps using the unix timestamp function which is not timezone aware allowing my to apply date directly on it thereby applying the timezone offset only oncei do not really like this hack as i can no longer retrieve those columns as i normally would or use to fetch all columns sometimes it simplifies queries greatly also sometimes it is simply not an option to use unix timestamp especially when using with opensource packages without much abstraction for query compositionanother issue is when storing the timestamp when usage of current timestamp or now is not an option storing a php generated timestamp will store it with the timezone offset which i would like to avoidi am probably missing something really basic here but so far i have not been able to come up with a generic solution to handle those issues so i am forced to treat them casebycase your thoughts are very welcome,['php'] +4889,djangocontribflatpages without models i have some flatpages with empty content field and their content inside the template given with template name fieldwhy i am using djangocontribflatpagesit allows me to serve mostly static pages with minimal url configurationi do not have to write views for each of themwhy i do not need the model flatpagei leave the content empty and just supply a template path therefore i can take advantage of having the source in a filei can edit the source directly from the file system without the help of a server such as admini can take advantage of syntax highlightning and other editor featureswith the model i have to maintain fixtures for flatpagesso the data for the same entity is in two seperate placesif i move the content inside the fixture it will be more difficult to editeven if fixture maintenance was a nonissue i would still need to dump and load these fixtures again and again during developmentwhat i am looking forbasically getting rid of flatpage model while maintaining contribflatpages functionality i do not have a clear idea how this should be solved if there is a clean way of modifying like add to class flatpages to get the information somewhere other than the database i would prefer that maybe the metadata can be inserted to the templates and then a special manager that reads this data would replace the default manager of flatpagesif i do not prefer manual editing over admin functionality for flatpages how can take the database out of the equation,['python'] +4890,two html tables side by side centered on the page i have two tables on a page that i want to thisplay side by side and then center them within the page actually within another div but this is the simplest i could come up withstyle outer textalign center inner textalign left margin 0 auto t float left table border 1px solid black clearit clear left stylediv idouter ptwo tables side by side centered together within the pagep div idinner div classt table trthaththbthtr trtd1tdtd2tdtr trtd4tdtd9tdtr trtd16tdtd25tdtr table div div classt table trthaththbththcthtr trtd1tdtd2tdtd2tdtr trtd3tdtd5tdtd15tdtr trtd8tdtd13tdtd104tdtr table div div div idclearitall donedivdivi understand that it is something to do with the fact that the tables are floated but i am at a loss as to understand what i am missing there are many web pages that describe something like the technique i show here but in any event it does not work the tables cling stubbornly to the left hand margin,['css'] +4892,how should i choose an authentication library for codeigniter i see there are a few which ones are maintained and easy to use what are their pros and cons,['php'] +4894,should i delete or thisable a row in a relational database in a brand new program where space is not really that big a deal is it better to delete a row or to thisable a row by let us say a boolean thisabled and have the program just ignore itfor example if i wanted to remove a user from a program,"['mysql', 'sql']" +4896,tone generation in cocoa touch i need to generate a tone that i can manipulate frequency and wave the overall goal is to create a basic piano does anyone know how i can achieve thismy development platform is the iphone 2x,"['iphone', 'objective-c']" +4901,iphone truststore ca certificates does any of you have a clue how to alter the contents of securityframeworktruststoresqlite3 it seems as if the iphone uses it to store trusted ca certificates i really want my ipod touch to trust my custom certificate beside that does anyone of you know an app win32 to edit sqlite3 database files except sqliteman this one always crashes for me,['iphone'] +4903,what do 1inf00 1ind00 and 1ind mean i am messing around with some c code using floats and i am getting 1inf00 1ind00 and 1ind when i try to print floats in the screen what does those values mean i believe that 1inf00 means positive infinity but what about 1ind00 and 1ind i also saw sometimes this value 1nan which is not a number but what causes those strange values and how can those help me with debuggingi am using mingw which i believe uses ie 754 representation for float pointscan someone list all those invalid values and what they mean,"['c++', 'c']" +4904,iphone and opencv i know that opencv was ported to mac os x however i did not find any info about a port to the iphonei am not a mac developer so that i do not know whether a mac os x port is enough for the iphonedoes anyone know better than me edit thanks for the informed answer adam,['iphone'] +4910,in c is it possible to have a defined purely virtual function heres the deal i have a big class hierarchy and i have this one method that is extended all the way through the method always has to look at one or two more variable at each new level and these variable depend on the actual class in the hierarchy what i want to do is check those two extra variables then call the superclas version of that same function i want to be able to define this function as all it is immediate children will use it but i want to force any children of that class to have to redefine that method because they will have to look at their new data membersso how would i write this i usually use 0 in the h file but i assume i cannot use that and define it,['c++'] +4912,sort an array by keys based on another array is it possible in php to do something like this how would you go about writing a function here is an example the order is the most important thingcustomeraddress 123 fake stcustomername timcustomerdob 12081986customerdontsortme this value doesnt need to be sortedand i would like to do something like properorderedarray sortarraybyarraycustomer arrayname dob addressbecause at the end i use a foreach and they are not in the right order because i append the values to a string which needs to be in the correct order and i do not know in advance all of the array keysvaluesi have looked through phps internal array functions but it seems you can only sort alphabetically or numerically,['php'] +4915,how can i download all emails with attachments from gmail how do i connect to gmail and determine which messages have attachments i then want to download each attachment printing out the subject and from for each message as i process it,"['java', 'python']" +4920,code coverage tools for php is there any code coverage tool available for phpi wish to check the code coverage of my code and apis written in php but have not been able to lay my hands on any code coverage tool for php as it is more of a server side language and dynamic in naturedoes anyone know of a method by which code coverage for php can be executed,['php'] +4926,report section style list numbering in css now i know about the normal css list styles roman latin etc and certainly in years past they were somewhat inflexible in not allowing things likeaor aonlyanow i believe that you can get an effect like the above with the before and after pseudoelements is that correct and whats the browser compatibility like if you canmy main question however is that i want to have report style numberingintroduction11 objectives12 assumptions13 limitations131 new sectionand so oncan css do this and if so whats the browser compatibility like,"['html', 'css']" +4927,how long before aspnet mvc becomes widely used in industry i am trying to decide whether to learn aspnet mvc or to spend the time learning another technology that interests me i know that it is an elegant framework but i am trying to assess my future job opportunities if i invest in this skill in your estimation how long is it going to be before demand for aspnet mvc developers rivals that for developers in the other top web dev frameworks is it a matter of a year 2 years 3 on a related note do you see use of aspnet mvc surpassing classic aspnet in the foreseeable future scott guthrie says the two will exist side by side but i am curious just how much of the mind share aspnet mvc is expected to grabi know this is a speculative question i am just interested in your subjective hunches,['asp.net'] +4929,mysql tool or query that suggests table structure i used a query a few weeks ago in mysql that described a table and suggested possible improvements to its structure for example if i have an int field but only the numbers 13 in that field it will suggest set123 as the typei think i was using phpmyadmin but i have been through all the functions i can find analyze describe explain optimize etc to no avail i cannot for the life of me remember what the query was,['mysql'] +4935,builtin helper to parse useridentityname into domainusername is there any builtin utility or helper to parse httpcontextcurrentuseridentityname eg domainuser to get separately domain name if exists and useror is there any other class to do soi understand that it is very easy to call stringsplit but just interesting,"['c#', 'asp.net', '.net']" +4937,friendly byte formatting in rails i need to format an integer representation of bytes into something friendly and i am hoping that there is a utility function in ruby or in rails that will do that formatting for me to perpetuate my laziness of coursei am looking for something that would look likeformat bytes1024 1 kbformat bytes1048576 1 mblooks like there is some stuff in activesupport to do it the other way around but i have not found a way to do it in this directionif there is not one that exists does anyone have a particularly elegant solution,"['ruby-on-rails', 'ruby']" +4946,testing for whitespace in sql server i have got some blank values in my table and i cannot seem to catch them in an if statement i have triedif value and if value null and neither one catches the blank values is there any way to test whether or not a varchar is entirely whitespaceaha turns out i was testing for null wrong thanks,['sql'] +4948,what tools do you recommend to profile rails apps i have been looking for profiling tools for rails for a while i am currently playing and testing rubyprof and railsbench but i kinda frustrated with the amount of tweaking and mangling required to make then workalthought i do not mind much the tweaking i would like to know if is there any other more straightforward and easy to use tools to profile a rails app which tools you recommend,"['ruby-on-rails', 'ruby']" +4949,how to convert a string to a guid i did not find the tryparse method for the guid iam wondering how others handle converting a guid in string format into a guid typeguid idtry id new guidrequestquerystringidcatch id guidempty,['c#'] +4950,eclipse custom variable for java code templates how do you add a new variable to be inserted into a java code template how do i add a variable to the list in windowpreferencesjavacode stylecode templatescodenew java fileseditinsert variable currently my new files get created withfilecommentpackage declarationtypecommenttype declarationi would like them to get created with something likebegin filecommentpackage declarationtypecommenttype declarationend filecommentwhere begin filecomment and end filecomment appear in the insert variable list,['java'] +4954,how bad is ignoring oracle dup val on index exception i have a table where i am recording if a user has viewed an object at least once hence hasviewed objectid number fk to object table userid number fk to users tableboth fields are not null and together form the primary keymy question is since i do not care how many times someone has viewed an object after the first i have two options for handling insertsdo a select count and if no records are found insert a new recordalways just insert a record and if it throws a dup val on index exceptions indicating that there already was such a record just ignore itwhats the downside of choosing the second optionupdatei guess the best way to put it is is the overhead caused by the exception worse than the overhead caused by the initial select,['sql'] +4959,where can i find a list of socketerrorcode and nativeerrorcode thrown by socketexception a socketexception has a socketerrorcode and nativeerrorcodei would like to find a list where these codes or the common oncesare listed so i can respond in proper fasiondoes anybody know where to find such a list,"['c#', '.net']" +4966,why are net programmers so afraid of exceptions first of all i am not trying to be critical of anyone here or saying that all net programmers are this way but i am definitely noticing a trend net programmers seem to avoid exceptions like they are the plagueof course there is always the raymond chen blog post about how hard exceptions can be to handle but that does not just apply to netin a lot of other languagesenvironments i do not notice that programmers are as likely to avoid exceptions as they are in net heck in python exceptions are thrown in normal program execution iterators throw stopiteration exceptionsso what am i missing here or am i totally off base in thinking that net programmers avoid exceptions more than others,"['c#', '.net']" +4977,how do you do an in or contains in linq using lambda expressions i have the following transactsql that i am trying to convert to linq and struggling select from projectwhere projectprojectid in select projectid from projectmember where memberid a45bd16d9be0421bb5bf143d334c8155any help would be greatly appreciated i would like to do it with lambda expressions if possible thanks in advance,['sql'] +4979,skipping a column in filehelper using the filehelper library for net can i somehow skip a number of columns from the source fileaccording to docs and samples i have to add fields for all columns alas i have an excel sheet with 216 columns to import from which as few as 13 are necessary,['.net'] +4986,what is the difference between stringstream clear and str i just wanted to know whats the difference between clear and strfor examplestringstream stack overflowssclearstri wanted to know the underlying technical difference,['c++'] +4988,how to create an xps document i would like to create an xps document for storing and printingwhat is the easiest way to create an xps document for example with a simple grid with some data inside in my program and to pass it around,"['c#', '.net']" +4990,weighted random selection with and without replacement recently i needed to do weighted random selection of elements from a list both with and without replacement while there are well known and good algorithms for unweighted selection and some for weighted selection without replacement such as modifications of the resevoir algorithm i could not find any good algorithms for weighted selection with replacement i also wanted to avoid the resevoir method as i was selecting a significant fraction of the list which is small enough to hold in memorydoes anyone have any suggestions on the best approach in this situation i have my own solutions but i am hoping to find something more efficient simpler or both,['python'] +4993,when to catch javalangerror in what situations should one catch javalangerror on an application,['java'] +4997,does a truststore need the subca certificate i am trying to setup a hierarchical pki can i create a truststore containing only the root ca certificate and will that mean my application trusts certificates signed by a subca certificate which is in turn signed by the root caas an aside it seems that you must provide an entire certificate chain including the root ca certificate surely if the root ca is trusted the certificate should not need to be sent we just want to check if the next certificate down is signed by it,['java'] +5002,how do i find the name of the calling function i have been using pretty function to output the current function name however i have reimplemented some functions and would like to find out which functions are calling themin c how can i get the function name of the calling routine,['c++'] +5003,how do i replace an int property with an enum in entity framework i have an entity class that has a property with an underlying db column of datatype int however in reality i want this property to be an enum is there any way to specify that this property returns an enum,"['c#', '.net']" +5005,how can i detect a threadabortexception in a finally block net i have some critical logic in a finally block with an empty try block because i want to guarantee that the code gets executed even if the thread is aborted however i would also like to detect the threadabortexception i have found that wrapping my critical tryfinally block in a trycatch does not catch the threadabortexception is there any way to detect ittry try finally critical logic catchexception ex threadabortexception is not caught here but exceptions thrown from within the critical logic are,['.net'] +5009,prevent creation of class whose member functions are all static all the member variables and member functions in my class classa are static if a user is trying by mistake to create an object of this class he receives a warning classa local variable never referenced because all the functions are static so this object is never referenced so i want to prevent the user from trying to create an object of this class would it be enough to create a private default no variables constructor or do i have to also create private copy constructor and private assignment operator to prevent using the default constructors and if i do have to create them too maybe it would be better just to create some dummy pure virtual function instead and this will prevent the user from creating an objectthank you,['c++'] +5018,sql join where clause vs on clause after reading it this is not a duplicate of explicit vs implicit sql joinsthe answer may be related or even the same but the question is differentwhat is the difference and what should go in eachif i understand the theory correctly the query optimizer should be able to use both interchangeably,['sql'] +5019,in javascript what is the difference between indexof and search being fairly new to javascript i am unable to thiscern when to use each of thesecan anyone help clarify this for me,['javascript'] +5022,transitions and setting up layersscenes in cocos2d iphone i am looking to setup a transition between two levelsafter one level is complete use one of cocos2ds slick transition to transition into the next level in my gamelayer implementation i have methods setup to do things like self buildlevel 3 to build the playfield what do i need to do to instantiate a new gamelayer or layer node or gamescene or scene node to be able to do things such asgamelayer nextlevellayernextlevellayer buildlevel 4 do a transition between the level 3 and level 4perhaps i have laid out my code in a complete misunderstanding of objective c i am assuming you cannot setup a new gamelayer in the init code as it will hang continuously created new nodes i probably have too much playfield setup code in my init code for the gamelayer how do you guys usually handle it do you set a flag before scheduling the selector for the games main loop then if the flag is set setup the level in the games main loop or is there a better way to go about itthanks in advance,"['objective-c', 'iphone']" +5024,create a colored bubblecircle programmatically in objectivec and cocoa can anyone guide me in the correct way to build a colored bubblecircle programmaticallyi cannot use images as i need it to be able to be any color depending on user interactionmy thought was maybe to make a white circle image and then overlay a color on top of ithowever i am not sure if this would work or how to really go about itif someone could point me the right direction i would appreciate it,['objective-c'] +5032,formatting double as string in c i have a double which could have a value from around 01 to 10i wish to format this number as a string but conditionally depending on its size so if it is very small i want to format it with something likestringformat0 numberif it is not that small say 01 then i want to use something likestringformat0 numberand if it is over say 10 then format it asstringformat00 numberis there a clever way to construct this format string based on the size of the value i am going to format,"['c#', '.net']" +5034,c vs java generics i have heard that the java implementation of generics is not as good as the c implementation in that the syntax looks similar what is it that is substandard about the java implementation or is it a religious point of view,"['c#', 'java']" +5037,convert vbnet c projects can anyone recommend a good application that could be used to convert vbnet projects to c without having to do too much manual workweve used reflector to do small libraries manually but some of the larger projects will be too slow and complex to do this manually,"['c#', '.net']" +5042,sorting an array of objects in php in a specific order i have two arrays in php the first array author array is comprised of user ids in a particular order like so 8 1 6the second array user results is comprised of an array of objects like soarray 0 stdclass object id 1 user login user1 1 stdclass object id 6 user login user6 2 stdclass object id 8 user login user8 i would like to sort the second array so it is in this order which matches the order of the values in the first array of 8 1 6 so it would look like thisarray 0 stdclass object id 8 user login user8 1 stdclass object id 1 user login user1 2 stdclass object id 6 user login user6 i am weak on data structures how could i do this thanks in advance for your helpbob,['php'] +5046,c html template framework templatizing library html generator library i am looking for templategenerator libraries for c that are similar to eg rubys erb haml phps smarty etcit would be great if i it would sport some basic features like loops ifelse int conversion to strings etcparameter passing to template rendering engine is also important if i could pass all of them in a hash map instead of calling some function for each of parametersdo you have any recommendationsi can see also the possibility of embedding languages like lua however i have not found a templatizing library for that either,['c++'] +5049,aspnet mvc public alternative to urlhelpergenerateurl i want to embed a link to a controller action in my page so i can use it from javascript something likevar pollaction mycontrollercheckstatusnow i am happy to hardcode it but it would be really nice if there were a method i could use to create the url the ajaxhelperhtmlextensions contain methods to create hyperlinks actionlink and so on but if you look into the guts of them they rely on a method called urlhelpergenerateurl to resolve a controller and action into a url this is internal so i cannot really get at thisanyone found a good method in the framework to do this or must i roll my own,['c#'] +5056,have resharper keep using system when optimizing usings i was wondering if there is some option to keep resharper from removing just the using system directive perhaps this is configurable somewherealso is there a way to have resharper sort the remaining directives just as visual studio 2008 does it alphabetically i thinkthanks,['c#'] +5058,how to compute the nth root of a very big integer i need a way to compute the nth root of a long integer in python i tried powm 10n but it does not workoverflowerror long int too large to convert to floatany ideasby long integer i mean really long integers like11968003966030964356885611480383408833172346450467339251 1960931441410456834630852915677488411620264826942334897996389 485046262847265769280883237649461122479734279424416861834396522 819159219215308460065265520143082728303864638821979329804885526 557893649662037092457130509980883789368448042961108430809620626 059287437887495827369474189818588006905358793385574832590121472 6808665219708027083798371486461915677655840391752491710593159 305029014037881475265618958103073425958633163441030267478942720 703134493880117805010891574606323700178176718412858948243785754 898788359757528163558061136758276299059029113119763557411729353 91584892611258557170143200452921437591774643804348545733054 940683350937992500211758727939459249163046465047204851616590276 7245644110372168440058779182242015693911077690299591465502737 9617767993118598810609564651988597274957354987960494256488224 613682478900505821893815926193600121890632,['python'] +5063,regular expression to extract html body content i am looking for a regex statement that will let me extract the html content from just between the body tags from a xhtml documentthe xhtml that i need to parse will be very simple files i do not have to worry about javascript content or cdata tags for examplebelow is the expected structure of the html file is that i have to parse since i know exactly all of the content of the html files that i am going to have to work with this html snippet pretty much covers my entire use case if i can get a regex to extract the body of this example i will be happydoctype html public w3cdtd xhtml 10 stricten html xmlns head title title head body contenteditabletrue p example paragraph content p p nbsp p p br nbsp p h1header 1h1 bodyhtmlconceptually i have been trying to build a regex string that matches everything but the inner body content with this i would use the c regexsplit method to obtain the body content i thought this regexnbody bodynwould do the trick but it does not seem to work at all with my test content in regexbuddy,"['c#', 'html']" +5068,select object when a property equals max with nhibernate we have a query that selects rows depending on the value of another ie the max i do not think that really makes much sense so here is the queryvar deatched detachedcriteriaforenquirye2 setprojectionprojectionsaliasprojectionsmaxproperty maxproperty addrestrictionseqpropertye2enquirycode eenquirycodesessioncreatecriteriatypeofenquiry e addsubqueriespropertyeqproperty deatched addorderorderascenquirycodemy question is is this the best way can anyone suggest a better way,['c#'] +5071,pexpect running sshcopyid is hanging when trying to spawn a second process i am doing a python script where i need to spawn several sshcopyid processes and they need for me to type in a password so i am using pexpecti have basically thischild pexpectspawncommandchildexpectpasswordchildsendlinethe passwordand then i want to spawn another process i do not care about this one anymore whether it ended or notchild pexpectspawncommand2childexpectpasswordchildsendlinethe passwordand the code is hanging at the second spawnhowever if i comment out the first call the second one works so i am guessing that the fact that the first one is still running or something is keeping it from workingnow the other thing i have not been able to do is wait until the first one stopsi have triedchildclose it hangs both with true and false as parameterschildread1 it hangschildexpectpexpecteof it hangschildterminate it hangs both with true and false as parametersany ideas on what could be happeningnote i am not a python expert and i have never used pexpect before so any idea is more than welcomethanksupdate this is definitely related to sshcopyid because with other processes spawn works well even if they do not returnalso apparently sshcopyid never returns an eof,['python'] +5072,c functors and their uses i keep hearing a lot about functors in c can someone give me an overview as to what they are and in what cases they would be useful,['c++'] +5075,memory mapped files net i have a project and it needs to access a large amount of proprietary data in aspnet this was done on the linuxphp by loading the data in shared memory i was wondering if trying to use memory mapped files would be the way to go or if there is a better way with better net support i was thinking of using the data cache but not sure of all the pitfalls of size of data being saved in the cache,"['c#', '.net', 'asp.net']" +5078,load freemarker templates from database i would like to store my freemarker templates in a database table that looks something liketemplate name template contenthello hello usergoodbye so long userwhen a request is received for a template with a particular name this should cause a query to be executed which loads the relevant template content this template content together with the data model the value of the user variable in the examples above should then be passed to freemarkerhowever the freemarker api seems to assume that each template name corresponds to a file of the same name within a particular directory of the filesystem is there any way i can easily have my templates loaded from the db instead of the filesystemedit i should have mentioned that i would like to be able to add templates to the database while the application is running so i cannot simply load all templates at startup into a new stringtemplateloader as suggested belowcheersdon,['java'] +5079,bypass ie the webpage you are viewing pop up is there a way to bypass the following ie popup boxthe webapge you are viewing is trying to close the window do you want to close this window yesnothis is occurring when i add windowclose to the onclick event of an aspnet button control,"['javascript', 'asp.net']" +5085,is const cast safe i cannot find much information on const cast the only info i could find on stack overflow isthe const cast is used to addremove constness or volatileness of a variablethis makes me nervous could using a const cast cause unexpected behavior if so whatalternatively when is it okay to use const cast,['c++'] +5099,spaceefficient data structure for storing a word list is there anything better than a trie for this situationstoring a list of 100k english wordsneeds to use minimal memorylookups need to be reasonable but do not have to be lightning fasti am working with java so my first attempt was to just use a setstring however i am targeting a mobile device and already running low on memory since many english words share common prefixes a trie seems like a decent bet to save some memory anyone know some other good optionsedit more info the data structure will be used for two operationsanswering is some word xyz in the listgenerating the neighborhood of words around xyz with one letter differentthanks for the good suggestions,['java'] +5101,alternate background colors for list items i have a list and each item is linked is there a way i can alternate the background colors for each itemul lia hreflinklink 1ali lia hreflinklink 2ali lia hreflinklink 3ali lia hreflinklink 4ali lia hreflinklink 5aliul,"['html', 'css']" +5104,base64 encode in mysql i want to select a blob col from one table base64 encode it and insert it into another tables is there any way to do this without round tripping the data out of the db and through my app,['mysql'] +5106,how to install a windows service programmatically in c i have 3 projects in my vs solution 1 is a web app the other is a windows service and the last one a setup project for my web app what i want is by the end of the installation of the web app in my setup project within my custom action to try and install my windows service given that i have the location of the assembly by thenthanks for all the help in advance,"['c#', '.net']" +5117,creating a delegate type inside a method i want to create a delegate type in c inside a method for the purpose of creating anonymous methodsfor example public void mymethod delegate int sumint a int b sum mysumimplementationdelegate int a int b return ab consolewritelinemysumimplementation11tostringunfortunately i cannot do it in net 20 and c 20,['c#'] +5124,how can i force the propertygrid to show a custom dialog for a specific property i have a class with a string property having both a getter and a setter that is often so long that the propertygrid truncates the string value how can i force the propertygrid to show an ellipsis and then launch a dialog that contains a multiline textbox for easy editing of the property i know i probably have to set some kind of attribute on the property but what attribute and how does my dialog have to implement some special designer interfaceupdatethis is probably the answer to my question but i could not find it by searching my question is more general and its answer can be used to build any type of custom editor,['.net'] +5134,mixing qt and boost i am looking at starting a project in c using the qt 4 framework a crossplatform gui is required i have heard great things about the boost libraries from friends and online i have started reading up on both and wanted to ask a cursory question before i got too deep are these two development systems mutually exclusive my initial searching and reading shows some overlap in the signal handling custom build systems and other lowlevel primitivesdoes it make sense to use them both in the same project,['c++'] +5138,unit testing with spring security my company has been evaluating spring mvc to determine if we should use it in one of our next projects so far i love what i have seen and right now i am taking a look at the spring security module to determine if it is something we canshould use our security requirements are pretty basic a user just needs to be able to provide a username and password to be able to access certain parts of the site such as to get info about their account and there are a handful of pages on the site faqs support etc where an anonymous user should be given accessin the prototype i have been creating i have been storing a logincredentials object which just contains username and password in session for an authenticated user some of the controllers check to see if this object is in session to get a reference to the loggedin username for example i am looking to replace this homegrown logic with spring security instead which would have the nice benefit of removing any sort of how do we track logged in users and how do we authenticate users from my controllerbusiness code it seems like spring security provides a perthread context object to be able to access the usernameprincipal info from anywhere in your appobject principal securitycontextholdergetcontextgetauthenticationgetprincipal which seems very unspring like as this object is a global singleton in a waymy question is this if this is the standard way to access information about the authenticated user in spring security what is the accepted way to inject an authentication object into the securitycontext so that it is available for my unit tests when the unit tests require an authenticated userdo i need to wire this up in the initialization method of each test caseprotected void setup throws exception securitycontextholdergetcontextsetauthenticationnew usernamepasswordauthenticationtokentestusergetlogin testusergetpassword this seems overly verbose is there an easier way the securitycontextholder object itself seems very unspringlike,['java'] +5159,initializing stdstring from char without copy i have a situation where i need to process large many gbs amounts of data as suchbuild a large string by appending many smaller c char stringstrim the stringconvert the string into a c const stdstring for processing read onlyrepeatthe data in each iteration are independentmy question is i would like to minimise if possible eliminate heap allocated memory usage as it at the moment is my largest performance problemis there a way to convert a c string char into a stl c string stdstring without requiring stdstring to internally alloccopy the dataalternatively could i use stringstreams or something similar to reuse a large bufferedit thanks for the answers for clarity i think a revised question would behow can i build via multiple appends a stl c string efficiently and if performing this action in a loop where each loop is totally independant how can i reuse thisallocated space,['c++'] +5162,vs2008 binary 3x times slower than vs2005 i have just upgraded a native c project from vs2005sp1 to vs2008sp1the first thing i tested was a very basic functionality test of the application and the first thing i noticed is that the main numbercrunching algorithm performs three times slower in the vs2008 binaryi tested again the vs2005 binary to make sure there is not any other difference and it still performed as it did beforedid anyone stumble into this,['c++'] +5167,is there any native way in aspnet to do a success message say you have something like an aspnet aspdetailsview to show and edit a single record in a databaseit is simple to record the error cases you add validation and a validation summary when your update form fails validation it naturally makes noise it shows the validation message andor the validation summary not a single code behind is requiredbut then you pass validation and it makes your update completely silently there is no sense that anything happened and there does not seem to be any default settings to make a success message without codebehindsbut even codebehinds are confusing what event should show the success message onitemupdate right fine but then let us say you make another change and get a validation error your success message stays i was not able to find an event that would reliably turn off an existing success message if there were a validation error this should be web development 101 why is it so hardeditsomeone suggested using the itemcommand event i tried this and many other events but that success message just would not thisappear heres some codemy message in aspnetlabel idsuccessmessage clasuccessmessage runatserverlabeland my dataview tag simplified aspdetailsview ideditclient datakeynameslicenseid datasourceidmysource runatserver onitemupdatedsuccessfulclientupdate onitemcommandclearmessagesand my codebehindprotected void successfulclientupdateobject sender detailsviewupdatedeventargs e successmessageinnertext stringformatyour changes were saved successmessagevisible trueprotected void clearmessagesobject sender detailsviewcommandeventargs e successmessageinnertext stringempty successmessagevisible falseonce i do a successful update however nothing seems to make that message thisappear not even failed validation2nd editjust want to be clear that i did try putting the clearmessages code in page load however nothing seems to make that successmessage label thisappear when i hit update a 2nd time with a validation error can anyone suggest any other troubleshooting tips,['asp.net'] +5173,thread safety and const how does const pointers references and member functions help with thread safety in c,['c++'] +5176,image resize in grails i am developing a web album using grails and for image processing i am using grailsimagetools plugin i need a functionality to resize the images if the uploaded images size is too big for eg more than 600 840 in this case i need to resize this image to 600 840 what is the most efficient way to do this thanks a lot,['java'] +5182,are iframes considered bad practice somewhere along the line i picked up the notion that using iframes is bad practice is this true what are the proscons of using them,['html'] +5183,java memory model can someone explain it for years and years i have tried to understand the part of java specification that deals with memory model and concurrency i have to admit that i have failed miserably yes i understand about locks and synchronized and wait and notify and i can use them just fine thank you i even have a vague idea about what volatile does but all of that was not derived from the language spec rather from general experiencehere are two sample questions that i am asking i am not so much interested in particular answers as i need to understand how the answers are derived from the spec or may be how i conclude that the spec has no answerwhat does volatile do exactlyare writes to variable atomic does it depend on variables type,['java'] +5184,how do realloc and memcpy work dear all here are my questions1 do realloc and memcpy copy the entries in an array to another in a way faster than just iterating on each element on if the answer is yes then what do you think is its complexity 2 if the size allocated is smaller than the original size does realloc copy the entries to somewhere else or just leave them as they are decreasing the size of the array thanks so much,['c'] +5185,should an interface that is inherited from baseclass be implemented explicitly in subclass my question is if an interface that is implemented implicitly by extending a class that already implements it should be explicitly implemented by the class if the class wants to advertise the fact that it fulfills the contract of that interface for instance if you want to write a class that fulfills the contract of the interface javautillist you implement this extending the class javautilabstractlist that already implements the interface list do you explicitly declare that you implement listpublic class mylist extends abstractlist implements listor do you save typing by using the implicit waypublic class mylist extends abstractlistwhich way is considered better style what reasons do you have to prefer one way or another in which situations you would prefer way 1 or way 2,['java'] +5186,what is the best way to determine application root directory i need to get all dlls in my application root directory what is the best way to do thatstring root applicationstartuppathorstring root new fileinfoassemblygetexecutingassemblylocationfullnameand after thatdirectorygetfilesroot dllwhich way is better are there better ways,"['c#', '.net']" +5188,circular dependencies between dlls with visual studio i have a circular dependency between two functions i would like each of these functions to reside in its own dll is it possible to build this with visual studiofooint i if i 0 bari i should compile into foodllbarint i if i 0 fooi i should compile into bardlli have created two projects in visual studio one for foo and one for bar by playing with the references and compiling a few times i managed to get the dlls that i want i would like to know however whether visual studio offers a way to do this in a clean wayif foo changes bar does not need to be recompiled because i only depend on the signature of bar not on the implementation of bar if both dlls have the lib present i can recompile new functionality into either of the two and the whole system still worksthe reason i am trying this is that i have a legacy system with circular dependencies which is currently statically linked we want to move towards dlls for various reasons we do not want to wait until we clean up all the circular dependencies i was thinking about solutions and tried out some things with gcc on linux and there it is possible to do what i suggest so you can have two shared libraries that depend on each other and can be built independent of each otheri know that circular dependencies are not a good thing to have but that is not the thiscussion i want to have,['c++'] +5190,jrails vs prototype i am not trying to make this a preference question i am really wondering what peoples experiences are with using jquery and rails or jrails for development most rails users including myself up to now have been using prototype however i am mixing in a lot of jquery plugins since they are so easy to use and extendi am now thinking about moving from prototype to jquery for a new rails project however i love the power of prototype protoype is almost a new language that sites ontop of js whereas i find that jquery is like a great scripting language with lots of syntax sugar and chaininganyway your thoughts would be much appreciated,"['javascript', 'jquery', 'ruby-on-rails']" +5193,how to avoid xml injection i have input field value from that is used for forming xpath querywhat symbols in input string should i check to minimise possibility of xml injection,['.net'] +5201,stringbuilder for string concatenation throws outofmemoryexception we mostly tend to following the above best practicehave a look at string vs stringbuilderbut stringbuilder could throw outofmemoryexception even when there is sufficient memory available it throws oom exception because it needs continuous block of memorysome links for referencestringbuilder outofmemoryexceptionand there are many morehow many of you faced this problem or aware and what did you do to resolve itis there anything i am missingps i was not aware of thisi have rephrased the question the same thing worked with manual concatenationi will verify this and update so the other thing that caused me concern was that there is enough memory in the system that is the reason i raised this question here to check whether any one faced this problem or there was something drastically wrong with the code,['c#'] +5208,approach to convert from orgjodatimedatetime to javautilcalendar anyone done this and can share i see an option or two but want to know what others have accomplished,['java'] +5209,basic how is the session id created does iis create the session id when a request is received and where is that saved client or serverhow does server recognize that the request is coming from the same usersession,['asp.net'] +5212,how do you reduce compile time and linking time for visual c projects native c how do you reduce compile time and linking time for vc projects native cplease specify if each suggestion applies to debug release or both,['c++'] +5223,difference between a postback and a callback i keep on hearing this words callback and postback tossed aroundwhat is the difference between two is postback very specific to the aspnet pages,"['asp.net', 'javascript']" +5224,cross platform keylogger i am looking for ways to watch mouse and keyboard events on windows linux and mac from pythonmy application is a time tracker i am not looking into the event i just record the time when it happens if there are no events for a certain time say 10 minutes i assume that the user has left and stop the current projectwhen the user returns events come in again i wait a moment so this does not get triggered by the cleaning crew or your pets or an earthquake if the events persist over a longer period of time i assume that the user has returned and i pop up a small inactive window where she can choose to add the time interval to break the current project meeting etc or a different projecti have solved the keylogger for windows using the pyhookon linux i have found a solution but i do not like it i can watch all device nodes in etcinput and update a timestamp somewhere in var or tmp every time i see an event there are two drawbacks 1 i cannot tell whether the event if from the user who is running the time tracker and 2 this little program needs to be run as root not goodon mac i have no idea yetquestionsis there a better way to know whether the user is creating events than watching the event devices on linuxany pointers how to do that on a mac,['python'] +5225,proper way to stop tcplistener i am currently using tcplistener to address incoming connections each of which are given a thread for handling the communication and then shutdown that single connection code looks as followstcplistener listener new tcplisteneripaddressany portsystemconsolewritelineserver initialized listening for incoming connectionslistenerstartwhile listen step 0 client connection tcpclient client listeneraccepttcpclient thread clientthread new threadnew parameterizedthreadstarthandleconnection clientthreadstartclientgetstream clientclosethe listen variable is a boolean that is a field on the class now when the program shuts down i want it to stop listening for clients setting listen to false will prevent it from taking on more connections but since accepttcpclient is a blocking call it will at minimum take the next client and then exit is there any way to force it to simply break out and stop right then and there what effect does calling listenerstop have while the other blocking call is running,['c#'] +5230,visual studio skips build when i try to build my project i get the following message in the build window build 0 succeeded or uptodate 0 failed 1 skipped i tried rebuilding then building again but it does not help is there a way to view more detailed messages the skipped part does not give me any info on whats wrong i am using visual studio 2005 professional edition,['c++'] +5233,howto rotate image using jquery rotate plugin how do you rotate an image using jqueryrotate plugini have tried the following and it does not seem to workhtmlheadmeta httpequivcontenttype contenttexthtml charsetwindows1252titleview phototitlescript typetextjavascript srcscriptsjqueryjsscriptscript typetextjavascript srcscriptsjqueryrotate11jsscriptscript typetextjavascriptvar angle 0setinterval function e rotate 100 function rotate angle angle 1 picrotateanglescriptheadbodyimg border0 srcplayergif namepic idpicbodyhtmlother methods that are supported by most browsers are wanted too thanks,['jquery'] +5234,android development with netbeans ide has anybody had any success with developing for android platform using netbeans 55 ide i know of atleast netbeans one plugin that is supposed to support it but wanted to hear if anyone is using netbeans for android development and how easy it is to set it up,['android'] +5236,how can i make eclipse cdt autoindent properly when using boost foreach i write this tiny c example in eclipse 341 cdt 501include iostreaminclude vectorinclude boostforeachhppint foo stdvectorint numbers boost foreachint n numbers stdcout and stdendl stdcout numberssize stdendlthen i hit shiftctrlf to format my code and it becomesinclude iostreaminclude vectorinclude boostforeachhppint foo stdvectorint numbers boost foreachint n numbers stdcout and stdendlstdcout numberssize stdendlthis is with the bsdallman code style other styles obviously vary the look of the formatted code but none give correct indentationwhen i use the format feature on a larger piece of code subsequent functions or methods are also affected by too little indentation making the formatting help pretty unhelpfulis there something i can do to make the indentation work properly with boost foreach,['c++'] +5238,how to organize python test in a way that i can run all tests in a single command currently my code is organized in the following tree structuresrc module1py module2py test module1py test module2py subpackage1 init py moduleapy modulebpy test moduleapy test modulebpywhere the modulepy files contains the source code and the test modulepy contains the testcases for the relevant modulewith the following comands i can run the tests contained in a single file for example cd src nosetests test filesystempyran 18 tests in 0390sokhow can i run all tests i tried with nosetests m test but it does not workcd src nosetests m test ran 0 tests in 0sokthanks,['python'] +5240,what are the differences between perl python awk and sed just want to know what are the main differences among them and the power of each language where it is better to use itedit it is not vs like topic just information,['python'] +5246,is it safe to run a pool under nt authoritynetwork service i normally would create a limited rights user and run the process under that but the fact that pools automatically created under iis7 in 2008 use this account makes me think that this is perfectly safe and possibly more so than something i create the whole secure by default push from redmond would lead me to believe this is the case,['asp.net'] +5248,dynamic memory allocation failure recovery i am working on an embedded processor 400 mhz intel pxa255 xscale and i thought i saw one case where there was not enough memory to satisfy a new operation the program did not crash so i assumed other threads had freed their memory and it was just a transient thing this is some pretty critical code so exiting is not an option and some sort of error needs to be returned to the remote userwould the following small fix be enough to solve the problem or is there a better way before replacing every new with the following code i thought i would askchar somearrdo somearr new char10 sleep100 no justification for choosing 100 ms while somearr null does the sleep help should i set some max number of retries is it possible to use static initialization everywherefinal update thank you very much for the helpful responses but it turns out there was an error in the code checking for failed memory allocation i will keep all of these answers in mind and replace as many mallocs and news as i can though especially in errorhandling code,['c++'] +5252,how much input validation should i be doing on my python functionsmethods i am interested in how much up front validation people do in the python they writehere are a few examples of simple functionsdef factorialnum computes the factorial of numdef ispalindromeinputstr tests to see if inputstr is the same backwards and forwardsdef sumnums same as the builtin sum computes the sum of all the numbers passed inhow thoroughly do you check the input values before beginning computation and how do you do your checking do you throw some kind of proprietary exception if input is faulty badinputexception defined in the same module for example do you just start your calculation and figure it will throw an exception at some point if bad data was passed in asd to factorial for examplewhen the passed in value is supposed to be a container do you check not only the container but all the values inside itwhat about situations like factorial where whats passed in might be convertible to an int eg a float but you might lose precision when doing so,['python'] +5255,how to change xml attribute how can i change an attribute of an element in an xml file using c,['c#'] +5264,is there a way to prevent reflector from being able to reflect my source code is there a way reliable and preferably not commercial to prevent from reflector to reflect my source codethanksadi,['.net'] +5267,javascript hashmap equivalent as made clear in update 3 on this answer this notationvar hash hashxdoes not actually hash the object x it actually just converts x to a string via tostring if it is an object or some other builtin conversions for various primitive types and then looks that string up without hashing it in hash object equality is also not checked if two different objects have the same string conversion they will just overwrite each othergiven this are there any efficient implementations of hashmaps in javascript for example the 2nd google result of javascript hashmap yields an implementation which is on for any operation various other results ignore the fact that different objects with equivalent string representations overwrite each other,['javascript'] +5276,some antipatterns on using assert java and others finally i have a question to ask on stack overflow the main target is for java but i believe it is mostly language agnostic if you do not have native assert you can always simulate iti work for a company selling a suite of softwares written in java the code is old dating back to java 13 at least and at some places it shows that is a large code base some 2 millions of lines so we cannot refactor it all at oncerecently we switched the latest versions from java 14 syntax and jvm to java 16 making conservative use of some new features like assert we used to use a debugassert macro i know assert has been introduced in 14 but we did not used it before generics only typed collections foreach loop enums etci am still a bit green about the use of assert although i have read a couple of articles on the topic yet some usages i see leave me perplex hurting my common sense so i thought i should ask some questions to see if i am right to want to correct stuff or if it goes against common practices i am wordy so i bolded the questions for those liking to skim stufor reference i have searched assert java in so and found some interesting threads but apparently no exact duplicate how to avoid a nulla statements in java and how much null checking is enough are quite relevant because lot of asserts we have just check if variable is null at some places in our code there are usages of the null object eg returning new string0 but not always we have to live with that at least for maintenance of legacy codesome good answers also in java assertions underusedoh and so indicates with reason that when should i use debugassert question is related too nice feature to reduce duplicatesfirst main issue which triggered my question todaysubdocument asubdoc documentsgetat i assert asubdoc null if asubdocgettype gis doc continueassert asubdocgetdoc null contentsinfo ci contentsinfo asubdocgetdocyes we use ms cc stylecode conventions and i even like it coming from same background so sue usfirst the assert form comes from conversion of debugassert calls i thislike the extra parentheses since assert is a language construct not no longer here a function call i thislike also return foo next the asserts do not test here for invariants they are rather used as guards against bad values but as i understand it they are useless here the assert will throw an exception not even documented with a companion string and only if assertions are enabled so if we have ea option we just have an assertion thrown instead of the regular nullpointerexception one that does not look like a paramount advantage since we catch unchecked exceptions at highest level anywayam i right supposing we can get rid of them and live with that ie let java raise such unckecked exception or of course test against null value if likely which is done in other placesside note should i have to assert in the above snippet i would do that against ci value not against the getter even if most getters are optimizedinlined we cannot be sure so we should avoid calling it twicesomebody told in the last referenced thread that public methods should use tests against values of parameters usage of the public api and private methods should rely on asserts instead good advicenow both kinds of methods must check another source of data external input ie data coming from user from a database from some file or from the network for examplein our code i see asserts against these values i always change these to real test so they act even with assertions thisabled these are not invariants and must be properly handledi see only one possible exception where input is supposed constant for example a database table filled with constants used in relations program would break if this table is changed but corresponding code was not updateddo you see other exceptionsanother relatively frequent use i see which seems ok in the default of a switch or at the end of a series of else if testing all possible values these cases date back before our use of enums there is often an assert false unexpected value for stuff stufflooks legitimate for me these cases should not happen in production what do you think beyond the no switch use oo advices which are irrelevant hereand finally are there any other useful use cases or annoying gotchas i missed here probably,['java'] +5282,monitoring load on aspnet application i am looking for ways to keep track of simultaneous users within an application i cannot use iis logs due to a load balancer that abstracts the users ip address i am looking for a net code based solution or a configuration item possibly with health monitoring to be able to track the true simultaneous user counti know that i can monitor the number of sessions but that is not really an ideal method to show as it can be bloated based on the number of sessions with users abandoning their session,['asp.net'] +5287,why should you not use number as a constructor i entered this statement in jslintvar number new number3and received the following messagedo not use number as a constructorwhy is that the statement is creating a number object not a primitive value so i do not see why using new is a problemedit thanks for all the responses they have got me thinking further so i posted a followup question hereupdate thanks again for all the responses they have been very helpful i guess to sum up in javascript an object type is not equal to another object type even when they have the exact same value unless they are both the exact same objectin other words in matthews example below n1 n2 is false because you are comparing two references to two separate objects but n1 n1 is true because you are comparing references to the exact same objectso while i now understand why using number as a constructor can cause problems i found you can use the valueof property when comparing number objects in other words n1valueof n2valueof is true this is because youre comparing the return values of the valueof function not the references to the objects themselves,['javascript'] +5302,how can i include css files from an mvc partial control i am using aspnet mvc and i have a partial control that needs a particular css js file included is there a way to make the parent page render the script and link tags in the head section of the page rather than just rendering them inline in the partial contolto clarify the control that i want to include the files from is being rendered from a view with htmlrenderpartial and so cannot have serverside content controls on it i want to be able to include the files in the html head section so as to avoid validation issues,"['javascript', 'css']" +5305,java get jpanel components i have a jpanel full of jtextfieldsfor int i0 imaxpoints i jtextfield textfield new jtextfield pointsaddtextfieldhow do i later get the jtextfields in that jpanel like if i want their values with textfieldgettextthanks,['java'] +5306,in sql or django orm whats the conventional way to have an ordered onetomany say i wanted to have a project and onetomany with todo items and wanted to reorder the todo items arbitrarily in the past i have added a numbered order field and when someone wants to change the order had to update all the items with their new order numbers this is probably the worst approach since it is not atomic required several updatesi notice django has a multivalued commaseparatedintegerfield which could contain the order by storing the ordered keys to the items in the todo items table right in one field of the project tablei have pondered a dewey decimal system where if i wanted to take item 3 and put it between 1 and 2 i would change it is order number to 15something tells me there is an easier option that i am missing thoughhow would you give order to a onetomany relationship,['sql'] +5310,differences between python game libraries pygame and pyglet i have had some experience with pygame but there seems to be a lot of buzz around pyglet these dayshow do these two libraries compare what would be the advantage of using one over the other both in features and ease of usefinally would you say that one is more pythonic than the other,['python'] +5314,how do i programmatically check an item in a checkedlistbox in c i have a checkedlistbox and i want to automatically tick one of the items in it the checkeditems collection does not allow you to add things to itany suggestions,['c#'] +5325,loadvideobyid in youtubes regular player not chromeless i have a youtubes player in the webpage i need to change the video played by this player dynamicalythis is relatively easy using youtubes chromeless player it has method loadvideobyid which works perfectly the problem is that the chromeless player does not have any controls playpause etc the regular youtube player has all this but it does not have the loadvideobyid methodis there any way to include the controls of regular player into chromeless player or to implement loadvideobyid method in the regular playerthanks,['javascript'] +5333,net xmlwriter unexpected encoding is confusing me environment is vs2008 net 35the following c code note the specified encoding of utf8xmlwritersettings settings new xmlwritersettings stringbuilder sb new stringbuildersettingsencoding systemtextencodingutf8settingsindent falsesettingsnewlinechars nsettingsconformancelevel systemxmlconformanceleveldocumentxmlwriter writer xmlwritercreate sb settings write xml data writerwritestartelement ccheader writerwriteattributestring protocolversion 100 writerwriteattributestring servercapabilities 0x0f writerwriteendelement writerflush actually generates the xml omitted because so barfs on themxml version10 encodingutf16ccheader protocolversion100 servercapabilities0x0f why do i get the wrong encoding generated here what am i doing wrong,['c#'] +5339,net processing spawning issues i have an executable that runs instantly from a command prompt but does not appear to ever return when spawned using systemdiagnosticsprocessbasicly i am writing a net library wrapper around the accurev cli interface so each method call spawns the cli process to execute a commandthis works great for all but one command accurevexe show depotshowever when running this from a console it runs fine when i call it using a net process it hangsthe process spawning code i use is public static string executecommandstring command process p createprocesscommand pstart pwaitforexit accurev writes to the error stream if exitcode is non zero if pexitcode 0 string error pstandarderrorreadtoend logwritecommand failed error throw new accurevexceptionerror else return pstandardoutputreadtoend creates accurev process summary param namecommandparam returnsreturns private static process createprocestring command logwriteexecuting command command procestartinfo startinfo new procestartinfo process p new process startinfocreatenowindow false startinforedirectstandardoutput true startinforedirectstandardinput true startinforedirectstandarderror true startinfouseshellexecute false startinfoarguments command startinfofilename accurev pstartinfo startinfo return p it hangs at pwaitforexitany adviceedit solvednet proces hang if the output buffer overflows i switched to using an asynchronous read method and everything works public static string executecommandstring command stringbuilder outputdata new stringbuilder process p createprocesscommand poutputdatareceived delegateobject sender datareceivedeventargs e outputdataappendlineedata pstart pbeginoutputreadline pwaitforexit accurev writes to the error stream if exitcode is non zero if pexitcode 0 string error pstandarderrorreadtoend logwritecommand failed error throw new accurevexceptionerror else return outputdatatostring,['.net'] +5341,generics arrays and the classcastexception i think there must be something subtle going on here that i do not know about consider the followingpublic class foot private t a t new object5 public foo add some elements to a public t geta return a suppose that your main method contains the followingfoodouble f new foodoubledouble d fgetayou will get a castclassexception with the message javalangobject cannot be cast to javalangdoublecan anyone tell me why my understanding of classcastexception is that it is thrown when you try to cast an object to a type that cannot be casted that is to a subclass of which it is not an instance to quote the documentation egobject o new double3double d double o working caststring s string o classcastexceptionand it seems i can do this if a was just a t instead of an array t we can get a and cast it without a problem why do arrays break thisthanks,['java'] +5347,getset in the c world fauxpas i notice that getset is not the c way as far as i can tell by looking at booststl and even reading the writings of some of the top c expertsdoes anyone use getset in their c class design and can someone suggest a rule of thumb on where if at all this paradigm belongs in the c worldit is obviously very popular in java and imitated by c using property syntactic sugareditwell after reading more about this in one of the links provided in an answer below i came across at least one argument for keeping the accessors of a member field the same name as the member field namely that you could simply expose the member field as public and instead make it an instance of a class and then overload the operator by using setget youd force clients to not only recompile but to actually change their code not sure i love the idea seems a bit too fine grained to me but more details are herec killed the gettersetter,['c++'] +5351,how do you databind to a systemwindowsformstreeview control i am looking at this control and it seems to be lacking the standard net datasource and datamember properties for databinding is this control not bindable i can write some custom function that populates the treeview from a given data source i suppose and embed data objects as necessary but is that the best practice or does everyone simply use a 3rd party treeview control,['.net'] +5353,do you use the tr 24731 safe functions the iso c committee isoiec jtc1sc21wg14 has published tr 247311 and is working on tr 247312tr 247311 extensions to the c library part i boundschecking interfaceswg14 is working on a tr on safer c library functions this tr is oriented towards modifying existing programs often by adding an extra parameter with the buffer length the latest draft is in document n1225 a rationale is in document n1173 this is to become a technical report type 2tr 247312 extensions to the c library part ii dynamic allocation functionswg14 is working on a tr on safer c library functions this tr is oriented towards new programs using dynamic allocation instead of an extra parameter for the buffer length the latest draft is in document n1337 this is to become a technical report type 2questionsdo you use a library or compiler with support for the tr247311 functionsif so which compiler or library and on which platformsdid you uncover any bugs as a result of fixing your code to use these functionswhich functions provide the most valueare there any that provide no value or negative valueare you planning to use the library in the futureare you tracking the tr247312 work at all,['c'] +5355,finding the current active window in mac os x using python is there a way to find the application name of the current active window at a given time on mac os x using python,"['python', 'objective-c']" +5356,check for column name in a sqldatareader object how do i check to see if a column exists in a sqldatareader object in my data access layer i have create a method that builds the same object for multiple stored procedures calls one of the stored procedures has an additional column that is not used by the other stored procedures i want to modified the method to accommodate for every scenariomy application is written in c,"['c#', '.net']" +5357,simple standalone java soap web service client from wsdl using maven i am looking to generate a simple standalone java client which will make calls to a soap web service given a wsdl when i say simple and standalone i mean that once i am done i want to be able to do something likeimport mygeneratednonsensepublic static void mainstring args client client new client clientgetsomethingi have had great time recently with maven on some other projects and i want to keep that going so would aim to use it here i do not want the tool to generate anything expect the classes that allow me to do the aboveanyone done this recently and can recommend a ws library and maven plugin thanks,['java'] +5358,how do i get the utc time of midnight for a given timezone the best i can come up with for now is this monstrosity datetimeutcnow replacetzinfopytzutc astimezonepytztimezoneaustraliamelbourne replacehour0minute0second0microsecond0 astimezonepytzutc replacetzinfononedatetimedatetime2008 12 16 13 0ie in english get the current time in utc convert it to some other timezone set the time to midnight then convert back to utci am not just using now or localtime as that would use the servers timezone not the users timezonei cannot help feeling i am missing something any ideas,['python'] +5360,insert dates in the return from a query where there is none we are building a query to count the number of events per hour per day most days there are hours that do not have any activity and therefore where the query is run the count of activities per hour show up but there are gaps and the query excludes these we still want to show the hours that do not have activity and thisplay a zero so that zero value can then be charted the query we using looks like this aselect datepartyear dev time as year datepartmonth dev time as month datepartday dev time as day dateparthour dev time as hour counttdm msg as total activitesfrom tckt actwhere tdm msg a4162a2 and dev time dateaday 1 getdategroup by datepartyear dev time datepartmonth dev time datepartday dev time dateparthour dev timeorder by datepartyear dev time asc datepartmonth dev time asc datepartday dev time asc dateparthour dev time asc,['sql'] +5363,why is app offline failing to work as soon as you it starts loading dlls could anyone please help me with this on the production site app offlinehtm works only till you start uploading dlls as soon as you start uploading dlls it throws following errorcould not load file or assembly subsonic or one of its dependencies the process cannot access the file because it is being used by another processnow this clearly shows that iis is still trying to serve the aspx page is there anything i am missing here any help would be appreciated i have spent hours googling but to no availthanks in advancemanisha,['asp.net'] +5368,why does stdafxh work the way it does as usual when my brains messing with something i cannot figure out myself i come to you guys for help this time i have been wondering why stdafxh works the way it does to my understanding it does 2 thingsincludes standard headers which wemight use and which are rarely changedwork as a compilerbookmark for whencode is no longer precompilednow these 2 things seems like two very different tasks to me and i wonder why they did not do two seperate steps to take care of them to me it seems reasonable to have a pragmacommand do the bookmarking stuff and to optionally have a headerfile a long the lines of windowsh to do the including of oftenused headers which brings me to my next point why are we forced to include oftenused headers through stdafxh personally i am not aware of any often used headers i use that i am not already doing my own includes for but maybe these headers are necessary for dll generationthx in advance,['c++'] +5369,how to change font color of thisabled input in firefox when i thisable input elements the text is taking the font color 0 in firefox this is not happening in ie please check the below page in ie and firefox let me know how to give it a gray look as in ietest,"['html', 'css']" +5382,chained if structure imagine this case where i have an object that i need to check a propertyhowever the object can currently have a null valuehow can i check these two conditions in a single if conditioncurrently i have to do something like thisif myobject null if myobjectid pid myobjectid pid myobjectorder porder i would like something like thisif myobject null myobjectid pidi want to evaluate the second condition only if the first was truemaybe i am missing something and that is why i need your help,"['c#', 'java']" +5383,boxingunboxing and nullable i understand that boxing and unboxing is about casting real type to object object to real type but i do not understand what the msdn say about it with the nullable here is the text i do not understandwhen a nullable type is boxed the common language runtime automatically boxes the underlying value of the nullable object not the nullable object itself that is if the hasvalue property is true the contents of the value property is boxed when the underlying value of a nullable type is unboxed the common language runtime creates a new nullable structure initialized to the underlying value sourcewhen you change your object to a real type the real type variable that was nullable will be the type of object i do not get it,['.net'] +5385,can intellij idea open more than one editor window for files from the same project i can split editor panes horizontally or vertically but it does not seem possible to view code in two separate physical windows i am aware that idea can open multiple projects in separate windows but i would like to be able to do this for two files in a single project one answer suggested unpinning the tab but i have not been able to make that work i am on mac osx if that mattersthis seems like a basic feature in todays world of multiheaded workstations before moving to an ide i used to do this regularly with good old emacs is there some trick i am not aware of to make this happen,['java'] +5386,validating file types by regular expression i have a net webform that has a file upload control that is tied to a regular expression validator this validator needs to validate that only certain filetypes should be allowed for upload jpggifdocpdfthe current regular expression that does this isazaz2wjpgjpggifgifdocdocpdfpdfhowever this does not seem to be workingcan anyone give me a little reg ex helpthanks,"['c#', '.net']" +5400,java equivalent to phps preg replace callback i am in the process of moving an application from php to java and there is heavy use of regular expressions in the code i have run across something in php that does not seem to have a java equivalentpreg replace callbackfor every match in the regex it calls a function that is passed the match text as a parameter as an example usagearticletext preg replace callbackthumbdthumbreplace articletext function thumbreplacematches global photos return img srcthumbs photosmatches1 what would be the ideal way to do this in java,"['java', 'php']" +5404,how does one test a file to see if it is a valid xml file before loading it with xdocumentload i am loading an xml document in my c application with the followingxdocument xd1 new xdocumentxd1 xdocumentloadmyfilebut before that i do test to make sure the file exists withfileexistsmyfilebut is there an easy way to test the file before the xdocumentload to make sure it is a valid xml file in other words my user can accidentally click on a different file in the file browser and trying to load say a php file causes an exception the only way i can think of is to load it into a streamwriter and simple do a text search on the first few characters to make sure they say thanksadeena,['c#'] +5407,detect failure to load contents of an iframe i can detect when the content of an iframe has loaded using the load event unfortunately for my purposes there are two problems with thisif there is an error loading the page 404500 etc the load event is never firedif some images or other dependencies failed to load the load event is fired as usualis there some way i can reliably determine if either of the above errors occurredi am writing a semiweb semidesktop application based on mozillaxulrunner so solutions that only work in mozilla are welcome,"['javascript', 'html']" +5409,getting the net framework directory path how can i obtain the net framework directory path inside my c applicationthe folder that i refer is cwindowsmicrosoftnetframeworkv2050727,"['c#', '.net']" +5410,creating a temp dir in java possible duplicatecreate a temporary directory in java i have a test for a create db method and i need a temp directory to put it in the directory will be removed after the test is done i tried using filecreatetempfile like sotempdir filecreatetempfileinstall dirtempdirmkdirbut tempdir is already exists as a file how do i create a temp directory as opposed to a file,['java'] +5412,firefox vs ie vs chrome vs safari currently i am designing a website and i am finding it very difficult to thisplay the website perfect on all browsers is there any rules suggestions etc to followthanks,"['html', 'css']" +5413,nsdictionary with ordered keys i am curious if this is a situation any other folks have found themselves in i have an nsdictionary stored in a plist that i am basically using as an associative array strings as keys and values i want to use the array of keys as part of my application but i would like them to be in a specific order not really an order that i can write an algorithm to sort them into i could always store a separate array of the keys but that seems kind of kludgey because i would always have to update the keys of the dictionary as well as the values of the array and make sure they always correspond currently i just use mydictionary allkeys but obviously this returns them in an arbitrary nonguaranteed order is there a data structure in objectivec that i am missing does anyone have any suggestions on how to more elegantly do this,"['iphone', 'objective-c']" +5421,how can i add a context menu to a listboxitem i have a listbox and i want to add a context menu to each item in the list i have seen the solution to have the right click select an item and suppress the context menu if on white space but this solution feels dirty does anyone know a better way,['c#'] +5427,newest microsoft chart and aspnet mvc recently aspnet developer launched its newest control charting control microsoft chart does this compatible with aspnet mvc or its only compatible with aspnet webform,['asp.net'] +5437,using group concat on subquery in mysql i have a mysql query in which i want to include a list of ids from another table on the website people are able to add certain items and people can then add those items to their favourites i basically want to get the list of ids of people who have favourited that item this is a bit simplified but this is what it boils down tobasically i do something like thisselect group concatselect userid from favourites where itemid itemsid separator as idlistfrom itemswhere id someidthis way i would be able to show who favourited some item by splitting the idlist later on to an array in php further on in my code however i am getting the following mysql error1242 subquery returns more than 1 row i thought that was kind of the point of using group concat instead of for example concat am i going about this the wrong wayok thanks for the answers so far that seems to work however there is a catch items are also considered to be a favourite if it was added by that user so i would need an additional check to check if creator userid can someone help me come up with a smart and hopefully efficient way to do thisthank youedit i just tried to do thisselect left join favourites on userid itemid or creator useridand idlist is empty note that if i use inner join instead of left join i get an empty result even though i am sure there are rows that meet the on requirement,"['mysql', 'sql']" +5441,elegantly determine if more than one boolean is true i have a set of five boolean values if more than one of these are true i want to excecute a particular function what is the most elegant way you can think of that would allow me to check this condition in a single if statement target language is c but i am interested in solutions in other languages as well as long as were not talking about specific builtin functions one interesting option is to store the booleans in a byte do a right shift and compare with the original byte something like ifmybyte mybyte 1 but this would require converting the separate booleans to a byte via a bitarray and that seems a bit pun intended clumsy editsorry that should have been ifmybyte mybyte 1 editnote this is of course very close to the classical population count sideways addition or hamming weight programming problem but not quite the same i do not need to know how many of the bits are set only if it is more than one my hope is that there is a much simpler way to accomplish this,['c#'] +5443,recursive sql problem i have a problem that i would like have solved via a sql query this is going tobe used as a poc proof of conceptthe problemproduct offerings are made up of one or many product instances a productinstance can belong to many product offeringsthis can be realised like this in a tablepo pia 10a 11a 12b 10b 11c 13now i would like to get back the product offer from a set of product instanceseg if we send in 1013 the expected result back is b c and if we send inonly 10 then the result should be null since no product offering is made up ofonly 10 sending in 1012 would result in a not a b since 12 is not a valid product offer in it selfprerequisitesthe combination of product instances sent in can only result in one specificcombination of product offerings so there is only one solution to each query,['sql'] +5445,how can i set the position of my datagrid scrollbar in my winforms app in my c winforms app i have a datagrid when the datagrid reloads i want to set the scrollbar back to where the user had it set how can i do thisedit i am using the old winforms datagrid control not the newer datagridview,['c#'] +5447,how can i debug a win32 process that unexpectedly terminates silently i have a windows application written in c that occasionally evaporates i use the word evaporate because there is nothing left behind no were sorry message from windows no crash dump from the dr watson facilityon the one occasion the crash occurred under the debugger the debugger did not breakit showed the application still running when i manually paused execution i found that my process no longer had any threadshow can i capture the reason this process is terminating,['c++'] +5452,getting selected value from radiobuttonlist new to aspnetci have a radiobuttonlist on my page that is populated via databindingaspradiobuttonlist idrb runatserveraspradiobuttonlistaspbutton textsubmit onclicksubmit runatserver how do i get the value of the radio button that the user selected in my submit method,"['c#', 'asp.net']" +5469,can you nest html forms is it possible to nest html forms like thisform namemainform form namesubform formformso that both forms work my friend is having problems with this a part of the subform works while another part of it does not,['html'] +5472,fade in each element one after another i am trying to find a way to load a json page to thisplay my content which i currently have but i am trying to fade in each element one after another is anyone familiar with a way to do thatfade in each element with a slight delayhere is an example of my code i am using the jquery frameworkcode,['jquery'] +5473,how to get the path to the current template in joomla 15 i am writing a component and would like to insert images from the template folderhow do you get the correct path to the template folder,['php'] +5491,python single instance of program is there a pythonic way to have only one instance of a program running the only reasonable solution i have come up with is trying to run it as a server on some port then second program trying to bind to same port fails but it is not really a great idea maybe there is something more lightweight than this take into consideration that program is expected to fail sometimes ie segfault so things like lock file would not workupdate the solutions offered are much more complex and less reliant than just having a port occupied with a nonexistent server so i would have to go with that one,['python'] +5496,reverting css style of i am using a bookmarklet that inserts a script tag into the current web pagethis script has some ui and an input typesubmit tag in itweb page a has chosen not to style input typesubmit tags whereas web page b has styled themthis results in the bookmarklet thisplaying differently styled submitbuttons based on the underlying pages stylei want the submit buttons to be styled identically on all web pages in its default mannerone solution is to set the css style for the submit button within my script so it shows up identically on all pages this is what i have done for all other tagsmy question is how do i set the css style for the submit button so it thisplays in a default manner or can one remove existing styling and if so how for the button so that it thisplays in the default mannerin other words how can i have the submit buttons within the ui of my bookmarklet be thisplayed in the default manner regardless of whether the underlying web page has chosen to style it or notnote by default manner i mean the way the submit button is thisplayed when no styling is added to it for example the google search or i am feeling lucky buttons on,['css'] +5506,how do i redirect output to stderr in groovy i am looking for a way to redirect output in a groovy script to stderrcatchexception e println want this to go to stderr,['java'] +5513,c experts is the offset of a member variable to its class constant under these conditions given a variable foo of type fooclass and a member variable in that class named bar is the thistance between foo and foobar the same in any situation with some constraintsfooclass is a nonpod typewe know that foo will always point to an instance of fooclass and not some subtype of itwe only care about behaviour under a single compiler and a single compilation that is the value this may result in under gcc is never used in code compiled with msvc and it is never saved to be reused between compilations it is computed in the binary and used in the binary and that is itwe do not use a custom new although some instances of the class may be stackallocated and some heapallocatedthere is no explicit ctor for fooclass it relies upon the compilergenerated one and each of the fields in fooclass is either pod or defaultconstructablei cannot find a guarantee either way on this in the standard nor did i expect to but my rudimentary testing with gcc leads me to believe that it will always be the case there i also know that this guarantee is made for podtypes but let us assume this type cannot be podan updateclarification this is just for a single compilation of a single binary the calculated offsets will never leave that single execution basically i want to be able to uniquely identify the fields of a class in a static map and then be able to lookup into that map for some macrotemplateevil trickery it is merely for my own amusement and no life support machines will rely on this code,['c++'] +5527,intersection of two lines defined in rhotheta parameterization have created a c implementation of the hough transform for detecting lines in images found lines are represented using rho theta as described on wikipediathe parameter r represents the thistance between the line and the origin while i is the angle of the vector from the origin to this closest point how can i find the intersection point in x y space for two lines described using r i for reference here are my current functions for converting in and out of hough spaceget r length of a line from pole corner 00 thistance from center perpendicular to a line intersecting point xy at a given angle given the point and the angle in radiansinline float point2houghint x int y float theta returnfloatxcosfthetafloatysinfthetaget point y for a line at angle theta with a thistance from the pole of r intersecting x bad explanation inline float hough2pointint x int r float theta float y iftheta0 ycosfthetasinfthetaxfloatrsinftheta else yfloatr wth theta may 0 returnysorry in advance if this is something obvious,['c'] +5531,mapping of strings to integers what is the easiest way in java to map strings java string to positive integers java int so thatequal strings map to equal integers anddifferent strings map to different integersso similar to hashcode but different strings are required to produce different integers so in a sense it would be a hascode without the collision possibilityan obvious solution would maintain a mapping table from strings to integersand a counter to guarantee that new strings are assigned a new integer i am just wonderinghow is this problem usually solvedwould also be interesting to extend it to other objects than strings,['java'] +5536,private method naming convention is there a convention for naming the private method that i have called add here i am not a fan of the leading underscore but it is what one of my teammates suggestspublic vector addvector vector check vector for null and compare length to vectorlength return addvectorpublic static vector addvector vector1 vector vector2 check parameters for null and compare lengths vector returnvector vector1clone return returnvector addvector2private vector addvector vector for int index 0 index length index thisindex vectorindex return this,['c#'] +5538,what is the best library for java to gridclusterenable your application this is the ability to run your application on a cluster of servers with the intent to thistribute the load and also provide additional redundancyi have seen a presentation for gridgain and i was very impressed with itknow of any others,['java'] +5550,adding javascript to the onblur property of an aspnet text box control is there a way to specify some javascript to execute on the onblur event of an aspnet text box it seems to me like if i add any event handlers to the textbox object they will just cause postbacks to the server isntead of doing what i want basically i just want to be able to have the textbox be rendered in this htmlinput typetext onbluralert1234 thanks,"['asp.net', 'javascript']" +5552,streaming audio from server to iphone i am looking to stream some audio files i have on my server to an iphoneclient application i am writing some of the audio files can be rather large in size even after compression my question is is there a cocoa framework that helps me with buffering the audio so it becomes available to the user while the rest is being brought down the pipes if not can anyone point me in the right direction to learn more about the technologies required to make such a thing happen using objectiveccocoaa definitive resource on buffering and compression of audio from a serverclient infrastructure would be ideal,"['iphone', 'objective-c']" +5555,windows gadgets jquery i am creating a vista gadget and i have not been able to get jquery to work i have tried a few very simple calls like thisfunction aclickfunction boxhtmltest i know you can use javascript so it does not make much sense to me why you wouldnt be able to use a librarydoes anyone know if any examples,"['javascript', 'jquery']" +5559,missing avfoundationframework avfoundationframework is not where the documentation says it should be i have iphone sdk 22 installed never had previous sdk versions installed and i cannot find that folder under systemlibraryframeworksi did find it under developerplatformsiphoneosplatformdevelopersdksiphoneos22sdksystemlibraryframeworksfolder but if i add it from that location then the compiler cannot find the header files i tried copying the entire avfoundationframework folder to systemlibraryframework but it still cannot find the header fileshow can i use avfoundation classesthanksalex,['iphone'] +5566,javascript identify whether a property is defined and set to undefined or undefined say i have the following codefunction one oneprototypex undefinedfunction two var o new onevar t new twoox and tx will both evaluate to undefined ohasownpropertyx and thasownpropertyx will both return false the same goes for propertyisenumerable two questionsis there any way to tell that ox is defined and set to undefinedis there ever any reason to should the two be semantically equivalenta small caveat doing for propname in o loop will yield x as one of the strings while doing it in t will not so there is a difference in how they are represented internally at least in chrome,['javascript'] +5577,getting started with ironruby on rails can somebody point me to a tutorial andor getting started document to get ironruby running rails i am particularly interested in a detailed stepbystep reference not general guidelines,['ruby-on-rails'] +5587,opensocial server implementation what is the preferred method of implementing the opensocial platform i am aware of apache shindig but cannot really find any useful information on it also is it possible to use an existing solution like the railsbased lovdbyless and add opensocial features to it,['ruby-on-rails'] +5594,how to make an image center vertically horizontally inside a bigger div i have a div 200 x 200 px i want to place a 50 x 50 px image right in the middle of the div how can it be donei am able to get it centered horizontally by using textalign center for the div but vertical alignment is the issue,"['html', 'css']" +5597,stacktrace information preserving paths of original source i am using cnet for application developmentto log and debug exceptions i use the stacktracei executed my application on another machine but when errors occur it refers to the path of my development machineex dprojectsxyzcs line no 12 error message herewhy does it trace to the path on my development machine path even though i am running the application on another machine,"['c#', '.net']" +5602,how do i use the built in password resetchange views with my own templates for example i can point the url accountspasswordreset to djangocontribauthviewspassword reset with my template filename in the context but i think need to send more context detailsi need to know exactly what context to add for each of the password reset and change views,['python'] +5606,how does the addextension property work in c 20 i want to open a save file dialog have the user enter a filename and if they forget the csv extension have it tacked onit would seem that the savefiledialog addextension property would work but its does not i have even set the defaultext property to csv and still nothing gets tacked on my file gets saved just fine but sans extension so the user cannot just double click on the file and have it open in exceli have to be missing something obvious heres what i have got savefiledialog sfd new savefiledialog sfddefaultext csv sfdfilter comma separatedcsv if sfdshowdialog dialogresultok do my file saving,['c#'] +5611,cannot debug the breakpoint will not currently be hit no symbols have been loaded for this document i am getting the error in the subject line i am running vs2k8 on server 2k3sp2 i have tried deleting the pdbs cache directories verifying that debugging is set up on the specific page the interesting thing is other pages debug just fine just when i go to this one page must be a configuration issue but the page directive looks like thisprint page languagec autoeventwireuptrue codebehindmembersearchaspxcs inheritssurencyportalemployerportalmembersearch debugtrue i have also noticed that when debugging if i open the modules window almost all of the symbols show a status of symbol not loaded however after more research from the msdn article below one of the msft posts said that if it is a core net dll it will not load symbols so i am not worried about that some of the microsoft modules like systementerpricesserviceswrapperdll show an exclamation point with the message the module did not load at the default load address not sure why that dll is there as i do not know of any calls to ithere are the things i have triedbill,"['c#', '.net', 'asp.net']" +5617,can my build stipulate that my code coverage never get worse i am using hudson ci to manage a straight java web project using ant to buildi would like to mandate that the unit test coverage never be worse than the previous build thereby making sure any new code is always tested or at least the coverage is continually improvingis there a hudson plugin that works this wayedit i am currently using emma but would be willing to switch to another coverage appalso as a clarification i have seen the thresholds in some hudson plugins but that is not exactly what i am after for example what i would like is that if coverage for build 12 was 46 overall and someone checked in build 13 with 45 coverage the build would breakthe reason i want to do this is that i have a codebase with low test coverage we do not have time to go back and retroactively write unit tests but i would like to make sure that the coverage keeps getting betterupdate dan pointed out an edge case with my plan that will definitely be a problem i think i need to rethink whether this is even a good idea,['java'] +5621,authenticating against active directory with java on linux i have a simple task of authenticating against active directory using java just verifying credentials and nothing else let us say my domain is funxyztld ou path is unknown and usernamepassword is testutestp i know there is a few java libraries out there that simplify this task but i was not successful at implementing them most examples that i have found addressed ldap in general not specifically active directory issuing ldap request means sending an ou path in it which i do not have also the application that issues ldap request should be already bound to active directory in order to access it insecure since the credentials would have to be stored someplace thiscoverable i would like a test bind with test credentials if possible this would mean that account is validlast if possible is there a way to make such authentication mechanism encrypted i know that ad uses kerberos but not sure if javas ldap methods dodoes anyone has an example of working code thanks,['java'] +5623,elegant ways to support equivalence equality in python classes when writing custom classes it is often important to allow equivalence by means of the and operators in python this is made possible by implementing the eq and ne special methods respectively the easiest way i have found to do this is the following methodclass foo def init self item selfitem item def eq self other if isinstanceother self class return self dict other dict else return false def ne self other return not self eq otherdo you know of more elegant means of doing this do you know of any particular thisadvantages to using the above method of comparing dict snote a bit of clarificationwhen eq and ne are undefined youll find this behavior a foo1 b foo1 a is bfalse a bfalsethat is a b evaluates to false because it really runs a is b a test of identity ie is a the same object as bwhen eq and ne are defined youll find this behavior which is the one were after a foo1 b foo1 a is bfalse a btrue,['python'] +5624,onbeforeunload in opera i am using the code that netadictos posted to the question here all i want to do is to thisplay a warning when a user is navigating away from or closing a windowtabthe code that netadictos posted seems to work fine in ie7 ff 305 safari 321 and chrome but it does not work in opera v963 does anyone know of way of doing the same thing in operathx trev,['javascript'] +5633,cannot operator be applied to generic types in c according to the documentation of the operator in msdn for predefined value types the equality operator returns true if the values of its operands are equal false otherwise for reference types other than string returns true if its two operands refer to the same object for the string type compares the values of the strings userdefined value types can overload the operator see operator so can userdefined reference types although by default behaves as described above for both predefined and userdefined reference typesso why does this code snippet fail to compilevoid comparett x t y return x y i get the error operator cannot be applied to operands of type t and t i wonder why since as far as i understand the operator is predefined for all typesedit thanks everybody i did not notice at first that the statement was about reference types only i also thought that bitbybit comparison is provided for all value types which i now know is not correctbut in case i am using a reference type would the the operator use the predefined reference comparison or would it use the overloaded version of the operator if a type defined oneedit 2 through trial and error we learned that the operator will use the predefined reference comparison when using an unrestricted generic type actually the compiler will use the best method it can find for the restricted type argument but will look no further for example the code below will always print true even when testtestbnew b new b is calledclass a public static bool operatora x a y return true class b a public static bool operatorb x b y return false class test void test a t b where t a consolewritelinea b,['c#'] +5637,what is an httphandler in aspnet what is an httphandler in aspnet why and how is it used,['asp.net'] +5639,phpunit warning on an utilitary class i use phpunit on a integration server to run all tests and if i lauch phpunit command from the command line i receivephpunit 3218 by sebastian bergmannfitime 6 secondsthere was 1 failure1 warningphpunit framework warningno tests found in class tufailurestests 24 failures 1 incomplete 9via apache running the same test file phpunit 3218 by sebastian bergmannitime 7 secondsok but incomplete or skipped teststests 23 incomplete 9my tu class just include all tests classes with a suiteaddtestfileand which have two static functions main which run all the testsand suite which return the tests suitebut the tu class is not in the primary file given as parameter tophpunit command it is a generic class wich scan files and list all testclassi have the same problem with a class witch extends phpunit framework testcase to add specific assert wich is not included via suiteaddtestfile but only by a requirehow can i correct thisthanks in advanceregardscadric,['php'] +5640,make resizeable is there a way to make a div container resizeable with dragndrop so that the user can change the size of it using dragndropany help would really be appreciated,['html'] +5642,javascript prototypal inheritance doubt ii ibeen doing some inheritance in js in order to understand it better and i found something that confuses mei know that when you call an constructor function with the new keyword you get a new object with a reference to that functions prototypei also know that in order to make prototypal inheritance you must replace the prototype of the constructor function with an instance of the object you want to be the superclaso i did this silly example to try these conceptsfunction animalfunction doganimalprototyperun functionalertrunningdogprototype new animal dogprototypebark functionalertarfvar fido new dogfidobark okfidorun okconsolelogdogprototype its an object consolelogfidoprototype undefinedconsolelogfidoconstructorprototype dogprototype this is truefunction killerdogkillerdogprototypedeathbite functionalertarf bitefidoprototype new killerdogconsolelogfidoprototype no longer undefinedfidodeathbite but this does not workthis was done in firebugs console1 why if all new objects contain a reference to the creator functions prototype fidoprototype is undefined2 is the inheritance chain obj constructor prototype instead of obj prototype 3 is the prototype property of our object fido ever checked if so why is deathbite undefined in the last partthanks,['javascript'] +5647,why cannot i declare a friend through a typedef does anyone know why typedefs of class names do not work like class names for the friend declarationclass apublicclass b public apublic typedef a superclasstypedef a xclass cpublic friend class a ok friend class x fails friend class bsuperclass fails,['c++'] +5648,what are your concrete usecases for metaclasses in python i have a friend who likes to use metaclasses and regularly offers them as a solutioni am of the mind that you almost never need to use metaclasses why because i figure if you are doing something like that to a class you should probably be doing it to an object and a small redesignrefactor is in orderbeing able to use metaclasses has caused a lot of people in a lot of places to use classes as some kind of second rate object which just seems thisastrous to me is programming to be replaced by metaprogramming the addition of class decorators has unfortunately made it even more acceptableso please i am desperate to know your valid concrete usecases for metaclasses in python or to be enlightened as to why mutating classes is better than mutating objects sometimesi will startsometimes when using a thirdparty library it is useful to be able to mutate the class in a certain waythis is the only case i can think of and it is not concrete,['python'] +5660,is symfony a better choice than zend for a web development shop 10 because it is a full stack framework my team at work is considering to use a framework for developing web sites and applications some of the seniors are convinced we should use the zend framework because it is easier to pickandchoose the features so the framework we will be lightweight i am afraid however that they are only looking at the technical advantages that a lightweight framework will have in my opinion it is better to have a fullstack framework and i am a proponent of symfony because it will also provide us with a standard way of working without writing new documentationif we would like to use new features we would only have to read the documentation to see how it can be used instead of having to build it into our setup of zend firsti do not expect all my questions to be answered by everybody but this is what i am looking for in the answer do i have a point here have you been in a similar situation and how did you handle that do you have more arguments that i could use or could make me reconsider my own opinion the contexti work at a small shop with about 10 programmers we mostly program php we use a really simple inhouse developed framework and orm library that are practically undocumented and lack anything but the most basic features no validators no transactions no caching no authentication,['php'] +5669,restricting symbols in a linux static library i am looking for ways to restrict the number of c symbols exported to a linux static library archive i would like to limit these to only those symbols that are part of the official api for the library i already use static to declare most functions as static but this restricts them to file scope i am looking for a way to restrict to scope to the libraryi can do this for shared libraries using the techniques in ulrich dreppers how to write shared libraries but i cannot apply these techniques to static archives in his earlier good practices in library design paper he writesthe only possibility is to combine all object files which need certain internal resources into one using ld r and then restrict the symbols which are exported by this combined object file the gnu linker has options to do just thiscould anyone help me thiscover what these options might be i have had some success with strip w k prefix but this feels brutish ideally i would like a solution that will work with both gcc 3 and 4thanks,['c'] +5670,how accurate is systemdiagnosticsstopwatch how accurate is systemdiagnosticsstopwatch i am trying to do some metrics for different code paths and i need it to be exact should i be using stopwatch or is there another solution that is more accuratei have been told that sometimes stopwatch gives incorrect information,"['c#', '.net']" +5680,jquery select class inside parent div i am trying to change the alt of the image i am clicking by selecting the images class add answernote add answer shows up multiple times inside different containing divsjqueryfunction add answerjqueryadd answerclickfunction var count thisattralt count a type countshow thisparentsdivfirstadd answerattralt count this line does not seem to be working how do i select this add answer classby way of it is parent div thisparentsdivfirstadd answerattralt countanyone else have an ideai am trying having trouble decreasing the alt value on the add answer image when destroy answer is clicked jqueryfunction hide answer jquerydestroy answerclickfunction thisparentsdivfirsthide var count add answerattralt count add answerthisparentdivfirstattraltcount problem line add answerthisparentdivfirstattraltcount,"['javascript', 'jquery']" +5684,override a method at instance level is there a way in python to override a class method at instance levelfor exampleclass dog def barkself print woofboby dogbobybark woof method overridebobybark wof,['python'] +5685,how i can get the calling methods in c possible duplicatehow can i find the method that called the current methodi need a way to know the name of calling methods in cfor instance private void dosomething i need to know who is calling me method1 or method2 do something pursuant to who is calling you private void method1 dosomethingprivate void method2 dosomething,['c#'] +5688,quick java question casting an array of objects into an array of my intended class just for review can someone quickly explain what prevents this from working on compileprivate hashset datapublic dataobject getdataobjects return dataobject datatoarrayand what makes this the way that does workpublic dataobject getdataobjects return dataobject datatoarray new dataobject datasize i am not clear on the mechanism at work with casting or whatever it is that makes this so,['java'] +5691,jquery ui datepicker and datejs i want to have a datepicker where you can also just type basically i want to have the jquery ui datepicker and datejs in one i want to type tomorrow and i want it to select the right day i want to be able to type saturday and it actually getting the date right,"['javascript', 'jquery']" +5693,can i use a foreignkey in unicode return i have the following classes ingredients recipe and recipecontentclass ingredientmodelsmodel name modelscharfieldmax length30 primary keytrue qty on stock modelsintegerfield def unicode self return selfnameclass recipemodelsmodel name modelscharfieldmax length30 primary keytrue comments modelstextfieldblanktrue ingredient modelsmanytomanyfieldingredient def unicode self return selfnameclass recipecontentmodelsmodel recipe modelsforeignkeyrecipe ingredients modelsforeignkeyingredient qty used modelsintegerfieldbut for unicode in recipecontent i would like to use the recipe name to which this recipecontent belongs to is there a way to do it,['python'] +5696,url mapping in php i come from a java background and with any servletsbased technology it is trivial to map a range of urls eg reports securedo to a specified servlet now i am less familiar with php but i have not yet seen anything that does quite the same thing with php or mod php it is entirely possible that i am missing something simplehow do you do this in phpone of the reasons i want to do this is one use urls now this can sorta be done with get parameters like an md5 hash token but i am interested in url mapping as a general solution to many problemsanother big reason to use something like this is to have restful urls,['php'] +5700,what is the best way to check for memory leaks in c i am implementing a sparse matrix with linked lists and it is not fun to manually check for leaks any thoughts,['c++'] +5713,converting a development team from ftp to a versioning system i work at a small lamp development studio where the idea has been to just get the code done and go on to the next item on the listthe team works in zend studio 55 connected to the live server via ftp or sftp what they love about this is the speed of their deployment of code since its just modifying live codebut of course this is not good due to many obvious reasonsi would like to move them to a versioning system cvs svn or any other tool but the catch is i am not their senior so i need a carrot for them to start using thiswhat kind of setup would i need to build on their machine so they can code along as usualwhat i would do is create this setup on my machine and then show them i know this is kinda unusual but it is turned into a passion of mine to change their way of thinking from the usual hacking of code to structure and elegance thanksupdate for jonathan lefflers answeryesnoyes they really doquestion also the studio makes a centralized cms system that is hosted on hundreds of sites they need to modify individual sites should the sites be in the main compository or within their own one,['php'] +5724,c what does the string indexer of dictionary return what does the string indexer of dictionary return when the key does not exist in the dictionary i am new to c and i cannot seem to find a reference as good as the javadocsdo i get null or do i get an exception,['c#'] +5728,sql selecting window around particular row it is quite possible a question like this has been asked before but i cannot think of the terms to search fori am working on a photo gallery application and want to thisplay 9 thumbnails showing the context of the current photo being shown in a 3x3 grid with the current photo in the centre unless the current photo is in the first 4 photos being shown in which case if eg if the current photo is the 2nd i want to select photos 1 through 9 for example given an album containing the list of photos with ids1 5 9 12 13 18 19 20 21 22 23 25 26if the current photo is 19 i want to also view9 12 13 18 19 20 21 22 23if the current photo is 5 i want to also view1 5 9 12 13 18 19 20 21i have been thinking of something along the lines ofselect from photoswhere absid currentphoto 5order by id asc limit 25but this does not work in the case where the ids are nonsequential as in the example above or for the case where there are insufficient photos before the currentphotoany thoughtsthanksdomps please leave a comment if anything is unclear and i will clarify the question if anyone can think of a more useful title to help other people find this question in future then please comment too,"['sql', 'mysql']" +5730,change assembly version in a compiled net assembly simple question is there a way to change the assembly version of a compiled net assemblyi would actually be fine with a way to change the assembly file version,['.net'] +5738,why would you use a pfx file in net what is the pfx extension used for in netwhy does it ask for a password when the solution is being built,['.net'] +5740,whats the difference between using jquerys onclick and the onclick attribute whats the difference between the following two pieces of html apologies if there are any typos as i am typing this freehandusing jqueryscript typetextjavascript documentreadyfunction clickmeclickfunction alertclicked scripta idclickme hrefjavascriptvoid0click meanot using jquerya idclickme hrefjavascriptvoid0 onclickalertclickedclick mea,['jquery'] +5748,going where php parse url does not parsing only the domain phps parse url has a host field which includes the full host i am looking for the most reliable and least costly way to only return the domain and tldgiven the examples parse url returns wgooglecom for host parse url returns wgooglecouk for hosti am looking for only googlecom or googlecouk i have contemplated a table of valid tldssuffixes and only allowing those and one word would you do it any other way does anyone know of a precanned valid regex for this sort of thing,['php'] +5750,is it possible to get the raw param string in rails given the following url wee2what is the quickest way to get the raw param part of the url from an action iebar1wee2,"['ruby-on-rails', 'ruby']" +5752,on checkboxes is there a reason why more websites do not use it i always try to do the followinglabelinput typecheckbox some textlabelorlabel foridoffieldinput typecheckbox ididoffield some textlabelmy question is related to the label tag specifically on a checkboxmost websites i would say 40 do not use the label tagis there a reason for this is there a problem in a browser or some other issuenote incase people do not know about the label tag it has a number of advantagescheckboxes radios you can click on the text as well as the checkbox to check the checkbox as well as focus i believe blah blah blahother inputs if you click the text it will focus the input textarea text file this functionality is not as useful as checkboxes radiosnote 2 some people have mentioned that example 2 is more correct than 1 above but according to the documentation here either is correct,['html'] +5758,iphone development complex application using multiple viewsxibnib i am new to iphone development and multiple views xib or nib are really confusing me this is what i am trying to achieveview with tab bar tab 1 tab 2 tab 3tab 2 view navigation controller21 selecting table row will show a view with cell details22 add button on the navigation bar will show a series of view interfaces to get different type of information eg location information personal information etc need this to be sequential cannot use control segment for this once information is successfully gathered create a new cell in tab 2 view table save related information to a custom structure and show a completion page with 2 options add another view added item readonly viewi am confused about how to handle these multiple views both linking them together and communicating information back and forth will all these be handled by my application delegate class or i canshould use multiple delegate classes either way can you point me in the right direction possibly some sample application or tutorial explaining how to handle situation like this or more complexany help in this regard will be highly appreciatedi have seen both theelements and seismicxml examples theelements sample code gives a basic idea of how to use uitabbarcontroller and uinavigationcontroller but the example does not thiscuss passing information from child controller to parent in my case i have a uitabbarcontroller one of the tab shows a uinavigationcontroller with on the top right corner or navigation bar now will open an interface for user input and that input will be used to store the data say in sql and create a new table cell in uitableview embedded in uinavigationcontroller now the interface that will open using will take user input following a sequence of steps like main step 1 step 2 complete each step will show a separate view i am getting hard time trying to design this model or maybe i am not used to programming in cocoaiphone and i am not looking straight what other options do i have when it comes to taking user input involving 2030 fields text list date image etc can you provide some input regarding thisthanks for your help,['iphone'] +5762,best compiler warning level for cc compilers what compiler warning level do you recommend for different cc compilersgcc and g will let you get away with a lot on the default level i find the best warning level for me is wall and i always try to remove fix the code for the warnings it generates even the silly ones about using parenthesis for logical precedence rules or to say i really mean if x ywhat are your favorite levels for the different compilers such as sun cc acc hpux visual studio intelediti just wanted to point out that i do not use werror but i do understand it is utility on gccg because i usewarning this is a note to myselfin a few places in my code do all the compilers understand the warning macro,"['c++', 'c']" +5767,linq returns list or single object i have a linq to entities query like this onevar results from r in entitiesmachinerevision where rmachineidmachine pidmachine rcategory intpcategory select rusually i use the code below to check if some results are returnedif resultscount 0 return new omachinerevisionresultsfirstidmachinerevisionhowever i am getting notsupportedexception in the if conditionthe error message is unable to create a constant value of type closure type only primitive types such as int32 string and guid are supported in this contextnote that pcategory is an enum type,['c#'] +5768,how to thispose asynchronously let us say i have a class that implements the ithisposable interface something like thismyclass uses some unmanaged resources hence the thispose method from ithisposable releases those resources myclass should be used like thisusing myclass myclass new myclass myclassdosomethingnow i want to implement a method that calls dosomething asynchronously i add a new method to myclassnow from the client side myclass should be used like thisusing myclass myclass new myclass myclassasyncdosomethinghowever if i do not do anything else this could fail as the object myclass might be thisposed before dosomething is called and throw an unexpected objectthisposedexception so the call to the thispose method either implicit or explicit should be delayed until the asynchronous call to dosomething is done i think the code in the thispose method should be executed in a asynchronous way and only once all asynchronous calls are resolved i would like to know which could be the best way to accomplish thisthanksnote for the sake of simplicity i have not entered in the details of how thispose method is implemented in real life i usually follow the thispose patternupdate thank you so much for your responses i appreciate your effort as chakrit has commented i need that multiple calls to the async dosomething can be made ideally something like this should work fineusing myclass myclass new myclass myclassasyncdosomething myclassasyncdosomethingi will study the counting semaphore it seems what i am looking for it could also be a design problem if i find it convenient i will share with you some bits of the real case and what myclass really does,['c#'] +5769,how do i automatically delete tempfiles in c what are a good way to ensure that a tempfile is deleted if my application closes or crashes ideally i would like to obtain a tempfile use it and then forget about itright now i keep a list of my tempfiles and delete them with an eventhandler that triggers on applicationapplicationexitis there a better way,"['c#', '.net']" +5776,what are the major differences between rails 1x and 2x most deadtree books and web tutorials address rails 1x i am wondering if they are worth using to learn rails 2x if so what sections and concepts should i avoid and what have pretty much stayed the same,"['ruby-on-rails', 'ruby']" +5779,how can i create an instance of an arbitrary array type at runtime i am trying to deserialize an array of an type unknown at compile time at runtime i have thiscovered the type but i do not know how to create an instancesomething likeobject o activatorcreateinstancetypewhich does not work because there is no parameterless constructor array does not seem to have any constructor,['c#'] +5782,preventive vs reactive c programming i have always been one to err on the side of preventing exception conditions by never taking an action unless i am certain that there will be no errors i learned to program in c and this was the only way to really do thingsworking with c i frequently see more reactive programing try to do something and handle exceptions to me this seems like using exceptions as control statements the first few times i saw this i thismissed it as bad practice but over the past few months i have seen it all over the place and just have to wonder is this acceptedefficient or just an epidemicupdatefor a bit of clarification most of the exception handling i am seeing is things liketry open filecatch message box for file not foundor even worsetry open xml modify xml 100 lines of codecatch message for unspecified errori understand there are times when exception handling is very good to use such as database connections but i am referring to the use of exceptions in place of more traditional control i asked this because i felt like this programming style was using exceptions as a crutch instead of as a recovery method and wanted to know if this was just something i would have to learn to expect in the c world,['c#'] +5791,jquery video tutorial resources is there any place where i can find jquery video tutorials from novice level to master level the books i saw mostly assume you are very familiar with css syntax if there is any video tutorial resource for css that would be awesome too,"['jquery', 'css']" +5793,trace and debug statements im a little confused over how to use the net trace and debug classeswhy would you bother using trace instead of debugtracetraceerrortracetraceinformationtraceassertdebugwritelinedebugassertalso i understand that debug statements are ignored when your in release config mode but if trace statements apply all the time how does this affect performance,['.net'] +5795,layering images in css possible to put 2 images in same element supposing i am setting a background image for a web page in css like thisbody fontsize 625 resets 1em to 10px fontfamily verdana arial sansserifbackgroundcolor 9d5922color 0marginleft automarginright automargin 0padding 0 background urlimagesdeskgif repeat bottom leftis there any way to layer a second image on top of the deskgif within the body element itself or is the only way to create a separate class and use the z axissorry it is a simpleminded question but i have been trying to figure this out and though i have not been able to make it work i also have not found a clear slapdown of the idea anywhere online so is there a way or is this just a no can dothanks,['css'] +5797,is it possible to add to classpath dynamically in java java classpath classesjar parsertesterhow can i get the functionality in the above command programmatically like is it possible to run asjava parsertesterand get the same result i tried using urlclassloader but it modifies the classpath and does not add to itthanxthanks for the response milhous but that is what i am trying to do how is it possible to get the jar into the classpath first i tried using a custom classloader too that works but sorry that i need to run it only asjava parsertesteri would like to know if such a thing is possibleit needs to be so bcoz i have parsertesterjava and class in a separate folder i need to retain the file structure the parsertester makes use of a jar in a separate jar folder,['java'] +5804,how to find the next record after a specified one in sql i would like to use a single sql query in mysql to find the record which comes after one that i specifyie if the table hasid fruit 1 apples2 pears3 orangesi would like to be able to do a query likeselect from table where previous record has id1 order by idclearly that is not real sql syntax i am just using pseudosql to illustrate what i am trying to achievewhich would return2 pearsmy current solution is just to fetch all the records and look through them in php but that is slower than i would like is there a quicker way to do iti would be happy with something that returned two rows ie the one with the specified value and the following rowedit sorry my question was badly worded unfortunately my definition of next is not based on id but on alphabetical order of fruit name hence my example above is wrong and should return oranges as it comes alphabetically next after apples is there a way to do the comparison on strings instead of ids,['mysql'] +5810,convert xsd into sql relational tables is there something available that could help me convert a xsd into sql relational tables the xsd is rather big in my world anyway and i could save time and boring typing if something pushed me ahead rather than starting from scratchthe xsd is here if you want to have a look it is a standardizedlocalized format to exchange msds,"['c#', 'c++', 'sql']" +5833,can i use a regex in an xpath expression something like dividfood to capture div tags with idfoo123i am using net if that matters,['.net'] +5842,what is a cyclic data structure good for i was just reading through learning python by mark lutz and came across this code sample l grail lappendl lgrail it was identified as a cyclic data structureso i was wondering and here is my questionwhat is a cyclic data structure used for in real life programmingthere seems to be a little confusion which i think stems from the very brief code sample heres a few more lines using the same object l l0grail l10grail l110grail,['python'] +5852,get the id of inserted row using c i have a query to insert a row into a table which has a field called id which is populated using an auto increment on the column i need to get this value for the next bit of functionality but when i run the following it always returns 0 even though the actual value is not 0mysqlcommand comm connectcreatecommandcommcommandtext insertinvoicecommcommandtext invoicedatetostringymmdd hhmmss bookfee adminfee totalfee customerid int id converttoint32commexecutescalaraccording to my understanding this should return the id column but it just returns 0 every time any ideaseditwhen i runinsert into invoice invoice date book fee admin fee total fee customer id values 20090101 102112 50 7 57 2134last insert idi getyou have an error in your sql syntax check the manual that corresponds to your mysql server version for the right syntax to use near last insert id at line 1,"['c#', 'mysql']" +5869,can java enumerations be merged like bitwise in c is there a way in java to declare an enumeration whose values can be used together for exampleenum fileaccess read write readwrite is it possible to define readwrite as read write or anything that would yield the same result,['java'] +5878,calling a const function from a nonconst object i need to call a const function from a nonconst object see examplestruct iprocess virtual bool dosomework const 0lclass foo public iprocess virtual bool dosomework const class barpublic const iprocess getprocess const return iprocess getprocess return void dootherwork getprocessdosomework calling getprocessdosomeworkwill always results in a call toiprocess getprocessis there another way to callconst iprocess getprocess constfrom a non constant member functioni have so far usedconst castconst barthisgetprocessdosomeworkwhich does the trick but seems overly complicatededit i should mention that code is being refactored and eventually only one function will remainconst iprocess getprocess consthowever currently there is a side effect and the const call may return a different instance of iprocess some of the timeplease keep on topic,['c++'] +5881,binding a object with a sub objects as properties to a datagrid i am working with an object which has sub objects within see example below i am attempting to bind a listrootclass to the datagrid when i bind the list in the cell that contains the subobject i see the following value namespacesubobject the string values thisplay correctlyideally i would like to see the adescriptiona property of the subobject in the datacell how can i map the subobjectdescription to show in the datacellpublic class subobject int id string description public string description get return description public class rootclass string value1 subobject value2 string value3 public string value1 get return value1 public subobject value2 get return value2 public string value3 get return value3,['c#'] +5885,how best to use xpath with very large xml files in net i need to do some processing on fairly large xml files large here being potentially upwards of a gigabyte in c including performing some complex xpath queries the problem i have is that the standard way i would normally do this through the systemxml libraries likes to load the whole file into memory before it does anything with it which can cause memory problems with files of this sizei do not need to be updating the files at all just reading them and querying the data contained in them some of the xpath queries are quite involved and go across several levels of parentchild type relationship i am not sure whether this will affect the ability to use a stream reader rather than loading the data into memory as a blockone way i can see of making it work is to perform the simple analysis using a streambased approach and perhaps wrapping the xpath statements into xslt transformations that i could run across the files afterward although it seems a little convolutedalternately i know that there are some elements that the xpath queries will not run across so i guess i could break the document up into a series of smaller fragments based on it is original tree structure which could perhaps be small enough to process in memory without causing too much havoci have tried to explain my objective here so if i am barking up totally the wrong tree in terms of general approach i am sure you folks can set me right,"['c#', '.net']" +5887,what is the benefit of tableless design if you need clearing blocks everywhere i understand that the goal of moving towards div tags from table makes sense since it is more semantic however i do not understand the benefit gained if you still need a clearing block to make columnbased layouts work for example note locationinfo personalinfo both float left div classcontact div classpersonalinfo p shawn etc etc p div div classlocationinfo paddressetcaddressp div br styleclearboth clearing block divthe extraneous br tag is used strictly to describe style and is required to make the layout work does not this ruin all benefits gained from removing tables,"['html', 'css']" +5888,adding date picker to view programatically can someone illustrate or point me to a good tutorial on how to add a date picker to a view programatically ie without using the interface editor,['iphone'] +5895,when to use a float years ago i learned the hard way about precision problems with floats so i quit using them however i still run into code using floats and it make me cringe because i know some of the calculations will be inaccurateso when is it appropriate to use a floateditas info i do not think that i have come across a program where the accuracy of a number is not important but i would be interested in hearing examples,['c#'] +5899,how do i check out an svn project into eclipse as a java project i was trying to check out a project from svn using eclipse i tried using checkout as to make it into a java project from existing ant script but the project wizard requires the file to have already been downloaded is there a way to checkout the project into eclipse as a java project without having to download it elsewhere firsti am using eclipse ganymade 341 with subversive,['java'] +5901,returning from inside the scope of a using statement i have got some code that looks like thisusing dbdatacontext dc new dbdatacontextconnectionstring main main new main clienttime clienttime dcmainsinsertonsubmitmain dcsubmitchanges return mainidif i return from inside a using will the using still clean up,"['c#', '.net']" +5903,microsoft exception handling block is not it a perfect example for overengineering ever since microsoft has introduced the application blocks i have been bumping into people who use the exception handling application block i have recently had a closer look myself and would summarize the basic functionality as follows skip the following block if you already know what it doesthe exception handling application block aims to centralize and make fully configurable with config files the following key exception handling taskslogging an exceptionreplacing an exceptionwrapping an exceptionpropagating an exceptionetcthe library does that by having you modify your try catch blocks as followstry run codecatchdataaccessexception ex bool rethrow exceptionpolicyhandleexceptionex data access policy if rethrow throw based on what is specified in the appconfig for the policy name see here for docs handleexception will either throw a completely new exception replace the original exceptionwrap the original exception in a new one and throw thatswallow the exception ie do nothinghave you rethrow the original exceptionadditionally you can also configure it to do more stuff beforehand eg log the exceptionnow heres my problem i completely fail to see how it can be beneficial to make it configurable whether an exception is replaced wrapped swallowed or rethrown in my experience this decision must be made at the time you write the code because youll typically have to change the surrounding or calling code when you change the exception handling behaviorfor example your code will likely start to behave incorrectly when you reconfigure such that a particular exception thrown at a particular point is now swallowed instead of rethrown there might be code after the catch block that must not be executed when the exception occurs the same goes for all other possible changes in exception handling eg replace rethrow swallow wrapso to me the bottom line is that the exception handling block solves problems that really do not exist in practice the exception logging and notifying bit is fine but is not all the other stuff just a perfect example for overengineering,['.net'] +5905,regular expression to parse an array of json objects i am trying to parse an array of json objects into an array of strings in c i can extract the array from the json object but i cannot split the array string into an array of individual objectswhat i have is this test stringstring json itemsid0namelorem ipsumid1name lorem ipsumid2namelorem ipsumright now i am using the following regular expressions right now to split the items into individual objects for now they are 2 separate regular expressions until i fix the problem with the second oneregex arrayfinder new regexitemsitems regexoptionsexplicitcaptureregex arrayparser new regexitems regexoptionsexplicitcapturethe arrayfinder regex works the way i would expect it but for reasons i do not understand the arrayparser regex does not work at all all i want it to do is split the individual items into their own strings so i get a list like thisid0namelorem ipsumid1namelorem ipsumid2namelorem ipsum whether this list is a string array or a group or match collection does not matter but i am stumped as to how to get the objects split using the arrayparser and the json string declared above i have tried this code which i assumed would work with no luckstring json itemsid0namelorem ipsumid1name lorem ipsumid2namelorem ipsumregex arrayfinder new regexitemsitems regexoptionsexplicitcaptureregex arrayparser new regexitems regexoptionsexplicitcapturestring array arrayfindermatchjsongroupsitemsvalue at this point the array variable contains id0namelorem ipsumid1namelorem ipsumid2namelorem ipsum i would have expected one of these 2 lines to return the array of matches i am looking forcapturecollection c arrayparsermatcharraycapturesgroupcollection g arrayparsermatcharraygroupscan anybody see what it is i am doing wrong i am totally stuck on this,"['c#', '.net']" +5906,stack static and heap in c i have searched but i have not understood very well these three concepts when do i have to use dynamic allocation in the heap and whats its real advantage what are the problems of static and stack could i write an entire application without allocating variables in the heap i heard that others languages incorporate a garbage collector so you do not have to worry about memory what does the garbage collector do what could you do manipulating the memory by yourself that you could not do using this garbage collectoronce someone said to me that with this declarationint asafenew inti have a pointer to a pointer what does it mean it is different ofasafenew int,['c++'] +5908,what is the difference between swing and awt can someone please explain me whats the difference between swing and awtare there any cases where awt is more usefuladvised to use than swing or viceversa,['java'] +5919,sorting and grouping nested lists in python i have the following data structure a list of lists 4 21 1 14 20081024 154258 3 22 4 2somename 20081024 152203 5 21 3 19 20081024 154545 6 21 1 1somename 20081024 154549 7 22 3 2somename 20081024 154551i would like to be able touse a function to reorder the list so that i can group by each item in the list for example i would like to be able to group by the second column so that all the 21s are together use a function to only thisplay certain values from each inner list for example i would like to reduce this list to only contain the 4th field value of 2somename so the list would look like this 3 22 4 2somename 20081024 152203 7 22 3 2somename 20081024 154551,['python'] +5924,what is java written in what language is suns jvm written in,['java'] +5929,ruby basics what is the best online resource for learning the ruby language preferably intermediate and advanced topics,['ruby'] +5933,how to trace a nullpointerexception in a chain of getters if i get a nullpointerexception in a call like thissomeobjectgetsomethinggetsomethingelse getanotherthinggetyetanotherobjectgetvaluei get a rather useless exception text likeexception in thread main javalangnullpointerexceptionat packagesomeclasomemethodsomeclassjava12i find it rather hard to find out wich call actually returend null often finding myself refactoring the code to something like thisfoo ret1 someobjectgetsomethingbar ret2 ret1getsomethingelsebaz ret3 ret2getanotherthingbam ret4 ret3getyetanotherojectint ret5 ret4getvalueand then waiting for a more descriptive nullpointerexception that tells me which line to look forsome of you might argue that concatening getters is bad style and should be avoided anyway but my question is can i find the bug without changing the code hint i am using eclipse and i know what a debugger is but i cannot figuere out how to apply it to the problemmy conclusion on the answerssome answers told me that i should not chain getters one after another some answers showed my how to debug my code if i thisobayed that advicei have accepted an answer that taught me excactly when to chain gettersif they cannot return null chain them as long as you like no need for checking null no need to worry about nullpointerexceptions be warned that chaining still vialotes the law of demeter but i can live with thatif they may return null do not ever never ever chain them and perform a check for null values on each one that may return nullthis makes any good advice on actual debugging useless,['java'] +5934,include a text file in a c program as a char is there a way to include an entire text file as a string in a c program at compiletimesomething likefiletxtthis isa littletext filemaincinclude stdiohint mainvoid blackmagicincludefiletxt content equiv char content this isna littlentext file printfs contentobtaining a little program that prints on stdout this isa littletext fileat the moment i used an hackish python script but it is buttugly and limited to only one variable name can you tell me another way to do it,['c'] +5940,understanding iequatable if i want to compare objects and they implement the iequatable interface i have a few questionswhy do i have to override equalsobject if i have to implements equalscan i use and once i implement iequatable,['c#'] +5943,enterprise library unity vs other ioc containers whats pros and cons of using enterprise library unity vs other ioc containers windsor springnet autofac,"['c#', '.net']" +5945,how do i retrieve a django model class dynamically without having the full module path of a django model is it possible to do something likemodel user in django namespacemodelobjectsallas opposed touserobjectsalledit i am trying to make this call based on commandline input is it possible to avoid the import statement eg model djangoauthxmodelsuserwithout django returning the errorglobal name django is not defined,['python'] +5948,how do i skip items when tabbing without using tabindex is there a good way in a javascript onfocus handler to trampoline the focus to the next item in the tab order without having to manually enter the id of the item that should be nexti built an html date picker in djangojquery it is a line edit followed by a calendar icon that pops up a calendar i want to be able to tab from the line edit to the next input skipping the link for the calendar icon i mean for it to be a generalized widget so i cannot hardcode the id of whatever is next and call focus i know i could set tabindex attributes on everything but that is more manual than i would like also iirc that wouldnt prevent it from taking the focus it would just put it at the end of the tab order,['javascript'] +5950,formsauthenticationsignout does not log the user out smashed my head against this a bit too long how do i prevent a user from browsing a sites pages after they have been logged out using formsauthenticationsignout i would expect this to do itformsauthenticationsignoutsessionabandonformsauthenticationredirecttologinpagebut it does not if i type in a url directly i can still browse to the page i have not used rollyourown security in a while so i forget why this does not work,['asp.net'] +5951,combine paths in java is there a java equivalent for systemiopathcombine in cnet or any code to accomplish thisthis static method combines one or more strings into a path,['java'] +5957,orm and soa in the net world from my experience the major orm frameworks for net nhibernate linqtosql entity framework work best when they keep track of loaded objects this works fine for simple clientserver applications but when using three or more tier architecture with web services in a service oriented archtitecture this is not possible eventually by writing a lot of code to do the tracking yourself it could be done but is not orm supposed to simplify db access is the idea to use orm in service oriented architecture good at all,['.net'] +5968,c how to remove namespace information from xml elements how can i remove the xmlns namespace information from each xml element in c,"['c#', '.net']" +5971,when i run the rakedb migrate command i get an error uninitialized constant createarticles i created a model ruby scriptgenerate model article simple enuffhere is the migration file create articlesrbdef selfup create table articles do t tcolumn user id integer tcolumn title string tcolumn synopsis text limit 10 tcolumn body text limit 20 tcolumn published boolean default false tcolumn created at datetime tcolumn updated at datetime tcolumn published at datetime tcolumn category id integer enddef selfdown drop table articles endendwhen i run the rakedb migrate command i receive an error rake aborted uninitialized constant createarticles does anyone know why this error keeps happening,['ruby-on-rails'] +5976,what is the right way to initialize a nonempty static collection in c 20 i want to initialize a static collection within my c class something like thispublic class foo private static readonly icollectionstring g collection i am not sure of the right way to do this in java i might do something likeprivate static final collectionstring g collection arraysaslista bis there a similar construct in c 20 i know in later versions of cnet you can do collection initializers but migration is not an option for our system at the momentto clarify my original question i am looking for a way to succinctly declare a simple static collection such as a simple constant collection of strings the staticinitializerstyle way is also really good to know for collections of more complex objectsthanks,['c#'] +5978,visual studio on a mac my job is currently based on visual studio aspnetlooking for experiences using visual studio on a macdoes it work,"['c#', '.net']" +5979,how to programmatically select an item in a wpf treeview how is it possible to programmatically select an item in a wpf treeview the itemscontrol model seems to prevent it,['.net'] +5983,is there a good java networking library i am currently searching for a java networking library what i want to do is sending xml json or other serialized messages from a client to another client andor client to servermy first attempt was to create an pojo for each message plus a messagewriter for sending and a messagereader for receiving it plus socket and error handling which is quite a lot of error prone workwhat i am looking for is a a higher level library which abstracts from sockets furthermore it should supports something like code generation for the messagesgoogles protocol buffers looks promising but are there alternatives the emphasis is not on speed or security at the moment it is just supposed to work reliable and with a low amount of implementation time,['java'] +5989,linq sorting anonymous types how do i do sorting when generating anonymous types in linq to sqlexfrom e in linq0order by user descending select new id eid commenttext ecommenttext userid euserid user euserfirstname euserlastnametrim date stringformat0d edate,['c#'] +5992,how do you set up solution configuration specific config files i have a web service that needs different settings for different environments debug test prod whats the easiest way to setup separate config files for these different environments everything i find on the web tells me how to use configuration manager to retrieve settings but not how to find particular settings based on the current build configuration,['c#'] +5997,best method of instantiating an xmlhttprequest object what is the best method for creating an xmlhttprequest objectit should work in all capable browsers,['javascript'] +6003,how do i make tomcat stop caching my servlet responses i am learning servlets programming using apache tomcat 6 on a ubuntu 810 machine and i am running with a very annoying issue apparently related to cachingthis is what i am doing i write a servlet put it in a nice directory structure and deploy it using the tomcat web application manager it works as expected then i edit the servlet recompile and try to access it again but tomcat keeps returning the same old version reloading the application or even restarting the server does not work the only thing that works is undeploying the application then deploying it all over again i have to do this every single time i make any small change on my code it sucksi am sure there is a way around this but i could not find the answer anywhere on the web and i did search a lot i would really appreciate any help thanks,['java'] +6004,prototype and jquery peaceful coexistence i know very little about javascript but despite this i am trying to cobble something together on my wordpress blog it is not working and i do not know how to resolve it and hey that is what stackoverflow is for rightfirstly the error message iserror elementthispatchevent is not a functionsource file httpwpincludesjsprototypejsver16line 3936it happens on page load my page load handler is registered thuslyeventobservewindow load show dates as local timethe error goes away if i thisable some other plugins and this plus googling led me to conclude that it was a conflict between prototype and jquery which is used by some of the other pluginssecondly i am following the wordpress recommended practice of using wp enqeue script to add a dependency from my javascript to the prototype library as followsadd action wp print scripts depo theme add javascript function depo theme add javascript wp enqueue scriptfriendly dates javascriptfriendly datesjs arrayprototypenow i am also aware that there are some potential conflicts between jquery and prototype which are resolved using the jquery noconflicts method i have tried calling that from various places but no good i do not think this is the problem because a the noconflict function relates solely to the variable which does not seem to be the problem here and b i would expect wordpress to sort it out for me because it canlastly using the venkman debugger i have determined that the element referenced in the error message is indeed an htmldocument but also does lack a thispatchevent not sure how this could happen given it is a standard dom method,"['javascript', 'jquery']" +6005,regex named groups in java it is my understanding that the javaregex package does not have support for named groups so can anyone point me towards a thirdparty library that doesi have looked at jregex but its last release was in 2002 and it did not work for me admittedly i only tried briefly under java5,['java'] +6006,redirect console output to textbox in separate program i am developing an windows forms application that requires me to call a separate program to perform a task the program is a console application and i need to redirect standard output from the console to a textbox in my program i have no problem executing the program from my application but i do not know how to redirect the output to my application i need to capture output while the program is running using events the console program is not meant to stop running until my application stops and the text changes constantly at random intervals what i am attempting to do is simply hook output from the console to trigger an event handler which can then be used to update the textboxi am using c to code the program and using the net framework for development the original application is not a net programeditheres example code of what i am trying to do in my final app i will replace consolewriteline with code to update the textbox i tried to set a breakpoint in my event handler and it is not even reached void method var p new process var path cconsoleappexe pstartinfofilename path pstartinfouseshellexecute false poutputdatareceived p outputdatareceived pstart static void p outputdatareceivedobject sender datareceivedeventargs e consolewriteline 0 edata,"['c#', '.net']" +6009,stubbing functions in simulations i am working on an embedded c project that depends on some external hw i wish to stub out the code accessing these parts so i can simulate the system without using any hw until now i have used some macros but this forces me to change a little on my production code which i would like to avoidexamplestubhifdef stub hwdefine stub hwname stub nameelse stub hwdefine stub hwname nameendif stub hwmy hwcword stub hwclear rx tx clear my rxtx buffer on target hw test my hwcifdef stub hwword clear rx tx simulate clear rxtx buffer on target hw with this code i can turn onoff the stubbing with the preprocessor tag stub hw is there a way to acomplish this without having to change my prod code and avoiding a lot of ifdefs and i would not mix prod and test code in the same file if i can avoid it i do not care how the test code looks as long as i can keep as much as possible out of the production codeeditwould be nice if it was posible to selectrename functions without replacing the whole file like take all functions starting on nrf and giving then a new name and then inserting test nrf to nrf if it is posible,['c'] +6016,what is the best way to track memory management while testing my iphone app while developing my app i have come to realize that the majority of my app crashes have arisen from poor memory managementi understand i can print or log retain counts through nslog retain count isdmyinstance retaincountbut is not there a better less manual method possibly a visual representation of your objects and instancesanswered cheers adam jason,['iphone'] +6023,java map with values limited by keys type parameter is there a way in java to have a map where the type parameter of a value is tied to the type parameter of a key what i want to write is something like the followingpublic class foo this declaration would not compile what should it be private static mapclasst t defaultvalues these two methods are just fine public static t void setdefaultvalueclasst clazz t value defaultvaluesputclazz value public static t t getdefaultvalueclasst clazz return defaultvaluesgetclazz that is i can store any default value against a class object provided the values type matches that of the class object i do not see why this should not be allowed since i can ensure when settinggetting values that the types are correctedit thanks to cletus for his answer i do not actually need the type parameters on the map itself since i can ensure consistency in the methods which getset values even if it means using some slightly ugly casts,['java'] +6031,can i use a net dll in delphi 2007 for win32 is it possible to use a net dll in delphi 2007 for win32 i have tried to import the dll in the same way i have done for an activex component but it does not appear to work component menu import component import net assemblyis it possible and if so what are the steps,['.net'] +6033,scaffolding activerecord two columns of the same data type another basic rails questioni have a database table that needs to contain references to exactly two different records of a specific data typehypothetical example i am making a video game database i have a table for companies i want to have exactly one developer and exactly one publisher for each videogame entryi know that if i want to have one company i can just do something likescriptgenerate videogame companyreferencesbut i need to have both companies i would rather not use a join table as there can only be exactly two of the given data type and i need them to be thistinctit seems like the answer should be pretty obvious but i cannot find it anywhere on the internet,"['ruby-on-rails', 'ruby']" +6035,watin or selenium i am going to start building some automated tests of our presentation soon it seems that everyone recommends watin and selenium which do you prefer for automated testing of aspnet web forms why did that product work better for youas a side note i noticed that watin 20 has been in ctp since march 2008 is that something to be concerned about,['asp.net'] +6041,abstract classes and methods in java inheritance i have class b which inherits from class a the superclass a is abstract containing one abstract method i do not want to implement the abstract method in class b therefore i need to declare class b as abstract as well declaring class b abstract two things are working for me the programs compile and run correctly1 i do not declare any abstract methods in class b even thought the class is abstract this works i assume because the class inherits the abstract method of class a and this is enough for the class to be declared as abstract we do not need any other abstract methods directly declared in the class2 i do declare the same abstract method in class b as it is declared in class a this is some kind of overriding not in the same sense as overriding in java using the same header but providing different implementation here i just use again the same header of the methodboth things are working and i am not sure whether they are both ok and whether some of them is preferred more correct that the other are the two ways the same do they mean the same to java here i give some example classes so that what i mean is more clear for youcase 1public abstract class a public abstract string givesumpublic abstract class b extends a case 2public abstract class a public abstract string givesumpublic abstract class b extends a public abstract string givesumregards,['java'] +6043,how to right align a tag i have a couple of p tags that i want to right align does anyone know how to do this,"['html', 'css']" +6054,subdirectories within an ios application is there a way to have directories within an appat the moment if i add a file into xcode regardless of what group hierarchy it is in the file always lands in a flat filesystem within my application bundle,['iphone'] +6058,managing and debugging sql queries in ms access ms access has limited capabilities to manage raw sql queries the editor is quite bad no syntax highlighting it reformats your raw sql into a long string and you cannot insert commentsdebugging complex sql queries is a pain as well either you have to split it into many smaller queries that become difficult to manage when your schema changes or you endup with a giant query that is a nightmare to debug and updatehow do you manage your complex sql queries in ms access and how do you debug themeditat the moment i am mostly just using notepad for some syntax colouring and sql pretty printer for reformatting sensibly the raw sql from accessusing an external repository is useful but keeping there is always the risk of getting the two versions out of sync and you still have to remove comments before trying the query in access,['sql'] +6061,how to get javascript function data into a php variable i am using php and javascript my javascript code contains a function get datafunction get data var name var job return buffernow i have php code with the followingphp i0 buffer data here i need to get the value from javascript get data of buffer and assign to variable buffer data how do i assign the javascript function data into the php variable,"['php', 'javascript']" +6072,java receive a multipart http response i am writing a java client application to receive live mjpeg video from an ip camera the video is sent by the camera as an endless multipart http message where each part is a single jpeg frame i need to process each of these frames as they arrive so i am hoping there is a way to make an http request that asynchronously triggers an event as each message partvideo frame is receivedis anyone aware of any libraries that can do this all the examples i can find on google would not work because they use blocking calls that only parse the response and break it up into parts after the entire response has finished being received which obviously would not work for an endless responsei realise i could manually break up the data into parts as it arrives by searching for the message boundary but it just feels like i would be reinventing the wheel,['java'] +6085,guidelines for using brushes and pens how expensive is it to create gdi brushes and pens should i create them on an add needed basis and wrap them in a using so they are thisposed quickly or should i create a static class similar to systemdrawingbrushes class,"['c#', '.net']" +6086,how to store ipv6compatible address in a relational database how do i do thatright now ipv6 will not be used but i need to design the application to make it ipv6ready it is necessary to store ip addresses and cidr blocks also bgp nlri but this is another story in a mysql database i have alway used an int for ipv4 a tinyint for masklen but ipv6 is 128 bitwhat approach will be best for that 2xbigint char16 for binary storage char39 for text storage 8xsmallint in a dedicated tablewhat would you recommend,['mysql'] +6090,equivalent of javas concurrenthashmap in c is there anything,['c#'] +6093,python setuppy develop not updating easy installpth according to setuptools documentation setuppy develop is supposed to create the egglink file and update easy installpth when installing into sitepackages folder however in my case it is only creating the egglink file how does setuptools decide if it needs to update easy installpthsome more infoit works when i have setuptools 06c7 installed as a folder under sitepackages but when i use setuptools 06c9 installed as a zipped egg it does not work,['python'] +6095,how do i find the caller of a method using stacktrace or reflection i need to find the caller of a method is it possible using stacktrace or reflection,['java'] +6098,is endian conversion required for wchar t data in cc if a multibyte wide character wchar t value is transmitted from a bigendian system to a littleendian system or viceversa will it come out the same value on the other side or will the bytes need to be swapped,"['c++', 'c']" +6105,capture characters from standard input without waiting for enter to be pressed i can never remember how i do this because it comes up so infrequently for me but in c or c what is the best way to read a character from standard input without waiting for a newline press enteralso ideally it wouldnt echo the input character to the screen i just want to capture keystrokes with out effecting the console screen,"['c++', 'c']" +6109,in c check that filename is possibly valid not that it exists is there a method in the systemio namespace that checks the validity of a filenamefor example cfoobar would validate and would notor a little trickier xfoobar would validate is there is an x drive on the system but wouldnt otherwisei suppose i could write such a method myself but i am more interested in a builtin one,['c#'] +6110,how to access the user profile in a django template i am storing some additional peruser information using the auth profile modulewe can access the user in a django template using requestuser but how do we access fields in the profile since the profile is only accessible via a function userget profile is it really required to explicitly pass the profile into the template every time,['python'] +6111,how can i include a cdata section in a configurationelement i am using the net fx 35 and have written my own configuration classes which inherit from configurationsectionconfigurationelement currently i end up with something that looks like this in my configuration fileblahmail templates add nametemplatenbr1 subject bodyhirnthis is a testrn from address add templatesblahmaili would like to be able to express the body as a child node of template which is the add node in the example above to end up with something that looks likeblahmail templates add nametemplatenbr1 subject from address bodycdatahithis is a testbody add templatesblahmail,['c#'] +6112,php framework or template engine or something else i have a relatively simple application up and working with some basic functionality which i have built as a bit of a project i would like to now build on that and add some more complex features including loginthe code has got quite complex and it is written in plain php so all the presentation code is mixed in with the logic i have decided that before i go any further i would like to re factor it to separate this out so it is easier to maintain and add to i have been researching mvc and think that is the way i should be goingi had decided to give the zend framework a go and have spent a while trying to get to grips with it however i have found the learning curve extremely steep as i have no object oriented experienceis there another framework or option that anyone could recommend i am considering having a look at cake based on reading other posts in this forum but i would accept any guidance my requirments areeasiest to learn for non oo experienceincludes some login authentication featureshandles database interaction with mysql easilyall suggestions appreciated,['php'] +6116,canonical operator overloading is there a canonical or recommended pattern for implementing arithmetic operator overloading in c numberlike classesfrom the c faq we have an exceptionsafe assignment operator that avoids most problemsclass numberimplclass number numberimpl impl number numberoperatorconst number rhs numberimpl tmp new numberimplrhsimpl delete impl impl tmp return thisbut for other operators etc very little advice is given other than to make them behave like the operators on builtin typesis there a standard way of defining these this is what i have come up with are there pitfalls i am not seeing member operatornumber numberoperator const number rhs implvalue rhsimplvalue obviously this is more complicated return this nonmember nonfriend addition operatornumber operatornumber lhs const number rhs return lhs rhs,['c++'] +6118,structure of a c object in memory vs a struct if i have a class as follows class example class private int x int y public example class x 8 y 9 example class and a struct as followsstruct int x int y example structis the structure in memory of the example struct simmilar to that in example classfor example if i do the followingstruct example struct foo structexample class foo class example classmemcpyfoo struct foo class sizeoffoo structwill foo structx 8 and foo structy 9 ie the same values as the xy values in the foo class the reason i ask is i have a c library do not want to change it that is sharing an object with c code and i want to use a struct to represent the object coming from the c library i am only interested in the attributes of the objecti know the ideal situation would be to have example class wrap arround a common structure between the c and c code but it is not going to be easy to change the c library in use,['c++'] +6125,rails form validation conditional bypass i have a rails model that validates uniqueness of 2 form values if these 2 values are not unique the validation errors are shows and the submit button is changed to resubmit i want to allow a user to click the resubmit button and bypass the model validation i want to do something like this from the rails validation documentationvalidates uniqueness of value unless procnew user usersignup step 2 but i do not have a a value in my model that i can check forjust the params that have the resubmit valueany ideas on how to do this,"['ruby-on-rails', 'ruby']" +6134,how to return more than one value from a function in python how to return more than one variable from a function in python,['python'] +6140,php header redirect not working includeheaderphpname postnamescore postscoredept postdeptmydbprepinsert into demo idnamescoredept date values namescoredeptdate bind a value to our id hook produces select from demo table where id 23mydbbinddate date run the querymydbrunheaderlocationindexphp exitthe above code keeps giving me an issue with the redirect the error is warning cannot modify header information headers already sent by outputstarted at applicationsmamphtdocstestygubbinsootestheaderphp15 inapplicationsmamphtdocstestygubbinsootestformphp on line 16i am totally flummoxed by this does anyone know what i should be doing to make it workeditheaderphp codephpincludeclassuserphpincludeclassconnectionphpdate dateymjhtmlhead link relstylesheet hrefcstylecss typetextcss mediascreen titletesttitleheadbodydiv idpage,['php'] +6143,rounded swing jbutton using java well i have an image that i would like to put as a background to a button or something clicable the problem is that this image is round so i need to show this image without any borders etcthe jcomponent that holds this button has a custom background so the button really needs to only show the imageafter searching google i could not manage to do so i have tried all the following but with no luckbuttonsetborderpaintedfalsebuttonsetcontentareafilledfalsebuttonsetopaquetrueand after i paint the icon at the background the button paints it but holds an ugly gray background with borders etc i have also tried to use a jlabel and a jbutton and to paint an imageicon at it but if the user resizes or minimizes the window the icons thisappearhow can i fix thisi just need to paint and round an image to a jcomponent and listen for clicks at it,['java'] +6144,stringdictionary not saving as user setting i have created a user scoped setting with the type systemcollectionsspecializedstringdictionary whenever i open the local settings i can see it in the config but it is emptyi have other user settings that save correctly but this dictionary does not seem to be saving at allis there something i need to do in order to get a dictionary to save,"['c#', '.net']" +6150,is there a way to get rid of aspx placeholder files in a aspnet web deployment project i am using a web deployment project in order to precompile my aspnet 35 web project it creates a single extra dll for the code in aspx and ascx files and for every aspx file there is a placeholder aspx file empty which needs to be copied to the serveri would like to simplify the deployment process is there a way configuring the iis site and adding some sort of http handlers etc to get rid of these aspx placeholdersalso i would like to know if there is a way to get rid of the compiled files in the bin folder it would make the deployment process smootherthanks,['asp.net'] +6156,thisplay a map in a windows form app i built a winform app several months ago that schedules appointments for repair techs i would like to update the app by adding a map for the customers address on the customer form and then print that map on the report the techs take when they leave the officei have been looking around but i have not found a good solution for this yeti currently have an address for the customer what i would like to do is submit the address to one of the popular online map sites and get a minimap of the locale i can almost do this with google maps using their embedded link feature i can get the following html after adding an address to their websiteiframe width300 height300 frameborder0 scrollingno marginheight0 marginwidth0 srcampieutf8ampthampg1193presqueisledrportcharlottefl33952ampsaartsjqswtjywj7ucpvs6uu2einkrk6jlaampll2701210882087955ampspn0573506437ampz16ampoutputembediframemy first plan was to simply parse this html and insert whichever customers address was needed in place this address then show the result in a browser object on the form however if i change the address in the above iframe google gives me a your client does not have permission to get url messagei have no preference on which map service i ultimately use the important thing is that the solution cannot have an associated expenses and its usable from windows formsanyone got an ideasrecommendationsresources on how to tackle thisresultsi ended up using the control found here i find it an okay solution it is tedious to get working as the code does not work asis i am pretty stunned to find that none of the popular map apis support winforms,['c#'] +6158,detecting whether a file is locked by another process or indeed the same process this is how i do it at the moment i try to open the file with the fileshare set to none so i want exclusive acces to the file if i cannot get that then its a good bet somebody else has the file lockedthere is got to be a better and faster way any ideas try using filestream fs fileopengetlockfilename filemodeopen fileaccessreadwrite filesharenone fsclose the file is not locked catch exception the file is locked,"['c#', '.net']" +6170,using datetime in a sqlparameter for stored procedure format error i am trying to call a stored procedure on a sql 2005 server from c net 20 using datetime as a value to a sqlparameter the sql type in the stored procedure is datetimeexecuting the sproc from sql management studio works fine but everytime i call it from c i get an error about the date format when i run sql profiler to watch the calls i then copy paste the exec call to see whats going on these are my observations and notes about what i have attempted1 if i pass the datetime in directly as a datetime or converted to sqldatetime the field is surrounding by a pair of single quotes such asdate of birthn182009 80617 pm2 if i pass the datetime in as a string i only get the single quotes3 using sqldatetimetosqlstring does not result in a utc formatted datetime string even after converting to universal time4 using datetimetostring does not result in a utc formatted datetime string5 manually setting the dbtype for the sqlparameter to datetime does not change the above observationsso my questions then is how on earth do i get c to pass the properly formatted time in the sqlparameter surely this is a common use case why is it so difficult to get working i cannot seem to convert datetime to a string that is sql compatable eg 20090108t082245editre bfree the code to actually execute the sproc is as followsusing sqlcommand sproccommand new sqlcommandsprocname sproccommandconnection transactionconnection sproccommandtransaction transaction sproccommandcommandtype systemdatacommandtypestoredprocedure sproccommandparametersaddrangeparameterstoarray sproccommandexecutenonqueryto go into more detail about what i have triedparametersaddnew sqlparameterdate of birth dobparametersaddnew sqlparameterdate of birth dobtouniversaltimeparametersaddnew sqlparameterdate of birth dobtouniversaltimetostringsqlparameter param new sqlparameterdate of birth systemdatasqldbtypedatetimeparamvalue dobtouniversaltimeparametersaddparamsqlparameter param new sqlparameterdate of birth sqldbtypedatetimeparamvalue new sqldatetimedobtouniversaltimeparametersaddparamparametersaddnew sqlparameterdate of birth new sqldatetimedobtouniversaltimetosqlstringadditional editthe one i thought most likely to worksqlparameter param new sqlparameterdate of birth systemdatasqldbtypedatetimeparamvalue dobresults in this value in the exec call as seen in the sql profilerdate of birth20090108 150821813if i modify this to bedate of birth20090108t150821it works but it would not parse with pair of single quotes and it wont convert to a datetime correctly with the space between the date and time and with the milliseconds on the endupdate and successi had copypasted the code above after the request from below i trimmed things here and there to be concise turns out my problem was in the code i left out which i am sure any one of you would have spotted in an instant i had wrapped my sproc calls inside a transaction turns out that i was simply not doing transactioncommit i am ashamed to say it but there you have iti still do not know whats going on with the syntax i get back from the profiler a coworker watched with his own instance of the profiler from his computer and it returned proper syntax watching the very same executions from my profiler showed the incorrect syntax it acted as a redherring making me believe there was a query syntax problem instead of the much more simple and true answer which was that i need to commit the transaction i marked an answer below as correct and threw in some upvotes on others because they did after all answer the question even if they did not fix my specific brain lapse issue,['c#'] +6172,django on ironpython i am interested in getting an install of django running on ironpython has anyone had any success getting this running with some level of success if so can you please tell of your experiences performance suggest some tips resources and gotchas,['python'] +6177,what is the ld preload trick i came across a reference to it recently on proggit and as of now it is not explainedi suspect this might be it but i do not know for sure,['c'] +6178,how do you post data with a link i have a database which holds the residents of each house in a certain street i have a house view php web page which can thisplay an individual house and residents when given the house number using post i also have a street view web page which gives a list of houses what i want to know is if you can have links on the street view which will link to the house view and post the house number at the same time without setting up a form for eachregards,"['php', 'html']" +6181,how do i mock the python method optionparsererror which does a sysexit i am trying to unit test some code that looks like thisdef main parser optparseoptionparserdescriptionthis tool is cool progcooltool parseradd optionfoo actionstore helpthe foo option is selfexplanatory options arguments parserparse args if not optionsfoo parsererrorfoo option is required print your foo is s optionsfoo return 0if name main sysexitmainwith code that looks like thispatchoptparseoptionparserdef test main with missing p4clientsdir optionself mock optionparser setup optionparser mock mock mock optionparserreturn value optionparser mock options stub mock options stubfoo none optionparser mockparse argsreturn value options stub sentinelarguments def parser error mockmessage selfassertequalsmessage foo option is required sysexit2 optionparser mockerror parser error mock exercise verify selfassertequalssutmain 2i am using michael foords mock and nose to run the testswhen i run the test i get file usersdspitzerprogrammingpythontestoptparseerrortestssut testspy line 27 in parser error mock sysexit2systemexit 2ran 1 test in 0012sfailed errors1the problem is that optionparsererror does a sysexit2 and so main naturally relies on that but nose or unittest detects the expected sysexit2 and fails the testi can make the test pass by adding return 2 under the parsererror call in main and removing the sysexit call from parser error mock but i find it thistasteful to modify the code under test to allow a test to pass is there a better solutionupdate dfs answer works although the correct call is selfassertraisessystemexit sutmainwhich means the test passes whatever the number is in the sysexit in parser error mock is there any way to test for the exit codebtw the test is more robust if i addselfassertequalsoptionparser mockmethod calls add option foo action store help the foo option is selfexplanatory parse args at the endupdate 2 i can test for the exit code by replacing selfassertraisessystemexit sutmain withtry sutmainexcept systemexit e selfassertequalstypee typesystemexit selfassertequalsecode 2except exception e selffailunexpected exception s eelse selffailsystemexit exception expected,['python'] +6187,what is the easiest way to export data from a live google app engine application i am especially interested in solutions with source code available django independency is a plus but i am willing to hack my way through,['python'] +6188,is drupal ready for the enterprise is anyone out there using drupal for large scale business critical enterprise applicationsdoes drupals lack of database transaction support thissuade potential usersare there any other lightweight webframeworks based on dynamic languages that people are using for these types of apps what about java portals such as jbossportal or jetspeed as an alternative or a drupal j2ee hybrid architecture,['php'] +6193,how to create a guiduuid using the iphone sdk i want to be able to create a guiduuid on the iphone and ipad the intention is to be able to create keys for thistributed data that are all unique is there a way to do this with the ios sdk,"['ios', 'iphone']" +6197,javascript drag and drop grid i am looking for a script that would allow me to have a grid of draggable divs used to organize image thumbnails so when one div is dragged over another the divs would shift to create an empty spot to drop the divi know jquery has a drag and drop lib but it does not seem to allow for the functionality i need snapping to a grid and moving of surrounding divsanyone know of a script or framework that has what i needthanks,['javascript'] +6204,using powermock or how much do you let your tests affect your design i have been a fan of easymock for many years now and thanks to so i came across references to powermock and it is ability to mock constructors and static methods both of which cause problems when retrofitting tests to a legacy codebase obviously one of the huge benefits of unit testing and tdd is the way it leads to forces a much cleaner design and it seems to me that the introduction of powermock may detract from that i would see this mostly manifesting itself asgoing back to initialising collaborators rather than injecting themusing statics rather than making the method be owned by a collaboratorin addition to this something does not quite sit right with me about my code being bytecode manipulated for the test i cannot really give a concrete reason for this just that it makes me feel a little uneasy as it is just for the test and not for productionat my current gig were really pushing for the unit tests as a way for people to improve their coding practices and it feels like introducing powermock into the equation may let people skip that step somewhat and so i am loathe to start using it having said that i can really see where making use of it can cut down on the amount of refactoring that needs to be done to start testing a classi guess my question is what are peoples experiences of using powermock or any other similar library for these features would you make use of them and how much overall do you want your tests influencing your design,['java'] +6211,how can i replicate the trashing animation of mailapp in my iphone app i have put a uibarbutton of type uibarbuttonsystemitemtrash in my uitoolbar when pressed i would like to replicate the animation of mailapp the bin opens the uiview folds and flies into itis there a way to access this animation ithrough the iphone sdk presently i am using a custom made animation but there are some limits for example i cannot animate the bin itselfdo you have any suggestion code samplescheersdavide,['iphone'] +6213,select either a file or folder from the same dialog in net is there an easy way to select either a file or a folder from the same dialogin many apps i create i allow for both files or folders as inputuntil now i always end up creating a switch to toggle between file or folder selection dialogs or stick with draganddrop functionality only since this seems such a basic thing i would imagine this has been created before but googling does not result in much information so it looks like i would need to start from scratch and create a custom selection dialog but i rather not introduce any problems by reinventing the wheel for such a trivial taskanybody any tips or existing solutionsto keep the ui consistent it would be nice if it is possible to extend the openfiledialog or the folderbrowserdialog,"['c#', '.net']" +6216,assigning cout to a variable name in ansi c how can i assign the cout stream to a variable name what i want to do is if the user has specified an output file name i send output there otherwise send it to the screen so something likeofstream outfileif outfilerequested outfileopenfootxt iosoutelse outfile cout will not compile because outfile does not have an assignment operatoroutfile whatever endli tried doing this as a macro function as welldefine output outfilerequestedoutfilecoutoutput whatever endlbut that gave me a compiler error as welli supposed i could either use an ifthen block for every output but i would like to avoid that if i could any ideas,['c++'] +6231,using xmlserializer with private and public const properties whats the simplest way to get xmlserializer to also serialize private and public const properties of a class or struct right not all it will output for me is things that are only public making it private or adding const is causing the values to not be serialized,['c#'] +6232,array posting in php i am trying to post an array full of checkboxes and to open it in the next pageit only gives me the last result anyone know why or how to fix itform nameinput actioncreateeventphp methodpostevent title input typetext nameeventtitle size20brevent description input typetext namedescription size20brplease select the days that you are free to arrange this meetingbrmondayinput typecheckbox nameday valuemonday br tuesdayinput typecheckbox nameday valuetuesday br wednesdayinput typecheckbox nameday valuewednesday br thursdayinput typecheckbox nameday valuethursday br fridayinput typecheckbox nameday valuefriday br saturdayinput typecheckbox nameday valuesaturday br sundayinput typecheckbox nameday valuesunday br br input typesubmit valuesubmitand no matter how many you select it only gives a single result on the next pageday sizeof postdayonly ever gives 1 answer and when i get them to the next page i will want to be able to select them separatelythanks,['php'] +6233,naming conventions for abstract classes i thistinctly remember that at one time the guideline pushed by microsoft was to add the base suffix to an abstract class to obviate the fact that it was abstract hence we have classes like systemwebhostingvirtualfilebase systemconfigurationconfigurationvalidatorbase systemwindowsformsbuttonbase and of course systemcollectionscollectionbasebut i have noticed that of late a lot of abstract classes in the framework do not seem to be following this convention for example the following classes are all abstract but do not follow this conventionsystemdirectoryservicesactivedirectorydirectoryserversystemconfigurationconfigurationelementsystemdrawingbrushsystemwindowsformscommondialogand that is just what i could drum up in a few seconds so i went looking up what the official documentation had to say to make sure i was not crazy i found the names of classes structs and interfaces on msdn at design guidelines for developing class libraries oddly i can find no mention of the guideline to add base to the end of an abstract clas name and the guidelines are no longer available for version 11 of the frameworkso am i losing it did this guideline ever exist has it just been abandoned without a word have i been creating long class names all by myself for the last two years for nothing someone throw me a bone hereupdatei am not crazy the guideline existed krzysztof cwalina gripes about it in 2005,['.net'] +6239,why is the with construct not included in c when it is really cool in vbnet i am c developer i really love the curly brace because i came from c c and java background however i also like the other programming languages of the net family such as vbnet switching back and forth between c and vbnet is not really that big of deal if you have been programming for a while in net that is very common approach in the company where i work as c guy i really like the xml literal and with keywords provided by the vbnet compiler i wish microsoft had included those features in c also i am just curious what other developer has to say about it,['c#'] +6242,render pdf in itextsharp from html with css any idea how to render a pdf using itextsharp so that it renders the page using css the css can either be embedded in the html or passed in separately i do not really care just want it to work specific code examples would be greatly appreciatedalso i would really like to stick with itextsharp though if you do have suggestions for something else it is got to be free open source and have a license that permits using it in commercial software,"['c#', 'html']" +6246,open source html to pdf renderer with full css support i asked about getting itextsharp to render a pdf from html and a css sheet before here but it seems like that may not be possible so i guess i will have to try something elseis there an open source netc library out there that can take html and css as input and render it correctly i must reiterate the library must be free and preferably something with a fairly liberal license i am working with basically no budget here,"['c#', 'html', 'css']" +6248,prevent mutually recursive execution of triggers suppose you have the tables presentations and events when a presentation is saved and contains basic event information such as location and date an event will be created automatically using a trigger i am afraid it is impossible for technical reasons to simply keep the data at one place and use a view in addition when changing this information later on in the presentation the trigger will copy the updates over to the event as well like socreate trigger update presentationson presentationsafter updateasbegin update events set eventsdate presentationsdate eventslocation presentationslocation from presentations inner join events on presentationseventid eventsid where presentationsid in select id from insertedendnow the customer wants it so that if a user ever changes the information in the event it should go back to the presentation as well for obvious reasons i cannot do the reversecreate trigger update eventson eventsafter updateasbegin update presentations set presentationsdate eventsdate presentationslocation eventslocation from events inner join presentations on eventspresentationid presentationsid where eventsid in select id from insertedendafter all this would cause each trigger to fire after each other what i could do is add a column last edit by to both tables containing a user id if filled by the trigger with a special invalid id say by making all user ids of actual persons positive but user ids of scripts negative i could use that as an exit condition and last edit by 0this might work but what i would like to do is indicate to the sql server that within a transaction a trigger should only fire once is there a way to check this or perhaps to check that a table has already been affected by a triggeranswer thanks to steve robbinsjust wrap the potentially nested update statements in an if condition checking for trigger nestlevel for examplecreate trigger update presentationson presentationsafter updateasbegin if trigger nestlevel 2 update events set eventsdate presentationsdate eventslocation presentationslocation from presentations inner join events on presentationseventid eventsid where presentationsid in select id from insertedendnote that trigger nestlevel appears to be 1based not 0based if you want each of the two triggers to execute once but not more often just check for trigger nestlevel 3 in both triggers,['sql'] +6252,is there an open source c visual debugger for windows is there an open source c visual debugger for windowsi have heard about the visual c express free edition but does it have a visual debuggerthanks,['c'] +6259,window border width and height in win32 how do i get it getsystemmetrics sm cybordercomes back with 1 and i know the title bar is taller than one pixel i also tried rect r rleft rtop 0 rright rbottom 400 adjustwindowrect r ws overlapped false bdw uwordrright rleft 400 bdh uwordrbottom rtop 400but border wh came back as 0in my wm size handler i need to make sure the windows height changes insteps so for example a whole new line of text could fit in the windowwith no junky partial line space at the bottombut movewindow needs the dimensions with the border space added insomebody must have done this beforethanks for any help,['c++'] +6262,how to render decoded html in a ie a in gridview cell i am binding a gridview to an linq query some of the fields in the objects created by the linq statement are strings and need to contain new linesapparently gridview htmlencodes everything in each cell so i cannot insert a br to create a new line within a cellhow do i tell gridview not to html encode the contents of cellsmaybe i should use a different control instead,"['c#', 'asp.net']" +6263,is possible send a array in objc for a variable arguments function in python it is easy to build a dictionary or array and pass it unpacked to a function with variable parametersi have this bool executeupdatensstringsql and the manual way is thisdb executeupdateinsert into test a b c d e values hi look i put in a and i am not escaping it nsstring stringwithformatnumber d i nsnumber numberwithinti nsdate date nsnumber numberwithfloat22fbut i cannot hardcode the parameters i am calling i wantnsmutablearray values nsmutablearray arrayfor nsstring fieldname in props values addobject valuedb executeupdateinsert into test a b c d e values values,['objective-c'] +6279,writing custom ienumerator with iterators how can i write a custom ienumeratort implementation which needs to maintain some state and still get to use iterator blocks to simplify it the best i can come up with is something like thispublic class myenumeratort ienumeratort private ienumeratort enumerator public int position get private set or some other custom properties public myenumerator position 0 enumerator makeenumerator private ienumeratort makeenumerator yield return something depending on position public bool movenext bool res enumeratormovenext if res position return res delegate reset and current to enumerator as wellpublic class mycollectiont ienumerablet ienumeratort ienumerabletgetenumerator return getenumerator public myenumeratort getenumerator return new myenumeratort,['c#'] +6283,hyperlinks within about text for iphone application i am on the final stretch of my first simple iphone application i am building an about view with creditsinfoetci am failing on the simplest thing how can i embed hyperlinks into the text i am current using a uiview with a uilabel for the texti have looked on here and the sample apps but not got anywhere should i use a uiwebview thx,['iphone'] +6285,recommendations of a high volume log event viewer in a java enviroment i am in a situation where i would like to accept a lot of log events controlled by me notably the logging agent i am preparing for slf4j and then analyze them interactivelyi am not as such interested in a facility that presents formatted log files but one that can accept log events as objects and allow me to sort and thisplay on eg threads and timelines etcchainsaw could maybe be an option but is currently not compatible with logback which i use for technical reasonsis there any project with stand alone viewers or embedded in an ide which would be suitable for this kind of log handling i am aware that i am approaching what might be suitable for a profiler so if there is a profiler projekt suitable for this kind of data acquisition and thisplay where i can feed the event pipe i would like to hear about itthanks for all feedbackupdate 20090319 i have found that there is not a log viewer which allows me to see what i would like a visual thisplay of events with coordinates determined by day and time etc so i have decided to create a very terse xml format derived from the log4j xmllayout adapted to be as readable as possible while still being valid xmlsnippets and then use the microsoft logparser to extract the information i need for postprocessing in other tools,['java'] +6291,is wpf production ready i am wondering if there are people out there with experience of wpf application development and maybe more interesting running wpf in productionis it mature enough to use in larger projects what are the obvious pitfalls any best practices databinding in wpf seems pretty nifty but does it work in real projectsthanks in advance,['.net'] +6295,rails how do you access restful helpers i am trying to work through this guide to rails routing but i got stuck in section 33creating a restful route will also make available a pile of helpers within your applicationand then they list some helpers like photos url photos path etcmy questionswhere can i find the complete list of helpers that is made availableis there a way to call the helpers in the console i created an app then opened up the console with scriptconsole i tried to call one of the helpers on the console like this entries urlbut gotnameerror undefined local variable or method entries url for object0x349a4 from irb8,"['ruby-on-rails', 'ruby']" +6298,array of structs and new delete i have a struct like thisclass items private struct item unsigned int a b c item itemsmax itemssay i wanted to delete an item like soitems5 nulland i created a new item on that same spot lateritems5 new itemwould i still need to call delete to clean this up or would not this be needed since bounds of array items are known before compiling is setting that pointer to null valid or should i be calling delete there,['c++'] +6299,how to reverse a unicode string it was hinted in a comment to an answer to this question that php can not reverse unicode strings as for unicode it works in php because most apps process it as binary yes php is 8bit clean try the equivalent of this in php perl mutf8 e print scalar reversea you will get garbage not a a jrockwayand unfortunately it is correct that phps unicode support atm is at best lacking this will hopefully change drastically with php6 phps multibyte functions does provide the basic functionality you need to deal with unicode but it is inconsistent and does lack a lot of functions one of these is a function to reverse a stringi of course wanted to reverse this text for no other reason then to figure out if it was possible and i made a function to accomplish this enormous complex task of reversing this unicode text so you can relax a bit longer until php6test codeenc utf8text adefaultenc mb internal encodingecho showing results with encoding defaultencnnrevnormal strrevtextrevint mb strrevtextrevenc mb strrevtext encecho original text is text necho normal strrev output revnormal necho mb strrev without encoding output revintnecho mb strrev with encoding enc output revencnif mb internal encodingenc echo nsetting internal encoding to enc from defaultencnn revnormal strrevtext revint mb strrevtext revenc mb strrevtext enc echo original text is text n echo normal strrev output revnormal n echo mb strrev without encoding output revintn echo mb strrev with encoding enc output revencn else echo ncould not set internal encoding to encn,['php'] +6300,extending xhtml i am playing around with writing a jquery plugin that uses an attribute to define form validation behavior yes i am aware there is already a validation plugin this is as much a learning exercise as something i will be using ideally i would like to have something like thisexample 1 inputinput idname typetext vonvalidatereturn thisvaluelength 0 example 2 wrapperdiv vonvalidatereturn thisfindvaluelength 0 input idfield1 typetext input idfield2 typetext input idfield3 typetext divexample 3 predefinedinput idname typetext vvalidationnot empty the goal here is to allow my jquery code to figure out which elements need to be validated this is already done and still have the markup be valid xhtml which is what i am having a problem with i am fairly sure this will require a combination of both dtd and xml schema but i am not really quite sure how exactly to executebased on this article i have created the following dtdentity xhtml1formvalidation1 public w3cdtd xhtml 11 formvalidation 10en xhtml1formvalidation1entity inlspecialextra divqname entity xhmtlmodelmod system formvalidationmodel1mod entity xhtml11dtd public w3cdtd xhtml 11en xhtml11dtdand here is formvalidationmodel1attlist divqname onvalidation cdata implied xhtml1formvalidation1xmlnsextraattribi have never done dtd before so i am not even really exactly sure what i am doing when i run my page through the w3 xhtml validator i get 80 errors because it is getting duplicate definitions of all the xhtml elements am i at least on the right track any suggestionsediti removed this section from my custom dtd because it turned out that it was actually selfreferencing and the code i got the template from was really for combining two dtds into one not appending specific items to oneentity xhtml1formvalidation1 public w3cdtd xhtml 11 formvalidation 10en xhtml1formvalidation1i also removed this because it was not validating and did not seem to be doing anythingentity inlspecialextra divqname additionally i decided that since i am only adding a handful of additional items the separate files model recommended by w3 does not really seem that helpful so i have put everything into the dtd file the content of which is now thisattlist div onvalidate cdata impliedentity xhtml11dtd public w3cdtd xhtml 11en xhtml11dtdso now i am not getting any dtdrelated validation errors but the onvalidate attribute still is not validupdate i have ditched the dtd and added a schema using vonvalidate appears to validate in visual studio but the w3c service still does not like itheres a page where i am using it so you can look at the sourceand heres the link to the w3c validation resultcharsetdetectautomaticallydoctypeinlinegroup0is this about as close as i will be able to get with this or am i still doing something wrong,['jquery'] +6301,in linq to sql how do you pass parts of a linq query into a function is it possible to pass parts of a linq query into a function i want create a common interface for my dal that always uses the same query interface for example listt getjoin j where w select s return currentdatacontexttjoinjwherewselectstolist is this sort of thing possible i am thinking it would be done with expression trees but i have not been able to find examples of it,['c#'] +6302,for python support what company would be best to get hosting from i want to be able to run wsgi apps but my current hosting restricts it does anybody know a company that can accommodate my requirements,['python'] +6305,cleaning up a database in django before every test method by default when django runs against sqlite backend it creates a new in memory database for a test that means for every class that derives from unittesttestcase i get a new database can this be changed so that it is cleared before every test method is runexample i am testing a manager class that provides additional abstraction on top of django persistent objects the code looks moreless like thatclass testformanagerunittesttestcase def testaddingblahself manager manager selfassertequalsmanagergetblahs 0 manageraddblah selfassertequalsmanagergetblahs 1 def testaddingblahindifferentwayself manager manager selfassertequalsmanagergetblahs 0 manageraddblahindifferentway selfassertequalsmanagergetblahs 1now the first assertion of second test fails because the state of the database is preserved between test calls and there already is an instance of blah in the database,['python'] +6307,how do i make a field in mysql autoincrementing in phpmyadmin i created a field in my table and set it as the index but i cannot get it to increase on it s own when a new item is added how do i do make it do this through phpmyadmin,"['php', 'mysql']" +6310,is a string property itself threadsafe strings in c are immutable and threadsafe but what when you have a public getter property like thispublic string sampleproperty get private setif we have two threads and the first is calling get and the second is calling set at the same time what will happenimho the set must made a lock to be threadsafe like thisprivate string samplefieldprivate object threadsafer new objectpublic string sampleproperty get return thissamplefield private set lockthreadsafer samplefield value,['c#'] +6311,printing from web applications how do you generate paperprints from a web applicationspecifically i am thinking about more complex paper documents like diplomas invoices and contracts variable number of pages with frames tables logos and headersfooterstoday i use custom forms and css for certain things and itextsharp for others i work with aspnet and mssql but i think both approaches are timeconsuming and hard to make consistent across different documentsis there a better way to go about it,['asp.net'] +6312,transaction rollback and web services given an example of calling two web services methods from a session bean what if an exception is thrown between the calls to two methods in the case of not calling the web services the transaction will rollback and no harm done however the web service will not rollback of course even with a single web service there is a problem while this is a generic question i am interested in solutions having to do with ejb session beansan easy and customized answer would be to add a special rollback method to the web service for each real functionality method what i am asking for is some standardized way to do so,['java'] +6313,how to determine installed iis version what would the preferred way of programmatically determining which the currently installed version of microsoft internet information services iis isi know that it can be found by looking at the majorversion key in hkey local machinesystemcurrentcontrolsetservicesw3svcparameters would this be the recommended way of doing it or is there any safer or more beautiful method available to a net developer,['.net'] +6322,how are css frameworks used for some reason it never dawned on me that there could be frameworks for css i have been working on my own personal site and i just really hate designing with css i think more then a few programmers might agree with me anyways i understand the benefits of a framework for a language such as java php insert language i downloaded a couple different css frameworks and couldnt really figure out how to use them i guess i might be expecting an api or something which obviously doesnt make sense given the lack of logic in css has anyone here used and would reccomend a css framework is it overkill for a relatively simple layoutplease do not post links to other sites i know how to use google i would rather hear the opinions and insights of the community thanks,['css'] +6323,activemq issue with queue lookup i have set up a queue by configuring it in activemqxml activemq version 520 as described in the documentationdestinations queue physicalnamefoobar queue physicalnamedummy destinationsi am trying to access it from java on the same host with the following codehashtable properties new hashtablepropertiesputcontextinitial context factory orgapacheactivemqjndiactivemqinitialcontextfactorypropertiesputcontextprovider url tcplocalhost61616context new initialcontextpropertiesfactory connectionfactory contextlookupconnectionfactoryconnection factorycreateconnectionsession connectioncreatesessionfalse sessionauto acknowledgequeuename dummy which can be either foobar or dummydest destination contextlookupqueuenamei am receveing the following error although the queue is visible in jconsole tree orgapacheactivemq queuejavaxnamingnamenotfoundexception dummyplease tell me what i am doing wrong many many thanks,['java'] +6325,are there good java libraries that facilitate building commandline applications i need to write a simple commandline application in java it would be nice to use a library that takes care of parsing commands and takes care of things like flags and optionalmandatory parametersupdatesomething that has builtin tab completion would be particularly great,['java'] +6328,find java classes implementing an interface some time ago i came across a piece of code that used some piece of standard java functionality to locate the classes that implemented a given interface i know the functions were hidden in some nonlogical place but they could be used for other classes as the package name implied back then i did not need it so i forgot about it but now i do and i cannot seem to find the functions again where can these functions be foundedit i am not looking for any ide functions or anything but rather something that can be executed within the java application,['java'] +6331,does java have native support for events similar to that of c i am a bit confused from what i have heard java does not do eventsbut i know that it does gui eventsam i missing something does java have an event handling mechanismi am aware that i can implement a publisher subscriber pattern but i am looking for native support within javai seem to remember something about java adding events in either java 5 or 6 but i cannot remember where i heard this and i may be making it upbasically i am wrapping a device in a java class the device throws events and i am looking for the most logical way of exposing this i come mostly from a net background and i am looking for something like the events in net cany help would be appreciated,['java'] +6332,javascript accessing private member variables from prototypedefined functions is there any way to make private variables those defined in the constructor available to prototypedefined methodstestclass function var privatefield hello thisnonprotohello functionalertprivatefieldtestclassprototypeprototypehello functionalertprivatefieldthis workstnonprotohellobut this does nottprototypehelloi am used to defining my methods inside the constructor but am moving away from that for a couple reasonsthanks sktrdiethat works it would be nice not to have to create the thisaccessprivatefield if my hello function is defined inside the constructor privatefield is in the scope chain of the function so i can treat privatefield as i would a private field in java it is a little more cumbersome to set up accessors thisaccessprivatefield and then privatefield is not really private any morei know javascript is not java but i like java,['javascript'] +6333,python is there a way to determine the encoding of text file i know there is something buried in here but i was just wondering if there is an actual way built into python to determine text file encodingthanks for your help edit as a side question it can be ignored if you want but why is the type of encoding not put into the file so it could be detected easier,['python'] +6335,are constant c expressions evaluated at compile time or at runtime if i write a define that performs an operation using other preprocessor constants is the final value computed each time the macro appears at runtime does this depend on optimizations in the compiler or is it covered under a standardexampledefine external clock frequency 32768define timer 1 s external clock frequencydefine timer 100 ms timerb 1 s 10will the operation 32768 10 occur at runtime every time i use the timer 100 ms macroi would like to avoid the followingdefine external clock frequency 32768define timer 1 s external clock frequencydefine timer 100 ms 3276summarya compiler is required to be able to evaluate constant integral expressions because they are necessary for calculating things like array sizes at compile time however the standard only says they can not must do so therefore only a braindead compiler would not evaluate a constant integral expressions at compile time but a simple check of the assembly output for an unconventional compiler would verify each case,['c'] +6337,linux c debugger i am looking for the perfect linux c debugger i do not expect success but the search should be informativei am a quite capable gdb user but stl and boost easily crush my debugging skills it not that i cannot get into the internals of a data structure it is that it takes so long i usually find another way when in doubt print it out the macro language for gdb is weird and not very adaptive just look at the code for the stanford gdb utils to print out stl structures in short i am unhappy with what i have goti recently stumbled upon zero bugs it looks like a silver bullet what do the current zero bugs users think of ithas anyone found other good solutions to the linux c debugger problem,['c++'] +6339,uriabsolutepath messes up path with spaces in a winapp i am simply trying to get the absolute path from a uri objecturi myuri new urimypath mypath is a stringsomewhere else in the codestring path myuriabsolutepaththis works fine if no spaces in my original path if spaces are in there the string gets mangled for example documents and settings becomes documents20and20setting etcany help would be appreciatededitlocalpath instead of absolutepath did the trick,['c#'] +6343,local html file ajax call and jquery woes i am working on a offline version of a website using jquery and some xml files i am running in to a problem in jquery when i do a ajax call on a xml file jquery throws a errorwhen i look at the error i can tell its loading the xml file because its in the errors responcetext property it seams to work just fine in firefoxthis is how my call looksajax type get url modules moduleid modulecontentxml datatype xml success functionx xml x processxml error functionx alertxresponcetext when i run this on a web server it works just fine its only when i run it from the file its self when i have this problemany ideas on how i can make this work in ieedit i found the answer to my problem here,['jquery'] +6344,is switching appconfig at runtime possible is there a way at runtime to switch out an applications appconfig currentconfig to newconfig file for file i have a backuprestore process which needs to replace its own applicationexeconfig file i have seen this post but it does not answer how to do this at runtime,['c#'] +6354,can someone explain this template code that gives me the size of an array templatetypename t size t nsize t array sizeconst t n return nthe part that i do not get is the parameters for this template function what happens with the array when i pass it through there that gives n as the number of elements in the array,['c++'] +6355,ironpython webframework there seem to be many excellent web frameworks for python has anyone used any of these pylons web2py django with ironpython,['python'] +6359,friend scope in c if i have three classes a b c a and b are friends bidirectionally also b and c are friends bidirectionally a has a pointer to b and b has a pointer to c why cannot a access cs private data through the pointerjust to clarify this is a pure theoretical c language question not a design advice question,['c++'] +6360,exclude a column from being sorted using jquery tablesorter i am looking for a way to exclude a single column from being sorted using jquerys tablesorter plugin specifically i have a fairly large table and would like to keep a row number column fixed so that it is easy to see what position in the table a particular row is after sortingfor example name1 papaya2 apple3 strawberry4 bananawhen sorted on the name column should result in name1 apple2 banana3 papaya4 strawberrythanks,['jquery'] +6362,type to use to represent a byte in ansi c8990 c is there a standardscomplaint method to represent a byte in ansi c8990 c i know that most often a char happens to be a byte but my understanding is that this is not guaranteed to be the case also there is stdinth in the c99 standard but what was used before c99i am curious about both 8 bits specifically and a byte sizeofx 1,['c'] +6363,java synchronized static methods lock on object or class the java tutorials say it is not possible for two invocations of synchronized methods on the same object to interleave what does this mean for a static method since a static method has no associated object will the synchronized keyword lock on the class instead of the object,['java'] +6367,the level of a treeview in wpf in a winforms application the level of a treeview is given by nodelevelwhat is the corresponding one in wpfthanks,['c#'] +6370,monitor a proces network usage is there a way in c or cc win32 to monitor a certain proces network usage without that application being built by you obviously i would like to monitor just 1 process for like an hour or so then return the bytes used by only that process such as limewire for exampleis it possible i know netstat e on windows will tell you total bytes sentreceived but that is for all processesedit if i cannot return just one processes usage how can i get the bytes sentreceived by the entire system as netstat thisplays except i just want the integersegnetstat e received sentbytes 21568926 1133174989unicast packets 3016480 2711006nonunicast packets 3122 1100thiscards 0 0errors 0 0unknown protocols 0i just want to get 2 variables like rec 21568926 and sent 1133174989,['c#'] +6381,how do i write a query that outputs the row number as a column how do i write a query that outputs the row number as a column this is db2 sql on an iserieseg if i havetable beatlesjohnpaulgeorgeringoand i want to write a statement without writing a procedure or view if possible that gives me1 john2 paul3 george4 ringo,['sql'] +6389,is it alright to add custom html attributes i have a site i am working on where i want to mark if a row of data has been changedif something has been changed in that row i would mark it with a custom attributelike sotr td isdirtytrue row data tdtrthis works great with jquery and it does not add to much code to my pagebut is this really the correct way of doing something like this and what are the downsidesi guess another way of doing this would be like this but it seems like over killtr td row data input idisdirty typehidden valuetrue tdtr,"['jquery', 'html', 'css']" +6398,best way to programmatically modify excel spreadsheets i am looking for a library that will allow me to programatically modify excel files to add data to certain cells my current idea is to use named ranges to determine where to insert the new data essentially a range of 1x1 then update the named ranges to point at the data the existing application this is going to integrate with is written entirely in c so i am ideally looking for a c solution hence why this thread is of limited usefulness if all else fails i will go with a net solution if there is some way of linking it against our c appan ideal solution would be open source but none of the ones i have seen so far myxls and xlsstream seem up to the challenge i like the looks of asposecells but it is for net or java not c and costs money i need to support all excel formats from 97 through the present including the xlsx and xlsb formats ideally it would also support formats such as openoffice and for output pdf and htmlsome usecases i need to supportreading and modifying any cell in the spreadsheet including formulascreating reading modifying named ranges the ranges themselves not just the cellscopying formatting from a cell to a bunch of others including conditional formatting well use one cell as a template for all the others we fill in with dataany help you can give me finding an appropriate library would be great i would also like to hear some testimonials about the various suggestions including the ones in my post so i can make more informed decisions whats easy to use bugfree cheap etc,['c++'] +6399,how do you create a javascript date object with a set timezone without using a string representation i have a web page with three dropdowns for day month and year if i use the javascript date constructor that takes numbers then i get a date object for my current timezonenew datexiyear ximonth xidategive the correct date but it thinks that date is gmt0100 due to daylight savings timethe problem here is that i then give this date to an ajax method and when the date is deserialised on the server it has been converted to gmt and so lost an hour which moves the day back by onenow i could just pass the day month and year individually into the ajax method but it seems that there ought to be a better waythe accepted answer pointed me in the right direction however just using setutchours by itself changedapr 5th 0 gmt0100 toapr 4th 2300 gmt0100i then also had to set the utc date month and year to end up withapr 5th 0100 gmt0100which is what i wanted,['javascript'] +6410,detect version of java using javascript is there a reliable way of detecting what version of java is installed on the clients machine using javascript,"['java', 'javascript']" +6412,implementing a lazyproperty class is this a good idea i often find myself writing a property that is evaluated lazily something likeif backingfield null backingfield someoperationreturn backingfieldit is not much code but it does get repeated a lot if you have a lot of propertiesi am thinking about defining a class called lazypropertypublic class lazypropertyt private readonly funct getter public lazypropertyfunct getter thisgetter getter private bool loaded false private t propertyvalue public t value get if loaded propertyvalue getter loaded true return propertyvalue public static implicit operator tlazypropertyt rhs return rhsvalue this would enable me to initialize a field like thisfirst new lazypropertyheavyobject new heavyobject myproperty value and then the body of the property could be reduced topublic heavyobject first get return first this would be used by most of the company since it would go into a common class library shared by most of our productsi cannot decide whether this is a good idea or not i think the solutions has some pros like less codeprettier codeon the downside it would be harder to look at the code and determine exactly what happens especially if a developer is not familiar with the lazyproperty class what do you think is this a good idea or should i abandon it also is the implicit operator a good idea or would you prefer to use the value property explicitly if you should be using this class opinions and suggestions are welcomed,"['c#', '.net']" +6413,unicode vs strdecode for a utf8 encoded byte string python 2x is there any reason to prefer unicodesomestring utf8 as opposed to somestringdecodeutf8my only thought is that decode is a bound method so python may be able to resolve it more efficiently but correct me if i am wrong,['python'] +6425,using with statement for csv files in python is it possible to use the with statement directly with csv files it seems natural to be able to do something like thisimport csvwith csvreaderopenmyfilecsv as reader do things with readerbut csvreader does not provide the enter and exit methods so this does not work i can however do it in two stepsimport csvwith openmyfilecsv as f reader csvreaderf do things with readeris this second way the ideal way to do it why wouldnt they make csvreader directly compatible with the with statement,['python'] +6426,javabeans alternatives i hate the javabeans pattern with a passion that burns like the fire of a thousand suns whyverbose it is 2009 i should not have to write 7 loc for a property if they have event listeners then hold on to your hatno typesafe references there is no typesafe way to reference a property the whole point of java is that it is type safe and its most popular pattern is not at all typesafewhat i would like is something likeclass customer public propertystring name new propertyi am a web developer mostly so it needs jpa and wicket supporthelp me off the javabean train,['java'] +6430,about memory management in java and c well i have been given an assignment to basically figure out how memory allocation works for whatever language i will be using after some research i have some questions and doubts which i would like to get some insight in for examplei read here that java specifies exactly how the stack contents are organized looking at the jvm spec structure it basically says the stack contains frames and that the frames contain whatever is inside the class by properly allocating the variables and functions maybe i am missing something here but i do not understand how this is any different than what c does i ask because the first link says javas specification of stack contents avoid compiler incompatibilitiesalso i have yet to find how the memory segments are exactly organized on top of each other for example i know the memory is divided into global variables call stack heap and code for c yet i do not know if the heaps address is higher than the stacks or if that depends on the implementation i also wonder whether a java program has more than that and how it would be laid out as well i imagine there is a standard since the jvm has to know where it all is to use it though i suppose it could just have the pointers and leave the rest to the os i imagine too that there must be at least a de facto standardanother the thing i do not understand is the runtime constant pool it is supposed to be a perclass or perinterface runtime representation of the constant pool table in a class file but i do not think i understand what it does it seems to have a tag to indicate what type the structure in question is then the name of the structure given by the programmer or assigned by the underlying system then it seems the rest of it varies with whatever the tag describes a thread an array etcif my interpretation of the runtime constant pool is right then why are they necessary as well as stack frames is it because stack frames only take care of the stack segments and the runtime constant pool must also have pointers for the heap allocated memory,"['java', 'c++']" +6432,why does c limit the set of types that can be declared as const compiler error cs0283 indicates that only the basic pod types as well as strings enums and null references can be declared as const does anyone have a theory on the rationale for this limitation for instance it would be nice to be able to declare const values of other types such as intptri believe that the concept of const is actually syntactic sugar in c and that it just replaces any uses of the name with the literal value for instance given the following declaration any reference to foo would be replaced with foo at compile timeconst string foo foothis would rule out any mutable types so maybe they chose this limitation rather than having to determine at compile time whether a given type is mutable,['c#'] +6434,write a number with two decimal places sql server how do you write a number with two decimal places for sql server,['sql'] +6441,prepopulate an inline formset i am working on an attendance entry form for a band my idea is to have a section of the form to enter event information for a performance or rehearsal heres the model for the event tableclass eventmodelsmodel event id modelsautofieldprimary keytrue date modelsdatefield event type modelsforeignkeyeventtype description modelstextfieldthen i would like to have an inline formset that links the band members to the event and records whether they were present absent or excusedclass attendancemodelsmodel attendance id modelsautofieldprimary keytrue event id modelsforeignkeyevent member id modelsforeignkeymember attendance type modelsforeignkeyattendancetype comment modelstextfieldblanktruenow what i would like to do is to prepopulate this inline formset with entries for all the current members and default them to being present around 60 members unfortunately django does not allow initial values in this caseany suggestions,['python'] +6449,best way to interact with command line application i need to write a component for an application that interacts tightly with a command line application the command line application asks a series of questions performs some computations then terminates which i need to detect essentially i want to wrap up this interaction in a wrapper classhas any one achieved similar in the past if so how did you go about it did you notice a pattern or maybe some good build in classes to use cheers,['c#'] +6457,where can i find a java to c converter i needed to convert a java 15se app to c 20does anyone know of a tool preferably freeopen source to do this,"['c#', 'java']" +6459,what are the major differences between c and c and when would you choose one over the other for those of you with experience with both what are the major differences for a newcomer to either which would be better to learn are there situations where you might choose c but then other situations where you would choose c is it a case of use the best tool for the job or one is significantly better than the other i know c is an enhancement of c but it was created in 83 and has not completely replaced c so there must be something more to iti know this question is subjective and i am not trying to start any religious war so please try to be as objective as possible clear strengths and weaknesses and comparisons,"['c++', 'c']" +6460,insert row in table for each id in another table i tried searching here for a similar solution but did not see one so i was wondering what is the best way to accomplish the followingi have a table with 17 million rows all have a unique id we have recently created a new table that will be used in conjunction with the previous table where the foreign key of the new table is the unique id of the old tablefor extable 1 id field1 field2 field3table 2 table1id field1 the problem is since we are migrating this into a live environment we need to back fill table 2 with a row containing the id from table 1 for each row in table 1ex table 1 1 test nulltable 2 now needs to have 1 null and so on for each row that is in table1 the main issue is that the ids are not all sequential in table 1 so we will have to read from table 1 and then insert based of the id of found into table 2is there any easier way to go about thisthanks in advancejoealso to clarify table 2 will be new data and the only thing that it will contain from table 1 is the id to keep the foreign key relationshipalso this is sql server 20,['sql'] +6464,creating a specific xml document using namespaces in c we were given a sample document and need to be able to reproduce the structure of the document exactly for a vendor however i am a little lost with how c handles namespaces heres a sample of the documentxml version10 encodingutf8doc1 xmlns xmlnsxsi xsischemalocation header stuffdatastuff morestuffdatamorestuff header doc1how i would usually go about this is to load a blank document and then start populating itxmldocument doc new xmldocumentdocloadxmldoc1doc1 add nodes here with insert etconce i get the document started how do i get the namespace and schema into the doc1 element if i start with the namespace and schema in the doc1 element by including them in the loadxml then all of the child elements have the namespace on them and that is a nono the document is rejectedso in other words i have to produce it exactly as shown and i would rather not just write texttoafile in c and hope it is valid xml,['c#'] +6467,how can i get greasemonkey to call a function on a page after it loads i have a very simple greasemonkey script that i want to call an already existing javascript function on the page i have read the documentation and nothing seems to workwindowsettimeoutfunction alerttest this alert works but nothing after it does myfunction undefined windowmyfunction undefined documentmyfunction undefined 10,['javascript'] +6470,httplistenerstart accessdenied error on vista running this code as a regular user throws httplistenerexception access denied snippet runs ok as an administatorclass program static void mainstring args httplistener listener new httplistener listenerprefixesaddhttpmyip8080app listenerstart and so on i went ahead and added the uri using netsh netsh http show lists the urinetsh http add urlacl urlhttp8080app userdomainuserstill getting the same error adding acls did work for other projects they did not use httplistener though i tried multiple portapplication name combinations nothing worksany ideas what might be the causerunning net 35 sp1 on vista,['.net'] +6472,div with horizontal scrolling only i have a fixed width div containing a table with many columns and need to allow the user to scroll the table horizontally within the divthis needs to work on ie6 and ie7 only internal client applicationthe following works in ie7overflowx scrollcan anyone help with a solution that works in ie6 as well,"['html', 'css']" +6473,java tostring using reflection i was writing a tostring for a class in java the other day by manually writing out each element of the class to a string and it occurred to me that using reflection it might be possible to create a generic tostring method that could work on all classes ie it would figure out the field names and values and send them out to a stringgetting the field names is fairly simple here is what a coworker came up withpublic static list initfieldarraystring classname throws classnotfoundexception class c classfornameclassname field field cgetfields liststring classfields new arraylistfieldlength for int i 0 i fieldlength i string cf fielditostring classfieldsaddcfsubstringcflastindexof 1 return classfieldsusing a factory i could reduce the performance overhead by storing the fields once the first time the tostring is called however finding the values could be a lot more expensivedue to the performance of reflection this may be more hypothetical then practical but i am interested in the idea of reflection and how i can use it to improve my everyday programming,['java'] +6479,why cannot enums constructor access static fields why cannot enums constructor access static fields and methods this is perfectly valid with a class but is not allowed with an enumwhat i am trying to do is store my enum instances in a static map consider this example code which allows lookup by abbreivationpublic enum day sundaysun mondaymon tuesdaytue wednesdaywed thursdaythu fridayfri saturdaysat private final string abbreviation private static final mapstring day abbrev map new hashmapstring day private daystring abbreviation thisabbreviation abbreviation abbrev mapputabbreviation this not valid public string getabbreviation return abbreviation public static day getbyabbreviationstring abbreviation return abbrev mapgetabbreviation this will not work as enum does not allow static references in its constructor it however works just find if implemented as a classpublic static final day sunday new daysunday sunprivate daystring name string abbreviation thisname name thisabbreviation abbreviation abbrev mapputabbreviation this valid,['java'] +6481,do you recommend using semicolons after every statement in javascript in many situations javascript parsers will insert semicolons for you if you leave them out my question is do you leave them outif youre unfamiliar with the rules there is a description of semicolon insertion on the mozilla site heres the key pointif the first through the nth tokens of a javascript program form are grammatically valid but the first through the n1st tokens are not and there is a line break between the nth tokens and the n1st tokens then the parser tries to parse the program again after inserting a virtual semicolon token between the nth and the n1st tokensthat description may be incomplete because it does not explain dreass example anybody have a link to the complete rules or see why the example gets a semicolon i tried it in jscriptnetthis stackoverflow question is related but only talks about a specific scenario,['javascript'] +6483,object oriented questions in javascript i have been using javascript for a while but have never learned the language past the basics i am reading john resigs pro javascript techniques i am coming up with some questions but i am not finding the answers to them in the book or on google etcjohn gives this example in his bookfunction 1function user name age thisname name thisage age add a new function to the object prototypeuserprototypegetname function return thisnameuserprototypegetage function return thisagevar user new user bob 44 consoleloguser usergetname age usergetagei am still learning about the prototype property so i tried writing something similarfunction 2function user name age thisname name thisage age thisgetname function return thisname thisgetage function return thisage var user new user bob 44 consoleloguser usergetname age usergetageit does not use the prototype property to create the getname and getage functions but the output is the same as johns examplei took it one step further and created thisfunction 3var user name age 0 setname functionname thisname name setage functionage thisage age getname function return thisname getage function return thisage usersetnamebobusersetage44consoleloguser usergetname age usergetageagain it looks different than johns example and i had to add setter methods but the output is the samequestion 1 what is the difference between the 3 functions what is the advantage of the prototype property and is function 2 doing anything incorrectly because it seems more straight forward to code 2 instead of 1 although i am sure 1 is doing it better seeing as john created itquestion 2 how could i modify function 3 to not use the setname and setage methods but still keep the shorthand can the shorthand have constructorsthanks in advance for helping me learnediti think my 2nd question was a little confusing i meant how could i use the shorthand to create a user object but then after i create the object say something likevar user new userbob 44just like in function 1 or is that not possibleedit 2wow thanks everyone for the awesome answers that really makes it a lot more clear to me so if i understand correctly the difference between 1 and 2 are not too much if i only ever create one user object they probably are not different at all but if my program creates many user objects 1 would most likely be more efficient and use less memory since all objects will share the same functionsi really appreciate all of the great answers thanks,['javascript'] +6485,can you use the aspnet membership provider in a windows application the aspnet membership provider has some clear uses in a web app i am thinking about trying to leverage some of the features in a windows application more specifically wpf does anyone know if it is possible to use the core features in a windows app i am mostly just looking for it to create my database tables and maintain users roles and profiles i obviously do not need to use the builtin web controls eg login,"['.net', 'asp.net']" +6488,how do i focus a foreign window i have an application which may only have one instance of itself open at a time to enforce this i use this code systemdiagnosticsprocess myprocesses systemdiagnosticsprocessgetprocesses systemdiagnosticsprocess me systemdiagnosticsprocessgetcurrentprocess foreach systemdiagnosticsprocess p in myprocesses if pprocessname meprocessname if pid meid if already running abort this copy return launch the application it works fine i would also like it to be able to focus the form of the alreadyrunning copy that is before returning i want to bring the other instance of this application into the foregroundhow do i do thatre setforegroundwindowsetforegroundwindow works to a point systemruntimeinteropservicesdllimportuser32dll public static extern bool setforegroundwindowintptr hwnd if pid meid if already running focus it and then abort this copy setforegroundwindowpmainwindowhandle return this does bring the window to the foreground if it is not minimized awesomeif the window is minimized however it remains minimizedit needs to unminimizesolution via switchtothiswindow works systemruntimeinteropservicesdllimportuser32dll public static extern void switchtothiswindowintptr hwnd bool falttab stathread static void main systemdiagnosticsprocess me systemdiagnosticsprocessgetcurrentprocess systemdiagnosticsprocess myprocesses systemdiagnosticsprocessgetprocessesbynamemeprocessname foreach systemdiagnosticsprocess p in myprocesses if pid meid switchtothiswindowpmainwindowhandle true return now go ahead and start our application,"['c#', '.net']" +6495,left outer join on two columns performance issue i am using a sql query that is similar to the following formselect col1 col2from table1left outer join table2on table1person uid table2person uidand table1period table2periodand it is either way too slow or somethings deadlocking because it takes at least 4 minutes to return if i were to change it to thisselect col1 col2from table1left outer join table2on table1person uid table2person uidwhere table1period table2periodthen it works fine albeit not returning the right number of columns is there any way to speed this upupdate it does the same thing if i switch the last two lines of the latter queryselect col1 col2from table1left outer join table2on table1period table2periodwhere table1person uid table2person uidupdate 2 these are actually views that i am joining unfortunately they are on a database i do not have control over so i cannot easily make any changes to the indexing i am inclined to agree that this is an indexing issue though i will wait a little while before accepting an answer in case there is some magical way to tune this query that i do not know about otherwise i will accept one of the current answers and try to figure out another way to do what i want to do thanks for everybodys help so far,['sql'] +6496,jquery scope or race condition in ajaxgetjson i have a piece of jquery code which invokes several getjson calls in quick successionvar table tableoutputfor var i in items var thisitem itemsi getjsonmyservice itemid thisitem functionjson var str tr str td thisitem td str td jsonsomemember td str tr tableappendstr when i run this against a laggy server the table gets populated with the expected jsonsomemember values they arrive out of order i do not mind that but the thisitem column is populated with an unpredictable mixture of values from various iterationsi am assuming this is something to do with scope and timing the callback function is reading thisitem from a wider scope am i right how do i prevent thismy current workaround is for the json service to return a copy of its inputs which is unsatisfying to say the least,"['javascript', 'jquery']" +6501,what is the equivalant of a friend keyword in c sharp what is the equivalant of a friend keyword in c sharphow do i use the internal keywordi have read that internal keyword is a replacement for friend in ci am using a dll in my c project that i have the source code for and yet i do not want to modify the existing code i have inherited the class and i can use my inherited class any way i want the problem is that most of the code in the parent class has protected methods will using a friend somehow make it possible to access or call these protected methods,['c#'] +6504,when cannot an object be converted to a reference i want to compile the following line of code from enheout enhsetw26gcc gives the following errorerror no match for operator in enheout enhsetw26but the enhsimoutput class of which enheout is an instance does declareenhsimoutput operator setw pthis problem goes away if i implement a version of the operation that accepts the object by valueenhsimoutput operator setw por if i create the enhsetw object as a local ieenhsetw wvalue26enheout wvaluemy question is this why does gcc not select the byreference version of the operator to begin withthe developers who wrote this code clearly made it compile yet default gcc refuses to do it why is there a difference between an object declared separately as a local variable and a local created inline,['c++'] +6505,is using a while block to do nothing a bad thing i am currently working through the excercises in the c programming language heres one of my solutions int cwhile cgetchar eof if c while c getchar do nothing putchar putcharci found some solutions here that are quite different to mine and use an extra variable to keep track of whats going on whereas i just use a while loop to skip through all the spaces my solution feels a bit messy as it seems bit hackish to have a while loop with nothing between the curly braces i was wondering if there are any good reasons not to do this thanks for any advice,['c'] +6507,jquery form submit is not working in ie6 i want to submit a with using jquery as belowformidsubmitits working perfect in all browsers except ie6how to make it work in ie6,"['javascript', 'jquery', 'html']" +6511,why is longvalueof0equalsintegervalueof0 false this questions is prompted by i think i understand why mapkvput takes a k but mapkvget takes an object it seems not doing so will break too much existing code now we get into a very errorprone scenariojavautilhashmaplong string m new javautilhashmaplong stringmput5lfive compiler barfs on mput5 fivemcontains5 no complains from compiler but returns falsecould not this have been solved by returning true if the long value was withing int range and the values are equal,['java'] +6513,css two divs next to each other i want to put two divs next to each other the right div is about 200px and the left div must fill up the rest of the screen width how can i do this,"['html', 'css']" +6519,how to detect iis version using c how to detect iis version using cupdatei meant from a winapp actually the scenario is developing a custom installer that wants to check the version of the installed iis to call the appropriate apis,['c#'] +6530,matching exact string with javascript how can i test if a regex matches a string exactlyvar r artesta returns truertestba returns truetestexactr ba should return falsetestexactr a should return true,['javascript'] +6538,php mail encodes subject line when i try to send a html encoded email from php if the subject line contains special chars like heres the information you requested php encodes it to read here039s the information you requestedhow do i fix thisheres what the code looks like using php mailheaders mimeversion 10 rnheaders contenttype texthtml charsetiso88591 rnheaders to mod paramsname mod paramsemail rnheaders from do not rn email to mod paramsemailemail sub heres the information you requestedbody html entity decodehtmlbody email html body bodyhtmlmailemail toemail subbodyheadersit gives the same error as running it through the sugarphpmailer class,['php'] +6540,php best design practices ok have a bunch of questions that i have been thinking about the past few days currently i have a site that is just a bunch of php files with mysql statements mixed in with php html and css basically a huge mess i have been tasked with cleaning up the site and have made for myself the following requirementsthe site needs to be efficient and well laid out the source code i would like to be able to write as little code as possiblethere has to be good separation between structure presentation and logicfor whatever reason i cannot use a framework and need to keep the code maintainable and simple as there will be future developers working with itthere needs to be an admin section for at least a few pagessaying that this is what i know about the site as it is nowconsists of 1012 pages a few are completely static most are dynamically driven via a database and there is a huge form for users to fill out 2030 fields that need to be validated and checkedthe hierarchy of the site is basically 56 main pages and then subpages within thoseso knowing those things i wanted to know if anyone had any tipssuggestions as to how to go about doing this with the least amount of headaches would an oo approach be best in this situationsince there are many static pages and the dynamic pages just need the content filled in would it be best to use some kind of basic templateedit thanks for the answers when i said no frameworks i basically meant anything that would require new syntax other than php as whoever gets hired to work on this site after me will probably only know php,['php'] +6550,how do i append a newline character for all lines except the last one i am iterating through a hashmap see my earlier question for more detail and building a string consisting of the data contained in the map for each item i will have a new line but for the very last item i do not want the new line how can i achieve this i was thinking i could so some kind of check to see if the entry is the last one or not but i am not sure how to actually do thatthanks,['java'] +6570,programmatically binding list to listbox lets say for instance i have the following extremely simple windowwindow xclasscalendargeneratorwindow1 xmlns xmlnsx titlewindow1 height300 width447 grid listbox margin1240012 nameeventlist horizontalalignmentleft width134 gridwindowand a simple list defined asliststring listofnames new liststringand lets assume that the list has several names in it how would i go about binding the list to the listbox using as much codebehind as possible,['c#'] +6572,how do i determine the size of an object in python in c we can find the size of an int char etc i want to know how to get size of objects like a string integer etc in pythonrelated question how many bytes per element are there in a python list tuplei am using an xml file which contains size fields that specify the size of value i must parse this xml and do my coding when i want to change the value of a particular field i will check the size field of that value here i want to compare whether the new value that i am gong to enter is of the same size as in xml i need to check the size of new value in case of a string i can say its the length but in case of int float etc i am confused,['python'] +6573,webbased mysql interface better that phpmyadmin is there any webbased interface for mysql better than phpmyadmin i use phpmyadmin a lot but it is becoming a pain especially it is slow sometimes i would like to have deep export functionality like phpmyadmin but more design features,['mysql'] +6576,error the object cannot be deleted because it was not found in the objectstatemanager trying to get a handle on entity framework here and i am hitting some speed bumpsi have a get method that works fine and has been tested but my delete method is not working public static void deletestring name j1entities db new j1entities dbdeleteobjectgetname dbsavechanges but i get the following error error the object cannot be deleted because it was not found in the objectstatemanageri ran the debugger and the object inside the deleteobject is correct what am i missing thank you,['c#'] +6577,dividing workload on several threads i was wondering if anyone knows about a good article which describes dividing workload on to several threads preferebly it would be written for c but it is really the concept i am after so it is not an issue if it is written for a different similar languagei have a problem where i would have to divide a large amount of computing into several threads and then sum the generated data after one iteration completes so i would need to know that all threads have finished and then start a new iteration supplying all the threads with the data generated in the last iteration the data would be modified before the end of each iterationi hope this makes sense and is possible either way i would appreciate some advice on how to tackle the problem of computing large amounts of data divided on to several threads so i can use more than one processors corethank you for your answers,['c#'] +6579,recommended javascript html template library for jquery any suggestions on which html template library would go well with jquery googling turns up quite a number of libraries but i am not sure whether there is a well recognized library that would stand the test of time,"['javascript', 'jquery']" +6582,is there already some stdvector based setmap implementation for small sets or maps it is usually much faster to just use a sorted vector instead of the treebased setmap especially for something like 510 elements llvm has some classes in that spirit but no real adapter that would provide a stdmap like interface backed up with a stdvectorany free implementation of this out thereedit thanks for all the alternative ideas but i am really interested in a vector based setmap i do have specific cases where i tend to create huge amounts of setsmaps which contain usually less than 10 elements and i do really want to have less memory pressure think about for example neighbor edges for a vertex in a triangle mesh you easily wind up with 100k sets of 34 elements each,['c++'] +6590,login to the page with httpwebrequest how can i login to the this page by using httpwebrequest login button is poaalji upper left cornerhtml source of login pagetable idmaintable border0 cellspacing0 cellpadding0 styleheight100 width100 tr td width367 styleverticalaligntoppadding3pxscript typetextjavascriptfunction checkuserid if document documentgetelementbyid var f documentgetelementbyiduserid if f if fvaluelength 8 alertkorisniako ime treba biti you formatu 061062 x return false return truescriptdiv stylemarginbottom12pxtable classleftbox styleheight184px backgroundimageurlweb2007slikeokvirjpg cellspacing0 cellpadding0 tr th styleverticalalignmiddleform action methodpost onsubmitreturn checkuserid input typehidden namerealm valuesso input typehidden nameapplication valueportal input typehidden nameurl valueampurlportalshowidc1 table classformbox aligncenter cellspacing0 cellpadding0 tr th styleverticalalignmiddle textalignrightpaddingright4pxkorisnikth tdinput typetext size20 iduserid nameuseridtd tr tr th styletextalignrightpaddingright4pxlozinkath tdinput typepassword size20 namepassword td tr tr th colspan2 input classdugmic typeimage idprijava1 altprijava srcweb2007dugmiciposalji 1jpg onmouseoverchangeimageprijava1web2007dugmiciposalji 2jpg onmouseoutchangeimageprijava1web2007dugmiciposalji 1jpg th tr table div stylepadding12px a hrefportalshowidc1121da li ste novi bh mobile korisnikabr a hrefportalshowidc1121da li ste zaboravili lozinkuaifruabr div formth trtabledivform action is how can i use this with httpwebrequest to get a cookie and use some date from this page,['c#'] +6595,change the ruby process name in top i would like to change the name of the ruby process that gets thisplayed in the linuxunix top command i have tried the 0minameapproach but it only works with the ps command and in top the process keeps getting thisplayed as ruby,['ruby'] +6613,datatable to json i recently needed to serialize a datatable to json where i am at were still on net 20 so i cannot use the json serializer in net 35 i figured this must have been done before so i went looking online and found a number of different options some of them depend on an additional library which i would have a hard time pushing through here others require first converting to listdictionary which seemed a little awkward and needless another treated all values like a string for one reason or another i could not really get behind any of them so i decided to roll my own which is posted below as you can see from reading the todo comments it is incomplete in a few places this code is already in production here so it does work in the basic sense the places where it is incomplete are places where we know our production data would not currently hit it no timespans or byte arrays in the db the reason i am posting here is that i feel like this can be a little better and i would like help finishing and improving this code any input welcomenote that this capability is built into net 35 and later and so the only reason to use this code today is if youre still limited to net 20 even then jsonnet has become the goto library for this kind of thingpublic static class jsonhelper public static string fromdatatabledatatable dt string rowdelimiter stringbuilder result new stringbuilder foreach datarow row in dtrows resultappendrowdelimiter resultappendfromdatarowrow rowdelimiter resultappend return resulttostring public static string fromdatarowdatarow row datacolumncollection cols rowtablecolumns string coldelimiter stringbuilder result new stringbuilder for int i 0 i colscount i use index rather than foreach so we can use the index for both the row and cols collection resultappendcoldelimiterappend appendcolsicolumnnameappend appendjsonvaluefromdatarowobjectrowi colsidatatype coldelimiter resultappend return resulttostring possible types vs80aspx private static type numeric new type typeofbyte typeofdecimal typeofdouble typeofint16 typeofint32 typeofsbyte typeofsingle typeofuint16 typeofuint32 typeofuint64 i do not want to rebuild this value for every date cell in the table private static long epochticks new datetime1970 1 1ticks private static string jsonvaluefromdatarowobjectobject value type datatype null if value dbnullvalue return null numeric if arrayindexofnumeric datatype 1 return valuetostring todo eventually want to use a stricter format specifically separate integral types from floating types and use the r roundtrip format specifier boolean if datatype typeofbool return boolvalue true false date see if datatype typeofdatetime return date new timespandatetimevaluetouniversaltimeticks epochtickstotalmillisecondstostring todo add timespan support todo add byte support todo this would be much faster with a state machine todo way to select between double or single quote literal encoding todo account for database strings that may have single r or and line breaks stringchar return valuetostringreplace replaceenvironmentnewline nreplace updatethis is old now but i wanted to point out something about how this code handles dates the format i used made sense at the time for the exact rationale in the url however that rationale includes the followingto be perfectly honest json schema does solve the problem by making it possible to subtype a string as a date literal but this is still work in progress and it will take time before any significant adoption is reachedwell time has passed today it is okay to just use the iso 8601 date format i am not gonna bother changing the code because really this is ancient just go use jsonnet,"['c#', '.net']" +6621,get the xpath to an xelement i have got an xelement deep within a document given the xelement and xdocument is there an extension method to get its full ie absolute eg rootitemelementchild xpatheg myxelementgetxpatheditokay looks like i overlooked something very important whoops the index of the element needs to be taken into account see my last answer for the proposed corrected solution,['c#'] +6628,python object repr self should be an expression i was looking at the builtin object methods in the python documentation and i was interested in the documentation for object repr self heres what it sayscalled by the repr builtin function and by string conversions reverse quotes to compute the aofficiala string representation of an object if at all possible this should look like a valid python expression that could be used to recreate an object with the same value given an appropriate environment if this is not possible a string of the form some useful description should be returned the return value must be a string object if a class defines repr but not str then repr is also used when an ainformala string representation of instances of that class is requiredthis is typically used for debugging so it is important that the representation is informationrich and unambiguousthe most interesting part to me wasif at all possible this should look like a valid python expression that could be used to recreate an object with the same value but i am not sure exactly what this means it says it should look like an expression which can be used to recreate the object but does that mean it should just be an example of the sort of expression you could use or should it be an actual expression that can be executed eval etc to recreate the object or should it be just a rehasing of the actual expression which was used for pure information purposesin general i am a bit confused as to exactly what i should be putting here,['python'] +6637,how do i create a list of python lambdas in a list comprehensionfor loop i want to create a list of lambda objects from a list of constants in python for instancelistofnumbers 12345square lambda x x xlistoflambdas lambda squarei for i in listofnumbersthis will create a list of lambda objects however when i run themfor f in listoflambdas print fi would expect that it would print1 4 9 16 25instead it prints25 25 25 25 25it seems as though the lambdas have all been given the wrong parameter have i done something wrong and is there a way to fix it i am in python 24 i thinkedit a bit more of trying things and such came up with thislistoflambdas for num in listofnumbers action lambda squarenum listoflambdasappendaction print actionprints the expected squares from 1 to 25 but then using the earlier print statementfor f in listoflambdas print fstill gives me all 25s how did the existing lambda objects change between those two print callsrelated question why results of map and list comprehension are different,['python'] +6638,suggest a jpa unit test framework how to unit test jpa code is there any way to generate unit test case itself note i am lazy and new to unit test code,['java'] +6644,how can i create a product key for my c application how can i create a product key for my c applicationi need to create a product or license key that i update annually additionally i need to create one for trial versionsrelated how do i best obfuscate my c product license verification code webbased license activation how do you protect your software from illegal thistributionbest activation key software for net application,"['c#', '.net']" +6653,javas virtual machine and clr as a sort of follow up to the question called differences between msil and java bytecode what is the major differences or similarity in how the java virtual machine works versus how the net framework common language runtime clr worksalso is the net framework clr a virtual machine or does it not have the attributes of a virtual machine,"['java', '.net']" +6655,protocol buffers in c projects using protobufnet best practices for code generation i am trying to use protobuf in a c project using protobufnet and am wondering what is the best way to organise this into a visual studio project structurewhen manually using the protogen tool to generate code into c life seems easy but it does not feel righti would like the proto file to be considered to be the primary sourcecode file generating c files as a byproduct but before the c compiler gets involvedthe options seem to becustom tool for proto tools although i cannot see where to start thereprebuild step calling protogen or a batchfile which does thati have struggled with 2 above as it keeps giving me the system cannot find the file specified unless i use absolute paths and i do not like forcing projects to be explicitly locatedis there a convention yet for thiseditbased upon jons comments i retried the prebuild step method and used this protogens location hardcoded for now using googles addressbook examplecbinprotobufprotogen iprojectdiraddressbookproto oprojectdiraddressbookcs tcbinprotobufcsharpxsltedit2taking jons recommendation to minimise buildtime by not processing the proto files if they have not changed i have knocked together a basic tool to check for me this could probably be expanded to a full custombuild toolusing systemusing systemdiagnosticsusing systemionamespace prebuildchecker public class checker static int mainstring args try checkargs return 0 catch exception e consolewritelineemessage return 1 public static void checkstring args if argslength 3 throw new argumentexception command line must be supplied with source target and commandline plus options string source args0 string target args1 string executable args2 string arguments argslength 3 getcommandlineargs null fileinfo targetfileinfo new fileinfotarget fileinfo sourcefileinfo new fileinfosource if sourcefileinfoexists throw new argumentexceptionstringformat source file 0 not found source if targetfileinfoexists sourcefileinfolastwritetimeutc targetfileinfolastaccesstimeutc process process new process procestartinfofilename executable procestartinfoarguments arguments procestartinfoerrordialog true consolewritelinestringformat source newer than target launching tool 0 1 executable arguments procestart private static string getcommandlinestring args string arguments new stringargslength 3 arraycopyargs 3 arguments 0 argumentslength return stringjoin arguments my prebuild command is now all on one linesolutiondirprebuildcheckeroutdirprebuildchecker projectdiraddressbookproto projectdiraddressbookcs cbinprotobufprotogen iprojectdiraddressbookproto oprojectdiraddressbookcs tcbinprotobufcsharpxslt,['c#'] +6666,what are the differences between llvm and java bytecode i dont understand the difference between llvm and the java bytecode what are theyedit by what are they i mean the differences between llvm and java bytecode not what are llvm and java,['java'] +6670,protecting adobe air apps i am about to deliver an adobe air app to a customerbut it is my first delivery of any sort ie i haveno experience whatsoever with licensing etcusers of this app may or may not be online so cannot count on that in fact it is 99 sure thatthey will be offlinenor do i expect them to very techsavvy who willspend enough time scouting for ways to crack itso is there an okeish type of way to protect thisapp that is i do not want people to simply copythe installation folder take it to another machineand run it it should be slightly harder than thisoh and i am also using php and mysql with whichthis air app communicates so anything you guys couldhelp me with is very very welcome,"['php', 'mysql']" +6671,restricting t to string and int i have built myself a generic collection class which is defined like this public class statisticitemhitstthis class can be used with int and string values only however thispublic class statisticitemhitst where t string int would not compile what am i doing wrong,['c#'] +6672,which editor would you give your mom to let her edit her own website i mean this quite literally a close relative wants to create her own website for her business and asked me for help i have offered her to set up the website take care of domain registration and all but i do not have the time to design the website for her so i want to give her a software in which she can edit the page and publish it on her ownmy featurewishlist the software shouldof course be easytouse as she is not a pro at the computerbe able to publish the website once the ftpconnection has been enteredhave some predefined themes but also the possibilites to define a custom themeoffer a german ui since she does not understand englishi so far looked at nvu too complicated zeta producer crashed even before i could start editing the first page citydesk very promising but still too complicated and not in german i am quite happy with namu6 but unfortunately it is english onlyi would be happy for any suggestioneditsome were asking for a platform she is only using windows so mac or linux is not an option,['html'] +6673,eclipse editor plugin error when opening file outside project i am developing an editor plugin for eclipse it works fine on files within eclipse projects but when an external file is opened via the file open file menu which works file with eg java files i get a page thisplaying nothing but a horizontal blue line and the word error the error log of eclipse is empty as is the log file in the metadata directory what could cause this how can i diagnose the error when i have no error message that tells me where to look there does not seem to be a way to get more detailed logging from eclipseediti have found that the source of the problem is close to what jamesh mentioned but not a classcastexception there simply is no idocument instance for the text viewer to thisplay because storagedocumentprovidercreatedocument returns null the reason for this is that it only knows how to create documents for instances of orgeclipseuiistorageeditorinput but in this case it gets an instance of orgeclipseuiidefilestoreeditorinput which does not implement that interface but instead implements orgeclipseuiiurieditorinput,['java'] +6680,json datetime between python and javascript i want to send a datetimedatetime object in serialized form from python using json and deserialize in javascript using json what is the best way to do this,"['javascript', 'python']" +6682,what is the best method to merge two php objects we have two php5 objects and would like to merge the content of one into the second there are no notion of subclasses between them so the solutions described in the following topic cannot applyhow do you copy a php object into a different object typewe have thisobjectaaobjectabobjectbcobjectbdwe want the easiest way to getobjectcaobjectcbobjectccobjectcdremarksthese are objects not classesthe objects contain quite a lot of fields so a foreach would be quite slowso far we consider transforming objects a and b into arrays then merging them using array merge before retransforming into an object but we cannot say we are proud if this,['php'] +6684,does php feature short hand syntax for objects in javascript you can easily create objects and arrays like sovar aobject foobla bar2 var anarray foo bar 2are simialar things possible in phpi know that you can easily create an array using the array function that hardly is more work then the javascript syntax but is there a similar syntax for creating objects or should i just use associative arraysanarray arrayfoo bar 2anobjectlikeassociativearray arrayfoobla bar2so to summarizedoes php have javascript like object creation or should i just use associative arrays,['php'] +6687,what is the function construct used for i have been noticing construct a lot with classes i did a little reading and surfing the web but i could not find an explanation i could understand i am just beginning with oopi was wondering if someone could give me a general idea of what it is and then a simple example of how it is used with php,['php'] +6688,dynamic allocating array of arrays in c i do not truly understand some basic things in c like dynamically allocating array of arraysi know you can doint min order to declare a 2 dimensional array which subsequently would be allocated using some alloc function also it can be easily accessed by doing m line column but how should i assign a value to an element from that array using gcc the following statement mlinecolumn 12 fails with a segmentation faultany articledocs will be appreciated,['c'] +6693,are there compelling reasons not to use groovy i am developing a lob application in java after a long absence from the platform having spent the last 8 years or so entrenched in fortran c a smidgin of c and latterly netjava the language is not much changed from how i remember it i like it is strengths and i can work around its weaknesses the platform has grown and deciding upon the myriad of different frameworks which appear to do much the same thing as one another is a different story but that can wait for another day allinall i am comfortable with java however over the last couple of weeks i have become enamoured with groovy and purely from a selfish point of view but not just because it makes development against the jvm a more succinct and entertaining and well groovy proposition than java the languagewhat strikes me most about groovy is its inherent maintainability we all i hope strive to write well documented easy to understand code however sometimes the languages we use themselves defeat us an example in 2001 i wrote a library in c to translate edifact edi messages into ansi x12 messages this is not a particularly complicated process if slightly involved and i thought at the time i had documented the code properly and i probably had but some six years later when i revisited the project and after becoming acclimatised to c i found myself lost in so much c boilerplate mallocs pointers etc etc that it took three days of thoughtful analysis before i finally understood what i would been doing six years previouslythis evening i have written about 20 lines of java it is the day of rest after all i have documented as best as i know how but but of those 20 lines of java a significant proportion is java boiler platethis is where i see groovy and other dynamic languages winning through maintainability and later comprehension groovy lets you concentrate on your intent without getting bogged down on the platform specific implementation it is almost but not quite self documenting i see this as being a huge boon to me when i revisit my current project which i will port to groovy asap in several years time and to my successors who will inherit it and carry on the good workso are there any reasons not to use groovy,['java'] +6696,destructors of builtin types int char etc in c the following code gives a compiler errorvoid destruct1 int item itemintthis code is nearly the same i just typedef the int to another type and something magic happenstypedef int myintvoid destruct2 myint item itemmyintwhy does the second code works does an int gets a destructor just because it has been typedefedin case you wonder why one ever would like to do this this comes from refactoring c code were removing the standard heap and replacing it with selfmade pools this requires us to call placementnew and the destructors i know that calling destructors for primitive types is useless but we want them in the code nevertheless in case we later replace pods with real classesfinding out that naked ints do not work but typedefed ones do was quite a surprisebtw i have a solution that involves templatefunctions we just typedef inside the template and everything is fine,['c++'] +6698,synchronize two databases schema in mysql i was looking for a portable script or command line program that can synchronize two mysql databases schema i am not looking for a gui based solution because that cannot be automated or run with the buiddeployment toolbasically what it should do is scan database1 and database2 check the schema difference tables and indexes and propose a bunch of sql statements to run on one so that it gets the similiar structure of the other minimizing data damage as much as possibleif someone can indicate a php python or ruby package where this type of solution is implemented i can try to copy the code from therea lot of mysql gui tools probably can do this but i am looking for a scriptable solutionedit sorry for not being more clear what i am looking for is synchronization in table structure while keeping data intact as far as possible not data replicationmore infowhy replication would not workthe installation bases are spread around the statewe want the installer to perform dynamic fixes on the db based on chagnes made in the latest version regardless of what older version the end user might be usingchanges are mostly like adding new column to a tables creating new indexes or dropping indexes adding tables or dropping tables used by the system internally we do not drop user data tableif it is a gui no it cannot be used we do not want to bunddle a 20mb app with our installer just for db diff specially when the original installer is less than 1 mb,['mysql'] +6699,sql queries how slow is too slow do you have any formal or informal standards for reasonably achievable sql query speed how do you enforce them assume a production oltp database under full realistic production load of a couple dozen queries per second properly equipped and configuredpersonal example for illustrative purposes not a recommendation highly contingent on many factors some outside your controlexpectationeach transactional unit single statement multiple sql statements from beginning to end transaction boundaries or a single stored procedure whichever is largest must execute in 1 second or less on average without anomalous outliersresolutionslower queries must be optimized to standard slow queries for reports and other analysis are moved to an olap cube best case or a static snapshot databaseobviously some execution queries insertupdatedelete cannot be moved so must be optimized but so far in my experience it is been achievable,['sql'] +6701,how lean do my c exception classes really need to be there are lots of places where guidelines for designing exception classes can be found almost everywhere i look there is this list of things exception objects should never do which impacts the design of those classesfor instance the boost people recommend that the class contain no stdstring members because their constructor could throw which would cause the runtime to terminate the program immediatelynow it seems to me that this is rather theoretical if stdstrings constructor throws it is either a bug i passed a nullpointer in or an outofmemory condition correct me if i am wrong here since i am on a desktop i just pretend i have an infinite amount of memory and running out of memory is fatal to my application no matter whatwith that in mind why should not i embed stdstring objects in my exception classes in fact why could not my exception classes be fullfeatured and also take care of logging stack tracing etc i am aware of the oneresponsibility principle and it seems to me to be a fair tradeoff to have the exception class do all that surely if my parser needs to report a syntax error an fullfeatured exception would be more helpful than an exception built around a statically allocated character arrayso lean c exception classes how big a deal is it in the realworld what are the tradeoffs are there good thiscussions on the topic,['c++'] +6703,how to thisplay text in system tray icon with win32 api trying to create a small monitor application that thisplays current internet usage as percentage in system tray in c using win32 api also wanting to use colour background or colour text based on how much is used relative to days left in monthedit to clarify i am wanting the system tray icon to be dynamic as the percentage changes i update the system tray icon looking for solution that uses just plain old win32 ie no mfc or wtl,['c'] +6705,how do i thisable tabs for tag i am using tags for links on a web page how do i thisable tab key from selecting either of them,"['javascript', 'html']" +6710,c how can i hide the cursor in a winforms app im developing a touchscreen app and i need to hide the cursor whenever it is within the main form any ideas,['c#'] +6711,c how to convert bitmap byte array to jpeg format how can i convert a bitmap in byte array format to jpeg format using net 20,"['c#', '.net']" +6717,how to throttle login attemps in java webapp i want to implement an efficient mechanism to throttle login attemps in my java web application to prevent bruteforce attacks on user accountsjeff explained the why but not the howsimon willison showed an implementation in python for django that does not really help me along as i cannot use memcached nor djangoporting his ideas from scratch does not seem like a great either i do not want to reinvent the wheeli found one java implementation though it seems rather naiive instead of a lru cache it just clears all entries after 15 minutesehcache could be an alternative for memcached but i do not have any experience with it and do not really want to intoduce yet another technology if there are better alternatives for this taskso whats a good way to implement login throttling in java,['java'] +6726,is there a better layout language than html for printing i am using python and qt 44 and i have to print some pages initially i thought i would use html with css to produce those pages but html has some limitationsnow the question is is there anything that is better than html but just or almost as easy to use additionally it should be gplcompatibleeditkdgregory mark g the most obvious limitation is that i cannot specify the printer margins there is another problem how do i add page numbersjeremy french one thing i have to print is a list of all the products someone ordered which can spread over a few pages,['python'] +6729,standard way to embed version into python package is there a standard way to associate version string with a python package in such way that i could do the followingimport fooprint fooversioni would imagine there is some way to retrieve that data without any extra hardcoding since minormajor strings are specified in setuppy already alternative solution that i found was to have import version in my foo init py and then have version py generated by setuppy,['python'] +6731,can intellij create hyperlinks to the source code from log4j output in the intellij console stack traces automatically contain hyperlinks that bring you to the relevant source files the links appear at the end of each line in the format log4jloggertestjava25 i can configure log4j to output text in a similar formatlog4jappenderconsolelayoutconversionpatterndabsolute fl mnin eclipse the console automatically turned text like this into links in intellij the stack traces are links but my own output in the same form remains unlinked is there any way to get intellij to do the same,['java'] +6739,objectivec error initializer element is not constant why does the compiler give me the following error message on the provided code initializer element is not constant the corresponding cc code compiles perfectly under gccimport foundationfoundationhconst float a 1const float b a a error hereint main int argc const char argv nsautoreleasepool pool nsautoreleasepool alloc init insert code here nsloghello world pool drain return 0,['objective-c'] +6740,initialize library on assembly load i have a net library dll that acts like a functional library there are a bunch of static types along with static methodsthere is some initialization code that i need to run to set up the library ready for usewhen the assembly gets loaded is there a way to ensure that a particular method is run something like appdomainassemblyload but called automatically from the assembly itself i was thinking that maybe there is something like an assemblyattribute that could be usedat the moment i have this initialization code in a static constructor but as this is a library with many entry points there is no guarantee that this particular type will be usedthanks,"['c#', '.net']" +6746,workaround for php5s pdo rowcount mysql issue i have recently started work on a new project using php5 and want to use their pdo classes for it the problem is that the mysql pdo driver does not support rowcount so there is no way to run a query and then get the number of affected rows or rows returned which is a pretty big issue as far as i am concerned i was wondering if anyone else has dealt with this before and what youve done to work around it having to do a fetch or fetchall to check if any rows were affected or returned seems like a hack to me i would rather just do stmtnumrows or something similar,['php'] +6751,custom c data transfer objects from javascript pagemethods i have created a custom object that i would like to return in json to a javascript method this object was created as a class in c whats the best way to return this object from a pagemethod webmethod if you like to a javascript onpagemethodcallback function i need to be able to access the properties of this object via javascript and update the dom according possibly using jquerythank you stackoverflow,"['asp.net', 'javascript']" +6765,c read line from pdf i want to be able to read line by line from a pdf compare it to a string a filename and if the string appears in that line write that line to a listso far i had a quick look at itextsharp and at pdfsharp but it does not seem like these are the right tools for the job as they focus most on altering and printing pdfsdoes anyone know another way of reading lines from a pdf or should i keep trying with itextsharp pdfsharp,['c#'] +6766,is there a maximum number you can set xmx to when trying to increase jvm memory is there a max size you can set xmx to i set it to 1024m and eclipse opens ok when i set it above 1024 eclipse does not open and i get the error jvm terminated exit code1i was doing this because i keep getting an javalangoutofmemoryerror java heap space i am reading in a 355mb txt file and this error occurs when it is just reading in the file using the whileline readerreadline null loop i would have thought that 1024mb would have been enough can anyone help me,['java'] +6769,persistence solutions for c with a sql database i am wondering what kind of persistence solutions are there for c with a sql database in addition to doing things with custom sql and encapsulating the data access to daos or something similar are there some other more general solutionslike some general libraries or frameworks something like hibernate co for java and net or something else something that i have not even thought of can also be welcome to be suggestededit yep i was searching more for an orm solution or something similar to handle sql queries and the relationships between tables and objects than for the db engine itself thanks for all the answers anyway,"['c++', 'sql']" +6775,multiple submit buttonsforms in rails i am trying to write a rails application which lets you go to a certain page say personid on this page it shows a set of available resources i want each resource to have a button next to it which reserves that resource to that person by creating a new instance of an allocation model as an extension i would like several buttons by each resource that cancel reservations and do other things i would also like to input data alongside some of the buttons eg to allocate some of a resourcemy problem is i cannot work out how to sensibly do this without repeating myself or having a very hacky controller how can i do this without matching on the value part of the submit buttons the text on the buttons or using any javascriptadditionally if you have two forms on a page how do you set it up so changes on both forms are saved when any submit button is clicked,"['ruby-on-rails', 'ruby']" +6776,can you convert the output of php crypt to valid md5 i have some strings that have been encrypted using the php function cryptthe outputs look something like this1vf41cgco33ebihvufhpwskmi0184vd4ps1pdalwroaiwdkcfjlyv11or1ry4v3xo04v1yfb7jxdj1scjwhile i believe crypt is using the md5 algorithm the outputs are not valid md5 hashesis there a way of converting the produced hashes into valid md5 hashes 16byte hex valuesupdatethanks for the replies so answers so far i am pretty sure the crypt function used is using some sort of md5 algorithm what i am looking to do is convert the ouput that i have into an md5 hash that looks something like the following9e107d9d372bb6826bd81d3542a419d6 e4d909c290d0fb1ca068ffaddf22cbd0 d41d8cd98f00b204e9800998ecf8427etaken from wikipediais there a way of converting from the hashes i have to ones like the above,['php'] +6779,selecting an index in a qlistview this might be a stupid question but i cannot for the life of me figure out how to select the row of a given index in a qlistviewqabstractitemview qlistviews parent has a setcurrentindexconst qmodelindex index the problem is i cannot construct a qmodelindex with the row number i want since the row and column field of the qmodelindex has no mutatorsqtableview which also inherits from qabstractitemview has a selectrowint row function why in the seven hells does not the qlistview have thisgood ol windows forms has the selectedindex property on it is listviews,['c++'] +6782,acquiring drive names as opposed to drive letters in java on my windows machine my main hard drive has the letter c and the name local thisk to list the drive letters in java on windows the file object has the static listroots method but i cannot find a way to acquire the drive names as opposed to the drive letters on windowshas anyone tried this before,['java'] +6785,why does not c have a pointer to member function type i could be totally wrong here but as i understand it c does not really have a native pointer to member function type i know you can do tricks with boost and mem fun etc but why did the designers of c decide not to have a 64bit pointer containing a pointer to the function and a pointer to the object for examplewhat i mean specifically is a pointer to a member function of a particular object of unknown type ie something you can use for a callback this would be a type which contains two values the first value being a pointer to the function and the second value being a pointer to the specific instance of the objectwhat i do not mean is a pointer to a general member function of a class egint fredcharfloatit would have been so useful and made my life easierhugo,['c++'] +6786,get file icon used by shell in net c or vb do not care given a file path string fileinfo struct or filesysteminfo struct for a real existing file how can i determine the icons used by the shell explorer for that filei am not currently planning to use this for anything but i became curious about how to do it when looking at this question and i thought it would be useful to have archived here on so,"['c#', '.net']" +6789,how to stretch in width a wpf user control to its window i have a window with my user control and i would like to make usercontrol width equals window width how to do thatthe user control is a horizontal menu and contains a grid with three columnscolumndefinition nameleftsidemenu width433columndefinition namemiddle widthcolumndefinition namerightsidemenu width90that is the reason i want the window width to stretch the user control to 100 width with the second column relativeediti am using a grid there is the code for windowwindow xclasstciindexeruioperacao xmlns xmlnsx xmlnstciclrnamespacetciindexeruicontroles title minheight550 minwidth675 loadedload resizemodenoresize windowstylenone windowstartuplocationcenterscreen windowstatemaximized focusabletrue xnamewindowoperacao canvas xnamecanv grid tcistatus xnameucstatus the control which i want to stretch in width grid canvaswindow,"['c#', '.net']" +6790,version of xslt in iphone i plan to use xmlxslt in my iphone application what version of xslt is currently supported on the iphone can i use xslt 20 or just 10,['iphone'] +6791,can i get the matrix determinant using numpy i read in the manual of numpy that there is function detm that can calculate the determinant however i cannot find the det method in numpyby the way i use python 25 there should be no compatibility problems with numpy,['python'] +6792,stringformat for c looking for an implementation for c of a function like nets stringformat obviously there is printf and it is varieties but i am looking for something that is positional as instringformathi there 0 you are 1 years old how does it feel to be 1 name agethis is needed because were going to try and make it easier to localize our app and giving the translators 0 and 1 to position anywhere in the sentence is much easier than giving them a s d d which must be positioned in that order in their translationi suppose search and replace with variable inputs va start va end etc is what i will end up building but if there is already a solid solution that would be preferrablethanks,['c++'] +6797,c library for image recognition images containing words to string does anyone know of a c library for taking an image and performing image recognition on it such that it can find letters based on a given font andor font height even one that does not let you select a font would be nice eg readlettersimage image,['c++'] +6802,what is the best way to pass information from java to c i have a java application i need to pass some info to a c program it has been suggested that i use some simple socket programming to do this is this the best way if not what are the alternatives if so how should i go about learning about socket programming,"['java', 'c++']" +6806,how to eliminate postrender flicker i have tried my best to be a purist with my usage of javascriptajax techniques ensuring that all ajaxy behavior is an enhancement of base functionality while the site is also fully functional when javascript is thisabled however this causes some problemsin some cases a dom node should only be visible when javascript is enabled in the browser in other cases it should only be visible when thisabled take for instance a submit button on a form that has a drop down with an onchange handler that autosubmits using jquerys form pluginform methodpost action label forid statestatelabel select namestate idid state onchangethisformajaxsubmitajax submit handler option valuealalabamaoption option valueakalaskaoption select input classwith js thisabled typesubmit valueok formand the javascriptscript typetextjavascript documentreadyfunction with js thisabledhide scriptwhen javascript is enabled the submit button is not required due to the onchange handler however jquerys documentready function and the more direct documentonload is only called after the page has been fully loaded and rendered hence the submit button is initially thisplayed and a flash occurs when the javascript is executed and the nodes thisplay is set to nonei have accepted this as the cost of doing business and have not found a way around it but is there a technique i am not aware of that will minimize the effect or even outright eliminate iteditthe noscript solution mentioned by many people below seems promising but is not working for me on safari however prestauls 2nd suggestion works beautifullybody script typetextjavascript documentbodyclassname has js script the rest of your page bodythis can then be styled using straight cssbody js enabled only thisplay none body js thisabled only thisplay block bodyhas js js enabled only thisplay block bodyhas js js thisabled only thisplay none this second line is just for reference and can and should be removed to avoid circumstances where your element should not be thisplayblock likewise you may need different variations on the third line for other thisplay styles but this solution is nice and clean imo and in my tests entirely eliminates the flicker effect,"['javascript', 'jquery', 'html']" +6808,jquery documentready failing in ie6 i have the following code creates a timer to check for elements popping into the dom timer setintervalfunction for p in pixeltypes checkelemspixeltypesp 10 add document finished callbackdocumentreadyfunction document is loaded so stop trying to find new pixels clearintervaltimer in firefox it works great but in ie6 i get a object expected error on the documentready linei cannot figure out what would cause ie6 to not recognize it jquery is fully loaded by this pointis this a known issue,"['javascript', 'jquery']" +6811,string conversions i have a method which takes string argumentin some cases i want to pass int value to that methodfor invoking that method i want to convert int into stringfor that i am doing the following amethod100one more option is amethodstringvalueof100both are correcti do not know which is appropriatewhich gives better performancemostly this is happen in gwtin gwt for setting size of panels and widgets i want to do thiscan anyone give suggestion,['java'] +6814,how are post and get variables handled in python in php you can just use post for post and get for get query string variables whats the equivalent in python,['python'] +6820,how to use include directive correctly is there any material about how to use include correctlyi did not find any cc text book that explains this usage in detailin formal project i always get confused in dealing with it,"['c++', 'c']" +6828,what does the iphone developer program give me over and above simple registration as an iphone developer simply put what does my 99 get me that i cannot already get for freeok ok sounds like a dumb question but the apple site is not clear to memy hunch is that you get the ability to submit apps to the app store for your 99 but you could get everything else for free but it is not clear to me hence the question,['iphone'] +6829,sharing c code between windows and silverlight class libraries we wrote a small windows class library that implements extension methods for some standard types strings initially i placed this in a library so that any of our projects would be able to make use of it by simply referencing it and adding using xextensionsa problem came up when we wanted to use some of these methods in silverlight although all the code was compatible a windows library cannot be referenced in silverlight so we created a silverlight library that had links to the same class files and put compiler directives into the classes to allow different using declarations and namespaces this worked fine until today when i added a new class to the windows extensions library and realised that i would have to remember to link the class into the silverlight library toothis is not ideal and i wondered if anyone might have ideas for a better way of sharing extension methods and other helper code between windows and silverlight projects,['c#'] +6835,how to handle diacritics accents when rewriting pretty urls i rewrite urls to include the title of user generated travelblogsi do this for both readability of urls and seo purposes du todrathe first integer is the id the rest is for us humans but is irrelevant for requesting the resourcenow people can write titles containing any utf8 character but most are not allowed in the urlmy audience is generally english speaking but since they travel they like to include names like aa t ben haddouwhat is the proper way to translate this for thisplaying in an url using php on linuxso far i have seen several solutionsjust strip all non allowed characters replace spacesthis has strange resultsaa t ben haddou a gallery280at ben haddounot really helpfulljust strip all non allowed characters replace spaces leave charcode stackoverflowcom most likely because of the regexhammer usedthis gives strange results tast tast a questions0t233stt233sttranslate to nearest equivalentaa t ben haddou a gallery280ait ben haddoubut this goes wrong for german for example a14 should be transliterated uefor me as a dutch person the 3rd result looks the besti am quite sure however that 1 many people will have a different opinion and 2 it is just plain wrong in the german exampleanother problem with the 3rd option is how to find all possible characters that can be converted to a 7bit equivalentso the question iswhat in your opinion is the most desirable result within techlimitshow to technically solve it reach the desired result with php,['php'] +6844,what is rhino mocks repeat what is rhino mocks repeat repeatanyrepeatoncewhat does it mean and how it works,['c#'] +6853,math resources for cc programmers my degree is in electrical and computer engineering but i am currently employed as a software engineer i took all of the algebra geometry and calculus classes that one would expect from someone with my degree however i must admit i think i learned just enough to pass the test but never really saw a use for it and therefore never really retained much of the materialnow that i have matured some i see the use for it all of the time i know that there are lots of places that math knowledge would improve my coding so i am ready to relearn the old stuff and learn some new stuffwhat are your favorite resources out there resources that can tie math into programming are even better if you have any books websites blogs,['c++'] +6862,how to use msxml with visual studio 2008 express no atl classes without becoming crazy it is not really a question because i have already found a solution it took me a lot of time that is why i want to explain it heremsxml is based on com so it is not really easy to use in c even when you have helpful classes to deal with memory allocation issues but writing a new xml parser would be much more difficult so i wanted to use msxmlthe problemi was able to find enough examples on the internet to use msxml with the help of ccomptr smart pointer to avoid having to call release for each ixmldomnode manually ccombstr to convert c strings to the com format for strings and ccomvariant this 3 helpful classes are atl classes and need an include atlbasehproblem visual studio 2008 express the free version does not include atlsolutionuse comutilh and comdefh which include some simple helper classes bstr t replaces more or less ccombstr variant t replaces more or less ccomvariant com ptr t replaces indirectly ccomptr through the use of com smartptr typedefsmall exampleinclude msxmlhinclude comdefhinclude comutilh define some smart pointers for msxml com smartptr typedefixmldomdocument uuidofixmldomdocument ixmldomdocumentptr com smartptr typedefixmldomelement uuidofixmldomelement ixmldomelementptr com smartptr typedefixmldomnodelist uuidofixmldomnodelist ixmldomnodelistptr com smartptr typedefixmldomnamednodemap uuidofixmldomnamednodemap ixmldomnamednodemapptr com smartptr typedefixmldomnode uuidofixmldomnode ixmldomnodeptrvoid test msxml this program will use comcoinitializeexnull coinit multithreaded create parserixmldomdocumentptr pxmldochresult hr cocreateinstance uuidof domdocument null clsctx inproc server iid ixmldomdocument voidpxmldocpxmldocput validateonparsevariant falsepxmldocput resolveexternalsvariant falsepxmldocput preservewhitespacevariant false open filevariant bool bloadokstdwstring sfilename ltestfilexmlhr pxmldocload variant tsfilenamec str bloadok search for node testtagixmldomnodeptr pnodehr pxmldocselectsinglenode bstr tltesttag pnode read something bstr t bstrtexthr pnodeget textbstrtextgetaddrestdstring ssomething bstrtext i am finished with com do not call before all ixmldomnodeptr are out of scopecouninitialize,['c++'] +6868,is there a perl equivalent of pythons refindallrefinditer iterative regex results in python compiled regex patterns have a findall method that does the followingreturn all nonoverlapping matches of pattern in string as a list of strings the string is scanned lefttoright and matches are returned in the order found if one or more groups are present in the pattern return a list of groups this will be a list of tuples if the pattern has more than one group empty matches are included in the result unless they touch the beginning of another matchwhats the canonical way of doing this in perl a naive algorithm i can think of is along the lines of while a search and replace with the empty string is successful do suite i am hoping there is a nicer way thanks in advance,['python'] +6869,in what situation should the builtin operator module be used in python i am speaking of this modulefrom the articlethe operator module exports a set of functions implemented in c corresponding to the intrinsic operators of python for example operatoraddx y is equivalent to the expression xy the function names are those used for special class methods variants without leading and trailing are also provided for conveniencei am not sure i understand the benefit or purpose of this module,['python'] +6873,how do you run android instrumentation tests from eclipse currently i am running instrumentations tests from the command line this wayadb shell am instrument w comblahblahandroidtestinstrumentationtestrunneris there a way to run them from eclipse with automatic installation of the application,['android'] +6880,free code coverage tools in net for personal project i need a free code coverage tools in net for personal project ncover is bit expensive for person use,['.net'] +6883,how can i combine multiple rows into a commadelimited list in oracle i have a simple queryselect from countrieswith the following resultscountry namealbaniaandorraantiguai would like to return the results in one row so like thisalbania andorra antigua of course i can write a plsql function to do the job i already did in oracle 10g but is there a nicer preferably nonoraclespecific solution or may be a builtin function for this taski would generally use it to avoid multiple rows in a subquery so if a person has more then one citizenship i do not want herhim to be a duplicate in the listmy question is based on the similar question on sql server 2005updatemy function looks like thiscreate or replace function append field sqlstr in varchar2 sep in varchar2 return varchar2 isret varchar240 type cur typ is ref cursorrec cur typfield varchar240begin open rec for sqlstr loop fetch rec into field exit when recnotfound ret ret field sep end loop if lengthret 0 then return else return substrret1lengthretlengthsep end ifend,['sql'] +6887,any python olapmdx orm engines i am new to the mdxolap and i am wondering if there is any orm similar like django orm for python that would support olapi am a pythondjango developer and if there would be something that would have some level of integration with django i would be much interested in learning more about it,['python'] +6892,jquery append to fronttop of list i have this unordered listul litwoli lithreeliulis there a way i can prepend to the unordered list so that it ends up like thisul lioneli litwoli lithreeliulnotice the one is added to the fronttop of the list,['jquery'] +6894,detect closed pipe in redirected console output in net applications the net console class and its default textwriter implementation available as consoleout and implicitly in eg consolewriteline does not signal any error when the application is having its output piped to another program and the other program terminates or closes the pipe before the application has finished this means that the application may run for longer than necessary writing output into a black holehow can i detect the closing of the other end of the redirection pipea more detailed explanation followshere are a pair of example programs that demonstrate the problem produce prints lots of integers fairly slowly to simulate the effect of computationusing systemclass produce static void main for int i 0 i 10 i systemthreadingthreadsleep100 added for effect consolewritelinei consume only reads the first 10 lines of input and then exitsusing systemclass consume static void main for int i 0 i 10 i consolereadline if these two programs are compiled and the output of the first piped to the second like soproduce consume it can be observed that produce keeps on running long after consume has terminatedin reality my consume program is unixstyle head and my produce program prints data which is costly to calculate i would like to terminate output when the other end of the pipe has closed the connectionhow can i do this in neti know that an obvious alternative is to pass a commandline argument to limit output and indeed that is what i am currently doing but i would still like to know how to do this since i want to be able to make more configurable judgements about when to terminate reading eg piping through grep before headupdate it looks horribly like the systemio consolestream implementation in net is hardcoded to ignore errors 0x6d error broken pipe and 0xe8 error no data that probably means i need to reimplement the console stream sigh,"['c#', '.net']" +6896,command line or equivalent tools for net development spending most of my time in visual studio and using all the ide tools i wish i could spend more time using either of the followingthe command window in visual studiocmdexecygwin mingwpowershellscriptswhat are your favorite and essential commands to type in opposed to keyboard shortcuts or clicking around,['.net'] +6898,boostbind with functions that have parameters that are references i noticed that when passing reference parameters to boost bind those parameters would not act like references instead boost creates another copy of the member and the original passed in variable remains unchanged when i change the references to pointers everything works okmy question isis it possible to get references to work or at least give a compiling error when it tries to use reference parameters,['c++'] +6903,javautillogginglogger does not respect javautillogginglevel in plain java se 6 environmentlogger l loggergetloggernamelesslsetlevellevelalfinesomemessagenothing shows up in eclipse console linfo and above works just fine but anything below fine just does not seem to work whats could be wrongtia,['java'] +6904,how to select only the records with the highest date in linq i have a table lasttraces with the following fieldsid accountid version downloadno datethe data looks like this280921524010717822009040473120090120 13102202809461615010717822009040769620090120 13113802809595317010717822009040769520090120 1310180281011524010717822009040474020090120 14102202810361615010717822009040769020090120 14113802810495317010717822009040771020090120 1410180how can i in linq to sql only get the last lasttrace of every accountid the one with the highest date,"['c#', '.net']" +6909,how do i resolve lnk1104 error with boost filesystem library in mscv i am having trouble getting my project to link to the boost version 1370 filesystem lib file in microsoft visual c 2008 express edition the filesystem library is not a headeronly library i have been following the getting started on windows guide posted on the official boost web page here are the steps i have takeni used bjam to build the complete set of lib files usingbjam builddircprogram filesboostbuildboost toolsetmsvc buildtypecompletei copied the libs directory located in cprogram filesboostbuildboostboostbinv2 to cprogram filesboostboost 1 37 0libsin visual c under project properties additional library directories i added these pathscprogram filesboostboost 1 37 0libscprogram filesboostboost 1 37 0libsfilesystembuildmsvc90expressdebuglinkstaticthreadingmultii added the second one out of desperation it is the exact directory where libboost systemvc90mtgd1 37lib residesin configuration properties cc general additional include directories i added the following pathcprogram filesboostboost 1 37 0then to put the icing on the cake under tools options vc directories library files i added the same directories mentioned in step 3despite all this when i build my project i get the following errorfatal error lnk1104 cannot open file libboost systemvc90mtgd1 37libadditionally here is the code that i am attempting to compile as well as a screen shot of the aformentioned directory where the assumedly correct lib file residesinclude boostfilesystemhpp includes all needed boostfilesystem declarationsinclude iostream for stdcoutusing boostfilesystem for ease of tutorial presentation a namespace alias is preferred practice in real codeusing namespace stdint main cout hello world endl return 0,['c++'] +6913,jython and python modules i have just started using the pythoninterpreter from within my java classes and it works great however if i try to include python modules re htmlparser etc i am receiving the following exception for reexception in thread main traceback innermost last file line 1 in importerror no module named rehow could i make the classes from the jython jar see the modules python has available,"['java', 'python']" +6919,hide text using css i have a tag in my html like thish1my website title hereh1using css i want to replace the text with my actual logo i have got the logo there no problem via resizing the tag and putting a background image in via css however i cannot figure out how to get rid of the text i have seen it done before basically by pushing the text off the screen the problem is i cannot remember where i saw it,['css'] +6920,customizing an admin form in django while also using autothiscover i want to modify a few tiny details of djangos builtin djangocontribauth module specifically i want a different form that makes username an email field and email an alternate email address i would rather not modify auth any more than necessary a simple form change seems to be all that is neededwhen i use autothiscover with a customized modeladmin for auth i wind up conflicting with auths own admin interface and get an already registered errorit looks like i have to create my own admin site enumerating all of my models it is only 18 classes but it seems like a dry problem every change requires both adding to the model and adding to the customized admin siteor should i write my own version of autothiscover with exclusions to essentially import all the admin modules except auth,['python'] +6926,aspnet http server push to client whats the best way to push info from a server to a web client i know it is possible to setup sockets with silverlight and flash but i want to stay way from those two technologiesgmail seems to do a great job of polling the servers for updated emails and even their chat programs work great all working in my web browser any ideas on the best way to do something like this but using aspneteditif i have to poll i would like to poll the server every 2 or 3 seconds so i am not sure how to do this without bringing the web server to it is knees under heavy usage,['asp.net'] +6927,how i do to force the browser to not store the html form field data when typing in html forms browsers like firefox or ie store the values sometimes quietly so when typing in another webforms the browser smartly suggest the same information another method to show the dropdown list is doubleclicking an empty textboxin a ecommerce website the customer type the credit card number and another sensitive information how i do to avoid or block the browser to store that sensitive informationanother worry is about tampered form data stored by a malware by example then the customer can select this contaminated data and compromise the siteregards,['asp.net'] +6929,why nsuserdefaults failed to save nsmutabledictionary in iphone sdk i would like to save an nsmutabledictionary object in nsuserdefaults the key type in nsmutabledictionary is nsstring the value type is nsarray which contains a list of object which implements nscoding per document nsstring and nsarray both are conform to nscodingi am getting this error nsuserdefaults setobject forkey attempt to insert nonproperty value of class nscfdictionaryany solution for this,"['iphone', 'objective-c']" +6936,usage of slots what is the purpose of slots in python a especially with respect to when would i want to use it and when not,['python'] +6944,how do i create email with css and images from rails how do you create and send emails from rails application that contain images and proper formatting like the ones you get from facebook and like,"['ruby-on-rails', 'css']" +6947,how to pass an array size as a template with template type my compiler behaves oddly when i try to pass a fixedsize array to a template function the code looks as followsinclude algorithminclude iostreaminclude iteratortemplate typename tsize tsize nvoid ftsize arrayn stdcopyarray array n stdostream iteratortsizestdcout stdcout stdendlint main int x 1 2 3 4 5 unsigned int y 1 2 3 4 5 fx fy line 15 see the error messageit produces the following compile error in gcc 412testcpp15 error size of array has nonintegral type atsizeatestcpp15 error invalid initialization of reference of type aunsigned int 1a from expression of type aunsigned int 5atestcpp6 error in passing argument 1 of avoid ftsize n with tsize unsigned int tsize and tsize5anote that the first call compiles and succeeds this seems to imply that while int is integral unsigned int is nothowever if i change the declaration of my above function template totemplate typename tsize unsigned int nvoid ftsize arraynthe problem just goes away notice that the only change here is from tsize n to unsigned int nsection dcltypesimple in the final draft isoiec fthis 148821998 seems to imply that an integral type is either signed or unsignedthe signed specifier forces char objects and bitfields to be signed it is redundant with other integral typesregarding fixedsize array declarations the draft says dclarrayif the constantexpression exprconst is present it shall be an integral constant expression and its value shall be greater than zeroso why does my code work with an explicit unsigned size type with an inferred signed size type but not with an inferred unsigned size typeedit serge wants to know where i would need the first version first this code example is obviously simplified my real code is a bit more elaborate the array is actually an array of indicesoffsets in another array so logically the type of the array should be the same as its size type for maximum correctness otherwise i might get a type mismatch eg between unsigned int and stdsize t admittedly this should not be a problem in practice since the compiler implicitly converts to the larger of the two typesedit 2 i stand corrected thanks litb size and offset are of course logically different types and offsets into c arrays in particular are of type stdptrdiff t,['c++'] +6949,how to change the auto growth size ms sql server 2005 in ms sql server 2005 by default 1mb auto growth is there how can i change it to whatever i needthanxambanna,['sql'] +6957,in jquery is there way for slidedown method to scroll the page down too the slidedown applied to a div does the slidedown but does not scroll the page down and the div slided down div remains hidden from view is there a way to scroll the page down as well so the user can view the div,['jquery'] +6958,aspnet membershipdeleteuser in testing the user on a db i have used was a big jefe in production he only has executewhen i calledmembershipdeleteuseruserin testing it workedi try the same in production and i get thisthe delete statement conflicted with the reference constraint fk aspnet us useri 37703c52 the conflict occurred in database testing table dboaspnet usersinroles column useridin my seargles searches on google i came across this linkwhere the dude was saying error the delete statement conflicted with the reference constraint fk aspnet me useri 15502e78 the conflict occurred in database yourdbname table dboaspnet membership column useridtook me a while to find a solution to this across multiple sites and options as the error and possible solutions were rather misleading turns out at least in my case it was a problem with permissions on the membership database the user i am using to connect had access to view the membership details within the database itself but as part of the aspnet users deleteuser stored procedure it selects from the sysobjects table the membership connection user apparently did not have sufficient rights to do that select so the overall delete failed the fix for me was to add the user to the aspnet membership fullaccess role for the membership databasebut when i did that it did not work anyone have any ideas on how to deal with this,['asp.net'] +6963,ruby string mutability this may be a bit of a nooby question i have been trying to get better at ruby recently and started reading the fantastic the ruby programming language something that was mentioned is that string literals are considered mutable so in a loop it is better to use a variable then a literal as a new string will get instantiated at every iterationmy question is why at first i thought it was because of interpolation but symbols are immutable and they support interpolation coming from a static background it does not really make much sense to meeditafter reading thenduks answer i think i may have it afaik languages like java or c do not have destructive string methods they use upcase but not upcase because of things like upcase or the literal cannot be immutablenot 100 sure on that the other possibility is that it is a compiletime interning that happens which is something that just does not happen in a scripting language,['ruby'] +6965,correct way to use actions to create menus toolbars and other components in java the naive way of writing building a menu in a java swing app is to do something likejmenu filemenu new jmenufilejmenuitem openitem new jmenuitemopenopenitemaddactionlistenernew actionlistener action listener stuff filemenuaddmenuitemopenitema more experienced developer will recognize that actions can be accessed through a variety of mechanisms menus toolbar buttons maybe even other workflows in the system that person is more likely to writeaction openaction new abstractactionopenactionsetnameopenopenactionaddactionlistenernew actionlistener action listener stuff jmenuitem openitem new jmenuitemopenactionmy question is what is the best way to manage these action objects so they can be used across menus toolbars etc create a factory class that returns specific actions declare all of the actions as private static final action in some utility class take advantage of a java application framework something else,['java'] +6968,how do you create a daemon in python searching on google reveals x2 code snippets the first result is to this code recipe which has a lot of documentation and explanation along with some useful thiscussion underneath however another code sample whilst not containing so much documentation includes sample code for passing commands such as start stop and restart it also creates a pid file which can be handy for checking if the daemon is already running etcthese samples both explain how to create the daemon are there any additional things that need to be considered is one sample better than the other and why,['python'] +6970,why is the destructor ignored in this code the following code demonstrates a weird problem i have in a turbo c explorer project one of the three stack objects in dd is not destroyed after going out of scope this only happens if compiled in release mode the auto ptrs a and b are of different types and the exception thrown does not inherit from stdexception it appears to work just fine in vc 2005 and c builder 2009 i did install the bds2006 update 2 the hotfix rollup and hotfix 12is it my code or the compiler do you know of a fix not being able to reliably use auto ptr in a vcl project would be quite inconvenient include memoryinclude stdexceptinclude iostreamtypedef stdexception my error will work fine if replaced with line belowclass my error public stdexception class a class b class cpublic cint id id id stdcout cc id stdendl c stdcout cc id stdendl private int id class dpublic d c c11 c c22 c c33 throw my error private stdauto ptra a stdauto ptrb b will work fine if replaced with line below stdauto ptra b stdauto ptrc c see expected outputpragma argsusedint mainint argc char argv try d d catch stdcout caught exception stdendl return 0expectedcc 1cc 2cc 3cc 3cc 2cc 1caught exceptiongotcc 1cc 2cc 3cc 2cc 1caught exceptiongot with line stdauto ptrc c uncommentedcc 1cc 2cc 3cc 1caught exceptionedit made suggested changesedit 2 i just tested it with c builder 2007 110290210471 which shows the same problem the release configuration works as soon as i check the debug information box in project options c compiler debugging it surprises me that the executable gets smaller with debug information enabled down to 315 kb from 395 kb edit 3 in turbo c explorer c builder 2006 100228842451 the release configuration works if i uncheck the inline function expansion vi box in project options c compiler debugging replacing the first line include memory with the following code makes it work too pragma option push viinclude memorypragma option pop,['c++'] +6971,tool for diagnosing memory leaks in net aspnet application we need a tool to detect easily memory leaks in an aspnet application we have an application which consumes lot of memorythanks,"['.net', 'asp.net']" +6977,should mvc controller be in separate dll i have created a net winforms mvc the controller and view are in the same exe model is in a set of dlls that get used by several groups the mvc is very explicit model knows nothing of controller and controller knows nothing of view i am thinking to put the controller in its own dll so that it can be unit tested highly unlike someone will reuse the controller unit testing is the only reason i have for the move into a dllconceptually should the controller always be in the same assembly as the view what are reasons foragainst keeping them together,['.net'] +6981,should exception messages be globalized i am working on a project and i am just starting to do all the work necessary to globalize the application one thing that comes up quite often is whether to globalize the exception messages but ensuring that stringformat uses cultureinfocurrentculture instead of cultureinfoinvariantculture additionally this would mean that exception messages would be stored in resource files that can be marked as culturespecificso the question is should exception messages be globalized or should be be left in either the invariantculture or the authors country in my case enus,['c#'] +6984,convert pixels to inches and vice versa in c i am looking to convert pixes to inches and vice versa i understand that i need dpi but i am not sure how to get this information eg i do not have the graphics object so that is not an optionis there a way,['c#'] +6985,boost vs ace c cross platform performance comparison i am involved in a venture that will port some communications parsing data handling functionality from win32 to linux and both will be supported the problem domain is very sensitive to throughput and performance i have very little experience with performance characteristics of boost and ace specifically we want to understand which library provides the best performance for threading can anyone provide some data documented or wordofmouth or perhaps some links about the relative performance between the twoeditthanks all confirmed our initial thoughts well most likely choose boost for system level crossplatform stuff,['c++'] +6988,defining an entity framework 11 association i am trying to define a 11 association between two entities one maps to a table and the other to a view using definedquery in an entity framework model when trying to define the mapping for this in the designer it makes me choose the 1 table or view to map the association to what am i supposed to choose i can choose either of the two tables but then i am forced to choose a column from that table or view for each end of the relationship i would expect to be able to choose a column from one table for one end of the association and a column from the other table for the other end of the association but there is no way to do thishere i have chosen to map to the dw wf claiminfo view and it is forcing me to choose two columns from that view one for each end of the relationshipi have also tried defining the mapping manually in the xml as followsassociationsetmapping nameentity1entity2 typenameclaimsmodelentity1entity2 storeentitysetentity1 endproperty nameentity2 scalarproperty namedocument columnnamedocument endproperty endproperty nameentity1 scalarproperty namepk documentid columnnamepk documentid endpropertyassociationsetmappingbut this giveserror 2010 the column document specified as part of this msl does not exist in metadataworkspaceseems like it still expects both columns to come from the same table which does not make sense to mefurthermore if i select the same key for each end egassociationsetmapping nameentity1entity2 typenameclaimsmodelentity1entity2 storeentitysetentity1 endproperty nameentity2 scalarproperty namedocument columnnamepk documentid endproperty endproperty nameentity1 scalarproperty namepk documentid columnnamepk documentid endpropertyassociationsetmappingi then geterror 3021 problem in mapping fragment starting at line 675 each of the followingcolumns in table assignedclaims is mapped to multiple conceptual side properties assignedclaimspk documentid is mapped to assignedclaimdw wf claiminfodw wf claiminfodocument assignedclaimdw wf claiminfoassignedclaimpk documentidwhat am i not getting,['.net'] +6992,what are the dimensions file types and ppi resolution of an ios app icon what are the specifications for the icons required by apple for a custom iphone application published57x57 png no transparency no layers 72 ppi512x512 tiff or jpeg no transparency no layers 72 ppinote iphone os applies rounded corners optionally shine and other effectsalso have a large version of your logo with the name of the application in case apple contacts you needing a version for marketing purposes,"['iphone', 'ios']" +7014,comparing two integers without any comparison is it possible to find the greatest of two integers without any comparison i found some solutions ifab if a is less than b then division result will be zero cout b is greater than aelse if ab we know a is greater than or equal to b now check whether they are equal cout a and b are equalelse cout a is greater than bbut ifc or ifc is a comparison to zero in addition it does not work for negative numbers in fact i need a solution that avoids any if statement instead i should use switch statements and arithmetic operators thanx,['c++'] +7021,is there a way to access an iterationcounter in javas foreach loop is there a way in javas foreach loopforstring s stringarray dosomethingwithsto find out how often the loop has already been processedaside from using using the old and wellknown forint i0 i boundary i loop is the constructint i 0forstring s stringarray dosomethingwiths ithe only way to have such a counter available in a foreach loop,['java'] +7022,array functions in jquery i am using jquery in my web application i want to use arrays but i am not able to find out functions for arrays add remove or append elements in array in jquery is there any link related to jquery array functions which will explain the jquery array functions,"['javascript', 'jquery']" +7023,primitive type short casting in java i have a question about the primitive type short in java i am using jdk 16 if i have the following short a 2short b 3short c a bthe compiler does not want to compile it says that it cannot convert from int to short and suggests that i make a cast to short so thisshort c short a breally works but my question is why do i need to cast the values of a and b are in the range of short the range of short values is 32768 32767i also need to cast when i want to perform the operations i have not checked for othersif i do the same for primitive type int i do not need to cast aabb to int the following works fineint aa 2int bb 3int cc aa bbi thiscovered this while designing a class where i needed to add two variables of type short and the compiler wanted me to make a cast if i do this with two variables of type int i do not need to cast thank you very much in advancea small remark the same thing also happens with the primitive type byte so this worksbyte a 2byte b 3byte c byte a bbut this notbyte a 2byte b 3byte c a bfor long float double and int there is no need to cast only for short and byte values,['java'] +7024,whats the idiomatic python equivalent to djangos regroup template tag i can think of a few ways of doing it with loops but i would particularly like to know if there is a neat oneliner,['python'] +7030,why are there many jre implementations i was wonderingthere is suns jre ibms jre beas jre oracles jre and some more less know jres in the marketwhy is there so many jre implementations does the fact that sun opened the java platforms mean that there will be one open jre jdk or are we going towards what happened with linux and its many thistributions,['java'] +7045,trim is not part of the standard cc library is it me or are there no standard trim functions in the c or c library is there any single function that acts as a trim if not can anyone tell me why trim is not part of the standard library i know trim is in boostmy trim code isstdstring trimconst stdstring str size t s strfind first not of nrt size t e strfind last not of nrt if stringnpos s stringnpos e return else return strsubstrs es1test cout trim nrrn rn text herenwith return nrrn rn editi mostly wanted to know why it wasnt in the standard library bobbyshaftoe answer is great,['c++'] +7047,nested accordion menu in jquery i have a menu implemented using a set of nested accordions 1 and 2 each with elements a and bi would like to implement the following logicwhen i click 1a i will get the data of 1a and two submenu 2a2bwhen i click 2a 2b i will get the data of each respectivelythe problemdesired resulti only want to thisplay the nthmost child element for the last click collapsing all othersupon initialization only 1a and 1b should be visiblecurrent resultclicking on 1b then on 2b 1b is still fully visiblejavascript codedocumentreadyfunction acc1accordion activeuiaccordionleft alwaysopen false autoheight false header aacc1 clearstyle true acc2accordion alwaysopen false autoheight false header aacc2 clearstyle true htmlul idacc1 classuiaccordioncontainer li div classuiaccordionleftdiv a classuiaccordionlink acc11a span classuiaccordionrightspan a div data of 1abr data of 1abr data of 1abr div div ul classuiaccordioncontainer idacc2 li div classuiaccordionleftdiv a classuiaccordionlink acc22a span classuiaccordionrightspan a div data of 2abr data of 2abr data of 2abr div li li div classuiaccordionleftdiv a classuiaccordionlink acc22b span classuiaccordionrightspan a div data of 2bbr data of 2bbr data of 2bbr div li ul div li li div classuiaccordionleftdiv a classuiaccordionlink acc11b span classuiaccordionrightspan a div data of 1bbr data of 1bbr dta of 1b br div liul,['jquery'] +7048,detect os language from c is there a way to detect the language of the os from within a c class,['c#'] +7051,enum tostring with user friendly strings my enum consists of the following valuesprivate enum publishstatusses notcompleted completed errori want to be able to output these values in a user friendly way thoughi do not need to be able to go from string to value again,['c#'] +7060,wcf service throttling lets assume that i am dealing with a service that involves sending large amounts of dataif i implement this with wcf will wcf throttle the service based on how much memory each request takes to serve or will i be getting continuous out of memory exceptions each time i receive a large number of hits to my servicei am quite curious as to dealing with this problem outside of wcf i am still a bit new to service development,"['c#', '.net']" +7069,send message from one running console app to another i have one console app that is doing some lengthy syncing to an ftp serveranother console app prepares a local filesystem with some needed updated filesthen the second one will wait for the first one to finish before swapping a final directory name so it becomes visible on the webi searched for the best way to make the syncing app to communicate to the second app that it is finished it is job it looks like using data copy for ipc is the best suited solution for this question is two foldam i right is there a more straight forward way to get to the same resultis there a managed net way to do this,"['c#', '.net']" +7071,is c a superset of c is c a superset of c in anyway like objectivec or c is there a way to compile c online with constructs such compiler flags,"['c#', 'c']" +7076,code to calculate median of five in c note please do not interpret this as homework question this is just a thing i curious to know the median of five is sometimes used as an exercise in algorithm design and is known to be computable using only 6 comparisonswhat is the best way to implement this median of five using 6 comparisons in c all of my attempts seem to result in awkward code i need nice and readable code while still using only 6 comparisonspublic double medianoffivedouble a double b double c double d double e return medianreturn cnote i think i should provide the algorithm here tooi found myself not able to explain the algorithm clearly as azereal did in his forum post so i will reference his post here from csactionthisplaynum1061827085well i was posed this problem in one of my assignments and i turned to this forum for help but no help was here i eventually found out how to do itstart a mergesort with the first 4 elements and order each pair 2 comparisonscompare the two lower ones of each pair and eliminate the lowest one from the possibilities 3 comparisonsadd in the 5th number set aside to the number without a pair and compare the two 4 comparisonscompare the two lowest of the two new pairs and eliminate the lower one 5 comparisonscompare the one by itself and the lower of the last pair and the lower number is the medianthe possible median is within the parentesis5432154 32 2 comparisons45 23 1 42 3 comparisons245 3 113 4 comparisons245 1341 5 comparisons1245 343 6 comparisons12345 three is the medianedit as your request and to prevent myself from getting more downvotes this are c code i wrote to find median of five do not mind it is awkwardnessdouble stagegeneratormedianoffivedouble n1 double n2 double n3 double n4 double n5 double a n1 b n2 c n3 d n4 e n5 double tmp makes a b and b d ifb a tmp a a b b tmp ifd c tmp c c d d tmp eleminate the lowest ifc a tmp b b d d tmp c a gets e in a e makes a b and b d ifb a tmp a a b b tmp eliminate another lowest remaing abd ifa c tmp b b d d tmp a c ifd a return d else return ait should be more compact is not it editas pablito pointed out in his answer the builtin listsort cannot fulfill this requirement since it uses up to 13 comparisons,['c#'] +7079,limiting access to a wcf rest webhttpbinding service using the aspnet membership provider i have found a lot of material on the web about using the aspnet membership provider with the wshttpbindings but i have not seen any reference to using it with webhttpbindingsi am looking for a system that will work in two scenariosthe user is logged into an aspnet website and the website is making calls to the servicethe user accesses the service directly via restis this possible using the built in framework ie just through configuration if so how do i configure the service and how does the user pass the credentials to the rest service,['asp.net'] +7081,is bcrypt a good hashing algorithm to use in c where can i find it i have read that when hashing a password many programmers recommend using the bcrypt algorithm i am programming in c and is wondering if anyone knows of a good implementation for bcrypt i found this page but i do not really know if it is bogus or not what should i be aware of when choosing a password hashing scheme is bcrypt a good implementation,['c#'] +7094,how to add a tabbar to navigationcontroller based iphone app i have a simple navigationcontroller based app the main window shows a tableview and selecting an item loads a subview i used interface builder for ui viewsnow i want to add a tabbar to the app where do i put it do i need a tabbarcontroller should it go in the mainwindowxib or rootviewcontrollerxibhow do i tie it together with my navigationcontroller,['iphone'] +7101,how do i convert a string to a double in python i would like to know how to convert a string containing digits to a double,['python'] +7106,can you tell on runtime if youre running java from within a jar i have an application that some of my users run from eclipse and others run it by using a jar filei want some actions to be done when running from within the jar but i do not want them to be done when running from eclipseis there a way to know on runtime whether the current application is running from within a jarthanksdikla,['java'] +7114,implementing and using the icommand interface mvvm although i deeply fell in love with the mvvm pattern there seem to be a lot of problems i cannot yet figure out for myselfi wonder what the parameters of the methods of the icomamnd interface are good foreg void executeobject parameteri tie my view to the view model like thisbutton commandbinding somecommand and so parameter will always be nullany hints are welcomethanksupdatedarn one minute after i posted this question i found the answer on stackoverflow obviously controls do have a commandparameter property,['.net'] +7125,why is systemobject not abstract in net i know it is commonly used as a lock object but is that really sufficient reasonwhat is the meaning ofobject o new objectan nonabstract class is something that represents actual objects asdasdf is a string what actual instance can there be of object class it does not make sense oopwise my question is if there is some practical reason for its existence besides being used as a lock object,['.net'] +7138,restoring mysql database from physical files is it possible to restore a mysql database from the physical database files i have a directory that has the following file typesclientfrmclientmydclientmyi but for about 20 more tablesi usually use mysqldump or a similar tool to get everything in 1 sql file so what is the way to deal with these types of files,['mysql'] +7140,mstestexe not finding appconfig i am currently trying to run mstestexe from ncover but i believe the question could apply generally to running mstestexe from the command lineif i have the noisolation argument then mstestexe appears to find and use the appconfig as expected without it ncover does not capture any coverage information from my research so far it seems ncover needs noisolation so the question is how to get my config files to work when that argument is passedmy ncover settings areapplication to profilecprogram files x86microsoft visual studio 90common7idemstestexeworking foldercdocuments and settingsmyprofilemy documentsvisual studio 2008projectsxyzxyzcoretestbindebugapplication argumentsnoisolation testcontainercdocuments and settingsmyprofilemy documentsvisual studio 2008projectsxyzxyzcoretestbindebugxyzcoretestdllupdate i added a trace showing that my config is not surprisingly trying to read from cprogram files x86microsoft visual studio 90common7idemstestexeconfigupdate 2 if at all possible i do not want to edit mstestexeconfig that just is not terribly portable,['.net'] +7144,calling a remote com servicedcomponent from a c client i have a serviced component installed in a com server application i want to create an instance from a remote client the client needs to be able to specify the server machines name dynamically how do i do thisi tried using activator xsltranscomponentxsltransformeractivatorgetobject typeofxsltranscomponentxsltransformer servername but i get thissystemruntimeremotingremotingexception cannot create channel sink to connect to url server an appropriate channel has probably not been registered at systemruntimeremotingremotingservicesunmarshaltype classtoproxy string url object datado i need to register a channel if so howanother idea is to use marshallbindtomoniker but how do i specify a moniker for a remote object hosted on com on server x,['.net'] +7157,how could i implement autocompletion using swing i am interested in providing an autocompletion box in a jframe the triggering mechanism will be based on mnemonics i think but i am not really sure what to use for the autocompletion box i would like results to be filtered as the user presses keyshow would you implement this some sort of jframe or a jpopupmenu i would like to know how this is implemented so please do not post links to available jcomponents,['java'] +7158,portable interoperable wcf contracts i was wondering if anybody out there had some good tipsdos and do nots for designing wcf contracts with a mind for webservice interoperability both in terms of older microsoft web service technologies eg wse and nonmicrosoft technologies such as java calling wcf web services for example are there any special rules that need to be taken into account when exposing datetime as a type in your contract how about dictionaries and hashtables what are the issues you might run into with the various bindings available,['.net'] +7160,keys values functionality to iterators in c i know this questions has come up in various guises before but this is slightly differenti have a class which contains a stdmap although i wish to use the map for other purposes inside the class externally i want to expose an iterator adapter to just the values inside the map ie the second item in the stdpairfor example in python i might do something like thisdef iter self return self dictitervalueshow do i go about doing this in c hiding the implementation inside the classthanksdan,['c++'] +7176,how to serialize an exception object in c i am trying to serialize an exception object in c however it appears that it is impossible since the exception class is not marked as serializable is there a way to work around thatif something goes wrong during the execution of the application i want to be informed with the exception that occurred my first reflex is to serialize it,"['c#', '.net']" +7177,python shelve module question does the python shelve module have any protection built in to make sure two processes are not writing to a file at the same time,['python'] +7179,why does c designergenerated code like form1designercs play havoc with subversion my workshop has recently switched to subversion from sourcesafe freeing us from automatic locks this led to concurrent editing of the forms which is wonderful but when multiple developers commit their changes the code files created by the designer all the files named theformnamedesignercs cause conflicts which are very difficult to resolveas far as i can tell this is because the code generated by the designer is heavily rearranged whenever the user modifies it no matter how little the actual change really didhow do i make these conflicts easier to resolve is there some way to tell the designer to modify the code lesshow do you the experienced c teams deal with concurrent modification of a form,['c#'] +7189,serving faviconico in aspnet mvc what is the finalbest recommendation for how to serve faviconico in aspnet mvci am currently doing the following adding an entry to the very beginning of my registerroutes method routesignoreroutefaviconicoplacing faviconico in the root of my application which is also going to be the root of my domaini have two questions is there no way to put faviconico somewhere other than the root of my application its pretty icky being right there at the same level as content and controllersis this ignoreroutefaviconico statement sufficient or should i also do the following as thiscussed in a blog post from phil haack i am not aware of ever having seen a request to faviconico in any directory other than the root which would make this unnecessary but its nice to know how to do itroutesignoreroutefavicon new faviconfaviconico,['asp.net'] +7194,best practice for using java system properties our code uses a lot of system properties eg javaiotmpdir userhome username etc we do not have any constants defined for these anywhere and neither does java i think or any other clever thing for dealing with them so they are in plain text littered throughout the codestring tempfolderpath systemgetpropertyjavaiotmpdirhow is everyone using system properties,['java'] +7201,allow user to sort columns from a linq query in a datagridview i cannot quite work out how to allow a datagridview populated at runtime to sort when users click on the column headers where a linq from xml query is the datasource via a bindingsource dim queryreorder from q in query where 0 qqualifier cmbtsstakevaluetext 01 order by qqualifier descending select q dim bs as new bindingsource bsdatasource queryreorder dgfindmatchdatasource bssome of the datagridviews properties are sortnothingstringsortpropertynothingsystemcomponentmodelpropertydescriptorsupportsadvancedsortingfalsebooleansupportschangenotificationtruebooleansupportsfilteringfalsebooleansupportssearchingfalsebooleansupportssortingfalsebooleanis there a simple solution that will allow a user to be able to sort these values by clicking the column headerthanks,['.net'] +7202,winforms acceptbutton not working ok this is bugging me and i just cannot figure out what is wrongi have made two forms first form just has a simple button on it which opens the other as a dialog like sousing form2 f new form2 if fshowdialog dialogresultok messageboxshownot ok else messageboxshowokthe second which is that form2 has two buttons on it all i have done is to set the forms acceptbutton to one and cancelbutton to the other in my head this is all that should be needed to make this work but when i run it i click on the button which opens up form2 i can now click on the one set as cancelbutton and i get the not ok message box but when i click on the one set as acceptbutton nothing happensthe initializecomponent code of form2 looks like thisprivate void initializecomponent thisbutton1 new systemwindowsformsbutton thisbutton2 new systemwindowsformsbutton thissuspendlayout button1 thisbutton1location new systemdrawingpoint211 13 thisbutton1name button1 thisbutton1size new systemdrawingsize75 23 thisbutton1tabindex 0 thisbutton1text button1 thisbutton1usevisualstylebackcolor true button2 thisbutton2dialogresult systemwindowsformsdialogresultcancel thisbutton2location new systemdrawingpoint130 13 thisbutton2name button2 thisbutton2size new systemdrawingsize75 23 thisbutton2tabindex 1 thisbutton2text button2 thisbutton2usevisualstylebackcolor true form2 thisacceptbutton thisbutton1 thisautoscaledimensions new systemdrawingsizef6f 13f thisautoscalemode systemwindowsformsautoscalemodefont thiscancelbutton thisbutton2 thisclientsize new systemdrawingsize298 59 thiscontrolsaddthisbutton2 thiscontrolsaddthisbutton1 thisname form2 thistext form2 thisload new systemeventhandlerthisform2 load thisresumelayoutfalsei have done nothing else than add those two buttons and set the acceptbutton and cancelbutton why does not it work,['c#'] +7207,c compare two generic values possible duplicatecanat operator be applied to generic types in c i have coded something like thispublic bool isdatachanged t value1 getvalue2 t value2 getvalue1 return valueindb valuefromviewright now the function does not compile with the error operator cannot be applied to operands of type t and t what do i have to do to make this function work,['c#'] +7213,calculate exponential moving average in python i have a range of dates and a measurement on each of those dates i would like to calculate an exponential moving average for each of the dates does anybody know how to do thisi am new to python it does not appear that averages are built into the standard python library which strikes me as a little odd maybe i am not looking in the right placeso given the following code how could i calculate the moving weighted average of iq points for calendar datesfrom datetime import datedays date200811 date200812 date200817iq 110 105 90there is probably a better way to structure the data any advice would be appreciated,['python'] +7214,with numbers another color ol litestli litestliolwill show astesttesti want to have numbers coloured and text blacki can edit the css but i do not have access to the html,"['html', 'css']" +7217,which java mvc frameworks integrate easily with stringtemplate it is hard to see how stringtemplate integrates easily or not with popular java web mvc frameworkswhich java mvc frameworks integrate easily with stringtemplatea good answermentions one solution to integrate with a frameworkincludes a link to something useful and applicable likea tutorialor documentationor a reference to source codefreeand open source or public domainreadersvoters please vote for a solution if you know it is true and greatin the scope of this question i am not interested in any other templating engine than stringtemplate,['java'] +7219,context agnostic javascript testing framework i am looking for a javascript testing framework that i can easily use in whatever context be it browser console xul etcis there such a framework or a way to easily retrofit an existing framework so its context agnosticedit the testing framework should not be tied to any other framework such as jquery or prototypejs and should not depend on a dom or document object being present i am looking for something to test pure javascript,['javascript'] +7223,vertically align text next to an image why would not verticalalign middle work and yet verticalalign top does workdiv img stylewidth30pxheight30px span styleverticalalignmiddledoes not workspandiv,['css'] +7224,hql row identifier for pagination does anyone know if hql has a keyword to identify rows such as rowid or rownumi would like to implement pagination with hql but i am not able to use setmaxresult or setfirstresult because i do not work with the session object directly and therefore do not use the query object but simply create my query as a string and use the find method i tried using limit and offset in my query but hql seems to be ignoring these keywords and is returning the whole result to me no matter whati am also not able to use hibernate criteria because it does not have support for the having clause that appears in my querymy last resort is to restrict the result set using the rownumrowid keyword does anyone else have any other suggestions,['java'] +7227,import csv fileexcel into sql database aspnet i am starting a project with aspnet visual studio 2008 sql 20 2005 in future using cthe tricky part for me is that the existing db schema changes often and the import files columns will all have to be matched up with the existing db schema since they may not be one to one match on column names there is a lookup table that provides the tables schema with column names i will usei am exploring different ways to approach this and need some expert advice is there any existing controls or frameworks that i can leverage to do any of thisso far i explored fileupload net control as well as some 3rd party upload controls to accomplish the upload such as slickupload but the files uploaded should be 500mbnext part is reading of my csv excel and parsing it for thisplay to the user so they can match it with our db schema i saw csvreader and others but for excel its more difficult since i will need to support different versionsessentially the user performing this import will insert andor update several tables from this import file there are other more advance requirements like record matching but and preview of the import records but i wish to get through understanding how to do this firstupdate i ended up using csvreader with lumenworksframework for uploading the csv files,"['c#', 'asp.net']" +7229,what are some common uses for python decorators while i like to think of myself as a reasonably competent python coder one aspect of the language i have never been able to grok is decoratorsi know what they are superficially i have read tutorials examples questions on stack overflow and i understand the syntax can write my own occasionally use classmethod and staticmethod but it never occurs to me to use a decorator to solve a problem in my own python code i never encounter a problem where i think hmmthis looks like a job for a decoratorso i am wondering if you guys might offer some examples of where youve used decorators in your own programs and hopefully i will have an aha moment and get them,['python'] +7235,jsp template inheritance coming from a background in django i often use template inheritance where multiple templates inherit from a common base is there an easy way to do this in jsp if not is there an alternative to jsp that does this besides django on jython that is base templatehtml body block content endblock bodyhtmlbasic content extends base template block content h1 contenttitle fills in a variableh1 contentbody fills in another variable endblock will render as follows assuming that contentitle is insert title here and contentbody is insert body herehtml body h1insert title here fills in a variableh1 insert body here fills in another variable bodyhtml,['java'] +7245,keeping an array sorted in php i have a php script which reads a large csv and performs certain actions but only if the username field is unique the csv is used in more than one script so changing the input from the csv to only contain unique usernames is not an optionthe very basic program flow which i am wondering about goes like thisallusernames arraywhilerow fgetcsvfp username row0 if in arrayusername allusernames continue allusernames username process this rowsince this csv could actually be quite large it is that in array bit which has got me thinking the most ideal situation when searching through an array for a member is if it is already sorted so how would you build up an array from scratch keeping it in order once it is in order would there be a more efficient way to search it than using in array considering that it probably does not know the array is sorted,['php'] +7251,how do i unset an elements css attribute using jquery if i set a css value on a specific element usingelementcssbackgroundcolor ci want to be able to unset that elementspecific value and use the cascaded value along the lines ofelementcssbackgroundcolor nullbut that syntax does not seem to work is this possible using another syntaxthanks in advanceedit the value is not inherited from the parent element the original values comes from an elementlevel selector sorry for any confusion,"['jquery', 'css']" +7267,how to use jquery in firefox extension i want to use jquery inside a firefox extensioni imported the library in the xul file like thisscript typeapplicationxjavascript srcchromemyextensioncontentjqueryjs scriptbut the function is not recognized in the xul file neither do the jqueryi googled about the problem and found some solutions but no one did work with met989465i have also tried to pass the contentdocument objectwhich refrences the document object as the context parameter to the jquery function like thisimgcontentdocumentbut still not workingdoes any one came across this problem before,"['javascript', 'jquery']" +7272,concatenating lambda functions in c using c 35 i wanted to build up a predicate to send to a where clause piece by piece i have created a very simple console application to illustrate the solution that i arrived at this works perfectly absolutely perfectly but i have no idea how or why public static functran bool getpredicate functran bool predicate null predicate t tresponse 00 predicate t tamount 100 return predicate when i say predicate what does that mean predicate appears to do nothing and are not liked by the compilerthe compiler does not like predicate predicate t tresponse eitherwhat have i stumbled on i know what it does but how does it do itif anyone wants to go delve into more complicated lambdas please do so,['c#'] +7273,risk of using contenteditable in ie we have to add a basic html editor to our product as we only support ie at present most customers are still on ie 6 i have been told to use the internet explorer builtin xhtml editing capabilities a eg div contenteditabletrue as explained at editing a web page apart from not working in other browsers the management does not consider it being a problem our customers will put up with our software only working with ie we have never lost any money by our software only working in ie most customers will only let their staff use ie6 at present anywaywhat other problem are we likely to get with contenteditableupdatethe html editor i wrote with acontenteditablea proved to very hard to get reliable with many problems if i had to do this again i would push very hard to one of the many open source solutions eg tinymce or buy in a supported html editor no doubt that a very skilled jscript programmer can get acontenteditablea to work well given enough time it just that all the examples on the web looks so simple until you test common operations like doing a cutpaste from word and trying to edit the resulting html just the sort of things a customer will dojust search for acontenteditablea on stackoverflow to get some ideal of the problems other people have had,"['javascript', 'html']" +7281,blocking and waiting for an event it sometimes want to block my thread while waiting for a event to occuri usually do it something like thisprivate autoresetevent autoresetevent new autoreseteventfalseprivate void oneventobject sender eventargs e autoreseteventset buttonclick oneventtry autoreseteventwaitonefinally buttonclick oneventhowever it seems that this should be something that i could extract to a common class or perhaps even something that already exists in the frameworki would like to be able to do something like thiseventwaiter ew new eventwaiterbuttonclickewwaitoneeventwaiter ew2 new eventwaiterformclosingew2waitonebut i cannot really find a way to construct such a class i cannot find a good valid way to pass the event as an argument can anyone helpto give an example of why this can be useful consider something like thisvar status showstatusformstatusshowinsertusbstickbool cancelled waitforusbstickorcancelifcancelled statusshowwritingonusbstick writeonusbstick statusaskusertoremoveusbstick waitforusbsticktoberemoved statusshowfinishedelse statusshowcancelledstatuswaituntiluserpressesdonethis is much more concise and readable than the equivalent code written with the logic spread out between many methods but to implement waitforusbstickorcancel waitforusbsticktoberemoved and waituntiluserpressesdone assume that the we get an event when usb sticks are inserted or removed i need to reimplement eventwaiter each time of course you have to be careful to never run this on the guithread but sometimes that is a worthwhile tradeoff for the simpler codethe alternative would look something like thisvar status showstatusformstatusshowinsertusbstickusbhandlerinserted oninsertedstatuscancel oncancelvoid oninserted usbhandlerinserted oninserted statusshowwritingonusbstick methodinvoker mi writeonusbstick mibegininvokewritingdone nullvoid writingdone endinvoke statusaskusertoremoveusbstick usbhandlerremoved onremovedvoid onremoved usbhandlerremoved onremoved statusshowfinished statusdone ondone etc i find that much harder to read admittedly it is far from always that the flow will be so linear but when it is i like the first styleit is comparable to using showmessage and formshowdialog they also block until some event occurs though they will run a messageloop if they are called on the guithread,"['c#', '.net']" +7288,making your javascript maintainable i am in the process of converting an internal application to use more ajax via jquery i am moving away from the standard code behind of the current aspnet application and incorporating javascript methods that are going to run client side my concern is what is the best method for allowing this application to stay maintainable for those who come behind me,"['javascript', 'jquery']" +7294,how can i get the values of the parameters of a calling method questioni am writing some code that needs to be able to get the values of the parameters from the method that called into the class i know how to get all the way to the parameterinfo array but i do not know how to then get the values is this even possibleif it is i think it has something to do with using the methodbody property from the methodinfo object which allows you to inspect the il stream including properties but i do not know how to do it and i have not found applicable code on googlecode finds calling method from class that called into this onepublic class someclass public static void findmethod for int i 1 i framecount i var frame new stackframei var methodinfo framegetmethod if methodinfodeclaringtype thisgettype string methodname framegetmethodname var paraminfos methodinfogetparameters now what how do i get the values from the paraminfos break else if i framecount 1 throw new transportexceptioncould not find method name,['c#'] +7297,jquery vs microsoftajax in aspnet mvc under what circumstances would you use microsoftajax over jquery in an aspnet mvc applicationaccording to scott cate in this podcast object oriented ajax with scott cate microsoftajax is good for sending and retrieving data to and from the server and jquery is good for manipulating your data via the dom once it arrives at the client yet with a simple form plugin for jquery you can send and retrieve data with jquery quite easily often with a single line of codeso i am wondering what the difference is between microsoftajax and jquery within aspnet mvc,['jquery'] +7298,python restarting a loop i havefor i in range2n ifsomething do something else do something else i 2 restart the loopbut that does not seem to work is there a way to restart that loop thanks,['python'] +7304,creating xml in c code in my project there are situations where we have to send xml messages as char among modules they are not really large ones just 1015 lines right now everybody just creates the string themselves i dont think this is the right approach we are already using xerces dom library so why not create a dom tree serialize it and then send itwhat do you guys suggest,['c++'] +7306,does anyone know any gemspluginstutorials related to exporting events to ical google calendar outlook from a rails application i am trying to figure out if there is already a plug in that does the interaction with ical google apis that i can use or do i need to just get my hands dirty and write it myself if anyone knows of good resources that i can look at that could help me with the implementation that would be good as well i am new to ror and i have been trying to learn it for a while i finally decided to just start playing with my own application rather than just following a book any help in this matter would be appreciated thanks,['ruby-on-rails'] +7307,why no compiler error for main without a return at the end i am working on a cbrain teaser write the standard helloworld program without semicolonsmy best answer so far isint mainvoid if printfhello worldn exit0 0 do nothing but i do not understand why i do not get compiler error visual studioerror c4716 main must return a valuei have tried other functions with a returntype declared but missing a returnstatement and get this compiler errornote that i have also triedint foovoid if printfhello worldn exit0 true do nothing int mainvoid fooand do not get a compiler error on foo if i remove the exit0 i do get the compiler error apparently the compiler has knowledge that exit is a special function this seems very odd to me,['c'] +7310,converting a string to a class name i have a string variable that represents the name of a custom class example string s customeri will need to create an arraylist of customers so the syntax needed islistcustomer cust new how do i convert the string s to be able to create this arraylist on runtime,"['c#', '.net']" +7313,how do you convert a url to a virtual path in aspnet without manual string parsing i have seen similar questions and answers regarding conversions from virtual to absolute and url but how can i convert a url to a virtual path without manual string parsingexample i want httpmyserverhomeaspx converted to homeaspxi realize the above example would be an easy string parsing routine but i am looking for a proper solution that will scale to the changing of the url format,['asp.net'] +7316,persistent connection with client is there a general way to implement part of an application with javascript and supplying a persistent connection to a server i need the server to be able to push data to the client regardless of the client being behind a firewall thanks in advance,['javascript'] +7322,how different is cakephp from ruby on rails i almost never hear the word cakephp without hearing the word rails shortly afterwards are these two frameworks mainly similar based on how they adhere to the mvc model or do they have other significant similaritiesdifferences one of the main attractions of rails for me is how easy it is to do ajax would that also be true of cakephp,"['php', 'ruby-on-rails']" +7325,java how do i check if a date is within a certain range i have a series of ranges with start dates and end dates i want to check to see if a date is within that rangedatebefore and dateafter seem to be a little awkward to use what i really need is something like this pseudocodeboolean iswithinrangedate testdate return testdate startdate testdate enddatenot sure if it is relevant but the dates i am pulling from the database have timestamps,['java'] +7329,how do you thisplay custom uiviews in interfacebuilder i seem to enjoy designing new uiviews and uicontrols that implement their own drawrect method this work well for me especially when composed using uiviews in interface builderbut composing them in interface builder is annoying because they just show up as boring plain rectanglesit would be great if the views would actually render themselves as the builtin controls dois there any way i can structure my project so that interface builder will render my custom views,['objective-c'] +7331,how does transactionscope roll back transactions i am writing an integration test where i will be inserting a number of objects into a database and then checking to make sure whether my method retrieves those objectsmy connection to the database is through nhibernateand my usual method of creating such a test would be to do the followingnhibernatesessionbegintransactionuse nhibernate to insert objects into databaseretrieve objects via my methodverify actual objects returned are the same as those insertednhibernatesessionrollbacktransactionhowever i have recently found out about transactionscope which apparently can be used for this very purposesome example code i have found is as followspublic static int adepartmentwithemployeesdepartment dept int res 0 departmentadapter deptadapter new departmentadapter employeeadapter empadapter new employeeadapter using transactionscope txscope new transactionscope res deptadapterinsertdeptdepartmentname custom method made to return department id after inserting the department identity column deptdepartmentid deptadaptergetinsertreturnvalue foreachemployee emp in deptemployees empemployeedeptid deptdepartmentid res empadapterinsertempemployeename empemployeedeptid txscopecomplete return resi believe that if i do not include the line txscopecomplete that the data inserted will be rolled back but unfortunately i do not understand how that is possible how does the txscope object keep a track of the deptadapter and empadapter objects and their transactions on the databasei feel like i am missing a bit of information heream i really able to replace my begintransaction and rollbacktransaction calls by surrounding my code using transactionscopeif not how then does transactionscope work to roll back transactions,"['c#', '.net']" +7335,top 1 on left join subquery i am trying to take a person and thisplay their current insurance along with their former insurance i guess one could say that i am trying to flaten my view of customers or people i am running into an issue where i am getting multiple records back due to multiple records existing within my left join subqueries i had hoped i could solve this by adding top 1 to the subquery but that actually returns nothingany ideas select pperson id as mirid pfirstname as first plastname as last pgname as group ename as aor pleaddate as contact date dbogetpicampaignthisperson id 2009 as pi 2009 dbogetpicampaignthisperson id 2008 as pi 2008 dbogetpicampaignthisperson id 2007 as pi 2007 a thispname as curr thisp a insname as curr ins a prodtypename as curr ins type a tdate as curr ins app date a teffdate as curr ins eff date b thispname as prev thisp b insname as prev ins b prodtypename as prev ins type b tdate as prev ins app date b teffdate as prev ins eff date b ttermdate as prev ins term datefrom person pleft outer join employee eon eemployee id pagentofrecord idinner join dboperson physician ppon pperson id person idinner join dbophysician phonphphysician id physician idinner joindboclinic con cclinic id phclinic idinner joindbod physgroup pgonpgd physgroup id cphysgroup idleft outer join selecttr1from transaction tr1left outer join d vendor ins1on ins1d vendor id tr1d vendor idleft outer join d product type prodtype1on prodtype1d product type id tr1d product type idleft outer join d commission type ctype1on ctype1d commission type id tr1d commission type idwhereprodtype1name medicare part dand tr1termdate is null as a tona tperson id pperson idleft outer join d vendor a inson a insd vendor id a td vendor idleft outer join d product type a prodtypeon a prodtyped product type id a td product type idleft outer join d commission type a ctypeon a ctyped commission type id a td commission type idleft outer joind thisposition a thispona thispd thisposition id a td thisposition idleft outer join selecttr2from transaction tr2left outer join d vendor ins2on ins2d vendor id tr2d vendor idleft outer join d product type prodtype2on prodtype2d product type id tr2d product type idleft outer join d commission type ctype2on ctype2d commission type id tr2d commission type idwhereprodtype2name medicare part dand tr2termdate is not null as b tonb tperson id pperson idleft outer join d vendor b inson b insd vendor id b td vendor idleft outer join d product type b prodtypeon b prodtyped product type id b td product type idleft outer join d commission type b ctypeon b ctyped commission type id b td commission type idleft outer joind thisposition b thisponb thispd thisposition id b td thisposition idwherepgd physgroup id physgroupid,['sql'] +7342,list of css features not supported by ie6 i just finished slicing and coding a very nice tableless css template for my website all the time i was testing with ie7 and chromethen i just had the brilliant idea of testing this template with ie6 i installed windows xp on a virtual pc and then i opened my website on ie6it looks extremely badthe format of my page looked like garbage nothing thisplaying correctly like in ie7 and chrome i knew that some things were not supported by ie6 but i did not think that my page would render like it didso i would like to know if there is a place where i can see what is not supported by ie6 so i can fix my css or even create a new one only for ie6any info will be very helpfulthanks,['css'] +7349,c how to make a form remember its bounds and windowstate taking dual monitor setups into account i have made a class which a form can inherit from and it handles form location size and state and it works nicely except for one thing when you maximize the application on a different screen than your main one the location and size before you maximized gets stored correctly but when it is maximized according to its previous state it is maximized on my main monitor when i then restore it to normal state it goes to the other screen where it was before when i then maximize it again it of course maximized on the correct screenso my question is how can i make a form when it is maximized remember what screen it was maximized on and how do i restore that when the form opens againkind of complete solution to problemi accepted the answer which had a very good tip about how to if on screen but that was just part of my problem so here is my solutionon loadfirst get stored bounds and windowstate from whatever storagethen set the boundsmake sure bounds are visible either by screenallscreensanya a boundsintersectswithbounds or mdiparentcontrolsoftypemdiclientfirstclientrectangleintersectswithboundsif it does not just do location new pointthen set window stateon closingstore windowstateif windowstate is formwindowstatenormal then store bounds otherwise store restoreboundsand thats it some example codeso as suggested by oliver here is some code it needs to be fleshed out sort of but this can be used as a start for whoever wants topersistentformhandlertakes care of storing and fetching the data somewherepublic sealed class persistentformhandler summarythe form identifier in storagesummary public string name get private set summarygets and sets the window state int instead of enum so that it can be in a bi layer and not require a reference to winformssummary public int windowstate get set summarygets and sets the window bounds x y width and heightsummary public rectangle windowbounds get set summarydictionary for other valuessummary private readonly dictionarystring binary othervalues summary instantiates new persistent form handler summary param namewindowtypethe see creftypefullname will be used as see crefnameparam param namedefaultwindowstatedefault state of the windowparam param namedefaultwindowboundsdefault bounds of the windowparam public persistentformhandlertype windowtype int defaultwindowstate rectangle defaultwindowbounds thiswindowtype null defaultwindowstate defaultwindowbounds summary instantiates new persistent form handler summary param namewindowtypethe see creftypefullname will be used as base see crefnameparam param nameiduse this if you need to separate windows of same type will be appended to see crefnameparam param namedefaultwindowstatedefault state of the windowparam param namedefaultwindowboundsdefault bounds of the windowparam public persistentformhandlertype windowtype string id int defaultwindowstate rectangle defaultwindowbounds name stringisnulloremptyid windowtypefullname windowtypefullname id windowstate defaultwindowstate windowbounds defaultwindowbounds othervalues new dictionarystring binary summary looks for previously stored values in database summary returnsfalse if no previously stored values were foundreturns public bool load see note 1 summary stores all values in database summary public void save see note 2 summary adds the given paramref keyvalue to the collection of values that will be stored in database on see crefsave summary typeparam keyttype of objecttypeparam param namekeythe key you want to use for this valueparam param namevaluethe value to storeparam public void settstring key t value create memory stream using var s new memorystream serialize value into binary form var b new binaryformatter bserializes value store in dictionary othervalueskey new binarystoarray summary same as see crefgettstringt but uses defaulttypeparamref namet as fallback value summary typeparam namettype of objecttypeparam param namekeythe key used on see crefsettparam returnsthe stored object or the defaulttypeparamref namet object if something went wrongreturns public t gettstring key return getkey defaultt summary gets the value identified by the given paramref namekey summary typeparam namettype of objecttypeparam param namekeythe key used on see crefsettparam param namefallbackvalue to return if the given paramref namekey could not be found in other words if you have not used see crefsett yetparam returnsthe stored object or the paramref namefallback object if something went wrongreturns public t gettstring key t fallback if we have a value with this key if othervaluescontainskeykey create memory stream and fill with binary version of value using var s new memorystreamothervalueskeytoarray try deserialize cast and return var b new binaryformatter return tbdeserializes catch invalidcastexception t is not what it should have been code changed perhaps catch serializationexception something went wrong during deserialization else return fallback return fallback note 1 in the load method you have to look for previously stored windowstate windowbounds and other values we use sql server and have a window table with columns for id name machinename for environmentmachinename userid windowstate x y height width so for every window you would have one row with windowstate x y height and width for each user and machine in addition we have a windowvalues table which just has a foreign key to windowid a key column of type string and a value column of type binary if there is stuff that is not found i just leave things default and return falsenote 2 in the save method you then of course do the reverse from what you do in the load method creating rows for window and windowvalues if they do not exist already for the current user and machinepersistentformbasethis class uses the previous class and forms a handy base class for other forms should have been abstract but that makes the the designer crash at the momentpublic class persistentformbase form private persistentformhandler persistencehandler get set private bool handlerready protected persistentformbase prevents designer from crashing if licensemanagerusagemode licenseusagemodedesigntime load persistentformload formclosing persistentformformclosing protected event eventhandlereventargs valuesloaded protected event eventhandlereventargs storingvalues protected void storevaluetstring key t value if handlerready throw new invalidoperationexception persistencehandlersetkey value protected t getvaluetstring key if handlerready throw new invalidoperationexception return persistencehandlergettkey protected t getvaluetstring key t fallback if handlerready throw new invalidoperationexception return persistencehandlergetkey fallback private void persistentformloadobject sender eventargs e create persistencehandler and load values from it persistencehandler new persistentformhandlergettype int formwindowstatenormal bounds persistencehandlerload handlerready true set size and location bounds persistencehandlerwindowbounds check if we have an mdiparent ifmdiparent null if we do not make sure we are on screen if screenallscreensanya a boundsintersectswithbounds location new point else if we do make sure we are visible within the mdiclient area var c mdiparentcontrolsoftypemdiclientfirstordefault ifc null cclientrectangleintersectswithbounds location new point set state windowstate enumisdefinedtypeof formwindowstate persistencehandlerwindowstate formwindowstate persistencehandlerwindowstate formwindowstatenormal notify that values are loaded and ready for getting var handler valuesloaded if handler null handlerthis eventargsempty private void persistentformformclosingobject sender formclosingeventargs e set common things persistencehandlerwindowstate int windowstate persistencehandlerwindowbounds windowstate formwindowstatenormal bounds restorebounds notify that values will be stored now so time to store values var handler storingvalues if handler null handlerthis eventargsempty save values persistencehandlersave and thats pretty much it to use it a form would just inherit from the persistentformbase that would automatically take care of bounds and state if anything else should be stored like a splitter thistance you would listen for the valuesloaded and storingvalues events and in those use the getvalue and storevalue methodshope this can help someone please let me know if it does and also please provide some feedback if there is anything you think could be done better or something i would like to learn,['c#'] +7355,can we write a sub function or procedure inside another stored procedure sql server i want to check if sql server20508 has the ability to write a nested stored procedure what i meant is writing a sub functionprocedure inside another stored procedure not calling another sp why i was thinking about it is one of my sp is having a repeated lines of code and that is specific to only this spso if we have this nested sp feature then i can declare another sublocal procedure inside my main sp and put all the repeating lines in that and i can call that local sp in my main sp i remember such feature is available in oracle spsif sql server is also having this feature can someone please explain some more details about it or provide a link where i can find documentationthanks in advancesai,['sql'] +7367,c virtual function from constructor why the following example prints 0 and what must change for it to print 1 as i expected include iostreamstruct base virtual const int value const return 0 base stdcout value stdendl virtual base struct derived public base virtual const int value const return 1 int mainvoid derived example,['c++'] +7368,paging sorting grids with aspnet mvc i am new to mvc and am not following how youd do paging and sorting on a grid i am used to using the aspnet gridview control with an objectdatasource pointed at objects in our business layer and in that case the ods handles all of the paging sorting using the methods that our orm generates on the objectsi have looked at using the same orm with mvc and things work out fine there i just loop thru the collections to build the table on the page but without the ods to handle the paging sorting i am confused as to how i would handle that would i have a separate controller for the paging and sorting i understand that i need to roll my own but where do i start i have created a customercontroller and a view that thisplays a table of customers that looks like below and i want to sort on firstname or lastname columns my model has a sort method on it thatll take a string sort expression in the format that would be used by a gridviewods pair would i create a new action on my customercontroller called sort and put an actionlink in my header table tr th first name th th last name th tr foreach var item in model tr td htmlencodeitemfirstname td td htmlencodeitemlastname td tr table,['asp.net'] +7381,mathematical formula for calculating call duration i was working for a telecom company some years ago and i had to generate a formula which calculates duration of a call according to the following algorithmt1 is the first period t2 is the recurring periodrct is the actual call time in secondscd is the effective call duration for billing purposesif rct is less than t1 then the cd equals t1if rct is greater than t1 then cd t1 xt2 where x will round rct to the next highest multiple of t2this algorithm translates to charge for the first t1 seconds then charge every t2 seconds after thatexamplet1t2rctcd60104860601065706010121130302025303020355030206570can you create a function sql that will return the call duration cdwithout using if then else,['sql'] +7384,safely override c virtual functions i have a base class with a virtual function and i want to override that function in a derived class is there some way to make the compiler check if the function i declared in the derived class actually overrides a function in the base class i would like to add some macro or something that ensures that i did not accidentally declare a new function instead of overriding the old onetake this exampleclass parent public virtual void handle eventint something const boring default code class child public parent public virtual void handle eventint something new exciting code int main parent p new child phandle event1here parenthandle event is called instead of childhandle event because the childs method misses the const declaration and therefore declares a new method this could also be a typo in the function name or some minor difference in the parameters types it can also easily happen if the interface of the base class changes and somewhere some derived class was not updated to reflect the changeis there some way to avoid this problem can i somehow tell the compiler or some other tool to check this for me any helpful compiler flags preferably for g how do you avoid these problems,['c++'] +7387,are you using virtual machine as your primary development enviroment recently i have purchased a notebook that cames with windows home basic that do not have with aspnetiis i thought in upgrade the windows version to one with aspnetiis but i thought in another possibilityi have an hard thisk case with a 360gb hd i thought in create a virtual machine with windows ultimate installing too aspnet iis and visual studio 2008 in this hd case then i can access my development enviroment in any computer that i will work on my desktop machine and my notebookbut i was worried about the performance i do not have experience working in virtual machines i use it just to quick compatibility testsare you using virtual machine as your primary development enviroment what your findsthanks for your answers it really did help me i would like to know too about portability ie the virtual machine that i created in my laptop will work in the desktop i will need reactivate windows,['asp.net'] +7388,whats the use of yield break possible duplicatewhat does ayield breaka do in c can anyone see a use for the yield break statement that could not have been otherwise achieved by using break or returnthis statement seems to be utterly useless whats more without this statement the yield return x statement could have been simplified to yield x which much more readablewhat am i missing,['c#'] +7389,how can i make tomcat precompile jsps on startup were using both apache tomcat 60 and jetty 6 where i work we mostly use jetty for testing it is great for running embedded in junit tests and tomcat for productionby default tomcat compiles jsps onthefly as users request them but this results in degraded performance for the first hit it also highlights bizarre bugs in tomcats jsp compilerthe tomcat documentation gives recommendations for precompiling jsps at build time using ant and a maven plugin is also available but the resulting war contains tomcatspecific stuff eg pagecontextimplproprietaryevaluate so we cannot use it in jettyis there some flag or setting we can use somewhere to force tomcat to precompile all jsps as soon as the war is initialized were prepared to wait a little longer on startup for thisin advance i know there is a way to precompile exactly one jsp by explicitly identifying a servletloadonstartup tag in webxml for one jsp but for dozens or even hundreds of jsps that becomes unmanageable,['java'] +7391,learning clojure without java knowledge ok so i am psyched about another list i got myself a copy of the beta clojure programming bookand the one thing i am noticing most is that it is assumed i know like all the major java classesexcept generally i do not really care about java i just want enough knowledge of it for clojure to be an option for meany suggestion as to how to learn just what i need of it all,['java'] +7396,pass arguments into c program from command line so i am in linux and i want to have a program accept arguments when you execute it from the command linefor example myprogram 42 b sso then the program would store that number 42 as an int and execute certain parts of code depending on what arguments it gets like b or s,['c'] +7398,an object reference is required for the nonstatic field method or property on a windows form namespace windowsapplication1 public partial class form1 form public form1 initializecomponent private void button1 clickobject sender eventargs e int val 0 0 int val if textbox1text messageboxshowinput any no else val converttoint32textbox1text thread ot1 new threadnew parameterizedthreadstartsumdata ot1startval private static void readdataobject state systemwindowsformsapplicationrun void settextboxtextint result if thisinvokerequired thisinvokenew intdelegatesettextboxtextsafe new object result else settextboxtextsaferesult void settextboxtextsafeint result label1text resulttostring private static void sumdataobject state int result int icount intstate int icount intstate for int i icount i 0 i result i systemthreadingthreadsleep10 settextboxtextresult delegate void intdelegateint result private void button2 clickobject sender eventargs e applicationexit could anyone gave me the answer why this error is occuringan object reference is required for the nonstatic field method or property windowsapplication1form1settextboxtextint,['c#'] +7403,is django a good choice for a security critical application is django a good choice for a security critical applicationi am asking this because most of the online banking software is built using java is there any real reason for this,['python'] +7407,trim string in javascript how do i trim a string in javascript,['javascript'] +7408,java how to determine the correct charset encoding of a stream with reference to the following threadwhat is the best way to programatically determine the correct charset encoding of an inputstreamfile i have tried using the following file in new fileargs0 inputstreamreader r new inputstreamreadernew fileinputstreamin systemoutprintlnrgetencodingbut on a file which i know to be encoded with iso8859 1 the above code yields ascii which is not correct and does not allow me to correctly render the content of the file back to the console,['java'] +7416,sql server 2005 nullable foreign key constraint i have a foreign key constraint between tables sessions and users specifically sessionsuid usersid sometimes i want sessionsuid to be null can this be allowed any time i try to do this i get an fk constraint violationspecifically i am inserting a row into sessions via linq i set the sessionuser null and i get this error an attempt was made to remove a relationship between a user and a session however one of the relationships foreign keys sessionuid cannot be set to nullhowever when i remove the line that nulls the user property i get this error on my submitchanges linevalue cannot be nullparameter name consnone of my tables have a field called cons nor is it in my 5500line datacontextdesignercs file nor is it in the quickwatch for any of the related objects so i have no idea what cons isin the database sessionuid is a nullable int field and userid is a nonnullable int i want to record sessions that may or may not have a uid and i would rather do it without thisabling constraint on that fk relationship is there a way to do this,['sql'] +7418,is pthread a good choice for multiplatorm cc multithreading program been doing mostly java and smattering of net for last five years and have not written any significant c or c during that time so have been away from that scene for a whileif i want to write a c or c program today that does some multithreading and is source code portable across windows mac os x and linuxunix is pthread a good choicethe c or c code would not be doing any gui so would not need to worry with any of thatfor the windows platform i do not want to bring a lot of unix baggage though in terms of unix emulation runtime libraries would prefer a pthread api for windows that is a thinaspossible wrapper over existing windows threading apisaddendum editam leaning toward going with boostthread i also want to be able to use c trycatch exception handling too and even though my program will be rather minimal and not particularly oopish i like to encapsulate using class and namespace as opposed to c thisembodied functions,"['c++', 'c']" +7422,what is the significance of starting constants with k i am teaching myself objectivec and i noticed in a lot of books and examples the use of k and camelcasing in constant definition eg define kmyconstant 0what is the significance of the k is this unique to objectivec style or common to c in generalwhy the deviation from what i have always thought as a best practice k my constant stylethanks,['objective-c'] +7430,how do django model fields work first of alli am not into web programming i bumped into django and read a bit about models i was intrigued by the following code from djangoprojectcom class personmodelsmodel first name modelscharfieldmax length50 last name modelscharfieldmax length50 def str self note use of djangoutilsencodingsmart str here because first name and last name will be unicode strings return smart strs s selffirst name selflast nameby my understanding of python first name and last name are class variables right how is that used in code because i guess that setting personfirst name or personlast name will affect all person instances why is it used that way,['python'] +7434,how do i convert a decimal to an int in c how do i convert a decimal to an int,"['c#', '.net']" +7436,format date in c how can i format a date as ddmmy or mmddyy like in vb formatddmmyynowhow can i do this in c,"['c#', '.net']" +7440,simple simulations for physics in python i would like to know similar concrete simulations as the simulation about watering a field herewhat is your favorite libraryinternet page for such simulations in pythoni know little simpy numpy and pygame i would like to get examples about them,['python'] +7441,webform postbackoptions documentation is there any documentation on the parameters to webform postbackoptions i cannot find anything by googling,['asp.net'] +7442,bind to a method in wpf how do you bind to an objects method in this scenario in wpfpublic class rootobject public string name get public observablecollectionchildobject getchildren public class childobject public string name get xamltreeview itemssourcesome list of rootobjects treeviewresources hierarchicaldatatemplate datatypextype datarootobject itemssource textblock textbinding pathname hierarchicaldatatemplate hierarchicaldatatemplate datatypextype datachildobject textblock textbinding pathname hierarchicaldatatemplate treeviewresourcestreeviewhere i want to bind to the getchildren method on each rootobject of the tredit binding to an objectdataprovider does not seem to work because i am binding to a list of items and the objectdataprovider needs either a static method or it creates it is own instance and uses thatfor example using matts answer i getsystemwindowsdata error 33 objectdataprovider cannot create object typerootobject errorwrong parameters for constructorsystemwindowsdata error 34 objectdataprovider failure trying to invoke method on type methodgetchildren typerootobject errorthe specified member cannot be invoked on target targetexceptionsystemreflectiontargetexception nonstatic method requires a target,['.net'] +7445,passing const variable to method in java is there an equivalent in java to the passing on const references in cis not leaving out the constness misleading in regard to the method signature,"['java', 'c++']" +7447,css wordwrapping in div i have a div with a width of 250px when the innertext is wider than that i want it to break down the div is float left and now has an overflow i want the scrollbar to go away by using wordwrapping how can i achieve thisdiv idtreeviewdiv idhandboekbox div idhandboektitel asplabel idlblmanual runatserverasplabel div div idhandboekclose aspimagebutton idbtnclosemanual runatserver imageurlgraphicsclosepng onclickbtnclosemanual click borderwidth0 tooltipsluit handboek divdivasptreeview idtvmanual runatserver rootnodestylecssclassrootnode nodes nodesasptreeviewdivcsstreeviewpaddingright 5pxwidth 250pxheight 100float leftborderright solid 1px blackoverflowx scroll,"['css', 'html']" +7449,versioning css files with a query string like stackoverflow does if you look at stackoverflowcoms source youll see the reference to their css file islink hrefcontentallmincssv2383 relstylesheet typetextcss how is this done so they can pass a version via query string and have the correct css file served up,['css'] +7453,wcf advantages and thisadvantages i would like to find out about both advantages and thisadvantages of windows communication foundation from people who have used it or just know it theoretically,['.net'] +7456,eclipse how to build an executable jar with external jar i am trying to build an executable jar program which depends on external jar downloaded in my project i included them in the build path and can be run and debug within eclipsewhen i tried to export it to a jar i can run the program but i cannot when i try to press a button which includes function calls and classes from the external jar i have edited the environment variables windows xp classpath to include paths of all the external jar but it does not worka point to note is that i got compile warnings while exporting my executable jar but it does not show up any description about the warningswould someone kindly provide a thorough guide on how to include an external jar program using eclipse,['java'] +7459,structuremap instancescopehybrid and ithisposable i am working on an aspnetmvc application the linq data context is being passed into my service objects by structure map i have got is set to have a scope of hybrid this all works just fineprotected override void configure forrequestedtypeaetherdatacontext thedefaultis new aetherdatacontext cachebyinstancescopehybridthe problem is that i keep running our of memory i am wondering if the ithisposable interface is ever actually being calledanyone got any ideasfailing that anyone got any other idea for things that might be causing my memory exceptionsupdateso some additional information i just stuffed a couple of methods into my data context an put brake points in thereprotected override void thisposebool thisposing debugwritelinethisposing datetimenow basethisposethisposingpublic new void thispose debugwritelinethisposing datetimenow basethisposei am not quite sure that i am doing this the correct way i am guessing that the new method will be calledanyway neither of the brake points were hit however the constructor for the same class was called on every request though not ideal i am thinking,['c#'] +7474,javascript endian encoding a response on so got me thinking does javascript guarantee a certain endian encoding across oss and browsersor put another way are bitwise shifts on integers safe in javascript,['javascript'] +7475,oracle delete rows matching on multiple values i want to do something likedelete from student wherestudentcourse studentmajor inselect schedulecourse schedulemajor from schedulehowever it seems that you can only use one column with the in operator is that true seems like a query like this should be possible,['sql'] +7488,how do i find the current machines full hostname in c hostname and domain information in a c project posix how do i get the fully qualified name for the current systemfor example i can get just the hostname of my machine by doinggethostname from unistdh this might give me machine3 in return but i am actually looking for machine3somedomaincom for examplehow do i go about getting this information i do not want to use a call to system to do this if possible,['c'] +7492,developing a robocode type game with net for a school assignment i am currently in my final year at school studying for a higher national diploma in computer studies and basically in this final semester we need to develop a software project that basically incorporates a whole systemnow what i am thinking of doing is something along the lines of robocode but instead of java i will be doing this with the net frameworkwhat is robocode for those of you do not know what robocode is it is basically a sort of programming game in where people develop their own robots using methods from the class interfaces and downloadable classes that exist and then they fight each other in an autonomous battle in an arenalike such so basically as i said i want to recreate this sort of scenario using the net frameworkand i am posting this question here on stackoverflow in hope that more experienced developers will be able to guide me in the right direction for this projectwhat i have in mind up till now is basically to createan offline application that will serve as the battle arena and the userinterface to create new battles with existing robots and suchan online interface that players will able to use to register new robots view past tournament scores etcand obviously the class interfaces that players will need to use to create their robotsanimation and graphics for the actual battlesnow of course there will be some sort of animation and movement when the battle occurs and i have not decided what yet to use as a medium for thisthe options i currently have in mind aredeveloping as i said in the first above bullet points an offline application that will serve as a battle grounds and all animations will be done using mainly c codeor develop a silverlight application that will handle the animations thus changing the scenario from an offline applcation to now an online oneor maybe the least feasable of them create the battle animations using javascript with something like the canvaswhat do you think could be more suitable for this particular scenario developing classes and interfacesfor the players to develop the robots i will provide certain class interfaces that they will be able to use like in robocodeexamples of such events and methods may includepublic void run public void onscannedrobotscannedrobotevent e walk ammount in pixels or we to walk to turnright value in degrees for an angular turn etchere is a snippet from code in robocode java public class myfirstrobot extends robot public void run while true ahead100 turngunright360 back100 turngunright360 for then to actually make the battles happen i am thinking of using reflection to actually read what methods the user is actually making use of and implementing them to run and be invoked at particular moments of the battle and suchnow what i kindly and humbly ask of you experienced developers is to guide me a bit through this project of mine and advise me on what needs to be donefor starters is this project feasible at all and if it actually is from where do i need to actually start with my projectas regards technologies and software i intend to be using are net framework 35 with c 30linq language integrated querysql server 2008microsoft visual studio 2008jquery frameworkpossibly silverlighti thank you all even for managing to read up to this point in my question and i will need and appreciate greatly all the help i can get to finish this projectthank you for your time and effortbtw up till now apart from robocode i have found these games that are similar to what i am trying to createnrobotvirii thanks marc,['.net'] +7494,how to change the text color on uinavigationbar button items i have got a uinavigationcontroller and i have changed it to white using the tint property of the navigation bar in interface builder but the text in buttons and the title is still the default color white and so gets lost against the white background anyone know how to work around this,['iphone'] +7495,deflatestream 4gb limit in net from msdn deflatestream classdeflatestream cannot be used to compress files larger than 4 gbare there any other implementations for net without the 4 gb limitnote i really need to decompress a file in gz format with content larger than 4 gb can any code do that,"['c#', '.net']" +7497,py2exe for python 30 i am looking for a python30 version of py2exe i tried running 2to3 on the source for py2exe but the code remained brokenany ideas,['python'] +7502,what are some resources for learning msil can someone please give me a link to a tutorial or answer how to read msil i think once i learn how to read this it could be a very useful tool,['c#'] +7503,idiomatic way to set default value in javascript what would be the most idiomatic way to do the following in javascriptif myparam is not passed into myfunc by the caller then i want to set it to a default value but first i want to try and get it from another object which may not yet exist function myfuncmyparam if myparam if myobj myparam 10 else myparam myobjmyparam alertmyparami started to write myparam myparam myobjmparam 10but realized that if myobj does not exist then this would fail i might guess the following myparam myparam myobj myobjmparam 10it might even work but is it the best wayhow would for example john resig do it,['javascript'] +7504,can i ignore delegate parameters with lambda syntax i am curious why c allows me to ignore delegate parameters in some cases but not othersfor instance this is permittedactionint action delegate consolewritelinedelegate but this is notactionint action consolewritelinelambdais there a way to initialize a delegate and ignore the parameters using a lambda i know that i can add a single parameter to the lambda and fix the previous line but this is more of an academic question pertaining to the compiler and why or how this works,['c#'] +7505,what do you mean ruby on rails is not thread safe i was just reading up on ror have not dived into it yet and i hear that it is not thread safe obviously this does not mean that more than one person cannot access your site at one time so what exactly does it mean where do threads come into play in ror do they just mean the request handling,"['ruby-on-rails', 'ruby']" +7509,javascript 64 bit numeric precision is there a way to represent a number with higher than 53bit precision in javascript in other words is there a way to represent 64bit precision numberi am trying to implement some logic in which each bit of a 64bit number represents something i lose the lower significant bits when i try to set bits higher than 253mathpow253 mathpow20 mathpow253is there a way to implement a custom library or something to achieve this,['javascript'] +7516,how we can show uiviewcontroller and uiview by using cocos2d i am trying to build an iphone app by using cocos2dbut i have used four types of classeslike bellowinterface menuscene scene endinterface flipview uiimageview cgpoint starttouchposition nsstring dirstring uiimageview firstpieceview uiimageview secondpieceviewendinterface hellocontroller uiviewcontrollerendinterface menulayer layer todo todo menu menu sqlite3 database nsmutablearray todos nsstring dirstring cgpoint starttouchpositionproperty nonatomic retain nsmutablearray todosvoid button1 idsendervoid button2 idsendervoid black jack idsenderendbut how can i show flipview and hellocontroller class through menulayer class,"['iphone', 'objective-c']" +7520,writing standards for unit testing i plan to introduce a set of standards for writing unit tests into my team but what to includethese two posts unit test naming best practices and best practices for file system dependencies in unitintegration tests have given me some food for thought alreadyother domains that should be covered in my standards should be how test classes are set up and how to organize them for example if you have class called orderlineprocessor there should be a test class called orderlineprocessortest if there is a method called process on that class then there should be a test called processtest maybe more to test different statesany other things to includedoes your company have standards for unit testingedit i am using visual studio team system 2008 and i develop in cnet,['c#'] +7528,does ienumerable concat preserve the order of elements assume two lists a and b so that a 123 and b 456 will aconcatb preserve the order so that the result is 123456,"['c#', '.net']" +7533,problem with ftpclient class in java i am using orgapachecommonsnetftpftpclient and seeing behavior that is well perplexingthe method beneath intends to go through an ftpfile list read them in and then do something with the contents that is all working what is not really working is that the ftpclient object does the following1 properly retrieves and stores the first file in the list 2 list item evaluates to null for x number of successive iterations of the loop x varies on successive attempts 3 manages to retrieve exactly 1 more file in the list 4 reports that it is null for exactly 1 more file in the list 5 hangs indefinitely reporting no further activitypublic static string mergexmlfileslistftpfile files string rootelementnodename ftpclient ftp string ret null string fileasstring null inputstream instream int c iffiles null rootelementnodename null return null try systemoutprintlngetting filessize files for ftpfile file files fileasstring inputstream instream ftpretrievefilestreamfilegetname ifinstream null systemoutprintlnftputilmergexmlfiles could not initialize instream for file filegetname continuethis is the part that i see for files 1 arbitrary number usually around 20 and then 1 more time for x 2 after x 1 passes successfully whilec instreamread 1 fileasstring charactervalueofcharc instreamclose systemoutprintlnfile filegetname n fileasstring catch exception e systemoutprintlnftputilmergexmlfiles failed e return ret has anyone seen anything like this i am new to ftpclient am i doing something wrong with it,['java'] +7534,what are the pros and cons of running iis as 32bit vs 64bit on a 64bit os possibly better suited for rack overflow but from a developers point of view what are the advantages and thisadvantages of running iis serving both legacy classic asp and net as a 32bit process instead of a 64bit process on a 64bit windows host the main advantage of 3264 iisserver over 3232 seems to be the ability to go up to 4gb in memory per iis process the advantages i expect of 3264 over 6464 appear to be that it is easier to access legacy 32bit inprocess dlls of which we still have one from a partner vendor we cannot move away from immediately and perhaps a smaller memory footprint for the same code given smaller memory pointers are there any performance benefits of 6464 over 3264 or anything else that would warrant a full switch now have i made any false assumptions here,['asp.net'] +7536,mysql select from another server i am afraid that i already know the answer to my question but i will ask it anywaywhen there are two mysql db servers can i access data that is stored on the other server in other words can i somehow do thisinsert into table x y z select x y xy from otherserverdatabasetableis the answer really as short as no,['mysql'] +7537,what is the shortest way to implement a proxy or decorator class in c when you have a class car that implements ivehicle and you want to wrap it in a decorator that forwards all calls to car and counts them how would you do itin ruby i could just build a decorator without any methods and use method missing to forward all calls to the car objectin java i could build a proxy object that runs all code through one method and forwards it afterwardsis there any similiar thing i can do in cupdatebased on the answeres and what ia ve read about systemreflectionemit it should be possible to write a method similiar to thistype proxybuildertype sometype delagate functiontobeapplied object forwardwhere type implements all interface of sometype executes functiontobeapplied and then forwards the method call to object while returning its returnis there some lib that does just that or would i have to write my own,"['c#', '.net']" +7541,quaternion libraries in cc any good libraries for quaternion calculations in cc side note any good tutorialsexamples i have google it and been to the first few pages but maybe you have have some demoslabs from compsci or math courses you couldwould share thanks,['c++'] +7542,create xml nodes based on xpath does anyone know of an existing means of creating an xml hierarchy programatically from an xpath expression for example if i have an xml fragment such asfeed entry datadata contentcontent entryfeedgiven the xpath expression feedentrycontentsource i would havefeed entry datadata content sourcecontent entryfeedi realize this is possible using xslt but due to the dynamic nature of what i am trying to accomplish a fixed transformation would not worki am working in c but if someone has a solution using some other language please chime inthanks for the help,['c#'] +7548,java equivalent of unsigned long long in c i enjoyed having access to a 64 bit unsigned integer via unsigned long long int or via uint64 t now in java longs are 64 bits i know however they are signedis there an unsigned long long available as a java primitive how do i use it,['java'] +7571,cgcontext is there a way to reset the current context in my iphone project i have got a uiview where i implement the drawrect method voiddrawrectcgrectrect cgcontextref context uigraphicsgetcurrentcontextinside the method i do a whole bunch of drawing of lines images and texts using this context the problem is that when i reuse this view the context does not get reset is there a method i can call to reset the context somehow,['iphone'] +7575,which api to use to draw 3d objects in c i would like to do some 3d programming in c but i am not sure where to start looking for an api if i were doing this in c i know the options are opengl and directx but i am not sure what the options are for c i do not necessarily want to program a whole game just manipulate a few objects,['c#'] +7577,what is so evil about a flash based website i have the feeling that flashbased or silverlightbased websites are generally frowned upon except when you are creating games or multimediacontent rich applications why this is so,['html'] +7582,getting the parent name of a uriurl from absolute name c given an absolute uriurl i want to get a uriurl which does not contain the leaf portion for example given i should get the code which i could come up with seems a bit lengthy so i am wondering if there is a better waystatic string getparenturistringuri uri stringbuilder parentname new stringbuilder append the scheme http ftp etc parentnameappendurischeme appned the after the http ftp etc parentnameappend append the host name wfoocom parentnameappendurihost append each segment except the last one the last one is the leaf and we will ignore it for int i 0 i urisegmentslength 1 i parentnameappendurisegmentsi return parentnametostring one would use the function something like this static void mainstring args uri uri new uri should return string parentname getparenturistringuri thanksrohit,['c#'] +7583,how to handle incomplete files getting exception i need to create a java program which will create thread to search for a file in particular foldersource folder and pick the file immediately for process workconvert it into csv file format once it found the file in the source folder problem i am facing now is file which comes to source folder is big sizeftp tool is used to copy file from server to source folder thread is picking that file immediately before it copies fully to source folder and throwing exception how do i stop thread until the file copy into source folder completely it has to pick the file for processing only after the file is copied completely into source folder,['java'] +7584,getting table metadata in mysql i am trying to find out how to get the following constraint information from a table in mysql 50 primary keyforeign keys and table referencesunique columnswhat is the syntax of the query or queries to do so i have a feeling i am close with this but there is no example,['mysql'] +7588,java jtree expand only level one nodes with a jtree assuming the root node is level 0 and there may be up to 5 levels below the root how can i easily expand all the level 1 nodes so that all level 1 2 branches and leafs are visible but levels 3 and below are not,['java'] +7596,is there an stl and utf8 friendly c wrapper for icu or other powerful unicode library i need a good unicode library for c i needtransformations in a unicode sensitive way for example sort all strings in a case insensitive way and get their first characters for index convert various unicode strings to upper and to lower case split text at a reasonable position words that would work for chinese and japanese as wellformatting numbers dates in locale sensitive way should be thread safetransparent support of utf8 primary internal representationas far as i know the best library is icu however i cannot find normal developer friendly api documentation with examples also as far as i see it is not too friendly withmodern c design work with stl and so on like thisstdstring msgunistring umsgfrom utf8msgunistringword iterator wiforwiumsgwordsbeginn0wiusmgwordswi endn10win msgumsgsubstrumsgwordsbeginwito utf8cout five 10 words are msgis there a good stl friendly icu wrapper released under open source license preferred is a license permissive like mit or boost but others like lgplv2 compatible are ok as wellis there another high quality library similar to icuplatform unixposix windows support is not requirededit unfortunately i was not logged in so i cannot make accept an answer i have attached the answer by myself,['c++'] +7602,select count is slow even with where clause i am trying to figure out how to optimize a very slow query in mysql i did not design thisselect count from change event me where change event id 1212281603783391 count 3224022 1 row in set 1 min 016 seccomparing that to a full countselect count from change event count 6069102 1 row in set 421 secthe explain statement does not help me here explain select count from change event me where change event id 1212281603783391g 1 row id 1 select type simple table me type rangepossible keys primary key primary key len 8 ref null rows 4120213 extra using where using index1 row in set 0 secok it still thinks it needs roughly 4 million entries to count but i could count lines in a file faster than that i do not understand why mysql is taking this longheres the table definitioncreate table change event change event id bigint20 not null default 0 timestamp datetime not null change type enumcreateupdatedeletenoop default null changed object type enumbrandbroadcastepisodeondemand not null changed object id varchar255 default null changed object modified datetime not null default 10101 0 modified datetime not null default 10101 0 created datetime not null default 10101 0 pid char15 default null episode pid char15 default null import id int11 not null status enumsuccessfailure not null xml diff text node digest char32 default null primary key change event id key idx change events changed object id changed object id key idx change events episode pid episode pid key fk import id import id key idx change event timestamp ce id timestampchange event id key idx change event status status constraint fk change event import foreign key import id references import import id engineinnodb default charsetutf8version mysql versionmysql ver 1412 thistrib 5037 for pcsolaris28 i386 using readline 50is there something obvious i am missing yes i have already tried select countchange event id but there is no performance difference,['mysql'] +7607,add a link stylesheet dynamically in the how to add a link stylesheet reference to the head of a document i have found this code but it is not working with all browsers it crashes my ie7 var ss documentcreateelementlinksstype textcsrel stylesheetsshref stylecssdocumentgetelementsbytagnamehead0appendchildssthanks,['javascript'] +7609,php landmines in general what surprises have other people found with writing php web applications there is the well known and to be fixed issue with compile time class inheritance but i know of a couple others and wanted to try and build a list of the top gotchas of the languagenote i have held several positions as a sr php5 developer so php work pays my bills this question is not meant to bust on php as a language as every single language i have worked with has some well known or not so well known surprises,['php'] +7612,what coding tricks have you used to avoid writing more sql this question was suggested by kyralessa in the what is your most useful sql trick to avoid writing more sql i got so many good ideas to try from the last question that i am interested to see what comes up with this questiononce again i am not keeping the reputation from this question i am waiting 7 days for answers then marking it wiki the reputation that the question has earned goes into a bounty for the question ground ruleswhile it is certainly reasonable to write code to move processing from sql into the code to address performance issues that is really not the point of the question the question is not limited to performance issues the goal is less simply less sql to get the job donecommunicate the concept so that other users say oh wow i did not know you could do thatexample code is very useful to help people that are primarily visual learnersexplicitly state what language you are using and which dialect of sql you are usingput yourself in your readers shoes what would they need to see right there on the screen in front of them that will cause an epiphany your answer is there to benefit the reader write it for themoffsite links are ok if they appear after the example offsite links as a substitute for a real answer are notthere are probably other things to make it nicer for the reader that i have not thought of get creative share knowledge have fun showing offedit it looks like there hasent been any activity in a while 5 votes 50 so there is the bounty and it has been wikified,['sql'] +7619,gedit plugin development in python does anyone know where information about writing gedit plugins can be found i am interested in writing them in python i know of geditpythonpluginhowto but it is not very good besides the code of writing a plugin that does nothing i cannot seem to find more information i started to look at other peoples code but i think this should not be the natural way of writing plugins can someone help,['python'] +7621,programmatic msil injection let us say i have a buggy application like thisusing systemnamespace consoleapplication1 class program static void mainstring args consolewriteline2 1 0 add2 1 static int addint x int y return x x oops the application is already compiled and deployed into the wild someone has found the bug and now they are requesting a fix for it while i could redeploy this application with the fix its an extreme hassle for reasons outside of my control i just want to write a patch for the bug insteadspecifically i want to insert my own msil into the offending assmembly source file i have never done anything like this before and googling has not turned up any useful information if i could just see a sample of how to do this on the code above it would help me out tremendously how do i programmatically inject my own msil into a compiled net assemblyedit to add to those who asked i do not need runtime hotswapping its perfectly fine for me to have the app closed manipulate the assembly then restart the program againedit one more time it looks like the general consensus is manipulating the assembly is a bad way to patch a program i would not go down that road if its a bad ideai will leave the question open because msil injection might still be useful for other purposes,['.net'] +7622,is there a css parser for c my program need to parse css files into an inmemory object format any advice on how this should be done,"['c#', 'css']" +7629,php xml parsing which is the best way to parse an xml file in php firstusing the dom object codedom new domdocumentdomloadxmlxmlroot domgetelementsbytagnametagforeachroot as tagsubchild rootgetelementsbytagnamechild extract values and loop again if neededsecondusing the simplexml load method codexml simplexml load stringxmlxmlroot xmlrootforeachroot as tagsubchild tagchild extract values and loop again if needednote these are the two i am aware of if there are more fill inwanted to know which method is the best for parsing huge xml files also which method is the fastest irrespective of the way the method needs to be implementedsize will be varying from 500kb to 2mb the parser should be able to parse small as well as large files in the least amount of time with good memory usage if possible,['php'] +7632,how to open a file for nonexclusive write access using net is it possible to open a file in net with non exclusive write access if so how my hope is to have two or more processes write to the same file at the same timeedit here is the context of this question i am writing a simple logging httpmodule for iis since applications running in different app pools run as thistinct processes i need a way to share the log file between processes i could write a complex file locking routine or a lazy writer but this is a throw away project so its not importantthis is the test code i used to figure out the processusing systemusing systemcollectionsgenericusing systemtextusing systemiousing systemthreadingnamespace fileopentest class program private static bool keepgoing true static void mainstring args consolecancelkeypress new consolecanceleventhandlerconsole cancelkeypress consolewriteenter name string name consolereadline open the file in a shared write mode filestream fs new filestreamfiletxt filemodeopenorcreate fileaccessreadwrite filesharereadwrite while keepgoing almostguaranteedappendname fs consolewritelinename threadsleep10 fsclose fsthispose private static void almostguaranteedappendstring stringtowrite filestream fs streamwriter sw new streamwriterfs force the file pointer to reseek the end of the file this is the key to keeping multiple processes from stomping each other when writing to a shared file fsposition fslength note there is a possible race condition between the above and below lines of code if a context switch happens right here and the next process writes to the end of the common file then fsposition will no longer point to the end of the file and the next write will overwrite existing data for writing periodic logs where the chance of collision is small this should work swwritelinestringtowrite swflush private static void console cancelkeypressobject sender consolecanceleventargs e keepgoing false,['.net'] +7636,open webconfig from console application i have a console capplication that runs on the same computer that hosts a bunch of webconfig files i need the console application to open each webconfig file and decrypt the connection string and then test if the connection string worksthe problem i am running into is that openexeconfiguration is expecting a winforms application configuration file appdllconfig and openwebconfiguration needs to be run through iis since this is my local machine i am not running iis i use visual studios builtin serveris there a way i can open the webconfig files while still getting the robustness of nets capabilities to decrypt the connectionstringsthanksupdatethe openwebconfiguration works if you are querying iis directly or are the website in question that you want to look up the webconfig for what i am looking to accomplish is the same sort of functionality but from a console application opening up the webconfig file of a website on my same machine not using an iis query because iis is not running on my machine,['asp.net'] +7642,should i use javas stringformat if performance is important we have to build strings all the time for log output and so on over the jdk versions we have learned when to use stringbuffer many appends thread safe and stringbuilder many appends nonthreadsafewhats the advice on using stringformat is it efficient or are we forced to stick with concatenation for oneliners where performance is importanteg ugly old stylestring s what do you get if you multiply varsix by varnine vs tidy new style and possibly slowstring s stringformatwhat do you get if you multiply d by d varsix varninenote my specific use case is the hundreds of oneliner log strings throughout my code they do not involve a loop so stringbuilder is too heavyweight i am interested in stringformat specifically,['java'] +7653,html document to pdf i have got an aspnet web page that is a dynamically generated report for business reasons this exact report needs to be produced as a pdf whats the best way to do this setting the selected printer to adobe pdf is not an optionlearn to programmatically create pdfs from scratch is there a way to render it in some browser control then save the ouput,['asp.net'] +7657,how to validate numeric input c i would like to know how to limit an input value to signed decimals using stdcin,['c++'] +7661,is there any way to determine how many characters will be written by sprintf i am working in ci want to write a potentially very long formatted string using sprintf specifically a secure counted version like snprintf s but the idea is the same the approximate length is unknown at compile time so i will have to use some dynamically allocated memory rather than relying on a big static buffer is there any way to determine how many characters will be needed for a particular sprintf call so i can always be sure i have got a big enough buffermy fallback is i will just take the length of the format string double it and try that if it works great if it does not i will just double the size of the buffer and try again repeat until it fits not exactly the cleverest solutionit looks like c99 supports passing null to snprintf to get the length i suppose i could create a module to wrap that functionality if nothing else but i am not crazy about that ideamaybe an fprintf to devnullnul might work instead any other ideasedit alternatively is there any way to chunk the sprintf so it picks up midwrite if that is possible it could fill the buffer process it then start refilling from where it left off,['c++'] +7670,how do you deploy a website to your webservers at my company we have a group of 8 web developers for our business web site entirely written in php but that should not matter everyone in the group is working on different projects at the same time and whenever they are done with their task they immediately deploy it cause business is moving fast these days currently the development happens on one shared server with all developers working on the same code base using rcs to lock files away from others when deployment is due the changed files are copied over to a staging server and then a sync script uploads the files to our main webserver from where it is thistributed over to the other 9 serversquite happily the web dev team asked us for help in order to improve the process after us complaining for a while and now our idea for setting up their dev environment is as followsa dev server with virtual directories so that everybody has their own codebase svn or any other vcs to keep track of changesa central server for testing holding the latest checked in codethe question is now how do we manage to deploy the changed files on to the server without accidentaly uploading bugs from other projects my first idea was to simply export the latest revision from the repository but that would not give full control over the fileshow do you manage such a situation what kind of deployment scripts do you have in action as a special challenge the website has organically grown over the last 10 years so the projects are not split up in small chunks but files for one specific feature are spread all over the directory tree,['php'] +7673,how to set up headers and libraries for linux development i recently set up for a learning exercise an ubuntu desktop pc with kde 42 installed eclipse and started to look for information on how to develop for kde i know there is kdevelop and will probably have a look at that at some time in the future right now however i do not have the correct headers and libraries for creating kde applications in cc using eclipse if i have the followinginclude kapplicationhit fails to compile since there are dependancies on other header files that are not present on my hard thisk or reference classes that are not declared anywhereso the question is what packages do i need to install in order to have the correct set of headers to allow me to write applications for kde 42 are there any packages i should not have alternatively if there are no packages then where can i get the appropriate filesas a corollary are there any good tutorials on kde development something like the petzold windows bookedit clarifying what i am really after where can i download the correct set of header files libraries in order to build a kde application ides to compile code are not a real problem and are easy to get as is setting up compiler options for include search paths and so on does the kdevelop package have all the correct include and library files or are they separate i guess they are separate as kdevelop is an ide that can do other languages as well but i am probably wrong so the kdeqt header files i have do not work where do i get the right onesskizz,['c++'] +7687,relative paths not working in xcode c there are numerous post over the net that detail how relative paths do not work in xcode i do have an xcode template that i downloaded where the relative paths do work however i have not been able to figure out why nor replicate it in other projectsfirstly i am using c in xcode 31 i am not using objectivec nor any cocoacarbon frameworks just pure chere is the code that works in my other xcode templatesoundloadmusic stdstring resourcesaudiopopwav this relative path works for me also in windows running the following command gives me an absolute path to the applications full pathstdcout current directory is getcwd buffer 10 napplicationsmyapphow can we get relative paths to work in an xcode app bundle,['c++'] +7694,what does the visual studio any cpu target mean i have some confusion related to the net platform build options in visual studio 2008what is the any cpu compilation target and what sort of files does it generate i examined the output executable of this any cpu build and found that they are the x86 executables who would not see that coming so is there any the difference between targeting executable to x86 vs any cpuanother thing that i noticed is that managed c projects do not have this platform as an option why is that does that mean that my suspicion about any cpu executables being plain 32bit ones is right,['.net'] +7704,return eats exception i found the following behavior at least weirddef errors try errorerrorerror finally return 10print errors prints 10 it should raise nameerror name errorerrorerror is not definedthe exception thisappears when you use return inside a finally clause is that a bug is that documented anywherebut the real question and the answer i will mark as correct iswhat is the python developers reason to allow that odd behavior,['python'] +7705,why volatile is not enough i am confused answers to my previous question seems to confirm my assumptions but as stated here volatile is not enough to assure atomicity in net either operations like incrementation and assignment in msil are not translated directly to single native opcode or many cpus can simultaneously read and write to the same ram locationto clarifyi want to know if writes and reads are atomic on multiple cpusi understand what volatile is about but is it enough do i need to use interlocked operations if i want to get latest value writen by other cpu,['c#'] +7712,when not to use the entity framework i have been playing around with the ef to see what it can handle also many articles and posts explain the various scenarios in which the ef can be used however if miss the con side somehow now my question is in what kind of scenarios should i stay away from the entity framework if you have some experience in this field tell me what scenarios do not play well with the ef tell me about some downsides you experienced where you whished you would have chosen a different technology,"['c#', '.net']" +7717,how to clear python interpreter console like most python developers i typically keep a console window open with the python interpreter running to test commands dir stuff help stuff etclike any console after a while the visible backlog of past commands and prints gets to be cluttered and sometimes confusing when rerunning the same command several times i am wondering if and how to clear the python interpreter consolei have heard about doing a system call and either calling cls on windows or clear on linux but i was hoping there was something i could command the interpreter itself to donote i am running on windows so ctrll does not work,['python'] +7718,is javascript a passbyreference or passbyvalue language the primitive types number string etc are passed by value but objects are unknown because they can be both passedbyvalue in case we consider that a variable holding an object is in fact a reference to the object and passedbyreference when we consider that the variable to the object holds the object itselfalthough it does not really matter at the end i want to know what is the correct way to present the arguments passing conventions is there an excerpt from javascript specification which defines what should be the semantics regarding this,['javascript'] +7722,where is a good address parser i am looking for a good tool that can take a full mailing address formatted for thisplay or use with a mailing label and convert it into a structured objectso for instance start with a formatted address in a single stringstring f 18698 e main streetrnbig town az 86011 parse into addressaddress addr new addressfaddrstreet 18698 e main streetaddrlocality big townaddrregion azaddrpostalcode 86011now i could do this using regex but the tricky part is keeping it general enough to handle any address in the worldi am sure there has to be something out there that can do itif anyone noticed this is actually the format of the opensocialaddress object,['c#'] +7726,rotate a uiview around its center but several times i am trying to rotate some uiview around its center so the simple code goes something like in pseudocodeuiview beginanimationscrazyrotate contextniluiview setanimationduration10someviewtransform cgaffinetransformmakerotationangleuiview commitanimationsnow if i set angle to say m pi2 the thing rotates nicelyif i set it to 2m pi well it does nothing i can understand that the matrix translates to something that does nothing rotating 360 means stay in a senseyet i want to rotate it 5 times think of a newspaper rotate scale coming at you effect i am not great at describing hope someone understandsso i tried adding setting angle to 180 deg m pi and add a nested animatationblock but i guess that since i am setting the same property someviewtransition again it ignores it somehowi tried setting repeat count of the animation to 2 with angle m pi but it seems to simply rotate 180 going back to straight position and then initiating the rotate againso i am a little out of ideasany help appreciatedt,"['ios', 'objective-c']" +7743,is it possible to pass a method as an argument in objectivec i have a method that varies by a single method call inside and i would like to pass the methodsignature of the method that it varies by as an argument is this possible in objective c or is that too much to hope for,['objective-c'] +7750,network programming to maintain sockets or not i am currently translating an api from c to java which has a network componentthe c version seems to keep the input and output streams and the socket open for the duration of its classes being usedis this correctbearing in mind that the application is sending commands and receiving events based on user input is it more sensible to open a new socket stream for each messagei am maintaining a serversocket for listening to the server throwing events but i am not so sure that maintaining a socket and output stream for outbound comms is such a good ideai am not really used to socket programming as with many developers i usually work at the application layer when i need to do networking and not at the socket layer and it is been 5 or 6 years since i did this stuff at universitycheers for the help i guess this is more asking for advice than for a definitive answer,['java'] +7754,why is there no linq method to return thistinct values by a predicate i want to get the thistinct values in a list but not by the standard equality comparisonwhat i want to do is something like thisreturn mylistthistinct x y xurl yurl i cannot there is no extension method in linq that will do this just one that takes an iequalitycompareri can hack around it with thisreturn mylistgroupby x xurl select g gfirst but that seems messy it also does not quite do the same thing i can only use it here because i have a single keyi could also add my ownpublic static ienumerablet thistinctt this ienumerablet input functtbool compare write my own herebut that does seem rather like writing something that should be there in the first placeanyone know why this method is not theream i missing something,['c#'] +7758,where is python used i read about it a lot on reddit i have downloaded the pyscripter and learning python but i have no idea if it has any job value especially in india i am learning python as a hobby but it would be comforting to know if python programmers are in demand in india,['python'] +7760,jquery if div does not have class x in jquery i need to do an if statement to see if this does not contain the class selectedthumbshoverfunctionthisstopfadetonormal 10functionthisstopfadetoslow 03basically when this function is run on hover i do not want to perform the fades if the class selected has been appended to the div this will mean that the image will be at full opacity to signify that it is selected searched on google to no luck even though it is a simple question of how to use an if statement,['jquery'] +7764,how can i determine property types using reflection how would i test a property of a type to see if it is a specified typeedit my goal is to examine an assembly to see if any of the types in that assembly contain properties that are mytype or inherited from mytypehere is the track i have gone downassemblyname and new assemblynamencodebase file dllnameassembly a appdomaincurrentdomainloadnforeach type t in agettypes foreach propertyinfo pi in tgetproperties if pipropertytype is mytype warning cs0184 consolewritelinefound a property that is mytypethis compiles with warning cs0184 the given expression is never of the provided mytype type,"['c#', '.net']" +7770,googles imageless buttons there have been a few articles recently about googles new imageless buttonsi really like how these new buttons work in gmail how can i use these or similar buttons on my site are there any open source projects with a similar look feelif i wanted to roll my own button package like this using jqueryxhtmlcss what elements could i use my initial thoughts arestandard input typebutton with css to improve the look the design article talked mostly about the cssimges involvesjquery javascript to bring up a custom dialog rooted to the button on the onclick event which would have a tags in them and a search bar for filtering would a table layout for that popup be sanei am terrible at reverse engineering things on the web what are some of the tools that i could use to help reverse engineer these buttons using firefoxs web developer toolbar i cannot really see the css or javascript even if it is minified that is used on the buttons popup dialogs what browser tool or other method could i use to peek at them and get some ideasi am not looking to steal any of googles ip just get an idea of how i could create similar button functionality,"['javascript', 'html', 'css']" +7772,ie and memory accumulation in javascript here is the test urlprocedureclose all ie instancesopen the url in ie7open the task manager look for memory consumed by ienow click on create buttonwatch the memory it will jump up by about 2know click on destroy button and the div will be destroyed but the memory remains the sameyou can try it repeatedly and memory just adds upis there any way to fix this any way to call garbage collector forcefully without reloading the windowi am under assumption that when i remove div the memory will be freed but does not seem to work that wayplease let me know any fix to thisthanks for your helpsuhas,['javascript'] +7773,css maxheight not working i have a very simply problem where i need a div to expand to fit its contents unless the height reaches a certain size when i want the div to scroll vertically instead as a test i created a page containingdiv stylewidth300pxmaxheight25pxbackgroundcolorgreenoverflowauto 1br 2br 3br 4br 5divunfortunately the maxheight does not seem to work what am i doing wrongi am using ie7,"['html', 'css']" +7777,how to simulate windows shutdown for debugging i have an issue with my application when windows shuts down my app is not exiting nicely resulting in the end task window being thisplayed how can i use the debugger to see whats going on is there a way to send the windows shutdown messages to my application so it thinks windows is shutting down so i can see exactly how it behaves,"['c#', '.net']" +7781,examples of good java desktop applications more of a wiki listcollection i am looking for a list of good java desktop apps i have added a couple below to get started please list the frameworkwidget toolkit being used if it is know as well,['java'] +7786,rewriting urls in aspnet i am using aspnet chow do i implement url rewriting procedure that is similar to stackoverflowcomalso what is the meaning of values such as 358630 in the url is this the question id the basis for which they use to fetch the data from the table whatever it is in my application i am identifying records using an id field this field is an identity column in an sql table right now my urls are like the followingbut i would like them to appear like question titleor question titleor whatever the best way which will taste good to search botsmy application is hosted on go daddys shared hosting service and i feel that no customized aspnet http module or no customized dll for url rewriting is working on their server i tried many samples but no luck yeti found that stack overflow is hosted on go daddy shared hosting maybe stack overflows method will work for me,"['c#', 'asp.net']" +7800,how can i set the value of auto property backing fields in a struct constructor given a struct like thispublic struct somestruct public somestructstring stringproperty int32 intproperty thisstringproperty stringproperty thisintproperty intproperty public string stringproperty get set public int32 intproperty get set of course a compiler error is generated that reads the this object cannot be used before all of its fields are assigned tois there a way to assign values to the backing fields or the properties themselves or do i have to implement properties the oldfashioned way with my own explicit backing fields,['c#'] +7809,passing a method as a parameter in ruby i am trying to mess around a little bit with ruby therefor i try to implement the algorithms given in python from the book programming collective intelligence rubyin chapter 8 the author passes a method a as parameter this seems to work in python but not in rubyi have here the methoddef gaussianthist sigma100 fooendand want to call this with another methoddef weightedknndata vec1 k 5 weightf gaussian foo weight weightfthist fooendall i got is an errorargumenterror wrong number of arguments 0 for 1,['ruby'] +7810,how can i strip python logging calls without commenting them out today i was thinking about a python project i wrote about a year back where i used logging pretty extensively i remember having to comment out a lot of logging calls in innerlooplike scenarios the 90 code because of the overhead hotshot indicated it was one of my biggest bottlenecksi wonder now if there is some canonical way to programmatically strip out logging calls in python applications without commenting and uncommenting all the time i would think you could use inspectionrecompilation or bytecode manipulation to do something like this and target only the code objects that are causing bottlenecks this way you could add a manipulator as a postcompilation step and use a centralized configuration file like soleave error and abovemy modulesomeclassmethod with lots of warn callsleave warn and abovemy modulesomeotherclassmethod with lots of info callsleave info and abovemy modulesomeweirdclassmethod with lots of debug callsof course youd want to use it sparingly and probably with perfunction granularity only for code objects that have shown logging to be a bottleneck anybody know of anything like thisnote there are a few things that make this more difficult to do in a performant manner because of dynamic typing and late binding for example any calls to a method named debug may have to be wrapped with an if not isinstancelog logger in any case i am assuming all of the minor details can be overcome either by a gentlemans agreement or some runtime checking,['python'] +7811,android textview timer for my android application there is a timer that measures how much time has passed ever 100 milliseconds i update my textview with some text like score 10 time 10010 seconds but i find the textview only updates the first few times the application is still very responsive but the label will not update i tried to call invalidate but it still does not work i do not know if there is some way to fix this or a better widget to usehere is a example of my codefloat secondsjavautiltimer gametimervoid updatecount textview t textviewfindviewbyidridtopscoretsettextscore 10 time seconds secondstpostinvalidatepublic void oncreatebundle sis load the ui etc gametimerschedulenew timertask public void run seconds01 updatecount 100 100,"['java', 'android']" +7821,is there a view for inputing integers in android i am looking for something like the individual parts of the date picker dialog a view that allows you to input integers and only integers that you can limit between 1 and 10 for example where you can use the keyboard or the arrows in the view itself does it existsit is for a dialog a readymade dialog to request an integer would also help,['android'] +7830,sockets in c how to get the response stream i am trying to replace thisvoid processrequestobject listenercontext var context httplistenercontextlistenercontext uri url new uricontextrequestrawurl httpwebrequestdefaultwebproxy null httpwebrequest httpwebrequest httpwebrequestwebrequestcreateurl httpwebrequestmethod contextrequesthttpmethod httpwebrequestheadersclear if contextrequestuseragent null httpwebrequestuseragent contextrequestuseragent foreach string headerkey in contextrequestheadersallkeys try httpwebrequestheaderssetheaderkey contextrequestheadersheaderkey catch exception using httpwebresponse httpwebresponse httpwebresponsehttpwebrequestgetresponse stream responsestream httpwebresponsegetresponsestream if httpwebresponsecontentencodingtolowercontainsgzip responsestream new gzipstreamresponsestream compressionmodedecompress else if httpwebresponsecontentencodingtolowercontainsdeflate responsestream new deflatestreamresponsestream compressionmodedecompress memorystream memstream new memorystream byte respbuffer new byte4096 try int bytesread responsestreamreadrespbuffer 0 respbufferlength while bytesread 0 memstreamwriterespbuffer 0 bytesread bytesread responsestreamreadrespbuffer 0 respbufferlength finally responsestreamclose byte msg memstreamtoarray contextresponsecontentlength64 msglength using stream strout contextresponseoutputstream stroutwritemsg 0 msglength catch exception ex some error handling with sockets this is what i have so farvoid processrequestobject listenercontext httplistenercontext context httplistenercontextlistenercontext uri url new uricontextrequestrawurl string getstring stringformatget 0 http11rnhost 1rnacceptencoding gziprnrn contextrequesturlpathandquery contextrequestuserhostname socket socket null string hostandport if contextrequestuserhostnamecontains hostandport contextrequestuserhostnamesplit else hostandport new string contextrequestuserhostname 80 iphostentry ipaddress dnsgethostentryhostandport0 ipendpoint ip new ipendpointipaddressparseipaddressaddresslist0tostring intparsehostandport1 socket new socketipaddressfamily sockettypestream protocoltypetcp socketconnectipbegin new codeencoding ascii encodingasciibyte bytegetstring asciigetbytesgetstringbyte receivebyte new byte256string response stringemptysocketsendbytegetstring bytegetstringlength 0int32 bytes socketreceivereceivebyte receivebytelength 0response asciigetstringreceivebyte 0 byteswhile bytes 0bytes socketreceivereceivebyte receivebytelength 0strpage strpage asciigetstringreceivebyte 0 bytessocketclosestring separator rnrnstring header strpagesubstring0strpageindexofseparatorstring content strpageremove0 strpageindexofseparator 4byte byteresponse asciigetbytescontentcontextresponsecontentlength64 byteresponse lengthcontextresponseoutputstreamwritebyteresponse 0 byteresponse lengthcontextresponseoutputstreamcloseend new codeafter connecting to the socket i do not know how to get the stream response to decompress and send back to contextresponseoutputstreamany help will be appreciatedthankscheersedit 2with this edit now seems to be working fine same as httpwebrequest at least do you find any error hereedit 3false alarm still cannot get this workingedit 4i needed to add the following lines to scotts code because not always the first to bytes of reponsestream are the gzip magic numberthe sequence seems to be 0x0a 10 0x1f 31 0x8b 139 the last two are the gzip magic number the first number was always before in my testsif contentencodingequalsgzip int magicnumber 0 while magicnumber 10 magicnumber responsestreamreadbyte responsestream new gzipstreamresponsestream compressionmodedecompress,['c#'] +7831,aspnet your most used httpmodules interested in description of your most used aspnet httpmodules that solved a specific problem for your webappbest practices and inthefield usages are welcome,"['c#', 'asp.net', '.net']" +7837,best practice for pk in sql server i have been wondering what the best practices or ramifications are in setting up the pk in a m2m table in sql server for instancei have 2 tablesusersrolesi am making a new tableuserrolewhich has 2 fields roleid useridnow should i create a userroleid as the pk and make userid and roleid the fksmake the pk userid and roleid and set them as fkssomething elsei would like to know the performance issues with each of the options and what the recommended best practices are,['sql'] +7843,c combobox in dropdownlist style how do i set the text i want to use a combobox with the dropdownlist style the one that makes it look like a button so you cannot enter a value to insert a value into a text box i want the combobox to have a text label called wildcards and as i select a wildcard from the list the selected value is inserted in to a text box and the combobox text remains wildcard my first problem is i cannot seem to set a text value when the combobox is in dropdownlist style using the properties pallet does not work the text value is simply cleared when you click off adding comboboxtext wildcards to form load does not work either can anyone help,"['c#', '.net']" +7846,numpy pil adding an image i am trying to add two images together using numpy and pil the way i would do this in matlab would be something like m1 imread 1jpg m2 imread 2jpg resm m1 m2 imwriteresm resjpgi get something like thisusing a compositing program and adding the images the matlab result seems to be rightin python i am trying to do the same thing like thisfrom pil import imagefrom numpy import im1 imageopenusersrem7desktop 1jpgim2 imageopenusersrem7desktop 2jpgim1arr asarrayim1im2arr asarrayim2addition im1arr im2aresultimage imagefromarrayadditionresultimagesaveusersrem7desktopajpgand i get something like thiswhy am i getting all those funky colors i also tried using imagemathevalab aim1 bim2 but i get an error about rgb unsupportedi also saw that there is an imageblend but that requires an alphawhats the best way to achieve what i am looking forsource images images have been removedhumm ok well i added the source images using the add image icon and they show up when i am editing the post but for some reason the images do not show up in the post images have been removed 2013 05 09,['python'] +7849,which design pattern to use for filtering query c i have a database table with a list of products clothing the products belong to categories and are from different storessample categories tops bottoms shoessample stores gapcom macyscom targetcommy customers can request to filter products in the following waysall products no filterby categoryby storeby category and storeright now i have one method in my products class that returns the products depending on the type of filter requested by the user i use a filterby enum to determine which products need to be returnedfor example if the user wants to view all products in the tops category i call this functionproductsgetproductsfilterbycategory tops i have the last parameter empty because it is the string that contains the store to filter by but in this case there is no store however if the user wants to filter by category and store i would call the method this wayproductgetproductsfilterbycategoryandstore tops macyscommy question is whats a better way to do this i just learned about the strategy design pattern could i use that to do this in a better easier to extend and easier to maintain waythe reason i am asking this question is because i figure this must be a pretty common problem that people are repeatedly solving filtering products in various ways,"['c#', 'asp.net']" +7853,how to remove diagramming support objects from sql server i need to remove diagramming support tables stored procs views etc from sql servrer using tsql script is there such a script available sql 2005 and 2008,['sql'] +7855,large text and images in sql is it a good idea to store large amounts of text eg html pages inside your sql database or is it a better idea to store it as html files in the filesystemthe same goes for images is it a good idea to store image data in the database or better to put them on thiskwill storing large amounts of data cause me performance problems for example what are the pros and cons of each method of storagein terms of the size of data in this case i am looking in the region of a few pages of html and images less than about 500kb in size probably a lot smaller though enough to produce your average articleblog entryetc scale web page,"['sql', 'mysql']" +7863,byte order with a large array of characters in c hey guys question from a cnetworking newbiei am doing some socket programming in c and trying to wrestle with byte order problems my request send is fine but when i receive data my bytes are all out of order i start with something like thischar aresponse char malloc512int total recvsock aresponse 511 0when dealing with this response each 16bit word seems to have it is bytes reversed i am using udp i tried to fix that by doing something like this unsigned short netorder unsigned short aresponse unsigned short newhostorder unsigned short malloctotal for i 0 i total i newhostorderi ntohs netorderi this works ok when i am treating the data as a short however if i cast the pointer to a char again the bytes are reversed what am i doing wrongthanks,['c'] +7864,handling overflow when casting doubles to integers in c today i noticed that when i cast a double that is greater than the maximum possible integer to an integer i get 2147483648 similarly when i cast a double that is less than the minimum possible integer i also get 2147483648 is this behavior defined for all platformswhat is the best way to detect this underoverflow is putting if statements for min and max int before the cast the best solution,"['c++', 'c']" +7874,c programming how to program for unicode what prerequisites are needed to do strict unicode programmingdoes this imply that my code should not use char types anywhere and that functions need to be used that can deal with wint t and wchar tand what is the role played by multibyte character sequences in this scenario,['c'] +7875,autoincrement fields on databases without autoincrement field in ms sql server is easy create autoincrement fields in my systems i stopped to use autoincrement fields for primary keys and now i use guids it was awesome i have got a lot of advantages with that change but in another nonprimary key fields i really was needing implement a soft autoincrement it is because my system is db independent so i create the autoinc value programatically in c i would like about solutions for autoincrement fields on databases without autoincrement what the solution that your use and why there is some sql ansi statement about this and generating directly from my c is a better solutionps i know that select maxid1 from table it is not really concurrent friendly,['sql'] +7878,how do i find the position of a cursor in a text box c i have a standard winforms textbox and i want to insert text at the cursors position in the text how can i get the cursors positionthanks,['c#'] +7882,f naming convention is there an official naming casing convention for fi am always in doubt of using c style or not classmyfunctionname or modulemy function namein f youre meant to mix bcl classes and f library ones they have different casing and the code looks very ugly,['.net'] +7895,how to deploy a python application with libraries as source with no further dependencies background i have a small python application that makes life for developers releasing software in our company a bit easier i build an executable for windows using py2exe the application as well as the binary are checked into subversion thistribution happens by people just checking out the directory from svn the program has about 6 different python library dependencies eg elementtree makothe situation developers want to hack on the source of this tool and then run it without having to build the binary currently this means that they need a python 26 interpreter which is fine and also have the 6 libraries installed locally using easy installthe problemthis is not a public classical open source environment i am inside a corporate network the tool will never leave the walled garden and we have seriously inconvenient barriers to getting to the outside internet ntlm authenticating proxies andor machines without direct internet accessi want the hurdles to starting to hack on this tool to be minimal nobody should have to hunt for the right dependency in the right version they should have to execute as little setup as possible optimally the prerequisites would be having a python installation and just checking out the program from subversionanecdote the more selfcontained the process is the easier it is to repeat it i had my machine swapped out for a new one and went through the unpleasant process of having to reverse engineer the dependencies reinstall thistutils hunting down the libraries online and getting them to install see corporate internet restrictions above,['python'] +7897,how can i create a pfx file from a java keystore i have a java keystore jks file holding a single certificate how can i create a pfx file from this keystore,"['java', '.net']" +7898,what is a good desktop programming language to learn for a web developer i am want to learn a desktop programming language preferably c c or c i am a phphtmlcss programmer and i would like to get into desktop applications i need something pretty powerful and i would like to be able to create applications with windows guis what would the stack overflow community recommend is there any knowledge i should have before diving into these languages,"['c#', 'c++', 'c']" +7900,calculate a ratio in c i thought this would be simple but searching google did not seem to helpi am basically trying to write a function which will return a ratio as a string eg 43 when supplies with two integers eg 800 and 600string getratioint a int b code i am looking for return ratio,['c#'] +7906,what is the format accepted by systemnetmailmailaddress parser i am working on an app that is using systemnetmailmailaddress and friends for sending emails does that parser implement the full rfc5322 or a subset or what the msdn is not very forthcoming on this topicany hints appreciated,['.net'] +7910,lambda cannot be inferred from the usage i have the following dictionary declaredprivate readonly dictionaryint image dictionaryand i have a method which is causing a compiler error public iqueryableimage findfuncimage bool exp return dictionarysingleexp the error i get is error 1the type arguments for method systemlinqenumerablesingletsourcesystemcollectionsgenericienumerabletsource systemfunctsourcebool cannot be inferred from the usage try specifying the type arguments explicitlycworkmsdaidsimagesmsdaidsimagestesttestimagerepositorycs3430msdaidsimagestesti have tried googling around i cant seem to find anything definitive as to what i am doing wrongedit this is monday morning at worki meant to put where not singleedit 2ok the code is now thispublic iqueryableimage findfuncimage bool exp return dictionaryvalueswhereexpnow i get the following errorerror 1cannot implicitly convert type systemcollectionsgenericienumerablemsd aids images dataimage to systemlinqiqueryablemsd aids images dataimage an explicit conversion exists are you missing a castcworkmsdaidsimagesmsdaidsimagestesttestimagerepositorycs3420msdaidsimagestestas an fyi the method there is for implementing an interface the declaration for that isiqueryablet findfunct bool expthis has got more complicated than it should be,['c#'] +7919,sql sort by version number a string of varying length i am trying to create an sql query that will order the results by a version number eg 11 4510 etcheres what i triedselect from requirements where requirementsrelease not like obsolete order by requirementsreqnumnow the reqnum field is a string field and unfortunately i cannot change it to a float or something like that because i have requirement numbers like 1621when i get the results back i will get ordering like this1013how can i write a query that will sort by lexicographic order orhow can i correctly sort the datathanks for the input in advance,['sql'] +7929,including a service reference from a class library i have a c class library and a startup project a console app the class library includes a service reference to a web service when i try to run the project i get an invalidoperationexception because the startup project is not reading the class librarys appconfig and it is ignoring the service reference to get it working i am forced to add the same service reference to the startup project is there any way i can avoid this can i make the startup project recognize the class librarys service reference and appconfig without having to copy it to the startup projecti have tried adding a link to the appconfig from the class library but that does not work the class library is not very portable if it requires anyone who uses it to add that service reference to the startup project,['c#'] +7935,django how to prepopulate admin form fields i know that you can prepopulate admin form fields based on other fields for example i have a slug field that is automatically populated based on the title fieldhowever i would also like to make other automatic prepopulations based on the date for example i have an url field and i want it to automatically be set to where 20090209 is ymmdd i would also like to have a text field that automatically starts with something like hello my name is author where author is the current users name of course i also want the person to be able to edit the field the point is to just make it so the user can fill out the admin form more easily and not just to have fields that are completely automatic,['python'] +7939,is it possible to thisplay a message in an empty datagrid i have a datagrid which is populated with csv data when the user dragdrops a file onto it is it possible to thisplay a message in the blank grid for example please drag a file here or this grid is currently empty the grid currently thisplays as a dark grey box as i wait until the file is dragged to setup the columns etc,['c#'] +7947,sftp libraries for net can anyone recommend a good sftp library to use right now i am looking at products such as secureblackbox ipworks ssh wodsftp and rebex sftp however i have never used any sftp library before so i am not sure what i am looking forif anyone has used these before is there any reason why i should go with product x over ythanks,"['c#', '.net']" +7953,python 2x gotchas and landmines the purpose of my question is to strengthen my knowledge base with python and get a better picture of it which includes knowing its faults and surprises to keep things specific i am only interested in the cpython interpreteri am looking for something similar to what learned from my php landminesquestion where some of the answers were well known to me but a couple were borderline horrifyingupdate apparently one maybe two people are upset that i asked a question that is already partially answered outside of stack overflow as some sort of compromise heres the url gotchashtmlnote that one or two answers here already are original from what was written on the site referenced above,['python'] +7957,a serious issue with jquery and activex security has anyone not noticed that jquery uses activex controlswhen a user has limited their activex security they will get script prompt popups and a yellow bar accross the top of their browser window this setting is by default on windows servers internet cafes dont support active xcompany internal workstations dont support thisconsidering this i do not see how people can use jquery in a commercial applicationdo you use jquery in a commercial application does this concern you do you think i should be concerned with this,"['javascript', 'jquery']" +7958,net optimized int32 while reading through the 70536 training kit it states the runtime optimizes the performance of 32bit integer types int32 so use those types for counters and other frequently accessed integral variablesdoes this only apply in a 32 bit environment does int64 take over in a 64 bit environment or is int32 still the better choice,['.net'] +7963,design order firefox ie or both when coding new javascript heavy websites which order or web browser do you code fori can see these possible orders but i am not sure which i like bestcode for one first and get it working well then start testing with other and fix errors as i gothis will allow for the most rapid development with firefox at least but i have learned from experience that debugging ie with so much going on at once can be a paincode for both at the same time in other words for each new feature ensure it works with both browsers before moving onthis seems like it will actually take more time so maybe do several features in firefox then move to ie to patch them upwhat do you all doedit 1 to respond to a couple of answers herejquery usage for some reason i was not expecting this kind of a response however now that this seems to be the overwhelming accepted answer i guess i should tell everyone a few more things about the specifics of my app this is actually the dynweb that i started another question for and as i am developing a lot of the important code seems to require that i use documentwhatever instead of any jquery or prototype functions that i could find specifically when dynamically importing changing css i have to use some similar tovar cssid documentall rules cssrules found this to take care of ie and firefoxdocumentstylesheetssheetindexcssidcssrulestyleelement valueand i expect that i will have to continue to use this kind of raw coding currently unsupported by either jquery or prototype in the future so while i would normally accept jquery as an answer i cannot as it is not a solution for this particular webappwedge and bigmattyh as the webapp is supposed to build other webapps part of the criteria is that anything it builds look and work functionally the same in whatever browsers i support right now i am thinking firefox and ie78 atm maybe more later on so as this is a more interesting and much more complicated problem are there any sites references or insights you may have for specific trouble areas css entities specific javascript pitfalls and differences etc and how to avoid them i am almost certain that i am going to have to have some sort of isie variable and simply perform different actions based on that but i would like to avoid it as much as possiblethanks for your input so far i will keep this open for the rest of the day to see what others may have to say and will accept an answer sometime tonight,['javascript'] +7982,threading in an application server i have a java programthread that i want to deploy into an application server glassfish the thread should run as a service that starts when the application server starts and stops when the application server closes how would i go about doing this it is not really a session bean or mdb it is just a thread,['java'] +7986,tabs in html mode in emacs so i have started using emacs and i love it however i am a tab person unless i am working on a project that is already using spaces i use tabs i mostly do php and html work i have got tabs in php working well but i cannot figure out how to have html mode use tabs instead of two spaceshere is what i have so farsetq cdefaultstyle pythonsetqdefault cbasicoffset 4 tabwidth 4 indenttabsmode twhat can i set so that html mode will use tabsedit using emacs 2231,['html'] +7991,dependency graph for rails partials in my current ruby on rails view we have many views and partials so many in fact that it is not clear which view uses which partial which itself may use other partials as wellthe question is if there is a tool out there that generates a dependency graph of all views and partials ideally generating a graph but that is easy to do or how you have solved this problem,"['ruby-on-rails', 'ruby']" +8000,allow net 20 runtime to run executables from network with full trust guys this cannot be for reali am trying to make a net 20 executable run from a network drive and it turns out that since microsoft net 20 has no mscorcfgmsc installed on server 2003 in order to get one i have to install the full sdk i simply want to run the dang thing without downloading 350mb piece of crapsorry for rant anyone can think of an easy solutionedit1 there seems to be a misunderstanding as to what is it that i want to achieve this is for my test environment i have many virtual machines and all i want is to just thisable the dang security altogether the task seems to be so trivial yet it seems so far i have to deploy sdk or 35 sp1 or some other multiterabyte package to every machine in order to achieve it,['.net'] +8001,ninject resolving an object by type and registration nameidentifier i am looking for a way to do something like this with ninject sample from the unity application blockimyservice result mycontainerresolveimyservicedata from is it possible,['c#'] +8002,what does self refer to in a classmethod i thought i was starting to get a grip on the python way of programming methods of a class accept self as the first parameter to refer to the instance of the class whose context the method is being called in the classmethod decorator refers to a method whose functionality is associated with the class but which does not reference a specific instanceso what does the first parameter of a classmethod canonically self refer to if the method is meant to be called without an instance reference,['python'] +8004,dynamic thispatch and binding are dynamic thispatch and dynamic binding the same thingthanksmaciej,"['c#', 'java']" +8009,how to build apples gcc on linuxwindows i do not have a mac but i have an iphone i want to develop applications for iphoneafter some research i think i need just the headers and library from the free sdk and a gcc build that supports armmachoapple released the code for gcc used in the iphone sdk they had to so i think if i could build it on windows or linux i can use it with the headers and libs from the sdk to develop iphone appsi can then install the app on any jailbroken iphonehow to build it on any non apple machine,"['ios', 'iphone']" +8015,mssql select statement with incremental integer column not from a table i need if possible a tsql query that returning the values from an arbitrary table also returns a incremental integer column with value 1 for the first row 2 for the second and so onthis column does not actually resides in any table and must be strictly incremental because the order by clause could sort the rows of the table and i want the incremental row in perfect shape alwaysthanks in advanceeditsorry forgot to mention must run on sql server 20,['sql'] +8023,return anonymous type results using the simple example below what is the best way to return results from multiple tables using linq to sqlsay i have two tablesdogs name age breedidbreeds breedid breednamei want to return all dogs with their breedname i should get all dogs using something like this with no problemspublic iqueryabledog getdogs var db new dogdatacontextconnectstring var result from d in dbdogs join b in dbbreeds on dbreedid equals bbreedid select d return resultbut if i want dogs with breeds and try this i have problemspublic iqueryabledog getdogswithbreednames var db new dogdatacontextconnectstring var result from d in dbdogs join b in dbbreeds on dbreedid equals bbreedid select new name dname breedname bbreedname return resultnow i realize that the compiler would not let me return a set of anonymous types since it is expecting dogs but is there a way to return this without having to create a custom type or do i have to create my own class for dogswithbreednames and specify that type in the select or is there another easier way,['c#'] +8026,zend form how do i make it bend to my will i have read the manual many times i have scoured the posts offered by google on the subject i have even bought a couple of books that deal with zf now why am i still confusedi can using zend form make a form that validates and functions fine what i cannot do it make a form that looks exactly like i want it to look with the error messages that i want it to have i want custom buttons i want funky layouts i want to insert text in the midst of the form etc does anyone have a simple way of achieving these sorts of things something that makes me feel like the framework is saving me time rather than costing i could forego zend form make my own form have its action hit a page to validate and process the posted data and i could do it about as fast as i can type but i really want to get this and be able to use it as it was apparently intended any advice any simple how tos for custom buttons funky layouts and basic or rather advanced as there are tons of basic tutorials that skip over the harder issues getting things done with zend form,['php'] +8030,tracking the script execution time in php php must track the amount of cpu time a particular script has used in order to enforce the max execution time limit is there a way to get access to this inside of the script i would like to include some logging with my tests about how much cpu was burnt in the actual php the time is not incremented when the script is sitting and waiting for the databasei am using a linux box,['php'] +8031,how to add nsdebugh and use nszombie in iphone sdk i want to enable nszombies for my iphone appi have read several articles online and i am still unsure of the exact procedurei know i have to set the environment variables which i have donenszombieenabled yesnsdebugenabled yesnsdeallocatezombies noi think i am not sure i have to import nsdebughwhen i check the headers of the foundation framework in my project there is no nsdebughafter some research i found them in the iphonesimulator foundation frameworkso and i am not sure if this is correct i imported the iphonesimualtor foundation framework into my projecti noticed that the file still does not show up in the project window even though i can locate it in the finderis this normal behaviorso i opened up main and addedifdef target iphone simulatorimport foundationnsdebughendifi am not sure if that is right either after this i still cannot get the nszombie to work unless i have misunderstood what it is supposed to doi am expecting to see a log of nszombie sent a release or something but i do not see anythingi am sure i am just not doing this right a good step by step would be appreciatedthanksalso of note i have also enablednsmallocstackllogging yesmallocstackloggingnocompact yes,['iphone'] +8033,is if variable the same as if variable nil in objectivec i am getting a exc bad access sigbus on this line in my iphone projectif timeouttimer timeouttimer invalidatethe thing that has me stumped is that i do not understand how that line could crash since the if statement is meant to be checking for nil am i misunderstanding the way objectivec works or do line numbers in crash statements sometime have the wrong line in them,"['objective-c', 'iphone']" +8034,jquery set attribute for tag i am use exprattrhashvalue to set a hash attribute for html anchor element a but the jquery would not do that but if i change expr to div then i can sethash attribute to div tagis this behavior a xhtml specification i can set id of a tag attribute since id is a built in attribute for html a tag,['jquery'] +8035,adding new methods to linq to sql generated classes i am new to linq i just dragged all my database tables onto the designer in a linq to sql dbml all my relationships are correct and look nice in the designer i am able to pull data using simple linq code i want to add my own methods now but do not want to blow away my changes if when i need to regenerate my dbml i am guessing i just create a new class file and setup partial classes of the generated classes is this correct for example i have a generated class called systemuser which contains the columns systemuserid username password personid securityquestionid securityquestionresponse i want to add a method called void authenticate and a new property called bool authenticated basically i want to pass in a username and password to authenticate and set the authenticated property based on finding a matching user etc where and how would i do this,['asp.net'] +8048,check browsers cache for a js file how can i check for a javascript file in users cache if he refreshed the page or visits the site after sometime i need not download that js file again does the js files get cleaned up after a site is closed,['javascript'] +8050,how does excel vsto work how does excel vsto work if i create an excel workbook solution in visual studio 2005 i can then happily code away with full access to the excel object model and even treat the excel sheet as a design surface when i build the solution i get a xls file and a dll containing my c codei can now start up the excel sheet just by double clicking on the xls and there is my sheet functioning with all my c code and any controls i dropped on the sheet etchow is the sheet referencing the dll what part of the excel workbooksheet tells it that it needs to fire up the clr and host my assembly,['c#'] +8056,drop all the tables stored procedures triggers constraints and all the dependencies in one sql statement is there any way in which i can clean a database in sql server 2005 by dropping all the tables and deleting stored procedures triggers constraints and all the dependencies in one sql statementreason for requesti want to have a db script for cleaning up an existing db which is not in use rather than creating new ones especially when you have to put in a request to your db admin and wait for a while to get it done,['sql'] +8058,entity attachment issues in linq i am trying to attach a linq entity to the data context after i receive it from a form post however all i get is the following exceptionan entity can only be attached as modified without original state if it declares a version member or does not have an update check policyi have also tried attaching the original row like sodatacontextpeopleattachperson originalpersonin this case i get the following exceptionobject reference not set to an instance of an objectheres the code in my controlleracceptverbshttpverbspostpublic actionresult editint id person person var prevperson datacontextpeoplesinglep pid id datacontextpeopleattachperson prevperson datacontextsubmitchanges return redirectpeopleindexany ideas on what i am doing wrong here i can post the entity code if needed,['c#'] +8063,block commenting in ruby does ruby have block commentsif not is there an efficient way of inserting in front of a block of highlighted code in textmate,['ruby'] +8066,how to connect to a secure website using ssl in java with a pkcs12 file i have a pkcs12 file i need to use this to connect to a webpage using https protocol i came across some code where in order to connect to a secure web page i need to set the following system propertiessystemsetpropertyjavaxnetssltruststore mytruststoresystemsetpropertyjavaxnetssltruststorepassword changeitsystemsetpropertyjavaxnetsslkeystoretype pkcs12systemsetpropertyjavaxnetsslkeystore new certp12systemsetpropertyjavaxnetsslkeystorepassword newpassi have the p12pkcs12 file all i need is a truststore filei extracted the certificates usingopensslexe pkcs12 in cmykeyp12 out ccerttxt nokeys clcertsnow converted the cert pem file to deropensslexe x509 in ccerttxt outform der out ccacertdernow adding the der file to a keystorekeytool import file ccacertder keystore mytruststorenow i have the truststore but when i use it i get the following errorexception in thread main javanetsocketexception javasecuritynosuchalgorithmexception error constructing implementation algorithm default provider sunjsse class comsunnetsslinternalssldefaultsslcontextimplupdate after removing certain properties and setting only the truststore truststorepassword and truststoretype property i got the following exceptionjavasecurityinvalidalgorithmparameterexception the trustanchors parameter must be nonemptyplease help,['java'] +8077,differences between wpf frame and webbrowser controls i am working on a webenabled media center which will be able to load video feeds into a gallery style view like coolirisrather than loading thumbnail images of each video i plan to load the actual video so it can be played inplace andor popped out to fullscreenthis means i need to host a bunch of flashplayer instances inside my wpf pageis there any advantage to using a frame control rather than an sp1 webbrowser control i know that while the webbrowser is technically a wrapped windows forms control and the frame control is native wpf even the frame control uses a win32 msinternalcontrolswebbrowser to show content given this fact are the two controls roughly equivalent especially as performance is concerned,['.net'] +8079,getting the value of a form field after keypress event myinputvalue is one keystroke behind when i examine it in a keypress event handler so if the users types a myinputvalue gives me then when the user types b myinputvalue gives me a and so it the value does not seem to get updated with the character input by the keystroke that triggered the event what am i doing wrongthanksmorgan,['javascript'] +8081,whats the best way to manage a dependency tree in net in my last project we used msbuild as a scripting language yeah really we also wrote hundreds of custom msbuild tasks for the parts that made more sense in c i even wrote an msbuild task to generate the boilerplate code for an msbuild task yes it consumed itselfwhile i do not recommend anyone else take this same approach one of the things i found very helpful was the builtin dependency management as youd expect it was easy to express dependency relationships and let msbuild take care of satisfying them for example almost every step in our software required that a certain set of files be copied to a certain location you could easily writestep1 copyfilesstep2 copyfiles step1and when you execute step2 it would only copy the files oncebuilding and satisfying a dependency tree is a pretty common in software i wish the msbuild team would take their dependency management code decouple it from msbuild and move it in to the net framework where anyone can use it baring that what do you think is the best option for managing dependencies this way,['.net'] +8082,whats a good html template engine for c possible duplicatec html template framework templatizing library html generator library planning to write a website in c would like to use a template system like clearsilver but maybe there is a better alternative,['c++'] +8085,app data web applications data directory how secure is it in many places in msdn documentation you can find references to app data directory for example here we can readto improve security when using a local data file in an aspnet application you should store the data file in the app data directory andfiles stored in the app data directory will not be served to the webi could not find a direct reference that would specify how is that security guaranteed are there any iis settings etc that i should watch out to ensure that the files we put in the app data directory suddenly do not become available to everyone,['asp.net'] +8090,proper use of the ithisposable interface i know from reading the msdn documentation that the primary use of the ithisposable interface is to clean up unmanaged resourcesto me unmanaged means things like database connections sockets window handles etc but i have seen code where the thispose method is implemented to free managed resources which seems redundant to me since the garbage collector should take care of that for youfor examplepublic class mycollection ithisposable private liststring thelist new liststring private dictionarystring point thedict new dictionarystring point die clear it up free unmanaged resources public void thispose thelistclear thedictclear thelist null thedict null my question is does this make the garbage collector free memory used by mycollection any faster than it normally wouldedit so far people have posted some good examples of using ithisposable to clean up unmanaged resources such as database connections and bitmaps but suppose that thelist in the above code contained a million strings and you wanted to free that memory now rather than waiting for the garbage collector would the above code accomplish that,"['c#', '.net']" +8098,pros and cons of various java web presentation layer technologies i am currently working on a web app that makes heavy use of jsf and icefaces weve had some thiscussions of moving to another presentation layer and i thought i would take the thiscussion out into so and see what the experts think i am curious if anyone could weigh in on the pros and cons of the various java presentation layer technologies if youve only worked with one say why you love it or hate it if youve worked with several give your impressions of how they stack up against each otherour technologies under consideration are icefacesjsf without icefacesgwt google web toolkitwickettapestryand if i am missing anything from my list let me know thanks,['java'] +8101,what rails plugins are good stable and really enhance your code anyone have a list of rails plugins that are both stable and give you enough functionality to be worth the extra effort of supporting editi am mostly interested in the best most complete list of plugins so i can use it the next i am starting a rails app i do not currently need a particular plugin,"['ruby-on-rails', 'ruby']" +8104,why should i not use the gac there have been a few questions asked along this line stackoverflow such as what are the advantages and thisadvantages of using the gacand when and whennot to install into the gac and a few people have asked it on the web expamle i cannot any convincing arguments for not using the gac i am sure i am being naive but it seams like there are more benefits such as performance and version control issues to using the gac then not using it why should i not use the gac,['.net'] +8105,can i get the key of a style in codebehind wpf if i have the following codestyle defaultstyle stylefindresourcemyteststyleis there a way to get the name of the style ie reverselookup something likestring name defaultstylesomemagiclookupfunctionwhere name would evaluate to myteststyleis this possible,['.net'] +8109,should private helper methods be static if they can be static let us say i have a class designed to be instantiated i have several private helper methods inside the class that do not require access to any of the class members and operate solely on their arguments returning a resultpublic class example private something member public double compute double total 0 total computeonemember total computemoremember return total private double computeonesomething arg private double computemoresomething arg is there any particular reason to specify computeone and computemore as static methods or any particular reason not toit is certainly easiest to leave them as nonstatic even though they could certainly be static without causing any problems,['java'] +8123,how does net make use of io threads or io completion ports we have a net application that makes several concurrent calls to various web services collects their responses and then makes a few calculations off those responses in attempting to derive additional performance i have been investigating the use of approaches that make use of nets io threading via the use of io completion ports i have read through several resources including joe duffys recent book concurrent programming on windows and while i get their usefulness i am a little unclear as to their behavior within net and am looking for a concise explanation,['.net'] +8131,java class loaders can anyone point me a good resource or explain me about the concept behind class loaders i found the following resource on class loaders but still no help the following questions may look silly but trying to answer them always confuses mewhy do developers write custom class loaders why not invoke a bootstrap class loader to invoke your custom classes what is the need to define custom class loaderswhy there are so many varieties of class loaders eg bootsrap comman catalina class loader etcthanks in advance,['java'] +8154,extracting extension from filename in python is there a function to extract the extension from a filename,['python'] +8155,how to i access an attached property in code behind i have a rectangle in my xaml and want to change its canvasleft property in code behindusercontrol xclasecond90page xmlns xmlnsx width400 height300 keydowntxt keydown canvas rectangle nametheobject canvastop20 canvasleft20 width10 height10 fillgray canvasusercontrolbut this does not workprivate void txt keydownobject sender keyeventargs e theobjectcanvasleft 50does anyone know what the syntax is to do this,['c#'] +8156,how do i read any request header in php how should i read any header in phpfor example the custom header xrequestedwith,['php'] +8157,php readdir not returning files in alphabetical order i am reading through a directory with some pictures and such using a pretty simple implementation of readdir like the followingif handle opendirpath while false szfilename readdirhandle if szfilename0 if is filepathszfilename do stuff the problem that i am having is that the files are not being read in alphabetical order as the docs for readdir statereturns the filename of the next file from the directory the filenames are returned in the order in which they are stored by the filesystemanother weird thing is that on the local testing server the same code works great this is running on a server using the lamp stack in both casesi know that i can build an array and just sort it but i was wondering if i was missing something in what i was doing,['php'] +8166,multiple line code example in javadoc comment i have a small code example i want to include in the javadoc comment for a method ex looping through list of map objects code for int i 0 i listsize i map map maplistgeti systemoutprintlnmapgetwordid systemoutprintlnmapgetword code param query select statement return list of map objects the problem is the code example shows up in the javadoc with no line breaks making it hard to read ex looping through list of map objects for int i 0 i listsize i map map maplistgeti systemoutprintlnmapgetwordid systemoutprintlnmapgetword parametersquery select statement returnslist of map objectsi guess i am wrong in assuming the code tag would handle line breaks what is the best way to format code examples in javadoc comments,"['java', 'html']" +8178,how do i create a parameterized sql query why should i i have heard that everyone is using parameterized sql queries to protect against sql injection attacks without having to vailidate every piece of user inputhow do you do this do you get this automatically when using stored proceduresso my understanding this is nonparameterizedcmdtext stringformatselect foo from bar where baz 0 fuzwould this be parameterizedcmdtext stringformatexec foo from baz 0 fuzor do i need to do somethng more extensive like this in order to protect myself from sql injectionwith command parameterscount 1 parametersitem0parametername baz parametersitem0value fuzend withare there other advantages to using parameterized queries besides the security considerationsupdate this great article was linked in one of the questions references by grotok sqlhtml,['sql'] +8182,need a custom currency format to use with stringformat i am trying to use stringformat0c somevalue in c but am having a hard time figuring out how to configure the output to meet my needs here are my needs0 outputs to blank100 outputs to 10010 outputs to 1010 outputs to 1010 outputs to 10i have tried stringformat0c somevalue but for zero values it outputs 0 which is not what i want i have also tried stringformat0 somevalue but for 10 it outputs 0100 stringformat0 somevalue works for most cases but when somevalue is 10 the output is 10 is there some format that will fit all 5 cases above all of the documentation i have read only details the basics and does not touch on this type of scenario,['c#'] +8188,how can i insert an image into a richtextbox most of the examples i see say to put it on the clipboard and use paste but that does not seem to be very good because it overwrites the clipboardi did see one method that manually put the image into the rtf using a pinvoke to convert the image to a wmf is this the best way is there any more straightforward thing i can do,['c#'] +8200,getopt in vc i am quite fond of using gnu getopt when programming under linux i understand that getopt is not available under ms vcnotewin32 environmentusing visual studiono boostno mfcnot concerned with portabilityquestionhow can i then port getopt accordinglywhat guidelines should i be aware of while portingknown port with same features,['c++'] +8201,equals vs like when using sql are there any benefits of using in a where clause instead of likewithout any special operators like and are the same right,['sql'] +8205,hide a div rails hiding a div would be easy enough in javascript but is there some railsy way to do it i can think of some ways to do it by calling javascript from a partial erb of course but i would prefer not to write any javascript at all possibleedit the page is loaded and i would like to hide the div after well on an ajax call so i am in one of those render update blocks,"['html', 'ruby-on-rails']" +8206,rails inline javascript and best practices i am kinda new to using rails and an app i am working on is progressing well however i am looking though the generated html and noticed things likescript typetextjavascriptcdatadroppablesaddscriptsprinkled around the html which of course matches up with places where i use drop receiving element what i am wondering is is there a better way to do this or make it cleaner some of these script tags are coming from partials so putting them at the bottom of the page does not really help in this situationanother option may be pushing all these tag blocks into an array then writing them out in the applicationrhtml file but its still a bit messy,"['javascript', 'ruby-on-rails']" +8209,difference between div id versus div class whats the difference between div class and div id when it comes to css is it right to use div idi see different developers doing this in both ways and since i am self taught i have never really figured it out,"['css', 'html']" +8210,are there reasons to still use the import css rule i recently came across a use of the import rule on codacom they are actually using to import the main style sheet for the site specifically the formatstyle typetextcss mediascreen import urlcodacstylewhich will hide the rules from netscape 3 and ie 3 and 4 since a web development tools primary audience will be using modern browsers what other reasons would there be to use this rather then a link,['css'] +8212,does visibility affect dom manipulation performance ie7windows xpi have a third party component in my page that does a lot of dom manipulation to adjust itself each time the browser window is resizedunfortunately i have little control of what it does internally and i have optimized everything else such as callbacks and event handlers as much as i can i cannot take the component off the flow by setting thisplaynone because it fails measuring itself if i do soin general does setting visibility of the container to invisible during the resize help improve dom rendering performance,['javascript'] +8215,c wrappers for ncurses can anyone recommend a c wrapper for ncurses,['c++'] +8216,best way to change the value of an element in c i am trying to look at the best way of changing the value of an element in xmlmyxmltype myxmlelementvaluemyxmlelementmyxmltypewhat is the easiest andor best way to change value in ci have looked at xmldocument and it will cause a load of the whole xml document to memory could you do it safely with the xmlreader the problem is changing the value and emitting it back seems like an interesting conundrum cheers d,"['c#', '.net']" +8218,detecting honest web crawlers i would like to detect on the server side which requests are from bots i do not care about malicious bots at this point just the ones that are playing nice i have seen a few approaches that mostly involve matching the user agent string against keywords like bot but that seems awkward incomplete and unmaintainable so does anyone have any more solid approaches if not do you have any resources you use to keep up to date with all the friendly user agentsif youre curious i am not trying to do anything against any search engine policy we have a section of the site where a user is randomly presented with one of several slightly different versions of a page however if a web crawler is detected wed always give them the same version so that the index is consistentalso i am using java but i would imagine the approach would be similar for any serverside technology,['c#'] +8222,custom ttf fonts to use in c windowsform how do i use a custom tff font file i have with my current windowsforms application i read some where that i use it as an embedded resource but how do i set it the systemdrawingfont type,['c#'] +8245,tool or combination of tools for reproducible environments in python i used to be a java developer and we used tools like ant or maven to manage our developmenttestinguat environments in a standardized way this allowed us to handle library dependencies setting os variables compiling deploying running unit tests and all the required tasks also the scripts generated guaranteed that all the environments were almost equally configured and all the task were performed in the same way by all the members of the team i am starting to work in python now and i would like your advice in which tools should i use to accomplish the same as described for java,['python'] +8246,which config element affects exception handling with unhandledexceptionmode set to unhandledexceptionmodeautomatic i have a windows forms application that has this code in the programs start upapplicationsetunhandledexceptionmodeunhandledexceptionmodeautomaticin the msdn documentation for unhandledexceptionmodeautomatic it states thatautomatic route all exceptions to the threadexception handler unless the applications configuration file specifies otherwisedoes anyone know exactly which elementattribute in the config file it is that affects this setting,['c#'] +8255,float in database to in net if you have a float in mssqlserver to what do you map this in netcan you convert it to double or will you lose numbers,['.net'] +8264,passing arrays and matrices to functions as pointers and pointers to pointers in c given the following codevoidfoo int array voidbar int matrix intmain void int array 10 int matrix 10 10 foo array bar matrix return 0i do not understand why i get this warningwarning passing argument 1 of abara from incompatible pointer typealthough foo call seems to be okthanks,['c'] +8265,why is a font in net of size 8 thisplayed as 825 when you select for example a size of 8 in a font dialog for microsoft sans serif it returns a font that net thisplays as having a size 825 why is this exactly,['.net'] +8266,why cannot you build a website in release mode in aspnet if i set up a web application i can configure it to be in release mode but with a website i can only set the configuration to be in debug mode why is this,['asp.net'] +8269,automatic feedback on javascript error is there a way to get an automatic feedback if an error even syntax errors occurs when running a javascript on the client sidei was thinking of something like thisscript srcdebuggerjsscriptscript some script with an error in itscriptand every time the debugger notices an error it sends a feedback to the server,['javascript'] +8273,is the empty base optimization in gcc configurable consider these types struct a struct b a int i sizeofa 0 as required by the standardsizeofb should be 4 due to the empty base optimization yet on gcc 411 it is 5 i am using a pack of 1 in this area and inconsistently some of my files are getting it some are not cannot be sure what the differences are yet we have a large prjoecton the other three compilers i am using by microsoft and freescale i do not have this problem the empty base optimization is optional apparently according to this articleis there a compiler option or pragma to tune this in gcc 411 i can work around the issue but i would like to understand whats going on first i googled for a while and cannot seem to find anything,['c++'] +8287,dynamic sql execsql versus exec sp executesqlsql what are the real world pros and cons of executing a dynamic sql command in a stored procedure in sql server usingexec sqlversusexec sp executesql sql,['sql'] +8288,java ignore single click on double click can anyone think of a good way to ignore the single click that comes with a doubleclick in java i am looking to have different behaviors for each such thatsingleclick paints crosshairs on the click pointdoubleclick selects an object on the screen but should not paint crosshairs on the click point can anyone think of a way to do this some sort of timer setup maybe an ideas appreciated thisclaimer and yes i know i am committing a most heinous usability ui faux pas thisclaimeredit 2 even though this works the delay due to the timer is maddening i am abandoning this solution and using middleclick for selection instead of doubleclickeditthanks cgull this is what i was able to come up with given your confirmation that there is no easy way to do this note that if i set the timer 200 odd racing is seen between the click the timer but as long as i set this to a value 200 things work just peachy public void mouseclickedmouseevent e systemoutprintln click at egetx egety if egetclickcount 2 systemoutprintln and it is a double click wasdoubleclick true else integer timerinterval integer toolkitgetdefaulttoolkitgetdesktopproperty awtmulticlickinterval timer new timertimerintervalintvalue new actionlistener public void actionperformedactionevent evt if wasdoubleclick wasdoubleclick false reset flag else systemoutprintln and it is a simple click timersetrepeatsfalse timerstart,['java'] +8315,i get missing these required gems but gems are installed since i updated ruby using mac ports on leopard i have got several problems and i also had to reinstall gems now when i run mongrel i keep getting the error missing these required gems followed by the list of gems that i required in environmentrb but that gems seems to be correctly installed as i see running gem listi think that rails is looking for a previous installation but i do not know how to configure it to use the new rubygem paththanks,"['ruby-on-rails', 'ruby']" +8318,removing the tk icon on a tkinter window does anybody know how to make the icon not show up i am looking for a way to have no icon at all,['python'] +8321,uses for machinekey in aspnet what different ways are machine keys useful in aspneti think the following are correct but thought there may be moremultiple applications can use the same cookiemultiple servers can work with the same viewstate,"['c#', 'asp.net']" +8328,overload print python am i able to overload the print function and call the normal function what i want to do is after a specific line i want print to call my print which will call the normal print and write a copy to filealso i dont know how to overload print i dont know how to do variable length arguments i will look it up soon but just told me i cant overload print in 2x which is what i am using,['python'] +8334,speed up rails app on development env i have huge rails app on development right now which run very slow on e development i use mongrel as web server is there any way to speed up a little bit everything because i have to wait 310 sec to reload a page thanks,['ruby-on-rails'] +8335,making html content expand to fill the window i have an html page divided vertically intoheaderbodyfooterthe body in turn is divided horizontally intoa large div on the left surrounded by scrollbars thisplaying a portion of a diagrama form on the rightthe header and footer are fixedheight the body should expand vertically to fill the portion of the window not occupied by the header and footersimilarly the form is fixedwidth and the scroll pane should expand horizontally to fill the window widththe diagram is very large up to 10x10 screenfuls so i cannot thisplay all of it instead i want to thisplay as much as possible using the whole window so that the user needs to scroll as little as possiblei also cannot use javascript because some users are necessarily paranoid and must thisable itsome options i have considereda table with the scroll pane cells width and height set to 100 and all others to 1does not work the table and hence the page expands to contain the entire diagram even with absolute positioning on the scroll pane divabsolute positioning to offset the pane from the bottom of the page by the height of the footerworks but inaccurate the footers height depends on the current font size and whether text is wrapped this means i must leave a large margin to ensure they do not overlapplace the diagram in an iframethe best solution i have found with scripts thisabled but limits what i can do in scripts when they are enabledi notice that google maps uses a fixedsize area for the map when scripts are thisabled if google has given up on this problem does that mean it is not feasible,"['html', 'css']" +8343,customizing uialertview anyone have code to make thisor better yet a 3x2 grid of buttons with images using the uialertview objecti do not care about the textfield it is the buttons in a grid i want preferably with images rather than text,['iphone'] +8349,which group messaging technology to use i feel a little bit kind of confused a for about 24 hours i have been thinking which group broadcasting technology to use in my projectbasically what i need iscreate groups by some backend processbroadcast messages by any client 1n nnpotentially direct messages 11important authenticateauthorize clients with my own backend say through some kind of http apito be able to kick specific clients by backend process or server plugin here is what i will have backendrelated processes in either ruby or haxefrontend in jshaxeflash9 a in browser so ideally communicating through 80443 but not necessarilyso this technology will have to be easily accessible in haxe for flash and preferably rubyi have been thinking about rabbitmq or openamq rabbitmqstomp ejabberd ejabberdbosh juggernaut with a need to write a haxe lib for itany ideassuggestions,['ruby'] +8351,aspnet page events button click event comes after gridview bind my understanding of the order of page events is thispage loadcontrol databind for a gridview or whatevercontrol loadcontrol clicked for a buttonpage prerendercontrol prerenderthere are lots of others but these are the ones i am interested inthe important thing to notice here is that the buttons click event comes after the gridviews bind event if the button causes a change to the data the gridview thisplays the old data i could rebind the control in the prerender event but that seems totally uglythis must be a very common pattern a button that updates data how do i put this together so that the gridview binds to the data after the button click changes it,['asp.net'] +8352,android how do i set a preference in code i have an android application in which i have my preferences in a xml file which works fine i have now want to set one of the preferences using code instead of thisplaying the entire preference screen how would i go about doing this,['android'] +8353,using the context of the this keyword with jquery as a jquery neophyte i am somewhat confused by the different contexts in which the this keyword is used sometimes it refers to a dom element eg thisid and sometimes it refers to a jquery object eg thisvalremy sharps blog post is helpful but i would like to know how you would explain the difference to a novice is the difference strictly a jquery issue or common to all javascriptthanks for all the responses so far great stuff i will pick an answer tomorrow here is another blog post i subsequently came across that was also helpful what is this by mike alsup,['jquery'] +8373,updating wpf list when item changes i have a wpf listbox and i have added some foobar objects as items by codefoobars are not wpf objects just dumb class with an overwritten tostring functionnow when i change a property which influences the tostring i would like to get the listbox to updatehow can i do this quick and dirty like repaintis dependency properties the way to go on thisis it worth italways advisable to create a wpf wrapper class for my foobarsthanks,['.net'] +8375,event is not defined in mozilla firefox for javascript function function onlynumeric if eventkeycode 48 eventkeycode 57 eventreturnvalue false onkeypressonlynumnericin ie this code is working fine however in mozilla firefox the event is an undefined error,['javascript'] +8380,how to create duplicate allowed attributes i am using a custom attribute inherited from an attribute class i am using it like this mycustomattributecontrol mycustomattributealt mycustomattributeshift mycustomattributed public void setcolorbut the duplicate mycustomattribute attribute error is shownhow can i create a duplicate allowed attribute,['c#'] +8388,how to get the actual sizeonthisk of a file from powershell i am writing an administrative script and i need to calculate the size of files on thisk these files are on a compressed ntfs volumei cannot use fileinfolength because that is file size and not size on thisk for example if i have a 100mb file but it is only using 25mb due to ntfs compression i need my script to return 25mbis there a way to do this in powershell i know about the getcompressedfilesize win32 call but i was hoping that this is already wrappered at some level,['.net'] +8396,iphone use of mutexes with asynchronous url requests my iphone client has a lot of involvement with asynchronous requests a lot of the time consistently modifying static collections of dictionaries or arrays as a result it is common for me to see larger data structures which take longer to retrieve from a server with the following errors terminating app due to uncaught exception nsgenericexception reason collection nscfarray 0x37c0 was mutated while being enumeratedthis typically means that two requests to the server come back with data which are trying to modify the same collection what i am looking for is a tutorialexampleunderstanding of how to properly structure my code to avoid this detrimental error i do believe the correct answer is mutexes but i have never personally used them yetthis is the result of making asynchronous http requests with nsurlconnection and then using nsnotification center as a means of delegation once requests are complete when firing off requests that mutate the same collection sets we get these collisions,"['objective-c', 'iphone']" +8406,php standard input i know php is usually used for web development where there is no standard input but php claims to be usable as a generalpurpose scripting language if you do follow it is funky webbased conventions i know that php prints to stdout or whatever you want to call it with print and echo which is simple enough but i am wondering how a php script might get input from stdin specifically with fgetc but any input function is good or is this even possible,['php'] +8412,templates use forward declarations to reduce compile time i have to deal with a library that consists of many templated classes which are of course all implemented in header files now i am trying to find a way to reduce the unbearably long compile times that come from the fact that i pretty much have to include the whole library in each and one of my compilation unitsis using forward declarations a possibility despite the templates i am trying something along the lines of the example below where i attempted to get around the include vector as an example but it is giving me a linker error because push back is undefined include iostreamnamespace std templateclass t class vector public void push backconst t t int mainint argc char argv stdvectorint vec new stdvectorint vecpush back3 delete vec return exit success g fwddeclcppccuqbcmpotext0x140 in function main undefined reference to stdvectorintpush backint constcollect2 ld returned 1 exit statusi tried precompiled headers once but that did not change the compile times at all i did make sure they were indeed loaded instead of the real headers but if you all say that precompiled headers should be the way to go then i will give that a try againupdate some people say it is not worth to forwarddeclare the stl classes i should stress that the stl vector above was just an example i am not really trying to forwarddeclare stl classes but it is about other heavily templated classes of some library that i have to useupdate 2 is there a way to make above example actually compile and link properly logan suggests to use fnoimplicittemplates and put template class stdvectorint somewhere presumably into a separate cpp file that gets compiled with fnoimplicittemplates but i still get linker errors again i am trying to understand how it works for stdvector so that i can then apply it to the templated classes that i am actually using,['c++'] +8415,finding memory usage in java following is the scenario i need to solve i have struck with two solutionsi need to maintain a cache of data fetched from database to be shown on a swing guiwhenever my jvm memory exceeds 70 of its allocated memory i need to warn user regarding excessive usage and once jvm memory usage exceeds 80 then i have to halt all the database querying and clean up the existing cache fetched as part of the user operations and notifying the user during cleanup process i will manually handle deleting some data based up on some rules and instructs jvm for a gc whenever gc occurs if memory cleans up and reaches 60 of the allocated memory i need to restart all the database handling and giving back control to the user for checking jvm memory statistics i found following two solutions could not able to decide which is best way and whyruntimefreememory thread created to run every 10 seconds and check for the free memory and if memory exceeds the limits mentioned necessary popups will intimate user and will call the methods to halt the operations and freeing up the memorymemorypoolmxbeangetusage java 5 has introduced jmx to get the snapshot of the memory at runtime in jmx i cannot use threshold notification since it will only notify when memory reachesexceeds the given threshhold only way to use is polling in memorymxbean and check the memory statistics over a periodin case of using polling it seems for me both the implementations are going to be sameplease suggest the advantages of the methods and if there are any other alternativesany corrections to the methods using,['java'] +8418,how do i get all the values of a dictionary as an ilist i have a the following dictionaryidictionaryint ilistmyclass mydictionaryand i am wanting to get all the values in the dictionary as an ilistjust to add a bit of a background as to how i have gotten into this situationi have a method that gets me a list of myclass i then have another method that converts that list into a dictionary where they key is the id for myclass later onand without access to that original listi am needing to obtain the original ungrouped list of myclasswhen i pass mydictionaryvaluestolist to a method that takes an ilist i get a compile error that says that it cannot convert from systemcollectionsgenericlistsystemcollectionsgenericilistmyclasstosystemcollectionsgenericilistmyclassnow i can understand that its gone and added each of the groups of ilist to the new list as separate elements of the listbut in this instance its not really what i am after i just want a list of all the values in the entire dictionaryhow then can i get what i am after without looping through each of the key values in the dictionary and creating the list i want,['c#'] +8430,httpcontextcurrent accessed in static classes can i call httpcontextcurrent from within a static class and methodi want to store a value on a peruser basis but want to be able to access it in a static mannereg will this workpublic static class staticclass public static string something get return httpcontextcurrentitemssomeitemtostring,"['c#', 'asp.net']" +8434,is f a usable language for net windows development i have been hearing about f and microsoft now have a guy who is blogging and coding away in redmond somewhere about it can you really write gui code from f i would love to see an example of say adding a button to a form and subscribing to the onclick event for instancedoes f have full access to all of neti am honestly curious and i know i could google but i would love to hear from someone who is really using the language,['.net'] +8436,can i prettyprint the dbic trace output in dbixclass setting the dbic trace environment variable to truebegin envdbic trace 1 generates very helpful output especially showing the sql query that is being executed but the sql query is all on one lineis there a way to push it through some kinda sql tidy routine to format it better perhaps breaking it up over multiple lines failing that could anyone give me a nudge into where in the code i would need to hack to add such a hook and what the best tool is to accept a badly formatted sql query and push out a nicely formatted onenice formatting in this context simply means better than all on one line i am not particularly fussed about specific styles of formatting queriesthanks,['sql'] +8438,recommendations for java openpgp i want to develop a small openpgp client and i am searching for a java library for openpgpare there any open source recommendations for this approachcryptixorg does not seem alive anymore,['java'] +8439,python list serialization fastest method i need to load deserialize a precomputed list of integers from a file in a python script into a python list the list is large upto millions of items and i can choose the format i store it in as long as loading is fastestwhich is the fastest method and whyusing import on a py file that just contains the list assigned to a variableusing cpickles loadsome other method perhaps numpyalso how can one benchmark such things reliablyaddendum measuring this reliably is difficult because import is cached so it cannot be executed multiple times in a test the loading with pickle also gets faster after the first time probably because pageprecaching by the os loading 1 million numbers with cpickle takes 11 sec the first time run and 02 sec on subsequent executions of the scriptintuitively i feel cpickle should be faster but i would appreciate numbers this is quite a challenge to measure i think and yes it is important for me that this performs quicklythanks,['python'] +8447,should i always fully qualify column names in sql out of interest when working with sql statements should i always use the fully qualifed column name tablenamecolumnname even if only working with one table egselect tablecolumn1 tablecolumn2 from table,['sql'] +8449,how to get the type of t from a generic list let say i have a listt abc new listt inside a class public class myclasst later when i initialize the class the t becomes mytypeobject1 so i have a generic list list mytypeobject1 i would like to know what type of object the list of my class contain eg the list called abc contain what type of object i cannot do abc0gettype because the list might contain zero elements how can i do it,"['c#', '.net']" +8450,django having middleware communicate with viewstemplates alright this is probably a really silly question but i am new to pythondjango so i cannot really wrap my head around its scoping concepts just yet right now i am writing a middleware class to handle some stuff and i want to set global variables that my views and templates can access what is the right way of doing this i considered doing something like thismiddlewarepyfrom djangoconf import settingsclass beforefilterobject def process requestself request settingsmy var hello world return noneviewspyfrom djangoconf import settingsfrom djangohttp import httpresponsedef myviewrequest return httpresponsesettingsmy varalthough this works i am not sure if it is the django way or the python way of doing thisso my questions are1 is this the right way2 if it is the right way what is the right way of adding variables that can be used in the actual template from the middleware say i want to evaluate something and i want to set a variable headername as my site name in the middleware and i want to be able to do headername in all templates doing it the way i have it now i would have to add headername to the context inside every view is there anyway to bypass this i am thinking something along the lines of cakephps thissetheadernamemy site name3 i am using the middleware class as an equivalent of cakephps beforefilter that runs before every view or controller in cakephp is called is this the right way of doing this4 completely unrelated but it is a small question what is a nice way of printing out the contents of a variable to the browser ala print r say i want to see all the stuff inside the request that is passed into the view is pprint the answer,['python'] +8454,what versioning design pattern would you recommend i have a requirement to build versioning into an application and was wondering how best to approach it i have this general patternmodel a has many bswhere on update the attributes of a need to be versioned and its associated objects bs also need to be versioned so the application will thisplay the current version of a but it must also be possible to view previous versions of a and its associated objectsi would like to use a document store however this is only a portion of the application and having a doc store and a relation database would introduce more complexity i have considered using a star schema but before i progress i was wondering if there is a design pattern floating around tackling this problemthis question is slanted towards resolving the issue of storing the versions of an associated object in a relational database where there is an inherent need to be able to effectively query the data ie serializing object would not suffice update what i was thinkinghave implemented but want to see if the is a better way 1 model a model b pk a id b version version version where i would be duplicating model a and all the associated bs and incrementing the version attribute then doing a select to join the bs via b version and bversion just wondering if this can be done better,"['mysql', 'ruby-on-rails']" +8456,i am getting a blank page while deploying mvc application on iis i am currently deploying my application built using rc of mvc aspnet on the production server which is showing nothing now the routes in my globalascx are typical ie routesmaproute default route name controlleraspxactionid url with parameters new controller home action index id parameter defaults routesmaproute root new controller home action index id can any one figure out why it is showing me only blank pagessorry i forget to mention the it is iis 6 interestingnly it is also working on my local iis ie both local built in with vs standard with xp as well,['asp.net'] +8461,why cannot i do in c i often find myself doingfoo foo xwhy cannot i dofoo xedit i know it is not part of the language my question is why not i find the necessity to repeat foo to be unpleasing and potentially errorprone it looks just as ugly asfoo foo x,['c#'] +8463,does using namespace consume more memory does using namespace consume more memoryi am currently working on a mobile application and i was just curious if those unneeded using statements that visual studio places when creating a class make my application require some extra memory to run,['c#'] +8464,best practices for databinding in aspnet for maintainability i would like to know what are the best practices for using aspnet databinding in terms of maintainability i do not want the application to fall appart when i have to make changes to the databaseshould i databind completely in codebehind i am planning on using objectdatasources for the databinding is there something that is easier to maintain than using databinding if so what is it are there considerations i should take into account when designing my data access layer and my business layer thanks,"['.net', 'asp.net']" +8465,how do i change the color of a cocos2d menuitem menuitemfont setfontsize20menuitemfont setfontnamehelveticai am trying to change the color of start below itemmenuitem start menuitemfont itemfromstringstart game targetself selectorselectorstartgamemenuitem help menuitemfont itemfromstringhelp targetself selectorselectorhelpmenu startmenu menu menuwithitemsstart help nilstartmenu alignitemsverticallyself addstartmenu,"['iphone', 'objective-c']" +8478,xpath selectnodes in net document a b cc b a e f cc f g cc g edocumentif i load the above xml into an xmldocument and do a selectsinglenode on a using the xpath query cxmlnode onode odocumentselectsinglenodeexmlnodelist onodelist onodeselectnodescwhy does it return nodes from under b when what i would expect to happen would that it only return nodes from under emake senseedit how would i make it only return from that node onwards,['c#'] +8481,best practice for using windowonload i develop joomla websitescomponentsmodules and plugins and every so often i require the ability to use javascript that triggers an event when the page is loaded most of the time this is done using the windowonload functionmy question is is this the best way to trigger javascript events on the page loading or is there a betternewer wayif this is the only way to trigger an event on the page loading what is the best way to make sure that multiple events can be run by different scripts,['javascript'] +8487,looking for java spell checker library i am looking for an open source java spell checking library which has dictionaries for at least the following languages french german spanish and czech any suggestion,['java'] +8488,selecting empty mysql datetime fields is there a better way to select empty datetime fields than thisselect from table where datetime field 0 0,"['php', 'mysql']" +8489,is getting json data with jquery safe json allows you to retrieve data in multiple formats from an ajax call for examplegetsourceurl data callback jsoncould be used to get and parse json code from sourceurl json is the simply javascript code used to describe data this could be evaled by a javascript interpreter to get a data structure back it is generally a bad idea to evaluate code from remote sources i know the json spec does not specifically allow for function declarations but there is no reason you could not include one in code and have an unsafe and naive consumer compileexecute the codehow does jquery handle the parsing does it evaluate this code what safeguards are in place to stop someone from hacking sourceurl and thistributing malicious code,"['javascript', 'jquery']" +8496,conditional compilation in python how to do conditional compilation in python is it using def,['python'] +8509,empty html tags i have a lot of empty span tags and so on in my code due to css image replacement techniquesthey trigger a html validation warning should i carethanks,['html'] +8511,stringformat parameters how many parameters can you pass to a stringformat methodthere must be some sort of theoretical or enforced limit on it is it based on the limits of the params type or the memory usage of the app that is using it or something else entirely,['c#'] +8516,when is the javascript prefix valid syntax i know that you can use a javascript pseudo protocol for urls in an a tag however i have noticed that firefox and ie will both allow javascript to precede javascript code within a script tag is this valid syntax does it change the scoping rulesexamplesi have seen this many timesa onclickjavascriptalerthello worldhello worldabut is this legalvalid syntax and does it do anything specialscript typetextjavascriptjavascriptalerthello worldscript,['javascript'] +8520,how many mysql queries should i limit myself to on a page php mysql okay so i am sure plenty of you have built crazy database intensive pages i am building a page that i would like to pull all sorts of unrelated database information from here are some sample different queries for this one pagearticle content and infoif the author is a registered user their infoupdate the articles view counterretrieve comments on the articleretrieve information for the authors of the commentsif the reader of the article is signed in query for info on themetci know these are basically going to be pretty lightning quick and that i could combine some but i wanted to make sure that this is not abnormalhow many fairly normal and unheavy queries would you limit yourself to on a page,"['php', 'mysql']" +8525,in java how do i parse xml as a string instead of a file i have the following code documentbuilderfactorynewinstancenewdocumentbuilderparsexmlfilehow can i get it to parse xml contained within a string instead of a file,['java'] +8528,requested registry access is not allowed i am writing a tweak utility that modifies some keys under hkey classes rootall works fine under windows xp and so on but i am getting error requested registry access is not allowed under windows 7 vista and 2008 i guess toohow should i modify my code to add uac support,"['c#', '.net']" +8534,what advantages are there to developing a win32 app in c over a net app in c i learned windows programming using visual c and the win32 api nowadays it seems most apps are being developed in net using c i understand that most of the time there is not much performance difference between native code and managed code so i am wondering if i were to start writing a new desktop app today is there any reason other than the fact that i am more familiar with c that i might want to write it in nonmanaged c instead of net are there still some advantages to using c and native code or has that method been moreorless replaced with net on the windows platform of course i know that people who are writing lowlevel device drivers and similar programs wouldnt do it in net i am asking with reference to typical clientfacing apps that do not make direct hardware calls,"['c#', '.net', 'c++']" +8540,best practices for multithreaded processing of database records i have a single process that queries a table for records where process ind n does some processing and then updates the process ind to y i would like to allow for multiple instances of this process to run but do not know what the best practices are for avoiding concurrency problems where should i start,['sql'] +8543,where can i find a good nhibernate and aspnet mvc reference application where can i find a good nhibernate and aspnet mvc reference application i downloaded sarp and this seemed to be a lot more than i needed ioc and codegen via t4 i might work my way up to this later but i need something smaller at firstany simple examples i just want to pick up how nhibernate session handling works in aspnet mvc and maybe how some simple query scenarios work still trying to grasp how a select thistinct would be done in nhibernate and through to the view via the viewdata,"['.net', 'asp.net']" +8546,how can i resolve a provider load failure for wmi requests i am using wmi to collect system information it works fine on every system i have tested it on but i have one or two users that are reporting problems the debug logs show the wmi code is throwing a provider load failure exception i have not been able to replicate the issuethe users have verified that the wmi service is running in automatic modeheres the exceptionsystemmanagementmanagementexception provider load failure at systemmanagementmanagementexceptionthrowwithextendedinfomanagementstatus errorcode at systemmanagementmanagementobjectcollectionmanagementobjectenumeratormovenextany thoughts on how to troubleshoot and resolve this issue,"['c#', '.net']" +8554,reading an excel file in php i am trying to read an excel file office 2003 there is an excel file that needs to be uploaded and its contents parsedvia google i can only find answers to these related and insufficient topics generating excel files reading excel xml files reading excel csv files or incomplete abandoned projects i own office 2003 so if i need any files from there they are available it is installed on my box but is not and cannot be installed on my shared hostedit so far all answers point to phpexcelreader andor this additional article about how to use it,['php'] +8555,jquery how to add a class to every last list item got some code here that is not workingsidebar ul lilasteachfunction thisaddclasslastbasically i have 3 lists and want to add a class last to each item appearing last in each unordered listul liitem 1li liitem 2li li classlastitem 3liulhope that makes sensecheers,"['jquery', 'css']" +8556,why does threadsleep0 fix my problems and how to avoid it i am working on a client server application at certain times on certain machines when there is more than 5 clients requesting data it seems to reach a deadlock if i step in to debug the problem then the program appears to be processing simply setting a break point where i know the program is executing and causing it to hit the breakpoint a few times causes it to finish if i insert threadsleep0 at certain points in the code mostly around some cpu intensive loops it seems to pretty much totally resolve the problem the one problem that i have now is that if i call threadsleep0 too much it can slow down the code if i do not call it enough the code seems to be in deadlock although i can verify that it is not in deadlock because if i step into the code it causes the problem to thisappear simply because i am pausing a thread is there a good way to track down exactly what is causing this it seems that it only happens on my laptop which is running vista but not on my desktop which is running windows xp however it is impossible to debug because simply stepping into the code causes the problem to go away i have read comments that calling threadsleep0 is a bad practice and should not be necessary and i do not like putting witchcraft type code into my applications that i do not understand why it has to be there any pointers would be greatly appreciatedediti can also verify that the code is still running when it is deadlocked because if i leave it long enough it will finish only the amount of time it takes is many orders of magnitude higher i mean like it is actually at least 100 times slower when it is in this deadlocked mode the cpu is pegged at 8095 so it is working altough what it is doing is beyond me because it is taking forever to complete the taskmore infojust because everybody here is insistent that it is a deadlock i removed all the code that did any locking there was only a couple lines of code that did any locking whatsoever the threads work completely independantly for the most part so it was not much work to remove the locking completely still the problem persists there is no more synclocks in my code no more mutexs no more stuff that i see see that would cause a deadlock but the problem is still there and it is not deadlocked it runs albeit very slowly even though it is eating up all the processor resources,['.net'] +8557,how can i check the memory usage of objects in ipython i am using ipython to run my code i wonder if there is any module or command which would allow me to check the memory usage of an object for instancein 1 a range10in 2 memusage aout2 1mbsomething like memusage object and return the memory used by the objectduplicatefind out how much memory is being used by an object in python,['python'] +8559,is there a way to simulate a click on an alert in javascript i have a page with an iframe whose source page is in a separate domain from time to time the source page generates an alert when it does so it stops what it is doing until the user clicks ok to the alertwhat i would like to do is programmatically click ok on this alert so the source page can get back to being useful is this possible,['javascript'] +8566,difference between if and if endif are there any differences betweenif value andif valueendif,['php'] +8569,can you store a variable inside a ifclause i am kinda waiting for a no answer on this questioni was interested if you can save a variable at the same time when you checking it in an ifclause let us say i have this codeiffoonull iffoogetbarnull bar bar foogetbar systemoutprintlnsuccess bar else systemoutprintlnfailure else systemoutprintlnfailurei handling now to failure states independently even if the outcome is the same i could get them together like thisiffoonull foogetbarnull bar bar foogetbar systemoutprintlnsuccess bar else systemoutprintlnfailuremuch neater code already if foo is null it will stop there and would not try foogetbar in the if so i would not get a npe the last thing i would like to enhance and the main question do i really gave to call on foogetbar twice it would be nice to get away from the second identical call if getbar would be a very heavy operation so i am wondering if there is somehow possible to do something similiar to thisiffoonull bar bar foogetbarnull bar bar foogetbar systemoutprintlnsuccess bar else systemoutprintlnfailurei would have to break it up to two different ifs again if i would like to do bar bar foogetbarif barnull,['java'] +8575,embedding mono vs lua i am interested in hearing about peoples experience with embedding mono open source implementation of net in a cc application how is it to thistribute such an application and what are the dependencies i have tested on os x and mono comes as a huge framework hundreds of mb do users of my app all need this big framework or can it be stripped down or everything be compiled into the main executable i previously have experience with embedding lua in a c app and that works really well because i can link statically the whole lua interpreter in with my main executable so i have no external dependencies is it possible to do something similar with monoany lua people here who can comment on how they found mono compared to luaps by embedding i mean a c application which initializes a mono environment and loads a net assembly and executes it and then allows for communication between say c code in assembly and c methods in main executable,['c++'] +8576,splitting string into pair of characters in ruby i have a string eg aabbccddeeff and want to split this into an array with each element containing two characters aa bb cc dd ee ff,['ruby'] +8581,convert html to pdf in net i want to generate a pdf by passing html contents to a function i have made use of itextsharp for this but it does not perform well when it encounters tables and the layout just gets messyis there a better way,"['c#', 'html']" +8594,bigint in c what is the easiest way to handle huge numbers in c i need to store values in the area 10900 does anybody know of an easy way to do that any help would really be appreciated,['c'] +8598,deep copying an array using jquery possible duplicatewhat is the most efficient way to clone a javascript object i need to copy an ordered not associative array of objects i am using jquery i initially tried jqueryextend myarraybut naturally this gives me back an object where i need an array really love jqueryextend by the wayso whats the best way to copy an array,"['javascript', 'jquery']" +8602,difference between join and inner join both these joins will give me the same resultsselect from table join othertable on tableid othertablefkvsselect from table inner join othertable on tableid othertablefkis there any difference between the statements in performance or otherwise does it differ between different sql implementations,['sql'] +8606,how do you change the owner of a database in sql in management studio you can see the owner under properties but it would not let you change it my guess is there is some stored procedure to change it and you cannot do it through the gui,['sql'] +8617,how do i calculate the average direction of two vectors i am writing and opengl based iphone app and would like to allow a user to translate around a view based on the direction that they move two fingers on the screen for one finger i know i could just calculate the vector from the start position to the current position of the users finger and then find the unit vector of this to get just the direction but i do not know how i would do this for two fingers i do not think adding the components of the vectors and calculating the average would work so i am pretty much stuck,['iphone'] +8618,c casting types dynamically i currently have this type of codeprivate void fillobjectobject mainobject foo arg1 bar arg2 if mainobject is someclasstype1 someclasstype1 helpobject someclasstype1mainobject helpobjectproperty1 arg1 helpobjectproperty2 arg2 else if mainobject is someclasstype2 someclasstype2 helpobject someclasstype2mainobject helpobjectproperty1 arg1 helpobjectproperty2 arg2 assuming that someclasstype1 and someclasstype2 have the same set of properties that i want to assign although they may differ in other ones is it possible to dynamically cast mainobject to the appropriate type and then assign the value without duplicating the code this is what i would like to see in the endprivate void fillobjectobject mainobject foo arg1 bar arg2 type dynamictype null if mainobject is someclasstype1 dynamictype typeofsomeclasstype1 else if mainobject is someclasstype2 dynamictype typeofsomeclasstype2 dynamictype helpobject dynamictypemainobject helpobjectproperty1 arg1 helpobjectproperty2 arg2and obviously c complains about not being able to find dynamictypethe type or namespace name dynamictype could not be found are you missing a using directive or an assembly referenceis something like this possible in c 20 if it is more messy than my current code than i see no point in doing this but i am very interested to find out thanksedit just to clarify i perfectly understand that implementing an interface is the most appropriate and probably correct solution that said i am more interested in seeing how to i could do it without implementing an interface thanks for great replies,['c#'] +8620,how can i install a certificate into the local machine store programmatically using c i have a certificate generated via makecert i want to use this certificate for wcf message security using peertrust how can i programmatically install the certificate into the trusted people local machine certificate store using c or neti have a cer file but can also create a pfx,"['c#', '.net']" +8627,delegates predicate action func can someone provide a good explanation hopefully with examples of these 3 most important delegatespredicateactionfuncwhat other delegates should a c developer be aware ofhow often do you use them in production code,['c#'] +8636,aspnet absolute path of a url to make it simpler for a webapp to share files with another app on a different server i am using a base href tag in my master page as many people have thiscovered this breaks webform paths i have a working form adaptor class but am not sure how to get the absolute path of the url currently my program is hardcoded to use something akin to httpcontext context httpcontextcurrentvalue httplocalhost contextrequestrawurlit is worth noting that i am currently testing on my local iis server so there is a strange tendency for a lot of things i have tried using in order what the absolute path do not include the domain name my local iis is not visible externally which means it is not an absolute path and thus the base href will wreck itis there a good way to handle this such that it will work locally without hardcoding but will also work properly when uploaded to a server i would prefer to avoid anything that involves doing something different on the serverside copyyes i realize i could use separate webconfig files locally and on the server to get this information but this is ugly and violates dry,"['c#', 'asp.net']" +8655,pythonlike list unpacking in c in python i can do something like thislist3 4def addx y return x yaddlist 7is there any way to do this or something similar in c basically i want to be able to pass a list of arguments to an arbitrary function and have them applied as the functions parameters without manually unpacking the list and calling the function explicitly specifying the parameters,['c#'] +8665,what is better many small assemblies or one big assembly all is in the title currently we have a vs2005 solution with 20 projets likemysolutionmysolutionmodulesfoomysolutionmodulesbarinsert many heremysolutionmodulesbazcan there be a harm to merge mysolutionmodules in one project all namespaces will be preserved so no problem herebut is there anything i did not think about note currently there cannot be circular references if mysolutionmodulesfoo references mysolutionmodulesbar mysolutionmodulesbar cannot reference mysolutionmodulesfoo so well have to be careful not to create some,['.net'] +8668,why is memory still accessible after stdmapclear is called i am observing strange behaviour of stdmapclear this method is supposed to call elements destructor when called however memory is still accessible after call to clearfor examplestruct a a x 0 int xint main void stdmap int a my map a a new a ax 5 my mapinsert stdmake pair int a 0 a addresses will be the same will print 5 stdcout a my map0 my map0x stdendl my mapclear will be 0 stdcout ax stdendl return 0the question is why is variable a still accessible after its destructor was called by mapclear do i need to write delete a after calling my mapclear or is it safe to overwrite the contents of athanks in advance for your helpsneg,['c++'] +8679,how to keep track of thread progress in python without freezing the pyqt gui questionswhat is the best practice for keeping track of a treads progress without locking the gui not respondinggenerally what are the best practices forthreading as it applies to guidevelopmentquestion backgroundi have a pyqt gui for windowsit is used to process sets of htmldocumentsit takes anywhere from three secondsto three hours to process a set ofdocumentsi want to be able to processmultiple sets at the same timei do not want the gui to locki am looking at the threading moduleto achieve thisi am relatively new to threadingthe gui has one progress bari want it to thisplay the progress ofthe selected threadthisplay results of the selectedthread if it is finishedi am using python 25my idea have the threads emit a qtsignal when the progress is updated that triggers some function that updates the progress bar also signal when finished processing so results can be thisplayednote this is example code for my idea you do not have to read this to answer the questionsimport threadingfrom pyqt4 import qtcore qtguiimport reimport copyclass processingthreadthreadingthread qtcoreqobject pyqtsignals progressupdatedstr resultsreadystr def init self docs selfdocs docs selfprogress 0 int between 0 and 100 selfresults threadingthread init self def getresultsself return copydeepcopyselfresults def runself num docs lenselfdocs 1 for i doc in enumerateselfdocs processed doc selfprocessdocdoc selfresultsappendprocessed doc new progress intfloatinum docs100 emit signal only if progress has changed if selfprogress new progress selfemitqtcoresignalprogressupdatedstr selfgetname selfprogress new progress if selfprogress 100 selfemitqtcoresignalresultsreadystr selfgetname def processdocself doc this is tivial for shortness sake return refindalla a docclass guiappqtguiqmainwindow def init self selfprocessing threads thread name threadprocessing thread selfprogress object thread name intthread progress selfresults object thread name selfselected thread thread name def processdocsself docs create new thread p thread processingthreaddocs thread name example thread name p threadsetnamethread name p threadstart add thread to dict of threads selfprocessing threadsthread name p thread init progress object for this thread selfprogress objectthread name p threadprogress connect thread signals to guiapp functions qtcoreqobjectconnectp thread qtcoresignalprogressupdatedstr selfupdateprogressobjectthread name qtcoreqobjectconnectp thread qtcoresignalresultsreadystr selfupdateresultsobjectthread name def updateprogressobjectself thread name update progress object for all threads selfprogress objectthread name selfprocessing threadsthread nameprogress update progress bar for selected thread if selfselected thread thread name selfsetprogressbarselfprogress objectselfselected thread def updateresultsobjectself thread name update results object for thread with results selfresults objectthread name selfprocessing threadsthread namegetresults update results widget for selected thread try selfsetresultswidgetselfresults objectthread name except keyerror selfsetresultswidgetnoneany commentary on this approach eg drawbacks pitfalls praises etc will be appreciatedresolutioni ended up using the qthread class and associated signals and slots to communicate between threads this is primarily because my program already uses qtpyqt4 for the gui objectswidgets this solution also required fewer changes to my existing code to implementhere is a link to an applicable qt article that explains how qt handles threads and signals excerpt belowfortunately qt permits signals and slots to be connected across threadsaas long as the threads are running their own event loops this is a much cleaner method of communication compared to sending and receiving events because it avoids all the bookkeeping and intermediate qeventderived classes that become necessary in any nontrivial application communicating between threads now becomes a matter of connecting signals from one thread to the slots in another and the mutexing and threadsafety issues of exchanging data between threads are handled by qtwhy is it necessary to run an event loop within each thread to which you want to connect signals the reason has to do with the interthread communication mechanism used by qt when connecting signals from one thread to the slot of another thread when such a connection is made it is referred to as a queued connection when signals are emitted through a queued connection the slot is invoked the next time the destination objects event loop is executed if the slot had instead been invoked directly by a signal from another thread that slot would execute in the same context as the calling thread normally this is not what you want and especially not what you want if you are using a database connection as the database connection can be used only by the thread that created it the queued connection properly thispatches the signal to the thread object and invokes its slot in its own context by piggybacking on the event system this is precisely what we want for interthread communication in which some of the threads are handling database connections the qt signalslot mechanism is at root an implementation of the interthread eventpassing scheme outlined above but with a much cleaner and easiertouse interfacenote eliben also has a good answer and if i werent using pyqt4 which handles threadsafety and mutexing his solution would have been my choice,['python'] +8685,whats the best way to communicate between view controllers being new to objectivec cocoa and iphone dev in general i have a strong desire to get the most out of the language and the frameworksone of the resources i am using is stanfords cs193p class notes that they have left on the web it includes lecture notes assignments and sample code and since the course was given by apple devs i definitely consider it to be from the horses mouthclass websitelecture 08 is related to an assignment to build a uinavigationcontroller based app that has multiple uiviewcontrollers pushed onto the uinavigationcontroller stack that is how the uinavigationcontroller works that is logical however there are some stern warnings in the slide about communicating between your uiviewcontrollersi am going to quote from this serious of slidespage 1651how not to share dataglobal variables or singletons this includes your application delegatedirect dependencies make your code less reusable and more difficult to debug testok i am down with that do not blindly toss all your methods that will be used for communicating between the viewcontroller into your app delegate and reference the viewcontroller instances in the app delegate methods fair nuffa bit further on we get this slide telling us what we should dopage 1851best practices for data flowfigure out exactly what needs to be communicateddefine input parameters for your view controllerfor communicating back up the hierarchy use loose couplingdefine a generic interface for observers like delegationthis slide is then followed by what appears to be a place holder slide where the lecturer then apparently demonstrates the best practices using an example with the uiimagepickercontroller i wish the videos were available ok so i am afraid my objcfu is not so strong i am also a bit confused by the final line in the above quote i have been doing my fair share of googling about this and i found what appears to be a decent article talking about the various methods of observingnotification techniquesmethod 5 even indicates delegates as an method except objects can only set one delegate at a time so when i have multiple viewcontroller communication what am i to dook that is the set up gang i know i can easily do my communication methods in the app delegate by references the multiple viewcontroller instances in my appdelegate but i want to do this sort of thing the right wayplease help me do the right thing by answering the following questionswhen i am trying to push a new viewcontroller on the uinavigationcontroller stack who should be doing this push which classfile in my code is the correct placewhen i want to affect some piece of data value of an ivar in one of my uiviewcontrollers when i am in a different uiviewcontroller what is the right way to do thisgive that we can only have one delegate set at a time in an object what would the implementation look like for when the lecturer says define a generic interface for observers like delegation a pseudocode example would be awfully helpful here if possible,"['objective-c', 'iphone']" +8695,are java applets unable to communicate with javascript within firefox on mac os i have a java applet running in a browser that is calling some javascript functions and expecting a result from theses functions this is working with the following configurations internet explorerfirefox windowssafari macbut it is not working with firefox on mac osthe source of the problem seems to be the wineval calls that always return nulli tested this with firefox 306 on a mac os x 10411 a bit of code jsobject win jsobject jsobjectgetwindowthisobject exp winevaltestfuncsystemoutprintlnexp exptostringthis triggers a javalangnullpointerexception exptostring statementthe testfunc javascript function just returns truei tried with wincall and got the same resultmy applet tag includes the mayscript and scriptable attributesi found the answer thanks to tristan testing his solution i created a really simple test that could work and worked my way to find the culprit i was sure i did my tests with an empty testfunc that just returned true but i probably did not because in that case it does workthe real problem here was that the function called a public method of the applet liveconnect does not seem to be able to handle that case in firefox maclet me give you an example java class public class myapplet extends applet public int getmyvalue return 5 public void somefunction jsobject win jsobject jsobjectgetwindowthis object exp winevaljsfunc systemoutprintlnexp exptostring and the javascript code function jsfunc var myapplet documentgetelementbyidapplet id return myappletgetmyvalue 5exp will be null in somefunction because jsfunc calls the getmyvalue method of the applet if you remove all calls to properties of the applet youre coolto solve my problem i decided to give all the values of the applet that i neded as parameters of my javascript function and i am good nowthat may not be the case always if the javascript changes the state of the applet i was lucky,"['java', 'javascript']" +8697,recording sound as wav on iphone i am making an iphone recording app that needs to submit the sound file as a wav to an external serverstarting from the speakhere example i am able to record sound as a file but only as cafdoes anyone know how to record it as a wav instead or how to convert from caf to wav on the iphone the conversion must happen on the phoneediti am wondering if anything can be done with using kaudiofilewavetype instead of kaudiofilecaftype in audiofilecreatewithurl,['iphone'] +8698,running commands over ssh with java scenerio i would like to run commands on remote machines from a java program over ssh i am using openssh on my development machine i would also like to make the ssh connection by passing the password rather than setting up keys as i would with expectproblem when trying to do the expect like password login the process that is created with processbuilder cannot seem to see the password prompt when running regular nonssh commands eg ls i can get the streams and interact with them just fine i am combining standard error and standard out into one stream with redirecterrorstreamtrue so i am not missing it in standard errorwhen i run ssh with the v option i see all of the logging in the stream but i do not see the prompt this is my first time trying to use processbuilder for something like this i know it would be easier to use python perl or good ol expect but my boss wants to utilize what we are trying to get back remote log files and running scripts within an existing java program so i am kind of stuckthanks in advance for the help,['java'] +8705,amazon s3 url rewrite how can i change the amazon s3 url from to editbasically the whole reason for this is to hide the amazon s3 url from my usersi was thinking about a httpmodule that would redirect the request from imagemydomaincom to bucketamazons3com but that would require all requests to be handled by my servers first then forwarded,['asp.net'] +8707,how to debug javascriptjquery event bindings with firebug or similar tool i need to debug a web application that uses jquery to do some fairly complex and messy dom manipulation at one point some of the events that were bound to particular elements are not fired and simply stop workingif i had a capability to edit the application source i would drill down and add a bunch of firebug consolelog statements and commentuncomment pieces of code to try to pinpoint the problem but let us assume i cannot edit the application code and need to work entirely in firefox using firebug or similar toolsfirebug is very good at letting me navigate and manipulate the dom so far though i have not been able to figure out how to do event debugging with firebug specifically i just want to see a list of event handlers bound to a particular element at a given time using firebug javascript breakpoints to trace the changes but either firebug does not have the capability to see bound events or i am too dumb to find it any recommendations or ideas ideally i would just like to see and edit events bound to elements similarly to how i can edit dom today,"['javascript', 'jquery']" +8716,adding elements to python generators is it possible to append elements to a python generatori am currently trying to get all images from a set of thisorganized folders and write them to a new directory to get the files i am using oswalk which returns a list of image files in a single directory while i can make a generator out of this single list i do not know how to combine all these lists into one single generator any help would be much appreciatedrelatedflattening a shallow list in python,['python'] +8718,is there a vr vertical rule in html i know there is a hr horizontal rule in html but i do not believe there is a vr vertical rule am i wrong and if not why is not there a vertical rule,['html'] +8719,why is java ee scalable i heard from various sources that java ee is highly scalable but to me it seems that you could never scale a java ee application to the level of the google search engine or any other large website i would like to hear the technical reasons why it is so scalable,['java'] +8722,thisabling log4j output in java how can one quickly turn off all log4j output using a log4jproperties file,['java'] +8734,c scaling usercontrol content to match users dpifont size how do i get my ownerdrawn usercontrol to respect the users dpi 96120x andor fontsize normal large extra largesome people suggest to use the dpix and dpiy properties on a graphics object but that does not seem to to anything in my control ie they are always set to 96 regardless of which fontsize or dpi i choosethere is another similar question here on stackoverflow where it suggests to use the autoscale properties but the suggested solutions do not really do anything eitheris there no way of doing this in net except for relying on wpf,"['c#', '.net']" +8744,include header path change from windows to linux i am porting an application written in c from windows to linux i have a problem with the header files path windows uses and linux uses i am finding it cumbersome to change this in each and every source and header file is there some work around,['c++'] +8751,howto print java class garbage collection events java version 150 14javatm 2 runtime environment standard edition build 150 14b03java hotspottm server vm build 150 14b03 mixed modei am trying to debug a nullpointerexception i am getting for passing a reference to statically defined field to be more specific i am setting a global on a drools3 working memory instanceworkingmemorysetgloballog workingmemorieslogmy assumption is that the class where the field is statically defined is being garbage collected the receiving class must be using weakreference or something like that i do not really knowhow would you suggest to debug thisi think that if i could know exactly when jvms gc unloads a class instance of a class then i could narrow down on the cause of the buggy behavior if not the exact time of the event at least getting an indication that something did happenedthank youmaxim,['java'] +8757,is there an advantage to use a synchronized method instead of a synchronized block can any one tell me the advantage of synchronized method over synchronized block with an example,['java'] +8758,what does the operator mean in c what does the in this statement signifydel new somedelegate someactionis the above declaration the same as this onedel new somedelegatethissomeactionthanks,['c#'] +8761,how to design data transfer objects in business logic layer dtoi am building a web application i would like to scale to many users also i need to expose functionality to trusted third parties via web servicesi am using llblgen to generate the data access layer using sql server 2008 the goal is to build a business logic layer that shields the web app from the details of dal and of course to provide an extra level of validation beyond the dal also as far as i can tell right now the web service will essentially be a thin wrapper over the bll the dal of course has its own set of entity objects for instance customerentity productentity and so forth however i do not want the presentation layer to have access to these objects directly as they contain dal specific methods and the assembly is specific to the dal and so on so the idea is to create data transfer objects dto the idea is that these will be essentially plain old cnet objects that have all the fields of say a customerentity that are actually the database table customer but none of the other stuff except maybe some ischangedisdirty properties so there would be customerdto productdto etc i assume these would inherit from a base dto class i believe i can generate these with some template for llblgen but i am not sure about it yetso the idea is that the bll will expose its functionality by accepting and returning these dto objects i think the web service will handle converting these objects to xml for the third parties using it many may not be using net also some things will be script callable from ajax calls on the web app using jsoni am not sure the best way to design this and exactly how to go forward here are some issues1 how should this be exposed to the clients the presentation tier and to the web service codei was thinking that there would be one public class that has these methods every call would be be an atomic operationinsertdto updatedto deletedto getproducts getproductbycustomer and so forth then the clients would just call these methods and pass in the appropriate arguments typically a dtois this a good workable approach2 what to return from these methods obviously the getfetch sort of methods will return dto but what about inserts part of the signature could beinsertdtodto dtohowever when inserting what should be returned i want to be notified of errors however i use autoincrementing primary keys for some tables however a few tables have natural keys particularly manytomany onesone option i thought about was a result classclass result public exception error get set public dto affectedobject get setso on an insert the dto would get its get id like customerdtocustomerid property set and then put in this result object the client will know if there is an error if resulterror null and then it would know the id from the resultaffectedobject propertyis this a good approach one problem is that it seems like it is passing a lot of data back and forth that is redundant when it is just the id i do not think adding a int newid property would be clean because some inserts will not have a autoincrementing key like that another issue is that i do not think web services would handle this well i believe they would just return the base dto for affectedobject in the result class rather than the derived dto i suppose i could solve this by having a lot of the different kinds of result objects maybe derived from a base result and inherit the error property but that does not seem very cleanall right i hope this is not too wordy but i want to be clear,['c#'] +8766,python how to ignore an exception and proceed i have a tryexcept block in my code and when an exception is throw i really just want to continue with the code because in that case everything is still able to run just fine the problem is if you leave the except block empty or with a do nothing it gives you a syntax error i cannot use continue because its not in a loop is there a keyword i can use that tells the code to just keep going,['python'] +8776,use of synthesizeproperty in objectivec inheritance if you have class a with an instance var foo which has a propertysynthesize directive and class b inherits from class a does it also need to propertysynthesize foo the reason i ask is because when i try to use class bs foo the calling class says that foo is not something of a structured union or a member which makes me believe it needs to be explicitly synthesized,['objective-c'] +8780,why cannot gcc find the random interface when stdc99 is set i do include stdlibh at the top of the sourceexample compilationusrbincolorgcc stdc99 fgnu89inline g wall iusrinclude i i i i i o3 o f8 f8cin file included from f8c7ctypecmpc in function arandomizedactypecmpc48 warning implicit declaration of function arandomactypecmpc in function amainactypecmpc153 warning implicit declaration of function asrandomaaisxcaliburt when i turn off stdc99 the function isfinite can not be found so i do want to use stdc99 for this and other reasons is there some trick i am missing,['c'] +8782,url encoding using c i have an application which i have developed for a friend it sends a post request to the vb forum software and logs someone in with out setting cookies or anythingonce the user is logged in i create a variable that creates a path on their local machinectempfolderdateusernamethe problem is that some usernames are throwing illegal chars exception for example if my username was masfenix it would throw an exceptionpathcombine environmentgetfolderpathsystemenvironmentspecialfoldercommonapplicationdata datetimenowtostringddmmyyhhmm form1usernamei do not want to remove it from the string but a folder with their username is created through ftp on a server and this leads to my second question if i am creating a folder on the server can i leave the illegal chars in i only ask this because the server is linux based and i am not sure if linux accepts it or notedit it seems that url encode is not what i want heres what i want to doold username masfenixnew username masxxfenixwhere xx is the ascii value or any other value that would easily identify the character,"['c#', '.net']" +8787,java regex reduce spaces in a string i do not have time to get my head around regex and i need a quick answer platform is javai need the string some text with spacesto be converted tosome text with spacesie 2 or more consecutive spaces to be changed to 1 space,['java'] +8795,which c compiler do you recommend for windows which c compiler do you recommend for windows not c c ansirelatedc compiler for windowscc compiler for windows,['c'] +8796,is a ruby module equivalent to a java interface as i understand it an interface is java is intended to enforce a design by laying out methods for classes implementing the interface to fill in is this the idea with a ruby module also i see that just like with interfaces in java you cannot instantiate a module in ruby,"['java', 'ruby']" +8802,asynchronous webrequest best practices what is the best practice for getting a webrequest asynchronouslyi want to download a page from the internet does not matter whatand avoid blocking a thread as much as possiblepreviously i believed that it was enough to just use the begingetresponse and endgetresponse pair but on closer inspection i also see that there is the option of using begingetrequeststream update getrequeststream is used for post operationsand then to add to the confusion should i be using streambeginread and endreadupdate this article suggests it is even better to process the httpresponsegetresponsestream asynchronously using streambeginreadwhat a messcan someone point me in the right directionwhat is the best practice,['.net'] +8803,lock android app after a certain amount of idle time my android application requires a password to be entered in the first activity i want to be able to automatically send the application back to the password entry screen after the application has been idle for a fixed amount of timethe application has multiple activities but i would like the timeout to be global for all activities so it wouldnt be sufficient to create a timer thread in the onpause method of an activityi am not sure what the best definition for the application being idle is but no activities being active would be sufficient,['android'] +8808,get timezone from datetime does the net datetime contain information about time zone where it was created i have a library parsing datetime from a format that has zz at the end and while it parses correctly and adjusts a local time i need to get what the specific time zone was from the datetime object is this possible at all all i can see is datetimekind which specifies if time is local or utc,"['c#', '.net']" +8812,alternatives for jcifs ntlm library are there any alternatives for jcifs ntlm library,['java'] +8816,should i ignore the occasional invalid viewstate error every now and then once every day or so were seeing the following types of errors in our logs for an aspnet 35 applicationinvalid viewstateinvalid postback or callback argumentare these something that just happens from timetotime with an aspnet application would anyone recommend we spend a lot of time trying to diagnose whats causing the issues,['asp.net'] +8822,creating new exception in c i have a c class and i am trying to run it in ubuntuifndef wrongparameterexception h define wrongparameterexception h include iostreaminclude exceptioninclude stringusing namespace stdpragma onceclass wrongparameterexception public exception public wrongparameterexceptionchar message exceptionmessage virtual wrongparameterexception throw endifwhen i try to compile it the compiler gives me this errorwrongparameterexceptionh in constructor awrongparameterexceptionwrongparameterexceptioncharawrongparameterexceptionh14 error no matching function for call to astdexceptionexceptioncharausrincludec43exception59 note candidates are stdexceptionexceptionusrincludec43exception57 note stdexceptionexceptionconst stdexceptioncan anyone tell me what am i doing wrong i tried changing the message variable to string or const string or const string but it did not helphere is how i use the new exception that i created from maintry if strtoint1 1 parameters1 null strtoint3 1 parameters3 null throw wrongparameterexceptionerror in the config or commands file catchwrongparameterexception e logaddmsgewhat,['c++'] +8825,map file analysis wheres my code size comes from i am looking for a tool to simplify analysing a linker map file for a large c project vc6 during maintenance the binaries grow steadily and i want to figure out where it comes from i suspect some overzealeous template expansion in a library shared between different dlls but jsut browsign the map file does not give good cluesany suggestions,['c++'] +8828,pairwise iteration in c or sliding window enumerator if i have an ienumerable likestring items new string a b c d i would like to loop thru all the pairs of consecutive items sliding window of size 2 which would be ab b c c dmy solution was is this public static ienumerablepairt t pairsienumerablet enumerable ienumeratort e enumerablegetenumerator emovenext t current ecurrent while emovenext t next ecurrent yield return new pairt tcurrent next current next used like this foreach pairstringstring pair in itertoolsstringpairsitems systemoutprintline0 1 pairfirst pairsecond when i wrote this code i wondered if there are already functions in the net framework that do the same thing and do it not just for pairs but for any size tuples imho there should be a nice way to do this kind of sliding window operationsi use c 20 and i can imagine that with c 30 w linq there are more and nicer ways to do this but i am primarily interested in c 20 solutions though i will also appreciate c 30 solutions,"['c#', '.net']" +8830,running xcodebuild from a forked terminal i am trying to setup an automated build server for an iphone application i would like to be able to have nightly adhoc beta builds so that testers can follow the developmenti have setted up xcode successfully xcode to perform adhoc builds and i can also launch the build from the command linexcodebuild configuration adhoc sdk iphoneos22 clean buildthe problem i am having is that the following line does not work from a forked terminal using nohup or screen and failed with the followingcodesign error code signing identity iphone thistribution x does not match any codesigning certificate in your keychain once added to the keychain touch a file or clean the project to continuei have checked my environment variables in my shell and in nohup or screen and did not found a cluei guess my problem is that the forked terminal cannot access to the keychain but i have no clue on how to allow itthanks for your help,['iphone'] +8832,how can i make this python recursive function return a flat list look at this simple functiondef prime factorsn for i in range2n if and i 0 return i prime factorsn i return nheres the result of prime factors1202 2 2 3 5instead of nested tuples i want it to return one flat tuple or list2 2 2 3 5is there a simple way to do that,['python'] +8836,can file uploads time out in php hi im quite new to php i have created a form for very large csv files to be uploaded to my server some one mentioned to me that the browser can time out due to the uploading file being to big is this true and if so can it be preventedthanks for your help,['php'] +8846,how trustworthy is javascripts random implementation in various browsers i would like to do some experimenting with javascript and encryption and i got curious as to how unpredictable the implementation of the random function is has anyone done any hard testsclearly browsers have the ability to generate strong randomness for ssl the questions is do they give javascript access to the same strength,['javascript'] +8851,what is the best way to expose a wcf service so that it can be easily consumed from javacxf weve written a wcf service to be used by a java shop who is using cxf to generate the adapters were not that familiar with java but have exposed the service using basichttpbinding ssl and basic authentication integration tests show that a net client can consume the service just fine however the java shop is having trouble consuming the service specifically they getthe following jaxb error two declarations cause a collision in the objectfactory class this is usually caused if 2 operations have the same name and namespace when cxf attempts to create adapter classes we cannot find any type or operation names that should cause any sort of collision we have made sure that all custom types specify a namespace and tempuriorg is not specified anywhere in the wsdl the java shop suspects the error is because the generated wsdl contains xsdimport elements so my questions is there any better way than cxf for the java shop consume the wcf service project tango looks interesting but i do not know enough to tell them to consider using it is cxf a defacto standard in javabasichttpbindingsslbasic auth are ms recommended for interop scenarios but the client still seems to have interop problems should we consider other bindings or settings to make this easier to consumeis there a way to configure wcf to always output a single wdsl with no schema imports,['java'] +8856,formatting long numbers as strings in python what is an easy way in python to format integers into strings representing thousands with k and millions with m and leaving just couple digits after commai would like to show 7436313 as 744m and 2345 as 234kis there some string formatting operator available for that or that could be done only by actually dividing by 10 in a loop and constructing result string step by step,['python'] +8861,how to put the content of a bytebuffer into an outputstream i need to put the contents of a javaniobytebuffer into an javaiooutputstream wish i had a channel instead but i do not whats the best way to do thisi cannot use the bytebuffers array method since it can be a readonly bufferi also may be interspersing writes to the outputstream between using this bytebuffer and having a regular array of byte which i can with use outputstreamwrite directly,['java'] +8867,python orm that autogeneratesupdates tables and uses sqlite i am doing some prototyping for a new desktop app i am writing in python and i want to use sqlite and an orm to store datamy question is are there any orm libraries that support autogeneratingupdating the database schema and work with sqlite,['python'] +8876,convert collection to list i am using treebidimap from the apache collections library i want to sort this on the values which are doublesmy method is to retrieve a collection of the values usingcollection coll themapvalueswhich naturally works finemain question i now want to know how i can convertcast not sure which is correct coll into a list so it can be sorted i then intend to iterate over the sorted list object which should be in order and get the appropriate keys from the treebidimap themap using themapgetkeyiteratornext where the iterator will be over the list of doubles,['java'] +8877,avoiding dynamic castrtti i was recently working on a piece of c code for a side project the cppmarkdown library for the curious and ran into a coding question that i would like some opinions oncppmarkdown has a base class called token which has a number of subclasses two of the main subclasses are container which holds collections of other tokens and textholder used as a base class for tokens that contain text of coursemost of the processing is handled via virtual functions but some of it was better handled in a single function for that i ended up using dynamic cast to downcast the pointer from a token to one of its subclasses so i could call functions that are specific to the subclass and its child classes there is no chance the casting would fail because the code is able to tell when such a thing is needed via virtual functions such as isunmatchedopenmarkerthere are two other ways i could see to handle thiscreate all of the functions that i want to call as virtual functions of token and just leave them with an empty body for every subclass except the ones that need to handle them orcreate a virtual function in token that would return the properlytyped pointer to this when it is called on certain subtypes and a null pointer if called on anything else basically an extension of the virtual function system i am already using therethe second method seems better than both the existing one and the first one to me but i would like to know other experienced c developers views on it or whether i am worrying too much about trivialities,['c++'] +8882,will html be replaced by any new technology i see various frameworks being launched that promise rich ui and better user experience as they call it silverlight flash yahoos new framework etc etcdoes this mean that over a period of time these frameworks will replace the existing html javascript css based web applicationswouldnt it be same as opening an application inside a browser window,"['javascript', 'html', 'css']" +8885,adding classpath in linux export classpathsomejarjarmysqlconnectorjava516binjarjava xmx500m foldersubfolderdit1somexmlcd is the above statement for setting the classpath to already existing classpath in linux is correct or not,['java'] +8886,new to unit testing i would like to know how to implement unit testing in an existing quite large application using visual studio 2008 net 20i understand that developing unit tests for the existinglegacy code is not realistic but i would like to have tests for code moving forwardi have found plenty of examples on how to write tests for code but nothing on how to set it up from scratch on an existing project and how to integrate it into the development cycle,"['.net', 'asp.net']" +8887,can we run a cwpf application on mac os x i sell a cwpf application targeting net 30 at the moment and people keep asking me for a mac versionthe application is a time tracking application with a good gui there is not that much business logic in a time tracking application so most of the application is gui rewriting just the gui is equivalent to rewriting the entire applicationi do not have the resources to rewrite the application or maintain two different code bases so i need a way to run the same code on a mac i know i will have to debug and modify the code what i mean is i can support only one code base i cannot split the project into different mac and windows projects i just do not have the time to work on two projects porting the application to a crossplatform ui library to a different programing language or to silverlight are all not relevant it will take too much time and i think i will get more sales by investing this time in new featuresdoes anyone know of a tool that can run or port cwpf to the mac,['c#'] +8889,sharepoint development environment setup i need to setup a development environment for writing share point web parts what do i exactly needmy development machine is a windows xp prof with visual studio 2008 prof if found windows share point services 30 software development kit sdk and windows share point services 30 tools visual studio 2008 extensions version 12 but i cannot install it ob windows xp because share point services 30 are required to be installed locally i can not imagine that it is really necessary to install visual studio at a server operating systemis there any other way to setup a clean development environment under windows xp and using a dedicated windows server for running share point services,['.net'] +8898,select count of subquery without running it twice i have got a procedure to return a result set which is limited by page number and some other stuff as an output parameter i need to return a total amount of selected rows according to the parameters except the page number so i have something like thatwith selecteditems asselect id row1 row2 row number over order by row1 as positionfrom itemswhere row2 row2select id row1 row2from selecteditemswhere position between from and toand then i need to set the output parameter to the number of rows in the innerquery i can just copy the query and count it but this query could returns thousands of rows and will be more in the future so i am looking for method to do that with a good performance i was thinking about table variables is it a good idea or any other suggestionsto be more specific it is the microsoft sql server 2008thank you jan,['sql'] +8899,static context in enum definition the syntax sugar provided by javas enum facility can sometimes be a little confusing consider this example which does not compilepublic enum testenum foofoo public void foo helper compiler error string name testenumstring name thisname name public abstract void foo private void helper do stuff using thisname so must not be static can anyone explain why the compiler says nonstatic method helper cannot be referenced from a static contexthow exactly is this context staticyou can make this compile by changing the call to thishelper here is one confusing point if we really are in a static context like the compiler suggests how can this work or by increasing the visibility of helper to default level which would you prefer also feel free to suggest a better question title edit i found some thiscussion about this but no real answers my colleague thinks the fact that that thishelper works is actually a compiler bug and indeed with newer java versions it seems not to work although superhelper does cannot find symbol helper although there is something odd going on after trying with different java versions i cannot get thishelper to compile again with any of them,['java'] +8900,the use of undefined variables in ifstatements this snippet results in a javascript runtime error foo is not definedif foo i have to define foo first like sovar foo foo null or undefined 0 etc and only then can i doif foo why is thatupdatethis was somewhat of a brainfart on my side of things fcourse you cannot access a variable which is not allocatedfun stuff that you can do a typeof on an undefined variable thou i am gonna accept miccets answer since i think it is the most elegant solution,['javascript'] +8902,how can i create a temp file with a specific extension with net i need to generate a unique temporary file with a csv extensionwhat i do right now is string filename systemiopathgettempfilenamereplacetmp csvhowever this does not guarantee that my csv file will be uniquei know the chances i ever got a collision are very low especially if you consider that i do not delete the tmp files but this code does not looks good to meof course i could manually generate random file names until i eventually find a unique one which should not be a problem but i am curious to know if others have found a nice way to deal with this problem,"['c#', '.net']" +8913,can i change a nested master pages master dynamically okay so we all know about changing a master page dynamically in a pages onpreinit eventbut what about a nested master page can i change a masters masterthere is no onpreinit event exposed in the masterpage classany ideas,['asp.net'] +8921,castle windsor suppress exceptions thrown by resolve when resolving a component which the windsor container cannot find an exception is thrownstructuremap has a trygetinstance method which returns null of it cannot find the requested componentdoes castle windsor has something like this or am i forced to catch these exceptions i do not like that because of the performance overhead of throwing and catching exceptionsthanks in advanceremco,['.net'] +8923,c beginendreceive how do i read large data when reading data in chunks of say 1024 how do i continue to read from a socket that receives a message bigger than 1024 bytes until there is no data left should i just use beginreceive to read a packets length prefix only and then once that is retrieved use receive in the async thread to read the rest of the packet or is there another wayediti thought jon skeets link had the solution but there is a bit of a speedbump with that code the code i used ispublic class stateobject public socket worksocket null public const int buffer size 1024 public byte buffer new bytebuffer size public stringbuilder sb new stringbuilderpublic static void read callbackiasyncresult ar stateobject so stateobject arasyncstate socket s soworksocket int read sendreceivear if read 0 sosbappendencodingasciigetstringsobuffer 0 read if read stateobjectbuffer size sbeginreceivesobuffer 0 stateobjectbuffer size 0 new aynccallbackasync send receiveread callback so return if sosblength 0 all of the data has been read so thisplays it to the console string strcontent strcontent sosbtostring consolewritelinestringformatread 0 byte from socket data 1 strcontentlength strcontent sclosenow this corrected works fine most of the time but it fails when the packets size is a multiple of the buffer the reason for this is if the buffer gets filled on a read it is assumed there is more data but the same problem happens as before a 2 byte buffer for exmaple gets filled twice on a 4 byte packet and assumes there is more data it then blocks because there is nothing left to read the problem is that the receive function does not know when the end of the packet isthis got me thinking to two possible solutions i could either have an endofpacket delimiter or i could read the packet header to find the length and then receive exactly that amount as i originally suggestedthere is problems with each of these though i do not like the idea of using a delimiter as a user could somehow work that into a packet in an input string from the app and screw it up it also just seems kinda sloppy to methe length header sounds ok but i am planning on using protocol buffers i do not know the format of the data is there a length header how many bytes is it would this be something i implement myself etcwhat should i do,['c#'] +8946,need loop to copy chunks from byte array i have to process a large byte array that is passed to my function i need to copy the content from this incoming byte array in smaller chunks to an outbound byte arrayfor every chunk of data created in the outbound array i need to call a web serviceupon return i need to resume looping through the incoming byte array continuing to pass a whole or partial chunk of data until the complete incoming array is processed ie sent to the web service in chunksi am very new to c and i am struggling with a loop that works i know how to call the web service to handle a chunk but i cannot get the looping correct here is a sketch of the pathetic mess i currently haveint chunksize 10byte outboundbuffer new bytechunksize while bytesread 0long i 0foreach byte x in incomingarray bytesread 1 outboundbufferi incomingarrayi iuploadobjectsize bytesreaduploadobjectmtompayload outboundbuffer call web service here and pass the uploadobject get next chunk until incomingarray is fully processed i know this is a mess and would not work could someone sketch a proper loop to get this done thanks very much,['c#'] +8947,continuing a statement on the next line with a comment if i have a statement in ruby that i want to continue on the next line normally i would add a backslash at the end of the line like thisprint x ybut if i have comments on the line it does not workprint x show x y show yis there a way around thisedit squeegys solution is correct and actually i knew you could do that but i was wondering particularly whether there is a way to have a comment on the same line as the backslash,"['ruby-on-rails', 'ruby']" +8957,code contracts will you use them microsoft just released code contracts a tool that integrates with visual studio and allows you to define contracts for your net code and get runtime and compile time checkingwatch the video on channel 9 that shows how it being usedfor now it is an addon but it will be part of the base class library in net 40is this something you see yourself usingi wonder if this means the death of specupdatewhat i mean by the death of spec is that we now have 2 different projects for writing contractsspec is an evolution of c and it introduces new keywords and behaviours on the other hand what microsoft just released is a library that can be used with any net languagesince the latter looks like it is going to become the defacto standard i wonder where that leaves spec,['.net'] +8962,how do you perform a left outer join using linq extension methods assuming i have a left outer join as suchfrom f in foojoin b in bar on ffoo id equals bfoo id into gfrom result in gdefaultifemptyselect new foo f bar result how would i express the same task using extension methods egfoogroupjoinbar f ffoo id b bfoo id fb select,['c#'] +8965,why ano database selecteda sqlexception why this program is not executing when it goes in to the do while loop second time and why it is giving the exception exception javasqlsqlexception mysqlodbc 51 drivermysqld5051acommunityntno database selectedimport javaioinputstreamimport javasqlconnectionimport javasqldrivermanagerimport javasqlresultsetimport javasqlsqlexceptionimport javasqlstatementimport javautilscannerimport javautilvectorpublic class database public void loaddriver load the jdbcodbc bridge driver try classfornamesunjdbcodbcjdbcodbcdriver catch classnotfoundexception ee eeprintstacktrace 2open a data source name by means of the jdbcodbcdriver static void connect throws sqlexception connect to the database connection con drivermanagergetconnectionjdbcodbcmysql root admin statement stmt concreatestatement shut off autocommit consetautocommitfalse systemoutprintln1insert 2delete 3update 4select scanner s new scannersystemin int x x snextint string query sql select string resultset rs sql query results boolean more more rows found switch string v1 v2 temporary storage results vectorobject results new vectorobject10 if x 1 try stmtexecuteupdateinsert into employee emp idemp name values 122shiva catchexception esystemoutprintlnexception eeprintstacktrace if x 2 try stmtexecuteupdatedelete from employee where emp id102 catchexception esystemoutprintlnexception eeprintstacktrace if x 3 try stmt executeupdateupdate employee set emp name madavan where emp id20 catchexception esystemoutprintlnexception eeprintstacktrace query select from employee try rs stmtexecutequeryquery check to see if any rows were read more rsnext if more systemoutprintlnno rows found return loop through the rows retrieved from the query while more v1 id rsgetintemp id v2 name rsgetstringemp name systemoutprintlnv1 systemoutprintlnv2 systemoutprintln resultsaddelementv1 n v2 n more rsnext rsclose catch sqlexception e systemoutprintln resultssize results where found finallystmtclose public static void mainstring args throws sqlexception string str y do database s new database sloaddriver databaseconnect scanner sc new scannersystemin systemoutprintlndo you want to proceed to query str scnext while str n,['java'] +8966,whats better at freeing memory with php unset or var null i realise the second one avoids the overhead of a function call update is actually a language construct but it would be interesting to know if one is better than the other i have been using unset for most of my coding but i have recently looked through a few respectable classes found off the net that use var null insteadis there a preferred one and what is the reasoning,['php'] +8983,iphone development related podcasts anyone have any suggestions for good iphone development related podcastsonly one i have run across is and was looking for some others,['iphone'] +8988,stringjoin vs stringbuilder which is faster in a previous question about formatting a double to csv format marc gravell said that using stringbuilder would be faster than stringjoin is this true,['.net'] +8997,how can i reverse a nsarray in objectivec i need to reverse my nsarrayas an example12345 must become 54321what is the best way to achieve this,['objective-c'] +8999,table layout using stdcout how do i format my output in c streams to print fixed width leftaligned tables something like printf143f143fn 1234512345 1234512345poducing12345123 12345123,['c++'] +9005,eliminating temporary aspnet files how do you prevent aspnet from creating too many temporary files my website creates gigabytes of temporary files and that overflows the main partition on the server how do i prevent this from happening,['asp.net'] +9006,java keeps lock on files for no apparent reason despite closing streams in finally clauses i seem to constantly run into cleaning up problems when using java filedelete fails to delete files windows explorer fails too running systemgc helps sometimes but nothing short of terminating the vm helps consistently and that is not an optiondoes anyone have any other ideas i could try i use java 16 on windows xpupdate flac code sample removed the code worked if i isolated itupdate more info this happens in apache tomcat commons fileupload is used to upload the file and could be the culprit also i use runtimeexec to execute lame in a separate process to encode the file but that seems unlikely to cause this since processexplorer clearly indicates that javaexe has a rw lock on the file and lame terminates fineupdate i am working with the assumption that there is a missing close or a close that does not get called somewhere in my code or external library i just cannot find it,['java'] +9013,c constructor syntax simple question are the following statements equivalent or is the second one doing more implicit things behind the scenes if so whatmyclass x3myclass x myclass3thanks,['c++'] +9015,good aspnet excellike grid control we are looking for an aspnet compatible data grid that allows for multiline editing similar to excel or a winforms data grid it must also support very basic keyboard input tab arrow keys return note that we are not looking for excel capabilities functions formatting formulas just a grid for fast data entryi have looked at telerik infragistics componentone devexpress and many others all their support teams have said that the controls either do not support multiline or do so in such a clunky way that it would be unusable has anyone used any excellike grids that they can recommend the clientside grids seemed closer to what we needed with sigma widgets example being the closest i have found so far extjss grid was too inflexible and the jquery grid was too buggy,"['asp.net', 'javascript']" +9026,how to thistinguish between multiple input devices in c i have a barcode scanner which acts like a keyboard and of course i have a keyboard too hooked up to a computer the software is accepting input from both the scanner and the keyboard i need to accept only the scanners input the code is written in c is there a way to thisable input from the keyboard and only accept input from the scannernotekeyboard is part of a laptopso it cannot be unplugged also i tried putting the following code protected override boolean processdialogkeysystemwindowsformskeys keydata return true but then along with ignoring the keystrokes from the keyboard the barcode scanner input is also ignoredi cannot have the scanner send sentinal characters as the scanner is being used by other applications and adding a sentinal character stream would mean modifying other codealso i cannot use the timing method of determining if the input came from a barcode scanner if its a bunch of characters followed by a pause since the barcodes scanned could potentially be single character barcodesyes i am reading data from a streami am trying to follow along with the article thistinguishing barcode scanners from the keyboard in winforms however i have the following questionsi get an error nativemethods is inaccessible due to its protection level it seems as though i need to import a dll is this correct if so how do i do it which protected override void wndprocref message m definition should i use there are two implementations in the articleam getting an error related to securitypermission securityactionlinkdemand flags securitypermissionflagunmanagedcode error cs0246 the type or namespace name securitypermission could not be found are you missing a using directive or an assembly reference how do i resolve this errorthere is also an error on the line containing if from hardwareid in hardwareids where devicenamecontainshardwareid select hardwareidcount 0 error is error cs1026 expectedshould i be placing all the code in the article in one cs file called barcodescannerlistenercsfollowup questions about c solution source code posted by nicholas piasecki on i was not able to open the solution in vs 2005 so i downloaded visual c 2008 express edition and the code ran however after hooking up my barcode scanner and scanning a barcode the program did not recognize the scan i put a break point in onbarcodescanned method but it never got hit i did change the appconfig with the id of my barcode scanner obtained using device manager there seems to be 2 devicenames with hidvid 0536pid 01c1 which is obtained from device manager when the scanner is hooked up i do not know if this is causing the scanning not to work when iterating over the devicenames here is the list of devices i found using the debuggerhidvid 0536pid 01c1mi 01925ca53704d1e55b2f16f11cf88cb001030hidvid 0536pid 01c1mi 00938e10b90884b96c356ef11d1bc8c00a0c91405ddhidvid 413cpid 2101mi 0081966e83d0884b96c356ef11d1bc8c00a0c91405ddhidvid 413cpid 30127960fae0378de44c56ef11d1bc8c00a0c91405ddrootrdp kbd0884b96c356ef11d1bc8c00a0c91405ddacpipnp030342f94427b0884b96c356ef11d1bc8c00a0c91405ddrootrdp mou0378de44c56ef11d1bc8c00a0c91405ddacpipnp0f1342f94427b0378de44c56ef11d1bc8c00a0c91405ddso there are 2 entries for hidvid 0536pid 01c1 could that be causing the scanning not to workok so it seems that i had to figure out a way to not depend on the ascii 0x04 character being sent by the scannersince my scanner does not send that character after that the barcode scanned event is fired and the popup with the barcode is shown so thanks nicholas for your help,['c#'] +9030,link to open jquery accordion i am trying to open an accordion div from an external link i see the navigation true option but i am not sure how to implement it do you give each div an id and call the link like this i am new to jquery so bear with me here is the code i am using if it helpsscript typetextjavascript function accordionaccordion header h2 autoheight false animated false navigation true scriptdiv idaccordiondiv h2a hrefservicesah2 div claservices pmore information about all of these servicesp divdiv,['jquery'] +9031,windowonload vs documentonload which is more widely supported windowonload or documentonload,['javascript'] +9034,this backgroundworker is currently busy and cannot run multiple tasks concurrently i get this error if i click a button that starts the backgroundworker twicethis backgroundworker is currently busy and cannot run multiple tasks concurrentlyhow can i avoid this,['c#'] +9039,what is the best way to escape nonformat characters in oracles to char i am trying to print a date in a select statement but i need to add a letter to the outputto chardate updated ymmddthhmmssoracle does not like the t i just want the t to be output like the colons and the dashes can i escape it with a backslash or something,['sql'] +9043,what is wpf and how does it compare to winforms i have been looking at wpf but i have never really worked in it except for 15 minutes which prompted this question i looked at this post but its really about the flash of a wpf so what is the difference between a windows forms application and a wpf application,['c#'] +9051,how do you detect the main hard drive letter such as c drive how do you detect the main hard drive letter such as c drive,['c#'] +9054,jquery and appending large amounts of html i have come to find that using jquery to create html clientside can be a huge performance booster if done properly i use ajax returning json to retrieve dynamic content and then i build the relevant html and insert it using jquery the first time i messed with this technique i found that the string concatenator in ies javascript performed really slowly so that building a dynamic table with more than 50 or so rows performed terribly var shtml tableforvar i0i100i shtml trtda bunch of contenttdtrshtml tablemytableappendshtmlthen i found a technique for string concatenation that changed everything instead of using the sting operator use arrays to do concatenationvar shtml tableforvar i0i100i shtmlpushtrtda bunch of contenttdtrshtmlpushtablemytableappendshtmljoini found that performance improved significantly now however there is a ceiling of about 100 rows before i start to see the browser itself struggle with dynamically inserting so much content at once does anyone have any pointers or techniques that can be used to help me achieve the next performance boost for large sets of dynamic html,"['javascript', 'jquery']" +9057,how to alloc a dynamic typed object i have seen a lot of talk about dynamic typing in objectivec but i have not seen any examples of what i think it is supposed to belets say i have a generic function that is supposed to juggle two objects one gets allocated and the other gets freed and the calling object attaches it self to the newly alloced object both are inherited from class0please feel free to interpret this however you want if you think it will explain somethingif the class is picked at runtime how do i deal with the arguments list is a placeholder for nowhow do i alloc a object whos class is not defined until runtimevoid juggleobjclass1objclass2 temp alloc initobjclass1 temptemp releaseobjclass2view removefromsuperviewselfhandle insertsubviewobjclass1view,['objective-c'] +9059,passing data from a jquery ajax request to a wcf service fails deserialization i use the following code to call a wcf service if i call a test method that takes no parameters but returns a string it works fine if i add a parameter to my method i get a wierd errorexceptiondetailhelplinknullinnerexceptionnullmessagethe token was expected but found stacktrace at systemxmlxmlexceptionhelperthrowxmlexceptionxmldictionaryreader reader string res string arg1 string arg2 string arg3u0du0a at systemxmlxmlexceptionhelperthrowtokenexpectedxmldictionaryreader reader string expected char foundu0du0a at systemruntimeserializationjsonxmljsonreaderparsestartelementu0du0a at systemruntimeserializationjsonxmljsonreaderreadu0du0a at systemservicemodelthispatcherdatacontractjsonserializeroperationformatterdeserializebodycorexmldictionaryreader reader object parameters boolean isrequestu0du0a at systemservicemodelthispatcherdatacontractjsonserializeroperationformatterdeserializebodyxmldictionaryreader reader messageversion version string action messagedescription messagedescription object parameters boolean isrequestu0du0a at systemservicemodelthispatcheroperationformatterdeserializebodycontentsmessage message object parameters boolean isrequestu0du0a at systemservicemodelthispatcheroperationformatterdeserializerequestmessage message object parametersu0du0a at systemservicemodelthispatcherdemultiplexingthispatchmessageformatterdeserializerequestmessage message object parametersu0du0a at systemservicemodelthispatcheruritemplatethispatchformatterdeserializerequestmessage message object parametersu0du0a at systemservicemodelthispatchercompositethispatchformatterdeserializerequestmessage message object parametersu0du0a at systemservicemodelthispatcherthispatchoperationruntimedeserializeinputsmessagerpc rpcu0du0a at systemservicemodelthispatcherthispatchoperationruntimeinvokebeginmessagerpc rpcu0du0a at systemservicemodelthispatcherimmutablethispatchruntimeprocessmessage5messagerpc rpcu0du0a at systemservicemodelthispatcherimmutablethispatchruntimeprocessmessage4messagerpc rpcu0du0a at systemservicemodelthispatcherimmutablethispatchruntimeprocessmessage3messagerpc rpcu0du0a at systemservicemodelthispatcherimmutablethispatchruntimeprocessmessage2messagerpc rpcu0du0a at systemservicemodelthispatcherimmutablethispatchruntimeprocessmessage1messagerpc rpcu0du0a at systemservicemodelthispatchermessagerpcprocessboolean isoperationcontextsettypesystemxmlxmlexceptionexceptiontypesystemxmlxmlexceptionmessagethe token was expected but found stacktrace at systemxmlxmlexceptionhelperthrowxmlexceptionxmldictionaryreader reader string res string arg1 string arg2 string arg3u0du0a at systemxmlxmlexceptionhelperthrowtokenexpectedxmldictionaryreader reader string expected char foundu0du0a at systemruntimeserializationjsonxmljsonreaderparsestartelementu0du0a at systemruntimeserializationjsonxmljsonreaderreadu0du0a at systemservicemodelthispatcherdatacontractjsonserializeroperationformatterdeserializebodycorexmldictionaryreader reader object parameters boolean isrequestu0du0a at systemservicemodelthispatcherdatacontractjsonserializeroperationformatterdeserializebodyxmldictionaryreader reader messageversion version string action messagedescription messagedescription object parameters boolean isrequestu0du0a at systemservicemodelthispatcheroperationformatterdeserializebodycontentsmessage message object parameters boolean isrequestu0du0a at systemservicemodelthispatcheroperationformatterdeserializerequestmessage message object parametersu0du0a at systemservicemodelthispatcherdemultiplexingthispatchmessageformatterdeserializerequestmessage message object parametersu0du0a at systemservicemodelthispatcheruritemplatethispatchformatterdeserializerequestmessage message object parametersu0du0a at systemservicemodelthispatchercompositethispatchformatterdeserializerequestmessage message object parametersu0du0a at systemservicemodelthispatcherthispatchoperationruntimedeserializeinputsmessagerpc rpcu0du0a at systemservicemodelthispatcherthispatchoperationruntimeinvokebeginmessagerpc rpcu0du0a at systemservicemodelthispatcherimmutablethispatchruntimeprocessmessage5messagerpc rpcu0du0a at systemservicemodelthispatcherimmutablethispatchruntimeprocessmessage4messagerpc rpcu0du0a at systemservicemodelthispatcherimmutablethispatchruntimeprocessmessage3messagerpc rpcu0du0a at systemservicemodelthispatcherimmutablethispatchruntimeprocessmessage2messagerpc rpcu0du0a at systemservicemodelthispatcherimmutablethispatchruntimeprocessmessage1messagerpc rpcu0du0a at systemservicemodelthispatchermessagerpcprocessboolean isoperationcontextsetmy jquery looks like this but i tried changing the actual data which i send as a string serialized json as you can see to a pure json object with the same sad resultajax type post contenttype applicationjson charsetutf8 url ajaxstatisticssvcget7daysstatistics datatype json data customerid 2 timeout 10 success functionobj updatestatisticsobjd error functionxhr if xhrresponsetext bodyhtmlxhrresponsetext else alertunknown error return the wcf service looks like this suppressmessagemicrosoftperformance ca1822markmembersasstatic operationcontract public string get7daysstatisticsstring customerid debugwritelinecustomerid return test done it is placed in a a class with the following attributesservicecontractnamespace aspnetcompatibilityrequirementsrequirementsmode aspnetcompatibilityrequirementsmodeallowedi would not list the configuration in the webconfig to keep this long message short but i can post it if anybody thinks they can use it i just want to stress that i can call a method and get a result string or even a json object i can read from as long as i do not pass any data to the wcf service,['jquery'] +9064,should i use java date and time classes or go with a 3rd party library like joda time i am creating a web based system which will be used in countries from all over the world one type of data which must be stored is dates and timeswhat are the pros and cons of using the java date and time classes compared to 3rd party libraries such as joda time i guess these third party libraries exist for a good reason but i have never really compared them myself,['java'] +9065,what options are available for the layout of directed or undirected graphs in net by graph here i mean something resembling these imagesthe ideal solution woulduse only managed codeallow output to a bitmap imageallow output to wpf elementsinclude some kind of interactive surface for thisplaying the graph that supports zooming panning and reorganisation of nodesi am also interested in hearing about projects that could potentially be used as the starting point for this kind of work if it requires some development to achieve what i want then i am prepared to tackle it the most complex portion of this goal seems to be obtaining the graph layout in a reasonable time frame,['.net'] +9068,setting the http referer in a global beforeall in rspec in order to avoid addingrequestenvhttp referer to a before block on every controller spec file i create i have tried to add this to the global config in spec helperrbconfigbeforeeach requestenvhttp referer the problem is i get the following erroryou have a nil object when you did not expect itthe error occurred while evaluating nilenvhas anyone any pointers on how to implement this correctlycheers,['ruby-on-rails'] +9069,how to log stack frames with windows x64 i am using stackdumps with win32 to write all return adresses into my logfile i match these with a mapfile later on see my article post mortem debugging1 edit problem solved see my own answer belowwith windows x64 i do not find a reliable way to write only the return adresses into the logfile i tried several waystrial 1 pointer arithmetic context context rtlcapturecontextcontext char enextbp char contextrdi forulong frame 0 enextbp frame char pbp enextbp enextbp char pbp next bp in stack fprintflogfile 2d called from 016lx pbp at 016lxn frame ulong64char pbp 8 ulong64pbp this works fine in the debug version but it crashes in the release version the value of contextrdi has no usable value there i did check for differences in the compiler settings visual studio 2005 i have not found anything suspicioustrial 2 using stackwalk64rtlcapturecontextcontextstackframe64 stkmemsetstk 0 sizeofstkstkaddrpcoffset contextripstkaddrpcmode addrmodeflatstkaddrstackoffset contextrspstkaddrstackmode addrmodeflatstkaddrframeoffset contextrbpstkaddrframemode addrmodeflatforulong frame 0 frame bool result stackwalk64 image file machine amd64 in dword machinetype getcurrentprocess in handle hprocess getcurrentthread in handle hthread stk inout lp stackframe64 stackframe context inout pvoid contextrecord null in opt pread process memory routine64 readmemoryroutine symfunctiontableaccess64 in opt pfunction table access routine64 functiontableaccessroutine symgetmodulebase64 in opt pget module base routine64 getmodulebaseroutine null in opt ptranslate address routine64 translateaddress fprintfgapplsetuptracefile 2d called from 016lx stack 016lx frame 016lxn frame ulong64stkaddrpcoffset ulong64stkaddrstackoffset ulong64stkaddrframeoffset if result breakthis does not only dump the return addresses but the whole stack i receive about 10 lines in my log file using this approach i can use this but i have to search trough the lines and some data of the stacks happens to be a valid code addresstrial 3 using backtracestatic ushort winapis pfncapturestackbacktraceulong ulong pvoid pulong 0 if s pfncapturestackbacktrace 0 const hmodule hntdll getmodulehandlentdlldll reinterpret castvoids pfncapturestackbacktrace getprocaddresshntdll rtlcapturestackbacktrace pvoid myframes128 s pfncapturestackbacktrace0 128 myframes null forint ndx 0 ndx 128 ndx fprintfgapplsetuptracefile backtrace 3d 016lxn ndx ulong64myframesndxresults in no usable informationhas anyone implemented such a stack walk in x64 that does only write out the return adresses in the stack ive seen the approaches stacktrace642 stackwalker3 and other ones they either do not compile or they are much too much comlicated it basically is a simple tasksample stackdump64cppinclude windowshinclude dbghelphinclude winbasehinclude stdiohvoid writestackdump file myfile fopenstackdump64log wt context context memsetcontext 0 sizeofcontext rtlcapturecontextcontext rtlcapturecontextcontext stackframe64 stk memsetstk 0 sizeofstk stkaddrpcoffset contextrip stkaddrpcmode addrmodeflat stkaddrstackoffset contextrsp stkaddrstackmode addrmodeflat stkaddrframeoffset contextrbp stkaddrframemode addrmodeflat forulong frame 0 frame bool result stackwalk64 image file machine amd64 in dword machinetype getcurrentprocess in handle hprocess getcurrentthread in handle hthread stk inout lp stackframe64 stackframe context inout pvoid contextrecord null in opt pread process memory routine64 readmemoryroutine symfunctiontableaccess64 in opt pfunction table access routine64 functiontableaccessroutine symgetmodulebase64 in opt pget module base routine64 getmodulebaseroutine null in opt ptranslate address routine64 translateaddress fprintfmyfile 2d called from 016i64lx stack 016i64lx addrreturn 016i64lxn frame stkaddrpcoffset stkaddrstackoffset stkaddrreturnoffset if result break fclosemyfilevoid funcc writestackdumpvoid funcb funccvoid funca funcbint mainint argc char argv funcarunning this sample results in the follwing log file content 0 called from 0140109e stack 012f780 addrreturn 01405798 1 called from 01033d160 stack 012f788 addrreturn 014057b0 2 called from 014057b0 stack 012f790 addrreturn 01 3 called from 02 stack 012f798 addrreturn 014057b0 4 called from 02 stack 012f7a0 addrreturn 012f7f0 5 called from 012f7f0 stack 012f7a8 addrreturn 0 6 called from 0 stack 012f7b0 addrreturn 07ff7250cf40 7 called from 07ff7250cf40 stack 012f7b8 addrreturn 07ff7250d390 8 called from 07ff7250d390 stack 012f7c0 addrreturn 07ff725b6950 9 called from 07ff725b6950 stack 012f7c8 addrreturn c 10 called from c stack 012f7d0 addrreturn 01033d160 11 called from 01033d160 stack 012f7d8 addrreturn c 12 called from c stack 012f7e0 addrreturn c 13 called from c stack 012f7e8 addrreturn c 14 called from c stack 012f7f0 addrreturn 0 15 called from 0 stack 012f7f8 addrreturn 0 16 called from 0 stack 012f800 addrreturn 0 17 called from 0 stack 012f808 addrreturn 0 18 called from 0 stack 012f810 addrreturn 0 19 called from 0 stack 012f818 addrreturn 0 20 called from 0 stack 012f820 addrreturn 01f8010f 21 called from 01f8010f stack 012f828 addrreturn 0053002b002b0033 22 called from 0053002b002b0033 stack 012f830 addrreturn 0206002b002b 23 called from 0206002b002b stack 012f838 addrreturn 0 24 called from 0 stack 012f840 addrreturn 0 25 called from 0 stack 012f848 addrreturn 0 26 called from 0 stack 012f850 addrreturn 0 27 called from 0 stack 012f858 addrreturn 0 28 called from 0 stack 012f860 addrreturn 0 29 called from 0 stack 012f868 addrreturn 0246 30 called from 0246 stack 012f870 addrreturn 012f7f0 31 called from 012f7f0 stack 012f878 addrreturn 0 32 called from 0 stack 012f880 addrreturn 0 33 called from 0 stack 012f8 addrreturn 012f8 34 called from 012f8 stack 012f890 addrreturn 0 35 called from 0 stack 012f898 addrreturn 0 36 called from 0 stack 012f8a0 addrreturn 012fe10 37 called from 012fe10 stack 012f8a8 addrreturn 0 38 called from 0 stack 012f8b0 addrreturn 0 39 called from 0 stack 012f8b8 addrreturn 0 40 called from 0 stack 012f8c0 addrreturn 0246 41 called from 0246 stack 012f8c8 addrreturn 0 42 called from 0 stack 012f8d0 addrreturn 0 43 called from 0 stack 012f8d8 addrreturn 0 44 called from 0 stack 012f8e0 addrreturn 0 45 called from 0 stack 012f8e8 addrreturn 0 46 called from 0 stack 012f8f0 addrreturn 027f 47 called from 027f stack 012f8f8 addrreturn 0 48 called from 0 stack 012f900 addrreturn 0 49 called from 0 stack 012f908 addrreturn 0f01f80 50 called from 0f01f80 stack 012f910 addrreturn 0 51 called from 0 stack 012f918 addrreturn 0 52 called from 0 stack 012f920 addrreturn 0 53 called from 0 stack 012f928 addrreturn 0 54 called from 0 stack 012f930 addrreturn 0 55 called from 0 stack 012f938 addrreturn 0 56 called from 0 stack 012f940 addrreturn 0 57 called from 0 stack 012f948 addrreturn 0 58 called from 0 stack 012f950 addrreturn 0 59 called from 0 stack 012f958 addrreturn 0 60 called from 0 stack 012f960 addrreturn 0 61 called from 0 stack 012f968 addrreturn 0 62 called from 0 stack 012f970 addrreturn 0 63 called from 0 stack 012f978 addrreturn 0 64 called from 0 stack 012f980 addrreturn 0 65 called from 0 stack 012f988 addrreturn 0 66 called from 0 stack 012f990 addrreturn 0 67 called from 0 stack 012f998 addrreturn 0 68 called from 0 stack 012f9a0 addrreturn 0 69 called from 0 stack 012f9a8 addrreturn 0 70 called from 0 stack 012f9b0 addrreturn 0 71 called from 0 stack 012f9b8 addrreturn 0 72 called from 0 stack 012f9c0 addrreturn 0 73 called from 0 stack 012f9c8 addrreturn 0 74 called from 0 stack 012f9d0 addrreturn 0 75 called from 0 stack 012f9d8 addrreturn 0 76 called from 0 stack 012f9e0 addrreturn 0 77 called from 0 stack 012f9e8 addrreturn 0 78 called from 0 stack 012f9f0 addrreturn 0 79 called from 0 stack 012f9f8 addrreturn 0 80 called from 0 stack 012fa00 addrreturn 0 81 called from 0 stack 012fa08 addrreturn 0 82 called from 0 stack 012fa10 addrreturn 0 83 called from 0 stack 012fa18 addrreturn 0 84 called from 0 stack 012fa20 addrreturn 0 85 called from 0 stack 012fa28 addrreturn 0 86 called from 0 stack 012fa30 addrreturn 0 87 called from 0 stack 012fa38 addrreturn 0 88 called from 0 stack 012fa40 addrreturn 0 89 called from 0 stack 012fa48 addrreturn 0 90 called from 0 stack 012fa50 addrreturn 0 91 called from 0 stack 012fa58 addrreturn 0 92 called from 0 stack 012fa60 addrreturn 0 93 called from 0 stack 012fa68 addrreturn 0 94 called from 0 stack 012fa70 addrreturn 0 95 called from 0 stack 012fa78 addrreturn 0 96 called from 0 stack 012fa80 addrreturn 0 97 called from 0 stack 012fa88 addrreturn 0 98 called from 0 stack 012fa90 addrreturn 0 99 called from 0 stack 012fa98 addrreturn 0 100 called from 0 stack 012faa0 addrreturn 0 101 called from 0 stack 012faa8 addrreturn 0 102 called from 0 stack 012fab0 addrreturn 0 103 called from 0 stack 012fab8 addrreturn 0 104 called from 0 stack 012fac0 addrreturn 0 105 called from 0 stack 012fac8 addrreturn 0 106 called from 0 stack 012fad0 addrreturn 0 107 called from 0 stack 012fad8 addrreturn 0 108 called from 0 stack 012fae0 addrreturn 0 109 called from 0 stack 012fae8 addrreturn 0 110 called from 0 stack 012faf0 addrreturn 0 1 called from 0 stack 012faf8 addrreturn 0 112 called from 0 stack 012fb00 addrreturn 0 113 called from 0 stack 012fb08 addrreturn 0 114 called from 0 stack 012fb10 addrreturn 0 115 called from 0 stack 012fb18 addrreturn 0 116 called from 0 stack 012fb20 addrreturn 0 117 called from 0 stack 012fb28 addrreturn 0 118 called from 0 stack 012fb30 addrreturn 0 119 called from 0 stack 012fb38 addrreturn 0 120 called from 0 stack 012fb40 addrreturn 0 121 called from 0 stack 012fb48 addrreturn 0 122 called from 0 stack 012fb50 addrreturn 0 123 called from 0 stack 012fb58 addrreturn 0 124 called from 0 stack 012fb60 addrreturn 0 125 called from 0 stack 012fb68 addrreturn 0 126 called from 0 stack 012fb70 addrreturn 0 127 called from 0 stack 012fb78 addrreturn 0 128 called from 0 stack 012fb80 addrreturn 0 129 called from 0 stack 012fb88 addrreturn 0 130 called from 0 stack 012fb90 addrreturn 0 131 called from 0 stack 012fb98 addrreturn 0 132 called from 0 stack 012fba0 addrreturn 0 133 called from 0 stack 012fba8 addrreturn 0 134 called from 0 stack 012fbb0 addrreturn 0 135 called from 0 stack 012fbb8 addrreturn 0 136 called from 0 stack 012fbc0 addrreturn 0 137 called from 0 stack 012fbc8 addrreturn 0 138 called from 0 stack 012fbd0 addrreturn 0 139 called from 0 stack 012fbd8 addrreturn 0 140 called from 0 stack 012fbe0 addrreturn 0 141 called from 0 stack 012fbe8 addrreturn 0 142 called from 0 stack 012fbf0 addrreturn 0 143 called from 0 stack 012fbf8 addrreturn 0 144 called from 0 stack 012fc00 addrreturn 0 145 called from 0 stack 012fc08 addrreturn 0 146 called from 0 stack 012fc10 addrreturn 0 147 called from 0 stack 012fc18 addrreturn 0 148 called from 0 stack 012fc20 addrreturn 0 149 called from 0 stack 012fc28 addrreturn 0 150 called from 0 stack 012fc30 addrreturn 0 151 called from 0 stack 012fc38 addrreturn 0 152 called from 0 stack 012fc40 addrreturn 0 153 called from 0 stack 012fc48 addrreturn 0 154 called from 0 stack 012fc50 addrreturn 0 155 called from 0 stack 012fc58 addrreturn 0 156 called from 0 stack 012fc60 addrreturn 0 157 called from 0 stack 012fc68 addrreturn 0 158 called from 0 stack 012fc70 addrreturn 0 159 called from 0 stack 012fc78 addrreturn 0 160 called from 0 stack 012fc80 addrreturn 0 161 called from 0 stack 012fc88 addrreturn 0 162 called from 0 stack 012fc90 addrreturn 0 163 called from 0 stack 012fc98 addrreturn 0 164 called from 0 stack 012fca0 addrreturn 0 165 called from 0 stack 012fca8 addrreturn 0 166 called from 0 stack 012fcb0 addrreturn 0 167 called from 0 stack 012fcb8 addrreturn 0 168 called from 0 stack 012fcc0 addrreturn c 169 called from c stack 012fcc8 addrreturn c 170 called from c stack 012fcd0 addrreturn c 171 called from c stack 012fcd8 addrreturn c 172 called from c stack 012fce0 addrreturn c 173 called from c stack 012fce8 addrreturn 030 174 called from 030 stack 012fcf0 addrreturn 030 175 called from 030 stack 012fcf8 addrreturn 030 176 called from 030 stack 012fd00 addrreturn 012fcf0 177 called from 012fcf8 stack 012fd08 addrreturn 030 178 called from 030 stack 012fd10 addrreturn 012fd10 179 called from 012fd18 stack 012fd18 addrreturn 030 180 called from 030 stack 012fd20 addrreturn 0 181 called from 0 stack 012fd28 addrreturn 0 182 called from 0 stack 012fd30 addrreturn 0 183 called from 0 stack 012fd38 addrreturn 0 184 called from 0 stack 012fd40 addrreturn 0 185 called from 010 stack 012fd48 addrreturn 010 186 called from 0 stack 012fd50 addrreturn 0 187 called from 0 stack 012fd58 addrreturn 010 188 called from 010 stack 012fd60 addrreturn 0 189 called from 0 stack 012fd68 addrreturn 0 190 called from 0 stack 012fd70 addrreturn 0 191 called from 0 stack 012fd78 addrreturn 0 192 called from 0 stack 012fd80 addrreturn 0 193 called from 0 stack 012fd88 addrreturn 0 194 called from 0 stack 012fd90 addrreturn 0 195 called from 0 stack 012fd98 addrreturn 0 196 called from 0 stack 012fda0 addrreturn 0 197 called from 0 stack 012fda8 addrreturn 0 198 called from 0 stack 012fdb0 addrreturn 0 199 called from 0 stack 012fdb8 addrreturn 0 200 called from 0 stack 012fdc0 addrreturn 0 201 called from 0 stack 012fdc8 addrreturn 0 202 called from 0 stack 012fdd0 addrreturn 0 203 called from 0 stack 012fdd8 addrreturn 0 204 called from 0 stack 012fde0 addrreturn 0 205 called from 0 stack 012fde8 addrreturn c 206 called from c stack 012fdf0 addrreturn 0cec 207 called from 0cfc stack 012fdf8 addrreturn c01 208 called from c01 stack 012fe00 addrreturn fe 209 called from fe stack 012fe08 addrreturn c 210 called from c stack 012fe10 addrreturn 012fe40 211 called from 012fe40 stack 012fe18 addrreturn 0140122f 212 called from 0140122f stack 012fe20 addrreturn c 213 called from c stack 012fe28 addrreturn c 214 called from c stack 012fe30 addrreturn c 215 called from c stack 012fe38 addrreturn c 216 called from c stack 012fe40 addrreturn 012fe70 217 called from 012fe70 stack 012fe48 addrreturn 0140125f 218 called from 0140125f stack 012fe50 addrreturn c 219 called from c stack 012fe58 addrreturn c 220 called from c stack 012fe60 addrreturn c 221 called from c stack 012fe68 addrreturn c 2 called from c stack 012fe70 addrreturn 012fea0 223 called from 012fea0 stack 012fe78 addrreturn 0140128f 224 called from 0140128f stack 012fe80 addrreturn c 225 called from c stack 012fe88 addrreturn c 226 called from c stack 012fe90 addrreturn c 227 called from c stack 012fe98 addrreturn c 228 called from c stack 012fea0 addrreturn 012fed0 229 called from 012fed0 stack 012fea8 addrreturn 014012cb 230 called from 014012cb stack 012feb0 addrreturn c 231 called from c stack 012feb8 addrreturn c 232 called from c stack 012fec0 addrreturn c 233 called from c stack 012fec8 addrreturn c 234 called from c stack 012fed0 addrreturn 0 235 called from 0 stack 012fed8 addrreturn 0140190c 236 called from 0140190c stack 012fee0 addrreturn 0101 237 called from 0101 stack 012fee8 addrreturn 0454b50 238 called from 0454b50 stack 012fef0 addrreturn 0 23,"['c++', 'c']" +9075,c declaring and using a list of generic classes with different types how having the following generic class that would contain either string int float long as the typepublic class mydatat private t data public mydata t value data value public t data get return data i am trying to get a list of mydatat where each item would be of different ti want to be able to access an item from the list and get its value as in the following codemydata mydata mylist0 could be string int somemethod mydatadatawhere somemethod is declared as followspublic void somemethod string valuepublic void somemethod int valuepublic void somemethod float valueupdatesomemethod is from another tier class i do not have control of and somemethodobject does not existhowever i cannot seem to find a way to make the compiler happyany suggestionsthank you,"['c#', '.net']" +9076,gwt capturing url parameters in get request i need to build a gwt application that will be called by an external application with specific url parameters for example how do i capture the orderid parameter inside the gwt application,['java'] +9077,making sure onpropertychanged is called on ui thread in mvvm wpf app in a wpf app that i am writing using the mvvm pattern i have a background process that doing it is thing but need to get status updates from it out to the uii am using the mvvm pattern so my viewmodel knows virtually nothing of the view ui that is presenting the model to the usersay i have the following method in my viewmodelpublic void backgroundworker reportprogressobject sender reportprogressargs e thismessagesaddemessage onpropertychangedmessagesin my view i have a listbox bound to the messages property a liststring of the viewmodel onpropertychanged fulfills the role of the inotifypropertychanged interface by calling a propertychangedeventhandleri need to ensure that onpropertychanged is called on the ui thread how do i do this i have tried the followingpublic thispatcher thispatcher get set public myviewmodel thisthispatcher thispatchercurrentthispatcherthen adding the following to the onpropertychanged methodif thisthispatcher thispatchercurrentthispatcher thisthispatcherinvokethispatcherprioritynormal new threadstartdelegate onpropertychangedpropertyname returnbut this did not work any ideas,['.net'] +9080,ninject where do you keep your reference to the kernel i am using ninject on a new web application and there are two things that are unclear to medo not i need to keep a reference to the kernel around sessionapp variable to insure that gc does not collect all my instances for example if i specify using and then the kernel object gets collected are not all my singletons collected as wellif i do need keep a reference to a kernel object around how do i allow the arguments passed in to witharguments to change or is that not possible,['c#'] +9083,whats the best wysiwyg editor when using the aspnet mvc framework was wondering what the best wysiwyg editor that i can embed in a website based on the aspnet mvc framework ideally it should be xhtml compliant and allow users to embed images etcthe only one i have used before is the fckeditor how well does this work with the mvc has anyone triedmy main requirements arexhtml compliancedeprecate as best it can when javascript is thisabledmodify the toolbar optionsskinable at least easily change the look and feeleasy to use client side apiplays nicely with the aspnet mvc frameworkeditas nick said the xstandard editor is good but requires a pluginwhat are your thoughts on requiring a plugin for website functionalitythankskieronadditional infoas hippo answered the tinymce edit is ideal for completness heres there download pagethere is a download for net jsp coldfusion php and a jquery plugin tooalso there are language packs availablebeen using it for a while now best editor i have used thanks all,['javascript'] +9084,identify ithisposable objects i have to review a code made by some other person that has some memory leaks right now i am searching the thisposable objects to enclause them with the using statement and i would like to know if there is a quick way that tells you all the thisposable objects declared in i mean something like resharper or another visual studio pluginthanks,['c#'] +9086,can i add a and links to a javascript alert i have the following statementbtnapplyattributesaddonclick alertmust be a member to use this toolis there a way to add a new line i tried but it showed the in the text in addition can i add a link that would close the alert and take the user to another pagehow can i do this with my examplewhen i added the n the alert does not show up,['javascript'] +9087,can i use a decorator to mutate the local scope of a function in python is there any way of writing a decorator such that the following would workassert z not in globalsmy decoratordef funcx y print zedit moved from anwserin answer to hops why syntax sugar dryit is not about caching it is about calculating z and z1 z2 z3 based upon the values of x yi have lots of functions which do related things and i do not want to do have to writez1 z2 z3calculate fromx yat the beginning of every single function i will get it wrong somewhere if this were c i would do this with cpp if this were lisp i would do this with macros but i wanted to see if decorators could do the same thingif it helps i would almost certainly call the decorator precalculate z and it certainly wouldnt be part of any public apii could probably get a similar effect from using the class infrastructure as well but i wanted to see if it was doable with raw functions,['python'] +9093,how can you programmatically tell the cpython interpreter to enter interactive mode when done if you invoke the cpython interpreter with the i option it will enter the interactive mode upon completing any commands or scripts it has been given to run is there a way within a program to get the interpreter to do this even when it has not been given i the obvious use case is in debugging by interactively inspecting the state when an exceptional condition has occurred,['python'] +9097,how to thisable file input text box in ie is it possible to prevent a user from typing in a file input text box in ie the reason i ask is that if a user enters text that does not look like a file system path eg does not start with something like c then when the user clicks the submit button nothing will happeni would either like to not allow the user to type in the box or have the form submit as normali have found that the same question was asked here with no answerand this person came up with a hack which i can use if there is no other suitable answer file inputs with css and the domedit to clarify if the user types not a file path in the text box next to the browse button and clicks submit in ie nothing will happen the form will not submit ie does not allow a form to be submitted when a input typefile box does not have a real file path,['html'] +9105,static vs extern cc what is the difference between a static member function and an extern c linkage function for instance when using makecontext in c i need to pass a pointer to function google recommends using extern c linkage for it because makecontext is c but i found out that using static works as well am i just lucky orclass x public static void proxyint i makecontext void void xproxy vsextern c void proxyint i makecontext void void proxy edit i am sorry but i am still not convinced can you show a compiler or architecture where the static member version does not work and it is not a bug in the compiler,['c++'] +9124,is a master preferences class a good idea i have a class that manages user preferences for a large software project any class in the project that may need to set or retrieve a user preference from a persistent store is to call the static methods on this class this centralized management allows the preferences to be completely wiped programmatically which would be impossible if each pref was handled close to its use code sprinkled throughout the projecti ran into another implication of the centralization design in the course of this the software has a public api that api can be provided by itself in a jar classes in that api might refer to the pref management class so the pref manager has to go in the api jareach preference might have a default value upon software startup that default might be computed the algorithm depends on the preference and thus tends to reside near the use code so if the pref manager needs to come up with a default it calls the class in questionbut now that pref manager has become an octopus class sucking in all sorts of classes into the api jar that should not be there if it does not then programs using the api jar quickly run into classdef exceptions if it does then the api jar is now bloated as each of those other classes may refer to still othersin general do other java programmers manage their preferences with a centralized classdoes it make sense to thistribute that static pref management class as part of a public apishould that pref manager be the keeper of the code for determining defaults,['java'] +9134,what is the best way to store configuration variables in php i need to store a bunch of configuration information in phpi have considered the following does not seem rightmysqlpass password seems slightly betterconfig array mysql pass password seems dangerous having this data accessible by anything but it cannot be changed via this methoddefinemysql password password do not know if this is such a good ideaclass config const static mysql password password this is all i have thought of so far i intend to import this configuration information into my application with require configincphpwhat works for you with regard to storing configuration data and what are best practices concerning this,['php'] +9137,c comparing with null are these equivalentif nullmyobjectdo something andif myobjectnulldo something or will they produce different code,['c#'] +9140,why does int is uint true in c can somebody clarify the c is keyword please in particular these 2 questionsq1 line 5 why does this return trueq2 line 7 why no cast exceptionpublic void test object intarray new int 100 200 if intarray is uint why does this return true uint uintarray uintintarray why no class cast exception for int x 0 x uintarraylength x consoleoutwritelineuintarrayx msdns description does not clarify the situation it states that is will return true if either of these conditions are met vs71aspxmdsn articleexpression is not nullexpression can be cast to typei do not believe that you can do a valid cast of int into uint becausea this code does not compileint signed new int 100 uint unsigned uintsignedb doing the cast in the debugger gives an erroruintsignedcannot convert type int to uintsure enough if line 3 was int instead of object then it would never compile which brings me to a final question related to q2q3 why does c raise a castconversion error in the debugger and compiler but not at runtime,['c#'] +9145,thisplay bmp in jlabel java can thisplay png jpg a some other picture formats but i have to thisplay a bmp file in a jlable by getting the file pathimageicon imageicon new imageiconimagefilegetabsolutepathimageicon support the typical pnggifjpg imagesin the project i am working i can not open a bmp file and store the same file as a jpg because i am not allow to store something at runtime i could only generate the image in hold it in memory but i dont know how to do thishow can i show bmp in java 14thanks,['java'] +9161,c binary literals is there a way to write binary literals in c like prefixing hexadecimal with 0x 0b does not workif not what is an easy way to do it some kind of string conversion,['c#'] +9162,overriding static variables when subclassing i have a class lets call it a and within that class definition i have the followingstatic qpainterpath pathwhich is to say i am declaring a static classwide pointer to a path object all instances of this class will now have the same shared data member i would like to be able to build upon this class subclassing it into more specialised forms layering behaviour and with each class having its own unique path object but not having to repeat the boring bits like calculating bounding boxes or calling the painting routinesif i subclass it to create a class f for example i want f to use the inherited drawing routines from a but to use the static classwide path object declared in f i have tried having the declaration above in the private section and repeating it in the derived class f and tried having it in the protected section all with no joyi can sort of see why this is happeningvoid apaint thispathis referring to apath instead of fpath even when the object is of class fis there an elegant way to get round this and allow each class to maintain a static path object while still using drawing code defined in the base class and having all classes except perhaps the base class be real and instantiatable,['c++'] +9165,fix for backgroundposition in ie i get this problem in ie7 when running a piece of code that uses jquery and 2 jquery plugins the code works in ff3 and chromethe full error isline 33 char 6 error bg is null or not an object code 0 url httplocalhostindex2htmlhowever line 33 is a blank linei am using 2 plugins draggable and zoom no matter what i do to the code it is always line 33 that is at fault i check the source has update via view source but i feel this could be lying to mebodydiv idzoom classzoomdivdiv iddraggable classmain internalimg srctilesmapspainsmallerjpg altdivscript typetextjavascriptdocumentreadyfunction draggabledrag zoomzoomtarget divdraggable zoom imagesnew arraytilesmapspainsmallerjpg tilesmapspainjpg scriptbodyessentially what i am trying to do is recreate the pragmatic ajax map demo with jqueryit would appear that the second line of this snippet is causing the troublebg thiscssbackgroundposition ifbgindexof1it seems to be trying to select the backgroundposition property of draggable and not finding it manually adding a backgroundposition 0 0 did not fix it any ideas on how to get around this problemi tried using the ms script debugger but that is nearly useless cannot inspect variables or anything else,"['javascript', 'jquery']" +9177,difference between generic argument constrained to an interface and just using the interface what is the difference between thisvoid mymethodimyinterface value and thisvoid mymethodtt value where t imyinterface,['.net'] +9183,why does strcmp return 0 when its inputs are equal when i make a call to the c string compare function like thisstrcmptimetimeit returns 0 which implies that the strings are not equalcan anyone tell me why c implementations seem to do this i would think it would return a nonzero value if equal i am curious to the reasons i am seeing this behavior,['c'] +9199,how can i tell whether an element matches a selector let us say i have got a dom element how can i tell whether it matches a jquery selector such as p or myclass it is easy to use the selector to match children of the element but i want a truefalse answer to whether this particular element matchthe element may not have an id and i cannot assign it a random one for reasons beyond this so i cannot apply my selector to the elements parent and look for children with the same id as minewill this work as intended i cannot figure out javascript object comparisons selector myelementparentnodeeach if this myelement found itseems like there would be an easy way to see whether a dom element matches a jquery selector,"['javascript', 'jquery']" +9214,how do i simulate a slow internet connection edge3g on a mac is there a firefox plugin exact duplicate how do i simulate a slow internet connection edge3g on a mac is there a firefox plugin,['iphone'] +9219,how to determine a windows executables dll dependencies programatically how to determine what dlls a binary depends on using programmatic methods to be clear i am not trying to determine the dll dependencies of the running exec but of any arbitrary exec that may be missing a required dll i am looking for a solution to implement in a cc application this is something that needs to be done by my application at runtime and cannot be done by a third party app like depends,['c++'] +9228,what are the differences between a multidimensional array and an array of arrays in c what are the differences between multidimensional arrays double and arrayofarrays double in cif there is a difference what is the best use for each one,['c#'] +9234,internationalization with nibs is that really a good idea in the apple docs they say that a nib enables internationalization by just translating the nib into many languages i am thinking now about a worse but realistic scenario you have made a huge user interface then you translate this into 25 languages so you get 25 different nibs you also get a huge redundancy in styling and defining the ui 25 times the same stuff same bindings same everything just text is differentso i really think this is a very bad approach instead i would prefer to just link in all texts from a resource bundle or something like that just a file with text strings which is linked in at run time from the appropriate language resource then you only have trouble linking in the text which really doesnt make any fun but then you can do changes on your ui once without having to do the same step 25 times over and over again a new binding in every nib that would be so horriblenow please tell me i got that wrong apple does not assume that we do something so creazy,['objective-c'] +9236,mysql check if the user exists and drop it thereas not standard way to check if a mysql user exists and based on that drop it are there any workarounds for this edit i need a straight way to run this without throwing up an erroregdrop user testlocalhost,['mysql'] +9238,before the parameter name just a quick and no doubt easy question i am pretty new to php and am looking through some existing code i have tried to find the answer to my question on google but to no availcan somebody please let me know what the sign before the parameter var doesfunction setdefaultvar default if issetvar var default,['php'] +9246,most important things about c generics lesson learned what are most important things you know about generics hidden features common mistakes best and most useful practices tipsi am starting to implement most of my libraryapi using generics and would like to collect most common patterns tips etc found in practicelet me formalize the question what is the most important thing youve learned about genericsplease try to provide examples it would be easier to understand as opposed to convoluted and overlydry descriptionsthanksthis question is somewhat similar to jons question though on a different subject,"['c#', '.net']" +9251,generation pdf from html component for net can you please point me to open source or a reasonably priced comercial product capable of generating pdf from html,"['.net', 'html']" +9256,how to pass information using an http redirect in django i have a view that accepts a form submission and updates a modelafter updating the model i want to redirect to another page and i want a message such as field x successfully updated to appear on this pagehow can i pass this message to the other page httpresponseredirect only accepts a url i have seen this done before on other sites how is this accomplished,['python'] +9258,why does not the weakref work on this bound method i have a project where i am trying to use weakrefs with callbacks and i do not understand what i am doing wrong i have created simplified test that shows the exact behavior i am confused with why is it that in this test test a works as expected but the weakref for selfmycallbackb thisappears between the class initialization and calling test b i thought like as long as the instance a exists the reference to selfmycallbackb should exist but it does notimport weakrefclass aobject def init self def mycallbacka print mycallbacka selfmycallbacka mycallbacka self testa weakrefproxyselfmycallbacka self testb weakrefproxyselfmycallbackb def mycallbackbself print mycallbackb def test aself self testa def test bself self testbif name main a a atest a atest b,['python'] +9262,how to include all php files from a directory very quick n00b question in php can i include a directory of scriptsie instead ofincludeclassesclass1phpincludeclassesclass2phpis there something likeincludeclassescould not seem to find a good way of including a collection of about 10 subclasses for a particular class,['php'] +9267,python choosing between modules and classes in my application i have to maintain some global application state and global application wide methods like currently connected users total number of answers create an application config file etc there are two optionsmake a separate appstatepy file with global variables with functions over them it looks fine initially but it seems that i am missing something in clarity of my codecreate a class appstate with class functions in a appstatepy file all other modules have been defined by their specific jobs this looks fine but now i have to write longer line like appstateappstateget user list moreover the methods are not so much related to each other i can create separate classes but that would be too many classesedit if i use classes i will be using classmethods i do not think there is a need to instantiate the class to an object,['python'] +9278,jqueryjavascript reordering rows i have a aspx page that looks something like thistr idrow1 tdsome labeltd tdsome complex controltdtrtr idrow2 tdsome labeltd tdsome complex controltdtrtr idrow3 tdsome labeltd tdsome complex controltdtras soon as the page is loaded i would want to reorder these rows based on the users previously selected order stored in a databasehow would i use jqueryjs to accomplish thisediti have run into a performance issue with the appendto code it takes 400ms for a table of 10 rows which is really unacceptable can anyone help me tweak it for performancefunction rearrangetablecsvorder tableid var arrcsvorder csvordersplit no need to rearrange if array length is 1 if arrcsvorderlength 1 for var i 0 i arrcsvorderlength i tableidfindfieldname arrcsvorderi eq0parentstreq0appendto tableid,"['javascript', 'jquery']" +9280,divs collapsing around header i have a few nested divsdiv idwrapper div idheader a bunch of float divs here div div idbody div idcontent a bunch of html controls here div divdivwrapper style width 780px margin20px auto border solid black 5pxheader style position relativeminheight 125pxbody style position relativecontent style position absoluteleft 50px top 0pxi have a bunch of html elements in the content div and for some reason the body div and the wrapper div are collapsing around the header and the content div hangs out on its own if i do not set a fixed height for the body div the only float elements i have are in the headereditif i remove the content div and drop the html elements directly in body the body div stops collapsing trying to understand why guess it is due to the position absolute of the content divany clue why this is happening and how to solvei had a look at this question but it does not seem to work for me or maybe i am clearing inthe wrong place,"['html', 'css']" +9281,errors on non model fields in rails whats the best way to report errors on form fields not associated with a particular model in rails as an example i have a form for the batch creation of user accounts with random users passwords it takes as inputs the quantity of users to make information about what attributes all users should have and information about the batch which is stored in a user batches model associated with the created usersideally there would be some errors on like way to list errors coming from the quantity field which is associated with no model the user information fields associated with the user records that get created and the user batches model with minimal codethis also applies to search forms and the like which do not get run through ar validations any ideas,['ruby-on-rails'] +9285,what is sql injection possible duplicatesxkcd sql injection please explaincan someone explain sql injection how does it cause vulnerabilities where exactly is the point where sql is injected,['sql'] +9286,winforms data binding bind to objects in a list i need some helpguidance on winforms data binding and i cannot seem to get google to help me with this onehere is my scenario consider the following classes which is similar to what i needpublic class car public string name get set public listtire tires get set public class tire public double pressure get set my instances of this will be an object of class car with a list with four tire objects note that i will always have a known number of objects in the list herenow i want to data bind this to a form containing five textboxes one textbox with the name of the car and one textbox with each of the tires pressuresany idea on how to make this work the designer in vs does not seem to allow me to set this up by assigning to list indexes like tires0pressuremy current solution is to bind to a bindablecar which would be likepublic class bindablecar private car car public bindablecarcar car car car public string name get return carname set carname value public double tire1pressure get return cartires0pressure set cartires0pressure value public double tire2pressure get return cartires1pressure set cartires1pressure value public double tire3pressure get return cartires2pressure set cartires2pressure value public double tire4pressure get return cartires3pressure set cartires3pressure value but this becomes really ugly when my lists contains 20 instead of 4 objects and for each of those objects i want to bind against 6 properties that makes a huge bindableobject,"['c#', '.net']" +9295,oolong sio2 or commercial game engine for 3d iphone games newbie i am trying to pick between the oolong and sio2 iphone game engines for my first game programming project i have some cocoa experience and many years of c including relatively low level 2d graphics and developing quicktime plugins but only minor opengl exposure which engine would be easiest to learn and most productive for someone with my background and limited timeboth include the bullet physics engine i lean towards oolong because of its c source and optimisation for the powervr graphics however the lua interpreter and additional sound goodies in sio2 are appealing sio2 also seems to have a good range of tutorials i am also willing to spend money on unity or torque game environment if they will save me significant time the pricing gets interesting though the unity indie license only applies to companies with turnover not revenue of under usd 10 so youre easily out of that category and up for usd 30 per seat i would want a lot of convincing it will save time to justify that investment over just using sio2 the torque 3d product does not seem to be released yet but looks like costing about usd 500 on top of a usd 150 indie license their income threshold is usd 250edit dec 2011 sio2 is no longer free,['iphone'] +9296,minimize browser window using javascript is there a javascript or jquery method to minimize the current browser window,"['javascript', 'jquery']" +9299,data binding poco properties are there any data binding frameworks bcl or otherwise that allow binding between any two clr properties that implement inotifypropertychanged and inotifycollectionchanged it seems to be it should be possible to do something like thisvar binding new bindingbindingsource somesourceobjectbindingsourcepath customernamebindingtarget sometargetobjectbindingtargetpath clientnamebindingmanagerbindbindingwhere somesourceobject and sometargetobject are just pocos that implement inotifypropertychanged however i am unaware of any bcl support for this and am not sure if there are existing frameworks that permit thisupdate given that there is no existing library available i have taken it upon myself to write my own it is available herethanks,"['c#', '.net']" +9300,how to write meaningful docstrings what in your opinion is a meaningful docstring what do you expect to be described therefor example consider this python clas init def init self name value thisplaynamenone matchingrulestrict name field name value field value thisplayname nice thisplay name if empty will be set to field name matchingrule i have no idea what this does set to strict by default do you find this meaningful post your goodbad examples for all to know and a general answer so it can be accepted,['python'] +9302,how do i utilise all the cores for nmake i just got a new quad core computer and noticed that nmake is only using 1 processi used to use make which had the switch j4 for launching 4 processes what is the nmake equivalenteditbased on the information below i have been able to add a command to my qmake project fileqmake cxxflags mpwhich effectively did it for me many thanks,['c++'] +9303,how to create a string or char from an ascii value in javascript in javascript how to get a string representation of an ascii value eg how to turn 65 into a,['javascript'] +9307,changing font colour in textboxes in ie which are thisabled i noticed that you can change the colour of text in textboxes which are thisabled in firefox applying a simple class but could not get a way to do it in ie 67 does anyone out there have a elegant solution to achieve this,['css'] +9312,how to initialize an nsobjects subclass on iphone i want to write some methods in a class so that other classes can call these methods using instance methodnameparameterif the class is a subclass of uiviewcontroller i can use initwithnibname to initialize it but i want to write the methods in an nsobjects subclass how can i initialize it,['iphone'] +9313,how can i use c class in python i have implemented a class in c i want to use it with pythonplease suggest step by step method and elaborate each stepsomthing like thisclass test private int n public testint k nk void setintint k and k int getint return n now in python t1 test12 t1getint12 t1setint32 t1getint32please suggesthow can i do this note i would like to know manual way to do that i do not want any third party library dependency,"['c++', 'python']" +9321,should i return an array or a collection from a function whats the preferred container type when returning multiple objects of the same type from a function is it against good practice to return a simple array like mytype or should you wrap it in some generic container like icollectionmytype thanks,"['c#', '.net']" +9334,inline member functions in c iso c says that the inline definition of member function in c is the same as declaring it with inline this means that the function will be defined in every compilation unit the member function is used however if the function call cannot be inlined for whatever reason the function is to be instantiated as usual the problem i have with this definition is that it does not tell in which translation unit it would be instantiatedthe problem i encountered is that when facing two object files in a single static library both of which have the reference to some inline member function which cannot be inlined the linker might pick an arbitrary object file as a source for the definition this particular choice might introduce unneeded dependencies among other thingsfor instancein a static libraryahclass a public virtual bool foo return true u1cppa a1u2cppa a2and lots of dependenciesin another projectmaincppinclude ahint main a a afoo return 0the second project refers the first how do i know which definition the compiler will use and consequently which object files with their dependencies will be linked in is there anything the standard says on that matter tried but failed to find thatthanksedit since i have seen some people misunderstand what the question is i would like to emphasize if the compiler decided to create a symbol for that function and in this case it will because of virtualness there will be several externallyseen instantiations in different object file which definition from which object file will the linker choose,['c++'] +9346,switch from microsofts stl to stlport i am using quite much stl in performance critical c code under windows one possible cheap way to get some extra performance would be to change to a faster stl libraryaccording to this post stlport is faster and uses less memory however it is a few years oldhas anyone made this change recently and what were your results,['c++'] +9347,padding is invalid and cannot be removed using aesmanaged i am trying to get simple encryptiondecryption working with aesmanaged but i keep getting an exception when trying to close the decryption stream the string here gets encrypted and decrypted correctly and then i get the cryptographicexception padding was invalid and cannot be removed after consolewriteline prints the correct stringany ideasmemorystream ms new memorystreambyte rawplaintext encodingunicodegetbytesthis is annoyingusing aes aes new aesmanaged aespadding paddingmodepkcs7 aeskey new byte1288 aesiv new byte1288 using cryptostream cs new cryptostreamms aescreateencryptor cryptostreammodewrite cswriterawplaintext 0 rawplaintextlength csflushfinalblock ms new memorystreammsgetbuffer using cryptostream cs new cryptostreamms aescreatedecryptor cryptostreammoderead byte rawdata new byterawplaintextlength int len csreadrawdata 0 rawplaintextlength string s encodingunicodegetstringrawdata consolewritelines,"['c#', '.net']" +9348,how to parse hex or decimal int in python i have a string that can be a hex number prefixed with 0x or a decimal number without a special prefix except for possibly a minus sign 0x123 is in base 16 and 298 is in base 10how do i convert this to an int or long in pythoni do not want to use eval since it is unsafe and overkill,['python'] +9352,global keyboard capture in c application i want to capture a keyboard shortcut in my application and trigger a dialog to appear if the user presses a keyboard combo even outside of the app similar to google desktop searchs ctrl ctrl to bring up the search dialogi have tried using some keyboard hook modules out there that basically use win32 interop to get this effect but each implementation i have tried ties down the keyboard to some extent to where you start getting weird behaviors when the application is doing something intensive such as loading a large amount of data this would cause the keyboard and mouse to lockupi am looking for a lightweight solution that would allow this to be done without tying down the keyboard and mouse,['.net'] +9357,convertingaccessing querystring values in aspnet i am curious what everyone does for handlingabstracting the querystring in aspnet in some of our web apps i see a lot of this all over the siteint val 0ifrequestquerystringsomekey nullval converttoint32requestquerystringsomekeywhat are some better ways to handle this grossness,"['c#', '.net', 'asp.net']" +9360,is there a way to put inner controls inside a aspnet custom control i want to do something like updated exampleuctabs tab namea handy tab node urldefaultaspx node urlnode2aspx tab tab nameanother handy tab node urlneatoaspx node urlnode3aspx node urlnode4aspx tabuctabspossible any tutorials or howtos i am not sure what to even search on or what this is called so have not found anything so far inner controls inner collection something something,"['.net', 'asp.net']" +9366,interesting test of javascript regexp i wrote a javascript regexp test to detect date string format i added an redundant g flag by mistake and found something interestingvar s 20090310var regexd4d2d2galertregextestsalertregextestsalertregextestsalertregextestsi got a true followed by a false then another true then another falseif i use a loop to execute it i found something more interesting i got four true in ie and safari and truefalsetruefalse in ff chromefor var i0 ilt4 i var s 20090310 var regexd4d2d2g alertregextestsdoes anybody has idea to explain why the javascript regex behaves like that and what cause browsers return different results related to variable declaration and life scope,['javascript'] +9367,can i do sti and still use polymorphic path helpers i am using single table inheritance and have comments on all the subclasses i am only using 1 controller for all the different sti types when the form for helper generates a url for a subtype it tries to use a helper for the subtype but i want it to use the helper for the parent this is the error i getundefined method subclasstypename comments path for actionviewbase0x41ef27cthe path helper it should use isparentclasstypename comments path,"['ruby-on-rails', 'ruby']" +9371,ntfs alternate data streams net how would i create delete read write ntfs alternate data streams from netif there is no native net support which win32 apis would i use also how would i use them as i do not think this is documented,"['c#', '.net']" +9375,noncollapsing but still linebreakable space in html what can i use in html if i want to have whitespace in the middle of the line that looks like three spaces but can still be broken if the line gets too longregular whitespace gets collapsed a run of spaces looks the same as a single space and at the nonbreaking space nbsp the line cannot be brokenupdate i think what i really want is a i14prei14 tag that can still break long lines i need to thisplay source code,['html'] +9382,how to select html nodes by id with jquery when the id contains a dot if my html looked like thistd classcontrolcell input classinputtext idsearchbagcompanyname namesearchbagcompanyname typetext value tdhow could i select searchbagcompanyname with jqueryi cannot get it to work and i fear it is the dot that is breaking it allthe annoying thing is that renaming all my ids would be a lot of work not to mention the loss in readabilitynoteplease let us not start talking about how tables are not made for layouting i am very aware of the value and shortcomings of css and try hard to use it as much as possible,['jquery'] +9384,reasons for why a winforms label does not want to be transparent why cannot i set the backcolor of a label to transparent i have done it before but now it just do not want toi created a new usercontrol added a progressbar and a label to it when i set the backcolor of the label to transparent it is still gray why is thiswhat i wanted was to have the label on top of the progressbar so that its text was in the progressbar,['c#'] +9390,how can i change the color of the gridlines of a grid in wpf i have a grid not a datagrid but a real grid with gridlines set to true how can i change the color of the gridlineshardcoded in xaml is ok since it is just for developmentreasonsgrid showgridlinestrue,['.net'] +9394,how can i debug a regular expression in python is there a way to debug a regular expression in python and i am not referring to the process of trying and trying till they work edit here is how regexes can be debugged in perl use re debugmy str get http11ifstr getssi print match1nthe code above produces the following output on my computer when ran compiling rex getssfinal program 1 exactf 3 3 plus 5 4 space 0 5 open1 7 7 plus 9 8 nspace 0 9 close1 11 11 end 0stclass exactf minlen 5matching rex getss against get http11matching stclass exactf against get http11 33 chars 0 1exactf 3 3 3plus5 space can match 1 times out of 2147483647 4 5 open17 4 7 plus9 nspace can match 20 times out of 2147483647 24 9 close1 24 11 end0match successfulmatchfreeing rex getss,['python'] +9396,is there a cross browser way of setting stylefloat in javascript usually if you need to set a style attribute in javascript you say something likeelementstyleattribute valuethere are slight variations but usually the attribute name is a similar albeit camelcased version of the html attribute namethe problem for me is that the float attribute does not work float is a keyword in javascript and so stylefloat makes all the javascript for the page break i looked in msdn and it said to use stylefloat like soelementstylestylefloat valuethat only works in ie firefox safari chrome opera none of them seem to have an answer where am i going wrong there has to be a simple answer to this,['javascript'] +9404,is there a java library to access the native windows api is there a java library to access the native windows api either with com or jni,['java'] +9410,databinding a custom control i have a custom control windows form that is a lookup text box a property on the control is current selection which is a custom object containing identifier code and description this property is databound using a bindingsourcethisplaying the information works great on the other hand regardless of whether i set the update to onvalidate or onvaluechange it never updates the bindingsource is there something i am missing to get this to auto updateprivate systemwindowsformsbindingsource buildplancomponentdatabindingsource public void loadbuildplanstring itemnumber var buildplancomponents buildplanloadbuildplancomponentsitemnumber automaticprice buildplancomponentdatabindingsourcedatasource buildplancomponents assemblynumber itemnumber bindabletruedefaultvaluenullpublic ilookupselection currentselection get if currentselection null currentselection new lookupselection code txtlookuptext return currentselection set if value null return currentselection value settextcurrentselection thisplaytext setdescriptioncurrentselection thisplaydescription,['c#'] +9416,wpf how do i set the owner window of a dialog shown by a usercontrol i have got a wpf application with these three types of thingswindowmainusercontrolzackwindowmodalusercontrolzack1 sits on my windowmainwindow xclasswindowmain xmlns xmlnsx xmlnslocalclrnamespaceprojectname namewindowmain grid localusercontrolzack xnameusercontrolzack1 gridwindowusercontrolzack1 thisplays a windowmodal dailog boxpartial public class usercontrolzack private sub somebutton click instantiate the dialog box and open modally dim box as windowmodal new windowmodal boxowner boxshowdialog process data entered by user if dialog box is accepted if boxdialogresultgetvalueordefault true then somevar boxsomevar end if end subend classhow do i set boxowner to the correct window my running instance of windowmaini cannot use boxowner meowner because owner is not a member of projectnameusercontrolzacki cannot use boxowner meparent because that returns a grid not the windowi cannot use boxowner windowmain because windowmain is a type and cannot be used as an expression,['.net'] +9419,please critique my php authentication efforts after posting this a while back i decided to create my own registration authentication capability in php i would love anyone to point out the flaws opportunities for improvement particularly around whats stored in the sessionthe logical flow is1 user registers using email as username a site name which then forms part of any url which they will have access to and a password of at least 6 characters which must contain letters and numbers i know this could be stronger2 provided the user and site are unique i then store both of those along with a randomly generated string salt in a row in the auth table in my database i then take the users password concatenate the salt to it and store an md5 hash of this salted password in the same database row3 when a user then logs in i take the password she is entered and concatenate the salt to it create an md5 hash of that and compare it to what i have stored in the database if they match the user has entered the right password and their username is written to the session4 on every request i use the username stored in the session to query the database and read the site name associated with this user i then compare this to the site name in the url itself and if they match i set a variable which is accessible to the rest or of the script not a global variable it is just readable by my controller which decides if a user can see a particular page if the two site names do not match the user is redirected back to loginmy concern is could someone write to the session and thus be able to access peoples pages if they know the username they signed up with how would you go about preventing thisbefore anyone accuses me of negligence by the way this is a personal project for learning i am not exposing any clients data,['php'] +9420,how to change the star images of the ratingbar with android sdk 11 r1 is there any way to change the ratingbar widget clas star image with my own is this possible at all if so then how thanks,['android'] +9433,is it possible to deserialize xml into list given the following xmlxml version10user list user id1id namejoename user user id2id namejohnname useruser listand the following classpublic class user xmlelementid public int32 id get set xmlelementname public string name get set is it possible to use xmlserializer to deserialize the xml into a listuser if so what type of additional attributes will i need to use or what additional parameters do i need to use to construct the xmlserializer instancean array user would be acceptable if a bit less preferable,['c#'] +9434,forms authentication across subdomains is it possible to authenticate users across subdomains when the authentication takes place at a subdomain instead of the parent domain for exampleuser logs into site1parentcom and then we need to send them to reportingparentcomcan i authenticate them to the reporting site even though the login occured at a subdomainso far all of the research i have done has users logging into the parent domain first and then each subdomain has access to the authentication cookie,"['c#', 'asp.net']" +9437,c string memory management last week i wrote a few lines of code in c to fire up a large text file 30 lines into a dictionary it took ten minutes to write and it executed in less than a second now i am converting that piece of code into c because i need it in an old c com object i have spent two days on it this far although the productivity difference is shocking on its own it is the performance that i would need some advice onit takes seven seconds to load and even worse it takes just exactly that much time to free all the cstringws afterwards this is not acceptable and i must find a way to increase the performanceare there any chance that i can allocate this many strings without seeing this horrible performace degradationmy guess right now is that i will have to stuff all the text into a large array and then let my hash table point to the beginning of each string within this array and drop the cstringw stuffbut before that any advice from you c experts out thereedit my answer to myself is given below i realized that that is the fastest route for me and also step in what i consider the right direction towards more managed code,['c++'] +9438,finding the type of an element using jquery in jquery if i have a reference to an element how can i determine what kind of element it is for example an input or an dropdown is there any way to find outduplicatehow can i determine the element type of a matched element in jquery,['jquery'] +9440,using scandir to find folders in a directory php i am using this peice of codetarget extracted name0 scan scandirtargetto scan the directory of a folder which is used for zip uploads i want to be able to find all the folders inside my target folder so i can delete them and their contents leaving only the files in the target directory once i have returned the contents of the folder i do not know how to differentiate between the folders and the files to be able to delete the folders also i have been told that the rmdir function cannot delete folders which have content inside them is there any way around thisthanks ben,['php'] +9441,best way to stream files in aspnet whats the best way to stream files using aspnetthere appear to be various methods for this and i am currently using the responsetransmitfile method inside an http handler which sends the file to the browser directly this is used for various things including sending flvs from outside the webroot to an embedded flash video playerhowever this does not seem like a reliable method in particular there is a strange problem with internet explorer 7 where the browser just hangs after a video or two are viewed clicking on any links etc have no effect and the only way to get things working again on the site is to close down the browser and reopen itthis also occurs in other browsers but much less frequently based on some basic testing i suspect this is something to do with the way files are being streamed perhaps the connection is not being closed properly or something along those linesafter trying a few different things i have found that the following method works for meresponsewritefilepathresponseflushresponsecloseresponseendthis gets around the problem mentioned above and viewing videos no longer causes internet explorer to hanghowever my understanding is that responsewritefile loads the file into memory first and given that some files being streamed could potentially be quite large this does not seem like an ideal solutioni am interested in hearing how other developers are streaming large files in aspnet and in particular streaming flv video files,['asp.net'] +9442,coding guides how do you split up your large source files the project i am working on has just hit 4200 lines in the main c file which is causing intellisense to take a few seconds sometimes up to 6 or so to respond during which visual studio locks up i am wondering how everyone else splits their files and whether there is a consensusi tried to look for some guides and found googles c guide but i could not see anything about semantics such as function sizes and file sizes maybe it is there i have not looked at it for a while so how do you split your files do you group your methods by the functions they serve by types event handlers privatepublic and at what size limit do you split functions edit to clarify the application in question handles data so it is interface is a bigass grid and everything revolves around the grid it has a few dialogs forms for management but it is all about the data the reason why it is so big as there is a lot of error checking event handling and also the grid set up as masterdetail with 3 more grid for each row but these load on master row expanded i hope this helps to clarify what i am on about,['c#'] +9447,how do i use jquerys formserialize but exclude empty fields i have a search form with a number of text inputs drop downs that submits via a get i would like to have a cleaner search url by removing the empty fields from the querystring when a search is performedvar form form var serializedformstr formserialize i would like to remove inputs where value is or herewindowlocationhref search serializedformstrany idea how i can do this using jquery,"['javascript', 'jquery']" +9458,download textarea contents as a file using only javascript no serverside i am being asked to make a download button that downloads the contents of a textarea on the same page as a file with the browsers save as dialog showing up copypaste would do the job just fine but it is a requirementright now i am just posting the contents of the textarea to the server which echos them back with contentthisposition attachment slapped on is there a way to do this with just clientside javascript,"['javascript', 'html']" +9465,convert from enum ordinal to enum type i have the enum type reporttypeenum that get passed between methods in all my classes but i then need to pass this on the url so i use the ordinal method to get the int value after i get it in my other jsp page i need to convert it to back to an reporttypeenum so that i can continue passing it how can i convert ordinal to the reporttypeenumusing java 6 se,['java'] +9477,is there a java implementation of the activerecord pattern that is built on top of hibernate similar to castle windsor i am looking for a java implementationation of the activerecord pattern which is built on top of hibernatein net there is a open source project castle windsor activerecord which implements the activerecord pattern on top of nhibernatei am looking for something like this except sitting on top of the nhiberate persistence frameowork for java,['java'] +9480,validate on text change in textbox i have implemented validation rules on a textbox in my winform and it works well however it checks the validation only when i tab out of the field i would like it to check as soon as anything is entered in the box and everytime the content changes also i would like it to check validation as soon as the winform opens i remember doing this fairly recently by setting some events and whatnot but i cannot seem to remember how,"['c#', '.net']" +9483,when do extension methods break we are currently thiscussing whether extension methods in net are bad or not or under what circumstances extension methods can introduce hard to find bugs or in any other way behave unexpectedlywe came up withwriting an extension method for types that are not under your control eg extending directoryinfo with gettotalsize etc is bad because the owner of the api could introduce a method that hides our extension and might have different edge cases for example testing for null in an extension method will automatically translate into a nullreferenceexception if the extension method is no longer used due to hidingquestionare there any other dangerous situations than hiding that we are not thinking ofeditanother very dangerous situationsuppose you have an extension methodnamespace exampleextensionmethods public static class extension public static int conflictthis testme obj return 1 and use itnamespace exampleextensionmethodsconflicttest testfixture public class conflictextensiontest test public void conflicttest testme me new testme int result meconflict assertthatresult isequalto1 notice that the namespace where you use it is longernow you reference a dll with thisnamespace exampleextensionmethodsconflict public static class conflictextension public static int conflictthis testme obj return 1 and your test will fail it will compile without a compiler error it will simply fail without you even having to specify using exampleextensionmethodsconflict the compiler will walk the namespace name and find exampleextensionmethodsconflictconflictextension before exampleextensionmethodsextension and will use that without ever complaining about ambiguous extension methods oh the horror,"['c#', '.net']" +9485,maximum number of workable tables in sql server and mysql i know that in sql server the maximum number of objects in a database is a little over 2 billion objects contains tables views stored procedures indexes among other things i am not at all worried about going beyond 2 billion objects however what i would like to know is does sql server suffer a performance hit from having a large number of tables does each table you add have a performance hit or is there basically no difference assuming constant amount of data does anybody have any experience working with databases with thousands of tables i am also wondering the same about mysql,['mysql'] +9486,install php 5 without libxml2 i am trying to install a copy of php 5 to my home directory on the school computer the problem is that whenever i try it complains that my copy of libxml2 is too outdated to workis there any way i can install this without upgrading libxml2 since i do not have permission to upgradeany suggestions,['php'] +9490,how can i set autoincrement format to 01 in mysql how can i make mysql auto increment in 4 digit formatso instead of 1 make 01,['mysql'] +9492,continuous integration stack on windows with mercurial mercurial queues weve been using mercurial with mercurial queues guards for patches for source control of a number of windows aspnet projects i am interested in setting up a continuous integration environment for this but am getting lost in conflicting reports of success with cctrac etc i am wondering who else out there is doing this and what your working stack of appsutils is also if youve got hints on workflow i am all ears appreciation in advance,['asp.net'] +9496,sqltransaction has completed i have an application which potentially does thousands of inserts to a sql server 2005 database if an insert fails for any reason foreign key constraint field length etc the application is designed to log the insert error and continueeach insert is independent of the others so transactions are not needed for database integrity however we do wish to use them for the performance gain when i use the transactions well get the following error on about 1 out of every 100 commitsthis sqltransaction has completed it is no longer usable at systemdatasqlclientsqltransactionzombiecheck at systemdatasqlclientsqltransactioncommitto try to track down the cause i put trace statements at every transaction operation so i could ensure the transaction was not being closed before calling commit i have confirmed that my app want closing the transactioni then ran the app again using the exact same input data and it succeedsif i turn the logging off it fails again turn it back on and it succeeds this onoff toggle is done via the appconfig without the need to recompileobviously the act of logging changes the timing and causes it to work this would indicate a threading issue however my app is not multithreadedi have seen one ms kb entry indicating a bug with net 20 framework could cause similar issues however the fix they provided does not solve this issue,['.net'] +9497,java inputstream blocking read according to the java api the inputstreamread is described asif no byte is available because the end of the stream has been reached the value 1 is returned this method blocks until input data is available the end of the stream is detected or an exception is throwni have a whiletrue loop doing a read and i always get 1 when nothings sent over the stream that is expectedmy question is when would read ever block since if it does not get any data it returns 1 i would expect a blocking read to wait until data is received if youve reached the end of the input stream should not read simply wait for data instead of returning 1or does read only block if there is another thread accessing the stream and your read cannot access the stream which leads me to my next question i used to have event listener provided by my library that would notify me when data is available when i was notified i would call whileabyte read 1 store the byte i was puzzled when i would get two events in very close time proximity and not all my data was being thisplayed it seemed like only the tail end of the second events data would be thisplayed and the the rest was missingi eventually changed my code so that when i get an event i would called ifinputstreamavailable 0 whileabyte read 1 store the byte now it worked properly and all my data was thisplayedcan someone explain this behavior the inputstreamavailable is said to return the number of bytes you can read before blocking the next caller of the stream even if i do not use available i would expect the read of the first event to just block the read of the second event but not erase or consume too much stream data why would doing this cause not all of my data to be thisplayed,['java'] +9499,which java oriented lexer parser for simple project antlr diy etc i am working on a small text editor project and want to add basic syntax highlighting for a couple of languages java xmljust to name a few as a learning experience i wanted to add one of the popular or non popular java lexer parserwhat project do you recommend antlr is probably the most well known but it seems pretty complex and heavyhere are the option that i know ofantlrragel yes it can generate java source for processing inputdo it yourself i guess i could write a simple token parser and highlight the source code,['java'] +9504,any way to make xmlserializer output xml in a defined order currently i am using xmlserializer to serialize and deserialize an object the xml is generated in an undefined order which is understandable but makes it annoying when comparing versions of the object since the order of properties is different each time so for instance i cannot use a normal diff tool to see any differencesis there an easy way to generate my xml in the same order every time without writing the readxml and writexml methods myself i have a lot of properties on the class and add new ones every now and again so would prefer to not have to write and then maintain that codec net 20,"['c#', '.net']" +9510,rmi and exceptions i am new to using rmi and i am relatively new to using exceptionsi want to be able to throw an exception over rmi is this possiblei have a simple server which serves up students and i have delete method which if the student does not exist i want to throw a custom exception of studentnotfoundexception which extends remoteexception is this a good thing to doany advice or guidance would be greatly appreciatedserver interface method delete a student on the server param id of the student throws remoteexception throws studentnotfoundexception when a student is not found in the system void removestudentint id throws remoteexception studentnotfoundexceptionserver method implementation overridepublic void removestudentint id throws remoteexception studentnotfoundexceptionstudent student studentlistremoveidif student nullthrow new studentnotfoundexceptionstudent with id id not found in the systemclient method private void removestudentint id throws remoteexceptiontryserverremovestudentidsystemoutprintlnremoved student with id idcatch studentnotfoundexception esystemoutprintlnegetmessagestudentnotfoundexception package studentservercommonimport javarmiremoteexceptionpublic class studentnotfoundexception extends remoteexception private static final long serialversionuid 1l public studentnotfoundexceptionstring message supermessage thank you for your reply i have now managed to fix my problem and realised that extending remoteexception was bad idea,['java'] +9516,wcf how do i get the list of endpoints from servicehost i can add endpoints using servicehostaddserviceendpoint how do i get that list of endpoints back out,['.net'] +9517,do you know of any openssh libraries for windows i would like to incorporate openssh support into a windows application and i am looking for a library preferably net or something easily integrated into net that can provide this functionality i am more interested in ssh client software than server software but both functions would be even better edit i would prefer a free and open source solution,['.net'] +9521,how do i contest an iphone app store review i have an application in the app store i have submitted 3 updates to the app 2 of those 3 updates have been rejected based on something that has not changed at all since the original submission i recognize that they have a different person each time review my applicationhowever the net effect ishow do i effectively contest a review i have replied to the review response email each time and never once received a response if i did not have customers who expect bugfixes and updates i would just resubmit asis and expect a different revieweris there any phone number or other way to actually talk to a human about this the most recent rejection was based on infringing on apples trademarks which was ludicrous,['iphone'] +9527,how to put the build date of application somewhere in the application i would like to put the date the application was built somewhere in the application say the about box any ideas how this can be done i need to do this for c but i am also looking for a general idea so you can answer this for any specific language other than c,['c#'] +9533,backgroundworker abort i recently tried to use backgroundworker instead of classic threads and i am realizing that it is causing at least for me more problems than solutionsi have a backgroundworker running a synchronous read in this case from serialport and getting blocked around 30 seconds in 1 code line then cancellationpending is not the solution i am seeing that if the application gets closed at this point either with the cross button and applicationexit the process keeps zombie forever i need a way to force abort or to kill the backgroundworker thread,['c#'] +9539,access timezoneinfo from sql 2005 server the net timezoneinfo class is great and i thought it would answer all my issues with recording data from multiple time zones in my sql 2005 databaseto convert a utc datetime in the database to any other time zone i would just get the time zone into a timezoneinfo class using timezoneinfofindsystemtimezonebyid and then call the timezoneinfoconverttimefromutc brilliant i would just call this from the sql net clrbuttimezoneinfo has a host protection attribute of mayleakonabortwhen i use vs 2008 to create an sql function or stored procedure i cannot even see the systemtimezoneinfo class nevermind use it i am assuming also that even if i could somehow reference the timezoneinfo class i would probably get some sort of security exception if i tried to register the assembly in sql sever 2005help is there any way to access timezoneinfo class and all its riches from sql server 2005nb i have just added this caveat after the first answerwe have sites at different locations around the world we need to store local time and utc time in the database against events which may require trending at site level a trend may consist of over 520 data points over a year so for efficiency i cannot just store times in utc in the db and convert every datapoint on the client thus i need the ability within the db to convert a local time in any timezone to and from utc time,"['asp.net', 'sql']" +9551,writing a minilanguage i have an application that needs to allow users to write expressions similar to excelh1 d1 c3 i8and more complex things like ifh1 true d3 2 d3 5i can only do so much with regular expressions any suggestions as to the right approach to doing this as well as any resources i can learn from would be much appreciatedthanks,['.net'] +9553,should i learn python after c im currently studying c and want to learn another languagefor work i use c asp just started learning it actually but i want something less microsoft and powerfuli have heard python is a popular and powerful language not so complicated as c but many people mentioned it was hard for them to get back to cjava from python because they started thinking in it get used to absence of memory management etcwhat do you recommend,"['c++', 'python']" +9562,retrieving the calling method name from within a method possible duplicatehow can i find the method that called the current method i have a method in an object that is called from a number of places within the object is there a quick and easy way to get the name of the method that called this popular methodpseudo code examplepublic main popularmethodpublic buttonclickobject sender eventargs e popularmethodpublic button2clickobject sender eventargs e popularmethodpublic void popularmethod get calling method namewithin popularmethod i would like to see the value of main if it was called from main i would like to see buttonclick if popularmethod was called from buttonclicki was looking at the systemreflectionmethodbasegetcurrentmethod but that would not get me the calling method i have looked at the stacktrace class but i really did not relish running an entire stack trace every time that method is called,['c#'] +9563,how do i access a control in the headertemplate of my gridview i want to have a dropdownlist in the header of my gridview in my codebehind i cannot seem to access it here is the headertemplateasptemplatefield sortexpressionexception type headertemplate asplabel idtypeid runatserver texttype asplabel aspdropdownlist idtypefilter runatserver autopostbacktrue aspdropdownlist headertemplate asptemplatefieldand here is the section in the code behind where i am trying to access the control typefilterprotected void objectdatasource1 selectedobject sender objectdatasourcestatuseventargs e datatable dt datatableereturnvalue int numberofrows dtrowscount totalcounttext numberofrowstostring dataview dv new dataviewdt datatable types dvtotabletrue new string exception type dropdownlist typefilter dropdownlistgridview1findcontroltypefilter typefilterdatasource types typefilterdatabindyou will notice that i am trying to use findcontrol to get a reference to the dropdownlist control this call returns null instead of returning the control how do i get access to the control,"['c#', 'asp.net']" +9568,reset scroll position after async postback aspnet what is the best way to reset the scroll position to the top of page after the an asynchronous postback the asynchronous postback is initiated from a aspnet gridview commandfield column and the aspnet update panel update method is called in the gridview onrowcommandmy current application is an aspnet 35 web site edit i have received excellent feedback from everyone and i ended using the pagerequestmanager method in a script tag but my next question ishow do i configure it to only execute when the user clicks the aspnet commandfield in my gridview control i have other buttons on the page that perform an asynchronous postback that i do not want to scroll to the top of the pageedit 1 i have developed a solution where i do not need to use the pagerequestmanager see my follow up answer for solution,"['c#', 'asp.net']" +9570,making a css footer either sit at the bottom of the browser window or bottom of content duplicate of this questioni have got an existing site jacquelinewhitecouk on it there is a footer currently this footer always sits underneath the main content i am trying to make it float to the bottom of the browser window or if the content is bigger than the window stay at the bottom of the contenteffectively the html is structured like thisdiv idcontainer div idtop bar divdiv idheaderdivdiv idleft menudivdiv idright contentdivdiv classcleardiv footer area div idfooterdiv end footer area divi have tried absolute position bottom 0 which puts the footer at the bottom of the window but if the content of the window is bigger then the footer covers the contenthow should i fix this,['css'] +9571,multiple inheritance virtual function mess i have a diamond multiple inheritance scenario like this a b c dthe common parent a defines a virtual function fnis it possible for both b and c to define fnif it is then the next question is can d access both b and cs fn without thisambiguation i am assuming there is some syntax for thisand is it possible for d to do that without knowing specifically who are b and c b and c can be replaces by some other classes and i want the code in d to be genericwhat i am trying to do is to have d somehow enumerate all of the instances of fn it has in its ancestry is this possible in some other means that virtual functions,['c++'] +9576,windows chooses wrong icon from multiicon file and self renders to correct size i have an ico file with 5 icon sizes embedded in it being used as the main application icon and the system tray iconwhen it shows up in the task bar the icon is using the 16x16 format which is desiredwhen the icon shows up in the notification areasystem tray it is using the 32x32 format and windows is rendering it down to a 16x16 icon which looks horriblehow do i force windows to use the 16x16 icon size in the notification areaheres my code to put the icon in the system traycontextmenu cmnotify new contextmenumenuitem minotify new menuitempropertiesresourcesnotify textminotifydefaultitem trueminotifyclick new eventhandlernotifyhandlercmnotifymenuitemsaddminotifynotifyicon new notifyiconnotifyiconicon thisiconnotifyiconvisible truenotifyiconcontextmenu cmnotifynotifyicontext appconstantsapplication name,['.net'] +9588,export orders from magento for shipment i am working on an online store on the magento platform and have hit a major roadblock for some reason i cannot figure out how to export current orders with shipping informationshipment typeetc does anyone have any suggestions this seems as if it should be one of the most basic things for a system like this to do but i have not been able to find out how thank you in advance for your helpandy,['php'] +9591,installing plruby for postgresql 83 this is to enable the development of postgres functions with embedded ruby codebut i have been unable to build itas advised byi am trying to build the needed plrubyso from the latest version plruby053targz provided at i have sorted out where my local postgres set up is and adjusted the invocation toruby extconfrb withpgsqlincludeusrpostgresql834includeserver enableshared thisableconversion withpgsqlversion83i have tried quite number of variations on that but it does not seem to be able to successfully makethe conftestc fileit says thischecking for catalogpg proch yes extconfrb failed could not create makefile due to some reason probably lack ofnecessary libraries andor headers check the mkmflog file for moredetails you may need configuration optionsand here is what i end up with in my mkmflog have header checking for catalogpg proch yesgcc e i iusrlibruby18x86 64linux i iusrpostgresql834includeserver g o2 fpic conftestc o conftestichecked program was begin 1 include catalogpg proch end when i run the gcc line manually it says there is no conftestc and there is not butit is supposed to be generateduname a giveslinux vdev1 26188xen 2 smp thu may 8 115229 pdt 2008 x86 64 x86 64 x86 64 gnulinuxruby v givesruby 186 20080811 patchlevel 287 x86 64linuxany help andor advice would be appreciated mike berrow,['ruby'] +9594,what ide has the strongest support for symfony framework i am looking for an ide with use with the symfony frameworki have a bit of experience using the netbeans 65 ide but it does not always seem to complete the class methods plus it does not seem to have any php code snippets built inhere are the features i would ideally like to have in order of importance from an idecode completion of all the symfony and propel class methods i can never remember themcode templatesclass skeletons html structures symfony templatesstraightforward code debuggingsource control,['php'] +9607,how to handle general exceptions in aspnet mvc i want to transfer all unhandled exceptions to an error page in aspnet mvc what is the way to handle the unhandled exceptions in aspnet mvc is there anything like application error,['c#'] +9617,enable aspnet asmx web service for http post get requests i would like to enable a aspnet classic asmx web service for http post and get requests i realise this can be done on a machine or application level by adding webservices protocols add namehttpget add namehttppost protocolswebservices to the machineconfig or webconfig my question is can http post and get requests be enabled per web service or web method level rather than per application or machinemy web service is written in c using net 35sp1,['asp.net'] +9620,python metaclasses i have been hacking classes in python like thisdef hackfaclass class myclassaclass def fself f return myclassa hackafuncawhich looks pretty clean to me it takes a class a creates a new class derived from it that has an extra method calling f and then reassigns the new class to ahow does this differ from metaclass hacking in python what are the advantages of using a metaclass over this,['python'] +9624,deserializing chrome bookmark json data in c in response to a question i asked a few days ago i am attempting to stretch myself a little and do something that i have not really focussed on much before i have done some searching both here and in general but cannot find the answers or even reasonable hints to what i want to achieve though a few things come closeishbasically i am trying to deserialize the data for the google chrome bookmarks file using the jsonnet library though if there is a better alternative i am all for that the documentation for this library is a little confusing in places i am a little confused as to the next step to take due primarily to being used to phps fantastic handling of json data using json decode allowing for a single function call and then simple associativearray accessthe library jsonnet wants me to specify an object type that it can deserialize the json data into but i am not really sure how to go about structuring such an object given the format of the bookmarks file itself the format is something along the lines of roots bookmark bar children children date added 12880758517186875 name example url type url url date added 12880290253039500 name another url type url url date added 12880772259603750 date modified 12880772452901500 name sample folder type folder date added 128808238263250 name jsonnet type url url date added 0 date modified 12880823831234250 name bookmarks bar type folder other children date added 0 date modified 0 name other bookmarks type folder version 1now in php i would be far more used to doing something along the lines of the following to get the data i wanted and ending up with jsonnetdatarootsbookmark barchildren0namei can work out simply enough what objects to create to represent the data something like a root object then a bookmark list object and finally an individual bookmark object but i am really not sure as to how to implement them and then get the library to deserialize into the relevant objects correctlyany advice that can be offered would be greatly appreciated,"['c#', '.net']" +9628,net inserting null values into sql server database from variable values there have been similar questions but the answers werent what i was looking for i want to insert the a value of null into the sql server database if the reference is null or a value has not yet been assigned at the moment i am testing for null and it looks likestring teststring nullif teststring null commandparametersaddparameternew sqlparametercolumn dbnullvalueelse commandparametersaddparameternew sqlparametercolumn teststringthis looks and feels incredibly clumsy to me i have quite a few values that i am inserting into a database and to test them all like the above is very verbose does net not handle this in some way i thought maybe if i used string as opposed to string but that also does not appear to work looking around i found articles which talk about using nullable typessystemnullablet variablethis seems to work for primitives int char double and bool so that might work for those but what about strings am i missing something here what types should i be using for primitive values and for string values so that i do not have to repeatedly test values before inserting themeditbefore i get too many answers about ternary operators i like them but not in this context it does not make sense for me to need to test that value and have all that extra logic when that sort of thing could have been inplemented lower down in the net framework and if i knew what types to give then it would get it for freditokay so guys help me formulate my plan of attack i will use the nullable for my primitives int double etc and for my strings i will use the string but the test this keeps things less verbose is there anything that i am missing here like maybe losing some semantics,['.net'] +9637,whats the most efficient test of whether a php string ends with another string the standard php way to test whether a string str ends with a substring test isendswith substr str strlen test testis this the fastest way,['php'] +9639,rails i cannot call a function in a module in lib what am i doing wrong i know i am doing something stupid or failing to do something intelligent i am frequently guilty of bothheres an example of whats causing me paini have a module saved in lib as test functionsrb that looks like thismodule testfunctions def abc puts 123 endendgoing into ruby scriptrunner i can see that the module is loading automatically good ol convention over configuration and all that testfunctionsinstance methods abcso the method is known let us try calling it testfunctionsabcnomethoderror undefined method abc for testfunctionsmodule from irb3nope how about this testfunctionsabcnomethoderror undefined method abc for testfunctionsmodule from irb4testnope againdefinedtestfunctionsabc nil buttestfunctionsmethod defined abc truelike i said at the top i know i am being dumb can anyone dedumb me,"['ruby-on-rails', 'ruby']" +9647,can i use entity framework with aspnet membership i am creating really recreating an app that has existing user and other data in msaccess databases the data will be moved to sql server and part of that involves migrating users i want to use ef to do orm and i am pretty sure i know what the data model will be in sql server i am new to ef but not to aspnet and i would like to take advantage of the membership features in aspnet i am thinking about several ways to do this and would like some advice i have done only a little research about this idea thus far maybe it is been answered elsewhere so here goes a cluster of related questionscan ef work with directly with aspnet membership through some class or namespace that i am not aware ofif i transition users to the membership system to align their userids with data in other tables should i create another set of tables for user data atop the aspnet tables a la dotnetnukei want to avoid a situation where i use the builtin membership functions for only user authentication and switch over to ef context when i am working with usertagged data seems clumsy to withdraw user info to bind to a column in a gridview by going into a membership user for every row but maybe that is whats needed do i need to suck it up and replicate the membership classes in ef for data retrieval purposesi was thinking of maybe implementing some kind of ef provider for membership on the idea that maybe then the provider could sit inside the overall ef data model is this crazy talk i have never written my own provider beforefeel free to tell me i am not making any sense,"['asp.net', '.net']" +9654,sqlalchemy obtain primary key with autoincrement before commit when i have created a table with an autoincrementing primary key is there a way to obtain what the primary key would be that is do something like reserve the primary key without actually committingi would like to place two operations inside a transaction however one of the operations will depend on what primary key was assigned in the previous operation,"['python', 'sql']" +9662,null pointer with boostshared ptr whats the equivalent to the followingstdvectorfoo vecvecpush backnullwhen dealing with boostshared ptr is it the following codestdvector boostshared ptrfoo vecvecpush backboostshared ptrfoonote i may push back a lot of such objects should i declare a global static nullptr object somewhere that way only one of them would have to be constructedboostshared ptrfoo nullptr,['c++'] +9664,checkboxes on rails whats the correct way of making checkboxes that are related to a certain question in ruby on rails at the moment i havediv classform row label forfeaturesfeatureslabel br check box tag features scenarios scenarios br check box tag features role profiles role profiles br check box tag features private messages private messages br check box tag features chatrooms chatrooms br check box tag features forums forums br check box tag features news news br check box tag features polls pollsdivi also want to be able to automatically check the previously selected items if this form was reloaded how would i load the params into the default value of these,['ruby-on-rails'] +9667,calling aspnet web service from c application i have a question how can i invoke a web service and get the result from a c desktop application i am making a desktop app and i want it to be able to connect to my online aspnet web services how is this possible,"['c#', 'asp.net']" +9673,what is the purpose of remove unused references i have read that removing unused references makes no difference to the compiler as it ignores assemblies that are not being referenced in the code itselfbut i find it hard to believe because then what is the real purpose of removing unused references it does not have any noticeable effect on the size of the generated assembly or otherwise or is this smart behaviour limited to the c compiler cscexe and not inherent to vbcexeif this functionality is so useless why does resharper offer it as a feature why is it provided within the visual studio project configuration dialogthe only activity i can think of where this would be useful is during deployment references used or unused would still be copied by the installer but for assemblies that reside in the gac for instance bcl assemblies this would not be a problem either,['.net'] +9684,net remoting vs wcf i am working on a net website which is going to have 10s of concurrent usersi am thinking of keeping the business components on the app server and ui components on the web server database ms sql server 2005 will be hosted on another server i am planning to use the load balancing as wellgiven this whats the best way of communication from web server to app server if i want to have the optimum application performance and scalability,['c#'] +9694,why would pthread create fail with only 2 threads active i am having some trouble in my first foray into threads in c i am trying for now to write a very simple server program that accepts a socket connection and starts a new thread to process it it seems to work fine except that it will only create about 300 threads 303 sometimes 304 before pthread create fails with the eagain code which meansthe system lacked the necessary resources to create another thread or the systemimposed limit on the total number of threads in a process pthread threads max would be exceededthis is not 303 threads at the same time each thread exits which is confirmed by gdb each time the process request function is called there are two threads runningso it means the system lacked the necessary resources my question is and it may be a bit stupid what are these resources presumably it is a memory leak in my program certainly possible likely even but i would have thought that even so it could manage more than 300 considering the rest of the program does very littlehow can i find out how much memory my program has available to confirm that it is running out of it there is plenty of memory and swap free so presumably there is an artificial limit imposed by the os linuxthanks,['c'] +9695,c hashes i am new to chow do i hash files with cwhat is available md5 crc sha1 etcis there an interface i should inheritbasically i want to checksum multiple files and store it in a db along with using two of my own checksumshashes,['c#'] +9698,c development on linux where do i start i decided to leave my windows install behind and am now running debian as my default os i have always coded in windows and specifically with visual studio i am currently trying to get used to compiling my code under linuxalthough i still have a lot of documentation to read and do not expect you guys to make it too easy for me it would still be nice to get some pointers on where to start i have some specific questions but feel free to suggestrecommend anything else regarding the subjectwhat are recommended guides on creating a make file how do i compile from this makefile do i call g myself do i use makelooking at other linux software they almost always seem to have a configure file what exactly does it do does it only check if the required libraries are installed or does it more than just checking requirementshow do i link libraries and how does this relate to my makefile or g parameters in windows i would compile the library include some header files tell my linker what additional lib file to link and copy a dll file how exactly does this process work in linuxrecommendations for code editors i am currently using nano and i have heard of vim and emacs but do not know what the benefits of them are over eachother are there any others and why would i consider them over any of the previous three note i am not looking for an ideany help links to guides documentation preferably those that are aimed at beginners are very much appreciated,['c++'] +9703,why cannot i directly add attributes to any python object i have this code class g def init self selfx 20 gg g ggx20 ggy 20and this code from datetime import datetime my obj datetimenow my objinteresting 1 attributeerror datetimedatetime object has no attribute interestingfrom my python knowledge i would say that datetime overrides setattrgetattr but i am not sure could you shed some light hereedit i am not specifically interested in datetime i was wondering about objects in general,['python'] +9713,is it possible to speed up a recursive file scan in php i have been trying to replicate gnu find find in php but it seems impossible to get even close to its speed the php implementations use at least twice the time of find are there faster ways of doing this with phpedit i added a code example using the spl implementation its performance is equal to the iterative approachedit2 when calling find from php it was actually slower than the native php implementation i guess i should be satisfied with what i have got measured to 317 of gnu finds speed when run directly from a shellfunction list recursivedir if dh opendirdir while false entry readdirdh if entry entry continue path direntry echo pathn if is dirpath list recursivepath closedird measured to 315 of gnu finds speed when run directly from a shellfunction list iterativefrom dirs arrayfrom while null dir array popdirs if dh opendirdir while false entry readdirdh if entry entry continue path direntry echo pathn if is dirpath dirs path closedirdh measured to 315 of gnu finds speed when run directly from a shellfunction list recursivedirectoryiteratorpath it new recursivedirectoryiteratorpath foreach it as file if fileisdot continue echo filegetpathname measured to 390 of gnu finds speed when run directly from a shellfunction list gnufinddir dir escapeshellcmddir h popenusrbinfind dir r while s freadh 2048 echo s pcloseh,['php'] +9716,how do i read write gzipped files how do i read write gzipped files in cthe iostream wrapper classes here look good and here is a simple usage examplegzigzstream infilenamestdstring linewhilestdgetlinein line stdcout line stdendlbut i was not able to actually link it although i have a usrliblibza a simpleg testgzstreamcpp lzdid not do it undefined reference to gzgzstreambasegzstreambase,['c++'] +9717,how to reuse an ostringstream i would like to clear out and reuse an ostringstream and the underlying buffer so that my app does not have to do as many allocations how do i reset the object to its initial state,['c++'] +9722,tracking unthisposed thisposable objects is there a tool that can scan your code and determine which objects that implement ithisposable are not being thisposed in a code base at compile time or runtimei have possible areas in the code that are not thisposing objects but it is hard to look back and see which objects require this in the first place,['.net'] +9737,does malloc allocate a contiguous block of memory i have a piece of code written by a very old school programmer it goes something like this typedef struct ts request ts request buffer header def header char package1 ts request def ts request buffer def request buffer mallocsizeofts request def 2 1024 1024the programmer basically is working on a buffer overflow concept i know the code looks dodgy so my questions aredoes malloc always allocate contiguous block of memory because in this code if the blocks are not contiguous the code will fail big time doing freerequest buffer will it free all the bytes allocated by malloc ie sizeofts request def 2 1024 1024or only the bytes of the size of the structure sizeofts request def do you see any evident problems with this approach i need to thiscuss this with my boss and would like to point out any loopholes with this approach,['c'] +9741,what is the fastest way to read a large number of small files into memory i need to read 50 files on every server start and place each text files representation into memory each text file will have its own string which is the best type to use for the string holderwhat is the fastest way to read the files into memory and what is the best data structuretype to hold the text in so that i can manipulate it in memory search and replace mainlythanks,['java'] +9751,jquery popup bubbletooltip i am trying to make a bubble that can popup when the onmouseover event is fired and will stay open as long as the mouse is over the item that threw the onmouseover event or if the mouse is moved into the bubble my bubble will need to have all manners of html and styling including hyperlinks images etci have basically accomplished this by writing about 200 lines of ugly javascript but i would really like to find a nice jquery plugin to clean this up a bit i did some searching and could not find anything to suit my fancydoes anyone know of a good jquery plugin for doing fancy bubbles please let me know if you have any questions or need more information and i would be happy add more,"['javascript', 'jquery', 'html', 'css']" +9771,sql help conditional where clause based on a bit variable sql server i need help writing a conditional where clause here is my situationi have a bit value that determines what rows to return in a select statement if the value is true i need to return rows where the import id column is not null if false then i want the rows where the import id column is nullmy attempt at such a query below does not seem to work what is the best way to accomplish thisdeclare imported bitselect id import id name from foo where imported 1 and import id is not null and imported 0 and import is is nullthanks,['sql'] +9774,how to run a netbeans project in command prompt my professor asked us to create a java program that would be able to run in command prompt but could also be opened using netbeansthe program is about using the different types of sorting specifically selection insertion exchange quick and heap sorting our professor specifically told us to use object oriented programming in java and that she wants to see a main class plus the different classes that would do the sortingi tried to write the program in netbeans a thinking that later i could simply run the program in cmd using javacin cmd i typed the path where my netbeans project was saved and i tried to compile the files using javac but it says that javac is not recognized as an internal or external command operable program or batch fileso i tried to save the files in sunsdkjdkbin and from there i tried to compile the files and it was fine the problem sets in when i tried to run themheres how i tried to compile the filesjavac mainjava sortchoicejava selectionjava selectionsortjava insertionjava insertionsortjava exchangejava exchangesortjavai havent finished the syntax for the next two sortingheres how i tried to run the files in cmdjava main sortchoice selection selectionsort insertion insertionsort exchange exchangesortand cmd saysexception in thread main javalangnoclassdeffounderror main wring name myjavamainat javalangclassloaderdefineclass1nativ methodat javalangclassloaderdefineclassclasslat javasecuritysecureclassloaderdefineclat javaneturlclassloaderdefineclassurlcat javaneturlclassloaderaccess0urlclat javaneturlclassloader1runurlclassloat javasecurityaccesscontrollerdoprivile methodat javaneturlclassloaderfindclassurlclaat javalangclassloaderloadclassclassloaat sunmisclauncherappclassloaderloadclaat javalangclasloaderloadclassclassloadat javalangclassloaderloadclassinternalwhat should i do sorry for my kilometriclong explanation i just wanted to put in as many details as possiblei would also like to emphasize that i am just a beginner in java programming,['java'] +9805,can i stop 100 width text boxes from extending beyond their containers lets say i have a text box that i want to fill a whole line i would give it a style like thisinputwide thisplayblock width 100this causes problems because the width is based on the content of the text box text boxes have margin borders padding by default which makes a 100 width text box larger than its containerfor example here on the rightis there any way to make a text box fill the width of its container without expanding beyond ithere is some example html to show what i meandoctype html public w3cdtd xhtml 10 transitionalen html xmlns head titleuntitled pagetitle style typetextcss outerborder 1px solid 0 width 320px margin 0pxpadding0px innermargin 20px padding 20px background 9border 1px solid 0 inputwide thisplayblock margin 0px inputnormal thisplayblock float right styleheadbody div idouter div idinner input typetext classwide input typetext classnormal div styleclearbothdiv div divbodyhtmlif this is run you can see by looking at the normal text box that the wide text box is sticking out beyond the container the normal text box floats to the actual edge of the container i am trying to make the wide text box fill its container without expanding beyond edge like the normal text box is,"['html', 'css']" +9806,jsf tuning running into an issue where jsf is filling up our sessions we had a system crash the other day sent the heap to ibm for review and found that we had some sessions as large as 50m they found jsf components in the session and some very large so is there any tuning that can be done configuration items to look at or other directionour system is build using jsf and spring for the presentation layer the back end is ejb spring and hibernate all running on websphere 61,['java'] +9809,have a good hash function for a c hash table i am in need of a performanceoriented hash function implementation in c for a hash table that i will be coding i looked around already and only found questions asking whats a good hash function in general i have considered crc32 but where to find good implementation and a few cryptography algorithms my table though has very specific requirementsheres what the table will be like10 items max20 capacity so the load is 05hashing a 6character string which is a part of english sentence examples become and he not the number one priority of my hash table is quick search retrieval quick insertion is not important but it will come along with quick search deletion is not important and rehashing is not something i will be looking into to handle collisions i will be probably using separate chaining as described here i have already looked at this article but would like an opinion of those who have handled such task before,['c++'] +9832,what does mean in c came across the following line in the composite application guidelinesi know the is a lambda but what does the meanwhat are some other examples of thiswhat is it called so i can search for itthisregionviewregistryregisterviewwithregionregionnamesselectionregion thiscontainerresolveemployeeslistpresenterview,['c#'] +9837,configuring windows dns resolver cache note that i am talking about the client dns resolver cache this message is not concerned with the windows dns serveri have a c program that does a lot of dns resolutions because the httpwebrequest component would not let me change the host header i cannot create my own internal dns cache so i have to depend on the windows dns cache which does not appear amenable to changethere is a reasonably good technet article about the dns cache registry settings in windows server 2003 but i have not been able to prove that setting them does anything all the other pages i found through a google search either reference that page or paraphrase it sometimes incorrectlywindows ipconfig command has a thisplaydns switch that will output the contents of the cache to my knowledge that is the only way to determine the size of the dns cache in my experiments on a 32 bit windows xp box with 2 gb of memory no matter what i set the dns cache registry values to i always end up with between 30 and 40 items in the cacheeven after doing thousands of dns resolutions on my 64bit windows 2008 machine with 16 gb of memory i always get between 270 and 300 items in the cachei am stumped i do not know what the answer is but i figure one of the following is the caseit is not possible to change the size of the dns resolver cacheit is possible but the documentation is wrongthe documentation is correct as far as it goes but itas incompletethe documentation is correct and complete but iam too dumb to make sense of itthe documented registry entries actually changed the size of the cache but ipconfig isnat showing me all the entries that are in the cache can anybody tell me if it is possible to configure the size of the dns resolver cache in windows xp vista or server 2008,"['c#', '.net']" +9840,net httpcookie class session cookie questions i am interested on how to make a regular httpcookie object into a cookie that expires at the end of a session i am not interested in someone showing me httpcontextsession how does a session cookie look in the response headers compared to a normal cookie how can i modify a httpcookie to expire at the end of a session thanks,['.net'] +9841,store pointers to member function in the map i would like to map string to an instance member functions and store each mapping in the mapwhat is the clean way of doing something like thatclass myclass virtual double getx virtual double getsomethingelse virtual double gett virtual double getrr class processor private typedef double myclassmemfuncgetter static mapstdstring memfuncgetter descrtofuncmap public static void initialize void processmyclass m stringvoid processorinitialize descrtofuncmapxmyclassgetx descrtofuncmapsomethingelsemyclassgetsomethingelse descrtofuncmaprrmyclassgetrr descrtofuncmaptmyclassgettvoid processorprocessmyclass ms const stdstring key mapstdstring getteriterator founddescrtofuncmapfindkey iffounddescrtofuncmapend memfuncgetter memfuncfoundsecond double dresultmsmemfunc stdcoutcommandkey and resultresultstdend let me know if you see a problem with this approach and what are common idioms for thatperhaps i should use ifelseif statement chain given that i have a limited number of member functions instead of a confusing map of func pointersbtw i found some of the useful info here in the cfaqlite,['c++'] +9842,pure virtual destructor in c is it wrong to writeclass a public virtual a 0for an abstract base classat least that compiles in msvc will it crash at run time,['c++'] +9856,looking for a command line argument parser for net i am looking for a command line argument parser such as command line parser from features i am looking forautogeneration of usageshould able to check required and optional parametersparameters should support ienumerable with separator supportshould support flag parameterswould be nice to support combining parameters such as fx f xwould be nice to not force for a space after a parameter such as ftesttxt f testtxtps command line parser is quite good i really like the design of it but there is no documentation no new updates and i could not figure out to do certain stuff such as how to check for required parameters,"['c#', '.net']" +9869,apply css style to child elements i want to apply styles only to the table inside the div with a particular classnote i would rather use a cselector for children elementswhy does the 1 works and 2 doesnt1divtest th divtest td divtest caption padding40px 100px 40px 50px2divtest th td caption padding40px 100px 40px 50pxhtml html head style divtest th td caption padding40px 100px 40px 50px style head body div table border2 trtdsometdtr trtddatatdtr trtdheretdtr table div div classtest table border2 trtdsometdtr trtddatatdtr trtdheretdtr table div bodyhtmlwhat am i doing wrong,['css'] +9871,webbased resx file editor i am working on a sharepoint site and the site eventually needs to be localized to many different languages we can use resource files but wed like for the translators to be able to update those files while the site is live without requiring developer assistance to recompile redeploy etcto me i think the easiest way to do this would be to provide a web application to edit the resx files as they sit in the app globalresources directory does anyone know of some sort of a webbased resx editor like that i found one from lavablast but it thisplays the values for all languages at once with the number of languages we plan on having i think that would eventually get unwieldyany suggestions are appreciated,['asp.net'] +9877,flipping uiviews from top bottom i am well aware that there are only two available uiview transitions uiviewanimationtransitionflipfromleft and uiviewanimationtransitionflipfromright i am wondering if there is anyway that i can implement emulate a uiviewanimationtransitionflipfromtop or uiviewanimationtransitionflipfrombottomthe only way i can think to do this is by flipping the x axis with the y axis but i have not seen any information about how to do this just setting the coordinates of each axis would not fix the issue as the xaxis till remains the xaxis does anyone have any ideas how this can be accomplished,['iphone'] +9879,cast received object to a list or ienumerable i am trying to perform the following cast private void mymethodobject myobject ifmyobject is ienumerable listobject collection listobjectmyobject do something else do something but i always end up with the following excepction unable to cast object of type systemcollectionsgenericlist1myspecifictype to type systemcollectionsgenericlist1systemobject i really need this to work because this method needs to be very generic to receive single objects and collections both of unspecified types is this possible or is there another way of accomplishing this thank you,"['c#', '.net']" +9889,c enums and casting if you declare an enum in c the default type is automatically intso then why in a case statement or other instances when using the enum do you have to explicitly recast in order to use the values whats the point of having an underlying type if you have to explicitely case or am i just doing something wrong hereprivate enum myenum value1 value2 value3 switch somevalue case intmyenumvalue1 someothervar ss break case intmyenumvalue2 someothervar yy break case intmyenumvalue3 someothervar gg break,['c#'] +9895,selenium click event seems not to be always triggered results in timeout heres what i doseleniumclicklinkmylinkseleniumwaitforpagetoload60 do something then navigate to a different page window focus is never changed inbetweenseleniumclicklinkmylinkseleniumwaitforpagetoload60the link mylink does exist the first invocation of click always works but the second click sometimes seems to work sometimes notit looks like the click event is not triggered at all because the page does not even start to load unfortunately this behaviour is underterministicheres what i already triedset longer time timeout did not helpwait for an element present after loading one page does not work either since the page does not even start to loadfor now i ended up invoking click twice soseleniumclicklinkmylinkseleniumwaitforpagetoload60 do something then navigate to a different page window focus is never changed inbetweenseleniumclicklinkmylinkseleniumclicklinkmylinkseleniumwaitforpagetoload60that will work but it is not a really nice solution i have also seen in another forum where someone suggested to write something like a clickandwaitwithretry try superclicklinkmylink superwaitforpagetoload60 catch seleniumexception e superclicklinkmylink superwaitforpagetoload60 but i think that is also not a proper solutionany ideasexplanations why the click event is sometimes not triggered,['java'] +9898,what is the best implementation for aop in net there is a lot of aop implementation in c vbnet this is some of aop implementations postsharp loomnetaspectnetenterprise library 30 policy injection application blockaspectdngdotspect spectthe springnet framework as part of its functionalitywicca and phxmorphan exhaustive analysis on aosd solutions for net is available from twente universityseasarnetaspectpuzzlenaspectcomposesetpointwhat is the best implementation for aop in net what i should use,['.net'] +9899,converting html files to pdf i need to automatically generate a pdf file from an exisiting xhtmldocument the input files reports use a rather simple tablebased layout so support for really fancy javascriptcss stuff is probably not neededas i am used to working in java a solution that can easily be used in a javaproject is preferable it only needs to work on windows systems thoughone way to do it that is feasable but does not produce good quality output at least out of the box is using css2xslfo and apache fop to create the pdf files the problem i encountered was that while cssattributes are converted nicely the tablelayout is pretty messed up with text flowing out of the table celli also took a quick look at jrex a javaapi for using the gecko rendering engine is there maybe a way to grab the rendered page from the internet explorer rendering engine and send it to a pdfprinter tool automatically i have no experience in ole programming in windows so i have no clue whats possible and what is notdo you have an ideaedit the flyingsauceritext thing looks very promising i will try to go with thatthanks for all the answers,"['java', 'html']" +9913,get current methodbase through reflection can i get the current methods methodinfo somehow,"['c#', '.net']" +9918,cpu load from java is there a way to get the current cpu load under java without using the jni,['java'] +9933,selecting all empty text fields in jquery how can i find all text fields that have an empty valuetextvaluegives a javascript errori know i can do text iterate through and return all fields with thisvali am looking for a cleaner method and using jquery 131it has to work if the element originally had a value when the page was loaded and then the user cleared it elemattrvalue gives the original value in that place though val works properly,['jquery'] +9937,append an xml document to an xml node in c how can i append an xml document to an xml node in c,['c#'] +9941,gckeepalive versus using in his article about preventing multiple instances of an application michael covington presents this codestatic void main args are ok here of course bool ok m new systemthreadingmutextrue yournamehere out ok if ok messageboxshowanother instance is already running return applicationrunnew form1 or whatever was there gckeepalivem importanthe explains that the gckeepalivem is required to prevent the garbage collector from collecting the mutex early since there are no additional references to itmy question will wrapping the mutex in a using do the same thing that is will the following also prevent the gc from pulling the rug out from under mestatic void main args are ok here of course bool ok using var m new systemthreadingmutextrue yournamehere out ok if ok messageboxshowanother instance is already running return applicationrunnew form1 or whatever was there my gut reaction is that the using will work since using is supposed to be equivalent tomutex m new systemthreadingmutextrue yournamehere out oktry do stuff herefinally mcloseand i would think that the mclose there would be enough to signal to the jit compiler that there is another reference thus preventing premature garbage collection,['c#'] +9949,why does glibc timezone global not agree with system time on dst i am experiencing a bizarre issue where my system clock knows that it is daylight savings time but glibc seems not to this is an uptodate ubuntu installation and i have checked etclocaltime and it has the correct changeover time for last weeks switch to dstthe current correct timezone for me is pacific daylight time utc7 when i ask my system what time zone i am in it tells me correctly date z0700but when i run the following programinclude timehinclude stdiohint main tzset printflun timezone return 0the output is incorrectly28800which corresponds to utc8 or pacific standard time and no tz is not set in my environmenti thought glibc and the date program would get their time zone information from the same source but apparently either they do not or i am misunderstanding how the glibc timezone global worksthe basic questions are thenwhy are these two outputs differenthow can i reliably detect the system utc offset from a c program,['c'] +9962,java componentshow hide are deprecated why anyone know the reason just curious,['java'] +9964,is there any java equivalent of phps http build query function i have a map with my data and want to build a query string with it just like i would with http build query on php i am not sure if this code is the best implementation of it or if i am forgetting somethingpublic string toquerystringmap data throws unsupportedencodingexception stringbuffer querystring new stringbuffer for entry pair dataentryset querystringappend urlencoderencode string pairgetkey utf8 querystringappend urlencoderencode string pairgetvalue utf8 if querystringlength 0 querystringdeletecharat querystringlength 1 return querystringtostring,"['java', 'php']" +9968,best ui library to use with jquery what do you guys recommend for a ui library to use with jquery jquery ui seems to have less widgets compared to other frameworks i have been playing around lately with the dojo toolkit which seems pretty nice so far and i know that there is always the yahoo user interface but is there anything else i also need to consider licensing something that can be thistributed with open source software licensed under the bsd license as well as internaluse software,"['javascript', 'jquery']" +9970,wxpython or pygame for a simple card game i have been playing around with writing some simple card games in python for fun and i would like to add a graphical user interface gui to the games which library would you recommend for writing the gui for a simple card game,['python'] +9974,java reading a pdf file from url into byte arraybytebuffer in an applet i am trying to figure out why this particular snippet of code is not working for me i have got an applet which is supposed to read a pdf and thisplay it with a pdfrenderer library but for some reason when i read in the pdf files which sit on my server they end up as being corrupt i have tested it by writing the files back out againi have tried viewing the applet in both ie and firefox and the corrupt files occur funny thing is when i trying viewing the applet in safari for windows the file is actually fine i understand the jvm might be different but i am still lost i have compiled in java 15 jvms are 16 the snippet which reads the file is belowpublic static bytebuffer getasbytearrayurl url throws ioexception bytearrayoutputstream tmpout new bytearrayoutputstream urlconnection connection urlopenconnection int contentlength connectiongetcontentlength inputstream in urlopenstream byte buf new byte512 int len while true len inreadbuf if len 1 break tmpoutwritebuf 0 len tmpoutclose bytebuffer bb bytebufferwraptmpouttobytearray 0 tmpoutsize lines below used to test if file is corrupt fileoutputstream fos new fileoutputstreamcabcpdf foswritetmpouttobytearray return bbi must be missing something and i have been banging my head trying to figure it out any help is greatly appreciated thankseditto further clarify my situation the difference in the file before i read then with the snippet and after is that the ones i output after reading are significantly smaller than they originally are when opening them they are not recognized as pdf files there are no exceptions being thrown that i ignore and i have tried flushing to no avail this snippet works in safari meaning the files are read in it is entirety with no difference in size and can be opened with any pdf reader in ie and firefox the files always end up being corrupted consistently the same smaller size i monitored the len variable when reading a 59kb file hoping to see how many bytes get read in at each loop in ie and firefox at 18kb the inreadbuf returns a 1 as if the file has ended safari does not do thisi will keep at it and i appreciate all the suggestions so far,['java'] +9979,how to pass arguments when debugging a dot net application i have an command line that uses arguments i have no problem with this but each time i want to test the application i need to compile it run the cmd call the application with the parameters from the cmd because i did not find any solution that let me dynamically pass arguments to the console in visual studioany idea about thatthanks a lot,['.net'] +9983,c clearing the thread principal how do you clear the thread principal in ci have a background thread that does amembershipvalidateuserusername passwordwhich then copies the resulting principal back to the main threadappdomaincurrentdomainsetthreadprincipalthreadcurrentprincipalthis works fine but if i log off i want to clear the principal if i set it to null it does nothing threadcurrentprincipal null if i try and set it again viaappdomaincurrentdomainsetthreadprincipalthreadcurrentprincipali get the error default principal object cannot be set twiceany ideas,['c#'] +9987,rest on iis i am wondering how many folks using the microsoft development stack iis andor aspnet are actually using rest if so what forms of rest are being usedrest can be categorized a zillion ways but for the purpose of this question i will categorize it as followsradically rest using all thehttp methods putpostgetdeletemoderate rest using getpost rest hybrid uses just the get orpost http method but followsrestful principles of addressabilityand statein a class i am teaching weve been trying to implement a radically restful service on iis but weve been having difficulty implementing the put method there does not seem to be a lot of buzz on implementing put on iis so i am wondering how many people are actually using full blown rest are you using rest,"['asp.net', '.net']" +9994,showing page count with reportlab i am trying to add a simple page x of y to a report made with reportlab i found this old post about it but maybe six years later something more straightforward has emerged i found this recipe too but when i use it the resulting pdf is missing the images,['python'] +10005,profiling c multithreaded applications have you used any profiling tool like intel vtune analyzer what are your recommendations for a c multi threaded application on linux and windows i am primarily interested in cache misses memory usage memory leaks and cpu usage i use valgrind only on unix but mainly for finding memory errors and leaks,['c++'] +10006,ruby on rails versus python i am in the field of data crunching and very soon might make a move to the world of web programming although i am fascinated both by python and ruby as both of them seem to be having every similar styles when it comes to writing business logic or data crunching logicbut when i start googling for web development i start inclining towards ruby on rails my question is why is the web world obsessed with ruby on rails and active records so muchthere seem to be so many screencasts to learn ruby on rails and plethora of good books too why is python not able to pull the crowd when it comes to creating screencasts or orms like active record,"['python', 'ruby']" +10008,in sql how can i convert a money datatype to a decimal i want to convert a money datatype to a decimal because i want to record the results to 8 decimal placesfor example in a currency rate table i see the rate stored as 287104742820 as a money datatype using microsoft sql management studio i want to divide that by 10 in order to achieve the result 28710474282 however the result i am actually getting is 2871047i believe the reason i am getting only the 4 decimal places is because it is money datatype and therefore i think the way forward is to convert this to a decimal datatype,['sql'] +10020,how can i compare a float to nan if comparisons to nan always return false i have a float value set to nan seen in the watch window but i cannot figure out how to detect that in codeif fvalue floatnan returns false even though fvalue is nan,['c#'] +10027,what are the advantages of delegates what are the benefitsadvantages of using delegates can anyone provide any simple examples,"['c#', '.net']" +10036,how to add extra newline with puts without sticking newline character into string if i sayputs helloand decide to add an extra newline i need to do thisputs hellonhaving this character in the string is ugly is there any way to do this without polluting my string,['ruby'] +10040,how to make a dropdownlist thisabled on change event using jquery documentreadyfunction ddlcontinentsclientid changefunction var element this var totallength elementchildrenlength if thisthisabled false thisthisabled true what i am trying to do is fire off the change event of the dropdownlist and on change making this dropdownlist thisabled the code is firing and everything but it does not thisable the dropdownlistthis portion of the code is not workingif thisthisabled false thisthisabled true,"['asp.net', 'jquery']" +10044,read iphone sms messages is there a possibility to read received sms messages,['iphone'] +10046,is jasperreports the appropriate solution to thisplay reports in a web application we want to generate reports either embedded as html pages in a web app or downloadable as a pdf hence i came across jasperreports because it thought it would fullfill these requirements currently we assume our report will have about 50100 pages consisting of nearly only histograms and some tables the data is retrieved by some expensive queries from our dbafter evaluating it the whole day i have several doubts regarding web app aspects1 pagination of course i do not want to thisplay all pages in a single web page we need something like pagination but jasperreports seems not to support this approach the wepp demo which comes with jasperreports sketches the way to go i have to create a jasperprint which is already the full report allocating unrequired memory and which has performed the expensive queries then i could thisplay a single page but doing this again and again for each page does not appear as a proper solution to me2 as mentioned above our report will mostly consist of diagrams images are generated during exporting the jasperprint to its output format if i understand everything correct the imageservlet which comes with jr is capable but retrieve these images bei reading the generated images from the file system ii the exporter has stored them in the session therefore in memory since i think we will have a lot of images ii is not an option if we want to keep the memory footprint of the webapp low but on the other hand flooding the file system with files is also not the best idea i could imagine does it delete the files somewhen did i got something wrong is my understanding correct,['java'] +10047,image widthheight as an attribute or in css whats the correct semantic way to specify image height and width in csswidth15pxor inlineimg width15css seems like the right place to put visual information on the other hand few would argue that image src should not be specified as an attribute and the heightwidth seem as tied to the binary image data as the src isyes i realize from a technical enduser perspective this really does not matter,"['html', 'css']" +10061,email integration i was wondering if someone could help me out in some web application the app will send out emails say when a new message has been posted then instead of signing into the application to post a reply you can just simply reply to the email and it will automatically update the web app with your responsemy question is how is this done and what is it calledthanks,['python'] +10063,what tools exist for comparing c code to coding guidelines there exist tools for comparing code against a custom specified set of coding guidelinesstandards for a variety of languages rather than pure static analysis for common defects examples include fxcop for net code and checkstyle for java but i was wondering what examples people know of in the c worldan existing question was asked regarding free tools which provided examples like vera but i was also wondering about commercial tools that may be available,['c++'] +10065,best way to convert delphi code to c i have an application written in delphi that compiles in delphi 2007 i think it was originally written in delphi 7anyway i need to convert all the core nongui code into c because i want to release a mac version of the softwarewhat is the best way to do this any shortcuts i can take to speed up the processedit the code compiles to native code not net,['c++'] +10067,reference aspnet control by id in javascript when aspnet controls are rendered their ids sometimes change like if they are in a naming container button1 may actually have an id of ctl00 contentmain button1 when it is rendered for examplei know that you can write your javascript as strings in your cs file get the controls clientid and inject the script into your page using clientscript but is there a way that you can reference a control directly from javascript using aspnet ajaxi have found that writing a function to parse the dom recursively and find a control that contains the id that i want is unreliable so i was looking for a best practice rather than a workaround,"['javascript', 'asp.net']" +10071,how should i log while using multiprocessing in python right now i have a central module in a framework that spawns multiple processes using the python 26 multiprocessing module because it uses multiprocessing there is modulelevel multiprocessingaware log log multiprocessingget logger per the docs this logger has proceshared locks so that you do not garble things up in sysstderr or whatever filehandle by having multiple processes writing to it simultaneouslythe issue i have now is that the other modules in the framework are not multiprocessingaware the way i see it i need to make all dependencies on this central module use multiprocessingaware logging that is annoying within the framework let alone for all clients of the framework are there alternatives i am not thinking of,['python'] +10073,strange 5 second pause with php command line interface related to mysqlmysqli extension i am getting a strange 5 to 7 second pause when executing php scripts from the commandline php client php 52 on windowsduring this pause the php script just appears to freeze for a while before returning to the command prompt it is not using any significant cpu time it is like it is waiting for some delayafter experimenting with phpini i have narrowed this down to the fact that the mysql or mysqli extension is enabled if these extensions are both thisabled no annoying pause and the php script terminates in mere millisecondsthe command i am using iscprogram filesphpphpexe f 1where 1 is the php scriptthe pause still occurs even if the php script being executed is essentially emptyphpdo you know what is causing this pause and how i can remove it while still allowing mysql or mysqli support for php on the command line,['php'] +10077,will a using statement rollback a database transaction if an error occurs i have got an idbtransaction in a using statement but i am unsure if it will be rolled back if an exception is thrown in a using statement i know that a using statement will enforce the calling of thisposebut does anyone know if the same is true for rollbackupdate also do i need to call commit explicitly as i have below or will that also be taken care of by the using statement my code looks sort of like thisusing microsoftpracticesenterpriselibrarydatausingidbconnection connection databaseinstancecreateconnection connectionopen usingidbtransaction transaction connectionbegintransaction attempt to do stuff in the database potentially throw an exception transactioncommit,['c#'] +10079,treeview control in c select and focus when i select a node in the treeview it highlights and i show data based on that node below when i select another control the treeview loses focus it is no longer highlighted how do i keep it highlighted after losing focus while doing a search i cant tell which node is selected since i must keep the focus on the textbox so the user can type more text,['c#'] +10081,can 3d opengl game written in python look good and run fast i am planning to write an simple 3disometric view game in java using jmonkeyengine nothing to fancy i just want to learn something about opengl and writing efficient algorithms random map generating ones when i was planning what to do i started wondering about switching to python i know that python did not come into existence to be a tool to write 3d games but is it possible to write good looking games with this language i have in mind 3d graphics nice effects and free cpu time to power to rest of game engine i had seen good looking java games and too be honest i was rather shocked when i saw level of detail achieved in runescape hd on the other hand pygameorg has only 2d games with some starting 3d projects are there any efficient 3d game engines for python is pyopengl the only alternative good looking games in python are not popular or possible to achieve i would be grateful for any information feedback,['python'] +10087,whats the best way to deprecate a column in a database schema after reading through many of the questions here about db schema migration and versions i have come up with a scheme to safely update db schema during our update process the basic idea is that during an update we export the database to file drop and recreate all tables and then reimport everything nothing too fancy or risky therethe problem is that this system is somewhat viral meaning that it is only safe to add columns or tables since removing them would cause problems when reimporting the data normally i would be fine just ignoring these columns but the problem is that many of the removed items have actually been refactored and the presence of the old ones in the code fools other programmers into thinking that they can use themso i would like to find a way to be able to mark columns or tables as deprecated in the ideal case the deprecated objects would be marked while updating the schema but then during the next update our backup script would simply not select the objects which have been marked in this way allowing us to eventually phase out these parts of the schemai have found that mysql and probably other db platforms too but this is the one we are using supports the column attribute to both fields and tables this would be perfect except that i cannot figure out how to actually use it in a meaningful manner how would i go about writing an sql query to get all column names which do not contain a comment matching text containing the word deprecated or am i looking at this problem all wrong and missing a much better way to do this,"['sql', 'mysql']" +10090,firefox onkeydown detect pressed key from an input text i need to call a function to capture the onkeydown event and i need to pass a parameter to that event for exampleinput typetext onkeydowntextonkeydownmyprefix then in that function i need to know what key was pressed i usefunction textonkeydownprefix var key eventkeycode this works like a charm in ie but not in firefox i have read that for firefox you have to pass an argument to the handler and then use it to get the key something similar toinput typetext onkeydowndetectkeyeventfunction detectkeye var key documentall ekeycode ewhich but i cannot get to pass my parameter and the needed event parameter for firefox any suggestions,"['javascript', 'html']" +10100,what should i consider when choosing a mocking framework for net there are lots of mocking frameworks out there for net some of them have been superseded by others that are better in everyway however that still leaves many mocking frameworks that have different styles of usagethe time it takes to learn all of them well enough to decide witch to use is unreasonable i donat believe that we have yet reached a stage that we can talk about the best mocking framework so what questions should i by asking about the project and myself to help decide on the best mocking framework to use in a given caseit would also be useful to know why you choose the mocking framework you are currently using and if you are still happy with that chooseis there yet a useful vocabulary to use when comparing the styles of mocking frameworksi have limited this question to net as java does not have attributes or lambda expression so i hope the mocking frameworks can be better for net then javesummary so farif you need to mock static method ornone virtual methods then the onlyreasonable option is typemock however it is not free and does not drive you towards a good designrhino mocks is a very good option if youare doing tdd eg the objects youwish to mock implement interfaces at present it seems to be the market leadermoq introduction should be considered if you areusing net 35 moq may be againing on rhino mocks for new projectswhat have i missed from this summaryso what drives the choose between rhino mocks and moq if you are using net 35see alsowhat c mocking framework to use what are the capabilities of moq and rhinomockswhat are the realworld pros and cons of each of the major mocking frameworksawhat should i consider when choosing a dependency injection framework for neta may also be of interest as it asks the aother sidea of the question,['.net'] +10102,how to convert string into float in javascript i am trying to parse two values from a datagridthe fields are numeric and when they have a comma ex 55420 i cannot get the numbers after the commai have tried parseint and parsefloat how can i do this,['javascript'] +10103,faking browser request in aspnet c i am using the code below to pull one of our 3rd party developed pages in so i can parse it as xml for my random bits of workirritatingly we stil have a browser detection level set on the server that only allows certain browsers on to the site so the question is how would i fake it so that the server thinks its a browser request static string gethtmlpagestring strurl string strresult systemnetwebresponse objresponse systemnetwebrequest objrequest systemnethttpwebrequestcreatestrurl objresponse objrequestgetresponse using systemiostreamreader sr new systemiostreamreaderobjresponsegetresponsestream strresult srreadtoend srclose return strresult,['asp.net'] +10105,what language decision in c annoys you i was just dealing with strings and i find myself annoyed that strings can be nullable so i have to have ifteststringstringemptystringemptyall over the place would string have been so hard for allowing nullability in the relatively few cases where it is needed dbs idiot user inputs etc i also find myself irritated with having to export readonly interfaces in the cases where i want some form of const correctness so what c language constructdecision annoys youedit thanks for the isnullorempty function i had not seen that before still does not lessen my annoyance at it being nullable d,['c#'] +10109,should locks and mutexes in c be used together wouldnt this be overkill and only one of these necessary i have searched and found different posts about mutual exclusion and locks in c here and hereexamplein our app we have a function that spins off multiple reconnection threads and inside this thread we use a mutex and a lock wouldnt lock block access to this section of code and prevent connect from being updated by any other threadbool connect falsemutex reconnectmutex new mutexfalse reconnect keytry locksite ifsitecontainskeykey siteinfo siteinfositekey ifreconnectmutexwaitone100 true connect true if connect process thread logic catchreconnectmutexreleasemutexmore infothis is in an aspnet webservice not running in a web garden,['c#'] +10112,freeze th header and scrolling data i have a html table and i want to freeze the header row th tag for scrolling the data how i can do that does i need to use the domthanks,"['javascript', 'jquery', 'html']" +10126,commandtypetext vs commandtypestoredprocedure is there any benefit to explicitly using the storedprocedure commandtype as opposed to just using a text command in other words iscmd new sqlcommandexec storedprocp1 p2cmdcommandtype commandtypetextcmdparametersaddp1 1cmdparametersaddp2 2any worse thancmd new sqlcommandstoredproccmdcommandtype commandtypestoredprocedurecmdparametersaddp1 1cmdparametersaddp2 2edit fixed bad copy paste job again also the whole point of the question is for a data access class i would much rather be able to pass the stored proc name and parameters in one line as opposed to extra lines for each parameter,"['c#', 'sql']" +10131,design considerations for internationalization i have read joels article on unicode and i feel that i have at least a basic grasp of internationalization from a character set perspective in addition to reading this question i have also done some of my own research on internationalization in regards to design considerations but i cannot help but suspect that there is a lot more out there that i just do not know or do not know to asksome of the things i have learnedsome languages read righttoleftinstead of lefttorightcalendar dates times currency andnumbers are thisplayed differentlyfrom language to languagedesign should be flexible enough toaccommodate a lot more text becausesome languages are far more verbosethan othersdo not take icons or colors forgranted when it comes to theirsemantic meaning as this can varyfrom culture to culturegeographical nomenclature varies fromlanguage to languagewhere i am atmy design is flexible enough toaccommodate a lot more texti automatically translate eachstring including error messages and help dialogsi have not come to a point yet wherei have needed to thisplay units of timecurrency or numbers but i will bethere shortly and will need todevelop a solutioni am using the utf8 character setacross the boardmy menus and various lists in the application are sortedalphabetically for each language for easier readingi have a tag parser that extractstags by filtering out stop words thestop words list is language specificand can be swapped outwhat i would like to know more abouti am developing a downloadable php web applicationso any specific advice in regards tophp would be greatly appreciatedi have developed my own framework andam not interested in using otherframeworks at this timei know very little about nonwesternlanguages are there specificconsiderations that need to be takeninto account that i have not mentionedabove also how do phps arraysorting functions handle nonwesterncharactersare there any specific gotchas thatyouve experienced in practice i am looking in terms of both the gui and the application code itselfany specific advice for working withdate and time thisplays is there abreakdown according to region orlanguagei have seen a lot of projects and siteslet their communities providetranslation for their applicationsand content do you recommend thisand what are some good strategies forensuring that you have a goodtranslationthis question is basically the extentof what i know aboutinternationalization what do not iknow that i do not know that i shouldlook into furtheredit i added the bounty because i would like to have more realworld examples from experience,['php'] +10133,how does python sort a list of tuples empirically it seems that pythons default list sorter when passed a list of tuples will sort by the first element in each tuple is that correct if not whats the right way to sort a list of tuples by their first elements,['python'] +10136,query on select system call select is defined as int selectint nfds fd set readfds fd set writefds fd set errorfds struct timeval timeoutnfds represents the highest file descriptor in all given sets plus one i would like to know why is this data required for select when the fd set information is available if the fds in the set are say 4 8 9 the value of nfds would be 10 would select moniter fds 987654,['c'] +10141,allow php sessions to carry over to subdomains i use php sessions not cookies except for session id cookie for all user data and when a user goes to their profile usermydomaincom they are immediately logged out untill then remove the subdomainis there a way to accept sessions from all domains as long as its mydomaincom,['php'] +10142,force uiviewuiviewcontroller orientation were writing an application that is in landscape mode exclusively we use a transform on a root view to rotate it to landscaperight then every view that gets loaded by that view shares the coordinate system that is all fine and dandy except one of our views has a uiwebview object that is being loaded by a view controller the site that were trying to look at does not have its content filling the view when i view the same site in mobile safari in landscape mode it looks correct my guess is that the view controller were using to host the webview still thinks it is in portrait mode as querying the interfaceorientation of the property returns 1is there a way to trick a viewview controller to think it is in a specific orientation,['iphone'] +10153,mimic window onerror in opera using javascript i am currently working on a web application i have a js logging mechanism that handles javascript error that are not caught by the js code inside the page i am using windowonerror to catch all such errors and log them else wherehowever problem is with opera which does not have windowonerror event one approach i could think of is to string process all js functions code and insert try catch blocks inside those functions after body load it does not work in many cases though but it at least works to some extenti am sure this approach sucks but i could not think of anything betterplease adviseupdate for now i am calling the code below to catch as many errors as i couldfunction onbodyload var allelements documentgetelementsbytagname forvar cnt 0cnt allelementslengthcnt registeralleventsallelementscnt function registeralleventsobjtoprocess forvar cnt 0cnt objtoprocessattributeslengthcnt ifisattributeaneventobjtoprocessattributescntname objtoprocessattributescntvalue tryobjtoprocessattributescntvaluecatcherrlogerror objtoprocessid err,['javascript'] +10164,how to access your website through lan in aspnet i have an aspnet webpage application and i want it to be accessed using a local area networklan or wireless area networkwlani do not know where to start is there something that i will configure in order for others to access my webpage i would really appreciate your answer thanks a lot,['asp.net'] +10167,is using a mutex to prevent multiple instances of the same program from running safe i am using this code to prevent a second instance of my program from running at the same time is it safemutex appsingleton new systemthreadingmutexfalse myappsingleinstncemutxif appsingletonwaitone0 false applicationenablevisualstyles applicationsetcompatibletextrenderingdefaultfalse applicationrunnew mainform appsingletonclose else messageboxshowsorry only one instance of myapp is allowedi am worried that if something throws an exception and the app crashes that the mutex will still be held is that true,['c#'] +10188,deep copying an nsarray is there any builtin function that allows me to deep copy an nsmutablearrayi looked around some people say amutablearray copywithzonenil works as deep copy but i tried and it seems to be a shallow copyright now i am manually doing the copy with a for loopdeep copy a 99 mutable array to a passedin reference arraydeepmucopy nsmutablearray array tonewarray nsmutablearray arraynew arraynew removeallobjectsensure it is clean for int y 0 y9 y arraynew addobjectnsmutablearray new for int x 0 x9 x arraynew objectatindexy addobjectnsmutablearray new nsmutablearray adomain array objectatindexy objectatindexx for int i 0 iadomain count i copy object by object nsnumber and nsnumber numberwithintadomain objectatindexi intvalue arraynew objectatindexy objectatindexx addobjectn but i would like a cleaner more succinct solution,['objective-c'] +10189,how to refresh the windows desktop programmatically ie f5 from c yeah i know this seems like a dumb question its just a oneoff hack i need to wrap up a somewhat mundane task so i can move on to something more interestingeditmaybe more info would help i am trying to remove some shortcuts from the desktop and i need the user to see it removed right away so they do not have to press f5,"['c#', '.net']" +10190,c to ccli to c dll systemiofilenotfoundexception i am getting systemiofilenotfoundexception the specified module could not be found when running c code that calls a ccli assembly which in turn calls a pure c dll it happens as soon as an object is instantiated that calls the pure c dll functionsbackingstore is pure ccppdemoviewmodel is ccli calling backingstore it has a reference to backingstorei tried the simplest possible case add a new c unit test project that just tries to create an object defined in cppdemoviewmodel i added a reference from the c project to cppdemoviewmodel a ccli test project works fine with just the added ref to cppdemoviewmodel so it is something about going between the languagesi am using visual studio 2008 sp1 with net 35 sp1 i am building on vista x64 but have been careful to make sure my platform target is set to x86this feels like something stupid and obvious i am missing but it would be even more stupid of me to waste time trying to solve it in private so i am out here embarrassing myselfthis is a test for a project porting a huge amount of legacy c code which i am keeping in a dll with a viewmodel implemented in cclieditafter checking directories i can confirm that the backingstoredll has not been copiedi have the standard unique project folders created with a typical multiproject solutionwpfviewmodelincpp backingstore cppviewmodel cppviewmodeltestincs bin debug debugthe higherlevel debug appears to be a common folder used by the c and ccli projects to my surprisewpfviewmodelincppdebug contains backingstoredll cppdemoviewmodeldll cppviewmodeltestdll and their associated ilk and pdb fileswpfviewmodelincppcppviewmodeltestincsbindebug contains cppdemoviewmodel and cppviewmodeltestincs dll and pdb files but not backingstore however manually copying backingstore into that directory did not fix the errorcppdemoviewmodel has the property copy local set which i assume is responsible for copying its dll when if is referenced i cannot add a reference from a c project to a pure c dll it just says a reference to backing store could not be addedi am not sure if i have just one problem or twoi can use an oldfashioned copying build step to copy the backingstoredll into any given c projects directories although i would hoped the new net model did not require thatdependencywalker is telling me that the missing file is gpsvcdll which has been suggested indicates security setting issues i suspect this is a red herringedit2with a manual copy of backingstoredll to be adjacent to the executable the gui now works fine the c test project still has problems which i suspect is due to the runtime environment of a test project but i can live without that for now,['c#'] +10191,is the original java ideal dead i feel that while i love j2me and java it is hypocritical of them to have two apis for java java was designed with one code many platforms in mind and now it is more like one api for every os and one api for everything smaller than a netbook i see a lot of j2me emulators and such being ported to things like the psp and other consoles for homebrew and i wonder why no one is doing this with normal java i would love to write a game to play on my pc than fire up a simple emulator and play the same game on the psp or the dreamcast but i cannot j2me cannot even run on a pc you need an emulator for it which reduces your market greatly plus most emulators are bulky and not goodwith superphones like the iphone coming out people are going to want more than little j2me games so if java cannot port their standard jre to it they might find themselves missing the boat like microsoft did with the netbook boomit just feels like sun needs to ether work on making the standard jre smaller and more portable or making j2me available on the pc easily,['java'] +10193,cocoa or objectivec in regards to iphone development how do you now when your using a cocoa vs pure objectivec objects for example the following are objectivecnstimernsstringint floatnsmutablearraybut these are cocoauilabeluicoloruiviewand to be clear doescocoa touch iphone developmentcocoa mac os x development,"['objective-c', 'iphone']" +10194,converting an empty string into nil in ruby i have a string called word and a function called infinitive such thatwordinfinitive would return another string on some occasions and an empty string otherwisei am trying to find an elegant ruby one line expression for the codesnippet below if wordinfinitive return wordelse return wordinfinitivehad infinitive returned nil instead of i could have done something likewordinfinitive or wordbut since it does not i cannot take advantage of the shortcircuit orideally i would want1 a single expression that i could easily embed in other code2 the function infinitive being called only once3 to not add any custom gems or plugins into my code,['ruby'] +10201,python test that succeeds when exception is not raised i know about unittest python modulei know about assertraises method of testcase classi would like to write a test that succeeds when an exception is not raisedany hints please,['python'] +10205,how do i create an instance from a string in c i am reading information from an xml which contains the type of an object that i need to instantiate along with it is constructor parametersthe object type is actually in another project within a sibling namespace i need to create a companyproject2type within companyproject1 classi found this question but it does not handle the constructor parameters or the fact that it is in another namespacehow can i do thisedit the assembly name and default namespace was not set correctly in the project properties,['c#'] +10211,evaluation order of new expression in the following code sample do the c standard guarantee that i is evaluated after the memory allocation call to operator new but before the call to xas constructornew x i,['c++'] +10212,how can i list all processes running in windows i would like to find a way to loop through all the active processes and do diagnostics checks on them mem usage cpu time etc kinda similar to the task manager the problem is broken down into two partsfinding all the processesfinding diagnostics attributes about themi am not sure even in what namespace to go looking about it any help tips links is grateful,"['c#', '.net']" +10216,is there a way to delay an event handler say for 1 sec in windows forms i need to be able to delay the event handlers for some controls like a button to be fired for example after 1 sec of the actual event click event for example is this possible by the net framework i use a timer and call my code from the timers tick event as below but i am not sure if this is the best approach void onbuttonclick timer1enabled truevoid ontimertick timerenabled false callmycodenow,"['c#', '.net']" +10220,c templates undefined reference i have a function declared like sotemplate typename t t readand defined like sotemplate typename tt packetreaderread offset sizeoft return tbufoffsetsizeoft however when i try to use it in my main functionpacketreader readerreaderreadinti get the following error from gg o main maino packetomaino in function mainmaincpptext0xcc undefined reference to int packetreaderreadintcollect2 ld returned 1 exit statusmake main error 1can anyone point me into the right direction,['c++'] +10222,stdvector on visualstudio2008 appears to be suboptimally implemented too many copy constructor calls i have been comparing a stl implementation of a popular xmlrpc library with an implementation that mostly avoids stl the stl implementation is much slower i got 47s down to 45s i have diagnosed some of the reasons it is partly due to stdstring being misused eg the author should have used const stdstring wherever possible do not just use stdstrings as if they were java strings but it is also because copy constructors were being constantly called each time the vector outgrew its bounds which was exceedingly often the copy constructors were very slow because they did deepcopies of trees of xmlrpc valuesi was told by someone else on stackoverflow that stdvector implementations typically double the size of the buffer each time they outgrow this does not seem to be the case on visualstudio 2008 to add 50 items to a stdvector took 177 calls of the copy constructor doubling each time should call the copy constructor 64 times if you were very concerned about keeping memory usage low then increasing by 50 each time should call the copy constructor 121 times so where does the 177 come frommy question is a why is the copy constructor called so often b is there any way to avoid using the copy constructor if youre just moving an object from one location to another in this case and indeed most cases a memcpy would have sufficed and this makes a big differencenb i know about vectorreserve i am just a bit thisappointed that application programmers would need to implement the doubling trick when something like this is already part of any good stl implementationmy test programinclude stringinclude iostreaminclude vectorusing namespace stdint constructorcallsint assignmentcallsint copycallsclass c int npublic cint n and n constructorcalls cconst c orig copycalls and orign void operatorconst c orig assignmentcalls and orign int mainint argc char argv stdvectorc a areserve50 for int i0 i 50 i apush backi cout constructor calls constructorcalls n cout assignment calls assignmentcalls n cout copy calls copycalls n return 0,['c++'] +10223,why emacsvimtextmate is not xcode good enough hi i mostly do c objectivec programming and i found xcode plus an auto completionmacro plugin completion dictionary quite adequatehowever all people seem to praise over their pure text editors i tried textmate for a bit liked its simplicity but thislike its filesframework handlingam i missing something here or do vim or emacs have autocompletion as good as xcode,['objective-c'] +10233,what does end of stream mean when working with sockets when working with sockets in java how can you tell whether the client has finished sending all binary data before you could start processing them consider for exampleistream new bufferedinputstream socketgetinputstreamostream new bufferedoutputstreamsocketgetoutputstreambyte buffer new bytebuffer sizeint countwhileistreamavailable 0 count istreamreadbuffer 1 do something assuming all input has been readostreamwritegetresponse ostreamflushi have read similar posts on so such as this but could not find a conclusive answer while my solution above works my understanding is that you can never really tell if the client has finished sending all data if for instance the client socket sends a few chunks of data and then blocks waiting for data from another data source before it could send more data the code above may very well assume that the client has finished sending all data since istreamavailable will return 0 for the current stream of bytes,['java'] +10242,how to do an efficient priority update in stl priority queue i have a priority queue of some objecttypedef priority queueobject queuequeue queuefrom time to time the priority of one of the objects may change i need to be able to update the priority of that object in the queue in an efficient way currently i am using this method which works but seems inefficientqueue newqueuewhile queueempty object objqueuetop queuepop if priorityhaschangedobj newqueuepush backobjectnew priority else newqueuepush backobjnewqueueswapqueue this only works because i actually subclassed the priority queue class and exposed a swap method that swaps in the containeri implemented it this way because i was in kind of a hurry at the time and this was the quickest thing i could do that i could be sure it would work ok there has to be a better way than this though really what i want is a way to eitherextract out the instance with the changed priority and insert a new one with the new priority valueupdate the instance with the changed priority and then update the queue so that it is correctly sortedwhat is the best way to do this,['c++'] +10245,detecting the launch of a application how do i detect with c on windows the moment when an external application is being launchedi tried the filesystemwatcher which does not work because the file is not really changing also having a timer constantly check all the open processes might be a bit over kill is there any other way to do this if not in c is it possible to do so in c if so please give me an examplethe reason i want to do this is for logging purposes,"['c#', 'c++']" +10251,developing kernels and testing them in virtual machines i like programming challenges and writing a kernel seems a programming challengeunfortunately kernels are particularly hard to test because they are basically the core of operating systems and so they cannot be easily ran on top of an operating systemhowever i know about applications called virtual machines that can emulate computer hardwarewhat is the easiestbest way to develop and test kernelscassembly using virtual machines,['c'] +10257,do python lists have an equivalent to dictget i have a list of integers i want to know whether the number 13 appears in it and if so where do i have to search the list twice as in the code belowif 13 in intlist i intlistindex13in the case of dictionaries there is a get function which will ascertain membership and perform lookup with the same search is there something similar for lists,['python'] +10258,cache ajax requests i am sending ajax getrequests to a php application and would like to cache the request returns for later usesince i am using get this should be possible because different requests request different urls eg gethtmlphppage2 and gethtmlphppage5what headers do i need to declare in the phpapplication to make the clients browser cache the request url content in a proper way do i need to declare anything in the javascript which handles the ajaxrequest i am using jquerys ajax function which has a cache parameterhow would i handle edits which change the content of eg gethtmlphppage2 so that the client does not fall back to the cached versionadding another parameter to the get request eg gethtmlphppage2version2 is not possible because the link to the requested url is created automatically without any checking which is preferably the way i want it to behow will the browser react when i try to ajaxrequest a cached request url will the ajaxrequest return success immediatelythankswillem,"['php', 'javascript', 'jquery']" +10259,get month from datetime in sqlite i am trying to get extract the month from a datetime field in sqlite monthdatefield does not work as well as strftimem datestart any ideas,['sql'] +10263,hibernate tutorials let us say that i am new to hibernate is there a way to get my skills up to speed are there any good tutorials,['java'] +10269,jquery adding context to a selector is much faster than refining your selector i just noticed that adding context to the selector is much faster than refining your selectorlibarappendblais twice as faster thanbar liappendblais this generally true,['jquery'] +10278,i do not understand this code i do not understand this code snippet function ms var plcunescape unescape x43x43x43x43nxef urlcollectgarbage if mfreturn0 mf1 var hsta0x0c0c0c0chbs0x10plplclength2shbspl0x38 var ssgssaddrhstashbhstahbshbs fori0ihbi missplc hav return1 in the above function i cannot seem to figure out the variable types or figure out what it is doing with the hsta variable and what it is assigning to itvar hsta0x0c0c0c0chbs0x10plplclength2shbspl0x38var ssgssaddrhstashbhstahbshbsfori0ihbimissplci also cannot figure out this function function fb try var objnull objcobj5c6698d97be441228ec5291d84dbd4a0 ifobj ms var buf addr0x0c0c0c0c while buflength 400 buf buf buf bufsubstring0400 objextractiptc buf objextractexif buf catche return 0 what does the following code mean cobj5c6698d97be441228ec5291d84dbd4a0what kind of variable is this var buf addr0x0c0c0c0cbuf bufsubstring0400objextractiptc bufobjextractexif bufmost importantly what is that code snippet trying to dohere are some more functionsfunction hexnumwidth var digits0123456789abcdef var hexdigitssubstrnum0xf1 whilenum0xf numnum4 hexdigitssubstrnum0xf1hex var widthwidthwidth0 whilehexlengthwidthhex0hex return hex function addraddr return unescapeuhexaddr0xf4uhexaddr160xf4 any guidance would be appreciated,['javascript'] +10280,how to have jquery restrict file types on upload i would like to have jquery limit a file upload field to only jpgjpeg png and gif i am doing backend checking with php already i am running my submit button through a javascript function already so i really just need to know how to check for the file types before submit or alert,"['javascript', 'jquery']" +10285,using md5 hash on a string in cocoa possible duplicatemd5 algorithm in objective c i need to hash a string using the md5 technique in cocoa any frameworks that are used must be able to be accessed on the iphone please provide code if possible,"['iphone', 'objective-c']" +10286,escaping verbatim string literals i have the following string which would not compilestring formlookuppull select value1 tablename columnname from lkplookups where table tablename and field columnname the offending sections are table and field the compiler is getting all mixed up on the escape sequence can anyone see whats wrong,['c#'] +10288,what is the appdelegate for and how do i know when to use it i am just beginning to work on iphone apps how do i know when i should be putting stuff in appdelegate versus a custom class is there a rule or any type of analogy with another programming language like python or php that uses an appdelegate like pattern,"['objective-c', 'iphone']" +10291,how do i detect a lock this computer command from a wpf application would prefer an answer in c net 35 using wpf windows forms also okayi have an application that is essentially a toolbar window or tray icon it needs to detect if a user locks hisher workstation and walks away in order to update the persons status in a centralized systemi can detect a session switch or a logout easily enough using the systemevents but i cannot for the life of me figure out how to detect or receive an event on lockthanks for any assistance,['c#'] +10296,delete with join in mysql create table clients client id int11 primary key client idcreate table projects project id int11 unsigned client id int11 unsigned primary key project idcreate table posts post id int11 unsigned project id int11 unsigned primary key post idin my php code when deleting a client i want to delete all projects postsdelete from postsinner join projects on projectsproject id postsproject idwhere projectsclient id client idthe posts table does not have a foreign key client id only project id i want to delete posts that are posted in projects that have the passed client idthis is not working right now no posts are deleted,['mysql'] +10308,equivalent to exclamation mark for method names from ruby in other languages in ruby methods with side effects or methods that change the object passed as parameters have as a postfixfor examplesomestringgsubs swould be changing the string object whilesomestringgsubs swould work on a copy of the string object and would not change the state of any objects outside of the methodi like this convention and i would like to use it when programming in other languages toomy question do real ruby programmers i am not one actually use this convention if not why not are there equivalent conventions for naming methods in java php perl cobol,['ruby'] +10318,gccollect in a loop i found this piece of code inside systemwebisapiruntime using reflectorpublic void dogccollect for int i 10 i 0 i gccollect can anyone comment on this is there a reason to do gccollect in a loop why 10 times and not 3 5 or 20 analysis indicated that it is not used inside net framework but it is public so i suppose that iis could call itedit just for clarification purposes i have never called gccollect and i have no intentions of using it i know it is a bad idea in most if not all cases the question is why net framework does it thanks for all your answers,"['c#', '.net']" +10322,c optimization techniques is there a site that provides a great list of common c optimization practiceswhat i mean by optimization is that you have to modify the source code to be able to run a program faster not changing the compiler settings,"['c++', 'c']" +10323,what is the most efficient way to convert an int to a string say i haveint somevalue 42now i want to convert that int value to a string which way is more efficient onestring stringvalue integertostringsomevalue twostring stringvalue stringvalueofsomevalue threestring stringvalue somevalue i am just curious if there is any real difference or one is better than the other,['java'] +10327,cleanup php session files on my website i use php sessions session information is stored in files in my session path after a few months i thiscovered that these session files are never deleted by now there are 1450 of them in this directory how should these be cleaned up do i have to do it programmatically or is ther a setting i can use somewhere that would have this cleanup happen automaticallyedit forgot to mention this site runs at a provider so i do not have access to a command line i do have ftpaccess but the session files belong to another user the one the webserver proces runs i guess from the first answers i got i think it is not just a setting on the server or php so i guess i will have to implement something for it in php and call that periodically from a browser maybe from a cron job running on my own machine at home,['php'] +10334,programmatically detecting releasedebug mode net possible duplicatehow to find out if a net assembly was compiled with the trace or debug flag possible duplicatehow to idenfiy if the dll is debug or release build in net whats the easiest way to programmatically check if the current assembly was compiled in debug or release mode,['.net'] +10336,is there a java collection or similar that behaves like an autoid sql table note that i am not actually doing anything with a database here so orm tools are probably not what i am looking fori want to have some containers that each hold a number of objects with all objects in one container being of the same class the container should show some of the behaviour of a database table namelyallow one of the objects fields to be used as a unique key i e other objects that have the same value in that field are not added to the containerupon accepting a new object the container should issue a numeric id that is returned to the caller of the insertion methodinstead of throwing an error when a duplicate entry is being requested the container should just skip insertion and return the key of the already existing objectnow i would write a generic container class that accepts objects which implement an interface to get the value of the key field and use a hashmap keyed with those values as the actual storage class is there a better approach using existing builtin classes i was looking through hashset and the like but they did not seem to fit,['java'] +10343,how to update and order by using ms sql ideally i want to do thisupdate top 10 messages set status10 where status0 order by priority descin english i want to get the top 10 available status0 messages from the db and lock them status10 a message with a higher priority should be gotten firstunfortunately ms sql does not allow an order by clause in the updateanyway how to circumvent this,['sql'] +10351,jquerywcf without aspnet ajax i am proper struggling getting that magic moment when wcf is configured nicely and jquery is structuring its requestsunderstanding responses nicelyi have a service servicehost languagec debugtrue servicexywcfdataclientbroker factorysystemservicemodelactivationwebscriptservicehostfactory this was recommended by the man rick strahl to avoid having to define the behaviours within webconfigmy interface for the wcf service sits in another assemblynamespace xywcfdata servicecontractnamespace ywcf public interface iclientbroker operationcontract webinvokemethodpostbodystylewebmessagebodystylewrappedresponseformatwebmessageformatjson iclient getclientjsonint clientid the concrete service class isnamespace xywcfdata aspnetcompatibilityrequirementsrequirementsmode aspnetcompatibilityrequirementsmodeallowed class clientbroker iclientbroker public iclient getclientjsonint clientid iclient clientnew client gets and returns an iclient return client my iclient is an entity framework class so is decorated with datacontractdatamember attributes appropriatelyi am trying to call my wcf service using the methods outlined on rick strahls blog at the full fat version the debugger jumps into the wcf service fine so my jqueryjson is being understood and gets the iclient and returns it however when i return the response i get various useless errors the errors i am getting back do not mean much i am using postam i right to be using an interface instead of a concrete object as it does get into the wcf service it does seem to be the encoding of the result that is failingdoes anyone have any ideas,"['c#', 'jquery']" +10356,how to configure ipython to use gvim on windows this really looks like something i should be able to find on google but for some reason i cannot make heads or tails of it there is the editor environment variable the ipy user confpy file the ipythonrc file some weird thing about running gvim in server mode and a bunch of other stuff i cannot wrap my head around probably because of lack of sleepis there a guide somewhere i can follow or maybe someone can just outline the steps i need to take,['python'] +10378,print designers moving to web what do they need to know i am trying to compile a guide for students used to publishing in print who are learning web designsome obvious things which web developers know but they do notyou cannot rotate graphics in htmlall objects have to be rectangular you cannot have a circular divmany typographical effects in their repertoire cannot be achievedsome things which are tricky arecan they have variable opacity well yes and nocan they have rounded corners maybesome things which are not technical difficulties but which are problemsimage file sizes i have a student who wants to have a different large graphic header on every page of their site that is not technically a problem but it will mean a visitor has to wait for a new graphic to load every time they navigateaccessibility why not just make everything a graphic to overcome the limitations of htmlplease help me fill out my list and add any hints or tips for people making this transition,"['html', 'css']" +10382,is there any way to get readable gcc error and warning output at the command line for some long errors the gcc output is dense and has lots of linewrapping etc especially when errors are subtle it can take me 1030 seconds of squinting to parse it with my eyesi have taken to pasting this in an open codeeditor window to get some basic syntax highlighting and enable reformatting with regexshas anyone invented a more automated method,"['c++', 'c']" +10395,query unmapped columns in nhibernate i have a class that is mapped to a table using nhibernate the problem is that only some of the properties are mapped to columns in the table this is fine because the only columns we use for thisplay are mapped however i was wondering if there is any way to query against other columns in the table that are not mapped to properties in my classfor example we have a table with the following columnscustomercustomeridnamedatecreatedand we have an objectpublic class customer public virtual int customerid getset public virtual string name getsetand name and customerid are mapped however datecreated is not because we never thisplay it anywhere we would like to query the customer table for customers that were created by a certain date is there any way to do this without mapping the datecreated also it would be preferable to do this using the criteria api,['c#'] +10396,which is the best data access frameworkapproach for c and net edit i made it a community wiki as it is more suited to a collaborative formatthere are a plethora of ways to access sql server and other databases from net all have their pros and cons and it will never be a simple question of which is best the answer will always be it dependshowever i am looking for a comparison at a high level of the different approaches and frameworks in the context of different levels of systems for example i would imagine that for a quickanddirty web 20 application the answer would be very different from an inhouse enterpriselevel crud applicationi am aware that there are numerous questions on stack overflow dealing with subsets of this question but i think it would be useful to try to build a summary comparison i will endeavour to update the question with corrections and clarifications as we goso far this is my understanding at a high level but i am sure it is wrongi am primarily focusing on the microsoft approaches to keep this focusedadonet entity frameworkdatabase agnosticgood because it allows swapping backends in and outbad because it can hit performance and database vendors are not too happy about itseems to be mss preferred route for the futurecomplicated to learn though see 267357it is accessed through linq to entities so provides orm thus allowing abstraction in your codelinq to sqluncertain future see is linq to sql truly deadeasy to learn only works with ms sql serversee also pros and cons of linqstandard adonetno ormno abstraction so you are back to roll your own and play with dynamically generated sqldirect access allows potentially better performancethis ties in to the ageold debate of whether to focus on objects or relational data to which the answer of course is it depends on where the bulk of the work is and since that is an unanswerable question hopefully we do not have to go in to that too much imho if your application is primarily manipulating large amounts of data it does not make sense to abstract it too much into objects in the frontend code you are better off using stored procedures and dynamic sql to do as much of the work as possible on the backend whereas if you primarily have user interaction which causes database interaction at the level of tens or hundreds of rows then orm makes complete sense so i guess my argument for good oldfashioned adonet would be in the case where you manipulate and modify large datasets in which case you will benefit from the direct access to the backendanother case of course is where you have to access a legacy database that is already guarded by stored proceduresaspnet data source controlsare these something altogether different or just a layer over standard adonet would you really use these if you had a dal or if you implemented linq or entitiesnhibernateseems to be a very powerful and powerful ormopen sourcesome other relevant linksnhibernate or linq to sqlentity framework vs linq to sql,"['c#', '.net', 'asp.net', 'sql']" +10398,experiences with javascript history frameworks i am seeking a javascript history framework to handle navigation inside a page when the user selects multiple options which change the page behaviourthere are multiple artefacts on the page that change the data loading of the page and i would like to store this as a stacked set of behaviour in a wider sense i would like to add this as a toolkit to my future web projects for the same reasonsi am primarily writing in aspnet with jquery but i am only really worried about jquery for now i do write other projects in php python and perl depending on the gig so it would have to be platform agnostici have been looking on the net and have found a few but only one covered on oreilly looked like it would fit the bill i have started playing with it but i wanted to know what toolkits other people were using and what others would recommendso if you have any experience of history frameworks handling the back button etc in ajax i would love to hear about what youve used and how it worked out it would really help me make a final choice on librarythankss,"['javascript', 'jquery']" +10427,url hash with html base tag windowlocationhashwhen using a link for a javascript action i usually do something like thisa hreflink textathat way when someone clicks the link before the page loads nothing terrible happenshtml base tagon my current project i use this same construct but with a base taghtmlhead base href headbody a hreflink textabodyhtmlhowever if the page url isclicking the link navigates torather thanhow can i fix this,"['javascript', 'html']" +10429,why is there a special new and delete for arrays what is wrong with using delete instead of deleteis there something special happening under the covers for allocating and freeing arrayswhy would it be different from malloc and free,"['c++', 'c']" +10438,do i need to thispose or close an eventwaithandle if i am using eventwaithandle or autoresetevent manualresetevent to synchronise between threads then do i need to call the close or thispose methods on that event handle when i am done with iteventwaithandle inherits from waithandle which implements ithisposable and fxcop complains if i do not implement ithisposable on any class that contains an eventwaithandle so this suggests that i do need to call ithowever none of these msdn usage examples call thispose or closevs80aspxvs80aspxvs80aspxis this just an example of microsoft ignoring their own advice,"['c#', '.net']" +10450,c xml serialization leading question marks problemby leveraging some samples i found online here i have written some xml serialization methodsmethod1 serialize an object and return a the type b the xml stringmethod2 takes a and b above and gives you back the objecti noticed that the xml string from the method1 contains a leading this seems to be fine when using method2 to reconstruct the object but when doing some testing in the application sometimes we got leading instead this caused the method2 to throw an exception while trying to reconstruct the objectthe object in this case was just a simple intsysteminvalidoperationexception was unhandled messagethere is an error in xml document 1 1 sourcesystemxml stacktrace at systemxmlserializationxmlserializerdeserializexmlreader xmlreader string encodingstyle xmldeserializationevents events at systemxmlserializationxmlserializerdeserializexmlreader xmlreader string encodingstyle at systemxmlserializationxmlserializerdeserializestream stream at xmlserializationprogramdeserializexmlstringtoobjectstring xmlstring string objecttype in cdocuments and settingsprojectsxmlserializationprogramcsline 96 at xmlserializationprogrammainstring args in cdocuments and settingsprojectsxmlserializationprogramcsline 49would anyone be able to shed some light on what might be causing thissample codeheres sample code from the minitester i wrote while coding this up which runs as a vs console app it will show you the xml string you can also uncomment the regions to append the extra leading to reproduce the exceptionusing systemusing systemiousing systemtextusing systemxmlusing systemxmlserializationnamespace xmlserialization class program static void mainstring args deserialize to string region int object inobj 5 endregion region string object inobj testing123 endregion region list list inobj new list inobjadd025 inobjadd126 endregion string stringarray serializeobjecttoxmlstringinobj region include leading int indexofbracket stringarray0indexof stringarray0 stringarray0 endregion region strip out leading int indexofbracket stringarray0indexof string trimmedstring stringarray0substringindexofbracket stringarray0 trimmedstring endregion consolewritelineinput consolewriteline consolewritelineobject type stringarray1 consolewriteline consolewritelinexml string environmentnewline stringarray0 consolewritelinestringempty serialize back to object object outobj deserializexmlstringtoobjectstringarray0 stringarray1 consolewritelineoutput consolewriteline region int consolewritelineobject intoutobj endregion region string consolewritelineobject stringoutobj endregion region list string temparray list list listoutobj foreach string pair in list temparray pairsplit consolewritelinestringformatkey0 value1 temparray0 temparray1 endregion consoleread private static string serializeobjecttoxmlstringobject obj xmltextwriter writer new xmltextwriternew memorystream encodingutf8 writerformatting formattingindented xmlserializer serializer new xmlserializerobjgettype serializerserializewriter obj memorystream stream memorystreamwriterbasestream string xmlstring utf8bytearraytostringstreamtoarray string objecttype objgettypefullname return new stringxmlstring objecttype private static object deserializexmlstringtoobjectstring xmlstring string objecttype memorystream stream new memorystreamstringtoutf8bytearrayxmlstring xmlserializer serializer new xmlserializertypegettypeobjecttype object obj serializerdeserializestream return obj private static string utf8bytearraytostringbyte characters utf8encoding encoding new utf8encoding return encodinggetstringcharacters private static byte stringtoutf8bytearraystring pxmlstring utf8encoding encoding new utf8encoding return encodinggetbytespxmlstring,['c#'] +10451,determine list of event handlers bound to event i have a winforms form that would not close in onformclosing ecancel is set to true i am guessing that some object in my application has bound to the closing or formclosing event and is blocking the close to find out i would like to determine what delegates are bound to one of these eventsis there a way to determine the list of handlers bound to an event ideally i would do this via the visual studio debugger but can write code in the application to find the handlers if necessary understanding that an event is like a hidden private field i have navigated through the debugger to the nonpublic fields for the windowsformsform ancestor of my form but to no avail,['c#'] +10452,change the alpha value of a bufferedimage how do i change the global alpha value of a bufferedimage in java ie make every pixel in the image that has a alpha value of 100 have a alpha value of 80,['java'] +10462,how do i include class files in my project in eclipse java hey all i am working on a project for school where we are given the class file but not the source to include in our code i am using eclipse and i want to include the file in my project so i can instantiate objects from it and use it the file is tokenizerimplclass and i want to use it like this tokenizerimpl tokenizer new tokenizerimplfooi put the file in my project folder and eclipse says that tokenizeimpl cannot be resolved as a type which i assume means it cannot find the class or source i tried putting it in the bin folder of the project and got the same error google search and so search did not seem to answer this so i will give it a shot how do i do this oh wise ones edit oh dear i found the problem was something else entirely these solutions worked fine but i just forgot to create the tokenizer interface that tokenizerimpl implements doh thanks for all your help though i did learn a lot about eclipse,['java'] +10467,how to add native library to javalibrarypath with eclipse launch instead of overriding it i got a native library that needs to be added to javalibrarypath with jvm argument djavalibrarypathpath i can set the path as i wantmy problem is that my other library pentaho reporting searches fonts based on the default javalibrarypath including system directories etc and the manual setting overrides the default pathso how can i add a path entry to the default javalibrarypath instead of overriding it which seems to be done with djavalibrarypath i wouldnt want to add the default path by hand which wouldnt be nice for the sake of deploymentedit sorry for missing details i am working with eclipse the deployment is done with jnlp and there i can use nativelib under resources,['java'] +10484,how to change the popup position of the jquery datepicker control any idea how to get the datepicker to appear at the end of the associated text box instead of directly below it what tends to happen is that the text box is towards the bottom of the page and the datepicker shifts up to account for it and totally covers the text box if the user wants to type the date instead of pick it they cannot i would rather have it appear just after the text box so it does not matter how it adjusts verticallyany idea how to control the positioning i did not see any settings for the widget and i have not had any luck tweaking the css settings but i could easily be missing something,"['javascript', 'jquery']" +10486,android sms content contentsmssent i am having a problem reading the sms messages from the devicewhen acquiring a content provider for the uri contentsmsinboxeverything is fine i can read the person column to find the foreign keyinto the people table and ultimately reach the contact and theirnamehowever i also want to traverse the sent messages too when readingfrom contentsmssent the person field always appears to be 0 isthis the correct field to be reading to locate the recipient data forthe sent message if so any idea why mine is always 0all my testing has been done in the emulator and i have created 3contacts i have sent messages to those contacts from the emulator inthe normal manner youd send a messagejust to reiterate i can see the 4 sent messages and read theassociated body text my problem is that i cannot seem to read theperson id and hence i cannot work out who the recipient isany help would be greatly appreciatedmany thanksmartin,['android'] +10503,whats the advantage of this indirect function call i found the following code in a libraryclass bar public bool fooint i return foo i private virtual bool foo int i 0now i am wondering why would you use this indirection could there be any reasons why the above would be better than the simple alternativeclass bar public virtual bool fooint i 0,['c++'] +10505,whats the deal with a leading underscore in php class methods while looking over various php libraries i have noticed that a lot of people choose to prefix some class methods with a single underscore such aspublic function fooinstead ofpublic function fooi realize that ultimately this comes down to personal preference but i was wondering if anyone had some insight into where this habit comes frommy thought is that it is probably being carried over from php 4 before class methods could be marked as protected or private as a way of implying do not call this method from outside the class however it also occurred to me that maybe it originates somewhere a language i am not familiar with or that there may be good reasoning behind it that i would benefit from knowingany thoughts insights andor opinions would be appreciated,['php'] +10510,c nested try catch statements or methods simple best practice questionshould you nest try catch statements or just use methodsfor instance if you have a method that opens a file does work and closes the file you would have the open and close outside the try catch or rather the close in the finally blocknow if your open method fails the method would assert right so should your wrap that in a try catch block or should that be called from another method which in turn as a try catch block,['c#'] +10513,iphone sdk uitextfield with button for contacts in some applications like mail when you have a uitextfield there is a little button to the right when you tap it a modal view controller comes up which you can select a phone number address etc from and it will appear in the text field i was wondering how to implement this in my own app thanksisaac,['iphone'] +10515,how to set up java to use user specific certificates for eclipse i cannot believe i am the only person to run up against this problem i have been googling for hours and have not had any luck the java security documentation does not seem to address pkcs12 certificates thoroughlyi am trying to setup java for user specific pkcs12 certificates among other things this will be used so that in eclipse i can access a trac server that is authenticated via certificates i am using the trac mylyn integration plugin for eclipsehere is the setupuser home directories are at homemultiuser mount at centraleach user has a personal certificate at userp12password for personal certificates is pass1234the users password is stored in a 0400 file at passwordtxta readonly trust store for the ca is at centralcajksno password for the truststorejdk 16 installed at centraljdk 160eclipse 34 installed at centraleclipse 340java homecentraljdk 160java home is set to the jdk location because eclipse needs thiseclipse homecentraleclipse 340jre lives at java homejreeach user has a javapolicy filethere is a trac server running at the trac server authenticates using certificatesnow i want to be able to have each user simply modify some file that they own like the javapolicy file for example and be able to launch the central eclipse application and access the trac repository seems simple enoughright now the only way i can get this to work is to edit the eclipse homeeclipseini file and add djavaxnetsslkeystorehomeuseruserp12djavaxnetsslkeystoretypepkcs12djavaxnetsslkeystorepasswordpass1234djavaxnetssltruststorecentralcajksok that works but there are two problems with iteach user has to have their own ecipse install or can eclipse read that from a user fileit is eclipse specific i would ultimately like to have this as a java configurationalso i remember from some time back that you can edit the java homejrelibsecurityjavasecurity file and addkeystorehomeuseruserp12keystoretypepkcs12keystorepasswordpass1234truststorecentralcajksbut eclipse does not seem to pick that up could it be because my java home points to a jdk and not the jdks nested jrei have seen the java pkcs11 reference that references the following propertieskeystoreurlnone keystoretypepkcs11 keystorepasswordurlsome pin url there was another reference i saw that said you could edit the javapolicy file to includekeystore filehomeuseruserp12 pkcs12 sunjssekeystorepasswordurl filehomeuserpasswordtxtbut that does not get picked up either maybe it actually does work and its not getting read for the same reason the javasecurity file does not work or maybe it just does not work at allsome system properties i have seenjavaxnetsslkeystorehomeuseruserp12javaxnetsslkeystoretypepkcs12javaxnetsslkeystorepasswordpasswordjavaxnetsslkeystoreprovidersunjssejavaxnetssltruststorehomeusercajksjavaxnetssltruststoretypejksjavaxnetssltruststorepasswordjavaxnetssltruststoreprovidersunso right now i guess i am stuck with having each user to have their own eclipse intall i know it sounds like a complicated setup but this should not really have anything to do with eclipse as far as the certificate setup its really a java setup for user specific certificatesany ideas,['java'] +10527,calculate a running total in mysql i have this mysql queryselect dayofyeardate as d count from orders where haspaid 0group by dorder by dwhich returns something like thisd count 20 5 21 7 22 12 23 4 what i would really like is another column on the end to show the running totald count 20 5 5 21 7 12 22 12 24 23 4 28 is this possible,"['mysql', 'sql']" +10529,uibarbuttonitem with color is it possible to have a red uibarbuttonitem,['iphone'] +10536,can there be more than one awt event queue i have got a thread dump of an applet running on jvm 160 12 in opera 964 build 10487 and it shows three event queues as far as i know the java swing event handling is single threaded did this change in any recent updatemy problem is that multiple event queues will tend to cause deadlocks since i have got some more locks than only the gui treelock,['java'] +10544,zend framework form with jquery any one a idea how to simply create a form with zend form and jquery i want to use zend form to validate the form so i do not have to dual script the form in javascript and phpthank youivo trompert,"['php', 'jquery']" +10550,decent javascript ide what is a decent ide for developing javascript i will be writing both client side stuff and writing for rhino ideally it needs to run on mac osx although something that runs on windows too would be niceadditionalhaving had a play with both js2 and aptana i think i will be continuing to use aptana mainly because i find emacs a bit hard to get my head round although i did think that the error hilighting in js2 was better than that in aptanai am still looking for a way to visually debug my js code that is running atop rhino,['javascript'] +10553,deep clone utility recomendation is there any utility for deep cloning for java collectionsarrayslistsmapsnote prefer some solution without usage of serialization but with use of objectclone method i can be sure that my custom object will implement clone method and will use only javastandard classes that are cloneable,['java'] +10575,sorting dropdown list using javascript i want to sort the drop down items using javascriptcan anyone tell me how to do this,['javascript'] +10580,specifying tabwidth is it possible to define the tabwidth when whitespace is thisplayed say within a pre tag or something i cannot find anything to do this with css but this seems like it would be a pretty common thing to want to doin my case the tab width is so wide that it causes some of my code snippets on a page to be too wide if i could somehow shorten the tabwidth to make it fit without scrollbars it would make things much easier i suppose i could just replace the tabs with spaces but ideally i would love to find a way to do this without doing that,"['html', 'css']" +10585,the benefits of using function pointers i have been programming for a few years now and have used function pointers in certain cases what i would like to know is when is it appropriate or not to use them for performance reasons and i mean in the context of games not business softwarefunction pointers are fast john carmack used them to the extent of abuse in the quake and doom source code and because he is a genius i would like to use function pointers more but i want to use them where they are most appropriate these days what are the best and most practical uses of function pointers in modern cstyle languages such as c c c and java etc,"['c#', 'c++', 'c']" +10588,full command line as it was typed i want to get the full command line as it was typed this joinsysargv does not work here deletes double quotes also i prefer not to rejoin something that was parsed and splitedany ideas thank you in advance,['python'] +10589,how to tell if a connection is dead in python i want my python application to be able to tell when the socket on the other side has been dropped is there a method for this,['python'] +10602,whats the most efficient way to make bitwise operations in a c array i have a c array likechar byte array10and another one that acts as a maskchar byte mask10i would like to do get another array that is the result from the first one plus the second one using a bitwise operation on each bytewhats the most efficient way to do thisthanks for your answers,['c'] +10606,handling objectthisposedexception correctly in an ithisposable class hierarchy when implementing ithisposable correctly most implementations including the framework guidelines suggest including a private bool thisposed member in order to safely allow multiple calls to thispose thisposebool as well as to throw objectthisposedexception when appropriatethis works fine for a single class however when you subclass from your thisposable resource and a subclass contains its own native resources and unique methods things get a little bit tricky most samples show how to override diposebool thisposing correctly but do not go beyond that to handling objectthisposedexceptionthere are two questions that i have in this situationfirstthe subclass and the base class both need to be able to track the state of thisposal there are a couple of main options i know of 1 declare private bool thisposed in both classes each class tracks its own thisthisposed and throws as needed2 use protected bool thisposed get private set instead of a field this would let the subclass check the thisposed state3 provide some protected helper method to check the thisposed state and throw by pulling the current type name via reflection if the object is thisposedthe advantages as thisadvantages i see to each by option are1 this smells to me since it contains duplicated booleans but seems to work fine i often use this when subclassing other code2 this takes out the duplicated booleans but is not the way the design guidelines books are written etc this is what i typically use though since it keeps it a single point for state3 this seems like the cleanest option to me but does not appear in standard guidelines it may be a little less expected of an approach than others from users of the classi at one point or another have tried using all three of these approaches i would like to know advantages and thisadvantages to the three approaches as well as any other ideas for a cleaner better way to handle this what choice would you make in handling this and whysecondwhen throwing the objectthisposedexception what do you use for the name argument i know the typical method call isthrow new objectthisposedexceptiongettypefullnamethere is a comment on this page from a microsoft employee suggesting that implementing the concrete clas full name is the appropriate usagein the third option above this would be the only meaningful choice however if the class implements the throwing itself you could potentially return the name of the class that defines the method that was called ie the base class could return the base clas name not the concrete subclassi do not think this is a good idea but i ran into this on some code written by somebody else are there advantages or thisadvantages to having the name of the class implementing the method returned,"['c#', '.net']" +10629,split old net code into designer partial class i am working on an older net code base that has all the designer code stuffed into the same code file as my code pre partial classesis there a mechanism to tell visual studio 2008 to go back and refactor designer code into a xdesignercs partial class file,['.net'] +10631,net setup projects using visual studio 2008 when you create a setup project for a windowsconsole application you find that there are two outputssetupexemsiwhat does setupexe and msi do which one should be used for installationi have seen that i can install the application using both but setupexe is fairly small file compared to the msi file questionsif i have to ship to the client i cannot send two files whats the best approach to merge these two files into one setup file i have read that setupexe is a bootstrapper which checks the net framework and then calls the msi file is it correcti could not test for the unavailability of net framework because i am a net developer and also my team works on net and have net installed i did not want to risk the visual studio by uninstalling the net framework and testing the setup application how does it install net framework it is 200 mb odd but my setup is less than 3 mb does it give a option to download or somethingany help appreciatedthanks,['.net'] +10640,ampersand operator in a sql server where clause sorry for the very basic question what does the operator do in this sqlwhere scattributes 1 0 sc is an alias for a table which contains a column attributesi am trying to understand some sql in a report and that line is making it return 0 entries if i comment it out it works i have limited sql knowledge and i am not sure what the 1 is doing,['sql'] +10641,how do can you make redirect to use a different http request at the end of one of my controller actions i need to redirect to a page that only accepts put requests i have been trying to figure out how to get redirect to to use a put request but to no success is this possible or is there another way to accomplish this,['ruby-on-rails'] +10642,jquery gettime function is it possible to create a jquery function so that it gets current date and time i have been looking around documentation but have not found anything so far,['jquery'] +10647,application to reverse engineer mysql postgresql db is there an application to reverse engineer an existing database in mysql andor postgre i am interested in obtaining the db diagram from an existing one similar as it can be done in mssql server,['mysql'] +10655,cascading style sheets use id or class when styling specific html elements i tend to always use the class attribute the css code looks cleaner imowhy do both exist which one should you use and when,"['html', 'css']" +10659,performance of inner join compared to cross join the effect of issuing an inner join is the same as stating a cross join with the join condition in the whereclause i noticed that many people in my company use cross joins where i would use inner joins i did not notice any significant performance gain after changing some of these queries and was wondering if it was just a coincidence or if the dbms optimizes such issues transparently mysql in our case and here a concrete example for thiscussionselect userfrom user addresswhere useraddressid addressidselect userfrom userinner join address on useraddressid addressid,['sql'] +10665,tips for managing a large number of files there are some very good questions here on so about file management and storing within a large projectstoring images in db yea or naywould you store binary data in database or in file systemthe first one having some great insights and in my project i have decided to go the file route and not the db routea major point against using the filesystem is backup but in our system we have a great backup scheme so i am not worried about thatthe next path is how to store the actual files and i have thought about having the files location static at all times and create a virtual directory system in the database side of things so links to the file do not changethe system i am building will have one global file management so all files are accessible to all users but many that have gone the file route talk about physical directory size if all the files are within one directory for exampleso my question is what are some tips or best practice methods in creating folders for these static files or if i should not go the virtual directory route at allthe project is on the lamp stack php if that helps at all,['php'] +10675,how does sizeofarray work how does c find at run time the size of array where is the information about array size or bounds of array stored,['c'] +10678,can i detect ie6 with php is there a way to use php to detect if the page is being loaded using ie6,['php'] +10680,simple crud generator for c i am looking for a simple crud or dal generator for c i do not want anything heavyweight since i only have a couple of tables in a sql server 2008 databaseany suggestions i know nettiers but it is way too much for what i needthanksupdate i tried linq to sql and it does not work well for my needs,['c#'] +10681,comparing string to integer gives strange results i am really confused as to why this operation works can someone explain ittest1 d85d1d81b25614a3504a3d5601a9cb2etest2 3581169b064f71be1630b321d3ca318fif test1 0 echo test 1 is equalif test2 0 echo test 2 is equal returns test 1 is equalfor clarification i am trying to compare the string 0 to the test variables i already know to fix the code i can just enclose as i should have the 0 in si am wondering if this is a php bug a server bug or somehow a valid operation according to this should not have workededit scratch that apparently it does mention that loose comparisons between string and 0 is true but i still do not know whyedit 2 i have revised my question why does the test2 value of 3581169b064f71be1630b321d3ca318f not work,['php'] +10687,java pattern to match any sequence of characters except a given list how do i write a pattern java to match any sequence of characters except a given list of wordsi need to find if a given code has any text surrounded by tags like besides a given list of wordsfor example i want to check if there are any other words besides one and two surrounded by the tag this is the first tag spanonespan and this is the third spanthreespanthe pattern should match the above string because the word three is surrounded by the tag and is not part of the list of given words one two,['java'] +10694,what is the use of passing const references to primitive types in a project i maintain i see a lot of code like this for simple getset methodsconst int myclassgetfoo return m foo void myclasetfooconst int foo m foo foo what is the point in doing that instead of the followingint myclassgetfoo return m foo removed const and void myclasetfooconst int foo m foo foo removed passing a reference to a primitive type should require the same or more effort as passing the types value itself rightit is just a number after allis this just some attempted microoptimization or is there a true benefit,['c++'] +10698,what are the most common and often overlooked causes of memory leaks in managed net applications please can anyone recommend a quick checklist best practice guide to help us avoid simple but subtle mistakes that cause could cause memory leaks in net appsi find it difficult and quite painful to begin searching for the cause of a memory leakage when i am in the testing phase of a projectif there are rules of thumb to completely guide against memory leaks in managed applications i implore you to please share your experiencethanksi thought managed applications are suppose to be memory managed ie the gc why then do we still find leakages in purely managed code,['.net'] +10705,remove project jars from project explorer view in eclipse the list of jars just takes up too much space can i collapse it or hide it,['java'] +10708,how do i print an unsigned char as hex in c using ostream i want to work with unsigned 8bit variables in c either unsigned char or uint8 t do the trick as far as the arithmetic is concerned which is expected since afaik uint8 t is just an alias for unsigned char or so the debugger presents itthe problem is that if i print out the variables using ostream in c it treats it as char if i haveunsigned char a 0unsigned char b 0xffcout a is hex a b is hex b endlthen the output isa is b is 377instead of a is 0 b is ffi tried using uint8 t but as i mentioned before that is typedefed to unsigned char so it does the same how can i print my variables correctlyedit i do this in many places throughout my code is there any way i can do this without casting to int each time i want to print,['c++'] +10715,transactionscope and multithreading i was wondering how you would use the transactionscope class in the correct way when you are dealing with multithreadingwe create a new scope in our main thread and then we spawn of a couple of worker threads and we want these to participate in the main scope so that for example the rollback is called on each worker if the scope is never completedi read something about transactionscope using the threadstaticattribute internally which made the above impossible very difficult could someone verify either way if we run out code in a syncrhonized fashion then the rollbacks work ie the inner transactions are able to participate in the main transaction but not if we switch over to a threaded executionthanks,['.net'] +10723,customize cout how can i derive a class from cout so that for example writing to itnew cout messagewould be equivalent tocout function message end of message endl,['c++'] +10729,regarding javascript for loop voodoo i was for quite some time under the impression that a for loop could exist solely in the following formatfor initializer stop condition incdecrementer code this is however most definitely not the case take a look at this javascript implementation of the fisheryates shuffleshuffle functiono for var j x i olength i j parseintmathrandom i x oi oi oj oj x return o this little snippet completely blows my mind how in the world is so much going on inside a simple for loop declaration i mean it does not even open a brace all of the magic is being done right there inside the for statement it would be absolutely wonderful if somebody could provide a relatively thorough explanation as to how in the world this voodoo is doing what it does much appreciated in advance,['javascript'] +10732,go to the end of the c function in vim if i am in the middle of the function i would like go to the very end of it in vim i run into this problem as we sometimes have function of 500 lines long do not ask why i use vim gvim,['c++'] +10733,what is the question marks significance in mysql at where column i am thissecting some code and came across this sql select page authorname as author updatorname as updator from table prefixpage as page left join table prefixuser as author on authorid pagecreated by id left join table prefixuser as updator on updatorid pageupdated by id where slug and parent id and status idpagestatus reviewed or status idpagestatus published or status idpagestatus hiddeni am wondering what the does in the where statement is it some sort of parameter holder,['mysql'] +10734,how can i access runatserver asp element using javascript it seems everyone is doing this in code posts etcbut i dont know how whenever i try to manipulate an asp element using javascript i get a element is null or document is undefined etc errorjavascript works fine usuallybut only when i add the runatserver attribute does the element seem invisible to my javascriptany suggestions would be appreciatedthanks andrew,"['asp.net', 'javascript']" +10741,tabcompletion in python interpreter in os x terminal several months ago i wrote a blog post detailing how to achieve tabcompletion in the standard python interactive interpretera feature i once thought only available in ipython i have found it tremendously handy given that i sometimes have to switch to the standard interpreter due to ipython unicode issuesrecently i have done some work in os x to my thiscontent the script does not seem to work for os xs terminal application i am hoping some of you with experience in os x might be able to help me troubleshoot it so it can work in terminal as welli am reproducing the code belowimport atexitimport ospathtry import readlineexcept importerror passelse import rlcompleter class irlcompleterrlcompletercompleter this class enables a tab insertion if there is no text for completion the default tab is four spaces you can initialize with t as the tab if you wish to use a genuine tab def init self tab selftab tab rlcompletercompleter init self def completeself text state if text readlineinsert textselftab return none else return rlcompletercompletercompleteselftextstate you could change this line to bind another key instead tab readlineparse and bindtab complete readlineset completerirlcompletertcomplete restore our commandline history and save it when python exitshistory path ospathexpanduserpyhistoryif ospathisfilehistory path readlineread history filehistory pathatexitregisterlambda xhistory path readlinewrite history filexnote that i have slightly edited it from the version on my blog post so that the irlcompleter is initialized with a true tab which seems to be what is output by the tab key in terminal,['python'] +10749,finding your applications url with only a servletcontext i am writing a java web app using spring mvc i have a background process that goes through the database and finds notifications that must be emailed to my users these email messages need to include hyperlinks to the application this seems like a fairly common pattern for a web app but i am having troublehow do i derive my applications fully qualified url with server name and context path i do not have access to any of the methods in httpservletrequest because i am running this as a background process not in response to a web request the best i can do is get access to servletcontextcurrently i am putting the base url into a configuration file and reading it at startup but this application is going to be licensed and deployed to customers application servers and if possible i would like them not to have to configure this manually,['java'] +10753,sdlc opengl program how do i stop sdl from catching sigint i am using sdl for an opengl application running on linux my problem is that sdl is catching sigint and ignoring it this is a pain because i am developing through a screen session and i cannot kill the running program with ctrlc the program the computer is running on is connected to a projector and has no input devicesis there a flag or something i can pass to sdl so that it does not capture sigint i really just want the program to stop when it receives the signal ie when i press ctrlc,['c++'] +10761,different ways of loading a file as an inputstream whats the difference betweeninputstream is thisgetclassgetclassloadergetresourceasstreamfilenameandinputstream is threadcurrentthreadgetcontextclassloadergetresourceasstreamfilenameandinputstream is thisgetclassgetresourceasstreamfilenamewhen are each one more appropriate to use than the othersthe file that i want to read is in the classpath as my class that reads the file my class and the file are in the same jar and packaged up in an ear file and deployed in websphere 61,['java'] +10768,how change list data to iqueryable data possible duplicateilistt to iqueryablet i have a list data but i want a iqueryable data is it possible from list data to iqueryable datashow me code,['.net'] +10772,can java annotations be unit tested i have recently started creating my own annotations and to sport tddbdd i would want to unit test my annotations to create a clear specification for them however since annotations are basically merely fancy interfaces which to my knowledge cannot be really instantiated directly is there any way short of reflection to unit test an annotation,['java'] +10780,dictionary enumeration in c how do i enumerate a dictionarysuppose i use foreach for dictionay enumeration i cannot update a keyvalue pair inside foreach so i want some other method,"['c#', '.net']" +10782,private member access java is the private member access at the class level or at the object level if it is at the object level then the following code should not compile class privatemember private int i public privatemember i 2 public void printi systemoutprintlni is i public void messwithiprivatemember t ti 2 public static void main string args privatemember sub new privatemember privatemember obj new privatemember objprinti submesswithiobj objprinti please clarify if accessing the member i of obj within the messwithi method of sub is valid,['java'] +10792,which browsers have problems caching xmlhttprequest responses do any of the currently popular browsers have particular problems caching xmlhttprequest responses that i need to be aware ofi would like to be able to include xmlhttprequest queries on every page as a method of dynamically loading content ie json or behaviour like evaled javascript relevant to the type of page but wanted to make sure that the resources it receives from the server could be cached if the server sent the right headersi was concerned to read this article which mentions that browsers such as firefox 11 do not cache any content obtained via xmlhttprequest and that it always requests new data is sent completely with cachecontrol and no ifmodifiedsince regardless of headers sent by the serverobviously that article is very old i do not even remember a firefox 11 so what are the considerations i need to make for current popular browsers and is there any trick for when i specifically want responses to be cachedto clarify my question by caching i mean clientside caching where the server issues freshness information in the form of a cachecontrol maxage directive or an expires header and the browser stores a copy of the response in its cache along with an expiry date so that future requests for the same resource issued from subsequent pages can be satisfied from the browser cache without the need for any contact with the server at all all major browsers do this correctly for most content but i have heard that firefox cannot do this for xmlhttprequest content what i am asking is if anyone knows of cases where any of the modern browsers do not cache responses according to the spec when using xmlhttprequest,['javascript'] +10794,how can i programmatically get the mac address of an iphone does anyone know how to programmatically get an iphones mac address and ip address,"['iphone', 'objective-c']" +10797,do i need to explicitly call the base virtual destructor when overriding a class in c with a virtual destructor i am implementing the destructor again as virtual on the inheriting class but do i need to call the base destructorif so i imagine it is something like thismychildclassmychildclass virtual in header call to base destructor thismybaseclassmybaseclass some destructing specific to mychildclassam i right,['c++'] +10810,sql injections with prepared statements if i remember correctly i think jeff has mentioned in the stack overflow podcast a possible weakness in sql prepared statements i am wondering what kinds of weaknesses did he refer to was it possibly just about inappropriate usage thereof or something more sinisterthe podcast to my remembering did not go deeper into the subject it was just a passbyremark,['sql'] +10817,how do i make an http request using cookies on android i would like to make an http request to a remote server while properly handling cookies eg storing cookies sent by the server and sending those cookies when i make subsequent requests it would be nice to preserve any and all cookies but really the only one i care about is the session cookiewith javanet it appears that the preferred way to do this is using javanetcookiehandler abstract base class and javanetcookiemanager concrete implementation android has javanetcookiehandler but it does not seem to have javanetcookiemanageri could code it all by hand by inspecting http headers but it seems like there must be an easier waywhat is the proper way to make http requests on android while preserving cookies,"['java', 'android']" +10826,how to return generic dictionary in a webservice i want a web service in c that returns a dictionary according to a searchdictionaryint string getvaluesstring search the web service compiles fine however when i try to reference it i get the following erroris not supported because it implements idictionaryawhat can i do in order to get this working any ideas not involving return a datatable,['c#'] +10837,advice on a better way to extend c stl container with userdefined methods i inherited from c stl container and add my own methods to it the rationale was such that to the clients it will look act a regular list yet has applicationspecific methods they can readily be called this works fine but i have read numerous posts about not inheriting from stl can someone provide a concrete advice of how i might write the code below in a better way class item int a int b int c int specialb return a b c class itemlist public stdvectoritem int maxa if thisempty throw int maxa this0a for int idx 1 idx thissize idx if thisidxa maxa maxa thisidxa return maxa int specialb if thisempty throw int specialb this0specialb for int idx 1 idx thissize idx if thisidxspecialb specialb specialb thisidxc return specialb int avgc if thisempty throw int csum 0 for int idx 0 idx thissize idx csum thisidxc return csum thissize average edit thanks for a bunch of thoughtful answers i will create helper functions instead and from now on will never inherit from stl containers,['c++'] +10839,why are doctype declarations split on two lines i know there is more important questions to thiscuss probably but at the cost of appearing a fool i would like an answer take this for instancedoctype html public w3cdtd html 401enis it to comply to the 80 column standard also i normally use single quotes in my html as they are easier on the eye does it make any difference to browsers will it send ie6 in quirks mode putting it on one line and singlequoting attributesthanks,['html'] +10841,best way to profileoptimize a website on googles appengine i am currently trying to optimize my website which run on the googles appengine it is not an easy task because i am not using any powerful tooldoes anyone have experience in optimizing python code for this purposehave you find a good python profiler,['python'] +10843,fastest way to format a phone number in c what is the fastest way to format a string using the us phone format x x using cmy source format is a string,['c#'] +10849,where to stopdestroy threads in android service class i have created a threaded service the following waypublic class tcpclientservice extends service overridepublic void oncreate measurements new linkedliststring enabledatasending overridepublic ibinder onbindintent intent todo replace with service binding implementation return nulloverridepublic void onlowmemory measurementsclear superonlowmemoryoverridepublic void ondestroy measurementsclear superondestroy try senddatathreadstop catchexception e private runnable backgrounsenddata new runnable public void run dosenddata private void enabledatasending senddatathread new threadnull backgrounsenddata send data senddatathreadstart private void addmeasurementtoqueue ifmeasurementssize 100 string measurement packdata measurementsaddmeasurement private void dosenddata whiletrue try ifmeasurementsisempty threadsleep10 continue logdtcp c connecting socket socket new socket socketsettcpnodelaytrue socketconnectnew inetsocketaddreserveraddress portnumber 30 socketconnectnew inetsocketaddreserveraddress portnumber ifsocketisconnected throw new exceptionserver unavailable try logdtcp c sending message printwriter out new printwriter new bufferedwriter new outputstreamwritersocketgetoutputstreamtrue string message measurementsremove outprintlnmessage threadsleep200 logdtcp c sent logdtcp c done connectionavailable true catchexception e logetcp s error e connectionavailable false finally socketclose announcenetworkavailabilityconnectionavailable catch exception e logetcp c error e connectionavailable false announcenetworkavailabilityconnectionavailable after i close the application the phone works really slow and i guess it is due to thread termination failuredoes anyone know what is the best way to terminate all threads before terminating the application,"['java', 'android']" +10857,explicit nulling in what situations in java is explicit nulling useful does it in any way assist the garbage collector by making objects unreachable or something is it considered to be a good practice,['java'] +10865,access events added with attachevent addeventlistener in javascript how can i access events added with attachevent addeventlistener in javascriptuse case debug events using firebugs console,['javascript'] +10875,interface naming convention this is a subjective thing of course but i do not see anything positive in prefixing interface names with an i to me thing is practically always more readable than ithingmy question is why does this convention exist then sure it makes it easier to tell interfaces from other types but wouldnt that argument extend to retaining the hungarian notation which is now widely censuredwhats your argument for that awkward i or more importantly what could be microsofts,['c#'] +10877,how to programmatically get svn revision description and author in c how do i programmatically get the revision description and author from the svn server in c,['c#'] +10887,returning json from php to javascript i have a php script that is being called through jquery ajax i want the php script to return the data in json format to the javascript heres the pseudo code in the php scriptjson foreachresult as addr foreachaddr as line json line n json nnjson basically i need the results of the two for loops to be inserted in json,"['php', 'javascript']" +10901,persisting the state column on transition using rubyistaasm acts as state machine what is the best way to persist the objects state to the database on a transition using aasm i had thought that this would happen automatically but this does not seem to be the caseedit when i manually save the object the state column does get updated but a save is not done on transitionsi cannot find much useful documentation for this plugin so if you have a suggestion for an alternative finite state machine implementation with better documentation that might help as well,['ruby-on-rails'] +10908,getting the diff between two arrays in c let us say i have these two arraysvar array1 new a b cvar array2 new a c di would like to get the differences between the two i know i could write this in just a few lines of code but i want to make sure i am not missing a built in language feature or a linq extension methodideally i would end up with the following three resultsitems not in array1 but are in array2 ditems not in array2 but are in array1 bitems that are in boththanks in advance,['c#'] +10909,how to make a window always stay on top in net i have a c winforms app that runs a macro in another program the other program will continually pop up windows and generally make things look for lack of a better word crazy i want to implement a cancel button that will stop the process from running but i cannot seem to get the window to stay on top how do i do this in c edit i have tried topmosttrue but the other program keeps popping up its own windows over top is there a way to send my window to the top every and millisecondsedit the way i solved this was by adding a system tray icon that will cancel the process by doubleclicking on it the system tray icon does no get covered up thank you to all who responded i read the article on why there is not a superontop window it logically does not work,"['c#', '.net']" +10915,what is the best resource for learning c expression trees in depth when i first typed this question i did so in order to find the duplicate questions feeling sure that someone must have already asked this question my plan was to follow those dupe links instead of posting this question but this question has not been asked before as far as i can see it did not turn up in the related questions listwhat are some of the best resources youve found articles books blog posts etc for gaining an indepth understanding of expression trees in c i keep getting surprised by their capabilities and now i am at the point where i am saying ok enough surprise i want to stop right now and get a phd in these things i am looking for material that systematically methodically covers the capabilities and then walks through detailed examples of what you can do with themnote i am not talking about lambda expressions i am talking about expression t and all the things that go with it and arise from itthanks,['c#'] +10921,referencing error to the audiotoolbox in objective c i am getting the following error in a simple roulett app where i am trying to play some wav files i am not sure what the error means because no warning flags come up in the code and i have imported here is the errorundefined symbols audioservicescreatesystemsoundid referenced from custompickerviewcontroller playwinsound in custompickerviewcontrollero custompickerviewcontroller spin in custompickerviewcontrollero audioservicesplaysystemsound referenced from custompickerviewcontroller playwinsound in custompickerviewcontrollero custompickerviewcontroller spin in custompickerviewcontrollero ld symbols not found collect2 ld returned 1 exit status audioservicescreatesystemsoundid referenced from custompickerviewcontroller playwinsound in custompickerviewcontrollero custompickerviewcontroller spin in custompickerviewcontrollero audioservicesplaysystemsound referenced from custompickerviewcontroller playwinsound in custompickerviewcontrollero custompickerviewcontroller spin in custompickerviewcontrollero ld symbols not found collect2 ld returned 1 exit statusand here is the codeimport custompickerviewcontrollerhimport audiotoolboxaudiotoolboxhimplementation custompickerviewcontrollersynthesize pickersynthesize winlabelsynthesize column1synthesize column2synthesize column3synthesize column4synthesize column5synthesize button voidshowbutton buttonhidden novoidplaywinsound nsstring path nsbundle mainbundle pathforresourcewin oftypewav systemsoundid soundid audioservicescreatesystemsoundidcfurlrefnsurl fileurlwithpathpath soundid audioservicesplaysystemsound soundid winlabeltext win self performselectorselectorshowbutton withobjectnil afterdelay15ibactionspinidsender bool win no int numinrow 1 int lastval 1 for int i 0 i 5 i int newvalue random selfcolumn1 count if newvalue lastval numinrow else numinrow 1 lastval newvalue picker selectrownewvalue incomponenti animated yes picker reloadcomponenti if numinrow 3 win yes buttonhidden yes nsstring path nsbundle mainbundle pathforresourcecrunchoftypewav systemsoundid soundid audioservicescreatesystemsoundidcfurlref nsurl fileurlwithpathpath soundid audioservicesplaysystemsoundsoundid if win self performselectorselectorplaywinsound withobject nil afterdelay 5 else self performselectorselectorshowbutton withobject nil afterdelay 5 winlabeltext,['objective-c'] +10924,whats the best way to resolve a combinatorial explosion of interactions one of the things i am working on right now has some similarities to a game for purposes of illustration i am going to explain my problem using an example drawn from a fictitious hypothetical gamelet us call it deathblaster 4 the deathening in db4 you have a number of ship objects which periodically and randomly encounter phenomena as they travel a given phenomenon may have zero one or more effects on a ship that encounters it for example we might have four kinds of ships and three kinds of phenomena phenomena ships gravitywell blackhole nebulafield redship 20 speed 50 power 50 shieldblueshipa no effect invulnerable death effects of variousgreenship 20 speed death 50 shield phenomena on shipsyellowship death 50 power no effect additionally effects may interact with each other for example a greenship that is in both a gravitywell and a nebulafield may derive some kind of synergy between the generated speedeffect and shieldeffect in such cases the synergistic effect is itself an effect for example there might be a powerlevelsynergyeffect that results from this interaction no information other than the set of effects acting on a ship is needed to resolve what the final result should beyou may begin to see a problem emerging here as a naive first approach either every ship will have to know how to handle every phenomenon or every phenomenon will have to know about every ship this is obviously unacceptable so we would like to move these responsibilities elsewhere clearly there is at least one external class here perhaps a mediator or visitor of some sortbut whats the best way to do that the ideal solution will probably have these propertiesjust as easy to add a new ship as it is to add a new phenomenon interactions that produce no effect are the default and do not require additional code to represent convention over configurationunderstands how effects interact with each other and is capable of managing these interactions to decide what the final result will bei have already decided what my approach will be i think but i am interested to hear what the bestdesign consensus is where would you start what avenues would you explore followup update thanks for your responses everybody heres what i wound up doing my main observation was that the number of different effects seems to be small relative to the number of possible phenomena ships interactions that is although there are many possible combinations of interactions the number of kinds of results of those interactions is a smaller numberyou can see that for example although there are 12 interaction combinations in the table there are only five kinds of effects modifications to speed modifications to power modifications to shield invulnerability deathi introduced a third class the interactionresolver to determine the result of interactions it contains a dictionary that maps shipphenomenon pairs to effects which are basically a delegate that performs the effect and some metadata each ship is handed an effectstack corresponding to the effects it is experiencing when the result of computing the interaction is completeships then use the effectstack to determine the actual result of the effects on them by adding modifiers to their existing attributes and propertiesi like this becauseships never need to know about phenomenathe complexity of the shipphenomena relationship is abstracted into the interactionresolverthe details of how to resolve multiple and possibly complex effects is abstracted away by the interactionresolver ships only have to apply the effects as necessarythis enables additional useful refactorings for example the way in which a ship processes effects could be differentiated by making an effectprocessorstrategy the default might be to process all effects but say a boship might ignore minor effects by having a different effectprocessorstrategy,['c#'] +10926,synchronizing a timer to prevent overlap i am writing a windows service that runs a variable length activity at intervals a database scan and update i need this task to run frequently but the code to handle is not safe to run multiple times concurrentlyhow can i most simply set up a timer to run the task every 30 seconds while never overlapping executions i am assuming systemthreadingtimer is the correct timer for this job but could be mistaken,['c#'] +10928,using interfaces on abstract classes in c i am learning c coming from c and have run into a walli have an abstract class abstractwidget an interface idoescoolthings and a class which derives from abstractwidget called realwidgetpublic interface idoescoolthings void docoolpublic abstract class abstractwidget idoescoolthings void idoescoolthingsdocool consolewritei did something cool public class realwidget abstractwidgetwhen i instantiate a realwidget object and call docool on it the compiler gives me an error saying realwidget does not contain a definition for docooli can cast realwidget object to an idoescoolthings and then the call will work but that seems unnecessary and i also lose polymorphism abstractwidgetdocool will always be called even if i define realwidgetdocooli imagine the solution is simple but i have tried a variety of things and for the life of me cannot figure this one out,['c#'] +10935,advantage of using threadstart vs queueuserworkitem in multithreaded net programming what are the decision criteria for using threadpoolqueueuserworkitem versus starting my own thread via new thread and threadstart in a server app let us say an aspnet app or a wcf service i think the threadpool is always there and available what about in a client app like a winforms or wpf app is there a cost to spin up the thread pool if i just want 3 or 4 threads to work for a short period on some computation is it better to quwi or to threadstart,"['c#', '.net']" +10948,is there a way to override class variables in java class dad protected static string me dad public void printme systemoutprintlnme class son extends dad protected static string me sonpublic void doit new sonprintmethe function doit will print dad is there a way to make it print son,['java'] +10956,run multiple commands in one executescalar in oracle i have a batch of sql statements such as insert into insert into delete etcwhen i try to execute them against oracle it gives me this error ora00911 invalid characternow i can understand that this is because of the semicolon between the statements i tried this on sql server and it worked but in oracle no luck so faris there a way to run multiple statements against oracle by using the executescalar or some other functionduplicate,['sql'] +10963,making an entire row clickable in a gridview i have a gridview and i need to make an event fire when a row is clickedis there an existing gridview event i need to bind to to make this happen,"['c#', 'asp.net']" +10970,why is my return type meaningless i am trying to use a return type of const myclass const however i get a warningwarning 815d type qualifier on return type is meaninglessis this not a valid type i want a pointer than cannot be changed and i want the thing it points to to not be changed either,['c++'] +10976,static generic class as dictionary a static field in a generic class will have a separate value for each combination of generic parameters it can therefore be used as a dictionarytype whateveris this better or worse than a static dictionarytype whateverin other words which of these implementations more efficientpublic static class methodgentparam public static readonly actiontparam method createmethod static actiontparam createmethod orpublic static class methodgen static readonly dictionarytype delegate methods new dictionarytype delegate public static actiont getmethodt in production code this would readerwriterlock delegate method ifmethodstrygetvaluetypeoft out method methodsaddtypeoft method createmethodt return method static actiont createmethodt in particular how does the clr lookup the static fields by generic type parameter,"['c#', '.net']" +10977,google analytics why have two script blocks why does the google analytics script i add to my webpage need to come in two script blocksscript typetextjavascript var gajshost https documentlocationprotocol httpsl httpw documentwriteunescape3cscript src gajshost googleanalyticscomgajs typetextjavascript3e3cscript3escriptscript typetextjavascript try var pagetracker gat gettrackeruax pagetracker trackpageview catch err script,['javascript'] +10979,best resources for starting jython i just got my first jython and python project and i was wondering what documentation ides etc are best suited to a java buff like me i know there are a lot of questions about starting out with python so i am asking for things that might be specific to jython where should i start if it helps i am running linux and solaris only,['python'] +10982,large object heap fragmentation the cnet application i am working on is suffering from a slow memory leak i have used cdb with sos to try to determine what is happening but the data does not seem to make any sense so i was hoping one of you may have experienced this beforethe application is running on the 64 bit framework it is continuously calculating and serialising data to a remote host and is hitting the large object heap loh a fair bit however most of the loh objects i expect to be transient once the calculation is complete and has been sent to the remote host the memory should be freed what i am seeing however is a large number of live object arrays interleaved with free blocks of memory eg taking a random segment from the loh0 dumpheap 05b5b10 06351da10 address mt size05d4f92e0 064280c7c970 1614787205e45f880 01661d0 1901752 free05e62fd38 0642788d8ba8 1056 05e630158 01661d0 59848 free05ebe6348 0642788d8ba8 105605ebe6768 01661d0 6481336 free05f214d20 0642788d8ba8 105605f215140 01661d0 7346016 free05f9168a0 0642788d8ba8 105605f916cc0 01661d0 7611648 free0600591c0 0642788d8ba8 10560600595e0 01661d0 264808 freeobviously i would expect this to be the case if my application were creating longlived large objects during each calculation it does do this and i accept there will be a degree of loh fragmentation but that is not the problem here the problem is the very small 1056 byte object arrays you can see in the above dump which i cannot see in code being created and which are remaining rooted somehowalso note that cdb is not reporting the type when the heap segment is dumped i am not sure if this is related or not if i dump the marked object cdbsos reports it fine0015 dumpobj 05e62fd38name systemobjectmethodtable 0642788d8ba8eeclass 0642789d7660size 10560x420 bytesarray rank 1 number of elements 128 type classelement type systemobjectfieldsnonethe elements of the object array are all strings and the strings are recognisable as from our application codealso i am unable to find their gc roots as the gcroot command hangs and never comes back i have even tried leaving it overnightso i would very much appreciate it if anyone could shed any light as to why these small 85k object arrays are ending up on the loh what situations will net put a small object array in there also does anyone happen to know of an alternative way of ascertaining the roots of these objectsupdate 1another theory i came up with late yesterday is that these object arrays started out large but have been shrunk leaving the blocks of free memory that are evident in the memory dumps what makes me suspicious is that the object arrays always appear to be 1056 bytes long 128 elements 128 8 for the references and 32 bytes of overheadthe idea is that perhaps some unsafe code in a library or in the clr is corrupting the number of elements field in the array header bit of a long shot i knowupdate 2thanks to brian rasmussen see accepted answer the problem has been identified as fragmentation of the loh caused by the string intern table i wrote a quick test application to confirm thisstatic void main const int iterations 10 for int index 0 index iterations index string str noninterned index consoleoutwritelinestr consoleoutwritelinecontinue consoleinreadline for int index 0 index iterations index string str stringinterninterned index consoleoutwritelinestr consoleoutwritelinecontinue consoleinreadlinethe application first creates and dereferences unique strings in a loop this is just to prove that the memory does not leak in this scenario obviously it should not and it does notin the second loop unique strings are created and interned this action roots them in the intern table what i did not realise is how the intern table is represented it appears it consists of a set of pages object arrays of 128 string elements that are created in the loh this is more evident in cdbsos0 loadby sos mscorwks0 eeheap gcnumber of gc heaps 1generation 0 starts at 0x00f7a9b0generation 1 starts at 0x00e79c3cgeneration 2 starts at 0x00b210ephemeral segment allocation context none segment begin allocated size00b20 00b210 010029bc 0x004e19bc5118396large object heap starts at 0x01b210 segment begin allocated size01b20 01b210 01b8ade0 0x069de0433632total size 0x54b79c52028gc heap size 0x54b79c52028taking a dump of the loh segment reveals the pattern i saw in the leaking application0 dumpheap 01b210 01b8ade001b8a120 793040bc 52801b8a330 00175e88 16 free01b8a340 793040bc 52801b8a550 00175e88 16 free01b8a560 793040bc 52801b8a770 00175e88 16 free01b8a780 793040bc 52801b8a990 00175e88 16 free01b8a9a0 793040bc 52801b8abb0 00175e88 16 free01b8abc0 793040bc 52801b8add0 00175e88 16 free total 1568 objectsstatistics mt count totalsize class name00175e88 784 12544 free793040bc 784 421088 systemobjecttotal 1568 objectsnote that the object array size is 528 rather than 1056 because my workstation is 32 bit and the application server is 64 bit the object arrays are still 128 elements longso the moral to this story is to be very careful interning if the string you are interning is not known to be a member of a finite set then your application will leak due to fragmentation of the loh at least in version 2 of the clrin our applications case there is general code in the deserialisation code path that interns entity identifiers during unmarshalling i now strongly suspect this is the culprit however the developers intentions were obviously good as they wanted to make sure that if the same entity is deserialised multiple times then only one instance of the identifier string will be maintained in memory,"['c#', '.net']" +10990,c shorthand property question so here is a bit of syntax that i have never seen before can someone tell me what this means not sure if this is supposed to be some shorthand for an abstract property declaration or something or whatpublic class1 myvar get set for what its worth class1 is an abstract class,['c#'] +10995,how do i expand a tuple into variadic template functions arguments consider the case of a templated function with variadic template argumentstemplatetypename tret typename t tret funcconst t tnow i have a tuple t of values how do i call func using the tuple values as argumentsi have read about the bind function object with call function and also the apply function in different some nowobsolete documents the gnu gcc 44 implementation seems to have a call function in the bind class but there is very little documentation on the subjectsome people suggest handwritten recursive hacks but the true value of variadic template arguments is to be able to use them in cases like abovedoes anyone have a solution to is or hint on where to read about it,['c++'] +10997,preparedstatements and performance so i keep hearing that preparedstatements are good for performancewe have a java application in which we use the regular statement more than we use the preparedstatement while trying to move towards using more preparedstatements i am trying to get a more thorough understanding of how preparedstatements work on the client side and the server sideso if we have some typical crud operations and update an object repeatedly in the application does it help to use a ps i understand that we will have to close the ps every time otherwise it will result in a cursor leakso how does it help with performance does the driver cache the precompiled statement and give me a copy the next time i do connectionpreparestatement or does the db server help i understand the argument about the security benefits of preparedstatements and i appreciate the answers below which emphasize it however i really want to keep this thiscussion focused on the performance benefits of preparedstatementsupdate when i say update data i really mean more in terms of that method randomly being called several times i understand the advantage in the answer offered below which asks to reuse the statement inside a loop some code blah blah update some more code blah blah update public void update throws sqlexception try preparedstatement ps connectionpreparestatementsome sql pssetstring1 foobar1 pssetstring2 foobar2 psexecute finally psclose there is no way to actually reuse the ps java object and i understand that the actual connectionpreparestatement call is quite expensive which is what brings me back to the original question is this some sql preparedstatement still being cached and reused under the covers that i dont know abouti should also mention that we support several databasesthanks in advance,['java'] +10999,open source surveyquestionnaire engine for java is there an open source survey engine for java that will allow branching of questions ie question 1 has the options of a b or c and they each take you to a different set of followup questionsi have found a couple jsurveylib and socrates qe but those seem to be very tied to a guithe application that i am writing has a java backend running on glassfish and a flex frontend eventually there are plans for different fontends so the engine needs to be very independent of the gui,['java'] +11004,microsoft message queue priority flag or a separate queue i have implemented a system in c that uses the microsoft message queue systemmessaging for communication between related processes essentially a number of sender services generate messages to put in the queue and a number of receiver processes watch the queues and grab those messages when they arrivei have just been told that there are some messages that will need priority over othersmessages are likely to come in waves and there could potentially be occasions where a very large number of messages are put in the queue in one hit say a thousand or so so there could be a delay before the final message gets processedmy original thought was to have a second priority message queue which is also watched by each of the receiver processes in a different thread there would be far fewer messages in this queue so there would be less delaythen i stumbled across the messagepriority propertysoshould i use this priority flag rather than implementing another queue will it successfully and efficiently jump these messages ahead of the rest if so what conditions and side effects are there likely to be if anyor should i stick with my original plan and implement another queue for priority messages,"['c#', '.net']" +11012,what to do when you need to store a very large number i am trying to do a project euler problem but it involves adding the digits of a very large number 100using java int and long are too small thanks for any suggestions,['java'] +11017,how to make sure the code is still working after refactoring dynamic language how to make sure that code is still working after refactoring ie after variable name changein static language if a class is renamed but other referring class is not then i will get a compilation error but in dynamic language there is no such safety net and your code can break during refactoring if you are not careful enough you can use unit test but when you are using mocks it is pretty hard to know the name changes and as a consequence it may not helphow to solve this problem,"['php', 'python']" +11018,how to create a utf8 string literal in visual c 2008 in vc 2003 i could just save the source file as utf8 and all strings were used as is in other words the following code would print the strings as is to the console if the source file was saved as utf8 then the output would be utf8printfchinese traditionalprintfa a12ea c1a12printfiei e2i2 printfchinaas tradicionali have saved the file in utf8 format with the utf8 bom however compiling with vc2008 results inwarning c4566 character represented by universalcharactername uc911 cannot be represented in the current code page 932warning c4566 character represented by universalcharactername uad6d cannot be represented in the current code page 932etcthe characters causing these warnings are corrupted the ones that do fit the locale in this case 932 japanese are converted to the locale encoding ie shiftjisi cannot find a way to get vc 2008 to compile this for me note that it does not matter what locale i use in the source file there does not appear to be a locale that says i know what i am doing so do not fng change my string literals in particular the useless utf8 pseudolocale does not workpragma setlocale65001 error c2175 65001 invalid localeneither does cpragma setlocalec see warnings above in particular locale is still 932it appears that vc2008 forces all characters into the specified or default locale and that locale cannot be utf8 i do not want to change the file to use escape strings like xbfx11 because the same source is compiled using gcc which can quite happily deal with utf8 filesis there any way to specify that compilation of the source file should leave string literals untouchedto ask it differently what compile flags can i use to specify backward compatibility with vc2003 when compiling the source file ie do not change the string literals use them byte for byte as they areupdatethanks for the suggestions but i want to avoid wchar since this app deals with strings in utf8 exclusively using wchar would then require me to convert all strings back into utf8 which should be unnecessary all input output and internal processing is in utf8 it is a simple app that works fine as is on linux and when compiled with vc2003 i want to be able to compile the same app with vc2008 and have it work for this to happen i need vc2008 to not try to convert it to my local machines locale japanese 932 i want vc2008 to be backward compatible with vc2003 i want a locale or compiler setting that says strings are used as is essentially as opaque arrays of char or as utf8 it looks like i might be stuck with vc2003 and gcc though vc2008 is trying to be too smart in this instance,['c++'] +11025,capicom verify signedcode is from a trusted publisher without ui i am using capicom in a net 30 c app to check an authenticode signature on an exe file i need to make sure that the certificate is listed as a trusted publisher using signedcodeverifytrue will show a dialog if the certificate is not already trusted so the user can choose whether or not to do so however signedcodeverifyfalse is verifying the signature even if it is not from a trusted publisher presumably this is only checking that the certificate is validhow can i check that the signature on a file is from a valid and trusted certificate without the ui,['c#'] +11027,best way to programmatically configure network adapters in net i have an application written in c that needs to be able to configure the network adapters in windows i have this basically working through wmi but there are a couple of things i do not like about that solution sometimes the settings do not seem to stick and when the network cable is not plugged in errors are returned from the wmi methods so i cannot tell if they really succeeded or noti need to be able to configure all of the settings available through the network connections properties tcpip screenswhats the best way to do this,"['c#', '.net']" +11028,how is the upcoming dynamic keyword in net 40 going to make my life better i do not quite get what it is going to let me do or get away with,['.net'] +11032,java collections copy list i do not understand i have an arraylist and i want to copy it exactly i use utility classes when possible on the assumption that someone spent some time making it correct so naturally i end up with the collections class which contains a copy methodsuppose i have the followingliststring a new arrayliststringaaddaddbaaddcliststring b new arrayliststringasizecollectionscopybathis fails because basically it thinks b is not big enough to hold a yes i know b has size 0 but it should be big enough now should not it if i have to fill b first then collectionscopy becomes a completely useless function in my mind so except for programming a copy function which i am going to do now is there a proper way to do this,['java'] +11034,java concurentmap keyset question when map is modified and iterating over keyset quick background i have a concurrent map i used to cache some values that change quite often still worth caching them from testing i want to evict items from my cache at regular intervals by examining an expire time in the value i am using the keyset method to get a reference to all my keys and then check the values and if expired i remove them in other threads the cache is being queried and updatedremoved constantly from the javadocs for keyset it mentioned if the map changes while i am iterating over the keyset set the results are undefined obviously i would like a defined way of dealing with this so the results are valid would it be enough to pass the set to a hashset and then iterate over this set as it is my understanding this set will not be backed by the map is this a wasteful of memory way of doing it any ideas appreciatedunfortunately my evictor is not the only way for items to be removed from the concurrent map so am i correct in saying that i need to copy the keyset to another set before iterating through itthanks in advanceedit it turns out i was reading the javadocs for the map keyset method instead of the concurrentmap keyset thanks my bad returns a set view of the keys contained in this map the set is backed by the map so changes to the map are reflected in the set and viceversa if the map is modified while an iteration over the set is in progress except through the iterators own remove operation the results of the iteration are undefined the set supports element removal which removes the corresponding mapping from the map via the iteratorremove setremove removeall retainall and clear operations it does not support the add or addall operations,['java'] +11040,hashtable with multidimensional key in c i am basically looking for a way to access a hashtable value using a twodimensional typed key in ceventually i would be able to do something like this hashtable1false 5int a hashtable1falsea 5this is what i have been tryinghas not workedhashtable test new hashtabletestaddnew dictionaryint bool 1 true 5dictionaryint bool temp new dictionaryint bool 1 truestring testz testtemptostring,['c#'] +11063,communicating with an http proxy via a net tcpclient how can i communicate through an http proxy with tcpclient in c kind of like webproxy when using httpwebresponse,"['c#', '.net']" +11070,spring validation how to have propertyeditor generate specific error message i am using spring for form input and validation the form controllers command contains the model that is being edited some of the models attributes are a custom type for example persons social security number is a custom ssn typepublic class person public string getname public void setnamestring name public ssn getsocialsecurtynumber public void setsocialsecurtynumberssn ssn and wrapping person in a spring form edit commandpublic class editpersoncommand public person getperson public void setpersonperson person since spring does not know how to convert text to a ssn i register a customer editor with the form controllers binderpublic class editpersoncontroller extends simpleformcontroller protected void initbinderhttpservletrequest req servletrequestdatabinder binder superinitbinderreq binder binderregistercustomeditorssnclass personssn new ssneditor and ssneditor is just a custom javabeanspropertyeditor that can convert text to a ssn objectpublic class ssneditor extends propertyeditorsupport public string getastext converts ssn to text public void setastextstring str converts text to ssn throws illegalargumentexception for invalid text if setastext encounters text that is invalid and cannot be converted to a ssn then it throws illegalargumentexception per propertyeditor setastexts specification the issue i am having is that the text to object conversion via propertyeditorsetastext takes place before my spring validator is called when setastext throws illegalargumentexception spring simply thisplays the generic error message defined in errorsproperties what i want is a specific error message that depends on the exact reason why the entered ssn is invalid propertyeditorsetastext would determine the reason i have tried embedded the error reason text in illegalargumentexceptions text but spring just treats it as a generic erroris there a solution to this to repeat what i want is the specific error message generated by the propertyeditor to surface to the error message on the spring form the only alternative i can think of is to store the ssn as text in the command and perform validation in the validator the text to ssn object conversion would take place in the forms onsubmit this is less desirable as my form and model has many properties and i do not want to have to create and maintain a command that has each and every model attribute as a text fieldthe above is just an example my actual code is not personssn so there is no need to reply with why not store ssn as text,['java'] +11071,reusing a jpanel in netbeans gui designer this is in netbeans 65 java 6i have the following hierarchy in the netbeans gui designerjframe jtabbedpane jpanel x jpanel jbutton jpanel y jbuttonquestionjpanel y is identical to jpanel x so i would like to simply reuse jpanel x in both places but how do i do this inside the gui builderattemptsi tried copypasting jpanel x but it creates a full deep copy jpanel x1 etc duplicating everything in jpanel xsome googling indicated it might be possible to add it to the palette but i have not found a way to add a simple jpanel to the palette as opposed to a complete jframe,['java'] +11078,is it bad form to call a classmethod as a method from an instance exif i have something like thisclass cobject classmethod def fcls x return x xthis will workc ccf24but is that bad formshould i only callcfor c class fobviously this would only make sense in cases where f does not interact with selfcls expecting it to be class,['python'] +11081,rails application admin section i am working on my first rails application and want to create an admin section do i want to keep my views and controllers completely separate that is in separate directories for the admin section and the rest of the site how can i organize my viewscontrollers in custom directories how do i configure the routing,"['ruby-on-rails', 'ruby']" +11086,examples of usage of generics in net cvbnet what are some examples of where you would use generics in cvbnet and why would you want to use generics,"['c#', '.net']" +11093,tcp how are the seq ack numbers generated i am currently working on a program which sniffs tcp packets being sent and received to and from a particular address what i am trying to accomplish is replying with custom tailored packets to certain received packets i have already got the parsing done i can already generated valid ethernet ip andfor the most parttcp packetsthe only thing that i cannot figure out is how the seq ack numbers are determinedwhile this may be irrelevant to the problem the program is written in c using winpcap i am asking for any tips articles or other resources that may help me,['c++'] +11096,application start not being hit in aspnet web app i am trying to debug something in the globalasaxcs file in an aspnet web app and have set a breakpoint in the application start event however that event is not getting fired when i start the web app inside vs2008 i am targeting the 35 frameworkwhat could prevent this event from being fired or how could i have messed up the project such that this event is no longer wired up,['asp.net'] +11098,how can you find unused functions in python code so youve got some legacy code lying around in a fairly hefty project how can you find and delete dead functionsi have seen these two references find unused code and tool to find unused functions in php project but they seem specific to c and php respectivelyis there a python tool thatll help you find functions that are not referenced anywhere else in the source code notwithstanding reflectionetc,['python'] +11101,how do i pass a linq query to a method i would like to pass a linq query to a method how do i specify the argument typemy link query look something likevar query from p in pointlist where px 100 select new x px y pyclearly i am new to linq and will probably get rid of the receiving method eventually when i convert the rest of my code but it seems like something i should knowthanks,"['c#', '.net']" +11105,php on zend how to escape a variable for a query im doing some queries in zend framework and i need to make sure no sql injection is possible in the next kind of formats i can use mysql escapedeprecated and wont do all the work if i try to use real mysql escape it wont be able to grab the conection with the database and i cant find how zend filter would solve the problem the query im doing simplied have the next sintaxesdb zend registrygetdbselect select count as numfrom message mwhere mmessage like username row dbfetchrowselectwhat is the best way to prevent sql injection with this framework,"['php', 'mysql']" +11107,how do i get started using boost i hear a lot about boost here and i am beginning to think it could help a lot with my software development more so in concurrency and memory management in my particular case as we have had a lot of bugs in this area what are the key language features i need to polish up on to effectively benefit from using boost and to shorten the learning curve i have seen that function objects are commonly used so i would probably need to polish up on thatadditionally are there any tutorials and 101 resources i can quickly look at to just get a feel and understanding on using boost i realise there is a lot boost offers and i have to pick the right tools for the right job but any leads will helprelatedhow to learn boost no longer valid http return status 404,['c++'] +11115,iocdi framworks with smart client winform apps how should i approach this i am starting a new winforms app and i intend to use an iocdi framework probably ninject but i am also thinking about structuremap and linfuit seems like nearly everyone who is using iocdi is doing so in a web based environment and have found virtually nothing on using winforms with iti would like to know if anyone is using iocdi with winforms and what approaches you used to deal with winforms related issues for instance how do you make the container available in various parts of the app do you use the framework to instantiate your forms etcif anyone knows of any open source winforms based projects that use iocdi does not matter which framework i should be able to translate concepts i would like links to those as welleditare people just not writing smart clients anymore editif you could point me to some realworld code that uses iocdi in a winforms or even console type application ie something that is not web based i would appreciate itediti have been using ninject and thiscovered that ninject will happily inject an instance of it is common kernel interface if you specify an ikernel constructor parameter this has been working out pretty well but i would still like to hear other approaches people use,['c#'] +11118,create random number sequence with no repeats duplicateunique random numbers in o1i want an pseudo random number generator that can generate numbers with no repeats in a random orderfor examplerandom10might return5 9 1 4 2 8 3 7 6 10is there a better way to do it other than making the range of numbers and shuffling them about or checking the generated list for repeatseditalso i want it to be efficient in generating big numbers without the entire rangeediti see everyone suggesting shuffle algorithms but if i want to generate large random number 1024 byte then that method would take alot more memory than if i just used a regular rng and inserted into a set until it was a specified length right is there no better mathematical algorithm for this,"['c++', 'c']" +11124,how do i read jpeg and png pixels in c on linux i am doing some image processing and i would like to individually read each pixel value in a jpeg and png imagesin my deployment scenario it would be awkward for me to use a 3rd party library as i have restricted access on the target computer but i am assuming that there is no standard c or c library for reading jpegpngso if you know of a way of not using a library then great if not then answers are still welcome,"['c++', 'c']" +11138,why is set as startup option stored in the suo file and not the sln file it seems like this setting should be stored in the solution file so it is shared across all users and part of source code control since we do not check in the suo file each user has to set this separately which seems strange,['c#'] +11139,how do you copy an calayer how to you make an nsarray full of multiple instances of a calayer all with the same frame contents etcbackground calayer takes a bit of overhead to create so i would like to create a number of calayers all sharing the same properties in the init method of a class to be used later on in that class,"['iphone', 'objective-c']" +11140,apc for windows alternative download i am trying to install apc on windows but the site is down for a while now with the messagethe pecl4win build box is temporarily out of service were preparing a new build systemis there an alternative download for this or can anyone share theirs,['php'] +11144,how do i add a property to a javascript object using a variable as the name i am pulling items out of the dom with jquery and want to set a property on an object using the id of the dom element for exampleobj jqueryitemsfromdomeachfunction element jquerythis name elementattrid value elementattrvalue heres the problem objname valueif itemsfromdom includes an element with an id of myid i want obj to have a property named myid the above gives me namehow in javascript do i name a property of an object using a variable,['javascript'] +11147,how to return a part of an array in ruby with a list in python i can return a part of it using the following codefoo 123456bar 102030405060half lenfoo 2foobar foohalf barhalfsince ruby does everything in arrays i wonder if there is something similar to that,['ruby'] +11149,running ant with jdk 16 on mac os x i am having a problem running ant with jdk 16 on mac os x even though java application versions is set to java se 6 in os xs java preference executing java version in terminal also shows java version 160 07 ant still seems to use jdk 15 to be using jdk 15 as it does not see jdk 16 classes when compiling my codei understand that ant relies on java home environment variable to specify which jdk to use however i do not quite understand how this variable can be set on mac os xhence my question is how to make ant runs with jdk 16 on mac os x if the correct way is still to set java home environment variable how to set the variable on os x,['java'] +11151,what is llvm and how is replacing python vm with llvm increasing speeds 5x google is sponsoring an open source project to increase the speed of python by 5xunladenswallow seems to have a good project planwhy is concurrency such a hard problem is llvm going to solve the concurrency problem are there solutions other than multicore for hardware advancement,['python'] +11154,using the repository pattern with entity framework mvc storefront can anyone give a helping hand i have been watching the videos for the mvc storefront and have created my own website using these techniques ie d repository pattern but i wish to use entity frameworkin the interfaces it returns iqueryable but with entity framework should i return objectquery instead i will be using linqalso in the storedfront example it goes something like this iqueryablecategory getcategoriesalso in the mvc store the category class was a built entity class standard class but with entity framework these classes are prebuilt in the object context are they notso i should need to build themi am a little confused if anyone has any helpful example or code it would be really helpful as i say i have watched the videos from the mvc storefront using linq2sql but really would like to use entity frameworkany ideasthanks smithy,['asp.net'] +11155,why do i have to define ld library path with an export every time i run my application i have some code that uses some shared libraries c code on gcc when compiling i have to explicitly define the include and library directories using i and l since they are not in the standard places when i try to run the code i get the following errorsync test sync test error while loading shared libraries libsyncso cannot open shared object file no such file or directoryhowever do the following everything works just fineexport ld library pathpathtolibrarysync testnow the strange part is this only works once if i try and run sync test again i get the same error unless i run the export command first i tried adding the following to my bashrc but it made no differenceld library pathpathtolibrary,['c'] +11160,how to access the description attribute on either a property or a const in c how do you access the description property on either a const or a property iepublic static class group description specified parentchild relationship already exists public const int parentchildrelationshipexists 1 description user is already a member of the group public const int userexistsingroup 2orpublic static class group description specified parentchild relationship already exists public static int parentchildrelationshipexists get return 1 description user is already a member of the group public static int userexistsingroup get return 2 in the calling class i would like to access the description property ieint x groupuserexistsingroupstring description groupuserexistsingroupgetdescription or similari am open to ideas to other methodologies as wellediti should have mentioned that i have seen an example provided herehowever i am looking for a method to access the description attribute without having to enter a string literal into the property type ie i would rather not do thistypeofgroupgetpropertyuserexistsingroupsomething along the lines of an extension method similar to the following method that will return the description attribute on an enum via an extension methodpublic static string getenumdescription this enum obj try systemreflectionfieldinfo fieldinfo objgettypegetfield objtostring object attribarray fieldinfogetcustomattributes false if attribarraylength 0 var attrib attribarray0 as descriptionattribute if attrib null return attribdescription return objtostring catch nullreferenceexception ex return unknown,"['c#', '.net']" +11164,how do i declare classlevel properties in objectivec maybe this is obvious but i do not know how to declare class properties in objectiveci need to cache perclass a dictionary and wonder how put it in the class,['objective-c'] +11169,create if an entry does not exist otherwise update kinda strange to put it into words that short hehanyway what i want is basically to update an entry in a table if it does exist otherwise to create a new one filling it with the same datai know that is easy but i am relatively new to mysql in terms of how much i have used it p,"['php', 'mysql']" +11175,avoiding parallel inheritance hierarchies i have two parallel inheritance chainsvehicle car truck etcvehiclexmlformatter carxmlformatter truckxmlformatter etcmy experience has been that parallel inheritance hierarchies can become a maintenance headache as they growie not adding toxml tosoap toyaml methods to my principal classeshow do i avoid a parallel inheritance hierarchy without breaking the concept of separation of concerns,['java'] +11187,for what reasons do people choose ruby over java i am a beginner to ruby i have heard the following complaints about ruby and was hoping the stack overflow community could address each point raised common complaints about ruby that i have heardruby is slower than javaruby is not statically typedit is not suitable for large projectsgiven these admittedly opinion based statements how is ruby better than java and will ruby ever be a widely used language both by businesses and individuals,"['java', 'ruby']" +11193,how do i get the filepath for a class in python given a class c in python how can i determine which file the class was defined in i need something that can work from either the class c or from an instance off cthe reason i am doing this is because i am generally a fan off putting files that belong together in the same folder i want to create a class that uses a django template to render itself as html the base implementation should infer the filename for the template based on the filename that the class is defined insay i put a class locationartifact in the file baseartifactspy then i want the default behaviour to be that the template name is baselocationartifacthtml,['python'] +11198,how to copy directory from source tree to binary tree copying directory from source tree to binary tree for example how to copy w to bin folderworkaabinaasrc aadoing a aaw aainclude aalibthanks,['c'] +11200,aspnet master page and file path issues i am trying to add a script reference to jquery in my master page so that it will work for any page it currently looks like thisscript typetextjavascript srcjqueryjsscriptthe problem is that the path is always relative to the executing aspx page so this will only work if the jqueryjs file is located in the same folder to make it work i have to change the line toscript typetextjavascript srcjqueryjsscriptthis is obviously less than ideal because it will only work for pages that are two levels deep from the root folder if i try the following iis throws an error about an unexpected characterscript runatserver typetextjavascript srcjqueryjsscriptany ideasedit i forgot to mention as well that the script must be in the head tagthe current top answer throws a aspnet ajax clientside framework failed to load error when i add it to my master page its thrown from javascript and not the net compiler if i move the scriptmanager to the head section where it should be i get a compile error about the scriptmanager needing to be inside a form tagthe third answer throws a illegal characters in path exception from the compileredit 2 when i add that line to my head tag i get this error from iisthe controls collection cannot be modified because the control contains code blocks ie solved i took the edited response from the answer below and put it inside an aspcontentplaceholder element,"['asp.net', 'javascript', 'jquery']" +11210,how can i initialize a modules instance variables in ruby i have some modules where i would like to use instance variables in i am currently initializing them like thismodule mymodule def selfmethod aparam var 0 other logic goes here endendi also could call a init method to initialize themdef init var 0endbut this would mean i have to remember to always call it is there a better way of doing this,['ruby'] +11213,search for nearest value in an array of doubles in c i have a sorted array of double values in c is there an stl function that will return the index of the nearest value in the array to a given double valuefor example given the following arraydouble myarray5 10 12 14 15 19 the function callsearchmyarray 16should return 3 the index of the element nearest to 16 instead of 1 or some other flag value indicating that the value 16 was not found,['c++'] +11215,escaping html in rails what is the recommended way to escape html to prevent xss vulnerabilities in rails appsshould you allow the user to put any text into the database but escape it when thisplaying it should you add before save filters to escape the input,['ruby-on-rails'] +11218,change selected and unfocused listbox style to not be grayed out i have a really simple wpf listbox with selectionmode set to multiplelistbox selectionmodemultiple when the listbox loses focus it is really hard to tell whats been selected because the selection colour changes from blue to a light grey colour whats the easiest way of changing this behaviour so that it stays bluei know it is probably something to do with the listitems style but i cannot find wherecheerssimilarwpf listview inactive selection color,['.net'] +11228,why should i implement icloneable in c can you explain to me why i should inherit from icloneable and implement the clone methodif i want to do a deep copy cannot i just implement my method let us say myclonewhy should i inherit from icloneable what are the advantages is it just a matter of making code more readable,"['c#', '.net']" +11231,whats the best way to tell if a python program has anything to read from stdin i want a program to do one thing if executed like thiscat something my programpyand do another thing if run like thismy programpybut if i read from stdin then it will wait for user input so i want to see if there is anything to read before trying to read from stdin,['python'] +11239,c assemblyfileversion usage within a program i am working on a program and i am trying to thisplay the assembly file version public static string version get assembly asm assemblygetexecutingassembly fileversioninfo fvi fileversioninfogetversioninfoasmlocation return stringformat01 fvifilemajorpart fvifileminorpart at the moment this only returns the first two version numbers in the assemblyversion not assemblyfileversion i would really like to just reference the assemblyfileversion rather than store an internal variable called version that i have to update both this and the assembly versionassembly assemblyversion10assembly assemblyfileversion350that is my assemblyfileversion from assemblyinfocs i would like to just reference the 35x part not the 10 thankszack,['c#'] +11240,adding to builtin excludefrombuild itemgroup with web deployment project i have added a web deployment project to my solution to create a clean deployment of my web application this works mostly as expected ie builds the source then copies the files to be deployed to a release folder and excludes things like source files and my svn folders etcbut now i want to explicitly exclude some other files for the sake of simplicity lets just say one file called somefiletxt so i add an item group to the wdproj file as followsitemgroup excludefrombuild includesomefiletxt itemgroupthis does indeed exclude the specific file as requested but now the files excluded by default are no longer excluded specifically now all my svn files are in the release folder there is also a source folder at the same level with all the source in itbasically it seems that defining the excludefrombuild item group is overwriting some set of builtin defaults rather than adding to themnot exactly a show stopper but not ideal so does anyone know how to simply add a file to the default excludefrombuild group or is it a case of using the defaults vs excluding everything by hand vs deleting the files you do not after a default build,['.net'] +11251,subtraction without minus sign how can i do subtraction of integers in c without using either the unary or binary operatoror can we do the same for other data types like floatdouble,['c'] +11260,how can i import only a couple of functions from a ruby module suppose i have a module with the methods function1function2function3 i want to import function1 and function2 but not function3 is there a way to do this in ruby,['ruby'] +11267,variable database name is there any way in mysql to put the name of the database into a variablefor example when i have a database called db1 can i do something like thisset db db1select from dbmytableedit there is another example of what i want to doset dbfrom db1set dbto db2insert into dbtomytable col1col2col3 select col2col1col3 from dbfrommytable,"['sql', 'mysql']" +11268,whats the significance of oct 12 19 in the signout method of systemwebsecurityformsauthentication the aspnet team chose to expire the formsauth cookie by setting the expiration date to oct 12 19httpcookie cookie new httpcookieformscookiename strcookiehttponly truecookiepath formscookiepathcookieexpires new datetime0x7cf 10 12whats the significance of october 12th 19 is it an inside joke or is there some valid reason to set your cookie expiration to that particular dateeditthe theories below are interesting but they are just guesses since phil scott and other members of the aspnet team are on stackoverflow i thought it would be fun to offer a bounty hopefully someone can track down the original developer and get an authoritative answer awardedto scott hanselman for escalating this one all the way to scottgu i was really hoping for some sort of supersecret illuminatiesque meaning but looks like it was just the old one year ago trick,"['.net', 'asp.net']" +11269,is it ok to return a const reference to a private member i need to implement readonly access to a private member container if i return a constant reference is it possible to const cast it and obtain a full access to the member whats the technique to be usedthanks,['c++'] +11272,is there an unbuffered io in windows system i want to find lowlevel cc apis equivalent with write in linux systems that do not have a buffer is there one the buffered io such as fread fwrite are not what i wanted,"['c++', 'c']" +11274,externalinterfacecall not getting return value i have a javascript function that returns the innerhtml of a div i am attempting to call this function from actionscript and store the return value i know that the javascript function is being called because there is an alert that thisplays the return data the data that is returned to actionscript however is null i am not sure what is causing this here is a code example of what i am attempting to dojavascriptfunction jsfunc var x documentgetelementbyidmydiv alertxinnerhtml return xinnerhtmlactionscriptimport flashexternalif externalinterfaceavailable var retdataobject externalinterfacecalljsfunc ifretdata null textfieldtext retdatatostring else textfieldtext returned null else textfieldtext external interface not availablelike i said earlier the alert shows up with the contents of the div but the text in the textfield is always returned null meaning that the externalinterface is available i should add that i can only test this in ie7 and ie8 any advice on what to do would be much appreciated,['javascript'] +11276,how do i rename a filename after uploading with php how do i rename the file either before or after it gets uploaded i just want to rename the filename not the extensionchangetxt sessionusernameuploadername strtolowerchangetxtchangetxt strtolowerchangetxtchangetxt ucfirstchangetxtfilelocation postuserfilefilename postfilenamemax size postmax file sizefile filesuserfileallowedextensions arraywma mp3 wavfunction isallowedextensionfilename global allowedextensions return in arrayendexplode filename allowedextensionsiffileerror upload err ok ifisallowedextensionfilename uploaddir uploadsuploadernameuploadfile uploaddir basename filesuserfilenameif move uploaded file filesuserfiletmp name uploadfile echo thank you for uploading your musicbr br else echo your file did not uploadbr br echo n echo a hrefindexphpreturna to indexbr br uploaddir else echo you have tried to upload an invalid file typebr br else diecannot upload,['php'] +11279,launching ruby without the prefix ruby i am on os x with bash and a newbie at unix i want to know if it is possible to amend some file such that to run a ruby program i do not need ruby filerb but instead can just run rubyrbis there a reason not to do thisthanks,['ruby'] +11287,how can i allow my user to insert html code without risks not only technical risks i developed a web application that permits my users to manage some aspects of a web site dynamically yes some kind of cms in lamp environment debian apache php mysqlwell for example they create a news in their private area on my server then this is published on their website via a curl request or by ajaxthe news is created with an wysiwyg editor fck at moment probably tinymce in the next futureso i cannot thisallow the html tags but how can i be safewhat kind of tags i must delete javascriptsthat in meaning to be serversafe but how to be legally safeif an user use my application to make xss can i be have some legal troubles,"['php', 'javascript', 'html']" +11303,jquery dialog theme and style how do i change the background color of the title bar of a jquery dialogi have looked at the themeroller but it does not seem to work for methanks,['jquery'] +11306,sorting and paging with gridview aspnet i am trying to get a gridview to sort and page manually with no successthe problem is that when a user clicks the column they want to sort it sorts that page but does not sort the datasource dataview behind the gridview so when they progress to a different page their sort is lost pretty much i am looking for a sort that will actually sort the datasource behind the gridview here is what i have so farprotected void gridview onsortobject sender gridviewsorteventargs estring sortexpression esortexpressionif gridviewsortdirection sortdirectionascendingdataview mydataview new dataviewmybllgetitemsorderedmydataviewsort sortexpression descgridviewdatasource mydataviewgridviewdatabindelsedataview mydataview new dataviewmybllgetitemsorderedmydataviewsort sortexpression ascgridviewdatasource mydataviewgridviewdatabindany help would be appreciated thanks,['asp.net'] +11307,making a template parameter a friend exampletemplateclass tclass base public base friend class tnow this does not work is there a way of doing thisi am actually trying to make a general class sealer like thisclass clasealer private friend class sealed clasealer class sealed private virtual clasealer class failstoderive public sealed cannot be instantiatedi found this example on this site somewhere but i cannot find it herei know there are other ways of doing this but just now i am curious if you actually can do something like this,['c++'] +11311,building a highly modular business application with wpf i am fleshing out a wpf business application in my head and one thing that sparked my interest was how i should handle making it incredibly modular for example my main application would simply contain the basics to start the interface load the modules connect to the server etc these modules in the form of class libraries would contains their own logic and wpf windows modules could define their own resource dictionaries and all pull from the main applications resource dictionary for common brushes and suchwhats the best way to implement a system of this nature how should the main interface be built so that the modules it loads can alter virtually any aspect of its user interface and logici realize it is a fairly vague question but i am simply looking for general input and brainstormingthanks,['c#'] +11316,valid email address regular expression i have done some testing but i wanted to ask if anyone sees a problem with this ruby regular expression for email validationasaz09az2zilook goodthankstony,['ruby'] +11323,preventstop auto anchor link from occurring i need to prevent the automatic scrollto behavior in the browser when using linkhtmlidx and div ididxthe problem i am trying to solve is where i am trying to do a custom scrollto functionality on page load by detecting the anchor in the url but so far have not been able to prevent the automatic scrolling functionality specifically in firefoxany ideas i have tried preventdefault on the windowload handler which did not seem to worklet me reiterate this is for links that are not clicked within the page that scrolls it is for links that scroll on page load think of clicking on a link from another website with an anchor in the link what prevents that autoscroll to the ideveryone understand i am not looking for a workaround i need to know if and how it is possible to prevent autoscrolling to anchors on page loadnotethis is not really an answer to the question just a simple raceconditionstyle klugeuse jquerys scrollto plugin to scroll back to the top of the page then reanimate the scroll using something custom if the browsercomputer is quick enough there is no flash on the pagei feel dirty just suggesting thisdocumentreadyfunction fix the urlid scrollto effect that cannot be aborted apparently in ff by scrolling back to the top of the page scrolltobody0 otheranimatestuffhappensnowcredit goes to wombleton for pointing it out thanks,"['javascript', 'jquery']" +11332,why is list not threadsafe from this siteunfortunately list is not threadsafe cas arraylist and javaas vector are threadsafe c also has a hashtable the generic version iswhat makes listt not threadsafe is it implementation problem on net framework engineers part or are generics not threadsafe,['.net'] +11334,can i transpose a file in vim i know i can use awk but i am on a windows box i am making a function for others that may not have awk i also know i can write a c program but i would love not have to create maintain and compile something for a little vim utility i am making the original file might bethe day was long the way was fastand it would becometthheedwaayywwaasslfoansgtupdate golf rules apply to selecting correct answerupdate python fans should check out mr duffys answer below,['python'] +11338,why cannot i leverage 4gb of ram in my computer to process less than 2gb of information in c scenario over 15gb of text and csv files that i need to process mathematically i tried using sql server express but loading the information even with bulk import takes a very long time and ideally i need to have the entire data set in memory to reduce hard thisk iothere are over 120 records but even when i attempt to filter the information to just one column inmemory my c console application is consuming 35gb of memory to process just 125mb 700mb actually readin of textit seems that the references to the strings and string arrays are not being collected by the gc even after setting all references to null and encapsulating ithisposables with the using keywordi think the culprit is the stringsplit method which is creating a new string for each comma separated valueyou may suggest that i should not even read the unneeded columns into a string array but that misses the point how can i place this entire data set in memory so i can process it in parallel in ci could optimize the statistical algorithms and coordinate tasks with a sophisticated scheduling algorithm but this is something i was hoping to do before i ran into memory problems and not because ofi have included a full console application that simulates my environment and should help replicate the problemany help is appreciated thanks in advanceusing systemusing systemcollectionsgenericusing systemtextusing systemionamespace inmemprocessingleak class program static void mainstring args setup test environment uncomment once 15020 files would be more realistic inmemoryprocessingleakgeneratetestdirectoryfilesandcolumns30 3 gc gccollect demostrate large object memory allocation problem lomap inmemoryprocessingleakselectcolumnfromallfiles30 2 class inmemoryprocessingleak public static liststring selectcolumnfromallfilesint filestoselect int column liststring allitems new liststring int filecount filestoselect long filesize totalreadsize 0 for int i 1 i filecount i allitemsaddrangeselectcolumni column out filesize totalreadsize filesize consoleclear consoleoutwritelinereading file 0 of 1 i filecount consoleoutwritelinememory 0mb gcgettotalmemoryfalse 1048576 consoleoutwritelinetotal read 0mb totalreadsize 1048576 consolereadline return allitems reads a csv file and returns the values for a selected column private static liststring selectcolumnint filenumber int column out long filesize string filein fileinfo file new fileinfostringformatmemleaktestfilesfile0txt filenumber filesize filelength using systemiofilestream fs fileopenfilemodeopen fileaccessread fileshareread using systemiostreamreader sr new systemiostreamreaderfs filein srreadtoend string linedelimiter n string alines fileinsplitlinedelimiter stringsplitoptionsnone liststring processedcolumn new liststring string current for int i 0 i alineslength 1 i current getcolumnfromprocessedrowalinesi column processedcolumnaddcurrent for int i 0 i linedelimiterlength i gc linedelimiteri null linedelimiter null for int i 0 i alineslength i gc alinesi null alines null current null return processedcolumn returns a row value from the selected comma separated string and column position private static string getcolumnfromprocessedrowstring line int columnposition string entirerow linesplittochararray string currentcolumn entirerowcolumnposition gc for int i 0 i entirerowlength i entirerowi null entirerow null return currentcolumn region generators public static void generatetestdirectoryfilesandcolumnsint filestogenerate int columnstogenerate directoryinfo dirinfo new directoryinfomemleaktestfiles if dirinfoexists dirinfocreate random seed new random string columns new stringcolumnstogenerate stringbuilder sb new stringbuilder for int i 1 i filestogenerate i int rows seednext10 80 for int j 0 j rows j sbappendgeneraterowseed columnstogenerate using textwriter tw new streamwriterstringformat0file10txt dirinfo i twwritesbtostring twflush sbremove0 sblength consoleclear consoleoutwritelinegenerating file 0 of 1 i filestogenerate private static string generatestringrandom seed stringbuilder sb new stringbuilder int characters seednext4 12 for int i 0 i characters i sbappendconverttocharconverttoint32mathfloor26 seednextdouble 65 return sbtostring private static string generaterowrandom seed int columnstogenerate stringbuilder sb new stringbuilder sbappendseednext for int i 0 i columnstogenerate 1 i sbappend sbappendgeneratestringseed sbappendn return sbtostring endregion these other columns will be needed and accessed both sequentially and randomly through the life of the program so reading from thisk each time is a tremendously taxing overheadenvironment notes 4gb of ddr2 sdram 800 core 2 duo 25ghz net runtime 35 sp1 vista 64,['c#'] +11347,what is your experience with arm jazelle i am evaluating between open source and closed source jvm for arm in particular the closed source jvm can make use of jazelle java acceleration for newer armsdo you have any experice with this technologyand btw which os do you use with it,['java'] +11352,should i do all the exercises in kr this is a quick slightly subjective question i need to ask in order to become a proficient c programmer i felt i would learn c from the kr i find the book a little easygoing difficult to understand sometimes but easygoing on the wholemy question here is do i have to absoultely do all the exercises even those that stumped me to become a proficient programmer in c or can i skip most of them the format and layout of the questions asked are difficult at best without using the tools available to cs rich set of libraries,['c'] +11358,is there a jquery plugin which combines draggable and selectable i am looking to implement a web interface with a number of items which can be selected and dragged around to position them either in groups or singly rather like the windows desktop reallywere using jquery already so additions to that would be first choice jquery ui draggables and selectables individually do much of what we want but do not really work together to give the sort of effect were looking fori am completely overwhelmed by the jq plugin site it is popular algorithm does not seem very useful and would welcome guidance as to the best way to avoid a lot of wheelreinvention here as i would guess that this metaphor has already been done,"['jquery', 'html']" +11363,aspnet menuitem individual styles i am hoping to use an aspnet menu control for navigation through my site however i have got a requirement that each menuitem must be styled differently different colors both static and onhover without creating a custom class that would inherit from menuitem is this possiblethoughts on a better solution,['asp.net'] +11378,are uninitialized struct members always set to zero consider a c structstruct t int x int ywhen this is partially initialized as in struct t t 42is ty guaranteed to be 0 or is this an implementation decision of the compiler,"['c++', 'c']" +11381,how can i change the image thisplayed in an uiimageview programmatically i have an iboutlet to an uiimageview but when i look at the uiimageview doc i cannot see any hint about how to programmatically change it do i have to fetch an uiimage object from that uiimageview,['iphone'] +11402,clean efficient algorithm for wrapping integers in c returns a number between klowerbound and kupperbound eg wrap1 0 4 returns 4 eg wrap5 0 4 returns 0 int wrapint const kx int const klowerbound int const kupperbound suggest an implementation,['c++'] +11403,in python how can i access static class variables within class methods if i have the following python codeclass fobject bar 1 def bahself print barf foofbahit complains nameerror global name bar is not definedhow can i access clastatic variable bar within method bah,['python'] +11410,is there a reasonable approach to default type parameters in c generics in c templates one can specify that a certain type parameter is a default ie unless explicitly specified it will use type t can this be done or approximated in ci am looking for something likepublic class mytemplatet1 t2string so that an instance of the type that does not explicitly specify t2mytemplateint t new mytemplateintwould be essentiallymytemplateint string t new mytemplateint stringultimately i am looking at a case wherein there is a template that is fairly widely used but i am considering expanding with an additional type parameter i could subclass i guess but i was curious if there were other options in this vein,['c#'] +11413,javascript why compare with null an open source javascript project i work on includes codeif color tapedivstylebackgroundcolor color set color here if defined by event else use css a contributor wants to change it to if color null this line changed tapedivstylebackgroundcolor color set color here if defined by event else use css color is a string var only a string of more than 0 characters should be used to explicitly set the colorsince js casts and null as boolean false why would the comparison null be neededam i missing something in thinking that the first form is just as good and a bit shorter than the secondi see comparisons with null quite often in js source why are they needed when all js simple objects have known results when cast as booleans thankslarryps i suppose if 0 an integer was a valid case then if0 would be false a problem and if0 null would be true allows the 0 case any other reasonpps should have mentioned that the tapediv is newly created so there is no point to resetting the style to since the div is brand new,['javascript'] +11414,gcc compiler error redefinitionpreviously defined i am getting a lot of redefinition of xx previously defined here please what does this error means,['c++'] +11417,why would i want to use jquery i understand that someone else asked a similar question and it was closed as argumentative but i am really interested in understanding the arguments around thisi know javascript really well i have been writing it professionally for years i have internalized a lot of the crossbrowser incompatibilities and sketchiness know dom manipulation like the back of my hand have worked with some of the best web developers in the industry picked up a lot of their mojo i have been checking out jquery i understand the point of a javascript library how many times have i written animation getelementsbyclass and hideshow functions but to be honest it seems like a waste of time to learn an entirely new syntax that is not less complex it seems like i would be bashing my head against a wall to learn an entirely new interface to the same old javascripti am not technically an engineer so maybe i am missing something could someone spell out the tradeoffs of jquery is it really faster to learn and understand jquery syntax than to just learn javascript,"['javascript', 'jquery']" +11419,php fatal error cannot redeclare class does anyone know what can cause this problemphp fatal error cannot redeclare class,['php'] +11420,how to use http get request in c with ssl protocol violation i am currently trying to get a response from a server that is using ssl in c i have the code to do this in java but it looks like they do not translate 11 i do have some code that i found that works for regular pages but not for the one i need maybe because of the ssl thing here is the code webrequest request webrequestcreatehttps sslserverhost sslserverport requestproxy null requestcredentials credentialcachedefaultcredentials httpwebresponse response httpwebresponserequestgetresponse stream datastream responsegetresponsestream streamreader reader new streamreaderdatastream string responsefromserver readerreadtoendupdate sorry i seem to have forgotten what the error is i am getting a protocol violation exception at the httpwebresponse response httpwebresponserequestgetresponse lineany ideas thanks guys,['c#'] +11431,what are the correspondent of servlet and applet in net i am trying to understand whats the correspondent of servlets and applets in net but i do not have much experience in javai am thinking applets could be compared to the silverlight stuff meaning you code independently from the browser but then it is not like that since between other things you can reuse an applet outside the browseri need to demonstrate web technologies for a javabased collegecourse and i can use net as long as i can demonstrate the same stuff any help or ideas appreciated,"['java', '.net']" +11432,create image with transparent background using gdi i am trying to create an image with a transparent background to thisplay on a web pagei have tried several techniques but the background is always blackhow can i create a transparent image and then draw some lines on it,"['c#', 'asp.net']" +11436,mysql dump tables only in my database i have some tables and views how can i export all the tables and not the views from my database from command line,['mysql'] +11444,java rationale of the cloneable interface why was not the clone method specified in the javalangcloneable interface,['java'] +11446,python code convention using pylint i am trying out pylint to check my source code for conventions somehow some variable names are matched with the regex for constants constrgx instead of the variable name regex variablergx how to match the variable name with variablergx or should i extend constrgx with my variablergx stuffegc0103 31 invalid name settings should match az az19,['python'] +11447,capture multiple key downs in c how can i capture multiple key downs in c when working in a windows forms formi just cannot seem to get both the up arrow and right arrow at the same time,['c#'] +11449,linq in line property update during join i have two obects a b for this thiscussion i can join these objects tables via a common relationship or foreign key i am using linq to do this join and i only want to return objecta in my result set however i would like to update a property of obejcta with data from objectb during the join so that the objectas i get out of my linq query are slightly different from their original state in the storage medium of choicehere is my query you can see that i would just like to be able to do something like objectasomeproperty objectbavalueiwantbadlyi know i could do a new in my select and spin up new objectas but i would like to avoid that if possible and simply update a fieldreturn from objecta in getobjectas join objectb in getobjectbs on objectaid equals objectbaid update object a with object b data before selecting it select objecta,['c#'] +11451,append new javadoc to existing from super method i have generated an interface which is very well documented every method does have his own javadoc the clases which implement this interface can have little differents in their logichow can i add javadoc to the existing javadoc from the super class the key word inheritdoc only set the javadoc of the super class to the current method but when i try to add some words the javadoc of the super method is gone like inheritdoc these value depends on does anybody have a idea how i can update the javadoc of a super method without deletingeditregarding to brian agnew answer which is good but not a real answer you also can have the same problem when you want to overwrite an existing method like paint in swing and want to describ how to initialize or handle the draw behaviour from outsidethis is not only for interface description,['java'] +11455,how method hiding works in c why the following program printsbbas it shouldpublic class a public void print consolewritelinea public class b a public new void print consolewritelineb public void print2 print class program static void mainstring args var b new b bprint bprint2 but if we remove keyword public in class b like so new void print consolewritelineb it starts printingab,['c#'] +11458,how can i know the address of owner object in c i would like to create in c a notifier class that i will use in other objects to notify various holders when the object gets destroyed template class ownerclass notifierowner public notifierowner owner notifier notifies the owner that an object is destroyedclass ownerclass owned public ownedowner ownerprivate notifierowner notifiermy point is that as i have a dense and complicated object graph i would like to avoid storing the address of the owned object in the notifier is there a way to change my notifier class so that it can deduce the owned objects address from its own address and an offset that would be computed at compile timenote also that any object may have to notify several owners possibly from the same classthanks,['c++'] +11474,reload uitableviewcontroller i am trying to reload data in a uitableviewcontroller after a location is found this also means after the viewdidload method my class is extending a uitableviewcontroller with this interfaceinterface rootviewcontroller uitableviewcontroller uitableviewdelegate uitableviewdatasource cllocationmanagerdelegatein the implementation i try to reload data using selfview reloaddatareloaddata does not seem to be a method of uitableviewcontroller or the view because i get an error messages without a matching method signature will be assumed to return id and accept as argumentscan someone please post some code of how to reload a table view extended like in my case,['iphone'] +11476,c permutation of an array of arraylists i have an arraylist mylist and i am trying to create a list of all the permutations of the values in the arraysexample all values are stringsmylist0 1 5 3 9 mylist1 2 3 mylist2 93 the count of mylist can be varied so its length is not known beforehand i would like to be able to generate a list of all the permutations similar to the following but with some additional formatting1 2 931 3 935 2 935 3 933 2 933 3 939 2 939 3 93does this make sense of what i am trying to accomplish i cannot seem to come up with a good method for doing this if anyediti am not sure if recursion would interfere with my desire to format the output in my own manner sorry i did not mention before what my formatting wasi want to end up building a string array of all the combinations that follows the format like belowfor the 1 2 93 permutationi want the output to be val01val12val293i will experiment with recursion for now thank you drjokepu,['c#'] +11486,opensource cc decompiler duplicate of and taken togetherdoes somebody know any opensource cc decompiler i do not want to use any commercial solution like ida pro,"['c++', 'c']" +11488,learning to work with audio in c my degree was in audio engineering but i am fairly new to programming i would like to learn how to work with audio in a programming environment partly so i can learn c better through interesting projectsfirst off is c the right language for this is there any reason i should not be using it i have heard of soundfile and some other libraries what would you recommendfinally does anyone know of any good tutorials in this subject i have learnt the basics of dsp i just want to program itedit i use windows i would like to play about with realtime stuff a bit like maxmsp but with more control,['c++'] +11489,launch jar files with command line arguments but with no console window i have to do a demo of an application the application has a serverjar and clientjar both have command line arguments and are executable i need to launch two instances of serverjar and two instances of clientjari thought that using a batch file was the way to go but the batch file executes the first command ie serverbat argument1 argument2 and does not do anything else unless i close the first instance in which case it then runs the 2nd command and also the i do not want a blank console window to open or be minimizedwhat i really need is a batch script that will just launch these apps without any console windows and launch all instances that i needthanks in advanceeditjavaw works if i type the command into the console window individually if i put the same in the batch file it will behave as before console window opens one instance starts whichever was first and it does not proceed further unless i close the application in which case it runs the 2nd command i want it to run all commands silently,['java'] +11496,debugging exception thrown in objective c and xcode i am a long time microsoft developer and i am new to iphone development using xcode so i am reading a book and going through examples trying to teach myself how to write an iphone application using objectivec all has been good so far however once in a while i run into the generic objc exception throw message at runtime when this happens the source of this exception is very difficult to find after some trial and error i found my answer one of the parameters was misspelled as you can see below i misspelled the otherbuttontitles parameter by leaving out the second t in button uialertview alert uialertview alloc initwithtitledate and time selected messagemessage delegatenil cancelbuttontitlecancel otherbutontitlesnilthe reason this took me time to find is that the code built successfully is this normal behavior for the objectivec compiler i am used to having the build fail in the net compiler when i make a common syntax error like this is there a compiler setting i can change to make the built fail when i make these mistakes,['iphone'] +11504,use thisplaynameattribute in aspnet i want to bind a list to a gridview on a web page but override the way the property names thisplay via annotation i thought systemcomponentmodel would work but this does not seem to work is this only meant for windows formsusing systemcomponentmodelnamespace mywebapp public class mycustomclass thisplaynamemy column public string myfirstproperty get return value public mycustomclass then on the pageprotected void page loadobject sender eventargs e ilistmycustomclass mycustomclasses new listmycustomclass new mycustomclass new mycustomclass testgriddatasource mycustomclassestestgriddatabindthis renders with myfirstproperty as the column header rather than my column is not this supposed to work,['asp.net'] +11506,list all tests found by nosetest i use nosetests to run my unittests and it works well i want to get a list of all the tests nostests finds without actually running them is there a way to do that,['python'] +11509,whats your choice for your next aspnet project web forms or mvc let us say that you will start a new aspnet web siteapplication tomorrow would you chose web forms or mvc and why,['asp.net'] +11519,where can i find a nice net tab control for free i am doing this application in c using the free krypton toolkit but the krypton navigator is a paid product which is rather expensive for me and this application is being developed on my free time and it will be available to the public for freeso i am looking for a free control to integrate better into my krypton application because the default one does not quite fit and it will be different depending on the os versionany suggestionsps i know i could ownerdraw it but i am trying not to have that kind of work i prefer something already done if it exists for frediti just found exactly what i wanted 350zip,"['c#', '.net']" +11520,list of special characters for sql like clause what is the complete list of all special characters for a sql i am interested in sql server but others would be good too like clauseegselect name from person where name like jonsql server specifier eg azspecifierescape clause eg 30 escape will evaluate 30 as true characters need to be escaped with eg they are becomes theyremysql any string of zero or more characters any single characterescape clause eg 30 escape will evaluate 30 as trueoracle any string of zero or more characters any single characterescape clause eg 30 escape will evaluate 30 as truesybase specifier eg azspecifierprogress any string of zero or more characters any single characterreference guide here pdfpostgresql any string of zero or more characters any single characteransi sql92 an escape character only if specifiedpostgresql also has the similar to operator which adds the followingspecifierspecifier either of two alternatives repetition of the previous item zero or more times repetition of the previous item one or more times group items togetherthe idea is to make this a community wiki that can become a one stop shop for this,['sql'] +11538,classloader confusion i have seen several places that classgetclassloader returns the classloader used to load that particular class and therefore i am stumped by the results of the following examplepackage testimport javalangpublic class classloaders public static void mainstring args throws javalangclassnotfoundexception myclassloader mcl new myclassloader class clazz mclloadclasstestfoobar systemoutprintlnclazzgetclassloader mcl prints false systemoutprintlnclazzgetclassloader prints eg sunmisclauncherappclassloader553f5d07 class foobar class myclassloader extends classloader should not the statement clazzgetclassloader mcl return true can someone explain what i am missing herethanks,['java'] +11539,concurrent file write in java on windows what happens when you concurrently open two or more fileoutputstreams on the same filethe java api says thissome platforms in particular allow a file to be opened for writing by only one fileoutputstream or other filewriting object at a timei am guessing windows is not such a platform because i have two threads that read some big file each one a different one then write it to the same output file no exception is thrown the file is created and seems to contain chunks from both input filesside questionsis this true for unix tooand since i want the behaviour to be the same actually i want one thread to write correctly and the other to be warned of the conflict how can i determine that the file is already opened for writing,['java'] +11545,how to drop identity property of column in sql server 2005 i want to be able to insert data from a table with an identity column into a temporary table in sql server 2005the tsql looks something like create empty temp tableselect into tmp mytablefrom mytablewhere 10while begin insert into tmp mytable select top n from mytable endthe above code created tmp table with an identity column and the insert subsequently fails with an error an explicit value for the identity column in table tmp mytable can only be specified when a column list is used and identity insert is onis there a way in tsql to drop the identity property of the column in the temporary table without listing all the columns explicitly i specifically want to use select so that the code will continue to work if new columns are added to mytablei believe dropping and recreating the column will change its position making it impossible to use select updatei have tried using identity insert as suggested in one response it is not working see the repro below what am i doing wrong create test tablecreate table dbotesttable id numeric18 0 identity11 not null name varchar50 null constraint pk testtable primary key clustered id asc go insert some datainsert into testtablenameselect oneunion allselect twounion allselect threego create empty temp tableselect into tmpfrom testtablewhere 10set identity insert tmp on i also tried off oninsert into tmpselect top 1 from testtableset identity insert tmp off go drop test tabledrop table dbotesttablegonote that the error message an explicit value for the identity column in table tmpmytable can only be specified when a column list is used and identity insert is on i specifically do not want to use a column list as explained aboveupdate 2tried the suggestion from mike but this gave the same error create empty temp tableselect into tmpfrom select m1 from testtable m1 left outer join testtable m2 on m1idm2id where 10 dtinsert into tmpselect top 1 from testtableas for why i want to do this mytable is a staging table which can contain a large number of rows to be merged into another table i want to process the rows from the staging table insertupdate my main table and delete them from the staging table in a loop that processes and rows per transaction i realize there are other ways to achieve thisupdate 3i could not get mikes solution to work however it suggested the following solution which does work prefix with a nonidentity column and drop the identity columnselect cast1 as numeric180 as id2 into tmpfrom testtablewhere 10alter table tmp drop column idinsert into tmpselect top 1 from testtablemikes suggestion to store only the keys in the temporary table is also a good one though in this specific case there are reasons i prefer to have all columns in the temporary table,['sql'] +11563,selectionstartend with textareas i am having this annoying problem i cannot seem to get the starting and ending index of the selected text in a textarea all i get is undefined like thismyareaselectionstart return undefineddid i do something wrong,"['javascript', 'jquery']" +11565,mysql performance optimization order by datetime field i have a table with roughly 10 blog postings linked to a table with 50 feeds via an 1n relationship when i query both tables with a select statement ordered by a datetime field of the postings table mysql always uses filesort resulting in very slow query times 1 second heres the schema of the postings table simplified field type null key default extra id int11 no pri null auto increment feed id int11 no mul null crawl date datetime no null is active tinyint1 no mul 0 link varchar255 no mul null author varchar255 no null title varchar255 no null excerpt text no null long excerpt text no null user offtopic count int11 no mul 0 and heres the feed table field type null key default extra id int11 no pri null auto increment type int11 no mul 0 title varchar255 no null website varchar255 no null url varchar255 no null and heres the query that takes 1 second to execute please note that the post date field has an index but mysql is not using it to sort the postings tableselect postingsid unix timestamppostingspost date as post date postingslink postingstitle postingsauthor postingsexcerpt postingslong excerpt feedstitle as feed title feedswebsite as feed websitefrom postingsjoin feeds on feedsid postingsfeed idwhere feedstype 1 and postingsuser offtopic count 10 and postingsis active 1order by postingspost date desclimit 15the result of the explain extended command on this query shows that mysql is using filesort id select type table type possible keys key key len ref rows extra 1 simple postings ref feed idis activeuser offtopic count is active 1 const 30996 using where using filesort 1 simple feeds eq ref primarytype primary 4 feedianpostingsfeed id 1 using where when i remove the order by part mysql stops using filesort please let me know if you have any ideas on how to optimize this query to get mysql to sort and select the data by using indexes i have already tried a few things such as creating a combined index on all whereorder by fields as suggested by a few blog postings but this did not work either,['mysql'] +11570,looking for a better alternative to pil for basic image file io and processing in python are there better alternatives to pil python imaging library for basic image file io and processing in python,['python'] +11582,best way to encode tuples with json in python i have a dictionary that maps tuples to a list of tuples eg 12 2317i want to be able to encode this data use it with javascript so i looked into json but it appears keys must be strings so my tuple does not work as a keyis the best way to handle this is encode it as 12 and then parse it into something i want on the javascript or is there a more clever way to handle this,['python'] +11584,how to clone arraylist and also clone its contents how can i clone an arraylist and also clone its items in javafor example i havearraylistdog dogs getdogsarraylistdog clonedlist something to do with dogsand i would expect that objects in clonedlist are not the same as in dogs list,['java'] +11603,udp nat and setting up connections i know the word connection is not really appropriate when talking about udp buthow does a server the one with the known ip get its udp packets through the internet to a client that is behind natfor example say a client connects and authenticates to the server using some messaging over tcp at this point the server is ready to start streaming data to the client over udp but how does the server know where to address the udp packets so that they would find their way through any nat routers to the clientif the client fist sends an i am ready for the streaming please message over udp would the nat routers keep the port open so that the server can respond with its stream of udp dataor am i waay off track here,['.net'] +11611,rotating table header text with css transforms this looks like it should be possible with the followingverticaltext ieonly dx filter writingmode tbrl filter flipv fliph safarichrome function webkittransform rotate270deg works in latest fx builds moztransform rotate270degthis works in ieit goes wrong in a bizarre way in safari chrome and fx the cells size is calculated before the text is rotatedhere is a demo i am using dynamic images as a workaround although that also has its problems i am happy with that as a fallback but it seems like there should be a way to make this css work it is almost thereanyone know a way to make the cells fit the content after the transform has been applied,['css'] +11621,best way to offload heavy processing like image resizing out of php request i am working on a php web interface that will receive huge traffic some insertupdate requests will contain images that will have to be resized to some common sizes to speed up their further retrievalone way to do it is probably to set up some asynchronous queue on the server eg set up a table in a db with a tasks queue that would be populated by php requests and let some other process on the server watch the table and process any waiting tasks how would you do that what would be the proper environment for that long running process java or maybe something lighter would do,['php'] +11625,is ruby really an interpreted language if all of its implementations are compiled into bytecode in the chosen answer for this question about blue ruby chuck saysall of the current ruby implementations are compiled to bytecode contrary to saps claims as of ruby 19 mri itself includes a bytecode compiler though the ability to save the compiled bytecode to thisk thisappeared somewhere in the process of merging the yarv virtual machine jruby is compiled into java class files i do not have a lot of details on maglev but it seems safe to say it will take that road as welli am confused about this compilationinterpretation issue with respect to rubyi learned that ruby is an interpreted language and that is why when i save changes to my ruby files i do not need to rebuild the projectbut if all of the ruby implementations now are compiled is it still fair to say that ruby is an interpreted language or am i misunderstanding something,['ruby'] +11627,javalangoutofmemoryerror java heap space with netbeans this is the error i get when i run my web application in an instance of the tomcat servlet container started by netbeans to fix this i even changed the heap size in netbeansconf but still it shows the same error how can i keep this from happeninghttp status 500 type exception reportmessage description the server encountered an internal error that prevented it from fulfilling this requestexception javaxservletservletexception servlet execution threw an exception orgnetbeansmoduleswebmonitorservermonitorfilterdofiltermonitorfilterjava362root cause javalangoutofmemoryerror java heap spacenote the full stack trace of the root cause is available in the apache tomcat559 logs,['java'] +11634,how to install simplejson package for python i am just diving into the python world and want to make a simple twitter application which requires the installation of simplejson but not sure how i can set it up and get it workingi am on a windows system,['python'] +11641,segmentation fault in strcpy consider the program below char str5 strcpystrhello12345678 printfsstrwhen run this program gives segmentation faultbut when strcpy is replaced with following program runs finestrcpystrhello1234567so question is it should crash when trying to copy to str any other string of more than 5 chars lengthso why it is not crashing for hello1234567 and only crashing for hello12345678 ie of string with length 13 or more than 13this program was run on 32 bit machine,"['c++', 'c']" +11644,not nullable types is there a way to create a non nullable type in c like datetime or timespanalso is there a way an attribute maybe to enforce that not null arguments wouldnt be passed to methods and properties without adding ifarg1 null throw new argumentnullexceptionthis attribute is null,['c#'] +11646,stretch right float div width i have 2 floatleft div the first is fixed and i want the second div stretch the remain spacediv idcontainer div idleftform div div idrightform divdivany idea thanks,"['html', 'css']" +11648,conversion tool comparisons for visual basic 60 has anyone here used either of the following or any other tool to convert your vb6 code to a net languageartinsofts upgrade companion converts to c and vbnetvbmigration partner converts to vbnethow effective were they and what size project did you converthow much work was left to do afterwardshow happy are you with the resultant net projectwhat was the support likeis there a support forum anywhere for users of tools like these neithervendor seems to offer onewhat did they charge their prices are not published and i have heard wildly differing prices from different sources for both the above examples,['c#'] +11653,is there an async version of directoryinfogetfiles directorygetdirectories in dotnet is there an asynchronous version of directoryinfogetfiles directorygetdirectories in dotnet i would like to use them in an f async block and it would be nice to have a version that can be called with asynccallbacks problem is i am trying to suck in a bunch of directories probably on smb mounts over slow network connections and i do not want a bunch of thread pool threads sitting around waiting for network reads when they could be doing other work,['.net'] +11654,kohana where do you put ajax scripts i am using kohana but this question applies to rails ci or any other mvc web development framework where is the best place to stick ones server side ajax scripts i was planning on creating an ajax controller and using a methodaction per individual scriptfor example a login form on the home page indexphphome would send an xmlhttprequest to indexphpajaxlogin and the edit profile form indexphpprofileedit would send an xmlhttprequest to indexphpajaxeditprofile whats the best practice,['php'] +11667,c streaming an audio file from a server to a client i am currently writing an application that will allow a user to install some form of an application maybe a windows service that will open a port on it is pc and given a particular destination on the hard thisk will then be able to stream mp3 filesi will then have another application that will connect to the server being the users pc and be able to browse the hosted data by connecting to that pc remotely ofcourse given the port and stream mp3 files from the server to the applicationi have found some tutorials online but most of them are about file servers in c and they download allow you to download a whole file what i want is to stream an mp3 file so that it starts playing when a certain number of bytes are download ie whilst it is being bufferedhow do i go about in accomplishing such a task what i need to know specifically is how to write this application that i will turn into a windows service later on that will listen on a specified port a stream files so that i can then access the files by something of the sort httpserverip650acdcwholelottarosiemp3 and hopefully be able to stream that file in a wpf mediaplayerupdatei was following this tutorial about building a file server and sending the file from the server to the client is what i have to do something of the sortupdatecurrently reading this post play audio from a stream using c and i think it looks very promising as to how i can play streamed files but i still do not know how i can actually stream the files from the server,['c#'] +11682,removing specific items from djangos cache i am using site wide caching with memcached as the backend i would like to invalidate pages in the cache when the underlying database object changes if the page name changes then i would invalidate the whole cache as it affects navigation on every page clumsy but sufficient for my needsif just the page content changes then i would like to invalidate the cache of just that pageis there an easy way to do this,['python'] +11687,what to return from a failed method and when to throw ia ve lately been thinking about the things ia m returning from methods and i noticed that there are 4 different things i return when the method fails what bothers me about it is that my code is not very consitent in this regard so i wanted to ask about your best practicesso lets imagine a method that takes foo and returns a list of barpublic ilistbar methodfoo somethingor to keep it more generalpublic ibar methodifoo somethingthe question is what do you return on what kind of failure the options would beempty return type like new list or new emptybarnullthrow an exceptiona special list value indicating failure like new listnew failurebari really hate option 4 so ia m mostly interessted to hear when you use the other 3 options and why,"['c#', '.net']" +11688,jquery hyperlinks href value on my website i use jquery to hook the events of elements namely hyperlinks as these hyperlinks only perform actions on the current page and do not lead anywhere i have been putting a href attribute of ina hrefmy linkahowever in some browsers this causes the page to scroll right to top which is obviously undesirable behaviour i have tried using a blank href value or not including one but then the mouse does not change to the hand cursor upon hoveringwhat should i put in there,['jquery'] +11701,php accelerator review 1 can you recommend me a php accelerator for php v5262 do you know about any recent test comparationreview of those modulesalternative php cache eaccelerator xcache zend optimizer zend platform ioncube php accelerator turck mmcache nusphere phpexpress,['php'] +11702,adding a postbuild event to a web site in visual studio 2008 i am using a web site in visual studio 2008 and i would like to add a postbuild event which would append the build time to the webconfig file is it possible,['asp.net'] +11707,using reflection to check if a method is extension method as part of my application i have a function that receives a methodinfo and need to do specific operations on it depending if that method is extension methodi have checked the methodinfo class and i could not find any isextension property or flag that shows that the method is extensiondoes anyone knows how can i find that from the methods methodinfo,['c#'] +11709,how can i get generic type from a string representation i have myclasstand then i have this string s myclassanotherclass how can i get type from the string sone way ugly is to parse out the and and do type actype typegettypeanotherclass type whatiwant typeof myclassmakegenerictypeactypebut is there a cleaner way to get the final type without any parsing etc,['c#'] +11711,doubleparse internationalization problem this is driving me crazy i have the following string in a aspnet 20 webform pagestring s 09simple enough now if my culture is spanish which is eses and i try to convert the string to double i do the followingdouble d doubleparses new cultureinfoeseswhat i would expect is 09 instead i get 9 i understand that net thinks it is a thousand separator which in enus is a comma but should not it take the culture info i am passing to the parse method and apply the correct format to the conversionif i dodouble d 09dstring formatted dtostringnew cultureinfoesesformatted is now 09 anybody,['c#'] +11712,connecting to sql server with activerecord have you ever had to connect to sql server with activerecord is this possible can anyone provide some starting points,['ruby-on-rails'] +11718,instantly detect client thisconnection from server socket how can i detect that a client has thisconnected from my serveri have the following code in my acceptcallback methodstatic socket handler nullpublic static void acceptcallbackiasyncresult ar accept incoming connection socket listener socketarasyncstate handler listenerendacceptari need to find a way to thiscover as soon as possible that the client has thisconnected from the handler socketi have triedhandleravailablehandlersendnew byte1 0socketflagsnonehandlerreceivenew byte1 0socketflagsnonethe above approaches work when you are connecting to a server and want to detect when the server thisconnects but they do not work when you are the server and want to detect client thisconnectionany help will be appreciated,"['.net', 'c#']" +11719,is there an equivalent to the scanner class in c for strings in java i can pass a scanner a string and then i can do handy things like scannerhasnext or scannernextint scannernextdouble etcthis allows some pretty clean code for parsing a string that contains rows of numbershow is this done in c landif you had a string that say had0 0 1 22 39 0 0 1 2 33 33in java i would pass that to a scanner and do a whilescannerhasnext myarrayi scannernextintor something very similar what is the c ish way to do this,"['c#', 'java']" +11736,in an onclick handler how can i detect whether shift was pressed how can i write an onclick handler that does one thing for regular clicks and a different thing for shiftclicks,['javascript'] +11764,best practices for on screen realtime log viewer for log4net i have a multithreaded c application that use log4net for logging capabilities mainly the rollingfileappenderi want to offer the capability for the user to view the activity of the application in an application log window this will consist of a listview details mode a grid or something similari am looking for best ways to do it the only solution i have so far is to setup an udp appender and create a special thread that will listen and foward all messages to the uii also examined the possibility to create a wrapper that both write to the ui the log the message using log4net humthanks a lot in advance for your help,['c#'] +11772,converting void to stdvector i have a void buffer that i need to convert to stdvectorunsigned char before i can pass it on unfortunately my c casting skills a little weak any suggestions,['c++'] +11783,optimize memory usage of a collection of strings in java i have a large number of name value pairs approx 100k that i need to store in some sort of cache say a hash map where the value is a string with an average of about 30k bytes in sizenow i know for a fact that a large number of the values have exactly the same string data in order to avoid having to allocate the identical string data several times i would like to somehow reuse a previously allocated string thus consuming less memory in addition this needs to be reasonably fast ie scanning through all the previously allocated values onebyone is not an optionany recommendations on how i could solve this problem,['java'] +11792,serialize in c then deserialize in c is there an easy way to serialize data in c either to xml or binary and then deserialize the data in c i am working with some remote winnt machines that would not run net my server app is written entirely in c so i want an easy way to share simple data key value pairs mostly and maybe some representation of a sql result set i figure the best way is going to be to write the data to xml in some predefined format on the client transfer the xml file to my server and have a c wrapper read the xml into a usable c objectthe client and server are communicating over a tcp connection and what i really want is to serialize the data in memory on the client transfer the binary data over the socket to a c memory stream that i can deserialize into a c object eliminating file creation transfer etc but i do not think anything like that exists feel free to enlighten me editi know i can create a struct in the c app and define it in c and transfer data that way but in my head that feels like i am limiting what can be sent i would have to set predefined sizes for objects etc,"['c#', 'c++']" +11796,verify value of reference parameter with moq i just switched to moq and have run into a problem i am testing a method that creates a new instance of a business object sets the properties of the object from user input values and calls a method savecustomercontact to save the new object the business object is passed as a ref argument because it goes through a remoting layer i need to test that the object being passed to savecustomercontact has all of its properties set as expected but because it is instantiated as new in the controller method i cannot seem to do sopublic void addcontact var contact new customercontact customerid m modelcustomerid contactname m modelcustomercontactname contactphonenumber m modelphonenumber contactfaxnumber m modelfaxnumber contactemail m modelemail contactreceiveinvoiceflag m modelreceiveinvoiceflag contactreceivestatementflag m modelreceivestatementflag contactreceivecontractflag m modelreceivecontractflag contactemailflag m modelemailflag contactfaxflag m modelfaxflag contactpostalmailflag m modelpostalmailflag contactcustomerlocationid m modelcustomerlocationid remotinghandlersavecustomercontact ref contact heres the testtestmethodpublic void addcontacttest int customerid 0 string name a var actual new customercontact var expected new customercontact customerid customerid name name modelsetup m mcustomerid returns customerid modelsetupproperty m modelcustomercontactname name modelsetupproperty m mphonenumber stringempty modelsetupproperty m mfaxnumber stringempty modelsetupproperty m memail stringempty modelsetupproperty m mreceiveinvoiceflag false modelsetupproperty m mreceivestatementflag false modelsetupproperty m mreceivecontractflag false modelsetupproperty m memailflag false modelsetupproperty m mfaxflag false modelsetupproperty m mpostalmailflag false modelsetupproperty m mcustomerlocationid 0 remote setup r rsavecustomercontact ref actual callback assertareequal actual expected targetaddcontactthis is just the most recent of many attempts to get ahold of that parameter for reference the value of actual does not change from its initial constructed statemoving the assertareequalexpected actual after the target call fails if i add verifiable to the setup instead of the callback and then call remoteverify after the target or i assume set the mock to strict it always fails because the parameter i provide in the test is not the same instance as the one that is created in the controller methodi am using moq 303082 any ideas on how to test this would be appreciated thanks,['c#'] +11797,how do i take screenshots of web pages using ruby and a unix server i am trying to programatically create thumbnail images of a large number of web pages that are hosted on my own rubyrailsbased websitei want to be able to code a standalone bit of ruby that looks something like thisrequire awesomescreenshotmakeritemseach do id url id shooter awesomescreenshotmakernew02 thumbnails are 20 of original shootercaptureurl imagesthumbnailidpngendi need the awesomescreenshotmaker library and its dependencies to be fairly easy to build on linux solaris and mac os x ideally it will install with a single gem install commandi have spent the afternoon exploring various options including moz snap shooter webkit2png and rbwebkitgtk they are all in the right area but none seem to work on all three platformsrmagick looks like a possible option if i am willing to output pdfs from my rails app instead of web pages but that strikes me as hacky it is also very laborious to get rmagic and imagemagick up and running on mac os xdoes such a library exist that can easily be setup on three platforms,['ruby'] +11812,nested object w checkboxes massassignment even with accepts nested attributes for i thought that there should have been a simple solution to this given that rails 23 has this newfangled nested forms feature basically i want to create or update a user and assign them roles at the same timeit seems like i am doing everything right but i get the error warning cannot massassign these protected attributes roles attrributesi even tried changing the view to userpermissions attrributesrole id because i thought that maybe the join table was confusing rails anyways any suggestions on how this should actually workmodelclass user activerecordbase has many permissions has many roles through permissions accepts nested attributes for roles accepts nested attributes for permissionsendexcerpt from view notice i tried and failed to get fields for to generate what i want here maybe that is my problem for role in roleall check box tag userroles attrributesidroleid rolerolename br end params coming across seem to be right userpassword confirmationfiltered roles attrributesid2 solution a combination of me misspelling not using attr accessible needing to access permissions attributes and the form being slightly off modelhas many permissions dependent destroyhas many roles through permissionsaccepts nested attributes for permissionsattr accessible permissions attributesview roleallorder rolename asceach with index do roleidx check box tag userpermissions attributesidxrole idroleid rolerolename br end,['ruby-on-rails'] +11814,how do i write to the console in google app engine often when i am coding i just like to print little things mostly the current value of variables out to console i do not see anything like this for google app engine although i note that the google app engine launcher does have a log terminal is there any way to write to said terminal or to some other terminal using google app engine,['python'] +11823,three arguments to main and other obfuscating tricks the following obfuscated c code prints the words to the 12 days of xmasi was trying to puzzle out how it works i am basically completely lost what is the significance of the three untyped arguments to main in the initial call the series of characters after the first return the negative numeric arguments to the calls to main eek i am mostly doing this thinking maybe i will learn some interesting corners of the c language so replies in that vein are the most welcomeinclude stdiohmaint achar areturn0tt3main7913amain871 main860a1a1t maint1 a3main9427tat2 13main2 1s d dn916t0t72main tnwwcdnrrdewwqnlnqnkr d3wk wkedql qdkkqrekkwrekknlqnwnlndrw i nlnn rwr ncnllk rw iknlwqnwk nw iwknlwlw i nlqldrnlwbdec nlrwncnwkderdqw nr rln t50 aputchar31amain65 a1mainat a1 0tmain22samain0main61aekdc ibkqwnr3lnuwlocaom vpbksfxntdceghirya1,['c'] +11825,can i dynamically unload and reload other versions of the same jar i am writing a server program which is used to run unit tests of an apithisplaying lots of information and providing web access to control monitor the whole thingthis api is known to the server during compile time and is providedas a jarto be able to compare between unit test results of different versionsof the api without restarting the serveri want to be able to unload the current version of the apiand to reload a newer one or an older onei do not want to use urlclassloader and invoke every singlemethod by name using getdeclaredmethodsomemethod because the server heavily depends on the api and it would becomplicated to wrap every method call in such dirty wayi was thinking since all interfaces of all versions of the jarare same could not i do it by somehow reloading an other versionof the jar without that bynameinvokationnote i am using latest java se 6 and java ee 5if you think what i am trying to achieve is not possibleplease suggest a workaround or a different concept,['java'] +11830,how do i correctly clone a javascript object i have an object x i would like to copy it as object y such that changes to y do not modify x i realized that copying objects derived from builtin javascript objects will result in extra unwanted properties this is not a problem since i am copying one of my own literalconstructed objectshow do i correctly clone a javascript object,['javascript'] +11845,c how to add subitems in listview creating an itemunder the key is easybut how to add subitemsvaluelistview1columnsaddkeylistview1columnsaddvaluelistview1itemsaddsdasdasdasdhow to add asdasdasd under value,"['c#', '.net']" +11852,c how to invoke with more than one parameter i use the code below to access the properties on my formbut today i would like to write stuff to a listviewwhich requires more parameters public string textvalue set if thismemoinvokerequired thisinvokemethodinvokerdelegate thismemotext value n else thismemotext value n how to add more than one parameter and how to use themvaluevalue,['c#'] +11855,how to use multiple caches in rails i have a rails application where i would like to use both memcached and the file store cache for different purposesi want to use the file store cache to keep a large number of pages that do not change often some not at all ie page caching and use memcached for everything else action and db caching etc the reason is that the pages stored on the file store cache are likely to require a large amount of storage but individually most will be accessed infrequentlyis this possible to do or will configuring memcached as the cache mean that it is also used for page cachingas a secondary question what is a safe way to remove pages from the file store cache in some form of cron job as there does not seem to be an option to specify ttl for this cache for example a unix find command would quickly find and remove all old pages or pages that have not been accessed in a long time is this safe to do given the app server might potentially try to serve one of those pages at the time tho this is very unlikely if not then what is the best way to do this,['ruby-on-rails'] +11857,javascript charting library google analytics style i am searching for a javascript library to create line charts like the ones of google analytics when the mouse is over a point a box shows you the dataan example is at no flash or air only js and clientside canvasbetter if free,['javascript'] +11865,do you use or define non standard annotations and for what reason how about recursive annotations the question tells it allfor the experts is there a reason the sun java 5 compiler accepts recursive annotations contrary to the langspec while the later compilers do not i mean what could be an argument against recursive annotationsedit a recursive annotation is something likepanellayoutborderlayoutclass nested panelregionnorth layoutflowlayoutclass panelregionsouth layoutflowlayoutclass,['java'] +11866,is there a difference between throw and throw ex there are some posts that asks what the difference between those two are alreadywhy do i have to even mention thisbut my question is different in a way that i am calling throw ex in another error godlike handling methodpublic class program public static void mainstring args try something catch exception ex handleexceptionex private static void handleexceptionexception ex if ex is threadabortexception ignore then return if ex is argumentoutofrangeexception log then throw ex if ex is invalidoperationexception show message then throw ex and so on if try catch were used in the main then i would use throw to rethrow the errorbut in the above simplied code all exceptions go through handleexceptiondoes throw ex has the same effect as calling throw when called inside handleexception,"['c#', '.net']" +11868,how to throw exception without resetting stack trace this is a followup question to is there a difference between athrowa and athrow exais there a way to extract a new error handling method without resetting the stack traceediti will be trying both inner method and another answer provided by earwicker and see which one can work out better to mark an answer,"['c#', '.net']" +11869,gprof and arguments to executable when using gprof gprof options executablefile profiledatafiles outfileif you have options to pass to the executable likegprof aout varfred32then gprof assumes that i am passing an invalid option to it instead of to the program being profiled aoutany way to get around this,['c++'] +11877,which is the fastest way to access native code from java which is the fastest way of calling a native library from javathe ones i know about arenativecall what were currently usingjna have not used it but looks reasonablejni looks horrendous to write but well do it if we get the speed,['java'] +11879,c how to set the autopostback property when using aspnet mvc i am using aspnet mvc framework on my page i have a dropdwonbox and when an option is clicked i want to go to another page but i cannot find howwhere to set the autopostback property to true this is the code i am usingaspx htmldropdownlistqchap new selectlist ienumerableviewdataqchap id title controllerpublic actionresult indexint id chapter c new chapter viewdataqchap cgetallchaptersbymanualid return viewwhat do i have to do to use the autopostback functionality,['c#'] +11881,applicationrestart not working in clickonce deployed application possible duplicatewhy is applicationrestart not reliable i pulled the code straight from msdn this updates my application but restart does not work the application shuts down but it does not restart i added a menuitem to my form to validate that restart works at all private void restarttoolstripmenuitem clickobject sender eventargs e applicationrestartthis will restart the application of course it performs no updates and is user initiated so it is fairly useless i have nothing else going on with this application no event handlers for the form on shutdown nothing this is the most basic windows forms application i could build it just thisplays a resource jpeg in an imagepanel why does restart not work here,['c#'] +11897,css selector for targeting only immediate children and not other identical descendants i have nested sortable list that can have items dynamically added or removed and can be nested nlevels deep on nesting a new ul element is injected into whatever li element is selected to be the parent the initial state of the list is something like the followingul idparent li idonea href classlistlinkspan classposition1spanoneali li idtwoa href classlistlinkspan classposition2spantwoali li idthreea href classlistlinkspan classposition3spanthreea ul li idaa href classlistlinkspan classposition1spanaali li idba href classlistlinkspan classposition2spanbali li idca href classlistlinkspan classposition3spancali li idda href classlistlinkspan classposition4spandali li idea href classlistlinkspan classposition5spaneali li idfa href classlistlinkspan classposition6spanfali ul li li idfoura href classlistlinkspan classposition4spanfourali li idfivea href classlistlinkspan classposition5spanfiveali li idsixa href classlistlinkspan classposition6spansixaliuli am using mootools to do the sort etc and it works fine but what i am having trouble doing is resetting the position text correctly on sort every css selector i try to use also includes all of the children rather than just the li elements that belong in the list and not any belonging to sublists assume that except for id position and text each li element in all lists is identical to all others is there a selector for getting only the immediate children is there another way to do this editi have tried some child selectors like the ones mentionedul li will select all li elementsthat are a child of a ul not just the immediatechildrenparent li does the same asaboveedit 2here is the function that i am currently having run when an item is dropped this does not handle the sorting which works fine just updating the position note that it is also mootools syntaxvar drop functionel elgetparentsulreverseeachfunctionitem var poscount 1 itemgetelementsli a spanclasspositioneachfunctionpos possettext poscount poscount currently changing any item order on the main level will renumber everything 112 even the sublists changing any item on a sublist will give the correct numbers for that list but cause the parent lists to incorrectly count all child li elements in numberingedit 3okay i feel like this is an ugly hack but it worksvar drop function var ulcount 1 uleachfunctionitem ifitemgetid parent itemsetid idulcount var elid itemgetid var poscount 1 documentgetelementselidliaspanclasspositioneachfunctionpos possettext poscount poscount ulcount,"['javascript', 'css']" +11898,how to iterate in reverse over a map in c i am having trouble iterating in reverse over a map in gcc c when i use a reverse iterator it seems i cannot assign anything to it the compiler complains i am working around it with some awkward code using a forward iterator but it is not very elegant any thoughts,['c++'] +11899,serving static files with mod wsgi and django i have a django application using mod python fairly typical configuration except that media files are being served by a i know not recommended media directory in the document root i would like to test and maybe deploy with mod wsgi but i cannot figure out how to create something simple to serve static files mod python allows the use of apache directives likelocation sethandler myapplicationxyzlocationlocation media sethandler nonelocationthe django docs seem to point to the second block above as the correct way to make a similar exception for mod wsgi but in my tests everything below root is still being sent to the wsgi app is there a good way set a static media directory with mod wsgi or is what i am trying to do intentionally unsupported for compelling technical reasons answers that point to entirely different approaches are welcome,['python'] +11914,why should we use literals in c in some c code i have seen staments like thisfloat somefloat 57fi want to know why we should use literals like f in the above case,['c#'] +11918,when to override gethashcode when should we override the gethashcode method provided by object class in system namespace,"['c#', '.net']" +11924,good text editor for windows i am looking for a text editor much like textmate wmacromatescom on mac but i want it to have a builtin compiler for example i do not want an ide like visual studio or eclipse i am looking for an editor where i can click run and it will compile my code and show me the results in a terminal i know of a text editor which is textmates sister application for windows but it does not have a builtin compiler i also do not want to install cygwin for ggcc,['c++'] +11928,why do we not have a virtual constructor in c why does c not have a virtual constructor,['c++'] +11932,renaming the created at updated at columns of activerecordrails i want to rename the timestamp columns defined in timestamprb can the methods of timestamprb be overwritten and what has to be done in the application that the module with the overwritten methods is used,['ruby-on-rails'] +11936,what is the key difference between a debug and a release build in net duplicate of debug vs release in netwhy there are debug and release modes on build in dot net applicationwhat is the major technical difference between them,['.net'] +11938,mysql vs sql server 20052008 performance i intend to start developing an aspnet application and i am wondering which database to use performance is very important and the database should be able to handle without issues a database of about 50gb i am wondering however if a sql server license is worth paying for i have looked for performance and scalability comparisons between mssql server 20052008 and mysql but i cannot seem to find any good tests can you point me to some extensive benchmarks related to this subject,"['asp.net', 'mysql']" +11943,persistent data structures in java does anyone know a library or some at least some research on creating and using persistent data structures in java i do not refer to persistence as long term storage but persistence in terms of immutability see wikipedia entryi am currently exploring different ways to model an api for persistent structures using builders seems to be a interesting solution create persistent instanceperson p buildercreatepersonclass withnamejoe withaddressbuildercreateaddressclass withcityparis build build change persistent instance ie create a new one person p2 builderupdatepwithnamejackperson p3 builderupdatep withaddressbuilderupdatepaddress withcityberlin build buildbut this still feels somewhat boilerplated any ideas,['java'] +11953,oo design do you use public properties or private fields internally i am working in c 20 but this would apply to most object oriented languages when i create classes with public properties that wrap private fields i switch back forth between whether i should use the property or field internally of course c 30 makes this easier with autoproperties but it could still applydoes it matterpublic class person private string name public string name get return name set name value public personstring name name name should i use the property or field here,['c#'] +11955,how to crop an image using c how can i write an application that will crop images in c,['c#'] +11959,c linq to sql refactoring this generic getbyid method i wrote the following methodpublic t getbyidint id var dbcontext db var table dbcontextgettablet return tabletolistsingleordefaulte converttoint16egettypegetpropertiesfirstgetvaluee null idbasically it is a method in a generic class where t is a class in a datacontextthe method gets the table from the type of t gettable and checks for the first property always being the id to the inputted parameterthe problem with this is i had to convert the table of elements to a list first to execute a gettype on the property but this is not very convenient because all the elements of the table have to be enumerated and converted to a listhow can i refactor this method to avoid a tolist on the whole tableupdatethe reason i cannot execute the where directly on the table is because i receive this exceptionmethod systemreflectionpropertyinfo getproperties has no supported translation to sqlbecause getproperties cannot be translated to sqlupdatesome people have suggested using an interface for t but the problem is that the t parameter will be a class that is auto generated in datacontextnamedesignercs and thus i cannot make it implement an interface and it is not feasible implementing the interfaces for all these database classes of linq and also the file will be regenerated once i add new tables to the datacontext thus loosing all the written dataso there has to be a better way to do thisupdatei have now implemented my code like neil williams suggestion but i am still having problems here are excerpts of the codeinterfacepublic interface ihasid int id get set datacontext view codenamespace musicrepo datacontext partial class artist ihasid public int id get return artistid set throw new systemnotimplementedexception generic methodpublic class dbaccesst where t class ihasidnew public t getbyidint id var dbcontext db var table dbcontextgettablet return tablesingleordefaulte eidequalsid the exception is being thrown on this line return tablesingleordefaulte eidequalsid and the exception issystemnotsupportedexception the member musicrepo datacontextihasidid has no supported translation to sqlupdate solutionwith the help of denis trollers posted answer and the link to the post at the code rant blog i finally managed to find a solutionpublic static propertyinfo getprimarykeythis type entitytype foreach propertyinfo property in entitytypegetproperties columnattribute attributes columnattributepropertygetcustomattributestypeofcolumnattribute true if attributeslength 1 columnattribute columnattribute attributes0 if columnattributeisprimarykey if propertypropertytype typeofint throw new applicationexceptionstringformatprimary key 0 of type 1 is not int propertyname entitytype return property throw new applicationexceptionstringformatno primary key defined for type 0 entitytypenamepublic t getbyidint id var dbcontext db var itemparameter expressionparametertypeof t item var whereexpression expressionlambdafunct bool expressionequal expressionproperty itemparameter typeof tgetprimarykeyname expressionconstantid new itemparameter return dbcontextgettabletwherewhereexpressionsingle,['c#'] +11960,can the application error dialog box be thisabled i am using hudson as a continuous integration server to test cc code unfortunatly i have a bug somewhere that causes memory corruption so on some windows machines i will sometimes get a application error dialog box explaining that an instruction referenced memory that could not be read this dialog box pops up and basically hangs the test run as it requires manual intervention is there a way to prevent this dialog box from appearing so that the test run simply fails and is reported as such in hudson is it possible to automatically generate a minidump instead of showing the dialog,['c++'] +11961,java reflection access protected field how can i access an inherited protected field from an object by reflection,['java'] +11963,how to get a users client ip address in aspnet we have requestuserhostaddress to get the ip address in aspnet but this is usually the users isps ip address not exactly the users machine ip address who for example clicked a link how can i get the real ip addressfor example in a stack overflow user profile it is last account activity 4 hours ago from 861231278 but my machine ip address is a bit different how does stack overflow get this address in some web systems there is an ip address check for some purposes for example with a certain ip address for every 24 hours can the user just have only 5 clicks on download links this ip address should be unique not for an isp that has a huge range of clients or internet usersdid i understand well,"['c#', 'asp.net']" +11976,why are methods in ruby documentation preceded by a hash sign this is something that has been bugging me for a while when i see any ruby method printed in text it usually appears asclassmethodor methodnow i would useclassmethodwhy are all ruby methods preceded by a pound sign is there any reason for it just curious,['ruby'] +11987,add new attribute element to json object using javascript how do i add new attribute element to json object using javascript,['javascript'] +12003,create weak multimap with google collections is there an equivalent to the nice mapmaker for multimaps currently i create the cache like this public static mapsessionlistperson personcache new mapmakerweakkeysmakemapthe whole point of multimap is to avoid the nested list values is there any way to construct the multimap with weak keys,['java'] +12008,cc array size at run time wo dynamic allocation is allowed i have been using c for a few years and today i do not know if this is a mere brainfart or what but how can this be perfectly legalint mainint argc char argv size t size cin size int arraysize forsize t i 0 i size i arrayi i cout i endl return 0compiled under gcc how can the size be determined at runtime without new or malloc just to double check i have googled some and all similar codes to mine are claimed to give storage size error even deitels c how to program p 261 states under common programming error 45 only constants can be used to declare the size of automatic and static arraysenlight me,"['c++', 'c']" +12010,why prefer properties to public variables other being able to sanity check values in a setter is there a more underlying reason to prefer properties to public variables,['c#'] +12023,restrict file access to authorized php users i have inherited an application with a glaring security hole it has sessionbased security but file uploads which are user specific are not secured in any way and they are stored in the public file treefilenames do not follow any convention as such making them hard to guess but the data is sensitive and thus i need to implement a security measure to prevent unauthorized file accessmoving the location of the files is not really an option so i am looking at a htaccess solution to forward requests to a php handler scriptdoes anyone have experience in implementing this type of thing or any good alternative solutions specific examples of htaccess syntax greatly appreciated as i am struggling in this area,['php'] +12028,querying the dns service records to find the hostname and tcpip in a paper about the life science identifiers see lsid tester a tool for testing life science identifier resolution services dr roderic dm page wrote given the lsid urnlsidubioorgnamebank11815 querying the dns for the srv record for lsid tcpubioorg returns animaliaubioorg80 as the location of the ubioorg lsid servicei learned that i can link lsid tcpubioorg to animaliaubioorg80 using the host command on unixhost t srv lsid tcpubioorg lsid tcpubioorg has srv record 1 0 80 animaliaubioorghow can i do this dns thing using the java j2se api without any external java library i would like a lightweight solution thank you,['java'] +12032,c or java prepend strings with stringbuilder i know we can append strings using stringbuilder is there a way we can prepend strings ie add strings in front of a string using stringbuilder so we can keep the performance benefits that stringbuilder offers,"['c#', 'java']" +12035,how can i check if a resource bundle key does not exist using jstl tags i have a resource file that will have some optional keys if the optional resource key is not present i set a default instead it appears that there is no easy way to determine if a key exists in the resource bundle so this is what i am doing to get around it fmtmessage vartitle keyloginregsignupsignupformregfromtitle cif testfnstartswithtitle fmtmessage vartitle keyloginregsignupdefaulttitle cifis there a better way,['java'] +12037,is there any cure for the preprocessor blues i know that i can kick the the preprocessor to spit out output with the e option in my particular circumstance for generated code this preprocessor output is murderous for example i have a 4gl application and informix converts this into c which in turn gets spit out to a horrible ugly messwhat i want is an editor that will allow me to specify what preprocessor values are in effect and show me only the relevant code i have something very basic working in vim matching ifdef and endif but the code is riddled with more advanced constructs such is ifndef if and else to make matters worse the constructs are logically more complex and i do not think my vim scripting skills are adequate for me to get what i want out of it for exampleif dlevel 5 define signal 1 if stackuse 1 define stack 200 else define stack 100 endifelse define signal 0 if stackuse 1 define stack 100 else define stack 50 endifendifif dlevel 0 define stack 0elif dlevel 1 define stack 100elif dlevel 5 thisplay debugptr else define stack 200endifincludes defining an expression evaluator if i want to tackle it this has to be a solved problem if you have vim suggestions or other ones please let me know,['c'] +12038,customizeremove django select box blank option i am using django 102 i have written a modelform backed by a model this model has a foreignkey where blankfalse when django generates html for this form it creates a select box with one option for each row in the table referenced by the foreignkey it also creates an option at the top of the list that has no value and thisplays as a series of dashesoption valueoptionwhat i would like to know iswhat is the cleanest way to remove this autogenerated option from the select box what is the cleanest way to customize it so that it shows asoption valueselect itemoptionin searching for a solution i came across django ticket 4653 which gave me the impression that others had the same question and that the default behavior of django may have been modified this ticket is over a year old so i was hoping there might be a cleaner way to accomplish these thingsthanks for any helpjeffedit i have configured the foreignkey field as such verb modelsforeignkeyverb blankfalse defaultget default verbthis does set the default so that it is no longer the emptydashes option but unfortunately it does not seem to resolve either of my questions that is the emptydashes option still appears in the list,['python'] +12041,google app engine intro to their data store api for people with sql background does anyone have any good information aside from the google app engine docs provided by google that gives a good overview for people with ms sql background to porting their knowledge and using google app engine data store api effectivelyfor example if you have a self created users table and a message tablewhere there is a relationship between users and message connected by the userid how would this structure be represented in google app engineselect from users inner join message on usersid messageuserid,"['python', 'sql']" +12048,extract cursor image in java i was wondering if there is a way to extract an image object from a cursor object in javaa use for this would be for instance image img extractcursorimagecursorgetdefaultcursorwhich you then can draw on a toolbar button that is the purpose i want it for,"['java', 'c++']" +12049,read net configuration from database the net 20 and up configuration system is quite powerful and extensible as long as you do not want to change the fact it all comes from xml files in the filesystemin my requirement i cannot change files since my app runs in a managed environment outside my reach but i could change the sql server databaseso i am looking at storing configuration files or sections in a sql table but how can i tie the net 20 configuration system into thisis there a way to write a custom config provider that will read its config sections not from a config file in the file system but from a table in the sql databasei have been looking at creating my own custom configurationsection or configurationelement or even a custom configuration per se but it seems i always end up back at the point that i can extend the configsystem in the filesystem as much as i like but i cannot make it read my xml fragments from a database tablewhat am i missing has someone done this already and care to explain share thanksmarcps i also tried to just read the config xml into a string and then deserializing it into the appropriate eg servicemodelconfigsection that does not work unfortunately because the configsection base class somehow does not implement a method that is required for it to be xml serializable yikes,['.net'] +12051,detect browser font size is it possible to detect browser font size also is it possible to dedect new font size when user changes the font size from menu selectionmany thanks for everybody helpbest regards,"['html', 'css']" +12053,how to release the unused capacity of a string i am dealing with a lot of strings in my programthese string data do not change through out the whole life time after they being read into my programbut since the c string reserves capacity they waste a lot of space that would not be used for surei tried to release those spaces but it did not workthe following is the simple code that i triedstring temp 1234567890123456string strcout strcapacity endl strreserve16 cout strcapacity endl capacity is 31 on my computer str temp cout strcapacity endl strreserve16 cout strcapacity endl cannot release the capacity is still 31the compiler is visual chow could i release it,['c++'] +12059,what is the difference between debugwrite and tracewrite what is the difference between debugwrite and tracewrite when should each be used,['.net'] +12068,sqlalchemy manytomany orphan deletion i am trying to use sqlalchemy to implement a basic usersgroups model where users can have multiple groups and groups can have multiple userswhen a group becomes empty i want the group to be deleted along with other things associated with the group fortunately sqlalchemys cascade works fine with these more simple situationsthe problem is that cascadeall deleteorphan does not do exactly what i want instead of deleting the group when the group becomes empty it deletes the group when any member leaves the groupadding triggers to the database works fine for deleting a group when it becomes empty except that triggers seem to bypass sqlalchemys cascade processing so things associated with the group do not get deletedwhat is the best way to delete a group when all of its members leave and have this deletion cascade to related entitiesi understand that i could do this manually by finding every place in my code where a user can leave a group and then doing the same thing as the trigger however i am afraid that i would miss places in the code and i am lazy,['python'] +12072,parse an xml with simplexml which has multiple namespaces i have this ugly xml which has alot of namespaces on it when i try to load it with simplexml if i indicate the first namespace i would get an xml object but following tags with other namespaces would not make it to the object how can i parse this xml xml version10 encodingutf8soapenvenvelope xmlnssoapenv soapenvheader ebmessageheader xmlnseb ebversion10 soapenvmustunderstand1 ebfrom ebpartyid ebtypeuriwscompanycomebpartyid ebfrom ebto ebpartyid ebtypeurimysitecomebpartyid ebto ebcpaidsomethingebcpaid ebconversationidmoredatacomebconversationid ebservice ebtypecompxmltheserviceebservice ebactiontheactionebaction ebmessagedata ebmessageida certain messageidebmessageid ebtimestamp20090411t184358ebtimestamp ebreftomessageidmidareferenceebreftomessageid ebmessagedata ebmessageheader wssesecurity xmlnswsse wssebinarysecuritytoken valuetypestring encodingtypewssebase64binaryan impresive binary security toeknwssebinarysecuritytoken wssesecurity soapenvheader soapenvbody sessioncreaters xmlns version1 statusapproved conversationidthe goodbye tokenconversationid sessioncreaters soapenvbodysoapenvenvelopeim trying to parse it with the following codephpxml simplexml load stringresnullnullbut the xml object would only contain the followingsimplexmlelement object header simplexmlelement object body simplexmlelement object,['php'] +12075,python write string directly to tarfile is there a way to write a string directly to a tarfile from it looks like only files already written to the file system can be added,['python'] +12076,javascript load events for embed elements if i do an online onload event for embed objects that seems to work but i cannot seem to get the load event working through addeventlistener is this expected,['javascript'] +12093,getting the time elapsed objectivec i need to get time that elapsed between two events for example between appearance of uiview and between users first reaction,"['iphone', 'objective-c']" +12097,programatically determining amount of parameters a function requires python i was creating a simple command line utility and using a dictionary as a sort of case statement with key words linking to their apropriate function the functions all have different amount of arguments required so currently to check if the user entered the correct amount of arguments needed for each function i placed the required amount inside the dictionary case statement in the form keywordfunctionname amountofargumentsthis current setup works perfectly fine however i was just wondering in the interest of self improval if there was a way to determine the required number of arguments in a function and my google attempts have returned so far nothing of value but i see how args and kwargs could screw such a command up because of the limitless amount of arguments they allowthanks for any help,['python'] +12102,how to detect the point of a stack overflow i have the following problem with my c program somewhere is a stack overflow despite compiling without optimization and with debugger symbols the program exits with this output within or outside of gdb on linuxprogram terminated with signal sigsegv segmentation faultthe program no longer existsthe only way i could detect that this actually is stack overflow was running the program through valgrind is there any way i can somehow force the operating system to dump a call stack trace which would help me locate the problemsadly gdb does not allow me to easily tap into the program either,['c'] +12103,does anyone know a dom inspector javascript library or plugin does anyone know of a dom inspector javascript library or plugini want to use this code inside a website i am creating i searched a lot but did not find what i wanted except this one helphtmlupdateseems that no one understood my question i want to find an example or plugin which let me implement dom inspector i do not want a tool to inspect doms with i want to write my own,"['javascript', 'jquery', 'html']" +12109,tsql update with insert into select from so i have an old database that i am migrating to a new one the new one has a slightly different but mostlycompatible schema additionally i want to renumber all tables from zero currently i have been using a tool i wrote that manually retrieves the old record inserts it into the new database and updates a v2 id field in the old database to show its corresponding id location in the new database for example i am selecting from mv5posts and inserting into mv6posts upon the insert i retrieve the id of the new row in mv6posts and update it in the old mv5postsmv6id field is there a way to do this update via insert into select from so i do not have to process every record manually i am using sql server 2005 dev edition,"['c#', 'sql']" +12110,how to access command line parameters outside of main in c i am writing a net class that needs to parse the command line of the process i do not want to have a dependency between the main method and that class how can the class access the command line,['.net'] +12112,rails active record findall order issue i seem to be unable to use the activerecordbasefind option order for more than one column at a time for example i have a show model with date and attending columnsif i run the following codeshows showfindall order datei get the following resultsshow id 7 date 20090418 attending 2 show id 1 date 20090418 attending 78 show id 2 date 20090419 attending 91 show id 3 date 20090420 attending 16 show id 4 date 20090421 attending 136if i run the following code shows showfindall order attending descshow id 4 date 20090421 attending 136 show id 2 date 20090419 attending 91 show id 1 date 20090418 attending 78 show id 3 date 20090420 attending 16 show id 7 date 20090418 attending 2but if i runshows showfindall order date attending descor shows showfindall order date attending ascor shows showfindall order date asc attending desci get the same results as only sorting by date show id 7 date 20090418 attending 2 show id 1 date 20090418 attending 78 show id 2 date 20090419 attending 91 show id 3 date 20090420 attending 16 show id 4 date 20090421 attending 136where as i want to get these resultsshow id 1 date 20090418 attending 78show id 7 date 20090418 attending 2 show id 2 date 20090419 attending 91 show id 3 date 20090420 attending 16 show id 4 date 20090421 attending 136this is the query being generated from the logs4351muser load 06ms0m 0mselect from users where usersid 1 limit 10m4361mshow load 30ms0m 01mselect from shows order by date asc attending desc0m4351muser load 06ms0m 0mselect from users where usersid 1 0mfinally here is my model create table shows force true do t tstring headliner tstring openers tstring venue tdate date ttext description tdatetime created at tdatetime updated at tdecimal price ttime showtime tinteger attending default 0 tstring time endwhat am i missing what am i doing wrongupdate thanks for all your help but it seems that all of you were stumped as much as i was what solved the problem was actually switching databases i switched from the default sqlite3 to mysql,"['ruby-on-rails', 'ruby']" +12114,clone is not cloning select values i did not expect it but the following test fails on the cloned value checktestclone should retain values of select function var select selectappendoption val1 appendoption val2 selectval2 equalsselectfindoptionselectedval 2 expect 2 var clone selectclone equalsclonefindoptionselectedval 2 expect 2is this right,['jquery'] +12117,which initializers to override for uitableviewcontroller subclass i have a uitableviewcontroller subclass that is instantiated depending on where it is used in a nib or via code in both cases i want to do customization in the initializer method does that mean i need to implement both initwithnibnamebundle and initwithcoder and would each method call its respective super initializerwhile i do not need this right now what if i also want to be able to instantiate the view controller with initwithstyle would i then need 3 different init methods that replicate the same behaviorit seems like this violates the whole designated initializer convention as there would essentially be 3 separate initializers that do not end up calling a common init method or is there a way to create a common designated initializer while supporting the 3 different instantiate routes,"['iphone', 'objective-c']" +12127,page refresh causes duplicate post in aspnet applications i have an application in which i am adding a new record and the record is added two times if i am pressing refresh buttoni am clearing the cache but i am having the same problemwhat to do,['asp.net'] +12140,turning off autocomplete for text fields in firefox am supposed to be learning french at the moment but rather than learning any vocab i have been mucking around with a rails app that tests vocab so it thisplays a word and i have to type its translationunfortunately firefox remembers everything i have already type there so which diminishes its usefulness somewhatis it possible through the options for form for or otherwise to turn this normally useful behaviour off,['ruby-on-rails'] +12142,tripledes specified key is a known weak key for tripledes and cannot be used i am using the net 30 class systemsecuritycryptographymactripledes class to generate a mac value unfortunately i am working with a hardware device that uses 1 as hex as a singlelength des key the systemsecuritycryptography library does some sanity checking on the key and returns a exception if you try to use a cryptographically weak keyfor examplebyte key new byte24for int i 0 i keylength i keyi 0x11byte data new byte 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 byte computedmac nullusing mactripledes mac new mactripledeskey computedmac maccomputehashdatathrows an exceptionsystemsecuritycryptographycryptographicexception specified key is a known weak key for tripledes and cannot be usedi know this is not a secure key in production the device will be flashed with a new secure key in the mean time is there any way to inhibit this exception from being thrown perhaps an appconfig or registry settingedit the key would actually be 101010 due to the algorithm forcing odd parity i am not sure if this is universal to the des algorithm or just a requirement in the payment processing work i doedit 2 daniels answer below has some very good information about hacking net unfortunately i was not able to solve my problem using this technique but there is still some interesting reading there,"['c#', '.net']" +12145,converting ruby to c need to convert the following code from ruby to c however i am kind of puzzled by the use of the yield keyword and the general syntax of ruby can anyone that knows a little bit ruby please help out and convert the code class cachestale refresh 1stale created 2 caches data received from a block the difference between this method and usual cacheget is following this method caches data and allows user to regenerate data when it is expired wo running data generation code more than once so dogpile effect would not bring our servers downdef smart getkey ttl nil generation time 30seconds fallback to default caching approach if no ttl given return getkey yield unless ttl create window for data refresh real ttl ttl generation time 2 stale key keystale try to get data from memcache value getkey stale getstale key if stale key has expired it is time to regenerate our data unless stale putstale key stale refresh generation time lock value nil force data regeneration end if no data retrieved or data regeneration forced regenerate data and reset stale key unless value value yield putkey value real ttl putstale key stale created ttl unlock end return valueendend,"['c#', 'ruby']" +12148,does it make sense to integrate scripting languages to c apps i have been thinking about integrating ruby into my app but some of my friends at work told me that c is already very high level but to me it seems like it has more baggage for doing very quick thingswhat do you guys thinkalso if i do integrate then does it make sense to limit it so that you can do just about anything using the existing functionality of the app but not extend itreason for this is scritping languages are not known for performance and if you say give people to write filters like blur contrast etc then those would be way slower than they should be and degrade the experience of the client of the scripter right,"['c#', '.net']" +12154,hide mouse cursor after an idle time i want to hide my mouse cursor after an idle time and it will be showed up when i move the mouse i tried to use a timer but it did not work well can anybody help me please,['c#'] +12157,using jquery hover with html image map i have a complicated background image with a lot of small regions that need rollover illustration highlights along with additional text thisplay and associated links for each one the final illustration stacks several static images with transparency using zindex and the highlight rollover illustrations need to thisplay in one of the inbetween asandwicha layers to achieve the desired effectafter some unsuccessful fiddling with blocks i decided this might be done with an oldschool image map i made a schematic test map with four geometric shape outlines and afilleda them using with png rollovers the idea is to associate the image map with the bottom background layer initialize all the rollovers with css visibility hidden and use jqueryas hover method to make them visible as well as reveal associated text in a separate div the separate text function is why iam not trying to this with the hover pseudoclass instead of jquery hover because i was using the image map i made all the rollover pngs which have transparent backgrounds sized to the full container for exact placement so everything lines up preciselywhat i got works not really the image map is correctly mapped to activate only the geometric areas but the href from each rollover area works only intermittently and using jquery hover with css visibility is messed up desired behavior is that rolling into the area simply would make the shape solid what actually happens is any motion inside the shape makes rapid toggling between visible and hidden when the cursor stops within the shape it might be visible or it might not any ideas appreciatedsample hover setup iall ultimately use arrays for real rollovers associated links and texttrianglehover function id trianglecssvisibility visible function id trianglecssvisibility hidden image mapdiv idcontainer img srcimagestestmap wpng width800 height220 alttestmap w usemaptestmap map nametestmap area shapepolygon coords20201062010610620106 href idbox area shapepolygon coords2165033950277156 href idtriangle area shapepolygon coords46005740460220 href idbordertriangle area shapepolygon coords704657691157441965196640115 href idpentagon map img srcimagestestmap boxpng width800 height220 alttestmap box idid box img srcimagestestmap trianglepng width800 height220 alttestmap triangle idid triangle img srcimagestestmap border trianglepng width800 height220 alttestmap border triangle idid bordertriangle img srcimagestestmap pentagonpng width800 height220 alttestmap pentagon idid pentagondiv,"['javascript', 'jquery']" +12158,how to determine uiwebview height based on content within a variable height uitableview i am trying to create a uitableview with variable height rows as explained in the answer to this questionmy problem is each cell contains a uiwebview with different statically loaded content i cannot figure out how to calculate the proper height based on the content is there a way to do this i have tried things like this cgfloattableviewuitableview tableview heightforrowatindexpathnsindexpath indexpath webviewcell cell webviewcellself tableviewtableview cellforrowatindexpathindexpath cell setneedslayout cell layoutifneeded return cellboundssizeheight the cells themselves are loaded from a nib which is simply a uitableviewcell containing a uiwebview it would also be fine if the cells just adjusted themselves to the largest of the html content though variable height would be nicer,"['ios', 'iphone']" +12160,c sizeof decimal unclear on the sizeof for decimal types does the size in bytes vary by precision as in sql server is the precision variable for the c type decimali do not want to turn on unsafe code to just call sizeof on a decimal type how would you approach this,['c#'] +12179,realistic usage of the c99 restrict keyword i was browsing through some documentation and questionsanswers and saw it mentioned i read a brief description stating that it would be basically a promise from the programmer that the pointer would not be used to point somewhere else can anyone offer some realistic cases where its worth actually using this,['c'] +12182,aspnet scroll to control i have got a particularly large form in an page when the form is validated and a field is invalid i want to scroll the window to that control calling the controls focus does not seem to do this i have found a javascript workaround to scroll the window to the control but is there anything built into aspnet,['asp.net'] +12186,copy constructors c can i write a copy constructor by just passing in a pointer instead of the const reference would it be ok if i make sure that i am not going to change any values thoughlike sosampleclasampleclasampleclass p do the necessary copy functionalityinstead ofsampleclasampleclassconst sampleclass copyobjdo the necessary copythanks in advancethanks everyone so if i write a constructor that takes in a pointer and thought that is my copy constructor the compiler would still supply with the default copy constructor in which case my constructor which i thought was my copy constructor would not be called and the default copy constructor would be called got it,['c++'] +12187,where do i save partial views in zend framework to be accessible for all views in my app i have several view partials like paginator partial which i want them to be availableto all view scripts in my applicationis there a directory i can put partial vies in and they will be available to allor how do i define such a directory,['php'] +12190,filtering fiddler to only capture requests for a certain domain i am not sure how to modify the customrulesjs file to only show requests for a certain domaindoes anyone know how to accomplish this,"['c#', '.net']" +12192,how to lose marginpadding in uitextview i have a uitextview in my ios application which thisplays a large amount of text i am then paging this text by using the offset margin parameter of the uitextview my problem is that the padding of the uitextview is confusing my calculations as it seems to be different depending on the font size and typeface that i usetherefore i pose the question is it possible to remove the padding surrounding the content of the uitextviewlook forward to hearing your responses,"['ios', 'iphone']" +12203,whats wrong with calling invoke regardless of invokerequired i have seen the common setup for cross threading access to a gui control such as thiscussed hereall the web hits i found describe a similar thinghowever why do we need to check invokerequired cannot we just call invoke directlyi assume the answer is no so my real question is why,['c#'] +12204,rails validation and fieldwitherrors wrapping select tags is it normal behaviour to not get the div classfieldwitherrors wrapped arround select tags that have validation errors i personally see no reason why the select tags should be treated differently than other form tags input textareai do get the error in error messages for and error message on methods for that fieldps i have altered a bit the actionviewbasefield error proc in order to get span tags instead of divs but that is not the problemactionviewbasefield error proc procnew html tag instance if i puts html tag here i only get the input tags span classfieldwitherrorshtml tagspan,['ruby-on-rails'] +12205,debugging on linux for windows developer primarily i have done basic novice level software development on a windows machine but i have always had ms visual studio to help me step through the process of debugging now however it looks like i will be on linux so in order to get ready for the jump i want to make sure i have a tooltools lined up to help me step through the code and debug unfortunately when i have verbally asked folks how they go about debugging on linux i typically get the following answer oh i just put a bunch of print statements omg no way you say but yes that is their answer since it is on linux and will be working with c code on the centos 32bit os i am hoping here is a preferred opensource solution so i guess i asking for the preferred opensource ide for c code on centos linux thanks for any insight and suggestions,['c++'] +12206,differences between jvm implementations where do jvm implementations differ except licensingdoes every jvm implement type erasure for the generic handlingwhere are the differences betweenjrockitibm jvmsun jvmopen jdkblackdown kaffedeals one of them with tailcalloptimization,['java'] +12210,what is the meaning of numeric limitsdigits10 what is the precise meaning of numeric limitsdigits10some other related questions in stackoverflow made me think it is the maximum precision of a double but the following prototype starts working sucess is true when precision is greater that 17 2numeric limitsdigits10with stlport readdoubleinfinity at the end with microsofts stl readdouble 00has this prototype any kind of meaning here is the prototypeinclude floathinclude limitsinclude mathhinclude iostreaminclude iomanipinclude sstreaminclude stringint mainint argc const char argv stdostringstream os int digit10stdnumeric limitsdoubledigits10 15 int digitstdnumeric limitsdoubledigits 53 os stdsetprecision17 os dbl max stdcout osstr stdstringbuf sbosstr stdistream issb double readdouble00 is readdouble bool success fabsdbl maxreaddouble01,['c++'] +12212,jquery selecting checked checkbox suppose i have the following htmlform idmyform input typecheckbox namefoo check 1br input typecheckbox namefoo checkedtrue check 2br input typecheckbox namefoo check 3brformnow how do i select the checked input fields with name foothis is my try but it does not workmyform inputnamefoocheckedenabled,['jquery'] +12219,how to thisplay simple html in a silverlight textblock i have got a source of data that has html tags in it b i a and need to thisplay this in a silverlight listbox searching around it seems to be an issue but most of the posts are old and have to do with silverlight 1 it seemswhat is currently the best way to thisplay simple html with silverlight if nothing else just the b i and a tags for bold italic and hyperlinks,['html'] +12221,benchmarking django apps i am interested in testing the performance of my django apps as i go what is the best way to get line by line performance datanote googling this returns lots of people benchmarking django itself i am not looking for a benchmarks of django i am trying to test the performance of the django apps that i am writing thanksedit by line by line i just mean timing individual functions db calls etc to find out where the bottlenecks are on a very granular level,['python'] +12229,updating thisplay order of multiple mysql rows in one or very few queries i have a table with say 20 rows each with a number for thisplay order 120select from mytable order by thisplay order descfrom an admin area you can drag the rows around or type a new number manually for each rowsurely it is not good to loop over an update query for every row whats an alternative in one or very few queries suitable for updating one cell in 20 rows or even more 50200edit a lot of good responses and ideas i might expand on the ideas i have considered so farone array string i could have the order in a string listing the unique row ids in the order i want eg rows 192623 when the order is updated a hidden field updates with javascript and adds that to the database or a text file when completeupdate my thispaly order table set thisplay order192623update each row individually this is what i was trying to avoid but it would only be changed very infrequently so 2030 calls in one hit once a week or month might not be a problem so simply calling update on each row is what i usually doupdate mytable set thisplay order1 where rowid 1update mytable set thisplay order2 where rowid 9update mytable set thisplay order3 where rowid 2update mytable set thisplay order4 where rowid 6update mytable set thisplay order5 where rowid 23,"['php', 'mysql']" +12230,best way to obfuscate an email address on a website i have spent the past few days working on updating my personal website the url of my personal website is my first namemy last namecom as my last name is rather unusual and i was lucky enough to pick up the domain name my email address is my first namemy last namecom so really when it comes down to guessing it it is not very hardanyways i want to integrate a mailto link into my website so people can contact me and despite my email address not being very hard to guess i would rather not have it harvested by spam bots that just crawl websites for email address patterns and add them to their databasewhat is the best way for me to obfuscate my email address preferably in link form the methods i know of area hrefmailtoemail meait works but it also means that as soon as my website hits google i will be wading through spam as spam bots easily pick out my email addressimg srcimagesemailpng this is less desirable because not only will visitors be unable to click on it to send me an email but smarter spam bots will probably be able to detect the characters that the image containsi know that there is probably no perfect solution but i was just wondering what everyone thought was best i am definitely willing to use javascript if necessary as my website already makes use of tons of it,"['javascript', 'html']" +12233,does the sun jvm slow down when more memory is allocated via xmx does the sun jvm slow down when more memory is available and used via xmx assumption the machine has enough physical memory so that virtual memory swapping is not a problemi ask because my production servers are to receive a memory upgrade i would like to bump up the xmx value to something decadent the idea is to prevent any heap space exhaustion failures due to my own programming errors that occur from time to time rare events but they could be avoided with my rapidly evolving webapp if i had an obscene xmx value like 2048mb or higher the application is heavily monitored so unusual spikes in jvm memory consumption would be noticed and any flaws fixedpossible important detailsjava 6 runnign in 64bit mode4core xeonrhel4 64bitspring hibernatehigh thisk and network ioedit i tried to avoid posting the configuration of my jvm but clearly that makes the question ridiculously open ended so here we go with relevant configuration parametersxms256m xmx1024m xxuseconcmarksweepgc xxalwaysactasserverclassmachine xxmaxgcpausemillis10 xxmaxgcminorpausemillis10 xxprintgctimestamps xxheapdumponoutofmemoryerror,['java'] +12236,keep a http connection alive in c how do i keep a connection alive in c i am not doing it right am i suppose to create an httpwebrequest obj and use it to go to any urls i need i dont see a way to visit a url other then the httpwebrequestcreate static methodhow do i create a connection keep it alive browse multiple pagesmedia on the page and support proxys i hear proxy are easy and support is almost standardedit good answers how do i request a 2nd url httpwebrequest webrequestobject httpwebrequesthttpwebrequestcreatewebrequestobjectkeepalive truedo stuffwebrequestobjectsomething allimageslogogif,['c#'] +12237,partial list unpack in python in python the assignment operator can unpack list or tuple into variables like thisl 1 2a b l here goes auto unpackbut i need to specify exactly the same amount of names to the left as an items count in the list to the right but sometimes i do not know a size of the list to the right for example if i use split examplea b length25split this will result in alength and b25but the following code will lead to an errora b default lengthsplit error list has only one itemis it possible to somehow unpack list in the example above so i get a default length and b equals to none or not set a straightforward way looks kind of longa b noneif in string a b stringsplitelse a string,['python'] +12242,default values in a c struct i have a data structure like this struct foo int id int route int backup route int current route and a function called update that is used to request changes in it update42 dont care dont care new routethis is really long and if i add something to the structure i have to add a dont care to every call to update i am thinking about passing it a struct instead but filling in the struct with dont care beforehand is even more tedious than just spelling it out in the function call can i create the struct somewhere with default values of dont care and just set the fields i care about after i declare it as a local variable struct foo bar id 42 current route new route updatebarwhat is the most elegant way to pass just the information i wish to express to the update function and i want everything else to default to 1 the secret code for dont care,['c'] +12266,how can i print a single jpanels contents i have a jpanel with two labels with pictures i need to print these content of the jpanel please help me out how can i print only this jpanels contents as i also have different components on my jframe but i just need to print this jpanelthanks,['java'] +12268,java xml apis i have dealt with a few xml apis in java but i do not have a good understanding of all the frameworks available in java for dealing with xml for whatever purpose eg jaxb jaxp xerces stax castor etc can anyone highlight the most popular java xml apis and give a quick description of what they are intended to be used for i would also be interested in which apis are used nowadays and which might be considered deprecated,['java'] +12282,best way to get the next id number without identity i have to insert some records in a table in a legacy database and since it is used by other ancient systems changing the table is not a solutionthe problem is that the target table has a int primary key but no identity specification so i have to find the next available id and use thatselect idisnullmaxrecid11 from subscriberhowever i want to prevent other applications from inserting into the table when i am doing this so that we do not have any problems i tried thisbegin transaction declare id as int select idisnullmaxrecid11 from subscriber with holdlock tablock select id waitfor delay 01 insert into subscriber recid values idcommit transactionselect from subscriberin two different windows in sql management studio and the one transaction is always killed as a deadlock victim i also tried set transaction isolation level serializable first with the same resultany good suggestions to how i can ensure that i get the next id and use that without risking that someone else or me is getting hosedsorry for not mentioning this earlier but this is a sql 20 server so i cannot use things like for update and output update this is the solution that worked for mebegin transaction declare id int select idrecid from identities with updlock rowlock where table name subscriber waitfor delay 06 insert into subscriber recid values id update identities set recidrecid1 where table name subscribercommit transactionselect from subscriberthe waitfor is so that i can have multiple connections and start the query several times to provoke concurrency thanks to quassnoi for the answer and to all you other guys that contributed awesome,['sql'] +12286,how to xml configure spring bean for constructor injection when bean has varargs constructor is there a way to write a spring bean in xml so that it uses constructor injection when that constructor has a varargs parameter type ie is there a way to specify an array the way you can specify a list for instanceclass myclass myclastring args rest omitted,['java'] +12290,which validation framework to choose spring validation or validation application block enterprise library 40 i am trying to choose one of the validation frameworks for a major application and while both options seem enticing i was wondering whether there are any specific pros and cons i should be aware of before committing to one or the other,['.net'] +12294,multiple footer rows in a jsf datatable i am wanting to know if there is any way to have multiple footer rows in a hdatatable or tdatatable i want to do somthing like this which does not compile hdatatable varrow hcolumn ffacet nameheader header ffacet houtputtext valuerowvalue ffacet namefooter firstfooter ffacet ffacet namefooter second footer in a new tr ffacet hcolumnhdatatablewith the result being somthing like thistable border1 styleborder1px solidtheadtrthheaderthtrtheadtbodytrtddata value 1tdtrtrtddata value 2tdtrtrtddata value tdtrtrtddata value ntdtrtbodytfoottrtdfirstfootertdtrtrtdsecond footer in a new trtdtrtfoottableany ideas how best to accomplish thisthankseditit would be great if i could avoid using a custom controlcustom renderer,['java'] +12296,initializing a genericlist in c in c i can initialize a list using the following syntaxlistint intlist new listint 1 2 3 i would like to know how that syntax works and if it has a name there is a constructor that takes an ienumerable you could call thatlistint intlist new listintnew int 1 2 3 that seems more standard when i deconstruct the default constructor for the list i only see this items arrayemptyi would like to be able to do thiscustomclass abc new customclass 1 2 3and be able to use the 1 2 3 list how does this workupdate jon skeet answeredit is calling the parameterless constructor and then calling add listint tmp new listint tmpadd1 tmpadd2 tmpadd3 listint intlist tmpi understand what is does i want to know how how does that syntax know to call the add method updatei know how cliche to accept a jon skeet answer but the example with the strings and ints is awesome also a very helpful msdn page isobject and collection initializers c programming guide,"['c#', '.net']" +12302,downsides to immutable objects in java the advantages of immutable objects in java seem clearconsistent stateautomatic thread safetysimplicityyou can favour immutability by using private final fields and constructor injectionbut what are the downsides to favouring immutable objects in javaieincompatibility with orm or web presentation toolsinflexible designimplementation complexitiesis it possible to design a largescale system deep object graph that predominately uses immutable objects,['java'] +12313,how to connect to https server using common access card i need to write a java program to connect to a https server dod website the website requires cac dod common access card authentication if you access this site via browser you insert your cac first and then enter a pini need to accomplish the authentication process programmatically in java kind of acting like browser how do i retrieve the information from the cac i have been googling around and read the java pkcs11 reference guide seems like sun pkcs11 provider can do it but you need the native pkcs11 token implementation am i right has anybody done this before any suggestion or comment will be greatly appreciated,['java'] +12321,programmatically generate video or animated gif in python i have a series of images that i want to create a video from ideally i could specify a frame duration for each frame but a fixed frame rate would be fine too i am doing this in wxpython so i can render to a wxdc or i can save the images to files like png is there a python library that will allow me to create either a video avi mpg etc or an animated gif from these framesedit i have already tried pil and it does not seem to work can someone correct me with this conclusion or suggest another toolkit this link seems to backup my conclusion regarding pil,['python'] +12322,how to catch error in jquerys load method i am using jquerys load method for reterive some data when user click on buttonthen show the result in it is okbut the problem is i do not know how to catch error in load when error occure while data reterivingplease help me thanks,['jquery'] +12327,inheritance and overriding init in python i was reading dive into python and in the chapter on classes it gives this exampleclass fileinfouserdict store file metadata def init self filenamenone userdict init self selfname filenamethe author then says that if you want to override the init method you must explicitly call the parent init with the correct parameters what if that fileinfo class had more than one ancestor classdo i have to explicitly call all of the ancestor classes init methods also do i have to do this to any other method i want to override,['python'] +12350,what is the purpose of the subinterpreter api in cpython i am unclear on why the subinterpreter api exists and why it is used in modules such as the mod wsgi apache module is it mainly used for creating a security sandbox for different applications running within the same process or is it a way to allow concurrency with multiple threads maybe both are there other purposes,['python'] +12352,how do i detect that an object is a generic collection and what types it contains i have a string serialization utility that takes a variable of almost any type and converts it into a string thus for example according to my convention an integer value of 123 would be serialized as i3123 iinteger 3length of string 123valuethe utility handles all primitive type as well as some nongeneric collections like arraylists and hashtables the interface is of the formpublic static string stringserializeobject o and internally i detect what type the object is and serialize it accordinglynow i want to upgrade my utility to handle generic collections the funny thing is i cannot find an appropriate function to detect that the object is a generic collection and what types it contains both of which pieces of information i need in order to serialize it correctly to date i have been using coding of the form if o is int do somethingbut that does not seem to work with genericswhat do you recommendedit thanks to lucero i have gotten closer to the answer but i am stuck at this little syntactical conundrum hereif tisgenerictype if typeoflist tgetgenerictypedefinition type lt tgetgenericarguments0 listlt x listlto stringifylistx this code does not compile because lt is not allowed as the t argument of a list object why not and what is the correct syntax,['c#'] +12357,customizing uislider look to customize the visual look of a uislider you can set the thumb and track images part of the track images gets stretched to the appropriate with from the documentationa stretchable region sits between two end cap regions the end caps define the portions of the image that remain as is and are not stretched the stretchable region is a 1point wide area between the end caps that can be replicated to make the image appear longernow the problem i have is that my stretchable region needs to be more than 1point wide it is a pattern unfortunately the 1point width seems to be hard coded in the sdkanyone having an idea how to work around this or will i have to write my own slider from scratch for this,['ios'] +12359,best practice in cakephp for saving data using models in component i am writing a cake component and it seems to make sense that i use it for saving data rather than doing so in a controller in the manual it says using models in a component is thiscouraged but the other way of doing it would mean i would be repeating code in the controllerthe component basically analyses a load of data from various sources and will then insert data for various models,['php'] +12367,how to retrieve field names from temporary table sql server 2008 i am using sql server 2008 say i create a temporary table like this onecreate table mytemptable col1 intcol2 varchar10how can i retrieve the list of fields dynamically i would like to see something like thisfieldscol1col2i was thinking of querying syscolumns but it does not seem to store any info about temporary tables any ideas,['sql'] +12369,pylint warning on except exception for a block like thistry some stuffexcept exception passpylint raises warning w0703 catch exception why,['python'] +12373,striped table rows in aspnet mvc without using jquery or equivalent when using an aspnet webforms listview control to thisplay data in an html table i use the following technique in to stripe the table rowsitemtemplate tr class containerthisplayindex 2 0 alternate table cells in here tritemtemplatewith the following csstralternate backgroundcolor eff5fbi have just gone through the aspnet mvc movie database application tutorial and learnt that in mvcland table rows can be must be constructed as follows foreach var item in model tr td htmlencodeitemtitle td and so on for the rest of the table cells tr what can i add to this code to stripe the rows of my tablenote i know that this can be done using jquery i want to know if it can be done another wayeditif jquery or equivalent is in your opinion the best or most appropriate post i would be interested in knowing why,['jquery'] +12380,multiple tuple to twopair tuple in python what is the nicest way of splitting thistuple a b c d e f g hinto thistuples a b c d e f g hassuming that the input always has an even number of values,['python'] +12385,java priorityqueue removal of arbitrary elements performance say i have a java priorityqueue which java implements as a heap that i iterate over to remove elements based on some criteriapriorityqueue q new priorityqueueiterator it qiteratorwhileithasnext if somecriterionitnext itremovehow long does each remove operation take i am not sure whether it is ologn or o1,['java'] +12398,is making a function template specialization virtual legal in c a function template specialization is supposed to act exactly like a normal function does that mean that i can make one virtualfor examplestruct a template class t void f template virtual void fint struct b a template class t void f template virtual void fint int mainint argc char argv b b a a b afintvisual studio 2005 gives me the following errorfatal error c1001 an internal error has occurred in the compiler,['c++'] +12400,programatically calculate memory occupied by a java object including objects it references i need to programmatically find out exactly how much memory a given java object is occupying including the memory occupied by the objects that it is referencingi can generate a memory heap dump and analyse the results using a tool however it takes a considerable amount of time to generate a heap dump and for such a tool to read the dump to generate reports given the fact that i will probably need to do this several times my work would be a lot more agile if i could throw in some code in my project that would give me this value runtimeany ideas as to how i could best achieve thisps specifically i have a collection of objects of type javaxxmltransformtemplates,['java'] +12426,is it possible to make anonymous inner classes in java static in java nested classes can be either static or not if they are static they do not contain a reference to the pointer of the containing instance they are also not called inner classes anymore they are called nested classesforgetting to make an nested class static when it does not need that reference can lead to problems with garbage collection or escape analysisis is possible to make an anonymous inner class static as well or does the compiler figure this out automatically which it could because there cannot be any subclassesfor example if i make an anonymous comparator i almost never need the reference to the outside collectionssortlist new comparatorstring int comparestring a string b return atouppercasecomparetobtouppercase,['java'] +12446,how to implement a keyword search in mysql hi alli am really a new sq l programmer can some one help me in solving thisi have a table job where the fields are idpositioncategorylocationsalary range description refnoi want to implement a keyword search from the front end the keyword can be reside in any of the field of the said table,"['sql', 'mysql']" +12452,add request to django model method i am keeping track of a user status on a model for the model lesson i have the status finished learning viewed in a view for a list of models i want to add the user status what is the best way to do thisone idea adding the request to a models method would do the trick is that possibleedit i meant in templatecode lessonget status with get statusself request is it possible it does not work yet,['python'] +12456,what does the suffix den mean on the value of a variable when debugging in vs2005 i have a float in the locals window whose values is1744e039denwhat does the den signifystand for,['c++'] +12474,is it legal to write to stdstring in stdstring there are only const members to fetch the data like c str however i can get a reference to the first element of the string via operator and i can write to itfor example if i have functionvoid toupperchar firstchar last plus onei can write directly to vector getting a pointer to the first elementvectorchar message has some messagetouppermessage0message0messagesizecan i do same thing with stdstringstring messagesome messagetouppermessage0message0messagesizedoes the standard guarantee that the location of the memory is actually linear iemessagebeginn messagenthanks,['c++'] +12483,how does the in predicate work in sql after prepairing an answer for this question i found i could not verify my answerin my first programming job i was told that a query within the in predicate gets executed for every row contained in the parent query and therefore using in should be avoidedfor example given the queryselect count from table1 where table1id not in select table1id from table2 where id user 1table1 rows of in executions 10 10 100 100 10 10 10 10is this correct how does the in predicate actually work,['sql'] +12487,why csvreader is not pythonic i started to use the csvreader in python 26 but you cannot use len on it or slice it etc whats the reason behind this it certainly feels very limitingor is this just an abandoned module in later versions,['python'] +12492,how can i check for average concurrent events in a sql table based on the date time and duration of the events i have a set of call detail records and from those records i am supposed to determine the average concurrent active calls per system per hour at a precision of one minute if i query 7pm to 8pm i should see the average concurrent calls for the hour averaging the concurrent calls for each minute within that hour for each system so i need a way to check for a count of active calls for 700701 701702 etc then average those numbers a call is considered active if the calls time and duration fall within the current minute being checkedwhat makes this even more difficult is that it needs to span sql 70 and sql 20 some functions in 20 are not available in 70 such as getutctime if i can just get 20 working i will be happywhat approaches to this problem can i takei thought about looping through minutes 60 in the hour being checked and adding the count of calls that fall between that minute and then somehow cross referencing the duration to make sure that a call that starts at 700 pm and has a duration of 300 seconds shows active at 704 but i cannot imagine how to approach the problem i tried to figure out a way to weight each call against particular minute that would tell me if the call was active during that minute or not but could not come up with an effective solution the data types here are the same as i have to query against i do not have any control over the schema other than possibly converting the data and inserting into another table with more appropriate data types i have provided some example data that i know has concurrent active callscreate table records seconds char10 time char4 date char8 dur int system int port intseconds is an stime value it is the difference of seconds from utc 1970 0 to the current utc time we use it as an identifier like epochtime is the time the call was madedate is the day the call was madedur is the duration of the call in secondssystem is the system numberport is the port on the system not particularly relevant for this questioninsert into recordsseconds time date dur system port values123992422819232009041610522insert into recordsseconds time date dur system port values1239923455191020090416884197insert into recordsseconds time date dur system port values1239924221192320090416116215insert into recordsseconds time date dur system port values1239924259192420090416901102insert into recordsseconds time date dur system port values123992345819102009041689121insert into recordsseconds time date dur system port values123992425519242009041699242insert into recordsseconds time date dur system port values123992433619252009041620258insert into recordsseconds time date dur system port values123992429319242009041664241insert into recordsseconds time date dur system port values12399234721911200904168227insert into recordsseconds time date dur system port values1239924347192520090416251100insert into recordsseconds time date dur system port values123992430119252009041677255insert into recordsseconds time date dur system port values123992433219252009041652243insert into recordsseconds time date dur system port values12399242401924200904161517insert into recordsseconds time date dur system port values123992431319252009041696262insert into recordsseconds time date dur system port values1239924094192120090416315216insert into recordsseconds time date dur system port values1239923643191420090416788234insert into recordsseconds time date dur system port values123992471927200904166227insert into recordsseconds time date dur system port values1239924342192520090416119215insert into recordsseconds time date dur system port values123992439719262009041676241insert into recordsseconds time date dur system port values123992445719272009041623227,['sql'] +12506,do singleton exceptions work a collegue of mine at work gave a presentation on static factory methods right out of effective java and then gave an example of its use for obtaining static singleton exceptions this set off a red flag for me are not exceptions stateful are not they populated by the jvm for stack trace info what savings do you really get with this since exceptions should only occur for well exceptional situationsmy knowledge on exceptions is rather limited so i come to you with this will singleton exceptions work and is there any reason to use them,['java'] +12509,how to thisplay all elements in an arraylist say i have a car class with attributes make and registration and i create an arraylist to store them how do i thisplay all the elements in the arraylisti have this code right nowpublic car getall forint i 0 i carssize i cars name of arraylist car car carsgeti return carsget i return nullit compiles fine but when i try it out in my tester class using this codeprivate static void getallcar c1 arraylist car cars c1getall error incompatible type forcar item cars systemoutprintlnitemgetmake itemgetreg i am getting a error of incompatible type is my coding correct if not can someone please show me how it should bethank you,['java'] +12527,deleting a char array this question is related to this one given this codechar p new char200delete pwhat would happen if you set p100 0 before deleting p i had some code where i got a debug error when i tried to delete a not nullterminated char array something about deleting heap memory that is not assigned it seemed to delete memory out of the arrays boundsedit thx,['c++'] +12536,what are the thisadvantages of having many indices i recently sped up a complicated query by an order of magnitude by giving sqlite a good index to work with results like this make me wonder if i should index a lot of other fields that are commonly used for joins or order by clauses but i do not want to get overzealous and have it backfire on me i assume there must be some reasons not to create indices or every field would be indexed by defaulti am using sqlite in this case but of course dbmsagnostic advice is welcome as well,['sql'] +12538,a list of string replacements in python is there a far shorter way to write the following codemy string my stringreplacea 1my string my stringreplaceb 2my string my stringreplacec 3my string my stringreplaced 4my string my stringreplacee 5note that i do not need those exact values replaced i am simply looking for a way to turn 5 lines into fewer than 5,['python'] +12542,how do i make firefox print a backgroundcolor style i have some simple csomeelement backgroundcolorblack colorwhiteit looks ok in the browser but when i go to print it in firefox it comes out as black text on a white background i imagine this is some sort of inksaving feature but is there any way around it,['css'] +12546,sqlite performance benchmark why is memory so slowonly 15x as fast as thisk why is memory in sqlite so slowi have been trying to see if there are any performance improvements gained by using inmemory sqlite vs thisk based sqlite basically i would like to trade startup time and memory to get extremely rapid queries which do not hit thisk during the course of the application however the following benchmark gives me only a factor of 15x in improved speed here i am generating 1m rows of random data and loading it into both a thisk and memory based version of the same table i then run random queries on both dbs returning sets of size approx 300k i expected the memory based version to be considerably faster but as mentioned i am only getting 15x speedups i experimented with several other sizes of dbs and query sets the advantage of memory does seem to go up as the number of rows in the db increases i am not sure why the advantage is so small though i had a few hypotheses the table used is not big enough in rows to make memory a huge winnermore joinstables would make the memory advantage more apparentthere is some kind of caching going on at the connection or os level such that the previous results are accessible somehow corrupting the benchmarkthere is some kind of hidden thisk access going on that i am not seeing i have not tried lsof yet but i did turn off the pragmas for journalingam i doing something wrong here any thoughts on why memory is not producing nearly instant lookups heres the benchmark sqlite memory vs thisk benchmarkpy usrbinenv pythonattempt to see whether memory offers significant performance benefitsimport osimport timeimport sqlite3import numpy as npdef load matconnmat c conncursor try to avoid hitting thisk trading safety for speed cexecutepragma temp storememory cexecutepragma journal modememory make a demo table cexecutecreate table if not exists demo id1 int id2 int val real cexecutecreate index id1 index on demo id1 cexecutecreate index id2 index on demo id2 for row in mat cexecuteinsert into demo values row0row1row2 conncommitdef querytimeconnquery start timetime foo connexecutequeryfetchall diff timetime start return diff1 build some fake data with 3 columns int int floatnn 10 numrowscmax 700 num uniques in 1st colgmax 50 num uniques in 2nd colmat npzerosnn3dtypeobjectmat0 nprandomrandint0cmaxnnmat1 nprandomrandint0gmaxnnmat2 nprandomuniform01nn2 load it into both dbs build indicestry osunlinkfoosqliteexcept oserror passconn mem sqlite3connectmemoryconn thisk sqlite3connectfoosqliteload matconn memmatload matconn thiskmatdel mat3 execute a series of random queries and see how long it takes each of thesenumqs 10numqrows 30 max number of ids of each kindresults npzerosnumqs3for qq in rangenumqs qsize nprandomrandint1numqrows1 id1a npsortnprandompermutationnparangecmax0qsize ensure uniqueness of ids queried id2a npsortnprandompermutationnparangegmax0qsize id1s joinstrxx for xx in id1a id2s joinstrxx for xx in id2a query select from demo where id1 in s and id2 in s id1sid2s resultsqq0 roundquerytimeconn thiskquery4 resultsqq1 roundquerytimeconn memquery4 resultsqq2 intqsize4 now look at the resultsprint thisk memory qsizeprint for row in results print 4f 4f d row0row1row2heres the results note that thisk takes about 15x as long as memory for a fairly wide range of query sizes ramanujanpython oo sqlite memory vs thisk cleanpy thisk memory qsize90332 68100 1263090905 66953 589490078 68384 1779891179 67673 6085090629 68355 9485489688 68093 1794090785 66993 5800390309 68257 8566391423 67411 6604791814 69794 11345should not ram be almost instant relative to thisk whats going wrong here editsome good suggestions here i guess the main takehome point for me is that there is probably no way to make memory absolutely faster but there is a way to make thisk access relatively slower in other words the benchmark is adequately measuring the realistic performance of memory but not the realistic performance of thisk eg because the cache size pragma is too big or because i am not doing writes i will mess around with those parameters and post my findings when i get a chance that said if there is anyone who thinks i can squeeze some more speed out of the inmemory db other than by jacking up the cache size and default cache size which i will do i am all ears,['python'] +12556,code generation in maven i want to autogenerate some java classes from interfaces my first thought was to write a code generator and integrate it as a maven plugini was thinking of creating a maven plugin with a codegen goal that is called during the build proceso if i choose this route how do i provide the plugin with the interfaces to be processed and where should the generated files goare there any existing plugins that can be configured to generate default class implementations,['java'] +12557,serializing vs database i believe that the best way to save your application state is to a traditional relational database which most of the time its table structure is pretty much represent the data model of our system meta datahowever other guys in my team think that today it is best to simply serialize the entire object graph to a binary or xml fileno need to say but i will still say it that world war 3 is going between us and i would like to hear your opinion about this issuepersonally i hate serialization becausethe data saved is adhered only to your development platform c in my case no other platforms like java or c can use this data entire object graph including all the inheritance chain is saved and not only the data we need changing the data model might cause severe backward compatibility issues when trying to load old states sharing parts of the data between applications is problematic i would like to hear your opinion about thatthanksadi barda,['c#'] +12586,does entity frameworklinq to sql data binding use reflection forgive me if this has been asked before i did a search but could not find anything that specifically answered this question but i would be happy to be referredi am taking a peek at both the entity framework and linq to sql and while i like the systems and of course the linq integration i am a little skeptical on the databinding aspect i have taken query results and inspected them and they do not appear to implement the standard net listbinding interfaces ibindinglist and more importantly itypedlist leading me to believe that binding them to a grid or anything else is going to use reflection to getset my entity properties this seems like a comparatively expensive operation especially when all of the code is generated anyway and could implement the interfacesdoes anyone have any insight into this is reflection used to getset the value of the properties if yes does this have a performance impact that is noticeable and does anyone have any idea why they went this routeediti am actually concentrating on whether or not itypedlist is implemented somewhere along the way as that is what has the capability to provide an explicit mechanism for defining and interacting with properties without resorting to reflection while i did not have a linq to sql project up i did inspect a simple entity framework entity query result and it did not appear to implement itypedlist does anyone know if i am just looking at something incorrectly or if not why this is the caseedit 2after accepting marcs answer i thought it might be helpful for others if i posted some simple code i used to seamlessly implement his solution i put the following in the static constructor for my classpublic static contextname foreachtype type in systemreflectionassemblygetexecutingassembly gettypes if typegetcustomattributestypeofsystemdatalinqmapping tableattribute true null systemcomponentmodeltypedescriptoraddprovider new hypercomponentmodelhypertypedescriptionprovider systemcomponentmodeltypedescriptorgetprovider type type while this is for linq to sql i am sure an equivalent version could be written for the entity framework this will scan the assembly for any types with the table attribute and add a custom provider for each of them,['c#'] +12594,ruby on rails on windows xp ctrlc in console not stopping mongrel i am currently in the process of learning ruby on rails i have been following the learning rails podcast and screencasts i have run into a problem well more of an annoyance every time the screencast has me kill the mongrel server i am forced to close the console window because ctrlc isnt killing it as it should i then have to open a new console window navigate to my rails app and issue a ruby scriptserver command to restart itwhat i am looking for is possibly a reason for this a way to fix it or other suggestions to make this process faster andor less annoying or even possibly a batch file or shortcut to open a cmd window right to where i need it,"['ruby-on-rails', 'ruby']" +12639,ora01654 unable to extend index calling all oracle gurusi am in the process of clustering a well tested application on websphere the application in question made it about half way through processing 1k of jms messages from a queue before this happened begin backtrace for nested throwablesjavasqlsqlexception ora01654 unable to extend index dabuatindex1 by 128 in tablespace dabuat tblsp at oraclejdbcdriverdatabaseerrorthrowsqlexceptiondatabaseerrorjava112 at oraclejdbcdrivert4cttioerprocesserrort4cttioerjava331 at oraclejdbcdrivert4cttioerprocesserrort4cttioerjava288 at oraclejdbcdrivert4c8oallreceivet4c8oalljava745i have had a quick look online and found a few possible suggestions as to why this could have happend if anyone could give a clear explanation as to why this may have occurred now my application has been clusterd i would be most gratefulregards karl,['java'] +12649,html table text to image using c can anyone point me to some sample code in c for converting an html table to image i know how to convert text to image but i need to create an image of well formatted text the whole text is formatted in html table,"['c#', 'asp.net', 'html', 'css']" +12650,postgres xml datatype what are the benefits of using the xml datatype versus storing the xml content inside a text datatypeam i able to query by some specific xml attribute or elementwhat about indexing and query performancebesides the postgresql manual what other online sources can you point me to,['sql'] +12652,how you would you describe the observer pattern in beginner language currently my level of understanding is below all the coding examples on the web about the observer pattern i understand it simply as being almost a subscription that updates all other events when a change is made that the delegate registers however i am very unstable in my true comprehension of the benefits and uses i have done some googling but most are above my level of understanding i am trying to implement this pattern with my current homework assignment and to truly make sense on my project need a better understanding of the pattern itself and perhaps an example to see what its use i do not want to force this pattern into something just to submit i need to understand the purpose and develop my methods accordingly so that it actually serves a good purpose my text does not really go into it just mentions it in one sentence msdn was hard for me to understand as i am a beginner on this and it seems more of an advanced topic how would you describe this observer pattern and its uses in c to a beginner for an example please keep code very simple so i can understand the purpose more than complex code snippets i am trying to use it effectively with some simple textbox string manipulations and using delegates for my assignment so a pointer would help,['c#'] +12653,is there a parameter i can use in java that works with all foreach loops suppose i have got a method that accepts an array and processes each element in it using javas built in foreach loop like thispublic static void myfunsomeclass arr for someclass sc arr stuff is processed here this works just fine but now i want to be able to pass the same method a listsomeclass instead am i destined to use collectiontoarrayt or is there a parameter i can use for myfun that accepts any type that can be used in a foreach constructto clarify i want a method signature that will accept any iterable object be it a primitive array or a collection i can very easily write two methods with one wrapping the other but i am just curious if there is a better way,['java'] +12655,why is my cat function with system calls slower compared to linuxs cat i have done this function in c using system calls open read and write to simulate the cat function in linux systems and it is slower than the real onei am using the same buffer size as the real cat and using strace i think it is making the same amount of system calls but the output from my cat is a little bit slower than the real catthis is the code i havedefine bufsiz 32768int syswritebufferint fdout char buffer ssize t readbytes ssize t writtenbytes 0 whilewrittenbytes readbytes writtenbytes writefdout buffer writtenbytes readbytes writtenbytes ifwrittenbytes 1 return 1 return 0int catprintint fdin int fdout char bufferbufsiz ssize t readbytes do readbytes readfdin buffer bufsiz ifreadbytes 1 return 1 ifsyswritebufferfdout buffer readbytes 1 return 1 whilereadbytes 0 return 0i am reading from a file that i pass as argument to main i think that code is not needed here than i call the catprint function with that file descriptor and 1 for the output descriptor so it prints to stdouti do not understand why it is slower because i am using the same file for testing and with both the real cat and mine there is only one read and one write for the whole text should not the whole text just appear on screenps i have tagged this as homework although my question here why it is slower is not part of the homework i only needed to use the system calls to create a cat type function which is done i am just intrigued by my code that is a bit a slowerproblem solved with stupidity from mei just decided to call linuxs original cat a few times on the same file one after the other and i just realized that it was also slow some of the times i called it just as slow as my own i guess everythings fine thansorry for wasting your time like this people,['c'] +12659,easiest way to copy a dataview to a datatable in c i need to copy a dataview into a datatable it seems like the only way to do so is to iterate through the dataview item by item and copy over to a datatable there has to be a better way,['c#'] +12663,how do i select a top level attribute of an xml column in sql server 2005 i have an xml column in sql server 2005 that is the equivalent oftest foobar otherstuff bazbelch testi want to be able to get the value of the foo attribute of test the root element as a varchar my goal would be something along the lines ofselect cast test foobarotherstuff bazbelch test as xmlvaluefoovarchar20 as foowhen i run the above query i get the following errormsg 2390 level 16 state 1 line 1 xquery value toplevel attribute nodes are not supported,['sql'] +12692,escape analysis in java as far as i know the jvm uses escape analysis for some performance optimisations like lock coarsening and lock elisioni am interested if there is a possibility for the jvm to decide that any particular object can be allocated on stack using escape analysissome resources make me think that i am right is there jvms that actually do it,['java'] +12694,how do you configure wcf known types programmatically my clientserver application is using wcf for communication which has been great however one shortcoming of the current architecture is that i must use known type configuration for certain transmitted types i am using an inhouse pubsub mechanism and this requirement is unavoidablethe problem is that it is easy to forget to add the known type and if you do wcf fails silently with few clues as to whats going wrongin my application i know the set of types that are going to be sent i would like to perform the configuration programmatically rather than declaratively through the appconfig file which currently contains something like thissystemruntimeserialization datacontractserializer declaredtypes add typemyprojectmyparent myprojectassembly knowntype typemyprojectmychild1 myprojectassembly knowntype typemyprojectmychild2 myprojectassembly knowntype typemyprojectmychild3 myprojectassembly knowntype typemyprojectmychild4 myprojectassembly knowntype typemyprojectmychild5 myprojectassembly add declaredtypes datacontractserializersystemruntimeserializationinstead i would like to do something like thisforeach type type in transmittedtypes how would i write this method addknowntypetypeofmyparent typecan someone please explain how i might do thisedit please understand that i am trying to set the known types dynamically at run time rather than declaratively in config or using attributes in the source codethis is basically a question about the wcf api not a style questionedit 2 this msdn page page statesyou can also add types to the readonlycollection accessed through the knowntypes property of the datacontractserializer unfortunately that is all it says and it does not make terribly much sense given that knowntypes is a readonly property and the propertys value is a readonlycollection,['.net'] +12712,django payment proccessing can anyone suggest any good payment processing libraries for pythondjango,['python'] +12718,what does the package directive do in objectivec does anyone know exactly what the package directive is used for in objectivecthe only mention i could find of it in programming in objectivec 20 by stephen kochan waspackage for 64 bit images the instance variable can be accessed anywhere within the image that implements the classwhat is this restricted to being used with images as in pictures or does it mean images as in thisk imagesit is a confusing description and does not elaborate whatsoever throughout the rest of the bookany help would be awesome thanks,['objective-c'] +12729,why are 0d arrays in numpy not considered scalar surely a 0d array is scalar but numpy does not seem to think so am i missing something or am i just misunderstanding the concept foo numpyarray1 numpyfloat64 numpyndimfoo0 numpyisscalarfoofalse fooitem1,['python'] +12730,are there any standalone html markup validation tools other than submit individual web pages for verification on the w3c site are there any standalone tools that will do this job ideally this would be a visual studio plugin that could catch errors at design time but one that would just take a wep application url running locally would be goodopen source suggestions would be preferable,['html'] +12732,can you provide examples of parsing html how do you parse html with a variety of languages and parsing libraries when answeringindividual comments will be linked to in answers to questions about how to parse html with regexes as a way of showing the right way to do thingsfor the sake of consistency i ask that the example be parsing an html file for the href in anchor tags to make it easy to search this question i ask that you follow this formatlanguage language namelibrary library nameexample codeplease make the library a link to the documentation for the library if you want to provide an example other than extracting links please also includepurpose what the parse does,['html'] +12734,android customizing tabs on state how do i make a selector a drawable i know how to put the icon on each tab that is no problem i also ran across this stack overflow thread on pretty much same thing1i followed one of the links from that question and found this2pretty much it said use a selector defined in the xml sure did that but there is no id associated w it so i am not sure how to get the selector function as a drawable so i can use it as the icon for the tabs maybe i am going about this the wrong way but this is what i have and obviously missing somethingselector androidididmyselector xmlnsandroid non focused states item androidstate focusedfalse androidstate selectedfalse androidstate pressedfalse androiddrawabledrawabledarklogo item androidstate focusedfalse androidstate selectedtrue androidstate pressedfalse androiddrawabledrawablelightlogo focused states item androidstate focusedtrue androidstate selectedfalse androidstate pressedfalse androiddrawabledrawablelightlogo item androidstate focusedtrue androidstate selectedtrue androidstate pressedfalse androiddrawabledrawablelightlogo pressed item androidstate pressedtrue androiddrawabledrawablelightlogo selectorin my code an example tab is generated using hostaddtabhostnewtabspecthree setindicatormapdrawables setcontentnew intentthis mapclass right now drawables is just a reference to an drawable image resource how do i make the selector a drawable this is my question 1 updating android tab icons 2 threadthreadef3bdebcb715b385,['android'] +12753,how to hide the content of the div in css i have this html codediv idmybox a divand this is my cssmybox backgroundcolorgreenmyboxhover backgroundcolorredthe question is how to hide the content of the div a when the mouse hover event by using css only and without changing the structure of the code i think i should put some code under myboxhover but i do not know the codethanks in advance for help,"['html', 'css']" +12772,please confirm or correct my english interpretation of this haskell code snippet i am a c developer who is working through real world haskell in order to truly understand functional programming so that when i learn f i will really grok it and not just write c code in f so to speakwell today i came across an example which i thought i understood 3 different times only to then see something i missed update my interpretation and recurse and curse too believe menow i believe that i do actually understand it and i have written a detailed english interpretation below can you haskell gurus please confirm that understanding or point out what i have missednote the haskell code snippet quoted directly from the book is defining a custom type that is meant to be isomorphic to the built in haskell list typethe haskell code snippetdata list a cons a list a nil defining showedit after some responses i see one misunderstanding i made but am not quite clear on the haskell parsing rules that would correct that mistake so i have included my original incorrect interpretation below followed by a correction followed by the question that still remains unclear to meedit here is my original incorrect english interpretation of the snippeti am defining a type called listthe list type is parameterised it has a single type parameterthere are 2 value constructors which can be used to make instances of list one value constructor is called nil and the other value constructor is called consif you use the nil value constructor then there are no fieldsthe cons value constructor has a single type parameterif you use the cons value constructor there are 2 fields which must be provided the first required field is an instance of list the second required field is an instance of ai have intentionally omitted anything about defining show because it is not part of what i want to focus on right nowthe corrected interpretation would be as follows changes in boldi am defining a type called listthe list type is parameterised ithas a single type parameterthere are 2 value constructors which can be used to make instances of list one value constructor is called nil and the other value constructor is called cons if you use the nil value constructor then there are no fields5 this line has been deleted it is not accurate the cons value constructor has a single type parameterif you use the cons value constructor there are 2 fields which must be provided the first required field is an instance of a the second required field is an instance of listofai have intentionally omitted anything about defining show because it is not part of what i want to focus on right nowthe question which is still unclearthe initial confusion was regarding the portion of the snippet that reads cons a list a in fact that is the part that is still unclear to mepeople have pointed out that each item on the line after the cons token is a type not a value so that means this line says the cons value constructor has 2 fields one of type a and the other of type listofathat is very helpful to know however something is still unclear when i create instances using the cons value constructor those instances interpret the first a as meaning place the value passed in here but they do not interpret the second a the same way for example consider this ghci session main cons 0 nilcons 0 nilmain cons 1 itcons 1 cons 0 nilmainwhen i type cons 0 nil it uses the cons value constructor to create an instance of list from 0 it learns that the type parameter is integer so far no confusionhowever it also determines that the value of the first field of the cons is 0 yet it determines nothing about the value of the second field it only determines that the second field has a type of list integerso my question is why does a in the first field mean the type of this field is a and the value of this field is a while a in the second field means only the type of this field is list of aedit i believe i have now seen the light thanks to several of the responses let me articulate it here and if somehow it is still incorrect in some fashion please by all means let me knowin the snippet cons a list a we are saying that the cons value constructor has two fields and that the first field is of type a and that the second field is of type list of athat is all we are saying in particular we are saying nothing about values this is a key point i was missinglater we want to create an instance using the cons value constructor we type this into the interpreter cons 0 nil this explicitly tells the cons value constructor to use 0 for the value of the first field and to use nil as the value for the second field and that is all there is to it once you know that the value constructor definition specifies nothing but types everything becomes clearthanks everyone for the helpful responses and as i said if anything is still off please by all means tell me about it thanks,['c#'] +12779,currency library i am looking for a net classlibrary to use with currency acronyms in the same way the timezoneinfo class works with timezones i need to populate a drop down list with these acronyms and store the result in a databse this value will be used to retrieve up to date exchange rates from the web at a later stageany ideas,['c#'] +12785,multiple simultaneous network connections telnet server python i am currently writing a telnet server in python it is a content server people would connect to the server via telnet and be presented with textonly contentmy problem is that the server would obviously need to support more than one simultaneous connection the current implementation i have now supports only one this is the basic proofofconcept server i began with while the program has changed greatly over time the basic telnet framework has notimport socket osclass server def init self selfhost selfport localhost 50 selfsocket socketsocketsocketaf inet socketsock stream selfsocketbindselfhost selfport def sendself msg if typemsg str selfconnsendmsg end elif typemsg list or tuple selfconnsendnjoinmsg end def recvself selfconnrecv4096strip def exitself selfsendthisconnecting you selfconnclose selfrun closing a connection opening a new one main runtime def runself selfsocketlisten1 selfconn selfaddr selfsocketaccept there would be more activity here ie sending things to the connection we just mades serversrunthanks for your help,['python'] +12786,how to make canvas with swing i am trying to make a paint editor with java in which i have a toolbar with the objects that i would like to paste in the canvas i am using swing components to make the gui but when i looked for the way of making the canvas i only found the class canvas from awt is there any way to make something similar to canvas with swing for example jpanel i have read that using the class canvas from awt with a gui made with swing would not work correctly is that true,['java'] +12791,why is the iteration variable in a c foreach statement readonly as i understand it cs foreach iteration variable is immutablewhich means i cannot modify the iterator like thisforeach position location in map we want to fudge the position to hide the exact coordinates location location random compiler error plotlocationi cannot modify the iterator variable directly and instead i have to use a for loopfor int i 0 i mapcount i position location mapi location location random plotlocation i locationcoming from a c background i see foreach as an alternative to the for loop but with the above restriction i usually fallback to using the for loop i am curious what is the rationale behind making the iterator immutable edit this question is more of a curiousity question and not as a coding question i appreciated the coding answers but i cannot mark them as answersalso the example above was oversimplified here is a c example of what i want to do the games rules the laser of death tm moves around the game board from the start area index 0 until the end area index boardsize if the laser hits a teleporter destroy that teleporter on the board and move the laser to the square where the teleporter points to if the laser hits a player deal 15 damage and stop the laserfor int i 0 i boardsize i if getitemboardi teleporter teleportsquare getteleportsquareboardi setitemboardi freespace i teleportsquare if getitemboardi player playerlife 15 break i cannot do the above in cs foreach because the iterator i is immutable i think correct me if i am wrong this is specific to the design of foreach in languagesi am interested in why the foreach iterator is immutable,['c#'] +12794,ie7 8 not fireing jquery click events for elements appended inside a table i have an ie bug that i am not sure how to fixusing jquery i am dynamically moving a menu to appear on an element on mouseovermy code simplified looks something like thisj jquerynoconflictjdocumentreadyfunction do something on the menu clicks jdivicoclickfunction alertjthisparenthtml setupactionstableid menuidon mouseover set up the actions menu to appear on mouseoverfunction setupactionstableselector menuselector jtableselector divtestmouseoverfunction note that append will move the underlying dom element with all events from it is old parent to the end of this one jthisappendjmenuselectorshow this menu does not seem to register events correctly for the menu after it is been moved in ie7 ie8 and ie8asie7 yeah ms that is really a new rendering engine in ie8 we all believe youit works as expected in everything elseyou can see the behaviour in a basic demo herein the demo you can see two examples of the issuethe image behind the buttons should change on hover done with a css hover selector it works on the first mouseover but then persiststhe click event doesnat fire a however with the dev tools you can manually call it and it is still subscribedyou can see 2 in ie8s dev toolsopen page in ie8open dev toolsselect script tab and console subtabtype jtestfloat divicofirstclick to manually call any subscribed eventsthere will be an alert on the page this means that i am not losing the event subscriptions they are still there ies just not calling them when i clickdoes anyone know why this bug occurs other than just because of ies venerable engineis there a workaroundcould it be something that i am doing wrong that just happens to work as expected in everything else,"['jquery', 'css']" +12800,javascript undefined undefined note as per ecmascript51 section 15113 windowundefined is readonlymodern browsers implement this correctly for example safari 51 firefox 7 chrome 20 etcundefined is still changeable in chrome 14 when i recently integrated facebook connect with tersus i initially received the error messages invalid enumeration value and handler already exists when trying to call facebook api functionsit turned out that the cause of the problem wasobjectx undefinedreturning false when there is no property x in objecti worked around the problem by replacing strict equality with regular equality in two facebook functionsfbsysisundefined functiono return o undefinedfbsyscontainskey functiond key return dkey undefinedthis made things work for me but seems to hint at some sort of collision between facebooks javascript code and my ownwhat could cause thishint it is well documented that undefined null while undefined null this is not the issue here the question is how comes we get undefined undefined,['javascript'] +12808,php ide with vi key bindings at the moment i am using eclipse with viplugin i also know about netbeans and its vi plugini find both of these ides do not really fit my tastes though too slow bad remote editing support i do not really have time at the moment to set up and try a vim based ide eitherso what other php ide is available that supports vi key bindings i am willing to pay for a commercial one if necessary,['php'] +12813,what is the biggest mistake people make when starting to use linq what are the fundamental misunderstandings people have when they first start using linq for instance do they think it is one thing when it is really something else and are there some best practices to employ to avoid these mistakes,['.net'] +12815,c letting a boost thread wait for 1 second i have created a boost thread usingboostthread thrdconnectionthread where connectionthread is a simple void function this works fine however when i try to make it wait for some seconds for example usingboostxtime xtboostxtime getxt boosttime utcxtsec 1boostthreadsleepxt sleep for 1 secondthe program crashes at the xtime get line even when manually trying to set xtsec it does not work i have tried several other methods but i cannot seem to make it work is there something i am doing wrong is there a easier way to achieve my goal,['c++'] +12837,best way to embed an irc client in a webpage i am looking for a good free preferrably open source irc client to be embedded in a web pagethe obvious requirements of supporting most browsers if requiering a plugin it should be a plugin that is allready widley deployed and it should not put too much strain on the webserver serving the page,['html'] +12839,calling c code from c i need to be able to invoke arbitrary c functions from c suggests using iclrruntimehostexecuteindefaultappdomain but this only allows me to invoke methods having this format int methodstring argwhat is the best way to invoke arbitrary c functions,['c#'] +12844,zend framework zend form decorators inside button element i have a button element that i have created like sosubmit new zend form element buttonsubmitsubmitsetlabelmy buttonsubmitsetdecoratorsarray viewhelper arrayhtmltag arraytag lisubmitsetattribtype submitthis generates the following htmlli label forsubmit classoptionalmy buttonlabel button namesubmit idsubmit typesubmitmy buttonbuttonlii would like to wrap the inside of the button with a span like thisbuttonspanmy buttonspanbuttonwhat is the best way to do this using zend form,['php'] +12847,how to upload a pristine python package to pypi whats the magic python setuppy some incantation here command to upload a package to pypi in a form that can be downloaded to get the original package in its original formi have a package with some source and a few image files as package data if i do setuppy sthist register upload the targz has the image files excluded if i do setuppy bthist egg register upload the egg contains the images but excludes the setuppy file i want to be able to get a file uploaded that is just the entirety of my project aka setuppy the whole freaking thing register uploadperhaps the best way to do this is to manually targz my project directory and upload it using the pypi web interfacecaveat i am trying to avoid having to store a simple project i just created in my svn repo as well as on pypi it seems like a waste of work to keep track of its history and files in two places,['python'] +12851,using mysql triggers to log all table changes to a secondary table i have a tablecreate table data table data id int not null auto increment primary key field1 int not null field2 int not null field3 int not null engine myisam i would log to log any chances to field1 2 or 3 tocreate table data tracking tracking id int not null auto increment primary key data id int not null field varchar 50 not null old value int not null new value int not null modified datetime not null engine myisam i am using mysql 5 and i would like to create a trigger to do i would like to insert a new row into data tracking anytime data table is updated and record the oldupdated value as well as the field changed i tried the following without any successdelimiter drop trigger update data create trigger update data after update on data tablefor each rowbegin if newfield1 oldfield1 then insert into data tracking set old value oldfield1 new value newfield1 field field1 end ifenddelimiter it gave an error on the insert line i am not quite sure what the syntax on that should be or if i am going about this the right way any help would be appreciated thanks,['mysql'] +12852,set new id with jquery this is a text field new id is an integerwhen i apply the following snippetthisattrid thisid new idthisattrname thisname new idthisattrvalue testthe id changes the name changes too but not the value if i change the last line to this and therefore use a string literalmytextfield 3attrvalue testit worksany ideas edit thanks to steerpike for the quick plugin test i believe it should work but i cannot find the errorheres some more codei create the clone usingclone thisfindclone fields containerfirstcloneclone now contains a div which has embedded input fieldsafter generating a new id iterate over input and select fields in container clonechildreninputselecttextareaeachfunction thisattrid thisid new id thisattrname thisname new id thisvaltest consolelogthis the text fields do not have any values,"['javascript', 'jquery']" +12858,where on the file system was my java class loaded from i think this is a situation every java programmer runs into if they do it long enough youre doing some debugging and make a change to class when you go to rerun the program these changes do not seem to be picked up but rather the old class still seems to be running you clean and rebuild everything same issue sometimes this can come down to a classpath issue of the same class being on the classpath more than once but there does not seem to be an easy way to figure out where the class being loaded is coming fromis there any way to find the file path for the class that was loaded preferable something that would work either if the class was loaded from a class file or a jar file any ideas,['java'] +12859,what is the recommended batch size for sqlbulkcopy what is the recommended batch size for sqlbulkcopy i am looking for a general formula i can use as a starting point for performance tuning,['.net'] +12861,in javascript can you extend the dom in javascript you can extend existing classes by using its prototype objectstringprototypegetfirstletter function return this0is it possible to use this method to extend dom elements,['javascript'] +12862,should i use char argv or char argv in c i am just learning c and was wondering which one of these i should use in my main method is there any differenceedit so which one is more common to use,['c'] +12869,convert a number to a list of integers how do i write the magic function below num 123 lst magicnum print lst typelst1 2 3 type list,['python'] +12876,cc static function in header file what does it mean i know what it means when declared in source file i reading some code find that static function in header files could be invoke in other files,['c'] +12877,what does snapstodevicepixels in wpf mean in layman terms anybody say i have a window class and i give snapstodevicepixels true what happens,['c#'] +12886,need job scheduler in aspnet we have a website where we need a scheduler to receive notifications email on specific time eg a person setting reminder at 5 pm to attend the meeting at 445 pm will receive email at 445 pm about sameas this site is hosted on shared server we do not have any control over the server to run any sql job or scheduler applicationis there anything in aspnet which can help in this scenario,['asp.net'] +12895,copy constructor with pointers i have recently thiscovered that when i have pointers within a class i need to specify a copy constructorto learn that i have made the following simple code it compiles but gives me runtime error when performing the copy constructori am trying to copy just the value from the pointer of the copied object but avoiding assigning the same addreso whats wrong here include stdioh include stdlibh include floath include mathh include iostream using namespace std class try public try try trytry const int pointer void setpointerint void trysetpointerint a pointer a return trytry trytry trytrytry const copytry int a copytrypointer pointer a int main try a asetpointer5 try b a bsetpointer8 cout address of object a a endl cout address of object b b endl cout address of apointer apointer endl cout address of bpointer bpointer endl cout value in apointer apointer endl cout value in bpointer bpointer endl return 0 i will be using this concept for other classes with lots of pointers in it where i need to copy all values from on object to the other copying is initially necessary for this code so i would like to keep the copying possibility i would not be hiding the copy constructor as privatebesides the real class i need to implement has like 10 pointers and it might be changing with time is not there a somewhat smarter way to have a deep copy constructor in c,['c++'] +12896,can the parent window be notified when a child window closes on a diff domain can the parent window be notified when a child window closes on a different domaintrying to get around the windowopener not working when on different domainscan i at least be notified somehow when the child window closes,['javascript'] +12902,innodb the table is full error i have a mysql innodb table on a redhat enterprise linux 4 server and after trying to import a database previously backed up using mysqldump i got a the table is full error the table currently has 463062 rows in it and the ibdata1 file on thisk is currently 337gb a quick show variables shows that the innodb data file path is set to ibdata110mautoextend and the filesystem is ext3 so i would expect it to have plenty of room left to growany ideas how i can go about establishing exactly what the problem is,['mysql'] +12907,threads in spring i have a web application using spring and hibernate and struts it runs on tomcatthe call sequence is something like thisstruts action calls spring service bean which in turn calls spring dao bean the dao implementation is a hibernate implementationthe question iswould all my spring beans be running in the same thread can i store something in the threadlocal and get it in another beani am quite sure this would not work in stateless session beanthe ejb container can or will spawn a new thread for every call to the session beanwill the spring container do the same ie run all beans in the same thread when i tried a junit test i got the same id via threadcurrentthreadgetid in the test case and the two beans which leads me to believe there was only one thread in actionor is the behavior unpredictableor will it change when running on tomcat server clarificationi do not wish to exchange data between two threads i want to put data in the threadlocal and be able to retrieve it from all beans in the call stack this will work only if all beans are in the same thread,['java'] +12911,beginners guide for setting up emacs with gccgdb i looked around the gnu emacs material and did not find anything helpfuldoes anyone know of a good tutorial for setting up emacs to basically turn it into an ide i am looking for interfacing with gccgdbmake etc,['c'] +12913,working with large text snippets in java source are there any good ways to work with blocks of text strings within java source code many other languages have heredoc syntax available to them but java does not this makes it pretty inconvenient to work with things like tag libraries which output a lot of static markup and unit tests where you need to assert comparisons against blocks of xmlhow do other people work around this is it even possible or do i just have to put up with it,['java'] +12920,how do i filter a bindingsource with a linq query as the datasource i am having trouble getting a filter to work on a bindingsource that is the datasource for a datagridview control basically i have linq query that is the datasource for the bindingsource and i would like to filter down the results below is an example of what i am trying to accomplishdim query from row in datatable select new myrowrowdim bs as new bindingsourcebsdatasource querytolistgriddatasource bsbsfilter col1 valuepublic class myrow private key as string private col1 as string public sub newbyval row as datatablerow key getnewkeyvalue col1 rowcol1 end sub public readonly property key as string get return key end get end property public readonly property col1 as string get return col1 end get end propertyend claso i can see all the rows in the datagridview control but the filter does not have any effect if i switch the bindingsources datasource to use a datatable then the filtering works as expected what am i missing,['.net'] +12929,unit of workrepository managers for nhibernate i am a net developer by day but have been working with rails and merb for the past year on my own side projects so when it comes to mvc and orms i am more used to them and using activerecord and datamapperi am getting started with aspnet mvc and i like what i see in nhibernate and fluent nhibernate but looking for a little bit more around how to best handle the unit of work or repository type modeli would like something that is not huge on architecture i have seen some projects like sarp architecture but it looks kind of bloatedall i am really after is a simple way to manage connections and handling data retrievalstorage a simple guide or sample application would even suffice,"['c#', 'asp.net']" +12959,why does no database fully support ansi or iso sql standards if i were designing a oil refinery i wouldnt expect that materials from different vendors would not comply with published standards in subtle yet important ways pipework valves and other components from one supplier would come with flanges and wall thicknesses to ansi standards as would the same parts from any other supplier interoperability and system safety is therefore assuredwhy then are the common databases so choosy about which parts of the standards they adhere to and why have no 100 standardscompliant systems come to the fore are the standards broken lacking in scope or too difficult to design fortaking this to conclusion what is the point of ansi or iso defining standards for sqledit list of implementation differences between common databases,['sql'] +12972,good patterns for a cc pluginbased system when developing a cc 2 plugin based framework with shared objectsdynamic libraries that need to support live swapping what examples would be helpful to look at for implementation detailsthanks note live swapping is the key point here no need to restart the system is a requirement,"['c++', 'c']" +12990,using youtubes javascript api with jquery i am currently trying to use the youtube api as part of a jquery plugin and i have run into a bit of a problemthe way the yt api works is that you load the flash player and when it is ready it will send a call back to a global function called onyoutubeplayerreadyplayerid you can then use that id combined with getelementbyidplayerid to send javascript calls into the flash player ie playerplayvideoyou can attach an event listener to the player with playeraddeventlisteneronstatechange playerstate which will send any state changes to another global function in this case playerstatethe problem is i am not sure how to associate a state change with a specific player my jquery plugin can happily attach more than one video to a selector and attach events to each one but the moment a state actually changes i lose track of which player it happened ini am hoping some example code may make things a little clearer the below code should work fine in any html filedoctype html public w3cdtd html 401en htmlhead meta httpequivcontenttype contentapplicationtexthtmlutf8 titlesandboxtitle link typetextcss href relstylesheet script typetextjavascript srcscriptscript typetextjavascript googleloadjquery 132 googleloadjqueryui 170scriptscript typetextjavascript srcscriptscript typetextjavascriptfunction fnsimplified function return thiseachfunctioni var params allowscriptaccess always var atts id ytplayeri div div attrid containerplayeri swfobjectembedswfenablejsapi1playerapiidytplayeri containerplayeri 425 356 8 null null params atts thisappenddiv jqueryfunction onyoutubeplayerreadyplayerid var player playerid0 playeraddeventlisteneronstatechange playerstatefunction playerstatestate consolelogstatedocumentreadyfunction secondarysimplifiedscriptheadbody div idcontainer div clasecondary div div clasecondary div div clasecondary div div clasecondary div divbodyhtmlyoull see the consolelog outputtin information on the state changes but like i said i do not know how to tell which player it is associated with anyone have any thoughts on a way around thisedit sorry i should also mentioned that i have tried wrapping the event call in a closurefunction onyoutubeplayerreadyplayerid var player playerid0 playeraddeventlisteneronstatechange functionstate return playerstatestate playerid player function playerstatestate playerid player consolelogstate consolelogplayeridin this situation playerstate never gets called which is extra frustrating,"['javascript', 'jquery']" +12995,unittesting database setup for tests i am writing unittests for an app that uses a database and i would like to be able to run the app against some sampletest data but i am not sure of the best way to setup the initial test data for the testswhat i am looking for is a means to run the codeundertest against the same database or schematically identical that i currently use while debugging and before each test i would like to ensure that the database is reset to a clean slate prior to inserting the test datai realize that using an irepository pattern would allow me to remove the complexity of testing against an actual database but i am not sure that will be possible in my caseany suggestions or articles that could point me in the right directionthankseditthanks everyone those are some great suggestions i will probably go the route of mocking my data access layer combined with some simple setup classes to generate exactly the data i need per test,['c#'] +13005,how to properly manage tomcat web apps inside eclipse i used to run tomcat separately on my machine i had an ant script that would rebuild my project deploy it locally and restart tomcat that all worked ok but i was not able to debug the web app inside eclipse so i learned how to setup tomcat inside eclipse and got my web app running now the problem is that i do not understand fully how to manage it this way eclipse is set to automatically build my project on changes but those changes do not seem to always be reflected in the web app sometimes i have to manually build the project and manually clean the server for the changes to be reflectedare there rules somewhere about how to manage this setup for instance if i only change a jsp then will it automatically be synchronized if i change a servlet class then i need to manually rebuild the project are these rules consistent or should i just manually rebuild and clean every timei would really appreciate it if someone could give me the best practice rules or point me to a good resource to learn how to manage this environmentps i am using eclipse 341 java ee package and tomcat v55,['java'] +13007,programmatically retrieve memory usage on iphone i am trying to retrieve the amount of memory my iphone app is using at anytime programmatically yes i am aware about objectallocleaks i am not interested in those only to know if it is possible to write some code and get the amount of bytes being used and report it via nslogthanks,"['iphone', 'objective-c']" +13013,why is jquery ajax so slow on ie7 i am having a problem with jquery ajax calls on ie7 this simple code works fine on ff and opera but on ie7 it takes 35sec that is 20 times slower than ff loading content is pure html and inline javascript code no js rendering i even turned of the inline javascript code bu still slow blockloadsome urlhow to overcome this problem any help would be greatly appreciated,['jquery'] +13016,how do you copy a file into sharepoint using a webservice i am writting a winforms c 20 application that needs to put an xml file into a document library on sharepoint i want to use a webservice instead of using the object model no sharepointdll to reference here i am currently using the httpwebserversite vti bincopyasmx webservicehere is some code byte xmlbytearrayusing memorystream memorystream new memorystream xmldocumentsavememorystream xmlbytes memorystreamtoarraystring destinationurlarray new string httpwebserversitedoclibuploadeddocumentxmlfieldinformation fieldinfo new fieldinformationfieldinformation fields fieldinfo copyresult resultsarrayusing copy copyservice new copy copyservicecredentials credentialcachedefaultcredentials copyserviceurl httpwebserversite vti bincopyasmx copyservicetimeout 60 uint documentid copyservicecopyintoitems destinationurlarray fields xmlbytearray out resultsarraywhen this code runs i get a single result in the resultsarray out parameter destinationurl httpwebserversitedoclibuploadeddocumentxmlerrorcode unknownerrormessage object reference not set to an instance of an objectfrom my searching i have found a couple of possible helps microsoft technet the copyasmx copyintoitems will only work if the source and destination urls are in the same spwebapplication site collectionmicrosoft social object reference not set to an instance of an object error occurs because of sharepoint not able to identified that particular propertythis leads me to believe my source url should be set to something but what this is originating from a client workstation and does not have a source urlany help would be appricated hank youkeith,['c#'] +13019,how to make the division of 2 ints produce a float instead of another int in another bruce eckels exercise in calculating velocity v s t where s and t are integers how do i make it so the division cranks out a floatclass calcv float v float calcvint s int t v s t return v end calcvpublic class passobject public static void main string args int thistance thistance 4 int t t 3 float outv calcv v new calcv outv vcalcvthistance t systemoutprintlnvelocity outv end mainend class,['java'] +13035,passing arguments to javascript function from codebehind i would like to call a javascript function from an aspx control for instance suppose i hadhtml xmlns head runatservertitleuntitled pagetitlescript typetextjavascript function testx y scriptheadbody form idform1 runatserver div aspbutton idbutton1 runatserver textbutton onclickbutton1 click div formbodyhtmland in the code behindprotected void button1 clickobject sender eventargs e do stuff really going to a database to fill x and y int x new int 1 2 3 4 5 int y new int 1 2 3 4 5 call javascript function as testxyis there a way to do it,"['c#', 'javascript', '.net', 'asp.net']" +13038,is there a shorter way to require a file in the same directory in ruby is there a shorter way to require a file located in the same directory as the script being executedrequire fileexpand pathfiledirname file some other scripti read that require my script and require my script will actually load the script twice ruby will not recognize that it is actually the same script and this is the reason why fileexpand path is recommended if it is used every time the script is required then it will only be loaded onceit seems weird to me that a concise language like ruby does not seem to have a shorter solution for example python simply has thisimport some other module in the same directoryi guess i could monkeypatch require but that is just evil,['ruby'] +13049,how to synchronize svn revision and version ressources of exedll files say i have some c project which builds an exe or dll file the project is checked into a svn repository i want to automatically synchronize the revision from svn with the version resource embedded in my exedll file ie the version should be something like majorminorsvn revisionany ideas on how to achieve this are there any outofthebox solutions available,['c++'] +13050,how can i import the sqlite3 module into python 24 the sqlite3 module is included in python version 25 however i am stuck with version 24 i uploaded the sqlite3 module files added the directory to syspath but i get the following error when i try to import ittraceback most recent call last file stdin line 1 in file sqlite3 init py line 23 in from dbapi2 import file sqlite3dbapi2py line 26 in from sqlite3 import importerror no module named sqlite3the file sqlite3 is in libdynload but if i include this in the sqlite3 directory i get additional errorsany suggestions i am working in a limited environment i do not have access to gcc among other things,['python'] +13051,best practice for renaming propertymethod names that are reserved words i am creating a class whats the best practice for naming propertiesmethods when your preferred name is a reserved word,"['c#', '.net']" +13061,javascript function hooks edit ok i believe the following solutions are validuse the jquery aop plugin it basically wraps the old function together with the hook into a function sandwich and reassigns it to the old function name this causes nesting of functions with each new added hookif jquery is not usable for you just pillage the source code there did not seem to be any jquery dependencies in the plugin and the source is simple and very smallhave an object describing all hooks and their targets and one to store the initial unmodified function when adding a new hook the wrapping would be redone around the original function instead of rewrap the the previous wrapping functionyou escape nested functions and get two objects to handle instead potentially this could also mean easier hook handling if you addremove hooks often and out of orderi will go with the first since it is already done and i do not have performance to worry about and since the original functions are not affected even if i switch hooking methods i will only need to redo the hook adding which might be just some simple searchreplace operationshiis it possible to create a mechanism in which function a might have a set of hooksfunctions that will execute beforeafter function aideally function a would not be aware of hooking functionality so that i do not have to modify the source code of function a to call the hooks something likea function alerti am a naive functionb function alerti am having a piggyback ride on function a and the fool does not even know itaddhookb aadd hook b to function aagetting alerts i am a naive functioni am having a piggyback ride on function a and the fool does not even know iti have been trying to hack something up for a couple of hours but so far no luck,['javascript'] +13075,updating file in a jar throws zipexception i am trying to update a file in an existing jar in this example antlr using the commandjar uf antlrworks123jar organtlrcodegentemplatesjavajavastgbut i get the following messagejavautilzipzipexception duplicate entry antlrantlrerrorclass at javautilzipzipoutputstreamputnextentryzipoutputstreamjava175 at javautiljarjaroutputstreamputnextentryjaroutputstreamjava92 at suntoolsjarmainupdatemainjava508 at suntoolsjarmainrunmainjava185 at suntoolsjarmainmainmainjava1044any ideas,['java'] +13082,is extending string class with isnullorempty confusing everyone knows and love stringisnulloremptyyourstring methodi was wondering if it is going to confuse developers or make code better if we extend string class to have method like thisyourstringisnulloremptypro more readableless typingconscan be confusing because yourstringvariable can be null and it lookslike youre executing method on anull variablewhat do you thinkthe same question we can ask about myobjectisnull methodthat how i would write itpublic static class stringext public static bool isnulloremptythis string text return stringisnulloremptytext public static bool isnullthis object obj return obj null,['c#'] +13086,jquery getjson to external php page i have been trying to make an ajax request to an external serveri have learned so far that i need to use getjson to do this because of security reasons now i cannot seem to make a simple call to an external pagei have tried to simplify it down as much as i can but it is still not workingi have 2 files testhtml testphpmy testhtml makes a call like this to localhost for testing getjsonhttplocalhostoutvoiceservicestestphp functionjsonalertjson data jsonand i want my testphp to return a simple test results testecho json encoderesultsi am probably making some incredible rookie mistake but i cannot seem to figure it outalso if this works how can i send data to my testphp page like you would do like testphpid15 the testhtml page is calling the testphp page on localhost same directoryi do not get any errors just no alert,"['php', 'jquery']" +13088,how to synthesize sounds i would like to produce sounds that would resemble audio from real instruments the problem is that i have very little clue how to get thatwhat i know this far from real instruments is that sounds they output are rarely clean but how to produce such unclean soundsthis far i have gotten to do this it produces quite plain sound from which i am not sure it is even using the alsa correctlyimport numpyfrom numpyfft import fft ifftfrom numpyrandom import random samplefrom alsaaudio import pcm pcm nonblock pcm format float lepcm pcmmodepcm nonblockpcmsetrate44100pcmsetformatpcm format float lepcmsetchannels1pcmsetperiodsize4096def sine wavex freq100 sample numpyarangex4096 x14096 dtypenumpyfloat32 sample numpypi 2 44100 sample freq return numpysinsamplefor x in xrange10 sample sine wavex 100 pcmwritesampletostring,['python'] +13091,should i store enum idvalues in the database or a c enumeration say my database tables have columns like usertype salestype etcshould i have database tables with usertypeid usertypename or should i just create a c enumeration,['c#'] +13092,what tools to automatically inline css style to create email html code when you take a look at you learn that you need to embed inline styles in your html in order for your email to be read in any mail clientdo you know any tools or script to automatically convert an html file with a declared in to an html file with only inline ccs style attributes edit any javascript solution ie with jquery,"['html', 'css']" +13095,regularexpressionvalidator does not detect empty strings i have the following regex set as the validationexpression property on a regularexpressionvalidator in a web form when i enter an illegal character in the validated control the validator detects it and shows an error message appsettings add keycategorypattern valueazaz09 150 appsettingsmy validatoraspregularexpressionvalidator validationexpression appsettingscategorypattern my server side validationregex rex new regexconfigurationmanagerappsettingscategorypatternif rexmatchcategorynamesuccess throw new argumentexceptioncategoryname must match expression rexas you can see exactly the same pattern is applied client side and server sidehowever when i clear the validated control and submit an empty string the validator thinks it is ok and i get an error from my server side validation anyone know what is wrong here except for the broken contract of the regularexpressionvalidator,['asp.net'] +13096,wpf custom errorhandling dialog box i am trying to set up my wpf application so that when an exception goes unhandled an error dialog pops up in good ol winforms this was possible by addingapplicationthreadexception new systemthreadingthreadexceptioneventhandlerapplication threadexceptionto your programcs file and then showing whatever dialog you wanted in the event handling code in wpf i have tried to useappthispatcherunhandledexception new systemwindowsthreadingthispatcherunhandledexceptioneventhandlerthispatcher unhandledexceptionhowever when i use show on my errorhandling custom window the application immediately goes to blahblahexe has stopped working and closes if i use showdialog the window is usable until it is closed and then the same has stopped working dialog pops up and diesin winforms it seems that closing any error dialog would allow the app to continue running depending on how severe the exception was i cannot seem to figure out how to properly do this in wpfany ideas,['c#'] +13099,more elegant exception handling than multiple catch blocks using c is there a better way to handle multiple types of exceptions rather than a bunch of ugly catch blockswhat is considered best practice for this type of situationfor exampletry many types of exceptions can be throwncatch customexception ce catch anothercustomexception ace catch exception ex,"['c#', '.net']" +13108,easy to implement net library for geocoding using a free service i need to geocode adresses get latlong from addresses using in net to store in the databasewhat is the libraryproject to look into to get that done after a search here on google and codeplexcom i have found there to be a few options that seem like they will do what i ask for but some of them could be crap and a waste of time and some might just be stellarwhich one is the one to go for have you used any of them,['.net'] +13112,iphone url request add value to http header field i am trying to add a value to the header for a url request something like this works just fineurlrequest addvaluegzip forhttpheaderfieldacceptencodingbut this does not even show up in the headernsstring authstring nsstring alloc initwithstring defaults objectforkeyauthurlrequest addvalueauthstring forhttpheaderfieldiphoneidi am completely stumped the auth string is around 90 characters long is this a problemeditheres the code i am tryingnsstring authstring nsstring alloc initwithstringdefaults objectforkeyauth urlrequest addvalueauthstring forhttpheaderfieldiphoneid urlrequest addvaluegzip forhttpheaderfieldacceptencodingi can see the acceptencoding header being sent through wireshark but iphoneid is nowhere to be found it is just a string 8090 characters longanother updateso it seems that the problem is not the field iphoneid but rather the authstring i am trying to pass into it other strings that i just create with the something work fine but the auth string that i pull from nsuserdefaults does not appearsuggestions on how to debug this,['iphone'] +13121,when to close wcf client i have put an instance of the client proxy for the wcf service into a property on the app class so i can get it from anywhere in the app i am not closing the client i am leaving it open for the duration of the app the main reason for this is that if i were to follow the comment in the wcf service mex page the one you get if you point a browser at the wcf service url it says always close the client clientclosewhich is fine except if i call clientclose right after i make a call to clientsomeasync method then it is being closed before the results come back should i be putting the close into the completed method or should i just forget about closing it as once its closed i have to create a new instance of the client proxy might as well not store it in the aproperty if that is the case thanksstephen,['c#'] +13122,iphonexcode can different project targets have different bundle identifiers i am a little confused how this works this is my understandinga targets provisioning profile is linked to a specific app idthe bundle identifier for a target is found under target infoproperiesidentifierbut bundle id is also located in infoplist it seems that if you change the bundle id in infoplist xcode changes it automatically in target infopropertiesidentifier and vice versaso which is it that takes precedence the target infopropertiesidentifier bundle id or the infoplist bundle idthe reason i ask is because i would like to have two versions for my app a free ad supported version and a paid version and i would like to accomplish that with two different targets since they will be two different apps in the app store my understanding is they need two different app ids and i do not want to go down the route with app ids the description of how that works on the app store made my brain hurtwould i need two different infoplists for each target if i did this or can i use the same infoplist and just have the different targets use a different developmentthistribution provisioning profile,['iphone'] +13132,create list with values at compile time it is possible to create an array at compile time likeint myvalues new int 1 2 3 but i would like to do something like thislistint myvalues new listint 1 2 3 the compiler says no is there a way to do this c 20 without using linq c 30,['c#'] +13134,is there any ready to use module for test feedback for web applications i want to implement test feedback in my web application in the following manner when a user with testing privileges logs in every page in the web app will open small feedback window and dock it to the corner testers can use this window to describe the issue and eventually add attachments on confirmation the module saves that data in the database and records relevant data like browser version serialize relevant objects etcis there anything like that already implemented as free for use module thxedittalking about aspnet i envision this as a class that inherits page implementing defaults to enable testing you inherit from this class after the testing is complete you could thisable the entire thing by inheriting from page againthe database configuration could be set up using webconfig the class could also provide overridable methods like writeissuecontext c userinput input which default implementation uses webconfig and some hardcoded table you need to provide in you database then if you need other type of storage like for example creating issue on issue server you could override this method to provide custom implementation webconfig could also contain other customizations like dock type window css and similar,"['c#', 'asp.net']" +13136,globally catch exceptions in a wpf application we are having a wpf application where parts of it may throw exceptions at runtime i would like to globally catch any unhandled exception and log them but otherwise continue program execution as if nothing happened kinda like vbs on error resume nextis this possible in c and if so where exactly would i need to put the exception handling codecurrently i cannot see any single point where i could wrap a trycatch around and which would catch all exceptions that could occur and even then i would have left whatever has been executed because of the catch or am i thinking in horribly wrong directions hereeta because many people below pointed it out the application is not for controlling nuclear power plants if it crashes it is not that much a big deal but random exceptions that are mostly uirelated are a nuisance in the context where it would be used there were and probably still are a few of those and since it uses a plugin architecture and may be extended by others also students in that case so no experienced developers that are able to write completely errorfree codeas for the exceptions that get caught i do log them to a log file including the complete stack trace that was the whole point of that exercise just to counter those people that were taking my analogy to vbs oern too literallyi know that blindly ignoring certain classes of errors is dangerous and might corrupt my application instance as said before this program is not missioncritical for anyone noone in their right mind would bet the survival of the human civilization on it it is simply a little tool for testing certain design approaches wrt software engineeringfor the immediate use of the application there are not many things that can happen on an exceptionno exception handling a error dialog and application exit experiment has to be repeated though likely with another subject no errors have been logged which is unfortunategeneric exception handling a benign error trapped no harm done this should be the common case judged from all errors we were seeing during development ignoring this kind of errors should have no immediate consequences the core data structures are tested well enough that they will easily survive thisgeneric exception handling a serious error trapped possibly crash at a later point this may happen rarely weve never seen it so far the error is logged anyway and a crash might be inevitable so this is conceptually similar to the very first case except that we have a stack trace and in the majority of cases the user would not even noticeas for the experiment data generated by the program a serious error would at worst just cause no data to be recorded subtle changes that change the result of the experiment ever so slightly are pretty unlikely and even in that case if the results seem dubious the error was logged one can still throw away that data point if it is a total outlierto summarize yes i consider myself still at least partially sane and i do not consider a global exception handling routine which leaves the program running to be necessarily totally evil as said twice before such a decision might be valid depending on the application in this case it was judged a valid decision and not total and utter bullshit for any other application that decision might look different but please do not accuse me or the other people who worked on that project to potentially blow up the world just because were ignoring errorsside note there is exactly one user for that application it is not something like windows or office that gets used by millions where the cost of having exceptions bubble to the user at all would be very different in the first place already,['c#'] +13137,database reporting services in django or python i am wondering if there are any django based or even python based reporting services ala jasperreports or sql server reporting servicesbasically i would love to be able to create reports send them out as emails as csv or html or pdf without having to code the reports even if i have to code the report i wouldnt mind but the whole framework with schedules and so on would be niceps i know i could use django apps to do it but i was hoping if there was any integrated solutions or even projects such as pinax or satchmo which brings together the apps neededpps it would have to work off postgresthanks and regardsmark,['python'] +13138,xmldocumentation for a namespace would you write xmldoc for a namespace and if yes how and wherei would think if it is possible maybe an almost empty file like this summary this namespace contains stuff summarynamespace somenamespacebut will that work since you declare or at least use the namespace in all the other files as well and what would happen if you wrote an xmldocumentation thing somewhere else on the same namespace would one be gone or would they be merged somehow,['c#'] +13145,iphone uitextfield how to insert new line by the return key i want to get a carriage returnnew line by hitting the return keyon an uitextfields keyboardi have found out that textfieldshouldreturn gets calledbut how do i insert a carriage return in the text field,['iphone'] +13146,compilerparametersreferencedassemblies add reference to systemwebuiwebcontrols i am compiling classes at runtime using the codedomprovider class this works fine for classes only using the system namespaceusing systempublic class test public string helloworld return hello world if i try to compile a class using systemwebuiwebcontrols though i get this errorerror cs06 metadata file systemwebuiwebcontrols could not be found systemcodedomcompilercompilererrorheres a snippet of my codevar cp new compilerparameterscpreferencedassembliesaddsystemwebuiwebcontrolshow do i reference the systemwebuiwebcontrols namespace,['c#'] +13149,net guidelines why exception for twoletter acronyms microsofts framework design guidelines define among other things the followingdo capitalize both characters of twocharacter acronyms except the first first word of a camelcased identifierso there is an exception defined for acronyms that comprise of only two letters since acronyms with three or more letters are properly camel cased or pascal casedthe question is why is there an exception ie what is the rationale behind it i could not get an explanation from the fdg book or the blogs of abrams and cwalina,['.net'] +13152,hello world the tdd way well i have been thinking about this for a while ever since i was introduced to tdd which would be the best way to build a hello world application which would print hello world on the console using test driven developmentwhat would my tests look like and around what classes request no wikipedialike links to what tdd is i am familiar with tdd just curious about how this can be tackled,['c#'] +13157,good zend framework example apps to learn from do you know of any opensource zend framework applications besides magento that show in a good oopway how to develop big apps with zend frameworkmy problem right now is that i am pretty good at php and oop but i do not have enough knowledge of the zend framework and how things should be solved in itso do you know any good applications that showcase bestpractices for zfthanks,['php'] +13158,i have php running on google app engine how do i use a db i followed php on the google appengine to setup and it works great any suggestions on how to use a database datastore with php on gae,['php'] +13165,how to create aspnet userserver control that uses a list of asplistitem as child controls i am looking to create a userserver control that will be created with something like the followingmymylistcontrol runatserver asplistitem texttest1 valuetest1 asplistitem texttest2 valuetest2 mymylistcontroli am just looking for a start herearticles or code sampleswhat base class should i inherit from what to overridepossibly how to customize what sub items my control accepts mylistitem instead of asplistitemwhat i am looking to do is create a very simple bread crumb control for a small section of my site i have it all working with stock aspnet controls but the items are added in code which means fixing a spelling mistake or formatting bug involves a recompile which is not idealeditheres my code with the addition of joshs suggestion belownamespace mysitecontrols partial class breadcrumbs inherits usercontrol private m breadcrumbs as new listof breadcrumbitem persistencemodepersistencemodeinnerproperty public property items as listof breadcrumbitem get return m breadcrumbs end get setbyval value as listof breadcrumbitem m breadcrumbs value end set end property private sub page loadbyval sender as object byval e as eventargs handles mybaseload bind end sub private sub bind lvcrumbsdatasource items medatabind end subend classpublic class breadcrumbitem private m text as string public property text as string get return m text end get setbyval value as string m text value end set end property private m url as string public property url as string get return m url end get setbyval value as string m url value end set end propertyend classend namespacethen my page code looks like this page languagevb autoeventwireupfalse inheritsmysitemypage titlemy page codebehindmypageaspxvb register tagprefixmy namespacemysitecontrols assemblymysite mybreadcrumbs idbreadcrumbs runatserver items mybreadcrumbitem textanother page urlanotherpageaspx itemsmybreadcrumbs,"['.net', 'asp.net']" +13172,does index of array exist i have inherited some code at work that has a really bad smell i am hoping to find the most painless solution possibleis there a way to check if some arbitrary number is a valid element in an arrayexample i need to check if array25 existspreferably i would prefer to do this without doing a foreach through the array to found the rowsis there any way to do this or am i stuck with foreach loop,['c#'] +13174,css 100 height header with static height i am building a layout which includes a header which is 40 px in height underneath this header a swf resides that should take up the rest of the available spacethe best solution untill now has been working with a table giving the first row 40px height and the second row a 100 height but these rows still add up in internet explorer resulting in a scrollbar appearing for 40 extra pixels which should not be the case i tried using this frames v2 fullheight it works fine if you have content that pushes down eventually but with a swf with 100 in it it will take over the whole page or half the page depending on putting the swf in the content div or the swf being the content divbefore i resort to javascript to take care of this business i am wondering if someone else knows a better solution,['css'] +13181,java is never passbyreference rightright possible duplicateis java apassbyreferencea i found an unusual java method todayprivate void addshortenednamearrayliststring voicesetlist string vsname if null vsname vsname else vsname vsnametrim string shortenedvoicesetname vsnamesubstring0 mathmin8 vsnamelength scr10638 prevent export of empty rows if shortenedvoicesetnamelength 0 if voicesetlistcontains shortenedvoicesetname voicesetlistadd shortenedvoicesetname according to everything i have read about javas behavior for passing variables complex objects or not this code should do exactly nothing so umam i missing something here is there some subtlety that was lost on me or does this code belong on thedailywtf,['java'] +13188,how to compare value of 2 fields in django queryset i have a django model like thisclass playermodelsmodel name modelscharfield batting modelsintegerfield bowling modelsintegerfieldwhat would be the django queryset equivalent of the following sqlselect from player where batting bowling,['python'] +13190,nested use of c object initializers so object initializers are all kinds of handy especially if youre doing linq where they are downright necessary but i cannot quite figure out this onepublic class class1 public class2 instancepublic class class2 public class1 parentusing like thisclass1 class1 new class1class1instance new class2class1parent class1as an initializerclass1 class1 new class1 instance new class2 parent class1 this does not work class1 is supposedly an unassigned local variable it gets even trickier in linq when you are doing something likeselect new class1 it does not even have a name to refer to it byhow do i get around this can i simply not make nested references using object initializers,['c#'] +13191,how to deserialize an object persisted in a db now when the object has different serialversionuid my client has an oracle data base and an object was persisted as a blob field via objoutstreamwriteobject the object now has a different serialversionuid even though the object has no change maybe different jvm version and when they try to deserialize an exception is thrownjavaioinvalidclassexception commissionresult local class incompatible stream classdesc serialversionuid 8452040881660460728 local class serialversionuid 5239021592691549158they did not assign a fixed value for serialversionuid since the beginning so now that some thing changed that exception is thrown now they do not want to loose any data to do so i think the best is to read the objects deserialize them and persist them again via xmlencoder to avoid future errors like the current class incompatible error apparently there are 2 different values for the serialversionuid persisted for that object so i want to read the data try with one value and if it fails then try with the other value to do so i have tried to change the serialversionuid of the class usingthe asm api i have been able to change the value but the problem is how to make active the change upon the class so when it is deserialized the objinpstrreadobject take my modified version of the class with my specific serializedversionuid i made a test class to simulate the real environment i take an object which has as property the object with different serialversionuid problem the object name is reservation the property iscommissionresultpublic class reservation implements javaioserializable private commissionresult commissionresult nullpublic class commissionresult implements javaioserializableimport orgobjectwebasmclassreaderimport orgobjectwebasmclassvisitorimport orgobjectwebasmclasswriterimport orgobjectwebasmcommonsserialversionuidadderpublic class serialversionuidredefiner extends classloader public void workwithfiles try reservation res new reservation fileoutputstream f new fileoutputstreamhomexabstracttemporesser objectoutputstream out new objectoutputstreamf outwriteobjectres outflush outclose classwriter cw new classwriter0 classvisitor sv new serialversionuidaddercw assigns a real serialversionuid classvisitor ca new myownclassadaptersv asigns my specific serialverionuid value classreader crnew classreaderreservation cracceptca 0 serialversionuidredefiner loader new serialversionuidredefiner byte code cwtobytearray class exampleclass loaderdefineclassreservation code 0 codelength at this point the class reservation has an especific serialversionuid value that i put with myownclassadapter loaderresolveclassexampleclass loaderloadclassreservation deserializerthread dtnew deserializerthread dtsetcontextclassloaderloader dtrun catch exception e eprintstacktrace import javaiofileinputstreamimport javaioobjectinputstreampublic class deserializerthread extends thread public void run try fileinputstream f2 f2 new fileinputstreamhomexabstracttemporesser objectinputstream in new objectinputstreamf2 reservation c1 reservationinreadobject systemoutprintlnc1 catch exception e eprintstacktrace stop myownclassadapter relevant codepublic void visitend asign svuid and add it to the class try cvvisitfieldopcodesacc final opcodesacc static serialversionuid j null new long11001computesvuid catch throwable e eprintstacktrace throw new runtimeexceptionerror while computing svuid for x e supervisitend the test should fail with the javaioinvalidclassexception local class incompatiblebecause i changed the serialversionuid after i saved the file and used a new one to readde file but it does not fails so it means that the objectinputstreamreadobject is notusing my modified version of the reservation classany ideas thanks in advanceupdateok it is possible to redefine the resultclassdescriptor to override the stream serialversionuid but some thing strange happens as i said before it seems thereare 2 versions of the class persisted objects with serialversionuid 5239021592691549158l and others with value 8452040881660460728l this last value isthe one generated if i do not specify a value to the local classif i do not specify a value for the serialversionuid then the default value 8452040881660460728l is used but is not possible to deserealize the objects thathas the other value an error is thrown saying that a property is of an other typeif i specify the value 5239021592691549158l then classes persisted with that valueare successfully deserialized but not the others same error of typesthis is the error trace potentially fatal deserialization operation javaioinvalidclassexception overriding serialized class version mismatch local serialversionuid 5239021592691549158 stream serialversionuid 8452040881660460728javalangclasscastexception cannot assign instance of javautilhashmap to field composadasicrulescommoncommisionrulescommissionresultstatuscode of type javalangstring in instance of composadasicrulescommoncommisionrulescommissionresultwhen this error was thrown the class had the value of 5239021592691549158 if changethe value to 8452040881660460728 the class is successfully deserialized so what happens why is that error that tries to cast for wrong class thanks,['java'] +13194,change highlight color jquerys highlight method will highlight any div with a yellow backgroundhow do i specify what color to use instead of yellow for highlight,['jquery'] +13205,rails has many association count child rows what is the rails way to efficiently grab all rows of a parent table along with a count of the number of children each row hasi do not want to use counter cache as i want to run these counts based on some time conditionsthe cliche blog exampletable of articles each article has 0 or more commentsi want to be able to pull how many comments each article has in the past hour day weekhowever ideally i do not want to iterate over the list and make separate sql calls for each article nor do i want to use include to prefetch all of the data and process it on the app serveri want to run one sql statement and get one result set with all the infoi know i can hard code out the full sql and maybe could use a find and just set the joins group and conditions parameters but i am wondering if there is a better way aka the rails waythanks in advance,['ruby-on-rails'] +13211,php zend framework generator i am in the phase of learning zend framework for php development i have been doing dirty php programming for about 2 years now and i have learnt quite a bit from my mistakesi have been introduced to ruby on rails it is a great framework and ruby is quite an interesting language too but not everyone wants their web sites to be in ror at least not all of my clientshence as a result i do a lot of php having worked on ror i find zend framework to provide very similar functionality and environment and hence i am really excited about the samehowever i am interested to know if there are any generator scripts that help you along the process to generate automate common tasks such as project structure creation model creation controller creation just like those in rorif such a thing already exists great otherwise i will go ahead and build such scripts myself as i am very certain they will come in very handy especially for me,['php'] +13214,round number to nearest 02 with php i am creating this rating system using 5edged stars and i want the heading to include the average rating so i have created stars showing 15ths using 12 i will get a full star and one point on the next star and so onbut i have not found a good way to round up to the closest 2 i figured i could multiply by 10 then round of and then run a switch to round 1 up to 2 3 up to 4 and so on but that seems tedious and unnecessary,['php'] +13215,python method to extract content excluding navigation from an html page of course an html page can be parsed using any number of python parsers but i am surprised that there do not seem to be any public parsing scripts to extract meaningful content excluding sidebars navigation etc from a given html doc i am guessing it is something like collecting div and p elements and then checking them for a minimum amount of text content but i am sure a solid implementation would include plenty of things that i have not thought of,"['python', 'html']" +13217,are there known false positives issues with valgrind are there any known false positives with valgrind i get a conditional jump or move depends on uninitialised values with the fmemopen function writing in c and compiling with gcc can i be sure it is realedit are there known issues that are not in the suppression files are there some things one can do in a program that are not really errors but valgrind will say they are if there are known issues a list would be nice,['c'] +13232,file uploading in ajax updatepanel without full postback i have a update panel in the update panel i have fileupload control and button control on button click i need the file that i have upload in the fileupload control in updatepanel exact scenario i have 8 tabs on page each tab contains too much information one of the tab is attachment when user click on add new attachment modal popup shown modal contains detailsview in updatepanel and in the detailsview i have fileupload control when user hit save button detailsview inserting event fired in the inserting event i need the file that i have upload please note my page is heavy and i do not want full postbackdoes anyone have solution of this issue advance thanks for your kind help,['asp.net'] +13243,c is it possible to mark overriden method as final in c is it possible to mark an overridden virtual method as final so implementers cannot override it how would i do itan example may make it easier to understandclass a abstract void doactionclass b a override void doaction implements action in a way that it does not make sense for children to override eg by setting private state later operations depend on class c b this would be a bug override void doaction is there a way to modify b in order to prevent other children c from overriding doaction either at compiletime or runtime,"['c#', '.net']" +13249,is this the best way in c to convert a delimited string to an int array given the string belowstring str 123will this be the best extension to convert it to an int arraystatic class stringextensions public static int tointarraythis string s return tointarrays public static int tointarraythis string s char separator string ar ssplitseparator listint ints new listint foreach var item in ar int v if inttryparseitem out v intsaddv return intstoarray,['c#'] +13252,extending an activexobject in javascript i want to add some functionality track certain calls to activex object methods in javascript i usually create my activex object like thisvar tconn new activexobjecttconnectori need to log every time the open method is called on tconn and all other instances of that activex controli cant modify tconns prototype because it does not have one i think that i can create a dummy activexobject function that creates a proxy object to proxy calls to the real one can you help me do thatnote writing a direct wrapper is out of question because there are already 10s of calls to this activex within the application,['javascript'] +13254,objectivec iphone how to set default value for a property hi i have got the following code in a viewcontrollerhimport uikituikithinterface calcviewcontroller uiviewcontroller nsnumber result nsstring input nsstring input iboutlet uitextfield thisplayproperty retain nsnumber resultproperty retain nsstring inputproperty nonatomic retain uitextfield thisplayendthe problem is that i want to append a string to input but this is not possible when its still null thats why i want to set the default value of input to be but where do i put this codei am aware of one possible solution where you put it in a default constructor but i have got no idea in what file to put this and where i should call it fromi unfortunately only got a limited understanding of c and realise that perhaps a h file is not the right placethe project type is a viewbasedapplication if you should need thishope you can help,"['iphone', 'objective-c']" +13258,algorithm for neatly indenting sql statements python implementation would be nice i would like to reformat some sql statements that are a single string with newlines in to something that is much easier to readi do not personally know of a good coding style for indenting sql how should nested queries where clauses left joins etc by represented to maximise readabilityhas anyone seen a prettyprinting algorithm that does this already in python would be even better,"['python', 'sql']" +13262,testing if value is a function i need to test whether the value of a forms onsubmit is a function the format is typically onsubmitreturn valid is there a way to tell if this is a function and if it is callable using typeof just returns that it is a string which does not help me muchedit of course i understand that return valid is a string i have replaced it down to valid and even valid i want to know if either of those is a functionedit heres some code which may help explain my problemabuttonparentsformsubmitfunction var submit function abuttonparentsformattronsubmit if submit function typeof submit functionreplacereturn function return evalsubmit functionreplacereturn else alertonsubmit is not a functionis the script included return false edit 2 heres the new code it seems that i still have to use an eval because calling formsubmit does not fire existing onsubmitsvar formobj abuttonparentsformformobjsubmitfunction if formobj0onsubmit typeof formobjonsubmit function return evalformobjattronsubmitreplacereturn else alertonsubmit is not a functionis the script included return false suggestions on possibly how to do this better,['javascript'] +13269,how to turn a ruby hash into http params that is pretty easy with a plain hash like a a b bwhich would translate into aabut what do you do with something more complex like a a b c d ewhich should translate in aab0cb1db2eor even worse with something like a a b c c d d e e f fthanks for the much appreciated help with that,['ruby'] +13271,what should i choose jquery mootools yui scriptaculous or prototype duplicate which javascript framework jquery vs dojo vs a i am totally new to javascript but i want to implement ajax features into my website which js framework should i learn please recommend or which one you are using and why you use it,"['javascript', 'jquery']" +13274,how to determine if a string is a valid ipv4 or ipv6 address in c i know regex is dangerous for validating ip addresses because of the different forms an ip address can takei have seen similar questions for c and c and those were resolved with a function that does not exist in c inet ntopthe net solutions i have found only handle the standard d form any suggestions,"['c#', '.net']" +13281,io redirection in eclipse is it possible to use io redirection in eclipse i want to redirect standard inputoutput on the command line like java myprogram inputtxt outputtxt but i cannot seem to get it to work in eclipse i tried including the s as part of the program arguments which was ignored and also in the vm arguments which just threw up a class not found error anybody know how to do thischeers,['java'] +13282,valid javabeans names for boolean getter methods i know most variable names will work with is such as isblue but is has also a valid prefix like hasproperty,['java'] +13296,two way data binding with a dictionary in wpf i would like to bind a dictionarystring int to a listview in wpf i would like to do this in such a way that the values in the dictionary get updated via the data binding mechanism i do not want to change the keys just the values i also do not care about adding new mappings to the dictionary i just want to update existing onessetting the dictionary as the itemssource of the listview does not accomplish this it does not work because the listview uses the enumerator to access the contents of the dictionary and the elements of that enumeration are immutable keyvaluepair objectsmy current line of investigation attempts to use the keys property i assign this to the itemssource property of my listview this does allow me to thisplay the keys but i do not know enough about wpfs databinding mechanism to access the values in the dictionaryi found this question access codebehind variable in xaml but still cannot seem to bridge the gapdo any of you know how to make this approach workdoes anyone have a better approachit seems like as a last resort i could build a custom object and stick it in a list from which i recreateupdate my dictionary but this seems like a way to circumvent the builtin data binding functionality rather than effectively utilize it,['c#'] +13303,iis 70 with pipeline mode integrated doesna t load any imagecss in asp net i have a full system working in iis 51 i migrated to iis 70 with pipeline mode classic all works fine but with pipeline integrated my imagescss are not loaded ia m using aspnet 35 with a web applicationany help,['asp.net'] +13305,do i need to explicitly alloc my nsnumber i am defining a number as followsnsnumber nn0 nsnumber numberwithint0it works fine without any alloc my understanding is that if i use numberwithint alloc and init are called automaticallyif i try to release at the end of my function i run into problemsnn0 releasei get a runtime error my question is if i use numberwithint to initialise the nsnumber do i have to do any memory management on it,"['iphone', 'objective-c']" +13310,sql grouping by all the columns is there any way to group by all the columns of a table without specifying the column names likeselect from table group by,['sql'] +13311,how to implement undo operation in net windows application assume that a win form has certain input fields and user entersreenters some datahow to retain data previously entered by undo operationjust i want to know the best way to accomplish it,['.net'] +13313,dynamically invoking any function by passing function name as string how do i automate the process of getting an instance created and its function executed dynamicallythanksedit need an option to pass parameters too thanks,['c#'] +13314,looking for a php andor python rad i am looking for rad like environment for php andor python free or not does not matterit should have a visual environment where one can use a point and click interface so that it is possible to select objects with mouse and move them aroundi have looked at delphi4php the rad part is fantastic but i do not like the framework on which it is based vcl4php vcl4phpsourceforgenet is crappy just to deploy a simple hello world application we will have to deploy 40mb of that framework that is just stupidi looked at eclipse but it is only a code ide does not have a visual way of designing a pagewindow did i miss any plugin that supports this featurei was suggested to give netbeans ide a close look so i also looked that up but did not find what i wantedi have also looked up following but none of these are true radnusphere phpedvs php for visual studio php designer not a designer by any means just a plain old idei have not been able to find any descent python rad tool alsoi have looked up yes softwares code charge studio wyessoftwarecom but it cannot be used to develop complicated applications like say for example an accounting system or an inventory management app etc it is useful but for very simple apps making changes to visual part referred as components by this people is a nightmare finally it does not support python,"['php', 'python']" +13323,c how to draw a binary tree to the console what algorithms can be used to draw a binary tree in the console the tree is implemented in c for example a bst with numbers 2 3 4 5 8 would be shown in the console as,['c'] +13329,deriving class from generic t i have a parameterized hibernate dao that performs basic crud operations and when parameterized is used as a delegate to fulfil basic crud operations for a given daopublic class hibernatedao t id extends serializable implements genericdaot idi want to be able to derive class from t at runtime to create criteria queries in hibernate such thatpublic t findbyprimarykeyid id return t hibernateutilgetsessionloadtgetclass idi knowtgetclassdoes not exist but is there any way to derive the correct class object from t at runtimei have looked at generics and reflection but have not come up with a suitable solution perhaps i am missing somethingthanks,['java'] +13337,how can i print out the memory adress of an variable i would like to print whats behind an myvariable i tried nslogmyintvar but it would not work,['objective-c'] +13340,is anyone using springsource tc server as a tomcat replacement it looks like springsource has just released a ga version of their tc server application serverit sounds from their description like it is a dropin replacement for apache tomcat with better enterprise capabilities such as advanced diagnostics better operations management deployment etc and of course the support that they want to sell you as their primary business modelso i am curious and i am not sure if this is truly a so question but is anyone using tc server today in any shape or fashion has it worked out well for you did you find whatever features they are adding to tomcat to be worth it,['java'] +13341,why does eclipse cdt say syntax error but compilation no problem i am working in existing c code which has a couple of lines with statements similar to this onestruct collect conn tc struct collect conn char c offsetofstruct collect conn runicast connthe struct collect conn goes along the following linesstruct collect conn struct runicast conn runicast conn struct announcement announcement const struct collect callbacks cb struct ctimer t uint16 t rtmetric uint8 t forwarding uint8 t seqnoi am using eclipse cdt and it marks the line with an orange squiggly line as syntax error i think it is marked as such by the cdt indexerhowever compilation manually in a terminal is no problemthis is a bit inconvenient however since the elements on the line do not get indexed so the call hierarchy tree is not always correct or the highlighting of elements etcwhy does ecipse not like the line as it is,['c'] +13349,how to build a visual c project for linux whats the best and easiest way to build for linux a c application which was written in visual studio the code itself is ready i used only crossplatform libsis it possible to prepare everything under windows in visual studio and then build it with a cli tool under linux are there any docs describing this edit some more information libs used stl wxwidgets boost asio cryptlibvery little linux knowhowedit2 i chose the following solution make new project with kdevelop and compile everything there,['c++'] +13350,redefining a single ruby method on a single instance with a lambda in ruby is there a way to redefine a method of a particular instance of a class using a proc for exampleclass foo def bar return hello endendx foonewy foonewsomething likeymethodbar lambda return goodbye xbarybarproducinghellogoodbyethanks,['ruby'] +13359,customizing a tabcontrol for the closing of individual tabs my scenario is the followingi am working on a winforms application in c that has a button inside the main page of a tabcontrol that will generate another tabpage each time that it is clicked each new tabpage will contain a layout defined by a user control my questions arehow can i allow the user to then close one of the tabs that were created dynamically at runtimehow might i go about modifying the tabcontrol itself so that it has a small x in each tab that the user may click on in order to close that particular tab like firefox hashow can i expose the selectedindex property of the tabcontrol to the user control if i want to close the tab with a button inside the user control instead,['c#'] +13360,how to serialize on to existing file let say i have a file that contains a serialized object by binaryfomatter now i want to be able to serialize another object and append this on that existing filehow can i do it,"['c#', '.net']" +13363,google maps thousands of markers json in the following example the markers are loaded from a jsonif there are 20 markers the json is going to be quite big is there any way to send different json files according to zoom level instead of sending one huge array maphtml,['javascript'] +13374,ant compile does not copy the resources i created my own buildxml which hastarget namecompile mkdir dirbuild javac destdirbuild src pathsrc javactargettarget namebuild dependscompile mkdir dirthist jar destfilethistappjar basedirbuild targettarget namerun dependscompile java classnamewebserverloader classpathbuild forktrue targetit works great when i call ant run so it compiles and runs my application but my application has a package with icons and it is not moved to a folder build so my application ends with an exception that it could not locate my icons when i move them by myself then it worksi tried to usecopy todirbuildappicons fileset dirsrcappiconscopyit works but i would like to do it without the copy command is there any parameter to javac or something elsethank you for answer,['java'] +13384,example code for embedding svg canvas in swt project is there a good example of how to include an svg canvas into a java swt project particularly holongate though i would be interested in any other options additionally i would need to support this svg canvas on mac os x windows and linux clients in case an implementation relies on native libraries thanks for any pointers,['java'] +13385,how to find fqdn of local machine in cnet how can you get the fqdn of a local machine in c,['c#'] +13389,get php class property by string how do i get a property in a php based on a string i will call it magic so what is magicobjname somethingget objnamewould be likemagicobj name somethingget magicobj name,['php'] +13396,loading up a webxml for integration tests with jetty ok this is kind of related to got great answers there and have been able to load up servlets programmatically and its all made of awesome what i would like to do however is load up a webxml in a test all in the classpath and have it run up a server using the current classpath i have seen in docs how to point it to a directory to do that but i want to work off the classpath better for in place testing essentially validating my webxml its not relevant but this app is in scala but i have had no issue with that everything works as advertised,['java'] +13401,can i set an infinite autopopdelay for a tooltip in a net windows forms window i have a requirement to not have the standard net windows forms tooltip automatcially hide that is i need them to remain visible until the mouse moves off the control that has the tooltip i would like to avoid having to use specific mouseenter and mouseleave events for all controls with a tooltip i am happy to hear about thirdparty solutions if they would solve the problem,"['c#', '.net']" +13407,newbie teaching self python what else should i be learning i am a newbie to programming i had 1 semester of computer science we used java i got an a in the course and was able to do everything assigned however i am not sure i really understood it i ignored the text and learned by looking at sample programs and then trial and error i was ahead of the class except for two guys who came in knowing java or another oop languagei would like to learn python i am also going to build a second pc from extra parts i have and use linux basically i want to enhance my knowledge of computers thats my motivationnow on learning python are there any good programming theory books that would be useful or should i read up on more on how computers operate on the lowest levels i do not think i know enough to ask the question i want i guess to make it simple i am asking what should i know to make the most of learning python this is not for a career this is from a desire to know i am no longer a computer science major it also would not have any direct applications to my anticipated careeri am not looking to learn in 30 days or 1 week or whatever so starting from a very basic level is fine with me thanks in advance i did a search and did not quite find what i was looking for update thanks for all the great advice i found this site at work and could not find it on my home computer so i am just getting to read now,['python'] +13408,computing md5sum of large files in c i am using following code to compute md5sum of a file byte b systemiofilereadallbytesfilestring sum bitconvertertostringnew md5cryptoserviceprovidercomputehashbthis works fine normally but if i encounter a large file 1gb eg an iso image or a dvd vob file i get an out of memory exceptionthough i am able to compute the md5sum in cygwin for the same file in about 10secsplease suggest how can i get this to work for big files in my programthanks,['c#'] +13409,sqldatetimeminvalue datetimeminvalue why i wonder why sqldatetimeminvalue is not the same as datetimeminvalue,['.net'] +13411,automated web ui testing what are the good automated web ui testing toolsi want to be able to use it in the net world but it does not have to written in netfeatures such as a record mode integration into build process continuous integration would be niceim going to look atwatirseleniumare there any others i should look at,['asp.net'] +13414,how do i give text or an image a transparent background using css is it possible using css only to make the background of an element semitransparent but have the content text images of the element opaquei would like to accomplish this without having the text and the background as two separate elementswhen tryingp position absolute backgroundcolor green filter alphaopacity60 opacity 06span color white filter alphaopacity100 opacity 1p spanhello worldspanpit looks like child elements are subjected to the opacity of their parents so opacity1 is relative to the opacity06 of the parent,"['html', 'css']" +13415,c what does the operator do in detail in c what does exactly happen in the background when you do a comparison with the operator on two objects does it just compare the addresses or does it something like equals or compareto ps what about the operator in java does it behave the same,"['c#', 'java']" +13430,naming conventions for bool objc 2 properties i have a readonly bool property what is dominant naming pattern herebackground for plain old method declarations the accepted pattern booliseditable voidseteditableboolflagin a property world that would typically be expressed aspropertygetteriseditable bool editablehowever there are examples to the contrary such as in calstorecalcalendarhpropertyreadonly bool iseditableis calcalendar wrong here or is that the also an acceptable naming pattern for readonly bool propertiesi have got a controller which manages a view which may or may not be resizable the property is read onlypropertyreadonly bool viewisresizablepropertyreadonly bool isviewresizablepropertyreadonly getterisviewresizable bool viewresizablewhich pattern is most natural or cocoalike,['objective-c'] +13437,infragistics controls are they stableeasy to learn what is your opinion on infragistics controls both web and win is this a stable library what do you feel about the learning curve,['asp.net'] +13448,bcl base class library vs fcl framework class library whats the difference between the two can we use them interchangeably,"['c#', '.net']" +13464,combine two or more pdfs background i need to provide a weekly report package for my sales staff this package contains several 510 crystal reportsproblemi would like to allow a user to run all reports and also just run a single report i was thinking i could do this by creating the reports and then doinglistreportclass reports new listreportclassreportsaddnew weeklyreport1reportsaddnew weeklyreport2reportsaddnew weeklyreport3snipforeach reportclass report in reports reportexporttothiskexportformattypeportabledocformat creports reportresourcename pdfthis would provide me a folder full of the reports but i would like to email everyone a single pdf with all the weekly reports so i need to combine themis there an easy way to do this without install any more third party controls i already have devexpress crystalreports and i would prefer not to add too many morewould it be best to combine them in the foreach loop or in a seperate loop or an alternate waythanks,"['c#', '.net']" +13466,jquery fade background on hover there is a link with no background and a css rule which changes background on hoverparent bg is white link on hover bluehow can i do a hover effect slowly from white to bluethanksli a li ahover background blue,"['javascript', 'jquery', 'css']" +13473,django manager chaining i was wondering if it was possible and if so how to chain together multiple managers to produce a query set that is affected by both of the individual managers i will explain the specific example that i am working oni have multiple abstract model classes that i use to provide small specific functionality to other models two of these models are a deletemixin and a globalmixinthe deletemixin is defined as suchclass deletemixinmodelsmodel deleted modelsbooleanfielddefaultfalse objects deletemanager class meta abstract true def deleteself selfdeleted true selfsavebasically it provides a pseudodelete the deleted flag instead of actually deleting the objectthe globalmixin is defined as suchclass globalmixinmodelsmodel is global modelsbooleanfielddefaulttrue objects globalmanager class meta abstract trueit allows any object to be defined as either a global object or a private object such as a publicprivate blog postboth of these have their own managers that affect the queryset that is returned my deletemanager filters the queryset to only return results that have the deleted flag set to false while the globalmanager filters the queryset to only return results that are marked as global here is the declaration for bothclass deletemanagermodelsmanager def get query setself return superdeletemanager selfget query setfilterdeletedfalseclass globalmanagermodelsmanager def globalsself return selfget query setfilteris global1the desired functionality would be to have a model extend both of these abstract models and grant the ability to only return the results that are both nondeleted and global i ran a test case on a model with 4 instances one was global and nondeleted one was global and deleted one was nonglobal and nondeleted and one was nonglobal and deleted if i try to get result sets as such somemodelobjectsall i get instance 1 and 3 the two nondeleted ones great if i try somemodelobjectsglobals i get an error that deletemanager does not have a globals this is assuming my model declaration is as such somemodeldeletemixin globalmixin if i reverse the order i do not get the error but it does not filter out the deleted ones if i change globalmixin to attach globalmanager to globals instead of objects so the new command would be somemodelglobalsglobals i get instances 1 and 2 the two globals while my intended result would be to only get instance 1 the global nondeleted onei was not sure if anyone had run into any situation similar to this and had come to a result either a way to make it work in my current thinking or a rework that provides the functionality i am after would be very much appreciated i know this post has been a little longwinded if any more explanation is needed i would be glad to provide itediti have posted the eventual solution i used to this specific problem below it is based on the link to simons custom querysetmanager,['python'] +13478,c compiler cannot access static method in a nonstatic context i have the code below public class anything public int data get setpublic class mygenericbaset public void instancemethodt data do some job public static void staticmethodt data do some job others memberspublic sealed class usefulcontroller mygenericbaseanything public void proxytostaticmethod staticmethodnull others non derived memberspublic class container public usefulcontroller b get set public class demo public static void test var c new container cbinstancemethodnull works as expected cbstaticmethodnull does not work static method call on object rather than type how to get the static method on the base type cbproxytostaticmethod works as expected the compiler is very angry i understand the error message but i do not know how to solve this i was trying to get a type rather than an object to make my static method call but i do not find the way to do it correctly moreover this results in something not elegant at allbasically the genericbase is a class from a framework with a lot of static methods and some instance methods the controller is typing this class and extending itthe container is a group of logical related controllersinteresting thing a java version of this code compiles correctly but with a warning the execution is correct toodoes it exist a design pattern to solve this thanks for your inputs i found a way to get rid of this problem thanks to your answers it seems to work but i can not tell if there are side effects right know public class genericbaset mygenericbaset create instance calls here for every base static methodpublic sealed class usefulcontroller genericbaseanything others non derived members,['c#'] +13497,datetime difference operator considers daylight saving as far as i know the difference operator of the datetime type considers leap years so new datetime2008 3 1 new datetime2008 2 1 should return 29 daysnew datetime2009 3 1 new datetime2009 2 1 should return 28 daysbut what about daylight saving,['.net'] +13502,sql express 20052008 concurrent connections how many concurrent connections do the express editions allow my front end uses standard adonet code where i open the connection to the server get my data and then close the connection am i right in saying that as soon as the connection is closed it then allows this connection to be opened by another user,['sql'] +13507,iphone developer program how to sell under multiple company names i work for a web agency and we have just been commissioned to produce an iphone app for a clientwe would want to sell the app on the appstore under the clients company name not our own when signing up our company to the iphone developer program i see it says apps in the appstore will appear under our company namedoes this mean that we would have to sign up to the developer program once for each client we do an app for is there anyway we can have an account but thistribute under multiple company nameshow do freelance iphone developers handle thisedit i am specifically interested in how dev shops which produce iphone apps to sell on behalf of their clients handle this,['iphone'] +13521,c how to compile dll in a exe i am creating a c program but i want to be able to offer just a exe file to the user however i am using libraries curl among others which have some dlls is it possible to compile these dlls into the exe filei use codeblocks and mingw,['c++'] +13522,how can i get jquery to execute animations in exact parallel i am trying to create an accordion widget in jquery similar to jquerys accordion plugin with the difference that i want the handles to appear below their respective content instead of above my accordion works by decreasing the height of the open content section while at the same time increasing the height of the clicked content section i have posted an example here my problem is that the animations are not started at exactly the same time and there is a noticeable jump due to the slight delay before the second animation is startedscriptaculous has a function called effectparallel that allows you to create an array of animation effects and execute them in parallel unfortunately i cannot seem to find something similar with jquery is there a way i can run precise parallel animations on separate divs in jqueryedit i am as much interested in alternative methods of coding this accordion widget so if there is any other method people think would work i am open to that,"['javascript', 'jquery']" +13532,what is the best way to code up a month and year drop down list for aspnet i have an internal application that i needs to have a drop down list for two date type elements month and year these values are not in a database or other repository of informationi know i could just setup a list with the values i need by adding them to a dictionary like object i need to correlate the month to the numerical representation january 01var months new dictionarystringstringmonthsadd01 januarythe drop down list for the year will be a bit easier as i can just choose a starting year and iterate up to the current or current1 year in a generic listis there a better way to handle these data elements something built in or a good design pattern that i should be implementing,"['c#', 'asp.net']" +13537,how can i reorder rows in sql database is it possible to reorder rows in sql databasefor example how can i swap the order of 2nd row and 3rd rows valuesthe order of the row is important to me since i need to thisplay the value according to the orderthanks for all the answers but order by would not work for mefor example i put a list of bookmarks in database i want to thisplay based on the result i get from query not in alphabet order just when they are inserted but user may rearrange the position of the bookmark in any way heshe wants so i cannot use order byan example is how the bookmark thisplay in the bookmark in firefox user can switch position easily how can i mention that in dbthank you,['sql'] +13549,nhibernate update on single property updates all properties in sql i am performing a standard update in nhibernate to a single property however on commit of the transaction the sql update seems to set all fields i have mapped on the table even though they have not changed surely this cannot be normal behaviour in nhibernate am i doing something wrong thanksusing var session sessionfactoryopensession using var transaction sessionbegintransaction var singlemeeting sessionloadmeeting10193 singlemeetingsubject this is a test 2 transactioncommit,['sql'] +13556,java 16 determine symbolic links in a directorywalker class i want to find out if a file instance is actually a symbolic link to a directory assuming the walker walks on unix systems given i already know the instance is a directory would the following be a reliable condition to determine the symbolic linkfile file if filegetabsolutepathequalsfilegetcanonicalpath real directory do normal stuff else possible symbolic link do link stuff,['java'] +13563,why is not all code compiled position independent when compiling shared libraries in gcc the fpic option compiles the code as position independent is there any reason performance or otherwise why you would not compile all code position independent,['c'] +13574,how to troubleshoot net 20 error reporting messages in the event log i work on an open source product called evemon written in c targeting the net 20 platform i have one user who is suffering from a strange net crash that we have been unable to resolveevent type errorevent source net runtime 20 error reportingevent category noneevent id 50date 4292009time 105810 pmuser nacomputer removed thisdescriptioneventtype clr20r3 p1 evemonexe p2 1271301 p3 49ea37c8 p4systemwindowsforms p5 20 p6 4889dee7 p7 6cd3 p8 18 p9systemargumentexception p10 nildatahex representation of the above descriptionthe application itself crashes with out thisplaying an error despite having a error handling ui the above messages was copied out of the windows event log the end user has reinstalled net and updated to the latest versions the pdb files are thistributed with every release version of the program to aid in debugging and testing the user with the problem in question has the full complement of pdb files for the correct version of evemonis there a specific tried and tested technique to analyse and diagnose this type of crash and if so what tools and technologies are available to aid in debuggingspecial thanksi would like to give special thanks to steffen opel and highlight that his answer whilst not directly answering the question i was asking addressed the bigger issue with my code base that the global error handling was missing an important component,"['c#', '.net']" +13581,is there a decorator to simply cache function return values consider the followingpropertydef nameself if not hasattrself name expensive calculation self name 1 1 return self namei am new but i think the caching could be factored out into a decorator only i did not find one like it ps the real calculation does not depend on mutable values,['python'] +13585,how to designate unreachable python code whats the pythonic way to designate unreachable code in python as ingender readfromdb either m or fif gender m greeting mrelif gender f greeting mselse what should this line say,['python'] +13586,how do i get a list of installed updates and hotfixes a list of every update and hotfix that has been installed on my computer coming from either microsoft windows update or from the knowledge base i need the id of each in the form of kbx or some similar representationcurrently i haveconst string query select hotfixid from win32 quickfixengineeringvar search new managementobjectsearcherqueryvar collection searchgetforeach managementobject quickfix in collection consolewritelinequickfixhotfixidtostringbut this does not seem to list everything it only lists qfesi need it to work on windows xp vista and 7,"['c#', '.net']" +13588,wait until qwidget closes i am working on a project in c and qt and i want to open a new qwidget window have the user interact with it etc then have execution return to the method that opened the window example myclass inherits qwidigetvoid dostuff myclass newwindow new myclass i do not want the code down here to execute until newwindow has been closed i feel like there is most likely a really easy way to do this but for some reason i cannot figure it out how can i do this,['c++'] +13595,hide uitabbar in my app i have a tab bar and in some views i as well have a toolbar so when i come to those views with a toolbar it looks ugly two bars at the bottom of the view i thought that it would be a best solution to hide a tab bar when entering those particular viewsbut i just could not figure out how to do it in a right way i tried to set uitabbarcontrollers tabbar hidden property to yes but it did not work and i as well tried to do the following thing in whatever view i amselfhidesbottombarwhenpushed yesbut it did not work as wellwhat is the right solution to this situation i do not want to have 2 bars at any viewthank you,['iphone'] +13600,what steps do you take to troubleshoot problems with php curl almost any working php programmer has faced having to use curl to send raw http requests whether it is for credit card payment processing nefarious screen scraping or something inbetweenalmost any forum where php programmers congregate has a large number of people who cannot get the curl functions to do what they wantwhen curl is not working for you what troubleshooting techniques do you use to figure out why it is not working what weird gotchas with phps curl implementation have you run into if someone asks a halp my curl iz broken question on a forum what are the steps you take to figure out why their request is not working,['php'] +13605,advanced gui possible in java perhaps a philosophical question iave seen some interesting visuals lately in guis mostly on native platform apis i know that aitas just softwarea and that likely with enough work anything can be done with pixels the question is finally is java really an option for doing fancy things with a gui seems like a silly thing i guess but i kind of like some of the windows presentation foundation work i donat see a consolidated effort like this for java where should i look,['java'] +13609,google maps zoomoutpanzoomin animation i am wondering how i get a smooth zoom in animation with the google maps apii have 2 points one in let say china and one in france when i am zoomed in on china and click the button france i want it to gradually zoom out smooth one zoom level at the time when it is zoomed out it should pan to the new location and then zoom in on the new location one zoom level at the timehow can i do this,['javascript'] +13615,how do you force a makefile to rebuild a target i have a makefile that builds and then calls another makefile since this makefile calls more makefiles that does the work it doesnt really change thus it keeps thinking the project is built and upto date dnetdev11 makemake release is up to datehow do i force the makefile to rebuild the targetclean make f x compileworkspacemak cleanbuild svn up x clean cbp2makcbp2mak c x x compileworkspace make f x compileworkspacemak 1 release build debug build debug1clean cleaninstall cp xsourcex utilityreleasex util usrlocalbin cp xsourcex utilityreleasexcoreso usrlocallibnote names removed to protect the innocentedit final fixed versionclean make f x compileworkspacemak cleanbuild svn up clean cbp2makcbp2mak c x compileworkspace make f x compileworkspacemak 1 phony release debug clean installrelease call builddebug call builddebug1clean cleaninstall cp sourcex utillityreleasex util usrbin cp dllsreleasexcoreso usrlib,['c++'] +13619,when is it appropriate to use nolock i am having timeout issues and deadlocks from time to time with some long running queriesi am wondering when is it most appropriate to use nolock and wheredo i use it on the updates inserts or reads,['sql'] +13621,whats the best way to use objc 20 properties with mutable objects such as nsmutablearray i have an objc 20 class that has an nsmutablearray property if i use the following code then the synthesised setter will give me an immutable copy not a mutable oneproperty readwrite copy nsmutablearray myarrayis there any reason that apple did not implement the following syntaxproperty readwrite mutablecopy nsmutablearray myarraysince we do not have mutablecopy whats the best way to handle this seemingly common situation should i just write my own setter that does a mutablecopy,"['iphone', 'objective-c']" +13626,how do i add more than one row with zend db i have an array with information which looks more or less like thisdata arraycontentasddata arraycontentasdfand i want to add both entries into the databasedbinserttable datadoes not add both entries what am i doing wrong do i have to use zend db tabledata arraycontentasdfdbinserttable dataworks of course,"['php', 'mysql']" +13631,should i create a blog in rails or use something that already exists in my next rails project i am going to need blogging functionality i am wondering whether anyone has any good suggestions or should i just roll my own probably not in 15 minutes i think the most important feature will be to thisplay code samples elegantly,['ruby-on-rails'] +13637,how can i create a temporary folder in java possible duplicatecreate a temporary directory in java duplicate stackoverflowcomquestions375910is there a way of creating a temporary folder in java i know of files static method createtempfile but this will only give me a temporary file,['java'] +13649,forcing page refresh on click of back button i have 2 aspnet pagespage a and page bon clicking a link on page a user gets redirected to page bwhen on page b if user clicks browsers back button i need to forcefully invoke page refresh of page ahow do i achieve this functionalitynotecode needs to be compatible across different browsersie ie firefox opera etc,"['asp.net', 'javascript']" +13658,draganddrop files onto an nstableview i have an nstableview which i wish to allow users to draganddrop video files onto when they drop the file it will get added as a row in the table viewhow would i go about doing this currently the tableviews takes its data from an array controller which takes its data from a nsmutablearrayi found this documentation but cannot seem to make it worki havemade a tablecon class which i changed to inherit from nstableview not nsobjectchanged the nstableview class to tableconset the nstableviews delegate outlet to that classcalled registerfordraggedtypes in tablecons initimplemented nsdragoperationdraggingenteredid nsdragginginfosender again in tableconbut nothing it acts like i never changed anything no errors what am i doing wrongedit i have tried implementing boaz stullers suggestion and also found this description of the solution the first reply includes the solution to the first post so what i have done now issubclass nsarraycontroller which feeds content to the table view tablelistconadd tableview outlet to tablelistcon and pointed it at the nstableviewimplement validatedrop writerowswithindexes and acceptdrop in tablelistconcalled registerfordraggedtypes on the tableview outletagain no errorswarnings but only the awakefromnib method seems to be called none of the other methods are called,['objective-c'] +13659,multiple responses from one ajax request not really looking for code examples here just concepts i have three sections on a page now that are being updated via three separate ajax calls to php scripts which return json what would be the easiest way to condense these three calls into one larger call and receive the responses back on the client in json how would i separate the responses on the client so i can manipulate the response data based on what information is sent back,"['php', 'javascript']" +13665,how to know query generated by fluent nhibernate i am using linq to nhibernate to fire some select query to data basemy question is how do i know the query generated by fluent nhibernate,['sql'] +13679,no xmlrootelement generated by jaxb i am trying to generate java classes from the fpml finanial products markup language version 45 a ton of code is generated but i cannot use it trying to serialize a simple document i get thisjavaxxmlbindmarshalexception with linked exception comsunistacksaxexception2 unable to marshal type orgfpml 2008fpml 4 5positionreport as an element because it is missing an xmlrootelement annotationin fact no clases have the xmlrootelement annotation so what can i be doing wrong i am pointing xjc jaxb 21 to fpmlmain45xsd which then includes all types,['java'] +13687,which is fastermore efficient dictionary or dictionary are enum types fastermore efficient than string types when used as dictionary keys idictionarystringobject or idictionaryenumobjectas a matter of fact which data type is most suitable as a dictionary key and whyconsider the following note only 5 properties for simplicitystruct mykeys public string incomplete in public string submitted su public string processingpr public string completed co public string closed cl andenum mykeys incomplete submitted processing completed closedwhich of the above will be better if used as keys in a dictionary,['c#'] +13690,oracle connection string without tnsnamesora file i am using the net framework with the systemdataoracleclient namespace i have the oracle 11 client installed on my computer i do not want to use the tnsnamesora file to store connection informationcould someone please tell me what the connection string would look like if i did not want to use the tnsnamesora file i will be storing the connection string in a webconfig file of a web application project,"['.net', 'asp.net']" +13705,best practices when includingusing a partial view in modern web frameworks like rails and symfony the concept of partial includes or partial views is well documented and recommendedwhat i am having trouble with lately is deciding how much design to include in the partialit is kind of hard to explain but i want to know what others do when creating a partial and including it in a template do you only thisplay the data and position it in the template or do you put all the styling and positioning code in the partial and just include it like soi guess my question is what is your thought process when deciding to create a partial and when do you use it in your own code and how much do you put into your partial when you decide to use one 207insidetheviewlayerpartials,['ruby-on-rails'] +13712,any good references or tools available for converting asp to aspnet what tools practices or documentation have you used in your conversion process that you would recommend to others,['asp.net'] +13717,comments compiled into exe in net i know you can use a net reflector to view code created with net but if i put something in the comments for my own personal reminder is that compiled in the exe as welli do not intend to release the source code for my application and i know the 100 safe bet is to just remove everything i do not want out but i was just wondering if someone could reverse engineer my commentsthankscrash,"['c#', '.net']" +13722,is this interview question too hard for a php dev job were looking for someone to help us enhance maintain our highquality phpbased prototype of a transactional web app ideally who can communicate well and do both front and backend web development as well as smartgets things done etc among other more general things i have been using this questiongiven this foo array1 3 7write a function on this whiteboard to sum the values of the arrayit seems trivially easy to me but has caused a couple of deerintheheadlights situations which always makes me feel like a villain i have read a number of posts here and there including both joels and jeffs saying that how candidates think design skills passion etc are more important than any specific technical skill and i agree with that also i can see that programming at a whiteboard is a little unrealistic otoh this seems so basic to me that i am inclined to see it as a fine firstpass filter between frontend devs who know their way around html css and how to copyandpaste a js function or two and people who can really code thoughtsa touch more info i am open to all sorts of answers array sum a for loop a foreach loop heck if they want to write an arraysum class that would be overkill but just fine using javascript or another language would be fine if they are more comfortable with that even attempts with minor errors would be ok but i have had a couple of complete freezes so i just wanted to sanity check myself,['php'] +13723,how can i serialize an object that has an interface as a property i have 2 interfaces ia and ibpublic interface ia ib interfaceb get set public interface ib ia interfacea get set void setiaia valueeach interfaces references the other i am trying to serialize classa as defined belowserializablepublic class classa ia public ib interfaceb get set public classa call outside function to get interface b ib interfaceb programgetinsanceforib set ib to have a interfacebsetiathis serializablepublic class classb ib public ia interfacea get set public void setiaia value thisinterfacea value as classa i get an error when i try too serialize because the 2 properties are interfaces i want to serialize the propertieshow would i get around thisi need to have references in each interface to the other and i need to be able to serialize the class back and forth,['c#'] +13724,how does phusion passenger reuse threads and processes i am setting up an apache2 webserver running multiple ruby on rails web applications with phusion passenger i know that passenger spawns ruby processes for handling requests i have the following questionsif more than one request has to be handled at the same time will passenger spawn multiple processes or multiple ruby threads how do i configure it so it always spawns singlethreaded processesif i have two rails applications imagine that a request for app a goes to process 1 then later request for app b arrives is it possible that process 1 will handle this request as well when and how is this possible in other words is one process allowed to handle requests for multiple rails applicationsi have the same rails application exported in multiple urls and multiple virtual hosts such as http and https will the same process be able to serve different virtual hosts the answer to this seems to be yes i have set a global variable in answering a request to virtual host a and i was able to retrieve the value in virtual host b,"['ruby-on-rails', 'ruby']" +13729,modify a txt file in java i have a text file that i want to edit using java it has many thousands of lines i basically want to iterate through the lines and changeeditdelete some text this will need to happen quite oftenfrom the solutions i saw on other sites the general approach seems to beopen the existing file using a bufferedreaderread each line make modifications to each line and add it to a stringbuilderonce all the text has been read and modified write the contents of the stringbuilder to a new filereplace the old file with the new filethis solution seems slightly hacky to me especially if i have thousands of lines in my text fileanybody know of a better solution,['java'] +13744,iif equivalent in c is there a iif equivalent in c or similar shortcut,"['c#', '.net']" +13749,creating a loading view using iphone sdk how to create that blackgray modal popup kind of view that many apps use when some long pending operation is in progresslike when using location based services loading a webpage the screen goes dim and there is a modal view showing a spinning icon please waitexample in the following screenshot,['iphone'] +13760,javascript confirm popup yes no button instead of ok and cancel javascript confirm popup i want to show yes no button instead of ok and canceli have used this vbscript codescript languagejavascript function windowconfirmstr execscriptn msgbox str 4132 vbscript return n 6 scriptthis only works in ie in ff and chrome it does not workis there any workround to achieve this in javascripti also want to change the title of popup like in ie windows internet explorer is shown i want to show here my own application name,"['javascript', 'html']" +13763,c listcontains too slow could anyone explain me why the generics lists contains function is so slowi have a list with about a million numbers and the code that is constantly checking if there is a specific number within these numbersi tried doing the same thing using dictionary and the containskey function and it was about 1020 times faster than with the listof course i do not really want to use dictionary for that purpose because it was not meant to be used that wayso the real question here is is there any alternative to the listcontains but not as whacky as dictionarycontainskey thanks in advance,['.net'] +13769,accurate sleep for java on windows does anyone know a library which provides a threadsleep for java which has an error not higher than 12 millisecond i tried a mixture of sleep error measurement and busywait but i do not get this reliable on different windows machines it can be a native implementation if the implementation is available for linux and macos tooeditthe link nick provided the hotspot vm clocks is a really good resource to understand the issues all kinds of timerssleepsclocks java has,['java'] +13775,should entity framework context be put into using statement the entity framework context object implements a thispose method which releases the resources used by the object context what does it do really could it be a bad thing to always put it into a using statement i have seen it being used both with and without the using statementi am specifically going to use the ef context from within a wcf service method create the context do some linq and return the answeredit seems that i am not the only one wondering about this another question is whats really happening inside the thispose method some say it closes connections and some articles says not whats the deal,['c#'] +13780,saving bidirectional manytomany i have two entity classes annotated in the following wayentityclass a manytomanymappedbya cascadecascadetypeall private listb b entityclass b manytomanycascadecascadetypeall private lista a if i store an instance of the class b the relations are stored in the database and the getter in class a will return the correct subset of bs however if i make changes to the list of bs in a the changes are not stored in the databasemy question is how can i make it so that changes in either class are cascaded to the other classedit i have tried different variations of removing the mappedbyparameter and defining a jointable and columns but i have been unable to find the correct combination,['java'] +13781,when should i use perl cgi instead of php or vice versa for hobby purposes i have a shared space on a hosting server that is providing as many of them are both php and perl cgi i have read on several places that cgi scripts are obsolete now i think mainly for performance issues like but since i just started studying perl i wouldnt want to waste time on implementing solutions in php that are way easier or only possible in perlalso there are the boilerplate issues i am aware of cpan that is the existence not yet the content but not familiar with php libraries although i have no doubt they exist i am not prepared to write a loginprocedure or basic user administration from scratch for the 1010th timei do not the luxury at this point to waste a lot of time in research for hobby projects either so i thought let us ask the experts for a headstart,['php'] +13794,how to select all textareas and textboxes using jquery how can i select all textboxes and textareas eginput typetext andtextareatextareaon a page and have the property stylewidth90 applied to them,"['javascript', 'jquery']" +13800,how do i get the name of a ruby class how can i get the class name from an activerecord objecti haveresult userfind1i triedresultclass userid integer name string resultto s user0x3d07cdci need only the class name in a string user in this case is there a method for that i know this is pretty basic but i searched both rails and rubys docs and i could not find it,"['ruby-on-rails', 'ruby']" +13803,inverse stringreplace faster way of doing it i have a method to replace every character except those i specify for example replacenottest stop or not tochararray would return now this is not an instance of premature optimization i call this method quite a few times during a network operation i found that on longer strings it is causing some latency and removing it helped a bit any help to speed this up would be appreciated public static string replacenotthis string original char pattern char replacement int index 0 int old 1 stringbuilder sb new stringbuilderoriginallength while index originalindexofanypattern index 1 sbappendnew stringreplacement index old 1 sbappendoriginalindex old index if originallength old 1 sbappendnew stringreplacement originallength old 1 return sbtostring final s i also added a test case for a 3k character string ran at 100k times instead of 1m to see how well each of these scales the only surprise was that the regular expression scaled better than the others but it is no help since it is very slow to begin withuser short 1m long 100k scalejohn 319 2125 6luke 360 2659 739guffa 409 2827 691mine 447 3372 754dirkgently 1094 9134 835michael 1591 12785 804peter 21106 94386 447update i made the creation of the regular expression for peters version a static variable and set it to regexoptionscompiled to be fairuser short 1m long 100k scalepeter 8997 74715 830pastebin link to my testing code please correct me if it is wrong,['c#'] +13817,how can i access request headers that do not appear in server i am attempting to create a rest api in php and i would like to implement an authentication scheme similar to amazons s3 approach this involves setting a custom authorization header in the requesti had thought i would be able to access the header with serverhttp authorization but it is nowhere to be found in var dump server the apache request headers function would solve my problem but my host implements php as cgi so it is unavailableis there another way i can access the complete request headers in php,['php'] +13820,any real world experience with h2 database has anybody out there got any real world experience with the h2 database i am interested inperformancestabilitybugs,['java'] +13823,thisable auto correction of iphone text field when i try to edit texts in my iphone application uitextfield it autocorrects my input could you let me know how can i thisable this,"['objective-c', 'iphone']" +13835,is there an accepted bestpractice on making asynchronous http requests in android i have seen any number of examples and they all seem to solve this problem differently basically i just want the simplest way to make the request that would not lock the main thread and is cancelableit also does not help that we have at least 2 http libraries to choose from javanet such as httpurlconnection and orgapachehttp is there any consensus on what the best practice is,"['java', 'android']" +13841,how do i get textual contents from blob in oracle sql i am trying to see from an sql console what is inside an oracle blobi know it contains a somewhat large body of text and i want to just see the text but the following query only indicates that there is a blob in that fieldselect blob field from table with blob where id row idthe result i am getting is not quite what i expected blob field oraclesqlblob1c4ada9so what kind of magic incantations can i do to turn the blob into it is textual representationps i am just trying to look at the content of the blob from an sql console eclipse data tools not use it in code,['sql'] +13845,phpregex how to get the string value of html tag i need help on regex or preg match because i am not that experienced yet with regards to those so here is my problemi need to get the value get me but i think my function has an errorthe number of html tags are dynamic it can contain many nested html tag like a bold tag also the get me value is dynamicphpfunction gettextbetweentagsstring tagname pattern tagnametagname preg matchpattern string matches return matches1str textformat leading2p alignleftfont size10get mefontptextformattxt gettextbetweentagsstr fontecho txt,"['php', 'html']" +13848,why does not this c code compile double test true null 10in my book this is the same asif true test null else test 10but the first line gives this compiler errortype of conditional expression cannot be determined because there is no implicit conversion between null and double,"['c#', '.net']" +13852,how to build a query string for a url in c a common task when calling web resources from a code is building a query string to including all the necessary parameters while by all means no rocket science there are some nifty details you need to take care of like appending an if not the first parameter encoding the parameters etcthe code to do it is very simple but a bit tediousstringbuilder sb new stringbuilderif needstoaddparameter a sbappenda sbappendhttputilityurlencodethevalueofa if needstoaddparameter b if sblength0 sbappend sbappendb sbappendhttputilityurlencodethevalueofb this is such a common task one would expect a utility class to exist that makes it more elegant and readable scanning msdn i failed to find onewhich brings me to the following questionwhat is the most elegant clean way you know of doing the above,"['c#', '.net']" +13857,handling combat effects in game development i am trying to nut out a highlevel tech spec for a game i am tinkering with as a personal project it is a turn based adventure game that is probably closest to archon in terms of what i am trying to do what i am having trouble with is conceptualising the best way to develop a combat system that i can implement simply at first but that will allow expansion and complexity to be added in the future specifically i am having trouble trying to figure out how to handle combat special effects that is bonuses or negatives that may be applied or removed by an actor an item or an environment do i have the actor handle all effects that are in play foragainst them should the game itself check each weapon armour actor and location each time it tries to make a decisive rollare effects handled in individual objects or is there an effect object or a bit of bothi may well have not explained myself at all well here and i am more than happy to try and expand the question if my request is simply too broad and airy but my intial thinking is that smarter people than me have spent the time and effort in figuring things like this out and frankly i do not want to taint the conversation with the culdesac of my own stupidity too earlythe language in question is javascript although at this point i do not imagine it makes a great difference,['javascript'] +13858,getting todays date in java i have tried the regular ways i need todays date and zero anything else 050608 0 i have tried calendar calendar calendargetinstance calendarsetcalendarhour 0 date date1 calendargettime systemoutprintlndate1run this is seriously messed upif the hour on the computer is 1200 at noon sun mar 08 004439 ist 2009if the hour on the computer is 1200 at noon sun mar 08 124653 ist 2009so i gave this upall the dates setters are deprecated except the epoch time so i do not want to use them eitherthe only thing i could think of is calendar calendar calendargetinstance simpledateformat dateformat new simpledateformatddmmystring sdate dateformatformatcalendargettimedate today dateformatparsesdatebut this is such a lame code i cannot bring myself to write itany other optionthanks,['java'] +13866,calling constructor from other constructor in same class i have a class with 2 constructorspublic class lens public lensstring parameter1 blabla public lensstring parameter1 string parameter2 want to call constructor with 1 param here i want to call the first constructor from the 2nd one is this possible in c,['c#'] +13890,vc2008 compiler errors opening sbr files c2418 c1903 c2471 edit see my answer below for the hotfixoriginal questionin setting up for our boatprogramming adventure i have to set up source control and fix project files for a team to use them the project was previously only being worked on by one person who took shortcuts with setting up the project includes etci am fixing those sln and proj files when trying to do a build on an external usb drive i have not tried it on the primary hard drive i am getting odd errors lots of them for various filesfatal error c1083 cannot open compiler generated file debugsbr permission deniedthese files are referenced in the vcproj file with relative paths in double quotesrelativepathsourcecppi get the same errors form within a sln file in the ide or if i call msbuild with the sln filethe files are kind of shared for a few sln files projectsthe person who originally created the sln files is not known for being a wizard at configuring msdev or making things work for teams is this an issue with the way the source files are referenced any suggestions on how to fix thesethis url does not seem to have helpful informationfatal error c1083 on msdnnote there wereare still hardcoded paths in the proj file but i dont see them for these files they were mostly for the include and lib dirs i think i removed them alli also get these errorssourcecpp error c2471 cannot update program database debugvc90pdbsourcecpp336 fatal error c1903 unable to recover from previous errors stopping compilationsourcecpp336 error c2418 cannot delete browser file debugsbr,['c++'] +13891,how to get get request parameters in javascript how to get get variables from request in javascriptdoes jquery or yui have this feature builtin,['javascript'] +13894,how can i set the scrolling position of an uiscrollview i have seen the setcontentoffsetanimated method is that going to scroll to a specific position or what does that offset mean,['iphone'] +13899,what is the current state of xslt 20 availability within net the latest i can find from the web and blogosphere indicate that microsofts xml team would be supporting xslt 20 now that it was a full blown w3c recommendation i cannot find anything beyond that whats the current status is it available in net 3540 or are they stuck with xslt 11 and pushing xquery and linq,['.net'] +13900,c tabcontrol tabpage change how do i change the tabpage being thisplayed in my tabcontrol programmatically,"['c#', '.net']" +13903,class vs type in ruby whats the difference between the class and type methods in ruby i have noticed that type works to find the type of some classes but not others,['ruby'] +13909,how should unit tests set up data sources when not running in an application server thank you all for your help a number of you posted as i should have expected answers indicating my whole approach was wrong or that lowlevel code should never have to know whether or not it is running in a container i would tend to agree however i am dealing with a complex legacy application and do not have the option of doing a major refactoring for the current problemlet me step back and ask the question the motivated my original questioni have a legacy application running under jboss and have made some modifications to lowerlevel code i have created a unit test for my modification in order to run the test i need to connect to a databasethe legacy code gets the data source this wayjndiname is a defined stringcontext ctx new initialcontextdatasource datasource datasource ctxlookupjndinamemy problem is that when i run this code under unit test the context has no data sources defined my solution to this was to try to see if i am running under the application server and if not create the test datasource and return it if i am running under the app server then i use the code aboveso my real question is what is the correct way to do this is there some approved way the unit test can set up the context to return the appropriate data source so that the code under test does not need to be aware of where it is runningfor context my original questioni have some java code that needs to know whether or not it is running under jboss is there a canonical way for code to tell whether it is running in a containermy first approach was developed through experimention and consists of getting the initial context and testing that it can look up certain values private boolean isrunningunderjbosscontext ctx boolean runningunderjboss false try the following invokes a naming exception when not running under jboss ctxgetnameinnamespace the url packages must contain the string jboss string urlpackages string ctxlookupjavanamingfactoryurlpkgs if urlpackages null urlpackagestouppercasecontainsjboss runningunderjboss true catch exception e if we get there we are not under jboss runningunderjboss false return runningunderjboss context ctx new initialcontextif isrunningunderjbossctxnow this seems to work but it feels like a hack what is the correct way to do this ideally i would like a way that would work with a variety of application servers not just jboss,['java'] +13913,using in clause in a native sql query we are trying to dynamically generate an in clause for a native sql query to return a jpa entity hibernate is our jpa provider our code looks something like thisnamedquery namefooquery querystringselect f from foo f where fstatus in 1query q entitymanagercreatenamedqueryfooqueryqsetparameter1 newoldreturn qgetresultlistthis does not work the in clause does not recognize any of the values passed in via this manner does anyone know of a solution to this problem,['sql'] +13918,sql delete all the data from all available tables i am using oracle db to maintain more than 30 tables how can i delete all the data from all the tables i only want to delete the data but not drop the tables,['sql'] +13923,how to serialize classes that were not designed to be serialized i need to save some classes and data structures to a file my first reflex was to use xml or binary serialization but this is turning into a nightmare i have a set of classes that were not meant to be serialize private setters no parameterless constructors no serialization attribute dictionaries etc considering that i cannot change those classes what should i do is there any workaround this and still use serializationam i going to have to write all the code to write the properties collections etc,['c#'] +13928,stripping html tags in java is there an existing java library which provides a method to strip all html tags from a string i am looking for something equivalent to the strip tags function in php i know that i can use a regex as described in this stackoverflow question however i was curious if there may already be a striptags method floating around somewhere in the apache commons library that can be used,"['java', 'html']" +13930,modern c game programming examples to what extent are modern c features likepolymorphism stl exception safetyhandling templates with policybased class design smart pointersnewdelete placement newdeleteused in game studios i would be interested to know the names of libraries and the c features they use for example orge3d uses all modern c features including exceptions and smart pointers in other words if i would be looking for an example for a game library using modern c i would go to orge3d but i do not know if these features deter game studios from using orge3d further i do not know if there are other examples for example i used box2d some time before briefly but it uses only placement new and class keyword as the c features even encapsulation is broken in these classes as all members are public ideally if c features would be the best match for all situations these would be used most often but it seems not what are the impedances the obvious one is having to read stacks of books but that is half a reason only this question is a follow up on c for game programming love or thistrust from the responses there i got an impression that many c features are still not used in games which is not necessarily the way it should be,['c++'] +13931,how to scroll the window using jquery scrollto function i am trying to scroll down 100px every time the user gets near the top of the documenti have the function executing when the user gets close to the top of the document but the scrollto function is not workingi put an alert after and before to check to see if it actually was the line or not that was stopping it and only the first alert goes off heres the codealertstartingscrollto top 100px left 0px 800alertfinishedi know i have the jquery page linked properly because i am using many other jquery functions throughout and they all work fine i have also tried removing the px from above and it does not seem to make a difference,"['javascript', 'jquery']" +13933,programmatically lock and unlock iphone screen how do i programmatically lock and unlock the main screen ie the device itself of an iphone,['iphone'] +13934,why do i get a platform not supported exception while adding new response header why do i get a platform not supported exception while adding a new response header i am debugging a website using visual studio web serverresponseheadersxxrdslocation urlexception messagethis operation requires iis integrated pipeline modeany help would be appreciated,['asp.net'] +13946,gridview row editing dynamic binding to a dropdownlist i am trying to get an aspnet 35 gridview to show a selected value as string when being thisplayed and to show a dropdownlist to allow me to pick a value from a given list of options when being edited seems simple enoughmy gridview looks like this simplifiedaspgridview idgrvsecondarylocations runatserver datakeynamesid oninitgrvsecondarylocations init onrowcommandgrvsecondarylocations rowcommand onrowcancelingeditgrvsecondarylocations rowcancelingedit onrowdeletinggrvsecondarylocations rowdeleting onroweditinggrvsecondarylocations rowediting onrowupdatinggrvsecondarylocations rowupdating columns asptemplatefield itemtemplate asplabel idlblpbxtypecaption runatserver text evalpbxtypecaptionvalue itemtemplate edititemtemplate aspdropdownlist idlpbxtypens runatserver width200px datatextfieldcaptionvalue datavaluefieldoid edititemtemplate asptemplatefieldaspgridviewthe grid gets thisplayed ok when not in editing mode the selected pbx type shows its value in the asplabel control no surprise therei load the list of values for the dropdownlist into a local member called pbxtypes in the onload event of the form i verified this it works the values are therenow my challenge is when the grid goes into editing mode for a particular row i need to bind the list of pbxs stored in pbxtypes simple enough i thought just grab the drop down list object in the rowediting event and attach the listprotected void grvsecondarylocations roweditingobject sender gridviewediteventargs e grvsecondarylocationseditindex eneweditindex gridviewrow editingrow grvsecondarylocationsrowseneweditindex dropdownlist ddlpbx editingrowfindcontrolddlpbxtypens as dropdownlist if ddlpbx null ddlpbxdatasource pbxtypes ddlpbxdatabind more stufftrouble is i never get anything back from the findcontrol call seems like the ddlpbxtypens does not exist or cannot be foundwhat am i missing must be something really stupid but so far all my googling reading up on gridview controls and asking buddies has not helpedwho can spot the missing link,['asp.net'] +13947,php pdobindparam data types how does it work i am wondering what the declaration of the data type in the bind parameter or value is used fori mean i thought that if i define a param like int pdoparam int the param must be converted to an int something likedeletebindparam1 kill pdoparam intshould works likedeletebindparam1 intkillor at least throw an error if the param is not the type declared but it is not sogoogling around i found that in the phpnet archivehi alli am currently working on pdo exactly on the bindparam function the third parameter data type seems to be here to force the type of the value but when i try sql insert into produit idproduit nom marque values null nom marquestmt dbhpreparesqlnom testarossa marque ferrari stmtbindvaluemarquemarque stmtbindparamnomnompdoparam int stmtexecute nom 250 gto stmtexecute i was expecting to have either a php error or an interger in my database but in my db i have 22 testarossa ferrari 23 250 gto ferrariit mean that it did not change if i have the third parameter or not or perhaps i miss something can someone tole me more or just can someone told me where i can find information about itregardscyrussthat is exactly my situationwhere are my thoughts going wrong,['php'] +13950,in net is it possible to use responsewrite in a class that does not inherit from systemwebuipage just been asked this question as a true false in a telephone job interview and was a little stumped any ideas,"['c#', '.net']" +13954,js object to json string how can i convert a javascript object to a json string in a javascript function i need the json string to pass to a jsp page,['javascript'] +13956,java stringreplaceall regex what is the regex to strip the mycorp part of na inputed string like mycorpmyname with the java stringreplaceall method so i can get only the myname parti triedpublic static string stripdomainstring userwithdomain return userwithdomainreplaceall but i got unexpected internal error near index 4,['java'] +13959,finding out which locks that are acquired in a query on sql server i have a sql statement from my application i would like to know which locks that statement acquires how can i do that with sql serverthe statement has been involved in a deadlock which i am trying to analyze i cannot reproduce the deadlocki am running on ms sql server 2005,['sql'] +13964,how to do fuzzy string search without a heavy database i have a mapping of catalog numbers to product names35 cozy comforter35 warm blanket67 pillowand need a search that would find misspelled mixed names like warm cmfrterwe have code using editthistance difflib but it probably would not scale to the 180 namesi achieved something similar with lucene but as pylucene only wraps java that would complicate deployment to enduserssqlite does not usually have fulltext or scoring compiled inthe xapian bindings are like c and have some learning curvewhoosh is not yet welldocumented but includes an abusable spellcheckerwhat else is there,['python'] +13977,winforms suspendlayoutresumelayout is not enough i have a library of a few custom controls essentially we have our own buttons rounder corner panels and a few groupboxes with some custom paint despite the math in the onpaint methods the controls are pretty standard most of the time all we do is draw the rounded corners and add gradient to the background we use gdi for all thatthese controls are ok and very nice looking according to our customers however and despite the doublebuffer you can see some redrawing especially when there are 20 buttons for example on the same form on form load you see the buttons drawinga which is annoying i am pretty sure that our buttons are not the fastest thing on earth but my question is if double buffer is on should not all that redraw happen in background and the windows subsystem should show the results instantly on the other hand if there is complex foreach loop that will create labels add them to a panel double buffered and change their properties if we suspendlayout of the panel before the loop and resume layout of the panel when the loop is over should not all these controls labels and buttons appear almost instantly this does not happen like that you can see the panel being filledany idea why this is not happening i know it is hard to evaluate without sample code but that is hard to replicate too i could make a video with a camera but trust me on this one it is not fast,['c#'] +13982,views and fluent nhibernate it is possible to map a view using fluent nhibernate if so how,"['c#', 'sql']" +13989,how to do sql like in linq i have a procedure in sql that i am trying to turn into linqselect oid oname as organizationfrom organizations ojoin organizationshierarchy oh on oidohorganizationsidwhere ohhierarchy like 12the line i am most concerned with iswhere ohhierarchy like 12i have a column that stores the hierarchy like 1312 for example so i just use 12 to search for itmy question is what is the linq or net equivalent to using the percent sign,['.net'] +13993,java on linux listening to broadcast messages on a bound local address i have a somewhat weird requirement to be able to listen to a number of network interfaces from java on a linux machine and determine if one of them receives udp packets of a certain type the output data which i need is the ip address of the interface in question is there any way to do this in java listening on the wildcard address new datagramsocketport does not help because while i do get the broadcast packets i cannot determine the local ip address of the interface they came through listening to broadcasts while being bound to a certain interface new datagramsocketport address does not receive the packets at all this case deserves a code example which shows what i am trying to doenumeration interfaces networkinterfacegetnetworkinterfaceswhile interfaceshasmoreelements networkinterface ni networkinterface interfacesnextelement enumeration addresses nigetinetaddresses while addresseshasmoreelements inetaddress address inetaddressaddressesnextelement if addressisloopbackaddress address instanceof inet6address continue not interested in loopback or ipv6 this time thanks datagramsocket socket new datagramsocketport address try to read the broadcast messages from socket here i also tried to to initialize the socket with the broadcast address constructed based on the beginning of the real ip of the interface and the rest according to the correct netmask byte mask byte255 0 0 0 byte addrbytes inetaddressgetbyname126567getaddressfor int i0 i 4 i addrbytesi byte0xff maskiinetaddress bcastaddr inetaddressgetbyaddressaddrbytesthat just throws a bindexception when constructing the datagramsocketedit bindexception javanetbindexception cannot assign requested address from calling datagramsockets constructor with a broadcastaddress eg 126255255255 only comes with the latest ubuntu 904 probably not ubuntu but kernelversion specific issue though with ubuntu 810 this worked as well as with the red hat release rhel 4x i am dealing withapparently not receiving the packets while bound to a certain local ip is the correct behaviour although in windows this works i need to get it working on linux rhel and ubuntu with lowlevel ccode there is a workaround setsockoptso bindtodevice which i cannot find in the javaapis this does not exactly make me burst with optimism though,['java'] +13996,is there any way to get the me card from iphone address book api so i am stumped on this one in mac os x there is an easy way to get the me card the owner of the macaccount from the builtin address book api has anyone found a way to find out which contact if it exists belongs to the owner of the iphone,"['iphone', 'objective-c']" +14039,java exception vs c exceptions where are exceptions stored stack heap how is memory allocated and deallocated for exceptionsnow if you have more than one exception which needs to be handled are there objects of all these exceptions created,"['java', 'c++']" +14040,bus error vs segmentation fault difference between a bus error and a segmentation faultcan it happen that a program gives a seg fault and stops for the first time and for the second time it may give a bus error and exit,['c'] +14041,how to read list separator from os in java i am writing a csv exporter in java that should respect the users custom settings especially the list separator to use as a delimiterin windows one can set this list separator incontrol panel regional and language options regional options customizei do not know about the other operating systems but i am pretty sure that you can change that on other oses toowhat is the best way to get this custom setting from the os into java i am in an eclipse rcp environment so i might use rcprelated solutions if there is something available,['java'] +14042,what are the steps followed by sql engine to execute the query my question is not how to use inner join in sql i know about how it matches between table a and table b i would like to ask how is the internal working of inner working what algorithm it involves what happens internally when joining multiple tables,['sql'] +14047,how to select first row of the first table in an html page using jquery suppose if i have multiple tables in my html page without their id attribute so how can i select first row of the first table or any specific table using jquery selectors,['jquery'] +14048,jpa or hibernate for java persistence i am researching the development of enterprise applications in java net and groovy for each platform were going to try how hard it is to realize a simple soap web service well use the tools and libraries that are most commonly used to research the real world as accurately as possiblein this regard when using hibernate for persistence would it better reflect the real world to use the new jpa java persistence api or the hibernate custom api that existed before jpa came around,['java'] +14059,how can i get a future without using executorservice i would really like to do something like this callablemyobject mycallable futuremyobject new thread mycallablestarti basically want to start a single longrunning task that runs in parallel with my main task and i do not want pooling or thread reuse the executors stuff seems to be very pooling oriented and it requires me to shut down the pool all of which i do not want to doi want to use the callablefuture pattern because i may later have to introduce executors but as things currently stand they are just overheadany suggestions,['java'] +14071,timespan formatting possible duplicatehow can i stringformat a timespan object with a custom format in net how do you elegantly format a timespan to say example 1 hour 10 minutes when you have declared it as timespan t new timespan0 70 0i am of course aware that you could do some simple maths for this but i was kinda hoping that there is something in net to handle this for me for more complicated scenariosduplicate of how can i stringformat a timespan object with a custom format in net,"['c#', '.net']" +14072,linq and the equality operator expression of type systemint32 cannot be used for parameter of type systemobject i am trying to override the equality operator in c to handle comparing any type to a custom type the custom type is really a wrapperbox around nullso i have thisinternal sealed class nothingpublic override bool equalsobject objif obj null obj is nothingreturn trueelsereturn falsepublic static bool operator object x nothing yif x null x is nothing y null y is nothingreturn truereturn false now if i make a call likenothing and new nothingbool equal 10 nit works perfectly fine however if i try to do this same thing through a linq expression trexp expressionequal expressionconstant10 expressionconstantnew nothing typeofnothingit throws the exceptionsystemargumentexception expression of type systemint32 cannot be used for parameter of type systemobject of method boolean op equalitysystemobject partsfinderrulesruntimerulesnothing at systemlinqexpressionsexpressionvalidateargumenttypesmethodinfo method readonlycollection1 arguments at systemlinqexpressionsexpressionvalidatecallargsexpression instance methodinfo method readonlycollection1 arguments at systemlinqexpressionsexpressioncallexpression instance methodinfo method ienumerable1 arguments at systemlinqexpressionsexpressioncallexpression instance methodinfo method expression arguments at systemlinqexpressionsexpressioncompilergeneratebinarymethodilgenerator gen binaryexpression b stacktype askany ideas on why the base system can convert int32 to object but linq cannot or how i can fix thisthis whole thing stared because linq also cannot compare int32 to object in the first placeexp expressionequal expressionconstant10 expressionconstantnullthrows an exception stating that there is no comparison operator for systemint32 and systemobjectquick followupthe following do work without issueexp expressionequal expressionconstant10 typeofobject expressionconstantnew nothing typeofnothingexp expressionequal expressionconstant10 typeofobject expressionconstantnullso specifically casting everything to object so does linq just not handle inheritance internally thats pretty annoyingfollowup 2i also tried using a custom comparison methodexp expressionequal expressionconstant10 expressionconstantnull false thisgettypegetmethodvalueequals bindingflagspublic bindingflagsstaticpublic static bool valueequalsobject x object yif x null y nullreturn trueif xgettype ygettypereturn falsereturn x ythis too throws an exceptionsysteminvalidoperationexception the operands for operator equal do not match the parameters of method valueequals at systemlinqexpressionsexpressiongetmethodbasedbinaryoperatorexpressiontype binarytype expression left expression right methodinfo method boolean lifttonullbut again casting everything directly to object worksexp expressionequal expressionconstant10 typeofobject expressionconstantnull typeofobject false thisgettypegetmethodvalueequals bindingflagspublic bindingflagsstaticso i guess i have my workaround cast everything to object and use a custom comparison method i am still surprised linq does not do the conversion automatically as normal c does,"['c#', '.net']" +14074,changing the current working directory in java how can i change the current working directory from within a java program everything i have been able to find about the issue claims that you simply cannot do it but i cannot believe that that is really the casei have a piece of code that opens a file using a hardcoded relative file path from the directory it is normally started in and i just want to be able to use that code from within a different java program without having to start it from within a particular directory it seems like you should just be able to call systemsetproperty userdir pathtodir but as far as i can figure out calling that line just silently fails and does nothingi would understand if java did not allow you to do this if it werent for the fact that it allows you to get the current working directory and even allows you to open files using relative file paths,['java'] +14081,matrix library for net i am looking for a good welltested fullyfeatured and ideally with a nice interface matrix library for netc my main requirements here are only that it should be free i do not particularly care whether it is opensource in this case and preferably support sparse matrix operations the obligatory requirements are all the basic operations eg multiplication transposition inversion as well as finding eigenvalues eigenvectors implementation of a numerical rather thanas well as analytical methods for thiscovery of eigenvalues particularly the lanczos algorithm for sparse matrices would be highly preferable since the matrices i am going to be dealing with are very large lengths of 10 upwards as well as square and also reasonably sparse saying that i could be asking for a bit much there so any suggestions for a reasonably complete matrix library would be greatnow i am aware that python has one or two useful libraries for such tasks namely numpyscipy but net unfortunately seems to be lacking in the areaa bit of searching turned up the following libraries for net which i could potentially usedlutz roeders mapackdotnetmatrix codeprojectc matrix library codeprojecthowever since i have had no experience whatsoever using any of these libraries or others and not exactly enough time to check each of them out properly in any case i would very much appreciate if anyone here could thiscuss their recommendations regarding the various libraries their proscons particularly with regards to suitability for my uses and their general experiences with themresorting to matlab is always an option but not a preferred one as it would be much more convenient if i could integrate the matrix math directly with my program,['.net'] +14089,factory pattern enums or types when implementing a factory or simple factory what would go against using a type instead of an enum to specify the class to instantiatefor examplepublic class simplefactory public static itest createtype type if type typeofconcretetest1 return new concretetest1 if type typeofconcretetest2 return new concretetest2 throw new exceptioninvalid type,['c#'] +14095,what does it mean when virtual is in class foo public virtual bar as opposed to virtual void frob what does it mean when virtual is in class foo public virtual bar as opposed to virtual void frobfor a given method there are 8 cases stemming from the presence or absence of virtual in the following three locationsa superclas functionsthe inheritance chain for this classthis classes functionsi think i understand how numbers 1 and 3 interact but number 2 seems redundant is it what am i not understanding,['c++'] +14107,php exceptions vs errors maybe i am missing it somewhere in the php manual but what exactly is the difference between an error and an exception the only difference that i can see is that errors and exceptions are handled differently but what causes an exception and what causes an error,['php'] +14132,static constants in c i have this codeusing systemnamespace rapido class constants public static const string frameworkname rapido framework visual studio tells me the constant rapidoconstantsframeworkname cannot be marked statichow can i make this constant available from other classes without having to create a new instance of it ie directly accessing it via rapidoconstantsframeworkname,['c#'] +14133,convert string to cllocationcoordinate2d i have an array with nsstrings in it some of these are latitude and longitudes and i need to use this with the below codethe lattext and lontext are my strings that i am trying to use as coordinates cllocationcoordinate2d pinlocationmapviewuserlocationcoordinatepinlocationlatitude lattextpinlocationlongitude lontext,['iphone'] +14145,webkit or gecko which one is better for embedding in c app which one would you choose and whyi would like to hear opinions from people having experience with embedding a web browser engine in c applicationi should stress i need all features of web browser engine except rendering ie http client cookie handling dom style http parser javascript engine how can one strip either webkit or gecko of rendering code to avoid coding and runtime overheadthis is a follow up to what embedded browser for c project,['c++'] +14148,writing a init function to be used in django model i am trying to write an init function for one of my models so that i can create an object by doingp usernameemailwhen i write the model i have def init self name email house id password modelsmodel init self selfname name selfemail emailthis works and i can save the object to the database but when i do userobjectsall it does not pull anything up unless i take out my init function any ideas,['python'] +14151,how to replace dom element in place using javascript i am looking to replace an element in the dom for example there is an a element that i want to replace with a span insteadhow would i go and do that,['javascript'] +14154,fastest way to test internet connection c 2008 sp1i am using this code to connect to our client website this is for a softphone application before the user makes a call the softphone has to test if there is an active internet connection so want i have done is used the httpwebrequest class to connect to our clients website if the response is ok then the internet connection can proceed however i have noticed that the response is taking too long to respond i am not sure if this is not a very efficient way to test however when i browse to their website it takes less than a second to load the page but takes too long when i use the httpwebrequest claso requirements for this aresometime a proxy will be used at the clients office to i cannot use the tcpclient class does not have a proxy propertythe proxy does not support socks so cannot use the sockets classi need to use a timeout property so cannot use the webclient class this is because the softphone would freeze until a response is returned so timeout after a few secondsso the only one i can think of is the httpwebrequest class httpwebrequest request httpwebrequestwebrequestcreate requesttimeout 50 requestcredentials credentialcachedefaultnetworkcredentials httpwebresponse response httpwebresponserequestgetresponse if responsestatuscode httpstatuscodeok consolewritelineissipserveravailable responsestatuscode isavailable true edit using pinvoke dllimportwininetdll charset charsetauto private extern static bool internetgetconnectedstateref internetconnectionstate e lpdwflags int dwreserved flags enum internetconnectionstate e int internet connection modem 0x1 internet connection lan 0x2 internet connection proxy 0x4 internet ras installed 0x10 internet connection offline 0x20 internet connection configured 0x40 in function for checking internet internetconnectionstate e flags 0 bool isconnected internetgetconnectedstateref flags 0,['c#'] +14155,iphone uiwebview local resources using javascript and handling onorientationchange i am trying to server html javascript and css content from an iphone applications local resources and i am having trouble handling onorientationchange events and including external javascripti seem to be able to link in css properly but not javascript i am trying to use the following example of handling onorientationchange how to build an iphone website but i am serving the webpage from my apps nsbundle mainbundlei tried attaching a javascript function to bodyonorientationchange and to windowonorientationchange but neither work when served from uiwebview locally or remotely but it works if i am using the iphone safaridoctype html public w3cdtd xhtml 10 transitionalen html xmlnshead meta httpequivcontenttype contenttexthtml charsetutf8 titlehow to build an iphone websitetitle meta nameauthor contentwill meta namecopyright contentcopyright 2008 wengageinteractivecouk meta namedescription contentwelcome to engege interactive on the iphone meta nameviewport contentwidthdevicewidth initialscale10 maximumscale10 link relappletouchicon hrefimagestemplateengagepng style typetextcss import urliphonecss style script typetextjavascript srcorientationjsscript script typetextjavascriptfunction updateorientation try var contenttype show normal switchwindoworientation case 0 contenttype show normal break case 90 contenttype show right break case 90 contenttype show left break case 180 contenttype show flipped break documentgetelementbyidpage wrappersetattributeclass contenttype alertorientation contenttype catche alerterror emessage windowonload function initialload try loaded updateorientation catche alerterror emessage function loaded documentgetelementbyidpage wrapperstylevisibility visible scriptheadbody onorientationchangeupdateorientation div idpage wrapper h1engage interactiveh1 div idcontent left pyou are now holding your phone to the leftp div div idcontent right pyou are now holding your phone to the rightp div div idcontent normal pyou are now holding your phone uprightp div div idcontent flipped pthis does not work yet but there is a chance apple will enable it at some point so i have put it in anyway you would be holding your phone upside down if it did workp div divbodyhtml,['iphone'] +14159,sending messages to a flash game with c and autoit i am making a bot for a flash game and i have figured out how to import all the autoit functions into my c codestring title minesweeperstring full autowingettitletitlestring handle autowingethandlefull if autowinexistsfull 1 textbox1text window existsaddressboxtext fullfor int r 1 r 40 r autocontrolclickfull left 2 r 10 r 10 autocontrolclickhandle left 2 r 10 r 10i am pretty sure the uncommented one should be the one with handle and vice versa but this works for minesweeperso it works for minesweeper and does not require it to be the active window when i try to make it work on my flash game it requires the internet explorer window to be the active one is this something flash requires or is there something additional that i could do to make it work when the game is minimizedthis does not have to be done using the autoit imports i tried sendmessage from user32 at one point also but that did not work for flash content at all for mei just tested this on a random website instead of a flash site or minesweeper and for some reason the code works if i execute it from within the autoit scripting program but not from my c programjune 20th 2012 i am pretty sure this has something to do with the way the handle gets passed i have done some tests with calling an autoit exe file and using the handle i get from the c code as an argument i have to add an 0x to it and also then within the autoit code i have to cast it from a string to an hwnd so that could be something in which case i do not know what to do since the imported function relies on a string input for the handle,['c#'] +14164,whats better isset or not is there any speed difference betweenif isset postvarorif postvarand which is better or are they the same,['php'] +14170,make background of uiview a gradient without sub classing is there a way to make the background of a uiview a gradient without subclassing it i would rather not use an image file to accomplish this either it just seems obtuse to have to subclass uiview just to draw a gradient for the background,['iphone'] +14172,strange collection was modified after the enumerator was instantiated exception perhaps someone can point me in the correct direction because i am completely stumped on thisi have a function that simply prints out a linkedlist of classes linkedlistcomponent components new linkedlistcomponent private void printcomponentlist consolewritelinecomponent list componentscount entries foreach component c in components consolewritelinec consolewriteline the component object actually has a custom tostring call as such int id public override string tostring return gettype id this function typically works fine however i have run into the issue that when it builds to about 30 or so entries in the list the printcomplentlist foreach statement comes back with an invalidoperationexception collection was modified after the enumerator was instantiatednow as you can see i am not modifying the code within the for loop and i have not explicitly created any threads although this is within an xna environment if it matters it should be noted that the printout is frequent enough that the console output is slowing down the program as a wholei am completely stumped has anyone else out there run into this,['c#'] +14175,is there a better way to get clientids into external js files i know this has been asked before but i have found a different way to get references to controls in external js files but i am not sure how this would go down in terms of overall speedmy code ispublic static void generateclientidspage page params webcontrol controls stringbuilder script new stringbuilder scriptappendlinescript typetextjavascript foreach webcontrol c in controls scriptappendlinestringformatvar 0 1 cid cclientid scriptappendlinescript if pageclientscriptisclientscriptblockregisteredvars pageclientscriptregisterclientscriptblockpagegettype vars scripttostring this was i can reference the id of the aspx page in my js filescan anyone see any drawbacks to doing things this way i have only started using external js files before everything was written into the usercontrol itself,"['asp.net', 'javascript']" +14176,is there a convenient function in objectivec cocoatouch to find a lowest number i have two numbers and need to get returned the lower one is there any function i could use sure it is a easy task i could do an ifstatement i just want to know,['objective-c'] +14181,emulating passbyvalue behaviour in python i would like to emulate the passbyvalue behaviour in python in other words i would like to make absolutely sure that the function i write do not modify user supplied data one possible way is to use deep copyfrom copy import deepcopydef fdata data deepcopydata do stuffis there more efficient or more pythonic way to achieve this goal making as few assumptions as possible about the object being passed such as clone methodedit i am aware that technically everything in python is passed by value i was interested in emulating the behaviour ie making sure i do not mess with the data that was passed to the function i guess the most general way is to clone the object in question either with its own clone mechanism or with deepcopy,['python'] +14182,get the last modified date of a remote file i would like to get the last modified date of a remote file by means of curl does anyone know how to do that,"['php', 'jquery']" +14183,java negative int to hex and back fails public class main3 public static void mainstring args integer min integermin value string minhex integertohexstringintegermin value systemoutprintlnmin minhex systemoutprintlnintegerparseintminhex 16 gives 2147483648 80exception in thread main javalangnumberformatexception for input string 80 at javalangnumberformatexceptionforinputstringnumberformatexceptionjava48 at javalangintegerparseintintegerjava459 at main3mainmain3java7whats up,['java'] +14188,javascript to get paragraph of selected text in web page after highlighting text i would like to obtain the paragraph in which the selected text residesvar select window contentdocumentgetselectionany pointers please,['javascript'] +14195,is there a function that returns the ascii value of a character c i need a function that returns the ascii value of a character including spaces tabs newlines etcon a similar note what is the function that converts between hexadecimal decimal and binary numbers,['c++'] +14201,how to access the forms name variable from php i am trying to create a bmi calculator this should allow people to use either metric or imperial measurementsi realise that i could use hidden tags to solve my problem but this has bugged me before so i thought i would ask i can use postvariablename to find the submitted variablename fieldvalue buti do not know or see how to verify which form was used to submit the variablesmy codes below though i am not sure it is strictly relevant to the questionphp bmisubmitted postbmisubmitted if issetbmisubmitted height postheight weight postweight bmi floorweightheightheight ul idbmi liweight in kilograms is spanphp echo weight spanli liheight in metres is spanphp echo height spanli libody mass index bmi is spanphp echo bmi spanli ul php else div idformselector ul lia hrefmetricmetricali lia hrefimperialimperialali ul form namemet idmetric actionphp echo serverphp self methodpost enctypeformmultipart fieldset label forweightweight abbr titlekilogramskgabbrlabel input typetext nameweight idweight label forheightheight abbr titlemetresmabbrlabel input typetext nameheight idheight input typehidden namebmisubmitted idbmisubmitted value1 fieldset fieldset input typereset idreset valueclear input typesubmit idsubmit valuesubmit fieldset form form nameimp idimperial actionphp echo serverphp self methodpost enctypeformmultipart fieldset label forweightweight abbr titlepoundslbsabbrlabel input typetext nameweight idweight label forheightheight incheslabel input typetext nameheight idheight input typehidden namebmisubmitted idbmisubmitted value1 fieldset fieldset input typereset idreset valueclear input typesubmit idsubmit valuesubmit fieldset form php i verified that it worked though without validation at the moment i did not want to crowd my question too much with metric i have added the form but not the processing for the imperial yetthanks for any help and if it is ridiculously easy i will flagellate myself as requiredcheers,['php'] +14220,read unicode characters from commandline arguments in python 2x on windows i want my python script to be able to read unicode command line arguments in windows but it appears that sysargv is a string encoded in some local encoding rather than unicode how can i read the command line in full unicodeexample code argvpyimport sysfirst arg sysargv1print first argprint typefirst argprint first argencodehexprint openfirst argon my pc set up for japanese code page i getctempargvpy pcaa12aac3e 080924docpcaa12aac3e 080924doctype str50438145835c83748367905c90bf8f9130382e30392e32342e646f63open file pcaa12aac3e 080924doc mode r at 0x00917d90that is shiftjis encoded i believe and it works for that filename but it breaks for filenames with characters that are not in the shiftjis character setathe final open call failsctempargvpy jargentxtjorgentxttype str4a6f7267656e2e747874traceback most recent call last file ctempargvpy line 7in module print openfirst argioerror errno 2 no such file or directory jorgentxtnoteai am talking about python 2x not python 30 i have found that python 30 gives sysargv as proper unicode but it is a bit early yet to transition to python 30 due to lack of 3rd party library supportupdatea few answers have said i should decode according to whatever the sysargv is encoded in the problem with that is that it is not full unicode so some characters are not representableheres the use case that gives me grief i have enabled draganddrop of files onto py files in windows explorer i have file names with all sorts of characters including some not in the system default code page my python script does not get the right unicode filenames passed to it via sysargv in all cases when the characters are not representable in the current code page encodingthere is certainly some windows api to read the command line with full unicode and python 30 does it i assume the python 2x interpreter is not using it,['python'] +14222,is twisted an httplib2socket replacement many python libraries even recently written ones use httplib2 or the socket interface to perform networking tasksthose are obviously easier to code on than twisted due to their blocking nature but i think this is a drawback when integrating them with other code especially gui one if you want scalability concurrency or gui integration while avoiding multithreading twisted is then a natural choiceso i would be interested in opinions in those mattersshould new networking code with the exception of small command line tools be written with twistedwould you mix twisted http2lib or socket code in the same projectis twisted pythonic for most libraries it is more complex than alternatives introduce a dependency to a nonstandard packageedit please let me phrase this in another way do you feel writing new library code with twisted may add a barrier to its adoption twisted has obvious benefits especially portability and scalability as stated by gimel but the fact that it is not a core python library may be considered by some as a drawback,['python'] +14243,crossplatform way of getting temp directory in python is there a crossplatform way of getting the path to the temp directory in python 26 for example under linux that would be tmp while under xp cdocuments and settingsuserapplication settingstempthanks,['python'] +14265,cols colgroups and css hover psuedoclass i am trying to create a table to thisplay an individuals bmias part of this i would like on hover for the tr and col or colgroup to be highlighted also in order for the intersection to be more apparentas the table will feature both metric and imperial measurements the hover does not have to stop at the cell from any direction and would in fact be a bonus if it extended from one axis to the other i am also using the xhtml 11 strict doctype if this makes a differencesoan example the real tableslarger but this should be representativescripttrhover backgroundcolor ffa colgrouphovercolhover backgroundcolor ffa scripttable col classweightcolcolgroup span3col classbmicolcolgroup tr thth th50kgth th55kgth th60kgth tr tr td160cmtd td20td td21td td23td tr tr td165cmtd td18td td20td td22td tr tr td170cmtd td17td td19td td21td trtableam i asking the impossible do i need to go jquerywards,['css'] +14267,how do i get the coordinate position after using jquery drag and drop how do i get the coordinate position after using jquery drag and drop i want to save the coordinate to a database so that next time i visit the item will be in that position for example x 520px y 300pxediti am php and mysql programmer is there any tutorial out there,['jquery'] +14269,is mod rails or phusion passenger finally the answer to ruby on rails deployment i read from some books that phusion passenger is the answer to easy ruby on rails deployment but my friend said that first there was apache bunch of mongrels and then lighttpd and then nginx and now passenger and it seems endlesshe also said he uses dreamhost which uses passenger and sometimes he sees his request not being processedso i wonder if passenger is the final answer to ror deployment do you use it and used the ab command to test if the site is doing quite well,"['ruby-on-rails', 'ruby']" +14270,how do i cast from systemwebhttppostedfilebase to systemwebhttppostedfile while trying to implement an mvc file upload example on scott hanselmans blog i ran into trouble with this example codeforeach string file in requestfiles httppostedfile hpf requestfilesfile as httppostedfile if hpfcontentlength 0 continue string savedfilename pathcombine appdomaincurrentdomainbasedirectory pathgetfilenamehpffilename hpfsaveassavedfilenamei converted it to vbnetfor each file as string in requestfiles dim hpf as httppostedfile trycastrequestfilesfile httppostedfile if hpfcontentlength 0 then continue for end if dim savedfilename as string pathcombineappdomaincurrentdomainbasedirectory pathgetfilenamehpffilename hpfsaveassavedfilenamenextbut i am getting an invalid cast exception from the compilervalue of type systemwebhttppostedfilebase cannot be converted to systemwebhttppostedfilehanselman posted his example on 20080627 and i assume it worked at the time msdn does not have any similar examples so what gives,['asp.net'] +14279,how to stop the gem utility from accessing my home directory when i run gem install somegemcommand the gem utility tries to access my home directory it contains some nonlatin characters and installation fails because of that for example erubybingem install somegemerror while executing gem errnoenoent no such file or directory cdocuments and settingsuserif i switch to another user account with a username containing ascii characters only gem works finedoes anybody know how to tell gem not to check my home directoryupdate i tried to set up gem home as suggested below but it did not help still checks the user home directory,['ruby'] +14280,error in velocity and log4j i built a webapp that works perfectly fine in my localhost tomcat but when i tried to deploy velocity crashes in init leaving me with this strange stack trace here sorry for the sizeerror main velocityconfiguratorjava62 error initializing velocityorgapachevelocityexceptionvelocityexception failed to initialize an instance of orgapachevelocityruntimeloglog4jlogchute with the current runtime configuration at orgapachevelocityruntimeloglogmanagercreatelogchutelogmanagerjava206 at orgapachevelocityruntimeloglogmanagerupdateloglogmanagerjava255 at orgapachevelocityruntimeruntimeinstanceinitializelogruntimeinstancejava795 at orgapachevelocityruntimeruntimeinstanceinitruntimeinstancejava250 at orgapachevelocityruntimeruntimeinstanceinitruntimeinstancejava589 at orgapachevelocityruntimeruntimesingletoninitruntimesingletonjava229 at orgapachevelocityappvelocityinitvelocityjava107 at comwebcodeivelociraptorvelocityvelocityconfiguratorinitvelocityvelocityconfiguratorjava57 at comwebcodeivelociraptorvelocityvelocityconfiguratorconfigurevelocityconfiguratorjava42 at comwebcodeivelociraptorvelocilistenercontextinitializedvelocilistenerjava26 at orgapachecatalinacorestandardcontextlistenerstartstandardcontextjava3827 at orgapachecatalinacorestandardcontextstartstandardcontextjava4336 at orgapachecatalinacorecontainerbaseaddchildinternalcontainerbasejava761 at orgapachecatalinacorecontainerbaseaddchildcontainerbasejava741 at orgapachecatalinacorestandardhostaddchildstandardhostjava525 at orgapachecatalinastartuphostconfigdeploydescriptorhostconfigjava626 at orgapachecatalinastartuphostconfigdeploydescriptorshostconfigjava553 at orgapachecatalinastartuphostconfigdeployappshostconfigjava488 at orgapachecatalinastartuphostconfigstarthostconfigjava1138 at orgapachecatalinastartuphostconfiglifecycleeventhostconfigjava311 at orgapachecatalinautillifecyclesupportfirelifecycleeventlifecyclesupportjava120 at orgapachecatalinacorecontainerbasestartcontainerbasejava1023 at orgapachecatalinacorestandardhoststartstandardhostjava719 at orgapachecatalinacorecontainerbasestartcontainerbasejava1015 at orgapachecatalinacorestandardenginestartstandardenginejava443 at orgapachecatalinacorestandardservicestartstandardservicejava448 at orgapachecatalinacorestandardserverstartstandardserverjava710 at orgapachecatalinastartupcatalinastartcatalinajava552 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava39 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava25 at javalangreflectmethodinvokemethodjava597 at orgapachecatalinastartupbootstrapstartbootstrapjava288 at orgapachecatalinastartupbootstrapmainbootstrapjava413caused by javalangruntimeexception error configuring log4jlogchute at sunreflectnativeconstructoraccessorimplnewinstance0native method at sunreflectnativeconstructoraccessorimplnewinstancenativeconstructoraccessorimpljava39 at sunreflectdelegatingconstructoraccessorimplnewinstancedelegatingconstructoraccessorimpljava27 at javalangreflectconstructornewinstanceconstructorjava513 at orgapachevelocityutilexceptionutilscreatewithcauseexceptionutilsjava67 at orgapachevelocityutilexceptionutilscreateruntimeexceptionexceptionutilsjava45 at orgapachevelocityruntimeloglog4jlogchuteinitappenderlog4jlogchutejava133 at orgapachevelocityruntimeloglog4jlogchuteinitlog4jlogchutejava85 at orgapachevelocityruntimeloglogmanagercreatelogchutelogmanagerjava157 33 morecaused by javaiofilenotfoundexception velocitylog permission denied at javaiofileoutputstreamopenappendnative method at javaiofileoutputstreamfileoutputstreamjava177 at javaiofileoutputstreamfileoutputstreamjava102 at orgapachelog4jfileappendersetfilefileappenderjava290 at orgapachelog4jrollingfileappendersetfilerollingfileappenderjava194 at orgapachelog4jfileappenderfileappenderjava109 at orgapachelog4jrollingfileappenderrollingfileappenderjava72 at orgapachevelocityruntimeloglog4jlogchuteinitappenderlog4jlogchutejava118 35 moreerror main velocityconfiguratorjava63 javalangruntimeexception error configuring log4jlogchute orgapachevelocityexceptionvelocityexception failed to initialize an instance of orgapachevelocityruntimeloglog4jlogchute with the current runtime configuration at orgapachevelocityruntimeloglogmanagercreatelogchutelogmanagerjava206 at orgapachevelocityruntimeloglogmanagerupdateloglogmanagerjava255 at orgapachevelocityruntimeruntimeinstanceinitializelogruntimeinstancejava795 at orgapachevelocityruntimeruntimeinstanceinitruntimeinstancejava250 at orgapachevelocityruntimeruntimeinstanceinitruntimeinstancejava589 at orgapachevelocityruntimeruntimesingletoninitruntimesingletonjava229 at orgapachevelocityappvelocityinitvelocityjava107 at comwebcodeivelociraptorvelocityvelocityconfiguratorinitvelocityvelocityconfiguratorjava57 at comwebcodeivelociraptorvelocityvelocityconfiguratorconfigurevelocityconfiguratorjava42 at comwebcodeivelociraptorvelocilistenercontextinitializedvelocilistenerjava26 at orgapachecatalinacorestandardcontextlistenerstartstandardcontextjava3827 at orgapachecatalinacorestandardcontextstartstandardcontextjava4336 at orgapachecatalinacorecontainerbaseaddchildinternalcontainerbasejava761 at orgapachecatalinacorecontainerbaseaddchildcontainerbasejava741 at orgapachecatalinacorestandardhostaddchildstandardhostjava525 at orgapachecatalinastartuphostconfigdeploydescriptorhostconfigjava626 at orgapachecatalinastartuphostconfigdeploydescriptorshostconfigjava553 at orgapachecatalinastartuphostconfigdeployappshostconfigjava488 at orgapachecatalinastartuphostconfigstarthostconfigjava1138 at orgapachecatalinastartuphostconfiglifecycleeventhostconfigjava311 at orgapachecatalinautillifecyclesupportfirelifecycleeventlifecyclesupportjava120 at orgapachecatalinacorecontainerbasestartcontainerbasejava1023 at orgapachecatalinacorestandardhoststartstandardhostjava719 at orgapachecatalinacorecontainerbasestartcontainerbasejava1015 at orgapachecatalinacorestandardenginestartstandardenginejava443 at orgapachecatalinacorestandardservicestartstandardservicejava448 at orgapachecatalinacorestandardserverstartstandardserverjava710 at orgapachecatalinastartupcatalinastartcatalinajava552 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava39 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava25 at javalangreflectmethodinvokemethodjava597 at orgapachecatalinastartupbootstrapstartbootstrapjava288 at orgapachecatalinastartupbootstrapmainbootstrapjava413caused by javalangruntimeexception error configuring log4jlogchute at sunreflectnativeconstructoraccessorimplnewinstance0native method at sunreflectnativeconstructoraccessorimplnewinstancenativeconstructoraccessorimpljava39 at sunreflectdelegatingconstructoraccessorimplnewinstancedelegatingconstructoraccessorimpljava27 at javalangreflectconstructornewinstanceconstructorjava513 at orgapachevelocityutilexceptionutilscreatewithcauseexceptionutilsjava67 at orgapachevelocityutilexceptionutilscreateruntimeexceptionexceptionutilsjava45 at orgapachevelocityruntimeloglog4jlogchuteinitappenderlog4jlogchutejava133 at orgapachevelocityruntimeloglog4jlogchuteinitlog4jlogchutejava85 at orgapachevelocityruntimeloglogmanagercreatelogchutelogmanagerjava157 33 morecaused by javaiofilenotfoundexception velocitylog permission denied at javaiofileoutputstreamopenappendnative method at javaiofileoutputstreamfileoutputstreamjava177 at javaiofileoutputstreamfileoutputstreamjava102 at orgapachelog4jfileappendersetfilefileappenderjava290 at orgapachelog4jrollingfileappendersetfilerollingfileappenderjava194 at orgapachelog4jfileappenderfileappenderjava109 at orgapachelog4jrollingfileappenderrollingfileappenderjava72 at orgapachevelocityruntimeloglog4jlogchuteinitappenderlog4jlogchutejava118 35 moreerror main velocityconfiguratorjava64 failed to initialize an instance of orgapachevelocityruntimeloglog4jlogchute with the current runtime configurationorgapachevelocityexceptionvelocityexception failed to initialize an instance of orgapachevelocityruntimeloglog4jlogchute with the current runtime configuration at orgapachevelocityruntimeloglogmanagercreatelogchutelogmanagerjava206 at orgapachevelocityruntimeloglogmanagerupdateloglogmanagerjava255 at orgapachevelocityruntimeruntimeinstanceinitializelogruntimeinstancejava795 at orgapachevelocityruntimeruntimeinstanceinitruntimeinstancejava250 at orgapachevelocityruntimeruntimeinstanceinitruntimeinstancejava589 at orgapachevelocityruntimeruntimesingletoninitruntimesingletonjava229 at orgapachevelocityappvelocityinitvelocityjava107 at comwebcodeivelociraptorvelocityvelocityconfiguratorinitvelocityvelocityconfiguratorjava57 at comwebcodeivelociraptorvelocityvelocityconfiguratorconfigurevelocityconfiguratorjava42 at comwebcodeivelociraptorvelocilistenercontextinitializedvelocilistenerjava26 at orgapachecatalinacorestandardcontextlistenerstartstandardcontextjava3827 at orgapachecatalinacorestandardcontextstartstandardcontextjava4336 at orgapachecatalinacorecontainerbaseaddchildinternalcontainerbasejava761 at orgapachecatalinacorecontainerbaseaddchildcontainerbasejava741 at orgapachecatalinacorestandardhostaddchildstandardhostjava525 at orgapachecatalinastartuphostconfigdeploydescriptorhostconfigjava626 at orgapachecatalinastartuphostconfigdeploydescriptorshostconfigjava553 at orgapachecatalinastartuphostconfigdeployappshostconfigjava488 at orgapachecatalinastartuphostconfigstarthostconfigjava1138 at orgapachecatalinastartuphostconfiglifecycleeventhostconfigjava311 at orgapachecatalinautillifecyclesupportfirelifecycleeventlifecyclesupportjava120 at orgapachecatalinacorecontainerbasestartcontainerbasejava1023 at orgapachecatalinacorestandardhoststartstandardhostjava719 at orgapachecatalinacorecontainerbasestartcontainerbasejava1015 at orgapachecatalinacorestandardenginestartstandardenginejava443 at orgapachecatalinacorestandardservicestartstandardservicejava448 at orgapachecatalinacorestandardserverstartstandardserverjava710 at orgapachecatalinastartupcatalinastartcatalinajava552 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava39 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava25 at javalangreflectmethodinvokemethodjava597 at orgapachecatalinastartupbootstrapstartbootstrapjava288 at orgapachecatalinastartupbootstrapmainbootstrapjava413caused by javalangruntimeexception error configuring log4jlogchute at sunreflectnativeconstructoraccessorimplnewinstance0native method at sunreflectnativeconstructoraccessorimplnewinstancenativeconstructoraccessorimpljava39 at sunreflectdelegatingconstructoraccessorimplnewinstancedelegatingconstructoraccessorimpljava27 at javalangreflectconstructornewinstanceconstructorjava513 at orgapachevelocityutilexceptionutilscreatewithcauseexceptionutilsjava67 at orgapachevelocityutilexceptionutilscreateruntimeexceptionexceptionutilsjava45 at orgapachevelocityruntimeloglog4jlogchuteinitappenderlog4jlogchutejava133 at orgapachevelocityruntimeloglog4jlogchuteinitlog4jlogchutejava85 at orgapachevelocityruntimeloglogmanagercreatelogchutelogmanagerjava157 33 morecaused by javaiofilenotfoundexception velocitylog permission denied at javaiofileoutputstreamopenappendnative method at javaiofileoutputstreamfileoutputstreamjava177 at javaiofileoutputstreamfileoutputstreamjava102 at orgapachelog4jfileappendersetfilefileappenderjava290 at orgapachelog4jrollingfileappendersetfilerollingfileappenderjava194 at orgapachelog4jfileappenderfileappenderjava109 at orgapachelog4jrollingfileappenderrollingfileappenderjava72 at orgapachevelocityruntimeloglog4jlogchuteinitappenderlog4jlogchutejava118 35 moredoes anyone knows the workaround or at least understood the error i have done some googling but no clues only this page facing the same problem but no solution,['java'] +14291,javascript override or prevent execution i am working on a client project and i have to include their header and footer which includes some core javascript files i have a couple of pngs on the page but their core js file is poorly coded and does not check for ie 7 before attempting to replace img tags that contain png files with divs that use the alphaimageloader filter the result is that in ie 7 all my png images are replaced with div tags that have a default thisplay block causing a linebreak after every single png image in my pageswhat i would like to do is override their function with a better one or somehow prevent theirs from executing but i cannot modify the js file itself which both defines the function and attaches it to the window onload event i have tried redefining the function under the same name in several places header just before the body tag in documentready etc but the original function always seems to execute presumably because the original function code is what is stored with the event handler and not merely a pointer to the functionany way i can fix is there a way to selectively remove onload event handlers,"['javascript', 'jquery']" +14299,maven s3 wagon provider how to deploy with wagon s3 provideri have found several plugins most of them are incomplete some of them are not maintaned there is also a sandbox plugin from official maven svn repository but i am figuring how to use it any hint,['java'] +14300,whats an efficient way to concatenate all strings in an array separating with a space let us say i have an array of stringsstring mystrings new string first second third i want to concatenate them so the output isfirst second thirdi know i can concatenate them like this but therell be no space in betweenstring output stringconcatmystringstoarrayi can obviously do this in a loop but i was hoping for a better wayis there a more succinct way to do what i want,['c#'] +14302,python py pyo pyc which can be eliminated for an embedded system to squeeze into the limited amount of filesystem storage available in an embedded system i am currently playing with i would like to eliminate any files that could reasonably be removed without significantly impacting functionality or performance the py pyo and pyc files in the python library account for a sizable amount of space i am wondering which of these options would be most reasonable for a python 26 installation in a small embedded systemkeep py eliminate pyc and pyo maintain ability to debug performance sufferskeep py and pyc eliminate pyo does optimization really buy anythingkeep pyc eliminate pyo and py will this workkeep py pyc and pyo all are needed,['python'] +14303,reliable method to get machines mac address in c i need a way to get a machines mac address regardless of the os it is running using c application will need to work on xpvistawin7 32 and 64 bit as well as on those oss but with a foreign language default many of the c commands and os queries do not work across os any ideas i have been scraping the output of ipconfig all but this is terribly unreliable as the output format differs on every machinethanks,['c#'] +14307,what is this new axum programming language i read this story on slashdot today where they announce a new parallel programming language by microsoftwhat is this new programming language about it says parallel programming but is it going to be an alternativereplacement for mpi pvm openmp and similar parallel librariesframeworksany thoughts,['.net'] +14309,learning objective c without a mac i do not have a mac or an iphone however the concept of taking c and making it more dynamic towards the idea of smalltalk python or ruby is really attractive to me i would love to start on objective c is objective c just a syntax superset of c or is it really like c as in can it be compiled with gcc etc i do most of my programming in ruby objective c seems so much more forgiving than c you can write native extensions for ruby in c can you write native extensions for ruby in objective chow can i get started with objective c outside of owning an maciphone and having xcode,"['objective-c', 'ruby']" +14321,garbage collection of static members will static members be ever collected by the garbage collector,['.net'] +14323,how does python import modules from egg files how can i open init pyc here import stompservice module stompservice from cpython25libsitepackagesstompservice010py25eggstompservice init pycall i see in cpython25libsitepackages is the egg file but where are the internal files of the package,['python'] +14327,django imagefield issue i have a similar modelclass studentmodelsmodela simple class which holds the basic infoof a studentname modelscharfieldmax length50age modelspositiveintegerfieldphoto modelsimagefieldupload tofoobar blanktrue nulltrueas we can see photo field is optional i wanted all the students who have their images saved in the college db for that i did this studentobjectsexcludephoto namenonebut i am getting this error fielderror join on field photo not permittedso how can i extract all those students having their photosany sort of help regarding this would be appreciatedthanks in advance,['python'] +14329,check a collection size with jstl how can i check the size of a collection with jstlsomething likecif testcompaniessize 0cif,['java'] +14345,adding jquery click events to dynamically added content i have a table with multiple rows and columns populated by php and mysql for some of the tds i am adding jquery clickevents in the documentready function to let the user change the contentbut i also have an option for adding rows to the table and populating them manually but since the rows i am adding are not there on the document ready they would not get the click event handler appended and so i am not able to click them to get input boxestable tr td classclickablesome infotd td classclickablesome more infotd tdunchangable infotd tr more similar rows tableand then the jquerytrclickableclickfunction add input fieldsspanaddnewrowclickfunction tableappendtrtd classclickabletd tr,['jquery'] +14353,executing sql statements with fluent nhibernate basically i want to be able to do this sessionexecutesqli do not need it to map to any entities or return any values any suggestions,"['c#', '.net']" +14355,wcf retrieving methodinfo from operationcontext is there an elegant way to get the method that will be executed on a service instance from messageinspectorauthorizationpolicysome other extension point i could useoperationcontextcurrentincomingmessageheadersactionbut i hope there is some way to do it without manually matching soap actions with operationcontractswhat i am trying to do is examine the methods attributes before it executes,['.net'] +14357,jtable scrolling to a specified row index i have a jtable that is within a jscrollpane rows are added to the table at runtime based on events that happen in my application i want to have the scoll pane scroll to the bottom of the table when a new row is added to the tablefor jlists there is the ensureindexisvisible1 that forces a particular index in the list to be visible i am looking for the same thing but for a jtable it looks like i might have to manually move the scrolling view on the scroll pane but i figured there had to be an easier way,['java'] +14366,what do i need to read microsoft access databases using python how can i access microsoft access databases in python with sqli would prefere a solution that works with linux but i could also settle for windowsi only require read access,['python'] +14377,jquery xml parsing with namespaces i am new to jquery and would like to parse an xml documenti am able to parse regular xml with the default namespaces but with xml such asxml xmlnssuuidbdc6e3f06da311d1a2a300aa00c14882 xmlnsdtuuidc2f4101065b311d1a29f00aa00c14882 xmlnsrsurnschemasmicrosoftcomrowset xmlnszrowsetschema sschema idrowsetschema selementtype namerow contenteltonly rscommandtimeout30 sattributetype nameows id rsnameid rsnumber1 sdatatype dttypei4 dtmaxlength4 sattributetype sattributetype nameows docicon rsnametype rsnumber2 sdatatype dttypestring dtmaxlength512 sattributetype sattributetype nameows linktitle rsnametitle rsnumber3 sdatatype dttypestring dtmaxlength512 sattributetype sattributetype nameows servicecategory rsnameservice category rsnumber4 sdatatype dttypestring dtmaxlength512 sattributetype selementtype sschema rsdata zrow ows id2 ows linktitlesample data 1 zrow ows id3 ows linktitlesample data 2 zrow ows id4 ows linktitlesample data 3 rsdataxmlall i really want are the zrowsso far i have been doinggetxmlpath functionxml rsdata xmlfindzroweachfunctioni alertfound zrow xmlwith really no luck any ideas thanks,"['javascript', 'jquery']" +14388,linq to sql tracking new dirty objects is there a way to determine if a linq object has not yet been inserted in the database new or has been changed since the last update dirty i plan on binding my ui to linq objects using wpf and need it to behave differently depending whether or not the object is already in the databasemydatacontext context new mydatacontextmyobject objif new randomnextdouble 5 obj new myobjectelse obj contextmyobjectsfirst how can i thistinguish these two casesthe only simple solution i can think of is to set the primary key of new records to a negative value my pks are an identity field and will therefore be set to a positive integer on insert this will only work for detecting new records it also requires identity pks and requires control of the code creating the new objectis there a better way to do this it seems like linq must be internally tracking the status of these objects so that it can know what to do on contextsubmitchanges is there some way to access that object statusclarificationapparently my initial question was confusing i am not looking for a way to insert or update records i am looking for a way given any linq object to determine if that object has not been inserted new or has been changed since its last update dirty,['c#'] +14405,why is the use of tuples in c not more common why does nobody seem to use tuples in c either the boost tuple library or the standard library for tr1 i have read a lot of c code and very rarely do i see the use of tuples but i often see lots of places where tuples would solve many problems usually returning multiple values from functionstuples allow you to do all kinds of cool things like thistieab make tupleba swap a and bthat is certainly better than thistempaabbtempof course you could always do thisswapabbut what if you want to rotate three values you can do this with tuplestieabc make tuplebcatuples also make it much easier to return multiple variable from a function which is probably a much more common case than swapping values using references to return values is certainly not very elegantare there any big drawbacks to tuples that i am not thinking of if not why are they rarely used are they slower or is it just that people are not used to them is it a good idea to use tuples,['c++'] +14408,jms vs webservices what are the big advantages from jms over webservices or vice versaare webservices bloated is jms overall better for providing interfaces,['java'] +14413,when and why to return false in javascript when and why to return false in javascript,"['javascript', 'jquery']" +14420,codesmith vs t4 nettiers level suite has someone ported the nettiers template set to visual studios t4 templates or is there a system of similar scope does anyone use t4 in a work environment what if any major differences are there between codesmith and t4,['.net'] +14432,mvp pattern how many views to a presenter we are trying to get the modelviewpresenter pattern used on virtually all new dev work that we undertakei am a strong believer in having a framework to help people meet a design requirement we have a few inhouse frameworks for various different components logging email sending etc so i am trying to get some kind of mvp framework developedi have managed to put together something that is easy to use for people who are not familiar with mvp and that is not too far removed from how we currently work the problem is that it is doing a relationship of 1 view to 1 presenterheres a rough outline of the frameworkpublic abstract class presentertview where tview iview public virtual t view get set public virtual void setuptview view thisview view public interface iview the basic way that it works is that any view created inherits from the iview interface and passed to a presenter class which inherits from the presenter abstract classas you can see i am using net generics so that the developer will have strong typing of the view when they are working on the presenter and then ultimately a class inheriting from the presenterso i can set up a basic login component like thispublic class login presenterilogin public override setupilogin view basesetupview thisviewlogin new eventhandlerlogin void loginobject sender eventargs e public interface ilogin iview string username get set string password get set event eventhandler loginso as i said i quite like this there is compiler enforced typing strongly typed views and a mvplike patternsome people though are not quite as happy with the implementation because it has a 1 to 1 relationship between presenters and views and strictly speaking this is not how mvp is meant to bei question how valid this argument really is on the several projects i have been trailing this framework with ranging from medium to large projects i have not found any good example where i thought i need to have multiple views for this presenter when i see functionality which can be shared across multiple views i question if it should even be tied to a particular presenter or whether it should be in a more neutral classis the framework i am trying to achieve too far from mvp to be called mvp is the need to have mutliple views to a presenter the primary goal of mvp is it even possible to have a true net mvp framework with nview support,['.net'] +14456,what are the reasons why mapgetobject key is not fully generic what are the reasons behind the decision to not have a fully generic get method in the interface of javautilmapk vto clarify the question the signature of the method is v getobject keyinstead of v getk keyand i am wondering why same thing for remove containskey containsvalue,['java'] +14463,how to connect to sql server database from javascript in the browser can anybody give me some sample source code showing how to connect to a sql server 2005 database from javascript locally i am learning web programming on my desktopor do i need to use any other scripting language suggest some alternatives if you have them but i am now trying to do it with javascript my sql server is locally installed on my desktop a sql server management studio 2005 and ie7 browser,['javascript'] +14465,big smart viewmodels dumb views and any model the best mvvm approach the following code is a refactoring of my previous mvvm approach fat models skinny viewmodels and dumb views the best mvvm approach in which i moved the logic and inotifypropertychanged implementation from the model back up into the viewmodel this makes more sense since as was pointed out you often you have to use models that you either cannot change or do not want to change and so your mvvm approach should be able to work with any model class as it happens to existthis example still allows you to view the live data from your model in design mode in visual studio and expression blend which i think is significant since you could have a mock data store that the designer connects to which has eg the smallest and largest strings that the ui can possibly encounter so that he can adjust the design based on those extremesquestionsi am a bit surprised that i even have to put a timer in my viewmodel since it seems like that is a function of inotifypropertychanged it seems redundant but it was the only way i could get the xaml ui to constantly once per second reflect the state of my model so it would be interesting to hear anyone who may have taken this approach if you encountered any thisadvantages down the road eg with threading or performancethe following code will work if you just copy the xaml and code behind into a new wpf projectxamlwindow xclasstestmvvm73892window1 xmlns xmlnsx xmlnslocalclrnamespacetestmvvm73892 titlewindow1 height300 width300 windowresources objectdataprovider xkeydatasourcecustomer objecttypextype localcustomerviewmodel methodnamegetcustomerviewmodel windowresources dockpanel datacontextstaticresource datasourcecustomer stackpanel dockpaneldocktop orientationhorizontal textblock textbinding pathfirstname textblock text textblock textbinding pathlastname stackpanel stackpanel dockpaneldocktop orientationhorizontal textblock textbinding pathtimeofmostrecentactivity stackpanel dockpanelwindowcode behindusing systemusing systemwindowsusing systemcomponentmodelusing systemthreadingnamespace testmvvm73892 public partial class window1 window public window1 initializecomponent view model public class customerviewmodel inotifypropertychanged private string firstname private string lastname private datetime timeofmostrecentactivity private timer timer public string firstname get return firstname set firstname value thisraisepropertychangedfirstname public string lastname get return lastname set lastname value thisraisepropertychangedlastname public datetime timeofmostrecentactivity get return timeofmostrecentactivity set timeofmostrecentactivity value thisraisepropertychangedtimeofmostrecentactivity public customerviewmodel timer new timercheckforchangesinmodel null 0 10 private void checkforchangesinmodelobject state customer currentcustomer customerviewmodelgetcurrentcustomer mapfieldsfrommodeltoviewmodelcurrentcustomer this public static customerviewmodel getcustomerviewmodel customerviewmodel customerviewmodel new customerviewmodel customer currentcustomer customerviewmodelgetcurrentcustomer mapfieldsfrommodeltoviewmodelcurrentcustomer customerviewmodel return customerviewmodel public static void mapfieldsfrommodeltoviewmodel customer model customerviewmodel viewmodel viewmodelfirstname modelfirstname viewmodellastname modellastname viewmodeltimeofmostrecentactivity modeltimeofmostrecentactivity public static customer getcurrentcustomer return customergetcurrentcustomer inotifypropertychanged implementation public event propertychangedeventhandler propertychanged private void raisepropertychangedstring property if propertychanged null propertychangedthis new propertychangedeventargsproperty model public class customer public string firstname get set public string lastname get set public datetime timeofmostrecentactivity get set public static customer getcurrentcustomer return new customer firstname jim lastname smith timeofmostrecentactivity datetimenow,['c#'] +14469,nullable types and the ternary operator why is 10 null forbidden i just came across a weird errorprivate bool getboolvalue do some logic and return true or falsethen in another method something like thisint x getboolvalue 10 nullsimple if the method returns true assign 10 to the nullableint x otherwise assign null to the nullable int however the compiler complainserror 1 type of conditional expression cannot be determined because there is no implicit conversion between int and nullam i going nuts,"['c#', '.net']" +14473,java memory explained sun jvm i tried to find an interpretation of the memory segments of the sun java vm which would also be understandable by an administrator it should explain what heap nonheap memory is and the significance of the different memory pools if it would somehow relate to the jconsole view it would be a bonusis there somewhere a website with such an explanation,['java'] +14476,xml indenting when injecting an xml string into an xmlwriter i have an xmltextwriter writing to a file and an xmlwriter using that text writer this text writer is set to output tabindented xmlxmltextwriter xtw new xmltextwriterfooxml encodingutf8xtwformatting formattingindentedxtwindentchar txtwindentation 1xmlwriter xw xmlwritercreatextwchanged per jeffs msdn linkxmlwritersettings set new xmlwritersettingssetindent truesetindentchars tsetencoding encodingutf8xw xmlwritercreatef setthis does not change the end resultnow i am an arbitrary depth in my xmlwriter and i am getting a string of xml from elsewhere that i cannot control that is a singleline nonindented xml if i call xwwriteraw then that string is injected verbatim and does not follow my indentation i wantstring xml externalmethodxwwriterawxmlessentially i want a writeraw that will parse the xml string and go through all the writestartelement etc so that it gets reformatted per the xmltextwriters settingsmy preference is a way to do this with the setup i already have and to do this without having to reload the final xml just to reformat it i would also prefer not to parse the xml string with the likes of xmlreader and then mimic what it finds into my xmlwriter very very manual processat the end of this i would rather have a simple solution than one that follows my preferences best solution naturally would be simple and follows my preferences,"['c#', '.net']" +14485,file to byte in java how do i convert a javaiofile to a byte,['java'] +14486,how can i target css to a particular sharepoint page layout file is it possible to create a css file for each sharepoint page layout i develop or does the css for each possible layout in a master page need to be referenced in the master pageie is it possible to affect the head of the page a page layout is used in,['css'] +14494,table size using jpa query language using jpa query language how do i determine the size number of rows in an entity table,['java'] +14497,do i need a lock when only a single thread writes to a shared variable i have 2 threads and a shared float global one thread only writes to the variable while the other only reads from it do i need to lock access to this variable in other wordsvolatile float xvoid reader thread while 1 grab mutex here float local x x release mutex do stuff with valuelocal x void writer thread while 1 float local x get new value from somewhere grab mutex here x local x release mutex my main concern is that a load or store of a float not being atomic such that local x in reader thread ends up having a bogus partially updated valueis this a valid concernis there another way to guarantee atomicity without a mutexwould using sig atomic t as the shared variable work assuming it has enough bits for my purposesthe language in question is c using pthreads,['c'] +14500,on a dereferenced pointer in c trying to understand the behaviour of pointers in c i was a little surprised by the following example code belowinclude stdiohvoid add one v1int our var ptr our var ptr our var ptr 1void add one v2int our var ptr our var ptrint main int testvar testvar 63 add one v1testvar try first version of the function printfdn testvar prints out 64 printf pnn testvar testvar 63 add one v2testvar try first version of the function printfdn testvar prints 63 printf pn testvar address remains identical output64 0xbf84c6b063 0xbf84c6b0what exactly does the our var ptr statement in the second function add one v2 do since it is clearly not the same as our var ptr our var ptr 1,['c'] +14507,whoami in python what is the best way to find out the user that a python process is running underi could do thisname ospopenwhoamiread but that has to start a whole new processosenvironuserworks sometimes but sometimes that environment variable is not set,['python'] +14517,stack overflows from deep recursion in java after some experience with functional languages i am starting to use recursion more in java but the language seems to have a relatively shallow call stack of about 10is there a way to make the call stack bigger like can i make functions that are millions of calls deep like in erlangi am noticing this more and more when i do project euler problemsthanks,['java'] +14518,sharepoint file size limit i have tried many tutorials online on how to increase the upload file size for a sharepoint document library with no luckany ideas on how to increase the limit of file upload to a document libraryi have tried,['asp.net'] +14521,what refactoring tools do you use for net do you use any of the refactoring tools like devexpress refactor pro which tool do you use and whyi am looking for recommendations ideally i would like open source tool that works with vb and c inside vs2005 and vs2008 if i had to narrow down my list of ideals i would purchase something for vs2008 not sure on the language choice probably vb for now,['.net'] +14526,how does the javascript preloading work i do not want to know a way to preload images i found much on the net but i want to know how it workshow is javascript able to preload imagesi mean i tried a snippet from here and even if it works it does not seem to preload imageswhen i check firebug i can see that the image is loaded twice once while the preloading another time when thisplaying itto improve this code i would like to know how it workshere is what i do function preloadarrayofimages arrayofimageseachfunction img0src this new imagesrc this alertthis i then i do something like thatpreloader function preloadmyimagesdocumentreadypreloaderhere is how i thisplayadd the image liworksclickfunction viewerchildrenempty viewerchildrenappendimg srcimagesrefthisfirstchildidjpg altthisfirstchildid viewerchildrenfadein,['javascript'] +14527,how to get uitextview to respect newlines in interface builder i have a simple app with a uitextview embedded into a uiscrollview interface builder would not let me add multiple newlines for spacing when i hit return it sees that as end of input rather than appending the newline to the uitextviewhow can i get it to accept newlines for spacing,['iphone'] +14528,is it possible to have versionindependent dll references in a class i would like to create a class that compiles into a single dll this dll would add functionality to an existing product to make this work the custom class references dlls contained in the underlying product these references are needed to compileeverything works fine here and the custom class compiles i can drop the dll produced into the product and everything works finehowever this product has several versions minor versions service packs i would like to thistribute this dll to others but i am finding the dll must match perfectly the version of the product if there is not a perfect match then the following error occurscould not load file or assembly productwebui version3619202 cultureneutral publickeytokendfeaee0e3978ac79 or one of its dependencies the located assemblys manifest definition does not match the assembly reference exception from hresult 0x80131040how do i produce a dll that is not picky about the version reference,['.net'] +14534,ordering a list of dictionaries in python i have got a python list of dictionariesmylist id0 weight10 factor1 metaabcid1 weight5 factor1 metaabcid2 weight5 factor2 metaabcid3 weight1 factor1 metaabcwhats the most efficientcleanest way to order that list by weight then factor numericaly the resulting list should look likemylist id3 weight1 factor1 metaabcid1 weight5 factor1 metaabcid2 weight5 factor2 metaabcid0 weight10 factor1 metaabc,['python'] +14537,url to load resources from the classpath in java in java you can load all kinds of resources using the same api but with different url protocolsfiletmptxtjarcomfooquuxclassthis nicely decouples the actual loading of the resource from the application that needs the resource and since a url is just a string resource loading is also very easily configurableis there a protocol to load resources using the current classloaderthis is similar to the jar protocol except that i do not need to know which jar file or class folder the resource is coming fromi can do that using classgetresourceasstreamaxml of course but that would require me to use a different api and hence changes to existing code i want to be able to use this in all places where i can specify a url for the resource already by just updating a property file,['java'] +14540,assign a method for didendonexit event of uitextfield how do i programmatically assign a method observer to the didendonexit event of a uitextfield objectthis is easy enough to do in ib but i cannot figure out how to do it in code,['iphone'] +14548,how can i limit the find to a specific number in cakephp i have a user model which gives me latest users as output how can i limit the record to just output me 200 records instead of all the users in database,['php'] +14550,how to wrap text of html button with fixed width i just noticed that if you give a html button a fixed width the text inside the button is never wrapped i have tried it with wordwrap but that cuts of the word even though there are spaces available to wrap onhow can i make the text of an html button with a fixed width wrap like any tablecell wouldtd classcategory column input typesubmit namectl00contentplaceholder1datalist1ctl12procat namebutton valueroos sturingen sensors idctl00 contentplaceholder1 datalist1 ctl12 procat namebutton classoutset styleheight118pxwidth200pxfontsize18pxcolor7f7f7fwidth200pxwhitespacepre tdthe css classes do nothing but adding borders and modify the paddingif i add wordwrapbreakword to this button it will wrap it like thisroos sturingen sensorsand i dont want it to cut of in the middle of a word if it is possible to cut it off between wordsthanks,"['html', 'css']" +14553,convert decode hexadecimal string to binary string how can i convert 1234567890 to x12x34x56x78x90 in ruby,['ruby'] +14565,how can i use the relaycommand in wpf how can i use the relaycommand in wpf,['c#'] +14574,java usb library is there a good java usb api i can use i tried jusb but it does not seem to work it is also very old no updates since 2001,['java'] +14582,aspnet membership which roleprovider to use so userisinrole checks activedirectory groups very simple question actuallyi currently have iis anonymous access thisabled users are automatically logged on using their windows login however calling userisinrolerole name returns false i doublechecked useridentityname and the role name and it should return truei currently have this in my webconfigupdatei was calling userisinrolerole name where i should call userisinroledomainrole name however i still like to know if the membership entry is needed at allwhat should i change and is the membership entry needed at all authentication modewindows forms nameadauthcookie timeout10 authenticationmembership defaultprovideradmembershipprovider providers clear add nameadmembershipprovider typesystemwebsecurityactivedirectorymembershipprovider systemweb version20 cultureneutral publickeytokenb03f5f7f11d50a3a connectionstringnameadconnectionstring connectionusernamexspecialaduser connectionpasswordxx providersmembershiprolemanager enabledtrue defaultproviderwindowsprovider providers clear add namewindowsprovider typesystemwebsecuritywindowstokenroleprovider providersrolemanager,['asp.net'] +14583,binding converter as inner class i have a usercontrol that uses a binding converter i have made the converter an inner class ofpublic partial class mypanel usercontrol public class cornerradiusconverter ivalueconverter how do i reference the converter class from the xaml the following does not workcontrolsmypanelcornerradiusconverter xkeycornerradiusconverter it gives this error the tag lenspanelcornerradiusconverter does not exist in xml namespace clrnamespacemyappwindowscontrols,"['c#', '.net']" +14586,crossplatform objectivec c development i work in a team of developers one of us works specifically under windows and i work primarily in mac os x were wanting to develop cbased applications either in c or objectivec however i am not really knowledgeable in how to go about a crossplatform development projectis it viable to work in c using mac os x obviously they are geared towards objectivec but is there just as much support for c what about crossplatform development in these languages i would use something like boost and some kind of ui libraryhas anyone got any experience in developing for multiple platforms yet allow applications to run natively without the need for a vmedit there is a lot of answers i want to mark as correct now it seems like qt is the way to go and develop it in c chances are this will be for nix os x and windows so that would be the best option for us personally if i can avoid writing objectivec so the team sticks to c then all the better if i have to write the gui in objectivec and mix and match then that is not too much bother either,"['c++', 'objective-c']" +14604,replacing diacritics in javascript how can i replace diacritics a etc with their normal form ast in javascript,['javascript'] +14610,write file from assembly resource stream to thisk i cannot seem to find a more efficient way to copy an embedded resource to thisk than the followingusing binaryreader reader new binaryreader assemblygetmanifestresourcestreamnamespaceresourcesfileext using binarywriter writer new binarywriternew filestreampath filemodecreate long bytesleft readerbasestreamlength while bytesleft 0 65535l is int32maxvalue so no need to test for overflow byte chunk readerreadbytesintmathminbytesleft 65536l writerwritechunk bytesleft chunklength there appears to be no more direct way to do the copy unless i am missing something,"['c#', '.net']" +14613,converting double to string in c hi guys i am having some issues trying to convert a double to c string here is my codestdstring doubletostringdouble val stdostringstream out out val return outstrthe problem i have is if a double is being passed in as 10 then the string value being returned is 1e007how can i get the string value as 10,['c++'] +14616,very large uploads with php i want to allow uploads of very large files into our php application hundred of megs 8 gigs there are a couple of problems with this howeverbrowserhtml uploads have crappy feedback we need to either poll for progress which is a bit silly or show no feedback at allflash uploader puts entire file into memory before starting the uploadserverphp forces us to set post max size which could result in an easily exploitable dos attack i would like to not set this setting globallythe server also requires some other variables to be there in the post vars such as an secret key wed like to be able to refuse the request right away instead of after the entire file is uploadedrequirementshttp is a musti am flexible with clientside technology as long as it works in a browserphp is not a requirement if there is some other technology that will work well on a linux environment that is perfectly cool,['php'] +14618,how long does it take to learn java for a complete newbie i have absolutely no programming experience but need to learn java enough to take a j2me fasttrack course i only have 10 weeks can i do this whats your advice about the best resources i can use currently using suns java tutorials,['java'] +14624,conditional compile when running in simulator as opposed to on a device is there a compiler directive i can use to compile a different line of code when targetting the simulator as opposed to my device something like if simulatorselfimagepicker setsourcetypeuiimagepickercontrollersourcetypephotolibrary elseselfimagepicker setsourcetypeuiimagepickercontrollersourcetypecamera endeditdirect link to docs,"['iphone', 'objective-c']" +14634,firefox capture autocomplete input change event i am trying to subscribe to change events on an input tag for an ajax auto complete form these change events are not firing when the user clicks an autocomplete suggestion from firefoxi have seen fixes for ie but not firefox you can view this behavior here steps to recreatetype any input in one of the boxes and click submit start typing the value again in the same box you should see the autocomplete suggestion box appear below the input box notice that clicking the suggestion does not fire the change event it also does not fire the click eventcurrently my only option is to thisable autocomplete on this field but i do not want to do that,['javascript'] +14638,unit of measure conversion library what is the bestmost elegant way to abstract out the conversion of units of measures in the client based on a userpreferred unit of measure settingfor example let us say user as preferred unit of measure is metric while users bs preference is imperialnow lets say i have calculated the area of something in meters squared when i go to thisplay the value i need to use different conversion factors for each user eg 1 meter 109361 yards or say i have calculated the fluid volume in ml user bs view will get calculated using the conversion 236588237 ml 1 us cupis there an existing javascript library that anyone here knows about that handles these trivial uom conversions,['javascript'] +14642,using beautifulsoup to find a html tag that contains certain text i am trying to get the elements in an html doc that contain the following pattern of text s11h2 this is cool 12345678901 h2so the previous would match by usingsouph2textrecompiler s11and the results would be something likeublahblah 223409823523 uthisisinteresting 293845023984i am able to get all the text that matches see line above but i want the parent element of the text to match so i can use that as a starting point for traversing the document tree in this case i would want all the h2 elements to return not the text matchesideas,['python'] +14648,is it a good idea to use varargs in a c api to set key value pairs i am writing an api that updates a lot of different fields in a structurei could help the addition of future fields by making the update function variadicupdatefield name1 10 field name2 20then later add field name3 with out changing any existing callsupdatefield name1 10 field name2 20 field name3 30words of wisdom please,['c'] +14650,how can i programmatically remove the 2 connection limit in webclient those fine rfcs mandate from every rfcclient that they beware of not using more than 2 connections per hostmicrosoft implemented this in webclient i know that it can be turned off with appconfigxml version10 encodingutf8 configuration systemnet connectionmanagement add address maxconnection100 connectionmanagement systemnet configurationfound on but how can i do it programmaticallyaccordin tochanging the defaultconnectionlimit property has no effect on existing servicepoint objects it affects only servicepoint objects that are initialized after the change if the value of this property has not been set either directly or through configuration the value defaults to the constant defaultpersistentconnectionlimiti would like best to configure the limit when i instanciate the webclient but just removing this sad limitation programmatically at the start of my programm would be fine toothe server i access is not a regular webserver in the internet but under my control and in the local lan i want to do apicalls but i do not use webservices or remoting,['.net'] +14652,what has render on ssrs20 webservice been replaced with on ssrs2008 weve recently upgraded one of our ssrs2005 servers to ssrs2008 and have found that all of our applications that utilized the reporting services web service for producing reports no longer worksthe first issue is that the web service itself was no longer available at reportserviceasmx and had been replaced by reportservice2005asmx we changed our web reference to the new location and we are now getting the message that the render method is not a part of reportservice2005asmx what has the following code implementation been replaced with in ssrs2008report rptrenderreportpath reportname thisformattostring null devinfotostring parameters null null out encoding out mimetype out parametersused out warnings out streamidseditafter doing some more research it turns out that the reportserviceasmx was part of sql 20 reporting services which has now been deprecated out of sql 2008 reporting services,['c#'] +14661,mysql versus pdo i am fairly new to php and have built a medium sized website using standard mysql database calls however i have recently learned about pdo and i am hoping to find out from the community if it is worth switching from mysql over to pdo for security i have been using mysql real escape stringinfo about the sitei am using a mix of insert and select calls the data returned from select calls is not massive no more than 30 records returned by using limit there will also not be a whole lot of inserts the site is currently not live and so making changes now is easyin your professional opinions is it worth my time to switch the site over to pdo from mysql or is staying with mysql just as good or in other words what would be the reason if any to switch to pdo now,['mysql'] +14662,qt how to set main windows initial position i think the normally window manager determines the initial position of the qmainwindow position on the desk top i want to set the initial position myself how is this done with qt on windows,['c++'] +14663,how do you get the ip address from a request in aspnet i have been trying to figure this out but cannot find a reliable way to get a clients ip address when making a request to a page in aspnet that works with all servers,"['c#', 'asp.net']" +14670,drag a wpf form around the desktop i am trying to make a c wpf form where i can drag it around the screen by clicking on it and moving with the mouse the forms characteristics include being completely transparent and containing only one image this being said the window style is none and it is not thisplayed in the taskbar so essentially all you can see when the app is running is a little image and ideally i want to be able to drag it around the desktop if i click and hold the left mouse button and move it aboutdoes anyone know a simple way i can accomplish this or have i overlooked a build in functionthanks,['c#'] +14677,j2me networking threads and deadlocks the simple piece of midlet code class moo below after the excerpts deadlocks at least i assume it deadlocks after reading this post on threads herei have reproduced the relevant excerpts from the post string url connection conn null try conn connectoropen url do something here catch ioexception e error the root of the problem is the blocking nature of the open call on some platforms the system does the actual connection under the covers on the equivalent of a separate thread the calling thread blocks until the connection thread makes the connection at the same time the security subsystem may require the user to confirm the connection and the connection thread blocks until the event thread gets confirmation from the user deadlock occurs because the event thread is already waiting for the connection thread public class moo extends midlet protected void destroyappboolean arg0 throws midletstatechangeexception todo autogenerated method stub protected void pauseapp protected void startapp throws midletstatechangeexception thisplay thisplay thisplaygetthisplaythis mycanvas mycanvas new mycanvas thisplaysetcurrentmycanvas mycanvasrepaint class mycanvas extends canvas protected void paintgraphics graphics try image bgimage imagecreateimagegetwidth getheight httpconnection httpconnection httpconnection connector open image image imagecreateimagehttpconnection openinputstream bgimagegetgraphicsdrawimageimage 0 0 0 httpconnectionclose graphicsdrawimagebgimage 0 0 0 catch ioexception e eprintstacktrace can someone please tell me how the system thread invocation is done here event and notification threads and the sequence of events leading to the deadlock i am not clear as to what are the thread involved here that lead to deadlockis there any documentation on j2me thread modelwhere can i get the sources for j2me system classes i want to check out the implementation of connection classesedit in the above code i get the logic but the below code should at least work right this one also deadlocks where i am doing the network connection in a separate threadpublic class foo extends midlet protected void destroyappboolean arg0 throws midletstatechangeexception todo autogenerated method stub protected void pauseapp todo autogenerated method stub protected void startapp throws midletstatechangeexception thisplay thisplay thisplaygetthisplaythis mycanvas mycanvas new mycanvas thisplaysetcurrentmycanvas mycanvasrepaint class mycanvas extends canvas protected void paintgraphics graphics try image bgimage imagecreateimagegetwidth getheight fetchimage fetchimage new fetchimage thread thread new threadfetchimage threadstart threadjoin bgimagegetgraphicsdrawimagefetchimageimage 0 0 0 graphicsdrawimagebgimage 0 0 0 catch exception e todo autogenerated catch block eprintstacktrace public class fetchimage implements runnable public image image public void run httpconnection httpconnection try httpconnection httpconnection connector open image imagecreateimagehttpconnectionopeninputstream httpconnectionclose catch ioexception e todo autogenerated catch block eprintstacktrace,['java'] +14692,sql script to alter all foreign keys to add on delete cascade i have a sql 2005 database with approx 250 tablesi want to temporarily enable on delete cascade to all of the foreign keys so that i can do a bulk delete easilyi then want to turn off on delete cascade on all foreign keysthe only way i know of doing this is to use management studio to generate a full database create script do some kind of search and replace to strip out everything but foreign keys save the script then do some more search and replacing to add the on delete cascadethen i run the script do my delete and then run the other scriptis there an easier way to produce this script this method seems far too prone to error and i will have to keep the script up to date with any other changes we make to the database or regenerate it manually each time i may need to use itis an alternative option to run a select on the system tables to generate the script for me could it even be possible to run an update on a system table that enables and thisables on delete cascade,['sql'] +14696,good examples of pythonmemcache memcached being used in python i am writing a web app using python and the webpy framework and i need to use memcached throughouti have been searching the internet trying to find some good documentation on the pythonmemcached module but all i could find was this example on the mysql website and the documentation on its methods is not great,['python'] +14702,culture name is not supported i am receiving culture name uploads is not supported when my aspnet application start where do i have to viewdebug to toggle the errora fulltext search for uploads returns 0 entries in my project,['asp.net'] +14710,sql server 2008 change data capture who made the change i asked a question on sof a week or so ago about auditing sql data changes the usual stuff about using triggers came up there was also the mention of cdc in sql server 2008 i have been trying it out today and so far so good the one thing i cannot see it supports is keeping a track of who actually made the change who executed the statementi am interested to know if anyone has used cdc for auditing and how you kept track of who made the change,['sql'] +14712,copying data between oracle schemas using sql i am trying to copy data from one oracle schema core data into another my data using an insert into sql statementwhat would the sql statement look like,['sql'] +14718,resolving a parameter name at runtime possible duplicatefinding the variable name passed to a function in c in c is there a way terser the better to resolve the name of a parameter at runtimefor example in the following method if you renamed the method parameter youd also have to remember to update the string literal passed to argumentnullexception public void woofobject resource if resource null throw new argumentnullexceptionresource,['c#'] +14719,getting simplexmlelement to include the encoding in output thisxml new simplexmlelementfoo echoxmlasxmloutputs thisxml version10foobut i want it to output the encoding tooxml version10 encodingutf8foois there some way to tell simplexmlelement to include the encoding attribute of the xml tag aside from doing thisxml new simplexmlelementxml version10 encodingutf8foo echoxmlasxmlwhich works but it is annoying to have to manually specify the version and encodingassume for the purposes of this question that i cannot use domdocument instead,['php'] +14723,why are union queries so slow in mysql when i optimize my 2 single queries to run in less than 002 seconds and then union them the resulting query takes over 1 second to run also a union all takes longer than a union thistinct i would assume allowing duplicates would make the query run faster and not slower am i really just better off running the 2 queries separately i would prefer to use the union,['mysql'] +14724,using curlpp with vs2008 i am trying to build a c console app in vs2008 using the static curlpp library the code which is curlpp example 00 is as followsinclude stdafxhinclude curlppcurlpphppinclude curlppeasyhppinclude curlppoptionshppusing namespace curlppoptionsint mainint char try our request to be sent curlppeasy myrequest set the url myrequestsetopturl send request and get a result by default the result goes to standard output myrequestperform catchcurlppruntimeerror e stdcout ewhat stdendl catchcurlpplogicerror e stdcout ewhat stdendl return 0i have downloaded the source and have my include path pointed to the source include files but when i try and compile i get a boatload of errors in the inline files of the typedefinition of dllimport function not allowedsurely lots of folks have used curlpp with vs2008 and i am missing something obvious,['c++'] +14726,how to access static resources when mapping a global front controller servlet on i have mapped the spring mvc thispatcher as a global front controller servlet on servlet servletnamehomeservletname servletclassorgspringframeworkwebservletthispatcherservletservletclass servlet servletmapping servletnamehomeservletname urlpatternurlpattern servletmappinghowever this mapping stops the access to static files like css js images etc which are all in the res folderhow can i access them anyway,['java'] +14733,is there a good natural language processing library i need to implement some nlp in my current module i am looking for some good library that can help me here i came across lingpipe but could not completely follow on how to use itbasically we need to implement a feature where the application can decipher customer instructions delivery instructions typed in plain english egwill pick up at 1200 noon tomorrowrequest delivery after 10th juneplease do not send before wednesdayadd 10 more units of xyz to the order,['java'] +14736,in python how do you filter a string such that only characters in your list are returned imagine a string like agh2341 zdrkfd and i only wish to perform some operating on it such that only the lowercase letters are returned as an example which in this case would bring ghzdrkfdhow do you do this in python the obvious way would be to create a list of characters a through z then iterate over the characters in my string and build a new string character by character of those in my list only this seems primitivei was wondering if regular expressions are appropriate replacing unwanted characters seems problematic and i tend to prefer whitelisting over blacklisting the match function does not seem appropriate i have looked over the appropriate page on the python site but have not found a method which seems to fitif regular expressions are not appropriate and the correct approach is looping is there a simple function which explodes a string into a list or am i just hitting another for loop there,['python'] +14755,webkit javascript reference for gecko there is mozilla developer networkfor ie there is msdnfor webkit there isapple developer connection there are a couple of javascript related documents on adc but nothing as comprehensive as mdn or msdn there is no reference there is no way to look up methods of arrays or strings for webkit or anything is there so what do we just assume it is the same as gecko ie,['javascript'] +14771,how does system exactly work in linux i have been reading its man page but have not yet been successful in figuring out how it works on calling system is a new child process forked and the shell binary execed in it that may be a stupid guess though,['c'] +14773,most efficient way to find whether a large list contains a specific string python i have a file containing roughly all the words in english 60k words 500k characters i want to test whether a certain word i receive as input is in english ie if this exact word is in the listwhat would be the most efficient way to do this in pythonthe trivial solution is to load the file into a list and check whether the word is in that list the list can be sorted which i believe will shrink the complexity to ologn however i am not sure about how python implements searching through lists and whether there is a performance penalty if such a large list is in memory can i abuse the fact i can put a cap on the length of words eg say the longest one is 15 characters longplease note i run the application on a machine with lots of memory so i care less for memory consumption than for speed and cpu utilizationthanks,['python'] +14774,javascript swap array elements is there any simpler way to swap two elements in an arrayvar a listx b listylisty alistx b,['javascript'] +14797,memory management and performselectorinbackground which is right thisnsarray foo nsarray alloc initwithobjectsa b nilbar performselectorinbackgroundselectorbaz withobjectfoo voidbaznsarrayfoo foo releaseornsarray foo nsarray alloc initwithobjectsa b nil autoreleasebar performselectorinbackgroundselectorbaz withobjectfoo voidbaznsarrayfoo nsautoreleasepool pool nsautoreleasepool alloc init pool releasei know the first one works but clang complains about it so i wonder if there is a better pattern to usei would just try out the 2nd one but with autoreleasing who knows whether the absence of exc bad access means that youre doing it right or that you just got lucky,"['objective-c', 'iphone']" +14803,why does javautilproperties implement map and not map the javautilproperties class is meant to represent a map where the keys and values are both strings this is because properties objects are used to read properties files which are text filesso why in java 5 did they retrofit this class to implement mapobjectobject and not mapstringstring the javadoc statesbecause properties inherits from hashtable the put and putall methods can be applied to a properties object their use is strongly thiscouraged as they allow the caller to insert entries whose keys or values are not strings the setproperty method should be used instead if the store or save method is called on a compromised properties object that contains a nonstring key or value the call will failsince the keys and values are both supposed to be strings then why not enforce that statically by using the proper generic typei guess making properties implement mapstringstring would not be fully backward compatible with code written for prejava 5 if you have older code that sticks nonstrings into a properties object then that code would no longer compile with java 5 but is not that a good thing is not the whole point of generics to catch such type errors at compile time,['java'] +14817,swing creating a draggable component i searched the web for examples of draggable swing componentsbut i found either incomplete or nonworking exampleswhat i need is a swing component that can be dragged by the mouseinside an other component while being dragged it should already change its position not just jump to its destinationi would appreciate examples which work without nonstandard apisthank you,['java'] +14818,wpf how do i loop through the all controls in a window how do i loop through the all controls in a window in wpf,"['c#', '.net']" +14824,is objectivec only used for development on mac osiphone i do not know objectivec but to me it appears a nice language but the only context i know it from is everything apple but objectivec is even in the gnu compiler collection is there something missing in the open ones or is there already a broader base for objectivec i am interested if there are companies that chose objectivec to develop their products,['objective-c'] +14826,best sqlite practices on the iphone what are some best practices to keep in mind when working extensively with sqlite on the iphone tipstricksconvenience factors all appreciated,"['iphone', 'objective-c']" +14828,regex for tree structures are there regular expression equivalents for searching and modifying tree structures concise minilanguages like perl regex are what i am looking forhere is an example that might clarify what i am looking forroot node name1 subtrees node node name2 node name21 data node other subtrees noderootan operation that would be possible on the above tree is move subtree at node 21 intothe subtree at node 1 the result of the operation might look something likeroot node name1 subtrees node name21 data node node node name2 other subtrees noderootsearch and replace operations like find all nodes with atleast 2 children find all nodes whose data starts with a and replace it with b if the subtrees have atleast 2 other siblings etc should be supported for strings where the only dimension is across the length of the string we can do many of above operations or their 1d equivalents using regular expressions i wonder if there are equivalents for trees instead of a single regex you might need to write a set of transformation rules but that is oki would like to know if there is some simple mini language not regex perse but something that is as accessible as regex via libraries etc to perform these operations preferably as a python library,"['java', 'python', 'c']" +14829,setneedsthisplay does not always call drawrect i have a custom view in a custom table cell every time a specific property on the custom view is changed i call self setneedsthisplay which redraws the view in voiddrawrectcgrectrect that property is set in the table view delegates tableviewcellforrowatindexpath but when the table view is larger than the screen and cells have to be reused drawrect is not called every time setneedsthisplay is especially when i flick the table quickly slow scrolling works fine this leads to the information in the first and last cells often being incorrectin the log i can see that normally for every call to setneedsthisplay there is a call to drawrect but when i scroll the table view quickly there are more calls to setneedsthisplay than drawrect surely there should be a onetoone ratio herei use the same custom view in a normal uiview and it redraws perfectly every time i call setneedsthisplay the problem seems isolated to table views and reusing cellsdoes anyone know whats going on hereis there any other way to force the custom view to redraw itself,['iphone'] +14830,how do you abstract out your persistence code when using linq to sql i love linq to sql but it has been bugging me that in using it my repository code becomes generated by the linq to sql framework and hence tightly coupled to an sql server databaseare any of you using linq to sql in an abstracted loosely coupled fashion and if so how did you approach the problem of keeping your code databaseindependent,['.net'] +14844,getting json on ajax response callback i am trying to create a little ajax chat system just for the heck of it and i am using prototypejs to handle the ajax partone thing i have read in the help is that if you return json data the callback function will fill that json data in the second parameterso in my php file that gets called i haveheadercontenttype applicationjsonif response acs ajch sqlpostmsgacs ajch msgacs ajch usernameacs ajch channelacs ajch ts client true echo json encodearraylastid acs ajch sqlmsgidelse echo json encodearrayerror responseon the ajax request i haveonsuccess function responsejson alertresponseresponsetext alertjson the alert of the responseresponsetext gives me lastid 8 but the json gives me nullanyone know how i can make this work,"['php', 'javascript']" +14890,javascript range slider dual slider exist without using a framework i am looking for a javascript control that is a range slider dual knob thatdoes not use an existing js framework eg dojo jquery etc unless you can rollcreate your own sub framework where i can compile in just the components i needworks in all major browsersan example a range slider is below but of course this uses jquery so this is not an option because even if i built jquery only including the components i need jquery ui core slider it is 140kb minified,['javascript'] +14891,java getting resolutions of oneall available monitors instead of the whole desktop i have two differentsized monitors connected together using i believe twinviewi triedsystemoutprintlntoolkitgetdefaulttoolkitgetscreensizeand getjavaawtdimensionwidth2960height1050which is true if you count both monitors togetherinstead of this i would like to be able achieving one of the followinggetting resolution of the current monitorgetting resolution of the main monitor,['java'] +14901,programatically install certificate revocation list crl i need to download and install about 50 crls once a week and install them on several windows servers downloading is the easy part is there a way i could script the crl import process,['c#'] +14903,java curve fitting library i am hoping to find a simple library that can take a series of 2 dimensional points and give me back a larger series of points that model the curve basically i want to get the effect of curve fitting like this sample from jfreechartthe problem with jfreechart is that the code does not provide this type of api i even looked at the source and the algorithm is tightly coupled to the actual drawing,['java'] +14912,explanation of func i was wondering if someone could explain what funcint string is and how it is used with some clear examples,"['c#', '.net']" +14913,is a modal confirm box using jquery possible looked around quite a bit and cannot seem to find a jquery solution maybe its just a limitation of javascript for thisa hrefsomelinkphp onclickreturn confirmgo to somelinkphpclick hereain the above example when a user clicks on the link it will only go to its href if the user clicks ok in the confirm boxwhat i am trying to do is get a more modern look using a popup div perhaps something like thisa hrefsomelinkphp onclickreturn jq confirmgo to somelinkphpclick hereawhere jq confirm is a custom jquery confirm function that pops up a nice div with a yesno or okcancel button pair however i cannot seem to find any such thing i have looked at some jquery widget libraries etc which offer similar functionality but none will wait for the response from the user at least not in the scenario described above but instead they just proceed and take the user to the link or run any javascript embedded in the href piece of the link i suspect this is because while you can attach a callback function to many of these widgets to return a truefalse value the onclick event does not wait for a response callbacks are asynchronous thereby defeating the purpose of the confirm boxwhat i need is the same kind of haltalljavascript modal functionality that the default confirm command provides is this possible in jquery or even in javascriptas i am not an expert in javascript nor in jquery i defer to you gurus out there any jquery or even pure javascript solution is welcome if possiblethanks,"['javascript', 'jquery']" +14941,adding text labels to sliders in iphone settings application when configuring a settingsbundle as part of an iphone application bundle it is trivial to add minimum and maximum value images to sliders pssliderspecifier but not simple maximum and minimum text labelsiphone gurus is anyone aware of a simple means to apply text labels to these sliders for use within the settings application therefore no slider subclassing shenanigans it all has to be done via a plist i suppose i could just use an image of the label butewbonus points if there is a way to show the current value of a slider in some sort of number format,"['iphone', 'objective-c']" +14948,can i set two background images on the same element with css sample html codetabletr td classa bsample css filea backgroundimageurlapngb backgroundimageurlbpngit seems like the b part is ignoredis there any way to inlclude both images in the same cell even using other technique,"['html', 'css']" +14951,mysql order by using date data row i have a query something like thisselect title desc date from tablename order by date asc title ascworks fine when the data actually has a date issue is date submission is optional so i sometimes get 0 as a date which has the unfortunate effect of placing all nondated rows on topso i then tried thisselect title desc date from tablename order by date desc title ascwhich sort of works but not really all items with dates non 0 get listed in descending order followed by all items with 0what i want to do is order by date asc title asc but only if the date 0 but if date is 0 then just order by title asc on those i think i explained that correctlythe only ways i can think to do this are nonsql based either 2 queries or each query just populates an inmemory array and then i sort using phpis there a sql query that can do this,"['php', 'sql', 'mysql']" +14954,can modules have properties the same way that objects can with python properties i can make it such that objy calls a function rather than just returning a valueis there a way to do this with modules i have a case where i wantmoduley to call a function rather than just returning the value stored there,['python'] +14955,is it bad practice to use unicode symbols or shapes in a i app there have been a few times where i have used unicode symbols in place of small icons in one of my cocoa apps either because it is easier to draw inline with text or because i did not feel like firing up photoshop to draw a simple arrow i have wondered though could there be issues with localization or fonts i might not be aware of are there any cases where these symbols might not match what i am seeing on my workstation,['objective-c'] +14956,question about server socket programming model over the last couple of months i have been working on some implementations of sockets servers in c and java i wrote a small server in java that would handle process input from a flash application hosted on a website and i managed to successfully write a server that handles input from a 2d game client with multiple players in c i used tcp in one project udp in the other one now i do have some questions that i could not really find on the net and i hope that some of the experts could help me let us say i would like to build a server in c that would handle the input from thousands of standalone andor web applications how should i design my server then so far i usually create a new unique thread for each user that connects but i doubt this is the way to go also how does one determine the layout of packets sent over the network is data usually sent over the network in a binary or text state how do you handle serializated objects when you send data to different media eg c server to flash applicationand last is there any easy to use library which is commonly used that supports portability eg development on a windows machine deployment on a linux box other than boost asiothank you,['c++'] +14972,how to modularize a large java app i have a rather large several mloc application at hand that i would like to split up into more maintainable separate parts currently the product is comprised of about 40 eclipse projects many of them having interdependencies this alone makes a continuous build system unfeasible because it would have to rebuild very much with each checkin is there a best practice way of how toidentify parts that can immediately be separateddocument interdependencies visuallyuntangle the existing codehandle patches we need to apply to libraries currently handled by putting them in the classpath before the actual libraryif there are freeopen tools to support this i would appreciate pointerseven though i do not have any experience with maven it seems like it forces a very modular design i wonder now whether this is something that can be retrofitted iteratively or if a project that was to use it would have to be layouted with modularity in mind right from the startedit 20090710we are in the process of splitting out some core modules using apache antivy really helpful and well designed tool not imposing as much on you as maven does i wrote down some more general details and personal opinion about why we are doing that on my blog too long to post here and maybe not interesting to everyone so follow at your own thiscretion wdanielschnellercom,['java'] +14977,sorting json by values i have a very simple json object like the following people f namejohn l namedoe sequence0 titlepresident urlgooglecom color3 f namemichael l namegoodyear sequence0 titlegeneral manager urlgooglecom color3 now that this is returned from my server side code i run jqueryeach to form the necessary html and output the result right now what i am doing is sending an ajax call to the server containing my sort info eg title desc and rerun an sql query to return the new result set but i want to avoid this and use jquery to sort the resulting json to prevent round trips to the server and multiple database accesshow can i achieve this using jquery,['jquery'] +14982,problem with ie when using thisplayblock for links this is my htmldiv idlinks a hreflink 1a a hreflink 2a a hreflink 3a a hreflink 4adivand these are the css styleslinks position absolute border 1px solid 0links a thisplay blocklinks ahover backgroundcolor cthis thisplays a list of links the problem is that in ie i can only click a link by directly clicking the text link which is not the case with other browsers where you can click anywhere whether the text link or anywhere else as long as it is in the link block is there any fix for that with only css no javascriptplease note that i do not want to specify a width for the links or the div,"['html', 'css']" +14985,excel net com automation error the system cannot find the file specified i have a net 20 com object that is used by vba in excel it works fine on my dev machine but when trying to use it on a clean vm workstation i get this errorautomation error the system cannot find the file specifiedthe dll is registered with regasm tlb codebase mycomdll and not put in the gaci do not have administration rights on the vm boxany ideas,['.net'] +14986,troubleshooting consistent sqlexception lock wait timeout exceeded i have an application running quartz 161 wpersistent job store with mysql 51 as the db this application used to boot up okay in tomcat6 at some point it began throwing the following exception upon every boot misfirehandler error handling misfires failure obtaining db row lock lock wait timeout exceeded try restarting transactionorgquartzimpljdbcjobstorelockexception failure obtaining db row lock lock wait timeout exceeded try restarting transaction see nested exception javasqlsqlexception lock wait timeout exceeded try restarting transaction at orgquartzimpljdbcjobstorestdrowlocksemaphoreexecutesqlstdrowlocksemaphorejava112 at orgquartzimpljdbcjobstoredbsemaphoreobtainlockdbsemaphorejava112 at orgquartzimpljdbcjobstorejobstoresupportdorecovermisfiresjobstoresupportjava3075 at orgquartzimpljdbcjobstorejobstoresupportmisfirehandlermanagejobstoresupportjava3838 at orgquartzimpljdbcjobstorejobstoresupportmisfirehandlerrunjobstoresupportjava3858caused by javasqlsqlexception lock wait timeout exceeded try restarting transaction at commysqljdbcsqlerrorcreatesqlexceptionsqlerrorjava1055 at commysqljdbcsqlerrorcreatesqlexceptionsqlerrorjava956 at commysqljdbcmysqliocheckerrorpacketmysqliojava3491 at commysqljdbcmysqliocheckerrorpacketmysqliojava3423 at commysqljdbcmysqliosendcommandmysqliojava1936 at commysqljdbcmysqliosqlquerydirectmysqliojava2060 at commysqljdbcconnectionimplexecsqlconnectionimpljava2542 at commysqljdbcpreparedstatementexecuteinternalpreparedstatementjava1734 at commysqljdbcpreparedstatementexecutequerypreparedstatementjava1885 at commchangev2c3p0implnewproxypreparedstatementexecutequerynewproxypreparedstatementjava76 at orgquartzimpljdbcjobstorestdrowlocksemaphoreexecutesqlstdrowlocksemaphorejava92 4 morei should mention this application also utilizes jpa whibernate using c3p0 for data source connection pooling this exception is always thrown directly after jpa finishes updating my schemafirst i upgraded to quartz 165 and the exception went away but the application appears frozen the last thing in the logs where the exception used to be ishbm2ddl stuff2969 thread1 info orghibernatetoolhbm2ddlschemaupdate schema update complete handling 6 triggers that missed their scheduled firetimewith nothing coming after and the webapp not servicing requests they just hang indefinitelywhen i run mysql commandline client with show innodb status right after the exception it does consistently show two suspicious transactionssemaphoresos wait array info reservation count 49 signal count 49mutex spin waits 0 rounds 2100 os waits 0rwshared spins 115 os waits 49 rwexcl spins 0 os waits 0transactionstrx id counter 0 165688purge done for trxs no 0 165685 undo no 0 0history list length 12list of transactions for each sessiontransaction 0 0 not started os thread id 5012mysql thread id 8 query id 1798 localhost 127001 rootshow innodb statustransaction 0 165687 active 300 sec os thread id 37722 lock structs heap size 320 1 row locksmysql thread id 30 query id 1795 localhost 127001 my apptransaction 0 165685 active 360 sec os thread id 54602 lock structs heap size 320 1 row locks undo log entries 1mysql thread id 34 query id 1680 localhost 127001 my appi am looking for guidance on how to further investigate this issue perhaps if i could somehow identify the owners of these two transactions or what resources they are lockingupdate i deleted all rows in the qrtz simple triggers table without problem i then tried to do the same on the qrtz triggers table and my mysql client threw a lock wait timeout exceeded error at this point i stopped my still hanging application and was then able to delete all rows of the qrtz triggers table once this was done i was able to successfully boot my applicationit appears i need to log a new quartz bug but i would like to be able to give them more information about what is actually hapenning here so as per the original question how can i troubleshoot these types of issues,['mysql'] +14988,generating missing spec files for rspec is there any command available for generating all missing spec files for existing models controllers i have a project that has several models that have been generated with out spec files,"['ruby-on-rails', 'ruby']" +14993,sorting an array of objects in ruby by object attribute i have an array of objects in ruby on rails i want to sort the array by an attribute of the object is it possible,['ruby'] +15000,parse string to date with different format in java i want to convert string to date in different formatsfor example i am getting from userstring fromdate 19052009 ie ddmmy formati want to convert this fromdate as a date object of ymmdd formathow can i do this,['java'] +15001,how to hide cgibin py etc from my urls brand new to web design using python got apache up and running test python script working in cgibin directory get valid results when i type in the url explicitly cgibinshowenvpybut i do not want the url to look that way here at stackoverflow for example the urls that thisplay in my address bar never have the messy details showing the script that was used to run them they are clean of cgibin py etc extensions how do i do thatedit thanks for responses every single one helpful lots to learn i am going with url rewriting for now example in the docs looks extremely close to what i actually want to do but i am committed to python so will have to look at wsgi down the road,['python'] +15004,how to decide where to store peruser state registry appdata isolated storage when should the windows registry be used for peruser state and when should we use the filesystem particularly the users appdata folder eg cusersusernameappdata where does isolated storage come in is there a pretty firm rule or is it just a fuzzy thing like use the registry until it becomes too much data to store in the registry or use whatever you feel like usingare there windows logo requirements that affect the decisionif i use the appdata directory how do i choose between local roaming and locallow edit i just noticed these similar questions when and why should you store data in the registry registry vs ini file for storing userconfigurable app settings i will summarize replies,['c#'] +15017,how can i determine if a date is between two dates in java how can i check if a date is between two other dates in the case where all three dates are represented by instances of javautildate,['java'] +15018,how to dynamically add a style for textalign using jquery i am trying to correct the usual ie bugs around css 21 and need a way to alter an elements style properties to add a custom textalign stylecurrently in jquery you can do something likethiswidth or thisheightbut i cannot seem to find a good way to alter the textalign w this same approachthe item already has a class and i do set the textalign in that class with no luck is it possible to just add a textalign css attribute to this element after a class is definedi have something like this thiscsstextalign centerjust after my width adjustment and after i view this in firebug i see only width is the only property set on the style any helpeditwhoa big response on this question thanks to everyone who replied a bit more detail around the problem at handi am tweaking the js source for jqgrid a35 to do some custom sub grid work and the actual js i am tweaking is shown below sorry for using this in my examples above but i wanted to keep this simple for brevityvar subgridjson functionsjxml sbid var tbl trdiv tddiv result i cur sgmap dummy documentcreateelementtable tbl documentcreateelementtbody dummyattr cellspacing 0 cellpadding 0 border 0 trdiv documentcreateelementtr for i 0 i tspsubgridmodel0namelength i tddiv documentcreateelementth tddivclassname uistatedefault uithcolumn tddivhtmltspsubgridmodel0namei tddivwidthtspsubgridmodel0widthi trdivappendchildtddiv tblappendchildtrdivi have tried both of the below from the answers provided with no lucktddivwidthtspsubgridmodel0widthiattrstyle textalign centerandtddivwidthtspsubgridmodel0widthicsstextalign centeri will continue to work on this issue today and post a final solution for anyone feeling my pain around this strange issue,"['jquery', 'css']" +15022,problems with deploymentitem attribute i am currently maintaining an old system written in cnet removing some obsolete features and doing some refactoring thanks god the previous guy wrote some unit tests mstests i quite comfortable with junit tests but did not do yet much with msteststhe test methods have a deploymentitem attribute specifying a text file which is parsed by the business logic method that is being tested and a 2nd deploymentitem where just a path has been specified containing a bunch of tif files that have to be deployed tootestmethoddeploymentitemfilesvalidvalid entriestxtdeploymentitemfilestifpublic void existstiftest the tests worked before but now i had to change the names of the tif files contained in the filestif directory according to a rule the tif filenames have to match a certain pattern which is also checked by the existstiftest methodnow i had to change the filenames in order to adapt them to the new requirements and suddently the tif files are no more being deployed as beforecan someone give me a hint why this happens or what may be the cause the same thing happens also if i add a new textfile say my2ndtesttxt beside the valid entriestxt in the filesvalid directory with the according deploymentitem attribute on the test method the file does not get deployedi got the images now deployed by defining the deployment path directly in the testrunconfig but i would like to understand why these things happen or why for instance my new file my2ndtesttxt does not get deployed while the others dothanks a lot,['c#'] +15024,python multiprocessing atexit error error in atexit run exitfuncs i am trying to run a simple multiple processes application in python the main thread spawns 1 to and processes and waits until they all done processing the processes each run an infinite loop so they can potentially run forever without some user interruption so i put in some code to handle a keyboardinterruptusrbinenv pythonimport sysimport timefrom multiprocessing import processdef main set up inputs spawn processes proc 1start proc 2startclass proc process def init self procnum selfid procnum process init self def run self donework false while true try do work timesleep1 sysstdoutwrite if donework print proc strselfid done break except keyboardinterrupt print user aborted sysexit main entryif name main mainthe problem is that when using ctrlc to exit i get an additional error even though the processes seem to exit immediatelyuser abortederror in atexit run exitfuncstraceback most recent call last file cpython26libatexitpy line 24 in run exitfuncs functargs kargs file cpython26libmultiprocessingutilpy line 281 in exit function pjoin file cpython26libmultiprocessingprocesspy line 119 in join res self popenwaittimeout file cpython26libmultiprocessingforkingpy line 259 in wait res subprocesswaitforsingleobjectintself handle msecskeyboardinterrupterror in sysexitfunctraceback most recent call last file cpython26libatexitpy line 24 in run exitfuncs functargs kargs file cpython26libmultiprocessingutilpy line 281 in exit function pjoin file cpython26libmultiprocessingprocesspy line 119 in join res self popenwaittimeout file cpython26libmultiprocessingforkingpy line 259 in wait res subprocesswaitforsingleobjectintself handle msecskeyboardinterrupti am running python 26 on windows if there is a better way to handle multiprocessing in python please let me know,['python'] +15049,how to spawn parallel child processes on a multiprocessor system i have a python script that i want to use as a controller to another python script i have a server with 64 processors so want to spawn up to 64 child processes of this second python script the child script is called python create graphspy namenamewhere name is something like xyz abc nyu etcin my parent controller script i retrieve the name variable from a listmy list xyz abc nyu so my question is what is the best way to spawn off these processes as children i want to limit the number of children to 64 at a time so need to track the status if the child process has finished or not so i can efficiently keep the whole generation runningi looked into using the subprocess package but rejected it because it only spawns one child at a time i finally found the multiprocessor package but i admit to being overwhelmed by the whole threads vs subprocesses documentationright now my script uses subprocesscall to only spawn one child at a time and looks like thispathtopythonimport subprocess multiprocessing queuefrom multiprocessing import processmy list xyz abc nyu if name main processors multiprocessingcpu count for i in rangelenmy list if i processors cmd python pathtocreate graphspy name my listi child subprocesscall cmd shellfalse i really want it to spawn up 64 children at a time in other stackoverflow questions i saw people using queue but it seems like that creates a performance hit,['python'] +15050,how to create google sitemap for mvc site i was wondering if anyone has done this yet or has any exampleson how to create a google sitemap for an mvc websiteany help or example would be appreciatedim talking about this,['asp.net'] +15052,setting up ehcache replication what multicast settings do i need i am trying to set up ehcache replication as documented here this is on a windows machine but will ultimately run on solaris in productionthe instructions say to set up a provider as follows cachemanagerpeerproviderfactory classnetsfehcachethistributionrmicachemanagerpeerproviderfactory propertiespeerthiscoveryautomatic multicastgroupaddress2301 multicastgroupport46 timetolive32and a listener like thiscachemanagerpeerlistenerfactory classnetsfehcachethistributionrmicachemanagerpeerlistenerfactory propertieshostnamelocalhost port401 sockettimeoutmillis20my questions areare the multicast ip address and port arbitrary i know the address has to live within a specific range but do they have to be specific numbersdo they need to be set up in some way by our system administrator i am on an office networki want to test it locally so am running two separate tomcat instances with the above configwhat do i need to change in each one i know both the listeners cannot listen on the same port but what about the provideralso are the listener ports arbitrary tooi have tried setting it up as above but in my testing the caches do not appear to be replicated the value added in one tomcats cache is not present in the other cacheis there anything i can do to debug this situation other than packet sniffingthanks in advance for any help been tearing my hair out over this one,['java'] +15060,how to synchronize lifetime of forms authentication cookie and aspnet session i am building an aspnet web site that uses formsauthentication and a standard session mechanism with configuration likeauthentication modeforms forms cookielessusecookies namemyappauth loginurlloginaspx timeout20authenticationsessionstate timeout20 cookielessusecookies it seems that the lifetime of an authentication cookie is not equal to the lifetime of the user sessionso aspnet does not guarantee thatsession terminates when user logoutsession does not terminates before user logoutis there a way to customize formsauthentication orand the session state mechanism to reach these goals,['asp.net'] +15072,c regular expression to match letters numbers and underscore i am trying to create a regular expression pattern in c the pattern can only allow forlettersnumbersunderscoresso far i am having little luck i am not good at regex here is what i have tried thus far create the regular expressionstring pattern w regex regex new regexpattern compare a string against the regular expressionreturn regexismatchstringtotest,['c#'] +15075,linking javascript libraries in user controls i have been using aspnet mvc for six months or so and have been checking out the nerd dinner example created by those microsoft guys one thing i noticed they did when enabling ajax to rsvp for a dinner is put the javascript references in the user control being used for rsvpingfile rsvpstatusascx control languagec inheritssystemwebmvcviewusercontrolnerddinnermodelsdinner script srcscriptsmicrosoftajaxjs typetextjavascriptscriptscript srcscriptsmicrosoftmvcajaxjs typetextjavascriptscriptthis does not seem right to me as there is a really good chance i would be using these same libraries elsewhere like logon authentication plus if i change script versions i need to hunt down all the references to the librariesso i ask if my thinking is correct and these references should actually be in a more central location like the master pageplease let me know what the best practice is for this and pros and cons if any,['javascript'] +15077,creating an index on a table variable can you create a index on a table variable in sql server 20ie declare temptable table id int not null primary key name nvarchar 255 collate database default null can i create a index on name,['sql'] +15078,how do i make the code in lib automatically reload when the file changes this is a follow up to this question during development i have to restart the rails app everytime i change the code in lib in order for the code changes to take effect how do i get this code to automatically reload like controllers models etc,['ruby-on-rails'] +15087,prime numbers c and i would like to program something like thisplaying the prime numbers in a listbox if user will input any integer in the textbox that means if they write 10 it will thisplay the prime numbers from 010 or 20 from 020 etcwhat should i consider first before i do the programmingi know there are many examples in the internet but first i would like to know what will i needthanks for the tipthanks guys so youre suggesting that it is better to do it first in the console applicationi did an example of for loop using console application a very simple one but then when i tried to do it in the windows form application i am not sure how to implement iti am afraid that if i keep doing examples in the console then i will have difficulty to do it in windows form appswhat do you thinkhello againi need some feedback with my code consolewritelineplease enter your integer long yourinteger yourinteger int32parseconsolereadline thisplaying the first prime number and comparing it to the given integer for long i 2 i yourinteger i i 1 controls i if its prime number or not if i 2 0 i 2 consolewrite0 i,['c#'] +15088,creating unordered list in a div i have a div i want to dynamically generate a bulleted list inside the div using jquery with a items list i have with mefor cnt 0 cnt somelistlength cnt somelistcntfirstname somelistcntlastname br what to write here,['jquery'] +15089,how can i tell if a network cable has been unplugged i have a c application that should only be used when the network is down but am afraid users will just unplug the network cable in order to use itis there a way to detect if the network cable has been unpluggedthanks,['c#'] +15093,nsurlconnection is run many times i connect asynchronously with server each 5 seconds the url is the same but postbody is changed each time now i create nsurl nsurlrequest and nsurlconnection from the scratch each timei think it would be more effective to set connection once and just use that one further i am a newbie and not sure if that possible there is no mutable nsurlconnection but may it is need to create nsurlconnection likensmutableurlrequest request nsmutableurlrequest alloc initwithurl urlnsurlconnection connection nsurlconnection alloc initwithrequestrequest delegateselfand change nsmutableurlrequest postdata to send another request to serverwhich way is right,['iphone'] +15094,what are android application update issues and best practices i have published an android applications on the android market and now have an update to doi want to know if any of you have already done that and what experience can you share about it how to manage version conflicts what to do with databases can you make appear a message with whats new if it is an update but nothing it is a new installation should you backup old data before updating and how did you run into any trouble and how did you solve it can update be partial like just a patch any advice is welcome,['android'] +15103,whats the most optimal way to get a random floatingpoint number between floata and floatb i have an interval consisting of two float numbers and need to generate 20 random numbers in a look that are somewhere inbetween this interval defined by the two floatslets say for examplefloat a 1249953ffloat b 3911234ffloat r best way to get best randomly numbers between a and bthe random number may be a and b what would you suggest i know that all computers and languages have problems with random numbers and that there are many ways to generate them but i have no experience in objective cit is pretty important that the numbers that are generated are not the same in one block of 20 numbers that are generated in the loop i think for that i would make a method put the number in an array and check if the generated number differs from all others in the array and if it doesnt i would generate another onei have tried thiscgfloat r 1 arc4random 5but that will only generate integers and most of the time i get 2 times the same random number after another,"['iphone', 'objective-c']" +15106,sql server extract table metadata description fields and their data types i am trying to find a way to extract information about my tables in sql server 2008the data i need needs to include the description of the table filled from the description property in the properties window a list of fields of that table and their respective data typesis there any way i can extract such metadata i presume i have to use some sys sp but in not sure which one,['sql'] +15109,does dropping a table in mysql also drop the indexes it is not explicitly mentioned in the documentation i ask because i just saw a curious database migration in a rails project where the developer was removing all the indexes before dropping the table and that seemed unnecessary,['mysql'] +15120,why python compile the source to bytecode before interpreting why python compile the source to bytecode before interpretingwhy not interpret from the source directly,['python'] +15128,how to run php script in eclipse i installed eclipse pdtallinonewin32200ga and wampserver 20i try to run as php script in eclipse but i have this errorthe current debugger does not have any defined php executable how do i create this exe,['php'] +15143,has many and single table inheritance i have a has many relationship between two entities feeds and posts i also have specific types of posts videos and photos this is structured in the database using single table inheritanceright now i have my feed model specifying a has many relationship between feeds and posts including the subtypesclass feed activerecordbase has many posts has many photos has many videosis there a better more conventional way to specify this or is what i have as simple as it can get,['ruby-on-rails'] +15144,how do i get the executing object for a stackframe when using reflection it is possible to obtain the call stack apart from that it can be a crude approximation due to jit optimizations using systemdiagnosticsstacktrace and examine the stackframe objects containedhow can i get a reference to the object the thispointer on which a method in a stack frame is executingi know i can get the methodbase by calling getmethod on the stack frame object but what i am looking for is something along the lines of getobject whichd naturally return null if the method is static it seems like the stack frame object can only be queried for statically determined info such as method info originating file etcthe vs debugger knows although it probably use another method of obtaining the call stack trace as one can double click any stack frame in the call stack window and look at the values of the locals and class fieldseditto clarify i want the object instance on which the method was called ie if method foo is called on object instance a somewhere on the call stack and it cascades to the method i do the stack trace i would like to obtain a reference to a from where i perform the stack trace not the declaring type of the method base,['c#'] +15145,how can i get a precise time for example in milliseconds in objectivec is there an easy way to get a time very precisely i need to calculate some delays between method calls more specifically i want to calculate the speed of scrolling in an uiscrollview,"['iphone', 'objective-c']" +15155,accurate timing of functions in python i am programming in python on windows and would like to accurately measure the time it takes for a function to run i have written a function time it that takes another function runs it and returns the time it took to rundef time itf args start timeclock fargs return timeclock start10i call this 10 times and average the result the 10 constant at the end is to give the answer in millisecondsthis function seems to work but i have this nagging feeling that i am doing something wrong and that by doing it this way i am using more time than the function actually uses when its runningis there a more standard or accepted way to do thiswhen i changed my test function to call a print so that it takes longer my time it function returns an average of 25 ms while the cprofilerunf returns and average of 70 ms i figured my function would overestimate the time if anything what is going on hereone additional note it is the relative time of functions compared to each other that i care about not the absolute time as this will obviously vary depending on hardware and other factors,['python'] +15159,jquery call function after load need to call a filter function on some options based on a radio selected link here how can i call this after the page is loaded the radio is set from a db call and i would like to filter the options,['jquery'] +15160,how do i format a double to currency rounded to the nearst dollar right now i have double numba 52126312stringformat0c converttoint32numba this will give me521300but i do not want the 00 i know i can just drop the last three characters of the string every time to achieve the effect but seems like there should be an easier way,['c#'] +15162,better way for dynamic forms with spring what i wonder is if there is a easierbetter way to handle dynamic forms adding form items to the dom via js when using springmvc and spring formsimaging having an invoice object that have many lineitemspublic class invocie private list lineitems public invoice lineitems listutilslazylistnew arraylistlineitem factoryutilsinstantiatefactorylineitemclass to show the items belonging to an invoice i currently useforeach itemsinvoicelineitems varstatusi forminput pathlineitemsiindexproductname cforeachto add lineitems i have some js that calculates the new index and adds that to the dom when deleting a lineitem i currently have to renumber all the indexes and that is the part i would like to avoid is it possible,['java'] +15178,which iphone app ad solution gives the best rates i have a free iphone app downloaded by 30 users most of whom use my app at least once per day so i plan to show ads in my app which ad solution is best i looked in some sites but no one is giving clear details about cpmshow much will i get for 10 impressions using different ad solutions,['iphone'] +15180,iphone net wcf interoperability i am architecting a net web service and an iphone application that will consume these services i am curious if there are any best practices for architecting the protocol for exchanging data between the two soapbased web services feel too heavy to me for an iphone app perhaps rest json pox instead certainly the specifics of the application dictate the protocol to some degree but i am curious what others have doneideally i would like to leverage wcf if possible again perhaps its rest json or pox support so that i can keep my options open for creating other bindings for other client applications in the futureany advice would be greatly appreciatedthanks,"['.net', 'iphone']" +15189,can i change beautifulsoups behavior regarding converting xml tags to lowercase i am working on code to parse a configuration file written in xml where the xml tags are mixed case and the case is significant beautiful soup appears to convert xml tags to lowercase by default and i would like to change this behaviori am not the first to ask a question on this subject see here however i did not understand the answer given to that question and in beautifulsoup3101 beautifulsouppy does not appear to contain any instances of encodedname or tag str,['python'] +15195,how do i insert a large number of rows in mysql how do i insert for example 100 0 rows into mysql table with a single query,['mysql'] +15197,allow users to change font size in a webpage i would like to be able to change the size of text in a web page i guess jquery can be used but i have no experience in javascriptanother problem is that the webpage is a phtml file and multiple php echo commands are used and the page is made up of multiple phtml filesedit i would like to give users 3 choices for different font sizes,"['jquery', 'html', 'css']" +15228,how do i construct a stdstring from a dword i have following codetoolsloggerlogstringgetlasterror errorgetlasterror returns a dword a numeric value but the constructor of stdstring does not accept a dwordwhat can i do,['c++'] +15239,when zeroing a struct such as sockaddr in sockaddr in6 and addrinfo before use which is correct memset an initializer or either whenever i look at real code or example socket code in books man pages and websites i almost always see something likestruct sockaddr in foomemsetfoo 0 sizeof foo or bzero which posix marks as legacy and is not in standard c foosin port htons42instead ofstruct sockaddr in foo 0 if at least one member is initialized all others are set to zero as though they had static storage duration as per isoiec 989919 678 initialization foosin port htons42orstruct sockaddr in foo sin port htons42 new in c99 or static struct sockaddr in foo static storage duration will also behave as if all members are explicitly assigned 0 foosin port htons42the same can also be found for setting struct addrinfo hints to zero before passing it to getaddrinfo for examplewhy is this as far as i understand the examples that do not use memset are likely to be the equivalent to the one that does if not better i realize that there are differencesmemset will set all bits to zero which is not necessarily the correct bit representation for setting each member to 0memset will also set padding bits to zeroare either of these differences relevant or required behavior when setting these structs to zero and therefore using an initializer instead is wrong if so why and which standard or other source verifies this if both are correct why does memsetbzero tend to appear instead of an initializer is it just a matter of style if so that is fine i do not think we need a subjective answer on which is better stylethe usual practice is to use an initializer in preference to memset precisely because all bits zero is not usually desired and instead we want the correct representation of zero for the types is the opposite true for these socket related structsin my research i found that posix only seems to require sockaddr in6 and not sockaddr in to be zeroed at but makes no mention of how it should be zeroed memset or initializer i realise bsd sockets predate posix and it is not the only standard so are their compatibility considerations for legacy systems or modern nonposix systemspersonally i prefer from a style and perhaps good practice point of view to use an initializer and avoid memset entirely but i am reluctant becauseother source code and semicanonical texts like unix network programming use bzero eg page 101 on 2nd ed and page 124 in 3rd ed i own bothi am well aware that they are not identical for reasons stated above,['c'] +15241,how can i run several php scripts from within a php script like a batch file how can i run several php scripts from within another php script like a batch file i do not think include will work if i understand what include is doing because each of the files i am running will redeclare some of the same functions etc what i want is to execute each new php script like it is in a clean fresh stack with no knowledge of the variables functions etc that came before itupdate i should have mentioned that the script is running on windows but not on a web server,['php'] +15243,sql left join vs multiple tables on from line most sql dialects accept both the following queriesselect afoo bfoofrom a bwhere ax bxselect afoo bfoofrom aleft join b on ax bxnow obviously when you need an outer join the second syntax is required but when doing an inner join why should i prefer the second syntax to the first or vice versa,['sql'] +15244,small portable web browser library i am looking for a small and portable web browser to embed into my 3d engine basically i need something small and fast that can render into a graphical buffer and take my input for links and stuff it would be great if it could do js as wellso far i have looked at gecko and webkit and webkit is the winner so far gecko is way too huge and messy to even considerare there other more obscure engines that i am missing,"['c++', 'html']" +15245,if i make a mistake in code and cause an infinite loop in javascript and it keeps on calling alert is there a way out to stop the loop sometimes i use debug code to alert something in javascript for example matching something in regular expression but forget a modifier and and the alert is in an infinite loop or if the loop matches the pattern 300 times if using firefox the alert keeps on coming out and there is no way to even close the tab the window or the appif i force exit it will close all the tabs and even other windows of firefox is there actually a way to stop the loop more gracefully,['javascript'] +15247,how to do hibernate mapping for table or view without a primary key possible duplicatehibernate and no pk anyone knows how to do hibernate mapping for table or view without a primary key,['java'] +15250,aspnet equivalent of server side includes although the classic asp method of serverside includes works in aspnet i get the impression it is not the preferred method how am i supposed to be achieving the same effectthis is how i am doing it at the moment include file functionlibaspx,['asp.net'] +15252,set a default parameter value for a javascript function i would like a javascript function to have optional arguments which i set a default on which gets used if the value is not defined in ruby you can do it like thisdef read filefile delete after false codeenddoes this work in javascriptfunction read filefile delete after false code,['javascript'] +15256,what is your favorite feature of jquery i just had the jquery epiphany the other day and still feel like there is tons of power in it that i am not utilizingso that said what is your favorite feature of jquery that saves you time andor makes your client side applications that much more cool or powerful,['jquery'] +15257,append two or more byte arrays in c is there a best see below way to append two byte arrays in cpretending i have complete control i can make the first byte array sufficiently large to hold the second byte array at the end and use the arraycopyto function or i can loop over individual bytes and make an assignmentare there better ways i cannot imagine doing something like converting the byte arrays to string and joining them and converting them back would be better than either method abovein terms of bestbetter in orderfastestleast ram consumptiona constraint is that i must work in the net 20 frameworkthe two choices recommended are memorystream and blockcopy i have run a simple speed test of 10 loops 3 times and got the following resultsaverage of 3 runs of 10 loops in millisecondsblockcopy time 1154 with a range of 13 millisecondsmemorystream getbuffer time 1470 with a range of 14 millisecondsmemorystream toarray time 1895 with a range of 3 millisecondscopyto time 2079 with a range of 19 millisecondsbytebybyte time 2203 with a range of 10 millisecondsresults of listbyte addrange over 10 million loopslistbyte time 16694relative ram consumption 1 is baseline higher is worsebytebybyte 1blockcopy 1copy to 1memorystream getbuffer 23memorystream toarray 33listbyte 42the test shows that in general unless you are doing a lot of byte copies which i am looking at byte copies is not worth a focus eg 10 million runs yielding a difference of as much as 11 seconds,['c#'] +15262,using python to develop web application i have been doing some work in python but that was all for stand alone applications i am curious to know whether any offshoot of python supports web developmentwould some one also suggest a good tutorial or a website from where i can pick up some of the basics of web development using python,['python'] +15264,how do i scroll a richtextbox to the bottom i need to be able to scroll a richtextbox to the bottom even when i am not appending text i know i can append text and then use that to set the selection start however i want to ensure it is at the bottom for visual reasons so i am not adding any text,['c#'] +15270,why does visual studios format document tool put heading tags over two lines so if i have a html heading like thish2a headingh2and i run edit format document it ends up looking like thish2 a headingh2why is this it does not do it to other block elements but it does do it to other inline elements eg labelupdate to clarify i mean why is this the default not where are the settings to change this,['html'] +15271,how to change color of selected row in uipickerview ok maybe i am missing something really simple and i apologize if that is the case however i have googled every permutation of the title and have not found so this is simply what i want to do change the background color of the label i am using as the row view in a 2 component pickerview when that row has been selected so i thought this would workif row pickerview selectedrowforcomponent viewlabelbackgroundcolor redcolorbut this does not work it seems to arbitrarily choose which row to color and sometimes even give a bad access error i have tried all different clauses to no effect any suggestions would be greatly appreciatedheres the full method uiview pickerviewuipickerview pickerview viewforrownsintegerrow forcomponentnsintegercomponent reusingviewuiview view if component knumbercomponent define picker label font size 24define picker label alpha 10 uifont font uifont boldsystemfontofsizepicker label font size uifont font uifont fontwithnameapplegothic size24 uilabel carslabel uilabel alloc initwithframecgrectmake0 0 75 50 autorelease picker selectrowrow incomponentcomponent animatedyes nsstring pickertext selfnumbers objectatindexintrow carslabeltext pickertext carslabeltextalignment uitextalignmentcenter nslogcarslabel carslabeltext carslabeltext maybe because the string is not long enough carslabeltextcolor uicolor blackcolor carslabelfont font carslabelopaque yes view addsubviewcarslabel return carslabel else uifont font uifont fontwithnameapplegothic size18 uilabel carslabel uilabel alloc initwithframecgrectmake0 0 225 50 autorelease id fact selffacts objectatindexintrow nsstring pickertext dictionary entry if fact iskindofclassnsstring class pickertext selffacts objectatindexintrow carslabeltext pickertext carslabeltextalignment uitextalignmentcenter nslogcarslabel carslabeltext carslabeltext maybe because the string is not long enough carslabeltextcolor uicolor blackcolor carslabelfont font if row 0 carslabelbackgroundcolor uicolor redcolor carslabelbackgroundcolor uicolor colorwithpatternimageuiimage imagenamedblackboardpng carslabelopaque yes view addsubviewcarslabel return carslabel return nil,['iphone'] +15278,what are the grails advantages over other java web frameworks i have worked with jsf spring mvc and struts and i think i got a good level on these frameworks recently i heard that many good developers i worked with are learning grails and using it in their projectswhat are the practical advantages of grails over other frameworks is worth to learn it besides i know other frameworks what is all the buzz around grails is it only because of groovynote i did research in so and the only related question i found was this and grails is not mentioned,['java'] +15281,in ruby are there any related applications of the syntax class self end class selfattr accessor n totalx totalyendthe syntax above is used for defining class instance variables but when i think about what syntax implies it does not make any sense to me so i am wondering if this type of syntax is used for any other types of definitions my point of confusion here is thisclass selfthe append operator normally means add whats on the right to the object on the left but in the context of this block how does that add up to put the contents of this block into the definition of the class instance rather than the instancefor the same reason i am confused as to why in one context class self can define class instance variables while in another it seems to create class variables such as hereclass point instance methods go here class self class methods go here endend,['ruby'] +15286,sql batched delete i have a table in sql server 2005 which has approx 4 billion rows in it i need to delete approximately 2 billion of these rows if i try and do it in a single transaction the transaction log fills up and it fails i do not have any extra space to make the transaction log bigger i assume the best way forward is to batch up the delete statements in batches of 10i can probably do this using a cursor but is the a standardeasyclever way of doing thisps this table does not have an identity column as a pk the pk is made up of an integer foreign key and a date,['sql'] +15290,a good way to escape quotes in a database query string i have tried all manner of python modules and they either escape too much or in the wrong waywhats the best way youve found to escape quotes in python,['python'] +15299,large file 30mb uploads over the internet what are the better options a friend and i have been thiscussing whats the best way to send large file over the internet ftp single web services chunking bytes to multiple web services http file post multipart message ria interface silverlight or flash are there answerssolutions that are missing let me give you more of my specific situationi have a net 20 windows form client application that interacts by web services with an aspnet application in the client application i need the ability to upload a large file and communicate the status of the upload to the user i was doing a single web service but found the file size to be problematic over the internet so created multiple web services to chunk the byte array now wanting to consider other optionssome research donesilverlight file uploadwcodeplexcomsilverlightfileupldaspnet file uploadwbrettlecomneatuploadftp in net frameworkwindowsdevcentercompubawindows20061212buildingftpservicesusingnet20htmlwanting others opinions thanks,['.net'] +15304,really cheap commandline option parsing in ruby edit please please please read the two requirements listed at the bottom of this post before replying people keep posting their new gems and libraries and whatnot which clearly do not meet the requirementssometimes i want to very cheaply hack some command line options into a simple script a fun way to do it without dealing with getopts or parsing or anything like that isquiet argvdeletedinteractive argvdeletei deal with argv as usual here maybe using argf or whateverit is not quite the normal unix options syntax because it will accept options nonoption command line parameters as in myprog i foo bar q but i can live with that some people such as the subversion developers prefer this sometimes i do tooan option that is just present or absent cannot be implemented much more simply than the above one assignment one function call one side effect is there an equally simple way to deal with options that take a parameter such as f filenameeditone point i did not make earlier on because it had not become clear to me until the author of trollop mentioned that the library fit in one 800line file is that i am looking not only for clean syntax but for a technique that has the following characteristicsthe entirety of the code can be included in the script file without overwhelming the actual script itself which may be only a couple of dozen lines so that one can drop a single file in a bin dir on any system with a standard ruby 1857 installation and use it if you cannot write a ruby script that has no require statements and where the code to parse a couple of options is under a dozen lines or so you fail this requirementthe code is small and simple enough that one can remember enough of it to directly type in code that will do the trick rather than cutting and pasting from somewhere else think of the situation where youre on the console of a firewalled sever with no internet access and you want to toss together a quick script for a client to use i do not know about you but besides failing the requirement above memorizing even the 45 lines of simplified microoptparse is not something i care to do,['ruby'] +15318,jquery making simultaneous ajax requests is it possible i am using jquery to try and retrieve multiple pieces of data at the same time the background of the requirement is that different bits of data take various lengths of time to become available so i want to thisplay each piece as it is returnedthe problem is that the requests seem to queue the next request does not go until the previous one has returned after extensive reading it seems the option async false might be what i am after but this seems to make no differencefrom the tcpip debug i can see the browser does not initiate more than one connection it uses the same connection when the prior request has returnedi have seen many sites in my time which load data over ajax simultaneously so obviously it is possible but i am tearing my hair out trying to get this workinghere is my codeajax type get async false url foo1php ajax type get async false url foo2php ajax type get async false url foo3php,['jquery'] +15320,entitykey and applypropertychanges i need to set an entityobjects entitykey i know its type and its id value i do not want to query the database unnecessarilythis works post departmentedit5acceptverbshttpverbspostpublic actionresult editguid id department model modelentitykey from department d in dbdepartment where did id select dfirstordefaultentitykey dbapplypropertychangesmodelentitykeyentitysetname model dbsavechanges return redirecttoactionindexthis fails post departmentedit5acceptverbshttpverbspostpublic actionresult editguid id department model string entitysetname dbdefaultcontainername modelgettypename modelentitykey new systemdataentitykeyentitysetname id modelid dbapplypropertychangesmodelentitykeyentitysetname model dbsavechanges return redirecttoactionindexthe applypropertychanges line fails with this exceptionthe objectstatemanager does not contain an objectstateentry with a reference to an object of type samplemodelsdepartmentthe two entitykeys are equal why does the second block of code fail how can i fix it,"['c#', '.net']" +15333,bc30560 default aspx is ambiguous in the namespace asp when i compiled my latest aspnet program and trying to run on the test server i am getting this errorline 46 dim dependencies as stringline 47 ctypemeglobalsystemwebuipageapprelativevirtualpath defaultaspxline 48 if globalaspdefault aspx initialized false thenline 49 dependencies new string0 line 50 dependencies0 defaultaspxsource file cwindowsmicrosoftnetframeworkv2050727temporary aspnet filesocbuildc0c442f0292c99app web defaultaspxcdcab7d24ubu1wgu0vb line 48detailed errors when i expand the compiler outputmicrosoft r visual basic compiler version 80507273053for microsoft r net framework version 20507273053copyright c microsoft corporation all rights reservedcwindowsmicrosoftnetframeworkv2050727temporary aspnet filesocbuildc0c442f0292c99app web defaultaspxcdcab7d24ubu1wgu0vb48 error bc30560 default aspx is ambiguous in the namespace asp if globalaspdefault aspx initialized false then cwindowsmicrosoftnetframeworkv2050727temporary aspnet filesocbuildc0c442f0292c99app web defaultaspxcdcab7d24ubu1wgu0vb51 error bc30560 default aspx is ambiguous in the namespace asp globalaspdefault aspx filedependencies megetwrappedfiledependenciesdependencies cwindowsmicrosoftnetframeworkv2050727temporary aspnet filesocbuildc0c442f0292c99app web defaultaspxcdcab7d24ubu1wgu0vb52 error bc30560 default aspx is ambiguous in the namespace asp globalaspdefault aspx initialized true cwindowsmicrosoftnetframeworkv2050727temporary aspnet filesocbuildc0c442f0292c99app web defaultaspxcdcab7d24ubu1wgu0vb76 error bc30560 default aspx is ambiguous in the namespace asp private sub buildcontroltreebyval ctrl as default aspx cwindowsmicrosoftnetframeworkv2050727temporary aspnet filesocbuildc0c442f0292c99app web defaultaspxcdcab7d24ubu1wgu0vb100 error bc30560 default aspx is ambiguous in the namespace asp meaddwrappedfiledependenciesglobalaspdefault aspx filedependencies cwindowsmicrosoftnetframeworkv2050727temporary aspnet filesocbuildc0c442f0292c99app web defaultaspxcdcab7d24ubu1wgu1vb31 error bc30560 default aspx is ambiguous in the namespace asp return new aspdefault aspx i checked a few things and all of them turned out to be okay default is not defined twice anywhere everything was working on the last release 1 week back there are no old files that are still staying with the compiled files also i cleared the temporary files many times i have tried with other aspx files and all of them is giving ambiguous error error in different source files the original source works just fine only the error shows up on the compiled codeany ideas or any clues on how to resolve this ambiguitythankssk,['asp.net'] +15338,how to copy the contents of a string to the clipboard in c if i have some text in a string how can i copy that to the clipboard so that the user can paste it into another window eg from my application to notepad,"['c#', '.net']" +15341,how do i write unit tests in php with a procedural codebase i am mostly convinced of the benefits of unit testing and i would like to start applying the concept to a large existing codebase written in php less than 10 of this code is objectorientedi have looked at several unit testing frameworks phpunit simpletest and phpt however i have not found examples for any of these that test procedural code whats the best framework for my situation and are there any examples of unit testing php using nonoop code,['php'] +15348,how can i add cgpoint objects to an nsarray the easy way i have about 50 cgpoint objects that describe something like a path and i want to add them to an nsarray it is going to be a method that will just return the corresponding cgpoint for an given index i do not want to create 50 variables like p1 p2 and so on is there an easy way that would let me to define those points instantly when initializing the nsarray with objects,"['iphone', 'objective-c']" +15354,example of a multi condition delete with zend framework can someone give me an example of how i would delete a row in mysql with zend framework when i have two conditionsie trying to do thisdelete from messages where message id 1 and user id 2my code that is failing miserably looks like this is this our messagecondition array message id messageid profile id useridn dbdeletemessages condition,"['php', 'mysql']" +15358,difference between long and int data types considering that the following statements return 4 what is the difference between the int and long types in csizeofintsizeoflong,['c++'] +15359,c project source code layout one of the popular way to organize project directory is more or less like thismylib mylib class ah mylib class acpp mylib library private helpersh mylib library private helperscppmyapp other classh other classcpp appcppappcppinclude other classhinclude mylib class ah using library myliball h and cpp files for the same library are in the same directory to avoid name collision file names are often prefix with company name andor library name mylib will be in myapps header search path etc i am not a fan of prefixing filenames but i like the idea of looking at the include and know exactly where that header file belongs i do not hate this approach of organizing files but i think there should be a better waysince i am starting a new project i want to solicit some directory organization ideas currently i like this directory structureproja include proja mylib class ah app other classh src mylib class acpp library private helpersh library private helperscpp app other classcpp appcpp utilhappcppinclude utilh private utilh fileinclude projaappother classh public header fileinclude projamylibclass ah using class ah of mylibinclude other3rdptylibclass ah class ah of other3rdptylib no name collisioninclude class ah not projamylibclass ahinclude projamyliblibrary private helpersh error cannot find hcpp files and private only visible to immediate library h files are stored under the src directory src is sometimes called lib public header files are organized into a projectlib directory structure and included via projectnamelibrarynameheadernameh file names are not prefixed with anything if i ever needed to package up mylib to be used by other teams i could simply change my makefile to copy the appropriate binary files and the whole includeproja directoryonce files are checked into source control and people start working on them it will be hard to change directory structure it is better to get it right at the getgo anyone with experience organizing source code like this anything you do not like about it if you have a better way to do it i would very much like to hear about it,['c++'] +15361,elegant way to compare sequences does python provide an elegant way to check for equality of sequences of different types the following work but they seem rather ugly and verbose for python codedef comp1a b if lena lenb return false for i v in enumeratea if v bi return false return truethe following is a bit shorter but also less efficient since a third sequence is createddef comp2a b for l r in mapnone a b if l r return false return trueshoehorning one of those examples into a list comprehension is not really what i am looking for eitheredit ideally i am looking for a solution that does not create another sequence during the comparison,['python'] +15372,is the mavennativeplugin widely used to build c projects using maven it is been a little while since i did c development professionally and i would like to get caught up on what the current state of c development is in a number of areas most of my recent work has been java making heavy use of maven when i last did c development for work some variant of make was widely accepted as the way to go for building c projects we were also using make to do builds the java code in our mixed java and c projects although i believe ant was starting to become mainstream i like using maven for builds my question is not to debate the relative merits of using maven but to determine what the level of adoption is for the native maven plugin for building c projects and what peoples experience with this has been alternately is there a new common toolchain for c builds that has a lot of momentum,"['java', 'c++']" +15373,how to send data to com port using java possible duplicatejava serial communication on windows friendsi want to connect and transfer data to com port either virtual or original in java,['java'] +15383,core data primary key this may seem stupid but i still could not figure out how to mark a attribute as a primary key in the xcdatamodel filemy persistent storage is sqlite filecan anyone help mein that case how can i validate a id to be uniqueshould i write a validation method or something,['iphone'] +15394,unzip strings in javascript anyone knows a simple javascript library implementing the unzip algorithm no thiskfile access only zip and unzip a string of valuesthere are activex using winzip and other client dependent software for zip written in js but no pure javascript algorithm implementationi would use it for thisplaying kmz files in a html page with the gmap object google maps the kmz file is just a zipped kml file i want to unzip a kmz file and feed the kml to gmap,['javascript'] +15407,data storage to ease data interpolation in python i have 20 tables similar to table 1 where all letters represent actual valuestable 1 cars 1 2 3 410 a b c d20 e f g h30 i j k l40 m and o pa user input could be for example 24 24594 which is a value between f g j and kmy python function definition and pseudocode to calculate this bilinear interpolation is as followsdef bilinear interpolation x in y in x high x low y low y high interpolate with respect to x interpolate with respect to y return resulthow should i store the data from table 1 a file a dict tuple of tuples or dict of lists so i can perform the bilinear interpolation most efficiently and correctly,['python'] +15408,iphone convert date string to a relative time stamp i have got a timestamp as a string likethu 21 may 09 191009 0700and i would like to convert it to a relative time stamp like 20 minutes ago or 3 days agowhats the best way to do this using objectivec for the iphone,"['iphone', 'objective-c']" +15411,should i always give a return value to my function i write javascript code and i try to use its functional language naturein other functional languages or even in ruby if i do not explicitly set the return value of a function it will return the value of the last evaluated expression javascript does not follow this pattern to be precise javascript always returns a value as well if nothing was set then undefinedmy question is the following i have a function that does not need to and does not return a value does it make sense in a functional programming context to have a function with no explicit return value or did a fail somewhere if i found myself in this casefor example i have the following function it checks periodically if location hash was changed and if so calls the given functionlib hashmanager functionf context var prev var pollhash function if prev windowlocationhash prev windowlocationhash fapplycontext windowsetintervalpollhash 100should i return here anythingupdatemeanwhile it came to my mind that if anytime in the future i will need to extend the knowledge of lib hashmanager following the functional constructor pattern i can simply add methods to an object and lib hashmanager will return that produced objectlib hashmanager functionf context inside logic and later i may writelib hashmanager functionf context inside logic return public methods return so does not make sense then to return an empty object in the first case,['javascript'] +15412,hasattr vs tryexcept block to deal with nonexistent attributes if hasattrobj attribute do somthingvstry access objattributeexcept attributeerror e deal with attributeerrorwhich should be preferred and why,['python'] +15414,in ruby on rails 232 how to print out params during a create action there is a scaffold created story and in the create action there isstory storynewparamsstoryi was curious as to what is in params so i want to dump out params but there is no view associated with the create action is there a way to dump out its content is there a way to dump out the post variables in of my code too to see whats going on in the lower level,['ruby-on-rails'] +15419,how should i load native libraries for jni to avoid an unsatisfiedlinkerror i want to use jni on ubuntu 810 using eclipse and gcc the standard one with ubuntu if there are flavoursi cannot seem to load my library despite the make file creating it successfullythe main java class is as followsclass hello public native void sayhello static systemloadlibraryhelloso public static void mainstring args hello h new hello hsayhello my make file is as such all hellosohelloso helloo gcc shared o helloso helloohelloo helloc helloh gcc iusrlibjvmjava6suninclude iusrlibjvmjava6sunincludelinux c helloc o helloohelloh helloclass javah jni helloclean del helloh del helloothe rest of the code helloc looks like one would thinkthe error i am getting is as followsexception in thread main javalangunsatisfiedlinkerror no helloso in javalibrarypathif i use an explicit pathsystemloadlibraryhomegavinworkworkspacejnihellosothen it works but i would much rather not use an explicit path if possible,"['java', 'c']" +15423,java 2d game engine for tilebased game can anyone recommend a good java game engine for developing simple tilebased games i am looking for an engine that will allow me to build maps using something like tiled wmapeditororgslick is exactly what i am looking for slickcokeandcodecom but i cannot get it working on vista64 the best i can manage iscannot load ia 32bit dll on a amd 64bit platform and this after downloading the latest lwjgl version can anyone suggest something similar that will run on 64bit vista,['java'] +15427,how to run an osgi framework within usual javacode can anybody give me an example how to use the osgi framework classes i have not a clue how to use those classes brmarkus,['java'] +15431,the wrong python interpreter is called i updated my python interpreter but i think the old one is still called when i check for the version i get python vpython 301but i believe the old interpreter is still being called when i run the commandpython myprogpythe script runs properly but when i invoke it with the commandmyprogpyi get the error messageattributeerror str object has no attribute formatwhich apparently is due to the old interpreter being called how can i fix this i run mac os x 105 has it something to do with the first lineusrbinpythoni just started out with python and am not very familiar with interpreted languages so i am not too sure what is going onedit wow that was quick thanks a lot,['python'] +15438,how can i add a right click menu to finder how can i add a custom view to the right click menu of every file in os x findereg i want to thisplay the image if it is an image type and do some custom action etcis this possible with c or objectivec if yes how without using any available tool,['objective-c'] +15449,how do i round a float up to the nearest int in c in c how do i round a float to the nearest inti see mathceiling and mathround but these returns a decimal do i use one of these then cast to an int,"['c#', '.net']" +15453,resources concerning python scripting in vim i am trying to learn a little about python scripting in gvim but i am having trouble with starting elementary things reallyare there any resources tutorials concerting python scripting in vim out there simple examples which show the basic principles would be welcomed also,['python'] +15463,what use is reflection in net possible duplicateswhen do you use reflection patternsantipatternswhat exactly is reflection and when is it a good approach what is the need for reflection in net what are the situations where it comes in handy,['.net'] +15473,javascript validation block special characters how can i restrict users from entering special characters in the text box i want only numbers and alphabets to be entered typed pasted any samples,['javascript'] +15486,jstack and not enough storage is available to process this command i am trying to run jstack command on my java application application is rather big running inside jboss as occupying about 4gb of memory os is windows server 2003 standard edition every time i get an error not enough storage is available to process this command there is enough ram 16gb and thisk space so any ideas,['java'] +15493,why is javascript considered bad by some why is javascript allowed to be thisabled in the browser ie why is it considered bad,['javascript'] +15500,tabbing in c resource file hihow do i add a tab t to a string resource ttext does not work,['c#'] +15501,java getminutes and gethours how do you get hours and minutes since dategethours and dategetminutes got deprecated the examples that i found on google search used the deprecated methods,['java'] +15503,simultaneously stream and save a video i am writing an app part of which allows the user streamplay videos i want to restrict the functionality so that they can only stream videos if they have a wifi connection i will then save the video so that when they have a 3g only or lesser connection they cannot stream videos and can only replay videos that are saved on the phoneideally i would like to get mpmovieplayercontroller to streamplay the movie and then access the movie data and save it however the mpmovieplayercontroller api does not seem to support access to the movie datai would like to avoid and downloadthenplay scenario any ideas,['iphone'] +15508,can someone explain classcastexception in java i read some articles written on classcastexception but i could not get a good idea on that can someone direct me to a good article or explain it briefly,['java'] +15509,how can i tell if a point belongs to a certain line how can i tell if a point belongs to a certain lineexamples are appreciated if possible,"['c#', '.net']" +15513,gather all python modules used into one folder i do not think this has been asked beforei have a folder that has lots of different py files the script i have made only uses somebut some call others i do not know all the ones being used is there a program that will get everything needed to make that script run into one foldercheers,['python'] +15514,css printing avoiding cutinhalf divs between pages i am writing a plugin for a piece of software that takes a big collection of items and pops them into html in a webview in cocoa which uses webkit as its renderer so basically you can assume this html file is being opened in safarithe divs it makes are of dynamic height but they do not vary too much they are usually around 200px anyway with around sixhundred of these items per document i am having a really rough time getting it to print unless i get lucky there is an entry chopped in half at the bottom and top of every page and that makes actually using printouts very difficulti have tried pagebreakbefore pagebreakafter pagebreakinside and combinations of the three to no avail i think it might be webkit not properly rendering the instructions or maybe it is my lack of understanding of how to use them at any rate i need help how can i prevent the cuttinginhalf of my divs when printing,['css'] +15516,how do you prevent a windows from being moved how would i go about stopping a form from being moved i have the form border style set as fixedsingle and would like to keep it this way because it looks good in vista,"['c#', '.net']" +15517,how do i put data to rails using jquery i am trying to send a jquery ajax put request that looks like thisajax type put url adminpages1json data page datatype json success functionmsg alert data saved msg but i get the following errorthe error occurred while evaluating nilname libraryrubygems18gemsactivesupport232libactive supportxml minirexmlrb29in merge element libraryrubygems18gemsactivesupport232libactive supportxml minirexmlrb18in parse delegation 2in send delegation 2in parse libraryrubygems18gemsactivesupport232libactive supportcore exthashconversionsrb154in from xml is like rails is trying to parse the params as xml but i want to use jsonwhat shall i do to put json to rails,"['jquery', 'ruby-on-rails']" +15518,optimizing lookups dictionary key lookups vs array index lookups i am writing a 7 card poker hand evaluator as one of my pet projects while trying to optimize its speed i like the challenge i was shocked to find that the performance of dictionary key lookups was quite slow compared to array index lookupsfor example i ran this sample code that enumerates over all 52 choose 7 133784560 possible 7 card handsvar intdict new dictionaryint intvar intlist new listintfor int i 0 i 10 i intdictaddi i intlistaddiint resultvar sw new stopwatchswstartfor int card1 0 card1 46 card1 for int card2 card1 1 card2 47 card2 for int card3 card2 1 card3 48 card3 for int card4 card3 1 card4 49 card4 for int card5 card4 1 card5 50 card5 for int card6 card5 1 card6 51 card6 for int card7 card6 1 card7 52 card7 result intdict32131 perform c527 dictionary key lookupsswstopconsolewritelinetime for dictionary lookups 0 ms swelapsedmillisecondsswresetswstartfor int card1 0 card1 46 card1 for int card2 card1 1 card2 47 card2 for int card3 card2 1 card3 48 card3 for int card4 card3 1 card4 49 card4 for int card5 card4 1 card5 50 card5 for int card6 card5 1 card6 51 card6 for int card7 card6 1 card7 52 card7 result intlist32131 perform c527 array index lookupsswstopconsolewritelinetime for array index lookups 0 ms swelapsedmillisecondswhich outputstime for dictionary lookups 2532 mstime for array index lookups 313 msis this type of behavior expected performance decrease by a factor of 8 iirc a dictionary has on average o1 lookups while an array has worstcase o1 lookups so i do expect the array lookups to be faster but not by this muchi am currently storing poker hand rankings in a dictionary i suppose if this is as fast as the dictionary lookups can be i have to rethink my approach and use arrays instead although indexing the rankings will get a little tricky and i will probably have to ask another question about it,"['c#', '.net']" +15524,rails dashboard design one controller action per div i am implementing a dashboard as a relative rails newbie more of an infrastructure guy the dashboard will consist of multiple pages each page of which will contain multiple chartstablesetc for modularity i want it to be as easy as possible to add new charts or change views of the datasay one page has 5 different charts i could have the controller do 5 separate data lookups hold all the relevant data in instance variables and render 5 partials each of which touch subsets of the data but it seems more modular to have one index controller action whose render has a bunch of divs and for each div there is another controller action which does the data lookup and has an associated view partial in charge of managing the view of that data within the div so if i am showing the website dashboard page which has two graphs websiteindex would use websitegraph1 and websitegraph2 to look up the data for each and then graph1htmlerb and graph2htmlerb would use the controller data to fill out divs graph1 and graph2 etc is this the right design and if so whats the easiest way to accomplish this i have an approximation using remote function with action graph1 to fill out divs but i am not 100 happy with it i suspect i am missing something easier that rails will do for me,"['ruby-on-rails', 'ruby']" +15527,is not cs inline totally optional i have a class that had an inline member but i later decided that i wanted to remove the implementation from the headers so i moved the members body of the functions out to a cpp file at first i just left the inlined signature in the header file sloppy me and the program failed to link correctly then i fixed my header and it all works fine of coursebut was not inline totally optionalin codefirstclasshclass myclass void inline foo next changed to would not linkclasshclass myclass void inline fooclasscppvoid myclassfooand then to will work fineclasshclass myclass void fooclasscppvoid myclassfooi thought inline was optional and imagined i might get by with a warning for my sloppiness but did not expect a linking error whats the correctstandard thing a compiler should do in this case did i deserve my error according to the standard,['c++'] +15528,get installed applications in a system how to get the applications installed in the system using c code,"['c#', '.net']" +15554,reading from excel range into multidimensional array c how would i read from an excel sheet and load the marked selection area into an multidimensional array a column in excel could itself be a multi dimensional array since it would contain more than just one valuethe idea not sure how good or bad this is is right now is to do a for loop through all the excelarea selected fields and add the content of that field to the multi dimensional array since the multi dimensional array is of type object and therefore nongeneric there is no convenient add method to it all of it needs to be done manuallyany idea if this approach is ok or if it could be done more efficientltymany thanks,['c#'] +15565,cancelling a long running regex match say i am running a service where users can submit a regex to search through lots of data if the user submits a regex that is very slow ie takes minutes for matcherfind to return i want a way to cancel that match the only way i can think of doing this is to have another thread monitor how long a match is taking and use threadstop to cancel it if necessarymember variableslong regex timeout 30lobject lock new objectboolean finished falsethread matcherthreadmatcher threadtry matcherthread threadcurrentthread imagine code to start monitor thread is here try matched matcherfind finally synchronized lock finished true locknotifyall catch threaddeath td send angry message to client handle error without rethrowing tdmonitor threadsynchronized lock while finished try lockwaitregex timeout if finished matcherthreadstop catch interruptedexception ex ignore top level method in dedicated thread etc i have read javasuncomj2se142docsguidemiscthreadprimitivedeprecationhtml and i think this usage is safe since i am controlling where threaddeath is thrown via synchronisation and handle it and the only damaged objects could be my pattern and matcher instances which will be thiscarded anyway i think this breaks threadstop because i am not rethrowing the error but i do not really want the thread to die just abort the find methodi have managed to avoid using these deprecated api components so far but matcherfind does not seem to be interruptible and can take a very long time to return is there any better way to do this,['java'] +15585,warning about hiding member variables the following code snippet has a memory leak that i spent too much time chasing down the problem is that inside foo the local variable x hides the member variable x it is quite annoying too because the compiler could have warned me about it is there a flag in gcc for such a warning for the curious i have arrived at the buggy code by first using a local variable then changing it to a member variable but forgetting to remove the type declarationstruct a a x null a delete x void foo hugethingy x new hugethingy x bari need garbage collection now hugethingy x thisallow copy and assigna macro to prevent copyassign,['c++'] +15587,how do i define my own selectablechannel how would i define a new type of javaniochannelsselectablechannel say for serial ports,['java'] +15590,python best practices abstract syntax trees modifying abstract syntax treesi would like to be able to build and modify an ast and then optionally write it out as python byte code for execution later without overheadi have been hacking around with the ast docs for python30 and python26 but i cannot seem to find any good sources on best practices for this type of codequestionwhat are some best practices and guidelines for modifying abstract syntax trees in pythoneditunknown states that byteplay is a good example of such a libraryalso benford cites geniusql which uses abstract syntax trees to transform python code to sql,['python'] +15599,throw exceptions with custom stack trace is it possible to throw an exception could be any exception with a customized stack traceas a concrete example lets say i have a set of some small static utility methods which might throw exceptions however i would like the exception to appear to have originated from the previous method instead of the utility method i want to ignore the 1st frame of the trace,['.net'] +15600,xdocument cannot load xml with version 11 in c linq xdocumentload throws exception when using xml file name of xml with version 11 instead of 10any clean solutions to resolve the error no regex and load the document,['c#'] +15604,invalid or expired security context token in wcf web service alli have a wcf web service let us called service b hosted under iis using a service account vm windows 2003 sp2 the service exposes an endpoint that use wshttpbinding with the default values except for maxreceivedmessagesize maxbufferpoolsize maxbuffersize and some of the time outs that have been increasedthe web service has been load tested using visual studio load test framework with around 800 concurrent users and successfully passed all tests with no exceptions being thrown the proxy in the unit test has been created from configurationthere is a sharepoint application that use the office sharepoint server search service to call web services a and b the application will get data from service a to create a request that will be sent to service b the response coming from service b is indexed for search the proxy is created programmatically using the channelfactory when service a takes less than 10 minutes the calls to service b are successfull but when service a takes more time 20 minutes the calls to service b throw the following exceptionexception message an unsecured or incorrectly secured fault was received from the other party see the inner faultexception for the fault code and detailinner exception message the message could not be processed this is most likely because the action namespaceoperationname is incorrect or because the message contains an invalid or expired security context token or because there is a mismatch between bindings the security context token would be invalid if the service aborted the channel due to inactivity to prevent the service from aborting idle sessions prematurely increase the receive timeout on the service endpoints bindingthe binding settings are the same the time in both client server and web service server are synchronize with the windows time service same time zonewhen i look at the server where web service b is hosted i can see the following security errors being loggedsource securitycategory logonlogoffevent id 537user nt authoritysystemlogon failurereason an error occurred during logonlogon type 3logon process kerberosauthentication package kerberosstatus code 0xc06dsubstatus code 0xc0133after reading some of the blogs online the status code means status logon failure and the substatus code means status time difference at dc but i already checked both server and client clocks and they are syncronizedi also noticed that the security token seems to be cached somewhere in the client server because they have another process that calls the web service b using the same service account and successfully gets data the first time is called then they start the proccess to update the office sharepoint server search service indexes and it fails then if they called the first proccess again it will fail toohas anyone experienced this type of problems or have any ideasregardsdamian,['c#'] +15613,using subprocess to run python script on windows is there a simple way to run a python script on windowslinuxos xon the latter two subprocesspopenthescriptpy works but on windows i get the following errortraceback most recent call last file test functionalpy line 91 in test functional log tvnamerifiytmp file test functionalpy line 49 in tvnamerifiy stdout pipe file cpython26libsubprocesspy line 595 in init eread errwrite file cpython26libsubprocesspy line 804 in execute child startupinfowindowserror error 193 1 is not a valid win32 applicationmonkuts comment the use case is not clear why use subprocess to run a python script is there something preventing you from importing the script and calling the necessary functioni was writing a quick script to test the overall functionality of a pythoncommandline tool to test it on various platforms basically it had to create a bunch of files in a temp folder run the script on this and check the files were renamed correctlyi could have imported the script and called the function but since it relies on sysargv and uses sysexit i would have needed to do something likeimport sysimport tvnamersysargvappendb thefoldertry tvnamermainexcept baseexception errormsg print typeerrormsgalso i wanted to capture the stdout and stderr for debugging incase something went wrongof course a better way would be to write the script in more unittestable way but the script is basically done and i am doing a final batch of testing before doing a 10 release after which i am going to do a rewriterestructure which will be far tidier and more testablebasically it was much easier to simply run the script as a process after finding the sysexecutable variable i would have written it as a shellscript but that wouldnt have been crossplatform the final script can be found here,['python'] +15614,c intellectual property protectionantireversing i have seen a lot of thiscussion on here about copy protection i am more interested in antireversing and ip protectionthere are solutions such as safenet and hasp that claim to encrypt the binary but are these protected from reversing when used with a valid keywhat kinds of strategies can be used to obfuscate code and throw off reversers are there any decent commercial implementations out therei know most protection schemes can be cracked but the goal here is to delay the ability to reverse the software in question and make it much more blatant if another company tries to implement these methods,['c++'] +15619,how to target the blackberry browser i am using the following to target iphones and handheld devices to use specific mobile styles sheets but the blackberry browers is picking up only the regular screen style sheetslink mediahandheld only screen and maxdevicewidth 320px hrefmobilecss typetextcss relstylesheet link mediaonly screen and maxdevicewidth 480px hrefmobilecss typetextcss relstylesheet all the other mobile devices i have tested the site on are picking up the correct style sheetsdoes anyone know a way to target the blackberry browser to do the samethanks,['css'] +15621,why does push back or push front invalidate a deques iterators as the title asksmy understanding of a deque was that it allocated blocks i do not see how allocating more space invalidates iterators and if anything one would think that a deques iterators would have more guarantees than a vectors not less,['c++'] +15622,how to capitalize the first character of each word or the first character of a whole string with c i could write my own algorithm to do it but i feel there should be the equivalent to rubys humanize in c i googled it but only found ways to humanize datesexamplesa way to turn lorem lipsum et into lorem lipsum et a way to turn lorem lipsum et into lorem lipsum et,['c#'] +15625,is there any runtime overhead to readonly for some reason i have always assumed that readonly fields have overhead associated with them which i thought of as the clr keeping track of whether or not a readonly field has been initialized or not the overhead here would be some extra memory usage to keep track of the state and a check when assigning a value perhaps i assumed this because i did not know a readonly field could only be initialized inside a constructor or within the field declaration itself and without a runtime check you wouldnt be able to guarantee it is not being assigned to multiple times in various methods but now i know this it could easily be statically checked by the c compiler right so is that the case another reason is that i have read that the usage of readonly has a slight performance impact but they never went into this claim and i cannot find information on this subject hence my question i do not know what other performance impact there might be aside from runtime checks a third reason is that i saw that readonly is preserved in the compiled il as initonly so what is the reason for this information to be in the il if readonly is nothing more than a guarantee by the c compiler that the field is never assigned to outside of a constructor or declarationon the other hand i have found out you can set the value of a readonly int through reflection without the clr throwing an exception which should not be possible if readonly was a runtime check so my guess is the readonlyness is only a compile time feature can anyone confirmdeny this and if it is what is the reason for this information to be included in the il,['c#'] +15628,iphone sdk how do you measure the width and height of a string using quartz before i ask my questions this is from apples documentation re how to determine the width of a string using quartzif text measurements are important to your application it is possible to calculate them using quartz 2d functions however you might first consider using atsui whose strength is in text layout and measurement atsui has several functions that obtain text metrics not only can you obtain afterlayout text metrics but in the rare cases you need them you can obtain beforelayout text metrics unlike quartz for which you must perform the calculations yourself atsui computes the measurements for you for example you can obtain the image bounding rectangle for text by calling the atsui function atsumeasuretextimageif you decide that quartz text suits your needs better than atsui or cocoa you can follow these steps to measure the width of text before quartz draws itcall the function cgcontextgettextposition to obtain the current text positionset the text drawing mode to kcgtextinvisible using the function cgcontextsettextdrawingmodedraw the text by calling the function cgcontextshowtext to draw the text at the current text positiondetermine the final text position by calling the function cgcontextgettextpositionsubtract the starting position from the ending position to determine the width of the texthere are my questionsis this really the best way to determine the width of a string using core graphics it seems flimsy and since my text coexists with 2d graphical elements i would like to use the same context for all rendering i was hoping there would be some compact method likecgcontextgettextwidthandheightcontext texti read that atsui is outdated and going to be replaced by core text is that true and if so is it in the iphone sdki apologize in advance if these are basic questions but i have been googling for hours and cannot find meaningful information,"['iphone', 'objective-c']" +15629,what is static i am beginning to program in javapublic static void mainstringargsa book said that i should use static in this case but does not clearly say why i should or what it meanscould you clarify this,['java'] +15631,django error too many values to unpack i am learning django by building a simple recipes app i have a 1 table model using the choices field option for recipe categories rather than using a 2nd categories table and a foreign key relationship so i created db table via syncdb and then loaded table with test data when i go to admin and click on the recipes link in an attempt to view recipes i get the following errortemplate errorin template varlibpythonsupportpython26djangocontribadmintemplatesadminchange listhtml error at line 34caught an exception while rendering too many values to unpackif anyone can shed light on this cryptic error that would be great db is sqlite django version is 10 the model is listed belowfrom djangodb import modelsclass recipemodelsmodel category choices 1 uappetizer 2 ubread 3 udessert 4 udrinks 5 umain course 6 usalad 7 uside thish 8 usoup 9 usaucemarinade 10 uother name modelscharfieldmax length255 submitter modelscharfieldmax length40 date modelsdatetimefield category modelssmallintegerfieldchoicescategory choices ingredients modelstextfield directions modelstextfield comments modelstextfieldnulltrue blanktrue,['python'] +15636,confusion on iterators invalidation in deque i am bit confused regarding iterator invalidation in deque in the context of this questionfollowing is the excerpts from the c standard library a tutorial and reference by nicolai m josuttis any insertion or deletion of elements other than at the beginning or end invalidates all pointers references and iterators that refer to elements of the dequefollowing is the excerpts from sgi sitethe semantics of iterator invalidation for deque is as follows insert including push front and push back invalidates all iterators that refer to a deque erase in the middle of a deque invalidates all iterators that refer to the deque erase at the beginning or end of a deque including pop front and pop back invalidates an iterator only if it points to the erased elementimho deque is collection of blocks with first block growing in one direction and the last block in opposite direction v push back push front should not have any impact on deque iterators i agree with josuttiswhat is the correct explanation what the standard say on this,['c++'] +15637,unit testing in c i have been reading a lot about unit tests and test driven developemntrecently i also read java unit test codei however prefer to develop in qt so i googled up unit testing in c and found a host of information about various unit testing frameworks available for chowever i could not find a reliable comparison of the the various frameworksso i look to the so community to guide me through the selection of what may the best unit testing framework for calso if anybody had specific comments regarding tdd in qt especially using qtcreator then they are more than welcomejrh,['c++'] +15645,why does visual studio break the naming convention for methods in c i know the naming convention for class methods in c is to begin with a capital letter and each new word is a capital letter eg getdevicenameso my question is why when i create a form place a control on it then double click the control for the method to be created automatically for me by the ide i get a method begining with a noncapital letter eg selectbutton clickobject sender eventargs e,['c#'] +15653,how can i change the visibility of a textblock with a trigger when i try to compile the following code i get the error visibility member is not valid because it does not have a qualifying type namewhat do i have to change so that i can make the textblock thisappear when statusoffxamlwindow xclasstesttrigger123345window1 xmlns xmlnsx titlewindow1 height300 width300 stackpanel textblock textthis is a sentence textblocktriggers trigger propertybinding status valueoff setter propertyvisibility valuecollapsed trigger textblocktriggers textblock textblock textbinding status stackpanelwindowcode behindusing systemwindowsnamespace testtrigger123345 public partial class window1 window public window1 initializecomponent datacontext this status off public string status get set i changed to datatrigger and dependency properties and it gets the same errorxamlwindow xclasstesttrigger123345window1 xmlns xmlnsx titlewindow1 height300 width300 stackpanel horizontalalignmentleft textblock textbinding status textblocktriggers datatrigger bindingbinding status valueoff setter propertytextblockbackground valuetan datatrigger textblocktriggers textblock stackpanelwindowcode behindusing systemwindowsnamespace testtrigger123345 public partial class window1 window public window1 initializecomponent datacontext this status off region dependencyproperty status public string status get return stringgetvaluestatusproperty set setvaluestatusproperty value public static readonly dependencyproperty statusproperty dependencypropertyregisterstatus typeofstring typeofwindow1 new frameworkpropertymetadata endregion i redid this with a viewmodel that has a property status that implements inotifypropertychanged and it gets that same errorwindowviewmodelcsusing systemcomponentmodelnamespace testtrigger123345 class windowviewmodel region viewmodelproperty status private string status public string status get return status set status value onpropertychangedstatus endregion region propertchanged block public event propertychangedeventhandler propertychanged private void onpropertychangedstring property if propertychanged null propertychangedthis new propertychangedeventargsproperty endregion code behindusing systemwindowsnamespace testtrigger123345 public partial class window1 window public window1 initializecomponent windowviewmodel windowviewmodel new windowviewmodel windowviewmodelstatus off datacontext windowviewmodel surely there is a way to do this with a trigger somehow,['c#'] +15662,how can i run sql statements on a named range within an excel sheet all i am trying to do is take a standard range on an excel sheet ie a named range or even a1f100 and run some sql queries on it and return a recordset that i can either step through in vba code or even just paste into some other sheet in the same workbookusing adodb was one thought but how could i setup the connectionstring to point to some range within the current workbooki know before i have made use of the microsoft query wizard which was not ideal but would work i cannot seem to get this to refer to a range within the sheet only other excel fileshere is the function i am left with when i run it a few times my excel crashes with the usual out of resources error message i have removed this function from my spreadsheet and everything runs seamlessly multiple times thus it is definitely caused by the code herei have cleaned up all the objects correctly does anyone have any ideas what could be going wrong could there be something in the connection string that could be tweaked or could it be something to do with the variant that is returned from the getrows methodi am using ms ado 28 and have also tried 25 with the same behaviourfunction gettimebuckets as collectiondim strfile as stringdim strcon as stringdim strsql as stringdim daterows as variantdim i as integerdim today as datedim cn as adodbconnectiondim rs as adodbrecordsetset cn createobjectadodbconnectionset rs createobjectadodbrecordsetset gettimebuckets new collectionstrfile thisworkbookfullnamestrcon providermicrosoftjetoledb40data source strfile extended propertiesexcel 80hdryesimex1cnopen strconstrsql select thistinctexpiration from positionsummarytable where instrument type lstopt rsopen strsql cndaterows rsgetrowsrsclosetoday datetoday 6may2009for i 1 to ubounddaterows 2 if daterows0 i today then gettimebucketsadd daterows0 i end ifnext iset daterows nothingset cn nothingset rs nothingend function,['sql'] +15667,how can i get the path of the current users application data folder 1how can i find out the windows installation drive in which the user is working i need this to navigate to the applicationdata in documentsandsettings2also how can i get the user name too so that i can goto applicaitiondata eg ddocuments and settingsuserapplication data,['c#'] +15672,how do i chose the most appropriate type of exception to throw there are already lots of questions on so about exceptions but i cannot find one that answers my question feel free to point me in the direction of another question if i have missed itmy question is quite simple how do other c developers go about choosing the most appropriate type of exception to throw earlier i wrote the following code if enumisdefinedenumtype value return tenumparseenumtype value else throw new argumentexceptionstringformatparameter for value 0 is not defined in 1 value enumtype i have since realised that throwing an invalidenumargumentexception would probably have been more appropriate had i known of its existence at the timeis there an authoritative resource available that helps developers chose exception types or is it simply a matter of experienceediti have given the points to noldorin for providing a range of ideas in a well thoughtout answer the points could have gone to any one of you really thanks for all the suggestions,['c#'] +15677,memory leak using jni to retrieve strings value from java code i am using getstringutfchars to retrieve a strings value from the java code using jni and releasing the string using releasestringutfchars when the code is running on jre 14 there is no memory leak but if the same code is running with a jre 15 or higher version the memory increases this is a part of the code msg idenvgetstringutfcharsenv msgidnull opcdata set stropc msg id opcdata msgid msg idenvreleasestringutfcharsenv msgidmsg id i am unable to understand the reason for leakcan someone helpthis one is because if i comment the rest of the code but leave this part the memory leak takes place this is a part of the code that i am usingjniexport jobjectarray jnicall java msiapi msiapi msgtoescalate jnienv env jobject job jstring msgid jlong msgseverity jstring msgprefixtext jint flag opcdata opc msg id data struct to store a mesg id const char msg id int ret ret2 jint val val67 jstring strnull jobjectarray array null jclass sclassnull create an opc data structure to store message ids of messages to escalate if ret2opcdata createopcdtype message id opc msg id opc err ok fprintfstderr cannot create opc data structure to store message opcdata createdn ret2 cleanup all msg idenvgetstringutfcharsenvmsgidnull opcdata set stropc msg id opcdata msgid msg id envreleasestringutfcharsenv msgid msg id retopcmsg ackconnectionopc msg id ifflag0 ret0 sclass envfindclassenv javalangstring array envnewobjectarrayenv 2 sclass null strenvnewstringutfenv0 envsetobjectarrayelementenvarray0str envdeletelocalrefenv str strenvnewstringutfenv0 envsetobjectarrayelementenvarray1str envdeletelocalrefenv str opcdata freeopc msg id ifret0 return null else returnarrayin the one above is if i comment the sections between i do not see any memory leak,"['java', 'c']" +15679,is xml or xul the future of java gui building after spending a lot of time and code on programming in swing i thought this cannot be stateoftheart java gui building after not finding a userfriendly visual gui bilder for eclipse i stumbled upon declarative gui building with xml ui toolkits and i thought this must be it i think it is the right way to go easy and also close to webprogramming but after looking around in the web and on so i got the impression that it is not very common although there are many implementations and apis it seems like most of them are kind of dead and had no updates in the last 5 yearsso i wonder is my feeling right that xml is not very widespread for java guis and if so what are the reasons maybe it could not become accepted or it has some major drawbacks or people are doing everything in the web instead with fatclients or there are better alternatives maybe javafxi just need to know if it is worth spending time in that area or better look for alternate ways as i dont read developer magazines i just do not know what the trends in gui building are and which technologies are believed to have a future but i cannot imagine that people still spend so much time on writing nasty swing or swt apps,['java'] +15680,is there a lock statement in vbnet does vbnet have the equivalent of cs lock statement,['c#'] +15682,django auth user truncating email field i have an issue with the djangocontribauth user model where the email max length is 75i am receiving email addresses that are longer than 75 characters from the facebook api and i need to would really like to store them in the user for continuity among users that are from facebook connect and othersi am able to solve the problem of data truncated for column email at row 1 by manually going editing the field in our mysql database but is there a better way to solve this preferably one that does not involve me manually editing the database every time i reset it for a schema changei am ok with editing the database as long as i can add it to the reset script or the initial datajson file,"['python', 'mysql']" +15683,python plotting libraries what alternatives are there to pylab for plotting in python in particular i am looking for something that does not use the stateful model that pylab does,['python'] +15700,can a c compiler reorder elements in a struct can a c compiler specifically g reorder the internal elements of a structi am seeing some strange behaviour where i have a structure that contains something like the followingstruct somestruct long somelong long somelongarray25 unsigned long someunsignedlong unsigned long someunsignedlongarray8 unsigned long int someunsignedlongint when i write output this to file the order of someunsignedlongarray and somelongarray seem to be reversed ie the elements in somelongarray appear after someunsignedlong and the elements of someunsignedlongarray appear after somelong is this possiblethanksupdateas requested i am writing out the structure using the followingint fd openfspeco rdwro creato trunc06int writeres writefdchar somestructsizeofsomestructfor completeness here is the full structstruct somestructbyte somebytebyte somebytearray6char somecharchar somechararray5char somechararrayarray35short someshortsigned short someshortarray2unsigned short someunsignedshortunsigned short someunsignedshortarray8int someintint someintarray3int someintarrayarrayarrayarray4326int psomeintunsigned int someunsignedintunsigned int someunsignedintarray9long somelonglong somelongarray25unsigned long someunsignedlongunsigned long someunsignedlongarray8unsigned long int someunsignedlongintlong long somelonglonglong long somelonglongarray5bool someboolbool someboolarray3unsigned long long someunsignedlonglongunsigned long long someunsignedlonglongarray5unsigned long long someunsignedlonglongarrayarray52unsigned long long int psomeunsignedlonglongint,['c++'] +15705,how do i convert a cstring to a double in c how do i convert a cstring to a double in c unicode support would be nice alsothanks,['c++'] +15711,having trouble with fork pipe dup2 and exec in c heres my codeinclude stdiohinclude stdlibhinclude unistdhinclude waithinclude readlinereadlinehdefine numpipes 2int mainint argc char argv char bbuffer sptr aptr null pipecommsnumpipes cmdargs10 int fdpipe2 pcount acount i status lpidsnumpipes pid t pid pipefdpipe while1 bbuffer readlineshell ifstrcasecmpbbuffer exit return 0 sptr bbuffer pcount 1 do aptr strsepsptr pipecommspcount aptr whileaptr fori 0 i pcount i acount 1 do aptr strseppipecommsi cmdargsacount aptr whileaptr cmdargsacount 0 ifstrlencmdargs0 0 pid fork ifpid 0 ifi 0 closefdpipe0 dup2fdpipe1 stdout fileno closefdpipe1 else ifi 1 closefdpipe1 dup2fdpipe0 stdin fileno closefdpipe0 execvpcmdargs0 cmdargs exit1 else lpidsi pid waitpidpid status 0 ifwifexitedstatus printfd terminated status dn pid wexitstatusstatus fori 0 i pcount i waitpidlpidsi status 0 ifwifexitedstatus printfd terminated status dn lpidsi wexitstatusstatus return 0the code was updated to reflect he changes proposed by two answers below it still does not work as it shouldheres the test case where this failsnazgulled projectssog08 ls ltotal 8rwxrxrx 1 nazgulled nazgulled 7181 20090527 1744 aoutrwxrxrx 1 nazgulled nazgulled 754 20090527 0142 datahrwxrxrx 1 nazgulled nazgulled 1305 20090527 1750 maincrwxrxrx 1 nazgulled nazgulled 320 20090527 0142 makefilerwxrxrx 1 nazgulled nazgulled 14408 20090527 1721 progrwxrxrx 1 nazgulled nazgulled 9276 20090527 1721 progcrwxrxrx 1 nazgulled nazgulled 10496 20090527 1721 progorwxrxrx 1 nazgulled nazgulled 16 20090527 1719 testnazgulled projectssog08 aout shell ls lgrep prog4804 terminated status 0rwxrxrx 1 nazgulled nazgulled 14408 20090527 1721 progrwxrxrx 1 nazgulled nazgulled 9276 20090527 1721 progcrwxrxrx 1 nazgulled nazgulled 10496 20090527 1721 progothe problem is that i should return to my shell after that i should see shell waiting for more input you can also notice that you do not see a message similar to 4804 terminated status 0 but with a different pid which means the second process did not terminatei think it has something to do with grep because this worksnazgulled projectssog08 aout shell echo qsudo fthisk devsda4838 terminated status 0the number of cylinders for this thisk is set to 1305there is nothing wrong with that but this is larger than 1024and could in certain setups cause problems with1 software that runs at boot time eg old versions of lilo2 booting and partitioning software from other oss eg dos fthisk os2 fthiskcommand m for help 4839 terminated status 0you can easily see two terminate messagesso whats wrong with my code,['c'] +15727,put icon inside input element in a form how do i put an icon inside a forms input elementlive version at tidal force theme,['css'] +15728,any way to select without causing locking in mysql queryselect countonlineaccount id cnt from onlinebut online table is also modified by an event so frequently i can see lock by running show processlistis there any grammar in mysql that can make select statement not causing locksand i have forgotten to mention above that it is on a mysql slave databaseafter i added into mycnftransactionisolation readuncommittedthe slave will meet with error error binary logging not possible message transaction level readuncommitted in innodb is not safe for binlog mode statement on queryso is there a compatible way to do this,['mysql'] +15731,nstextfieldcell delegate i have a text field cell in a table view from which i need to be made aware when it ends editing i thought i would set my controller class as the text field cells delegate and then use nstextfields delegate method textdidendediting but realized that the text field cell does not seem to have delegate methods why is this and what can i do other than subclassing to be informed when editing is finishedthanks,['objective-c'] +15734,how to find a list of wireless networks ssids in java c andor c is there a toolkitpackage that is available that i could use to find a list of wireless networks ssids that are available in either java c or c for windows xp any sample code would be appreciated,"['c#', 'java', 'c']" +15760,c capturing the mouse cursor image backgroundi am writing a screen capture applicationmy code is based derived from this project note that the code captures the the mouse cursor also which is desirable for memy problemcode works fine when the mouse cursor is the normal pointer or hand icon the mouse is rendered correctly on the screenshothowever when the mouse cursor is changed to the insertion point the ibeam cursor for example typing in notepad then code does not work the result is that i get a faint image of the cursor like a very translucent gray version of it instead of the blank white one would expectmy questionhow can i capture the mouse cursor image when the image is one of these ibeamtype imagesnote if you click on the original article someone offers a suggestion it does not worksourcethis is from the original article static bitmap capturecursorref int x ref int y bitmap bmp intptr hicon win32stuffcursorinfo ci new win32stuffcursorinfo win32stufficoninfo icinfo cicbsize marshalsizeofci if win32stuffgetcursorinfoout ci if ciflags win32stuffcursor showing hicon win32stuffcopyiconcihcursor if win32stuffgeticoninfohicon out icinfo x ciptscreenposx inticinfoxhotspot y ciptscreenposy inticinfoyhotspot icon ic iconfromhandlehicon bmp ictobitmap return bmp return null,['c#'] +15770,optimum query delay for autocomplete in a yui autocomplete or similar how many milliseconds are you using as query delay time between the last key input and the request to the serveri recently changed the default value of an autocomplete cotrol similar to yuis from 750ms to 280ms using keystrokelevel model as a reference any other useful references out there,['javascript'] +15771,can a variable number of arguments be passed to a function in a similar way to using varargs in c or cfna bfna b c d,['python'] +15776,codefirst or databasefirst how to choose let us suppose we are going to start new project application that contains some business logic user interface on aspnet wpf or both of them wed like to use orm or dal code generator and implement our business logic in net classes there are several fundamental ways how we can express our ideas of business domainimplement business classes on net and let orm generate appropriate database schemacreate database schema manually and generate net classes by code generatoruse some kind of visual designer that can generate business classes and database structure or scriptwhat do you prefer to write create table persons or public class person what are pros and cons of those waysmaybe there are some special situations where one way is better than anotherhow to choose optimal way in a particular projecti am quite familiar with codefirst or modelfirst way but it seems most of orms are designed as code generators or mappers that suppose that i will manually implement both database structure and business classesanswers based on expirience and examples of orms are especially welcomeedit note the question is not what should i do first when starting new project but what should be manually declared automatically generated domain classes or database structure,['.net'] +15783,what is the purpose of cxa pure virtual whilst compiling with avrgcc i have encountered linker errors such as the followingundefined reference to cxa pure virtuali have found this document which statesthe cxa pure virtual function is an error handler that is invoked when a pure virtual function is calledif you are writing a c application that has pure virtual functions you must supply your own cxa pure virtual error handler function for exampleextern c void cxa pure virtual while 1 defining this function as suggested fixes the errors but i would like to knowwhat the purpose of this function iswhy i should need to define it myself andwhy it is acceptable to code it as an infinite loop,['c++'] +15786,read session id using javascript is it by any means possible to read the browser session id using javascript,['javascript'] +15788,try catch on a convert in a select statement is it possible to use try catch blocks in sql selectsfor stuff similar to this for exampleselect order convertdatetime orderdatefrom orderswhats the best way of handling this scenario,['sql'] +15792,sending multipart html emails which contain embedded images i have been playing around with the email module in python but i want to be able to know how to embed images which are included in the htmlso for example if the body is something likeimg srcpathimagepngimgi would like to embed imagepng into the email and the src attribute should be replaced with contentid does anybody know how to do this,['python'] +15794,how to create json by javascript for loop i have array of select tagselect iduniqueid namestatus option value1presentoption option value2absentoption selectand i want to create a json object having two fields uniqueidofselect and optionvalue in javascripti use getelementsbynamestatus and i iterate on itediti need out put likeselectid2optionvalue2selectid4optionvalue1and so on,['javascript'] +15798,jquery on iphoneandroidblackberry i do not have any of the devices to test at the moment i guess i will start using the emulators later onwere looking to offer mobile support i was wondering how jquery or even javascript renders in their respective browsers what works what does not any tips advice,"['jquery', 'iphone', 'android']" +15799,how can i ensure that a division of integers is always rounded up i want to ensure that a division of integers is always rounded up if necessary is there a better way than this there is a lot of casting going on intmathceilingdoublemyint1 myint2,['c#'] +15800,how can i join on a stored procedure i have a stored procedure that takes no parameters and it returns two fields the stored procedure sums up all transactions that are applied to a tenant and it returns the balance and the id of the tenanti want to use the record set it returns with a query and i need to join it is results on the id of the tenantthis is my current queryselect ttenantname tcarplatenumber tcarcolor tsex tssno tphone tmemo uunitnumber ppropertynamefrom tbltenant t left join tblrentalunit u on tunitid uid left join tblproperty p on upropertyid pidorder by ppropertyname tcarplatenumberthe stored procedure is thisselect tenantid as tenantid sumisnulltransamount0 as tenantbalance from tbltenant tenantleft join tbltransaction transon tenantid transtenantidgroup by tenantidi would like to add the balance from the stored procedure to it alsohow can i do this,['sql'] +15803,is it possible to clone html element objects in javascript jquery i am looking for some tips on how to solve my problem i have a html element like select box input field in a table now i want to copy the object and generate a new one out of the copy and that with javascript or jquery i think this should work somehow but i am a little bit clueless at the momentsomething like this pseudo codeoldl ddl 1get newddl oldloldlattrid newidoldlhtml,"['javascript', 'jquery']" +15809,sharing loginsystem between classic asp and aspnet a client uses classic asp to log in to their web based backofficei have written a new aspnet app to be included in the backoffice and i need to utilize the already existing loginsystem so that when they are logged in there they do not need to log in again in the new aspnet applogins and passwords are stored as clear text in a sql server db that i can access from my aspnet appwhat would be an effective way to integrate these systems my current best idea isin the link to my aspnet app i link to a gateway loginpage with their userid and a hashed password common secret in the querystring i then compare this to the password of the user in the database but the problem is that if this querystring is intercepted it can be used to access the aspnet site without actually knowing the username and passwordi am most likely overlooking something simple,['asp.net'] +15822,jquery to find all exact td matches servertable tdeq server this finds only 1 first i think match how to find all matches btw tdcontains will not work for me,"['javascript', 'jquery']" +15836,why cannot i make a vector of references when i do thisstdvectorint helloeverything works great however when i make it a vector of references insteadstdvectorint helloi get horrible errors like error c2528 pointer pointer to reference is illegali want to put a bunch of references to structs into a vector so that i do not have to meddle with pointers why is vector throwing a tantrum about this is my only option to use a vector of pointers instead,['c++'] +15840,how to mark a global as deprecated in python i have seen decorators that let you mark a function a deprecated so that a warning is given whenever that function is used i would like to do the same thing but for a global variable but i cannot think of a way to detect global variable accesses i know about the globals function and i could check its contents but that would just tell me if the global is defined which it still will be if the function is deprecated and not all out removed not if it is actually being used the best alternative i can think of is something like this myglobal 3myglobal deprecated3but besides the problem of how to get deprecated to act exactly like a 3 i am not sure what deprecated could do that would let you detect every time it is accessed i think the best it could do is iterate through all of the globals methods since everything in python is an object so even 3 has methods for converting to string and the like and decorate them to all be deprecated but that is not idealany ideas has anyone else tackled this problem,['python'] +15857,how do i avoid the use of getdate in a sql view i am writing a database view to sum up a bunch of records where the value in a date column is within the last 7 days it looks something like thiscreate view recentrecordsum asselect tid sumtsomevalue as valuesumfrom sometable twhere trecorddate datead7getdategroup by tidis there a way of doing this without having the getdate directly in the where clause i am using sql server 20 and 2005looking at the query plan shows that the cost of the getdate call is only 003 of the entire query which is considerably more complex than the one above so performance is not an issue however i like my queries to be deterministicideally i would also like to expose the 7 parameter as a column so that it could be used in the where clause of something querying the view currently i am contemplating a small number of views for 7 14 28 day windows,['sql'] +15862,coding standards large amount of arguments hey i am a fresh out of college graduate i am working on a project that i expect will be ultimately maintained by somebody else i keep encountering an annoying situation on this project and that is objects that require many private variables and as a result very long constructorsapart from variable naming there is not any coding standard enforced i am wondering how to deal with the likes of this sometimes i fear i will see some of my own code on dailywtf in the futurei tought about trying to enclose some of these arguements in other classes but in this situation it doesnt really make senseis this a total nonissue or is it something that should and is easily correctablepublic function constructucode uname utime uarea udomain utext uid unum uvideo 0 uaudio 0 uimage 0,['php'] +15868,why do i get connection refused after 1024 connections i am testing on a local linux server with both the server and client in the same server after about 1024 connections in my code where i connect i get connection refused at first i thought it was the fd set max limit of 1024 for select and changed the server to do poll instead of select and i still do not get past this number my ulimit n is set to 2048 and i monitor the lsof on the server it reaches about 1033 not sure if this is exact number and fails any help is much appreciated,['c'] +15884,best way to retrieve variable values from a text file python json referring on this question i have a similar but not the same problemon my way i will have some text file structured likevar a homevar b carvar c 155and i need that python read the file and then create a variable named var a with value home and so onexamplepython stuff over heregetvarfromfilefilename this is the function that im looking forprint var boutput car as stringprint var coutput 155 as numberis this possible i mean even keep the var typenotice that i have the full freedom to the text file structure i can use the format i like if the one i proposed is not the bestedit the configparser can be a solution but i do not like it so much because in my script i will have then to refer to the variables in the file withconfiggetset var namebut what i will love is to refer to the variable directly as i declared it in the python scriptthere is a way to import the file as a python dictionaryoh last thing keep in mind that i do not know exactly how many variables would i have in the text fileedit 2 i am very interested at stephans json solution because in that way the text file could be read simply with others languages php then via ajax javascript for example but i fail in something while acting that solutionfor the example i dont load the file but create a var with the supposed file contentfile content var a 4 var b a stringmydict dictfile contenterror valueerror dictionary update sequence element 0 has length 1 2 is requiredfile content 2 var a 4 var b a stringmydict 2 dictjsondumpfile content 2 trueerrortraceback most recent call lastfile pyshell5 line 1 in modulemydict 2 dictjsondumpfile content 2 truefile cpython26libjson init py line 181 in dumpfpwritechunkattributeerror bool object has no attribute writein what kind of issues can i fall with the json formatand how can i read a json array in a text file and transform it in a python dictps i do not like the solution using py files i will prefer txt inc whatever is not restrictive to one language,['python'] +15886,thispelling the uiimage imagenamed fud edit feb 2014 note that this question dates from ios 20 image requirements and handling have moved on a lot since then retina makes images bigger and loading them slightly more complex with the built in support for ipad and retina images you should certainly use imagenamed in your codei see a lot of people saying imagenamed is bad but equal numbers of people saying the performance is good especially when rendering uitableviews see this so question for example or this article on iphonedevelopertipscom uiimages imagenamed method used to leak so it was best avoided but has been fixed in recent releases i would like to understand the caching algorithm better in order to make a reasoned decision about where i can trust the system to cache my images and where i need to go the extra mile and do it myself my current basic understanding is that it is a simple nsmutabledictionary of uiimages referenced by filename it gets bigger and when memory runs out it gets a lot smallerfor example does anyone know for sure that the image cache behind imagenamed does not respond to didreceivememorywarning it seems unlikely that apple would not do thisif you have any insight into the caching algorithm please post it here,['iphone'] +15887,what makes an app console or windows form application visual studio 2008i created a new project for console application and modified it to look like thisclass program static void main string args threadsleep 20 then i created another project for windows form application and modified itstatic class program stathread commented this line static void main string args added args commented following lines applicationenablevisualstyles applicationsetcompatibletextrenderingdefault false applicationrun new form1 commented this line threadsleep 20 now i have neither written console functions consolewrite etc in first application nor i have written forms related operations in second one looks identical to mestill first application shows black window and second one does not show anything what makes it work like this,"['c#', '.net']" +15888,how to make the how to make the a href tag refer to nothingi use jquery i need to make some anchor tags perform no actioni usually write it like thisa hreflinkahowever this refers to the top of the page,"['jquery', 'html']" +15891,can the c main function be static can the main function be declared static in a c program if so then what is the use of itis it possible if i use assembly code and call the static main function myself consider embedded programs,['c'] +15893,how to cache inputstream for multiple use i have an inputstream of a file and i use apache poi components to read from it like thispoifsfilesystem filesystem new poifsfilesysteminputstreamthe problem is that i need to use the same stream multiple times and the poifsfilesystem closes the stream after usewhat is the best way to cache the data from the input stream and then serve more input streams to different poifsfilesystem edit 1by cache i meant store for later use not as a way to speedup the application also is it better to just read up the input stream into an array or string and then create input streams for each use edit 2sorry to reopen the question but the conditions are somewhat different when working inside desktop and web application first of all the inputstream i get from the orgapachecommonsfileuploadfileitem in my tomcat web app does not support markings thus cannot reset second i would like to be able to keep the file in memory for faster acces and less io problems when dealing with files,['java'] +15897,python queue multiprocessing queue how they behave this sample code works i can write something in the filefrom multiprocessing import process queuequeue queuedef printerself queue queueputhello worlddef cmdthispself queue f filecmdlog w print f queueget fcloseinstead this other sample not errormsg module object is not callableimport queuequeue queuedef printerself queue queueputhello worlddef cmdthispself queue f filecmdlog w print f queueget fclosethis other sample not i cannot write something in the fileimport queuequeue queuequeuedef printerself queue queueputhello worlddef cmdthispself queue f filecmdlog w print f queueget fclosecan someone explain the differences and the right to do,['python'] +15901,how can i see a page error in jmeter how can i see a error in jmeterin other words if a test fail how is possible to see the page returned with error,['java'] +15915,remove characters from nsstring nsstring mystring a b c d e f gi want to remove the spaces so the new string would be abcdefg,['objective-c'] +15924,alternatives to use polymorphism in ruby on rails i am currently writing some intranet web application where people could submit to admins requests for adding different resources the example requests would beinstalling programs in this case user will select which program he wants installedincreasing quota in this case user will just enter the amount of thisk space he needs or maybe he will select the predefined quantities 1gb 10gb etccreate new email alias in this case user will just type the aliasi was thinking about having just one model userrequests with the reference to the sender andtwo optional attributes one would be reference id that would refefrence to other tables forexample the program that he wants installed and another would be used for free type fieldslike email alias or quota so my problem is that based on the type of the request the model should contain eitherreference to other tableinteger data string databased on the type of the request the given action should be taken probably email aliascould be added from rails but the application on users computer will be installed by handdoes anyone had similar problem do you think using polymorphism for this kind of stuff is a good idea do you have any suggestions on how to organize data in the tables,['ruby-on-rails'] +15929,find text string using jquery say a web page has a string such as i am a simple string that i want to find how would i go about this using jquery,['jquery'] +15934,how can i get the users network login name i am building a c application and i want to identify users by their username for example if i logged onto the domain mydomain as the user myusername i would want to get the mydomainmyusername so i can identify the userhow can i do this with c,['c#'] +15966,how to simulate a db for testing java i am programming in java and my applications are making a lot of use of db hence it is important for me to be able to test my db usage easilywhat db tests are all about for me they should supply two simple requirements verify sql syntaxmore importantly check that the data is selectedupdatedinserted correctly according to a given situation well then it seems that all i need is a dbbut actually i prefer not as there are few difficulties using a db for a test just get yourself a testing db how hard could it be well in my working place to have a personal testing db is pretty impossible you have to use a public db which is accessible for everyonethese tests sure am not fast db tests tend to be slower than usual tests it is really not ideal to have slow teststhis program should handle any case it becomes somewhat annoying and even impossible to try and simulate each and every case in a db for each case a certain amount of insertupdate queries should be made which is annoying and takes timewait a second how do you know there are 542 rows in that table one of the main principles in testing is to be able to test the functionality in a way different from that of your testedcode when using a db there is usually one way to do something therefore the test is exactly the same as the corecodeso you can figure out i do not like dbs when it comes to tests of course i will have to get to this in some point but i would rather get there later on my testing after i found most bugs using the rest of the test methods but what am i looking for i am looking for a way to simulate a db a mock db using the file system or just virtual memory i thought that maybe there is a java toolpackage which allows to simply construct using code interface a db mock per test with simulated tables and rows with sql verification and with a code interface for monitoring its status rather then using sql are you familiar with this kind of tooledit thanks for the answers although i was asking for a tool you also provided me with some tips concerning the problem it will take me some time to check out your offers so i cannot say right now whether your answers were satisfying notanyway heres a better view of what i am looking for imagine a class named dbmonitor that one of its features is finding the number of rows in a table here is an imaginary code of how i would like to test that feature using junitpublic class testdbmonitor extends testcase override public void setup throws exception mockconnection connection new mockconnection thistablename table1 mocktable table new mocktabletablename string columnname column1 columntype columntype columntypenumber int columnsize 50 mockcolumn column new mockcolumncolumnname columntype columnsize tableaddcolumncolumn for int i 0 i 20 i hashmapmockcolumn object fields new hashmapmockcolumn object fieldsputcolumn i tableaddrowfields thisconnection connection test public void testgatherstatistics throws exception dbmonitor monitor new dbmonitorconnection monitorgatherstatistics assertequalsmockconnection connectiongetnumberofrowstablename monitorgetnumberofrowstablename string tablename connection connectioni hope this code is clear enough to understand my idea excuse me for syntax errors i was typing manually without my dear eclipse p by the way i use orm partially and my raw sql queries are quite simple and should not differ from one platform to another,['java'] +15979,performance of aspnet in monolinux vs iiswindow is there any performance different between hosting your aspnet in mono on linux and iis on window server,['asp.net'] +15980,aspnet how to apply css class for a table generated in c codebehind i have an aspnet page and i am generating an html table in my server side code codebehind file as follows htmltable itblcart new htmltable htmltablerow irowheader new htmltablerow htmltablecell icellhead1 new htmltablecell icellhead1innertext item irowheadercellsaddicellhead1 itblcartrowsaddicartrow pnlphonecartcontrolsadditblcart appending to a paneli want to apply a css class to this tablei could not find such a property from the intellisenseam i missing anything can anyone guide me how to go ahead,"['c#', 'asp.net']" +15986,what are best practices for multilanguage database design what is the best way to create multilanguage database to create localized table for every table is making design and querying complex in other case to add column for each language is simple but not dynamic please help me to understand what is the best choose for enterprise applications,['sql'] +15993,find the element before and after a specific element i have a list with links i use with tabs it looks like thisul lia hreffirst tabali lia hrefsecond tabali li classactivea hrefactive tabali lia hreffourth tabali lia hreffifth tabaliulhow can i find the list element before and after the active tab in this case the second and fourth tabtried using find with no success,['jquery'] +15998,modulo in javascript large number i try to calculate with js modulo function but do not get the right result which should be 1 here is a hardcoded piece of codevar checksum 2105017012345678131468alertchecksum 97result 66whats the problem hereregardsbenedikt,['javascript'] +16002,protected methods in c what are the benefits to defining methods as protected in clike protected void keydemo keypress object sender keypresseventargs e some codeas compared to something like thisprivate void formname click object sender eventargs e some codei have seen in books many examples and i do not understand why and when do they private and protected,"['c#', '.net']" +16012,python parsing irc messages whats the best way to parse messages received from an irc server with python according to the rfc i simply want some kind of listwhatever for exampletest privmsg channel hibecomes this sender test target channel message hi and so onedit i want to parse irc messages in general not just privmsgs,['python'] +16013,how do i clone a jaxb object i have some jaxb objects instantiated from code generated from xsd by jaxb that i need to clone the jaxb class does not appear to provide an interface for doing this easily i can not hand edit the class and can not extend it so i need to create a helperutility method to do this what is the best approach,['java'] +16015,how to set time zone of mysql on one serverwhen i runmysql select now now 20090530 165429 1 row in set 0 secon another servermysql select now now 20090530 200143 1 row in set 0 sec,['mysql'] +16025,converting a console application to a service i am looking for different ways with strengthsweaknesses for converting a console application we are using long term in to a windows service we use something called java service wrapper for activemq and i believe people have told me you can wrap anything with it that is not saying that you should wrap anything with it though weve had our issues with this setupthe console app is a net console application that by default logs a lot of info to the console though this is configurableany reccomendationsshould we just rebuild it in visual studio as a service use a wrapper which one,['.net'] +16026,what is the event to catch form submission in javascript a couple of questions herei was wondering what event do i use to execute some javascript on form submission to do some validationonce i have done my validation how do i then submit the form in javascript cheers,['javascript'] +16029,how to update dataset parent child tables with autogenerated identity key i am using adonet datasets in my vb applications i have a typed dataset with one parent table and many child tables i want to generate identity key when i insert data into parent table and then update the data in all child tables with the same key as foregin keyat last i want to update the dataset in databasesql server08well the above thing can be possible by first inserting parent table in database directly get the identity column and than use to for child tablesbut i want to this as an automatic operation like linq to sql which takes care of primary foreign key in datacontexti such thing possible in dataset which takes care of autogenerated column for parent and child tablesthanksabb,['.net'] +16030,what are some strategies to unit test a scheduler this post started out as what are some common patterns in unit testing multithreaded code but i found some other thiscussions on so that generally agreed that it is hard tm and it depends tm so i thought that reducing the scope of the question would be more usefulbackground we are implementing a simple scheduler that gives you a way to register callbacks when starting and stopping jobs and of course configure the frequency of scheduling currently were making a lightweight wrapper around javautiltimeraspectsi have not found a way to test this scheduler by relying on only public interfaces something like addjobjobschedule jobargsjoblistener removejobjobid how do i time the fact that the the job was called according to the schedule specified,['java'] +16031,javascript inheritance i know there is a lot of similar questions are tons of great answers to this i tried to look at the classical inheritance methods or those closure methods etc somehow i consider they are more or less hack methods to me as it does not really what the javascript is designed to do welcome anybody correct me if i am wrongok as long as it works i satisfy with the classical inheritance pattern likeparentclass function basevar do something here parentclassprototype a b c d prototype is auto gen inheritance goes herechildclass function childvar do something childclassprototype new parentclass1 actual inheritance to the prototype statement instancechildinstance new childclasswhateverabove is somehow to my understanding the inheritance of js but one scenario i have no idea how to implement is that what if i want to do some initializing during object creation ie within constructor and the new object can be used right away my illustration on problem might not be too clear so let me use the following c psuedo to explain what i want to doclass parent public parent basevar class child parent public child basevar parent basevar constructor of child and call parent constructor during construct for some reason like init ui elements putting them in constructor seems the best way to do anyone have idea on how can i do itps in the 1 i have no idea what i should put there ps2 the above situation i did found the jqueryinherit library can do i just wonder if not using library can achieve itps3 or my understanding is wrong since javascript is not intended to mimick oop that is why i call it hack what is the correct logic to implement this,['javascript'] +16034,what is more efficient a switch case or an stdmap i am thinking about the tokenizer hereeach token calls a different function inside the parserwhat is more efficient a map of stdfunctionsboostfunctionsa switch case,['c++'] +16039,triggering a checkbox value changed event in datagridview i have a grid view that has a check box column and i want to trigger a drawing event as soon as the value of the cell is toggled i tried the valuechaged and the cellendedit and beginedit and chose the selection mode as cellselect as for the the first 2 events the event was triggered upon the finishing of the edit mode like moving out of the current cell or going back and forth it is just a weird behavior is there anything that triggers the event on the grid view as soon as the cell value is changedbest regards,['c#'] +16041,java generics with class so i have a map mapstring class format new hashmapstring classand i would add elements to it like thisformatputvendor number integerclassformatputvendor thispatch dateclass i have a generic method as followspublic static t t verifytypestring name classt type if type integerclass return typecastnew integerintegerparseintname return nullnow this piece of code works great with no compiler issues integer i verifytype100integerclassbut when i try this integer i verifytype100formatgetvendor numberor class type integerclass integer i verifytype100typecompiler shows me this warning type safety unchecked invocation verifytypestringclass of the generic method verifytypestring class that leaves me puzzled please help,['java'] +16046,c ranking of objects multiple criteria i am building a plugin for a lan party website that i wrote that would allow the use of a round robin tournamentall is going well but i have some questions about the most efficient way to rank over two criteriabasically i would like the following ranking layout rank wins totalscorepersone 1 5 50persond 2 35 37persona 2 35 37personc 4 25 26personb 5 25 24personf 6 0 12in sql server i would useselect person rank over order by wins desc totalscore desc rank wins totalscorenow i only have list dictionary and etc to work withspecificallydictionarytournamentteam double wins new dictionarytournamentteam doubledictionarytournamentteam double score new dictionarytournamentteam doubleis there a way to do this style of ranking with linqif not is there an extensible way that would allow me later to take in to account winlossdraw instead of just wins if i choose toeditmy adaptation of thesoftwarejedis answerprivate class rrwinrecord icomparable public int wins get set public int losses get set public int draws get set public double overallscore get set public double winrecord get return thiswins 10 thisdraws 05 thislosses 00 public int comparetoobject obj public override bool equalsobject obj public override int gethashcode public static bool operator rrwinrecord lhs rrwinrecord rhs public static bool operator rrwinrecord lhs rrwinrecord rhs public static bool operator rrwinrecord lhs rrwinrecord rhs public static bool operator rrwinrecord lhs rrwinrecord rhs public static bool operator rrwinrecord lhs rrwinrecord rhs public static bool operator rrwinrecord lhs rrwinrecord rhs int r 1 lastrank 1 rrwinrecord lastrecord null var ranks from team in recordskeys let teamrecord recordsteam orderby teamrecord descending select new rank team team rank r record teamrecord foreach var rank in ranks if rankrecord null lastrecord rankrecord rankrank lastrank lastrecord rankrecord lastrank rankrank string scoredescription stringformat012 rankrecordwins rankrecordlosses rankrecorddraws yield return new tournamentrankingrankteam rankrank scoredescription yield break,['c#'] +16048,jquery ui datepicker opens automatically within dialog i have a datepicker which is used within the jquery dialog object the source of the dialogs content is loaded using load within the dialog i created a script which creates a datepicker for the text inputdatedatepicker when i open the dialog for the first time everything is okay but if i close it and reopen again the datepicker is triggered automatically and there is no such an option like autoopenfalseis there any way of preventing this or what am i doing wrong,['jquery'] +16052,why does it appear that my random number generator is not random in c i am working in microsoft visual c 2008 expressi found this snippet of code public static int randomnumberint min int max random random new random return randomnextmin max the problem is that i have run it more than 100 times and it is always giving me the same answer when my min 0 and max 1 i get 0 every single time i created a test function to run it really i am getting 0 each time i am having a hard time believing that is a coincidence is there something else i can do to examine or test this i did rerun the test with min 0 and max 10 and the first 50ish times the result was always 5 the 2nd 50ish times the result was always 9 i need something a little more consistently randomadeena,['c#'] +16058,type variance in net framework 40 ienumerablet icomparablet and a few more are now typevariant ilistt icollectiont and many others are not why,['.net'] +16073,can net code compiled with the unsafe tag run in mono i have some code that does bitmap manipulation using the lockbits method and accessing the bitmap data directly using a pointer this code has to be wrapped in an unsafe block of course and i was wondering if this means that the code would not work in monoi am assuming the bitmap class is available in mono but maybe that is another dealbreaker,['.net'] +16078,unique hardware id in mac os x mac os x development is a fairly new animal for me and i am in the process of porting over some software for software licensing and registration i need to be able to generate some kind of hardware id it does not have to be anything fancy ethernet mac address hard drive serial cpu serial something like thati have got it covered on windows but i have not a clue on mac any idea of what i need to do or where i can go for information on this would be great editfor anybody else that is interested in this this is the code i ended up using with qts qprocess classqprocess procqstringlist argsargs c ioreg rd1 c ioplatformexpertdevice awk ioplatformuuid print 3 procstart binbash args procwaitforfinishedqstring uid procreadallnote i am using c,['c++'] +16088,how do i find the location of the executable in c is there a way in cc to find the location full path of the current executed programthe problem with argv0 is that it does not give the full path,"['c++', 'c']" +16096,write to utf8 file in python i am really confused with the codecsopen function when i dofile codecsopentemp w utf8filewritecodecsbom utf8filecloseit gives me the errorunicodedecodeerror ascii codec cannot decode byte 0xef in position 0 ordinal not in range128if i dofile opentemp wfilewritecodecsbom utf8filecloseit works finequestion is why does the first method fail and how do i insert the bomif the second method is the correct way of doing it what the point of using codecsopenfilename w utf8,['python'] +16102,size limit for xml datatype in sql 2005 is there a size limit on the xml data type in sql 2005when i try to return anything more than 44kb size of the xml string from my stored proc it just returns an empty string i am using for xml path to return hierarchical data sets in xml format from my stored procs,['sql'] +16112,can i change a private readonly field in c using reflection i am wondering since a lot of things can be done using reflection can i change a private readonly field after the constructor completed its executionnote just curiositypublic class foo private readonly int bar public fooint num bar num public int getbar return bar foo foo new foo123consolewritelinefoogetbar thisplay 123 reflection code hereconsolewritelinefoogetbar thisplay 456,['c#'] +16133,why and how would you use exceptions in this sample php code i have been wondering why would i use exceptions in my php let us take a look at a simple exampleclass worker public function gotowork return isinthatmood okay i will do it true in your dreams false worker new workerif workergotowork if dateltime sunday echo fine you do not have to work on sundays else echo get your a back to workelse echo goodis there a reason for me to use exceptions for that kind of code why how would the code be builtand what about code that may produce errorsclass fileoutputter public function outputfilefile if file existsfile return false return file get contentsfile why would i use exceptions in the above case i have a feeling that exceptions help you to recognize the type of the problem which occured trueso am i using exceptions appropriately in this codeclass fileoutputter public function outputfilefile if file existsfile return throw new exceptionfile not found123 try contents file get contentsfile catch exception e return e return contents or is that poor now the underlying code can do thisfo new fileoutputtertry fooutputfilefileextensioncatch exception e something happened we could either thisplay the errorproblem directly echo egetmessage or use the info to make alternative execution flows if egetcode 123 the one we specified earlier do something else now create an exceptionor am i completely lost here,['php'] +16135,what tools can i use to produce iphone app screencasts i need to produce demonstration video screencasts for my iphone app i am referring to those such as this one for the reddit iphone app the one on the right not the youtube video i am assuming the best way to do this is to record the simulator using a screen recording utility does anyone have any other methods what tools have you used successfully,"['ios', 'iphone']" +16139,accepts nested attributes for child association validation failing i am using accepts nested attributes for in one of my rails models and i want to save the children after creating the parentthe form works perfectly but the validation is failing for simplicitys sake imagine the followingclass project activerecordbase has many tasks accepts nested attributes for tasksendclass task activerecordbase belongs to project validates presence of project id validates associated projectendand i am runningprojectcreate name something task attributes name 123 name 456 upon saving the project model the validation is failing on the tasks because they do not have a project id since the project has not been savedit seems like rails is following the pattern belowvalidate projectvalidate taskssave projectsave tasksthe pattern should bevalidate projecton pass save project and continuevalidate taskson pass save taskson fail delete project rollback maybeso my question boils down to how can i get rails to run the project id or project method and validation on the children tasks after the parent project has been saved but not save the parent project model if any child task is invalidany ideas,['ruby-on-rails'] +16141,atomically copying one mysql table over another i am trying to copy one table over another one atomically basically i want to update a table periodically such that a process that reads from the table will not get an incomplete result if another process is updating the tableto give some background info i want a table that acts as a leaderboard for a game this leaderboard will update every few minutes via a separate process my thinking is as followstable scores contains the publiclyviewable leaderboard that will be read from when a user views the leaderboard this table is updated every few minutes the process that updates the leaderboard will create a scores temp table that contains the new leaderboard once that table is created i want to copy all of its contents over to scores atomically i think what i want to do is something liketruncate table scoresinsert into scores select from scores tempi want to replace everything in scores i do not need to maintain my primary keys or auto increment values i just want to bring in all the data from scores temp but i know that if someone views the scores before these 2 statements are done the leaderboard will be blank how can i do this atomically such that it will never show blank or incomplete data thanks,['mysql'] +16144,creating a logging handler to connect to oracle so right now i need to create and implement an extension of the python logging module that will be used to log to our database basically we have several python applicationsthat all run in the background that currently log to a random mishmash of text files which makes it almost impossible to find out if a certain application failed or not the problem given to me is to move said logging to text files to an oracle db the tables have already been defined and where things need to be logged to but right now im looking at adding another logging handler that will log to the db i am using python 254 and cx oracle and the applications in general can be ether run as a servicedaemon or a straight applicationi am just mainly curious about what would be the best possible way to go about this few questionsif any errors occur with cx oracle where should these errors be logged to if its down would it be best to just go and have the logger retreat to the default text fileawhile back we started enforcing that people use sysstderrstdoutwrite instead of print so worst case scenario we wouldnt run into any issues with print becoming deprecated is there a way to seamlessly make all of the thousands of sysstd calls be piped directly into the logger and have the logger pickup the slackafter every logged message should the script automatically do a commit there is going to be several dozen a secondwhat is the best way to implement a new handler for the logging system inheriting from the basic handler class seems to be easiest any ideas suggestions would be great,['python'] +16145,how can i use servermappath from globalasax i need to use servermappath to combine some files path that i store in the webconfighowever since servermappath relies on the current httpcontext i think i am unable to do this when trying to use the method even though its available i get the following exceptionserver operation is not available in this contextis there another method that can map a web root relative directory such as app data to the full physical path such as cinetpubwrootprojectapp data,"['c#', 'asp.net']" +16146,read only n bytes from a file in cocoa how to read only n bytes from a specified file,['objective-c'] +16153,make mysql fetch assoc automatically detect return data types when using mysql fetch assoc in php how can i make it return the correct data types right now it appears to convert everything to strings i would prefer if it left the ints as ints and somehow designated the datetime as either object or somehow different than stringsthe reason for this is that i am using php as a backend to a flex application and flex has some features such as automatically detecting return types which do not work that well if everything comes in as a string,"['php', 'mysql']" +16159,a question about referencing functions in javascript the problem i have a jquery heavy page that has a built in admin interface the admin functions only trigger when an admin variable is set these functions require a second library to work properly and the second file is only included if the user is an admin when the page is first created the functions will never trigger for normal users and normal users do not get the include for the second libraryis it bad to reference a function does not exist in the files currently included even if that function can never be called does that make sense pseudocodeheader notice that adminjs is not includedscript typetextjavascript srcscriptjsscriptscript typetextjavascript srcuserjsscriptscriptjs admin functions referenced but cannot be executedadmin false assume thissomethingdblclickfunction ifadmin adminstuff implemented in adminjs not included else userstuffideasi suppose two separate files for users and admins could be used but i feel that would be an overly complicated solution do not want to maintain two large files with only a few lines of difference the only reason i include a reference to the admin function in this file is i need to attach it to page elements that get refreshed as a part of the script when jquery refreshes the page i need to reattach function to interactive elementsthe questioni want to keep things very simple and not have to include file i do not have to if they will not be used by the user is this a good way to do this or should i be going another route,"['javascript', 'jquery']" +16169,best regular expression for email format validation with aspnet 35 validation i have used both of the following regular expressions for testing for a valid email expression with aspnet validation controls i was wondering which is the better expression from a performance standpoint or if someone has better one w 09azazw09azaz09azazw09azazazaz29i am trying avoid the exponentially slow expression problem described on the bcl team blogupdatebased on feedback i ended up creating a function to test if an email is validpublic function isvalidemailbyval emailstring as string optional byval isrequired as boolean false as boolean dim emailsplit as string dim isvalid as boolean true dim localpart as string stringempty dim domainpart as string stringempty dim domainsplit as string dim tld as string if emailstringlength 80 then isvalid false elseif emailstringlength 0 and emailstringlength 6 then email is too short isvalid false elseif emailstringlength 0 then email is optional only test value if provided emailsplit emailstringsplitcchar if emailsplitcount 2 then only 1 should exist isvalid false else localpart emailsplit0 domainpart emailsplit1 end if if isvalid false orelse domainpartcontains false then needs at least 1 period after isvalid false else test localpart length and characters if localpartlength 64 orelse validatestringlocalpart validatetestsemaillocalpartsafechars false orelse localpartstartswith orelse localpartendswith orelse localpartcontains then isvalid false end if validate domain name portion of email address if isvalid false orelse validatestringdomainpart validatetestshostnamechars false orelse domainpartstartswith orelse domainpartstartswith orelse domainpartcontains then isvalid false else domainsplit domainpartsplitcchar tld domainsplitubounddomainsplit top level domains must be at least two characters if tldlength 2 then isvalid false end if end if end if else if no value is passed review if required if isrequired true then isvalid false else isvalid true end if end if return isvalidend functionnotes isvalidemail is more restrictive about characters allowed then the rfc but it does not test for all possible invalid uses of those characters,['asp.net'] +16171,python recursion and return statements i am fairly new to python and recursive functions as a whole so pardon my ignorancei am trying to implement a binary search tree in python and have the following insert method taken out of a classdef insertself key rootnone inserts a node in the tree if root none root selfroot if rootkey none self updateroot key return 0 else tmp root if key tmpkey we work with the right subtree selfinsertkey roottmpright elif key tmpkey we work with the left subtree selfinsertkey roottmpleft else key already exists return 0i am not sure if this is legible but it traverses the tree until it gets to a none value and updates the node with the key to insertnow the method works nicely and correctly creates a bst from scratch but there is a problem with the return statements as it only returns 0 if there is no recursion performed bstinsert100 bstinsert15 bstrootrightkey15inserting the root key again returns 0 from line 15 the way it should bstinsert100i cannot figure out why this happens if i put a print statement in line 6 it executes correctly yet it just would not return anything past the first insertion why is this i am pretty sure i am missing some basic information regarding python and recursionthanks for your helpivanps i have read that recursion is not the best way to implement a bst so i will look into other solutions but i would like to know the answer to this before moving on,['python'] +16184,routing vs url rewrite iis7 performance i was wondering is there any difference in terms of performance between the two approaches any good articles on this,"['.net', 'asp.net']" +16185,how to access xml text node in jquery suppose i get the following xml structurerootitem item1text1item1 item2text2item2 more text hereitemrootmore text here is a text node that is at the same level as the other data nodes in the hierarchy but it does not seem to be accessibleis there a way of extracting the text node shown above using jquery functions,['jquery'] +16190,jquery set value of table cell inside div i have a floating div which contains a title and i want to change that title i tried thisdivdragtitle3textnew titlebut the title is actually in a table inside the div this is the tabletabletbodytrtdannouncementstdtd styletextalignrightimg srcbuttontoppng classdivtitlebutton iddragbutton3 onmousedownjavascripttogglecontentwin3tdtrtbodytablei want to know how i can change the title without entering the whole tables code when i set the new table,['jquery'] +16193,create a dictionary on a list with grouping i have the following object in a listpublic class democlass public int groupkey get set public string demostring get set public object someotherproperty get set now i want to create following dictionary out of itdictionaryint listdemoclassi want to group the listdemoclass by the property groupkey but i do not understand how this is done and some helpafter thinking a bit i achieved the needed behaviour withvar groupeddemoclasses from democlass in mysepcialvariablewhichisalistofdemoclass group democlass by democlassgroupkey into groupeddemoclass select groupeddemoclassvar neededdictionary groupeddemoclasstodictionarygdc gdckey gdc gdctolistbut is there a way to make this into a single statement,"['c#', '.net']" +16195,tilde operator in regular expressions i want to know whats the meaning of tilde operator in regular expressionsi have this statementif preg matchd10 postisbn warnings isbn should be 10 digitsi found this document explaining what tilde means it said that is a perl operator that means run this variable against this regular expressionbut why does my regular expression contains two tilde operators,['php'] +16197,get current url from iframe is there a simple way to get the current url from an iframethe viewer would going through multiple sites i am guessing i would be using something in javascript,['javascript'] +16220,when will c aes algorithm be fips compliant right now the only way i can get the rijndaelmanaged algorithm to work on a computer with the local security setting for fips turned on is to thisable it it is a government computer so i am not sure how that will fly i have seen posts on the msdn blog sites that say they are working on an aes fips compliant version but i cant seem to find out anything more does anyone know when this might happen,['c#'] +16226,resourcesopenrawresource issue android i have a database file in resraw folder i am calling resourcesopenrawresource with the file name as rrawfilename and i get an input stream but i have an another database file in device so to copy the contents of that db to the device db i use bufferedinputstream bi new bufferedinputstreamisand fileoutputstream but i get an exception that database file is corrupted how can i proceedi try to read the file using file and fileinputstream and the path as resrawfilename but that also does not work,"['java', 'android']" +16231,simple formula for determining date using week of month given a standard piece of scheduling information such as the second tuesday in june 2009 or the last friday in july 2009 whats the simplest and most efficient formula to translate that into a dateinputs w week of month enumeration 1st 2nd3rd 4th or last d day of week enum sun through satm month integery year integeredit again it does not matter what day the week begins on i want to get the wth instance of d in the given month thus the 2nd sunday in june 2009 is 14 june even though that technically falls in the 3rd week of june similarly the 1st sunday in june is 7 june not nullexception,['c#'] +16243,setintervalsettimeout return value two questionshow is the value returned from setinterval and settimeout the ones used to clear the timers calculatedis it possible for both the functions to return the same value during runtimefor examplevar a setintervalfn1 10var b settimeoutfn2 10is it possible for a and b to have the same valuethe first one is more of a formyknowledge question but the second one is more important,['javascript'] +16246,page load or page init in aspnet when do you bind your gridviews at page load or page initwhy,['asp.net'] +16251,which of these select statements is better and why i have 2 table person and rolei have to all the persons based on roleselect person from person inner join role onpersonroleid roleid where roleid roleidorselect person from person inner join role onpersonroleid roleid and roleid roleidwhich one of the above two solutions is better and why,['sql'] +16257,copy data from a table in one database to another separate database basically i have a two databases on sql server 2005i want to take the table data from one database and copy it to another databases tablei tried thisselect into dbodb1temptable from dbodb2temptablethis did not worki do not want to use a restore to avoid data lossany ideas,['sql'] +16261,can comments appear before the doctype declaration possible duplicatedoes the doctype declaration have to be the first tag in an html document i would like to place a comment this style at the very top of my html code preceding the doctype declaration does this conform to the standards is it supported by the major browsers are there any pitfalls in doing this,['html'] +16263,possible to get excanvas to work in ie 8 i used to work on a jquery plugin named beautytips and it was working just fine but since i have installed ie 8 this plugin stop working because it needs excanvas to make ie draw the vectors images etci have tried to download the newer version of excanvas but it is not working at all,['jquery'] +16265,validating a slug in django i am guessing this is going to involve regexp or something but i will give it a shot at the minute a user can break a website by typing something similar to a in the title field which is converted into a slug using django slugifybecause none of these characters can be converted django returns an error my question is what should i put in the form validation method to raise a formsvalidationerror when the user uses a title like thisthanks,['python'] +16281,how do i put data in a masterpage how do you put a strongly typed object in aspnet mvc into the master page do you have a viewmodelbase class that contains master page information and inherit from it for every view model or is there a better approach,['c#'] +16285,c functor and function templates consider this simple and pointless codeinclude iostreamstruct a templateint n void test stdcout and stdendl int main a a atest1it is a very simple example of a function template what if however i wanted to replace atest with an overloaded operator to make it a functorinclude iostreamstruct a templateint n void operator stdcout and stdendl int main a a a1 error how do i do thiscertainly if the operator took parameters which were dependent on the template the compiler could possibly deduce the template but i just cannot figure out the proper syntax to specify template parameters with a parameterless functoris there a proper way to do thisobviously this code would work since it bypasses the functor syntaxaoperator1but that kinda defeats the purpose of it being a functor p,['c++'] +16289,is there a way to hide the tab bar of jtabbedpane if only one tab exists i want a behavior similar to eg firefox where the list of available tabs does only show up if at least two tabs existi was not able to find anything like that yetthe best idea i had was changing the layout manuallyin case of one component just add that to the surrounding panelif a component is added remove the component from the surrounding panel add a jtabbedpane instead and add both the previous and the new component to that paneif a component is removed and only one component is left in the pane remove the pane and add the contained component insteadwhile this would probably work it feels like a hack or workaroundany better ideaa solution should ideally work in both java 15 and 16 but i would be happy about a 16only solution too,['java'] +16292,missing median aggregate function in django the development version of django has aggregate functions like avg count max min stddev sum and variance link text is there a reason median is missing from the list implementing one seems like it would be easy am i missing something how much are the aggregate functions doing behind the scenes,['python'] +16296,php mysql fulltext search lucene sphinx or this is admittedly similar to but not a duplicate of however what i am looking for are specific supported recommendations from the benefit of experience with more than one of the available systems there seems to be a lot of i have used lucene but not sphinx and vice a versathe setup standard lamp mysql 50 php 5mysql tables are using the innodb engine for foreign key constraintswe are looking at indexing data not pages data to be indexed may be in multiple languages utf8 charseta number of the comparisons i have come across like are either not entirely applicable ferret is a lucene port but not the same as zend search lucene or they are pushing their own systemsimplementations not exactly unbiasedsome others i have come across such as and provide very different results for performance of the two systemsalso all but ignored in much of what i have read is xapian might this be worth consideration as wellso i am hoping that some of you here on so have some experience with this question and could help with some recommendations or point me in the right direction,"['php', 'mysql']" +16310,difference between static in c and static in c what is the difference between the static keyword in c and c,"['c++', 'c']" +16320,variables in jsp pages with included pages what are the scoping rules for variables in a jsp page with pages added to them using tagsmy understanding is that an included page is essentially copied verbatum into the page which would lead me to assume that if i have declared a variable in a parent jsp that it would be available in the child oneshowever eclipse complains about this understandably because i could feasibly include the pages in any page or use them as stand alone and whe i try to start the tomcat server it fails to starti basically want to get a couple of variables fromt he session in the parent page and use them in the child pages this does not workso i have struck ont he idea of getting them from the session in each of the child pages however i was wondering if i could give them all the same variable names or if i would have to pick different variable names for them in each page so they did not clashalso what about imports if i import log4net in the parent jss do i also have to import it in the child ones,['java'] +16326,jquery fadeout not working with table rows i have the following html table is rendered to my browseri am creating this table from my aspnet codebehind filetable classtbltradeincarttr classtblcartheadertditemtdtdmodeltdtd pricetdtddeletetdtrtr idtr 15 1tdimg srcdiaimageslgvx9700jpg width50 height50 tdtdlg vx9700tdtd 122tdtda href onclickdeleteitem151tr 15 1img srclibimagesnccrossgif styleborder0pxatdtrtr idtr 11 8tdimg srcdiaimagesnok5610jpg width50 height50 tdtdnokia 5610tdtd 122tdtda href onclickdeleteitem118tr 11 8img srclibimagesnccrossgif styleborder0pxatdtrtr idtr 14 9tdimg srcdiaimagesnokn95jpg width50 height50 tdtdnokia n95tdtd 915tdtda href onclickdeleteitem149tr 14 9img srclibimagesnccrossgif styleborder0pxatdtrtableand in my javascript i have the delete function as followsfunction deleteitemmodeliditemindexid rowid getremovefromcartaspx modelmodelidcartitemitemindexidmoderemovefromcartrandmathrandom functiondata documentgetelementbyidrowidstylethisplay none var rowrowid rowfadeout10but when i call the deleteitem function i am not getting the fading effectits simply hiding the row like the thisplaynonecan any one guide me how to fix this,['jquery'] +16333,extract floating point numbers from a string in php i would like to convert a string into floating numbers for example15215 x 1234 x 11mminto15215 1234 and 11and store in an array such that dim015215 dim11234 dim211i would also need to handle things like 15215x1234x11 mm15215mmx1234mm x 11mmthank you,['php'] +16335,java bittorrent library are there any decent bittorrent libraries for java i need to program a simple torrent client but it would be great if i did not have to write everything from scratch,['java'] +16337,how do i access a config file inside the jar i am using flatpack to parse and load data from flat files this requires loading a config file that stores mappings of the columns of the flat filei have a constant to define the location of the mapping fileprivate static final string mapping file srccomcompanyconfigmapingpzmapxmli have a parsefile datafile method that actually does the parsingprivate void parsefile datafile throws filenotfoundexception sqlexception parser parser loginfoparsing datafilegetname filereader mappingfilereader new filereadermapping file filereader datafilereader new filereaderdatafile parser defaultparserfactorygetinstancenewfixedlengthparsermappingfilereader datafilereader parsersethandlingshortlinestrue dataset dataset parserparse process the datawhen i jar up everything and run it as a jar it bombs out on filereader mappingfilereader new filereadermapping file with a filenotfoundexception that file is inside the jar thoughhow do i get to iti have looked at this question and this question about accessing files inside jars and they both recommend temporarily extracting the file i do not want to do that though,['java'] +16340,how to check for nan in python floatnan results in a thingy simply called nan but how do i check for it should be very easy but i cannot find it,['python'] +16352,how can i script the creation of a movie from a set of images i managed to get a set of images loaded using python i would like my script to take this series of images in whatever format i need them and create a video from them the big limit in all this is that i am looking for something easy and simple to install ideally using the standard os x installation procedure download dmgclickmove into the application folderi do not want to expend a lot of effort to install the video editing program just something simple that worksquestionswhat format should i aim for i need my video to be playable on linux mac and windows systems the images are graphs so we are speaking of thiscreet images not photographs it should be pretty easy to compress it there will be about 10 images so this will be a short moviewhat tools should i use to produce the actual video i need to either do it directly from python using a library designed for this purpose or by scripting commandline tools called from python,['python'] +16356,how do i present a tree in an html table i am trying to show a tree structure in an html table it is basically a list of people you referred to a site but you can expand each and see the people they referred too only 2 or 3 levelsi am also showing a number of pieces of information on each person so i am using a table with several columnsi am wondering whats the best way to thisplay this so that people in lower levels look indented but avoiding a mismatch between the data contents and the headers showing what each number meansi am mostly looking for stealing ideas here have you ever seen or done a site that has something like thisedit thank you for all the answers so fari think i failed to correctly explain what i am trying to dothis is a list of people but the reason of existence of this report is the numbers attached to each person not the list itselffor each person in this list i am going to show data to their right that needs to be aligned for example to have totals at the bottom etcpicture if you will having windows explorer with the tree on the left so you can open and close folders but then to the right of each folder you have data like how many files are in there what kind of information etc just like you get in the right pane in windows explorer for files in details view only that i do it for the tree on the leftthis is not what i am doing but it is the closest analogy i could think ofthis is why i am leaning towards making a table rather than a listif these where just the peoples names or a tree of folders i totally agree than nesting uls is the way to go my problem in this case is that the extra data that i need to show for each item is the most important part of the whole report,['html'] +16372,equivalent javascript functions for pythons urllibquote and urllibunquote are there any equivalent javascript functions for pythons urllibquote and urllibunquotethe closest i have come across are escape encodeuri and encodeuricomponent and their corresponding unencoding functions but they do not encodedecode the same set of special characters as far as i can tellthankscameron,"['javascript', 'python']" +16376,allow access permission to write in program files of windows 7 my application throws access denied errors when writing temporary files in the installation directory where the executable resides however it works perfectly well in xp how to provide access rights to program files directory in windows 7edithow to make the program ask the user to elevate rights ie run program with full admin rights,['c#'] +16379,how should a c programmer design software in c as a c programmer we have to deal with concepts and the relation of relatedconcepts before implementing them to classeshoweverhow to design a software in procedure languages like c how can i deal with concepts without the help of class in crelatedwhat is the best way to plan and organize development of an application in cstruggling with c coming from object oriented land,"['c++', 'c']" +16387,using pythons list index method on a list of tuples or objects pythons list type has an index method that takes one parameter and returns the index of the first item in the list matching the parameter for instance some list apple pear banana grape some listindexpear1 some listindexgrape3is there a graceful idiomatic way to extend this to lists of complex objects like tuples ideally i would like to be able to do something like this tuple list pineapple 5 cherry 7 kumquat 3 plum 11 some listgetindexoftuple1 71 some listgetindexoftuple0 kumquat2getindexoftuple is just a hypothetical method that accepts a subindex and a value and then returns the index of the list item with the given value at that subindex i hopeis there some way to achieve that general result using list comprehensions or lambas or something inline like that i think i could write my own class and method but i do not want to reinvent the wheel if python already has a way to do it,['python'] +16405,c net web services passing custom objects to a web service i have a need to pass a custom object to a remote web service i have read that it may be necessary to implement iserializable but i have done that and i am encountering difficulties what is the proper way in c to pass a custom object to a web service method,['c#'] +16407,how to list contents of a server directory using jsp when writing a jsp file how can i get the current directory of this file at runtimeto be able to iterate the directory and list its contentswould some file io operations be restricted because of some security issuesi would prefer a solution without accessing some implementationspecificserver variables propertiesediti wouldnt ask if it were as simple as new file because this would just give the directory of servers executables,['java'] +16408,how to save a python interactive session i find myself frequently using pythons interpreter to work with databases files etc basically a lot of manual formatting of semistructured data i do not properly save and clean up the useful bits as often as i would like is there a way to save my input into the shell db connections variable assignments little for loops and bits of logic some history of the interactive session if i use something like script i get too much stdout noise i do not really need to pickle all the objects though if there is a solution that does that it would be ok ideally i would just be left with a script that ran as the one i created interactively and i could just delete the bits i did not need is there a package that does this or a diy approachupdate i am really amazed at the quality and usefulness of these packages for those with a similar itchipython should have been using this for ages kind of what i had in mindreinteract very impressive i want to learn more about visualization and this seems like it will shine there sort of a gtkgnome desktop app that renders graphs inline imagine a hybrid shell graphing calculator mini eclipse source thistribution here built fine on ubuntu integrates into gnome desktop windows and mac installers toobpython extremely cool lots of nice features autocomplete rewind one keystroke save to file indentation well done python source thistribution pulled a couple of dependencies from sourceforgei am converted these really fill a need between interpreter and editor,['python'] +16414,objective c twophase construction of objects i have been reading up on raii and single vs twophase constructioninitialization for whatever reason i was in the twophase camp up until recently because at some point i must have heard that it is bad to do errorprone operations in your constructor however i think i am now convinced that singlephase is preferable based on questions i have read on so and other articlesmy question is why does objective c use the twophase approach allocinit almost exclusively for nonconvenience constructors is there any specific reason in the language or was it just a design decision by the designers,['objective-c'] +16421,suppress first chance exceptions is it possible to suppress first chance supressions in visual studio c debugger for specific lines of codei want to use first chance exceptions in the debugger but there are about 50 first chance exceptions i need to go through every debug session before i get to the interesting codecurrently i turn off first chance exceptions and then manually turn them on but that is a hassle and a time sink,['c#'] +16438,getting networkcredential for current user c i am trying to invoke a webservice from a console application and i need to provide the client with a systemnetnetworkcredential objectis it possible to create a networkcredential object for the user that started the application without prompting for usernamepassword,['c#'] +16441,how to navigate to a bookmark in eclipse 341 i am able to set bookmarks in a source file but are there shortcut keys to navigate to a bookmark the navigate menu has a goto line but that is not useful,['java'] +16451,how can i perform premain initialization in cc with avrgcc in order to ensure that some initialization code runs before main using arduinoavrgcc i have code such as the followingclass init public init initialize init initideally i would like to be able to simply writeinitializebut this does not compileis there a less verbose way to achieve the same effectnote the code is part of an arduino sketch so the main function is automatically generated and cannot be modified for example to call initialize before any other codeupdate ideally the initialization would be performed in the setup function but in this case there is other code depending on it which occurs before main,"['c++', 'c']" +16453,mysql triggerprocedure execution delay is there a decent way to delay execution of mysql trigger while condition 0 sleep for awhileinsert into some table valuesnewvalue1 newvalue2,['mysql'] +16462,how to run c project under linux do you know any ways to run a c project under linux are there any framewoks or libraries for thisregards,"['c#', '.net']" +16474,check if javascript is enabled server side aspnet is it possible to check if the client browser has javascript enabled from aspnet codei was hoping to ideally do this on prerender of controls or pageload so that i can change how they lookany suggestions work arounds etc would be much appreciated,"['asp.net', 'javascript']" +16478,how to concatenate numbers and strings to format numbers in tsql i have the following function alter function dboactualweightdims add the parameters for the function here actualweight int actual dims lenght int actual dims width int actual dims height intreturns varchar50asbegindeclare actualweightdims varchar50actual weight if actualweight is not null set actualweightdims actualweightactual dims if actual dims lenght is not null and actual dims width is not null and actual dims height is not null set actualweightdims actual dims lenght x actual dims width x actual dims height returnactualweightdimsendbut when i tried to use it i got the following error conversion failed when converting the varchar value x to data type int when i use the following select statementselect ba adjustment detailid number id number ba adjustment detailsubmit date submit date ba categorycategory category ba type of requestrequest type of request dboactualweightdimsba adjustment detailactualweightba adjustment detailactual dims lenghtba adjustment detailactual dims widthba adjustment detailactual dims height actual weightdims ba adjustment detailnotes notes ba adjustment detailupscustomerno upsno ba adjustment detailtrackingno airbillno ba adjustment detailstoreno storeno ba adjustment detaildownload date download date ba adjustment detailshipment dateshipmentdate ba adjustment detailfranchiseno franchiseno ba adjustment detailcustomerno customerno ba adjustment detailbillto billto ba adjustment detailadjustment amount requested adjustment amount requestedfrom ba adjustment detailinner join ba category on ba categoryid ba adjustment detailcategoryidinner join ba type of requeston ba type of requestid ba adjustment detailtypeofrequestidwhat i want to do is if the actualweight is not null then return the actualweight for the actual weightdims or else use the actual dims lenght width and heightif it is dims then i want to format the output to be lenghtxwidhtxheight 15x10x4 the actualweight adcutal dims lenght width and height are all int integer value but the output for actual weightdims should be varchar50where am i getting it wrongthankedit the user can only pick either weight or dims on aspnet page and if user selected dims then they must supply length width and height else it will throw error on the aspnet page should i worry about it on the sql side,['sql'] +16480,usage of trycatch blocks in c in general i tend to use trycatch for code which has multiple failure points for which the failures have a common handler in my experience this is typically code which qualifies input or context before performing some action or output after performing some actioni have received counsel from literature and colleagues to minimize the code in such blocks and i accept that as generally good advicei would like to understand a bit more about the foundation for the above advicewhat is the nature of the overheadare there recent development guidelines that address the recommended usage or avoidance of trycatch blockshow much do faster processors and more modern compilers mitigate the problems with trycatchthanks in advance for the helpaj,['c++'] +16485,eclipse wtp how do i enable ssl on tomcat eclipse wtp creates its own serverxml file which it places in some folder which configures the tomcat instance you are running for your web project if you double click on the server in the servers list you get a nice screen which makes it simple to configure some aspects of the serverxml filehow do i configure a new connection to allow ssl connections on port 8443 everytime i edit the serverxml file manually eclipse overwrites my changes with the settings it has stored in the server properties page of the configuration and it seems there is no way to add a new connector from the interface that eclipse providesis this possible here is the connector i want to addconnector port8443 protocolhttp11 sslenabledtrue maxthreads150 schemehttps securetrue keystorefiledapachetomcat6018keystorekeyssl keystorepasspass clientauthfalse sslprotocoltls,['java'] +16488,how to dynamically alter the class of an htmlactionlink in mvc i am looking for a way to alter the class of an actionlink in the controller based on specific criteria not found in the model so i cannot write a conditional in the view itself but i cannot seem to find the viewdataname that allows me to work w this element i assume this is possible but i am missing somethingi have an html helper like so in my viewhtmlactionlinkview index homebut in my controller i am not sure how to reference this like the below to add an attribute like class or onclickviewdataviewattributesaddclass active,['css'] +16489,jquery rails problematic is that true i saw comments in a previous question saying that it is best to use prototype with rails however my own experience is that jquery is a superior javascript library being new to rails i have not yet investigated how to use jquery with rails but i assumed this would work is it correct that this may be a problematic combination especially in relation to ajax and that i may need to use prototype instead,"['javascript', 'jquery', 'ruby-on-rails']" +16493,dependency injection frameworks why do i care i was reading over injection by hand and ninjection as well as why use ninject i encountered two pieces of confusionthe inject by hand technique i am already familiar with but i am not familiar with ninjection and thus am not sure how the complete program would work perhaps it would help to provide a complete program rather than as is done on that page showing a program broken up into piecesi still do not really get how this makes things easier i think i am missing something important i can kind of see how an injection framework would be helpful if you were creating a group of injections and then switching between two large groups all at once this is useful for mocking among other things but i think there is more to it than that but i am not sure what or maybe i just need more examples of why this is exciting to drive home the point,['c#'] +16494,gwt with a content management system after seeing some of the benefits of gwt my partner and i decided that it would be a good front end for the web app we hope to build a main part of this web app will be content management we were hoping to use a cms framework and put gwt on the front end but all the open source cms systems we find seem to be very tied to their front end does anybody know of a cms that would work well with gwt,['java'] +16496,how do i save eclipse launch profiles across workspaces when i copy an eclipse project directory it contains the classpath and project files so that when i take that same directory to another eclipse instance i do not have to setup my build path and such assuming that all the resources are contained in the project and not externalhowever this procedure does not cause launch profiles to travel with the directoryis there some other filedirectory structure i can carry around to another instance of eclipse that will include my launch profiles,['java'] +16512,integer value comparison i am a newbie java coder and i just read a variable of an integer class can be described three different ways in the api i have the following code if countcompareto0 systemoutprintlnout table count this is inside a loop and just outputs out tablemy goal is to figure out how to see if the value in integer count 0 i realize the countcompare0 is the correct way or is it countequals0 i know the count 0 is incorrect is this right is there a value comparison operator where its just count0,['java'] +16521,inline function linker error i am trying to use inline member functions of a particular class for example the function declaration and implementation without inlining is as suchin the header fileint gettpllsizein the cpp fileint needleussimgettpllsize return sampledim1for some reason if i put the inline keyword in either one of the implementation and declaration as well as in both places i get linker errors as shown creating library cdocume1stanleylocals1tempmex hn1templibx and object cdocume1stanleylocals1tempmex hn1templibexp mexfunctionobj error lnk2019 unresolved external symbol public int thiscall needleussimgettpllsizevoid gettpllsizeneedleussimqaehxz referenced in function mexfunction mexfunctionmexw32 fatal error lnk1120 1 unresolved externals cprogra1matlabr2008bbinmexpl error link of mexfunctionmexw32 failed what needs to be in order to get rid of this error ie what am i doing wrong in terms of making these inline member functions,['c++'] +16522,can i have hibernate create an object through factory method is there a way to map a factory method in hibernate as opposed to having hibernate call a default constructor and reflectively set properties or fieldsand if it cannot be mapped does hibernate provide a hook for custom object creation on a class by class basisthanks,['java'] +16529,getting objects parent namespace in python in python it is possible to use in order to access objects dictionary items for exampleclass test object def init self selfb 1 def foo self passobj testa objfoofrom above example having a object is it possible to get from it reference to obj that is a parent namespace for foo method assigned for example to change objb into 2,['python'] +16533,serving large files through nginx via rails 23 using xsendfile let us say i have a rails 232 application fronted by nginx and served by mongrel in which i need to serve a large static file through rails to control access to it i want the rails app to delegate the transfer of the file to nginx to avoid blocking the mongrel instancethe available information seems contradictory and incomplete this post shows how to do it with apache and hints that it can also be done with ngninx but no examples this post and this post show how to do it using the a plugin that apparently rails 23 makes uncessary this post suggests that maybe there is not support for xsendfile with nginx after alli would rather not muck around with plugins for things rails can now do by itselfhas anybody gotten xsendfilelike behavior to work using no plugins and rails 23nginxmongrel if not whats the best documentation for getting it to work with a plugin andor monkeypatch and rails 23nginxmongrel,['ruby-on-rails'] +16534,automapper ignore the rest is there a way to tell automapper to ignore all of the properties except the ones which are mapped explicitly i have external dto classes which are likely to change from the outside and i want to avoid specifying each property to be ignored explicitly since adding new properties will break the functionality cause exceptions when trying to map them into my own objects,['.net'] +16545,how to run a php script from the command line with mamp i have mamp installed now i am trying to run a script from the command line but i cannot seem to get it to workhow should i set up my environment so that i can run a script from the command line and use the php version i installed with mampupdate i agree with jjeaton below here is a nice solution of creating an alias to mamps php add this to your bash profilealias phpmampapplicationsmampbinphpphp536binphpnow you can use it from the command line phpmamp help,['php'] +16549,remove css from a div using jquery i am new to jquery in my app i have the followingthisplaypanel divliveclick function thiscssbackgroundcolor pink fontweight bolderwhen i click on a div the color of that div is changed within that click function i have some functionalities to do after all that i want to remove the applied css from the div how could i do it in jquery,"['jquery', 'css']" +16551,similarity string comparison in java i want to compare several strings to each other and find the ones that are the most similar i was wondering if there is any library method or best practice that would return me which strings are more similar to other strings for examplethe quick fox jumped the fox jumped the quick fox jumped the foxthis comparison would return that the first is more similar than the secondi guess i need some method such asdouble similarityindexstring s1 string s2is there such a thing somewhereedit why am i doing this i am writing a script that compares the output of a ms project file to the output of some legacy system that handles tasks because the legacy system has a very limited field width when the values are added the descriptions are abbreviated i want some semiautomated way to find which entries from ms project are similar to the entries on the system so i can get the generated keys it has drawbacks as it has to be still manually checked but it would save a lot of work,['java'] +16554,c difference between casting and as possible duplicatewhat is the difference between the following casts in c in c is a there difference between casting an object or using the as keyword hopefully this code will illustrate what i meanstring text hello helloobject obj text string originalcast stringobjtoupperstring originalas obj as stringtoupperthanks,['c#'] +16563,a good example of ant best practices i have read lots of articles on ant that explain all sorts of options and i have read much of the documentation for ant but i do not really know the right way to do many things can anyone recommend a good example illustrating how to use ant something that is not too complicated but also not too simplei found this one by doug sparling specifically related to hibernate and it looks pretty good but was wondering if you folks could comment on it because i do not want to adopt the style of someone who has questionable habits but it seems good to me,['java'] +16577,linux c error undefined reference to dlopen i work in linux with c eclipse and want to use a libraryeclipse shows me an errorundefined reference to dlopen do you know a solution here is my code include stdlibhinclude stdiohinclude dlfcnhint mainint argc char argv void handle double deskchar char error handle dlopen libcedd libso6 rtld lazy if handle fputs dlerror stderr exit1 desk dlsymhandle apply if error dlerror null fputserror stderr exit1 dlclosehandle,['c++'] +16585,code cleanup in netbeans is there something similar to the eclipse cleanup rules preferences java code style clean up in netbeansthe cleanup rules in eclipse will allow you to clean things up like organizing imports removing unnecessary casts adding missing override annotations etcalso can you do that on a whole set of classespackages instead of individual classes,['java'] +16589,accessing parent view controller custom properties i have written a uitabbarcontroller subclass called mainviewcontroller and added a few instance variables specifically a venue of type venue each tab of the mainviewcontroller needs to access the venue variable of the mainviewcontroller in the first tab a uiviewcontroller subclass named homeviewcontroller i wrote my viewdidload method and tried to output to nslog with bothnslog selfparentviewcontrollervenuenameandnslog selftabbarcontrollervenuenamebut xcode gives the errorerror request for member venue in something not a structure or unioni can access the venue property from within mainviewcontroller just fine so have ruled out an error there the iphone simulator does see both selfparentviewcontroller and selftabbarcontroller as an instance of mainviewcontroller the linenslog selftabbarcontrolleroutputs20090605 175446502 venue2972920b mainviewcontroller 0x536600since it is seen as a mainviewcontroller instance i doubt using casting would help is my only other option to initialize the homeviewcontroller with a copy of the venue or am i just doing something completely wrong with selfparentviewcontrollervenuename thanks rob,"['objective-c', 'iphone']" +16592,suggestions on a project in c thistributed systems networks i would like to work on a 23 month long project full time that involves coding in c and is related to networks protocol stacks i was considering writing my own network stack but that does not seem as interesting it would be great to find an idea to implement a tcpiplike stack for thistributed systemgpus that is better as far as network performance goes i have been googling this for 3 hours but have not come across anything that seems worth spending 2 months on open source projects like netperf seem beyond my scope i would really like a relatively small stand alone project that i can work on at my own pacethe intent of this project is to utilize my free time on a project that i might later release under open source license and gain expertise and handson experience in c networks parallel programming gpu thistributed systems etci seem to have hit a roadblock while finding ideas or perhaps i am not too clear on what i exactly what to do so any suggestions would be really appreciatedthanks,['c++'] +16600,how to set the javalibrarypath from eclipse how can i set the javalibrarypath for a whole eclipse project i am using a java library that relies on os specific files and need to find a dllsojnilib but the application always exits with an error message that those files are not found on the library path i would like to configure this whole project to use the library path i tried to add the path as a vm argument to some run configurations in eclipse but that did not work,['java'] +16610,how do i prevent css inheritance i have a hierarchical navigation menu in my sidebar that uses nested lists ul and li tags i am using a premade theme which already has styles for list items but i want to alter the style for the toplevel items but not have it apply to the subitems is there an easy way to apply styles to the toplevel list item tag without having those styles cascade down to its children list items i understand that i can explicitly add overriding styles to the subitems but i would really like to avoid having to duplicate all of that style code if there is an easy way to just say apply these styles to this class and do not cascade them down to any children elementshere is the html i am usingul idsidebar li classtoplevelnav spanheading 1span ul lisubheading ali lisubheading bli ul li li classtoplevelnav spanheading 2span ul lisubheading ali lisubheading bli ul liulso the css has styles for sidebar ul and sidebar ul li already but i would like to add additional styles to sidebar toplevelnav that do not cascade down to its subchildrenis there any way to do this simply or do i need to rearrange all of the styles so the styles that were on sidebar ul are now specific to certain classes,['css'] +16631,what is nhibernate as a followup to my previous question i am an aspnet programmer and am wondering how nhibernate would help me get my job done easier and more quickly than it would otherwise pretend i know nothing about nhibernate what is it and what can it do for me,['asp.net'] +16639,generic way to detect if html form is edited i have a tabbed html form upon navigating from one tab to the other the current tabs data is persisted on the db even if there is no change to the datai would like to make the persistence call only if the form is edited the form can contain any kind of control dirtying the form need not be by typing some text but choosing a date in a calendar control would also qualifyone way to achieve this would be to thisplay the form in readonly mode by default and have an edit button and if the user clicks the edit button then the call to db is made once again irrespective of whether data is modified this is a better improvement to what is currently existingi would like to know how to write a generic javascript function that would check if any of the controls value has been modified,"['javascript', 'jquery', 'html']" +16644,fastest way to replace string in a template i have some template stringthis is my 0 template 1 stringwhich i plan to put user values in using stringformatthe string actually is longer so for readability i usethis is my goodname1 template goodname2 stringand then stringreplace each parameter with its valuehow can i get the highest performance and readabilitymaybe i should not have this template in a file as now but dynamically build it by concatanating to a string builder and adding the params when required although it is less readable whats my other options,['c#'] +16646,singular value decomposition svd in php i would like to implement singular value decomposition svd in php i know that there are several external libraries which could do this for me but i have two questions concerning php though1 do you think it is possible andor reasonable to code the svd in php2 if 1 is yes can you help me to code it in phpi have already coded some parts of svd by myself heres the code which i made comments to the course of action in some parts of this code are not completely correctit would be great if you could help me thank you very much in advance,['php'] +16652,aspnet mvc controlleronexception not being called i have a base controller class where i am overriding to the controlleronexception handler method in order to provide a generic error handling for certain types of controllers that will inherit from this class these are api controllers that will return json results the onexception method never gets called when an exception gets raised by the controller does anyone see what i am doing wrong or is there a better way to handle this situationusing mvc 10base classpublic class apicontroller controller protected override void onexceptionexceptioncontext filtercontext this is never called filtercontextresult new jsonresult baseonexceptionfiltercontext inheriting classpublic class mycontroller apicontroller public ajaxresult forcedexception throw new systemexception,['c#'] +16654,how to set google app engine java contenttype to utf8 it seems i cannot get utf8 encoding to be sent in the response headersi tried using this to no availrespsetheadercontentencoding utf8does anyone know when is this bug to be fixed or is there a workaroundreferences threadthread68a480cb7bec869e,['java'] +16656,profiling objectivec binary image size i am looking for tools and approaches to determining what parts of of my cocoa and cocoatouch programs are most contributing the the final binary image size and ways to help reduce it i am not looking for a magic bullet compiler flag i am looking for profiling techniques for evaluating and reducing image size waste in the same vein as shark and instruments help for runtime evaluationa firstorder approximation may be the size of the os but how trustworthy is this in terms of final image size after optimizations and deadcode stripping if i add up all the os they are much larger than my final image so clearly the linker is already helping me out significantly but this means the size of the os may not be a useful measurewhere do others look to reduce image size without undermining code maintainability,['objective-c'] +16675,expressions in hibernate criteria let us say i have a persistent class item with a quantity field and a price fieldis there a way to build a criteria that calculates the sum of quantityprice,['java'] +16693,equals method implementation helpers c everytime i write some data class i usually spend so much time writing the iequatable implementationthe last class i wrote was something likepublic class polygon public point vertices get set implementing iequatable was exaustive surely c30linq helps a lot but the vertices can be shifted andor in the reverse order and that adds a lot of complexity to the equals method after many unit tests and corresponding implementation i gave up and changed my application to accept only triangles which iequatable implementation required only 11 unit tests to be fully coveredthere is any tool or technique that helps implementing equals and gethashcode,"['c#', '.net']" +16702,should we store format strings in resources for the project that i am currently on i have to deliver specially formatted strings to a 3rd party service for processing and so i am building up the strings like sostring somestring stringformat012 some message some percentage 3 token1 token2 token3 numberrather then hardcode the string i was thinking of moving it into the project resourcesstring somestring stringformatpropertiesresourcessomestring token1 token2 token3 numberthe second option is in my opinion not as readable as the first one ie the person reading the code would have to pull up the string resources to work out what the final result should look likehow do i get around this is the hardcoded format string a necessary evil in this case,['c#'] +16703,how to add an extra language input to android is it possible to add extra languages to android my current android phone only supports english and chinese language input i would like to have dutch also as i can use it for word completion the question on top of that is how to switch easily between these languages in the text input keyboard gui,['android'] +16706,undo scaffolding in rails is there any way to undo the effects of a scaffold command in rails,['ruby-on-rails'] +16707,how do i configure junit ant task to only produce output on failures i am configuring junit in ant so that unit tests will be run on each build i would like the output of failing tests to be printed in the ant console output whenever they are run i do not need to see any output from succeeding testshere is the relevant bit of my buildxml filejunit classpath pathelement pathbuild classpath formatter typebrief usefilefalse batchtest fileset dirsrc includesmytreejunit batchtestjunitthis produces almost what i want failing tests are detailed in the ant output except that succeeding tests also write the following output junit testsuite mytreejunitexampletest junit tests run 7 failures 0 errors 0 time elapsed 02 seci believe i have tried all the combinations listed in the junit task documentation includingprintsummary attributeshowoutput attributeformatter element with each kind of typemy use case is running ant from the command line as i write more tests i do not want the output from succeeding tests to be so large that output from failing tests scrolls off the screen i just want ant to be quiet unless there is a failing test that needs my attention how can i configure antjunit to do thisi am using ant version 164 and junit 46,['java'] +16715,zipping dynamic files in app engine python is there anyway i can zip dynamically generated content such as a freshly rendered html template into a zip file using zipfilethere seem to be some examples around for zipping static content but none for zipping dynamic ones or is it not possible at allone more question is it possible to create a zip file with a bunch of subfolders inside itthanks,['python'] +16718,datasetwritexml to string i am tring to get a string from a dataset without using getxml i am using writexml instead how to use it to get a stringthanks,"['c#', '.net']" +16742,is javascript an untyped language i have found that some people call javascript a dynamically weakly typed language but some even say untyped which is it really,['javascript'] +16746,jquery ajax post and encoding i am unable to understand why i cannot get a correct iso88591 charstet from the server answer being this a work on legacy code i hardly could change charset encoding on the pagesi make use of the jquery callpostserversidecode tctext iioff sidsessionid functiondata status chkappenddata posting a textarea value created using javascriptform acceptcharsetiso88591 methodposttextarea cols40 rows8 idcommentotextareabrinput typebutton valueinvia idsubmitformthe server side script processing the request declares at its very toptexthtml charsetiso88591so honestly i cannot figure out what else i should declare in terms of encoding this notwithstanding the accented characters a a a2a1 bounce back as a aa a2aa1 when placing the server answer in an html elementthe source is saved as ascii tryng to do this to have rudimentary html encoding on the variable to be posted does not solvectext escapehtmlctextfunction escapehtml str var div documentcreateelementdiv var text documentcreatetextnodestr divappendchildtext return divinnerhtml some ideathanks,['jquery'] +16747,python simple reading lines from a pipe i am trying to read lines from a pipe and process them but i am doing something silly and i cannot figure out what the producer is going to keep producing lines indefinitely like thisproducerpyimport timewhile true print data timesleep1the consumer just needs to check for lines periodicallyconsumerpyimport sys timewhile true line sysstdinreadline if line print got data line else timesleep1when i run this in the windows shell as python producerpy python consumerpy it just sleeps forever never seems to get data it seems that maybe the problem is that the producer never terminates since if i send a finite amount of data then it works finehow can i get the data to be received and show up for the consumer in the real application the producer is a c program i have no control over,['python'] +16748,in java switch statements on enums why am i getting a compilation error when i qualify my values in each case i have a switch statement in java on an enum which let us call imyinterfacemyenumeach of my case statements has the formimyinterfacemyenummyvalue though i could drop the imyinterface if i importedhowever the compiler java 6 throws an errorthe qualified case label imyinterfacemyenummyvalue must be replaced with the unqalified enum constant myvaluei can obviously do that but for the life of me i do not understand what is the purpose of this error clearly if the compiler can deal with the actual value it should be able to deal with the fully qualified name just as it would for constants in fact i would have assumed that the compiler turns the constant into the fully qualified nameso java gurus whats the rationale behind thisthank you,['java'] +16749,developer tool for configuring iis6 edit iis6 i am not sure iis7 is an option in the immediate futurefrom a developer angle i am constantly changing my iis settings or need to merge settings from other teams into different vms the save configuration to thisk has never really worked well for mebecause we are making lots of small changes web installation projects have never really worked either tools aimed for the webadmin are not necessarily a good fit for the developer we have different aims and needsdoes anyone have a script tool utility that would allow us to quickly configure iis in particularremove everything start cleanadd a load of virtual directories each mapped to application base pathsset as an applicationset the apool well assume the app pool already existsset the aspnet version to 2x if neededfrom some find of flat input list any format would do,['asp.net'] +16757,c generics syntax for multiple type parameter constraints possible duplicategeneric methods and multiple constraints i need a generic function that has two type constraints each inheriting from a different base class i know how to do this with one typevoid foot where t baseclasshowever i do not know how to do this with two typesvoid footone ttwo where tone baseone and ttwo basetwo how do you do this using net 2,['c#'] +16761,java optional parameters how do i use optional parameters in java what specification supports optional parameters,['java'] +16762,c preprocessor testing definedness of multiple macros i searched the site but did not find the answer i was looking for so here is a really quick questioni am trying to do something like that ifdef win32 win64 include coniohendifhow can i do such a thing i know that win32 is defined for both 32 and 64 bit windows so i would be okay with either for windows detection i am more interested in whether i can use logical operators like that with preprocessor directives and if yes how since the above does not workcompiling with gcc i get warning extra tokens at end of ifdef directive and it basically just takes the first macro and ignores the rest,['c'] +16765,how can i write a real time chat using xajax and php how can i write a real time chat using xajax and phpin other words is there a way to send xajax responses from the server to multiple clientsor is the only possibility to check for new messages every few seconds on client side,['php'] +16785,what does fpic mean when building a shared library i know the fpic option has something to do with resolving addresses and independence between individual modules but i am not sure what it really means can you explain,"['c++', 'c']" +16797,are implicityexplicit conversion methods inherited in c i am not sure what i am doing wrong here i have a generic class which is basically a glorified integer with a few methods for certain string formatting as well as intofrom string and int conversionspublic class base protected int m value from int public static implicit operator baseint value return new basevalue to string public static explicit operator stringbase value return stringformat0x6 intvalue and it functions fine i can successfully use implicit and explicit conversionsbase b 1consolewritelinestringb outputs 01 as expectedthen i derive from this class different child classes which turn onoff different named bits in m value for examplepublic class derived baseand then i cannot use my implicit tofrom int conversionsderived d 3 cannot implicitly convert type int to derived an explicit conversion exists are you missing a casteven this gives the same errorderived d int3are the implicitexplicit conversions not inherited in the derived class this will require a lot of code copying if notresponsethank you so much for the quick responses you all deserve the answer checkmark they are all very good answers the key is to think about the types on both sides of the equal sign now that i think about it like that it makes perfect sensei obviously only have to rewrite my to derived conversions the to int32 string etc conversions still apply,['c#'] +16800,creating program libraries in windows and linux c i am planning to use libraries in my c program development is happening on linux but application is designed to compile on both linux and windows i understand direct equivalent for shared librariesso in windows is dll right in linux using g i can create shared library using fpic and shared flags afaik there is no other code change required for a shared library but things are different in a windows dll there i should specify the functions which have to be exported using dllexport right my question is how do i manage this situation i mean dllexport is invalid in linux and the compiler will give an error but it is required in windows so how do i write a function which will compile on both platforms without any code change compilers usedg linuxvc windowsany help would be great,['c++'] +16802,java xslt tutorial can any one suggest good xslt with java tutorials,['java'] +16814,how do you check the browsers user agent in a jsp page using jstl el i need to check the browsers useragent to see if it is ie6 however i should not use scriptlets we have a strict no scriptlets policy to do this currently i usestring ua requestgetheader useragent boolean ismsie ua null uaindexof msie 1 if ismsie div what is the cleanest way to do this using jstl el etc and not scriptlets,['java'] +16818,image upload in rails how do i upload images and zip files in ror i am a newbie so please helpgive me both the view and the controller code examplethanks in advance,['ruby-on-rails'] +16820,how to print out the method name and line number and conditionally thisable nslog i am doing a presentation on debugging in xcode and would like to get more information on using nslog efficientlyin particular i have two questionsis there a way to easily nslog the current methods name line numberis there a way to thisable all nslogs easily before compiling for release code,['objective-c'] +16822,exact time measurement for performance testing what is the most exact way of seeing how long something for example a method call took in codethe easiest and quickest i would guess is thisdatetime start datetimenow do some worktimespan timeittook datetimenow startbut how exact is this are there better ways,"['c#', '.net']" +16832,ruby on rails what does the symbol mean i am working my way through head first rails and i keep seeing it is in the routesmapconnect marmotsnew controllermarmots actionnewit is in rendering partialsrender partialnew marmotit is in options for links link to destroy marmot confirmare you sure methoddelete basically seems to mean equals but if so why not just use an equals sign is it more like send tohow do you pronounce and what do you understand it to mean i can get by without knowing this but it bugs me,['ruby-on-rails'] +16851,css id vs class what is the basic difference between css id and css clasomeone told me that id can be used only once in a page but i found that it can be used multiple timeslikebody backgroundcolor 3399ffdivmenupane position absolute left 25px top 25px width 25divmenu thisplay block fontsize 14px margin 0 padding 0 border 2px solid 7fc07fdivmenu a thisplay block fontweight bold textdecoration none textalign right letterspacing 1px margin 0px color black bordertop 1px solid 487048divmenu alink background 33ccffdivmenu avisited background 33ccffdivmenu ahover background 3fc73f letterspacing 2pxdivmenu h4 padding 2px margin 0pxdivcontent position absolute left 30 top 25px width auto border 2px double 7fc07f backgroundcolor 33ccff padding 2px marginright 5pxdivcontent h3 backgroundcolor a3f4a3 textalign right letterspacing 1px color 386938 borderbottom 1px solid blackdivcontent alink avisited background0099ff color a3f4a3 letterspacing 1pxdivcontent ahover background ff0 color a3f4a3 letterspacing 1px,['css'] +16864,using ref with class c i want to give a certain linked list to a class i am making i want the class to write into that list eg by addlastshould i use the ref keyword for thati am somewhat puzzled on where to use the ref and out keywords in c as all classes are allocated dynamically on the heap and we actually use pointers for most operationsof course out and ref keywords make sense for primitives and structsalso if i do not send the list directly but send a class containing the list it is internal and needed do i still need to use ref or if i pass it between functions exvoid aref linkedlistint list blistvoid bref linkedlistint list mylist list,['c#'] +16883,get first 100 characters from string respecting full words i have asked a similar question here before but i need to know if this little tweak is possible i want to shorten a string to 100 characters and use small substrbig 0 100 to do so however this just takes the first 100 characters and does not care whether it breaks up a word or notis there any way to take up to the first 100 characters of a string but make sure you do not break a wordexamplebig this is a sentence that has more than 100 characters in it and i want to return a string of only full words that is no more than 100 characterssmall some functionbigsmall this is a sentence that has more than 100 characters in it and i want to return a string of onlyis there a way to do this using php,['php'] +16895,regular expression to limit string length i have an issue where i need to use a regularexpressionvalidator to limit the length of a string to 400 charactersmy expression was 0400my question is there a way to limit the length of characters to 400 without taking into consideration blank spacesi want to be able to accept blank spaces in the string but not count it in the length is this possible,['asp.net'] +16898,whats faster memcached or mysql in memory table like heap if i have a pretty static set of data that i want to be able to access as quickly as possible should i cache the data into memcached or should i store it in a heap table or something inside mysql would one scale better than the otheris there some other option that is even faster,['mysql'] +16899,what patterns do you use to decouple interfaces and implementation in c one problem in large c projects can be build times there is some class high up in your dependency tree which you would need to work on but usually you avoid doing so because every build takes a very long time you do not necessarily want to change its public interface but maybe you want to change its private members add a cachevariable extract a private method the problem you are facing is that in c even private members are declared in the public header file so your build system needs to recompile everythingwhat do you do in this situationi have sketched two solutions which i know of but they both have their downsides and maybe there is a better one i have not yet thought of,['c++'] +16904,why in java functions are written virtual by default and c nonvirtual why java functions are virtual by defaultbut c its the opositewhich is betteror what is the advantage and thisadvantage in boththankssc,"['c#', 'java']" +16905,what size do you use for varcharmax in your parameter declaration i normally set my column size when creating a parameter in adonetbut what size do i use if the column is varcharmaxcmdparametersaddblah sqldbtypevarchar value blah,['c#'] +16908,how to auto generate rails rest api documentation for controllers how to automatically generate api documentation for rails rest controlleris there any example i can look into using rdoc to do this,['ruby-on-rails'] +16909,how to integrate zsh and ipython i have been in love with zsh for a long time and more recently i have been thiscovering the advantages of the ipython interactive interpreter over python itself being able to cd to ls to run or to is indeed very handy but now it feels weird to have such a clumsy shell when in ipython and i wonder how i could integrate my zsh and my ipython betterof course i could rewrite my zshrc and all my scripts in python and emulate most of my shell world from ipython but it does not feel right and i am obviously not ready to use ipython as a main shell anywayso here comes my question how do you work efficiently between your shell and your python commandloop am i missing some obvious integration strategy should i do all that in emacs,['python'] +16912,basesend include instancemethods what does this do i am looking at a module x which contains two modules called instancemethods and classmethodsthe last definition in module x is this def selfincludedbase basesend include instancemethods basesend extend classmethods endwhat does this do,['ruby'] +16918,setting up ecommerce in aspnet i am an ecommerce newbie i am looking for an exceptional guide for setting up casual ecom or plugging it into an exsiting site for aspnet complete with recommended components for a product catalogshopping cartmerchant account and any anything else i might needi do not have a large product inventory less than 50 and do not plan on doing more than 100 transactions a dayideally the components would be highly configurable and be reasonable in price or free i am not looking for someone to go shopping for me i would appreciate it if youve actually used or had experience with the components you recommendfailing that if you can find a dynamite articlewalkthrough i would take that too i did not find much on the end of a google searchthanks in advanceupdatei wouldnt suggest aspnet storefront to anyone especially if you want source code their product is for lack of a better word terrible dotnetcart is half decent although they have a pretty awkward api,['asp.net'] +16919,nhibernate on azure has anyone tried nhibernate on azure is there conflicts with the medium trust or sql integration,['c#'] +16936,onkeydown issue i would like to create a photovideo capture application i have created a captureview class which extends surfaceview and placed it in the main formthe main forms activity has oncreateoptionsmenu method which creates a menu the menu worked fine but then i tried to implement a method onkeydownoverridepublic boolean onkeydownint keycode keyevent event ifeventgetaction keyeventaction down switchkeycode case keyeventkeycode camera videopreviewtakepicture return true return superonkeydownkeycode eventthe menu does not appear anymore and the method does not catch onkeydown eventdoes anyone know what could be the reason for this issue,['android'] +16942,reset multiple css styles for one single div element my question is if it is possible to reset css styles a lot off them for a single divand all elements that are contained in that divi am asking because i found this tutorial for a jquery shoutbox that has it is owncss filei can not just copy the styles over to my own css file because it will screw up the rest off the page where the styles are already set i thought off using a divwrapper and apply all those resets only to that onei am just not sure if it is possiblei only know this waydivwrapper td set styles charset utf8 general reset html body div span applet object iframe h1 h2 h3 h4 h5 h6 p blockquote pre a abbr acronym address big cite code del dfn emfont img ins kbd q s samp small strike strong sub sup tt var dl dt dd ol ul li fieldset form label legend table caption tbody tfoot thead tr th td border0pt nonefontfamilyinheritfontsize 100fontstyleinheritfontweightinheritmargin0ptpadding0ptverticalalignbaselinethanks richard,"['jquery', 'css']" +16943,passing javascript variable to script languagejavascript typetextjavascriptvar scrt var 10 scripthtml parthtml this is a a href 2html key scrt varlink ahtmli just want to sent the javascript variable to link url parameter no ajax,['javascript'] +16959,how to code drivers i want to code drivers in c in linux os though i think its very tough can i get some hints as to how to start or books to follow drivers can be from my usb port to graphics card i know as to where i can search for books i would like to know as to what the basic knowledge i should start with do i need to have hardware knowledge and which specific books are good for novice like me,['c'] +16972,trouble creating new entity data model i am trying to add a new adonet entity data model to an mvc project i am working onwhen i complete the wizard choosing my db and tables just a single table for now i get an error exception has been thrown by the target of an invocation and it throws me back the add new item dialogat this point an empty data model has been created in my project if i then choose update model from database and complete the wizard again i get a similar erroran exception of type systemreflectiontargetinvocationexception occurred while attempting to update from the database the exception message is exception has been thrown by the target of an invocationany ideas i have tried doing this in an empty project also and still no dicealex,['asp.net'] +16976,which java blocking queue is most efficient for singleproducer singleconsumer scenarios i am working on a standard java system with critical timing requirements for my producers 1100s of ms matters i have a producer placing stuff in a blocking queue and a single consumer later picking up that stuff and dumping it to a file the consumer blocks when data is not available obviously blocking queue is the appropriate interface but which actual implementation should i choose if i want to minimize the cost to the producer i wan to play as little as possible on things like locking and allocating when i am putting stuff in the queue and i do not mind if the consumer has to wait a lot longer or work a lot harderis there an implementation that can be faster because i only have a single consumer and single producer,['java'] +16977,change text of return keyboard button how can i change the standard text of the return button to something elsei want it to be add,['ios'] +16979,fading in a background image i have a web page that uses a large image for its background i was hoping to use jquery to load the image once it is downloaded basically the way that bingcom loads its background image is this possible with jquery if so is there a plugin that you would recommend,['jquery'] +16984,scoring rating engines advice and examples i need to create a flexible and preferably dynamic scoring engine much like a credit scoring or premium calculating system does anyone with practical experience of creating a scoring engine have any advice examples or suggested patternsi already know aboutrete algorithmficothe open source rules engines listed here thanksedit to provide a little more detail ok so i have had a look around and i think a rules engine is what i am after it is more flexible and rules can be used to achieve pretty much anything however the material i can find on the web is highly abstract the rete algorithm nodes forward chaining and so on i really need practical architectural advice so for example how would you tackle these problemsassume the rules engine itself is generic and agnostic of the context in which it is being used so it is pluggable now in order to use it you have to feed specific and identifiable data items in and match those items with conditions and rules so how would you go about solving this conundrumhow would you handle the situation where one rule updates a data item which invalidates other previously assessed rules,['.net'] +16993,swing cannot get jbutton to update repaint not working i am using swing for the first time to create a simple gui it consists of a jframe upon which i have placed a single jbutton which when clicked calls some other code which takes approx 3 seconds to returnjust before the call to this code in actionperformed i want to update the text on the button to inform the user that processing is occuring my problem is that the text on the button does not update until after the 3second call has returned i want the updated text to be present during the call then i will change it back afterwardscalling repaint on the jbutton does not do anything and calling it on the jframe results in exception in thread awteventqueue0 javalangnullpointerexception being thrown when i click the button,['java'] +16994,redirecting fortran called via f2py output in python i am trying to figure out how to redirect output from some fortran code for which i have generated a python interface by using f2py i have triedfrom fortran code import fortran functionstdout holder sysstdoutstderr holder sysstderrsysstdout filedevnullwfortran functionsysstdoutclosesysstderrclosesysstdout stdout holdersysstderr stderr holderthis is the de facto method of redirecting output in python but it does not seem to work in this case ie the output is thisplayed anywayi did find a mailing list post from 2002 saying that it is possible to read messages from pts devices eg ttysnoop does this information on ttysnoop seems to be pretty difficult to find online i do not think it is been updated in quite a few years for example the first result on google for ttysnoop has only dead links to tarballs rpms and debs and this request for a port to os x received the response no luck it requires some linux specific utmp functions which i cannot createi am open to any suggestions on how to redirect the output it does not have to use ttysnoopthanks,['python'] +16999,how do i get a keyiterator for a linkedhashmap by looking at the source code for linkedhashmaps from sun i see that there is a private class called keyiterator i would like to use this how can i gain access,['java'] +17000,reverse engineering a statistics data file from my insulin pump controller this may or may not be a grey area subject though my intentions are certainly not so my intention is not to stir up an ethical debate on the topic of reverse engineering i am a type 1 diabetic currently undergoing pump therapy i am an omnipod user it is a thisposable pod that adheres to my body and thispenses insulin for 3 days it is controlled by a personal diabetes manager pdm seen below which controls how much insulin to thispense during meals bloor sugar readings and it contains a food index for carb counting on the gothe new pdm has a usb port for the downloading of data the software is free for windows users a package called copilot but there is no mac supportupon plugging the pdm into my mac it mounted like any other usb device would and presented me with a readable volume with a single file on it with an ibf extension it weighs in at 16kbmy first instinct was to pass it through a text editor and was presented with a very binary looking file i then passed it through strings see below and opened it up with a hex editor though i could not gain much information aside from the strings below no compression format details or anything strings omnipoddataibf insuletomnipodbasal 1postmealemealpremealebedtimeprebedtimepwhat should be my next step in this process i am a dynamic language guy so any resources for ruby would be great or python are there any test driven reverse engineering processesas far as the data i am looking to obtain it is information i would like to chart to gain more information on my progress insulin intake blood sugar readings timestamps all of which is possible in the windows software package,['ruby'] +17001,how do i use securestring securely all of the examples i have seen end up converting a securestring back to a standard string before using it defeating the object whats a good way of using a secure string without this problemi know i can marshall the securestring to a bstr but what can i do with this bstr can i get the characters back one at a time if so how,"['c#', '.net']" +17010,is it worth wrapping a logging framework in an additional layer i am currently looking at upgrading the logging mechanism in a mediumtolargesized java codebase messages are currently logged using static methods on a debug class and i have recommended switching from this to something like slf4j or commonsloggingthe application architect prefers that i encapsulate the dependency on slf4j possibly by wrapping it up in the aforementioned debug class this will make it easier to change the logging implementation in the futurethis seems like overkill to me as slf4j is already abstracting the concrete logging implementationis it worth wrapping a 3rdparty logging abstraction like slf4j in another homegrown abstraction,['java'] +17012,javascript how to detect if document has loaded ie 7firefox 3 i want to call a function after a document loads but the document may or may not have finished loading yet if it did load then i can just call the function if it did not load then i can attach an event listener i cannot add an eventlistener after onload has already fired since it would not get called so how can i check if the document has loaded i tried the code below but it does not entirely work any ideasvar body documentgetelementsbytagnamebody0 condition does not workif body bodyreadystate loaded dostufunction else code below works if windowaddeventlistener windowaddeventlistenerload dostufunction false else windowattacheventonload dostufunction,['javascript'] +17014,how to strip whitespaceonly text nodes from a dom before serialization i have some java 50 code that constructs a dom from various cached data sources then removes certain element nodes that are not required then serializes the result into an xml string using serialize dom back into a stringwriter out new stringwritertransformer tf transformerfactorynewinstancenewtransformertfsetoutputpropertyoutputkeysomit xml declaration yestfsetoutputpropertyoutputkeysencoding utf8tfsetoutputpropertyoutputkeysindent notftransformnew domsourcedoc new streamresultoutreturn outtostringhowever since i am removing several element nodes i end up with a lot of extra whitespace in the final serialized documentis there a simple way to removecollapse the extraneous whitespace from the dom before or while it is serialized into a string,['java'] +17016,union and struct packing problem i am writing some software where each bit must be exactit is for the cpu so packed is very important typedef unionuint32 t rawstructunsigned int present1unsigned int rw1unsigned int user1unsigned int dirty1unsigned int free7unsigned int frame20 packed packed page union tthat is my structure and union it does not work howeverpage union t p thispframetrg pagepuseruserprwrwppresentpresentand thisprawtrg page12 user2 rw1 presentshould create the same uint32 but they do not create the same thingis there something i can not see that is wrong with my union,['c'] +17018,any reason not to slap the synchronized keyword everywhere in my java project almost every nonstatic method i have written is synchronized i have decided to fix up some code today by removing most of the synchronized keywords right there i created several threading issues that took quite a while to fix with no increase in performance in the end i reverted everythingi do not see anyone else writing code with synchronized everywhere so is there any reason i should not have synchronized everywherewhat if i do not care too much about performance ie the method is not called more than once every few seconds,['java'] +17019,hibernate polymorphism this is a hibnerate polymorphism question and a data model designquestion they are intertwingled i have used hibernate in the pastand have enjoyed it but sometimes i find it difficult to thinkabout anything but trivial designs not a knock on hibernate justan observation that orm in general can be challengingi think this is a hibernate 101 question but i am not sure what i am trying to achieve may not even be possiblei have an abstract class fruit that will be subclassed into appleand orange i have a note class that represents notes or commentsabout apples and oranges an apple or orange can have many notesassociated with it but only one apple or orange will ever beassociated with a given notehere are sketches of the classes where i am for now omitting wherethe object ids go and the properties of apples that thistinguishthem from oranges for the time being i do not feel strongly about which hibernate inheritance strategy i use abstract public class fruit apples have notes written about thempublic class apple extends fruit private setnote note onetomanycascade cascadetypeall public setnote getnote return note oranges have notes written about thempublic class orange extends fruit private setnote note onetomanycascade cascadetypeall public setnote getnote return note here is the note class currently implemented wherein we see that it has fields for both an apple and an orange the flaw or inelegance in this design is that a single note instance will only point toone of apple or orange and never both so if a note is bound to an apple the orange field is superfluous and unsightly andviceversa a note about an apple or orangepublic class note private string thenote private apple apple private orange orange with the usual many to one mapping manytoone joincolumnname apple id public apple getapple return apple with the usual many to one mapping manytoone joincolumnname orange id public orange getorange return orange however this is the note class that i think i want to base mydesign on but i am not sure how to think about this with respectto hibernate annotation and table mapping a note about a fruitpublic class note private string thenote private fruit fruit whereupon fruit will be either an apple or orange instancecan this latter note class with its reference to a fruit which will actually hold an apple or orange even be reconciled with hibernate orm mapping if yes can someone please talk about how,['java'] +17026,how to add an onchange event to select tag in rails how do i add an onchange event hereframework railsdatabase mysqli am populating the options from the database and that made me use options from collection for selectselect tagvariableoptions from collection for selectall id name,['ruby-on-rails'] +17032,background image for navigation view i am having problems with properly thisplaying background image of navigation view here is the pichere is the code idinitwithstyleuitableviewstylestyle if self super initwithstylestyle uiimage image uiimage imagenamed bg table activepng uiimageview imageview uiimageview alloc initwithimage image uibarbuttonitem addbutton uibarbuttonitem alloc initwithtitlenslocalizedstringsettings styleuibarbuttonitemstyledone targetself actionselectorgotosettings selfnavigationitemtitleview imageview selfnavigationitemrightbarbuttonitem addbutton selfnavigationitemhidesbackbutton true return selfhow can i make the picture stretch to the whole navigation view,['iphone'] +17038,how to preserve empty xml tags after xslt prevent collapsing them from to say i have a very simple xml with an empty tag broot afooa bb cbarcrooti am currently using xslt to remove a few tags like c for examplexml version10 xslstylesheet version20 xmlns xmlnsxslxsloutput methodxml indentno encodingutf8 omitxmldeclarationyes xsltemplate matchxslcopyxslcopyof select xslapplytemplates xslcopyxsltemplatexsltemplate matchc xslstylesheetso far ok but the problem is i end up having an output like thisroot afooa brootwhen i actually really wantroot afooa bbrootis there a way to prevent b from collapsingthanks,['java'] +17044,how to create a lightweight c code sandbox i would like to build a c preprocessor compiler that allows functions to be collected from local and online sources iefetch mp3filebuilder fetch ipoddevicereader void mymodule main mp3filebuildersome datathat is the easy part the hard part is i need a reliable way to sandbox the imported code from direct or unrestricted access to thisk or system resources including memory allocation and the stack i want a way to safely run small snippets of untrusted c code modules without the overhead of putting them in separate process vm or interpreter a separate thread would be acceptable thoughrequirementsi would need to put quotas on its access to data and resources including cpu time i will block direct access to the standard librariesi want to stop malicious code that creates endless recursioni want to limit static and dynamic allocation to specific limitsi want to catch all exceptions the module may raise like divide by 0modules may only interact with other modules via core interfacesmodules may only interact with the system io etc via core interfacesmodules must allow bit ops maths arrays enums loops and branchingmodules cannot use asmi want to limit pointer and array access to memory reserved for the module via a custom safe mallocmust support ansi c or a subset see belowthe system must be lightweight and crossplatform including embedded systems the system must be gpl or lgpl compatiblei am happy to settle for a subset of c i do not need things like templates or classes i am primarily interested in the things highlevel languages do not do well like fast maths bit operations and the searching and processing of binary datait is not the intention that existing c code can be reused without modification to create a module the intention is that modules would be required to conform to a set of rules and limitations designed to limit the module to basic logic and transformation operations like a video transcode or compression operations for examplethe theoretical input to such a compilerpreprocessor would be a single ansi c file or safe subset with a module main function no includes or preprocessor directives no asm it would allow loops branching function calls pointer maths restricted to a range allocated to the module bitshifting bitfields casts enums arrays ints floats strings and maths anything else is optionalexample implementationheres a pseudocode snippet to explain this better here a module exceeds it is memory allocation quota and also creates infinite recursionbuffer transcodetoavi main in buffer int buffer10 allocation exceeding quota whiletrue infinite loop return bufferheres a transformed version where our preprocessor has added watchpoints to check for memory usage and recursion and wrapped the whole thing in an exception handlerbuffer transcodetoavi main in buffer try core funcstart file func tell core were executing this function buffer core newarray10 file func memory allocation from quota whiletrue core checkloop file func line break break loop on recursion limit core moduleend file func catch core exceptionhandler file func return bufferi realise performing these checks impact the module performance but i suspect it will still outperform highlevel or vm languages for the tasks it is intended to solve i am not trying to stop modules doing dangerous things outright i am just trying to force those dangerous things to happen in a controlled way like via user feedback ie module x has exceeded it is memory allocation continue or abortupdatethe best i have got so far is to use a custom compiler like a hacked tcc with bounds checking and some custom function and looping code to catch recursions i would still like to hear thoughts on what else i need to check for or what solutions are out there i imagine that removing asm and checking pointers before use solves a lot of the concerns expressed in previous answers below i added a bounty to pry some more feedback out of the so community for the bounty i am looking fordetails of potential exploits against the theoretical system defined abovepossible optimisations over checking pointers on each accessexperimental opensource implementations of the concepts like google native clientsolutions that support a wide range of os and devices no oshardware based solutionssolutions that support the most c operations or even c if that is possibleextra credit for a method that can work with gcc ie a preprocessor or small gcc patchi will also give consideration to anyone who can conclusively prove what i am attempting cannot be done at all you will need to be pretty convincing though because none of the objections so far have really nailed the technical aspects of why they think it is impossible in the defence of those who said no this question was originally posed as a way to safely run c i have now scaled back the requirement to a limited subset of cmy understanding of c could be classed as intermediate my understanding of pc hardware is maybe a step below advanced try to coach your answers for that level if you can since i am no c expert i will be going largely based on votes given to an answer as well as how closely the answer comes to my requirements you can assist by providing sufficient evidence for your claims respondents and by voting everyone else i will assign an answer once the bounty countdown reaches 6 hoursfinally i believe solving this problem would be a major step towards maintaining cs relevance in an increasingly networked and paranoid world as other languages close the gap performancewise and computing power grows it will be harder and harder to justify the added risk of c development as it is now with asm i believe your answers will have a much greater relevance than scoring a few so points so please contribute what you can even if the bounty has expired,['c'] +17051,update appconfig systemnet setting at runtime i need to update a setting in the systemnet sectiongroup of a net exe appconfig file at runtime i do not have write access to the original config file at runtime i am developing a net dll addin which is hosted in an exe provided by the app which i have no control over so i was hoping to save a copy of the file and replace the config in the exe with the modified version at runtime i have tried the following but it is not working any suggestions configuration config configurationmanageropenexeconfigurationconfigurationuserlevelnone netsectiongroup netsectiongroup configgetsectiongroupsystemnet as netsectiongroup netsectiongroupsettingshttpwebrequestuseunsafeheaderparsing true configsaveascprogramdatatestconfig configurationsavemodefull appdomaincurrentdomainsetdataapp config file cprogramdatatestconfig,"['c#', '.net']" +17073,can windows drivers be written in python can windows drivers be written in python,['python'] +17076,instantiate an object with a runtimedetermined type i am in a situation where i would like to instantiate an object of a type that will be determined at runtime i also need to perform an explicit cast to that typesomething like thisstatic void casttestmyenum val call a native function that returns a pointer to a structure intptr somenativefunctionparams determine the type of the structure based on the enum value type structtype gettypefromenumval structtype mystruct structtypemarshalptrtostructureintptr structtypethis is obviously not valid code but i hope it conveys the essence of what i am trying to do the method i am actually working on will have to perform the marshaling operation on 35 different types i have several other methods that will need to do something similar with the same set of types so i would like to isolate the typedetermining logic from these methods so that i only need to write it once and so that the methods stay clean and readablei must admit to being a total novice at design could anyone suggest a good approach to this problem i suspect there might be an appropriate design pattern that i am unaware of,"['c#', '.net']" +17077,what happens if a throw statement is executed outside of catch block in c throw when executed inside a catch block rethrows the currently caught exception outside the blockin this answer an idea of exception thispatcher is brought up as a solution to reducing code duplication when using complex exception handling oftentry codethatmightthrow catch exceptionhandlervoid exceptionhandler try throw catch fileexception e do handling with some complex logic delete e catch genericexception e do handling with other complex logic delete e throwing a pointer or a value does not make any difference so it is out of the questionwhat happens if exceptionhandler is called not from a catch blocki tried this code with vc7int main int char try throw catch messagebox 0 0 return 0 first it causes the debugger to indicate a firstchance exception then immediately an unhandled exception if i run this code outside the debugger the program crashes the same way as if abort has been calledwhat is the expected behaviour for such situations,['c++'] +17085,touchxml parsing xml attributes how do i use touchxml to parse this xml i want to store all the attributes as keyvalue pairs in a dictionaryplayer playernamepadraig harrington currentposition1 currentrank1 countryirl numberofholesplayed18 parrelativescore3roundscore roundnumber1 score74 roundscore roundnumber2 score68 roundscore roundnumber3 score72 roundscore roundnumber4 score69 playerplayer playernameian poulter currentposition2 currentrank2 countryeng numberofholesplayed18 parrelativescore7roundscore roundnumber1 score72 roundscore roundnumber2 score71 roundscore roundnumber3 score75 roundscore roundnumber4 score69 playerplayer playernamehenrik stenson currentposition3 currentrankt3 countryswe numberofholesplayed18 parrelativescore9roundscore roundnumber1 score76 roundscore roundnumber2 score72 roundscore roundnumber3 score70 roundscore roundnumber4 score71 playeri have no problem is the xml is formatted like soplayercountryukcountrynumberofholesplayed12numberofholesplayedbut i am not sure what to do when dealing with attributeshow can you get attributes with touchxml in particular if a node has a subnode that also has attributes as per the first example xml file in the first xml example i managed to get the player attributes but not the child nodes roundscore attributeswould love a helping handthanksdan,['iphone'] +17087,is it useful in c to apply demorgans theorem to manually optimize boolean expressions in conditional statements eg if conditions back in the day when i did most of my work in c and c as a matter of course i would manually apply demorgans theorem to optimize any nontrivial boolean expressionsis it useful to do this in c or does the optimizer render this unnecessary,['c#'] +17089,how to manage the game state in face of the edt i am developing a real time strategy game clone on the java platform and i have some conceptional questions about where to put and how to manage the game state the game uses swingjava2d as rendering in the current development phase no simulation and no ai is present and only the user is able to change the state of the game for example builddemolish a building addremove production lines assemble fleets and equipment therefore the game state manipulation can be performed in the event thispatch thread without any rendering lookup the game state is also used to thisplay various aggregated information to the userhowever as i need to introduce simulation for example building progress population changes fleet movements manufacturing process etc changing the game state in a timer and edt will surely slow down the rendering lets say the simulationai operation is performed in every 500ms and i use swingworker for the computation of about 250ms in length how can i ensure that there is no race condition regarding the game state reads between the simulation and the possible user interaction i know that the result of the simulation which is small amount of data can be efficiently moved back to the edt via the swingutilitiesinvokelater callthe game state model seems to be too complex to be infeasible for just using immutable value classes everywhereis there a relatively correct approach to eliminate this read race condition perhaps doing a fullpartial game state cloning on every timer tick or change the living space of the game state from edt into some other threadupdate from the comments i gavethe game operates with 13 ai controlled players 1 human player and has about 10 game objects planets buildings equipment research etc a game object for example has the following attributesworld planets players fleets planet location owner population type map buildings taxation allocation building location enabled energy worker health in a scenario the user builds a new building onto this planet this is performed in edt as the map and buildings collection needs to be changed parallel to this a simulation is run on every 500ms to compute the energy allocation to the buildings on all game planets which needs to traverse the buildings collection for statistics gathering if the allocation is computed it is submitted to the edt and each buildings energy field gets assignedonly human player interactions have this property because the results of the ai computation are applied to the structures in edt anywayin general 75 of the object attributes are static and used only for rendering the rest of it is changeable either via user interaction or simulationai decision it is also ensured that no new simulationai step is started until the previous one has written back all changesmy objectives areavoid delaying the user interaction eg user places the building onto the planet and only after 05s gets the visual feedbackavoid blocking the edt with computation lock wait etcavoid concurrency issues with collection traversal and modification attribute changesoptionsfine grained object lockingimmutable collectionsvolatile fieldspartial snapshotall of these have advantages thisadvantages and causes to the model and the gameupdate 2 i am talking about this game my clone is here the screenshots might help to imagine the rendering and data model interactionsupdate 3i will try to give a small code sample for clarify my problem as it seems from the comments it is misunderstoodlistgameobject largelistofgameobjects listbuilding prefilteredlistofbuildings in edtpublic void onaddbuildingclicked building b new building100 kw largelistofgameobjectsaddb prefilteredlistofbuildingsaddb in edtpublic void paintgraphics g int y 0 for building b prefilteredlistofbuildings gdrawstringintegertostringbpowerassigned 0 y y 20 in edtpublic void assignpowertobuilding b int amount bpowerassigned amount in simulation threadpublic void thistributepower int sum 0 for building b prefilteredlistofbuildings sum bpowerrequired final int alloc sum prefilteredlistofbuildingssize 1 for final building b prefilteredlistofbuildings swingutilitiesinvokelater assignpowertob alloc so the overlapping is between the onaddbuildingclicked and thistributepower now imagine the case where you have 50 of these kind of overlappings between various parts of the game model,['java'] +17090,firefox throwing a exception with html canvas putimagedata so i was working on this little javascript experiment and i needed a widget to track the fps of it i ported a widget i have been using with actionscript 3 to javascript and it seems to be working fine with chromesafari but on firefox is throwing an exceptionthis is the experimentdepth of fieldthis is the errorexception an invalid or illegal string was specified code 12 nsresult 0x80530c ns error dom syntax err location of field debugjsnethiresdebugstatsjs line 105the line that is complaning about is this onegraphputimagedatagraphdata 1 0 0 0 69 50which is a crappy code to scroll the bitmap pixels the idea is that i only draw a few pixels on the left of the bitmap and then on the next frame i copy the whole bitmap and paste it on pixel to the right this error usually is thrown because youre pasting a bitmap bigger than the source and it is going off the limits but in theory that should not be the case as i am defining 69 as the width of the rectangle to paste being the bitmap 70px wideand this is full codevar stats basefps nulltimer nulltimerstart nulltimerlast nullfps nullms nullcontainer nullfpstext nullmstext nullmemtext nullmemmaxtext nullgraph nullgraphdata null init functionuserfpsbasefps userfpstimer 0timerstart new date 0timerlast 0 fps 0ms 0container documentcreateelementdivcontainerstylefontfamily arialcontainerstylefontsize 10pxcontainerstylebackgroundcolor 033containerstylewidth 70pxcontainerstylepaddingtop 2pxfpstext documentcreateelementdivfpstextstylecolor f00fpstextstylemarginleft 3pxfpstextstylemarginbottom 3pxfpstextinnerhtml fpscontainerappendchildfpstextmstext documentcreateelementdivmstextstylecolor 00ff00mstextstylemarginleft 3pxmstextstylemarginbottom 3pxmstextinnerhtml mscontainerappendchildmstextmemtext documentcreateelementdivmemtextstylecolor 00fmemtextstylemarginleft 3pxmemtextstylemarginbottom 3pxmemtextinnerhtml memcontainerappendchildmemtextmemmaxtext documentcreateelementdivmemmaxtextstylecolor ff0070memmaxtextstylemarginleft 3pxmemmaxtextstylemarginbottom 3pxmemmaxtextinnerhtml maxcontainerappendchildmemmaxtextvar canvas documentcreateelementcanvascanvaswidth 70canvasheight 50containerappendchildcanvasgraph canvasgetcontext2dgraphfillstyle 033graphfillrect0 0 canvaswidth canvasheight graphdata graphgetimagedata0 0 canvaswidth canvasheightsetintervalthisupdate 10basefpsreturn containerupdate functiontimer new date timerstartif timer 10 timerlastfpstextinnerhtml fps fps basefpstimerlast timergraphputimagedatagraphdata 1 0 0 0 69 50graphfillrect00150graphdata graphgetimagedata0 0 70 50var index mathfloormathmin50 fps basefps 50 280 70 4 graphdatadataindex graphdatadataindex 1 256index mathfloormathmin50 50 timer ms 5 280 70 4 graphdatadataindex 1 256graphputimagedata graphdata 0 0fps 0fpsmstextinnerhtml ms timer msms timerany ideas thanks in advance,"['javascript', 'html']" +17098,obfuscate strings in python i have a password string that must be passed to a method everything works fine but i do not feel comfortable storing the password in clear text is there a way to obfuscate the string or to truly encrypt it i am aware that obfuscation can be reverse engineered but i think i should at least try to cover up the password a bit at the very least it wont be visible to a indexing program or a stray eye giving a quick look at my codei am aware of pyobfuscate but i do not want the whole program obfuscated just one string and possibly the whole line itself where the variable is definedtarget platform is gnu linux generic if that makes a difference,['python'] +17114,type checking typeof gettype or is i have seen many people use the following codetype t typeofobj1if t typeofint some code herebut i know you could also do thisif obj1gettype typeofint some code hereor thisif obj1 is int some code herepersonally i feel the last one is the cleanest but is there something i am missing which one is the best to use or is it personal preference,['c#'] +17119,calling a method from another method in the same class in c i wrote a method that works fine for a in a class i want to write another method in that class that calls the first method sovoid aa do stuffvoid ab a do stuffi suppose i could just rewrite b so ba obj but i do not want to in java can you do something like thisai want to do objb where obja would be called as a result of objb,['c++'] +17123,what does unauthenticated user mean in mysql mysql show full processlist id user host db command time state info 1 system user null connect 623 waiting for master to send event null 2 system user null connect 0 reading event from the relay log null 400 root localhost v3 sleep 68 null 585 root localhost v3 query 0 null show full processlist 748 unauthenticated user 1721902732833 null connect null login null 749 unauthenticated user 1721902732836 null connect null login null 750 unauthenticated user 1721902732838 null connect null login null 751 unauthenticated user 1721902732841 null connect null login null 752 unauthenticated user 1721902732844 null connect null login null 753 unauthenticated user 1721902732846 null connect null login null 754 unauthenticated user 1721902732848 null connect null login null 755 unauthenticated user 17219013946827 null connect null login null 756 unauthenticated user 17219013946830 null connect null login null 757 unauthenticated user 17219013946831 null connect null login null 758 unauthenticated user 1721902732857 null connect null login null 759 unauthenticated user 1721902732858 null connect null login null 760 unauthenticated user 1721902732859 null connect null login null 761 unauthenticated user 1721902732863 null connect null login null 762 unauthenticated user 1721902732864 null connect null login null 763 unauthenticated user 1721902732866 null connect null login null 764 unauthenticated user 1721902732870 null connect null login null 765 unauthenticated user 1721902732871 null connect null login null 766 unauthenticated user 17219013946833 null connect null login null 767 unauthenticated user 1721902732878 null connect null login null 768 unauthenticated user 1721902732881 null connect null login null 769 unauthenticated user 1721902732885 null connect null login null 770 unauthenticated user 17219013946835 null connect null login null 771 unauthenticated user 17219027328 null connect null login null 772 unauthenticated user 1721902732890 null connect null login null 773 unauthenticated user 17219013946837 null connect null login null 774 unauthenticated user 17219013946839 null connect null login null 775 unauthenticated user 17219013946841 null connect null login null 776 unauthenticated user 17219013946844 null connect null login null 7 unauthenticated user 17219013946845 null connect null login null 778 unauthenticated user 17219013946847 null connect null login null 779 unauthenticated user 1721902732898 null connect null login null 780 unauthenticated user 1721902732900 null connect null login null 781 unauthenticated user 17219013946850 null connect null login null 782 unauthenticated user 17219013946852 null connect null login null 783 unauthenticated user 17219013946854 null connect null login null 784 unauthenticated user 17219013946857 null connect null login null 785 unauthenticated user 17219013946859 null connect null login null 786 unauthenticated user 1721902732903 null connect null login null 787 unauthenticated user 17219013946862 null connect null login null 788 unauthenticated user 17219013946865 null connect null login null 789 unauthenticated user 17219013946866 null connect null login null 790 unauthenticated user 17219013946868 null connect null login null 791 unauthenticated user 17219013946871 null connect null login null 792 unauthenticated user 17219013946873 null connect null login null 793 unauthenticated user 1721902732907 null connect null login null 794 unauthenticated user 1721902732909 null connect null login null 795 unauthenticated user 1721902732911 null connect null login null 796 unauthenticated user 17219013946875 null connect null login null 797 unauthenticated user 1721902732914 null connect null login null 798 unauthenticated user 1721902732916 null connect null login null 799 unauthenticated user 17219013946877 null connect null login null 800 unauthenticated user 17219013946879 null connect null login null 57 rows in set 0 sec,['mysql'] +17125,c formatted input how to skip tokens suppose i have an input file in this formatval1 val2 val3val1 val2 val3i am writing a program that would be interested only in val1 and val3 in c if i wanted to skip the second value i would do as followschar val1length char val3lengthfile input filefscanfinput file s s s val1 val3meaning i would use the s formatter to make fscanf read this token and skip it how do i do this with cs cin is there a similar command or do i have to read to a dummy variablethanks in advance,['c++'] +17128,how can i use vim to do net development visual studio is the defacto editor but what are our other options that avoid a heavy ui while still integrating with a c build chainlooking for options which preferably use vi or vim directly and those which emulate some or all of the functionality of vi andor vim,"['c#', '.net']" +17135,jquery autocomplete textbox on selected events how do i fire another event after i have completed the selection on the textbox that has autocomplete i want to show a valid div area based on the selected value,['jquery'] +17136,c strategy design pattern by delegate vs oop i wonder whats the proscons of using delegate vs oop when implementing strategy design patternwhich one do you recommend to use or what kind of problem does delegate solve and why should we use oop if oop is betterthankstep,['c#'] +17139,c is calling an event handler explicitly really a good thing to do this question is related to c but may be applicable to other languages as well i have a reservation against using code such as the followingusing systemwindowsformsclass myform form private timer mytimer private button mybutton public myform initialize the components etc mytimertick new eventhandler mytimer tick mybuttonclick new eventhandler mybutton click mytimerstart private void mytimer tick object sender eventargs eventargs mytimerstop also i see a lot of usage of timerenabled truefalse instead of mybutton click this ea or event eventargsempty or null return private void mybutton click object sender eventargs eventargs do a lot of stuff with lots of logic that does not even use the state of the eventargs return am i alone in that the above style is a pet peeve of mine are there others who enjoy the clarity of separating event handling from the workload of functions or even separating out complex routines into separate functionsis there even an accepted style i feel like any expressiveness and flexibility that event handling in c has can be lost with styles like this i feel like if you have a method that means a button has been clicked then it should only be called when a button is clickedto those who write like this i would say if you insist on having an eventhandler method to handle your timer tick and your button click then call it something other than button click perhaps handleuserevent object sender eventargs eventargs really though the question is are there any style guidelines that are widely used which either support or thiscourage usage such as the above,"['c#', '.net']" +17145,what is my script src url is there a simple and reliable way to determine the url of the currentlyexecuting javascript file inside a web pagemy only thought on this is to scan the dom for all the script src attributes to find how the current file was referenced and then figure out the absolute url by applying it to documentlocation anyone have other ideas is there some supereasy method i completely overlookedupdate script elements accessed via the dom already have a src property which contains the full url i do not know how ubiquitousstandard that is but alternatively you can use getattributesrc which will return whatever raw attribute value is in the xhtml,['javascript'] +17156,easiest way to obtain database metadata in java i am familiar with the javasqldatabasemetadata interface but i find it quite clunky to use for example in order to find out the table names you have to call gettables and loop through the returned resultset using wellknown literals as the column namesis there an easier way to obtain database metadata,['java'] +17160,can i call an overloaded constructor from another constructor of the same class in c can i call an overloaded constructor from another constructor of the same class in c,['c#'] +17169,will setinterval drift this is a pretty simple question really if i use setintervalsomething 10 can i be completely sure that after say 31 days it will have triggered something exactly 60602431 times or is there any risk for so called drifting,['javascript'] +17179,removing the apache tomcat runtime from a project in eclipse i have got a project i have been building on eclipse ganymede targetted at tomcat 60 i have imported it into europa and i need it to run on apache tomcat 55i cannot find the reference to where the runtime is set to 60 to remove it i have tried going to windows preferences server and i have installed the 55 runtimei cannot however seem to find where the reference is to runtime 60 to remove itany help would be appreciatedupdatei cant find any reference to tomcat v60 in my build path there is a reference to the servletapijar of tomcat 55 though,['java'] +17185,in jquery how do i select an element by its name attribute i have 3 radio buttons in my web page like belowlabel forthemegrey input typeradio idthemegrey nametheme valuegrey greylabellabel forthemepink input typeradio idthemepink nametheme valuepink pinklabellabel forthemegreen input typeradio idthemegreen nametheme valuegreen greenlabelin jquery i want to get the value of the selected radio button when any of these three are clicked in jquery we have id and class selectors but what if i want to find a radio button by its name as belowradiobutton name attributeclickfunctionplease tell me how to solve this problem,"['javascript', 'jquery', 'html']" +17186,how can i determine which exceptions can be thrown by a given method my question is really the same as this one finding out what exceptions a method might throw in c however i would really like to know if anyone knows of a way to determine the stack of all the exceptions that may be thrown by a given method i am hoping for a tool or utility that i can analyze code at compile time or through reflection like fxcop stylecop or ncover i do not need this information at run time i just want to make sure we are trapping exceptions and logging them correctly in out code we are currently trapping the exceptions that we know about and logging all the wild cards this does work well however i was just hoping someone has used or knows of a tool that can thiscover this information,['c#'] +17195,how do i attach a process to the debugger in visual studio i know i can start a process in code with procestartis it also possible to attach the debugger to that process not from code per se but just a way to do it,['.net'] +17201,how to change image permission mode to 7 using java code i want to give permissions mode value 7 to image file using java code how can i give that using java because i cannot delete the image with default permission mode 664,['java'] +17209,adding rspec test for library module does not seem to pickup expectations and matchers i am adding more rspec testing to my app and would like to test a scoringmethods module which is in libscoring methodsrb so i added a speclib directory and added scoring methods specrb there i required spec helper and set up the describe block as so require fileexpand pathfiledirname file spec helperdescribe scoringmethods do describe should have scorepubliccontest method do methods scoringmethodsinstance methods methods0should matchscorepubliccontest endendnow methods0 is a string and there is no problem matching the public method name with the regular expression and the relative path to spec helper is correctthe problem is that the entire setup does not seem to use the rspec libraryrunning the example yields speclibscoring methods specrb7 undefined method match for specrailsexamplerailsexamplegroupsubclass 1subclass 1class nomethoderror the entire expectation and matcher support seems to be missing to test my supposition i changed a working helper spec by replacing is instance of to is foobar of that test simply fails and says is foobar of is not a method of the targeted object that it this entire specrailsexample hierarchy is not presenti have tried using other matchers as well i have tried be instance of and some others it seems that i am not including the rspec library properlyfinally scoringmethods is a module just the same way helpers are modules so i thought that it would be possible to test a module as opposed to classes such as controllers and modelsi would greatly appreciate your thoughts on what i have done wrong perhaps there is a more effective way of testing library modules thanks,['ruby-on-rails'] +17213,jquery round corner code for ie8 in standards mode i need a solution for round corners using javascript with or without jquery in ie8 standards mode,"['javascript', 'jquery']" +17216,how to iterate over a date range in plsql i need to write a report that generates summary totals against a table with date ranges for each recordtable dataoption start date end dateopt1 6122009 6192009opt1 632009 6132009opt2 652009 662009what i want out is basically thisdate option count612009 opt1 0612009 opt2 0622009 opt1 0622009 opt2 0632009 opt1 0632009 opt2 1i am having a hard time figuring out how to iterate over a date range i am sure this is some simple cursor that could be created for this but i am at a loss preferably in plsqlupdatei ended up using the example here to accomplish what i wanted to do this creates a function that generates a table of dates,['sql'] +17217,how do i get the markup of an element including itself using jquery i know i can wrap it is html in a tag but the element itself has a dynamically set id class etc how do i get jquery to return the elements markup including itself,['jquery'] +17218,dynamically change user control in aspnet i am trying to create a web page that will thisplay an appropriate user control based on the selected value of a drop down listbasically the page layout is thisdrop down selection user control created based on drop down selection i have it half working the controls are changing when the selection changesin oninit i dynamically create the last selected control whose value gets saved in session state because viewstate is not available at oninitwhen the drop down selection change occurs i remove the old user control and add a new one the problem is with the new control being added from the selection changed event i am not able to save changes from the user on the first postback after the first post back the selected control is created from oninit instead of the change event and state is saved from then on until the next selection changehere is the selectionchanged methodprotected void selectionchangedobject sender eventargs e selectedvalue intparsedropdownlistselectedvalue store in session control usercontrol getspecificusercontrolselectedvalue placeholder1controlsclear remove old user control placeholder1controlsaddusercontrolany changes made to the new control by the user after selectionchanged happens are not saved on the following post back however subsequent postbacks do get saved at that point the control is getting created in oninitis there some way to force the correct post back and viewstate when the control changes is it possible to force a page reinitialization after the control is changed,['asp.net'] +17232,populating a va list is there a way to create a va list from scratch i am trying to call a function that takes a va list as a parameterfuncvoid entry int num args va list args char keyfrom a function that does not take a variable number of arguments the only way i can think of is to create an intermediary function that takes varargs and then passing along its va list which is pretty stupidvoid stupid funcvoid entry char key int num args va list args va startargs num args funcentry num args args key va endargsis there a better way i cannot change funcs signature,['c'] +17257,how to know when thismissmodalviewcontrolleranimated is initiated and also when it is done is there a way to know when the thismissmodalviewcontrolleranimated is initiated and when it is completed such as the idiom for viewwillappear and viewdidappear unlike other animations this one does not seem to have a delegate that tells you,"['iphone', 'objective-c']" +17266,how do you handle command line options and config files what packages do you use to handle command line options settings and config files i am looking for something that reads userdefined options from the command line andor from config files the options settings should be dividable into different groups so that i can pass different subsets of options to different objects in my codei know of boostprogram options but i cannot quite get used to the api are there lightweight alternativesbtw do you ever use a global options object in your code that can be read from anywhere or would you consider that evil,['c++'] +17270,differences between java interfaces and objectivec protocols i know java and now i am learning objectivec what exactly are the differences between java interfaces and objectivec protocols,"['java', 'objective-c']" +17280,handling touches inside uiwebview i have created a subclass of uiwebview and have implemented the touchesbegan touchesmoved and touchesended methodsbut the webview subclass is not handling the touch eventsis there any method to handle the touch events inside the uiwebview subclass,['iphone'] +17282,difference between barrier in c 40 and waithandle in c 30 i am picking up c 40 and one of the things which is confusing me is the barrier conceptis this not just like using the waitall method of waithandle does not that wait for all threads to finishi learnt the barrier construct from this page however it seems just like the waitall method what am i missing whats the difference herethanks,"['c#', '.net']" +17284,how to make my font bold using css i am very new to html and css and i was just wondering how i could make my font bold using cssi have a plain html page that imports a css file and i can change the font in the css but i do not know how to make the font bold can anyone help me,['css'] +17287,counting repeated characters in a string in python i want to count the number of times each character is repeated in a string is there any particular way to do it apart from comparing each character of the string from azand incrementing a counterupdate in reference to anthonys answer whatever you have suggested till now i have to write 26 times is there an easier way,['python'] +17309,static constructor equivalent in objectivec i am new to objective c and i have not been able to find out if there is the equivalent of a static constructor in the language that is a static method in a class that will automatically be called before the first instance of such class is instantiated or do i need to call the initialization code myselfthanks,['objective-c'] +17315,django for loop counter break this is hopefully a quickeasy one i know a way to work around this via a custom template tag but i was curious if there were other methods i was over looking i have created a gallery function of sorts for my blog and i have a gallery list page that paginates all my galleries now i do not want to show all the photos of each gallery in that list since if each gallery even has 20 images then that is 100 images on a page if i paginate at 5 posts that would be wasteful and the wrong way to go about thingsthe question i have is is there a way to just thisplay 3 photos from the photo set what i would like to do but i do not think is possible is something like pseudocode for photos in galleryphoto set if forloopcounter lt 3 img src photosurl endif endfor judging from the documentation unless i am completely missing it that is not possible via the templating system hence i can just write my own template tag of sorts to work around it i could probably do something from the view aspect but i have not looked to far into that idea the other option i have is giving the model a preview field and allow the user to select the photos they want in the preview field anyways a few different options so i thought i would poll the audience to see how youd do it any opinion is appreciated personally enjoying that there is numerous ways to skin this cat,['python'] +17318,simplexml selecting elements which have a certain attribute value in an xml document i have elements which share the same name but the value of an attribute defines what type of data it is and i want to select all of those elements which have a certain value from the document do i need to use xpath and if so could you suggest the right syntax or is there a more elegant solutionheres some example xmlobject data typememynamedata data typeyouyournamedata data typememyothernamedataobjectand i want to select the contents of all data tags children of object whos type is meps i am trying to interface with the netflix api using php this should not matter for my question but if you want to suggest a goodbetter way to do so i am all ears,['php'] +17325,unresolved host exception android i am trying to call a restful web service from an android application using the following methodhttphost target new httphosthttp servicewrapperserver hostservicewrapperserver porthttpget get new httpgetliststring result nullhttpentity entity nullhttpclient client new defaulthttpclienttry httpresponse response clientexecutetarget get entity responsegetentity result entityutilstostringentity catch exception e eprintstacktrace finally if entitynull try entityconsumecontent catch ioexception e return resulti can browse to address and see the xml results using the android emulator browser and from my machine i have given my app the internet permission i am developing with eclipsei have seen it mentioned that i might need to configure a proxy but since the web service i am calling is on port 80 this should not matter should it i can call the method with the browserany ideas,"['java', 'android']" +17335,how to detect when a uiscrollview has finished scrolling uiscrollviewdelegate has got two delegate methods scrollviewdidscroll and scrollviewdidendscrollinganimation but neither of these tell you when scrolling has completed scrollviewdidscroll only notifies you that the scroll view did scroll not that it has finished scrollingthe other method scrollviewdidendscrollinganimation only seems to fire if you programmatically move the scroll view not if the user scrollsdoes anyone know of scheme to detect when a scroll view has completed scrolling,['iphone'] +17341,should i delete vector i have painfully learned during last few days a lot about programming in ci love it i know i should release memory the golden each mallocfree or each newdelete rules exist now in my world but i am using them to rather simple objectswhat about vector wherever i can i am using vectorclear but that clearly is not enough because i am having huge memory leakscould you guide me on how should i treat this thingeditthanks your comments made me think about the alghorithm of this application and i will be able to eliminate the vector totally osorry i started explaining what is my use case here and i found out what i really need it is like that when you code last 3 days for 18 hours a day edit 2this is crazy by small changes in code i have eliminated memory usage from 2x130 mb constantly growing into 2x 135mb constant size thanks for making me think about that in another way btw such self code review got a name anyone remember that it is when you ask anyone even your mother or dog and start explaining whats your problem and suddenly you solve this 5 hour problem yourself just by trying to look at it from other point of view or just by trying to summarize whats it all about i often find myself being catched on that,['c++'] +17345,are strtol strtod unsafe it seems that strtol and strtod effectively allow and force you to cast away constness in a stringinclude stdlibhinclude stdiohint main const char foo hello world char bar strtolfoo bar 10 or strtodfoo bar printfdn foo bar prints 1 they are equal bar x segmentation fault return 0above i did not perform any casts myself however strtol basically cast my const char into a char for me without any warnings or anything in fact it wouldnt allow you to type bar as a const char and so forces the unsafe change in type is not that really dangerous,['c'] +17348,mysql table incrementing by 10 for some reason the id field in a mysql table is incrementing by 10 11 21 31 for some reason here is the table definitioncreate table clients id int11 not null auto increment first name varchar255 default null last name varchar255 default null engineinnodb auto increment52 default charsetutf8if i do a simple insert statement in sql the next id will be 41,['mysql'] +17352,how can i get jqueryui sortable to revert faster jquerys sortable has an option to revert the item that the user drags back in line with the rest but the animation is a little slowis there a simple way to specify fast like some of the other methods,['jquery'] +17359,compare an object to null i am trying to verify whether an object is null or not and i am using this syntaxvoid rendersearchcustomer c systemoutprintlnsearch customer rendering try ifcequalsnull systemoutprintlnsearch customer found else systemoutprintlnsearch customer not found catch exception e systemerrprintln search customer rendering error egetmessageegetclass i get the following exception search customer rendering error null class javalangnullpointerexceptioni thought that i was considering this possibility with my if and else loop any help would be appreciated,['java'] +17365,writing drivers in c i have written earlier in cc but currently i need it to convert into ccan anyone tell me the codeway how to write drivers in cactually currently i have some problems with my old application written in c and we have to write the drivers of our lpt1com printers and other usb drivers in c,['c#'] +17372,reliable way to validate ibanbic in java does anyone know of a reliable way to validate international bank account number iban and bank identifier code bic in java,['java'] +17374,how to create our own listener interface in android could someone help me to create user defined listener interface with some code snippets,['android'] +17381,filewriteallbytes causes error insufficient system resources exist to complete the requested service i have a standard soap webservice with a webmethod which accepts a byte array and then performs awebmethodtruewritefilebyte data string filepath filewriteallbytesfilepath dataif this process is passed a large file eg 2 meg it is bombing out with the following error messageinsufficient system resources exist to complete the requested servicelooking at the stack trace i am gettingsystemiofilewriteallbytessystemiofilestreamwritesystemiofilestreamwritecoresystemio errorwinioerrorsystemioioexception insufficient system resources exist to complete therequested servicei have tried all the obvious things such as setting the maxrequestlength and executing timeout to more realistic settingshttpruntime maxrequestlength409600 executiontimeout900it still seems to fail over with the above if you send a smaller file it saves to thisk fine so it is either file size or time that is the issuedoes anyone know of anything else i can do to sort this outthanksdave,['.net'] +17387,in jquery are there any function that similar to html or text but return the whole content of matched component for example if the match is div classclass1hello worlddiv i need to return div classclass1hello worlddivnot just hello worldthanks,['jquery'] +17394,is there a right way to return a new object instance by reference in c so i was writing some code and i had something like thisclass box private float x y w h public rectangle getrect void const return rectangle x y w h then later in some coderectangle rect theboxgetrectwhich worked in my debug build but in release there were issues returning that rectangle by reference i basically got an uninitialized rectangle the rectangle class has an operator and a copy constructor without getting into why this broke i am actually more interested in the correct way to return a new object by reference for the purpose of assigning copying to a variable am i just being silly should it not be done i know i can return a pointer and then dereference on assignment but i would rather not some part of me feels like returning by value would result in redundant copying of the object does the compiler figure that out and optimize it it seems like a trivial question i feel almost embarrassed i do not know this after many years of c coding so hopefully someone can clear this up for me,['c++'] +17396,how to use google guice to create objects that require parameters maybe i am just blind but i do not see how to use guice just starting with it to replace the new call in this methodpublic boolean mymethodstring aninputvalue processor proc new processorimplaninputvalue return procisenabledfor testing there might be a different implementation of the processor so i would like to avoid the new call and in the course of that get rid of the dependency on the implementationif my class could just remember an instance of processor i could inject it via the constructor but as the processors are designed to be immutable i need a new one every timehow would i go about and achieve that with guice 20,['java'] +17398,content for linux operating systems class i will be ta for an operating systems class this upcoming semester the labs will deal specifically with the linux kernelwhat conceptscomponents of the linux kernel do you think are the most important to cover in the classwhat do you wish was covered in your studies that was left outany suggestions regarding the linux kernel or overall operating systems design would be much appreciated,['c'] +17428,how do you install jdk i have eclipse and i can test run java apps but i am not sure how to compile them i read that i should type javac version into my cmdexe and see if it is recognized it is not so i went to suns website and downloadedinstalled jdk v6 yet it still says javac is an unrecognized command what am i doing wrongthanksupdateok after reading some replies it seems like what i am trying to do is create a jar file that can be ran on another computer with the runtime however i am having trouble figuring out how to do that this might be because i am using flex buildereclipse but i added the ability to create java projects as wellthanksupdateok i do not want to make a jar file i am not trying to archive itthe whole point of making a program is to send it to users so they can use the programthat is what i am trying to dowhy is this so hard,['java'] +17429,dtd download error while parsing xhtml document in xom i am trying to parse an html document with the doctype declared to usethe transitional dtd as followsdoctype html public w3cdtd xhtml 10 transitionalenwhen i do builderbuild on the document i get the following exception javaioioexception server returned http response code 503 for url at sunnetwprotocolhttphttpurlconnectiongetinputstreamhttpurlconnectionjava1305 at orgapachexercesimplxmlentitymanagersetupcurrententityunknown source at orgapachexercesimplxmlentitymanagerstartentityunknown source at orgapachexercesimplxmlentitymanagerstartdtdentityunknown source at orgapachexercesimplxmldtdscannerimplsetinputsourceunknown source at orgapachexercesimplxmldocumentscannerimpldtdthispatcherthispatchunknown source at orgapachexercesimplxmldocumentfragmentscannerimplscandocumentunknown source at orgapachexercesparsersdtdconfigurationparseunknown source at orgapachexercesparsersdtdconfigurationparseunknown source at orgapachexercesparsersxmlparserparseunknown source at orgapachexercesparsersabstractsaxparserparseunknown source at nuxombuilderbuildbuilderjava1127 at nuxombuilderbuildbuilderjava1019if i remove the doc type declaration it parses just fine i cansuccessfully download the dtd from my browser which tells me that theurl is valid i do not want to remove the doc type declaration isthere a way tell the builder not to download the dtd or provide itwith an alternate dtd,['java'] +17432,jquery vs standard backend programming i am curious to know peoples preferencesi have recently gone headfirst into jquery and i am loving it however i am finding that i am replacing a lot of somewhat trivial backend tech aspnet functions with tiny jquery functions for instance rather than assign a navigation button as a backend control and change its class when its page is landed on ie highlight the about button when on the about us page i simply parsed the url and added a class to the buttonvar pathname windowlocationpathnameif pathname about navaboutaddclaselectedsolutions like these seem rather simple maybe too simple but i am always wary to rely too heavily on javascript does anyone else do similar things to this and if so how do you maintain code like this how do you know where to strike the balance between good ol trusty server code that works every time and fast fancy shiny jquery that works pretty much every time except when the user may have javascript turned offediti am not really speaking of this particular instance i am talking about little enhancements like this what is the line you draw when it comes to jquery enhancements or just do it on the server thanks,['jquery'] +17434,great resources in f for beginners use and examples for business are there some links to great resources for f forbeginners useexamples in applying it to business and enterprise applicationswhat i meant by great is similar to the videos presented in the learn section of aspnet and windowsclientnetthanks,['.net'] +17440,is a valid character in xml on this datarow id37501 postid135577 textuses thoughx10i am getting an error with the python sax parserxmlsax exceptionssaxparseexceptioncommentsxml29776332 reference to invalid character numberi trimmed the example 332 points to x10is the parser correct in rejecting this character,['python'] +17442,why cannot iterator methods take either ref or out parameters i tried this earlier todaypublic interface ifoo ienumerableint getitems a ref int somethingelse ienumerableint getitems b ref int somethingelse public class bar ifoo public ienumerableint getitems a ref int somethingelse ok public ienumerableint getitems b ref int somethingelse yield return 7 cs1623 iterators cannot have ref or out parameters whats the rationale behind this,['c#'] +17443,how to get all subsets of an array given an array dog cat mousewhat is the most elegant way to createmousecatcatmousedogdogmousedogcatdogcatmousei need this to work for any sized arraythis is essentially a binary counter where array indices represent bits this presumably lets me use some bitwise operation to count but i cannot see a nice way of translating this to array indices though,['c#'] +17444,c hello world boost tee example program the boost c library has function template teethe class templates tee filter and tee device provide two ways to split an output sequence so that all data is directed simultaneously to two different locationsi am looking for a complete c example using boost tee to output to standard out and to a file like sampletxt,['c++'] +17447,is it possible to execute a string in mysql i have to convert a mssql stored proc that passes a varchar that is a queryinsert into results exec expresionthis is not working i am pretty sure that exec and execute are not mysql commands but call does not work either does anyone know if it is even possible to have something like javascripts eval function for mysql,['mysql'] +17449,phpgd cropping and resizing images i have coded a function that crops an image to a given aspect ratio and finally then resizes it and outputs it as jpgphpfunction imageimage crop null size null image imagecreatefromstringfile get contentsimage if is resourceimage true x 0 y 0 width imagesximage height imagesyimage crop aspect ratio section if is nullcrop true crop arraywidth height else crop array filterexplode crop if emptycrop true crop arraywidth height else if emptycrop0 true is numericcrop0 false crop0 crop1 else if emptycrop1 true is numericcrop1 false crop1 crop0 ratio array 0 width height 1 crop0 crop1 if ratio0 ratio1 width height ratio1 x imagesximage width 2 else if ratio0 ratio1 height width ratio1 y imagesyimage height 2 how can i skip join this operation with the one in the resize section result imagecreatetruecolorwidth height if is resourceresult true imagesavealpharesult true imagealphablendingresult false imagefillresult 0 0 imagecolorallocatealpharesult 255 255 255 127 imagecopyresampledresult image 0 0 x y width height width height image result resize section if is nullsize true size arrayimagesximage imagesyimage else size array filterexplodex size if emptysize true size arrayimagesximage imagesyimage else if emptysize0 true is numericsize0 false size0 roundsize1 imagesximage imagesyimage else if emptysize1 true is numericsize1 false size1 roundsize0 imagesyimage imagesximage result imagecreatetruecolorsize0 size1 if is resourceresult true imagesavealpharesult true imagealphablendingresult true imagefillresult 0 0 imagecolorallocateresult 255 255 255 imagecopyresampledresult image 0 0 0 0 size0 size1 imagesximage imagesyimage headercontenttype imagejpeg imageinterlaceresult true imagejpegresult null 90 return falsethe function works as expected but i am creating a nonrequired gd image resource how can i fix it i have tried joining both calls but i must be doing some miscalculationsphpusage examplesimage transparency demonstration 1png 11 600ximage transparency demonstration 1png 21 600ximage transparency demonstration 1png 2 250x300any help is greatly appreciated thanks,['php'] +17451,question about pure virtual destructor if we define a abstract class which has a pure virtual destructor why do we have to give a definition of a destructor in the abstract class,['c++'] +17453,natural language processing in ruby i am looking to do some sentence analysis mostly for twitter apps and infer some general characteristics are there any good natural language processing libraries for this sort of thing in rubysimilar to but for ruby i would prefer something very general but any leads are appreciated,['ruby'] +17458,integer out of range on postgres db simple rails app using postgres db getting integer out of range error when trying to insert 2176968859 should be an easy fix to the migrations but i am not sure right now i have gotcreate table targets do t tinteger tid end,['ruby-on-rails'] +17466,data binding to selecteditem in a wpf treeview how can i retrieve the item that is selected in a wpftreeview i want to do this in xaml because i want to bind ityou might think that it is selecteditem but apparently that does not exist is readonly and therefore unusablethis is what i want to dotreeview itemssourcebinding pathmodelclusters itemtemplatestaticresource clustertemplate selecteditembinding pathmodelselectedcluster i want to bind the selecteditem to a property on my modelbut this gives me the errorselecteditem property is readonly and cannot be set from markupeditok this is the way that i solved thistreeview itemssourcebinding pathmodelclusters itemtemplatestaticresource hoofdclustertemplate selecteditemchangedtreeview onselecteditemchanged and in the codebehindfile of my xamlprivate void treeview onselecteditemchangedobject sender routedpropertychangedeventargsobject e modelselectedcluster clusterenewvalue,['c#'] +17482,how to keep a python script output window open i have just started with python when i execute a python script file on windows the output window appears but instantaneously goes away i need it to stay there so i can analyze my output how can i keep it open,['python'] +17486,which ruby orm framework to use in a standalone ruby app i would like to use postgresql with foreign keys to define relationships in data so that other platformsapps would also be able to easily use the same database having some kind of ruby dsl to define database schema with migration support would also be great which framework would you recommend for meis there some kind of framework for only handling database schema changes migrations and versions separate of orm,['ruby'] +17489,console based progress in java is there are easy way to implement a rolling percentage for a process in java to be thisplayed in the console i have a percentage data type double i generated during a particular process but can i force it to the console window and have it refresh instead of just printing a new line for each new update to the percentage i was thinking about pushing a cls and updating because i am working in a windows environment but i was hoping java had some sort of builtin capability all suggestions welcomed thanks,['java'] +17492,how to write a utf8 file with java i have some current code and the problem is its creating a 1252 codepage file i want to force it to create a utf8 filecan anyone help me with this code as i say it currently works but i need to force the save on utf can i pass a parameter or somethingthis is what i have any help really appreciatedvar out new javaiofilewriter new javaiofile path text new javalangstring src outwrite text 0 textlength outflushoutclose,['java'] +17496,what is the best free sql gui for linux for various dbms systems as i make the full switch from windows to linux centos 5 i am in search of the best free gui sql client tool for mssql mysql oracle etc any suggestionsi have tried dbvisualizer the best bet so far but still limited by the free version not all functionality is there mysql gui tools good but only for mysql need other dbs as well and aqua data studio same as dbvis it is good but a lot of the functionality is missing in the free version,['sql'] +17510,sending multiple items to mvc controller via jqueryajax if youa are serializing a form using something like jquery it will often map the json keys and values to the properties of a object on the controller action you are posting to sojqueryfunction postform ajax url hometestmvc type post datatype applicationjson data formserialize complete callfunction presuming main details contains elements which will have the name of the parameter as a key they should map to the object directlyactionpublic void testmvcmyobject objobj should now contain the data from the serialised formpostname bobage 9sex unknowndoes anyone know how this works it is breaking every time i pass the form and any additional data to the controller i would like to send the contents of the data as well as a querystring which could contain any number and types of keyvalue pairs to the controller i can extract these keyvalue pairs on the server since i cannot create an object for them on the method signature however this fails to work as intended jqueryfunction postform ajax url hometestmvc type post datatype applicationjson data obj formserialize theweirdquerystring additionalparamsserialize actionpublic void testmvcmyobject obj string theweirdquerystringobj now does not contain the element it is null whereas theweirdquerystring works fine postobj namebobage9sexunknowntheweirdquerystring param11param22i think this is because i have actually created a json object as the data and set the properties to the name of the object there is a difference in the post values which appear in firebug when i post the object alone the post values are all the keys of the objectform with their corresponding values in the second example there are two simple properties the name i gave them each containing a querystring foo1bar2 and mvc cannot map a querystring to the members of an object or so it would appearis there anyway at all to get to work like it does in the first instance but also to send extra data to a 2nd argument on the action i am guessing it is to add an extra property to all the existing ones created when jquery does the serialisation of the form the post i actually want isname bobage 9sex unknowntheweirdquerystring param11param22,['jquery'] +17521,how do i get jquerys uploadify plugin to work with aspnet mvc i am in the process of trying to get the jquery plugin uploadify to work with aspnet mvci have got the plugin showing up fine with the following javascript snippetscript typetextjavascript documentreadyfunction fileuploadfileupload uploader contentflashuploaderswf script placementupload folder uploads multi true buttontext browse thisplaydata speed simuploadlimit 2 cancelimg contentimagescancelpng scriptwhich seems like all is well in good if you notice the script attribute is set to my placementupload which is my placement controller and my upload actionthe main problem is i am having difficulty getting this action to fire to receive the file i have set a breakpoint on that action and when i select a file to upload it is not getting executedi have tried changing the method signature based off this article public string uploadhttppostedfilebase filedata do something with the filedata return upload okbut this still does not firecan anyone help me write and get the upload controller actions signature correctly so it will actually fire i can then handle dealing with the file data myself i just need some help getting the method action to fire,['jquery'] +17525,aspnet mvc htmlbeginform problem i have a partial view control languagec inheritssystemwebmvcviewusercontroldomainmodelentitiesproduct div classitem h3 modelname h3 modeldescription using htmlbeginformaddtocart cart htmlhiddenproductid htmlhiddenreturnurl viewcontexthttpcontextrequesturlpathandquery input typesubmit value add to cart h4 modelpricetostringch4divand here is the html that gets rendereddiv classitem h3kayakh3 a boat for one person form action methodpost input idproductid nameproductid typehidden value1 input idreturnurl namereturnurl typehidden value input typesubmit value add to cart form h427500h4 divnothing happens when the submit button is clicked and i am pretty sure it is because the form action attribute has no value should not beginformaction controller take care of rendering out the form action what am i doing wrongeditcode from cartcontroller addtocart action public redirecttorouteresult addtocartcart cart int productid string returnurl product product productsrepositoryproductsfirstordefaultp pproductid productid cartadditemproduct 1 return redirecttoactionindex new returnurl edit 2the view that renders the partialaspcontent idcontent2 contentplaceholderidmaincontent runatserver foreach var product in model htmlrenderpartialproductsummary product div classpager page htmlpagelinksintviewdatacurrentpage intviewdatatotalpages x urlactionlist new page x category viewdatacurrentcategory divaspcontentedit 3routespublic static void registerroutesroutecollection routes routesignorerouteresourceaxdpathinfo routesmaproute null do not need a name matches the root url ie new controller products action list category stringnull page 1 defaults routesmaproute null do not need name pagepage url pattern eg page683 new controller products action list category stringnull defaults new page d constraints page must be numerical routesmaproutenull category new controller products action list page 1 routesmaproutenull categorypagepage new controller products action list new page d constraints page must be numerical,['c#'] +17527,not locking mutex for pthread cond timedwait and pthread cond signal on linux is there any downside to calling pthread cond timedwait without taking a lock on the associated mutex first and also not taking a mutex lock when calling pthread cond signal in my case there is really no condition to check i want a behavior very similar to java waitlong and notifyaccording to the documentation there can be unpredictable scheduling behavior i am not sure what that meansan example program seems to work fine without locking the mutexes first,"['c++', 'c']" +17534,complete c i18n gettext hello world example i am looking for a complete i18n gettext hello world example i have started a script based upon a tutorial on native language support using gnu gettext by g mohanty i am using linux and gcodecat hellogtcxx eof hellogtcxxinclude libintlhinclude localehinclude iostreaminclude cstdlibint main char cwd getenvpwd stdcout getenvpwd cwdcwdnull stdendl char l getenvlang stdcout getenvlang llnull stdendl char s setlocalelc all stdcout setlocale ssnull stdendl stdcout bindtextdomain bindtextdomainhellogt cwd stdendl stdcout textdomain textdomain hellogt stdendl stdcout gettexthello world stdendleofg ohellogt hellogtcxgettext d hellogt o hellogtpot hellogtcxxmsginit notranslator l es mx o hellogt spanishpo i hellogtpotsed inplace hellogt spanishpo expression shola mundosed inplace hellogt spanishpo expressionspackage versionhellogt 10mkdir p es mxlc messagesmsgfmt c v o es mxlc messageshellogtmo hellogt spanishpoexport langes mxls l pwdes mxlc messageshellogtmohellogtstrace e traceopen hellogtthe program compiles the text is extracted spanish file is created modified and binary created but hellogt still thisplays english the trace shows no evidence of looking in the current working directory for es mx nor any references to lc messages directory,['c++'] +17535,measure a string without using a graphics object i am using pixels as the unit for my font in one place i am performing a hit test to check if the user has clicked within the bounding rectangle of some text on screen i need to use something like measurestring for this unfortunately the code doing the hit test is deep within a library which does not have access to a graphics object or even a controlhow do i get the bounding box of a string given the font without using the graphics class why do i even need a graphics object when my font is in pixels,['c#'] +17555,aspnet mvc defaultmodelbinder with nested lists i have a view with a table representing an employees timesheet days across the top projects down the side with each dayproject intersection containing two values for regular hours and overtimethe simplified class definitions for the page model arepublic class timesheetformmodel public listproject projects other thingspublic class project public string name public listworkunit workunitspublic class workunit public datetime date public decimal regularhours public decimal overtimehoursthe form elements on the page are named as follows in an attempt to get the defaultmodelbinder to pick up on themmodelprojects0name new projectmodelprojects0workunits0date 5232009 120 ammodelprojects0workunits0regularhours 0modelprojects0workunits0overtimehours 0modelprojects0workunits1date 5242009 120 ammodelprojects0workunits1regularhours 0modelprojects0workunits1overtimehours 0modelprojects0workunits2date 5252009 120 ammodelprojects0workunits2regularhours 0modelprojects0workunits2overtimehours 0 etcwhen the view is submitted however the model parameter is not being completely populated modelprojects contains projects but the projects workunits field is empty does the defaultmodelbinder support nested collections like i am trying to do if not what should i do,['asp.net'] +17570,should interfaces be placed in a separate package i am new to a team working on a rather large project with lots of components and dependencies for every component there is an interfaces package where the exposed interfaces for that component are placed is this a good practicemy usual practice has always been interfaces and implementations go in the same package,['java'] +17587,how to add encoding information to the response stream in aspnet i have following piece of codepublic void processrequest httpcontext context contextresponsecontenttype textrtf charsetutf8 contextresponsecharset utf8 contextresponsecontentencoding systemtextencodingutf8 contextresponseaddheadercontentthisposition attachmentfilenamelista obecnoscicsv contextresponsewritea14aoaa3a1awhen i try to open generated csv file i get following behaviorin notepad2 everything is finein word conversion wizard opens and asks to convert the text it suggest utf8 which is somehow okin excel i get real mess none of those polish characters can be thisplayedi wanted to write those special encodinginformation characters in front of my string iecontextresponsewritechar0xefcontextresponsewritechar0xbbcontextresponsewritechar0xbfbut that would not do any good the response stream is treating that as normal data and converts it to something differenti would appreciate help on this one,['asp.net'] +17588,what is the runtime complexity of python list functions i was writing a python function that looked something like thisdef foosome list for i in range0 lensome list barsome listi iso that it was called withx 0 1 2 3 fooxi had assumed that index access of lists was o1 but was surprised to find that for large lists this was significantly slower than i expectedmy question then is how are python lists are implemented and what is the runtime complexity of the followingindexing listxpopping from the end listpoppopping from the beginning listpop0extending the list listappendxfor extra credit splicing or arbitrary pops,['python'] +17591,scoping rules when inheriting c i was reading the c0x faq by stroustrup and got stuck with this code consider the following codestruct a void fdouble stdcout in double stdendl struct b a void fint stdcout in int stdendl int main a a af1010 as expected af will get called b b bf1010 this calls bf and we lose the 10 here return 0my understanding was when a type is inherited all protected and public members will be accessible from the derived class but according to this example it looks like i am wrong i was expecting the bf will call base classes f i got the expected result by changing the derived class likestruct b a using af void fint stdcout in int stdendl questionswhy was it not working in the first codewhich section in the c standard describes all these scoping rules,['c++'] +17596,file access denied i am using an ftpclient library to transfer files from a windows share to an ftp serverthe sendfile method of the library uses the following codefilestream stream new filestreamlocalfilename filemodeopenthis results in a systemunauthorizedaccessexception being thrown however i am able to open rename and move the file using windows explorer under the same user account which the code is being executedcan anyone tell me why this is happeningeditthe strange thing is that i can access other files on the share which have been granted the same ntfs permissions as the one that i cannotthis is also a windows forms appupdatestill no luck with this i am able to read the file using a streamreader but not a file stream i cannot understand why the two behave differently,['c#'] +17599,should i use json or ajax for response data why json i have done some tests today and the request time for both json or a normal ajax request was the same in the normal request i have returned the complete texthtml tags in the json request logically i returned a json return type and i have created the html with clientside javascripti do not get it why are the big sites google reader etc or even small sites using json or do i not understand when i should use json,"['javascript', 'jquery']" +17606,what is the default session timeout value in aspnet what is the default session timeout value in aspnet,['asp.net'] +17607,how to call a secondlevel base class method like basebasegethashcode class a public override int gethashcode return 1 class b a public override int gethashcode return objectthisgethashcode new bgethashcodethis overflows the stack how can i call objectgethashcode from bgethashcodeedit b now inherits from a,['c#'] +17623,aspnet cannot createshadow copy i get this error repeatedly when developing aspnet applications cannot createshadow copy x when that file already existswhere x is a random dll typically the dll is one of the dlls from microsofts enterprise library but it varies it is really random and it is very frustrating i will go hours without getting the error and then get this error every 1020 minutes i have seen several solutions for instance this question i have tried using clean solution option and i have also simply restarted my local iis however it still occurs at the same random but persistent frequency i have also seen many people mention using this option in the config filehostingenvironment shadowcopybinassembliesfalse however others have mentioned it being problematic and it should definitely not be used in production so should i just give up and try the shadowcopybinassemblies option and make sure not to copy this change to other environments am i the only one who gets this issue that oftennote i am using visual studio 2008,['asp.net'] +17627,javascript function aliasing does not seem to work i was just reading this question and wanted to try the alias method rather than the functionwrapper method but i could not seem to get it to work in either firefox 3 or 35beta4 or google chrome both in their debug windows and in a test web pagefirebug windowmyalias documentgetelementbyidfunction myaliasitem1 windowmyaliasitem1 documentgetelementbyiditem1div iditem1if i put it in a web page the call to myalias gives me this erroruncaught exception exception illegal operation on wrappednative prototype object nsresult 0x80570c ns error xpc bad op on wn proto location js frame filesniptesthtml top level line 7 data nochrome with s inserted for clarity windowmyalias documentgetelementbyidfunction getelementbyid native code windowmyaliasitem1typeerror illegal invocation documentgetelementbyiditem1div iditem1and in the test page i get the same illegal invocationam i doing something wrong can anyone else reproduce thisalso oddly enough i just tried and it works in ie8,['javascript'] +17642,c getting enum values i have a enum containing the following for exampleunitedkingdomunitedstatesfranceportugalin my code i use countryunitedkingdom but i want to have the value be uk if i assign it to a string for exampleis this possible,"['c#', '.net']" +17645,what is the bestpractice casing style for javascript why one aspect of javascript that it is hard to find information on is casing practices by casing practices i mean what casing style ie camelcase pascalcase etc should be used for what elements constructors private functions public functionsthe only rule i have heard was from a douglas crockford lecture on yui theater stating that constructors should be the only functions that start with an uppercase letter beyond that there does not seem to be many casing standards that people follow in javascriptdoes anyone know any casing best practices for javascript and why it is reasonable to use themalso do you follow a casing style with your js files,['javascript'] +17652,my rails queries are starting to get complicated should i switch to raw sql queries what do you do my rails app is starting to need complicated queries should i just start using raw sql queries what is the trend in the rails communityupdate i do not have written queries right now i wanted to ask this question before i start but here is an example of what i want to doi have books which have categories i want to saygive me all books that were created at added to store between date1 and date2updated at before date3joined with books that exist in shopping carts right nowi have not written the query yet but i think the rails version will be something like thisbooks to consider bookfindall conditions created at date2 and created at date1 and updated at date3 joins as b inner join carts as c on cbook id bidi am not saying activerecord cannot handle this query but is it more accepted to go with raw sql for readability or maybe there are other limitations i do not know of yet,"['sql', 'ruby-on-rails']" +17655,write a file onthefly to the client with c i am using c and aspnet 25i want a simple way to generate a file onthefly let us say a csv file for this example and transmit it to the client without actually writing it to the server file system,"['c#', 'asp.net']" +17661,learning nhibernate i am interested in learning nhibernateso i found thisi would like to watch these but i am afraid that the videos are for a previous version of nhibernate is this true and if so should i still watch them is there a current video seriesany other suggestions for learning nhibernate,['.net'] +17669,how can i detect with javascriptjquery if the user is currently active on the page i am needing to detect when a user is inactive not clicking or typing on the current page for more than 30 minutesi thinking it might be best to use event blubbling attached to the body tag and then just keep resetting a timer for 30 minutes but i am not exactly sure how to create thisi have jquery available although i am not sure how much of this will actually use jqueryedit i am more needing to know if they are actively using the site therefore clicking changing fields or position within a field or selecting checkboxesradios or typing in an input textarea etc if they are in another tab or using another program then my assumption is they are not using the site and therefore should be logged out for security reasonsedit 2 so everyone is clear this is not at all for determining if the user is logged in authenticated or anything right now the server will log the user out if they do not make a page request within 30 minutes this functionality to prevent the times when someone spends 30 minutes filling in a form and then submitting the form only to find out that they have not been logged out therefore this will be used in combination with the server site to determine if the user is inactive not clicking or typing basically the deal is that after 25 minutes of idle they will be presented with a dialog to enter their password if they do not within 5 minutes the system automatically logs them out as well as the servers session is logged out next time a page is accessed as with most sitesthe javascript is only used as a warning to user if javascript is thisabled then they would not get the warning and along with most of the site not working they will be logged out next time they request a new page,"['javascript', 'jquery']" +17670,how do i perform vector addition in ruby how do i perform vector addition in ruby so that100 100 2 3yields102 103instead of joining two arraysor it can be another operator too such as 100 100 2 3or 100 100 2 3,['ruby'] +17680,selecting option by text content with jquery i want to set a dropdown box to whatever has been passed through a querystring using jquery how do i add the selected attribute to an option such that the text value is equal to a certain param from the query string documentreadyfunction var cat jqurlgetcategory if cat null cat urldecodecat var dd cbcategory var options option dd optionseachfunction if thistext cat thisselect this is where my problem is,['jquery'] +17683,command line arguments in python i am originally a c programmer i have seen numerous tricks and hacks to read many different arguments what are some of the ways python programmers can do thisrelatedwhatas the best way to grabparse command line arguments passed to a python scriptimplementing a acommand action parametera style commandline interfaceshow can i process command line arguments in pythonhow do i format positional argument help using pythonas optparse,['python'] +17686,android eclipse plugin instrumentation test runner not specified i am getting this error when trying to run unit tests from eclipse with an android project the list of instrumentation test runners is empty in the android preferences20090617 235751 myapp error application does not specify a androidtestinstrumentationtestrunner instrumentation or does not declare useslibrary androidtestrunnerit is also annoyingly decided that because i tried to run a unit test once that is what i always want to do,['android'] +17689,python get original function arguments in decorator i am trying to write a login required decorator for the views in a wsgiwerkzeug applicationin order to do this i need to get at the users session which is accessible via the request object that is passed into the view methodsi cannot figure out how to get at that instance of request in the decorator though i looked at pep318 specifically the fourth example but i am not quite getting itheres what i am tryingdef login requiredargs kw def goto loginkw return redirecturl forlogin def decoratef args0 should be request args0client sessiontest true logged in 0 if logged in return f else return goto login return decoratelogin requiredexposehellostringnamedef hellorequest name return render templatesay hellohtml namenamebut i get an index out of bounds error trying to call args0is there any way i can get access to the request argument passed into the hello function in the login required decorator,['python'] +17697,how do i launch a process with low priority c i want to execute a cmd line tool to process data it does not need to be blockingi want it to be low priority so i wrote the below process app new process appstartinfofilename binconvertexe appstartinfoarguments theargs apriorityclass processpriorityclassbelownormal appstarthowever i get a systeminvalidoperationexception with the msg no process is associated with this object why how do i properly launch this app in low priorityps without the line apriorityclass processpriorityclassbelownormal the app runs fine,['c#'] +17721,what makes ruby slow ruby is slow at certain things but what parts of it are the most problematichow much does the garbage collector affect performance i know i have had times when running the garbage collector alone took several seconds especially when working with opengl librariesi have used matrix math libraries with ruby that were particularly slow is there an issue with how ruby implements basic mathare there any dynamic features in ruby that simply cannot be implemented efficiently if so how do other languages like lua and python solve these problemshas there been recent work that has significantly improved performance,['ruby'] +17740,delaying a jquery script until everything else has loaded i have a jquery script which i need to run only once everything else on the page including some other javascripts over which i have no control have finished doing their thingi though perhaps there was an alternative to documentready but i have not been able to find it,"['javascript', 'jquery']" +17745,how to add attributes for c xml serialization i am having an issue with serializing and object i can get it to create all the correct outputs except for where i have an element that needs a value and an attribute here is the required outputroot methodretrievemethod options filter times timefrom20090617timefrom times document typeworddocument namedocument filter optionsadcourierapii can build all of it but can not find a way to set the document type attribute here is a segment of the object classxmlrootroot serializable public class root xmlelementmethod public string methodretrieveapplications xmlelementoptions public options options public class options xmlelementfilter public filter filter public class filter xmlelementtimes public times times xmlelementdocuments public string documents which gives medocumentdocument namedocumentrather than document typeworddocument namedocumentbut i can not find a way to correct this please advisethanks,['c#'] +17748,bash or python to go backwards i have a text file which a lot of random occurrences of the string string a and i would be interested in writing a short script which removes only some of them particularly one that scans the file and once it finds a line which starts with this string likestring athen checks if 3 lines backwards there is another occurrence of a line starting with the same string likestring astring aand if it happens to delete the occurrence 3 lines backward i was thinking about bash but i do not know how to go backwards with it so i am sure that this is not possible with bash i also thought about python but then i should store all information in memory in order to go backwards and then for long files it would be unfeasible what do you think is it possible to do it in bash or pythonthanks,['python'] +17756,finite state machine compiler what is the best opensource fsm compiler which can generate c code,['c++'] +17761,developing in ruby on windows i am starting a new job soon where i am going to be developing in ruby and rails on a windows machine i have not used windows for years and the likes of textmate git and bash are an integral part of the workflow using a macso does anybody have any suggestions or recommendations as to the best tools or work strategies to use or pitfalls to avoidin particular of course i am interested in the best text editor i am seriously thinking about taking the opportunity to learn vim or emacs or whatever the windows ports are called but any other thoughts would be welcomeadditionally any ideas of useful plugins tools or programs would be appreciatedif you think that i have completely lost my mind then feel free to tell me too cheers,"['ruby-on-rails', 'ruby']" +17787,best way to detect whether code is running in an application server java for a j2ee bean i am reusing code that was developed for a java swing application joptionpaneshowmessagedialog is unfortunately commonly used most occurences luckily in code sections that are not reused by the j2ee application but in some cases lower levels of the code has instances of joptionpaneshowmessagedialog obviously this it results in dialog boxes popping up on the server which is what i want to avoidas a first step i would like to somehow assure that no dialog boxes will ever occur on the serversomeone suggested peeking in some event or paint queue i do not recall which onethat would be old code joptionpaneshowmessagedialogmsgif someeventqueuesize 0 consider this pseudocode loglogmsg i am running on a server tell the logelse joptionpaneshowmessagedialogmsg i have a user made of meat tell himi never really got that working what would you do,['java'] +17798,class vs java whats the difference between a class file and a java file i am trying to get my applet to work but currently i can only run it in eclipse i cannot yet embed in htmlthanksedit how to compile with jvm then,['java'] +17800,java how do i build standalone thistributions of mavenbased projects i often encounter thistributions of java applications or libraries whichuse maven as their build toolsome of them sadly do not provide standalone or rethistributable jarsis it possible to build mavenbased applications in such a way thatthe build result contains all dependencies and can be rethistributed to work outofthe boxi tried to build jackrabbit is ocm modulefor some very intelligent reasons there is no downloadable standaloneversionso i built jackrabbit with maven the source package of jackrabbit includesocm and got the same jar as found in the apache repositorythe jar does not contain necessary dependencies and is useless to me,['java'] +17812,why are html character entities necessary why are html character entities necessary what good are they i do not see the point,['html'] +17813,how would one represent scheduled events in an rdbms i have to store scheduled events like say class times for example that can be organized on a weekly daily or monthly basis events can occur say every monday and wednesday or every second thursday of the month is there a way to store this information in an rdbms that adheres to 3nfedit this is not homework i am building something with a friend for our own edification and we want it in 3nf to be specific i am trying to store the schedules for mass and confession times at rc parishes these can be scheduled in a hell of a lot of ways such as every sunday at x time or every tuethu at a different time sometimes it is only the third friday of the monthand others are only offered at a certain time once a year i need to not only store this information but query it so that i can quickly get a comprehensive list of available times in the next day or week or whateveri suppose that strictly speaking 3nf is not a requirement but it would be easier for us if it were and it is better to get it correct off the bat than to change our schema later,['sql'] +17814,how can i make deleterowsatindexpaths work with generictableviewcontroller i am using matt gallaghers generictableviewcontroller idea for controlling my uitableviews my datasource is a nsfetchedresultscontrollereverything is working fine until i try to delete a celli have the following code in my view controller voidtableviewuitableview tableview commiteditingstyleuitableviewcelleditingstyleeditingstyle forrowatindexpathnsindexpath indexpath if editingstyle uitableviewcelleditingstyledelete delete the managed object nsmanagedobjectcontext context winerycontroller managedobjectcontext context deleteobjectwinerycontroller objectatindexpathindexpath nserror error if context saveerror handle the error tableview deleterowsatindexpathsnsarray arraywithobjectindexpath withrowanimationuitableviewrowanimationfade the final line crashes with the rather verbose explanation in the console terminating app due to uncaught exception nsinternalinconsistencyexception reason invalid update invalid number of rows in section 0 the number of rows contained in an existing section after the update 5 must be equal to the number of rows contained in that section before the update 5 plus or minus the number of rows inserted or deleted from that section 0 inserted 1 deletedok i understand what it is saying a row is not getting deleted i would assume because i am not forwarding some message to the right place since i have moved some code from its normal location anyone have any idea which one i am totally stumped on this one,"['iphone', 'objective-c']" +17824,how to improve the performance of ftpwebrequest i have an application written in net 35 that uses ftp to uploaddownload files from a server the app works fine but there are performance issuesit takes a lot of time to make connection to the ftp server the ftp server is on a different network and has windows 2003 server iis ftp when multiple files are queued for upload the change from one file to another creates a new connection using ftpwebrequest and it takes a lot of time around 810 secondsis is possible to reuse the connection i am not very sure about the keepalive property which connections are kept alive and reusedthe iisftp on windows server 2003 does not support ssl so anyone can easily see the usernamepassword through a packet sniffer such as wireshark i found that windows server 2008 supports ssl over ftp in its new version if iis 70i basically want to improve the uploaddownload performance of my application any ideas will be appreciated please note that 3 is not an issue but i would like people to have comments on it,['.net'] +17825,facebook status update through php i want to develop a bot which will update the status of a facebook account using phpplease guide me on this,['php'] +17838,rails flash message remains for two page loads i am using a flash notice in a rails application with the following codeflashnotice sorry we werent able to log you in with those detailsrender action newthe flash message renders as expected on the new action but then it also shows on the next page the user visits whatever that might be it should only show once but somethings making it stick around,"['ruby-on-rails', 'ruby']" +17842,extract the text in a element with jquery i want to extract the text inside a element with jquerydiv idbla spanstrongbla bla blastrongi want this textspandivi want only the text i want this text without the strongtag how can i do that,['jquery'] +17856,expand div to max width when floatleft is set i have something like thatdiv stylewidth100pxfloatleftmenudivdiv stylefloatleftcontentdivboth floats are neccesary i want the content div to fill the whole screen minus those 100px for the menu if i dont use float the div expands exactly as it should but how do i set this when float is set if i use sth likestylewidth100then the content div gets the size of the parent which is either the body or another div which i also tried and so of course it does not fit right of the menu and is then shown below,['html'] +17860,how to get x newest files from a directory in php the code below is part of a function for grabbing 5 image files from a given directoryat the moment readdir returns the images in the order in which they are stored by the filesystem as per the specmy question is how can i modify it to get the latest 5 images either based on the last modified date or the filename which look like 091652009png 0121752009png etcif handle opendirabsolute dir i 0 image array array while countimage array 5 file readdirhandle false if file file file svn file img image arrayiurl relative dir file image arrayilast modified date f d y his filemtimeabsolute dir file i closedirhandle,['php'] +17867,net serialization ordering i am trying to serialize some objects using xmlserializer and inheritance but i am having some problems with ordering the outcomebelow is an example similar to what i have setup public class serializablebase xmlelementorder 1 public bool property1 get set xmlelementorder 3 public bool property3 get setxmlrootobjectpublic class serializableobject1 serializablebasexmlrootobjectpublic class serializableobject2 serializablebase xmlelementorder 2 public bool property2 get setthe outcome i want is as follows object property1property1 property2property2 property3property3objecthowever i am getting an outcome of object property1property1 property3property3 property2property2objectdoes anyone know if it is possible or of any alternativethanks,['c#'] +17869,simplest way to do a fire and forget method in c i saw in wcf they have the operationcontractisoneway true attribute but wcf seems kind of slow and heavy just to do create a nonblocking function ideally there would be something like static void nonblocking methodfoo but i do not think that existswhat is the quickest way to create a nonblocking method call in cegclass foo static void main fireaway no callback just go away consolewritelinehappens immediately static void fireaway systemthreadingthreadsleep50 consolewriteline5 seconds later nb everyone reading this should think about if they actually want the method to finish see 2 top answer if the method has to finish then in some places like an aspnet application you will need to do something to block and keep the thread alive otherwise this could lead to fireforgetbutneveractuallyexecute in which caseof course it would be simpler to write no code at all a good description of how this works in aspnet,"['c#', '.net']" +17872,how to convert object array to string array in java i use the following code to convert an object array to a string array object object arraynew object100 get values in the object arraystring string arraynew stringobject arraylengthfor int i0istring arraylengthi string arrayiobject arrayitostringbut i wonder if there is another way to do this something like string arraystringobject arraybut this would cause a runtime error exception in thread awteventqueue0 javalangclasscastexception ljavalangobject cannot be cast to ljavalangstringwhats the correct way to do it,['java'] +17874,performance of c0x exceptions what are the performance implications of using exceptions in c0x how much is this compiler dependent should we expect to use exceptions more for general logic handling like in java,['c++'] +17880,querying core data with predicates iphone so i am trying to fetch objects from core data i have list of say 80 objects and i want to be able to search through them using a uisearchbar they are thisplayed in a tableusing the apple documentation on predicates i have put the following code in oneof the uisearchbar delegate methods voidsearchbarsearchbuttonclickeduisearchbar searchbar if selfsearchbartext nil nspredicate predicate nspredicate predicatewithformatname like selfsearchbartext fetchedresultscontrollerfetchrequest setpredicatepredicate else nspredicate predicate nspredicate predicatewithformatall fetchedresultscontrollerfetchrequest setpredicatepredicate nserror error nil if self fetchedresultscontroller performfetcherror handle error nslogunresolved error error error userinfo abort fail selftableview reloaddata searchbar resignfirstresponder shadeview setalpha00fif i type in the search field an exact match to the name property of one of those objects the search works and it repopulates the table with a single cell with the name of the object if i do not search the name exact i end up with no results any thoughts,['iphone'] +17884,whats missing in cocoa if you could add anything to cocoa what would it be are there any features major or minor that you would say are missing in cocoa perhaps there is a wheel you have had to invent over and over because of an omission in the frameworks,['objective-c'] +17896,speed of calculating powers in python i am curious as to why it is so much faster to multiply than to take powers in python though from what i have read this may well be true in many other languages too for example it is much faster to doxxthanx2i suppose the operator is more general and can also deal with fractional powers but if that is why it is so much slower why does not it perform a check for an int exponent and then just do the multiplicationedit heres some example code i trieddef pow1r n for i in ranger p indef pow2r n for i in ranger p 1 for j in rangen p inow pow2 is just a quick example and is clearly not optimisedbut even so i find that using and 2 and r 10 then pow1 takes 2500ms and pow2 takes 1700ms i admit that for large values of n then pow1 does get much quicker than pow2 but that is not too surprising,['python'] +17902,when do i define objectivec methods i am learning objectivec and have a cc background in objectoriented c you always need to declare your method before you define implement it even if it is declared in the parent class in proceduralstyle c iirc you can get away with just defining a function so long as it is only called from something else in the same compilational unit ie the same file that came later on in the file well provided you do not declare it elsewhere with externnow in objectivec it appears that you only need to declare selectors in the header file if they are going to be used by something external and that you can make up selectors in your m file just fine and call them within the m file also it appears that delegate methods or inherited methods are never redefinedam i on the right track when do you need to define a selector in objectivec,['objective-c'] +17905,how to do pgp in python generate keys encryptdecrypt i am making a program in python to be thistributed to windows users via an installerthe program needs to be able to download a file every day encrypted with the users public key and then decrypt itso i need to find a python library that will let me generate public and private pgp keys and also decrypt files encrypted with the public keyis this something pycrypto will do documentation is nebulous are there other pure python libraries how about a standalone command line tool in any languageall i saw so far was gnupg but installing that on windows does stuff to the registry and throws dlls everywhere and then i have to worry about whether the user already has this installed how to backup their existing keyrings etc i would rather just have a python library or command line tool and mange the keys myselfupdate pyme might work but it does not seem to be compatible with python 24 which i have to use,['python'] +17907,how do i run django and php together on one apache server i can currently run either django through mod wsgi or php on my apache servermy django projects run at httplocalhost and source is at cdjango projmy php projects run at and source is at cwebif i turn both on phplocalhost and localhost go to the django project i have already set them up through apache virtual hostshere are some relevant lines in httpdconfdocumentroot cwebdirectory options followsymlinks allowoverride none order denyallow deny from alldirectorydirectory cweb options indexes followsymlinks allowoverride none order allowdeny allow from alldirectorydirectory cdjango proj order allowdeny allow from alldirectoryinclude cdjango projapacheapache django wsgiconfthe relevant lines in apache django wsgiconf iswsgiscriptalias cdjango projapacheprojwsgidirectory cdjango projapache order allowdeny allow from alldirectoryinside httpdvhostsconfdirectory cweb order denyallow allow from alldirectorydirectory cdjango proj order denyallow allow from alldirectoryvirtualhost 80 documentroot cdjango proj servername localhostvirtualhostvirtualhost 80 documentroot cweb servername phplocalhostvirtualhostmy php project is current inaccessible does anyone have any ideas what i am missing,['php'] +17917,loading a image from documents directory in iphone i want to load a image to uiimageview from my app documents library i am trying to use the following code but it is not workinguiimageview background uiimageview alloc initwithframecgrectmake3 10 48 36 autoreleasebackground setimageuiimage imageatpathnsbundle mainbundle pathforresourcethumbnailsmall oftypejpg indirectoryusersnbojjalibraryapplication supportiphone simulatoruserapplications60c2e4ec2fe045799f8608ccf078216ddocumentseb43ac648807425083494b1f5d7d0d9286371c564f40b499bda2aceb00a6d39 retaincan someone help me with doing this thanks,['iphone'] +17919,interacting with another command line program in python i need to write a python script that can run another command line program and interact with it is stdin and stdout streams essentially the python script will read from the target command line program intelligently respond by writing to its stdin and then read the results from the program again it would do this repeatedlyi have looked through the subprocess module and i cannot seem to get it to do this readwritereadwrite thing that i am looking for is there something else i should be trying,['python'] +17922,programming slim c programs like utorrent for windows i have always admired the original utorrent program it looked great was less than 64kb was extremely fast and had all the features i needed unfortunately the program is closed source and becoming more bloated by the day so i come to stackoverflow for inspirationwhat methods do you recommend in writing fast memory efficient and elegant programs on windowswhile c and the whole net concept are cool ideas i am more interested in purist answers and the challenge of writing efficient fast software for the windows platform much like the original utorrent client i do not mind allocating my own memory doing my own garbage collection and creating my own data structuresrecommendations on books articles libraries ides even efficient ways of getting more caffeine into my system welcome,['c++'] +17931,database design for school attendance system i am working on a project for a school where a particular module deals with attendance system i am using lampphp 52 mysql 5 stack for development now the school strength is around 1500 and total number of working days per year is around 250 plus i have to keep records for 5 years before it can be erased the table structure isstudentid varchar12 date datefn varchar1 forenoonaf varchar1 afternoonif i simply use a single table that means 18750 records for a 5 year period now instead of such a humongous database i considered making a table for each class not section so considering there are 12 classes i will have 12 tables which means an average of 1550 records per table which is manageable is this the right way to do it or are there any better ways,['mysql'] +17938,jquery xml parsingtraversing i have the following xmlrows row id5 cellitem1cell attrs attr id1id typecheckboxtype values value id10id value value id11id value values attr attr id2id typecheckboxtype values value id20id value value id21id value values attr attrs rowrowswhat i want to do is to loop each of the of a certain rowi tried to do this in order to get all of the attr ids but i also got the values idsfunction fillformid var therow thexmldocfindrowididget therowfindattreachfunctioni alertthisfindidtext i also would like to note that main goal is loop each attr and afterwards to loop each value while i have the attrs idps if you think of an easiersimpler way to do so with some other library i am open for suggestionsthanks in advance,['jquery'] +17940,do i need static libraries to statically link on c linuxdo i need static libraries to statically link or the shared ones i have sufficeif not why not do not they contain the same data,['c'] +17950,subtle differences between javascript and lua i simply love javascript it is so elegant imagine the quiet sound of lovestruck fanboy sighing in the backgroundso recently i have played with lua via the lave2d framework nice and i think lua is also great they way i see it those two languages are very similarthere are obvious differences likesyntaxproblem domainlibrariestypes a bitbut which are the more subtle ones is there anything a javascript coder would take for granted that works in lua just slightly different are there any pitfalls that may not be obvious to the experienced coder of one language trying the other onefor example in lua arrays and hashes are not separate there are only tables in javascript they are numerical arrays and hashed objects well this is one of the more obvious differencesbut are there differences in variable scope immutability or something like this,['javascript'] +17953,accessing a variable from another class very simple question but i cannot do it i have 3 classesdrawcircle classimport javaawtimport javaawteventimport javaxswingclass drawcircle extends jpanel private int w h di dibig thismall maxrad xsq ysq xpoint ypoint public drawframe d public drawcircle w 400 h 400 dibig 300 thismall 10 maxrad dibig2 thismall xsq 50 ysq 50 xpoint 200 ypoint 200 public void paintcomponentgraphics g superpaintcomponentg gsetcolorcolorblue gdrawovalxsq ysq dibig dibig forint yysq yysqdibig yythismall2 forint xxsq xwxsq xxthismall ifmathsqrtmathpowypointy2 mathpowxpointx 2 maxrad gdrawovalx y thismall thismall forint yysq10 yysqdibig yythismall2 forint xxsq5 xwxsq xxthismall ifmathsqrtmathpowypointy2 mathpowxpointx 2 maxrad gdrawovalx y thismall thismall drawframe classpublic class drawframe extends jframe public drawframe int width 400 int height 400 settitleframe setsizewidth height addwindowlistenernew windowadapter public void windowclosingwindowevent e systemexit0 container contentpane getcontentpane contentpaneaddnew drawcircle circmain classimport javaawtimport javaawteventimport javaxswingpublic class circmain public static void mainstring args jframe frame new drawframe frameshow one class creates a frame the other draws a circle and fills it with smaller circles in drawframe i set width and height in drawcircle i need to access the width and height of drawframe how do i do thisi have tried making an object and tried using getwidth and getheight but cannot get it to work i need specific code here because i have tried a lot of things but cannot get it to work am i declaring width and height wrong in drawframe am creating the object the wrong way in drawcirclealso the variables i use in drawcircle should i have them in the constructor or not,['java'] +17956,memorymapped files in java i have been trying to write some very fast java code that has to do a lot of io i am using a memory mapped file that returns a bytebufferpublic static bytebuffer bytebufferforfilestring fname filechannel vectorchannel bytebuffer vector try vectorchannel new fileinputstreamfnamegetchannel catch filenotfoundexception e1 e1printstacktrace return null try vector vectorchannelmapmapmoderead only0vectorchannelsize catch ioexception e eprintstacktrace return null return vectorthe problem that i am having is that the bytebuffer array method which should return a byte array does not work for readonly files i want to write my code so that it will work with both memory buffers constructed in memory and buffers read from the thisk but i do not want to wrap all of my buffers a bytebufferwrap function because i am worried that this will slow things down so i have been writing two versions of everything one that takes a byte the other that takes a bytebuffershould i just wrap everything or should i doublewrite everything,['java'] +17971,c eval support we need to evaluate a value in an object in run time while we have a textual statement of the exact member path for example myobjectfirstmembersecondmember3textwe thought of parsing this textual statement using regex and then evaluate the text value by using reflection but before we do that i wonder if c support some kind of eval ability so we would not have to do the parsing ourself how do microsoft do this in their immediate window or watch windows thanks you very much adi barda,['c#'] +17972,cannot step into iterator block whilst debugging c i am trying to debug my code which is being executed from a unit test project but when i try to step into a method it just passes straight onto the next line and the breakpoint inside that method is not hit the method is on a class which is in a different project but all the code is built in debug mode and i have tried cleaning and rebuilding the solution with no joyhowever this has only happened since i added an iterator block to the method when i remove it and rebuild i can step in fine weirdi am using visual studio 2010 beta 1 could this just be a bug,['c#'] +17984,mono c tutorial is there any good tutorial to learn c with mono so far google has not been helpful because most tutorial are for visual studioi am a java developer so i am familiar with object oriented ideasmy goal is to be able to develop a small portable application with a sqlite backendthanks,['c#'] +17996,problem unsetting a session variable there is a form on my site that is used for inviting friends it is a simple text field and a submit button if there is an error i redirect back to this page and thisplay an error message if their is a session variable setif isset sessioninvite error echo sessioninvite error unset sessioninvite errorhowever if i navigate away from this page and come back to it the error message is still being thisplayed if i navigate away and come back one more time it will be done it is the same when i refresh that page1 refresh would not get rid of it but 2 will i cannot destroy the entire session i just want to unset this one variable php version is 525 build 6 register globals is off i am calling session start at the top of this page i have tried using a nocache header as welledit added full codephp ob startsession startuser id sessionuser iduser name sessionuser nameif user idnull headerlocation loginphpif isset sessioninvite errors error sessioninvite errors unset sessioninvite errorsrequire onceuiheaderphpdiv idinvite classcontent php iferror div classerrors round php echo error div php h3invite your friendsh3 div classinviteform form methodpost actioncontrollersinvitephp div classrow textarea classtxtarea nameemails idemails rows5textarea div classtipseparate multiple email addresses with div div div classrowsubmit input typesubmit namesubmit idsubmit clasubmitbtn valuesubmit div form divdivphp require onceuifooterphp,['php'] +18002,i need some clarification on the mvc architecture and the threetier architecture i have been reading the book pro asp net mvc framework and i am getting really confused with a lot of things i have been trying to do some research but i am finding that with so many different approaches and concepts being thrown at me it is just making things worseso i have a few questionsi know mvc is supposed to split the functionality into three main things model controller view is the mvc a different approach than the threetier architecture or am i still supposed to be thinking of creating a data access layer and a business logic layer in my projectwhat exactly are repositories it is what acts as my data access layer wherehow do repositories fit into the mvcthe book talks about using linq to sql to interact with the database but yet it states that linq to sql will not be supported in the future and that microsoft is dropping it for the entity framework where does the entity framework fit into the mvc and how do i interact with itthanks in advance for your helpmatt,['asp.net'] +18008,how do you automatically resize columns in a datagridview control and allow the user to resize the columns on that same grid i am populating a datagridview control on a windows form c 20 not wpfmy goal is to thisplay a grid that neatly fills all available width with cells ie no unused dark grey areas down the right and sizes each column appropriately according to the data it contains but also allows the user to resize any of the columns to their likingi am attempting to achieve this by setting the autosizemode of each column to be datagridviewautosizecolumnmodeallcells except for one of the columns which i set to datagridviewautosizecolumnmodefill in order to ensure the entire area of the grid is neatly filled with data i do not mind that when the user attempt to resize this column it springs back to a size that ensures the horizontal space is always usedhowever as i mentioned once loaded i would like to allow the user to resize the columns to suit their own requirements in setting these autosizemode values for each column it appears the user is then unable to then resize those columnsi have tried not setting the autosizemode of all the columns which does allow resizing but does not set the initial size according to the data the cells contain the same result occurs when changing the grids autosizemode back to not set after loading the datais there a setting i am missing here which allows automatic setting of default column widths and user resizing or is there another technique i must use when populating the datagridview control,['c#'] +18023,how to find out next character alphabetically how we can find out the next character of the entered one for example if i entered the character b then how do i get the answer c,['c#'] +18024,whats the standard convention for creating a new nsarray from an existing nsarray let us say i have an nsarray of nsdictionaries that is 10 elements long i want to create a second nsarray with the values for a single key on each dictionary the best way i can figure to do this is nsmutablearray namearray nsmutablearray alloc initwithcapacityarray count for nsdictionary p in array namearray addobjectp objectforkeyname selfmy new array array array release namearray releasebut in theory i should be able to get away with not using a mutable array and using a counter in conjunction with namearray addobjectatindexcount because the new list should be exactly as long as the old list please note that i am not trying to filter for a subset of the original array but make a new array with exactly the same number of elements just with values dredged up from the some arbitrary attribute of each element in the array in python one could solve this problem like thisnew list pname for p in old listor if you were a masochist like thisnew list maplambda p pname old listhaving to be slightly more explicit in objectivec makes me wonder if there is an accepted common way of handling these situations,"['ios', 'objective-c']" +18030,getting a list of all classloaders in a jvm is it possible to get a list of all class loaders in a jvm or at least all class loaders associated with web apps in a java ee server weblogic in my case,['java'] +18032,can i write a c application without using the heap i am experiencing what appears to be a stackheap collision in an embedded environment see this question for some backgroundi would like to try rewriting the code so that it does not allocate memory on the heapcan i write an application without using the heap in c for example how would i use the stack only if i have a need for dynamic memory allocation,['c'] +18038,how to pass two parameters when using stdmem fun lets say i have hierarchy like this this is just a test program please do not point anything related to memory leaks destructor is not virtual etcclass ipublic virtual void funint n int n1 0class a public ipublic void funint n int n1 stdcoutafun n and n1 n1n class b public ipublic void funint n int n1 stdcoutbfun n and n1 n1n int main stdvectori a apush backnew a apush backnew b i want to use stdfor each to call function fun with two argumentshow do i call fun method which takes two arguments using the stdfor each i think i have to use stdmem fun probably with stdbind2nd but am not able to figure out how to do this any clue how to achieve this i am not using boost,['c++'] +18042,read file into array i have a file of wordsphrases separated by newlines i need to get the file and read each wordphrase into the array i have this so far nsfilehandle wordsfile nsfilehandle filehandleforreadingatpathnsbundle mainbundle pathforresourcewordlist oftypenil nsdata words wordsfile readdatatoendoffile wordsfile closefile wordsfile releasebut i am not sure if that is right and if so where to go from therealso teabots answer of nsstring componentsseparatedbycharactersinset nscharacterset newlinecharactersetworks great but it is 105 only how would this behavior be replicated for 104,['objective-c'] +18046,datagridview capturing user row selection i am having trouble handling the selections in datagridviewmy grid view contains an amount column there is a textbox on the form which should thisplay the total amount of the selected grid view rows hence i need to capture events when the user selects deselects the gridview rows and calculate add subtract the amount accordingly i have found two methods of doing itusing the rowenter and rowleave events these work fine when user selects deselects a single row however when the user is selecting multiple rows at one go the event gets fired only for the last row hence from my total amount only the amount in the last row gets added subtracted thus making my result erroneoususing the rowstatechanged eventthis works for multiple rows however the event gets fired event if the user scrolls through the datagrid has anyone handled such a scenario i would like to know which datagrid event i should be using so that my code executes only when user selects deselects rows including multiple rows,['c#'] +18050,using stl algorithms is it better to pass a function pointer or a functor which of these 2 methods is better and whymethod 1void funint i do stufor eachabegin aend funmethod 2class functor public void operatorint ifor eachabegin aend functoredit should have formulated it this way in what situation is one of the above method preferable to the otherthanks a lot,['c++'] +18059,improving performance reflection what alternatives should i consider i need to dynamically set values on a bunch or properties on an object call it a transmission object there will be a fair number of these transmission objects that will be created and have its properties set in a short space of timei want to avoid the use of reflection are there alternativ if so are there sample implementations i could look atthanks,"['c#', '.net']" +18060,is python a stable platform for facebook development i am trying to build my first facebook app and it seems that the python facebook pyfacebook wrapper is really out of date and the most relevant functions like stream functions are not implementedare there any mature python frontends for facebook if not whats the best language for facebook development,['python'] +18062,the test form is only available for requests from the local machine i created a web service in net and so the address of the service file has a nifty auto generated explanation about how it works when i run the page from the machine it is hosted on it even has a form that i can use to submit test values to the service however on remote machines it hides the form and gives the message as seen aboveis there a point to this i have seen other sites call this more secure but anyone could create their own forms easily making this nothing more than a nuisance if you ask me,['.net'] +18065,what is the difference between stringempty and aa and null possible duplicatewhat is the difference between stringempty and is equivalent to stringemptywhich is preferred for initializing string values,"['c#', '.net']" +18069,set commandtimeout used in strongly typed dataset tableadapter preambleso over the past 5 years or so various applications and tools have been written here at my company unfortunately many of the people who developed these applications used strongly typed datasets i am considering outlawing them in our shop nowone of the larger processes that used strongly typed datasets is now timing out i intend to rewrite the the whole process using nhibernate in the next few months but for the moment i need to change the timeout to allow our users to use the process albeit slowly unfortunately microsoft made the commandtimeout methods private so i cannot access them directly the only solution i have come across so far is to create a partial class for each tableadapter and include the timeout methods there this is quite clunky as it would mean adding partial classes for quite a few tableadaptersanyone know of a more efficient way to handle this,['c#'] +18070,use cases for boxing a value type in c there are cases when an instance of a value type needs to be treated as an instance of a reference type for situations like this a value type instance can be converted into a reference type instance through a process called boxing when a value type instance is boxed storage is allocated on the heap and the instances value is copied into that space a reference to this storage is placed on the stack the boxed value is an object a reference type that contains the contents of the value type instanceunderstanding nets common type system in wikipedia there is an example for java but in c what are some cases where one would have to box a value type or would a bettersimilar question be why would one want to store a value type on the heap boxed rather than on the stack,['c#'] +18071,clr sql stored procedures testing with unit test project i am just getting into using vs2008 to write clr stored procedures for sql 2008 when writing c code i am used to having a separate test project where i would place all my unit testing code however it appears at first blush that i cannot have the same setup with a clr sql project with stored procedures it feels like this can be done and i am missing a couple of configuration parameters but i am not sure what those might bei am usingvisual studio 2008ms testms sql 2008my requirements aredebug the stored procedure in the visual studio debuggerhave a bunch of unit test to test the stored proceduresdoes anyone know how i can have the unit test project properly depoly the stored procedures to the server connect up to the sql server and allow me to step through the unit test to the stored procedures that are sitting on the serverupdatethank you to everyone for the answers so far however they are not excatly what i am looking formark seemanns answer below is an interesting approach that i did not know about and i will certainly use when it comes to resetting my database to a known state however i am looking to debug clr stored procedures and it does not appear marks method will allow me to step from my unit test project through to the sql server and debug the code sitting on the serveri am looking to actually debug the c sitting on the server much like the solution pho3nix listed below however using this standard approach you need to write your test scripts using a testsql file and not using a unit test project from within visual studioi hope i can have two projects in my solution one for my clr stored procedures and one for my unit test project when i want to run my tests in my unit test project i hope that all of the changes made to my clr stored procedure project will be published to the server the test project will start executing and if i set a break point in the clr stored procedure when the unit test begins to test that stored procedure it will break on the server and i can then step through the codethe closest solution i have found so far is by alex kuznetsov and alex styler however using this solution i can not step through to the sql serverupdate 2this is more of a bump to bring this question back upi have still had no luck stepping to the sql server from the unit tests any other thoughts,['sql'] +18077,are inner classes commonly used in java are they bad are inner classes commonly used in java are these the same as nested classes or have these been replaced in java by something better i have a book on version 5 and it has an example using an inner class but i thought i read somewere that inner classes were badi have no idea and was hoping for thoughts on itthank you,['java'] +18078,what is the rollsroyce way to deploy a java applet i know how to deploy an applet using applet object embed tags and javascript but i am after the best approach in terms of end user experiencesun suggests using the applet tag and a mixed embed object tag on the same pagewhat i am considering is the followingcrossbrowser supportfallback to download page if incorrect java version is found eg pre 15loading page for both java vm start period and while the jar is downloaded ideally a custom splash screen with a progress barquestions have been asked before how to deploy check for 16 and plugin framework none of these fully answer my question i am also not considering web start or java fxmy current solution is to include an additional small test applet compiled for java 11 if java pre15 is found it redirects the page to the failure page if no java is found the page asks the user to visit javacom this works acceptably but is poor because it requires an additional applet and does not show anything while the vm is starting,['java'] +18092,how can i enable multiple segments of a uisegmentedcontrol to be selected lets say my uisegmentedcontrol has 8 numbered segments i would like for the user to be able to turn on 2 3 or more of them at once toggling them essentially like a bits in a byte is this possible i believe it is on regular mac os x but i cannot seem to find a way to do it in the iphone sdkif i have to simulate this by putting buttons into a view is there any way to do the followinground the corners of the view so that it looks like the bar style uisegmentedcontroluse the builtin backgrounds the bar style has on the buttonsgive the buttons a shadow like the whole bar style has not the text,['iphone'] +18097,get mime type from filename extension how can i get the mime type from a file extension,"['c#', 'asp.net']" +18102,php alternative to trac possible duplicateis there an equivalent to trac written in php are there any php alternatives to edgewalls trac solution which works on python and not really portable,['php'] +18105,how to deal with codeigniter templates i am fairly new to mvc and i have found codeigniter recently i am still learning everyday but one problem is its template engine what is the best way to create templates in codeignitercakephp comes with its own template library is there a similar feature in codeigniter,['php'] +18108,how do you pass multiple enum values in c sometimes when reading others c code i see a method that will accept multiple enum values in a single parameter i always thought it was kind of neat but never looked into itwell now i think i may have a need for it but do not know how toset up the method signature to accept thiswork with the values in the methoddefine the enumto achieve this sort of thingin my particular situation i would like to use the systemdayofweek which is defined asserializablecomvisibletruepublic enum dayofweek sunday 0 monday 1 tuesday 2 wednesday 3 thursday 4 friday 5 saturday 6i want to be able to pass one or more of the dayofweek values to my method will i be able to use this particular enum as it is how do i do the 3 things listed above,['c#'] +18115,race conditions in django here is a simple example of a django view with a potential race condition myappviewspyfrom djangocontribauthmodels import userfrom my libs import calculate pointsdef add pointsrequest user requestuser userpoints calculate pointsuser usersavethe race condition should be fairly obvious a user can make this request twice and the application could potentially execute user requestuser simultaneously causing one of the requests to override the othersuppose the function calculate points is relatively complicated and makes calculations based on all kinds of weird stuff that cannot be placed in a single update and would be difficult to put in a stored procedureso here is my question what kind of locking mechanisms are available to django to deal with situations similar to this,['python'] +18132,simultaneous java and scala development within the same project i want to leverage the scalas actor framework while i develop the user interface in the familiar swing wayis it possible to have a mixed java scala project in eclipse netbeans or any other ide,['java'] +18138,c enum in interfacebase class i have problem with enumi need make a enum in base class or interface but empty oneclass base public enum test and after make diffrent enums in some parent classesclass parent1 public enum test a b cclass parent2 public enum test j h kand now i have next class with method when i have to use enumclass testt public void footest enum int value int enum it is there any way to do something like that if not i have to use static ints in every class class parent1 public static int a 0 public static int b 5 public static int c 7class parent2 public static int j 1 public static int h 3 public static int k 6class testt public void fooint enum int value enum it looks bad in code in some classes i have to use 20 variables,['c#'] +18145,entity framework references not loading automatically in the adonet entity framework i have an object which has 4 references to other objects for some reason when i query those references two of them load automatically as expected and two of them always return nullbizarrely enough when i manually ask the references to load they load just dandyas an exampleif accountholdingentity null accountholdingentityreferenceentitykey null accountholdingentityreferenceload accountholdingentity accountholdingentityreferencevaluewhen i first check the holdingentity it is always null however the load will return the holdingentity without problemany cluesthanks,['c#'] +18147,how is a rounded rect view with transparency done on iphone a lot of apps pop up a transparent view with rounded corners and an activityindicator when running a time consuming operationhow is this rounding done and is it possible to do it just using interface builder as there are lots of places i would like to use something like this or should i use an imageview with a rounded rect or stretchable image do i need to draw the background myselfso far i have managed to get a basic view with similar transparency by setting the alphavalue in interface builder however it does not have rounded corners and also the transparency seems to apply to all subviews i do not want the text and activityindicator to be transparent however even though i set the alphavalue on those in ib it seems to get ignored,['iphone'] +18156,what is a good naturallanguage naming scheme for belonging or property interfaces note this is not the popular interface naming question aboutusing or not using i at the beginningi encounter often the problem to namean interface which indicates a belonging or property of a classplease see following listlet us brainstorm what kinds of interfaces are thereindicate the kind of a classdatastructure number thingindicate the profession of a classcomparator executor listenerindicate a possible action performed with a classcomparable executable closeablethe above are all clear to anyone but let us get to my problemindicate a belonging or property of a classhaslistener linkstoroot belongstoparent knowssibling containschildrennamed withdescription so the last point is my problem my english is not perfectbut even i feel strange about such namesthey sound to me less successfully chosen then other less meaningfulbut i often end up choosing right this kind of namesit is even a greater thiscomfort in c where interfaces are expectedto start with an iihaslistener iknowssibling sound to me like lolspeak i can haz a kitteh tawtally being full ofcuteness omgso how should i name an interface which indicates a belonging orproperty of a class,"['c#', 'java']" +18161,how do you do page performance tests i know everyone who reads the question will think firebug right away maybe some will think yslow and google page speedwhile i really like these tools i am more concerned with how the quickly the page will render in ie 678 all of the above tools require firefox that is all fine and you can definitely test the underlying speed of getting the page to the browser but what about when it comes to actually rendering the pagei have not seen any really good answers on how to test optimization at the browser level how do you write performance tests for htmljs across difference browsers,"['javascript', 'html']" +18168,c exiting a using block with a thread still running onthe scoped object what happens to a thread if it is running a method in an object that was freed by exiting a using blockexample using someobject obj new someobject objparam 10 thread newthread new thread objwork newthreadstart objwork is running on a new thread but obj is an ithisposable object that would normally get released when the using block exits what happens if the thread continues running after the using block ends will the object get thisposed only after the thread completes or will the thread breakthanks,['c#'] +18183,simple jquery ajax example not finding elements in returned html i am trying to learn jquerys ajax functions i have got it working but jquery does not find elements in the returned html dom in the same folder as jquery run this pagedoctype html public w3cdtd xhtml 10 strictenhtml xmlns langen xmllangenhead titlerunthistitle script typetextjavascript languagejavascript srcjquery132minjsscript script tyletextjavascript documentreadyfunction inputclickfunction ajax type get url ajaxtestloadhtml datatype html success functiondata alert data shows whole dom alert datafindwrapperhtml returns null error function alertsorry the requested property could not be found scriptheadbody input typebutton valueload bodyhtmlwhich loads this page ajaxtestloadhtmldoctype html public w3cdtd xhtml 10 strictenhtml xmlns langen xmllangenhead titleload thistitleheadbody div idwrapper test divbodyhtmlit gives two alerts one showing the dom was loaded but the second shows null instead of the wrapper what am i doing wrong edit i am loading ajaxtestloadhtml which includes the whole header including jquery again is that the issue,['jquery'] +18197,performance of interlockedincrement is interlockedincrementref x faster or slower than x for ints and longs on various platforms,['.net'] +18209,javas versus operator i am without my java reference book and i am having a tough time finding an answer with googlewhat is the difference between the and operators in javaint value 0x0100int result value 8systemoutprintlnvalue 8 result prints value 8 1result value 8systemoutprintlnvalue 8 result prints value 8 1,['java'] +18220,best way to combine fragment and object caching for memcached and rails lets say you have a fragment of the page which thisplays the most recent posts and you expire it in 30 minutes i am using rails here cacherecent posts expires in 30minutes do end obviously you do not need to do the database lookup to get the most recent posts if the fragment exists so you should be able to avoid that overhead toowhat i am doing now is something like this in the controller which seems to workunless railscacheexist viewsrecent posts posts postfindall limit20 orderupdated at descendis this the best way is it safeone thing i do not understand is why the key is recent posts for the fragment and viewsrecent posts when checking later but i came up with this after watching memcached vv to see what it was using also i do not like the duplication of manually entering recent posts it would be better to keep that in one placeideas,"['ruby-on-rails', 'ruby']" +18224,reading binary file in python and looping over each byte in python how do i read in a binary file and loop over each byte of that file,['python'] +18232,sql server how to set nolock hint as a default is there some way to tell sql server to use the nolock hint or every select in a stored procedureis pretty tiresome to add it to each an every select,['sql'] +18276,which cipher suites to enable for ssl socket i am using javas sslsocket to secure communications between a client and a server program the server program also serves up https requests from web browsersaccording to beginning cryptography with java page 371 you should always call setenabledciphersuites on your sslsocket sslserversocket to ensure that the cipher suite that ends up being negotiated is sufficiently strong for your purposesthat being said a call to my sslsocketfactorys getdefaultciphersuites method yields some 180 options these options range from tls rsa with aes 256 cbc sha which i think is fairly secure to ssl rsa with rc4 128 md5 not so sure if that is secure given md5s current status to ssl dhe dss export with des40 cbc sha not entirely sure what that doeswhats a sensible list of cipher suites to restrict the sockets tonote that the client and server have access to the bouncy castle service provider and that they may or may not have unlimited cryptographic policy files installed,['java'] +18289,data structure for maintaining tabular data in memory my scenario is as follows i have a table of data handful of fields less than a hundred rows that i use extensively in my program i also need this data to be persistent so i save it as a csv and load it on startup i choose not to use a database because every option even sqlite is an overkill for my humble requirement also i would like to be able to edit the values offline in a simple way and nothing is simpler than notepadassume my data looks as follows in the file it is comma separated without titles this is just an illustration row name year priority 1 cat 1998 1 2 fish 1998 2 3 dog 19 1 4 aardvark 20 1 5 wallaby 20 1 6 zebra 2001 3notesrow may be a real value written to the file or just an autogenerated value that represents the row number either way it exists in memorynames are uniquethings i do with the datalookup a row based on either id iteration or name direct accessthisplay the table in different orders based on multiple field i need to sort it eg by priority and then year or year and then priority etci need to count instances based on sets of parameters eg how many rows have their year between 1997 and 2002 or how many rows are in 1998 and priority 2 etci know this cries for sqli am trying to figure out whats the best choice for data structure following are several choices i seelist of row listsa aappend 1 cat 1998 1 aappend 2 fish 1998 2 aappend 3 dog 19 1 list of column lists there will obviously be an api for add row etca aappend 1 2 3 4 5 6 aappend cat fish dog aardvark wallaby zebra aappend 1998 1998 19 20 20 2001 aappend 1 2 1 1 1 3 dictionary of columns lists constants can be created to replace the string keysa aid 1 2 3 4 5 6aname cat fish dog aardvark wallaby zebra ayear 1998 1998 19 20 20 2001 apriority 1 2 1 1 1 3dictionary with keys being tuples of row fieldcreate constants to avoid string searchingname1year2priority3aa1 name cata1 year 1998a1 priority 1a2 name fisha2 year 1998a2 priority 2and i am sure there are other ways however each way has thisadvantages when it comes to my requirements complex ordering and counting whats the recommended approacheditto clarify performance is not a major issue for me because the table is so small i believe almost every operation will be in the range of milliseconds which is not a concern for my application,['python'] +18290,mysql select into outfile tmp no output i cannot get the following code to generate any output the mysql user has all grant level tmp is writable the query returns a results set mysql select field from test table where conditiontest into outfile tmptestcsv fields terminated by enclosed by lines terminated by nquery ok 1 row affected 0 secmysql1 stopped mysqlrootweb1 cat tmptestcsvcat tmptestcsv no such file or directoryshould i be seeing different output from mysql in case of failure can i verify the result further than 1 row affected,"['mysql', 'sql']" +18294,dependency injection with guice something that is not covered by any tutorial i just tinkered around with google guice for dependency injection and started integrating it into my existing application so far so good i have many classes which need beside their dependencies strings datasources et cetera i know there are namedbindings but i really do not want to create an annotation for every simple string i have to pass to the constructor for each class then there is a thing called assistedinject creating factory implementions for me wow but i still have to define the interface of the factory thats okay for classes which do have dependencies but what about this example classpublic class foobarclass public foobarclastring name string anotherone some stuff there are cases where i am in doubt how to use guice or more generally di the right way often i hear xyz framework is the new new but this implicit that i have to create every instance with the di frameworkonly one instance is requiredwhat if i need only one instance of this class this class has absolutly no dependencies beside two strings think about a shutdown hook which will be instanciated only once and passed to the jvm as my shutdown hook should i create this instance with guice this looks very dumb to me because there is nothing to inject but i have to write a factory interface to pass guide both parameters and have to create an interface for my foobarclass to use dimultiple instances are requiredthe same thing applies to a case where i need multiple instances of this class no dependencies but i have to create a bunch of boilerplate code to get nothing out of it this seems wrong to meso how i am supposed to use di andor guicethanks a lot,['java'] +18297,in python how do i easily generate an image file from some source data i have some some data that i would like to visualize each byte of the source data roughly corresponds to a pixel value of the imagewhat is the easiest way to generate an image file bitmap using python,['python'] +18298,how can i convert an integer to localized month name in java i get an integer and i need to convert to a month names in various localesexample for locale enus1 january2 februaryexample for locale esmx1 enero2 febrero,['java'] +18300,datatype conversion in ibm db2 bigint to varchar i am writing a query to do some stuff but its not working the way i want it toselect corr id from table1where corr id not in select id from table2the problem is table2id is a long while table1corr id is a stringso how can i make it workps i am using ibm udb,['sql'] +18301,dynamic paths in helper i am trying to create a helper method for my admin links in quite a fewviews i have the code if current user link to edit edit model pathmodel link to new new model path link to delete model confirm youre a noob method delete end that only thisplay these when logged ini would like to do something like this in their place admin linksmodel and pass the current item into the application helper methoddef admin linksm if current user a link to edit edit m pathm a link to new new m path a link to delete m confirm your a noob method delete endendor something of the like,['ruby-on-rails'] +18307,what is the most appropriate data type for storing an ip address in sql server what should be the most recommended datatype for storing an ipv4 address in sql serveror maybe someone has already created a user sql datatype net assembly for iti do not need sorting,['sql'] +18316,how do i browse a websphere mq message without removing it i am writing a net windows forms application that will post a message to a websphere mq queue and then poll a different queue for a response if a response is returned the application will partially process the response in real time but the response needs to stay in the queue so that a daily batch job which also reads from the response queue can do the rest of the processingi have gotten as far as reading the message what i have not been able to figure out is how to read it without removing itheres what i have got so far i am an mq newbie so any suggestions will be appreciated and feel free to respond in cpublic function getmessagebyval msgid as string as mqmessage dim q connecttoresponsequeue dim msg as new mqmessage dim getopts as new mqgetmessageoptions dim runthru nowaddmillisecondscintconfigurationmanagerappsettingsresponsetimeoutms systemthreadingthreadsleep10 wait for one second before checking for the first response while true try qgetmsg getopts return msg catch ex as mqexception when exreason mqcmqrc no msg available if now runthru then throw ex systemthreadingthreadsleep30 finally qclose end try end while return nothing should never reach hereend functionnote i have not verified that my code actually removes the message but that is how i understand mq to work and that appears to be whats happening please correct me if that is not the default behavior,['.net'] +18323,what are ftl files i am new to a project and have to learn it inside out i see a lot of files with the extension ftl in them in not sure what they are i know they can be modified and the user sees changes in the front end,"['java', 'javascript']" +18325,how to insert values into c dictionary on instantiation does anyone know if there is a way i can insert values into a c dictionary when i create it i can but do not want to do dictaddint string for each item if there is something more efficient like dictionaryint string0 string1string22string3,['c#'] +18327,why cannot i roll a loop in javascript i am working on a web page that uses dojo and has a number 6 in my test case but variable in general of project widgets on it i am invoking dojoaddonloadinit and in my init function i have these linesdojoconnectdijitbyidproject 0inputnode onchange function makematch0dojoconnectdijitbyidproject 1inputnode onchange function makematch1dojoconnectdijitbyidproject 2inputnode onchange function makematch2dojoconnectdijitbyidproject 3inputnode onchange function makematch3dojoconnectdijitbyidproject 4inputnode onchange function makematch4dojoconnectdijitbyidproject 5inputnode onchange function makematch5and change events for my project widgets properly invoke the makematch function but if i replace them with a loopfor var i 0 i 6 i dojoconnectdijitbyidproject iinputnode onchange function makematchisame makematch function same init invocation same everything else just rolling my calls up into a loop the makematch function is never called the objects are not wiredwhats going on and how do i fix it i have tried using dojoquery but its behavior is the same as the for loop case,['javascript'] +18334,c using memset function this is the code that i want to try to writeinclude stdiohinclude mathhinclude stdlibhinclude stringhinclude mallochint mainint argc char argv float arry3 0 memsetarry int 100 3sizeoffloat return 0my problem is that i want to see if it is possible to use memset to make every entry of an array to be a number other than 0 however after stepping through that line the array contents change to a very small number 0 i wonder what i am doing wrong in this case with using the memset function i hope this is not a duplicate post as none of the suggested related questions as i am typing this appears to be,['c'] +18344,wildcard search for linq i would like to know if it is possible to do a wildcard search using linqi see linq has contains startswith endswith etcwhat if i want something like test ifit work how do i do itregards,"['c#', 'sql']" +18356,creating controls in a nonui thread i have a sort of plugin model in which various complex user controls are stored in dlls and loaded and instantiated at run time using activatorcreateinstancefromdllpath classnamesince i am loading quite a few of these i wanted to do it in the background keeping my ui responsive by creating a new thread to do the loading the controls are then parented to the main form and thisplayed when neededthis seems to work fine until i try to set any property on any nested control on one of these user controls eg in the event handler of a button which throws a cross threading exception i do realize i could avoid this by checking invokerequired every time i access a property but i would rather not have to worry about that when writing the code for the user controls especially since there are others writing these bits of code too who might not always rememberso my question is is there any safe way to do what i am attempting or how should i best go about loading these controls in the background or is it basically impossible and do i have to stick to the main thread for creating controlsi hope that the information i have provided is enough to make my situation clear if not i would be glad to elaborate and provide code samples,['.net'] +18358,net vs ejb what is the comparable technology of ejb enterprise java beans in net,"['java', '.net']" +18363,referencetype conversion operators asking for trouble when i compile the following code using gclass a void fooa int main fooa return 0i get the following error messages g testcpp o test testcpp in function aint mainatestcpp10 error invalid initialization of nonconst reference of type a from a temporary of type atestcpp6 error in passing argument 1 of avoid fooafter some reflection these errors make plenty of sense to me a is just a temporary value not an assignable location on the stack so it wouldnt seem to have an address if it does not have an address then i cannot hold a reference to it okay finebut wait if i add the following conversion operator to the class aclass apublic operator a return this then all is well my question is whether this even remotely safe what exactly does this point to when a is constructed as a temporary valuei am given some confidence by the fact thatvoid fooconst a can accept temporary values according to g and all other compilers i have used the const keyword can always be cast away so it would surprise me if there were any actual semantic differences between a const a parameter and an a parameter so i guess that is another way of asking my question why is a const reference to a temporary value considered safe by the compiler whereas a nonconst reference is not,['c++'] +18365,iphone weird space at the top of uinavigationcontroller i am having a strange problem with adding a uinavigationcontroller to my iphone application i add the controller as followsmyviewcontroller viewcontroller myviewcontroller alloc initwithnibnamemyview bundlenilmynavigationviewcontroller navigationcontroller mynavigationviewcontroller alloc initwithrootviewcontrollerviewcontrolleruiview finalview myenavigationviewcontrollerviewselfview addsubviewfinalviewall seems to work as planned except i get a weird white space at the top of my view between the status bar and the uinavigationcontroller title bari have searched online but do not really know what to search for has anyone else had this problem can you point me in the direction of some helpthanks in advance,"['iphone', 'objective-c']" +18381,whats the most efficient way to erase duplicates and sort a vector i need to take a c vector with potentially a lot of elements erase duplicates and sort iti currently have the below code but it does not workvecerase stduniquevecbegin vecend vecendstdsortvecbegin vecendhow can i correctly do thisadditionally is it faster to erase the duplicates first similar to coded above or perform the sort first if i do perform the sort first is it guaranteed to remain sorted after stdunique is executedor is there another perhaps more efficient way to do all this,['c++'] +18389,using scanf in c programs is faster than using cin i do not know if this is true but when i was reading faq on one of the problem providing sites i found something that poke my attentioncheck your inputoutput methods in c using cin and cout is too slow use these and you will guarantee not being able to solve any problem with a decent amount of input or output use printf and scanf insteadcan someone please clarify this is really using scanf in c programs faster than using cin something if yes that is it a good practice to use it in c programs i thought that it was c specific though i am just learning c,"['c++', 'c']" +18393,best way to add a new column with an initial but not default value i need to add a new column to a ms sql 2005 database with an initial value however i do not want to automatically create a default constraint on this column at the point in time that i add the column the defaultinitial value is correct but this can change over time so future access to the table must specify a value instead of accepting a defaultthe best i could come up with isalter table tbl add col integer nullupdate tbl set col 1alter table tbl alter column col integer not nullthis seems a bit inefficient for largish tables 10 to 10 records i have experimented with adding the column with a default and then deleting the default constraint however i do not know what the name of the default constraint is and would rather not access sysobjects and put in database specific knowledgeplease there must be a better way,['sql'] +18408,design tips for storekit in iphone os 30 i am going to implement storekit in an iphone application and wanted to know if there is any experience out there already that could point out any pitfalls or traps in using storekiti know the api is new but there is some premium content in my app that i would like to ask users to pay for and this seems an ideal way to do it rather than directing them to a website for separate payment on their subscriptioni also assume there are guidelines for how you list an app in the app store to make clear that the app is free to install but you must upgrade for certain functionalityupdate from commentsyou cannot convert a free app into a paid app so the user must first install it at the minimum cost before you can then use the storekit api to charge for additional software2nd update you can now use the api in free apps apple changed the rules recentlycan anyone recommend a good application that uses the storekit api that i might model the user interaction on,['iphone'] +18413,retrieving a pixel alpha value for a uiimage i am currently trying to obtain the alpha value of a pixel in a uiimageview i have obtained the cgimage from uiimageview image and created a rgba byte array from this alpha is premultipliedcgimageref image uiimagecgimagensuinteger width cgimagegetwidthimagensuinteger height cgimagegetheightimagecgcolorspaceref colorspace cgcolorspacecreatedevicergbrawdata mallocheight width 4bytesperpixel 4bytesperrow bytesperpixel widthnsuinteger bitspercomponent 8cgcontextref context cgbitmapcontextcreate rawdata width height bitspercomponent bytesperrow colorspace kcgimagealphapremultipliedlast kcgbitmapbyteorder32bigcgcolorspacereleasecolorspacecgcontextdrawimagecontext cgrectmake0 0 width height imagecgcontextreleasecontexti then calculate the array index for the given alpha channel using the coordinates from the uiimageviewint byteindex bytesperrow uiviewpointy uiviewpointx bytesperpixelunsigned char alpha rawdatabyteindex 3however i do not get the values i expect for a completely black transparent area of the image i get nonzero values for the alpha channel do i need to translate the coordinates between uikit and core graphics ie is the yaxis inverted or have i misunderstood premultiplied alpha valuesupdatenikolai ruhe is suggestion was key to this i did not in fact need to translate between uikit coordinates and core graphics coordinates however after setting the blend mode my alpha values were what i expectedcgcontextsetblendmodecontext kcgblendmodecopy,['iphone'] +18415,django unit testing with datetimebased objects suppose i have the following event modelfrom djangodb import modelsimport datetimeclass eventmodelsmodel date start modelsdatefield date end modelsdatefield def is overself return datetimedatetoday selfdate endi want to test eventis over by creating an event that ends in the future today 1 or something and stubbing the date and time so the system thinks weve reached that future datei would like to be able to stub all system time objects as far as python is concerned this includes datetimedatetoday datetimedatetimenow and any other standard datetime objectswhats the standard way to do this,['python'] +18416,writing directly to stdstring internal buffers i was looking for a way to stuff some data into a string across a dll boundary because we use different compilers all our dll interfaces are simple charis there a correct way to pass a pointer into the dll function such that it is able to fill the string buffer directlystring stringtofillin100 0functionindll stringtofillinc str stringtofillinsize definitely wrongfunctionindll const castcharstringtofillindata stringtofillinsize wrongfunctionindll stringtofillin0 stringtofillinsize wrongstringtofillinresize strlen stringtofillinc str the one that looks most promising is stringtofillin0 but is that a correct way to do this given that youd think that stringdata string0 it seems inconsistentor is it better to swallow an extra allocation and avoid the questionvectorchar vectortofillin100functionindll vectortofillin0 vectortofillinsize string dllgaveus vectortofillin0,['c++'] +18418,performance of nested yield in a tree i have got a treelike structure each element in this structure should be able to return a enumerable of all elements it is root to let us call this method ienumerablefoo getall so if we have a topmost root b c d e f ga call to getall on element c returns c f g fixed order of elements would be nice but is not needed i guess everybody knew that alreadythe current implementation of getall looks like thispublic ienumerablefoo getall yield return this foreach foo foo in mychildren foreach foo f in foogetall yield return f in an earlier implementation i returned a list and added the childfoos using listaddrangemy question is if the version using yield is correcly implemented or if it should be improved esp in terms of performance or is this just bad and i should stick to lists or readonlycollections instead,['c#'] +18423,how can i include the output of a perl script into a php page weve been asked to support some rather old perl forms on a new site as were using a php based cms we need to include the perl scripts into our new cmsi have tried a bit of shell exec but that is thisabled has anyone got any ideas,['php'] +18431,iphone 30 compass how to get a heading i am relatively new to objectivec and really do not know much about it yet so i apologise for what is probably a really amateurish questioni am trying to get the magnetic heading from clheading and cllocationdirection however i am getting compile errors for this line of codelocationlabeltext location course magneticheading stringvaluethe errors arewarning invalid receiver type cllocationdirection error cannot convert to a pointer typei do not really understand what i am doing wrong here please help,['iphone'] +18432,how to stop thinking relationally at work we recently started a project using couchdb a documentoriented database i have been having a hard time unlearning all of my relational db knowledgei was wondering how some of you overcame this obstacle how did you stop thinking relationally and start think documentally i apologise for making up that wordany suggestions helpful hintsedit if it makes any difference were using ruby couchpotato to connect to the databaseedit 2 so was hassling me to accept an answer i chose the one that helped me learn the most i think however there is no real correct answer i suppose,['ruby'] +18444,import using angle brackets and quote marks i am wondering what decides whether youre allowed to use headerh or headerh when youre importing files in objectivec so far my observation has been that you use the quote marks for files in your project that youve got the implementation source to and angle brackets when youre referencing a library or framework but how exactly does that work what would i have to do to get my own classes to use the brackets right now xcode will not allow me to do that for my own headersalso by looking in some frameworks headers i see that the headers reference each other with frameworknamefileh how does that work it looks a lot like packages in java but as far as i know there is no such thing as a package in objectivec,['objective-c'] +18447,unhandled exceptions in backgroundworker i have a small winforms app that utilizes a backgroundworker object to perform a longrunning operationthe background operation throws occasional exceptions typically when somebody has a file open that is being recreatedregardless of whether the code is run from the ide or not net pops up an error dialog informing the user that an unhandled exception has occurred compiling the code using the release configuration does not change this eitheraccording to msdnif the operation raises an exception that your code does not handle the backgroundworker catches the exception and passes it into the runworkercompleted event handler where it is exposed as the error property of systemcomponentmodelrunworkercompletedeventargs if you are running under the visual studio debugger the debugger will break at the point in the dowork event handler where the unhandled exception was raisedi expect these exceptions to be thrown on occasion and would like to handle them in the runworkercompleted event rather than in dowork my code works properly and the error is handled correctly within the runworkercompleted event but i cannot for the life of me figure out how to stop the net error dialog complaining about the unhandled exception from occurringis not the backgroundworker supposed to catch that error automagically is not that what the msdn documentation states what do i need to do to inform net that this error is being handled while still allowing the exception to propage into the error property of runworkercompletedeventargs,['c#'] +18459,nsinvalidargumentexceptioncopywithzone exception with nsmutabledictionary i have a class that i am encapsulating abrecordid with and when it is used as a key to add to an nsmutabledictionary i get the runtime exceptionnsinvalidargumentexception myrecordid copywithzone unrecognized selector sent to instancemyrecordid declared asinterface myrecordid nsobject abrecordid abrecordididinitwithidabrecordidanabrecordidproperty nonatomic abrecordid abrecordidendadding to dictionarynsmutabledictionary dict nsmutabledictionary alloc initmyrecordid recordid myrecordid alloc initwithidanabrecordiddict setobjecthello forkeyrecordidthe last line causes the exception i know that you cannot store nonobject types as keys for a dictionary but i thought that wrapping it up in nsobject derived class would make it okayam i not supposed to store abrecordid in other objects should i be doing something else,['iphone'] +18467,how to set tcp nodelay on bsd socket on solaris i am trying to turn off nagles algorithm for a bsd socket usingsetsockoptnewsock ipproto tcp tcp nodelay charflag sizeof flagbut the compiler claims tcp nodelay has not been seen beforeerror tcp nodelay undeclared first use this functionthis is the full list of includes for the file this is ininclude arpainethinclude fcntlhinclude iostreaminclude netdbhinclude stringinclude syssockethinclude systypeshusing namespace stdi also have the lnsl and lsocket linker options but it just would not compile am i missing somethingall of this is on a solaris 8 machine,"['c++', 'c']" +18474,dealing with firefox and internet explorers differences this question is because i just found out that my site is looking ok in ie7 and in ie8 with compatibilitymode but in ff it is all screwed upwhat would be the best way to go about itseparate css filesthanks richard,['css'] +18478,is there a better way to wait for queued threads is there a better way to wait for queued threads before execute another processcurrently i am doingthisworkerlocker new object global variablethisrunningworkers arraystringslength global variable initiate processforeach string somestring in arraystrings threadpoolqueueuserworkitemthisdosomething somestring threadsleep100 waiting execution for all queued threadslock thisworkerlocker global variable object while thisrunningworkers 0 monitorwaitthisworkerlocker do anything else consolewritelineend method dosomething definitionpublic void dosomethingobject data do a slow process lock thisworkerlocker thisrunningworkers monitorpulsethisworkerlocker,['c#'] +18484,streaming large file uploads to aspnet mvc for an application i am working on i need to allow the user to upload very large filesie potentially many gigabytesvia our website unfortunately aspnet mvc appears to load the entire request into ram before beginning to service itnot exactly ideal for such an application notably trying to circumvent the issue via code such as the followingif requestmethod post requestcontentlength clientrequestinputstreamlength var rgbbody new byte32768 using var requeststream requestgetrequeststream int cbread while cbread clientrequestinputstreamreadrgbbody 0 rgbbodylength 0 filestreamwritergbbody 0 cbread fails to circumvent the buffertherequestintoram mentality is there an easy way to work around this behavior,['asp.net'] +18489,how to build a visual studio 90 solution from cygwin and get build output i am trying to set up an automated build system on windows using cygwin among other things it needs to be able to build several visual c solutions i have a script which sets up the environment variables needed for devenv and if i type devenv in bash it brings up the visual studio ide no problems so fari am also able to build a solution from cygwins bash prompt by typing devenv mysolutionsln build debugthe problem is that it is not showing me the build output in fact it does not even tell me whether or not the build succeeded the command simply finishes and i get back the prompt then i can go into the output directory and check whether or not the executable was created but for a build system i want to be able to grep for errorswhat am i doing wrong i can see the debug output when i run devenv in the windows shell but not in cygwin where is it being sent and how do i get it back,['c++'] +18490,how can i validate a string to only allow alphanumeric characters in it how can i validate a string using regular expressions to only allow alphanumeric characters in iti do not want to allow for any spaces either,['c#'] +18493,using jslint in notepad i have seen other text editors use extensions to allow syntax checkers such as jslint is this possible with notepad,['javascript'] +18501,extract rgb values from a avframe ffmpeg in c i am currently trying to read in video frames by using ffmpeg the format is pix fmt rgb24 for each frame the rgb values are all combined together in framedata0 where frame is of the type avframe how do i extract the individual r g and b values for each frame this is for processing the video i would think it would work the same way as extracting the rgb values from a bitmap too thanks,['c++'] +18502,how do i wait until the user has finished writing down in a text input to call a function i am designing a web site and i would like to be able to call a function 1 second after the last user input i tried using onkeyup but it waited 1 second after the first keystrokedoes anyone know how would this be possible,"['javascript', 'html']" +18511,ms access library for python is there a library for using ms access database in python the win32 module is not as easy as the mysql library is there a simpler way to use ms access with python,['python'] +18525,how to call a net web service from android i need to call a web service with a url something like from androidplease anyone help me with a full example,"['.net', 'android']" +18538,how do i check whether a given usb device is plugged in our winforms application supports a custom controller using the manufacturers sdk but there is no support to detect whether a device is present or not how do i check whether a given usb device is plugged in,"['c#', '.net']" +18542,adding an identity to an existing column i need to change the primary key of a table to an identity column and there is already a number of rows in table i have got a script to clean up the ids to ensure they are sequential starting at 1 works fine on my test database whats the sql command to alter the column to have an identity property,['sql'] +18549,retrieve single entity framework entities using a linq query or getobjectkey it looks like getobjectkey has the benefit of searching for existing instantiated objects and then the data store however it also seems like you lose some of the strong typing and need to cast your resulting objectgetobjectkeyint customerid 1entitykey key new entitykeymyentitiescustomers customerid customeridcustomer customer contextgetobjectbykeykey as customervs linqint customerid 1customer customer from c in contextcustomers where ccustomerid customerid select cfirstordefaultpersonally i prefer the latter method because of the typing also your dal will be fairly uniform with all of the get methods being queries although that is just a personal preferencewhat do you boys and girls use,"['c#', 'asp.net']" +18555,obtain output files from a msbuild project is it possible to obtain a list all all the output files from a msbuild projectin a simple project i could do something like createitem includeoutputdir output itemnamealloutputs taskparameterincludecreateitembut my projects are part of a larger build and all outputs go to a common location i want to be able to exculde dlls and content that do not belongany ideas,['.net'] +18563,can a ruby method yield as an iterator or return an array depending on context i have an arbitrary method in ruby that yields multiple values so it can be handed to a blockdef arbitrary yield 1 yield 2 yield 3 yield 4endarbitrary x puts x i would like to modify this method so that if there is no block it just returns the values as an array so this construct would work as wellmyarray arbitraryp a 1 2 3 4 5is this possible in ruby,['ruby'] +18567,maintain file permissions when extracting from a zip file using jdk 5 api i am using javautilzip and javautilzipentry to successfully extra a zip files contents to thisk i would like to maintain the file permissions set when extracting on a nix filesystemcan anyone point me to the correct way to do this,['java'] +18573,tsql user defined function overloading i understand that tsql is not object oriented i need to write a set of functions that mimics method overloading in cis function overloading supported in tsql in any way if there is a hack to do this is it recommended,['sql'] +18574,adding hours to javascript date object it amazes me that javascripts date object does not implement an add function of any kindi simply want a function that can do thisvar now datenowvar fourhourslater nowaddhours4function dateprototypeaddhoursh how do i implement this i would simply like some pointers in a directiondo i need to do string parsing can i use settimehow about millisecondslike thisnew datemilliseconds 4360010 4 hrs in msthis seems really hackish though and does it even work,['javascript'] +18584,how can i control ie6jqueryjqueryui memory leaks heres a sample page with a couple datepickers heres the drip result for thatthis page leaks indefinitely in ie6sp1 when i click the refresh button repeatedly ie6sp3 opera 9 chrome2 and ff3 seem to be good the memory goes up and never goes down until i actually close the browser completelyi have also tried using the latest nightly of jquery r6414 and the latest stable ui 172 but it did not make any difference i have tried various things with no success collectgarbage antileak othersi am looking for a solution other than use a different browser1 as i do not have any control over that any help will be greatly appreciatedupdate 1 i added that button event to a loop and this is what happens the sudden drop off is when i terminate ieupdate 2 i filed a bug report fingers crossedupdate 3 this is also on the mailing listupdate 4 this as reported on the mailing list does not work and in fact makes things worsewindowbindunload function hasdatepickerdatepickerdestroy windowunbind it is not enough to just call destroy i am still stranded with this one and getting very close to ripping jquery out of the project i love it i really do but if it is broken i cannot use itupdate 5 starting the bounty another 550 points to one helpful individualupdate 6 some more testing has shown that this leak exists in ie6 and ie6sp1 but has been fixed in ie6sp2 now about the answers i have so farso far all answers have been any one of theseabandon ie6sp0sp1 users or ignorethemdebug jquery and fix the problem myselfi cannot repro the problemi know beggars cannot be choosers but those simply are not answers to my problemi cannot abandon my users they make up 25 of the userbase this is a custom app written for a customer designed to work on ie6 it is not an option to abandon ie6sp0sp1 it is not an option to tell my customers to just deal with it it leaks so fast that after five minutes some of the weaker machines are unusablefurther while i would love to become a js ninja so i can hunt down obscure memory leaks in jquery code granted this is mss fault not jquerys i do not see that happening either finally multiple people have reproduced the problem here and on the mailing list if you cannot repro it you might have ie6sp2 or you might not be refreshing enoughobviously this issue is very important to me hence the 6 revisions bounty etc so i am open to new ideas but please keep in mind that none of those three suggestions will work for methanks to all for your consideration and insights please keep them comingupdate 7 the bounty has ended and keiths answer was autoaccepted by so i am sorry that only half the points were awarded since i did not select the answer myself but i am still really stuck so i think half is fair i am hopeful that the jqueryjqueryui team can fix this problem but i am afraid that i will have to write this off as impossible for now and stop using some or all of jquery thanks to everyone for your help and consideration if someone comes along with a real solution to my problem please post and i will figure out some way to reward you,"['javascript', 'jquery']" +18588,why do i need setuid0 within a setuidroot c program that calls an administrative program with system i had to do a dirty linux hack for somebody so they could start a printer with the cupsenable printername shell command while being a nonroot user i did not want them to be able to use the entirety of the cupsenable syntax as root so i just wrote a c wrapper that sanitizes the input in argv1 and calls systemcupsenable sanitizedprinternamei made the program setuid root but even so cupsenable failed with permission denied then i inserted a setuid0 call before system and lo and behold it workedthisregard the issue of there being a better way to give users control of the printer there probably is a better way what i am interested in are the intricacies of chmod us vs setuid0 vs system why did it behave that way,['c'] +18593,correct way to add external jars libjar to an intellij idea project when creating a new java project in intellij idea the following directories and files are createdprojectnameimlprojectnameiprprojectnameiwssrci want to configure intellij idea to include my dependency jars in libjar to the project what is the correct way to achieve this in intellij idea,['java'] +18594,column width of a datagrid in a windows mobile application i am having problems trying to adjust the width of a column of a datagrid i used the answer posted here but i cannot solve iti am using a list of objects as a datasource in this simple example i have just created a smart device application and just added a datagrid then my code is this one public form1 initializecomponent listprueba lista new listprueba listaaddnew pruebauno dos listaaddnew pruebatres cuatro datagrid1datasource lista datagridtablestyle tablestyle new datagridtablestyle tablestylemappingname listagettypetostring datagridtextboxcolumn tbcname new datagridtextboxcolumn tbcnamewidth 40 tbcnamemappingname uno tbcnameheadertext uno tablestylegridcolumnstylesaddtbcname datagrid1tablestylesclear datagrid1tablestylesaddtablestyle public class prueba public string uno get set public string dos get set public pruebastring uno string dos thisuno uno thisdos dos the width remains the same do you have a clue thank you,['c#'] +18600,iphone sdk 30 inapp email changing navigation bar tint color my app uses the iphone sdk 30s new inapp email featurei want to change the tint color of the email ui to black and make it translucenti tried the following codepickernavigationcontrollernavigationbartintcolor uicolor blackcolorpickernavigationcontrollernavigationbartranslucent yes but it is changing the color of the view that createsmfmailcomposeviewcontroller picker mfmailcomposeviewcontroller alloc initthe compose window rather than the compose window itselfis this atleast possible or should we stick to apple provided blue itself,['iphone'] +18601,how to call a net webservice from android using ksoap2 i have a problem while calling a webservice i have a net web service on the server and i am using ksoap2 ksoap2j2sefull212 in android while running the program i got an runtime exception like orgksoap2serializationsoapprimitive what should i dohere is my codepackage projectsksoap2sampleimport orgksoap2soapenvelopeimport orgksoap2serializationsoapobjectimport orgksoap2serializationsoapserializationenvelopeimport orgksoap2transporthttptransportseimport androidappimport androidosimport androidwidgettextviewpublic class ksoap2sample extends activity called when the activity is first created private static final string soap action private static final string method name helloworld private static final string namespace private static final string url textview tv override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain tvtextviewfindviewbyidridtext1 try soapobject request new soapobjectnamespace method name requestaddpropertyprop1 myprop soapserializationenvelope envelope new soapserializationenvelopesoapenvelopever11 envelopedotnettrue envelopesetoutputsoapobjectrequest httptransportse androidhttptransport new httptransportseurl androidhttptransportcallsoap action envelope object result objectenvelopegetresponse string results string result tvsettext results0 catch exception e tvsettextegetmessage,['android'] +18602,what is wrong with this clone i have written this clone method for when the parent of the employee class is abstract and the clone method in the parent class is abstracti wanted to copy the primitive data type of the employees object with this code instead of copying each primitive data type individually but this code has problem with the line that i call clone method this code is in employee classpublic object clone object obj new objectobject object objclone emphasis herereturn objectthe error is the method clone from the type object is not visiblebut my employee class is in the class hierarchy which can access the protected clone method in the object classthis is my simple employee classpublic class employee extends person implements cloneable private int idpublic employee id 0public void setidint id thisid idpublic int getid return idpublic object clone1 throws clonenotsupportedexception try object obj new objectobject object objclonereturn object catch clonenotsupportedexception ex return null,['java'] +18610,checking if number is even by looking at the last bit are there any other tricks like this one recently i thiscovered that if i need to see if variable is even or odd i could just see if last bit of variable equals 0 this thiscovery when implemented replaced few modulo 2 calculations and thus whole function ran fasterare there any other tricks like this one where working with bits could replace other calculations leading to improved function execution time,['c++'] +18611,javaioioexception invalid keystore format does anyone know how to solve thisi tried many things but none of them workedand when i click more details i get thisat sunsecurityproviderjavakeystoreengineloadunknown sourceatsunsecurityproviderjavakeystorejksengineloadunknown sourceat javasecuritykeystoreloadunknown sourceat comsundeploysecurityrootcertstore1rununknown sourceat javasecurityaccesscontrollerdoprivilegednative methodat comsundeploysecurityrootcertstoreloadcertstoreunknown sourceat comsundeploysecurityrootcertstoreloadunknown sourceat comsundeploysecurityrootcertstoreloadunknown sourceat comsundeploysecurityimmutablecertstoreloadunknown sourceat comsundeploysecuritytrustdeciderisallpermissiongrantedunknown sourceat comsundeploysecuritytrustdeciderisallpermissiongrantedunknown sourceat sunpluginsecuritypluginclassloadergetpermissionsunknown sourceat javasecuritysecureclassloadergetprotectiondomainunknown sourceat javasecuritysecureclassloaderdefineclassunknown sourceat javaneturlclassloaderdefineclassunknown sourceat javaneturlclassloaderaccess0unknown sourceat javaneturlclassloader1rununknown sourceat javasecurityaccesscontrollerdoprivilegednative methodat javaneturlclassloaderfindclassunknown sourceat sunappletappletclassloaderfindclassunknown sourceat javalangclassloaderloadclassunknown sourceat sunappletappletclassloaderloadclassunknown sourceat javalangclassloaderloadclassunknown sourceat sunappletappletclassloaderloadcodeunknown sourceat sunappletappletpanelcreateappletunknown sourceat sunpluginappletviewercreateappletunknown sourceat sunappletappletpanelrunloaderunknown sourceat sunappletappletpanelrununknown sourceat javalangthreadrununknown source,['java'] +18612,problems using getjson i am calling the following url using yql20from20yahoofinancequotes20where20symbol20in2022utgl220a0909formatjsonenvhttp3a2f2fdatatablesorg2falltablesenvcallbackcbfuncthis returns the following in jsoncbfuncquerycount1created20090627t115344zlangenusupdated20090627t115344zurifromyahoofinancequoteswheresymbolin2822utgl29diagnosticspubliclycallabletrueurlexecutiontime468contentexecutiontime634contentexecutiontime351contentfaa2bb2b3b4cc1c3c6c8dd1d2ee1e7e8e9ghjkg1g3g4g5g6ii5j1j3j4j5j6k1k2k4k5ll1l2l3mm2m3m4m5m6m7m8nn4opp1p2p5p6qrr1r2r5r6r7ss1s7t1t7t8vv1v7ww1w4xyexecutiontime357contentselect from csv where urlurl and columnsaskaveragedailyvolumebidaskrealtimebidrealtimebookvaluechangepercentchangechangecommissionchangerealtimeafterhourschangerealtimedividendsharelasttradedatetradedateearningsshareerrorindicationreturnedforsymbolchangedinvalidepsestimatecurrentyearepsestimatenextyearepsestimatenextquarterdayslowdayshighyearlowyearhighholdingsgainpercentannualizedgainholdingsgainholdingsgainpercentrealtimeholdingsgainrealtimemoreinfoorderbookrealtimemarketcapitalizationmarketcaprealtimeebitdachangefromyearlowpercentchangefromyearlowlasttraderealtimewithtimechangepercentrealtimechangefromyearhighpercebtchangefromyearhighlasttradewithtimelasttradepriceonlyhighlimitlowlimitdaysrangedaysrangerealtimefiftydaymovingaveragetwohundreddaymovingaveragechangefromtwohundreddaymovingaveragepercentchangefromtwohundreddaymovingaveragechangefromfiftydaymovingaveragepercentchangefromfiftydaymovingaveragenamenotesopenpreviousclosepricepaidchangeinpercentpricesalespricebookexdividenddateperatiodividendpaydateperatiorealtimepegratiopriceepsestimatecurrentyearpriceepsestimatenextyearsymbolsharesownedshortratiolasttradetimetickertrendoneyrtargetpricevolumeholdingsvalueholdingsvaluerealtimeyearrangedaysvaluechangedaysvaluechangerealtimestockexchangedividendyieldjavascriptinstructionsused66024usertime1537servicetime1810buildversion1949resultsquotesymbolutglask12900averagedailyvolume354500bid12850askrealtime12900bidrealtime12850bookvalue0change percentchange750 619change750commissionnullchangerealtime750afterhourschangerealtimena nadividendshare0lasttradedate6262009tradedatenullearningsshare0errorindicationreturnedforsymbolchangedinvalidnaepsestimatecurrentyear0epsestimatenextyear0epsestimatenextquarter0dayslow12200dayshigh12875yearlow3625yearhigh31975holdingsgainpercent annualizedgainholdingsgainnullholdingsgainpercentrealtimena naholdingsgainrealtimenullmoreinfocredorderbookrealtimenamarketcapitalizationnullmarketcaprealtimenullebitda0changefromyearlow9250percentchangefromyearlow25517lasttraderealtimewithtimena b12875bchangepercentrealtimena 619changefromyearhigh19100percebtchangefromyearhigh5973lasttradewithtimejun 26 b12875blasttradepriceonly12875highlimitnulowlimitnulldaysrange12200 12875daysrangerealtimena nafiftydaymovingaverage125714twohundreddaymovingaverage10063changefromtwohundreddaymovingaverage2812percentchangefromtwohundreddaymovingaverage2794changefromfiftydaymovingaverage3036percentchangefromfiftydaymovingaverage242nameunite groupnotesopen12200previousclose12125pricepaidnullchangeinpercent619pricesalesnullpricebooknullexdividenddate14apr04perationulldividendpaydate13may05peratiorealtimenullpegrationullpriceepsestimatecurrentyearnullpriceepsestimatenextyearnullsymbolutglsharesownednullshortrationulasttradetime1135amtickertrendnbspnbsponeyrtargetpricenullvolume254927holdingsvaluenullholdingsvaluerealtimenullyearrange3625 31975daysvaluechange 619daysvaluechangerealtimena nastockexchangelondondividendyieldnullpercentchange619but i am struggling to use the data i am a newbie with jquery and json usinggetjson20from20yahoofinancequotes20where20symbol20in2022utgl220a0909formatjsonenvhttp3a2f2fdatatablesorg2falltablesenvcallbackcbfunc functiondatafrom this example just flashes a restricted url erroranybody help i simply was to parse the data and print to screen thanks in advance,"['javascript', 'jquery']" +18618,file put contents with array i am using file put contentsfile data function for putting contents in file because these files are created on fly with name of sessions data is an multidimensional array when i am echoing array it prints out fine but in file no contents get recorded except the word arraywhat should i do or is there any other function which automatically creates the file and records the data arraythank you,['php'] +18632,php apc what happens when apc cache is full what happens when you try to add a variable into apc and the apc cache is full does it automatically remove least used variable from the cache,['php'] +18635,css background image positioning negative position i am trying to add an icon which sits on top of the border splitting it in halfhere is what i have so farhtmlhead meta httpequivcontenttype contenttexthtml charsetiso88591 titleuntitled documenttitle style typetextcss body backgroundcolor26140c box width 800px margin 0 auto margintop 40px padding 10px border 3px solid a5927c backgroundcolor 3d2216 backgroundimage urlcontentsimgicon neutralpng backgroundrepeat norepeat backgroundposition10px 20px styleheadbody div classbox h1this is a testh1 divbodyinstead of image being over the border like i was hoping its under it,"['html', 'css']" +18650,is it possible to specify formatting options for to yaml in ruby the coderequire yamlputs yamlloadis something values yes noto yamlproduces is something values yes nowhile this is a correct yaml it just looks ugly when you have a hash of arrays is there a way for me to get to yaml to produce the inline array version of the yaml an options hash can be passed to to yaml but how do you use itedit 0 thanks pozsar balazs but as of ruby 187 20090408 patchlevel 160 the options hash does not work as advertised irbirbmain0010 require yaml trueirbmain0020 puts crispin glover to yaml indent 4 useheader true useversion true crispin glover nil,['ruby'] +18667,how to tell a variable is iterable but not a string i have a function that take an argument which can be either a single item or a double itemdef iterablearg if arg is an iterable print yes else print noso that iterable ff yes iterable ff yes iterableffnothe problem is that string is technically iterable so i cannot just catch the valueerror when trying arg1 i do not want to use isinstance because that is not good practice or so i am told,['python'] +18670,how to sanitze user input in php before mailing i have a simple php mailer script that takes values from a form submitted via post and mails them to mephpto name postnamemessage postmessageemail postemailbody person name submitted a message messagesubject a message has been submittedheaders from emailmailto subject body headersheaderlocation how can i sanitize the input,['php'] +18671,add pear packages to subversion repository i am working on a project thatll use pear packages because you never know what version of the pear package will be installed on your hosting provider and especially because i require a patch to have been applied to one of the packages i would like to put the pear source for my project right into svn so other developers can immediately have the dependenciesbut everything related to pear seems to have absolute directories running pear configcreate pearconf to set up a new pear directory even fails with the error messageroot directory must be an absolute pathi checked out the pear config files on some other servers and they too seem to have absolute pathswhenever a developer checks this out to his own machine or we export it all to a server we do not know what the absolute path will beis there any way to set this up,['php'] +18677,deactivate focusvisualstyle globally i want to globally deactivate the focus rectangles in my wpf application for single controls that can be done viastyle targettypebutton setter propertyfocusvisualstyle valuexnull stylebut how to apply it to all controls in my application when applying to frameworkelement nothing happens what i need would be something like apply to class x and all derived classesthanks in advancestefan,['c#'] +18678,data access layer design patterns i have to design a data access layer with net that probably will use more than one database management system mysql and sql server with the same relational designbasically it has to be simple to switch from one database to another so i would like you to recommend me some websites or books that has been useful for you with common design patterns or information in general to implement this kind of data access layerthank you,['.net'] +18682,using ajax is it better to generate aditional markup in the server or the client side which is better in ajax request response with ready html or response with just data and write html using javascript and this javascript will use a predefined html template to put the coming data inside and show on the pagecreating the html on the server and send to the page will decrease the client side js code but will increase the response sizesending the data to the client side will decrease the response size but will increase the js codewhich is better and most used,"['asp.net', 'javascript']" +18689,determining which code line threw the exception in dotnet a line throws an exception and is caught how can i figure out which line in which file threw the exception seems relatively straightforward but i cannot figure it out,['c#'] +18692,how to thisplay a label next to a marker for google maps i would like to thisplay a text label next to the markers on google maps i have used virtual earth before and i am just starting to use google maps i tried setting the title property but that only changes the roll over text is there a way to thisplay a small line of text underneath a marker that will stay there as the user zooms pans and uses the mapthanks in advance,['javascript'] +18693,java swing guis on mac os x have you ever attempted using swing only to end up changing courses because it just could not do what you wantedi am pretty new to swing having only used it for school projects over 5 years ago but it seems swing has come a long way in providing a more native look and feel so much so that i am considering using it to develop the gui for an app on mac os x before i do though i wanted to see if anyone has run into any showstopper issues that prevented them from using swingjust off the top of my head some possibilitiesproblems developing custom components that looked rightbad interactions with native applications and widgetsperformance issues unresponsiveness repaint problemsinability to mimic native behaviors like dock interaction,['java'] +18695,how to use sql user defined functions in net i created a scalar function in the dbset ansi nulls ongoset quoted identifier ongoalter function dbofn getuserid username username varchar32 returns intas begin declare userid int select userid userid from user where username username return userid endnow i want to run it within my net c or vbnet codei use entity framework i tried to map it with function mapping and i did not successi do not care to do it with simple dbcommand the problem is that i get no results the function exists in the entities classpublic int getuseridbyusernamestring username entityconnection connection entityconnectionconnection dbcommand com connectionstoreconnectioncreatecommand comcommandtext fn getuserid username comcommandtype commandtypestoredprocedure comparametersaddnew sqlparameterusername username if comconnectionstate connectionstateclosed comconnectionopen try var result comexecutescalar always null catch exception e return resultis there any solutionposts in either c or vbnet will be welcommed,"['.net', 'sql']" +18697,how to autostart an android application i am not sure how to autostart an android application after the android emulator completes its booting does anyone have any code snippets that will help me,['android'] +18702,what does mean in collection what meaning has e on the code collectione,['java'] +18707,how to determine controller class given url string within the scope of a rails controller or a viewhow can i query the rails routing mechanism to turn a relative url string eg controllernameactionwhatever into the controller class that would be responsible for handling that requesti want to do something like thiscontrollerclass somemethodcontrollernameactionwhateverwhere contorllerclass is an instance of classi do not want to make any assumptions about a routing convention eg that the controllername in the above example is always the name of the controller because it is not,['ruby-on-rails'] +18713,bluetooth in c which stack which sdk weve got an application which needs to be able to use bluetooth for the following requirementsreceive files from bluetooth devices up to 2 devices at the same timethisplay all bluetooth devices in rangesend files to bluetooth devicesscan for bluetooth devices and transfer files at the same timewere running on windows xpi have done some looking around and there seems to be 3 main stacksbluesoleilon the bluesoleil website in their sdk section it seems to mention only 1 connection is supported which is obviously no goodwindowsonly seems to support 1 bluetooth dongle which will probably mean we cannot meet all our requirementswidcommexpensive and potentially overkill more complex api thoughtsin terms of sdk for c was looking at franson bluetools anyone used this apithanks,"['c#', '.net']" +18749,can iphone web apps get gps position is there an easy way to design a website to facilitate an iphone user providing gps coordinates to the site i am wondering if there might be a naming convention for form fields for example to let the user input in an automated wayi am considering building a location based website and would like to tailor it for iphone and other mobile users i realize an iphone app could do this but i am not equipped to create one,['iphone'] +18756,true isometric projection with opengl i am a newbie in opengl programming with c and not very good at mathematics is there a simple way to have isometric projectioni mean the true isometric projection not the general orthogonal projectionisometric projection happens only when projections of unit x y and z vectors are equally long and angles between them are exactly 120 degreescode snippets are highly appreciated,['c++'] +18760,clickonce error missing files need to get missing filename my clickonce app gives an error for a user cannot download the application the application is missing required files contact the application vendor or your system administrator for assistancehow can i pinpoit which file is missing do i manually need to put files on the publishing serveri thought when i click on the prerequisities and set the option to download the prerequisites from the component vendors web site and set to include components clickonce would include all of them looks like i am missing something how do i know what it is manually going through the manifest is going to be time consuming,['.net'] +18765,thistributed lock service which thistributed lock service would you userequirements area mutual exclusion lock that can be seen from different processesmachineslockrelease semanticsautomatic lock release after a certain timeout if lock holder dies it will automatically be freed after x secondsjava implementationnice to have net implementationif it is free deadlock detection mitigationeasy deployment see note belowi am not interested in answers like it can be done over a database or it can be done over javaspaces i know i am interested in a ready outofthebox proven implementation,['java'] +18766,default value to a parameter while passing by reference in c is it possible to give a default value to a parameter of a function while we are passing the parameter by reference in cfor example when i try to declare a function likevirtual const ulong writeulong state 0 bool sequence truewhen i do this it gives an errorerror c2440 default argument cannot convert from const int to unsigned long a reference that is not to const cannot be bound to a nonlvalue,['c++'] +18767,facebook offline access stepbystep update facebook offline access permission is being deprecated please refer to the official documentation for more information youll have till may 1 2012 at which date this setting will be thisabled refer to the developer roadmap for more infoafter searching literally 1 day on facebook and google for an uptodate and working way to do something seemingly simplei am looking for a stepbystep explanation to get offline access for a user for a facebook app and then using this session key to retrieve offline not within a browser friends profile datapreferrably doing this in the fb java apithanksand yes i did check the facebook wikiupdate anyone this keyapikeyv10ext permoffline accessgives me offline access however how to retrieve the session keywhy cannot facebook just do simple documentation i mean there are like 600 people working therethe seemingly same questiongetting offline access to work with facebookdoes not answer how to retrieve the session keyedit i am still stuck with that i guess nobody really tried such a batch access out yet,['java'] +18778,changing variable names with python for loops i was just wondering if anyone knew of a way to change variable names based off of a for loop for something like thisfor i in range3 groupiselfgetgroupselected headeriso that the names of the variables change to accomodate the data thankssam,['python'] +18786,invalidoperationexception object is currently in use elsewhere red cross i have a c desktop application in which one thread that i create continously gets an image from a sourceit is a digital camera actually and puts it on a panelpanelimage img in the guiwhich must be another thread as it is the codebehind of a controlthe application works but on some machines i get the following error at random time intervalsunpredictable exception text systeminvalidoperationexception the object is currently in use elsewhere then the panel turns into a red cross red x i think this is the invalid picture icon that is editable from the properties the application keeps working but the panel is never updatedfrom what i can tell this error comes from the controls onpaint event where i draw something else on the picturei tried using a lock there but no luck the way i call the function that puts the image on the panel is as followsif thisreceivedframe null delegate clients thisreceivedframegetinvocationlist foreach delegate del in clients try deldynamicinvokenew object this new streameventargsframe catch this is the delegatepublic delegate void receivedframeeventhandlerobject sender streameventargs e public event receivedframeeventhandler receivedframeand this is how the function inside the control codebehind registers to itcamerareceivedframe new camerareceivedframeeventhandlercamera receivedframei also tried delmethodinvokedeltarget new object this new streameventargsb instead of deldynamicinvokenew object this new streameventargsframe but no luckdoes anyone know how i could fix this error or at least catch the error somehow and make the thread put the images on the panel once again,['c#'] +18796,why is nonbreaking space not a whitespace character in java while searching for a proper way to trim nonbreaking space from parsed html i have first stumbled on javas spartan definition of stringtrim which is at least properly documented i wanted to avoid explicitly listing characters eligible for trimming so i assumed that using unicode backed methods on character class would do the job for me that is when i thiscovered that characteriswhitespacechar explicitly excludes nonbreaking spacesit is a unicode space character space separator line separator or paragraph separator but is not also a nonbreaking space u00a0 u2007 u202f why is that the implementation of corresponding net equivalent is less thiscriminating,['java'] +18799,regex match a pattern before a character i am currently building a toy assembler in c going through the elements of computing systems booki need to match a very simple pattern i thought this would be a good time to learn some regex but i am strugglingin the following examples i would just like to match the letters before the madmmdaadadmamdai have come up with the followingaz13however this also matches the which i do not wanti also triedaz13but i still have the same problem it a matches the sign as welli am using this site to test my regexesany help would be really appreciatedthank you in advance,['c#'] +18801,what to do when bit mask flags enum gets too large i have a very large set of permissions in my application that i represent with a flags enumeration it is quickly approaching the practical upper bound of the long data type and i am forced to come up with a strategy to transition to a different structure soon now i could break this list down into smaller pieces however this is already just a subset of the overall permissions for our application based on our applications layout we use this thistinction extensively for thisplay purposes when managing permissions and i would rather not have to revisit that code at this time if i can avoid ithas anybody else run into this issue how did you get past it general examples are fine but i am most interested in a c specific example if there are any language specific tricks that i can employ to get the job donemay not be neccessary but here is the list of permissions currently defined for the portion of the app i am dealing withsubgroup webagentflagspublic enum webagentpermission long descriptionattributeview rule group viewrulegroup 1 descriptionattributeadd rule group addrulegroup 2 descriptionattributeedit rule group editrulegroup 4 descriptionattributedelete rule group deleterulegroup 8 descriptionattributeview rule viewrule 16 descriptionattributeadd rule addrule 32 descriptionattributeedit rule editrule 64 descriptionattributedelete rule deleterule 128 descriptionattributeview location viewlocation 256 descriptionattributeadd location addlocation 512 descriptionattributeedit location editlocation 1024 descriptionattributedelete location deletelocation 2048 descriptionattributeview volume statistics viewvolumestatistics 4096 descriptionattributeedit volume statistics editvolumestatistics 8192 descriptionattributeupload volume statistics uploadvolumestatistics 16384 descriptionattributeview role viewrole 32768 descriptionattributeadd role addrole 65536 descriptionattributeedit role editrole 131072 descriptionattributedelete role deleterole 262144 descriptionattributeview user viewuser 524288 descriptionattributeadd user adduser 1048576 descriptionattributeedit user edituser 2097152 descriptionattributedelete user deleteuser 4194304 descriptionattributeassign permissions to user assignpermissionstouser 8388608 descriptionattributechange user password changeuserpassword 167216 descriptionattributeview audit logs viewauditlogs 33554432 descriptionattributeview team viewteam 67108864 descriptionattributeadd team addteam 134217728 descriptionattributeedit team editteam 268435456 descriptionattributedelete team deleteteam 536870912 descriptionattributeview web agent reports viewwebagentreports 1073741824 descriptionattributeview all locations viewalocations 2147483648 descriptionattributeaccess to my search accesstomysearch 4294967296 descriptionattributeaccess to pespective search accesstopespectivesearch 8589934592 descriptionattributeadd pespective search addpespectivesearch 17179869184 descriptionattributeedit pespective search editpespectivesearch 34359738368 descriptionattributedelete pespective search deletepespectivesearch 68719476736 descriptionattributeaccess to search accesstosearch 137438953472 descriptionattributeview form roles viewformrole 274877906944 descriptionattributeadd edit form roles addformrole 5497558138 descriptionattributedelete userformrolesdifferencemasks deleteformrole 10995116276 descriptionattributeexport locations exportlocations 2199023252 descriptionattributeimport locations importlocations 43980465104 descriptionattributemanage location levels managelocationlevels 87960930208 descriptionattributeview job title viewjobtitle 175921860416 descriptionattributeadd job title addjobtitle 351843720832 descriptionattributeedit job title editjobtitle 70368744177664 descriptionattributedelete job title deletejobtitle 140737488355328 descriptionattributeview dictionary manager viewdictionarymanager 281474976710656 descriptionattributeadd dictionary manager adictionarymanager 562949953421312 descriptionattributeedit dictionary manager editdictionarymanager 11258906842624 descriptionattributedelete dictionary manager deletedictionarymanager 2251799813685248 descriptionattributeview choice manager viewchoicemanager 4503599627370496 descriptionattributeadd choice manager addchoicemanager 9007199254740992 descriptionattributeedit chioce manager editchoicemanager 18014398509481984 descriptionattributedelete choice manager deletechoicemanager 36028797018963968 descriptionattributeimport export choices 57 importexportchoices 72057594037927936,['c#'] +18805,in a csproj file what is for how isnone includecfoobar different fromcontent includecfoobar,['c#'] +18817,jquery click on anchor element forces scroll to top link text1i am running in to a problem using jquery and a click event attached to an anchor element 1 this so question seems to be a duplicate and the accepted answer does not seem to solve the problem sorry if this is bad so etiquette in my ready function i havejqueryid of anchorclickfunctionevent start function when any update link is clickedfunction that does ajaxand my anchor looks like thisa href idid of anchor link text abut when the link is clicked the ajax function is performed as desired but the browser scrolls to the top of the page not goodi have tried addingeventpreventdefaultbefore calling my function that does the ajax but that does not help what am i missingclarificationi have used every combination of return falseeventpreventdefault eventstoppropagationbefore and after my call to my js ajax function it still scrolls to the top,['jquery'] +18824,php zip files on the fly whats the easiest way to zip say 2 files from a folder on the server and force download without saving the zip to the server zip new ziparchive the string file1 is the name were assigning the file in the archivezipaddfilefile get contentsfilepath1 file1 file 1 that you want compressedzipaddfilefile get contentsfilepath2 file2 file 2 that you want compressedzipaddfilefile get contentsfilepath3 file3 file 3 that you want compressedecho zipfile this sends the compressed archive to the output buffer instead of writing it to a filecan someone verifyi have a folder with test1doc test2doc and test3docwith the above example file1 file2 and file3 might just be test1doc etcdo i have to do anything with filepath1 is that the folder directory that holds the 3 docssorry for my basic question,['php'] +18834,how to use nsenumerator with nsmutabledictionary how do i use nsenumerator with nsmutabledictionary to print out all the keys and valuesthanks,['iphone'] +18835,c compilation time for large projects compared to c i often hear people praise the compilation speed of c so far i have only made a few tiny applications and indeed i noticed that compilation was very fast however i was wondering if this still holds for large applications do big c projects compile faster than c projects of a similar size,['c#'] +18836,wpf xaml stringformat datetime output in wrong culture i am having some trouble with the output of a datetime value my computers current culture is set to deat austriathe following codestring s1 datetimenowtostringdstring s2 stringformat0d datetimenowresults in s1 and s2 both having the correct value of 30062009but when using the same format in xaml textblock textbinding sourcexstatic sysdatetimenow stringformatdthe output is 6302009 it seems the xaml stringformat ignores the current culture settings this happens on both vista and xpi do not want to specify a custom format because the output should be formatted in the users preferred culture settinganybody with the same problem is this a bug in wpf,['c#'] +18851,debug c dll in c i have a dll from c and i want to debug it in c but i do not know how towhen i compiled the c project visual studio asked me to execute an exei supposed that i had to create a project to execute the dllbut i am lost how could i debug it,"['c#', 'c++']" +18854,map implementation with duplicate keys i want to have map with duplicate keys i know there are many map implementationseclipse shows me about 50 so i bet there must be one that allows this i know its easy to write your own map that does this but i would rather use some existing solution maybe something in commonscollections or googlecollections,['java'] +18859,how to resolve server error in application error i am trying to deploy an aspnet application in our server while i am receiving the following errorserver error in application configuration error description an error occurred during the processing of a configuration file required to service this request please review the specific error details below and modify your configuration file appropriately parser error message it is an error to use a section registered as allowdefinitionmachinetoapplication beyond application level this error can be caused by a virtual directory not being configured as an application in iissource error line 63 aspnet to identify an incoming user line 64 line 65 authentication modewindowsline 66 forms loginurlscruilogin1aspxline 67 authenticationsource file dbarclayspayamentmanagementsystemscruiwebconfig line 65what is the reason and how to resolve itplease help,['asp.net'] +18870,best way to initialize an entity framework context when initialize an entity framework context one is to initialize at class level such aspublic class entitycontactmanagerrepository contactmanagermodelsicontactmanagerrepository private contactmanagerdbentities entities new contactmanagerdbentities contact methods public contact getcontactint id return from c in entitiescontactsetincludegroup where cid id select cfirstordefault the other way is to initialize at the method levelpublic class entitycontactmanagerrepository contactmanagermodelsicontactmanagerrepository contact methods public contact getcontactint id using var entities new contactmanagerdbentities return from c in entitiescontactsetincludegroup where cid id select cfirstordefault from an adonet background i prefer the later oneinitialize in method but the first one is from the example developed by stephen walthe or another question does it matter at all,['c#'] +18880,is it bad to think in linq when the skill is not transferrable outside c i use linq in my code all the time i have gotten to the point where it just seems so natural to group order an organize a bunch of objects using the linq syntax that i struggle to think how i would do the same things without iti had never delved into the sqlesque world before this but i imagine many people who learned even the normal sql syntax suddenly felt constricted by most normal programming languages abilities to wrangle complex object hierarchiesam i painting myself into a corner becoming reliant on linq to do my more complex tasks it just feels so much more expressive than if i wrote plain c codeis becoming dependent on the linq syntax in my daytoday programming going to hurt me in the long run if i end up switching languages or frameworks where something like it is not available,['c#'] +18881,design patterns used in the net framework one way to increase your understanding of design patterns is to thiscover how patterns are used in the net frameworkhave you found any examples of design patterns in the net framework in your answer please give a short description of the pattern and example of how it is used in the frameworkexample answerthe strategy design pattern decouples an algorithm from the class that uses it by encapsulating the algorithm into a separate class this allows for switching of algorithmsthe sort method of the list class is an example of the strategy patternpublic void sorticomparert comparerby accepting an icomparer interface users of the class can switch the sorting algorithm at runtime,['.net'] +18891,iphone corrupt jpeg data for image received over http i am getting an image over http using nsurlconnection as follows nsmutabledata receiveddata voidgetimage selfreceiveddata nsmutabledata alloc init nsurlconnection theconnection create connection voidconnectionnsurlconnection connection didreceivedatansdata data receiveddata appenddatadatavoidconnectiondidfinishloadingnsurlconnection connection connection release uiimage theimage uiimage imagewithdatareceiveddatausually it works just fine but sometimes i am seeing this get logged corrupt jpeg data premature end of data segment at this point the image does not completely render i will see maybe 75 of it and then the lower right hand corner is a grey boxany ideas on how to approach fixing this am i constructing my image improperly,['iphone'] +18899,superinterface in java what is superinterface is java what is the purpose of superinterface,['java'] +18902,whats the main difference between java se and java ee whats the main difference between java se and java ee,['java'] +18905,performance impact of changing to generic interfaces i work on applications developed in cnet with visual studio very often resharper in the prototypes of my methods advises me to replace the type of my input parameters with more generic ones for instance list with ienumerable if i only use the list with a foreach in the body of my method i can understand why it looks smarter to write that but i am quite concerned with the performance i fear that the performance of my apps will decrease if i listen to resharpercan someone explain to me precisely more or less whats happening behind the scenes ie in the clr when i writepublic void mymethodienumerablestring list foreach string s in list consolewritelines static void main liststring list new liststringnew string a b c mymethodlistand what is the difference withpublic void mymethodliststring list foreach string s in list consolewritelines static void main liststring list new liststringnew string a b c mymethodlist,"['c#', '.net']" +18906,in rails thisplay time between two dates in english in a rails project i want to find the difference between two dates and then thisplay it in natural language something like date1 date2to natural language 3 years 2 months 1 week 6 daysbasically this for ruby google and the rails api have not turned up anything i have found some things that will give you the difference in one unit ie how many weeks between two dates but not something that will accurately calculate years months weeks days all together,"['ruby-on-rails', 'ruby']" +18920,using action as an argument in c mimicking a function pointer i need to write a delegate function that can wrap some whiletrycatch code around a basic udp call to verify the linki made it work for func for a function that has no arguments but i cannot make it work for action which has an argument but no return i cannot seem to pass in the argument in a logical way without the compiler complainingam i going about this all wrong i am new to c and i am essentially trying to mimick the idea of a function pointer should i not be overloading this function i know you cannot overload delegates i assume that is why func and action existthis worksprotected tresult udpcommandtresultfunctresult command tresult retvalue defaulttresult while linkdownfail try retvalue command break catch linkstatecallbackip getlinkstatus if linkdownfail throw new linkdownexception threadsleep100 return retvalue but this does notprotected void udpcommandtactiont commandt value whilelinkdownfail try commandvalue break catch linkstatecallbackip getlinkstatus if linkdownfail throw new linkdownexception threadsleep100 return calling convention for one that worksudpcommanduintsomeudpcommand,['c#'] +18921,preventing an aspnet session timeout when using silverlight i am writing a program which has both an aspnet configuration system and a silverlight application most users will remain on the silverlight page and not visit the aspnet site except for logging in etcthe problem is i need the session to remain active for authentication purposes but the session will timeout even if the user is using the features of the silverlight appany ideas,"['c#', 'asp.net']" +18925,gwt html file with css when i am creating new project with gwt plug in it creates a skeleton project for me in html file there is a comment saying consider inlining css to reduce the number of requested fileswhy would i consider using inline css i tough having css in separate file not inline reduces size of my file is not it true,['css'] +18928,how to use long id in rails applications how can i change the default type for activerecords ids int is not long enough i would prefer long i was surprised that there is no long for the migrations does one just use some decimal,['ruby-on-rails'] +18940,problem with converting int to string in linq to entities var items from c in contacts select new listitem value ccontactid cannot implicitly convert type int contactid to string value text cname var items from c in contacts select new listitem value ccontactidtostring throws exception tostring is not supported in linq to entities text cname is there anyway i can achieve thisnote that in vbnet there is no problem use the first snippet it works just great vb is flexible im unable to get used to cs strictness,"['c#', 'asp.net']" +18943,create an assoc array with equal keys and values from a regular array i have an array that looks likenumbers arrayfirst second thirdi want to have a function that will take this array as input and return an that would look likearrayfirst firstsecond secondthird thirdi wonder if it is possible to use array walk recursive or something similar,['php'] +18944,outlook interop mail formatting i have an application written in c that uses outlook interop to open a new mail message prefilled with details the user can edit before manually sending itvar newmail outlookmailitemoutlookapplicationcreateitem outlookolitemtypeolmailitemnewmailto newmailsubject examplenewmailbodyformat outlookolbodyformatolformathtmlnewmailhtmlbody pdear exampleppexample examplepnewmailthisplayfalsewhen the same user creates a new message manually the font is set to calibri or whichever font the user has set as their default the problem is that the text in the automatic email appears in times new roman font which we do not wantif i view source of one of the delivered emails i can see that outlook has explicitly set the font in the email source automatedpmsonormal limsonormal divmsonormal margin0cm marginbottom01pt fontsize120pt fontfamilytimes new roman manualpmsonormal limsonormal divmsonormal margin0cm marginbottom01pt fontsize110pt fontfamilycalibrisansserifwhy are the formats different and how can i get the automated email to use the users default settings i am using version 11 of the interop assemblies as there is a mix of outlook 2003 and 2007 installed,['c#'] +18955,translating perl to python i found this perl script while migrating my sqlite database to mysqli was wondering since i do not know perl how could one rewrite this in pythonbonus points for the shortest code answer edit sorry i meant shortest code not strictly shortest answer usrbinperlwhile line if line begin transaction line commit line sqlite sequence line create unique index if line create table az name 1 sub 2 sub sg line drop table if exists namencreate table if not exists namesubn elsif line insert into az line insert into 12n line sg line sg else line sg line st1this is true2g line sthis is true1g line sf1this is false2g line sthis is false0g line sautoincrementauto incrementg print line some additional code was necessary to successfully migrate the sqlite database handles one line create table statements foreign keys fixes a bug in the original program that converted empty fields to i posted the code on the migrating my sqlite database to mysql question,['python'] +18957,my productivity is decreasing as the project becomes larger how to increase productivity as size of project increases i initially started off with a small project editing php files and such in notepad it used to be easy to think of a feature and add it on as a separate file onto the project as the project became larger my productivity began to decrease because i could not remember all of the functions i made and where they were stored etc then i added an ide phped and svn and then noticed a large boost in productivity i find myself slowing down in productivity again because everything is becoming too complex againthe project has gone from about 20 or so files 100 files and is becoming difficult to manage all in my head even using an idei am wondering if people have advice on what i can do to increase productivity again what is the next level if there is oneany software tools or tips on how to approach program designmake things simpler to visualize at least i know there is no silver bullet but any ideas would be helpfulfor example do you guys use certain tools to get through the day besides an idesvn also do you write code in a certain way so this would not be a problem in the future specifics pleasethanksthanks for everyones input everyone has such good advice,['php'] +18960,c modifying structs in a list short question how can i modify individual items in a list or more precisely members of a struct stored in a listfull explanationfirst the struct definitions used belowpublic struct iteminfo strings chars boring public string namestr you get the idea nothing fancy public string subnum btw this is the element i am trying to sort onpublic struct slotinfo public char catid public string sortname public bitmap mainicon public ilistiteminfo subitemspublic struct catinfo public char catid public string catdesc public ilistslotinfo items public int numitemscatinfo gallcats new catinfo31gallcats is populated on load and so on down the line as the program runsthe issue arises when i want to sort the iteminfo objects in the subitems arrayi am using linq to do this because there does not seem to be any other reasonable way to sort lists of a nonbuiltin typeso heres what i haveforeach slotinfo sinf in gallcatscitems var sortedsubitems from iteminfo iinf in sinfsubitems orderby iinfsubnum ascending select iinf ilistiteminfo sortedsubtemp new listiteminfo foreach iteminfo iinf in sortedsubitems sortedsubtempaddiinf sinfsubitemsclear sinfsubitems sortedsubtemp error see belowthe error is cannot modify members of sinf because it is a foreach iteration variablea this restriction makes no sense is not that a primary use of the foreach constructb also out of spite what does clear do if not modify the list btw the list does get cleared according to the debugger if i remove the last line and run itso i tried to take a different approach and see if it worked using a regular for loop apparently this is only allowable because gallcatscitems is actually an ilist i do not think it will allow you to index a regular list this wayfor int s 0 s gallcatscitemscount s var sortedsubitems from iteminfo iinf in gallcatscitemsubitems orderby iinfsubnum ascending select iinf ilistiteminfo sortedsubtemp new listiteminfo foreach iteminfo iinf in sortedsubitems sortedsubtempaddiinf note the following two lines were incorrect in the original post gallcatscitemsubitemsclear gallcatscitemsubitems sortedsubtemp error see belowthis time the error is cannot modify the return value of systemcollectionsgenericilistthisint because it is not a variable ugh what is it if not a variable and when did it become a return valuei know there has to be a correct way to do this i am coming to this from a c background and i know i could do it in c albeit with a good bit of manual memory management i searched around and it seems that arraylist has gone out of fashion in favor of generic types i am using 30 and i cannot use an array since the size needs to be dynamic,['c#'] +18961,what are some interesting features of the everyblockcom source code the source code behind everyblockcom a major djangopowered website founded by adrian holovaty one of the cobenevolent dictators for life of the django framework was recently opensourced the source is available as tarballs and on githubthis large body of code from an originator of django should have some interesting features patterns tricks or techniques what is your favorite,['python'] +18967,use types of same name namespace in 2 net assemblies out of curiosity i have created 2 assemblies which both have a class class1 with the exact same namespace library1 i then create another client referencing those 2 assemblies and try to create an instance of class1 the compiler not surprisingly gives me a compileerror about the ambiguous reference is there any way to explicitly specify the type in the assembly i want to use to avoid the ambiguitynote i know this rarely if ever at all happens in practice it is just a question out of curiosity about language feature,"['c#', '.net']" +18969,sse2 option in visual c x64 i have added x64 configuration to my c project to compile 64bit version of my app everything looks fine but compiler gives the following warningcl command line warning d9002 ignoring unknown option archsse2is there sse2 optimization really not available for 64bit projects,['c++'] +18979,identifying last loop when using for each i want to do something different with the last loop iteration when performing foreach on an object i am using ruby but the same goes for c java etc list abc listeachi puts looping i if not last loop iteration puts last one i if last loop iteration the output desired is equivalent to looping a looping b last one cthe obvious workaround is to migrate the code to a for loop using for i in 1listlength but the for each solution feels more graceful what is the most graceful way to code a special case during a loop can it be done with foreach,"['c#', 'java', 'ruby']" +18985,javascript regex multiline flag does not work i wrote a regex to fetch string from html but it seems the multiline flag does not workthis is my pattern and i want to get the text in h1 tagvar pattern div classboxcontent5h1h1mim htmlsearchpatternreturn m1i created a string to test it when the string contains n the result is always null if i remove all the n it gave me the right result no matter with or without m flagwhats wrong with my regex,['javascript'] +18989,is there an easy way to open a uri and get whatever it points to c i have a uri object being passed to a constructor of my class i want to open the file the uri points to whether it is local network http whatever and read the contents into a string is there an easy way of doing this or do i have to try to work off things like uriisfile to figure out how to try to open it,['c#'] +18998,winforms progress bar does not update c in my program c winforms i have progress bar listview through one method i am performing some operations then updating data in listview the no of records added is the value i am setting for progressbarvalue property what i want here is according to value of progress bar it should show its progress however the progress bar is not getting updated only at the end of method execution progress bar shows entire progress ie 100 can someone help me in this regardthanksamit,['c#'] +19001,can i pass parameters by reference in java i would like semantics similar to cs ref keyword,"['c#', 'java']" +19024,sprites vs image slicing i do not have much experience with the sprite approach to images anyone care to share some proscons of sprites vs oldschool slices,"['html', 'css']" +19027,net equivalent for getlastinputinfo is there a net equivalent to the windows getlastinputinfo apii know it is possible to pinvoke the api but i am looking for a method or technique that is already built into the net framework,"['c#', '.net']" +19029,how to rollback a transaction in entity framework string userstoadd new string asd asdert gasdff6 using entities context new entities foreach string user in userstoadd contextaddtousersnew user name user try contextsavechanges exception thrown user gasdff6 already exist catch exception e roll back all changes including the two previous users or maybe this is done automatically meaning that if error occurs committing changes are canceled for all the changesis it,['c#'] +19041,can i have multiple security contexts with spring security i have one security context definition that uses preauthenticatedprocessingfilterentrypoint for the flex part of my application how can i have another definition that will use standard form login with html forms for another part of my application heres what i currently have xml version10 encodingutf8beansbeans xmlns xmlnsbeans xmlnsxsi xsischemalocation http autoconfigtrue accessdeniedpageadminaccessdenied intercepturl patternadminlogin filtersnone intercepturl patternadminaccessdenied filtersnone intercepturl patternadmin accessrole admin formlogin loginpageadminlogin authenticationfailureurladminloginlogin error1 defaulttargeturladminindex loginprocessingurladminloginprocess logout logoutsuccessurladminlogin httpglobalmethodsecurity jsr250annotationsenabled beansbean idpreauthenticatedentrypoint classorgspringframeworksecurityuipreauthpreauthenticatedprocessingfilterentrypoint beansbean beansbean iduseraccountmanager classcommycompservicemanagersjpauseraccountjpamanager beansbean iduserservice classcommycompauthdefaultuserdetailsservice beansbean iddefaultpasswordencoder classcommycompauthdefaultpasswordencoder authenticationprovider userservicerefuserservice passwordencoder refdefaultpasswordencoder authenticationproviderbeansbeanswhat i would like to do is use another authentication provider for the urls that are in the admin site the one i currently have is for the flex application so i want the security for the admin urls to use another userdetailsservice bean,['java'] +19045,how can i write custom exceptions how can i create a new exception different from the premade typespublic class invalidbankfeeamountexception extends exception public invalidbankfeeamountexceptionstring message supermessage it will show the warning for the invalidbankfeeamountexception which is written in the first line,['java'] +19049,aspnet mvc routing with a controller named propertiescontroller i am having a tricky issue bear with me as i am new to mvc with trying to use a controller and a route subsequently with the name propertiescontrolleri believe this is because there is a directory which i cannot really remove called properties in my solution is there a way round thisthe route setup is just one simple routeroutesmaproute default route name controlleractionid url with parameters new controller properties action list id parameter defaults and the error i get in iis7 when requesting httplocalhostaptment2properties issurely there is a way round this that i just cannot find cheers,['asp.net'] +19050,javascript function in href vs onclick i want to run a simple javascript function on a click without any redirectionis there any difference or benefit between putting the javascript call in the href attribute like this a hrefjavascriptmy functionwindowprinta vs putting it in the onclick attribute binding it to the onclick event,['javascript'] +19051,how does http adaptive bitrate streaming work on the iphone apple has included http adaptive bitrate streaming in the iphone os 30 in particular safari handles this automaticallyi would like to play with this in a low cost manner but i expect it will require a custom http server in the worst case and interesting phpetc scripting in the best casebut first i need to know what the protocol differences or standard is http is reasonably simple as a protocol but adaptive bitrate means the file size is different the chunk locations are different at different bitrates etc for instance does the client tell the server anything special about the stream as it is downloading or is it all handled on the server sideeliminating buffering pauses for the end user is very attractive for both live and prerecorded video streams and doing both over http is even better given many networks and governments are limiting non port 80 trafficwhat are the technical details for http adaptive bitrate streaming especially apples implementationwhere is this best implemented part of the http server itself part of a mod in a scriptwhat changes are required for the client side if one were to implement this in an application,['iphone'] +19055,set a css class on an aspnet radiobuttonlist listitem is there any way to set a css class on an input item in a radio button list i would like to reference these form values by class in jquerygiven an aspnet radiobuttonlist with classes set on the listitems aspradiobuttonlist idradiobuttonlist runatserver asplistitem classmyclass textyes value1 asplistitem classmyclass textno value0 aspradiobuttonlistwill render as span idradiobuttonlist classradiobuttonlistfield myclass span classmyclass input idradiobuttonlist 0 typeradio value1 nameradiobuttonlist label forradiobuttonlist 0yeslabel span span classmyclass input idradiobuttonlist 1 typeradio value0 nameradiobuttonlist label forradiobuttonlist 1nolabel span spanunfortunately the myclass class is added to the span that contains the radio button item not the input itself how could i get it to look like this instead span idradiobuttonlist classradiobuttonlistfield myclass span input idradiobuttonlist 0 classmyclass typeradio value1 nameradiobuttonlist label forradiobuttonlist 0yeslabel span span input idradiobuttonlist 1 classmyclass typeradio value0 nameradiobuttonlist label forradiobuttonlist 1nolabel span spanthis does not even get into the issue of adding the classes to dynamically bound radiobuttonlists,"['asp.net', 'css']" +19062,is the primary key automatically indexed in mysql do you need to explicitly create an index or is it implicit when defining the primary key is the answer the same for myisam and innodb,['mysql'] +19071,how to use jodatime with javasqltimestamp i have a prepared statementinsert into msttime values where time is of type timestamp in a postgresql databasei am inserting a jodatime datetime object or i should say i am trying to i can find no way to convert the datetime object into a javasqltimestamp i have read the jodatime docs and see no reference to thisthanks,['java'] +19078,using facebook connect with authlogic i am trying to make authlogic and facebook connect using facebook play nice so that you can create an account either the normal registration way or with facebook connect i have been able to get the connect to work one way but logging out only loggs out on facebook and not on my site i have to delete the cookies to make it working any help would be awesome thank you,"['ruby-on-rails', 'ruby']" +19088,learning python for a net developer i have been doing active development in c for several years now i primarily build enterprise application and in house frameworks on the net stacki have never had the need to use any other mainstream high level languages besides c for my tasks since net is the standard platform we usethere are some legacy python applications that i have been asked to support going forward i have no exposure to python and dynamic languages in generalalthough i have done a fair bit of javascripti was hoping to get some guidanceadvise to aid in how to go about learning a language like python for the statically typed mindedit using ironpython is not an option,"['c#', '.net', 'python']" +19089,winverifytrust to check for a specific signature i am implementing a process elevation helper for windows it is a program that will run in elevated mode and launch other programs with administrator privileges without thisplaying additional uac prompts for security reasons i want to make sure only binaries that are digitally signed with my companys authenticode key can be executedthe winverifytrust function gets me halfway there but it only ensures that a binary is signed by some key that is part of microsofts chain of trust is there a relatively simple way to perform the authenticode verification and ensure that it is signed by our private key,['c'] +19092,iphone why does the documentation say uiimageview is nscoding compliant ideally an nscoding compliant class will work as expected using encodewithcoder and initwithcoder at least i thought so till recently without the developer having to bother about what goes on inside the routines unless my idea of an nscoding compliant class are totally screwed upthe uiimageview class is nscoding compliant so i should not have to bother how it will be serializeddeserialized using the nskeyedarchiver and nskeyedunarchiver classes but every time i try and encode a uiimageview object i get an error that uiimage does not recognize encodewithcoder methodnow the uiimageview internally uses a uiimage object but should not the encoding have taken care of that itselfor is the nscoding compliance specified in the documentation to just let the user know that they can implement the initwithcoder and encodewithcoder methodscan someone please clarify this for me i am thoroughly confused,['iphone'] +19098,how can i determine whether a java class is abstract by reflection i am interating through classes in a jar file and wish to find those which are not abstract i can solve this by instantiating the classes and trapping instantiationexception but that has a performance hit as some classes have heavy startup i cannot find anything obviously like isabstract in the classjava docs,['java'] +19099,user friendly framework for personal website which are the user friendly frameworks for building personal sites specially if that comes with little programming knowledge and integrated jquery will be great python or php based framework will do betteri tried wordpress and joomla but those are far more complex for a simple personal site with personal blogging live commenting twitting keeping personal projects and resume etcplease suggest me thanks in advance,"['php', 'python']" +19101,invalid token in class struct or interface after checkout i am having problems compiling an episerver web application after checking it out of subversioni get this errorcompiler error message cs1519 invalid token in class struct or interface member declarationsource errorline 116 line 117 line 118 public virtual episerverpersonalizationsubscriptioninfo episerversubscription info line 119 get line 120 return episerverpersonalizationsubscriptioninfo episerverthisgetpropertyvaluesubscriptioninfosource filecwindowsmicrosoftnetframeworkv2050727temporary aspnet filesroot956e6fc566c11597app code9 fan95p0cs line 118 as you can see from the error this file is in the temporary aspnet files folder and is part of the build process this is not my source codei have seen this question which suggests that the web config contains type referencesspecified in the namespaceclassname assemblyname formatso i went into my webconfig and changed the sectionprofile properties add namesubscriptioninfo typeepiserverpersonalizationsubscriptioninfo episerver providersqlprofile toprofile properties add namesubscriptioninfo typeepiserverpersonalizationsubscriptioninfo providersqlprofile this removed the immediate error above but then i got the same error for a different type so i went through all the types that were in namespacetypename assemblyname format and removed the assemblyname this stopped all the cs1519 errors but then i start getting cs0234compiler error message cs0234 the type or namespace name personalization does not exist in the namespace episerver are you missing an assembly referencesource error line 116 line 117 line 118 public virtual episerverpersonalizationsubscriptioninfo subscriptioninfo line 119 get line 120 return episerverpersonalizationsubscriptioninfothisgetpropertyvaluesubscriptioninfoi am using visualstudio 2008 episerver 523727 visualsvn 172 and a debian box as the subversion repo running svn version 142 r22196the application built fine then i checked it in to the repo checked it out to a different location on the same computer and hit f5 and these errors start to appeardoes anyone have any suggestionsupdatethanks for your replies devio zhaphi have added the following to my webconfig in the compilation sectionassemblies add assemblysystemwebextensions version10610250 cultureneutral publickeytoken31bf3856ad364e35 add assemblyepiserver version523757 cultureneutral publickeytoken8fe83dea738b45b7 add assemblyepiserverbaselibrary version523757 cultureneutral publickeytoken8fe83dea738b45b7 add assemblyepiserverconfiguration version523757 cultureneutral publickeytoken8fe83dea738b45b7 add assemblyepiserverenterprise version523757 cultureneutral publickeytoken8fe83dea738b45b7 add assemblyepiserverimplementation version523757 cultureneutral publickeytoken8fe83dea738b45b7 add assemblyepiserverlucene version523757 cultureneutral publickeytoken8fe83dea738b45b7 add assemblyepiserverscheduler version523757 cultureneutral publickeytoken8fe83dea738b45b7 add assemblyepiserverwebwebcontrols version523757 cultureneutral publickeytoken8fe83dea738b45b7 add assemblyepiserverworkflowfoundation version523757 cultureneutral publickeytoken8fe83dea738b45b7 add assemblyepiserverwsrp version523757 cultureneutral publickeytoken8fe83dea738b45b7 add assemblyepiserverxforms version523757 cultureneutral publickeytoken8fe83dea738b45b7assembliesthere was no assemblies section previouslythe project has all of those dlls in its references all the episerver dlls are in the gacthe new nonworking checkout is on the same machine that the original project was created oni now get parser error message could not load file or assembly episerverscheduler or one of its dependencies the system cannot find the file specifiedcprojectswebprovidentppc2providentppcwebconfig line 301source error line 299 add nameinitializationmodule typeepiserverwebinitializationmodule line 300 add namebasicauthentication typeepiserversecuritybasicauthentication episerver line 301 add nameinitializer typeepiserverschedulerinitializer episerverscheduler line 302 add nameworkflowruntime typeepiserverworkflowfoundationworkflowsystem line 303 add nameurlrewritemodule typeepiserverweburlrewritemodule source filecprojectswebprovidentppc2providentppcwebconfigline 301as i say episerverscheduler is in my gac and added to the project as a referenceany more ideas would be greately appreciated,['asp.net'] +19105,i want to use javascript to insert an attribute to an element any ideas how i would go about writing a javascript method to insert an attribute to a tageg i haveinput idin1 valuesubmit typesubmitand i want to insert an attribute nameinput idin1 namesubmit content valuesubmit typesubmitthanks,"['javascript', 'html']" +19109,c custom casting to a value type is it possible to cast a custom class to a value typeheres an examplevar x new foovar y int x does not compileis it possible to make the above happen do i need to overload something in foo,"['c#', '.net']" +19112,pyqt clipboard does not copy to system clipboard the following snippet of code does not seem to affect the system clipboard at allclipboard qtguiqapplicationclipboardclipboardsettexttextaccording to the qt documentation this is how you copy text to clipboard why is not it workinggoogling turned this upit suggests adding this after the above codeevent qtcoreqeventqtcoreqeventclipboardappsendeventclipboard eventbut this one behaves odd it only copies the text to the clipboard after the program exits plus some people in that link reported that this does not work with linuxupdatenevermind i was doing something wrong else where instead of binding the copy slot to the copy button i connected it to the quit button,['python'] +19114,how to make eclipse aware of osgi bundles within a maven repository local remote i have a project which is build through maven each module is built as an osgi bundle within eclipse the modules have also the plugin nature some modules require external dependencies log4j apache commons which are also available as plugins from a maven repository for instance the spring enterprise repository which is also an obrmaven itself has no problem to resolve those dependencies but how can i convince eclipse to retrieve and resolve those bundles as plugins using a maven repository i do not want to make for each of those a wrapper pluginis there a maven provisioner which could be installed in eclipse,['java'] +19125,serve a dynamically generated image with django how do i serve a dynamically generated image in django i have an html taghtml img srcimagesdynamic chartpng htmllinked up to this request handler which creates an inmemory imagedef chartrequest img imagenewrgb 300300 f data irandint100200 for i in range030010 draw imagedrawdrawimg drawpolygondata fill0 now what return httpresponseoutputi also plan to change the requests to ajax and add some sort of caching mechanism but my understanding is that wouldnt affect this part of the solution,['python'] +19128,remove uiwebview shadow does anyone know if its possible to remove the shadow that is placed on the uiwebview window example olub5shadowpngif its possible how do you do itthanks,['iphone'] +19132,efficient hashcode implementation i often autogenerate an clas hashcode method using intellij idea and typically the method takes the formresult 31 result my question is what is the purpose of multiplying by 31 i know this is a prime number but why pick 31 specifically also if implementing a hashcode for a particularly small large dataset would people approach this problem differently,['java'] +19133,how to catch exception of mvc view in controller trycatch can catch exception how to catch exception in view for example a view may have code like htmlencodemodelmyidif model is null you will get exception when access the view where to catch the exception and redirect user to a error page with userfriendly error message,['.net'] +19137,with a browser how do i know which decimal separator does the client use i am developing a web applicationi need to thisplay some decimal data correctly so that it can be copied and pasted into a certain gui application that is not under my controlthe gui application is locale sensitive and it accepts only the correct decimal separator which is set in the systemi can guess the decimal separator from acceptlanguage and the guess will be correct in 95 cases but sometimes it failsis there any way to do it on server side preferably so that i can collect statistics or on client sideupdatethe whole point of the task is doing it automaticallyin fact this webapp is a kind of online interface to a legacy gui which helps to fill the forms correctlythe kind of users that use it mostly have no idea on what a decimal separator isthe acceptlanguage solution is implemented and works but i would like to improve itupdate2i need to retrive a very specific setting decimal separator set in control panel regional and language options regional options customizei deal with four kinds of operating systemsrussian windows with a comma as a ds 80english windows with a period as a ds 15russian windows with a period as a ds to make poorly written english applications work 4english windows with a comma as a ds to make poorly written russian applications work 1all 100 of clients are in russia and the legacy application deals with russian govermentissued forms so asking for a country will yield 100 of russian federation and geoip will yield 80 of russian federation and 20 of other incorrect answers,['html'] +19139,how do i zip on the fly and stream to responseoutput in real time i am trying to use the following code i get a corrupted zip file whythe file names seem ok perhaps they are not relative names and that is the problem private void trysharpziplibarraylist filestoinclude response header responseclear responseclearheaders responsecachesetcacheabilityhttpcacheabilitynocache responsestatuscode 200 long zipsize calculatezipsizefilestoinclude string contentvalue stringformatattachment filenamemoshezip size0 zipsize responsecontenttype applicationoctetstream applicationzip responseaddheadercontentthisposition contentvalue responseflush using zipoutputstream zipoutputstream new zipoutputstreamresponseoutputstream zipoutputstreamsetlevel0 foreach string f in filestoinclude string filename pathcombineservermappath f using filestream fs fileopenreadfilename zipentry entry new zipentryzipentrycleannamefilename datetime filegetcreationtimefilename compressionmethod compressionmethodstored size fslength zipoutputstreamputnextentryentry byte buffer new bytefslength write to zipoutstream via buffer the zipoutstream is directly connected to responseoutput in the constructor icsharpcodesharpziplibcorestreamutilscopyfs zipoutputstream buffer responseflush for immediate response to user using file stream each file responseflush responseend,['asp.net'] +19147,wpf listview rightclick problem so i have attached a context menu rightclick menu to a wpf listviewunfortunately when you rightclick it brings up both the menu and selects whatever item you are over is there a way to shut off this rightclick select behavior while still allowing the context menu,['c#'] +19155,running php zend test in eclipse is it possible to run php zend test cases those that extend zend test phpunit controllertestcase etc through eclipse pdti would like to be able to run them in a similar fashion as you run junit tests in eclipse by rightclicking the test file and selecting run as a junit test case i would love to see the green or red bar instead of having to go to the command line thanks in advance,['php'] +19158,running javascript standalone engine bit of a strange question here i knowbut i wanted to know if some kind of standalone engine for javascript existsbasically i want to test running of my javascript without having to load a web pagemaybe it does not exist like some kind of ide where i can run commands directly without launching ie etci have a great editor but it does not support that i still need to launch ie firefxowhat i was thinking of some kind of standalone javascript engine existed that i could write my code here and make debugging a bit easier and then copy to my webpagei know firebug exists but you cannot specifically do what i am asking cna youany ideas,['javascript'] +19159,jquery class inheritance var afunctionextendaprototype initfunctionalerta initvar bfunctionextendbprototypeaprototypeinitfunctionalertb initvar pnew apinitvar xnew bxinitis the above the best way to create class and inheritance in jquery in bs init how do i invoke parents init similar to superinit in oo languages,['jquery'] +19168,how do i create unique ids like youtube i have always wondered how and why they do thisan example how are these ids generated such that there are no duplicates and what advantage does this have over having a simple auto incrementing numeric idhow do one keep it short but still keep it is uniqueness the string uniqid creates are pretty long,['php'] +19172,modify listcontains behavior i have a listmyobj with the class myobj icomparable i wrote the method compareto in the myobj class per the icomparable interface but when i use the listmyobjcontainsmyobjinstance it returns false when it should be true i am not sure i am understanding how i need to proceed to make sure the list uses my custom comparison method when calling then contains functionhere is my compareto implementation region icomparable members public int comparetoobject obj myobj myobj myobjobj return stringcomparethissymbol myobjsymbol true endregionnote the symbol property is a stringto clarify i have put a stopping point in that compareto method and it does not even go in there anyone has ever tried thatthanks,['c#'] +19181,datacontractserializer does not call my constructor i just realized something crazy which i assumed to be completely impossible when deserializing an object the datacontractserializer does not call the constructor take this class for instance datacontractpublic class book public book breakpoint here datamemberorder 0 public string title get set datamemberorder 1 public string author get set datamemberorder 2 public string summary get set when i deserialize an object of that class the breakpoint is not hit i have absolutely no idea how it is possible since it is the only constructor for this object i assumed that perhaps an additional constructor was generated by the compiler because of the datacontract attribute but i could not find it through reflectionso what i would like to know is this how could an instance of my class be created without the constructor being called note i know that i can use the ondeserializing attribute to initialize my object when deserialization begins this is not the subject of my question,"['c#', '.net']" +19192,converting words to numbers in php i am trying to convert numerical values written as words into integers for exampleiphone has two hundred and thirty thousand seven hundred and eighty three appswould become iphone as 230783 appsbefore i start coding i would like to know if any function code exists for this conversion,['php'] +19197,deletereset all entries in core data do you know of any way to delete all of the entries stored in core data my schema should stay the same i just want to reset it to blankediti am looking to do this programmatically so that a user can essentially hit a reset button,['iphone'] +19198,javascript memory leaks after unloading a web page i have been reading up to try to make sense of memory leaks in browsers esp ie i understand that the leaks are caused by a mismatch in garbage collection algorithms between the javascript engine and the dom object tree and will persist past what i do not understand is why according to some statements in the articles i am reading the memory is not reclaimed after the page is unloaded by the browser navigating away from a webpage should put all the dom and javascript objects out of scope at that point should not it,['javascript'] +19209,is mono stable and fast enough c looks great because it is a compiled language which seems to run quite well without too much cpu and does not consume too much memory and stackoverflow and serverfault are good examples of an mvcnetc stack that scalesc is also interesting because despite being compiled it still has a lot of advanced features as a language only found on slower interpreted languagemy server being linux only ubuntu 804 lts i am wondering if installing mono in place of the net framework is a good idea for production usei currently do not have any existing applications using net but i am interested in using existing frameworks like ms mvc,['c#'] +19220,can you expand defines into string literals is there a way to get the c preprocessor to expand a defineed value into a string literalfor example define new line nprintfoutputnew line or whateverthis looks to me like it should be possible as it is before compilationor is there a better design pattern to achieve this kind of behaviour without resorting to runtime fixes like sprintfedit i understand that defines can be evil but for arguments sakeadditional does anyone have any criticism of this approach,['c++'] +19221,how to make these dynamically typed functions typesafe is there any programming language or type system in which you could express the following pythonfunctions in a statically typed and typesafe way without having to use casts runtimechecks etc1 my function what would its type be def applyx return xx example usageprint applylambda 422white noneblack nonedef white for x in xrange1 10 print white move s x yield blackdef black for x in xrange1 10 print black move s x yield whitewhite whiteblack black what would the type of the iterator objects befor it in white it itnext,['python'] +19223,javascript jquery how to prevent active input field from being changed how do i prevent the user to change the value in an input field which contains a certain value to be copied into the clipboard without using thisabledtrue the text should be selected once the user clicks in the field that is working already but entering anything should have no effectthanksjqueryinputautoselectvaluefocusfunction jquerythisselect,"['javascript', 'jquery']" +19228,how to determine position of row in sql resultset i have a sql queryselect id name from table order by nameresult looks like this52 arnold 33 berta 34 chris 47 doris52 emilfor a given id47 how can i determine the position in the result setthe result should be 4 because52 arnold33 berta34 chrisare before 47 doris and id41 is on the 4th position in the result sethow to do this in sql how in hql in a pagination example do i have to execute 2 statements or is there a solution where i can retrieve exactly that window which contains the row with id47postgresql and java,['sql'] +19242,calling consolewriteline from multiple threads why does consolewriteline work from multiple threads,['.net'] +19267,why is this a floating point exception today i was tracking down a floating point exception in some code i had just written it took a little while to find because it was actually caused by taking an integer mod zero obviously doing anything mod zero is not going to be defined but i thought it was strange that the error was so misleading what is it within the c modulo operator that would use floating point for two integers i am using gcc 432heres a simple program to demonstrate the errorint main int a3b0 int cab return 0,['c++'] +19269,how do you do something after you render the view django i want to do something after i have rendered the view using return render to responseare signals the only way to do this do i need to write a custom signal or does request finished give me enough information basically i need to know what page was rendered and then do an action in response to thatthanksupdate from comments i do not want to hold up the rendering of the page so i want to render the page first and then do the action,['python'] +19270,table layout problem firefox versus chrome and ie7 i am trying to layout an html table it is tabular data and it is rendering differently in firefox 35 and chrome 20172 edit and ie7 which renders the table like chrome doesi have the table inside a divdiv idlistcontainer table classtasklist colgroup col classnarrow col classwide more column definitions here colgroup various code here tabledivand i have got css for the div and tabledivlistcontainer position relative float left width 98 padding 0 border 1px overflowx scrolltabletasklist width auto tablelayout auto border thin solid fontsize 9pt bordercollapse collapse emptycells showcolnarrow minwidth 50px colwide minwidth 200px in firefox the table renders wider than the containing div and the scrollbar on the div allows the user to scroll over to the additional columns which is the intended action however chrome and ie7 appear to ignore the minwidth property of the columns and crams the whole table into the containing div which is not what i want what am i doing wrongedit i put the minwidth elements on the th and td elements themselves instead of using colgroup and then it renders as expected in all three browsers using cols inspecting the elements in chrome indicates that the calculated style has rendered the column widths to fit inside the div,['css'] +19274,optimizing oracle connect by when used with where clause oracle start with connect by clause is applied before applying where condition in the same query thus where constraints would not help optimize connect by for example the following query will likely perform full table scan ignoring selectivity on dept idselect from employees where dept id salestart with manager id is nullconnect by prior employee id manager idi tried to improve performance in 2 waysquery aselect from employees start with manager id is null and dept id saleconnect by prior employee id manager idquery bselect from select from employees where dept id sale start with manager id is nullconnect by prior employee id manager idwhile both queries did much better than original on oracle 10g release 2 query b did performed much better than a did you have similar performance optimization to deal with with respect to connect by and where clauses how would you explain query b doing much better than query a,['sql'] +19276,how to ease the transition from winforms to wpf i am working on a large winforms application dealing with large amounts of data exposed through grids i see us eventually moving completely to an mvvm wpf implementation but now were still closer to a ballofmud than anything resembling loose couplingas we evolve toward cleaner separation of concerns what are some specific patterns we can implement while still in the winforms world but yielding a smoother transition once we take the wpf plunge specifically is there any guidance on exploiting winforms limited binding and event handling in a fashion that approximates wpfmvvm,"['c#', '.net']" +19284,best practices for writing open source java where can i find some best practices for writing open source java codei am not looking for directions on how to write the code proper but rather on thistribution packaging documentation and all the other aspects besides java filesmy goal is to take a module i have written and publish it as open sourceedit i am still missing direct concrete instructions on what the zip file should contain are there conventions for this or should i just pick some reasonable structure,['java'] +19285,how to access system time finer than 1 second on the iphone the system time function time0 gives me a resolution of 1 second rightis there a finergrained functioni am using it to determine the time interval between two eventsa line of code would help me greatly it makes it easier to have something concrete to hang the concept on when i look in the official documentation,['iphone'] +19286,linking to an external url in javadoc something like see linktourl,['java'] +19287,how do i remove a mysql database you may notice from my last question that a problem caused some more problems reading mysql manuals in mysql monitormy database is now unusable partly due to my interest to break things and my inability to look at error messages i know that i should not reuse primary keys but i would like to use them again after the removal of the database that i deteriorated sohow can i correctly remove a mysql database,['mysql'] +19294,what order should i use gzipoutputstream and bufferedoutputstream can anyone recommend whether i should do something likeos new gzipoutputstreamnew bufferedoutputstreamoros new bufferedoutputstreamnew gzipoutputstreamwhich is more efficient should i use bufferedoutputstream at all,['java'] +19299,how to build jars from intellij properly i have a project that contains a single module and some dependenciesi would like to create a jar in a separate directory that contains the compiled module in addition i would like to have the dependencies present beside my moduleno matter how i twist intellijs build jar process the output of my module appears empty besides a metainf file,['java'] +19308,java reflection create an implementing class class someinterface classfromnamesomepackagesomeinterfacehow do i now create a new class that implements someinterfacei need to create a new class and pass it to a function that needs a someinterface as an argument,['java'] +19310,what are the java equivalents to linq and entity framework having played with linq to sql and objects as well as the entity framework from microsoft recently i was wondering what the nonnet specifically java equivalents are,['java'] +19315,running json through pythons eval best practices aside is there a compelling reason not to do thisi am writing a postcommit hook for use with a google code project which provides commit data via a json object gc provides an hmac authentication token along with the request outside the json data so by validating that token i gain high confidence that the json data is both benign as there is little point in thistrusting google and validmy own brief investigations suggest that json happens to be completely valid python with the exception of the escape sequence a which gc does not appear to generateso as i am working with python 24 ie no json module eval is looking really temptingedit for the record i am very much not asking if this is a good idea i am quite aware that it is not and i very much doubt i will ever use this technique for any future projects even if i end up using it for this one i just wanted to make sure that i know what kind of trouble i will run into if i do,['python'] +19324,how resource intensive are listeners in java i am new to java programming but an experienced c programmer i was learning how to program guis using swing i was wondering how resource intensive runtime as well as memory are actionlisteners is there a general guideline to the total number of listeners that one should create in a particular program how many until performance is affectedi am currently learning java through the deitel developer series java for programmers book in a particular example they have an array of jradiobuttonitems as a private variable for the class they also had created an itemhandler class that extended from the actionlistener class that conducted a linear search on the entire array of radio buttons in order to determine the one that was selected and changes the state of the program accordingly all of the radio buttons in the array shared the same action listener this seemed rather inefficient to conduct a linear search of information so i had rewritten the actionlistener class to take in the proposed value to modify in the constructor and gave each radio button its own actionlistener with the proposed value passed in by the constructor in order to avoid doing a linear search which method would be better performancewise i apologize for sounding like a noob i am just trying to develop a good set of habits for programming in java attached is a small example of the code thanks original code in deitel book with linear search of selected radio button in actionlistener import javaawtcolorimport javaawteventactioneventimport javaawteventactionlistenerimport javaxswingbuttongroupimport javaxswingjframeimport javaxswingjlabelimport javaxswingjmenuimport javaxswingjmenubarimport javaxswingjmenuitemimport javaxswingjradiobuttonmenuitempublic class menutest extends jframe private final color colorvalues colorblack colorwhite colorgreen private jradiobuttonmenuitem coloritems private buttongroup colorbuttongroup public menutest supermenu test jmenu filemenu new jmenufile jmenubar bar new jmenubar setjmenubarbar baraddfilemenu string colors black white green jmenu colormenu new jmenucolor coloritems new jradiobuttonmenuitemcolorslength colorbuttongroup new buttongroup itemhandler itemhandler new itemhandler forint count 0 count colorslength count coloritemscount new jradiobuttonmenuitemcolorscount colormenuaddcoloritemscount colorbuttongroupaddcoloritemscount coloritemscountaddactionlisteneritemhandler coloritems0setselectedtrue filemenuaddcolormenu filemenuaddseparator private class itemhandler implements actionlistener public void actionperformedactionevent event forint count 0 count coloritemslength count ifcoloritemscountisselected getcontentpanesetbackgroundcolorvaluescount public static void mainstring args menutest menuframe new menutest menuframesetdefaultcloseoperationjframeexit on close menuframesetsize600400 menuframesetvisibletrue menuframegetcontentpanesetbackgroundmenuframecolorvalues0 my code redefined version of deitels wo linear search in actionlistener import javaawtcolor import javaawteventactionevent import javaawteventactionlistener import javaxswingbuttongroup import javaxswingjframe import javaxswingjlabel import javaxswingjmenu import javaxswingjmenubar import javaxswingjmenuitem import javaxswingjradiobuttonmenuitem public class menutest extends jframe private final color colorvalues colorblack colorwhite colorgreen private jradiobuttonmenuitem coloritems private buttongroup colorbuttongroup public menutest supermenu test jmenu filemenu new jmenufile jmenubar bar new jmenubar setjmenubarbar baraddfilemenu string colors black white green jmenu colormenu new jmenucolor coloritems new jradiobuttonmenuitemcolorslength colorbuttongroup new buttongroup itemhandler itemhandler new itemhandler forint count 0 count colorslength count coloritemscount new jradiobuttonmenuitemcolorscount colormenuaddcoloritemscount colorbuttongroupaddcoloritemscount coloritemscountaddactionlistenernew itemhandlercolorvaluescount coloritems0setselectedtrue filemenuaddcolormenu filemenuaddseparator private class itemhandler implements actionlistener private color setcolor public itemhandlercolor incolor super setcolor incolor public void actionperformedactionevent event getcontentpanesetbackgroundsetcolor repaint public static void mainstring args menutest menuframe new menutest menuframesetdefaultcloseoperationjframeexit on close menuframesetsize600400 menuframesetvisibletrue menuframegetcontentpanesetbackgroundmenuframecolorvalues0,['java'] +19326,di object graph building separating logic and construction graph sorry if this is a really basic question but it is been really getting to me i really like the idea of di it really helps me with my testing but i have hit a bit of a brick wall i think so i have two types table tablemanagernow the table object has a constructor on it like thistableitablecommandrunner tablerunner iqueryprovider queryprovider idatareader reader string namenow the table object pretty much only uses those objects so following the rule that you ask for what you need i pass them in now my tablemanager object is used to open and close etc tables the only thing it needs is a itablecommandrunner so i pass that in the constructor tablemanageritablecommandrunner tablrunnerok that is fine but in the tablemanageropentable command i need call the open table comand on the itablecommandrunner and then construct a new table object to pass back public itable opentablestring tablename call open table command on tablerunner i need a iqueryprovider and idatareader to pass to the table return new tabletentitythistablerunner providerreader tablename but now in my open table command i have to make a idatareader and iqueryprovider if i pass them into the constructor of tablemanager does not that violate taking objects just to pass it down to a inner type and not really using themi am not really sure how i do this could anyone help me with thisi am just not sure how i separate object construction and logic,['c#'] +19327,how to attach source code of libraries downloaded with ivy i use ivy with the ivy eclipse plugin to download dependencies works great but how can i attach the source code for those libraries in order to step into these libraries,['java'] +19337,how to find the previous and next record using a single query in mysql i have a database and i want to find out the previous and next record ordered by id using a single query i tried to do a union but that does not work select from table where id 1556 limit 1union select from table where id 1556 order by product id limit 1any ideasthanks a lot,['mysql'] +19341,how check file size on upload whats the best way to check the size of a file during upload using aspnet and c i can upload large files by altering my webconfig without any problems my issues arises when a file is uploaded which is more than my allowed max file sizei have looked into using activex objects but that is not cross browser compatible and not the best answer to the solution i need it to be cross browser compatible if possible and to support ie6 i know what you are thinking however 80 of my apps users are ie6 and this is not going to change anytime soon unfortunately has any dev out there come across the same problem and if so how did you solve itmany thankscragly,"['c#', 'asp.net']" +19342,getting only new mail from an imap server i am writing a client application that fetches emails from an imap server and then stores them in a database the problem is that once i have checked the mail the next time i only want to download the mail that has arrived since so if i had checked the server for mail two hour ago i only want to get the mail that has arrived in the last two hoursi could use search with since date but there is no support for time date could be easily spoofedi also tried the recent flag but that does not seem to work with gmail in ruby it shows nil everytime,"['ruby-on-rails', 'ruby']" +19360,how do cc compilers work after over a decade of cc coding i have noticed the following pattern very good programmers tend to have detailed knowledge of the innards of the compiler i am a reasonably good programmer and i have an adhoc collection of compiler superstitions so i would like to reboot my knowledge and start from the basicscan anyone recommend links to online resources or favorite books i am particularly interested in cc compiling optimization gcc and llvmbtw at university i was interested in compilers and so i signed up for subject called parsing and translation bad move it ended up being the professors vehicle for testing his advanced parsing and grammar theory textbook on unsuspecting 3rd year comp sci students i was left with no practical knowledge and even more confused than before,"['c++', 'c']" +19362,how do i suppress eclipse 35s warnings of dead code i use a class for detecting email addresses which uses static final booleans to configure the matching behavior since i upgraded to eclipse 35 i get warnings about dead code since eclipse notices that one branch in this can not be reachedprivate static final boolean allow domain literals falseprivate static final string domain allow domain literals rfc2822domain rfc1035domainnameoddly enough it is happy with thisprivate static final string domainstatic ifallow domain literals domain rfc2822domain else domain rfc1035domainname since it seems to recognize the common ifdebug pattern but the ternary operator does not seem to countsince i would rather not fork the class too much just to keep eclipse happy i would prefer putting an suppresswarnings at the top instead of changing the code unfortunately i cannot find a matching one apart from the bruteforce all is there a value just for the dead code detection,['java'] +19366,difference between targettypecontroltype and targettypextype controltype in wpf you can set the targettype to either the name of the type or you can set it to xtype nameoftypedoes anyone know what the difference is,['.net'] +19377,export c reportviewer control programmatically does anyone know if you can programmatically save a report shown in a reportviewer control in cwhen a report is shown there are export to buttons and i would like to automate the saving to pdf function,['c#'] +19379,how do i wrap link to around some html ruby code how do i wrap a link around view code i cannot figure out how to pass multiple lines with ruby code to a single link to method the result i am looking for is that you click the column and get the show pagediv clasubcolumns div classc25l div clasubcl image tag albumphotomediaurlthumb class image rescue nil div div div classc75r div clasubcr p albumcreated at p link to halbumtitle album p albumcreated at p p albumphoto count p div divdiv,"['ruby-on-rails', 'ruby']" +19407,pointers to virtual member functions how does it work consider the following c codeclass apublic virtual void f0int main void afafif i would have to guess i would say that af in this context would mean the address of as implementation of f since there is no explicit seperation between pointers to regular member functions and virtual member functions and since a does not implement f that would be a compile error however it is notand not only that the following codevoid afafa anew b b is a subclass of a which implements fafwill actually call bfhow does it happen,['c++'] +19415,total height of the page i am trying to get the total height of a page using javascript and jquery so i can check if the page is long enough to thisplay something however in my testing i am unable to get the total height of a pagei have looked around on the internet but things like this do not seem to be well documented as all i can find is scrollheight which as i might mention does not work any way to use jquery to find it,"['javascript', 'jquery']" +19422,how to test a css parser i am writing a parser to parse cssi started by modifying the css reference grammar to use whichever grammar and lexer syntax are supported by the 3rdparty parser generator tool which i am usingi think that i have finished coding the grammar the parsergenerator is able now to generate state transition tables forfrom my grammarthe result the output from the parsergenerator is approximately 116 rules which correspond to 116 cases in a switch statement examples of these rulesswitch statements arestylesheet begins with specifying a charsetstylesheet begins without specifying a charsetstylesheet is emptystylesheet begins with whitespaceetcthe parsergenerator has done all it can for me and now i am begining to write by hand the various cases of the switch statements which will build what i think people call an abstract syntax treemy question is about how to test this i think that what i want is a set of css files which exercise the various combination and possibilities eg one css file which specifies a charset another file which does not specify a charset etcis there general a way to autogenerate this set of input data for an arbitrary grammar or set of rulesalternatively is there a set of specifically css files whose purpose is to cover the combination and possibilities allowed by the standard css grammarfeel free to comment too if i am going about this all wrongat the moment i do not needfiles to test handling of illegal input ie of files which do not conform to the grammartesting of how various browsers render based on their parsing of css,['css'] +19423,define statements within a namespace if i have a define statement within a namespace as suchnamespace mynamespace define some value 0xdeadbabeam i correct in saying that the define statement is not restricted to the namespace is the following the correct thing to donamespace mynamespace const unsigned int some value 0xdeadbabe,['c++'] +19444,itemgroup item scope alternatively why does msbuild hate me i have a solution i am trying to get to build on tfs i want to update the versions of all appropriate files and i have been stuck trying to get this done there are plenty of links on how to do it but none of them work for me due to one little issue scopexml version10 encodingutf8project defaulttargetsdesktopbuild xmlns toolsversion35 target namedesktopbuild calltarget targetsgetfiles message textcsfiles csfiles target target namegetfiles itemgroup csfiles includeassemblyinfocs itemgroup message textcsfiles csfiles targetprojectmy tree looks like thistestprojapplicationslnapplication foldermaincsproperties folderassemblyinfocswhen i run cwindowsmicrosoftnetframeworkv35msbuildexe testproj from the solution folder i get the following outputmicrosoft r build engine version 35307291microsoft net framework version 20507273074copyright c microsoft corporation 2007 all rights reservedbuild started 762009 35410 pmproject dsrctestproj on node 0 default targets csfiles applicationpropertiesassemblyinfocsdesktopbuild csfiles done building project dsrctestproj default targetsbuild succeeded 0 warnings 0 errorstime elapsed 04so how can i make my itemgroup have global scope all the targets files used by the compiler and teambuild do this same thing and theirs all seem to be global i do not understand why this is not working for meany help,['c#'] +19451,eclipse cdt how to reference 3rd party includes via a relative path i am new to eclipsecdt setting up a new project for the first time i am trying to reference boost without hardcoding an absolute pathi have put boost in my workspace folder eg homeuserworkspaceboost 1 39 0i was then hoping to add an include directory pointing to that folder relative to the workspace but eclipse would not do that it seems to only want to point to thinks in homeuserworkspacemyprojectnamehereany tips it does not seem to make sense to copy boost into my project folder because then it shows up in eclipse and eclipse wants to build it sure i could exclude italex,['c++'] +19462,aspnet mvc project structure hi guys i have created the following project structure for my new aspnet mvc project any i was after some feedback as how other people are structuring their projects and if i would improve minehere is what i have so farassetsimages scripts stylesheets more things like the above herecontrollers supportactions any custom action classescontrollers base controller classesmodelsdomain contains any class that specialise view specific domain logicurlprocessing encodingdecoding business entities as url parts more things like the above hereviews contains view modelssupportviews base classes for any view modelssupportapplication global application interface classes ie class that wraps the function of the global asaxconfiguration typed config classeshelpers where you put additional html helper classes etcservicesbootstrap tasks that run on mvc startup that are specific to the mvc projectinversion specific ioc registration registrations for this project more things like the above hereviewshomeshared more things like the above herecheers anthony,['asp.net'] +19474,special magic methods in python what are all the special magic methods in python the x methods that isi am often looking for a way to override something which i know is possible to do through one of these methods but i am having a hard time to find how since as far as i can tell there is no definitive list of these methods plus their names are not really google friendly so i think having a list of those here on so would be a good idea,['python'] +19475,are static methods thread safe i have a static timer class which will be called by any webpage to calculate how long each page has taken to be constructedmy question is are static classes thread safe in my example will concurrent users cause a problem with my start and stop times eg a different threads overwriting my start and stop values public static class timer private static datetime starttime private static datetime stoptime summary gets the amount of time taken in milliseconds summary returnsreturns public static decimal duration timespan duration stoptime starttime return durationmilliseconds public static void start starttime datetimenow public static void stop stoptime datetimenow should this class be a nonstatic classthis class will called from the aspnet masterpage,"['c#', 'asp.net']" +19487,how can i use and access an sqlite db using php and wamp server i know php 5 already supports sqlite but for some reason i cannot get it to worki followed the instructions from sqlite tutorial getting started i also made sure that the following are not commented out from phpiniextensionphp pdo sqlitedll extensionphp sqlitedllbut when i open the php file from localhost using firefox i get this errorfatal error class sqlitedatabase not foundi am on windows by the way if that info matterswhat may be the cause of this problem,['php'] +19499,c timer or threadsleep i am running a windows service and using a loop and threadsleep to repeat a task would it be better to use a timer methodif yes a code example would be greati am currently using this code to repeatint curminuteint lastminute datetimenowaddminutes1minutewhile condition curminute datetimenowminute if lastminute curminute do your onceperminute code here lastminute curminute threadsleep50 sleeps for 50 seconds if error condition that would break you out of this break leaves looping structure,['c#'] +19500,phps usort callback function parameters this is a really esoteric question but i am genuinely curious i am using usort for the first time today in years and i am particularly interested in what exactly is going on suppose i have got the following arraymyarray array1 9 18 12 56i could sort this with usortusortmyarray functiona b if a b return 0 return a b 1 1i am not 100 clear about what is going on with the two parameters a and b what are they and what do they represent i mean i could assume that a represents the current item in the array but what exactly is this getting compared to what is bi could increase my array to include stringsmyarray array arrayapples 10 arrayoranges 12 arraystrawberries 3and run the followingusortmyarray functiona b return strcmpa0 b0and that would sort my childarrays alphabetically based upon the 0 index value but this does not offer any clarity about what a and b are i only know that the match the pattern that i am seekingcan somebody offer some clarity about what is actually taking place,['php'] +19503,how to convert datetime to datetime i want to convert a nullable datetime datetime to a datetime but i am getting an errorcannot implicitly convert type systemdatetime to systemdatetime an explicit conversion exists are you missing a casti have attempted the followingdatetime updatedtime datetime objhotelpackageorderupdateddate null datetimenow objhotelpackageorderupdateddate,"['c#', '.net']" +19505,xml vs binary performance for serializationdeserialization i am working on a compact framework application and need to boost performance the app currently works offline by serializing objects to xml and storing them in a database using a profiling tool i could see this was quite a big overhead slowing the app i thought if i switched to a binary serialization the performance would increase but because this is not supported in the compact framework i looked at protobufnet the serialization seems quicker but deserialization much slower and the app is doing more deserializing than serializing should binary serialization should be faster and if so what i can do to speed up the performance heres a snippet of how i am using both xml and binaryxml serializationpublic string serializet obj utf8encoding encoding new utf8encoding xmlserializer serializer new xmlserializertypeoft memorystream stream new memorystream xmltextwriter writer new xmltextwriterstream encodingutf8 serializerserializestream obj stream memorystreamwriterbasestream return encodinggetstringstreamtoarray 0 converttoint32streamlengthpublic t deserializestring xml utf8encoding encoding new utf8encoding xmlserializer serializer new xmlserializertypeoft memorystream stream new memorystreamencodinggetbytesxml return tserializerdeserializestreamprotobufnet binary serializationpublic byte serializet obj byte raw using memorystream memorystream new memorystream serializerserializememorystream obj raw memorystreamtoarray return raw public t deserializebyte serializedtype t obj using memorystream memorystream new memorystreamserializedtype obj serializerdeserializetmemorystream return obj,"['c#', '.net']" +19507,over clause in oracle what is the meaning of the over clause in oracle,['sql'] +19515,autogenerate stub methods that throw in eclipse similar to how to change generate method stub to throw notimplementedexception in vs but for eclipse instead of visual studioboth netbeans and eclipse have a function that if you declare a java class to implement an interface but omit one or more methods will automatically generate a stub method for youthe difference is that the eclipse version will do nothing and return zero or null egpublic string mungestring foo todo autogenerated method stub return nullthe netbeans version will throw an exception insteadpublic string mungestring foo throw new unsupportedoperationexceptionnot supported yetwhich i preferis it possible to configure eclipse to do this,['java'] +19517,how to prevent aspnet from removing items from cache i want to permanently add an item to the cache i am using the following syntaxhttpcontextcurrentcacheinsertcachename c null cachenoabsoluteexpiration cachenoslidingexpirationi have found out that aspnet still sometimes removes items from the cacheany ideas on how to prevent this in addition to dropping the cache and using dictionary stored in a static membermatra,['asp.net'] +19523,jquery ui 171 modal close on overlay click i am trying to override the default behavior of a jquery ui modal dialog box to close the box when the overlay is clicked the code i have below will close the dialog box after i open it for the first time and click on the overlay when i open the dialog box again clicking on the overlay does nothing i am missing an event here can someone point out what i am doing wrong herethanksfunction production schedule dialogdialog autoopen false width 570 modal true closeonescape true production schedule dialog linkclickfunction production schedule dialogdialogopen return false documentbindclick dialogblurvar dialogblur functionevent var target eventtarget if targetisuidialog targetparentsuidialoglength return uidialogvisiblefinduidialogtitlebarclosetriggerclick documentunbindclick dialogblur,['jquery'] +19525,unit testing and checking private variable value i am writing unit tests with c nunit and rhino mockshere are the relevant parts of a class i am testingpublic class classtobetested private ilistobject insertitems new listobject public bool onsaveobject entity object id var auditable entity as iauditable if auditable null insertitemsaddentity return false i want to test the values in insertitems after a call to onsavetestpublic void onsave adds object to insertitems array setup myclasstobetestedonsaveauditableobject null check auditableobject has been added to insertitems array what is the best practice for this i have considered adding insertitems as a property with a public get or injecting a list into classtobetested but not sure i should be modifying the code for purposes of testingi have read many posts on testing private methods and refactoring but this is such a simple class i wondered what is the best option,['c#'] +19533,how to find all unselected checkboxes in jquery how does one go about finding all the unchecked checked boxescheckboxcheckedappears to be me all checked boxes but what i need is all nonchecked boxes,['jquery'] +19536,can microsoft code contracts be used with an aspnet website i am currently using microsoft code contracts in an aspnet mvc application without any issues but i can not seem to get it quite running in a basic aspnet web site i am not entirely sure it was made to work with this type of project although it should not matter so i wanted to bring it up to everyonei can compile the contracts just fine but the code skips over them since i am assuming it has not been enabled through the properties page like you would do in other project types ie aspnet mvc i have gone to the property page of the project which thisplays a dialog instead of the typical properties page in my aspnet web site but it does not yield the same menu options and as such does not have a section devoted to code contractsalso i have microsoft code contracts properly enabled within a class library project that i use to separate my business logic from the web site the contracts compile fine but when a contract is violated it throws a rather uninformative exception of type systemexecutionengineexception was thrown error with no inner exception my contract specifies a message to thisplay upon violation but it is nowhere within the exception it simply halts the execution of the process which i believe is the default functionality for microsoft code contractsi cannot find anywhere that explicitly states that a particular project type can or cannot or should not be used with contracts so i just wanted to see if anyone has had this issuethanks for any help,['asp.net'] +19538,pulling mx record from dns server i am writing an application that is requiring me to do a dns lookup for an mx record i am not sure if anyone has had experience doing this kind of work but if you do any help would be appreciatededitthe thing that i am going for is an application that will send an email alert the problem is i need to have the application be able to lookup the mx record for a domain,['c'] +19541,how do i calculate the number of days minus sundays between two dates in c i am creating a library management system i have used the timestamp to calculate the date difference and with the help of date difference i am calculating the fine alsonow this date difference includes all days in a week but for a library application fine should be charged only for 6 daysmon sat in weeki am not able to do thiscan anyone help me out in performing this taskthanks in advance,['c#'] +19560,umbraco list child nodes in user control i have a user control in which i need to return child nodes based on parentid i am able to get the parentid but do not know the syntax for returning child nodes,"['c#', 'asp.net']" +19573,respond with 404 error from aspnet page codebehind i have a scenario in which i am serving a file from codebehindwhich file depends on request in some cases there will be no file to serve and i want to return 404 to the browserhow can i do that from codebehind is this the correct course of action to show user there is no file available,['asp.net'] +19587,is there any way to show or throw a php warning i have a select method in a database class that has an optional boolean argument sum this argument is used to say if the method should or not use count tooi would like to show a warning like those normal php errors if i try to access clasum if the attribute is not set ie when i call select with sum falseis there any way to show a warning like this or i should just echo an error and be happy,['php'] +19600,why does not junit provide assertnotequals methods does anybody know why junit 4 provides assertequalsfoobar but not assertnotequalfoobar methods it provides assertnotsame corresponding to assertsame and assertfalse corresponding to asserttrue so it seems strange that they did not bother including assertnotequalby the way i know that junitaddons provides the methods i am looking for i am just asking out of curiosity,['java'] +19603,instantiate class from name imagine i have a bunch of c related classes all extending the same base class and providing the same constructor that i declared in a common header file which i include and their implementations in some other files which i compile and link statically as part of the build of my program i would like to be able to instantiate one of them passing the name which is a parameter that has to be passed to my program either as command line or as a compilation macrothe only possible solution i see is to use a macroifndef class namedefine class name mydefaultclasstouseendifbaseclass o new class nameparam1 param2 is it the only valuable approach,['c++'] +19612,in c left shift char 0xff by 8 and cast it to int on left shift of char 0xff by 8 and casting it to int we get 256 or 0xf00can somebody explain why this should happen include stdiohint main void char c 0xff printfd xn intc8intc8 return 0output is256 f00,['c'] +19637,checking if a key exists in a javascript object how do i check if a particular key exists in a javascript object or arrayif a key does not exist and i try to access it will it return false or throw an error,['javascript'] +19642,unit testing of private methods in xcode i am trying out test driven development in a toy project i can get the tests working for the public interface to my classes although i am still on the fence because i am writing more testing code than there is in the methods being testedi tend to use a lot of private methods becuase i like to keep the public interfaces clean however i would still like to use tests on these methodssince cocoa is a dynamic language i can still call these private methods but i get warnings in my tests that my class may not respond to these methods although it clearly does since i like to compile with no warnings here are my questionshow do i turn off these warnings in xcodeis there something else i could do to turn off these warningsam i doing something wrong in trying white box testing,['objective-c'] +19643,marginal browser support by the bbc and why the bbc they cannot use jquery the bbc just released their javascript library glow they rolled their own because the major libraries do not adequately support older browsersi am wondering if i should take the time to learn the library do other large institutions have similar laws and rules regulating them that prevent them from using the mainstream libraries such as jquery,"['javascript', 'jquery']" +19660,whats the difference between getpath getabsolutepath and getcanonicalpath in java whats the difference between getpath getabsolutepath and getcanonicalpath in javaand when do i use each one,['java'] +19670,is there a function in android analogous to int main in cc which contains the programs main loop normally in a c or c program there is a main loopfunction usually int main is there a similar function that i can use in android java development,"['java', 'android']" +19673,contact form in sitefinity c i want to do basic functionality with a simple contact form and on submit the form emails to someone this is quite easy to do in aspnet however i am having trouble once i upload it as a user control do you have a good example i can look at thank you,"['c#', 'asp.net']" +19676,sql server any equivalent of strpos i am dealing with an annoying database where one field contains what really should be stored two separate fields so the column is stored something like the first stringthe second string where is the delimiter again i did not design this i am just trying to fix iti want a query to move this into two columns that would look something like thisupdate userattributesset str1 substringdata 1 strposdata str2 substringdata strposdata 3 lendatastrposdata 3but i cannot find that any equivalent to strpos exists,['sql'] +19680,fftbased 2d convolution and correlation in python is there a fftbased 2d crosscorrelation or convolution function built into scipy or another popular librarythere are functions like thesescipysignalcorrelate2d the direct method implemented by convolvend will beslow for large datascipyndimagecorrelate the array is correlated with the given kernel usingexact calculation ie not fftscipyfftpackconvolveconvolve which i do not really understand but seems wrongnumarray had a correlate2d function with an ffttrue switch but i guess numarray was foldedinto numpy and i cannot find if this function was included,['python'] +19682,what is this constructor call with following double braces unfortunately i have not coded java for about five years and i absolutely can not remember how or why the following code is workingi stumbled across a similar example and broke it down to this the emphasis is on the part below the comment i do not get the constructor notation followed by the block in double brackets and unfortunately i can not find anything in the java documentation or by using google what words should i googlepackage syntaxtestpublic class main public static void mainstring args what kind of notation is this mytest tester new mytest setnamejohn johnson systemoutprintlntestergetname class mytest private string name public string getname return name public void setnamestring name thisname name so here are my questionshow is this notationsyntax called where can i read some documentation about it i guess hope i will be able to answer the second question by myself if somebody can provide me with the answer to the first questionto make it clear i know the output is john johnson but i do not know why it is working,['java'] +19687,multiline string literal in c is there an easy way to create a multiline string literal in cheres what i have nowstring query select foo bar from table where id 42i know php hasblockblockdoes c have something similar,['c#'] +19698,irc python bot best way i want to build a bot that basically does the followinglistens to the room and interacts with users and encourages them to pm the botonce a user has pmed the bot engage with the client using various ai techniques should i just use the irc library or sockets in python or do i need more of a bot frameworkwhat would you dothankshere is the code i am currently using however i have not gotten it to workusrbinpython import socketnetwork holmesfreenetnetport 67irc socketsocket socketaf inet socketsock stream ircconnect network port ircsend nick pyircrn ircsend user pyirc pyirc pyirc python ircrn ircsend join pyircrn ircsend privmsg pyirc can you hear mern ircsend part pyircrn ircsend quitrn ircclose,['python'] +19704,determine if running on a rooted device my app has a certain piece of functionality that will only work on a device where root is available rather than having this feature fail when it is used and then show an appropriate error message to the user i would prefer an ability to silently check if root is available first and if nothide the respective options in the first placeis there a way to do this,['android'] +19705,oracle sql developer sharing configuration via dropbox i would like to share my oracle sql developer configuration across my several computers that use dropboxhow can i do this,['sql'] +19716,tkinter attributeerror nonetype object has no attribute get i have seen a couple of other posts on similar error message but could not find a solution which would fix it in my casei dabbled a bit with tkinter and created a very simple ui the code followsfrom string import from tkinter import import tkmessageboxroottkvid intvardef grabtextevent if entryboxgetstrip tkmessageboxshowerrorerror please enter text else print entryboxgetstrip roottitlemy samplerootmaxsizewidth550 height200rootminsizewidth550 height200rootresizablewidthno heightno labellabelroot text enter textgridrow2column0stickywentryboxentryrootwidth60gridrow2 column1stickywgrabbtnbuttonroot textgrabgrabbtngridrow8 column1grabbtnbindbutton1 grabtextrootmainloopi get the ui up and running when i click on the grab button i get the following error on the consolecpython25pythonexe myfilestestbedpyexception in tkinter callbacktraceback most recent call last file cpython25liblibtktkinterpy line 1403 in call return selffuncargs file myfilestestbedpy line 10 in grabtext if entryboxgetstripattributeerror nonetype object has no attribute getthe error traces back to tkinterpyi am sure some one might have dealt with this before any help is appreciated,['python'] +19722,how to navigate from one screen to another screen how to navigate from one activity screen to another activity screen in the first screen i am having one button if i click the button it has to move to another activity screen,"['java', 'android']" +19729,how to provide custom string placeholder for string format i have a string string str enter 0 patient namei am using stringformat to format itstringformatstr hellonow if i want patient also to be retrieved from some config then i need to change str to something likeenter 0 1 name so it will replace the 1 with second value the problem is that i want instead of 1 some other format something like pat but when i try to use it throws an error the reason i want a different format is that there are lot of files i need to change like thiswhich may contain 01 etc so i need a custom placeholder which can be replaced at runtime,"['c#', '.net']" +19742,how would you encode a map using protocol buffers i am trying to use protocol buffers for message serializationmy message format should contain map string object entries but how do i write the proto definition as far as i know protocol buffers does not have a buildin map type i could model around that using repeating fields but the big problem i have is that you need to define all your types i want my message to be flexible so i cannot specify the types any ideas,['java'] +19751,return number of rows affected by update statements how can i get the number of rows affected by an update query in a stored procedure sql server 2005 as a resultset egcreate procedure updatetablesasbegin set nocount on added to prevent extra result sets from interfering with select statements set nocount on update table1 set column 0 where column is null update table2 set column 0 where column is null update table3 set column 0 where column is null update table4 set column 0 where column is nullendthen returntable1 table2 table3 table432 45 0 3,['sql'] +19756,how do i in jdbc read a possibly null double value from resultset i have a column in my database that is typed double and i want to read the value from it using a jdbc resultset but it may be null what is the best way of doing this i can think of three options none of which seem very goodoption 1 bad because exception handling verbose and smellydouble dtry d rsgetdouble1 do something catchsqlexception ex ifrswasnull do something else else throw ex option 2 bad because two fetchess rsgetstring1 or getobjectifs null do something else else double d rsgetdouble1 do somethingoption 3 bad because java rather than sql conversions rsgetstring1 or getobjectifs null do something else else double d doubleparsedoubles do somethingany suggestions on which way is better or is there another superior way and please do not say use hibernate i am restricted to jdbc code only here,['java'] +19768,java hashmap get works but containskey does not i am trying to locate a key in a hashmap i can print the selected key by using get but when i use containskey in an if statement it is not foundi know the key is present in the map but it keeps returning false any ideas peoplemy codepublic static boolean checklowerstructuralsupportlocation location boolean hassupport false location supportinglocation new locationlocationgetx locationgety locationgetz 1 systemoutprintln levelsgetsupportinglocationgetzgetlevelsites2getsupportinglocation works if levelsgetsupportinglocationgetzgetlevelsites2containskeysupportinglocation hassupport true else hassupport false return hassupporthere is the code for the location classpublic class location protected int x protected int y protected int z public locationint xaxis int yaxis int zaxis this x xaxis this y yaxis this z zaxis public void equals not implemented yet public void hashcode not implemented yet public string tostring string locationstring integertostring x integertostring y integertostring z return locationstring public void setxint xaxis this x xaxis public int getx return this x public void setyint yaxis this y yaxis public int gety return this y public void setzint zaxis this z zaxis public int getz return this z,['java'] +19789,call pthread cond broadcast with mutex held or not with a pthread cond t we have to associate a mutex when signalling the condition i have seen code such aspthread mutex lockmutexcode that makes condition truepthread cond broadcastcondpthread mutex unlockmutexand pthread mutex lockmutexcode that makes condition truepthread mutex unlockmutexpthread cond broadcastcondwhich one is the proper way does it matter,['c'] +19790,sanity check floats as primary keys i am working with an old sql server 20 database mixing some of it is information with a new app i am building i noticed some of the primary keys in several of the tables are floats rather than any type of ints they are not foreign keys and are all unique i cannot think of any reason that anyone would want to make their unique primary key ids floats but i am not a sql expert by any means so i guess what i am asking is does whoever designed this fairly extensive database know something i do not,['sql'] +19794,is there a way to draw colored text using the uikit addition for nsstring on the iphone is there a way to draw colored text using the uikit addition for nsstring on the iphone,"['iphone', 'objective-c']" +19805,is it better to call tolist or toarray in linq queries i often run into the case where i want to eval a query right where i declare it this is usually because i need to iterate over it multiple times and it is expensive to compute for examplestring raw var lines from l in rawsplitn let ll ltrim where stringisnulloremptyll select lltolistthis works fine but if i am not going to modify the result then i might as well call toarray instead of tolisti wonder however whether toarray is implemented by first calling tolist and is therefore less memory efficient than just calling tolistam i crazy should i just call toarray safe and secure in the knowledge that the memory would not be allocated twice,['.net'] +19818,how to thisplay html as inline element this is probably a basic htmlcss questioni have a simple onebutton form that i would like to thisplay inline inside paragraph textpread this sentence form stylethisplayinline input stylethisplayinline typesubmit valueor push this button formpeven though form has stylethisplayinline attribute i get a linebreak before the form is there a way to get rid of itcan form elements appear inside p,"['html', 'css']" +19821,find functions explicitly defined in a module python ok i know you can use the dir method to list everything in a module but is there any way to see only the functions that are defined in that module for example assume my module looks like thisfrom datetime import date datetimedef test return this is a real methodeven if i use inspect to filter out the builtins i am still left with anything that was imported eg i will seedate datetime testis there any way to exclude imports or another way to find out whats defined in a module,['python'] +19833,c argument validation nullempty strings i do not know how many countless times i have had to write code to validate string argumentspublic roomnamestring name if stringisnulloremptyname throw new argumentexceptioncannot be empty name is there anyway to avoid this is there some attribute or designbycontract mechanism to avoid this is there no way to saypublic roomnamenotnulloremptystring namewithout having to actually create that type,['c#'] +19835,python lambda problems whats going on here i am trying to create a list of functionsdef fab return abfuncs for i in range010 funcsappendlambda xfixthis is not doing what i expect i would expect the list to act like thisfuncs33 9funcs05 0but all the functions in the list seem to be identical and be setting the fixed value to be 9funcs33 27funcs31 9funcs26 54any ideas,['python'] +19836,how can i select an element by name with jquery have a table column i am trying to expand and hide jquery seems to hide the td elements when i select it by class but not by element name for example why does boldhide selecting by class workstcol1hide select by element name does not worknote the html below the second column has the same name for all rows how could i create this collection using the name attributetr tddata1td td nametcol1 classbold data2tdtrtr tddata1td td nametcol1 classbold data2tdtr tr tddata1td td nametcol1 classbold data2tdtr,"['javascript', 'jquery', 'html']" +19839,will a mac mini suffice for an iphone development machine so the past two clients i have been at all the talk has been about creating an iphone app and i would not lie i want to make one or at least learn how to make themi have never owned a mac so i have no idea how their os functionsworksperforms whatever i am a net developer and build my own gaming rigs at home but as far as mac hardware goes i am cluelessi am wondering if any iphone devs out there can share their insight on their machines i am assuming it is comparable i am looking at a mac mini 20ghz duo core intel 2gb ramthis seems fine for a dev machine it beats my awful machine at worklet me know guys and thanks again in advance,['iphone'] +19848,mvc c simplest possible implementation my first try of mvc am trying to implement a simple example inspiration from here have i got this pattern yetview hey controller the user just told me he wants the first personcontroller hmm having checked his credentials he is allowed to do that hey model i want you to get me the first personmodel first person got it back to you controllercontroller here i will collect the new set of data back to you viewview cool i will show the first person to the user nowviewnamespace winformmvc public partial class form1 form controller cont new controller public form1 initializecomponent private void button1 clickobject sender eventargs e textbox1text contcheckpermissionsandgetfirstperson controllerpublic class controller public string checkpermissionsandgetfirstperson string returnvalue if checkpermissions model m new model returnvalue mgetfirstperson return returnvalue public bool checkpermissions return true modelpublic class model public string getfirstperson return bill smith,['c#'] +19849,cannot send email to addresses at my own domain i have a simple php script on my domain that sends me an emailtomail this works i get the email at my gmailtomail this does not i get nothingmailtomail subject message headerwhat setting to i change to fix this,['php'] +19853,size t can not be found by g41 or others on ubuntu 81 this has happened before to me but i cannot remember how i fixed iti cannot compile some programs here on a new ubuntu install something is awry with my headersi have tried g41 and 43 to no availg g frepo diz linux iusrincludelinux iusrinclude iinclude c qlisttestcppusrincludelibioh332 error asize ta does not name a typeusrincludelibioh336 error asize ta was not declared in this scopeusrincludelibioh364 error asize ta has not been declaredusrincludelibioh373 error asize ta has not been declaredusrincludelibioh493 error asize ta does not name a typeusrincludestdioh294 error asize ta has not been declaredthe fileinclude stdiohinclude stdlibhinclude stringhinclude unistdhubuntuworkzpksrc cat usrincludelinuxtypesh grep size ttypedef kernel size t size ttypedef kernel ssize t ssize ttypesh is definitely in the path and is getting picked up i verified by changing the file name and get an error its missingdoes anyone have any ideas i would really appreciate the help,['c++'] +19869,delete a null pointer does not call overloaded delete when destructor is written class widget public widget coutwidgetendl widget coutwidgetendl void operator newsize t sz throwbad alloc coutoperator newendl throw bad alloc void operator deletevoid v coutoperator deleteendl int main widget w 0 try w new widget catchbad alloc coutout of memoryendl delete w getch return 1in this code delete w does not call the overloaded delete operator when the destructor is there if the destructor is omitted the overloaded delete is called why is this sooutput when widget is written operator new out of memory output when widget is not written operator new out of memory operator delete,['c++'] +19871,svg draggable using jquery and jquerysvg i have an html 5 page where i load an svg circle when i click on the circle i create another small circle where i click i want to be able to drag the second circle but cant seem to do it with jqueryui draggablei am able to move the circle by accessing its cx and cy attributes so there must be a way to drag it doctype html html headtitletitlelink hrefcssresetcss relstylesheet typetextcsslink hrefcsslayoutcss relstylesheet typetextcsslink hrefcstylecss relstylesheet typetextcscript srcjsjqueryjs typetextjavascript scriptscript srcjsjquerysvgjquerysvgjs typetextjavascript scriptscript srcjsjqueryuijs typetextjavascript scriptscript typetextjavascript jquerydocumentreadyfunction targetsvgonload drawinitial circleclickfunctione drawshapee var shape thisid dragmousedownfunctione var shape thisid thissetattributecx epagex thissetattributecy epagey function drawinitialsvg svgaddsvginline function drawshapee var svg targetsvgget resulttexteclientx epagex var dragme svgcircleeclientx eclienty 5 fill green stroke red strokewidth 3 class drag dragmedraggablescriptheadbody div idtarget div svgsvg idsvginline svgcircle idcirc11 classarea cx75 cy75 r50 strokeblack strokewidth2 fillred svgsvg div idresult fdivbodyhtml,['jquery'] +19872,how to implement a cocoabased adobe photoshop plugin cocoa used to work on cs3 with the trick of putting a cocoa bundle inside the main carbon plugin bundle loading it from carbon and issuing a nsapplicationload that is because photoshop cs3 was carbononly and used to unload the plugin bundles photoshop cs4 uses cocoa and has its own nsautorelease pool in place on the main thread on photoshop cs4 very simple windowbased xibsnibs loaded by a nswindowcontroller work out of the boxbut just add a binding to a control on the window and youll get funny crashes optionally when you close the window or the second time you use the plugin or even when closing photoshop itselfwhy everything seem to work well until i use some advanced cocoa features i am stuckedit i have really found myself the solution to the broader problem how to use cocoa in a photoshop cs3cs4 plugin see below,['objective-c'] +19877,why do i always get the same sequence of random numbers with rand this is the first time i am trying random numbers with c i miss c here is my codeint i j 0fori 0 i 10 i j rand printfj dn jwith this code i get the same sequence every time i run the code but it generates different random sequences if i add srandsomevalue before the for loop can anyone explain why,['c'] +19884,whats the difference between the httpruntime cache and the httpcontext cache i know there is a very similar question here but i was hoping to get a better explination why would i ever use httpcontextcache instead of httpruntimecache if the httpcontext really uses the httpruntimecache behind the scenesin the article simulate a windows service using aspnet to run scheduled jobs omar uses the httpcontext to store his cache items but when jeff atwood implemented it here he chose to use the httpruntime instead obviously in this particular situation it makes sense since since you do not have to do a web request to add the cache item back into the httpcontexthowever i am looking for some good pointers as to when to use one versus the other,['asp.net'] +19896,do adonet datatables have indexes i am using vsts 2008 c net 35 sql server 2008 adonet if i load a table from a database by using a datatable of adonet and in the database table i defined a couple of indexes on the table my question is whether on the adonet datatable there is related index the same as the indexes i created on physical database table to improve certain operation performance on datatablethanks in advancegeorge,"['c#', '.net']" +19908,persistent hashtable for ruby programs i need a small unstructured database for my ruby scripts not sqlite something more like a persistent hashtables would work perfectly as long as it can store basic ruby structures arrays strings hashes etc all serializable and would not get corrupted when ruby scripts crashi know there is plenty of solutions like that for perl with tiehash so there is probably some gem like that for ruby what gem would that beedit as far as i can tell pstore and yaml solutions are based on reading unmarshaling remarshaling and writing entire database on every change that not only requires all of it to fit memory it is on2 so neither of them seem like a particularly good solution,['ruby'] +19912,how to get the values of an enum into a selectlist imagine i have an enumeration such as this just as an examplepublic enum direction horizontal 0 vertical 1 diagonal 2how can i write a routine to get these values into a systemwebmvcselectlist given that the contents of the enumeration are subject to change in future i want to get each enumerations name as the option text and its value as the value text like thisselect option value0horizontaloption option value1verticaloption option value2diagonaloptionselectthis is the best i can come up with so far public static selectlist getdirectionselectlist array values enumgetvaluestypeofdirection listlistitem items new listlistitemvalueslength foreach var i in values itemsaddnew listitem text enumgetnametypeofdirection i value itostring return new selectlistitems however this always renders the option text as systemwebmvclistitem debugging through this also shows me that enumgetvalues is returning horizontal vertical etc instead of 0 1 as i wouldve expected which makes me wonder what the difference is between enumgetname and enumgetvalue,['c#'] +19913,how to make php script run another php script i am trying to do exactly the same thing as in my previous python question but in php see my previous answered questionphp script from previous question does something and then runs another php script on the same server does something and then quits while second script still continues its work how do i achieve thisplease note that php script is also a web page at the same time so maybe we can use it like in previous question where answer to my question was snippet that made python just open url instead of running subprocess although i do not have a clue if that is useful information maybe it is different in php i am not too experienced in php and that i want to make each scripts independent so if first php script will finish i would like second php script to continue working even though first one endedwhat do you think is most elegant way to do this would echoing iframe work or should i do this differently,['php'] +19934,basic file upload in gwt i am trying to figure out how to upload one file using gwts fileupload widget i am using gwt and google appengine with java but i would like to upload file to my own linux server i have the following code already but now i cannot figure out how to submit my file to the google appserver server and save it to another serverpublic class fileuploader private controlpanel cp private formpanel form new formpanel private fileupload fu new fileupload public fileuploadercontrolpanel cp thiscp cp thiscpsetprimaryareagetfileuploaderwidget suppresswarningsdeprecation public widget getfileuploaderwidget formsetencodingformpanelencoding multipart formsetmethodformpanelmethod post formsetaction what should i put here verticalpanel holder new verticalpanel fusetnameupload holderaddfu holderaddnew buttonsubmit new clickhandler public void onclickclickevent event gwtlogyou selected fugetfilename null formsubmit formaddsubmithandlernew formpanelsubmithandler public void onsubmitsubmitevent event if equalsignorecasefugetfilename gwtloguploading file null now what else eventcancel cancel the event formaddsubmitcompletehandlernew formpanelsubmitcompletehandler public void onsubmitcompletesubmitcompleteevent event windowalerteventgetresults formaddholder return form now what do i need to do next what do i need to put in webxml and how do i write my servlet so i can store file and return url of that object if possible,['java'] +19937,undefined reference error for template method this has been driving me mad for the past hour and a half i know it is a small thing but cannot find whats wrong the fact that it is a rainy friday afternoon of course does not helpi have defined the following class that will hold configuration parameters read from a file and will let me access them from my programclass vaconfig friend stdostream operator stdostream lhs const vaconfig rhsprivate vaconfig static stdstring configfilename static vaconfig pconfiginstance static tixmldocument pxmldoc stdmapstdstring stdstring valuehashpublic static vaconfig getinstance static void setconfigfilename stdstring filename configfilename filename virtual vaconfig void readparameterset stdstring parametergroupname templatetypename t t readparameter const stdstring parametername templatetypename t t convert const stdstring value where the method convert is defined in vaconfigcpp astemplate typename tt vaconfigconvert const stdstring value t t stdistringstream iss value stdistringstreamin iss t return tall quite simple but when i test from my main program usingint y parametersconvertint5i get an undefined reference to int vaconfigconvertint compilation error ditto for readparameterlooked at a lot of template tutorials but coul not figure this out any ideas,['c++'] +19945,how to handle screen orientation change when progress dialog and background thread active my program does some network activity in a background thread before starting it pops up a progress dialog the dialog is thismissed on the handler this all works fine except when screen orientation changes while the dialog is up and the background thread is going at this point the app either crashes or deadlocks or gets into a weird stage where the app does not work at all until all the threads have been killedhow can i handle the screen orientation change gracefullythe sample code below matches roughly what my real program doespublic class myact extends activity implements runnable public progressdialog mprogress ui has a button that when pressed calls send public void send mprogress progressdialogshowthis please wait please wait true true thread thread new threadthis threadstart public void run threadsleep10 message msg new message mhandlersendmessagemsg private final handler mhandler new handler override public void handlemessagemessage msg mprogressthismiss stackewindowmanager 244 activity myact has leaked window comandroidinternalpolicyimplphonewindowdecorview433b7150 that was originally added hereewindowmanager 244 androidviewwindowleaked activity myact has leaked window comandroidinternalpolicyimplphonewindowdecorview433b7150 that was originally added hereewindowmanager 244 at androidviewviewrootinitviewrootjava178ewindowmanager 244 at androidviewwindowmanagerimpladdviewwindowmanagerimpljava147ewindowmanager 244 at androidviewwindowmanagerimpladdviewwindowmanagerimpljava90ewindowmanager 244 at androidviewwindowlocalwindowmanageraddviewwindowjava393ewindowmanager 244 at androidappdialogshowdialogjava212ewindowmanager 244 at androidaprogressdialogshowprogressdialogjava103ewindowmanager 244 at androidaprogressdialogshowprogressdialogjava91ewindowmanager 244 at myactsendmyactjava294ewindowmanager 244 at myact4onclickmyactjava174ewindowmanager 244 at androidviewviewperformclickviewjava2129ewindowmanager 244 at androidviewviewontoucheventviewjava3543ewindowmanager 244 at androidwidgettextviewontoucheventtextviewjava4664ewindowmanager 244 at androidviewviewthispatchtoucheventviewjava3198i have tried to thismiss the progress dialog in onsaveinstancestate but that just prevents an immediate crash the background thread is still going and the ui is in partially drawn state need to kill the whole app before it starts working again,['android'] +19951,how to run function of parent window when child window closes i have asked this question before and the problem was half solved in the sense i was helped to find out that javascript has some tough security in placewhat i learnt a parent window opens a child window the child window redirects to a different domain and gets redirected back it attempts to fire off a function of the parent window upon closing itself windowopenerstartloadthis leads to a permissions security problem and will not workhalf new problem how can i get a window to open a child window and when it closes run a function in the parent window i need a very efficient way of doing this as this will be happening a lotthank you for any help,['javascript'] +19961,how do startstop services using net stop command in c how do startstop services using net stop command in cfor exampledim pstart as new procestartinfodim path as string environmentgetfolderpathenvironmentspecialfoldersystemdim p as new processpstartfilename path cmdexepstartuseshellexecute falsepstartcreatenowindow truepstartworkingdirectory pathpstartfilename cmdexepstartarguments net start mysqlpstartinfo pstartpstarti have used process class but no result,['c#'] +19978,php remove url from string if i have a string that contains a url for examples sake well call it url such asurl here is a funny site how do i remove the url from the stringdifficulty is urls might also show up without the http such as url here is another funny site wtinyurlcom5there is no html present how would i start a search if http or w exists then remove the textnumberssymbols until the first space,['php'] +19990,android screen timeout i know its possible to use a wakelock to hold the screen cpu ect on but how can i programmatically change the screen timeout setting on an android phone,"['java', 'android']" +19996,xcode question quickly jump to a particular selectorclasymbol what is the quickest way to jump to a particular symbolselectorclass in xcode i am looking for keyboard shortcuts preferablyright now i know two ways of doing thisaopen quicklya click on the symbols dropdown menu at the top of the editor select the selector to jump to itclick on aproject symbolsa in the agroups and filesa section on the left sidebar and type in a name in the search text field in the top right of the xcode windowis there a quicker way of doing this if i could even assign a shortcut to jump to the aproject symbolsa that would suffice for me alternatively if i can find a keyboard shortcut to jump to the symbol dropdown above an editor that would do it to for experienced xcode programmers what do you use to jump to a symbol,['objective-c'] +20004,which is the best c compiler can a c compiler produce a not so good binary you can think here of the outputs robustness and performance is there such a thing as the best c compiler to use if not what are the strong points and of course the notsostrong known bugs and issues points of the wellknown compilers g intel c compiler visual c etcare there documented cases when a compiler produced incorrect output which resulted in a failure of missioncritical software,['c++'] +20014,casting object array to integer array error whats wrong with the following codeobject a new object1integer b1a0binteger c integer athe code has the following error at the last line exception in thread main javalangclasscastexception ljavalangobject cannot be cast to ljavalanginteger,['java'] +20015,how to add a class to dom element in javascript how to add a class for the divvar new row documentcreateelementdiv,['javascript'] +20018,can javaxpersistencequerygetresultlist return null and if so under what circumstancesjavadoc and jpa spec says nothing,['java'] +20022,memoryefficient c strings interning ropes copyonwrite etc my application is having memory problems including copying lots of strings about using the same strings as keys in lots of hashtables etc i am looking for a base class for my strings that makes this very efficienti am hoping forstring interning multiple strings of the same value use the same memorycopyonwrite i think this comes for free in nearly all stdstring implementationssomething with ropes would be a bonus for o1ish concatenationmy platform is g on linux but that is unlikely to matterdo you know of such a library,['c++'] +20029,techniques for writing a scalable website i am new in the website scalability realm can you suggest to me some the techniques for making a website scalable to a large number of users,"['php', 'mysql']" +20038,how to read a singly linked list backwards one method which i can think of is to reverse the list and then read itbut this involves changing the list which is bador i can make a copy of the list and then reverse it but this uses additional on memoryis there any better method which does not use extra memory and does not modify the list and runs in on timereverse linked list code is something like this in cvoid reverse node head node prev null node current head node nextnode null while currentnull nextnode currentnext currentnext prev prevcurrent current nextnode head prevrecursive solution is void readbackward node n if nnull return else readbackwardnnext consolewritelinendata,['c#'] +20039,c interlocked exchange i have a bit of my game which looks like thispublic static float timefloat somevalue 123interlockedexchangeref time somevaluei want to change time to be a uint32 however when i try to use uint32 instead of float for the values it protests that the type must be a reference type float is not a reference type so i know it is technically possible to do this with nonreference types is there any practical way to make this work with uint32,['c#'] +20040,whats the best way to create a short hash similiar to what tiny url does i am currently using md5 hashes but i would like to find something that will create a shorter hash that uses just azaz09 it only needs to be around 510 characters long is there something out there that already does this updatei like the crc32 hash is there a clean way of calculating it in netupdate2 i am using the crc32 function from the link joe provided how can i convert the uint into the characters defined above,"['c#', '.net']" +20066,i need a regex that validates for minimum 7 digits in the given string i wanna validate a phone numbermy condition is that i want mimimum 7 numbers in the given string ignoring separators x paranthesesactually i want to achieve this function in regexfuncstring bool validate s stochararraywherecharisdigitcount 7funcstring bool regexvalidate s systemtextregularexpressionsregexismatchs regex pattern should come herestring x asda 1234567 sdfasdfstring y asda sdfa 123456 sdfasdfbool xx validatex truebool yy validatey falsethe purpose of my need is i want to include this regex in an aspregularexpressionvalidator,"['c#', '.net']" +20068,speech recognition on iphone i need to develop an iphone application which recognizes speech and based on the result it performs further tasksi know iphone 30 does not support speech recognition and i need to implement speech recognition software on the server side i know this thing only since i am newbie i do not know how to deal with thatmean which software i need to buy and implement it at server side and how to use that service,['iphone'] +20076,explicit keyword on multiarg constructor i recently came across some weird looking class that had three constructorsclass class public explicit classint classanotherclass explicit classyetanotherclass anotherclass this does not really make sense to me i thought the explicit keyword is to protect compiler chosen construction from a foreign typeis this allowed if it it what does it mean,['c++'] +20087,where do i find the definition of size t i see variables defined with this type but i do not know where it comes from nor what is its purpose why not use int or unsigned int what about other similar types void t etc,"['c++', 'c']" +20094,jpahibernate embedding an attribute i am having a trouble mapping an embedded attribute of a class i have created some classes that are similar to what i am trying to do to illustrate basically i have an embeddable class hierarchy that uses inheritance the top level class part number has only one attribute and the extending classes add no attributes to the part number class they only add some validationlogichere is what i meanpartentitytablenamepartpublic class part private integer id private string name private partnumber partnumber id generatedvaluestrategygenerationtypesequence public integer getid return id public void setidinteger id thisid id columnnamepart name public string getname return name public void setnamestring name thisname name embedded public partnumber getpartnumber return partnumber public void setpartnumberpartnumber partnumber thispartnumber partnumber partnumberembeddablepublic abstract class partnumber protected string partnumber private string generalpartnumber private string specificpartnumber private partnumber public partnumberstring partnumber thispartnumber partnumber columnname part number public string getpartnumber return partnumber public void setpartnumberstring partnumber thispartnumber partnumber param partnumber return public boolean validatestring partnumber do some validation return true returns the first half of the part number return generalpartnumber transient public string getgeneralpartnumber return generalpartnumber returns the last half of the part number which is specific to each car brand return specificpartnumber transient public string getspecificpartnumber return specificpartnumber ford partnumberpublic class fordpartnumber extends partnumber ford part number is formatted as 12341234 param partnumber public fordpartnumberstring partnumber superpartnumber validatepartnumber nonjavadoc see comtestpartnumbervalidatejavalangstring override public boolean validatestring partnumber do some validation return true nonjavadoc see comtestpartnumbergetgeneralpartnumber override public string getgeneralpartnumber return partnumber nonjavadoc see comtestpartnumbergetspecificpartnumber override public string getspecificpartnumber return partnumber chevy partnumberpublic class chevypartnumber extends partnumber chevy part number is formatted as 12341234 param partnumber public chevypartnumberstring partnumber superpartnumber validatepartnumber nonjavadoc see comtestpartnumbervalidatejavalangstring override public boolean validatestring partnumber do some validation return true nonjavadoc see comtestpartnumbergetgeneralpartnumber override public string getgeneralpartnumber return partnumber nonjavadoc see comtestpartnumbergetspecificpartnumber override public string getspecificpartnumber return partnumber of course this does not work because hibernate ignores the inheritance hierarchy and does not like the fact that partnumber is abstract is there some way to do this using jpa or hibernate annotations i have tried using the inheritance jpa annotationi am not able to refactor the partnumber part of the hierarchy because the original developer wants to be able to extend partnumber with and many xpartnumber classesdoes anyone know if anything like this will be a part of the jpa 20 or a new version of hibernate,['java'] +20095,how do i get the current year using sql on oracle i need to add the current year as a variable in an sql statement how can i retrieve the current year using sqlie between to date0101currentyear 0 ddmmy hh24miss and to date3112currentyear 235959 ddmmy hh24miss,['sql'] +20096,loading files with classloader this problem has been bugging me for a while i have to load a couple files in my java app and the only way i got working so far looks like thisurl hsurlifsystemgetpropertyosnametolowercasecontainswindows hsurl new urlfile systemgetpropertyuserdir helpsetshelpsethselse hsurl new urlfile systemgetpropertyuserdir helpsetshelpsethsbut this is ugly and terrible for a while i thought i had this workinghsurl classloadergetsystemresourcehelpsetshelpsethsbut that no longer works for some reason i must have changed something and not noticed it returns nullshould i be using getresource instead of getsystemresource if so why is getsystemresource static but not getresourcei am using eclipse and i have tried including the folder in the build path classpath and not including it it does not seem to make a difference,['java'] +20103,how can i read and parse csv files in c i need to load and use csv file data in c at this point it can really just be a commadelimited parser ie do not worry about escaping new lines and commas the main need is a linebyline parser that will return a vector for the next line each time the method is calledi found this article which looks quite promising 35 0libsspiritexamplefundamentallist parsercppi have never used boosts spirit but am willing to try it but only if there is not a more straightforward solution i am overlooking,['c++'] +20105,c how to determine if https how do i determine and force users to view my website using https only i know it can be done through iis but want to know how its done programmatically,['c#'] +20110,what is the best irc network for java java is efnet the network to be on in java or are there other more active networks,['java'] +20111,c actiondelegate style question what is considered better style for an event definitionpublic event actionobject double onnumberchangedorpublic delegate void dnumberchangedobject sender double numberpublic event dnumberchanged onnumberchangedthe first takes less typing but the delegate one gives names to the parameters as i type this i think number 2 is the winner but i could be wrongedit a different third approach is the winner read below,"['c#', '.net']" +20124,how to let curl use same cookie as the browser from php i have a php script that does an http request on behalf of the browser and the outputs the response to the browser problem is when i click the links from the browser on this page it complains about cookie variables i am assuming it needs the browsers cookies for the sitehow can i intercept and forward it to the remote site,['php'] +20127,how do i determine which monitor my net windows forms program is running on i have a c windows application that i want to ensure will show up on a second monitor if the user moves it to one i need to save the main forms size location and window state which i have already handled but i also need to know which screen it was on when the user closed the applicationi am using the screen class to determine the size of the current screen but i cannot find anything on how to determine which screen the application was running onedit thanks for the responses everyone i wanted to determine which monitor the window was on so i could do proper bounds checking in case the user accidentally put the window outside the viewing area or changed the screen size such that the form wouldnt be completely visible anymore,"['c#', '.net']" +20144,can the android handset led be manipulated without using a notification object i want to control the led on an android device with more control than is offered by the notification class notifications allow you to change the rate of flashing eg 300 milliseconds on 10 milliseconds off but that is itessentially i would like to turn the led on and off at will at arbitrary times does anyone know if this is possible the api does not seem to say so does it depend on the specific hardware,['android'] +20149,jquery and questions i am modifying some code that has a lot of jquery but i am not sure what some of the jquery statements are doingat the top of the jquery code there is jquerynoconflict1 i understand that but then there is a some code that hasscript typetextjavascriptfunction documentreadyfunction jqueryfnfixemail function return thiseachfunction var s this code scripti get that jquery is used because of the noconflict whats the parameter 2 in another function they use script typetextjavascriptjqueryfunctionvar jqueryvar cc mode teaserfeaturevisible trueloader p classloadinganimationimg height32 src configxoimgurl imagesajaxloadergif width32 p more code scriptso they are setting to the jquery from noconflict but why could they have just used jquery3 there is a plugin that i want to use that is initialized by var j jquerynoconflict var jdocumentreadyfunction jhistoryinitpageload jarelhistoryclickfunction more code i understand what the noconflict does but what does var do,['jquery'] +20153,c singleton with constructor that accepts parameters i want to create a static class or singleton class that accepts a reference to another object in its constructor static classes are out but i figured i could create a singleton that accepts parameters in its constructor so far i have not had any luck figuring out or googling the syntax is this possible if so how do i do it sorry for no example in the initial post i wrote it in a rush i have the feeling that my answer is already in the replies but heres some clarification of what i want to doi want to create a single instance of a specific type said singleton but that single instance of the type needs to hold a reference to a different object for example i might want to create a singleton status class which owns a stringbuilder object and a draw method that can be called to write said stringbuilder to the screen the draw method needs to know about my graphcisdevice in order to drawso what i want to do it thispublic class statusprivate static status instanceprivate stringbuilder messagesprivate graphicsdevice gdeviceprivate statusstring message graphicsdevice device messagesappendmessage gdevice device the following is not threadsafe this constructor part is what i am trying to figure outpublic static status instance graphicsdevice device get if instance null instance new statustest message device return instance public void updatemessagepublic void draw draw my status to the screen using gdevice and messages all over the code i retrieve my status singleton and call its updatemessage methodprivate status status statusinstance pass reference to graphicsdevice statusupdatemessagefoothen in my main class i also retrieve the singleton and draw it statusdrawyes this means that wherever i retrieve the singleton i need to do so by passing in the reference to the graphicsdevice in case it is the first time i instantiate the singleton and i couldwould use different means to retrieve something as fundamental as the graphicsdevice in my singleton class for example register a service elsewhere and get that service in the status class this example got pretty contrived i am trying to figure out if something like this pattern is possible in the first place,['c#'] +20155,does python have anonymous classes i am wondering if python has anything like the c anonymous classes feature to clarify heres a sample c snippetvar foo new x 1 y 2 var bar new y 2 x 1 fooequalsbar truein python i would imagine something like thisfoo recordx 1 y 2bar recordy 2 x 1foo bar truethe specific requirement is being able to create an object with specified fields in expression context eg usable in lambdas and other places where statements are not allowed with no additional external declarations and ability to access individual components by name via the normal member access syntax foobar the created object should also implement structural comparison by component names not by position as tuples doin particular tuples is not it because their components are not named classes is not it because they require a declaration dicts is not it because they have undesired foobar syntax to access componentsnamedtuple is not it because it still requires a name even if you define the type inline and the comparison is positionbased not namebased in particular def foo return namedtuplefoo x yx 1 y 2 def bar return namedtuplefoo y xx 1 y 2 foo bar false because fields are compared in order and not by name true would be desired insteadi know how to write such a thing in python if needed but i would like to know if there is anything like that in the python standard library or any popular thirdparty librarieseditjust for the sake of it heres a singleexpression solution that combines two very informative answers by ken and alanlcode yielding structural equality without any extra outside declarationstype init lambda self kwargs self dict updatekwargs eq lambda self other self dict other dict x 1 y 2technically it satisfies all the requirements of the question but i sincerely hope that noone ever uses it i definitely would not,['python'] +20157,how do you drop a default value or similar constraint in tsql i know the syntaxalter table thetable drop constraint thedefaultconstraintbut how to i drop the default constraint when i do not know its name that is it was autogenerated at create table time,['sql'] +20158,why do we need typename here templateclass tclass set public void insertconst t item void removeconst t itemprivate stdlistt reptemplatetypename tvoid settremoveconst t item typename stdlisttiterator it question here stdfindrepbeginrependitme ifitrepend reperaseitwhy the typename in the remove is needed,['c++'] +20164,how to lock a critical section in django i cannot find a good clean way to lock a critical section in django i could use a lock or semaphore but the python implementation is for threads only so if the production server forks then those will not be respected does anyone know of a way i am thinking posix semaphores right now to guarantee a lock across processes or barring that a way to stop a django server from forking,['python'] +20181,how do i share an object between uiviewcontrollers on iphone my application is a tab bar application with a separate view controller for each tabi have an object in my first view controller a which contains all my stored application data please ignore nsuserdefaults for this which needs to be accessed by the second view controller b when i press a button on it how can i achieve this in the best way,"['iphone', 'objective-c']" +20187,any ideas why qhash and qmap return const t instead of const t unlike stdmap and stdhash map corresponding versions in qt do not bother to return a reference is not it quite inefficient if i build a hash for quite bulky classeditespecially since there is a separate method value which could then return it by value,['c++'] +20204,tiled background image can i do that easily with uiimageview i have a fullscreen background image that is tiled ie it has to be reproduced a few times horizontally and vertically in order to make a big one like in the browsers on ugly home pages is uiimageview my friend for this,['iphone'] +20205,setting the default page for aspnet visual studio server configuration when i build and run my application i get a directory listing in the browser also happens for sub folders and i have to click on indexaspx it is making me crazyvisual studio 2008aspnet development server 90,['asp.net'] +20215,how do i use jquery to select all children except a select element i have a div let us say the id is container with many elements in it including a select element i would like to select all everything in the div except the selectthings i have tried container notselectcontainer notselectoridput a div around the select andcontainer notselectorcontainercontainer notselectorcontainer container notselectorcontainer selectorcontainer also tried without wildcard descendant selector so just like all the above butcontainernotselectorid,['jquery'] +20216,how can i split a comma delimited string into an array in php i need to split my string input into an array at the commashow can i go about accomplishing thisinput98,['php'] +20217,python documentation generator i am looking for a documentation generator for python i am familiar with javadoc and i tried doxygen but it seems quite unfit and counterintuitive for pythonany ideasedit apart from the excellent answers below you can also consult wikipedias exhaustive comparison of documentation generators,['python'] +20227,how to find the width of a string in pixels in win32 can you measure the width of a string more exactly in win32 than using the gettextmetrics function and using tmavecharwidthstrsize,['c++'] +20230,how to get network adapter stats in linuxmac osx i am looking for a way to get hold of network stats in c on linux and macosx specifically i need to monitor the number of bytes uploaded and downloaded from each network adapter on the system i do not need to do packet inspection or differentiate between protocols just a total bytes counter which i can poll at intervals would be fine in windows i can do this using the iphlpapidll library via getiftable to list the network adapters and getifentry to read the stats but i cannot find the linuxosx equivalents my knowledge of c is fairly basic so i would appreciate a solution that is not too involved any help would be much appreciated,['c'] +20231,how can i auto increment the c assembly version via our ci platform hudson myself and my group are horrendous at incrementing assembly version numbers and we frequently ship assemblies with 10 versions obviously this causes a lot of headacheswere getting a lot better with our practices via our ci platform and i would really like to set it up to auto increment the values within the assemblyinfocs file so that the versions of our assemblies are auto updated with the code changes in that assemblyi had previously setup before we found hudson a way to increment the value through either msbuild or the command line cannot remember but with hudson that will update the svn repository and trigger another build that would result in a slow infinite loop as hudson polls svn every houris having hudson increment the version number a bad idea what would be an alternative way to do itideally my criteria for a solution would be one thatincrements the build number in assemblyinfocs before a buildonly increments the build number in assemblies that have changed this may not be possible as hudson wipes out the project folder every time it does a buildcommits the changed assemblyinfocs into the code repository currently visualsvndoes not cause hudson to trigger a new build the next time it scans for changesworking this out in my head i could easily come up with a solution to most of this through batch files commands but all of my ideas would cause hudson to trigger a new build the next time it scans i am not looking for someone to do everything for me just point me in the right direction maybe a technique to get hudson to ignore certain svn commits etceverything i have found so far is just an article explaining how to get the version number automatically incremented nothing takes into account a ci platform that could be spun into an infinite loop,['.net'] +20232,is it possible to go into ipython from code for my debugging needs pdb is pretty good however it would be much cooler and helpful if i could go into ipython is this thing possible,['python'] +20242,c what would you name an ienumerable class when reading this question i started to wonder a bit say you have these twoclass productcollection icollectionproductclass productlist ilistproductwhat would you call one that were an ienumerableproductclass product ienumerableproductbefore i read that other question i might have called it a productcollection actually but taking the new info into account that would have been a bit misleading since it does not implement icollectionproduct could you call it productsvar products new products products isare productsalmost works but sounds a bit strange what would you call it,['.net'] +20244,how to add reference in c i am new to c and there is something i just completely do not get in c if i want to use an external library log4net for example i just add a reference to the log4net dll and its members are automatically available to me and in intellisense how do i do that in nonmanaged c,['c++'] +20250,why use a using statement with a sqltransaction i have been running into some problems concerning a sqltransaction i am using in my code during my googling i see many people using a using statement with a sqltransactionwhat is the benefit andor difference of using this type of statement with a sqltransactionusing sqlconnection cn new sqlconnection using sqltransaction tr cnbegintransaction some code trcommit currently my code looks like thissqlconnection cn new sqlconnectionconfigurationmanagerappsettingst3cnopensqltransaction tr cnbegintransactiontry some code trcommit cnclosecatchexception ex trrollback cnclose throw exwhat is the advantage of one way over the other,['c#'] +20252,how to suppress java warnings for specific directories or files such as generated code i am using a parser generator that creates somewhat ugly code as a result my eclipse project has several dozen warnings emanating from generated source files i know i can use the suppresswarning annotation to suppress particular warnings in particular elements but any annotations i add by hand will be lost when the parser generator runs again is there a way to configure eclipse to suppress warnings for a particular file or directory,['java'] +20254,ruby on rails render layout i am trying to split up a web site into two sections one which should use the application layout and one that should use the admin layout in my applicationrb i created a function as followsdef admin layout if current useris able tositeadmin render layout admin else render layout application endendand in the controllers where it might be one or the other i put before filter admin layoutthis works fine for some pages where its just text but for others i get the classic erroryou have a nil object when you did not expect ityou might have expected an instance of arraythe error occurred while evaluating nileachdoes anyone have an idea of what i am missing how should i properly use render and layout,['ruby-on-rails'] +20256,win32 api to enumerate dll export functions i found similar questions but no answer to what i am looking for so here goesfor a native win32 dll is there a win32 api to enumerate its export function names,['c++'] +20278,how can i make setuptools ignore subversion inventory when packaging a python package with a setuppy that uses the setuptoolsfrom setuptools import setupthe source thistribution created bypython setuppy sthistnot only includes as usual the files specified in manifestin but it also gratuitously includes all of the files that subversion lists as being version controlled beneath the package directory this is vastly annoying not only does it make it difficult to exercise any sort of explicit control over what files get thistributed with my package but it means that when i build my package following an svn export instead of an svn checkout the contents of my package might be quite different since without the svn metadata setuptools will make different choices about what to includemy question how can i turn off this terrible behavior so that setuptools treats my project the same way whether i am using subversion or version control it is never heard of or a bare tree created with svn export that i have created at the end of my project to make sure it builds cleanly somewhere besides my working directorythe best i have managed so far is an ugly monkeypatchfrom setuptoolscommand import sthistdel sthistfindersbut this is python not the jungle so of course i want a better solution that involves no monkeys at all how can i tame setuptools turn off its magic and have it behave sensibly by looking at the visible predictable rules in my manifestpy instead,['python'] +20283,format from ticks to date i am needing to transfer some logs which were timestamped in ticks to an xml document i would prefer the timestamps to be more specific such as july 14 2009 101804 pmi was planning to using something along the line ofdatetime logdate datetimeparselogtextlogdatetostringm dd y hhmmss tti figured this would be ok as datetimenowticks is how you can get ticks it is however returning that it is not a proper datetime format during setting logdatei am sure there is a simple solution but i just cannot come across it,['c#'] +20305,eclipse classpath entries only used for tests in maven you can have compiletime dependencies and test dependencies this is a feature i love and the m2eclipse plugin makes this available in eclipse too which is great so if i add jmockjar to my project as a test dependency it will show up on the classpath for junit tests but would not be present when i am debugging the application itselfthis is exactly what i would like to achieve now but without m2eclipse or maven is there a way to do this in plain eclipse possibly without installing any plugins,['java'] +20311,get full path of a file with fileupload control i am working on a web application which uses the fileupload control i have an xls file in the full filepath cmailidxls that i am attempting to uploadwhen i use the command fileupload1postedfilefilenamei cannot get the full filepath from my system however when i use the above command in another system it works finei also tried the following commands with no success systemiopathgetfullpathfileupload1postedfilefilename pathgetfilenamefileupload1postedfilefilename systemiopathgetdirectorynamefileupload1postedfilefilenametostring converttostringsystemiodirectorygetparentfileupload1postedfilefilenamehow can i get full path,['asp.net'] +20328,get md5 hash of big files in python i have used hashlib which replaces md5 in python 2630 and it worked fine if i opened a file and put its content in hashlibmd5 functionthe problem is with very big files that their sizes could exceed ram sizehow to get the md5 hash of a file without loading the whole file to memory,['python'] +20331,are generators threadsafe i have a multithreaded program where i create a generator function and then pass it to new threads i want it to be sharedglobal in nature so each thread can get the next value from the generatoris it safe to use a generator like this or will i run into problemsconditions accessing the shared generator from multiple threads if not is there a better way to approach the problem i need something that will cycle through a list and produce the next value for whichever thread calls it,['python'] +20334,using relative directory path in java i am trying to use a relative path to locate an executable file within a java class instead of hardcoded lines which worked but using something likefinal static string directory gglasamplesobjlinux x86fails what is the proper way of using a relative path in java,['java'] +20337,the param inverse function in javascript jquery given the following formform input namefoo valuebar input namehello valuehello worldformi can use the param construct to serialize the formparam form input foobarhellohelloworldhow can i deserialize the above string with javascript and get a hash backfor examplemagicfunctionfoobarhellohelloworld foo bar hello hello worldreference jqueryparam obj,"['javascript', 'jquery']" +20360,why can some operators only be overloaded as member functions other as friend functions and the rest of them as both why can some operators only be overloaded as member functions other as nonmember free functions and the rest of them as bothwhat is the rationale behind thosehow to remember which operators can be overloaded as what member free or both,['c++'] +20363,extension method resolution i wrote an extension method for string to get a char argument stringremovechar but when i used this it instead called the default stringremoveint methodshould not the presence of an actual method have higher priority than an implicit conversion,"['c#', '.net']" +20370,django serialization of inherited model i have a problem with serialization of django inherited models for exampleclass animalmodelsmodel color modelscharfieldmax length50class doganimal name modelscharfieldmax length50 now i want to serialize dog model with animal inherited fields obviously includedprint serializersserializexml dogobjectsalland only dog model has been serializedi can do smth like all objects listanimalobjectsall listdogobjectsallprint serializersserializexml all objectsbut it looks ugly and because my models are very big so i have to use sax parser and with such output it is difficult to parseany idea how to serialize django models with parent classedit it use to work ok before this patch has been applied and the explanation why the patch exist model saving was too aggressive about creating new parent class instances during deserialization raw save on a model now skips saving of the parent class i think there should be an option to be able to serialize local fields only by default and second option all to serialize all inherited fields,['python'] +20385,how do i convert a string into an integer in javascript how do i convert a string into an integer in javascript,['javascript'] +20398,update url on ajax call right now the biggest issue i am having with using ajax is the fact that if i use ajax on a page go to another page then use the browsers back button to go back anything that was changed with ajax is gonei have thought about using the jquery addres plugin to solve that problem but i do not like how it only amends the url with whateverhtml instead of changing it completelyideally what i would like is to have the url go from wmysitecomp2 to wmysitecomp3 when i make the relevant ajax callis this at all possible,['jquery'] +20408,google appengine session example i just enabled session in my google appenginejava gwt application and how do i use it how do i get session id and play will all good stuff from it are there any real examples of simple login page where i am just entering loginname and password then it goes to the server over rpc call authenticates against database and sends session id back to the clienti have following code already but do not know what to do nextgwt login formpublic class loginform private final loginserviceasync loginservice gwtcreateloginserviceclass verticalpanel loginvp new verticalpanel textbox logintxt new textbox textbox passtxt new textbox button loginbtn new buttonlogin public widget getloginwidget loginbtnaddclickhandlernew clickhandler public void onclickclickevent arg0 loginserviceauthenticateuserlogintxtgettext passtxtgettext new asynccallbackstring public void onfailurethrowable caught infopanelshowinfopaneltypehumanized message no connetion problem conneting to the server public void onsuccestring result infopanelshowinfopaneltypehumanized message session id your session id is result gwtlogsetting up session null string sessionid result final long duration 10 60 60 24 14 duration remembering login 2 weeks date expires new datesystemcurrenttimemillis duration cookiessetcookiesid sessionid expires null false loginvpaddlogintxt loginvpaddpasstxt loginvpaddloginbtn return loginvp rpc servletpublic class loginserviceimpl extends remoteserviceservlet implements loginservice sends back to the client session id public string authenticateuserstring login string password string sessionid new string todo figure out how to work with session id in gaej sessionid how to get session id return sessionid public boolean checkifsessionisvalidstring sessionid todo figure out how to check users credentials return true any hints in the right direction would be helpful thanks,['java'] +20419,what is f lacking for oo or imperative many times i hear that f is not suited to particular tasks such as ui use the right tool is a common phrase apart from missing tools such as a winformswpform designer i am not sure what exactly is missing in f honestly yet particularly with ui i am told that c just does it better so what are the actual differences and omissions in f when using it imperatively here is a list i came up withlots of missing tool supportf is still betayour developers do not know fi would like to not consider those points as they are not really intrinsic to fmutables need mutable or need to be ref ref needs to dereferencemutables assign with and ref uses they are both 1 more character than just val needs defaultvalueattribute to get a default valuef does not emit implicit interfaces protected members are more difficult to deal withno automatic propertiesimplemented virtual members on abstract classes require two definitionsquotationstolinqexpressiontrees produces trees slightly different than cvb annoying for apis that expect their expressions in a specific formatno stackallocf does not have the conditional operatorpointers might be considered more cumbersome in fdelegatesevents might possibly be considered more cumbersome i would argue they are easier but at a minimum they are differentno automatic type conversions like int to float or implicit castsno special syntax support for nullable cs type annotation and operator as well as using operators on nullablesno automatic upcasting to common base class or boxing ex let x obj if true then 1 else hi this would not typecheckvalues cannot be thiscarded without a warning ignore to get around itdoes not have cstyle syntax to the question which of these are a hindrance to writing imperative or oo code why short examples which ones did i miss what are the best workarounds and why are they not enoughplease note i am not talking about writing socalled idiomatic f and i am certainly not talking about functional programming i am more interested along the lines of if i were to force myself to write ui or imperativeoo code in f using f ooimperative features and class types what hurts the mostbonusif you do not know f but use c or vbnet and think it is a better tool for some situations please indicate the specific language features and syntax you find appealing,['c#'] +20437,how have your ideas about c programming practices changed in the last ten years objectoriented programmers seem to have all the fun not only are they treated to major framework revisions every two years and new and improved languages every five they also get to deal with design practices tailormade to their programming style from testdriven development to design patterns objectoriented programmers have a lot to keep up withby contrast the c programming world seems far more sedate the last major revision to the language was in 19 and the next one is likely to be far less impressive kr 2nd edition is still held up as a good introductory text by many despite being twenty years old nowif we as c programmers have developed and improved our skills and practices and i think we probably have we do not seem to be very good at communicating them we do not sell books about them post about them on blogs or organise workshops around them not in the way the rest of the software development world seems toso let us sharewhat are your preferred modern c programming practicesdo you use template libraries of long involved preprocessor macros to squeeze the last inch of performence out of hardware in the same way c programmers can do you use a allocation library like halloc to minimize the time you spend on managing memory or do you use a fullblown automatic garbage collectorof course if youve been using these things since 1987 feel free to chime in as well the point of this question is to share practices that are out of the ordinary but might benefit otherswhat are your preferred modern c software design practicesdesign considerations are at least as important of course do you adapt design practices from the objectoriented world do you use uml or you opt to iron out specifications in a languageneutral style flowcharts z weakest precondition calculus anything,['c'] +20443,any quick and dirty antialiasing techniques for a rotated uiimageview i have got a uiimageview full frame and rectangular that i am rotating with a cgaffinetransform the uiimage of the uiimageview fills the entire frame when the image is rotated and drawn the edges appear noticeably jagged is there anything i can do to make it look better it is clearly not being antialiased with the background,['iphone'] +20446,am i implementing ithisposable correctly this class uses a streamwriter and therefore implements ithisposablepublic class foo ithisposable private streamwriter writer public foo string path here happens something along the lines of filestream filewrite fileopen path filemodeopenorcreate fileaccesswrite filesharereadwrite writer new streamwriter filewrite new asciiencoding public void thispose thispose true gcsuppressfinalize this foo thispose false protected virtual void thispose bool thisposing if thisposed return if thisposing writerthispose writer null thisposed true private bool thisposedis there any issue with the current implementation ie do i have to release the underlying filestream manually is thisposebool written correctly,['c#'] +20454,can you use the params keyword in a delegate i would like to define a delegate that takes a couple of dates an unknown number of other parameters using the params keyword and that returns a list of objectsfuncdatetime datetime params int listobjectvisual studio does not like the syntax which is making me think this is not allowed can anyone tell me why,"['c#', '.net']" +20455,does opengl es have a better performance than core animation and uikit when it comes to highly animated user interfaces currently i have an user interface that makes incredible heavy use of core animation i wonder if it is worth to spent another 2 months for learning opengl es does that really improve drawing performance for 2d surfaces i have no 3d objects but highly animated 2d stuff sometimes with 3d thistortions a lot of rotations and scalingin particular i made a whole game with lots of sprites just using ca performance is ok but not perfect,['iphone'] +20472,changing the commandtimeout in sql management studio how can i change the commandtimeout in sql management studio,['sql'] +20475,understanding update and delete rules for relationships in ssms 2008 i am confused about what means the update and delete rule in sql server 2008 management studio when we define foreign key constraints i also did not find related help documents eg f1 helphere is the screen snapshot appreciate if anyone could describe what do they mean and recommend some related documents to read,['sql'] +20476,how to make an android slidingdrawer slide out from the left i am using a slidingdrawer in my application that has its handler placed at the bottom when in portrait mode when the user switches to landscape mode widescreen i would like to have the handler located on the left when i change the orientation from vertical to horizontal the handler is placed on the right i have defined my layout xml like thisslidingdrawer androidididl drawer androidlayout widthfill parent androidlayout heightfill parent androidhandleidl handle androidcontentidl content androidorientationhorizontal androidlayout gravityleft anyone have an idea for how to make it slide from left to right,['android'] +20479,visual c project dependency analysis i have a few large projects i am working on in my new place of work which have a complicated set of statically linked library dependencies between them the libs number around 4050 and it is really hard to determine what the structure was initially meant to be there is not clear documentation on the full dependency mapwhat tools would anyone recommend to extract such data presumably in the simplest manner if did the followingdefine the set of paths which correspond to library unitsset all cpph files within those to belong to those compilation unitscapture the 1st order include dependency tree one would have enough information to compose a map refactor and recompose the map until one has created some orderi note that have something nice but that is exclusively net unfortunatelyi read something about doxygen being able accomplish some static dependency analysis with configuration has anyone ever pressed it into service to accomplish such a task,['c++'] +20495,mysql query to calculate the previous month i would like to calculate total order amount in the previous monthi got the query for getting the data for the present month from the current dateselect sumgoods total as total amount from orderswhere order placed date date subcurrent date interval 1 monthnow how can i get previous months data only excluding this monthfor eg this month july i made 150 and last monthjune i made 140i get the 150 by running the above query but i dont know how to calculate previous months,['mysql'] +20499,javadoc for packageinfojava only i have a situation where i would like to execute javadoc in a project that has no classes it only has packageinfojava for one package when executing javadoc the following error is givenan error has occurred in javadocs report generationexit code 1 javadoc error no public or protected classes found to documentis there any way to force it to process packageinfojava only aside from the obvious hacky solutions creating a dummy class scripting the copying of a packagehtml etci am executing javadoc as part of a maven build so the mavenjavadocplugin is performing the actual javadoc command,['java'] +20507,how to replace tokens in a string without stringtokenizer given a string like so hello first name this is a personalized message for youwhere first name is an arbitrary token a key in a map passed to the method to write a routine which would turn that string intohello jim this is a personalized message for yougiven a map with an entry first name jimit would seem that stringtokenizer is the most straight forward approach but the javadocs really say you should prefer to use the regex aproach how would you do that in a regex based solution,['java'] +20515,how to ignore duplicate key error in tsql sql server i have a transaction that contains multiple sql statements insert update andor deletes when executing i want to ignore duplicate error statements and continue onto the next statement whats the best way of doing that,['sql'] +20516,alternative xml parser for elementtree to ease utf8 woes i am parsing some xml with the elementtreeparse function it works except for some utf8 characterssingle byte character above 128 i see that the default parser is xmltreebuilder which is based on expatis there an alternative parser that i can use that may be less strict and allow utf8 charactersthis is the error i am getting with the default parserexpaterror not wellformed invalid token line 311 column 190the character causing this is a single byte x92 in hex i am not certain this is even a valid utf8 character but it would be nice to handle it because most text editors thisplay this as aedit the context of the character is canat where i assume it is supposed to be a fancy apostraphe but in the hex editor that same sequence is 63 61 6e 92 74,['python'] +20518,when should i use cross apply over inner join what is the main purpose of using cross applyi have read vaguely through posts on the internet that cross apply can be more efficient when selecting over large data sets if you are partitioning paging comes to mindi also know that cross apply does not require a udf as the righttablein most inner join queries onetomany relationships i could rewrite them to use cross apply but they always give me equivalent execution plans can anyone give me a good example of when cross apply makes a difference in those cases where inner join will work as welleditheres a trivial example where the execution plans are exactly the same show me one where they differ and where cross apply is fastermore efficientcreate table company companyid int identity11 companyname varchar100 zipcode varchar10 constraint pk company primary key companyidgocreate table person personid int identity11 personname varchar100 companyid int constraint fk person companyid foreign key companyid references dbocompanycompanyid constraint pk person primary key personidgoinsert companyselect abc company 19808 unionselect xyz company 08534 unionselect 123 company 10016insert personselect alan 1 unionselect bobby 1 unionselect chris 1 unionselect xavier 2 unionselect yoshi 2 unionselect zambrano 2 unionselect player 1 3 unionselect player 2 3 unionselect player 3 3 using cross apply select from person pcross apply select from company c where pcompanyid ccompanyid czip the equivalent query using inner join select from person pinner join company c on pcompanyid ccompanyid,['sql'] +20525,excel external table is not in the expected format i am trying to read an excel xlsx file using the code shown below i get an external table is not in the expected format error unless i have the file already open in excel in other words i have to open the file in excel first before i can read if from my c program the xlsx file is on a share on our network how can i read the file without having to open it firstthanksstring sql select from sheet1string excelconnection providermicrosoftjetoledb40data source pathname extended propertiesexcel 80hdryesimex1using oledbdataadapter adaptor new oledbdataadaptersql excelconnection dataset ds new dataset adaptorfillds,['c#'] +20527,accessing parent namespace in c i have got a scenario like the followingclass criterion stuff about criterianamespace hex class criterion public criterion does not compile this should inherit from the a hex specific criterion criterion class in the global namespace my question is how does one inherit from a class in a namspace which is the parent of another namespacebilly3,['c++'] +20534,whats the best and most efficient book to learn javascript whats the best and most efficient book to learn javascript,['javascript'] +20547,how to remove the focus from a textbox in winforms i need to remove the focus from several textboxes i tried usingtextbox1focused falseits readonly property value is truei then tried setting the focus on the form so as to remove it from all the textboxes but this also fails to workthisfocusand the function returns false when a textbox is selectedso how do i remove the focus from a textbox,"['c#', '.net']" +20559,is there any way to pass an anonymous array as an argument in c i would like to be able to declare an array as a function argument in c as shown in the example code below which does not compile is there any way to do this other than declaring the array separately beforehandinclude stdiohstatic void printarrayint arraylen const int array for int i0 iarraylen i printfi in i arrayiint mainint char printarray5 56789 does not compile return 0,['c++'] +20571,why htmljavascriptcss are not compiled languages and will they ever be why htmljavascriptcss are not becoming compiled languages or maybe even merge into a single compiled language what if browsers were running browser virtual machine and htmljavascriptcss sources could by compiled to a browser bytecode wouldnt it help developers and users a loti can see a few challengeswhat to do with zillions of existing pages make this compilation optional so if you want you can use plain old html if you want to feed a browser with a compiled page just use chtml for examplehow search providers would index pages make a decompiler that would decompile bytecode into exact original sources for example like flash can be decompiled or search providers can use the same virtual machine and get data they need from therehow to make it compatible with all browsers have one centralized developer lets say w3c to develop this virtual machine and then each browser would embed it but what about benefitsspeedsizeno more loose and halfcorrect html it is either correct or would not compilelooks the same in every supported browserif not a bytecode then at least have some native compression going on html probably is not the most efficient way of data storing i know there is gzip but why to compress pages every time on a server and decompress in a browser if we can compress it once and feed it to a browserso what stops us from taking this road well besides a huge amount of effort to make it all happen,['html'] +20572,using mono for developing in c i am starting to use mono to develop applications in c and c i wanted to ask you how is mono compiling the c code is it using gcc it is amazing to see that it has the stl containers also can i use the boost libraries and gsl libraries with mono thanks in advance,"['c#', 'c++']" +20576,is comeau compiler worth it compared to gcc i have been using gcc g for my c c application development till now and have found it to be amazing but browsing through stack overflow i found many members stating that error reporting in comeau compiler is much more than any other compiler is this true i have not invested in any commercial release of a compiler is it really worth spending money on a commercial release of a cc compiler when gcc g are doing the trick,"['c++', 'c']" +20587,rationale behind eventargs class i am learning events in c and understand that the eventargs class carries data about the event but i am having difficulties understanding why eventargs is necessary for instance in this msdn example could not the wakemeup class read all of the necessary data snoozepressed nrings from the fields of alarmclock if it can set them why could not it also get them,"['c#', '.net']" +20613,create ntfs junction point in python is there a way to create an ntfs junction point in python i know i can call the junction utility but it would be better not to rely on external tools,['python'] +20614,how to concat two or more gzip filesstreams i want to concat two or more gzip streams without recompressing them i mean i have a compressed to agz and b to bgz i want to compress them to single gzip abgz without compressing once again using c or cseveral noteseven you can just concat two files and gunzip would know how to deal with them most of programs would not be able to deal with two chunksi had seen once an example of code that does this just by decompression of the files and then manipulating original and this significantly faster then normal recompression but still requires on cpu operationunfortunaly i cannot found this example i had found once concatenation using decompression only if someone can point it i would be greatfulnote it is not duplicate of this because proposed solution is not fits my needsclearification editi want to concate several compressed html pices and send them to browser as one page as per request acceptencoding gzip with respnse contentencoding gzipif the stream is concated as simple as cat agz bgz abgz gecko firefox and khtml web engines gets only first part a ie6 does not thisplay anything and google chrome thisplays first part a correctly and the second part b as garbage does not decompress at allonly opera handles this wellso i need to create a single gzip stream of several chunks and send them without recompressingupdate i had found gzjoinc in the examples of zlib it does it using only decompression the problem is that decompression is still slower them simple memcpyit is still faster 4 times then fastest gzip compression but it is not enoughwhat i need is to find the data i need to save together with gzip file in order tonot run decompression procedure and how do i find this data during compression,['c++'] +20641,how do i drop to the irb prompt from a running script can i drop to an irb prompt from a running ruby scripti want to run a script but then have it give me an irb prompt at a point in the program with the current state of the program but not just by running rdebug and having a breakpoint,['ruby'] +20643,unable to connect mysql from sequel gem when i try to connect to mysql from sequel i am getting these errorsrequire rubygems require sequel db sequelconnectadapter mysql user root host localhost database scantypasswordxx dbtables sequeldatabaseconnectionerror nameerror uninitialized constant mysqlclient multi results from optlocallibrubygems18gemssequel320libsequeladaptersmysqlrb98in connect from optlocallibrubygems18gemssequel320libsequeldatabaserb92in initialize from optlocallibrubygems18gemssequel320libsequelconnection poolrb166in call from optlocallibrubygems18gemssequel320libsequelconnection poolrb166in make new from optlocallibrubygems18gemssequel320libsequelconnection poolrb153in available from optlocallibrubygems18gemssequel320libsequelconnection poolrb144in acquire from optlocallibrubygems18gemssequel320libsequelconnection poolrb143in synchronize from optlocallibrubygems18gemssequel320libsequelconnection poolrb143in acquire from optlocallibrubygems18gemssequel320libsequelconnection poolrb105in hold from optlocallibrubygems18gemssequel320libsequeldatabaserb471in synchronize from optlocallibrubygems18gemssequel320libsequeladaptersmysqlrb128in execute from optlocallibrubygems18gemssequel320libsequeldatasetrb314in execute from optlocallibrubygems18gemssequel320libsequeladaptersmysqlrb342in execute from optlocallibrubygems18gemssequel320libsequeladaptersmysqlrb298in fetch rows from optlocallibrubygems18gemssequel320libsequeldatasetrb185in each from optlocallibrubygems18gemssequel320libsequeldatasetconveniencerb156in map from optlocallibrubygems18gemssequel320libsequeldatasetconveniencerb156in map from optlocallibrubygems18gemssequel320libsequeladapterssharedmysqlrb60in tables from irb6irbmain0070 sequeldatabaseconnectionerror nameerro,"['mysql', 'ruby']" +20650,is there an automated way to backup hudson ci files here at my company we have three hudson ci servers with 100 jobs configured we are looking for an automated way to periodically backup job configurations and build history currently we have an ant script that we configure as a job but it is not easy to maintain and not eleganthave any of you found a way to manage this,['java'] +20662,alternative to backgroundworker that accepts more than one argument the backgroundworker object allows us to pass a single argument into the doworkeventhandler setupinitbackgroundworker endcallworker new backgroundworkerendcallworkerdowork new doworkeventhandlerendcallworker doworkendcallworkerrunworkerasyncusername the handlerprivate void endcallworker doworkobject sender doworkeventargs e string username eargument as string to pass multiple arguments i must wrap them in an object like this poor string array setupinitbackgroundworker startcallworker new backgroundworkerstartcallworkerdowork new doworkeventhandlerstartcallworker doworkstartcallworkerrunworkerasyncnew stringusername targetnumber the handlerprivate void startcallworker doworkobject sender doworkeventargs e string args eargument as string string username args0 string targetnumber args1is there another object or pattern that allows us pass multiple arguments nicely or ideally write our own signature,"['c#', '.net']" +20663,how to get height of entire document with javascript some documents i cannot get the height of the document to position something absolutely at the very bottom additionally a paddingbottom on seems to do nothing on these pages but do on the pages where height will return cases in pointon fandangojquerys documentheight returns correct valuedocumentheight returns 0documentbodyscrollheight returns 0on paperback swapjquerys documentheight typeerror document is nulldocumentheight returns an incorrect valuedocumentbodyscrollheight returns an incorrect valuenote i have browser level permissions if there is some trick there,['javascript'] +20665,can autocapitalize be turned off with javascript in mobile safari mobile safari supports an attribute on input elements called autocapitalizedocumented here which when set to off will stop the iphone capitalizing the text input into that field which is useful for url or email fieldsinput typetext classemail autocapitalizeoff but this attribute is not valid in html 5 or another spec as far as i know so including it in the html will produce an invalid html page what i would like to do is be able to add this attribute to particular fields onload with javascript with something like thisdocumentreadyfunction jqueryinputemail inputurlattrautocapitalize offwhich adds the correct attribute in firefox and desktop safari but does not seem to do anything in mobile safari any ideas why,"['javascript', 'iphone']" +20669,why cannot i build a hello world for glib so heres the worlds simplest glib programinclude glibhi try to compile it with gcc testc and i gettestc118 error glibh no such file or directoryso i make sure that i have the right packages dpkg l grep libglibii libglibperl 1831 perl interface to the glib and gobject libraii libglib12dev 121019build1 the glib library of c routines developmentii libglib12ldbl 121019build1 the glib library of c routinesii libglib200 22010ubuntu2 the glib library of c routinesii libglib20cil 21211ubuntu2 cli binding for the glib utility library 21ii libglib20data 21820ubuntu2 common files for glib libraryii libglib20dev 22010ubuntu2 development files for the glib libraryii libglibmm241c2a 21811 c wrapper for the glib toolkit shared libthen i search for any glibh anywhere under usrinclude i get two usrincludeglib12glibh and usrincludeglib20glibh so i try gcc iusrincludeglib20 wall testc in file included from usrincludeglib20glibgallocah34 from usrincludeglib20glibh32 from testc2usrincludeglib20glibgtypesh3424 error glibconfigh no such file or directoryabout 10 more errors snippedi do not seem to have a glibconfigh anywhere on my computerwhat do i do now,['c'] +20672,problem sending json object succesfully to aspnet webmethod using jquery i have been working on this for 3 hours and have given upi am simply trying to send data to an aspnet web method using jquerythe data is basically a bunch of keyvalue pairs so i have tried to create an array and adding the pairs to that arraymy webmethodaspxcs looks like this this may be wrong for what i am building in javascript i just dont know webmethod public static string saverecordlistobject items here is my sample javascriptvar items new array var data1 compid 1 formid 531 var data2 compid 2 formid 77 var data3 compid 3 formid 99 var data4 status 2 statusid 8 var data5 name value value myvalue items0 data1 items1 data2 items2 data3 items3 data4 items4 data5here is my jquery ajax callvar options error functionmsg alertmsgd type post url packagelistaspxsaverecord data items items contenttype applicationjson charsetutf8 datatype json async false success functionresponse var results responsed jqueryajaxoptionsi get the error invalid json primitive itemssoif i do thisvar dto items items and set the data parameter like this data jsonstringifydtothen i get this errorcannot convert object of type u0027systemstringu0027 to type u0027systemcollectionsgenericlist1systemobjectu0027i have been going in circles for hourssomeone please help my small brain figure this outthanks a ton,"['asp.net', 'javascript', 'jquery']" +20676,eclipse is trying to build the files in my svn directories how can i tell it to stop i am storing my android project in a subversion repository after recently shuffling a bunch of stuff around i started getting tons of errors likesyntax error entriesproject namesrcsvnline 1android aidl problemsyntax error do not know what to do with entriesproject namesrcsvnline 28android aidl problemetc it seems as if eclipse is trying to build the files in the svn directories now this setup used to work fine how can i fix this,"['java', 'android']" +20682,switch from google appengine to another server currently i am building my java web application on google appengine gae but due to a lot of limitations they have i am afraid that i am going to have to switch from gae to my own server which is running glassfish or i can setup any other server if needed also i am planning to run oracle or mysql databases what do i need to do in order to switch from gae to my server do i need to rewrite my code should i continue using datanucleus or switch to something else anything else,['java'] +20683,problem detecting newlines in javascript range object i have some javascript that manipulates html based on what the user has selected for real browsers the methods i am using leverage the range object obtained as such var sel windowgetselection var range selgetrangeat0 var content rangetostringthe content variable contains all the selected text which works fine however i am finding that i cannot detect the newlines in the resulting string for exampleselected text isabcdefghirangetostring evaluates to abcdefghiany search on special characters returns no instance of and f r or even s if however i write the variable out to an editable control the line feeds are present againdoes anyone know what i am missingit may be relevant that these selections and manipulations are on editable divs the same behaviour is apparent in chrome firefox and opera surprisingly ie needs totally different code anyway but there are not any issues there other than it just being iemany thanks,['javascript'] +20695,what does this security warning mean net process class i am using vsts 2008 net 20 c and i am running code analysis after build i got the following confusing security warning here is the warning and related code any ideas what is wrong if there is security warning how to fix itsystemdiagnosticsprocess myprocess new systemdiagnosticsprocessmyprocestartinfofilename iexploreexemyprocestartinfoarguments defaulthtmlmyprocestartinfoverb runasmyprocestartwarning ca2122 microsoftsecurity testhtml calls into procestart which has a linkdemand by making this call procestart is indirectly exposed to user code review the following call stack that might expose a way to circumvent security protection,"['c#', '.net']" +20714,maven vs aspectj example my aspect works great from eclipse with aspectj plugin however if i try to use it with maven i get nothing i tried this i add loggin in my aspect and i try to test it with junit test but when i runmvn cleanmvn testi get info aspectjcompile execution defaultbut i dont see logging in testif i do compiling in eclipse it works find but id like it to be ide independentso i could use it with hudsonps i use aj file for aspecti tried to google it but i cant find any working example,['java'] +20728,how can i use sphinx autodocextension for private methods i am using sphinx for documenting my python project i have the autodoc extension enabled and have the following in my docs autoclass classname membersthe problem is it only documents the nonprivate methods in the class how do i include the private methods too,['python'] +20730,formatting associative array declaration when declaring an associative array how do you handle the indentation of the elements of the array i have seen a number of different styles php syntax since that is what i have been in lately this is a pretty picky and trivial thing so move along if youre interested in more serious pursuits1 indent elements one more levelarray array foo bar baz qux 2 indent elements two levelsarray array foo bar baz qux 3 indent elements beyond the array constructor with closing brace aligned with the start of the constructorarray array foo bar baz qux 4 indent elements beyond the array construct with closing brace aligned with opening bracearray array foo bar baz qux personally i like 3athe broad indentation makes it clear that were at a break point in the code constructing the array and having the closing brace floating a bit to the left of all of the arrays data makes it clear that this declaration is done,['php'] +20731,how do you include another js file in googles v8 how do you include another script file inside a js script file in v8there is the script tag in html but how can it be done inside a v8 embedded program,['javascript'] +20734,does php have an equivalent to the operator i am wanting to assign a variable only it has not already been assigned whats the php way of doing the followingresult nullresult check1result check2result defaulti checked the standard operators and the is null function but there does not seem to be an easy way of doing the above operation,['php'] +20736,how to write to the output window in visual studio which function should i use to output text to the output window in visual studioi tried printf but it does not show up,['c++'] +20738,using aspnet routing to serve static files can aspnet routing not mvc be used to serve static filessay i want to routetoand i want to do it dynamically in the sense that the rewritten url is computed on the fly i cannot set up a static route once and for allanyway i can create a route like thisroutesadd staticroute new routestaticfile new fileroutehandlerin the fileroutehandlerprocessrequest method i can rewrite the path from staticpicturejpg to abcpicturejpg i then want to create a handler for static files aspnet uses the staticfilehandler for this purpose unfortunately this class is internal i have tried to create the handler using reflection and it actually worksassembly assembly assemblygetassemblytypeofihttphandlertype staticfilehandlertype assemblygettypesystemwebstaticfilehandlerconstructorinfo constructorinfo staticfilehandlertypegetconstructorbindingflagsnonpublic bindingflagsinstance null typeemptytypes nullreturn ihttphandler constructorinfoinvokenullbut using internal types does not seem to be the proper solution another option is to implement my own staticfilehandler but doing so properly supporting http stuff like ranges and etags is nontrivialhow should i approach routing of static files in aspnet,['asp.net'] +20740,how to draw line of ten thousands of points with wpf within 05 second i am writing wpf code to show a realtime plot which is a connected line containing about10 points it takes about 5 seconds to show a picture in my computer does anyone have an idea to make it quicker and within 05 secondclass e frameworkelement public e children new visualcollectionthis random rand new random drawingvisual dv new drawingvisual using drawingcontext dx dvrenderopen pen drawingpen new penbrushesblack 1 double xrandnext300 double y randnext300 for double i 0 i 10 i i 01 y 100 randnext100 dxdrawlinedrawingpen new pointi x new pointi 1 y x y childrenadv,['c#'] +20746,ios private api documentation is there a web site or project documenting private apis for the iphone sdk,['iphone'] +20751,is it ok to use classic mallocfree in objectiveciphone apps i have been playing around with iphone development for a while and although it feels a bit awkward when youre a hard core net developer it is not all that bad once you get used to itin every book i read about objectivec there is only talk about retainrelease reference counting for memory management as an oldskool cc developer it seems strange that allocating the normal way using malloc and free is only mentioned in some footnotesi know that malloc and free work in objectivec but i am curious if it is common practice or not after all if i want to allocate an array of 100 integers it seems that this is the most efficient way to do itint array mallocsizeofint 100memsetarray0sizeofint 100 use the arrayfreearrayis this indeed the best way or should i avoid plain c memory management,"['c', 'objective-c']" +20766,how to implement authorization checks in aspnet mvc based on session data this will be my first aspnet mvc application with forms authentication so i am trying to make sure i do not miss anything the scenario is this public secured areaswithin the private area it is even further limited to specific areas user these areas are defined by customizations to the base area that is customized per user groupso for example a user could get to url areacontrolleraction they would need to have permission to the secured area or they would be redirected to the signin viewi have been reading about the authorizeattribute but i am not sure howwhere i should be doing these basic checks my initial hunch would be to store a user object in the session after a successful signin with the users ip and details about what they have access to etcthe authorization check for each secured controller call would verify that a valid user object exists in the session the ips still match up and the user has access to the specific area is there any obvious holes to this setupedit wherehow do i implement these checks so that when a controller is tagged with authorize it will perform those session object checksany pointers or suggestions would be much appreciated thanks,"['c#', 'asp.net']" +20768,is there a set of stubsmocks for jdbc available anywhere for the past few years i have continuously struggled with unit testing database code and all the pain that comes with it i found this existing thread which i found very enlighteningwhats the best strategy for unit testing databasesthe author of the accepted answer suggests that it might be useful to mock the entire database layer in order to validate the generated sql i did not think much of it when i first read the answer a few months ago but recently i have observed several bugs caused by incorrectly generated sql wrongly assigned fields and so on i do realize that jdbc is rather bloated and error prone to use but it is not an option to switch to something different at this pointthe application in question is a batch processor of data feeds and uses jdbc directly rather than an orm all jdbc code is separated into thistinct dao objects where each object has its own interface and stub besides the actual implementations this has allowed me to achieve good test coverage of the business layer but the testing of the database layer is virtually nonexistantis there an existing stub implementation of the jdbc javasql interfaces that can be injected into dao classes and used to validate the generated sql and possibly send back some preprogrammed results,['java'] +20771,c auto class implementation in editor much of my time spent developing c applications is wasted implementing class definitions by that i mean the prototyping of classes then creating their respective implementationsfor exampleifndef foo hdefine foo hclass foopublic foo const x x const y y foo void performxyz int countendifand now i will have to copy and paste then add the repetitive foo onto each functionfoofoo const x x const y yfoofoo void fooperformxyz int countfor now i copy the function declarations over to their respective cpp files remove empty lines then replace with n however i still have to specify the namespace for each functionare there tools in eclipse vim or any other ideeditor that take this burden off a developer,['c++'] +20773,passing by ref i am still confused about passing by refif i have a cache object which i want to be accessedavailable to a number of objects and i inject it using constructor injection i want it to affect the single cache object i have created egpublic class cache public void removestring filetoremove public class objectloader private cache cache public objectloadercache cache public removefromcachefilethathasbeendeletedorsimilaroperationstring filename cacheremovefilename should i be using ref when i pass the cache into the objectloader constructor,"['c#', '.net']" +20780,nhibernate cascadesaveupdate thisclaimer i am an nhibernate noobie so hopefully this question makes sense i have a manytomany relationship between two classes something likeapublic class entity1 public virtual guid entityid get set public virtual ilistentity2 entity2list public class entity2 public virtual guid entityid get set public virtual ilistentity1 entity1listiave added a manytomany relationship with a bag in both class mappings defining an association table but am unsure of which cascade option to use i want to be able to create a new entity1 instance add a new entity2 instance to itas list call save and both be inserted into the database and viceversa when deleting an entity it should delete any associations to child entities but not the child entity itself should i be using cascadesaveupdate,['c#'] +20781,escaping only what is necessary is that possible i am working with a team of developers on a website the website will be using classes i am in charge of creating the data access layer for the classes there is an understanding that all user input will be escaped upon retrieval from the post or get having little control over the input level unless i personally review everyones code i thought it would be cool to throw in escaping on my end as well right before it hits the database the problem is that i do not know how to use mysql real escape string without adding even more slashes since user input may very well contain a slash i cannot check to make sure there are slashes in it i might be able to check for all the things that need escaping and make sure they have a slash in front of them but that does not seem like the best way to do itany suggestions,"['php', 'mysql']" +20783,how to test if a file is fully copied in net i am monitoring a folder for new files and need to process them the problem is that occasionally file opening fails because system has not finished copying itwhat is the correct way to test if the file is finished copyingclarificationi do not have write permissions to the folderfiles and cannot control the copying process it is the user,['.net'] +20787,postgres sql to list table foreign keys is there a way using sql to list all foreign keys for a given table i know the table name schema and i can plug that in,['sql'] +20802,how do you increase the height of an html textbox how do you increase the height of an textbox along with its font size,['html'] +20810,how to detect that a given pe file exe or dll is 64 bit or 32 bit i need to detect whether a given dll or exe file is 32 bit or 64 bitat the moment i have only one solution read the pe header from the specified file and take the machine field from there specification microsoft portable executable and common object file format specification docx file at section 33 coff file header object and image this field can take up to about 20 values three of them areimage file machine i386 32bit image file machine ia64 64bit image file machine amd64 64bit my questions1 is machine to bitness mapping correct or did i miss something are there any other caveats2 is there easier way to detect 3264 bitness probably some specific field in pe format i did not notice or some special system function,['c++'] +20826,how does google use html tags to enhance the search engine i know that googleas search algorithm is mainly based on pagerank however it also does analysis and uses the structure of the document h1 h2 title and other html tags to enhance the search resultswhat is the name of this technique using the document structure to enhance the search resultsand are there any academic papers to help me study this areathe fact that google is taking the html structure into account is well covered in seo articles however i could not find it in the academic papers,['html'] +20833,getting started with osgi felix which packages of felix do i need to get started there are a zillion of them on the downloads pageps is the name a reference to the odd couple in contrast to osgis oscar reference framework this occurred to me after reading one of the tutorial pages i got a chuckle out of it,['java'] +20857,realtime microphone sound level monitoring i am trying to access sound volume data from the microphone in realtime i have tried avaudioplayer but it only monitors sounds from a source like an mp3 and not from a microphone i have also tried the speakhere app but it is proving to be much tougher to understand with all the objective c syntax i am a newbie is there another class similiar to the one in speakhere but written only in objective c,['iphone'] +20889,rearranging uitableview with core data possible duplicatehow to implement reordering of coredata records i am trying to find a code sample that shows how to handle movingrearranging cells in a tableview when the cell uses a fetchedresultscontroller ie in conjunction with core data i am getting the moverowatindexpath call to my data source but i cannot find the right combination of black magic to get the tabledata to recognize the change properlyfor example when i move row 0 to row 2 and then let go it looks correct then i click done the row 1 that had slid up to fill row 0 still has it is editing mode appearance minus and move icons while the other rows below slide back to normal appearance if i then scroll down as row 2 originally 0 remember nears the top it completely thisappearswtf do i need to somehow invalidate the fetchedresultscontroller whenever i set it to nil i get crashes should i release it instead am i in the weedsheres what i have currently got in there voidtableviewuitableview tableview moverowatindexpathnsindexpath fromindexpath toindexpathnsindexpath toindexpath nsmanagedobjectcontext context fetchedresultscontroller managedobjectcontext update the links data in response to the move update the thisplay order indexes within the range of the move if fromindexpathsection toindexpathsection nsinteger start fromindexpathrow nsinteger end toindexpathrow nsinteger i 0 if toindexpathrow start start toindexpathrow if fromindexpathrow end end fromindexpathrow for i start i end i nsindexpath temppath nsindexpath indexpathforrowi insectiontoindexpathsection linkobj link fetchedresultscontroller objectatindexpathtemppath managedobjectcontext deleteobjectfetchedresultscontroller objectatindexpathtemppath linkorder nsnumber numberwithintegeri managedobjectcontext refreshobjectlink mergechangesyes managedobjectcontext insertobjectlink save the context nserror error if context saveerror handle the error voidcontrollerwillchangecontentnsfetchedresultscontroller controller the fetch controller is about to start sending change notifications so prepare the table view for updates if selfthetableview nil selfthetableview beginupdates voidcontrollerdidchangecontentnsfetchedresultscontroller controller the fetch controller has sent all current change notifications so tell the table view to process all updates if selfthetableview nil selfthetableview endupdates,['iphone'] +20908,how to wait for exit of nonchildren processes for child processes the wait and waitpid functions can be used to suspends execution of the current process until a child has exited but this function can not be used for nonchild processes is there another function which can wait for exit of any process,['c'] +20911,understanding mysql explain so i have never understood the explain of mysql i understand the gross concepts that you should have at least one entry in the possible keys column for it to use an index and that simple queries are better but what is the difference between ref and eq ref what is the best way to be optimizing queries for example this is my latest query that i am trying to figure out why it takes forever generated from django models id select type table type possible keys key key len ref rows extra 1 simple t6 ref yourock achiever achievement idyourock achiever alias id yourock achiever alias id 4 const 244 using temporary using filesort 1 simple t5 eq ref primary primary 4 pault6achievement id 1 using index 1 simple t4 ref yourock achiever achievement idyourock achiever alias id yourock achiever achievement id 4 pault6achievement id 298 1 simple yourock alias eq ref primary primary 4 pault4alias id 1 using index 1 simple yourock achiever ref yourock achiever achievement idyourock achiever alias id yourock achiever alias id 4 pault4alias id 152 1 simple yourock achievement eq ref primary primary 4 paulyourock achieverachievement id 1 6 rows in set 0 seci had hoped to learn enough about mysql explain that the query wouldnt be needed alas it seems that you cannot get enough information from the explain statement and you need the raw sql query select yourock achievementid yourock achievementmodified yourock achievementcreated yourock achievementstring id yourock achievementowner id yourock achievementname yourock achievementdescription yourock achievementowner points yourock achievementurl yourock achievementremote image yourock achievementimage yourock achievementparent achievement id yourock achievementslug yourock achievementtrue pointsfrom yourock achievementinner join yourock achieveron yourock achievementid yourock achieverachievement idinner join yourock aliason yourock achieveralias id yourock aliasidinner join yourock achiever t4on yourock aliasid t4alias idinner join yourock achievement t5on t4achievement id t5idinner join yourock achiever t6on t5id t6achievement idwhere t6alias id 6order by yourock achievementmodified desc,['mysql'] +20917,visual studio 2005 designer moves controls and resizes form when i open a form in visual studio 2005 c the designer automaticaly resize the form and moveresize controls without touching the designer at all the source file is changed and when i close the designer i am asked to save the cs filei tried to look into visual studio options without any successany ideasvisual studio setup or somethingthankstal,['c#'] +20922,binding to a member variable i am confused as to what boostbind does when we bind to member variables with binding to member function we essentially create a function object and then call it passing to it the arguments that are provided or delayed and substituted via placeholdersbut what does this expression do behind the scenesboostbindstdpairsecond 1what gets substituted in place of the placeholder 1i found this while reading this example from an article on boostbindvoid print stringconst stdstring s stdcout s nstdmapintstdstring my mapmy map0boostmy map1bindstdfor each my mapbegin my mapend boostbindprint string boostbind stdmapintstdstringvalue typesecond 1source,['c++'] +20923,how to handle incorrect values in a constructor please note that this is asking a question about constructors not about classes which handle timesuppose i have a class like thisclass timeprotected unsigned int m hour unsigned int m minute unsigned int m secondpublic timeunsigned int hour unsigned int minute unsigned int secondwhile i would want a to be constructed successfully i would want the constructor of b to failtime a time123456time b time123465 second is larger than 60however this is not possible because constructors do not return any values and will always succeedhow would the constructor tell the program that it is not happy i have thought of a few methodshave the constructor throw an exception and have handlers in the calling function to handle ithave a flag in the class and set it to true only if the values are acceptable by the constructor and have the program check the flag immediately after constructionhave a separate probably static function to call to check the input parameters immediately before calling the constructorredesign the class so that it can be constructed from any input parameterswhich of these methods is most common in industry or is there anything i may have missed,['c++'] +20928,using xml parser implementation as osgi service i am developing an application using osgi equinox platform and one of the bundles needs to parse xml files so far i implemented this with sax javaxxmlparserssaxparserfactory and i would like to retrieve the saxparserfactory from the platformi saw the osgi standard provides for a xmlparseractivator to allow jaxp implementations to register themselves so my guess is that there should be some bundles that offer the saxparserfactory as a servicehowever i could not figure out which bundle to add as dependency in order to find a service that offers a saxparserfactory i try to retrieve a service reference usingcontextgetservicereferencessaxparserfactoryclassgetname parsernamespaceawaretrueparservalidatingtruegiven that xml parsing is a rather common thing to do i suppose there are implementations available or other means for getting a xml parser service from the platformany help would be very welcome,['java'] +20933,how to concatenate string in objectivec iphone possible duplicatehow do i concatenate strings in objectivec firstly the platform is iphone and labeltext changes the label thisplayed consider this scenarioi have an array of integers and i want to thisplay it on the screen heres my take on itibaction updatetext idsender int a2 a01 a12 a23 for int i0 i10i labeltext nsstring stringbyappendingstring nsstring stringwithformat i ai as you can probably see i am pretty confused pls pls help me out,"['iphone', 'objective-c']" +20962,java io streams what are the differences javaio has many different io streams fileinputstream fileoutputstream filereader filewriter bufferedstreams etc and i am confused in determining the differences between them what are some examples where one stream type is preferred over another and what are the real differences between them,['java'] +20973,how do i group data in an aspnet mvc view in reporting tools like crystal reports there are ways to take denormalized data and group it by a particular column in the data creating row headings for each unique item in the specified columnif i have thiscategory1 data1category1 data2category1 data3category2 data4category2 data5category2 data6the reporting software will group it like thiscategory1 data1 data2 date3category2 data4 data5 data6is there a way to do this in an aspnet mvc view perhaps using a simple linq phrase or linq extension method with a foreach or a nested foreach,['c#'] +20975,how do i detect the iphone orientation before rotating in my program i am moving things based on rotation but i am not rotating the entire view i am using static uideviceorientation previousorientation uideviceorientationportrait voidapplicationdidfinishlaunchinguiapplication application window addsubviewviewcontrollerview window makekeyandvisible nsnotificationcenter defaultcenter addobserverself selectorselectordidrotate nameuideviceorientationdidchangenotification objectnil void didrotatensnotification notification uideviceorientation orientation uidevice currentdevice orientation self dorotationstufforientation previousorientationpreviousorientation orientation this works as long as when the program is launched the device orientation is portrait but not if the initial orientation is landscape or upside down because self dorotationstuff makes changes relative to the difference from the previous orientationis there a way to detect the orientation either at launch or right before the device is rotated,"['iphone', 'objective-c']" +20979,log to database instead of log files i am interested in sending all rails application logging to a database mysql or mongodb either in addition to or instead of to a log file there are a few reasons most of which are concerned about log file analysis we already use google analytics but there are a variety of things we want to do that are not as workable in analytics furthermore i would like to do real time investigation of issues by looking at logs sifting through a log file is a tedious way to do that and i would like to do better searching and filtering than a log file easily allows for finally i often want to examine something closer to site visitor behavior tracing the path through the site for example so that i can see what the last page was that a user was looking at before an error occurred given we have multiple app servers the separate log files make this a real pain if all the data were in a database i could then easily see the proper sequence of pages for a given visitor i know that syslog would be one way to solve this particular thing single log filerepository but i want to combine that with better searching abilities that i associate with database searchesi am wondering what folks recommend to solve this do you directly log to a database or do you dump log files into a db but whats your approach for that so that it is essentially realtimeas up to date as the logfile itself i am currently determining at what level i would like this logging because another thing i looked at is writing a small rack filter that would log all requests this would miss all the extra output that the normal rails logging dumps out all the sql and output on cache hits and misses etc but it would achieve a big part of my goal and seems to have the advantage of not thisturbing anything else in the systemanyway i am not looking for one right answer more of a thiscussion and information on what anyone else might be doing in this same light,['ruby-on-rails'] +20980,wpf vs xbap vs silverlight which suits business applications i am pretty familiar with a lot of the ins and outs of full fledged wpf client applications i know that wpf client applications supports the full net framework 35 allows for hardware acceleration of 2d and 3d graphics theming templating styling triggers the workswhat i am not clear about is what features andor niceties are either present or lacking in xbap and silverlight applications i have heard that xbaps are intrinsically limited in certain ways due to security concerns but that is about iti know for a fact that wpf is robust enough to be used in fullscale business applications but what about xbap and silverlight what are the significant capabilities and limitations of each do either of them lack features that would render them useless when used in a business application,['.net'] +20983,detect click outside element similar to this question but taking it a step further i would like to detect clicks outside of a set of items which i am handling in the following waymenu divliveclick function close other open menu items if any toggle the clicked menu item bodyoneclick functionevent hide the menu item eventstoppropagation this works like a charm unfortunately when another menu item is open and asecond is clicked it requires two clicks to open the second item the firstclick hides the first menu item that was open the second shows the second menuitemthe correct behavior works in the following wayclicking a menu item opens it clicking the same menu item or it is children closes itclicking another menu item closes the first opens the secondclicking away from open menu items closes them i have tried the following in place of the above bodyone order to ignore clicks on menu items with little success captures click on menu items in spite of the notnotmenu oneclick function hide menu notmenuoneclick function hide menu as always thanks for any help,"['javascript', 'jquery']" +20985,iphone binary submitting tutorial alright i got my iphone application completly done and have done all the steps to get it submitted except for uploading the binary is there a step by step tutorial out therefor getting the binary all ready for uploading cause i am completly lost i just signed up for the developers program last night and am not sure if i need to download something to be able to publish my application or something,['iphone'] +20993,parent control mouse enterleave events with child controls i have a c net 20 winforms app my app has a control that is a container for two child controls a label and some kind of edit control you can think of it like this where the outer box is the parent control label control edit control i am trying to do something when the mouse enters or leaves the parent control but i do not care if the mouse moves into one of its children i want a single flag to represent the mouse is somewhere inside the parent or children and the mouse has moved outside of the parent control boundsi have tried handling mouseenter and mouseleave on the parent and both child controls but this means the action begins and ends multiple times as the mouse moves across the control in other words i get thisparentonmouseenter start doing somethingparentonmouseleave stopchildonmouseenter start doing somethingchildonmouseleave stopparentonmouseenter start doing somethingparentonmouseleave stopthe intermediate onmouseleave events cause some undesired effects as whatever i am doing gets started and then stopped i want to avoid thati do not want to capture the mouse as the parent gets the mouse over because the child controls need their mouse events and i want menu and other shortcut keys to workis there a way to do this inside the net framework or do i need to use a windows mouse hook,"['c#', '.net']" +20996,get the unix timestamp of midnight on the previous wednesday how would i go about finding the unix timestamp of midnight of the previous wednesday my only approach would be to get the day index and day number of today and subtract the difference but i can think of several scenarios where this would fail for example early in a month before a wednesday has happenedi guess more concisely how do i find the date of the previous wednesdayany help would be appreciated,['php'] +21016,count the number of nodes in an xml snippet using javascripte4x consider this problemusing javascripte4x in a nonbrowser usage scenario a javascript hl7 integration engine there is a variable holding an xml snippet that could have multiple repeating nodes pets pet typedogbarneypet pet typecatsockspetpetsquestion how to get the count of the number of pet nodes in javascripte4x edit to clarify this question should be around e4x ecmascript for xml apologies to those who answered without this information i should have researched posted this info beforehand,['javascript'] +21017,open source grammar checker for an online project i am working on i am looking for a open source grammar checker i have searched google with some good results etc but i am wondering what all of you think about this topici need this to be able to be used online versus desktop based but this is the only real specification i have if it has a builtin spell checker that would be a plus but i can always use another project for that purposethanks for any help,['php'] +21018,how can i get dns records for a domain in python how do i get the dns records for a zone in python i am looking for data similar to the output of dig,['python'] +21019,regular expressions and gwt my questions is is there a good solution to use regular expression in gwti am not satisfied with the use of stringsplitregex for example gwt translates the code to js and then uses the regex as a js regex but i cannot use something like the java matcher or java pattern but i would need these for group matchingis there any possibility or libraryi tried jakarta regexp but i had other problems because gwt does not emulate all methods of the java sdk this library uses i want to be able to use something like this on the client side compile and use regular expressionpattern pattern patterncompilepatternstrmatcher matcher patternmatcherinputstrboolean matchfound matcherfindif matchfound get all groups for this match for int i0 imatchergroupcount i string groupstr matchergroupi systemoutprintlngroupstr,['java'] +21026,mysqli real escape string and prepared statements should be a simple enough questionif i am using mysqli prepared statements do i still need to use mysqli real escape string as wellis this necessary or a good ideathanks nico,['php'] +21035,getting started with socket programming in c best practices i have seen many resources here on so about sockets i believe none of them covered the details which i wanted to know in my application server does all the processing and send periodic updates to the clients intention of this post is to cover all the basic ideas required when developing a socket application and thiscuss the best practices here are the basic things that you will see with almost all socket based applications1 binding and listening on a socketi am using the following code it works well on my machine do i need to take care about something else when i deploy this on a real serveriphostentry localhost dnsgethostentrydnsgethostnameipendpoint endpoint new ipendpointlocalhostaddresslist0 4serversocket new socketendpointaddressfamily sockettypestream protocoltypetcpserversocketbindendpointserversocketlisten102 receiving datai have used a 255 sized byte array so when i am receiving data which is more than 255 bytes i need to call the receive method until i get the full data right once i got the full data i need to append all the bytes received so far to get the full message is that correct or is there a better approach3 sending data and specifying the data lengthsince there is no way in tcp to find the length of the message to receive i am planning to add the length to the message this will be the first byte of the packet so client systems knows how much data is available to read any other better approach4 closing the clientwhen client is closed it will send a message to server indicating the close server will remove the client details from it is client list following is the code used at client side to thisconnect the socket messaging part not shownclientshutdownsocketshutdownbothclientcloseany suggestions or problems5 closing the serverserver sends message to all clients indicating the shutdown each client will thisconnect the socket when it receives this message clients will send the close message to server and close once server receives close message from all the clients it thisconnects the socket and stop listening call thispose on each client sockets to release the resources is that the correct approach6 unknown client thisconnectionssometimes a client may thisconnect without informing the server my plan to handle this is when server sends messages to all clients check the socket status if it is not connected remove that client from the client list and close the socket for that client any help would be great,"['c#', '.net']" +21051,what are vti cnf vti pvt vti script and vti txt folders these folders appear in my net web project why do they appear are they useful,['asp.net'] +21058,how to output javascript with php i am new to php i need to output the following javascript with php this is my codehtmlbodyphpecho script typetextjavascriptecho documentwritehello worldecho scriptbodyhtmlbut it is showing the errorparse error syntax error unexpected t string expecting or in varwhtmlworkbenchpersonscriptphp on line 4can anyone please help i also need some simple tutorials on how to use php html and javascript for an application,['php'] +21069,what is a good way to think about c references i have been programming c mainly in an embedded environment for years now and have a perfectly good mental model of pointers i do not have to explicitly think about how to use them am 100 comfortable with pointer arithmetic arrays of pointers pointerstopointers etc i have written very little c and really do not have a good way of thinking about references i have been advised in the past to think of them as pointers that cannot be null but this question shows that that is far from the full storyso for more experienced c programmers how do you think of references do you think of them as a special sort of pointer or as their own thing entirely whats a good way for a c programmer to get their head round the concept,['c++'] +21077,using python from within java possible duplicatejava python integration i have a large existing codebase written in 100 java but i would like to use python for some new sections of it i need to do some text and language processing and i would much rather use python and a library like nltk to do this i am aware of the jython project but it looks like this represents a way to use java and its libraries from within python rather than the other way round am i wrong about thisif not what would be the best method to interface between java and python such that ideally i can call a method in python and have the result returned to java thank you,"['java', 'python']" +21078,image resizing with django i am new to django and python and i have been trying to work out a few things myself before jumping into using other peoples apps i am having trouble understanding where things fit in the django or pythons way of doing things what i am trying to work out is how to resize an image once it is been uploaded i have my model setup nicely and plugged into the admin and the image uploads fine to the directoryfrom djangodb import models this is to list all the countries for starters though this will be just united kingdom gbclass countrymodelsmodel name modelscharfieldmax length120 help textfull name of country code modelscharfieldmax length2 help textthis is the iso 3166 2letter country code see digraphshtml flag modelsimagefieldupload toimagesuploadedcountry max length150 help textthe flag image of the country blanktrue class meta verbose name plural countries def unicode self return selfnamethe thing i am now having trouble with is taking that file and making a new file into a thumbnail like i say i would like to know how to do it without using others apps for now i have got this code from djangosnippetsfrom pil import imageimport ospathimport stringiodef thumbnailfilename size50 50 output filenamenone image imageopenfilename if imagemode not in l rgb image imageconvertrgb image imageresizesize imageantialias get the thumbnail data in memory if not output filename output filename get default thumbnail filenamefilename imagesaveoutput filename imageformat return output filenamedef thumbnail stringbuf size50 50 f stringiostringiobuf image imageopenf if imagemode not in l rgb image imageconvertrgb image imageresizesize imageantialias o stringiostringio imagesaveo jpeg return ogetvaluedef get default thumbnail filenamefilename path ext ospathsplitextfilename return path thumbjpgbut this has ultimately confused me as i do not know how this fits in to my django app and really is it the best solution for simply making a thumbnail of an image that has been successfully uploaded can anyone possibly show me a good solid decent way that a beginner like me can learn to do this properly as in knowing where to put that sort of code modelspy formspy and how it would work in context i just need a bit of help understanding and working this problem outthank you,['python'] +21080,what security issues should i look out for in php i just starting out learning php i have been developing web apps in aspnet for a long while i was wondering if there are any php specific security mistakes that i should be looking out forso my question is what are the top security tips that every php developer should knowplease keep it to one tip per answer so people can vote up down effectively,['php'] +21090,how do i remove a tooltip currently bound to a control i am currently adding a tooltip to a label like sotooltip labeltooltip new systemwindowsformstooltiplabeltooltipsettooltipthislocationlabel textwhen i need to change this tooltip as the labels text changes i try doing the same to add a new tooltip unfortunately the old tooltip remains under the new one which is really annoying is there a method to remove the old tooltip or should i just make a new label when i want to change the text in a label,"['c#', '.net']" +21108,should tryfoo ever throw an exception a common pattern in the net framework is the tryx pattern i do not know if that is what they really call it in which the called method attempts to do something returning true if it was successful or false if the operation failed a good example is the generic dictionarytrygetvalue methoddocumentation for these methods say that they will not throw exceptions that failure will be reported in the method return value all good so fari recently encountered two different circumstances in which net framework methods that implement the tryx pattern threw exceptions see and for detailsin both cases the tryx method called other methods that threw unexpected exceptions and those exceptions escaped my question does this break the implied contract of not throwing exceptionsput another way if you were writing tryfoo would you guarantee that exceptions cannot escape by writing it like thispublic bool tryfoostring param out foothing foo try do whatever return true catch foo null return false it is tempting because that guarantees no exceptions will escape thereby honoring the implied contract but it is a bug hidermy gut feeling based on my experience says that this is a really bad idea but if tryfoo lets some exceptions escape then what it is really saying is i would not throw any exceptions that i know how to handle and then the whole idea of the contract i would not throw exceptions is thrown out the windowso whats your opinion should tryfoo handle all exceptions or just those that it is expecting to happen whats your reasoning,['.net'] +21120,why is this overreleasing uinavigationcontroller uitableview i am pushing a view controller onto my navigation controllers stack from within my tableviewcontrollers didselectrowatindexpath method as somyviewcontroller myviewcontroller myviewcontroller alloc initwithnibnamemyviewcontroller bundlenilmyappdelegate appdelegate myappdelegate uiapplication sharedapplication delegatemyobject myo myobject appdelegatemyos objectatindexindexpathrowmyviewcontrolleramount myoamountselfnavigationcontroller pushviewcontrollermyviewcontroller animatedyesmyviewcontroller releaseif i uncomment that last line then the app crashes upon return with an error calayer release message sent to deallocated instance 0xd4f860digging in a bit further i find the crash can further be narrowed down to the call to super dealoc within myviewcontrollers dealoc method by uncommenting super dealoc we do not crash i am having trouble narrowing this down further super would be the uiviewcontroller class and i cannot further investigate that dealoc methodcan i maybe there is a way to see what exactly 0xd4f860 was pointing to but i am not aware how any ideas,['iphone'] +21132,how to programmatically clear outputcache for controller action method if the controller action has the outputcache attribute specified on an action is there any way to clear the output cache without having to restart iisoutputcache duration3600varybyparamparam1param2public string ajaxhtmloutputmethodstring param1 string param2 var somemodel somemodelfind param1 param2 set up viewdata return rendertostring viewname somemodel i am looking at using httpresponseremoveoutputcacheitemstring path to clear it but i am having trouble figuring out what the path should be to map it to the action method i am going to try again with the aspx page that is rendered by viewnamepossibly i will just manually insert the output of rendertostring into the httpcontextcache instead if i cannot figure this one out updateplease note that the outputcache is varybyparam and testing out a hardcoded path controlleraction does not actually clear the outputcache so it looks like it has to match controlleractionparam1param2that means i will probably have to revert to object level caching and manually cache the output for rendertostring,['asp.net'] +21137,is there a way to get the javadoc tool to document annotations in my project we use a number of annotations that would be very useful to see in the javadoc api documentationdoes anyone know a simple way to include annotations in generated javadocs i do not want to write my own javadoc plugin are there any solutions out there,['java'] +21142,get selected time from uidatepicker i have a uidatepicker on my viewi have set datepicker in time modeso user can select only timewhatever time is selected by user should be thisplayed in a textboxi dont know how to thisplay time value that is set by user through datepicker time modeplease help me,['iphone'] +21151,best way to clear a uitextfield for an iboutlet uitextfield does it matter as far as memory management or other reasons how you clear the text valuetextfieldxtext nilortextfieldxtext in objectivec it is acceptable to message a nil object and is a static nsstring i am not sure if every points to the same object in memory or if it allocates a bunch of 1 byte null terminated stringsnot a big deal just thought i would ask the community thanks,"['iphone', 'objective-c']" +21156,maven for other languages i am relatively new to the world of java and maven but i could not imagine starting a new java project without using maventhe idea of providing a humanreadable project model is something that i would imagine is universally desirable across many languages this is especially true when your application relies upon numerous external librariesare there any other project management or build tools for languages other than java that are similar in nature to maven that is that provide a mechanism for the project maintainer to specify dependencies and build order,['java'] +21157,smart date interpretation i cannot remember which application i was using but i do recall it having really neat date parsinginterpretationfor example you could type in two days ago or tomorrow and it would understandany libraries to suggest bonus points if usable from python,['python'] +21159,rails renaming associations i have two models treenode and user each user has one treenode which is the root of the treeclass treenode acts as tree belongs to userendclass user has one tree nodeendi would like to have this setup so that rails will make the association so that i can do something likeuserfirsttreeinstead of userfirsttree nodehow would one go about doing something like this,['ruby-on-rails'] +21160,pass additional viewdata to a stronglytyped partial view i have a stronglytyped partial view that takes a productimage and when it is rendered i would also like to provide it with some additional viewdata which i create dynamically in the containing page how can i pass both my strongly typed object and my custom viewdata to the partial view with the renderpartial callvar index 0foreach var image in modelimagesorderbyp porder htmlrenderpartialproductimageform image pass index to partial index,"['c#', 'asp.net']" +21178,waiting for the command to complete in c i am new to c and trying to develop a small application which internally opens a command prompt and executes some command here this is what i have done so far m command new process m commandstartinfofilename cmdexe m commandstartinfouseshellexecute false m commandstartinfowindowstyle processwindowstylehidden m commandstartinfocreatenowindow true m commandstartinforedirectstandardinput true m commandstartinforedirectstandardoutput true m commandstart m reader m commandstandardoutput m writer m commandstandardinput m writerwritelinesomecommand execute some commandas you can see i have redirected the input and output my question is how do i execute the some command synchronously ie i want to read the result of my command using the redirected output for that i have to wait until the command i invoked using writeline to complete how do i do that,['c#'] +21207,how to change application settings settings while app is open i have written a class that should allow me to easily read and write values in app settingspublic static class settingsmanager public static string complexvalidationsstring get return stringpropertiessettingsdefaultcomplexvalidations set propertiessettingsdefaultcomplexvalidations value propertiessettingsdefaultsave the problem is the value is not really saved i mean it is not changed when i exit the application and run it again what can i do to ensure that the saved value persists between closing and opening again,"['c#', '.net']" +21213,where to put break in switchcase statement with blocks when i use braces around case code block in c to localize variables should i put break inside or outside the blockcase foo break inside int i dostuff break case bar break outside int i dostuff breakthanks,['c++'] +21219,unable to inspect variables on eclipse i am unable to inspect variables on eclipse when debugging remote java application what could be the reasoneditedi am not able to inspect any variables message shown in inspector mini window is variable name cannot be resolved i am able to see the contents when i run it locally with test code,['java'] +21226,formatting trace output i am using textwritertracelistener to log diagnostics messages to a text file however i want also to log a timestamp of every trace message added is it possible to define a kind of formatter for the listener that would automatically add timestampscurrently i am adding timestamps manually on every tracewriteline call but this is not very comfortable,['c#'] +21227,trying to understand djangos sorlthumbnail i have been playing around with sorlthumbnail for django and trying to understand how it works better i have read the guide for it installed it in my sitepackages made sure pil is installed correctly put sorlthumbnail in the installed apps in my settingspy put from sorlthumbnailfields import imagewiththumbnailsfield at the top in my modelspy added image imagewiththumbnailsfieldupload toimages thumbnailsize80 80 as one of my model fields passed the model through my view to the template and in the template added load thumbnail at the top and put in the variable mymodelimagethumbnail tag in there toobut from what i understood is that when i upload an image through the admin it would create the thumbnail straight away but it only actually creates in when i see my template in the browser is this correct the thumbnail shows fine it looks great in fact but i thought that adding the model field part of it would create the thumbnail instantly once the image has uploaded why not just use the modelsimagefield in my model insteador have i done this all ok and i have just got the way it works wrong,['python'] +21236,just how to you use ttstyledtextlabel all i want is to thisplay some simple text in my viewcontroller and have the hyperlinks autoparsed when the user clicks on the link i want the control to somehow do a callback where i can do something with the url how can i achieve this i have already looked through the ttcatalog for hours i have also tried looking into the source code of three20 as well as looking at the stack trace no help i just cannot figure out how my app can react to the click of the url any hints please,['iphone'] +21249,when should you not use the asterisk when declaring a variable in objective c i have just started learning objective c and the asterisk is giving me some trouble as i look through sample code sometime it is used when declaring a variable and sometimes it is not what are the rules for when it should be used i thought it had something to do with the data type of the variable asterisk needed for object data types not needed for simple data types like int however i have seen object data types such as cgpoint declared without the asterisk as well is there a definitive answer or does it have to do with how and what you use the variable for,"['objective-c', 'iphone']" +21258,how to debuglogtrace an applet loading problem recently two of our clients have reported problems with our applets looking at the java plugin console it is full of classnotfoundexception so none of our code is executedi have been able to reproduce the stack trace using a virtual pc image with 0 free space on thisk but the problem goes away as i restore some thisk space and the users tell me that their thisk is not full they are able to create new filesour applet requires java 6 and the problem has appeared with updates 1 10 and 14 of the jre we have also tried different browsers ie and firefox clearing the browser and java caches how can i debug or trace what is the jvm doing to load our appleti suppose that the problem lies on some security directive on windows so i am using sysinternals process monitor to log the activity but i do not really know where to look at,['java'] +21261,using java generics with enums update thanks for everyone who helped out the answer to this one lay in what i was not noticing in my more complex code and what i did not know about the java5 covariant return types original posti have been playing around with something this morning while i know that i could tackle this whole problem differently i am finding myself obsessed with figuring out why it is not working the way that i was expecting after spending some time reading around on this i find i am no closer to understanding so i offer it up as a question to see if i am just being stupid or if there is really something i do not understand going on herei have created a custom event hierarchy like sopublic abstract class abstractevents t extends enumt private s src private t id public abstractevents src t id thissrc src thisid id public s getsource return src public t getid return id with a concrete implementation like sopublic class myeventextends abstracteventstring myeventtype public enum type selected selection cleared public myeventstring src type t supersrc t and then i create an event like sofireeventnew myeventmyclassmymethod myeventtypeselectedwhere my fireevent is defined asprotected void fireeventmyevent event foreventlistener l getlisteners switcheventgetid case selected lselectedevent break case selection cleared lunselectevent break so i thought that this would be pretty straightforward but it turns out that the call to eventgetid results in the compiler telling me that i cannot switch on enums only convertible int values or enum constants it is possible to add the following method to myeventpublic type getid return supergetidonce i do this everything works exactly as i expected it to i am not just interested in finding a workaround for this because i obviously have one i am interested in any insight people might have as to why this does not work as i expected it to right off the bat,['java'] +21267,randomness in jython when using pseudo random numbers in jython would it be more efficient to use the python random module or javas random class,"['java', 'python']" +21269,how do you deelevate privileges for a child process i know how to launch a process with admin privileges from a process usingprocstartinfouseshellexecute trueprocstartinfoverb runaswhere proc is a systemdiagnosticsprocess but how does one do the opposite if the process youre in is already elevated how do you launch the new process without admin privileges more accurately we need to launch the new process with the same permission level as windows explorer so no change if uac is thisabled but if uac is enabled but our process is running elevated we need to perform a certain operation unelevated because were creating a virtual drive and if it is created with elevated permissions and windows explorer is running unelevated it would not show upfeel free to change the title to something better i could not come up with a good description,['c#'] +21277,html change height of how do i specify the height of the blank line that inserting a p creates,"['html', 'css']" +21279,is an atomic operation enough class stopit private bool stop void loop while stop work void stop stop true basically if the loop method is running in one thread and stop is called from another will the operation stop properly i understand that bool readwrite is atomic but is this enough if the thread loop is not stopped immediately there is trouble should i mark stop volatile,['c#'] +21280,django comments how to prevent form errors from redirecting the user to the preview page currently djangocontribcomments sends the user to the preview page if there is any error on the form i am using comments in the context of a blog and i would much rather that the user stayed on the page they were on if something went wrong with the submission as far as i can tell though this is hardcoded in djangocontribcommentsviewscommentspost comment if there are errors or if we requested a preview show the commentif formerrors or preview template list commentss s previewhtml tuplestrmodel metasplit commentss previewhtml model metaapp label commentspreviewhtml return render to response template list comment formdatagetcomment form form next next requestcontextrequest is there any way that i can change this behavior without changing the source code to djangocontribcommentsany pointer would be appreciatedthanks,['python'] +21285,use jqueryjs to determine the day of week is there a method using either javascript or jquery to determine what day of the week it is for instance if the date a user picks in the box is a sunday i can alert themthanks,"['javascript', 'jquery']" +21303,int32tryparse or intcommandexecutescalar i have a sql query which returns only one field an id of type intand i have to use it as integer in c codewhich way is faster and uses less memoryint idifint32tryparsecommandexecutescalartostring out id use idorint id intcommandexecutescalarifidhasvalue use idvalueorint id commandexecutescalar as intifidhasvalue use idvalue,"['c#', '.net']" +21313,count the number of existing tabs in jquery i am using a dynamic jquery tab widget to addremove tabs generated programmaticallyhow do i check through jquery and count how many existing tabs are present in the widgeti am using this code but it does not workcontainer1 ultabsadd tabname namevar newtabif container1 lisize 0 newtab tabnamecssthisplay block else newtab tabnamecssthisplay nonenewtabhtmliframe srcviewpatientaspxpname name width100 frameborder0 scrollingno height300iframe,['jquery'] +21320,in java what is a shallow copy javautilcalendarclone returns a new calendar with the same properties and returns a shallow copy of this calendarthis does not appear to be a shallow copy as answered here on so that question is tagged languageagnostic java does not seem to follow the language agnostic definition as i step through the code i notice that the structure and the elements are copied to this new object more than the language agnostic structure onlyin java what is a shallow copyhow does it differ from a java deep copy if that exists,['java'] +21327,create excel file in java i want to create an excel file and write data just like writing a text file with java i tried to change file extension from txt to xls but i want to bold letters in the excel file how can i do thati have tried using the jxl api but every time i have to create a label i want add no label cannot o edit row and column of the table,['java'] +21333,silverlight datagrid binding each rows style i have got a silverlight v2 datagrid where some items are section headers and as such must appear with a different background colour i am trying to do this with the following xaml dgdatagridrowstyle style targettypedgdatagridrow setter propertybackground valuebinding pathbackground modeonetime style dgdatagridrowstylei expect it to bind the background property of the datagrid row viewmodel to each rows background property instead i get a lovely unknown xaml parsing errorsystemwindowsmarkupxamlparseexception ag e runtime managed unknown error line 16 position 57 at systemwindowsapplicationloadcomponentobject component uri resourcelocator at etanasurveysilverlightuserinterfaceviewsmaximumprobablelosspageinitializecomponent at etanasurveysilverlightuserinterfaceviewsmaximumprobablelosspagectorif i try to explicitly specify red and not try and bind the style then it works so i wonder if silverlight would allow me to bind a style like that or if there is some other trick to it the xaml is based on a wpf implementation of this which works fineany input would be much appreciated,['c#'] +21343,footer on last printed page i have a web page that a client would like to print and the part i am having trouble getting my head around is to get the footer to sit at the bottom of the last printed page not just when the content endsi tried something like printfooterthisplay block positionfixed bottom 0but it thisplayed the footer at the end of each pagemaybe im asking a bit too much from css is it doablei am thinking i should just go crazy with br s,['css'] +21348,acronyms in camel back i often see java class names likexmlreaderinstead ofxmlreadermy gut feeling is to completely upper case acronyms but apparently many people think differently or maybe it is just because a lot of code generators are having trouble with acronymsso i would like to hear the the public opinionhow do you capitalize your class names containing acronyms,['java'] +21349,android how to make all elements inside linearlayout same size i would like to create a dialog to thisplay a video title and tags below text i would like to add buttons view edit and delete and make these elements same size does anyone know how to modify xml layout file in order to make elements inside linearview same sizethe current layout file looks like thislinearlayout xmlnsandroid androidlayout widthfill parent androidlayout heightwrap content androidorientationvertical linearlayout androidlayout widthwrap content androidlayout heightwrap content androidorientationvertical textview androidlayout widthwrap content androidlayout heightwrap content androidididtxttitle androidtexttitle textview textview androidlayout widthwrap content androidlayout heightwrap content androidididtxttags androidtexttags textview linearlayout linearlayout androidlayout widthfill parent androidlayout heightwrap content androidorientationhorizontal button androidlayout widthwrap content androidlayout heightwrap content androidididbtnplay androidtextview button button androidlayout widthwrap content androidlayout heightwrap content androidididbtnedit androidtextedit button button androidlayout widthwrap content androidlayout heightwrap content androidididbtndelete androidtextdelete button linearlayoutlinearlayouti would appreciate if anyone could show the solution by modifying the pasted file contentthanks,['android'] +21350,determine whether client browser has java installed and can launch applets i am developing an aspx page which will ultimately launch an applet after the user clicks on a button i am using the applet tag so i would like to detect if java is enabledinstalled on the users browser i am using navigatorjavaenabled method however even though this is working fine on ie7 it is returning inconsistent results on firefox 3012 do not know about different browsers sometimes saying that java is enabled which it is and then after launching the applet and coming back out of the applet to this page again it will report false if i close firefox and return to the applet launching page navigatorjavaenabled will report true again correctlyis there anything that is determining this inconsistent behaviour or is navigatorjavaenabled not the best way to do the java applet checkthanks in advance,['java'] +21351,how to merge several arrays in a list using linq i have listproduct and i need to join them into one product,['.net'] +21354,programmatically determine fontsize for singleline thisplay i am thisplaying articles on a page the article titles sometimes spill over onto two lines and may even have only a single word on the second line this is very undesirable using jquerycss what would be the best method to programmatically determine a new fontsize for the titles to keep them on one line,"['jquery', 'css']" +21361,how to stop uitextview from scrolling up when entering it i have a uitextview included in a uitableviewcell the layout is correct when the views are initially thisplayed but once i click in the uitextview it automatically scrolls up a bit and the top half of the characters on the first line becomes invisible this image is when the uitextview is not activeand this one is when i clicked in the uitextview to make it activei do not the uitextview to scroll up at all it should simple stay fixed how can i achieve this i already tried several settings in interface builder but no luck so farany suggestions are appreciatedgero,['iphone'] +21362,does anybody know what means shellhook message hshell rudeappactivated i am writing application which establishes shell hooks to get shell events i am using c if it mattersi am using this example dafd19bc5d669d8f132entryhook is working fine but i do not receive message on which i am interested hshell windowactivated all other windowrelated events work wellinstead i am receiving message with code 32772 which should be hshell rudeappactivated some googling helped but i cannot understand why i am not receiving hshell windowactivated at all and what this hshell rudeappactivated message means msdn does not have any mention of it can anybody explain it to me,['c#'] +21366,websphere application server what on earth will it take to start any fast i am using rational application developer v70 that ships with an integrated test environment when i get to debugging my webapp the server startup time in debug mode is close to 56 minutes enough time to take a coffe break at times it so pisses me off that i start cursing ibm for building an operating system instead of an app server spawning 20 processes and useless services with no documented configuration to tuning it to starting any faster i am sure there are many java developers out there who would agree with me on this now i tried to thisable the default apps and a set of services via my admin console however that has not helped muchi have no webservices no enterprise beans no queues just a simple web app which requires a connection pool have you done something in the past to make your integrated test environment start fast in debug mode and there by consume less ram update i tried thisabling a few services internationaliztion default apps etc and now the websphere server went from bad to worse not only does not it take horrifying startup time it keeps freezing every now and then for upto 2 minutes sounds like optimization is not such a good thing always,['java'] +21368,why does as t get an error but casting with t not get an error why can i do thispublic t getmaincontentitemtstring modulekey string itemkey return tgetmaincontentitemmodulekey itemkeybut not thispublic t getmaincontentitemtstring modulekey string itemkey return getmaincontentitemmodulekey itemkey as tit complains that i have not restricted the generic type enough but then i would think that rule would apply to casting with t as well,['c#'] +21370,what is a good book to learn stl possible duplicates where can i learn about the c standard template library stlthe definitive c book guide and listi am having very less knowledge on templates and stl so looking for a good for stl,['c++'] +21372,swing ui not updating after using invokelater i have a java swing ui that is not updatingrepainting as i thought it should the app sends an xmpp message and receives a response on a different thread that response is processed and the ui is updated to reflect information contained in the messagewhen the response is received i update a jpanel component usingjavaxswingswingutilitiesinvokelaternew runnable public void run execute logic to update panel it is been quite sometime since i have developed in java but based on my research online invokelater queues the runnable up for execution on the gui thread however my gui does not update until i do something else in the app that causes a repaint such as resizing the window what am i missing after the logic for updating the panel i have tried various combinations of invalidate and repaint but the result is still the same the gui does not update until i say resize the windowedit when i say updating the panel i am specifically doing a removeall and then adding a handful of jlabels,['java'] +21407,how to find the most recent file in a directory using net and without looping i need to find the most recently modified file in a directory i know i can loop through every file in a folder and compare filegetlastwritetime but is there a better way to do this without looping,"['c#', '.net']" +21410,apache poi xls column remove i do not find how to remove a column with the apache poi apii would appreciate a sample code or help on this point,['java'] +21412,best way to sort 1m records in python i have a service that runs that takes a list of about 10 dictionaries and does the followingmyhashtable mylists hits misses total sorted hits misses total for item in mylist id itempopid myhashtableid item for k v in itemiteritems mylistskid vso if i had the following list of dictionaries idid1 hits200 misses300 total400 idid2 hits300 misses100 total500 idid3 hits100 misses400 total600i end up withmyhashtable id1 hits200 misses300 total400 id2 hits300 misses100 total500 id3 hits100 misses400 total600andmylists hits id1200 id2300 id3100 misses id1300 id2100 id3400 total id1400 id2500 id3600 i then need to sort all of the data in each of the mylists dictionarieswhat i doing currently is something like the followingdef dosortkey sortedkey sortedmylistskeyitems keyoperatoritemgetter1 reversetruewhich would yield in the case of missesid3 400 id1 300 id2 200this works great when i have up to 10 records or so but with 10 it is taking at least 5 10 minutes to sort each with a total of 16 my original list of dictionaries actually has 17 fields including id which is popped edit this service is a threadingtcpserver which has a method allowing a client to connect and add new data the new data may include new records meaning dictionaries with unique ids to what is already in memory or modified records meaning the same id with different data for the other key value pairsso once this is running i would pass in idid1 hits205 misses305 total480 idid4 hits30 misses40 total60 idid5 hits50 misses90 total20i have been using dictionaries to store the data so that i do not end up with duplicates after the dictionaries are updated with the newmodified data i resort each of them end edit so what is the best way for me to sort these is there a better method,['python'] +21423,weird switch error in objc i have this switch statement in my codeswitchbuttonindex case 0 actionsheet thismisswithclickedbuttonindexbuttonindex animatedyes breakcase 1uiimagepickercontroller imagepicker uiimagepickercontroller alloc initimagepickerdelegate selfimagepickersourcetype uiimagepickercontrollersourcetypecameraself presentmodalviewcontrollerimagepicker autorelease animatedyesbreakdefaultself openemailviewinviewcontrollerselfand at the uiimagepickercontroller instantiation in case 1 i am getting an errorerrorexpected expression before uiimagepickercontrollerand i have no idea what i am doing wrong thoughtsoh and buttonindex is an nsinteger,"['iphone', 'objective-c']" +21426,mysql errorno 121 i am getting this error in mysql create i am doingcreate table blogreply id int24 not null auto increment comment primary key of this table blogid int24 not null comment blog where this reply was posted userid int24 null comment user the blog was posted by name varchar100 null default unknown comment the name of the user that the reply was posted by email varchar100 null default unknown comment the email of the user that the reply was posted by http varchar300 null default unknown comment the webaddress of the user that the reply was posted by message text not null comment text of the blog votes int10 default 0 comment rating of the blog ratedby text comment people who have already voted on this blog datereg bigint not null comment date the user was registered primary key id constraint fk userid foreign keyuserid references user id on delete set null on update cascade constraint fk blogid foreign keyblogid references blog id on delete cascade on update cascade engine innodbany ideas the error states cannot create table xblogreplyfrm errno 121,['mysql'] +21428,c determine a nullable property datetime type when using reflection i have a question on how to determine an objects nullable property typeobjecta with a property datetime createdatewhen i am iterate through it is properties like the following code how do i check if a property is a nullable datetime type thanksforeach propertyinfo pi in objectagettypegetproperties do the compare here,['c#'] +21432,public fields versus automatic properties were often told we should protect encapsulation by making getter and setter methods properties in c for class fields instead of exposing the fields to the outside worldbut there are many times when a field is just there to hold a value and does not require any computation to get or set for these we would all do this numberpublic class book private string title public string title get return title set title value well i have a confession i could not bear writing all that really it was not having to write it it was having to look at it so i went rogue and used public fieldsthen along comes c 30 and i see they added automatic propertiespublic class book public string title get set which is tidier and i am thankful for it but really whats so different than just making a public fieldpublic class book public string title,['c#'] +21434,what increases an objects retain count here is code i am referring to personhinterface person nsobject nsstring firstname nsstring lastnameend personmimplementation person idinit if super init return nil firstname john lastname doeend myclassmimplementation myclass nsarray getpeople nsmutablearray array nsmutablearray alloc init int i for i 0 i 10 i person p person alloc init array addobjectp return array endnow i know there is no memorymanagement going on in this sample code what would be requiredin the getpeople loop i am allocing a person retaincount 1 then adding it to array the retain count is now 2 right if it is two should i be p releaseing after adding it to the array bringing the retaincount back down to 1am i right in that it is the callers responsibility to release the array returned by the method which would also free the memory of the persons and their instance variables assuming their counts are at 1i have read apples memory management document but i guess what i am most unclear about is what increases an objects retain count i think i grasp the idea of whos responsibility it is to release though this is the fundamental rule according to appleyou take ownership of an object if you create it using a method whose name begins with aalloca or anewa or contains acopya for example alloc newobject or mutablecopy or if you send it a retain message you are responsible for relinquishing ownership of objects you own using release or autorelease any other time you receive an object you must not release itbobdevils sentence only worry about the retain counts you add to the item explicitly made it click for me after reading the ownership policy at apple essentially the objectmethod that created the new object is the one responsible for releasing it is interest in it is this correctnow let us say i a method that receives an object and assigns it to a instance variable i need to retain the received object correct as i still have an interest in itif any of this is incorrect let me know,['objective-c'] +21448,bing maps cost money i am building a new web site in aspnet and im newbie with using mapsfor my web site i will need the following functionality thisplay a map of specific locationthisplay route map between two or more locationcalculate thistance between 2 locationsi found most of the functionality at the bing maps interactive sdk site and it works finemy questions aredoes it cost money to use this sdk for the third task i understand that i will have to use mappoint servicesis there another way does it code money to use iti will really appreciate it if you dont send me links cause my english is not the best onethanks a lot,['asp.net'] +21449,set cursor position on contenteditable i am after a definitive crossbrowser solution to set the cursorcaret position to the last known position when a contenteditableon div regains focus it appears default functionality of a content editable div is to move the caretcursor to the beginning of the text in the div each time you click on it which is undesirablei believe i would have to store in a variable the current cursor position when they are leaving focus of the div and then reset this when they have focus inside again but i have not been able to put together or find a working code sample yetif anybody has any thoughts working code snippets or samples i would be happy to see themi do not really have any code yet but here is what i do havescript typetextjavascript jquerydocumentreadyfunction areafocusfunction focus i would imagine i needscriptdiv idarea contenteditabletruedivps i have tried this resource but it appears it does not work for a div perhaps only for textarea how to move cursor to end of contenteditable entity,"['javascript', 'jquery', 'html']" +21483,converting source ascii files to jpegs i publish technical books in print pdf and kindlemobi with epub on the waythe kindle does not support monospace fonts which are kinda useful for source code listings the only way to do monospace fonts is to convert the text java source html xml etc into jpeg images more specifically due to pagination issues a given input ascii file needs to be split into slices of 6 lines each with each slice turned into a jpeg so listings can span a screen this is a royal painmy current mechanism to do that involvesrunning expand to set a consistent 2space tab size which pipes toa2ps which pipes toa small perl snippet to add a languagelevel 3n line which pipes toimagemagicks convert to take the eps and make a jpeg out it with an appropriate background cropped to 575x148528 etcthat used to work 100 of the time it now works 95 of the time the rest of the time i get convert geometry does not contain image errors which i cannot seem to get rid of in part because i do not understand what the problem isbefore this process i used to use a prettyprint engine sourcehighlight to get html out of the source codebut then the only thing i could find to convert the html into jpegs was to automate screengrabs from an embedded gecko engine reliability stank which is why i switched to my current mechanismso if you were you and you needed to turn source listings into jpeg images in an automated fashion how would you do it bonus points if it offers some sort of prettyprint process eg bolded keywordsor if you know what typically causes convert geometry does not contain image that might help my current process is ugly but if i could get it back to 100 reliability that would be just fine for nowthanks in advance,['html'] +21488,how do concepts differ from interfaces how do concepts ie those recently dropped from the c0x standard differ from interfaces in languages such as java,['c++'] +21491,how can i execute an external function when an element is clicked i am trying to execute an external function on click of a dom element without wrapping it in another functionsay i have a function called sayhello as followsfunction sayhello alerthelloto execute it on click i currently have to do thismyelementclickfunction sayhellonotice i am forced to wrap the single function call in yet another functionwhat i am trying to do is something like thismyelementclicksayhelloexcept that simply does not workcan i avoid wrapping the single function call in another function in any waythanksadditional informationhow would i achieve the same thing when i need to pass parameters to the functionadditional informationlike chris brandsma and jani hartikainen pointed out one should be able to use the bind function to pass parameters to the function without wrapping it in another anonymous function as suchmyelementbindclick john sayhellowith sayhello now accepting a new parameter as suchfunction sayhelloname alerthello namethis unfortunately does not seem to work any ideasthe eventsbind documentation is located herethanks,"['javascript', 'jquery']" +21495,web service php or ruby on rails or python i am a net sql server developer via my daytime job and on the side i do some objective c development for the iphone i would like to develop a web service and since dreamhost supports mysql python ruby on rails and php5 i would like to create it using one of those languages if you had no experience in either python ruby on rails or php which would you go with and why the service basically just takes a request and talks to a mysql databasenote was planning on using the soap protocol though i am open to suggestions since i have a clean slate with these languages,"['php', 'python', 'ruby-on-rails']" +21499,how do singletons in google app engine or more generally in a thistributed server environment work i am intrigued as to how singletons work in google app engine or any thistributed server environment given your application can be running in multiple processes on multiple machines at once and requests can get routed all off the place what actually happens under the hood when an app does something like cachemanagergetinstancei am just using the gae cachemanager as an example but my point is there is a single global application instance of a singleton somewhere so where does it live is an rpc invoked in fact how is global application state like sessions actually handled generallyregardsshane,['java'] +21506,what is the meaning of this c error stdlength error while running my program i get this errorterminate called after throwing an instance of stdlength error what basic string s createabort trapi know that you cannot do much without the code but i think that this error is too deep in the code to copy all of it maybe i can figure it out if i understand what this error means is this a sign for an issue with reading or writing at the wrong memory addressis there something i can do to get more information about the problem from my program,['c++'] +21509,best way to rotate an image using sdl i am building a game and the main characters arm will be following the mouse cursor so it will be rotating quite frequently what would be the best way to rotate it,['c++'] +21521,powershell runspace vs dlr with the net 40 beta now available and thus the wider availability of the net dynamic language runtime i guess these kinds of topics are going to become hotter i am confused about the conceptual differences between the dlr and powershell it seems to me that if i want to provide scripting capabilities in my net app i can use the dlr and so enable scripting in ironpython or ironruby or whatever other iron languages are available for the dlr or host a powershell runspace what are the pros and cons of each method why might i choose one over the other as a dynamic language itself and a firstclass net language at that why does not powershell also target the dlr,['.net'] +21528,css causing an ul to be indented too much in ie i have a navigation bar at the top of a page in ff and chrome the navigation bar thisplays fine however in ie8 with or without compatibility the ul seems to indent from the left hand side not each li just the whole li despite declaringtextaligncenter width600px marginauto paddingleft0any ideas what could be causing this,"['html', 'css']" +21531,dynamically loading css stylesheet does not work on ie i dynamically load a css stylesheet with a little help from jquery like thisvar head documentgetelementsbytagnamehead0documentcreateelementlink attr type textcss href mzmzcss rel stylesheet appendtoheadthis works fine in firefox and google chrome but not in ieany helpthanks,"['javascript', 'jquery', 'html', 'css']" +21540,python is osread oswrite on an ospipe threadsafe considerpipe read pipe write ospipenow i would like to know two things1 i have two threads if i guarantee that only one is reading osreadpipe readn and the other is only writing oswritepipe write will i have any problem even if the two threads do it simultaneously will i get all data that was written in the correct order what happens if they do it simultaneously is it possible that a single write is read in pieces likethread 1 oswritepipe write 1234567thread 2 osreadpipe readbig number 123thread 2 osreadpipe readbig number 4567or again consider simultaneity will a single oswritesome string always return entirely by a single osreadpipe read very big number2 consider more than one thread writing to the pipe write end of the pipe using logginghandlersfilehandler i have read that the logging module is threadsafe does this mean that i can do this without losing data i think i would not be able to control the order of the data in the pipe but this is not a requirementrequirementsall data written by some threads on the write end must come out at the read end a string written by a single loggerinfo loggererror has to stay in one pieceare these reqs fulfilledthank you in advancejanphilip gehrcke,['python'] +21549,how can i step into microsofts net framework source code i would like to step into microsofts source code but cannoti followed the instructions at configuring visual studio for debugging in particular i thisabled enable just my code and enabled enabled net framework source stepping finally set the source symbol location to however when i double click on a frame item on the stack i get some assembler code not c code also the go to source code menu item is thisabledi am using visual studio 2008 sp1 and net 35 sp1 i created a brand new folder for the downloaded stuff i get some pdb files but no c filei looked at configuring visual studio to debug net framework source code and installed the path it makes no difference i am trying to the source code of wpf the pdb are downloaded so it looks like microsoft supports thoseis there a trick to fix this,"['c#', '.net']" +21557,how to set default values in rails i am trying to find the best way to set default values for objects in rails the best i can think of is to set the default value in the new method in the controller does anyone have any input if this is acceptable or if there is a better way to do it,"['ruby-on-rails', 'ruby']" +21596,does thisposing a streamwriter close the underlying stream the streamwriterclose says it also closes the underlying stream of the streamwriter what about streamwriterthispose does thispose also thispose andor close the underlying stream,"['c#', '.net']" +21601,how to exit from python without traceback i would like to know how to i exit from python without having an traceback dump on the output i still want want to be able to return an error code but i do not want to thisplay the traceback logi want to be able to exit using exitnumber without trace but in case of an exception not an exit i want the trace,['python'] +21605,streaming a dynamic zip from amazon s3 i am looking for a way to dynamically stream download a zip of files from amazon s3 the application is hosted on ec2 and the files are stored on s3need to give users the ability to select from a group of files which will then get bundled up and downloaded to them have heard about a few actionscript libraries aszip and fzip that might be possible or could do this in ruby or even possibly php the files do not need any compression zip is just being used to bundle the files up into one single download,['ruby'] +21614,good or bad practice in python import in the middle of a file suppose i have a relatively long module but need an external module or method only onceis it considered ok to import that method or module in the middle of the moduleor should imports only be in the first part of the moduleexampleimport string pythis pythatdef func blah blah blah from pysomething import foo foo etc etc etcplease justify your answer and add links to peps or relevant sources,['python'] +21616,in jquery how do you find out the eq of an element of what is being clicked when one of the divs inside uploadchoice is clicked how can i ascertain which one is clicked can i return an eq value somehow div iduploadchoice divtextdiv divimagediv divtext imagedivdivuploadchoice divclickfunction insert code here,['jquery'] +21617,is it time to start developing with html5 from searching so this question was already asked almost a year ago nowso now with the new ff opera ie is it finally time to start developing sites with html5 or is it still a little premature and will cause compatibility issues is using html5 just going to require us to use more and more js on websites to trick older browsers into working properly,"['javascript', 'html']" +21629,java beans overglorified associative arrays i do not understand the nature of java beans that well well at least how i see them used in some codebases that pass through our shopi found this questionthe accepted answer there makes it look like programmers tend to abuse java bean which i really do not doubt but i see it happen so often and so deliberately i think i am still missing somethingi see code that looks likepublic class foobean private int a private int b private int c public int geta return a public int setaint x a x etcno further structure or control than getters and setters is there some sort of super awesome compiler trick going on that involves reflection getters and setters and the need for some very awkward but compiler optimized static associative arraysor maybe i am completely missing the point cheerseditdefinitely not promoting the idea of public fields here,['java'] +21634,scalability of duplex polling with silverlight iis i have been building a client server app with silverlight web services and polling apparently i missed the whole duplex communication thing when i was first researching this subject at any rate the msdn article i saw on the subject was promisingwhen researching the scalability it appears as if there is conflicting opinions on the subjectsilverlightnetforumst89970aspx this thread seems to indicate that the duplex polling only supports a finite amount of concurrent clients on the server enddotnetaddictdotnetdevelopersjournalcomsl polling duplexhtm this blog entry shows up in multiple places so it muddies waterssilverlightnetforumst108396aspx this thread shows that i am not the only one with this concern but there are no answers in itsilverlightnetforumst32858aspx despite all the bad press this thread seems to have an official response saying the 10 concurrent connections is per machinein short does anyone have facts benchmarksthanks,['c#'] +21646,how to compile mod python 331 for python 26 and apache 22 on windows i have no experience compiling code other than using visual studios build command i am hoping we can create a step by step guide for compiling mod python on windows please be as descriptive as possiblethis is what i have done so fardownload and install python 262download and install apache 2211download the most recent source code for mod python from svnfrom here i am lost to what the next step is i have downloaded microsoft visual c 2008 express editionas mentioned by hao i have already tried the tutorial mentioned in that link here is the error messages i am receiving with that tutorialcmod pythonthistbuild installerbatcould not find cmod pythonsrcobjrunning bthist wininstrunning buildrunning build pycreating buildcreating buildlibwin3226creating buildlibwin3226mod pythoncopying cmod pythonlibpythonmod pythonapachepy buildlibwin3226mod pythoncopying cmod pythonlibpythonmod pythoncachepy buildlibwin3226mod pythoncopying cmod pythonlibpythonmod pythoncgihandlerpy buildlibwin3226mod pythoncopying cmod pythonlibpythonmod pythoncookiepy buildlibwin3226mod pythoncopying cmod pythonlibpythonmod pythonimporterpy buildlibwin3226mod pythoncopying cmod pythonlibpythonmod pythonpsppy buildlibwin3226mod pythoncopying cmod pythonlibpythonmod pythonpublisherpy buildlibwin3226mod pythoncopying cmod pythonlibpythonmod pythonpython22py buildlibwin3226mod pythoncopying cmod pythonlibpythonmod pythonsessionpy buildlibwin3226mod pythoncopying cmod pythonlibpythonmod pythontesthandlerpy buildlibwin3226mod pythoncopying cmod pythonlibpythonmod pythonutilpy buildlibwin3226mod pythoncopying cmod pythonlibpythonmod python init py buildlibwin3226mod pythonrunning build extbuilding mod python so extensioncreating buildtempwin3226creating buildtempwin3226releasecreating buildtempwin3226releasemod pythoncreating buildtempwin3226releasemod pythonsrccprogram filesmicrosoft visual studio 90vcbinclexe c nologo ox md w3 gs dndebug dwin32 dndebug d windows icmod pythonsrcinclude icapacheinclude icpython26include icpython26pc tccmod pythonsrcmod pythonc fobuildtempwin3226releasemod pythonsrcmod pythonobjmod pythonccapacheincludeap configh25 fatal error c1083 cannot open include file aprh no such file or directoryerror command cprogram filesmicrosoft visual studio 90vcbinclexe failed with exit status 2,['python'] +21649,mkmapview refresh after pin moves a custom annotationview is updated with new coordinates but the problem is that it visually updates only after some manipulations with mkmapview eg zooming or movingwhat should i do to manually update visual position on a mapps i have tried to change region to current maps region but it does change zoom it is strangemapview setregionmapview region animatedyes,"['iphone', 'objective-c']" +21650,set the tooltip delay time for a particular component in java swing i am trying to set tooltips on a jeditorpane the method which i use to determine what tooltip text to show is fairly cpu intensive and so i would like to only show it after the mouse has stopped for a short amount of time say 1 secondi know i can use tooltipmanagersharedinstancesetinitialdelay however this will set the delay time for tooltips on all swing components at once and i do not want this,['java'] +21656,is it possible to write mapreduce jobs for amazon elastic mapreduce using net is it possible to write mapreduce jobs for amazon elastic mapreduce using net languages in particular i would like to use cpreliminary research suggests not the above urls marketing text suggests you have a choice of java ruby perl python php r or c without mentioning net languages this amazon thread support for c f mapreducers explicitly says that currently amazon elastic mapreduce does not support mono platform or languages such as c or fthe above suggests that it cannot be done i am wondering if there are any workarounds though for example can i modify the elastic mapreduce machine image for my account and install mono on therean alternative suggested by amazon faqs using other software required by your jar advancedtopicshtml and how to use additional files and libraries with the mapper or reducer fileshtml is to make the first step of the mapreduce job be to install mono on the local instance that sounds kind of inefficient but maybe it could workmaybe a saner alternative would be to try to forgo the convenience of elastic mapreduce and manually set up my own hadoop cluster on ec2 then i assume i could install mono without difficulty,['.net'] +21659,retrieving the com class factory for component error while generating word document i am trying to edit a word document from vbnet using for the most part this codehow to automate word from visual basic net to create a new documentit works fine on my machine but when i publish to the server i get the following errorretrieving the com class factory for component with clsid 0209ff0c046 failed due to the following error 800705description an unhandled exception occurred during the execution of the current web request please review the stack trace for more information about the error and where it originated in the codeexception details systemunauthorizedaccessexception retrieving the com class factory for component with clsid 0209ff0c046 failed due to the following error 800705the actual error happens when i try to just create a word application object dim oword as new wordapplicationusing visual studio 2008 and vbnet 35 i made a reference to the microsoft word 100 object library and i see interopworddll file in the bin directory using ms office 2003 on development machine and windows server 2003still fairly new to net and do not have much knowledge about window server but unauthorizedaccessexception sounds like a permission issue i am wondering if someone could point me in the right direction on what i might need to do to give my little application access to use word,['asp.net'] +21666,use phpjquery ajax to check mysql database for changes and load the changes i have a database of links that users can submit every time a user submits a new link it is added to the database i have a separate page that lists all the submitted links how can i have this separate page check the database for changes and load them with ajax when it finds them,"['jquery', 'mysql']" +21693,good readings on unixlinux socket programming though i have not worked with sockets professionally i find them interesting i read some part of unix network programming by richard stevens considered to be the bible i suppose as it is referred by everyone i ask but the problem is the examples require a universal header unph which is a pia to usecan some of you suggest a good reading for socket programming in unixlinux considering i am relatively experienced cc coder,['c++'] +21701,making tabulation look different than just whitespace how to make tabulation look different than whitespace in vim highlighted for examplethat would be useful for code in python,['python'] +21717,how can i check whether a byte array contains a unicode string in java given a byte array that is either a utf8 encoded string or arbitrary binary data what approaches can be used in java to determine which it isthe array may be generated by code similar tobyte utf8 hello worldgetbytesutf8alternatively it may have been generated by code similar tobyte messagecontent new byte256for int i 0 i messagecontentlength i messagecontenti byte ithe key point is that we do not know what the array contains but need to find out in order to fill in the following functionpublic final string getstringfinal byte datatoprocess determine whether datatoprocess contains arbitrary data or a utf8 encoded string if datatoprocess contains arbitrary data then we will base64 encode it and return if datatoprocess contains an encoded string then we will decode it and returnhow would this be extended to also cover utf16 or other encoding mechanisms,['java'] +21718,what happens when a thread throws an exception if i invoke the run method on a thread and the run method throws an uncaught exception what would be the outcome who catches this exception does it even get caught,['java'] +21726,truncate text containing html ignoring tags i want to truncate some text loaded from a database or text file but it contains html so as a result the tags are included and less text will be returned this can then result in tags not being closed or being partially closed so tidy may not work properly and there is still less content how can i truncate based on the text and probably stopping when you get to a table as that could cause more complex issuessubstrhello my strongnamestrong is emsamem iacutem a web developer026would result inhello my strongnamestwhat i would want ishello my strongnamestrong is emsamem iacutemhow can i do thiswhile my question is for how to do it in php it would be good to know how to do it in c either should be ok as i think i would be able to port the method over unless it is a built in methodalso note that i have included an html entity acute which would have to be considered as a single character rather than 7 characters as in this examplestrip tags is a fallback but i would lose formatting and links and it would still have the problem with html entities,"['php', 'html']" +21736,java metric unit conversion library i have an application that will need to perform a number of unit conversions metric to imperial imperial to metricis there an existing java library that does this or will i need to roll my own my initial google searches proved moderately useless,['java'] +21738,is there a standard pythonic way to treat physical units quantities in python is there a standard pythonic way to treat physical units quantities in python i saw different modulespecific solutions from different fields like physics or neuroscience but i would rather like to use a standard method than islandsolutions as others should be able to easily read my code,['python'] +21742,copying an nsarray with mutable copies of the original elements i am creating an array of dictionaries in a class i want to return a copy of that array to any other object that asks for it this copy that is passed to other objects needs to be modified without modifying the originalso i am using the following in a getter method of my class that holds the master arraynsmutablearray alloc initwitharraymasterarray copyitemsyeshowever this seems to make all the dictionaries inside immutable how can i avoid thisi think i am missing something here any help will be much appreciated,['objective-c'] +21755,how do i thisplay progress during a busy loop i am working in c and wpf very new to both i have a loop that reads plenty of data from an external source the process takes about 20 seconds and i want to show the progress to the user i do not need any fancy progress bars so i chose to plot my progress in a label that will say step 110 then change to step 210 etcmy code looks something like this count is the number of steps in the loop i receive it in previous codestring countlabel counttostringfor i 0 i count i do analysis labelprogresscontent step itostringcountlabelhowever during that analysis the screen is stuck and the progress does not show as advancing i understand this behavior from my past in c where i would probably have a separate thread showing a progress bar receiving notifications from the loop or some form of repaintrefresh or forcing the windowapp to process its message queuewhats the right way to do it in c i am not tied to the label so if there is a simple progressbar popup screen i could use instead of this label it would also be greatthanks,['c#'] +21762,why do i get javalangabstractmethoderror when trying to load a blob in the db i have got a problem with jdbcihave the following codeblargeparam is a blob columnpreparedstatement pst connectionpreparestatementupdate gcp processparams log set blargeparam where idprocessparamslog1pstsetbinarystream1inputstream i get the following errorexception in thread main javalangabstractmethoderror oraclejdbcdrivert2cpreparedstatementsetbinarystreamiljavaioinputstreamv my connection string is jdbcoracleoci the oracle version is 11g from the error message it seems that something is missing but when i read from the same blob columnwith blobgetbytes everythingworksthe dlls of the instant client arecorrectly in the library paththis is the manifest of the oraclejdbc jar in my class pathmanifestversion 10 specificationtitle oracle jdbc driver classes for use with jdk14 sealed true createdby 142 14 sun microsystems inc implementationtitle ojdbc14jar specificationvendor oracle corporation specificationversion oracle jdbc driver version 102040 implementationversion oracle jdbc driver version 102040 implementationvendor oracle corporation implementationtime sat feb 2 114029 2008,['java'] +21765,why is this name with an underscore not cls compliant why do i get the compiler warningidentifier logicdomainobjectbase isnew is not clscompliantfor the following codepublic abstract class domainobjectbase protected bool isnew,"['c#', '.net']" +21770,getting started with tdd we are in the initial phase of trying to implement tdd i demod the visual studio team system code coverage tdd tools and the team is excited at the possibilities currently we use devpartner for code coverage but we want to eliminate it because its expensive we have very limited experience in tdd and want to make sure we do not go a wrong direction currently we are using sourcesafe for source control but will be migrating to team system in about a year i can tell you our applications are very data centric we have about 900 tables 60 stored procedures and about 45gb of data we have lots of calculations that are based upon userdata and different rates in the system also a lot of our code is based upon time calculate interest to the current date some of these calculations are very complex and very intensive only a few people know the details for some of them we want to implement tdd to solve qa issues a lot of developers are forced to fix bugs in areas they are not familiar with and end up breaking something there are also areas that developers are almost afraid to touch because the code is used by everything in the system we want to mitigate this problem i am afraid since our code is so data centric that implementing tdd might be a little bit more complex than most systems i am trying to come up with a gameplan that i can present to management but i want to hopefully not get caught up in some of the tdd beginner mistakes also if tools facilities in team system make tdd more complete then that would be nice but we do not want to wait for team system to get startedthe first question we our asking is should we just start with the tools in visual studio i have read post were people complain about the intrinsic tools in visual studio need to create a separate project to create your test but the one thing about the tools in visual studio is they are free and the integration is good if we decide to go the other route in using something like xunit mbunit or nunit then we are most likely going to have some maybe significant cost1 if we want ide integration failed to mention most of our code is vbnettestdrivennet or resharper or 2 if we want code coveragencover seems pretty pricey for its functionalityalso i have seen some pretty cool functionality demoed in visual studio 2010 like the ability to do input testing data entered on a form or the ability to record what the user has done and then feed that into your unit test to reproduce a problemalso although i do not quite grasp the mocking object concept yet i know a lot of people feel it is a must the question is can all the mocking frameworks plug into visual studios version of tdd mstest i have advised management that we should probably just add regression testing going forward new development or found bugs but not try to go through all our code and put in unit tests it would be way too big of projectanyways i would appreciate anyones help,['.net'] +21778,ajax back button and dom updates if javascript modifies dom in page a user navigates to page b and then hits back button to get back to the page a all modifications to dom of page a are lost and user is presented with version that was originally retrieved from the serverit works that way on stackoverflow reddit and many other popular websites try to add test comment to this question then navigate to different page and hit back button to come back your comment will be gonethis makes sense yet some websites applecom basecamphqcom etc are somehow forcing browser to serve user the latest state of the page go to click on say downloads link at the top and then click back button all dom updates will be preservedwhere is the inconsistency coming from,['javascript'] +21781,grouped uitableview row animation quirks i have got a grouped uitableview with a couple of rows and i am animating a few more rows in and out on the toggle of a button the problem is that with any of the row animation types i am using top bottom the animation looks horrible heres a screenshot midanimationis there a reason why it is looking so bad or do all grouped table view animations look this shockingi think it only looks so bad when the first or last row in a section is being animated so i am just wondering if there is any way to get it looking a bit better otherwise i think i will just call reloaddata and have it all just appearthanks for your helpmichael,['iphone'] +21784,performance extension method vs instance method is there any performance difference between an instance method and an extension method,"['c#', 'asp.net']" +21794,how can i get configurationmanager to load application settings from multiple files i am writing applications that interoperate with a thirdparty application this application exposes an api to developers via methods in a dll some time ago the vendor of this app started integrating their own net components into their program and when they did they decided that their components should use the configurationmanager to get settings at runtimewhat this means their program fooexe calls fooenginedll and it reads its settings from fooexeconfig my program barexe also calls fooenginedll and it reads its settings from barexeconfigwell that is just plain wrong but how do i fix itthe simple workaround is to replicate fooexeconfigs settings in barexeconfig thatll work but it is stupid it means that from an administrative standpoint a given setting has to be maintained in and different files that is going to fail sooner or lateri tried putting a configsource attribute on the appsettings section in my config file as it happens i am using the applicationsettings section for my settings and they are using the appsettings section for theirs so i can live with simply getting that section from a different file but the configurationmanager does not like that it wants the path in configsource to be not only relative to but below my programs directoryi can physically read their settings file into an xmldocument and then set them myself but now i am tightly coupling my code to their implementation if they put out a new release that moves the settings to the applicationsettings section which is where they should be now that it is 2009 my code will breakis there another way out of this,"['c#', '.net']" +21796,how can i migrate my database with rails to the first revision without dropping the database first i have a database set up for my rails installation and some migrations set up i would like to be able to reset my database back down to having no tablesconstraintsetc but cannot find a reasonable way to do this without knowing the number of migrations or the timestamp of the first migration here are my options as i see themrake dbmigrateresetrake dbmigratedown version20090701154839 where 20090701154839 is the timestamp associated with the first migrationrake dbrollback step15 where there have been 15 migrationsthe problem with dbmigratereset is that it drops the database first it does dbdrop dbcreate then dbmigratethe problem with dbmigratedown is that i do not want to encode the version of the beginningthe problem with dbrollback is that i do not know the number of steps it is back to the beginningwhat are my options,['ruby-on-rails'] +21802,assigning result of function which returns a foo to a const foo i have got a function which returns an object of type foofoo getfooi know the following will compile and will work but why would i ever do itconst foo myfoo getfooto me the following is much more readable and does not force me to remember that c allows me to assign an rvalue to a const referenceconst foo myfoo getfoowhat are the differences between the two why would i use the first over the second why would i use the second over the first,['c++'] +21804,using regular expressions to extract the first image source from html codes i would like to know how this can be achievedassume that there is a lot of html code containing tables divs images etcproblem how can i get matches of all occurances more over to be specific how can i get the img tag source src exampleimg src alt how can i print out in this case i want to assume that there are also other tags in the html code as i mentioned and possibly more than one image would it be possible to have an array of all images sources in html codei know this can be achieved way or another with regular expressions but i cannot get the hang of itany help is greatly appreciated,"['php', 'html']" +21806,perlembed c mono linux has anyone attempted using perlembed in mono on linuxhere is the link perlembedhere is my first attempt at the dllimport signaturesprivate const string perl lib usrlibperl5588i386linuxthreadmulticorelibperlsodllimportperl lib entrypoint perl alloc setlasterror truepublic static extern intptr allocdllimportperl lib entrypoint perl construct setlasterror truepublic static extern void constructintptr hperldllimportperl lib entrypoint perl destruct setlasterror truepublic static extern void destructintptr hperldllimportperl lib entrypoint perl free setlasterror truepublic static extern void freeintptr hperldllimportperl lib entrypoint perl parse setlasterror truepublic static extern void parseintptr hperl intptr null int argc stringbuilder argv stringbuilder envdllimportperl lib entrypoint perl run setlasterror truepublic static extern void runintptr hperldllimportperl lib entrypoint eval pv setlasterror truepublic static extern void evalstring expr bool flagthe core directory can change per linux thistro the following code runs but crashes on the parse methodtry consolewritelinealloc intptr perl alloc consolewritelineconstruct constructperl consolewritelineparse parseperl intptrzero 3 new stringbuildere 0 new stringbuilder consolewritelinerun runperl consolewritelineeval evala 314 a 2 true consolewritelinedestruct destructperl consolewritelinefree freeperl catch exception exc consolewritelineexctostringmy crash readsgot a sigsegv while executing native code this usually indicatesa fatal error in the mono runtime or one of the native librariesused by your applicationstacktracein wrapper managedtonative wootparse intptrintptrintsystemtextstringbuildersystemtextstringbuilder 0x4in wrapper managedtonative wootparse intptrintptrintsystemtextstringbuildersystemtextstringbuilder 0xf9f85in wootmain 0x8din wrapper runtimeinvoke systemobjectruntime invoke void objectintptrintptrintptr 0x7c79b09native stacktrace monomono handle native sigsegv0xbb 0x81368fb mono 0x8105670 0x4c45a440 usrlibperl5588i386linuxthreadmulticorelibperlsoperl parse0xa3 0x4c6e6e93 0x43ad78 0x434cae 0x434abe monomono runtime exec main0x62 0x80ae5a2 monomono runtime run main0x152 0x80af6e2 monomono main0xef9 0x805dae9 mono 0x805c702 liblibcso6 libc start main0xdc 0x4c48d724 mono 0x805c651there are some perl sys init3 and perl sys term calls that perlembed mentions but i have not been able to call those methods through dllimport i always get entrypointnotfoundexception in those cases i am sure they are in a different file i need to importcan someone direct me in the correct way to call dllimports to perlembed,['c#'] +21821,is it possible to write an impure template in c is it possible to write an impure template in c that is a template that will sometimes give a different resulting type or int for the same template parameters for example is it possible to write a template foot where foointtype is sometimes char and at other times float or a template foot where foodoublemy static const int is sometimes 10 and other times 20,['c++'] +21840,iterate over tuple how can i iterate over a tuple using c11 i tried the following but that does not workforint i0 istdtuple sizetvalue i stdgetimy tupledo stherror 1 sorry unimplemented cannot expand alistener a into a fixedlength argument list error 2 i cannot appear in a constant expressionso how do i correctly iterate over the elements of a tuple,['c++'] +21847,force net interop to use local com dll is it possible to force an interop assembly to reference a local copy of its associated com dllheres the scenarioi have a net app that references an interop assembly interopotaclientdll which is the interop for a com dll otaclientdll which is the automation api for hp quality center i am not very knowledgable on com but as i understand it the interop assembly looks up the com classes via guid references in the registry rather than pointing to a specific filethe issue i have is that the copy of otaclientdll that the registry keys point to gets overwritten by different versions depending on which version of qc i have just logged into in a browser and the different versions of these dlls are not compatible with each other the net app will only be connecting to a specific version of qc so i cannot have the com dll varying in this wayany suggestions would be greatly appreciated as this behaviour is really irritating i have seen other questions on com interop issues but they all seem to be about forcing a local version of the interop dll to be used instead of one in the gac rather than this particular scenario involving the actual com dll,['.net'] +21857,read xml file using javascript hi friendsmy xml file format is as belowmarkers marker typetype titletitle addressaddress latitudelatitude longitudelongitude marker marker typetype titletitle addressaddress latitudelatitude longitudelongitude marker markersplease suggest me how can i read all the marker elementi need to get value of all child element of the markerthanks,['javascript'] +21860,file exists by file name pattern i am using fileexistsfilepathwhat i would like to do is swop this out for a pattern because the first part of the filename changesfor example the file could be01 peachxml02 peachxml03 peachxmlhow can i check if the file exists based on some kind of search pattern,"['c#', '.net']" +21865,combine javascript files at deployment in python i am trying to reduce the number of scripts included in our website and we use buildout to handle deployments has anybody successfully implemented a method of combining and compressing scripts with buildout,"['javascript', 'python']" +21869,instancing a class with an internal constructor i have a class whose constructor is defined as internal which means i cannot instantiate it while that may make sense i would still like to do it once for debugging and research purposesis it possible to do so with reflection i know i can access privateinternal members but can i call an internal constructoror as the constructor does nothing important can i use reflection to say look just give me an instance of the class without calling the constructor i will do it is work manuallyperformance and stability is not an issue here as it is not production codeedit just as clarification sadly i do not control the other assembly and do not have it is source code i merely try to understand how it works as it is documentation is next to nonexistent but i am supposed to interface with it,"['c#', '.net']" +21906,how do i determine if a database role exists in sql server i am trying to figure out how i can check if a database role exists in sql server i want to do something like thisif not exists select 1 from sometable where rolenamerolebegincreate role role authorization myuserendwhat tableproc should i use here,['sql'] +21908,fast algorithm for drawing filled circles i am using bresenhams circle algorithm for fast circle drawing however i also want to at the request of the user draw a filled circleis there a fast and efficient way of doing this something along the same lines of bresenhamthe language i am using is c,['c'] +21918,is it possible to bulk delete from a manymany association with hql and if so what is the syntaxassume that i want an instance of foo to be unassociated from all instances of barin sql it would simply bedelete from foo bar mappingwhere foo id in hql i assumed it would be something likedelete from barfoos fooswhere foosid idwhere foos is a mapped collection of foobut appears to be wrong givingorghibernatehqlastquerysyntaxexception barfoos is not mappedis this even possible with hql,['java'] +21926,how do i generate rdoc for all of rails i can dosudo gem rdoc activerecord noriand sudo gem rdoc actionpack noriboth of which give me good docsbutsudo gem rdoc rails norigives me pretty much nothing as the rails gem itself is really just a holder for the others how can i generate the equivalent of,"['ruby-on-rails', 'ruby']" +21934,how can i add a css class to an updatepanel in aspnet how can i add a css class to an updatepanel in the c code behind file of aspnet,"['c#', 'asp.net', 'css']" +21940,how to find what numbers in a set add up to another given number heres a problem that i seem to be running into working with an accounting systemi have a set of transactions but their sum does not equal the amount that the accounting department thinks that it should they are not questioning the math just the transactions being included pis there an algorithm that would help me determine which transactions in the set should not be included in order for the sum to match a given amountgiven set 2 4 5 7given sum amount13result set247editthere is less than 100 transactions in the set does anyone have a c example as there is not one on the solving the npcomplete problem in xkcd question man i should have gotten a cs degree,['c#'] +21942,is there cleaner syntax for where id 1 and id 2 and id 7 is there a cleaner way to perform this query in mysqlselect from table where id 1 and id 2 and id 7likeselect from table where id 127,['mysql'] +21966,which datatype is better to use text or varchar this question is based on two things performance and sizewhich datatype is better to use text or varchar based on performance which will affect and which will impove,['mysql'] +21967,autofac test all registered types can be resolved i have a bunch of types registered with autofac and some of the dependencies are rather deep is there a built in way to test that i can resolve all registered types i want to fail fast at application startup and not several minutes later part way inthis is what i am currently doing and it seems to work but i still wonder if there is not a better way public void verifyallregistrations foreach icomponentregistration registration in containercomponentregistrations bool isnewinstance registrationresolveinstance container new parameter0 new thisposer out isnewinstance private class thisposer ithisposer public void thispose noop public void addinstanceforthisposalithisposable instance instancethispose,['c#'] +21970,slow sqlite insert using the jdbc drivers in java i just inserted 1million records into a simple sqlite table with five columns it took a whooping 18 hours in java using the jdbc drivers i did the same thing in python25 and it took less than a minute the speed for select queries seem fine i think this is an issue with the jdbc drivers is there a faster driver for sqlite3 in java speed of inserting large numbers of rows is important for my schema migration script and i would rather not have to use an external script to do the migrations if i do not have to edit fixed with connectionsetautocommitfalsethanks mark rushakoff for hinting me to the solution,['java'] +21972,css horizontal menu equally spaced i guess this is a common question but have not found any good answer about it and questions around here are not exactly my case also this is my first question so please do not be too harsh on me loli have a standard css menu made with ul and li tags i need them to get to cover the whole page horizontally not my real case but i will take this to simplify the situation however the items are created dynamically and so i am not able to hardcode any with to li items nor marginsi have seen solutions using javascript to set those values but i would really love to avoid themlastly i have seen a pretty good solution which is settingmenu width 100 etc menu ul thisplay tablemenu ul li thisplay tablecellthis will create the desired behavior in most browsers except for ieany ideas thanks in advanceedit thanks for the responses however as the code that generates the items is not mine i am not able to set inline styles when creating them without using javascript later,['css'] +21995,create a pdf file with php i want to create pdf file from my web page written by php my document must produce from mysql and produce pdf filei want to be to save this pdf and to readplease give me code sample,['php'] +22016,stretch a row if data overflows in jasper reports how do i stretch a row when data overflows the band height in jasper reports i have set the stretch with overflow flag as true but it does not work,['java'] +22019,why do these division equations result in zero the result of all of the division equations in the below for loop is 0 how can i get it to give me a decimal eg297 315 030793650793650793650793650793651codeusing systemnamespace testdivide class program static void mainstring args for int i 0 i 100 i decimal result i 100 long result2 i 100 double result3 i 100 float result4 i 100 consolewriteline012 345 6 i 100 i 100 result result2 result3 result4 consolereadline answerthanks jon and everyone this is what i wanted to dousing systemnamespace testdivide class program static void mainstring args int maximum 300 for int i 0 i maximum i float percentage i floatmaximum 100f consolewritelineon 0 1 finished i percentage consolereadline,['c#'] +22050,how to set css for thisabled checkboxes i would like change the css for thisabled checkboxes in a grid they are too hard to see for the users what is a simple way to do thismy preference in technologies used in descending ordercssjavascriptjqueryother,"['html', 'css']" +22051,how to create uncompressed zip archive in java i am using the zip utility package of java and wanted to know how to create a zip file with no compression at all setting the level to 0 does not help is this rightalso when i used the stored method it throws following exceptionjavautilzipzipexception stored entry missing size compressed size or crc32i can set the size but now following exception is thrownjavautilzipzipexception invalid entry crc32 i am just following all the examples available by searching on web and am not able to really understand it properly i guess it would be great if someone can help me on this and provide me suggestion to correct the problem i might be doing,['java'] +22059,embedding base64 images purely out of curiosity what browsers does base64 image embedding work in what i am referring to is thisi realize it is not usually a good solution for most things as it increases the page size quite a bit i am just curioussome exampleshtmlimg altembedded image srcdataimagepngbase64ivborw0kggoansuheugadia cssdivimage width100px height100px backgroundimageurldataimagepngbase64ivborw0kggoansuheugadia,['html'] +22073,can jsonnet handle a list listuser list loadusersjobject json new jobjectjsonusers new jvaluelistdoes not seem to be workingerror could not determine json object type for type systemcollectionsgenericlist1,"['c#', 'asp.net']" +22078,what is the cost of calling arraylength while updating for loops to foreach loops in our application i came across a lot of these patternsfor int i 0 and alength i n i instead offor int i 0 i alength i i can see that you gain performance for collections because you do not need to call the size method with each loop but with arraysso the question arose is arraylength more expensive than a regular variable,['java'] +22079,preferred javascript mode for emacs is it js2mode from yegge there are a couple javascript modes out therejs2mode by steve yegge javascriptel by karl landstramespressosomething else does anyone have a recommendation on which to useedit2011 june 11 this is sort of an old outdated question at this point fyi emacs v23 now includes a javascript mode it is called jsmode and it is basically a renamed and updated espresso mode i have chosen to use the builtin mode,['javascript'] +22094,how to create nested objects using accepts nested attributes for i have upgraded to rails 233 from 21x and i am trying to figure out the accepts nested attributes for method i can use the method to update existing nested objects but i cannot use it to create new nested objects given the contrived exampleclass product activerecordbase has many notes accepts nested attributes for notesendclass note activerecordbase belongs to product validates presence of product id bodyendif i try to create a new product with a nested note as followsparams name test notes attributes 0 body bodyp productnewparamspsaveit fails validations with the messageactiverecordrecordinvalid validation failed notes product cannot be blanki understand why this is happening it is because of the validates presence of product id on the note class and because at the time of saving the new record the product object does not have an id however i do not want to remove this validation i think it would be incorrect to remove iti could also solve the problem by manually creating the product first and then adding the note but that defeats the simplicity of accepts nested attributes foris there a standard rails way of creating nested objects on new records,['ruby-on-rails'] +22098,trying to understand jqgrid for jquery how do i change the url for my ajax call i have everything working from the tutorial replacing it with my data but it is a hardcoded situation for example in the tutorial which is what i have working i havejquerydocumentreadyfunction jquerylistjqgrid url datatype xml mtype get colnamesproductidtitle descriptionpricetaxnotes colmodel nameinvid indexinvid width55 nameinvdate indexinvdate width90 nameamount indexamount width80 alignright nametax indextax width80 alignright nametotal indextotal width80 alignright namenote indexnote width150 sortablefalse pager jquerypager rownum10 rowlist102030 sortname title sortorder desc viewrecords true imgpath caption product list but the url is hard coded to pull up data the tutorial hasjquerydocumentreadyfunction jquerylistjqgrid urlexamplephp datatype xml mtype get colnamesinv nodate amounttaxtotalnotes colmodel nameinvid indexinvid width55 nameinvdate indexinvdate width90 nameamount indexamount width80 alignright nametax indextax width80 alignright nametotal indextotal width80 alignright namenote indexnote width150 sortablefalse pager jquerypager rownum10 rowlist102030 sortname id sortorder desc viewrecords true imgpath themesbasicimages caption my first grid obviously the data in my querystring will change and i would not always want the same url of and the tutorial with examplephp needs querystring variables so it can get the right data but they never show that part that i can find so how do i change the querystring how do i send items dynmically also the pager buttons send stuff like this because of the hardcode urlrows10sidxproductnamesorddescnd1248988261293 searchfalsehow can i just have a url like testthe right variables how can i change the querystringthank you for any help i hope it is not too obvious i found setgridparamurlnewvalue but did not understand how to use ithere is the documentation the tutorial is at the first part topedit thanks for the below i am trying to see how they use the setgridparam in their tutorial with examplephp they simply have examplephp and i cannot see how they got the querystring variables there from the html page to the examplephp page setgridparam may be the right way to accomplish this but it is no where in the example so i cannot figure out how they passed the initial querystring variables overi know that i can do this function gridsearch listsetgridparam url page1 triggerreloadgridreload grid trigger return false input idsdata classeditbutton typesubmit valuesearch onclickreturn gridsearchand that that will reload the grid i tested it it works but how did they send over items in the tutorial in the first place what if i do not want a button to reload but just pass in variables for it to initially load,['jquery'] +22099,how do you control mysql timeouts from sqlalchemy whats the right way to control timeouts from the client when running against a mysql database using sqlalchemy the connect timeout url parameter seems to be insufficienti am more interested in what happens when the machine that the database is running on eg thisappears from the network unexpectedly i am not worried about the queries themselves taking too long the following script does what youd expect ie time out after approximately one second if somehost is unavailable before the while loop is ever reached but if somehost goes down during the while loop eg try yanking out its network cable after the loop has started then the timeout seems to take at least 18 seconds is there some additional setting or parameter i am missingit is not surprising that the wait timeout session variable does not work as i think that is a serverside variable but i threw it in there just to make surefrom sqlalchemy import from sqlalchemyexc import import timeimport sysengine create enginemysqluserpasswordsomehosttestconnect timeout1try engineexecuteset session wait timeout 1 while true t timetime print t engineexecuteshow tablesexcept dbapierror passfinally print timetime t seconds to time out,"['python', 'mysql']" +22101,what should i name my php class file i have seen many different naming schemes and extensions used for php files that are basically just classes some examplesmyclassphpmyclassclassphpmyclassclasswhat is the difference and which is better,['php'] +22111,get url for mediawiki page given the title programmatically in php how can i get url for an article in mediawiki given the titlei want to create links to certain pages in the skin template programmatically using php right now i am doing thisa hrefphp wgscriptpath indexphppage titlepage titleawhich is a bit too wordy i would like something php page link by titlepage title thanks,['php'] +22127,cron job on ubuntu for php i am using ubuntu on the server and i am using putty to access i want to create cronjobs for my php site how can i do this,['php'] +22132,will there be generic attributes in c 4 so if there is not particular reason why there is not generic attributesi am wondering maybe they will be implementedthose would be great for aspnet mvc action filters,['c#'] +22147,windows service terminated unexpectedly i have a windows service which has a number of threads that do some workall has been going well in testing until once where i saw windows service terminated unexpectedly in the event viewer how do i go about trying to debug where this is happening i have exceptions being caught under normal circumstances but not in this casei do not know where to startjd,['c#'] +22152,special random number i would like to have a random number like thisin crandom r new randomrnext 010but it is important to the random number be more near 8or it be usually big i mean if we use a forfor int i 0 ii write rnext 010the result be like this8 7 6 9 1 0 5 3 22 3 8 9 7 7 6 2 38 8 9 7 2 8 2 8 43,['c#'] +22154,anonymous type in repeater databound event i am setting the datasource of an aspnet repeater as followsrpttargetsdatasource from t in dbsalestargets select new ttarget tsalesreprepname now in the repeaters ondatabound event how can i retrieve the repname and target properties from the anonymous type contained in eitemdataitemmany thanks,"['c#', 'asp.net']" +22159,create a css rule class with jquery at runtime usually i have a css file which has the following rulemywindow position fixed zindex 102 thisplaynone top50 left50how can i avoid creating such a static css file by adding the css information during runtime actions to the body or something similar only using jqueryi want to define it once but with jquery and use it many times later that is why i do not want to add it each time to the specific dom elementsi know the simple features cssattr1 value but how can i create a complete reusable css rule,"['jquery', 'css']" +22172,javascript or php option to detect aim status the website is the code i use for the status indicators is img src url greengifoff url offlinegifwhich is a neat thing that bigoscaraolcom lets you do it redirects it to whatever image you have set for the on url if they are online and same for off url for offline however i want to use this in an if statement in php or javascript to thisplay different things currently i am using thisfunction getaimscreenname ch curl init url screennameon urltrueoff urlfalse curl setoptch curlopt urlurl curl setoptch curlopt returntransfer1 added to fix php 516 issue curl setoptch curlopt header 1 result curl execch curl closech iferegitrueresult return true else return false if getaimimperialpalaces print online else print offline the problem with this code is that for some reason at random times it can take up to 12 seconds for it to actually retrieve the results whereas the standard img trick is almost instant is there a known issue with curl is there a faster way i have seen someone try to read the src of the img tag and do an if statement like that but i couldnt get it to work,"['php', 'javascript']" +22179,what is the most compatible way to install python modules on a mac i am starting to learn python and loving it i work on a mac mainly as well as linux i am finding that on linux ubuntu 904 mostly when i install a python module using aptget it works fine i can import it with no troubleon the mac i am used to using macports to install all the unixy stuff however i am finding that most of the python modules i install with it are not being seen by python i have spent some time playing around with path settings and using python select nothing has really worked and at this point i am not really understanding instead i am just poking aroundi get the impression that macports is not universally loved for managing python modules i would like to start fresh using a more accepted if that is the right word approach so i was wondering what is the method that mac python developers use to manage their modulesbonus questions do you use apples python or some other versiondo you compile everything from source or is there a package manger that works well finkany tips or suggestions here are greatly appreciated thanks for your time,['python'] +22181,how to get a color image in iphone sdk i want something as followsuiimage solid uiimage imagewithcoloruicolor darkgraycolorto create an image with respect to some colorhow to do it in iphone sdk,['iphone'] +22187,how to get the length of a mp3 in c yes this is an exact duplicate of this question but the link given and accepted as answer is not working for me it is returning incorrect values a 2 minutes mp3 will be listed as 130 3 minutes as 220 with no obvious patternso here it is again how can i get the length of a mp3 using c orwhat am i doing wrong with the mp3header classmp3header mp3hdr new mp3headerbool boolismp3 mp3hdrreadmp3information1mp3ifboolismp3 responsewritemp3hdrintlength,"['c#', '.net']" +22199,win32 api to do wildcard string match i am looking for a wildcard string match api not regex match i cannot use anything other than win32 apis,"['c++', 'c']" +22206,set php include path from nginx apache lets you set phpini values for virtual hosts with the php value directive does nginx have something similar is there another way to set the include path on a persite basis,['php'] +22207,javascript stringreplace with dynamic regular expressions i have the following code which works but i need to inject some different stuff into the regular expression object regex2 at runtime however textreplace does not seem to like a string object for the regular expression so how can i make this workvar regex2 documentwriteresult textreplaceregex2 br,['javascript'] +22212,how does synchronized lockunlock in objectivec does synchronized not use lock and unlock to achieve mutual exclusion how does it do lockunlock thenthe output of the following program is only hello worldinterface mylock nslocknslockingendimplementation mylock idinit return super init voidlock nslogbefore lock super lock nslogafter lock voidunlock nslogbefore unlock super unlock nslogafter unlockendint main int argc const char argv nsautoreleasepool pool nsautoreleasepool alloc init mylock lock mylock new autorelease synchronizedlock nsloghello world pool drain,['objective-c'] +22220,ubuntu virtualenv a mess virtualenv hates thistpackages wants sitepackages can someone please explain to me what is going on with python in ubuntu 904i am trying to spin up virtualenv and the nositepackages flag seems to do nothing with ubuntu i installed virtualenv 133 with easy install which i have upgraded to setuptools 06c9 and everything seems to be installed to usrlocallibpython26thistpackagesi assume that when installing a package using aptget it is placed in usrlibpython26thistpackages the issue is there is a usrlocallibpython26sitepackages as well that just sits there being empty it would seem by looking at the path in a virtualenv that this is the folder virtualenv uses as backup thus even thought i omit nositepackages i cant access my local systems packages from any of my virtualenvsso my questions arehow do i get virtualenv to point to one of the thistpackageswhich thistpackages should i point it to usrlibpython26thistpackages or usrlocallibpython26thistpackageswhat is the point of usrlibpython26sitepackages there is nothing in thereis it first come first serve on the path if i have a newer version of package xyz installed in usrlocallibpython26thistpackages and and older one from ubuntu reposaptget in usrlibpython26thistpackages which one gets imported when i import xyz i am assuming this is based on the path list yeswhy the hell is this so confusing is there something i am missing herewhere is it defined that easy install should install to usrlocallibpython26thistpackageswill this affect pip as wellthanks to anyone who can clear this up,['python'] +22223,another javalangclassnotfoundexception in ants junit task i cannot figure out why i am getting this exception from my ant buildxml file i checked and everything is in the classpath why must this be so complicatedi had trouble with ant in the past and it seems it always is something related to the classpath i am pointing to junitjar using both ways within eclipse windowpreferencesantruntimeant homeadd external jars and also within the buildxml script this time ant is not able to locate my test class in the junit task is there something wrong with the way i am pointing to this classtarget nameinit property namesourcedir valuesrc property nameoutputdir valuebuild property namejunitlocation valuecorgjunit4 431junitjar targettarget nameclean dependsinit delete diroutputdir targettarget nameprepare dependsclean mkdir diroutputdir targettarget namecompile dependsprepare javac srcdirsourcedir destdiroutputdir classpathjunitlocationtargetpath idclasspath pathelement locationoutputdir pathelement locationjunitlocation pathtarget nametestapplication dependscompile echorunning the junit testsecho junit forkyes haltonfailureyes test namemypackagemytest formatter typeplain usefilefalse classpath refidclasspath junittargeti am always getting junit testsuite mypackagemytest junit tests run 1 failures 0 errors 1 time elapsed 0 sec junit caused an error junit mypackagemytest junit javalangclassnotfoundexception mypackagemytest junit at javaneturlclassloader1rununknown source junit at javasecurityaccesscontrollerdoprivilegednative method junit at javaneturlclassloaderfindclassunknown source junit at javalangclassloaderloadclassunknown source junit at sunmisclauncherappclassloaderloadclassunknown source junit at javalangclassloaderloadclassunknown source junit at javalangclassloaderloadclassinternalunknown source junit at javalangclassforname0native method junit at javalangclassfornameunknown sourcebuild failedapparently ant finds junitjar and attempts to start the test but why cannot it find my test class i point to the folder with compiled test class so i know that junit is on ants classpath at least but the classnotfound puzzles meany ideas perhaps many thanks,['java'] +22228,localization with jquery i have no idea how to handle localization with jquery i want to set an innerhtml with german text but if the browser is configured to use english then i want to set english textin php i use gettext for such stuff but how to do it in javascriptjquery,['jquery'] +22237,django newbie deployment question importerror could not import settings settings the app runs fine using django internal server however when i use apache mod python i get the below error file usrlocallibpython26thistpackagesdjangoconf init py line 75 in init raise importerror could not import settings s is it on syspath does it have syntax errors s selfsettings module eimporterror could not import settings settings is it on syspath does it have syntax errors no module named settingshere is the needed information 1 project directory rootdjangoprojectsmysite2 directory listing of rootdjangoprojectsmysitels ltrtotal 28rwrr 1 root root 546 aug 1 0834 managepyrwrr 1 root root 0 aug 1 0834 init pyrwrr 1 root root 136 aug 1 0835 init pycrwrr 1 root root 2773 aug 1 0839 settingspyrwrr 1 root root 1660 aug 1 0853 settingspycdrwxrxrx 2 root root 4096 aug 1 0904 pollsrwrr 1 root root 581 aug 1 1006 urlspyrwrr 1 root root 314 aug 1 1007 urlspyc3 app directory rootdjangoprojectsmysitepolls4 directory listing of rootdjangoprojectsmysitepolls ls ltrtotal 20rwrr 1 root root 514 aug 1 0853 testspyrwrr 1 root root 57 aug 1 0853 modelspyrwrr 1 root root 0 aug 1 0853 init pyrwrr 1 root root 128 aug 1 0902 viewspyrwrr 1 root root 375 aug 1 0904 viewspycrwrr 1 root root 132 aug 1 0904 init pyc5 anywhere in the filesystem running import django in python interpreter works fine6 content of httpdconflocation mysite sethandler pythonprogram pythonhandler djangocorehandlersmodpython setenv django settings module settings pythonoption djangoroot mysite pythonpath rootdjangoprojects rootdjangoprojectsmysiterootdjangoprojectsmysitepolls varw syspath pythondebug onlocation7 pythonpath variable is set to echo pythonpathrootdjangoprojectsmysite8 django settings module is set toecho django settings modulemysitesettings9 content of syspath is import sys syspath rootdjangoprojectsmysite usrlibpython26 usrlibpython26platlinux2 usrlibpython26libtk usrlibpython26libold usrlibpython26libdynload usrlibpython26thistpackages usrlocallibpython26thistpackageshow do i add settings location to syspath such that it persistent across sessions i have read umpteen no of post with people having the same issue it and i have tried a lot completely beats me as to what i need to dolooking for some helpthanks in advanceankur gupta,['python'] +22247,how can i simulate interfaces in c since c lacks the interface feature of java and c what is the preferred way to simulate interfaces in c classes my guess would be multiple inheritance of abstract classeswhat are the implications in terms of memory overheadperformanceare there any naming conventions for such simulated interfaces such as serializableinterface,['c++'] +22250,why is the eclipse ide getting slower i have downloaded the latest eclipse ide galileo and tested it to see if it good for developing web applications in java i have also tried the ganymede version of eclipse and find that is it also goodmy problem is that sometimes it hangs and stops responding while i am developing sometimes when i open a file eclipse hangs and does not respond for awhile it seems that eclipse is going slower and my job is getting slower because of the time that i am spending waiting for the response of eclipsewhen i went to netbeans 67 it was good and the performance was good the loading is faster and the ide responds well during my development testingmy computer has 1 gb of ram and a 16 ghz cpuwhat can you say about this,['java'] +22254,net inherited winforms form vs designer issue i have several forms in a c application i use visual studio 2010 beta but net 35 and c 3i have a base form called filteredqueryviewform in the shd namespace and i want some other forms to inherit it because they will basically do the same stuff but with some additionsi changed things from private to protected in the filteredqueryviewform class so they are accessible from the derived forms after this i have created a derived form and set the base class to filteredqueryviewformthe designer of the derived class complained about shdfilteredqueryviewform not having any constructors regardless of the fact it had one with 3 parameters i thought parameters can be a problem so i also created a public of course constructor without parameters but it still does not work the error message is the sameconstructor on type shdfilteredqueryviewform not foundand the designer of the derived class would not loadi have tried restarting vs2010beta recreating the derived form but nothing seem to help google did not yield any useful results for me on this problem is this a problem of visual studio 2010 beta or am i doing something wrong,['c#'] +22283,httpwebrequest has no close method i am very surprised to see httpwebrequest has no close method but its counterpart httpwebresponse has it makes me a little bit confused and inconvenient so we only need to call close on response and no need to treat with request my concern is about leaks and better resource usage efficiency i am using vsts2008 c net 35,"['c#', '.net']" +22288,what does a php function return by default if i return nothing explicitly what does a php function exactly returnfunction foo what type is itwhat value is ithow do i test for it exactly with did this change from php4 to php5is there a difference between function foo and function foo return i am not asking how to test it like if foo 0,['php'] +22291,pythons sum and noninteger values is there a simple and quick way to use sum with noninteger valuesso i can use it like thisclass fobject def init selfbar selfbarbarmylistfoo3foo34foo63200resultsummylist result should be 300i tried overriding add and int etc but i do not have found a solution yeteditthe solution is to implement def radd self other return other selfbaras will suggested in his post but as always all roads lead to rome but i think this is the best solution since i do not need add in my class,['python'] +22293,how to isolate your program from calls to a bad api when i developed a piece of academic software using java i was forced to use an api that was rather badly implemented this means that calls to this api for a certain set of input data would sometimes never return this must have been a bug in the software as the algorithms that it offered were deterministic ones and sometimes it would terminate on a set of data sometimes it would run into an infinite loop on the same set of datahowever fixing the api or reimplementing it was simply beyond scope i even had the source but the api heavily relied on other apis which were undocumented and without source and had by the time vanished from the web or never been there on the other hand this bad api was the only one out there that solved the specific problem i had so i really had to stick with itthe question is what is the cleanest way of dealing with an api that behaves that well nasty when i faced this problem i decided to put the calls to the api into a separate thread another thread would then occasionally check if this thread had terminated if a certain amount of time had passed i would kill the processing thread using threadstop and start the processing again hoping that it would return the next time now i know and knew back then that this method is deprecated and must not be used but in this academic context it was acceptable to have the software potentially run into an undefined state instead of having it crash it was also not acceptable to just ignore the processing thread that had run into an infinite loop because it did some quite cpuintensive operations that would slow down the users machine significantlyanother way which i did not try is to start the processing in a separate process instead of a thread because a subprocess can be killed cleanly without putting the software in an inconsistent state or could the new swingworker class which was not yet available have done the job it has a cancel method but the docs say that it attempts to cancel execution of this task so it does not look like a reliable approach either,['java'] +22307,remove a json attribute if i have a json object sayvar myobj test key1 value key2 valuecan i remove key1 so it becomestest key2 value,['javascript'] +22313,htmlencoding in javascriptjquery iam using javascript to pull a value out from a hidden field and thisplay it in a textbox the value in the hidden field is encodedfor exampleinput idhiddenid typehidden valuechalk amp cheese gets pulled intoinput typetext valuechalk amp cheese via some jquery to get the value from the hidden field itas at this point that i lose the encodinghiddenidattrvaluethe problem is that when i read chalk amp cheese from the hidden field javascript seems to lose the encoding to escape and i want the encoding to remainis there a javascript library or a jquery method that will htmlencode a string,"['javascript', 'jquery']" +22335,how can you read values from an open application in windows i want to create a program or use a program that will read the memory values out of another application does anyone know of an applicationlibrary that will do this the target app is this i would like to read the exchange rate values from it i am an experienced c programmer but have never worked with the win32user32 api which is what i am assuming i will have to deal with to pull this off any help that gets me going in the right direction is greatly appreciated updatei managed to use spy to get the window handle so i am sure i can get the values some how,['c#'] +22342,windows like services development in linux using mono i just moved from net development to linux mono development and i don have much experience with linux dev earlier i have a requirement to create a background service like windows services in mono c is it possible and is it possible to access the linux native apis from mono c like winapi calls from win c,['c#'] +22348,how do i use performancecountertype averagetimer32 i am trying to measure the time it takes to execute a piece of code on my production server i would like to monitor this information in real time so i decided to give performance analyser a whizz i understand from msdn that i need to create both an averagetimer32 and an averagebase performance counter which i duly have i increment the counter in my program and i can see the callcount go up and down but the averagetime is always zero what am i doing wrongheres a snippit of code long init call time environmenttickcount lots and lots of code count number of callsperformancecounter perf new performancecountercat callcount instance falseperfincrementperfclose count execution timeperformancecounter perf2 new performancecountercat calltime instance falseperf2nextvalueperf2incrementbyenvironmenttickcount init call timeperf2close average base for execution timeperformancecounter perf3 new performancecountercat calltimebase instance falseperf3incrementperf3closeperf2nextvalue,['c#'] +22363,getting multiple guice singletons of the same type can you get 2 singleton instances of the same underlying type this is obviously trivial in spring as it is based on named instances to which you attach a scope but i cannot see the equivalent in guice which is about binding types to implementation classes note that i do not want to have to bind to the instance as the instances in question are injected with other dependencies by guice,['java'] +22367,singleton logger static logger factory logger how to log i am wrapping the patterns practices enterprise library logging application block for an application written in neti want to be able to subclass a logger ie to provide domain specific loggingwhat is the best way to do thisfor eg i have a static logger class at the moment but this does not allow me to specialize it for domain specific loggingfor examplelogmydomainobj obj string msg,['c#'] +22368,what is the best way to get the executing exes path in net from program aexe located in cdir i need to open text file cdirtexttxt i do not know where aexe could be located but texttxt will always be in the same path how to get the name of the currently executing assembly from within to program itself so that i can access the text fileeditwhat if aexe is a windows service it does not have application as it is not a windows applicaionthanks in advance,"['c#', '.net']" +22372,multiple file selection for uploading in aspnet there are several resources available on net to upload multiple files but using multiple fileupload controls what i need to have multiple file selection dialog box so that user can select multiple files at one shot and then all files should be uploaded on one clickanyone of you have any ideathanks in advance,['asp.net'] +22377,how does fastcgi work on a web server eg apache 22 i had a look at the sources of fastcgi fcgi240 and actually there is no sign of forkif i am correct the web server spwans a process for fastcgi module compiled in it or loaded as a sodll and handles control of the main socket the port tcp80 usually over to iton nix the fastcgi module locks that socket using a file write lock libfcgios unixc989 on the whole file descriptor the listen socket indeed this way when new connections income only the fastcgi module is able to process thesethe incoming socket lock is released just before handing over to the http req processingas seen as fastcgi module is not multi processthread no internal usage of forkpthread create i assume the concurrent handling of multiple simultaneous connections is obtained through spwaning from the web server through os spawnchild of and fastcgi module processesif we spawn as example 3 fastcgi processes apache calls 3 x os spawnchild does that mean that we could only have max 3 requests served concurrentlya is my vision of fastcgi way of working correctb if the cost for the os to spawn a new processcreate a connection to local db could be considered negligible what are the advantages of fastcgi against an old fashioned executable approachthanksema,"['c++', 'c']" +22381,check if 2 urls are equal is there a method around that tests if 2 urls are equal ie point to the same placei am not talking about 2 urls with different domain names pointing to the same ip address but for example 2 urls that point to the same aspx pagecdefis equal to theseproductsdefaultaspxproductsnoteassumtionsquerystring values are ignoredaspnet pref cdefaultaspx is the default pageupdatethis is a very crude method that tests a url to see if matches the current urli tried the creating a new uri with both the local and check urls but dont know that works and went down the string checking avenuethe implemenation of the sitemapprovider skips this step if the url starts with http as this assumes an external url since i have an saas framework that will always ensure relative paths as these can be on different subdomains it easier to strip things downany comments on optimization i guess for a start we can pass in a variable containing the current url not sure of the overhead of calling httpcontextcurrentrequesturllocalpath many times summary assumes url is relative aspx page or folder path summary param nameurlparam returnsreturns public static bool currenturlmatchstring url string localurl httpcontextcurrentrequesturllocalpath if httpcontextcurrentrequesturlhost localhost localurl localurlsubstringlocalurlindexof 1 localurl localurlsubstringlocalurlindexof string compareurl urltolower remove querystring values if localurlcontains localurl localurlsplit0 if compareurlcontains compareurl compareurlsplit0 if localurlcontains localurl localurlsplit0 if compareurlcontains compareurl compareurlsplit0 prepare end of local url if localurlcontainsaspx if localurlendswith localurl stringconcatlocalurl prepare end of compare url if compareurlcontainsaspx if compareurlendswith compareurl stringconcatlocalurl if localurlendswith localurl stringconcatlocalurl defaultaspx if compareurlendswith compareurl stringconcatcompareurl defaultaspx if compareurlcontains compareurl compareurlreplace stringempty compareurl compareurlsubstringcompareurlindexof 1 compareurl compareurlreplace stringempty if localurl compareurl return true return false,"['c#', 'asp.net']" +22385,how to make scrollbars appear in a resizable panel when the contained control is too big for it i am developing a windows forms application net 20 vs 2005 i have a form that essentially contains a panel that is dynamically resized with the form thispanel1dockdockstylefillthis panel is simply used as a container at runtime a custom control will be added usercontrol ucnew usercontrolpanel1controlsadducucdockdockstylefillas this custom control has a minimum size requirement i want scroll bars to appear on the containing panel if it gets too small to show the entire control thispanel1autoscrolltruethis does not work i have tried to resize the panel using the anchor property rather than the dock property to no avail,['.net'] +22398,how can i set the color of a selected row in datagrid this seems like a nobrainer but i just cannot see how to do itthe default background color of a selected row in datagrid is so dark that i cannot read it is there anyway of overriding ittried this modified from neverminds link dgdatagridrowstyle style targettypextype dgdatagridrow styletriggers trigger propertyisselected valuetrue setter propertybackground valuegainsboro trigger styletriggers styledgdatagridrowstylebut still nothing,['c#'] +22399,iphone how do you color an image i would love to know how to color an image make a white png red for example i have seen various suggestions but never any confirmation that this is actually possible i have tried thisuiimage colorizeimageuiimage baseimage coloruicolor thecolor uigraphicsbeginimagecontextbaseimagesize cgcontextref ctx uigraphicsgetcurrentcontext cgrect area cgrectmake0 0 baseimagesizewidth baseimagesizeheight cgcontextscalectmctx 1 1 cgcontexttranslatectmctx 0 areasizeheight cgcontextsavegstatectx cgcontextcliptomaskctx area baseimagecgimage thecolor set cgcontextfillrectctx area cgcontextrestoregstatectx cgcontextsetblendmodectx kcgblendmodenormal cgcontextdrawimagectx area baseimagecgimage uiimage newimage uigraphicsgetimagefromcurrentimagecontext uigraphicsendimagecontext return newimagemyimageviewimage self colorizeimageuiimage imagenamedwhiteimagepng coloruicolor redcolorbut it does not work the image is still white on the screen,['iphone'] +22401,indexer as part of the interface in c in c whats the syntax for declaring an indexer as part of an interface is it still this something feels odd about using the this keyword in an interface,['c#'] +22403,equivalent of a windows service on osx with mono what do i need to do to have my netmono application run as a background process on osx and start when the os starts up assuming the application is otherwise ready to go on osxrelatedbuild an installer for net app that can run on windows and os x,['.net'] +22408,is c code faster than visual basicnet code is c code faster than visual basicnet code or that is a myth,['c#'] +22410,we have to use c for performance reasons in this age of many languages there seems to be a great language for just about every task and i find myself professionally struggling against a mantra of nothing but c is fast where fast is really intended to mean fast enough i work with very rational open minded people who like comparing numbers and all i have is thoughts and opinion could you help me find my way past subjective opinions and into the real worldwould you help me find research as to what if any other languages could be used for embedded and linux systems programming i very well could be pushing a false hypothesis and would greatly appreciate research to show me this could you please link or include good numbers so as to help keep the that is just hisher opinion comments to a minimum edit memory is not a serious constraint portability is not a serious concern this is not a real time system,['c'] +22415,difference between utility and helper classes are not utility classes really the same concept as helpers i mean utility methods do not extend an existing class such as helpers but the two types of methods really could be referred to as helpers in either case,['c#'] +22418,objectivec mutating method sent to immutable object error i am pretty new to objectivec and try to create a small app for the iphonei am nearly done beside this little error here actually i have searched hours with google to find a proper solution but unfortunately i am not able to find a solution which worksi am using this tutorial here to build up an uitableview uitableview tutorialthe full error message looks like this terminating app due to uncaught exception nsinternalinconsistencyexception reason nscfarray insertobjectatindex mutating method sent to immutable objectthis is the data controller headermylinksdatacontrollerhinterface mylinksdatacontroller nsobject nsmutablearray tablelist important part unsignedcountoflist idobjectinlistatindexunsignedtheindex voidadatansstring data important part voidremovedataatindexunsignedtheindexproperty nonatomic copy readwrite nsmutablearray tablelist important partand the data controller methodmylinksdatacontrollermimport mylinksdatacontrollerhimplementation mylinksdatacontrollersynthesize tablelist idinit if self super init nsloginitilizing datacontroller instantiate list nsmutablearray locallist nsmutablearray alloc init selftablelist locallist copy locallist release add initial data self adata self adatab return selflater on in the source code voidadatansstringdata tablelist addobjectdata here the app crashesi would pretty much appreciate any helpthank you for your support in advancedaniel,['objective-c'] +22433,different types of catransition types available in iphone sdk do anyone knows the link to the different types of name for available catransitionlike rippleswifti want to know all the available names,['iphone'] +22435,what is the advantage of using unescape on documentwrite to load javascript the code that you have to add to track a web page with google analytics looks likescript typetextjavascriptvar gajshost https documentlocationprotocol httpsl httpwdocumentwriteunescape3cscript src gajshost googleanalyticscomgajs typetextjavascript3e3cscript3escriptscript typetextjavascripttry var pagetracker gat gettrackeruaxpagetracker trackpageview catcherr scriptwhats the advantage of doing these linedocumentwriteunescape3cscript src gajshost googleanalyticscomgajs typetextjavascript3e3cscript3eversus these linedocumentwritescript src gajshost googleanalyticscomgajs typetextjavascriptscripti wrote some code that does something similar load javascript via document write but it does not use unescape and i am wondering if i should follow the googleanalytics example,['javascript'] +22446,how can i align text directly beneath an image i used to know how to put an image on top and then justify the text below the image so that it stays within the borders of the width of the image however now i have no idea how to do this how is this accomplished,"['html', 'css']" +22448,php converting excel xls to pdfs is there any phpjavaopen source software converters or php libraries that will convert an xls file to a pdf documentrundown have preexisting code generating xls spreadsheets circa 20022006 pre open xml version i believe need to turn them into pdfs for various reasonsbeen searching everywhere including here i think i just need a bump in the right direction i am sure there is something out there already that does it,['php'] +22456,google app engine repackaged package what is the purpose of the classes in this packagei want to use base64 encoding in my app as i am typing away in eclipse i am prompted if i want to import a class called comgoogleappenginerepackagedcomgooglecommonutilbase64i cannot find any documentation about what this class does no javadoc or no mention in the google app engine manual that i can see is this some kind of hidden api that i am not supposed to have access to,['java'] +22458,linq to dataset multiple group by on a data table i am using linq to dataset to query a datatable if i want to perform a group by on column1 on data table i use following queryvar groupquery from table in mytableasenumerablegroup table by tablecolumn1 into groupedtableselect new x groupedtablekey y groupedtablecountnow i want to perform group by on two columns coulmn1 and column2 can anybody tell me the syntax or provide me a link explaining multiple group by on a data tablethanks,['c#'] +22465,is this a proper way to destroy all session data in php got it from phpnet but i am not sure is this how everybody destroy all sessions unset all sessions session arrayif isset cookiesession name setcookiesession name time 420 session destroydoes the code will destroy all the sessions is it the most common way how do you guys destroy php sessionsoh yeah btw what is that session name all session name eg sessionvar1 sessionvar2 i dont need to use unset sessionvar1 any more rightwhats the different between using session destroy and unset session,['php'] +22472,how to return the correct contenttype for json in cakephp i am trying to set the contenttype header for a json response accessed with an ajax get request i have followed tutorials on blogs and the backery but i always receive texthtml back from cakephp how do i set the contenttype header correctlyheres my code at the momentpublic function admin controller actions ajax configurewritedebug 0 if thisrequesthandlerisget thisautorender false aco id thisparamsurlaco id aro id thisparamsurlaro id assertaco id null aro id null is numericaco id is numericaro id actions thisresourcegetactionsforcontrolleraco id aro id assertis arrayactions is arrayactions0 i made requesthandler part of the components property thisrequesthandlersetcontentjson thisrequesthandlerrespondasjson i have tried json json applicationjson but none of them work thissetjson content json encodearrayresponse actions0 thislayout null thisrenderjsondefault jsondefaultctp php echo json content any help would be appreciatedthanks isaac,['php'] +22479,linq expressions nhibernate and like comparison i am trying to do a like comparison based on an outside parameter passed by a search form that determines type of comparison string or string or string i was thinking in the following directionquery querywhere entitystringpropertylikesearchstring selectedcomparsiontypelike method would than based on selected type returnstartswith or endswith or substringmy knowledge of expressions is apparently far from great since i have not been able to construct a method that could yield the right result server side comparison in sql just like with startswith method,['c#'] +22492,which collection type should i use for best performance while setting wcf client service configuration there is an option collection type which defaults to systemarray if i change it to generic list is there any performance loss,['c#'] +22495,what is function tcf 0 seen when using gprof and g we use g 424 and i am trying to track down some performance problems in my codei am running gprof to generate the profile and i am getting the following strangeness in that the most expensive function is tcf 0each sample counts as 001 seconds cumulative self self total time seconds seconds calls mscall mscall name 40 004 004 1 40 9500 tcf 0this function then appears to calls most of my user functions ie it is the one that is called from main the nearest explanation that i found for this was here but that link refers to static objects and atexit and i do not think this applies in my caseif it is helpful i am using boost program options and fusion and the hdf5 librariesupdatethe command i use when building isg wreturntype wunused winline pg dlinux dhas setenv dfusion max map size15 dfusion max vector size15 g o0 param largefunctiongrowth300 param inlineunitgrowth200,['c++'] +22506,java create a file not a folder perhaps somewhat embarassing but after some hours i still cannot create a file in javafile file new filedirname filenametry this statement gives an exception the system cannot find the path filecreatenewfile this creates a folder also named a directory with the name filename filemkdirs systemoutprintlnfile null return filecatch exception e systemoutprintlnegetmessage return nullwhat am i missing here,['java'] +22534,is it possible to use an external sql file in a rails migration i have to create a rails migration which creates many triggers and stored procedures normally one would do that using the execute method but because of the size of the statements i would rather keep them in an external file and reference it from the migrationhow can i do that is it even possible,"['sql', 'ruby-on-rails']" +22539,jqueryajax submit all elements in form without manually entering them i would like to use jqueryajax to submit a form using post without having to specify everything manually in the data partthis is what i do not want data username documentgetelementbyidusernamevalue email documentgetelementbyidemailvalueis there a way to just have it include alla elements with their values from an entire form field this form is generated dynamically so it would save me a lot of time,"['javascript', 'jquery']" +22541,how do i prevent my unused global variables being compiled out i am using static initialisation to ease the process of registering some classes with a factory in c unfortunately i think the compiler is optimising out the unused objects which are meant to do the useful work in their constructors is there any way to tell the compiler not to optimise out a global variableclass someclass public someclass do something useful someclass instancemy breakpoint in someclas constructor does not get hit in my actual code someclass is in a header file and instance is in a source file more or less aloneedit as guessed by kjawolf this code is actually compiled into a static lib not the executable its purpose is to register some types also provided by the static lib with a static list of types and their creators for a factory to then read from on construction since these types are provided with the lib adding this code to the executable is undesirablealso i thiscovered that by moving the code to another source file that contains other existing code it works fine it seems that having a file purely consisting of these global objects is whats causing the problem it is as if that translation unit was entirely ignored,['c++'] +22546,aspnet username change i have an aspnet site which uses the aspnet membership provider each comment entry etc in the db is tracked by the userid since ms does not provide a way to change the username i have found the username in the users table in the db and there is only 1 place where the username appears my question is is it safe to provide an edit profile page where the user is allowed to edit their own username of course i would handle this change in the background by directly changing the username value in the dbare there any downsides to this i have created and modified some test accounts and it seems to be fine i am just wondering if there is any known negatives to this before putting it into production,['asp.net'] +22563,jquery how can i pass args to event handler how can i pass args to the event handler function this runs the function on page load which is not the desired effect i need this routine validatetext to run against several different textbox dropdown combinations can i reuse validatetext instead of creating one per textdropdown combination add blur event handler to the textbox with jquery when the page is finished loading documentreadyfunction mytextboxblurvalidatetextmytextbox select1 function validatetexttextbox dropdown var message message var isvalid false get the value the user type in var textboxvalue textboxval get the options from the lookup var options option dropdown loop through the options and compare it to value optionseachfunction var optvalue thisval if optvalue textboxvalue isvalid true if isvalid messagetexttextboxvalue is not a valid value from the list else messagetexttextboxvalue is perfectly valid,"['javascript', 'jquery']" +22570,junit throw warning while still passing test i am working on a project at the moment that were using junit to test but as its still fairly early stages a lot of features are not yet implemented though they already have tests written for themthis means these tests obviously always faili was wondering if anyone knew a way to get junit to pass the test while thisplaying a warning preferably with a customizable message so we can note that the feature is not yet implementedthe point of this being that we want to code to compile only if all tests pass and at the moment this simply is not possiblei realise we can just comment out or remove the problem tests but we then run the risk of forgetting to add them back in later,['java'] +22572,how do you force refresh of a wxpanel i am trying to modify the controls of a panel have it update then continue on with code execution the problem seems to be that the panel is waiting for idle before it will refresh itself i have tried refresh of course as well as getsizerlayout and even sent a resize event to the frame using the sendsizeevent method but to no avail i am at a loss here i find it difficult to believe there is no way to force a redrawing of this panel here is the code that changes the controlsdef hidebuttonsself selfnewbuttonshowfalse selfopenbuttonshowfalse selfexitbuttonshowfalse selfbuttonsizerdetachselfnewbutton selfbuttonsizerdetachselfopenbutton selfbuttonsizerdetachselfexitbutton loadinglabel wxstatictextselfsplashimage wxid any loading stylewxalign left loadinglabelsetbackgroundcolourwxwhite selfbuttonsizeraddloadinglabel selfgetsizerlayout selfsplashimagerefreshhas anybody else encountered anything like this and how did you resolve it if so,['python'] +22575,how to program in c with textmate as my ide yes i know there is monodevelop but what if i want to use textmate insteadso my question here is aimed at the net developer who has developed some c applications using textmate i am curious as to what their processworkflow is with this setupwhat is the best c bundle out there for syntaxlanguage grammarhow do you build your project easy to build app for 20 30 andor 35 frameworkcan you easily start a c application in visual studio and then continue to use textmate in it is placeare there too many pitfalls here in thinking i could do this and am i just taking crazy pills,['c#'] +22584,systemweb inside of appconfig file with clientauthenticationmembershipprovider added by default i just upgraded my windows forms project from net 30 to net 35 and the upgrade added the following to my appconfig file systemwebmembership defaultproviderclientauthenticationmembershipprovider providers add nameclientauthenticationmembershipprovider typesystemwebclientservicesprovidersclientformsauthenticationmembershipprovider systemwebextensions version3500 cultureneutral publickeytoken31bf3856ad364e35 serviceuri providersmembershiprolemanager defaultproviderclientroleprovider enabledtrue providers add nameclientroleprovider typesystemwebclientservicesprovidersclientroleprovider systemwebextensions version3500 cultureneutral publickeytoken31bf3856ad364e35 serviceuri cachetimeout86400 providersrolemanagersystemwebi thought that systemweb was only for web projects does this seem wrong,['.net'] +22598,innerhtml removes attribute quotes in internet explorer when you get the innerhtml of a dom node in ie if there are no spaces in an attribute value ie will remove the quotes around it as demonstrated below html head titletitle head body div iddiv1div iddiv2divdiv script typetextjavascript alertdocumentgetelementbyiddiv1innerhtml script bodyhtmlin ie the alert will readdiv iddiv2divthis is a problem because i am passing this on to a processor that requires valid xhtml and all attribute values must be quoted does anyone know of an easy way to work around this behavior in ie,['javascript'] +22601,how to mappath in a unit test in c i want to load an external xml file in a unit test to test some processing code on that xml how do i get the path of the fileusually in a web app i would doxdocumentloadservermappathmyfilexmlbut obviously in my unit test i have no reference to server or httpcontext so how can i map a path so that i do not have to specify the full pathupdatei just want to make it clear that the code i am actually testing is for an xml parser class something likepublic static class customerxmlparser public static customer parsexmlxdocument xdoc so to test this i need to parse a valid xdocument the method being tested does not access the file system itself i could create the xdocument from a string directly in the test code but i thought it would be easier to just load it from a file,['c#'] +22603,mysql load data local infile example in python i am looking for a syntax definition example sample code wiki etc for executing a load data local infile command from pythoni believe i can use mysqlimport as well if that is available so any feedback and code snippet on which is the better route is welcome a google search is not turning up much in the way of current infothe goal in either case is the same automate loading hundreds of files with a known naming convention date structure into a single mysql tabledavid,"['python', 'mysql']" +22609,how do i empty an array in javascript is there a way to empty an array and if so possibly with removefor instance a 1234how can i empty that,['javascript'] +22610,c how to logon to a share when using directoryinfo if i want to instantiate a directoryinfo object with an unc path directoryinfo mydi new directoryinfo serversharehow can i pass a username password that is required to access that sharethanks,['c#'] +22615,netbeansesque retrospective autocommentphpdocumentor tool for eclipse or standalone is there anything similar to netbeans javadoc auto comment tool for phpphpdocumentoreclipse in the netbeans implementationa dialog pops up and allows you to run through all the members of your class and enter comments which are added to the source file it even verifies that there are no parameters you have not accounted for so you can be sure that your comments are completeideally this would be standalone software but plugins are ok too ps netbeans 6 auto comment was movedrenamed now in tooloptions tab java code javadoc hints edit screengrab of the original netbeans tool,['php'] +22627,why should i setup a plugin interface in c instead of c as a result of my previous questions i asked myself is it usefull at all to setup a c interface for a plugin system the following points are speaking against itno common abi between different compilers and their versions no common layout of the objects in memoryno direct class export you have to export factories and destructors problems arises if your objects are held by other objects which only delete them for example smart pointersdifferent implementations of the stl you cannot pass a stdlistt to the plugindifferent versions of used libraries like boostif you restrain yourself to the remaining parts of the c language you nearly end up with the c subset are there any points speaking for using c how do the qttoolkit solve the mentioned problemsremark i am referring mostly to the linux system nevertheless i am interested in solutions on other platformsadditional question what are the problems using a c interface the memory layout of structs which language parts of c should be avoided,"['c++', 'c']" +22632,making sure php substr finishes on a word not a character i know how to use the substr function but this will happy end a string halfway through a word i want the string to end at the end of a word how would i go about doing this would it involve regular expression any help very much appreciated this is what i have so far just the substrecho substrbody0260cheers,['php'] +22641,capturing powershell output in c after pipelineinvoke throws i am running a powershell test script from a c application the script can fail due to a bad cmdlet which causes pipeinvoke to throw an exceptioni am able to capture all the information i need about the exception but i would like to be able to thisplay the scripts output up to that point i have not had any luck since results appears to be null when an exception is thrownis there something i am missing thanksm runspace runspacefactorycreaterunspacem runspaceopenpipeline pipe m runspacecreatepipelinepipecommandsaddscriptfilereadalltextscriptfilepipecommandsaddoutstringtry results pipeinvokecatch systemexception m runspaceclose how can i get to the powershell output that comes before the exception,['c#'] +22655,how to get current ear location programmatically with jboss does anyone know how to get programmatically the absolute path in the filesystem for an ear deployed in jboss from java code within that same eari need this because i want to copy some files that are inside the ear to another part of the filesystem on deploytimethank you everyone,['java'] +22661,how do i replace a character in a string in java using java i want to go through the lines of a text and replace all ampersand symbols with the xml entity reference ampi scan the lines of the text and then each word in the text with the scanner class then i use the characteriterator to iterate over each characters of the word however how can i replace the character first strings are immutable objects second i want to replace a character with several charactersamp how should i approach thischaracteriterator it new stringcharacteriteratortokenforchar ch itfirst ch characteriteratordone ch itnext ifch,['java'] +22664,could not obtain information about windows nt group user i am creating a sql server replication using a script when i try to execute the job failed unable to determine if the owner starmoorer7 of job l3bpt2matlas14 has server access reason could not obtain information about windows nt groupuser starmoorer7 error code 0x5 sqlstate 420 error 15404this is a job created by a script that defines replicationhow do i debug this,['sql'] +22672,c socket server unable to saturate cpu i have developed a mini http server in c using boostasio and now i am load testing it with multiple clients and i have been unable to get close to saturating the cpu i am testing on a amazon ec2 instance and getting about 50 usage of one cpu 20 of another and the remaining two are idle according to htopdetailsthe server fires up one thread per corerequests are received parsed processed and responses are written outthe requests are for data which is read out of memory readonly for this testi am loading the server using two machines each running a java application running 25 threads sending requestsi am seeing about 230 requestssec throughput this is application requests which are composed of many http requestsso what should i look at to improve this result given the cpu is mostly idle i would like to leverage that additional capacity to get a higher throughput say 800 requestssec or whateverideas i have hadthe requests are very small and often fulfilled in a few ms i could modify the client to sendcompose bigger requests perhaps using batchingi could modify the http server to use the select design pattern is this appropriate herei could do some profiling to try to understand what the bottlenecks areis,['c++'] +22673,is it a bad idea to use pointers as loop incrementers instead of the usual int i an example of this would be char str helloint strlength strlenstrfor char pc str pc str strlength pc pc 2edit accounted for writeprotected memory issue,"['c++', 'c']" +22677,integration testing with authlogic for the life of me i do not understand why authlogic is not logging me in in this integration test i have not had any problems w authlogic logging me in in functional tests using this code according to the authlogic rdocs simulating a loggedin state is the same in functional integration tests so i am pretty confused any help is much appreciatedclass tipscontroller applicationcontroller before filter require user only destroy undelete def destroy tip tipfindparamsid if can deletetip tipdestroy set flashgood tip deleted a hrefundelete tip urltipidundoa respond to do format formathtml redirect to city pathtipcity end else set flashbad seems like you cannot delete this tip sorry respond to do format formathtml render action show id tip end end endendclass deletetipandrender actioncontrollerintegrationtest context log user in do setup do user create user tip create tip end context delete tip do setup do activate authlogic usersessioncreateuser us usersessionfind post tipsdestroy id tipid end should redirect tocity pathtipcitycity pathtipcity end endend,['ruby-on-rails'] +22689,web based codereview tools for team foundation server our team is looking to start utilizing a code review tool i have used many in the past and i am very fond of a few options that are available for svn however we are using team foundation server for source control and i have found there to be a real lack in options so far through searching i have found smartbears code collaborator and an open source project ideally there would be a tool like that would tie in to tfs any suggestions,['.net'] +22705,compiling python modules whith debug defined on msvc python rather stupidly has a pragma directive in its include files that forces a link against python26 dlib when the debug preprocessor variable is defined this is a problem because the python installer does not come with python26 dlib so i cannot build applications in msvc in debug mode if i temporarily undef debug for just one file i get many complaints about inconsistent dll linkage if i change the pragma in pythons include file i get undefined references to various debug functionsi have tried compiling my own version of python but its somehow different enough from the python that gets thistributed that i cannot use my modules with apps built with the vanilla version of pythoncan anyone give me any advice on how to get round thisthanks,['python'] +22712,how do i replace the entire html node using jquery i have a string which looks likehtmlheadtitleexampletitleheadbodysome example textbodyhtmli get this string returned as a result to an ajax requesti would like the browser to render and thisplay that string the idea would be to do something like htmlparenthtmlmystringwell that does not work i have attempted to use an iframe but i have not figured out how to get that to work eithernote it is impossible for me to change this string it is also impossible for me to regenerate this string in a subsequent call to the server otherwise i could just redirect the browser to that url,"['javascript', 'jquery']" +22714,c using windows named pipes for some reason both the mast and slave fail however i could find any good examples on how their meant to work so im not sure where i went wrongthe master never exits the waitforsingleobject after connectnamedpipe and the slave throws an exception in the first boostasioread call waiting for a process to open the other end of the pipe which i though the waitnamedpipe was meant to wait for along with the connectnamedpipe in the mastermastercppasioio service ioservice asiowindowsstream handle inioservice int main handle pipe invalid handle value try create pipe pipe createnamedpipepipefltest pipe access duplex file flag first pipe instance file flag overlapped pipe type byte pipe readmode byte 255 5050 0 0 ifpipe invalid handle value printwinerror return 1 inassignpipe stdcout created pipe stdendl spawn child startupinfo startinfo zeromemorystartinfo sizeofstartupinfo startinfocb sizeofstartupinfo process information procinfo zeromemoryprocinfo sizeofprocess information ifcreateprocess0 slaveexe 00 false create new console 0 0 startinfo procinfo stdcout slave process created stdendl else printwinerror thisconnectnamedpipepipe return 1 overlapped overlapped 0 overlappedhevent createevent0truefalse0 ifconnectnamedpipepipe overlapped false unsigned error getlasterror iferror error pipe connected error error io pending printwinerror thisconnectnamedpipepipe return 1 waitforsingleobjectoverlappedhevent infinite closehandleoverlappedhevent stdcout pipe connected stdendl forint i 0 i 100 i boostsystemerror code error unsigned and i 5 asiowriteinasiobuffercharn sizeofunsigned asiotransfer all error iferrorthrow boostsystemsystem errorerror stdcout sent data stdendl flushfilebufferspipe thisconnectnamedpipepipe systempause return 0 catchconst stdexception e stdcout ewhat stdendl ifpipe invalid handle value thisconnectnamedpipepipe systempause return 1 slavecppasioio service ioservice asiowindowsstream handle inioservice int main try waitnamedpipepipefltest nmpwait wait forever stdcout pipe avaible stdendl handle pipe createnamedpipepipefltest pipe access duplex file flag overlapped pipe type byte pipe readmode byte 255 5050 ifpipe invalid handle value printwinerror return 1 inassignpipe stdcout pipe connected stdendl forint i 0 i 100 i stdcout i i stdendl boostsystemerror code error unsigned n asioreadinasiobuffercharnsizeofunsigned asiotransfer all error iferrorthrow boostsystemsystem errorerror systempause return 0 catchconst stdexception e stdcout ewhat stdendl systempause return 1 obviously ive got something completely wrong however i could not find anything on the net to compare my code with,['c++'] +22722,how to make opengl apps in 64bits windows opengl expertsmy project compiles link and run in xp32 then i tried to cross compile it to x64 and i came across a lot of questionsthere is no native x64 instalable opengl sdk so i link against whati saw someone saying that x64 apps use 32bits opengl dll i tryied to run my compiled 64bits app in a xp64 with drivers to my video card radeon 4850 the same i use on xp32 and i got that typical error bla bla bla maybe reinstalling you application will resolve the problemif i use video card drivers how to keep it working with another cards should i build a version for each no sense should i load an available library dinamicaly same no sense which is the reference implementation for x64 where do i find its libs to link againsti am really lost on that matter i did a lot of searchs and found nothing that helped me understant till the momment so what is the path what i want to know to make native x64 opengl appsany help is highly appreciated,['c++'] +22751,how to use a struct in c this is code for a linked list in the c programming languageinclude stdioh for printf include stdlibh for malloc typedef struct node int data struct node next pointer to next element in list llistllist list addllist p int ivoid list removellist pllist list searchllist n int ivoid list printllist nthe code is not completed but i think it is enough for my question here at the end of struct node llist is used and it is also used as a return type in the prototyping of the function list add what is going on,['c'] +22779,debugging app when launched by push notification i am currently developing an app that receives push notifications i have this all working 100 through a php page there are several different types of push notifications my app can receive the php handles this and sends different packets of information to my app which are all received just fine however when the users views the notification and my app launches i obviously want to take a different action than i would if the user just launched the app manually and on top of that different actions depending on the push notification type i have got this working fine structurallyone of my push types is supposed to open a uiview that makes several connections to several different servers and negotiates data back and forth this uiview works fine when for example triggered from the main menu however when my push notification is triggering this uiview to appear the socket connections are not acting as expectednow my question is not about the sockets but more so how do you debug such a problem from what i can tell i am relatively new when the app launched from a push notification there is no way to link that execution to the debugger console etc i am having a very difficult time trying to debug the code using uialertviews as there are many lines of communication back and forth between the various serversany advice you have for me would be greatly appreciated,['iphone'] +22783,looking for an easier way to write debugging print statements in java edit i would love to read reactions to steve reeds aop approach comments to his answer are encouragedi am a novice and at some point i realized it would be helpful to know the contents of a variable during program execution so i started doing thisedit fixed this used to be var var which was totally wrong dumb typosystemerrprintln var var later i learned that this was common practice at least where a debugger was unavailable or unwantedi use a basic text editor and typing the print statement every time i need to debug a variable is pretty tiresome so i thought why not something like thisvoid dbug object obj string variablename objsomehowgetvariablename string variablecontents objtostring systemoutprintln variablename variablecontents but apparently getting the variable name is easier said than donejavareflectionhowtogetthenameofavariableam i stuck withsystemerrprintln var var or is there a popular shorthand version of this,['java'] +22794,reading mp3 information using objective c i have mp3 files stored on the iphone and i my application should to be able to read the id3 information ie length in seconds artist etcdoes anyone know how to do this or what library to use in objectivecyour thoughts are much appreciated,"['iphone', 'objective-c']" +22795,restrictions of gpl on javascript libraries if i use gpllicensed javascript components on my website would it be considered as a release to the public as clientside code of the components is loaded to users browsers via http and i have to opensource the whole website so can we say that the usage of javascript components on a website is thistribution of the code and it involves the thistribution of the whole website codehope the question is clear and you can help me to understand this aspect of gpl,['javascript'] +22796,how do i specify the shell to use for a ruby system call i am trying to run commands from ruby via system or by using backticks but am running into problems when i try to call a command the shell is unable to find it even though i know it works if i call it straight for examplezip sh zip command not foundthe problem seems to be that ruby is using the sh shell in which path is not set correctly rather than bash and i am not sure why the user my application is running under is set up to use bash by defaultis there any way to tell ruby to use bash instead of sh,['ruby'] +22806,description of initwithnibname awakefromnib and viewdidload is there a good overview of initwithnibname awakefromnib and viewdidload that lays out the best way to use each of these and describes exactly what each does i find these very confusing in the template that is generated with a view controller the comment about initwithnibname saysthe designated initializer override to perform setup that is required before the view is loadedexcept that this method never seems to be called i am using ib to set up the view controller so should i use awakefromnib or viewdidload to initialize instead,"['iphone', 'ios']" +22821,what is the net equivalent of deprecated in java is there an annotation in net which allows methods or classes to be deprecated so that their use and their callers are identified by the compiler cf deprecated in java,"['c#', '.net']" +22822,check if a point is in a rotated rectangle c i have a program in c windows forms which draws some rectangles on a picturebox they can be drawn at an angle too rotatedi know each of the rectangles start point upperleft corner their sizewidthheight and their angle because of the rotation the start point is not necessarely the upperleft corner but that does not matter herethen when i click the picturebox i need to check in which rectangle if any i have clickedso i need some way of checking if a point is in a rectangle but i also need to take into account the rotation of each rectangledoes anybody know of a way to do this in c,['c#'] +22831,how does inheritance work for attributes what does the inherited bool property on attributes refers to does it mean that if i define my class with an attribute abcatribute that has inherited true and if i inherit another class from that class that the derived class will also have that same attribute applied to itto clarify this question with a code example imagine the followingattributeusageattributetargetsclass inherited truepublic class random attribute attribute logic here randomclass mother class child mother does child also have the random attribute applied to it,"['c#', '.net']" +22832,why do you specify the size when using malloc in c take the following code int p malloc2 sizeof pp0 10 using the two spaces ip1 20 allocated with malloc beforep2 30 using another space that i did not allocate for printfd p1 correctly prints 20printfd p2 also correctly prints 30 although i did not allocate space for itwith the line malloc2 sizeof p i am allocating space for two integers right but if i add an int to the third position i still gets allocated correctly and retrievableso my question is why do you specify a size when you use malloc,['c'] +22842,how do i get arguments in a form application i can find many examples on how to get arguments in a console application but i cannot seem to find an example of how to get arguments in a windows form applicationi would like to following thingswhenever i open a jpg file windows launches my applicationi would like to know path and name of the jpg file from my applicationhow do i do that,['c#'] +22843,collection removeall ignoring case ok so here is my issue i have to hashsets i use the removeall method to delete values that exist in one set from the other prior to calling the method i obviously add the values to the sets i call touppercase on each string before adding because the values are of different cases in both lists there is no rhyme or reason to the caseonce i call removeall i need to have the original cases back for the values that are left in the set is there an efficient way of doing this without running through the original list and using comparetoignorecaseexamplelist1bobjoejohnmarkdavebilist2joemarkdaveafter this create a separate hashset for each list using touppercase on strings then call removeallset1removeallset2set1 bob john billi need to get the list to look like this againbobjohnbillany ideas would be much appreciated i know it is poor there should be a standard for the original list but that is not for me to decide thank you,['java'] +22844,what is the correctsafest way to escape input in a forum i am creating a forum software using php and mysql backend and want to know what is the most secure way to escape user input for forum postsi know about htmlentities and strip tags and htmlspecialchars and mysql real escape string and even javascripts escape but i do not know which to use and wherewhat would be the safest way to process these three different types of input by process i mean get save in a database and thisplaya title of a post which will also be the basis of the url permalinkthe content of a forum post limited to basic text inputthe content of a forum post which allows htmli would appreciate an answer that tells me how many of these escape functions i need to use in combination and whythanks,"['php', 'javascript', 'mysql']" +22856,symfony vs cakephp what is conceptually the difference between symfony and cakephp,['php'] +22858,c memory efficient solution for axb linear algebra system i am using numeric library bindings for boost ublas to solve a simple linear systemthe following works fine except it is limited to handling matrices am x m for relativelysmall min practice i have a much larger matrix with dimension m 106 up to 107is there existing c approach for solving axb that uses memory efficientlyincludeboostnumericublasmatrixhppincludeboostnumericublasiohppincludeboostnumericbindingstraitsublas matrixhppincludeboostnumericbindingslapackgesvhppinclude boostnumericbindingstraitsublas vector2hpp compileable with this commandg ihomefoolbboostincludeboost1 38 ihomefoolbboostnumbindincludeboostnumericbindings solve axb byhandcc o solve axb byhand llapacknamespace ublas boostnumericublasnamespace lapack boostnumericbindingslapackint main ublasmatrixfloatublascolumn major a33 ublasvectorfloat b3 forunsigned i0i asize1i forunsigned j 0j asize2j stdcout enter element i j stdendl stdcin aij stdcout a stdendl b0 21 b1 1 b2 17 lapackgesvab stdcout b stdendl return 0,['c++'] +22864,why does this python program print true xtruedef stupid xfalsestupidprint x,['python'] +22871,can a c static library link to shared library say i have a static c lib staticlib and i want to call some functions from a c shared lib say sharedlib is it possiblenow assume that i have another shared lib say shared2lib which links to staticlib but does not link to sharedlib does the linker automatically link shared2lib to sharedlib in this casei am using microsoft visual studio 2003,['c++'] +22872,constructor initializationlist evaluation order i have a constructor that takes some arguments i had assumed that they were constructed in the order listed but in one case it appears they were being constructed in reverse resulting in an abort when i reversed the arguments the program stopped aborting this is an example of the syntax i am using the thing is a needs to be initialized before b in this case can you guarantee the order of construction egclass a public aotherclass o string x int y a o b a x y otherclass a anotherclass b,['c++'] +22873,problems with header when thisplaying a pdf file in ie8 so i have a file that sends the followingheaderpragma publicheaderexpires 0headercachecontrol privateheadercontenttype applicationpdfheadercontentthisposition inline filenamefilepdfheadercontentlength 7735then i echo out the file it is a pdf fileworks fine in ie6 7 on xp and ff for that matterthe very same code shows nothing when running on ie8 on either xp or vistathere are no security warnings etc so i do not think it has to do with thatand if my memory serves me correctly this worked on ie8 a while agowhat am i doing wrong here am i missing something out of the headersis there a way for me to see what header information normal comes over when viewing a pdf in ie8 so i know what to emulateafter looking at things it still works in ie8 except when ssl is on,['php'] +22879,how to read and write from the serial port i just start to learn how to send and receive data from my hardware through the c guican anyone please write a detail how to read data from the serial port,['c#'] +22889,saving user credentials in a windows application is there is a best practices way to store credentials in a net windows application be it be a built in api or just a recommend encryption algorithmalong the same lines as tortoise svn spotify and skypeedit my intention is to use a web service that returns a token from it is authentication service the other services then accept that token as a parameter however the token expires after 30 minutes so storing the token itself it pointless for this task,['.net'] +22916,adobe reader plugin interaction through javascript i am thisplaying pdf file that are generated onthefly within a asp page the pdf generation and download to the client can take some time and i would like to provide the user with some feedback a loading message or somethingafaik there is no way to know when the pdf is viewed because the dom events get triggered when the adobe reader plugin gets loaded even though it is not thisplaying anything yeti noticed that there is a javascript api for the plugin object that i could potentially use i notivced a loadfile method on it but unfortunately it does not seem to do muchadobes documentation is really useless it talks of javascript only as a plugin writting language or as ole interaction and poorlyis there any documentation for the api and is it possible to know when the pdf has been loaded it would be perfect if i could pass on a pdf stream to a pdf viewer of some sort,['javascript'] +22923,progressively enhance html table with jqgrid i cannot find an example of jqgrid being used to paint an existing clean html table is this possible i am currently using datatables because it is easy to implement on existing html but would prefer jqgrids theme support and hooks,['jquery'] +22929,generating comma separated values suppose i have a collection of stringsfoobarxyzand i would like to generate a comma separated values from the list into something likefoo bar xyznotice the lack of at the endi am aware that there are dozens of ways to generate thisuse forloop and stringformat or stringbuilderuse integer counter and remove the ending if the value 0do not put on the first runetcsample code of what i have right nowif strscount 0 var sb new stringbuilder foreach var str in strs sbappendformat0 str return sbremove0 2tostringwhat is the best code that is highly reusable for the above scenario and why,"['c#', '.net']" +22932,over the last 78 years what are the biggest influences on c programming i started programming in c it was my first language but i have not used it in many yearswhat are the new developments in the c world what are the big things technologies books frameworks libraries etcover the last 78 years what are the biggest influences on c programmingperhaps we could do one influence per post and that way we can vote on them,['c++'] +22943,can you guarantee destructor order when objects are declared on a stack i have code that controls a mutex lockunlock based on scopevoid performlogin scopelock lock loginlock m loginlock dologincommand scopelock sharedmemorybase memorylock m sharedmemory dostorelogin can i guarantee that memorylock will be destructed before loginlock,['c++'] +22946,javascript indexof to ignore case i am trying to find if an image has in its source name nopic which can be in upper or lower casevar nopic largesrcindexofnopicshould i write var nopic largesrctolowercaseindexofnopicbut this solution does not work,['javascript'] +22951,typegetproperties method i have a class like thisclass itemlist int64 count get set and when i write thisitemlist list new itemlist type type listgettype propertyinfo props typegetproperties i get an empty array for propswhy is it because getproperties does not include automatic properties,"['c#', '.net']" +22952,why do not c header files increase the binarys size i wrote the following c programclass myclass public int i int j myclass int mainvoid myclass inst insti 1 instj 2and i compiled g programcpp ls l aoutrwxrxrx 1 root wheel 4837 aug 7 2050 aoutthen i included the header file iostream in the source file and i compiled again g programcpp ls l aoutrwxrxrx 1 root wheel 6505 aug 7 2054 aoutthe file size as expected was increasedi also wrote the following c programint mainvoid int i 1 int j 2and i compiled gcc programc ls l aoutrwxrxrx 1 root wheel 4570 aug 7 2101 aoutthen i included the header file stdioh and i compiled again gcc programc ls l aoutrwxrxrx 1 root wheel 4570 aug 7 2104 aoutoddly enough the executable files size remained the same,['c++'] +22956,need content in uiwebview to thisplay quickly part of my app caches web pages for offline viewing to do that i am saving the html fetched from a site and rewriting img urls to point to a file on the local store when i load the html into a uiwebview it loads the images as expected and everythings fine i am also caching stylesheets in this fashionthe problem is that when i put the phone into airplane mode loading this cached html causes the uiwebview to thisplay a blank screen and pause for a while before thisplaying the page i have figured out that it is caused by noncached urls referenced from the original html doc that the web view is trying to fetch these other urls include images within the cached stylesheets content in iframes and javascript that opens a connection to fetch other resources the pause happens when the uiwebview tries to fetch these resources and the web page only appears after all these other fetches have timed outmy questions is how can i make uiwebview just thisplay the stuff i have cached immediately here are my thoughtswrite even more code to cache these other references this is potentially a ton more code to catch all the edge cases etc especially having to parse the javascript to see what it loads after the page is loadedforce uiwebview to time out immediately so there is no pause i have not figured out how to do thissomehow get whats already loaded to thisplay even though the external references have not finished fetching yetstrip the code of all scripts link tags and iframes to erase the external references i have tried this one but for some sites the resultant page is severely messed upcan anyone help me here i have been working on this forever and am running out of ideas,['iphone'] +22966,how should i pass a table name into a stored proc i just ran into a strange thingthere is some code on our site that is taking a giant sql statement modifying it in code by doing some search and replace based on some user values and then passing it on to sql server as a query i was thinking that this would be cleaner as a parameterized query to a stored proc with the user values as the parameters but when i looked more closely i see why they might be doing itthe table that they are selecting from is variably dependant on those user valuesfor instance in one case if the values were foo bar the query would end up being something like select from foo baris there an easy and clear way to do this everything i am trying seems inelegantedit i could of course dynamically generate the sql in the stored proc and exec that bleh but at that point i am wondering if i have gained anythingedit2 refactoring the table names in some intelligent way say having them all in one table with the different names as a new column would be a nice way to solve all of this which several people have pointed out directly or alluded to sadly it is not an option in this case,['sql'] +22976,java native process timeout at the moment i execute a native process using the followingjavalangprocess process runtimegetruntimeexeccommand int returncode processwaitforsuppose instead of waiting for the program to return i wish to terminate if a certain amount of time has elapsed how do i do this,['java'] +22983,how to change the color of winform datagridview header i have tried to do it without success is it possible,"['c#', '.net']" +22986,reading audio buffer data with audioqueue i am attempting to read audio data via audioqueue when i do so i can verify that the bit depth of the file is 16bit but when i get the actual sample data i am only seeing values from 128 to 128 but i am also seeing suspicious looking interleaved data which makes me pretty sure that i am just not reading the data correctlyso to begin with i can verify that the source file is 44100 16bit mono wav filemy buffer is allocated thuslychar buffer nullbuffer mallocbuffer sizeassertbufferall the relevant values are set and used inaudiofilereadpacketsinaudiofilefalsebytesreadnullpacketnumnumpacketsbuffer as a test just so that i can see the data retrieved i runforint i0ibuffer sizei nslogi bufferinow i know my source file peaks all over the place but the values i see only max at 128 and 128 being as this is a 16bit file i would expect that the values would instead be 32768 to 32768in addition there seems to be two patterns in the data heres an example of the data returned70133189157116431128184212339741105546126now take a look at every other row starting with the second row 13 see how it increases not evenly but at least smoothly the oddnumbered rows are not anywhere near that smoothmy first thought would be that this is interleaved stereo data but no it is only one channel so there should not be any interleaving rightmy best guess is that i am just reading the data incorrectly so the sample data is being spanned across two returns any idea how to read it correctlythanks for reading through the whole question and for any insight you can offer,"['iphone', 'objective-c']" +22987,detect key event enter with jquery in javascript on linux platform updatei finally figured out that keypress has a better compatibility than keydown or keyup on linux platform i just changed keyupkeydown to keypress so all went welli do not know what the reason is but it is solution for me thanks all who had responsed my questioni have some codes that needs to detect key press event i have to know when the user press enter with jquery and here are the codes in javascriptjinputbindkeyup function l if documentselection g iecacheselection documentselectioncreaterange bindkeydown functionl consoleloglkeycode if lkeycode 13 iflctrlkey ginsertcursorposn return true else var k dthis and kval ifkattrintervaltime alertcan not send kcsscolorredvaldont send too many messagesattrthisabledthisabledcsscolorred settimeoutfunctionkcsscolorvalnattrthisabledfocus10 return ifg debug numparseinthbuddyinfoidundefined g debug numparseinthbuddyinfoid1 if dtrimn var m to hbuddyinfoid from hmyinfoid stype msg body g debug numparseinthbuddyinfoid n timestamp new dategettime gaddhistorym kval gtriggersendmessage m lpreventdefault gsendstatuses kattrintervaltime100 settimeoutfunctionkremoveattrintervaltime10 return return it works fine on windows but on linux it fails to catch the enter event sometimes can someone helpupdatedit seems good if i only use english to talk but i have to use some input method to input chinese if it is the problem jquery can not detect enter if i use chinese input method,"['javascript', 'jquery', 'html']" +22994,convert string to keyevents i have thiscovered the robot class today and wanted to use it to do some funny scriptsi want to convert a string into keyevent to do something like this writekeyboardmybotabcdpublic void writekeyboardrobot bot string st char arr arrtochararray int i arrlength int j 0 int keycode while ji keycode arrjsomething botkeypresskeycode botkeyreleasekeycode j,['java'] +22995,gcc42 failed with exit code 1 iphone i have seen this error with different variations on thiscussion forums but being a non programmer i am not sure how to progress thisbasically i have code which i found to help me with changing the background colors of cells on a grouped uitableview the code introduced a line as suchcgcontextaddarctopointc minx miny midx miny round sizethis gave an error indicated that it was not declared so i added to my h file the following under import uikitimport uikituikithdefine round size 10now it shows that i have an errorcommanddeveloperplatformsiphonesimulatorplatformdeveloperusrbingcc42 failed with exit code 1 iphonesome thiscussions talk about libraries but because i do not have a programming background i do not understand what to do i also see that some people show a log output but i am not sure where that comes from as i do not get any debug windows because i am guessing it does not get that far i simply click build and go and i get this error in the message windowany thoughts,['iphone'] +23017,simple pythonregex problem removing all new lines from a file i am becoming acquainted with python and am creating problems in order to help myself learn the ins and outs of the language my next problem comes as followsi have copied and pasted a huge slew of text from the internet but the copy and paste added several new lines to break up the huge string i wish to programatically remove all of these and return the string into a giant blob of characters this is obviously a job for regex i think and parsing through the file and removing all instances of the newline character sounds like it would work but it does not seem to be going over all that well for me is there an easy way to go about this it seems rather simple,['python'] +23029,graph layout optimization in c i have got a list of objects that i need to organize as an aesthetic graph my current approach involves ironpython and a genetic algorithm but this takes way too longi have been reading up on graphviz quickgraph and graph but i do not need the visualization part i already have an app that will thisplay the nodes given the xy coordinates i have been told that both the sugiyama algorithm and the forcebased family of algorithms tend to output pleasing graphs but i cannot seem to find a net library that will output the coordinates instead of the image without some pretty severe sourcecode hackingcan anyone recommend libraries algorithms or the like,['c#'] +23036,differences between visual studio modes general web dev c what exactly are the differences between the different visual studio install modes general web development c this is also confusing because i do web development in c which one should i use,['.net'] +23053,how to sort out numeric strings as numerics if you have strings likefile 0file 1file 2file 3file 4file 5file 6file 11how can you sort them so that file 11 does not come after file 1 but comes after file 6 since 11 6do i have to parse the string and convert it into a number for thiswindows explorer in win7 sorts files out the way i wanted,"['c#', '.net']" +23062,how to run two jquery animations simultaneously is it possible to run two animations on two different elements simultaneously i need the opposite of this question jquery queueing animationsi need to do something like thisfirstanimate width 200 200secondanimate width 600 200but to run those two at the same time the only thing i could think of would be using settimeout once for each animation but i do not think it is the best solution,"['javascript', 'jquery']" +23080,how to wait for a set of threads to complete what is a way to simply wait for all threaded process to finish for example let us say i havepublic class dosomethinginathread implements runnable public static void mainstring args for int n0 n10 n thread t new threadnew dosomethinginathread tstart wait for all threads run methods to complete before continuing public void run do something here how do i alter this so the main method pauses at the comment until all threads run methods exit thanks,['java'] +23081,parametrized get request in ruby how do i make an http get request with parameters in rubyit is easy to do when youre posting require nethttp require uri httppost form uriparse q ruby max 50 but i see no way of passing get parameters as a hash using nethttp,"['ruby-on-rails', 'ruby']" +23094,opengl windowing library for 2009 trying to decide on a library for creating a window and capturing user input for my opengl app but there are just way too many choicesglut win32freeglutopenglutsfmlglfwsdlfltkoglwfwclutterqtothersglut is simply outdated i liked glfw but it seems you cannot set the window position before thisplaying it i wanted it centered is that so much to ask so you see it appear and then shift over which bothers me plus development seems to have stopped on it too sfml has some nice features but it uses event polling rather than callbacks which i prefer for decoupling i do not think i need all the gui features of fltk sdl is slow does not seem to take advantage of the gpu and the other 3 i do not know much about freeglut openglut oglwfw so which is the lesser of the evils are there others i have not heard abouti am just trying to make a simple 2d game i am familiar enough with opengl that i do not really need drawing routines but i probably wouldnt complain about other functions that might be useful if they are implemented properly,['c++'] +23095,ie hidden radio button not checked when the corresponding label is clicked i just noticed a strange behaviour in ie7i have radio buttons with associated labels as followsinput typeradio namefilter idfilter 1 valueactivities checkedchecked label forfilter 1activitieslabelinput typeradio namefilter idfilter 2 valueservices label forfilter 2serviceslabelthe radio button is hidden via css with thisplaynone or visibility hidden do not askthe problem is when i click the label in ie7 have not looked at other ie versions yet the associated radio button is not actually checked i confirmed this with jquery the label click event is fired but the radio button click event is not a form post also confirms that the checked radio button does not changethis works correctly in firefox and also works correctly if i remove the css that hides the radio buttonsis this an ie bug or am i missing something,['css'] +23116,floating point addition lossofprecision issues in short how can i execute ab such that any lossofprecision due to truncation is away from zero rather than toward zerothe long storyi am computing the sum of a long series of floating point values for the purpose of computing the sample mean and variance of the set since varx ex2 ex2 it suffices to maintain running count of all numbers the sum of all numbers so far and the sum of the squares of all numbers so farso far so goodhowever it is absolutely required that ex2 ex2 which due to floating point accuracy is not always the case in pseudocode the problem is thisint countdouble sum sumofsquaresdouble value currentvaluedouble sqrval valuevalue countsum value slightly rounded down since value is truncated to fit into sumsumofsquares sqrval rounded down more since the orderofmagnitude difference between sqrval and sumofsquares is twice that between value and sumfor variable sequences this is not a big issue you end up slightly underestimating the variance but it is often not a big issue however for constant or almostconstant sets with a nonzero mean it can mean that ex2 ex2 resulting in a negative computed variance which violates expectations of consuming codenow i know about kahan summation which is not an attractive solution firstly it makes the code susceptible to optimization vagaries depending on optimization flags code may or may not exhibit this problem and secondly the problem is not really due to the precision which is good enough it is because addition introduces systematic error towards zero if i could execute the linesumofsquares sqrvalin such a way as to ensure that sqrval is rounded up not down into the precision of sumofsquares i would have a numerically reasonable solution but how can i achieve thatedit finished question why does pressing enter in the dropdownlist in the tag field submit the question anyhow,"['c#', 'c++']" +23119,why do round and ceil not return an integer once in a while i find myself rounding some numbers and i always have to cast the result to an integerint rounded int floorvaluewhy do all rounding functions ceil floor return a floating number and not an integer i find this pretty nonintuitive and would love to have some explanations,"['c++', 'c']" +23140,reimport a module in python while interactive i know it can be done but i never remember howhow can you reimport a module in python the scenario is as follows i import a module interactively and tinker with it but then i face an error i fix the error in the py file and then i want to reimport the fixed module without quitting python how can i do it,['python'] +23151,i need to create a threadsafe static variable in c net ok its a little more complicated than the questionclass a static int needstobethreadsafe 0 public static void m1 needstobethreadsafe randomnumber public static void m2 printneedstobethreadsafe now i require that between m1 and m2 calls needstobethreadsafe stays thread safe,['c#'] +23154,should i remove qdebug header for release i have a qt application and i use qdebug message for my applicationhowever i have gotten lazy and left in a load ofinclude qdebugin my header files should i remove them for a production deployment and what benefit will it give,['c++'] +23158,changing text color in a webview there is a method for altering background color but not fontany ideas,['android'] +23177,how do you transform a linq query result to xml newbie in the linq to xml arenai have a linq query with results and i would like to transform those results into xml i am guessing there must be a relatively easy way to do it but i cannot find itthanks,['c#'] +23186,setting the start position for openfiledialogsavefiledialog for any custom dialog form in a winform application i can set its size and position before i thisplay it withformstartposition formstartpositionmanualformdesktopbounds mywindowpositionthis is particularly important when dealing with multiple monitors without such code when you open a dialog from an application that you have dragged to a second monitor the dialog appears on the primary monitor this presents a poor user experiencei am wondering if there are any hooks to set the position for the standard net openfiledialog and savefiledialog which do not have a startposition property,['c#'] +23187,django getting last object created simultaneous filters apologies i am completely new to django and pythoni have 2 questions first how would i go about getting the last object created or highest pk in a list of objects for example i know that i could use the following to get the first objectlist listobjectsall0is there a way to get the length of listobjects i have tried listobjectslength but to no availsecond is it possible to create simultaneous filters or combine lists here is an exampledef findnumberrequest number phone list numbersobjectsfiltercellnumberi want something like the above but more likedef findnumberrequest number phone list numbersobjectsfiltercellnumber or home phonenumberwhat is the correct syntax if any,['python'] +23189,why is boost scoped lock not unlocking the mutex i have been using boostmutexscoped lock in this mannervoid classnamefunctionname boostmutexscoped lock scopedlockmutex do stuff waitbooleantrue whilewaitboolean true sleep1 get on with the threads activitiesbasically it sets waitboolean and the other thread signals that it is done by setting waitboolean to false this does not seem to work however because the other thread cannot get a lock on mutex i was assuming that by wrapping the scoped lock in brackets i would be terminating its lock this is not the case reading online says that it only gives up the mutex when the destructor is called would not it be destroyed when it goes out of that local scopesignaling part of codewhilerunning boostmutexscoped lock scopedlockmutex run some function that need to be done ifwaitboolean waitbooleanfalse thanks,['c++'] +23200,streaming audio mms to the iphone i would like to stream a mms url to my iphone app but so far information on the topic is hard to come by i know there are a couple apps out there that can do it already fstream wunderradio tuner and i have read a few notes about them possibly using libmms and ffmpeg to accomplish this taskdoes anyone know of a way to achieve this is there a library out there that i am missing or some example to do this already i was hoping this was going to be as easy as a simple somelibrary streamsurlmmsmymmsurlherecomthanks for any help,['iphone'] +23205,best approach avoid naming conflicts for javascript functions in separate js files is there a preferred approach to isolating functions in a js file from potential conflicts with other js files on a page due to similar namesfor example if you have a functionfunction addtagin corejs and then there is a function addtagin ordersjs they would conflict how would you best structure your js files and what naming conventions would you use to isolate themthanks,['javascript'] +23209,making a joptionpane with 4 options i need to make a custom dialog with 4 options but as far as i can tell you can only have one with three options here is how i would make an option pane with 3 options frame refframe dialogutilsgetreferenceframe todo use dialogutils int option joptionpaneshowoptiondialogrefframe msg rscstr918 joptionpaneyes no cancel option joptionpaneinformation message dialogutilsinfo icon options options0but i could not find some sort of open ended substitution for yes no cancel option is there a way to make the joptionpane allow four choices,['java'] +23210,css border only inside the table i am trying to figure out how to add border only inside the table when i dotable border 0table td table th border 1px solid blackthe border is around the whole table and also between table cells what i want to achieve is to have border only inside the table around table cells without outer border around the tablehere is markup i am using for tables even though i think that is not importanttable tr thheading 1th thheading 2th tr tr tdcell 11td tdcell 12td tr tr tdcell 21td tdcell 22td tr tr tdcell 31td tdcell 32td trtableand here are some basic styles i apply to most of my tablestable bordercollapse collapse borderspacing 0,"['html', 'css']" +23212,structuremap scopelifecycle guidance is there any reason to switch from the default scope transient to something else outside of needing to control the scope for functional reasons eg singletonif i stick with the default scope every default instance of every plugin type will effectively get instantiated on each request assuming a web app is that correct can this affect performance noticeably i have considered using http session scope to limit this to one instance per user logged in however that will result in at least one instance of each plugin type stored in memory for each user at all times using default scope these instances would only be held in memory while a page request was being processed i am not sure which is preferableif you use structuremap how do you generally configure scope for each of your plugin typesthanks for any insightphil,['c#'] +23213,c listview column width auto how can i set the column width of a c winforms listview control to auto something like width 1 2,"['c#', '.net']" +23217,boost program options examples in the boost tutorials online for program options 39 0dochtmlprogram optionstutorialhtmlid2891824it says that the complete code examples can be found at boost rootlibsprogram optionsexample directory i could not figure out where is this can anyone help me finding the examples,['c++'] +23230,parameters hide instance variables in objectivec is there a way to give a parameter to a method the same name as an instance variable in objectivec without hiding that variablefor instance voiddosomethingidobject selfobject objectthe code above gives the warning local declaration of object hides instance variablethe obvious solution is to name the parameter arguments differently but i find it annoying having to choose a name like anobject instead of object,['objective-c'] +23232,simplest way to parse a date in javascript i want to parse a date chosen by uservar ds 11 08 2009i usevar d new datedsit gives me november 08 2009 but what i need is august 11 2009what is the simplest way to parse the date,['javascript'] +23234,preserve sql indexes while altering column datatype i have a smalldatetime column that i need to alter to be a datetime column this is something that will be part of an install process so it cannot be a manual procedure unfortunately the column has a few indexes and a not null constraint on it the indexes are performance related and would need to be retained only using the new data type is it possible to write a statement that will allow me to retain the relevant information while still altering the column datatype if so how can this be done,['sql'] +23238,why should you use strncpy instead of strcpy edit i have added the source for the examplei came across this examplechar sourcemax 123456789char source1max 123456789char destinationmax abcdefgchar destination1max abcdefgchar return stringint index 5 this is how strcpy works printfdestination is originally sn destinationreturn string strcpydestination sourceprintfafter strcpy dest becomes snn destination this is how strncpy works printf destination1 is originally sn destination1 return string strncpy destination1 source1 index printf after strncpy destination1 becomes sn destination1 which produced this outputdestination is originally abcdefgafter strcpy destination becomes 123456789destination1 is originally abcdefgafter strncpy destination1 becomes 12345fgwhich makes me wonder why anyone would want this effect it looks like it would be confusing this program makes me think you could basically copy over someones name eg tom brokaw with tom bro763 what are the advantages of using strncpy over strcpy,['c'] +23246,finding the whole number portion of a number how can you find the whole number of a given decimal or other number in javascriptgiven result 12 115 119 1whats the best way to perform this for both positive and negative numbers,['javascript'] +23255,c varargs va copy issues i am writing a function in c that takes a variable number of argumentssize t myprintfchar fmt so far so good i have decided it is best to do things the right waya and make a version that takes variable arguments and another version that takes a va listsize t myprintfchar fmt size t myvprintfchar fmt va list argsnot that hard to do except my vprintf needs to send its args out to two different functions first to snprintf with a length of 0 to determine how much room we need then to sprintf after weve allocated that much room i do this with va copysize t myvprintfchar fmt va list args va list args2 va copyargs args2 do stuff with args2 va endargs2 do more stuff with argsthis is all fine and dandy but c99 is a bit poorly implemented i would like if possible for my code to work in c89 as well and to work with as many compilers and on as many platforms as possible i currently have this after include stddefh but before any codeifndef va copy ifdef va copy define va copyab va copyab else va copy define va copyab ab endif va copy endif va copy i am led to believe that ab is unreliable and that i should perhaps use memcpy or something similar but this is still on the level of if you do not support c99 i hope it works rather than if you do not support c99 never fear which is what i want is there any good way to get around this limitation i have seen a few solutions va list functions that eat one argument and recurse passing the va list twice so that two separate copies are made etc but i do not know how well they would work and the recursive solution would not do so well if i just want to call vsnprintf now will itso i turn to you stackoverflow user is there anything more i can do to provide c89 compatibility or are users without va copy and va copy admittedly few and far between just going to have to suck it in and take it,['c'] +23259,how do i properly split a path variable in php i want to splitpath getenvpathinto its components how do i determine the separator char in an osdependent fashion,['php'] +23288,is there a free java gui designer is there a free or relatively cheaper java gui designerbuilder,['java'] +23292,aspnet c lists which and when in c there seem to be quite a few different lists off the top of my head i was able to come up with a couple however i am sure there are many moreliststring types new liststringarraylist types2 new arraylistlinkedliststring types4 new linkedliststringmy question is when is it beneficial to use one over the othermore specifically i am returning lists of unknown size from functions and i was wondering if there is a particular list that was better at this,"['c#', 'asp.net']" +23323,simulate keypress in a linux c console application is there any way to simulate a keypress in linux using cin my specific situation i am on ubuntu 904 and need a simple app that invokes a press on the pause button when launched that would get an iframe in firefox to refresh using javascript,['c'] +23326,suggestions on how to create a custom geojson serializer using jsonnet i will be attempting to create a c library to serialize objects to geojson using jsonnet for serialization and geoapinet for geometry definitions i have thought about two different approaches for the serialization implementation and i am not clear which one would be the best approach they areapproach 1 custom attributesthe first approach involves creating several custom attributes that could be applied to any class to modify the serialization for instance a class might be decorated like sogeojsonfeaturepublic class building geojsonid public guid id get set geojsonproperty public string name get set geojsonproperty public int floorcount get set geojsongeometry public geoapigeometriesigeometry geometry get set serializing the object would then be as simple asjsonnetresult jsonnetresult new jsonnetresultjsonnetresultformatting formattingindentedjsonnetresultdata buildingreturn jsonnetresultthe advantage of this approach is that any business object could be turned into a geojson object assuming it has the required properties eg geometry the thisadvantage would be that i would need to create a number of custom attributes to support the serialization additionally this has the affect of muddying the business objectfinally i have not yet determined if this approach is even possible with jsonnet though it seems that it will beapproach 2 custom jsonconverterthe second approach involves creating custom converters for various types for instance i might have a geojsonconverter that when passed an object of a given type say feature the geojson object is created this might look likepublic class geojsonfeatureconverter public override void writejsonjsonwriter writer object value jsonserializer serializing code here public override void readjsonjsonreader reader type objecttype jsonserializer serializer deserializing code here public override bool canconverttype objecttype return typeoffeatureisassignablefromobjecttype i would then be able to serialize to geojson like sojsonnetresult jsonnetresult new jsonnetresultjsonnetresultformatting formattingindentedjsonnetresultserializersettingsconvertersaddnew geojsonfeatureconverterjsonnetresultdata buildingthe advantage here is that this seems easier to create i have proven that this approach is possible via a very simple prototype additionally the feature class is already defined if i link to nettopologysuite the thisadvantage would be that my business objects would need to be mapped to a feature before being serialized though this might be considered an advantage since this might provide a natural decoupling between the layers there would definitely be tight coupling with the geoapi in both cases and nettopologysuite in the later i think i am okay with thati am aware of several other geojson serializers available such as geojsonnet however i would like an approach that is consistent with the jsonnet api as this is our serializer of choicedo you see any obvious reasons why one approach would be preferred over the other perhaps there is another approach that i am not aware offyi i am leaning towards the second approach it seems that it would be easier to implement and that it would be cleaner overall i also happen to like the natural boundary between domain objects and geojson objects that it would create,['c#'] +23339,jquery empty div except for matched elements is there a way to empty a div leaving only elements with a specific class name or is there a way to remove all elements within a div leaving only elements with a specified class,['jquery'] +23344,ruby boolean attribute naming convention and use learning ruby i am under the impression that boolean attributes should be named as followsmy boolean attributehowever i get syntax errors when attempting to do the followingclass myclass attr accessor my boolean attribute def initialize my boolean attribute false endendapparently ruby is hating the is this the convention what am i doing wrong,['ruby'] +23351,how to use contains in an if statement i have html that looks like thisdiv classitemlist h3monday sep 21h3 h3tuesday sep 22h3 h3wednesday sep 23h3if todays date is on the list then that date should be red if today is not on the list hey it is still august then the 21st should be red i used this code to successfully turn sept 21 red but i do not know how to put it in an ifelse i tried some basic stuff and searched but i am lame with jsitemlist h3containsmonday sept 21csscolorredthat monday sept 21 will eventually be a variable based on todays date,"['javascript', 'jquery']" +23353,good way to organize c source files the way i have always organized my c source was to put struct macro and function prototypes in header files and function implementations in c files however i have recently been reading alot of other peoples code for large projects and i am starting to see that people often define things like structs and macros in the c source itself immediately above the functions that make use of it i can see some benefit to this as you do not have to go searching around to find the definition of structs and macros used by particular functions everything is right there in roughly the same place as the functions that use it however i can also see some thisadvantages to it as it means that there is not one central repository for structmacro definitions as they are scattered through the sourcecode my question is what are some good rules of thumb for deciding when to put the macrostruct definition in the c source code as opposed to the header files themselves,['c'] +23357,maximum execution time in phpmyadmin when i try to execute some queries in phpmyadmin i get this errorfatal error maximum execution time of 60 seconds exceeded in cxamphpmyadminlibrariesdbimysqldbilibphp on line 140because i have a very large table over 9 millions recordsi have edited the file cxamphpphpini and changed the value of max execution time from 60 to 10 then restarts the php and still have the same errorany solution,"['php', 'mysql']" +23364,mechanize and beautifulsoup for php i was wondering if there was anything similar like mechanize or beautifulsoup for php,"['php', 'python']" +23366,generate a create table sql command based on an existing table in mysql i have a mysql shell but for security reasons i cannot run the mysqldump commandi have a table that i made a while ago with a lot of columns and i want to generate a new create table command to create that table on a different databaseis there some command i can run in the mysql shell to generate thatthanks,['mysql'] +23376,how to create log file in in tomcatlogs folder i am using log4j to log in applicationnow the log file is created in the some location like jlogsmyloglog i want the log file myloglog to be created in the tomcatlogs foderhow to set thisnow current log4j property is as followslog4jappenderfileappenderorgapachelog4jdailyrollingfileappenderlog4jappenderfileappenderdatepatterndd m ylog4jappenderfileappenderfilelogstestparentlearnfilelog,['java'] +23390,django annotate multiple times causes wrong answers django has the great new annotate function for querysets however i cannot get it to work properly for multiple annotations in a single querysetfor example tour list tourobjectsallannotate counttourcomment annotate counthistory a tour can contain multiple tourcomment and history entries i am trying to get how many comments and history entries exist for this tour the resultinghistory count and tourcomment countvalues will be incorrect if there is only one annotate call the value will be correct there seems to be some kind of multiplicative effect coming from the two left outer joins for example if a tour has 3 histories and 3 comments 9 will be the count value for both 12 histories 1 comment 12 for both values 1 history 0 comment 1 history 0 comments this one happens to return the correct valuesthe resulting sql call isselect testapp tourid testapp touroperator id testapp tourname testapp tourregion id testapp tourdescription testapp tournet price testapp toursales price testapp tourenabled testapp tournum views testapp tourcreate date testapp tourmodify date testapp tourimage1 testapp tourimage2 testapp tourimage3 testapp tourimage4 testapp tournotes testapp tourpickup time testapp tourdropoff time counttestapp tourcommentid as tourcomment count counttestapp historyid as history count from testapp tour left outer join testapp tourcomment on testapp tourid testapp tourcommenttour id left outer join testapp history on testapp tourid testapp historytour idgroup by testapp touridorder by testapp tourname asci have tried combining the results from two querysets that contain a single call to annotate but it does not work right you cannot really guarantee that the order will be the same and it seems overly complicated and messy so i have been looking for something bettertour list tourobjectsallfilteroperator user exact requestuser filterenabled exact trueannotate counttourcomment tour list historycount tourobjectsallfilter enabled exact true annotate counthistory for io in enumeratetour list ohistory count tour list historycountihistory countthanks for any help stackoverflow has saved my butt in the past with a lot of alreadyanswered questions but i was not able to find an answer to this one yet,['sql'] +23403,what is a callback what is it for and how is it implemented in for example c i realise this is a newbie question but as i am trying to learn c i am stumpling upon this expression callback frequently i have googled it and checked wikipedia but without finding a good explination i am familiar with some java and c but how unlikely it sounds i have never really understood what a callback meansif someone know how to explain this term to a simple layman i would be really thankfull,['c++'] +23410,how to test things in crontab this keeps happening to me all the time1 i write a scriptruby shell etc2 run it it works3 put it in crontab so it runs in a few minutes so i know it runs from there4 it doesnt no error trace back to step 2 or 3 a 10 timeswhen i ruby script fails in crontab i cannot really know why it fails cause when i pipe output like thisruby scriptrb pathtooutputi sorta get the output of the script but i do not get any of the errors from it and i do not get the errors coming from bash like if ruby is not found or file is not therei have no idea what environmental variables are set and whether or not it is a problem turns out that to run a ruby script from crontab you have to export a ton of environment variablesis there a way for me to just have crontab run a script as if i ran it myself from my terminalwhen debugging i have to reset the timer and go back to waiting very time consuminghow to test things in crontab better or avoid these problems,['ruby'] +23424,should i sanitize markdown for my post entity i store both html and markdown in database html is converted from markdown html is for rendering on page and markdown for editing ability with wmd i sanitize html before storing to db question is should i sanitize markdown too or it is xsafe if i only pass it to wmdeditor,['html'] +23425,iphone sdkhow do you play video inside a view rather than fullscreen i am trying to play video inside a uiview so my first step was to add a class for that view and start playing a movie in it using this code ibactionmovieidsender nsbundle bundle nsbundle mainbundle nsstring moviepath bundle pathforresourcemovie oftypem4v nsurl movieurl nsurl fileurlwithpathmoviepath retain mpmovieplayercontroller themovie mpmovieplayercontroller alloc initwithcontenturlmovieurl themoviescalingmode mpmoviescalingmodeaspectfill themovie playbut this just crashes the app when using this method inside it is own class but is fine elsewhere does anyone know how to play video inside a view and avoid it being full screen,"['ios', 'objective-c']" +23433,how to find the maximum value for each key in a list of dictionaries using linq i have a list of dictionaries that have keys of type string and values that are intsmany of the dictionaries have the same keys in them but not all of themso my question is using linq how would i find the maximum value associated with each thistinct key across all of the dictionariesso for example given the following inputvar data new listdictionarystring int new dictionarystring int alpha 4 gorilla 2 gamma 3 new dictionarystring int alpha 1 beta 3 gamma 1 new dictionarystring int monkey 2 beta 2 gamma 2i would like some kind of collection that containsalpha 4gorilla 2gamma 3beta 3monkey 2i am currently looping through the list and keeping track of things myself really just wondering if there is a nicer linqesque way of doing itedit i also do not know what the string keys are in advance,['c#'] +23440,python remove lots of items from a list i am in the final stretch of a project i have been working on everything is running smoothly but i have a bottleneck that i am having trouble working aroundi have a list of tuples the list ranges in length from say 40 10 records now i have a dictionary where each and every value key is a tuple in the listso i might havemylist 20 11 160 4 140 9mydict 1120 9140 i want to remove each v k tuple from the listcurrently i am doingfor k v in mydictiteritems mylistremovev kremoving 838 tuples from the list containing 20 tuples takes anywhere from 3 4 seconds i will most likely be removing more like 10 tuples from a list of 10 so i need this to be fasteris there a better way to do thisi can provide code used to test plus pickled data from the actual application if needed,['python'] +23441,whats the best way to do literate programming in python on windows i have been playing with various ways of doing literate programming in python i like noweb but i have two main problems with it first it is hard to build on windows where i spend about half my development time and second it requires me to indent each chunk of code as it will be in the final program which i do not necessarily know when i write it i do not want to use leo because i am very attached to emacsis there a good literate programming tool thatruns on windowsallows me to set the indentation of the chunks when they are used not when they are writtenstill lets me work in emacsthankscorrection noweb does allow me to indent later i misread the paper i found on it by default notangle preserves whitespace and maintains indentation when expanding chunks it can therefore be used with languages like miranda and haskell in which indentation is significantthat leaves me with only the runs on windows problem,['python'] +23442,how do i create an ear file with an ant build including certain files i am using eclipse to build an ear file using ant i am using oc4j and i want to make sure that orionapplicationxml is included in the build what i am currently using but does not work is target nameear depends echobuilding the ear fileecho copy todirbuilddirmetainf fileset dirconfdir includesorionapplicationxml copy ear destfilethistdirantprojectnameear appxmlconfdirapplicationxml fileset dirthistdir includesjarwar ear targetwhat is the right way to add this to the ear,['java'] +23446,where to place the core data stack in a cocoacocoa touch application in the iphone core data template apple places the core data stack in the app delegatemy initial inclination however is to move this code into it is own class whose responsibility is to handle the management of the core data stackdo you typically encapsulate this functionality within its own class or do you leave it in the app delegate,['iphone'] +23453,top 10 sql server performance bottlenecks what is the most common performance bottleneck that is not caused by the database structure,['sql'] +23454,django formset without instance in this django doc explain how to create a formset that allows you to edit books belonging to a particular authorwhat i want to do is create a formset that allows you to add new book belonging to a new author add the book and their authors in the same formsetcan you gime a light thanks,['python'] +23476,aspnet rdlc with external images not thisplaying images in pdf i am using the microsoft reportviewer that comes with aspnet and have a report parameter that should be setting the value path of an image in my report i am providing the path as a complete url right now starting with http but have also tried this as an app relative path site rooted path etc and for some reason the image is always showing as the red x when it exports to pdf i am just creating an instance of a control in code setting the properties and exporting directly to the response stream so it acts a downloadi am just not sure what the problem could be with the image not showing up so if anyone has any ideas please let me knowupdate 1i have determined that i can embed the image with a url if it is on my public web server but when i am running in localhost the image would not embed i have confirmed for localhost that if i paste the same url into my browser the image will open fine as far as i know i do not have a proxy so i can work around my issue but i still do not understand what the problem is with localhostupdate 2forgot to mention that when the url to the image is opened from a browser it works fine,['asp.net'] +23489,scale an image in gtk in gtk how can i scale an image right now i load images with pil and scale them beforehand but is there a way to do it with gtk,['python'] +23493,globbing in cc on windows is there a smooth way to glob in c or c in windowseg myprogramexe txt sends my program an argv list that hasargv1txt in iti would like to be able to have a function let us call it readglob that takes a string and returns a vector of strings each containing a filenamethis way if i have files atxt btxt ctxt in my directory and readglob gets an argument txt it returns the above filelistprototype of this hypothetical functionvectorstring readglobstringdoes such exist,"['c++', 'c']" +23499,zend framework 19 and doctrine integration i am trying to setup zend framework and doctrinethere is this previous thiscussion with zf 18that thiscussion does not take into account the autoloader bootstrap systemif i generate an application skeleton with zhsh how would i go about integrating doctrine,['php'] +23517,passing a string by reference in java i am used to doing the following in cvoid main string ztext fillstringztext printfztextvoid fillstringstring ztext ztext fooand the output isfoohowever in java this does not seem to work i assume because the string object is copied instead of passed by referenced i thought strings were objects which are always passed by reference what is going on here,"['java', 'c']" +23519,mysql how can i find last mondays date performance issue is there a simpler way than writingselect date subcurdate interval weekdaycurdate day as lastmonday from dual,['mysql'] +23524,most concise way to check whether a list is empty or contains only none most concise way to check whether a list is empty or contains only nonei understand that i can testif mylist passandif not mylist passbut what if the list has an item or multiple items but those items are nonemylist none none noneif pass,['python'] +23527,how to remove two chars from the beginning of a line i am a complete python noob how can i remove two characters from the beginning of each line in a file i was trying something like thispython26import ref openmfiletxtlinesfreadlinesi0for line in lines line linestrip do something here,['python'] +23528,use httplistener for a production caliber web server is it realistic to use the c net class httplistener as the foundation for a production caliber web serverthe http web service i need to host contains no aspx or static files all http responses are dynamic and generated in c code that is invoked via a few switch statements which inspect a restful url formatmy thinking is that iis is really a usermode wrapper around the windows os httpsys kernel module that does all the heavy duty network handling and so is httplisteneri already have a basic multithreaded web server running which is excellent for development because it starts in debug mode in an instance now i am thinking do i need the overkill of iis for production a low memory footprint is another attraction,"['c#', '.net']" +23534,reseting generator object in python i have generator object returned by multiple yield preparation to call this generator is rather timeconsuming operation that is why i want to reuse generator several timesy functionwithyieldfor x in y printxhere must be something to reset yfor x in y printxof course i am taking in mind copying content into simple list,['python'] +23541,validate select box i am using the jquery plugin validation to validate a form i have a select list looking like thisselect idselectoption valuechoose an optionoptionoption valueoption1option1optionoption valueoption2option2optionoption valueoption3option3optionselectnow i want to make sure that the user selects anything but choose an option which is the default one so that it would not validate if you choose the first option how can this be done,"['javascript', 'jquery', 'html']" +23542,counting null and nonnull values in a single query i have a table create table us a numbernow i have data likea1234nullnullnull89now i need a single query to count null and not null values in column a,['sql'] +23547,generating a jaxb class that implements an interface i am currently using jaxb to generate java classes in order to unmarshall xml now i would like to create a new schema very similar to the first and have the classes that are generated implement the same interfacesay for example i have two schema files which define xml with similar tagsadultxsdxml version10 encodingutf8xselement nameperson xscomplextype xssequence xselement namename typexsstring xselement nameage typexsinteger xselement namejob typexsstring xssequence xscomplextypexselementkidxsdxml version10 encodingutf8xselement nameperson xscomplextype xssequence xselement namename typexsstring xselement nameage typexsinteger xselement nameschool typexsstring xssequence xscomplextypexselementusing jaxb and xjc i would like to generate two class filespublic class adult implements person public string getname public int getage public string getjob public class kid implements person public string getname public int getage public string getschool where the person interface defines the getname and getage methodsi have looked at some of the documentation for mapping interfaces but this appears to only be for the situation when you already have java classes that you want to map to a domalso i have tried to use this external plugin but it does not appear to work here is my xjb binding filejxbbindings version10 xmlnsjxb xmlnsxs xmlnsxjc xmlnsext jxbextensionbindingprefixesxjc jxbbindings schemalocationxsdadultxsd nodexsschemaxscomplextypenameperson extinterfacemypackagehelloextinterface jxbbindingsjxbbindingsbut this gives the following error java cp libactivationjarlibinterfacesxjcpluginjarlibjaxb1impljarlibjaxbapijarlibjaxbxjcjarlibjsr173 10 apijar comsuntoolsxjcxjcfacade p mypackagemyxml extension xinterfaces xsdadultxsd b bindingxjbparsing a schemaerror xpath evaluation of xsschemaxscomplextypenameperson results in empty target node line 8 of filecdevjaxbjaxbribindingxjbfailed to parse a schemais it possible to generate a class with jaxb that implements an interfaceupdatei have tried using the interface insertion plugin but for some reason cannot get it to work this is how i am calling xjc yet it is as if the plugin jar is not getting picked up from the classpath java cp libxjcifinsjarlibjaxbxjcjar comsuntoolsxjcxjcfacade p mypackage extension xifins myschemaxsd b bindingxjbi get the errorunrecognized parameter xifinsany ideas,['java'] +23548,is there a way to get the name of a variable php reflection i know this is not exactly reflection but kind ofi want to make a debug function that gets a variable and prints a var dump and the variable nameof course when the programmer writes a call to the function they already know the variables name so they could write something likedebug myvar myvar but i want it to be quick and easy to write just the function name the variable and voila debug myvar quicker and easier,['php'] +23552,checking for write access in a directory before creating files inside it my small utility application asks the user for an output directory via a gui file selectorthen it creates a lot of files in this output directory after some processingi need to check if the application has write access so that it informs the user and does not continue with the processing which might take a long timemy first attempt was the canwrite method of javaiofile but this does not worksince it deals with the directory entry itself and not its contents i have seen at leastone instance of a windows xp folder that can be renamed or deleted but no files may be createdin it because of permissions this is actually my testcasei finally settled with the following solutionuser places the input file in a directory and selects it from the guiall output files will be created in the directory that contains the input filefile filebrowse choosergetselectedfile chooser is a jfilechooserfile sample new filefilebrowsegetparentemptytxt try create and delete a dummy file in order to check file permissions maybe there is a safer way for this check samplecreatenewfile sampledeletecatchioexception e error message shown to user operation is abortedhowever this does not feel elegant to me since it just tries to actually create a file and checks if the operation succeedsi suspect that there must be a better way for this but all solutions i have found so farwith security managers and stuff deal with java applets and not standalone applicationsam i missing somethingwhat is the recommended way of checking for file access inside a directory beforeactually writing the filesi am using java 5,['java'] +23565,how to find and replace all old cstyle data type casts in my c source code how can i locate all old cstyle cast in my sourcei am using visual studio may be there is some compiler warning that i have to enable,"['c++', 'c']" +23569,what does a colon following a c constructor name do what does the colon operator do in this constructor is it equivalent to myclassm classid 1 m userdata 0class myclass public myclass m classid1 m userdata0 int m classid void m userdata,['c++'] +23570,should c add partial constructors an answer in this question made me wonder about the net framework design choicesthe net framework has full support for partial classes interfaces and methods is there a compelling reason that support for partial constructors was not added in the same mannerthis seems like it would simplify class construction within partial classes for example form constructors built by a designer in windows forms could have the form construction code directly in the constructor split into two files partial initialize methods seem to be a somewhat common pattern which could be simplified in this casethe only potential downside i can see would be the lack of determinism in the order of constructor calls but in many cases the ordering of the parts wouldnt matter if it did you could always avoid the partial constructor,"['c#', '.net']" +23583,ioexception while reading from inputstream i am running into a strange problem while reading from an inputstream on the android platform i am not sure if this is an android specific issue or something i am doing wrong in generalthe only thing that is android specific is this callinputstream is getresourcesopenrawresourcerrawmyfilethis returns an inputstream for a file from the android assets anyways heres where i run into the issuebytes buffer new bytes2isreadbufferwhen the read executes it throws an ioexception the weird thing is that if i do two sequential single byte reads or any number of single byte reads there is no exception in example this worksbyte bufferbuffer bytebufferreadbuffer bytebufferreadany idea why two sequential single byte reads work but one call to read both at once throws an exception the inputstream seems fine isavailable returns over a million bytes as it shouldstack trace shows these lines just before the inputstreamreadjavaioioexceptionat androidcontentresassetmanagerreadassetnative methodat androidcontentresassetmanageraccess800assetmanagerjava36at androidcontentresassetmanagerassetinputstreamreadassetmanagerjava542changing the buffer size to a single byte still throws the error it looks like the exception is only raised when reading into a byte arrayif i truncate the file to 10 bytes file is 1917408 bytes originally it works fine is there a problem with files over a certain sizeany help is appreciatedthanks,"['java', 'android']" +23603,using jquery within onclick am i allowed to use jquery within an onclick functionfor examplea onclickmy save functioninputidvalinput typehidden idinputid valuefoosuch that when clicked the anchor tag runs thismy save functionfooafter a few searches i could not find a similar topic thank you for any help,['jquery'] +23608,jaxb is good until i need to do something complex what are the alternatives jaxb works well until i need to do something like serialize beans for which i cannot modify the source if the bean does not have a default constructor or if it refers to objects i want to mark transient then i am stuck writing a separate bean which i can annotate and then manually copy the information over from the other beanfor instance i wanted to serialize exception objects but found that the only way to do that was use a hack that required using comsun classesso what alternatives are there whats the next most popular xml serializing api it would be nice to be able to do things likechoose at serialization time whether to include certain fields in the result marking things transient when running the serializerhandle loops in the object graph by using references or something other than just dyingperhaps annotate an object so that in version 1 it serializes things in one way and in version 2 it serializes them in another then when serializing i just choose which version of the object ot serializehave a way to generate xsds from annotations on an objectbasically i just want more flexibility than i currently have with jaxb,['java'] +23615,does wifstream support different encodings when i read a text file to a wide character string stdwstring using an wifstream does the stream implementation support different encodings ie can it be used to read eg ascii utf8 and utf16 filesif not what would i have to doi need to read the entire file if that makes a difference,['c++'] +23631,using accepts nested attributes for mass assignment protection in rails say you have this structureclass house activerecordbase has many rooms accepts nested attributes for rooms attr accessible rooms attributesendclass room activerecordbase has one tv accepts nested attributes for tv attr accessible tv attributesendclass tv belongs to user attr accessible manufacturer validates presence of userendnotice that tvs user is not accessible on purpose so you have a tripplenested form that allows you to enter house rooms and tvs on one pageheres the controllers create methoddef create house housenewparamshouse if housesave standard stuff else standard stuff endendquestion how in the world would you populate user id for each tv it should come from current userid whats the good practiceheres the catch22 i see in thispopulate user ids directly into params hash they are pretty deeply nestedsave will fail because user ids are not massassignablepopulate user for every tv after save is finishedsave will fail because user id must be presenteven if we bypass the above tvs will be without ids for a moment of time sucksany decent way to do this,"['ruby-on-rails', 'ruby']" +23652,how to use web camera in android emulator to capture a live image as far as i know android emulator does not have a camera to capture a live image we have to use the web camera i have seen code in this web site to use the web camera in the android emulator to capture an image but i do not know how to use this code,['android'] +23665,how to pass an event object to a function in javascript button typebutton valueclick me onclickcheck me function check me eventpreventdefault var hello documentmyformusernamevalue var err ifhello hello null err user name required iferr alerterr usernamefocus return false else return true in firefox when i try to submit an empty value it throws up the error and sets the focus back to element but same thing does not happen in ie as it throws up error and after clicking ok and posts the form returns truehow i can avoid this i was thinking to avoid this using eventpreventdefault but i am not sure how to do this using this method i tried passing checkmeevent but it didnt work i am using prototype jsi know how to pass an event when i bind an click function in javascript instead of calling onclick within html using jquery but i have to debug this piece of code,['javascript'] +23675,how do i refer to java 16 apis while degrading gracefully against java 15 i would like to use the javatextnormalizer class from java 16 to do unicode normalization but my code has to be able to run on java 15i do not mind if the code running on 15 does not do normalization but i do not want it to give noclassdeffounderrors or classnotfoundexceptions when it runswhats the best way to achieve this,['java'] +23677,datetime string parsing i have made a generic parser for parsing ascii fileswhen i want to parse dates i use parseexact function in datetime object to parse but i get problems with the yearthe text to parse is ie 090812 with the parseexact string yymmddi am hoping to get a datetime object saying 1282009 but i get 1281909i know that i could make an ugly solution by parsing it afterwards and thereby modifying the year anyone know of a smart way to solve this thanks in advancesa ren,"['c#', '.net']" +23681,best equivalent visualstudio ide for mac to program netc i am using my mac most time at work at home there is my windows computer where i program with visual studio my netc stuffbecause i want to program outside it would be great to have an equivalent ide for my macwhich software are the best solution in my case to have a similar workplace with the same functionalityi prefer open source but commercial software is okay too,"['c#', '.net']" +23682,what is the difference between group by and order by in sql when do you use which in general examples are highly encouragedi am referring so mysql but cannot imagine the concept being different on another dbms,"['sql', 'mysql']" +23696,maven2 compiler custom execution source directory and target directory i want to run the maven compiler plugin in a different phase and with different sourcedirectories and destinationdirectories such that code from directories other than srcmainjava and srctestjava can be usedi thought the solution would look something like the below where the phase i was linking it to was preintegrationtest however the properties for testsourcedirectory and testoutputdirectory do not seem to be specified in this way as they are in the section of the pomplugin groupidorgapachemavenpluginsgroupid artifactidmavencompilerpluginartifactid executions execution idcompile mytestsid goals goaltestcompilegoal goals phasepreintegrationtestphase configuration testsourcedirectorybasedirsrcinttestjavatestsourcedirectory testoutputdirectorybasedirtargetinttestclassestestoutputdirectory configuration execution executionspluginis there a way to get this plugin to compile different directories in different phases without affecting its default operation,['java'] +23697,how can i get the count of line in a file in an efficient way i have a big file it includes approximately 3020 lines how can i get the total count of lines in the file using java,['java'] +23709,sort array returned by activerecord by date or any other column how can i sort an array returned by an activerecord query by a created at date columnthis occurs once the query has been executed please do not tell me to do it in the query because i need this to happen in the view,"['ruby-on-rails', 'ruby']" +23712,bracket highlighting in textmate javascript i have some gnarly functions in javascript that i am using textmate to edit i see an extremely short flash of the matching bracket but it is almost imperceptible if you do not arrow over the bracket repeatedly is there a way to make the bracket highlight persistent,['javascript'] +23717,what value does null really have i know what null is and what its is used forquestion ok say we make a reference to an object in whatever language the computer makes a little 32bit or other size depending on computers design space in memory for that reference that memory can be assigned to a value that represents an objects location in memory but when i set the reference to null what value does it really have what are the individual bits in the reference set to are the bits just zeroed out but wouldnt that also be a location in memory how does the computer tell that the reference contains null instead of a reference to an objecti know this is not an important question but i am curious as to how it worksthanks guys d,"['c#', 'java']" +23720,jpa with toplink no metainfpersistencexml was found in classpath public class logintest public static void mainstring args entitymanagerfactory emf persistencecreateentitymanagerfactoryircbotpu entitymanager em emfcreateentitymanager emgettransactionbegin login lg new login lgsetpasswordpassword lgsetusernamerocky empersistlg emflush login st emfindloginclass lggetpassword systemoutprintlnst emgettransactioncommit emclose emfclosei am getting an exception when i try to run this classjavaxpersistencepersistenceexception no persistence provider for entitymanager named ircbotpu no metainfpersistencexml was found in classpathmetainfpersistencexml is in my classpath i do not know what is the reason or this exceptionpersistence library is toplink,['java'] +23727,overhead of c inheritance with no virtual functions in c whats the overhead memorycpu associated with inheriting a base class that has no virtual functions is it as good as a straight up copypaste of class membersclass apublic void getprotected int pxclass b public acompared withclass apublic void getprotected int pxclass bpublic void getprotected int px,['c++'] +23728,php ssl curl object moved error im developing a php script to scrape this website and email me the data to me it seems to be logging in correctly because when the script runs it seems to redirect and give me a message saying object moved here and the here is linked to the defaultaspx page which is what exactly happens when i manually login below is my script phpuseragentmozilla50 windows u windows nt 51 enus rv1811 gecko20061204 firefox2001 init curlch curl initinit curl curl setoptch curlopt useragent useragent set url for the post form logincurl setoptch curlopt url curl setoptch curlopt followlocation 0 set your login and password for authenticationcurl setoptch curlopt userpwd testupasswdcurl setoptch curlopt httpauth curlauth any this is occassionally required to stop curl from verifying the peers certificate curlopt ssl verifyhost may also need to be true or false if curlopt ssl verifypeer is thisabled it defaults to 2 check the existence of a common name and also verify that it matches the hostname providedcurl setoptch curlopt ssl verifypeer false optional return the result instead of printing itcurl setoptch curlopt returntransfer 1 enable http postcurl setopt ch curlopt post 1 set post parameters form values for each fieldcurl setopt ch curlopt postfields usernametestupasswordpasswd setting curlopt returntransfer variable to 1 will force curl not to print out the results of its query instead it will return the results as a string return value from curl exec instead of the usual truefalsecurl setopt ch curlopt returntransfer 1 execute 1st request form loginstore curl exec checho store close curlcurl close chany ideas what could be preventing the page to output the page correctly i am guessing its not redirecting correctly thanks in advance,['php'] +23757,wxpython items in boxsizer do not expand horizontally only vertically i have several buttons in various sizers and they expand in the way that i want them to however when i add the parent to a new wxboxsizer that is used to add a border around all the elements in the frame the sizer that has been added functions correctly vertically but not horizontallythe following code demonstrates the problem usrbinenv pythonimport wximport webbrowserclass appwxapp def oninitself frame mainframe frameshow selfsettopwindowframe return trueclass mainframewxframe title title def init self wxframe init self none 1 selftitle panel wxpanelself icon wxiconiconpng wxbitmap type png selfseticonicon sizer wxflexgridsizerrows2 cols1 vgap10 hgap10 button1 wxbuttonpanel 1 button sizeraddbutton1 0 wxexpand buttonsizer wxflexgridsizerrows1 cols4 vgap10 hgap5 buttondelete wxbuttonpanel 1 delete buttonsizeraddbuttondelete 0 0 buttonedit wxbuttonpanel 1 edit buttonsizeraddbuttonedit 0 0 buttonnew wxbuttonpanel 1 new buttonsizeraddbuttonnew 0 0 buttonsizeraddgrowablecol0 0 sizeraddbuttonsizer 0 wxexpandwxhorizontal sizeraddgrowablecol0 0 sizeraddgrowablerow0 0 mainsizer wxboxsizerwxexpand mainsizeraddsizer 0 wxexpandwxall 10 panelsetsizerandfitsizer sizersetsizehintsself panelsetsizerandfitmainsizer mainsizersetsizehintsselfif name main app appfalse appmainloopcommenting out lines 57 and 58 and uncommenting lines 55 and 56 removes the extra boxsizer and shows how i expect everything to function without the whitespace of coursei am completely stuck with this problem and still have no clue as to how to fix it,['python'] +23767,whats the ruby equivalent of pythons oswalk does anyone know if there is an existing modulefunction inside ruby to traverse file system directories and files i am looking for something similar to pythons oswalk the closest module i have found is find but requires some extra work to do the traversalthe python code looks like the followingfor root dirs files in oswalk for name in files print name for name in dirs print name,"['python', 'ruby']" +23768,run process with realtime output in php i am trying to run a process on a web page that will return its output in realtime for example if i run ping process it should update my page every time it returns a new line right now when i use execcommand output i am forced to use c option and wait until process finishes to see the output on my web page is it possible to do this in phpi am also wondering what is a correct way to kill this kind of process when someone is leaving the page in case of ping process i am still able to see the process running in the system monitor what makes sense,['php'] +23769,port number of sql server i am wondering what ports are used by sql server database engine i need such port number to write configuration scripts to grant access to specific port of the machine installed with sql server to make it safe a related question is whether sql server database engine will use one static port number to serve all client requests or using one port for each requestbtw my background is sql server 2008 enterprisethanks in advancegeorge,['sql'] +23770,can i edit the pixels of the uiimages property cgimage uiimage has a readonly property cgimage i have to read its pixels to a memory block and edit them and then make a new uiimage to replace the old one i want to know if there is a way bypass the readonly property and edit those pixels directlythanksthanks all i have found a way to do it write a class with those methodvoidpreprocessuiimagesrcimage m context created by calling cgbitmapcontextcreate cgcontextdrawimagem context rect srcimagecgimage m bits unsigned charcgbitmapcontextgetdata mcontextvoidpostprocess cgcontextreleasem context freem bitsuiimagedoprocesscgpointpt just a example unsigned char ppxl m bits do something cgimageref imref cgbitmapcontextcreateimagemcontext return uiimage imagewithcgimageimrefand preprocess and postprocess are called just once,['iphone'] +23784,checking for directory and file write permissions in net in my net 20 application i need to check if sufficient permissions exist to create and write to files to a directory to this end i have the following function that attempts to create a file and write a single byte to it deleting itself afterwards to test that permissions do existi figured the best way to check was to actually try and do it catching any exceptions that occur i am not particularly happy about the general exception catch though so is there a better or perhaps a more accepted way of doing thisprivate const string temp file tempfiletmp summary checks the ability to create and write to a file in the supplied directory summary param namedirectorystring representing the directory path to checkparam returnstrue if successful otherwise falsereturnsprivate static bool checkdirectoryaccestring directory bool success false string fullpath directory temp file if directoryexistsdirectory try using filestream fs new filestreamfullpath filemodecreatenew fileaccesswrite fswritebyte0xff if fileexistsfullpath filedeletefullpath success true catch exception success false,"['c#', '.net']" +23800,wheres the difference between myclass alloc and self class alloc is there a good reason why i should not do something like thisexamplei have a class myclass in there i have this implementation idcopywithzonenszonezone myclass copy myclass allocwithzonezone init copysomeproperty selfsomeproperty copy autorelease return copyinstead of that i found a snippet that looks like this idcopywithzonenszonezone myclass copy self class allocwithzonezone init copysomeproperty selfsomeproperty copy autorelease return copythe difference is that the first one just uses the name if its own class humanly readable just as if it was any other class and the second one asks self for what class that is does that make a difference or are both totally okay to use in this case,['iphone'] +23804,how can you use jquery measure how far down the user has scrolled i need to change the style of an element after the user has scrolled down beyond a certain number of pixels and then change it back once the user has scrolled back up i am using jquery already so i would like to use jquery if possible can anyone provide an example where you add a a classname to a div once the user has scrolled beyond 200 pixels and then remove the classname once the user has scrolled back up to less than 200 pixels,"['jquery', 'css']" +23809,any javascript engine for netc i am looking for an open source javascript engine for net thanks,"['c#', 'javascript']" +23810,best practices for receiving email in rails i have been trying to figure out the best way to handle incoming email in a rails applications i realize best practices is quite subjective so i will start by stating that my primary concerns are scalability and efficiency this is an issue primarily because my use will involve handling potentially large attachmentsseems like just yesterday the accepted method was to use actionmailer to receive the email but recently i have stumbled across several articles saying this is inefficient as it spawns a new rails instance with each email horrible at high volumesmost recently this article has been getting my attentionthe post talks about a slimmed down version of the actionmailer system that is not forced to spawn an entire rails instance but the comments talk about several other options like a dedicated mail directory maildir and imappop retrieval my question is does anyone have any thoughts on what the best option would currently be for processing incoming email in a rails application including attachments,"['ruby-on-rails', 'ruby']" +23817,iphone core data unresolved error while saving i am getting a strange error message from the core data when trying to savebut the problem that the error is not reproducible it appears at different times when doing different tasksthe error messageunresolved error domainnscocoaerrordomain code1560 userinfo0x14f5480 operation could not be completed cocoa error 1560 nsdetailederrors error domainnscocoaerrordomain code1570 userinfo0x5406d70 operation could not be completed cocoa error 1570error domainnscocoaerrordomain code1570 userinfo0x14f9be0 operation could not be completed cocoa error 1570and the method that generates the error is ibactionsaveactionidsender nserror error if self managedobjectcontext saveerror handle error nslogunresolved error error error userinfoerror localizeddescription exit1 fail any idea for the reason of this message giving that it appears at random times,"['iphone', 'objective-c', 'ios']" +23820,c comparison to null religious arguments asideoption1if pointeri null option2if pointeri in c is option1 functionally equivalent to option2 does the later resolve quicker due to absence of a comparison,['c'] +23835,implement comet server push in google app engine in python how can i implement comet server push in google app engine in python,['python'] +23848,attempting to deploy my app on my jailbroken iphone but the app closes immediately i am trying to develop iphone apps on my jailbroken iphone and i cannot seem to get the process down for whenever i deploy my app set all file permissions to 7 and respring the application closes immediately when i try to launch it furthermore it does not have the autogloss xcode shows in the iphone simulator so what givesi have generated the cert via keychain access and added the two keys for requireprovisioning and allowprovisioning both values no and then set the appropriate cert in xcode but the application still closes immediately when i attempt to run it on my phonewhat gives,['iphone'] +23863,ruby implementation is numeric for strings need better alternatives i wanted to validate numericality of a string its not an attribute in an activerecord model i just need it to be a valid base 10 positive integer string i am doing thisclass string def numeric check if every character is a digit selfmatcha09z endendclass string def numeric check is there is any nonnumeric character selfmatch09 endendwhich of these is a more plausible alternative or is there any other better implementation,['ruby'] +23880,net equivalent of javas listsublist is there a net equivalent of javas listsublist that works on ilistt,"['java', '.net']" +23890,ruby gsub and regex quick background i have a string which contains references to other pages the pages are linked to using the format 12 a hash followed by the id of the pagesay i have the following stringstr this string links to the pages 12 and 125i already know the ids of the pages that need linkingpage ids strscandflatten 12 125how can i loop through the page ids and link the 12 and 125 to their respective pages the problem i have run into is if i do the following in railspage idseach do id str strgsubid link toid page pathidendthis works fine for 12 but it links the 12 part of 125 to the page with id of 12any help would be awesome,"['ruby-on-rails', 'ruby']" +23895,jquery if found in string how can i have jquery check to see if the content of a variable contains a specific word and have it execute an alert if matched,['jquery'] +23896,in objectivec why should i check if self super init is not nil i have a general question about writing init methods in objectiveci see it everywhere apples code books open source code etc that an init method should check if self super init is not nil before continuing with initialisationthe default apple template for an init method is id init self super init if self nil your code here return selfwhyi mean when is init ever going to return nil if i called init on nsobject and got nil back then something must be really screwed right and in that case you might as well not even write a programis it really that common that a class init method may return nil if so in what case and why,['objective-c'] +23903,activatorcreateinstance how to create instances of classes that have parameterized constructors i have read a few bits and bobs online about this topic but found none that work for mewhat i am trying to do is create a class of a runtime typei use activatorcreateinstance which works fine for classes with constructors that contain no arguments for those with arguments it throws an exception is there a way around thisi am more than happy to pass null values or empty values to the ctor so long as i can create the class itself,"['c#', '.net']" +23916,android dropdown select css i am currently writing some stylesheets for mobile browsers and have come across a strange issue in the android browser when changing the fontsize css attribute of a text box the box gets bigger to accomodate the larger text doing this on a select box however does not change the size of the select box but the text still gets larger actually overlapping the top and bottom of the rendered form elementcan anyone tell me if it is possible to increase the height of select boxes in the android browser or if not point me in the direction of a list of css attributes that can be applied to themthanks,"['css', 'android']" +23925,attach child process to debugger automatically if the main process is currently being debugged in visual studio how can i have it so any new processes it spawns are also attached to the same instance of visual studio as the main process iscurrently the new processes are created just with a createprocess call however i can add extra code or use a different api altogether if needed as well as making changes to the project or solution configurations each process has its own project in a single solution,['c++'] +23930,c backgroundworker reports string how can i report a string like now searching file found selection back to my windowsform from a backgroundworker as well as a percentage additionally i have a large class that contains the method i want to run in the backgroundworker work i can call it by class method but i am then unable to report my percentage done or anything from the called class only from the backgroundworker work methodthanks,['c#'] +23944,is there a recommended package for machine learning in python is there a recommended package for machine learning in pythoni have previous experience in implementing a variety of machine learning and statistical algorithms in c and matlab but having done some work in python i am curious about the available packages for python,['python'] +23968,how do i unit test code that uses a fluent interface i have created a few small fluent interfaces through method chaining they typically call a number of repositories that fetch data from webservices databaseshow should i go about unit testing methods that use the fluent interfacepublic ienumberablecomputer findcomputersstring serialnumber return computersfindbyserialnumberybcx00900 attachconfiguration ensureallcomputershaveconfigurationi can unit test the individual components of the fluent interface but if i want to unit test the findcomputers method above what should i douse the concrete implementation of the fluent interface and writeexpectations on the repository classesmock the fluent interface itself and set expectations on thattest only the fluent interface itself and not the findcomputers methodi would like to find an easily maintainable approach,"['c#', '.net']" +23975,determine document order from nodes if i have two nodes in an html document how can i tell which one comes first in html document order in javascript using dom methodsfor examplefunction funstuffa b a and b can be any node in the dom text element etc ifb comes before a in document order var t b b a a t process the nodes between a and b i can handle this part when i know that a comes before b,"['javascript', 'html']" +23978,capture iphone screen with status bar included i am looking for a way to capture a screenshot on the iphone with the top status bar included i am currently using the following code uigraphicsbeginimagecontextselfviewboundssize selfviewwindowframesizeselfviewlayer renderincontextuigraphicsgetcurrentcontextuiimage viewimage uigraphicsgetimagefromcurrentimagecontextuigraphicsendimagecontextuiimagewritetosavedphotosalbumviewimage nil nil nilthe above code sucessfully takes a screenshot of the iphone uiview but does not include the top status bar in its place is just a blank 20px space,"['iphone', 'objective-c']" +23983,select multiple images uiimagepickercontroller or photosapp share ui in iphone os 30 apple added the ability to share multiple pictures at once using the share button and selecting multiple uiimages where a checkmark is used i would love to have a uiimagepickercontroller which lets the user select multiple images at once rather than having to go one by one is there a way to do this or do i have to wait until they add this feature,"['ios', 'iphone']" +23984,java xml parsing using dom to get nodevalue try string data ab cd ef015ba documentbuilderfactory documentbuilderfactory documentbuilderfactory newinstance documentbuilder documentbuilder documentbuilderfactory newdocumentbuilder inputsource is new inputsource issetcharacterstreamnew stringreaderdata document document documentbuilderparseis nodelist nl documentgetelementsbytagnameb node and node nlitem0 systemoutprintlnngetnodevalue catch exception e systemoutprintlnexception e i am expecting it to print 015 but it prints null any ideasedit this did the trick if nhaschildnodes systemoutprintlnngetfirstchildgetnodevalue else systemoutprintlnngetnodevalue,['java'] +23985,jqgrid dynamic select option i am creating a jqgrid with drop down columns and i am using cell editing i need the options of the drop down columns to change dynamically and i have tried implementing this by setting the column to be name accountlookup index accountlookup width 90 editable true resizable true edittype select formatter select and then in the beforecelledit event i havebeforeeditcell functionid name val irow icol ifnameaccountlookup var listdata getlookupvaluesid name if listdata null listdata 11 jquerygridsetcolpropname editoptions value listdatatostring getlookupvalues just returns a string in the format 1one2two etcthat works fine however the options are populated one click behind ie i click on accountid in row 1 and the dropdown is empty however when i then click on accountid in row 3 the options i set in the row 1 click are shown in the row 3 click and so on so always one click behindis there another way of achieving what i need bacially the dropdown options thisplayed are always changing and i need to load them as user enters the cell for editingperhaps i can somehow get at the select control in the beforeeditcell event and manually enter its values instead of using the setcolprop call if so could i get an example of doing that pleaseanother thing if the dropdown is empty and a user does not cancel the cell edit the grid script throws an error i am using clientarray editing if that makes a difference,['jquery'] +23991,how to build good documentation with rest api in rails currently i am working on building restful web service in rails i am looking for some ways to build a good documentation in my rails restful web service i found some ways to do itwiki like twitter apirdocwadl i am not sure if anyone is currently using itcould anyone gives any recommendations,['ruby-on-rails'] +24030,how do i refresh the browser every x seconds with javascript i use a firefox plugin that can refresh the browser window every x seconds as a frontend developer this is really useful as i can get instant feedback on css xhtml changes the moment i save them in my editori have noticed however that this often stops working i am guessing this may be due to javascriptjquery that i have added to the page interfering with the plugini was just wondering if it was possible to add a temporary line of javascript to mimic this autorefresh behaviour when needed,['javascript'] +24031,how do i center vertically and horizontally buttons in a div tag i am trying to determine how to center vertically and horizontally buttons in a div taggiven the following cssdivlistboxmoverusercontrol width 350px height 175pxdivlistboxmoverusercontrol div height 150pxdivlistboxmoverusercontrol div select width 150px height 150pxdivlistboxmoverusercontrol divlistboxmoverusercontrol column1 float left width 150pxdivlistboxmoverusercontrol divlistboxmoverusercontrol column2 float left width 50pxdivlistboxmoverusercontrol divlistboxmoverusercontrol column3 float left width 150pxi would like to have the buttons in this markup centered how can i modify the css to achieve thisdiv classlistboxmoverusercontrol div classlistboxmoverusercontrol column1 labeltest1label asplistbox runatserverasplistbox div div classlistboxmoverusercontrol column2 input idbtnmoveright typebutton value br input idbtnmoveleft typebutton value br div div classlistboxmoverusercontrol column3 labeltest2label asplistbox runatserverasplistbox divdiv,"['css', 'html']" +24032,t4 transformation and build order in visual studio i have a vs project that contains1 a prebuild action of running texttransform on a templatett to generate generatedcs2 generatedcs listed as one of the files to compile ie in the list of project fileswhen i build the project the prebuild action is done generatedcs is recreated but vs compiles the previous version of it that i guess it loaded to memory at start of the build processwhat can be done so that the build will use the newlly generated cs file that is generated in the prebuild actionnote that in my situation the text transformation input is dynamic hence cannot be done in design timethanks,['c#'] +24033,how can i do an update statement with join in sql i need to update this table in sql server 2005 with data from its parent table see belowsaleid intudid intassid intudid intassid intsaleassid contains the correct value to update udassid what query will do this i am thinking a join but i am not sure if it is possible,['sql'] +24034,sql to output line number in results of a query i would like to generate a line number for each line in the results of a sql query how is it possible to do thatexample in the request select thistinct client name from deliveriesi would like to add a column showing the line numberi am working on sql server 2005,['sql'] +24042,is there any way to change directory using c language is there any way by which i can change to any directory by executing a c program,['c'] +24048,php split a string in to an array foreach char i am making a method so your password needs at least one captial and one symbol or numberi was thinking of splitting the string in to lose chars and then use preggmatch to count if it contains one capital and symbolnumberhowever i did something like this in action script but cannot figure out how this is called in php i cant find a way to put every char of a word in a arrayas3 example forvar iuint 0 i thiswordcodelength 1 ithiswordcodeverdeeldi thiswordcodecharatitrace thiswordcodeverdeeldithanksmatthy,['php'] +24060,c automatic properties i am a bit confused on the point of automatic properties in c egpublic string forename get set i get that you are saving code by not having to declare a private variable but whats the point of a property when you are not using any get or set logic why not just usepublic string forename i am not sure what the difference between these 2 statements is i always thought you used properties if you wanted additional getset logic,['c#'] +24064,set colspan dynamically with jquery i have a simple table structure like this what i would like to do is to dynamically merge some columns based on some condition within the for example if td1 and td3 are empty then merge the cells and do td classcol1 colspan31meetingtdi tried playing around with jquery using tblsimpleagenda tdcontainshidebut it had not the effectwhat would be the the best way using jquery to achieve this cheersterrytable classtblsimpleagenda cellpadding5 cellspacing0 tbody th alignlefttimeth th alignleftroom 1th th alignleftroom 2th th alignleftroom 3th tr valigntop td classcoltime0900 a 10td td classcol1td td classcol2meeting 2td td classcol3td tr tr valigntop td classcoltime10 a 1045td td classcol1meeting 1td td classcol2meeting 2td td classcol3meeting 3td tr tr valigntop td classcoltime1100 a 1145td td classcol1meeting 1td td classcol2meeting 2td td classcol3meeting 3td trtbodytable,['jquery'] +24074,whats the difference between boolean and boolean in java i would like to understand the difference between the boolean and boolean types in java specifically as they relate to gwti know that methods are not supported but i want more info if it is available,['java'] +24080,javascript date subtraction helloi am looking for a way to do proper subtraction between two javascript date objects and get the day deltathis is my approach but it fails for todays date as an inputscript typetextjavascriptfunction getdaydeltaincomingyearincomingmonthincomingdayvar incomingdate new dateincomingyearincomingmonthincomingdayvar today new datevar delta incomingdate todayvar resultdate new datedeltareturn resultdategetdateworks for the future datesalertgetdaydelta2009910alertgetdaydelta2009819fails for the today as input as expected 0 deltainstead gives 31alertgetdaydelta2009818scriptwhat would be a better approach for this,['javascript'] +24085,good resources for learning plpgsql i have been looking around the net trying to find good resources for learning postgresqls procedural programming language plpgsqlso far the only thing i have managed to dig up is the tutorial in the postgresql documentation while that is good i have been looking for something more indepth can you recommend anything,['sql'] +24093,windows 7 progress bar in taskbar in c if youve noticed in the windows 7 beta if you copy files or other system actions the windows explorer icon in the taskbar will fill up with a green progress bar equivalent to the progress bar on the form is there a way that in my c forms i can force my taskbar progress bar to match the progress of whatever task i am doing converting transferring generating there are so many uses for that progress bar,['c#'] +24094,javascript to select multiple options i have a form with a select box that allows multiple options after a user saves these options it stores them in a database table i can then read this database table to get the options they chose one again i need to be able to grab this data from the database put it into an array then have the options in that select box to be preselected when they go to edit their optionsreading the data into an array is fine and i know how to make a single option selected within a select box however i am not sure how to handle multiple options being selected in javascriptcan someone help me figure out the javascript required to do this,['javascript'] +24099,android quotes within an sql query string i want to perform a query like the followinguvalue edittext some user value p query select from mytable where name field uvalue mdbrawquery p query null if the user enters a single quote in their input it crashes if you change it top query select from mytable where name field uvalue it crashes if the user enters a double quote in their inputand of course they could always enter both single and double quotes,['android'] +24104,building v8 without jit i would like to run some tests on v8 with and without jit to compareperformancesi know jit will improve my average speed performance but it would benice for me to have some actual more detailed tests results as i want to work with mobile platformsi have not found how to enable or thisable jit like it exists on squirrelfish cf enable jit in javascriptcorewtfplatformhdoes somebody knows how to do that with v8thanksalexandre,['javascript'] +24105,smtp send is locking up my files c i have a function thats sending messages a lot of them and their attachments it basically loops through a directory structure and creates emails from a file structure for example cemailsmessage01 attachments cemailsmessage02 attachmentsthe creation of the messages takes place using net c standard stuff after all messages are created i have another function that runs directly afterwards that copies the message folder to another location problem is files are lockednote i am not moving the files just copying themany suggestions on how to copy locked files using cupdatei have this add attachments method private void addattachmentsmailmessage mail string attachmentdirectorypath cmessagesmessage1 directoryinfo attachmentdirectory new directoryinfoattachmentdirectorypath fileinfo attachments attachmentdirectorygetfiles foreach fileinfo attachment in attachments mailattachmentsaddnew attachmentattachmentfullname,['c#'] +24110,teamcity msbuild integration is there any way to get teamcitys build numbering to match the publish version applicationrevision number generated by msbuilds publish task,['.net'] +24112,does ironpython implement python standard library i tried ironpython some time ago and it seemed that it implements only python language and uses net for libraries is this still the case can one use python modules from ironpython,['python'] +24113,net mvc call method on different controller can anybody tell me how to call a method on a different controller from within an action method i do not want to redirect i want to call a method on a different controller that returns a string and use the response within my action method,['.net'] +24117,is it possible to read and step into net framework source code is there any way for people using vs2008 to step into and read the source code for the msdn librariesi come from a java background where this is possible,['.net'] +24136,detect cpu speedmemoryinternet speed using java is it possible within java to identify the total cpu speed available as well as the total system memory network connection speed to the web would also be awesome,['java'] +24156,what are the pros and cons of adopting html 5 now for a site redesign i am working on a large siteas rewrite and redesign i have been reading up on html 5 and wanted to know what the cons are before adopting it for this design implementationthe design needs to work in agrade browsers yes including ie6 so i am wondering how footer section etc will be rendered inlineblock etci would also like to know the pros so that i can sell it to any conservatives within the business,['html'] +24158,c trying to capture the keydown event on a form i am creating a small game the game is printed onto a panel on a windows form now i want to capture the keydown event to see if its the arrow keys that has been pressed the problem however is that i cannot seem to capture itlet me explain on the form i have 4 buttons and various other controls and if the user for instance press one of the buttons to trigger a game event then the button has focus and i cannot capture the movements with the arrow keysi tried something likeprivate void keydownkeyeventargs e if ekeycode keysleft gamemoveplayerdonutwarslibrarygameobjectsdirectione gamedrawobjectspanel1creategraphics else if ekeycode keysright gamemoveplayerdonutwarslibrarygameobjectsdirectionw gamedrawobjectspanel1creategraphics else if ekeycode keysup gamemoveplayerdonutwarslibrarygameobjectsdirectionn gamedrawobjectspanel1creategraphics else if ekeycode keysdown gamemoveplayerdonutwarslibrarygameobjectsdirections gamedrawobjectspanel1creategraphics and then when the form key down event was pressed i used thisprivate void mainform keydownobject sender keyeventargs e keydowne i also added keydown for the buttons and the various other controls on the windows form but i am not getting any response back i have setup a breakpoint inside the function to see if it is being called but that breakpoint never triggersany ideasthe most optimal was to have a general keydown event that triggers regardless of what control that currently has focus and then calls the keydown method,['c#'] +24175,can i save an object in a sql server database i want to save an object of any type into a field in a database in sql server 2005 is it possible do i have to convert the object into something like a byte array for example and cast it back when retrieving it,['c#'] +24177,programmatic web browser java library does anyone know of any java library for programmatic web browsingprowser does not cut it because there is no push the button method and watij is limited to internet explorer windows only,['java'] +24180,javac not recognized what can i do when i keep receiving the errorjavac is not recognized as an internal or external command operable program or batch filewhen i want to compile my jar or class filethanks,['java'] +24184,event delegate or interface suppose i have a monkey class which sometimes needs to acquire an instance of banana the way this banana is provided is not of interest to the monkey but it does initiate the banana acquisitionnow i have at least three possible ways to wire my monkey to a banana provider what is the best way to do it1 eventraise a monkeybanananeeded event the event handler sets the banananeededeventargsbanana property2 interfaceinvoke ibananaprovidergetbanana the ibananaprovider instance is injected in the monkey as a constructor argument or through a property3 delegateinvoke a delegate of type systemfuncbanana the delegate is injected in the monkey as a constructor argument or through a property this one is tempting because it does not require the declaration of any extra interfaces or classes but apparently it is not a popular choice,['c#'] +24185,how to handle add to list event i have a list like thislistcontrols list new listcontrolshow to handle adding new position to this listwhen i domyobjectmylistaddnew controli would like to do something like this in my objectmylistaddingevent handleaddingeventand then in my handleaddingevent delegate handling adding position to this list how should i handle adding new position event how can i make this event available,['c#'] +24188,ignore openmp on machine that does not have it i have a c program using openmp which will run on several machines that may have or not have openmp installed how could i make my program know if a machine has no openmp and ignore those include openmp directives like pragma omp parallel andor library functions like tid omp get thread num thanks and regards,"['c++', 'c']" +24194,good php metric tools i have been coding in php for a while using netbeans but it does not provide any tools for obtaining code metrics i have also used sourcemonitor before but it does not support php same with code analyzerhas anyone used and can recommend any tools for getting code metrics from php code,['php'] +24208,md5 hash with salt for keeping password in db in c could you please advise me some easy algorithm for hashing user password by md5 but with salt for increasing reliabilitynow i have this oneprivate static string generatehashstring value var data systemtextencodingasciigetbytesvalue data systemsecuritycryptographymd5createcomputehashdata return converttobase64stringdata,"['c#', '.net']" +24215,openid trying to get email address from google op iam using dotnetopenauth 32 to implement openid and canat figure out how to get google to pass the email address in the claims response i know that google doesnat support simple registration but i canat determine what they do support caveat to this question is that i just started learning openid and i know i donat have a solid grasp on the specification which i think is leading to my confusion any help would be appreciated,['c#'] +24220,set variable in parent window from iframe i have a parent document with an embedded iframe inside the iframe i have an upload field once the user selects a file to upload i trigger a jquery change event on that event i want to set a variable in the parent window to true so that the parent knows that the upload has starteddoes anyone know how to do thiswas trying this but did not workvar testnewsletter emailchangefunction parentwindowtest truesendclickfunction if test alertfile has been uploaded else alertyou need to upload a file,['javascript'] +24225,tools to find included headers which are unused i know pclint can tell you about headers which are included but not used are there any other tools that can do this preferably on linuxwe have a large codebase that through the last 15 years has seen plenty of functionality move around but rarely do the leftover include directives get removed when functionality moves from one implementation file to another leaving us with a pretty good mess by this point i can obviously do the painstaking thing of removing all the include directives and letting the compiler tell me which ones to reinclude but i would rather solve the problem in reverse find the unused ones rather than rebuilding a list of used ones,['c++'] +24234,whats a great dev setup for working with php mysql i have been a php dev for many years now and it just dawned on me that maybe i could be using better development toolsfor example my typical setup for development is notepaddev wamp server local machine usuallycodeigniter framework lately i have fallen in love with it as it speeds up deployment for me big timephpmyadmin for mysql of courseif you are a php dev whats your typical setup eclipse too bulky for me at times etci am curious if i am missing something that might save me a ton of time like some kind of on the fly php code validator before i hit f5 and then debut what the error is i currently achieve somewhat of a validation by seeing the color highlights in notepad,"['php', 'mysql']" +24238,what is the simplest way in python to print to a remote ippcups server or printer i have a postscript file and want it to be printed on a ipp capable device or cups server what is the minimal code and dependencies i could get away with to do thatusing lpr or libcups gives me lot of crossplattform dependencies so my first approach was to implement a minimal subset of ipp the protocol used by cups and many modern printers since it is only extended http but unfortuntely a ipp client is a lot more code than a few lines and so far i found no ipp client implementation meant for just printing and not managing a printserveri would prefer a solution in python but would also be happy with something in an oter dynamic language,['python'] +24248,padding error when using rsa encryption in c and decryption in java currently i am receiving the following error when using java to decrypt a base64 encoded rsa encrypted string that was made in cjavaxcryptobadpaddingexception not pkcs1 block type 2 or zero paddingthe setup process between the exchange from net and java is done by creating a private key in the net key store then from the pem file extracted created use keytool to create a jks version with the private key java loads the already created jks and decodes the base64 string into a byte array and then uses the private key to decrypthere is the code that i have in c that creates the encrypted stringpublic string encryptstring value byte bain null byte baret null string keycontainername test cspparameters cp new cspparameters cpflags cspproviderflagsusemachinekeystore cpkeycontainername keycontainername rsacryptoserviceprovider rsa new rsacryptoserviceprovidercp convert the input string to a byte array bain unicodeencodingunicodegetbytesvalue encrypt baret rsaencryptbain false convert the encrypted byte array to a base64 string return converttobase64stringbarethere is the code that i have in java that decrypts the inputted stringpublic void decryptstring base64string string keystorepath ckeykeystore string storepass 1234 string keypass abcd byte data base64decodebase64string byte cipherdata null keystore keystoregetinstancejks keystoreloadnew fileinputstreamkeystorepath storepasstochararray rsaprivatekey privatersakey rsaprivatekey keystoregetkeyalias keypasstochararray cipher cipher ciphergetinstancersaecbpkcs1padding cipherinitcipherdecrypt mode privatersakey cipherdata cipherdofinaldata systemoutprintlnnew stringcipherdatadoes anyone see a step missing or where the padding or item needs to be changed i have done hours of reading on this site and others but have not really found a concrete solutionyoure help is vastly appreciatedthanks matt,"['c#', 'java']" +24250,lua vs phppythonjspetc i am about to begin my next web development project and wanted to hear about the merits of lua within the webdevelopment spacehow does lua compare to phppythonjspetc for web developmentany reason why lua would be a poor choice for a web application language vs the others,"['php', 'python']" +24262,javascript onclickformsubmit does not work on ie opera i have a code see it below it works perfectly in firefox it saves submitted information after clicking jl save button and keeps user on same pagebut in internet explorer opera it only redirects to index page indexphp and does not save submitted information what can i do for solving this problem thankshere is my code form actionindexphp idmosform methodpost enctypemultipartformdata fieldset legend jl about myselflegend span classa onclickshowhidelegendabout myself 1 jl edit blockspan div idabout myself descr stylethisplay block jl self descrdiv div idabout myself 1 stylethisplay nonephp include htmlabout myself fillphpdiv div idabout myself 2php include htmlabout myself showphpdiv fieldset fieldset legend jl about myselflegend span classa onclickshowhidelegendtype 1 jl edit blockspan php if typ block php input typecheckbox idjl type block namejl type block php if roon type block echo checked input typecheckbox idjl type block namejl type block thisabled php echo checked label forjl type block jl on blocklabel php else echo jl off block div idabout myself descr stylethisplay block jl self descrdiv div idtype 1 stylethisplay none php include htmltypephp div php if typ block div idtype 2 php include htmltype showphp div php fieldset fieldset legend jl interestlegend span classa onclickshowhidelegendinterest 1 jl edit blockspan php if interest block input typecheckbox idjl interest block namejl interest block thisabled php echo checked label forjl interest block jl on blocklabel php else echo jl off block div idinterest descr stylethisplayblock jl interest descrdiv div idinterest 1 stylethisplaynone php include htmlinterestphp div php if interest block div idinterest 2 php include htmlinterest showphp div php fieldset input typesubmit namesave value jl save onclickmosformsubmit input typehidden nameoption valuecom joomlove input typehidden idtask nametask valuesave info formfull source available here,['javascript'] +24266,activerecordrecordnotfound could not find user without an id please see updates at the bottom of the questionfor reference this problem evolved out of some fixes i made based on a previous problem i was having here associating two models in rails user and profilei am building an app that has a user model and a profile modeli want to associate these models such that after the user creates an account he is automatically sent to the create profile page and the profile he creates is connected to only that particular user only the user who owns the profile can edit iti generated the user model using nifty generators when the user hits submit for the account creation i redirect him to the new profile view to create a profile i did this by editing the redirect path in the user controller the user controller looks like thisdef new user usernewenddef create user usernewparamsuser if usersave sessionuser id userid flashnotice thank you for signing up you are now logged in redirect to new user profile pathuser id user else render action new endendwhen i click submit to create a new user it now sends me to the following url which seems right localhost30users6profilenew but it throws the following exceptionnomethoderror in profilescontrollernew you have a nil object when you did not expect it the error occurred while evaluating nilbuildthe trace indicates that the problem is in the profiles controller in the new method the profiles controller looks like thisdef index user userfindparamsuser id profile userprofileorder created at descenddef show user userfindparamsuser id profile userprofilefindparamsidenddef new user userfindparamsuser id profile userprofilebuildenddef edit user userfindparamsuser id profile userprofilefindparamsidenddef create user userfindparamsuser id profile userprofilebuildparamsprofile if profilesave flashnotice profile was successfully created redirect toprofile else flashnotice error something went wrong render action new endendadditionally the app also throws an exception when i try to view the index page of the profiles there are currently no profiles because i cannot get past the user creation step to create one this is the exceptionactiverecordrecordnotfound in profilescontrollerindexcould not find user without an id this is what the log is telling me processing profilescontrollerindex get parameters actionindex controllerprofiles activerecordrecordnotfound could not find user without an id appcontrollersprofiles controllerrb5in indexto give you the rest of the details on the app the models have the following associations profile belongs to user user has one profile i have this in the routesrb file mapresources users has one profile in the view for the new profile page that is throwing the first exception listed above i have this form foruser profile do f ferror messages end in the view for the profile index that is throwing the second exception explained above i have this profileseach do profile div classpost div classleft pstore p pcategory p div div classright ph profilename p ph profilecategory p div div classbottom p link to go to profile user profile pathuser profile p p link to edit edit user profile pathuser profile p p link to destroy user profile pathuser profile confirm are you sure method delete p div i have spent hours trying to track down the problem myself as a learning exercise but at this point i have no idea how to fix this appreciate the helpupdate jdl per your requestprofilesnewhtmlerb form foruser profile do f ferror messages div classleft p flabel name br ftext field name required p p flabel category br ftext field category required p p flabel address1 br ftext field address1 p p flabel address2 br ftext field address2 p p flabel city br ftext field city p p flabel state br ftext field state p p flabel zip br ftext field zip required p p flabel phone br ftext field phone p p flabel email br ftext field email p div div classright p flabel website br ftext field website p p flabel description br ftext area description p div p fsubmit create p end routesrb actioncontrollerroutingroutesdraw do map mapsignup signup controller users action new maplogout logout controller sessions action destroy maplogin login controller sessions action new mapresources sessions mapresources users has one profile maproot controller home mapconnect controlleractionid mapconnect controlleractionidformat end profiles controller as of 82009 8pm est class profilescontroller applicationcontroller def index users userallorder created at desc end def show user userfindparamsuser id end def new userprofile profilenew end def edit user userfindparamsuser id profile userprofilefindparamsid end def create user userfindparamsuser id profile userprofilebuildparamsprofile if profilesave flashnotice profile was successfully created redirect toprofile else flashnotice error something went wrong render action new end end def update profile profilefindparamsid if profileupdate attributesparamsprofile flashnotice profile was successfully updated redirect toprofile else render action edit end end def destroy profile profilefindparamsid profiledestroy redirect toprofiles url endendcody the index page below is throwing the following exceptionnomethoderror in profilesindexshowing appviewsprofilesindexhtmlerb where line 14 raisedundefined method name for div idposts userseach do profile div classpost div classleft pstore p pcategory p div div classright ph profilename p ph profilecategory p div div classbottom p link to go to profile user profile pathuser profile p p link to edit edit user profile pathuser profile p p link to destroy user profile pathuser profile confirm are you sure method delete p div div,['ruby-on-rails'] +24289,using linq dynamic query library with dictionary and asqueryable in one of my previous questions about using dynamically built up strings where clauses and using them in linq i was guided towards the linq dynamic query library dynamic linqthe first issue was that it only applies to iqueryable this however can be overcome by using the asqueryable extension method on any ienumerablethe problem i ran into was that dynamic linq is looking for a property called customerid or whatever was passed in to the string predicate for dynamic linq on my dictionary which obviously would not work since a dictionary only has keys and valuesso thinking i am being clever i created a class extending dictionarystring object icustomtypedescriptorthis allowed me to override getproperties on the type which is great i can now iterate the dictionary keys and add them to a propertydescriptorcollection which gets returnedbut then i ran into another problem throughout the dynamic linq library they work with expression instance which only contains a type but for my customtypedescriptor solution to work i need an actual instance of the type before i can apply typedescriptorgetpropertiesinstance falseso getting to the actual question taking all the above information into account how do i apply a custom where clause in string format customerid1234 and quantity 10 to a linq query if the data is stored in a dictionary with keyvalue pairsmy current solution is transforming the data into a datatable and using the selectquery method which works but i am interested in finding other solutions especially for benchmarking purposesany ideas,['c#'] +24292,curious is it possible to have dynamic ajax data variable names some backgroundon a recent project i tried to write a streamlined jquery plugin that would handle some ajax calls made when various inputs were updated i wrote the javascript function as a plugin so that i could just call it on various inputs like soemailupdatechangesthen from within the plugin i collected the inputs id value etcthe problemsomething that i really wanted to do but could not find a solution for was to dynamically generate the name of the data variable being passed through ajaxto be more clear given this functionjqueryfnupdatechanges function thisbindblurfunction var inputname thisattrname var inputvalue thisval postajaxupdatevaluephp email inputvalue functionret if retsuccess alertall good how do i present the data for the ajax call as password inputvalue instead of email inputvalue when the inputname variable is password instead of email this is a very specific example but basically i am just looking for a way to read the name of the data variable from a separate dynamic variablei tried windowinputname with no luck and i am pretty much convinced this is impossible however if someone has an idea i would be very impressedincidentally we ended up going with type inputname value inputvalue instead but it required a little bit more legwork on the php side do not ask me i am just the frontend guy thanks in advance,"['javascript', 'jquery']" +24303,how to set list of parameters on prepared statement i have a list of names egliststring names namesaddcharlesand a statementpreparedstatement stmt connpreparestatementselect from person where name in how to do the followingstmtsetparameterlist1namesis there a workaround can someone explain why this method is missingusing java postgresql jdbc3,['java'] +24305,how to show ajax loading gif animation while the page is loading i try to implement ajax in my website when the content of the div changepass is clicked then it should load changepasstemplatephp here is the code im using for that function changepassclickfunction block1loadviewschangepasstemplatephp return false my question is how to show gif animation loadinggif while the page changepasstemplatephp is fully loaded give me some code tips please,"['php', 'jquery', 'css']" +24307,how to get the current date and time of your timezone in java i have my app hosted in a london server i am in madrid spain so the timezone is 2 hours how can i obtain the current date time with my time zonedate curr date new datesystemcurrenttimemilliseg date curr date new datesystemcurrenttimemillismad timezonewith jodatimedatetimezone zone datetimezoneforideuropemadriddatetime dt new datetimezoneint day dtgetdayofmonthint year dtgetyearint month dtgetmonthofyearint hours dtgethourofdayint minutes dtgetminuteofhour,['java'] +24310,concat in javascript not working for associative arrays i have a problem concatenating two associative arrays in javascript below is the sample codevar firstarray new arrayfirstarrayc1 sam firstarrayc2 kamvar secarray new arraysecarrayc3 sam secarrayc4 kamvar res firstarrayconcatsecarrayis this a known limitation whats the best way to achieve this,['javascript'] +24314,net when are attributes instantiated and can i get a reference to the type they are decorating two questions about attributeswhen are attribute classes instantiated when the type is first accessed or at the start of executionfrom within the attribute class can i find out for which type the attribute was instantiatedthe idea is that i want to make a list of all the classes in my assembly that have my attribute applied to it i could of course iterate through all of them with reflection and check but it would be nicer if the attribute could simply append to a global static list upon instantiation,['.net'] +24316,return an allocated variable i know we should free any variable allocated with malloc but what if i return it in a function something like thischar somefunctionint somearg char str strchar mallocsizeofchar some code return strshould i free str how could i do that,['c'] +24317,weblogic or jboss i am a long time java developer on jbossand tomcat in the last year i had to develop over weblogic and i have to say i really miss jboss since my experience with weblogic is pretty shallow i am asking the more experienced guys out there is there a reason for spending money on weblogic is not jboss giving you all that you need,['java'] +24329,can you prevent your aspnet application from shutting down i think i heard that aspnet applications will shut down after a while of being idle ie no visitorsis there a way to prevent this behavior from happening i have a timer that runs some code from the globalasaxcs application start event and want to make sure that it continues to run even when no visitors are hitting the sitethanks in advance,"['c#', 'asp.net']" +24334,calculating a sha hash with a string secret key in python amazon product api now requires a signature with every request which i am trying to generate ushing pythonthe step i get hung up on is this onecalculate an rfc 2104compliant hmac with the sha256 hash algorithm using the string above with our dummy secret access key 1234567890 for more information about this step see documentation and code samples for your programming language given a string and a secret key in this case 1234567890 how do i calculate this hash using python update the first solution using hmacnew looks correct however i am getting a different result than they areaccording to amazons example when you hash the secret key 1234567890 and the following stringgetwebservicesamazoncomoncaxmlawsaccesskeyid0itemid0679722769operationitemlookupresponsegroupitemattributes2coffers2cimages2creviewsserviceawsecommerceservicetimestamp20090101t123a003a00zversion20090106you should get the following signature naceu3az4ohn7tisqgs1vdlbhbeijwcbecql5xn9xgi am getting this 411a59403c9f58b4a434c9c6a14ef6e363acc1d1bb2c6faf9adc30e20898c83b,['python'] +24338,mapping a nested list with list comprehension in python i have the following code which i use to map a nested list in python to produce a list with the same structure nested list hello world goodbye world mapstrupper x for x in nested listhello world goodbye worldcan this be done with list comprehension alone without using the map function,['python'] +24342,json vs serialized array in database what are the advantages and thisadvantages of storing json data in mysql database vs serialized array,"['php', 'mysql']" +24366,generic function with a has property x constraint i have a thirdparty closed source application that exports a com interface which i am using in my cnet application through interop this com interface exports many objects that all show up as systemobject until i cast them to the appropriate interface type i want to assign an property of all of these objects thusforeach object x in bigcominterfacechickens x as chickenattribute valueforeach object x in bigcominterfaceducks x as duckattribute valuebut assigning the property is likely for applicationspecific reasons that are unavoidable to throw exceptions from which i want to recover so i really want a trycatch around each one thusforeach object x in bigcominterfacechickens try x as chickenattribute value catch exception ex handle foreach object x in bigcominterfaceducks try x as duckattribute value catch exception ex handle obviously it would be so much cleaner to do thisforeach object x in bigcominterfacechickens setattributechickenx as chicken valueforeach object x in bigcominterfaceducks setattributeduckx as duck valuevoid setattributett x systemobject value try xattribute value catch handle see the problem my x value can be of any type so the compiler cannot resolve attribute chicken and duck are not in any kind of inheritance tree and they do not share an interface that has attribute if they did i could put a constraint for that interface on t but since the class is closedsource that is not possible for mewhat i want in my fantasy is something like a constraint requiring the argument to have the attribute property regardless of whether it implements a given interface to witvoid setattributett x systemobject value where thaspropertyattributei am not sure what to do from here other than to cutpaste this little trycatch block for each of chicken duck cow sheep and so onmy question is what is a good workaround for this problem of wanting to invoke a specific property on an object when the interface that implements that property cannot be known at compile time,['c#'] +24370,view generated source after ajaxjavascript in c is there a way to view the generated source of a web page the code after all ajax calls and javascript dom manipulations have taken place from a c application without opening up a browser from the codeviewing the initial page using a webrequest or webclient object works ok but if the page makes extensive use of javascript to alter the dom on page load then these do not provide an accurate picture of the pagei have tried using selenium and watin ui testing frameworks and they work perfectly supplying the generated source as it appears after all javascript manipulations are completed unfortunately they do this by opening up an actual web browser which is very slow i have implemented a selenium server which offloads this work to another machine but there is still a substantial delayis there a net library that will load and parse a page like a browser and spit out the generated code clearly google and yahoo are not opening up browsers for every page they want to spider of course they may have more resources than me is there such a library or am i out of luck unless i am willing to thissect the source code of an open source browsersolutionwell thank you everyone for youre help i have a working solution that is about 10x faster then selenium woothanks to this old article from beansoftware i was able to use the systemwindowsformswebbrowser control to download the page and parse it then give em the generated source even though the control is in windowsforms you can still run it from aspnet which is what i am doing just remember to add systemwindowforms to your project referencesthere are two notable things about the code first the webbrowser control is called in a new thread this is because it must run on a single threaded apartmentsecond the generatedsource variable is set in two places this is not due to an intelligent design decision i am still working on it and will update this answer when i am done wb documentcompleted is called multiple times first when the initial html is downloaded then again when the first round of javascript completes unfortunately the site i am scraping has 3 different loading stages 1 load initial html 2 do first round of javascript dom manipulation 3 pause for half a second then do a second round of js dom manipulationfor some reason the second round is not cause by the wb documentcompleted function but it is always caught when wbreadystate complete so why not remove it from wb documentcompleted i am still not sure why it is not caught there and that is where the beadsoftware article recommended putting it i am going to keep looking into it i just wanted to publish this code so anyone whos interested can use it enjoyusing systemthreadingusing systemwindowsformspublic class webprocessor private string generatedsource get set private string url get set public string getgeneratedhtmlstring url url url thread t new threadnew threadstartwebbrowserthread tsetapartmentstateapartmentstatesta tstart tjoin return generatedsource private void webbrowserthread webbrowser wb new webbrowser wbnavigateurl wbdocumentcompleted new webbrowserdocumentcompletedeventhandler wb documentcompleted while wbreadystate webbrowserreadystatecomplete applicationdoevents added this line because the final html takes a while to show up generatedsource wbdocumentbodyinnerhtml wbthispose private void wb documentcompletedobject sender webbrowserdocumentcompletedeventargs e webbrowser wb webbrowsersender generatedsource wbdocumentbodyinnerhtml,"['c#', '.net']" +24383,is iphone os 64 bit or 32 bit anyone knows if iphone os is based on 32bit or 64bit architecture,['iphone'] +24387,transparency in pngs with reportlab 23 i have two pngs that i am trying to combine into a pdf using reportlab 23 on python 25 when i use canvasdrawimageimagereader to write either png onto the canvas and save the transparency comes out black if i use pil 116 to generate a new image then paste either png onto the pil image it composits just fine i have double checked in gimp and both images have working alpha channels and are being saved correctly i am not receiving an error and there does not seem to be anything my googlefu can turn up has anybody out there composited a transparent png onto a reportlab canvas with the transparency working properly thanks,['python'] +24409,php eval that evaluates html php i am messing around with templating and i have run into a situation where i need to echo to the browser a template that contains html php how do i evaluate the php and send it to the browserso heres an example mainphpdiv id containerdiv idheadphp if id 10 h3greater than 10h3php else h3less than 10h3php endif div divand then in the templatephp php contents contains mainphp in string format echo evalcontents does not work how do i do this line edit my template also allows you to inject data from the controller smartystyle would an output buffer allow me to do this and then evaluate my php the ideal is that it does a firstpass through the code and evaluates all the tags in first then runs the php this way i can create loops and stuff from using data sent from my controllerso maybe a more complete example div id container div id titletitlediv this adds data sent from a controller div idhead php if id 10 h3greater than 10h3 php else h3less than 10h3 php endif div divthanks,['php'] +24416,php function comments just a quick question i have seen that some php functions are commented at the top using a format that is unknown to me convert an object to an array param object object the object to convert return array my ide gives me a dropdown selection for the things such as param and return so it must be documented somewhere i have tried searching google but it would not include the symbol in its searchwhat is this format of commenting and where can i find some information on it,['php'] +24417,how can i add logic to an existing dependencyproperty callback i am trying to add a propertychangedcallback to uielementrendertransformoriginproperty an exception is thrown when i try to override the propertymetadata i have searched msdn and google and all i have been able to come up with is this dependencypropertydescriptoraddvaluechanged is suggested at some point in that post but that would not solve my problem since this is not a perinstance callback i do not understand what this exception means at all does anyone know what i am doing wrong public class foo frameworkelement private static void origin changed dependencyobject d dependencypropertychangedeventargs e static foo propertymetadata originalmetadata uielementrendertransformoriginpropertygetmetadata typeofframeworkelementan exception is thrown when this line is executed cannot change property metadata after it has been associated with a property originalmetadatapropertychangedcallback new propertychangedcallbackorigin changed uielementrendertransformoriginpropertyoverridemetadata typeoffoo originalmetadata,"['c#', '.net']" +24430,c amazon product advertising api as of august 15 amazon made it compulsory to sign all requests made to their product advertising api i thought i had got everything working just fine but when the 15th finally came around my web application stopped working and pretty much ever since i have been trying to find out how to sign the soap requestsamazon has an outdated sample code for signing requests that does not appear to work here basically i need to know how to add a signature to the my requests using the most current c soap api and net 35i hope i have given enough details if i have not please feel free to ask me to elaboratethank youthe loraxupdatei am using mvc and need to know how to add the signature to the the itemlookup or awsecommerceservice object is there an attribute that contains the signature value how does it get attached to the requeston this page they say that i must include the signature and timestamp parameters but the intellisense does now show any such attributes,['c#'] +24434,what is the oldest time that can be represented in python i have written a function comptime1 time2 which will return true when time1 is lesser than time2 i have a scenario where time1 should always be lesser than time2 i need time1 to have the least possible valuedate how to find this time and how to form the corresponding object,['python'] +24441,transaction mode for file operations in java perhaps what i am trying to explain here does not make any sense so i would like to apologize in advance anyway i will tryi am trying to read from a file perform some database operations and move the content to another file i was wondering if it is possible to perform all this operations in an atomic way in java so if anything goes wrong in the list of actions rollback the complete sequence and go back to the start pointthanks in advance for your help,['java'] +24450,propertyplaceholder location from another property i need to load some properties into a spring context from a location that i do not know until the program runs so i thought that if i had a propertyplaceholderconfigurer with no locations it would read in mylocation from the system properties and then i could use that location in a contextpropertyplaceholderlike thisbean classorgspringframeworkbeansfactoryconfigpropertyplaceholderconfigurer contextpropertyplaceholder locationmylocationbut this does not work and nor does locationclasspathmylocationpaul,['java'] +24455,where to tweak an eclipse to change the default settings used when creating a new workspace we use eclipse with projects in cvs it has proven to be the simplest to create a new workspace when having to deal with another branch or application and then use team import project set to get all the needed projects from cvsunfortunately i then have to do the following each and every timechange text font to consolas 11 ptthisable spell checking in text editorsrun everything in the backgroundplus some more of the samei would like to change the standard values once and for all in the eclipse thistribution files after having unzipped the thistribution windows where are these defaults located inside eclipseedit for now we just have a preference file which must be read in an extra step but worksedit 2014 i have ended up creating a workspace with the settings i want and then creating a new copy everytime i need a new one also handles maven central information etc accepted the oldest answer saying essentially this,['java'] +24470,how to pass parameters to php template rendered with include need your help with php templating i am new to php i am coming from perlembperl anyway my problem is simplei have a small template to render some item let it be a blog postthe only way i know to use this template is to use include directivei want to call this template inside a loop going thru all the relevant blog postsproblem i need to pass a parameters to this template in this case reference to array representing a blog postcode looks something like thisrows executeselect from blogs where datedate order by date descforeach rows as row print rendertemplatesblog entryphp rowfunction rendertemplate param ob start includetemplatehow to pass param to it it needs that row to render blog entry ret ob get contents ob end clean return retany ideas how to accomplish this i am really stumped is there any other way to render a template,['php'] +24471,print stylesheet one page prints and cuts off remaining text i am working on a printable list of events the printer prints one page fine but cuts off some of the text on the bottom then it print a second blank pagei have tried everything i know but am at a lossheres the link,['css'] +24491,retrieving the last record in each group there is a table messages that contains data as shown belowid name other columns1 a a data 12 a a data 23 a a data 34 b b data 15 b b data 26 c c data 1if i run a query select from messages group by name i will get the result as1 a a data 14 b b data 16 c c data 1what query will return the following result3 a a data 35 b b data 26 c c data 1that is the last record in each group should be returnedat present this is the query that i useselect from select from messages order by id desc as x group by namebut this looks highly inefficient any other ways to achieve the same result,"['sql', 'mysql']" +24492,defining a user with useridentityname in controller constructor for my actions that are going to interact with the users account i would like to create a theuser object in addition to adding that object to viewdatatheuser as soon as any action on my controller is calledif the user is logged in it will grab the users info from the database if not theuser object will just be nulli tried accessing useridentityname in the controller constructor but it is not created prior to any action being calledi was looking at custom authorization filters but those wouldnt allow me to create the theuser object and store it in the viewdatathis is a brief snippet of what i would like to accomplishauthorizepublic class homecontroller controller user theuser public homecontroller theuser useridentityisauthenticated userrepositorygetuseruseridentityname null viewdatatheuser theuser,['c#'] +24495,inconsistent date parsing using simpledateformat i am really scratching my head on this one i have been using simpledateformats with no troubles for a while but now using a simpledateformat to parse dates is only sometimes just plain wrongspecificallysimpledateformat sdf new simpledateformatymmdd hhmmssdate date sdfparse20090819 120systemoutprintdatetostringprints the string wed aug 19 0 edt 2009 what the heck it does not even parse into the wrong date all the timeupdate that fixed it beautifully wouldnt you know it that was misused in a few other places as well gotta love debugging other peoples code,['java'] +24497,is there any way to accept only numeric values in a jtextfield is there any way to accept only numeric values in a jtextfield is there any special method for this,['java'] +24509,c type conversion when passing an argument on a function call from the c programming language 2nd editionsince an argument of a function call is an expression type conversions also take place when arguments are passed to function in absence of a function prototype char and short become int and float becomes doubleby reading the text i am getting an impression that unless you explicitly specify the argument type by either using cast or function prototype function arguments will always be passed as either passed as int or doublein order to verify my assumption i compiled the following codeinclude stdiohmain unsigned char c z float number 314f function callc numbervoid function callchar c float fafter compilation i get the following warningstypeconversionc11 warning conflicting types for afunction callatypeconversionc7 warning previous implicit declaration of afunction calla was heremy guess is c and number were both converted to int and double on the function call and were then converted back to char and float is this what actually happened,['c'] +24517,how to setup iprincipal for a mockup i want to mockup iprincipal so i did thispublic mockiprincipal principal get set in my setup of my nunit principal new mockiprincipalso this should be all that i need in my nunit unit test but how about in my actual controller filelike how do i set it upfor example i have a membershipproviderso what i did was in my controller constructor i didprovider membershipproviderso then in my controller i just used providerwhatever i needi am not sure how to setup the principal thing in the same way,['asp.net'] +24520,jquery how to capture the tab keypress within a textbox i want to capture the tab keypress cancel the default action and call my own javascript function,"['javascript', 'jquery']" +24524,using java map for range searches i have a use case where if a number lies between 010 it should return 0 and if it lies between 1120 it should return 1 etc 0 03 0 and 3 are inclusive1 415 4 and 15 are inclusive2 1640 16 and 40 are inclusive3 4188 41 and 88 are inclusive5 89300 89 and 300 are inclusivei was thinking how could i implement and was thinking java maps but it does not allow range searching i am interested in something like this i have a functionint foo if foo returns 5 since it lies between 0 to 10 i would use 0 if foo return 25 it would use 2 any ideasedit actually the ranges are not as simple as 010 1120 i want to be able to do range searches sorry about the confusion based on the queries i have added the correct example the numbers are continous,['java'] +24557,how to implement url routing in php im a newcomer to know this concept help me i need to know how to implement url routing in php im a amateur php developer guide me any help would be greatly appreciated,['php'] +24563,having an image file buffer in memory what is the fastest way to create its thumbnail trying to create a an image acquiring application optimized for a fast scanner which can provide up to 6 compressed images colorgraybinaryfrontrear for each paper at speed of 150 ppm i have some speed issuesusing twain technology and memory buffer transfer mode twsx memory i receive image buffer as jpeg or tiff file loaded in memory from scanner and save it to my application destination pathif i do not want to create thumbnails my application causes no speed loss for the scanner but if i want to due the way i do it saving buffer into a file in my c twain handling dll notifying my net host application with destination file path using a function pointer opening the image file in c and creating the thumbnail image my application causes extreme speed loss to scanning speedi tried some optimizations such as performing loading phase in a separate thread and sending unmanaged image file buffer to net host and trying to load it in an unsafe context unmanagedmemorystream and creating thumbnail but it did not improve the speed significantly so my question is having an image file buffer in memory eg 24 bit jpeg compressed without embeded thumbnail is there a fast direct way to create a thumbnail image from it what do you suggest as fastest method for creating thumbnails in this case,['c++'] +24567,a c code generator from an xml spec i would like to know if there is a tool which allows you to do class definition based on an xml format i am not looking for data binding anyone can help thanks,['c++'] +24568,reading a remote file using java i am very new to java and have been struggling with it i am looking for an easy way to get files that are situated on a remote server for this i created a local ftp server on my windows xp and now i am trying to give my test applet the following addresstry uri new uriftplocalhostmytesttestmid file midifile new fileuricatch exception exand of course i receive the following erroruri scheme is not filei have been trying some other ways to get the file they do not seem to work any insight of how i should do it this should be straight forward should not it btw i am also keen to perform an http request,['java'] +24577,regular expression to check if a given password contains at least one number and one letter in c can anyone help me write a regular expression for checking if a password has at least one letter and one number in iti have a requirement that users passwords must be alphanumeric and i want to be able to check for that using a regular expression,"['c#', '.net']" +24579,when to use static modifier in php doing some code reviews lately i came across a number of classes that have significant number of static methods in them and i cannot seem to grasp why hence my questionwhat are the best practices regarding using static methods in phpwhen would one want to use them and when would one should not use themwhat are specific difference in how runtime handles static methods do they affect performance or memory footprint,['php'] +24584,jquery ajax load java script not executing i have read several posts about this issue but i cannot solve iti am loading an html file into a div the file i am loading contains a unordered listthis list should be expanded a menu with submenu items and closed therefore i need jsbut unfortunately this script is not loadedcan anyone help mewould be so great thanks a lot,"['javascript', 'jquery']" +24590,finding matching keys in two large dictionaries and doing it fast i am trying to find corresponding keys in two different dictionaries each has about 600k entriessay for example myrdp actinobacter gatcgatca subtilus sp atcgattact mynames actinobacter 8924342 i want to print out the value for actinobacter 8924342 since it matches a value in myrdpthe following code works but is very slow for key in myrdp for jey in mynames if key jey print key mynameskeyi have tried the following but it always results in a keyerror for key in myrdp print mynameskeyis there perhaps a function implemented in c for doing this i have googled around but nothing seems to workthanks,['python'] +24594,strip byte order mark from string in c i have read similar posts on this and they do not answer my questionin c i have a string that i am obtaining from webclientdownloadstring i have tried setting clientencoding to new utf8encodingfalse but that is made no difference i still end up with a byte order mark for utf8 at the beginning of the result string i need to remove this to parse the resulting xml with linq and want to do so in memoryso i have a string that starts with x00efx00bbx00bf and i want to remove that if it exists right now i am usingif xmlstartswithbyteordermarkutf8 xml xmlremove0 byteordermarkutf8lengthbut that just feels wrong i have tried all sorts of code with streams getbytes and encodings and nothing works can anyone provide the right algorithm to strip a bom from a stringthank you,['c#'] +24603,how do i resize the uitableviews height dynamically in my app i would like to resize the tableviews height when it is in edit mode vs when it is not in order to make room for editing controls below the table viewhow should this be done,['iphone'] +24614,creating datetime from date and time is there way in mysql to create datetime from a given attribute of type date and a given attribute of type time,['mysql'] +24615,how can i make a mysql sum query return zero instead of null if there are no records here is my select queryselect sumrating as this week from table name where unix timestampcreated at unix timestamp 604800which basically counts the rating of an item for the last week 604800 is a number of seconds in 1 weekthe problem is that when there are no rows in the table the this week will be returned as null i would like the query to return 0 in case there are no rows in the table how to do it,"['sql', 'mysql']" +24620,how to iterate over a treemap possible duplicatehow do i iterate over each entry in a map i want to iterate over a treemap and for all keys which have a particular value i want them to be added to a new treemap how can i do this,['java'] +24624,session login vs http authentication advantages thisadvantages i noticed a few big sites use http authentication im wondering what the main difference is between this and session based logins areany advantages or thisadvantagesany explanation and or suggestions would be helpful as i am trying to decide which login to use for my sitethanks,['php'] +24637,file formats supported by uiwebview what are all the file formats supported by uiwebviewin my testing i found that it supports xls doc ppt pdf but not xlsx and docx rtfit supports image files like jpg png gif bmp not sure about tiff orexactly what all types are supported is not clearthe uiwebview documentation also does not state it clearlycould someone please help,['iphone'] +24655,getting the class of a java generic and interface implementation of generics i would like to make a class that looks basically like thispublic class myclasst implements serializable void function class c tclass two errors i cannot call tclass even though i can do that with any other object type i cannot enforce that t implements serializable in this wayhow do i solve my two generics problemscheersnik,['java'] +24669,how to extend thistutils with a simple post install script i need to run a simple script after the modules and programs have been installedi am having a little trouble finding straightforward documentation on how to do this it looks like i need to inherit from thistutilscommandinstall override some methods and add this object to the setup script the specifics are a bit hazy though and it seems like a lot of effort for such a simple hook does anyone know an easy way to do this,['python'] +24677,waiting for a timer to finish in java i am using javautiltimer to schedule a periodic task at one point i would like to shut it down and wait for it to finishtimercancel will prevent any future tasks from running how do i make sure any tasks are not running at the moment or wait for them if they arei can introduce external synchronization mechanisms but i do not see how they can cover all cases for example if i synchronize on some monitor within the task i still miss the case when the task just started executing but did not take the monitorwhat is the recommended practice for waiting until all tasks are really done including currently running tasks,['java'] +24687,how to efficiently parse concatenated xml documents from a file i have a file that consists of concatenated valid xml documents i would like to separate individual xml documents efficientlycontents of the concatenated file will look like this thus the concatenated file is not itself a valid xml document xml version10 encodingutf8somedatasomedataxml version10 encodingutf8somedatasomedataxml version10 encodingutf8somedatasomedataeach individual xml document around 14 kb but there is potentially a few hundred of them all xml documents correspond to same xml schemaany suggestions or tools i am working in the java environmentedit i am not sure if the xmldeclaration will be present in documents or notedit let us assume that the encoding for all the xml docs is utf8,['java'] +24688,using send file to a remote source ruby on rails in my app i have a requirement that is stumping mei have a file stored in s3 and when a user clicks on a link in my app i log in the db they have clicked the link decrease their download credit allowance by one and then i want to prompt the file for downloadi do not simply want to redirect the user to the file because it is stored in s3 and i do not want them to have the link of the source file so that i can maintain integrity and accessit looks like send file wont work with a remote source file anyone recommend a gem or suitable code which will do this,['ruby-on-rails'] +24694,is it a good idea to prefer nsnumberformatterbehavior10 4 over nsnumberformatterbehaviordefault i wonder if it would be more secure to rely on a nsnumberformatterbehavior10 4 instead of default because default may change arbitrary some day in future and suddenly the app looks ugly or am i wrong with that,"['iphone', 'objective-c']" +24699,gotchas where numpy differs from straight python folksis there a collection of gotchas where numpy differs from pythonpoints that have puzzled and cost time the horror of that moment i shall never never forget you will though the queen said if you do not make a memorandum of itfor example nans are always trouble anywhereif you can explain this without running it give yourself a point from numpy import array nan isnanpynan floatnanprint pynan is pynan pynan is nan nan is nana 0 pynanprint a a1 is pynan anyaa is pynan for aa in aa array 0 nan print a a1 is nan isnan a1 i am not knocking numpy lots of good work there just think a faq or wiki of gotchas would be usefuledit i was hoping to collect half a dozen gotchas surprises for people learning numpythen if there are common gotchas or better common explanationswe could talk about adding them to a community wiki where it does not look like we have enough so far,['python'] +24706,read xml file using http is anyone aware of a quick way of reading in an xml file over httpeg i have a file located in how can i read this file from a java appall help is greatly appreciatedthanksdamien,['java'] +24713,confusion between dtos linq2sql and class objects i have been successfully working with linq2sql and the linq dtos the classes that are created by linq2sql i am confused i have the task of updating an old application and i can see that my dtos will be used how they should be to transport datei am using the repository pattern so i am passing data from the repository to the service via the linq2sql dtos once i am in the service layer this is basically my business logic then i need to pass around class objects these class objects are basicaly a mirror image more or less of the dtos there are some changes in some place but generally the sameso getting back to the question in hand is this good practice to use dtos only to transport data from repository to service layer and once in the service layerbusiness logic i should but mapping all my dtos to there class object counter parts of course using automappermy other alternative is to continue to use the dtos like class objects and pass them around from method to method and as return types etc but i feel this is bad practice and i keep going round in circles wondering which method i should applyany help really appreciatedthanks,['c#'] +24719,has key or in i wonder what is better to dod a 1 b 2a in dtrueord a 1 b 2dhas keyatrue,['python'] +24720,how do i tell which tab you are moving fromto in a winforms tab control i need to determine which tab the user is coming from and going to when they switch tabs and possibly cancel the switch i have tried the deselecting deselected selecting selected events and all of them show the etabpageindex to be the same as the senderselectedindexis there an event or property that i can use so that i can determine both sides of this or do i have to hack something together with caching it from one event and using that value in the new eventi am trying to avoid handling the deselectingdeselected events and caching the value to use in the selecting event i already know i can do this so i am asking if there is a cleaner way without doing thisi have tried in both c and vb with the same results no surprisethanks,"['c#', '.net']" +24721,linq and a natural sort order whats the easiest way to get a linq query from an sql database does that matter to order strings naturallyfor example i am currently getting these resultsproject 1project 10project 2what i would like is to see is thisproject 1project 2project 10the query i am using is thisreturn from p in datacontextprojects orderby pname select p,['c#'] +24743,can an stl map iterator go out of bounds through incrementing for associative containers can the operator send an iterator past the end of a collectionexamplemapuint32 uint32 new mapnew map0 0new map1 1mapuint32 uint32 new iter new mapbeginnew iternew iternew iternew iternew iternew iternew iterat the end of this does new iter new mapend or does it end up in the great unknownnote i know this is messed up and not the way to do things i am working around some wtf corporate code,['c++'] +24755,how to send a string via postmessage inside my app i want to send a message to a dialog from a different threadi want to pass an stdexception derived class reference to the dialog something like thistry do stuffcatch myexception the exception postmessagemyhwnd cwm some error 0 0 send the exception or the exceptionerror string herei want to receive the message in my dialog and show the error that is in the exceptionerror stringlparam cmydlgsomeerrorwparam lparam show error return 0passing the stdstring the exceptionerror string using postmessage would also be ok i guess,['c++'] +24756,c reflection base class static fields in derived type in c when i am reflecting over a derived type how come i do not see base classes static fieldsi have tried both typegetfieldsbindingflagsstatic and typegetfields,['c#'] +24768,date and time helper for php like jodatime in java i am looking for a library open source like jodatime in the java world is there any library like thatjodatime is very helpful to calculate date and time i can add days weeks month year and also can converting date and time easilyi wish there is library like jodatime for phpedit i need some functions that available in jodatime like daysbetween to calculate number of days between 2 date monthsbetween and weeksbetween some functions about add and substract date is available from php itself,"['java', 'php']" +24776,avoid instantiating a class in java recently i have faced a question how to avoid instantiating a java classhowever i answered by sayingif you do not want to instantiate a class use abstract modifier ex javaxservlethttpservlet is declared as abstractthough none of its methods are abstract to avoid instantiationdeclare a no argument private constructornow my question is a are there any other waysb why does any one do not want to instantiate a class after searching in so i got to know from this that util classes can be made not to instantiate any other places where we do not want to instantiate a class in oop,['java'] +24777,zend framework how to set headers i have a question how can i do something like thisheadercontentthisposition inline filenameresultpdf headercontenttype applicationxpdfwith zend framework i have tried thisgetresponse setheadercontentthispositioninline filenameresultpdfsetheadercontenttype applicationxpdfbut does not work correctlybest regards,['php'] +24784,how can i thisable a browser or element scrollbar but still allow scrolling with wheel or arrow keys i want to hide any scrollbars from my div elements and my whole body but still let the user scroll with the mouse wheel or arrow keys how can this be achieved with raw javascript or jquery any ideas,"['javascript', 'jquery', 'css']" +24790,is it possible to detect animated gif images client side is it possible to detect animated gif images client side in internet explorer you can use the onload event for this since it wil be fired for every frame loaded behaviour changed in ie8 but is there a way for other browsers too,['javascript'] +24791,how to detect out of memory condition i have an application running on websphere application server 60 and it crashes nearly every day because of outofmemory from verbose gc is certain there are the memory leaksmany of them unfortunately the application is provided by external vendor and getting things fixed is slow painful process as part of the process i need to gather the logs and heapdumps each time the oom occursnow i am looking for some way how to automate it fundamental problem is how to detect oom condition one way would be to create shell script which will periodically search for new heapdumps this approach seems me a kinda dirty another approach might be to leverage the jmx somehow but i have little or no experience in this area and do not have much idea how to do itor is in was some kind of triggerhooks for this thank you very much for every advice,['java'] +24797,oracle delete query taking too much time i have a query likedelete from tablename where colname valuewhich takes awfully long time to executewhat could be the reason i have an index on colname,['sql'] +24816,split argb into byte values i have a argb value stored as an int type it was stored by calling toargbi now want the byte values of the individual color channels from the int valuefor exampleint mycolor 16748byte rgbagetbytesfromcolormycolorout a out r out g out bhow would you implement getbytesfromcolorto give the context i am passing a color value persisted in db as int to a silverlight application which needs the individual byte values to construct a color object systemwindowsmediacolorfromargbbyte a byte r byte g byte b,['c#'] +24838,pythonsuds type not found xscomplextype i have the following simple python test script that uses suds to call a soap web service the service is written in aspnetfrom sudsclient import clienturl client client url result clientservicegetpackagedetails mypackage print resultwhen i run this test script i am getting the following error used code markup as it does not wrapno handlers could be found for logger sudsbindingsunmarshallertraceback most recent call last file sudstestpy line 9 in module result clientservicegetpackagedetails t3db file buildbthistcygwin1525i686eggsudsclientpy line 240 in call file buildbthistcygwin1525i686eggsudsclientpy line 379 in call file buildbthistcygwin1525i686eggsudsclientpy line 240 in call file buildbthistcygwin1525i686eggsudsclientpy line 422 in call file buildbthistcygwin1525i686eggsudsclientpy line 480 in invoke file buildbthistcygwin1525i686eggsudsclientpy line 505 in send file buildbthistcygwin1525i686eggsudsclientpy line 537 in succeeded file buildbthistcygwin1525i686eggsudsbindingsbindingpy line 149 in get reply file buildbthistcygwin1525i686eggsudsbindingsunmarshallerpy line 303 in process file buildbthistcygwin1525i686eggsudsbindingsunmarshallerpy line 88 in process file buildbthistcygwin1525i686eggsudsbindingsunmarshallerpy line 104 in append file buildbthistcygwin1525i686eggsudsbindingsunmarshallerpy line 181 in append children file buildbthistcygwin1525i686eggsudsbindingsunmarshallerpy line 104 in append file buildbthistcygwin1525i686eggsudsbindingsunmarshallerpy line 181 in append children file buildbthistcygwin1525i686eggsudsbindingsunmarshallerpy line 104 in append file buildbthistcygwin1525i686eggsudsbindingsunmarshallerpy line 181 in append children file buildbthistcygwin1525i686eggsudsbindingsunmarshallerpy line 102 in append file buildbthistcygwin1525i686eggsudsbindingsunmarshallerpy line 324 in startsudstypenotfound type not found xscomplextypelooking at the source for the wsdl files header reformatted to fitxml version10 encodingutf8 wsdldefinitions xmlnshttp xmlnssoap xmlnss xmlnssoapenc xmlnstnshttphttpsomeinternalurlwebservicesasmx xmlnstm xmlnsmime targetnamespace xmlnswsdli am guessing based on the last line of outputsudstypenotfound type not found xscomplextypethat i need to use suds doctor class to fix the schema but being a soap newbie i do not know what exactly needs fixed in my case does anyone here have any experience using suds to fixcorrect schema,['python'] +24860,net event every minute on the minute is a timer the best option i want to do stuff every minute on the minute by the clock in a windows forms app using c i am just wondering whats the best way to go about it i could use a timer and set its interval to 60 but to get it to run on the minute i would have to enable it on the minute precisely not really viablei could use a timer and set its interval to 10 then within its tick event i could check the clocks current minute against a variable that i set if the minute has changed then run my code this worries me because i am making my computer do a check every 1 second in order to carry out work every 1 minutes surely this is ugly i am using windows forms and net 20 so do not want to use the thispatchtimer that comes with net 35 this must be a fairly common problem have any of you a better way to do this,['c#'] +24874,c compare char array with string i am trying to compare a character array against a string like soconst char var1 var1 getenvmyenvvarifvar1 dev do stuffthis if statement never validates as true when i output var1 it is dev i was thinking maybe it has something to do with a null terminated string but the strlen of dev and var1 are equal i also thought maybe var1 dev was comparing dev against the memory location of var1 instead of the value var1 dev results in an error tried many things probably a simple solution for the saavy c developer i havent coded c in a long timeeditweve triedifstrcmpvar1 dev 0and ifstrncmpvar1 dev 3 0thanksedit after testing at home i am just going to suggest my coworker changes the datatype to a string i believe he was comparing a char array of a large size against a string i put together a program that outputs sizeof strlen etc to help us work through it thanks to everyone for the help,['c++'] +24876,when to use volatile or threadmemorybarrier in threadsafe locking code c when should i use volatilethreadmemorybarrier for thread safety,"['c#', '.net']" +24888,c trythrowcatch machine code mentally i have always wondered how trythrowcatch looks behind the scenes when the c compiles translates it to assembler but since i never use it i never got around to checking it out some people would say lazyis the normal stack used for keeping track of trys or is a separate perthread stack kept for this purpose alone is the implementation between msvc and g big or small please show me some pseudo asm ia32 is ok too so i never have to check it out myself edit now i get the basics of msvcs implementation on ia32 handling anybody know for g on ia32 or any other cpu for that matter,['c++'] +24905,selecting qcombobox in qtablewidget one cell in each row of a qtablewidget contains a comboboxfor each row in table qcombobox combo new qcombobox tablesetcellwidgetrowcolcombo combosetcurrentindexnodetype connectcombo signalcurrentindexchangedintthis slotchangedint in the handler function changedint index i have qcombobox comboqcomboboxtablecellwidget row col combocurrentindexto get back a copy of the combobox and get the new selectionbut i cannot get the rowcolnone of the table cellx signals is emitted when an embedded item is selected or changed and currentrowcurrentcolumn are not set,['c++'] +24913,how can request validation be thisabled for httphandlers is it possible to thisable request validation for httphandlersa bit of background i have got an aspnet web application using an httphandler to receive the payment response from worldpay the iis logs show that the handler is being called correctly from worldpay but the code inside the handler is never calledif i create a physical aspx page and set validaterequestfalse in the header and put the same code in the page load method the code is called without any problemsthis solves the problem though i would prefer to stick with using an httphandler for this as it is better suited for this type of functionality rather than having an empty aspx page though this is dependent on being able to thisable request validationthe web application is using aspnet 20 and the server is iis6,['asp.net'] +24915,how to change fromaddress when using gmail smtp server i want to send an email from a to bwith header and content through gmailhow to do that by phpi have specified the frombut when i receive the emailit is still from my gmail accountmailfrom mailfromname mailermailaddaddress josh adams name is optionalmailaddreplyto informationhow do i change the from part,['php'] +24930,how to change the language of google news regarding the gsnewsbar object ajax api the following deals with gsnewsbar object of the goolgeajax search api which is explained herethere are some parameters which allow to change the layout of the news but there is no example of how to set the news languagecurrently i always get news in english but my aim is to provide the user a selectbox which provides different languages endeitnles which objectmethod should be used to change the language before requesting news,['javascript'] +24935,submitting form programmatically im trying to submit a specific form programatically but i allways get the initial page backi must be doing something wrong or missing something hereim sending the session cookie and some post data like viewstate that i parse from the initial request and sessionid this is the value i change in the form toget data from other years but in the second request i allways get data for session 899 instead of the one i request 875here is the code used any help is greatly apreciatedretrieveedmindexforsession875 protected string retrieveedmindexforsessionint sessionid cookiecontainer cookies httpwebrequest orequest httpwebresponse oresponse stream sw streamreader sr string pagedatastring pathremote download the index page so we can get cookies and viewstate from it orequest httpwebrequestwebrequestcreatepathremote orequestmethod get orequestallowautoredirect true orequestcookiecontainer new cookiecontainer orequestaccept texthtmlapplicationxhtmlxmlapplicationxmlq09q08 orequestreferer oresponse httpwebresponse orequestgetresponse sr new streamreaderoresponsegetresponsestream pagedata srreadtoend extract view state from pagedata string viewstate thisextractviewstatepagedata lets submit the form with the parameters we want orequest httpwebrequestwebrequestcreatepathremote orequestmethod post orequestallowautoredirect true orequestcontenttype applicationxwformurlencoded orequestcookiecontainer new cookiecontainer orequestcookiecontaineraddoresponsecookies orequestaccept texthtmlapplicationxhtmlxmlapplicationxmlq09q08 orequestreferer string postdata eventtarget eventargument viewstate viewstate menuctrl3addlsession sessionid menuctrl3a gotox57 menuctrl3a gotoy14ddlstatus1ddlsortedby1 byte buffer encodingutf8getbytespostdata orequestcontentlength bufferlength send post data into request stream first sw orequestgetrequeststream swwritebuffer 0 bufferlength swflush swclose connect send and get response oresponse httpwebresponseorequestgetresponse sr new streamreaderoresponsegetresponsestream onlogupdated1 rnstatus code oresponsestatuscode onlogupdated1 rnserver oresponseserver pagedata srreadtoend string result getsessionidpagedata onlogupdated1 rnrestuls result onlogupdated1 rnpage pagedata return pagedataprivate string extractviewstatestring str string viewstate string pattern viewstate valueval match match regexmatchstr pattern if matchsuccess viewstate matchgroupsvalvalue viewstate httputilityurlencodeunicodeviewstate return viewstateprotected string getsessionidstring str string sessionid stringempty str strtrim string pattern session match match regexmatchstr pattern regexoptionsignorecase if matchsuccess sessionid matchgroups1tostring return sessionidthis is the raw request being sent by the net scriptpost edmiedmlistaspx http11 contenttype applicationxwformurlencoded accept texthtmlapplicationxhtmlxmlapplicationxmlq09q08 referer useragent net framework client host edmiparliamentuk cookie aspnet sessionidk55fqarvx2oszp2wxhtrol45 contentlength 2431 expect 100continue eventtarget eventargument viewstateddwxmdgynzixndq2o3q8o2w8atwzpjs2bo2w8ddw7bdxppde2bo2k8mz47atw1pjtppdexpjs2bo2w8ddw7bdxppdezpjtppde3pjs2bo2w8ddx0pha8cdxsperhdgfwywx1zuzpzwxko0rhdgfuzxh0rmllbgq7pjtspfnfu1njt05jrdtjvevnx1zbtfvfoz42boz47ddxppdiwpjtapda4lta5oza3lta4oza2lta3oza1lta2oza0lta1ozazlta0ozayltazozaxltayozawltaxozk5ltawozk4ltk5ozk3ltk4ozk2ltk3ozk1ltk2ozk0ltk1ozkzltk0ozkyltkzozkxltkyozkwltkxozg5ltkwoz47qdw4otk7odkxozg4nts4nzu7odczozy4mjs2ode7njgwozy3ots3mdm7nzayozcwmts3mda7njk5ozy5ods2otc7njk2ozy5nts2otq7njkzoz42boz47oz47ddxwpgw8vgv4dds2bo2w8tglzdcbpzibfyxjsesbeyxkgtw90aw9uczs2bpjs7pjs2bpjt0pdtspgk8mt47atwzpjs2bo2w8ddx0pds7bdxppda2boz42bozs2bo3q8ddw7o2w8atwwpjs2bpjs7pjs2bpjt0pdtspgk8mt47atwzpjs2bo2w8ddw7bdxppde2bo2k8mz47atw1pjtppdc2boz47bdx0pha8cdxspenvbw1hbmrbcmd1bwvuddtdc3ndbgfzcztfbmfibgvko18hu0i7pjtspda7ugfnzuzpcnn0rglzywjszwq7bzxmpjtppdi2boz42boz47oz47ddxwpha8bdxdb21tyw5kqxjndw1lbnq7q3nzq2xhc3m7rw5hymxlzdtfivncoz47bdwtmttqywdluhjldkrpc2fibgvko288zj47atwypjs2bpjs2bozs2bo3q8cdxwpgw8q29tbwfuzefyz3vtzw50o0nzc0nsyxnzo18hu0i7pjtspde7ugfnzu5lehrfbmfibgvko2k8mj47pj47pjs7pjt0pha8cdxspenvbw1hbmrbcmd1bwvuddtdc3ndbgfzcztfivncoz47bdw0mjtqywdltgfzdevuywjszwq7atwypjs2bpjs2bozs2boz42bo3q8o2w8atwxpjtppdm2bo2k8nt47atw3pjs2bo2w8ddxwpha8bdxuzxh0oz47bdwymta5oz42boz47oz47ddxwpha8bdxuzxh0oz47bdxfre1zigfuzcbwvuzg1lbnrzoz42boz47oz47ddxwpha8bdxuzxh0oz47bdwxoz42boz47oz47ddxwpha8bdxuzxh0oz47bdw1mds2bpjs2bozs2boz42boz42bo3q8o2w8atwxpjtppdm2boz47bdx0pdtspgk8mt47atwzpjtppdu2bo2k8nz47pjtsphq8cdxwpgw8q29tbwfuzefyz3vtzw50o0nzc0nsyxnzo0vuywjszwq7xyftqjs2bo2w8mdtqywdlrmlyc3reaxnhymxlzdtvpgy2bo2k8mj47pj47pjs7pjt0pha8cdxspenvbw1hbmrbcmd1bwvuddtdc3ndbgfzcztfbmfibgvko18hu0i7pjtspc0xo1bhz2vqcmv2rglzywjszwq7bzxmpjtppdi2boz42boz47oz47ddxwpha8bdxdb21tyw5kqxjndw1lbnq7q3nzq2xhc3m7xyftqjs2bo2w8mttqywdltmv4devuywjszwq7atwypjs2bpjs2bozs2bo3q8cdxwpgw8q29tbwfuzefyz3vtzw50o0nzc0nsyxnzo18hu0i7pjtspdqyo1bhz2vmyxn0rw5hymxlzdtppdi2boz42boz47oz47pj47ddxwpha8bdxwaxnpymxloz47bdxvpgy2boz42boz47bdxppde2bo2k8mz47atw1pjtppdc2boz47bdx0pha8cdxspfrlehq7pjtspdixmdk7pj47pjs7pjt0pha8cdxspfrlehq7pjtspevetxmgyw5kieftzw5kbwvudhm7pj47pjs7pjt0pha8cdxspfrlehq7pjtspde7pj47pjs7pjt0pha8cdxspfrlehq7pjtspduwoz42boz47oz47pj47pj47pj47pj47bdxftwvudun0cmw6x0dvvg87pj5nhcfbpbnznuwxs7syldue2omkjw3d3d menuctrl3addlsession875 menuctrl3a gotox57 menuctrl3a gotoy14ddlstatus1ddlsortedby1this is the raw request sent by iepost edmiedmlistaspx http11 accept imagegif imagejpeg imagepjpeg imagepjpeg applicationxshockwaveflash applicationxamlxml applicationvndmsxpsdocument applicationxmsxbap applicationxmsapplication applicationvndmsexcel applicationvndmspowerpoint applicationmsword referer acceptlanguage engb useragent mozilla40 compatible msie 80 windows nt 51 trident40 net clr 114322 net clr 2050727 net clr 300450630 infopath1 net clr 3004506648 officeliveconnector13 officelivepatch00 net clr 3045062152 net clr 3530729 contenttype applicationxwformurlencoded acceptencoding gzip deflate host edmiparliamentuk contentlength 2431 connection keepalive pragma nocache cookie wt fpcid8321799254236424249630021299lv1249572414567ss1249572414567 aspnet sessionidvwxgo4rlex1j5m55l0bivrqo eventtarget eventargument viewstateddwxmdgynzixndq2o3q8o2w8atwzpjs2bo2w8ddw7bdxppde2bo2k8mz47atw1pjtppdexpjs2bo2w8ddw7bdxppdezpjtppde3pjs2bo2w8ddx0pha8cdxsperhdgfwywx1zuzpzwxko0rhdgfuzxh0rmllbgq7pjtspfnfu1njt05jrdtjvevnx1zbtfvfoz42boz47ddxppdiwpjtapda4lta5oza3lta4oza2lta3oza1lta2oza0lta1ozazlta0ozayltazozaxltayozawltaxozk5ltawozk4ltk5ozk3ltk4ozk2ltk3ozk1ltk2ozk0ltk1ozkzltk0ozkyltkzozkxltkyozkwltkxozg5ltkwoz47qdw4otk7odkxozg4nts4nzu7odczozy4mjs2ode7njgwozy3ots3mdm7nzayozcwmts3mda7njk5ozy5ods2otc7njk2ozy5nts2otq7njkzoz42boz47oz47ddxwpgw8vgv4dds2bo2w8tglzdcbpzibfyxjsesbeyxkgtw90aw9uczs2bpjs7pjs2bpjt0pdtspgk8mt47atwzpjs2bo2w8ddx0pds7bdxppda2boz42bozs2bo3q8ddw7o2w8atwwpjs2bpjs7pjs2bpjt0pdtspgk8mt47atwzpjs2bo2w8ddw7bdxppde2bo2k8mz47atw1pjtppdc2boz47bdx0pha8cdxspenvbw1hbmrbcmd1bwvuddtdc3ndbgfzcztfbmfibgvko18hu0i7pjtspda7ugfnzuzpcnn0rglzywjszwq7bzxmpjtppdi2boz42boz47oz47ddxwpha8bdxdb21tyw5kqxjndw1lbnq7q3nzq2xhc3m7rw5hymxlzdtfivncoz47bdwtmttqywdluhjldkrpc2fibgvko288zj47atwypjs2bpjs2bozs2bo3q8cdxwpgw8q29tbwfuzefyz3vtzw50o0nzc0nsyxnzo18hu0i7pjtspde7ugfnzu5lehrfbmfibgvko2k8mj47pj47pjs7pjt0pha8cdxspenvbw1hbmrbcmd1bwvuddtdc3ndbgfzcztfivncoz47bdw0mjtqywdltgfzdevuywjszwq7atwypjs2bpjs2bozs2boz42bo3q8o2w8atwxpjtppdm2bo2k8nt47atw3pjs2bo2w8ddxwpha8bdxuzxh0oz47bdwymta5oz42boz47oz47ddxwpha8bdxuzxh0oz47bdxfre1zigfuzcbwvuzg1lbnrzoz42boz47oz47ddxwpha8bdxuzxh0oz47bdwxoz42boz47oz47ddxwpha8bdxuzxh0oz47bdw1mds2bpjs2bozs2boz42boz42bo3q8o2w8atwxpjtppdm2boz47bdx0pdtspgk8mt47atwzpjtppdu2bo2k8nz47pjtsphq8cdxwpgw8q29tbwfuzefyz3vtzw50o0nzc0nsyxnzo0vuywjszwq7xyftqjs2bo2w8mdtqywdlrmlyc3reaxnhymxlzdtvpgy2bo2k8mj47pj47pjs7pjt0pha8cdxspenvbw1hbmrbcmd1bwvuddtdc3ndbgfzcztfbmfibgvko18hu0i7pjtspc0xo1bhz2vqcmv2rglzywjszwq7bzxmpjtppdi2boz42boz47oz47ddxwpha8bdxdb21tyw5kqxjndw1lbnq7q3nzq2xhc3m7xyftqjs2bo2w8mttqywdltmv4devuywjszwq7atwypjs2bpjs2bozs2bo3q8cdxwpgw8q29tbwfuzefyz3vtzw50o0nzc0nsyxnzo18hu0i7pjtspdqyo1bhz2vmyxn0rw5hymxlzdtppdi2boz42boz47oz47pj47ddxwpha8bdxwaxnpymxloz47bdxvpgy2boz42boz47bdxppde2bo2k8mz47atw1pjtppdc2boz47bdx0pha8cdxspfrlehq7pjtspdixmdk7pj47pjs7pjt0pha8cdxspfrlehq7pjtspevetxmgyw5kieftzw5kbwvudhm7pj47pjs7pjt0pha8cdxspfrlehq7pjtspde7pj47pjs7pjt0pha8cdxspfrlehq7pjtspduwoz42boz47oz47pj47pj47pj47pj47bdxftwvudun0cmw6x0dvvg87pj5nhcfbpbnznuwxs7syldue2omkjw3d3d menuctrl3addlsession885ddlstatus0ddlsortedby1 menuctrl3a gotox37 menuctrl3a gotoy12the ie header seems to have an extra cookiewt fpcid8321799254236424249630021299lv1249572414567ss1249572414567 witch appers to track visitors using cookies via the webtrends cookie plugin both post requests return http status code 302 and redirect to a get request that returns status 200any ideas,['c#'] +24940,negating a set of words via java regex i would like to negate a set of words using java regexsay i want to negate cvs svn nvs mvc i wrote a regex which is svncvsnvsmvcsome how that seems not to be working,['java'] +24947,how to edit a pdf in objectivec i am writing an application in objectivec using cocoa i have a pdf template i need to substitute actual values into placeholders in pdf and then save the result into new pdfhow can i do it which library should i use,['objective-c'] +24948,ruby scope of data after end i am using this ruby trick with end and data to put some data inside my program fileclass foo def initialize puts datareadinspect endendputs datareadinspectfoonew end testthis generates the following outputtesti had assumed data would be the same globally but inside the class it has no content how would i get access to the data after end inside a class apart from the obvious and ugly solution using global variablesadded i see how reading data twice gives me nothing the second time i could use rewind to get back to the start but read then gives me the entire source code of my program is there an easier way to get to just the part after end on subsequent uses of data or would i be better of reading it once and storing it somewhere else for future use,['ruby'] +24951,usual functions vs function variables in javascript is there any difference between function myfunc codeandvar myfunc function codein javascript,['javascript'] +24953,delete none values from python dict newbie to python so this may seem sillyi have two dictsdefault a alpha b beta g gammauser a newalpha b nonei need to update my defaults with the values that exist in user but only for those that have a value not equal to none so i need to get back a new dictresult a newalpha b beta g gamma,['python'] +24966,combining javascript objects into one i have a function called colorbox jquery plugin that takes a number of parameters like sothiscolorbox width 500px height 500pxi have several different types of this though each with their own properties like sovar type video width 500px height 500px gallery width 1065px height 600px beyond that i have other behaviors logic and a default group of settings which get overwritten by more specific ones what i am trying to do is push all the appropriate settings from multiple objects into a single object so i can just callthiscolorboxsettingshow would i transfer an unknown group of properties and their values for example width and height from something like typevideo into settings the goal is to be able to call settingsheight and get back the value i pushed in,"['javascript', 'jquery']" +24976,is the memory of a character array freed by going out of scope very much related to my previous question but i found this to be a separate issue and am unable to find a solid answer to thisis the memory used by a character array freed by going out of scopean examplevoid method1 char str10 manipulate strso after the method1 call is the memory used by str 10 bytes freed or do i need to explicitly call free on this as wellmy intuition tells me this is just a simple array of primitive types so it is automatically freed i am in doubt because in c you cannot assume anything to be automatically freed,['c'] +24995,how do i merge two arrays to create one array in javascript imagine i have got two arrays in javascriptvar geoff one twovar degeoff three fourhow do i merge the two arrays resulting in an array like thisvar geoffdegeoff one two three four,['javascript'] +25005,positioning mkmapview to show multiple annotations at once i have got several annotations i want to add to my mkmapview it could 0n items where and is generally around 5 i can add the annotations fine but i want to resize the map to fit all annotations onscreen at once and i am not sure how to do thisi have been looking at regionthatfits but i am not quite sure what to do with it i will post some code to show what i have got so far i think this should be a generally straightforward task but i am feeling a bit overwhelmed with mapkit so far voidlocationmanagercllocationmanager manager didupdatetolocationcllocation newlocation fromlocationcllocation oldlocationlocation newlocationcoordinateone location is obtained just zoom to that locationmkcoordinateregion regionregioncenter locationset zoom level using spanmkcoordinatespan spanspanlatitudedelta 0015spanlongitudedelta 0015regionspan span set the region here but i want this to be a dynamic size obviously this should be set after i have added my annotationsmapview setregionregion animatedyes test data using these as annotations for nownsarray arr nsarray arraywithobjectsone two three four nilfloat ex 001for nsstring s in arr jbannotation placemark jbannotation alloc initwithlatlocationlatitude ex lonlocationlongitudemapview addannotationplacemarkex ex 05 what do i do here mapview setregionmapview regionthatfitsregion animatedyesnotice this all happens as i receive a location update i do not know if that is an appropriate place to do this if not where would be a better place viewdidloadthanks in advance,"['iphone', 'objective-c']" +25008,css only horizontal overflow is it possible to achieve only horizontal overflow in css 21overflow autowill cause a block element to have both horizontal and vertical scrollbars i want a block element let us say div which will thisplay only horizontal scrollbars how do i do that,"['html', 'css']" +25015,strategic eager loading for manytomany relations in datamapper i am using datamapper an open source orm for ruby and i have in itch i would like to scratch at the moment datamapper can use strategic eager loadingsel for onetomany relationships but not manytomany where n1 queries occur i would like to hack around with making this work correctly but i cannot find where to do it so two part questionhow to i run the test suite so it will show this to be failing nb right now all the specs that should be failing are marked as pendingwhere and how is sel implemented for onetomany relationships,['ruby'] +25018,how do you specify a java fileencoding value consistent with the underlying windows code page i have a java application that receives data over a socket using an inputstreamreader it reports cp1252 from its getencoding method javanet socket sock inputstreamreader is new inputstreamreadersockgetinputstreamsystemoutprintlncharacter encoding isgetencoding prints character encoding cp1252that does not necessarily match what the system reports as its code page for examplecchcpactive code page 850the application may receive byte 0x81 which in code page 850 represents the character a14 the program interprets that byte with code page 1252 which does not define any character at that value so i get a question mark insteadi was able to work around this problem for one customer who used code page 850 by adding another commandline option in the batch file that launches the applicationjavaexe dfileencodingcp850 but not all my customers use code page 850 of course how can i get java to use a code page that is compatible with the underlying windows system my preference would be something i could just put in the batch file leaving the java code untouchedencjavaexe dfileencodingenc,['java'] +25022,modify valuetype from extension method a few days ago i needed to toggle a bool and i ended up doing like soisvisible isvisiblei found that to be the simplest way to archive that functionailybut before doing like the example above i tried out some different waysmostly about using a extension methodwhich in my opinon would make it even simplier or at least less chars to writeisvisibletogglebut as a boolean is a value type the bool that is sent though to the extension method is a copy of the original bool and not a reference typepublic static void togglethis boolean valuevalue valuewhich would do what i needed but as the boolean getting toggled is a copy of the original boolean the change isnt applied to the originali tried putting the ref keyword infront of boolean but that did not compileand i still have not found a reason for that not compiling wouldnt that be the perfect functionality for extension methodspublic static void togglethis ref boolean valuei even tried casting the boolean into a object which in my head would make it into a reference type and then it would no longer be a copy and the change would get passed backthat did not work eitherso my question is if its possible to make a extension pass back changes or another way to make it even simplier than it already isi know it quite possible would not get any simplier or more logical than the top example but you never know thanks in advance,['c#'] +25034,get imageformat from file extension is there quick way to get the imageformat object associated to a particular file extension i am looking for quicker than string comparisons for each format,"['c#', '.net']" +25047,error property myboolvariablename with retain attribute must be of object type i have a bool value inside my interface definition in my h file here it is below it has the same problem whether it is a pointer or notinterface mycustomviewcontroller uiviewcontroller uiwebviewdelegate more iboutlets defined above bool myboolvariablenamewhen i compile i get error property myboolvariablename with retain attribute must be of object type on the line for the import of my h filei found this page here about an integer nsnumber so it seems i cannot use bool values inside an interface definition what can i use insteadwhat should i do for bool boolean values,"['objective-c', 'iphone']" +25049,speeding up web development situationi have been working on a project lately where the ui development seems to be way too time consuming in this case the business rules on the serverside are much more complicated than the presentation aspects as far as a computer science or complexity perspectivei have found myself scratchingbanging my head against the wall with problems with behaviour that differs from the intuitive approach all the way to being a black hole of time waste and poor documentation where i might be trying to get a simple ui element to line up correctlyi am not complaining i understand there are complexities and a wide audience to support with web development but i am perplexed by how long it takes to do what seems should be the easy part compared to how long it takes to write the code with complex logic math science etc questionwhat are you thoughts and personal experience to go from concept to reality with web development and to do this rapidly or at least in a way that you can have a sense of how long it might take i have purposefully not mentioned any frameworks or languages because i would really like to here what web development stacks you use what tools or best practices help you get things done faster and how you end up with code that does not feel totally brittle and full of hackshyperbole language preferences and all thoughts welcome i would at least like to get a sense of what is being used for web development that has a high success rate even if it is not the latest and greatest thing aroundthanks for your inputbn,['html'] +25059,ruby templates how to pass variables into inlined erb i have an erb template inlined into ruby coderequire erbdata a hellob worldtemplate erbnew eofcurrent key is current current value is datacurrent eofdatakeyseach do currentresult templateresultoutputfile filenewcurrentto sfilecreatfiletruncfilerdwroutputfilewriteresultoutputfilecloseendi cannot pass the variable current into the templatethe error iserb1 undefined local variable or method current for mainobject nameerrorhow do i fix this,['ruby'] +25077,how to get the address of the stdvector buffer start most elegantly i want to use stdvector for dynamically allocating memory the scenario isint neededlength computelength some logic here this will allocate the buffer stdvectortchar buffer neededlength call a function that accepts tchar and the number of elementscallfunction buffer0 buffersize the code above works but this buffer0 looks ugly is there a more elegant way to achieve the same,['c++'] +25087,fastest way to compare strings literal and numerical i have a performance problem related to string comparison in javai am working on a project that needs to sort a huge list a tableviewer in eclipse anyway i have pinpointed the bottleneck down to the call to compareto for the string to be comparedis there any way to optimize the performance of a string compare i have searched and googled to no avail as the project is strictly limited to a win32 environment i was thinking that maybe it would be possible to leverage on thatany suggestions would be greatly appreciatededit i forgot to mention that i would need both numerical comparison and literal comparison of the stringsedit2 the goal is essentially to speed up the user interface because it is unacceptable to wait a few seconds each time you click on the header of the table to perform a sort i am looking into maybe caching values somehow to speed up the comparison as the strings are pretty much static i think it would be possibleedit3 i know a lot of you have been thisturbed by the trycatch thing actually that is less of a concern because even if i remove that code and only execute the catchblock a single compareto it still executes at virtually the same speed as the original code if however i comment out the compareto also leaving me with only the overhead of the compare function getting labels etc it is lightning fast so i still need a better way to compare strings either by caching or by doing some other magicunfortunately it is not possible to change the sorting algorithm however i doubt that it is that slow because it succeeds in sorting pure integers quite fastclarificationthe compare function is implemented as part of the tableviewer framework for performing sort operations which means that i am not implementing the specific sorting algorithm but rather it is implemented by swtjface i am only implementing the compare functionwhat is further more interesting is the fact that the code for sorting doubles is faster than the string comparison it is faster to sort columns with only numbers than with actual literal strings which leads me to the conclusion that something fishy is going on in the compareto methodhere is the core of the function e1label and e2label is strings to be compared be smart about the comparison and use nonlexical comparison if possible ie if both strings are actually numbers warning this is only semismart as the sorting might get a bit messed up if some of the values in a column can be parsed as doubles while others can nottry try using numeric double comparison of label valuesdouble e1 double doubleparsedoublee1labeldouble e2 double doubleparsedoublee2labelrc doublecomparee1 double e2 double catch numberformatexception e use lexical comparison if double comparison is not possiblerc e1labelcomparetoignorecasee2label,['java'] +25088,c datatable insert column at position 0 does anyone know the best way to insert a column in a datatable at position 0,['c#'] +25089,how can i detect the installed sunoracle jre on windows i tried googling the answer but all i found was tips on how to detect java from a browser or the very generic way of just starting java and see if it runs which introduces a possibly long delay in my application two seconds when started the very first time on my machinei hope there is a faster way if the following restrictions applyonly sunoracle jres or jdks only 16 and higheronly windows platformsnot from a browser but from a plain old win32 executablethis detection is not meant for a public application but for internal use on windows platforms onlyis there a registry path i can read or some configuration file i can parse,['java'] +25111,gdi how do i draw a line that is one inch in length on any device it is drawn on i need to draw a line one inch long on any device given a graphics reference to it i need it to be an inch long regardless of what transform is set to let us assume that the scaling factor of the transform is given by scale in both horizontal and vertical directionssome ccli codegdrawlinepensblack 500f 500f 500f oneinchequivalent scale 500fnow that was not difficult at all now all we need to do is calculate oneinchequivalentgdpix gives me a thistance of what looks like one inch on screen but not on the printer it seems that on printers drawing a line of 100 units with gpageunit set to graphicsunitthisplay will give me a line one inch long but i really need this to work regardless of the pageunit setting in fact changing pageunit will change the width of the penedit i have tentatively accepted the only answer here as it is pretty close to what i am looking for,['.net'] +25128,what does cc on mean in javascript sometimes i see cc on in javascript what does it mean,['javascript'] +25139,how to make the python interpreter correctly handle nonascii characters in string operations i have a string that looks like so6aa 918aa 417aa 712the clear cut way to trim this string as i understand python is simply to say the string is in a variable called s we getsreplacea that should do the trick but of course it complains that the nonascii character xc2 in file blablapy is not encodedi never quite could understand how to switch between different encodingsheres the code it really is just the same as above but now it is in context the file is saved as utf8 in notepad and has the following headerusrbinpython24 coding utf8 the codef urlliburlopenurlsoup beautifulsoupfs soupfinddiv idmain countmaking a print s here goes well it shows 6a 918a 417a 712sreplacea save main countsit gets no further than sreplace,['python'] +25152,android text view color does not change when thisabled when i call setenabledfalse for a textview object the text color does not change i expected it will be changed to gray if i remove the line of androidtextcolor in my xml file it backs to normalany ideas,['android'] +25160,c location of using statements one thing i have noticed a lot of back and forth on is where using statements should be placed in a c code file whether its in the outermost scope or inside a namespace i understand that the location of the using statement affects the scope of the references within that file but what i do not understand is why in most cases someone would ever want their using statements inside their namespacein almost all cases only one namespace declaration ever exists in a single file so scoping the using statements seemsis useless if one were placing multiple types and multiple namespaces in the same file then scoped using statements make perfect sense yet i still see plenty of cases of this being done even in files with one namespace whyusing systemnamespace mynamespaceusing systemtextpublic class myclass an example of this being done throughout a project seemingly unnecessarily is the aspnet mvc source,['c#'] +25164,wpf handling custom attached events on custom controls i have a routed event declared as such names have been changed to protect the innocentpublic class draghelper dependencyobject public static readonly routedevent dragcompleteevent eventmanagerregisterroutedevent dragcomplete routingstrategybubble typeofdragroutedeventhandler typeofdraghelper public static void adragcompletehandler dependencyobject dependencyobject dragroutedeventhandler handler uielement element dependencyobject as uielement if element null elementaddhandlerdragcompleteevent handler public static void removedragcompletehandler dependencyobject dependencyobject dragroutedeventhandler handler uielement element dependencyobject as uielement if element null elementremovehandlerdragcompleteevent handler pretty standard stuff in xaml i have a datatemplate that contains a single custom control i am attempting to attach this event as well as some other attached properties to the controldatatemplate mycustomcontrol mydraghelperisdragsourcetrue mydraghelperdragcompletedragcompletehandler datatemplatethis fails to produce the desired results specifically while the code that calls raiseevent for the dragcomplete event is called the handler is never invoked nor in fact are the handlers for any other custom routed events that are hooked up elsewhere in this xaml filei tried changing the name of the routed event and i tried switching the data template from one with a datatype to one with an xkey this produced no visible change in the behaviorhowever if i change mycustomcontrol to any builtin wpf control such as a textblock the events are fired exactly as i would exect similarly if i replace my custom control with any other custom usercontrol subclass from my project the behavior reverts to the broken noeventseverseemtogethandled statethis is not make a whole lot of sense to me is there something specific i need to do to get this scenario to work it seems like it should not matter i suppose it is possible there is a specific thing i have done in all my custom controls that causes the event handling to break but i have not seen anything common in the three or four custom controls i have tried so far,['c#'] +25170,c stack and scope i tried this code on visual c 2008 and it shows that a and b do not have the same addressint main int a printfpn a int b printfpn bbut since a does not exist anymore when b gets defined it seems to me that the same stack location could be reusedi do not understand why the compiler does not seem to do what looks like a very simple optimization which could matter in the context of larger variables and recursive functions for example and it does not seem like reusing it would be heavier on the cpu nor the memory does anyone have an explanation for thisi guess the answer is along the lines of because it is much more complex than it looks but honestly i have no ideaedit some precisions regarding the answers and comments belowthe problem with this code is that each time this function is called the stack grows one integer too much of course this is no problem in the example but consider large variables and recursive calls and you have a stack overflow that could be easily avoidedwhat i suggest is a memory optimization but i do not see how it would damage performanceand by the way this happens in release builds will all optimizations on,['c++'] +25172,when debugging on windows where does stderr go when trying to debug a program on windows i cannot seem to find where the output i push to stderr is going how do i get a hold of my stderr output is there a debuggerlevel setting msvc 9 i can change to redirect stderr to some part of the uiupdate i have not looked into trace or outputdebugstring but the code base is crossplatform so platformspecific apis while not totally off the table are secondary to a standardscompliant solution,"['c++', 'c']" +25174,ssis timestamps can anyone provide details on what the three of these meansystemcontainerstarttime systemcreationdate systemstarttimethe documentation for these three is virtually nonexistent,['sql'] +25175,ruby on rails connection problem i have a ruby on rails project that i was developing on a hosted server but have decided to work on my local windows machine withto get started i thought i would make sure that i could just take my models from the old project and put them in a new project then query them in the console this failsedit to reflect more accurate problemthe connection that rails builds to query my models can run only one query then gives the not connected exception for all subsequent queries anybody know whats going on i have checked my configuration a lot if there is some setting on mysql server that i do not know about i would be willing to look at thatstack tracepricefind1activerecordstatementinvalid mysqlerror query not connected show fields from prices from cprogram filesrubylibrubygems18gemsactiverecord233libactive recordconnection adaptersabstract adapterrb212in log from cprogram filesrubylibrubygems18gemsactiverecord233libactive recordconnection adaptersmysql adapterrb320in execute from cprogram filesrubylibrubygems18gemsactiverecord233libactive recordconnection adaptersmysql adapterrb466in columns from cprogram filesrubylibrubygems18gemsactiverecord233libactive recordbaserb1271in columns from cprogram filesrubylibrubygems18gemsactiverecord233libactive recordbaserb1279in columns hash from cprogram filesrubylibrubygems18gemsactiverecord233libactive recordbaserb1578in find one from cprogram filesrubylibrubygems18gemsactiverecord233libactive recordbaserb1569in find from ids from cprogram filesrubylibrubygems18gemsactiverecord233libactive recordbaserb616in find from irb2i have verified that my mysql database is accepting connections and has the data and structure i expect i have double checked my connections etc can anyone shed some light,"['mysql', 'ruby-on-rails']" +25186,rounding number to 2 decimal places in c how can i round a float such as 379 to two decimal places 3778 in c,['c'] +25189,how can i use jqueryload to replace a div including the div i have a div with the id of secondheader and i want to replace that entire div with another div with the same id of secondheader but instead of replacing it it just adds the loaded div inside the first one secondheaderloadloggedincontenthtml secondheaderthis is what happensdiv idsecondheaderdiv idsecondheaderdivdivwhat i want to happen is the secondheader div from the ajax load to totally replace the secondheader in the initial pagei know it sounds dumb but heres what i am trying to accomplishwhen a user is not logged in they see a nonlogged in header i am using ajax to allow the person to log into the site and i want to replace the nonlogged in header with the logged in one via ajaxi have tried everything i know such assecondheaderreplacewithsecondheaderloadloggedincontenthtml secondheaderand using remove before handany ideas,['jquery'] +25190,documentation for stl i have spent the last several years fighting tooth and nail to avoid working with c so i am probably one of a very small number of people who likes systems programming and template meta programming but has absolutely no experience when it comes to the stl and very little c template experiencedoes anyone know of a good document for getting started using stli would prefer pdf or something else i can kill trees with and i am looking for something more along the lines of a reference than a tutorial although an 8020 split would be nice therei ended up using the docs from here pringing them out via a pdf driver and tacking them together with this idea now i am off to print them off 2up double sided 190 pages even so but i have 1k pages in my quota and only 4 months till graduation,['c++'] +25191,how to use custom font with webview now i want to thisplay some unicode characters and i have used tag font facearialsomething herefont but it seems that webview can not find the arialfont because i can only see ufocharacters do i have to copy arialttf tosomewhere or how can i use this truetype font with webview thanks,['android'] +25195,java preprocessor if i have a boolean field likeprivate static final boolean debug falseand within my code i have statements likeifdebug systemerrprintlnerr1does the java preprocessor just get rid of the if statement and the unreachable code,['java'] +25201,why is documentgetelementbyidtableidinnerhtml not working in ie8 i modify documentgetelementbyidinnerhtml with java script in a page it is working fine in firefox but not ie8 please see below for more detailshtml codetable tr idabc td idc stylecolorredctd trtablejava script code documentgetelementbyidabcinnerhtml td idbbc stylecoloryellowabctdwhen i run the js code in firefox it will change the thisplay word from c to abc but it is just not working in ie8 does anyone know why is there any way i can make this work in ie8 as well,['javascript'] +25202,efficient way to insert a number into a sorted array of numbers i have a sorted javascript array and want to insert one more item into the array such the resulting array remains sorted i could certainly implement a simple quicksortstyle insertion functionvar array 123456789var element 35function insertelement array arraysplicelocationofelement array 1 0 element return arrayfunction locationofelement array start end start start 0 end end arraylength var pivot parseintstart end start 2 10 if endstart 1 arraypivot element return pivot if arraypivot element return locationofelement array pivot end else return locationofelement array start pivot consoleloginsertelement arrayhowever i noticed that implementations of the arraysort function might potentially do this for me and nativelyvar array 123456789var element 35function insertelement array arraypushelement arraysortfunctiona b return a b return arrayconsoleloginsertelement arrayis there a good reason to choose the first implementation over the secondedit note that for the general case an ologn insertion as implemented in the first example will be faster than a generic sorting algorithm however this is not necessarily the case for javascript in particular note thatbest case for several insertion algorithms is on which is still significantly different from ologn but not quite as bad as on logn as mentioned below it would come down to the particular sorting algorithm used see javascript arraysort implementationthe sort method in javascript is a native function so potentially realizing huge benefits ologn with a huge coefficient can still be much worse than on for reasonably sized data sets,['javascript'] +25203,how do i use modi in an aspnet web application i have written an ocr wrapper library around the microsoft office document imaging com api and in a console app running locally it works flawlessly with every testsadly things start going badly when we attempt to integrate it with a wcf service running as an aspnet web application under iis6 we had issues around trying to free up the modi com objects and there were plenty of examples on the web that helped ushowever problems still remain if i restart iis and do a fresh deployment of the web app the first few ocr attempts work great if i leave it for 30 minutes or so and then do another request i get server failure errors like thisthe server threw an exception exception from hresult 0x80010105 rpc e serverfault at modidocumentclasscreatestring fileopenfrom this point on every request will fail to do the ocr until i reset iis and the cycle begins againwe run this application in it is own app pool and it runs under an identity with local admin rightsupdate this issue can be solved by doing the ocr stuff out of process it appears as though the modi library does not play well with managed code when it comes to cleaning up after itself so spawning new processes for each ocr request worked well in my situationhere is the function that performs the ocr public class imagereader ithisposable private modidocument document private modiimages images private modiimage image private modilayout layout private manualresetevent completedocr new manualreseteventfalse snip code removed for clarity private string performmodistring filename document new modidocument documentonocrprogress new modi idocumentevents onocrprogresseventhandler document onocrprogress documentcreatefilename documentocrmodimilanguagesmilang english true true completedocrwaitone50 documentsave images documentimages image modiimage images0 layout imagelayout string text layouttext documentclosefalse return text void document onocrprogressint progress ref bool cancel if progress 100 completedocrset private static void setcomobjecttonullparams object objects for int i 0 i objectslength i object o objectsi if o null marshalfinalreleasecomobjecto o null methodimplmethodimploptionsnoinlining public void thispose setcomobjecttonull layout image images document gccollect gcwaitforpendingfinalizers i then instantiate an instance of imagereader inside a using block which will call ithisposablethispose on exitcalling marshalfinalreleasecomobject should instruct the clr to release the com objects and so i am at a loss to figure out what would be causing the symptoms we havefor what it is worth running this code outside of iis in say a console app everything seems bullet proof it works every timeany tips that help me diagnose and solve this issue would be an immense help and i will upvote like crazy thanks,['asp.net'] +25209,possible to build a shared library with static link used library i can build a executable with gcc with static linkgcc static xc o xso i can run x without any external dependent librarybut what if i want to build shared library without externel dependent library which i mean i want the shared library statically linked its externel reference in,['c'] +25217,image over image css i am creating a webpage and i am trying to put a png buttons over gif fileswhen the page renders it makes the png file appear after or under the gif filei tried using and tags but neither work i have also tried using various css padding alignments etc but it does not seem to workis there a way code to get images to appear on top of images,"['html', 'css']" +25227,stack smashing detected i am executing my aout file after execution the program runs for some time then exits with the message stack smashing detected aout terminated backtrace libtlsi686cmovlibcso6 fortify fail0x48abortedwhat could be the possible reasons for this and how do i rectify it,['c'] +25235,fast access to the typemethod that holds an attribute in c i have made a custom attribute here named aatribute and for instance a class called b where one or more methods use the attribute is it possible to get the methodinfo of the method that holds the attribute in this case bmethod1 as one of it is attributes without walking through the whole assembly and looking at all defined methods for their attributes and is their an analogue way for other attributetargets parameterstypesproperties i wouldo not want an array of all methods that use that type of attribute but just the method with this attirbuteobject in particual i want to use it to put additional constraints on the method return type parameter name other attributeusageattributeusageattributetargetsmethodpublic class aatribute attribute some fields and properties public aatribute perhaps with some parameters some operations methodinfo miacces to the methodinfo with this attribute as an attribute the question some operations with the methodinfo some methodspublic class b some fields properties and constructors a public void bmethod1 some operations other methods,['c#'] +25238,aspnet mvc antiforgerytoken over ajax i am currently developing an mvc application in aspnet i am using ajaxactionlink to provide a delete link in a list of records however this is very insecure i have put thisacceptverbshttpverbspostover the function to do the deleting which stops the function being called simply by a url however the other security hole that still exists is that if i were to make a basic html page with this contentform action methodpostinput typesubmit formit would still be perfoming a post but from a different locationis it possible to use the antiforgerytoken with an ajax actionlink if so is this a secure approach are there more security holes i have not realised,['asp.net'] +25247,how to make a net application large address aware assuming i have booted a 32bit windows server with the 3gb switch how can i make a net application use the additional address space,['.net'] +25263,how do i create a reusable blockproclambda in ruby i want to create a filter and be able to apply it to an array or hash for exampledef isoddi i 2 1endthe i want to be able to use it like sox 1234puts xselectisoddxdelete ifisoddputs xthis seems like it should be straight forward but i cannot figure out what i need to do it get it to work,['ruby'] +25275,convert a positive number to negative in c you can convert a negative number to positive like thisint myint systemmathabs5is there an equivalent method to make a positive number negative,['c#'] +25277,how do i unregister anonymous event handler say if i listen for an eventsubjectnewevent delegateobject sender neweventargs e some codenow how do i unregister this event or just allow the memory to leak,"['c#', '.net']" +25286,how to make nsdateformatter thisplay localespecific date i am using nsdateformatter to set my date in my iphone app and dates are showing up properly however i am finding all the locales my app supports up to 12 different languages are sticking to the date format i specify via setdateformat ideally i want the date format to appear in a form natural to the region setting for the user instead of following my format which works well for english but may not be natural for other localesfollowing is my code nsdateformatter dateformatter nsdateformatter alloc init dateformatter setdatestylensdateformattermediumstyle dateformatter settimestylensdateformattershortstyle dateformatter setdateformatm dd y kkmmss selfcreationdatetext dateformatter stringfromdatecreationtimestamp,['iphone'] +25304,loadtime elf relocation i am writing a simple userspace elf loader under linux why for fun my loader at the moment is quite simple and is designed to load only staticallylinked elf files containing positionindependent codenormally when a program is loaded by the kernels elf loader it is loaded into its own address space as such the data segment and code segment can be loaded at the correct virtual address as specified in the elf segmentsin my case however i am requesting addresses from the kernel via mmap and may or may not get the addresses requested in the elf segments this is not a problem for the code segment since it is position independent however if the data segment is not loaded at the expected address code will not be able to properly reference anything stored in the data segmentindeed my loader appears to work fine with a simple assembly executable that does not contain any data but as soon as i add a data segment and reference it the executable fails to run correctly or segfaultshow if possible can i fixup any references to the data segment to point to the correct place is there a relocation section stored in the static elf file for this purpose,['c'] +25310,convert jpanel to image is there a way to convert a jpanel that has not yet been thisplayed to a bufferedimagethanksjeff,['java'] +25311,matplotlib coord sys origin to top left how can i flip the origin of a matplotlib plot to be in the upperleft corner as opposed to the default lowerleft i am using matplotlibpylabplot to produce the plot though if there is another plotting routine that is more flexible please let me knowi am looking for the equivalent of the matlab command axis ijalso i have spent a couple hours surfing matplotlib help and google but have not come up with an answer some info on where i could have looked up the answer would be helpful as well,['python'] +25312,storing datetime as utc in phpmysql everywhere i read about converting time to a users timezone says that the best method is to store a date and time in utc then just add the users timezone offset to this timehow can i store a date in utc time i use the mysql datetime field when adding a new record to mysql in my php code i would use now to insert into mysql datetimewould i need to use something different than now to store utc time,"['php', 'mysql']" +25321,finding current page number in jqgrid how can i find the current page number in jqgrid using jquery of course also how do i know how many pages are there in total,['jquery'] +25322,arguments in selector is there any way that i can pass arguments in selectorexamplei have this method voidmymethodnsstringvalue1 setvalue2nsstringvalue2and i need to call this function through a selector passing two argumentsnstimer scheduledtimerwithtimeinterval01 targetself selectorselectormy method userinfonil repeatsyeshow can i do this,['iphone'] +25324,c what are some high performance best practicestips for adonet i decided not to use an orm and going to use straight adonet for my project i know i know its gonna take longer to program but i just want pages to load at high speeds even at peak time,"['c#', '.net']" +25341,ruby mailing list library or gem can anyone recommend a good gem or library for managing a mailing list with ruby no rails solutions if possible please i do not want to have actionwhatever dependencies this will most likely be done with ramazei just need basic features like management of the list itself crud operations on the user list plus being able to send notifications welcome messages and also auto respond to basic things like subscribe and unsubscribeoptimally people should be able to subscribe via both a ramaze web page ie i would have ramaze callaccess the libs api as well as by sending an email to a specific email address but i am willing to forego the operations by emaili am willing to entertain nonruby or nonprogrammatic solutions if they are good but the ability to subscribe from a web page under my control is a mustedit sorry one important detail i forgot to add this is intended to be a oneway mailing list that is people should be able to subscribe and unsubscribe alright but only one person should be allowed to send to the list for broadcasting,['ruby'] +25342,how to expand an array dynamically in c like in vector lets say i have int pp new int5forint i0i5i piinow i want to add a 6th element to the array how do i do it,['c++'] +25349,how to add composite primary key to table create table did numeric1 code varchar2after i create the above table how can i add a composite primary key on both fields and also a foreign key,['sql'] +25364,what does exited with code 9009 mean during this build what does this error message mean what could i do to correct this issueassemblyinfocs exited with code 9009the problem is probably happening as part of a postbuild step in a net solution in visual studio,['.net'] +25371,how to break outer cycle in ruby in perl there is an ability to break an outer cycle like thisa for my stuff otherstuff for my foo bar last a if somethingbad syntax may be wrong which uses a loop label to break the outer loop from inside the inner loop is there anything similar in ruby,['ruby'] +25372,php language detection im a hobbycoder that is trying to build his first multilangual sitei use this piece of code to detect users language if you havent chosen a language it will include your language file based on http accept language i dont know where it gets it from thosession startif isset sessionlang sessionlang substr serverhttp accept language 0 2elseif isset getsetlang getsetlang en sessionlang enelseif isset getsetlang getsetlang sv sessionlang svelseif isset getsetlang getsetlang pl sessionlang plelseif isset getsetlang getsetlang fr sessionlang frincludelanguages sessionlangphpit works for me and includes the polish lang file but is this code accurate or is there another way how do you think youtube does this for examplewould be great if some english french swethish or polish folks could visit my site and see if it includes the right file so i know that it doesnt just work for me anyway you think i could improve my code it it will looks messy as i add more languages with all those elseifthanks,['php'] +25376,opening sqlite3 as readonly with pdo the sqlite3 class has an option like thisdb new sqlite3mysqlitedbdb sqlite3 open readonlyin pdo you would simply open withdb new pdosqlitemysqlitedbdbmy question is however is there a way to open a database with pdo in readonly mode,['php'] +25377,safe to get count value from generic collection without locking the collection i have two threads a producer thread that places objects into a generic list collection and a consumer thread that pulls those objects out of the same generic list i have got the reads and writes to the collection properly synchronized using the lock keyword and everything is working finewhat i want to know is if it is ok to access the count property without first locking the collectionjaredpar refers to the count property in his blog as a decision procedure that can lead to race conditions like thisif listcount 0 return list0if the list has one item and that item is removed after the count property is accessed but before the indexer an exception will occur i get thatbut would it be ok to use the count property to say determine the initial size a completely different collection the msdn documentation says that instance members are not guaranteed to be thread safe so should i just lock the collection before accessing the count property,"['c#', '.net']" +25378,c static array initialization how verbose do i need to be to initialize an int array with all zeros do i need to useint foo10 0 0 0 0 0 0 0 0 0 0or will this workint foo10 0,"['c++', 'c']" +25379,rails view without a controller can rails handle creating a view without a controller for example let say i have a page that just links to other pages would i need to create a dummy controller for that or could i just do something in my routes file,['ruby-on-rails'] +25381,pointer implementation details in c i would like to know architectures which violate the assumptions i have listed below also i would like to know if any of the assumptions are false for all architectures that is if any of them are just completely wrongsizeofint sizeofchar sizeofvoid sizeoffunc ptr the inmemory representation of all pointers for a given architecture is the same regardless of the data type pointed tothe inmemory representation of a pointer is the same as an integer of the same bit length as the architecturemultiplication and division of pointer data types are only forbidden by the compiler note yes i know this is nonsensical what i mean is is there hardware support to forbid this incorrect usageall pointer values can be casted to a single integer in other words what architectures still make use of segments and offsetsincrementing a pointer is equivalent to adding sizeofthe pointed data type to the memory address stored by the pointer if p is an int32 then p1 is equal to the memory address 4 bytes after pi am most used to pointers being used in a contiguous virtual memory space for that usage i can generally get by thinking of them as addresses on a number line see stack overflow question pointer comparison,['c'] +25382,can someone abuse linq and solve this money puzzle for the fun of it i would like to see someone use and abuse linq to solve this money problemi really have no idea how you would do it i suppose populating some set and then selecting off of itif given a total number of coins and give the total amount of all coins added togethershow every possible combination of coins coins are quarters25 dimes10 nickels05 and pennies01include the option so that there can be zero of a type of coin or there must be at least 1 of eachsample problem if i have 19 coins and the coins add up to 156 and there must be at least 1 of every type of cointhe answer would be1 quarters 9 dimes 8 nickels 1 pennies2 quarters 5 dimes 11 nickels 1 pennies2 quarters 9 dimes 2 nickels 6 pennies3 quarters 1 dimes 14 nickels 1 pennies3 quarters 5 dimes 5 nickels 6 pennies4 quarters 1 dimes 8 nickels 6 pennies5 quarters 1 dimes 2 nickels 11 penniesand if we allowed zero for a coint we allowed get an additional0 quarters 13 dimes 5 nickels 1 pennieshere is some sample c code using a brute force method to solve the problemdo not bother improving the sample let us just see a solution using linqtry not to use any regualar c looping code if possibleprivate void solvecoinproblemint totalnumberofcoins double totalamount int minimumnumberofeachcoin int foundcount 0 long numberoftries 0 consolewritelinestringformatsolving coin problemtotalnumberofcoins0totalamount1minimumnumberofeachcoin2 totalnumberofcoins totalamount minimumnumberofeachcoin for int totalquarters minimumnumberofeachcoin totalquarters totalnumberofcoins totalquarters for int totaldimes minimumnumberofeachcoin totaldimes totalnumberofcoins totaldimes for int totalnickels minimumnumberofeachcoin totalnickels totalnumberofcoins totalnickels for int totalpennies minimumnumberofeachcoin totalpennies totalnumberofcoins totalpennies numberoftries if totalquarters totaldimes totalnickels totalpennies totalnumberofcoins if mathroundtotalquarters 25 totaldimes 10 totalnickels 05 totalpennies 012 totalamount consolewritelinestringformat0 quarters 1 dimes 2 nickels 3 pennies totalquarters totaldimes totalnickels totalpennies foundcount consolewritelinestringformat0 combinations found we tried 1 combinations foundcount numberoftries,['c#'] +25386,free sql comparison tool i have been using sql compare by redgate at my company and was very satisfied with it are there any free comparison tools that are similar or what would be my best shot for synchronizing two sql dbs without a paid application,['sql'] +25398,multiprocessing debug techniques i am having trouble debugging a multiprocess application specifically using a process pool in pythons multiprocessing module i have an apparent deadlock and i do not know what is causing it the stack trace is not sufficient to describe the issue as it only thisplays code in the multiprocessing moduleare there any python tools or otherwise general techniques used to debug deadlocks,['python'] +25405,radio button selected i would like to know for a specific radio button group if a radio button is selected or not with jquery thanks,['jquery'] +25415,serve image with php script vs direct loading image i want to monitor how often some external images are loadedso what my idea was instead of giving a uri directly like thiswsitecomimage1jpgi create a php script which reads the image so i build a php file and my html would look like thisimg srcwsitecomserveimagephpimgimage1jpgbut i do not know how to read the image from thisk and return it would i return a byte array or set the content typekind regardsmichel,['php'] +25424,login system php cookies and sessions i want to make a login system using cookiessessions but i am not sure what security and such is like with them with sessions if login is set to yes can i trust that are users able to change what it returns should i just store the encrypted password and check it on every pagewith cookies would i have to check for things like mysql injectionsthis might sound like beginner stuff but it would really help if someone could clarify it for me thanks in advance for any replies,['php'] +25425,form padding differences in firefox and operachromeie i am having a problem with the padding in my form on my websiteif i have set a heightwidth to a form element and then adds a padding to it in all browsers i have tried except firefox the padding is added to the heightwidthif i have a input with 200 in width and 20px in height and padding at 5 all ways the sum and total width and height would be 210px and 30px but in firefox it is 200px and 20px how do i work my way around this,['css'] +25432,why yui reset css dosent pass validation i tried to validate my sites css using the w3c css validator unfortunately resetmincss from yui framework produced parse error on the string fontsize100 the validator resultson further investigation i noticed the following error on firefoxs error consolewarning expected declaration but found skipped to next declarationi could not find any explanation for the meaning of the nor references for a problem in this popular reset csswhat am i missing,['css'] +25438,using propertyinfogetvalue i have a class that creates a static array of all properties using a static constructor i also have a function getnamesandtypes that lists the name type of each property in that arraynow i want to create another instancelevel function getnamesandtypesandvalues that thisplays the name type of each property in the class as well as that instances value how would i do that heres the code that i have written so farstatictestcsusing systemusing systemcomponentmodelusing systemglobalizationusing systemreflectionnamespace statictestpublic class classtestprivate string m a m b m cprivate static propertyinfo allclasspropertiesstatic classtesttype type typeofclasstestallclassproperties typegetproperties sort properties alphabetically by name arraysortallclassproperties delegatepropertyinfo p1 propertyinfo p2return p1namecomparetop2namepublic int aget return converttoint32m a set m a valuetostring public string bget return m b set m b value public datetime cget return datetimeparseexactymmdd m c cultureinfoinvariantculture set m c stringformat0ymmdd value public static void getnamesandtypesforeach propertyinfo propertyinfo in allclasspropertiesconsolewriteline0 type 1 propertyinfoname propertyinfopropertytypepublic void getnamesandtypesandvaluesforeach propertyinfo propertyinfo in allclasspropertiesconsolewriteline0 type 1 propertyinfoname propertyinfopropertytypeprogramcsusing systemusing systemcollectionsgenericusing statictestnamespace consoleapplication2class programstatic void mainstring argsconsolewritelinestatic getnamesandtypesclasstestgetnamesandtypesconsolewritelineclasstest classtest new classtestclasstesta 4classtestb baconclasstestc datetimenowconsolewritelineinstance getnamesandtypesandvaluesclasstestgetnamesandtypesandvaluesconsolereadlinei tried using propertyinfogetvalue but i could not get it to work,"['c#', '.net']" +25439,compressing big number or string to small value my aspnet page has following query string parameteraids1012102110131022here ids parameter will always have numbers separated by something in this case currently there are 4 numbers but normally they would be in between 3 and 7 now i am looking for method to convert each big number from above into smallest possible value specifically compressing value of ids query string parameter both compressing each number algorithm or compressing whole value of ids query string parameter are welcomeencode or decode is not an issue just compressing the value ids query string parametercreating some unique small value for ids and then retrieving its value from some data source is out of scopeis there an algorithm to compress such big numbers to small values or to compress value of the ids query string parameter all together,['c#'] +25446,preventing a uitabbar from applying a gradient to its icon images when i make icons for a uitabbar it applies a gradient to the images i need to know how to prevent it from having this gradient,['iphone'] +25450,cannot access the configuration manager from my solution i have a three tier setup someone suggested i should get the connectionstring from the webconfig file and i have got it set up like thisnow i am trying to access the connectionstring from my dal tier but i cannot find the configurationmanager how can i invoke my connection string from here,['c#'] +25455,how is an instance initializer different from a constructor in other words why would you need an instance initializer what difference or advantage do you have in writing a instance initializer over a constructor,['java'] +25466,iphone blur uiimage in my iphone application i have a blackandwhite uiimage i need to blur that image gaussian blur would doiphone clearly knows how to blur images as it does that when it draws shadowshowever i did not found anything related in the apido i have to do blurring by hand without hardware acceleration,['iphone'] +25469,d entitys collection and repositories suppose i have public class product entity public ilistitem items get set suppose i want to find an item with max something i can add the method productgetmaxitemsmth and do it with linq from i in items select ismthmax or with a manual loop or whatever now the problem is that this will load the full collection into memorythe correct solution will be to do a specific db query but domain entities do not have access to repositories right so either i doproductrepositorygetmaxitemsmthproductwhich is ugly no or even if entities have access to repositories i use iproductrepository from entity productgetmaxitemsmth return servicegetrepositoryiproductrepositorygetmaxitemsmth which is also ugly and is a duplication of code i can even go fancy and do an extensionpublic static ilistitem getmaxitemsmththis product product return servicegetrepositoryiproductrepositorygetmaxitemsmthwhich is better only because it does not really clutter the entity with repository but still does method duplicationnow this is the problem of whether to use productgetmaxitemsmth or productrepositorygetmaxitemsmthproduct again did i miss something in d what is the correct way here just use productrepositorygetmaxitemsmthproduct is this what everyone uses and are happy withi just do not feel it is right if i cannot access a products items from the product itself why do i need this collection in product at all and then can product do anything useful if it cannot use specific queries and access its collections without performance hitsof course i can use a less efficient way and never mind and when it is slow i will inject repository calls into entities as an optimization but even this does not sound right does itone thing to mention maybe it is not quite d but i need ilist in product in order to get my db schema generated with fluent nhibernate feel free to answer in pure d context thoughupdate a very interesting option is described here not only to deal with dbrelated collection queries but also can help with collection access control,['c#'] +25493,change the value in appconfig file dynamically i want to modify a value in appsetting section in appconfig so i wroteconsolewritelineconfigurationmanagerappsettingsnameconsolereadconfiguration configconfigurationmanageropenexeconfigurationconfigurationuserlevelnone configappsettingssettingsnamevalue raja configsaveconfigurationsavemodemodified configurationmanagerrefreshsectionappsettingsconsolewritelineconfigurationmanagerappsettingsnameconsolereadafter the execution of above code i verified the appconfig whether the value of name element has been changed or not but no changewhat is the wrong with my code or is there any other way to do this,"['c#', '.net']" +25494,what is the relationship between osgi and dependency injection what are they of each otherspecification and implementationcompetitorsunrelated,['java'] +25521,what is external linkage and internal linkage in c i want to understand the external linkage and internal linkage and their difference i also want to know the meaning ofconst variables internally link by default unless otherwise declared as extern,['c++'] +25524,how to compare 2 files fast using net typical approaches recommend reading the binary via filestream and comparing it bytebybytewould a checksum comparison such as crc be fasterare there any net libraries that can generate a checksum for a file,['c#'] +25537,how do i change the text of a span element in javascript if i have a span sayspan idmyspan hereismytext spanhow do i use javascript to change hereismytext to newtext,"['javascript', 'html']" +25550,how do you find a min max with ruby i want to do something simple and straightforward like min510 or mathmax47 are there functions to this effect in ruby,['ruby'] +25556,c training quizzes i have been programming 10 years mostly in vba and vbnet but i know c well enough to program what i normally do i yesterday was applying for a senior c position and i did so poorly on the induction test its not funny i have always found that for me the best way to learn and recall is via questions and answers multichoice and short answer that is a question is posed and after i answer instant feedback is given as to whether i choose right or wrong and the reasons whyas such i was wondering if anyone knew of or could recommend a c quiz website something like a daily c quiz to keep my brain up to date and fresh if i am not always programming in it not something wimpy either something that does everything paying is not an obstacle id prefer to pay for a good resource than muck aroundthank you,"['c#', 'c']" +25561,facebook api and facebook connect using java new to facebook api and facebook connectfound the facebook java api open source library on google codei am really excited that there is an api prewritten in java for itam interested in writing a server side java layer which uses rest to be able to access a useras facebook friends list their wall send them messages innetwork etcdownloaded the binary and unfortunately i have not found any sample or demo code when i unzipped itquestions1 does this library support facebook connect2 what is the best way to get start using facebook connect with server side java3 since i am building middleware do i still have to create a sample app on the online facebook developer page4 what should i include in my am a newbie in maven pomxml in order to get started,['java'] +25568,how to show a comparison of 2 html text blocks i need to take two text blocks with html tags and render a comparison merge the two text blocks and then highlight what was added or removed from one version to the nexti have used the pear text diff class to successfully render comparisons of plain text but when i try to throw text with html tags in it it gets ugly because of the word and characterbased compare algorithms the class uses html tags get broken and i end up with ugly stuff like pspan classnew spanp it slaughters the htmlis there a way to generate a text comparison while preserving the original valid html markupthanks for the help i have been working on this for weeks this is the best solution i could think of findreplace each type of html tag with 1 special nonstandard character like the apple logo opt shift k render the comparison with this kind of primative markdown then revert the nonstandard characters back into tags any feedback,"['php', 'html']" +25591,how to insert if not exists in mysql i started by googling and found this article which talks about mutex tablesi have a table with 14 million records if i want to add more data in the same format is there a way to ensure the record i want to insert does not already exist without using a pair of queries ie one query to check and one to insert is the result set is emptydoes a unique constraint on a field guarantee the insert will fail if it is already thereit seems that with merely a constraint when i issue the insert via php the script croaks,"['php', 'sql', 'mysql']" +25598,simple virtual filesystem in cc i would like to implement a very simple virtual filesystem vfs which supports some basic file system operation like fwritefopen fput etc the vfs is an abstraction layer on top of some concrete os eg windows linux etc assume now thatthe fopen interface looks something like thisfile vfs file open const unsigned char strfile int flags now i am wondering how i can make in the actual implementation of this interface the thistinction about whichfilesystem i am talking to is there in c something that tells me on which os the application is running so thati could do something like this file vfs file open const unsigned char strfile int flags int os getosidif 0s 1 implement here the system calls required to open a file on a win oselse if os 2 implement here the system calls required to open a file on a linux osetc edit thanks so far for your answer gents that was really helpful to clarify some thingsnow i am wondering if anyone knows where i can find the system calls for file oeprations for windows it is easy to find them for linux but i struggeled to find something similar for windows eg i would be interested in the system calls to open a file write a file etcon another note the c stdioh offers a number of stand io operations likefile fopen const char filename const char opentypein other words i do not have to reimplement the fopen routine in my vfs as the gnu c library takes care about what os it is dealing with is that right i just have to implementfunctionaliy that is not supported by stdio library eg creating directories which differ from filesystem to filesystemthanks,['c++'] +25599,slow mysql inserts i am using and working on software which uses mysql as a backend engine it can use others such as postgresql or oracle or sqlite but this is the main application we are using the software was design in such way that the binary data we want to access is kept as blobs in individual columns each table has one blob column other columns have integersfloats to characterize the blob and one string column with the blobs md5 hash the tables have typically 2 3 or 4 indexes one of which is always the md5 column which is made unique some tables already have millions of entries and they have entered the multigigabyte in size we keep separate peryear mysql databases in the same server so far the hardware is quite reasonable i think for general applications a dell poweredge 2uform servermysql select queries are relatively fast there is little complaint there since these are most of the time in batch mode however insert queries take a long time which increases with table size number of rows admittedly this is because the md5 column is of type unique and so each insert has to figure out whether each new row has a corresponding alreadyinserted md5 string and it is not too strange i think if the performance gets worse if there are other indexes not unique but i still cannot put my mind to rest that this software architecture choice i suspect keeping blobs in the table row instead of thisk has a significant negative impact is not the best choice insertions are not critical but it is an annoying feeling to havedoes anyone have experience in similar situations with mysql or even other preferably linuxbased rdbmes any insights you would care to provide maybe some performance figures btw the working language is c which wraps c calls to mysqls api,['mysql'] +25600,cubic root of the negative number on python can someone help me to find a solution on how to calculate a cubic root of the negative number using python mathpow3 float13nanit does not work cubic root of the negative number is negative number any solutions,['python'] +25601,reordering control in uitableview i am developing a game in which i am using a uitableview which has custom cell uitableviewcell subclassin editing modeonly the reordering control of the uitableview should showright now i am getting the delete and the reordering controlhow to get only reordering control while editing,['iphone'] +25609,jaxb vs apache xmlbeans anyone can tell me which one is better jaxb or apache xmlbeans taking in account the performance for files bigger than 10mb,['java'] +25610,is the c stdset threadsafe i have a question about the thread safety of stdsetas far as i know i can iterate over a set and adderase members and that does not invalidate the iteratorsbut consider following scenariothread a iterates over a set of shared ptrtypethread b occasionally adds items to this seti have experienced segfaults as the program runs and i am not sure why this happens is lack of thread safety the cause,['c++'] +25618,eclipse spell checker how do i remove a word i added i accidentally added a word i am forever misspelling into eclipses spellchecker dictionary how do i get it back out again,['java'] +25633,how do you set cache headers in spring mvc in an annotationbased spring mvc controller what is the preferred way to set cache headers for a specific path,['java'] +25636,can i specify maxlength in css can i replace the maxlength attribute with something in cssinput typetext idphone extension maxlength4,"['html', 'css']" +25638,is there a way to catch an willrotatetointerfaceorientation event from an uiview every uiviewcontroller has a method called willrotatetointerfaceis it possible to do this within a uiview toodoes this match the idea of model view controller the only way i can think of is to send the event from the uiviewcontroller to the uiviewis there a global variable for the current orientation,"['iphone', 'objective-c']" +25643,autowiring a list using util schema gives nosuchbeandefinitionexception i have a bean that i want to inject with a named list using spring util namespace utillist idmylist but spring is looking for a collection of beans of type string instead my broken test isrunwithspringjunit4classrunnerclasscontextconfigurationpublic class listinjectiontest autowired qualifiermylist private liststring stringlist test public void testnotnull testcaseassertnotnullstringlist not null stringlist my context isbeans xmlnsxsi xmlnsutil xmlns xmlnscontext xsischemalocation utillist idmylist valuefoovalue valuebarvalue utillistbeansbut i get caused by orgspringframeworkbeansfactorynosuchbeandefinitionexception no matching bean of type javalangstring found for dependency collection of javalangstring expected at least 1 bean which qualifies as autowire candidate for this dependency dependency annotations orgspringframeworkbeansfactoryannotationautowiredrequiredtrue orgspringframeworkbeansfactoryannotationqualifiervaluemylist at orgspringframeworkbeansfactorysupportdefaultlistablebeanfactoryraisenosuchbeandefinitionexceptiondefaultlistablebeanfactoryjava726 at orgspringframeworkbeansfactorysupportdefaultlistablebeanfactoryresolvedependencydefaultlistablebeanfactoryjava571 at orgspringframeworkbeansfactoryannotationautowiredannotationbeanpostprocessorautowiredfieldelementinjectautowiredannotationbeanpostprocessorjava412which puzzles me rather as i figured this would be the way it was expected to work,['java'] +25649,printing results immediately php i have a php script that connects 10 different servers to get data i want it to print the results of the 1st connection before the second one begins,['php'] +25651,javascript moving element in the dom let us say i have three div elements on a page how can i swap positions of the first and third div jquery is fine,"['javascript', 'jquery']" +25670,how to get and set the window position of another application in c how can i get and set the position of another application using cfor example i would like to get the top left hand coordinates of notepad letas say it is floating somewhere at 100400 and the position this window at 00 whats the easiest way to achieve this,['c#'] +25677,python generating python i have a group of objects which i am creating a class for that i want to store each object as its own text file i would really like to store it as a python class definition which subclasses the main class i am creating so i did some poking around and found a python code generator on effbotorg i did some experimenting with it and heres what i came up with a python code generator backend fredrik lundh march 1998 code taken from import sys stringclass codegeneratorbackend def beginself tabt selfcode selftab tab selflevel 0 def endself return stringjoinselfcode def writeself string selfcodeappendselftab selflevel string def indentself selflevel selflevel 1 def dedentself if selflevel 0 raise syntaxerror internal error in code generator selflevel selflevel 1class point defines a point has x and y def init self x y selfx x selfy y def dump selfself filename selfc codegeneratorbackend selfcbegintab selfcwriteclass 01pointnformatselfxselfy selfcindent selfcwritedefines a point has x and yn selfcwritedef init self x0 y1nformatselfx selfy selfcindent selfcwriteselfx 0nformatselfx selfcwriteselfy 0nformatselfy selfcdedent selfcdedent f openfilenamew fwriteselfcend fcloseif name main p point34 pdump selfdemopythat feels really ugly is there a cleanerbettermore pythonic way to do this please note this is not the class i actually intend to do this with this is a small class i can easily mock up in not too many lines also the subclasses do not need to have the generating function in them if i need that again i can just call the code generator from the superclass,['python'] +25681,how to save a rendered view as a static file my rails 23 app generates a page in htmlcss or as a word doc i would like to save that html file to the filesystem as a static file ie filenamehtml or filenamedoc i plan to have a preview action w the fully rendered page and a save report button our users will access those static files later i will save the path to the dbany suggestions for how to do this i am as far as creating a file and saving it but i am not sure how to get my rendered view into it bonus points if anyone knows how to save it up to s3 many thanks,['ruby-on-rails'] +25690,are there any widespread modern java coding conventions suns code conventions for the java programming language was last updated april 19 ten years later a lot has changed in the language as well as general usage patterns are there more up to date widely adopted standardsmost guidelines omit specifying file encoding and line endings sun recommends mixed tabs and spaces the eclipse ide defaults to eclipses standard which is tabs only the maven style guide is spaces only many style guides such as jboss follow suns guidelines but prefer kr braces instead of otbs each apache project has it is own style guide with slight differences between each one,['java'] +25703,can an xcode static library require linkage with a dynamic library i have created a static library in xcode that requires several dynamic libraries eg libsqlite30dylib i can create an application that is dependent upon my static library using crossproject references in xcode but it seems that i have to manually add all of the required dynamic libraries to each of my application projects to get them to linkis there any way to configure a static library project in xcode so that dependent applications will automatically link against whatever dynamic libraries it requiresi tried adding the dynamic libraries to the list of frameworks in my static library project but this seemed to have no effect,['iphone'] +25707,how to trigger an event on payment received in magento greetings in magento i want to trigger an event once an order has been set to processing by gateway confirmation or manually that example if a general customer id 1 spends over 100 and the payment has been confirmed set his group id to 4 silver vip which by promotion rule gets 2 thiscount globallyi would give a bounty to this but i would like the answer before 2 days o oedit the answer i received so far is only a partial answer also i find the links very confusing i am not clear on what is the minimal setup what do i have to configure create etc also i am trying to find out how to get the paying customers idmodel,['php'] +25720,why is systemwebhttputilityurlencode giving namespace name does not exist in visual c 2008 i am trying to encode a url using the httputilityurlencode method why am i getting the type or namespace name httputility does not exist in the namespace systemweb are you missing an assembly referenceerror i am using visual c 2008 express editionthe code i am using is simplisticusing systemusing systemtextusing systemwindowsformsusing systemnetusing systemiousing systemwebnamespace lincr public partial class frmmain form public frmmain initializecomponent private void cmdshorten clickobject sender eventargs e webrequest wrurl stream objstream wrurl webrequestcreate systemwebhttputilityurlencodetxturltext modeapifull1 objstream wrurlgetresponsegetresponsestream streamreader objsreader new streamreaderobjstream textbox1text objsreaderreadtoendtostring,['c#'] +25734,logoff user when browser tab page is closed aspnet mvc in one of the aspnet mvc apps we would like to logoff the user automatically if he closes the browser tab in which the app is openedwe are using the following code when he authenticates formsauthenticationsetauthcookieusername falseas of now if we closes the browser window and relaunch it users are asked to authenticate again but we want to ask users to authenticate again if they close the tab and try to access any of the website urls,['asp.net'] +25737,difference between delegateinvoke and delegate delegate void delegatetestdelegatetest deltestwhats the difference between calling deltestinvoke and deltest both would execute the delegate on the current thread right,['c#'] +25738,crossplatform crash handler i am looking for a crossplatform crash handler google breakpad looks promising but it is sorely lacking any documentation and requires a reasonable amount of fiddling to actually get goingwhat is a better alternative all i need is the ability to reliably record crash dumps stack traces and cpu information at the time of a crash alternatively what is the experience using google breakpad has it been great or horrible,['c++'] +25752,checking customerrors turned on in code is it possible to check weather custom errors is turned on or off in the code on web application runtime,['c#'] +25753,whats the difference between keydown and keypress in net what is the difference between the keydown and keypress events in net,['.net'] +25754,how do i deal with a classnotloadedexception while debugging so i am remotely debugging a javajboss application in eclipse stepping through line by line at one point an array of gridsquare objects gridsquare is a fairly simple standalone class contains a few properties and methods is created by a method call iegridsquare squares thisthegridgetsquares14 18 220 2while when i actually execute the code the squares array does get populated with gridsquare objects i get something odd when stepping through the code and debugging at a breakpoint on the line immediately following the assignment shown above if i try to view the squares array instead of a value i get thisorgeclipsedebugcoredebugexception comsunjdiclassnotloadedexception type has not been loaded occurred while retrieving component type of arrayanyone know what that is about,['java'] +25762,how to output unicode string to rtf using c i am trying to output unicode string into rtf format using c and winformsfrom wikipediaif a unicode escape is required the control word you is used followed by a 16bit signed decimal integer giving the unicode codepoint number for the benefit of programs without unicode support this must be followed by the nearest representation of this character in the specified code page for example u1576 would give the arabic letter beh specifying that older programs which do not have unicode support should render it as a question mark insteadi do not know how to convert unicode character into unicode codepoint u1576 conversion to utf 8 utf 16 and similar is easy but i do not know how to convert to codepoint scenario in which i use thisi read existing rtf file into string i am reading templatestringreplace token with myunicodestring template is populate with datawrite result into another rtf fileproblem arise when unicode characters arrived,['c#'] +25766,aspnet mvc caching scenario i am still yet to find a decent solution to my scenario basically i have an aspnet mvc website which has a fair bit of database access to make the views 23 queries per view and i would like to take advantage of caching to improve performancethe problem is that the views contain data that can change irregularly like it might be the same for 2 days or the data could change several times in an hourthe queries are quite simple select from where and not huge joins each one returns on average 2030 rows of data with about 10 columnsthe queries are quite simple at the sites current stage but over time the owner will be adding more data and the visitor numbers will increase they are large at the moment and i would be looking at caching as traffic will mostly be coming from google adwords etc and fast loading pages will be a benefit apparentlythe site will be hosted on a microsoft sql server 2005 database but can upgrade to 2008 if requireddo i eitherset the caching to the minimum time an item does not change for eg cache for say 3 mins and tell the owner that any changes will take upto 3 minutes to appearfind a way to force the cache to clear and reprocess on changes eg if the owner adds an item in the administration panel it clears the relevant cachesforget caching all togetheror is there an option that would be suit this scenario,['c#'] +25776,when should i use implicit casting when is it safe to use implicit castinguse case i am working with a set of com objects that need to be taken care of specially marshalreleasecomobject is it ok to create a wrapper class that implicitly converts back to the actual com object wrappedwhat are some situations when i should not use implicit casting,"['c#', '.net']" +25781,unit testing is it bad form to have unit test calling other unit tests i have a unit test called testmakeavalidcall it tests my phone app making a valid calli am about to write another test called testshowcallmessage that needs to have a valid call made for the test is it bad form to just call testmakeavalidcall in that testfor reference this is my testmakeavalidcall test testmethod public void testmakeavalidcall arrange phoneincall false phonecurrentnumber stub the call to the database dataexpectx xgetwhitelistdata returnfilltestobjectsgetsingleentrywhitelist get some bogus data string phonenumber filltestobjectsgetsingleentrywhitelist firstphonenumber stub th call to makecall so that it looks as if a call was made phoneexpectx xmakecallphonenumber whencalledinvocation phonecurrentnumber phonenumber phoneincall true act select the phone number devicecontrolformselectednumber phonenumber press the call button to make a call devicemediatorcallbuttonpressed assert assertistruephoneincall assertistruephonecurrentnumber phonenumber,['c#'] +25791,sending user to their browsers home page using javascript is it possible to get a browsers home page using javascript i would like to place a link on a page that goes to the home page set in the browser,['javascript'] +25799,php curl retrieving server ip address i am using php curl to send a request to a server what do i need to do so the response from server will include that servers ip address,['php'] +25805,databasesql how to store longitudelatitude data performance question i have a database of houses that have geolocation data longitude latitudewhat i want to do is find the best way to store the locational data in my mysql v5024a using innodb databaseengine so that i can perform a lot of queries where i am returning all the home records that are between x1 and x2 latitude and y1 and y2 longituderight now my database schema ishomes geolat float 106geolng float 106and my query isselect where geolat between x1 and x2and geolng between y1 and y2is what i described above the best way to store thelatitude and longitude data in mysql using float 106 and separating out the longitudelatitude if not what is there exist float decimal and even spatial as a data typeis this the best way to perform thesql from a performance standpoint if not what isdoes using a different mysqldatabaseengine make senseupdate still unansweredi have 3 different answers below one person say to use float one person says to use int one person says to use spatialso i used mysql explain statement to measure the sql execution speed it appears that absolutely no difference in sql execution result set fetching exist if using int or float for the longitude and latitude data typeit also appears that using the between statement is significantly faster than using the or sql statements it is nearly 3x faster to use between than to use the and statementwith that being said i still am unceratin on what the performance impact would be if using spatial since it is unclear to me if it is supported with my version of mysql running v5024 as well as how i enable it if supportedany help would be greatly appreacited,"['sql', 'mysql']" +25818,string concatenation vs string buffers in javascript i was reading this book professional javascript for web developers where the author mentions string concatenation is an expensive operation compared to using an array to store strings and then using the join method to create the final string curious i did a couple test here to see how much time it would save and this is what i got somehow the firefox usually produces somewhat similar times to both ways but in ie string concatenation is much much faster so can this idea now be considered outdated browsers probably have improved since,['javascript'] +25824,django flush response i am sending an ajax request to a django view that can potentially take a lot of time it goes through some welldefined steps however so i would like to print status indicators to the user letting it know when it is finished doing a certain thing and has moved on to the nextif i was using php it might look like this using the flush functiondo somethingprint done doing somethingflushdo something elseprint done doing something elseflushhow would i go about doing the same with django looking at the documentation i see that httpresponse objects have a flush method but all it has to say is that this method makes an httpresponse instance a filelike object i am not sure that is what i want i am having a hard time wrapping my head around how this could be done in django since i have to return the response and do not really have a control of when the content goes to the browser,['python'] +25830,in objectivec how does alloc know how much memory to allocate let us say i have a class declared asclass someclassinterface someclass nsobject nsstring mystring nsstring yourstringendand later in some other code i saysomeclass myclass someclass alloc inithow does someclass know how much memory to allocate given that it did not override alloc presumably it needs storage for the ivars mystring and yourstring but it is using alloc inherited from nsobject is there reference material that covers these details,['objective-c'] +25838,state machines tutorials i am just wondering if anyone know of some good tutorials on the internet for developing state machines or ebooksi am starting working on state machines and just need something general to get me started,['c'] +25860,linux ide with proper support for stl debugging i am looking for a linux ide with support for stl debuggingthe problem is that with eclipse cdt if i inspect the vector after the push backint main vectorstring v vpush backblah return 0i get something hostile likestd vector basestdbasic stringchar stdchar traitschar stdallocatorchar stdallocatorstdbasic stringchar stdchar traitschar stdallocatorchar m impl stdallocatorstdbasic stringchar stdchar traitschar stdallocatorchar gnu cxxnew allocatorstdbasic stringchar stdchar traitschar stdallocatorchar no data fields no data fields m start 0x1fee040 m finish 0x1fee048 m end of storage 0x1fee048 no data fieldsinstead of something likevectorblahor something similaris there an alternative idedebugger for linux that provides better stl support,['c++'] +25868,c redefinition header files winsock2h how do i prevent from including header files twice the problem is i am including the in myclassh and then i am including myclassh in many files so it includes multiple times and redefinition error occurs how to preventi am using pragma once instead of include guards and i guess that is finemyclassh myclasshpragma onceinclude winsock2hclass myclass methodspublic myclassunsigned short port virtual myclassvoidedit few of the errors i am gettingcprogram filesmicrosoft sdkswindowsv60aincludews2defh91 warning c4005 af ipx macro redefinition cprogram filesmicrosoft sdkswindowsv60aincludewinsockh460 see previous definition of af ipxcprogram filesmicrosoft sdkswindowsv60aincludews2defh124 warning c4005 af max macro redefinition cprogram filesmicrosoft sdkswindowsv60aincludewinsockh479 see previous definition of af maxcprogram filesmicrosoft sdkswindowsv60aincludews2defh163 warning c4005 so dontlinger macro redefinition cprogram filesmicrosoft sdkswindowsv60aincludewinsockh402 see previous definition of so dontlingercprogram filesmicrosoft sdkswindowsv60aincludews2defh206 error c2011 sockaddr struct type redefinition cprogram filesmicrosoft sdkswindowsv60aincludewinsockh485 see declaration of sockaddrcprogram filesmicrosoft sdkswindowsv60aincludews2defh384 error c2143 syntax error missing before constantcprogram filesmicrosoft sdkswindowsv60aincludews2defh384 error c2143 syntax error missing before constantcprogram filesmicrosoft sdkswindowsv60aincludews2defh384 error c2059 syntax error constantcprogram filesmicrosoft sdkswindowsv60aincludews2defh437 error c2143 syntax error missing before cprogram filesmicrosoft sdkswindowsv60aincludews2defh437 error c4430 missing type specifier int assumed note c does not support defaultintcprogram filesmicrosoft sdkswindowsv60aincludews2defh437 error c4430 missing type specifier int assumed note c does not support defaultintcprogram filesmicrosoft sdkswindowsv60aincludews2defh518 warning c4005 in classa macro redefinition cprogram filesmicrosoft sdkswindowsv60aincludewinsockh287 see previous definition of in classacprogram filesmicrosoft sdkswindowsv60aincludews2defh524 warning c4005 in classb macro redefinition cprogram filesmicrosoft sdkswindowsv60aincludewinsockh293 see previous definition of in classbcprogram filesmicrosoft sdkswindowsv60aincludews2defh530 warning c4005 in classc macro redefinition cprogram filesmicrosoft sdkswindowsv60aincludewinsockh299 see previous definition of in classccprogram filesmicrosoft sdkswindowsv60aincludews2defh541 warning c4005 inaddr any macro redefinition cprogram filesmicrosoft sdkswindowsv60aincludewinsockh304 see previous definition of inaddr anycprogram filesmicrosoft sdkswindowsv60aincludews2defh543 warning c4005 inaddr broadcast macro redefinition cprogram filesmicrosoft sdkswindowsv60aincludewinsockh306 see previous definition of inaddr broadcastcprogram filesmicrosoft sdkswindowsv60aincludews2defh577 error c2011 sockaddr in struct type redefinition cprogram filesmicrosoft sdkswindowsv60aincludewinsockh312 see declaration of sockaddr incprogram filesmicrosoft sdkswindowsv60aincludewinsock2h132 error c2011 fd set struct type redefinition cprogram filesmicrosoft sdkswindowsv60aincludewinsockh68 see declaration of fd setcprogram filesmicrosoft sdkswindowsv60aincludewinsock2h167 warning c4005 fd set macro redefinition cprogram filesmicrosoft sdkswindowsv60aincludewinsockh102 see previous definition of fd setcprogram filesmicrosoft sdkswindowsv60aincludewinsock2h176 error c2011 timeval struct type redefinition cprogram filesmicrosoft sdkswindowsv60aincludewinsockh1 see declaration of timevalcprogram filesmicrosoft sdkswindowsv60aincludewinsock2h232 error c2011 hostent struct type redefinition cprogram filesmicrosoft sdkswindowsv60aincludewinsockh167 see declaration of hostentcprogram filesmicrosoft sdkswindowsv60aincludewinsock2h245 error c2011 netent struct type redefinition cprogram filesmicrosoft sdkswindowsv60aincludewinsockh180 see declaration of netentcprogram filesmicrosoft sdkswindowsv60aincludewinsock2h252 error c2011 servent struct type redefinition cprogram filesmicrosoft sdkswindowsv60aincludewinsockh187 see declaration of serventcprogram filesmicrosoft sdkswindowsv60aincludewinsock2h264 error c2011 protoent struct type redefinition cprogram filesmicrosoft sdkswindowsv60aincludewinsockh199 see declaration of protoent,['c++'] +25878,matching a value to multiple columns in one statement from a table using mysql i am working with a table in mysql that contains the following columnsid january february march april etcthe data in the table looks like thisaa 0 0 1 0ab 1 0 1 0ac 1 1 0 0ad 1 1 1 0to query it i could easily do thisselect from table where january 1 and february 1the result would beac 1 1 0 0ad 1 1 1 0i want to know if there is a way to do it like thisselect from table where tablecolumns 1i want to use table columns in expression without actually specifying the names manually typing them outbonus 1 questioncould it be done using matchagainst like thisselect from tablewhere match somehowgetthetablecolumnsineedhere against 1 in boolean modethanks for your time,"['sql', 'mysql']" +25884,how to add folder to assembly search path at runtime in net my dlls are loaded by a thirdparty application which we can not customize my assemblies have to be located in their own folder i can not put them into gac my application has a requirement to be deployed using xcopywhen the root dll tries to load resource or type from another dll in the same folder the loading fails filenotfoundis it possible to add the folder where my dlls are located to the assembly search path programmatically from the root dll i am not allowed to change the configuration files of the application,['.net'] +25896,file open is this bad python style to read contents of a filedata openfilename rreadthe open file immediately stops being referenced anywhere so the file object will eventually close and it should not affect other programs using it since the file is only open for reading not writingedit this has actually bitten me in a project i wrote it prompted me to ask this question file objects are cleaned up only when you run out of memory not when you run out of file handles so if you do this too often you could end up running out of file descriptors and causing your io attempts at opening files to throw exceptions,['python'] +25901,how can i have wpf use one window style for debug mode and another for release mode i have two different styles for my windowregular window has title bar and can be movedresizedfixed window has no title bar and is fixed at the center of the screenthe window is too wide for either of the monitors on my development machine but it is a perfect fit for the targetinstall machine so when debugging i need to be able to move the window so i can see everything on it but when i release the app i need it to run in full screen mode like a powerpoint app in projector modeis there any way to set the style property of the window based on whether i am compiling in debug vs release mode i was thinking i might be able to use a binding but i am not quite sure how to implement it,['c#'] +25906,how to verify a jar signed with jarsigner programmatically i am wanting to sign a jar using jarsigner then verify it using a java application which does not have the signed jar as part of it is classpath ie just using a filesystem location of the jarnow my problem is getting the signature file out of the jar is there a simple way to do thisi have had a play with the inflater and jar inputstreams with no luckor is this something that can be accomplished in a better waythanks,['java'] +25913,type casting an object using a type object in c this one has proven to be a little tricky for me so far i am wondering if it is possible to type cast an object using a systemtype objecti have illustrated below what i meanpublic interface idataadapter object transformobject input type getoutputtypepublic class somerandomadapter idataadapter public object transformobject input string output do some stuff to transform input to output return output public type getoutputtype return typeofstring later when using the above methods i would like to be able to govar output ttransforminput as tgetoutputtypethe above is a generic interface which is why i am using object for the types,['c#'] +25918,good resources for learning objectivec i have developed for a number of years in java primarily for linux and windows during my undergrad and grad school times i also did quite a bit in c and c i have recently in the last year and a half started using primarily apple computers at home and am interested in exploring their xcode development environment i am interested in learning how to use the cocoa interface etc however i know nothing or next to nothing about objectivec i am aware it is a pure superset of c however i am interested in some resources for learning itin the past to teach myself concepts of swing for java i have used oreilly books such as the swing bible java swing by marc loy et al is there a similar book for objectivec or a book that is really good to learn from i would prefer if it was fairly technical had examples etc has anyone else attempted to learn objectivec this way are there any specific things i should look atjust to note yes i do have kr i have read it too many times to count and i am aware of c syntax it has been a while but i do remember large amounts of it i did see this question but i did not see any particular resources mentioned simply some general statements about learningthanks,['objective-c'] +25921,can jquery ui and jquery tools work together can jquery ui and jquery tools work together ie if i include both libraries on one page will it still work,['jquery'] +25926,how to customize tableview separator in iphone by default there is a single line separator in uitableviewbut i want to put my customized line as a separatoris it possible how,['iphone'] +25931,get information about the source of an event with jquery a function is bound to an event for many objects one of those objects fires the event and jquery kicks in how do i find out who fired the event inside the javascript functioni have tried using function nameevent and poking at event but i get data is null or not an objectheres my code right nowscript typetextjavascript documentreadyfunction openingbindclick functionevent code to populate eventdata since right now the tags do not hold the infothey will eventually with an xhtml custom namespace eventdatabuilding student center eventdataroom pacific ballroom a eventdatas time 9152009 800 eventdatae time 9152009 10 indicatepreferencebyclickevent function indicatepreferencebyclickevent alerti got clicked and all i got was this alert box leftloadreservespacepreferencebyclick building eventdatabuilding room eventdataroom s time eventdatas time e time eventdatae time script,['jquery'] +25934,very simple c csv reader i would like to create an array from a csv filethis is about as simple as you can imagine the csv file will only ever have one line and these valuesdevice signalstrength location time agei would like to put these values into one dimensional arrayi have tried some examples but they have all been more complicated than required,['c#'] +25946,how to pull up a uikeyboard without a uitextfield or uitextview i am currently developing an opengl es game for the iphone and ipod touch i was wondering how i can easily pull up the uikeyboard is there an official documented possibility to pull up a uikeyboard without using a uitextfield of uitextview,['iphone'] +25950,javascript replacing the escape character in a string literal i am trying to replace the backslash escape character in a javascript string literal i need to replace it with a double backslash so that i can then do a redirectvar newpath filecfunstuffbuildtoolsviewerhtmlreplacegwindowlocation newpathhowever it seems to have no result i do not have the option of properly escaping the backslashes before they are handled by javascripthow can i replace with so that javascript will be happythanksderek,['javascript'] +25953,how to extract a string between 2 other strings in python like if i have a string like str1 iwanttomasterpythonif i want to extract py from the above string i writeextractedstring foomasterthoni want to do all this because i am trying to extract lyrics from an html page the lyrics are written like div class lyricbox lyrics goes heredivany suggestions on how can i implement,['python'] +25963,castle windsor constructor resolution order just wondering how castle windsor determines which constructor to resolve when there are multiple constructors presentcheersanthony,"['c#', '.net']" +25966,how do you deal with missing data using numpyscipy one of the things i deal with most in data cleaning is missing values r deals with this well using its na missing data label in python it appears that i will have to deal with masked arrays which seem to be a major pain to set up and do not seem to be well documented any suggestions on making this process easier in python this is becoming a dealbreaker in moving into python for data analysis thanksupdate it is obviously been a while since i have looked at the methods in the numpyma module it appears that at least the basic analysis functions are available for masked arrays and the examples provided helped me understand how to create masked arrays thanks to the authors i would like to see if some of the newer statistical methods in python being developed in this years gsoc incorporates this aspect and at least does the complete case analysis,['python'] +25971,programmable usb dongles where can i buy a programmable usb dongle that supports c as a development language,['c'] +25978,can i code same functionality for 2 id elements in one click function is there any method to have the same coding for the click function of two different id elements in one click functionfor examplei have two link elements with ids myformstabsubmitted and formstatussubmitted both the link is of same functionality when i click both these links the same div elementsubmitted is showedand other divs are hiddenso instead of writing two click functions one for myformstabsubmitted and another for formstatussubmitted can i have one click function for both like myformstabsubmitted formstatussubmittedclickfunctionallmyformshidedraftedmyformshidesubmittedmyformsshowmyformstabfindselectedremoveclassmyformstabsubmittedaddclaselected,['jquery'] +25985,how do you call a method from the view in rails let us say i did thisscriptgenerate controller homeand in the home controller made a the methoddef say puts you are hereendhow would i call that method in the indexhtmlerbwhen learning ruby it just said to run the whateverrb in the terminalto run what ever code you wrote within that file just curious on howthat would work with rails,"['ruby-on-rails', 'ruby']" +25986,how to get constructor as methodinfo using reflection the constructor looks like thispublic nameandvaluestring name string valuei need to get it as a methodinfo using reflection it tried the following but it does not find the constructor getmethod returns null methodinfo constructor typeofnameandvaluegetmethodctor new typeofstring typeofstring what am i doing wrong,"['c#', '.net']" +25988,what error codes can occur with copyfileex i am writing some c code that needs to call the copyfileex function the documentation for copyfileex like most other win32 functions saysif the function fails the return value is zero to get extended error information call getlasterrorwhich is all well and good however does anyone know where i can find a list of the error codes that a specific api function may return via getlasterror in this case i want to handle different error conditions in different ways but without a list of the error codes for this function i am going to be reduced to generating the error conditions i want to handle just to see what error code is prodcued or going through the system error codes from numbers 0 to 159 trying to guess which ones might applyedit here is a little more context to help explain the issue and why i want to know if there is a definitive list of error codes that can be returned by a function anywherethe code will be used as part of a windows service so while there are users they would not always be there to respond to errors i need to be able to thistinguish between errors that do not need reporting every time if a file is locked i am just to retry it again later if i do not have permissions to read a particular file i can log the problem and carry on if the destination directory is unreadable or is full then i want the service to stop and to trigger a reporting process that will atrract the attention of a userwithout a comprehensive list of the ways that copyfileex can fail i am finding it hard to do this,['c++'] +25990,performance concurrenthashmap vs hashmap how is the performance of concurrenthashmap compared to hashmap especially get operation i am especially interested for the case of only few items in the range between maybe 050is there any reason not to use concurrenthashmap instead of hashmapi know that null values are not allowedupdatejust to clarify obviously the performance in case of actual concurrent access will suffer but how compares the performance in case of no concurrent access,['java'] +26001,eclipse amusthavea development toolsplugins for php according to this post i ask titlewhich are your favorite php coding related eclipse plugins without you cannot live whyi list my own plugins of choiceeclipse pdt mylyn subclipsewhich are yours,['php'] +26002,how can i make a multipartformdata post request using java in the days of version 3x of apache commons httpclient making a multipartformdata post request was possible an example from 2004 unfortunately this is no longer possible in version 40 of httpclientfor our core activity http multipart is somewhat out of scope wed love to use multipart code maintained by some other project for which it is in scope but i am not aware of any we tried to move the multipart code to commonscodec a few years ago but i did not take off there oleg recently mentioned another project that has multipart parsing code and might be interested in our multipart formatting code i do not know the current status on that is anybody aware of any java library that allows me to write an http client that can make a multipartformdata post requestbackground i want to use the remote api of zoho writer,['java'] +26005,android content provider database leak issue i am writing a content provider for this application and in my content provider i am opening a database connection running a query and returning the cursor of results to the calling program if i close this database connection in the provider the cursor has no results if i leave it open i get leak found errors in my ddms log what am i missing here whats the clean proper way to return a cursor of database results,"['java', 'android']" +26011,ie7 cause of text empty text node i am using the ie web developer toolbar to troubleshoot an issue a blank white space is appearing below a list item and i cannot logically figure out why using the web dev toolbar i see that in example 1 below a text empty text node is being output below text google ironically in the second with a space manually inserted after the word google that text node no longer appears it would make complete sense to me if the results were reversed any ideas what may cause this odd behavior note this is occuring in ie7 but not ie8lia hrefwgooglecomgoogleali empty text node appears at endlia hrefwgooglecomgoogle ali no empty text nodeupdate ok i have narrowed down this issue basically it seems like there is a conflict between some of the attributes i am using i need the a tags to be thisplay as block so they will wrap correctly when there are multiple lines but i also need no empty space in between the items i am not quite sure why that empty space solves the problem and would prefer not to just hack itdoctype html public w3cdtd xhtml 10 transitionalen htmlheadstyle typetextcssa thisplayblockli zoom 1style headbody ul li div stylebackgroundcolorblue a hrefimg src allimageslogogifa div ul li stylebackgroundcolorreda hrefoneali li stylebackgroundcolorgreena hreftwo ali li stylebackgroundcoloryellowa hrefthreeali ul li ulbodyhtml,['css'] +26019,pytz localize vs datetime replace i am having some weird issues with pytzs localize function sometimes it wouldnt make adjustments to the localized datetimelocalize behaviour tzdsttzinfo africaabidjan lmt1 day 234400 std ddatetimedatetime2009 9 2 14 45 42 91421 tzlocalizeddatetimedatetime2009 9 2 14 45 42 91421 tzinfodsttzinfo africaabidjan gmt0 std tznormalizetzlocalizeddatetimedatetime2009 9 2 14 45 42 91421 tzinfodsttzinfo africaabidjan gmt0 stdas you can see time has not been changed as a result of localizenormalize operationshowever if replace is used dreplacetzinfotzdatetimedatetime2009 9 2 14 45 42 91421 tzinfodsttzinfo africaabidjan lmt1 day 234400 std tznormalizedreplacetzinfotzdatetimedatetime2009 9 2 15 1 42 91421 tzinfodsttzinfo africaabidjan gmt0 stdwhich seems to make adjustments into datetime question is which is correct and why others wrongthanks,['python'] +26031,nested appconfig webconfig files is it possible to have two appconfig files where one appconfig serves as a container for second nested appconfig file i would like to reference specific sections of a nested file from the outer onewhy i need this is because of source control issue for detailed description see thisany other solution for the root problem is greatly appreciated,['.net'] +26033,list of best practice mysql data types is there a list of best practice mysql data types for common applications for example the list would contain the best data type and size for id ip address email subject summary description content url date timestamp and human readable geo points media height media width media duration etcthank you,"['sql', 'mysql']" +26041,setting uilabel font through code generates error iphone see following code carefully because it works perfectly try to add in your application it will work voidviewdidload super viewdidload title label tipuilabel tmpuilabel alloc initwithframecgrectmake50 50 200 200 tmptextcoloruicolor colorwithred1402550 green1050255 blue1280255 alpha10tmp setfontuifont fontwithnamearial size18 tmptextsagartmpbackgroundcoloruicolor clearcolor selfview addsubviewtmp tmp releasenow see following code carefully because it does not work see there is nothing difference between both of these code voidviewdidload super viewdidload title label tipuilabel tmpuilabel alloc initwithframecgrectmake50 50 200 200 tmptextcoloruicolor colorwithred1402550 green1050255 blue1280255 alpha10tmp setfontuifont fontwithnamearial black size18 tmptextsagartmpbackgroundcoloruicolor clearcolor selfview addsubviewtmp tmp releasei have just mentioned arial black instead arial however it is not workingis it because of iphone does not support arial black i would like to know why it is not workinghow many different kind of font does iphone supportis there any listhow to set a font name to a uilabel or to any control font which has space within there name thanks in advance for sharing your knowledge with me,['iphone'] +26045,checking string has balanced parentheses i am reading the algorithm design manual second edition and this is from an exercise question quoting the questiona common problem for compilers and text editors is determining whether the parentheses in a string are balanced and properly nested for example the string contains properly nested pairs of parentheses which the strings and do not give an algorithm that returns true if a string contains properly nested and balanced parentheses and false if otherwise for full credit identify the position of the first offending parenthesis if the string is not properly nested and balancedquestion is under stacksqueues and lists category here is what i wrote in cconst char leftparenthesis const char rightparenthesis bool areparenthesesbalancedstring str out int errorat var items new stackintstrlength errorat 1 for int i 0 i strlength i char c stri if c leftparenthesis itemspushi else if c rightparenthesis if itemscount 0 errorat i 1 return false itemspop if itemscount 0 errorat itemspeek 1 return false return truethis works well but i am not sure that this is the right method to approach this problem any better ideas are welcome,['c#'] +26048,what is the best way to clean up an object in java we do not have any destructor in java as we have in c q1 how should we clean up any object in javaq2 is there any alternative to a finally blockq3 sometimes we have to call explicitely initializationtermination of a third party code from our class egpublic clas myclass public myclass thirdpartyinitialize protected void finalize thirdpartyterminate is this the correct way,['java'] +26050,what is ansi as utf8 and how can i make fputcsv generate utf8 wbom i made a php script that generates csv files that were previously generated by another processand then the csv files have to be imported by yet another processthe import of the old csv files works fine but but when importing the new csv files there are issues with special characterswhen i open old csvs with notepad it says the encoding is utf8 and when i open the new csvs with it it says their encoding is ansi as utf8whats the difference of the twoand how can i make fopen and fputcsv use the pure utf8 encodingthanks,['php'] +26052,add variables to tuple i am learning python and creating a database connectionwhile trying to add to the db i am thinking of creating tuples out of information and then add them to the db what i am doingi am taking information from the user and store it in variables can i add these variables into a tuple can you please help me with the syntaxalso if there is an efficient way of doing this please shareeditlet me edit this question a biti only need the tuple to enter info into the db once the information is added to the db should i delete the tuple i mean i do not need the tuple anymore,['python'] +26063,how can a child thread notify a parent thread of its statusprogress i have a service responsible for many tasks one of which is to launch jobs one at a time on a separate thread threadjob child these jobs can take a fair amount of time and have various phases to them which i need to report backever so often a calling application requests the status from the service getstatus this means that somehow the service needs to know at what point the job child thread is at my hope was that at some milestones the child thread could somehow inform setstatus the parent thread service of its status and the service could return that information to the calling applicationfor example i was looking to do something like thisclass serviceprivate thread threadjobprivate int job statuspublic service job status idle public void runtask threadjob new threadnew threadstartperformwork threadjobisbackground true threadjobstart public void performwork setstatusstarting do some work setstatusphase i do some work setstatusphase ii do some work setstatusphase i do some work setstatusfinished private void setstatusint status job status status public string getstatus return job status so when a job needs to be performed runtask is called and this launches the thread threadjob this will run and perform some steps using setstatus to set the new status at various points and finally finish now there is also function getstatus which should return the status whenever requested from a calling application using ipc this status should reflect the current status of the job running by threadjobso my problem is simple enoughhow can threadjob or more specifically performwork return to service the change in status in a threadsafe manner i assume my example above of setstatusgetstatus is unsafe do i need to use events i assume i cannot simply change job status directly should i use a lock if so on what,['c#'] +26081,using temporary using filesort a bad idea in mysql i am trying to optimize my mysql queries to avoid using temporary using filesort i could use some help first here is the explainhere is the queryselect pfmloginmavatar from profile friends pf members m where pffriend id mid and pfmember id 16586 order by mlastlogin desc limit 024mysql explain select pfmloginmavatar from profile friends pf members m where pffriend id mid and pfmember id 16586 order by mlastlogin desc limit 024 id select type table type possible keys key key len ref rows extra 1 simple pf ref member id indexfriend id index member id index 4 const 160 using where using temporary using filesort 1 simple m eq ref primarymember id privacy indexid last login index primary 4 mydbpffriend id 1 using where there are 2 tables involved profilefriends pf and members m this query is just trying to find the recent 24 friends for this particular member id recent means sort by lastlogin datethanks,['mysql'] +26092,how to retrieve users current city name how do you retrieve the users current city name,"['iphone', 'objective-c']" +26094,confusion over action delegate and lambda expressions private void stringactionstring astring method to be called returnprivate void testdelegatestatement1 does not work var stringaction new systemactionstringactiona string error method expectedprivate void testdelegatestatement2 does not work var stringaction new systemactionparam stringactiona string error systemargument does not take 1 arguments stringactionprivate void testdelegatestatement3 this is ok var stringaction new systemactionstringactioncaller stringactionprivate void stringactioncaller stringactiona stringi do not understand why testdelegatestatement3 works but testdelegatestatement1 fails in both cases action is supplied with a method that takes zero parameters they may call a method that takes a single parameter astring but that should be irrelevant they do not take a parameter is this just not possible to do with lamda expressions or am i doing something wrong,['c#'] +26103,how can i return a value from a thread in ruby if i have the following code threads 15each do i threads threadnew process xibin endthreadseach do t tjoin i would like to get the output of the process command nowendwhat do i have to do to get the output of the process command how could i create a custom thread so that i can accomplish this,['ruby'] +26111,c inheritancevtable questions update replaced the destructor example with a straight up method call example hiif i have the following codeclass apublic virtual void func0 a has a vtable now void func1class b public apublic void func0 afunc0 void func2is there a vtable in b b has no virtual functions but calls afunc0 from bfunc0does func1 reside in a vtable it is not virtualdoes func2 reside in a vtablewill the answers to the above be different if there was not a afunc0 call in bfunc0thanks,['c++'] +26112,aspnet user control page load fires before property is set this is driving me crazyi have a very simple user controlpublic int imageid set getprotected void page loadobject sender eventargs e do something with imageidand then i put this control on the page with listview within updatepanelasplistview idlistviewimages runatserver datasourceidsrc layouttemplate aspplaceholder iditemplaceholder runatserver layouttemplate itemtemplate mymycontrol imageid evalid idcippreview runatserver itemtemplateasplistviewthe problem is page load fires before aspnet sets imageid with debuggers help i found out that for some reason imageid in mycontrol is set but it happens only after page load has finished processing whats wrong,"['c#', 'asp.net']" +26116,jquery how do you get an image to fade in on load all i want to do is fade my logo in on the page loading i am new today to jquery and i cannot managed to fadein on load please help sorry if this question has already been answered i have had a look and try to adapt other answers for different question but nothing seems to work and its starting to frustrate me thanks code script typetextjavascript function loadfunction set the image hidden by default logohidefadein30 script link relstylesheet hrefchallengecss titleacme widgetstitle head body div idwrapper div idheader img idlogo srclogosmallerjpg div div idnav navigation div div idleftcol left col div div idrightcol div idheader2 header 2 div div idcentrecol body text div div idrightcol2 right col div div div idfooter footer div div bodyhtml,['jquery'] +26117,how datareader works i was thinking that the sqldatareader should not work if there is no connection to the sqlserveri experimented this scenario i execute the executereader then stop the sqlserver service and tried to iterate through the datareader what i expected was an exception but it gave the results one after the other ideally the datareader should read one row at a time from the stream that gets connected to the db server and which should throw an exception if we thisconnect the db serveri do not know what is it that i am missing here,"['c#', '.net', 'asp.net']" +26125,calculating factorial of large numbers in c in my c code i want to calculate the factorial for numbers in the range 1 to 100 for small numbers the function works but for bigger numbers for example 100 it returns incorrect result any ways to handle factorial of large numbers in c the compiler im using is gcc v433 my code is as follows include stdiohinclude mathhdouble print solutionintint mainvoid int no of inputsn int ctr 1 scanfdno of inputs read no of inputs do scanfdn read the input printf0fnprint solutionn ctr whilectr no of inputs return 0 double print solutionint n ifn 0 and 1 return 1 else return nprint solutionn1,['c'] +26154,why are alloc and init called separately in objectivec note i am relatively new to objectivec and am coming from java and phpcould someone explain to me why i always have to first allocate and then initialize an instancecould not this be done in the init methods like this myclassinit myclass instance myclass alloc instance setfoobla return instance myclassinitwithstringnsstringtext myclass instance myclass init instance setfootext return instanceis this just a relict from the old c days or is there something that i am not seeingi know this is not a problem as i could as well always call alloc and init but since it is a bit tedious i would like to at least know why i am doing iti am liking the expressiveness of the language so far but this is something that i want to fully understand in order to think the objectivec waythank you,['objective-c'] +26177,animating rows in an nstableview is there a simple way of animating rows in an nstableviewi would like to be able to do something like flash a row or fade out a rowessentially to provide a bit of visual feedback when rows are added or removededited to addi would had a quick look over google before posting this but i wanted to know if there was some way to do this that i would missed other than drawing and animating parts of the table view myself,['objective-c'] +26179,pil image resizing algorithm similar to firefoxs i am getting about the same bad looking resizing from all the 4 algorithms of pil data utilsfetch image imageopenstringiostringiodata imagesavehomeptarjanwtmpmetawardoriginalpng image imageopenstringiostringiodata imageresize3636 imageantialiassavehomeptarjanwtmpmetawardantialiaspng image imageopenstringiostringiodata imageresize3636 imagebilinearsavehomeptarjanwtmpmetawardbilinearpng image imageopenstringiostringiodata imageresize3636 imagebicubicsavehomeptarjanwtmpmetawardbicubicpng image imageopenstringiostringiodata imageresize3636 imagenearestsavehomeptarjanwtmpmetawardnearestpng image imageopenstringiostringiodata imagethumbnail3636 imageantialias imagesavehomeptarjanwtmpmetawardantialiasthumbpng image imageopenstringiostringiodata imagethumbnail3636 imagebilinear imagesavehomeptarjanwtmpmetawardbilinearthumbpng image imageopenstringiostringiodata imagethumbnail3636 imagebicubic imagesavehomeptarjanwtmpmetawardbicubicthumbpng image imageopenstringiostringiodata imagethumbnail3636 imagenearest imagesavehomeptarjanwtmpmetawardnearestthumbpng image imageopenstringiostringiodata imageconvertrgbresize3636 imageantialiassavehomeptarjanwtmpmetawardantialiasrgbpng image imageopenstringiostringiodata imageconvertrgbresize3636 imagebilinearsavehomeptarjanwtmpmetawardbilinearrgbpng image imageopenstringiostringiodata imageconvertrgbresize3636 imagebicubicsavehomeptarjanwtmpmetawardbicubicrgbpng image imageopenstringiostringiodata imageconvertrgbresize3636 imagenearestsavehomeptarjanwtmpmetawardnearestrgbpngbut the results look much worse that just resizing in firefoxhow can i get a similar effect to the firefox result using pil or another python image libraryedit hover your mouse to see what each image isit looks like the rgb and then antialis looks the best any other recommendationsfor reference this is the one that looked the best image imageopenstringiostringiodata imageconvertrgbresize3636 imageantialias,['python'] +26181,manually set updated at in rails i am migrating my old blog posts into my new rails blog and i want their updated at attribute to match the corresponding value on my old blog not the date they were migrated into my new rails bloghow can i do this when i set updated at manually it gets overridden by the before save callback,['ruby-on-rails'] +26183,php echo vs php short tags are they equal in safeness i was informed that usingfunction herewas less safe and that it slows down page load timesi am strictly biased to using echowhat are the advantagesthisadvantages,['php'] +26191,linq to sql get top 10 most ordered products i am wanting to grab the 10 most ordered products my tables look similar to thisproductproductid productnameorderedproductproductid orderidorderorderid dateorderedat the moment i have got the followingreturn from product in dbproducts from orderedproduct in dborderedproducts where orderedproductproductid productproductid select productorderbydescendingthistincttake10i have noted in the above query where i am uncertain of what to put how do i orderby the number of products that appear in the ordered products table,['sql'] +26211,how to install android market app on the emulator i am not able to access android market through emulator,['android'] +26214,difference between systemwebcache and httpcontextcurentcache what is the difference between systemwebcache and httpcontextcurentcache in which cases both are used,['asp.net'] +26227,how do i make the jdk the default jre i use eclipse with ant scripts and eclipse works well with the default jre installation on windows xpthe annoyance comes when i want to run ant scripts compiling with the javactag where it fails because there is no toolsjar in the classpathi have gotten the idea that if i could make the jdk become the default java on windows then i would have what i have today plus ant working out of the boxcan this be done what have i missed in the installation processedit i know of java home but that is tedious and error prone manually updating environment variables when a fresher jdk is available is not always something i remember edit i ended up figuring out how to make the javac task use the eclipse compiler ecjjar which works very nicelyedit maven also supports using the eclipse compiler but this appears to be very rarely used and with an old version of ecjjar i intend to look in to this at a later time edit using ecj with mavencompilerplugin 30 works very well and allows for building with a jre edit i had problems with the javadoc tool crashing when parsing bytecode generated by ecj,['java'] +26228,change uiview background color programmatically i have just created a new view based application and now i want to set the background color at the application startup rather then in ib i have found this code in a tutorialuiview view uiview alloc initwithframeuiscreen mainscreenapplicationframeview setbackgroundcoloruicolor greencolorbut my view is still whitehow do i make it workthanks in advance,['iphone'] +26232,using rsync to backup mysql i use the following rsync command to backup my mysql data to a machine within the lan network it works as expectedrsync avz mysql root roottestmei just want to make sure that this is the correct way to use rsynci will also like to know if the 5 minute crontab entry for this will work,['mysql'] +26239,python automatically initialize instance variables i have a python class that looks like thisclass process def init self pid ppid cmd fds reachable userfollowed by selfpidpid selfppidppid selfcmdcmd is there any way to autoinitialize these instance variables like cs initialization list it would spare lots of redundant code,['python'] +26251,c byte array comparison i have two byte arrays in c using net 30 what is the most efficient way to compare whether the two byte arrays contains the same content for each elementfor example byte array 0x1 0x2 is the same as 0x1 0x2 but byte array 0x1 0x2 and byte array 0x2 0x1 are not the same,"['c#', '.net']" +26253,why is qt looking for my slot in the base class instead of derived one i have my class x which inherits from qts class base i declared and defined void myslot slot in my class x and i am connecting some signal to this slot in xs constructor however when running my program i get an error message saying there is no such slot as void myslot in the class basewhy is the code generated by meta object compiler moc looking for my slot in the base class and not in my derived class,['c++'] +26258,systemlinqdynamic and datetime i am using systemlinqdynamic to do custom where clauses from an ajax call in net mvc 10it works fine for strings int etc but not for datetime i get the exception cannot compare string to datetime the very simple test code isitems itemswherestringformat 0 121 searchfield delimiter searchstringwhere searchfield will be for example start date and the data type is datetime delimiter is tried with nothing as well and searchstring will be 01jan2009 tried with 01012009 as well and items is an iqueryable from linqtosqlis there a way of specifying the data type in a dynamic where or is there a better approach it is currently already using some reflection to work out what type of delimiter is required,['c#'] +26273,httpwebrequest how to handle premature closure of underlying tcp connection i have a hard time figuring out if there is a way to handle potential connectivity problems when using nets httpwebrequest class to call a remote server specifically a rest web service from my investigations the behaviour of the webclient class is the same which is somewhat expected since it appears to only offer a more simple interface to the httpwebrequestfor simulation purposes i have written a very simple http server that does not behave according to the http 11 rfc what it does is it accepts a client connection then sends appropriate http 11 headers and a hello world payload back to the client and closes the socket the thread accepting client connections on the server side looks as follows private const string m defaultresponse htmlbodyh1hello worldh1bodyhtml private void listen while true using tcpclient clientconnection m listeneraccepttcpclient networkstream stream clientconnectiongetstream stringbuilder httpdata new stringbuilderhttp11 200 okrnserver ivyrncontenttype texthtmlrn httpdataappendformatcontentlength 0rnrn m defaultresponselength httpdataappendformatm defaultresponse threadsleep30 sleep to simulate latency streamwriteencodingasciigetbyteshttpdatatostring 0 httpdatalength streamclose clientconnectionclose since the http 11 rfc states that http 11 by default keeps connections alive and that a server must send a connection close response header if it wants to close a connection this is unexpected behaviour for the clientside the client uses httpwebrequest in the following way private static void sendrequestobject state webresponse resp null try httpwebrequest request httpwebrequestwebrequestcreate requesttimeout 50 10 datetime requeststart datetimenow resp requestgetresponse timespan requestduration datetimenow requeststart consolewritelineok request took intrequestdurationtotalmilliseconds ms catch webexception ex if exstatus webexceptionstatustimeout consolewritelinetimeout occurred else consolewritelineex finally if resp null respclose manualresetevent stateset the above method is queued via threadpoolqueueuserworkitemwaitcallback stateobject the manualresetevent is used to control queuing behavior so that not the entire thread pool gets filled up with waiting tasks since the httpwebrequest implicitly uses worker threads because it functions asynchronously internally to implement the timeout functionalitythe problem with all this is that once all connections of the httpwebrequests underlying servicepoint are used up ie closed by the remote server there will no new ones be opened up it does also not matter if the connectionleasetimeout of the servicepoint is set to a low value 10 seconds once the system gets into this state it will no longer function properly because it does not reconnect automatically and all subsequent httpwebrequests will time out now the question really is if there is a way to solve this by somehow destroying a servicepoint under certain conditions or closing underyling connections i did not have any luck with servicepointcloseconnectiongroup yet the method is also pretty undocumented in terms of how to properly use itdoes anybody have any idea how i could approach this problem,['c#'] +26274,mvc set selected value of selectlist how can i set the selectedvalue property of a selectlist after it was instantiated without a selectedvalueselectlist selectlist new selectlistitems id namei need to set the selected value after this stage,['c#'] +26279,httpmodule with aspnet mvc not being called i am trying to implement a sessionperrequest pattern in an aspnet mvc 2 preview 1 application and i have implemented an ihttpmodule to help me do thispublic class sessionmodule ihttpmodule public void inithttpapplication context contextresponsewriteinit contextendrequest context endrequest etcand i have put this into the webconfig systemweb httpmodules add namesessionmodule typemynamespacesessionmodule httpmodules systemwebserver modules runallmanagedmodulesforallrequeststrue remove namesessionmodule add namesessionmodule typemynamespacesessionmodule moduleshowever init never gets written to the page i am using the builtin vs web server cassini additionally i have tried putting breakpoints in the sessionmodule but they never break what am i missing,"['.net', 'asp.net']" +26284,who owns an nswindowcontroller in standard practice i am seeking further clarification after seeing i am writing a simple inventory management application for my nephews i have a table view that thisplays the contents of their library etc to add a new item to the library they click a button this button opens a new window prompting them the details of the item and validates the input when they click okall of that is working just fine however i have a question about the memory management to create the new window i use the following code ibactionaddnewitemidsender libraryitemeditorcontroller editorcontroller libraryitemeditorcontroller alloc initwithwindownibnamelibraryitemeditor editorcontroller showwindownil editorcontroller is leaked here it seemsi cannot release nor autorelease editorcontroller at the end of addnewitem because nothing else is referencing editorcontroller if i release it the window immediately thisappears i do however want the window controller to be released once its window is closed in apples window programming guide i read the followingif you want the closing of a window to make both window and window controller go away when it isnat part of a document your subclass of nswindowcontroller can observe nswindowwillclosenotification or as the window delegate implement the windowwillclose method and include the following line of code in your implementationself autoreleasei have used self autorelease in the windowwillclose method of the window controller this works and does not leak memory however it just feels ugly addnewitem looks like it is leaking memory and static analysis thinks so too i know that it is actually taken care of in windowdidclose but it just feels wrong further the window controller is now releasing itself without ever having retained itself this all goes against the memory management rules i have learnedmy other option is to put an ivar on the parent controller either an nswindowcontroller or an nsmutableset of nswindowcontrollers and then watch for the nswindowwillclosenotification in the parent controller and release it in response this is cleaner and is probably what i will do it is also a fair amount more work though which leads me to my questionsis watching for the nswindowdidclosenotification the standard way of doing this whats the standard way of managing nswindowcontrollers that are created and destroyed on demand is the self autorelease way the traditionallyrecommended option and it is only now that we have static analysis that this is a problem,['objective-c'] +26292,java gui alternatives i write applications in java and i am looking for ways to speedup gui programming binding frameworks help but the particular application i am working on now wouldnt benefit too much from that it does not thisplay a lot of data just a lot of ways to manipulate the data i feel like i spend way too much time writing boilerplate gui code like adding action listeners laying out components etc while i am not a c developer i have heard xaml works very well and have seen jaxx which appears to be similar to xaml i am also looking at the groovy swing builder it just seems like there are so many options maybe even too manycan anyone share their thoughts on alternatives to hand writing simple java ui codealso i would be interested in thiscussing how to migrate existing java swing code to use some of these optionsthanksjeff,['java'] +26293,embed mirc color codes into a c literal i am working on a simple irc bot in c and i cannot figure out how to embed the typical mirc control codes for boldcolor etc into string literalscan someone point me towards how to do this,['c#'] +26296,shadowing events in net in vbnet there is a keyword shadows let us say i have a base class called jedi and a derived class called yoda which inherits from jedi if i declare a method in jedi called forcepush and shadow that out in yoda then when calling the method on an instance of the yoda class it will ignore the base class implementation and use the derived class implementation however if i have an instance of yoda that was declared originally as of type jedi ie dim j as jedi new yoda and called the forcepush method on the instance it will use the jedi implementationnow let us say i have an event that is called usingforce which is raised when the forcepush method is called and i shadow the event out in the derived class this is because yoda has an interface iforcepowers that declares this event and each class raises it is respective event if i have an instance of yoda that is declared as type jedi like above and i put an event handler on the usingforce event of jedi and then the forcepush method is called in the yoda class will this event handler be reached,['.net'] +26303,how to convert a string to charsequence how to convert a string to charsequence in java,['java'] +26309,mvvm dynamic menu ui from binding with viewmodel i am new to wpf and mvvm i am working with a team on lob application we would like to have a dynamic menu control which creates the menu based on the logged in user profile in previous development scenarios namely aspnet we use to iterate through data which describes collection and generate menuitem dynamically in mvvm how would i do this can i separate xaml view from viewmodel which describes menu elementssolutionwith inputs from commentators i were able to bind menu dynamically with the data from viewmodel this article was of great help tooxamlhierarchicaldatatemplate datatypextype selfmenu itemssourcebinding pathchildren updatesourcetriggerpropertychanged contentpresenter contentbinding pathmenutext recognizesaccesskeytruehierarchicaldatatemplatemenu height21 margin0 namemainmenu verticalalignmenttop horizontalalignmentstretch itemssourcebinding pathmenuitems updatesourcetriggerpropertychanged itemcontainerstylestaticresource topmenuitems menubackground imagebrush imagesourcewpfmodulescomponentimagesmenubgjpg menubackgroundmenumenu data classpublic class menu viewmodelbase public menu isenabled true children new listmenu region menu properties private bool isenabled private string menutext private icommand command private ilistmenu children public string menutext get return menutext set menutext value baseonpropertychangedmenutext public bool isenabled get return isenabled set isenabled value baseonpropertychangedisenabled public icommand command get return command set command value baseonpropertychangedcommand public ilistmenu children get return children set children value endregion,['c#'] +26310,sizeof string literal the following codeinclude iostream using namespace stdint main const char const foo f const char bar b cout sizeofstring literal sizeof f endl cout sizeofconst char const sizeof foo endl cout sizeofconst char sizeof bar endloutputssizeofstring literal 2sizeofconst char const 4sizeofconst char 2on a 32bit os compiled with gccwhy does sizeof calculate the length of the space needed for the string literal does the string literal have a different type from char or char when given to sizeof,['c++'] +26322,why use i instead of i in cases where the value is not used anywhere else in the statement i am well aware that in cint somevalue iarrayi othervaluehas different effect compared toint somevalue iarrayi othervaluebut every once in a while i see statements with prefix increment in forloops or just by their ownfor int i 0 i count i do stuffor for int i 0 i count do some stuff if condition i else i 4 in the latter two cases the i looks like an attempt to produce smartylooking code am i overseeing something is there a reason to use i instead of i in the latter two cases,['c++'] +26338,abstract class mandatory constructor for child classes possible duplicatewhy canat i create an abstract constructor on an abstract c class how can i write one abstract class that tells that is mandatory for the child class to have one constructorsomething like thispublic abstract class fatherclass public childconstructorstring val1 string val2 someother codepublic class childclass1 fatherclass public childclass1string val1 string val2 do something update 1if i cannot inherit constructors how can i prevent that someone will not forget to implement that specific child class constructor,"['c#', '.net']" +26356,how to use jaxbelement in web service i am developing a web service using wcfit is an interoperable web servicenow i am consuming this web service from a java clientnow when i created the proxy classit created all getter setter methodnow in that proxy class it created a jaxbelement fieldi searched for it in jdk api for itand found constructorjaxbelementqname name classt declaredtype class scope t valuei am finding it hard to use this constructorif anyone can please show me how to use this constructorplease explain all the parameter and if there is a good tutorial on net for using it,['java'] +26359,jquery each backwards i am using jquery to select some elements on a page and then move them around in the dom the problem i am having is i need to select all the elements in the reverse order that jquery naturally wants to select them for exampleul liitem 1li liitem 2li liitem 3li liitem 4li liitem 5liuli want to select all the li items and use the each command on them but i want to start with item 5 then item 4 etc is this possible,"['javascript', 'jquery']" +26364,detect program termination c windows i have a program that has to perform certain tasks before it finishes the problem is that sometimes the program crashes with an exception like database cannot be reached etcnow is there any way to detect an abnormal termination and execute some code before it diesthankscode is appreciated,['c'] +26370,what gnu make substitute do you recommend imagine youre free to choose a tool like gnu make for a new c project what would you choose are any usable substitutes out thereit shall havebea command line interfaceeasy to understand easy to set up for a default c projectmay support srcbin seperation as common for javamay not add too much dependencies to other softwarelibs platform independent newfeaturesbuild rules templates like make but in an human readable wayrecursively crawling directories and applying the rules if there is no other makefileconfiguration by exceptionnotenothings wrong with gnu make i just do not like its grammar all the stuff that grows in the years and the silly recursive make problems i am using gmake for years now but now i have the chance to switch to something new so i will take the chance and asking the community i thank all of you for your contribution,['c++'] +26374,how to select the first element in the dropdown using jquery i want to know how to select the first option in all select tags on my page using jquerytried thisselect optionnth0attrselected selectedbut did not work,"['javascript', 'jquery', 'html']" +26378,make a php site send snmp information to a network management app i am trying to make a php website send information through snmp i have been reading allot about snmp but i am still a bit clueless about where to starti believe i need to create an mib with all the oids my website will use to send the info is this correct how and where can i define those variables oids can someone point me in the right directioni am using freebsd on the serverthanks in advance,['php'] +26382,how to tame the windows headers useful defines in one of the answers to this question jalf spoke about useful define nominmax that could prevent from unwanted defining minmax macros are there other useful defines that can help to control windowsh or other windows headers for instance microsoft c runtime headers or stl implementation behavior,"['c++', 'c']" +26383,how to generate web service out of wsdl i know this must be answered a lot of times but i did not get the answer what i am looking forso the client provided me the wsdl to generate the web servicebut when i used the wsdlexe command it generated the cs class out of it i consumed that class in my web service and when i provided the wsdl to client it did not match their schema actually i want the asmx to be automatically generated from the wsdl so that i could fill in the web method so that it will exactly match their schemahope it make sense,['c#'] +26407,changing img src with javascript i am new at javascript and while there are many more complex solutions i do not understand them and hope i do not have to at this pointi have a main pictureimg srcmainpicturejpg namemainpic idimageand i want to be able to change this picture when i click on one of two thumbnailsa href onclickfirstpicimg srcreplacement1jpg namepic1aa href onclicksecpicimg srcreplacement2jpg namepic2amy javascript code i thought would be super easy i am currently usingfunction firstpic documentmainpicsrc documentpic1src return function secpic documentmainpicsrc documentpic2src return now the variable is changing however it is not staying changed when the thumbnail is clicked on the replacement picture flashes on the screen and then it returns to the original mainpicturejpghow do i make the change permanent until a different thumbnail is clickedthanks,['javascript'] +26417,what does the in int style swtapplication modal swtok do and how to google it i cannot search for in google if you had found it in a software source code that you are trying to interpret you did not know what it does and you could not ask other people for help how would you find out what it does,"['java', 'c++', 'c']" +26430,visual c precompiled headers errors updatewhat are the effects of including stdafxh in my header filesi started on a c project in linuxeclipse cdt and imported it into visual cwindows in visual c i started using precompiled headers to speed up compilation and defined stdafxcpp and stdafxh heres my stdafxhpragma onceinclude stringinclude vectorinclude mapand my stdafxcppinclude stdafxhin every h and cpp file i have the followingpragma once if in a header fileinclude stdafxhfor both release and debug i have create precompiled header yc it compiled fine in debug mode but in release mode it keeps reportingerror lnk2005 pchsym 00ufhvihuaszladuwlxfnvmghunnluhixunnlpedunnlpeduivovzhvuvmgrgbolyq already defined in aobjif i switch both to use precompiled header i get in both debug and releasefatal error c1854 cannot overwrite information formed during creation of the precompiled header in object filedoes anyone know whats going on,['c++'] +26434,what is the purpose of constraint naming what is the purpose of naming your constraints unique primary key foreign keysay i have a table which is using natural keys as a primary keycreate table order loginname varchar50 not null productname varchar50 not null numberordered int not null orderdatetime datetime not null primary keyloginname orderdatetimewhat benefits if any does naming my pk bringegreplace primary keyloginname orderdatetimewith constraint order pk primary keyloginname orderdatetimesorry if my data model is not the best i am new to this,['sql'] +26459,xml serialization xmlcdatasection as serializationxmltext i am having problems serializing a cdata section using ci need to serialize xmlcdatasection object property as the innertext of the elementthe result i am looking for is thistest value2another test cdataphello worldptestto produce this i am using this objectpublic class test systemxmlserializationxmltext public xmlcdatasection value get set systemxmlserializationxmlattributeattribute public string value2 get set when using the xmltext annotation on the value property the following error is thrownsysteminvalidoperationexception there was an error reflecting property value systeminvalidoperationexception cannot serialize member value of type systemxmlxmlcdatasection xmlattributexmltext cannot be used to encode complex typesif i comment out the annotation the serialization will work but the cdata section is placed into a value element which is no good for what i am trying to dotest value2another test valuecdataphello worldpvaluetestcan anybody point me in the right direction to getting this to workthanks adam,['c#'] +26461,how to use like with column name normally like statement used to check the pattern like dataex select from table1 where name like army problem is to use one column of table with like statement exselect from table1 table2 where table1x is like table2yquery above results error how to use one column data in like query,"['sql', 'mysql']" +26463,downloading file using ie from python i am trying to download file with python using iefrom win32comclient import thispatchwitheventsclass eventhandlerobject def ondownloadbeginself passie thispatchwitheventsinternetexplorerapplication eventhandlerievisible 0ienavigatehttpwebsitefilexmlafter this i am getting a window asking the user where to save the file how can i save this file automatically from pythoni need to use some browser not urllib or mechanize because before downloading file i need to interact with some ajax functionality,['python'] +26464,add different delimiters in javascript tostring normally javascriptas tostring method returns the array in a comma seperated value like this var myarray zero one two three four five var result myarray tostringand it returns the output like this zeroonetwothreefourfivebut i have a requirement to represent the result in this format zero one two three four five replacing the comma with i know we can do this using replace method after converting the array to string is there a better alternative available,['javascript'] +26472,how do i get my maven integration tests to run i have a maven2 multimodule project and in each of my child modules i have junit tests that are named testjava and integrationjava for unit tests and integration tests respectively when i execute mvn test all of the junit tests testjava within the child modules are executed when i execute mvn test dtestintegration none of the integrationjava tests get execute within the child modulesthese seem like the exact same command to me but the one with the dtestintegration does not work it thisplays 0 tests being run at the parent level which there are not any tests,['java'] +26491,what causes an http 405 invalid method http verb error when posting a form to php on iis i have one form in a php 5291 application that causes iis microsoftiis60 to throw the following error when postedthe page you are looking for cannot be thisplayed because an invalid method http verb was used to attempt accessit is an http 405 status code all other forms in the application work so i believe that the iis verbs setting for php pages is correctthis is a customers server which i have no access to for verifying settings or testing code all i can do is send the customer replacement files other customers on iis servers have no such issuethe form is perfectly straightforwardform methodpost actionindexphp fields formwhat can cause iis to throw that error on one form only but work fine on others,['php'] +26515,how to listen for changes in contact database i am trying to listen for any change in the contact databaseso i create my contentobserver which is a child class of contentobserver private class mycontentobserver extends contentobserver public mycontentobserver supernull override public void onchangeboolean selfchange superonchangeselfchange systemoutprintln calling onchange mycontentobserver contentobserver new mycontentobservercontextgetcontentresolverregistercontentobserver peoplecontent uri true contentobserverbut when i use editcontactactivity to change the contact database my onchange does not get called,['android'] +26521,scheduledthreadpoolexecutor schedulewithfixeddelay and urgent execution i have the following problem that the standard library does not solve well and i am wondering if anybody has seen another library out there than can do it so i do not need to hack together a custom solution i have a task that is currently scheduled on a thread pool using schedulewithfixeddelay and i need to modify the code to handle requests for urgent execution of the task related to asynchronous events thus if the task is scheduled to occur with a delay of 5 minutes between executions and an event occurs 2 minutes after the last completed execution i would like to execute the task immediately and then have it wait for 5 minutes after the completion of the urgent execution before it runs again right now the best solution that i can come up with is to have the event handler call cancel on the scheduledfuture object returned by schedulewithfixeddelay and execute the task immediately and then set a flag in the task to tell it to reschedule itself with the same delay parameters is this functionality available already and i am just missing something in the documentation,['java'] +26530,ruby enterprise edition vs ruby 19 i am planning to build a website that will be a simple cms where users submit and view postings with videos photos and textone decision i want to make is choosing between ruby enterprise edition and ruby 19things i care about in orderperformance scalabilitycompatibility with existing gemspluginsopen source projectsspeed of development and deployment i will be deploying on a vpswhat is your suggestion,"['ruby-on-rails', 'ruby']" +26531,compare two java objects with a check for null i feel like such a novice for asking this question but is there a method in the jdk that compares two objects for equality accounting for nulls something like thispublic static boolean equalsobject o1 object o2 if o1 null return o2 null two nulls are considered equal else if o2 null return false return o1equalso2it seems silly to write this method myself since i would think that it has to exist already somewhereupdate removed the generics type parameter since it did not add any value in this case,['java'] +26538,passing an int array of variable length as a function parameter in objective c i have the following code which works fineint testarr33 1 101 1 self testcall testarrwhich calls this function voidtestcall int33 arr nslogcell value is uarr11i need the array to be of variable length what is the best way to declare the functionusing blanks does not work voidtestcall int arr thanks for your help,['objective-c'] +26551,most frequently repeated numbers in a huge list of numbers i have a file which has a many random integersaround a million each seperated by a white space i need to find the top 10 most frequently occurring numbers in that file what is the most efficient way of doing this in java i can think of1 create a hash map key is the integer from the file and the value is the count for every number in the file check if that key already exists in the hash map if yes value else make a new entry in hash2 make a bst each node is the integer from the file for every integer from the file see if there is a node in the bst if yes do value value is part of the nodei feel hash map is better option if i can come up with good hashing functioncan some one pl suggest me what is the best of doing this is there is anyother efficient algo that i can use,['java'] +26556,how do you dynamically allocate a matrix how do you dynamically allocate a 2d matrix in ci have tried based on what i already knowinclude iostreamint main int rows int cols int arr arr new introwscols it works for one parameter but now for two what should i do,['c++'] +26567,how to avoid multiple instances of windows form in c how to avoid multiple instances of windows form in c i want only one instance of the form running because there are chances of opening the same form from many pages of my application,['c#'] +26569,how can i get php to thisplay the headers it received from a browser are they all stored in server even custom ones,['php'] +26573,converting html to pdf not pdf to html using php i am a php developer and in one of my projects i need to convert some html documents about 30 to 50 pages into pdf documentsmy search has turned up the following possible solutions among them are some php libraries and some command line applications each has its own advantages and thisadvantagesphp librariesfpdf need more effort to converttcpdf need more effort to convert html2fpdf html2pdf dompdf compared to other works wellfor each library i have problems liketakes a long time more than five minutes to convert 30 html pagesrequires too many resources memory and time i set the following parameters in phpinimax execution time 600memory limit 250mbut things still do not workneeds html pages to be wellformatted eg no missing close tagsall of these work when i try to convert simple html docs five or fewer pages with little csscommand line applicationsall command line apps work perfectly and very quickly compared to the above libraries but only when i run them directly on console when i try to use them in php with exec or system they give me errorsthe following are the command line applications and their errors when i run them in phphtml2pdf html2ps html2pdfhtmhtml2pdf11380 gtkwarning cannot open thisplay 00 no protocol specifiedwkhtmltopdfloading page 10 loading page 33 loading page 100 waiting for redirect outputting pages qpainterbegin returned false qpainterbegin returned false qpaintersave painter not active qpainterscale painter not active qpaintersetrenderhint painter must be active to set rendering hints qpaintersetbrush painter not active qpainterpen painter not active qpaintersetpen painter not activehtmltopdf so now i am looking for help can anyone answerwhich php library would work well in my case why do these errors occur in command line applications,"['php', 'html']" +26575,how do you implement a class in c assuming i have to use c no c or object oriented compilers and i do not have dynamic memory allocation what are some techniques i can use to implement a class or a good approximation of a class is it always a good idea to isolate the class to a separate file assume that we can preallocate the memory by assuming a fixed number of instances or even defining the reference to each object as a constant before compile time feel free to make assumptions about which oop concept i will need to implement it will vary and suggest the best method for eachrestrictionsi have to use c and not an oopbecause i am writing code for anembedded system and the compiler andpreexisting code base is in c there is no dynamic memory allocationbecause we do not have enough memoryto reasonably assume we would not run outif we start dynamically allocatingitthe compilers we work with have no problems with function pointers,['c'] +26581,java date vs calendar could someone please advise the current best practice around date and calendar typeswhen writing new code is it best to always favour calendar over date or are there circumstances where date is the more appropriate datatype,['java'] +26593,using rails migration on different database than standard production or development i have a rails project running that defines the standard production development and test dbconnections in configdatabaseymlin addition i have a quiz development and quiz production definition pointing to a differnet hostdbuserpasswordmy goal now is to define a migration that uses quiz rails env as its database configurationwhat i have tried and failedsetting activerecordbaseconnection in the migration filechanging the dbmigrate task in rails to set activerecordbaseconnection therequestionhow can i make rake dbmigrate use that other database definitionthanksfrank,"['ruby-on-rails', 'ruby']" +26598,sql collation conflict when comparing to a column in a temp table i have a sql query that compares a value in the database to a constantselect from my tableinner join temptable tem on my tableid tempid and my tablekey some stringand i get the errorcannot resolve the collation conflict between sql latin1 general cp1 ci as and latin1 general ci as in the equal to operationhow can i get around this without making changes to the databaseupdate i get this error even if i remove the last like the string comparison,['sql'] +26599,sql identifying source table from union query i am building an rss feed in php which uses data from three separate tables the tables all refer to pages within different areas of the site the problem i have is trying to create the link fields within the xml without knowing which table each record has come from i cannot create the correct link to itis there a way to solve this problem i tried using mysql fetch field but it returned blank values for the tablessql select title from table1union select title from table2union select title from table3there are other fields involved but this is basically the query i am usingany help would be appreciatedthanks,['sql'] +26601,using super in an objective c category i would like to override a method in an objective c class that i do not have the source toi have looked into it and it appears that categories should allow me to do this but i would like to use the result of the old method in my new method using super to get the old methods resultwhenever i try this though my method gets called but super is nil any idea why i am doing iphone development with the xcode 22 sdk i am definitely working with an instance of a class and the method of the class is an instance method implementation sampleclass filepathresolvernsstring fullpathfromrelativepathnsstring relpath nsstring result super fullpathfromrelativepath relpath do some stuff with the old result return resultnote and clarification from what i can see in the apple docs it appears to me that this should be allowedcategories docs at developerapplecom when a category overrides an inherited method the method in the category can as usual invoke the inherited implementation via a message to super however if a category overrides a method that already existed in the categorys class there is no way to invoke the original implementation,['objective-c'] +26611,what is the best way to divide two timespan objects i want to get the ratio of one timespan against another timespan basically the progress of a playing video from it is total time my current methods is to get the milliseconds of the two timespan objects and divide one against the other something like int durationinmilliseconds totaltimespanmilliseconds int progressinmilliseconds progresstimespanmilliseconds double progressratio progressinmilliseconds durationinmillisecondsis there a more direct route it is a simple problem and i am just curious if there is a super elegant way to solve itcheers alljames,['c#'] +26634,how to fake ivars in an objc category iphone updateiphone os 31 has associated objects however the iphone simulator does not if you want to test associated objects code in the simulator you should file a bug see my so question hererdar7477326snow leopard now has associated objectsis there a way to accomplish something similar without associated objects specifically for the iphonei am pretty sure i saw something like this a while back but i cannot remember where something about turning any object into a kvc container,"['iphone', 'objective-c']" +26637,jquery ajax polling for json response handling based on ajax result or json content i am a novicetointermediate javascriptjquery programmer so concreteexecutable examples would be very much appreciatedmy project requires using ajax to poll a url that returns json containing either content to be added to the dom or a message status pending that indicates that the backend is still working on generating a json response with the content the idea is that the first request to the url triggers the backend to start building a json response which is then cached and subsequent calls check to see if this json is ready in which case it is providedin my script i need to poll this url at 15second intervals up to 130 mins and do the followingif the ajax request results in an error terminate the scriptif the ajax request results in success and the json content contains status pending continue pollingif the ajax request results in success and the json content contains usable content ie any valid response other than status pending then thisplay that content stop polling and terminate the scripti have tried a few approaches with limited success but i get the sense that they are all messier than they need to be heres a skeletal function i have used with success to make a single ajax request at a time which does its job if i get usable content from the json response make the ajax requestfunction ajax request ajax url json url json url is a global variable datatype json error functionxhr data terminate the script success functionxhr data if xhr datastatus pending continue polling else successxhr data contenttype applicationjson however this function currently does nothing unless it receives a valid json response containing usable contenti am not sure what to do on the lines that are just comments i suspect that another function should handle the polling and call ajax request as needed but i do not know the most elegant way for ajax request to communicate its results back to the polling function so that it can respond appropriatelyany help is very much appreciated please let me know if i can provide any more information thanks,"['javascript', 'jquery']" +26650,dynamically adding and removing table rows android i am trying to dynamically add and remove rows from a tablelayoutthe layout is defined in an xml filei am able to successfully remove a row but when i call the corresponding addview command nothing happenstable tablelayoutfindviewbyidridtablerow tablerowfindviewbyidridrowtableremoveviewrowtableaddviewrowthis results in a row being removed but not being added againedit it turns out it was adding if after all just at the bottom of the screen instead of in the same location as it was removed fromi am able to add it in the correct position by specifying the indextableaddviewrow4 4 happens to the the rowbut i can not figure out how to determine the index of the row there does not seem to be a method to accomplish this anyone know how do to that ie if i did not know the index was 4 how could i figure that outedit included xml this is just the row in question there are other rows above and below ittablerow androidididrow textview androidididfield1 androidtexttesting androidlayout widthwrap content androidlayout heightwrap content androidpadding3dip androidtextstylebold androidtextsize18dip textview androidididfield2 androidpadding3dip androidtexttest androidtextsize18dip androidgravityright tablerow,['android'] +26660,when do we do gethashcode for a dictionary i have used dictionarytkey tvalue for many purposes but i have not encountered any scenario to implement gethashcode which i believe is because my keys were of primary types like int and stringi am curious to know the scenarios real world examples when one should use a custom object for key and thus implement methods gethashcode equals etcand does using a custom object for key necessitate implementing these functions,"['c#', '.net']" +26678,how to call generic method with a given type object i want to call my generic method with a given type objectvoid footype t mygenericmethodtobviously does not workhow can i make it work,"['c#', '.net']" +26684,is it bad to use properties for private variables just for the memory management benefits is it bad to create properties for private variables just for the memory management benefitsit seems messy and wrong to have public facing properties for many private variablesmainly i am releasing private ivars during low memory conditions using the respective event methodsexamplei usually do this to release a private ivarname release name nilbut with properties i can do thisselfname nillater in my code will do this hence the need to set to nilif name name nsstring alloc initwithformathi inputname,['objective-c'] +26693,mono compatible networkingsocket library are there any mono c compatible networking socket libraries out therepreferably something that ismulti threadedevent drivencapable of multiple connectionshandles client and server piecesruns on mono and ms net runtimesvery simplefree and usable in commercial softwareit would also be really great if it wasnet compact framework windows mobile compatiblemonotouch iphone compatibleeditto clarify more what i meant by my one level above tcpip comment was that i want something that is basically a self contained server client i do not want to have to deal with writing the threading code handling each connection etc for example i would love for the code to look like thisserver s new server8080snewconnection new connectioneventhandlernewconnectionsdatarecieved new dataeventhandlernewdatasstartvoid newconnectionobject sender eventargs e ssendconnectionsender hello world connectionsender is the connection instance so the server knows which to send the response tovoid newdataobject sender eventargs e ssendconnectionsender edata echo backnot the cleanest code but i think it gives the basic idea,['c#'] +26697,how do i hide the field label for a hiddeninput widget in django admin i have got a bit of django form code that looks like thisclass galleryadminformformsmodelform auto idfalse order formscharfieldwidgetformshiddeninputand that makes the form field go away but it leaves the label order in the django admin page if i useorder formscharfieldwidgetformshiddeninput labeli am still left with the between where the field and label used to behow do i hide the whole thing,['python'] +26704,how to intercept and modify sql query in linq to sql i was wondering if there is any way to intercept and modify the sql generated from linq to sql before the query is sent offbasically we have a record security layer that given a query like select from records it will modify the query to be something like select from records where somesecurityfilteri am trying to find the best way to intercept and modify the sql before its executed by the linq to sql provider,['sql'] +26707,how to select within a container with jquery div idcontainer1spanspandivdiv idcontainer2spanspandivsay if i have get the jquery object container1how to find the span in it,['jquery'] +26725,parsing javascript date string in java a javascript client sends some strings to my server one of which comes in form of a javascript date objects string representationnow this javascript date object has its own formatting and i was just wondering if there is a class that does the right conversion as i am experiencing problems with the simpledateformatterthis is how a javascript date string looks like tue feb 12 2013 211228 gmt0100 cet,"['java', 'javascript']" +26732,code sign error with xcode 32 i had a fully working build environment before upgrading to iphone os 31 and xcode 32 now when i try to do a build i get the followingcode sign error provisioning profile fooapp test specifies the application identifier nofooappiphoneapp which does not match the current setting tgecmyz3vknofooappiphoneappthe problem is that xcode somehow manages to think that the fooapp test provisioning profile specifies the application identifier nofooappiphoneapp but this is not the casein the organizer and in the iphone developer portal website the app identifier is correctly seen as tgecmyz3vknofooappiphoneappalso when setting the provisioning profile in the build options at the project level xcode correctly identifies the app identifier but when i go to the target i am unable to select any valid provisioning profilewhat could be causing this problemupdate i have tried to create a new provisioning profile but still no luck i also tried simply changing the app identified in infoplist to just nofooappiphoneapp the build succeeds but now i get an error from the organizerthe executable was signed with invalid entitlements the entitlements specified in your applications code signing entitlements file do not match those specified in your provisioning profile 0xe8008016this seems reasonable as the provisioning profile still has the tgecmyz3vknofooappiphoneapp application identifieri also double checked that all certiicates are valid in the keychainso my question is how i can get xcode to see the correct application identifierupdate as noted below what seems to fix the problem is deleting all provisioning profiles certificates etc making new certificates profiles and installing them again if anyone has any other solutions they would be welcome,['iphone'] +26733,ruby proccall vs yield what are the behavioural differences between the following two implementations in ruby of the thrice methodmodule withyield def selfthrice 3times yield yield to the implicit block argument endendmodule withproccall def selfthriceblock converts implicit block to an explicit named proc 3times blockcall invoke proccall endendwithyieldthrice puts hello world withproccallthrice puts hello world by behavioural differences i include error handling performance tool support etc,['ruby'] +26735,sql last insert in drupal is it really threadsafe i have a query that might be executed by several users consecutively i am scared that if i run the db last insert id command some users might not get the last insert id due to concurrency but according to it satesreturns the last insert id this function is thread safemy question is how is this thread safe the code is onlyphp function db last insert idtable field return db resultdb queryselect currval db escape tabletable db escape tablefield seq i do not see anything about locking tables or nothing,['mysql'] +26756,how to add an icon to an application built with eclipse galileo c and mingw i have read a lot about how to add an icon to an application built with visual studio but i have no idea how to do this with eclipse galileo c mingwcan anyone write a description or give me a link ta a description,['c'] +26758,access violation exceptioncrash from c callback to c function so i have a native 3rd party c code base i am working with lib and hpp files that i used to build a wrapper in ccli for eventual use in c i have run into a particular problem when switching from debug to release mode in that i get an access violation exception when a callbacks code returns the code from the original hpp files for callback function formattypedef int callbackfunction void inst const void datacode from the ccli wrapper for callback function formati will explain why i declared two in a momentpublic delegate int managedcallbackfunction intptr oinst const intptr odatapublic delegate int unmanagedcallbackfunction void inst const void dataquickly the reason i declared a second unmanagedcallbackfunction is that i tried to create an intermediary callback in the wrapper so the chain changed from native c c to a version of native c ccli wrapper cfull thisclosure the problem still lives it is just been pushed to the ccli wrapper now on the same line the returnand finally the crashing code from cpublic static int hreceivelogeventintptr pinstance intptr pdata consolewritelinein hreceivelogevent consolewritelinepinstance 0 pinstance consolewritelinepdata 0 pdata provide object context for static member function helloworld hw helloworldgchandlefromintptrpinstancetarget if hw null pdata null consolewritelinehreceivelogevent received null instance pointer or null datan return 0 typecast data to datalogger object ptr intptr ip2 gchandletointptrgchandleallocnew dataloggerwrappdata dataloggerwrap dlw dataloggerwrapgchandlefromintptrip2target do logging stuff consolewritelineexiting hreceivelogevent consolewritelinepinstance 0 pinstance consolewritelinepdata 0 pdata consolewritelinesetting pdata to zero pdata intptrzero pinstance intptrzero consolewritelinepdata 0 pdata consolewritelinepinstance 0 pinstance return 1 all writes to the console are done and then we see the dreaded crash on the returnunhandled exception at 0x04d1004c in helloworldexe 0xc05 access violation reading location 0x04d1004cif i step into the debugger from here all i see is that the last entry on the call stack is 04d1004c which evaluates to a decimal value of 80805964which is only interesting if you look at the console which shows entering registerdataloggerpointer to callback handle 790848fp for callback 2631370pointer to inst 790844in hreceivelogeventpinstance 790844pdata 80805964exiting hreceivelogeventpinstance 790844pdata 80805964setting pdata to zeropdata 0pinstance 0now i know that between debug and release some things are quite different in the microsoft world i am of course worried about byte padding and initialization of variables so if there is something i am not providing here just let me know and i will add to the already long post i also think the managed code may not be releasing all ownership and then the native c stuff which i do not have the code for may be trying to delete or kill off the pdata object thus crashing the appmore full thisclosure it all works fine seemingly in debug modea real head scratch issue that would appreciate any help,"['c#', 'c++']" +26775,what difference it makes when i set python thread as a deamon what difference it makes when i set python thread as a deamon using threadsetdaemontrue,['python'] +26793,hadoop thistribution differences can somebody outline the various differences between the various hadoop thistributions availablecloudera yahoo using the apache hadoop thistro as a baseline is there a good reason to using one of these thistributions over the standard apache hadoop thistro,['java'] +26796,why do my controllers instance variables not work in views rails i would like to add a couple of instance variables to my controller since the variables in question are required from within more than one actions view however the below example does not work as i would expectclass examplecontroller applicationcontroller var1 cheese var2 tomato def show pizza topping what i want is the above instance vars from within the view here end def show sandwich filling what i want is the above instance vars from within the view here endendas i understand it rails takes the instance variables from the controller and makes them available in the view if i assign the same variables within the action methods it works fine but i do not want to do it twice why does my way not worknote this is a bit of a rubbish example but i hope it makes senseedit i have found the answer to this question here edit 2 when is the best time to use filters such as before filter and the initialize method,"['ruby-on-rails', 'ruby']" +26808,hibernate mapping package i am using hibernate annotationsin all my model classes i annotate like thisentitytablepublic class somemodelclass my hibernatecfgxml ishibernateconfiguration sessionfactory some properties mapping packagecomfoopackage mapping classcomfoopackagesomemodelclass sessionfactoryhibernateconfigurationfor every class i add to the comfoopackage i have to add a line in the hibernatecfgxml like thismapping classcomfoopackageanothermodelclass is there a way i can add new model classes but do not need to add this line to hibernatecfgxml,['java'] +26815,rails cookieoverflow suddenly in my first rails app i have started seeing this error failsafe fri sep 11 173048 0400 2009status 500 internal server erroractioncontrollersessioncookiestorecookieoverflowa little research points to the usage of of cookies to store session data but i am not doing that at least not intentionally moreover this just started happening today the only thing i have started working on today is the ability to upload a zip file the zip file that i am trying to use for testing is 11mbadditionally firebug shows only 2 cookies for this domain the one named html session is 507b and the one named user credentials is 147b are uploaded files temporarily stored in such a way that a largeish file could be causing this uploading a single image works just finethanks for your helpupdate oops contrary to my comments to vitaly and xijo below the error is not quite instant in this case i am uploading something to my image model and the error is happening when my imagescontroller calls imagesavewhats interesting is that i still do not really understand where the error happens i created an imagebefore validation method and raising an exception there but the cookieoverflow error happens before i ever get there is there any place i can drop code after the controller makes the save call and before that particular callback my understanding is that before validation is the first callback,['ruby-on-rails'] +26817,showing an image from console in python what is the easiest way to show a jpg or gif image from python consolei have got a python console program that is checking a data set which contains links to images stored locally how should i write the script so that it would thisplay images popup graphical windows,['python'] +26822,switchtothreadthreadyield vs threadsleep0 vs theadsleep1 i am trying to write the ultimate yield method to yield the current time slice to other threads so far i have found that there are several different ways to make the thread yield its allocated time slice i just want to make sure i am interpreting them correctly since the documentation is not very clear so from what i have read on stackoverflow msdn and various blog posts the following options exist that all have different advantages thisadvantagesswitchtothread win32 threadyield net 4 beta 1 yields to any thread on same processoradvantage about twice as fast asthreadsleep0thisadvantage yields only to threadson same processorthreadsleep0 yields to any thread of same or higher priority on any processoradvantage faster thanthreadsleep1thisadvantage yields only to threadsof same or higher prioritythreadsleep1 yields to any thread on any processoradvantage yields to any thread onany processorthisadvantage slowest optionthreadsleep1 will usuallysuspend the thread by about 15ms iftimebeginperiodtimeendperiodwin32 are not usedwhat about threadspinwait can that be used for yielding the time slice of the thread if not what is it used fori there something else i have missed or incorrectly interpreted i would be grateful if you could correct add to my understandingthis is how my yield method looks like so farpublic static class thread dllimportkernel32dll static extern bool switchtothread dllimportwinmmdll internal static extern uint timebeginperioduint period dllimportwinmmdll internal static extern uint timeendperioduint period summary yields time slice of current thread to specified target threads summary public static void yieldtothreadyieldtarget threadyieldtarget switch threadyieldtarget case threadyieldtargetnone break case threadyieldtargetanythreadonanyprocessor timebeginperiod1 reduce sleep to actually 1ms instead of system time slice with is around 15ms systemthreadingthreadsleep1 timeendperiod1 undo break case threadyieldtargetsameorhigherprioritythreadonanyprocessor systemthreadingthreadsleep0 break case threadyieldtargetanythreadonsameprocessor switchtothread break default throw new argumentoutofrangeexceptionthreadyieldtarget public enum threadyieldtarget summary operation system will decide when to interrupt the thread summary none summary yield time slice to any other thread on any processor summary anythreadonanyprocessor summary yield time slice to other thread of same or higher piority on any processor summary sameorhigherprioritythreadonanyprocessor summary yield time slice to any other thread on same processor summary anythreadonsameprocessor,['.net'] +26833,django not sending emails to admins according to the documentation if debug is set to false and something is provided under the admins setting django will send an email whenever the code raises a 500 status code i have the email settings filled out properly as i can use send mail fine but whenever i intentionally put up erroneous code i get my 500html template but no error email is sent what could cause django to not do this,['python'] +26844,how do you add more than one uibarbutton on uinavigationitemrightbarbuttonitem or leftbarbuttonitem i have tried this approachhackthe problem is this leaves a faint seam i tried setting the background image of the nested toolbar to an image i captured of what it should be that did not work the image was not applied i have also tried using a nested uinavigationbar and that did not seem to worki have seen this done in several iphone apps does anyone know howedit i want the buttons to look like normal uibarbuttonitems and be able to use system styles like uibarbuttonsystemitemadd uibarbuttonsystemitemrefresh the link i provided does this except you can see a faint seam because it is a uitoolbar nested in the navigationbarplease do not mention this breaking the human interface guidelines we knowi appreciate you contributing your hacks thats the only way to do this,['iphone'] +26847,use javascript to openactivate firebug i have been looking for a solution to use javascript to open or activate firebugyou see by default firebug is deactivatedclosed at the corner of the status baryou need to click the icon to activate firebug the icon becomes colouredis there a way to activate firebug via javascript in the javascript codesee following check if firebug is installed and activatedifwindowconsole windowconsolefirebug do firebug debugging and so onelse alertfirebug is not installed or activated,['javascript'] +26858,recommended approach on handling sqlexceptions in db applications i work on a database application written in c with sql server as backend and for data integrity i try to enforce as much as possible on database level relations check constraints triggersdue to them if data is not consistent the save update insert can fail and app throw sqlexceptioni do various validations both in ui to present user with meaningful info if data entered is not valid also in bl which reports errors back to ui which presents it to userhowever there are things that really cannot be checked in the app and are handled by the db i mean errors on delete when no cascade delete and user try to delete a entity from a master table etceg employees table acts as master in lot of relations manager of employee manager of department cashier team leader teams members etc etc if i add anew employee which is not involved in any relation i can delete it but of user try to delete one that is master oin such relation the delete fails as it should due to ri rules enforced at db level and that is oki write delete code in a try catch and handle the exception telling user he cannot delete that employee but i want to give user more meaningful info the reason the record cannot be deleted maybe it was just a test employee record which was also added to a test team but user forget where added that and if i could tell cannot delete employee because it is part of team t1 user will know to go first to team t1 remove user then try to delete it again that is a simple example since as i said an employee can be involved in lot of relations in my app i have at least 20the solution is to thisplay the message reported by sqlexception but that is not elegant at all first that msg is very technical it talks about fk pk triggers which are meaningless for users and will scare them second my app is uses multilang ui and all menus and msgs are shown in user selected language selected either at login time or in user profile and the msg from sqlexception is english if i use english version or worst less common languages like german or dutch if it happens that sql server is in that language is there any common or recommended approach to extract meaningful info from sql exception to be able to present user a meaningful msg eg what relation or child table caused the failure or what trigger etc but something i can test in program in a langindependent fashion and then format my own error msg in a userfriendly way how do you handle this situationthanks for all answersps sorry for the long post,"['c#', 'sql']" +26860,can my enums have friendly names i have the following enumpublic enum myenum thisnameworks this name does not work neitherdoesthisis it not possible to have enums with friendly names,['c#'] +26876,problem solving in c with stl i am preparing for a programming competition in witch we solve programming problems in c looking at the former year solutions they seem quite easy not more than 30 lines of code i realised that they are widely using the stl for easy manipulating vectors sets maps lists and also the algorithms available in stlany site for beginners like me who want to learn the features of stl and its use in solving problems thank you in advance,['c++'] +26882,forth interpreter in java here i found a simple forth interpreter implemented in javahowever i do not understand the significance of it if i want to use itwhat could be the advantage of the forth interpreterif the final compiled code to beexecuted by the jvm is still bytecode what would we the forthinterpreter be doingwill it help in writingefficienttight programswill i be writing my code in forthand the interpreter will convert itto javayour thoughts,['java'] +26890,restrict access to net assembly is there a way to have a net assembly accessible for only authorized sourcesi mean i want to have a dll that contains components but i do not want anyone to be able to use these components but the other dlls exes in my solutioni do want them to be in separated dlls thoughrestriction on namespace might also be a good idea if this feature exists out thereis there a way,['.net'] +26896,create uiimage from nsdata below is code i copied from this site and modified only slightly since the original code would not compile i want to manipulate the byte array for edge detection and eventually simple changes to colors but first i wanted to get the basic code working currently the system compiles and runs it thisplays a badly drawn elephant on screen when i touch the image it thisappears stepping through shows the result of imagewithdata as 0x0 i have tried this with both a png and a bmp and same result any clues to what i am doing wrong imageviewdrawable is defined as interface imageviewdrawable uiimageview i am using the following code to initialize this imageviewimageviewdrawable uiv imageviewdrawable alloc initwithimageuiimage imagenamedelepng void touchesbegannsset touches witheventuievent event get and work on pixel data nsdata pixeldata nsdata cgdataprovidercopydatacgimagegetdataproviderselfimagecgimage char bytes pixeldata bytes take away the red pixel assuming 32bit rgba forint i 0 i pixeldata length i 4 bytesi bytesi red bytesi1 bytesi1 green bytesi2 bytesi2 blue bytesi3 bytesi3 alpha convert pixel back to uimage nsdata newpixeldata nsdata datawithbytesbytes lengthpixeldata length char bytes2 pixeldata bytes uiimage newimage uiimage imagewithdatanewpixeldata self setimage newimage,['iphone'] +26899,rails i update migration file then run dbmigrate but my schema is not updating im trying to add an extra field to one of my tablesive added the field in the migration file under dbmigratethen ran rake dbmigrate which ran without troubles and my text editor even told me my schemadb file has been updated and needs to refreshthe schema file does not contain my new field and any attempts to reference the field from my views fail miserablyhow do i do this it is possible to update a table with an extra field via rails without having to totally drop and recreate the database againthanksevolve,['ruby-on-rails'] +26903,aspect oriented programming in c are there any good resources to wrap my head around aspect oriented programmingps i need to understand ao programming not the libraries or frameworks available for net or c,"['c#', '.net']" +26904,how to thisable all inside a form with jquery form idtargetform,['jquery'] +26907,how to fetch result from mysql row with multiple samename columns with php select from a left join b on acolumncbcolumndresults returned by above sql will include both columns of a and band what if a and b have some columns with the same namehow to retrieve the value from php,"['php', 'sql', 'mysql']" +26908,iphone app is in landscape mode but views bounds is still portrait whats really going on behind the scene when you set the phones orientation to landscape mode when i traced out main screens bounds and any subviews bounds the width and height is still 320x480 rather than 480x320any idea why,['iphone'] +26913,should a static final logger be declared in uppercase in java static final variables are constants and the convention is that they should be in uppercase however i have seen that most people declare loggers in lowercase which comes up as a violation in pmd egprivate static final logger logger loggergetloggermyclassclassjust search googleor so for static final logger and you will see this for yourselfshould we be using logger instead,['java'] +26920,how do i get my page title to have an icon i would like to have my siteas logo shown in the icon area of the title rather than the default white document exactly as stack overflow has it,['html'] +26931,extending generic abstract class correct use of super public abstract class abstracttoolat extends abstractthing protected arraylistat ledger public abstracttool ledger new arraylistat public at gettoolatint i return ledgergeti more code which operates on ledger public class toolat extends abstractthing extends abstracttool public tool super how do i correctly call super to pass the at generic of tool to the abstracttool constructorit seems no matter what i pick at to be when i declare tool say toolthing that i always get back an abstractthing instead of thing this seems to defeat the purpose of genericshelp,['java'] +26934,string strip for javascript whats a clean and efficient javascript implementation to strip leading and trailing spaces from a string for example dogdog dog dog all get turned intodog,['javascript'] +26938,intervaltree deletenode java implementation i need an intervaltree or rangetree implementation in java and am having trouble finding one with working deletion supportthere is a builtin one at sunjvmhotspotutilitiesintervaltree but the deletenode method in the rbtree superclass states fixme this does not work properly yet for augmented redblack trees since it does not update nodes need to figure out exactly from which points we need to propagate updates upwards trying to delete nodes from a tree ends up throwing the exceptionnodes max endpoint was not updated properlyhow difficult would it be to properly implement delete functionality in a subclass of the sunjvmhotspotutilitiesintervaltree or is there another interval tree implementation which already implements this correctly currently i am just wiping out the tree and repopulating it every time there is a deletion which is far from ideal note setting debuggingfalse in the rbtree sped things up tremendously,['java'] +26955,implementing ithisposable on a sealed class i do not think this question has been asked before i am a bit confused on the best way to implement ithisposable on a sealed classaspecifically a sealed class that does not inherit from a base class that is a pure sealed class which is my made up termperhaps some of you agree with me in that the guidelines for implementing ithisposable are very confusing that said i want to know that the way i intend to implement ithisposable is sufficient and safei am doing some pinvoke code that allocates an intptr through marshalallochglobal and naturally i want to cleanly thispose of the unmanaged memory i have created so i am thinking of something like thisusing systemruntimeinteropservicesstructlayoutlayoutkindsequentialpublic sealed class memblock ithisposable intptr ptr int length memblockint size ptr marshalallochglobalsize length size public void thispose if ptr intptrzero marshalfreehglobalptr ptr intptrzero gcsuppressfinalizethis memblock thispose i am assuming that because memblock is completely sealed and never derives from another class that implementing a virtual protected thisposebool thisposing is not necessary also is the finalizer strictly necessary all thoughts welcome,['c#'] +26957,is using char as a primaryforeign key a no no consider that there is a bunch of tables which link to countries or currencies tablesfor making data easier to read i would like make char field with country code eg us gb au and currency code usd aud a primary keys in each of those 2 tables and all other tables will use this char as a foregin keydatabase is mysql with innodb engineis it going to cause performance issues is it something i should avoid,"['sql', 'mysql']" +26960,how to change session id after login in aspnet i have a website that is using forms authentication and membership a user must have cookies enabled to use the site i have been asked to change the code so that the session id is changed as soon as a user logs in aparently this will protect against a session fixation attack does anyone know how i can change the session id without losing the whole session php has a specific method for doing this but i cannot find a net equivalent,['asp.net'] +26970,just installed qtopengl but cannot import it from python i just installed it with aptget on debian linux withaptget install libqt4openglthe rest of pyqt4 is available but i cant get to this new modulefrom pyqt4 import qtopenglraises importerror any idea what to do,['python'] +26974,auto update is this secure dot net auto updatei felt like net was lacking a simple secure automatic update library so i have implemented something and put it up here before anyone considers using the library i was keen for the update process to get a bit a peer review here are the stepsthe client software is populated with a public key and uri to pollclient polls a uri for a manifest filemanifest is downloaded and signature in a separate signature is used to check that the manifest is valida list of pending updates is parsed out of the manifest to show to the userthe installer file is downloaded and again is verified with a corresponding signature file the downloaded file will be protected with aclsthe installer is runmitigated threatsthe manifest signature should prevent any malicious downloads carpet bombingthe installer signature should prevent any mitm attacks from sending malicious installersprotecting the downloaded installer with acls should prevent any local escalation attacksunmitigated threatsa mitm attack where the attacker always reports no updates available could keep a client at a vulnerable versionreferencessecure software updates thisappointments and new challengesblack ops 2008 itas the end of the cache as we know it evilgrade will destroy us allwhat have i missed,"['c#', '.net']" +26986,do not stop debugger at that exception when it is thrown and caught in toolsexceptions i have set the option that the debugger stops when an exception is thrown whether it is caught or not how do i exclude an exception of that rule somewhere in my code there is a caught exception that is part of the program logic so i obviously do not want that exception to stop the debugger each time it is hitexample i want to ignore the nullreference exception which is caught on line 344 i want to stop at all other exceptions,"['c#', '.net']" +26998,nullable value with xsdexe generated class i have been using xsdexe to generate a class for deserializing xml intoi have decimal value in the source xsd that is not requiredxsattribute namebalance typexsdecimal useoptional the resulting class from xsd generates the following codeprivate decimal balancefieldsystemxmlserializationxmlattributeattributepublic decimal balance get return thisbalancefield set thisbalancefield value which i note is not nullablehow do i instead generate the field as nullable illustrated as followsprivate decimal balancefieldsystemxmlserializationxmlattributeattributepublic decimal balance get return thisbalancefield set thisbalancefield value,['c#'] +27001,iphone uiimageview rotation can anyone tell me how to rotate an image in circular motion,['iphone'] +27007,formatting doubles for output in c running a quick experiment related to is double multiplication broken in net and reading a couple of articles on c string formatting i thought that this double i 10 069 consolewritelinei consolewritelinestringformat 0f20 i consolewritelinestringformat 0f20 69 i consolewritelinestringformat 0f20 69would be the c equivalent of this c code double i 10 069 printf fn i printf 20fn i printf 20fn 69 i printf 20fn 69 however the c produces the output69 690 0818 690despite i showing up equal to the value 68946709 rather than 69 in the debuggercompared with c which shows the precision requested by the format690 68946709 0818 69035527whats going on microsoft net framework version 351 sp1 visual studio c 2008 express edition i have a background in numerical computing and experience implementing interval arithmetic a technique for estimating errors due to the limits of precision in complicated numerical systems on various platforms to get the bounty do not try and explain about the storage precision in this case it is a difference of one ulp of a 64 bit double to get the bounty i want to know how or whether net can format a double to the requested precision as visible in the c code,['c#'] +27017,inserting space in an aspnet dropdownlist control i have an aspnet dropdownlist control that retrieves the first and last name from a column in the database instead of having just one space between the first and last name i want there to be three how do i add the extra spaces between the two pieces of text in the dropdownlist,['asp.net'] +27018,which python mpi library to use i am starting work on some simulations using mpi and want to do the programming in pythonscipy the scipy site lists a number of mpi libraries but i was hoping to get feedback on quality ease of use etc from anyone who has used one,['python'] +27021,how to i launch a ruby script from the command line by just its name on windows i can run my ruby script like this ruby myscriptrbbut i want to set things up so that i can just do this instead myscriptrbhow do i do this i know it is possible because i have recently moved from one pc that had this set up to a new pc that does not yet,['ruby'] +27027,c with sharpziplib compatibility of sharpziplib with winzip and xp i am using the csharpziplib library to automatically zip some files the problem is that the resulting zip file does not work with winzip version 81 or xps compressed foldersit does work with 7zipwinzip gives an error that this file is not in the standard zip 20 formatis there a parameter that i can change that would get the library to compress in a winzipxp compatible format,['c#'] +27032,how i get the tag value from the sender ibactiononclick1idsender make sure it is a uibutton if sender iskindofclassuibutton class return nsstring title uibutton sender currenttitlei understand how to get the title and other current values but i do not see how i can get the value of the tag property,"['iphone', 'objective-c']" +27038,pytz why is normalize needed when converting between timezones i am reading the not so complete pytz documentation and i am stuck on understand one part of itconverting between timezones also needs special attention this also needs to use the normalize method to ensure the conversion is correct utc dt utclocalizedatetimeutcfromtimestamp1143408899 utc dtstrftimefmt20060326 213459 utc0 au tz timezoneaustraliasydney au dt au tznormalizeutc dtastimezoneau tz au dtstrftimefmt20060327 083459 est1100 utc dt2 utcnormalizeau dtastimezoneutc utc dt2strftimefmt20060326 213459 utc0i tried this very example without using normalize and it turned out just the same in my opinion this example does not really explain why we have to use normalize when converting between datetime objects in different timezoneswould someone please give me an example like the one above where the result differs when not using normalizethanks,['python'] +27057,default duration of cacheinsert in aspnet if i have the following line when should i expect the cache to expiresystemwebhttpruntimecacheinsertsomekey test value,['asp.net'] +27065,iphone development pointer being freed was not allocated i got this message from the debuggerpixture12570xa0610500 malloc error for object 0x21a80 pointer being freed was not allocated set a breakpoint in malloc error break to debugso i did a bit of tracing and gotgdb shell malloc history 1257 0x21a80alloc 0x2196a0x21a89ff size73728 thread a0610500 start main uiapplicationmain gseventrun gseventrunmodal cfrunloopruninmode cfrunlooprunspecific cfrunloopdoobservers catransactionobserver callback cfrunloopobserver unsigned long void catransactioncommit cacontextcommit transactioncatransaction calayerthisplayifneeded calayer thisplay cabackingstoreupdate backing callbackcgcontext void calayer drawincontext uiviewcalayerdelegate drawlayerincontext avatarview drawrect avatarview overlaypng uiimageutility createmaskof uigraphicsgetimagefromcurrentimagecontext cgbitmapcontextcreateimage create bitmap data provider malloc malloc zone mallocand i really cannot understand what i am doing wrong heres the code of the uiimageutility createmaskof function uiimage createmaskofuiimage source cgrect rect cgrectmake0 0 sourcesizewidth sourcesizeheight uigraphicsbeginimagecontextcgsizemakesourcesizewidth sourcesizeheight cgcontextref context uigraphicsgetcurrentcontext cgcontexttranslatectmcontext 0 sourcesizeheight cgcontextscalectmcontext 10 10 uiimage original self creategraycopysource cgcontextref context2 cgbitmapcontextcreatenull sourcesizewidth sourcesizeheight 8 4 sourcesizewidth cgcolorspacecreatedevicergb kcgimagealphanoneskiplast cgcontextdrawimagecontext2 cgrectmake0 0 sourcesizewidth sourcesizeheight originalcgimage cgimageref unmasked cgbitmapcontextcreateimagecontext2 const float mymaskingcolorsframecolor6 125612561256 cgimageref mask cgimagecreatewithmaskingcolorsunmasked mymaskingcolorsframecolor cgcontextsetrgbfillcolor context 256256256 1 cgcontextfillrectcontext rect cgcontextdrawimagecontext rect mask uiimage whitemasked uigraphicsgetimagefromcurrentimagecontext uigraphicsendimagecontext return whitemaskedthe other custom function called before that is the following uiimage overlaypngsinglepart sp nslogsp description rect and context setup cgrect rect cgrectmake0 0 spimagesizewidth spimagesizeheight nslogf x f spimagesizewidth spimagesizeheight create an image of a color filled rectangle uiimage basecolor nil if sphasowncolor basecolor uiimageutility imagewithrectrect ofcolorspcolor else singlepart facepart editingavatarfacepartlist objectatindex0 basecolor uiimageutility imagewithrectrect ofcolorfacepartcolor crete the mask of the layer uiimage mask uiimageutility createmaskofspimage mask uiimageutility creategraycopymask create a new context for merging the overlay and a mask of the layer uigraphicsbeginimagecontextcgsizemakespimagesizewidth spimagesizeheight cgcontextref context2 uigraphicsgetcurrentcontext adjust the coordinate system so that the origin is in the lower left corner of the view and the y axis points up cgcontexttranslatectmcontext2 0 spimagesizeheight cgcontextscalectmcontext2 10 10 create masked overlay color layer cgimageref maskedimage cgimagecreatewithmask basecolorcgimage maskcgimage draw the base color layer cgcontextdrawimagecontext2 rect maskedimage get the result of the masking uiimage overlaymasked uigraphicsgetimagefromcurrentimagecontext uigraphicsendimagecontext uigraphicsbeginimagecontextcgsizemakespimagesizewidth spimagesizeheight cgcontextref context uigraphicsgetcurrentcontext adjust the coordinate system so that the origin is in the lower left corner of the view and the y axis points up cgcontexttranslatectmcontext 0 spimagesizeheight cgcontextscalectmcontext 10 10 get the result of the blending of the masked overlay and the base image cgcontextdrawimagecontext rect overlaymaskedcgimage set the blend mode for the next drawn image cgcontextsetblendmodecontext kcgblendmodeoverlay component image drawn cgcontextdrawimagecontext rect spimagecgimage uiimage blendedimage uigraphicsgetimagefromcurrentimagecontext uigraphicsendimagecontext cgimagereleasemaskedimage return blendedimage,"['iphone', 'objective-c']" +27071,most vexing parse why does not a a work among the many things stack overflow has taught me is what is known as the most vexing parse which is classically demonstrated with a line such asa ab declares a functionwhile this for most intuitively appears to be the declaration of an object a of type a taking a temporary b object as a constructor parameter it is actually a declaration of a function a returning an a taking a pointer to a function which returns b and itself takes no parameters similarly the linea a declares a functionalso falls under the same category since instead of an object it declares a function now in the first case the usual workaround for this issue is to add an extra set of bracketsparenthesis around the b as the compiler will then interpret it as the declaration of an objecta ab declares an objecthowever in the second case doing the same leads to a compile errora a compile errormy question is why yes i am very well aware that the correct workaround is to change it to a a but i am curious to know what it is that the extra does for the compiler in the first example which then does not work when reapplying it in the second example is the a ab workaround a specific exception written into the standard,['c++'] +27074,garbage collection vs non garbage collection programming languages so if i understand well garbage collection automatically deallocates objects that are not used by the program anymore like the garbage collector in javai hear in languages like c that do not support garbage collection the programs can have memory leaks and subsequently exhaust the memoryso what are the errors that programmer make in languages like c that do not support garbage collection i would guess not deallocating objects after they are not used anymore but are these the only errors that we can make because of the lack of a garbage collector,"['java', 'c']" +27076,why is my join on a javascript array failing i have a function that accepts multiple arguments only one is defined in the function thoughvar getsearchfields functionmethod consolelogarguments this prints them out nicely into the console var args arguments var argsstring argsjoin i expect arg1arg2arg3 instead i get argsjoin is not a functioni just want a string of all the arguments being sent to the function i keep getting this error argsjoin is not a functioncan someone please tell me what i am doing wrong,['javascript'] +27085,access sometimes jumps to existing record on save new record access2k fesql2005 be this is my first question on so am really posting this out of desperation after searching around a lot for an answer and trying a few different things with no success i have an access database where i have recently migrated the tables to sql 2005 access continues to function to the users as a frontend providing forms reports and queries however since moving to the access fesql be setup the users have been reporting that sometimes when they are entering a new record they click into a subform saving the record or click save on the menu itself it jumps to an existing record the new record has been saved but for some reason access switches to a different record as it refreshes the user then has to close out find the saved record and continue editing it scenario a user is entering a quote and fills out all the quote details customer date etc then clicks in the lineitems subform to add a product or clicks save in the menu and suddenly the quote form and lineitem subform is showing the details of some random quote the random quote could be recent or from years ago and has nothing in common with the quote they were enteringthis weird behavior only happens on inserting a new record never on editing an existing record users tell me that it happens more often when they go to add a new quote customer whatever after opening the databasei have noticed it is only happening on forms that have subforms so my first thought is that it had to do with access sending through the subform data before the form data is saved causing a pk violation but this does not appear to be happening there are no errors on the sql server and the record is successfully saved forcing the users to save the main form record before adding subform records ie on a quote forcing them to save the quote before they can add line items did not work it just causes the jump sometimes on the save it is not vba running on the save or on current i have set breakpoints on all the event handlers as it jumps and no vba is being executed some of the jumping forms have no vba on the form but all have subforms i suspect it has to do with record lockingthe server running the tables is sql server 2005 the users are using a mix of access 20 and 2003 mostly xp sp3 with a couple of old win2k boxes they are using merge replication and a couple of users are running replicated ssee2005 editions and subscribing to the main server most users are not replicated just connecting directly to the server via odbc or sql native client connections but i have verified that this is happening to all users usually once or twice a day and it has happened to me before so it is not a user issuethe worst part about this behavior is that it only happens some of the time and i have not managed to find a scenario that will always cause it to happen if anyone has experienced anything like this before please let me know how you sorted it out or even suggestions would be welcome thanksupdate 11009 problem solved thanks to david fenton setting the form to data entry mode formdataentry true before opening it to add records does indeed prevent the jumping client reports no issues at all since i changed this a week ago thanks for your help david phillipe and tony,['sql'] +27086,select rows with maximum column value group by another column this should be a simple question but i cannot get it to work how to select rows that have the maximum column valueas group by another columnfor example i have the following table definitioniddel indexdocgroupviewidthe issue now is that i want to group by results by docgroupviewid first and then choose one row from each docgroupviewid group depending on which one has the highest del indexi tried select docgroupviewid maxdel indexid from tablegroup by docgroupviewidbut instead of return me with the correct id it returns me with the earliest id from the group with the same docgroupviewid any ideas,"['sql', 'mysql']" +27089,auto implemented properties in c is there a way to continue to utilise autoimplemented properties while still raising a change event such as inotifypropertychanged when set is calledinstead ofprivate string valuepublic string value get return this value set this value value thisvaluechangedthiseventargsempty can i just dopublic string value get set thisvaluechangedthiseventargsempty although the setter looks wrong is it possible to do this without filling my class with backingstore variablesupdate looks like there is no standard solution to my lazy objective i think that the best solution is to use coderush or resharper to generate all my backing stores for me,"['c#', '.net']" +27096,difference between scanf and strtol strtod in parsing numbers note i completely reworked the question to more properly reflect what i am setting the bounty for please excuse any inconsistencies with alreadygiven answers this might have created i did not want to create a new question as previous answers to this one might be helpfuli am working on implementing a c standard library and am confused about one specific corner of the standardthe standard defines the number formats accepted by the scanf function family d i u o x in terms of the definitions for strtol strtoul and strtodthe standard also says that fscanf will only put back a maximum of one character into the input stream and that therefore some sequences accepted by strtol strtoul and strtod are unacceptable to fscanf isoiec 989919 footnote 251i tried to find some values that would exhibit such differences it turns out that the hexadecimal prefix 0x followed by a character that is not a hexadecimal digit is one such case where the two function families differfunny enough it became apparent that no two available c libraries seem to agree on the output see test program and example output at the end of this questionwhat i would like to hear is what would be considered standardcompliant behaviour in parsing 0xz ideally citing the relevant parts from the standard to make the pointinclude stdiohinclude stdlibhinclude asserthint main int i count rc unsigned u char endptr null char culprit 0xz file io to assert fscanf sscanf file fh fopen testfile w fprintf fh s culprit rewind fh fscanf base 16 you 1 count 1 rc fscanf fh xn u count printf fscanf returned d result 2d consumed dn rc u count rewind fh strtoul base 16 you strtoul culprit endptr 16 printf strtoul result 2d consumed dn u endptr culprit puts fscanf base 0 i 1 count 1 rc fscanf fh in i count printf fscanf returned d result 2d consumed dn rc i count rewind fh strtol base 0 i strtol culprit endptr 0 printf strtoul result 2d consumed dn i endptr culprit fclose fh return 0 newlib 114fscanf returned 1 result 0 consumed 1strtoul result 0 consumed 0fscanf returned 1 result 0 consumed 1strtoul result 0 consumed 0 glibc28fscanf returned 1 result 0 consumed 2strtoul result 0 consumed 1fscanf returned 1 result 0 consumed 2strtoul result 0 consumed 1 microsoft msvcfscanf returned 0 result 1 consumed 1strtoul result 0 consumed 0fscanf returned 0 result 0 consumed 1strtoul result 0 consumed 0 ibm aixfscanf returned 0 result 1 consumed 1strtoul result 0 consumed 1fscanf returned 0 result 0 consumed 1strtoul result 0 consumed 1,['c'] +27100,definition of html whitespace rules i am looking for this definition to make my html renderer conform a bit better currently it is guessing which whitespace to keep which to collapse and what to throw the sgml standard is hard to find and the html standard does not seem to treat the subject with the required depth for my needscurrently my renderer parses the html into a tree and then does a recursive layout pass to position all the elements and their content i am experimenting with throwing some whitespace out in the parse stage ie not emitting whitespace only text chunks in certain circumstances which kinda works for the majority of cases but there are a fair few edge cases that are getting hard to deal withi am also working on an editor subclass of the html control and layout time solutions are proving to be a bit problem in the editor hence me working on getting them into the parse stage the layout information is not available till reflow time which is some time after you have edited the documentfire away with linkageflames,['html'] +27107,fatal error lnk1302 only support linking safe netmodules unable to link ijwnative netmodule i have native unmanaged code i have created a managed c dll and try to include this dll into native unmanaged code i got the following errorfatal error lnk1302 only support linking safe netmodules unable to link ijwnative netmodulehow can i include managed cclr dll into native unmanaged code,['c++'] +27121,most memory efficient way to grow an array in java i am not too concerned about time efficiency the operation will be rare but rather about memory efficiency can i grow the array without temporarily having all the values twiceis there a more efficient way to grow a large array than creating a new one and copying over all the values like concatenating it with a new onewhat about having fixedsize arrays stored in another array and reallocate copy that toplevel one would that leave the actual values in placei am aware of arraylist but i need a lot of control about accessing the array and the access needs to be very fast for instance i think i prefer ai to algetithe main reason why i care about this is that the array in question or a number of such arrays might very well occupy a large enough portion of main memory that the usual strategy of creating a double sized copy before thiscarding the original might not work out this may mean that i need to reconsider the overall strategy or up my hardware recommendations,['java'] +27126,how to use bluetooth to connect two iphone i want to use iphone sdk to implement a bluetooth connection between two iphones but i do not find any bluetooth api in iphone sdk 30 can anybody help me thanksbtw is it possible to connect more than two iphones at the same time by using bluetooth,['iphone'] +27131,preventing memory issues when handling large amounts of text i have written a program which analyzes a projects source code and reports various issues and metrics based on the codeto analyze the source code i load the code files that exist in the projects directory structure and analyze the code from memory the code goes through extensive processing before it is passed to other methods to be analyzed furtherthe code is passed around to several classes when it is processedthe other day i was running it on one of the larger project my group has and my program crapped out on me because there was too much source code loaded into memory this is a corner case at this point but i want to be able to handle this issue in the future what would be the best way to avoid memory issuesi am thinking about loading the code do the initial processing of the file then serialize the results to thisk so that when i need to access them again i do not have to go through the process of manipulating the raw code again does this make sense or is the serializationdeserialization more expensive then processing the code againi want to keep a reasonable level of performance while addressing this problem most of the time the source code will fit into memory without issue so is there a way to only page my information when i am low on memory is there a way to tell when my application is running low on memoryupdatethe problem is not that a single file fills memory its all of the files in memory at once fill memory my current idea is to rotate off the thisk drive when i process them,['c#'] +27134,indexof syntax for multidimensional arrays what is the syntax for indexof to go through a multidimensional arrayfor instancevar x do somethingxpushabxindexofa i want to find a and do something with b but it does not work as this method should be iterative itself i do not presume using any other iteration would be a good thing to do currently i simulate this using 2 simple arrays but i guess this should somehow work too,['javascript'] +27138,how do i execute a set of goals before my maven plugin runs i am writing a maven plugin mojo that needs to execute a standard set of other plugin executions before it is runis there a mechanism to declare all the goals within my plugin so i do not have to rely on the user defining them all in their pom,['java'] +27142,looping through rows in a dataview the dataview object does not have a rows property like datatablehow do i loop through the rows of a dataview,['.net'] +27153,can a php script continue running after ending the http request how do i write a php script that continues running even after flushing out some text and ending the http request is this possible,['php'] +27184,easiest way to convert a list to a set in java what is the easiest way to convert a list to a set in java,['java'] +27186,sql query need to get names where countid 2 i have a table programparticipants i am currently successfully querying the ids where countname 1 what i need now is to query the names that belong to those ids where countname 1example data result currently being returnedid countname1 23 44 3example data result neededid name1 nm11 nm33 nm23 nm33 nm43 nm74 nm54 nm84 nm9,['sql'] +27198,jquery select based on text i need to select an element based on its text in jqueryfor instancespanthis textspani know i can use contains to select based on text but it is not exclusivei do not want to selectspanthis text and that textspani want to select the element if it is the only text of the elementaside from using regex how do i do this with jquery selectorsthanks,['jquery'] +27199,add text to text area using javascript how can i add custom text to already written text in textarea using javascriptthanks,['javascript'] +27201,include struct in the union def with bisonyacc i am trying to include a struct as part of the union with bison but i get an error on the struct node args in union parsery17 error field aargsa has incomplete typethe codestruct node char val struct node nextunion char string struct node argstoken string cd word pwd exittype args arg listanyone know what i am doing wrong,['c'] +27202,c aspnet button click event not working i have an aspnet c page with some 3rd party controls some ajaxy stuff and some normal aspnet button controlsthe button click events do not fire when clickeddoubleclicking the button in design mode in vs 2008 switches to the codebehind but does not create the event handlercreating the event handler manually does not helpthe whole page is too big to include here but this is the top bit page languagec masterpagefilebasewidepage2master autoeventwireuptrue enableeventvalidationfalse codefilecompanycomplianceaspxcs inheritscompanycompliancepage title3dss register assemblyajaxcontroltoolkit namespaceajaxcontroltoolkit tagprefixcc1 register assemblyobout grid net namespaceoboutgrid tagprefixcc2 register srcusercontrolscalendarexascx tagnamecalendarex tagprefixuc2 mastertype virtualpathbasewidepage2master aspcontent idcontent2 contentplaceholderidcontentplaceholder1 runatserver script typetextjavascript a bunch of function declarations scriptand my button declaration on the pageaspbutton idlicensecsvbutton runatserver textexport to csv onclicklicensecsvbutton click and the codebehindprotected void licensecsvbutton clickobject sender eventargs e get data companycompliance cc new companycompliancemasterthecompanyid datatable dt ccbusinesslicensestables0 send to browser as download toolssendtableascsvtobrowserresponse dt licensedataany ideas could it be the ajax or something maybe the 3rd party obout grid controlupdatei did fix this a month or two ago so i came back to this question to answer it for posterity but could not remember exactly how i fixed it curse you old age i had some limited success by replacing some of the aspnet ajax controls with jquery ui ones but i think the real solution was that one of the properties in the one of the tags was pointing to a control that no longer existed if youre in this same situation try that and let me know what works in the comments and i will post the correct answer,"['c#', 'asp.net']" +27212,string formatting remove leading chars i have a string like this 001140 or 0240 how do i formated so that i can always get rid of the leading zeros and colons so it looks like this 1140 or 240,['ruby'] +27230,how to show special page for ie6 users requesting them to upgrade in aspnet mvc just like the every other web developer i am frustrated to hack my site code to work with ie 6 so decided to give up support for ie 6 and ask them politely to upgrade to ie 7 or firefoxcan you suggest me how to detect ie6 users and thisplay a special page showing the upgrade details in aspnet mvc is handling this at server side scripting a good idea or do you recommend to use any client side script like jquery to handle this,['asp.net'] +27249,generating java code parse trees and evaluating it for testing we have a need to generate java source code we do this by modeling the abstract syntax tree and have a tree walker that generate the actual source code text this far all goodsince my ast code is a bit old it does not have support for annotations and generics so i am looking around for open projects to use for future projects with code generation needs and this is where the actual issue comes we want to test that the code generated has the correct behaviorhere is where i got the idea to actually evaluate the ast instead of generating the java source code compile it and run tests against that code an evaluator would speed up the unit tests and one could evaluate smaller pieces of generated code such as only a method making the units more reasonableso far i have found the comsuncodemodel project that seems quite nice as for being a modern support for java5 and 6 features ast based codegenerating solutionanyone know if there is another project that would allow me to evaluate pieces of ast directly such as a single generated method,['java'] +27251,how to lock file please tell me how to lock file in cthanks,"['c#', '.net']" +27254,is there a way to get which classes a classloader has loaded i am trying to implement some unit testing for an old framework i am attempting to mock out the database layer unfortunately our framework is a bit old and not quite using best practices so there is no clear separation of concerns i am bit worried that trying to mock out the database layer might make the jvm load a huge number of classes that would not even be used i do not really understand class loaders that well so this might not be a problem is there a way to take a peak at all the classes a particular classloader has loaded to prove what is going on under the hood,['java'] +27261,any way to clear pythons idle window i know there is a similar topic about python console but i do not know if they are the same i tried systemclear and it did not work herehow do i clear pythons idle window,['python'] +27266,explaining persistent data structures in simple terms i am working on a library for python that implements some persistent data structures mainly as a learning exercise however i am beginning to learn that explaining persistent data structures to people unfamiliar with them can be difficult can someone help me think of an easy or at least the least complicated way to describe persistent data structures to themi have had a couple of people tell me that the documentation that i have is somewhat confusingand before anyone asks no i do not mean persistent data structures as in persisted to the file system google persistent data structures if youre unclear on this,['python'] +27272,validate number of days in a given month performance is of the utmost importance on this one guys this thing needs to be lightning fasthow would you validate the number of days in a given monthmy first thought was to make an array containing the days of a given month with the index representing the monthvar daysinmonth 31 january 28 february 31 march etcand then do something along the lines offunction validatedaysinmonthdays month if days 1 days daysinmonthmonth throw new errorfrackbut what about leap years how can i implement checking for leap years and keep the function running relatively fastupdate i would like you guys to show me some code which does the days in month leap year validationheres the flowchart describing the logic used today,['javascript'] +27276,multiples of 1010010 c i want an integer to be multiples of 1010010 and so on for eg double val 35 then i want int 40val 357 then i want int val 400val 245567 then i want int val 30val 245567986 then also i want int 30 is there anything in c that can help in generating these integer basic logic that i can think is extract the first integer add 1 to it count the total number of digits and add zeros totalno 1 is there any better way i want to assign these values to the chart axis i am trying to dynamically create the axis label values based on datapoints of the charts,['c#'] +27281,time complexity analysis of code int fooint n int x2 while xn x x return xi need to analyze its time complexity i noticed it reaches n much faster than just logn i mean it does less steps than ologn would do i read the answer but have no idea how they got to it it is ologlogn now how do you approach such a question,['c'] +27284,best way to check if systemtype is a descendant of a given class consider the following codepublic class a public class b a public class c b class d public static bool isdescendantofthis systemtype thistype systemtype thattype void main a cvalue new c cgettypeisdescendantofcvaluegettype what is the best way to implement isdescendantof,"['c#', '.net']" +27291,slice up an image into tiles given a loaded bitmap object i want to slice up this image into 256x256 tiles and save out each tile as a jpg fileyou may think this as a silverlight deep zoom sort task and youd be righti have got a solution using wpf but i would prefer a solution that would work in the net 20 framework gdi is not somewhere i have spent any amount of timeanyone know how i could go about this i cannot seem to find a create bitmap from a specified rectangle sort of method i would be surprised if one does not exist but perhaps i cannot see the wood for the trees,"['c#', '.net']" +27292,what do you do in sql server to create or alter the year is 2009 and sql server does not have create or alterreplace this is what i do insteadif exists select 1 from information schemaroutines where routine name synchronizeremotecatalog and routine schema dbo and routine type procedure exec drop procedure dbosynchronizeremotecatalogcreate procedure dbosynchronizeremotecatalogas begin bodyendfor triggers you have to lean on the proprietary system viewsis this the most accepted convention in the meantimeedit as n8wrl suggested the official word suggests that this feature is not a high priority hence the question,['sql'] +27305,get a list of solutionproject files for vs addin or dxcore plugin i am trying to write a addin for visual studio that among other things needs to keep track of every file in a visual studio solution i know what events i need to subscribe to when a solution is opened when a file is addedremovededited in it the same for projects etc but i do not understand how to actually get a list of files from any of iti recently installed coderush and have been playing with the dxcore framework i am very happy with it is approach at plugins but i still do not see an obvious way to get a list of files in the solutionso to sum it up how via the visual studio sdk or dxcore do i get a reliable list of files in the solution and it is projects,['c#'] +27307,c copy one bool to another by ref not val i am at a brick wall here is it possible to copy one bool to the ref of another consider this code bool a falsebool b ab is now a totally separate bool with a value of false if i subsequently change a it will have no effect on b is it possible to make a b by ref how would i do thatmany thanks,"['c#', '.net']" +27309,why is my castle windsor controller factorys getcontrollerinstance being called with a null value i am using castle windsor to manage controller instances among other things my controller factory looks like thispublic class windsorcontrollerfactory defaultcontrollerfactory private windsorcontainer container public windsorcontrollerfactory container new windsorcontainernew xmlinterpreter var controllertypes from t in assemblygetexecutingassemblygettypes where typeofcontrollerisassignablefromt select t foreach type t in controllertypes containeraddcomponentlifestyletfullname t lifestyletypetransient protected override icontroller getcontrollerinstancetype controllertype return icontroller containerresolvecontrollertype argumentnullexception is thrown here when i start up my aspnet mvc application and try to go to or another path i get an argumentnullexception i put a break point on entry of the getcontrollerinstance and found that it is called once with my homecontroller then a second time with null which is when the exception is thrown why is it being called againshould i change the method to something like thisprotected override icontroller getcontrollerinstancetype controllertype if controllertype null return null return icontroller containerresolvecontrollertype,['c#'] +27331,c stl containers whats the difference between deque and list what is the difference between the two i mean the methods are all the same so for a user they work identically is that correct,['c++'] +27336,c get and set the high order word of an integer whats an efficient or syntactically simple way to get and set the high order part of an integer,['c#'] +27337,iphone push notfication for a webapp is it possible to implement iphones push notification service for a webapp that has an icon on the desktop if so how,['iphone'] +27364,connecting to ldap from c using directoryservices i am trying to connect to an edirectory 88 server running ldap how would i go about doing that in net can i still use the classes in systemdirectoryservice such as directoryentry and directorysearcher or are they ad specific do i need to specify the connection string any differentlyi am trying something like the code below but it does not seem to workdirectoryentry de new directoryentry ldapnovellboxsamplecomadminpasswordauthenticationtypesnonedirectorysearcher ds new directorysearcherdevar test dsfindallany ideas,['c#'] +27375,protocol buffers java rpc stack according to this wikipedia entryprotocol buffers is very similar to facebookas thrift protocol except it does not include a concrete rpc stack to use for defined services since protocol buffers was open sourced a number of rpc stacks have emerged to fill this gaphowever there are no examples of rpc stacks cited can anyone suggest a javabased implementation of an rpc stack,['java'] +27391,installing python imaging library pil on snow leopard with updated python 262 i have a fresh install started with a wiped drive of snow leopard with the developer tools installed during the snow leopard installationi then installed python 262 replacing the snow leopard default python 261 i have tried to install pil byeasy installpipdownloading source and running python setuppy build manuallyall yield the same error link to pip log i have seen others have had success installing pil using the snow leopard default python 261 so i am not sure why i am having so much trouble getting it to work with 262,['python'] +27394,comparison of ci servers i am searching for a comparison of differentcontinuous integration ci servers esp focusingon net and could not find anytherefore i would like to know what you think about thedifferent solutions available what are the pros and conswhat are the hosting requirements and why ci server xy isthe server of your choicei am interested in your thoughts on feel free to comment onothers tohudson cruisecontrolcruisecontrolnetteamcitycifactory uses cruisecontrolnetpoints of interest areconfiguration easy flexibleintegration with scm esp dsvc like git or hgintegration with build sytems msbuild nant rakeintegration with testing frameworksintegration with source anaylsis simian ndepend fxcop ncover etcwebinterfacedashboardsinfrastructure requirements,['.net'] +27395,how to get a class object from the class name in java i know the class name say myclass and want to retrieve the class object ie myclassclass for future references is there a way to do thati have looked through the web but most of the things i found related to it were about the classloader which i presume are not suitable for my case i do not want to initialize a class but only get a class object for future usesedit regarding the first answers to thisi have already checked the forname method but i thought that is supposed to also initialize the class now i can call it with the full arguments and pass false to the second argument but would the third have to be null or whatwouldclassfornamemyclass false nullreturn myclassclassin fact what i want to do is replace an array of string ids associated with class objects with an array of ids from which the class objects are fetched automatically to get rid of some manual work thanks for the quick answers and sorry for not mentioning this before,['java'] +27407,how can i get the destination url using curl how can i get the destination url using curl when the http status code is 302phpurl ch curl initcurl setoptch curlopt urlurlcurl setoptch curlopt returntransfer 1html curl execchstatus code curl getinfochcurlinfo http codeifstatus code302 or status code301 url i want to to get the destination urlcurl closech,"['php', 'html']" +27425,how to implement java 256bit aes encryption with cbc i have read the following threads and they have helped a little but i am looking for a little more infohow to write aescbcpkcs5padding encryption and decryption with initialization vector parameter for blackberry java 256bit aes encryptionbasically what i am doing is writing a program that will encrypt a request to be sent over tcpip and then decrypted by a server program the encryption will need to be aes and doing some research i found out i need to use cbc and pkcs5padding so basically i need a secret key and an iv as well the application i am developing is for a phone so i want to use the java security packages to keep the size down i have got the design done but unsure of the implementation of the iv and the shared keyheres some code my user namebyte loginid logingetbytesbyte presharedkey128 acme1234acgetbytesbyte presharedkey192 acme1234acme1234agetbytes 256 bit keybyte presharedkey256 acme1234acme1234acme1234getbytesbyte presharedkey presharedkey256 initialization vector required for cbcbyte iv 0x0x0x0x0x0x0x0x0x0x0x0x0x0x0x0x00ivparameterspec ips new ivparameterspecivbyte encodedkey new byteloginidlength presharedkeylengthsystemarraycopyloginid 0 encodedkey 0 loginidlengthsystemarraycopypresharedkey 0 encodedkey loginidlength presharedkeylength the secretkeyspec provides a mechanism for applicationspecific generation of cryptography keys for consumption by the java crypto classes create a key specification first based on our key inputsecretkey aeskey new secretkeyspecencodedkey aes create a cipher for encrypting the data using the key we createdcipher encryptcipherencryptcipher ciphergetinstanceaescbcpkcs5padding initialize the cipher with key and parametersencryptcipherinitcipherencrypt mode aeskey ips our cleartextstring clearstring 33824409411501202251701v330byte cleartext clearstringgetbytes encrypt the cleartextbyte ciphertext encryptcipherdofinalcleartext now decrypt back again decryption ciphercipher decryptcipher ciphergetinstanceaescbcpkcs5padding initialize pbe cipher with key and parametersdecryptcipherinitcipherdecrypt mode aeskey ips decrypt the cleartextbyte deciphertext decryptcipherdofinalciphertextin a nutshell what it should do is encrypt some message that can decrypted by the server without the server needing to get a key or iv from the phone is there a way i could do this where i could secure the iv and key on the phone and still have the key and iv known by the server as well feel free to tell me to make things more clear if they are not,['java'] +27443,which sql server data type best represents a double in c is it money float real decimal,"['c#', 'sql']" +27446,set bufferedimage to be a color in java i need to create a rectangular bufferedimage with specified color as a background draw some pattern on the background and save it to file my problem comes from how to create the backgroundi am using nexted loopbufferedimage b img for every rowfor every columnsetrgbrgbbut it is very slow when the image is largehow to set the color in a more efficient way,['java'] +27460,c attributeusage for specific class is it possible to have something like attributeusage to restrict the use of an attribute to a specific class not just attributetargetsclass that would be any class,['c#'] +27470,how do i force redrawing drawrect of a subview when it changes dimensions i have a uiview that contains a row of subclasses of uiview the subclass has overridden drawrect and has set contentmode uiviewcontentmoderedrawas the user squashes and stretches the parent container the child views squash and stretch as the shape change occurs i would like to have drawrect called repeatedly to change the contents of the child views so far i have been unsuccessful what is the correct way to do thischeersdoug,"['ios', 'objective-c', 'iphone']" +27474,how to solve base controller dependency injection for testing purposes i have implemented my mvc base controller called defaultcontroller using dependency injection pattern in order to be able to construct test cases example belowpublic class defaultcontroller controller protected readonly isessionhelper sessionhelper string thisuseropenid protected iusersrepository userrepository public defaultcontroller not for testing public defaultcontrollerisessionhelper session iuserrepository repo sessionhelpersession userrepository repo then i have my controllers using this controller homecontroller usercontroller etcnow building some test cases i found myself in a situation where i do not know how to actually use the injection dependency pattern testmethod public void welcome message in viewdata has coockie user thisplay name below i want to insert fakerepositories using isessionhelper and so on but the constructor for homecontroller do not have it homecontroller controller new homecontrollerany ideas,"['c#', '.net']" +27492,the power of net without the garbage collection i love c because the powerful features of the net framework make it so easy to develop for windows however i also love standard c primarily because it gives me finetuned control over memory management is there a way to have the best of both worlds are there c libraries that can compete with the rich set of libraries in the net framework or is there a way to manually deallocate memory in one of the net languages that i have never used or is it possible to use a net dll in a standard c application i know i am really stretching here but i believe in magic,"['c#', '.net', 'c++']" +27496,how to extract last value in the url using jquery how to extract the last value that is 1 from the following url using jqueryurl formbuilderindexphpreportsexport1,['jquery'] +27505,difference between rest and webservices what is difference between rest and webservice soap i looked at the facebook api they use http headers and some parameters probably xml or non and return result in xml where else soap does exactly same http headers xml parameters and returns headers xmlrest also requires some authenticated token where else soap uses http session which is exactly same token used for auth and other information all i can see that soap is little advanced version of rest or are there any other performance considerations reading about rest just talks very high level of client server communication but even soap does exactly same can anyone point me where it can define correct boundry of rest and soapwe use lot of soap transparently in net however i just want to know is it really worth paying attension to rest where currently everything is running outstandingly smoothi know rest is an architecture and soap is a protocol but my question is in detail that is currently the aspnet webservice implementation of soap has rest architecture,['asp.net'] +27515,jquery toggle changes elements width i do not want it to i currently have a table that has a width of 94 and the following toggle set to itdocumentreadyfunctionmoreinfohidetoggleinfoclickfunction moreinfotogglenormalit toggles fine but as soon as you toggle the width goes really small and i have no idea why if i remove the hide it is the right width but again as soon as i start toggling it the width automatically resizesjust tried the following css toomoreinfo width 94 important edit it seems to completely remove any width applied through css when i toggle itedit2 wrapping it inside another div works not ideal but not a bad solution i guessany way to stop this please,"['javascript', 'jquery', 'html']" +27525,develop cnet on android devices i want to run c programs on my htc magic i can find the mono app on the android market but i have no clue on how to run c usingthe code is just for fun i do not want official support and such after coding visual basic on windows mobile i really want to code c on android whether directly using some sort of editor if exists or compiling it on a pc then installing it on androidif anyone knows a way to do such please let me knowthank you,"['c#', 'android', '.net']" +27544,is it possible to configure log4j to create a new file with every run of the application for example the first time i run an application or immediately after i clear out the logs directory i want log4j to write the applications logs to a file called log0 then i exit the application and restart it i want the logs to be written to log1 and so oni would like to keep this in the configuration file although if i cannot i guess i could always do it in my application when log4j is set upis this possible if so how,['java'] +27551,how to thisplay text in the browser status bar how can we change the text thisplayed in the browser status bar using javascript or jquery,"['javascript', 'jquery']" +27552,python module for creating pidbased lockfile i am writing a python script that may or may not depending on a bunch of things run for a long time and i would like to make sure that multiple instances started via cron do not step on each others toes the logical way to do this seems to be a pidbased lockfilea but i do not want to reinvent the wheel if there is already code to do thisso is there a python module out there which will manage the details of a pidbased lockfile,['python'] +27562,tinymce is changing my inline css i input this in the html editor p styleborder1px solid edede4bordertopnonepi click update and click the html editor again the html in firefox has changed to p styleborderstyle none solid solid bordercolor mozusetextcolor rgb237 237 228 rgb237 237 228 borderwidth medium 1px 1px mce styleborder1px solid edede4bordertopnonebrpif i do the same thing in internet explorer the html changes top styleborderright edede4 1px solid bordertop medium none borderleft edede4 1px solid borderbottom edede4 1px solid mce styleborder1px solid edede4bordertopnonenbsppwhy in the world does it change maybe there are some tinymce settings i can change but i already have cleanup false ideasif i enable cleanup the change i am mentioning does not happen however tinymce changes a lot of other stuff i do not want it to mess with my code any help would be appreciated,"['javascript', 'css']" +27579,const usage with pointers in c i am going over c and have a question regarding const usage with pointers i understand the following codeconst char somearraythis is defining a pointer that points to types of char and the const modifier means that the values stored in somearray cannot be changed however what does the following meanchar const arrayis this an alternate way of specifying a parameter that is a char pointer to an array named array that is const and cannot be modified lastly what does this combination meanconst char const s2for reference these are taken from the deitel c programming book in chapter 7 and all of these are used as parameters passed to functions,['c'] +27619,alternatives to dwr wdirectwebremotingorg i have been a big of dwr wdirectwebremotingorg in the past and have used it on a few projects it makes ajax easy by creating javascript proxy stubs to java classes on the serverwhile dwr has been around for years it seems to have slowed down ever since the main developer moved on it is also quite large compared to it is early daysas far as the need for a simply java to javascript proxyingmarshelling essentially abstract the lower level ajax stuff can anyone recommend an alternative all i have found is rajax but that is quite dated as wellthanks,['java'] +27639,low latency audio api for android what are my options for playing simultaneous audio on an android device with the least amount of latency am i going to get anything half decent out of the canned sdk or is that asking too much the documentation claims that the soundpool class is capable of playing multiple sounds simultaneously with relatively good performance but after running some tests in the emulator and on a physical device it seems pretty weak is there maybe a trick to it or do i have to go to a much lower level api for this kind of thing i have tried using a single sound pool with multiple samples loaded and i have tried multiple sound pools each managing a single sample i am preloading everything so that when i attempt to play back i have no additional code being executed other than the call to soundpoolplay,"['java', 'android']" +27647,variable length of s with the operator in python i am trying to do thismax title width maxlentext for text in columnsfor column in columns print 10s blah columnbut i want to replace the 10 with the value of max title width how do i do this in the most pythonic way possible,['python'] +27648,whats the main difference between cucumber and shoulda how would you make a decision between cucumber and shoulda if you were about to choose a testing framework what differentiates these two frameworks primarily,['ruby'] +27651,what is the usage of pdbs program debug database when compiling a library or an application eg a console application in the visual studio ide in the debug folder of the application apart from the dll or exe there will be one more file with extension pdb what is the exact usage of this pdb file,['c#'] +27652,how to install mysqldb package importerror no module named setuptools i am trying to install mysqldb package i found the source code herei did the followinggunzip mysqlpython123c1targztar xvf mysqlpython123c1tarcd mysqlpython123c1python setuppy buildas the result i got the followingtraceback most recent call last file setuppy line 5 in from setuptools import setup extensionimporterror no module named setuptoolsdoes anybody knows how to solve this problemby the way if i am able to do the described step i will need to do the followingsudo python setuppy installand i have no systemadministratorrights do i still have a chance to install mysqldbthank you,"['python', 'mysql']" +27661,how should i create my guid i am going to be uploading images to a system and need them to be referenced by a nonsequential unique id i have read a little about guids and i am wondering what the best approach to making one in php is should i md5 the current timestamp and salt it or will phps uniqueid function be sufficient enoughthanks,['php'] +27662,get daylight saving transition dates for time zones in java i would like to know the simplest way in java to get a list of dates in the future where daylight savings time will changeone rather inellegant way to do this would be to simply iterate over a bunch of years worth of days testing them against timezoneindaylighttime this will work and i am not worried about efficiency since this will only need to run every time my app starts but i wonder if there is a simpler wayif youre wondering why i am doing this it is because i have a javascript app which needs to handle thirdparty data containing utc timestamps i want a reliable way to translate from gmt to est on the client side see i have written some javascript which will do it but i want to get precise transition dates from the server,['java'] +27668,how to use dependency injection and the repository pattern with aspnet web services with regular aspnet mvc pages the repository is passed in to the constructor of the control then the tests can instantiate the controller passing in a mock repositoryhow can i do this with web services the problem i see is that we do not have the equivalent of controllerbuildersetcontrollerfactorywhat are the best practices to get my ioc framework castle to instantiate my web service with the correct repository implementationi thought there might be a way to extend httphandler and change the way the web service is actually instantiated i believe this is how the mvc framework does it,['asp.net'] +27672,how to write your own right click menu and thisable the default using jqueryjavascript i successfully thisabled the right click event on the page that i am working on using jquery i want to create a customize right click menu how can i do this does this need relevant css setting to get it working ie position,"['javascript', 'jquery']" +27674,change the focus from one text widget to another i am new to python and i am trying to create a simple gui using tkinter so often in many user interfaces hitting the tab button will change the focus from one text widget to another whenever i am in a text widget tab only indents the text cursordoes anyone know if this is configurable if not can pyqt or any other python ui framework offer this functionality,['python'] +27687,why ob start must come ahead of session start to work in php i do not think it is reasonablewhy is it actually such a rule,['php'] +27688,is there a php validator is there a php validator like there is an html validator at w3org,['php'] +27706,jquery live change in not working in ie6 ie7 the code below works as expected in ff but not in iesdocumentreadyfunction divfacet dropdown selectlivechange function var changed facet thisattrid var facets select thisclosestform var args windowlocationhrefsplit0 ajax1 var clear false forvar i 0 i facetslength i var ob facetsi var val obval ifclear val args obattrid val ifobattrid changed facet clear true getjsonargs functionjson forwidget id in json var sel field widget id divwidget selhtmljsonwidget id,"['javascript', 'jquery']" +27726,does anyone use the swingx extensions to swing i have seen swingx mentioned and referred to herehowever every time i try to visit the siteit is down is this still an active viable project or is it outdated and abandoned,['java'] +27745,does the enumerator of a dictionary return key value pairs in the order they were added i understand that a dictionary is not an ordered collection and one should not depend on the order of insertion and retrieval in a dictionaryhowever this is what i noticedadded 20 key value pairs to a dictionaryretrieved them by doing a foreachkeyvaluepairthe order of retrieval was same as the order in which they were addedtested for around 16 key value pairsis this by design,"['c#', '.net']" +27746,exception for missing data i was wondering what kind of exception should one throw for missing data for example if an xml node does not contain data it would be easy to throw new exception but this is not recommended another option would be to create a new exception class like missingdataexception or invaliddataexception but is not there a builtin exception class for this case,['c#'] +27748,declaring a c function to return an array how can i make a function which returns an array i tried thisconst int width11const int height11int main char awidthheight arand gridwidthheight return 0 initializes a random boardchar rand gridint i int k char aik forj0jij forl0lkl ajlran10 return a returns a random number from the set 09int ranint i srandunsigned int time0 returnrand10,['c'] +27751,is it safe to allow users to edit css i have a web application where i would like to allow end users to customise the look of the web site by uploading their own css fileare there any security issues with this i cannot see anything obvious but thought i would ask in case there was anything i would missed,['css'] +27752,c keep session id over httpwebrequest i need to preserve the same session id when navigating over a sites pages using cnet like a crawler i found a couple of methods a http sniffer was very handy to compare what my ie browser was sending http request and receiving from the web server http response as the important information is in the headers that are not thisplayed by the browserplease do not make confusion between session id which is public from server to browser and servers session variables which are private to server code like phpwebheadercollection headercollection new webheadercollectionusing httpwebresponse response httpwebresponserequestgetresponse save headers for int i 0 i responseheaderscount i headercollectionaddresponseheadersallkeysi responseheadersgeti save cookies cookiecontainer new cookiecontainer foreach cookie cookie in responsecookies cookiecontaineraddcookie to make the other get or post requestshttpwebrequest request httpwebrequestwebrequestcreateuri restore phpsessid for int i 0 i headercollectioncount i string key headercollectiongetkeyi if key setcookie key cookie else continue string value headercollectiongeti requestheadersaddkey value restore cookies requestcookiecontainer cookiecontainer complete request stream writestream requestgetrequeststreammy request is to contribute with better code or additional ideas to make a better crawler session preserving,['c#'] +27754,how to remove the white reflection on the application icon possible duplicatehow to thisable highlighting of the app icon hi this is an iphone objective c questionwhen i set the icon file for the app say iconpng when it is shown on the phone a white reflection effect is automatically added on the iconpngis there any way to remove te reflection effect cause i can see that there are apps without the white reflection effect on the icons,['iphone'] +27777,select range of text in wpf richtextbox flowdocument programmatically i have this wpf richtextbox and i want to programmatically select a given range of letterswords and highlight it i have tried this but it does not work probably because i am not taking into account some hidden flowdocument tags or similar for example i want to select letters 38 but 26 gets selectedvar start myrichtextboxdocumentcontentstartvar startpos startgetpositionatoffset3var endpos startgetpositionatoffset8var textrange new textrangestartposendpostextrangeapplypropertyvaluetextelementforegroundproperty new solidcolorbrushcolorsbluetextrangeapplypropertyvaluetextelementfontweightproperty fontweightsboldi have realised richtextbox handling is a bit trickier than i thought update i got a few answers on the msdn forums this thread where dekurver seid the offsets youre specifying are not character offsets but symbol offsets what you need to do is get a textpointer that you know is adjacent to text then you can add character offsetsand lesterlobo saidyou will need to loop through the paragraphs and inlines to find the next and then their offsets in a loop to apply for all appearances of the specific text note that when you edit your text would move but your highlight wouldnt move as its associated with the offset not the text you could however create a custom run and provide a highlight for itwould still love to see some sample code for this if someone knows their way around flowdocumentsedit i got a version of kratz vb code working it looks like thisprivate static textpointer getpointtextpointer start int x var ret start var i 0 while i x ret null if retgetpointercontextlogicaldirectionbackward textpointercontexttext retgetpointercontextlogicaldirectionbackward textpointercontextnone i if retgetpositionatoffset1 logicaldirectionforward null return ret ret retgetpositionatoffset1 logicaldirectionforward return retand i use it like thiscolorizeitemoffset itemtextlength colorsblueprivate void colorizeint offset int length color color var textrange myrichtextboxselection var start myrichtextboxdocumentcontentstart var startpos getpointstart offset var endpos getpointstart offset length textrangeselectstartpos endpos textrangeapplypropertyvaluetextelementforegroundproperty new solidcolorbrushcolor textrangeapplypropertyvaluetextelementfontweightproperty fontweightsbold,['c#'] +27793,how to access mysql from multiple threads concurrently were doing a small benchmark of mysql where we want to see how it performs for our datapart of that test is to see how it works when multiple concurrent threads hammers the server with various queriesthe mysql documentation 50 is not really clear about multi threaded clients i should point out that i do link against the thread safe library libmysqlclient rsoi am using prepared statements and do both read select and write update insert delete should i open one connection per thread and if so how do i even do this it seems mysql real connect returns the original db handle which i got when i called mysql initif not how do i make sure results and methods such as mysql affected rows returns the correct value instead of colliding with other threads calls mutexlocks could work but it feels wrong,"['c++', 'mysql', 'c']" +27812,jquery wait for function to complete to continue processing hey all i have what appears to be a trivial problem i have the following javascriptfunction var r getresults forvar i 0 i rlength i do stuff with r function getresults getjsoncontrollermethod null functiondata return data due to the fact that i am calling a method asynchronously the script continues executing and when it encounters the for loop r obviously is not going to have a value yet my question is when i have a method that is doing an asynchronous operation and i am dependent on the data it returns back in the main block how do i halt execution until the data is returned something likevar r getresultsparam function where the function is a callback function i cannot move the for loop processing into the callback function of the json request because i am reusing the functionality of getresults several time throughout the page unless i want to duplicate the code any ideas,"['javascript', 'jquery']" +27813,cannot modify c string consider the following codeint mainvoid char test abcdefghijklmnopqrstuvwxyz test5 x printfsn test return exit successin my opinion this should print abcdexghij however it just terminates without printing anythingint mainvoid char test abcdefghijklmnopqrstuvwxyz printfsn test return exit successthis however works just fine so did i misunderstand the concept of manipulating c strings or something in case it is important i am running mac os x 106 and it is a 32bit binary i am compiling,['c'] +27820,hiding the keyboard when losing focus on a uitextview so i have a uitextview that i am using to allow the user to submit some textmy problem is i cannot seem to figure out how to allow the user to cancel by tapping away from the uitextview,"['iphone', 'objective-c']" +27835,can youshould you use sql server service broker with net applications i have many operations in the database that need to trigger application code currently i am using database polling but i hear that sql server service broker can give me msmqlike functionalitycan i listen to sql server service broker queues from net applications running on a different machineif so should i do itif not what would you recommend,['.net'] +27841,why is it called wchar t and not simply wchar i have often wondered why c went with the name wchar t instead of simply wchar and i have never been able to find an answer search engines are no help because they think i am asking about windows wchar type any ideas,"['c++', 'c']" +27843,how do i read all classes from a java package in the classpath i need to read classes contained in a java package those classes are in classpath i need to do this task from a java program directly do you know a simple way to dolistclass classes readclassesfrommypackage,['java'] +27858,jquery ajax success anonymous function scope how do i update the returnhtml variable from within the anonymous success functionfunction getpriceproductid storeid var returnhtml jqueryajax url includesunitjsp params cache false datatype html success functionhtml returnhtml html return returnhtml,['jquery'] +27859,how to modify style attribute of element with known id using jquery i got 3 buttonslinks triggering some javascript code with indication if certain button is selected selected button got style attribute set to btn brown selected while other buttons got this attribute set to btn brownonly one button can be selected at one time each of buttons got different unique id my question is how using jquery access certain button to modify it is style attr what i need its only how to access by id single button and modify its style attribute to get immediate update on the screenthanks in advancemth,"['jquery', 'html', 'css']" +27865,sql question does the order of the where clause make a difference from a performance standpoint does the order of my sql where statements make a differencefor instanceselect from where a 1and b 2would that be any fasterslower thanselect from where b 2and a 1let us also assume that i know in advance that a 1 will narrow the result set the mostalso does it matter if i am joining two or more tables the order of my where statements,['sql'] +27867,vtable for referenced from compile error xcode i was getting the following error compiling an iphone project anybody know how i may fix it vtable for onedmultiformatupceanreader referenced from ztvn4oned23multiformatupceanreaderenon lazy ptr in multiformatupceanreaderold symbols not foundcollect2 ld returned 1 exit status,"['c++', 'iphone']" +27872,moq how do you test internal methods told by my boss to use moq and that is iti like it but it seems that unlike mstest or mbunit etc you cannot test internal methodsso i am forced to make public some internal implementation in my interface so that i can test itam i missing somethingcan you test internal methods using moqthanks a lot,"['c#', '.net']" +27877,python serializable objects json class gpagelet holds 1 the pagelet xpath which is a string 2 the list of pagelet shingles list def init self parent if not isinstance parent gwebpage raise exceptionparent must be an instance of gwebpage selfparent parent this must be a gwebpage instance selfxpath none string selfvisibleshingles list of tuples selfinvisibleshingles list of tuples selfurls list of stringclass gwebpage holds all the datastructure after the results have been parsed holds 1 lists of gpagelets 2 loc string location of the file that represents it def init self url selfurl url str selfnetloc false str selfgpagelets gpagelets instance selfpage key stris there a way for me to make my class json serializable the thing that i am worried is the recursive reference,['python'] +27889,how can i protect myself from a zip bomb i just read about zip bombs ie zip files that contain very large amount of highly compressible data 0when opened they fill the servers thiskhow can i detect a zip file is a zip bomb before unzipping itupdate can you tell me how is this done in python or java,"['java', 'python']" +27892,what is in html made by fckeditor i find the following character 13what is this character,['html'] +27907,tablesorter with jquery does not sort numbers correct trying for days now 2 that is to get tablesorter with jquery to get the numbers correctly sortedi am using the last versions of both scriptsthe table is rendered fine but sorting of the numbers goes wrongif sorted it gives the following result87432313 and so onwhere you would expect that32318etc would be thisplayedi read some comments on adding extra javascript code but no for me to understand not that much into javascript javascript example can be foundthe script i use now is basic and looks like thisdocumentreadyfunction table1 tablesorter sortlist 00 widthfixed true widgets zebra hoping for a good example that will resolve this issue for mefonsas per request the html result of the tabletable idtable1 classtablesorterthead tr th width65nameth th width40countth tr theadtbodytrtdname 1tdtd32tdtrtrtdname 2tdtd12tdtrtrtdname 3tdtd11tdtrtrtdname 4tdtd14tdtrtrtdname 5tdtd7tdtrtrtdname 6tdtd3tdtrtrtdname 7tdtd32tdtrtrtdname 8tdtd31tdtrtrtdname 9tdtd35tdtrtbodytablebodyhtmlthe only thing i changed in the result are the namesfons,['jquery'] +27908,javascript language and the in jquery i was wondering how does the in ajax work it doesnt make sense to me sure ajax as a member make sense but isnt a variable name or is it how is it defined,"['javascript', 'jquery']" +27912,best c rtprtsp library i am looking for a rtprtsp library in c i found pjsip but it is more cstyle i am looking for more oo library,['c++'] +27926,how do i get the current access points mac addressbssid my iphone is connected to an access point through a wifi connection does anybody now how i can retrieve this access points mac address with objectivec,"['iphone', 'objective-c']" +27930,before filter require owner i have a number of resources trips schedules etc with actions that should be limited to just the resources owner how do you implement code with a require owner method defined in applicationcontroller to achieve this ideally the code will look up the inheritance chain for the owner so the before filter will work on a comment that belongs to trip that belongs to userclass tripscontroller applicationcontroller belongs to member before filter require owner end,['ruby-on-rails'] +27942,validateinput attribute does not seem to work in aspnet mvc i am trying to get around the potentially dangerous requestform value error and i am having no luck yes yes i have read all the other stackoverflow related questions and none of them seem to get me closer to an answer i am using validateinputfalse on all related controller actionsand i have checked many times i am using validaterequestfalse in all the related aspx views i am using aspnet mvc 2 preview 1 but i do not think that is an issue since the error is being generated lower in the framework pageprocessrequest to be exact i cannot see anything i am doing wrong i even set page validaterequestfalse in the webconfig and that did not solve it either,['asp.net'] +27954,aspnet serverside comments inside i know that you can create serverside comments they would not be sent as commentstext to the client in aspnet mvc via the comment tags however i cannot seem to do this inside of a script tag if i try this i get a bunch of code underlined in red and weird unrelated errors invalid expression term etc from visual studiois there another way to have serverside comments inside of the script tag i want to comment my inline javascript but do not want my comments sent to the client,"['asp.net', 'javascript']" +27969,css hover one element effect for multiple elements i am looking for method for my hovering issuediv clasectiondiv classimageimg srcmyimagejpg divdiv classlayerlorem ipsumdivdivnow both classes image and layer has borders both have different color for normal and hoveris there way to make so if i hover layer class both layer and image class hovering border color is active and vise versa,['css'] +27971,can anyone provide a clear explanation of why google guice is useful i have read about google guice and understand the general issues with other approaches to dependency injection however i have not yet seen an example of someone using guice in practice where its value becomes cleari am wondering if anyone is aware of any such examples,['java'] +27973,can c compilers optimize if statements inside for loops consider an example like thisif flag for condition do somethingelse for condition do something elseif flag does not change inside the for loops this should be semantically equivalent tofor condition if flag do something else do something elseonly in the first case the code might be much longer eg if several for loops are used or if do something is a code block that is mostly identical to do something else while in the second case the flag gets checked many timesi am curious whether current c compilers most importantly g would be able to optimize the second example to get rid of the repeated tests inside the for loop if so under what conditions is this possible,['c++'] +27974,iterate over each line in a string in php i have a form that allows the user to either upload a text file or copypaste the contents of the file into a textarea i can easily differentiate between the two and put whichever one they entered into a string variable but where do i go from therei need to iterate over each line of the string preferably not worrying about newlines on different machines make sure that it has exactly one token no spaces tabs commas etc sanitize the data then generate an sql query based off of all of the linesi am a fairly good programmer so i know the general idea about how to do it but it is been so long since i worked with php that i feel i am searching for the wrong things and thus coming up with useless information the key problem i am having is that i want to read the contents of the string linebyline if it were a file it would be easyi am mostly looking for useful php functions not an algorithm for how to do it any suggestions,['php'] +27987,interfacing erlang application with php i have a website built with phpi have an erlang application running as a daemon on the same serveri need to call functions on the erlang application from php and get back the resulti have found phperlang and over php modules but i cannot install a php module on this server i can only use php codethe only way i know to solve it is run an erlang web server locally that the php will be able to talk tois there a better way to solve itif using a httpd server is the best way what erlang server should i useit should be as light as possible and does not need features like ssl and does not need to handle large loadthanks,['php'] +27988,how can i use php to dynamically publish an ical file to be read by google calendar any google search on php ical just brings up phpicalendar and how to parse or read in ical files i just want to write a php file that pulls events from my database and writes them out in ical formatmy problem is i cannot find anywhere that will answer two questionswhat is the exact ical format including headers file format footers etc in other words what does the file have to have exactly in order to be properly read in by google calendar etcif i build this file using a php extension how do i publish it as ical do i have to write to a new ics file or will google calendar etc read a php file as ical so long as the contents are in the correct format much like a stylecssphp file will be read as a css file if the contents are actually css etcany help you all can give or point me to will be greatly appreciated,['php'] +27989,deploying cherrypy daemon i have followed the basic cherrypy tutorial one thing not thiscussed is deploymenthow can i launch a cherrypy app as a daemon and forget about it what happens if the server rebootsis there a standard recipe maybe something that will create a service script etcinitdcherrypythanks,['python'] +27993,how to check if memcache or memcached is installed for php how do i test if memcache or memcached for php is installed on my apache webservermemcache is a caching daemon designed especially for dynamic web applications to decrease database load by storing objects in memory,['php'] +28001,how do i check that a form is prepopulated with values using cucumber and webrat i am learning cucumber and webrat with rails and would like some advice on the best way to test an edit form when i browse to a users profile i am presented with an edit form with the users information prepopulated in the form fields i would like to be able to test that the fields do in fact contain the information i expect heres my scenario scenario view my profile given i am logged in as mike with password secret when i go to my profile page then i should see mike in the login field and i should see in the email field and i should see a blank password field and i should see a blank password confirmation fieldcucumber tells me correctly that i need to define the following custom stepsthen i should see in the field do arg1 arg2 pendingendthen i should see a blank field do arg1 pendingendi am sure i can figure out some nasty regex to implement evaluating these steps but i feel there must be something already existing or more elegant that i can do how do you evaluate forms with data prepopulated in the form fields,['ruby-on-rails'] +28014,sql server 2005 database in recovery i restored a 35gb database on my dev machine yesterday and it was all going fine until this morning when my client app could not connect so i opened sql management studio to find the database in recovery i do not know a huge amount about this other than it is usually something to do with uncommitted transactions now since i know there are not any uncommitted transactions it must be something else so first off i would like to know under what conditions this can happen secondly while this is going on i cannot work so if there are any ways of either stopping the recovery speeding it up or at least finding roughly how long it is gonna be that would help,['sql'] +28017,html links to local network shares why do these links not work if i click on them in ff or chrome nothing happens it does not even try to open thema hreffilesomesharedirsubdirfiletxtlinkyaa hreffilesomesharedirsubdirfiletxt linkyaa hreffilesomesharedirsubdirfiletxtlinkyaany ideas,['html'] +28023,vim syntax highlighting for jinja2 how do you do jinja2 aware syntax highlighting for vim,['python'] +28029,c systemwindowsformswebbrowser requires flash to be installed when i create a form and add a webbrowser control to it and have it navigate to the flash area says i need adobe flash player installed this is already installed in ie but apparently not in the webbrowser controlis there are way to have the webbrowser control run flash without having to manually go to the flash site and install flash is already installed the normal ie browser just not the webbrowser control in the forms app,['c#'] +28037,python open builtin function difference between modes a a w w and r in the python builtin open function what is the exact difference between the modes w a w a and rin particular the documentation implies that all of these will allow writing to the file and says that it opens the files for appending writing and updating specifically but does not define what these terms mean,['python'] +28041,how to set an image as a background for frame in swing gui of java i have created one gui using swing of java i have to now set one samplejpeg image as a background to the frame on which i have put my componentshow to do that,['java'] +28051,how to know if an object is autoreleased or not i am getting a a bit annoyed about some objects being autoreleased without me knowing it is probably a good thing that they are but if they are i want to know the documentation does not say which methods autorelease objects so i usually test my way forward which in my opinion is silly for example nsdate date autoreleases the object and so does nsarray arraywithobjects how do you know without the documentation telling youi am starting to see a pattern though that methods like these the ones that create objects with a static function always returns the autoreleased object is this always true,['objective-c'] +28053,using getcurrentmethod in supposedly highperformance code for logging purposes some methods in our application include the following linedim log as ilog getlogreflectionmethodbasegetcurrentmethoddeclaringtypei have what might be described as an irrational fear of reflection which i try to keep in check however calls like this in methods that are executed potentially a hundred times a second concern me i do not know as much as i should about reflection but from looking briefly over the documentation it looks to me like i could replace the following withdim log as ilog getlogmegettypemy question is threefolddoes megettype actually return the same type as getcurrentmethoddeclaringtype does megettype actually do anything differently from getcurrentmethoddeclaringtype or is it doing the same thing under the hoodshould i not even be worried about this at all performance is critical in this application the program runs fine but the nature of our business is such that if we can shave off even a few microseconds here and there that is useful,['.net'] +28056,set innerexception of net exception object how can i set the innerexception property of an exception object while i am in the constructor of that object this boils down to finding and setting the backing field of a property that has no setterif your answer is this cannot be done do not answer please i am saying this because it should be possible via reflection so if you know how to do it please enlighten me btw i have seen this but looking for non ilbased solution if possiblethanks for the initial input but i should have clarified that the exception constructor is the place where the exception type is created so i cannot call it using the base class constructor myexception base etcthis is why i am looking into attempting to alter the backing field via reflection as the property is get only,['c#'] +28079,call base method in javascript using douglas crockfords functional inheritance basically how do i call a base method using this patter belowvar gs gsbaseclass function somedata var that thatdata somedata base class method thatsomemethod functionsomedata alertsomedata return thatgsderivedclass functionsomedata var that gsbaseclasomedata overwriting base method thatsomemethod functionsomedata how do i call base method from here do something else return thatthanks,['javascript'] +28087,unit testing frameworks for c comparison i am a ruby programmer and i really like to do tdd right now i am programming a little bit in c but i like my tools and the way i program with ruby so i am searching for a framework to do unit tests in c what do you can tell me about iti already found some options like cunit cmockery cutest and others the problem is i do not know how to evaluate the best one i am writing a simple compiler for my compilers college coursecould you help me,['c'] +28090,why the reset method on enumerator class must throw a notsupportedexception from what i saw on and article by jon skeet the c specification itself says that what would be the reason,"['c#', '.net']" +28111,datagridview not showing properites of objects which implement icustomtypedescriptor i am thisplaying a list of objects in a datagridview everything was working fine columns were automagicaly added to the datagridview based on the properties of the objectsnow i changed the class i am thisplaying in the grid to implement icustomtypedescriptor but now the grid now no longer shows any columns or rows when i set it is datasource to a list of my custom objecti am guessing this has something to do with the fact that with icustomtypedescriptor each instance shown in each row of each grid could be returning a different set of propertiesi am implementing icustomtypedescriptor so that i can allow the users to dynamically add custom properties to objects at run time these custom properties should be visible and editable through the datagridviewwhy does datagridview not see my icustomtypedescriptor methods is there another way that i can dynamically add properties to an object that will be thisplayed in a datagridview,['c#'] +28116,linq to mysql what is the best option has anyone used any of the utilities out there for linq to mysql do you know which one is bestso far i know of linq for nhibernate and dblinq,['mysql'] +28119,why does my embedded youtube video work in firefox but not internet explorer i am using the following code to thisplay a youtube videoobject width425 height344 param namemovie valueurl param param nameallowfullscreen valuetrue param embed srcurl typeapplicationxshockwaveflash allowfullscreentrue width425 height344 embedobjectit works in firefox but why does not it in internet exploreri am a totally new to web development so i am running into all these wonderful inconsistencies that you veterans are used to,['html'] +28120,aspnet datetime picker is there any good freeopen source time picker control that goes well with aspnet calendar control,['asp.net'] +28134,eclipsepydevgae memcache error i have started using eclipepydev as an environment for developing my first app for google app engine eclipse is configured according to this tutorialeverything was working until i start to use memcache pydev reports the errors and i do not know how to fix iterror undefined variable from import gethow to fix thissure it is only pydev checker problem code is correct and run on gaeupdatei am using pydev 150 but experienced the same with 148my pythonpath includes set in project propertiespydev pythonpathcprogram filesgooglegoogle appenginecprogram filesgooglegoogle appenginelibdjangocprogram filesgooglegoogle appenginelibwebobcprogram filesgooglegoogle appenginelibyamllibupdate 2i took a look at cprogram filesgooglegoogle appenginegoogleappengineapimemcache init py and found get is not declared as memcache module function they use the following trick to do that i did not hear about such possibility client nonedef setup clientclient obj sets the client object instance to use for all modulelevel methods use this method if you want to have customer persistent id or persistent load functions associated with your client args client obj instance of the memcacheclient object global client var dict globals client client obj var dictset servers clientset servers var dictthisconnect all clientthisconnect all var dictforget dead hosts clientforget dead hosts var dictdebuglog clientdebuglog var dictget clientget var dictget multi clientget multi var dictset clientset var dictset multi clientset multi var dictadd clientadd var dictadd multi clientadd multi var dictreplace clientreplace var dictreplace multi clientreplace multi var dictdelete clientdelete var dictdelete multi clientdelete multi var dictincr clientincr var dictdecr clientdecr var dictflush all clientflush all var dictget stats clientget statssetup clientclienthmm any idea how to force pydev to recognize that,['python'] +28135,how to thisable the gridview rows border can we thisable the gridview horizontal line i want to thisplay grid without horizontal lineshelp me thank you,['asp.net'] +28159,accessing the windows registry using net i am finding a strange behavior with a net module accessing the windows registry using the registrykey classfor example i have written a net module testcomdll which access the registry this testcomdll file is used both by a native 32bit application and a 64bit application my requirement is to get the value of a regkey path being hkey local machinesoftwaretestmyparameters and the key name is age this age key will be in 32bit registry on 32bit machines and 64bit registry not wow64 on 64bit machineson a 64bit machine when a 32bit application is using testcomdll the key age is searched in the wow64 registry when a 64bit application is using testcomdll the key age is searched in the 64bit registrymy requirement is to read the key in the 64bit registry on 64bit machines whatever the application uses the testcomdll file how can i do this,['.net'] +28161,wrapping long text in css i have text likediv stylefloatleft width 250px pellentesquepellentesquepellentesquepellentesquepellentesquepellentesquepellentesquepellentesquepellentesquepellentesquepellentesquepellentesquepellentesquepellentesquepellentesque feugiat tempor elit ut mollis lacinia quam sed pharetra augue aliquam ornare vestibulum metus massalaoreet tellus eget iaculis lacus ipsum et diam divi do not want horizontal scrolling is it possible to wrap the text autoline break i know there are some ie specific properties thank you for your timeupdate i can use jquery javascript php to do this also but how i mean the letters font are not fixed width or whatever you call that,"['php', 'javascript', 'jquery', 'css']" +28163,twisted network client with multiprocessing workers so i have got an application that uses twisted stomper as a stomp client which farms out work to a multiprocessingpool of workersthis appears to work ok when i just use a python script to fire this up which simplified looks something like this stompclientpyloggingconfigfileconfigconfig pathlogger logginggetlogger name add observer to make twisted log via pythontwistedpythonlogpythonloggingobserverstart initialize the process pool child processes get forked off immediatelypool multiprocessingpoolprocessesprocessesstompclientfactoryusername usernamestompclientfactorypassword passwordstompclientfactorydestination destinationreactorconnecttcphost port stompclientfactoryreactorrunas this gets packaged for deployment i thought i would take advantage of the twistd script and run this from a tac fileheres my verysimilarlooking tac file stompclienttacloggingconfigfileconfigconfig pathlogger logginggetlogger name add observer to make twisted log via pythontwistedpythonlogpythonloggingobserverstart initialize the process pool child processes get forked off immediatelypool multiprocessingpoolprocessesprocessesstompclientfactoryusername usernamestompclientfactorypassword passwordstompclientfactorydestination destinationapplication serviceapplicationmyappservice internettcpclienthost port stompclientfactoryservicesetserviceparentapplicationfor the sake of illustration i have collapsed or changed a few details hopefully they were not the essence of the problem for example my app has a plugin system the pool is initialized by a separate method and then work is delegated to the pool using poolapply async passing one of my plugins process methodsso if i run the script stompclientpy everything works as expectedit also appears to work ok if i run twist in nondaemon mode ntwistd noy stompclienttachowever it does not work when i run in daemon modetwistd oy stompclienttacthe application appears to start up ok but when it attempts to fork off work it just hangs by hangs i mean that it appears that the child process is never asked to do anything and the parent that called poolapply async just sits there waiting for the response to returni am sure that i am doing something stupid with twisted multiprocessing but i am really hoping that someone can explain to my the flaw in my approachthanks in advance,['python'] +28166,invoke external shell script from php and get its process id how can i invoke an external shell script or alternatively an external php script from php itself and get its process id within the same script,['php'] +28172,counting thistinct over multiple columns is there a better way of doing a query like thisselect count from select thistinct documentid documentsessionid from documentoutputitems as internalqueryi need to count the number of thistinct items from this table but the thistinct is over two columnsmy query works fine but i was wondering if i can get the final result using just one query without using a subquery,['sql'] +28176,normalizing from 05 1 to 0 1 i am kind of stuck here i guess it is a bit of a brain teaser if i have numbers in the range between 05 to 1 how can i normalize it to be between 0 to 1thanks for any help maybe i am just a bit slow since i have been working for the past 24 hours straight o o,['c++'] +28185,getting rid of error c2243 is it possible to getting rid of error c2243class b class d protected b d db p d conversion from d to b exists but is inaccessiblei had this error in my app and at the end i have managed to compile it by making an explicit conversiond db p bdi cannot understand why by making class d inherited protected from b makes the implicit conversion inaccessible i tried to avoid explicit conversion by creating a operator b in class d in order to make the conversion accessibleclass b class d protected b public operator b return thisbut there is no wayany other solution to avoid explicit conversion,['c++'] +28193,xmlattributexmlelement equivalent for javascriptserializer is there an equivalent attribute that can be placed on object properties in a net class that would perform the equivalent of xmlelement or xmlattributexmlrootobjectspublic class myobjects listmyobject xmlrootobjectpublic class myobject xmlattributename public string name get set xmlattributetitle public string title get set this would return xml similar to the followingobjects object namedavid titleengineer object namewilliam titledeveloper objectsi would like to have the javascriptserializer used by the aspnet mvc frameworks json method in the controller classpublic actionresult search code to populate data object return jsondatareturn the same formatted results like sonamedavidtitleengineernamewilliamtitledevelopercurrently outputting the object with the json method returnsnamedavid titleengineer namewilliam titledevelopernow i realize this example is super simplified and the only thing i have done here is change the casing of the property names but in more advanced scenarios i may completely remap the property name to something else systemwebscriptserialization contains a scriptignoreattribute attribute but this simply tells the javascriptserializer to ignore the property when serializing nothing appears to exist to change the names or format of the actual output however,"['.net', 'javascript']" +28195,pdo working with table prefixes i like to prefix my tables in case i need to install the application to a host with only one database i was wondering if there is a simple way of working with table prefixes using the pdo classat the moment i am having to overwrite each method in my own database wrapped replace p with the prefix and call the super method it is works but it is not pretty,"['php', 'mysql']" +28219,general strategy to resolve java memory leak i have a standalone program that i run locally it is meant to be a server type program running 247 recently i found that it has a memory leak right now our only solution is to restart it every 4 hours what is the best way to go about finding this memory leak which tool and method should we use,['java'] +28231,how can i tell gcc not to inline a function say i have this small function in a source filestatic void foo and i build an optimized version of my binary yet i do not want this function inlined for optimization purposes is there a macro i can add in a source code to prevent the inlining,['c'] +28239,javascript visibility error in internet explorer when setting focus on an input element this may be the most obscure bug i have yet encountered in many years of working with javascript and any version of internet explorer were using yui 27 for some of the nonconvenience methods sigh what i would do for jquerythis is affecting internet explorer 6 and internet explorer7 internet explorer 8 behaves properly all other browsers also behave properlyproblem when i set focus on a particular element i get the following errorcannot move focus to the control because it is invisible not enabled or of a type that does not accept focusso i have a div called addcommentloginoverlay that contains the input element this div is thisplaynone until the user clicks one of several links called loginthe following is the javascript code i am using that selects the login links which moves the position of the addcommentloginoverlay in the dom sets thisplayblock then sets focus on the 1st input field in the overlay it is this process of setting focus that is causing the error i wrote aboveget login links in comment formslinks yahooutildomgetelementsbyclassnameaddcommentloginlinkset click event for login linksyahooutileventaddlistenerlinks click functionel stop link yahooutileventpreventdefaultel move login overlay in dom if elsrcelement var target elsrcelement else var target elcurrenttarget yahooutildominsertafter overlay targetparentnodeparentnodeparentnodeparentnode set to visible yahooutildomsetstyle overlaythisplay block set focus to username field documentgetelementbyidaddcommentloginoverlayusernameinputfocusi can absolutely confirm that the overlay div is completely visible i can look at it i have added a setinterval timer to measure whats happening and it has no effect at one point i had 10 seconds going between the time the overlay was visible and when focus was called and the error still occurs other than the error the form is completely functional other than this errorthis is a simplified version of the overlay html code as a referencediv idaddcommentloginoverlay classaddcommentloginoverlay stylethisplay block div classaddcommentloginoverlaycontent clearfix div classaddcommentloginoverlaysignin clearfix input typetext tabindex2001 idaddcommentloginoverlayusernameinput input typepassword tabindex2002 idaddcommentloginoverlaypasswordinput div divdiv,['javascript'] +28243,how to readwrite intofrom text file with comma separated values how do i read data from a file if my file is like this with comma separated values1 2 3 4 5n6 7 8 9 10nnand after reading the file i want to write the data back into other file as same format abovei can get total number of lines usingstring linewhilefileeof getlinefileline numlines numline remove the last empty linebut how can i know total number of digits in a rowline i also have vector of ints to store the dataso i want to read the first line and then count total number of elements in that line here 5 12345 and store them in arrayvector and read next line and store them in vector again and so on till i reach eofthen i want to write the data to file again i guess this will do the job of writing data to filenumofcols1forint i 0 i vectorsize i file vectorati ifnumofcols5 file print comma ifi150 file endlprint newline after 5th value numofcols1start from column 1 again for the next line numofcolsfile endl last new lineso my main problem is how to read the data from file with comma separated values thanks,['c++'] +28247,object oriented programming looking for good tutorials i am tired of tutorials that just enumerate the concepts with examples how about some tutorials that show the wrong way of doing and then the correct way of doing things it would be great to learn things like interfaces delegates abstract classes singleton etc that way it would be great to read some clean code online as well but its hard to findany recommendationsi develop in c net ms technologies,['c#'] +28273,tail f in python with no timesleep i need to emulate tail f in python but i do not want to use timesleep in the reading loop i want something more elegant like some kind of blocking read or selectselect with timeout but python 26 select documentation specifically says it cannot be used on regular files to determine whether a file has grown since it was last readany other wayin a few days if no solution is given i will read tails c source code to try to figure it out i hope they do not use sleep hehethanksmarior,['python'] +28275,deadlock issues in procestandardoutputreadtoend i read that this portion of code can cause deadlock process p new process pstartinfouseshellexecute false pstartinforedirectstandardoutput true pstartinfofilename write500linesexe pstart pwaitforexit string output pstandardoutputreadtoendbecause a deadlock condition can result if the parent process calls pwaitforexit before pstandardoutputreadtoend and the child process writes enough text to fill the redirected stream the parent process would wait indefinitely for the child process to exit the child process would wait indefinitely for the parent to read from the full standardoutput streambut i do not quite why i mean in this case here whats the parent process and whats the child,['c#'] +28280,how to make a blinking or flashing cursor on iphone i am trying to create a custom blinking cursor in uikit i have tried as shown below having 2 functions that basically keep calling each other until the cursor is hidden but this leads to a nice infinite recursion for some reason the functions call each other right away not each halfsecond as expectedi tried returning if the finished parameter is not yes by uncommenting the if ok line but that leads to no animation at allany better idea did i miss something is there a mucheasier way to make a blinking cursor voidonblinkinnsstring animationid finishedboolok contextvoid ctx if cursorviewhidden returnif ok returnuiview beginanimationsnil contextuigraphicsgetcurrentcontextuiview setanimationcurveuiviewanimationcurveeaseinoutuiview setanimationduration05fuiview setanimationdelegateselfuiview setanimationdidstopselectorselectoronblinkoutfinishedcontextcursorviewtextcolor uicolor graycoloruiview commitanimations voidonblinkoutnsstring animationid finishedboolok contextvoid ctx if cursorviewhidden returnuiview beginanimationsnil contextuigraphicsgetcurrentcontextuiview setanimationcurveuiviewanimationcurveeaseinoutuiview setanimationduration05fuiview setanimationdelegateselfuiview setanimationdidstopselectorselectoronblinkinfinishedcontextcursorviewtextcolor uicolor clearcoloruiview commitanimations,"['ios', 'objective-c']" +28287,attributes on manytomany relationships hibernate i have entity classes a and c they are mapping the tables tbla and tblc and have a manytomany relationship between them with tblb to map between them tblb contains a id c id and setdate the last one being the date it was set thus an attribute to the relationship my question is how do i best map in this attribute at the moment they are unmapped like thisamanytomanytargetentitycclass cascade cascadetypepersist cascadetypemerge jointablenametblb joincolumnsjoincolumnnamea id inversejoincolumnsjoincolumnnamec id private collectionc cscmanytomany cascade cascadetypepersist cascadetypemerge mappedby cs targetentity aclass private collectiona ashow should i get tblbsetdate out of thischeersnik,['java'] +28291,oledbcommand parameters order and priority i have been debugging this query for the last 40 minutes and the problem apparently is the order of the parameters after allselect from tblsomething where id id and debut dtdebut and fin dtfinthen i add the parameters this way notice that the two last parameters are switched i get no resultscmdparametersaddid oledbtypeintegervalue idsocietecmdparametersadtfin oledbtypedatevalue datetraitementfincmdparametersadtdebut oledbtypedatevalue datetraitementdebutwhen i declare the parameters the way they appear in the queury everything works perfectlyi thought named parameters were at first place to address this problem what am i missing herethank you,['c#'] +28311,how to hide a text inputs browsergenerated dropdown list of previous items when i generate a text input like thisinput typetext namename when i start to type the browser will thisplay a dropdown list below the text input this list contains the values i previously used for this text input in this browser i want to generate my own autocompletion via ajaxhow do i tell the browser with either css or javascript to not generate this dropdown listif this task is easier by using jquery i would prefer such a solution,['html'] +28316,net filecreate cannot delete file afterwards using method systemiofilecreateafter the file gets created it still remains used by a process and i cannot delete it any idea how i can better create the file should be a 0byte file and then somehow close and thispose,"['c#', '.net']" +28322,python chat delete variables to clean memory in functions i am creating a chat daemon in python and twisted framework and i am wondering if i have to delete every variable create in my functions to save memory in the long run when multiple users are connected or are those variable automatically clear heres a strip down version of my code to illustrate my pointclass chatlineonlyreceiver lineonlyreceivermax length 500 def linereceivedself data selfsendmessagedata def sendmessageself data try message datasplitnone11 except indexerror return selffactorysendallmessage question do i have to delete message and date del message del dataclass chatfactoryfactory protocol chat def init self selfclients def addclientself newclient selfclientsappendnewclient def delclientself client selfclientsremoveclient def sendallself message for client in selfclients clienttransportwritemessage n,['python'] +28327,selectnodes not scoped to the element if i call selectnodes on an xmlelement and pass xpath query such as thisxmlnodelist nodes xmlelementselectnodesothernodethe nodes list will be for all the othernode elements in the document not just the ones from xmlelementi seem to recall that this is by design and for a good reason but i cannot remember what that good reason was nor how to get around it,['.net'] +28329,what can i do in java code to optimize for cpu caching when writing a java program do i have influence on how the cpu will utilize its cache to store my data for example if i have an array that is accessed a lot does it help if it is small enough to fit in one cache line typically 128 byte on a 64bit machine what if i keep a much used object within that limit can i expect the memory used by it is members to be close together and staying in cachebackground i am building a compressed digital tree that is heavily inspired by the judy arrays which are in c while i am mostly after its node compression techniques judy has cpu cache optimization as a central design goal and the node types as well as the heuristics for switching between them are heavily influenced by that i was wondering if i have any chance of getting those benefits tooedit the general advice of the answers so far is do not try to microoptimize machinelevel details when youre so far away from the machine as youre in java i totally agree so felt i had to add some hopefully clarifying comments to better explain why i think the question still makes sense these are belowthere are some things that are just generally easier for computers to handle because of the way they are built i have seen java code run noticeably faster on compressed data from memory even though the decompression had to use additional cpu cycles if the data were stored on thisk it is obvious why that is so but of course in ram it is the same principle now computer science has lots to say about what those things are for example locality of reference is great in c and i guess it is still great in java maybe even more so if it helps the optimizing runtime to do more clever things but how you accomplish it might be very different in c i might write code that manages larger chunks of memory itself and uses adjacent pointers for related datain java i cannot and do not want to know much about how memory is going to be managed by a particular runtime so i have to take optimizations to a higher level of abstraction too my question is basically how do i do that for locality of reference what does close together mean at the level of abstraction i am working on in java same object same type same arrayin general i do not think that abstraction layers change the laws of physics metaphorically speaking doubling your array in size every time you run out of space is a good strategy in java too even though you do not call malloc anymore,['java'] +28340,naming conventions for partial class files i am generating the bulk of my aspnet mvc scaffolding code all generated files are partial classes which use standard naming conventions for example my employee controller file is named employeecontrollercs if i wish to extend the employeecontroller with custom nongenerated logic i create a second partial class file named employeecontrollercustomcs i separate the custom and generated logic into two different files so the next time i generate the employeecontroller my custom changes are not overwritten adding the custom suffix to the file name seems reasonable to me but is there a more established partial class file naming convention which i should be following,['c#'] +28345,java name ambiguity between outer and inner class methods suppose i havepublic class outerclass public class innerclass public void somemethodint x somemethodx public void somemethodint x systemoutprintlnx how do i resolve the ambiguity between the somemethod of the outer class and the somemethod of the inner class,['java'] +28346,save the document generated by javascript javascript can manipulate the document the browser is thisplaying so the following script documentwritetabletrtdholatdtdadiostdtrtablescriptwill make the browser thisplay a table just like if it was the original html documenttable tr tdholatd tdadiostd trtableis there a way i can saveserve this document content currently we have some nicely generated reports using extjs what i would like to do is to have the texthtml version of it i mean something that does not require javascript so at the end of the page i would add a button save as blaba and the document should thisplay the textplain versionthe only way i could think right now is to write the content into a javascript variable like var content documenttostring or something magic like that post it to the serverthen post that value to the server and have the server present that value requestgetparametercontenttextbut looks very tricky is there an alternativeeditok i almost got it now i just need the new window to pop up so the option would you like to save it shows this is what i have got so farscript documentwritediv idcontenttabletrtdholatdtdadiostdtrtablediv function saveas var smarkup documentgetelementbyidcontentinnerhtml var onewdoc documentopenapplicationvndmsexcel onewdocwrite smarkup hr onewdocclose scriptinput typebutton valuesave as onclicksaveasthe line var onewdoc documentopenapplicationvndmsexcelshould specify the new content type but it is being ignored,['javascript'] +28349,how is if statement evaluated in c is if c the same as if c 0 in c,['c++'] +28351,making modal wizard how could i make a modal wizard with jquery,['jquery'] +28353,which opensource git hosting software should i install on my companys intranet instead of hosting my companys source code on github i would like to host it on our intranet under our controlwhat software could i use to simulate the same kinds of gitbased sourcecontrol features that are offered by sites like githubideally this solution would be associated with a rubybased web application,['ruby'] +28355,ms sql server when is a cursor good many times when i have written stored procedures etc i use a cursor at first and later find some performance issue with my procedureevery thing i read says cursors are awful cause unnecessary locking etc and performance testing proves the samemy question is when do you use a cursor and in what situations are they useful or goodif there is no use why would they make such a bad control structuretype for sql,['sql'] +28364,regular expression removing all words shorter than n well i am looking for a regexp in java that deletes all words shorter than 3 charactersi thought something like sw12s would grab all the 1 and 2 letter words a whitespace one to two word characters and another whitespace but it just does not workwhere am i wrong,['java'] +28371,python interpreter as a c class i am working on embedding python in to c in some peculiar case i require two separate instances of the interpreter in same threadcan i wrap python interpreter in to a c class and get services from two or more class instances,"['c++', 'python']" +28377,java graphics library i am looking for a highlevel java graphic library for creating artistic text watermarks resize crop image identification and manipulationimagemagic is a good example of such library but its java ports are somewhat problematic they either run imagemagic through jni or via commandline and are hellish to deploy to serversideally i would like to have similar functionality to imagemagic but pure java and opensource free to usehas anyone seen something like thatthis is for a serverside component a service that manipulates images of various web formats png jpg gif etcjava has its own libraries of course graphics2d but i am looking for something of higher levelhere are several use casesresize and crop images if it has smart resize or smart crop thatll be cool for example seam carving resize or cropping by points of interest in the photodrawing artistic text on images using fonts colors text effects 3d text charcoal and other effectsembedding watermarkslayering images using images as background masking with images etcimage identification such as number of colors stdev etcas mentioned java in its graphics2d supports all of the above but is too low level so i am looking for something that is nicer to work withthanks,['java'] +28398,rails text field default value thisappear on click and dimmed these text fields look great and are common on web 20 sites like facebookbasically instead of labeling the text field you can save space by putting the label inside the text field typically the text is dimmed in color a bit and when the user clicks in the text field the default value thisappears and the color switches to black or the regular color so the user can enter textso far this is how i have been creating them default value email address ftext field email style colora value default value onfocus ifthisgetvaluedefault valuethisclearthisstylecolor 0 onblur ifthisgetvaluethissetvaluedefault valuethisstylecolor a this basically works but one problem i have noticed is that if you type something in the field and submit a form that fails the form will reload with what you typed in the field as it should but the text is incorrectly dimmed this also happens if you click back on your browserit will thisplay the text you entered not the default value but the text color is dimmedis there an easier way to do this or way to solve the above problem thanks,"['javascript', 'ruby-on-rails']" +28412,how to get the os on which php is running for building a unixdos specific script i need to know on which kind of operating system i am how do i get this informationphpinfo tells me a lot more and not very clear whether i am running on unix or not,['php'] +28416,broken java mac 106 some backgroundon mac os x 106 using macports and i have dyld library path set in my bash profilethe problemwhen i run java version i get this errorerror occurred during initialization of vm unable to load native library libjavajnilibby way of one helpful forum thread i have thiscovered the problem is some files in my optlocallib directory are causing trouble because of the dyld library path i have setwhen i remove the files starting with libgif libjpeg libpng and libtiff from optlocallib the problem goes away and java version works but the ports that depend on those files breakanyone know of a way i can keep the files and still get java to work properly possibly setting the java path which i am not quite sure how to do and all my attempts have failedthanks,['java'] +28418,xrange2100 overflowerror long int too large to convert to int xrange function does not work for large integers and 10100 xrangentraceback most recent call lastoverflowerror long int too large to convert to int xrangen n10traceback most recent call lastoverflowerror long int too large to convert to intpython 3x and 10100 r rangen r rangen n10 lenr10is there a backport of py3k builtin range function for python 2xediti am looking for a complete implementation of lazy range not just a partial implementation of some of its functionality,['python'] +28428,combine two named scopes with or instead of and i want to find all annotations whose bodies are eitherequal to orlike whats the best way to do thisi would like to use searchlogic if possible but though searchlogic allows you to do each of the followingannotationbody equalsannotationbody likeand you can always chain them together annotationbody equalsbody likei am not sure how to combine them with ornote that you can combine named scopes with or if their argument is the same eg i could do annotationbody equals or body likebut this wouldnt helpnote that i am not attached to searchlogic but it would be great for a solution that does not require breaking its abstraction,['ruby-on-rails'] +28440,mysql views when to use when not to the mysql certification guide suggests that views can be used forcreating a summary that may involve calculationsselecting a set of rows with a where clause hide irrelevant information result of a join or unionallow for changes made to base table via a view that preserve the schema of original table to accommodate other applicationsbut from and maybe youre right that it does not work since mysql views are not good friends with indexing but still is there anything to search for in the shops tablei learn that views dont work well with indexing so will it be a big performance hit for the convenience it may provide,"['sql', 'mysql']" +28444,whats the best practice for getting a random datetime between two datetimes i am trying to randomize the value for a simple datetime datafieldi wish to get a random datetime between two datetimes eg min datetime and max datetimeso lets imagine i am after a random datetime between1120 10am and 1120 5pmalso this code will be used in a for loop with 100 items meaning all 100 items will have random datetimes between the minmax datetime periodphew any ideas,['.net'] +28471,using cin in qtcreator for school we use c as the language of choice i am currently using qtcreator as an ide and for its gui library it is wonderful the school is using visual studiohowever most of the programs we are writing make use of cin and cout for inputoutput cout works fine as output as you can see what it puts out in the application output but there is no way to provide to cin as if it were on a console like visual studio uses for its can exampleinclude iostreaminclude stringusing namespace stdint main string name cout enter name cin name cout your name is name endlis there a way to use a console or provide input to cin like in visual studioi am currently running os x leopard if it mattersthanks,['c++'] +28490,how to store local variables in jquery click functions i am trying to figure out how to store external variable values in the functions created during jquerys click event heres a sample of the code i am working with nowforvar i0 i3 itmpidiclickfunctionvar gid ialertgiddiv idtmpid01aldivdiv idtmpid1asddivdiv idtmpid2qwedivso whats happening is that the events are attaching properly but the value of gid is always the last incremented value of i i am not sure how to setup the private variable in this situation,['jquery'] +28493,whether a variable is undefined possible duplicatebest way to check for aundefineda in javascript how do i find if a variable is undefinedi currently havevar page name pagetoedit selectedtextvar table name pagetoedit selectedvalvar optionresult pagetoeditoptions selectedvalvar string zzif page name undefined string page name page name if table name undefined string table name table name if optionresult undefined string optionresult optionresult,['jquery'] +28499,api to write huge excel files using java i am looking to write to an excel xls ms excel 2003 format file programatically using java the excel output files may contain 20 rows which i plan to split over number of sheets 64k rows per sheet due to the excel limit i have tried using the apache poi apis but it seems to be a memory hog due to the api object model i am forced to add cellssheets to the workbook object in memory and only once all data is added i can write the workbook to a file here is a sample of how the apache recommends i write excel files using their apiworkbook wb new hssfworkbooksheet sheet wbcreatesheetnew sheetcreate a row and put some cells in itrow row sheetcreaterowshort0 create a cell and put a value in itcell cell rowcreatecell0cellsetcellvalue1 write the output to a filefileoutputstream fileout new fileoutputstreamworkbookxlswbwritefileoutfileoutcloseclearly writing 20k rowswith some 1020 columns in each row gives me the dreaded javalangoutofmemoryerror java heap space i have tried increasing jvm initial heapsize and max heap size using xms and xmx parameters as xms512m and xmx1024 still cant write more than 150k rows to the filei am looking for a way to stream to an excel file instead of building the entire file in memory before writing it to thisk which will hopefully save a lot of memory usage any alternative api or solutions would be appreciated but i am restricted to usage of java thanks,['java'] +28501,javascript type of custom object how can i check if my javascript object is of a certain typevar someobject function var s1 new someobjectin the case above typeof s1 will return object that is not very helpful is there some way to check if s1 is of type someobject,['javascript'] +28523,mysql too many columns i am creating a table with 3050 columns there are about 200k of these rows is it recommended to store this data in separate tables are there performance issues when you have this many columns i will explain a bit about the table i have to store all sports games over the past 10 years basketball baseball football hockey for each of these i need to keep additional data some of this data allows me to reuse fields across sports for example every team has a home and away team and a event date however for each of these games i am also storing things like how many first downs were acheived how many strikeouts and three pointers obviously this data only relates to some of the rows in the table i end up having a lot of null fields in each row as a result i can give more specifics if necessary thanks in advance for any general advice,"['sql', 'mysql']" +28540,access violation in wm paint not caught to test this problem i have written a minimal windows application if i force an access violation in the wm paint handler this exception never gets to the debugger if started without debugger the access violation also does not show up usually you should get the windows error reporting dialogdigging a bit deeper it seems that something in user32dll catches all incoming exceptions is this normal behavior can i control this somehow is not catching all exceptions a security risk at least it is annoying as hellthis is with a 32 and 64bit application on vista 64 on xp the exception seems to be handled as expected other windows messages have the same problem maybe all of themthe wm paint handlercase wm paint hdc beginpainthwnd ps int0 0 endpainthwnd ps break,['c++'] +28544,what is a binary null character i have a requirement to create a sysdesk log file in this requirement i am supposed to create an xml file that in certain places between the elements contains a binary null character can someone please explain to me firstly what is a binary null character and how can i write one to a text file,['c#'] +28545,iphone core data initializing managed object without a context is there a way to initialize a managed object outside of a context i am basically trying to allocinit a managed object outside of a context first then figure out if i really want to insert the object and then inject it into the datastore using an existing managed object contextis this possible or does it go against the intended usage of core data,['iphone'] +28547,what are the legal allowed characters for web server file names on what characters are allowed in filenames for html files on all servers nix windows etc i am looking for the lowest common denominator that will work on all serversuse i am naming a file to be served up publicly mysitecommypagehtmeg space etceg can i have filenamehtm file namehtm file namehtmobviously this needs to work with all servers and browsers iirc the name is limited by the server not the browser but i could be wrong,['html'] +28569,uiimagewritetosavedphotosalbum save as png with transparency i am using uiimagewritetosavedphotosalbum to save a uiimage to the users photo album the problem is that the image does not have transparency and is a jpg i have got the pixel data set correctly to have transparency but there does not seem to be a way to save in a transparencysupported format ideasedit there is no way to accomplish this however there are other ways to deliver png images to the user one of which is to save the image in the documents directory as detailed below once youve done that you can email it save it in a database etc you just cannot get it into the photo album for now unless it is a lossy nontransparent jpg,['iphone'] +28573,when is java the right choice for webbased applications i have been doing some research into taking my programming experience and moving into the java programming marketplace due to a combination of personal interest and local market forces as you can gather from the title the vast majority of my experience has been in building webbased sites and applications and i would like to move as much of my previous experience as possibleone thing that i have been unable to find a concrete answer for when should a website or webbased application designer look to going with a java based solution over other options currently on the market what options would java provide that would have a designer select java as the basic coding language to base a project uponthank you for any constructive replies that may arrive from this inquiryedit i should have included the caveat of if other factors are equal for example if hardware software developer skill in java is up to where they should be for such projects and so forth,['java'] +28578,best way to add thisqus comments to a rails application is there anything better than the thisqus ruby gem perhaps something geared specifically towards railsthe thisqus gem might be the best option i just have not been able to find much color one way or the other,['ruby-on-rails'] +28586,efficient way to determine number of digits in an integer what is a very efficient way of determining how many digits there are in an integer in c,['c++'] +28593,how do you grow as a developer when youre the only one in a given technology at your company i am not the only programmer but i am the only net developer everyone else works with perl ext js and related technologies i am primarily self taught using codeproject heavily to learn new techniques without any mentors at my company specifically knowledgeable in net i am unsure whether classes or online tutorials books or perhaps some other avenue might be most effective at helping me to become a better developer my goal optimistically is to become a developer capable of managing the next net developer we hire or at least to integrate well with himher i am currently taking on the task of documenting my programs in such a way as to receive review from the more experienced developers at my company regardless of them not knowing net and i expect this will be rather general but hopefully still beneficial does anyone have suggestions or advice for how to most effectively learn good practices without direct oversight,"['c#', '.net']" +28595,python modules most worthwhile reading i have been programming python for a while and i have a very good understanding of its features but i would like to improve my coding style i think reading the source code of the python modules would be a good idea can anyone recommend any ones in particularrelated threadsbeginner looking for beautiful and instructional python code this thread actually inspired this question,['python'] +28596,jquery inserting all stylesheets into iframe how can i insert all of a parent windows stylesheets into an iframes headsamedomainmy attempted code based on a similar questionfunction var d frames0document var stylesheets linkouterhtml dopen dwrite htmlhead stylesheets style typetextcss styleheadbodybodyhtml dcloseclearly this does not work outside of ie thanks in advanceedit attempt based on anthonys answerlinktypetextcsseachfunction var stylesheet thisclone iframecontentsfindheadappendstylesheet,"['javascript', 'jquery']" +28609,php get the latest file addition in a directory how to get the latest file name or the file path that is added into a directory,['php'] +28616,how do i find out which missing dll is making my net application crash on startup when dependencies on 3rd party assemblies are added to a typical net application it is very easy to forget to add them to the installer this problem tends to reveal itself only after the application is installed and in the form of a crash on startup with little helpful information readily availablewhat are the best tools and techniques to find out which assemblies need to be added to the installer,['.net'] +28623,pcap struct pcap pkthdr len vs caplen were sniffing packets using libpcap on linuxthe header we get on each packet looks likestruct pcap pkthdr struct timeval ts time stamp bpf you int32 caplen length of portion present bpf you int32 len length this packet off wire now it is my understanding that caplen is the length of the data we have captured whilelen is the length of the packet on the wire in some cases eg when setting the snaplen too low when opening the pcap device we might capture only parts of the packet that length will be caplen while len is the original length thus caplen should be equal to or less than len but never greater than lenis that a proper understanding were seing caplen len on some machines,['c'] +28640,what are the most useful third party iphone frameworks what really super useful third party frameworks toolkits projects are out there that people have used and have found to be a huge help in building their iphone apps bonus points if you include a story about how it helped you on a real world projecti will go firstcocos2djsonframeworkaqtoolkitedit turned this community wiki,['iphone'] +28653,what happens if i releasemutex twice the microsoft documentation is silent about what happens if i mistakenly call releasemutex when the mutex is already unlockeddetailsi am trying to fix up some windows code without having access to the compileri realise that winapi mutexes are all recursive and referencecounted if i were making use of that feature it is obvious that the extra releasemutex call would prematurely decrement the reference counterhowever the code that i am looking at does not use the mutex recursively so the reference count never gets higher than 1 it does release the mutex more times than necessary so what happens does the reference count go negative does it stay at zero unlocked and just return an ignorable errornaturally this code does not actually check for errors when it calls these functions,['c++'] +28656,ios open source voipsip objectivec code i have been tasked with investigating the feasibility of writing an iphone app to access our internal voipsip systemsi have never coded anything close to voip before are there any open source voipsip libraries or examples in c or objectivecan ios app that i can skin and add our required features to mainly ui related would be the holy grail here,"['iphone', 'objective-c']" +28675,embeddable workflowbpm library for python let us say you are building a pythonbased web app that requires some workflow management such as that in jbpm or windows workflow foundation is there a library that offers this in the python world,['python'] +28676,what does forwarding in the stack trace mean gdb bt0 0x302ac924 in terminating due to uncaught exception 1 0x92077e3b in objc exception throw 2 0x302d6ffb in nsobject doesnotrecognizeselector 3 0x3026e056 in forwarding 4 0x3024a0a2 in forwarding prep 0 5 0x04ae9 in gameobject doestouch self0xe893a0 cmd0x643ee obj0xe82e20 at usersadesktopcptgameclassesgameobjectm2206 0x06e05 in staticgrid checktouchnearest self0xe82f20 cmd0x64ec3 obj0xe893a0 at usersadesktopcptgameclassesstaticgridm627 0x0a393 in eaglview touchesbeganwithevent self0xe8dad0 cmd0x3199fa3c touches0x632c0b0 event0xe14590 at usersadesktopcptgameclasseseaglviewm4598 0x30910f33 in uiwindow sendtouchesforevent 9 0x308faecb in uiapplication sendevent 10 0x309013e1 in uiapplicationhandleevent 11 0x32046375 in purpleeventcallback 12 0x30245560 in cfrunlooprunspecific 13 0x30244628 in cfrunloopruninmode 14 0x32044c31 in gseventrunmodal 15 0x32044cf6 in gseventrun 16 0x309021ee in uiapplicationmain currently i have a rare occuring error that i do not know the cause yet i am not sure where to look at so what i want to ask is what do the first five lines 0 to 4 mean i know that it claims that there are some errors but what are those things like forwarding if you have some knowledge in this please help thank you very much,['objective-c'] +28677,detect user language in php stable solution i am currently working on a autouserlanguagedetection for providing the content in the users languageof course its possible to change the language manually but if a user visits the page for the first time i want to provide the content in his languageso i was googling and found the serverhttp accept languagevar to get a result like thatdededeq08enusq05enq03whats the best way to filter this result to get a clear result like en de itrl serverhttp accept language dededeq08enusq05enq03langcode strtoupperrl0rl1the second issue on this servervar is that its only give me a result if the browser provide some information is setting a default page language the only possibility to handle thatthe second possibility i am interested in is to get the language by ip so if i get the language i probably know the language of the user but whats in multilanguagecountries like switzerland belgium whats with tlds like com net org and so onso which method would you apply to detect the users languagethanks for helping,['php'] +28682,uiscrollview any thoughts on implementing infinite scrollzoom so uitableview supports essentially infinite scrolling there may be a limit but that sucker can scroll for a long time i would like to mimic this behavior with a uiscrollview but there are two fundamental impediments1 scrollviewcontentsize is fixed at creation time2 zooming can blow any lazyloading scheme all to hell since it can cause infinte data explosionhave others out there pondered this idea yah i know we are essentially talking about recreating google maps here any insights would be much appreciatedcheersdoug,['iphone'] +28694,with statement in java in vbnet there is the with command that lets you omit an object name and only access the methods and properties needed for examplewith foo bar resettrue myvar getnameend withis there any such syntax within javathanks,['java'] +28707,combining dictionaries of lists in python i have a very large collection of p q tuples that i would like to convert into a dictionary of lists where the first item in each tuple is a key that indexes a list that contains qexample original list 1 2 1 3 2 3 resultant dictionary 12 3 23furthermore i would like to efficiently combine these dictionariesexample original dictionaries 12 3 23 14 31 resultant dictionary 12 3 4 23 31these operations reside within an inner loop so i would prefer that they be as fast as possiblethanks in advance,['python'] +28720,concurrent modification exception i have this little piece of code and it gives me the concurrent modification exception i cannot understand why i keep getting it even though i do not see any concurrent modifications being carried outimport javautilpublic class someclass public static void mainstring args liststring s new arraylist listiteratorstring it slistiterator for string a args sadda if ithasnext string item itnext systemoutprintlns,['java'] +28725,why do activerecord callbacks require instance variables or instance methods to be prefixed with self keyword activerecord has a few different callback methods used to simplify model logic for example after find and before create methodsconsider this code exampleclass externalprintingcard activerecordbase belongs to user belongs to ph user after create change pin def change pin selfuserrandomize printer pin end def after find return if selfcard status false selfcard status false if selfis used up selfcard status false if selfis expired selfsave endendif i remove all the self prefixes from the instance variables or instance methods these 2 callbacks will be called but it is as if they are local variables inside these callback methodsthis instance variable card status instance methods save is used up and is expired and association user worked fine outside these 2 callback methods without the self prefixthe sample code in the rails documentation for callback methods instance methods seems to always use the self prefix even though it is calling instance variables or methods which by right they are accessible without the self prefix normallyi hope someone with a better understanding of activerecord callbacks can help to shed a light on this behaviourcheers,['ruby-on-rails'] +28742,program to test a sql connection string i need a free and quick to download program that can test a connection string,['sql'] +28750,linq where clause using if statements i am using cneti have two textboxes which if empty need to be part of a where clause within a linq queryhere is my code var result from a in x select aifstringisnulloremptypersonname return resultwherea aforenamecontainspersonname asurnamecontainspersonname else ifstringisnulloremptydatefrom return resultwherea aappstartdatetime datefromdateelse ifstringisnulloremptypersonname stringisnulloremptydatefrom return resultwherea aforenamecontainspersonname asurnamecontainspersonname aappstartdatetime datefromdatei thought this would work but it does not like the where and i cant access the a for example aforename the name a does not exist in the current contextwhat am i going wrong or can this not actually be donethanks in advance for any helpclare,"['c#', '.net']" +28753,strip text from html document using ruby there are lots of examples of how to strip html tags from a document using ruby hpricot and nokogiri have inner text methods that remove all html for you easily and quicklywhat i am trying to do is the opposite remove all the text from an html document leaving just the tags and their attributesi considered looping through the document setting inner html to nil but then really youd have to do this in reverse as the first element root has an inner html of the entire rest of the document so ideally i would have to start at the inner most element and set inner html to nil whilst moving up through the ancestorsdoes anyone know a neat little trick for doing this efficiently i was thinking perhaps regexs might do it but probably not as efficiently as an html tokenizerparser might,"['html', 'ruby']" +28808,detect urls in text with javascript does anyone have suggestions for detecting urls in a set of stringsarrayofstringsforeachfunctionstring detect urls in strings and do something swell like creating elements with linksupdate i wound up using this regex for link detectiona apparently several years laterklink detection regex azaz09az2aeroarpabizcomcoopedugovinfointjobsmilmuseumnamenatonetorgprotravellocalinternal0915az09 az09 az09 ampazaz09 sgithe full helper with optional handlebars support is at gist 1654670,['javascript'] +28809,how to script automatically the securables assigned to a sql account i want to generate script to assign an user account to some securables eg tableselecthow to do this,['sql'] +28830,how can the page know i am analyzing it with firebug lookwowhow can the webpage know i am using firebugbtw i could not find out how to show the translucent add banner,['javascript'] +28833,jquery click not working on replaced html i am still new to jquery so bare with mei am trying to create a gomoku game using jqueryphp and mysql databasei have a ajax function that updates the a board every second if neededvar turncount 1setintervalfunctiongetincludesboardcontrolphpturn turncount functiondataifdata boardhtmldataturncount turncounttextturncounttext 10this works just fine it checks the database to see if turn has been incremented and replaces the board if it has now what i want to ultimately do is create a click function that use ajax to update the board and turn count in the database i am hoping to somehow use the nth selector do determine what square i am clicking oni have several questions1 my click function right now isdocumentreadyfunction td imgclickfunctionalertclickedas of right now it works on a extra test table i wrote into the html but not on the table created with the previous function what am i doing wrong2 the tutorials i have looked at so far dictate that i should write code in the following waydocumentreadyfunction code herewhen i asked a question last night i was told that i was over complicating things with my functions so when should i use a documentready function and when not and is it fine to put all of my scripts into one documentready function or should i have multiple3once i get the click image to work i am hoping to send a xy coordinate to the server and change that corresponding spot on the board how would i determine what cell in the table is clicked in order to know what coordinates to use or is there a much easier waythanks in advance for all your help,"['javascript', 'jquery']" +28835,latex renderer for net i am curious as to whether a native net renderer for texlatex exists the closest match i have been able to find is a java implementation jmathtex i am tempted to port this to c but before i do so i would simply like to check whether anyone is aware of a net implementation out theremy current thoughts are to use miktex along with dvipng to compile the tex source and render the generated dvi as a png but i am still worrying this may incur an unacceptable amount of overhead not to mention the need to bundle miktex with the given program,['.net'] +28843,parsing out data using beautifulsoup in python i am attempting to use beautifulsoup to parse through a dom tree and extract the names of authors below is a snippet of html to show the structure of the code i am going to scrape htmlbodydiv classlistauthorsspan classdescriptorauthorsspan a hreffindastroph1aulin d010all01dacheng lina a hreffindastroph1auremillard r010all01ronald a remillarda a hreffindastroph1auhoman j010all01jeroen homana divdiv classlistauthorsspan classdescriptorauthorsspan a hreffindastroph1aukosovichev a010all01ag kosovichevadivthere are many other div tags with this structurebodyhtmlmy point of confusion is that when i do soupfind it finds the first occurrence of the div tag that i am searching for after that i search for all a link tags at this stage how do i extract the authors names from each of the link tags and print them out is there a way to do it using beautifulsoup or do i need to use regex how do i continue iterating over every other other div tag and extract the authors namesimport reimport urllib2sysfrom beautifulsoup import beautifulsoup navigablestringhtml urllib2urlopenaddressread soup beautifulsouphtml try authordiv soupfinddiv attrsclass listauthors linkstdsfindalla for link in links print joinlink0contents iterate through entire page and print authors except ioerror print io error,"['python', 'html']" +28845,invalid access of stack red zone from java vm i am trying to figure out what can cause this error in javainvalid access of stack red zone 0x115ee0ed0 rip0x114973900has anyone ever encountered this error message it is literally killing the jvm and everything stops therei am currently using this version of javaon os x 106java version 160 15javatm se runtime environment build 160 15b03219java hotspottm 64bit server vm build 141b0290 mixed modeall i am looking for is some sort of explanation and tips on how to avoid hitting this againthanks in advance,['java'] +28860,does xna effectively replace managed directx possible duplicatecomparison between xna and directx c the subject speaks for itselfdoes xna effectively replace managed directxwe have a few projects using managed directx in vbnet i was considering porting one over to xna but wonder whether it is worth the effort,['.net'] +28865,how to use webrequest to post data and get response from a webpage i need to implement an application to post request to a given url and get responsewhat are the best methods to post request to a given url and get responseplease help,"['c#', 'asp.net']" +28866,calculate thistance between two points in google maps v3 how do you calculate the thistance between two markers in google maps v3 similar to the thistancefrom function inv2thanks,['javascript'] +28868,favourite open source google app engine apps java or python to learn from good examples what are the best open source google app engine applications out therei do not care if it is java or python basedplease one app per answer feel free to add a link to the live app if there is and to the project page,"['java', 'python']" +28870,what are the most commonly used runtime exceptions in java as a java programmer who wishes to perfect his programming skills i often come across the situations that i have to create a runtime exception i know it is a good practice if one use wisely personally nullpointerexception and illegalstateexception are the most commonly used in the softwares that i have created how about youwhat runtime exceptions do you often use in what situations do you use them,['java'] +28875,how to detect and fix character encoding in a mysql database via php i have received this database full of people names and data in french which means using characters such as aa aa etc around 30 entriesapparently the data inside has been encoded sometimes using utf8 encode and sometimes not this result in a messed up output at some places the characters show up fine at others they do notat first i tried to track down every place in the ui where those issues arise and use utf8 decode where necessary but it is really not a practicable solutioni did some testing and there is no reason to use utf8 encode in the first place so i would rather remove all that and just work in utf8 everywhere at the browser middleware and database levels so i need to clean the database converting all misencoded data by its cleaned up versionquestion would it be possible to create a function in php that would check if a utf8 string is correctly encoded without utf8 encode or not with utf8 encode and if it was convert it back to its original statein other terms i would like to know how i could detect utf8 content that has been utf8 encode to utf8 content that has not been utf8 encoded update example here is a good example you take a string full of special chars and take a copy of that string and utf8 encode it the function i am dreaming of takes both strings leaves the first one untouched and the second string is now the same as string onei tried thisloc fr setlocalelc all fr beutf8fr beeuro fr be fr fra fr frstr1 aa a a str2 utf8 encodestr1function convert charsetstr charset mb detect encodingstr if charsetutf8 return utf8 decodestr else return str function correctstringstr echo nbefore str str convert charsetstr echo nafter str correctstringstr1echohrncorrectstringstr2and that gives mebefore aa a a after i12i12i12i12i12i12i12 before a a a after aa a a thanksalex,"['php', 'mysql']" +28876,enum declared outside class scope i went to this interview for a software developer position and they gave me a test with some cornercasecode situations with usually 4 options to chooseone of the questions had an enum declared outside the class scope i promptly checked the does not compile answer and went ahead with the other questionsit was something likeenum colors blueredgreenclass test other code not really important with my questionthis code actually compilesbesides the fact that an interview like this might or might not be useful to find out if one is a good developer what worries me is why would i declare an enum like this why i can only do this with enum i did some testing and found out that it is visible inside the class but not to other classessidenote i scored really poor p i got the max on the theory but near the lowest possibile on the cornercasecode situations i do not think i will get the job,['java'] +28879,get latitudelongitude from address how can i get latitude and longitude from a full address street city etc input by the user using the iphone sdk 3x,['ios'] +28887,implicit type cast in c i have a question about the implicit type conversionwhy does this implicit type conversion work in c i have learned that implicit code usually do not worki have a code sample here about implicit type conversion char c a int x c int and 5 int answer and c consolewritelineanswer,['c#'] +28890,purpose for i have used the following in webconfigpages enableeventvalidationfalsethis corrects a problem weve been having with ajaxwe have a web page that if you browse to directly using a standard html hyperlink works fineif you browse to the page from another page via link inside a gridview and responseredirecting in the rowcommand event to the page passing an id in the querystring the page throws errors from controls inside the panel stating invalid postback or callback argument event validation is enabled using in configuration or page enableeventvalidationtrue in a page for security purposes this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them if the data is valid and expected use the clientscriptmanagerregisterforeventvalidation method in order to register the postback or callback data for validation i am happy to leave the page validation as false as it seems to have had no other effectany ideas whats happening,['asp.net'] +28892,ok to release a pointer thats nil if i create a new object that includes two object pointers see below when the object is created the pointers are set to point to nilinterface rocketship nsobject nsstring name nsnumber thrustif for some unexpected reason i do not assign these pointers and later release them in my dealloc method is that ok i am pretty sure it is just wanted to check voiddealloc name release name nil thrust release thrust nil super deallocgary,['objective-c'] +28902,recursive call return a list return type causing me issues i have a recursive method that is return me categories and checking for its sub categoriesso it looks likepublic listcategory getallchildcatsint categoryid listcategory list new listcategory category c getcategoryid foreachcategory cat in cchildcategories listadd getallchildcatscatcategoryid this fails because the call to listadd expects a category object but it is return yet another list how should i work around this,['c#'] +28905,android use a switch statement with setonclicklisteneronclick for more than 1 button let us say i have a few buttons in a linearlayout 2 of them aremycards button buttonthisfindviewbyidridbutton mycardsexit button buttonthisfindviewbyidridbutton exiti register setonclicklistener on both of themmycards buttonsetonclicklistenerthisexit buttonsetonclicklistenerthishow do i make a switch to differentiate between the two buttons within the onclick public void onclickview v switch case start a new activity mycardsjava intent intent new intentthis mycardsclass thisstartactivityintent break case alerdialog when click on exit myalertdialog break,['android'] +28910,c what does the percentage sign mean i got this c macro and wonder what they mean by code2 the percentage sign define shuffle statement 2code a bswitch code2 case 0 a b break case 1 b a break,['c++'] +28922,whats the difference between like and in sql is there any difference betweenselect from users where usernamedavyjonesandselect from users where username like davyjonesi think i have bungled up the syntax pardon me for thati am mostly a desktop app development guy,['sql'] +28926,need to know if a jquery ui widget has been applied to a dom object i am using jquery and have some interactions with a jquery ui where i need to get options however there is a possibility that the jquery ui function has not been applied yet to the dom object i am getting a javascript error right now when i access an optioni have a dom object that has the progressbar attached to it maybe in another thread i am trying to access the options using domobjprogressbaroption valuehow do i determine if that domobj has a progressbar attached,['jquery'] +28939,hibernateehcache evicting collections from 2nd level cache not synchronized with other db reads i have an application using jpa hibernate and ehcache as well as springs declarativetransactions the load on db is rather high so everything is cached to speed things upincluding collections now it is not a secret that collections are cached separatelyfrom the entities that own them so if i delete an entity that is an element of suchcached collection persist an entity that should be an element of one or update anentity such that it travels from one collection to another i gotta perform the evictionby handso i use a hibernate event listener which keeps track of entities being inserted deletedor updated and saves that info for a transaction synchronization registered with springstransaction manager to act upon the synchronization then performs the eviction once thetransaction is committednow the problem is that quite often some other concurrent transaction manages to finda collection in the cache that has just been evicted these events are usually tenths of asecond apart according to log and naturally causes an entitynotfoundexception to occurhow do i synchronize this stuff correctlyi tried doing the eviction in each of the 4 methods of transactionsynchronization whichare invoked at different points in time relative to transaction completion it did not help,['java'] +28940,bestfastest way to write a parser in c what is the best way to build a parser in c to parse my own languageideally i would like to provide a grammar and get abstract syntax trees as an outputmany thanksnestor,['c#'] +28942,how to use export with python on linux i need to make an export like this in python export my datamy exporti have tried to do pythonmode coding utf8 import osossystemexport my datamy exportbut when i list export my data not appear exporthow i can do an export with python without saving my export into a file,['python'] +28953,java enums two enum types each containing references to each other is there a way to get around the classloading issues caused by having two enums that reference each otheri have two sets of enumerations foo and bar defined like sopublic class enumtest public enum foo abaralpha bbardelta cbaralpha private foobar b thisb b public final bar b public enum bar alphafooa betafooc deltafooc private barfoo f thisf f public final foo f public static void main string args for foo f foovalues systemoutprintlnf bar fb for bar b barvalues systemoutprintlnb foo bf the above code produces as outputa bar alphab bar deltac bar alphaalpha foo nullbeta foo nulldelta foo nulli understand why it happens the jvm starts classloading foo it sees the baralpha in fooas constructor so it starts classloading bar it sees the fooa reference in the call to baralphas constructor but since were still in fooas constructor fooa is null at this point so baralphas constructor gets passed a null if i reverse the two for loops or otherwise reference bar before foo the output changes so that bars values are all correct but foos values are notis there any way to get around this i know i can create a static map and a static map in a 3rd class but that feels fairly hackish to me i could also make foogetbar and bargetfoo methods that refer to the external map so it wouldnt even change my interface the actual classes i have use inspectors instead of public fields but it still feels kind of unclean to methe reason i am doing this in my actual system foo and bar represent types of messages that 2 apps send to each other the foob and barf fields represent the expected response type for a given message so in my sample code when app 1 receives a fooa it needs to reply with a baralpha and viceversathanks in advance,['java'] +28959,using visual studio c compiler in netbeans i want to develop a few assignments in c on windows but visual studio does not provide a few user functions that make development a real pain to go without can someone help me with setting up the netbeans c environment to use the same compiler that visual studio is using,['c++'] +28965,how to run single test from rails test suite rake test anything seems to not helppsthe question is about rails itself not rails app,['ruby-on-rails'] +28970,atomic compare and swap in a database i am working on a work queueing solution i want to query a given row in the database where a status column has a specific value modify that value and return the row and i want to do it atomically so that no other query will see itbegin transactionselect from table where pk x and status yupdate table set status z where pk xcommit transactionthe row would be returnedit must be impossible for 2 or more concurrent queries to return the row one query execution would see the row while its status y sort of like an interlocked compareandexchange operationi know the code above runs for sql server but will the swap always be atomici need a solution that will work for sql server and oracle,['sql'] +28980,how to setup or construct a php unit test class testclass extends phpunit framework testcase function testsomething class new class thisasserttrueclasomefunc1 function testsomethingagain class new class thisassertfalseclasomefunc0 hi do i really have to create class for every test function i create or is there an unknown constructor like function that i have yet to thiscover since constructors do not seem to work in phpunitthanks,['php'] +28985,getting raw sql queries in codeigniter 17 i am trying to debug some code in my first serious codeigniter app and i cannot seem to find where i can simply get the raw sql that my activerecord code just generatedwhere daydatetime start datedday and where monthdatetime start datemday thisdbfromeventswherewhereresult thisdbgetthanks for the help,['php'] +28986,searching for a sequence of bytes in a binary file with java i have a sequence of bytes that i have to search for in a set of binary files using javaexample i am searching for the byte sequence deadbeef in hex in a binary filehow would i go about doing this in java is there a builtin method like stringcontains for binary files,['java'] +28998,why does this polymorphic c code print what it does i was recently given the following piece of code as a sortof puzzle to help understand polymorphism and inheritance in oop c no compilingpublic class a public virtual string getname return a public class ba public override string getname return b public class cb public new string getname return c void main a instance new c consolewritelineinstancegetname no compilingnow after a long long chat with the other developer who presented the puzzle i know what the output is but i wont spoil it for you the only issue i am really having is how we get to that output how the code steps through whats inheriting what etci thought c would be returned as that seems to be the class that is defined then i went through my head as to whether b would be returned because c inherits b but b also inherits a which is where i got confusedquestioncould anyone explain how polymorphism and inheritance play their part in retrieving the output eventually thisplayed on screen,"['c#', '.net']" +29005,how can i erase the current line printed on console in c i am working on a linux system how can i erase the current line printed on the console in c i am working on a linux systemexample printfhelloprintfbyei want to print bye on the same line in place of hellobye,['c'] +29008,read string from resx file in c hi how to read the string from resx file in c please send me guidelines step by step,"['c#', '.net']" +29019,how to make a web bot or something i need to register to a site programmatically i did it with vb6 using the ie web browser component but i do not know how to edit textboxes on a website using webbrowser i do not need to do it with webbrowser it is just that i know it can be done with it i just need to insert a username a password etc using my programthanks,"['c#', '.net']" +29020,how can i share a resource file between projects in visual studio i am using c and how can i code to share a resource file between my projects in the same solutionthank you,['c#'] +29023,iphone adding segmented control to toolbar instead of buttons within navigation controller im new to iphone programming so if you could help me out i would appreciate it i have been all over the web and cant find the answer to thismy current setup is like thisnavigation controller in mainwindowxib view in navigation controller in mainwindowxib calls rootviewcontrollerxib rootviewcontrollerxib contains a single tableviewi can then load in a toolbar using the following code in rootviewcontrollermuibarbuttonitem buttonone uibarbuttonitem alloc initwithtitleone styleuibarbuttonitemstylebordered targetself actionselectorbuttononepusheduibarbuttonitem buttontwo uibarbuttonitem alloc initwithtitletwo styleuibarbuttonitemstylebordered targetself actionselectorbuttontwopushed nsarray bararray nsarray arraywithobjects buttonone buttontwo nilbuttonone releasebuttontwo releaseself settoolbaritemsbararray animatedyesselfnavigationcontroller settoolbarhiddenno animatedyesthis code works for buttons but i cannot for the life of me find out how to add a segmented control instead of the buttons i have tried an array with two segmented controls in it but then cannot add the array to the toolbarif anyone could let me know some code that will add segmented controls in the same fashion as i have used to add the buttons i would greatly appreciate itthanks dave,['iphone'] +29042,using generics causes unchecked conversion warning i have the following codestring innertext nullinnertext thisgetexceptiondetailgetchildelementscausing this warningtype safety the expression of type iterator needs unchecked conversion to conform to iteratorthe referenced method isprivate string getexceptioniteratoromelementimpl iterator the other method getchildelements is in a jar file that i cannot touch there are no other warnings or errorsfrom googling it seems like the usual way to get rid of this sort of warning issuppresswarningsuncheckedstring innertext thisgetexceptiondetailgetchildelementsbecause the compiler cannot guarantee safety ahead of time but i would prefer to avoid using suppresswarnings if possible is there a better wayedit getchildelements is documented here,['java'] +29056,where does android emulator store sqlite database i am working on an android application that stores data in a sqlite database my question is where does this database file get stored on the filesystem when youre using an emulatori have seen that it is stored in datadatapackage namedatabasesbut i need to know where on my local machines hard drive that actually maps to the database persists on multiple runs of the emulator even after having shut down the machine so it cannot just reside in ram,['android'] +29062,php array are array indexes case sensitive i do not know if this is a problem yet but wanted to start thinking about itquestionare php array indexes case sensitiveexampleaarrayadogbcatchorseadogbcatchorseprint raresultsarray a dog b cat c horse a dog b cat c horse i have run a couple of examples and this seems to hold true just wanted to make sure that i am seeing this correctly,['php'] +29085,wicket dynamic image url short questioni need to turn a dynamic image pulled from a database into a url without adding a component to the thisplaying page such as using a noncachingimage using wicketthe perfect solution that i have implemented in other frameworks is simply to create a page that takes the image id as a url parameter and renders the image to the response stream unfortunately wickets page class extends markupcontainer which revolves around markupstreams markupstreams are not very conducive to rendering byte data directlylong questioni am using wicket 140 running in tomcat 6018 the image is stored in a postgres database retrieved via jdbc the image needs to be rendered by a third party api that only accepts image urls i have a model object that contains the byte data mime type and a resource object that can pull the model from the db and add it to a response streamany ideas,['java'] +29091,grabbing text between all tags in nokogiri what would be the most efficient way of grabbing all texts between html tags diva hi abunch of texts surrounded by html tags,['ruby'] +29095,what is the difference between int x1 and int x1 in c possible duplicateis there a difference in c between copy initialization and assignment initialization i am new to c i seldom see people using this syntax to declare and initialize a variable int x1i tried the compiler did not complain and the output is the same as int x1 are they actually the same thingmany thanks to you all,['c++'] +29101,can i transform an object and access the private data members in c i want to access a private data member in a class there is no member function in the class to access the private data member it is private i want to take the class and some how crack it open one method was to copy the declaration of the class make the private member public and call the new class class something else then i do a reinterpret cast and copy the original object this works but i want something more elegant or perhaps generic or just another waywhat options are there can i use void can i memcpy the class into another empty class what are ways to do this,['c++'] +29110,why are all fields in an interface implicitly static and final i am just trying to understand why all fields defined in an interface are implicitly static and final the idea of keeping fields static makes sense to me as you cannot have objects of an interface but why they are final implicitlyany one knows why java designers went with making the fields in an interface static and final,['java'] +29117,scripting language for cc is there a scripting language for c like perl which can be used for rapid development and use some tool which can convert into cc program to get higher performance for deploymentedit based on some commented let me clarify the question i should be able to convert script into cc program or binary without modifying my script,"['c++', 'c']" +29123,how to generate xmlrootelement classes for base types in xsd i am having some issues with generating java classes with appropriate jaxb annotations from an xsd using xjci have a relatively simple xsd file defining my xml schema the complex types within the xsd take advantage of inheritance using the xsextension tags the problem i having is that i need all complex types to generate java classes with the xmlrootelement unfortunately the way in which xjc generates the classes means that only derived class gets the xmlrootelement not the base class i am using the simple global binding directive to ensure that it solves many of the other issues that i have faced with xjc here is an example snippet of the xsdxsschema version10 targetnamespace xmlnskmcs xmlnsxs xmlnsjaxb jaxbversion20 xmlnsxjc jaxbextensionbindingprefixesxjc elementformdefaultqualified xsannotation xsappinfo jaxbglobalbindings xjcsimple jaxbglobalbindings xsappinfo xsannotation xselement nameartifact typekmcsartifact xselement nameemailartifact typekmcsemailartifact xscomplextype nameartifact xssequence xselement nameartifactid typexsstring minoccurs0 xselement nameartifacttype typexsstring minoccurs0 xselement namecontenthash typexsstring minoccurs0 xssequence xscomplextype xscomplextype nameemailartifact xscomplexcontent xsextension basekmcsartifact xssequence xselement namesubject typexsstring minoccurs0 xselement namethreadsubject typexsstring minoccurs0 xselement namefrom typexsstring minoccurs0 xselement nameto typexsstring minoccurs0 xselement namecc typexsstring minoccurs0 xselement namebcc typexsstring minoccurs0 xselement namemessageid typexsstring minoccurs0 xselement namedate typexsdate minoccurs0 xselement namesize typexslong minoccurs0 xselement namehasattachment typexsboolean minoccurs0 xselement namesensitivity typexsstring minoccurs0 xselement nameheaderhash typexsstring minoccurs0 xssequence xsextension xscomplexcontent xscomplextypexsschemaas we can see from the above snippet emailartifact extends artifact the java class code for emailartifact contains the followingxmlaccessortypexmlaccesstypefieldxmltypename emailartifact proporder subject threadsubject from to cc bcc messageid date size hasattachment sensitivity headerhashxmlseealso extendedemailclassxmlrootelementname emailartifactpublic class emailartifact extends artifact protected string subject protected string threadsubject protected string from protected string to protected string cc protected string bcc protected string messageid xmlschematypename date protected xmlgregoriancalendar date protected long size protected boolean hasattachment protected string sensitivity protected string headerhashthe java class code for artifact contains the followingxmlaccessortypexmlaccesstypefieldxmltypename artifact proporder artifactid artifacttype contenthashxmlseealso manageddocartifactclass emailartifactclasspublic class artifact protected string artifactid protected string artifacttype protected string contenthashin the emailartifact we can see that it contains the xmlrootelement but the base type artifact does not contain xmlrootelement how can you force xjc to generate xmlrootelement for all classes including the base types,['java'] +29124,python implementation of the object pool design pattern i need an object pool and rather than implement it myself i thought i would look around for a readymade and tested python librarywhat i found was plenty of other people looking but not getting many straight answers so i have brought it over here to stack overflowin my case i have a large number of threads using the threading module which need to occasionally call a remote soapbased server they could each establish their own connection to the server but setting up a socket and completing the authentication process is expensive it is throttled by the server so i want to share a pool of connections creating more only as neededif the items to pool were worker subprocesses i might have chosen multiprocessingpool but they are not if they were worker threads i might have chosen this implementation but they are notif they were mysql connections i might have chosen pysqlpool but they are not similarly the sqlalchemy pool is outif there was one thread using a variable number of connectionsobjects i would consider this implementation but i need it to be threadsafei know i could implement this again fairly quickly but given there are many people looking for it i thought a canonical answer on stack overflow would be nice,['python'] +29138,how can i create new records with has many through and honor conditions let us say i have a course in which students can enroll via a membership eg a has and belongs to many relationsip of courses and students some memberships are for students who are just observing the class not for credit etc soclass course activerecordbase has many memberships has many students through memberships has many observers through memberships source student conditions memberships observer true endheres what works greatobservers coursefind37observersheres what does not worknew observer coursefind37observersbuildname joe studenti would have thought that one could build new records using the association and that would have generateda new student record joe studenta new membership record course id 37 student id joe observer truebut instead i getactiverecordassociationtypemismatch membership expected got arrayi am sure i am totally confused about how this and would appreciate any insights i have also tried to do this with named scopes on the membership model but i cannot seem to get has many to use a scope in the associationthanks so much for any help possible,['ruby-on-rails'] +29140,how to properly compare two integers in java i know that if you compare a boxed primitive integer with a constant such asinteger a 4if a 5a will automatically be unboxed and the comparison will workhowever what happens when you are comparing two boxed integers and want to compare either equality or less thangreater thaninteger a 4integer b 5if a bwill above code result in checking to see if they are the same object or will it autounbox in that casewhat aboutinteger a 4integer b 5if a 5,['java'] +29159,thisplay select users and groups dialog from wpf application i need to thisplay the standard select users and groups dialog from a netwpf application i also need to be able to thisplay it under a 64bit os i found this codeproject article which is quite ancient dating back to the net 11 days it is written in managed c and exposed as a com object which will not work for my needs has anyone implemented or know of an implementation of a pure netc wrapper for thisplaying and interacting with the standard system select users and groups dialog that will work with a wpf application,['.net'] +29172,confusion in output consider the following program includeiostreamusing namespace stdclass base public int bval base bval0class derivedpublic base public int dval derivedbase dval1int main derived d5 base p pd forint i0i5ip coutp bvalthe output of the above program is 01010i thought the output would be 0 because the value of bval was initialized to 0each time by the base class constructor but why is the output different from 0what am i missing,['c++'] +29173,how to resolve host only using boostasio according to the documentation of boostasioiptcpresolverquery in order to resolve host it should receive serviceas wellwhat if i want to resolve host without relation to port how should i do it at all shouldi specify dummy port,['c++'] +29175,wrapper printf function that filters according to user preferences my program writes to a log and to stdout every message however has a certain priority and the user specifies in preferences which priorities go to which stream log or stdout unsigned short prio high 0x01unsigned short prio normal 0x02unsigned short prio low 0x03the preferences is handled by some flagsunsigned short prio log prio high prio normalunsigned short prio std prio highthe write log function should work with the same parameters as the printf function with the added parameter of unsigned short prioritywrite logprio normalprio low hello s take d world 1even if prio normalprio low makes little sensechecking the flags is easy ifpriority prio log returns 1 if any flag is set in both argumentsi cannot however find out how i would go about passing the string literal and the format arguments to the printf function can anyone help or give me a pointer possible to an alternative method that achieves the same effect it would be much appreciated,['c'] +29176,how can i access an interbase ib database using rubyonrails i have a database in interbase and i want to access it directly from my rails app using activerecord how can i do it,['ruby-on-rails'] +29182,is not wpfs grid based layout the same as table based layout that is taboo in html both employ the same concept define some rows and columns and add content into specific positions but the grid is the most common wpf layout container while table based layout in html is very controversial so why is wpfs grid layout praised and htmls table based layout considered bad by some,['html'] +29189,anatomy of a thistributed system in php i have a problem which is giving me some hard time trying to figure it out the ideal solution and to better explain it i am going to expose my scenario herei have a server that will receive orders from several clients each client will submit a set of recurring tasks that should be executed at some specified intervals eg client a submits task aa that should be executed every minute between 20091231 and 20101231 so if my math is right that is about 525 600 operations in a year given more clients and tasks it would be infeasible to let the server process all these tasks so i came up with the idea of worker machines the server will be developed on phpworker machines are just regular cheap windowsbased computers that i will host on my home or at my workplace each worker will have a dedicated internet connection with dynamic ips and a ups to avoid power outages each worker will also query the server every 30 seconds or so via web service calls fetch the next pending job and process it once the job is completed the worker will submit the output to the server and request a new job and so on ad infinitum if there is a need to scale the system i should just set up a new worker and the whole thing should run seamlessly the worker client will be developed in php or pythonat any given time my clients should be able to log on to the server and check the status of the tasks they orderednow here is where the tricky part kicks ini must be able to reconstruct thealready processed tasks if for somereason the server goes downthe workers are not clientspecificone worker should process jobs forany given number of clientsi have some doubts regarding the general database design and which technologies to useoriginally i thought of using several sqlite databases and joining them all on the server but i cannot figure out how i would group by clients to generate the job reportsi have never actually worked with any of the following technologies memcached couchdb hadoop and all the like but i would like to know if any of these is suitable for my problem and if yes which do you recommend for a newbie is thistributed computing or is this parallel like me please keep in mind that the workers have dynamic ipslike i said before i am also having trouble with the general database design partly because i still have not chosen any particular rddbms but one issue that i have and i think it is agnostic to the dbms i choose is related to the queuing system should i precalculate all the absolute timestamps to a specific job and have a large set of timestamps execute and flag them as complete in ascending order or should i have a more clever system like when timestamp modulus 60 0 execute the problem with this clever system is that some jobs will not be executed in order they should be because some workers could be waiting doing nothing while others are overloaded what do you suggestps i am not sure if the title and tags of this question properly reflect my problem and what i am trying to do if not please edit accordinglythanks for your inputtimdevthe input will be a very small json encoded string the output will also be a json enconded string but a bit larger in the order of 15 kbthe output will be computed using several available resources from the web so the main bottleneck will probably be the bandwidth database writes may also be one depending on the rddbms,['php'] +29197,how to style unordered lists in css as comma separated text iam looking for a way to style an unordered list in xhtml with css such that it is rendered inline and the list items are separated by commasfor example the following list should be rendered as apple orange banana note the missing comma at the end of the listul idtaglist liappleli liorangeli libananaliulcurrently iam using the following css for styling this list which almost does what i want but renders the list as apple orange banana note the trailing comma after bananataglist thisplay inline liststyle nonetaglist li thisplay inlinetaglist liafter content is there a way to solve this problem with pure css,"['html', 'css']" +29199,iphone sdk open app store to specific app is there a way to open the app store to a specific applicationi tried using something like the followinguiapplication sharedapplication openurl nsurl urlwithstringmt8uo6but got the following safari cannot open the page because to many redirects occurred,['objective-c'] +29202,where is the jar files cached for java web startjnlp applications where is the jar files cached for java web startjnlp applications,['java'] +29237,resolve ip to hostname using php how can i resolve an ip address to a hostname using php,['php'] +29242,using reflection to find interfaces implemented i have the following case public interface iperson public class person iperson public class user person now if i have a user object how can i check if this implements iperson using reflection to be more precise i have an object that might have a property someuser which should be of some type implementing the interface iperson in my case i actually have a user but this is what i want to check through reflection i cannot figure out how to check the property type since it is a user but i want to check if it implements ipersonvar control containerresolveobjtype objtype is user herevar prop viewtypegetpropertysomeuserif prop null proppropertytype is iperson note that this is a simplification of my actual case but the point should be the same,"['c#', '.net']" +29247,images that are in app data folder not shown in browser when i set image url property to asp image control that is in app data folder image is showing in page design view but not in browserform idform1 runatserverdiv aspimage idimage1 runatserver imageurlapp datap3jpg divformit seems to be looking straight forward but not showing imagethanks,['asp.net'] +29261,what does aa double colon do in javascript the documentation of some javascript api shows the following snippets as example how to invoke some functionbutton typebutton onclickfoodoit72930clickbuttonbutton typebutton onclickfoodoit4234237438clickbutton is obviously used here to allow either one or two arguments to be passed to the functionwhat does do in javascriptand how does the function know if one or two values were passed how does it read themediton closer look the examples show other weird stuff likebutton typebutton onclickfoobar72893clickbuttonbutton typebutton onclickfooqux425134clickbuttonat least the looks just wrongso i guess it is not some fancy new syntax that i am not aware of but maybe the example are just missing quotes around a single string argument,['javascript'] +29263,running software built for net 35 on a system with only net 20 installed how far along does software compiled for net 35 get before crashing on a system that only has net 20 installedthe application i am developing uses wpf and requires net 35 but i would like to thisplay a userfriendly dialog rather than crashing if the user does not have it installedare there any standard ways to do this or official microsoft documentation on itedit in an ideal world i would just check that any net dependencies are satisfied during installation since some applications do not have installers and since users could potentially uninstall net after the application is installed i find the answers below to be useful,['.net'] +29269,why regexp with global flag in javascript give wrong results what is the problem with this regular expression when i use the global flag and the case insensitive flag query is a user generated input the result should be true truevar query foo bvar re new regexpquery givar result resultpushretestfoo barresultpushretestfoo bar result will be true falsevar reg agfori 0 i 10 consolelogregtesta,['javascript'] +29275,c mathround i am trying to understand how to round to the nearest tenths position with c for instance i have a value that is of type double this double is currently set to 1075 however i need to round and then truncate everything past the tenths position in this case i am seeking a value of 108 how do i round to the tenths position in cthank you,['c#'] +29277,cleanest method for copying native dlls in a net project i have a c gui application that references a managed c project which requires 7 native c dlls i am looking for the cleanest method for copying these 7 dlls to the final project outputwhat works add all dlls to the c applications specifyingbuild action content copy to output directory copy alwaysthis will make the base folder of the project a mess of dlls in some cases all of which are requirements of referenced projects and not that project itself what does not workadding these dlls to a folder named required dlls with the above settings it copies it to a folder with the same name in the output causing them to be in an incorrect location i cannot see a way to specify the output directoryembedded resources in c pinvoke you can add dlls youre referencing as embedded resources and the dlls are embedded inside your final library i do not see this possibility in managed c and i am not even sure if it works with reference chainsadding the dlls as content within the managed c project the files do not get copied to the output directorywhat is the best solution in this case i would prefer the managed c project to be able to handle it is own dll requirements if possible and preferably in a way that would not prevent the project from being used across multiple applicationsas far as having a clean project goes is it better to insert all my code files within subfolders in the project and have the dlls at the root to make the first solution worksolutionusing the postbuild suggestion from joseph the following command does the trick to use a required dlls folderxcopy projectdirrequired dlls targetdir q yq hides the individual files from the output and y suppresses overwrite prompts,['c#'] +29293,standard android button with a different color i would like to change the color of a standard android button slightly in order to better match a clients brandingthe best way i have found to do this so far is to change the buttons drawable to the following drawable located in resdrawablered buttonxmlxml version10 encodingutf8 selector xmlnsandroid item androidstate pressedtrue androiddrawabledrawablered button pressed item androidstate focusedtrue androiddrawabledrawablered button focus item androiddrawabledrawablered button rest selectorbut doing that requires that i actually create three different drawables for each button i want to customize one for the button at rest one when focused and one when pressed that seems more complicated and nondry than i needall i really want to do is apply some sort of color transform to the button is there an easier way to go about changing a buttons color than i am doing,['android'] +29300,how to make gedit a good jqueryweb design editor i want to have syntax highlighting for jquery and maybe when i type html it can automatically insert html is there anyway to make gedit do this,['jquery'] +29309,nslocale currentlocale always returns en us not users current language i am in the processes of internationalizing an iphone app i need to make programmatic changes to certain views based on what the users current locale is i am going nuts because no matter what the language preference on the iphone simulator or actual hardware are locale always evaluates to en usnsstring locale nslocale currentlocale localeidentifiernslogcurrent locale localethe crazy thing is that the rest of the application behaves as expected the correct strings are selected from the localizationstrings file and used in the interface and the correct xib files for the selected locale are usedi have also tried the following to no avail and with the same resultnsstring locale nslocale autoupdatingcurrentlocale localeidentifiernslogcurrent locale localeis there something simple i am missing a preference or an import perhapswhat i used to doas darrens answer suggests the preference i am looking for is not in nslocale rather it is herensuserdefaults userdefaults nsuserdefaults standarduserdefaultsnsarray languages userdefaults objectforkeyapplelanguagesnsstring preferredlanguage languages objectatindex0nslogpreferredlanguage preferredlangpeters answer seems to be a better solutionnsarray preferredlanguages nslocale preferredlanguagesnslogpreferredlanguages preferredlanguages,"['iphone', 'objective-c']" +29311,is there a way to mix monotouch and objectivec i would like to know if there is a way to mix c and objc code in one project specifically i would like to use cocos2d for my ui in objc and call some monotouch clibrary that does some computations and get some values back is there a way to do this or maybe the other way around i e building in monotouch and calling cocos2dfunctionsthanks,['objective-c'] +29316,does inputoutputstreams close on destruction does inputstreams and outputstreams in java close on destruction i fully understand that this may be bad form esp in c and c world but i am curiousalso suppose i have the following codeprivate void foo final string file bartxt properties p new properties pload new fileinputstreamfile does the nameless fileinputstream goes out of scope after pload and therefore get destroyed kinda like c scoping rules i tried searching for anonymous variable scope for java on google but that did not turn up what i thought it would bethanks,['java'] +29336,python list comprehension to assign different values i am making a 2d list and i would like to initialize it with a list comprehension i would like it to do something like thisx for i in range3 if j 1 x1 else x2 for j in range3so it should return something like1 1 2how might i go about doing thisthanks for your help,['python'] +29340,rails activerecord serialize attr method gives missing class or module error i am trying to serialize a simple attribute in an activerecord model and rails 234 does not like itclass shopper serialize tagsend a shoppernew shopperatags aoeustnh aoeusnth asave typeerror class or module requiredanyone know what i am missing,"['ruby-on-rails', 'ruby']" +29355,ensuring valid utf8 in php i am using php to handle text from a variety of sources i do not anticipate it will be anything other than utf8 iso88591 or perhaps windows1252 if it is anything other than one of those i just need to make sure the text gets turned into a valid utf8 string even if characters are lost does the translit option of iconv solve this for example would this code ensure that a string is safe to insert into a utf8 encoded document or databasefunction make safe for utf8 usestring encoding mb detect encodingstring utf8iso88591windows1252 if encoding utf8 return iconvencoding utf8translit string else return string,['php'] +29358,am i making the right choice in choosing yii as my php framework i am about to begin development of a new website and have been doing research on php frameworks i am not an advanced php developer but i have been developing web sites and apps in aspnet for a few years nowmy website will primarily be ajaxbased using jquery and making lots of calls to web services after some research heres what i came up withcakephp originally started developing in this but found it too complex the fact that it forces you to use and learn all this new stuff just to use it was a bit daunting so i put it aside for the time beingzend the performance of the framework leaves me a bit skeptical but i heard it has great support for creating web services i also heard it was a bit complexcodeigniter no real reason for not using this one based on what i have read codeigniter and yii are very similar but yii is a bit faster and does not have unneeded code for php4 since i plan on developing exclusively in php5as far as yii the only things that scare me about it are that it is newer than the other frameworks so it has a smaller community it also does not seem to have a ton of web service support only soap from my understanding as opposed to zend so my questions come down toshould these things worry me not as big of a community poor web service supportis there anything else i should look into is my choice of yii over the other frameworks ok for a primarily ajaxbased web appbara,"['php', 'jquery']" +29359,minwidth and maxwdith are ignored when element has thisplaytablecell i am trying to do simple fluid layout using css tables techniqe but there is one big flaw that i have found in it minwidth and maxwidth are ignored on elements with tablecell thisplay do you know any workaround that would allow me to specify how far sidebar element can stretch in the following examplexhtmldiv idwrapper div idmain div div idsidebar divdivcsswrapper thisplay tablerowbordercollapse collapse main thisplay tablecell sidebar thisplay tablecell width 30 minwidth 100px does not work maxwidth 310px does not work,['css'] +29362,how to print a list in python nicely in php i can do thisecho preprint rarrayecho prein python i currently just do thisprint the listhowever this will cause a big jumbo of data is there any way to print it nicely into a readable tree with indents,['python'] +29392,filecreatenewfile thowing ioexception no such file or directory i have a method that writes to a log file if the file exists it should append to it if not then i want it to create a new fileif fileexists filecreatenewfile systemerrprintlnerror with output file outfile ncannot create new file continuei have that to check that a file can be created file is a javaiofile object createnewfile is throwing an ioexception no such file or directory this method has been working perfectly since i wrote it a few weeks ago and has only recently starting doing this although i do not know what i could have changed i have checked the directory exists and i have write permissions for it but then i thought it should just return false if it cannot make the file for any reasonis there anything that i am missing to get this working,['java'] +29401,how to enumerate audio out devices in c i would like to know how to get a list of the installed audio out devices waveout on a machineos windows xp vista 7framework net 35language cwhen iterating through this list i would like to get information like identifier manufacturer per deviceany hints,['c#'] +29412,how do i use filesystem functions in php using utf8 strings i cannot use mkdir to create folders with utf8 charactersphpdir name depa3sitomkdirdir name but when i browse this folder in windows explorer the folder name looks like thisdepaa3sitowhat should i do,['php'] +29415,unsupported majorminor version 490 hi i am getting this exception when ever i am trying to login to the applicationjavaxservletservletexception comsunorgapachexalaninternalxsltctraxtransformerfactoryimpl unsupported majorminor version 490can anybody help,['java'] +29416,calculating the difference in months between two dates in cnet timespan has totaldays totalminutes etc but i cannot figure out a formula for total months difference variable days per month and leap years keep throwing me off how can i get totalmonthsedit sorry for not being more clear i know i cannot actually get this from timespan but i thought using totaldays and totalminutes would be a good example to express what i was looking for except i am trying to get total monthsexample dec 25 2009 oct 6 2009 2 totalmonths oct 6th to nov 5th equals 0 months on nov 6th 1 month on dec 6th 2 months,"['c#', '.net']" +29439,nstimezone what is the difference between localtimezone and systemtimezone under nstimezone class there is both localtimezone and systemtimezone i did a test on iphone simulator both return nstimezone object indicating the same timezone what is the difference which one i should use to find out the timezone setting of the iphone thanksmy testnsloglocal time zone nstimezone localtimezone namenslogsystem time zone nstimezone systemtimezone name,"['objective-c', 'iphone']" +29446,python 31 rss parser anyone know of a good feed parser for python 31i was using feedparser for 25 but it does not seem to be ported to 31 yet and it is apparently more complicated than just running 2to3py on itany help,['python'] +29463,determining maximum possible alignment in c is there any portable way to determine what the maximum possible alignment for any type isfor example on x86 sse instructions require 16byte alignment but as far as i am aware no instructions require more than that so any type can be safely stored into a 16byte aligned buffer i need to create a buffer such as a char array where i can write objects of arbitrary types and so i need to be able to rely on the beginning of the buffer to be alignedif all else fails i know that allocating a char array with new is guaranteed to have maximum alignment but with the tr1c0x templates alignment of and aligned storage i am wondering if it would be possible to create the buffer inplace in my buffer class rather than requiring the extra pointer indirection of a dynamically allocated arrayideasi realize there are plenty of options for determining the max alignment for a bounded set of types a union or just alignment of from tr1 but my problem is that the set of types is unbounded i do not know in advance which objects must be stored into the buffer,['c++'] +29466,how can i write to an excel spreadsheet using linq i am writing an app where i need to retrieve some rows from a db and dump them into an excel spreadsheet i am using linq to retrieve these rows is it possible to dump these rows directly into their counterparts in the excel sheet where one cell in excel corresponds to one cell from the db,['c#'] +29477,how to avoid dom parsing adding html doctype and tags string some photosbr span classnaslov slikephoto by ile img 167601spanbr span classnaslov slikephoto by ile img 169901spanbr span classnaslov slikephoto by ile img 169701spanbr span classnaslov slikephoto by ile img 169501spanbr dom new domdocument domloadhtmlstring dompreservewhitespace false elements domgetelementsbytagnamespan spans array foreachelements as span spans span foreachspans as span spanparentnoderemovechildspan echo domsavehtmli am using this code to parse strings when string is returned by this function it has some added tagsdoctype html public w3cdtd html 40 transitionalen htmlbodypsome photosbrbrbrbrbrpbodyhtmlis there any way to avoid this and to have clean string returned this input string is just for example in usage it can be any html string,['php'] +29481,how to implement enum like functionality in php how can enumlike functionality as provided in java and other high level languages be used in php i know php does not allow you to create enums currently but whats the closest one could get,['php'] +29482,why does shadowed variable evaluate to undefined when defined in outside scope consider the following piece of code htmlheadheadbody script typetextjavascript var outside scope outside scope function f1 alertoutside scope f1 scriptbodyhtmlthe output for this code is that the alert box thisplays the message outsidescope but if i slightly modify the code as htmlheadheadbody script typetextjavascript var outside scope outside scope function f1 alertoutside scope var outside scope inside scope f1 scriptbodyhtmlthe alert box thisplays the message undefined i could haveunderstood the logic if it thisplays undefined in both the cases but thatis not happening it thisplays undefined only in the second case why is thisthanks in advance for your help,['javascript'] +29489,split large file without copy questionare there windows api calls perhaps ntfs only which allows one to split a very large file into many others without actually copying any data in other words specify the logical breakpoints between joined files with file names and sizesexamples setfilevaliddata ntsetinformationfilescenarioi need to programatically thistributecopy 10gb of files from a nonlocal drive including network usb and dvd drives this is made up of over 10 individual files with median size about 16kbytes but joined into 2gb chunks however using simple filestream apis 64kb buffer to extract files from the chunks on nonlocal drives to individual files on a local hard drive seems to be limited on my machine to about 4mbs whereas copying the entire chunks using explorer occurs at over 80mbs it seems logical to copy entire chunks but give windows enough info to logically split the files which theoretically should be able to happen very very fast does not the vista install do something like this,"['c++', 'c']" +29491,how to print a nsinteger value from an nsmanagedobject using nslog when i try to print an integer value to the console that is retrieved from an nsmanagedobject it thisplays a 6 or 8 digit value the object id however if i use the debugger print description to console is shows up as the single digit value i expectfor example i assign the object sequence to an nsinteger and then thisplay using an nslog format stringmyprocess myprocess array objectatindexinsinteger sequence nsnumber numberwithintegernsintegermyprocesequence intvaluenslogsequence dmyprocesequenceconsole output is20091006 161105871 myprocess3318520b sequence 565256but when i try print to console from the debugger i see the value 1mystoryimage 0x3f59a80 entity myobject id 0x3f2d540 xcoredataff21959a 4b674587a25f66a7b8139dfamyprocessp2 data sequence 1xcoredataff21959a4b674587a25f66a7b8139dfamyprocessp1your help is appreciated,"['objective-c', 'iphone']" +29505,do you have to release iboulets in dealloc do you have to release iboulets in dealloc i am not sure on this one because i did not do the alloc and typically you only release for something you called alloc on anyone know,['iphone'] +29517,mvc and jquery best pratice for retreiving form data i have some jquery that uses ajax to send information back to my controler to be processedi am doing it like thisdefine my controlshtmltextboxpname modelpname new id pname get the values from my controlsvar param1 pnameval define the return url is this how to send info back var url urlcontentportsaverowajax id id param1 param1 param2 param2 param3 param3 param4 param4 param5 param5 ajax url url success functionhtml alertsuccess my c code that processes the request public void saverowajaxstring param1 is this the best way of doing it with mvcit seems a bit messy when i am contructing the url to post back to the server,"['c#', 'jquery']" +29526,length of an array in objective c i have not found answer in any of the questions askedi am passing an integer array to a functionnow i want to traverse through the arraybut as things worked in cc by simple using arraynamelength which gave the number of elements in array what is the way to find thatnsarrayobject length works for nsarray type but i want it for int not even xyz count worksso want another way to find that out,['objective-c'] +29539,how do i change my float into a two decimal number with a comma as a decimal point separator in python i have a float 123how do i change it into a two decimal number with a comma as a decimal point separator eg 123,['python'] +29547,how do i recursively create a folder in win32 i am trying to create a function that takes the name of a directory cfoobar or foobarbaz or someserverfoobar and creates directories as necessary so that the whole path is createdi am attempting a pretty naive implementation of this myself and it seems to be a string processing nightmare there is vs there is the special case of network shares which begin with also you cannot attempt to mkdir the first two levels of the path which are machine name and share name and there is type nonsense that can exist in a pathdoes there exist a simple way to do this in c,['c++'] +29555,incrementally building a numpy array and measuring memory usage i have a series of large text files up to 1 gig that are output from an experiment that need to be analysed in python they would be best loaded into a 2d numpy array which presents the first questionas the number of rows is unknown at the beginning of the loading how cana very large numpy array be most efficiently built row by rowsimply adding the row to the array would be inefficient in memory terms as two large arrays would momentarily coexist the same problem would seem to be occur if you use numpyappend the stack functions are promising but ideally i would want to grow the array in placethis leads to the second questionwhat is the best way to observe the memory usage of a python program that heavilyuses numpy arraysto study the above problem i have used the usual memory profiling tools heapy and pympler but am only getting the size of the outer array objects 80 bytes and not the data they are containing asides from a crude measuring of how much memory the python process is using how can i get at the full size of the arrays as they growlocal details osx 106 python 26 but general solutions are welcome,['python'] +29558,aspnet mvc project not supported by this installation i can create new mvc projects and they work and run however trying to open an existing project is not working at alli tried the following changing the project type toprojecttypeguidsf85e285da4e041529332ab1d724d3325349c585165df11da9384065b846f21fae04ec0301f11d3bf4b00c04f79efbcprojecttypeguidsthis worked on migrating a project from aspnet mvc preview 1 to preview 2 btwchanged the reference toreference includesystemwebmvc version20 cultureneutral publickeytoken31bf3856ad364e35 processorarchitecturemsil specificversionfalsespecificversion referencei tool this from a new project i created so i know that should be ok i even hardcoded the path to the same resultstill i get the dreaded the project file csproj cannot be opened the project type is not supported by this installationi also tried devenv setup and installing the sp1 for visual studiothe project i m trying to open is this one a devexpress sample of a grid working on aspnet mvc,['.net'] +29564,how to measure desktop applicaton usage by users i have wrote a app in c net 35 people download it and use i would like to know how many users do this and how many installed it how to do this,"['c#', '.net']" +29565,raise an error manually in tsql to jump to begin catch block is it possible to raise an error in a stored procedure manually to stop execution and jump to begin catch block some analog of throw new exception in chere is my stored procedures bodybegin trybegin tran do somethingif foobar is null here i want to raise an error to rollback transaction do something nextcommit tranend trybegin catch if trancount 0 rollback tran end catchi know one way select 10 but it is awful,['sql'] +29566,how to extend a class from an initializer and have it reload in development environment i am extending a class which is in a plugin by including a module this is done in an initializer require qwertycoreuserusersend include qwertycoreextensionsuserhowever in development before every request and after reload is called in the console all models are reloaded but because the initializers are not run again the module is not included leaving a model with missing partsbecause the model is in a plugin it does not seem wise to include code directly in the class which would be the usual approach for now i have simply added a before filter which includes the module if in development environment but i have copypasted and have duplicate code in the initializer and application controller class extensions in initalizers are overwrittern each request def development loading if rails env development usersend include qwertycoreextensionsuser end endis there a better wayas a side note the plugin is mine so i could add code in to it but the extensions held in the module may not always be present,"['ruby-on-rails', 'ruby']" +29571,how to design a cross client browser compatible email what are the proper practices in designing an email with a reasonable expectation that it will show up correctly for outlook 2003 2007 and in a webmail client i am subscribed to various email newletters and have viewed the source on them and have seen some of them have 20 lines of htmlcss along with if statements i have never seen before i assume related to determining versions of outlookis there a tool either free or commercial that can be used to create the markup is there a standard pattern on how to apply these huge stylesheets i have seen,"['html', 'css']" +29590,whats a good use case for net 40 expression trees this one was inspired by my languageguru coworker who cannot seem to find a good use for them and after a few lame attempts of my own i would have to agree now i know these concepts tend to flow a lot more easily once you get some good practical reasons down at the moment it seems as though its only purpose is to allow you to write a linq provideris that it is there any other benefits to this,['.net'] +29592,which iomanip manipulators are sticky i recently had a problem creating a stringstream due to the fact that i incorrectly assumed stdsetw would affect the stringstream for every insertion until i changed it explicitly however it is always unset after the insertion with timestruct with value of oct 7 904 amstdstringstream sfill0 setfiosright iosadjustfieldss setw2 timestructtm mdayss timestructtm hourss timestructtm minstdstring filingtime str bad 0794so i have a number of questionswhy is setw this way are any other manipulators this way is there a difference in behavior between stdios basewidth and stdsetw finally is there an online reference that clearly documents this behavior my vendor documentation ms visual studio 2005 does not seem to clearly show this,['c++'] +29602,programatically setting a png to a picture control in win32 apis i use visual studio 2008 i have the png file loaded in the resource view assigned it idb bang pngthe picture control is called idc static15i am having trouble trying to get the png loaded into the picture controllresult callback dialogprochwnd hdlg uint message wparam wparam lparam lparam way of loading a bmp with a mask perhaps or a png file programaticallystatic hbrush hbrushstatichbitmap hbmp loadbitmaphdlgmakeintresourceidb bang pngswitchmessagecase wm initdialogcheckdlgbuttonhdlg idc check falseenablewindowgetdlgitemhdlg idok false bitmap version is idb bang png is at idb bang png idc static15 is the picture framehwnd item getdlgitemhdlgidc static15sendmessageitemstm setimageimage bitmaplparamhbmpreturn true snipi am rather naive when it comes to win32gui development doing a quick project and got stuck her any help is appreciated,['c'] +29610,is there a production grade simpledb net library here you will find all the simpledb code samples on the aws pagehere you will find a vbnet simpledb libraryis there a production grade simpledb library preferable built in c if not may i use the vbnet library on a c project as a reference,['c#'] +29612,oracle analytic function for min value in grouping i am new to working with analytic functions dept emp salary 10 mary 10 10 john 20 10 scott 30 20 bob 10 20 betty 20 30 alan 10 30 tom 20 30 jeff 30i want the department and employee with minimum salaryresults should look likedept emp salary 10 mary 10 20 bob 10 30 alan 10edit heres the sql i have but of course it does not work as it wants staff in the group by clause as wellselect dept emp minsalary keep dense rank first order by salaryfrom mytablegroup by dept,['sql'] +29626,best aspect oriented framework for features build performances in net in various projects i worked with we had to use some aop or dependency injection frameworkwe used enterprise library unity and postsharp for now postsharp is my best choice when it comes to the flexibiity i get over how i generate my aspectsthe only problem is the build time required once postsharp is installed my developpers do not like to pay the time tax even in regard of all the godness comming from postsharpso my question is what aop framework would you recommand for fast build time and great fonctionnality thanks your answers are greatly appreciatedpatrick,"['c#', '.net']" +29631,randomize a sequence of div elements with jquery i am trying to do my frist steps with jquery but i have some trouble to understand how to find a list of child elements from a div parent element i am used to work with actionscript 2 and actionscript 3 so i could mistake some concept like what is the better way to randomize a sequence of div elements with jqueryi have this simple portion of html codediv classband div classmember ul lijohnli lilennonli ul div div classmember ul lipaulli limccartneyli ul div div classmember ul ligeorgeli liharrisonli ul div div classmember ul liringoli listarrli ul divdivi have attempted some way to do that like map member divs in one array and then changing the sort order but without successfunction setarrayelements element parent var arr alert element parent0innerhtml for var i 0 i element parentchildrenlength i arrpush element parentiinnerhtml setarrayelementsbandwhen i attempted to alert element parent0 i thought to get the first child of my member list of divs but it is notif i make an alert with element parent0innerhtml i see thatdiv classmember ul lijohnli lilennonli uldivdiv classmember ul lipaulli limccartneyli uldivdiv classmember ul ligeorgeli liharrisonli uldivdiv classmember ul liringoli listarrli uldivwhyhow can i do to get exactly one of the members like thisdiv classmember ul lipaulli limccartneyli uldivi am sure this should be easy but i just do not know howplease helpthanksvittorioeditthanks for the fastness and this various ways to get the selected children i will take a note of these ways for the futurei tried this methods but it seems i could not get the entire div please tellme if i mistake something it could be too much possiblei shoud get this contentdiv classmember ul liringoli listarrli uldivbut with one of this methods like divband divmembereq2 or the other useful ways i get thisalert divband divmember0 resultul liringoli listarrliulso is there a way to get the member div container too in my node,"['jquery', 'html']" +29633,in php when should i use static methods vs abstract classes i am under the interpretation that if i need to access a method statically i should make the class abstract only if i will never need it instantiated is that true,['php'] +29634,python how to show results on a web page most likely it is a dumb question for those who knows the answer but i am a beginner and here it goesi have a python script which i run in a commandline with some parameter and it prints me some results let us say results are some html codei never done any python programming for web and could not figure it out i need to have a page ok i know how to upload files to a server apache is running python is installed on the server with an edit field which will accept that parameter and submit button and i need it to print the results on a web page after the user submitted a proper parameter or show any output that in a commandline situation are printedi have read dive into pythons chapters about html processing and http web services but they do not describe what i am looking forif the answer is not short i would very much appreciate links to the more relevant stuff to read or maybe the key words to google for it,['python'] +29638,use different python version with virtualenv i have a debian system currently running with python 254 i got virtualenv properly installed everything is working fine is there a possibility that i can use a virtualenv with a different version of pythoni compiled python 262 and would like to use it with some virtualenv is it enough to overwrite the binary file or do i have to change something in respect to the libraries,['python'] +29648,are there any numeric suffixes for specifying a double void foofloat a 1void foodouble a 2 overloadedfoo10f calls function 1foo10 double numeric suffix calls function 2if not is a cast the only way this can be achieved i am mainly interested inensuring double precision math during certain operations etculong jdouble vj some valueifj0ul v 10 j if 10 is set as a float by the compiler then could it be likely we lose some precision here if a double would allow for more precision is a cast the only means of ensuring double precisionother tips on allowing the compiler to autodetermine the types during an operation would be helpful,['c++'] +29651,xmlserializer performance issue when specifying xmlrootattribute i am currently having a really weird issue and i cannot seem to figure out how to resolve iti have got a fairly complex type which i am trying to serialize using the xmlserializer class this actually functions fine and the type serializes properly but seems to take a very long time in doing so around 5 seconds depending on the data in the objectafter a bit of profiling i have narrowed the issue down bizarrely to specifying an xmlrootattribute when calling xmlserializerserialize i do this to change the name of a collection being serialized from arrayof to something a bit more meaningful once i remove the parameter the operation is almost instantany thoughts or suggestions would be excellent as i am entirely stumped on this one,"['c#', '.net']" +29655,phps magic method call on subclasses my situation is best described with a bit of codeclass foo function bar echo called foobar class subfoo extends foo function callfunc if func bar echo intercepted bar subfoo new subfoo what actually happenssubfoobar called foobar what would be nicesubfoobar intercepted bari know i can get this to work by redefining bar and all the other relevant methods in the subclass but for my purposes it would be nice if the call function could handle them it would just make things a lot neater and more manageableis this possible in php,['php'] +29656,in objective c can you check if an object has a particular property or message i wat to do something like thisif viewcontrollermapview viewcontrollermapview somemethodhowever if mapview is not a class variable this crashes how do i check if mapview exists,['objective-c'] +29662,jquery event when select option whats the event to bind for when a select form is selectedi have something like thisselect idlistoption value1option aoptionoption value2option boptionoption value3option coptionselectwhen option b is selected i want some function to runso what do i bind listbind function how do i check if it is option b that is selected hereblah blahthanks,"['javascript', 'jquery']" +29663,how are people handling content management system production staging i have been dipping my toe into web development technologies for fun ya i should get out more and am a little shocked at the lack of clear support for production staging ie development testing performance and production environments actually support is not the word content management systems seem to actively work against efforts to allow for clean stagingcurrently i am using drupal i have had a very hard time finding how the community solves this problem most of the posts i have seen recommend reproducing the steps done in development on the production system reading this actually shortened my life a small bit i also hear of pushing production data back to the developers so they can add incremental features this cannot be the way to go what if the client does not want you pulling their data back to your development environmentso finally my question how are you managing real world production staging issues for a cms i come from a background where pushing to production feels like sending people to the moon so i may need to relax a little bit however i am still interested answers that involve source control allow for production rollback and testing,['php'] +29665,convert graphics object to bitmap object how can i convert graphics object to bitmap object using c,['c#'] +29675,how do i create a mac installer for my java application i have created an executable jar file for my java application if i doubleclick then it works fine but i want to create installer for mac os because i cannot give a jar file to my users any suggestions,['java'] +29685,jquery click event handler is called twice for a checkbox i have a problem with the following code in an aspx pagescript typetextjavascriptdocumentreadyfunction testclickfunction alertclick scriptaspcheckbox runatserver textcheckbox xyz cssclasstest idcb1 in the browser ff35 ie8 i have the following problemif i click the checkbox the small square it works as expectedif i click the checkboxs text checkbox xyz then the click event is fired twice and the alert is shown twicei guess this has to do with the way the checkbox is rendered to html which is like thisspan classtest input idctl00 c1 cb1 typecheckbox namectl00c1cb1 checkedchecked label forctl00 c1 cb1checkbox xyzlabelspanhow do i correctly setup the click event handler to prevent it from being called twice,"['asp.net', 'jquery']" +29688,link order in css whats the correct order of styling the a element link visited hover active all are confusing by providing different combination like lvha lahv can anybody specify the correct ordering,"['html', 'css']" +29691,force a page refresh using javascript in firefox i have a simple request to refresh a page using a javascript code belowfunction tb closerefresh windowlocationreloadtruethis works fine in ie but firefox just gets the cached version and needs the user to press f5 to get the latest version of the pagei have added the meta tagmeta httpequivpragma contentnocachebut this does not helpany ideas,['javascript'] +29695,javascript controlling the insertion point for documentwrite i would like to create a page that runs a 3rd party script that includes documentwrite after the dom was already fully loadedmy page is not xhtml my problem is that the documentwrite is overwriting my own page which is what it does once the dom was loadedi tried overriding the documentwrite function in a way similiar to but that does not cover cases where the documentwrite contains partial tagsan example that would break the above code isdocumentwritedivdocumentwritedone heredocumentwritedivis there some way to modify the documentwrite insertion point through javascript does anyone have a better idea how to do this,['javascript'] +29726,difference between malloc and calloc what is the difference between doingptr char malloc maxelems sizeofchar orptr char calloc maxelems sizeofcharwhen is it a good idea to use calloc over malloc or vice versa,['c'] +29731,how can i theme the template for edit or add a node for a specific content type i want to theme the template for edit or add a node for a specific content typefor example to theme all the content type forms i use the file pagenodeaddedittplphp depending what i need to do add or editbut i did not found the template name for a custom node type for example productsi need to theme only for products but not for the other content typesi have tried with pagenodeeditproducttplphp and pagenodeproductedittplphp but no luck,['php'] +29743,under what circumstances would you want rails to be set not to reconnect to mysql i am experiencing a few errors on a rails app along the lines ofactiverecordstatementinvalid mysqlerror lost connection to mysql server during query select from actions where fooid 16what appears to be happening is that mysql connection is being closed after a timeout and rails is not noticing until it is too latethe remedies i find appear to be to set the reconnect flag to true in databaseyaml or for any database action adding some code like sodef some database operation begin accountfind1 or some other database operations here rescue activerecordstatementinvalid activerecordbaseconnectionreconnect unless already retried already retried true retry end raise else already retried false endendendi am listing this option over this one visible here because this option is apparently unsafe for transactionsactiverecordconnectionadaptersmysqladaptermodule eval do def execute with retry oncesql name nil retried false begin execute without retry oncesql name rescue activerecordstatementinvalid exception activerecordbaseloggerinfo exception retried retried our database connection has gone away reconnect and retry this method reconnect unless retried retried true retry end end end alias method chain execute retry onceendof the options to avoid this annoying error the reconnect option in the yaml file seems by the far the tidiest option but i am curious why you wouldnt set this value to be true by default in your databasei would rather not solve one problem by causing a load of others further down the linethanks,"['mysql', 'ruby-on-rails']" +29744,ruby is there a function to easily find the first number in a string for example if i typed ds35bdg56 the function would return 35 is there a premade function for something like that or do i need to iterate through the string find the first number and see how long it goes and then return that,['ruby'] +29757,is it possible to extend a class dynamically i have a class which i need to use to extend different classes up to hundreds depending on criteria is there a way in php to extend a class by a dynamic class namei assume it would require a method to specify extension with instantiationideas,['php'] +29775,html5 cache manifest in a uiwebview i would like to be able to use the html5 cache manifest to store images locally on an iphone that is visiting the page via a uiwebview within an appi have set up a sample that i think conforms to the specs and appears to work in safari 4 and mobile safari but not in my apps uiwebviewthe sample html is set up at this is very similar to the sample provided in the html5 draft standardhere is the entire nontemplate code of the sample app i am using for testing voidapplicationdidfinishlaunchinguiapplication application i thought this might help i do not see any difference though nsurlcache cache nsurlcache sharedurlcache cache setthiskcapacity5121024 cgrect frame uiscreen mainscreen applicationframe uiwebview webview uiwebview alloc initwithframeframe window addsubviewwebview nsstring urlstring nsurl url nsurl urlwithstringurlstring nsurlrequest request nsurlrequest requestwithurlurl webview loadrequestrequest window makekeyandvisiblei have reviewed a few related questions on stackoverflow but they do not seem to provide info to solve this for example i am pretty sure the files i am trying to cache are not too large since they are just a couple small text files way 25kany ideas for how to get this to work,['iphone'] +29783,check if a string has at least one number in it using linq i would like to know what the easiest and shortest linq query is to return true if a string contains any number character in it,['c#'] +29792,how to write good unit tests could anyone suggest books or materials to learn unit test some people consider codes without unit tests as legacy codes nowadays test driven development is the approach for managing big software projects with ease i like c a lot i learnt it on my own without any formal education i never looked into unit test before so feel left out i think unit tests are important and would be helpful in the long run i would appreciate any help on this topic my main points of concern arewhat is a unit test is it a comprehensive list of test cases which should be analyzed so lets us a say i have a class called complex numbers with some methods in it lets says finding conjugate an overloaded assignment operator and an overloaded multiplication operator what should be typical test cases for such a class is there any methodology for selecting test casesare there any frameworks which can create unit tests for me or i have to write my own class for tests i see an option of test in visual studio 2008 but never got it workingwhat is the criteria for units tests should there be a unit test for each and every function in a class does it make sense to have unit tests for each and every class,['c++'] +29793,jqgrid how to remove the page selection on the pager but keep the buttons i want to remove the paging buttons on the grid but i want to keep the add edit refresh etc buttons on the bottom left i do not want the pager there because i will be thisplaying all records in this particular grid implementationi want to keep what is in green but remove what is in redcurrently my solution is to empty out the center of the grids navigationpager centeremptybut this means that the pager renders to the page and then gets emptied i am wondering if i can just prevent it from even being rendered in the first place,"['javascript', 'jquery']" +29795,multiple group by and sum linq i have a products sales table that looks like thissaledate prod qty102209 soap 10092209 pills 05092509 soap 06092509 pills 15i need to make the sum of each month so the final table would look like thissaledate prod qty1009 soap 100909 soap 060909 pills 20can i do this with linq,['c#'] +29797,how do you get the checked value of aspradiobutton with jquery i need to do something like thisaspradiobutton idrbdate runatserver textdate groupnamegrpprimary and be able to check the value of the radio buttons checked value in jquery but my attempts like these do not return truefalseif namerbdateattrcheckedif namerbdateattrcheckedvalif namerbdatecheckedvala little help,"['c#', 'asp.net', 'jquery']" +29802,is this lockfree net queue thread safe my question is is the class included below for a singlereader singlewriter queue class threadsafe this kind of queue is called lockfree even if it will block if the queue is filled the data structure was inspired by marc gravells implementation of a blocking queue here at stackoverflowthe point of the structure is to allow a single thread to write data to the buffer and another thread to read data all of this needs to happen as quickly as possible a similar data structure is described in an article at ddj by herb sutter except the implementation is in c another difference is that i use a vanilla linked list i use a linked list of arraysrather than just including a snippet of code i include the whole thing with comment with a permissive open source license mit license 10 in case anyone finds it useful and wants to use it asis or modified this is related to other questions asked on stack overflow of how to create a blocking concurrent queues see creating a blockinq queue in net and threadsafe blocking queue implementation in net here is the codeusing systemusing systemcollectionsgenericusing systemthreadingusing systemdiagnosticsnamespace collectionsandbox this is a single reader singler writer buffered queue implemented with almost no locks this implementation will block only if filled up the implementation is a linkedlist of arrays it was inspired by the desire to create a nonblocking version of the blocking queue implementation in c by marc gravell class simplesharedqueuet istreambuffert used to signal things are no longer full manualresetevent canwrite new manualreseteventtrue this is the size of a buffer const int buffer size 512 this is the maximum number of nodes const int max node count 100 this marks the location to write new data to cursor adder this marks the location to read new data from cursor remover indicates that no more data is going to be written to the node public bool completed false a node is an array of data items a pointer to the next item and in index of the number of occupied items class node where the data is stored public t data new tbuffer size the number of data items currently stored in the node public node next the number of data items currently stored in the node public int count default constructor only used for first node public node count 0 only ever called by the writer to add new nodes to the scene public nodet x node prev data0 x count 1 the previous node has to be safely updated to point to this node a reader could looking at the point while we set it so this should be atomic interlockedexchangeref prevnext this this is used to point to a location within a single node and can perform reads or writers one cursor will only ever read and another cursor will only ever write class cursor points to the parent queue public simplesharedqueuet q the current node public node node for a writer this points to the position that the next item will be written to for a reader this points to the position that the next item will be read from public int current 0 creates a new cursor pointing to the node public cursorsimplesharedqueuet q node node thisq q thisnode node used to push more data onto the queue public void writet x traceassertcurrent nodecount check whether we are at the node limit and are going to need to allocate a new buffer if current buffer size check if the queue is full if qisfull signal the canwrite event to false qcanwritereset wait until the canwrite event is signaled qcanwritewaitone create a new node node new nodex node current 1 else if the implementation is correct then the reader will never try to access this array location while we set it this is because of the invariant that if reader and writer are at the same node readercurrent nodecount and writercurrent nodecount nodedatacurrent x we have to use interlocked to assure that we incremeent the count atomicalluy because the reader could be reading it interlockedincrementref nodecount pulls data from the queue returns false only if there public bool readref t x while true if current nodecount x nodedatacurrent return true else if current buffer size nodenext null move the current node to the next one we know it is safe to do so the old node will have no more references to it it and will be deleted by the garbage collector node nodenext if there is a writer thread waiting on the queue then release it conceptually there is a if qisfull but we cannot place it because that would lead to a race condition qcanwriteset point to the first spot current 0 one of the invariants is that every node created after the first will have at least one item so the following call is safe x nodedatacurrent return true if we get here we have read the most recently added data we then check to see if the writer has finished producing data if qcompleted return false if we get here there is no data waiting and no flagging of the completed thread wait a millisecond the system will also context switch this will allow the writing thread some additional resources to pump out more data especially if it iself is multithreaded threadsleep1 returns the number of nodes currently used private int nodecount get int result 0 node cur null interlockedexchangenoderef cur removernode counts all nodes from the remover to the adder not efficient but this is not called often while cur null result interlockedexchangenoderef cur curnext return result construct the queue public simplesharedqueue node root new node adder new cursorthis root remover new cursorthis root indicate to the reader that no more data is going to be written public void markcompleted completed true read the next piece of data returns false if there is no more data public bool readref t x return removerreadref x writes more data public void writet x adderwritex tells us if there are too many nodes and cannot add anymore private bool isfull return nodecount max node count,"['c#', '.net']" +29803,stl priority queue on custom class i am having a lot of trouble getting my priority queue to recognize which parameter it should sort by i have overloaded the less than operator in my custom class but it does not seem to use it heres the relevant codenodehclass node public node node bool operatornode anodenodecppinclude nodehbool nodeoperatornode anode return thisgettotalcost anodegettotalcostgettotalcost returns an intmaincpriority queuenode vectornodelessvectornodevalue type nodestocheckwhat am i missing andor doing wrong,['c++'] +29806,how to install a windows service developed in net 35 i have developed a windows service using visual studio 2008 i want to install that service in a machine where visual studio is not installed but net 35 is installedgenerally installutilexe shall be used for installing a windows service but the installutilexe utility is not available in net 35 when i tried installing that service using net 20 the service is getting thisplayed in the list of services but when starting the service windows service error 1053 is coming how we can avoid this problem and successfully install the service,"['c#', '.net']" +29811,what is the difference between web farm and web garden what is the difference between web farm and web garden please help,['asp.net'] +29816,how do i have plugin architecture in ruby on rails i have to built a social networking site on ruby on rails the features in the site may change from time to time so we will need to addremove features with ease moreover we may be building another social networking site due to these reasons we are thinking to build a basic framework for social networking sites in ror with the feature to install or uninstall extensions to the frameworki worked previously in joomla cms and its architecture for addingremoving extensions is kind of what i am looking at in a joomla installation there is usually an admin side from which you can addremovecustomize extensionsi am new to ror and finding it little difficult to decide how to do this any help will be appreciated,['ruby-on-rails'] +29821,ascii graphics library is there a platformindependent cc library that can draw simple graphics in pure ascii in a console program for example very roughly i could call a function in the library like rectangle3 6 to get the following output ultimately i would love to be able to plot simple graphs based on input data tables like and does anyone know if there is a way to specifically render data plotsgraphs in ascii or utf8,"['c++', 'c']" +29822,do something every 5 seconds and the code to stop it jquery how can i repeat a function dosomething every 5 secondsi also need code that will make it stop doing itand code to onthefly adjust the frequency,"['javascript', 'jquery']" +29823,margin while printing html page i am using a separate stylesheet for printing is it possible to set right and left margin in the stylesheet which set the print margin ie margin on paperthanks,"['html', 'css']" +29826,what is this type of method overriding called in java i am relatively new to java and i am using a new api i came across this method override and i am not sure what this is calledpublic void examplemethod button loginbutton new buttonlogin public void onsubmit submit code here from what i understand this is overriding the onsubmit method of the button class i have never come across this type of overriding before is there a specific name for it i want to read up more about it but i cannot find it all my searches so far result to regular method overriding by creating a new class which is what i am already familiar withi would appreciate if someone could point me in the right directionthanks,['java'] +29827,how can i call c functions from within ruby i am an experienced cc developer but i am a novice in rubyhow can i call a c function from with in ruby,"['c++', 'ruby']" +29841,a better boost reference the thing that really turns me off about boost is their documentation what i need is a good reference and instead of explaining what a good reference is to me i would give example javasuncomjavase6docsapiyes i love it it is also thiscppreferencecomwikistlvectorstarton the other hand what i find about boost is something like thisbasically some long page of text almost no formatting some bold text here and there and hopefully some links between elements not to mention that smart ptr is one of the better documented librariesif you do not find the difference between this and the above examples please stop reading and ignore this post do not get me wrong i write c and i use boost at my firm we use at least 4 of their libraries still each and every time i need to check a method prototype for instance it gets me out of my nerves scrolling through their essays and yes i know that boost is a collaborative project and that different libraries are developed by different teamsso does any of you share my thisappointment with boosts reference and do you know some better site documenting the boost libraries,['c++'] +29854,comprehensions in python and javascript are only very basic looking at comprehensions in python and javascript so far i cannot see some of the main features that i consider most powerful in comprehensions in languages like haskell do they allow things like multiple generators or are they just a basic mapfilter formif they do not allow multiple generators i find them quite thisappointing why have such things been left out,"['javascript', 'python']" +29860,force another programs standard output to be unbuffered using python a python script is controlling an external application on linux passing in input via a pipe to the external applications stdin and reading output via a pipe from the external applications stdout the problem is that writes to pipes are buffered by block and not by line and therefore delays occur before the controlling script receives data output by for example printf in the external applicationthe external application cannot be altered to add explicit fflush0 callshow can the pty module of the python standard library be used with the subprocess module to achieve this,['python'] +29874,iis session timeout vs aspnet session timeout in iis 6 and other versions too afaik there is a session timeout setting in properties home directory tab configuration button options tab looks like thisand in the aspnet webconfig there is a sessionstate setting looks like thissystemweb sessionstate timeout120 etc systemwebare they by any chance related do they set the same thing or different things,['asp.net'] +29876,is there a free python library for phone calling i am writting a small python script notify me when certain condition met i used smtplib which does the emailing for me but i also want the script to call my cell phone as welli cannot find a free library for phone callings does anyone know any,['python'] +29882,custom collection vs generic collection for public methods what are the recommendations for exposing a custom collection vs generic oneegpublic class imagecollection collectionimage public class product public imagecollection get setvspublic class product public collectionimage imagesget setwhat cases would you consider creating a custom collectionwhat are the pros and cons of each method,['c#'] +29893,python oneline for expression i am not sure if i need a lambda or something else but still i need the followingi have an array 12345 i need to put this array for instance into another array but write it all in one linefor item in array array2appenditemi know that this is completely possible to iterate through the items and make it oneline but googling and reading manuals did not help me that much if you can just give me a hint or name this thing so that i could find what that is i would really appreciate itupdate let us say this array2 some fancy expression that is going to get all the data from the first onethe example is not real i am just trying to iterate through different chunks of data but that is the best i could come up with,['python'] +29894,c code file extension cc vs cpp i have seen c code saved as both cc and cpp files is there a difference between the twothe google style guide seems to suggest cc but provides no explanationi am mainly concerned with programs on linux systems,['c++'] +29898,how to determine if a process id exists i am using c net 20 i need to determine if a pid exists i came up with the following codeprivate bool processexistsint iprocessid foreach process p in processgetprocesses if pid iprocessid return true return falseis there a better way to do this other than iterating all the processesthanks,"['c#', '.net']" +29904,how to setup a sophisticated java development infrastructure i am looking for a complete java development infrastructure with an integration ofan ide like eclipsea build system like mavena version control system like subversiona continuous integration server like hudsona repository manager like nexusan automated release plugin like maven release pluginfurther i would like to havea predefined multi component project structureand optionallyan issue manager like jiraan integration with an open source hoster like sourceforgeevaluating all these systems could take a long time making the setup of a running infrastructure a job of a month or longerat work i am ready to setup each system individually but for my private development at home i would like to have something like devware a development environment virtual appliance unfortunately i did not find a download link where everything is already installed and functionalso could you please give me some advice which combinations create a working infrastructure or even better where to find a preconfigured development infrastructureps i am not committed to any of the named products so feel free to suggest alternatives if they match better,['java'] +29907,convert datetime in gmt to est in javascript in javascript how can i convert datetime in gmt to est irrespective of user settings,['javascript'] +29908,searching for a objectguid in ad i am using the active directory explorer from mark russinovichit is a great tooli am using it to navigate active directory to make sure my program that uses directorysearcher from net returns correct datasomething happens though when i try to search inside my program with directorysearcher for objectguid if i pass in the actual guid as a string it does not return anything where as if i use active directory explorer when i addobjectguid with value f8d764ff9a6a418ea641b6f99661a8d5 its search clause becomesobjectguidffdd7f8j9a8eaa6ab6f996aa8d5how do i do this for directorysearcher in my program i am guessign it is an octet string thing but i cannot figure it out,['.net'] +29920,how to use both onclick and ondblclick on an element i have an element on my page that i need to attach onclick and ondblclick event handlers to when a single click happens it should do something different than a doubleclick when i first started trying to make this work my head started spinning obviously onclick will always fire when you doubleclick so i tried using a timeoutbased structure like thiswindowonload function var timer var el documentgetelementbyidtestbutton elonclick function timer settimeoutfunction alertsingle 150 elondblclick function cleartimeouttimer alertdouble but i got inconsistent results using ie8 it would work properly alot of times but sometimes i would get the single alert two timeshas anybody done this before is there a more effective way,['javascript'] +29924,check for the absence of puts in rspec i am using rspec for my test in a ruby project and i want to spec that my program should not output anything when the q option is used i triedkernelshould not receive putsthat did not result in a failed test when there was output to the consolehow do i verify the absents of text output,['ruby'] +29941,creating a favicon how can i create a favicon for my website,['html'] +29945,python 311 with enableshared will not build any extensions summary building python 31 on rhel 53 64 bit with enableshared fails to compile all extensions building normal works fine without any problemsplease note that this question may seem to blur the line between programming and system administration however i believe that because it has to deal directly with getting language support in place and it very much has to do with supporting the process of programming that i would crosspost it here also at thank youproblembuilding python 31 on rhel 53 64 bit with enableshared fails to compile all extensions building normal works fine without any problemsi can build python 31 just fine but when built as a shared library it emits many warnings see below and refuses to build any of the c based modules despite this failure i can still build mod wsgi 30c5 against it and run it under apache needless to say the functionality of python is greatly reducedinteresting to note that python 32a0 from svn compiles fine with enableshared and mod wsgi compiles fine against it but when starting apache i getcannot load etchttpdmodulesmod wsgiso into server etchttpdmodulesmod wsgiso undefined symbol pycobject fromvoidptrthe project that this is for is a longterm project so i am okay with alpha quality software if needed here are some more details on the problemhostdell poweredgeintel xenon rhel 53 64bitnothing specialbuildpython 311 source thistributionworks fine with configuredoes not work fine with configure enablesharedexport cflagsfpic has been donemake outputgcc pthread fnostrictaliasing dndebug g fwrapv o3 wall wstrictprototypes i iinclude iinclude fpic dpy build core c modules weakrefc o modules weakrefobuilding bz2 extensiongcc pthread fpic fnostrictaliasing dndebug g fwrapv o3 wall wstrictprototypes i iinclude iusrlocalinclude iinclude ihomebuildrpmbuildbuildpython311 c homebuildrpmbuildbuildpython311modulesbz2modulec o buildtemplinuxx86 6431homebuildrpmbuildbuildpython311modulesbz2moduleogcc pthread shared fnostrictaliasing dndebug g fwrapv o3 wall wstrictprototypes buildtemplinuxx86 6431homebuildrpmbuildbuildpython311modulesbz2moduleo lusrlocallib l lbz2 lpython31 o buildliblinuxx86 6431bz2sousrbinld usrlocalliblibpython31aabstracto relocation r x86 64 32 against a local symbol can not be used when making a shared object recompile with fpicfailed to build these modules bisect codecs cn codecs hk codecs iso2022 codecs jp codecs kr codecs tw collections csv ctypes ctypes test curses curses panel dbm elementtree gdbm hashlib heapq json lsprof multibytecodec multiprocessing pickle random socket sqlite3 ssl struct testcapi arrayatexit audioop binasciibz2 cmath cryptdatetime fcntl grpitertools math mmapnis operator ossaudiodevparser pyexpat readlineresource select spwdsyslog termios timeunicodedata zlib,['python'] +29958,how to assign a value to a tchar array i have a tchar array in my c code which i want to assign static strings to iti set an initial string to it viatchar myvariable260 textinitial valueeverything works fine on this however when i split it in two lines as intchar myvariable260myvariable textinitial valueit bugs and gives a compiler errorerror c2440 cannot convert from const char 14 to tchar 260should not the text function do exactly what i want here convert the given string to tchars why does it work when putting the two lines together what do i have to change in order to get it workingsome other confusing thing i have encounteredi have searched the internet for it and have seen that there are also t and text and t and text what are they for which of them should i use in what environment,['c++'] +29973,can c extension methods access private variables is it possible to access an objects private variables using an extension method,['c#'] +29975,how do i make my java application identify itself to oracle on connection when my application connects to an oracle database i want to be able to see by looking at the active sessions in the database that it is connected currently it identifies itself as jdbc thin client because that is the driver that i am using but other java based applications that i have are somehow able to set this value to something more meaningful like sql developer i thought it was a property of the connection or the oracledatasource but i have not managed to find one that does the trick is this possible in case it matters i am using java 15 with oracle 10g and the 10g thin driver,['java'] +29990,forcing a jquery ready block to run after all other ready blocks is it possible to have one jquery ready block executed after all others have done soi have this in my master page script typetextjavascript documentreadyfunction inputtypetextenabledfirst documentforms0focusselect scriptand this in one of my other pages script typetextjavascript documentreadyfunction textareamessagebodywysiwyg scriptthe problem i am seeing is that the first block is executed before the second block which is causing a problem with the tab key whats happening is that the keyboard focus goes to the address bar in my browser when i press the tab key i have changed the code slightly to have this in my master page script typetextjavascript documentreadyfunction var bodies textareamessagebody if bodieslength 0 bodieswysiwyg inputtypetextenabledfirst documentforms0focusselect scriptand do away with the other ready block completely doing that makes the tab key work properly and set the focus onto my textareai would rather not have page specific code in my master pageso is there a way to make my textbox focusing code run after the wysiwyg code,['jquery'] +30006,c equivalent of javatostring i would like to control what is written to a stream ie cout for an object of a custom class is that possible in c in java you could override the tostring method for similar purpose,['c++'] +30007,in which area is c mostly used i have been asked many times by my juniors about the areas in which c is widely used i usually answer operating systems are there any other areas where its extensively used,['c++'] +30011,cloning row or column vectors sometimes it is useful to clone a row or column vector to a matrix by cloning i mean converting a row vector such as123into a matrix123 123 123or a column vector such as1 2 3into1 2 3in matlab or octave this is done pretty easily x 123 a ones31 x a 1 2 3 1 2 3 1 2 3 b x ones13 b 1 1 1 2 2 2 3 3 3i want to repeat this in numpy but unsuccessfullyin 14 x array123in 14 ones31 xout14array 1 2 3 1 2 3 1 2 3 so far so goodin 16 xtranspose ones13out16 array 1 2 3 damn i end up with in 17 ones31 xtransposeout17array 1 1 1 2 2 2 3 3 3why was not the first method in16 working is there a way to achieve this task in python in a more elegant way,['python'] +30023,encoding an integer in 7bit format of c binaryreaderreadstring cs binaryreader has a function that according to msdn reads an integer encoded as seven bit integer and then reads a string with the length of this integeris there a clear documentation for the seven bit integer format i have a rough understanding that the msb or the lsb marks whether there are more bytes to read and the rest bits are the data but i will be glad for something more exacteven better is there a c implementation for reading and writing numbers in this format,"['c#', '.net']" +30034,detect chinese multibyte character in the string str this is a string containing a characters some more characters a aaooa12 how do i detect chinese characters from this string and print the part which starts with the first character and ends with it would be a characters some more characters thank you,['php'] +30041,get size of image without loading in to memory i have several png images eta but the format could also be jpeg or something else that i am going to thisplay in uitableviewcells right now in order to get the row heights i load in the images get their size properties and use that to figure out how high to make the rows calculating any necessary changes along the way since most of the images get resized before being thisplayed in order to speed things up and reduce memory usage i would like to be able to get size without loading the images is there a way to do thisnote i know that there are a number of shortcuts i could implement to eliminate this issue but for several reasons i cannot resize images in advance or collect the image sizes in advance forcing me to get this info at run time,['iphone'] +30044,when to release nsurlconnection object what is the correct point at which to release a nsurlconnection objectin my program i alloc a nsurlconnection and then initwithrequest to kick off asynchronously i am now responsible for releasing the object when do ican i release immediately if i am not using it again,['iphone'] +30059,help with error iso c forbids declaration of vector with no type as the title states i am not sure why i am getting this error i have put together a testcpp that is similar to this structure and it works fine also other than the vector problem there is the other problem about protected which is not even in the code i think protected is a macro so no telling whats there i am new to qt so i am likely doing it wrong that is certainly what the compilers suggestingin file included from drvcrystalfontzcpp8lcdtexth28 error iso c forbids declaration of vector with no typelcdtexth28 error expected before tokenlcdtexth30 error iso c forbids declaration of vector with no typelcdtexth30 error expected or before tokenlcdtexth46 error expected before protectedlcdtexth in constructor lcdtextlcdtextint int int int int int int qobjectlcdtexth33 error expected at end of inputscons drvcrystalfontzo error 1scons building terminated because of errorsheres the code i have numbered the lines noted in the errorifndef lcd text define lcd text include vectorinclude qobjectinclude lcdbasehinclude widgettexthinclude widgetbarhinclude widgethistogramhinclude widgeticonhinclude widgetbignumshinclude widgetgifhclass lcdtext public lcdbase public virtual qobject q object protected char layoutfb char thisplayfb int goto cost int chars int char0 int lrows int lcols int drows int dcols vectorvectorchar chars line 28 void textrealwrite const int row const int col const char data const int len void textrealdefchar const int ascii const vectorchar matrix line 30 public lcdtextint rows int cols int xres int yres int goto int chars int char0 qobject parent lcdbasexres yres qobjectparent line 33 lcdtext void textinitint rows int cols void textblitint row int col int height int width void textclear void textclearchars void textgreet void textdrawwidgettext widget void textbardrawwidgetbar widget void texthistogramdrawwidgethistogram widget void texticondrawwidgeticon widget void textbignumsdrawwidgetbignums widget void textgifdrawwidgetgif widget public signals line 46 void specialcharchangedint ch public slots void textspecialcharchangedint chendif,['c++'] +30060,writing an os for motorola 68k processor can i emulate it and can i testdrive os development next term i will need to write a basic operating system for motorola 68k processor as part of a course lab material is there a linux emulator of a basic hardware setup with that processor so my partners and i can debug quicker on our computers instead of physically restarting the board and stuffis it possible to apply testdriven development technique to os development code will be mostly assembly and c what will be the main difficulties with trying to testdrive this any advice on how to do it,['c'] +30063,rules of thumb for when to use operator overloading in python from what i remember from my c class the professor said that operator overloading is cool but since it takes relatively a lot of thought and code to cover all endcases eg when overloading you probably also want to overload and and also make sure to handle end cases like adding an object to itself etc you should only consider it in those cases where this feature will have a major impact on your code like overloading the operators for the matrix class in a math applicationdoes the same apply to python would you recommend overriding operator behavior in python and what rules of thumb can you give me,['python'] +30076,how to declare and consume events in java i have a simple class will call it animal i would like to fire off an event in the animal class and have it handled in the class where i instantiated the animal class in the event handler i want to pass an integer valuehow do i pull off something simple like that,['java'] +30078,python sqlite3 version python 262 r26271605 apr 14 2009 224002 msc v1500 32 bit intel onwin32type help copyright credits or license for more information import sqlite3 sqlite3version241questionswhy is the version of the sqlite3 module 241whats the reason behind bundling such an old sqlite with python the sqlite releaselog says 2002 mar 13 241,['python'] +30087,catch missing local resources in resx files i have many resource files in many different languageslets suppose for example we are supporting 3 languages en de fr and have this filecommonresxcommonderesxcommonfrresxi would like to detect occurrences when for instance a resource is requested in de but is missing and so reverts to the default language is there any way of catching this so i can log it and later add the missing resourcethanks,['.net'] +30090,wpf cannot set properties on property elements weirdness private textblock caption new textblockpublic textblock caption get return caption set caption value lcustompanel lcustompanelcaption textcaption text fontsize18 foregroundwhite lcustompanelgives me the following errorcannot set properties on property elementsif i uselcustompanel lcustompanelcaption textblock textcaption text fontsize18 foregroundwhite lcustompanelcaptionlcustompanelmy textblock shows up fine but it is nested inside another textblock like so it even seems to add itself outside of the caption propertylcustompanel lcustompanelcaption textblock inlineuicontainer textblock textcaption text fontsize18 foregroundwhite inlineuicontainer textblock lcustompanelcaption textblock inlineuicontainer textblock textcaption text fontsize18 foregroundwhite inlineuicontainer textblocklcustompanelas you might have already guessed what i would like my code to do is to set my caption property from xaml on a custom panel if this is possiblei have also tried the same code with a dependencyproperty to no availso anyone that can help me with this problem,"['c#', '.net']" +30091,how to upload html documentation generated from sphinx to github i just documented loads of my code and learnt how to use sphinx to generate the documentation i want to include that into my github project page but i do not know how to does anyone know existing tutorial or simple step to do sothanks,['python'] +30097,parsing javascript not json in php i have a php string containing the serialization of a javascript object string fubarbazbatthe actual string is far more complicated of course but still wellformed javascript this is not standard json so json decode fails do you know any php library that would parse this string and return a php associative array,"['php', 'javascript']" +30103,extract text from pdf in javascript i wonder if is possible to get the text inside of a pdf file by using only javascriptif yes can anyone show me howi know there are some serverside java c etc libraries but i would prefer not using a server thanks,['javascript'] +30105,understanding the or operator in if conditionals in ruby just briefly why are the following three lines not identical in their impactif controllercontroller name projects controllercontroller name partsif controllercontroller name projects partsif controllercontroller name projects partsthe first gives me the result i want but as there is actually more options than just projects and parts using that form creates a verbose statement the other two are more compact but do not give me the same result,['ruby'] +30108,windows os architecture book i have a background in programming and have done a little net but i feel that i would benefit from improving my understanding of the windows architecture can anyone recomend a good book that thiscusses the windows operating system from a technical perspactive particulary it is architecturedesign and how it works im not looking for a huge technical manual just looking to get a general appreciation of how windows worksthanks,['.net'] +30111,c combobox gotfocus i have a c combobox using wpf i have code that executes when the comboboxs gotfocus is activated the issue is that the gotfocus event is executed every time a selection is made from the combobox for example the gotfocus is executed when you first click on the combobox and then when you make a selection even though you have not click on any other controlis it possible to prevent this event from firing if a selection is being made in the list or is there a flag or something else in the event handler that can be used to determine if the gotfocus event handler was fired as a result of the user selecting an item in the list,['c#'] +30114,c const keyword use liberally in the following c functionsvoid myfunctionint age house purchased house void myfunctionconst int age house purchased house which is betterin both age is passed by value i am wondering if the const keyword is necessary it seems redundant to me but also helpful as an extra indication the variable will not be changingdoes anyone have any opinion as to which if any of the above are better,['c++'] +30117,dry vs avoid macros i am creating my own implementation of xul in c using the windows api the fact that the elements are constructed by the xml parser requires that they have identical interfaces so that we do not need to write custom code for each element constructor the result is that most of my elements look like thisclass button public elementpublic static const char type return button private friend class element buttonelement inparent const attributesmapping inattributesmappingclass label public elementpublic static const char type return label private friend class element labelelement inparent const attributesmapping inattributesmappingclass description public elementpublic static const char type return description virtual bool initprivate friend class element descriptionelement inparent const attributesmapping inattributesmappingso there is a lot of code duplication here i wonder if it would be a good idea to replace them with macro calls like thisdefine declare elementelementtype xulname class elementtype public element public static const char type return xulname private friend class element elementtype element inparent const attributesmapping inattributesmapping declare elementwindow windowdeclare elementbutton buttondeclare elementlabel labeli have not completely worked out the concept yet so a few things are missing here like the class definitions and maybe the ability to add methods per elementbut i would like to know your opinion of using macros in this situation feel free to share your thoughtsediti am now using a small ruby script that generates the source and header files from a set of templates i enhanced the scripts so that the files are also automatically marked for addition on svn and the visual studio project file is modified to include the files this saves me a lot of manual labor i am quite happy with this solution fyi this is what the templates look like nowifndef element name upper h includeddefine element name upper h includedinclude xulwinelementhnamespace xulwin class element name public element public static elementptr createelement inparent const attributesmapping inattr return elementcreateelement nameinparent inattr static const char type return element type virtual bool init private friend class element element nameelement inparent const attributesmapping inattributesmapping namespace xulwinendif element name upper h includedcpp documentinclude xulwinelement namehinclude xulwinelement nameimplhinclude xulwinattributecontrollerhinclude xulwindecoratorhnamespace xulwin element nameelement nameelement inparent const attributesmapping inattributesmapping elementelement nametype inparent new element nameimplinparentimpl inattributesmapping bool element nameinit return elementinit namespace xulwin,['c++'] +30120,how to save a model without sending a signal how can i save a model such that signals arent sent post save and pre save,['python'] +30133,which is latest c standard release from where i can download it possible duplicatewhere do i find the current x standard i have a simple question i am looking for soft copy of latest c standard release i have isoiec 14882 first edition 19980901 but i have doubt if it is latesti visited there are many draftsplease guide me which one is latest and i should refer,['c++'] +30141,difference between abort and interrupt in threads in net what is the difference between thraedabort and threadinterrupt how can i call them in a thread safe mannerit would be helpfulif simple example is provided,['c#'] +30160,sharing sqlite database between multiple android activities can two or more android activities open an sqlite3 database for write i have two activities that need to insert data into the same sqlite database when the second activity calls sqliteopenhelpergetwriteabledatabase an illegalstateexception is thrown with the message sqlitedatabase created and never closed i have been able to avoid the exception by making my database object a singleton but i am thinking there must be a better way thanksjohn,['android'] +30161,javamail api gmailauth and setfrom for this app i am following this examplei can send emails it looks goodbut i want to modify the sender email using thismimemessage msg new mimemessagemailsessionmsgsetfromnew internetaddress is dummy email is not mine when t use setfrom i recive the email from this email which i use to authenticate is the authentication the reason which thisable the setfrom methodi need to change the from email because i want that the recipient send me an replay to another email adress,['java'] +30164,objectivec best way to access rest api on your iphone been wrestling with this for some time i am trying to access a rest api on my iphone and came across the asihttp framework that would assist me so i did something likecall sites so we can confirm username and password and sitesitesnsurl url nsurl urlwithstring urlbaseasihttprequest request asihttprequest alloc initwithurlurl autoreleaserequest setusernamedoronkatz40xxcom request setpasswordxwhere urlbase is a url to a rest sitenow a developer has told me there might be an issue or bug with this framework and its not passing headers correctly is there another way of testing or accessing with authentication a network rest location,"['iphone', 'objective-c']" +30169,how to trap the back button event i have a uitableviewcontroller that launches a uiviewcontroller and i would like to trap whenever the back button is pressed in the child controller which is the class that derives from uiviewcontroller i can change the back button title but setting the target action values when setting the backbarbuttonitem seems to get ignored whats a way to receiving some kind of notification that the back button was tapped voidshowdetailview how i am creating showing the detail controller myviewcontroller controller myviewcontroller alloc initwithnibnamemydetailview bundlenil uibarbuttonitem backbutton uibarbuttonitem alloc initwithtitlepages styleuibarbuttonitemstylebordered targetself actionselectorhandleback selfnavigationitembackbarbuttonitem backbutton backbutton release selfnavigationcontroller pushviewcontrollercontroller animatedanimated controller release voidhandlebackidsender not reaching here nsloghandleback event reached,['iphone'] +30188,di handling life of ithisposable objects so i am working on my diioc container opennetcfioc and i have got a reasonable feature request to add some form of lifecycle management for ithisposable items in the container collectionsmy current thinking is that since i cannot query an object to see if it is been thisposed and i cannot get an event for when it is been thisposed that i have to create some form of wrapper for objects that a developer wants the framework to manageright now objects can be added with addnew for simplicity sake well assume there is only one overload and there is no addpublic ttypetobuild addnewttypetobuild what i am considering is adding a new method well group of them but you get the picturepublic thisposablewrappedobjectithisposable addnewthisposablettypetobuild where ttypetobuild class ithisposable where the thisposablewrappedobject looks like thispublic class thisposablewrappedobjectt where t class ithisposable public bool thisposed get private set public t instance get private set internal event eventhandlergenericeventargsithisposable thisposing internal thisposablewrappedobjectt thisposableobject if thisposableobject null throw new argumentnullexception instance thisposableobject thisposablewrappedobject thisposefalse public void thispose thisposetrue protected virtual void thisposebool thisposing lockthis ifthisposed return eventhandlergenericeventargsithisposable handler thisposing ifhandler null thisposingthis new genericeventargsithisposableinstance instancethispose thisposed true now when an items gets added to the container via addnewthisposable an eventhandler is also added so that when it gets thisposed via the wrapper the framework removes it from the underlying collectioni actually have this implemented and it is passing the unit tests but i am looking for opinions on where this might be broken or how it might be made more friendly to the consuming developeredit 1since there was a question on how the thisposing event is used heres some code trimmed to whats importantprivate object addnewtype typetobuild string id bool wrapthisposables object instance objectfactorycreateobjecttypetobuild m root if wrapthisposables instance is ithisposable thisposablewrappedobjectithisposable thispinstance new thisposablewrappedobjectithisposableinstance as ithisposable thispinstancethisposing new eventhandlergenericeventargsithisposablethisposableitemhandler addthispinstance as titem id expectnullid instance thispinstance return instanceprivate void thisposableitemhandlerobject sender genericeventargsithisposable e var key m itemsfirstordefaulti ivalue senderkey ifkey null return m itemsremovekey,['c#'] +30202,net and lotus notes interop i have lotus notes database file nsf at some location let us say is it possible in any way to read from that location using any net language,['.net'] +30227,send values from one form to another form i want to pass values between two forms c how can i do iti have two forms form1 and form2 form1 contains one button when i click on that button form2 should open and form1 should be in inactive mode ie not selectableform2 contains one text box and one submit button when i type any message in form2s text box and click the submit button the form2 should close and form1 should highlight with the submitted valuehow can i do it can somebody help me to do this with a simple example,['c#'] +30228,get custom attributes from lambda property expression i am using aspnet mvc 2 preview 2 and have written a custom htmlhelper extension method to create a label using an expression the tmodel is from a simple class with properties and the properties may have attributes to define validation requirements i am trying to find out if a certain attribute exists on the property the expression represents in my label methodthe code for the class and label ispublic class myviewmodel required public string myproperty get set public static mvchtmlstring labeltmodel tpropertythis htmlhelpertmodel htmlhelper expressionfunctmodel tproperty expression string label return mvchtmlstringcreatestringconcatlabel for expressiongetinputname label labelpublic static string getinputnametmodel tpropertythis expressionfunctmodel tproperty expression return expressionbodytostringsubstringexpressionparameters0namelength 1then i would call the label like thishtmllabelx xmyproperty my labelis there a way to find out if the property in the expression value passed to the label method has the required attributei figured out that doing the following does get me the attribute if it exists but i am hopeful there is a cleaner way to accomplish thispublic static mvchtmlstring labeltmodel tpropertythis htmlhelpertmodel htmlhelper expressionfunctmodel tproperty expression string label systemattributegetcustomattributeexpressionpropertyexpressionparameterexpressionparameters0type expressiongetinputname expressiongetinputnamemember typeofrequiredattribute return mvchtmlstringcreatestringconcatlabel for expressiongetinputname label label,['c#'] +30232,could not load file or assembly in nhibernate i recently had some problems with the hibernatecfgxml file as i had not had the following line inproperty nameproxyfactoryfactory classnhibernatebytecodecastleproxyfactoryfactory nhibernatebytecodecastlepropertynow that this is fixed i get the following errorcould not load file or assembly nhibernate version21040 cultureneutral publickeytokenaa95f207798dfdb4 or one of its dependencies the located assemblys manifest definition does not match the assembly reference exception from hresult 0x80131040why do i get this error and how do i fix it,"['c#', 'asp.net']" +30235,what is dbdevelopment structuresql in a rails project there is a development structuresql inside my db folder of my rails application rails 234 ruby 187 and i am not sure exactly what it doesis it needed for some specific environment i think i read somewhere that it is used for testsdo i need to add it to my git repository,"['sql', 'ruby-on-rails']" +30237,running apache ds embedded in my application i am trying to run an embedded apacheds in my application after reading i build thispublic void startdirectoryservice throws exception service new defaultdirectoryservice servicegetchangelogsetenabled false partition apachepartition addpartitionapache dcapachedcorg addindexapachepartition objectclass ou uid servicestartup inject the apache root entry if it does not already exist try servicegetadminsessionlookup apachepartitiongetsuffixdn catch ldapnamenotfoundexception lnnfe ldapdn dnapache new ldapdn dcapachedcorg serverentry entryapache servicenewentry dnapache entryapacheadd objectclass top domain extensibleobject entryapacheadd dc apache servicegetadminsessionadd entryapache but i cannot connect to the server after running it what is the default port or am i missing somethinghere is the solution service new defaultdirectoryservice servicegetchangelogsetenabled false partition apachepartition addpartitionapache dcapachedcorg ldapserver ldapservice new ldapserver ldapservicesettransportsnew tcptransport389 ldapservicesetdirectoryserviceservice servicestartup ldapservicestart,['java'] +30261,how to thisable submit behaviour of aspimagebutton i have a image button in a page which can be triggered on mouse click by default it gets triggered on enter press also which i want to thisablei know about usesubmitbehaviour attribute in aspbutton is there a way to do the same in aspimagebutton,['asp.net'] +30267,is it possible to use function pointers across processes i am aware that each process creates it is own memory address space however i was wonderingif process a was to have a function like int dostuff return 1 and a pointer typedef like typedef intdostuff fand a getter function like dostuff f getdostuff return dostuff and a magical way to communicate with process b via say boostinterprocesswould it be possible to pass the function pointer to process b and call process as dostuff from process b directly,['c++'] +30287,control flow in tsql sp using ifelse if are there other ways i need to branch my tsql stored procedure ms sql 2008 control flow to a number of directionscreate procedure foobar inputparam intasbegin if inputparam 1 begin end else if inputparam 3 begin end else if inputparam 3 begin endendis there any other ways for example in c i shoud use switchcase block,['sql'] +30294,converting to etc i want to convert amp to quot to ectis there a function in c that could do that without writing all the options manualy,['c#'] +30299,how to determine why an object is pinned i am trying to track down why some objects in my application are pinned the objects i have looked at so far are object arrays gcroot is showing the array as being pinned but i do not know how to figure out why it is pinned output0 dumpobj 0239cea0name systemobjectmethodtable 793041d0eeclass 790eda54size 5280x210 bytesarray rank 1 number of elements 128 type classelement type systemobjectfieldsnone0 gcroot 0239cea0note roots found on stacks may be false positives run help gcroot formore infoscan thread 0 osthread f3cscan thread 2 osthread e54scan thread 4 osthread 748scan thread 5 osthread fe0scan thread 7 osthread 7a0scan thread 9 osthread cf4scan thread 10 osthread a6cscan thread 11 osthread bc4scan thread 12 osthread 598scan thread 13 osthread a8scan thread 14 osthread 50cscan thread 15 osthread ba4scan thread 16 osthread b40scan thread 17 osthread 534scan thread 18 osthread 5fcscan thread 19 osthread dfcscan thread 20 osthread cc4scan thread 21 osthread f84scan thread 22 osthread 9f4scan thread 23 osthread ff0scan thread 24 osthread fb0scan thread 25 osthread c14scan thread 29 osthread 5c4domain0015eb90handlepinned971e74root0239cea0systemobjectdomain0015eb90handleweaksh971e74root0239cea0systemobjectdomain0015eb90handleweaksh971e74root0239cea0systemobjectdomain0015eb90handleweaksh971e74root0239cea0systemobjectdomain0015eb90handleunknwn971e74root0239cea0systemobjectdomain0015eb90handleweaksh971e74root0239cea0systemobjectdomain0015eb90handleunknwn971e74root0239cea0systemobjectdomain0015eb90handleweaksh971e74root0239cea0systemobjectdomain0015eb90handleweaksh971e74root0239cea0systemobjectdomain0015eb90handleunknwn971e74root0239cea0systemobjectdomain0015eb90handleunknwn971e74root0239cea0systemobjectdomain0015eb90handleweaksh971e74root0239cea0systemobjectdomain0015eb90handleunknwn971e74root0239cea0systemobjectdomain0015eb90handleunknwn971e74root0239cea0systemobjectdomain0015eb90handleunknwn971e74root0239cea0systemobjectdomain0015eb90handleunknwn971e74root0239cea0systemobjectdomain0015eb90handleunknwn971e74root0239cea0systemobjectdomain0015eb90handleunknwn971e74root0239cea0systemobjectdomain0015eb90handleunknwn971e74root0239cea0systemobjectdomain0015eb90handleunknwn971e74root0239cea0systemobjectdomain0015eb90handleunknwn971e74root0239cea0systemobjectdomain0015eb90handleunknwn971e74root0239cea0systemobjectdomain0015eb90handleunknwn971e74root0239cea0systemobjectdomain0015eb90handleunknwn971e74root0239cea0systemobjectdomain0015eb90handleunknwn971e74root0239cea0systemobjectdomain0015eb90handleunknwn971e74root0239cea0systemobjectdomain0015eb90handleunknwn971e74root0239cea0systemobjectdomain0015eb90handleunknwn971e74root0239cea0systemobjectedit added eeheap gc outputeeheap gcnumber of gc heaps 1generation 0 starts at 0x49a6f940generation 1 starts at 0x49a0c8a8generation 2 starts at 0x013010ephemeral segment allocation context none segment begin allocated size0130 013010 022f05a0 0x00fef5a0167090240d0d0 0d0d10 0e0bb0cc 0x00fea0cc166873080e9e0 0e9e10 0f9de3e8 0x00ffd3e81676592811020 110210 12014808 0x00ff38081672602415020 150210 15ff3958 0x00fd295816591192139f0 139f10 1499f584 0x00fae5841644275616020 160210 16fd7c30 0x00fb6c301647723219020 190210 1a013df4 0x00ff2df416723417020 170210 17fcfe8c 0x00faee8c1644506818020 180210 18fedb84 0x00fccb84165671721a020 1a0210 1afc8814 0x00fa78141641474026010 260110 26f97d2c 0x00f86d2c162808762d010 2d0110 2df97210 0x00f862101627803220010 200110 210028e0 0x00ff18e01671804821010 210110 220085d8 0x00ff75d81674184823810 238110 247acf60 0x00f9bf601636745628010 280110 28f84f80 0x00f73f80162036481c010 1c0110 1cfba544 0x00fa95441642121d010 1d0110 1dfdcf64 0x00fcbf641656406832010 320110 32f9189c 0x00f8089c162551321e010 1e0110 1eff9824 0x00fe8824166809962c010 2c0110 2cfd4904 0x00fc390416529668300a0 300a10 3104a488 0x00fa94881642202424810 248110 2571bd20 0x00f0ad201577296036d10 36d110 37c982d4 0x00f872d41628232429010 290110 29fc96a0 0x00fb86a016484027010 270110 27ee38bc 0x00ed28bc155424602a010 2a0110 2afab094 0x00f9a09416359572441c0 441c10 45149df0 0x00f88df01628926438d10 38d110 39ce4254 0x00fd3254165934923bd10 3bd110 3cc7a750 0x00f69750161605923ad10 3ad110 3bc8b878 0x00f7a87816230520411c0 411c10 421655a0 0x00fa45a0164018242b010 2b0110 2bfafae4 0x00f9eae416378596461c0 461c10 471a1bb0 0x00fe0bb0166491363e1c0 3e1c10 3f151c 0x00f5051c1605762834010 340110 35003ae4 0x00ff2ae416722660451c0 451c10 4609e680 0x00edd6801558694c1c0 4c1c10 4d105324 0x00f44324160079722f0a0 2f0a10 3007989c 0x00fd889c1661558050e10 50e110 51cf17d8 0x00ee07d81559957633010 330110 34005d88 0x00ff4d881673152837d10 37d110 38cc6d7c 0x00fb5d7c16473468481c0 481c10 4898a468 0x007c9468816445639d10 39d110 3acbe2d8 0x00fad2d8164379763f1c0 3f1c10 3fd1f378 0x00b5e3781192024851e10 51e110 52e01018 0x00ff001816711704431c0 431c10 441805d8 0x00fbf5d816512472401c0 401c10 4116b2b0 0x00faa2b016425648421c0 421c10 430da254 0x00f1925415831636491c0 491c10 49b98e0c 0x009d7e0c10321420large object heap starts at 0x023010 segment begin allocated size0230 023010 02f1bf20 0x00c1af2012693280total size 0x31786160829972832gc heap size 0x31786160829972832,['.net'] +30300,why does stylecop recommend prefixing method or property calls with this i have been trying to follow stylecops guidelines on a project to see if the resulting code was better in the end most rules are reasonable or a matter of opinion on coding standard but there is one rule which puzzles me because i have not seen anyone else recommend it and because i do not see a clear benefit to itsa1101 the call to method or property name must begin with the this prefix to indicate that the item is a member of the classon the downside the code is clearly more verbose that way so what are the benefits of following that rule does anyone here follow that rule,"['c#', '.net']" +30302,htmlbutton handler fires twice when clicked when autoeventwireuptrue i have an html button see below when it is clicked and autoeventwireuptrue the save click click handler is fired twice when autoeventwireupfalse it fires once why is it firing twice the button is not registered twice and no code which is adding the event handler using master page and no ajaxbutton idsave accesskeyv typesubmit runatserver onserverclicksave clickbutton,['asp.net'] +30314,anonymous code blocks in java are there any practical uses of anonymous code blocks in javapublic static void mainstring args in out please note that this is not about named blocks iename if something break name,['java'] +30315,how to enforce unique field value in java google app engine i am try to find out how to enforce uniqueness in fields other than the unique idexamplepersistencecapableidentitytype identitytypeapplicationpublic class user implements isserializable primarykey persistentvaluestrategy idgeneratorstrategyidentity private long id persistent private string name persistent private string email i want this to be unique as wellin the example above how can i enforce uniqueness of the email value across the databasedaniel,['java'] +30326,android simulate wifi in the emulator i would like to check from my app whether the device has wifi connectivity but in order to do that i must first find a way to get wifi in the emulator just going to settings wireless controls wifi says unable to start wifi while logcat saysewifiservice 566 failed to load wifi driverdsettingswifienabler 695 received wifi state changed from unknown to enablingdsettingswifienabler 695 received wifi state changed from enabling to unknownhow can i simulate wifi connectivity in the emulator,['android'] +30335,compression libraries for c i was reading about compression in programs and i started to create a new simple project a zipper just a zipper not an unzipper but i only found zlib and it is for c i know that c libraries can be used in c but i like to use c libraries does anyone know a good one to suggestbest regards,['c++'] +30354,when should i use nil and null in objectivec this is sample codensdictionary mydictionary nsdictionary dictionarynsnumber mynumber mydictionary valueforkey mynumbernslogmynumber mynumber output mynumber nullif mynumber nil nslogtest 1 mynumber nilif mynumber null nslogtest 2 mynumber nullif mynumber isequalnsnull null nslogtest 3 mynumber nsnull nullwhen should i use nil null and nsnull null,['objective-c'] +30363,thisplay an image or uiimage with a plain calayer i have often read that using a calayer rather than a uiimageview is an performance boost when it comes to heavy image usage that makes sense because uiimageview causes 3 copies of the image in memory which is needed for core animation but in my case i do not use core animationhow can i assign a uiimage or its image data to a calayer and then thisplay it,"['ios', 'iphone']" +30364,building a comma separated list i am tryin to use sql to build a comma separated list of cat idsthe code isdeclare output varcharmaxset output nullselect output coalesceoutput convertvarcharmaxcat idedit changed to null still samebut the output im getting is like so 66 23the leading comma should not be there what have i missed,['sql'] +30368,casting to string versus calling tostring object obj hellostring str1 stringobjstring str2 objtostringwhat is the difference between stringobj and objtostring,['c#'] +30370,c threading using monitorwait lock and pulseall i am new to csharp and threadingto be familiar with monitorwaitmonitorlock and monitorpulsealli framed a scenario described belowa footballground is being shared by different teams for practicing purpose at any time only one team can use the ground for their practice a team can use the ground for 30 minutes for their practice once the time reaches 25 minutes it should signal other threads that the ground is about to free after 5 minuteswhen the ground is wet enum has three values freeallottedwet no team is allowed to lock the ground and all should wait for 10 minutesahonestly speaking i do not know how turn the description in to actual coding based on my understanding i designed the outlinenamespace threadingsimulation a random activity can be picked up from this enum by a team public enum randomgroundstatus free allotted wet class footballground public void playingobject obj here the name of the team which is using the ground will be printed once the time is reached to 25 minnutes the active thread acquired the lock will signal other threads public void groundcleaninginprogressobject obj ground cleaning is in progress all of you wait for 10 minutes class team string teamname static void main select random value for grandstatus from enum if the ground is wet no team is allowed to get the ground for 10 minutes if the ground is free team a locks the ground otherwise team b locks the ground here i do not know how to apply locks and signallskindly help me,['c#'] +30378,how come a nonconst reference cannot bind to a temporary object why is it not allowed to get nonconst reference to a temporary object which function getx returns clearly this is prohibited by c standard but i am interested in the purpose of such restriction not a reference to the standard struct x x ref return this x getx return xvoid gx x int f const x x getx ok x x getx error x x getxref ok ggetx error ggetxref ok return 0it is clear that the lifetime of the object cannot be the cause because constant reference to an object is not prohibited by c standardit is clear that the temporary object is not constant in the sample above because calls to nonconstant functions are permitted for instance ref could modify the temporary object in addition ref allows you to fool the compiler and get a link to this temporary object and that solves our problemin additionthey say assigning a temporary object to the const reference extends the lifetime of this object and nothing is said about nonconst references though my additional question does following assignment extend the lifetime of temporary objectx x getxref ok,['c++'] +30388,how to add quartz core framework in new xcode 32 since new xcode 32 i find it very hard to add quartz core framework it does not appear in the list previously i just typed in quartz and some quartzcoreframework thing popped up finder is so bad it does not find any framework file on the mac so now the big question is where is it hidden,['iphone'] +30401,proper way to have an endless worker thread i have an object that requires a lot of initialization 12 seconds on a beefy machine though once it is initialized it only takes about 20 miliseconds to do a typical jobin order to prevent it from being reinitialized every time an app wants to use it which could be 50 times a second or not at all for minutes in typical usage i decided to give it a job que and have it run on its own thread checking to see if there is any work for it in the que however i am not entirely sure how to make a thread that runs indefinetly with or without workheres what i have so far any critique is welcomed private void dowork while true if jobquecount 0 do work on jobquedequeue else systemthreadingthreadsleep50 after thought i was thinking i may need to kill this thread gracefully insead of letting it run forever so i think i will add a job type that tells the thread to end any thoughts on how to end a thread like this also appreciated,"['c#', '.net']" +30409,how to make the class constructor private in ruby class aprivate def initialize puts wtf endendanew still works and calls initializeandclass aprivate def selfnew supernew endenddoes not work altogetherso whats the correct way i want to make new private and call it via a factory method,['ruby'] +30417,inheritance and templates in c why are methods invisible when a template publicly inherits from another template are not the base public methods supposed to be accessibletemplate int aclass test public test int mymethod1 return a template int bclass another public testbpublic another void mymethod2 mymethod1 int main another5 a amymethod1 amymethod2well gcc craps out on this i must be missing something totally obvious brain melt help,['c++'] +30422,using valueforkeypath on nsdictionary if a key starts the symbol i want to use valueforkeypath on my nsdictionary but the problem is that one of the keys is a string that starts with the symbol i have no control over the naming of the keyi am having problems trying to create the key path as i am getting a format exception even when trying to escape the symbolthis works finedict objectforkeykey1 objectforkeyspecialkey objectforkeykey3however none of these workdict valueforkeypathdict valueforkeypathkey1specialkeykey3any ideasthanksmike,"['iphone', 'objective-c']" +30432,integrating tumblr blog with website i would like to integrate my tumblr feed in to my website it seems that tumblr has an api for this but i am not quite sure how to use it from what i understand i request the page and tumblr returns an xml file with the contents of my blog but how do i then make this xml into meaningful html must i parse it with php turning the relevant tags into headers and so on i tell myself it cannot be that painful anyone have any insights,['php'] +30434,iphone application enterprise thistribution process i have a client that wises to thistribute their iphone application to only their employees and not on the itunes app store to me this sounds like a situation for enterprise thistribution could someone explain to me in as much detail as possible this process i know we will need to enroll as an enterprise thistribution member before any of this can happen but after that i am not sure how the endtoend thistribution process worksreally the main question is how do we push the application to the indviduals iphones thanks in advance any help is much appreciated,['iphone'] +30440,generating random number in each row in oracle query i want to select all rows of a table followed by a random number between 1 to 9select t select dbms randomvalue19 num from dual as randomnumberfrom mytable tbut the random number is the same from row to row only different from each run of the query how do i make the number different from row to row in the same execution,['sql'] +30471,mysql is it possible to get the difference of two query results i need to merge two query results as in union but i want to only keep the difference between the two results is this possiblei am basically selecting all resources in query 1 and notallowed resources in query 2 i obviously need the allowed resources in my last resultin pseodocodequery1 query2queryresult 1 id 1 2 3 4 5 6 queryresult 2 id 2 5 needed id 1 3 4 6,"['mysql', 'sql']" +30489,why clojure instead of java for concurrent programming when java is providing the capabilities for concurrent programming what are the major advantages in using clojure instead of java,['java'] +30497,what is the assert function i have been studying opencv tutorials and came across the assert function what does it do,"['c++', 'c']" +30504,can a dictionary be passed to django models on create is is possible to do something similar to this with a list dictionary or something else evendata dict title awesome title body great body of textmodelobjectscreatedata dicteven better if i can extend itmodelobjectscreatedata dict extrahello extra2world,['python'] +30508,iteration through groupcollection in c i am currently trying to use regular expressions in cregex reg gameinfo new regexpokerstars game hid09shorse gameholdemrazz7 card studomahaomaha hilobadugi limitno limitlimitpot limit currencysignsb09bb09 currency datetime regexoptionsmultilinematch matchresults reg gameinfomatchrawtextdictionarystringstring gameinfo new dictionarystringstringif matchresultssuccess gameinfoaddhid matchresultsgroupshidvalue gameinfoaddgame matchresultsgroupsgamevalue can i iterate through the matchresultgroups groupcollection and add the keyvalue pairs to my gameinfo dictionary,['c#'] +30525,a real use for as and is i have never used as or is in c or any language that supports the keyword what have you used it for i dont mean how do i use it i mean how have you actually need it i also got away with doing no typecasting in a fairly large c project i was proud so considering i almost never typecast why do i need the keyword as or is,['c#'] +30527,fastest way to scan for bit pattern in a stream of bits i need to scan for a 16 bit word in a bit stream it is not guaranteed to be aligned on byte or word boundaries what is the fastest way of achieving this there are various brute force methods using tables andor shifts but are there any bit twiddling shortcuts that can cut down the number of calculations by giving yesnomaybe contains the flag results for each byte or word as it arrivesc code intrinsics x86 machine code would all be interesting,"['c++', 'c']" +30542,is there a way to initialize an object through a hash if i have this classclass a attr accessor bcdendand this codea anewh b10c20d30is it possible to initialize the object directly from the hash without me needing to go over each pair and call instance variable set something likea anewhwhich should cause each instance variable to be initialized to the one that has the same name in the hash,['ruby'] +30545,are there any gui toolkits built on top of html canvas like swingswtgtk or qt are there any gui toolkits built on top of html canvas like swingswtgtk or qt so that it is possible to build applications like applets or flex guis inside the html canvas,"['javascript', 'html']" +30552,how to make jquery draggable with fixed x and y axis i am wondering if there is a way to make the jquery draggable to only drag straight up down and left right i want to prevent the user from dragging a div diagonally using the grid option in the draggable ui is not possible in my situationhow is this possiblethanks,['jquery'] +30556,convert exponential to decimal in python i have an array in python that contains a set of values some of them are232313e0721155e071923e071185611232how do i convert the exponential formats to the decimal formatadditional is there a way i can convert the exponent directly to decimal when printing out in unix with awk,['python'] +30557,net throwing custom exceptions can anyone shed some light on the pros and cons of throwing custom exceptions which inherit from systemexception or the proper way to use them i am already aware of the whenwhen not to throw exception but i am looking for guidance on how to create my own custom exceptions,['.net'] +30561,how do i refer to the document object of an from the parent page using jquery i am trying to access the document object of a page that lives in an iframe from the host page in other words i have a page that has an iframe in it and i want to use jquery on that page the parent page to access the document object of that iframespecifically i am trying to find the height of the iframed document once its content is rendered onload so that i can then resize the iframe from the parent page to match the height of the iframes content exactlyif it is important this iframe is created on the host page using javascript and is in the same domain as the parent page i already use this type of codeiframecontentsfindbodyappendpcontentpto populate the iframe with content but i do not know the exact syntax for getting the iframes document objectfor some reason i am finding a lot of ways to access the parents document object from within an iframe most with plain javascript but not the other way aroundthanks in advance for any help,"['javascript', 'jquery']" +30569,cakephp sessionauth logging out intermittently i am having reports and complaints from my user that they will be using a screen and get kicked back to the login screen immediately on their next request it does not happen all the time but randomly i am using cakephp and the auth component which seem to work well other than this issuei got some feedback on the cake forums once that this is sometimes caused by a 404 request that resets the session ie if you have a broken image link or a missing favicon file i have firebug open and there are no failed requests so i ruled this out as a possibility but the user is getting sporadically logged out this seems to occur across browsers and operating systemsbelow is a summary of my config settingssecuritylevel highsessiontimeout 1200 this means my actual timeout should be 120 secondssessionsave phpi am really at a loss as to what is causing this issue,['php'] +30576,jquery programmatically select an option in select box i am currently using jquery to return some json results once these results are returned i am using them to prepopulate fields in my formhowever i need some help in preselecting items in a drop down box for example i have a select box this is shortenedselect idstarttimeoption value140200 pmoptionoption value150300 pmoptionoption value160400 pmoptionoption value170500 pmoptionoption value180600 pmoptionselectand if my json value is var start time data0start let us say this is 170how can i using jquery make the option with value 170 selected option value170 selectedselected500 pmoption,['jquery'] +30584,functional programming library for objectivec is there any functional programming library for objectivec,['objective-c'] +30588,is it bad practice to use an enums ordinal value to index an array in java i have two arrays walls and neighborspublic boolean walls new boolean4public cell neighbors new cell4and i have an enumenum dir north south east westnow i would like to be able to access walls or neighbors by their direction so i do not have to pass around a bunch of magic indexeshowever when i was reading the documentation for enumordinal it said that programmers will have almost no use for this method which made me think it should not be used in this wayi was thinking of doing something likelistdir availabledirections new arraylistdirfordir direction dirvaluesif neighborsdirectionordinalvisitedavailabledirectionsadirectionor evenreturn neighborsdirnorthordinalshould i revert to using static constants for north south east west with the index value set to them or use an enums ordinal method,['java'] +30604,double click document file in mac os x to open java application i have a java application in an application bundle that i want to associate a file type withfor example if there is a filefooexamplewhen that file or any file with the example extension is doubleclicked i want my application to start and open the file i also want the files to have my applications iconi would like to do this by editing the infoplist file but it does not seem to be workingalso how does my java application know which file is passed to it,['java'] +30605,problems with setting the classpath in ant i am having problems getting my java program to run it uses some third party jars i can compile it fine but when i call my run target in ant it says it cannot find the class that i told it run in the classpath heres what my buildxml looks likeproject basedir defaultbuildproperty namebuild valuebuild property namesrc value property namelib valuelib path idclasspath fileset dirlib include namejar fileset fileset dirbuild include nameclass filesetpathtarget namebuild javac srcdirsrc destdirbuild classpath refidclasspath javactargettarget namerun java classnamefirstclass classpath refidclasspath javatargetdoes anyone know what i might be doing wrongheres my stack trace from antant run buildfile buildxmlrunjava could not find guistarter make sure you have it in your classpathjava at orgapachetoolsanttaskdefsexecutejavaexecuteexecutejavajava138java at orgapachetoolsanttaskdefsjavarunjavajava764java at orgapachetoolsanttaskdefsjavaexecutejavajavajava218java at orgapachetoolsanttaskdefsjavaexecutejavajavajava132java at orgapachetoolsanttaskdefsjavaexecutejavajava105java at orgapachetoolsantunknownelementexecuteunknownelementjava288java at sunreflectnativemethodaccessorimplinvoke0native methodjava at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava57java at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43java at javalangreflectmethodinvokemethodjava616java at orgapachetoolsantthispatchthispatchutilsexecutethispatchutilsjava106java at orgapachetoolsanttaskperformtaskjava348java at orgapachetoolsanttargetexecutetargetjava357java at orgapachetoolsanttargetperformtaskstargetjava385java at orgapachetoolsantprojectexecutesortedtargetsprojectjava1337java at orgapachetoolsantprojectexecutetargetprojectjava1306java at orgapachetoolsanthelperdefaultexecutorexecutetargetsdefaultexecutorjava41java at orgapachetoolsantprojectexecutetargetsprojectjava1189java at orgapachetoolsantmainrunbuildmainjava758java at orgapachetoolsantmainstartantmainjava217java at orgapachetoolsantlaunchlauncherrunlauncherjava257java at orgapachetoolsantlaunchlaunchermainlauncherjava104java java result 1build successful total time 1 second,['java'] +30613,how could i stop from printing both sides of a wall in my ascii maze i have written some code that generates mazes for me the maze consists of n x n cells each cell has a boolean value to represent a wall north south east westit is working fine and i wrote the function below to print out the mazepublic static void printmazecell maze forint i 0 i mazelength i forint j 0 j mazeilength j systemoutprintmazeijwallsgetdirnorth systemoutprintln forint j 0 j mazeilength j systemoutprintmazeijwallsgetdirwest systemoutprint systemoutprintmazeijwallsgetdireast systemoutprintln forint j 0 j mazeilength j systemoutprintmazeijwallsgetdirsouth systemoutprintln however because cells share walls i produce a sort of a doublewall corridor look in my print function how should i modify my print function so it looks like i fear i am going to face a similar problem when i eventually get to the point i start drawing my maze using actual graphics rather than ascii as wellhow do i modify my printmaze method so it goes from the first example to the second onein case anyone is interested the source code to my class for generating these is here,['java'] +30626,checking if a pointer is allocated memory or not can we check whether a pointer passed to a function is allocated with memory or not in ci have wriiten my own function in c which accepts a character pointer buf pointer to a buffer and size buf siz buffer size actually before calling this function user has to create a buffer and allocate it memory of buf siz since there is a chance that user might forget to do memory allocation and simply pass the pointer to my function i want to check this so is there any way i can check in my function to see if the pointer passed is really allocated with buf siz amount of memory edit1 it seems there is no standard library to check it but is there any dirty hack to check it edit2 i do know that my function will be used by a good c programmer but i want to know whether can we check or not if we can i would like to hear to it conclusion so it is impossible to check if a particular pointer is allocated with memory or not within a function,['c'] +30627,using sphinx to write personal websites and blogs sphinx is a python library to generate nice documentation from a set of rest formatted text filesi wonder if any one has written sphinx plugins to make it generate personal websites and blogsespecially for blogs there needs to be a way to automatically list posts chronologically and generate a rss feed one needs to write a sphinx plugin to do such special pagexml generationhas anyone tried this before,['python'] +30631,standard template string class stringfill i need a way to create a string of and chars in this case ascii value zeroi know i can do it by calling the constructorstring stemp1250 abut i would like to reuse stemp in many places and fill it with different lengthsi am calling a library that takes a string pointer and length as an argument and fills the string with bytes i know that technically string is not contiguous but for all intents and purposes it is and will likly become the standard soon i do not want to use a vectoris there some clever way to call the constructor again after the string has been created,['c++'] +30643,how the localhost port number of net development server set i see that time to time localhost port number changes httplocalhost1519 basically how does it being set or chosen and when does it changethanks,['.net'] +30659,has anyone found that uiwebview fails for some urls i have been working on an iphone app for a couple of weeks now and one of the earlier features i added was a uiwebview that loaded context sensitive wikipedia page topics this was pretty trivial to implement and has been working fine for some timetoday i found that functionality had unexpectedly stopped working i had been fiddling around at the perimeter of that piece of code and initially assumed that i had broken something i checked all the obvious places my urls was the uiwebview still hooked up in the xib etc i did not find any issues investigating further i stuck some error handling on my uiwebviewdelegate didfailloadwitherror and found i was getting a 9 errornsurlerrorcancelled returned when an asynchronous load is canceleda web kit framework delegate will receive this error when it performs a cancel operation on a loading resource note that an nsurlconnection or nsurldownload delegate will not receive this error if the download is canceledso this sounds like making a new request or cancelling before the original one has finished i check my code for anything like this and come up emptyso i went into my usual downward spiral of paranoia and assumed that wikipedia was blocking requests based on uagent or something and went on something of wild goose chase attempting to spoof my way back to a happy place these attempts were not successful and eventually sanity prevailed i created a simple python script to mimic the http request i was making from my app in the simulator to see what wikipedia was sending backstring get wikifranklin d roosevelt http11rnhost enwikipediaorgrnuseragent testrnreferer d rooseveltrnaccept rnacceptlanguage enusrn acceptencoding gzip deflaternconnection keepalivernrnimport sockets socketsocketsconnectenwikipediaorg80ssendstringx srecv 10while x print x x srecv 10so i run this guy and thiscover that wikipedia is very kindly returning my data promptly and completely so what is going onchinks started to appear in my every present paranoid armour it is always my fault and i decide to check out if other iphone apps can view these urls i post a tweet with an ironically amusing i am easily amused url and check out if tweetie can view the url it cannot a friend tries it out in twitterific same problem works fine in safari and the wikipedia app but it seems like iphone apps using a bog standard uiwebview are having problems with wikipedia pagesjust to be completely certain there are no other variables i created a simple test app with just a uiwebview that loads up it fails with the same error added that code at the endso what do you guys think is this just a uiwebview bug any apple gronks out there know what is going on here have i missed something completely obvious and i am once again sitting on the train to work without my pants onlooking forward to hearing what you think keep in mind this was working fine yesterdaydebrief or maybe post mortem is more appropriatethanks duncan for the solution and a pretty clear description of what is going on here looks like the reason i originally saw the error when i was not implementing the didfailloadwitherror delegate method at all was that the default behavior for that method is apparently to clear the uiwebview and consequently kill the request when i added my implementation to find out what was going on i stuck in some code to write the error to the view and as duncan points out this is what got meseems like a pretty horrible solution to ignore 9 error codes in the callback but i am fine with duct tapei tried quite a few apps to test if this was a uiwebview problem tweetie twitteriffic etc and they all had the issue it looks like this might be a pretty common oversight for developers maybe apple can clean this up in the next versionother interesting point is that when i switched my urls to use instead of the problem went away implement viewdidload to do additional setup after loading the view typically from a nib voidviewdidload super viewdidload webview uiwebviewselfview webviewdelegate self load the url fail nsurl newurl nsurl alloc initwithstring autorelease ok nsurl newurl nsurl alloc initwithstring autorelease nsurlrequest newurlrequest nsurlrequest requestwithurlnewurl webview loadrequestnewurlrequest delegate stuff boolwebviewuiwebview webview shouldstartloadwithrequestnsurlrequest req navigationtypeuiwebviewnavigationtypenavigationtype return yes voidwebviewdidstartloaduiwebview wv starting the load show the activity indicator in the status bar uiapplication sharedapplicationnetworkactivityindicatorvisible yes voidwebviewdidfinishloaduiwebview webview finished loading hide the activity indicator in the status bar uiapplication sharedapplicationnetworkactivityindicatorvisible no voidwebviewuiwebview webview didfailloadwitherrornserror error nsurlerrordomain load error hide the activity indicator in the status bar uiapplication sharedapplicationnetworkactivityindicatorvisible no webview loadhtmlstringnsstring alloc initwithformatfailed to load page error localizeddescription autorelease baseurlnil,['iphone'] +30662,why cannot i catch a generic exception in c i was doing some unit testing on code that could throw a number of exceptions depending on the inputs so i tried something like the below code simplified for the example static void mainstring args runtestargumentexception static void runtestt where t exception new try throw new t throw new argumentexception does not work either catch t tex consolewritelinecaught passed in exception type catch exception ex consolewritelinecaught general exception consoleread but this will always print out caught general exception the catcht tex handler will never work it does not matter whether i throw t or explicitly throw argumentexception any ideas why this is actually i was kind of surprised that i was even able to use t in the catch clause but since that is possible should not this work or at least give a compiler warningerror that says that this handler will never workmy environment is visual studio 2008 and 35 is the target frameworkupdate i tried it now directly from the command prompt and then it prints out caught passed in exception type so it looks like this is restricted to running from within visual studio maybe a peculiarity of the visual studio hosting process,"['c#', '.net']" +30666,ordering in a mysql group concat with a function in it i want to order the results in a group concat function the problem is that the selection in the group concatfunction is another function like this fantasy selectselect aname group concatthistinct concat ws bid cname order by bid asc as coursefrom people a stuff b courses cgroup by aidi want to get a result like ordered by bidmichael 1science2maths3physicsbut i getmichael 2maths1science3physicsdoes anyone know how i can order by bid in my group concat here,"['sql', 'mysql']" +30672,what options are there for a quick embedded db in net i am making this tiny utility program windows forms and it would need to save a bit of data to the thisk in db terms it would be about one table no more than about couple thousand rows each row being less then 1kb in sizewhat would you useadded forgot to say it would be really neat if the whole program would be just one exe file plus the data file of course thus i would prefer something that is built in net,['.net'] +30680,how to select columns as rows so i have been searching around and i have found things similar to my problem but i need more help to get a real solutioni am trying to construct a query that will return 2 columns of data the first column should be a list of the column names themselves and the second should be the value of that columnvisually it would look like thiscolumn1 column2 columna value of columnacolumnb value of columnb i am pretty sure that this is going to require dynamic sql to achieve but i have no idea how to even begin creating the queryany help is appreciated,['sql'] +30688,the procedure entry point could not be located in the dynamic link library coredll i am converting my project to use dlls and am trying to break apart my singleton class to avoid using templates my class ludomemory originally inherited from singleton i am trying to give it the functions to destroy and create itself now and have my main engine not rely on the singletoni have written a simple destroy method like suchludomemory memory singleton null void ludomemorydestroy ludo safe deletem singleton and upon running the program no compiler errors i recieve this errorthe procedure entry point destroyludomemorysaxxz could not be located in the dynamic link library ludocoredludocore is the project that ludomemory belongs to why is this happening how can i solve it,['c++'] +30689,get next date from weekday in javascript would you be so kind and tell me if this is possible in javascript to return the next date of given weekday it could be either a number 06 or names sundaysaturdayexample if today on 16oct2009 i passed infriday it would return todays date 16oct2009saturday returned 17oct2009thursday returned 22oct2009thanksi really hope to get an answer and people who search for this kind of function online would end up here since i have not found anything else out there that solves this this indeed am not rentacoder because the solution is accessible to everyone for free i do not think you need to comment if you do not know the answer i do however appreciate your comments andy josh,['javascript'] +30703,uiviewcontroller viewdidload vs viewwillappear what is the proper division of labor i have always been a bit unclear on the type of tasks that should be assigned to viewdidload vs viewwillappear in a uiviewcontroller subclass eg i am doing an app where i have a uiviewcontroller subclass hitting a server getting data feeding it to a view and then thisplaying that view what are the pros and cons of doing this in viewdidload vs viewwillappear,['ios'] +30716,what is mysql partitioning i have read the documentation but i would like in your own words what it is and why it is used is it mainly used for multiple servers so it does not drag down one serverso part of the data will be on server1 and part of the data will be on server2 and server 3 will point to server1 or server2is that how it workswhy does mysql documentation focus on partitioning within the same serverif the purpose is to spread it across servers,['mysql'] +30717,workflow for writing arm assembly code on the iphone i would like to begin writing arm assembler and running it on the iphone this is not with the intent of using in an app to be released to the app store basically i would like to solve problems on projecteuler using arm and the iphone just for hobby and educational purposes how can i go about doing this i have not been able to come up with a way get a project running using any hand written arm,['iphone'] +30726,whats the best way to search for a python dictionary value in a list of dictionaries i have the following data structure data site stackoverflow id 1 site superuser id 2 site serverfault id 3 i want to search the above list to see if it has any site with a specific value for instance search the above to see if the list contain a dictionary with site superuser and return truefalse i can do the above the usual way of looping over each item and comparing them is there an alternative way to achieve a search,['python'] +30728,how do i list all the columns in a table for the various popular database systems how do you list all the columns in a table,"['sql', 'mysql']" +30758,why throwing an ejbexception is a recommended practice i keep getting this suggestion from many fellow developers over and over again in my experience i have found that ejbexceptions are wellsuited for end of the world from the bean instance perspective like when something is so wrong that the bean instance cannot recover by itself if an instance can recover i think it is better to throw an application exception here is the pattern that i meet over and over againprivate someresource resourceejbcreate resource allocateresourceommessage try catch jmsexception e throw new ejbexceptione ejbremove freeresourceresourceimho this is a antipattern that causes resource leaksedit specifically the ejb specification says that if a bean throws a runtime exception and ejbexception is a runtime exception from the business method then the bean is thiscarded without calling ejbremove on itis this a relevant example against throwing an ejbexceptionwhat are the relevant cases when ejbexception should be thrown,['java'] +30759,how can i store my users passwords safely how much more safe is this than plain md5 i have just started looking into password security i am pretty new to phpsalt csdnfgksdgojnmfnbpassword md5salt postpasswordresult mysql queryselect id from users where username mysql real escape string postusername and password passwordif mysql num rowsresult 1 access denied echo the username or password you entered is incorrect else sessionid mysql resultresult 0 id headerlocation echo hello sessionid,['php'] +30761,what is the c equivalent of iterator in java i am manually converting java to c and have the following codefor iteratorsgroup thesgroupiterator sgroupgetsgroupiterator thesgroupiteratorhasnext sgroup nextsgroup thesgroupiteratornextis there an equivalent of iteratort in c or is there a better c idiom,"['c#', 'java']" +30776,user specified dynamic model fields in rails does anyone know of a gem or a good implementation of allowing the user to add fields to a modelexuser would like to add a internal notes field to the contact model in the interface they would just select new field type textthanks,['ruby-on-rails'] +30778,reset an nstimers firing time to be from now instead of the last fire i have a nstimer that fires with an interval of 3 seconds to decrease a value when i do an action that increases that value i want to restart the timer to count 3 seconds from that pointfor example if i increase the value and timer will fires in 1 second i want to change that and make the timer fire in 3 seconds instead can i invalidate the timer and create it again or can i do it with setfiredate using the current date and adding an interval of 3 seconds,['objective-c'] +30779,edit text file using python i need to update a text file whenever my ip address changes and then run a few commands from the shell afterwardscreate variable lastknown 21217113553 this is the ip address we have while writing this scriptget the current ip address it will change on a daily basiscreate variable current for the new ipcompare as strings current to lastknownif they are the same exitif they differ a copy the old config file etcipfconf containing lastknown ip address into tmpb replace lastknown with current in the tmpipfconf filec using subprocess mv tmpipfconf etcipfconfd using subprocess execute ipf fa f etcipfconfe using subprocess execute ipnat cf f etcipnatconf exiti know how to do steps 1 through 6 i fall down on the file editing part a c i cannot tell what module to use or whether i should be editing the file in place there are so many ways to do this i cannot decide on the best approach i guess i want the most conservative onei know how to use subprocess so you do not need to comment on that i do not want to replace entire lines just a specific dotted quad thanks,['python'] +30785,should i be trying to create a reversible enum in java or is there a better way i seem to have faced this problem many times and i wanted to ask the community whether i am just barking up the wrong tree basically my question can be thistilled down to this if i have an enum in java for which the values are important should i be using an enum at all or is there a better way and if i do use an enum then what is the best way to reverse the lookupheres an example suppose i want to create a bean representing a specific month and year i might create something like the followingpublic interface monthandyear month getmonth void setmonthmonth month int getyear void setyearint yearhere i am storing my month as a separate class called month so that it is typesafe if i just put int then anyone could pass in 13 or 5643 or 100 as a number and there would be no way to check for that at compiletime i am restricting them to put a month which i will implement as an enumpublic enum month january february march april may june july august september october november decembernow suppose that i have some backend database i want to write to which only accepts the integer form well the standard way to do this seems to bepublic enum month january1 february2 march3 april4 may5 june6 july7 august8 september9 october10 november11 december12 private int monthnum public monthint monthnum thismonthnum monthnum public getmonthnum return monthnum fairly straightforward but what happens if i want to read these values from the database as well as writing them i could just implement a static function using a case statement within the enum that takes an int and returns the respective month object but this means if i changed anything then i would have to change this function as well as the constructor arguments change in two places so heres what i have been doing first off i created a reversible map class as followspublic class reversiblehashmapkv extends javautilhashmapkv private javautilhashmapvk reversemap public reversiblehashmap super reversemap new javautilhashmapvk override public v putk k v v reversemapputv k return superputkv public k reversegetv v return reversemapgetv then i implemented this within my enum instead of the constructor methodpublic enum month january february march april may june july august september october november december private static reversiblehashmapjavalangintegermonth monthnummap static monthnummap new reversiblehashmapjavalangintegermonth monthnummapputnew javalanginteger1january monthnummapputnew javalanginteger2february monthnummapputnew javalanginteger3march monthnummapputnew javalanginteger4april monthnummapputnew javalanginteger5may monthnummapputnew javalanginteger6june monthnummapputnew javalanginteger7july monthnummapputnew javalanginteger8august monthnummapputnew javalanginteger9september monthnummapputnew javalanginteger10october monthnummapputnew javalanginteger11november monthnummapputnew javalanginteger12december public int getmonthnum return monthnummapreversegetthis public static month fromintint monthnum return monthnummapgetnew javalangintegermonthnum now this does everything i want it to but it still looks wrong people have suggested to me if the enumeration has a meaningful internal value you should be using constants instead however i do not know how that approach would give me the typesafety i am looking for the way i have developed does seem overly complicated though is there some standard way to do this kind of thingps i know that the likelihood of the government adding a new month isfairly unlikely but think of the bigger picture there are plenty of uses for enums,['java'] +30791,performance surprise with as and nullable types i am just revising chapter 4 of c in depth which deals with nullable types and i am adding a section about using the as operator which allows you to writeobject o int x o as intif xhasvalue use xvalue in herei thought this was really neat and that it could improve performance over the c 1 equivalent using is followed by a cast after all this way we only need to ask for dynamic type checking once and then a simple value checkthis appears not to be the case however i have included a sample test app below which basically sums all the integers within an object array but the array contains a lot of null references and string references as well as boxed integers the benchmark measures the code youd have to use in c 1 the code using the as operator and just for kicks a linq solution to my astonishment the c 1 code is 20 times faster in this case and even the linq code which i would have expected to be slower given the iterators involved beats the as codeis the net implementation of isinst for nullable types just really slow is it the additional unboxany that causes the problem is there another explanation for this at the moment it feels like i am going to have to include a warning against using this in performance sensitive situationsresultscast 10 121 as 10 2211 linq 10 2143 codeusing systemusing systemdiagnosticsusing systemlinqclass test const int size 30 static void main object values new objectsize for int i 0 i size 2 i 3 valuesi null valuesi1 valuesi2 1 findsumwithcastvalues findsumwithasvalues findsumwithlinqvalues static void findsumwithcastobject values stopwatch sw stopwatchstartnew int sum 0 foreach object o in values if o is int int x int o sum x swstop consolewritelinecast 0 1 sum long swelapsedmilliseconds static void findsumwithasobject values stopwatch sw stopwatchstartnew int sum 0 foreach object o in values int x o as int if xhasvalue sum xvalue swstop consolewritelineas 0 1 sum long swelapsedmilliseconds static void findsumwithlinqobject values stopwatch sw stopwatchstartnew int sum valuesoftypeintsum swstop consolewritelinelinq 0 1 sum long swelapsedmilliseconds,['c#'] +30795,can i instantiate a php class inside another class i was wondering if it is allowed to create an instance of a class inside another classor do i have to create it outside and then pass it in through the constructor but then i would have created it without knowing if i would need itexample a database classclass someifinclude site root applicatie dbclassphpdbnew db,['php'] +30796,c oracle data type equivalence with oracledbtype situationi am creating an app in c that uses oracledataaccessclient 11g to do certain operations on a oracle database with stored procedures i am aware that there is a certain enum oracledbtype that contains the oracle data types but i am not sure which one to use for certain typesquestionswhat is the equivalent oracle plsql datatype for each enumerated type in theoracledbtype enumerationthere are three types of integerint16 int32 int64 in the oracledbtype how to know which one to use or are they allsuppose to work,['c#'] +30813,304 not modified and front end caching i am using a php script to serve files i would like to be able to send back a 304 not modified header in my http response if the file has not changed since the client last downloaded it this seems to be a feature in apache and most other web servers but i have no clue how this can be implemented through phpi have heard of using serverhttp if modified since but this variable does not seem to appear in my server super array my question is not how to return a 304 header but how to know that one should be returnededit the problem is that my serverhttp if modified since is not set this is the content of my htaccess fileexpiresactive on expiresbytype imagejpeg modification plus 1 monthexpiresbytype imagepng modification plus 1 monthexpiresbytype imagegif modification plus 1 monthheader append cachecontrol mustrevalidate ifmodule mod rewritec rewriteengine on rewritecond 1 controllerphp rewriterule jpgpnggif controllerphp1ifmodulehttp if modified since still does not appear in the server super array,['php'] +30819,up to first and characters how do i get up to the first and characters of a string in java without doing a size check firstinline is acceptable or risking an indexoutofboundsexception,['java'] +30824,converting multidimensional arrays to pointers in c i have a program that looks like the followingdouble44 startmatrixdouble44 inversematrixinitializestartmatrix this puts the information i want in startmatrixi now want to calculate the inverse of startmatrix and put it into inversematrix i have a library function for this purpose whose prototype is the followingvoid matrixinversiondouble a int order double bthat takes the inverse of a and puts it in b the problem is that i need to know how to convert the double44 into a double to give to the function i have tried just doing it the obvious waymatrixinversiondoublestartmatrix 4 doubleinversematrixbut that does not seem to work is that actually the right way to do it,['c++'] +30830,how to merge two arrays in javascript and deduplicate items i have two javascript arraysvar array1 vijendrasinghvar array2 singh shakyai want the output to bevar array3 vijendrasinghshakyathe output array should have repeated words removedhow do i merge two arrays in javascript so that i get only the unique items from each array in the same order they were inserted into the original arrays,['javascript'] +30855,use of profile attribute in html head tag what is the use of profile attributes in the html head tag i happened to read about it in here headaspi could not understand this either since it is too technical for mei have never used it what is the purpose it serves,['html'] +30860,c function syntax parameter types declared after parameter list i am relatively new to c i have come across a form of function syntax i have never seen before where the parameter types are defined after that parameter list can someone explain to me how it is different than the typical c function syntaxexample int main argc argvint argcchar argvreturn0,['c'] +30882,access get directly from javascript i suppose i could use php to access get variables from javascriptscriptvar to gettovar from getfromscriptscript srcrealscript typetextjavascriptscriptbut perhaps it is even simpler is there a way to do it directly from js,"['php', 'javascript']" +30885,changing uitableview section header without tableviewtitleforheaderinsection i am trying to change the header title for a section in a uitableview when a cell from that section is selected tableviewtitleforheaderinsection is triggered by the application so that does not help i can call reloaddata but the performance suffers because the app has to reload all the visible cells i also tried to use a custom header but that also results in some performance problems is there any way to get a handle to the uilabel that the default header view uses and change its text manually thanks,['iphone'] +30889,how do i escape a single quote in sql server i am trying to insert some text data into a table in sql server 9the text includes a single quotehow do i escape thati tried using two single quotes but it threw me some errorseg insert into my table valueshi my names tim,['sql'] +30903,challenge c foreach before after even odd last first since c does not have a beforeafterlastfirst etc as part of its foreach the challenge is to mimic this behavior as elegantly as possible with the following criteriamust allow before first even odd last after eventsgive an option executenot execute the primary function function executed on all objects of the collection during the events listed in 1if you can exceed the above criteria pleases doi will post my answer below but its not elegant nor is it feasible so i would like to see what the community can conjure up hard coded for loops get annoying sometimes,['c#'] +30940,how does this escape the constructor in java i have heard about this happening in non threadsafe code due to improperly constructed objects but i really do not have the concept down even after reading about in in goetzs book i would like to solidify my understanding of this code smell as i maybe doing it and not even realize it please provide code in your explanation to make it stick thanks,['java'] +30943,get data value from listview itemdatabound i am sure i have done this before but really cant remember howin the itemdatabound event of a listview i need to get the actual data value i cant seem to find it in the listviewitemeventargs object that gets passed inthanks,"['c#', 'asp.net']" +30945,how to prepare a django project for future changes as i work on my first django powered site i am constantly learning new things and making all sorts of changes and additions to my apps as i go i try to follow dry and pythonic principles and be smart in my coding but eventually i will have to take the site live and am certain that not long after i do something new and exiting will come down the pipe and i will want to implement it preparing for the futurewith this in mind do folks have any suggestions about how i can prepare my code now to be as futureready as possible for these currently unforseenunknown upgradesadditions to my code base hindsight is 2020what do you wish you had done at the start that would have made your life easier now that your site is up and running little things i have learned examplesuse utc as the default timezone and use datetimedatetimeutcnowuse south to aid future database changes have not done it yet but it seems wisenot hard code links in my templates use get absolute url and reverse lookupscreate a separate tools app to contain small reusable templatetags and utility functions that i may want to use in future projects no need to decouple them laterthese are small tips and some straight from the djangodocs but i think they help how about you what are your best practices for a new app or project that prepare you for the future,['python'] +30947,mysql how to order by relevance innodb table i have got about 20 rows in an innodb table called cards so fulltext is not an optionplease consider this tableid name description1 john smith just some dude2 ted johnson another dude3 johnathan todd this guy too4 susan smith her too5 sam john bond and him6 john smith same guy as num 1 another record7 john adams last guy promiseso say the user searches for john i want the result set to be in the order of7 john adams6 john smith3 johnathan todd5 sam john bond2 ted johnsonplease note that weve only pulled john smith once we took his most recent entry due to my data all names are for the same exact person no need to worry about 2 different guys named john smithideas let me know if i can clarify anything,['mysql'] +30949,best practices tips for storing html tags in resource files i have the following situation assume i have to thisplay the data in the following formati am 20 years old i need the number 20 to be in bold i am fetching this string from a resource file like thisstringformathttpcontextgetglobalresourceobjectresourcefilekeyageshould i consider adding the tags b and b within the resource file is that considered a best practice could anyone provide useful links on localization as well,"['c#', 'html']" +30957,subtraction between two sql queries i have 2 queries in ms sql that return a number of results using the count functioni can run the the first query and get the first result and then run the other one to get the other result subtract them and find the results however is there a way to combine all 3 functions and get 1 overall resultas in run sql1 run sql2 run sql3 sql1sql2i tried them with x as a function but no luck,['sql'] +30984,initializer list argument evaluation order so the c standard requires that class members be initialized in the order in which they are declared in the class rather than the order that they are mentioned in any constructors initializer list however this does not imply anything about the order in which the arguments to those initializations are evaluated i am working with a system that frequently passes references to serialization objects around and wondering if i can ensure that bits are read from it in the right order independent of the order in which those bits get written into the objects fieldsstruct foo int a double b i want to be able to do this fooserobj s bsreaddouble asreadint rather than this foo serobj s b sreaddouble a sreadint obviously reordering things like ints and doubles in the declaration is not too big a deal but bigger objects and things requiring dynamic allocation sometimes can be,['c++'] +30991,how big should a uibarbuttonitem image be i am looking to create my own custom sort by date and sort by number buttons that i plan on placing in the navigation bar as the right buttonhow big should my image be to appropriately fill the space the uibaritem documentation page does not list anything about the size the image should be,"['ios', 'iphone']" +30995,android tabs mapview activities within tabs were in the process of writing an app that has 4 tabs map people places events the people places and events in the app show up as icons on the map by default the people places and events tabs each show a listview custom rendered thisplaying all the people places and events respectivelynow right now each of the tabs has as its content an intent set to launch the corresponding activity for instance there is a maptabactivity that extends mapactivity a showpeoplelistactivity that shows the people and so on and so forth i see a lot of stackoverflow questionsanswers saying that due to various limitations in the way the tabhost is setup it is best not to use activities as the content of tabs for instance it is impossible to launch a new activity and have it take the place of the existing activity within a tab whereas it is possible to switch out a view with a different view now i am at a crossroads weve for better or worse devoted a fair amount of time trying to get this app to work the way it is currently structured with the activities as the content of the tabs when an icon corresponding to a person place or event is clicked it fires off a view intent on a uri corresponding to that object this is picked up by an activity that then shows the object the same mechanism is at work both in the map and in the individual lists we really like the loose coupling this provides us we just give a view command and the uri to the personplaceevent and it automatically brings us to the right activity granted the activity that is launched covers up the tab view rather than appearing inside of that but we were willing to live with thisheres an issue though from the show activity we want to be able to go back to the map centered at that person place or event we can launch a new activity to show the map again but now we have the map activity as the content of the tab plus the show activity plus the new map activity in the activity stack given how resource intensive the map activity is i am guessing this is not the ideal way to goi guess my question is is there a good tutorial somewhere showing exactly how to do complex tasks with a tabhost i have seen hellotabwidget i am looking for something much more sophisticated than this i am worried that if we switch to the view based way of doing things well have to do a lot of housekeeping to intercept all the back events try to switch out the views etc etc as well as strongly coupling our program in a way we do not want any suggestions on a way forward would be extremely appreciated were new to android so were trying to follow the established best practices but it is difficult when the few examples weve seen are too simplistic for our use case,"['java', 'android']" +31004,drag a zoomed image within a div clipping mask using jquery draggable i am creating an interface to allow a user to zoom in on an image and drag the zoomed version around within a clipping mask div i have a div 200px by 200px that i set overflow hidden on then i load a std img img srcetc into the div that is say 10px by 10pxthen i use jquery myimagedraggable containment 8583992 the numbers are hard coded so far i can only find them by trial and errorthe problem is that each time i make a change to the page ie insert another element above my container div the page size changes and my hard coded x1 y1 x2 y2 stop working correctlythe main issue is i do not fully understand x1 y1 x2 y2 here is the jquery docs regarding thisam i right in thinking that x1 is the left most draggable point x2 is the right most draggable point and same for y1 y2if so what would be the best strategy to calculate them dynamicallyalso any other quick and easy solutions to the main problem of drag a zoomed image within a div clipping mask would be much appreciated,"['jquery', 'html']" +31019,how to execute a wix custom action dll file with dependencies i want to create a customaction c dll file that depends on a thirdparty net dll in this specific case it is mysqldatadll i have the c custom action dll file working with the wix fragment below i am just trying to figure out how to safely add a dependency to the custom action note i do not actually need this thirdparty dll file file for the installed application to run binary idmycustomactiondll sourcefilemycustomactioncadll customaction idfixupconfigformysql returncheck installexecutesequence custom actionfixupconfigformysql afterinstallfilesnot installedcustom installexecutesequencedo i need to install the thirdparty dll file mysqldatadll in order to get the custom action to runcan i just add another binary tag with the thirdparty dll file,['c#'] +31024,how to focus on a form input text field on page load using jquery this is probably very simple but could somebody tell me how to get the cursor blinking on a text box on page load,"['javascript', 'jquery', 'html']" +31039,is there a jms queue browser gui tool that can integrate with glassfish i have a few jms queues created on glassfish 21 server i need a gui browser that lets me view the messages being sent to the queue in real timei read about hermes on another so thread but i am not sure if it works with glassfishi also installed this plugin for netbeans but it is not working for me i get a capsmanagementremoteexception exception,['java'] +31048,how can i modify my shuntingyard algorithm so it accepts unary operators i have been working on implementing the shuntingyard algorithm in javascript for classhere is my work so farvar userinput promptenter in a mathematical expressionvar postfix infixtopostfixuserinputvar result evaluateexpressionpostfixdocumentwriteinfix userinput brdocumentwritepostfix rpn postfix brdocumentwriteresult result brfunction evaluateexpressionexpression var tokens expressionsplit09 var evalstack while tokenslength 0 var currenttoken tokensshift if isnumbercurrenttoken evalstackpushcurrenttoken else if isoperatorcurrenttoken var operand1 evalstackpop var operand2 evalstackpop var result performoperationparseintoperand1 parseintoperand2 currenttoken evalstackpushresult return evalstackpopfunction performoperationoperand1 operand2 operator switchoperator case return operand1 operand2 case return operand1 operand2 case return operand1 operand2 case return operand1 operand2 default return function infixtopostfixexpression var tokens expressionsplit09 var outputqueue var operatorstack while tokenslength 0 var currenttoken tokensshift if isnumbercurrenttoken outputqueuepushcurrenttoken else if isoperatorcurrenttoken while getassociativitycurrenttoken left getprecedencecurrenttoken getprecedenceoperatorstackoperatorstacklength1 getassociativitycurrenttoken right getprecedencecurrenttoken getprecedenceoperatorstackoperatorstacklength1 outputqueuepushoperatorstackpop operatorstackpushcurrenttoken else if currenttoken operatorstackpushcurrenttoken else if currenttoken while operatorstackoperatorstacklength1 if operatorstacklength 0 throwparenthesis balancing error shame on you outputqueuepushoperatorstackpop operatorstackpop while operatorstacklength 0 if operatorstackoperatorstacklength1match outputqueuepushoperatorstackpop else throwparenthesis balancing error shame on you return outputqueuejoin function isoperatortoken if tokenmatch return false else return truefunction isnumbertoken if tokenmatch09 return false else return truefunction getprecedencetoken switch token case return 9 case case case return 8 case case return 6 default return 1 function getassociativitytoken switchtoken case case case case return left case return right it works fine so far if i give it 53 8 it will outputinfix 53 8 postfix rpn 5 3 8 result 64 however i am struggling with implementing the unary operators so i could do something like53 8what would be the best way to implement unary operators negation etc also does anyone have any suggestions for handling floating point numbers as wellone last thing if anyone sees me doing anything weird in javascript let me know this is my first javascript program and i am not used to it yet,['javascript'] +31051,how can i test tilt efftect iphone simulator i am trying to write a game that game uses tilt effect but i do not know how to test it on iphone simulator 30 i search it on internet but the result is zero how can i,['iphone'] +31065,what is join in jquery what is join in jquery for examplevar newtext ptextsplit joinspan span,['jquery'] +31067,how to have quotation marks in html input values i have following problem from the server side i get a string like hoschibrotheri want to put this string into a input valuemystring this results in something likeinput valuehoschi brother which obviously does not work any workarounds for thisdoes escaping the character with quot work within the value tagthanks for your helptobi,['html'] +31072,which version of the net framework will sharepoint 2010 use now that the sharepoint conference has started and at least some of the nda restrictions have been liftedi was wondering which version for the net framework sharepoint 2010 will use am especially interested in if sharepoint workflow is built on the workflow in net 40 since we have had problems with performance in workflow for net 35,['.net'] +31075,debugging a generated net assembly from within the application that generated it the question in short how can i debug the code generated during a debugging session on the generating program see code belowi am facing the following issue i would like to debug into dynamically generatedcompiled code from the application that generates it i provided an oversimplified example to clarify it this example does not need debugging my real app generates many more lines and code that really justify debugging believe me i would like to know if there is a way to debug or put a breakpoint at helloworld stepping into the invokemethod call does not work maybe a solution involves code modification at the call sites to the generated assemblyi had a look at many questions already for example but none was helpful in solving the problem if solvable at alli took code from as a base and fixed the obsoleted calls beside this i generated the assembly onthefly in memory and the calls are working well i generated explicitly an assembly with debug information what gives me hope why would there be the option if debugging is not possibleusing systemusing systemtextusing systemiousing microsoftcsharpusing systemcodedomcompilerusing systemreflectionnamespace dynamicassembly class createcompileexecute stathread static void mainstring args creates a text file to store the new class stringbuilder builder new stringbuilder builderappendlineusing system builderappendlinenamespace csharpfriendsrocks builderappendline builderappendlineclass csharpfriends builderappendline builderappendlinepublic csharpfriends consolewritelinethe csharpfriends type is constructed builderappendlinepublic void helloworld consolewritelinehello world csharpfriendscom rocks builderappendline builderappendline create the c compiler csharpcodeprovider cscompiler new csharpcodeprovider input params for the compiler compilerparameters compilerparams new compilerparameters compilerparamsoutputassembly csharpfriendsdll compilerparamsgenerateinmemory true compilerparamsincludedebuginformation true compilerparamsreferencedassembliesaddsystemdll compilerparamsgenerateexecutable false generate the dll run the compiler and build the assembly compilerresults results cscompilercompileassemblyfromsource compilerparams buildertostring load the generated assembly into the applicationdomain assembly asm resultscompiledassembly type t asmgettypecsharpfriendsrockscsharpfriends bindingflags enumeration specifies flags that control binding and the way in which the search for members and types is conducted by reflection the following specifies the access control of the bound type bindingflags bflags bindingflagsdeclaredonly bindingflagspublic bindingflagsnonpublic bindingflagsinstance construct an instance of the type and invoke the member method object obj tinvokememberhelloworld bflags bindingflagscreateinstance null null null call the method tinvokememberhelloworld bflags bindingflagsinvokemethod null obj null,"['c#', '.net']" +31077,f listmap equivalent in c is there an equivalent to fs listmap function in c ie apply a function to each element in the list and return a new list containing the resultssomething like public static ienumerabletresult maptsource tresultthis ienumerabletsource source functsource tresult funkyforeach tsource element in sourceyield return funkyinvokeelementis there already a built in way or should i just write the custom extension,"['c#', '.net']" +31078,how do you plan your rails app i am starting a rails app for a customer and am considering either creating a mind map or jumping straight to a cucumber specificationhow do you plan your rails appas an additional question say you also start with cucumber at which point would you write unit tests before satisfying the specifications,['ruby-on-rails'] +31092,how to easily thisplay double quotes in strings in c if you have a string with a numerous double quotes in php you can do thisfilewritelinecontrolsformfield namestrasse labeltextstrassein c you have to do thisfilewritelinecontrolsformfield namestrasse labeltextstrasseis there a way in c to do what you can do above in php something like the ctemp which you can do so that you do not need double slashesthanks fredrik that makes even quotes and curly brackets in a stringformat fairly readable filewritelinestringformattextbox textbinding 0 styledynamicresource formularfieldtextbox fieldname,['c#'] +31107,how does the stls multimap insert respect orderings i have some data which come with a integer index i am continuous generating new data which needs to added to the collection of data i have sorted by that index at the same time i want to easily be able to go the start of the data and iterate through it this sounds like stdmultimap is just what i needhowever i also need data with the same index to be kept in the order in which it was inserted in this case meaning that when i iterate through the data i get to the earlier data before the later datadoes multimap do thisi have not found any guarantees that this is the case in the sgi manual i did not see any mention of whether i tried it on gcc 434 implementation and it seemed to be true for some limited test cases but of course i was wondering whether the standard demands this and i can rely on this factedit to be clearer in response to some of the answers i wanted the data sorted first by nonunique index and second by insertion time i had hoped that maybe the second part came for free with multimap but it seems like it does not,['c++'] +31113,how do i use waf to build a shared library i want to build a shared library using waf as it looks much easier and less cluttered than gnu autotoolsi actually have several questions so far related to the wscript i have started to writeversion001appnamelibmylibsrcdir blddir builddef set optionsopt opttool optionscompiler cc passdef configureconf confcheck toolcompiler cc confenvappend valueccflags stdgnu99 wall pedantic ggdbdef buildbld bldnew task gen features cc cshlib source c targetlibmylibthe line containing source c does not work must i specify each and every c file instead of using a wildcardhow can i enable a debug build for example currently the wscript is using the debug builds cflags but i want to make this optional for the end userit is planned for the library sources to be within a sub directory and programs that use the lib each in their own sub directories,['c'] +31128,asynchronous methods in nsoperation i am fetching some data from facebook connect using the fbconnect objectivec 20 framework and i am doing all that in an nsoperation it is in an nsoperation because i have several other operations that run as well and this is one of themthe problem is that all the fbconnect calls are asynchronous because of this the main method of the nsoperation quickly finishes and the operation is marked as completedis there some way to overcome this it would appear there are no synchronous options in fbconnectmany thanksmike,['iphone'] +31134,which python client library should i use for couchdb i am starting to experiment with couchdb because it looks like the perfect solution for certain problems we have given that all work will be on a brand new project with no legacy dependencies which client library would you suggest that i use and whythis would be easier if there was any overlap on the oses we use freebsd only has pysimplecouchdb already available in its ports collection but that librarys project website says to use couchdbkit instead neither of those come with ubuntu which only ships with couchdb since those two oses do not have an libraries in common i will probably be installing something from source and hopefully submitting packages to the ubuntu and freebsd folks if i have timefor those interested i would like to use couchdb as a convenient intermediate storage place for data passed between various services think of a message bus system but with less formality for example we have daemons that download and parse web pages then send interesting bits to other daemons for further processing a lot of those objects are illdefined until runtime heres some html plus a set of metadata and some actions to run on it rather than serialize it to an adhoc local network protocol or stick it in postgresql i would much rather use something designed for the purpose were currently using networkspaces in this role but it does not have nearly the breadth of support or the user community of couchdb,['python'] +31135,multidimensional arraylist or list in c is is possible to create a multidimensional list in ci can create an multidimensional array like so string results new string20 2but i would like to be able to use some of the features in a list or arraylist like being able to add and delete elements,['c#'] +31155,split button in net winforms i am looking for a split button in net winforms the kind where one side is a button and the other side has a dropdown button i see them used all over in windows like in the visual studio save as window so i figured they have got to have the control in some libraryi know there is one for toolstrips but i need one thats usable outside of toolstripsis there a microsoft library that has one or preferably a free libraryi am using net 35for an example,['.net'] +31165,iterate through a c array i have an array of structs that i created somewhere in my programlater i want to iterate through that but i do not have the size of the arrayhow can i iterate through the elements or do i need to store the size somewhere,['c'] +31167,architecture of a php app on amazon ec2 i recently experienced a flood of traffic on a facebook app i created mostly for the sake of education not with any intention of marketingneedless to say i did not think about scalability when i created the app i am now in a position where my meager virtual server hosted by mediatemple is not cutting it at all and it is really coming down to raw io of the machine since this project has been so educating to me so far i figured i would take this as an opportunity to understand the amazon ec2 platform the app itself is created in php using zend framework with a mysql backend i use application caching wherever possible with memcached i have spent the weekend playing around with ec2 spinning up instances installing the packages i want and mounting an ebs volume to an instancebut whats the next logical step that is going to yield good results for scalability do i fire up an ami instance for the mysql and one for the apache service or do i just replicate the instances out as many times as i need them and then do some sort of load balancing on the front end ideally i would like to have a centralized database because i do aggregate statistics across all database rows however this is not a hard requirement there are probably some application specific solutions i could come up with to work around thisi know this is probably not a straight forward answer so opinions and suggestions are welcome,['php'] +31172,c equivalent of c map i want to keep some totals for different accounts in c i would use stl like thismapstringdouble accounts add some amounts to some accountsaccountsfred 456accountsgeorge 100accountsfred 100cout fred owes me accountsfred endlnow how would i do the same thing in c,['c#'] +31175,link to in rails flash when a user fails login on my rails app i would like to point them to a password reset pageflashnotice login failed if you have forgotten your password you can link toreset it reset pathhowever i cannot use link to in a controller whats the best way to do this without mixing controller and view logicmy best guess is that the flash is the wrong place to do this but i would appreciate any input,['ruby-on-rails'] +31182,why is my transformable core data attribute not using my custom nsvaluetransformer i have a core data app with a fairly simple data model i want to be able to store instances of nsimage in the persistent store as png bitmap nsdata objects to save spaceto this end i wrote a simple nsvaluetransformer to convert an nsimage to nsdata in png bitmap format i am registering the value transformer with this code in my app delegate voidinitialize nsvaluetransformer setvaluetransformerpngdatavaluetransformer alloc init fornamepngdatavaluetransformerin my data model i have set the image attribute to be transformable and specified pngdatavaluetransformer as the value transformer namehowever my custom value transformer is not being used i know this as i have placed log messages in my value transformers transformedvalue and reversetransformedvalue methods which are not being logged and the data that is being saved to thisk is just an archived nsimage not the png nsdata object that it should bewhy is this not workinghere is the code of my value transformerimplementation pngdatavaluetransformer classtransformedvalueclass return nsimage class boolallowsreversetransformation return yes idtransformedvalueidvalue if value nil return nil ifnsiscontrollermarkervalue return value check if the value is nsdata ifvalue iskindofclassnsdata class nsexception raisensinternalinconsistencyexception formatvalue is not an nsdata instance value class return nsimage alloc initwithdatavalue autorelease idreversetransformedvalueidvalue if value nil return nil ifnsiscontrollermarkervalue return value check if the value is an nsimage ifvalue iskindofclassnsimage class nsexception raisensinternalinconsistencyexception formatvalue is not an nsimage instance value class convert the nsimage into a raster representation nsbitmapimagerep bitmap nsbitmapimagerep imagerepwithdata nsimage value tiffrepresentation convert the bitmap raster representation into a png data stream nsdictionary pngproperties nsdictionary dictionarywithobjectnsnumber numberwithboolno forkeynsimageinterlaced return the png encoded data nsdata pngdata bitmap representationusingtypenspngfiletype propertiespngproperties return pngdataend,['objective-c'] +31183,direct access to tablelayoutpanel cells i have a tablelayoutpanel where each cell contains a single panel i would like to be able to directly access any one of the cells by row and column and do something to the panel in it i cannot for the life of me figure out if i can access controls within a cell it would be great if i could do something like panel p layoutpanelcellxycontrols0 as panelpdosomethingcoolbut i cannot seem to get that kind of access even though it seems like something that should be quite possible,['c#'] +31192,ansi vs nonansi sql join syntax i have my businesslogic in 70 lines of tsql stored procedures and most of them has next join syntaxselect aa bb ccfrom a as a b as b c as cwhere ab bidand bc cidand cid paramwill i get performance growth if i will replace such query with thisselect aa bb ccfrom a as ajoin b as b on ab bidjoin c as c on bc cid and cid paramor they are the same,['sql'] +31193,how can i get an accurate utc time with python i wrote a desktop application and was using datetimedatetimeutcnow for timestamping however i have recently noticed that some people using the application get wildly different results than i do when we run the program at the same time is there any way to get the utc time locally without using urllib to fetch it from a website,['python'] +31197,anyway see why i get this concurrency violation in these few lines of code concurrency violation the updatecommand affected 0 of the expected 1 records here is the code any ideas why i get this errorprivate sqlitedataadapter da webfiles setup connection fill dataset etcdatatable dt thisdatasettableswebfilesdatarow newrow dtnewrownewrowpath urldtrowsaddnewrowthisda webfilesupdatethisdataset webfiles works to herenewrowcontent type test content typethisda webfilesupdatethisdataset webfiles get error here concurrency violation the updatecommand affected 0 of the expected 1 recordsthanks,['c#'] +31208,which html elements can receive focus i am looking for a definitive list of html elements which are allowed to take focus ie which elements will be put into focus when focus is called on them,['html'] +31216,visual c standards compliance i was wondering if and to what degree does microsofts visual c compiler conform to the current c c90c99 and c isoiec 148822003 standards unfortunately i am only able to find partial information on the subject i may be looking at all the wrong placesany pointers to related resources are much appreciated thanks in advanceeditsince is looks like this is a most touchy subject i would be content with a yesno answer on whether msvc wholly conforms to c90i have come to the understanding that this is not the case for c99 naturally and i still have no clue about cedit2thanks to everyone for their answers i have accepted mr rushakovs answer but upvoted all relevant answers which were all helpful,['c'] +31220,javascript advantages of object literal i have read that rather than simply writing a bunch of functions i should use object literalcan someone explain what the advantages of object literal are with examples because i do not understand thus farthanks,['javascript'] +31253,how to do the equivalent of a tsql select into into an existing table using tsql sqlserver 2005 i would like insert records from table table2 into an existing table table1as easily as i could enter it into a new table table1 usingselect facilabbr unitname sortnum into table1 from table2any ideas,['sql'] +31254,vim omnicompletion for java i have read heaps of blogs on vims supposedly great omnicompletion and yet no matter what i do i cannot get it to work satisfactorily it took me ages to figure thiscover that the version of ctags that is preinstalled on my system was the emacs one and did not have the recurse option but now that i have run ctagsexuberant on my copy of the openjdk sources to attempt to get some kind of code completion going vim hangs whenever i try to invoke it with cn or cpall i really want is something that works like the code completion in eclipse i like vim as an editor but eclipse just has those extra features outofthebox which vim seems to fail with eclipse with a vimode plugin was not particularly useful to me and it is too much of a memory and cpu hog to be of any use eclim does not quite like me eithercan anyone suggest a simpler way to get some kind of code completion working in vim that actually works,['java'] +31271,do not expose symbols from a used library in own static library i am writing a reusable static library for the iphone following the directions provided herei want to use minizip in my library internally but do not want to expose it to the userit should be possible for the user to include minizip themselves possibly a different version and not cause clashes with my inner minizip versionis this possibleediti have tried adding fvisibilityhidden to additional compiler flags for minizip files and changing functions to be private extern and attribute visibilityhidden but it still seems to produce defined external symbols0918 t unzopen058e t unzopen201d06 t unzopencurrentfile01d6b t unzopencurrentfile2edit 2apparently the symbols marked with these annotations are only made private by the linker which never happens when xcode builds the sources since it adds the c parameter compile or assemble the source files but do not link,"['iphone', 'c', 'objective-c']" +31280,ini4j how to get all the key names in a setting i have decided to use ini file to store simple keyvalue pair configuration for my java application i googled and searched stackoverflow and found that ini4j is highly recommended for parsing and interpreting ini files in java i spent some time reading the tutorial on ini4j site however i was not sure how to get all the key values for a setting in an ini filefor instance if i have a ini file like this food namesteaktypeamericanprice20 school deptcseyear2majorcomputer scienceand assume that i do not know names of keys ahead of time how do i get the list of keys so that i can eventually retrieve the values according to keys for instance i would get an array or some kind of data structure that contains name type and price if i get a list of keys for foodcan someone show me an example where you would open an ini file parse or interpret it so that an app knows all the structure and values of the ini file and get the list of keys and values,['java'] +31289,spring set property of one bean by reading the property of another bean is it possible to set the property of one bean by reading the property of another bean for instance suppose i hadclass a void setlistlist listclass b list getlisti would like spring to instantiate both classes and call as setlist method passing in the result of calling bs getlist method the spring configuration might look something likebean idb classbbean ida classa property namelist refb refpropertylistbeanalas this madeup xml does not workwhy not just inject b into a because i do not want to introduce the extra dependency a is only dependent list not on b,['java'] +31295,python problem executing popen in cron i use popen to execute commands in a python script and i call it via croncron calls out this script but the behavior is not the same if i call it by handsourcefrom subprocess import popen pipepp popenusrbinwhich iptables shelltrue stdoutpipedata for ln in ppstdout data datalnif data print koelse print ok databy hand python homeusertestpy sbiniptablesby cron in tmperr cron usrbinpython homeusertestpy tmperr cronkokokowhy does cron not run this script normally,['python'] +31302,how to monitor global modifier key state in any application i am using some carbon code in my cocoa project for handling global key events shortcuts from other applications currently i have setup a keventhotkeyreleased event handler and i can successfully obtain hot keys when my application is not active that triggers some operation in my applicationthe problem i have with the behavior of keventhotkeyreleased issay for example i press the cmdshiftp key combination as soon as i release the p key the hot key event is triggered i need to be able to trigger the event or manually trigger it when all of the keys are unpressed ie the cmd and shift keys are released tooit is easy to monitor for hot keys but i have seen nothing for monitoring individual keystrokes if i could monitor the modifier key states i would be in businessany hints on how to do thisthanks in advanceupdatei have tried using keventrawkeyup and keventrawkeymodifierschanged but while keventhotkeyreleased works those two do not even though i set them up in the exact same way as keventhotkeyreleasedeventtypespec eventtypes keventclasskeyboard keventhotkeyreleased keventclasskeyboard keventrawkeyup changing the order in the list does not help nor does removing keventhotkeyreleasedosstatus err installapplicationeventhandlerglobalhotkeyhandler geteventtypecounteventtypes eventtypes null null err noerr after this linethe globalhotkeyhandler method is called for keventhotkeyreleased but not for keventrawkeyup for some reason i cannot seem to grasp heres what my globalhotkeyhandler method looks likeosstatus globalhotkeyhandlereventhandlercallref nexthandler eventref anevent void userdata nslogsomething happenedis there an additional call that needs to be made or something else i forgotnb at first glance it seems like it could be that access for assistive devices is thisabled but it is not so i am pretty cluelessupdate 2i investigated a bit on the cgeventtap leibowitzn suggested and i came up with this setupcfmachportref keyupeventtap cgeventtapcreatekcghideventtapkcgheadinserteventtapkcgeventtapoptionlistenonlykcgeventkeyupkeyupcallbacknullcfrunloopsourceref keyuprunloopsourceref cfmachportcreaterunloopsourcenull keyupeventtap 0cfreleasekeyupeventtapcfrunloopaddsourcecfrunloopgetcurrent keyuprunloopsourceref kcfrunloopdefaultmodecfreleasekeyuprunloopsourceref and the callbackcgeventref keyupcallback cgeventtapproxy proxy cgeventtype type cgeventref event void refcon nslogkeyup event tapped return eventas you can see i am using kcgeventkeyup as the mask for the event tap but somehow i am receiving mouse down events update 3ok forget that i overlooked the line in the doc that said to use cgeventmaskbitkcgeventkeyup for this parameter so the correct call iscgeventtapcreatekcghideventtapkcgheadinserteventtapkcgeventtapoptionlistenonlycgeventmaskbitkcgeventkeyupkeyupcallbacknulli am still having a problem though modifier keys do not trigger the kcgeventkeyupupdate 4ok forget that again i am bound to answer to my own questions 5 minutes after asking them today huhto intercept modifier keys use kcgeventflagschangedcgeventtapcreatekcghideventtapkcgheadinserteventtapkcgeventtapoptionlistenonlycgeventmaskbitkcgeventflagschangedcallbackfunctionnullso in essence i got the key and modifier key state detection working but i am still interested in knowing why keventrawkeyup does not worknb also note that i am developing on tiger with the goal of having support for new and older versions of the os as much as possible cgeventtap is 104 only so i will be using this for now but a backwardscompatible solution would be welcome,['objective-c'] +31307,conversion of systemarray to list last night i had dream that the following was impossible but in the same dream someone from so told me otherwise hence i would like to know if it it possible to convert systemarray to listarray ints arraycreateinstancetypeofint 5intssetvalue10 0intssetvalue20 1intssetvalue10 2intssetvalue34 3intssetvalue113 4tolistint lst intsoftypeint not working,['c#'] +31319,convert a hashset to an array in net how do i convert a hashsett to an array in net,['.net'] +31322,how to fix a documentbody is nullerror i am having a documentbody is null error in my javascript because i usewindowwidthas value to assign to a variable in mydocumentreadyfunctioni would be very grateful to anyone who could help me with thiskind regardsedit sorry if this all was unclear i have a demo at at first the theme will load but then becomes white because of the error but when you reload you can see the whole theme because then he knows the value for windowwidthi am using this code to center the layout not possible with css because the left needs to have a width aswellfunction positioneerelement breedte documentbodyclientwidth 1124 2 bg leftcss width breedte containercss marginleft breedte i call function positioneerelement in the load functionsorry if this was not clear i though it was not necessary to put the demo here for this nor the codehowever i would like to thank the people who are trying to help,"['javascript', 'jquery']" +31325,how can i modify a python traceback object when raising an exception i am working on a python library used by thirdparty developers to write extensions for our core applicationi would like to know if it is possible to modify the traceback when raising exceptions so the last stack frame is the call to the library function in the developers code rather than the line in the library that raised the exception there are also a few frames at the bottom of the stack containing references to functions used when first loading the code that i would ideally like to remove toothanks in advance for any advice,['python'] +31326,best php qa tools i am looking for qa tools for php i am used to pmd findbugs and checkstyle in the java world are there some similar tools for php doing code analysisso far i have found these but not tested yetphplintpmds cpd modulephp codesniffer,['php'] +31334,how to set selected filter on qfiledialog i have a open file dialog with three filtersqstring filename qfiledialoggetopenfilename this title directory trjpeg jpg jpeg tiff tif all files this thisplays a dialog with jpeg selected as the default filter i wanted to put the filter list in alphabetical order so all files was first in the list if i do this however all files is the default selected filter which i do not wantcan i set the default selected filter for this dialog or do i have to go with the first specified filteri tried specifying a 5th argument qstring to set the default selected filter but this did not work i think this might only be used to retrieve the filter that was set by the user,['c++'] +31337,crosscompile apache portable runtime to the iphone this is a followup to a previous question on crosscompiling for the iphonebasically i am trying to compile the apache portable runtime apr version 138 latest for the iphone i am currently running into the following error during the configuration stepchecking for working process shared locks configure error in usersmichaelsafyandownloadsapr138configure error cannot run test program while cross compilingsee configlog for more detailsi am invoking the configure script via iphone31configure thisabledso enablethreads where iphone31configure is the following script that i have cookedup to invoke the configure script binbash program iphone31configure authors michael aaron safyan synopsis this program runs the configure script generated by the gnu autotools in order to crosscompile thirdparty libraries for the iphone 31 sdk run this script while in a directory containing an autotools configure script once you run this you can use make and sudo make install to build the library an install prefix of optiphone31 is usedunset cpathunset c include pathunset cplus include pathunset objc include pathunset libsunset dyld fallback library pathunset dyld fallback framework pathexport build darwin veruname rexport sdkver31export devrootdeveloperplatformsiphoneosplatformdeveloperexport sdkrootdevrootsdksiphoneossdkversdkexport pkg config pathdeveloperplatformsiphoneosplatformdevelopersdksiphoneossdkversdkusrlibpkgconfigdeveloperplatformsiphoneosplatformdeveloperusrlibpkgconfigoptiphonesdkverlibpkgconfigusrlocaliphonesdkverlibpkgconfigexport prefixoptiphonesdkverexport asdevrootusrbinasexport ascppdevrootusrbinasexport ardevrootusrbinarexport ranlibdevrootusrbinranlibexport cppflagspipe nocprecomp isdkrootusrlibgccarmappledarwin9421include isdkrootusrinclude idevrootusrinclude ioptiphonesdkverinclude iusrlocaliphonesdkverincludeexport cflagsstdc99 arch armv6 pipe nocprecomp sysrootsdkroot isystem sdkrootusrlibgccarmappledarwin9421include isystem sdkrootusrinclude isystem devrootusrinclude isystem optiphonesdkverinclude isystem usrlocaliphonesdkverincludeexport cxxflagsstdc99 arch armv6 pipe nocprecomp sysrootsdkroot isystem sdkrootusrlibgccarmappledarwin9421include isystem sdkrootusrinclude isystem devrootusrinclude isystem optiphonesdkverinclude isystem usrlocaliphonesdkverincludeexport ldflagsarch armv6 sysrootsdkroot lsdkrootusrlib ldevrootusrlib loptiphonesdkverlib lusrlocaliphonesdkverlibexport cppdevrootusrbincppexport cxxcppdevrootusrbincppexport ccdevrootusrbingcc42export cxxdevrootusrbing42export lddevrootusrbinldexport stripdevrootusrbinstripif d devroot then echo the iphone sdk could not be found folder devroot does not exist exit 1fiif d sdkroot then echo the iphone sdk could not be found folder sdkroot does not exist exit 1ficonfigure prefixprefix buildi386appledarwinbuild darwin ver hostarmappledarwin9 enablestatic thisableshared ac cv file dev zerono ac cv func setpgrp voidyes the error that configure is giving me is not the first time i have received a message along the lines of cannot run test program while cross compiling in fact the ac cv file dev zerono and ac cv func setpgrp voidyes elements in the iphone31configure script cause two similarly failing tests to be bypassed the problem i am having is that i do not know how to bypass this check that is i do not know what variables to set to bypass this test and any additional tests that try to run executables built for the target platform i was able to bypass the earlier two similar tests simply because i was able to locate the workaround on google does anyone know what variables to set or another way to bypass this checkif anyone knows a way to suppress all tests that cannot be executed when crosscompiling or if you just know how to suppress this specific check i would be greatly appreciative thank you very much,['iphone'] +31352,how can i grab the color of a pixel on my desktop linux i want to grab the color of a pixel with known coordinates on my linux desktopuntil now i have used import window somewindow crop 1x1xy tmpgrabjpgthen extracting the pixel value using python and pilthis does the job but since import grabs the whole window before cropping it is very slow are there any clever way to grab the color of only one pixel i know both relative window and absolute coordinates a python or shell script would be preferable but if you know some clever cx11 functions also please let me know,['python'] +31358,how to launch and run external script in background i tried these two methodsossystempython testpysubprocesspopenpython testpy shelltrueboth approaches need to wait until testpy finishes which blocks main process i know nohup can do the job is there a python way to launch testpy or any other shell scripts and leave it running in backgroundsuppose testpy is like thisfor i in range0 10 print iboth ossystem or subprocesspopen will block main program until 10 lines of output thisplayed what i want is let testpy runs silently and thisplay main program output only main program may quie while testpy is still running,['python'] +31362,using shared ptr in dllinterfaces i have an abstract class in my dllclass ibase protected virtual ibase 0 public virtual void f 0i want to get ibase in my exefile which loads dllfirst way is to create following functionibase createinterfaceand to add the virtual function release in ibasesecond way is to create another functionboostshared ptribase createinterfaceand no release function is neededquestions1 is it true that the destructor and memory deallocation is called in the dll not in exefile in the second case2 does the second case work well if exefile and dll was compiled with different compilers or different settings,['c++'] +31366,how to best configure php to handle a utf8 website what extensions would you recommend and how should php be best configured to create a website that uses utf8 encoding for everything egpage output is utf8forms submit data encoded in utf8internal processing of string data eg when talking to a database are all in utf8 as wellit seems that php does not really cope well with multibyte character sets at the moment so far i have worked out that mbstring looks like an important extensionis it worth the hassle,['php'] +31368,if statement weirdness in visual studio 2008 i have come across a problem so strange that i have recorded my session because i did not think anyone would belive mei came across a bug that seems to be at very fundamental level this is a single threaded application and all im doing is evaluating a booleanthe boolean equals false however the if statement is executing as if it were truesort of youll see what i mean i have cleaned the solution and rebuilt many times no idea whats going oni would love some explanations please,"['c#', '.net']" +31382,android custom separator or even item in listview depening on content of item i have a listview with items containing information about places with a rating and the thistance to the current locationthe items are sorted into groupsgroup 1 within 500mgroup 2 500m 1kmgroup 3 1km 15kmwithing these groups the items are sorted by their ratingnow i put out these items via my custom adapter extension of baseadapter into the listview which works perfectlyhowever what i would like to do is to put a separator before the each first item of each group this separator can be a textview saying eg 500m 1km followed by all the listview items in that groupany idea on how to realize this,['android'] +31383,how to sleep or pause a pthread in c on linux i am developing an application in which i do multithreading one of my worker threads thisplays images on the widget another thread plays sound i want to stopsuspendpausesleep the threads on a button click event it is same as when we click on video player playpause buttoni am developing my application in c on linux platform using the pthread library for threadingcan somebody tell me how i achieve threads pausesuspend,"['c++', 'c']" +31394,passing variable argument list to sprintf i would like to write a function that amongst other things accepts a variable number of arguments and then passes them to sprintffor examplephpfunction some funcvar s sprintfvar arguments that were passed some funcblah d blah numberhow do i do this in php,['php'] +31399,apple magic mouse api i just bought a magic mouse and i like it pretty much but as a mac developer it is even cooler but there is one problem is there already an api available for it i want to use it for one of my applications for example detect the users finger positions swipe or stretch gestures etcdoes anyone know if there is an api for it and how to use it,['objective-c'] +31416,sql server sum of multiple rows including where clauses i have a table that looks something like the following propertyid amount type enddate 1 100 rent null 1 50 water null 1 60 elec null 1 10 other null 2 70 rent null 2 10 water nullthere will be multiple items billed to a property also billed multiple times for example rent could be billed to property 1 12 times over a year however the only ones i am interested for are those with enddate of null in otherwords currenti would like to achieve propertyid amount 1 220 2 80i have tried to do something like this select propertyid sum as total costsfrom mytablehowever in the sum would i be forced to have multiple selects bringing back the current amount for each type of charge i could see this becoming messy and i am hoping for a much simpler solutionany ideas,['sql'] +31417,c auto resize form to datagridviews size i have a form and a datagridview i populate the datagridview at runtime so i want to know how do i resize the form dynamically according to the size of the datagridview is there any sort of property or method or do i have to determine the size myself and update accordingly,['c#'] +31419,breaking my head to get url routing in iis 7 hosting environment aspnet hi i am trying to implement aspnet url routing using the systemwebrouting and this seems to work fine on my localhost however when i go live i am getting an iis 7s 404 error file not found fyi the hosting uses windows server 2008 iis7i think this is making some difference in handling the routing mechanism but i am not able to figure out whats exactly happening below are the settings and changes that i have made so far to get it work and to give some credit to myself it works absolutely fine locallywebconfig settingsand then i have a systemwebserver section that has the following markupsystemwebserver validation validateintegratedmodeconfigurationfalse modules runallmanagedmodulesforallrequeststrue remove namesession add namesession typesystemwebsessionstatesessionstatemodule add nameurlroutingmodule typesystemwebroutingurlroutingmodule systemwebrouting version3500 cultureneutral publickeytoken31bf3856ad364e35 modules handlers add nameurlroutinghandler preconditionintegratedmode verb pathurlroutingaxd typesystemwebhttpforbiddenhandler systemweb version20 cultureneutral publickeytokenb03f5f7f11d50a3a handlers systemwebserverthen in the application start section i have defined one route as followsvoid application startobject sender eventargs e registerroutesroutetableroutes void registerroutesroutecollection routes routesadd myroute new routeproductdetailproductidproductname new myroutehandlerproductdetailaspxfinally myroutehandler looks as follows public ihttphandler gethttphandlerrequestcontext requestcontext var thisplay pagebuildmanagercreateinstancefromvirtualpath virtualpath typeofpage httpcontextcurrentitemsproductid requestcontextroutedatavaluesproduct return thisplay and on the routed page i am grabbing the product id as followsproductid inthttpcontextcurrentitemsproductand this is the end of my mess and this works fine locally i have been trying this for a while but did not succeeded so farany help will be deeply appreciatedthanks,"['c#', 'asp.net']" +31436,parser for the mathematica syntax is there a built parser that i can use from c that can parse mathematica expressionsi know that i can use the kernel itself to parse an expression and use netlink to retrieve the tree structure but i am looking for something that doesnt rely on the kernel,['c#'] +31451,ftp nlist command not working i am using the following code to connect to a ftp server and get a list of files it works ok on my local machinefedora 11 but not on production running ubuntu where the ftp nlist method returns falseftpinfo arraydirectory somewebsitecom user someuser password somepass port 21 timeout 30connectionid ftp connectftpinfodirectory ftpinfoport ftpinfotimeoutloginresult ftp loginconnectionid ftpinfouser ftpinfopasswordfiles ftp nlistconnectionid var dumpfilesftp closeconnectionidreturns an array of files on my machine and false on productionwhat makes this particularly annoying is that on both of the cases it manages to connect and login and successfullyvar dumploginresultreturns booltrue,['php'] +31460,copying delegates i was just reading a page on events on msdn and i came across a snippet of example code that is puzzling methe code in question is this make a temporary copy of the event to avoid possibility of a race condition if the last subscriber unsubscribes immediately after the null check and before the event is raisedeventhandlercustomeventargs handler raisecustomeventi understand the intentions of the code but i fail to see how that particular line is making a copy of anything all it is doing is copying the reference it is not actually making a deep copy of the delegate instance so to that end it does not actually prevent the race condition at allam i missing something obvious here,['c#'] +31462,how import pydev project into interactive console newbie question i am just getting started with python and pydevi have created a project playground with standard srcroot subfolder in there i have created examplepyhow do i import my example module into pydevs interactive console import example gives importerror no module named example,['python'] +31474,why does flowing off the end of a nonvoid function without returning a value not produce a compiler error ever since i realized many years ago that this does not produce an error by default in gcc at least i have always wondered whyi understand that you can issue compiler flags to produce a warning but should not it always be an error why does it make sense for a nonvoid function not returning value to be validan example as requested in the commentsinclude stdiohint stringsizeint main char cstring5 printf the last char is cn cstringstringsize1 return 0compiles,"['c++', 'c']" +31477,c graphic drawing library does anyone know whats the best graphic drawing library for c i want a lib that can draw basic shapes and can make image editing gradients and vector or 3d would be great tothe windows drawing functions are complicated and are not very advanced,['c++'] +31502,how to order by maximum of two column which can be null in mysql create table jobs id integer unsigned not null auto increment salaryminus integer unsigned default null salaryplus integer unsigned default null i want to do something like select from jobs order by maxofsalaryminus salaryplus limit 10maxofnull10 should be 10how to implement the maxof,"['sql', 'mysql']" +31516,how to call a function inside itself i have a function that generates a key of 4 characters that has to be unique for each time in order to do that the function first generates a key and then checks a database table to see if it is in use by someone elseif it is not in use it returns the key else it calls itself again but this causes the function to do an infinite loop which is a nono heres the whole functionfunction key generatorlength 4 i have subsequently left out the generating code which is not necesarry in this case key x if thisuser modelvalid keykey true return key else thiskey generator4 what is the correct way to call the function againby the way i am using codeigniter hence this,['php'] +31539,uses of c comma operator you see it used in for loop statements but it is legal syntax anywhere what uses have you found for it elsewhere if any,"['c++', 'c']" +31568,how to get jquery tablesorter to sort descending by default i cannot figure this out this question was also asked here with no responsei have tried tablesorterdefaultssortinitialorder descand altering the jquerytablesorterjs file to default to desc but it does not work when i click on the column headers the first sort is still ascending so the user has to click twice to descend the valueshow can i get tablesorter to sort by descending by default,"['javascript', 'jquery']" +31588,declaring instance variables iterating over a hash i want to do the followingi want to declare the instance variables of a class iterating over a dictionarylet us assume that i have this hashhash key1 value1key2 value2key3 value3and i want to have each key as instance variable of a class i want to know if i could declare the variables iterating over that hash something like thisclass myclass def initialize hash key1 value1key2 value2key3 value3 hasheach do kv k v end endendi know this does not work i only put this piece of code to see if you could understand what i want more clearlythanks,['ruby'] +31592,how can i know the day name from a selected date i have this datetimenow or 23102009i want this fridayfor local datetime gmt5 and using gregorian calendarthanks,['c#'] +31596,should webbrowsers allow to clearexpire cache programmatically currently browsers have incomplete caching implementation it only allows to set expiration or keep immediate expiration important 3rd option to expire cache programmatically is missing without that 3rd option developers cannot deploy new version of code efficiently and reliably if they use 2nd option it is inefficient if they have framework of many small files combining many small files into one is not efficient because any small change will cause whole framework to be deployed instead of one single file if they use 1st option updates will not get to user until cache expiration which creates compatibility problems between server side code and client side code and potentially between different parts of client side code setting expiration requires prediction of future deployment which is inconvenient and will thisallow quick bug fixeswhen people ask about that problem some suggest to use version numbers or other temporary ids to trick browser cache by loading unique urls the problem with it is that it puts unnecessary overhead on network and local file system to load and store unnecessary old versions and tons of unique urls it almost defeats the purpose of caching by url the right solution is to allow programmer of a web site to clean cache of files that came only from that web site that way list of updated files could be requested and cache of newer files would be cleaned to allow browser to load fresh versionsproper caching mechanism is simple and powerful pattern that could boost all web clientside development to new levels i only wonder why browser producers did not implement it yet,['javascript'] +31600,why this warning from ibm xl cc compiler heres a minimum code example that illustrates the probleminclude iostreamclass thing noncopyable thingconst thing thing operatorconst thing int and public thingint n and n int getvalue const return and void showconst thing t stdcout tgetvalue stdendlint main show3this yields the same errorint main show thing3 ibm xl cc 80 compiler under aix emits these warningstestwarningcpp line 249 15400306 w the private copy constructor thingconst thing cannot be accessedtestwarningcpp line 249 15400308 i the semantics specify that a temporary object must be constructedtestwarningcpp line 249 15400309 i the temporary is not constructed but the copy constructor must be accessiblei also tried g 412 with wall and pedantic and got no diagnostic why is access to the copy constructor required here how can i eliminate the warning besides making the object copyable which is outside my control or making an explicit copy to pass when the reallife object is expensive to copy,['c++'] +31606,java mechanisms at use in lambdaj closures lamdbaj allows the definition of closures in the java language various examples can be found heremy question is regarding the underlying java mechanisms at use for instance to define the println closure the following code is usedclosure println closure ofsystemoutprintlnvarstringclass this closure can be subsequently executed viaprintlnapplyfoobari am curious as to what mechanisms in java would allow the call to ofprintln to become associated with the println instance itself naturally the lambdaj source code is available to read but i was hoping for a slightly higher level explanation if anyone has one my reflection skills go as far as a bit of introspection and executing methods dynamically,['java'] +31608,eat sleep and breathe unit testingtddbdd i do write unit tests while writing apis and core functionalities but i want to be the cool fanboy who eats sleeps and breathes tdd and bdd whats the best way to get started with tddbdd the right way any books resources frameworks best practicesmy environment is java backend with grails frontend integrated with several external web services and databases,['java'] +31613,java solutions for thistributed transactions andor data shared in cluster what are the best approaches to clusteringthistributing a java server application i am looking for an approach that allows you to scale horizontally by adding more application servers and more database serverswhat technologies software engineering techniques or specific technologies would you suggest to approach this type of problemwhat techniques do you use to design a persistence layer to scale to many readerswritersscale application transactions and scale access to shared data best approach is to eliminate shared data what techniques can you apply to eliminate shared datadifferent approaches seem to be needed depending on whether your transactions are read or write heavy but i feel like if you can optimize a write heavy application that would also be efficient for readthe best solution would allow you to write a java application for a single node and hopefully hide most of the details of accessinglocking shared data in a thistributed environment the most difficult issue always comes down to having multiple transactions accessing shared data there seems like there is 2 common approaches to concurrent transactionsexplicit locks which is extremely error prone and slow to coordinate across multiple nodes in a thistributed systemsoftware transactional memory stm aka optimistic concurrency where a transaction is rolled back during a commit if it thiscovers that shared state has changed and the transaction can later be retriedwhich approach scales better and what are the tradeoffs in a thistributed systemi have been researching scaling solutions and in general applications that provide an example of how to scale such asterracotta provides transparent scaling by extending the java memory model to include thistributed shared memory using javas concurrency locking mechanism synchronized reentrantreadwritelocksgoogle app engine java allows you to write java or python applications that will be thistributed amongst cloud servers where you thistribute what server handles a transaction and you use bigtable to store your persistent data not sure how you transactions that access shared data or handle lock contentions to be able to scale effectivelydarkstar mmo server darkstar is suns open source mmo massively multiplayer online game server they scale transactions in a thread transactional manner allowing a given transaction to only run for a certain amount and committing and if it takes to long it will rollback kinda like software transactional memory they have been doing research into supporting a multinode server setup for scalinghibernates optimistic locking if you are using hibernate you can use their optimistic concurrency support to support software transactional memory type behaviorapache couchdb is supposed to scale to many readerwriter dbs in a mesh configuration naturally is there a good example of how you manage locking data or ensuring transaction isolationjcache scaling read heavy apps by caching results to common queries you can use in google appengine to access memcached and to cache other frequently read dataterracotta seems to be the most complete solution in that you can easily modify an existing server application to support scaling after defining root objects and autolockreadwrite methods the trouble is to really get the most performance out of a thistributed application optimization for thistributed systems is not really an after thought you kinda have to design it with the knowledge that object access could potentially be blocked by network io to scale properly it seems like it always comes down to partitioning data and load balancing transactions such that a given execution unit cpu core thread thistributed application node db master node it seems like though to make any app scale properly by clustering you need to be able to partition your transactions in terms of their data access readswrites what solutions have people come up with to thistribute their applications data oracle google bigtable mysql data warehousing and generally how do you manage partitioning data many write masters with many more read dbs etcin terms of scaling your data persistence layer what type of configuration scales out the best in terms of partitioning your data to many readersmany writers generally i would partition my data based on a given user or whatever core entity that generally is your root object entity being owned by a single master db,['java'] +31636,how to use alpha transparency in opengl heres my codevoid thisplayvoidint mainint argc char argv glutinitargc argv glutinitthisplaymodeglut singleglut rgba glblendfuncgl src alpha gl one minus src alpha glenable gl blend glutinitwindowsize600600 glutinitwindowposition20050 glutcreatewindowglut test glutthisplayfuncthisplay glutmainloop return 0void thisplay glcleargl color buffer bit glpointsize8 glbegingl points glcolor4f23783210 glvertex2f00 glcolor4f23783201 glvertex2f010 glend glflushthe problem is that these two points appear identical even when i set the alpha to 0 is there something i missed to enable alpha transparency,['c++'] +31642,non repeating random numbers i am usingfor int i 1 i100 i int i arc4random array countbut i am getting repeats every time how can i fill out the chosen int value from the range so that when the program loops i will not get any dupe,['objective-c'] +31652,c as first language for windows game programming i am a hobbyist programmer with a fair grasp of python and i am currently learning c recently i was talking to a colleague who also wants to learn to program in his case he wants to learn c as a path to windows game programming using directx personally i feel diving straight into c as your first language is a bit much it is hard enough keeping motivated in an easier language and i think it is better to learn another language to get your head round most of the basic concepts then go into something like ci found python worked well as my first language as i am more interested in network and web programming on linuxunix platforms but for someone mainly interested in windows game programming i was thinking c might be a better choice as he could learn using visual c express edition and xna then switch over to visual c when he is ready to start learning c and therefore already be in a familiar environment i think memory management is a lot to take in and c at least handles that so he can put that off till he starts learning cwhat do others think of c as a first programming language for this kind of application should i recommend he go for c instead,"['c#', 'c++']" +31655,how to support both ipv4 and ipv6 connections i am currently working on a udp socket application and i need to build in support so that ipv4 and ipv6 connections can send packets to a server i was hoping that someone could help me out and point me in the right direction the majority of the documentation that i found was not complete it would also be helpful if you could point out any differences between winsock and bsd socketsthanks in advance,['c++'] +31656,where can i set path to makeexe on windows when i try run make from cmdconsole on windows it runs turbo delphis makeexe but i need msyss makeexe there is no mention about turbo delphi in path variable maybe i can change it to msys in registry please help,['c++'] +31668,why the retentionpolicy for deprecated is runtime why at runtime is anyone interested in knowing that a method is deprecated can some provide me with some examples,['java'] +31675,getting a keyvaluepair directly from a dictionary i have systemcollectionsgenericdictionarya b dict where a and b are classes and an instance a a where dictcontainskeya is trueis it possible to get the keyvaluepair containing a directly from the dictionaryor do i need to create a new keyvaluepair new keyvaluepaira ba dicta,"['c#', '.net']" +31677,objectivec uninitialized pointers vs null pointers maybe my memory has gone completely wacko but i think i remember that declaring pointers without initializing them made them point to nil but recently this does not seem to be the case has it always been this way or has it something to do with the compiler settings,['objective-c'] +31690,how can you thisable scroll bars in the jquery ui dialog box does anyone know if there is a way to thisable scroll bars in the jquery dialog box the content that i have in the div is 300 px but the dialog is set to 200px it automatically puts the scrollbars but i do not want them i will add it myself to the second div that makes it bigger than the window any help is appreciated,['jquery'] +31692,drag and drop in mobilesafari is it possible to allow users to drag and drop items in mobile safari google images on the iphone does something similar but i am not sure if it is true drag and drop or some other work around anyone have any insights,['iphone'] +31695,how to write a js function that accepts and forwards variable number of parameters how do i write a javascript function that accepts a variable number of parameters and forwards all of those parameters to other anonymous functions for example consider the scenario of a method that fires an eventfunction firestartedeventabcdefg forvar i 0 i startedlistenerslength i startedlistenersiabcdefg especially since i have an event factory that generates these fire methods these methods have no interest in knowing how many parameters a given event or its handlers consume so i have it hardwired at 7 right now a through g if it is any less no problem if it is any more they get cut off how can i just capture and pass on all parametersthanksusing jquery or any other javascript framework is not an option here,['javascript'] +31740,why do include lines not end with a semicolon when including libraries c the line does not end with a semicolon while other statements dowhat is the reason behind this,['c'] +31742,dynamically adding functions to a python module our framework requires wrapping certain functions in some ugly boilerplate codedef prefix myname suffixobj def actual print hello world objregisteractual return obji figured this might be simplified with a decoratorregisterdef myname print hello worldhowever that turned out to be rather tricky mainly because the framework looks for a certain pattern of function names at module leveli have tried the following within the decorator to no availcurrent module import name new name prefix func name suffix method acurrent modulenew name func method bfunc name new namecurrent module funcany help would be appreciated,['python'] +31760,benchmarking method calls in c i am looking for a way to benchmark method calls in c i have coded a data structure for university assignment and just came up with a way to optimize a bit but in a way that would add a bit of overhead in all situations while turning a on call into o1 in somenow i want to run both versions against the test data to see if it is worth implementing the optimization i know that in ruby you could wrap the code in a benchmark block and have it output the time needed to execute the block in console is there something like that available for c,['c#'] +31762,what exactly is a register machine from i quoteusing a jit will also allow us to move python from a stackbased machine to a register machine which has been shown to improve performance in other similar languages ierusalimschy et al 2005 shi et al 2005in college i built a simple compiler for a language with recursive procedures which maintained stack frames for each procedure called so that they can be called recursively and so that parameters and return values would work2 things1 am i right in thinking that what i implemented would be considered a stackbased machine given the terminology used in the quotation above2 if my assumption in point 1 was right how does a register machine work ie how is it different from a stackbased machinethanks,['python'] +31781,stdregex is there some lib that needs to be linked i get a linker error with the following codeinclude regexint main stdregex rgxello return 0testo in function basic regexusrlibgcci586redhatlinux441includec441tr1 implregex769 undefined reference to stdbasic regexchar stdregex traitschar m compilecollect2 ld returned 1 exit status,['c++'] +31789,generic interface let us say i wanted to define an interface which represents a call to a remote service now the call to the remote service generally returns something but might also include input parameters suppose that an implementing class will typically only implement one service method given the above information is the following a poor design it does not quite feel rightpublic interface iexecutesserviceab public a executeservice public a executeserviceb inputparameternow let us say that i implement this interface with a class that executes a remote service with an input parameterpublic class servicea implements iexecutesservicestringstring public string executeservice this service call should not be executed by this class throw new illegalstateexceptionthis method should not be called for this classblabla public string executeservicestring inputparameter execute some service i have two questions regarding the aboveis the use of a generic interace iexecutesserviceab good in the case where you want to provide subclasses which require different input parmaters and return types for the interface methodshow can i do the above better ie i want to group my service executors under a common interface iexecutesservice however an implementing class will typically only implement one of the methods and the use of an illegalstateexception feels really ugly also the b type parameter in iexecutesserviceab will be redundant for an implementing class that calls a service without any input parameters it also seems overkill creating two separate interfaces for the two different service callsi will appreciate your comments on thischeers,['java'] +31800,machine learning libraries in c are there any machine learning libraries in c i am after something like wekathank you,['c#'] +31807,how to set root node name when xmlserializing an array i have an array of objects which i want to serialize as xml these objects are annotated to set xml node names but i was wondering how to set the name of the xml root nodethe code looks like this create list of itemslistlistitem list new listlistitemlistaddnew listitema1 new location1 2listaddnew listitema2 new location2 3listaddnew listitema3 new location3 4listaddnew listitema4xyz new location serialisexmlserializer ser new xmlserializertypeoflistitemfilestream os new filestreamdtempserixml filemodecreateserserializeos listtoarrayosclosethe output looks like thisxml version10arrayofplace xmlnsxsi xmlnsxsd place placenamea1placename location lat1lat long2long location place place listitem has been renamed to place using an xmlelement annotation but how can i set the name of the root node to rename the arrayofplace node,['.net'] +31815,what lucene analyzer can be used to handle japanese text which lucene analyzer can be used to handle japanese text properly it should be able to handle kanji hiragana katakana romaji and any of their combination,['java'] +31816,problem with png images in c working in visual studio 2008 i am trying to draw on a png image and save that image againi do the followingprivate image img imagefromfilefilepngprivate graphics newgraphicsand in the constructornewgraphics graphicsfromimageimgbuilding the solution gives no errors when i try to run it i get thisa graphics object cannot be created from an image that has an indexed pixel formati do not have much experience with using images in c what does this mean and how can i remedy thisedit through debugging visual studio tells me that the image has a format8bppindexed pixel formatso if i cannot use the graphics class what do i useedit2 after reading this i think it is safe to assume that i better stick to jpg files when working with gdi noedit3 my usingstatementsusing systemusing systemcollectionsgenericusing systemdrawingusing systemdrawingimagingusing systemwindowsforms,['c#'] +31826,iphone sdk uiactionsheet dynamic button titles i have a requirement in an application where i need to be able to add otherbuttontitles dynamically dependent upon some bool switches that a user has specified in the settings however i cannot seem to figure out how to go about doing this in the uiactionsheet initialization i have tried to pass a nsstring array nsstring2 and also a nsarray without any luckany help here is greatly appreciated,"['iphone', 'objective-c']" +31840,move list item to top of unordered list using jquery lets say i have the following unordered listul liahankali liaaliceali liatomali liaashleealiulwhat im looking for is when i click on tom that it moves animated and without dragging to the top of the list index 0ive considered jquery sortable but i cant find a way to activate the moving part programmatically,['jquery'] +31843,how can i pass a method acquired by reflection in c to a method that accepts the method as a delegate i realize the title needs to be read more than once for understanding i implemented a custom attribute that i apply to methods in my classesall methods i apply the attribute to have the same signature and thus i defined a delegate for thempublic delegate void testmethodi have a struct that accepts that delegate as a parameterstruct testmetadata testmethod method string testnameis it possible to get from reflection a method that has the custom attribute and pass it to the struct into the method member i know you can invoke it but i think reflection would not give me the actual method from my class that i can cast to the testmethod delegate,['c#'] +31848,c virtual function table memory cost considerclass a public virtual void update 0class b public a public void update stuff goes in here private double a b cclass c same kind of thing as b but with different update functiondata membersi am now doinga array new a10array0 new barray1 new cetc etcif i call sizeofb the size returned is the size required by the 3 double members plus some overhead required for the virtual function pointer table now back to my code it turns out that sizeofmyclass is 32 that is i am using 24 bytes for my data members and 8 bytes for the virtual function table 4 virtual functions my question is is there any way i can streamline this my program will eventually use a heck of a lot of memory and i do not like the sound of 25 of it being eaten by virtual functions pointers,['c++'] +31857,wrapping for in loops with if statements in javascript looping over arrays jslint keeps complaining about things like thisvar myarray 1 2 3for var value in myarray blahsaying that i should wrap it in an if statement i realize you need to wrap it if you are looping over an objects properties but here what should i put in the if statement to do the correct filteringadditionally when i do something likefor var i 0 i 10 i foofor var i 0 i 20 i barit complains that i has already been defined how do i prevent this other than using different variable names,['javascript'] +31898,downloading a file with a different name to the stored name is it possible to let your user download a file with a different namefor example there is a file called 4324ffsd34jpg i want people to download it via downloadphp with a different name like filetodownloadjpg without renaming the original file,['php'] +31912,objects allocated on heap whenever any new object is created the object is created on heap the memory allocated for each object has two additional fields 1 the type object pointer 2 sync block indexwhat exactly is the usage of these two fields can anybody shed light on this,['.net'] +31923,accessing measurement system unit names kglb min etc in c windows allows configuration of measurement system to metric or us is there a way to use this setting to read abbreviated unit names in ceg when thisplaying a weight in metric i want to show kg but in us i want to show lb similarly for length volume etci have looked at systeminformation cultureinfo configuration and globalization but did not see anything obvious did i miss something or am i looking in the wrong place,['c#'] +31944,multiple facebook accounts in single iphone app is there a way i can allow user to login with multiple facebook accounts at the same time like what tweetie2 does for twitter accounts so if i have two facebook accounts and i want the user to login with both of them on my iphone app selecting tab for will show statuses from a and selecting tab would do the same for bplease let me knowthanksaj,['iphone'] +31948,what is the pythonic way to detect the last element in a python for loop i would like to know the best way more compact and pythonic way to do a special treatment for the last element in a for loop there is a piece of code that should be called only between elements being suppressed in the last onehere is how i currently do itfor i data in enumeratedata list code that is done for every element if i lendata list 1 code that is done between elementsis there any better waynote i do not want to make it with hacks such as using reduce,['python'] +31950,duplicate key error does not cancelrollback mysql transaction when in a mysql innodb transaction i would expect a duplicate key error to cause a rollback it does not instead it simply throws an error and continues on to the next command once the commit command is reached the transaction will be committed sans the duplicate key causing commandis this the expected behaviour if so how would one go about setting it up so that the transaction is rolled back instead of committed when such an error occurstest environmentcreate table test id int11 not null primary key id engineinnodb default charsetlatin1 begin insert into test values 5 insert into test values 5commitexpected result table test is emptyactual result table test contains one record with value 5,['mysql'] +31952,any good tutorials on using com from c for one of a sideprojects i need to write a c app that required to use a thirdparty inproc com object unfortunately c is not my primary programming language so my knowledge is a bit limited is it any good tutorials available on how to access com object from c the usage of this thirdparty com object requires me to create implementation of specified com interface and supply that implementation into com object in order for it to function,['c#'] +31975,c regular expression howto it is been 10 years since i looked at c i need to write a little program in c that parses a string i wanted to use regular expressions since i have been using them for years but i have no idea how to do that in c i have spent the morning googling and i cannot find any straight forward examples ie use this library this is the methodology can someone give me a simple examplethanks,['c'] +31987,printf specify integer format string for float include stdiohint main float a 5 printfd a return 0this gives the output0why is the output zero,['c'] +31998,crud class library design to return useful messages about business logic failure that is not exceptional i am building a basic crud library that i anticipate use in both local add reference and wcf add service reference environmentswhat are the best return types for the create uupdate and delete portions that have more complex business rules of a crud setupi want to be able to minimize backandforth on the wire but i also want to provide my clients with meaningful information about when an operation fails my business logic but is technically valid thus it is not an exceptiontake for example the crud is for a person class which has these fields firstname middlename lastname and date of brith first last and dob are required but middle is nothow should i convey failures of business logic back to the client ie you must specify a value for firstnameis this where i should be throwingexceptions it does not feel likean exceptional case so i thinknot but i could be wrongshould i use void and an out parameter if so what type should it beshould i use an object return type and put data in there about what happenssome other option that i have missed completely,"['c#', '.net']" +32005,memory layout c objects i am basically wondering how c lays out the object in memory so i hear that dynamic casts simply adjust the objects pointer in memory with an offset and reinterpret kind of allows us to do anything with this pointer i do not really understand this details would be appreciated,['c++'] +32010,how does foreach work when looping through function results suppose i have the following codeforeachstring str in someobjgetmystrings do some stuffwill someobjgetmystrings be called on every iteration of the loop would it be better to do the following insteadliststring mystrings someobjgetmystringsforeachstring str in mystrings do some stuff,"['c#', '.net']" +32017,getting a python library listed in easy setup and pip every python developer is familiar with easy install and setup tools if i want to install a library that is well known all i have to do is thissudo easy setup install djangonow i have a library that i have written and would love to see widespread how do you get added to this library list,['python'] +32028,generic list as parameter on method how can i use a listt as a parameter on a method i try this syntax void exportlistt data params string parametersi got compilation error the type or namespace name t could not be found are you missing a using directive or an assembly reference,['c#'] +32032,wpf datagrid datagridcomboxbox itemssource binding to a collection of collections situationi have created a datagrid in xaml and the itemssource is binded to an observablecollection of a certain class that contains properties then in c i create a datagridtextcolumn and a datagridcomboboxcolumn and binded these to the properties of the objects inside the observablecollection i can bind the datagridcomboboxcolumn to a simple collection but what i want to do is bind it to a collection of collections of strings so that for each row the combobox inside the datagrid has a different collection of string i have failed to do soquestionhow can i bind the datagridcombboxcolumn so that i can have a different collection of strings for each row of this type of columncode samplexamlwindow wpftoolkitdatagrid xnamedg operations margin105105 height100 horizontalalignmentstretch fontweightnormal itemssourcebinding pathoperationsstats alternatingrowbackgrounddynamicresource specialcolor horizontalscrollbarvisibilityauto verticalscrollbarvisibilityvisible selectionmodeextended canuseraddrowsfalse canuserdeleterowsfalse canuserresizerowstrue canusersortcolumnstrue autogeneratecolumnsfalse isreadonlyfalse isenabledtrue borderthickness1 verticalalignmentstretch windowcpublic class datamodelstatsoperations public observablecollectionistatsoperation operationsstats get set public interface istatsoperation string operation get set collectionstring data get set public class statsoperation istatsoperation public statsoperationstring operation collectionstring data operation operation data data public string operation get set public collectionstring data get set private observablecollectionistatsoperation dataoperations new observablecollectionistatsoperation binding items new binding propertypath path new propertypathoperation itemspath path dg operationscolumnsaddnew datagridtextcolumn header operations width 133 binding items dg operationscolumnsaddnew datagridcomboboxcolumn header data width 190 itemssource selectedvaluebinding new bindingdata textbinding new bindingdata dataoperations addnew statsoperationcb operationselecteditemtostring datacollectiondg operationsdatacontext new datamodelstatsoperations operationsstats dataoperations any help would be greatly appreciatednotesokay so after reading the two first answers i noticed something my binding is really not right now what i want to do is something similar to what andyg proposeddg operationscolumnsaddnew datagridcomboboxcolumn header data width 190 itemssource new bindingdata notice this here does not work have a look at the following error selectedvaluebinding new bindingoperation textbinding new bindingoperationerror cannot implicitly convert type systemwindowsdatabinding to systemcollectionsienumerablehow can the itemssource be bound to data,['c#'] +32057,ruby function to remove all white spaces what is the ruby function to remove all white space kind of like phps trim,['ruby'] +32071,terminate a multithread python program how to make a multithread python program response to ctrlc key eventedit the code is like thisimport threadingcurrent 0class mythreadthreadingthread def init self total threadingthread init self selftotal total def stopself self thread stop def runself global current while currentselftotal lock threadinglock lockacquire current1 lockrelease print currentif name main threads thread count 10 total 10 for i in range0 thread count t mythreadtotal tsetdaemontrue threadsappendt for i in range0 thread count threadsistarti tried to remove join on all threads but it still does not work is it because the lock segment inside each threads run procedureedit the above code is supposed to work but it always interrupted when current variable was in 5060 range and through out the errors as belowexception in thread thread4 most likely raised during interpreter shutdowntraceback most recent call last file usrlibpython25threadingpy line 486 in bootstrap inner file testpy line 20 in runtype exceptionstypeerror unsupported operand types for nonetype and intexception in thread thread2 most likely raised during interpreter shutdowntraceback most recent call last file usrlibpython25threadingpy line 486 in bootstrap inner file testpy line 22 in run,['python'] +32088,javascript best singleton pattern possible duplicatesimplestcleanest way to implement singleton in javascript i am using this pattern for singletons in the example the singleton is planetearthvar namespace function var privatefunction1 function privatefunction2 var privatefunction2 function alerti am private var constructors constructorsplanetearth function privatefunction1 privatefunction2 constructorsplanetearthprototype somemethod function if console consolelog consolelogsome method constructorsperson function name address thisname name thisaddress address constructorspersonprototype walk function alertstomp return person constructorsperson there can be many planetearth new constructorsplanetearth there can only be one since planetearths constructor remains private there can only be onenow something tells me that this selfcooked thing is not the best one can do mostly because i do not have an academic education and i tend to solve problems in stupid ways what would you propose as a better alternative my method where better is defined as stylistically better andor more powerful,['javascript'] +32089,php web development ide i am coming from a c background and am used to testing code by setting breakpoints viewing variables in the debugger etci am now doing web development using the symfony framework what i really miss is not being able to set a breakpoint when a particular action is performed eg a url clicked etc is there a free gpl or other license php ide that can allow me to set breakpoints etc as described above,['php'] +32102,automatic resizing of the windows forms controls i am using vs2008s designer for doing thisfor example if i have a windows form of size say 500x500 and i added a datagridview to it 490x490 when i run this program and maximize the form the datagridview still remains of the same size rest of the additional space is blank on the form i want datagridview to also take the entire window sizeno software will be like that i do not know what to change inorder get desired behaviour,"['c#', '.net']" +32104,what to logtrace in a production environment i am wondering what kind of information should be logged to a file once an application has moved into a production environment besides the logging of exceptions and errorsshould the start and end of each method be logged the start and end of a running service each time the application saves data to a database or calls an external service i am trying to find the balance between loggingtracing everything and only logging errors,['.net'] +32112,are static fields in activity classes guaranteed to outlive a createdestroy cycle i frequently run into the problem that i have to preserve state between several invocations of an activity ie going through several oncreateondelete cycles unfortunately androids support for doing that is really pooras an easy way to preserve state i thought that since the class is only loaded once by the class loader that it would be safe to store temporary data that is shared between several instances of an activity in a static bundle fieldhowever occasionally when instance a creates the static bundle and stores data in it then gets destroyed and instance b tries to read from it the static field is suddenly nulldoes not that mean that the class had been removed and reloaded by the classloader while the activity was going through a createdestroy cycle how else could a static field suddenly become null when it was referencing an object before,"['java', 'android']" +32116,how can i get jqgrid to recognize server sent errors i have a jqgrid that is functionning very welli was wondering is it possible to catch server sent errors how is it done,['jquery'] +32147,java library to map http status code to description i am in the situation where i am writing custom error pages for a webapp primarily to reduce information thisclosure from the servlet containers default error pages since i need an error page for each error status code i am going to have to have a sensible response for each code as far as i can tell these error pages do not have to be particularly userfriendly but simply redirecting everything to a single it went wrong error page is going to make diagnosing problems very difficultso i am wondering if there is a java library that provides a good mapping between http status codes and a brief humanreadable description of them ideally a 24 word summary for use as a page title as well as a 13 sentence message expanding on the summary then i could just use this in a jsp to provide some feedback on the class of the error if not i am sure i can write one myself but if wheels have been invented i am happy to use them,['java'] +32148,cast dictionary keycollection to string array i have a dictionaryint string which i want to take the key collection into a csv stringi planned to dostringjoin mydickeystoarraycaststringthe cast is failing thoughthanks,"['c#', '.net']" +32157,how can i determine type of mysql database whether it is innodb or myisam how can i determine type of mysql database whether it is innodb or myisam how can i convert myisam to innodb or viceversa,"['sql', 'mysql']" +32159,preserving order in sequence of choices linq to xsd given the following xml example we could imagine a schema defining root as containing a sequence of unbound number of choices between type1 and type2root type1 type2 type2 type1 rooti am testing out migrating from the xsdexe tool which although adds typesafety has a lot of little annoyances the xsd tool in this case just creates within root an array of type systemobject and you have to figure out what type of objects type1 or type2 are in there its not completely elegant but at least you preserve orderthe problem is when linq to xsd creates the objects it defines root as having two independent lists of type1 and type2 this is great in that it is typesafe but i now appear to lose the order of the elements i built linq to xsd from the source on codeplex using linq to xsd how can i preserve the order of these elements,['c#'] +32161,how to conditionally show jsp content to logged in users with spring security i want to show content to any user that is logged in and to hide if they are not logged in i am using jsps and spring security obviously a home grown solution is easily done but whats the cleanest standard way of achieving this spring security tags do not seem to have nice way that will allow for the addition of new roles in the future,['java'] +32163,interfaces separated from the class implementation in separate projects we work on a middlesize project 3 developers over more than 6 months and need to make following decision wed like to have interfaces separated from concrete implementation the first is to store the interface in a separate file wed like to go further and separate the data even more wed like to have one project csproj with interface in one cs file plus another cs file with help classes like some public classes used within this interface some enums etc then wed like to have another project csproj with a factory pattern concrete interface implementation and other worker classes any class which wants to create an object implementing this interface must include the first project which contains the interfaces and public classes not the implementation itselfthis solution has one big thisadvantage it multiplies the number of assemblies by 2 because you would have for every normal project one project with interace and one with implementation what would you recommend do you think it is a good idea to place all interfaces in one separate project rather than one interface in its own project,['c#'] +32170,javascript at bottomtop of web page i was just using the plugin yslow for mozilla firefox and it told me that i should put javascript at the bottom i have heard this before but have not really thought about it too much is there really an advantage in putting javascript at the bottom of a web page compared to the top,['javascript'] +32184,how does the function construct work and why do people use it function and its jqueryspecific cousin function jquery pop up all the time in javascript codehow do these constructs work and what problems do they solveexamples appreciated,['javascript'] +32195,how to check whether one net type implements certain net interface abstractly i have a type and an interface and i need to verify that the type implements the interface abstractlyi have set to write a brute force code using reflection and it is pretty uglyi am wondering if there is a better way than the brute force implementation i am doing nowany ideasthanksedithave not checked the implementation yet but the brute force draft code looks like this public static bool isabstractinterfaceimplementationtype sometype type someinterface if someinterfaceisassignablefromsometype return false if sometypeisabstract return false var m interfacemembernames someinterfacegetmembersselectm mnametolist make sure every interface member implementation is abstract foreach var typemember in sometypefindmembersmembertypesevent membertypesproperty membertypesmethod bindingflagspublic bindingflagsinstance null null if m interfacemembernamescontainstypemembername methodinfo method make sure the ancestor member is abstract switch typemembermembertype case membertypesevent if isabstractimplementationeventinfotypemembergetaddmethod return false method eventinfotypemembergetremovemethod break case membertypesproperty method propertyinfotypemembergetgetmethod default method methodinfotypemember break if isabstractimplementationmethod return false return true public static bool isabstractimplementationmethodinfo methodinfo const methodattributes expectedattributes methodattributesabstract methodattributespublic methodattributesnewslot methodattributesvirtual return methodinfoattributes expectedattributes expectedattributes without compiling it i already see a problem with properties that the code has to check whether interface defines getter andor setter and verify the right methods instead of blindly assuming the getter anyway as one can see the code is pretty dull i am wondering if there is a better wayedit 2i wish to stress that this is just a draft implementation it works for simple cases and it is broken for more complex ones like when there are method overloads or method renames i do not know vb so i did not even think it was possible but it emphasizes my point that it demands much work to do it rightwhy would i want such a thing we need to create types dynamically using reflectionemit based on certain dynamically acquired metadata the generated dynamic type implements certain interface say idynamicobject and may derive from some ancestor type that ancestor type is statically compiled until recently the ancestor type was not allowed to implement the idynamicobject interface given an instance of the dynamic type one had to explicitly cast it to idynamicobject in order to gain access to its methods remember that the generated dynamic type does implement the interface i would like to eliminate these explicit casts the only way to do so is by letting the ancestor type implement the idynamicobject interface however the implementation must be all abstract which is verified by the dynamic type creation code voila,['.net'] +32208,how to udp send and receive on same port i need to be able to send and receive udp packets on the same porti am able to listen on say port 50 but my send uses a random high portthe system i am working written in vb with does this and my need is to write a udp responder for debugging various protocol issuesi am using the open source c sockets library from anders hedstrom and have been able to use the udpsocketbind to receive incoming udp packets using the virtual function udpsocketonrawdata but have been unable to cause the udpsocketopen calls connect to make the udpsocketsend use the port chosen in bind it uses random high number port insteadmoving the open function does not help i have posted a request on their forum but believe from what i have read that it should be possible to do this and i am probably not understanding how to use udpdoes anyone have any ideas on what i should trythanks,['c++'] +32209,how do i tell if the c function atoi failed or if it was a string of zeros when using the function atoi or strtol or similar functions for that matter how can you tell if the integer conversion failed or if the cstring that was being converted was a 0for what i am doing 0 is an acceptable value and the cstring being converted may contain any number of 0s it may also have leading whitespace,['c++'] +32220,how to load data infile on amazon rds not sure if this is a question better suited for serverfault but i have been messing with amazon rds lately and was having trouble getting file privileges to my web host mysql useri would assume that a simplegrant file on to webuserwould work but it does not and i cannot seem to do it with my root user as well what gives the reason we use load data is because it is super super fast for doing thousands of inserts at onceanyone know how to remedy this or do i need to find a different waythis page seems to suggest that i need to find a different way around thishelpupdatei am not trying to import a database i just want to use the file load option to insert several hundredthousand rows at a timeafter digging around this is what we have mysql grant file on to devuser error 1045 280 access denied for user root using password yes mysql select user file priv grant priv super priv from mysqluser user file priv grant priv super priv rdsadmin y y y root and y and devuser and and and,['mysql'] +32244,duplicate elements in javautilset javautilset implementations removes the duplicate elementshow are duplicates elements deleted internally in a javautilset,['java'] +32248,jpg to pdf convertor in c i would like to convert from an image like jpg or png to pdf i have checked out imagemagicknet but it is far too complex for my needswhat other net solutions or code are there for converting an image to a pdf,['c#'] +32260,how to delete columns in numpyarray i would like to delete selected columns in a numpyarray this is what i don 397 a array nan 2 3 nan 1 2 3 9in 398 print a nan 2 3 nan 1 2 3 9in 399 z anyisnana axis0in 400 print z true false false truein 401 deletea z axis 1out401 array 3 nan 3 9in this example my goal is to delete all the columns that contain nans i expect the last command to result inarray2 3 2 3how can i do that,['python'] +32278,get month name from date how can i generate the name of the month eg octoctober from this date object in javascriptvar objdate new date10112009,['javascript'] +32292,why no warning with if x when x undefined i occasionally write code something like this file1cppdefine do this 1if do this stuffendifduring the code development i may switch the definition of do this between 0 and 1recently i had to rearrange my source code and copy some code from one file to another but i found that i had made a mistake and the two parts had become separated like so file1cppdefine do this 1and file2cppif do this stuffendifobviously i fixed the error but then thought to myself why did not the compiler warn me i have the warning level set to 4 why is not if x suspicious when x is not definedone more question is there any systematic way i could find out if i have made the same mistake elsewhere the project is hugeedit i can understand having no warning with ifdef that makes perfect sense but surely if is different,['c++'] +32297,eclipse how to terminate all applications at once is there some way to terminate all java applications launched with eclipse at once,['java'] +32311,save write nsmutablearray of objects to thisk initially i thought this was going to work but now i understand it would not because artistcollection is an nsmutablearray of artist objectsinterface artist nsobject nsstring firname nsstring surnamemy question is what is the best way of recording to thisk my nsmutablearray of artist objects so that i can load them the next time i run my applicationartistcollection nsmutablearray alloc initnewartist artist alloc initnewartist setfirnameobjfirnamenewartist setsurnameobjsurnameartistcollection addobjectnewartistnslog save allartistcollection writetofileusersfgxdesktopstufftxt atomicallyyeseditmany thanks just one final thing i am curious about if artist contained an extra instance variable of nsmutablearray softwareowned of further objects applications how would i expand the encoding to cover this would i add nscoding to the applications object then encode that before encoding artist or is there a way to specify this in artistinterface artist nsobject nsstring firname nsstring surname nsmutablearray softwareownedinterface application nsobject nsstring appname nsstring appversionmany thanksgary,['objective-c'] +32315,emacs completions or intellisense the same as on visual studio emacs 21 on linuxi am doing some cc programming using emacs i am wondering does emacs support completions intellisense in visual studiofor example when filling structures i would like to see the list of members when i type the dot operator or arrow operatorthe same would go for function signatures that give me the types i am passing would thisplay,['c++'] +32316,searching on date ranges with lucene in java is it possible to search on date ranges using lucene in java how do i build lucene search queries based on date fields and dates ranges for examplebetween specified datesprior to a specified dateafter a specified datewithin the last 24 hourswithin the past weekwithin the past monthedit i am using lucene 241 and my system is really legacy and really poorly tested so i would like if possible not to have to upgrade,['java'] +32320,how to handle unicode nonascii characters in python i am programming in python and i am obtaining information from a web page through the urllib2 library the problem is that that page can provide me with nonascii characters like a a etc in the very moment urllib2 gets this character it provokes an exception like thisfile cpython25libhttplibpy line 711 in send selfsocksendallstr file string line 1 in sendall unicodeencodeerror ascii codec cannot encode character uxf1 in position 74 ordinal not in range128i need to handle those characters i mean i do not want to handle the exception but to continue the program is there any way to for example i do not know if this is something stupid use another codec rather than the ascii because i have to work with those characters insert them in a database etc,['python'] +32334,rails migrations check existence and keep going i was doing this kind of thing in my migrationsadd column statuses hold reason string rescue puts column already addedbut it turns out that while this works for sqlite it does not work for postgresql it seems like if the add column blows up even if the exception is caught the transaction is dead and so the migration cannot do any additional workis there any nondb sepecific ways to check if a column or table already exist failing that is there any way to get my rescue block to really work,['ruby-on-rails'] +32354,how do i import a com object namespaceenumeration in python i am relatively new to programmingpython so i would appreciate any help i can get i want to save an excel file as a specific format using excel through com here is the codeimport win32comclient as win32 def excel app excel x1 win32gencacheensurethispatchsapplication app ss x1workbooksadd sh ssactivesheet x1visible true shcells11value test write saveasfilenametempxls fileformat56 x1applicationquitif name main excelmy question is how do i specify the fileformat if i do not explicitly know the code for it browsing through the documentation i find the reference at about a fileformat object i am clueless on how to access the xlfileformat object and import it in a way that i can find the enumeration value for it thanks,['python'] +32365,jquery datepicker default date i am trying to get a attribute of a date picker to pull the date dynamically however i get uncaught exception errors when i try to set it to a variablethe errors only occur on pages that do not have the calendar inlinehow can i pul the rel tag from the selector without getting this errorevent calendar home page and listingfunction calendar picker calendarinlinedatepicker defaultdate thisattrrel dateformat yymmdd maxdate 1y mindate0d hideifnoprevnext true showbuttonpanel false navigationasdateformat false onselect functiondatetext inst var d new datedatetext var fmt1 datepickerformatdateyymmdd d ajax type post url eventslistingall20 datatype html date event datefmt1 success function windowlocationhref eventsbrowsefmt1 updatecorrect the commented line is what i am having issues with what is the correct way to pull the attribute rel from calendarinline from inside thisall attempts throw a uncaught error in jsupdate 2function calendar picker var mydate new datecalendarinlineattrrel calendarinlinedatepicker dateformat yymmdd defaultdatemydatesolutionfunction calendar picker var mydate nullif calendarinlineattrrel null mydate datepickerparsedateyymmdd calendarinlineattrrel calendarinlinedatepicker dateformat yymmdd defaultdatemydate,['jquery'] +32381,java dynamic array sizes i have a class xclass that i want to load in to an array of xclass so i have a declaration likexclass mysclass new xclass10myclass0 new xclassmyclass9 new xclassthe problem is i do not know if i will need 10 i may need 8 or 12 or any other number for that matter i would not know until runtime can i change the number of elements in an array on the fly if so howmany thanks for any help you may be able to provide,['java'] +32398,how to count group by rows in rails when i use usercountall group name i get multiple rows but it is not what i want what i want is the count of the rows how can i get it,"['ruby-on-rails', 'ruby']" +32400,is it possible to check whether you are building for 64bit with microsoft c compiler is there a simple preprocessor macro that is defined for a 64bit build i thought win64 might have been it but even when i build a 32bit target the parts enclosed in a ifdef win64 endif are compiled in and this is causing problems it is friday and i cannot think straight but i am sure i am overlooking something very simple here maybe even something involving sizeof,['c'] +32403,executorservices surprising performance breakeven point rules of thumb i am trying to figure out how to correctly use javas executors i realize submitting tasks to an executorservice has its own overhead however i am surprised to see it is as high as it ismy program needs to process huge amount of data stock market data with as low latency as possible most of the calculations are fairly simple arithmetic operationsi tried to test something very simple mathrandom mathrandomthe simplest test runs this computation in a simple loop the second test does the same computation inside a anonymous runnable this is supposed to measure the cost of creating new objects the third test passes the runnable to an executorservice this measures the cost of introducing executorsi ran the tests on my dinky laptop 2 cpus 15 gig ramin millisecondssimplecompuation47computationwithobjcreation62computationwithobjcreationandexecutors422about once out of four runs the first two numbers end up being equalnotice that executors take far far more time than executing on a single thread the numbers were about the same for thread pool sizes between 1 and 8question am i missing something obvious or are these results expected these results tell me that any task i pass in to an executor must do some nontrivial computation if i am processing millions of messages and i need to perform very simple and cheap transformations on each message i still may not be able to use executorstrying to spread computations across multiple cpus might end up being costlier than just doing them in a single thread the design decision becomes much more complex than i had originally thought any thoughtsimport javautilconcurrentexecutorserviceimport javautilconcurrentexecutorsimport javautilconcurrenttimeunitpublic class execserviceperformance private static int count 10 public static void mainstring args throws interruptedexception warmup simplecompuation computationwithobjcreation computationwithobjcreationandexecutors long start systemcurrenttimemillis simplecompuation long stop systemcurrenttimemillis systemoutprintlnsimplecompuationstopstart start systemcurrenttimemillis computationwithobjcreation stop systemcurrenttimemillis systemoutprintlncomputationwithobjcreationstopstart start systemcurrenttimemillis computationwithobjcreationandexecutors stop systemcurrenttimemillis systemoutprintlncomputationwithobjcreationandexecutorsstopstart private static void computationwithobjcreation forint i0icounti new runnable override public void run double x mathrandommathrandom run private static void simplecompuation forint i0icounti double x mathrandommathrandom private static void computationwithobjcreationandexecutors throws interruptedexception executorservice es executorsnewfixedthreadpool1 forint i0icounti essubmitnew runnable override public void run double x mathrandommathrandom esshutdown esawaittermination10 timeunitseconds,['java'] +32406,keycode on keydown event i am using keydown event where i get the keycode and convert it to charcodebut i got a problem where in keyboard is press 2 it gives 50 and charcode as 2when i press 2 in numpad it gives keycode 98 so when i convert charcode a,['javascript'] +32413,how hard is developing for iphone i want to know how difficult is to develop on iphone plataform by difficult i want to mean effort in terms of programmer versus software complexity to be clear how many programmers are needed to develop a medium sized app on iphone sdk learning curve hardware and other nonprogramming related stuff affecting the development how easy is to sell iphone software to be specific is easy to sell an app on itunes does it cost something i am confused about how to sell that apps on itunes store any one has experience on advertisement supported apps please tell me how has been thatthanks,['iphone'] +32415,cpu performance control wpf i need a control in silverlight that shows a cpu performance in real time just like the windows task manager doessomething like,['c#'] +32423,when using linq what is the difference between and multiple where clauses i am new to linq and thiscovered yesterday that you can have multiple where clauses such asvar items from object in objectlistwhere objectvalue1 100 where objectvalue2 10 select objector you can writevar items from object in objectlistwhere objectvalue1 100 objectvalue2 10 select objectwhat is the difference between the two,['c#'] +32440,whats the difference between import javautil and import javautildate i just want to output current and i wroteimport javautilat beginning and systemoutprintlnnew datein the main partbut what i got was something like thisdate124bfwhen i change the import to import javautildate the code works perfectly why the problem was ok my source file was datejava that is the causewell it is all my fault i confused everybody around pand thanks to everyone below it is really nice of you,['java'] +32449,use of retain in initwithcoder i am reading up about encoding and decoding and i noticed that sometimes people miss the retain off the end i have also noticed that retain is sometimes used on some varables but not others can i ask 1 what is the purpose of this retain and why is it sometimes not needed2 does the use of the retain imply that i need to match it with a release and if so where id initwithcoder nscoder decoder name decoder decodeobjectforkey cardname retain email decoder decodeobjectforkey cardemail retainor id initwithcoder nscoder decoder name decoder decodeobjectforkey cardname email decoder decodeobjectforkey cardemailgary,['objective-c'] +32464,difference between using and scoping what is the difference between the following two snippets of codeusing object o new object do somethingand object o new object do somethingi have started using using a lot more but i am curious as to what the actually benefits are as compared to scoping objectsedit useful tidbits i took from thisjon skeet note that this does not force garbage collection in any way shape or form garbage collection and prompt resource cleanup are somewhat orthogonalwill eddins commentunless your class implements the ithisposable interface and has a thispose function you do not use using,['c#'] +32469,datacontractserializer does not properly deserialize values for methods in object are missing my someclaserializabledatacontractnamespace public class someclass datamember public string firstname get set datamember public string lastname get set datamember private idictionarylong string customvalues public idictionarylong string customvalues get return customvalues set customvalues value my xml filexml version10 encodingutf8 someclass firstnamejohnfirstname lastnamesmithlastname customvalues value1onevalue1 value2twovalue2 customvalues someclassbut my problem is for the class i am only getting some of the data for my methods when i deserializevar xmlroot xelementloadnew streamreader filtercontexthttpcontextrequestinputstream filtercontexthttpcontextrequestcontentencodingxmldictionaryreader reader xmldictionaryreadercreatedictionaryreaderxmlrootcreatereader datacontractserializer ser new datacontractserializertypeofsomeclassdeserialize the data and read it from the instancesomeclass someclass someclaserreadobjectreader trueso when i check someclass firstname will have the value john but the lastname will be nullmystery is how can i get some of the data and not all of the data for the claso datacontractserializer is not pulling up all the data from xml when deserializingam i doing something wrongany help is appreciated thanks in advancelet me know if anyone has the same problem or any one has solution,['c#'] +32470,java cast collection type to subtype suppose class b extends class a i have a lista that i happen to know only contains instances of b is there a way i can cast the lista to a listbit seems my only option is to iterate over the collection casting one element at time creating a new collection this seems like an utter waste of resources given type erasure makes this completely unnecessary at runtime,['java'] +32474,nskeyedarchiver write xml or other human readable i have been trying to get the nskeyedarchiver to write out my data in a human readable form ie not as a binary file i understand that i can use setoutputformat nspropertylistxmlformat v1 0but i just cannot seem to get the syntax right can anyone point me in the right directionnsdata artistdatanslog save allartistdata nskeyedarchiver archiveddatawithrootobjectartistcollection artistdata writetofileusersfgxdesktopstuff atomicallyyesediti added setoutputformat see below but i get a warning at compile what am i missingwarning nsdata may not respond to setoutputformathere is the code i usednslog save allartistdata nskeyedarchiver archiveddatawithrootobjectartistcollection artistdata setoutputformat nspropertylistxmlformat v1 0artistdata writetofileusersfgxdesktopstuff atomicallyyesgary,['objective-c'] +32505,common language runtime detected an invalid program in visual studio i have been using visual studio 2008 quite long but lately i am getting this message when i am developing an application in ccommon language runtime detected an invalid programthis happens when i try to enter to the properties of a component text masked box properties tool box property etc but it really became a problem when i tried to launch an other solution that i downloaded from the developers 5 star program of microsoft and it did not allowed me to launch at all and just got the same problemi looked for the answer at google but just got some clues about people having the same vague error but in different situations like in aspneti would appreciate any help with this issue i do not want to reinstall vs that will be my last resourceupdatei never figured out what the problem was so i installed a virtual machine with windows xp on it there i only have visual studio and netbeans,['.net'] +32508,android webview cookie problem i have a server that sends my android app a session cookie to be used for authenticated communication i am trying to load a webview with a url pointing to that same server and i am trying to pass in the session cookie for authentication i am observing that it works intermittently but i have no idea why i use the same session cookie to make other calls on my server and these never fail authentication i only observe this problem when trying to load a url in a webview and it does not happen every time very frustratingbelow is the code that i am using to do this any help will be greatly appreciated string myurl cookiesyncmanagercreateinstancethis cookiemanager cookiemanager cookiemanagergetinstance cookie sessioncookie getcookie ifsessioncookie null string cookiestring sessioncookiegetname sessioncookiegetvalue domainsessioncookiegetdomain cookiemanagersetcookiemyurl cookiestring cookiesyncmanagergetinstancesync webview webview webview findviewbyidridwebview webviewgetsettingssetbuiltinzoomcontrolstrue webviewgetsettingssetjavascriptenabledtrue webviewsetwebviewclientnew mywebviewclient webviewloadurlmyurl,['android'] +32517,differences between exec and fork what are the differences between fork and exec,['c'] +32528,how to decrypt a string how to restore the value of a string after using formsauthenticationhashpasswordforstoringinconfigfilei have a string s1 abc thenformsauthenticationhashpasswordforstoringinconfigfiles1 sha1 a93e364706816aba3e25717850c26c9cd0d89dhow can i decrypt a93e364706816aba3e25717850c26c9cd0d89d back to abc,"['c#', 'asp.net']" +32529,dealing with path issues with phpunit i have just started to use phpunit but i have run into a bit of a snagmy code uses serverdocument root to compute paths for includes which works when my apache server is the one running php but document root is not set when i run phpunit from the command line with phpunit tests so these includes do not workam i missing something in the configuration of phpunit should it somehow be integrated with apache,['php'] +32531,does python have an ordered set python has an ordered dictionary what about an ordered set,['python'] +32536,ormpersistence layer advice hi alli am starting a new project and i am looking around for either a very good orm or for a nonsqlbased persistence layerfor this project i really do not care on how the data is persisted as long as it can be queried and stored with a reasonable speed and most importantly with simple queriesconcurrency should be handled seamlessly the frontend will be on another tier and therell be several simultaneous users although not necessarily working on the same data and the less i have to focus on the data layer easy queries automatic lazy loading etc the betteri also want to avoid at all cost having to mess with stringbased queries so tools supporting linq or otherwise intuitive and possibly strongly typed queries get a big bonusfinally working with poco objects is another thing i would really want to doheres a list of products i have evaluated and why they do not fit just so that i do not see any advice about using thosenhibernate crazy xml stuff too much set up high maintenance complexity and cost for model changes session factories are messy and do not fit well with my needscastle activerecord nhibernate based little documentation plus some problems related to nhibernate still apply furthermore to get decent models it takes so many attributes that one is better off creating the schema manually and the way relations are handled is a shamelinq to sql missing poco objects and according to ms it would not improve much overtime ef is what they are committed toentity framweork although in v4 poco objects are possible they are still pretty hacky and force you into doing too much manual work to set things up besides v4 is just a betallblgen pro good especially with selfservicing adapters but not poco also the linq provider is not perfect yet finally deleting a group of objects is not possible via linq which results in mixing apis one of which is far from intuitive and that i do not likexpo anything but intuitive very slow concurrency issues not pocosubsonic simplerepository for a few minutes i thought i was dreaming the deam came to an end as i figured out how the thing did not handle relationshipsi have also looked at mongodb and couchdb but in those cases the catches with related objects looked like they required too much testing before getting things right besides none of them offers strongly typed queriesthanks in advance for your suggestions,"['c#', '.net']" +32537,scope of exception object in c what is the scope of the exception object in c does it go out of scope as soon as catch handler is executed also if i create an unnamed exception object and throw it then while catching that exception does it matter if i catch it by const reference or a nonconst reference,['c++'] +32553,download manager in java i need to several some huge files several gigs from java via ftphttp is there a ready library java command line tool to facilitate the download some obvious requirements aremulticonnection download should be able to open several connections to the server to accelerate the download like flashgetgetrightresume a downloadedit i would really prefer not to write such a library but steal it or pay for an existing tested production grade library rsynch is not relevant since i need to download files from http and ftp sites it is not for internal file transfer,['java'] +32556,whats a good multicore 64bit hello world program i recently got my home pc upgraded to a quadcore cpu and 64bit os i have some former experience with cc and i am really itching to try exercising some 64bit cpu capabilities whats a good hello world type program that demonstrates 64bit multicore capabilities by doing some simple things that do not work well at all in 32bit singlecore codei am just trying to get a feel for how these new cpus can impact the performance of cc code in extreme cases,['c'] +32557,how to force a record to save itself even if i have not changed any attributes in order to clean up some bad data i added a before save callback now i need to force all the models to be saved again however no update operation happens if i do thisuserfirstsavehow do i force all the models to perform save operation even though i do not have any attributes changed,['ruby-on-rails'] +32559,when to use nil blank empty is there any guidelines on how to differentiate between nil blank and emptyi am generally always confused as to when to use them in my application as they all seem to mean the same thing but have different meaningsdoes anyone have any cheat sheet on the gory details,"['ruby-on-rails', 'ruby']" +32561,strange java cast exception why cannot i cast long to a float why cannot i cast long to a floati get this error messagejavalangclasscastexception javalanglong cannot be cast to javalangfloatwhy is this a problem the numbers that i am trying to cast are decimals in the domain 100 100 they start out as object instances returned using jformattedtextfieldgetvalue but they must be converted to floatsstack traceexception in thread awteventqueue0 javalangclasscastexception javalanglong cannot be cast to javalangfloat at submodeleranimationtimelinesetkeyedattributetimelinejava59 at submodeleruiattributestransformationattributepanelactionperformedtransformationattributepaneljava247 at javaxswingabstractbuttonfireactionperformedabstractbuttonjava2028 at javaxswingabstractbuttonhandleractionperformedabstractbuttonjava2351 at javaxswingdefaultbuttonmodelfireactionperformeddefaultbuttonmodeljava387 at javaxswingdefaultbuttonmodelsetpresseddefaultbuttonmodeljava242 at javaxswingplafbasicbasicbuttonlistenermousereleasedbasicbuttonlistenerjava236 at javaawtcomponentprocessmouseeventcomponentjava6348 at javaxswingjcomponentprocessmouseeventjcomponentjava3267 at javaawtcomponentprocesseventcomponentjava6113 at javaawtcontainerprocesseventcontainerjava2085 at javaawtcomponentthispatcheventimplcomponentjava4714 at javaawtcontainerthispatcheventimplcontainerjava2143 at javaawtcomponentthispatcheventcomponentjava4544 at javaawtlightweightthispatcherretargetmouseeventcontainerjava4618 at javaawtlightweightthispatcherprocessmouseeventcontainerjava4282 at javaawtlightweightthispatcherthispatcheventcontainerjava4212 at javaawtcontainerthispatcheventimplcontainerjava2129 at javaawtwindowthispatcheventimplwindowjava2475 at javaawtcomponentthispatcheventcomponentjava4544 at javaawteventqueuethispatcheventeventqueuejava635 at javaawteventthispatchthreadpumponeeventforfilterseventthispatchthreadjava296 at javaawteventthispatchthreadpumpeventsforfiltereventthispatchthreadjava211 at javaawteventthispatchthreadpumpeventsforhierarchyeventthispatchthreadjava201 at javaawteventthispatchthreadpumpeventseventthispatchthreadjava196 at javaawteventthispatchthreadpumpeventseventthispatchthreadjava188 at javaawteventthispatchthreadruneventthispatchthreadjava122,['java'] +32562,spring getting factorybean object instead of factorybeangetobject short question if i have class that impelemnts factorybean interface how can i get from factorybean object itself instead of factorybeangetobjectlong question i have to use 3rd party spring based library which is hardly use factorybean interface right now i always must configure 2 beans case 1bean idxyz classfactorybean1 scopeprototypeproperty namestepsbean classfactorybean2property nameitemreader refanamebeanpropertybeanbean idaname classcompackageclassname1 scopeprototypeproperty nameobjectcontextbean classcompackageabcpropertybean case 2bean idxyz2 classfactorybean1 scopeprototypeproperty namestepsbean classfactorybean2property nameitemreader refaname2beanpropertybeanbean idaname2 classcompackageclassname1 scopeprototypeproperty nameobjectcontextbean classcompackageqwepropertybeanactyually defintion of a bean with name xyz compare with xyz2 never will be changed but because of factory nature i must copy the code for each configurationdefinition of a bean with name aname always will be new ie each configuration will have own objectcontext valuei would like to simplify the configuration have a single factory bean remove xyz2 and rid of link to anamebean idxyz classfactorybean1 scopeprototypeproperty namestepsbean classfactorybean2propertybeanbean idaname classcompackageclassname1 scopeprototypeproperty nameobjectcontextbean classcompackageabcpropertybeanbean idaname2 classcompackageclassname1 scopeprototypeproperty nameobjectcontextbean classcompackageqwepropertybeanunfortunately it is not as simple as i expect i suppose to glue factory ie xyz bean from the example with necessary objects ie aname aname2 at runtimethe approach does not work because when i ask spring for factorybean object it returns to me factorybeangetobject which impossible to instanciate at that time because of missing itemreader valuei hope that springsource foresee my case i can somehome hook factorybeangetobject call to provide all necessary properties at runtime another complexity that thisturb me a bit it is chains of factories factory1 get an object from factory2 that i have to hook at runtimeany ideas will be appreciated,['java'] +32570,how do you flush python sockets i have written a server in python that is meant to send data to the client in the form headermessagei would like to be able to have each message sent individually so that the client will need to perform minimal work in order to read the header and the messageunfortunately i cannot figure out how to properly flush a python socket so when i have multiple sends execute in quick succession the messages get lumped together in the socket buffer and sent as one big chunkexampleserver sendssocketsend header1message1socketsend header2message2socketsend header3message3client receivesheader1message1header2message2header3message3i would like to receive three individual messagesheader1message1header2message2header3message3i need a way to flush after each send,['python'] +32574,linux optimistic malloc will new always throw when out of memory i have been reading about out of memory conditions on linux and the following paragraph from the man pages got me thinkingby default linux follows an optimistic memory allocation strategy this means that when malloc returns nonnull there is no guarantee that the memory really is available this is a really bad bug in case it turns out that the system is out of memory one or more processes will be killed by the infamous oom killer considering that the operator new implementation will end up calling malloc at some point are there any guarantees that new will actually throw on linux if there are not how does one handle this apparently undetectable error situation,['c++'] +32578,what are the most surprising elements of the c standard i have decided to get more acquainted with my favorite programming language but only reading the standard is boringwhat are the most surprising counterintuitive or just plain weird elements of c what has shocked you enough that you ran to your nearest compiler to check if it is really truei will accept the first answer that i would not believe even after i have tested it,['c++'] +32593,where can i find a simple aspnet mvc c tutorials i am coming from a php background and i am familiar with oop concepts but i am moving away from php and trying out aspnet mvc using c even without being forced to use web forms this is a big jump for me coming from php this is worsened by the fact that there are not very many tutorials out there on this subject in comparison to php all the tutorials i have found online are too complex or not very well put together so when i am going through them i always miss something that adds much confusion that being said i understand the visual studio ide pretty well from past experiencesis there any decent and simple mcv tutorial out there on the web that would be decent for a php programmer,['asp.net'] +32594,php check process id this is something i have wondered for a while and decided to ask about itwe have the function getmypid which will return the current scripts process id is there some kind of function such ascheckifpidexists in php i mean a inbuilt one and not some batch script solutionand is there a way to change a scripts pidsome clarificationi want to check if a pid exists to see if the script is already running so it dont run again faux cron job if you willthe reason i wanted to change the pid is so i can set the script pid to something really high such as 60 and hard code that value so this script can only run on that pid so only 1 instance of it would runeditto help anyone else with this proplem i have created this classclass instance private lock file private is running false public function constructid file id md5id thislock file sys get temp dir id if file existsthislock file thisis running true else file fopenthislock file w fclosefile public function destruct if file existsthislock file thisis running unlinkthislock file public function is running return thisis running and you use it like soinstance new instanceabcd the argument is optional as it defaults to file if instanceis running echo file already running else echo file not running,['php'] +32613,detecting support for specific html 5 features via jquery i am working on some html5 demo code including stuff like input typedate this currently works correctly in opera 10 asis but every other browser just thisplays a normal text input i am then using a jquerydateinput plugin to override this behaviour on browsers that do not support itproblem is the jquerys running on opera as well so in opera i am getting two calendar datepickers one from the browser one from jqueryi can work around this for now using if windowopera but is there some way using say jquerysupport that i can reliably detect whether the current browser supports a particular html5 feature or not,['jquery'] +32617,google search from a python app i am trying to run a google search query from a python app is there any python interface out there that would let me do this if there is not does anyone know which google api will enable me to do this thanks,['python'] +32618,nsbundle plist and other resources in an objc static library i have created a static library in xcode which i am able to successfully use in other projects however with resources like plists i find i must include any plists referenced in my library in the main project where the project is usedin my static library project i have my plist included in the copy bundle resources phase of the target in my code here is what i am doingnsbundle mainbundle nsbundle mainbundlensstring filepath mainbundle pathforresourcemyclassparams oftypeplistnsmutabledictionary params nsmutabledictionary alloc initwithcontentsoffilefilepathif i use mainbundle and the myclassparamsplist is included in the main project all is good if myclassparamsplist is included in the library project it does not work on the assumption that nsbundle mainbundle was referencing the wrong static method to use i replaced it with nsbundle mainbundle nsbundle bundleforclassmyclass classthis did not work either so is it possible to include a plist or any other resources with a static library or do i have to include whatever i need in the project where the lib is used,['iphone'] +32643,sql query to group by day i want to list all sales and group the sum by daysales saleid int amount int created datetimeupdatei am using sql server 2005,['sql'] +32654,how to get the database time with jpql with native sql i get the database time with a statement likeselect current timestampwith jpql i get the same result withselect current timestampfrom customer cwhere cid1is there a way to get rid of the last two linesthanks,['java'] +32661,downsides to with schemabinding in sql server i have a database with hundreds of awkwardly named tables in it cg001t gh066l etc and i have views on every one with its friendly name the view customers is select from gg120t for example i want to add with schemabinding to my views so that i can have some of the advantages associated with it like being able to index the view since a handful of views have computed columns that are expensive to compute on the flyare there downsides to schemabinding these views i have found some articles that vaguely allude to the downsides but never go into them in detail i know that once a view is schemabound you cannot alter anything that would impact the view for example a column datatype or collation without first dropping the view so that is one but aside from that it seems that the ability to index the view itself would far outweigh the downside of planning your schema modifications more carefully,['sql'] +32664,32bit to 16bit floating point conversion i need a crossplatform libraryalgorithm that will convert between 32bit and 16bit floating point numbers i do not need to perform math with the 16bit numbers i just need to decrease the size of the 32bit floats so they can be sent over the network i am working in ci understand how much precision i would be losing but that is ok for my applicationthe ie 16bit format would be great,['c++'] +32679,how to prevent your javascript code from being stolen copied and viewed i know its impossible for 100 protection but something high or that works for majority of the users for instance i encountered a site where viewing the current pages source returned nothingin another case accessing or trying to download the js files itself from browserwould redirect you and stuffif you obfuscate your code will it be very very difficult to decode it if so that is also another good solution what software is recommended,['javascript'] +32682,move imageview around inside relativelayout i need to move an imageview or anything else for that matter around inside a relativelayout does any one know the proper way to do this,['android'] +32691,initializing char pointers i have a char pointer which would be used to store a string it is used later in the programi have declared and initialized like thischar p nulli am just wondering if this is good practice i am using gcc 433,['c'] +32694,nose test script with command line arguments i would like to be able to run a nose test script which accepts command line arguments for example something along the linestestpyimport nose sysdef test do something with the command line arguments print sysargvif name main noserunmodulehowever whenever i run this with a command line argument i get an error python testpy argeerror failure importerror no module named argtraceback most recent call last file libraryframeworkspythonframeworkversions26libpython26sitepackagesnose01py26eggnoseloaderpy line 368 in loadtestsfromname module resolve nameaddrmodule file libraryframeworkspythonframeworkversions26libpython26sitepackagesnose01py26eggnoseutilpy line 334 in resolve name module import joinparts copyimporterror no module named argran 1 test in 01sfailed errors1apparently nose tries to do something with the arguments passed in sysargv is there a way to make nose ignore those arguments,['python'] +32698,android application update how to what is the best way to let my users perform an application updateis there any way to force device reboot after the update i am asking this because my application registers some behavior on bootplease note the application would not be published in the market updatemy app will be preinstalled on a set of 100 handsetsshould i periodically call a webservice that will inform the device about upgrade available and then redirect to an apk file within a webkit view,['android'] +32702,sharing code between aspnet mvc controllers i have got a few controllers here at work that contain methods i can use in other controllersi considered moving out some of the common functionality to a base controller which these could then inherit from the problem with this is that iad have methods i need in multiple base controls which iad not be able to access because we cannot inherit from multiple base controllersmy other idea is to move out the common functionality into their own classes outside of the controller folderwhat would you do is there a great way in aspnet mvc to share code like this that i do not yet know about,['c#'] +32709,detect underlying cause for javaiofilenotfoundexception filenotfoundexception is thrown on all sorts of occasions not necessarily only when the file name is invalid but also when e g permissions do not allow a file to be created or readjavaiofilenotfoundexception serversharedirectorytestcsv anmeldung fehlgeschlagen unbekannter benutzername oder falsches kennwort at javaiofileoutputstreamopennative method at javaiofileoutputstreaminitfileoutputstreamjava179 at javaiofileoutputstreaminitfileoutputstreamjava131 at javaiofilewriterinitfilewriterjava73the above example shows a german windows complaining about invalid username or passwordis there a way short of parsing the exceptions message to get a little finer grained information on why exactly the exception occurred problem with message parsing is that in different locales the messages will vary,['java'] +32731,hidden columns in jqgrid is there any way to hide a column in a jqgrid table but have it show as readonly when the row is edited in the form editor modal dialog,"['javascript', 'jquery']" +32739,what elements of net are missing in mono i mean library and syntax of c,"['c#', '.net']" +32743,updating multiple values mysql how can i update multiple values in mysql this did not work update test set list0price 0 cprice 0 where testid 3232,"['sql', 'mysql']" +32763,web application on an iphone styling it to look like native iphone app i saw some web pages thisplay diffrently on an ipod touch and iphone they pretty much looked like the native iphone appsthink this can be done with styles and optionally rendering diffrent html on the server side based on the user agent from request so how do i get this effect and also is there any emulator of iphone os browser so i could test my application before really launching it to see if it even thisplays,"['iphone', 'html', 'css']" +32769,varchar migration question for ruby on rails i have created a new table including a column note the default is varchar255 i believe but i wish to have this column be a text area vs a field and to allow more data i imagine that i would make this change in activerecordmigration file but i am curious as to the format do i simply change the varchar255 to varchar10 for example if so what is the formatdef selfup create table notes do t tstring note varchar10 endis that the right format furthermore how do i get the entry field to be multiple rows sorry if this is easy stuff but i am new to programming and ror thanks,['ruby-on-rails'] +32784,javascript memory profiler i am looking for a good javascript memory profiler specifically one that targets ie and any suggestions on how to go about finding javascript memory leaks would also be appreicated,['javascript'] +32787,python urllib2 reading content body even during httperror exception i am using urllib2 to fetch a a page via http sometimes the resource throws a http error 400 bad request when my request contains an error however that response also contains an xml element that gives a detailed error message it would be very handy to be able to see that error rather than just the httperror exception returned by urllib2 how do i return the document contents in spite of the exception,['python'] +32793,is there a rich domain model example i am looking for a simple example to illustrate the benefits of using a rich domain model ideally i would like a before and after code listing which should be as short as possiblethe before code listing should show the problem being solved using an anemic domain model and a lot of fairly procedural servicelayer code and the after code listing should show the same problem being solved using a rich objectoriented domain modelideally the code listing should be in java or groovy but anything fairly similar eg c would do,"['c#', 'java']" +32796,js function to calculate complementary colour does anybody know off the top of your heads a javascript solution for calculating the complementary colour of a hex valuethere is a number of colour picking suites and palette generators on the web but i have not seen any that calculate the colour live using jsa detailed hint or a snippet would be very much appreciated,['javascript'] +32811,commercializing a php application say i have developed a php webapp and would like to thistribute it for others to use as proprietary software is there anything i can do short of some sort of licence or just trusting the customer to avoid having to provide a hosted solution clearly if i just thistribute the application to paying customers to host independently i run the risk of them leaking the codeupdatesome of the responses so far suggest obfuscation however this would not prevent another user from simply plopping the leaked obfuscated code onto their servers and reusing it granted they would not be able to modify itbut i am looking for something more complete any ideas,['php'] +32816,how can i get all the inherited classes of a base class class foo class foo1 foo class foo2 foo how would i be able to get all the classes that use foo as a base class the inherited classes are not necessary in the same assembly,['c#'] +32821,why declare a variable or function static in c i understand what static does but not why we use it is it just for keeping the abstraction layer,['c'] +32863,how to count the number of times something occurs inside a certain string in python i remember there is a function to do thiscount the big brown fox is brownbrown 2,['python'] +32864,fetching single row single column with pdo i have a mysql query that targets a single column in a single row select some col name from table name where useruserafter i execute the statement stmtexecute how do i get this single cell directly placed into a variable with no loops in other words how to get from stmtexecuteto col value 100i tried the 2 below but neither worked the column is number 4 in the original table but i am assuming since in my select statement i am selecting it only it should be 1 when i specify the parameter for fetchcolumn col value stmtfetchcolumncol value stmtfetchcolumn0as you can see i am trying to do it in as few lines as possible,"['php', 'mysql']" +32876,is converting a namevaluecollection to a querystring using a c lamdba efficient in researching how to convert a namevaluecollection to a querystring i have come across different methods i am curious if the shorter lambda syntax is as efficient as it could behow to convert namevaluecollection to a query string using a iterating functionpublic static string constructquerystringnamevaluecollection parameters liststring items new liststring foreach string name in parameters itemsaddstringconcatname systemwebhttputilityurlencodeparametersname return stringjoin itemstoarrayjoin a namevaluecollection into a querystring in c uses a lambda expression which looks nice but i am not sure if it is efficient codeprivate static string joinnvctoqsnamevaluecollection qs return stringjoin arrayconvertallqsallkeys key stringformat01 httputilityurlencodekey httputilityurlencodeqskey,['c#'] +32880,how can i tell reliably if a boost thread has exited its run method i assumed joinable would indicate this however it does not seem to be the case in a worker class i was trying to indicate that it was still processing through a predicatebool isrunningreturn thread joinablewouldnt a thread that has exited not be joinable what am i missing what is the meaning of boost threadjoinable,['c++'] +32883,how do i convert a string object into a hash object i have a string which looks like a hash key a key 1a value 1a key 2a value 2a key b key 1b value 1b how do i get a hash out of it like key a key 1a value 1a key 2a value 2a key b key 1b value 1b the string can have any depth of nesting it has all the properties how a valid hash is typed in ruby,['ruby'] +32885,running a jar file without directly calling java i am deploying a commandline tool that is written in java that accepts commandline arguments i have it packaged as a jar file because it is convenient to have a single filethe problem is that to run it you must first call java jar filename args and that is quite annoyingthe current way i have it is to have a simple bash script that launches it but this is less than idealis there anyway in linux ubuntu server to make a jar file that invokes the java vm by itself i have looked for a shebang but could not find one which of course makes sense since it is compiled codethis is what i want to do myprogramjar arg1 arg2 instead of this java jar myprogramjar arg1 arg2thanksbrian,['java'] +32908,javascript min max array values how can i easily obtain the min and max values from a javascript arrayexample codevar arr 100 0 50 something like but it does not have to bearrmin return 0arrmax return 100,['javascript'] +32917,high quality jpeg compression with c i am using c and want to save images using jpeg format however net reduces quality of the images and saves them with compression that is not enoughi want to save files with their original quality and size i am using the following code but compression and quality are not like the original ones bitmap bm bitmapimagefromfilefilepath imagecodecinfo codecs imagecodecinfogetimageencoders imagecodecinfo ici null foreach imagecodecinfo codec in codecs if codecmimetype imagejpeg ici codec encoderparameters ep new encoderparameters epparam0 new encoderparametersystemdrawingimagingencoderquality long100 bmsavecquality xtostring jpg ici epi am archiving studio photos and quality and compression is very important thanks,"['c#', '.net']" +32929,how can i get pyplot images to show on a console app i am trying to create an image using matplotlibpyplotimshow however when i run the program from my console it does not thisplay anythingthis is the codeimport matplotlibpyplotmyimage gen imagematplotlibpyplotgraymatplotlibpyplotimshowresultsbut this shows nothing,['python'] +32937,what is the interop dll i need some clarification i have a reportwriter dll that uses crystal reports it is written in vb6 i have to add this dll to my aspnet project where it creates an interop dllto my understanding the interop dll is there as an intermediary so that my net code can speak to the reportwriter dllso do i register the interop dll or do i register the original dll,['asp.net'] +32940,can mysql replace multiple characters i am trying to replace a bunch of characters in a mysql field i know the replace function but that only replaces one string at a time i cannot see any appropriate functions in the manualcan i replace or delete multiple strings at once for example i need to replace spaces with dashes and remove other punctuation,"['sql', 'mysql']" +32973,why does python v write to the error stream i was writing a script to inspect pythons version on my system and i have noticed that python v writes to the error stream while python h for instance uses the standard output is there a good reason for this behavior,['python'] +32984,what does c mean in gcc inline assembly code i am trying to understand this inline assembly code which comes from hypercall0 hereasm volatile call hypercall pagecoffset r res offset i hypervisor name sizeofhypercall page0 memory edi esi edx ecx ebx eaxi am having trouble finding information on what c in the first line means i did not find any information in the most obvious section of the gcc manual which explains name but not cname is there any other place i should look at,['c'] +32996,error 2003 hy0 cannot connect to mysql server on 127001 1 i use the following commandmysql u root h 127001 pand the error message is error 2003 hy0 cannot connect to mysql server on 127001 1who can help me to fix it,['mysql'] +33013,can you have multiple httpequiv meta properties i do not really understand what it does but it is set in my project tometa httpequivcontenttype contenttexthtml charsetiso88591 i want to force compatibility mode in ie8 off cos people keep turning it on and it breaks stuff it is software used on the intranet where everyone has ie8i read that i should put this inmeta httpequivxuacompatible contentieemulateie8 to force it off however should i replace the first line with this one have both or do something else entirely,['html'] +33016,how can i trigger the jqgrid loading message i am intercepting server response via datatype but i have noticed that the loading messageis lacking how can i trigger it,['jquery'] +33028,who deletes the memory allocated during a new operation which has exception in constructor i really cannot believe i could not find a clear answer to thishow do you free the memory allocated after a c class constructor throws an exception in the case where it is initialised using the new operator egclass blahpublic blah throw oops void main blah b null try b new blah catch what now when i tried this out b is null in the catch block which makes sensewhen debugging i noticed that the conrol enters the memory allocation routine before it hits the constructor this on the msdn website seems to confirm thiswhen new is used to allocate memory for a c class object the objects constructor is called after the memory is allocatedso bearing in mind that the local variable b is never assigned ie is null in the catch block how do you delete the allocated memory it would also be nice to get a cross platform answer on this ie what does the c spec sayclarification i am not talking about the case where the class has allocated memory itself in the ctor and then throws i appreciate that in those cases the dtor would not be called i am talking about the memory used to allocate the object blah in my case,['c++'] +33039,arguments against annotations my team is moving to spring 30 and there are some people who want to start moving everything into annotations i just get a really bad feeling in my gut code smell when i see a class that has methods like this just an example not all real annotationstransactionmethodgetpathelementtimepathelementdateautowiredsecurerole adminpublic void managequalifiertimeint time am i just behind the times or does this all seem like a horrible idea to anyone else rather then using oo concepts like inheritance and polymorphism everything is now by convention or through annotations i just do not like it having to recompile all the code to change things that imo are configuration seems wrong but it seems to be the way everything especially spring is going should i just get over it or should i push back and try to keep our code as annotation free as possible,['java'] +33042,which twitter api library for ruby do you recommend what is the best twitter api library for ruby i want to do simple things likesearch for specifics keywords for a date rangestart following peopletweet messageshow can i do these things with the library you recommend,['ruby'] +33048,c ninject where do you put the kernel and your modules i am creating a tiny c application which currently consists of a core assembly and a winforms assembly i realize i probably do not really need ninject in a small thing like this but i would like to try it outanyways to work with ninject i have understood that you would write a set of modules which maps class is returned and so on after that you would create an instance of ikernel and load your modules into thatbut where do i keep those modules and where do i keep the kernel where do stuff go,['c#'] +33080,crossplatform equivalent to windows events i am trying to port some windows code to linux ideally through platformindependent libraries eg boost however i am not sure how to port this bit of event codethe bit of code involves two threads lets call them a and b a wants to do something that only b can so it sends b a message then waits for b to say its done in windows this looks something likevoid foothread a calls thisvoid barhandle evtvoid foo handle evt createevent0falsefalse0 bcallboostbindbar evt waitforsingleobjectevtinfinite closehandleevtvoid barhandle evt dosomething seteventevti looked at the boostthread library but it didnt seem to have anything that does this the closes i could see was the boostcondition variable but it appears that is means in conjunction with a mutex which is not the case here,['c++'] +33100,how to get a dom element from a jquery selector i am having an impossibly hard time finding out to get the actual domelement from a jquery selector sample codeinput typecheckbox idbob var checkbox bobclickfunction some code and in another piece of code i am trying to determine the checked value of the checkbox if checkboxeq0somemethodtogetarealdomelementchecked do somethingand please i do not want to do if checkboxeq0ischecked do somethingthat gets me around the checkbox but other times i have needed the real domelement,"['javascript', 'jquery']" +33102,what is the difference between focus and active what is the difference between the focus and active pseudoclasses,['css'] +33103,php server on local machine i am trying to build a php site and i am wanting to test my php files without uploading them to my host basically testing them on my own machine before i upload themthis question has probably been asked a million times but i cannot seem to find a thread on it any help would be appreciatedthanks in advancerich,['php'] +33110,confusion in htons little endian big endian when i send a integer variable from one process to other through socket and then printing the value at received end the value is still the same without using ntohlhtonl then where do i need to use these functions other than initializing socket structures i understand littebig endian but why do we need to convert port and ip nos to hostnetwork byte order when value remains the same please explain in detail how the integer is tranferred over network,['c'] +33112,javac not working in windows command prompt i am trying to use javac with the windows command prompt but its not workingafter adding the directory cprogram filesjavajdk160 16bin to the end of the environment path variable the java command works fine but using javac gives me the errorjavac is not recognized as an internal or external command operable program or batch fileany ideas thanks,['java'] +33140,c virtual function implementation if i have in cclass a private virtual int myfunctionvoid return 1class b public a private virtual int myfunctionvoid return 2then if i remove virtual from the myfunction definition in class b does that mean that if i had a class c based on class b that i could not override the myfunction since it would be statically compiledalso i am confused as to what happens when you switch around public and private here if i change the definition of myfunction in class b to be public and the one in class a remains private is this some sort of grave error that i should not do i think that virtual functions need to keep the same type so that is illegal but please let know if that is wrongthanks,['c++'] +33141,when using object initializers why does the compiler generate an extra local variable while answering a question on so yesterday i noticed that if an object is initialized using an object initializer the compiler creates an extra local variableconsider the following c 30 code compiled in release mode in vs2008public class class1 public string foo get set public class class2 public string foo get set public class testharness static void mainstring args class1 class1 new class1 class1foo foobar class2 class2 new class2 foo foobar2 consolewritelineclass1foo consolewritelineclass2foo using reflector we can examine the code for the main methodmethod private hidebysig static void mainstring args cil managed entrypoint maxstack 2 locals init 0 class classlibrary1class1 class1 1 class classlibrary1class2 class2 2 class classlibrary1class2 g initlocal0 l 0 newobj instance void classlibrary1class1ctor l 05 stloc0 l 06 ldloc0 l 07 ldstr foobar l 0c callvirt instance void classlibrary1class1set foostring l 0011 newobj instance void classlibrary1class2ctor l 0016 stloc2 l 0017 ldloc2 l 0018 ldstr foobar2 l 001d callvirt instance void classlibrary1class2set foostring l 0022 ldloc2 l 0023 stloc1 l 0024 ldloc0 l 0025 callvirt instance string classlibrary1class1get foo l 002a call void mscorlibsystemconsolewritelinestring l 002f ldloc1 l 0030 callvirt instance string classlibrary1class2get foo l 0035 call void mscorlibsystemconsolewritelinestring l 003a ret here we can see that the compiler has generated two references to an instance of class2 class2 and g initlocal0 but only one reference to an instance of class1 class1 now i am not very familiar with il but it looks like it is instantiating g initlocal0 before setting class2 g initlocal0why does this happen does it follow then that there is a performance overhead when using object initializers even if it is very slight,"['c#', '.net']" +33187,access to restricted uri denied code 1012 cross domain ajax request i need to do cross domain ajax request here is my code ajax url redirecturl data logincontainer formserialize querystring type post cache false datatype jsonp jsonp jsonp callback error exception access to restricted uri denied code 1012 nsresult 0x805303f4 ns error dom bad uri location httptestsiteassetsscriptsjquery132js line 19source file httptestsiteassetsscriptsjquery132jsline 19i have checkout the following links too access to restricted uri denied code 1012 ajax url redirecturlcallback data logincontainer formserialize querystring type post cache false datatype html i have tried callback in url too i had already seen all link in stackoverflow regarding this issue but not able to overcome this thingcan anyone please help and tell me how to overcome thanks,['jquery'] +33198,what is the difference between a delegate instance and a method pointer i thought that a delegate instance was interchangeable with a function instancetake the following codedelegate int adelegateint a int badelegate delegateinstancepublic void dostuff i can call this without a delegate instance methodthattakesaddadd i can also call it with a delegate instance delegateinstance add methodthattakesadelegateinstancepublic int addint a int b return a bpublic void methodthattakesaddadelegate addfunction consolewritelineaddfunction1 2tostringboth ways of calling it appear to be equivalent and if youre using only c youll never see the difference at least i have not up to this point however i was recently unmanaged code that was calling back into this managed code they are treated differently for example in one scenario i to get the error a callback was made on a garbage collected delegate if i use the function directly as a callback even though my object instance is kept around using the delegate instance fixes the problemis there someone out there that knows what the difference is,['c#'] +33203,settings iboutlets to nil in dealloc in the section titled memory warnings here i do not follow why the iboutlet is set to nil in the dealloc ifselfanoutlet nilcauses a crash as mentioned in the topic why are they setting the ivar to nilin general why would you set an ivar to nil in the dealloc when you are already calling release,"['objective-c', 'iphone']" +33205,read a file in chunks in ruby i need to read a file in mb chunks is there a cleaner way to do this in rubyfilenamedtmpfilebinmegabyte 10241024size filesizefilenameopenfilename rb do io read 0 while read size left size read cur left megabyte left megabyte data ioreadcur read datasize puts read cur bytes yield data endend,['ruby'] +33208,what can happen as a result of using nolock on every select in sql sever i get that the nolock optimizer hint allows for dirty reads but under what very specific scenarios is this a bad idea i have never seen such widespread use of nolock in an organization and it makes me nervous i would like an explanation in terms of user stories paul does a peter does b x happens instead of y,['sql'] +33209,c generics problem newing up the generic type with parameters in the constructor i am trying to create a generic class which news up an instance of the generic type as followspublic class homepagecarouselt listt where t ihomepagecarouselitem new private listt getinitialcarouseldata listt carouselitems new listt if jewellerhomepages null foreach pagedata pagedata in jewellerhomepages t item new tpagedata this line wont compile carouselitemsadditem return carouselitems but i get the following errorcannot provide arguments when creating an instance of a variable typei found the following related question which is very close to what i needhowever i cannot used jareds suggested answer as i amcalling the method within the generic class not outside ofit so i cannot specify the concrete classis there a way around thisi have tried the following based on the other question butit does not work as i do not know the concrete type of t tospecify as it is called from inside the generic class notoutsidepublic class homepagecarouselt listt where t ihomepagecarouselitem new private listt loadcarouselitems if iscarouselconfigued return getconfiguredcarouseldata i do not know the concrete class for the following line so how can it be instansiated correctly return getinitialcarouseldatal new tl private listt getinitialcarouseldatafuncpagedata t del listt carouselitems new listt if jewellerhomepages null foreach pagedata pagedata in jewellerhomepages t item delpagedata carouselitemsadditem return carouselitems edit added possible solutionsso i have tested 2 possible solutionsfirst is exactly as explained below by jon skeet thisdefinitely works but means having an obscure lambda in theconstructor i am not very comfortable with this as it meansusers need to know the correct lambda that is expectedafter all they could pass a lambda which does not new up thetype but does something entirely unexpectedsecondly i went down the factory method routei added a create method to the common interfaceijewellerhomepagecarouselitem createpagedata pagedatathen provided an implementation in each concrete classpublic ijewellerhomepagecarouselitem createpagedata pagedata return new jewellerhomepagecarouselitempagedata nulland used a two step initialisation syntaxt carouselitem new tt homepagemgmtcarouselitem t carouselitemcreatejewellerpagewould love to hear some feedback on the merit of each of these approaches,['c#'] +33214,css how to increase the size of a osx submit button how do i increase the native form submit button size for osxsafarii want to keep the native look of a form submit button for it is respective operating system while also enlarging the size of the submit button meaning no use of images custom borders etcusing the following cssinputsubmitbutton fontsize150on windows this increase the submit button size height and width as desired regardless of the browser safari firefox ie chromebut on osx safari does not increase the button size at all the form button size remains the default size,['css'] +33216,working on php projects on a remote dev server via sftp i am looking for an editor that can read and write remote php files via sftp i am talking about not having a local copy of my php filesbut here is the tricky part i would like that editor to be aware of all the files in my projet and provide me with intellisenselike autocompletion classes structures etcjust like eclipse pdt aptana and netbeans do but with the remote project storage and awareness featuredo you know about any editor with these features thanks edit i am absolutely not working on my production server but on a development server it is mostly because i need to works under windows on my desktop pc and do not want host my projects locally for various compatibility and tools availability reasons and use linux as a server os,['php'] +33230,functional data structures in java does the java standard library have any functional data structures like immutable sets lists etc with functional update,['java'] +33242,spaghetti stack in c does anybody know where i can find an example of a spaghetti stack written in c,['c'] +33245,java why charset names are not constants charset issues are confusing and complicated by themselves but on top of that you have to remember exact names of your charsets is it utf8 or utf8 or maybe utf8 when searching internet for code samples you will see all of the above why not just make them named constants and use charsetutf8,['java'] +33247,beautifulsoup extracting attribute values if beautiful soup gives me an anchor tag like thisa classblah blah idblah blah hreflinkhtmlahow would i retrieve the value of the href attribute,['python'] +33264,why does a return statement inside a try catch work with throws does not work compilation error missing return statementpublic sqlmapclienttemplate getsqltempl throws uivexception sqlexception try sqlmapclient scl sqlmapclient applicationinitializergetapplicationcontextgetbeanmysqlmapclient datasource dsc datasource servicelocatorgetinstancegetdatasourcepih eiv orcl return new sqlmapclienttemplate dsc scl catch namingexception ne logerrornegetmessage ne workspublic sqlmapclienttemplate getsqltempl throws uivexception sqlexception try sqlmapclient scl sqlmapclient applicationinitializergetapplicationcontextgetbeanmysqlmapclient datasource dsc datasource servicelocatorgetinstancegetdatasourcepih eiv orcl return new sqlmapclienttemplate dsc scl catch namingexception ne logerrornegetmessage ne throw new sqlexceptionunable to get database connection negetmessage why,['java'] +33266,com interop registration i have a net assembly which i am exposing to com the assembly has two public interfaces and one public class when i build the assembly i get this warningassemblynamedll does not contain any types that can be registered for com interopmy assembly information includes the following lineassembly comvisibletruemost people having this problem on the web that i have found fixed it with the above line in their assembly information this has not helped for mei also tried adding comvisibletrue to the class and interface definitions and it also did not help,"['c#', '.net']" +33272,how to avoid scientific notation for large numbers in javascript javascript converts a large int to scientific notation when the number becomes large how can i prevent this from happening,['javascript'] +33274,how do i get the last inserted id of a mysql table in php i have a table into which new data is frequently inserted i need to get the very last id of the table how can i do thisis it similar to select maxid from table,"['php', 'mysql']" +33283,convert html having javascript to pdf using javascript i want to convert html containing javascript to a pdf how can i do thati just want to show what is being shown in web page i am thisplaying a gantt chart that is generated by a javascript library now i want to save that html web page as a pdf how to do that,"['javascript', 'html']" +33284,sql server how to get all child records given a parent id in a self referencing table hi i have a table which references itself and i need to be able to select the parent and all it is child records from a given parent idmy table is as followsid parentid name 1 null a2 1 b13 1 b24 2 c15 2 c2so for the above example i would like to be able to pass in a value of 1 and get all the records aboveso far i have come up with the following recursive tablevaluedfunction but it is not behaving as expected only returning the first recordcreate function dboselectbranches id int parentid intreturns branchtable table id int parentid int name intasbegin if branchid is not null begin insert into branchtable select id parentid name from tbllinkadvertisercity where id id end insert into branchtable select brid brparentid brname from branchtable b cross apply dboselectbranchesnull bparentid br returnendgo,['sql'] +33286,pythonequivalent of shortform if in c possible duplicatepython ternary operator is there a way to write this cc code in pythona b true 123 456 thanks so much,"['c++', 'python']" +33297,which di container will satisfy this this is what i want from di containerpublic class class public classidependency dependency string data var obj diresolveclass new classnull testpoints of interestcan resolve both dependency and data in constructorcan use typesafe syntax to pass constructor parameters exact syntax may vary yes i can do it myself by getting constructor arguments from expressionbody as newexpression but i will need a way to detect what arguments are registered in the containeranother major requirements is that i would like my components to be automatically picked up ie i do not want to register class i want ioc to pick it up because it knows how to resolve idependencyalso property injection can be useful sometimes but this is optionalthe question is really about the combination of features to have all of them typesafe parameters automatic pickup it is easy to check one feature but a combination of them is not easy to verify unless ones familiar with particular container and knows its features thus the question,['c#'] +33300,javascript variable referencealias is it possible in javascript to assign an aliasreference to a local var somewayi mean something clikefunction foo var x 1 var y x y alertx prints 2 edit is it possible to alias argumentscallee in this codefunction foo argumentscalleemystaticvar argumentscalleemystaticvar 0 argumentscalleemystaticvar return argumentscalleemystaticvar,['javascript'] +33308,what is the default chunker for nltk toolkit in python i am using their default pos tagging and default tokenizationand it seems sufficient i would like their default chunker tooi am reading the nltk toolkit book but it does not seem like they have a default chunker,['python'] +33316,how to remove onclick with jquery php codea idaid onclickcheckid1 hrefjavascriptvoid0 classblackqualifyahow to remove onclickcheckid1 so qualify can not be clicked or checkid1 would not be fired how to do it with jquery,['jquery'] +33318,advantage of btree i create indexes without the using btree clause is there any advantage of using btree indexcreate index somename using btree on tbl namecolumn name,['mysql'] +33335,how might a class like nets concurrentbag be implemented i find myself very intrigued by the existence of a concurrentbagt class in the upcoming net 40 frameworkbags are useful for storing objects when ordering does not matter and unlike sets bags support duplicatesmy question is how might this idea be implemented most collections i am familiar with essentially amount to under the hood some form of array in which order may not matter but there is an order which is why even though it does not need to enumeration will pretty much always go through an unchanged collection be it list queue stack etc in the same sequenceif i had to guess i might suggest that internally it could be a dictionaryt linkedlistt but that actually seems quite dubious considering it wouldnt make sense to use just any type t as a keywhat i am expectinghoping is that this is actually an established object type that has already been figured out somewhere and that somebody who knows of this established type can tell me about it it is just so unusual to meone of those concepts that is easy to understand in real life but is difficult to translate into a usable class as a developerwhich is why i am curious as to the possibilitieseditsome responders have suggested that a bag could be a form of a hashtable internally this was my initial thought as well but i foresaw two problems with this ideaa hashtable is not all that useful when you do not have a suitable hashcode function for the type in questionsimply tracking an objects count in a collection is not the same as storing the objectas metaknight suggested perhaps an example would make this more clearpublic class expensiveobject private expensiveobject very intense operations happening in here public expensiveobject createexpensiveobject return new expensiveobject static void main var expensiveobjects new concurrentbagexpensiveobject for int i 0 i 5 i expensiveobjectsaddexpensiveobjectcreateexpensiveobject after this point in the code i want to believe i have 5 new expensive objects in my collection while expensiveobjectscount 0 expensiveobject expobj null bool objecttaken expensiveobjectstrytakeout expobj if objecttaken here i think i am queueing a particular operation to be executed on 5 separate threads for 5 separate objects but if concurrentbag is a hashtable then i have just received the object 5 times and so i am working on the same object from 5 threads at the same time threadpoolqueueuserworkitemdoworkonexpensiveobject expobj else break static void doworkonexpensiveobjectobject obj expensiveobject expobj obj as expensiveobject if expobj null some work to be done,['.net'] +33347,how useful is cs operator so i have been intrigued by the operator but have still been unable to use it i usually think about it when i am doing something likevar x someobject as sometypesomememberif someobject is valid and somemember is null i could dovar x someobject as sometypesomemember defaultvaluebut almost invariably i get into problems when someobject is null and does not help me make this any cleaner than doing the null check myself what uses have you guys found for in practical situations,['c#'] +33367,getting an instance name inside class init while building a new class object in python i want to be able to create a default value based on the instance name of the class without passing in an extra argument how can i accomplish this heres the basic pseudocode i am trying forclass someobject defined name u def init self def namenone if def name none def name us instance name selfdefined name def namethisobject someobjectprint thisobjectdefined name should print thisobject,['python'] +33386,php mysqli fetch field data type i need some help tracking down a bit of nitty gritty information on the information in the fetch field method of a mysqli result objectspecifically the type property from the documentation it would seem that this field returns an integergreati just cannot seem to find a table that will let me translate the number to it is respective data type i am not even sure if i am looking for php or mysql specific information push come to shove i can map it out myself but i would much rather if someone can point me to the actual documentationwhat am i missing,['php'] +33389,sending a file via http put in php i have been struggling for several hours trying to figure out how to get this work i am trying to send a file via httpput to an exist db there is user authentication for the server so i was trying to do something like thisi have the url where the doc is to be putted toi have the username and password for the exist dbi have the content that needs to be sent via the puti tried getting to work with curl but it would fail silentlyi tried to use php streams but kept getting error 201created but no file was actually createdany help with this would be greatly appreciatedheres some sample code i tried using php streams data file get contentstmpfile header array authorization basic base64 encodethisciconfigitemws login thisciconfigitemws passwd contenttype textxml params array http array method put header header content data ctx stream context createparams response file get contentsurl false ctx,['php'] +33399,what is the best way to store users images using php and mysql i was wondering what is the best way to store a users upload images like an avatar and so on using php and mysql where should i begin and is there a good article on this,"['php', 'mysql']" +33403,is it possible to catch out of memory exception in java i am developing a program that would require huge amount of memory and i want to catch when outofmemory exception happens i had heard this is not possible to do but curious if there is any development on this end,['java'] +33411,get heightwidth of image in javascript ideally without loading the image at all sorry if this has already been answered but i cannot find it if soi want to find the height and width of an image file in javascript i do not actually need to show the image in the page just the height and widthat the moment i have got the following code but it is returning height and width 0 in mozilla 5 var img new image imgsrc filenamejpg var imgheight imgheight var imgwidth imgwidth alertimage height imgheight image width imgwidththe file definitely exists it is in the same directory as the html and it does not have height and width 0 what am i doing wrong,['javascript'] +33461,visual studio jump to next error shortcut when a compile fails in vbnet in visual studio 2008 an error list pops up at the bottom of the screen to jump to an error i double click on an error in the error listis there a shortcut to automatically jump to the next error in the list it gets a little bit tedious at times having to reach down and double click a list that i like to keep collapsed,['.net'] +33470,altering http responses in firefox extension how can i alter the http response body in a firefox extension i have setup an httponexamineresponse observer and an nsistreamlistener object with the code below after i get the data parse it and alter it how do i push the altered response back to the firefox browser for example let us say i go to googlecom with my extension enabled the extension should intercept the response and change every occurence of google to goggle so when the page is loaded the user will see goggle everywherefunction tmsteroidsobserver thisregistertmsteroidsobserverprototype observe functionsubject topic data if topic httponexamineresponse else if topic httponmodifyrequest var channel subjectqueryinterfacecomponentsinterfacesnsichannel var listener new streamlistenerchannel register function var observerservice componentsclassesmozillaorgobserverservice1 getservicecomponentsinterfacesnsiobserverservice observerserviceaddobserverlistener httponmodifyrequest false observerserviceaddobserverlistener httponexamineresponse false unregister function var observerservice componentsclassesmozillaorgobserverservice1 getservicecomponentsinterfacesnsiobserverservice observerserviceremoveobserverthis httponmodifyrequest observerserviceremoveobserverthis httponexamineresponse queryinterface functionaiid if aiidequalscomponentsinterfacesnsisupports aiidequalscomponentsinterfacesnsiobserver return this throw componentsresultsns nointerface function streamlistenerchannel channelnotificationcallbacks listener channelasyncopenlistener nullstreamlistenerprototype mdata mchannel null nsistreamlistener onstartrequest function arequest acontext thismdata ondataavailable function arequest acontext astream asourceoffset alength var scriptableinputstream componentsclassesmozillaorgscriptableinputstream1 createinstancecomponentsinterfacesnsiscriptableinputstream scriptableinputstreaminitastream thismdata scriptableinputstreamreadalength onstoprequest function arequest acontext astatus if componentsissuccesscodeastatus request was successfull thismcallbackfuncthismdata else request failed thismcallbackfuncnull thismchannel null nsichanneleventsink onchannelredirect function aoldchannel anewchannel aflags if redirecting store the new channel thismchannel anewchannel nsiinterfacerequestor getinterface function aiid try return thisqueryinterfaceaiid catch e throw componentsresultsns nointerface nsiprogresseventsink not implementing will cause annoying exceptions onprogress function arequest acontext aprogress aprogressmax onstatus function arequest acontext astatus astatusarg nsihttpeventsink not implementing will cause annoying exceptions onredirect function aoldchannel anewchannel we are faking an xpcom interface so we need to implement qi queryinterface functionaiid if aiidequalscomponentsinterfacesnsisupports aiidequalscomponentsinterfacesnsiinterfacerequestor aiidequalscomponentsinterfacesnsichanneleventsink aiidequalscomponentsinterfacesnsiprogresseventsink aiidequalscomponentsinterfacesnsihttpeventsink aiidequalscomponentsinterfacesnsistreamlistener return this throw componentsresultsns nointerface,['javascript'] +33474,iframe background image i have a iframe on my page i have inserted a background image on it but its not showing the image here is my code iframe scrollingauto allowtransparencytrue namemain stylewidth100height90 stylebackgroundimageurlimgbg2jpg iframe,['html'] +33484,converting java projects to c with visual studio 2010 i remember that previous versions of visual studio contained a converter that automatically attempt to convert java projects to the corresponding c codehowever in visual studio 2010 beta 2 i cant find this anymorehas it been removedthanks,"['c#', 'java']" +33485,generated doctrine models respect case but generated yaml does not just getting started with doctrine orm for php v115 and ran into something unexpectedi am generating models from the db mysql 4 usingdoctrinegeneratemodelsfromdbpathtomodelsthen generating yaml from the models usingdoctrinegenerateyamlfrommodelspathtoschema schemayml pathtomodelsin the generated models the column names as defined in hascolumn use the same case for the fields as in the db all goodbut in the generated yaml the column names are all lowercase irrespective of the case in the modelthere do not seem to be any options available on the generateyamlfrommodels method that i could conceivably use to tweak this is there some other attribute i should be setting someplace perhaps at connectionlevel or at managerlevel etc might it be a bugany ideas greatly appreciated thanks and cheers,['php'] +33492,how to compile c under ubuntu linux i cutpasted the below code from a previous question into a file called avishaycpp and then ran gcc avishaycpponly to get the following error messages from the linker what went wrong what should i have donecarlcarlubuntuprojectsstackoverflow gcc static avishaycpp tmpcrnw34o in function static initialization and destruction 0int intavishaycpptext0x41 undefined reference to stdios baseinitinitavishaycpptext0x46 undefined reference to stdios baseinitinittmpcrnw34o in function afuncavishaycpptext zn1a4funcevafunc0x11 undefined reference to stdcoutavishaycpptext zn1a4funcevafunc0x16 undefined reference to stdbasic ostreamchar stdchar traitschar stdoperator stdchar traitschar stdbasic ostreamchar stdchar traitschar char constavishaycpptext zn1a4funcevafunc0x1e undefined reference to stdbasic ostreamchar stdchar traitschar stdendlchar stdchar traitschar stdbasic ostreamchar stdchar traitschar avishaycpptext zn1a4funcevafunc0x26 undefined reference to stdbasic ostreamchar stdchar traitschar operatorstdbasic ostreamchar stdchar traitschar stdbasic ostreamchar stdchar traitschar avishaycpptext zn1a4funcevafunc0x36 undefined reference to stdcoutavishaycpptext zn1a4funcevafunc0x3b undefined reference to stdbasic ostreamchar stdchar traitschar operatorinttmpcrnw34oeh frame0x12 undefined reference to gxx personality v0collect2 ld returned 1 exit statusthe c code not my code i was just trying to run itinclude iostreamusing namespace stdclass aprivate int dmemberpublic void func coutinside a endl cout dmember crash when reach here int main a a null afunc prints inside a return 1,['c++'] +33504,difference between various array copy methods what is the difference betweensystemarraycopyclonemanual copying by iterating through the elements and just doing arraynew arrayold,['java'] +33507,how to syntax highlight in a richtextbox c how do i syntax highlight in a richtextbox control as the user types and using a string keywords i will be publishing a lightweight notepad to the web soon and i want it to have syntax highlighting i am using windows forms can someone post a code example,['c#'] +33512,difference between system and exec in linux what is the difference between system and exec family commands especially i want to know which one of them creates child process to work,['c'] +33513,c connection between iformattable iformatprovider and icustomformatter and when to use what what are the difference and connection between iformattable iformatprovider and icustomformatter and when would they be used a simple implementation example would be very nice too and i do not really mean when it is used in the net framework but when i would implement these myself and in that case what classes would typically implement what interface and how to do it properly,['c#'] +33515,xcode open two editor windows with same file is it possible to open the same file in two separate windows in xcode i can open a file in one window and the same file in the main xcode editor window but i wanted two separate fulltime editor windows,['iphone'] +33518,stm hash library for c glib i am looking for some c library that includes stmstyle software transactional memory hash maps but i had no luck so far it would be great if it was based on glib gobject but it is not that crucial it also does not need proper transactions over many objects single immutable hash support is all i really needmust haves immutable snapshot read lockfree write with autoretry,['c'] +33520,detecting that a method was not overridden say i have the following 2 classesclass a def a method endendclass b aendis it possible to detect from within an instance of class b that method a method is only defined in the superclass thus not being overridden in bupdate the solutionwhile i have marked the answer of chuck as accepted later paolo perrota made me realize that the solution can apparently be simpler and it will probably work with earlier versions of ruby toodetecting if a method is overridden in bbinstance methodsfalseincludea methodand for class methods we use singleton methods similarlybsingleton methodsfalseincludea class method,['ruby'] +33525,multiple mime types in android is there a way to use intentsettype and supply multiple broad types like images and videoi am using an action get content it seems to be working with just commaseparated types,['android'] +33536,best gui for managing mysql 51 what is the best gui for managing mysql 51 installation would like something as close to sql servers management tools as possible as that is where my experience is the management client would need to run under windows xp vista 32 and 64bit flavors and 7 32 and 64bit flavors,['mysql'] +33537,giving command line arguments in xcode in c program i am solving my c assignment in xcode and in that program i have to give command line arguments when running the program and for this i have to user terminal like thisaout myfirstcommand mysecondcommandi was wondering if it possible to give these kind of commands within xcode instead of going to terminal thanks,['c'] +33576,best option for session management in java best way managing session in java i heard that cookies are not reliable option for this as they gets stored into browser and can be accessed later on is this correct if possible please come up with the answers with the coding examplewhich is the best amongurl rewriting server will add an additional parameter at the end of url linkhidden parameter in form server will add an additional parameter at every form in htmlcookie server will ask browser to maintain a cookie,['java'] +33580,hibernate onetoone mapping with interfacei need advice hello good peoplei am developping an application where all the pojos are exposed as interface but we map the real implementation classwe are using spring and jpa annotationi am about to test the onetoone relationship and i am having a light problem with the interfacecaused by orgspringframeworkbeansfactorybeancreationexception error creating bean with name sessioncontainer defined in class path resource metainfmodelconfigxml cannot resolve reference to bean sessionfactory while setting constructor argument nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name sessionfactory defined in class path resource metainfmodelconfigxml invocation of init method failed nested exception is orghibernateannotationexception onetoone or manytoone on commycompanyprojectsubprojectmodeluseraccountimplprofile references an unknown entity commycompanyprojectso before this class all the other mapped class are working as expected so i will only post part of the applicationcontext file that i named modelconfigxmlproperty namehibernateproperties props prop keyhibernatedialecthibernatedialectprop prop keyhibernateshow sqlhibernateshow sqlprop prop keyhibernatehbm2ddlautohibernatehbm2ddlautoprop prop keyhibernateformat sqlhibernateformat sqlprop props property property nameannotatedclasses list valuecommycompanyprojectsubprojectmodeluserprofileimplvalue valuecommycompanyprojectsubprojectmodeluseraccountimplvalue list propertyhere are the two involved class userprofileimpljava and useraccountimpljavauseraccountimpl classentitytablename user accountpublic class useraccountimpl implements useraccount id generatedvalue columnnameuser account id private long id onetoone joincolumnnameuser profile id private userprofile profile userprofileimpl classentitytablenameuser profilepublic class userprofileimpl implements userprofile id generatedvalue columnnameuser profile id private long id onetoonemappedbyprofile private useraccount useraccount i am still not very confortable with hibernate yet so i am wondering if i should change the userprofile reference in useraccountimpl to userprofileimplthen again the same can happen in the userprofileimpl for useraccount reference since it is a bidirectional navigation stuffwhats the best option that will no break the consistency of the structurethanks for reading this,['java'] +33582,can a model belongs to eitheror more than one model apologies if this is a slightly noob question but looking to clarify my thoughts on this i have a model that can either belong to one model or another for examplelet us say i have a team model and i have a member model and both of those models can have one bankaccountclass team has many members has one bank accountendclass member belongs to team has one bank accountendclass bankaccount belongs to team memberendto me the above makes sense but i would love to clarify this with some more experienced rails people does rails have any way of working out what the parent model is of any given bankaccount baring in mind it could be one of two models for example if i called bank accountmember on a team bank account will it throw a wobblythanks for your help,['ruby-on-rails'] +33583,how do i do outerhtml in firefox part of my code i get the outerhtml properyli onclicktabclickedthis searchname tabgroup1name so i can do stuff involing parsing itthere is no outerhtml property in javascript on firefox though and i cannot find an alternative way to get this string ideas,['javascript'] +33585,tddbdd rails cucumber rspec duplication can someone please clarify using a simple user story the full slice of what cucumber would be used for and what rspec would be used for i purchased the rspec book the other day and have been going through it the author seems to be quite vague at timeswhat i am thinking of if the user story is something like please excuse the syntax incorrectness this is just so you get the pointwhen a user enters an invalid telephone numberthen they get a message saying invalid telephone numberif i write out all the code for cucumber to check for this and then write the rspec stuff i am basically duplicating my test is there a scenario to explain how the cucumber test should be different from the rspec testi feel like you would be duplicating tests on both levels all the timeif there is no definitive answer on this i am going to begin to think the cucumber people just did not want to step on the rspec peoples toesplease help i feel like my head is about to explodethanks,['ruby-on-rails'] +33599,hibernategorm collection was not processed by flush i have an integration test in my grails application that fails when i try to save an entity of type memberinvitingmembersaveflush truethis raises the following exceptionorghibernateassertionfailure collection commycompanyfacetfacetchannels was not processed by flush at commycompanymembermemberconnectionserviceaddorupdatecontactmemberconnectionservicegroovy939earlier in the transaction i add an object to a collection property of invitingmember my guess is that the exception is thrown at the line above because it is only at this point that the object added to the collection is persisted,['java'] +33602,how to prevent jpa from rolling back transaction methods invoked1 struts action2 service class method annotated by transactional3 xfire webservice call everything including struts delegatingactionproxy and transactions is configured with spring persistence is done with jpahibernatesometimes the webservice will throw an unchecked exception i catch this exception and throw a checked exception i do not want the transaction to roll back since the web service exception changes the current state i have annotated the method like thistransactionalnorollbackforxfireruntimeexceptionclass exceptionclasspublic actionforward callwsorder order throws exception orderresult orderresult null try orderresult webserviceorderproduct user catch xfireruntimeexception xfireruntimeexception ordersetfailedtrue throw new webserviceorderfailedorder finally persistorder i still get this exceptionorgspringframeworktransactiontransactionsystemexception could not commit jpa transaction nested exception is javaxpersistencerollbackexception transaction marked as rollbackonlywhen i try to reproduce this with junit the transaction is not marked for roll back and it is still possible to commit the transaction how do i make spring not to roll back the transaction,['java'] +33621,sql query not between two dates i need some help with sql query i am trying to select all records from table test table which would not fit between two dates 20091215 and 20100102this is my table structurestart date date not null default 0end date date not null default 0 the following record should not be selectedstart date end date20030604 20100101my queryselect from test table where cast20091215 as date not between start date and end date and cast20100102 as date not between start date and end dateany idea why my query select wrong records should i change the order of values in query to something like start date not between cast20091215 as date and cast20100102 as datethanks a lot for any help,['sql'] +33626,how do i prevent my div layers from overlapping when the browser is resized i have just spent the last few weeks learning how to properly design a layout i basically thought i had everything perfect with my website layout and was ready to go about transferring the coding to wordpress and then i accidentally resized my web browser and thiscovered that all of my div layers were overlapping each other heres what it looks like basically it looks as though it is mainly my center content div that is being squeezed out as well as my header image and navigation witch are in the same top div my footer is also squeezed down as well i have searched the internet for a solution to this problem and cannot seem to find a thinghow do i fix it so that my divs stay in place when the browser is resized,"['css', 'html']" +33632,how to collect system info in osx using objective c is there any method api defined to collect system info in osxi want to write utility which will collect hardware information like cpuramnetwork adapterany idea thanks in advance,['objective-c'] +33633,how should i declare this c struct for interop i have to use a legacy c routine in the application i am developing the code in here works but i have to convert almost all the fields to char arrays in order to use it there is a better way to do it i have tried some version using strings all to no availthis is the code found in the original header filetypedef struct pxucamr char xumrversaocomc01 char xumrretcomc022 char xumrretusuc022 char xumrcodfalhac055 char xumrfiller1c01 char xumrtipoambclic01 char xumrambientec01 char xumrconvertec01 char xumroperacaoc01 char xumropcaoexec01 xumrcom t xumrhandleconnb31 char xumrreshconnc044 long xumrtamdadosb31 char xumrtransacaosrvc088 char xumrtransrvdb2c044 char xumrpgmservidorc088 char xumrversaopgmsrvc022 char xumrconectardbc01 char xumrusuariosrvc088 char xumrsenhasrvc088 char xumridcriptc088 char xumrpgmclientec088 char xumrversaopgmclientec022 char xumridclientec2020 char xumrtipoidclientec01 char xumrusuarioclientec088 char xumrprodutophac1616 char xumridservidorc3030 char xumrdadosc1010pxucamr t and this is the declaration i am using in my c appstructlayoutlayoutkindsequentialinternal struct pxucamr marshalasunmanagedtypebyvalarray sizeconst 1 public char xumrversaocomc01 marshalasunmanagedtypebyvalarray sizeconst 2 public char xumrretcomc02 marshalasunmanagedtypebyvalarray sizeconst 2 public char xumrretusuc02 marshalasunmanagedtypebyvalarray sizeconst 5 public char xumrcodfalhac05 marshalasunmanagedtypebyvalarray sizeconst 1 public char xumrfiller1c01 marshalasunmanagedtypebyvalarray sizeconst 1 public char xumrtipoambclic01 marshalasunmanagedtypebyvalarray sizeconst 1 public char xumrambientec01 marshalasunmanagedtypebyvalarray sizeconst 1 public char xumrconvertec01 marshalasunmanagedtypebyvalarray sizeconst 1 public char xumroperacaoc01 marshalasunmanagedtypebyvalarray sizeconst 1 16 public char xumropcaoexec01 marshalasunmanagedtypei4 public int xumrhandleconnb31 marshalasunmanagedtypebyvalarray sizeconst 4 public char xumrreshconnc04 marshalasunmanagedtypei4 public int xumrtamdadosb31 marshalasunmanagedtypebyvalarray sizeconst 8 36 public char xumrtransacaosrvc08 marshalasunmanagedtypebyvalarray sizeconst 4 public char xumrtransrvdb2c04 marshalasunmanagedtypebyvalarray sizeconst 8 public char xumrpgmservidorc08 marshalasunmanagedtypebyvalarray sizeconst 2 public char xumrversaopgmsrvc02 marshalasunmanagedtypebyvalarray sizeconst 1 public char xumrconectardbc01 marshalasunmanagedtypebyvalarray sizeconst 8 67 public char xumrusuariosrvc08 marshalasunmanagedtypebyvalarray sizeconst 8 public char xumrsenhasrvc08 marshalasunmanagedtypebyvalarray sizeconst 8 public char xumridcriptc08 marshalasunmanagedtypebyvalarray sizeconst 8 public char xumrpgmclientec08 marshalasunmanagedtypebyvalarray sizeconst 2 93 public char xumrversaopgmclientec02 marshalasunmanagedtypebyvalarray sizeconst 20 public char xumridclientec20 marshalasunmanagedtypebyvalarray sizeconst 1 114 public char xumrtipoidclientec01 marshalasunmanagedtypebyvalarray sizeconst 8 public char xumrusuarioclientec08 marshalasunmanagedtypebyvalarray sizeconst 16 138 public char xumrprodutophac16 marshalasunmanagedtypebyvalarray sizeconst 30 168 public char xumridservidorc30 marshalasunmanagedtypebyvalarray sizeconst 10 public char xumrdadosc10is there a better way of doing it editbased in justin rudds answer i have tested this version of the structstructlayoutlayoutkindsequential charsetcharsetansiinternal struct pxucamrv3 public char xumrversaocomc01 marshalasunmanagedtypebyvaltstr sizeconst 2 public string xumrretcomc02 marshalasunmanagedtypebyvaltstr sizeconst 2 public string xumrretusuc02 marshalasunmanagedtypebyvaltstr sizeconst 5 public string xumrcodfalhac05 public char xumrfiller1c01 public char xumrtipoambclic01 public char xumrambientec01 public char xumrconvertec01 public char xumroperacaoc01 public char xumropcaoexec01 16 marshalasunmanagedtypei4 public int xumrhandleconnb31 marshalasunmanagedtypebyvaltstr sizeconst 4 public string xumrreshconnc04 marshalasunmanagedtypei4 public int xumrtamdadosb31 marshalasunmanagedtypebyvaltstr sizeconst 8 36 public string xumrtransacaosrvc08 marshalasunmanagedtypebyvaltstr sizeconst 4 public string xumrtransrvdb2c04 same pattern to remaining fields i have tried it in just some fields with success but i changed all of it problems with the returning values appear for example i send thispxucamrv3xumrpgmservidorc08 phaprexwpxucamrv3xumrversaopgmsrvc02 01pxucamrv3xumrpgmclientec08 phaoclxnpxucamrv3xumrversaopgmclientec02 02pxucamrv3xumridservidorc30 n006pxucamrv3xumrcodfalhac05 0pxucamrv3xumrretcomc02 00pxucamrv3xumrretusuc02 00 and get this pxucamrv3xumrpgmservidorc08 phaprexpxucamrv3xumrversaopgmsrvc02 0pxucamrv3xumrpgmclientec08 phaoclxpxucamrv3xumrversaopgmclientec02 0pxucamrv3xumridservidorc30 n006pxucamrv3xumrcodfalhac05 01 pxucamrv3xumrretcomc02 wpxucamrv3xumrretusuc02 0 as we can see there is a problem with the marshallingunmarshalling of strings the char fields are looking alright it is not a mapping problem as the beggining of the string fields are ok but it seems to be truncating the end of the strings and my test call should not return an error using the previous struct it works so the c routine did not receive the data as it should too should return only zeros in xumrretcomc02 the returned w means there is an error but i there are lots of error codes starting in wi will keep digging into itagain sorry for my poor english,"['c#', '.net', 'c']" +33639,resize uiimage with aspect ratio i am using this code to resize an image on the iphonecgrect screenrect cgrectmake0 0 3200 4800uigraphicsbeginimagecontextscreenrectsizevalue drawinrectscreenrect blendmodekcgblendmodeplusdarker alpha1uiimage tmpvalue uigraphicsgetimagefromcurrentimagecontextuigraphicsendimagecontextwhich is working great as long as the aspect ratio of the image matches that of the new resized image i would like to modify this so that it keeps the correct aspect ratio and just puts a black background anywhere the image does not show up so i would still end up with a 320x480 image but with black on the top and bottom or sides depending on the original image sizeis there an easy way to do this similar to what i am doing thanks,['iphone'] +33643,implementation of redblack tree in c i am looking for an implementation of a redblack tree in c with the following featuressearch insert and delete in olog nmembers type should be genericsupport in comparert for sorting t by different fields in itsearching in the tree should be with the specific field so it would not accept t but it will accept the field type sorting itsearching should not be only exact value should support searching the lowerhigher onethank you,['c#'] +33645,remove excess whitespace from within a string i receive a string from a database query then i remove all html tags carriage returns and newlines before i put it in a csv file only thing is i cannot find a way to remove the excess white space from between the stringswhat would be the best way to remove the inner whitespace characters,['php'] +33652,how to implement a pythonic equivalent of tail f what is the pythonic way of watching the tail end of a growing file for the occurrence of certain keywordsin shell i might saytail f file grep string while read hit do stuffdone,['python'] +33654,is there anything to change the exports name mangling scheme in gcc i am trying to build a project i have and it has several exported functions the functions follow the stdcall convention and they get mangled if compiled with gcc asfuncxother compilers mangle the name like this funcxis any way i can force gcc to mangle the names of the exported functions to the later example,['c'] +33663,building excel files with c i need to create an excel file via c i have read a few places that creating an xml document is the easiest way to do this i need to have multiple named tabs and be able to specify that particular cells are text date time numeric etc any suggestions or good examples,"['c#', '.net']" +33668,timezone by coordinate as the title infers i need to find a time zone or perhaps just the utc offset based on a pair of coordinates i have been searching for different solutions and there is a couple of web services out there but i need to be able to access the application offline as the timezones is not completely based on longitude it does not seem that easyi though about querying an esri shapefile i have got containing all the countries in world and their timezones but it seems kind of complex if that should be the solution do you know of any net library providing this functionality,"['c#', '.net']" +33671,is there a way to force checkstyle to ignore particular warning in the source code pmd has a way to ignore particular warning with nopmdcomment inside java source filedoes checkstyle have similar option,['java'] +33675,rubyrails image processing libraries good friends of stackoverflow i am here today for guidance regarding image processingmanipulation using ruby in a rails environment i am creating onthefly dynamic banner ads that will feature mostly if not completely text it is fairly simple with just a line or two but i would like the option to adjust font text color text size etcwhat libraries do you recommend for this sort of taski have read up in rmagick a little bit and i see a lot of complaints about memory issues and lack of text rendering features i am not seeing many alternative active projectsthanksedit i got a chance to mess around with rmagick and while it is library is full featured it seriously lacks in the text department one feature i am unable to use is nonbreaking spaces i am printing a phone number in my text and it really does not make sense to have the area code on a different line than the rest of the numberi am choosing rmagick as the best solution for now because it is fullfeatured and actively developed but it is by no means a good solution,"['ruby-on-rails', 'ruby']" +33687,when is the earliest i can access session in the aspnet mvc page lifecycle my question is essentially the same as question 765054 on stackoverflow i am only asking it again because the accepted answer is incorrect you can not access the session object in application beginrequest our use case is that we want to store the authenticated users user object in the session so in subsequent requests we can correctly set the iprincipal and iidentity based on the user object in session,['asp.net'] +33694,getting started with libpurple i am writing a cocoa touch program that will hopefully use libpurple as it is background the only problem is that i have no clue where to get started i have been looking through some source code of applications that do use it but so far have not gotten anywhere does anyone know anything that will help me familiarize myself with libpurple,"['iphone', 'c']" +33699,xmlserializer validation i am using xmlserializer to deserialize xml achives but i found the class xsdexe generated only offers capability to read the xml but no validation for example if one node is missing in a document the attribute field of the generated class will be null rather than throws a validation exception as i expected how can i achieve that thanks,['c#'] +33704,java dynamically load multiple versions of same class what i would like to be able to do is to load set of classes probably all in the same folder all of which implement the same interface and are the same class then in my code i would like to be able to call functions on those classes,['java'] +33707,detecting image equality at different resolutions i am trying to build a script to go through my original highres photos and replace the old lowres ones i uploaded to flickr before i had a pro accountfor many of them i can just use exif info such as date taken to determine a match but some are really old and either the original file did not have exif info or it got clobbered by whatever stupid resizing software i used at the timeso unable to rely on metadata i am forced to resort to the content itself the problem is that the originals are in different resolutions than the ones on flickr which is the whole point of this endeavour so is there a way for me to compare them with some sort of fuzzy similarity measure that would allow me to set a threshold for requiring human input or noti guess knowing one image is a resized version of the other can yield better results than general similarity a solution in any language will do but ruby would be a plus,['ruby'] +33708,how to log error message in drupal how to log our own error messagesfor ex error due to invalid user date entry which is generated in php program to drupal error log,['php'] +33714,sinatra bundler i am wondering how one can use bundler with sinatra the idea is to use the gems that bundler downloads inside the gems folder,['ruby'] +33731,uploading multiple files in django through one form field is there any custom widget or a special magic way to upload multiple files or a whole folder through one form fieldi have tried this multifile widget but it uses many simple filefileds,['python'] +33733,handling function key press i have a c form with 5 buttons the users enters the information and depending on the press of a function key a specific action is performed f9execute order f6save f3lookupi have added the foolowing codeonform loadthiskeyup new systemwindowsformskeyeventhandlerkeyeventand private void keyeventobject sender keyeventargs e keyup event if ekeycode keysf9 messageboxshowfunction f9 if ekeycode keysf6 messageboxshowfunction f6 else messageboxshowno function but nothing happensthanks,['c#'] +33741,should we use workstation garbage collection or server garbage collection i have a large multithreaded c application running on a multicore 4way server currently were using server mode garbage collection however testing has shown that workstation mode gc is quickermsdn saysmanaged code applications that use the server api receive significant benefits from using the serveroptimized garbage collector gc instead of the default workstation gcworkstation is the default gc mode and the only one available on singleprocessor computers workstation gc is hosted in console and windows forms applications it performs full generation 2 collections concurrently with the running program thereby minimizing latency this mode is useful for client applications where perceived performance is usually more important than raw throughputthe server gc is available only on multiprocessor computers it creates a separate managed heap and thread for each processor and performs collections in parallel during collection all managed threads are paused threads running native code are paused only when the native call returns in this way the server gc mode maximizes throughput the number of requests per second and improves performance as the number of processors increases performance especially shines on computers with four or more processorsbut were not seeing performance shine has anyone got any advice,"['c#', '.net']" +33742,is it possible to use ref types in c builtin action delegate c has builtin delegates action and func is it possible to use ref type parameters for this delegates for example this codepublic delegate void dtest ref guid a public event dtest etestwill compile but if i use action it will not compilepublic event action ref guid etestany hints,['c#'] +33754,call python function from matlab i need to call a python function from matlab how can i do this,['python'] +33756,clear code for counting from 0 to 255 using 8bit datatype i was wondering if there is a clean way of counting from 0 to 255 using an 8 bit datatype something likeforuint8 t i0i255i this obviously will not work but it makes it clear you want to count from 0 to 255 a working solution would be something likeuint8 t i0do iwhilei 0but here it is not at all clear it counts from 0 to 255this will also work but it is just ugly imhouint8 t i0whiletrue if i 255 break iso i was wondering is there a clean way of doing this without using a larger datatypeediti like the version using for because it makes its intend clear without thinking looping from 0 to 255 all other versions require some thought about what is going on and therefore more likely to confuse othersi do not want to use int because the code is for a 8bit microcontroller with not much memory,['c'] +33759,date sorting problem with jquery tablesorter i am trying to sort a table which has column like 20091217 2359590i am using below to apply sort documentreadyfunction datatabletablesorter but its not working for the dates of format ymmdd can any one suggest how can i apply this format for sorting,['jquery'] +33761,fast way to filter illegal xml unicode chars in python the xml specification lists a bunch of unicode characters that are either illegal or thiscouraged given a string how can i remove all illegal characters from iti came up with the following regular expression but it is a bit of a mouthfulillegal xml re recompileux00x08x0bx1fx7fx84x86x9fud800udfufdd0ufddfufeufclean illegal xml resub dirtypython 25 does not know about unicode chars above 0xf so no need to filter those,['python'] +33776,how to thisable jquery keypress event for just one element on my site i have registered a keypress event handler for the whole documentdocumentkeypressmyhandlerand i handle the space key to scroll a listtrouble is there is an input typetext element and i do not want space keypress to scroll the list when it is entered in the inputi could not find any information in the event object passed by jquery to the handler to identify where the source of the event is,"['javascript', 'jquery', 'html']" +33778,python list vs tuple when to use each in python when should you use lists and when tuplessometimes you do not have a choice for example if you havehello s you are s years old xthen x must be a tuplebut if i am the one who designs the api and gets to choose the data types then what are the guidelines,['python'] +33779,jquery post possible to do a full page post request i know i can do an out of band post request with jquery and the post syntax however i am interested to know if it is possible for jquery to cause a post request on the whole page as when a form is submitted so that a brand new page is loaded is this possiblethere is no form element in the dom so i cannot do formsubmit,['jquery'] +33783,php recursively unset array keys if match i have the following array that i need to recursively loop through and remove any child arrays that have the key fields i have tried array filter but i am having trouble getting any of it to workmyarray array item array fields arrayid name part array fields arraypart number part name owner array fields arrayid name active company array fields arrayid name locations array fields arrayid name address zip state array fields arrayid name this is how i need it the result to look likemyarray array item array part array owner array company array locations array state array,['php'] +33788,what does u mean in a list this is the first time i have came across this just printed a list and each element seems to have a u in front of it ie uhello uhi uheywhat does it mean and why would a list have this in front of each elementas i do not know how common this is if youd like to see how i came across it i will happily edit the post,['python'] +33800,why is the nodoc syntax needed it seems a lot of librariesplugins use this syntax def selfincludedbase nodoc baseextend classmethods endwhy is the nodoc part necessary,['ruby'] +33803,euclidian thistance python implementation i am playing with the following code from programming collective intelligence this is a function from the book that calculated eclidian thistance between two movie criticsthis function sums the difference of the rankings in the dictionary but euclidean thistance in and dimensions also includes the square root of that sumafaik since we use the same function to rank everyone it does not matter we square root or not but i was wondering is there a particular reason for thatfrom math import sqrt returns a thistancebased similarity score for person1 and person2 def sim thistanceprefsperson1person2 get the list of shared items si for item in prefsperson1 if item in prefsperson2 siitem1 if they have no ratings in common return 0 if lensi0 return 0 add up the squares of all the differences sum of squaressumpowprefsperson1itemprefsperson2item2 for item in prefsperson1 if item in prefsperson2 return 11sum of squares,['python'] +33807,why is eclipse trying to copy my svn folders from src to bin and how can i make it stop i have checked out a bunch of java code using subversion 16 and then i imported those projects into eclipse subclipse 16 picked up the fact that the plugins are under version control except for a few foldersi now get a bunch of errors likethe resource is a duplicate of srcsvnallwcprops and was not copied to the output folderif i delete the project from eclipse not on thisk and reimport it that fixes the problem about half the time but since i have dozens of projects that are having this problem it means reimporting them 1020 times before i get them all working this is very painful and i am tired of doing it every time someone adds a new plugin to svn or when i need to recreate a workspace for some reasonis there an easier way to fix this than delete and reimport or is there a way to prevent this problem in the first place,['java'] +33821,change system font for iphone application entire application is there a way i can change the system font for an entire applicationi want to define the font for the entire application so that i do not have to go to individual labels or individual fonts to change it i would like a universal definition which will change all the fonts that exist within the application how do i do this,['iphone'] +33829,know any good c support vector machine svm libraries do you know of any good c svm libraries out therei tried libsvm but so far i am not flabbergastedi have also heard of svmlight and tinysvm have you tried them any new players thanks,['c++'] +33839,unit testing for failed malloc what is the best way for unit testing code paths involving a failed malloc in most instances it probably does not matter because youre doing something like thingy my thingy mallocsizeofthingyif my thingy null fprintfstderr were so screwedn exitexit failurebut in some instances you have choices other than dying because youve allocated some extra stuff for caching or whatever and you can reclaim that memory however in those instances where you can try to recover from a failed malloc that youre doing something tricky and error prone in a code path that is pretty unusual making testing especially important how do you actually go about doing this,['c'] +33848,returning a c class to java via jni i am currently using both c and java in a project and i would like to be able to send an object which is contained in c to my java interface in order to modify it via a gui and then send the modification back in cso far i have been returning either nothing an int or a boolean to java via the jni interface this time i have to send an object through the interface i have made similar class definition available both in c and in java i would like to know how i would go about creating the object so that i can use it in javain c i havejniexport myobject jnicall java ca x y z c 1getmyobjectjnienv env jclass jint numberthis function would get called by java in order to get the object from the c side the object is contained in a singleton easily accessibleon the java end i do a simple call to this methodmyobject anobject c getmyobject3which should return me the newly created objectjava currently returns me a unsatisfiedlinkerror when i do the actual call what is wrong,"['java', 'c++']" +33855,how do i specify close existing connections in sql script i am doing active development on my schema in sql server 2008 and frequently want to rerun my dropcreate database script when i run use mastergoif exists select name from sysdatabases where name nmydatabasedrop database mydatabasegoi often get this errormsg 3702 level 16 state 4 line 3cannot drop database mydatabase because it is currently in useif you right click on the database in the object explorer pane and select the delete task from the context menu there is a checkbox which to close existing connectionsis there a way to specify this option in my script,['sql'] +33860,what is this weird colonmember syntax in the constructor recently i have seen an example like the followinginclude iostreamclass foo public int bar fooint num barnum int mainvoid stdcout foo42bar stdendl return 0what does this strange barnum mean it somehow seems to initialize the member variable but i have never seen this syntax before it looks like a functionconstructor call but for an int makes no sense for me perhaps someone could enlighten me and by the way are there any other esoteric language features like this youll never find in a ordinary c book,['c++'] +33882,php and concurrency i have been doing some web development work in php recently which has led me to study up on the language in general so far i have not needed to use it to interact with a database but i know it provides a lot of convenient functions for doing soalthough i know basic sql and have worked with basic manipulation of data in a database i do not understand how web developers who base their websites around phpjavascriptsql are able to manage users modifying the same data at the same timefor example lets say you have a blackjack website which divides users into one of two teams when they sign up every time a user wins a game a portion of their winnings is added to a running total for that teamso lets say the pseudo code for the function that does this looks something like this total mysql queryselect score from team1total total mytotalmysql queryupdate team1 set scoretotalif two players are playing at the same time it is very possible that they will both call select before the other one has a chance to increment and update the table so one users changes will be immediately overwritten my question is how does one avoid this is it done using php at the code level or are there features provided by whatever database you are using that help to prevent this i have been doing some research and it seems that php does provide a semaphore mechanism and i have also noticed that mysql offers a lock table feature however i am not sure which of these if either is used in practice,['php'] +33889,linker error iphone unit test bundle referencing app classes starting with an app already in development i have carried out the instructions in the iphone development guide a unit testing applicationsi can successfully include and use my apps classes in applicationstyle tests that run on the device and output their results to the consoleif i add the following line of codestasserttrueviewcontroller iskindofclassloginviewcontroller class top view controller is not loginviewcontrollerthe following build error is generatedundefined symbols objc class loginviewcontroller referenced from objc classrefs data0 in loginviewtestold symbols not foundcollect2 ld returned 1 exit statusi can provide more configuration information for the project and the testing target but the setup works file without the loginviewcontroller class line in the test sourcewithout that line i can reference the class use it is properties and send it messages successfullyis there a linking build setting or bundle loading option that is required when attempting to use an app class in this fashion or should i find another type of test to confirm that the class of an object is the expected one,['iphone'] +33910,joda time gives wrong time zone i am using the joda time 16 libraries and it keeps returning datetime objects with the wrong time zone british summer time instead of gmtmy windows workstation running jdk 160 16 thinks it is in gmt and if i get the default time zone from the jdk datetime classes it is correct gmt i get the same behaviour on our linux servers as well i thought it could be an error in the time zone database files in joda so i rebuilt the jar with the latest database but with no change import javautiltimezoneimport orgjodatimedatetimeimport orgjodatimedatetimezoneimport orgjodatimelocaltimeimport orgjodatimeformatdatetimeformatterimport orgjodatimeformatisodatetimeformatpublic class timezonetest public static void mainstring args datetimeformatter timeparser isodatetimeformattimeparser timezone timezone timezonegetdefault systemoutprintlntimezonegetid europelondon systemoutprintlntimezonegetthisplayname greenwich mean time datetimezone defaulttimezone datetimezonegetdefault systemoutprintlndefaulttimezonegetid europelondon systemoutprintlndefaulttimezonegetname0l british summer time datetime currenttime new datetime datetimezone currentzone currenttimegetzone systemoutprintlncurrentzonegetid europelondon systemoutprintlncurrentzonegetname0l british summer time debugging through the static initialiser in orgjodatimedatetimezone i see that the systemgetpropertyusertimezone call gives europelondon as expected,['java'] +33914,how can one variableargs function call another say you have 2 functionsvoid funcint xint y do stuffvoid func2int x funcx123how can you make this work eg pass the arglist to the other functionedit this is a duplicate can someone merge them or whatever,['c'] +33939,adding a keyword argument to an overriden method and using kwarg i am subclassing an object in order to override a method that i want to add some functionality to i do not want to completely replace it or add a differently named method but remain compatible to the superclasses method by just adding an optional argument to the methodis it possible to work with args and kwargs to pass through all arguments to the superclass and still add an optional argument with a defaulti intutively came up with the following but it does not workclass aobject def fooself arg1 arg2 argopt1bar print arg1 arg2 argopt1class ba def fooself args argopt2foo kwargs print argopt2 afooself args kwargsb bbfooa b argopt2fof course i can get it to work when i explcitly add all the arguments of the method of the superclassclass ba def fooself arg1 arg2 argopt1foo argopt2bar print argopt2 afooself arg1 arg2 argopt1argopt1whats the right way to do this do i have to know and explicitly state all of the overridden methods arguments,['python'] +33951,alternatives to for creating strings containing multiple whitespace characters i am wondering if there is a more oo way of creating spaces in cliterally space codei currently have tabs new string and i cannot help but feel that this is somewhat reminiscent of using instead of stringemptywhat can i use to create spaces that is not,['c#'] +33955,how to insert duplicate rows in sqlite with a unique id this seems simple enough i want to duplicate a row in a sqlite tableinsert into table select from table where rowid5if there were no explicit unique column declarations the statement would work but the tables first column is declared rowid integer not null primary key is there any way to create a simple statement like the one above that works without knowing the schema of the table aside from the first column,['sql'] +33985,iphone inapp purchase store kit error 1003 cannot connect to itunes store i have been working on adding inapp purchases and was able to create and test inapp purchases using store kit yay during testing i exercised my app in a way which caused the app to crash mid purchase so i guess the normal cycle of receiving paymentqueueupdatedtransactions and calling finishtransaction was interruptednow i am unable to successfully complete any transactions and instead am getting only transactions with transactionstate skpaymenttransactionstatefailed when paymentqueueupdatedtransactions is calledthe transactionerrorcode is 1003 and the transactionerrorlocalizeddescription is cannot connect to itunes storei have tried removing all products from itunesconnect and rebuilt them using different identifiers but that did not help i have also tried using the app store app to really connect to the real app store and download some apps so i do have connectivity finally i have visited the settingsstore app to make sure i am signed out of my normal app store account,"['ios', 'iphone']" +33988,how to programatically thisable the autofocus of a webcam i am trying to do computer vision using a webcam the model is hercules dualpix i know it is not the ideal camera to use but i have no choice here the problem is the autofocus makes it hardimpossible to calibrate the camera anyone knows a way to thisable the autofocus feature or if someone has an idea to deal with it and calibrate the camera with the autofocus,['c++'] +33999,installing hpricot on ruby 191 on windows i am trying to install hpricot using the commandgem install hpricot v 082building native extensions this could take a whileerror error installing hpricot error failed to build gem native extensioncruby19binrubyexe extconfrbchecking for stdioh extconfrb failed could not create makefile due to some reason probably lack ofnecessary libraries andor headers check the mkmflog file for moredetails you may need configuration optionsprovided configuration options withoptdir withoutoptdir withoptinclude withoutoptincludeoptdirinclude withoptlib withoutoptliboptdirlib withmakeprog withoutmakeprog srcdir curdir rubycruby19binrubycruby19libruby191mkmfrb362in try do the complier failed to generate an executable file runtimeerroryou have to install development tools first from cruby19libruby191mkmfrb431in try cpp from cruby19libruby191mkmfrb809in block in have header from cruby19libruby191mkmfrb668in block in checking for from cruby19libruby191mkmfrb274in block 2 levels in postpone from cruby19libruby191mkmfrb248in open from cruby19libruby191mkmfrb274in block in postpone from cruby19libruby191mkmfrb248in open from cruby19libruby191mkmfrb270in postpone from cruby19libruby191mkmfrb667in checking for from cruby19libruby191mkmfrb808in have header from extconfrb2in gem files will remain installed in cruby19librubygems191gemshpricot082 for inspectionresults logged to cruby19librubygems191gemshpricot082extfast xsgem makeoutit mentions i need to install development tools but i have no idea what that refers to any suggestions,['ruby'] +34005,how to recreate jquery dialog after destroy i am creating three modal dialogs on page load using documentreadyfunction i create these dialogs by calling a setdialogwindows method and pass it the div for the dialog dialog creation code is belowfunction setdialogwindowselement elementdialog autoopen false modal true show blind hide blind width 600 resizable false buttons cancel function thisdialogdestroy save function thisdialogclose i will spare you the dialog html but there is some jquery dragdrop functionality that i want to be completely reset when the user clicks cancel hence the thisdialogdestroy however when i click the link again to open the dialog box it does not show up i realize this is because i have not reinited it but i really cannot do that because the dialogs are created on page load i tried adding a recursive call of sorts to the cancel function as such cancel function thisdialogdestroy setdialogwindowselement but that does not work still nothing opens when i click the link that should open it is there a way to just recreate the dialog box any ideas on where i should be reinitializing the dialog if the only place i do it now is on documentreadythanks,['jquery'] +34014,what is the right approach when using stl container for median calculation let us say i need to retrieve the median from a sequence of 10 random numeric valuesif using anything but stllist i have no builtin way to sort sequence for median calculation if using stllist i cannot randomly access values to retrieve middle median of sorted sequenceis it better to implement sorting myself and go with eg stlvector or is it better to use stllist and use stllistiterator to forloopwalk to the median value the latter seems less overheathish but also feels more uglyor are there more and better alternatives for me,['c++'] +34029,determine if sqlite3 transaction is active i am running an end transaction on my database and occasionally i get error1 that cannot commit no transaction is activeis there a way to determine if a transaction is active before trying a commit i have been tracking my begin transactions by hand but i feel there is a better wayi am using the c api,['iphone'] +34041,mvc jquery submit form without page refresh from javascript function i am pretty new to all thisi am using aspnet mvc c linq to sqli have an edit page that loads authors and all their booksthe books are loaded via an ajax call script typetextjavascript documentreadyfunction loadbooks function loadbooks bookshide booksloadbooksedit modelauthorid booksshowslow scriptthis part is working fine the page loads with the author info then the books load a partial view in a div idbooks just with the book category and book title control languagec inheritssystemwebmvcviewusercontrolsolutioncontrollersbookscontrollerbooksviewmodel using htmlbeginformnullnull formmethodpostnew id bookform fieldset legendbookslegend int i 0 foreach var book in modelbooks bookbookid htmlhiddenbook i bookid bookbookid htmldropdownlistbook i catid new selectlistmodelcategories catid cattitle bookcatid htmlvalidationmessagecatid htmltextboxbook i booktitle bookbooktitle htmlvalidationmessagebooktitle br i fieldset now on the main view page i want to have a linkwhen the link is clicked i want to do a few things via javascriptjqueryajaxwhateverthe first thing that i want to happen is to submit the books form id booksform from the partial view then continue on to the next jquery function so i click a link that calls a javascript function this function should calldoexecute the submission of the books formi feel like i have tried everything but i cannot get my books form to submit and process without a full page submitrefresh taking place note when the full submit does take place the actions i would expect in the controller do successfully process i want the controller processaction to return nothing other than some kind of successfailure indication i can then call loadbooks again to refresh the div on the pageany ideas,['jquery'] +34043,how do i fill a bitmap with a solid color i need to create a 24bit bitmap resolution 100x100 pixels using a unique rgb color and save the generated image to the thisk i currently use the setpixel function but it is extremely slowbitmap bmp new bitmapwidth heightbmpsetpixelxycolorfromargbredvalue greenvalue bluevalueis there a faster method than setpixel thanks in advance,['c#'] +34049,how to dynamically create css class in javascript and apply i need to create a css stylesheet class dynamically in javascript and assign it to some html elements like div table span tr etc and to some controls like asptextbox dropdownlist and datalistis it possibleit would be nice with a sample,"['javascript', 'css']" +34059,register file extension in window registry i want to register my own project extension in window registry i searched on google at least i found this code this works well but i do not understand one line what is meaning of lthe c code isstring ext ext registrykey key registryclassesrootcreatesubkeyext messageboxshowexepath keysetvalue my project keyclose key registryclassesrootcreatesubkeyext shellopencommand key keycreatesubkeycommand keysetvalue applicationexecutablepath l keyclose key registryclassesrootcreatesubkeyext defaulticon keysetvalue applicationstartuppath iconico keyclosethat is line which confuse me keysetvalue applicationexecutablepath lplease explain i am very thankful to you in advance,['c#'] +34060,removing files that are older than some number of days i guess this is a pretty common requirement in a application that does quite a bit of logging i am working on a c windows application net 35my app generates tons of log files which has a current date put in the file name like so 200912 what would be the best strategy to remove files older than say 30 days one approach i am about to use it is to loop through the file names extract the date part convert into datetime object and compare with todays date is there an elegant regular expression solution to this or something better,['c#'] +34068,why does my session expire when using performancetest and not integrationtest ok i am writing performance tests and am having trouble getting my session to persist like it does in integration tests as i understand it performancetest is a child of integrationtest and any integration tests should work with performance test however when i take a integration test and copy it over to performance change the actioncontrollerintegrationtest to actioncontrollerperformancetest and then run the test it failsi am using authlogic and have not had a problem with the integration test sessions sticking around with the performance tests though it looks like the session gets created properly but when i visit the reports page which is a protected page it redirects me to the login page like there is no user session at allrequire performance test helpclass simpletest actioncontrollerperformancetest setup activate authlogic test login do assert user session usersessioncreateuserfind by loginadmin get reports assert response success endendwhats going on here i have tried multiple ways to get a user session create post etc and nothing seems to work this is the first time i have written performance tests so i am probably doing something stupidbtw i am running ruby 187 rails 2 on debian squeeze,['ruby-on-rails'] +34107,should we validate method arguments in javascript apis i am developing a javascript library that will be used by 3rd party developersthe api includes methods with this signaturefunction dosomethingarg1 arg2 optionsarg1 arg2 are required simple type argumentsoptions is a hash object containing optional argumentswould you recommend to validate that argument types are valid options attributes are correct for example that the developer did not pass by mistake onsucces instead of onsuccesswhy do popular libraries like prototypejs do not validate,['javascript'] +34113,what does this c code do duffs device void sendint to const int from const int count int and count7 8 switchcount8 case 0 do to from case 7 to from case 6 to from case 5 to from case 4 to from case 3 to from case 2 to from case 1 to from while n0,['c++'] +34118,jquery limit text by length can i hide text in a div after a number of characters with jqueryso far i think it would go something like this jquery would cycle through the text until it gets to a certain number of characters it would then wrap a div from that position to the end of the text which could then be hidden with the hide method i am not sure how to insert that wrapping textany other way around this would also be appreciatedthanks,"['jquery', 'css']" +34124,undefined method map for nilnilclass my app seems to randomly be throwing a undefined method map for nilnilclass error when users are trying to update their profilebut whats weird is it is saying the error happens on update but the error line is actually in a view full errorusersupdate actionviewtemplateerror undefined method map for nilnilclasson line 52 of appviewsusersedithtmlerbline 52 options from collection for selectnetworks domestic id name usernetwork id and here are the params from a recent erroruseremail notify network id password confirmationfiltered mobile passwordfiltered email actionupdate methodput id5089 controllerusershonestly not sure where to even start looking i have had a user say he can update the same info from ie but not from firefox and when i use their same info i am able to update without issue so i am stumped,['ruby-on-rails'] +34157,how do i get rid of api restriction unittestframeworkdll already loaded error the following error pops up every now and thencprogram filesmsbuildmicrosoftvisualstudiov90teamtestmicrosoftteamtesttargets145 error api restriction the assembly filecprogram filesmicrosoft visual studio 90common7idepublicassembliesmicrosoftvisualstudioqualitytoolsunittestframeworkdll has already loaded from a different location it cannot be loaded from a new location within the same appdomainhow do i get rid of it,"['c#', '.net']" +34171,best practices for sqlite db and contentprovider my android app is reading and writing to a local sqlite db from a few different activities and a service pretty standard but i am not happy with the way i have got all the db details stored as constants that i then use anywhere i access the db i have been advised to wrap the db in a contentprovider sounds good to me while i am refactoring my code i figured i would ask what are your best practices for local db data storage in androidwhere and how do you store create table statements column names other sqlwould you mind sharing a list of the classes you instantiate and what goes into each contentprovider databaseprovider databasehelperhow do you coordinate the structure of your local android db with a serverside db available through a rest interfaceyeah i realize i am getting at the perennial wheres the android objectrelationmapping framework question for now i am mainly curious to hear how you structure your android apps with whats available in the standard sdkas always thanks for the pointers,['android'] +34172,uibutton flickers when pressed i have several uibuttons in my app with different graphics for their onoff states the smaller buttons all thisplay correctly without any flickering but the larger button 320x90px will flicker a black color over the button when pressed up to 75 of the time this is on the iphone not the simulator i have set different combinations of the uibuttons defaulthighlightedselectedand thisabled state images in ib but i still cannot get rid of this flicker is there something else i can try,['iphone'] +34176,is javas timezone threadsafe i wanted my application to just have one timezone object which will be used by many simpledateformat and calendar objects from the other places concurrently this is to avoid having to always do timezonegettimezoneid i know simpledateformat and calendar classes are not thread safe which is why i configure one thread to always create new instances of them but what about timezone it is not clear to me whether i can do the following safelyfinal timezone tz timezonegettimezonegmtthread 1thread t1 new threadrunnable public void run calendar cal calendargetinstancetz simpledateformat sdf new simpledateformat sdfsettimezonetz t1startthread 2thread t2 new threadrunnable public void run calendar cal calendargetinstancetz simpledateformat sdf new simpledateformat sdfsettimezonetz t2startthanks,['java'] +34188,formatting a number with exactly two decimals in javascript i have this line of code which rounds my numbers to two decimal places but i get numbers like this 108 24 etc these are not my idea of two decimal places so how i can improve the followingmathroundpricemathpow102mathpow102i want numbers like 1080 240 etc use of jquery is fine with me,['javascript'] +34202,ssl slowness in ec2 weve deployed our rails app to ec2 in our setup we have two proxies on small instances behind roundrobin dns these run nginx load balancers for a dynamically growing and shrinking farm of web servers each web server also runs nginx with a cluster of mongrels the nginx here takes care of static content and load balancing the mongrelsanyway our traffic byandlarge is https we have the 2 proxies taking care of ssl i have noticed that our network throughput on those instances caps out at only 60 mbps or so to contrast in testing i am able consistently to get 700 mbps on a small instance via regular http in fact this is the same as what i can get on a large instance similar to what the right scale guys got in their testing amazon says a small gets moderate network io while a large gets high if i had to speculate i think this is just their way of saying that there are more small instances per physical box sharing one network card i am not sure if it means that a large gets a dedicated network interface but i would doubt itin testing i was able to get a large instance to get about 250 mbps ssl this says to me that the cpu or some other resource is the bottleneck however our monitoring graphs do not show the cpu on our proxies being particularly busymy questions areis my instinct about ssl being slower due to cpu correct and our monitoring graphs are wrong or could some other resource be the limiting factorshould we just take the extra cost and put the proxies on highcpu instances or would it be better to do just add more small instancesshould we offload the ssl termination to the web servers this introduces one more problem though how do we get the client ip address in our application right now our proxy sets it in the xforwardedfor header but obviously this wouldnt be possible if it is not decrypting ssli would love to hear about any similar setups we tinkered a bit with their elastic load balancer but i think that basically puts us in the same situation as 3 above has anyone else made the switch to elb and found it to be worth it,['ruby-on-rails'] +34218,thisable horizontal scroll in jscrollpane i have a jscrollpane with flowlayout that i want to have a fixed width it should be scrolling vertically only and the contents should be rearranged automatically when i resize the window i think there should be a method like setenablehorizontalscrollfalse but cannot find itis there any easy way to do this,['java'] +34221,best solution for java http push messaging we want to push data from a server to clients but can only use http port 80 what is the best solution for messaging one idea is comet are there other ideas or frameworks which offer lets say jms over http yes activemq supports it too but waggly imho and jxta supports it too but the configuration is complicated something simple is preferred,['java'] +34240,how do you make the area of a div clickable not the whole div if you have a background image in a div with a drawn button in the middle and some other drawings around it how do you make the button clickable but not the whole div because i do not want the user to click the drawings around it if that makes sense i am i wasting my time playing with padding and margins should i just create two divs my boss says he has managed to make it using one div beforecheers,"['css', 'html']" +34243,creating boxed primitive instance when the class is known i need a method that returns an instance of the supplied class type let us assume that the supplied types are limited to such that an empty instance of them can be created for instance supplying stringclass would return an empty string supplying an integerclass would return an integer whose initial value is zero and so on but how do i create boxed primitive types on the fly like thispublic object newinstanceclass type if typeisprimitive return typenewinstance plus appropriate exception handling else now what if typeequalsintegerclass typeequalsintclass return new integer0 if typeequalslongclass etc is the only solution to iterate through all the possible primitive types or is there a more straightforward solution note that bothintclassnewinstanceandintegerclassnewinstancethrow an instantiationexception because they do not have nullary constructors,['java'] +34250,provide value for self when using proccall when using proccall to call a lambda function in ruby self always ends up with the value that it had when the function was defined rather than the value it has when the function is called for examplep lambda self class dummy def test pcall endendd dummynew dtest maincalling test returns main when what i intended it to return is dummy0xf794 an instance of dummy which was the value of self at the point in the code where i called pin javascript i would just pass the object that i want to be the callee as the first argument to call is there any such functionality in ruby allowing me to set an arbitrary object or at least the current value of self as the new value for self when i call a proc,['ruby'] +34251,operator overloading in c where should the actual code code go a bit of a conceptual questioni am creating my custom structure in the vein of a vector3 3 int values and i was working through overloading the standard operators etcas i am building a library for external use i am attempting to conform to fxcop rules as such they recommend having methods that perform the same functioneg add subtract etcto save on code duplication one of these methods the operator overload or the actual method is going to call the other onemy question is which should call whichis it and this is only an example codea public static mystruct operator mystruct struc1 mystruct struct2 return struc1addstruct2 public mystruct addmystruct other return new mystruct thisx otherx thisy othery thisz otherz orb public static mystruct operator mystruct struc1 mystruct struct2 return new mystruct struct1x struct2x struct1y struct2y struct1z struct2z public mystruct addmystruct other return this other i am really not sure either is preferable but i am looking for some opinions,"['c#', '.net']" +34257,how to set an item in clistctrl as selected clistctrl is set to single selection single column in report view with no header i have tried setitemstate0lvis selectedlvif state andsetselectionmarkint index but these do not work,['c++'] +34273,how to sum multiple sql queries together i am trying to run multiple queries on multiple tables similar to select count from tablea where x1 per tablewhat i would like to do is get all of the count values that are returned and sum them into a single valueany ideas,['sql'] +34274,mapkit routes and google license so this question is not if i can do routing with mapkit you cannot with the api so i found the clever way of using an annotation to render a route between two points the route is based on a series of latlong values in my app i use it to render a route but not for vehicles or walking there is no list of directions so it is not turn by turn just shows the line on the map this may be more legal but does this violate the license is there the possibility that my app could be rejected this is a very big deal for my app has anyone gotten a commercial app out using this method,['iphone'] +34279,append rows to a numpy record array is there a way to append a row to a numpy recarray for example x1nparray1234x2nparrayaddxyz12x3nparray11234r npcorerecordsfromarraysx1x2x3namesabcappendr5cc430axis0the easiest way would to extract all the column as ndarray types add the separate elements to each column and then rebuild the recarray this method would be memory inefficient unfortunately is there another way to this without separating the rebuilding the recarray cheerseli,['python'] +34280,what is the best solution for creating a soap server in php i need some advice on which library is the best choice when it comes to creating soap servers and eventually soap clients in phpi know there is builtin functions for this but is that really the best way to go about italso if you could attach some arguments as to why a certain librarymethod is the better i would be much delightedthe only requirement i currently have apart from the obvious clientserver part is that it can generate wsdl does the wsdl version really matter at all 11 or 20 whats the real differencebenefit of using 20,['php'] +34283,accessing aspnet development server from another pc on the network i would like to test my web app in other browsers i have installed virtual pc to do just that the aspnet development server does not allow remote connections so the virtual pc another computer on the network cannot access the websitei found this post that was started but there was no solutioni understand that using localhost will not work i heard about using the machines ip but how do i get that correct ip look at my lynksys router adminif i were to get as far as getting my ip im sure that the aspnet dev server does not allow remote connections how do i enable it to do so,['asp.net'] +34285,how to add option to select list in jquery my select list is called droplistbuilding the following code does not seem to work for var i 0 i buildingslength i var val buildingsi var text buildingsi alertvalue of builing at itostring is val droplistbuildingaddoptionval text false this line dies droplistbuildingaddoptionval text falsewhat is the right to add items to the drop down in jquery i have tested without that line and the buildings variable does have my data element,['jquery'] +34292,principal component analysis in python i would like to use principal component analysis pca for dimensionality reduction does numpy or scipy already have it or do i have to roll my own using numpylinalgeighi do not just want to use singular value decomposition svd because my input data are quite highdimensional 460 dimensions so i think svd will be slower than computing the eigenvectors of the covariance matrixi was hoping to find a premade debugged implementation that already makes the right decisions for when to use which method and which maybe does other optimizations that i do not know about,['python'] +34294,xpath is there a way to set a default namespace for queries is there a way to set javas xpath to have a default namespace prefix for expressons for example instead of htmlhtmlhtmlheadhtmltitletext the query could be htmlheadtitletextwhile using the namespace prefix works there has to be a more elegant waysample code snippet of what i am doing nownode node dom of a html documentxpath xpath xpathfactorynewinstancenewxpath set to a namespacecontext that simply returns the prefix html and namespace uri xpathsetnamespacecontextnew htmlnamespacestring expression htmlhtmlhtmlheadhtmltitletextstring value xpathevaluatequery expression,['java'] +34300,javascript check if a string has white space i am trying to check if a string has white space i found this function but it does not seem to be workingfunction haswhitespaces var rewhitespace new regexps check for white space if rewhitespacetests alertplease check your fields for spaces return false return truebtw i added quotes to regexp is there something wrong is there anything better that i can use hopefully jquerythanks for any help,['javascript'] +34325,thisplaying tooltip over a thisabled control i am trying to thisplay a tooltip when mouse hovers over a thisabled control since a thisabled control does not handle any events i have to do that in the parent form i chose to do this by handling the mousemove event in the parent form heres the code that does the job void form1 mousemoveobject sender mouseeventargs e m tooltipssettooltipthis testing tooltip on datetimenowtostring string tiptext thism tooltipsgettooltipthis if tiptext null tiptextlength 0 point clientloc thispointtoclientcursorposition control child thisgetchildatpointclientloc if child null childenabled false m tooltipstooltiptitle mousehover on thisabled control m tooltipsshowtiptext this 10 else m tooltipstooltiptitle mousehover triggerd m tooltipsshowtiptext this 30 the code does handles the tooltip thisplay for the thisabled control the problem is that when mouse hovers over a thisabled control the tooltip keeps closing and rethisplay again from the thisplay time i added in the tooltip when mouse is above the parent form the mousemove event gets called roughly every 3 seconds so the tooltip gets updated every 3 seconds but when mouse is over a thisabled control the tooltip refreshes every 1 second also when tooltip refreshes above form only the text gets updated with a brief flash but when tooltip refreshes above a thisabled control the tooltip windows closes as if mouse is moving into a enabled control and the tooltip is supposed to be closed but then the tooltip reappears right awaycan someone tell me why is this thanks,['c#'] +34334,what is a suitable buffer for pythons struct module in python i am accessing a binary file by reading it into a string and then using structunpack now i want to write to that string using structpack into but i get the error cannot use string as modifiable buffer what would be a suitable buffer for use with the struct module,['python'] +34343,django error opening sqlite3 db file on when running off apache i got this erroroperationalerror at unable to open database filethings i have tried so far are setting the absolute path of my devdb file in the settingspy i have tried adding wdata to my admin group and setting the group of my project folder to the admin and setting the group to wdata none of which solved the problemi am completely stuck here if anyone has a solution it would be much appreciatedshawn,['python'] +34349,link in javascript alert i want to put a link in a javascript alertis this possible i have searching for a solution but i keep getting things about links that fire alerts,['javascript'] +34367,what is the equivalent of javascripts encodeuricomponent in php what is the equivalent of javascripts encodeuricomponent in php,"['php', 'javascript']" +34376,how use instruments and thisplay the console in command lines applications i am using xcode on osx to develop command line c applications i would also like to use instruments to profile and find memory leakshowever i could not find a way to thisplay the console when launching the application from within instruments i am also unable to attach to a running command line process it exits with an errorheres an example codeinclude stdiohinclude signalhinclude stdlibhinclude setjmphstatic sigjmp buf jmpbufvoid handlerint sig char cbufsiz printf got signal dn sig printf deseja sair sn fgetsc sizeofc stdin ifc0 s exit0 else siglongjmpjmpbuf 1 int mainvoid char bufbufsiz signalsigint handler sigsetjmpjmpbuf 1 while1 printf fgetsbuf sizeofbuf stdin printf introduziu sn buf return0heres the error i got after launching instruments and trying to attach to the running process in xcodeswitching to process 1475switching to process 1475error while running hook stopsharedlibrary applyloadrules allerror while running hook stopinvalid type combination in ordering comparisonerror while running hook stopinvalid type combination in ordering comparisonerror while running hook stoperror while running hook stoperror while running hook stoperror while running hook stoperror while running hook stoperror while running hook stoperror while running hook stopunable to thisassemble cfinitializeany thoughts,['c'] +34384,can i add custom attribute to html tag can i add custom attribute to html tag like this tag myattrimyval,['html'] +34394,stop the browser athrobber of dooma while loading cometserver push xmlhttprequest this question is similar to this one but it is for using xmlhttprequest instead of an iframe for cometi am starting an async long poll like thisvar xhr new xmlhttprequestxhropenpost urlxhrsendif i do this inside scriptscript in the head it will cause the document to keep loading forever i am testing this in safari on mac os x and the iphone and it is the only browser i need to supportusing domcontentloaded or load events would not workusing a settimeout with a large enough delay will work 0 would not 10 will 100 will some times and not other times i do not feel comfortable with thisthe only way i found that works is the combination of bothdocumentaddeventlistenerdomcontentloaded function settimeoutfunction var xhr new xmlhttprequest xhropenpost url xhrsend 0i guess this solves the problem for now but i am still afraid it will break in the future edit this does not work reliably eitherdoes anyone know of a more reliable way,['javascript'] +34397,how do i split an integer into 2 byte binary givenprivate int width 400private byte data new byte 2i want to split the integer width into two bytes and load data0 with the high byte and data1 with the low bytethat is binary value of 400 1 1001 0 so data0 should contain 0 01and data1 should contain 1001 0,['java'] +34398,simple statistics java packages for calculating mean standard deviation etc could you please suggest any simple java statistics packagesi do not necessarily need any of the advanced stuff i was quite surprised that there does not appear to be a function to calculate the mean in the javalangmath packagewhat are you guys using for thiseditregardinghow hard is it to write a simple class that calculates means and standard deviationswell not hard i only asked this question after having handcoded these but it only added to my java frustration not to have these simplest functions available at hand when i needed them i do not remember the formula for calculating stdev by heart,['java'] +34401,how to group by week in mysql oracles table server offers a builtin function trunctimestampdy this function converts any timestamp to midnight on the previous sunday whats the best way to do this in mysqloracle also offers trunctimestampmm to convert a timestamp to midnight on the first day of the month in which it occurs in mysql this one is straightforwardtimestampdate formattimestamp ym01but this date format trick would not work for weeks i am aware of the weektimestamp function but i really do not want week number within the year this stuff is for multiyear work,['mysql'] +34407,rails html helper i am trying to figure out the cleanest way to generate a bit of html and nest content inside it using haml basically i want to do something like block large this is some nested contentand that should generatediv classblock large img srcblock large caratgif classblock large carat this is some nested contentdivthe problem is i do not know how to go about achieving this partials helper i am getting hung up on how i would nest whatever content i want trying to keep my haml dry and do not want to have to explicitly declare the image tag over and over again,['ruby-on-rails'] +34410,what is the best way to store a url value using mysql i was thinking of storing url values in my database but i know some urls sometimes get ridiculously long i think my mysql database is version 50i was thinking of using varchar255but this will only work for so long so should i usetext,['mysql'] +34418,sql constraint minvalue maxvalue is there a way to set a sql constraint for a numeric field that min value should be 1234 and max value should be 4523,['sql'] +34420,eclipse magic syntax error varargs are only available if source level is 15 or greater yesterday i made a project in eclipse and it was working compiling i used eclipse galileo for java ee today i open eclipse and see lots of errors saying that stuff is not available and that it is only available if source level is 15what to do,['java'] +34441,passing mouse clicks through an overlaying element is it possible to pass mouse clicks through an overlaying element div stylezindex 100 background urlimagesrain24png width 100 height 100 top 0 bottom 0 left 0 right 0nbspdivpass mouse clicks beneath it to underlaying elements eg a web page with images links etcthinking of another way to word this is there any way of creating a purely aesthetic overlaylayer in html5 css3 andor javascriptjquerythanks in advance and sorry if this question is not too clearpeace,"['javascript', 'jquery', 'html']" +34451,bytearray to image aspnet i have a byte array representing a picture i want to present the picture stored in that byte array in an aspx page can i do it using an image or imagemap control if so how if not whats the solution,['asp.net'] +34471,a problem with exception handling for ienumerable it is lazynessdependent i used to create interfaces with ienumerablet as return type whenever i want to specify that a particular output is readonly i like it as it is minimalistic hides implementation details and decouples a callee from a callerbut recently a colleague of mine argued that ienumerablet should be kept for scenarios which involve lazy evaluation only as otherwise it is unclear for a caller method where the exception handling should take it is place around a method call or around an iteration then for the eager evaluation cases with a readonly output i should use a readonlycollectionsounds quite reasonable for me but what would you recommend would you agree with that convention for ienumerable or are there better methods for exception handling around ienumerablejust in case if my question is unclear i made a sample class illustrating the problem two methods in here have exactly the same signature but they require different exception handlingpublic class evilenumerable ienumerableint throw throw new argumentexception ienumerableint lazythrow foreach var item in throw yield return item public void run try throw catch argumentexception consolewritelineimmediate throw try lazythrow catch argumentexception consolewritelineno exception is thrown try foreach var item in lazythrow do smth catch argumentexception consolewritelinelazy throw update 1 the question is not limited to argumentexception only it is about best practices for making friendly class interfaces that tell you whether they return lazy evaluated result or not because this influences the exceptionhandling approach,['c#'] +34474,how do i thisable the c message box beep whenever trigger a messagebox used in my c program i get a very annoying beep from my computer how do i thisable this beep using c codethe code i am using is very simplemessageboxshowtext,"['c#', '.net']" +34475,initializing jagged arrays i want to create array 10 10 10 in c like int not inti can write codeint count new int10for int i 0 i 10 i counti new int10 for int j 0 j 10 j countij new int10but i am looking for a more beautiful way for it may be something like thatint count new int101010,"['c#', '.net']" +34479,deploying jaxws web service on tomcat after noticing java 6 includes javaxxmlws i am able to create a standalone web service how would i go about hosting that in tomcat 6,['java'] +34487,variables set during getjson function only accessible within function this may be more of a scoping question i am trying to set a json object within a getjson function but i need to be able to use that object outside of the callbackvar jsonissues declare json variablegetjsonurl functiondata jsonissues dataissues jsonissues not accessible herea similar question like this one was asked in another post and the consensus was that anything i need to do with the json objects needs to be done within the callback function and cannot be accessed anywhere else is there really no way that i can continue to accessmanipulate that json object outside of the getjson callback what about returning the variable or setting a globali would appreciate any help this just does not seem rightupdatetried setting the ajax async setting to false and running through the same code with no luck code i tried is belowvar jsonissues declare json variableajax async false getjsonurl functiondata jsonissues dataissues jsonissues still not accessible herealso i have had a couple responses that a global variable should work fine i should clarify that all of this code is within documentreadyfunction to set a global variable should i just declare it before the documentready as suchvar jsonissues documentreadyfunction var jsonissues declare json variable getjsonurl functiondata jsonissues dataissues now accessiblei was under the impression that that a variable declared within documentready should be globally accessible and modifiable within any part of documentready including subfunctions like the getjson callback function i may need to read up on javascript variable scoping but there does not seem to be an easy to achieve what i am going for thanks for all the responsesupdate 2per comments given to answers below i did use ajax instead of getjson and achieved the results i wanted code is belowvar jsonissues ajax url url async false datatype json success functiondata jsonissues dataissues jsonissues accessible here goodcouple followup comments to my answers and i appreciate them all my purpose in doing this is to load a json object initially with a list of issues that the user can then remove from and save off but this is done via subsequent interactions on the page and i cannot foresee what the user will want to do with the json object within the callback hence the need to make it accessible once the callback complete does anyone see a flaw in my logic here seriously because there may be something i am not seeingalso i was reading through the ajax jquery documentation and it says that setting async to false loads data synchronously blocks the browser while the requests is active it is better to block user interaction by other means when synchronization is necessarydoes anyone have an idea how i should be blocking user interaction while this is going on why is it such a concern thanks again for all the responses,"['javascript', 'jquery']" +34511,how to get hex color value rather than rgb value using the following jquery will get the rgb value of an elements background colorselectorcssbackgroundcoloris there a way to get the hex value rather than the rgb,"['javascript', 'jquery']" +34513,java 3d plot library ok so i am doing a project on visualization of some financial stuff in java the main objective is to take some input from the stock market run it through a few equations and then plot the result as a 3d plot i have almost everything done but the visualization which is the most important i guessat first i was thinking about using java3d but i am running short on time and i do not really have the time to learn it is there any really simple library for visualizing 3d stuff in java i need stuff like zooming rotating etci found jmathtools which looked perfect but for some reason it doest want to compile,['java'] +34520,c program to compare integers without using logical operators can anyone tell me how to write a c program to compare numbersincluding negative numbers without using logical operators,['c'] +34525,how can i create a password i want to give maybe a million password to some users that should be likeit must have at least 6 charactersit must have digits and also lettersshould i use random here how,['java'] +34546,c implicit template instantiation i currently have a class hierarchy likematrixbase densematrix other types of matrices matrixview transposeview diagonalview other specialized views of matricesmatrixbase is an abstract class which forces implementers to define operatorintint and such things it represents 2 dimensional arrays of numbers matrixview represents a possibly mutable way of looking at a matrix like transposing it or taking a submatrix the point of matrixview is to be able to say something likescalediagonala 20where diagonal returns a diagonalview object which is a kind of lightweight adapternow heres the questions i will use a very simple matrix operation as an example i want to define a function liketemplate class tvoid scalematrixbaset a const t scale factorwhich does the obvious thing the name suggests i want to be able to pass in either an honesttogoodness nonview matrix or an instance of a subclass of matrixview the prototype as written above does not work for statements such asscalediagonala 20because the diagonalview object returned by diagonal is a temporary and scale takes a nonconst reference which cannot accept a temporary is there any way to make this work i tried to use sfinae but i do not understand it all that well and i am not sure if that would solve the problem it is important to me that these templated functions can be called without providing an explicit template argument list i want implicit instantiation ideally the statement above could work as writtenedit followup questionas sbi responded below about rvalue references and temporaries is there a way to define two versions of scale one which takes a nonconst rvalue reference for nonviews and one which takes a passbyvalue view the problem is to differentiate between these two at compile time in a way such that implicit instantiation will workupdatei have changed the class hierarchy toreadablematrixwritablematrix public readablematrixwritablematrixviewdensematrix public writablematrixdiagonalview public writablematrixviewthe reason writablematrixview is thistinct from writablematrix is that the view must be passed around by const reference while the matrices themselves must be passed around by nonconst ref so the accessor member functions have different constness now functions like scale can be defined astemplate class tvoid scaleconst writablematrixviewt a const t scale factortemplate class tvoid scalewritablematrixt a const t scale factor scalewritablematrixviewadapterta scale factornote that there are two versions one for a const view and a nonconst version for actual matrices this means for functions like multa b c i will need 8 overloads but at least it works what does not work however is using these functions within other functions you see each viewlike class contains a member view of what it is looking at for example in the expression diagonalsubmatrixa the diagonal function returns an object of type diagonalviewsubmatrixviewt which needs to know the fully derived type of a now suppose within scale i call some other function like it which takes either a base view or matrix reference that would fail because the construction of the needed views require the derived type of the argument of scale information it does not have still working on find a solution to thisupdatei have used what is effectively a homegrown version of boosts enable if to select between two different versions of a function like scale it boils down to labeling all my matrix and view classes with extra typedef tags indicating if they are readable and writable and view or nonview in the end i still need 2n overloads but now and is only the number of nonconst arguments for the final result see the here it is unlikely to get seriously revamped again,['c++'] +34547,why is there no dimension css attribute in css we can definemargintop 10pxmarginright 1pxmarginbottom 1pxmarginleft 1pxor just shortmargin 10 1 1 1we also can defineborderleft right bottom top or shortborder1px solid blackfor defining the dimensions of an element we needwidth 150pxheight 200pxwhy is not there something likedimension 150px 200pxor does something similar exist and i just dont know itthe reason why i ask i always misstype dth dht and ght gth and want to blame someone,['css'] +34548,c enumerable range what is the way to get range az likeenumerablerange1100 enumerablerangeaz,['c#'] +34561,how do i wait for pid x to exit if x is not a child process using c how do i wait for pid x to exit when it is not a child of my current processkillpid sigtermwaitpidpidnull0the above does not work as pid is not a child process,['c'] +34582,programmatically turn on bluetooth in the iphone sdk i have seen a lot of questions about this but no one actually gives a real answer frameworks to import actual code etc they only say with a private api and that will get your app rejected from the app storei am aware that use of a private api will get my app rejected by i was wondering how to do it for personal use iphone sdk 312 ipod touch 2g,"['iphone', 'objective-c']" +34583,zend framework multiplate navigation blocks i want to use the navigation helper to build my navigation menus using acl the acl part i have working finei now want to be able to thisplay a few different types of navigation eg adminnav sidenav newnav etc i cannot find anything about this in the docs only how to set the navigation and then use that one navigation object repeatedly within a layout or viewi tried something similar to this having two different containers with different arrays of pages then setting these containers in the registry then from within my view andor layout calling navigation and passing it a containerphp echo thisnavigationzend registrygetnewsnav the above is called in my news view the following is called in my layoutphp echo thisnavigationzend registrygetadminnav this works fine for all my pages apart from the news page on my news page the nav for news is thisplayed twice once in the layout and once in the news view the admin nav is never thisplayed and seems to be overwritten by the news navi could be going about this completely the wrong way if so please let me know a better way if this method seems fine can someone help me sort out why the news nav is being thisplayed in the layout and in the news viewthanks for your timejake,['php'] +34585,is there a standard way for net winforms apps to autoupgrade if you have a winforms app that is installed on a large number of machines is there a standard way of implementing an automatic upgrade functioneg each time it is started it checks a web site or web service and if there is a new version available it downloads and installs iti could figure out how to roll my own version of this but i am wondering if there are any frameworks already in place to help with this,['.net'] +34590,image height using jquery in chrome problem imgheight returns 0 in chrome but it returns the actual height in ie and firefoxwhats the actual method to get the height of the image in chrome,['jquery'] +34595,why should exceptions be used conservatively possible duplicatewhy is exception handling bad i often seehear people say that exceptions should only be used rarely but never explain why while that may be true rationale is normally a glib it is called an exception for a reason which to me seems to be the sort of explanation that should never be accepted by a respectable programmerengineer there is a range of problems that an exception can be used to solve why is it unwise to use them for control flow what is the philosophy behind being exceptionally conservative with how they are used semantics performance complexity aesthetics conventioni have seen some analysis on performance before but at a level that would be relevant to some systems and irrelevant to othersagain i do not necessarily thisagree that they should be saved for special circumstances but i am wondering what the consensus rationale is if such a thing exists,['c++'] +34596,datacontractserializer with multiple namespaces i am using a datacontractserializer to serialize an object to xml the main object is securityholding with the namespace and contains a property called amount that is a class with the namespace when i serialize this to xml i get the followingarrayofsecurityholding xmlnsi xmlns securityholdingamount xmlnsd3p1d3p1amount105d3p1amountd3p1currencycodeusdd3p1currencycodeamountbrokerageid0brokerageidbrokeragename iniltrue recordid3681recordid securityholdingarrayofsecurityholdingis there anyway i can control the d3p1 prefix am i doing something wrong or should i be doing something else,['c#'] +34598,handling foreign key exceptions in php what is the best way in php to handle foreign key exceptions on a mysql database is there a mysql class that can be used to simplify any codeideally what i want to do as an example is to try to delete a record where it is the foreign key parent to any number of child tables the foreign key throws the exception so then i would like to be able to look at each foreign key table and test it giving meaningful feedback on the tables and number of records causing the exception this would then be returned as the error so the end user can reference and delete the offending records,"['php', 'mysql']" +34602,how to fix array indexof in javascript for internet explorer browsers if you have worked with javascript at any length you are aware that internet explorer does not implement the ecmascript function for arrayprototypeindexof including internet explorer 8 it is not a huge problem because you can extend the functionality on your page with the following codearrayprototypeindexof functionobj start for var i start 0 j thislength i j i if thisi obj return i return 1when should i implement thisshould i wrap it on all my pages with the following check which checks if the prototype function exists and if not go ahead and extend the array prototypeif arrayprototypeindexof implement function hereor do browser check and if it is internet explorer then just implement itpseudocodeif browser ie style browser implement function here,['javascript'] +34623,can i use nettcp bindings for protobufnet wcf can i use nettcp bindings for protobufnet wcf can i use clientbase or i have to use protoclient,['.net'] +34635,spring singletonsession scopes and concurrency does singletonsession scopes of spring beans require that access to all its fields must be synchronized say through synchronized keyword or using some classes from package javautilconcurrentas example is this code not thread safe copypased from herecomponentsessionscopedpublic class shoppingcart private listproduct items new arraylistproduct public listproduct getallitems return items public void additemproduct item itemsadditem,['java'] +34639,last update timestamp with jpa i am playing around a bit with jpaeclipselink to be specific the below entity have a timestamp that is supposed to reflect whenever that entity was last updatedwhat are the strategies for making jpa update that timestamp automatically every timethis entity is changed how would i go about if i also want a creation timestamp only set when the entity is first persisted never allowed to be changed again entity public class item implements serializable private static final long serialversionuid 1l private integer id private string note public item id generatedvaluestrategysequence columnuniquetrue nullablefalse public integer getid return thisid public void setidinteger id thisid id columnlength255 columnnullablefalse public string getnote return thisnote public void setnotestring note thisnote note columnnullablefalse public timestamp getupdated return thisupdated public void setupdatedtimestamp updated thisupdated updated,['java'] +34644,practical use of interface events what is a good example of the power of interface events declaring events inside interfacemost of the times i have seen only public abstract methods inside interface,['c#'] +34660,unable to open a file with fopen i have been trying to open a file and output text but i keep getting errors so i thought i would start at the very beginning and just try opening the file this is my codeinclude stdiohinclude stdlibhdefine correct parameters 3int mainvoid file file file fopentestfile1txt r if file null printferror fclosefilewhen i run the file error gets printed to the console and that is it the testfile1txt is in the same location as my exe how do i fix this,['c'] +34661,get image color i want to thisplay images inside divs or tables as backgrounds if they images are not large enough i am going to need to find the outer most color of that image and apply it to the background of the containing div or table cell does anyone have experience with this in php i am a noob so please explain thank you so much,['php'] +34671,get mac address in linux using mono how do i get the mac address of my computer in a mono application on linux,['c#'] +34677,difference between javaioprintwriter and javaiobufferedwriter please look through code below aclassfile file new fileblahtxtfilewriter filewriter new filewriterfileprintwriter printwriter new printwriterfilewriter bclassfile file new fileblahtxtfilewriter filewriter new filewriterfilebufferedwriter bwriter new bufferedwriterfilewriterwhat is the difference between these two methodswhen should we use printwriter over bufferedwriter,['java'] +34686,alert view in iphone i am new to iphone application development i want to design an alert view with 2 buttons ok and cancel when the user touches the ok button then i will print a message that says hello when they touch the cancel button i will print cancelplease help how do i do this,"['iphone', 'objective-c']" +34692,select column if blank select from another how does one detect whether a field is blank not null and then select another field if it iswhat i really need is a isblank function that works the same as isnull but with with blanksreplace does not work with blanks coalesce only works with nulls,['sql'] +34699,performance of count sql function i have two choices when writing an sql statement with the count functionselect count from table nameselect countsome column name from table namein terms of performance what is the best sql statementcan i obtain some performance gain by using option 1,['sql'] +34708,how to convert uicolor value to a named color string i need to convert uicolor to an nsstring of the color name i tried nsstring colorstring nsstringfromclassuicolor redcolor class but colorstring did not give redcolor,"['ios', 'iphone']" +34723,create sub folders in the controller how can i do in aspnet mvc 1 to take sub folders for example taking the following folder structure on the controllercontroller blog viewscontrollercs articlescontrollercs customers salescontrollercs productscontrollercs homecontrollercsi would like to have the following folder structure in view each view found your controllerviews blog views indexaspx adminaspx showaspx articles showaspx adminaspx customers sales indexaspx totalsaspx products indexaspx promotionsaspx home indexaspx,['.net'] +34739,how can i make my mysql database records visible to search engines i am creating a classifieds website called mysite and i want whoever searches for honda mysite in google to find all ads with the description honda or headline honda from my databasehow is this done a htm page for every ad which then loads the ad data when user clicks to open the htm pagei have an example for you to look at wblocketse is a swethish site where you can buy almost anything i am guessing they dont actually have 500thousand html pages just so that google can find them righttry searching this in google blocket bmw 330ci and you will see results from blocketse databasequestion is how have they done it and how should i do it so that i have the same functionalitythanksif you need more input tell me and i will update,"['php', 'sql', 'mysql', 'html']" +34740,setting a category in the net enterprise library logging to event log i am writing some logs to the event log using the microsoft enterprise library its writes logs away fine but doesnt seem to set the category in the event log the category appears okay in the message body of the log if i choose to set that but the event viewer doesnt pick up the categorywhat am i missingc sourcelogentry log new logentrylogmessage testlogcategoriesaddeventloggerwritelogweb configloggingconfiguration namelogging application block tracingenabledtruedefaultcategorygeneral logwarningswhennocategoriesmatchtruelisteners add sourcetestlogsource formattertext formatter logtestlog machinename listenerdatatypemicrosoftpracticesenterpriselibraryloggingconfigurationformattedeventlogtracelistenerdata microsoftpracticesenterpriselibrarylogging version3100 cultureneutral publickeytokenb03f5f7f11d50a3a traceoutputoptionsnone typemicrosoftpracticesenterpriselibraryloggingtracelistenersformattedeventlogtracelistener microsoftpracticesenterpriselibrarylogging version3100 cultureneutral publickeytokenb03f5f7f11d50a3a nameformatted eventlog tracelistener listenersformatters add templatetimestamp timestampxdxamessage messagexdxacategory categoryxdxaseverity severity typemicrosoftpracticesenterpriselibraryloggingformatterstextformatter microsoftpracticesenterpriselibrarylogging version3100 cultureneutral publickeytokenb03f5f7f11d50a3a nametext formatter formatterscategorysources add switchvalueall nameevents listeners add nameformatted eventlog tracelistener listeners add add switchvalueall namegeneral listeners add nameformatted eventlog tracelistener listeners addcategorysourcesspecialsources allevents switchvalueall nameall events notprocessed switchvalueall nameunprocessed category errors switchvalueall namelogging errors amp warnings listeners add nameformatted eventlog tracelistener listeners errorsspecialsources,['c#'] +34769,how do you specify table padding in css table not cell padding i have a table with a colored background and i need to specify the padding between the table and it is content ie cellsthe table tag does not seem to accept a padding valuefirebug shows the table and tbodys layout with padding 0 but does not accept any value entered for them so i guess they just do not have the padding propertybut the thing is i want the same separation between cells than the top cells with the table top and the bottom cells with the tables bottomagain what i want is not cellpaddingedit thanks what i really needed i realize now was borderspacing or its html equivalent cellspacingbut for some reason they do not do anything in the site i am working onboth work great on a separate html but in the site they do noti thought it could be some style overwriting the property but cellspacing and an inline borderspacing should not get overwritten righti use firefox edit 2 no td padding is not what i need with td padding top and bottom paddings of adjacent cells sum up so there is double the space pad actually between two cells than between the top cell and the table top border i want to have exactly the same thistance between them,"['html', 'css']" +34770,using a method in seedsrb in ruby on rails i am trying to add a method to my seedsrb so that i do not have to write a bunch of verbose code however depending on the placement of the create deliverable method i get one of two error messages when running dbsetupwhen method is before callrake aborted private method create deliverable called for when method is after callrake aborted undefined method create deliverable for is it not possible to uses methods in seedsrb am i somehow calling the method incorrectly i have tried calling with and without the selfmethoddef create deliverablecomplexity project phase id deliverable type id deliverablecreatename 08map65rand25chrjoin size 2 rand6 rand6 rate 2 rand6 rand6 deliverable type id deliverable type id project phase id project phase id complexity complexityendcalling codewf projectproject phaseseach do phase deliverabletypefind by lifecycle phasephaselifecycle phase ideach do type selfcreate deliverablelow typeid phaseid selfcreate deliverablemedium typeid phaseid selfcreate deliverablehigh typeid phaseid endend,['ruby-on-rails'] +34781,calling jmx mbean method from a shell script are there any libraries that would allow me to call a jmx mbean method from a shell script we expose some operationsadmin commands through jmx and we could have our admins use jconsole or visualvm but some tasks are better left to automation in that automation wed like to be able to call a jmx mbean method on our running server preferably from a shell script,['java'] +34788,errorswarnings using svcutilexe to create proxy classes for several wcf services i am writing a net 35 app and have control over both the wcf service and clienti am using svcutil to generate proxy classes for my services combining several services since they share data typessvcutil outservicereferencecs noconfig namespaceglobalservicereference tcvversion35 httplocalhost12345firstsvc httplocalhost12345secondsvcthe more serious problem is the error i have got a class being created twice resulting lots of ambiguity between globalservicereferencemyclassmyfield and globalservicereferencemyclassmyfield errors note that right now this class is only referenced in one of the services though in the future it will be referenced from morethe two generated class look likesystemdiagnosticsdebuggerstepthroughattributesystemcodedomcompilergeneratedcodeattributesystemruntimeserialization 30systemruntimeserializationdatacontractattributenamemyclass namespacepublic partial class myclass object systemruntimeserializationiextensibledataobject fieldsandsystemcodedomcompilergeneratedcodeattributesvcutil 3045062152systemserializableattributesystemdiagnosticsdebuggerstepthroughattributesystemcomponentmodeldesignercategoryattributecodesystemxmlserializationxmltypeattributenamespacepublic partial class myclass same fieldsbased on the attributes applied to them this has something to do with the datacontractserializer vs the xmlserializer but i do not really understand what those meana second problem is that svcutil is giving a boatload of warnings of the formerror there was a validation error on a schema generated during export source line 1 column 10415 validation error the simpletype has already been declaredthese errors happen even with two very simple services for example if service 1 hasoperationcontractpublic string testint test return testand service 2 hasoperationcontractpublic int pingstring test return 23i get the warnings there is like a 100 of them all complaining about various globalelements globalattributes or simpletypes like guid duration char etcif i change one of the services to have only void parametersreturn type i do not get the warnings this is really confusing since this is the simplest possible test without using any custom types at all svcutil is barfing any idea whats going on here,"['c#', '.net']" +34796,google maps v3 api mouseover with polygons i am building a map using the google v3 api because it is way faster essentially it is a map of an area with about 30 cities with polygons over the regions when a user hovers over a city i want the fillcolor to get lighter and then return to it is normal state on mouseout when a user click it redirects them to another pagethe click event works just fine but looking through the v3 api documentation it seems as if google has implemented click doubleclick mousemove mousedown and mouseup as event triggers but no hover or mouseover or mouseout really geez i would think over and out would be higher priority than down and up anyway has anybody else come across this am i wrong or is there a workaroundthank you in advance for your helpstephanie,['javascript'] +34801,linq query returns incorrect result set i have a very complex linq to sql query that returns a result set from a microsoft sql server database the query is created using syntax similar todim db as mydatacontext mygetdatacontexthelperdim qry from rslt in dbmyview select columnlistif userparam1 isnot nothing then qry qrywherelambda for the filterend ifetcreturn qrytolistthere are several userspecified filters to the query including one that does a geographic radius searchheres the problem i have a break set on the tolist call right at the end when the break is hit i use the linq to sql debug visualizer to see the generated sql statement i copy that complex sql statement into a sql server management studio query window and execute it against my database to get exactly the result set i want so the generated sql appears to produce the desired result however when i execute the tolist method of the query object the list returned has fewer rows and some different rows i have also tried this using the datacontext log property writing to a file with the same result the query generates the correct result set in sql management studio but incorrect results from the tolist methodhow can that be if the generated sql is simply passed over the connection to the sql server should not it generate exactly the result set i see in sql server management studio i assume that i am misunderstanding something about the linq to sql mechanism ie that it is not just a passthrough to sql server is that correcteditas per a request below here is a much condensed version of the sql that is generated by linq with most of the result columns removed for brevity it produces the correct result in sql management studio but the result returned to my application is differentselect t3idfrom select thistinct t1id from select t0id t0itemdate from dbomysearchview as t0 as t1 where exists select null as empty from dbozipcoverage as t2 where t2id t1id and t2latitude 4109046 05 and t2latitude 4109046 05 and t2longitude 7343106 05 and t2longitude 7343106 05 and abs395608833132861 2 atn2sqrtpowersinconvertfloatconvertfloat00174532925199433 t2latitude 0717163818159029 convertfloat2 2 cos0717163818159029 cosconvertfloatconvertfloat00174532925199433 t2latitude powersinconvertfloatconvertfloat00174532925199433 t2longitude 128161377022951 convertfloat2 2 sqrt1 powersinconvertfloatconvertfloat00174532925199433 t2latitude 0717163818159029 convertfloat2 2 cos0717163818159029 cosconvertfloatconvertfloat00174532925199433 t2latitude powersinconvertfloatconvertfloat00174532925199433 t2longitude convertfloat2 2 5 and t1itemdate 172009 81242 pm as t3update 200917 was able to contact ms regarding this issue created a sample application which i submitted to their support rep they have duplicated the issue and are researching will post answer when i get a responseupdate 20091221 finally arrived at the correct answer with help from microsoft please see my accepted answer below for the explanation,['.net'] +34824,how much can sqlite store on the iphone i have an idea for a webapp for the iphone but its unknown to me how much data can be stored in mobile safaris sqlite db i tried searching through the apple docs but found nothingsafari clientside storage and offline applications programming guide using the javascript database,['iphone'] +34838,python optparse values instance how can i take the opt result ofopt args parserparse argsand place it in a dict python calls opt a values instance and i cannot find any way to turn a values instance into a list or dict one cannot copy items from opt in this wayfor i in opt mydicti optiinstead its a clumsymydictparm1 optparm1mydictparm2 optparm2which implies that every time i add an option i have to update this code as well there should be a way to let this take care of itself,['python'] +34859,can someone explain to me what this getcardinality method is doing i have been looking into faceted search with lucenenet i have found a brilliant example here which explains a fair amount apart from the fact that it completely overlooks the function which checks the cardinality of items in a bit arraycan anyone give me a run down of what it is doing the main things i do not understand is why the bitssetarray is created as it is what it is used for and how all the if statements work in the for loopthis may be a big ask but i have to understand how this works before i can even think of using it in my own codethankspublic static int getcardinalitybitarray bitarrayvar bitssetarray256 new byte 0 1 1 2 1 2 2 3 1 2 2 3 2 3 3 4 1 2 2 3 2 3 3 4 2 3 3 4 3 4 4 5 1 2 2 3 2 3 3 4 2 3 3 4 3 4 4 5 2 3 3 4 3 4 4 5 3 4 4 5 4 5 5 6 1 2 2 3 2 3 3 4 2 3 3 4 3 4 4 5 2 3 3 4 3 4 4 5 3 4 4 5 4 5 5 6 2 3 3 4 3 4 4 5 3 4 4 5 4 5 5 6 3 4 4 5 4 5 5 6 4 5 5 6 5 6 6 7 1 2 2 3 2 3 3 4 2 3 3 4 3 4 4 5 2 3 3 4 3 4 4 5 3 4 4 5 4 5 5 6 2 3 3 4 3 4 4 5 3 4 4 5 4 5 5 6 3 4 4 5 4 5 5 6 4 5 5 6 5 6 6 7 2 3 3 4 3 4 4 5 3 4 4 5 4 5 5 6 3 4 4 5 4 5 5 6 4 5 5 6 5 6 6 7 3 4 4 5 4 5 5 6 4 5 5 6 5 6 6 7 4 5 5 6 5 6 6 7 5 6 6 7 6 7 7 8var array uintbitarraygettypegetfieldm array bindingflagsnonpublic bindingflagsinstancegetvaluebitarrayint count 0for int index 0 index arraylength index count bitssetarray256arrayindex 0xff bitssetarray256arrayindex 8 0xff bitssetarray256arrayindex 16 0xff bitssetarray256arrayindex 24 0xffreturn count,['c#'] +34871,passing around fixedsize arrays in c basically i would like to do something like thatint3 array func return 1int mainint argcchar argv int3 pointarray funcbut that does not seem legal in c i know i can use vectors but since i know the size of the array is a constant it seems like a loss of performance is likely to occuri would also like to avoid a new if i can because allocating stuff on the stack is easier and also likely to improve performancewhats the solution here,['c++'] +34872,best way to return early from a function returning a reference let us say we have a function of the formconst someobject somescopereturnourobject if somecondition return early return return ourobjectclearly the code above has an issue if the condition fails then we have a problem as to how to return from this function the crux of my question is what is the best way to handle such a situation,['c++'] +34876,why jquery do this jqueryfninitprototype jqueryfn little extended question is why jquery dojqueryfn jqueryprototype init function f1 function jqueryfninitprototype jqueryfnwhy not simply add f1 etc into initprototype is it only aesthetic or there are some deep ideas,"['javascript', 'jquery']" +34878,getting the current aspnet machine key i find myself wanting to get the aspnet machine key for the current application this is of course easy if a machine key is specified in the configuration file but if it is set to auto generate then there does not seem to be a public method anywhere to get itbasically i want at it so i can write an encryptedmaced cookie for myself just like the aspnet forms authentication provider doesdoes anyone have any pointers or ideas,['asp.net'] +34880,thistributed computing framework net specifically for cpu intensive operations i am currently researching the options that are available both open source and commercial for developing a thistributed applicationa thistributed system consists of multiple autonomous computers that communicate through a computer network wikipediathe application is focused on thistributing highly cpu intensive operations as opposed to data intensive so i am sure mapreduce solutions do not fit the billany framework that you can recommend give a brief summary of any experience or comparison to other frameworks would be greatly appreciated,['.net'] +34881,validate data using dataannotations with wpf entity framework is there any way to validate using dataannotations in wpf entity framework,['.net'] +34896,is there any form designer available for google android i am a new comer in android development i have downloaded and installed the android sdk but not find any gui or form designer can any one know about some form designer in for android thanks in advance,"['java', 'android']" +34931,simplest way to do a recursive selfjoin in sql server what is the simplest way of doing a recursive selfjoin in sql server i have a table like thispersonid initials parentid1 cj null2 eb 13 mb 14 sw 25 yt null6 is 5and i want to be able to get the records only related to a hierarchy starting with a specific person so if i requested cjs hierarchy by personid1 i would getpersonid initials parentid1 cj null2 eb 13 mb 14 sw 2and for ebs i would getpersonid initials parentid2 eb 14 sw 2i am a bit stuck on this can cannot think how to do it apart from a fixeddepth response based on a bunch of joins this would do as it happens because we would not have many levels but i would like to do it properlythankschris,['sql'] +34940,please confirm which user you are changing the password for so i just made a change password form for my rails app it is just like any other very typical password change formso after a few times testing it out i started seeing a popup box sayingplease confirm which user you are changing the password fornow this really freaked me out a bit since i know i did not write any code to do such things and i definitely do not want users to change other users passwordsi soon found out it was firefoxs password manager so now i am calmed down about it but still i do not want this to happen to other people using my sitehow does firefox know it is changing a password anyways maybe it is the names of my password fields or maybe even my forms action url accountchange password is there a way to make it not do this has anyone else had experience with this,['ruby-on-rails'] +34949,c mysql vs microsoft sql server for the longest time i have been using mysql servers to handle data in java and in c but lately i have been hearing good things about linq and sql server i have been thinking of converting but i do not know much about the sql servercould anyone who has used sql server before please define how well it is compared to mysql server in terms of performance and usabilityi have also heard that sql server would be better for c as it is basically built in,"['c#', 'mysql']" +34962,how do i make a textbox postback on keyup i have a textbox that changes the content of a dropdown in the ontextchanged event this event seems to fire when the textbox loses focus how do i make this happen on the keypress or keyup eventhere is an example of my codeasptextbox idcode runatserver autopostbacktrue ontextchangedcode textchanged aspupdatepanel idupdate runatserver contenttemplate aspdropdownlist runatserver iddatelist contenttemplate triggers aspasyncpostbacktrigger controlidcode triggersaspupdatepanelso in the codebehind i bind the dropdown on page load the code textchanged event just rebinds the dropdown i would like this to happen on each keypress rather than when the textbox loses focus i inherited this code recently and this is not the ideal method of doing this for me but time limitations prevent me from rewriting this in a web servicy methodi have tried using jquery to bind the keyup event to match the change event for the textbox but this only works on the first key pressed,['asp.net'] +34966,calling a jquery plugin without specifying any elements say i have the following jquery pluginfnmyplugin function plugin codenormally you call a plugin on a certain number of elements like suchbodymypluginis there any way i can call my plugin without specifying an elementi have tried calling it like such myplugin but that does not workwhat works is this myplugin but is that the correct way to invoke it,"['javascript', 'jquery']" +34978,c exception handling fall through possible duplicatecatch multiple exceptions at once is there any way in c to easily achieve the following pseduocodetrycatch exceptiontypea exceptiontypeb exceptiontypec as ex same code for all threwortrycatch exceptiontypea ex catch exceptiontypeb ex catch exceptiontypec ex same code for all exceptions of a b or ci guess what i am saying would be great would be fallthrough on exception types,['c#'] +34980,when should i write the keyword inline for a functionmethod when should i write the keyword inline for a functionmethod in cafter seeing some answers some related questionswhen should i not write the keyword inline for a functionmethod in cwhen will the the compiler not know when to make a functionmethod inlinedoes it matter if an application is multithreaded when one writes inline for a functionmethod,['c++'] +34989,hql with a collection in the where clause i have been trying for the this whole a query who is officially giving me nightmares the system is a user and contact management so i have useraccount contact and phone useraccount has a bidirectional onetomany relationship with contact and an unidirectional one on phone all mapped by a setuseraccount mapping onetomanytargetentityphoneimplclass cascade cascadetypeallorghibernateannotationscascadevalueorghibernateannotationscascadetypedelete orphanprivate setphone phones new hashsetphoneonetomanytargetentitycontactimplclass cascadecascadetypeall mappedbyuseraccountorghibernateannotationscascadevalueorghibernateannotationscascadetypedelete orphanprivate setcontact contacts new hashsetcontactcontact now has a onetomany unidirectional with phonesonetomanytargetentityphoneimplclass cascadecascadetypeallprivate setphone phones new hashsetphonei am writing a method to check the existence of the same number for the same contact of a particular user by the email unique field i know i could have overridden the equals and hashcode for that but since phone in a entity mapped by set i do not know at this moment how to do that so i wanted to provide a method to rather check for that uniqueness for me before each entry on the contact page public boolean checkforexistingphonestring useremail string formatednumber listcontact result null session sess getdbsessiongetsession string query select contact cphonesformatednumber from contact c inner join contactphones cphones where cuseraccountemail email and cphonesformatednumber number try result listcontact sesscreatequeryquery setparameteremail useremail setparameternumber formatednumberlist catch hibernateexception hibernateexception loggererrorerror while fetching contacts of email useremail details hibernateexceptiongetmessage ifresult null return false else return truei keep on having this errororghibernatehqlastquerysyntaxexception contact is not mapped selectcphonesformatednumber from contact c inner join contactphones cphones wherecuseraccountemail email and cphonesformatednumber numberi cannot really figure out what happens and first i do not know how to treat collections in hsqthanks for reading,['java'] +34994,clickonce file association i have a console application that i am deploying using clickonce once the user installs the program the associations are set but the associated program is the installerclickonce application deployment support library and not the actual program how can i get the association to be the actual program and not the installeri have included the fileassociation node from the appmanifest below please let me know if you have any tips on this thanksfileassociation xmlnsurnschemasmicrosoftcomclickoncev1 extensionaav descriptionmy program progidmyprogram defaulticonmyiconico tested on 3 different computers ranging from windows xp vista windows 7 trust level is full trust auto update is set to fire prelaunch,['c#'] +35000,how to escape characters in pango markup my program has a gtktreeview which thisplays a gtkliststore the gtkliststore contains strings like this span sizemediumbsite titlebspannurlwhere url is obviously a url string sometimes there are characters in url that cause pango to fail to parse the markup is there a way to escape url as a whole so that pango will just ignore it so it will be thisplayed literally if not how should i escape special characters in urls,['python'] +35006,how to tell if browsertab is active possible duplicateis there a way to detect if a browser window is not currently active i have a function that is called every second that i only want to run if the current page is in the foreground ie the user has not minimized the browser or switched to another tab it serves no purpose if the user is not looking at it and is potentially cpuintensive so i do not want to just waste cycles in the backgrounddoes anyone know how to tell this in javascriptnote i use jquery so if your answer uses that that is fine,"['javascript', 'jquery']" +35013,foreach on requestfiles i am attempting upload multiple files in aspnet mvc and i have this simple foreach loop in my controllerforeach httppostedfilebase f in requestfiles if fcontentlength 0 fileuploadfthe previous code generates this errorunable to cast object of type systemstring to type systemwebhttppostedfile what i do not understand is why requestfiles1 returns an httppostedfilebase but when it is iterated over it returns strings presumably the file namesnote i know this can be solved with a for loopalso i tried using httppostedfile with the same error,"['c#', 'asp.net']" +35017,how to switch from table to div for form layout i am noticing most folks are talking about using divs and css forlabel textbox pairs how would one convert a table such astable tr tdsome label1 td tdsome textbox1 td tr tr tdsome label2 td tdsome textbox2 td tr tablefrom using a table into say a div with css a sample would be helpful currently i was using a table for such a thing imagine say a site that just thisplays some user information how would i thisplay the pairs the label the text box using divs rather than table formatassume the labels textboxs are aspnet labels and textboxes,"['css', 'html']" +35031,form resources usage for programmatic strings had a basic winform question by default a resx file is created for every form or user control along with the designercs this resx works fine for all the controls and the text added to the controls via the uii was wondering if i could use the same resx to add strings which have to be used programmatically and based on conditions attached to the controls will the resx get overridden in any case and this custom strings be removed what is the best practice to follow in this case,"['c#', '.net']" +35034,supported audio file formats in iphone what are the supported audio files formats in iphoneif i want to play a 2 hour audio files what is the best audio file format i should have in my appthanks,['iphone'] +35043,how can i implement tee programmatically in c i am looking for a way in c to programmatically ie not using redirection from the command line implement tee functionality such that my stdout goes to both stdout and a log file this needs to work for both my code and all linked libraries that output to stdout any way to do this,['c'] +35065,how to restart transactions on deadlocklocktimeout in spring what is the best practice on implementing a transaction restart upon deadlock or lock timeout exceptions when using spring specifically the spring recommended approach declarative transactions thanksasaf,['java'] +35073,can i hide or make my iphone application unsearchable on the app store i want my application to be unsearchable from the app store i would like that only those users who sign in to my web site and then click the link of my iphone application on app store can install and use my applicationis there any way to do that,['iphone'] +35075,yahoo finance api q do yahoo provides any finance api if yes the whats the link to that api,['java'] +35087,how do i find out what jar files are actually used when compiling a java project i am currently passing a very large classpath to javac to compile a java projecti know that a number of those jar files are not neededis there a simple way of finding out which files are not needed,['java'] +35098,select 5 random elements how can i select the first 5 random elementsul lifirstli lisecondli lithirdli linliuli am using this pluginalertlirandomtextbut it takes all random elements i only want the first 5is there another way to do the same thing,"['javascript', 'jquery']" +35104,use of mocks in tests i just started using mock objects using javas mockito in my tests recently needless to say they simplified the setup part of the tests and along with dependency injection i would argue it made the code even more robusthowever i have found myself tripping in testing against implementation rather than specification i ended up setting up expectations that i would argue that it is not part of the tests in more technical terms i will be testing the interaction between sut the class under test and its collaborators and such dependency is not part of contract or the interface of the classconsider that you have the followingwhen dealing with xml node suppose that you have a method attributewithdefault that returns the attribute value of the node if it is available otherwise it would return a default valuei would setup the test like the followingelement e mockelementclasswhenegetattributeattributethenreturnwhatwhenegetattributeotherthenreturnnullassertequalsattributewithdefaulte attribute default whatassertequalsattributewithdefaulte other default defaultwell here not only did i test that attributewithdefault adheres to the specification but i also tested the implementation as i required it to use elementgetattribute instead of elementgetattributenodegetvalue or elementgetattributesgetnameditemgetnodevalue etci assume that i am going about it in the wrong way so any tips on how i can improve my usage of mocks and best practices will be appreciatededitwhats wrong with the testi made the assumption above that the test is a bad style here is my rationalethe specification does not specify which method gets called a client of the library should not care of how attribute is retrieved for example as long as it is done rightly the implementor should have free reign to access any of the alternative approaches in any way he sees fit with respect to performance consistency etc it is the specification of element that ensures that all these approaches return identical valuesit does not make sense to refactor element into a single method interface with getelement go is quite nice about this actually for ease of use a client of the method should be able to just to use the standard element in the standard library having interfaces and new classes is just plain silly imho as it makes the client code ugly and it is not worth itassuming the spec stays as is and the test stays as is a new developer may decide to refactor the code to use a different approach of using the state and cause the test to fail well a test failing when the actual implementation adheres to the specification is validhaving a collaborator expose state in multiple format is quite common a specification and the test should not depend on which particular approach is taken only the implementation should,"['c#', 'java']" +35108,php convert a multidimensional array to string i am working on a small ajax application and need to see if the values being generated in the background are what is expected the value returned by the quest can be quite a complex multidimensional array is there a way to convert this into a string so that it can be shown with alertis there any other way of seeing these valuesany advice appreciatedthanks,['php'] +35112,events tab randomly appears and thisappears in vs 2008 i know it is a minor annoyance but it is still an annoyance and it baffles me about 3 months ago i was using vs 2008 and when i went to the properties tab there was the little lightning bolt for eventsin design mode then it suddenly went away about a week later i thiscovered that if i did not have the properties tab stickied then the events thing would be there but not when its stickied this morning all of this was working fine now today i went to add an event and suddenly the little lightning bolt icon is no longer there i can not see any option thisabling and it thisappeared without me doing any reconfiguration even without restarting vs and i have tried restarting vs to no availwhat am i missing here is this a highly annoying bug in vs 2008its up to date or am i missing some configuration update i am attaching a bounty to this question to see if i can get something a bit more helpful in short it seems like the event tab will appear and thisappear on a month or two cycle and it is not a context problem i have my cursor inside of a button for instance and i can edit all the properties of the button yet the events tab does not show up more confusing is that yet again this was working a few weeks ago,['asp.net'] +35116,c compiletime concatenation for string constants does c do any compiletime optimization for constant string concatenation if so how must my code by written to take advantage of thisexample how do these compare at run timeconsolewritelineabc defconst string s1 abcconsolewritelines1 defconst string s1 abcconst string s2 s1 defconsolewritelines2,['c#'] +35122,find index of a value in an array can linq somehow be used to find the index of a value in an arrayfor instance this loop locates the key index within an arrayfor int i 0 i wordslength i if wordsiiskey keyindex i,['c#'] +35133,yield return with null is there any way to optionally return a null with a return yield driven iteratori would like to return a null in some cases and i do not think this is particular to ienumerable of type string same goes for ienumerable of type int etc thanksstatic void mainstring args var items getitems if items null foreach var item in items consolewritelineitem else consolewritelinenull static ienumerablestring getitems if false yield return andy yield return jennifer return null compiler error cannot return a value from an iterator use the yield return statement to return a value or yield break to end the iteration,['c#'] +35151,c convert int and string to char this is a little hard i cannot figure it outi have an int and a string that i need to store it as a char the int must be in hexieint a 31string str a numberi need to put both separate by a tab into a charoutput should be like this1f a number,['c++'] +35165,how to store int array in application settings i am creating a simple windows forms application using c express 2008 i am an experienced c developer but i am pretty much brand new to c and neti am currently storing some of my simple application settings using the settings designer and code like this store setting propertiessettingsdefaulttargetlocation txtlocationtext restore setting txtlocationtext propertiessettingsdefaulttargetlocationnow i would like to store either an array of ints int or possibly a list of ints list int as a setting however i cannot figure out how to do this i have searched the documentation stackoverflow and google and i cannot find a decent explanation of how to do thismy hunch based on the sparse examples i have found is that i have to create a class that is serializable that wraps my array or list and then i will be able to use that type in the settings designer however i am not sure exactly how to do thisthanks in advance for your help,['c#'] +35188,iphone uisearchbar keyboardappearance when the keyboard appears i want to set the keyboardappearance uikeyboardappearancealerti have checked the documentation and it looks like you can only change the keyboardtypecan this be done without violating any of apples private apis,['iphone'] +35198,ruby xmlbuilder with hyphen in element name i am trying to generate some xml using xmlbuilder but my element names need to have hyphens in itwhen i try i get undefined methods with the element name being truncated at the hyphenxmlinstructxmlupdatemanifest do xmllatestid latest version updateguid xmldownloadurl latest version updatedownload url xmlreleaseinformationurl version guid urllatest vesrion updateguidendthe fixed version isxmlinstructxmltag updatemanifest do xmltag latestid latest version updateguid xmltag downloadurl latest version updatedownload url xmltag releaseinformationurl version guid urllatest vesrion updateguidend,['ruby'] +35205,how to add a function to jquery whats the easiest way to define a new jquery member functionso that i can call something likeidapplymyownfunc,['jquery'] +35220,how do i show what fields a struct has in gdb i came upon a struct called ngx http variable value t in my gdb session and i would like to print what fields it has in the console is that possible,['c'] +35255,how do i measure time elapsed in java possible duplicatehow do i calculate the elapsed time of an event in java i want to have something like this public class stream public starttime public endtime public getduration return starttime endtime which types to use in order to accomplish this in javaalso it is important that for example if the starttime it is 2300 and endtime 100 to get a duration of 200,['java'] +35258,why does google unescape their analytics tracking code just getting off my javascript training wheelswhy does google choose to unescape the documentwrite line in part 1 belowwhy do not they just write it like this maybe unescape is required for some older browser compatibilitydocumentwritescript src gajshost googleanalyticscomgajs typetextjavascriptscriptfor reference the entire google analytics tracking code looks like thispart 1script typetextjavascriptvar gajshost https documentlocationprotocol httpsl httpwdocumentwriteunescape3cscript src gajshost googleanalyticscomgajs typetextjavascript3e3cscript3escriptpart 2script typetextjavascripttry var pagetracker gat gettrackerua0 pagetracker trackpageviewcatcherrscripti understand what the rest of the code does just curious about the unescape parteditthe bottom line is unescape is required voted to close this question because it is a duplicate see answer marked correct,['javascript'] +35261,how to remove diacritics from text i am making a swethish website and swethish letters are a a and ai need to make a string entered by a user to become urlsafe with phpbasically need to convert all characters to underscore all except these az az 19and all swethish should be converted like thisa to a and a to a and a to o just remove the dots abovethe rest should become underscores as i saidim not good at regular expressions so i would appreciate the help guysthanksnote not urlencodei need to store it in a database etc etc urlencode wont work for me,['php'] +35266,execution priority in custom attributes in aspnet mvc i have two custom attributes in my aspnet mvcc applicationcustattribute1custattribute2when i use those attributes to my actions which will get executed firstcustattribute1custattribute2public actionresult indexcan i use more than one custom attributes for my actions if so in the above action which custom attribute will execute first,['c#'] +35268,how do i control the text input panel programmatically tabtipexe in windows vista7 i am adapting an application for touch screen interface and we want to use the tablet text input panel included in windows vista7 specifically its keyboard i want to show and hide it as appropriate for my app basically i want showkeyboard and hidekeyboard functions whats the best way to control thisi looked at the itextinputpanel api but i was unable to control the keyboard directly with it maybe i missed something i have also unsuccessfully tried to send window messages to its windowthe application is written in cmfcany pointers at all are greatly appreciated,['c++'] +35285,why does this if statement return false i have two text boxes and i want skip a block of code only when both are emptyif txtbox1texttrim stringempty txtbox2texttrim stringempty do somethingif either of the text boxes has something i want the do something part to execute only when both are empty do i want to skiphowever the above code fragment does not work why,"['c#', '.net']" +35304,using appconfig to set stronglytyped variables i am a c novice running net 35 and i would like to store a bunch of application default values in appconfig as the settings may vary by server environment eg development staging production what i want to do is similar to whats described in this stackoverflow article but i also want to be able to use nonstring values eg int bool something like this namevalues are just examples btwxml version10 encodingutf8 configuration applicationsettings myapp setting nameinittext serializeasstring valuehellovalue setting setting namestartat serializeasinteger value5value setting setting nameisweekend serializeasboolean valuetruevalue setting myapp applicationsettingsconfigurationcould somebody provide an example of how to do this and how to retrieve the values via c i have seen a lot of examples that require using and but i am not sure if i need those elements and if so how to create them,['c#'] +35319,in ruby how to i control the order in which testunit tests are run for example when these tests are run i want to ensure that test fizz always runs firstrequire testunitclass footest testunittestcase def test fizz puts running fizz assert true end def test bar puts running bar assert true endendupdate why do i want to do this my thought is that early failure by certain tests those testing the simpler more fundamental methods will make it easier to track down problems in the system for example the success of bar hinges on fizz working correctly if fizz is broken i want to know that right off the bat because there is no need to worry about bar which will fail too but with much more complicated output in the test results,['ruby'] +35326,diff tool that ignores newlines i frequently need to compare sql procedures to determine what has changed in the newest version the problem is everyone has their own style of formatting and sql does not usually care about where one puts their newlines eg where clauses all on one line vs newline before each andthis makes it very difficult especially for long procedures to see the actual differences i cannot seem to find a free diffmerge utility that will allow me to ignore newlines ie treat as whitespace so far i have tried winmerge and beyond compare without any luck does anyone know of a diff tool ideally free that would see these two examples as identicalex 1the quickbrownex 2thequickbrownthanks in advance,['sql'] +35333,convert xml to json and back using javascript how would you convert from xml to json and then back to xmlthe following tools work quite well but are not completely consistentxml2jsonjson2xmlhas anyone encountered this situation before,"['javascript', 'jquery']" +35336,threadvolatileread implementation i am looking at the implementation of the volatilereadvolatilewrite methods using reflector and i am puzzled by somethingthis is the implementation for volatilereadmethodimplmethodimploptionsnoinliningpublic static int volatilereadref int address int num address memorybarrier return numhow come the memory barrier is placed after reading the value of address dosent it supposed to be the opposite place before reading the value so any pending writes to address will be completed by the time we make the actual readthe same thing goes to volatilewrite where the memory barrier is place before the assignment of the value why is thatalso why does these methods have the noinlining attribute what could happen if they were inlined,['c#'] +35346,is there a dictionary like collection that can use a property of its value as the key instead of using dictionarytkeytvalue i want some type of collection class that can use a property of the value as the key is there something like this,['.net'] +35351,comparing java memory heap dumps memory profiling for java desktop application this is a more specific question to follow up on another question that i have asked recently a correct answer for this question will earn a correct answer for that previous question too since that is still in limbobasically i have a java desktop application with a memory leak issue i am using the memory profiler in netbeans ide to profile the memory issue these are the steps that i have taken done so farattach a new memory profiler to the netbeans projectdefine profiling points at several careful chosen lines of code and set them to trigger a memory heap dumprun the application in profiling modethe end result of this is that i have several memory dumps saved to thisk in hprof files netbeans ide lets me peruse the contents basic sort and search of these memory dumps and even lets me walk the heap by seeing what the references contained within each instance and what other objects reference each instance that is all good and i have been able to identify 1 or 2 fairly obvious memory leaks and rectify about 15 of the problem thus farhowever right now the method i am using relies on creating hypotheses about which objects should not be in memory at a particular point of time and then investigating those what i am after now is a way to compare two separate heap dumps basically i have two heap dumps that should be almost the same because the application has been restored to the same statehowever one is before the memory leak and the other after the memory leak and so they are obviously different if i am able to compare these two heaps using a of tool instead of manually as i am doing now then i need not rely on hypotheses to identify where the leaks are occuring and can just have the tool identify them for methis is important for me because of the the sheer number of classes and instances involved for this particular application 700 and millions repsectivelyis the netbeans ides profiler capable of doing thisif not is there a tool out there that is able to perform this taskthank you,['java'] +35364,c threadpool vs tasks as some may have seen in net 40 they have added a new namespace systemthreadingtasks which basically is what is means a task i have only been using it for a few days from using threadpool which one is more efficient and less resource consuming or just better overall,['c#'] +35379,why we always use to make navigation why not why do we always use ul to make navigation why not ol while we can use both technically,['css'] +35398,uitextfield move view when keyboard appears i am currently working on an iphone application with a single view which has multiple uitextfields for input when the keyboard shows it overlays the bottom textfields so i added the corresponding textfielddidbeginediting method to move the view up which works great voidtextfielddidbegineditinguitextfield textfield if textfield inputamount textfield inputage nstimeinterval animationduration 03011920929 cgrect frame selfviewframe frameoriginy koffset for keyboard framesizeheight koffset for keyboard uiview beginanimationsresizeforkeyboard contextnil uiview setanimationdurationanimationduration selfviewframe frame uiview commitanimations this method checks if the source of the message is one of the textfields that are visible when the keyboard shows and if not it moves the view upi also added the textfielddidendenditing method which moves the view down again and updates some model objects according to the changed input voidtextfielddidendeditinguitextfield textfield if textfield inputmenge textfield inputalter nstimeinterval animationduration 03011920929 cgrect frame selfviewframe frameoriginy koffset for keyboard framesizeheight koffset for keyboard uiview beginanimationsresizeforkeyboard contextnil uiview setanimationdurationanimationduration selfviewframe frame uiview commitanimations additional codehowever this solution has a simple flaw when i finish editing one of the hidden textfields and touch another textfield the keyboard vanishes the view moves down the view moves up again and the keyboard reappearsis there any possibility to keep the keyboard from vanishing and reappearing between two edits of the hidden textfields so that the view only moves when the selected textfield changes from one that would be hidden by the keyboard to one that would not be hidden,"['iphone', 'objective-c']" +35401,what is the difference between jquery and jquery ui what is the difference between jquery and jquery ui are they both different frameworks is jquery library needed to work jquery ui or both works standalone what is difference between any jquery tab plugin and jquery ui tab which is better to use,['jquery'] +35402,interesting params of ref feature any workarounds i wonder if there is any way something like this would be possible for value typespublic static class extensionmethods public static void settothis boolean source params boolean bools for int i 0 i boolslength i boolsi sourcethen this would be possibleboolean a true b c true d true ebsettoa c d eof course this does not work because the bools are a value type so they are passed into the function as a value not as a referenceother than wrapping the value types into reference types by creating another class is there any way to pass a variable into function by the reference ref while using params modifier,['c#'] +35406,replacing matlab with python i am a engineering student and i have to do a lot of numerical processing plots simulations etc the tool that i use currently is matlab i use it in my university computers for most of my assignments however i want to know what are the free options available i have done some research and many have said that python is a worthy replacement for matlab in various scenarios i want to know how to do all this with python i am using a mac so how do i install the different python packages what are those packages is it really a viable alternative what are the things i can and cannot do using this python setup,['python'] +35411,resharper exception rethrow possibly intended consider this method pardon the sad attempt at chuck norris humor public class chucknorrisexception exception public chucknorrisexception public chucknorrisexceptionstring message basemessage public chucknorrisexceptionstring message exception cause basemessage cause protected chucknorrisexceptionserializationinfo info streamingcontext context baseinfo context static void exceptiontestdouble x try double y 10 x consolewritelinequotient y catch exception e e e is dividebyzeroexception new chucknorrisexceptiononly chuck norris can divide by 0 e e throw e in resharper i get a warning on the throw e line saying exception rethrow possibly intended but obviously in this case that is not the intention since e could be wrapped in chucknorrisexception and if i just use throw that wrapped exception wouldnt get throwni know i can suppress the resharper warning but then it will be turned off for all scenarios if i am not mistaken i just wondered if anybody else had encountered this the only workaround i have found is to make another exception variable e2 for example and throw that that may be the best i can do here seems like resharper could detect this issue though and be smart enough to know that if e is modified then throw e is okthankseditsorry i forgot a step before the throw i need to log the exception so i cannot just doe e is dividebyzeroexception new chucknorrisexceptiononly chuck norris can divide by 0 e ethrow ei have to doe e is dividebyzeroexception new chucknorrisexceptiononly chuck norris can divide by 0 e elogexceptionethrow e,['c#'] +35417,change background position with jquery i would like to change the background position of a cssclass while hovering a lielementhtml div idcarousel ul idsubmenu liappleli liorangeli uldivcsscarousel float left width 960px height 360px background urlimagescarouselpngany suggestions on how to do this,"['jquery', 'css']" +35422,get id of the element i hover over with jquery i have a bunch of elements that look like thisspan classtags idhtmlhtmlspanspan classtags idphpphpspanspan classtags idsqlsqlspanhow would i get the name of the id of the one i hover over so i could output something like youre hovering over the html tag what i want to do is not that arbitrary but i do need to get the name of the tag the user hovers over in order to do it,['jquery'] +35438,in c is it possible to cast a list to list i want to do something like thislistchild childlist new listchildlistparent parentlist childlisthowever because parentlist is a list of childs ancestor rather than a direct ancestor i am unable to do this is there workaround other than adding each element individually,['c#'] +35439,php variable in a function name i want to trigger a function based on a variablefunction sound dog return woof function sound cow return moo animal cowprint sound animal the line is the line that is not correct i have done this before but i cannot find it i am aware of the potential security problems etc anyone many thanks,['php'] +35442,is it possible to store the address of a label in a variable and use goto to jump to it i know everyone hates gotos in my code for reasons i have considered and am comfortable with they provide an effective solution ie i am not looking for do not do that as an answer i understand your reservations and understand why i am using them anyway so far they have been fantastic but i want to expand the functionality in such a way that requires me to essentially be able to store pointers to the labels then go to them later if this code worked it would represent the type of functionality that i need but it does not work and 30 min of googling has not revealed anything does anyone have any ideasint main void int i1 void the label pointer the label the label pointer the label if i goto the label pointer return 0,['c'] +35454,wipe all data stored with coredata when the model has changed i have an app that fetches data from the internet and uses coredata to store them in the device for a smoother experiencebecause i use core data every time my schema changes the app crashes when i try to run it with the previous data stored on the device what is the fastest way to detect this change and wipe all the data from the device since i do not mind redownloading them all it beats crashing and remapping the schema to the new one in my casei see that this check is performed in the getter nspersistentstorecoordinator persistentstorecoordinatorso i only need to know the methodology to implement for wiping the whole database and seting up core data againthanks,"['iphone', 'objective-c']" +35464,when should i drop support for python24 on my public python library i maintain an open source python project right now it supports python 24 25 26 i am looking for to add support for python 3 i guess it will be easier if i drop 24 supporti know it is possible to support all but it is very annoying if i have to install 4 or 5 python versions on my machine and run the tests on all of them although it is easy to avoid new features introduced in the language i would like to make use of them and what is the point of supporting something that possible nobody uses i do want to drop it but also dont want to loose users existing and newwhen should i drop support for python 24 is there any recommendation on this,['python'] +35472,how to programatically use springs jdbctemplate we use springs jdbctemplate which is configured through spring config as illustrated below is there a way to do this without injecting the data source i would like to just create the jdbctemplate instance programatically and initalize the datasource using theoracledsour current config java classprivate jdbctemplate jdbctemplateresourcename mydatasourcepublic void setdatasourcedatasource datasource thisjdbctemplate new jdbctemplatedatasourcespring configjeejndilookup idmydatasource jndinamejavatheoracledsoracle datasource configxadatasource jndinametheoracledsjndiname xadatasourceupdate reason i am asking this is i am not a total believer in dependency injection having spring manage beans,['java'] +35473,why is linq to sql databinding to gridview much slower than passthrough sql i have compared two queries which fetch some fairly large data from a database table for query one i used linq to sql and for the other i use passthrough sql via adoneti know that linq to sql has to do a lot of work behind the scenes but what is it actually doing the two queries fetches the same amount of data but the linq to sql query is more than 5 seconds slower and uses 150mb more ramhere is my test codeusing linq to sql public void makelist int start environmenttickcount var document from d in dmtdokuments select d listtdokument documentlist documenttolist int end environmenttickcount gridview1datasource documentlist gridview1databind label1text end starttostring passthrough sql adonetpublic void makelist int start environmenttickcount sqlcommand sqlcommand new sqlcommandselect from tdokument connection sqldataadapter da new sqldataadaptersqlcommand dataset ds new dataset dafillds int end environmenttickcount gridview1datasource ds gridview1databind label1text end starttostring,['sql'] +35475,the difference between httpcookie and cookie so i am confused as msdn and other tutorials tell me to use httpcookies to add cookies via responsecookiesaddcookie but that is the problem responsecookiesadd only accepts cookies and not httpcookies and i get this errorcannot convert from systemnetcookiecontainer to systemnetcookieadditionally whats the difference between responsecookiesaddcookie and requestcookiecontaineraddcookiethanks for the help in advance i am trying to teach myself using c cookiecookie mycookie new cookiemycookiename sidmycookievalue sidmycookiehttponly truemycookiedomain domaincom httpcookiehttpcookie mycookie new httpcookiesidmycookievalue sidmycookiehttponly truemycookiedomain domaincomresponsecookiesaddmycookie,"['c#', 'asp.net']" +35484,incompatible character encodings ascii8bit and utf8 in ruby 19 i am getting the following error with my ruby 19 rails 234 this happens when user submits a nonascii standard characteri read a lot of online resources but none seems to have a solution that workedi tried using as some resources suggestedstringforce encodingutf8 but it did not helpany ideas how to resolve this is there a way to eliminate such characters before saving to the db or is a there a way to make them show,['ruby-on-rails'] +35503,is it possible to define an anonymous selector in objectivec i would like to be able to define an inline anonymous selector that a selector wherever a selector is needed as an argumentis this possible or do i have to just suck it up and define a methodbackground in my iphone application i need to update my ui from another thread to do this i use performselectoronmainthreadwithobjectwaituntildone however i would like to be able to get this functionality without having to define a whole other method,"['iphone', 'objective-c']" +35530,multiplying a tuple by a scalar i have the following codeprint imgsizeprint 10 imgsizethis will print70 7070 70 70 70 70 70 70 70 70 70 70 70 70 70 70 70 70 70 70 70while i would like it to print700 700is any way there to do this without having to writeprint 10 imgsize0 10 imgsize1ps imgsize is a pil image dunno if that matters anything in this case,['python'] +35531,does javadoc have an equivalent to unfortunately there is no cdata in htmlthis is a pity because it would be perfect for adding javadoc comments that include xml so you do not have to escape the and for examplecdata this parses complextype name however it would be possible for javadoc to recognize the cdata section and convert it to html for you for examplethis parses ltcomplextype namegtor it could use some simpler syntax than cdata because javadoc is extensible it is possible someone has added this functionality or maybe javadoc already has it buried somewhere inside does anybody know,"['java', 'html']" +35532,what is eof in the c programming language how do you get to see the last print in other words what to put in for eof i checked the definitions and it says eof is 1 and if you enter ctrld you would not see anythinginclude stdiohint main int c whilec getchar eof printfdn c printfd at eofn c,['c'] +35551,thistribute a python program with a minimal environment i want to thistribute a python application to windows users who do not have python or the correct python versioni have tried py2exe conversion but my python program is really complex and involve code import on the fly by xmlrpc process so it is not suitable for py2exethe complete python folder takes around 80mb but this includes docs and a lot of nonessential things do you know if there exists a small package of a minimal python interpreter i can include with my program include a folder of 80mb is a bit big,['python'] +35558,draw emf antialiased is there a way to draw an emf metafile exported form a drawing tool with antialiasing enabled the tools i tried are not capable of exporting emf files antaliased so i wondered if i can turn it back on manually when drawing the emf in the onpaint override of my controls if anyone can confirm that is technically possible to generate antialiased emf files another solution would be to use a drawing tool that can export to antialiased emf or have a 3rd party converter do this later if anyone knowns such a tool please let me knowedit when looking at the emf instructions it does not seem that emf itself can actually store the information whether it is to be rendered antialiased or not at least i could not find anything it is more likely that the antialiasing is done by the playback engine for example when i open an emf in word 2007 it is rendered antialiased but not when i draw it with gdi playback engine graphicsdrawimage or when i view it the standard windows image viewerthis makes me believe that some tools actually have their own emf playback engine so maybe there is free net library preferably with source code that give me an object model of the emf instructions stored in the parsed emf file so i can play it back myself instead of using graphicsdrawimage,"['c#', '.net']" +35566,adding line break in c code behind page i have written a code in c which is exceeding page width so i want it to be broken into next line according to my formatting i tried to search a lot to get that character for line break but was not able to find outin vbnet i use for line break same way what is used in c i am trying to break a string thanks in advanceshantanu gupta,['c#'] +35567,c copy constructor invocation as far as i know a copy constructor is invoked in the following scenarios 1 pass by value2 return by value3 when you create and initialize a new object with an existing objectheres the program include iostream using namespace std class example public example cout default constructor calledn exampleconst example ob1 cout copy constructor calledn example operatorconst example ob1 cout assignment operator calledn return this example coutndtor invokedendl int aaexample funct example ob2 ob2aa100 return ob2int main example x cout calling functn x funct return 0the output isdefault constructor calledcalling functdefault constructor calledassignment operator calleddtor invokeddtor invokedplease correct me iirc the following sequence of calls should occur 1 constructor of x is called2 constructor of ob2 is called3 the function returns and so copy constructor is invoked to copy ob2 to unnamed temporary variable ie funct 4 destructor of ob2 called 5 assign the unnamed temporary variable to x6 destroy temporary variable ie invoke its destructor7 destroy x ie invoke xs destructorbut then why copy constructor is not invoked and also only 2 calls to dtors are there whereas i expect 3i know compiler can do optimizations however is my understanding correct thanks a lot regardslali,['c++'] +35571,spring jta configuration how to set transactionmanager we configure our spring transaction in spring config astxjtatransactionmanageri gather this means that spring will automatically thiscover the underlying jta implementation so when we start up jboss we see these messages while spring searchesjtatransactionmanager no jta transactionmanager found at fallback jndi location javacomptransactionmanagerjavaxnamingnamenotfoundexception transactionmanager not boundbig stack trace more of the sameand then eventually seejtatransactionmanager jta transactionmanager found at fallback jndi location javatransactionmanagerjtatransactionmanager using jta usertransaction orgjbosstmusertxclientservervmclientusertransaction1f78ddequestion is how can we edit our txjtatransactionmanager tag to explicitly configure the javatransaction manager jta implementation so we avoid all these stack traces in the logs i would prefer not to just change the log4j logging levelsupdate i replaced txjtatransactionmanager with the below config and it seems to work i am guessing this is alrightbean idtransactionmanager classorgspringframeworktransactionjtajtatransactionmanager property nametransactionmanagername valuejavatransactionmanagerbean,['java'] +35577,sending an email using commonsemail to gmail email email new simpleemailstring authuser string authpwd very important do not use emailsetauthenticationemailsetsmtpport465emailsetauthenticatornew defaultauthenticatorauthuser authpwdemailsetdebugtrue true if you want to debugemailsethostnamesmtpgmailcomemailgetmailsessiongetpropertiesputmailsmtpauth trueemailgetmailsessiongetpropertiesputmaildebug trueemailgetmailsessiongetpropertiesputmailsmtpport 465emailgetmailsessiongetpropertiesputmailsmtpsocketfactoryport 465emailgetmailsessiongetpropertiesputmailsmtpsocketfactoryclass javaxnetsslsslsocketfactoryemailgetmailsessiongetpropertiesputmailsmtpsocketfactoryfallback falseemailgetmailsessiongetpropertiesputmailsmtpstarttlsenable trueemailsetfrom sendernameemailsetsubjecttestmailemailsetmsgthis is a test mailemailaddto tonameemailsendand it gives the following exceptionsevere orgapachecommonsmailemailexception sending the email to the following server failed smtpgmailcom465,['java'] +35595,how to break out of jquery each loop how do i break out of a jquery each loopi have tried return falsein the loop but this did not work any ideas,['jquery'] +35602,how to clear the content of an iframe how do i clear the content of my iframe element using javascript without loading a blank page into iti can figure out to do this iframe elementsrc blankhtml but there must be a better instant method,"['javascript', 'html']" +35605,ruby off the rails hosting many people have asked about rails hosting on this site but i am not familiar enough with the back end of things to know if there is a differencei want to host some ruby cgi webservices basically just ruby methods that take parameters from a post request access a mysql db and return datai have looked at ror and it seems like overkill for this from what i can tell it is for speeding up the development of data baesd crud sites which is not at all what i am doingso my question is does this affect the hosting provider i choose does anyone recommend a good ruby host for cgi operations i am not familiar with fastcgi mod ruby passenger mongrel etc and what they mean for performance scalability etc i just want to host my ruby scripts with reasonably good performance and all the info out thereand here seems to be focused on rails,['ruby'] +35608,how to do authentication between a webservice and a mobile phone i want to make a windows mobile 6 cellphone application this application will talk to a web service that i want to make i do not know much about web services and programming app for phones so i got a couple questionshow do i do authentication like my user loads up my app and goes to the login page they type in their credentials this gets sent to the server and authenticated now what do i send back is there some sort of formsauthenticationafter they log in do i have to keep doing checks to see if they are logged in like in aspnet mvc i have authorizeattributes on all my tags that way no one can just type in the url to that action method and be able to access it but since this is an application i am not sure if they could say go your login form first form and then somehow without logging in get to your main form the one after the login formdo web services have authorize tags like aspnet mvc since i probably need something along those lines to ensure no one types in their web brower my webservice path and get access to all those methods i made in iti am making a aspnet mvc application right now and when the user types their credentials on my site it is sent what i am guessing is clear text to the server hashed and then checked i know maybe one day when i can afford it maybe to get ssl to make it more secureso my question how about with sending the credentials from the phone to the server will it be less secure than what i have for my website right now about the same what can be done to make it more secure is it ssl againthanks,"['c#', '.net']" +35634,how to know in c code which type a variable was declared with i want to have some function that would return base if a variable of class base was passed to it derived if it was declared as derived etc not depending on runtime type of a value it was assigned to,['c#'] +35635,linq get thistinct values and fill list i am trying to figure out if i can use linq to provide me with the thistinct values of some data i have in a datatable firstname lastname qty i can get the thistinct values and fill my list but i have to run two different linq queries to get iti am sure there is a better way to do it any suggestions would be greatly appreciated very new to linqcode public static liststudentdata linqthistinctdatatable dt datatable linqtable dt get the thistinct values var query from names in dtasenumerable select new firstname namesfieldstringfirstname lastname namesfieldstringlastname thistinct fill my list with the thistinct values liststudentdata slist from sa in queryasenumerable select new studentdata firstname safirstname lastname salastname qty namesfieldintqty tolist return slist,['c#'] +35638,c is it possible to have a single application behave as console or windows application depending on switches i have a simple application that i would like to sort of automate via switches but when i do run it via switches i do not really want a user interface showing i just want it to run do it is job print stuff out in the console and exit on the other hand if i do not run it with any switches i want the user interface to pop up and in this case i do not really want a console window hanging around in the backgroundis there any way i can do this or do i have to create two separate projects one console application and one windows application,['c#'] +35639,mysql slow on first query then fast for related queries i have been struggling with a problem that only happens when the database has been idle for a period of time for the data queried the first query will be extremely slow on the order of 30 seconds and then related queries will be fast like 01 seconds i am assuming this is related to caching but i have been unable to find the cause of it changing the mysql variables tmp table size max heap table size to a larger size had no effect except to create the temp tables in memoryi do not think this is related to the query itself as it is well indexed and after the first slow query variants of the same query do not show up in the slow query log i am most interested in trying to determine the cause of this or a way to reset the offending cache so i can troubleshoot the issue,"['sql', 'mysql']" +35644,json object in ie6 how hiquick questions that probably a piece of cake for someone in the know to asnweri have a simple aspnet website that uses json for a bunch of stuff and jsonstringifyall good in firefox etc yet in ie6 i run into an error with json being undefinedis there a way i can include a json implementation without breaking what i have already using the native json objects in the other browsersif so howthanks,['javascript'] +35646,what is the true difference between lemmatization vs stemming when do i use each alsois the nltk lemmatization dependent upon parts of speechwouldnt it be more accurate if it was,['python'] +35674,how do i encrypt a string in php i want to make an encryption function that should have some secret key something like the followingfunction encryptstring key mastermind enc encryptfuncstring key return encthe same thing should apply for decryption,['php'] +35683,retrieving original row data from jqgrid it is possible to use the getrowdata method to retrieve the current of a cell but this retrieves the current cell content rather than the original data before it went through the formatterhow do i retrieve the original content before the formatting transformations are applied fyi i am populating the table using json,"['javascript', 'jquery']" +35687,how can i iterate through all checkboxes on a form i have a form that has many dynamically generated checkboxes at runtime how can i iterate through each of them so i can get their value and ids,['c#'] +35691,should the conditional operator evaluate all arguments when writing this 1 inline double f double arg 2 return arg 00 00 1arg3 4 const double d f 00 the microsoft visual studio 2005 64bit compiler came withline 4 warning c4723 potential divide by 0while you and i can clearly see that a divbyzero is never going to happen or is it,['c++'] +35693,objective c how to check if variable is nsarray or nsmutablearray how can i check if a variable is an nsarray or an nsmutablearray,"['objective-c', 'ios']" +35703,where can i get a list of all countriescities to populate a listbox kind of a programming question you create a sign up form and their address is taken from a list of countries and cities is there somewhere on the interwebs i can grab these lists from to stick in my listboxes,['html'] +35725,is it possible to protect from downloading a video from a site is it possible to protect a video from a site from being downloadedwhile users could record a video by using some hardware device it should not be possible to download a video using some link exactly like google videosfor example if i have real one player in my system i have an option to download the video this should be restricted,['php'] +35735,why or how to use nunit methods with icollection some of nunits assert methods are overloaded to use icollection but not icollectiont and thus you cannot use themis there anyway around this heck am i doing something stupidi am having to drop back to using assertareequal rather than specialised methods and its making my tests uglyany adviceeditthanks for the responses the that method of nunit seems interesting so i will look into it at a later datemark correctly mentioned this but nunit collection asserts are excellent i have recently used them on some new tests and found them excellent to work with,['c#'] +35736,render html in swing application i have a swing application that sends commands to server and receives result in xml format i need to transform this into html via xslt and then thisplay result html on the panel the problem is that the only swing component which is able to thisplay html jeditorpane takes either url or javaxswingtextstyleddocument as a source option with url does not work for me because i have to save my html as a file on the file system first and i would like to avoid thisso i have a gap between inmemory result of xsl transformation and javaxswingtextstyleddocument which can be rendered by jeditorpane or jtextpanehow to transform one to another or are there any other swing solutions to thisplay html from some inmemory sourcedom or string or whateverthank you in advance for help,"['java', 'html']" +35737,how to apply a logical operator to all elements in a python list i have a list of booleans in python i want to and or or or not them and get the result the following code works but is not very pythonicdef apply andalist if lenalist 1 return alist0 and apply andalist1 else return alist0any suggestions on how to make it more pythonic appreciated,['python'] +35738,running average in python is there a pythonic way to build up a list that contains a running average of some functionafter reading a fun little piece about martians black boxes and the cauchy thistribution i thought it would be fun to calculate a running average of the cauchy thistribution myselfimport math import randomdef cauchylocation scale p 00 while p 00 p randomrandom return location scalemathtanmathpip 05 is this next block of code a good way to populate running avgsum 0count 0max 10running avg while count max num cauchy31 sum num count 1 running avgappendsumcountprint running avg or do something else with it besides printingi think that this approach works but i am curious if there might be a more elegant approach to building up that running avg list than using loops and counters eg list comprehensionsthere are some related questions but they address more complicated problems small window size exponential weighting or are not specific to python,['python'] +35741,what is the difference between read and recv and between send and write what is the difference between read and recv and between send and write in socket programming performance and speed and other behavior,['c'] +35760,adding screen brightness controls to android application i am looking to add controls to adjust screen brightness locally in my app menu but cannot seem to figure out how to do it i have seen examples to maxout or dim brightness but i am looking to add controls so that the user can control and set the brightness level does anyone have any examples tutorials source code or just a place to point me in the right direction,"['java', 'android']" +35761,how do you assert an exception from another ruby module is thrown using assert throws i am trying to write code like thisassert throwsextractionfailed unitextract from5 x 2005extractionfailed is a trivial subclass of exception and under testunit i am trying to assert that it is thrown when i call unitextract from bad data i have moved extractionfailed into the semantictext module so now testunit saysextractionfailed expected to be thrown butsemantictextextractionfailed was throwni tried writing assert throwssemantictextextractionfailed but i got the rather confusing message typeerror semantictext is not a classmodulei can make it work by doing the following although it seems like a hack assert throwssemantictextextractionfailedto sto sym unitextract from5 x 2005so whats the right way to say this assertion in ruby,['ruby'] +35769,java find the first cause of an exception i need to check if an exception is caused by some database problem i receive an exception and check if its cause contains the ora string and return that something like ora01 the problem here is that the exception i receive is nested inside other exceptions so if i do not find out if it is an oracle exception i have to check into the cause of that exception and so onis there a cleaner way to do this is there a way to know the first cause the deepnested exception of a given exceptionmy current code looks like thisprivate string geterrororaclethrowable e final string oracle ora if egetcause null egetcausetostringcontainsoracle return egetcausetostring else ifegetcause null return geterrororacleegetcause else return null,['java'] +35770,should i use an intermediate temp variable when appending to an nsstring this works it does compile but i just wanted to check if it would be considered good practice or something to be avoidednsstring filename imagefilename filename stringbyappendingstringpngnslogtest filenameoutput test imagepngmight be better written with a temporary variablensstring filename imagensstring tempnametempname filename stringbyappendingstringpngnslogtest tempnamejust curious,['objective-c'] +35787,xml element name with colon i am working against a 3rd party xml api they have defined a required xml structure similar to the followingns1e xmlnsns1schemans1bns2sns2vns2bl ns2vns2sns1bns1ethere is a sql table with the information that i need to put into this xml format i have a linq to sql adapter to get the data and i am using a systemxml to create an xml document xmldocumentcreateelementns1e etcthis works fine as long as i remove the colons from the element names with the colons only the right hand side of the colon is in the element name i know colons are a nono but i do not have any control over what the 3rd party api is dictatingwhat are my options for getting around this are there any useful ways of forcing the colons into the element names i do not have to use xmldocument but not sure what other method will get me thereupdate i realize that the ns1 refers to a namespace and yes there are 2 when writing out the xml i can make it work if i say xmldocumentcreateelementns1e httpschemahowever the xml output of this is ns1e xmlnsns1httpschemaif i just say xmldocumentcreateelementns1e with no uri then the output is just e i do not want the output to have the schema reference but i do need to have the prefix the result i want to achieve is simply ns1e both namspaces are declared at the top which i would think would mean i would have to declare them at every node,['.net'] +35791,what are the limits of python i spent a few days reading about c and python and i found that python is so much simpler and easy to learn so i wonder does it really worth spending time learning it or should i invest that time learning c insteadwhat can c do and python cannot,"['c++', 'python']" +35792,how i can use mysql in c i have searched a lot all i found is a mysql but i do not know how to install iti do not have knowledge about libraries in c,"['c++', 'mysql']" +35795,subset of array in c if i have an array with 12 elements and i want a new array with that drops the first and 12th elements for example if my array looks like this a b c d e f g h i j k l i want to either transform it or create a new array that looks like b c d e f g h i j k i know i can do it by iterating over them i was just wondering if there was a cleaner way built into cupdated to fix a typo changed 10 elements to 12 elements,['c#'] +35796,slightly weird c code sorry if this is simple my c is rustywhat is this doing there is no assignment or function call as far as i can see this code pattern is repeated many times in some code i inherited if it matters it is embedded codevolatile uint16 somevarsomethingedit continuing from there does the following additional code confirm heaths suspicions exactly from code including the repetition except the names have been changed to protect the innocentif waitfornotbusy50 return error code xvolatile uint16 somevarsomethingif waitfornotbusy50 return error code xvolatile uint16 somevarsomethingx somedata,"['c++', 'c']" +35801,can ruby be used for ui based windows apps i am sorry if this question is noobish but i am not having much luck with google can ruby be used for ui based windows apps i am not looking for a rails app just rubythanks,['ruby'] +35808,explode string by one or more spaces or tabs how can i explode a string by one or more spaces or tabsexample a b c di want to make this an array,['php'] +35827,can i redefine a c macro then define it back i am using both the juce library and a number of boost headers in my code juce defines t as a macro groan and boost often uses t in it is template definitions the result is that if you somehow include the juce headers before the boost headers the preprocessor expands the juce macro in the boost code and then the compiler gets hopelessly lostkeeping my includes in the right order is not hard most of the time but it can get tricky when you have a juce class that includes some other classes and somewhere up the chain one file includes boost and if any of the files before it needed a juce include youre in troublemy initial hope at fixing this was toundef tbefore any includes for boost but the problem is if i do not redefine it then other code gets confused that t is not declaredi then thought that maybe i could do some circular define trickery like so some includes up heredefine t tundef t include boost headers heredefine t t undef t ugly but i thought it may worksadly no i get errors in places using t as a macro that t was not declared in this scopeis there a way to make these two libraries work reliably together,['c++'] +35830,determine which w3wpexe process belongs to which app pool in windows 7 iis75 i have recently upgraded my development machine from windows xp to windows 7 how can i tell which w3wpexe process belongs to which app pool on a desktop running windows 7on a server running iis6 you can run cwindowssystem32cscript iisappvbson a windows 2008 server running iis7 you can run appcmd list wpbut what about on my desktop,"['.net', 'asp.net']" +35838,how to thisable mobilesafari autoselection my webapp requires users to tap and hold on an element for a game action but iphone automatically selects the area which is confusing to the useranyone know what html elements prevent selection or if javascript can block selectionany help is appreciated,"['javascript', 'iphone']" +35840,what is haslayout i have read some article on it but did not get what is actually can anyone on so explain meis it only related to ie6 onlywhat does zoom1is layout is a ie only tagediti found this info very informative for mebecause internet explorer is so old as it was one of the first browsers available it hasnat had the luxury of starting anew as current browser do so as time went by microsoft began adapting new engines to make use of css seems finea however css changes the fundamental assumption that internet exploreras engine is based on a that anything significant is a rectangle that contains all its contentso to deal with the new standards of css microsoft decided to fix their ancient engine by implementing the haslayout property instead of rebuilding ie every element in internet explorer now has a haslayout property depending on the element it is set to either true or false by default if haslayout is set to true a the element is an independent box that is responsible for rendering itself if false a then the element relies on a parent element that has haslayout set to true to render it this is where a majority of ie bugs come to lifesource i found one more thiscussion here also,"['html', 'css']" +35853,how to exit from setinterval i need to exit from a running interval if the conditions are correctvar refreshid setintervalfunction var properid checkreload if properid 0 exit from the loop 10,['javascript'] +35858,log4net and extra fields is it possible to insert extra fields into the database and use them in log4net i have a userid i would like to have in an extra field in the logtable i have added the field in the log4netconfigparameter parametername valueuserid dbtype valueguid layout typelog4netlayoutrawpropertylayout parameterbut how do i update the ilog interface to support the extra database field so i could for example log log4netlogmanagergetloggerlognamefatalmessage exception userid,['.net'] +35861,can nltkpynltk work per language ie nonenglish and how how can i tell nltk to treat the text in a particular languageonce in a while i write a specialized nlp routine to do pos tagging tokenizing and etc on a nonenglish but still hindoeuropean text domainthis question seem to address only different corpora not the change in codesettingsnltk tagging in germanalternativelyare there any specialized hebrewspanishpolish nlp modules for python,['python'] +35879,what is faster many ifs or else if i am iterating through an array and sorting it by values into days of the weekin order to do it i am using many if statements does it make any difference to the processing speed if i use many ifs versus a set of else if statements,['php'] +35880,how can i get a list of all classes within current module in python i have seen plenty of examples of people extracting all of the classes from a module usually something like foopyclass foo pass testpyimport inspectimport foofor name obj in inspectgetmembersfoo if inspectisclassobj print objawesomebut i cannot find out how to get all of the classes from the current module foopyimport inspectclass foo passdef print classes for name obj in inspectgetmembers what do i do here if inspectisclassobj print obj testpyimport foofooprint classesthis is probably something really obvious but i have not been able to find anything can anyone help me out,['python'] +35884,how do i convert nsinteger to nsstring datatype how does one convert nsinteger to the nsstring datatypei tried the following where month is an nsinteger nsstring instr nsstring stringwithformatd month intvalue,['iphone'] +35888,accessing a python traceback from the c api i am having some trouble figuring out the proper way to walk a python traceback using the c api i am writing an application that embeds the python interpreter i want to be able to execute arbitrary python code and if it raises an exception to translate it to my own applicationspecific c exception for now it is sufficient to extract just the file name and line number where the python exception was raised this is what i have so farpyobject pyresult pyobject callobjectsomecallablepythonobject someargsif pyresult pyobject exctype excvalue exctraceback pyerr fetchexctype excvalue exctraceback pyerr normalizeexceptionexctype excvalue exctraceback pytracebackobject traceback pytracebackobjecttraceback advance to the last frame python puts the mostrecent call at the end while tracebacktb next null traceback tracebacktb next at this point i have access to the line number via tracebacktb lineno but where do i get the file name from digging around in the python source code i see they access both the filename and module name of the current frame via the frame structure which looks like it is a privatelydefined struct my next idea was to programmatically load the python traceback module and call its functions with the c api is this sane is there a better way to access a python traceback from c,['python'] +35889,in lex how to make yyin point to a file with the main function in yacc i am storing the arguments passed to main in yacc in a file now i want the lex to read its input from this file rather than the terminal i know i can point yyin to a file like yyin fopenfnr but this works only when main is in lex when i use this yyin declaration in main in yacc it shows an error so please suggest something to overcome this problem,['c'] +35910,template specialization with a templatized type i want to specialize a class template with the following functiontemplate typename tclass foopublic static int barthe function has no arguments and shall return a result based on the type of foo in this toy example we return the number of bytes of the type but in the actual application we want to return some metadata objectthe specialization works for fully specified types specialization 1 workstemplate int foointbar return 4 specialization 2 workstemplate int foodoublebar return 8 specialization 3 workstypedef pairint int intpairtemplate int foointpairbar return 2 foointbar however i would like to generalize this to types that depend on other template parameters themselvesadding the following specialization gives a compiletime error vs2005 specialization 4 errortemplate template typename u typename vint foostdpairu v bar return fooubar foovbar i am assuming this is not legal c but why and is there a way to implement this type of pattern elegantly,['c++'] +35911,file get contents receive cookies is it possible to receive the cookies set by the remote server when doing a file get contents request i need php to do a http request store the cookies and then make a second http request using the stored cookies,['php'] +35912,java sort an unmodifiable list how would one do thisi have tried creating a new empty list then copying unmodifiable lists elements to it but i am getting unsupported operation errorany help is appreciated,['java'] +35935,overcoming pythons limitations regarding instance methods it seems that python has some limitations regarding instance methodsinstance methods cannot be copiedinstance methods cannot be pickledthis is problematic for me because i work on a very objectoriented project in which i reference instance methods and there is use of both deepcopying and pickling the pickling thing is done mostly by the multiprocessing mechanismwhat would be a good way to solve this i did some ugly workaround to the copying issue but i am looking for a nicer solution to both problemsdoes anyone have any suggestionsupdatemy use case i have a tiny event system each event has an action attribute that points to a function it is supposed to trigger and sometimes that function is an instance method of some object,['python'] +35936,does mono support xaml does mono support xamlspecifically i am thinking of switching to using xaml for new gui work that i do but also i like to keep my personal projects compilable in mono should i just stick with plain old systemwindowsforms for now,['.net'] +35938,mvvm what is the ideal way for usercontrols to talk to each other i have a a user control which contains several other user controls i am using mvvm each user control has a corresponding vm how do these user controls send information to each other i want to avoid writing any code in the xaml code behind particularly i am interested in how the controls inside the main user control will talk to each other and how will they talk to the container user controlediti know that using eventsdelegates will help me solve this issue but i want to avoid writing any code in xaml codebehind,['c#'] +35942,working with heterogenous data in a statically typed language f one of fs claims is that it allows for interactive scripting and data manipulation exploration i have been playing around with f trying to get a sense for how it compares with matlab and r for data analysis work obviously f does not have all practical functionality of these ecosystems but i am more interested in the general advantages thisadvantages of the underlying languagefor me the biggest change even over the functional style is that f is statically typed this has some appeal but also often feels like a straightjacket for instance i have not found a convenient way to deal with heterogeneous rectangular data think dataframe in r assume i am reading a csv file with names string and weights float typically i load data in perform some transformations add variables etc and then run analysis in r the first part might look likedf readcsvweightscsvdflogweight logdfweightin f it is not clear what structure i should use to do this as far as i can tell i have two options 1 i can define a class first that is strongly typed expert f 910 or 2 i can use a heterogeneous container such as arraylist a statically typed class does not seem feasible because i need to add variables in an adhoc manner logweight after loading the data a heterogeneous container is also inconvenient because every time i access a variable i will need to unbox it in flet df readcsvweightscsvdflogweight logdouble dfweightif this were once or twice it might be okay but specifying a type every time i use a variable does not seem reasonable i often deal with surveys with 100s of variables that are addeddropped split into new subsets and merged with other dataframes am i missing some obvious third choice is there some fun and light way to interact and manipulate heterogeneous data if i need to do data analysis on net my current sense is that i should use ironpython for all the data exploration transformation interaction work and only use fc for numerically intensive parts is f inherently the wrong tool for quick and dirty heterogeneous data work,"['c#', '.net']" +35944,how to avoid double check locking when adding items to a dictionary object in net i have a question about improving the efficiency of my program i have a dictionarystring thingey defined to hold named thingeys this is a web application that will create multiple named thingeyas over time thingeyas are somewhat expensive to create not prohibitively so but iad like to avoid it whenever possible my logic for getting the right thingey for the request looks a lot like this private dictionarystring thingey thingeys public thingey getthingeyrequest request string thingeyname requestthingeyname if thisthingeyscontainskeythingeyname create a new thingey on 1st reference thingey newthingey new thingeyrequest lock thisthingeys if thisthingeyscontainskeythingeyname thisthingeysaddthingeyname newthingey else oops someone else beat us to it newthingey will eventually get gced return this thingeysthingeyname in this application thingeys live forever once created we donat know how to create them or which ones will be needed until the app starts and requests begin coming in the question i have is in the above code is there are occasional instances where newthingey is created because we get multiple simultaneous requests for it before itas been created we end up creating 2 of them but only adding one to our collectionis there a better way to get thingeys created and added that doesnat involve checkcreatelockcheckadd with the rare extraneous thingey that we created but end up never using and this code works and has been running for some time this is just the nagging bit that has always bothered mei am trying to avoid locking the dictionary for the duration of creating a thingey,['c#'] +35945,mysql resetting the index count to 0 i need to reset my table counter back to 0 is there a mysql command for this,['mysql'] +35953,getting attributes of enums value i would like to know if it is possible to get attributes of the enum values and not of the enum itself for example suppose i have the following enumusing systemcomponentmodel for descriptionattributeenum funkyattributesenum descriptionname with spaces1 namewithoutspaces1 descriptionname with spaces2 namewithoutspaces2what i want is given the enum type produce 2tuples of enum string value and its descriptionvalue was easyarray values systemenumgetvaluestypeoffunkyattributesenumforeach int value in values tuplevalue enumgetnametypeoffunkyattributesenum valuebut how do i get description attributes value to populate tupledesc i can think of how to do it if the attribute belongs to the enum itself but i am at a loss as to how to get it from the value of the enum,['c#'] +35964,how to combine firstchild and hover i have an unordered list i am using for a menu each item has a background image and a hover image the background image on the first element is different that the rest so i use the following to style it which works fineprodnavbar ullastchild lifirstchild since i want a rollover image on this element as well i have tried adding hover like soprodnavbar ullastchild lifirstchildhover but this does not work whats the syntax to combine firstchild and hover,"['html', 'css']" +35986,geolocation provider for firefox that allows manual input are there any easy ways to override the default behaviors of the geolocation api and just hard code your current locationi think this would be useful for testing and for privacy reasons providing fake location datai thought there was an add on for this but i cannot seem to find one only option right now seems to be changing the aboutconfig geowifiurl to some alternative webservice which i consider overly complicatedany ideasthanksideal scenariosomebody implements an addon where a google map appears and i can pick a new default location,['javascript'] +35992,can i use jquery with nodejs is it possible to use jquery selectorsdom manipulation on the serverside using nodejs,"['javascript', 'jquery']" +36016,does hibernate support the limit statement in mysql i am working on a project which uses javamysqlstruts2 mvc and hibernate i tried using limit statement in hql query but its not working properlyselect t from table1 t where tcolumn1 someval limit 05edit i am using this as a namedquery and calling this namedquery using jpa templatethis works correctly in mysql but when i ran this as a hql query this returns all records without regard to limit statement has anyone faced the same problem any help appreciatedregards rdj,['mysql'] +36017,building sql strings in accessvba occasionally i have had to build a sql string in vba and execute it with docmdrunsql i have always built these strings by concatenating variables into the string egdim mysqlstring as stringmysqlstring insert into mytable field1 field2 field3 values mysqlstring mysqlstring metextmyfield1 parameter commentsmysqlstring mysqlstring metextmyfield2 mysqlstring mysqlstring metextmyfield3 mysqlstring mysqlstring docmdrunsql mysqlstringvba does not seem to have a unary concatenation operator like and while this does not look ideal at least i can comment each of my parameters and change them independently it makes it easier to read and to change than one monster concatenated string but it still seems like a terrible way to build sql strings i have one with about 50 parameters at work so 50 lines of mysqlstring mysqlstring not cuteincidentally that rules out the use of linecontinuations to format the string as there is a limit on the number of linecontinuations you can use on a single string hint less than 50 also vba does not let you put a comment after the linecontinuation grrup until recently i thought this was the only way to build these strings but recently i have seen a different pattern injecting the parameters in the string like this question vbnet that i posted an answer on and wondered if there was an equivalent of parametersaddwithvalue for vba or if that would even be any better than the string concatenation approach so i figured that this deserves its own question maybe there is something i am missing herecan some of the access experts please clarify what are the best practices for building sql strings in accessvba,['sql'] +36032,changing font in a console window in net i have built a neat little console app which basically interacts with aspnet projects on a users machine i have a really trivial need all i need to do is before i show the console window i need to have it a black background a lime green foreground and a lucida font i could achieve the color part by using the static methods of console class although there is nothing in the class which talks about changing fonts has anyone been able to change console font programaticallyany help appreciated,['c#'] +36036,ensure java synchonized locks are taken in order we have two threads accessing one list via a synchronized method can wea rely on the run time to make sure that each of them will receive access to the method based on the order they tried to orb does the vm follow any other rulesc is there a better way to serialize the requestsmany thanks,['java'] +36038,setting onbeforeunload on body element in chrome and ie using jquery i have a system where i want to check with the user if they are sure they want to leave the page once a dirty flag is set i am using the following code in firefox i can look at the page source through firebug and the tag correctly has the onbeforeunload attribute inserted in it in chrome and firefox this does not happen though and i am able to navigate away from the page without any warning at all the jquery line to update the body tag is definitely being executed it just is not performing itif bodyattronbeforeunload null if windowevent ie and chrome use this bodyattronbeforeunload catchleavepageevent else firefox uses this bodyattronbeforeunload return falsecatchleavepageevent any ideas how to proceed from here,"['javascript', 'jquery']" +36049,load assembly at runtime and create class instance i have a assembly in this assembly i have a class and interface i need to load this assembly at runtime and want to create an object of the class and also want to use the interfaceassembly mydall assemblyloaddall dall is name of my dlltype myloadclass mydallgettypedaloadclass loadclass is my classobject obj activatorcreateinstancemyloadclassthis is my code how could it be improved,['c#'] +36050,waf generating visual studio projects can the waf build system generate visual studio project files for cc,"['c++', 'c']" +36053,firebug console window scope why is not this always the same firebug console scope why is not this always the same shoudnt it be window all the time,['javascript'] +36079,should junit tests be javadocced i have a number of junit test cases that are currently not documented with javadoc commentsthe rest of my code is documented but i am wondering if it is even worth the effort to document these tests,['java'] +36083,extending enums in c is there a way in c to extendinherit enumsieenum enum abcenum enumex public enum defor at least define a conversion between them,['c++'] +36092,retrieve java annotation attribute how can i retrieve the value of an annotation on the annotated methodi havemyannotationattribute1 value1 attibute2 value2public void mymethod i want to get value1 here,['java'] +36093,jquery drag and drop using live events i have an application with a long list that changes frequently and i need the items of that list to be draggable i have been using the jquery ui draggable plugin but it is slow to add to 400 list items and has to be readded every time new list items are added does anyone know of a plugin similar to the jquery ui draggable plugin that uses jquery 13s live events this would solve both problems,['jquery'] +36098,how might i get an elements border color value using jquery using idcssbackgroundcolor to retrieve an elements background color or most other css attributes works just fine butidcssbordercolor returns an empty string how can i get the border color value used on the element,"['jquery', 'css']" +36103,sql order by a column from another table i have 3 tables people groups and memberships memberships is a join table between people and groups and have 3 columns personid groupid and description texti want to select entries from the memberships table depending on a groupid but sorting the result by the names of people associated to the found memberships name is a column of people tableselect from memberships where membershipsgroupid 32 order by is it possible to achieve this in one single query,['sql'] +36111,rubyrails converting a date to a unix timestamp how would i get a unix timestamp number of seconds since 1970 gmt from a date object in a rails appi know timeto i returns a timestamp but doing dateto time and then getting the timestamp results in something that is off by about a month not sure why any help is appreciated thanksedit ok i think i figured it out i was processing a date several times in a loop and each time the date was moved a little because of a time zone mismatch ultimately leading to my timestamp being a month off still i would be interested in knowing if there is any way to do this without relying on dateto time,"['ruby-on-rails', 'ruby']" +36151,difference between using character pointers and character arrays basic questionchar new strchar newstrif i have to concatenate some data into it or use string functions like strcatsubstrstrcpy whats the difference between the twoi understand i have to allocate memory to the char approach line 2 i am not really sure how thoughand const char and string literals are the samei need to know more on this can someone point to some nice exhaustive contentmaterial,"['c++', 'c']" +36169,how to efficiently use mysqldb sscursor i have to deal with a large result set could be hundreds thousands of rows sometimes morethey unfortunately need to be retrieved all at once on start up i am trying to do that by using as less memory as possibleby looking on so i have found that using sscursor might be what i am looking for but i still do not really know how to exactly use themis doing a fetchall from a base cursor or a sscursor the same in term of memory usagecan i stream from the sscursor my rows one by one or a few by a few and if yeswhat is the best way to do so,"['python', 'mysql']" +36175,preventing a div and its content from being printed i have a print page and i want to put a div with some instructions on how to print the page in it i do not want this section to appear when they actually print the pagehow would i achieve this using css or javascript,['css'] +36182,web application problems webconfig errors http 50019 with iis75 and aspnet v2 this is driving the whole team crazy there must be some simple misconfigured part of iis or our web server but every time we try to run out aspnet web application on iis 75 we get the following errorheres the error in fullhttp error 50019 internal server errorthe requested page cannot be accessed because the related configuration data for the page is invaliddetailed error information module iis web corenotification unknownhandler not yet determinederror code 0x80070dconfig errorconfig file ewrootwebconfigrequested url httplocalhost80defaultaspxphysical path logon method not yet determinedlogon user not yet determinedconfig source 1 0the machine is running windows server 2008 r2 were developing our web application using visual studio 2008 according to microsoft the code 80070d means there is a syntax error in our webconfig except the project builds and runs fine locally looking at the webconfig in xml notepad does not bring up any syntax errors either i am assuming it must be some sort of poor configuration on my partdoes anyone know where i might find further information about the error nothing is showing in eventviewer either not sure what else would be helpful to mentionassistance is greatly appreciated thanksupdates posted webconfig belowok since i posted the original question above i have tracked down the precise lines in the webconfig that were causing the errorhere are the lines they appear between systemwebserver tagshttphandlersremove verb pathasmxadd verb pathasmx validatefalse typesystemwebscriptservicesscripthandlerfactory systemwebextensions version10610250 cultureneutral publickeytokenf2cb5667dc123a56httphandlersnote if i delete the lines between the httphandlers i still get the error i literally have to delete httphandlers and the lines inbetween to stop getting the above erroronce i have done this i get a new 50019 error however thankfully this time iis actually tells me which bit of the webconfig is causing a problemhandlersremove namewebservicehandlerfactoryintegratedadd verb pathasmx validatefalse typesystemwebscriptservicesscripthandlerfactorysystemwebextensions version10610250 cultureneutral publickeytokenf2cb5667dc123a56add namescripthandlerfactoryappservices verb path appserviceaxd preconditionintegratedmode typesystemwebscriptservicesscripthandlerfactory systemwebextensions version10610250 cultureneutral publickeytokenf2cb5667dc123a56add namescriptresource preconditionintegratedmode verbgethead pathscriptresourceaxd typesystemwebhandlersscriptresourcehandler systemwebextensions version10610250 cultureneutral publickeytokenf2cb5667dc123a56handlerslooking at these lines it is clear the problem has migrated further within the same systemwebserver tag to the handlers tagthe new error is also more explicit and specifically complains that it does not recognize the attribute validate as seen on the third line above removing this attribute then makes it complain that the same line does not have the required name attribute adding this attribute then brings up aspnet errorcould not load file or assembly systemwebextensions version10610250 cultureneutral publickeytokenf2cb5667dc123a56 or one of its dependencies the system cannot find the file specifiedobviously i think these new errors have just arisen from me deleting the httphandlers tags in the first place they are obviously needed by the application so the question remains why would these tags kick up an error in iis in the first placedo i need to install something to iis to make it work with themthanks again for any helpwebconfigheres the troublesome bits of our webconfig i hope this helps someone find our problemsystemweb stuff cut out httphandlers remove verb pathasmx add verb pathasmx validatefalse typesystemwebscriptservicesscripthandlerfactory systemwebextensions version10610250 cultureneutral publickeytokenf2cb5667dc123a56 add verb path appserviceaxd validatefalse typesystemwebscriptservicesscripthandlerfactory systemwebextensions version10610250 cultureneutral publickeytokenf2cb5667dc123a56 add verbgethead pathscriptresourceaxd typesystemwebhandlersscriptresourcehandler systemwebextensions version10610250 cultureneutral publickeytokenf2cb5667dc123a56 validatefalse httphandlers httpmodules add namescriptmodule typesystemwebhandlersscriptmodule systemwebextensions version10610250 cultureneutral publickeytokenf2cb5667dc123a56 httpmodulessystemwebsystemwebserver validation validateintegratedmodeconfigurationfalse modules add namescriptmodule preconditionintegratedmode typesystemwebhandlersscriptmodule systemwebextensions version10610250 cultureneutral publickeytokenf2cb5667dc123a56 modules remove verb pathasmx add verb pathasmx validatefalse typesystemwebscriptservicesscripthandlerfactory systemwebextensions version10610250 cultureneutral publickeytokenf2cb5667dc123a56 handlers remove namewebservicehandlerfactoryintegrated add verb pathasmx validatefalse typesystemwebscriptservicesscripthandlerfactorysystemwebextensions version10610250 cultureneutral publickeytokenf2cb5667dc123a56 add namescripthandlerfactoryappservices verb path appserviceaxd preconditionintegratedmode typesystemwebscriptservicesscripthandlerfactory systemwebextensions version10610250 cultureneutral publickeytokenf2cb5667dc123a56 add namescriptresource preconditionintegratedmode verbgethead pathscriptresourceaxd typesystemwebhandlersscriptresourcehandler systemwebextensions version10610250 cultureneutral publickeytokenf2cb5667dc123a56 handlerssystemwebserver,['asp.net'] +36199,how to implement serialization in c whenever i find myself needing to serialize objects in a c program i fall back to this kind of patternclass serializable public static serializable deserializeistream is int id is id switchid case example id return new exampleclassis void serializeostream os os getclassid serializemeos protected int getclassid0 void serializemeostream os0the above works pretty well in practice however i have heard that this kind of switching over class ids is evil and an antipattern whats the standard ooway of handling serialization in c,['c++'] +36225,prism event aggregation subscriber not triggered i am working on implementing an event aggregation with prism i have a few modules and i want each of them to subscribe to events that tells them when they are requested i started out doing an all plain example with both subscribed and publisher in the shell no problems there now when i move the subscribers out to my modules they do not get triggered whats even more odd is that it actually has worked a few times all of which i have been pending in a breakpoint so it seems to me to be some race condition but i do not understand why assumption made i do not need to set up the ieventaggregator anywhere eg registering in the ioc container this is built into prism such that i only have one instance of the event aggregator right so the question is basically howwherewhen i should set up my subscribers is there a specific order on stuff etc in my simplified example i have one module mymodule the bootstrapper will add mymodule to the catalog making it initialized catalogaddmoduletypeofmymodulemymodule will store the aggregator and use this for subscribing to the mymodulerequestedevent it also uses a menu registry to register in the application menu the idea is that eventually clicking in the menu should trigger the event notifying mymodule that it has been requested then i want it to be mymodules responsibility to figure out what to do further public mymoduleieventaggregator aggregator iapplicationmenuregistry menu applicationmenu menu aggregator aggregatorpublic void initialize var evnt aggregatorgeteventmymodulerequestedevent evntsubscribemymodulerequested applicationmenuregistermenuitemmymodule evntpublic void mymodulerequestedbool b messageboxshowmymodule requestednow i have a button in my shell which will publish this event the shell gets the same event aggregator when resolved public shellieventaggregator aggregator initializecomponent var evnt aggregatorgeteventmymodulerequestedevent eventtriggerbuttonclick s e evntpublishtruenotes have verified that the event is published adding a subscriber in the shell too will make this subscriber receive the event again the subscriber in mymodule is not triggered however it has strangely been on a few occasions i do not use the input to the event it seemed like you needed to have some inputtype so i just went with a dummy bool can i get rid of this,['.net'] +36233,how to declare a two dimensional array most easily in php like declare int d0m 0n,['php'] +36234,not able to capture enter key in winforms text box when the user is entering a number into a text box i would like them to be able to press enter and simulate pressing an update button elsewhere on the form i have looked this up several places online and this seems to be the code i want but it is not working when data has been put in the text box and enter is pressed all i get is a ding what am i doing wrong visual studio 2008private void tbxmod keydownobject sender keyeventargs e if ekeycode keysenter btnmodperformclick,['c#'] +36246,dial number without prompt i am trying to write a function for the android platform that will allow me to call 911 without any sort of prompt i have already added the permission androidpermissioncall privileged i just need a function that will dial 911 at the press of a button in my options menu,"['java', 'android']" +36252,can we check push notification in simulator possible duplicatehow can i test apple push notification service without an iphone i want to know that can we receive push notification on simulator or notalso i want something like this tell me if it is possiblethe app opens unregistered for push notification and when app terminates register for push notification,['iphone'] +36257,is it possible to unpack a tuple without using variables i am using the ospathsplit function on a path in my program to get the filename and pathname of a file then passing them into another method but my current solution seems rather uglypath ospathsplitsomefilesome classpath0 path1is it possible to unpack the path tuple in a cleaner way within the call to some class something likesome classospathsplitsomefileunpackor should i simply be going about this another way maybe a more pythonic way,['python'] +36264,is there any simple java ftp server libraries that is embeddable i have tried apache ftp server but it lacks document and supportand it is totally based on spring configuration framework which i do not think i could understand very quicklywhat i want is just a simple ftp server that could i could embed into my applicationi could handle download commands using my own code sending some data from database instead of from static filesany suggestion,['java'] +36271,get class name from a module how i can get from a module the class name of the class the module is included module actmethods def some methodattr names cls selfclass this does not work endendhow i can get into the cls variable the name of the class to with this module is loaded,['ruby'] +36284,incrementing in c when to use x or x i am currently learning c and i have learned about the incrementation a while agoi know that you can use x to make the incrementation before and x to do it afterstill i really do not know when to use either of the two i have never really used x and things always worked fine so far so when should i use itexample in a for loop when is it preferable to use xalso could someone explain exactly how the different incrementations or decrementations work i would really appreciate it,['c++'] +36298,database best performance way to query geo location data i have a mysql database i store homes in the database and perform literally just 1 query against the database but i need this query to be performed super fast and that is to return all homes within a square box geo latitude longitudeselect from homes where geolat between and and geolng between and how is the best way for me to store my geo data so that i can perform this query of thisplaying all home within the geolocation box the quickestbasicallyam i using the best sql statement to perform this query the quickestdoes any other method exist maybe not even using a database for me to query the fastest way a result of homes within a boxed geolocation boundsin case it helps i have include my database table schema belowcreate table if not exists homes home id int10 unsigned not null auto increment address varchar128 collate utf8 unicode ci not null city varchar64 collate utf8 unicode ci not null state varchar2 collate utf8 unicode ci not null zip mediumint8 unsigned not null price mediumint8 unsigned not null sqft smallint5 unsigned not null year built smallint5 unsigned not null geolat decimal106 default null geolng decimal106 default null primary key home id key geolat geolat key geolng geolng engineinnodb updatei understand spatial will factor in the curvature of the earth but i am most interested in returning geo data the fastest unless these spatial database packages somehow return data faster please do not recommend spatial extensions thanksupdate 2please note no one below has truly answered the question i am really looking forward to any assistance i might receive thanks in advance,['mysql'] +36306,what happens to a weakreference after gc of weakreferencetarget what happens to the weakreference when the target object referenced by weakreferencetarget has been garbage collected does the weakrerence stay alive and keeps existingthe reason why i am asking is that i have a list of weakreferences stored in a list during runtime new weakreferences constantly are getting added to that list now when the target object dies do i have to cleanup the abandoned weakreference myselfif so is there a clever trick how i could do this can i get notified when a weakreference becomes abandoned or do i have to introduce a timer that frequently loops through that list to see if any weakreference instances can be removed from that list,['.net'] +36316,simple way to convert a string to a dictionary what is the simplest way to convert a string of keywordvalues to a dictionary for example the following stringnamejohn smith age34 height1732 locationus avatarto the following python dictionarynamejohn smith age34 height1732 locationus avatarthe avatar key is just to show that the strings can contain and so a simple split would not do any ideas thanks,['python'] +36320,how can i translate this xpath expression to beautifulsoup in answer to a previous question several people suggested that i use beautifulsoup for my project i have been struggling with their documentation and i just cannot parse it can somebody point me to the section where i should be able to translate this expression to a beautifulsoup expressionhxsselecttdclassaltrow2ahrefreawthe above expression is from scrapy i am trying to apply the regex reaw to td class altrow to get the links from therei would also appreciate pointers to any other tutorials or documentation i could not find anythanks for your helpediti am looking at this page soupheadtitletitlewhite case llp lawyerstitle soupfindhrefrecompilecabel soupfindhrefrecompilediversitya hrefdiversitycommitteecommitteeayet if you look at the page source cabel is there td classaltrow valignmiddle width34 a hrefcabelabel christianafor some reason search results are not visible to beautifulsoup but they are visible to xpath because hxsselecttdclassaltrow2ahrefreaw catches cabeleditcobbal it is still not working but when i search thissoupfindallhrefrecompilerawlink hreffcwsiteincludestylesmaincss relstylesheet typetextcss link relshortcut icon typeimageico hreffcwsiteincludemain faviconico a hrefcareersnorthamericanorth americaa a hrefcareersmiddleeastafricamiddle east africaa a hrefcareerseuropeeuropea a hrefcareerslatinamericalatin americaa a hrefcareersasiaasiaa a hrefdiversitymanagerdiversity directorait returns all the links with second character a but not the lawyer names so for some reason those links such as cabel are not visible to beautifulsoup i do not understand why,['python'] +36332,what do xxprintgc and xxprintgcdetails flags do i found the jvm flags here is there a more detailed explaination of what exactly they do,['java'] +36340,whats an easy way to implement a quiet option in a python script am working on a command line python script throughout the script i have a lot of information i am printing to the terminal window so that i may follow along with what is happeningusing optionparser i want to add a quiet option so i can silence all the output i am looking for a pythonic way to go about implementing this throughout the script so that i do not end up doing something likeif not quiet global variable set by optionparser print my output am new to python and sure there is a better way ideas,['python'] +36357,lisp code called from java long storyi am doing a project for my functional programing class and i thought of writing an ai controller in lisp for the mario ai competitioni was looking over frameworkslibrariesways of calling lisp code from java or even better lispjava intercommunication i have looked at jacol but it is old and it does not compile fine for me my best choice so far is jathait is really neat although some lisp constructs are not yet implemented one can easily define his own constructs for example mapcar and cond are not implementedi have implemented my own mapcar named mapp in lisp like thisdefun map f l r if null l r map f rest l cons funcall f first l rdefun mapp f l reverse map f l nilnow i have a simple function that uses this for example a function that numbers how many atoms there are in a nonlinear listdefun myfunc l if atom l 1 apply mapp myfunc l myfunc 6 2this all works fine in clispnow to call lisp code from java i used jatha all one has to do is import the jatha library in the java project and load a lisp file like this eximport orgjathaimport orgjathadynatypepublic class main public static void mainstring args jatha lisp new jathafalse false lispinit lispstart lispvalue file lispmakestringxlispprojecttest1lisp lispvalue rez1 lisploadfile while that code works fine in clisp and other implementations this code produces a stackoverflowrunapply fn args 1 1s quote 1 quote 1exception in thread main javalangstackoverflowerror at javalanglongtostringlongjava242 at javalanglongtostringlongjava100 at javalangstringvalueofstringjava2946 at orgjathadynatypestandardlispintegertostringstandardlispintegerjava113 at orgjathadynatypestandardlispconstostringstandardlispconsjava152 at orgjathadynatypestandardlispconstostringascdr internalstandardlispconsjava174 at orgjathadynatypestandardlispconstostringstandardlispconsjava153 at orgjathadynatypestandardlispconstostringascdr internalstandardlispconsjava174 at orgjathadynatypestandardlispconstostringstandardlispconsjava153 at orgjathadynatypestandardlispconstostringascdr internalstandardlispconsjava174 at orgjathadynatypestandardlispconstostringstandardlispconsjava153 at orgjathadynatypestandardlispconstostringstandardlispconsjava152 at orgjathadynatypestandardlispconstostringstandardlispconsjava152 at orgjathadynatypestandardlispconstostringascdr internalstandardlispconsjava174 at orgjathadynatypestandardlispconstostringstandardlispconsjava153 at orgjathadynatypestandardlispconstostringstandardlispconsjava152 at orgjathadynatypestandardlispconstostringascdr internalstandardlispconsjava174 at orgjathadynatypestandardlispconstostringstandardlispconsjava153 at orgjathadynatypestandardlispconstostringstandardlispconsjava152 at orgjathadynatypestandardlispconstostringascdr internalstandardlispconsjava174 at orgjathadynatypestandardlispconstostringstandardlispconsjava153 at orgjathadynatypestandardlispconstostringstandardlispconsjava152 at orgjathadynatypestandardlispconstostringascdr internalstandardlispconsjava174 at orgjathadynatypestandardlispconstostringstandardlispconsjava153 at orgjathadynatypestandardlispconstostringstandardlispconsjava152 at orgjathadynatypestandardlispconstostringascdr internalstandardlispconsjava174 at orgjathadynatypestandardlispconstostringstandardlispconsjava153 at orgjathadynatypestandardlispconstostringstandardlispconsjava152 at orgjathadynatypestandardlispconstostringascdr internalstandardlispconsjava174 at orgjathadynatypestandardlispconstostringstandardlispconsjava153 at orgjathadynatypestandardlispconstostringstandardlispconsjava152 at orgjathadynatypestandardlispconstostringascdr internalstandardlispconsjava17so my question is why does it do this is my code wrong is it a bug in jatha see for yourself it does not take long to set up have you ever done something similardo you know any other better ways to do this all i want is to call from java some lisp code get it executed and get back results computed by the lisp code thanksedit fixed code pasted something wrong,['java'] +36358,is it possible to overuse late static binding in php starting with version 53 php supports late binding for static methods while it is an undoubtedly useful feature there are only several cases where its use is really necessary eg the active record pattern consider these examples1 convenience constructors createclass simpleobject public function construct public static function create return new static or return new self if this class may be extended however it is not extended by any class in the same package should late static binding be used just to make extending it easier without having to rewrite the create method and more importantly without having to remember to do thatnote this idiom is used to work around the impossibility to call methods on just constructed objects new simpleobjectdostuff is invalid in php 2 class constantsclass tagmatcher const tag pattern azi private subject public function constructsubject thissubject subject public function getalltags pattern statictag pattern preg match allpattern thissubject return pattern1 the reason to use static in this example is similar to the previous one it is used just because this class can be made to match differently formed tags just by extending it and overriding the constantso to wrap it all up are these uses and similar ones of late static binding are an overkill is there any noticeable performance hit also does frequent use of late binding reduce the overall performance boost given by opcode caches,['php'] +36361,is there a way to force a classloader to load a package even if none of its classes have been loaded let us say a java codebase has a package called comexampleat runtime we can get this package by callingpackage p packagegetpackage comexample returns nullor even get a list of all packages by callingpackages ps packagegetpackagesthe problem is if the classloader has not yet loaded any class from the package it would not be available to these function calls we can force it to load the package by forceloading one of the classes in the package first like thisthisgetclassgetclassloaderloadclass comexamplesomeclass package p packagegetpackage comexample returns nonnullhowever this is hacky and requires knowing ahead of time the name of some class that belongs to the packageso the question is is there any way to get an instance of package by name regardless of whether or not the classloader has done anything are my assumptions about how classloadingpackages seem to work in this situation accurate,['java'] +36368,why does csvwriterwriterow put a comma after each character this code opens the url and appends the names at the end and opens the page and prints the string to test1csvimport urllib2import reimport csvurl bios uname1 uname2 uname3csvwriter csvwriteropentest1csv afor l in bios openthislink url l response urllib2urlopenopenthislink html responseread item researchjdd html if item jd itemgroup csvwriterwriterowjd else nojd nojd csvwriterwriterownojdbut i get this resultjd columbia law schoolif i change the string to jd columbia law school then i get jd columbia law schooli could not find in the documentation how to specify the delimeter if i try to use delimenter i get this errortypeerror delimeter is an invalid keyword argument for this functionthanks for the help,['python'] +36372,embedded prolog interpretercompiler for java i am working on an application in java that needs to do some complex logic rule deductions as part of its functionality i would like to code my logic deductions in prolog or some other logicconstraint programming language instead of java as i believe the resulting code will be significantly simpler and more maintainablei googled for embedded java implementations on prolog and found number of them each with very little documentation my modest selection criteria areshould be embeddable in java eg can be bundled up with my java package instead of requiring any native installations on external programssimple interface to use from java for initiating deductions inspecting results and adding rulescome with at least a few examples on how to use itdoes not necessarily have to be prolog but other logicconstraint programming languages with the above criteria would suit my needs toowhat choices do i have and what are their advantages and thisadvantages,['java'] +36378,convert list to list while we can inherit from base classinterface why cannot we declare a listusing same classinterface interface a class b a class c b class test static void mainstring args a a new c ok lista listofa new listc compiler error is there a way around,['c#'] +36383,clicking a link when enter key is pressed using jquery i am trying to make it so when a user is in a text box and they press enter it is the same as clicking the link in which case it should take them to another page heres what i have and it does not work the codejquery documentreadyfunction if focus is in the input box drivingschoolinput drivingschoolinputliveclick function if enter key is pressedifekeycode 13 click the button and go to next pagebutton1click the markupform div classformdiv label forcitysearch by driving schoollabel span classinputboxinput typetext namecity classinput iddrivingschoolinput span div h4 clasubmitbuttona hrefschoolhtml idbutton1submitah4 form,"['javascript', 'jquery']" +36399,regular expression to remove a files extension i am in need of a regular expression that can remove the extension of a filename returning only the name of the filehere are some examples of inputs and outputsmyfilepng myfilemyfilepngjpg myfilepngi can obviously do this manually ie removing everything from the last dot but i am sure that there is a regular expression that can do this by itselfjust for the record i am doing this in javascript,['javascript'] +36402,sql server how do you remove punctuation from a field any one know a good way to remove punctuation from a field in sql serveri am thinkingupdate tblmytable set fieldname replacereplacereplacefieldname but it seems a bit tedious when i intend on removing a large number of different characters for example thanks in advance,['sql'] +36407,how to control positioning of jqueryui datepicker the datepicker in jqueryui renders with a dynamic position it renders according to its css if there is enough room for it but if there is not enough window space it tries to render on screen i need it to stay put and render in the same place every time independent of the screen position or other circumstances how can this be done with the jqueryui datepicker other implementations of jquery datepicker seem to have ways of doing this but i do not see a way of doing it for the ui version the answer does not seem to be just modifying the cssuidatepicker width 17em padding 2em 2em 0 trying topmargintoppositionrelative etc heresince when the datepicker is created it dynamically creates top and left in element style have not found a way around this yet one approach i saw is to give something like this in the beforeshow optionbeforeshow functioninputinst instdpdivcss top inputoffsetheight px leftinputoffsetwidth inputwidth px this has some effect but the top and left properties are still being dynamically set after this is run when the datepicker renders it is still trying to render on screen how do i get it to always render in the same spot my next step is probably to go into the datepicker guts and start pulling things out any ideasnote that the answer for the ui version is not inhowtochangethepopuppositionofthejquerydatepickercontrolchangethepositionofjqueryuidatepicker,['jquery'] +36428,return index of all occurances of a character in a string in ruby i am trying to return the indexs to all occurrences of a specific character in a string using ruby a example string is aasgsdfgd and the expected return is 15101213 when seaching for characters the following code does the job but there must be a simpler way of doing thisdef occurances line index 0 all index lineeach byte do x if x 0 then all index index end index 1 end all indexend,['ruby'] +36433,generate odtdocx and convert to pdf without oms i have a wsgi application that generates invoices and stores them as pdfso far i have solved similar problems with fpdf or equivalents generating the pdf from scratch like a gui sadly this means the entire formatting logic positioning headers footers and content styling is in the application where it really should not beas the templates already exist in office formats odt doc docx i would prefer to simply use those as a basis and fill in the actual content i have found the appy framework which does pretty much that with annotated odt filesthat still leaves the bigger problem open tho converting odt or doc or docx to pdf on a server running linux without gui libraries and thus without o or ms officeis this at all possible or am i better off keeping the styling in my codethe actual content that would be filled in is actually quite restricted a few paragraphs some of which may be optional a headline or two always at the same place and a few rows of a table in html this would be trivialedit basically i want a library that can generate odt files from odf files acting as templates and a library that can convert the result into pdf which is probably the crux,['python'] +36435,error unable to start debugging on the web server aspnet 40 i am getting an error when i want to create a web site on iis server i am using windows 7 and visual studio 2010 do i have to register or configure aspnet 40 for the iis,['asp.net'] +36442,python exists a function that is called when an object does not implement a function in smalltalk there is a message doesnotunderstand that is called when an object does not understand a message this is when the object does not have the message sent implemented so i like to know if in python there is a function that does the same thingin this exampleclass myobject def init self print myobject createdanobject myobject prints myobject createdanobjectdosomething raise an exceptionso can i add a method to myobject so i can know when dosomething is intented to be calledps sorry for my poor english,['python'] +36452,sql script to create insert script a bit of a vague title i will explaini am writing an sql script to create an insert statement for each row of a table in my database purely to be able to apply that data back to another databasehere is what i have at the momentselect insert into products idnamedescription values idnamedescription from productsand it works great outputting thisinsert into products idnamedescription values 1loremipsuminsert into products idnamedescription values 2loremipsuminsert into products idnamedescription values 3loremipsuminsert into products idnamedescription values 4loremipsumthe problem is if one of the fields is empty that row will fail to produce an update script in the output file the line is just blank obviously as there are 20 fields some optional this means that hardly any of my scripts are generatedis there a way to solve this issue,['sql'] +36473,peer to peer file transfer c hey i have been looking on google and i cannot seem to find anything about peer to peer transferbasically i want to be able to send a file from my computer to someone elses computer does anyone know of any guides that can help me with thisthanks,['c#'] +36485,what is the javascript operator and how do you use it i was looking at code from mozilla that add a filter method to array and it had a line of code that confused mevar len thislength 0i have never seen used in javascript before what is it and what does it do,['javascript'] +36491,yahoo weather api woeid retrieval i am creating an app php that takes yahoo weather data from the free rss feed and correlates it with a colour hex based on data retrieved from the rss feed the issue i am having is finding a way to grab the location code or woeid without doing it manuallyyahoos api sends back an rss feed as long as you provide a woeid is there an ethical way of doing this my beginner knowledge tells me i have to write a script that would search yahoo using the term and grab the first woeid but i would assume yahoo does not want scripts doing this and it seems overcomplicated if not are there any alternative apis that would make this easier on methanks,['php'] +36496,return an empty collection when linq where returns nothing i am using the below statement with the intent of getting all of the machine objects from the machinelist collection type ienumerable that have a machinestatus of i the machinelist collection will not always contain machines with a status of iat times when no machines have a machinestatus of i i would like to return an empty collection my call to activemachines which is used first works but inactivemachines does notpublic ienumerablemachine activemachines get return customermachinelist wherem mmachinestatus a public ienumerablemachine inactivemachines get return customermachinelist wherem mmachinestatus i editupon further examination it appears that any enumeration of machinelist will cause subsequent enumerations of machinelist to throw an exeception object reference not set to an instance of an objecttherefore it does not matter if a call is made to activemachines or inactivemachines as its an issue with the machinelist collection this is especially troubling because i can break calls to machinelist simply by enumerating it in a watch before it is called in code at its lowest level machinelist implements nhibernateiquery being returned as an ienumerable whats causing machinelist to lose its contents after an initial enumeration,['c#'] +36507,whats the best way to divide large files in python for multiprocessing i run across a lot of embarrassingly parallel projects i would like to parallelize with the multiprocessing module however they often involve reading in huge files greater than 2gb processing them line by line running basic calculations and then writing results whats the best way to split a file and process it using pythons multiprocessing module should queue or joinablequeue in multiprocessing be used or the queue module itself or should i map the file iterable over a pool of processes using multiprocessing i have experimented with these approaches but the overhead is immense in thistribution the data line by line i have settled on a lightweight pipefilters design by using cat file process1 outfile out1 numprocesses 2 process2 outfile out2 which passes a certain percentage of the first proces input directly to the second input see this post but i would like to have a solution contained entirely in python surprisingly the python documentation does not suggest a canonical way of doing this despite a lengthy section on programming guidelines in the multiprocessing documentationthanksvinceadditional information processing time per line varies some problems are fast and barely not io bound some are cpubound the cpu bound nondependent tasks will gain the post from parallelization such that even inefficient ways of assigning data to a processing function would still be beneficial in terms of wall clock timea prime example is a script that extracts fields from lines checks for a variety of bitwise flags and writes lines with certain flags to a new file in an entirely new format this seems like an io bound problem but when i ran it with my cheap concurrent version with pipes it was about 20 faster when i run it with pool and map or queue in multiprocessing it is always over 100 slower,['python'] +36525,how to serialize a derived class as its base class i have a derived class that adds only methods to a base class how can serialize the derived class so that it matches the serialization of the base classie the serialized xml of the derived class should look likebaseclass baseclassegthe following will throw an invalidoperationexceptionthe type derivedclass was not expected use the xmlinclude or soapinclude attribute to specify types that are not known staticallyclass baseclass class derivedclass baseclass derivedclass derived new derivedclastreamwriter stream new streamwriteroutput file pathxmlserializer serializer new xmlserializergettypebaseclaserializerstream derived,['.net'] +36562,c high precision time measurement in windows i am interested in measuring a specific point in time down to the nanosecond using c in windows is this possible if it is not is it possible to get the specific time in microseconds at least any library should do unless i suppose it is possible with managed codethanks,"['c++', 'c']" +36568,sql count and thistinct why cannot we use countthistinct in sql as in to count all thistinct rows,['sql'] +36589,android use webview to evaluate a javascript string and return the value given that scripting is not natively supported in android and wrapping libraries like javaxscriptscriptengine into your app will make it too large is it possible to send a javascript string to an invisible webview and have it evaluate the string and return you the results another stringi want to go this route because i want to save all my scripts to thisk so my app can remain smalledit i need java code to evaluate javascript strings not the other way around addjavascriptinterface does not help,['android'] +36595,how to unit test the default case of an enum based switch statement i have a switch statement in a factory that returns a command based on the value of the enum passed in something likepublic icommand createenumtype enumtype switch enumtype caseenumtypeval1 return new somecommand caseenumtypeval2 return new somecommand caseenumtypeval3 return new somecommand default throw new argumentoutofrangeexceptionunknown enumtype enumtype i currently have a switch case for each value in the enum i have unit tests for each of these cases how do i unit test that the default case throws an error obviously at the moment i cannot pass in an unknown enumtype but whos to say this would not be changed in the future is there anyway i can extend or mock the enumtype purely for the sake of the unit test,['c#'] +36612,apply css to jquery dialog buttons so i currently have a jquery dialog with two buttons save and close i create the dialog using the code belowdialogdivdialogautoopen falsemodal truewidth 600resizable falsebuttons cancel function cancel code heresave function save code hereclose function close code here incidentally same as cancel codehowever both buttons are the same color when this code is used i would like my cancel button to be a different color than my save is there a way to do this using some built in jquery options i did not get much help from the documentationnote that the cancel button i am creating is a predefined type but save i am defining myself not sure if that will have any bearing on the issueany help would be appreciated thanksupdate consensus was that there were two roads to travel hereinspect the html using a firefoxplugin like firebug and notethe css classes that jquery isapplying to the buttons and take astab at overriding them note inmy html both buttons were used theexact same css classes and no uniqueids so this option was outuse a jquery selector on dialog opento catch the button that i wantedand add a css class to it theni went with the second option and used the jquery find method as i think this is more appropriate than using first or firstchild bc the button that i wanted to change was not necessarily the first button listed in the markup using find i can just specify the name of the button and add css that way the code i ended up with is belowdialogdivdialogautoopen falsemodal truewidth 600resizable falsebuttons cancel function cancel code heresave function save code here open function uidialogbuttonpanefindbuttoncontainscanceladdclasscancelbuttonclass close function close code here incidentally same as cancel code,"['jquery', 'css']" +36626,portable equivalent to gccs attribute cleanup recently i came across a gcc extension that i have found rather useful attribute cleanupbasically this allows you to assign a cleanup call to a local variable at the time it exits scope for instance given the following section of code all memory must be maintained and handled explicitly in any and all cases within the call to foovoid foo char buff some memory allocation char buff2 0 buff3 0 if buff return else buff2 memory allocation if buff2 goto clean exit else and so on clean exit free buff free buff2 free buff3however by using the extension that can reduce to define clean pchar scope attribute cleanuppchar freevoid pchar free char c free c void foo char buff clean pchar scope some memory allocation char buff2 clean pchar scope 0 buff3 clean pchar scope 0 if buff return buff2 memory allocation if buff2 return and so on now all memory is reclaimed on the basis of scope without the use of nested ifelse or goto constructs coupled with a consolidated memory release section of the function i realize that the use of goto could be avoided there for a more nested ifelse construct so please no holy wars on the goto and that the example is contrived but the fact remains that this is can be quite a useful featureunfortunately as far as i know this is gccspecific i am interested in any portable ways to do the same thing if they even exist has anyone had experiences in doing this with something other than gcceditseems that portability is not in play considering that is there a way to do this outside of the gcc space it seems like to nice a feature to be gccspecific,['c'] +36647,solving a cubic equation as part of a program i am writing i need to solve a cubic equation exactly rather than using a numerical root finderax3 bx2 cx d 0i am trying to use the equations from here however consider the following code this is python but it is pretty generic codea 10b 00c 02 10d 07 02q 3ac b2 9 a2r 9abc 27a2d 2b3 54a3print q qprint r rdelta q3 r2print delta delta here delta is less than zero so we use the second set of equations from the articlerho q305 for x1 the imaginary part is unimportant since it cancels outs real rho13t real rho13print s real s realprint t real t realx1 s real t real b 3 aprint x1 x1print should be zero ax13bx12cx1dbut the output isq 0267r 007delta 0014062962963s real 05163979494t real 05163979494x1 1032795899should be zero 0135412149064so the output is not zero and so x1 is not actually a solution is there a mistake in the wikipedia articleps i know that numpyroots will solve this kind of equation but i need to do this for millions of equations and so i need to implement this to work on arrays of coefficients,['python'] +36664,jquery scrolltop does not seem to work in safari or chrome windows i have got a simple setup to allow a helpstyle window to be loaded and scrolled to a particular point on the page more or less the code looks like thisvar target code targetoffsetparentscrolltoptargetoffsettop fudgevaluethe target of the scroll and the fudge value are determined by a couple of hints dropped on the page and i am having no problems with that part of this mechanism anywhere in firefox and ie8 the above code works exactly like i want the scrolled box in this case the page body correctly scrolls the contained stuff to the right point in the window when it is told to do soin chrome and safari however the call to scrolltop apparently does nothing at all all the numbers are ok and the target refers to the right thing and the offsetparent is indeed the body element but nothing at all happens as far as i can tell from googling around this is supposed to work is there something funny about the renderer under safari and chromethis is jquery 132 if that matterstest page,"['javascript', 'jquery']" +36669,how can i apply multithreading to the backpropagation neural network training for my university project i am creating a neural network that can classify the likelihood that a credit card transaction is fraudulent or not i am training with backpropagation i am writing this in java i would like to apply multithreading because my computer is a quadcore i7 it bugs me to spend hours training and see most of my cores idlebut how would i apply multithreading to backpropagation backprop works by adjusting the errors backwards through the network one layer must be done before the other can continue is there any way that i can modify my program to do multicore backdrop,['java'] +36684,advantages thisadvantages of pconnect option in codeigniter one of the parameters in the codeigniter database config is the following pconnect truefalse whether to use a persistent connectionwhat do you recommend i set this tois there a significant performance hit if i set it to falsewhat potential problems might arise from setting it to true,['php'] +36695,static variable initialization i want to know why exactly static variables in c c and java are initialized by zero by default and why this is not true for local variables,"['java', 'c++', 'c']" +36697,python time comparison how do i compare times in pythoni see that date comparisons can be done and there is also timedelta but i am struggling to find out how to check if the current time from datetimenow is earlier the same or later than a specified time eg 8am regardless of the date,['python'] +36698,is there a way to mount android img to access the avd android virtual device contents i feel a bit blind developing on an emulator for android and not being able to see the file system on the avd imgis there a way to mount it in windows or linux so that i could at least see the file listing and maybe contentsbonus if it is mounted with write permissions as wellthank you,['android'] +36701,get namespace in a static function in an instance method i can easily find the executing namespacepublic void printnamespace consolewritelinethisgettypenamespaceq how do i do the same in a static function no this available without explicitely mentioning the class name no typeofmyclass,['.net'] +36707,how to add a panel to splitcontainer i am using splitcontainer and it contains only 2 panels but i need 3panelsquestionsis it possible to add more panels to splitcontainerif yes how else why notthanks,['c#'] +36719,byte code to java is it possible to convert a class file to java file if yes then how what about the correctness of the code extracted from this option,['java'] +36731,android id naming convention lower case with underscore vs camel case i am currently programming an application for the android now what i found out is that you cannot place resource objects say an image in the drawable folder and name it like mytestimagejpg this will give you a compiler error since camel case syntax is not allowed so youd have to rename it like my test imagejpgbut what about ids you define in the xml file say you have the following definitiontextview androidididmytextviewfirstname androidlayout widthwrap content androidlayout heightwrap content androidtextfirstname this is a valid definition compiles and works just fine on my android emulator although as you see i am specifying the id in camel case syntaxnow the android samples always use lower case and underscore is this just a naming convention to use lower case with underscore for the ids or may it cause problems on the real devicethx,['android'] +36747,why should not i use unity i am using the unity ioc container it really was not a decision i made it just came with prism and i have just stuck with it i have never used any other ioc frameworks and i must admit i am quite happy with unity however the satisfaction may come from ignorance as i do not really know what the other frameworks have got to offeri keep hearing that i should not use the unity ioc container use castle ninject or structuremap instead people are saying but i still have not heard any concrete arguments or examples to why i should use a different framework so why should not i use unity or maybe i should,['.net'] +36749,is using eval in python a bad practice i am using the following class to easily store data of my songsclass song the class to store the details of each song attstostorename artist album genre location def init self for att in selfattstostore exec selfsnoneattlower in locals def setdetailself key val if key in selfattstostore exec selfsvalkeylower in localsi feel that this is just much more extensible than writing out an ifelse block however eval seems to be considered a bad practice and unsafe to use if so can anyone explain to me why and show me a better way of defining the above class,['python'] +36757,how to get php get array is it possible to have a value in get as an arrayif i am trying to send a link with httplinkfoophpid1id2id3 and i want to use getid on the php side how can that value be an array because right now echo getid is returning 3 its the last id which is in the header link any suggestions,['php'] +36758,under what conditions it is good to have a partial class when does it become a good idea to have your class separate into two cs and have it as a partial classare there some signs showing that it is time to go with partial classthanks,['c#'] +36760,in sql server change column of type int to type text i would like to change a column in sql server from type int to type text while maintaining the column name the table with this column has lots of data and i do not want to lose it sql server does not seem to support implicit or explicit casts from int to text otherwise this would be pretty simple so how would you do it using only sql,['sql'] +36761,why cannot nullables be declared const testclasspublic class msprojectintegration const int projectid null the type int cannot be declared const why cannot i have a const intedit the reason i wanted a nullable int as a const is because i am just using it for loading some sample data from a database if it is null i was just going to initialize sample data at runtime it is a really quick test project and obviously i could use 0 or 1 but int just felt like the right data structure for what i wanted to do readonly seems like the way to go,['c#'] +36762,connection string with relative path to the database file i load data from sdf database in winforms app i use full path to the database file example conn new sqlceconnectionconnectionstring data sourcefmy documentsproject1bindebugdatabasesdfi d like use a relative path to the database file for example i have sdf file in folder fmy documentsproject1bindebugdatafilesdf and i want use relative path in connection string any advice thank you,['c#'] +36764,setting source port on a java socket i am very new to socket programmingis it possible to explicitly set the the source port on a java socket i am working on a clientserver application in which clients could potentially be listening for replies from the server on several ports it would be nice if i could set this reply port on the client side when initializing the socket so that the server would be able to determine which port to reply to on the other side,['java'] +36768,timespanparse time format hhmmss in c i have time in format hhmmss like 124510 for 124510 and i need to know the the totalseconds i used the timespanparse124510totalseconds but it doesnt take the format hhmmss any nice way to convert this,['c#'] +36776,any tutorials on how to use phpdocumentor i want to start using phpdocumentor but i am finding it hard going the web interface is not playing nicely and i cannot get it to parse the example files i probably have not set it up right and i would like a nice stepbystep tutorial ie not this one to check where i have gone wrong and hopefully get it parsing somethingbut i cannot find anything via google can anyone suggest any good tutorials or resources for getting started with phpdocmany thanksianedit thanks for jumping in ashnazg these were the steps i followedpear was not working on my mac so downloaded version 143 and unzipped it to a directoryspecified the absolute path to sample file 2 on my hd under file tabspecified an output folder which was world writableclicked create stuff going on in log media folder created but no report log concludes error nothing parsedi since got pear working and installed phpdoc that way can use it through the command line but any ideas about what could be up with the web interface to prevent it from parsing the file seems to be happy in all other respectsedit 2 thanks for the link to the developercom article liz it is very basic but a useful quickstart,['php'] +36793,python powershell or other what are the advantages of python powershell and other scripting environments we would like to standardize our scripting and are currently using bat and cmd files as the standard i think python would be a better option than these but am also researching powershell and other scripting toolsthe scripts would be used to trigger processes such as wget etc to call web services or other applicationstools that need to run in a specific order with specific parameterswe primarily work with the windows stack but there is a good chance we will need to support unix in the futurethanks,['python'] +36794,releasing a com object reference safely from net i have read a lot of articles on the net about releasing rcws safely and it seems to me that no one can agree on exactly what needs to be done in what order so i am asking you guys for your opinions for example one could do thisobject target nulltry instantiate and use the target object assume we know what we are doing the contents of this try block do in fact represent the entire desired lifetime of the com object and we are releasing all rcws in reverse order of acquisition finally iftarget null marshalfinalreleasecomobjecttarget target null gccollect gcwaitforpendingfinalizers however some people advocate doing the garbage collection before marshalfinalreleasecomobject some after and some not at all is it really necessary to gc every single rcw manually especially after it has already been detached from its com objectto my mind it would be simpler and easier to just detach the rcw from the com object and leave the rcw to expire naturallyobject target nulltry same content as above finally iftarget null marshalfinalreleasecomobjecttarget is it sufficient to do that,['.net'] +36800,properly converting nsstring to cgfloat nsinteger etc i have a question about safely or properly converting an nsstring into types such as cgfloat and nsinteger considering that these are simply wrapper types that apple created to use different primitives depending on certain factors eg nsinteger is typedefd to int on 32bit architectures and long on 64bit architecturesfor example i know i can use something like somestring intvalue or somestring longvalue but how do i instead say that i want somestring to become an nsinteger allowing the precision of the underlying primitive to be chosen by the compiler saying something like nsinteger integer somestring intvalue would result in data loss if somestring was created from an nsinteger on a 64bit system right whats the best way to deal with this situation,['objective-c'] +36802,sql server slow select from large table i have a table with about 20 million recordsstructure is likeeventid uniqueidentifiersourceuserid uniqueidentifierdestinationuserid uniqueidentifiercreatedat datetimetypeid intmetaid inttable is receiving about 100k records each dayi have indexes on each column except metaid as it is not used in where clausesthe problem is when i want to pick up eg latest 100 records for desired sourceuseridquery sometimes takes up to 4 minutes to execute which is not acceptableegselect top 100 from events with nolockwhere sourceuserid 15b534b175a5a415a9fc07565199c3461and typeid in 2 3 4 or typeid 60 and srcmemberid dstmemberidorder by createdat desci cannot do partitioning etc as i am using standard version of sql server and enterprise is too expensivei also think that the table is quite small to be that slow i think the problem is with order by clause as db must go through much bigger set of dataany ideas how to make it quicker perhaps relational database is not a good idea for that kind of datadata is always being picked up ordered by createdat descthank you for readingpablox,['sql'] +36804,can i have a uibarbuttonitem with a colored image i have an image that i want to thisplay on a uibarbuttonitem but for some reason it only shows the outline of it and the rest is all white how can i have it actually thisplay the imagethanks,"['iphone', 'objective-c']" +36809,byte order mark screws up file reading in java i am trying to read csv files using java some of the files may have a byte order mark in the beginning but not all when present the byte order gets read along with the rest of the first line thus causing problems with string comparesis there an easy way to skip the byte order mark when it is presentthanks,['java'] +36810,jquery changing css class to div if i have one div element for example and class first is defined with many css properties can i assign css class second which also has many properties differently defined to this same div just on some event without writing each property in line,"['jquery', 'css', 'html']" +36827,can i develop for net framework 4 in visual studio 2008 my aspnet application runs in iis on my web server and uses microsoft net framework 4 beta 2 its application pool is set to net framework version net framework v4021006it gives this new errora potentially dangerous requestform value was detected from the clientthis is due to a breaking change in net 4to revert to the behavior of the aspnet 20 request validation feature i added the following setting in the webconfig filehttpruntime requestvalidationmode20 now visual studio 2008 throws a compiletime errorthe requestvalidationmode attribute is not declaredand i can no longer debug on my development machine using the aspnet development server that comes with visual studioi need visual studio and its aspnet development server to recognize the new net framework 4 requestvalidationmode attributehow can i debug my application in net 4 must i switch from visual studio 2008 to visual studio 2010 beta 2,"['.net', 'asp.net']" +36837,jquery flot dataaxis labels on top of graph is there a way to overlay the xaxis and yaxis numeric labels onto a jquery flot graph so i want the labels to not be outside next to the graph but on top of the graph itselfthe following example creates an overlay div on top of the graph for the annotationsis there a straightforward way of grabbing the text and formatting of an axis from within flot and creating such an overlay out of it or is there maybe another better way of overlaying the axis labels on top of the graph,['jquery'] +36843,how to use a foreach loop but do something different on the last iteration this is probably a simple question but how do you iterate through an array doing something to each one until the last one and do something differenti have an array of names i want to output the list of names separated by commasjoe bob foobari do not want a comma at the end of the last name in the array nor if there is only one value in the array or noneupdate i cannot use implode because i have an array of user model objects where i get the name from each objectusers arrayusers new userforeach users as user echo username echo how can i achieve this and still use these objectsupdate i was worrying too much about how many lines of code i was putting in my view script so i decided to create a view helper instead heres what i ended up witharray arrayforeachusers as user array usernamenames implode array,['php'] +36877,what is internal representation of string in python 3x in python 3x a string consists of items of unicode ordinal see the quotation from the language reference below what is the internal representation of unicode string is it utf16the items of a string object are unicode code units a unicode code unit is represented by a string object of one item and can hold either a 16bit or 32bit value representing a unicode ordinal the maximum value for the ordinal is given in sysmaxunicode and depends on how python is configured at compile time surrogate pairs may be present in the unicode object and will be reported as two separate items,['python'] +36888,hibernate problems with auto increment id mysql 5 so i just stood up a spring hibernate app and i cannot seem to get my mapping file right i am using mysql 5 and an auto incrementing key here is the id portion of my mapping filehibernatemapping class nameorgxcontact tablecontact id nameid columnid typeint unsavedvaluenull generator classnative idhere is the sql generatedinsert into contact title first name middle name last name suffix job title dob passport number passport expiration employer dietary restrictions secondary contact fname secondary contact lname secondary contact mname secondary contact title secondary contact suffix secondary contact job title emergency contact name emergency contact phone emergency contact notes is company values here is the important part of the stack traceorghibernateassertionfailure null id in orgxcontact entry do not flush the session after an exception occursi have tried setting the unsavedvalue to 0 and 1 and sending them over the wire any ideas on what i am doing wrong,['mysql'] +36936,how to find the ip address of client connected to server my client pc is connected to as server pc via sockets over ethernet how do i find the ip of this client from the server side codethe server is thishing out one socket per client in a new threadwhen i do a csocketgetlocaladdresstostring on the client socket i still get the server ip address csocket is the socket that the server has spawned upon a now client connection and passed it to a new thread,['java'] +36938,what is difference between null and empty in mysql what is difference between null and empty string in mysql how much storage space it will take for example in the user table name null how much space its take phone how much space its take,['mysql'] +36942,java warning using vectors unchecked call to adde offending bit of codevector moves new vectormovesaddnew integerxerrorconnectfourjava82 warning unchecked unchecked call to adde as a member of the raw type javautilvector movesaddnew integerxnot really sure how much info is needed for an error like this,['java'] +36948,algorithm to reduce image to rectangles i am attempting to create pretty large bitmaps in a c application 60x60 though most is transparent and need to draw them to a specific output api which only supports drawing rectanglesnow i am wondering if anyone has an algorithm to reduce a bitmap to a series of filled rectangles of similarlycolored bitmaps since drawing everything as a 1x1 rectangle is way too slow for this purpose for example a circle should be reduces to a large center rectangle while the rest of the circle is reduced to efficient rectangles the algorithm does not even need to be that fast since most of the time taken with my singlepixel method is by the looping through every rectangle on the api itself,['c#'] +36969,how can a windows service determine its servicename i have looked and could not find what should be a simple questionhow can a windows service determine the servicename for which it was startedi know the installation can hack at the registry and add a command line argument but logically that seems like it should be unnecessary hence this questioni am hoping to run multiple copies of a single binary more cleanly than the registry hackeditthis is written in c my apps main entry point does different things depending on command line argumentsinstall or uninstall the service the command line can provide a nondefaultservicename and can change the number of worker threadsrun as a commandline executable for debuggingrun as a windows service here it creates an instance of my servicebasederivedclass then calls systemserviceproceservicebaseruninstancecurrently the installation step appends the service name and thread count to the imagepath in the registry so the app can determine it is servicename,['c#'] +36970,how can i make a hover info bubble appear on mouseover in wpf i want to make bubble of text appear when the mouse is over a textblockthe following code is the closest i can get but it just injects text into textboxtext itself and changes the color i want to have a eg borderstackpaneltextblock above the original textblock floating on a different layer during mouseoverhow can i make a hover panel similar to a web experience with the acronym tagusing systemwindowsusing systemwindowscontrolsusing systemwindowsinputusing systemwindowsmedianamespace testhover29282 public partial class window1 window public window1 initializecomponent textblock tb new textblock tbtext test tbmouseenter new mouseeventhandlertb mouseenter tbmouseleave new mouseeventhandlertb mouseleave mainstackpanelchildrenaddtb void tb mouseleaveobject sender mouseeventargs e textblock tb sender as textblock tbbackground new solidcolorbrushcolorstransparent tbtext test void tb mouseenterobject sender mouseeventargs e textblock tb sender as textblock tbbackground new solidcolorbrushcolorsorange tbtext this should be in a popup bubble,['c#'] +36983,uiwebview didfinishloading fires multiple times i have some code that needs to run after the a uiwebview finishes loading a document for that i have set the uiwebviews delegate to my controller and implemented the webviewdidfinishloading methodthis gets called multiple times depending on the type of page to load i am not sure if it is because of ajax requests requests for images or maybe even iframesis there a way to tell that the main request has finished meaning the html is completely loadedor perhaps delay my code from firing until all of those events are done firing,"['iphone', 'ios', 'objective-c']" +36993,consume rest api from net i am trying to consume rest api from my net application this apis are all written in javai am asked to pass the authentication credentials vis http headers how can i pass these authentication credentials like date authorization and accept via http headers which class in net can i use to accomplish this task can anyone help me with thisall your help will be appreciatedajish,['.net'] +37000,defining exceptions that can be thrown from a toolkit api is there a bestpractice or industry standard for throwing exceptions from a toolkit apishould the user facing methods catch and wrap up exception in some sort of customexception so that users only have to worry about customexceptions coming out of the apior is the convention to just let those bubble upwere concerned with being able to document all possible exceptions our api methods might throw for example if our api method calls streamwrite which throws 4 or 5 exceptions wed have to document all of those in addition to other exceptions that other called methods might throwwe were thinking of doing something like thispublic void customerfacingapimethod try api functionality goes here catch exception e throw new customexceptione,"['c#', '.net']" +37004,any good javascript bbcode parser currently i am parsing bbcode server side but i would like to show a preview just like this site doesif i process the bbcode serverside using ajax it is a bit laggy so i thought doing it client side to just show the previewdo you guys know any bbcode parser written in javascript,['javascript'] +37021,javascript performance dom reflow google article could someone prove to me that the advice given here copied below regarding removing dom elements before altering them and then reinserting them is ever quicker by prove i would like to see some figures its great that they research this but i think the article is very weak without including specifics as to what the problem actually is and how the solution fixes is in terms of speed as the article title speeding up javascriptthe articleoutoftheflow dom manipulationthis pattern lets us create multiple elements and insert them into the dom triggering a single reflow it uses something called a documentfragment we create a documentfragment outside of the dom so it is outoftheflow we then create and add multiple elements to this finally we move all elements in the documentfragment to the dom but trigger a single reflowthe problemlet us make a function that changes the classname attribute for all anchors within an element we could do this by simply iterating through each anchor and updating their href attributes the problems is this can cause a reflow for each anchorfunction updateallanchorselement anchorclass var anchors elementgetelementsbytagnamea for var i 0 length anchorslength i length i anchorsiclassname anchorclass the solutionto solve this problem we can remove the element from the dom update all anchors and then insert the element back where it was to help achieve this we can write a reusable function that not only removes an element from the dom but also returns a function that will insert the element back into its original position remove an element and provide a function that inserts it into its original position param element element the element to be temporarily removed return function a function that inserts the element into its original position function removetoinsertlaterelement var parentnode elementparentnode var nextsibling elementnextsibling parentnoderemovechildelement return function if nextsibling parentnodeinsertbeforeelement nextsibling else parentnodeappendchildelement now we can use this function to update the anchors within an element that is outoftheflow and only trigger a reflow when we remove the element and when we insert the elementfunction updateallanchorselement anchorclass var insertfunction removetoinsertlaterelement var anchors elementgetelementsbytagnamea for var i 0 length anchorslength i length i anchorsiclassname anchorclass insertfunction,['javascript'] +37023,jquery handle fallback for failed ajax request can jquery provide a fallback for failed ajax calls this is my tryfunction update var requestok false getjsonurl function alertrequest successful requestok true if requestok alertrequest failed unfortunately even if the callback function of the getjson method is called i get the message request failed before the callback function has the opportunity to set the requestok variable i think it is because the code runs in parallel is there a way to handle such situations i thought about chaining or some way of waiting for the ajax request including its callback function but how does anyone know how to do that,['jquery'] +37024,c string to float i have this bit of code hereint i 0 streamreader re fileopentexttextfile1txt string input null while input rereadline null string sites inputsplit for int j 0 j siteslength j myarrayi j converttoint32sitesj i for int a 0 a 5 a for int j 0 j 5 j consolewritemyarraya j consolewriteline my problem is this line of codemyarrayi j converttoint32sitesjits getting converted to an int how do i convert it to a float,['c#'] +37030,what does list mean in java generics what does list mean does it mean simply a list of objects of unspecified typegoogling for the string returns nothing useful,['java'] +37044,activity history stack wrong upon first install on device edit updateas an update to the below problem i found the exact action which causes it to happendownload an apk from a url through the android browserinstall the appafter install the app gives you two choices open or doneif you choose open the quirky behavior described below startsif you choose done then launch the app from the app tray it works fineso it seems like this problem is caused by using the open button the browser provides you after installing the apki am experiencing an error in the history stack of applications upon first install i made a test app to demonstrate thisthe test app is simply two activities a and b activity a launches b that is all it does rest is wizard generated template code from eclipsewhen the user installs the app via web url apk and runs it for the first time i get an outoforder activity stackuser starts the app a is on top they make a launch b by clicking a button b is on top of the stack user hits the home screen button user returns to the app a is thisplayed instead of b user hits the back key b is shown user hits the back key again a is shown user hits the back key again home screen shown now the stack is clean and app behaves normally from now on is any one else seeing this this is almost exactly like this known bug however my users are not installing from eclipseqfirst2020ii can provide the test appsource if anyone wants to try this is the manifest which does not have any special customizations made to itactivity androidnameactivitya androidlabelactivitya intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilteractivityactivity androidnameactivityb androidlabelactivityb intentfilter action androidnameandroidintentactionview category androidnameandroidintentcategorydefault intentfilteractivityas far as i know this should definitely not be happening and works fine after you clear the history stack the first timethanks,['android'] +37063,php is not equal to and is not equalequal to i keep seeing variations of thisnot equalnot equal equalwhich one is the standard or do they have different meaningsi am guessing the latter also checks the value and the name if it is a string while theformer might just check the value only,['php'] +37068,cause google analytics log from nonweb application eg via webclient i would like to gather some stats about the usage of my application and since i already have web stats in google analytics i thought it would be cool if i could send a request from the app that causes a hit in analytics egappv10debugthis would allow me to see how often my app is starting up or whateveri had a look online and found some examples of people doing similar things some to workaroudn javascript being thisabled and others doing the same as me but none in c i translated the code over as best as i could but i have called it a few times a couple of days ago and nothing showed up in the logs send a hit to google analytics so we can track which versions are being usedrandom rnd new randomint cookie rndnext10 9string statsrequest utmgif utmwv43 utmn rndnext10 used only to stop browser caching utmhnmyhostcom hostname utmhidrandom utmr referer utmpappv04debugtest requested page utmacua1234567 google analytics id utmcc utma3d cookie 3b2b utmz3d cookie 3busing var client new webclient clientdownloaddatastatsrequestdoes anyone know what to do to make this work it would be even better if i could store the cookie in some way so that people are considered returning visitors when they run the app multiple times but that is less important,"['c#', '.net']" +37079,addition for bigdecimal i want to do some simple sums with some currency values expressed in bigdecimal type bigdecimal test new bigdecimal0systemoutprintlntesttestaddnew bigdecimal30systemoutprintlntesttestaddnew bigdecimal45systemoutprintlntestobviously i do not understand well the bigdecimal arithmetics see output behindtest0can anyone help me out,['java'] +37084,open session in view pattern i am asking this question given my chosen development frameworks of jpa hibernate implementation of spring and insert mvc framework here struts 1 struts 2 spring mvc stripesi have been thinking a bit about relationships in my entity layer for example i have an order entity that has many order lines i have set up my app so that it eagerly loads the order lines for every order do you think this is a lazy way to get around the lazy initialization problems that i would come across if i was to set the fetch strategy to falsethe way i see it i have the following alternatives when retrieving entities and their associationsuse the open session in view pattern to create the session on each request and commit the transaction before returning the responseimplement a dto data transfer object layer such that every dao query i execute returns the correctly initialized dto for my purposes i do not really like this option much because in my experience i have found that it creates a lot of boilerplate copying code and becomes messy to maintaindo not map any associations in jpa so that every query i execute returns only the entities i am interested in this will probably require me to have dtos anyway and will be a pain to maintain and i think defeats the purpose of having an orm in the first placeeagerly fetch all or most associations in the example above always fetch all order lines when i retrieve an order so my question is when and under what circumstances would you use which of these options do you always stick with one way of doing iti would ask a colleague but i think that if i even mentioned the term open session in view i would be greeted with blank stares what i am really looking for here is some advice from a senior or very experienced developerthanks guys,['java'] +37086,javascript documentcreateelement delete domelement if you create a element within a function likefunction makedomelement var createdelement documentcreateelementtextareaand you do not append it anywhere in the dom ie via appendchild functions does it still remain in memory so would you have to dofunction makedomelement var createdelement documentcreateelementtextarea delete createdelementi am just curious,"['javascript', 'html']" +37093,how can i make a float top with css i know that css only supports left and right values for the float property but is there a technique to implement a floating top i will try to explain i have the following codediv stylefloatleftdiv stylefloatleftdiv stylefloatleftwith this code every div is floated to left until the right limit of the page is reached i want to do the same thing but vertically so that every div is placed at the bottom of the previous one and then when the bottom limit of the page is reached a new column is created is there a way to do this using only css and maybe editing the html code,"['html', 'css']" +37096,how do i loop through a date range i am not even sure how to do this without using some horrible for loopcounter type solution heres the problemi am given two dates a start date and an end date and on a specified interval i need to take some action for example for every date between 3102009 on every third day until 3262009 i need to create an entry in a list so my inputs would bedatetime startdate 3102009datetime enddate 3262009int dayinterval 3and my output would be a list that has the following dates313200931620093192009320093252009so how the heck would i do something like this i thought about using a for loop that would iterate between every day in the range with a separate counter like soint count 0forint i 0 i n i count ifcount dayinterval take action count 0 but it seems like there could be a better way,"['c#', 'asp.net']" +37103,why is there a performance warning on cast pointer to bool extendsi thought i was being cool when i did something likebool hasparent return thisparentnode even with a bool cast the warning still does not go awaywhere thisparentnode is null when there is no parent nodebut i am gettingwarning c4800 node forcing value to bool true or false performance warningwhats the deal yo why is that a performance warning i thought it would be more efficient to not write something likebool hasparent if thisparentnode return true else return false but the second version generates no warnings and the compiler seems a lot happier which is faster though,['c++'] +37119,how to use console output in an aspnet environment i would like to print some traces during the requests processingbut when i make consolewritelinesomething in this environment nothing is shownwhat is missing what do i need to do in order to use console to print these traces,"['c#', 'asp.net']" +37123,how do you write unit tests for your java servlets what are the best practices to unit test java servlets by the way this is a topic in which i have some dificulty how do you unit test your java servlets,['java'] +37127,named pipe not found when using wcf netnamedpipebinding i am the developer of a wcf service my test clients work very well with it but when it comes to real clients using the same client proxy it fails the same wcf service works with nettcpbinding this error occurs only with netnamedpipebinding even with concurrencymode concurrencymodesinglehere is the exceptionthere was no endpoint listening at netpipelocalhostmyservice that could accept the message this is often caused by an incorrect address or soap action see innerexception if present for more detailsserver stack trace atsystemservicemodelchannelspipeconnectioninitiatorgetpipenameuri uri at systemservicemodelchannelsnamedpipeconnectionpoolregistrynamedpipeconnectionpoolgetpoolkeyendpointaddress address uri via at systemservicemodelchannelscommunicationpool2takeconnectionendpointaddress address uri via timespan timeout tkey key at systemservicemodelchannelsconnectionpoolhelperestablishconnectiontimespan timeout at systemservicemodelchannelsclientframingduplexsessionchannelonopentimespan timeout at systemservicemodelchannelscommunicationobjectopentimespan timeout at systemservicemodelchannelsservicechannelonopentimespan timeout at systemservicemodelchannelscommunicationobjectopentimespan timeout at systemservicemodelchannelsservicechannelcalloncemanagercalloncetimespan timeout calloncemanager cascade at systemservicemodelchannelsservicechannelensureopenedtimespan timeout at systemservicemodelchannelsservicechannelcallstring action boolean oneway proxyoperationruntime operation object ins object outs timespan timeout at systemservicemodelchannelsservicechannelproxyinvokeserviceimethodcallmessage methodcall proxyoperationruntime operation at systemservicemodelchannelsservicechannelproxyinvokeimessage messageexception rethrown at 0 at systemruntimeremotingproxiesrealproxyhandlereturnmessageimessage reqmsg imessage retmsg at systemruntimeremotingproxiesrealproxyprivateinvokemessagedata msgdata int32 type atinner exceptionpipeexception the pipe endpoint netpipelocalhostmyservice could not be found on your local machine,['.net'] +37137,net remoting singleton memory leak tcp marshal by reference i am using the simplest example of remoting that i could find sharing an object between a windows service and a windows forms program client running on the same machinethe service instantiates the object like thisserviceconfigremote new serviceconfigdataremoteserverchannel new tcpserverchannel9090channelservicesregisterchannelserverchannel falseremotingservicesmarshalthisserviceconfigremote serviceconfigdatathe client establishes a connection like thistcpclientchannel channel new tcpclientchannelchannelservicesregisterchannelchannel falseconfigdata serviceconfigdataremoteactivatorgetobjecttypeofserviceconfigdataremote tcplocalhost9090serviceconfigdatathe idea is for the service to be able to make changes to some of the parameters of the object for the client to be able to read those changes the object itself ispublic sealed class serviceconfigdataremote marshalbyrefobject private bool myconnectedflag private bool mysendingflag private bool myupdateflag private string myclientconfiguration static readonly serviceconfigdataremote instance new serviceconfigdataremote static serviceconfigdataremote public serviceconfigdataremote myconnectedflag false mysendingflag false myupdateflag false myclientconfiguration public static serviceconfigdataremote instance get return instance public override object initializelifetimeservice return null public bool connected get return myconnectedflag set myconnectedflag value public bool sending get return mysendingflag set mysendingflag value public bool checkforupdates getreturn myupdateflag set myupdateflag value public string clientconfiguration get return myclientconfiguration set myclientconfiguration value while the service is running by itself the mem usage in task manager stays constant even though the service is continually updating the object with status information when the client is started both begin to increase in mem usage and never go downthis is the problem that i referred to in my previous question about finding memory leaksit is appearing differently on different machines some show no memory increases but the machines that do will reliably reproduce this problem running net memory profiler shows that on the service there is an ever increasing number of new instances with only one or two removed in the tab typesresources where namespacesystem is kernel and nameresource is heapmemory i am still trying to learn how to use the memory profiler so i apologize if this is the wrong information and tip on where else i should be looking would also be appreciatedthis object is instantiated once with just a couple of parameters to read and write no file io no allocating of memory that i can see and yet my memory usage only appears to go up the moment i start a connection from the client to that object and read its values any and all input would be appreciated as i would like to avoid pulling this code and replacing it with named pipes or similar but i am quickly approaching that point as my only option,"['c#', '.net']" +37141,mvc aspnet design templates does anyone know of any good sites to download good design templates master pages css files for mvc projects or aspnet projects in general i have used the aspnet mvc gallery but the options there are pretty limited i am willing to pay for some if they are good,['asp.net'] +37145,c arguments for exceptions over return codes i am having a thiscussion about which way to go in a new c project i favor exceptions over return codes for exceptional cases only for the following reasons constructors cannot give a return codedecouples the failure path which should be very rare from the logical code which is cleanerfaster in the nonexceptional case no checking ifelse hundreds of thousands of timesif someone screws up the return code settings forgets to return fail it can take a very long time to track downbetter information from the message contained in the error it was pointed out to me that a return enum could do the same for error codesfrom jared par impossible to ignore without code to specifically designed to handle itthese are the points i have come up with from thinking about it and from google searches i must admit to being prethisposed to exceptions having worked in c for the past couple of years please post further reasons for using exceptions over return codes for those who prefer return codes i would also be willing to listen to your reasoning thanks,['c++'] +37152,should setting checkboxchecked false not clear the html attribute too heres my htmlinput idtest typecheckbox checkedheres a firebug excerpt testinput idtest typecheckbox checked testchecked falsefalse testinput idtest typecheckbox checkedumam i missing something or should that last line not read the followinginput idtest typecheckboxuiwise the checkbox does indeed uncheck when i execute the checked false lineanyway if there is some legitimate explanation for this then whats the proper way to uncheck a checkbox from javascript if not checked false,['javascript'] +37158,how to get the value of a filteringselect in dojo i am using dijitformfilteringselect to provide a way to select values from a select the problem is when using dojo the label is returned instead of the value of the sfor exampleselect nametest dojotypedijitformfilteringselect option value1oneoption option value2twooptionselectdojo is returning the literal one if that option is selected instead of the value for that option 1 the same is true for two and 2if dojo is removed from this element the value is returned as expected,"['javascript', 'html']" +37163,memory effects of synchronization in java jsr133 faq saysbut there is more to synchronization than mutual exclusion synchronization ensures that memory writes by a thread before or during a synchronized block are made visible in a predictable manner to other threads which synchronize on the same monitor after we exit a synchronized block we release the monitor which has the effect of flushing the cache to main memory so that writes made by this thread can be visible to other threads before we can enter a synchronized block we acquire the monitor which has the effect of invalidating the local processor cache so that variables will be reloaded from main memory we will then be able to see all of the writes made visible by the previous releasei also remember reading that on modern sun vms uncontended synchronizations are cheap i am a little confused by this claim consider code likeclass foo int x 1 int y 1 synchronized alock x x 1 updates to x need the synchronization but does the acquisition of the lock clear the value of y also from the cache i cannot imagine that to be the case because if it were true techniques like lock striping might not help alternatively can the jvm reliably analyze the code to ensure that y is not modified in another synchronized block using the same lock and hence not dump the value of y in cache when entering the synchronized block,['java'] +37170,objective reasons for using python or ruby for a new rest web api so this thread is definitely not a thread for why python is better than ruby or the inverse instead this thread is for objective criticism on why you would pick one over the other to write a restful web api that is going to be used by many different clients mobile web browsers tablets etcagain do not compare ruby on rails vs django this is not a web app that is dependent on high level frameworks such as ror or django i would just like to hear why someone might choose one over the other to write a restful web api that they had to start tomorrow completely from scratch and reasons they might go from one to anotherfor me syntax and language features are completely superfluous the both offer an abundant amount of features and certainly both can achieve the same exact end goals i think if someone flips a coin it is a good enough reason to use one over the other i would just love to see what some of you web service experts who are very passionate about their work respond to why they would use one over the other in a very objective format,"['python', 'ruby']" +37172,jquery implementation of facebooks modal box i was wondering if anyone knew of a jquery implementation of this mootools modal box i have seen facebox but it looks like the old facebook modal dialog layout and not the newer oneif there are not any available then an example of how to theme jquerys ui modal dialog to look like that would be really helpful the html output for the jquery ui modal dialog looks like thisdiv classuidialog uiwidget uiwidgetcontent uicornerall uidraggable uiresizable div classuidialogtitlebar uiwidgetheader uicornerall uihelperclearfix span iduidialogtitledialog classuidialogtitledialog titlespan a classuidialogtitlebarclose uicornerall hrefspan classuiicon uiiconclosethickclosespana div div styleheight 200px minheight 109px width auto classuidialogcontent uiwidgetcontent iddialog pcontentp divdiv,['jquery'] +37190,handling scroll event on listview in c i have a listview that generates thumbnail using a backgroundworker when the listview is being scrolled i want to pause the backgroundworker and get the current value of the scrolled area when the user stopped scrolling the listview resume the backgroundworker starting from the item according to the value of the scrolled area is it possible to handle scroll event of a listview if yes how if not then what is a good alternative according to what i described above,['c#'] +37192,sql server 2005charindex starting from the end i have a string somefilenamei want to grab somefileto do thati need to find the last occurrence of in a stringmy solution is declare somestr varchar20 declare reversedstr varchar20 declare index int set somestr 001002003 set reversedstr reversesomestr set index lensomestr charindexreversedstr select leftsomestrindexwellis not it too complicatedi was just intented to using somefile in a whereclauseanyone has a good idea,['sql'] +37195,why use a framework with php i am curious what are the advantages and thisadvantages on using a framework with phpi have been using php on and off since version 3 i have never used any of the frameworks available for php so what am i missing out on,['php'] +37197,lua equivalent to shlex is there a lua equivalent for pythons shlex library,['python'] +37203,introduction to gui programming with c i am new gui and programming as whole and so far i have a general understanding of c and have spent quite some time writing console applicationsi am trying to learn gui but have so far been unsuccessful i have tried learning wxwidgets through official documentation gtk through official documentation and win32 forgers win32 tutorial but still have not quite gotten therei still really want to but cannot seem to find any good material what would you recommend as start for a beginner,['c'] +37206,how to split string into a dictionary i have this stringstring sxcolorindex3fontfamilyhelveticafontbold1and am splitting it withstring sxsplitnew char stringsplitoptionsremoveemptyentriesinstead of that how could i split the result into a dictionarystringstring theresulting dictionary should look likekey valuecolorindex 3fontfamily helveticafontbold 1,['c#'] +37224,retrieve incoming calls phone number in android i would like to retrieve the incoming calls phonenumber and do something with it like the doin could you please help me because i cannot find any information about thiswhere do i start and how do i get hold of the phonenumberok so currently my code looks like below when i place the call the custombroadcastreceiver catches it and the log message is printed out i can retrieve the telephone number from the bundle but i cannot get hte customphonestatelistener to work as you can see i have registered my customphonestate listener to the receiver but the log message never gets printed out from the customphonestatelistener class what am i my missing hereis my thinking correct receiver androidnamecustombroadcastreceiver intentfilter action androidnameandroidintentactionphone state intentfilterreceiverapplicationusessdk androidminsdkversion5 usespermission androidnameandroidpermissioninternet usespermission androidnameandroidpermissionwrite contacts usespermission androidnameandroidpermissionread phone state public class customphonestatelistener extends phonestatelistener private static final string tag customphonestatelistenerpublic void oncallstatechangeint state string incomingnumber logvtag we are inside logvtag incomingnumber switchstate case telephonymanagercall state ringing logdtag ringing break public class custombroadcastreceiver extends broadcastreceiver private static final string tag custombroadcastreceiveroverridepublic void onreceivecontext context intent intent logvtag we are inside telephonymanager telephony telephonymanagercontextgetsystemservicecontexttelephony service customphonestatelistener customphonelistener new customphonestatelistener telephonylistencustomphonelistener phonestatelistenerlisten call state bundle bundle intentgetextras string phonenr bundlegetstringincoming number logvtag phonenr phonenr,['android'] +37247,c macrodefine indentation i am curious as to why i see nearly all c macros formatted like thisifndef foo define fooendifor thisifndef foodefine fooendifbut never thisifndef foo define fooendifmoreover vims operator only seems to count the first two as correctis this due to portability issues among compilers or is it just a standard practice,['c'] +37250,comparing two nsdates and ignoring the time component what is the most efficientrecommended way of comparing two nsdates i would like to be able to see if both dates are on the same day irrespective of the time and have started writing some code that uses the timeintervalsincedate method within the nsdate class and gets the integer of this value divided by the number of seconds in a day this seems long winded and i feel like i am missing something obviousthe code i am trying to fix isif key comparetodaysdate nsordereddescending todaysdatesection eventsectionsarray count 1where key and todaysdate are nsdate objects and todaysdate is creating usingnsdate todaysdate nsdate alloc initregardsdave,"['iphone', 'objective-c']" +37254,when should we use intern method of string on string constants according to stringintern intern method is supposed to return the string from the string pool if the string is found in string pool otherwise a new string object will be added in string pool and the reference of this string is returned so i tried this string s1 rakeshstring s2 rakeshstring s3 rakeshinternif s1 s2 systemoutprintlns1 and s2 are same 1if s1 s3 systemoutprintlns1 and s3 are same 2i was expecting that s1 and s3 are same will be printed as s3 is interned and s1 and s2 are same will not be printed but the result is both lines are printed so that means by default string constants are interned but if it is so then why do we need the intern method in other words when should we use this method,['java'] +37260,what is the best way to call java code from python i have a java class library 3rd party proprietary and i want my python script to call its functions i already have java code that uses this library what is the best way to achieve this,"['java', 'python']" +37287,how to integrate ckeditor into aspnet mvc saw this post at codeproject for fckeditor can someone explain what about the new version,['jquery'] +37297,origin of term reference as in passbyreference javac language lawyers like to say that their language passes references by value this would mean that a reference is an objectpointer which is copied when calling a functionmeanwhile in c and also in a more dynamic form in perl and php a reference is an alias to some other name or runtime value in the dynamic casei am interested in the etymology here what were early uses of the term reference lets go for prejava but if you know of prec uses that would also interest mei am aware that vocabulary changes etc but i am just interested in the history,"['c#', 'java', 'c++']" +37306,how can i create a custom pindrop animation using mkannotationview i have an instance of mkmapview and would like to use custom annotation icons instead of the standard pin icons supplied by mkpinannotationview so i have setup a subclass of mkannotationview called custommapannotation and am overriding voiddrawrect to draw a cgimage this worksthe trouble comes when i try to replicate the animatesdrop functionality supplied by mkpinannotationview i would love for my icons to appear gradually dropped from above and in lefttoright order when the annotations are added to the mkmapview instancehere is voiddrawrect for custommapannotation which works when you just draw the uiimage which is what the 2nd line does voiddrawrectcgrectrect super drawrectrect incident selfannotationsmallicon drawinrectrect if newannotation self animatedrop newannotation no the trouble comes when you add the animatedrop methodvoidanimatedrop cgcontextref mycontext uigraphicsgetcurrentcontext cgpoint finalpos selfcenter cgpoint startpos cgpointmakeselfcenterx selfcentery4800 selflayerposition startpos cabasicanimation theanimation theanimationcabasicanimation animationwithkeypathposition theanimationfromvaluensvalue valuewithcgpointstartpos theanimationtovaluensvalue valuewithcgpointfinalpos theanimationremovedoncompletion no theanimationfillmode kcafillmodeforwards theanimationdelegate self theanimationbegintime 50 selfcenterx3200 theanimationduration 10 selflayer addanimationtheanimation forkeyit just does not work and there could be a lot of reasons why i would not get into all of them now the main thing i am wanting to know is if the approach is sound at all or if i should try something entirely differenti tried also to package up the whole thing into an animation transaction so that the begintime parameter might actually work this seemed to not do anything at all i do not know if this is because i am missing some key point or whether it is because mapkit is trashing my animations somehow does nothing catransaction begin map addannotationslist catransaction commitif anyone has any experience with animated mkmapannotations like this i would love some hints otherwise if you can offer caanimation advice on the approach that would be great too,['iphone'] +37316,sparse assignment list in python i need a list with the following behavior l sparselist l l2 hello l none none hello l5none l4 22 l none none hello none 22 lenl5 for i in l print inonenonehellonone22although it can emulated via a dictionary it is not exactly the same numpy array can behave this way but i do not want to import the whole numpy for something like this before coding it myself i ask if something similar exists in the standard library,['python'] +37323,how do i compare two timestamps in c i am writing a socket program that maintains fifo queues for two input sockets when deciding which queue to service the program pulls the most recent timestamp from each queue i need a reliable method for comparing two timeval structs i tried using timercmp but my version of gcc does not support it and documentation states that the function is not posix compliantwhat should i do,['c'] +37325,how to prevent newlineline break within a this is my codeform namepublishphp include locationselectorhtml input typesubmit valuesubmit formwhen thisplayed there is a newline preceding the submitbutton how to eliminate this newlineline breakthe html content of locationselectorhtml istabletrtde12eaocae a aatdtda aocoae a aatdtrtrtd aligncenterselect namepref onchangechangepreftrueoption value99a a12option value0aeoption value1ecoption value2a2coption value3aacoption value4coption value5aa12coption value6ca3coption value7e acoption value8 coption value9c34ecoption value10a14ccoption value11aecoption value12aoe12option value13caacoption value1412coption value15a acoption value16c3acoption value17caocoption value18a coption value19eecoption value20a2ecoption value21ea2coption value22ccoption value23a ecoption value24e3coption value25aoe12aooption value26aeaaooption value27aaocoption value28ae coption value29aacoption value30e3acoption value31a3 1coption value32a2acoption value33aoa3coption value34aacoption value35a343a3coption value36eacoption value37aacoption value38eccoption value39ca2coption value40a12e3coption value41ea coption value42ccoption value43aacoption value44aa coption value45e1aa3coption value462c cselecttdtd aligncenterselect namecityoption value99 selecteda aaooption valueoption valueoption valueoption valueoption valueoption valueoption valueselecttdtrtable,"['html', 'css']" +37327,run java code online codepadorg allow you to run ccd etc code online but not java is there a site that i can use for java,['java'] +37329,how to detect whether my rails is running in migration or not in environmentrb any easy way to detect it i want to skip some codes in envirmonmentrb when doing migration rake,['ruby-on-rails'] +37346,set custom keyboard for android application i know that there is the possibility to set a special keyboard with these attributes but i need my own keyboard as default how can i do that how can my app change the settingsas an example let us say i want the example softkeyboard as default for my appis that even possible,['android'] +37361,hibernate criteria integer and like i am migrating some of my hqlstatements to criterias now i am figuring one problemthe entity property is type integer but i need a like with wildcards search so in hql i dosessioncreatequeryfrom p1 where id like idsetstringid sno problem at all hibernate casts string to integerif i try this in criteria i only get a classcastexceptionstring cannot be cast to integercriteria crit sessionfactorygetcurrentsessioncreatecriteriap1classcritaddrestrictionslikeidsaddorderorderascidsetmaxresultsmaxresultswhy does hibernate handle both situations differently,['java'] +37374,more detailed error from createfileatpath is there anyway to get more detailed error data back from createfileatpath i was kind of expecting an nserror currently i am using the bool return valuesuccess fileman createfileatpathfileonthisk contentsdbuffer attributesnilifsuccess yes nslogfilecreatedelse nslogerror failed to create file return 1gary,['objective-c'] +37384,changing parent windows url from iframe i have a situation where i have web apps on two different servers where app1 contains app2 in an iframe any links in app2 can have target parent attribute which allow those links to open in the top window however i cannot find any way to get the same behavior in javascript i found this page which claims that the child frame can call javascript on the parent frame using parentfoo but that does not seem to work in ie8 or ff35 i found this so question which explains how this security model works but it seems odd that i cannot do in javascript what i can do with a simple a tag is there any workaround to this at all i know about windowpostmessage but as far as i know this only works in firefoxexampleserver1testhtmlhtmlheadscript typetextjavascriptfunction mycallbackfoo alertfooscriptheadbodyiframe srchttpserver2test2htm width400 height150iframebodyhtmlserver2test2htmlhtmlbodyscriptfunction clickit parentdocumentlocation not allowed parentmycallback not allowedscriptpthis should be in an iframeppa href target parentnormal link worksappa hrefjavascriptclickitjavascript linkapbodyhtml,"['javascript', 'html']" +37385,interleaving multiple arrays into a single array i need to merge several arrays into a single array the best way to describe what i am looking for is interleaving the arrays into a single array for example take item one from array 1 and append to the final array get item one from array 2 and append to the final array get item two from array 1 and appendetcthe final array would look something like thisarray1element1array2element1the kicker is that the individual arrays can be of various lengths is there a better data structure to use,['php'] +37396,setpropertiestofetch does not seem to have any effect i am trying to use setpropertiestofetch in my fetch request to limit the data that is retrieved from my store but it seems to have no effect when i use it and thisplay the object returned into the console i can see all my properties are there the same data is thisplayed whether i set the properties or not all the relationships thisplay as faults but all the data for the attributes is therensfetchrequest fetchrequest nsfetchrequest alloc initnsentitydescription entity nsentitydescription entityfornameentity inmanagedobjectcontextcontextnsdictionary entityproperties entity propertiesbynamefetchrequest setentityentityfetchrequest setfetchbatchsize20fetchrequest setincludespendingchangesnofetchrequest setreturnsobjectsasfaultsnofetchrequest setpropertiestofetchnsarray arraywithobjectsentityproperties objectforkeymyattrib nilthe fetch seems to return the same data per object with or without that last line any ideas,['iphone'] +37399,jquery accordion opening a box based on href i am trying to open an accordion based on a link i send to the pagethis is my urlserviceshtmlbrandingi am using the following code in the head script typetextjavascript documentreadyfunction accordionaccordioncollapsible true animated slide autoheight false navigation true active false scriptand the accordion looks likediv idaccordionh3 idbrandinga hrefbrandingah3divpdoes your business have apdivh3a hrefprintprintah3divpbrochuresapdivdivany help would be greatly appreciated,['jquery'] +37408,two macs one iphone developer license possible i work for a company that is interested in building iphone apps however we are not clear on one issuedoes the iphone developer certificate work on more than one computer at a time,['iphone'] +37413,is there a java package to handle building urls what i am looking for specifically is some code in java that will take a map object and convert it into a query string that i can append to a url i return i am sure there is a library that does this and much more but i cannot find it with a quick google search anyone know of one that will do this,['java'] +37425,strip nonnumeric characters from string consider a nondom scenario where youd want to remove all nonnumeric characters from a string using javascriptecmascript any characters that are in range 0 9 should be keptvar mystring abc1238blahdesired output is 1238how would you achieve this in plain javascript please remember this is a nondom scenario so jquery and other solutions involving browser and keypress events are not suitable,['javascript'] +37433,how do i actually get somewhere in gui programming i am an undergraduate student i was exposed to basic programming couple of years back in school till now i have an understanding of core java core python and basic c and cevery time i start off with some gui programming so as i can start off with a project of mine i get boggled by the sheer amount which is to be done api to be learnt mvc architecture and everything programmers talk about event handling etc etcstudied awt and swings for a while tried my hands on qt and gtk could not find much of documentation tried to make sense of pygame i end up at the same place knowing the core languagetkinter on my zenwalk linux is broken so could never start it athough i own a book on python with tkinter explainedbut i end up at the same place with just the basic understanding of the languagewant to start over seriously now i would like to choose python how should i go about studying gui programmingi need some internet resources and direction so that i do not end up at the same place,['java'] +37436,how to update gui with backgroundworker i have spent the whole day trying to make my application use threads but with no luck i have read much documentation about it and i still get lots of errors so i hope you can help mei have one big time consuming method which calls the database and updates the gui this has to happen all the timeor about every 30 secondspublic class updatecontroller private usercontroller usercontroller public updatecontrollerlogincontroller logincontroller usercontroller usercontroller usercontroller usercontroller logincontrollerloginevent update public void update backgroundworker backgroundworker new backgroundworker whiletrue backgroundworkerdowork new doworkeventhandlerbackgroundworker dowork backgroundworkerrunworkerasync public void backgroundworker doworkobject sender doworkeventargs e usercontrollerupdateusersonmap with this approach i get an exception because the backgroundworker is not and sta threadbut from what i can understand this is what i should use i have tried with a sta thread and that gave other errorsi think the problem is because i try to update the gui while doing the database callin the background thread i should only be doing the database call and then somehow it should switch back to the main thread after the main thread has executed it should go back to the background thread and so on but i cannot see how to do thatthe application should update the gui right after the database call firering events do not seem to work the backgroundthread just enters them editsome really great answers this is the new codepublic class updatecontrollerprivate usercontroller usercontrollerprivate backgroundworker backgroundworkerpublic updatecontrollerlogincontroller logincontroller usercontroller usercontroller usercontroller usercontroller logincontrollerloginevent update backgroundworker new backgroundworker backgroundworkerdowork backgroundworker dowork backgroundworkerrunworkercompleted backgroundworker runworkercompletedpublic void backgroundworker progresschangedobject sender progresschangedeventargs e usercontrollerupdateusersonmappublic void update backgroundworkerrunworkerasyncvoid backgroundworker runworkercompletedobject sender runworkercompletedeventargs e ui update systemthreadingthreadsleep10 updatepublic void backgroundworker doworkobject sender doworkeventargs e big database taskbut how can i make this run every 10 second systemthreadingthreadsleep10 will just make my gui freeze and whiletrue loop in update as suggested gives an exceptionthread too busy,['c#'] +37439,how to make ruby aes256cbc and php mcrypt rijndael 128 play well together i am generating data to send from a ruby stack to a php stack i am using the opensslcipher library on the ruby side and the mcrypt library in php when i encrypt using aes256cbc 256bit block size in ruby i need to use mcrypt rijndael 128 128bit block size in php to decrypt it i suspect the ruby code that is broken because the cipheriv len is 16 i believe it should be 32 cipher opensslcipherciphernewaes128cbc opensslciphercipher0x3067c5c cipherkey len 16 cipheriv len 16 cipher opensslcipherciphernewaes256cbc opensslciphercipher0x306de18 cipherkey len 32 cipheriv len 16so heres my test on the ruby side first i generate the key and iv cipher opensslcipherciphernewaes256cbc cipherencrypt iv cipherrandom iv iv64 ivpackmstrip vckaypm5tpmtp3tf7awrug key cipherrandom key key64 keypackmstrip rivfgoi9xzahs0bp0j9wdrynd6z7jrd3btiafcq8y0then i use those keys to do the encryption plain data hi don this is a string cipher opensslcipherciphernewaes256cbc cipherencrypt cipherkey base64decode64key64 cipheriv base64decode64iv64 encrypted data cipherupdateplain data encrypted data cipherfinal crypt64 encrypted datapackmstrip 5gfckjcnav2fji0haxnlcdraikwgtu54uoznvxf8k0heres the php decryptionruby crypt 5gfckjcnav2fji0haxnlcdraikwgtu54uoznvxf8k0encrypted data base64 decoderuby cryptkey base64 decoderivfgoi9xzahs0bp0j9wdrynd6z7jrd3btiafcq8y0iv base64 decodevckaypm5tpmtp3tf7awrugresult mcrypt decryptmcrypt rijndael 128 key encrypted data mcrypt mode cbc ivunencrypt rtrimresult x00x1fprint nunencrypted tokennunencryptnresultunencrypted tokenhi don this is a stringi would prefer to use the longer block size clearly i am misunderstanding the apis help,"['php', 'ruby']" +37451,is there any xpath processor for sax model i am looking for an xpath evaluator that does not rebuild the whole dom document to look for the nodes of a document actually the object is to manage a large amount of xml data ideally over 2gb with sax model which is very good for memory management and give the possibility to search for nodesthank you all for the supportfor all those who say it is not possible i recently after asked the question found a project named saxpath but i cannot find any implementing project,['java'] +37457,is there any scenario where the rope data structure is more efficient than a string builder related to this question based on a comment of user eric lippertis there any scenario where the rope data structure is more efficient than a string builder it is some peoples opinion that rope data structures are almost never better in terms of speed than the native string or string builder operations in typical cases so i am curious to see realistic scenarios where indeed ropes are better,['c#'] +37467,php coding conventions where can i find php coding convention references for php coding standards,['php'] +37474,list of interfaces vs list of derived type cannot convert expression type to return type why does this workpublic ilisticoupon getcouponsforsitestring siteslug var coupons dbcouponswherex xsiteslug siteslug selectx new couponxid var list new listicoupon foreach var coupon in coupons listaddcoupon return listbut this does does not work error cannot convert expression type to return typepublic ilisticoupon getcouponsforsitestring siteslug return dbcouponswherex xsiteslug siteslug selectx new couponxidtolist,['c#'] +37488,part ii how to make ruby aes256cbc and php mcrypt rijndael 128 play well together this question is a continuation of my last one regarding how to make ruby aes256cbc and php mcrypt rijndael 128 play well together i have got that working now but i am still struggling to go the other direction the php generated cryptogram appears to have all the information that was provided but i cannot get the ruby code to decrypt it without errorheres the php code i am using to generate the cryptogramcleartext whos the clever boykey base64 decode6sewmgakdbk5fa2rr6vvwniv base64 decodevckaypm5tpmtp3tf7awrugcryptogram mcrypt encryptmcrypt rijndael 128 key cleartext mcrypt mode cbc ivresult base64 encodecryptogramprint nresultnresultjm0oxminptnf1vwxdi3xdki0klvx210cvpjllfjagmthen heres the attempt to decrypt in ruby cipher opensslcipherciphernewaes128cbc cipherkey base64decode646sewmgakdbk5fa2rr6vvwn cipheriv base64decode64vckaypm5tpmtp3tf7awrug cryptogram base64decode64jm0oxminptnf1vwxdi3xdki0klvx210cvpjllfjagm cleartext cipherupdatecryptogram whos the clever cleartext cipherfinalopensslcipherciphererror bad decrypt from irb100in final from irb100whats really frustrating about this is that it is possible to get the entire cleartext out of that encrypted string repeating the above but adding a nonsense pad to the cryptogram cleartext cipherupdatecryptogram pad whos the clever boy0 cleartext cipherfinal opensslcipherciphererror bad decrypt from irb119in final from irb119in my actual use case the cleartext is structured a json string since you ask so i feel comfortable a this point that i could tell use this scheme and detect poorly encrypted input without performing the cipherfinal however i cannot tolerate this sort of kludge in my code so i would like to understand how to make the ruby code handle the final block gracefully,"['php', 'ruby']" +37492,why an is accepted in c during runtime why can we do this in cint nscanfdnint ani thought array is located memory during load time but seems like the above example works during runtimedo i misunderstand any thing can you guys helpthanks,['c'] +37495,php how to thisable dangerous functions how can i thisable the dangerous eval function can that be done using ini set functionalso how to thisable following functions can we thisable them using ini set functionallow url fopen allow url includeexecshell execsystempassthrupopenstream selecteval is one of the most dangerous function that bad guys can use to exploit the things there should be a mechanism to thisable that without resorting to phpini file but is should be done programaticallywell guys i am looking for an answers suggesting thisabling of these dangerous lovely fellows without going to phpini file i mean how to thisable them at runtime or programaticallythanks in advanceupdatehas anyone heard about php shell offender script it mainly used the eval function for the exploit hackers are able to run their php code on your sitemy question was that i do not want to thisable the eval function from phpini file altogether for example i have developed my own mvc framework now the framework users can specify from frameworks config file whether eval and others function should be thisabled or not so this is left to the choice of framework users once they specify to thisable it i should be able to thisable the eval function programaticallyso that is the scenario looking for helpful answerssolutionsthanks again,['php'] +37509,propertychanged event testing is this a good way i am developing wpf applications using mvvm pattern i have viewmodel with code like thispublic bool editmodeenabled get return editmodeenabled set modeeditmodeenabled value onpropertychangededitmodeenabled onpropertychangedcommenttextboxvisibility onpropertychanged is virtual method of base class which just raise propertychanged eventi want to test propertychanged event raising and there my test methodpublic void editmodeenabledtest var imageviewmodel testhelpergettestimageviewmodel var firedevents new liststring imageviewmodelpropertychanged sender e firedeventsaddepropertyname imageviewmodelmode true assertareequalfiredeventscount 2 assertistruefiredeventscontainseditmodeenabled assertistruefiredeventscontainscommenttextboxvisibility is it a good way to test proprtychanged event,"['c#', '.net']" +37519,c vs java constructors according to john c mitchell concepts in programming languages java guarantees that a constructor is called whenever an object is created this is pointed as a java peculiarity which makes it different from c in its behaviour so i must argue that c in some cases does not call any constructor for a class even if an object for that class is createdi think that this happens when inheritance occurs but i cannot figure out an example for that casedo you know any example,"['java', 'c++']" +37543,how to handle a static final field initializer that throws checked exception i am facing a use case where i would like to declare a static finalfield with an initializer statement that is declared to throw a checked exception typically it would look like thispublic static final objectname object name new objectnamefootypebarthe issue i have here is that the objectname constructor may throw various checked exceptions which i do not care about because i would know my name is valid and it is allright if it miserably crashes in case it is not the java compiler would not let me just ignore this as it is a checked exception and i would prefer not to resort topublic static final objectname object namestatic try object name new objectnamefootypebar catchfinal exception ex throw new runtimeexceptionfailed to create objectname instance in static blockex because static blocks are really really difficult to read does anyone have a suggestion on how to handle this case in a nice clean way,['java'] +37568,using custom makefile with eclipsecdt i have a project of multiple c and h files and i write my own makefile how can i configure eclipse to use my makefile and my source files from their original locations,['c'] +37576,mysql enums always contain empty string in possibilities i am trying to create a simple yesmaybeno enum in mysql with phpmyadmini set null to no and maybe as the default valuei am expecting an error when executing something like set enumcol because an empty string should not be a valid valuebut the query gets executed and the value gets set to which means i am forced to double check for this unwanted and illegal value whenever i read from the databaseis this a bug in mysql or phpmyadmindoes anyone know a way of thisabling this behaviorthanks,['mysql'] +37631,plot points for image map i want to add automatic area highlighting to image maps on my webpage i have found the mapperjs library to be very useful in achieving this however creating the xy plots around a regional map is very time consumingis there a quick way to create bounding coordinates of a irregular polygon such as can be found on regional mapseditthere has got to be a way to do this i have fireworks 8 as well as photoshop cs3 on my windows pc but i am more familiar with fireworksif i create a marquee i can right click modify marquee convert to path that creates a path with several points but i do not know how to get to the next step which is extracting the coords of those points i have tried inserting a hotspot a polygon slice then exporting to html and images both of these give me square hotspots not a polygon i have also tried right click on the path and edit copy path outlines as well as edit copy html code neither give me the polygon coordsi can only get polygon coords for a slice is there perhaps a way to convert the path to a slice in fireworks 8,['javascript'] +37638,aspnet memebership authorization without password to authanticate users in aspnet membership we can call method formsauthenticationauthenticateusername passwordhow can i do the same job generate session cookies and all other staff that authanticate does without users passwordi am trying to login user over facebook connect users facebook id is stored within the users data user should be signed in like a normal user,['asp.net'] +37657,how do i get the current url of my script using php how do i get the current url of my script using php,['php'] +37659,how to debug fuse filesystem crash in linux currently i am developing an application using fuse filesystem module in linux 26 kernel in c language due to some programming error the application crashes after mounting the filesystem since i am a novice developer in linuxc environment could you please let me tell me possible options to debug such programs,['c'] +37666,is ruby pass by reference or by value userupdate languagesparamslanguagelanguage1 paramslanguagelanguage2 paramslanguagelanguage3lang errors usererrorsloggerdebug lang errors101 lang errorsfull messagesinspectif paramsuser userstate paramsuserstate success success usersaveendloggerdebug lang errors102 lang errorsfull messagesinspectif lang errorsfull messagesemptyuser object adds errors to the lang errors variable in the update lanugages methodwhen i perform a save on the user object i lose the errors that were initially stored in the lang errors variablethough what i am attempting to do would be more of a hack which does not seem to be working i would like to understand why the variable values are washed out i understand pass by reference so i would like to know how the value can be held in that variable without being washed out,"['ruby-on-rails', 'ruby']" +37671,is it possible to iterate over arguments in variadic macros i was wondering if it is possible to iterate over arguments passed to a variadic macro in c99 or using any gcc extensions for eg is it possible to write a generic macro that takes a structure and its fields passed as arguments and prints offset of each field within the structure something like thisstruct a int a int b int c prn struct offsets will print offset of each of the fields within structure passed as the first argumentint mainint argc char argv prn struct offsetsstruct a a b c return 0,['c'] +37688,the difference between a destructor and a finalizer please note this question is about the difference in terminology between the words destructor and finalizer and their correct usage i have merely provided examples of their use in c and ccli to demonstrate why i am asking the question i am well aware of how it is implemented in both c and the clr but i am asking about the correct use of terminologyin the c world the terms destructor and finalizer seem to be used pretty much interchangeably which i suspect is because the c specification describes the nondeterministic cleanup functionality using the word destructor whereas the clr documentation always uses the word finalizer so within the realms of c they mean the same thinghowever in the ccli specification there is a thistinction made between the two it allows both deterministic and nondeterministic cleanup and uses the term destructor for the deterministic functionality and finalizer for the nondeterministic functionalitythe finalizer provides nondeterministic cleanup a finalizer is a lastchance function that is executed during garbage collection typically on an object whose destructor was not executedadditionally the wikipedia descriptions of destructor and finalizer indicate that destructors and finalizers are separate concepts and supports the ccli specs use of the terms with regard to determinismunlike destructors finalizers are not deterministic a destructor is run when the program explicitly frees an object a finalizer by contrast is executed when the internal garbage collection system frees the objectthe questionsis there from a computer science point of view a clearly defined difference between a destructor and a finalizer or is the terminology something that can only be defined contextuallyif there is a clearly defined difference then why would the c spec use the wrong terminology,['c#'] +37692,threadsafe logging i want to implement a simple class for logging from multiple threads the idea there is that each object that wants to log stuff receives an ostreamobject that it can write messages to using the usual operators the desired behaviour is that the messages are added to the log when the stream is flushed this way messages will not get interrupted by messages from other threads i want to avoid using a temporary stringstream to store the message as that would make most messages at least twoliners as i see it the standard way of achieving this would be to implement my own streambuffer but this seems very cumbersome and errorprone is there a simpler way to do this if not do you know a good articlehowtoguide on custom streambufsthanks in advancespace c0wbo0yupdatesince it seems to work i added my own answer,['c++'] +37696,android listview nonenabled items draw invisible divider if i have a listview with two different kinds of items enabled and thisabled ones meaning selectable and nonselectable android draws a small divider correctly between the enabled items but not between thisabled items instead it draws a transparent divider which causes really bad design issues this has already been thiscussed here google groups but without any solutionwhat i am looking for is a way to force android to draw the same divider which is being used between enabled items also to being used between thisabled items instead of just leaving a transparent space,['android'] +37699,maven webapp to place jsps in webinfjsp i have inherited a webapp built using netbeans internal antall jsps reside inwebinfjspand the webxml has hardcoded links to webinfjspsomefilejsphow can i use the maven war plugin to place the jsp there maintaining consistency with the current structure my pom currently readswarsourcedirectorybasedirwebwebinfwarsourcedirectory,['java'] +37702,using javascript historyback fails in safari how do i make it crossbrowser i am using a hrefindexphp onclickhistorybackreturn falsebackato provide a back to previous page link it works fine on windows iemozilla but fails in safari on both windowsmacis there a way to make it work on all of the systemsbrowsers crossbrowserplatformif it is not possible is there any other way using php etc,"['php', 'javascript']" +37711,reserved keywords in objectivec at the cocoaheads aresund meeting yesterday peylow had constructed a great objc quiz the competition was intense and three people were left with the same score when the final question was to be evaluated how many reserved keywords does objectivec add to csome spirited debate followed all agreed that interface implementation etc are all preprocessor directives rather than keywords but how about something like in it might be a keyword but it is not a reserved keyword for example the following will compile without errors or warningsnsarray infor in in in nslogbwahahaawe concluded that objc adds no reserved keywords to c and someone won a seemingly wellearned bookbut today i tried some more systematic abuse on the compiler by trying things like thisint self 45selfint y selfthat compiles fine and the same code works replacing self for bool bycopy inout oneway byref sel and impusing id as the variable name the first and last lines compile but not the second one the same goes for protocol and classusing super the first line compiles but not the second and thirdwith yes no and null all three lines fail to compile probably because they are just defined as true false and nilit looks to me like a lot of this is gcc getting confused and i am not so sure it reflects what is and is not a reserved keyword in objectivec why for example is it ok to use self as the name of an int but not superthe fact that the first assignment always works except for with yes no and null would seem to support the idea that none of the candidates are technically reserved keywords that are not found in c orcould someone please give us an authoritative explication of this thorny issueseveral peoples honor is at stakeedit as nikolai ruhe pointed out we need a clear definition of keyword to proceed niko cited a wikipedia article saying that a keyword is a word or identifier that has a particular meaningi think it is reasonable to use this definition from the same articlein many languages such as c and similar environments like c a keyword is a reserved word which identifies a syntactic form words used in control flow constructs such as if then and else are keywords in these languages keywords cannot also be used as the names of variables or functionsfurthermore as the article statestypically when a programmer attempts to use a keyword for a variable or function name a compilation error will be triggeredin this sense then are there any reserved keywords that are predefined in the languageas formal specifications and cannot be used as a userdefined name,['objective-c'] +37718,restart tomcat when a class file is changed why do we need to restart a tomcat server whenever a class file is changed is there no other way,['java'] +37719,cannot use string offset as an array in php i am trying to simulate this error with a sample php code but have not been successful any help would be greatcannot use string offset as an array,['php'] +37724,difference between casting in c and vbnet the following code works fine in c int32 a b int16 c a 0x7f b a 0xf c int16bbut this code crash with a overflowexception in vbnet dim a b as int32 dim c as int16 a h7f b a and hf c ctypeb int16both code snippets seem the same to me what is the difference and how can i get the c code converted to vbnet,"['c#', '.net']" +37732,webrequest post with both file and parameters i am trying to upload a file and a send along a few parameters to my site using net c having read a few tutorials that do either a few parameters or a file i have tried unsuccessfully to combine them here is how i try doing itwebrequest req webrequestcreatebaseurl uploadreqcredentials new networkcredentialusername passwordstring boundary b0undaryreqcontenttype multipartformdata boundary boundaryreqmethod posthttpwebrequestrequseragent uploadtester v01string postdata boundary ncontentthisposition formdatanpostdata myid123somefk456postdata n boundary ncontentthisposition formdata namefile filenameuploadpdf contenttype applicationpdfnnbyte bytearray encodingutf8getbytespostdatabyte filedata nullusing binaryreader reader new binaryreaderfileopenreadmyfilepdf filedata readerreadbytesintreaderbasestreamlengthreqcontentlength bytearraylength filedatalengthreqgetrequeststreamwritebytearray 0 bytearraylengthreqgetrequeststreamwritefiledata 0 filedatalengthwebresponse response reqgetresponsestream data responsegetresponsestreamstreamreader sreader new streamreaderdatastring sresponse sreaderreadtoendresponseclosewhen i execute it i get a 500 exception saying header section has more than 10240 bnytes maybe it is not properly terminated and wireshark informs me that the request sent was a malformed package where the mime multipart was malformedthere are probably several issues here so please let me know all the problems you can spotupdate to separate mime from cnet i have spawned a thread here update 2 so the backend indeed has issues with the contentlength saying that the amount of bytes available for reading is smaller than the stated contentlength but if i reduce the contentlength in reqcontentlength accordingly i do not have a buffer size large enough for sending the data any suggestionsupdate 3 actually it looks like the header has a too large size compared to how much data it contains,"['c#', '.net']" +37737,how to use javascript to change div backgroundcolor the html belowdiv idcatestory div classcontent h2some title hereh2 psome content herep div div classcontent h2some title hereh2 psome content herep div div classcontent h2some title hereh2 psome content herep divdivwhen mouseover the content of div then it is backgroundcolor and the h2inside this div backgroundcolor changejust like the css hover i know this can use css hover to do this in modern browser but ie6 doest workhow to use javascriptnot jquery or other js framework to do thisedithow to change the h2 backgroundcolor too,['javascript'] +37747,convert hex string to long are there any cocoa classes that will help me convert a hex value in a nsstring like 0x12fa to a long or nsnumber it does not look like any of the classes like nsnumberformatter support hex numbersthankshuaying,['objective-c'] +37754,code commenting do you put your code comments on interfaces or on concrete classes or both what is the best practice in documenting classes and interfaces say if you have a concrete class called foo that derives from an interface called ifoo where do you put your comments for your methods do you duplicate your comments on the interface as well as the concrete classhere is an example where comments are duplicatedpublic class foo ifoo summary this function does something summary public void dosomething public interface ifoo summary this function does something summary void dosomething,['c#'] +37761,what to do with asynctask in onpause i am using an asynctask in my activity looks likepublic class myactivity private asynctask mtask private void dosomethingcool mtask new asynctask mtaskexecute override protected void onpause superonpause how do i let the task keep running if just rotating if isfinishing false so if the user is rotating the device onpause will get called but i do not want to cancel the task just because of that i know there is a way to tell the system to not actually destroy my activity on rotation but is that recommended for this problem should i instead put the asynctask in a static global class that would not be bound to the activitythanks,['android'] +37766,elementstylesetattribute vs elementattribute in javascript is there any difference between using elementstylesetattributewidth 150pxandelementstylewidth 150px i have seen that keywords would not work with the first way like this but for nonkeyword attributes is there a difference,"['javascript', 'html']" +37768,how to implement collision effects in a game i building a game with qt every objects on my graphicsscene inherits from graphicspixmapitem player obstacles bombs i would like to implment collision effects for example when the player gets hover a bonus he can pick it with the qt framework i can get the collidings items but i do not know which type they are as there is not instanceof function any tips edit i get the collision event the thing i want to do is handle the different collisions i made another question with better wording,['c++'] +37778,simple efficient weak pointer that is set to null when target memory is deallocated is there a simple efficient weakguarded pointer i need multiple pointers to the same object that are all automatically set to null when the object is deleted there is one master pointer that is always used to delete the object but there can be several other pointers that reference the same objecthere are some solutions that do not quite match my needsqpointer i am not developing a qt app i do not wish to include this libaryderive from qobjectboostweak ptr an exception is thrown when accessing a deallocated object too expensive for my situation it should be normal to test a weak pointer i plan to do some manual cleanup when a weak pointer is no longer valid updateweak ptr can be tested without throwing exceptionslowoverhead weak pointers this is very close to what i am looking for except i do not like the fact this scheme is only guaranteed to work as long as you donat allocate 2sizeofint times in the same locationwhy i need these weakguarded pointersi have a game with a list of game objects some objects are dependent on others for example a debugstats object that is associated with a game entity the debugstatus object thisplays useful info about the game entity but it only makes sense while the game entity exists so if the game entity is deleted the debugstats object should realize this and delete itself another idea is a tracking missile instead of deleting itself it may search for a new targeti wish to keep the debugstats logic separate from the game entity the game entity should not have to know a debugstats object is attached to it while i would prefer an answer for weakguarded pointers i also welcome different ways to approach my specific task i am thinking i may have to implement a game object manager that tracks object lifetimes and uses handles instead of raw pointers to memory addressesi am developing in c,['c++'] +37785,how to set a breakpoint on a default java constructor in eclipse in eclipse i would like to set a breakpoint on a java default constructor i cannot simply double click to the left of any line of code since default constructors have no source code they are implicitly generated by the java compileri would like to be able to set such a breakpoint without modifying the existing code,['java'] +37791,can you have too much of adynamica in dynamic languages in last few months i have been making a transition from java to groovy and i can appreciate many of the benefits it brings less code closures builders mop that in the end makes framework like grails possible ease with mocking when writing tests etchowever i have been aaccuseda by my coworkers that my code is not groovy enough namely i still declare types for my parameters and fields tend to use inheritance and polymorphism instead of duck typing etc it seems to me that in these situations it is not only dynamic vs static but also dynamic vs objectoriented paradigm kind of dilemma in those cases i still tend to prefer oo i feel that oo paradigm has great value in its basic premise in allowing you to abstract and relate your code constructs to particular realworld conceptsso here are particular questions i need help withshould i declare types for my parameters fields etcshould i declare block of code as closure when simple method will dowhen should i use duck typing instead of polymorphic dynamic thispatch for example in groovy i can do animalaction or def animal animalaction instead of animal animal new dog animalaction i can see the problem with first in the context of openclosed principle but any other reasons to prefer oo style polymorphismwhen should i use interfaces in groovy if everi am sure that there are some other similar dilemmas i failed to write down i also think that these questions are valid not just for groovy but for any other dynamic languagewhat is your opinion,['java'] +37802,how do i download a file over http using ruby how do i download a file over http using ruby,['ruby'] +37812,whats the difference between all these audio frameworks in the documentation i see several frameworks for audio all of them seem to be targeted at playing and recording audio so i wonder what the big differences are between theseaudio toolbox audio unit av foundation and core audio or did i miss a guide that gives a good overview of all these,['iphone'] +37813,c stl stringstream direct buffer access this should be pretty common yet i find it fascinating that i could not find any straight forward solutionbasically i read in a file over the network into a stringstream this is the declarationstdstringstream membufstdiosin stdiosout stdiosbinarynow i have some c library that wants direct access to the read chunk of the memory how do i get that read only access is ok after the c function is done i thispose of the memorystream no need for itstr copies the buffer which seems unnecessary and doubles the memoryam i missing something obvious maybe a different stl class would work bettereditapparently stringstream is not guaranteed to be stored continuously what isif i use vectorchar how do i get byte buffer,['c++'] +37839,add tuple to list of tuples in python i am new to python and do not know the best way to do thisi have a list of tuples which represent points and another list which represents offsets i need a set of all the combinations that this formsheres some codeoffsets 0 0 01 0 1 1 01 0points 1 5 3 3 8 7so my set of combined points should be 1 5 1 4 1 6 2 5 0 5 3 3 3 2 3 4 4 3 2 3 8 7 8 6 8 8 9 7 7 7i am not able to use numpy or any other libraries,['python'] +37844,including rake tasks in gems 1 is there a best place for rake tasks inside of gems i have seen them in tasks libtasks and i have seen them written as rb and rake not sure which if any is correct2 how do i make them available to the app once the gem is configured in the environment,"['ruby-on-rails', 'ruby']" +37846,struct objects in python i wanted to create a throwaway struct object to keep various status flags my first approach was this javascript style status object statusfoo 3 traceback most recent call last file stdin line 1 in moduleattributeerror object object has no attribute foodefinitely not what i expected because this works class anon pass banon bfoo 4i guess this is because object does not have a dict i do not want to use a dictionary and assuming i do not want to create the anon object is there another solution,['python'] +37849,is there any pros and cons if i use always css class instead css id for everything in css we can use both id and class is there any pros and cons if i use class always instead id in terms of semantic web standards w3c seo accessibility and future maintainability,['css'] +37866,how to prevent a globally overridden new operator from being linked in from external library in our iphone xcode 321 project were linking in 2 external static c libraries libbluea and libgreena libbluea globally overrides the new operator for it is own memory management however when we build our project libgreena winds up using libblues new operator which results in a crash presumably because libbluea is making assumptions about the kinds of structures being allocated both libbluea and libgreena are provided by 3rd parties so we cannot change any of their source code or build optionswhen we remove libbluea from the project libgreena does not have any issues however no amount of shuffling the linking order of the libraries seems to fix the problem nor does any experimentation with the various linking flags is there some way to tell xcode to tell the linker to have libgreens use of the new operator use the standard c new operator rather than the one redefined by libblue,"['c++', 'iphone']" +37868,should one really set pointers to null after freeing them there seem to be two arguments why one should set a pointer to null after freeing themavoid crashing when doublefreeing pointersshort calling free a second time by accident does not crash when it is set to nullalmost always this masks a logical bug because there is no reason to call free a second time it is safer to let the application crash and be able to fix itit is not guaranteed to crash because sometimes new memory is allocated at the same addressdouble free occurs mostly when there are two pointers pointing to the same addresslogical errors can lead to data corruption tooavoid reusing freed pointersshort accessing freed pointers can cause data corruption if malloc allocates memory in the same spot unless the freed pointer is set to nullthere is no guarantee that the program crashes when accessing the null pointer if the offset is big enough somestructlastmember thearraysomebignumber instead of crashing there will be data corruptionsetting the pointer to null cannot solve the problem of having a different pointer with the same pointer valuethe questionsheres a post against blindly setting a pointer to null after freeingwhich one is harder to debugis there a possibility to catch bothhow likely is it that such bugs lead to data corruption instead of crashingfeel free to expand this question,['c'] +37870,about index and primary key in sql it may looks a naive question but i am wondering about the relationship between primary keys and indexes in most common sql databasesis it a standard rule for a sql database to create automatically an index for every primary key i am asking that because i am designing a model with django and i am wondering if it is redundant to set both primary keytrue and db indextrue,['sql'] +37871,how to remove duplicate value from arraylist in android arrayliststring valuesnew arrayliststringvaluesaddsvaluesaddnvaluesaddavaluesaddsin this array i want to remove repeated values,"['java', 'android']" +37900,will multiple controlbegininvokeinvoke calls execute in order i need to know whether controlbegininvoke and controlinvoke calls will execute in the order they are calledi have the following scenarioui thread is blockedwcf thread calls controlbegininvokewcf thread calls controlinvoke or possibly begininvoke againui thread is unblockedthe execution order of step 14 is guaranteed to be in the shown order technically the order is not guaranteed to be that way but the question i have is only relevant if the order is as shownthe question i have is whether there is any chance that the invokebegininvoke call in step 3 is executed before the begininvoke call in step 2also please do not comment on blocking the ui thread,"['c#', '.net']" +37901,easy object binding to treeview node how can i bind an object to a treeview winforms node in ci thought of something like exnode windowsformsnode that can take an object as member besides the treenode name however i am not sure that is the right approach,['c#'] +37903,visual studioc autoformat can i control newline after attributes visual studio keeps doing thisdatacontract public class mycontract datamember public bool mybool get set datamember public string mystring get set i would like thisdatacontract public class mycontract datamember public bool mybool get set datamember public string mystring get set no big deal if the public class mycontract is on the same line as the datacontractvisual studio seems to have a lot of detailed autoformatting options but i cannot find any regarding newlines after attributes am i missing something here or is it just not availableedit at very least i would like a do not change what i entered formatting option as opposed to a always insert or always remove newline option it is superannoying that it keeps unformatting my code after i type,['c#'] +37905,creating a huge dummy file in a matter of seconds in c i want to create a huge dummy file say 12 gbs in matter of secondshere is what i have written in c filewriteallbytesfilenamenew bytea huge numberand another way with indicating the status was like following long fss dintotalfreespacelong segments fss 10long last seg fss 10binarywriter br new binarywriterfsfor long i 0 i segments i brwritenew byte10 thislabel2text segments write itostring rn segments remain segmentsi1tostring applicationdoeventsbrwritenew bytelast segthislabel2text rndonebrclosewhere din is thisk information objectwell with these two approach it takes something like 2 or more minutes to write such a big but dummy file is there any other faster way for doing soregards,['c#'] +37928,find out if a function is called within a c project i am trying to remove functions that are not used from a c project over time it is become bloated and i am looking to remove functions that are not used at alli have all the projects in a solution file in visual studio but i use cmake so i can generate project files for another ide if necessary which is why this is not tagged with visualstudiodoes something like this exist where it will analyze the source and tell me which functions are not called i saw pclint mentioned in a few questions here but that does not seem to do thiswhat i really want to do is call find all references on each function and remove the functions not called but doing this manually would take much too long,['c++'] +37942,unable to cast object of type systemcollectionsgenericlist1item to type itemlist for some reason my boss likes to create custom types to represent a generic list even in most cases where his custom type has no members i think he is just lazy and does not like to type the list or something but to me this is lame and is causing me many headaches per the issue belowpoint in casepublic class itemnlist listitempublic personalization findbyidint idblahblah blah this is really an extension method that should be elsewhereconsequently when i am using a standard list mabye i hate his custom class and like to use plain net types like they should be used or maybe i am using a linq expression like below i always run into casting problems even though the custom type is inheriting from that listprivate itemlist somemethoditemlist itemlist itemlist itemlistitemswherex xitemtype itemtypecar xitemtype itemtypetrucktolist return itemlist,['c#'] +37946,passing a pointer to a member function as a template argument why does this work i have some code that 100 works for the use case i have i am just wondering if anyone can explain how and why it works i have a template class that sits between some code that handles threading and network communication and the library user to pass data received from the server to the usertemplate class bar class baz class bazreturntype void barbarsetterfunctionconst bazreturntype bazreturntype bazbazgetterfunctionvoid constclass foo foo bar bar m barbar void foomemberfunction const baz baz boostbind barsetterfunction m bar boostbind bazgetterfunction baz bar m barthis template is instantiated and used in the library depending on the types of bar and baz like sotypedef foomybar mybaz returntypefrombazgetterfunction mybaractualsetterfunction mybazactualgetterfunction myfoomybar bar new mybarmybaz baz new mybazmyfoo f new myfoo bar ffoomemberfunction baz this all works and boostbind calls the gettersetter functions to pass the data around where it needs to go how and why does passing pointers to member functions as a template argument like in this case workin response to comments i had not realized that pointers to member functions were valid template arguments it is not something i had seen in the wild before i tried it and it worked but i was not expecting it to,['c++'] +37948,javascript code checking beyond jslint i am looking for something that works like checkstyle for javascript i know about jslint and i am already using googles closure compiler but these mostly check for syntactic issues checkstyle can check for braces on the wrong line but it also makes it possible to write custom checks like do not use hashmap i am looking for something like that for an upcoming javascript project any ideas,['javascript'] +37970,c declarative parsing serialization looking at java and c they manage to do some wicked processing based on special languaged based anotation forgive me if that is the incorrect namein c we have two problems with this1 there is no way to annotate a class with type information that is accessable at runtime2 parsing the source to generate stuff is way to complexbut i was thinking that this could be done with some template metaprogramming to achieve the same basic affect as anotations still just thinking about it like char traits that are specialised for the different types an xml traits template could be used in a declaritive way this traits class could be used to define how a class is serialiseddeserialized by specializing the traits for the class you are trying to serializeexample thoughstemplatetypename tstruct xml traits typedef xml empty childrentemplatestruct xml traitscar typedef boostmplvectorbodywheelsengine childrentemplatetypename tstdostream serializet const my template foo is not that strong but somthing like this boostmplfor eachtypename xml traitstchildrenserializedatatemplatestdostream serializexml emptyt const do nothing my question ishas anybody seen any projectsdecumentation not just xml out there that uses techniques like this template metaprogramming to emulate the concept of annotation used in languges like java and c that can then be used in code generation to effectively automate the task by using a declaritive styleat this point in my research i am looking for more reading material and examples,['c++'] +37973,call a function for each value in a generic c collection i have a collection of integer values in a list collectioni want to call a function for each value in the collection where one of the functions argument is a collection value without doing this in a foreach loop is there a way to accomplish this with a lambdalinq expressionsomething like mylistwherep myfuncpvalue thanks in advances,['c#'] +37975,find the nth occurrence of substring in a string this seems like it should be pretty trivial but i am new at python and want to do it the most pythonic wayi want to find the nth occurrence of a substring in a stringthere is got to be something equivalent to what i want to do which is mystringfindsubstring 2ndhow can you achieve this in python,['python'] +37982,urlconnection does not follow redirect i cannot understand why javas httpurlconnection does not follow redirect i use the following code to get this pageimport javaneturlimport javanethttpurlconnectionimport javaioinputstreampublic class tester public static void mainstring argv throws exception inputstream is null try string bitlyurl url resourceurl new urlbitlyurl httpurlconnection conn httpurlconnectionresourceurlopenconnection connsetconnecttimeout150 connsetreadtimeout150 connsetrequestpropertyuseragent mozilla50 windows u windows nt 60 ru rv19011 gecko2009060215 firefox3011 net clr 3530729 connconnect is conngetinputstream string res conngeturltostring if restolowercasecontainsbitly systemoutprintlnbitly is after resolving res catch exception e systemoutprintlnerror happened etostring finally if is null isclose moreover i get the following response it seems absolutely rightget 4hw294 http11host bitlyconnection keepaliveuseragent mozilla50 windows u windows nt 60 ruru rv1913 gecko20090824 firefox353 net clr 3530729http11 301 movedserver nginx0742date thu 10 dec 2009 202844 gmtcontenttype texthtml charsetutf8connection keepalivelocation mimeversion 10contentlength 297unfortunately the res variable contains the same url and stream contains the following obviously javas httpurlconnection does not follow redirectdoctype html public ietfdtd html 20enhtmlheadtitlemovedtitleheadbodyh2movedh2a hrefthe requested url has moved hereap alignrightsmalliaolserver451 on ismallpbodyhtml,['java'] +37985,dynamically add a servlet to the servletconfig i have a java web application that uses a plugin architecture i would like to know if anyone has a solution where by one could add a servlet with serlvet mapping to the servletconfig while the web app is running the idea being that a class could be added to the webinfclasses folder and be made active as a servlet without restarting the web app by the same nature if the user chooses to remove the plugin then have the code remove the class from the the servletconfig,['java'] +37990,converting html to plain text in php for email i use tinymce to allow minimal formatting of text within my site from the html that is produced i would like to convert it to plain text for email i have been using a class called html2text but it is really lacking in utf8 support among other things i do however like that it maps certain html tags to plain text formatting a like putting underscores around text that previously had i tags in the htmldoes anyone use a similar approach to converting html to plain text in php and if so do you recommend any thirdparty classes that i can use or how do you best tackle this issuethanks,"['php', 'html']" +38014,whats the difference between varchar and char whats the difference between varchar and char in mysqli am trying to store md5 hashes,"['sql', 'mysql']" +38023,return value from thread how do i get a thread to return a tuple or any value of my choice back to the parent in python,['python'] +38024,how to find determinant of large matrix i found some c code for finding the determinant of matrix for 4x4 to 8x8 it works ok but my project needs matrices that are 18x18 or more and the code is too slow the code is recursive but is recursion the right concept to deal with an 18x18 matrix how else can i find the determinant,['c++'] +38036,php remove javascript i am trying to remove javascript from the html i cannot get the regular expression to work with php it is giving me an null array whyphpvar script typetextjavascript function selectcodea var e aparentnodeparentnodegetelementsbytagnamepre0 if windowgetselection var s windowgetselection if ssetbaseandextent ssetbaseandextente 0 e einnertextlength 1 else var r documentcreaterange rselectnodecontentse sremoveallranges saddranger else if documentgetselection var s documentgetselection var r documentcreaterange rselectnodecontentse sremoveallranges saddranger else if documentselection var r documentbodycreatetextrange rmovetoelementtexte rselect script function remove javascriptjava echo preg replacescriptbscripti java,"['php', 'javascript']" +38053,what controls the list of supported languages of an iphone app in itunes what controls the languages shown as supported in an iphone apps itunes page in the right side below description under languages from the itunes connect developers guide it appears it is not something you choose during submission i assume it is something in the bundle,['ios'] +38054,exception from lambda expressions strange one that i do not still get is thissaytry stateclientsocketbeginsendmessageprefixed 0 messageprefixedlength socketflagsnone ar stateclientsocketendsendar stateclientcatch socketexception ex handle socketexceptioncatch objectthisposedexception ex handle objectthisposedexceptioni do not understand why lambda expression that returns with objectthisposedexception is not caught i was going deeper into lambdas and i cant understand it is it about the scope of lambda range variables thread issue i know lambda has no multithreading by their nature but as you can see the return comes from another thread which is created by beginsend before converting the implementation into a lambda this was ok when i had an asynccallback method handling the endsendany help appreciatedthank you in advance,['c#'] +38060,decrypting message with a spring web service client 350 bounty and waffles to the person who can help mei have been struggling with spring web service encryption for days and i cannot figure out how to get springs encryption on the message body to work whenever i have the server encrypt the resulting message the client does not seem to be decrypting it before it attempts to validate it against the schema xsdhere is the server side configurationthe servers xwss security configurationthe clients spring configurationclients xwss configurationwhat i can do is encrypt the user token and decrypt it successfully i do that when sending data from the client to the server the server then decrypts the user token and authenticates the user credentials that works quite wellthe problem occurs if i try and encrypt the body of the message coming back the issue occurs on the client side it seems the client is trying to validate the message before it decrypts it and hence an error occurs when validating against the schemafatal error 1192 the prefix ns0 for element ns0holidaylistresponse is not bound11dec2009 74532 am comsunxmlwssimplapachecryptodecryptionprocessor decryptelementwithciphersevere wss1203 exception the prefix ns0 for element ns0holidaylistresponse is not bound while trying to decrypt messageand here is the soap response itselfand here is the marshalling mapping filexml version10 encodingutf8doctype mapping public exolabcastor mapping dtd version 10en mapping fieldhandler namedatehandler classcommycompanyhrhandlersdatefieldhandler fieldhandler namedatehandler2 classcommycompanyhrhandlersdatefieldhandler class namecommycompanyhrdataholiday mapto nsuri nsprefixns0 xmlholiday field namefrom typestring handlerdatehandler bindxml namestartdate nodeelement field field nameto typestring handlerdatehandler2 bindxml nameenddate nodeelement field class class namecommycompanyhrdataemployee mapto nsuri nsprefixns0 xmlemployee field namenumber typejavalanginteger bindxml namenumber nodeelement field field namefirstname typejavalangstring bindxml namefirstname nodeelement field field namelastname typejavalangstring bindxml namelastname nodeelement field class class namecommycompanyhrdataholidayrequest mapto nsuri nsprefixns0 xmlholidayrequest field nameholiday typecommycompanyhrdataholiday bindxml nameholiday nodeelement field field nameemployee typecommycompanyhrdataemployee bindxml nameemployee nodeelement field class class namecommycompanyhrdataholidayconfirmation mapto nsuri nsprefixns0 xmlholidayconfirmation field nameconfirmationcode typejavalanginteger bindxml nameconfirmationcode nodeelement field field nameconfirmationmessage typejavalangstring bindxml nameconfirmationmessage nodeelement field class class namecommycompanyhrdataholidayresponse mapto nsuri nsprefixns0 xmlholidayresponse field nameconfirmation typecommycompanyhrdataholidayconfirmation bindxml nameholidayconfirmation nodeelement field class class namecommycompanyhrdataholidaylistrequest mapto nsuri nsprefixns0 xmlholidaylistrequest field nameid typejavalanginteger bindxml nameuserid nodeelement field class class namecommycompanyhrdataholidaylistresponse mapto nsuri nsprefixns0 xmlholidaylistresponse field nameholidays typecommycompanyhrdataholiday collectionvector bindxml nameholiday nodeelement field classmappingi know it is a lot of information but i figured i would provide everything is my encryption setup correct is it not possible encrypt the body of the message and decrypt it on the client side at this point i am open to almost any suggestion,['java'] +38066,thistinguish java threads and os threads in production systemlike banking application running in linux environmenthow do i thistinguish running java threads and native threadsin linux there will be parent process for every child process and they say 0 is the parent of all the process will there be a parent thread of all the forked java threadshow do i know which java thread is related to os thread if a java thread forkes a native process threadis there any naming convention of java threads and os threadscan a running java threads can be suspended or killed from another java code,['java'] +38078,capistrano deployrb file refactoring i have following code in my deployrbnamespace app do desc copies the configuration frile from sharedconfigyml to config task copy config filesroles app do run cp fv deploy tosharedconfighoptoadrb release pathconfiginitializers run cp fv deploy tosharedconfigapp configyml release pathconfigapp configyml endendi thought it would be a good idea to keep my deployrb file clean and i attempted to move above code to capistrano utilitiesrb under config i am using rails application and i added following line of code to deployrb require fileexpand pathfiledirname file libcapistrano utilitiesnow i am getting following errorundefined method namespace for mainobject nomethoderrorthe value of self in the deployrb is capistranoconfiguration while the value of self in capistrano utilities is main so i understand why i am getting namespace method error what is the fix for this problem,"['ruby-on-rails', 'ruby']" +38081,numpy how to convert an array type quickly i find the astype method of numpy arrays not very efficient i have an array containing3 million of uint8 point multiplying it by a 3x3 matrix takes 2 second but converting the result from uint16 to uint8 takes another secondmore precisely print timeclock imgarray npdotimgarray m255 print timeclock imgarray imgarrayclip0 255 print timeclock imgarray imgarrayastypeb print timeclockdot product and scaling takes 2 secclipping takes 200 msectype conversion takes 1 secgiven the time taken by the other operations i would expect astype to be fasteris there a faster way to do type conversion or am i wrong when guesstimating that type conversion should not be that hard edit the goal is to save the final 8 bit array to a file,['python'] +38094,jquery click tracking with php yes i know about google analytics we use it for our overall site metrics and i know we can track individual links however we needed a tracking solution for very specific links and we need that tracking data available to our web application in real time so i wrote my own solutionjquery fntrack function var source url name ref this this this if windowlocationsearchsubstring1 source windowlocationpathname windowlocationsearchsubstring1 else source windowlocationpathname url jqueryurlencodethisattrhref name thisattrname ref jqueryurlencodesource thisliveclick function click clickpreventdefault postlibtrackphp url url name name ref ref function windowlocation thisattrhref using the jquery urlencode plugin now this code works fine with my php backend and on my machine but it does not seem to work reliably for everyone else sometimes the parameters passed in via jquery are not passed in resulting in a record in the database with no name url or reffor the life of me i cannot figure out why this might be happening i know the post is triggering since there are records in the database in the php i also record the ip of the request along with the timestamp but in many cases the php script is receiving blank post variables from jquery i have tested it live on every browser i have access to at my workplace and all of them work fine for me however about 75 of all the records created not by my computers come through as blank most of them are using the same browsers i am why could this be happening,"['php', 'jquery']" +38095,uitableviewuitableviewcell tap event response i have been googling around to try to figure out what sort of event handles are called when one row or cell in a uitableview is tapped but have not been able to figure it out i am trying to change the image property of the cell when it is tappedthanks,"['iphone', 'objective-c']" +38096,javascript operator what is the difference between the operator and the operator does it behave similar to the operator where it compares both value and the type,['javascript'] +38110,code bacteria evolving mathematical behavior it would not be my intention to put a link on my blog but i do not have any other method to clarify what i really mean the article is quite long and it is in three parts 123 but if you are curious it is worth the readinga long time ago 5 years at least i programmed a python program which generated mathematical bacteria these bacteria are python objects with a simple opcodebased genetic code you can feed them with a number and they return a number according to the execution of their code i generate their genetic codes at random and apply an environmental selection to those objects producing a result similar to a predefined expected value then i let them duplicate introduce mutations and evolve them the result is quite interesting as their genetic code basically learns how to solve simple equations even for values different for the training datasetnow this thing is just a toy i had time to waste and i wanted to satisfy my curiosity however i assume that something in terms of research has been made i am reinventing the wheel here i hope are you aware of more serious attempts at creating insilico bacteria like the one i programmedplease note that this is not really genetic algorithms genetic algorithms is when you use evolutionselection to improve a vector of parameters against a given scoring function this is kind of different i optimize the code not the parameters against a given scoring function,['python'] +38122,how to use cs ternary operator with two byte values there does not seem to be a way to use cs ternary operator on two bytes like sobyte somebyte someboolean 0 1that code currently fails to compile with cannot convert source type int to target type byte because the compiler treats the numbers as integers apparently there is no designated suffix to indicate that 0 and 1 are bytes so the only workarounds are to a cast the result into a byte or b to use an ifelse control after allany thoughts,['c#'] +38124,how do i inspect a class in objectivec update i fixed up the code to eliminate duplication of overridden methods and track originator of property or method by implementing marks suggestion have not tackled property types yet will probably start with property getattributes when i do also stripped out vestigial underscoresbasically i need a way to remind myself what methods and properties are available on a given object without hopping all the way down the inheritance treei have cooked up the following function but it leaves a bit to be desiredimport objcruntimehnsinteger inspectclass alphabeticsortid string1 id string2 void reverseif nsinteger reverse noreturn string2 localizedcaseinsensitivecomparestring1return string1 localizedcaseinsensitivecomparestring2void inspectclastopatclass inspectedclass class stopclassclass originalclass inspectedclassnsstring originalclastring nsstring stringwithformat originalclassnsstring inheritancepath nsstring stringwithformat originalclassmethod methodsobjc property t propertiesunsigned int iunsigned int methodcountunsigned int propertycountint reversesort nonsarray sortednsarray methodsandpropertieskeysnsmutabledictionary methodsandproperties nsmutabledictionary dictionarywithcapacity10nsstring inspectedclastringnsstring methodorpropertynamewhile inspectedclass stopclassinspectedclastring nsstring stringwithformat inspectedclassif inspectedclass originalclassinheritancepath inheritancepath stringbyappendingformat inspectedclassmethods class copymethodlistinspectedclass methodcountproperties class copypropertylistinspectedclass propertycountfor i0 imethodcount imethodorpropertyname nsstring stringwithformats sel getnamemethod getnamemethodsiif methodsandproperties objectforkeymethodorpropertynamemethodsandproperties setobjectinspectedclastring forkeymethodorpropertynamefor i0 ipropertycount imethodorpropertyname nsstring stringwithformat s property getnamepropertiesiif methodsandproperties objectforkeymethodorpropertynamemethodsandproperties setobjectinspectedclastring forkeymethodorpropertynameinspectedclass inspectedclass superclassfreemethodsfreepropertiesmethodsandpropertieskeys methodsandproperties allkeyssorted methodsandpropertieskeys sortedarrayusingfunctioninspectclass alphabeticsort contextreversesortnslog inheritancepathfor nsstring key in sortedif methodsandproperties objectforkeykey isequaltostringoriginalclastringnslogt key methodsandproperties objectforkeykeyelsenslogt keyvoid inspectclassclass inspectedclassinspectclastopatinspectedclass nsobject classand some sample output from inspectclasstextmap classtextmap surface position surface size surfaceaddchild surfacedeallocinit surfaceinitwithfileposition surfacerendersetposition surfacesetsize surfacesettextsize surfaceupdate surface,['objective-c'] +38126,how can i autopopulate a pdf form in djangopython i have pdf forms that i want to autopopulate with data from my django web application and then offer to the user to download what python library would let me easily prepopulate pdf forms these forms are intended to be printed out,['python'] +38127,how to prepare for a ruby interview in just one weekend i am a seasoned web developer but only have a modicum of rubyrails experience i just got an interview monday at a ruby shop they do realize i do not have much ruby experience besides 2 or 3 ruby books i have lying around what other resources might i avail myself of for a weekend crash course in ruby i do have a bare minimum account on hostingrails by the way though i have never used iti do not see any other exact duplicates of this searching for ruby interview i did find but i am not sure that that is not overkill or too much for one weekend,"['ruby-on-rails', 'ruby']" +38191,difference between format specifiers i and d in printf what is the difference between d and i when used as format specifiers in printf,"['c++', 'c']" +38214,any solution for classgetmethod reflection and autoboxing i want to useclassgetmethodstring name class parametertypesto find the method i need to invoke with the given parameters but apparently as described in bug 6176992 java does not include autoboxing there so if my reflected class has a method with a string int signature you still get a nosuchmethodexception with a stringclass integerclass array as a paremeteris there any sollution for this the only way i could think of to call getmethod with every permutation of primitive and non primitive types which i do not really want to doedit to make it more clear i am well aware of the primitive type classes but i do not see how they could help to solve my problem my parametertypes array comes from somewhere and i know that it will only return non primitive types i can not assume that the interface will only be declared with primitive types and that is exactly my problempublic interface testinterface public void dotestinteger i1 int i2 double d3 double dclass classes integerclass integerclass doubleclass doubleclass due to autoboxing i should become the dotest method here but it does not worktestinterfaceclassgetmethoddotest classes,['java'] +38217,django allow line break from textarea input how do i allow line breaking in textarea input in django to later show this input on page,['html'] +38218,ubuntu linux library path how do i determine the ubuntu linux library path that is how does the linker know where to got to grab the object files when linking my program,['c++'] +38219,row number in mysql is there a nice way in mysql to replicate the sql server function row numberfor exampleselect col1 col2 row number over partition by col1 col2 order by col3 desc as introwfrom table1then i could for example add a condition to limit introw to 1 to get a single row with the highest col3 for each col1 col2 pair,"['mysql', 'sql']" +38224,python tempfile module and threads are not playing nice what am i doing wrong i am having an interesting problem with threads and the tempfile module in python something does not appear to be getting cleaned up until the threads exit and i am running against an open file limit this is on os x 1058 python 251yet if i sort of replicate what the tempfile module is doing not all the security checks but just generating a file descriptor and then using osfdopen to produce a file object i have no problemsbefore filing this as a bug with python i figured i would check here as it is much more likely that i am doing something subtly wrong but if i am a day of trying to figure it out has not gotten me anywhereusrbinpythonimport threadingimport threadimport tempfileimport osimport timeimport sysnum threads 10def worker tempfile tempfd tempfn tempfilemkstemp tempobj osfdopentempfd wb tempobjwritehello world tempobjclose osremovetempfn timesleep10def worker notempfileindex tempfn strindex txt the values i am passing osopen may be different than tempfilemkstemp uses but it works this way as does using the open function to create a file object directly tempfd osopentempfn oso excl oso creat oso trunc oso rdwr tempobj osfdopentempfd wb tempobjwritehello world tempobjclose osremovetempfn timesleep10def main for count in rangenum threads if count 100 0 printopening thread s count wthread threadingthreadtargetworker tempfile wthread threadingthreadtargetworker notempfile argscount started false while not started try wthreadstart started true except threaderror printfailed starting thread s sleeping count timesleep3if name main mainif i run it with the worker notempfile line active and the worker tempfile line commentedout it runs to completionthe other way around using worker tempfile i get the following error python threadtempfiletestpy opening thread 0opening thread 100opening thread 200opening thread 300exception in thread thread301traceback most recent call last file systemlibraryframeworkspythonframeworkversions25libpython25threadingpy line 460 in bootstrap file systemlibraryframeworkspythonframeworkversions25libpython25threadingpy line 440 in run file threadtempfiletestpy line 17 in worker tempfile file systemlibraryframeworkspythonframeworkversions25libpython25tempfilepy line 302 in mkstemp file systemlibraryframeworkspythonframeworkversions25libpython25tempfilepy line 236 in mkstemp inneroserror errno 24 too many open files varfolders4l4ltd6bcveoipksvnacj2oktktmptmpj6wjv0any ideas what i am doing wrong is this a bug in python or am i being boneheadedupdate 20091214i think i have found the answer but i do not like it since nobody was able to replicate the problem i went hunting around our office for machines it passed on everything except my machine i tested on a mac with the same software versions i was using i even went hunting for a desktop g5 with the exact same hardware and software config i had same result both tests with tempfile and without tempfile succeeded on everythingfor kicks i downloaded python 264 and tried it on my desktop and same pattern on my system as python 251 tempfile failed and notempfile succeededthis is leading me to the conclusion that somethings hosed on my mac but i sure cannot figure out what any suggestions are welcome,['python'] +38230,i keep getting quit and connect http methods sent to my server what do they mean i keep getting the two following errors from my server i assumed they were just bots looking for potential targets but does anyone know specifically why i am getting these i am using the sslrequirement plugin to make sure all hits to the loginsignup page are redirected to ssl so all of these weird https requests to root should just be redirected to regular httpa actioncontrollerunknownhttpmethod occurred in applicationindexquit accepted http methods are get head put post delete and optionsusrlocallibrubygems191gemsactionpack234libaction controllerrequestrb35in request methodpath info remote addr 9919208249remote port 6376request method connectrequest uri server port 443server protocol http10server software apachea actioncontrollerunknownhttpmethod occurred in applicationindex connect accepted http methods are get head put post delete and optionsusrlocallibrubygems191gemsactionpack234libaction controllerrequestrb35in request methodhttps onhttp x forwarded proto httpspath info remote addr 9120919676remote port 50751request method quitrequest uri server port 443server protocol http09,['ruby-on-rails'] +38256,why should i use the using keyword to access my base class method i wrote the below code in order to explain my issue if i comment the line 11 with the keyword using the compiler does not compile the file and thisplays this error invalid conversion from char to const char it seems to not see the method void actionchar of the parent class in the son class why the compiler behave this way or have i done something wrongclass parent public virtual void action const char how thisaction how virtual void action const char how 0class son public parent public using parentaction why should i write this line void action const char how printf action cn how int main int argc char argv son s son saction a return 0,['c++'] +38284,script to convert log4jproperties to log4jxml i need to use custom filters so i need to convert some long log4jproperties files to log4jxmlis anyone aware of a tool to do this or willing to contribute one they have used searching has thus far turned up no such tool,['java'] +38286,in what ways do c exceptions slow down code when there are no exceptions thown i have read that there is some overhead to using c exceptions for exception handling as opposed to say checking return values i am only talking about overhead that is incurred when no exception is thrown i am also assuming that you would need to implement the code that actually checks the return value and does the appropriate thing whatever would be the equivalent to what the catch block would have done and it is also not fair to compare code that throws exception objects with 45 state variables inside to code that returns a negative integer for every errori am not trying to build a case for or against c exceptions solely based on which one might execute faster i heard someone make the case recently that code using exceptions ought to run just as fast as code based on return codes once you take into account all the extra bookkeeping code that would be needed to check the return values and handle the errors what am i missing,['c++'] +38291,what is the difference between the int and index methods in python 3 the data model section of the python 32 documentation provides the following descriptions for the int and index methodsobject int selfcalled to implement the builtin function int should return an integerobject index selfcalled to implement operatorindex also called whenever python needs an integer object such as in slicing or in the builtin bin hex and oct functions must return an integeri understand that they are used for different purposes but i have been unable to figure out why two different methods are necessary what is the difference between these methods is it safe to just alias index int in my classes,['python'] +38303,what c99 features are considered harmful or unsupported i usually write c code in c89 now some features of c99 like intxx t or va args or snprintf are very useful and can be even vitalbefore i more my requirements from c89 to c99 i wanted to know which of c99 features were widely supported and which ones were not widely supported or even considered harmfuli know we could just check our target compiler support but this would narrow our support a lot and as this is for open source software i would prefer having a wider supportfor example we use solaris suncc compiler and gcc but there might be other compiler we would move out of the way while we could keep compatibility with very little effortsfor example i never worked on windows nor i know anything about windows compilers but it would be good to keep windows compatibility,['c'] +38309,the command ruby does nothing on my mac i cannot get the ruby interpreter to run on either of my macs one macbook and one macbook pro both running snow leopard when i run it by typing ruby in terminal nothing happens it just sits there i can kill it by pressing ctrlc but that is it i know the ruby process is running since i can see it in activity monitor and running ruby version works finei have tried the following all to no availi have some bash customizations so i tried thisabling them but that did not helpi installed a new copy of ruby 187 using macports but that one had the same problemi tried quitting and restarting the terminal applicationsome other information that might be usefuli am trying to run the version of ruby that comes with snow leopardi have installed apples developer toolsother interpreters python io etc work finei spent a while tonight searching for this problem online but have not found any thiscussion of it i am at a loss for what could be causing it so any help anybody can provide would be greatly appreciated,['ruby'] +38321,count divs with a certain class seems pretty simple but i cannot get it to worki have two divs with the class user i want to output you have 2 divsscript typetextjavascript documentreadyfunction function divcount var mycount userlength documentwritemycount scripti am sure i am missing something simple,"['javascript', 'jquery']" +38345,wpf how to prevent a control from stealing a key gesture in my wpf application i would like to attach an input gesture to a command so that the input gesture is globally available in the main window no matter which control has the focusin my case i would like to bind keypagedown to a command however as soon as certain controls receive the focus eg a textbox or treeview control these controls receive the key events and the command is no longer triggered these controls have no specific commandbindings or inputbindings definedthis is how i define my input gesturexamlwindow xclasswindow1 xmlns xmlnsx titlewindow1 height300 width300 stackpanel treeview treeviewitem header1 treeviewitem header11treeviewitem treeviewitem header12treeviewitem treeviewitem treeviewitem header2 treeviewitem treeview textbox label namelabel1 stackpanelwindowcodeusing systemusing systemwindowsusing systemwindowsinputpublic static class commands private static routeduicommand mycommand static commands mycommand new routeduicommandmy command my command typeofcommands new inputgesturecollection new keygesturekeypagedown modifierkeysnone public static icommand mycommand get return mycommand public partial class window1 window public window1 initializecomponent commandbinding cb new commandbinding cbcommand commandsmycommand cbexecuted new executedroutedeventhandlercb executed cbcanexecute new canexecuteroutedeventhandlercb canexecute thiscommandbindingsaddcb void cb canexecuteobject sender canexecuteroutedeventargs e ecanexecute true void cb executedobject sender executedroutedeventargs e thislabel1content stringformatmy command was executed 0 datetimenow i already tried catching the windows previewkeydown event and marking it as handled this had not the desired effect i also set the focusable property to false this helped for textbox controls but not for the treeview and has the unwanted effect that the textbox no longer can be edited so it is not a solution for meso my question is how can i define a keyboard shortcut that works everywhere in the main window,['c#'] +38365,source code for xiaolin wus line algorithm in c i am looking for a nice and efficient implementation of xiaolin wus antialiased line drawing algorithm in c does anyone have this code they could share with methanks,['c'] +38391,how to expand all nodes of a wpf treeview in code behind i might be suffering of mondays dumbness but i cannot find a nice way of expanding all treeview nodes after i have added them in code behind something like treeviewexpandallany quick help,['c#'] +38394,cannot save phpini i have php for fastcgi installed on windows 7 through the web platform installer i need to edit phpini to enable logging but i am not able to overwrite the existing file apparently because something has it open andor locked stopping the server in iis manager does not help stopping the windows process activation service and the world wide web publishing service does not help phpinfo confirms that i am working with the correct file cprogram files x86phpphpini it is not marked as read only and i do have permissions for it i am out of ideas,['php'] +38400,a workaround for ssl on heroku got an app running great on heroku only issue is that their customdomain ssl solution is way expensive leaving piggybacking of their herokucom as an only viable option the good thing is that my app only requires ssl for a couple of pages for ordering right now i use ssl required in my controller for those couple actions any idea on how to create a before filter that would bump the user to just for those two actions and redirect to for anything else ugly ugly but seems like the best way to go for now,['ruby-on-rails'] +38404,optimal way to perform a shift operation on an array suppose i have an arrayunsigned char arr 0123456789is there a way to perform shift operation on them besides just copying them all into another array we can easily do it using linked lists but i was wondering if we can use a shift operator and get work done fasternote the data in this question is just an example the answer should be irrecpective of the data in the array,"['c++', 'c']" +38410,rounded rect with gradient color i have not really done much programming with core graphics and i tend to stick with quartzcore now that it does a lot of what i need through the layer property however i have a uiview which is currently gradient i would like to add rounded corners to this uiview and the layer property does not do this when i draw the gradient voiddrawrectcgrectrect cgcontextref currentcontext uigraphicsgetcurrentcontext cggradientref glossgradient cgcolorspaceref rgbcolorspace size t num locations 2 cgfloat locations2 00 10 cgfloat components8 10 10 10 095 start color 10 10 10 060 end color rgbcolorspace cgcolorspacecreatedevicergb glossgradient cggradientcreatewithcolorcomponentsrgbcolorspace components locations num locations cgrect currentbounds selfbounds cgpoint topcenter cgpointmakecgrectgetmidxcurrentbounds 00f cgpoint midcenter cgpointmakecgrectgetmidxcurrentbounds cgrectgetmaxycurrentbounds cgcontextdrawlineargradientcurrentcontext glossgradient topcenter midcenter 0 cggradientreleaseglossgradient cgcolorspacereleasergbcolorspacei am not really sure where i should be rounding in the drawrect method thanks,['iphone'] +38417,android activity that does not fill the parent screen any idea why this does not create an activity that looks like a popup instead of an activity that completely fills the screen xml version10 encodingutf8 linearlayout xmlnsandroid androidorientationvertical androidlayout width300dip androidlayout height120dip androidlayout margintop100dip relativelayout xmlnsandroid androidorientationvertical androidlayout height120dip androidlayout width300dip textview androidlayout widthfill parent androidlayout heightwrap content androidtextstringhello relativelayout linearlayouti assumed that i only needed to set the layout height and layout width to something other than fill parent but it still shows up as a black screen that completely fills the screenultimately i simply want to create a popup but i do not want to use an alertdialog is this possible,['android'] +38424,run script during clean clean all in xcode i have a fairly complex iphone sdk xcode project with many targets 4 static libs unit tests multiple sample apps a buildall that runs a shell script and a package that runs another shell script the buildall target creates a directory in the project with some subdirectories with contents ready for thistributionwhen i click clean all though xcode does not know to clean my thistribution directory i would like it to i cannot seem to find a way to do this does anybody know howit feels like clean and clean all should really just be targets in xcode and i should be able to add a run script phase not so to my knowledgebtw the buildall target does handle cleaning the thistribution directory so this is not the end of the world to me it is just irksome that clean all does not actually clean all in my particular case,['iphone'] +38428,why list comprehension is called so in python no flaming please asking as a community wiki so nobody gets reputation herei know python is not the first language to have list comprehensioni am just interest in the history of the namei am particularly interested in why it is called comprehension,['python'] +38438,getting the ip address of a remote socket endpoint how do i determine the remote ip address of a connected socketi have a remoteendpoint object i can access and well as its addressfamily memberhow do i utilize these to find the ip addressthankscurrently tryingipaddressparse testsocketaddressaddresstostring tostringand getting 100127 instead of 127001 for localhost end points is this normal,['c#'] +38452,how to programmatically make cocoa application active i have got a background process that makes a transparent window appear when a hotkey is pressedwindow makekeyandorderfrontnilcontent animator setalphavalue10 alpha was 00 the window shows up fine in front of the other windows as i want it to however until i manually click the window whatever application was active when the window appears remains active i was expecting the makekeyandorderfront to make the application active as well however adding a nslog line to my applicationwillbecomeactive shows it is not getting any active notification until the mouse click is performed does anyone know how i can set my application active the same time i issue the makekeyandorderfront i need it active so that it can begin accepting keyboard input any assistance needed,['objective-c'] +38461,unit testing an executable project maybe i am not thinking about this correctlyi am starting my second project using unit tests my first project i rolled my own for this project i am trying out boosttestmy question is what are the proper procedures for unit testing projects that compile into executables it seems like everything i see out there is for libraries and dependencies i want my exe project to be unit tested but i do not want a bunch of unit test functions floating around in the binary nor do i want to do ifdef debug boost auto test case my func endifaround all my tests i thought about creating a separate project for unit tests but that does not really work for executable unless i want to do some fancy prebuild operation copying from my other project into the test projectany thoughts or ideas,['c++'] +38470,cannot delete or update a parent row a foreign key constraint fails when doingdelete from jobs where job id 1 limit 1 it errors1451 cannot delete or update a parent row a foreign key constraint fails paymesomethingadvertisers constraint advertisers ibfk 1 foreign key advertiser id references jobs advertiser idhere are my tablescreate table if not exists advertisers advertiser id int11 unsigned not null auto increment name varchar255 not null password char32 not null email varchar128 not null address varchar255 not null phone varchar255 not null fax varchar255 not null session token char30 not null primary key advertiser id unique key email email engineinnodb default charsetutf8 auto increment2 insert into advertisers advertiser id name password email address phone fax session token values1 test company create table if not exists jobs job id int11 unsigned not null auto increment advertiser id int11 unsigned not null name varchar255 not null shortdesc varchar255 not null longdesc text not null address varchar255 not null time added int11 not null active tinyint1 not null moderated tinyint1 not null primary key job id key advertiser id advertiser idactivemoderated engineinnodb default charsetutf8 auto increment2 insert into jobs job id advertiser id name shortdesc longdesc address active moderated values1 1 test testtest testtestes 0 0alter table advertisers add constraint advertisers ibfk 1 foreign key advertiser id references jobs advertiser id,"['sql', 'mysql']" +38478,php call user func array pass by reference issue the below function generates error when a function contains referenced arguments egfunction testarg arg2 some codenow i can not use call user func array for above function it will generate an errorhow to solve this problemi do need to use call user func arrayalso assume that i do not know beforehand whether they are passed by reference or passed by valuethanks,['php'] +38484,c byreference argument and c linkage i have encountered a working with xlc8 and msft9 compilers piece of code containing a c file with a function defined with c linkage and a reference argument this bugs me as references are c only the function in question is called from c code where it is declared as taking a pointer argument to the same type in place of the reference argumentsimplified examplec fileextern c void fint i ic filevoid fint int main int a 2 fa printfdn a prints 3 now the word on the street is that most c compilers under the hood implement references just like a pointer is it like that and just pure luck the reason this code works or does it say somewhere in the c specification what the result is when you define a function with a reference argument and c linkage i have not been able to find any information on this,"['c++', 'c']" +38505,sending emailiphone simulator i have create an application where the user is able to send some info to others via email but how could i test this on simulator is there any way to do that,['iphone'] +38514,c outlook 2007 com interop application does not exit any ideas why the following code does not exit the outlook 2007 process created via com interopmicrosoftofficeinteropoutlookapplication app new microsoftofficeinteropoutlookapplicationvar item appsessionopenshareditemctestmsg as microsoftofficeinteropoutlookmailitemstring body itemhtmlbodyint att itemattachmentscountitem as microsoftofficeinteropoutlook mailitemclosemicrosoftofficeinteropoutlookolinspectorcloseolthiscardsystemruntimeinteropservicesmarshalreleasecomobjectitemapp as microsoftofficeinteropoutlook applicationquitsystemruntimeinteropservicesmarshalreleasecomobjectappsystemdiagnosticsdebuggerbreakan almost identical snippet using word works so i wonder if i am forgetting to clean up something,['c#'] +38522,examples of using doctests in django in an agile bdd way i am interested in learning how to doctests and unit tests in a more agile bdd wayi have found a few tutorials that seem reasonable but they are just thumbnailswhat i would really like to see is the source code of some django projects that were developed bdd stylethe things i am unclear about are how do you handle request objects etci have a situation where i have deployed my app and i am getting completely different behavior in production that i did in development or even from the python shell on the production server i am hoping some doctests will help me diagnose this and well as open the door for a more agile process of writing the tests firstspecifically here is the code i am trying to testdef match pictures with products queryset number of images 3 products i 0 for product in queryset if i number of images image productimagemain setall1 productphoto url image0photourl productsappendproduct i 1 return products def indexrequest returns the top 10 most clicked products products productobjectsall10 products match pictures with products products 10 return render to responseproductsproduct listhtml products productshow do i create a doctest that ensures that index returns 10 objectsthe product queries seem to work fine from the shell on the production server the actual server is not returning any products at all,['python'] +38533,calling a webservice that uses iso88591 encoding from wcf i am trying to call a webservice using wcf that uses the following encodingxml version10 encodingiso88591 i cannot change the encoding for this webservice i have generated a wcf proxy and when i try and call the proxy i get the following errorfailedsystemservicemodelprotocolexception the content type textxml charsetiso88591 of the response message does not match the content type of the binding textxml charsetutf8 if using a custom encoder be sure that the iscontenttypesupported method is implemented properlyhas anyone any idea how i call a webservice that is not utf8 using wcf,['.net'] +38539,how to become a good python coder i started with c but as we all know c is a monster i still have to take it and i do like c it takes programming a step further however currently i have been working with python for a while i see how you guys can turn some long algorithm into simple onei know programming is a progress and can take up to years of experiencei also know myself i am not a natural programmer and software engineering is not my first choice anyway however i would like to do heavy programming on my own and create projectshow can i become a better python programmer,['python'] +38541,simhash implementation in java has anyone come across a simhash function implemented in java i have already searched for it but could not find anything,['java'] +38545,uninstall of coderush and resharper intellisense not working install ordervisual studio 2008resharperuninstall resharpercoderush with refactor prouninstall coderush with refactor pro now my intellisense does not work any settings i should look at before i try a uninstall reinstall i am sure there must be something buried in the options that these plugins hook into or override,['.net'] +38546,c typecast array how can one typecast an array of int to an array of floatthanks,['c++'] +38548,chaining core animation animations which is the most elegant and modular way to chain animation in a core animation context i mean to do animations that starts just when other finished for example changing position and then opacity normal approach is to directly change propertieslayerposition new pointlayeropacity 00fbut this will do them at the same time i want to make one wait for the otherand what about chaining animations for different objects i have read about catransaction used likecatransaction beginlayer1property new propertycatransaction beginlayer2property2 new property2catransaction commitcatransaction commitbut it does not seem to work,['objective-c'] +38570,preferred jquery tooltip there are a bunch of jquery tooltip plugins out therewhich one should i use and why,['jquery'] +38575,how to get mouseup to fire once mousemove complete it seems that mouseup events are only fired when they are not in conjunction with a mousemove in other words push down on the left mouse button and let go and mouseup is fired but if you drag across the image and then let go no mouseup is fired here is an example that shows this behaviorscript srcscriptdiv idout img idimg src width500divscript languagejavascript function documentbindmouseupfunction alertup outbindmouseupfunction alertup imgbindmouseupfunction alertup scriptif you load this and click and let go up will alert however if you drag and then let go no up is firedhow can i have mouseup fire when mousemove is completed or how can i inspect the mousemove event to determine that the left mouse button is now off,"['javascript', 'jquery', 'html']" +38597,detecting individual unicode character support with javascript is it possible to detect if the client supports a particular unicode character or if it will be rendered as a missing glyph boximportant support in as many browsers as possiblenot important efficiency speed or elegancethe only method i can think of trying is using a canvas so i figured i would ask before i start going down that roadthanksedit this is not intended for use on a public web site i am just trying to compile a list of characters supported by each browser,['javascript'] +38604,make div text thisappear after 5 seconds using jquery i need to make a div text thisappear after x seconds of thisplaying it using an ajax callcan you help me on this please thanks,"['javascript', 'jquery']" +38613,design pattern question for maintainability i am not sure if there is a pattern that should be used here but here is the situationi have a number of concrete classes that implement an interfacepublic interface iperformaction bool shouldperformaction void performactioni have another class that checks input to determine if shouldperformaction should be execute the rub is that new checks are added fairly frequently the interface for the checking class is defined as followspublic interface ishouldperformactionchecker bool checkastring a bool checkbstring b bool checkcint c etcfinally i currently have the concrete classes call each of the checker methods with the data specific to that concrete classpublic class concreteclass iperformaction public ishouldperformactioncheck shouldperformactionchecker get set public string property1 get set public string property2 get set public int property3 get set public bool shouldperformaction return shouldperformactioncheckercheckathisproperty1 shouldperformactioncheckercheckbthisproperty2 shouldperformactioncheckercheckcthisproperty3 public void performaction do something class specific now each time i add a new check i have to refactor the concrete classes to include the new check each concrete class passes different properties to the checking method so subclasses the concrete classes is not an option any ideas on how this could be implemented in a cleaner manner,['c#'] +38614,nested ssh session with paramiko i am rewriting a bash script i wrote into python the crux of that script wash t firstcom ssh secondcom very remote commandi am having a problem with the nested authentication with paramiko i was not able to find any examples dealing with my precise situation but i was able to find examples with sudo on a remote hostthe first method writes to stdinsshconnect127001 usernamejesse passwordlolstdin stdout stderr sshexec commandsudo dmesgstdinwritelolnstdinflushthe second creates a channel and uses the socketlike send and recvi was able to get stdinwrite to work with sudo but it does not work with ssh on the remote hostimport paramikossh paramikosshclientsshset missing host key policyparamikoautoaddpolicysshconnectfirstcom usernameluser passwordsecretstdin stdout stderr sshexec commandssh stdinwritesecretstdinflushprint out print stdoutreadlinesprint error print stdereadlineshcloseprints out error pseudoterminal will not be allocated because stdin is not a terminalrn permission denied please try againrn permission denied please try againrn permission denied publickeypasswordkeyboardinteractivernthe pseudoterminal error reminded me of the t flag in my original command so i switched to the second method using a channel instead of sshexec command and later i havet sshget transportchan topen sessionchanget ptyprint send ssh cmd print chansendssh print recv print chanrecv9chan topen sessionprint send password print chansendsecretprint recv print chanrecv9but it prints send ssh cmd and just hangs until i kill the processi am new to python and none too knowledgeable about networks in the first case why does sending the password work with sudo but not with ssh are the prompts different is paramiko even the right library for this,['python'] +38620,does php error reporting0 affect error logging or just thisplay does error reporting0 have any effect on error logging to file or does it just suppress onscreen error thisplaythanks,['php'] +38641,one step check for null value emptiness of a string i have a setter methodthen when another say generate method is run i need to check the value of my fieldsso in the case of string property i need to know if it contains the value or if it was not setso it may be null or something meaningful there are 3 possibilitiesand it is rather boring to check first for a null value if s nullthen for an empty stringif sisemptyis there a onestep check here you can tell me that i can initialize my string field with an empty string is it common but what if someone passes a null value to the setter method setsso do we always have to check if the object value is null or not before doing something with that objectwell yes a setter method can check it is values and also a getter method can return a nonnull value if the field is null but is it the only solution it s too much work in getters setters for a programmer to do,['java'] +38643,are there any credible alternatives to itext for programmatic pdf generation within java anyone come across anything else that is similar or close in qualityfeaturescheers,['java'] +38678,can i convert a swf file to an image format i need to take a swf flash file ideally from a url but i can read the file from thisk also and create an image preview of it png gif or jpeg is fine i am using adobe coldfusion 8 so i am looking for a java solution i need to get the first frame of the flash movie only many thanks in advance edit i need to do this on the server in javacf at runtime it is got to be automatic i am not looking for screengrab software,['java'] +38682,split a generatoriterable every and items in python splitevery i am trying to write the haskel function splitevery in python here is it is definitionsplitevery int e e splitevery n splits a list into lengthn pieces the last piece will be shorter if n does not evenly divide the length of the listthe basic version of this works fine but i want a version that works with generator expressions lists and iterators and if there is a generator as an input it should return a generator as an output tests should not enter infinite loop with generators or listsspliteveryitertoolscount 10spliteveryrange10 10 last piece must be shorter if and does not evenly divideassert splitevery5 range9 0 1 2 3 4 5 6 7 8 should give same correct results with generatorstmp itertoolsisliceitertoolscount 10assert listsplitevery5 tmp 0 1 2 3 4 5 6 7 8current implementation here is the code i currently have but it does not work with a simple list def splitevery 1n iterable res listitertoolsisliceiterable n while lenres 0 yield res res listitertoolsisliceiterable nthis one does not work with a generator expression thanks to jellybean for fixing itdef splitevery 2n iterable return iterableiin for i in range0 leniterable nthere has to be a simple piece of code that does the splitting i know i could just have different functions but it seems like it should be and easy thing to do i am probably getting stuck on an unimportant problem but it is really bugging me it is similar to grouper from but i do not want it to fill extra values def groupern iterable fillvaluenone grouper3 abcdefg x abc def gxx args iteriterable n return izip longestfillvaluefillvalue argsit does mention a method that truncates the last value this is not what i want eitherthe lefttoright evaluation order of the iterables is guaranteed this makes possible an idiom for clustering a data series into nlength groups using izipitersnlistizipiterrange95 0 1 2 3 4 should be 0 1 2 3 4 5 6 7 8,['python'] +38683,whats the best way to have multiple threads doing work and waiting for all of them to complete i am writing a simple app for my wife no less p that does some image manipulation resizing timestamping etc for a potentially large batch of images so i am writing a library that can do this both synchronously and asynchronously i decided to use the eventbased asynchronous pattern when using this pattern you need to raise an event when the work has been completed this is where i am having problems knowing when it is done so basically in my downsizeasync method async method for downsizing images i am doing something like this public void downsizeasyncstring files string destination foreach var name in files string temp name countering the closure issue threadpoolqueueuserworkitemf string newfilename thisdownsizeimagetemp destination thisonimageresizednewfilename the tricky part now is knowing when they are all complete heres what i have considered using manualresetevents like here but the problem i came across is that you can only wait for 64 or less events i may have many many more imagessecond option have a counter that counts the images that have been done and raise the event when the count reaches the totalpublic void downsizeasyncstring files string destination foreach var name in files string temp name countering the closure issue threadpoolqueueuserworkitemf string newfilename thisdownsizeimagetemp destination thisonimageresizednewfilename total if total fileslength thisondownsizecompletednew asynccompletedeventargsnull false null private volatile int total 0now this feels hacky and i am not entirely sure if that is thread safeso my question is whats the best way of doing this is there another way to synchronize all threads should i not be using a threadpool thanksupdate based on feedback in the comments and from a few answers i have decided to take this approachfirst i created an extension method that batches an enumerable into batches public static ienumerableienumerablet getbatchestthis ienumerablet source int batchcount for ienumerablet s source sany s sskipbatchcount yield return stakebatchcount basically if you do something like this foreach ienumerableint batch in enumerablerange1 95getbatches10 foreach int i in batch consolewrite0 i consolewriteline you get this output1 2 3 4 5 6 7 8 9 1011 12 13 14 15 16 17 18 19 2021 22 23 24 25 26 27 28 29 3031 32 33 34 35 36 37 38 39 4041 42 43 44 45 46 47 48 49 5051 52 53 54 55 56 57 58 59 6061 62 63 64 65 66 67 68 69 7071 72 73 74 75 76 77 78 79 8081 82 83 84 85 86 87 88 89 9091 92 93 94 95the idea being that as someone in the comments pointed out there is no need to create a separate thread for each image therefore i will batch the images into machinecores 2 number of batches then i will use my second approach which is simply to keep a counter going and when the counter reaches the total i am expecting i will know i am donethe reason i am convinced now that it is in fact thread safe is because i have marked the total variable as volatile which according to msdnthe volatile modifier is usually used for a field that is accessed by multiple threads without using the lock statement to serialize access using the volatile modifier ensures that one thread retrieves the most uptodate value written by another threadmeans i should be in the clear if not please let me knowso heres the code i am going with public void downsizeasyncstring files string destination int cores environmentprocessorcount 2 int batchamount fileslength cores foreach var batch in filesgetbatchesbatchamount var temp batchtolist counter closure issue threadpoolqueueuserworkitemb foreach var item in temp string newfilename thisdownsizeimageitem destination thisonimageresizednewfilename total if total fileslength thisondownsizecompletednew asynccompletedeventargsnull false null i am open to feedback as i am in no way an expert on multithreading so if anyone sees any issue with this or has a better idea please let me know yes this is just a home made app but i have some ideas on how i can use the knowledge i gain here to improve our search index service we use at work for now i will keep this question open till i feel like i am using the right approach thanks everyone for your help,['c#'] +38687,what doctype is recommended for my html output for ie7ie8ff3 and how can i update my html validation in visual studio to reflect that change i noticed that visual studio defaults the doctype to xhtml 10 transitional this seems okay but i think that is more of a standard for generation 6 browsers were now in gen 7 and 8 browsers and i am wondering what doctype i should be putting in my htmlon a related note is there a way to add other doctypes to the html validation in visual studio 2008 tools options text editor html validation,['html'] +38697,boostbind boostfunction pointers to overloaded or templated member functions i have a callback mechanism the classes involved areclass app void oneventconst myevent event void oneventconst myotherevent event connector connectclass connector template class t void subscribeboostfunction void const t callbackappapp connectsubscribemyeventapponeventmyeventfirst off this code does not compile it is an illustration the use of templates complicates my example but i left them in because its affecting my problem it seems certain to me that my subscribe needs to be templated because the connector class does not know how many event types it handles when i try to create aboostfunction f apponeventi tried creating onevent as a template function with specializations but it seems that the compiler is treating my onevent functions as overloads rather than template specializations or else i get the template specialization not in namespace error if i try to explicitly declare it as template oneventconst myevent e i can get the following to compileboostfunction void app const myevent f apponeventfthis ethat compiles runs and worksboostfunctionvoid const myevent g boostbindapponevent thisdoes not i think its because i am not correctly specifying the address of an overloaded function having now explained all this to the teddy bear i think that my question is how do i correctly create a function pointer to an overloaded or templated member function and bind the this pointer to it,['c++'] +38698,when do you worry about stack size when you are programming in a language that allows you to use automatic allocation for very large objects when and how do you worry about stack size are there any rules of thumb for reasoning about stack size,['c++'] +38701,objc setassociatedobject unavailable in iphone simulator in the 31 sdk apple added support for associated objects however the simulator will not compile code that includes references to objc setassociatedobject objc getassociatedobject et al undeclared errorsis there away around this can i make the iphone simulator compile this code i would hate to have to do all testing on the deviceupdatebug filedrdar7477326,"['iphone', 'objective-c']" +38705,more fluent c net a coworker of mine came up with this and i wonder what others think personally i find it interesting but wonder if it is too big a departure code examples below extension methods at the bottomgeneral thoughts please other extension methods that could be addedvar ddl pagefindcontrollocationdropdownlist as dropdownlistddlvisible trueddlselectedvalue 123ifisadmin ddl selectedvalue 1becomespagefindcontrollocationdropdownlist castasdropdownlist withd dvisible true withd dselectedvalue 123 withifisadmin d ditemsaddnew listitemadmin 1or pagefindcontrollocationdropdownlist castasdropdownlist withd dvisible true dselectedvalue 123 withifisadmin d dselectedvalue 1extension methodspublic static tresult castastresultthis object obj where tresult class return obj as tresultpublic static t withtthis t t actiont action if action null throw new argumentnullexceptionaction actiont return tpublic static t withiftthis t t bool condition actiont action if action null throw new argumentnullexceptionaction if condition actiont return t,['c#'] +38716,need to read android sensors really fast issuei am developing a application whichneeds a new acceleration datum every 5millisecondmy approachi have created a remote servicewhich only reads the accelerationdata from sensormanageri had also set the read rate todelay fastest while initialize thesensormanagerthen i use ipc to communicate too mymain application to get thesereadingproblemif i put a log insideonsensorchange event i receive anew sensor data every 20 ms time but i need data every 5 msquestion is there any better method to readthe senor data fasteris there any way i can poll thesenor data rather that waiting forthe event handler to trigger theeventplease help me to find a better solution to read the data in 5 ms time or poll the acceleration data,['android'] +38731,di and singleton pattern in one implementation i want to refactor some code using the windsor iocdi framework but my issue is that i have some singleton classes and factory pattern classes and i am not sure that one can implement a singleton or factory using dihas anyone any ideas if that is possible and how,['c#'] +38738,how to avoid the unresponsive script popup in firefox with long running javascript i want to benchmark some javascript code in the browser but it may trigger firefoxs warning unresponsive script popup this allows the user to click stop script in the event that the browser is caught in a runaway function while the popup is thisplayed the currently running function has been halted this is not ideal so is there a way to run my benchmarks differently such that firefox does not popup this warning and ruin my results,['javascript'] +38748,howto start eclipse in jdk i just installed a maven plugin into eclipse the first time now there is a message on eclipse startup that i should start eclipse in jdk not jre to make maven components run fine there is a vm argument which i used in the eclipseinivm cprogram files x86javabut the message is still there after restarti have tried the cprogram files x86javabinand also the cprogram files x86javabinjavaexebut nothing changedhow do i start eclipse in jdkthanks in advance,['java'] +38750,a gina replacement in a net language i have searched quite a lot of places and i only found one gina replacement called pgina but it is in c which i do not know at alldoes anybody know one in either c or vbneti am writing software for use at work to control what employees are doing,"['c#', '.net']" +38755,how do we compare 2 class names of an object is there a way to get compare class name betwen 2 objectslikensstring bla nsstring alloc initifbla class isequal nsstring nslogsuccessunsure if my syntax is correct,['objective-c'] +38756,thisable html warnings in eclipse with eclipise for java ee developers edition i am working on a web app with eclipse for java ee i have jsp files that are built with html files as includes my indexjsp looks like thisjspinclude pageincludetophtml titletitletitlejspinclude pageincludeheaderhtml jspinclude pageincludemenuhtml div claspan15 prepend1 last h6what is an a href programming interfaceapiah6 pan application programming interface api is an interface that software programs implement in order to allow other software to interact with it much in the same way that software might implement a user interface in order to allow humans to interact with itp divjspinclude pageincludefooterhtml the problem is with the includes footerhtml looks like this hr h3 classaltba hrefcopyrighthtmlcopyrighta copy 2009b my company all rights reservedh3 hr p visit a hrefhomea p div bodyhtmlwhich gets put at the bottom of most pages and i am really annoyed with these warning messages like invalid location of tag body i know its invalid within this file but the other side belongs with headerhtmlin java classes you can suppress warnings with things like suppresswarningsserial any way to do something like this with these html or jsp files,"['java', 'html']" +38788,android sdk setup under windows 7 pro 64 bit the short version of my issue at hand windows 7 professional x64java jdk 160 17 x64eclipse galileo wadt plugin installedandroid sdktools r04since the android sdk download now only includes the tools you have to run the included sdk manager application sdk setup through which you can download the platforms additional tools docsetcunder my current configuration sdk setup bombs on launch so i cannot do anything since i do not have a single platform to start writing againsti have read a few places that the fix is just install the 32 bit jdk and all will be well that seems surprising and thisappointing option for a work arounddownloading it now to trymy question is this anyone else run into this same issue and how did you get past it is there a place i can download by hand the components i need that i missed on the android sdk site odds are pretty good that the 32 bit fix will work but that seems wrong that i will have to install a secondary version of the same sdkjre just to run this tool and to download the actual android sdk componentsthanksupdate well the work around that requires you to also install 32 bit java and referencing that as your java home worked either by calling the sdk setup manually or through eclipse i am not particularly happy with that so i will leave this one open for the time being in case there are other ways to get this done that people may know aboutupdate 2 not directly related since it is linux centric but there are troubleshooting steps if trying to run the sdkeclipse under linux 64bit where they reference the need to be able to run 32 bit but nothing similar under windows x64final update taking the info seths answer gave me and running the bat manuallyonce i knew what file sdk setup was running the answer for me was simply adding android swt path variable that pointed to a valid location with the x86 64 swtjarthe android sdk directory had one seemingly in the right place but it could not find it until i added that to my paththanks all,['android'] +38791,what is the differance between applets and swing what is the difference between applets and swing,['java'] +38796,get all elements in array besides the first one php is there a way to specify getting all but the first element in an array i generally use foreach to loop through my arrayssay array12345 i would only want 2 3 4 5 to show and for it to skip 1,['php'] +38802,need to run iphone app on simulator without using xcode i need to thistribute my app to be tested using iphone simulators so i built the binary and whenever i try to run the app by double clicking on it the app crashes with the error dyld error message library not loaded systemlibraryframeworksuikitframeworkuikit referenced from usersdeviphone workspacemd2finalbuildanalyzeriphonesimulatormd2finalappmd2final reason image not foundbut i have added the uikit to the project and am able to run the same application from xcode by using build and go is there a way i can build the binary in my xcode and thistribute only the binary to others for testing,['iphone'] +38813,c array initialization is this form of intializing an array to all 0s char myarrayarray size 0 supported by all compilers if so is there similar syntax to other types for example bool myboolarrayarray size false,['c++'] +38820,how can i remove the search bar and footer added by the jquery datatables plugin i am using jquery datatables i want to remove the search bar and footer showing how many rows there are visible that is added to the table by default i just want to use this plugin for sorting basically can this be done,"['jquery', 'html']" +38827,dynamic vs var possible duplicatewhats the difference between dynamicc 4 and var what is the difference between dynamic and var keyword in net 40 vs 2010 as per msdn the definition of dynamic is dynamic lookup allows you to write method operator and indexer calls property and field accesses and even object invocations which bypass the normal static binding of c and instead gets resolved dynamicallywhereas the definition for var is an implicitly typed local variable is strongly typed just as if you had declared the type yourself but the compiler determines the typehow is this different in the code context belowvar a1 new aa1foo1dynamic a2 new aa2foo1,['c#'] +38836,redirect back to a page after a login i am doing a simple forum with a series of servlets that each represent a home topic postedit login and userlist page on some of these pages there is a link that appears when a user is not logged inwhat i would like to achieve is to trigger a redirection using forward on a requestthispatcher after a login so the browser goes back to the page where a user was before clicking the login link in order to do this i see two solutionsthe first solution is to have an html form with a login button and an invisible field that will contain information that will say what page to redirect as a parameter this is doable but i would like to try something elsethe second solution is to add an attribute to the session that represents the first page in some way this could contain a string but this is no different from the first approach another twist would be to add a reference to the httpservlet and to use instanceof or a static string variable that could be used to identify the servlet in some way however this would require creating a common ancestor class for all the servletsperhaps there is another simple solution that you can see that would form a good compromise or maybe one of the above solutions is perfectly acceptable,['java'] +38849,resize an image c as size width height are get properties of systemdrawingimagehow can i resize an image object at runtime in cright now i am just creating a new image using objimage is the original imagebitmap objbitmap new bitmapobjimage new size227 171,['c#'] +38853,how to get the number of threads in a java process how can i see the number of threads in a java process,['java'] +38859,import a dll with c win32 how do i import a dll minifmoddll in c i want to be able to call a function inside this dll i already know the argument list for the function but i do not know how to call itis there a way of declaring an imported function in c like in c,['c++'] +38865,force browser to clear cache is there a way i can put some code on my page so when someone visits a site it clears the browser cache so they can view the changeslanguages used aspnet vbnet and of course html css and jquery,['html'] +38871,unpackextract zip file with php without relying on any extension is there any way to unpack or extract a zip file with php that does not rely on any installed extension has anyone written a class or something that can handle italternatively is there a solution that uses an extension that is relatively commonly installed on most serversi need this to work on as many different servers that i have no control over as possiblethanks for any help,['php'] +38880,how to draw a border at top of the linear layout i have followed the example in for the gradient dividersi have tried to draw a horizontal line at the bottom of my linear layouthere is my linear layout file linearlayout androidididtest androidlayout widthfill parent androidlayout heightwrap contentimageview androidididicon1 androidlayout width32dip androidlayout height32dipand i did add viewandroidbackgrounddrawableblack white gradientandroidlayout widthfill parentandroidlayout height1dpandroidlayout aboveidtestbut i do not see any line at the top of the linearlayout and when i go to hierarchy view and see he view for the hort separator the getwidth is 0 while getheight is 1can you please tell me what am i missingthank you,['android'] +38890,how to improve code folding in visual studio i want some automatic code folding for iftry etcit should be some code editor feature like one in vs for methods etcif i have this public frmmain initializecomponent if true try catch i want to get this public frmmain initializecomponent if true try catch even notepad can do this,['c#'] +38894,do not give away your internals c i am reading book called c coding standard by herb sutter andrei alexandrescu and in chapter 42 of this book is an examplechapter is short so i am taking the liberty and pasting part of itconsider class socket public a constructor that opens handle destructor that closes handle etc a int gethandle const return handle avoid this 1 why this is bad code and why there is a comment to avoid such code private int handle perhaps an os resource handle data hiding is a powerful abstraction and modularity device see items 11 and 41 but hiding data and then giving away handles to it is selfdefeating just like locking your house and leaving the keys in the lock this is becauseclients now have two ways to implement functionality they can use your clas abstraction socket or directly manipulate the implementation that your class relies on the sockets cstyle handle in the latter case the object is unaware of significant changes to the resource it thinks it owns now the class cannot reliably enrich or embellish functionality eg proxying logging collecting statistics because clients can bypass the embellished controlled implementationand any of the invariants it thinks it is adding which makes correct error handling next to impossible see item 70the class cannot change the underlying implementation of its abstraction because clients depend on it if socket is later upgraded to support a different protocol with a different set of lowlevel primitives calling code that fetches the underlying handle and manipulates it incorrectly will be silently brokenthe class cannot enforce its invariants because calling code can alter state unbeknownst to the class for example someone could close the handle being used by a socket object without going through a socket member function thus rendering the object invalidclient code can store the handles that your class returns and attempt to use them after your clas code has invalidated themthis is a summary from this bookdo not volunteer too much avoid returning handles to internal data managed by your class so clients would not uncontrollably modify state that your object thinks it ownsbasically what i am asking for is why line marked by me as 1 is listed as an example of bad code i always thought that returning pointers or reference is a bad idea but returning by value is ok here they are saying that returning by value is bad idea too is it possible that there is missing and what they really mean is to not return internal data by reference or pointers thank you,['c++'] +38904,mixing cout and printf for faster output after performing some tests i noticed that printf is much faster than cout i know that it is implementation dependent but on my linux box printf is 8x faster so my idea is to mix the two printing methods i want to use cout for simple prints and i plan to use printf for producing huge outputs typically in a loop i think it is safe to do as long as i do not forget to flush before switching to the other methodcout hello endlcoutflushfor int i0 i10 i printfworldnfflushstdoutcout last line endlcout flushis it ok like thatupdate thanks for all the precious feedbacks summary of the answers if you want to avoid tricky solutions just simply do not use endl with cout since it flushes the buffer implicitly use n instead it can be interesting if you produce large outputs,['c++'] +38907,how to detect if rails is at the root url what i want is seems simplein my application helper i setup thismodule applicationhelperdef isrootif root url container mainboxelsecontainer maincontainerboxendendendin my application layout i have this div id isroot how do i find out if my application is at the homepage if not do something else,['ruby-on-rails'] +38916,how to speed up android emulation i am trying to get started with android development i am using eclipse on linux and using a pentium iv 32gh with 1gb of rami have just followed the hello android howto with just one sad result the virtualization is too slow it seems that launching the virtual machine has to be slow and it will be slow even if i will use a better computer with slow i mean it takes almost 10 minutes to see hello android and if i change it to hello world it takes an other 10 minutes how can i solve it is it possible to make eclipse load again my app in the current and running virtual machine without opening a new one,['android'] +38926,rules engine in c or python i am looking for a rules engine in c or python but if you know a rules engine that is implemented in another language i would be glad to know about itthe engine will be used as way to automate a house like turning the light off when somebody leaves a room etc so no office rules there aka do you rules in excel or suchi have looked into jess and drools which are in java and do a perfect job i would like to know of others and possibly using less memory than java doesi have heard of rulecore in python but could not really find any documentation on it version 10 is available at sourceforge but it looks like they are selling v 20edit by rules engine inference engine i mean an implementation of rete or equivalent,"['java', 'python', 'c']" +38934,why should i use wpf over winforms any examples of wpf outperforming winforms there is a similar question at which has some good information but in my personal experience i see no reason to use wpf over winforms with wpf initially there was lots of talk about it is multithreaded functionality but in use i see no benefitsi have two applications that do the same thing one in wpf and on in winforms the winforms application blows the wpf application away in terms of performance by a factor of 10 and looks just as nice granted i am more proficient in winforms applications than wpf,['.net'] +38953,change page on uiscrollview i have a uiscrollview with 10 pages i am able to flick between them i also want to have 2 buttons a back button and a next button which when touched will go to the previous or next page i cannot seem to figure out a way to do this though a lot of my code comes from apples page control sample code can anybody helpthanks,['iphone'] +38969,use variable with top in select statement in sql server without making it dynamic declare top intset top 5select top top from tablenameis it possibleor any idea for such a logic i do not want to use dynamic query,['sql'] +38974,how to get the size of the current screen in wpf i know i can get the size of the primary screen by usingsystemwindowssystemparametersprimaryscreenwidthsystemwindowssystemparametersprimaryscreenheightbut how do i get the size of the current screen multiscreen users do not always use the primary screen and not all screens are using the same resolution rightit would be nice to be able to acces the size from xaml but doing so from code c would suffice,['c#'] +38975,how to verify background css image was loaded i have the following css classbg backgroundimage urlbgjpg thisplay nonethat i am applying on a td tagmy question is how can i tell with javascriptjquery that the background image finished loadingthank youupdate added thisplay propertysince my main objective it toggle it into view,"['javascript', 'jquery', 'css']" +38976,compare two images the pythonlinux way trying to solve a problem of preventing duplicate images to be uploadedi have two jpgs looking at them i can see that they are in fact identical but for some reason they have different file size one is pulled from a backup the other is another upload and so they have a different md5 checksum how can i efficiently and confidently compare two images in the same sense as a human would be able to see that they are clearly identicalexample and update i wrote this scriptimport math operatorfrom pil import imagedef comparefile1 file2 image1 imageopenfile1 image2 imageopenfile2 h1 image1histogram h2 image2histogram rms mathsqrtreduceoperatoradd maplambda ab ab2 h1 h2lenh1 return rmsif name main import sys file1 file2 sysargv1 print comparefile1 file2then i downloaded the two visually identical images and ran the script output589830484122can anybody tell me what a suitable cutoff should beupdate iithe difference between ajpg and bjpg is that the second one has been saved with pilbimageopenajpgbsaveopenbjpgwbthis apparently applies some very very light quality modifications i have now solved my problem by applying the same pil save to the file being uploaded without doing anything with it and it now works,['python'] +38979,setting far future expires header in code aspnet is there a way that i can programmatically set an expires header in code with aspnet specifically i need to set it on an entire folder and all subfolders and the folder contains only static files javasciprt css images etc and not aspx files so i cannot just add some code to an aspx codebehind page loadi can normally set this directly in iis but the server is locked down by the client i only have ftp access to web app directory for deployments and getting the client to set the expires header on iis would take an ice age it is a public sectorgovernment sitei am doing this for frontend optimisation reasons as per yahoos recommendations update i have tried creating an httpmodulepublic class farfutureexpiresmodule ihttpmodule public void thispose public void inithttpapplication context contextbeginrequest new eventhandlercontext beginrequest void context beginrequestobject sender eventargs e httpcontext context httpcontextcurrent string url contextrequesturltostring if urlcontainsstaticcontent contextresponsecachesetexpiresdatetimenowaddyears30 although this does not see to work i have placed a breakpoint on the code and it appers to run correctly however when i analyse the raw http header information in firefox the expires value is not being set notice i am using beginrequest but i have also tried hooking into postreleaserequeststate and presendrequestheaders and they do not seem to work either any ideasupdate 2 ok so it seems because i am running iis6 httpmodules would not run for static files only dynamic files aspx etc thanks to ricknzs help i came up with the following ihttpmodulepublic class farfutureexpiresmodule ihttpmodule public void thispose public void inithttpapplication context contextbeginrequest new eventhandlercontext beginrequest void context beginrequestobject sender eventargs e httpcontext context httpcontextcurrent string url contextrequesturltostring if urlcontainsstaticcontent contextresponsecachesetexpiresdatetimenowaddyears30 contextresponsecachesetmaxagetimespanfromdays3650 30 and it seems to work but only in the builtin web server in visual studio and in iis7 when in intergrated pipeline mode a work colleague mentioned setting wildcard mappings on iis6 to get httpmodules to work on static files but if i have access to iis6 i could just set the farfuture expires header directly and not bother with this httpmodule oh well,"['c#', 'asp.net']" +38983,command binding in hierarchical datatemplate i have menu in my app i am visualizing it using hierarchical data template menuitem headermain menu itemssourcebinding applicationmenu menuitemitemtemplate hierarchicaldatatemplate datatypextype tmrmenuitem itemssourcebinding pathchildrenitems menuitem headerbinding name commandbinding runoperationcommand hierarchicaldatatemplate menuitemitemtemplate menuitemmenu looks like as it should but command for each menu item is not fired even more it is not bounded which could be seen in debugger get accessor of icommand property has been never executedwhy it happens sodoing as usual works perfectmenu menuitem headersomeheader commandbinding runoperationcommandmenu,['.net'] +38991,which should generate the html javascript or php merry christmas and seasons greetings allquick question looking for some recommendations i have a site that will be requesting data from a database and thisplaying back to the user in a table i am using jquery ajax php and mysql where is the best place to generate the html for the table to thisplay the data should the php generate it and send the whole thing html data back from the server or should the php just send back the data and the jquery code make the table and insert the dataalthough this is running on an intranet the i would still prefer the speediest approachthanks in advanceupdatei wanted to add a little additional information to this topic in case it might be useful to others i agreed totally with the separation idea presented here and went with that as my design approach i used php to retrieve and organize the required data into json and then used jquery to generate the html to thisplay the returned information in this case i was creating a spreadsheet style table form using jquery and populating cells that had values as returned from the php with a few rows and columns things ran fine but as i increase to say a 16 x 16 table dynamically creating the input elements with jqueryat this point i once again ran up against the ugly spectre that is ie6ie6 is still the approved browser where i work so my app has to function on it when i test my design on firefox and opera the interface loads fast and is a pleasure to use when i run the same code in ie6 it takes far too long to generate the interface long enough that my users would start clicking things again thinking the app was not responding i can only chalk this up to the javascript engine that is in ie6 since the code runs fine in the newer browsers so because of this i am back to a redesign for part of the interface to have the php generate at least the inner table form elements populate with data and then send that back to the client it breaks the nice separation i wanted but i do not see any other way to speed things up on the client side in ie6anyway just thought others might be interested in the results here and for other beginners like me how much browser support requirements can affect design choicesthanks,"['php', 'javascript', 'html']" +38997,any good c or c libraries out there for dealing with large point clouds basically i am looking for a library or sdk for handling large point clouds coming from lidar or scanners typically running into many millions of points of xyzcolour what i am after are as followsfast thisplay zooming panningpoint cloud registrationfast low level access to the dataregression of surfaces and solids not as important as the otherswhile i do not mind paying for a reasonable commercial library i am not interested in a very expensive library eg in excess of about 5k or one with a per user runtime license cost open source would also be good i found a few possibilities via google but they all tend to be too expensive for my budget,['c++'] +39004,for realtime application which is better c or c iam electronic engineer with experience with both language c and c i wrote with c for microcontroller and with c i wrote for windows with borland c buildermy company develops motor control products and we are working with stm32 and iar compileri recognize the technical differences between the languages i interest in the development coast and in the maintenance cost of the codeis the development time of writing c code is longer then cis the maintenance cost of c code is cheaper then c i know that always will be changes in the codeis it easy to documents code in c against c documents that describe how the code works,"['c++', 'c']" +39013,net how to make a class such that only one other specific class can instantiate it i would like to have the following setupclass descriptor public string name get private set public ilistparameter parameters get private set set to readonlycollection private descrtiptor public descriptor getbynamestring name magic here caching loading parsing etc class parameter public string name get private set public string valuie get private set the whole structure will be readonly once loaded from an xml file i would like to make it so that only the descriptor class can instantiate a parameterone way to do this would be to make an iparameter interface and then make parameter class private in the descriptor class but in realworld usage the parameter will have several properties and i would like to avoid redefining them twiceis this somehow possible,"['c#', '.net']" +39021,c send structure objects through socket i have done a bit of reading in clientserver programming in c i am familiar enough with this process to ask the following questionhow do i transmit structure objects through tcpip instead of just stringsmy app is a networked game with chat capabilities so instead of just transmitting text i would like to imploy a data structure or class structure that will have two fields i packet type ii the data for the packet typeand i would transmit this when needed during the execution of the application and decode the data object at the receiving end and place it where it belongsim not looking for code just some ideas and search statements i can feed to google so i will have a better understandingive read about serialisationde serialisation is that he way to gothanksi have checked the posts that showed up as related topics but would still like further guidence,['c#'] +39042,what is the easiest way to programmatically extract structured data from a bunch of web pages what is the easiest way to programmatically extract structured data from a bunch of web pagesi am currently using an adobe air program i have written to follow the links on one page and grab a section of data off of the subsequent pages this actually works fine and for programmers i think thisor other languages provides a reasonable approach to be written on a case by case basis maybe there is a specific language or library that allows a programmer to do this very quickly and if so i would be interested in knowing what they are also do any tools exist which would allow a nonprogrammer like a customer support rep or someone in charge of data acquisition to extract structured data from web pages without the need to do a bunch of copy and paste,"['c#', 'java']" +39053,configuring extension modules with thistutilssetuptools i have a python project with mutiple extension modules written in c which talk to a thirdparty library however depending on the users environment and options some modules should not be built and some compiler flags should be enabledthisabled the problem is that i have to build the list of extension modules before i call setup and ideally i would like to use a thistutilscommand subclass to handle the user options right now i have a few optionsrequire a python setuppy configure command be run before building the modules store the information in a pickle file and use it to generate the extensions list next time the script runs this is how my project currently works which seems quite sillymanually scrape options out of sysargv and use them to build the list this is not a longterm solution because i will eventually want to run some scripts to check the settings before buildingsubclass build ext from thistutils do my configuration in the beginning of the run method possibly also using options sent via 2 and directly modify selfthistributionext modules before building i am afraid this may confuse setuptools however as it may assume the list of extension modules is fixed when setup is called it also means that when setup is called with a command other than build ext the list of extension modules is emptyis there a preferred way to do this,['python'] +39058,getting rid of table spool in sql server execution plan i have a query that creates several temporary tables and then inserts data into them from what i understand this is a potential cause of table spool when i look at my execution plan the bulk of my processing is spent on table spool are there any good techniques for improving these types of performance problems would using a view or a cte offer me any benefits over the temp tablesi also noticed that when i mouse over each table spool the output list is from the same temporary table,['sql'] +39066,c why resize image will increase the file size i have image file which is 6k jpg file with width 172px and hight 172pxi use the following code try to resize it to 128128px jpg filepublic static image resizeimageimage img int width int height var b new bitmapwidth height pixelformatformat24bpprgb using graphics g graphicsfromimageb gdrawimageimg 0 0 width height return b this code has strangely increased the file size to 50k can any one explain why and how to resize the image to 128128px and keep the size about 6k many thanksdy,['c#'] +39071,what is the correct way to format a datetime in sql server datetime field i have a datetime object in c and i want to do an insert into sql server datetime field what is the correct format for this,"['c#', 'sql']" +39077,why does not scanf need an ampersand for strings and also works fine in printf in c i am learning about strings in c nowhow come to use scanf to get a string you can do scanfsstr1and for printf you can doprintfthe string is sn str1i understand that for scanf it is because the string is just a character array which is a pointer but for printf how is it that you can just put the variable name just like you would for an int or float,['c'] +39080,can android do peertopeer adhoc networking is it possible to set up android in adhoc peertopeer wifi mode for example i would like to have one phone broadcast a message and have all peers in the network receive the broadcast without having a server i would like to use wifi since bluetooth range is more limited,['android'] +39096,copy constructor not called but compiler complains that there is no given the following codeinclude boostnoncopyablehppenum error err ok0 struct filter private boostnoncopyable filter virtual filter virtual int filterint data const 0struct specialfilter public filter private boostnoncopyable inline specialfilterunsigned int min unsigned int max minmin maxmax virtual specialfilter virtual int filterint data const return err ok unsigned int min unsigned int maxstruct aclass aclass aclassconst aclass other aclass int specialfilterint channel int minthreshold int maxthreshold return filterchannel specialfilter123 321 int filterint channel const filter filter return err ok my compiler gcc 42 complains warning direct base aboostnoncopyable noncopyablea inaccessible in aspecialfiltera due to ambiguity noncopyablehpp in copy constructor afilterfilterconst filtera noncopyablehpp27 error aboostnoncopyable noncopyablenoncopyableconst boostnoncopyable noncopyablea is private synthezised method first required here return filterchannel specialfilter123 321but i do not call the copy constructor,['c++'] +39101,confusing operation of javascript var keyword iave run into a very strange to me problem with the var keyword iave reduced it to a fairly minimal test case and found itas exhibited in nodejs thus v8 and chrome safari 4as inspector thus nitro and firebug obviously spidermonkey i was originally preparing a bug report but since itas so widely thisplayed iam going to assume that i completely misunderstand how javascript is supposed to scope and look up variablesthe test case is very small and on github here the only difference between the first and second example is the inclusion of the var keywordhere as well is a similar test case that exhibits the same aproblema in a different way edit to preclude any more answers attempting to explain how cascading scope works iam intimately familiar with that my problem is that i donat understand why the following code aworksa in that it alerts aoutera followed by ainnera and then again aouterafunction var foo outer alertouter foo foo function foo inner alertinner foo foo var foo alertouter foo foothe var foo occurs in a completely irrelevant position to the reaassignment of foo so why does it affect that assignment in a very substantial way,['javascript'] +39107,ccli why should i use it i am pretty familiar with c so i considered learning net and all its derivatives especially calong the way i bumped into ccli and i want to know if there is any specific use for that language is it just suppose to be a intermediate language for transforming from native c to canother question that popped to my head is why are there still so many programming languages in net framework vb ccli c,"['c#', '.net']" +39109,convert a date to string in javascript i am looking for a way to convert a javascript date object to a string i am converting my site from ruby to server side javascript and i am looking for something analogous to strftime in ruby c and many other languagesi found plenty of simple scripts that do this kind of conversion but i would prefer not to include a custom implementation if there is a standard way of doing thisi am not using a javascript framework i am using mozilla rhino but would prefer to stay away from using the java library as much as possible to allow moving my code easily between implementationsi want to be able to specify the format of the string since i want to embed it in a sentence i want to be able to insert arbitrary ons and ats and have the full name of the day not just it is abbreviation so tostring would not suffice,['javascript'] +39122,how do i insert datetime value into a sqlite database i am trying to insert a datetime value into a sqlite database it seems to be sucsessful but when i try to retrieve the value there is an errorunable to read datathe sql statements arecreate table mytable name varchar25 mydate datetimeinsert into mytable namemydate values fredjan 1 2009 132215,['sql'] +39146,is comparing a bool against yesa dangerous i found a comment today in a source file no longer compare bool against yes dangerousis comparing bool against yes in objectivec really that dangerous and why is that can the value of yes change during runtime maybe no is always 0 but yes can be 1 2 or 3 depending on runtime compiler your linked frameworks,['objective-c'] +39150,numpy to matlab interface with mlabwrap i am looking for a simple way to visualize some of my data in numpy and i thiscovered the mlabwrap package which looks really promising i am trying to create a simple plot with the ability to be updated as the data changes here is the matlab code that i am trying to duplicate h plot123 123 o seth xdata 0 drawnowto python from mlabwrap import mlab h mlabplot123 123 o mlabseth xdata 0 mlabdrawnowhowever the second to last command fails with an error message error one or more output arguments not assigned during call to setany suggestions on how to fix this,['python'] +39159,how to handle large file uploads via wcf i am looking into using wcf for a project which would require the ability for people to upload large files 64mb1gb to my server how would i handle this with wcf possibly with the ability to resume uploads in order to handle a larger client base i wanted to test out json via wcf how would this affect the file upload can it be done from json or would they need to switch to rest for the upload portion,['c#'] +39160,representing a 100k x 100k matrix in java how can i store a 100k x 100k matrix in javai cannot do that with a normal array declaration as it is throwing a javalangoutofmemoryerror,['java'] +39161,can i use apc and memcached on the same server i am using memcache for cacheing objects but would like to add in addition an opcode accelerator like apc since they both involve cacheing i am not sure if they will be stepping on each others toes ie i am not sure if memcache is already an op code accelerator can someone clarify i would like to use them both bit for different things memcache for cacheing my objects and apc for code acceleration,['php'] +39163,deploying to multiple heroku instances i have read a couple of the other posts on this issue but seemed to be stumped on something i am trying to have two separate branches that push out to two different heroku instances one production and one staging i suppose my setup will look as followslocal myapp master master myappstaging edge masteri have the following commands but for some reason i do not seem to be able to push to the staging service correctly git push staging master goes through but i cannot figure out why the changes do not seem to be getting reflected on the heroku instance when i go to myappstagingherokucom i might be doing something sill heredevgit checkout edgegit push staging master is this master or edgeheroku rake dbmigrate app myappstagingproductiongit checkout mastergit push master masterheroku rake dbmigrate app myappany help would be tremendously appreciated,['ruby-on-rails'] +39176,set ahover based on class i have the following htmldiv classmenu a classmainnavitem hrefhomehomea a classmainnavitemcurrent hrefbusinessbusinessa a classmainnavitem hrefaboutmeabout meadivin css i want to set the ahover for these menu items to a particular color so i writemenu ahover colordbut i want to set this ahover color only for those a tags with the class mainnavitem and not the mainnavitemcurrent because it has a different color and should not change on hover all a tags within the menu div should change color on hover except the one with the current classhow can i do it using cssi tried something likemenu ahover mainnavitem colordthinking that only ones with mainnavitem class will change color on hover and not the current one but it is not working,"['html', 'css']" +39183,how do i delete an embedded document in mongomapper hi guys i run a sinatra application with mongomapper i have models called moviedocument and coverembeddeddocumenti embed covers into movies usingmoviecovers covermoviesavethis works greatwhen hit moviescovers i got the array of embedded documentsbut i am not able to destroy the embedded document i tried something like thismoviecoverseach do ccdestroyendnomethoderror undefined method destroy for cover0xb7b20734 from irb5 from usrlibrubygems18gemsmongo mapper068libmongo mapperassociationsproxyrb85in call from usrlibrubygems18gemsmongo mapper068libmongo mapperassociationsproxyrb85in method missing from usrlibrubygems18gemsmongo mapper068libmongo mapperassociationsproxyrb85in each from usrlibrubygems18gemsmongo mapper068libmongo mapperassociationsproxyrb85in send from usrlibrubygems18gemsmongo mapper068libmongo mapperassociationsproxyrb85in method missing from irb4 from 0can anyone temme how to destroy it it would be great if someone enlightens me how to update the embedded document,['ruby-on-rails'] +39190,is it true that i cannot use curly braces in python i was reading that python does all it is code blocks by indentation rather than with curly braces is that right so functions ifs and stuff like that all appear without surrounding their block with curly braces,['python'] +39193,ruby on rails collection select thisplay attribute i am new to rails and am working with the collection select methodi have two fields i would like to thisplay in my select boxfirst name and last nameso far i can only thisplay one or the other not bothheres the code i am working withcollection selecthourshopper idshoppersidlast namethank you,['ruby-on-rails'] +39203,aspnet mvc 2 problem with updatemodel i am trying to use updatemodelmyitem formcollection with aspnet mvc 2 but it fails with the stack trace below at systemwebmvcformcollectiongetvaluestring name at systemwebmvcdefaultmodelbinderbindmodelcontrollercontext controllercontext modelbindingcontext bindingcontext at systemwebmvccontrollertryupdatemodeltmodeltmodel model string prefix string includeproperties string excludeproperties ivalueprovider valueprovider at systemwebmvccontrollertryupdatemodeltmodeltmodel model ivalueprovider valueprovider at stormbreakerdashboardcontrollersdashboardcontroller1updateformcollection collection in dprojectssvnstormbreakertrunkstormbreakerdashboardcontrollersdashboardcontrollercsline 23 at lambda methodexecutionscope controllerbase object at systemwebmvcreflectedactiondescriptorexecutecontrollercontext controllercontext idictionary2 parameters at systemwebmvccontrolleractioninvokerinvokeactionmethodcontrollercontext controllercontext actiondescriptor actiondescriptor idictionary2 parameters at systemwebmvccontrolleractioninvokerc thisplayclassdinvokeactionmethodwithfiltersb a at systemwebmvccontrolleractioninvokerinvokeactionmethodfilteriactionfilter filter actionexecutingcontext precontext func1 continuationmy action looks like this acceptverbshttpverbspost validateinputfalse public actionresult updateformcollection collection updatemodelcurrentitem collection currentitem t repositoryupdatecurrentitem return redirecttoactionedit new pagepath currentitemurlsegment and my form looks like this using htmlbeginformupdatedashboard formmethodpost new name editform div htmleditorformodel input typesubmit valuesave div,"['c#', 'asp.net']" +39217,jquery colorbox create a separate link to open the colorbox i am trying to open a jquery colorbox from a link outside the rest of the colorbox images so all of the examples look like thisa hrefimage1png relgroup1img srcthumb1png aa hrefimage2png relgroup1img srcthumb2png ascriptarelgroup1colorboxscriptok that is fine but i also need to open that colorbox from a separate linka href this link should also open the colorbox awhat do i have to put where to do that all of the colorbox examples just show whats in the first code block and i am no jquery expert,['jquery'] +39232,what language to learn for microcontroller programming i am getting into microcontroller programming and have been hearing contrasting views what language is most used in the industry for microcontroller programming is this what you use in your own work if not why notps i am hoping the answer is not assembly language,['c'] +39243,virtual directory not being configured as an application in iis i downloaded a testing website code from a site and i converted it to visual studio 2008 but i get the compilation error as followsit is an error to use a section registered as allowdefinitionmachinetoapplication beyond application level this error can be caused by a virtual directory not being configured as an application in iisanyone solve the problem plz,['asp.net'] +39244,coming from c to c hi alli have started a new job recently where i am supposed to work with c i have been doing programming in c language for past 5 years i am looking for ways to get me up to an acceptable level in oop i have all the basic concepts of c and oop but do not have much experience of actual class designingwhat i really am looking for is ways to learn class library designing as i will be working in a team who is writing c libraries for other programmers to use please suggest principles like responsibility assignment which can help me design classes in general,"['c++', 'c']" +39246,android application initialization i have an application that is driven by a configuration xml variousapp properties are loaded at the app starttime by parsing the xml andinitializing static variables of some class the data read from thisxml drives different activities of the application presently i havecalled the parsing and the propertiesinitialization from theoncreate of my main activityi have a few questions as regards this caseapproachshould i invoke the app initialization method from the applicationobject or is the current approach correct what advantagesthisadvantages dowould we gethave if i choose to invoke it from theapplication objectdo we really need a static class to store app properties or can we have all the properties as a static collection variable in the application objectparsing a xml200 nodes at app load time might take some timenotsure how long tho how can i avoid the dreaded anrs i am using apull parserplease help me find answers to these questionsthank you,['android'] +39248,c connecting through proxy i work in a office which requires all connections to be made through a specific http proxy i need to write a simple application to query some values from a webserver it is easy if there were no proxy how can i make the c application proxyaware how can i make any sort of connection through a proxy,['c#'] +39257,aspnet processmodel configuration optimization a regular aspnet installation will create machineconfig with the following configurationsystemweb processmodel autoconfigtrue i would like to override few properties values in webconfig likesystemweb processmodel maxworkerthreads100 maxiothreads100 minworkerthreads40 miniothreads30 memorylimit60 i would like to know that whether i have to write all default properties inside webconfig or it will automatically take other default properties of processmodel from machineconfigfollowing are the properties of processmodelprocessmodel enabletruefalse timeouthrsminssecsinfinite idletimeouthrsminssecsinfinite shutdowntimeouthrsminssecsinfinite requestlimitnuminfinite requestqueuelimitnuminfinite restartqueuelimitnuminfinite memorylimitpercent webgardentruefalse cpumasknum usernameusername passwordsecure password loglevelallnoneerrors clientconnectedcheckhrsminssecsinfinite comauthenticationleveldefaultnoneconnectcall pktpktintegritypktprivacy comimpersonationleveldefaultanonymousidentify impersonatedelegate responsedeadlockintervalhrsminssecsinfinite responserestartdeadlockintervalhrsminssecsinfinite autoconfigtruefalse maxworkerthreadsnum maxiothreadsnum minworkerthreadsnum miniothreadsnum servererrormessagefile pingfrequencyinfinite pingtimeoutinfinite maxappdomains20,['asp.net'] +39263,meta refresh count starts after page load or before meta httpequivrefresh content0 urldoes the count start from full page load or as soon as the page is loadinghaving tested it it looks to me it starts counting after full page loadi appreciate a confirm before i continue with this solution i did not like javascripts timeoutwill this play nicely with ie6,"['javascript', 'html']" +39286,syntax quirks or why is that valid python in python 26 why is the following line validmy line foo barand if that is valid why is not the followingmy list 1 2the first example is string concatenation however the following is not valid either thanks godfoo foobar barfoo bar foo bar,['python'] +39287,how can i abandon an ienumerator without iterating to the end consider the following code the first demonstrates that the cleanup executes when were finished iterating over the ienumerable of strings the second pass is what is causing me grief i need to be able abandon the ienumerable before reaching the end and then have the clean up code execute but if you run this youll see that in the second pass the clean up never fireswhat is the preferred way of abandoning an ienumerable like thisstatic void mainstring args first pass foreach string color in readcolors consolewritelinecolor second pass ienumeratorstring reader readcolorsgetenumerator if readermovenext consolewritelinereadercurrent readerthispose static ienumerablestring readcolors string colors red green blue for int i 0 i colorslength i yield return colorsi consolewritelinecleanup goes here,['c#'] +39297,syntax error caused by aspnet is this invalid to put in an aspx file i have some static aspx pages and i want to add a bit of c to one of them how can i do thisi figured just adding page languagecand then using to put a bit of c goodness in there but it says syntax error with a blue wavy line over this code,['asp.net'] +39299,google maps api v3 how do i dynamically change the marker icon using google maps api v3 how do i pro grammatically change the marker iconwhat i would like to do is when someone hovers over a link to have the corresponding marker icon on the map change colors to denote the marker in questionessentially the same function as what roost doeswhen you hover over a home listing on the left the corresponding marker on the right changes color,['javascript'] +39300,empty responsetext from xmlhttprequest i have written an xmlhttprequest which runs fine but returns an empty responsetextthe javascript is as follows var anurl var myrequest new xmlhttprequest callajaxanurl function callajaxurl myrequestopenget url true myrequestonreadystatechange responseajax myrequestsetrequestheadercachecontrol nocache myrequestsendnull function responseajax ifmyrequestreadystate 4 ifmyrequeststatus 200 result myrequestresponsetext alertresult alertwe made it else alert an error has occurred myrequeststatustext the code runs fine i can walk through and i get the readystate 4 and a status 200 but the responsetext is always blanki am getting a log error in safari debug of error thispatching getproperties which i cannot seem to find reference to i have run the code in safari and firefox both locally and on a remote serverthe url when put into a browser will return the string and give a status code of 200i wrote similar code to the same url in a mac widget which runs fine but the same code in a browser never returns a result,['javascript'] +39306,c datacontract serialization how to deserialize to already existing instance i have a class which holds a static dictionary of all existing instances which are defined at compile timebasically it looks like thisdatacontractclass foo private static dictionarylong foo instances new dictionarylong foo datamember private long id public static readonly foo a create1 public static readonly foo b create2 public static readonly foo c create3 private static foo createlong id foo instance new foo instanceid id instancesaddinstance return instance public static foo getlong id return instancesid there are other fields and the class is derived but this does not matter for the problemonly the id is serialized when an instance of this type is deserialized i would like to get the instance that has been created as the static field a b or c using foogetid instead of getting a new instanceis there a simple way to do this i did not find any resources which i was able to understand,['c#'] +39307,rails actionmailer problems on mac i have been working on learning to use rails the last couple days and i have run into something that i have not been able to solve with googleso i am just creating a basic contact form that sends an email everything seems to be working ok in testing which tells me that the form is working and actionmailer was implemented correctly however i am having trouble configuring actionmailer i am running osx 1062 i have postfix running and have verified that it is running using telnet localhost 25 when i try to use the form i get a connection refused errorthis is my current configurationconfigaction mailersmtp settings address localhost port 25i thought i might need to set domain but i am kind of confused on what that should be set to in this situation,"['ruby-on-rails', 'ruby']" +39311,what is a satellite assembly what is a satellite assembly and how can we use it,['.net'] +39318,how to change the source of an image dynamically in html please help me with this question i am trying to change the source of an image dynamically,['html'] +39331,convert xelement to string i have a simple xelement object xelement xml new xelementxml new xelement tokensessiontoken new xelementall inclusive 0 new xelementbeach 0 new xelementdest dep ddldestselectedvaluetostring new xelementflex 0where want to dump out the contents into a string exactly like how consolewritelinexml does but i want the contents in a string i tried various methonds xmltostring does not return anything on its ownthanks a lotmarty,['c#'] +39332,dedicated thread for io servicerun i want to provide a global io service that is driven by one global thread simple enough i just have the thread body call io servicerun however that does not work as run run one poll poll one return if there is no work to do but if the thread repeatedly calls run it will busy loop when there is nothing to doi am looking for a way to get the thread to block while there is not any work to be done in the io service i could add a global event to the mix for the thread to block on however that would require users of the io service to notify the event every time they used the service not the ideal solutionnote there are no actual globals and i never use events for concurrency i just simplified the problem down to my exact need the real goal is a asiodeadline timer subclass that does not require an io service as a construction parameter,['c++'] +39334,how to call context menu i open my context menu like this private onclicklistener optionsclicklistener new onclicklistener public void onclick view v registerforcontextmenu v opencontextmenu v how can i callregisterforcontextmenu v opencontextmenu v from inside my regular menu handler here public boolean onoptionsitemselected menuitem item switch itemgetitemid case options registerforcontextmenu v opencontextmenu v return truewhere i have no view to pass,['android'] +39335,gcc outputs error undefined reference to printf when using an nasm extern statement to access printf i am learning nasm and am tying to compile this code which i found here it assembles using this nasm commandnasm f coff l printflst printf1asmto printfo but this gcc linking commandgcc o printf1 printf1ofails with the errorprintf1oprintf1asmtext0x1a undefined reference to printfcollect2 ld returned 1 exit statuswhat am i doing wrong thanks in advance edit i am on windows 7 printf1asm print an integer from storage and from a register assemblenasm f coff l printflst printf1asm linkgcc o printf1 printf1o runprintf1 outputa5 eax7 equivalent c code printf1c print an int and an expression include int main int a5 printfad eaxdn a a2 return 0 declare some external functions externprintf the c function to be calledsection data data section initialized variablesa dd5 int a5fmt dbad eaxd 10 0 the printf format n0section text code section global main the standard gcc entry point main the program label for the entry point push ebp set up stack frame mov ebpespmoveax a put a from store into registeraddeax 2 a2pusheax value of a2 push dword a value of variable a push dword fmt address of ctrl string call printf call c function add esp 12 pop stack 3 push times 4 bytes mov esp ebp takedown stack frame pop ebp same as leave opmoveax0 normal no error return valueret return,['c'] +39368,determine original size of image cross browser is there a reliable framework independent way of determining the physical dimensions of a img srcxyzjpg resized on the client side,['javascript'] +39378,hibernate database specific columndefinition values the problem is as follows were using hibernate with annotations as or mappersome column annotations look likecolumncolumndefinition longblob name binarydata nullable trueorcolumncolumndefinition mediumtext name remark nullable truewith the columndefinition attributes being mysql specificon postgres for example the columndefinition values should be bytea and varchar9and on oracle probably something elseproblems arise currently at the time of schema export eg when creating the ddl statementspossible workarounds that i can think of are hack some jdbc driver that does a text replace eg longblobbytea for the ddl statements that is ugly but will work somehow use hibernate xml configuration instead of annotations that will probably work but i prefer annotationsdoes anybody know any alternatives hibernate specific workarounds are ok eg if the columndefinition attribute can contain dialect specific values like columncolumndefinition mysqlmediumtext postgresvarchar9 name remark nullable truethanksholger,['mysql'] +39406,why does not ospathjoin work in this case the below code will not join when debugged the command does not store the whole path but just the last entryospathjoinhomebuildtestsandboxes todaystr new sandboxwhen i test this it only stores the new sandbox part of the code,['python'] +39417,why are there no concurrent collections in c i am trying to get an overview of the thread safety theory behind the collections in c why are there no concurrent collections as there are in java java docs some collections appear thread safe but it is not clear to me what the position is for example with regard to compound operationssafety of using iteratorswrite operationsi do not want to reinvent the wheel i am not a multithreading guru and am definitely not underestimating how hard this would be anywayi hope the community can help,"['c#', 'java']" +39430,how does the python conditional operator workaround work from what i have read i found that a builtin ternary operator does not exist i will be happy to know more about iti found the following code as a substitutedef val var floatraw inputage status workingretiredvar65 print you should bestatusi could not understand how this code works can anyone explain me how actually the code is working i am also interested to know why the ternary operator does not exist any references or links about this will be ore useful i am running python 264 on windows vista,['python'] +39448,does python support mysql prepared statements i worked on a php project earlier where prepared statements made the select queries 20 fasteri am wondering if it works on python i cannot seem to find anything that specifically says it does or does not,"['python', 'mysql']" +39450,dynamic calculation of uilabel width in uitableviewcell i am building a custom inapplication settings view based on uitableviewcellstyle1 or so i am trying to dynamically calculate the width of the left label title of a cell to determine how wide my text field on the right can bewhen i launch the app in the simulator and the view loads the width of the title labels is zero until i scroll down the view and a cell is not visible then when i scroll back up the size adjusts as expected i believe this might have to do something with cell reusage i need the title labels in the cells to have their correct width when the view loads not after they have gone out of sight one time uitableviewcelltableviewuitableviewtableview cellforrowatindexpathnsindexpathindexpath static nsstring reuseidentifier settingscelluitableviewcell cell tableview dequeuereusablecellwithidentifierreuseidentifierif cell cell uitableviewcell alloc initwithstyleuitableviewcellstylevalue1 reuseidentifierreuseidentifier autorelease cell setbackgroundcoloruicolor baedarkgraycolor uilabel celabel cell textlabel celabel settextcoloruicolor whitecolor celabel setbackgroundcoloruicolor clearcolor cell setuserinteractionenabledyes cell setselectionstyleuitableviewcellselectionstylegray populate cell with corresponding datansdictionary tablesection tabledata objectatindexindexpathsection set the labeluilabel textlabel cell textlabelnsstring labelstring tablesection objectforkeyitemtitles objectatindexindexpathrowtextlabel settextlabelstring cgsize constrainedsize constrainedsizewidth maxfloat constrainedsizeheight maxfloatcgsize textlabelsize textlabeltext sizewithfonttextlabelfont constrainedtosizeconstrainedsizenslogtext label width f textlabelsizewidth set the accessory viewbaesettingstablecellaccessorytype accessorytype tablesection objectforkeyitemaccessories objectatindexindexpathrow integervalueswitch accessorytype case baesettingstablecellaccessorythisclosureindicator uiimageview thisclosureview uiimageview alloc initwithimageuiimage imagenamedaccessorythisclosurepng cell setaccessoryviewthisclosureview thisclosureview release break case baesettingstablecellaccessoryonoffswitch uiswitch onoffswitch uiswitch alloc initwithframecgrectzero onoffswitch setonyes cell setaccessoryviewonoffswitch onoffswitch release break case baesettingstablecellaccessorynone default break cgrect cellframe cell frame float detailtextfieldwidth cellframesizewidth textlabelsizewidth 50 float detailtextfieldheight cellframesizeheight 1 nslogdetail text field calculated frame width height f f detailtextfieldwidth detailtextfieldheight cgrect frame cgrectmakecellframeoriginx cellframeoriginy detailtextfieldwidth detailtextfieldheight uitextfield textfield uitextfield alloc initwithframeframe nsstring detaillabelstring tablesection objectforkeyitemdetailstrings objectatindexindexpathrow textfieldtext detaillabelstring textfieldtextcolor celldetailtextlabeltextcolor textfieldtextalignment uitextalignmentright textfieldborderstyle uitextborderstyleroundedrect cell setaccessoryviewtextfield textfield release break return cell,['iphone'] +39470,confusion between view logic and domain logic in a aspnet mvc web application i am getting confused between domainapplication logic and user interface logic to illustrate what i am trying to nail down i will describe an imaginary program below for illustration purposes1imagine a small application with a set of 3 cascading dropdowns as you select one dropdown it triggers a jquery ajax get which ends up hitting a mvc controller supplying the selected value of the previously selected dropdown the controller returns the allowable choices for the next dropdown the javacript in the view arranges these results into a dropdown and so on so each time you select a dropdown the next one gets populated2now throwing in a wrench there are some exceptions lets say if the user selects foo or bar in the first dropdown then the behavor changes so that the second dropdown is thisabled and the thrid dropdown will show a texbox insteadmy questions is in the context of mvc what is the appropriate place for this decision logic such as the code that is responsible for making these decisions like i explained in 2 the most convenient place that i have been putting this was right in the javascript of the view i simply wrote javascript to test if the first box is foo or bar then thisable the second dropwdown and swap out the third dropdown for a textbox but this does not feel quite right to me because it seems like it should be business logic therefore the code should belong in a domain layer some place but that does not feel quite right eitherand so i feel like i am going in circles can some one shed some light on this little design,['asp.net'] +39487,how can i catch a 404 i have the following codehttpwebrequest request httpwebrequestwebrequestcreateurlrequestmethod headrequestcredentials mycredentialcachetry requestgetresponsecatchhow can i catch a specific 404 error the webexceptionstatusprotocolerror can only detect that an error occurred but not give the exact code of the errorfor example catch webexception ex if exstatus webexceptionstatusprotocolerror throw ex is just not useful enough the protocol exception could be 401 503 403 anything really,"['c#', '.net']" +39491,define null null ifndef nulldefine null nullendifthis code compiles in gcc with no warningserrors can someone explain what the preprocessor is doing here,"['c++', 'c']" +39500,are axis2 generated stubs threadsafe are client stubs generated from wsdl by axis2 threadsafeof course threadsafe is not necessary a rigorously defined term so i am at least interested in the followingare different instances of the same stub class accessible concurrently by different threads with the same effective behavior as singlethreaded executionis a single instance of the same stub class accessible concurrently by different threads with the same effective behavior as the same calls interleaved in some arbitrary way in singlethreaded executionyou may also wish to use the terminology described here and originating here to thiscuss this more precisely,['java'] +39502,what can i use to replace sleep and usleep in my qt app i am importing a portion of existing code into my qt app and noticed a sleep function in there i see that this type of function has no place in event programming what should i do instead update after thought and feedback i would say the answer is call sleep outside the gui main thread only and if you need to wait in the gui thread use processevents or an event loop this will prevent the gui from freezing,['c++'] +39531,memory alignment of classes in c btw this refers to 32 bit ossome updatesthis is definitely an alignment issuesometimes the alignment for whatever reason is so bad that access to the double is more than 50x slower than its fastest accessrunning the code on a 64 bit machine cuts down the issue but i think it was still alternating between two timing of which i could get similar results by changing the double to a float on a 32 bit machinerunning the code under mono exhibits no issue microsoft any chance you can copy something from those novell guysis there a way to memory align the allocation of classes in cthe following demonstrates i think the badness of not having doubles aligned correctly it does some simple math on a double stored in a class timing each run running 5 timed runs on the variable before allocating a new one and doing it over againbasically the results looks like you either have a fast medium or slow memory position on my ancient processor these end up around 40 80 or 120ms per runi have tried playing with structlayoutattribute but have had no joy maybe something else is going onclass sample class variable public double value static void main const int count 10 while true var x new variable for int inner 0 inner 5 inner move allocation here to allocate more often so more probably to get 50x slowdown problem var stopwatch stopwatchstartnew var total 00 for int i 1 i count i xvalue i total xvalue if mathabstotal 5050 1 throw new applicationexceptiontotaltostring consolewrite0 stopwatchelapsedmilliseconds consolewriteline so i see lots of web pages about alignment of structs for interop so what about alignment of classesor are my assumptions wrong and there is another issue with the abovethankspaul,['c#'] +39533,find all the name using mysql query which start with the letter a i want to find the data from table artists where name is start with letter a b cie my op should containadamalanbobbenchriscameronbut not glain doc dolbie,['mysql'] +39539,how to loop through an associative array and get the key my associative array arr array 1 value1 2 value2 10 value10using the following code v is filled with arrs values foreacharr as v echov value1 value2 value10 how do i get arrs keys instead foreach echok 1 2 10,['php'] +39548,how can i get utctime in milisecond since january 1 1970 in c language is there any way to get miliseconds and its fraction part from 1970 using timeh in c language,['c'] +39555,php how to capture browser window screen with php first of all i am not sure if it is possible to capture browser window screen with php thenhow to do itif it is possible the best will be to capture just the website content excluding browser parts such as menubar toolbar statusbar etcthanks,['php'] +39557,android listview scroll to number of listitems i am using listview i want to scroll down to lists 10 item when view get loaded how can do that,['android'] +39571,lightweight message bus library i will be starting a small java gwt really project in the near future and i am at information gathering phaseq is there a lightweight message bus library written in java my requirements are lightweight too async no need for syncmulticast and pointtopointno strict message orderingmessage envelope ideally owned by message bus ie in terms of lifecycle managementlocalized delivery ie not interprocess nor internodeupdate it seems that gwt now supports an integrated event bus,['java'] +39573,why does java prohibit static fields in inner classes class outerclass class innerclass static int i 100 compile error static void f compile error although it is not possible to access the static field with outerclassinnerclassi if i want to record something that should be static eg the number of innerclass objects created it would be helpful to make that field static so why does java prohibit static fieldsmethods in inner classesedit i know how to make the compiler happy with static nested class or static inner class but what i want to know is why java forbids static fieldsmethods inside inner classes or ordinary inner class from both the language design and implementation aspects if someone knows more about itthanks,['java'] +39574,opensource frameworksprojects for iphone platform i am looking for a collection of opensource frameworksprojects for the iphone platform i have found quite a few good frameworks and resources such as asihttprequest drawkit and cocos2d just to name a few i am just curious about the minor or unknown frameworks that have yet surfaced or that i am unaware of do any of you know of frameworks that are not mentioned in the following linksome of the frameworks that i have found and utilize in some of my iphone applications can be found here list of iphone frameworksi am not limiting the scope or type of frameworksprojects all are welcome,['iphone'] +39582,datepickersetdate issues in jquery i have a function that executes a query to get some data based on a certain date range which is selected using datepicker i am trying to set the datepickers that are in the response data back to the date range which was selected before the query was executedquerydate 20091101datepickerdatepickersetdate querydatehas the interesting result of setting the datepicker to todays date i wouldnt be so confused if it just spit out an error why does it set it to todays datehow can i take the date which is formated like ymmdd and set the datepicker to iti am thinking it might be best to just set the textbox which the datepicker is linked to to querydatethanks,['jquery'] +39602,whats the point of a main function andor name main check in python possible duplicatewhat does if name main do i occasionally notice something like the following in python scriptsif name main do stuff like call mainwhats the point of this,['python'] +39608,how do i access a objects method when the methods name is in a variable say i have a class object named testtest has various methods one of them is whatever i have a variable named method whateverhow can i access the method using the variable with testthanks,['python'] +39610,javascript detect if google analytics is loaded yet i am working on a project here that will store some info in google analytics custom variables the script i am building out needs to detect if ga has loaded yet before i can push data to it the project is being designed to work across any kind of site that uses ga the problem is reliably detecting if ga has finished loading or not and is availablea couple of variabilities here1 there is multiple methods of loading ga older scripts from the urchin days up to the latest asynchronous scripts some of these are inline some are asynchronous also some sites do custom methods of loading ga like at my job we use yui getscript to load it2 variablevariable names in some scripts the variable name assigned to ga is pagetracker in others its gaq then there is the infinity of custom variable names that sites could be using for their implementation of gaso does anyone have any thoughts on what might be a reliable way to check if google analytics is being used on the page and if it is been loaded,['javascript'] +39620,bitmapfactory oom driving me nuts i have been doing a lot of searching and i know a lot of other peopleare experiencing the same oom memory problems with bitmapfactory myapp only shows a total memory available of 4mb using runtimegetruntimetotalmemory if the limit is 16mb then why does not the totalmemory grow to make room for the bitmap instead it throws an errori also do not understand that if i have 16mb of free memory accordingto runtimegetruntimefreememory why do i get an error saying vmwould not let us allocate 614400 bytes seems to me i have plentyavailable memorymy app is complete except for this problem which goes away when ireboot the phone so that my app is the only thing running i am usingan htc hero for device testing android 15at this point i am thinking the only way around this is to somehowavoid using bitmapfactoryanyone have any ideas on this or an explanation as to why vm would notallocate 614kb when there is 16mb of free memory,['android'] +39628,can one ruby object destroy another in ruby can one object destroy anotherfor exampleclass creature def initialize energy 1 end attr accessor energy endclass crocodile creature def eatcreature energy creatureenergy creature nil this does not work endendfish creaturenewcroc crocodilenewcroceatfishafter the crocodile has eaten a creature and absorbed its energy the creature should cease to exist but the code above does not destroy the creaturei know that if i say fish nil the object that the varible fish refers to will be garbage collected but saying creature nil inside the crocodiles eat method does not accomplish thatanother way of putting itfrom inside croceat can i say since the variable fish was passed to me when i am done i am going to set fish to nilupdate problem solvedi have essentially taken the approach that chuck suggested with some modifications here was my reasoningif there is no longer any variable pointing to an object it will be garbage collectedif when an object is created i add it to a hash like x object and do not create any other variable for it then deleting that item from the hash results in garbage collecting the objectit seems logical that a list of all creatures should be stored in the creature classtherefore i did thison the creature class object i created a hash and assigned it to an instance variable well call it creaturelist the reason i used an instance variable and not a class variable is so that any subclass of creature can have its own list tooin the initialize method a new creature hands itself to the creature classthe creature class adds a reference to that creature to creaturelist and returns an id to the creaturethe creature remembers that id in its own id variableif the creature dies it calls the parent class with creatureremoveid and the only reference to itself gets deletednow i can do thisclass predator creature def eatcreature energy creatureenergy creaturedie endendfish creaturenewcreaturelist shows the fishcroc predatornewcroceatfishcreaturelist no more fishof course in this example fish still points to that creature object so it is not garbage collected but eventually creatures will be created and eat each other based on rules so i would not be individually naming them,['ruby'] +39635,how to get current sort order from tablesorter plugin i am just starting to use christian bachs excellent tablesorter plugin and i need to get a columns current sort direction i have several columnsidname categoryid and name are set to nonsortable using headers 0 sorter false 1 sorter false i am adding a click handler on name so that it fires the sort event on the category column using the example sort table using a link outside the table i am able to get the name header to fire the category sort but it is hardcoded to sort in one direction how can i get it to look at the current direction the category column is currently sorted and sort in the opposite direction i can handle flipping the values since the sort order is 0 or 1 i can xor the value to get the opposite like var sort sort sort my question is how to get the current valueheres the code that currently sets the click handler on the name columnnamecolclickfunction var sorting 2 0 sort 3rd col category descending searchresultstriggersorton sorting searchresults is the id of the sortable table return false cancel default link action on anamecol thanks,['jquery'] +39656,hibernate lock wait timeout exceeded i am using hibernate trying to simulate 2 concurrent update to the same row in databaseedit i moved em1gettransactioncommit to be right after em1flush i am not getting any staleobjectexception the two transactions committed successfullysession em1managersessionfactoryopensessionsession em2managersessionfactoryopensessionem1gettransactionbeginem2gettransactionbeginuseraccount c1 useraccountem1get useraccountclass root useraccount c2 useraccountem2get useraccountclass root c1setbalance c1getbalance 1 em1flushsystemoutprintlnbalance1 is c2getbalancec2setbalance c2getbalance 1 em2flush failem1gettransactioncommitem2gettransactioncommitsystemoutprintlnbalance2 is c2getbalancei getting the following exception on em2flush why20091223 214837648 warn jdbcexceptionreporter100 sql error 1205 sqlstate 41020091223 214837649 error jdbcexceptionreporter101 lock wait timeout exceeded try restarting transaction20091223 214837650 error abstractflushingeventlistener324 could not synchronize database state with sessionorghibernateexceptiongenericjdbcexception could not execute jdbc batch update at orghibernateexceptionsqlstateconverterhandlednonspecificexceptionsqlstateconverterjava126 at orghibernateexceptionsqlstateconverterconvertsqlstateconverterjava114 at orghibernateexceptionjdbcexceptionhelperconvertjdbcexceptionhelperjava66 at orghibernatejdbcabstractbatcherexecutebatchabstractbatcherjava275 at orghibernatepersisterentityabstractentitypersisterprocessgeneratedpropertiesabstractentitypersisterjava3702 at orghibernatepersisterentityabstractentitypersisterprocessupdategeneratedpropertiesabstractentitypersisterjava3691 at orghibernateactionentityupdateactionexecuteentityupdateactionjava147 at orghibernateengineactionqueueexecuteactionqueuejava279 at orghibernateengineactionqueueexecuteactionsactionqueuejava263 at orghibernateengineactionqueueexecuteactionsactionqueuejava168 at orghibernateeventdefabstractflushingeventlistenerperformexecutionsabstractflushingeventlistenerjava321 at orghibernateeventdefdefaultflusheventlisteneronflushdefaultflusheventlistenerjava50 at orghibernateimplsessionimplflushsessionimpljava1028 at comchwhoisserverteststresstestmainstresstestjava54caused by javasqlbatchupdateexception lock wait timeout exceeded try restarting transaction at commysqljdbcpreparedstatementexecutebatchseriallypreparedstatementjava1213 at commysqljdbcpreparedstatementexecutebatchpreparedstatementjava912 at orghibernatejdbcbatchingbatcherdoexecutebatchbatchingbatcherjava70 at orghibernatejdbcabstractbatcherexecutebatchabstractbatcherjava268 10 more,['java'] +39666,calculate the number of html checkbox checked using jquery hihow can i calculate the number of checkboxes that a user has checked using jquerywhat i want to do is limiting the number of checking for checkboxes in a form to 10 for example and when a user exceeds this range thisplay a warning message,"['jquery', 'html']" +39670,how to configure vim for c development i am learning c using vim as editor on windows xp however i found issue that i have list belowi have downloaded and installed cvim and it essential file however when i start vim it show message cc template file cprogram filesvimvimfilescsupporttemplatestemplates does not exist or is not readable i want to know how to fixed this problemhow to make vim can compile c stl file,['c++'] +39678,public accessor net i think it was in net 20 microsoft introduced an accessor that was abbreviated to something like public string name get set but is there any real difference between the above code and simplypublic string name,['c#'] +39680,how to override operator what is the name of the method to override the operator for a class,['python'] +39698,django manytomany signals let us say i have such modelclass eventmodelsmodel users count modelsintegerfielddefault0 users modelsmanytomanyfielduserhow would you recommend to update users count value if event adelete some users,['python'] +39708,is it possible to pass an arbitrary method group as a parameter to a method i would like write a function like the following the type methodgroup below does not exist this is fantasycodepublic void myfunctionmethodgroup g do something with the method groupthe later i could call myfunction with any method group something like thismyfunctionobjectequalsif i commit to a signature then things work finepublic void myfunctionfuncobject object bool f do something with known delegatemyfunctionobjectequalsthe method group objectequals is happily coerced into the known delegate type funcobject object bool but i do not want to commit to a particular signature i would like to pass any method group to myfunction method groups cannot be converted to systemobjectpublic void myfunctionobject o do something with omyfunctionobjectequals does not worki think that everyones forgotten braces on a method call and thiscovered this at some point i am hoping that this does not mean that method groups are not or cannot be converted to first class objects i do not think that linq expressions will give the kind of generality i am looking for but i could certainly be missing somethingi should also mention that it would be fine if the method group contained overloads provided i have a way of inspecting the method groupwhat would i do with a method group i could print all the signatures of all the the methods in the group overloads extension methods etc or i could invoke the group with some arguments have it resolve to the correct overload in the group if possible there are other ways to do these things but they are some things you might want to do with a method groupas several people have mentioned i can accept a delegate and cast to a particular known delegate type when i call myfunctionpublic void myfunctiondelegate d do something with dmyfunctionfuncobject object boolobjectequalsbut this is not quite the same as passing the entire method group this selects one method from the group and converts it to a particular delegate i would really like to pass the whole group in one shot,['c#'] +39713,is it possible to send a variable number of arguments to a javascript function is it possible to send a variable number of arguments to a javascript function from an array var arr abcvar func function debug alertargumentslength forarg in arguments alertargfuncabcd prints 4 which is what i want then abcdfuncarr prints 1 then arrayi have recently written a lot of python and it is a wonderful pattern to be able to accept varargs and send them egdef funcargs print lenargs for i in args print ifuncabcd prints 4 which is what i want then abcdfuncarr prints 4 which is what i want then abcdis it possible in javascript to send an array to be treated as the arguments array,['javascript'] +39718,python scientific notation using d instead of e some results file produced by fortran programs report double precision numbers in scientific notation using the letter d instead of e for instance12345d02 instead of12345e02i need to process huge amounts of this data using python and i just realized it cannot read the numbers in the d notation for instance a 10d01 file stdin line 1 a 10d01 syntaxerror invalid syntaxcan i change my locale and let python know that d means e i really would not want to make a global searchandreplace,['python'] +39725,how to use objective c to send device token for push notifications and other user settings to sql table on server ideally i would like to send an http request using post to the push notification server that contains the device token as well as some userdefined settings from there i can set up a php script on the server to deal with the incoming data and input it into an sql table if this is the only way to do it how would i go about initiating and http request from objective c,"['mysql', 'objective-c']" +39735,abspath or file can someone tell me if either of these two methods has an advantage over the other and whymydir abspathwpcontentthemesmythemeimagesmydir dirname file imagesthey can both be used to obtain and absolute path to the images directory of mytheme regardless of structure of whether wordpress is installed on the root directory or in a subdirectory off the root in both cases they are being called from the functionsphp file which is located under the mytheme folder,['php'] +39739,jquery ajax submit form i have a form with name orderproductform and an undefined number of inputsi want to do some kind of jqueryget or ajax or anything like that that would call a page through ajax and send along all the inputs of the form orderproductformi suppose one way would be to do something likejquerygetmyurl action documentorderproductformactionvalue cartproductid documentorderproductformcartproductidvalue productid documentorderproductformproductidvalue however i do not know exactly all the form inputs is there a feature function or something that would just send all the form inputsthanks,['jquery'] +39740,test php functions not classes with netbeans and phpunit i would like to run unit test for a functions library filethat is i do not have a class it is just a file with helper functions in itfor example i have created a php project at wtestand a file wtestlibformatphpphpfunction toupper text return strtoupper text function tolower text return strtolower text function toproper text return toupper substr text 0 1 tolower substr text 1 tools create phpunit tests gives me the following errorphpunit 345 by sebastian bergmanncould not find class format in homesaswtestlibformatphpnow if i code by hand the filewtesttestslibformattestphpphprequire once phpunitframeworkphprequire once dirname file libformatphpclass formattest extends phpunit framework testcase protected function setup protected function teardown public function testtoproper thisassertequals sebastian toproper sebastian it works fine i can run itbut if i select test file from formatphp i gettest file for the selected source file was not foundany ideasaludossasps another question is there a way to update generated tests without having to manually delete themps2 using netbeans 28 dev,['php'] +39742,what to learn for making java web applications in java ee 6 my goal is to make web applicationsi finished reading the books headfirst java and headfirst servlets and jspbecause this topic web applications is so big and complicated i would like to ask what i should learn next i feel overstrained when i read catchwords like java ee ejb jsf jpa glassfish but i would not give upcan anyone please tell me how i should proceed with learning should i grab a book like thisbeginning java ee 6 platform with glassfish 3 from novice to professional or should i just make some online tutorialsthanks,['java'] +39751,add values to an associative array in php i want to append an element to to end of an associative arrayfor example my array is testarray chemical asdasd chemical hazards g and my result should be testarray chemical asdasd chemical hazards g solution good could you tell me how to implement this,['php'] +39752,what is nothrow delete in c this msdn page mentions that therere nothrow versions of new and delete nothrow new is quite a known thing returns null instead of throwing an exception if memory allocation fails but what is nothrow delete mentioned there,['c++'] +39763,return two and more values from a method is there any possibility to return multiple values from method something like thisdef do return a 10 someobjectnewenda b c do,['ruby'] +39764,ruby ampersand colon shortcut possible duplicatewhat does mapname mean in ruby in ruby i know that if i dosome objectseachfooit is the same assome objectseach obj objfoo that is foo creates the block obj objfoo turns it into a proc and passes it to each why does this work is it just a ruby special case or is there reason why this works as it does,['ruby'] +39767,list of things to check to prevent vc applications from showing fatal error message boxes every now and then there is a strong need to write a program in such a way that it never really never shows an error message as a message box for example it can be a program run inside a daily build if it hangs with a message box the daily build hangsunfortunately vc runtime has a lot of ways to trigger message boxes when indicating errorsfirst of all whenever an exception is not handled terminate is called which calls abort which causes this application has requested the runtime to terminate it in an unusual way message box this can be worked around by catching all exceptions andor using set terminate to set a custom terminate handler without message boxesthen whenever an exception escapes any destrutor during stack unwinding terminate is also called set terminate helps here as wellthen there is a pure virtual function call message box that is shown in some hardcore cases of mismatching the number of functions expected by the caller and those implemented by the callee set purecall handler should help herewhat else to do to a vc program to be absolutely positively sure it does not show a message box in some fatal situation,['c++'] +39769,problem in the getdeclaredmethods java i have a small problem in my codei have 2 classespublic class a public a fooint a return new apublic class b extends a public b fooint x return new bnow in my code i want to print only the method that was declared in class bin this wayb b new bmethod m bgetclassgetdeclaredmethodsfor int i 0 i mlength i systemoutprintmigetname why the output isfoofoowhy the getdeclaredmethods finds also the foo in the a classhow can i fix itthanks,['java'] +39783,moq invalid setup on a nonoverridable member x xgetbytitleasdf not sure how i can fix this trying to do a unit test on the method getbytitlehere are my definitionspublic class articledao genericnhibernatedaoiarticle int iarticledao public iarticle getbytitlestring title iquery query sessioncreatequery return queryuniqueresultiarticle public interface iarticledao iarticle getbytitlestring titleunit testtestpublic void can load by title mockdaofactorysetupx xgetarticledao returns mockarticledaoobject mockarticledaosetupx xgetbytitlesome title returnsarticle1object articlemanagerloadarticlesome title assertisnotnull articlemanagerarticlerunning the test gives me the errorsystemargumentexception invalid setup on a nonoverridable memberx xgetbytitlesome titleupdatemy setup looks likesetuppublic void setup mockdaofactory new mockidaofactory mockarticledao new mockarticledao articlemanager new articlemanager mockdaofactoryobject,['c#'] +39786,apply a regex on stream i am searching for fast and safe way to apply regular expressions on streamsi found some examples over the internet that talking about converting each buffer to string and then apply the regex on the stringthis approach have two problemsperformance converting to strings and gcing the strings is waste of time and cpu and sure can be avoided if there was a more native way to apply regex on streamspure regex support regex pattern sometimes can match only if combining two buffers together buffer 1 ends with the first part of the match and buffer 2 starts with the second part of the match the converttostring way cannot handle this type of matching natively i have to provide more information like the maximum length that the pattern can match this does not support the and regex signs at all and will never support unlimited match lengthso the converttostring way is not fast and does not fully support regexis there any way library that can be used to apply regex on streams without converting to strings and with full regex support,"['c#', '.net']" +39787,importance of varchar length in mysql table i have a mysql table where rows are inserted dynamically because i can not be certain of the length of strings and do not want them cut off i make them varchar200 which is generally much bigger than i need is there a big performance hit in giving a varchar field much more length than necessary,"['sql', 'mysql']" +39796,what is the ccli equivalent to cs defaultt i am working with some ccli code new syntax and am trying to declare a generic type and want to set a member variable to it is defaultin cclass classt t member defaulttwhats the equivalent in cligenerictypename t public ref class class public class memberdefaultt no worky private t member,['.net'] +39803,is c static member variable initialization threadsafe according to following resources in cspecially visual c scoped static variable initialization is not thread safe but global static variables are safeso is following code with static member variable threadsafeclass testclasspublic static myclass m instancemyclass testclassm instancethanks in advance,['c++'] +39805,selecting rows from a numpy ndarray i want to select only certain rows from a numpy array based on the value in the second column for example this test array has integers from 1 to 10 in the second column test numpyarraynumpyarange100 numpyrandomrandint1 11 100transpose test10 array 0 6 1 7 2 10 3 4 4 1 5 10 6 6 7 4 8 6 9 7if i wanted only rows where the second value is 4 it is easy testtest 1 4array 3 4 7 4 16 4 81 4 83 4 88 4but how do i achieve the same result when there is more than one wanted valuethe wanted list can be of arbitrary length for example i may want all rows where the second column is either 2 4 or 6 wanted 2 4 6the only way i have come up with is to use list comprehension and then convert this back into an array and seems too convoluted although it works testnumpyarraytestx 1 in wanted for x in rangelentestarray 0 6 3 4 6 6 90 2 91 6 92 2is there a better way to do this in numpy itself that i am missing,['python'] +39819,when should i use malloc in c and when do not i i understand how malloc works my question is i will see things like thisdefine a megabyte 1024 1024char some memorysize t size to allocate a megabytesome memory char mallocsize to allocatesprintfsome memory hello worldprintfsn some memoryfreesome memoryi omitted error checking for the sake of brevity my question is cannot you just do the above by initializing a pointer to some static storage in memory perhapschar some memory hello worldat what point do you actually need to allocate the memory yourself instead of declaringinitializing the values you need to retain,['c'] +39825,c test if 2 sets are thisjoint i know the stl has set difference but i need to just know if 2 sets are thisjoint i have profiled my code and this is slowing my app down quite a bit is there an easy way to see if 2 sets are thisjoint or do i need to just roll my own codeedit i also tried set intersection but it took the same time,['c++'] +39830,how to find easily the source of an android class hi alli know i can access android source code from but it is hard to select the right git repo if i only know the package and the name of an android class is not there a way to locate a file in thanks in advance,['android'] +39855,length and length in java why do we have length of an array as an attribute arraylength and for string we have a method strlengthjust came in my mind is there some reason,['java'] +39862,how to move net libraries to a subdirectory i want to put all libraries dll used by my application to a subdirectory let say named lib how to instruct assembly loader to look for referenced assemblies in that particular directory which is a subdirectory of a directory where main assembly existsi assume it should be done by some settings in appconfig right,"['c#', '.net']" +39863,where do you store your php script configurations like db access data i have an configphp file where i simply make an huge array that contains all the framework configuration also the database source string thing like mysqlhostlocalhostdbnamemydb whats that called btw and username password for db i am afraid this isstupidnot good better solution therenot secure so how do the php experts do that,['php'] +39866,what does this mean parse error syntax error unexpected t paamayim nekudotayim t paamayim nekudotayim sounds really exotic but most certainly absolutely nonsense to me i traced it all down to this lines of codephpclass context protected config public function getconfigkey heres the problem somewhere cnf thisconfig return cnfgetconfigkey function construct thisconfig new config in the constructor i create a config object heres the classfinal class config private static instance null private static config public static function getconfigkey return selfconfigkey public static function getinstance if selfinstance selfinstance new config return selfinstance private function construct include configuration file include root include path sysconfigconfigphp defines a config array thisconfig config no idea why this doesnt work what the error means,['php'] +39872,height100 is not working in html when using how i can fix this when i use html with out docymenttype my html page height100 is workingbut when i use docymenttype height is not working correctlydoctype html public w3cdtd xhtml 10 transitionalen html xmlns langenheadmeta httpequivcontenttype contenttexthtml charsetwindows1252titlenew page 1titleheadbodytable cellpadding0 cellspacing0 width11 height 100 tr td height100 bgcolor0080nbsptd trtablebodyhow i solve this problem,['html'] +39877,log errors max len 1024 in phpini but php log keeps growing as the title says i have set the max length for the php error log but it seems to keep growing much much larger than 1024 i am using the correct phpini i have restarted apache etc the permissions on the php log are 6,['php'] +39885,workflow design dilemma state machine yes or no i am a beginner with wf but i have read a book and done a lot of googling i want to write an inventory management service the inventory is made up of individual items which have a statespareinstalledinrepairitems may spend months in each state and there are thousands of itemsthe question is do i create a state machine workflow for all the different states or do i create workflows for transitioning between statesif i understand correctly if i create a single state machine workflow then there will always be a workflow running for every item this means thousands of everrunning workflows also i need to be able to thisplay a snapshot of the status of each item so that means i have to somehow query all the workflows for the state they are currently in or otherwise persist to a database after each state transitionhowever a statemachine workflow logically sounds like the right thing to do hence my dilemmaplease help me if you can thanksupdateassume i have more states than the above 3 and that not all state transitions are possiblebounty winner maurice thanks to everyone else for really helping me understand more about workflows the ms workflow foundation and other more lightweight alternatives unfortunately there can only be one bounty winner and maurices answer along with its comments helped me the most,"['c#', '.net']" +39889,how can i create a melody is there any soundmodule i am confused because there are a lot of programms but i am looking something like this i will type a melody like a4 c3 h3 a2 etc and then i want to hear this does anybody know what i am looking forthanks in advance,['python'] +39894,breaking nsstring into lines to fit desired width i am trying to get a nsstring broken into lines to fit a desired width as it would happen inside sizewithfontconstrainedtosize is there a better way to do this than guessing where the breaks would happen in sizewithfont,"['iphone', 'objective-c']" +39895,what does this operator mean here exampleset error handlerarraythis handleerror e all e strict e warning e noticewhat does that suppose to mean,['php'] +39898,c hex parsing i am wondering how to convert a hex string to a human readable string if that makes any sense this would be my first real encounter with hex values so i am still learning about them and how to manage themi have a program which is reading in data from a file which contains raw packet data hex and i need to parse this information so it is human readablean example of what i need to do is something like this site does where you can put in hex and have it converted to text,['c++'] +39901,truncate a utf8 string to fit a given byte count in php say we have a utf8 string s and we need to shorten it so it can be stored in n bytes blindly truncating it to n bytes could mess it up but decoding it to find the character boundaries is a drag is there a tidy wayedit 20100414 in addition to smarkas answer mb strcut i recently found another function to do the job grapheme extracts n grapheme extr maxbytes from the intl extension since intl is an icu wrapper i have a lot of confidence in it,['php'] +39906,onkeylistener not working with soft keyboard android i am using onkeylistener to get the onkey events it works fine with the normal keyboard but it does not work with soft keyboard i am only able to get onkey events for numerics and not alphabets is there any workaround to solve this any kind of help will be greatly appreciated,['android'] +39915,can i tweak my android emulator to make it fast i am using the android emulator to run my programsbut its really slow it takes around 90 seconds to startup and show the home screencan i tweak it so that i can reduce this time considerablythanks,['android'] +39924,jquery call click from another click is it possible to do something like thisidoneclickfunction alertwe do stuffidtwoclickfunction idoneclick i guess not but are there any possible workaroundsupdwell ok it is a little bit more complicated i have a jcarousel analog installed jquerytools scrollable i guess that is what its namethe link i presume that it has click event somehow hardcoded in it and when i click thumbs the plugin scrolls it to center position then i have bound another click event so that i can thisplay large image it works similar to the example in the link abovenow i have to make this big image clickable so clicking it i can proceed to next image in gallery i did that but now i have to make the carousel scroll automatically to the next thumb when i am clicking this big image so if i simplify my code the essence is still smth like thatidoneclickfunction alertwe do stuffidtwoclickfunction idoneclickwhere idone is a thumb in the gallery idtwo is that preview image i dont know what function is bound to click by default another thing my guess was that binding the same event to the same object should replace the previous it appears not necessarily and i am pretty sure that it is exactly click not mouseupdown etc cause calling idoneclickon page load does the trick and carousel scrolls to the thumb with ididonejust in case jquery132jsthanks everyone for your answers and excuse me my lame english no time for brushing up updok so i gave up on this one but to close this question and put an end to this thiscussion i have to know all you people who wrote that it is possible and suggested variants have you tried them do they really work for you is it me who is wrong and thanks anyway,['jquery'] +39931,h264 encoders other than ffmpeg x264 the iphone app i am working on captures images in series within certain userdefined time interval i am looking for a way to combine these images into h264 encoded videos i have done some research on google it looks like i will have to use something like ffmpegmencoder on iphone also found someone ported ffmpeg to iphone ffmpeg4iphone however i found that x264 is under gpl license and requires me to open source my project if i use ffmpeg also found some people suggested to use ogg theora but i will need to port it to iphone if i use it which i am not sure how to do it nowis there any workaround for this any ideas thanks,['iphone'] +39942,mapping a range of values to another i am looking for ideas on how to translate one range values to another in python i am working on hardware project and am reading data from a sensor that can return a range of values i am then using that data to drive an actuator that requires a different range of valuesfor example lets say that the sensor returns values in the range 1 to 512 and the actuator is driven by values in the range 5 to 10 i would like a function that i can pass a value and the two ranges and get back the value mapped to the second range if such a function was named translate it could be used like thissensor value 256actuator value translatesensor value 1 512 5 10in this example i would expect the output actuator value to be 75 since the sensor value is in the middle of the possible input range,['python'] +39943,what is the difference between html and xhtml extension xhtml is a markup language or ita different extension also what is the difference between the html and xhtml file extensions what is the benefit of using the xhtml extension why we are not using the xhtml extension is it just because of iewhat about xhtml extension with ie 8is xhtml supported in other browsers besides ie if yes then what benefit we will get when all browsers support the xhtml extension will we stop using htmlwhy do we use the xhtml doctype but save those files using the html extension,['html'] +39945,a way to load dll from central repository we have lot of products and there are some common dlls across each products application right now we copy each common dll into each products bin directory and treat them as private assembly this unnecessarily increase the msi size of each product and when a problem occurs in a dll we have to build each products msi comprising the dll and deploy itis there anyway to instruct the product application to use a common private directory to be used for loading dlls using manifest scheme note adding the private directory to path env will not provide a solution as if there is a dll with same name exist in system directory that would take the privilege over our private directory kartlee,"['c++', 'c']" +39964,should i always prefer mysql innodb over myisam someone just told me that innodb is much better than myisam so when i create a table should i always try to use innodb engine instead of myisam or do both have it is big benefits,['mysql'] +39969,how much faster is myisam compared to innodb people say innodb is not so fast like myisam but how much slower just as a rule of thumb in the wind of course i mean is it usually 05x as fast as myisam or even worse or does the average visitor not recognize any temporal difference when surfing an myisam platform vs same thing with innodb,['mysql'] +39979,store html entities in database or convert when retrieved quick question is it a better idea to call htmlentities or htmlspecialchars before or after inserting data into the databasebefore the new longer string will cause me to have to change the database to hold longer values in the field maxlength800 could change to a 804 char stringafter this will require a lot more server processing and hundreds of calls to htmlspecialchars could be made on every page load or ajax loadso will converting when results are retrieved slow my code significantly should i change the db,"['php', 'mysql']" +39985,mysql benchmark i am trying to use mysql benchmark to test some queries but i am running to an error select benchmark 10 select title from userand in return i get this errorerror 1242 210 subquery returns more than 1 rowdoes anyone know how to benchmark a querythanks,"['php', 'mysql']" +39987,python seek on remote file using http how do i seek to a particular position on a remote http file so i can download only that partlets say the bytes on a remote file were 1234567890i wanna seek to 4 and download 3 bytes from there so i would have 456and also how do i check if a remote file existsi tried ospathisfile but it returns false when i am passing a remote file url,['python'] +39997,custom rendering of zend navigation i am using a navigation xml file in conjunction with my zend framework mvc appa top level menu is rendered at the top of my layout the code to produce it looks like thisthisnavigationmenurendermenunullarraymaxdepth 0this will automatically render an unordered list of links that i have styled into my top menunow i want to render the submenu to render the active container tree taking advantage of all the builtin zend navigation goodness mvc and acl integration but with custom markup i would do this by inserting thisthisnavigationmenurendersubmenuin fact i have a very specific set of markup that i need to render this with it is so drastically different i do not think i could style an unordered list to accomodate my desired presentationis there a simple way or complicated if need be to customize a submenu,['php'] +40009,getting the first character of a string with str0 i want to get the first letter of a string and i have noticed that str0 works great i am just not sure whether this is good practice as that notation is generally used with arrays this feature does not seem to be very well documented so i am turning to you guys to tell me if it is all right in all respects to use this notationor should i just stick to the good ol substrstr 0 1also i noted that curly braces str0 works as well whats up with that,['php'] +40010,java form generator from a given wsdl file i am trying to develop a form generator in java in which users will be able to write a wsdl url and get the list of the operations supported by the web service in a combobox when the user selects one of the items in combobox then he will see form fields generated using the wsdl urli am a newbie in web service technologies after searching about web service parsers on the net i decided to use axis library but i really do not know which part of the wsdl document should i parsei am not trying to create java classes of the web service i have to generate form fields for any wsdl urlfor instance here is a web service which provides 9 operations and the wsdl file is herei need to know which parts of wsdl file should be parsed any help would be appreciated,['java'] +40027,which eclipse version should i download i am on a windows machinewant to practise java for the web using tomcat java jsps spring framework and hibernatesilly question but i am a newbie and do not want to get the wrong ide version,['java'] +40033,parsing json from xmlhttprequestresponsejson i am trying to parse a bitly json response in javscripti get the json via xmlhttprequestvar req new xmlhttprequest reqoverridemimetypeapplicationjson reqopenget bitly create api encodeuricomponenturl bitly api login true var target this reqonload function targetparsejsonreq url reqsendnullparsejson functionreq url if reqstatus 200 var jsonresponse reqresponsejson var bitlyurl jsonresponseresultsurlshorturl i do this in a firefox addon when i run i get the error jsonresponse is undefined for the line var bitlyurl jsonresponseresultsurlshorturl am i doing anything wrong in parsing json here or what is wrong with this code,['javascript'] +40068,mysql stored procedure causing problems editi have narrowed my mysql wait timeout down to this line if resultsfound 0 then insert into product search query querytext categoryid values keywords toplevelcategoryid end ifany idea why this would cause a problem i cannot work it outhi guys i have written a stored proc to search for products in certain categories due to certain constraints i came across i was unable to do what i wanted limiting but whilst still returning the total number of rows found with sorting etcit is meant splits up a string of category ids from 123 in to a temporary table then builds the fulltext search query based on sorting options and limits executes the query string and then selects out the total number of resultsnow i know i am no mysql guru very far from it i have got it working but i keep getting time outs with product searches etc so i am thinking this may be causing some kind of problemdoes anyone have any ideas how i can tidy this up or even do it in a much better way that i probably do not know aboutthanksdelimiter drop procedure if exists product search create definerrootlocalhost procedure product searchkeywords text categories text toplevelcategoryid int sortorder int startoffset int itemstoreturn intbegindeclare foundpos tinyint unsigneddeclare tmptxt textdeclare delimlen tinyint unsigneddeclare element textdeclare resultingnum int unsigneddrop temporary table if exists categoryidscreate temporary table categoryidscategoryid int engine memoryset tmptxt categoriesset foundpos instrtmptxt while foundpos 0 doset element substringtmptxt 1 foundpos1set tmptxt substringtmptxt foundpos1set resultingnum casttrimelement as unsignedinsert into categoryids categoryid values resultingnumset foundpos instrtmptxtend whileif tmptxt theninsert into categoryids categoryid values tmptxtend ifcase when sortorder 0 then set sortstring productresult relevance desc when sortorder 1 then set sortstring productresult price asc when sortorder 2 then set sortstring productresult price desc when sortorder 3 then set sortstring productresult stockstatus ascend caseset theselect concatconcat select sql calc found rows suppliersupplierid as supplier supplierid suppliername as supplier name supplierimagename as supplier imagename product resultproductid as productresult productid product resultsupplierid as productresult supplierid product resultname as productresult name product resultdescription as productresult description product resultthumbnailurl as productresult thumbnailurl product resultprice as productresult price product resultdeliveryprice as productresult deliveryprice product resultstockstatus as productresult stockstatus product resulttrackurl as productresult trackurl product resultlastupdated as productresult lastupdated matchproduct resultname against as productresult relevance from product latest state product result join supplier on product resultsupplierid suppliersupplierid join category product on product resultproductid category productproductid where matchproduct resultname against and category productcategoryid in select categoryid from categoryids order by sortstring limit set keywords keywords set startoffset startoffset set itemstoreturn itemstoreturn prepare theselect from theselect execute theselect using keywords keywords startoffset itemstoreturn set resultsfound found rows select resultsfound as totalresults if resultsfound 0 then insert into product search query querytext categoryid values keywords toplevelcategoryid end ifend delimiter any help is very very much appreciated,['mysql'] +40072,putting html inside htmlactionlink plus no link text i have two questionsi am wondering how i can thisplay no link text when using htmlactionlink in an mvc view actually this is sitemaster there is not an overloaded version that does not allow link text and when i try passing in just a blank string the compiler tells me it needs a nonempty string how can i fix thisi need to put span tags within the anchor tag but it is not working with htmlactionlink i would like to see the following outputspan texthow can i put tags inside of the anchor tag in aspnet mvc,"['c#', '.net']" +40077,android create a service that runs once a day i would like to create a service for android that performs an operation once a day at a given time whats an efficient way to accomplish this i want to make sure i am not draining the device battery since this service is idle 99 of the time,"['java', 'android']" +40080,when should i use a map instead of a for loop this is relating to the following in python codefor i in object dosomethingiversusmapdosomething objectboth are easy to understand and short but is there any speed difference now if dosomething had a return value we needed to check it would be returned as a list from map and in the for loop we could either create our own list or check one at a timefor i in object returnvalue dosomethingi dosomethingwithreturnvaluereturnvalueversusreturnvalue mapdosomething objectmapdosomethingwithreturnvalue returnvaluenow i feel the two diverge a little bit the two dosomethingwithreturnvalue functions may be different based on if checking them on the fly as we go through the loop or if checking them all at once at the end produce different results also it seems the for loop would always work maybe slower where the map would only work under certain scenarios of course we could make contortions to make either work but the whole point is to avoid this type of workwhat i am looking for is a scenario where the mapping function truly shines in comparison to a well done for loop in performance readability maintainability or speed of implementation if the answer is there really is not a big difference then i would like to know when in practice people use one or the other or if it is really completely arbitrary and set by coding standards depending on your institutionthanks,['python'] +40086,check if file is a media file in c i need a method that could tell me if a file is image audio or video file can i do this with c,['c#'] +40094,programmatically registering a servlet in jetty 7 i am trying to register a servlet in jetty 70 programmatically all the examples i find are for jetty 6 and jetty 7 is quite different here is my server sideimport orgeclipsejettyserverserverimport orgeclipsejettyservletservletcontexthandlerpublic class bootstrapper public static void mainstring args throws exception server server new server8080 servletcontexthandler servletcontexthandler new servletcontexthandlerserver context true false servletcontexthandleraddservlethessianserviceclass hessianservice serverstart systemoutprintlnstarted the result of this test is the sever starts but the client fails on connect caused by javaiofilenotfoundexception httplocalhost8080hessianservicei see nothing in my browser at httplocalhost8080hessianservice thanks,['java'] +40102,is nspersistentstorecoordinator thread safe i am working on an iphone app that uses core data the app makes a call to a web service parses the resulting xml file and then creates or modifies core data objects in my app i already handle the web service call and parsing asynchronously but i have been handing the parsed data back to the main thread to manipulate the core data objects i would like to run this process in the background thread as well a 12 second pause does not make for a great user experiencethe obvious approach would be to create a managed object context specifically for the background thread but then i read this line in apples core data programming guidea persistent store coordinator provides to its managed object contexts the fade of one virtual store for completely concurrent operations you need a different coordinator for each threadso heres the catch you cannot have two nspersistentstorecoordinators providing access to the same store but marcus zarras core data book asserts that nspersistentstorecoordinator is threadsafe and will serialize io requests pp 157can someone clear this up for me is it possible to have a second managed object context running on a separate thread sharing the same nspersistentstorecoordinator with the main thread or more succinctly is nspersistentstorecoordinator threadsafe,['iphone'] +40106,determining a php objects name in java well androids version at least all objects have a getclass method which returns the objects class and you can then call getsimplename to get the humanreadable name of the object this is great for logging i would like to be able to do something similar in a php program i have been working on is there any way to find out what type of object this is,['php'] +40110,android full text search does android come with a way to do full text searchi know is it not even possible to search contacts by the notes field being google the search company but i would be thisappointed if there is no api for that,['android'] +40133,perform trim while using split today i was wondering if there is a better solution perform the following code samplestring keyword abc foo barstring match foostring split keywordsplitnew char stringsplitoptionsremoveemptyentriesforeachstring s in split ifstrim match asjdklasd breakis there a way to perform trim without manually iterating through each item i am looking for something like split by the following chars and automatically trim each result ah immediatly before posting i foundliststring parts linesplitselectp ptrimtolistin still i am curious might there be a better solution to this or would the compiler probably convert them to the same code output as the linqoperation,['c#'] +40134,html forms input type submit problem with actionurl when url contains indexaspx i have a html form that truncates the action parameter after the mark which is not the desired behavior i am looking forhere is a representative html snippetform actionpathgym input typesubmit valuespu gymnasticsformin this case the submit button takes you to the page effectively ignoring tabgymnasticspathgym parameter it appears that all html and php pages referenced in the actionurl work as expected this behavior is consistent across all major browsers ie ff safari chrome operahas anyone seen this problem before or can suggest an alternative andor workaround consistent with my pure csshtmlphp web development approach i have tried replacing the special characters with html entity values with no impact i really do not want to use abandon my cstyled submit buttons by using javascript or button pngs or image mapsenvironmentweb server apache 2214php 5210os mac os x 1058html document infodoctype html public w3cdtd xhtml 10 transitionalenhtml xmlnstia trent,['html'] +40156,how to thisplay scrollbar in uitableview i want to thisplay some kind of indication to guide user to scrollusually when we touch the uitableview scrollbar appears if needed but i want this scrollbar indication already thisplayed on my tableviewhow is it possible to do so,['iphone'] +40157,web interface for c applications our company has a set of 3d modeling softwares written in c with qt based gui we are planning to offer these applications to customers to try them from a web browser i mean to say we need to create web interfaces for native c codes please suggest me which technology languages should be used if possible please give some links to some white papers or case studies for this kind of projects i am totally clue less,"['c++', 'c']" +40162,what uiview is returned when using viewwithtag when several views have same tag say i have 4 uiviews made in ib all with the tag property 2when i get a view with uiview thisview uiviewselfview viewwithtag2what is the criterion for retrieving that uiview since several have the same tag valueis it random the first one created the view with the lowest index in it is superview something else,['iphone'] +40164,traits in javascript how can i implement traits in javascript,['javascript'] +40180,in watin how to wait until postback is complete in watin how can i wait until postback is complete for example postback response modifies update panel elsewhere on pagebrowsertextidtypetextasd watin does not wait until postback is completed what code should i replace it withbrowserwaituntilcomplete,['asp.net'] +40185,how to copy a file to another path i need to copy a file to another path leaving the original where it isi also want to be able to rename the filewill fileinfos copyto method work,['c#'] +40193,how to render a doctype with pythons xmldomminidom i trieddocumentdoctype xmldomminidomdocumenttypehtml public w3cdtd xhtml 10 stricten dtdxhtml1strictdtdthere is no doctype in the output how to fix without inserting it by hand,['python'] +40196,defaultvalue attribute is not working with my auto property i have the following auto property defaultvaluetruepublic bool retrieveallinfo get set when i try to use it inside the code i find the default false for is false i assume this is the default value to a bool variable does anyone have a clue what is wrong,['c#'] +40204,xmlhttprequeststatus returns 0 and responsetext is blank in firefox 35 i am trying to hit a third party url to get the xml response and to show the reposne into my webpagei get a proper response with status as 200 and readystate as 4 in ie and safari browsersbut in ff35 and crome i get xmlhttprequest status as 0 and reponsetext comes as a blank string i tried many options writing the normal xmlhttprequest ajax code as well as using prototype 15 version js file for this ajax request but still the status and reponsetext in ff 35 remains the same as 0 and blank string any help how to resolve this issue or what exactly is causing this issue would be greatly appreciated i had also tried to execute my code locally as well as deploying to webserver still the repsonse in ff is samebelow is my code snippetscript typetextjavascript srcprototype ajaxjsscriptscript typetextjavascript languagejavascriptnew ajaxrequesti place my url here method get onsuccess functiontransport var resultdoc transportresponsetext var rootobj loadxmlresultdoc onfailure functiontransport alert on failure transport function loadxmlxmlfile var xmldocelement null var xmldoc null if windowactivexobject try code for ie xmldocnew activexobjectmicrosoftxmldom xmldocasyncfalse xmldocloadxmlxmlfile catch e alertinside catchemessage else code for mozilla firefox opera etc parsernew domparser xmldocparserparsefromstringxmlfiletextxml xmldocelementxmldocdocumentelement alertloadxml value xmldoc return xmldocscript,"['javascript', 'html']" +40205,pdf report generation edit i completed this project using abcpdf for anyone interested i love this product and their support is a everything i listed as a con for the html pdf solution was easily doable in abcpdfi have been charged with creating a data driven pdf report after reviewing the plethora of options i have narrowed it down to 2 i need you all to to help me decide or offer alternatives i have not considered here are the requirements100 data driveneventually pdf a stop in html is fine so long as it is convertedcan be run with multiple sets of data the layout is always the same the data is variablecontains normal analysisstyle copy saved in db with html markupcontains tables data for tables is generated at runtimeheaderpage on each pagetable of contentsnet vb or cdone quicklynow because of the fact that the report is going to be generated with multiple sets of data i do not think a stamped pdf template will work since i would not know how long or how many pages a certain piece of the report could requireso i think my best options areprogrammatic creation using an itextlike solutiongenerate in html and convert to pdf using a thirdparty application abcpdf is the tool i have played with so farboth solutions have their pros and consprogrammatic solutionprosflexibleeasy page numberingpage headertable of contentsfreeconstime consuming to write a layer on top of itext to do what i need and keep maintainablesince the copy is already stored in the db with html markup i would have to parse through the data before i place it into the pdf ensuring i do not have to break the paragraph into chunks so i can apply bold italic underline etc to specific phrases this seems like a huge pita and i hope i am wrong about that assumptionhtml pdfproseasy to generate from db no parsing necessarymany tools for conversionuses technology i am already familiar withbuiltin print preview not a req but niceconsedited after project completion all of my assumptions were incorrect and abcpdf is awesome1 almost impossible to generate page headers not true2 very difficult to generate page numbers not true3 nearly impossible to generate table of contents not true 4 crossbrowser support is not a con since its internal i can dictate what browser to use5 conversion tool quirks may not convert exactly as rendered in browser not true6 overall i think it would be very hard to format the html exactly as i would want it to appearconvert to pdf not true that is it i need the communitys help in deciding which way i should go i might be wrong about some of my procon assumptions if i am please tell me all thoughts and suggestions are welcome and appreciatedthanks,"['html', 'css']" +40213,urlwithstring returns nil it may be very easy but i do not seems to find out why is urlwithstring returning nil herelocalisationname is a arbitrary string herensstring webname localisationname stringbyaddingpercentescapesusingencodingnsutf8stringencoding nsstring stringurl nsstring stringwithformatalcommunautaurbainedemontraalquabeccanadaeoutputcsvoeutf8sensorfalsekey webnamensurl url nsurl urlwithstringstringurl,"['iphone', 'objective-c']" +40214,functional programming in c can someone guide me how do functional programming in c is there some good online material that i can referplease note that i know about the library fc i want to know how to do that with c standard library alonethanks,['c++'] +40215,sending long sms messages i have got an app that lets users send sms messages works great when the message 160 characters after that things work lessperfectly seems like there are a few options heremanually break the message up into multiple smss send each part as a separate smsuse the multipart send sms function sendmultiparttextmessagesend the message as an mms message senddatamessageheres my novice take on it1most well supported across carriers users may get mad that you just cost them and separate messages though instead of converting to mms or something2not sure if this is supported by different carriers and read that once the message is greater than 3 160 chars in length gets converted to mms anyway by different sms apps maybe stay away from this altogether3not sure how to do this and older phones might not support mms to send an mms using the android sdk do we just use the smsmanagersenddatamessage methodthanks,['android'] +40219,aspmvc viewdata is viewdata of mvc is equivalent to viewstate webforms,['asp.net'] +40220,programmatically get a screenshot of a page i am writing a specialized crawler and parser for internal use and i require the ability to take a screenshot of a web page in order to check what colours are being used throughout the program will take in around ten web addresses and will save them as a bitmap imagefrom there i plan to use lockbits in order to create a list of the five most used colours within the image to my knowledge it is the easiest way to get the colours used within a web page but if there is an easier way to do it please chime in with your suggestionsanyway i was going to use aca webthumb activex control until i saw the price tag i am also fairly new to c having only used it for a few months is there a solution to my problem of taking a screenshot of a web page in order to extract the colour scheme,['c#'] +40242,parse json into a listview friendly output so i have this json which then my activity retrieves to a string popular authors last month url itemoxylus sales1148 image url itemdigitalscience sales681 image items last week cost400 thumbnail url sales43 itemchristmas decoration balls rating3 id75682 cost30 thumbnail url sales27 itemxml flip book as3 rating5 id63869 items last three months cost500 thumbnail url sales641 itemimage logo shiner effect rating5 id55085 cost1500 thumbnail url sales533 itembanner rotator with auto delay time rating5 id243 it can be accessed here as well although it because it is quite a long string i have trimmed the above down to thisplay what is neededbasically i want to be able to access the items from items last week and create a list of them originally my plan was to have the thumbnail on the left with the item next to it but from playing around with the sdk today it appears too difficult or impossible to achieve this so i would be more than happy with just having the item data from items last week in the listcoming from php i am struggling to use any of the json libraries which are available to java as it appears to be much more than a line of code which i will need to deserialize i think that is the right word the json and they all appear to require some form of additional class apart from the jsonarrayjsonobject script i have which does not like the fact that items last week is nested again i think that is the json terminology and takes an awful long time to run on the android emulatorso in effect i need a preferably simple way to pass the items last week data to a listview i understand i will need a custom adapter which i can probably get my head around but i cannot understand no matter how much of the day i have just spent trying to figure it out how to access certain parts of a json string,['android'] +40244,how to generate a java call graph i would like to analyze and understand a certain java app and i think a call graph would be very useful how do i generate one i am using eclipse,['java'] +40249,what does the new mean in javascript looking through the jquery source in the function now i see the followingfunction now return new datei have never seen the plus operator prepended to the new operator like this what does it do,"['javascript', 'jquery']" +40261,why does not modulemethod definedmethod work correctly i am trying to check if a method is defined in a module using modulemethod definedmethod and it is returning false it should be returing truemodule something def selfanother 1 endendsomethingmethods has another listed but somethingmethod definedanother returns falseis this maybe not working because the method is defined on self if this is the case is there another way to check if the method is defined on the module other than using method defined,['ruby'] +40288,javascript array rotate i was wondering what was the most efficient way to rotate a javascript arrayi came up with this solution where a positive n rotates the array to the right and a negative n to the left length and length arrayprototyperotate function and thisunshift thissplice n thislength which can then be used this wayvar months jan feb mar apr may jun jul aug sep oct nov decmonthsrotate new dategetmonth my original version above has a flaw as pointed out by christoph in the comments bellow a correct version is the additional return allows chainingarrayprototyperotate function and thisunshiftapply this thissplice n thislength return thisis there a more compact andor faster solution possibly in the context of a javascript framework none of the proposed versions bellow is either more compact or fasteris there any javascript framework out there with an array rotate builtin still not answered by anyone,['javascript'] +40310,when should i create a new exception class i notice that a number of java exception classes differ only in the name of the class and do not add any new functionality most exceptions for example just seem to override exception or exceptionstring message this goes against the tenets of inheritance ie inherit to add new functionality what are some good reasons to create a new exception class,['java'] +40349,using or for folder paths in c when writing file paths in c i found that i can either write something like c or c and get the same path which one is recommended i heard somewhere that using a single was more recommended than using with as an escaped sequence,['c#'] +40353,generate a call sms etc from iphone is it possible to generate a call or an sms from an application that we create for iphone also is it possible to record a call,['iphone'] +40367,how to catch a specific exception in jdbc how to catch a specific exceptions in jdbc examples primary key exception or foreign key exception,['java'] +40373,rails tagging and tag list i saw alot of good tagging plugins but are these plugins really what i wanti want to tag products users and news search by tags list all tags like select thistinct tag for a autocomplete tag list and button tags like here on stackoverflowi am thinking of a separated model tag what is the best way to do it,['ruby-on-rails'] +40393,should i start with html or xhtml so which one to start with html or xhtml i am a beginner and wants to have solid foundations of markup language but as i started learning i found some people use html and some xhtml,['html'] +40401,how can i create nunit tests with resharper i am trying to get into unit testing with c various people told me to go with nunit since it is better than mstest apparently i have no idea and it also has very good support in resharper which i am usingnow i have never written a unit test before in my life bear with me i am a university student resharper has this nice createunittests context menu option that i have seen others casually looking over the shoulder use to great success you rightclick in a method select createunittests and there you go a test skeleton is created you just fill in the important bitsnow when i try the same resharper wants me to create a new test project and when i let it it creates what i am assuming a mstest project with obviously a mstest test template but i already have a class libarary project which references nunitframework and has a few nunit tests that resharper is more than willing to run still it only ever creates mstest test templates and only ever in special test project projectswhat am i doing wrong am i doing something wrong at all or is creating nunit test templates not possible with resharper i have searched the net and read the documentation of resharper and nunit and i still cannot figure out is this even possible or whati would be grateful if anyone could provide me with a sort of guide to using resharper nunit edit i am using resharper 45 and nunit 253edit2 apparently i am an idiot createunittests is not part of resharper but part of visual studio and thus only ever works with mstest,['c#'] +40409,reducing the memory footprint of a c application i am developing a c application which needs to process approximately 40 english sentences all these sentences are being stored in a tree where each node in the tree is a class which has these fieldsclass treenode protected string word protected dictionarystring treenode childrenmy problem is that the application is using up all the ram i have 2 gb ram when it reaches the 20th sentence so it only manages to process half the sentences and then it slows down drastically what can i do to try and reduce the memory footprint of the applicationedit let me explain a bit more my application so i have approximately 30 english sentences and from each sentence i am generating further sub sentences like thisexample sentence football is a very popular sportsub sentences i needfootball is a very popular sport is a very popular sporta very popular sportvery popular sportpopular sportsporteach sentence is stored in a tree word by word so considering the example above i have a treenode class with the word field football and the children list has the treenode for the word is the child of the is node is the a node the child for the a node is the very node i need to store the sentences word by word since i need to be able to search for all the sentences starting with example football is so basically for each word in a sentence i am creating a new subsentence and this is the reason i ultimately end up with 40 different sentences storing the data in a database is not an option since the app needs to work on the whole structure at once and it will further slow down the process if i had to stay writing all the data to a database thanks,['c#'] +40426,word document creation api in java i would like to create a word document using a template replace some variables fields and save it as a new word document i was thinking using apache poi is it the best for this purposecan you share your impression from it,['java'] +40433,what does the operator do in java what function does the caret operator serve in javawhen i try thisint a 5nit gives mefor and 5 returns 0 for and 4 returns 1 for and 6 returns 3 so i guess it does not perform exponentiation but what is it then,['java'] +40439,what kind of loop is for found in torvaldslinux26git kernelmutexc line 171i have tried to find it on google and such to no availwhat does for instruct,['c'] +40457,how to send through servletoutputstream characters in utf8 encoding my servlet code looks like thatresponsesetcontenttypetexthtml charsetutf8responsesetcharacterencodingutf8servletoutputstream out responsegetoutputstreamoutprintlnmyutf8 codethen i get the errorjavaiocharconversionexception not an iso 88591 character javaxservletservletoutputstreamprintservletoutputstreamjava89 javaxservletservletoutputstreamprintlnservletoutputstreamjava242 rtmservletscampaignlogicservletdopostcampaignlogicservletjava68 javaxservlethttphttpservletservicehttpservletjava637 javaxservlethttphttpservletservicehttpservletjava717how can i switch the charset of servlet us outputstream,['java'] +40471,check if int is between two numbers why cannot do you this if you try to find out whether an int is between to numbersif10 x 20instead of it youll have to doif10x x20which seems like a bit of overhead,['java'] +40476,sending emails with wamp i use the latest wamp and i get this when i try to send emailswarning mail functionmail failed to connect to mailserver at localhost port 25 verify your smtp and smtp port setting in phpini or use ini set in cwampwmaincreateaccountphp on line 8message delivery failedthe messageto subject hibody hinnhow are youif mailto subject body echopmessage successfully sentp else echopmessage delivery failedp do you need do download a mailserver alsoplease help,['php'] +40477,why was getenumerator stored in a separate interface from ienumerator i was wondering why the getenumerator method was factored out of ienumerator and placed in ienumerable it seems to me that it would make more sense to keep all of the enumerator methods in ienumeratorthanksscott,['c#'] +40481,static linking vs dynamic linking are there any compelling performance reasons to choose static linking over dynamic linking or visa versa in certain situations i have heard or read the following but i do not know enough on the subject to vouch for their veracity1 the difference in performance between static linking and dynamic linking is usually negligible2 1 is not true if using a profiling compiler that uses profile data to optimize program hotpaths because with static linking the compiler can optimize both your code and the library code with dynamic linking only your code can be optimized if most of the time is spent running library code this can make a big difference otherwise 1 still applies,"['c++', 'c']" +40488,map list onto dictionary is there a way to map a list onto a dictionary what i want to do is give it a function that will return the name of a key and the value will be the original value for examplesomefunctionlambda a a0 hello world hhello wworldthis is not a specific example that i want to do i want a generic function like map that can do this,['python'] +40490,should i use domready functions if my scripts are at the end of the body i know that in jquery we are told to use documentready in order to ensure that the dom elements are ready for interaction i know that this definitely applies if the script tags are in the head if they are at the end of the body after all of the dom elements should i still use a domready function are there browsers in which my code would fail if i did notthanks,"['javascript', 'jquery']" +40498,substantial android development in scala has anyone had success developing a substantial android app in scala is it a viable option yet are there any mature development environments given the state of the scala eclipse plugin it looks as if there is no good ide support at all other than possibly intellij ultimatea few people have posted tutorials describing how to fudge eclipse adt to sortof support scala and how to to slim the scala libraries using proguard but beyond that there has been worryingly little thiscussion about this topicupdate 20110801 an interesting article on androidscala from the developers behind the bump app bump dev blog how we use scala in bump for android,['android'] +40515,hibernate criteria returns children multiple times with fetchtypeeager i have an order class that has a list of ordertransactions and i mapped it with a onetomany hibernate mapping like soonetomanytargetentity ordertransactionclass cascade cascadetypeallpublic listordertransaction getordertransactions return ordertransactionsthese orders also have a field orderstatus that are used for filtering with the following criteria public listorder getorderforproductorderfilter orderfilter criteria criteria gethibernatesession createcriteriaorderclass addrestrictionsinorderstatus orderfiltergetstatusestoshow return criterialistthis works and the result is as excpectednow here is my question why when i set the fetch type explicitly to eager do the orders appear multiple times in the resulting listonetomanytargetentity ordertransactionclass fetch fetchtypeeager cascade cascadetypeallpublic listordertransaction getordertransactions return ordertransactionshow would i have to change my criteria code to reach the same result with the new setting,['java'] +40519,how do i backup a database file to the sd card on android i would like to add a feature to my android app that automatically backs up the sqlite database to the sd cardwhats the best way to go about this are any examples or tutorials available,['android'] +40520,html adding line numbers to textarea alli have a textarea as in code below how to thisplay the line numbers on the left hand side of itis there a jquery plugintextarea nameprogram idprogram rows15 cols65 textareathanks,['html'] +40531,find out 20th 30th nth prime number i am getting 20th but not 30th python the question is to find the 10th prime number i wrote the following python code for this the problem is i get the right answer for the 10th 20th prime but after that each increment of 10 leaves me one off the mark i cannot catch the bug here count1 to keep count of prime numbersprimes tuple to hold primescandidate3 variable to test for primeswhile count20 for x in range2candidate if candidatex0 candidatecandidate2 else pass primesprimescandidate candidatecandidate2 countcount1print primes print 20th prime is primes1in case youre wondering count is initialised as 1 because i am not testing for 2 as a prime numberi am starting from 3 and candidate is being incremented by 2 because only odd numbers can be prime numbers i know there are other ways of solving this problem such as the prime number theorem but i wanna know whats wrong with this approach also if there are any optimisations you have in mind please suggestthank you,['python'] +40541,aspnet control with visiblefalse cannot be used in javascript i have an aspnet text control fromdate whose visible property is set to false but i wanted a client side javascript to be able to toggle the visibility property using css propertieselement1stylethisplay none hides the elementelement1stylethisplay shows the elementbut when i attempt to get the textbox i get null on var element1 documentgetelementbyidfromdatewhen i try the same code with visbletrue as the default on the fromdate aspnet control it works although that is not the behavior i needany ideas,"['asp.net', 'javascript']" +40546,jquery qtip how to attach a single tooltip div to multiple target divs the normal behavior for the jquery qtip plugin is to create a new hidden div for every tooltip item assigned is there a way to tie a single hidden tooltip element to multiple targets to avoid cluttering the domcontrived examplediv idfoo1divdiv idfoo2divscript foo1foo2qtipcontenttest script creates two elements rather than one div classqtip stylethisplaynonetestdivdiv classqtip stylethisplaynonetestdivif qtip is unable to do this can anyone recommend another jquerybased tooltip plugin which supports rich html using only a single tooltip container thanks,['jquery'] +40556,keep aspect ratio with image width in css is there a way to fix the aspect ratio of images given a smaller width using css maybe by using jquery javascript thanks,"['javascript', 'jquery', 'css']" +40557,mysql varchar lengths and utf8 in mysql if i create a new varchar32 field in a utf8 table does it means i can store 32 bytes of data in that field or 32 chars multibyte,['mysql'] +40576,data directory has no readwrite permission in android i m using android 15 my data directory does not have the readwrite permissions systemoutprintlndata can writeenvironmentgetdatadirectorycanwritesystemoutprintlndata can readenvironmentgetdatadirectorycanreadso please suggest me how to provide permissions for the data directorywhat i am trying to do is to create a file and add some content to it in the data storage of the emulator like as belowprivate void writetosdcard try file lroot environmentgetdatadirectory if lrootcanwrite file lfile new filelroot samplefiletxt filewriter lfilewriter new filewriterlfile bufferedwriter lout new bufferedwriterlfilewriter loutwritex loutclose catch ioexception e logem ctag could not write file egetmessage,['android'] +40589,handling executescalar when no results are returned i am using the following sql query and the executescalar method to fetch data from an oracle databasesql select username from usermst where userid2string getusername commandexecutescalarit is showing me this error messagesystemnullreferenceexception object reference not set to an instance of an objectthis error occurs when there is no row in the database table for userid2how should i handle this situation,['c#'] +40607,javascript circular references and memory leaks from what i recall of a not too thistant past javascript interpreters suffered from memory leaking issues when faced with circular referencesis it still the case in the latest browsers eg chrome ff 35 etc,['javascript'] +40609,download link fails in ie i was trying to implement a download link and put it beside one of my report table so that users can download a csv file and open it with applications like excelthe records are generated dynamically based on the query made by usersso somewhere in my controller there is something likeresponseheaderscontenttype textcsvresponseheaderscontentthisposition attachment filenamexcsvreturn responsestreamdynamically generated csv requestrequestthis works in both firefox chrome but fails in iewhen i print out the response headers i found that several headers were added to my response by web2pyexpires cachecontrol etcand when i remove the cachecontrol header by doing the followingdel responseheaderscachecontrolit works in ieso it seems like ie has trouble dealing with a downloadable file with cachecontrol set to certain valuenow my question iswhy does web2py add these response headers implicitly and maybe without a way to set it offis there any side effect when i delete the cachecontrol header this waythanks in advance,['python'] +40621,datetimeparseexact string format exception i am trying to convert a string into datetime with the following c codedatetime dto datetimeparseexactdateto mmddy cultureinfoinvariantcultureeachtime i pass dateto as 112010 it fails instead it needs the string to be 01012010 what string format should i use to support both 01012010 and 112010,['c#'] +40637,implementing all portscanning techniques in c creating raw low level packets in c i am trying to write a port scanner in c i did some research on port scanning methodsif you are interested these are the links i found useful ppt presentation scanningaspold nmap the art of port scanning dochtmlport scanning techniques port scanning interactive example coming to my question these are the port scanning methodstcp connect scantcp syn scantcp fin scantcp xmas scantcp null scantcp window scanudp scanbut i implemented only tcp connect scanshown here but this is dead slow taking 05sec to test each port for implementing rest of the methods i need the packet level access i need to create raw packets is it possible to do that in c if so how to do that,"['c#', '.net']" +40639,javascript dot notation the following line is apparently written best in dot notation i am trying to clean my javascript code to make it strict what does it mean if iens6 var tipobjdocumentall documentalldhtmltooltip documentgetelementbyid documentgetelementbyiddhtmltooltip i added some context to my line of code in case this helpsi know nothing about dom i am not trying to support internet explorer 4 this is not my code and i wouldnt be able to write javascript myself i am only trying to get it compliant and the jslint tool says about this lineproblem at line 17 character 43 dhtmltooltip is better written in dot notation,['javascript'] +40646,get a list of available content providers is there a way to programmatically list all available content providers on a device no real use case i just thought it might be neat to see what apps i have installed on my phone that have exposed content providers,['android'] +40649,android listview get data index of visible item i have an android listview created with a simpleadapter that has more items in it than fit in the screen after the list has been scrolled i need to get the position in the data model of the first visible item in the list basically i want a function like listviewgetchildat0getpositionindatamodeladapter has a few functions in it like getitemidposition that looked useful however the simpleadapter implementation just returns the passed in position not a row id like i would hoped a brute force solution would be to get the view at index 0 and compare it to the view for each item in the adapter however there does not seem to be an easy way to get the view for a particular position from the adapteranyone have any thoughts,['android'] +40655,calling a class prototype method by a setinterval event i have a simple javascript class one method of this class sets up a timer using setinterval function the method that i want to call every time the event fires is defined inside the same class the question is how can i pass this method as a parameter to the setinterval functionone attempt was setintervalthisshowloading 100 but does not work this method access class properties so i need the this referencethis is the sample code function loadingpictureid thisimgarray null thiscurrentimg 0 thiselementid id thisloadingtimer null loadingpictureprototypeshowloading function ifthiscurrentimg imgarraylength currentimg 0 documentgetelementbyidthiselementidsrc imgarraythiscurrentimgsrc loadingpictureprototypestartloading function documentgetelementbyidthiselementidstylevisibility visible loadingtimer setintervalshowloading 100,['javascript'] +40656,hit testing in wpf i have an ellipse on a canvas and i am doing hit testing on itevery time i click the stroke of the ellipse the test passesif i click in the middle of the ellipse the test failsthis is goodafter i fill the ellipse like this myellipsefill new solidcolorbrushcolorsbluethe test pasess also when i click in the middle of the ellipsehow can i thisable thiseven when ellipse is filled the test will fail when i click in the middlethanks,"['c#', '.net']" +40661,c how to implement databinding without control is there a simple way to implement databinding when neither of both classes is of type controlin my case i would like to bind a variable to a property of a custom toolstripbuttonedit for clarification when binding to a control i can use controls databindings collection however i am searching for a way to bind properties regardless of the source and target typeedit using winforms,['c#'] +40666,implementing unit testing with the iphone sdk so i have followed this tutorial to setup unit testing on my app when i got a little stuck at bullet point 8 in that tutorial it shows this image which is what i should be expecting when i build however this is not what i get when i build i get this error message command binsh failed with exit code 1 as well as the error message the unit test has created then when i expand on the first error i get thisphasescriptexecution run script build3d poolbuilddebugiphonesimulatorlogictestsbuildscript1a6ba6ae10f28f408ac2a8shcd usersjamesdesktopfyp3d poolsetenv action buildsetenv alternate group staffsetenv xcode version major 0300setenv xcode version minor 0320setenv yacc developerusrbinyaccbinsh c usersjamesdesktopfyp3d poolbuild3d poolbuilddebugiphonesimulatorlogictestsbuildscript1a6ba6ae10f28f408ac2a8shdevelopertoolsrunplatformunittestsinclude412 note started tests for architectures i386developertoolsrunplatformunittestsinclude419 note running tests for architecture i386 gc offobjc12589 gc forcing gc off because objc thisable gc is settest suite usersjamesdesktopfyp3d poolbuilddebugiphonesimulatorlogictestsoctesttests started at 20100104 210506 0test suite logictests started at 20100104 210506 0test case logictests testfail startedusersjamesdesktopfyp3d poollogictestsm17 error logictests testfail must fail to succeedtest case logictests testfail failed 0 secondstest suite logictests finished at 20100104 210506 0executed 1 test with 1 failure 0 unexpected in 0 0 secondstest suite usersjamesdesktopfyp3d poolbuilddebugiphonesimulatorlogictestsoctesttests finished at 20100104 210506 0executed 1 test with 1 failure 0 unexpected in 0 02 secondsdevelopertoolsrunplatformunittestsinclude448 error failed tests for architecture i386 gc offdevelopertoolsrunplatformunittestsinclude462 note completed tests for architectures i386command binsh failed with exit code 1now this is very odd as it is running the tests and succeeding as you can see my stfail firing because if i add a different test which passes i get no errors so the tests are working fine but why am i getting this extra build failit may also be of note that when downloading solutionstemplates which should work out the box i get the same error i am guessing i have set something up wrong here but i have just followed a tutorial 100 correctly if anyone could help i would be very gratefulthanksedit according to this blog this post and a few other websites i am not the only one getting this problem it has been like this since the release of xcode 32 assuming the apple dev center documents and tutorials etc are pre32 as wellhowever some say its a known issue whereas others seem to think this was intentional i for one would like both the extended console and in code messages and i certainly do not like the command binsh error and really think they would have documented such an update hopefully it will be fixed soon anywayupdateheres confirmation it is something changed since the release of xcode 321this image is from my test build using 321 this one is from an older version 314 the project for both was unchangededit image urls updated,['iphone'] +40672,what are differences between insert and update in mysql it seems insert and update do the same things to meis there any occasions where i should use insert instead of update and vice versa,"['mysql', 'sql']" +40674,possible to pass null from powershell to a net api that expects a string apinamespace classlibrary1 public class class1 public static string teststring input if input null return it is null if input stringempty return it is empty else return nonempty string of length inputlength scriptaddtype path ctempclasslibrary1classlibrary1bindebugclasslibrary1dllclasslibrary1class1testnullclasslibrary1class1testobjectnullclasslibrary1class1testpsobjectnullclasslibrary1class1testdummyvarclasslibrary1class1testprofiledummypropertyoutputit is emptyit is emptyit is emptyit is emptyit is emptywhat am i missing,['.net'] +40676,character before a function call what is the difference between these two function calls in phpinit getsomevariableinit getsomevariable,['php'] +40677,php how to perform htmlspecialchar on an arrayofarrays how do i run the php function htmlspecialchars on an array of array objectsi have the following coderesult set array 0 array home id 1 address 4225 nasmyth dr city plano state tx zip 76798 1 array home id 8 address 4229 nasmyth dr city plano state tx zip 75093 this does not work since result set is an array of arrays and htmlspecialchars is expecting a stringhtmlspecialcharsresult set ent quotes utf8 updateplease note that even though there are quite a few answers below none of them work for an arrayofarrays the answers below only work for simple arraysi have tried the following but it does not workarray walk recursiveresult set htmlspecialchars arrayent quotesutf8i get the following error htmlspecialchars expects parameter 2 to be long string givenupdate 2when i tryfunction cleanoutputvalue return htmlspecialcharsvalue ent quotes utf8print rresult setprintprint rarray walk recursiveresult set cleanoutputi get the following undesired outputarray 0 array home id 1 address 4225 nasmyth dr city plano state tx zip 76798 1 array home id 8 address 4229 nasmyth dr city plano state tx zip 75093 1update 3when i tryfunction cleanoutputvalue return htmlspecialcharsvalue ent quotes utf8result set array 0 array home id 1 address 4225 nasmyth dr city plano state tx zip 76798 1 array home id 8 address 4229 nasmyth dr city plano state tx zip 75093 cleanedoutput arrayforeach result set as rs cleaned array mapcleanoutput rsprint rcleanedoutputi get the following undesired resultshomes,"['php', 'html']" +40679,net combining two generic lists let us say i have two generic lists of the same type how do i combine them into one generic list of that type,['.net'] +40682,android layout how to create a headercontent layout how do i go about creating the following layout in androidi want a header that is a header that stays the same at all times the only thing that should change is the area below the headerthink of it as a webpage where the contentarea is where its all happening h e a d e r c o and t e and t sure its easy enough to create a linearlayot add a view on the top and then another view below that tada but what im after is how you set up or design the project so its easy to just change whats in the contentwhat i really would like is to be able to swipe see here the area and then just roll in a new viewthing in the contentarea but keep the same headerwhat i really miss is a comprehensive library of layoytexamplesregards,['android'] +40691,reversing byte order in net in the code below why do x and y take on different values than what i would think intuitivelyif the bytes 07 are written to the buffer should not the resulting long have bytes in the same order it is like it is reading the long values in reverse orderx 0x0706050403020100 longy 0x0706050403020100 longz 0x01020304050607 longmemorystream ms new memorystreambyte buffer new byte 0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07 mswritebuffer 0 bufferlengthmsflushmsposition 0binaryreader reader new binaryreadermslong x readerreadint64long y bitconvertertoint64buffer 0long z bitconvertertoint64bufferreversebytetoarraybyte 0byte xbytes bitconvertergetbytesxbyte ybytes bitconvertergetbytesybyte zbytes bitconvertergetbyteszi do not know what to tag this question beyond just netbitconverterislittleendianis false if my computer is big endian why does this happenthis is a windows 7 64bit machineintel core2 quad q9400 266 ghz lga 775 95w quadcore processor model bx80580q9400supermicro mbdc2sbxo lga 775 intel x48 atx intel motherboardthe results of this code in response to jasons commentbyte buffer new byte 0x00 0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07 long y bitconvertertoint64buffer 1consolewritelinebitconverterislittleendianconsolewritelineyresultfalse506097522914230528,['.net'] +40702,how can i select all of the sundays for a year using python using pythonhow can i select all of the sundays or any day for that matter in a year 01032010011020100117201001242010 these dates represent the sundays for 2010 this could also apply to any day of the week i suppose,['python'] +40705,best way to cache data in android i have an arraylist of custom simple serializable objects i would like to cache to thisk and read on relaunch my data is very small about 25 objects and at most 5 lists so i think sqlite would be overkill in the iphone world i would use nskeyedarchiver and nskeyedunarchiver which works great on android i have attempted to do this with with a fileoutputstream and objectoutputstream and while the result is the same the performance is terrible is there a better read faster way to cache small objects to the file system in android,['android'] +40719,red x gui crash i almost gave up on solving it i am facing a complex bug with the dundas charting for winforms tool used with ms visual studio 2008 cthe following error occurs when a gui event is raised on the chart object while itas invalidating when the error happens the dundas chart shows a big x mark exception text systemargumentoutofrangeexception axis object the interval can not be zeroparameter name diff at dundaschartingwincontrolaxisscaleadouble at dundaschartingwincontrolaxisadouble double axisscalesegment datetimeintervaltype at dundaschartingwincontrolaxisachartgraphics boolean axisscalesegment boolean at dundaschartingwincontrolaxisbchartgraphics boolean boolean at dundaschartingwincontrolaxisresizechartgraphics chartgraph elementposition chartareaposition rectanglef plotarea single axesnumber boolean autoplotposition at dundaschartingwincontrolchartareaachartgraphics at dundaschartingwincontrolchartpictureresizechartgraphics chartgraph boolean calcareapositiononly at dundaschartingwincontrolchartpicturepaintgraphics graph boolean painttoplevelelementonly renderingtype renderingtype xmltextwriter svgtextwriter stream flashstream string documenttitle boolean resizable boolean preserveaspectratio at dundaschartingwincontrolchartpicturepaintgraphics graph boolean painttoplevelelementonly at dundaschartingwincontrolchartonpaintpainteventargs e at systemwindowsformscontrolpaintwitherrorhandlingpainteventargs e int16 layer boolean thisposeeventargs at systemwindowsformscontrolwmpaintmessage m at systemwindowsformscontrolwndprocmessage m at systemwindowsformscontrolcontrolnativewindowwndprocmessage m at systemwindowsformsnativewindowcallbackintptr hwnd int32 msg intptr wparam intptr lparamthe scenario is as followsi have a grid view that has the list of objects that reference the series being plotted the plot is being updated each 1 second using chartinvokeadata this is the event that causes the crashprivate void datagridview1 cellendeditobject sender datagridviewcelleventargs e if ecolumnindex 0 erowindex 0 appdataseries bounddata datagridview1ecolumnindex erowindexowningrowdatabounditem as appdataseries if bounddatatag null tag is of type dundaschartingwincontrolseries switch ecolumnindex case 1 muchartseriesbounddataseriesnamechartarea bounddatachartareatostring when you change the chart area of a series it crashes the chart control also when you enable or thisable a series using series1enabled true it could crash the chart control muchartchartareasbounddatachartareavisible true break the drawing is done in the following mannera background thread is capturingit is raising the eventondataavailable every secondhereas the handlervoid servicewrapperinstance dataavailableobject sender dataavailableeventargs e if eviewid currentviewid if muchartinvokerequired muchartinvokemethodinvokeradata else adata public void adata if muchartseriescount 0 for int i 0 i currentviewseriescount i addnewpointcurrentviewseriesixvalue muchartseriesicurrentviewseriesiyvalue currentviewseriesiisinverse 1 1currentviewseriesichartcolor datasavermuchartseriesinameaddnew datapointcurrentviewseriesixvaluedoublecurrentviewseriesiyvalue public void addnewpointdouble xvalue series ptseries double yvaluecolor pointcolor try ptseriespointsaddxyxvalue yvalue if draggeddroppedseriesmappercontainskeyptseries foreach series item in draggeddroppedseriesmapperptseriesdraggeddroppedseriesversions itempointsaddxyxvalue yvalue muchartinvalidate if i remove the previous line the plot doesnat crash but doesnat update catch exception ex loggerlogtracelevelerror addnewpoint ex the interesting thing about this bug is that it doesnat happen on all machines i noticed that it happens on high specs machines like our 8 core cpu dell machine and a new quad core laptop that we got here this raised the suspect of a threading problem however threading seems to be okay since the chart object is accessed from the same main thread please help me with thisupdatethe assignment using the setter that takes place in the function datagridview1 cellendedit muchartseriesbounddataseriesnamechartarea bounddatachartareatostring calls chartinvalidate internally while the invoked function adata that updates that chart calls it explicitly i read in the msdn library that controlinvalidate does not force a synchronous paint unless controlupdate is called after it i am almost certain that the conflict is happening upon invalidation even though everything is happening on the same thread since the redrawing is taking place asynchorounsely i understood whats happening this way but i do not know how to avoid it controlupdate is doing me no goodchangethechartconfigurationsdrawthechanges this works asynchronously updatedatapointsdrawthechanges this works while the first change has still not occured yet for example the series might have been moved to a difference chart area and dundaschartingwincontrolaxisscaleadouble the last function in the stack traceis being called on already hidden chart area that is just a thoughtupdatei logged the thread id from both the event handler and the addnewpoint function and it was the same as the main threads,['c#'] +40722,how to add style from code behind i want to add a style ahover to a hyperlink control from code behindi can do like this hyperlink hlrow new hyperlinkhlrowstyleaddcolor 0hlrowstyleaddtextdecoration nonebut how can i add styles for ahover for the hyperlink controldo i need to define a class and associate that class with this control if yes how,"['c#', 'asp.net', 'css']" +40726,shared memory between 2 processes applications i cannot find any useful answer for this question although it has been asked in a different way several timesi want to share a memory between two processes two different applicationsso that one of them can write to that memory and the other can readis this possible in net howthanks,['.net'] +40728,inherit interfaces which share a method name there are two base classes have same function name i want to inherit both of them and over ride each method differently how can i do that with separate declaration and definition instead of defining in the class definitioninclude cstdioclass interface1public virtual void name 0class interface2public virtual void name 0class realclass public interface1 public interface2public virtual void interface1name printfinterface1 okn virtual void interface2name printfinterface2 okn int main interface1 p new realclass pname interface2 q reinterpret castrealclassp qname i failed to move the definition out in vc8 i found the microsoft specific keyword interface can do this job successfully code belowinclude cstdio interface interface1 virtual void name 0 interface interface2 virtual void name 0class realclass public interface1 public interface2public virtual void interface1name virtual void interface2namevoid realclassinterface1name printfinterface1 oknvoid realclassinterface2name printfinterface2 oknint main interface1 p new realclass pname interface2 q reinterpret castrealclassp qname but is there another way to do this something more general that will work in other compilers,['c++'] +40739,why is djangos meta an oldstyle class i noticed that in django models there is a class meta which makes some additional definitions about the modelmy question is why is this done as an oldstyle class ie not subclassing object is there a reason for this or is this just a custom could i do it as a newstyle class in my projects,['python'] +40752,what encoding used when invoke fopen or open when we invoke system call in linux like open or stdio function like fopen we must provide a const char filename my question is what is the encoding used here it is utf8 or ascii or iso8859x does it depend on the system or environment settingi know in ms windows there is a wopen which accept utf16,['c'] +40755,handle arbitrary exception print default exception message i have a program a part of which executes a loop during the execution of this loop there are exceptions obviously i would like my program to run without errors but for the sake of progress i would like the program to execute over the entire input and not stop when an exception is thrown the easiest way to do this would be by implementing an except block however when i do this it excepts all exceptions and continues with the program and i never get to see the exception message which i need in order to debugis there a way to except any arbitrary exception and be able to print out the exception message in the except block,['python'] +40762,can i have eclipse close all my projects when i exit i would like to have eclipse 35 if that matters close any open projects i have before i exit my workspace is this possibleedit i forgot to mention that these projects are remotely stored and it would be nice for that reason as well,['java'] +40766,python equivalent of define func or how to comment out a function call in python my python code is interlaced with lots of function calls used for debuggingprofilingtracing etcfor exampleimport loggingloggingrootsetlevelloggingdebugloggingdebughelloj 0for i in range10 j i loggingdebugi d j d ijprintjloggingdebugbyei want to define these resource consuming functions out of the code something like the c equivalentdefine loggingdebugvalyes i know the logging module logging level mechanism can be used to mask out loggings below set log level but im asking for a general way to have the python interpreter skip functions that take time to run even if they dont do muchone idea is to redefine the functions i want to comment out into empty functionsdef lazyargs passloggingdebug lazythe above idea still calls a function and may create a myriad of other problems,['python'] +40778,submit form with delay while entering data into input field i have a simple form that i need to submit automatically when text is enteredi can use the onchange or onkeyup without the best resulthtml is form action idfusionsearchform methodpost input typetext clastd input idfusion searchtext formand jqueryjqueryfusionsearchformkeyupfunction thissubmitthis submits every time a character is entered i much rather would have it so there was a delay before submit so you can finish your typing that focus stays on the input field ready to type after submit if reloadany way to delay a formsubmit so the user can finish typing before form is submittedupdate to code to a more jquery kind of way to submitbr anders,['jquery'] +40798,how to send html email i found a way to send plain text email using intentfinal intent emailintent new intentandroidcontentintentaction sendemailintentsettypetextplain emailintentputextraandroidcontentintentextra email new string emailintentputextraandroidcontentintentextra subject subject emailintentputextraandroidcontentintentextra text testbut i need to send html formatted texttrying to settypetexthtml does not work,['android'] +40810,understanding keys in databases this question is geared towards mysql since that is what i am using but i think that it is probably the same or similar for almost every major database implementationhow do keys work in a database by that i mean when you set a field to primary key unique key or an index what do each of these do and when should i use each oneright now i have a table containing a few fields one of them being a guid minus the and around it i set the guid field to the primary key and i see that it created a binary tree so it improves search performance but what differentiates that from other types of keysi realize this may not really be programming related although it is development related i was not sure where exactly to ask this but so is what i use the most so i will ask here migrate as necessary,['mysql'] +40818,resize uitableviewcell textlabel i have a uitableviewcell that i would like to add a view to the right in addition to the accessory view i tried setting the size of textlabel to be a few pixels narrower but it just resizes it backis there any way to resize textlabel,['iphone'] +40822,drawback to creating a separate iis application pool for each website application currently on our production iis web farm we host about 15 applications in a single app pool default app pool there are two websites and about 13 virtual directoriesa colleague has recommended that we change our iis configuration so each application is a separate app pool with identical settingsis there any drawback or potential issues to doing thisis it possible that aspnet applications could have been built with the requirements that they are all within the same app pool,['asp.net'] +40829,in java why are arrays objects are there any specific reasons is there any reason why an array in java is an object,['java'] +40836,is it possible to get the users apple id through the sdk is it possible to get the users information such as apple id through the sdk i am writing an app which will require an account linked to the app user i want to allow the user to have one account across multiple devices so using the device id is not possible the easiest way to do this i am thinking is to use the app users apple id as this accounts id so not requiring them to create yet another account,['iphone'] +40840,ruby equivalent to pythons help when working in interactive python i tend to rely on the builtin help function to tell me what something expects andor returns and print out any documentation that might help me is there a ruby equivalent to this functioni am looking for something i could use in irb for example in interactive python i could type help1which would then printhelp on int objectclass intobject intx base integer convert a string or number to an integer if possible a,"['python', 'ruby']" +40841,using a uiwebview with loadhtmlstringloaddata breaks the back and forward buttons workaround there is a known problem with embedded uiwebviews that if you load data into them using loadhtmlstring or loaddata the cangobackcangoforward properties and gobackgoforward methods do not work these only work when using loadrequestsince safaris normal app cache does not work in embedded uiwebviews creating a native app that effectively caches otherwise live content becomes impossibleunusable that is i can cache the contents of the html javascript images etc and load them via loadhtmlstring or loaddata but then the back and forward buttons do not worki could also use loadrequest and specify a file url but that breaks when it comes to communicating with the live site even if i specify a tag because of cookie domain issuesi have a work around that involves basically reimplementing the app cache using local store and not having the native app do any caching itself which is ok but not really ideal are there any other work aroundssomething i missed,['iphone'] +40856,comment and uncomment a block of code is there a shortcut in netbeans to highlight a block of code and commentuncomment it,['java'] +40857,best api for lowlevel audio in windows i am working on an audio application written in c i need to provide live audio playback under windows i need to decide which audio api to use i am planning to use the basic waveout api but i wanted to check to see what the community here recommendsi want code that will just work on any recent version of windows with no need to install libraries and i want minimal latencyi do not need or want any effects i just need to faithfully play whatever wave samples the application generatesmy understanding is that most of the professional audio applications on windows use asio which gives excellent low latency but i do not want asio because i want my code to just work and most people do not have asio preinstalled on their computers at a later date i may go back and also add asio as an option but i am going for the most general solution firstis there anything out there that would be better than waveout for my purposes or is that the best choice,['c'] +40870,how do you return a json object from a java servlet how do you return a json object form a java servletpreviously when doing ajax with a servlet i have returned a string is there a json object type that needs to be used or do you just return a string that looks like a json object eg string objecttoreturn key1 value1 key2 value2,['java'] +40873,could anyone explain andor post c code for the algorithm of advance kalman filter i need an explanation of advance kalman filter algorithm preferably a c code but only the algorithm will work for me,['c'] +40874,mysql 126 incorrect key file for table i got the following error from a mysql query126 incorrect key file for tablei have not even declared a key for this table but i do have indices does anyone know what could be the problem,['mysql'] +40875,why does not the requestadditionaltime method work on restart in vista7 i have been doing some extensive testing of a windows service i have been writing in c net 35 i am having trouble getting windows to give me enough time for my service to shutdown properly when i restart or shutdown the computer even though i am invoking the requestadditionaltime method which should update the scm and keep my service running my code works properly if i manually stop the service however i have primarily been testing this code in windows vista and windows 7 upon deciding to test the code in windows xp everything worked perfectly does anyone know why this call does not work in vista7 i am thinking i need some kind of permission to keep the system from shutting down that i get by default in xp but not in vista7,"['c#', '.net']" +40878,how to handle null values for sqldecimal datatype in filehelper classes i am trying to load a file using filehelpers like it already except for this one issue p i have to save csv file data into the database and so am using a sqldecimal datatype to store the decimal values of the csv files filehelpersfieldoptionalfilehelpersfieldconvertertypeofsqldecimalconverterpublic sqldecimal rateall this works fine until i have a blank value for the fixrate1 this is flagged up with an error warn exceptionnull value found for the field rate in the class swtrade you must specify a fieldnullvalueattribute because this is a valuetype and cana t be nulli tried putting filehelpersfieldnullvaluesqldecimalnull but it obviously throws an error an attribute argument must be a constant expression typeof expression or array creation expression of an attribute parameter typeeven though i override the fieldtostring method in the sqldecimalconverter class the function is not called when reading the data well this being the case is there a way i can assign any null value or even some other hardcoded value to the rate data which i can then replace with a null direclty in my own logic please do let me know if you would need more detailsthanks in advance,['c#'] +40882,hiding extjs grid column header i understand i can hide grid column header using the codegridid xgrid3hdrow thisplaynone but i do not want to use any css change how to do the same using javascript,['javascript'] +40891,c equivalent of ld in java for stringformat for instance 112lf in c becomes 112f in javahow about for long format,['java'] +40899,how text length of a uitextview can be fixed i have a uitextview user can write maximum 160 character in the textviewhow can i fixed the maximum text length of a uitextview,['iphone'] +40911,delete operator and arrays i have an abstract base class and derived classint main base arrayptr3 for int i 0 i 3 i arrayptri new derived some functions here delete arrayptr return 0i am not sure how to use the delete operator if i delete array of base class pointers as shown above will this call derived class objects destructors and clean the memory,['c++'] +40914,generating an action url in javascript for aspnet mvc i am trying to redirect to another page by calling an action in controller with a specific parameter i am trying to use this linewindowopen urlactionreport survey new id selectedrow but i could not make it work it gives the following error cs1012 too many characters in character literalcannot i generate the action url this was on the client side or do i have to make an ajax call by supplying the parameter and get back the needed url this does not seem right but i want to if it is the only way is there an easier solution,"['asp.net', 'javascript']" +40917,facebook charset detection mechanism today i have looked into html code of facebookcom and found something like thisinput typehidden valueaa aa namecharset testit is repeated two times inside the formformany idea what this code might be useful for some kind of serverside client charset detection as far as i know browser charset is being transmitted in http request anyway an acceptcharset header,"['php', 'html']" +40918,can someone explain the difference between strong soft weak and phantom references and the usage of it i have been trying to understand the difference between different references but the theory does not provoke any ideas for me to visualize the samecould anyone please explain in brief the different referencesan example for each would do better,['java'] +40919,svn keeps corrupting files with mine how to fix i have got a visual studio c project which is under version control svni have always commited and updated the project without any problems but a couple of hours ago visual studio throws the following error when i try to launchrebuild the projectfiles has invalid value mine illegal characters in pathi do not know how to fix this problem what should i do,['c#'] +40924,c class template of specific baseclass let us say i have the classesclass baseclass a public base int iclass bpublic base bool band now i want to define a templated classtemplate typename t1 typename t2 class basepair t1 first t2 secondbut i want to define it such that only decendants of class base can be used as templateparametershow can i do that,['c++'] +40932,what are rendering differences between latest versions of safariwindows vs safarimac vs google chromemac vs google chromewindows should i check in all or in any one is enough because all share same rendering engine webkitmy question is related to html css rendering i know one difference safari for windows and mac both have font smoothing anti alisaingis there any other differences,['css'] +40936,how to get predefined paper size by paperkind i need to get paper size by systemdrawingprintingpaperkind are there any predefined values i do not want to hardcode or calculate paper sizes i just want to get it programmatically thanks,"['c#', '.net']" +40953,save data from ajax request in variable jquery how can i get the data from a ajax request saved in a variable with jquery,['jquery'] +40958,preemptive basic authentication with apache httpclient 4 is there an easier way to setup the http client for preemptive basic authentication than what described herein previous version 3x it used to be a simple method call eg httpclientgetparamssetauthenticationpreemptivetruethe main thing i want to avoid is adding the basichttpcontext to each method i execute,['java'] +40970,sql query theory question singlestatement vs multistatement queries when i write sql queries i find myself often thinking that there is no way to do this with a single query when that happens i often turn to stored procedures or multistatement tablevalued functions that use temp tables of one sort or another and end up simply combining the results and returning the result tablei am wondering if anyone knows simply as a matter of theory whether it should be possible to write any query that returns a single result set as a single query not multiple statements obviously i am ignoring relevant points such as code readability and maintainability maybe even query performanceefficiency this is more about theory can it be done and do not worry i certainly do not plan to start forcing myself to write a singlestatement query when multistatement will better suit my purpose in all cases but it might make me think twice or a little bit longer on whether there is a viable way to get the result from a single query i guess a few parameters are in order i am thinking of a relational database such as ms sql with tables that follow common best practices such as all tables having a primary key and so forthnote in order to win accepted answer on this youll need to provide a definitive proof reference to web material or something similar,['sql'] +40976,how do you prompt the user to rate your iphone app without waiting for them to delete the app i am referring to the popup window that asks the user to submit a reviewratingi know it can be done since the aardark app does itit asks several times in fact almost too spammy but there has to be an api to trigger the rating request google is giving me no love on this one,['iphone'] +40988,how to configure spring javamailsenderimpl for gmail i am trying to find the correct properties to use to connect to the gmail smtp sever using the javamailsenderimpl classlet me first say that i have tried the approach found here this worked fine but when i tried the configuration below that post with the exact same authentication information i received a javaxmailauthenticationfailedexception my currently configuration looks like thisbean idmailsender class orgspringframeworkmailjavamailjavamailsenderimpl property nameusername value property namepassword valuex property namejavamailproperties props prop keymailsmtphostsmtpgmailcomprop prop keymailsmtpport587prop prop keymailsmtpauthtrueprop prop keymailsmtpstarttlsenabletrueprop props propertybeanwhy am i still getting this javaxmailauthenticationfailedexception if i know that my credentials are correctupdatehere is my updated code based on the answers below i am still receiving the same exceptionbean idmailsender class orgspringframeworkmailjavamailjavamailsenderimpl property nameusername value property namepassword valuex property namejavamailproperties props prop keymailsmtpfromprop prop keymailsmtpuserprop prop keymailsmtppasswordxprop prop keymailsmtphostsmtpgmailcomprop prop keymailsmtpport587prop prop keymailsmtpauthtrueprop prop keymailsmtpstarttlsenabletrueprop props propertybean,['java'] +40989,how can i return a random line from a file interview question i am preparing for a phone interview i came upon these questions on the internet can anyone tell me some good answers for thesesuppose i give you a text file and ask you a to write a program that will return a random line from the file all lines must have equal probability to be returned same as part 1 except this time the entire text file cannot fit into main memory same as part 2 except now you have a stream instead of a fileplease helpokeveryone i really had a few ideas in my mintod before asking thisseeing the relentless attack by my fellow soers i am posting my answers please feel free to attack them too1 count the number of n in the file generate a random number between 1 and the number and return the line after the number1 n2 bring the file into main memory part by part and follow the above procedure3 i dont have much idea about this and would appreciate any inputsits wonderful that you guys really give an inspiration to push forward,"['c++', 'c']" +40990,sensitive data in memory i am working on a java password manager and i currently have all of the users data after being decrypted from a file sitting around in memory at all times and stored plainly as a string for thisplaying in the ui etcis this a security risk in any way i am particularly concerned with someone dumping or reading the computers memory in some way and finding a users naked datai have considered keeping all sensitive pieces of data the passwords encrypted and only decrypting each piece as needed and destroying thereafter but i would rather not go through and change a lot of code on a superstition,['java'] +41001,send activation email to user how would i do to check if a email actially exists cant understand how sites do to send mails with a unique link that the users clicks to validate that he is the owner of email make a 2 new columns called activationkey and activated and store some random string send an email with the activationkey and update the users activated 1 that match that activation linkregisterphpaactivatekey9cdfb439c7876e703e307864c9167a15any better ideas,['php'] +41008,net load two version of the same dll i need to load two versions of the same dll in order to compare their outputs i assume that i can use appdomains for this but i need some guidence,['.net'] +41013,why are not and and or operators in python i was not aware of this but apparently the and and or keywords are not operators they do not appear in the list of python operators just out of sheer curiosity why is this and if they are not operators what exactly are they,['python'] +41036,accessing using the mobilewififramework for a personal project of mine i am trying to retrieve iphone wifi signal strength i am fully aware that this in the land of undocumented goodness so please refrain from the no appstore answers anywho i have been reading up on previous wifi network scanner apps wifi stumbler but i am afraid most if not all reflect outdated sdk documentation hopefully this question will also provide some centralized insightful material with the most recent iphone sdk 312heres my incompletenotworking codeh void libhandle void airporthandle int openvoid int bindvoid nsstring int closevoid int scanvoid nsarray void mlibhandle dlopensystemlibraryprivateframeworksmobilewififrameworkmobilewifirtld lazyopen dlsymlibhandle apple80211openbind dlsymlibhandle apple80211bindtointerfaceclose dlsymlibhandle apple80211closescan dlsymlibhandle apple80211scanopenairporthandlebindairporthandle en0nslogresult libhandlewhen executed on the device it will produce my eversofavorite exception type exc bad access sigsegvi am thinking the dynamic loading call is not loading anything the directory systemlibraryprivateframeworks only lists a infoplist file with no binaries or aliasesprobably doing something terribly wrong wrong directory appreciate any helpalso as a follow up to extract the wifi information it might be done bygetinfocopy dlsymlibhandle apple80211getinfocopyand my questions are 1 has anybody had any luck with this 2 how do you get a header dump like i would using with classdump on objectivec libraries because mobilewifi is in c,['iphone'] +41049,how do i create an md5 hash of a string in cocoa i know sha1 is preferred but this project requires i use md5include opensslmd5h nsstring md5hasher nsstring query nsdata hashed query datausingencodingnsutf8stringencoding unsigned char digest md5hashed bytes hashed length null nsstring final nsstring stringwithutf8string char digest return finali got this code from an answer to another similar question on stackoverflow but i get the following error from gdb when the program breaks at return finalgdb p digest1 unsigned char 0xa06310e4 0206b260336316021ba9310225204gdb po finalcannot access memory at address 0x0gdb po digestprogram received signal exc bad access could not access memoryreason kern invalid address at address 0xb06236300x98531ed7 in objc msgsend the program being debugged was signaled while in a function called from gdbgdb has restored the context to what it was before the callto change this behavior use set unwindonsignal offevaluation of the expression containing the function nsprintfordebugger will be abandonedi cannot make any sense of it,['objective-c'] +41061,cross platform c library for gui apps free of charge simple to learnuse cross platform c library for gui apps am i looking for qtbonus question can i develop with the said librarytoolkit on mac then recompile on pclinuxsuper bonus question link to tutorial andor download of said librarythe truth is that i am in the process of catching up on the c family coming from web development xhtmlphpmysql to learn iphone development i do understand that c is not c or objectivec but i want to keep the learning curve as simple as possible not to get too off topic but i am also on the lookout for good starter books and websites i have found this so fari am trying to kill many birds with one stone here i don understand that there are platform specific extensions but i will try to avoid those for porting purposesthe idea is that i want to write the code on one machine and just compile thrice macwinlinux if objective c will compile on windows and linux as well as os x then that is good if i must use c that is also fine,['c'] +41069,use tnsnamesora in oracle sql developer i am evaluating oracle sql developermy tnsnamesora is populated and a tnsping to a connection defined in tnsnamesora works fine still sql developer does not thisplay any connectionsoracle sql developer soars mentions that ifyou have oracle client software and a tnsnamesora file already installed on your machine oracle sql developer will automatically populate the connections navigator from the net service names defined in tnsnamesorai also tried to set my tns admin environment variable but after restarting sql developer there are still no connections thisplayedany ideasanyone successfully working with sql developer and tnsnamesora,['sql'] +41072,eclipse have multiple dynamic web projects contribute to a single war file i am in a situation where i basically want to be able to have a web project in eclipse where the webcontents folder is merged from multiple projects instead of only a single dynamic web projectif i have ajsp in project a and bjsp in project b i would like to end up with a single web application in the web container where ajsp and bjsp sit next to each other in the same folder it would be perfect if all files not just the jspfiles could be merged like thisthis is to be able to have a core version of our application but being able to handle customer specific changes easilyi know i can do this with suitable ant magic but we want to have something that works well for our current eclipse based development process we will use jsr330 dependency injection on java classes and essentially i would like something along the lines of dependency injection but just for any resource and not just classescan eclipse do thisif eclipse cannot would an ear deployment be suitable perhaps i currently have experience with wars only,['java'] +41082,sftp using ftplib hi alli need to download a file from a host using sftpdo you know if is it possible to do that using python ftplibi saw an example here but when i try to connect i receive eoferrori tried this codeimport ftplibftp ftplibftpftpconnect 1234 22 this method returns with an error after long time so i cannot perform a call to logini cannot try the constructor ftphost user passwd acct timeout because my port is 22 but ftplib default is 21if i follow the exampleftp ftplibftp1234ftp ftplibftp123422i receive a connection refused so i cannot enter any username password can you help me thank you very much,['python'] +41091,efficiency of hibernates tablepersubclass inheritance strategy i am thinking about table layout for a hibernatemanaged class hierarchy and certainly the table per subclass technique strikes me as the most appropriate in a general sense however thinking through the logic i have some concerns about its performance especially as the number of subclasses scaleto give a very brief and classic example let us say you have the following classespublic abstract class animal int pkey string namepublic class dog extends animal long numslipperschewed int is not large enoughpublic class cat extends animal short micecaught but here int is far bigger than required i am eliding getters and setters and hibernate mappings etc just assume they are the basic obvious casethe database tables for these entities make sense you get nice denormalisation and so on however what query does hibernate do in order to pull out an individual animal i can think of at least two cases where this might happensome other entity having a onetoone or onetomany mapping such as a pet field of a human class this would store the pkey so when hibernate fetches a human object it will need to fetch the corresponding animal object too when given the pkey of the animal what queryies will hibernate use to extract and unmarshall the actual animal data given that it could reside in the cat or dog tableshql such as from animal where namerex let us assume names are unique this is similar to the above in that it lets you identify a row in the superclass table but you do not know which subclass table to inspect for further details does hql even let you issue a query from an abstract class using subclass specific stuff works nicely though eg from cat where micecaught 5i can think of two ways that this could be done in sql and neither seems pretty one is to run an exists query on each subclass table for the given pkey and then load from the table that returned a hit alternatively hibernate could perform some horrible union query joining in all the tables essentially simulating the tableperhierarchy scheme in that the result set would include attributes for all possible subclasses with the individual selects from the subclass tables returning null for the irrelevant arguments this latter case would probably even need to add a synthetic thiscriminator column so that hibernate could know which subclass table actually returned the row and thus what java class they should be parsed intothings get hairier too if you have subtypes of concrete typespublic class greyhound extends dog float lifetimeracingwinningsnow for a given animal pkey there may be valid rows in the dog and greyhound tables meaning that my first approach of manually checking the class that corresponds to a pkey gets a lot tougherthe reason i am so concerned is that i will be wanting to use this approach on a class hierarchy with about 70 classes with a maximum nesting chain of 45 levels so performing a union query on all of that is likely to have horrible performance does hibernate have any tricks up its sleeve to keep this relatively performant or is loading a reference to one of these classes by pkey going to take a long time,['java'] +41094,how to check if nsstring is numeric or not possible duplicateiphone how to check that a string is numeric only i have one nsstring then i want check the string is number or noti mean nsstring val 5 ifval isnumber return trueelse retun falsehow can i do this in objective c,['objective-c'] +41103,transactions in c first of all this will not be a post about database transactions i want to know more about the transactionmodel in net 20 and higher since i am developing against net 35 newer models are apprechiatednow what i would like to acheive is something like the following public void withdrawdouble amount using transactionscope scope new transactionscope money amount if money 0 scopecomplete which would mean that when the money is less than 0 everything inside the transactionscope should be rolledback however it is nota simple test as followed importantobject obj new importantobject1 consolewritelineobjmoney objwithdraw101 consolewritelineobjmoneyprovided that the stadard money amount is 100did i miss something here or is this not how the transactions should work and what are the performance losses using this model,"['c#', '.net']" +41104,javascript object id do javascript objectsvariables have some sort of unique identifier like ruby has object id i do not mean the dom id attribute but rather some sort of memory address of some kind,['javascript'] +41108,how does java efficiently search jar files for classes suppose i have 500 jar files linked to my program totaling over 500 mb size of all the jars not each one and my program makes a call to a class located in one of them how does java search through jars for a class and what is the efficiency of this on ologn,['java'] +41110,how to thisable auto submit behavior when hitting enter key i want to hit enter key to go to p2htm or p3htm according to the input text that i was typing in and i also want to hit submit1 button to alertno1 manuallyit works in firefox but in ie6 when i hit enter key it will submit the submit buttonhow can i make the thing right in ie 6 as it is in firefox i use javascript and jqueryinput idtext2 typetext onkeyupifeventkeycode13go2 input idtext3 typetext onkeyupifeventkeycode13go3 input idsubmit1 typesubmit valuesubmit onclickalertno1 script typetextjavascript function go2 windowlocation p2htm function go3 windowlocation p3htm script,['javascript'] +41116,why does nvl always evaluate 2nd parameter does anyone know why oracles nvl and nvl2 function always evaluate the second parameter even if the first parameter is not nullsimple testcreate function nvl test return number asbegin dbms outputput linecalled return 1end nvl testselect nvl 0 nvl test from dualreturns 0 but also prints callednvl test has been called even though the result is ignored since first parameter is not null,['sql'] +41120,ejb 31 ejb injection into pojo being a complete turbot this afternoon and cant seem to find the answer anywherewith the new ejb 31 spec is it possible to inject an ejb into a pojo i know in ejb 30 the ejb annotation could be used to inject an ejb but this did not work on simple pojosif it is not do i have to look the bean up in jndi as i know you cannot simple use the new keywordthanks in advance karl,['java'] +41121,detect thistance scrolled from top jquery how can i detect the number of pixels scrolled in a browser window i need this to dynamically adjust the height of a 100 height div i am using jqueryedit i cannot just use scrolltop because i am working with a 100 height div with overflow set to auto firefox does not detect browser scrolling due to this the only thing scrolling is a 100x100 div,['jquery'] +41130,rendering a rails view to string for email i would like to send emails from a table every night at midnight so i have created a model to track all communications to be sent this communication model stores who the letter is to from and the contents of the letter to be sent as html the user enters a criteria to match for whom the letter is intended state country favorite color and so which returns a list of acceptable matchesthis list of acceptable matches is iterated across and a new communication is generated for each how do i render the contents of a partial view to a string to store in the database for delivery at midnightcommunication communicationnewparamscommunicationcommunicationbody render partial with local variables to string herejanuary 8 2010 i have implemented the solution proposed by neutrino and my code looks like thiscommunicationmessage body render to string partial letterssmall letter locals quote quotethe drawback to this approach is that it requires a context so it must be rendered within a controller this rules out generating the email using a rake file as others have pointed out the approach of using a communication model may introduce some unnecessary complexity at this time since the conditions i use to generate the list of recipients is never stored i have opted to continue to use a communication model,['ruby-on-rails'] +41136,web scraping etiquette i am considering writing a simple web scraping application to extract information from a website that does not seem to specifically prohibit this i have checked for other alternatives eg rss web service to get this information but there are none available at this stagedespite this i have also developedmaintained a few websites myself and so i realize that if web scraping is done naivelygreedily it can slow things down for other users and generally become a nuisanceso what etiquette is involved in terms ofnumber of requests per secondminutehourhttp user agent contenthttp referer contenthttp cache settingsbuffer size for larger filesresourceslegalities and licensing issuesgood tools or design approaches to userobotstxt is this relevant for web scraping or just crawlersspiderscompression such as gzip in requestsupdatefound this relevant question on meta etiquette of screen scaping stackoverflow jeff atwoods answer has some helpful recommendationsother related stackoverflow questionsoptions for html scraping,['html'] +41140,how to execute web request in its own thread i am creating an android application which has to execute web requests in the background and then handle the received data and modify the user interface according to the server responsethe goal of posting requests and handling data in the background is to avoid the freezing of user interface currently however i notice that the user interface is freezing so i am not sure the logic is working as it is supposed tohere is the part of code which is supposed to post requests and handle responses in its own thread and then pass the data to guipublic class serverconnection queuestring requestsdefaulthttpclient httpclienthttphost targethosthandler handlerserverresponsehandler responsehandleractivity activitypublic serverconnectionactivity activity thisactivity activity thisresponsehandler serverresponsehandler activity httpclient new defaulthttpclient targethost new httphosttarget domain 80 http requests new linkedliststringprivate runnable requestsender new runnable override public void run ifrequestsisempty string requeststring requestsremove httpget httpget new httpgetrequeststring httpgetaddheaderaccept textxml string encodingstring testusertestpass string sencodedstring base64coderencodestringencodingstring try string scontent fetchurlrequeststring sencodedstring xmlparser xmlparser new xmlparser list product products xmlparsergetproductsscontent responsehandleronproductsresponseproducts catchexception ex logetag exgetmessage public void sendrequeststring requeststring requestsaddrequeststring handler new handler handlerpostrequestsenderthe method sendrequest is called from the main activity which implements serverresponsehandler i guess the request is executed in its own thread and by calling responsehandleronproductsresponseproductsthe list of products data from the web is passed to main activity anyway due to poor performance i would appreciate if anyone could correct any possible issue in the logic above or suggest any other better option,"['java', 'android']" +41156,how to get the size of a winforms form titlebar height so if it is toolwindow or a minimizable form i want to be able to get its height programmaticallyis this possible if so how,"['c#', '.net']" +41165,iis7 set nocache for all aspx pages but not imagescssjs i would like to not cache my aspx pages anywhere for some reason ie ignores meta tags which are set from my master pagemeta httpequivexpires content0meta httpequivcachecontrol contentnocachemeta httpequivpragma contentnocachei am trying to see if i can set my http response header to cachecontrol nocache setting something like httpcontextcurrentresponseheadersaddcachecontrol nocache httpcontextcurrentresponseheadersaddexipres datetimenowadays1toshortdatestringin every page would be painful i am thinking if there is anyway we can set this in iis7 add this header to aspx pages but not imagescssjs is it possible edit as per suggestion in adding a custom http response header adds the header to all files including jscssimages so adding cachecontrolnocache here did not work eitheredit2 i am thinking about adding a httpmodule something similar to gossnerarchive20080312iis7howtosendacustomserverhttpheaderaspx any suggestions,['asp.net'] +41168,drop user from sql server database how can i drop user from a database without dropping it is loggingthe script should check if the user exists in database if does then drop the user,['sql'] +41171,benefits of an enterprise service bus where can i find some information on the uses and benefits of an enterprise service bus esbi am looking for information aboutthe kinds of problems and esb helps to solvethe alternatives to an esb and the tradeoffs in selecting between themwhat you need to do as a developer to build esbcompatible systemsi am looking for a finer level of detail than just wikipedia or online marketing brochures from vendors ideally some example code would help to clarify whats involved in taking advantage of an esb information from a net or java perspective would be the most usefulthanks,"['java', '.net']" +41172,cannot access protected member objectmemberwiseclone i am trying to use memberwiseclone on a custom class of mine but it throws up this errorcannot access protected member objectmemberwiseclone via a qualifier of type blbgamebase v2enemy the qualifier must be of type blbgamebase v2gamebase or derived from itwhat does this mean or better yet how can i clone an enemy class,['c#'] +41181,dependency management with maven i have lately become a big fan of maven for controlling the build cycle for my application however i have encountered some rough edges with mavens dependency management i am wondering if these are limitations of the tool and paradigm necessary evils of dependancy management or if im just using the tool incorrectly first is the matter of transitive dependencies as i understand it if you provide a dependency maven will in turn find any dependencies of that dependency that is great but for many of my dependencies this has not worked for example including hibernate in my projectdependency groupidorghibernategroupid artifactidhibernatecoreartifactid version332gaversiondependencyresults in a missing dependency of slf4j i need to manually add this dependency which i assumed would be mavens job the same goes for spring if i add springmvc as a dependency should not all of the basic servlet dependencies be added for me because springmvc would need this stuff i am referring to the servlet jsp jstl libraries second is the management of repositories maven comes shipped with a default main repository but i have found that in many cases this repository is not up to date for example ifyou want spring3 you have to manually add the springsource repository and if you want hibernate 35 you have to add the jboss repository it seems to defeat the point of automatic dependency management when you have to hunt down the correct repositories yourself this hunting soon gets complicated for example to add spring3 you may want the spring release repo the spring externals repo and the spring milestone repo closely related to number 2 is ensuring you have the correct version of an artifact i have been burned several times by including the wrong versions of dependent artifacts for a given artifact for example the wrong version of the servletjspjstl apis for spring3 or the wrong version of persistence annotation apis for hibernate the repositories are filled with many versions some with confusing names like productx3ga productx3rc1 productx3snapshot productx3cr product3beta etc some of these are obvious rc release candidate but it can be confusing trying to determine the order of these versions finally the issue of the type a dependency i probably just do not understand this well enough but many repo artifacts are of type pom not jar several times i have added a dependency jar to my project only to find out at build time that the repo jar does not actually exist example is orghibernate ejb3persistence in the jboss repo with some experimenting i can usually get a build to work but is dependency management in general this complicated i still prefer this approach to manually adding jar files to my project but i would be interested to learn how to improve my maven dependency management skills,['java'] +41182,cannot use this in member initializer is this legal does it contain a hidden bug or flaw visual studio does not give any errors or warnings but resharper does summary immutable tuple for two summarypublic class pairtvalue1 tvalue2 singletontvalue1 public tvalue2 value2 get private set public pairtvalue1 value1 tvalue2 value2 funcpairtvalue1 tvalue2 string tostringfunc thisvalue1 value2 tostringfuncthis red light2 singletontvalue1,['c#'] +41184,get column name of property mapped with hibernate how can i access the hibernate mapping of my model to find out the column name of a property the column name is not specified in the mapping so hibernate generates it automatically i would like to create a native sql statement including this column name,"['java', 'sql']" +41186,how to create a default stream insertion operator in c i have a class similar to boostany in that it is a templated container class i would like to have a method to write the contained value to a string however if the contained type does not provide a stream insertion operator i would like my method to return some default tring rather than failing to compile below is as close as i have come and should make it clear as to what i am trying to donamespace w namespace hide template typename t stdostream operatorstdostream out const t t return stdoperatorout typeidtname template typename t struct c t t stdstring tostring const using namespace hide stdostringstream oss oss t return ostr this works pretty well with some caveats for example if i want to actually provide an overloaded insertion operator for a class then that operator has to either be in the same namespace as the class or it has to be in the w namespace for it to be consideredit also has problems with any type that already has a nonmember stdoperator eg char and stdstring if t is one of those types then the oss t line above becomes ambiguous this can be worked around by adding overloads for these types inside the w namespace for examplestdostream operator stdostream out const stdstring s return stdoperator out smy question is has anyone found a better method than this why do i have to add my own overloads for things like stdstring is this all supported according to the standard or am i taking advantage of nonstandard behavior i am testing with g 433,['c++'] +41195,is there a net library similar to gnu readline i am considering writing a console application in c and i want to incorporate history completion and command line editing features something like gnu readline but not necessarily as extensive as thatis there an existing library for net which provides this type of functionality i guess one option would be to use interop services to call gnu readline but is there a native option,"['c#', '.net']" +41201,instantiate generic type in c class pretty basic question in cclass datat t obj public data allocate to obj from t here some activatorcreateinstance method obj how do i do this,['c#'] +41203,when is the value of a c out or ref parameter actually returned to the caller when i make an assignment to an out or ref parameter is the value immediately assigned to the reference provided by the caller or are the out and ref parameter values assigned to the references when the method returns if the method throws an exception are the values returnedfor exampleint calleroutvalue 1int callerrefvalue 1mymethod123456 out calleroutvalue ref callerrefvaluebool mymethodint invalue out int outvalue ref int refvalue outvalue 2 refvalue 2 throw new argumentexception is calleroutvalue 1 or 2 is callerrefvalue 1 or 2,"['c#', '.net']" +41208,php is urlencode a safe way to allow valid utf8 strings in the url i have user submitted tags that can be any type of valid utf8 string i want to know if it is safe to include them in the url merly by running them through urlencodein other words is urlencode safe to use for valid utf8 stringsby valid i mean id have already forceencoded them to utf8,['php'] +41212,django sort dict in template i want to print out a dictionary sorted by the key sorting the keys is easy in the view by just putting the keys in a list and then sorting the list how can i loop through the keys in the template and then get the value from the dictionary for company in companies for employee dependents in company dictcompanyitems endfor endfor just made up the examplethe part that does not work is the company dictcompanyitems part i need the company to be the value of company right now the company prat is looking for a key named company not the value of company from the loop abovei am doing a bit of processing to put the dictionary of dictionaries together changing the layout of the data is not really an option i figure the right approach is to write up a template tag just wanted to know if there was a builtin way i missed,['python'] +41215,why cant partial methods be public if the implementation is in the same assembly according to msdn documentation for partial classes partial methods are implicitly privateso you can have this definition in file1cspartial void method1 implementation in file2cspartial void method1 method bodybut you cannot have this definition in file1cspublic partial void method1 implementation in file2cspublic partial void method1 method bodybut why is this is there some reason the compiler cannot handle public partial methods,"['c#', '.net']" +41227,what is java home how does the jvm find the javac path stored in java home i would like to know what is java home where do i set the path of javacexe and javaexe it is in environment variables when i compile a java program from command prompt how does the jvm find javacexe,['java'] +41246,adding core data to an existing iphone app i have started my application and now i want to add core data to my app how can i add it,"['iphone', 'objective-c']" +41248,java how to use urlconnection to post request with authorization i would like to generate post request to a server which requires authentication i tried to use the following methodprivate synchronized string createnewproductpost string urlstring string encodedstring string title string content double price string tags string data producttitle urlencoderencodetitle productcontent urlencoderencodecontent productprice urlencoderencodepricetostring tags tags try url url new urlurlstring urlconnection conn conn urlopenconnection connsetrequestproperty authorization basic encodedstring connsetdooutputtrue connsetdoinputtrue outputstreamwriter wr new outputstreamwriterconngetoutputstream wrwritedata wrflush get the response bufferedreader rd new bufferedreadernew inputstreamreaderconngetinputstream string line while line rdreadline null process line wrclose rdclose return rdtostring catch malformedurlexception e eprintstacktrace return egetmessage catch ioexception e eprintstacktrace return egetmessage but the server does not receive the authorization data the line which is supposed to add authorization data is the followingconnsetrequestproperty authorization basic encodedstringand the line bufferedreader rd new bufferedreadernew inputstreamreaderconngetinputstream also throws an ioexceptionanyway i would be very thankful if anyone could suggest any fix of the logic above in order to enable authorization using post with urlconnectionbut obviously it does not work as it is supposed to although if the same logic is used for get request everything works fine,['java'] +41253,why do i get the error unsafe code may only appear if compiling with unsafe why do i get the following errorunsafe code may only appear if compiling with unsafei work in c and visual studio 2008 for programming on windows ce,['c#'] +41260,rails using content for after the corresponding yield inside layout i think this has been asked before but even though i searched google i have not come up with a solutionso this is what i am trying to do in rails 235layoutsapplicationhtmlerbhtml head some other stuff yield head head body content for head something that belongs in the head bodyhtmlnotice the yield before the content fori know that rails by default does not allow the content of head to be defined after yield has been used makes sense i even tried hooking into the template render process but no success so farso my goal is to be able to define content for inside partialstemplates and have the yield somehow delayed and executed just before the response is send to the browserhas somebody come up with a solutiongreetings and thanksfrankupdatei will go with wepposs idea and try myself on rack middleware thanks,['ruby-on-rails'] +41270,whats the difference between spring beanfactoryaware and applicationcontextaware both can be used to get bean instance but which one is better to be used to implement,['java'] +41296,cast from generics to specific subclass i have a class as suchpublic class myclasst where t onetype t myobj get set public myclasst obj public class subclass myclasstwotype snip for other similar class definitionwhere twotype is derived from onetypenow i have this utility methodpublic static myclasst factorytt vd where t onetype switchvdtypename case constanttwotype return new subclasstwotypevd snip for other type check which function is obviously checks the type of vd and the creates an appropriate myclass type the only problem is the above code would not compile and i do not know why the error is cannot cast expression of t to twotype,['c#'] +41302,net garbage collection what does it affect we have a situation where we are considering forcing a garbage collection on a server that is very low on ram 364gb used on average no it is not really an option to upgrade this server unfortunatelyone of our service processes written indirectly in c do not ask does work with the net components and then sleeps for 10 minutes when that service is sleeping it is often hanging on to 600mb of ram that could be shared with other processes seems somehow related to wse tracing being turned on for debugging i can watch it wake up and gc on the next iteration on the first com call to net however then the process does some work and by the time it goes to sleep the ram use is back up around 600mb well you can see where this goesthe question i am considering adding a garbage collection just before the process goes to sleep there are other services on this box that are doing net related tasks when i call a garbage collection in this service process does that gc affect all other net related processes on the box or just the process that requests the collection i am a bit worried about creating some sort of performance problem for processes outside of the one i care about,['.net'] +41306,java sockets and dropped connections whats the most appropriate way to detect if a socket has been dropped or not or whether a packet did actually get senti have a library for sending apple push notifications to iphones through the apple gatways available on github clients need to open a socket and send a binary representation of each message but unfortunately apple does not return any acknowledgement whatsoever the connection can be reused to send multiple messages as well i am using the simple java socket connections the relevant code issocket socket socket returns an reused open socket or a new onesocketgetoutputstreamwritemmarshallsocketgetoutputstreamflushloggerdebugmessage sent min some cases if a connection is dropped while a message is sent or right before socketgetoutputstreamwrite finishes successfully though i expect it is due to the tcp window is not exhausted yetis there a way that i can tell for sure whether a packet actually got in the network or not i experimented with the following two solutionsinsert an additional socketgetinputstreamread operation with a 250ms timeout this forces a read operation that fails when the connection was dropped but hangs otherwise for 250msset the tcp sending buffer size eg socketsetsendbuffersize to the message binary sizeboth of the methods work but they significantly degrade the quality of the service throughput goes from a 100 messagessecond to about 10 messagessecond at mostany suggestionsupdatechallenged by multiple answers questioning the possibility of the described i constructed unit tests of the behavior i am describing check out the unit cases at gist 273786both unit tests have two threads a server and a client the server closes while the client is sending data without an ioexception thrown anyway here is the main methodpublic static void mainstring args throws throwable final int port 8005 final int first buf size 5 final throwable errors new throwable1 final semaphore serverclosing new semaphore0 final semaphore messageflushed new semaphore0 class serverthread extends thread public void run try serversocket ssocket new serversocketport socket socket ssocketaccept inputstream s socketgetinputstream sreadnew bytefirst buf size messageflushedacquire socketclose ssocketclose systemoutprintlnclosed socket serverclosingrelease catch throwable e errors0 e class clientthread extends thread public void run try socket socket new socketlocalhost port outputstream st socketgetoutputstream stwritenew bytefirst buf size stflush messageflushedrelease serverclosingacquire1 systemoutprintlnwriting new packets sending more packets while server already closed connection stwrite32 stflush stclose systemoutprintlnsent catch throwable e errors0 e thread thread1 new serverthread thread thread2 new clientthread thread1start thread2start thread1join thread2join if errors0 null throw errors0 systemoutprintlnrun without any errorsincidentally i also have a concurrency testing library that makes the setup a bit better and clearer checkout the sample at gist as wellwhen run i get the following outputclosed socketwriting new packetsfinished writingrun without any errors,['java'] +41312,java finding out why a class is loaded i am currently having the problem that i have a partial program that is trying to load a class but fails because it cannot find this class looking at the stack trace i cannot see any particular reason for why the vm tries to load this particular class at the first place are there any tools that would let me figure out why a particular class is being loadedhint i am already getting a stack trace at the exact point where the jvm tries to load the class through an agent however the stack trace contains no line numbers therefore i only know which method triggers the class being loaded not which statement then even knowing the statement may not be enough a single statement can cause a class to be loaded in many ways because sometimes the vm needs to load part of the transitive closure of classes,['java'] +41323,why can i write a generic catch statement in c that does nothing possible duplicatewhy cant i catch a generic exception in c i have been reviewing and writing circuit breaker code recently the following method compiles but the catch block is never entered i have plenty of workarounds and this is not the only way to get the right behavior filtering exceptions but i am curious why this compiles and does not workpublic void attemptcalltexceptionaction action where texception exception try action catchtexception e this block is never entered stateactuponexceptione throw here is a test that should enter the catch block of the previous methodtestmethodpublic void throw an exception circuitbreakerattemptcallexception throw new exception test the circuit breakers state,['c#'] +41325,wpf c path how to get from a string with path data to geometry in code not in xaml i want to generate a wpf path object in codein xaml i can do this path datam 100200 c 10025 400350 400175 h 280how can i do the same in code path path new path pathdata foo this would not accept a string as path datais there a classmethod available that converts the string with pathdata to pathgeometry or similar surely somehow the xaml gets parsed and the datastring converted,['c#'] +41332,how to check if an array has an element at the specified index i know there is array key exists but after reading the documentation i am not really sure if it fits for this casei have an array and an index now i want to access the array but do not know if it has an index matching index i am not talking about an associative array but an plain boring normal numerically indexed arrayis there an safe way to figure out if i would really access an array element with the given index which is an integerphp may not care if i access an array with an index out of bounds and maybe just returns null or so but i do not want to even attempt to code dirty so i want to check if the array has the key or not,['php'] +41341,print the contents of an array code is one line for use in immediate window of visual studio can you write a convenient line of code that prints the contents of an arrayi will use this in the immediate window of visual studio 2008 so really it has to work in that window i may have left out some requirements but that is pretty much what i am trying to do,"['c#', '.net']" +41342,aspnet deployment how to avoid losing session state when updating code how do you workaround the fact that sessions are dropped every time you deploy certain code files to an aspnet website sometimes we need to deploy a crucial fix in the middle of the day but do not want to boot off all our users for it,['asp.net'] +41346,iphone reproduce the magnifier effect i would like be able to create a movable magnifier like the one you have when you copy and paste in a custom view for zooming a part of my viewi have no idea on how to start do you have any ideathanks in advance for your help,['iphone'] +41355,python matplotlib rectangular binning i have got a series of xy values that i want to plot a 2d histogram of using pythons matplotlib using hexbin i get something like thisbut i am looking for something like thisexample codefrom matplotlib import pyplot as pltimport randomfoo lambda randomgauss0010x foo for i in xrange50y foo for i in xrange50pairs zipxyusing hexbin i supply the xy series and it does the binning for mehexfig pltfigurehexplt hexfigadd subplot1hexplthexbinx y gridsize 20to use imshow i have to bin the data myselfdef histbinpairsdataxbinsybinsnone if ybins none ybins xbins xdata ydata zippairsdata xminxmax minxdatamaxxdata xwidth xmaxxmin yminymax minydatamaxydata ywidth ymaxymin def xbinxval xbin intxbinsxvalxminxwidth return maxminxbinxbins10 def ybinyval ybin intybinsyvalyminywidth return maxminybinybins10 hist 0 for x in xrangexbins for y in xrangeybins for xy in pairsdata histybinyxbinx 1 extent xminxmaxyminymax return histextentplot using imshowimdataextent histbinpairs20imfig pltfigureimplt imfigadd subplot1impltimshowimdataextent extent interpolation nearestpltdrawpltshowit seems like there should already be a way to do this without writing my own binning method and using imshow,['python'] +41359,why is the app waiting for the debugger when its not connected to computer it seems like every step i take in the android world i run into problems im soon up to 20 questions here on stackoverflow hehe usually i have my htc hero connected to the computer via usb and i launch the application either in debug mode or in normal modeso the last time i ran the app in normal mode then i thisconnect the device i want to try to have it free not connected to computer and i start the app from the menu when i do that i get a popup saying application x is waiting for the debugger to attach and there it stops and eventually dieswhy is it waiting for the debugger when the last time i ran the app while connected i didnt run it as debugregardsedit 1i might add this little weird factif i do run greenwhite arrow when the device is connected i still get a popup on the device saying application x is waiting for the debugger to attachedit 2found this page he restared his device and that worked for me too stupid not to try that right away,['android'] +41361,iphone localization get the phones language code i am localizing my iphone app for multiple languages and in addition to changing some of the strings i need to change some backgrounds is it possible to query the iphone and get the users language codethanks,['iphone'] +41373,hide select option in ie using jquery currently i am using jquery to hideshow select options using following codecustcol7 optionvalue sizevalue hidethis works fine in firefox but doesnt do any good in other browsers how to i hide options from select in chrome opera and ie,"['javascript', 'jquery']" +41376,how to use boostarray with unknown size as object variable i would like to use boostarray as a class member but i do not know the size at compile timei thought of something like this but it does not workint main boostarrayint 4 array 1234 myclass objarrayclass myclass private boostarrayint stdsize t array public templatestdsize t n myclassboostarrayint n array arrayarray the compiler gcc sayserror typevalue mismatch at argument 2 in template parameter list for atemplateclass tp long unsigned int nm struct boostarrayaerror expected a constant of type along unsigned inta got asize tawhich obviously means that one cannot use variablesized arrays as class members if so this would negate all the advantages of boostarray over vectors or standard arrays can you show me what i did wrong,['c++'] +41377,what are the uppercase and lowercase rules of ruby method name i am a ruby beginner from the book i know that a ruby method name should start with a lowercase letter or underscore but i found different scenariosif a method is defined outside a class it can only begin with lowercase letter ruby will complain with an error if you try to define a method which begins with an uppercase letter for exampledefine sayhi puts hello endsayhi hellobut the following code does not workdefine sayhi puts hello endsayhi it will produce an errorin main uninitialized constant sayhi nameerrorif a method is defined inside a class then it can begin with uppercase letterclass test def sayhi puts hello endendt testnewtsayhi hellodoes anyone know why 1 does not work while 2 work what are the exact rules the ruby method name,['ruby'] +41378,how to sort an nsarray using compareoptions i have an nsarray containing numbers as nsstring objects ie array addobjectnsstring stringwithformatd 100how do i sort the array numerically can i use compareoptions and specify nsnumericsearch as nsstringcompareoptions please give me an examplesample code,['iphone'] +41383,valueerror in django i am getting a strange error and cannot figure out why i would appreciate any input i have been stuck on this for a few days here is my codemodelspyclass employeemodelsmodel lastname modelscharfieldmax length75 firstname modelscharfieldmax length75 position modelsforeignkeyposition jurisdiction modelsforeignkeyjurisdiction basepay modelsfloatfield ot modelsfloatfield benefits modelsfloatfield totalpay modelsfloatfield class meta ordering lastname firstname def unicode self return s s selffirstname selflastname def full nameself return s s selflastname selffirstname def get absolute urlself return salariesemployees selfid urlspyfrom djangoconfurlsdefaults import from djangodemosalariesmodels import employeefrom djangoviewsgeneric import list detailemployee info queryset employeeobjectsall template name salariesemployeehtmlurlpatterns patterns rsalariesemployee list detailobject list employee infoemployeehtml object list when i run python managepy runserver and look at in my browser i get this errortraceback most recent call last file fdjangoinstantdjangopython26libsitepackagesdjangocoreserversbasehttppy line 279 in run selfresult applicationselfenviron selfstart response file fdjangoinstantdjangopython26libsitepackagesdjangocoreserversbasehttppy line 651 in call return selfapplicationenviron start response file fdjangoinstantdjangopython26libsitepackagesdjangocorehandlerswsgipy line 241 in call response selfget responserequest file fdjangoinstantdjangopython26libsitepackagesdjangocorehandlersbasepy line 73 in get response response middleware methodrequest file fdjangoinstantdjangopython26libsitepackagesdjangomiddlewarecommonpy line 57 in process request is valid paths requestpath info file fdjangoinstantdjangopython26libsitepackagesdjangomiddlewarecommonpy line 142 in is valid path urlresolversresolvepath file fdjangoinstantdjangopython26libsitepackagesdjangocoreurlresolverspy line 294 in resolve return get resolverurlconfresolvepath file fdjangoinstantdjangopython26libsitepackagesdjangocoreurlresolverspy line 218 in resolve sub match patternresolvenew path file fdjangoinstantdjangopython26libsitepackagesdjangocoreurlresolverspy line 123 in resolve kwargsupdateselfdefault argsvalueerror dictionary update sequence element 0 has length 1 2 is required,['python'] +41390,issue with windowclose and chrome im trying to close a child window with javascript and in firefox everything works fine but in chrome the window doesnt closehere is what im usingdocumentreadyfunction if windowopener windowopenerclosed windowopenerlocation windowclosei tried a suggestion on google but to no availanyone having a similar issue or know of a workaround,['javascript'] +41395,passing a string literal as a parameter to a c template class i want a class which takes two parameters in its constructor the first can be either an int double or float so typename t and the second is always a string literal my string so i guess const char constcan anyone give me some compilable code which declares a simple class template as described and declares an object of that class thanks,['c++'] +41396,subclassing dict should dict init be called here is a twofold question with a theoretical part and a practical onewhen subclassing dictclass imagedbdict def init self directory dict init self necessary should dict init self be called just as a safety measure eg in case there are some nontrivial implementation details that matter is there a risk that the code break with a future version of python if dict init is not called i am looking for a fundamental reason of doing one thing or the other here practically calling dict init is safemy guess is that when imagedb init self directory is called self is already a new empty dict object and that there is therefore no need to call dict init i do want the dict to be empty at first is this correcteditthe more practical question behind the fundamental question above is the following i was thinking of subclassing dict because i would use the dba syntax quite often instead of doing dbcontentsa all the time the objects only data attribute is indeed really a dict i want to add a few methods to the database such as get image by name or get image by code for instance and only override the init because the image database is defined by the directory that contains itin summary the practical question could be what is a good implementation for something that behaves like a dictionary except that its initialization is different it only takes a directory name and that it has additional methodsfactories were mentioned in many answers so i guess it all boils down to do you subclass dict override init and add methods or do you write a factory function that returns a dict to which you add methods i am inclined to prefer the first solution because the factory function returns an object whose type does not indicate that it has additional semantics and methods but what do you thinkedit 2i gather from everybodys answer that it is not a good idea to subclass dict when the new class is not a dictionary and in particular when its init method cannot take the same arguments as dicts init which is the case in the practical question above in other words if i understand correctly the consensus seems to be when you subclass all methods including initialization must have the same signature as the base class methods this allows isinstancesubclass instance dict to guarantee that subclass instance init can be used like dict init for instanceanother practical question then pops up how should a class which is just like dict except for its initialization method be implemented without subclassing this would require some bothersome boilerplate code no,['python'] +41399,c fast divisionmod by 10x in my program i use a lot of integer division by 10x and integer mod function of power 10for exampleunsigned int64 a 12345a a 100orunsigned int64 a 12345a a 10if i am going to use the right bit shift then i will get mode of 2x which is not what i wantis there any way i can speed up my program in integer division and mod functions,['c++'] +41415,how well is objectivej documented is the documentation good enough to start using it seriously i consider going with objectivej instead writing plain javascript but i wonder if the documentation of the language and the frameworks is good enough since it seems like a very young development,['javascript'] +41416,put external library to the jar i have added some external libraries to my java project in netbeansis it possible to put the external jar library to the java archive and not to put them into a separate for example lib directory,['java'] +41423,size of dynamically allocated array is it true that a pointer assigned to the starting address of a dynamically allocated array does not have the information of the size of the array so we have to use another variable to store its size for later processing the array through the pointerbut when we free the dynamically allocated array we do not specify the size instead we just free ptr or delete ptr how could free or delete know the size of the array can we use the same scheme to avoid storing the size of the array in another variablethanks,"['c++', 'c']" +41431,form for with nested resources i have a twopart question about form for and nested resources let us say i am writing a blog engine and i want to relate a comment to an article i have defined a nested resource as followsmapresources articles do articles articlesresources commentsendthe comment form is in the showhtmlerb view for articles underneath the article itself for instance like this render partial articlesarticle form for article comment do f ftext area text submit tag submit end this gives an error called id for nil which would mistakenly etc i have also tried form for article comment do f which renders correctly but relates ftext area to the articles text field instead of the comments and presents the html for the articletext attribute in that text area so i seem to have this wrong as well what i want is a form whose submit will call the create action on commentscontroller with an article id in the params for instance a post request to articles1comments the second part to my question is whats the best way to create the comment instance to begin with i am creating a comment in the show action of the articlescontroller so a comment object will be in scope for the form for helper then in the create action of the commentscontroller i create new comment using the params passed in from the form for thanks,['ruby-on-rails'] +41432,how to start a java project in xcode i am currently programming objectivec in the xcode ide and i understand it should also support java projects when i open the ide and choose new project i do not find any project templates that correspond to java i have snow leopard so i assume my xcode is uptodatehow do i start a java project in the xcode ide,['java'] +41434,jquery document ready fires too early for my requirements i am developing a site based all around photos some areas of this site require calculations based on image dimensions in order to work correctly what i have found is that document ready is firing too early and my gui is behaving erratically as a resulti removed the document ready function and replaced it with the good ol windowonload function since if i read correctly this function does not fire until images are fully loadedmy question is will this cause any problems and are there any other solutions that i have missed perhapsthanks for the help guys,['jquery'] +41435,firefox does not show tooltips on thisabled input fields firefox does not thisplay tooltips on thisabled fields the following thisplays tooltip in iechromesafari except firefoxinput typetext thisabledthisabled titletooltip textwhy does not firefox thisplay tooltip on thisabled fields is there a work around this,['html'] +41454,how to initialize array with custom type how do i initialize this array of custom typesposttype q new posttypeqarraylengthinitialize arrayfor int x 0 x qarraylength x qx new posttypeis there a better way to initialize this array,['c#'] +41470,how to get the number of lines in a textarea what i would like is to count the number of lines in a textarea egline 1line 2line 3line 4should count up to 4 lines basically pressing enter once would transfer you to the next linethe following code is not workingvar text mytextareaval var lines textsplitrvar count lineslengthconsolelogcountit always gives 1 no matter how many lines,"['javascript', 'jquery']" +41475,implementing full text search on iphone i am looking for suggestions on the best way to implement a fulltext search on some static data on the iphonebasically i have an app that contains the offline version of a web site about 50mb of text and i would like for users to be able to search for terms i figure that i should somehow build an table of word reference to file containing word or something put that into either core data or just sqlite index the word column then have the search facility search the table for search terms and take the intersection of the sets of results for the terms or somethingthat wouldnt allow people to search for phrases but it would be pretty easy and probably not too slowi would like to just use existing sdk features for this should i use core data or sqlitedoes anyone have any other ideas on how this could be done,['iphone'] +41490,sortedlist vs sorteddictionary vs sort this is a continuation of questions like this one are there any guidelines for tweaking the performance i do not mean gains in bigo just saving some linear timefor example how much does presorting save on either sortedlist or sorteddictionarysay i have a personclass with 3 properties to sort on one of them is age in years should i bucket the objects on age first should i first sort on one property then use the resulting listdictionary to sort on two properties and so onany other optimizations that spring to mind,['.net'] +41491,how do getters and setters work i am from the php world could you explain what getters and setters are and could give you some examples,['java'] +41501,how can i creating executable jar with swt that runs on all platforms swt comes with a base jar and one specific jar per platform windows linux32bit linux64bit mac aix how can i create an executable jar that will select the correct platform jar at runtimeedit i was thinking to supply all platform jars in a subdirectory and in main would then modify the class loader has anyone already tried this,['java'] +41502,sqlmetal wrongly generates the return type of my stored proc linq hi have a stored proc that always returns a single row depending of a parameterif bleh 1 select top 1 xyz from abcelse select top 1 def from abci must use sqlmetal to generate the datacontext but this stored procedure returns a imultipleresults which is an error instead it should return a isingleresultif i remove the if putting a single select call an isingleresult return type is generatedany ideas,['.net'] +41503,listing buildout configuration variables i would like to find out exactly what variables are available when using zcbuildout i can always look at the source but ideally i would find a list somewhere or be able to query buildout to find out what it thinks are the variables available at any one time is this possible,['python'] +41523,android listview selector color hi alli have 2 questions regarding a listview in androidhow can i get the color of the listviews focused row i tried to use the listviewgetselector method which according to its documentation should give me what i am looking for but it is giving me a drawable object which i do not know how to retrieve the color from if possiblehow can i set the color of the listviews focused row here i tried to use the setselector method on the listview passing it a colordrawable object but the result of doing it is that the whole background of the list view is painted in that color and this is not what i wanted of coursethanks,['android'] +41529,write a program that will print c if compiled as an ansi c program and c if compiled as a c program taken from it looks very compiler specific to me do not know where to look for,"['c++', 'c']" +41539,in c and c why is each h file usually surrounded with ifndef define endif directives why does each h file starts with ifndef define endif we can certainly compile the program without those directives,"['c++', 'c']" +41544,cookies not working on different pages ok i have a cookie set and i can clearly see it if i go to private data in firefox ok so when i echo it on one page in a certain directory it works wexamplecomdir but on the index page of the site wexamplecom it wont echo it says the cookie is not set yes i have cookies enabled yes i tried clearing cache and all that any ideas php btw,['php'] +41547,how would you split by rn if stringsplitstring did not exist using the net microframework which is a really cutdown version of c for instance systemstring barely has any of the goodies that weve enjoyed over the yearsi need to split a text document into lines which means splitting by rn however stringsplit only provides a split by char not by string how can i split a document into lines in an efficient manner eg not looping madly across each char in the docps systemstring is also missing a replace method so that would not workpps regex is not part of the microframework either,['c#'] +41550,pythonre how do i match an alpha character how can i match an alpha character with a regular expression i want a character that is in w but is not in d i want it unicode compatible that is why i cannot use azaz,['python'] +41569,fastest way to find out minimum of 3 numbers in a program i wrote 20 of the time is being spent on finding out the minimum of 3 numbers in an inner loop in this routinestatic inline unsigned intminunsigned int a unsigned int b unsigned int c unsigned int m a if m b m b if m c m c return mis there any way to speed this up i am ok with assembly code too for x86x86 64edit in reply to some of the comments compiler being used is gcc 433 as far as assembly is concerned i am only a beginner there i asked for assembly here to learn how to do this i have a quadcore intel 64 running so mmxsse etc are supported it is hard to post the loop here but i can tell you it is a heavily optimized implementation of the levenshtein algorithm this is what the compiler is giving me for the noninlined version of minglobl min type min functionmin pushl ebp movl esp ebp movl 8ebp edx movl 12ebp eax movl 16ebp ecx cmpl edx eax jbe l2 movl edx eaxl2 cmpl ecx eax jbe l3 movl ecx eaxl3 popl ebp ret size min min ident gcc ubuntu 4335ubuntu4 433 section notegnustackprogbitsthe inlined version is within o2 optimized code even my markers mrk 0xfefefefe before and after the call to min are getting optimized away by gcc so i could not get hold of itupdate i tested the changes suggested by nils ephemient however there is no perceptible performance boost i get by using the assembly versions of min however i get a 125 boost by compiling the program with marchi686 which i guess is because the whole program is getting the benefits of the new faster instructions that gcc is generating with this option thanks for your help guysps i used the ruby profiler to measure performance my c program is a shared library loaded by a ruby program so i could get time spent only for the toplevel c function called by the ruby program which ends up calling min down the stack please see this question,['c'] +41571,jquery continuous animation on mouseover i am trying to have an animation run only when the mouse is over an object i can get one iteration of the animation and then have it set back to normal on mouse out but i would like the animation to loop on mouseover how would i do it using setinterval i am a little stuck,"['javascript', 'jquery']" +41583,is foo f new foo good c code reading through an old c journal i had i noticed somethingone of the articles asserted thatfoo f new foowas nearly unacceptable professional c code by and large and an automatic memory management solution was appropriateis this soedit rephrased is direct memory management unacceptable for new c code in general should auto ptror the other management wrappers be used for most new code,['c++'] +41584,rails build association is not working for a has one and belongs to relationship i have two modelsclass subscription activerecordbase belongs to clientendclass client activerecordbase has one subscriptionendbut when i try to create a parent from the child eg subbuild client the foreign key does not get set eg sub subscriptionnew subscription id nil token nil user id nil created at nil updated at nil cancelled nil active nil client id nil subsavefalse client subbuild client client id nil server id nil ip nil created at nil updated at nil clientsavefalse true subclient id nil sub subscription id 4 token nil user id nil created at 201001 060745 updated at 201001 060745 cancelled nil active nil client id nilit does work if i do clientbuild subscription client clientnew client id nil server id nil ip nil created at nil updated at nil clientsavefalse true sub clientbuild subscription subscription id nil token nil user id nil created at nil updated at nil cancelled nil active nil client id 4 subsavefalse true sub subscription id 5 token nil user id nil created at 201001 060932 updated at 201001 060932 cancelled nil active nil client id 4 client client id 4 server id nil ip nil created at 201001 060902 updated at 201001 060902 cive spent 3 hours fiddling and got nowhere fast can anyone explain what i am doing wrong things to check etc,['ruby-on-rails'] +41585,php function to generate v4 uuid so i have been doing some digging around and i have been trying to piece together a function that generates a valid v4 uuid in php this is the closest i have been able to come my knowledge in hex decimal binary phps bitwise operators and the like is nearly non existant this function generates a valid v4 uuid up until one area a v4 uuid should be in the form ofx4xyxwhere y is 8 9 a or b this is where the functions fails as it does not adhere to thati was hoping someone with more knowledge than me in this area could lend me a hand and help me fix this function so it does adhere to that rulethe function is as followsphpfunction gen uuid uuid array time low 0 time mid 0 time hi 0 clock seq hi 0 clock seq low 0 node array uuidtime low mt rand0 0xf mt rand0 0xf 16 uuidtime mid mt rand0 0xf uuidtime hi 4 12 mt rand0 0x10 uuidclock seq hi 1 7 mt rand0 128 uuidclock seq low mt rand0 255 for i 0 i 6 i uuidnodei mt rand0 255 uuid sprintf08x04x04x02x02x02x02x02x02x02x02x uuidtime low uuidtime mid uuidtime hi uuidclock seq hi uuidclock seq low uuidnode0 uuidnode1 uuidnode2 uuidnode3 uuidnode4 uuidnode5 return uuidthanks to anyone that can help me out,['php'] +41592,dreamweaver extension to beautify phpjavascriptjquery code i am looking so long for a dreamweaver extension to auto beautify php javascript jquery code currently dreamweaver can beautify only html and css apply source formattingany kind of help will be much appreciated,"['php', 'javascript']" +41593,finding the number of days between two dates how to find number of days between two dates using php,['php'] +41604,loop through all the resources in a resx file is there a way to loop through all the resources in a resx file in c,"['c#', '.net']" +41614,android listview first visible position how can i change the first visible item in a list view i searched a method such as setfirstvisibleposition,['android'] +41628,avoid repeated imports in java inherit imports is there a way to inherit importsexamplecommon enumpublic enum constant one two three base class using this enumpublic class base protected void registerconstant c string t sub class needing an import to use the enum constants convenient without enum nameimport static constant want to avoid this line public sub extends base public sub registertwo blabla without import constanttwo and another class with same import import static constant want to avoid this linepublic anothersub extends base i could use classic static final constants but maybe there is a way to use a common enum with the same convenience,['java'] +41643,how to raise warning if return value is thisregarded gcc or static code check i would like to see all the places in my code c which thisregard return value of a function how can i do it with gcc or static code analysis toolbad code exampleint fint z return z z2 z3 zz 23int main int i 7 fi here i thisregard the return value return 1updateit should work even if the function and its use are in different filesfree static check tool,"['c++', 'c']" +41652,enabling get in codeigniter i have been trying to figure out how to enable get in ciit appears the framework deliberately destroys the get array and that enabling it requires serious tinkering with the core classes can anyone say why this is and how to overcome itmind you i am looking to keep uri parsing and routing the way they are just simply have the get available as well,['php'] +41681,change style of android mediacontroller is there a way to customize the mediacontroller i need to change the style of buttons seekbar etc,['android'] +41700,default array values is there a way to assign a default values to arrays in javascriptex an array with 24 slots that defaults to 0,['javascript'] +41709,xstream collapsing xml hierarchy as i parse i have an xml document generated by adobe xfa forms that contains data like the followingposition positionborder title startdate enddate positionborderpositionsince this file is defined elsewhere i am not at liberty to change the format of the xml that i getin my java code i create a position class that contains the title start and end datesmy problem is when i use xstream to parse the file it wants a positionborder class to hold the title and dates i want to basically ignore the border and place all of the fields into the position classwhat i would really like to do is use something like the convertanother method to convert the child of the position element i tried to do just that and it fails because my positionconverter gets called for the positionborder when i call convertanotheranyone have any clues how to deal with collapsing the structure of an xml when parsing,['java'] +41715,crossbrowser support of pagebreakinside avoid i have a lot of divs on a page with variable amounts of content in them i am trying to use pagebreakinside avoid so that each div section is not broken over 2 pages it is working in firefox but not ie8i have this in my css print filepagebreakinsideavoid pagebreakinside avoid and my divs carry the class like in div classpagebreakinsideavoidie8 is supposed to support this now is not itam i doing something wrong anyone solved this issue or had any experience with itany help would be greatthanks a lotrichard,['css'] +41717,php session id changes between pages i have a problem where i am losing the php session between 2 pagesthe session start is included in a file called sessionincphp into every page requiring a session to be set this works for all pages on the site except one particular page memberprofilephp when this page is visited a new session with a different id same session name is set and used instead a few more detailssession name is set manuallyall pages are on the same server under the same domain nameif i put an additional session start above the includesessionincphp in the memberprofilephp file the session is carried over correctlyi have tried setting the session cookie domain and sessionsession name in the htaccess this worked for this domain but it stopped the session being passed over to out payment domain we are running apache 226 with php 525putting the session start above the includesessionincphp in the memberprofilephp file is the quick and dirty fix for this problem but i am wondering if anybody know why this would be happeningcheerswill,['php'] +41734,what is enough sanitization for a url the url would besaved to a mysql databaseused to thisplay a picture on the users profilewould strip tags and mysql real escape string be enough,"['php', 'mysql']" +41739,how to create an expression or is it a bug during my work with expression trees for a few days now i came across something that i find difficult to understand hopefully someone will be able so shed some light hereif you code expressionfuncdynamic dynamic expr1 x 2 x the compiler will complain and you would not get anywhere however it seems that if you create one such expression through a method then the compiler seems to be happy about it and the resulting app works this does not make sense so i am wondering what goes on behind the curtainsi suppose that under the hood the expression returned by convertexpression is perhaps of type expressionfuncobject object which is a valid type but it puzzles me that i cannot use expressionfuncdynamic dynamic type in a declaration and yet i can use it as the return type of a method see an example belowthanks a lotpublic class expressionexample public void main does not compile expressionfuncdynamic dynamic expr1 x 2 x compiles and works ok expressionfuncdouble double expr2 x 2 x funcdouble double func2 funcdouble doubleexpr2compile consolewritelinefunc250tostring outputs 10 compiles and works this is the confusing block expressionfuncdynamic dynamic expr3 convertexpressionexpr2 funcdynamic dynamic func3 funcdynamic dynamicexpr3compile consolewritelinefunc350tostring outputs 10 side note compiles and works expressionfuncobject object expr4 x doubleparse2tostring doubleparsextostring funcobject object func4 funcobject objectexpr4compile consolewritelinefunc450tostring outputs 10 private expressionfuncdynamic dynamic convertexpressiontinput toutputexpressionfunctinput toutput expression expressionfuncobject tinput converttoinput value tinputvalue the following does not compile var input expressionparametertypeofdynamic input var input expressionparametertypeofobject input expressionfunctoutput dynamic converttooutput value dynamicvalue var body expressioninvokeconverttooutput expressioninvokeexpression expressioninvokeconverttoinput input var lambda expressionlambdafuncdynamic dynamicbody input return lambda,['c#'] +41740,whats the opposite of a nbsp a nbsp character is a space which does not allow for line breakingplorem ipsum herenbsparenbspsomenbspwords and so onp lorem ipsum here are some words and so on whats the opposite of that that is a character which is not rendered as a space but can be used for line breakingpfoo supercalifragilisticexpialidocious barp put char here and here foo supercalifragi listicexpiali docious bar or with wider sizefoo supercalifragilisticexpiali docious bar i am aware of the softhyphen character but for my purposes i specifically do not want a hyphen added at the break,['html'] +41746,change webservice endpoint address at run time i used netbeans to generate web sevice client code from wsdl urlbut i cannot change endpoint address at run time using codeplease help me to solve that problem,['java'] +41754,how to create function inside another function in cis it possible is it possible to create a function inside another function in c if so how can this be done,['c#'] +41785,hosting clr in delphi withwithout jcl example can somebody please post here an example how to host clr in delphi i have read similar question here but i cannot use jcl as i want to host it in delphi 5 thank youedit this article about hosting clr in fox pro looks promising but i do not know how to access clrhostdll from delphiedit 2 i give up on delphi 5 requirement now i am trying jcl with delphi 7 but again i am unable to find any example here is what i have till nowmy c assemplynamespace delphinet public class netadder public int add3int left return left 3 i have compiled it to delphinetdllnow i want to use this assemply from delphiuses jcldotnet mscorlib tlbprocedure tform1button1clicksender tobjectvar clr tjclclrhost ads tjclclrappdomainsetup ad tjclclrappdomain ass tjclclrassembly obj objecthandle ov olevariantbegin clr tjclclrhostcreate clrstart ads clrcreatedomainsetup adsapplicationbase cdelhinet adsconfigurationfile cdelhinetmyconfig ad clrcreateappdomainmynet ads obj ad as appdomaincreateinstancefromdelphinetdll delphinetnetadder ov objunwrap button1caption done stringovadd35endthis ends with error eoleerror variant does not reference an automation objecti have not worked with delphi for a long time so i am stuck heresolution there was problem in com visibility which is not by default this is the correct net assemblynamespace delphinet comvisibletrue public class netadder public int add3int left return left 3 important notewhen working with net from delphi it is important calling set8087cw133f at the begining of your program ie before applicationinitialize delphi has enabled floating point exceptions by default see this and the clr doesnat like them when i had them enabled my program weirdly freezed,"['c#', '.net']" +41790,get all attributes from a html element with javascriptjquery i want to put all attributes in a html element into an arraylike i have a jquery object whichs html looks like thisspan nametest messagetest2spannow one way is to use the xml parser described here but then i need to know how to get the html code of my objectthe other way is to make it with jquery but howthe number of attributes and the names are genericthanksbtw i cannot access the element with documentgetelementbyid or something similar,"['javascript', 'jquery']" +41806,c variable scoping iftrue string var varstring var new varthis will result inerror 1 a local variable named var cannot be declared in this scope because it would give a different meaning to var which is already used in a child scope to denote something elsenothing earth shattering really but is not this just plain wrong a fellow developer and i were wondering if the first declaration should be in a different scope thus the second declaration cannot interfere with the first declaration why is c unable to differentiate between the two scopes should the first if scope not be completely separate from the rest of the methodi cannot call var from outside the if so the error message is wrong because the first var has no relevance in the second scope,['c#'] +41812,how many times will strlen be called in this for loop will the strlen function below get called just once with the value stored for further comparisons or is it going to be called every time the comparison is performedfor i 0 i strlenword i do stuff,['c'] +41820,how to select options in multiple select list with jquery i have two dropdowns when a user selects a value from the first one i want in the secondwhich has the multiple select option with jquery to select some values automatically how can i do thatfirst select boxselect idupdate carte s nameupdate carte s option value5896449ghid complet internetoption option value66762495pc pas cu pasoption option value71032795jocul ingeruluioption option value812839ghidul vinuriloroptionselectsecond select boxselect iduc autori s nameuc autorilist size5 multiple option value3rose tremainoption option value4jonathan coeoption option value5cecilia ahernoption option value6marinel serbanoption option value7emanuela cherchezoption option value8peter buckleyoption option value9clark duncanoption option value10carlosruiz zafonoption option value11catalin paduraruoption option value12dansilviu boerescuoptionselectthe bolded values from the first select box splitted by are the values that i want to select from the second select box for example 12 would mean in the second box options with values 11 and 12 to be selectedcurrently i have something like thisbookauthors bookdetailsarray1spliteachbookauthors function intindex objvalue uc autori svalobjvalueattrselectedselectedbut the problem is that only the last value is selected in my case 12selection of 11 is lost,['jquery'] +41822,shared folder permission i use this code to share folder public sub share dim managementclass as new managementclasswin32 share dim inparams as managementbaseobject managementclassgetmethodparameterscreate inparamsdescription my description inparamsname share name inparamspath dfolder inparamstype h0 dim outparams as managementbaseobject managementclassinvokemethodcreate inparams nothing if converttouint32outparamspropertiesreturnvaluevalue 0 then messageboxshowunable to share directory messageboxshowshared folder successfully end subnow what i want is to define user that can access to this folder through networkhow i can do that thanks,['.net'] +41827,how to run something every t seconds in c in c i want a block of statements to be executed repeatedly every t seconds how do i do this,['c'] +41829,confusion about windowonload in javascript i have one paragraph of javascript code and i do not understand it very well can you expain it line by line for me thanks a lot function addloadeventfunc var oldonload windowonload if typeof windowonload function windowonload func else windowonload function oldonload func and here is what i am thinking function addloadeventfunc define a function with a parameter func var oldonload windowonload assign windowonload event to variable oldonload if typeof windowonload function if windowonload is not a function then windowonload func assign func to windowonload event what does func mean else if windowonlad is a function windowonload function do not understand oldonload call function oldonload func call function func confusions windowonload is already an event and why do we use typeoffunction addloadeventfunc windowonload func func whats the difference among these funcs i am sorry for posting a novice problem but thanks to anyone who gives me some guidanceeditthis is improved original code by simon willison function addloadeventfunc var oldonload windowonload if typeof windowonload function windowonload func else windowonload function if oldonload oldonload func,['javascript'] +41843,php call equivalent for java is there a java equivalent for the call of phpit would make sense to me if that is not the case because it would probably result in compiler errorsfrom the php manual on magic methods call is triggered when invoking inaccessible methods in an object context,"['java', 'php']" +41844,what collection to use instead of 2d array in java i want to use a collection in place of 2d array so that i do not need to give its size at the time of declaration and i can add as many elements as i want dynamically,['java'] +41864,how to set a uitableviewcell unclickable on the iphone sdk hi i am trying to have my uitableviewcell rendered inactive so that a user cannot click but merely say the data in the cell i attempt to do so withuitableviewcell cell nilif indexpathrow factscount static nsstring factscellidentifier factscellcell tableview dequeuereusablecellwithidentifierfactscellidentifiercell setselectionstyleuitableviewcellselectionstylenonehowever the cell can still be clicked and highlightedthanks for your help,['iphone'] +41870,what does usingobject obj new object mean what does this statement means in c using object obj new object random stuff,"['c#', '.net']" +41884,manually raising throwing an exception in python how can i raise an exception in python so that it can later be caught via an except block,['python'] +41897,moving up multiple parents in jquery more efficient way so i have a navigation that is a list and has sublists and sublistsbasically the nav is by default collapsed but if people click on a page that is in a sublist i want to show the parent list and if it is a sublist of a sublist i need both parent lists to show i have it set up but i do not like putting 5 parentparent s to traverse upward to expand the list is there a more efficient waythe htmldiv idlessonsidebar ul lia hrefindexhtmlwelcome to beat basics and beyondali lia hreftableofcontentshtmlwhats in this courseali lia hrefdefiningyourbeathtml classactivedefining your beata ul lia hrefboundariesofyourbeathtmlboundaries of your beatali lia hrefthebeatdescriptionhtmlthe beat descriptionali lia hrefbuildyourownbeatdescriptionhtmlspan classitalactivityspan build your own beat descriptionali ul li lia hrefgettingstartedhtmlgetting starteda ul lia hrefdebriefyourpredecessorhtmldebrief your predecessorali lia hrefpredecessortopfivetipshtmlspan classitalactivityspan list the top five tips from your predecessorali lia hrefcoveringyourbeatwiththeinternethtmlcovering your beat with the internetali lia hrefgetinthecarandgohtmlget in the car and goali lia hrefmappingyourbeathtmlmapping your beatali lia hrefreadtheclipshtmlread the clipsali lia hrefactivitythissectthiscliphtmlspan classitalactivityspan thissect this clipali lia hrefwritingyourfirstarticlehtmlwriting your first articleali lia hrefstartingcoldonthebeathtmlstarting cold on the beatali ul li lia hrefworkingwithsourceshtmlworking with sourcesa ul lia hreffindingsourceshtmlfinding sourcesali lia hrefdiversifyyoursourceshtmldiversify your sourcesali lia hrefprospectingforstoriesandsourceshtmlprospecting for stories and sourcesali lia hrefbuildingrelationshipshtmlbuilding relationshipsali lia hrefgoingofftherecordhtmlgoing off the recordali ul li lia hrefdevelopingresourceshtmldeveloping resources to help you on the beata ul lia hrefdevelopacalendarofeventshtmldevelop a calendar of eventsali lia hrefbuildyourlibraryhtmlbuild your libraryali lia hreflearntheopenrecordlawshtmllearn the open record lawsali ul li lia hrefextraresourceshtmlextra resourcesa ul lia hrefbeatbreakdowntoolhtmlbeat breakdown toolali lia hreflinkslibraryhtmllinks librarya ul lia hrefgeneralresourcesforanybeathtmlgeneral resources for any beatali lia hrefcourtsandcriminaljusticelinkshtmlcourts and criminal justice linksali lia hrefeducationresourceshtmleducation resourcesali lia hreflocalgovernmentlinkshtmllocal government linksali lia hrefneighborhoodorsuburbanlinkshtmlneighborhood or suburban linksali lia hrefpoliceandpublicsafetylinkshtmlpolice and public safety linksali lia hrefreporterorganizationshtmlreporter organizationsali ul li lia hrefadditionalreadinghtmladditional readingali ul li lia hreffinalthoughtshtmlfinal thoughtsali ulthe jqueryfunction togglesubmenu if thishasclasubmenuhidden thisparentchildrenulslidetoggle thisremoveclassaddclasubmenuvisible else if thishasclasubmenuvisible thisparentchildrenulslidetoggle thisremoveclassaddclasubmenuhidden lessonsidebar ul ulhidelessonsidebar ul ul ulhidelessonsidebar ulfirstchildattrid rootlistlessonsidebar ul lihasulprependspan clasubmenuhiddenspancssliststylenonelessonsidebar ul li aeach function if thishasclassactive if it is a ul var length thisparentfindullength alertlength if length 0 if thisparentparentparentchildrenspanhasclasubmenuhidden thisparentparentparentchildrenulshow thisparentparentparentchildrenspanremoveclasubmenuhiddenaddclasubmenuvisible if thisparentparentparentparentparentchildrenspanhasclasubmenuhidden thisparentparentparentparentparentchildrenulshow thisparentparentparentparentparentchildrenspanremoveclasubmenuhiddenaddclasubmenuvisible if length 1 thisparentfindulslidetoggle thisparentchildrenspanremoveclasubmenuhiddenaddclasubmenuvisible ulrootlist li span ulrootlist li ul li spanbindclick togglesubmenuany and all help is majorly appreciated,['jquery'] +41903,which android sdk version to release to market i want to release an app on the market it uses nothing new from the 20 release like bluetooth for instance and it works well in every emulator using version 16 to 21my question is upon version of the sdk should i thistribute my application to make it compatible with all devices running 16 20 or 21i only have a physical device running 16 to test it but as i say it uses nothing fancy and works well on emulators using api levels 4 5 6 or 7thanks,['android'] +41915,php how to remove all specific characters at the end of a string how to remove the last character only if it is a periodstring something hereoutput something here,['php'] +41924,what is advanced sql looking at a job descriptions where advanced sql is a requirement i can write basic queries as well as anyone and have worked with mysql databases in a professional setting but what would i be getting into with these jobs if i were to be hired what are examples of advanced sql and where am i along the scale of sql noob to sql master,['sql'] +41931,it is recommendable to type the colors name instead of its hex value in css i always forget what colors i am dealing with in css when i see it hex value i would like to use the name instead eg color lightgreen is it supported by all browsers or only the basic 16 colors,['css'] +41932,how to get dpi of image in c hihow can i get dpi of an image using aspnet c,['c#'] +41937,can a c class determine whether it is on the stack or heap i have class foo is there a way for foo to be able to separate outfunction blah foo foo on the stackandfunction blah foo foo new foo on the heapi want foo to be able to do different things depending on whether it is allocated on the stack or the heapeditalof of people have asked me why do thisthe answeri am using a refcounted gc right now however i want to have ability to run mark sweep too for this i need to tag a set of root pointers these are the pointers on the stack thus for each class i would like to know whether they are in the stack or in the heap,['c++'] +41938,c listview embedding controls can anybody help me with embedding controls in the listview i need to add button controls as subitem of listview thanks,['c#'] +41942,advantage of using views in mysql i have learned that views can be used to create custom table views so to say that aggregate related data from multiple tablesmy question is what are the advantages of views specifically let us say i have two tablesevent eid typeid nameeventtype typeid max team membersnow i create a vieweventdetails eventeid eventname eventtypemax team members where eventtypeideventtypetypeidnow if i want to maximum number of members allowed in a team for some event i coulduse the viewdo a join query or maybe a stored procedurewhat would be my advantagesthisadvantages in each methodanother query if data in table events and eventtypes gets updated is there any overhead involved in updating the data in the view considering it caches resultant data,['mysql'] +41951,is a varchar 2 more efficient than a varchar 255 i am using django and setting my charfieldmax length255 even though i only intend to use about 5 characters is this less efficient i have read that it does not really matter with varchar but then read that it will save hard drive space to specify only what you need,['mysql'] +41957,how can i inject a property value into an annotation configured spring mvc 30 controller first i am using spring 30i have a problem when configuring my controller class the controller uses a web service which i want to define the endpoint address using a properties filecontrollerpublic class supportcontroller valueurlwebservice private string wsendpoint in my application context xmlfile i have defined thiscontextpropertyplaceholder locationwebinfproperties i have been reading the documentation trying different approaches like adding prefix systempropertiesbut i keep getting an error message telling me that it does not existfield or property url cannot be found on object of type orgspringframeworkbeansfactoryconfigbeanexpressioncontextok i have figured it outnow in the controllervaluesettingsurlwebservicethen in the context configuration i have this helper beanutilproperties idsettings locationwebinfsupportwebpropertiesutilproperties,['java'] +41965,how do i test which class an object is in objectivec how do i test whether an object is an instance of a particular class in objectivec let us say i want to see if object a is an instance of class b or class c how do i go about doing it,['objective-c'] +41975,format negative amount of usd with a minus sign not brackets java how do i get numberformatgetcurrencyinstance to print negative usd currency values with a minus sign,['java'] +41984,mysql query analyzer free solutions is there a good query analyzer for mysql that is either free or has a trial that can analyse a query and make suggestions for indexes like the thisplay estimated execution plan in microsoft sql server management studio,['mysql'] +41985,patterns for handling a sql deadlock in c i am writing an application in c which accesses a sql server 2005 database the application is quite database intensive and even if i try to optimize all access set up proper indexes and so on i expect that i will get deadlocks sooner or later i know why database deadlocks occur but i doubt i will be able to release the software without deadlocks occuring at some time the application is using entity framework for database accessare there any good pattern for handling sqlexceptions deadlocked in the c client code for example to rerun the statement batch after x millisecondsto clarify i am not looking for a method on how to avoid deadlocks in the first place isolation levels indexes order of statements etc but rather how to handle them when they actually occur,['c#'] +41996,ruby on rails reference the same model twice is it possible to set up a double relationship in activerecord models via the generate scaffold commandfor example if i had a user model and a privatemessage model the pm table would need to keep track of both the sender and recipientobviously for a single relationship i would just do thisruby scriptgenerate scaffold pm titlestring contentstring userreferencesis there a similar way to set up two relationsalso is there anyway to set up aliases for the relationsso rather than sayingmessageuseryou can use something likemessagesender or messagerecipientany advice would be greatly appreciatedthanks,['ruby-on-rails'] +41999,determine input encoding i am getting console input from the user and want to encode it to utf8 my understanding is c does not have a standard encoding for input streams and that it instead depends on the compiler the runtime environment localization and what nothow can i determine the input encoding,['c++'] +42004,stl map with custom compare function object i want to use the stls map container to lookup a pointer by using binary data as a key so i wrote this custom function objectstruct my cmp bool operator unsigned char const a unsigned char const b return memcmpab40 true false and using it like thismapunsigned char void my cmp mymapthis compiles and seems to work but i am not sure what an unsigned char const type is and why it did not work with just unsigned char,['c++'] +42011,how to add nil to nsmutablearray nsarray array nsarray alloc initwithobjectsi i courier acs acs i dhl interattica speedex ups i i i i nilthis is working because it has nil at the endbut i add objects like this addobjectname etcso at the end i have to add nil i do this addobhectnil but when i run the app it still crashes at cellforrowatindexpathhow can i do this work ok i dont have to add nilwhat is the reason that my app crashes then,"['iphone', 'objective-c']" +42014,how to set a threadname in macosx in windows it is possible to set the threadname via this code the threadname is then shown in debuggersin macosx i have seen several hints which indicates that there are threadnames i think the class nsthread also has a nameattribute my goal is that i can set the threadname in my c application and see it in xcodegdbother related questionscan i set the name of a thread in pthreads linux with a very good answeroverview for pthread herehow to name a thread in linux,['c++'] +42019,is it possible to save a dynamic assembly to thisk i recently bought ayendes book building dsls in boo buy it read it it is awesome but i am coming up against an implementation problem and i want to see what the generated code looks like i would normally use reflector to look at the code but in this case the assemblies are dynamic and only in memory is there a way to save dynamic assemblies to thisk so that i can reflect themedit my answer wow it took awhile to come back to this one unfortunately i left an important bit out from the original questionimportant bit i am using ayendes rhinodsl library as he recommends in the book i have access to the boo compiler in my subclass of dslengine which looks like thispublic class jobengine dslengine protected override void customizecompilerboolangcompilerboocompiler compiler boolangcompilercompilerpipeline pipeline string urls pipelineinsert1 new implicitbaseclasscompilersteptypeof jobbase prepare joblanguage log4net quartz to change the least and get what i wanted i needed to add one linepublic class jobengine dslengine protected override void customizecompilerboolangcompilerboocompiler compiler boolangcompilercompilerpipeline pipeline string urls compilerparametersgenerateinmemory false this one pipelineinsert1 new implicitbaseclasscompilersteptypeof jobbase prepare joblanguage log4net quartz this caused the compiler to output the assembly to my localsettingstemp directory and then i could then reflect it it is important to note that making that change caused the rest of the program to break rhinodsl could no longer find the assemblies in memory because i output them to thisk so this is only useful as a debugging tool,['.net'] +42020,why does not jquery ui datepicker work in jquery dialog modal i want to use jquery ui datepicker in one of my text inputs this one is in a dialog modalin fact i can call datepicker in the normal document text inputs and i got my calender normally but i cannot do that in dialog modal text inputs after clinking inside modal text input i got nothing without any javascript errorthis is my code to call datepicker function mytextinputiddatepicker dateformat ddmmyy i tried changing css uidatepicker zindex properties but i still got nothingdo you have tips to fix this problem regardsin my pagehtml i have function opensaisiearmodal window select codeagence new showmodalwindowsaisiearmodal 500 and i use this script var showmodalwindowfunctionid width var newididcopy thisidnewidvar previousnodedocumentgetelementbyidnewidifpreviousnodenull previousnodeparentnoderemovechildpreviousnodevar rootnodedocumentgetelementsbytagnamebody0thisnodedocumentcreateelementdivrootnodeappendchildthisnodethisnodesetattributeid newidthisnodesetattributetitle documentgetelementbyididgetattributetitlethisnodeinnerhtmldocumentgetelementbyididinnerhtmlifwidthnull width400newiddialogautoopen true modal true widthwidth thisclosewindowfunction thisiddialogclosethiscentercontentfunction thisnodestyletextaligncenterthiscenterfunction thisiddialogoption position centerand this is the modal html code in my pagehtmldiv stylethisplaynone div idsaisiearmodal titledate table classtableframe cellspacing0px width100 tr td classtopleft td td classtopcenter td td classtopright td tr tr td classmiddleleft td td classmiddlecenter table tr aligncenter td date td td input idmytextinputid typetext td tr table td td classmiddleright td tr tr td classbottomleft td td classbottomcenter td td classbottomright td tr table div div divdiv,['jquery'] +42023,why not standard android emulators i am new to android but have published iphone and bberry apps i see that i have to create an emulator using the sdk before i can write and test an app why are there no default emulators why not at least a nexus one or htc hero emulator shipped with the productsure its supposed to be flexible but why not make it easy to create hello world and play around with a virtual android phone both blackberry and iphone come with default simulators when you download the sdkthanksgerry,['android'] +42026,is sizing fonts using em still relevant those of you who use em when sizing fonts will know that they can be a headache when dealing with nested elements and having to make the px em calculations to ensure your design interpretation is correct 100 consumes extra timewith these admittedly minor issues in mind and given the recent progress the major browsers have made towards natively dealing with accessibility issues such as page scaling zooming is using em to size fonts still considered worthwhile legacy browser ie6 support excluded,['css'] +42036,why is c null translated as empty in vb6 instead of nothing i have a c application that reference a vb6 dll when i pass null from c into vb6 dll function the null is translated as value empty value in vb6 instead of nothing object for example function in vb6 dll that referenced by c app public sub testfuncbyval ovalue as variant if ovalue is nothing then set ovalue someobject end if main c code private void form1 loadobject sender eventargs e object testobject new object testobject null testfunctestobject when i pass an object not null then it will be passed into the vb6 as object but when null passed into vb6 it becomes value type empty instead of object type nothing any one knows why and is there anyway i can force null as nothing in vb6 when passed from c appthanks a lot,['c#'] +42040,using a variable name used in a child scope i have been wondering why in c using a variable name used previously in a child scope is not allowed like thisif true int i 1int i 2compiling the above code produces an error a local variable named i cannot be declared in this scope because it would give a different meaning to i which is already used in a child scope to denote something elseand yet you cannot use the variable defined in child scope either the code above works just fine in java and i can see no reason why it does not in c too i am sure there is a good reason but what is it,['c#'] +42054,output text file with line breaks in php i am trying to open a text file and output its contents with the code below the text file includes line breaks but when i echo the file its unformatted how do i fix thisthankshtmlheadheadbody fh fopenfilenametxt r pagetext freadfh 250 echo pagetextbodyhtml,"['php', 'html']" +42063,what is the best way to wait for a variable in a multithreaded application i would like to do something like the below for a multithreaded program wait for variable to become true but do not hog resources then resync queues is something like this a good solutionwhile ready threadsleep250 pause for 14 second,"['c++', 'c']" +42086,restore android app stack from background lets say i launch my app from the home screen navigate through some activities then i press the home key and do something else in the gmail app after i am done checking my maili press the home key again to leave the gmail app and click my apps icon at the home screen again to return to itwhen i return to my app i want it to return to the last activity i was at not start a whole new session i have been trying to figure this out all daymy manifest for my first activity is as follows activity androidnamemain androidlabelstringapp name androidscreenorientationportrait androidalwaysretaintaskstatetrue intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activitythe category attribute launcher makes my app always start at activity main so i do not know how to go about restoring the last activity people have told me to use sharedpreferences to save the last activity and load it on launch but i do not think it is intended to be done that way because it is not very elegant,"['java', 'android']" +42089,phpdoc return void necessary is it really necessary do something like this return void i have quite a few methods that do not have a return value and it seems really redundant to put something like this in the comment would it be considered bad form to leave it out,['php'] +42103,how can i tell if i am running in 64bit jvm or 32bit jvm from within a program how can i tell if the jvm my application runs in is 32 bit or 64bit specifically what function or preference do i access to detect this within the program,['java'] +42112,java cpu usage monitoring is there a way in monitoring cpu usage using pure java,['java'] +42133,how to schedule a background task there seems to be a couple of ways to go about having a background task being executed my usecase is to have my app fetch a datafeed every x minutes regardless of my gui is running and regardless of whether the phone is sleeping or noti use an alarmmanager to schedule an intent matching a broadcastreceiver in the onrecieve method i start a service startservice which spawns an asynctask the task fetches data and stores it and then stopself the servicein the onrecieve method i aquire a partial wake lock before starting the service and just before calling stopself in the service i release it againis this really the best way to do it do i even need the service in this scenarioi experience odd behaviour with this setup where the setup works for hours and then suddenly stops which makes it very hard to debugdoes anyone have a simple foolproof method to achive the same end,['android'] +42134,the 3 different equals what is the difference between and i think using one equal sign is to declare a variable while two equal signs is for a comparison condition and lastly three equal signs is for comparing values of declared variables,"['javascript', 'php']" +42152,android application global onpause and onresume is there something like an application global onpause and onresumemy main activity listens for gps fixes which i want to continue working when switching to another screenactivity therefor i cannot unregister my locationlistener in the activitys onpause however i still want to unregister my gps listener when switching to another application so save battery and turning it back on when returning to my application regardless what screenactivity the user is currently inany ideas,['android'] +42161,what are the current differences between jquery and prototype i have been building a ruby on rails site in recent months and i have only used a small amount of built in javascript functions however i will be doing much more javascript development in the coming weeks and months and i am debating on which javascript framework to go withon the one hand jquery seems to be the more popular one but then again prototype is already built into rails i have also read a bunch of articles online from a few years ago talking about how jquery is more concise at some things but sloppy on others and giving various other opinionsso my questions are to the people who have used both preferably recently what is the difference in using either prototype and jquery from a pure javascript and from a ruby on rails perspective is there a significant difference between them or are they now pretty close to each other in terms of functionality and code writinghow high is the switching cost in terms of things that have to be relearnt and code that has to be rewrittenthanks,"['javascript', 'jquery', 'ruby-on-rails']" +42168,c why bool is 8 bits long in c i am wondering why the bool type is 8 bits long on my system where only one bit is enough to hold the boolean value i used to believe it was for performance reasons but then on a 32 bits or 64 bits machine where registers are 32 or 64 bits wide whats the performance advantage or is it just one of these historical reasons,['c++'] +42176,how to refresh an iframe using javascript i have a webpage with an iframe and a button once the button is pressed i need the iframe to be refreshed is this possible if so how i searched and could not find any answers,['javascript'] +42190,fixed android detecting focuspressed color i am trying to detect the focuspressed color for button and other elementsthis is needed because i am developing new components and it is important that those look as part of platformthose colors are orange on android sdk and green on htc senseuiif i could detect that color my component will look as part of platform on both versiondoes anyone knows how to do thisit is possible to create selector which uses custom image for default state and platform default for focusselectionto do this follow the steps1 create xml file with selector in resdrawable eg red buttonxmlxml version10 encodingutf8selector xmlnsandroid item androidstate pressedtrue androiddrawableandroiddrawablebtn default item item androidstate focusedtrue androiddrawableandroiddrawablebtn default item item androiddrawabledrawablebtn default red itemselector2 from folder androidsdkmacplatformsandroid15dataresdrawable take picture btn default pressed9png and change color as you like i needed to change it to red and for this gimp is enough3 place altered picture in resdrawable eg with name btn default red9png4 define buttonbutton androidididinfo button androidlayout widthwrap content androidlayout height37dip androidlayout margintop1dip androidbackgrounddrawablered button androidtextinfo that is allthis is result,['android'] +42191,replacing css with javascript i am relatively new to clientside programming coming from the phpmysql environment i understand the roles both css and javascript can play in the browser environment however it appears css is irreversibly stagnant without javascript i by no means want to create a debate but this is what the situation looks like to me the novice so why not just use only javascript to set element attributesproperties and if so is this a common practice i am sure css is much faster,"['javascript', 'css']" +42195,event handlers in xaml or code behind i am new to silverlight and xaml while trying to learn the syntax and best practices i continue to come across a thiscrepancy or at least to me it seems that way in the way some implement event handlersin an example from msdn i see the following code usedusercontrol xclassdraganddropsimplepage xmlns xmlnsx width400 height300 canvas xnamerootcanvas width640 height480 backgroundgray you can drag this rectangle around the canvas rectangle mouseleftbuttondownhandle mousedown mousemovehandle mousemove mouseleftbuttonuphandle mouseup canvasleft30 canvastop30 fillred width50 height50 canvasusercontrolwhere the mouse handlers are set however in other code i have seen this method used in the code behind public window1 initializecomponent transformgroup group new transformgroup scaletransform xform new scaletransform groupchildrenaddxform translatetransform tt new translatetransform groupchildrenaddtt imagerendertransform group imagemousewheel image mousewheel imagemouseleftbuttondown image mouseleftbuttondown imagemouseleftbuttonup image mouseleftbuttonup imagemousemove image mousemove i would assume the example on msdn is the recommended way however i tend to like the second method is there a best practice for this situation,['c#'] +42201,confusion about virtualnewoverride i am a bit confused about the virtualnewoverride thing heres an exampleclass a public virtual void mvvirtual consolewritelineamvvirtual class b a public virtual void mvvirtual consolewritelinebmvvirtual class c b public override void mvvirtual consolewritelinecmvvirtual class test static void main b b1 new c b1mvvirtual cmvvirtual i understand this a a2 new c a2mvvirtual amvvirtual i do not get why in the second call we get amvvirtual i usually treat these issues with this algorithmcheck the type of the variable holding the reference for the object for an instance method called mvvirtual does not have onebut does have a virtual method with that signature and namevirtual method let us then check the type of the object being held by a2 c for an overriding of that method it has one executes cmvvirtualwhere is my algorithm wrong i really am confused by this and would greatly appreciate some help,['c#'] +42211,plotting waveform of the wav file i wanted to plot the waveform of the wav file for the specific plotting widthwhich method should i use to thisplay correct waveform plot any suggestions tutorial links are welcomed,"['c++', 'c']" +42213,the specified module could not be found 0x8007007e inside the constructor of a form when i am stepping through my code a method declared in the very same form is called before i can step inside the method i get a systemiofilenotfoundexception with message the specified module could not be found exception from hresult 0x8007007e the member method i try to enter is declared unsafe because it deals with unmanaged c code but like i said i can never step into the method anywayssince it sounds like a dll dependency issue i ran dependency walker dependency walker only shows problems with mprdll under shlwapidll the problem method is wnetrestoreconnectiona which i never call the dependency walker faq suggests that this is not a problem also this is not a web application or anything i am unfortunately stuck with vs2005what are some possible reasons for this problem to occur any ideas on what i could be missing or how i could debug this problem,"['c#', '.net', 'c++']" +42219,in cocoa how do you hide a window when the application launches specifically i want to create a new nswindow in ib in mainmenuxib but i do not want that to be open when the application launches i tried doing close and orderout in both the init and awakefromnib methods of my nswindowcontroller class but it flickers for a second before closing,['objective-c'] +42224,add pagecontrol programmatically i would like to add a uipagecontrol item programmatically to my view controller the selfview property contains a uiscrollview with the following propertiesscrollview uiscrollview alloc initwithframeapplicationframescrollviewbackgroundcolor uicolor blackcolorscrollviewmaximumzoomscale 10scrollviewminimumzoomscale 10scrollviewclipstobounds yesscrollviewshowshorizontalscrollindicator noscrollviewpagingenabled yesselfview scrollviewso far so good now i wanted to add a pagecontrol element by adding this a few lines laterpagecontrolnumberofpages 2pagecontrolcurrentpage 0the pagecontrol element is synthesized using the property and synthesize however this does not thisplay anything even if i add a selfview addsubviewpagecontrolany ideas why this is not working,['iphone'] +42227,does the tcpserver baserequesthandler in pythons socketserver close the socket after each call to handle i am writing a clientserver application in python and i am finding it necessary to get a new connection to the server for each request from the client my server is just inheriting from tcpserver and i am inheriting from baserequesthandler to do my processing i am not calling selfrequestclose anywhere in the handler but somehow the server seems to be hanging up on my client whats up,['python'] +42261,c cast entire array i see this arrayconvertall method but it requires a converter as an argument i do not see why i need a converter when i have already defined an implicit one in my class public static implicit operator vec2pointf p return new vec2px py i am trying to cast an array of pointfs to an array of vec2s is there a nice way to do this or should i just suck it up and write another converter or loop over the elements,['c#'] +42273,how to create a string class replica i need to create a class with exactly the same methods as javalangstringwhat is the best way to do this in java i know that i cannot extend string class as it is final i am not looking at solutions where i need to copy the source code of javalangstring for example assume that i need the functionality length within my custom class named mystring which has a corresponding mylength methodwhat is the best way to implement mylengthi am not looking at various algorithms to find out the length of a string but to reuse strings length method now once i have mystring class ready i should be able to use it anywhere for my custom manipulations,['java'] +42280,is there any functional difference between c sealed and javas final keyword possible duplicatewhat is the equivalent of javaas final in c in java final applies to more than just a claso i wonder is there any functional difference between the two keywordsthank you and sorry for a relatively noob questiona quick google search did not satisfy my needs,"['c#', 'java']" +42289,how to get a bus error i am trying very hard to get a bus errorone way is misaligned access and i have tried the examples given here and here but no error for me the programs execute just fineis there some situation which is sure to produce a bus error,['c++'] +42298,how to assign text size in sp value using java code if i assign an integer value to change a certain text size of a textview using java code the value is interpreted as pixel px now does anyone know how to assign it in sp,['android'] +42305,how to output my ruby commandline text in different colours how can i make the puts commands i output from a commandline based ruby program colouri would appreciated any references to how i call each different colour alsolets say we start with thisputs the following word is blue im blueputs the following word is green im greenputs the following word is red im redand i get different text i want in different colours i want you get the ideaim using ubuntu would i need to change my approach so that the program outputs correctly in diff os,['ruby'] +42319,drag drop using sendmessage this sounds funnyjust a little experimenti wanted to simulate a drag drop of a file on a applicationwindow using send messageis it possiblei dont have code for the application but on the executablethe application is ip messengerwhat i wanted to do is use send to functionality to send the file to an exe which willfind ipmessenger window and simulate a drag drop thr code the user will select the file and right click send to to the exe which will do drag drop from codenote ip messenger supports dragdrop operation for filesthxamit,"['c#', 'c++']" +42323,can automapper map a paged list i would like to map a paged list of business objects to a paged list of view model objects using something like thisvar listviewmodel mappingenginemapipagedlistrequestforquote ipagedlistrequestforquoteviewmodelrequestforquotesthe paged list implementation is similar to rob conerys implementation herehow can you setup automapper to do this,['c#'] +42330,is using spring aop for logging a good idea i am reading up on spring at the moment and one of the examples used for a use of aop is logging the start and end of method callsi have also read that using aop can impact performanceis using spring aop a good idea for this type of logging my understanding is that spring uses dynamic aop would it be be better to use static aop like aspectj for this type of aopcurently the coding policy of the company i work for requires a ridiculous amount of logging and i want to reduce the ammount of logging code i have to write and improve the readability of my codeam i barking up the wrong tree,['java'] +42335,c vb6 how to convert with statement to c how can i convert this piece of vb6 code into c i have tried on my own and got so far to edit code i am trying to translate exists here,['c#'] +42356,how can i speed up this method which removes text from a string i wrote the following method to remove the namespace in brackets from stringsi would like to make this as fast as possibleis there a way to speed up the following codeusing systemnamespace testremovefast class program static void mainstring args string tests modifiedat createdat foreach var test in tests consolewritelinecleantest consolereadline static string cleanstring line int pos lineindexof if pos 0 return linesubstringpos 1 linelength pos 1 else return line,['c#'] +42361,read udid from iphone with javascript on mobile safari how can i read udid from iphone with javascript on mobile safari,"['javascript', 'iphone', 'objective-c']" +42392,why autoimport only javalang package i know that the package javalang is autoimported by every java program we write hence all the classes in it are automatically available to usmy question is why not auto import javautil and other packages too that sure will save some typing so please explain why is this not done,['java'] +42402,serializing a nullable in to xml i am trying to serialize a class several of the datamembers are nullable objects here is a examplexmlattributeaccountexpirationdatepublic nullabledatetime accountexpirationdate get return userprincipalaccountexpirationdate set userprincipalaccountexpirationdate value however at runtime i get the errorcannot serialize member accountexpirationdate of type systemnullable1systemdatetime xmlattributexmltext cannot be used to encode complex typeshowever i checked and nullable is a serializableattribute what am i doing wrong,['c#'] +42410,are c autoimplemented static properties threadsafe i would like to know if c automatically implemented properties like public static t prop get set are threadsafe or not thanks,['c#'] +42430,php pecl http vs curl extension i am working on a php client for couchdb while browsing through the phpnet documentation regarding http and curl i came across the pecl http extension at first glance i think i would like to use this pecl extension instead of curl because it is much simpler to use and i am not doing very complicated http work anyways plus i always like trying new things so i wouldnt mind getting my feet wetas far as my question to the stackoverflow communityhas anyone used both the pecl http and curl extensionsdoes the pecl extension have any serious performance issuesis the pecl extension as userfriendly as it appears on the surfaceis the triedandtrue curl library still superioredit as it turns out the pecl http extension uses some of the curl source code under the hood so they are not completely different beasts both are also compiled extensions to php,['php'] +42433,windows 7 theme for wpf is there any way to make a wpf app look like it is running on windows 7 even if it is running on xp i am looking for some kind of theme i can just paste in i am aware of the themes project on codeplex but it lacks support for datagrid which is something i critically need i was thinking maybe the windows 7 theme would just be an easy port or exists in some file somewhere already any information you have even if it is bad news would be much appreciatedupdateusing lars truijens idea i was able to get the windows 7 look for the major controls but unfortunately it did not work for the wpf toolkit datagrid control which i needdatagrid looks like this with aero themedatagrid should look like thisso i am still looking for a solution to this problem if anyone has any ideas maybe someone has built an extension to the aero theme that covers the wpf toolkit controls again any information you have is much appreciatedupdate 2 problem solvedto get the aero theme to work with wpf toolkit controls you just need to add a second aero dictionary so your appxaml should now look like thisapplicationresources resourcedictionary resourcedictionarymergeddictionaries resourcedictionary sourcepresentationframeworkaerocomponentthemesaeronormalcolorxaml resourcedictionary sourcepackapplicationwpftoolkitcomponentthemesaeronormalcolorxaml resourcedictionarymergeddictionaries resourcedictionaryapplicationresourcesalso i would recommend turning the gridlines off in your datagrid controls because they look horribledatagrid gridlinesvisibilitynone,['.net'] +42437,more information on in c i have noticed that sometimes c macros are written as something like thisdefine foobar bar after some experimentation i have found that will compile but do nothing as expectedleaving the off will cause a syntax error a side effect of this is ensuring that foo looks like a function in your code although if you leave the semicolon off the error is not very useful for diagnosing the problemreturn complains about a void value not being ignored just like if i had tried to use a void functionis this just to make developers add a semicolon to their macros or does it have another purpose i have tried google but it fails miserably with punctuation is there a name for this,['c'] +42438,is this a bug in how jquery treats child selectors is there a bug in how jquery handles child selectors or am i missing out on something obvious i cannot get it to work when the child is anything other than heres the jquery selector i am runningmytable treachfunction do somthing and the table structure istable idmytable tr tdbuttonsomebuttonbuttontd tdtextareatextareatd trtableno elements are matched with the above selector mytable tr but the two selectors listed below work finemytable tr search all descendants for tror use a wildcard to match childrenmytable search all child elementsany ideas on what could be wrong herethanks for the rapid answers guys unfortunately can only select one,['jquery'] +42459,how to set text on status bar how to set text on status bar line that placed battery life time etc thanks in advance,['android'] +42484,why does wicket changes the id of the html elements if i write form wicketidform idformor even form wicketidformthen the rendered html shows the id form appended with different numbers whenever the page is refreshed eg form idform7is there a way to thisable this behavior of the wicket framework,['html'] +42492,how to load a c dll in python how can i load a c dll in pythondo i have to put some extra code in the c files like export in c filesi do not want to use ironpython i want to import a module to python,"['c#', 'python', '.net']" +42501,static file with mod wsgi in django i have searched a lot but i still have a problem with the static files css image with my django websitei am using mod wsgi with apache on archlinux 64bitsi have added it in my httpconf loadmodule wsgi module modulesmod wsgisovirtualhost 80 wsgidaemonprocess martlocalhost usermart groupusers processes2 threads25 wsgiprocessgroup martlocalhost loglevel debug alias media homemartprogrammationpythondjangomartfilesmedia directory homemartprogrammationpythondjangomartfiles order allowdeny allow from all directory wsgiscriptalias srvhttpwsgiscriptsdjangowsgivirtualhosti tried to use the djangowsgi in my home folder but it does not work permission denied to access strangely it works if i use the test script given hereall the directories and content apache folder wsgiscript martfiles have the permission 775 rootdevusers with the group devusers including my user http and rootin my template basehtml i call the css this way html head link relstylesheet hrefmediacstylecss and the error in varloghttperrorlog sat jan 16 1321 2010 error client 127001 13permission denied access to mediacstylecss denied referer httplocalhost sat jan 16 1321 2010 info mod wsgi pid14783 attach interpreter etchttpdconfhttpconfsrvhttpwsgiscriptdjangowsgihomemartfilessettingspythank youedit i precise that my django website is working fine except the sessions but i do not think it is related so i am not sure it is related to the djangowsgi file maybe i am wrong but what is sure is that i should be able to use the djangowsgi from outside the apache folderif i change the line alias media homemartprogrammationpythondjangomartfilesmedia with alias media srvhttpmedia and gives the right permissions it works but i do not want and should not to put all my media in the apache folder,['python'] +42502,need approach to show tables using segmented control hi there i using a segmented control on a view with the help of this segmented control i would like to thisplay to different tables on my view suppose i have two segments in my table on tap of segment 1 i would like to thisplay table 1 and on tap of segment 2 i would like to thisplay table 2 my table 1 is a plain table and table 2 is a grouped table apple is using approach to thisplay differnt apps in differnt categories on app store but i am not sure how do i do that please suggest any approach or any code sample for the same will also appriciatedthanks sandy,"['iphone', 'objective-c']" +42505,efficient way to process simple but large files in c i am working on a project that has me a bit over my head performancewise i am tasked with reading large 50mb or so files of particle coordinates and thisplaying them i would like to use c for this because i am learning it already the coordinate structure in the files are simple there is just alot say a million or so 12345667 52341566 coordinate 1 85326123 51526612 coordinate 2 being a noob i just want to read in the files line by line and store them in vectors is this wrong maybe i should be reading in the whole file first buffered and then parsing the valuesworking exampleclock t c1 clockvectordouble coordsdouble coordifstream finfiletxtwhilefin coord coordspush backcoordcout done coordssize2 coords readncout took clock c1doubleclocks per sec seconds endland corresponding output on a 40mb file with 2 million coordinatesdone 20 coords readtook 174 secondswhich is fast in my mind but i am thinking my mind is not a good judge,['c++'] +42515,how can i decode html entities in c how can i decode html entities in cfor example html quotmusicquot amp quotvideoquotdecoded music videothanks,"['c++', 'html']" +42518,android adb access to application databases without root can anyone tell me is it possible to use the adb to pull and push a database from an app without root privaliges on the phonefor example i know the location on my rooted magic and dream isdatadatacomxdatabasesxi know that you can use adb without root but when trying to use the shell you cannot view that location without root privaliges but i have been told you can use push and pull if you know the file you wantbasically i want to pull a database from my app on a non rooted phone modify it and push it back ononly trouble i have is the two phones i have are both root and i do not have access to a non root one to try it out,['android'] +42529,what is the point of the class optiont i am not able to understand the point of optiont class in scala i mean i am not able to see any advanages of none over nullfor example consider the codeobject main class personname string var age int def thisplay printlnname age def getperson1 person returns a person instance or null def getperson2 optionperson returns either someperson or none def mainargv arraystring unit val p getperson1 if pnull pthisplay getperson2 match case someperson personthisplay case none do nothing now suppose the method getperson1 returns null then the call made to thisplay on first line of main is bound to fail with npe similarly if getperson2 returns none the thisplay call will again fail with some similar errorif so then why does scala complicate things by introducing a new value wrapper optiont instead of following a simple approach used in javaupdatei have edited my code as per mitchs suggestion i am still not able to see any particular advantage of optiont i have to test for the exceptional null or none in both cases if i have understood correctly from michaels reply is the only advantage of optiont is that it explicitly tells the programmer that this method could return none is this the only reason behind this design choice,['java'] +42531,removingundefining a class method you can dynamically define a class method for a class like soclass fooendbar qdef bar bar endfooinstance evalbarbut how do you do the opposite removeundefine a class method i suspect modules remove method and undef method methods might be able to be used for this purpose but all of the examples i have seen after googling for hours have been for removingundefining instance methods not class methods or perhaps there is a syntax you can pass to instance eval to do this as wellthanks in advance,['ruby'] +42539,showinghiding navigation bar with smooth animation i have a navigation based app the first view rootcontroller starts with three large buttons only no navigationbar from there everything else is tableviews and have navigation bars i am doing this to showhide the navigation barmyappappdelegate appdelegate uiapplication sharedapplication delegateappdelegatenavigationcontrollernavigationbarhidden noonce i leave the root controller the navigation bar will jerk into place and lay on top of the tableview rather than pushing it down it clips the top part of the tableview going back to the root controller is not smooth in how the navigation bar thisappears is there a smootherbetter way to do accomplish hiding the navigation bar for the root controller only,"['iphone', 'objective-c']" +42544,c smart pointer const correctness i have a few containers in a class for example vector or map which containshared ptrs to objects living on the heapfor exampletemplate typename tclass myexamplepublicprivate vectortr1shared ptrt vec maptr1shared ptrt int hi want to have a public interface of this class that sometimes returns shared ptrsto const objects via shared ptrconst t and sometimes shared ptrt wherei allow the caller to mutate the objects i want logical const correctness so if i marka method as const it cannot change the objects on the heapquestions1 i am confused by the interchangeability of tr1shared ptrconst t and tr1shared ptrtwhen someone passes a shared ptrconst t shared ptr into the class do i store it as a shared ptrt or shared ptrconst t inside the vector and map or do i change the map vector types eg insert elemeentshared ptrconst t obj 2 is it better to instantiate classes as follows myexampleconst int that seemsunduly restrictive because i can never return a shared ptrint,['c++'] +42546,how do i create a static local variable in java i have read java does not support static local variables unlike cc now if i want to code a function with a local variable whose value should persist between function calls how do i do thatshould i resort to using instance variables,['java'] +42555,python web hosting numpy matplotlib scientific computing i write scientific software in numpyscipymatplotlib having developed applications on my home computer i am now interested in writing simple web applications example user uploads image or audio file my program processes it using numpyscipy and output is thisplayed on the browser using matplotlib or perhaps the user can download a processed file i already pay for hosting that does have python 243 installed but no numpyscipy i do not have shell access via command line either just draganddrop ftp pretty limited but i can get simple pythoncgi scripts workingsurprisingly a web search revealed few suitable options for web hosting with these capabilities already built in please guide me if i am wrong i am learning about the google app engine but i still do not have a full understanding about its tools and limitations what the web did tell me is that others have similar concernshoping for solutions i thought i would ask these simple questions to the awesome so communityis there a simple way of installing numpy or any thirdparty packagelibrary onto my already hosted space i know the python path on my hosted space and i know the relevant pythonnumpy directories on my home computer can i simply copy files over and have it work both local and remote systems run ubuntuwhat hosting sites exist either free or paid which have numpymatplotlib installed or if not installed the possibility of installing it are there any documented sites that you can reference with working applications no matter how simple can google app engine help me in any way or is it totally for something else have you or others used it to write scientific applications in pythonnumpy if so could you reference themthank you for your helpedit after the useful answers below i bought the 20 plan at slicehost and i love it so far i first tried amazon ec2 i must be stupid but i just could not get it to work setting up the ubuntu server with apache took mere hours and i am an apache novice it allows me to do exactly what i wanted with python plus much more i now have my own remote repository for version control too thanks againedit 2 nearly two years later i tried linode and ec2 again linode is great ec2 seemed easier this time around maybe it is just added experience or maybe it is the improvements that amazon made to the aws management console for those interested in numpyscipymatplotlibaudiolab here is my ubuntu cheat sheet whenever i launch an ec2 instanceec2 sudo aptitude install buildessential pythonscipy ipython pythonmatplotlib pythondev pythonsetuptools libsndfiledev libasound2dev mysqlserver pythonmysqldb upload scikitsaudiolab0110ec2scikitsaudiolab0110 sudo python setuppy installec2 sudo rm rf scikitsaudiolab0110ec2 nano ipythonipy user confpyipeximport matplotlib matplotlibuseagg import scipy pylab scipysignal as sig scipylinalg as lin scipysparse as spar os sys mysqldb boto from scikits import audiolabimport ipy greedycompleterimport ipy autoreload,['python'] +42562,how expensive are function calls in javascript i have been looking at other peoples javascript code and i have noticed that many programmers tend to create functions that could be combined with the functions that are calling them one example is this the initwebgl function could be combined with the start function and it would function the same another example is in the source of this where function tick which is called every 15 milliseconds makes calls to two other functions that may just as well be combined with tick i understand the organizational qualities of this but i am curious about the effect on performance is doing this good practice especially considering that javascript is an interpreted language,['javascript'] +42567,python multiprocessing and a shared counter i am having troubles with the multiprocessing module i am using a pool of workers with its map method to load data from lots of files and for each of them i analyze data with with a custom function each time a file has been processed i would like to have a counter updated so that i can keep track of how many files remains to be processed here is sample codedef analyze data args do something counter 1 print counterif name main list of files oslistdirsome directory global counter counter 0 p pool pmapanalyze data list of filesi cannot find a solution for this,['python'] +42573,mysqlsql retrieve first 40 characters of a text field how can i retrieve a text field from mysql db table but not the entire text just the few 40 or so characterscan this be done in sql or do i need to do it using phpbasically what i am trying to do is show the first x characters and then let the user click on that to view the full content,"['php', 'sql', 'mysql']" +42576,tips to solve problem 41 of project euler i am trying to solve problem 41of project euler in java by counting the number from 998 to 80which took very long time i got 98765431 as an answer but i am getting that answer not correct could anyone please tell me the reason of not getting the correct answer and how can i speed my program,['java'] +42578,embedded nonrelational nosql data store i am thinking about usingimplementing some kind of an embedded keyvalue or document store for my windows desktop application i want to be able to store various types of data gps tracks would be one example and of course be able to query this data the amount of data would be such that it could not all be loaded into memory at the same timei am thinking about using sqlite as a storage engine for a keyvalue store something like yserial but written in net i have also read about friendfeeds usage of mysql to store schemaless data which is a good pointer on how to use rdbms for nonrelational data sqlite seems to be a good option because of its simplicity portability and library size my question is whether there are any other options for an embedded nonrelational store it does not need to be thistributable and it does not have to support transactions but it does have to be accessible from net and it should have a small download sizeupdate i have found an article titled sqlite as a keyvalue database which compares sqlite with berkeley db which is an embedded keyvalue store library,['.net'] +42588,c getting the text off notifyicons tray icons i am crafting this what you are listening to plugin for learning purposes that thisplays the current spotify or winamp song as a message in an im clientso far it is really simple i am merely getting the song played from the title like soprocessgetprocessesbynamespotifyand then just pick out the song part spotify song title procmainwindowtitlesubstring10however most people do not keep the main window open or minimized to the taskbar but have it visible only as a tray icon i would like to get the text from there the one thisplayed when hovering above itis there any easy way of doing thisthanks,['c#'] +42589,what exactly do u and r string flags do in python and what are raw string literals while asking this question i realized i did not know much about raw strings for somebody claiming to be a django trainer this sucksi know what an encoding is and i know what u alone does since i get what is unicodebut what does r do exactly what kind of string does it result inand above all what the heck does ur dofinally is there any reliable way to go back from a unicode string to a simple raw stringah and by the way if your system and your text editor charset are set to utf8 does u actually do anything,['python'] +42604,communication between c applications the easy way i have two c programs and i want to send some data back and forth between them and check if the data arrived to the other application the two programs will always run on the same computer so no networking capability is required i have already read some questions with similar topics here but i am not entirely sure which is the right method for me wcf remoting etcwhat i want to know is which one is the easier to implement for a beginner in c i do not want it to get too complicated anyway it is only a few integers and some text that i want to sendif there is not a real difference in difficulty what advantages does one have over the otheri would really appreciate some simple example code as wellthanks in advance,['c#'] +42610,is there any way to put extras to intent from preferences hi i am launching activity from preferences screen activity is shared among three preferencesi wonder if i can set extras for this activity in xmlpreference androidkeyaction 1 androidtitlestringaction 1 title intent androidactioncompackagesharedaction intentpreferencei wonder if i can do something likeextras item androidname androidvalueextrasall i need to do to pass an integer really i can different actions and check action instead of extras,['android'] +42616,real time subprocesspopen via stdout and pipe i am trying to grab stdout from a subprocesspopen call and although i am achieving this easily by doingcmd subprocesspopenls l shelltrue stdoutpipefor line in cmdstdoutreadlines print linei would like to grab stdout in real time with the above method pipe is waiting to grab all the stdout and then it returnsso for logging purposes this does not meet my requirements eg see what is going on while it happensis there a way to get line by line stdout while is running or is this a limitation of subprocess having to wait until the pipe closeseditif i switch readlines for readline i only get the last line of the stdout not idealin 75 cmd popenls l shelltrue stdoutpipein 76 for i in cmdstdoutreadline print i total104thanks,['python'] +42620,whats the best way to test this i am going through the edgecase ruby koans in about dice projectrb there is a test called test dice values should change between rolls which is straightforward def test dice values should change between rolls dice dicesetnew diceroll5 first time dicevalues diceroll5 second time dicevalues assert not equal first time second time two rolls should not be equal endexcept for this comment that appears there think about it if the rolls are random then it is possible although not likely that two consecutive rolls are equal what would be a better way to test thiswhich obviously got me thinking what is the best way to reliably test something random like that specifically and generally,['ruby'] +42623,what could cc lose if they defined a standard abi the title says everything i am talking about cc specifically because both consider this as implementation issue i think defining a standard interface can ease building a module system on top of it and many other good thingswhat could cc lose if they defined a standard abi,"['c++', 'c']" +42630,php errors shows orange table and call stack recently if i have php errors on my localhost i am seeing this layout of an orange table and call stackis this caused by something in particular a php module maybe or is it now part of php by default i would like to go back to the simpler plain message i am running php on apache 2 on my ubuntu desktop,['php'] +42631,check if a double is evenly divisible by another double in c how can i check if a double x is evenly divisible by another double y in c with integers i would just use modulo but what would be the correctbest way to do it with doublesi know floating point numbers carry with them imprecision but i am getting the double from standard input maybe i should not scan it as a double straight away but as two integers instead but where would i go from then,['c'] +42634,worms style destructible terrain i want to prototype an idea for a game i have the idea for this game is that the player will dig through the ground creating tunnels and finding treasurei am looking to create worms style terrain with collision detection for the player wandering and jumping around the tunnels examples of this type of dynamic terrain can be seen in these picturesmy question is how is the best way to implement this type of destructible terrain i am using xna game studiothanksjames,['c#'] +42637,java using endpoint to publish webservice to tomcat server i am creating a simple soap web service i am to ensure that it runs on a tomcat web serviceim trying to implement this with jaxws see codemy question is does the endpointpublish use the tomcat server to host this or is it a mini glassfish kind of servershould i be extending unicastremoveobject or something similiar insteadideally it would be able to be packaged into a war and dropped in the directory and just workit does not seem to work with my installed tomcat server as is because it says the port is already in use i am using ubuntu karmic with the tomcat6 package installed it could also be my user doesnt have permissions to publish to the running tomcat on 8080i hope this question is clear enoughsample codewebservicepublic class userattributes public static void mainstring args userattributes instance new userattributes endpointpublishhttplocalhost8082webservicesuserattributes instance public string hello return hello world,['java'] +42640,flushtozero behavior in floatingpoint arithmetic while as far as i remember ie 754 says nothing about a flushtozero mode to handle denormalized numbers faster some architectures offer this mode eg libhtml in the particular case of this technical documentation standard handling of denormalized numbers is the default and flushtozero has to be activated explicitly in the default mode denormalized numbers are also handled in software which is sloweri work on a static analyzer for embedded c which tries to predict correct if sometimes imprecise ranges for the values that can happen at runtime it aims at being correct because it is intended to be usable to exclude the possibility of something going wrong at runtime for instance for critical embedded code this requires having captured all possible behaviors during the analysis and therefore all possible values produced during floatingpoint computationsin this context my question is twofoldamong the embedded architectures are there architectures that offer only flushtozero they would perhaps not have to right to advertise themselves as ie 754 but could offer closeenough ie 754style floatingpoint operationsfor the architectures that offer both in an embedded context is not flushtozero likely to be activated by the system in order to make the reaction time more predictable a common constraint for these embedded systemshandling flushtozero in the interval arithmetic that i use for floatingpoint values is simple enough if i know i have to do it my question is more whether i have to do it,['c'] +42641,possible to access the index in a hash each loop i am probably missing something obvious but is there a way to access the indexcount of the iteration inside a hash each loophash three one four two one threehasheach key value any way to know which iteration this is without having to create a count variable,['ruby'] +42668,ruby class variables the ruby classinstance stuff is giving me a headache i understand given thisclass foo var barendthat var is a variable on the created clas instancebut how do i create a subclass overridable class variablehere is an example of what i would do in pythonclass fishvar fishdef vself return selfvarclass troutfish var troutclass salmonfish var salmonprint troutvprint salmonvwhich outputstroutsalmonhow do i do the same thing in ruby,['ruby'] +42675,file sharing between android phone and a pc i am new to the android sdk is there a way to share files from my android app so that it can be accessed by another computer using wifi is there support for something like smb android version on phone is 16thanks,['android'] +42676,how to compare almost similar strings in java string thistance measure i would like to compare two strings and get some score how much these look alikefor example the sentence is almost similar and the sentence is similari am not familiar with existing methods in java but for php i know the levenshtein functionare there better methods in java,['java'] +42677,javascript anchor avoid scroll to top on click i created a function in javascript that i add to an anchor as such javascript somefunction function alertfoohtml a href onclickreturn somefunctionanchoraeverytime i click on the anchor the function executes but the screen scrolls to the topi know i could do this a hrefjavascriptvoid0 onclickreturn somefunctionanchorabut i have seen the first option implemented without this hick up of scrolling upis there any trick to itthank you,['javascript'] +42680,kill thread in pthread library i use pthread createthread1 attrs and need if some condition occured need to kill this thread how to kill this,"['c++', 'c']" +42699,c is there an exception overview i was wondering if there is a list with all exception types i know a few exceptions but i do not know them all sometimes i throw an exception and then i think maybe net already has an exception for thisfor example now i need an exception that says that a process does not exists like a fileso therefore my question is does anybody know to find a list of all exceptions i did not found it,"['c#', '.net']" +42703,authorization user info in a service layer net application i am currently working with an enterprise application in a net environment nlayered and i would like to know the best way to manage authentication authorization data filtering in my bussinesslayer bl we will use that bl from several interfaces aspnet applications and webservices and i think that my servicelayer should do the job but i just cannot find the best wayi suppose it could be something like this1 user gets authenticated aspnet web client perhaps using formsauthentication2 asp net code controller codebehind instanciate a service to get some user case done passing somehow the user3 service method checks if user exists authentication and his roles authorization to verify that he can call that method if not authenticated or authorized an exception is thrown4 service uses repositories other services whatever it needs to get the job done if some kind of finegrain filtering is required for example the user only has permissions over some projects the service applies it automaticallywhat i want is to get a servicelayer isolated from the web stuff not accesing session but who knows the user calling its methods to act correctly also i do not know how to match that work with asp net authentication in a good manneri am thinking in suministrating the user in the service ctor so that its methods have the context they need could that work i would appreciate some indications or existing code snippets on thatthank you for your help,['c#'] +42714,stop the android softkeyboard from word completion how do you stop the android softkeyboard from thisplaying completed text in a textview it is very important for my application that the spelling is not shown in 16 sdk i made the inputtype visiblepassword and that seemed to stop it however this does not appear to work in the 21 sdkthanks,['android'] +42721,youtube player api how to get duration of a loadedcued video without playing it i am not able to get the correct video durationlength in seconds of a loadedcued video via the getduration method of the youtube player api the same method however returns a valid value once the video starts playing wondering how youtube is able to show the valid duration of a loadedcued videowhen i load this html page with a 15 second video clip i get the following debug outputstate 5 duration 025 when i hit the play button i get the following debug outputstate 3 duration 15would greatly appreciate a solution or a workaround loading and immediately playing and pausing the player would be not my favorite methodhtmlhead script typetextjavascript var videoid videoid bbc videoid w a physics function id return documentgetelementbyidid script script srcscript script googleloadswfobject 21 scriptheadbody table trtd div idplayer you need flash player 8 and javascript enabled to view this video div script var ytplayer function myonplayerstatechangestate switchstate case 1 playing outinnerhtml playing break case 2 paused outinnerhtml paused break case 0 ended outinnerhtml ended break case 1 unstarted case 3 buffering case 5 cued outinnerhtml state state break default unknown outinnerhtml state state break outinnerhtml duration ytplayergetduration function myonplayererrorerrorcode outinnerhtml error occurred errorcode function onyoutubeplayerreadyplayerid ytplayer ytplayer playerid ytplayeraddeventlisteneronstatechange myonplayerstatechange ytplayeraddeventlisteneronerror myonplayererror var params allowscriptaccess always bgcolor c var atts swfobjectembedswfvideoid border0ampenablejsapi1ampplayerapiid player player 425 344 8 null null params atts script tdtr table div idoutdiv div iderrdivbodyhtml,['javascript'] +42747,decode html entities in python string i am parsing some html with beautiful soup 3 but it contains html entities which beautiful soup 3 does not automatically decode for me from beautifulsoup import beautifulsoup soup beautifulsoupound682mp text soupfindpstring print textpound682mhow can i decode the html entities in text to get a682m instead of pound682m,"['python', 'html']" +42752,callback on css transition is it possible to get a notification like callback when a css transition has been completed,"['javascript', 'css']" +42755,is a c destructor guaranteed not to be called until the end of the block in the c code below am i guaranteed that the obj destructor will be called after the more code executes or is the compiler allowed to destruct the obj object earlier if it detects that it is not used someobject obj more codei would like to use this technique to save me having to remember to reset a flag at the end of the block but i need the flag to remain set for the whole block,['c++'] +42758,an existing connection was forcibly closed by the remote host in wcf i have an abstract class called template defined asdatacontractpublic abstract class template datamember public virtual int id get set datamember public virtual string title get set datamember public virtual byte templatedoc get set datamember public virtual bool issystemtemplate get set two derived classes usertemplate and systemtemplate implements above abstract class which are defined aspublic class usertemplate template datamember public virtual int32 officeid get set datamember public virtual int32 userid get set protected usertemplate public usertemplatestring title byte templatedoc string templatedocname templatetype templatetype int officeid int userid thistitle title thistemplatedoc templatedoc thisissystemtemplate false thisofficeid officeid thisuserid userid public class systemtemplate template datamember public virtual int32 multilistgroupid get set protected systemtemplate public systemtemplatestring title byte templatedoc string templatedocname templatetype templatetype int multilistgroupid thistitle title thistemplatedoc templatedoc thisissystemtemplate true thismultilistgroupid multilistgroupid now when i try to call following service method listtemplate gettemplatesbytemplatetypeint officeid int userid templatetype templatetypei get this errorsystemnetsocketssocketexception an existing connection was forcibly closed by the remote hostis it because of the reason that i am trying to return an abstract classit runs fine if i try to call this method using unit test,"['c#', '.net']" +42760,can i make a custom colour definitions that i can share between css js and html i have a blueish colour that i want to use in many places in my app and at the moment i am copying and pasting it between styles in my css is there a way of defining a constant like the standard colours blue red etc that i could share between my css my html and my jsi would like to be able to say somewhere preferably cssmyblue 33cc99in css saybackgroundcolormybluein html saytd colormyblueand in javascripttagstylebackgroundcolor mybluei am guessing this is impossible and google turned nothing up so has anyone got any ideas i doubt i am the only person to come across this,"['javascript', 'html', 'css']" +42762,add a reference from a c app to a dll compiled without clr i am using visual studio 2008 to build a solution with two projects a c console app and a c dll i want the app to call a function from the dll using pinvoke therefore i am trying to add the dll as a reference to the c app but when i try the add reference command visual studio would not let me do it unless i set the clr property on the dll under configuration propertiesgeneral now i thought that pinvoke could handle plainold win32 dlls indeed if i build my dll without clr and just copy it by hand to bindebug then the app runs fine so why is clr required to add the dll as a reference and if vs would not let me add it is there some clean workaround so that my app finds the dlli see that someone had a similar issue here though with a 3rdparty dll the answer he got was to build a wrapper but this is not really necessary since the app can use the dll just fine it is just the add reference step that does not work and besides would not the wrapper code need a reference to the dll raising the same problem as before i would really like an answer that does not involve writing a wrapper at all,"['c#', 'c++']" +42764,profiling c in the presence of aggressive inlining i am trying to figure out where my c program is spending its time using gprof heres my dilemma if i compile with the same optimization settings i use for my release build pretty much everything gets inlined and gprof tells me unhelpfully that 90 of my time is spent in a core routine where everything was inlined on the other hand if i compile with inlining thisabled the program runs an order of magnitude sloweri want to find out how much time procedures called from my core routine are taking when my program is compiled with inlining enabledi am running 64bit ubuntu 904 on a quadcore intel machine i looked into googleperftools but that does not seem to work well on x86 64 running on a 32bit machine is not an optiondoes anyone have suggestions as to how i can more effectively profile my application when inlining is enablededit here is some clarification of my problem i apologize if it was not clear initiallyi want to find where the time was being spent in my application profiling my optimized build resulted in gprof telling me that 90 of the time is spent in main where everything was inlined i already knew that before profilingwhat i want to find out is how much time the inlined functions are taking preferably without thisabling optimization or inlining in my build options the application is something like an order of magnitude slower when profiling with inlining thisabled this difference in execution time is a convenience issue but also i am not confident that the performance profile of the program built with inlining thisabled will strongly correspond to the performance profile of the program built with inlining enabledin short is there a way to get useful profiling information on a c program without thisabling optimization or inlining,['c++'] +42772,in rails how do you render json using a view suppose youre in your users controller and you want to get a json response for a show request it would be nice if you could create a file in your viewsusers dir named showjson and after your usersshow action is completed it renders the filecurrently you need to do something along the lines ofdef show user userfind paramsid respond to do format formathtml formatjson render json userto json endendbut it would be nice if you could just create a showjson file which automatically gets rendered like sodef show user userfind paramsid respond to do format formathtml formatjson endendthis would save me tons of grief and would wash away that horribly dirty feeling i get when i render my json in the controller,"['ruby-on-rails', 'ruby']" +42777,modify a file with a rails generator how do you make a generator that alters a fileim trying to make it so that it finds a pattern in a file and adds come content to the line below it,['ruby-on-rails'] +42804,mysqli equivalent of mysql result i am porting some old php code from mysql to mysqli and i have ran into a minor snag is there no equivalent to the old mysql result functioni know mysql result is slower than the other functions when youre working with more than 1 row but a lot of the time i have only 1 result and 1 field using it lets me condense 4 lines into 1old codeif r mysql num rowsr blarg mysql resultr 0 blahdesired codeif r rnum rows blarg rresult0 blahbut there is no such thing is there something i am missing or am i going to have to suck it up and make everythingif r rnum rows row rfetch assoc blarg rowblah,['php'] +42812,right align and left align text in same html table cell i have a cell in an html table i would like part of the cell contents to be left justified and part to be right justified is this possible,"['html', 'css']" +42829,what version of python should i use if i am a new to python if i am absolutely new to python and am literally reading about printing statements to console variable types collections etcwhat version of python should i usei am aware that there is an abundance of 3rd party libraries for python 26x but i am scared i will learn some things that would not carry over well into python 3for example in python 3 you can use input in python 2 you have to use raw inputthank you very much for the information,['python'] +42830,python datetime localization what do i need to do modules to load locale methods to invoke etc so that when i calldatetimedate2009116strftimea ybdinstead of gettingout20 friday 2009jan16i get spanishfrenchgerman outputout20 viernes 2009ene16without having to change my whole operating systems locale ie just use python calls to dynamically set the locale and keep the changes scoped within my appthanks,['python'] +42853,where does mysql store database files i have uninstall wamp server and now i need my database to restore how can i do this process,['mysql'] +42857,whats the right way to define an anchor tag in rails it is obvious from the documentation and google how to generate a link with a segment eg podcast5comments you just pass a value for anchor to link tomy concern is about the much simpler task of generating the a namecommentscommentsa tag ie the destination of the first linki have tried the following and although they seemed to work the markup was not what i expectedlink to comments name commentslink to comments anchor commentsi think i am missing something obvious thanks,"['html', 'ruby-on-rails']" +42865,if swing models getters are not threadsafe how do you handle them it is well known that updating a swing gui must be done exclusively in the edt less is advertised that reading stuff from the gui mustshould also be done in the edt for instance let us take buttonmodels isselected method which tells for instance togglebuttons state down or up in every example i have seen isselected is liberally queried from the main or whichever thread but when i look at defaultbuttonmodels implementation it is not synchronized and the value is not volatile so strictly speaking isselected could return garbage if it is read from any other thread than the one from which it is set which is the edt when the user pushes the button or am i mistakeni originally thought about this when shocked by item 66 in blochs effective java this examplepublic class stopthread private static boolean stoprequested public static void mainstring args throws interruptedexception thread backgroundthread new threadnew runnable public void run int i 0 whilestoprequested i backgroundthreadstart timeunitsecondssleep1 stoprequested true contrary to what is seems that program never terminates on some machines at least updating the stoprequested flag from the main thread is invisible to the background thread the situation can be fixed with synchronized getters setters or by setting the flag volatilesois querying a swing models state outside the edt strictly speaking wrongif not how comeif yes how do you handle it by luck or by some clever workaround invokeandwait,['java'] +42869,which is better loading of images for listview i am wondering if which of the two is better in loading images in a listview from web is it by batch through some number of threads that are running simultaneously or one by one through thread queuei have noticed but i do not know if that is really the implementation from the youtube app that the images are loaded by batch and it is kinda fast even for not only loading images but also requesting some data from the web as well does anyone have an idea,['android'] +42870,project templates eclipse java i am researching possibilities to create project templates for the kind of projects my team is working on embedded java we want to make it trivial for a new developer to not mess up creating a new project all the tools we use in our team should be prthe basic idea is that there should be one command to set up a project and ide to provide for the following create a new java project including eclipse project file create a build script needs to work outside of the ide include deploy options in the build script set up a git project setup pmd to run with a configured set of rules integrated in the ide setup checkstyle to run with a configured set of rules integrated in the ide configure code templates eclipse to match our teams coding guidelines javadoc configure the eclipse code formatter the configuration of the command should be upgradeable easilyso far i see two ways to do this maven 2 archetype i basically do not like maven because i have been fighting with it so often i am not sure that the overhead of trying to make the tool do what i want it to justifies the effort on the other hand it seems like this is exactly what archetypes are supposed to do do you have any experience in how far you can customize the eclipseeclipse part i guess that the eclipse configuration with be the most complicated step eclipse nature i could create a project nature as far as i understand the eclipse ecosystem that is the component that would show up if i would choose to provide for something like right click new my java project type do you know how far i can customize the resulting eclipse project shell script i could create an empty project with all the configuration in place introduce some special tokens in the relevant plain text files like and then write a shellscript that reads values for these options from a properties file copy the project template and substitute the values while it is maybe a bit fragile it seems like a easy and quick way of doing itdo give you a little more context it is ok if the result locks us into eclipse while the build should run without eclipse for our ci the team uses eclipse and it is highly unlikely that we will ever switch also all developers run more or less the same hardsoftware linux we do not work in the domain of enterprise java apps so we really do not need all the fancy dependency management stuff from maven as a matter of fact our build process is so special that it probably is much easier to just call make or ant scriptsso the questions are do you have any experience with this kind of stuff do you have an opinion towards either the eclipse nature way or maven do you know other tools that provide for a setup like that thank you very much for your inputcheersvalentinps people seem to be religious about their build tools please note that i do not want to start a flamewar here for or against maven i am sure maven can be a great tool but i think in our context we only need 5 of its functionality and from my experience that remaining 95 can get in your way,['java'] +42871,silverlight or wpf iam about to start work on a new lob application which is mainly forms over data i am going to use either wpf or silverlight but am not sure which technology to use silverlight seems to have everything i need with the bonus of being cross platform as well is there any reason why i should use wpf in this context or is silverlight the way to go for these sort of applications,"['c#', '.net']" +42882,how do i use activatorcreateinstance with strings in my reflection code i hit a problem with my generic section of code specifically when i use a stringvar oval objecttestvar otype ovalgettypevar sz activatorcreateinstanceotype ovalexceptionan unhandled exception of type systemmissingmethodexception occurred in mscorlibdlladditional information constructor on type systemstring not foundi tried this for testing purposes and it occurs in this single liner toovar sz activatorcreateinstancegettype testoriginally i wrote var sz activatorcreateinstancegettypebut i get this erroradditional information no parameterless constructor defined for this objecthow do i create a string using reflection,"['c#', '.net']" +42890,how to edit and see live css effect in ie8 like we see in firefox web developer toolbar edit css function how to edit and see css effect in ie8 like we see in firefox web developer toolbar edit css functionwhere is similar function in ie8 developer toolbar or does any other ie plugin have this type functionality,"['html', 'css']" +42893,add hyperlink to textblock wpf greetings i have some text in a db and it is as followslorem ipsum dolor sit amet consectetur adipiscing elit duis tellus nisl venenatis et pharetra ac tempor sed sapien integer pellentesque blandit velit in tempus urna semper sit amet duis mollis libero ut consectetur interdum massa tellus posuere nisi eu aliquet elit lacus nec erat praesent a commodo quam a hrefsome siteasuspenthisse at nisi sit amet massa molestie gravida feugiat ac sem phasellus ac mauris ipsum vel auctor odiomy question is how can i thisplay a hyperlink in a textblock i do not want to use a webbrowser control for this purpose i do not want to use this control either also,['html'] +42930,silverlight 40 deploying the xap via a custom installer and configure it for oob elevated permissions is it possible to deploy a xap using a custom installer much like deploying a desktop app and configure it to run as oob with elevated permissionsbottomline is when the app is started it should run in elevated permissions oob with out any user intervention at all after the installation,"['c#', '.net']" +42939,when is it a good idea to store passwords in clear text i am working on an application that is targetted at non technical users i expect a large number of support calls regarding lost passwords and inability to logini am using aspnet membership provider that provides 3 options for storing passwords clear text hashed encryptedis it a good idea to store passwords in clear text given the nature of this application are there any legal issues involved in storing passwords in clear text,['asp.net'] +42947,passing parameters to phpunit i am starting to write phpunit tests and i would like the tests to be run from developers machines as well as from our servers developers machines are set up differently than the servers and even differently from each otherto run in these different places it seems to be the person that runs the test is going to have to indicate where it is being run the test can then look up the proper config of the machine it is running oni am imagining something likephpunitbat x johns laptop unittestphpor on the alpha serverphpunit x alpha unittestphpin the test i would be able to get the value if the x or whatever it is parameter and know for example what the path to the app root is for this machineit does not look like the command line allows for that or have i missed something,['php'] +42966,core data backing up to google app engine iphone i am considering backing up data from an iphone application using the google app engine gae i was also considering using python to build a restful app to deal with incomingoutgoing dataon the client side i am using core data to store the information i wish to back up and retrieve using the gaei was wondering whether there were any good tutorialsresources on carrying out the above or whether this is perhaps something that others have tried to implement any advice or pointers would be most welcome,"['iphone', 'objective-c']" +42970,how can i get geany to show me the methods a library has when i press the key in visual studio i could just press ctrlspacekey and the methods appeared in geany is there a way for me to get this functionality,['python'] +42999,iphone uitextview does not support data detectors when the text view is editable i am getting an interesting warning at build time iphone simulator that gives the followingeditviewxib350 uitextview does not support data detectors when the text view is editablethis is basically non existent on google and i would like to remove itmy editviewxib has a textview where i write notes into it is there any more info that is needed,['iphone'] +43005,net inheritance suppress a property from the base class consider the employee manager and assistant classespublic class emp public string name get set public manager manager get set public assistant assistant get set public class manager emp public class assistant empthe goal is to thisallow a piece of code to access a property like thisvar foo new managervar elmo new empelmomanager fooelmomanagermanager new manager how to thisallow access to managermanager because manager inherits from emp it has a manager and assistant propertyquestionare there any modifiers in nets inheritance implementation to remove the manager and assistant propertiesupdatethank you for your great answers everyone i was hoping the simplification and contrivance of empmgr would show through in this question it is clear that the inheritance in this example should be taken to another commonality something like person where the classes would share names birthdates etc your input is much appreciated,"['c#', '.net']" +43020,a terminallike window for wxwidgets i am looking to add an element to my wxwidgets gui that behaves like a terminal emulator not in terms of a shell which executes commands but just the inputoutput setup of an application running in a terminalbasically the requirements arestreaming inputoutput when you enter a character it is added to an input stream and when something is piped to the terminal it prints out immediatelyno editing once you type in a character it is permanently there since it is probably been consumed by the application running in the terminalsome sort of scrolling even if it just shows a few lines or somethingit would be nice if there is something that already does this but suggestions on how to implement this with already existing controls such as wxtextctrl would also be welcome,['c++'] +43057,defining custom hash function and equality function for unordered map i am trying to define a type of unordered map that has a custom hash function and equality comparison function the function prototypes of these functions are as followssetvertex3dxt is the type of the key cell3dxt is the type of the valuesize t vertexsethashfunctionsetvertex3dxt vertexset hash functionbool setequalsetvertex3dxt a setvertex3dxt b equalityi have these function prototypes declared and then i try to declare the type as followstypedef stdtr1unordered mapsetvertex3dxt cell3dxt vertexsethashfunction setequal celldatabasemaptypebut it says that the vertexsethashfunction and setequal are not valid template type arguments the documentation is confusing because it does not say exactly what type the template arguments are supposed to be am i just supposed to give it the function as i did here or is there some other kind of object that encapsulates the function because the documentation does talk about the hash function object type,['c++'] +43058,width for tag in html is it possible to set some width to the a tag in html if yes what is the way if no is there any work around,['html'] +43062,mysql find min but not zero i am trying to fetch the minimum value of a column in mysql using the min function but is it possible to tell mysql to ignore the zero values problem is that i am storing 0 as default value instead of null for a tinyint column what i want is to get the minimum value that is greater than 0select abaseloc id abaseloc latitude abaseloc longitude abaseloc thistance minbbasecost ton2 cost as minton2 minbbasecost ton3 cost as minton3 minbbasecost ton10 cost as minton10 from bbox logi base locations a left join bbox logi base cost b using baseloc id group by abaseloc idthank you for any helpedit 01sorry that i forgot to mention this the bbox logi base cost table has rows that contain fragmented values for example one row can have basecost ton2 cost as 0 but other columns filled with values and the other row can have every column but one as 0 so no row can be filtered using a where condition,['mysql'] +43064,unsigned keyword in c does the unsigned keyword default to a data type in c i am trying to write a function for a class for the prototypeunsigned rotateunsigned object int countbut i do not really get what unsigned means i thought it would be like unsigned int or something thanks,['c++'] +43068,difference between tostring and as string in c what is the difference between using the two following statements it appears to me that the first as string is a type cast while the second tostring is an actual call to a method that converts the input to a string just looking for some insight if anypagetheme sessionsessiontheme as stringpagetheme sessionsessionthemetostring,['c#'] +43094,can i pass a type object to a generic method i have a findall method on my dataaccesslayer which looks like thispublic findresultt findallt where t entity newand a client code that has a type array which it needs to use to iteratively call the findall method with like thisforeach var type in typearray var result dataaccesslayerfindalltype but the compiler complaints about type or namespace expected is there an easy way to get around this i have tried typegettype or typeoftype and neither workedmany thanks in advance,"['c#', '.net']" +43096,performance replacement for string in java anyone remembers the name of that opensource project that developed some nice replacement for string in java i know there is is one just cant find it in google and dont remember the namei am not talking about stringbuilderthanks,['java'] +43107,will c exceptions safely propagate through c code i have a c application that calls sqlites sqlite is in c sqlite3 exec which in turn can call my callback function implemented in c sqlite is compiled into a static libraryif an exception escapes my callback will it propagate safely through the c code of sqlite to the c code calling sqlite3 exec,"['c++', 'c']" +43110,linq or equivalent of where is there a method in linq where you can use to build sql strings like where a1 or a2,['.net'] +43112,patterns for php multi processes which design pattern exist to realize the execution of some php processes and the collection of the results in one php processbackgroundi do have many large trees 10 entries in php and have to run recursive checks on it i want to reduce the elapsed execution time,['php'] +43117,getting the id of the object when inside form for or fields for i have the following code that is generating fields for an invoicethis is in the edithtmlerb for the invoice class ffields forinvoice items do f render partial invoice itemsfields locals f f end and i generate the invoice items as part of the invoice objectinvoice invoicefindparamsid include invoice items order invoice itemsthisplay orderit works just fine but i need to wrap each one in a div and assign that objects id to the div div idi 2345 that kind of thing so i can use jquery wizardry where i am stumbling like a newborn foal is how do i access the the id of the invoice item that is being calledi can do a ftext field id and it gives me the correct id so it knows it but i am hoping there is some rails magic pixie dust i can sprinkle that will give it to me without having to rip that apart,['ruby-on-rails'] +43121,how to migrate ugly and undocumented vb6 code to net i know that there are already questions about vb6 migration but the code base of my project brings some new questions herei have to say the code quality structure and architecture is just a nightmarethere are 2 big projectsnr1 with 40 forms 40 modules and a few class files this exe is kind of a base systemnr2 with 80 forms 20 modules and a few class files again this exe calls functions form the base systemthen there are 10 other projects with gui 13 forms each and another 90 nongui projects most of them exe files some dlls the dlls are written in c c and vb6the code has grown evolutionary since 10 years and written mostly by 1 bad developer at a timefunctions with 500 lines and more are very common 90 of the gui components are named text1 command21 a copy and paste is all over the place e g an exe project without gui with 50 lines of code was copied and the only change in the copy was to send files per mail instead of ftp there are 2 further copies of the same project also i once had a small form 15 fields where i should solve a small problemmax a half hour thing normally every time i changed something it either did not work or produced new errors in the form after 2 days i decided to rewrite the form completely and from 20 sql statements in the old form only 2 survived in the new one do not even ask about comments in the code ai took over the project a few months ago and i am the only maintainer there is a constant but low flow of change requests and errors and we get a maintenance budget from our customers to keep the software running and up to date in terms of legal requirementsmy options1 rewrite from scratch in that case i could write it in java for portabilitythe problem here is that besides some old user help there is no documentation so the ugly code is the documentation there is one person who has the high level know how what the software should do also it is hard to convince management about doing it even if there are huge cost savings in the long term there are political issues i also cannot do that one vb project at a time because the database structure is no better than the code ie has to done from scratch too so i can only change the whole software at once2 migrate the code to vbnet cmigration of the main projects first i tested that already and got 20 upgrade comments from project nr1 most of them things like screenmousepointer changed functions with variant return values and so onmy idea here is after the convert create classes for db abstraction change the code to use these classes and do refactoring migrate and change the other projects too and when all the code uses the db classes change the db structure3 refactor the code in vb6 whenever i have to change something there anyway i am already doing this partly and at some point refactor also the rest that way it is more easy to see the original functionality because it is original code and when there are errors it is obvious that they cannot be results of the migrationwhen the code is refactored i assume it will be 5075 smaller then also it is easier to migrate it to net then change db structure and then do another round of refactoringathere are some bigger changes to do in the future make it compatible with win7 and another big cr which affects big parts of the code so there would be a good opportunity to do these changes as i will have to go through lots of the code anywaymy question is who has experience hints for migrating bad ugly code which options would you suggest,['.net'] +43128,why do i need the django settings module set every time i log on to my server through ssh i need to type the followingexport django settings modulesettingsif i do not any usage of the managepy module failsmy managepy has the following added codeif notification in settingsinstalled apps from notification import models as notification def create notice typesapp created models verbosity kwargs notificationcreate notice typefriends invite invitation received you have received an invitation notificationcreate notice typefriends accept acceptance received an invitation you sent has been accepted signalspost syncdbconnectcreate notice types sendernotificationelse print skipping creation of noticetypes as notification app not foundany ideas,['python'] +43132,phpunit test question how to unit test my class i am trying to get into unit testing for the obvious positives it introduces and i am trying to write a unit test for a class i wrote the other day i know this is the opposite to tdd please bear with memy class image is used in conjunction with some others for image manipulation image essentially wraps a gd image resource and stores data along with it for example an instance of image will always contain it is current state ie its new widthheight if resized the original image data etcthe image class also contains methods forcreating itself from a file string data or url eg imageloadfrompathcreating a new gd image resource from the properties of the current image instance eg for image resizing to maintain background transparency etccloning the gd image resource for use in the manipulation classeswhat i am struggling with is how to unit test this class properly with phpunit i have done some reading and i have a few conflicting ideas on how to approach it and i do not know whats right do iwrite a test for each method of the class i read somewhere that i should test each and every method however some of the methods run others rightly so may i add so you then have a chain of dependency but i also read that each unit test should be independent from the other so what do i do if this is the casewrite each test as a usage route of the class i also read somewhere that each test should instead represent 1 pathusage route you can take with the class therefore if you cover every usage youll ultimately get complete code coverageso which of these is correct if any,['php'] +43135,why does a native library use 15 times more memory when used by java as when used by a cprogramm under linux i have written a library in c which consumes a lot of memory millions of small blocks i have written a c program which uses this library and i have written a java program which uses the same library the java program is a very thin layer around the library basically there is only one native method which is called does all the work and returns hours later there is no further communication between java and the native library using the java invocation interface nor there are java object which consume a noteworthy amount of memoryso the c program and the java program are very similar the whole computationmemmory allocation happens inside the native library still when executed the c program consumes 3gb of memory but the java program consumes 43gb virt amount reported by topi checked the memory map of the java process using pmap only 40mb are used by libraries so additional libraries loaded by java are not the causedoes anyone have an explanation for this behavioredit thanks for the answers so far to make it a little bit more clearer the java code does nothing but invoke the native library once the java heap is standard size perhaps 60mb and is not used except for the one class containing the main method and the other class invoking the native librarythe native library method is a long running one and does a lot of mallocs and frees fragmentation is one explanation i thought of myself too but since there is no java code active the fragmentation behavior should be the same for the java program and the c program since it is different i also presume the used malloc implementations are different when run in c program or in java program,['java'] +43140,ioc and constructor overinjection antipattern resolution this question is a result of a post by jeffery palermo on how to get around branched code and dependency injection in his post jeffery has a class public class orderprocessor iorderprocessor that takes 2 interfaces on the constructor one is a validator iordervalidator and an iordershipper interface his method code branches after only using methods on the iordervalidator interface and never uses anything on the iordershipper interfacehe suggests creating a factory that will call a static method to get the delegate of the interface he is creating a new object in his refactored code which seems unnecessaryi guess the crux of the issue is we are using ioc to build all our objects regardless if they are being used or not if you instantiate an object with 2 interfaces and have code that could branch to not use one of them how do you handle itin this example we assume validatorvalidateorder always returns false and the iordershippership method is never calledoriginal codepublic class orderprocessor iorderprocessor private readonly iordervalidator validator private readonly iordershipper shipper public orderprocessoriordervalidator validator iordershipper shipper validator validator shipper shipper public successresult processorder order bool isvalid validatorvalidateorder if isvalid shippershiporder return createstatusisvalid private successresult createstatusbool isvalid return isvalid successresultsuccess successresultfailed public class ordershipper iordershipper public ordershipper threadsleeptimespanfrommilliseconds7 public void shiporder order ship the order refactored codepublic class orderprocessor iorderprocessor private readonly iordervalidator validator public orderprocessoriordervalidator validator validator validator public successresult processorder order bool isvalid validatorvalidateorder if isvalid iordershipper shipper new ordershipperfactorygetdefault shippershiporder return createstatusisvalid private successresult createstatusbool isvalid return isvalid successresultsuccess successresultfailed public class ordershipperfactory public static funciordershipper creationclosure public iordershipper getdefault return creationclosure executes closure and here is the method that configures this factory at startup time globalasax for aspnetprivate static void configurefactories ordershipperfactorycreationclosure objectfactorygetinstanceiordershipper,"['c#', '.net']" +43143,when to use a switch statement in java i appreciate that anything that can be done by a switch statment can be done by an if else statementbut are there stylistic rules for when one should use the switch rather than if else statment,['java'] +43145,jump into file line c how can i jump into some line in my file eg line 300 in ctexttxt,"['c#', '.net']" +43153,alternative to nssetuncaughtexceptionhandler on iphone i am trying to make a general error handler for an iphone app that brings the user to a recovery screen whenever any general error is thrown in the application without putting a trycatch block around every single method in the applicationusing nssetuncaughtexceptionhandler does not work because the application terminates after the handler is runis there any way to change this behavior or use any other handler that will catch exceptions in general and not cause the application to exit afterwardand please no nonanswers about whether it is a good or bad idea,"['iphone', 'objective-c']" +43155,gravatar how do i know if a user has a real picture i have gotten the gravatar service working on my site but i would like to know if the user has uploaded their picture or not is there a way to know this,['c#'] +43159,dataannotations vs idataerrorinfo dataannotations vs idataerrorinfopros and cons of bothbenefits of one over the other especially related to mvc,['.net'] +43165,how to check file size in python i am writing a python script in windows i want to do something based on the file size for example if the size is greater than 0 i will send an email to somebody otherwise continue to other things how do i check the file size,['python'] +43211,ui threading with viewmodels collections that are bound in a wpf view must be updated on the ui threadviewmodel exposes a collectiontherefore when collection in the viewmodel is modified it must be done in the ui threadbest practice is to keep viewmodels ignorant of view and presumably such details as thispatcher what is the cleanest way to resolve this while keeping view model testable,['.net'] +43218,efficiency for including files of functions in php if i had a large number of functions would it be better to keep them all in one large file or would it be better to separate them into several files of related functions by better i mean more efficient for both maintainability and for the server processing the requestfor example right now i have all my files in a file named includephp but would it be wiser to have an include file of includes likephp includefunctionsuserphp includefunctionsadminphp includefunctionscontentphp includefunctionsnavphp includefunctionsdatabasephp includefunctionsother junkphp,['php'] +43220,reopen files in python say i have this simple python scriptfile opencsome texttxtprint filereadlinesprint filereadlineswhen it is run the first print prints a list containing the text of the file while the second print prints a blank list not completely unexpected i guess but is there a way to wind back the file so that i can read it again or is the fastest way just to reopen it,['python'] +43226,search or compare within a grapheme cluster in korean in my current implementation of a uisearchbarcontroller i am using nsstring compare inside the filtercontentforsearchtextscope delegate method to return relevant objects based on their name property to the results uitableview as you start typingso far this works great in english and korean but what i would like to be able to do is search within nsstrings defined character clusters this is only applicable for a handfull of languages of which korean is onein english compare returns new results after every letter you enter but in korean the results are generated once you complete a recognized grapheme cluster i would like to be able to search through my korean objects name property via the individual elements that make up a syllable can anyone shed any light on how to approach this i am sure it has something to do with searching through utf16 characters manually or by utilising a lower level class cheershere is a specific example that is just not working nsstring string1 i nsstring string2 ansrange resultrange string1 decomposedstringwithcanonicalmapping rangeofstring string2 decomposedstringwithcanonicalmapping optionsnsliteralsearchthe result is always nsnotfound with or without decomposedstringwithcanonicalmapping any ideas,"['iphone', 'objective-c']" +43233,how should i log exceptions in aspnet how should i log exceptions i never tried logging in net before nor try to dump exceptions to a txt or binary file i dont require a text file just a way to view the logs with the file and line edit using aspnet,"['c#', '.net', 'asp.net']" +43248,debugging asserts in qt creator when i hit a normal assert statement while debugging with visual studio i get the option to break into the debugger so i can see the entire stack trace and the local variables not just the assert messageis it possible to do this with qt creatormingw32 and q assertq assert x,['c++'] +43257,surfaceview glsurfaceview framelayout i am new at this java and opengl so please bear with me if the answer to the question is simple i am trying to get a camera preview screen with the ability to thisplay 3d objects simultaneously having gone through the samples at the api demos i thought combining the code for the the examples at the api demo would suffice but somehow its not working the forces me to shut down upon startup and the error is mentioned as null pointer exception could someone share with me where did i go wrong and how to proceed from there how i did the combination for the code is as shown belowmyoverviewxml xml version10 encodingutf8 framelayout xmlnsandroid androidorientationhorizontal androidlayout widthfill parent androidlayout heightfill parent androidopenglglsurfaceview androidididcubes androidorientationhorizontal androidlayout widthfill parent androidlayout heightfill parent surfaceview androidididcamera androidlayout widthfill parent androidlayout heightfill parent framelayoutmyoverviewjava import androidappactivity import androidosbundle import androidviewsurfaceview import androidviewwindow public class myoverview extends activity override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate hide the window title requestwindowfeaturewindowfeature no title camera view as the background surfaceview cameraview surfaceview findviewbyidridcamera cameraview new cameraviewthis visual of both cubes glsurfaceview cubesview glsurfaceview findviewbyidridcubes cubesview new glsurfaceviewthis cubesviewsetrenderernew cuberendererfalse set view setcontentviewrlayoutmyoverview glsurfaceviewjava import androidcontentcontext class glsurfaceview extends androidopenglglsurfaceview public glsurfaceviewcontext context supercontext note i didnt list the rest of the files as they are just copies of the api demos the cameraview refers to the camerapreviewjava example and the cuberenderer refers to the cuberendererjava and cubejava example any help would be appreciated as i have been stuck at this for a couple of days p thanks sorry didnt realise that the coding was out of place due to formatting mistakes p,['android'] +43259,how do i indicate long text into a smaller fixed column with css how do i fit long text into a fixed width column where i have room for only one line of text the text needs to be cut to a fixed width lets say to 100px and i would like to add dots at the end something like this for examplegiven stringsome really long string that i need to fit in theredesired output in fixedwidthcolumn should besome really long string,['css'] +43265,does having more attributes in a table reduce performance so far i am quite comfortable working with c windows application i am about to shift to aspnet to develop a website the requirement has made me to put around 50 columns in a single table i know this concept of breaking it into small tables using normal formsi tried googling but dint get much resultsi need to know if my table with 50 attributes would decrease performance of my web application can somebody suggest me about this,"['c#', 'asp.net', 'sql']" +43281,compute percentage for bigdecimals i have not found any native method to do this so i created my own in a helper classpublic static bigdecimal percentagebigdecimal base bigdecimal pct return basemultiplypctdividenew bigdecimal100but i do not quite like it i wonder if the api has something similar the number class ancestor of bigdecimal would be a nice place,['java'] +43291,why is there no iarrayt interface in net update 2011jan06believe it or not i went ahead and incorporated this interface into an open source library i have started taonet i wrote a blog post explaining this librarys iarrayt interface which not only addresses the issues i originally raised in this question a year ago but also provides a covariant indexed interface something that is sorely lacking in my opinion in the bclquestion in shorti asked why net has ilistt which implements icollectiont and therefore provides methods to modify the list add remove etc but does not offer any inbetween interface such as iarrayt to provide random access by index without any list modificationedit 2010jan21 2 pm estin a comment to jon skeets original answer in which he questioned how often one would have any need for a contract such as iarrayt i mentioned that the keys and values properties of the sortedlisttkey tvalues class are ilisttkey and ilistvalue respectively to which jon repliedbut in this case it is declared to be ilist and you know to just use the indexers it is not hugely elegant i agree but it does not actually cause me any painthis is reasonable but i would respond by saying that it does not cause you any pain because you just know you cannot do it but the reason you know is not that it is clear from the code it is that you have experience with the sortedlisttkey tvalue classvisual studio is not going to give me any warnings if i do thissortedliststring int mysortedlist new sortedliststring int iliststring keys mysortedlistkeyskeysaddnewkeyit is legal according to iliststring but we all know it is going to cause an exceptionguillaume made an apt point as wellwell the interfaces are not perfect but a dev can check the isreadonly property before calling addremovesetagain this is reasonable but does this not strike you as a bit circuitoussuppose i defined an interface as followspublic interface icanwalkandrun bool iscapableofrunning get void walk void runnow suppose as well that i made it a common practice to implement this interface but only for its walk method in many cases i would opt to set iscapableofrunning to false and throw a notsupportedexception on runthen i might have some code that looked like thisvar walkerrunners new dictionarystring icanwalkandrun icanwalkandrun walkerrunner walkerrunnerssomekeyif walkerrunneriscapableofrunning walkerrunnerrun else walkerrunnerwalkam i crazy or is this kind of defeating the purpose of an interface called icanwalkandrunoriginal posti find it very peculiar that in net when i am designing a class with a collection property that provides random access by index or a method that returns an indexed collection etc but should not or cannot be modified by addingremoving items and if i want to do the right thing oopwise and provide an interface so that i can change the internal implementation without breaking the api i have to go with ilisthe standard approach it seems is to go with some implementation of ilistt that explicitly defines the methods add insert etc typically by doing something likeprivate listt itemspublic ilistt items get return itemsasreadonly but i kind of hate this if another developer is using my class and my class has a property of type ilistt and the whole idea of an interface is these are some available properties and methods why should i throw a notsupportedexception or whatever the case may be when heshe tries to do something that according to the interface should be completely legali feel like implementing an interface and explicitly defining some of its members is like opening a restaurant and putting some items on the menu perhaps in some obscure easytomiss part of the menu but on the menu nonetheless that are simply never availableit seems there ought to be something like an iarrayt interface that provides very basic random access by index but no addingremoving like the followingpublic interface iarrayt int length get t thisint index get and then ilistt could implement icollectiont and iarrayt and add its indexof insert and removeat methodsof course i could always just write this interface and use it myself but that does not help with all the preexisting net classes that do not implement it and yes i know i could write a wrapper that takes any ilistt and spits out an iarrayt but seriouslydoes anyone have any insight into why the interfaces in systemcollectionsgeneric were designed this way am i missing something is there a compelling argument against what i am saying about my issues with the approach of explicitly defining members of ilistti am not trying to sound cocky as if i know better than the people who designed the net classes and interfaces it just does not make sense to me but i am ready to acknowledge there is plenty i probably have not taken into consideration,['.net'] +43293,why not invalid column name xyz error in subquery although column name is not in subquery table when i run this queryselect customerid from stocksdbosuppliersit gives me this error invalid column name customerid this error is valid as there is no column customerid in suppliers table but when i use same query in subquery it does not give any error egselect from someotherdbdbocustomer where customerid in select customerid from stocksdbosuppliershere i am expecting same error invalid column name but query runs without any errorfully qualified name is just convention both dbs are on same server customerid does exists in someotherdbdbocustomer table but not in subquerywhy is this behavior is this something with subquerythanks,['sql'] +43296,c responsewritefile vs responsetransmitfile filesize issues i have a 5mb pdf on the server dowloading this file using a writefile gives me a 15mb download where as the transmitfile gives the correct 5mb filesizeis this due to some sort of uncompression into memory on the server for the writefile just wonder if anyone had seen the same thing happeningps only noticed it since we went to iis7code beingif fileexistsfilepath httpcontextcurrentresponseclear httpcontextcurrentresponsecontenttype applicationoctetstream httpcontextcurrentresponseaddheadercontentthispositionattachmentfilenamepathgetfilenamefilepath httpcontextcurrentresponseaddheadercontentlength new fileinfofilepathlengthtostring httpcontextcurrentresponsewritefilefilepath httpcontextcurrentresponsetransmitfilefilepath httpcontextcurrentresponseflush httpcontextcurrentresponseclose,['c#'] +43306,css could not override inherited textdecoration property i am going to use such css table for my menu menu textdecorationunderlinemenu alink textdecorationnone color0202c0menu aactive textdecorationnone color0202c0menu avisited textdecorationnone color0202c0menu ahover textdecorationunderline color0099ffbut while trying to apply it to the document span classmenu some underlined text came here a hrefthis text should not be underlined until mouse onaspani found unexpected behavior link text always stay underlined what i am doing wrong could it depends on browser i am using mozilla firefox 356 probably ie 60 thisplay it properly if so how can i rely css at all what should i use to substitute itin fact usually i got learned new programming languages very quickly and never had any problems with programing basis until i started html and css either i am incompatible with it or its features was never recounted well enough,"['html', 'css']" +43310,general type conversion without risking exceptions i am working on a control that can take a number of different datatypes anything that implements icomparablei need to be able to compare these with another variable passed inif the main datatype is a datetime and i am passed a string i need to attempt to convert the string to a datetime to perform a date comparison if the string cannot be converted to a datetime then do a string comparisonso i need a general way to attempt to convert from any type to any type easy enough net provides us with the typeconverter classnow the best i can work out to do to determine if the string can be converted to a datetime is to use exceptions if the convertfrom raises an exception i know i cant do the conversion and have to do the string comparison the following is the best i got string thestring 99122009 datetime thedate new datetime 2009 11 1 icomparable obj1 thestring as icomparable icomparable obj2 thedate as icomparable try typeconverter converter typedescriptorgetconverter obj2gettype if convertercanconvertfrom obj1gettype consolewriteline obj2compareto converterconvertfrom obj1 consolewriteline date comparison catch formatexception consolewriteline obj1tostring compareto obj2tostring consolewriteline string comparison part of our standards at work state that exceptions should only be raised when an exception situation ie an error is encounteredbut this is not an exceptional situation i need another way around itmost variable types have a tryparse method which returns a boolean to allow you to determine if the conversion has succeeded or not but there is no tryconvert method available to typeconverter canconvertfrom only dermines if it is possible to convert between these types and doesnt consider the actual data to be converted the isvalid method is also uselessany ideasediti cannot use as and is i do not know either data types at compile time so i dont know what to as and is toeditok nailed the bastard its not as tidy as marc gravells but it works i hope thanks for the inpiration marc will work on tidying it up when i get the time but i have got a bit stack of bugfixes that i have to get on with public static class cleanconverter summary stores the cache of all types that can be converted to all types summary private static dictionarytype dictionarytype conversioncache types new dictionarytype dictionarytype conversioncache summary try parsing summary param namesparam param namevalueparam returnsreturns public static bool tryparse icomparable s ref icomparable value first get the cached conversion method dictionarytype conversioncache type1cache null conversioncache type2cache null if typescontainskey sgettype type1cache new dictionarytype conversioncache typesadd sgettype type1cache else type1cache typessgettype if type1cachecontainskey valuegettype we havent converted this type before so create a new conversion type2cache new conversioncache sgettype valuegettype add to the cache type1cacheadd valuegettype type2cache else type2cache type1cachevaluegettype attempt the parse return type2cachetryparse s ref value summary stores the method to convert from type1 to type2 summary internal class conversioncache internal bool tryparse icomparable s ref icomparable value if this method null invoke the cached tryparse method object parameters new object s value bool result boolthis methodinvoke null parameters if result value parameters1 as icomparable return result else return false private methodinfo method internal conversioncache type type1 type type2 use reflection to get the tryparse method from it this method type2getmethod tryparse new type type1 type2makebyreftype,['c#'] +43316,is there a way using templates to prevent a class from being derivable in c i need to prevent a class from being derived from so i thought to myself this is something that boost is bound to have already done i know they have a noncopyable they must have a nonderivableimagine my surprise when i could not find itthat got me thinking there must be a reason maybe it is not possible to do using templatesi am sure if it was easy it is be in the boost librariesi know how to do it without using templates ie using a base class with a private constructor ieclass thatcantbederived forward referenceclass nonderiv nonderiv friend class thatcantbederivedclass thatcantbederived virtual public nonderivpublic thatcantbederived nonderiv or something like thismaybe it is the forward reference that causes the problem or maybe there is not a portable way to achieve iteither way i am not sure why it is not in boostany ideas,['c++'] +43317,how can a do a greatestnpergroup query in django this is the django version of the thread at suppose i have a table of customers and a table of purchases each purchase belongs to one customer i want to get a list of all customers along with their last purchase can it be done without raw sql and without multiple database queries,['sql'] +43328,how to stop endless ejb 3 timer i am new to ejb 3 i use the following code to start endless ejb 3 timer then deploying it on jboss 423statelesspublic class simplebean implements simplebeanremotetimerservice resourcetimerservice timerserviceprivate timer timer timeoutpublic void timeouttimer timer systemoutprintlnhello ejb then calling it timer timerservicecreatetimer10 50 nullit works well i created a client class that calls a method that creates the timer and a method that is called when the timer times outi forget to call cancel then it does not stop redeploy with cancel call never stop it restart jboss 423 never stop it how i can stop ejb timer thanks for helping,['java'] +43336,css style visibility not behaving as expected i have a html page with a basic tab control i use javascript to show and hide tabs and tab content divs my problem is that if i change the visibility of an element inside one of the tab content divs to hidden then back to visible the element seems to forget or lose its parent div container and remains visible regardless of its original parents visibilityto illustrate take the following exampledoctype html public w3cdtd html 401 transitionalen htmlheadscript typetextjavascript function hidetab documentgetelementbyidtab1stylevisibility hidden function showtab documentgetelementbyidtab1stylevisibility visible function hidecontent documentgetelementbyidtc1stylevisibility hidden function showcontent documentgetelementbyidtc1stylevisibility visible scriptheadbody a hrefjavascript hidetabhide tababr a hrefjavascript showtabshow tababr a hrefjavascript hidecontenthide contentabr a hrefjavascript showcontentshow contentabr br div idtab1 stylebackgroundyellowwidth100px div idtc1content textdiv divbodyhtmlin ie8 click hide tab then show tab this works ok with the tab shown click hide content then show content this is also correct now click hide tab again and you should see the tab thisappear but the content incorrectly remainsin ie8 the problem thisappears when i use compatibility mode also i have noticed that if i remove doctype element i cannot replicate the problemin chrome my personal favourite the problem is persistent regardless of the doctype element i have not tried this in firefoxi am sure there is a very good reason for this behaviour i am also sure that there will be a simple solution for me to make my tabs work correctly i look forward to your comments,"['javascript', 'css']" +43337,how do i fix pydev method should have self as first parameter errors i am developing in python using pydev in eclipse and some of my code generates errors in the code analysis tool specificallyclass groupobject def keyself k class subkeyobject def enter s self settingsbegingroupk return self def exit s type value tb self settingsendgroup return subkeygives me a method enter group should have self as first parameter error and a similar error for exit is there a way to solve this without assigning self to another variable and reusing the variable in the other method signatures,['python'] +43341,faster app engine development datastore alternative is there a way to use a real databasesqlite mysql or even some nonrelational one as datastore for development instead of memoryfile datastore that is providedi saw few projects gaesqlitedid not seem to be working and one tip about accessing production datastore using remote api still pretty slow for large datasets,['python'] +43344,what security considerations concerns should be addressed when using cdn hosted code working on a major financial companys website we tend to shy away from using the cdnhosted versions of the jquery library used throughout our site because of security concernsi am assuming although i have never had it fully explained that these concerns relate to potential physical security threats through the risk of code being compromised on googles or microsofts servers reputation risks through those cdn networks becoming unavailable thereby rendering the functionality on our site useless and any other inherent risks that might arise from these situationsmy question is how valid are these sorts of security concerns and what might be done to mitigate any security risks found on cdnhosted networks,['jquery'] +43346,how to read unicode utf8 binary file line by line hi programmersi want read line by line a unicode utf8 text file created by notepad i do not want thisplay the unicode string in the screen i want just read and compare the stringsthis code read ansi file line by line and compare the stringswhat i wantread test ansitxt line by lineif the line b print yeselse print noread ansi line by linecinclude stdiohint main char inname test ansitxt file infile char line bufferbufsiz bufsiz is defined if you include stdioh char line number infile fopeninname r if infile printfnfile s not foundn inname return 0 printfnsnn inname line number 0 while fgetsline buffer sizeofline buffer infile line number note that the newline is in the buffer if strcmpbn line buffer 0 printfd yesn line number else printfd non line numberline buffer printfnntotal dn line number return 0test ansitxtabccompilinggcc o read ansi line by line read ansi line by linecoutputtest ansitxt1 no2 yes3 nototal 3now i need read unicode utf8 file created by notepad after more than 6 months i do not found any good codelibrary in c can read file coded in utf8 i do not know exactly why but i think the standard c do not support unicodereading unicode binary file its ok but the probleme is the binary file most be already created in binary mode that mean if we want read a unicode utf8 file created by notepad we need to translate it from utf8 file to binary filethis code write unicode string to a binary file note the c file is coded in utf8 and compiled by gccwhat i wantwrite the unicode char to test bindatcreate bincdefine unicodeifdef unicodedefine unicodeelsedefine mbcsendifinclude stdiohinclude wcharhint main data to be stored in file wchar t line bufferbufsizl opening file for writing in binary mode file infilefopentest bindatwb writing data to file fwriteline buffer 1 13 infile closing file fcloseinfile return 0compilinggcc o create bin create bincoutputcreate test bindatnow i want read the binary file line by line and comparewhat i wantread test bindat line by lineif the line print yeselse print noread bin line by linecdefine unicodeifdef unicodedefine unicodeelsedefine mbcsendifinclude stdiohinclude wcharhint main wchar t inname ltest bindat file infile wchar t line bufferbufsiz bufsiz is defined if you include stdioh infile wfopeninnamelrb if infile wprintflnfile s not foundn inname return 0 wprintflnsnn inname reading data from file into temporary buffer while freadline buffer113infile note that the newline is in the buffer if wcscmp l line buffer 0 wprintflyesn else wprintflnon line buffer closing file fcloseinfile return 0outputtest bindatyesthe problemthis method is very long and not powerful i m beginner in software engineeringplease any one know how to read unicode file i know its not easyplease any one know how to convert unicode file to binary file simple methodplease any one know how to read unicode file in binary mode i m not surethank you,['c'] +43349,baffled by java logging systems with spring and hibernate when deploying my spring hibernate application i get the following warning related to logginglog4jwarn no appenders could be found for logger orgspringframeworkwebcontextcontextloaderlog4jwarn please initialize the log4j system properlysurprising to me was the lack of information from a google so search the only thing relevant was this so post however this is even beyond me can somebody clarify the logging systems in play here or point me to a recent resource on the matter there are some ancient google search results that do not really apply specifically the issues i am wrestling with arethe thistinction among commonslogging log4j slf4j and jcl my understanding is that slf4j is a wrapper while commonslogging and log4j are actual implementations i do not know where jcl fits in how to configure logging for spring what does in the webxml file do i need a log4jproperties file or a log4jxml file where does it go in webinf does anything go in my applicationcontextxml file sorry but i need to start from zero here i am using hibernate in my project and including via maven it seems that hibernate uses slf4jsimple i have seen warnings saying that i cannot have slf4jsimple and slf4jlog4j both on the classpath i have not included slf4jlog4j as a dependency but hibernate must be including it how do i solve this problem can i force hibernate to use log4j insteadany help would be greatly appreciated thanks editthanks for all the answers so far i am giving these suggestions a try what about spring webapp specifically i have seen examples of listeners and parameters and whatnot put into the webxml file is this also required,['java'] +43355,objectivec how to fetch the router address i tried to fetch the router address this way nsstring routerip nsstring address error struct ifaddrs interfaces null struct ifaddrs temp addr null int success 0 retrieve the current interfaces returns 0 on success success getifaddrsinterfaces if success 0 loop through linked list of interfaces temp addr interfaces whiletemp addr null iftemp addrifa addrsa family af inet check if interface is en0 which is the wifi connection on the iphone ifnsstring stringwithutf8stringtemp addrifa name isequaltostringen0 get nsstring from c string ifa addr address nsstring stringwithutf8stringinet ntoastruct sockaddr in temp addrifa dstaddrsin addr temp addr temp addrifa next free memory freeifaddrsinterfaces return addressthe router address always looks like x255255 but it is supposed to look like x01 or something this wayis there anything to do to get the valid addressthanks for your help,"['iphone', 'objective-c']" +43365,compare given date with today i have followingvar 20100121 0i would like to compare this date against todays date ie i would like to know if this var is before today or equals today or notwhat function would i need to use,['php'] +43366,how to send keystrokes to a window im using keybd event and i want use sendmessage to send keystroke to notepad can this be done,['c++'] +43367,viewexpiredexception jsf to handle viewexpiredexception in jsf i codederrorpage exceptiontypejavaxfacesapplicationviewexpiredexceptionexceptiontype locationerrorhtmllocationerrorpagesessionconfig sessiontimeout1sessiontimeoutsessionconfigin webxmlin errorhtml i have redirected to original login page but the problem is session scoped bean were not cleared out even session expired is there any way to solve this,['java'] +43368,good practices for writing html in javascript i was wondering about this if people have strong opinions about the best way to generate html on the fly especially with ajax based applicationsdo you just create the html code using server side scripting and then send it out to the page or perhaps just return a json string and let javascript do the job in my personal opinion the first way ties the presentation layer way too much to the logic and makes it harder to change and a nightmare to maintain the second way although is my preferred method also becomes a nightmare to maintain when the complexity of the project grows i was thinking of using a javascript templating system as another layer just to make the code more robust and less rigid anyone has good ideas of a light and really good js templating system,"['javascript', 'html']" +43379,in an android listview how can i iteratemanipulte all the child views not just the visible ones the code below does not change the text of all of a listviews rows because getchildcount does not get all of a listviews rows but just the rows that are visible for int i 0 i listviewgetchildcount i view v listviewgetchildati textview tx textview vfindviewbyidridmytext txsettextsizenewtextsizeso what should i do is there code for getting a notification when a listviews row becomes visible so i can set its text size then,['android'] +43387,which style is preferred option 1def f1c d usa ny china shanghai if c in d return dc return naoption 2def f2c d usa ny china shanghai try return dc except return naso that i can then callfor c in china japan for f in f1 f2 print s s c fcthe options are to either determine whether the key is in directory before hand f1 or just fallback to the exception f2 which one is preferred why,['python'] +43407,what is the deal with the pony in python community pony references are in several placesis there a cultural reference that i am missing what is the deal with ponies,['python'] +43408,does python have a module for parsing http requests and responses httplib now httpclient and friends all have conngetresponse and an httpresponse class but the serverside operations of conngetrequest and an httprequest class seem to be lackingi understand that basehttpserver and basehttprequesthandler can perform this functionality but they do not expose these methods for use outside of the moduleessentially what i want is basehttprequesthandlerparse request to be a static method that returns an httprequest object rather than populating member variables,['python'] +43420,stl multimap removeerase values hii have stl multimap i want to remove entries from the map which has specific value i do not want to remove entire key as that key may be mapping to other values which are requiredany help please,['c++'] +43421,design pattern for a database application that must work thisconnected i have to design an application is mostly an interface with a database for data entry the application must be able to work while it is thisconnected from the database with cached data and insert that data when it has connection again there will be two different modes connected or thisconnected no need to detect thisconnection in the middle of a connected session to switch to thisconnectedas this seems to me a common requisite i was wondering if there is a standard approach to face this problem caching tables to local file serializing the data queried to the database or whatever maybe there is an existent library for doing thatthanks in advancepd the application will be done in netedit is a winforms application not a web oneedit2 to enter more detail about the application it is to enter data at one database but sometimes users will be out of office several weeks and will need to enter data as if they were connected with cached data from the database and this data entered will be transfered to the database when they reconnect again,['.net'] +43428,is it possible to reload log4jxml log4jproperties file dynamically in tomcat the problem is whenever you change the log4jpropertieslog4jxml you need to restart the tomcat or say any other server is there any workaround of reloading the log4j configuration,['java'] +43443,logging to a file on android is there any way of retrieving log messages from an android handseti am building an application which uses the gps of my htc hero i can run and debug the application from eclipse but this is not a good use case of gps sat at my deskwhen i fire the app up when i am walking around i get an intermittent exception is there anyway i can output these exceptions to a text file on the sd card or output calls to logx to a text file so that i can see what the exception isthanksedit solutionhere is the code i finally went withthreadcurrentthreadsetuncaughtexceptionhandlernew threaduncaughtexceptionhandler override public void uncaughtexceptionthread thread throwable ex printwriter pw try pw new printwriter new filewriterenvironmentgetexternalstoragedirectoryrtlog true exprintstacktracepw pwflush pwclose catch ioexception e eprintstacktrace i had to wrap the line pw new printwriternew filewriterenvironmentgetexternalstoragedirectoryrtlog truein a trycatch as eclipse would not let me compile the app it kept saying unhandled exception type ioexception1 quick fix sorround with trycatchso i did and it all works which is fine by me but it does make me wonder what eclipse was on about,['android'] +43447,extracting text from pdfs in c pretty simply i need to rip text out of multiple pdfs quite a lot actually in order to analyse the contents before sticking it in an sql databasei have found some pretty sketchy free c libraries that sort of work the best one uses itextsharp but there are umpteen formatting errors and some characters are scrambled and alot of the time there are spaces everywhere inside words between every letter huge blocks of them taking up several lines it all seems a bit randomis there any easy way of doing this that i am completely overlooking quite likely or is it a bit of an arduous task that involves converting the extracted byte values into letters reliablycheersduncan,['c#'] +43449,difference of two date time in sql server is there any way to take the difference between two datetime in sql serverfor example my dates are20100122 15295509020100122 153009153so the result should be 14063 seconds,['sql'] +43456,how can i call a gwt rpc method on a server from a non gwt but java gapplication i have a regular java application and want to access an gwt rpc endpoint any idea how to make this happen my gwt application is on a gaej and i could use rest for example but i already have the gwt rpc endpoints and do not want to build another fadeyes i have seen but this thiscussion goes into a different direction,['java'] +43467,how to custom format data in datagridview during databinding i am looking for a way to format datagridviewtextboxcolumn so that the value to be databinded is formatted during databinding for example i have a companyname property and i need to take first 5 letters from the companyname when databinding happensi could hook on different datagridview events eg rowsadded and loop through all the rows and do the trick but i would like to find more sophisticated way to do this since i have decided to use databinding looping through data and modifying it is a bit against the databinding conceptwhat i am after is how to do the same as below but add custom formatting logicdatagridview1columnscolsomedateindexdatapropertyname somedatecolsomedatedefaultcellstyleformat yi think i should implement iformatprovider but i do not quite understand how i should implement itdatagridview1columnscompanynameindexdatapropertyname companynamecompanynamedefaultcellstyleformatprovider new shorttext shorttext should implement iformatprovider,['c#'] +43469,how to change font size in a textbox in html how can i change the font size of text inside the textbox in html,['html'] +43470,set maximum thisplayed rows count for html table have jsp page with dynamically generated html table with unknown number of rowshave property on backend that sets maximum number of rows eg max rows15how to limit number of rows for html table to max rows valueother part of table should be accessible by vertical scrollit means that user see 15 rows and if to scroll down that it will be seen other rows of tableit can be done empirically by calculating average height of row and using maxheight property for divwrapper but i think this approach is not very stableso it is needed to rely on row countperhaps there is plugin for such case or it is standard css or html solutionthank you for advise,['html'] +43473,how to insert uiimage into uitextview im working on a editable notebook type project it consists some text and images at any timein uitextview if we add images as subview the frames are fixed but i have editable option so i must save image as nsstring format in uitextview but it should look image type in uipart so please suggest me how can i handle this requierment thanks in advance,"['iphone', 'objective-c']" +43483,page unload event in aspnet is it possible to call a write a page unload event in code behind similar to page load event i wanted to call a method on page unload how do i achieve that,['asp.net'] +43488,stripping out all characters from a string leaving numbers hay i have a string like thisv8gn58gnr4nggb58gngg95h58gn48fn49tt8t8t57i want to strip out all the characters leaving just numbers and sany ideas how to do this is there a function prebuiltthanks,['php'] +43491,what are the things to know when diving into multithreaded programming in c i am currently working on a wireless networking application in c and it is coming to a point where i am going to want to multithread pieces of software under one process rather than have them all in separate processes theoretically i understand multithreading but i have yet to dive in practically what should every programmer know when writing multithreaded code in c,['c++'] +43495,nsxmlparser memory allocation efficiency for the iphone i have recently been playing with code for an iphone app to parse xml sticking to cocoa i decided to go with the nsxmlparser class the app will be responsible for parsing 10 computers all which contain 6 other strings of information for my test i have verified that the xml is around 900k1mb in sizemy data model is to keep each computer in an nsdictionary hashed by a unique identifier each computer is also represented by a nsdictionary with the information so at the end of the day i end up with a nsdictionary containing 10k other nsdictionariesthe problem i am running into is not about leaking memory or efficient data structure storage when my parser is done the total amount of allocated objects only does go up by about 1mb the problem is that while the nsxmlparser is running my object allocation is jumping up as much as 13mb i could understand 2 one for the object i am creating and one for the raw nsdata plus a little room to work but 13 seems a bit high i cannot imaging that nsxmlparser is that inefficient thoughtscodethe code to start parsingnsxmlparser parser nsxmlparser alloc initwithdata dataparser setdelegatedictparserparser parseoutput dictparser returndictionary retain parser releasedictparser releaseand the parsers delegate codevoidparsernsxmlparser parser didstartelementnsstring elementname namespaceurinsstring namespaceuri qualifiednamensstring qualifiedname attributesnsdictionary attributedict ifmutablestring mutablestring release mutablestring nil mutablestring nsmutablestring alloc init voidparsernsxmlparser parser foundcharactersnsstring string ifselfmutablestring selfmutablestring appendstringstring voidparsernsxmlparser parser didendelementnsstring elementname namespaceurinsstring namespaceuri qualifiednamensstring qname ifelementname isequaltostringsize the initial key tells me how many computers returndictionary nsmutabledictionary alloc initwithcapacitymutablestring intvalue ifelementname isequaltostringhashby the unique identifier ifmutabledictionary mutabledictionary release mutabledictionary nil mutabledictionary nsmutabledictionary alloc initwithcapacity6 returndictionary setobjectnsdictionary dictionarywithdictionarymutabledictionary forkeynsmutablestring stringwithstringmutablestring iffields containsobjectelementname any of the elements from a single computer that i am looking for mutabledictionary setobjectmutablestring forkeyelementnameeverything initialized and released correctly again i am not getting errors or leaking just inefficientthanks for any thoughts,['iphone'] +43497,difference between a jquery plugin and a jquery widget can someone concisely explain the differences between jquery plugins and jquery ui widgets what are the conceptual differences why would i choose one over the other and what pros and cons are there for each what are the differences in the intention and concept for eachi have written both but i am not clear on the nitty gritty differentiations i want to make sure i am choosing appropriately in each casethanks,['jquery'] +43501,set the same default background of the uitableview to a custom view controller i need to set the same gray stripped background to another viewcan anyone help me on this onethanksleonardo,['iphone'] +43502,how to remove null datamember properties from the response in wcf i am returning the xml output to the browser with a wcf webservice if a property of a datacontract is null it still comes through in the response asid iniltrue is there a way to have it not return in the response at all,['.net'] +43509,android getting audio to play through earpiece i currently have code that reads a recording in from the devices mic using the audiorecord class and then playing it back out using the audiotrack classmy problem is that when i play it out it plays via the speaker phonei want it to play out via the ear piece on the devicehere is my codepublic class loopprog extends activity boolean isrecording currently not used audiomanager am int count 0 called when the activity is first created override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain am audiomanager getsystemservicecontextaudio service amsetmicrophonemutetrue whilecount 10 record record new record recordrun count logdcount count is count public class record extends thread static final int buffersize 20 final short buffer new shortbuffersize short readbuffer new shortbuffersize public void run isrecording true androidosprocesetthreadpriorityandroidosprocessthread priority urgent audio int buffersize audiorecordgetminbuffersize11025 audioformatchannel configuration mono audioformatencoding pcm 16bit audiorecord arec new audiorecordmediarecorderaudiosourcemic 11025 audioformatchannel configuration mono audioformatencoding pcm 16bit buffersize audiotrack atrack new audiotrackaudiomanagerstream music 11025 audioformatchannel configuration mono audioformatencoding pcm 16bit buffersize audiotrackmode stream amsetroutingaudiomanagermode normal1 audiomanagerstream music int ok amgetroutingaudiomanagerroute earpiece logdrouting getrouting ok setvolumecontrolstreamaudiomanagerstream voice call amsetspeakerphoneontrue logdspeakerphone is speakerphone on amisspeakerphoneon amsetspeakerphoneonfalse logdspeakerphone is speakerphone on amisspeakerphoneon atracksetplaybackrate11025 byte buffer new bytebuffersize arecstartrecording atrackplay whileisrecording arecreadbuffer 0 buffersize atrackwritebuffer 0 bufferlength arecstop atrackstop isrecording false as you can see if the code i have tried using the audiomanager class and its methods including the deprecated setrouting method and nothing works the setspeakerphoneon method seems to have no effect at all neither does the routing methodhas anyone got any ideas on how to get it to play via the earpiece instead of the spaker phone,['android'] +43517,setattribute is not working for style attribute on ie i am porting a piece of js code written for firefox into internet explorer i faced a problem of changing style of an element using setattribute method which was working on firefoxbuttonsetattributestyle float righti tried setting the style member of button and it did not work either this was the solution in case of setting onclick event handlerbuttonstyle float rightfirst i wanna know the solution for the above problem andsecond are there any maintained lists for these differences between browsers,"['javascript', 'html']" +43528,best way to split and convert url params into string values i would like to split a custom url for app opening in iphone into values my scheme would be something likeappnameuserjonsmithmessageblah20blahwhere i would like to be able to get user and message as two nsstrings any advice on best approach,"['iphone', 'objective-c']" +43554,tool for creating net wrappers for a com dll is there any open source tool for automatically generating net wrappers for a com dll library,"['c#', '.net']" +43563,wcf deserialize enum as string i am trying to consume a restful web service using wcf i have no control over the format of the web service so i have to make a few workarounds here and there one major problem i cannot seem to get around however is how to make wcf deserialize an enum as a stringthis is my code names changed obviouslydatacontractpublic enum foo enummember value bar bar enummember value baz bazdatacontractpublic class unameit datamember name id public long id get private set datamember name name public string name get private set datamember name foo public foo foo get private set and this is the returned data that fails deserialization id123456 namejohn doe foobarfinally the exception thrownthere was an error deserializing the object of type servicefoo the value bar cannot be parsed as the type int64i do not want to switch to using the xmlserializer because among its many other shortcomings it would not let me have private setters on propertieshow do i make wcf or well the datacontractserializer treat my enum as string valuesedit doing this seems to be impossible and the behavior is the way it is by design thank you microsoft for not giving us options having to resort to hacks doing it the way somori suggests seems to be the only way to get string enums with json and wcf,"['c#', '.net']" +43564,how to select multiple fields in the same row mysql i asked a question yesterday about using mysql to tally results to a surveynow my question is if i had a table of survey questions a table of survey choices and a table of users answers to those survey questions how would i select the survey question along with all the choices for that survey within the same queryquestions tablequestion id intquestion textchoices tablechoice id intquestion id intchoice text varcharanswers tableanswer id intquestion id intchoice id intwhat select should i do to get the survey question along with all the choices for that survey known or unknown amount all in the same query if possible also do the math found in my other question within the same queryi am not so advanced with mysqlthanksedit sorry what i meant was i am trying to get a select statement to select the question and all the choices corresponding to that question in one rowif i do something likeselect question id question choice id choice text from questions left join choices usingquestion idi get multiple rows one for each choice id the results should be something likequestion choice 1 choice 2 choice 3a or b or c a b cthe math part is tallying up the results to the survey and yes the choice id is a pk if that helps,"['php', 'mysql']" +43572,how to generate json from a jersey resource i am using jersey and want to output the following json with only the fields listed name holidays value en40holidaycalendargooglecompublicbasic name personal value if i must i can surround that json with feeds but having this be optional would be best i want to pull this information from a list of calendarfeeds that are stored in a member pojo that is retrieved via hibernate here are the simplified pojospublic class member private string username private string password private setcalendarfeed calendarfeeds new hashsetcalendarfeedpublic class calendarfeed public enum feedtype gcal event private member owner private string name private string value private feedtype typecurrently i have got a jersey resource called calendarresource that manually outputs json with the calendar feeds informationpathcalendarspublic class calendarresource injectmemberservice private memberservice memberservice get producesmediatypeapplication json public string getcalendars get currently logged in member member member memberservicegetcurrentmember stringbuilder out new stringbuilder boolean first true for calendarfeed feed membergetpersongetcalendarfeeds if first outappend outappend outappendfeedgetname outappend outappendfeedgetvalue outappend first false outappend return outtostring but i am not sure how to go about automating this i am just starting to use jersey and am not clear on how to use it to return json it sounds like it has a way to do this built in but it looks like i need to add annotations to my pojos also i read others saying that i need to use jackson i have been googling and cannot seem to locate a good and simple example of returning json from a jersey resource anyone know of any or can you show me how to use jackson or jersey to create json for for the above example,['java'] +43577,is there a standard for documenting getpost parameters in a php project even when front controller logic is used for the main application there can be many standalone scripts ajax snippets and so onis there a standardized way either phpdoc or something else to define in the first comment block of the script what get andor post parameters the script will accept require and of which type they arei usually help myself by just adding params as if the file were a function and a return explanation for what the script does and returns but maybe there is a more specialized way i do not know of,['php'] +43583,storing objects in columns using hibernate jpa is it possible to store something like the following using only one table right now what hibernate will do is create two tables one for families and one for people i would like for the familymembers object to be serialized into the column in the databaseentityname familyclass family private final listperson familymembersclass person string firstname lastname int age,['java'] +43585,call instance method from class method so i need to call some instance methods from class methods in objecitvecexample idbarwithfoonsfoo self foo raises compiler warning voidfoo cool stuffso my question stackoverflow is how do you do such things in objectivec i am new kinda to oop so am i mad or is there a way to do this,['objective-c'] +43589,notification of or detecting screenshot being taken is there a notification or other mechanism of being informed that the user is taking a screenshot with the homepower buttonsi have seen threads about wanting to thisable the taking of screenshots but that is not what i am looking to doi have a photographer client whos concerned that his works will be copied by means of users taking screenshots and i thought that if there was an opportunity to put a watermark across the image before the screenshot was taken that would allay his fears,['iphone'] +43604,using do block vs brackets new to ruby put on your newbie glovesis there any difference obscure or practical between the following two snippetsmy array uno dos tresmy arrayeach item puts itemmy array uno dos tresmy arrayeach do item puts itemendi realize the bracket syntax would allow you to place the block on one linemy arrayeach item puts item but outside of that are there any compelling reasons to use one syntax over the other,['ruby'] +43606,file download using java struts 2 and ajax i want to give file download using javastruts2 and ajaxon my html page there is a button called export clicking on which ajax call will be made which will execute a query and will create xls file using code and i want to give that file for download to user without storing it on hard drivedoes any one know how to do that using struts2 and ajax in javais there any example availablelet me know if you need more details from methanksamar4kintu,['java'] +43617,is it better to handle friendlycleanpretty urls with mod rewrite or a language like php i am developing my first decentsized php site and i am a bit confused about what the right way assuming there ever is such a thing to handle cleanfriendlypretty urls in the applicationthe way i see it there are two main options i will use a simplified social news site as an example1 use mod rewrite to handle all potential urls this would look similar but not identical to the following rewriterule article contentarticlesphparticleid1slug2rewriterule users contentusersphpuserid1username2rewriterule search contentsearchphpquery12 pass everything to some handler script and let it worry about the details rewritecond request filename frewritecond request filename drewriterule handlerphpcontent1clearly this is all untested air code but you get the point is one of these two ways going to be seriously slower than the other presumably the mod rewrite is slower since i will be forced to use htaccess files for thisare there serious thisadvantages to either of these approaches is there a best practice for this sort of thing or is it something that each developer tends to decide for themselves i know wordpress uses option two though it was more trouble than it was worth when i investigated exactly how they did it,['php'] +43636,are object files platform independent is it possible to compile program on one platform and link with other what does object file contain can we delink an executable to produce object file,"['c++', 'c']" +43641,slow down scroll to top event by jquery animate i would like my page to go to the top when certain anchor is clicked here is how i tried to do it but it is not working it is scrolling super fast ahreftopclickfunction bodyanimate scrolltop 0 50i want to slow it down,"['javascript', 'jquery']" +43646,opengl gl line smooth not supported on all cards wont even draw the lines unless first of all whats the purpose of this codeglhintgl line smooth hint gl nicesti could put there gl dont care but it doesnt make my lines drawn unless i use glthisablegl line smooth so im asking if theres some built in mechanism to make it draw the lines even if the smooth lines arent supported so it would draw them without antialisingor do i have to make own functions for it and checking if smooth lines are supported etc and every time i want to draw smooth lines i need to call this function that checks whether or not its supported arghedit the lines are smooth on my other card on my other card they dont even show up unless i thisable smooth lines so that is the problem not glenablegl blend,['c++'] +43651,how do i implement interfaces in python public interface iinterface void show public class myclass iinterface region iinterface members public void show consolewritelinehello world endregionhow do i implement python equivalent of this c code class iinterfaceobject def init self pass def showself raise exceptionnotimplementedexceptionclass myclassiinterface def init self iinterface init self def showself print hello worldis this a good idea please give examples in your answers,"['c#', 'python']" +43658,what is the proper pinvoke signature for a function that takes var args there is a native functionint sqlite3 configint i would like to pinvoke to this function currently i have this declarationdllimportsqlite3 entrypoint sqlite3 configpublic static extern result config configoption optionresult and configoption are enums of the form enum result int i am actually only interested in the single parameter version of this function and do not need the other args is this correcti am also curious as to how you would declare the two argument form perhaps it would take 2 intptrs,['.net'] +43663,segmentation fault ocurring when modifying a string using pointers contexti am learning c and i am trying to reverse a string in place using pointers i know you can use an array this is more about learning about pointersproblemi keep getting segmentation faults when trying to run the code below gcc seems not to like the end begin line why is thatespecially since my code is nearly identical to the nonevil c function already thiscussed in another questioninclude stdiohinclude stringhvoid my strrevchar begin char temp char end end begin strlenbegin 1 whileendbegin temp end end begin begin temp end begin main char string foobar my strrevstring printfs string,['c'] +43665,learning web programming i am an oop programmer and have been it for almost two years now i know java and c what i donat know is web programming i know what html is but have never really worked with it what is the best way to get started with web programminghtml css javascript php aspnet what should i start withthe reason i want to learn web programming is mostly because everyone knows how to do it so as a software student i should too friends often ask if i can do a webpage for them but i donat even know where to start which annoys mehow hardeasy will the transition be,['html'] +43674,how can i see error logs of django views i am coding a small application with django but i cannot see any error logs in the console when an error eg python syntax error etc occurs in one of my views no action at allhow can i see the error logs of my views debugging like a blind is really annoying,['python'] +43685,activerecord has many where two columns in table a are primary keys in table b i have a model couple which has two columns first person id and second person id and another model person whose primary key is person id and has the column nameheres the usage i wantincluding person model for eager loading this is crucial for mec couplefindall include persons0puts cfirst personname and csecond personnameso how can i do this,"['ruby-on-rails', 'ruby']" +43687,getting the current type in a static generic method i have got an abstract class like thispublic abstract propertybase public static systemtype getmytype return some magic here i would like to subclass it and when i call the static getmytype i would like to return the subclas type so if i declare a subtypepublic class concreteproperty propertybase then when i callvar typename concretepropertygetmytypenamei expect typename to be set to concreteproperty i suspect there is no way to do it but i am interested if anyone out there knows a way to get this infothe particular problem i am trying to solve is the verbosity of dependency properties in wpf i would love to be able to do something like thisclass namedobject dependencyobject declare a name property as a type not an instance private class nameproperty propertybasestring namedobject call static methods on the class to read the property public string name get return namepropertygetthis set namepropertysetthis value and i almost have an implementation but i cannot quite get the info i need out of my nameproperty class,['c#'] +43691,must read articles for c memory mangement after reading c memory management from fear to triumph series i think they are mustread articles for memory management i would like to know what else mustread articles i should not missthanks,['c++'] +43696,converting a float to stdstring in c this is a seemingly simple problem but i am having difficulty coming up with an answer i have a float value that needs to be put into a stdstring like sofloat val 25stdstring my val val error hereobviously they are of different types how do i convert from float to stringall help is appreciated,['c++'] +43727,aspnet mvc viewengine viewlocationcachegetviewlocation returns null i am following chris pietschmanns solution for theming in aspnet mvcone thing i have noticed is that the view name is not being retrieved from the viewlocationcache on subsequent requests i am using aspnet mvc 20 rcwhen the following code is executedthisviewlocationcacheinsertviewlocationcontrollercontexthttpcontext cachekey virtualpathand i hover over thisviewlocationcache it just returns systemwebmvcnullviewlocationcache suggesting nothing was added,['asp.net'] +43731,double not operator in php what does the double not operator do in phpfor examplereturn rowwhat would the code above do,['php'] +43733,cc bitfields versus bitwise operators to single out bits which is faster better more portable i need to pack some bits in a byte in this fashion struct char bit0 1 char bit1 1 a if abit1 etc orif a 0x2 etc from the source code clarity it is pretty obvious to me that bitfields are neater but which option is faster i know the speed difference would not be too much if any but as i can use any of them if ones faster betteron the other hand i have read that bitfields are not guaranteed to arrange bits in the same order across platforms and i want my code to be portablenotes if you plan to answer profile ok i will but as i am lazy if someone already has the answer much betterthe code may be wrong you can correct me if you want but remember what the point to this question is and please try and answer it too,"['c++', 'c']" +43738,how to log an long long value with nslog how can i do that whats the format specifierfor example i havelong long verylong assume value herenslogf verylong of course wrong,['iphone'] +43740,can anyone explain this algorithm for calculating large factorials i came across the following program for calculating large factorialsnumbers as big as 100 can anyone explain me the basic idea used in this algorithmi need to know just the mathematics implemented in calculating the factorialinclude cmathinclude iostreaminclude cstdlibusing namespace stdint main unsigned int d unsigned char a unsigned int j n q z t int iarr101f double p cinn p 00 forj 2 j n j p log10j d intp 1 a new unsigned chard for i 1 i d i ai 0 initialize a0 1 p 00 for j 2 j n j q 0 p log10j z intp 1 for i 0 i znumdigits i t ai j q q t 10 ai chart 10 for i d 1 i 0 i cout intai coutn delete areturn 0,['c++'] +43747,ruby on rails storing application configuration i have a relatively simple rails app and i would like to store various configuration settings that administrator users can change whilst the application is running for example allowing comments on posts or changing the thisplay format of the datei know i can store constants etc in the environmentrb file however these appear to be loaded only when the server is restartedis there an alternative place i can define this information or would it be better to keep it in the databaseany advice appreciatedthanks,['ruby-on-rails'] +43757,how do i count occurrences by day in sql newbie sql question here i have got an occurrences table that contains a row for each time a user did something a user can do the thing multiple times per day it looks like thisdate username 119 user19 user19 user2129 user1129 user3139 user1139 user1139 user1139 user2139 user3i want a query to simply return the username and the quantity count of unique days they appear for the above data set the result i am looking for would beusername uniquedaysappeared user1 3user2 2user3 2i keep getting screwed up because my query is returning not the count of unique days per user but rather the number of occurrences of the user overall,['sql'] +43767,how to create timer in winapi c how to create timer in winapi c,['c++'] +43780,view the default functions generated by a compiler is there any way to view the default functions eg default copy constructor default assignment operator generated by a compiler such as vc2008 for a class which does not define them,['c++'] +43781,cout order of call to functions it prints the following codemyqueueenqueueamyqueueenqueuebcout myqueuedequeue myqueuedequeueprints ba to the consolewhilemyqueueenqueueamyqueueenqueuebcout myqueuedequeuecout myqueuedequeueprints ab why is thisit seems as though cout is calling the outermost closest to the function first and working its way in is that the way it behaves,['c++'] +43794,how can i set up celery to call a custom initialization function before running my tasks i have a django project and i am trying to use celery to submit tasks for background processing celery integrates well with django and i have been able to submit my custom tasks and get back resultsthe only problem is that i cannot find a sane way of performing custom initialization in the daemon process i need to call an expensive function that loads a lot of memory before i start processing the tasks and i cannot afford to call that function every timehas anyone had this problem before any ideas how to work around it without modifying the celery source codethanks,['python'] +43803,java subclassing a genericised class i have a genericised class that i wish to subclass as followspublic class sometablet extends basetableentry extends basetablet public sometableint rows int cols superrows cols sometableentryclass does not compile cannot find symbol constructor basetableint int javalangclassblahblahsometableentryclass where the genericised superclass ispublic class basetablet extends basetableentry public basetableint rows int cols classt clasz i understand the compiler error but cannot seem to find a workaround other than to include an extra parameter in the sometable constructorany suggestionsthanks,['java'] +43819,what are crossbrowser cross platfom web safe fonts how to make cross browser cross platform and all devices compatible css font stack,['css'] +43830,jqgrid sorting on client side i have a treegrid with autoloading rows the goal is to sort the grid by tree column right on client sidebut each time i click on sort column header it issues an ajax call for sorting but all i need is onplace sorting using the local datado i have incorrect grid parameters or does not tree work with clientside sorting on tree columncurrent jqgrid params for sorting are areloadonce true to enable sorting on client sidesortable true to enable sorting,"['javascript', 'jquery']" +43844,how to remove application shortcut from home screen on uninstall automaticaly i am developing an application that should add it is shortcut to home screen after installation and remove it after the application is being uninstalled the application will be preinstalled on the end user device but still should have an option for uninstall the task looks very simple but i have faced lots of troubles implementing itwhat i have doneadd shortcut to the home screen usingcomandroidlauncheractioninstall shortcuton app first launch or on newt devicerebootmanualy remove shortcut usingcomandroidlauncheractionuninstall shortcutwhat i cannot and almost giving upautomaticaly remove the shortcut whenthe application is being uninstalledthere is not way to use intentaction package removed because the application being uninstalled does not receive this intent i performed some tests and found out that the only shortcut type that is being removed with the application is the shortcut that is created from menu add to home screen shortcuts applications application activity the shortcuts that are being created programatically or that are declared in androidmanifest remain on home screen after the app is uninstalledthere is almost none docs and posts on forums about this topic and i am confused a little bit why such a simple operation that does not contradict with the android security policy could not be implemented in a straight wayis there any way to ask os to remove the corresponding shortcut on application uninstallcan i catch the event that the application is being uninstalled before it is removed,['android'] +43854,is there a widespread c library for reading namevalue pairs from a file my program is reading a text file containing various lines of text for a settings file some of the lines could get very large currently the buffer size is 4096 chars it is possible that some lines could exceed this whether through maliciousness or due to various factors operating within the programthe current routines were rather tedious to write and now i want to expand the possible contents of the file which will require more of this tedious repetitive code this is for a settings type file consisting of name value pairs and the occasional section header some numerical values need to be read as strings due to multiple precisionthe main thing i want is to read an arbitrary length line without buffer overflow i have just thiscovered getline can do this for me but is there for heavens sake a library that will just do the whole lot of this tediousness for meediti do not wish to be forced to place an sign between the name and values a blank space should suffice as separatorby widespread i mean the library should be available in the standard packages of the popular linux thistributionsi am aware of libconfig but it seems complete overkill for my requirements,['c'] +43855,remove null values from javascript array i am having a javascript arrayaddresses new arraydocumentclientcli buildvalue documentclientcli addressvalue documentclientcli cityvalue documentclientcli statevalue documentclientcli postcodevalue documentclientcli countryvaluedocumentclientcli postaladdressvalue addressesjoin i have to copy the content of all these array value to the postal address textarea when i use the above join function comma has been added for null values how to remove this extra commasthanks,['javascript'] +43859,how to get keypress event in windows panel control in c i want to get keypress event in windows panel control in c is any body help for me,['c#'] +43867,android listviewgetscrolly does it work i am using it but it always returns 0 even though i have scrolled till the end of the list,['android'] +43886,wpf fixeddocument in visual studio 2008 designer it is a wellknown bug that visual studio shows an error when you try to construct a fixeddocument in xaml for example the following snippetdocumentviewer fixeddocument pagecontent fixedpage width210cm height297cm textblockhello worldtextblock fixedpage pagecontent fixeddocumentdocumentviewercompiles and runs perfectly fine but visual studio shows an error in the error list property pages does not support values of type pagecontent this is quite annoyingi am looking for a solution that allows me to construct my documents in a xaml file in visual studio without getting that error message i have found a workaround which i would like to share below as an answer but i am curious if there is a better more elegant solution around,['.net'] +43887,does not name a type error i have two classes declared as belowclass userpublic mymessagebox datamsgboxclass mymessageboxpublic void sendmessagemessage msg user recvr message receivemessage vectormessage datamessagelistwhen i try to compile it using gcc it gives the following errormymessagebox does not name a type,['c++'] +43890,can i create an new instance of my custom managed object class without going through nsentitydescription from an apple example i have thisevent event eventnsentitydescription insertnewobjectforentityfornameevent inmanagedobjectcontextselfmanagedobjectcontextevent inherits from nsmanagedobject is there a way to avoid this weird call to nsentitydescription and instead just allocinit somehow directly the event class would i have to write my own initializer that just does that stuff above or is nsmanagedobject already intelligent enough to do that,['iphone'] +43913,why declare an interface as abstract whats point of declaring an interface as abstract same thing for an interface method is there a point to itegpublic abstract interface presenter public abstract void gofinal haswidgets container,['java'] +43957,whats the best way to force the user of a c function to acknowledge the semantic meaning of parameters that are numerical constants i would like to write function interfaces that force the user to acknowledge the semantic meaning of builtin constants for example i would like to takevoid rotatefloat angle rotate the world by an angle in radiansand change it tovoid rotateradians angleam i right in believing that the problem with making a radians class is that it adds code and makes the program slower is there a better way to do this,['c++'] +43963,electronic signatures in web pages i have an aspnet application it is an application where people fill out forms well we would like for people to be able to sign the form electronicallyas in their hand written signature so that the signatures are held in the server and thisplayed on the web page is there any kind of support for doing this kinda thing without having to resort to activex controls we would really strongly like to stay away from those is there anything up and coming that could be of some help such as the canvas html5 tag or anything like that it would be super neat if we could support both signature pads and tablet pcs also electronic signatures are required because we would prefer if they signed the form through the computer and stored it on our server rather than printing it off signing it and filing it away in some place to become out of date,"['asp.net', 'html']" +43973,creating an instance of a class with a variable in python i am trying to create a game for my little sister it is a virtual pet sort of thing and the pet has toys to play withi created a class toy and want to create a function getnewtoyname data1 data2 data3 data4 data5i want this function to create a new instance of the class toy and i want the function to be able to be called multiple times each time creating a new instancein my experience you create an instance withclass toy def init self name data1 data2 data3 data4 data5 passmytoy toymytoy 1 2 3 4 5then to use methods from the class withmytoymethod1seeing as i want to have the ability to have multiple toys each with a playwith method i want the instance to reflect the name of the toy each time one is calledi want the instance to be different each time i call the method getnewtoy and the instance to reflect the name,['python'] +43977,can i unit test an inner function in python is there any way to write unittests or doctests for innerfuncdef outerfunc def innerfunc do something return innerfunc,['python'] +43978,how to get the current time zone in most of the examples i had seentime zone ptr zone new posix time zonemst07 but i just want to get the current time zone for the machine that runs the code i do not want to hard code the time zone name,['c++'] +43987,javascript engines advantages i am confused about javascript engines right now i know that v8 was a big deal because it compiled javascript to native code then i started reading about mozilla spidermonkey which from what i understand is written in c and can compile javascript so how is this different from v8 and if this is true why does firefox not do thisfinally does rhino literally compile the javascript to java byte code so you would get all the speed advantages of java if not why do people not run v8 when writing scripts on their desktops,['javascript'] +43993,java operator precedence guidelines misunderstanding java operator precedence is a source of frequently asked questions and subtle errors i was intrigued to learn that even the java language specification says it is recommended that code not rely crucially on this specification jls a157 preferring clear to clever are there any useful guidelines in this areahere are a number of resources on the topicjls operatorsjls precedencejava glossaryprincetonoracle tutorialconversions and promotionsjava operator precedenceevaluation order and precedenceusenet thiscussionadditions or corrections welcome,['java'] +44012,css setting paddingmargins based on textwidth is there a measuring unit in css either planned or already in existence for setting the padding and margins based on the width of the font being usedi know that em is supposed to be the height of the uppercase m of the font the browser uses which is really handy for adding a clean doublespacing but i sometimes want the sidemargins of inline lists to be the width of a normal nonbreaking space or the width of an uppercase a with some fonts using em is vary unreliable,['css'] +44013,reading a specific line from a text file in java is there any method to read a specific line from a text file in the api or apache commons something like string readlinefile file int linenumberi agree it is trivial to implement but it is not very efficient specially if the file is very big,['java'] +44015,is this how the factory pattern works the singleton and the registry patterns were very simple and easy for me to understand right away but the factory pattern has been something i have not been able to get my brain to interpret 100 yet i think i might understand it now i have wrote a sample code below please review and tell me if this is the proper use of the factory pattern sample is in php php factoryclassphp class factory public static database public static cache public static session build our user object with all it is dependencies public static function makeuserobject user new user usersetdatabaseobjectself database usersetcacheobjectself cache usersetsessionobjectself session return user other objects will be here someday userclassphp class user public function construct inject database object public function setdatabaseobjectdatabaseconnectionobject this databaseobject databaseconnectionobject inject cache object public function setcacheobjectcacheobject this cacheobject cacheobject inject session object public function setsessionobjectsessionobject this sessionobject sessionobject other methods here for user object indexphp main page that puts it all together assume that classes are autoloaded into this page already set our database cache session objects into the factory objectfactory database new databsefactory cache new cachefactory session new session create our user object the factory class will build the user object and inject all it is dependencies for us user factorymakeuserobjectso basicly the database cache and session objects are created not shown here then they are added to the factory object i the can build a method in the factory class for each object that will need any of these 3 dependencies and i can set which ones they get too this also makes it where the individual classes can still be somewhat portable as i can directly inject there dependencies if i wanted to without the factory object does this sound right if this is right this sounds really usefulupdate 1this is based off this here a blog post i read here they refer to it as a factory i been using a registry and a lot of people keep telling me to look into a factory and everything i read about it just did not click in my head until i read this artcle but looks like it is not a factoryupdate 2from wikipedia objectin objectoriented computer programming a factory object is an object for creating other objects it is an abstraction of a constructor and can be used to implement various allocation schemes such as the singleton patterna factory object typically has a method for every kind of object it is capable of creating these methods optionally accept parameters defining how the object is created and then return the created objectfactory objects are used in situations where getting hold of an object of a particular kind is a more complex process than simply creating a new object the factory object might decide to create the objects class if applicable dynamically return it from an object pool do complex configuration on the object or other things so maybe this is a factory object in a way afterall,['php'] +44018,max thread number for one application i wanna know about max thread number for one applicationyou know threadactivecount returns the number of active threads in the running threads group and its subgroups if i can know the max number of threads to create in current activity i can limit active threadsi am using thread for http connection and catching http responsethanks in advance,['android'] +44026,layout of compiled objects is there a waymuch like viewing the result of preprocessing with gcc eto see what my objects look like once compiled into object filesi am talking about gcc but a solution including msvc would be fine,"['c++', 'c']" +44029,import pem into java key store i am trying to connect to an ssl server which requires me to authenticate myself in order to use ssl over apache mina i need a suitable jks file however i have only been given a pem file how would i go about creating a jks file from a pem file,['java'] +44041,adding soapheader username and password with wse 30 i have successfully created a ws client that works correctly when not using authenticationhowever the server websphere now requires adding a wssecurity username token and i am having a hard time doing this the resulting soap message is supposed to look something like thissoapenvenvelope xmlnsns xmlnsns1 xmlnssoapenv soapenvheader wssesecurity soapenvmustunderstand1 xmlnswsse wsseusernametoken wsuidusernametoken2 xmlnswsu wsseusernamefoowsseusername wssepassword typebarwssepassword wssenonce encodingtypefobarwssenonce wsucreated20100125t130924860zwsucreated wsseusernametoken wssesecurity soapenvheader soapenvbody nsfoobarnsfoobar soapenvbodyi have downloaded and installed microsofts wse 30 sdk and added a reference to the dll in my visual studio 2005 projecti now have access to the microsoftwebservices3 namespaces but i am currently stumped on how to proceedthe client code has been generated automatically by a web reference so i only do a minor amount of work to send the message to the server unauthenticatedwsfooresulthttpservice ws new wsfooresulthttpservicewsurl wssendsomethingmessagei have just begun to investigate using microsoftwebservices3securitytokensusernametokenmanager but so far i have not been able to get anything up and runningany hints would be greatly appreciated as i cannot seem to find any good recipes on the netthanks,['c#'] +44042,post serialized form data and extra variables using jquery i am trying to use this piece of code to serialize a form and send an extra variable not found in the form at the same time the following line of code is what i expected but sadly does not workvar thepage thefilenamepostpagedetailphp pagedetailformserialize thepage thepage functiondata alertdata any ideas,"['php', 'javascript', 'jquery']" +44046,efficiently filter an arraylist in javaandroid i am developing an android app android 16 but this is probably a more general java questioni have an arraylist of about 10 objectsthe objects contain 3 strings firstname middlename lastnamethe user is presented with a search box on android where they can search for a particular object by typing in part of the namei have a class which i call filterer that searches through the list of 10 for matching objects and then returns them as a sublistthe search is a little bit slow especially on an android handset and i am sure i am not doing the searchfiltering in the most efficient manner possibledoes anyone have any suggestions on how to speed up my search my code is below one possibility to to search against a secondary masterlist that already has every piece of information in lowercase and concatenatedabut there may be additional ways to improve this search that would also helptiapublic void filternames thisfilteredlistclear string sv thissearchstringtostringtrimtolowercase search value for int i 0 i thismasterlistsize i myobject d thismasterlistgeti string fn dgetfirstnametostringtolowercase string mn dgetmiddlenametostringtolowercase string ln dgetlastnametostringtolowercase if fnindexofsv 0 mdindexofsv 0 lnindexofsv 0 thiscurrentlistad,"['java', 'android']" +44055,how to get location on screen of row in listview i have implemented some gesture detection code so that i can detect when a row in my listview which is situated in a framelayout has been swipedpublic boolean onflingmotionevent e1 motionevent e2 float velocityx float velocityy if e2getx e1getx swipe min thistance mathabsvelocityx swipe threshold velocity int itemid mainactivitythisgetlistviewpointtopositionint e1getxint e1gety offer order offermainactivitythisgetlistviewgetadaptergetitemitemid view v mainactivitythisgetlistviewgetchildatitemid i want to thisplay a view over the top of the swiped row with a set of context sensitive options for that rowmy problems is that the following methodsvgettopvgetbottomreturn correct values only before the view has been scrolled i could probably do some calculation to work out offsets using scroll positions etc but i also noticed that i only get values when i swipe a row that is visible on screen to begin with if i scroll down the list and then swipe a row that was not originally offscreen then these methods return null valuesthe methods below seem to suffer from the same problemvgetlocationonscreenlocvgetlocationinwindowlocultimately i am looking to find the thistance between the top of the visible listview and the row that has been swiped i will then use this thistance to add a view to the parent framelayout with the appropriate height padding so that it covers the swiped rowany help would be much appreciated,['android'] +44069,operator for array in php test arrayhitest arraytestohvar dumptestwhat does mean for array in php,['php'] +44076,how does the iphone learn new wifi locations in terms of using them for location estimates i know the iphone can and does use wifi proximity to get approximate location this obviously only can occur when some database in the sky knows the approximate location of that wifi hotspot my question is how do hotspots get into that db is it automatically added whenever the iphone has a reasonably accurate gps position and detects the wifi or is there some manual or programatic way of adding hotspots,"['ios', 'iphone']" +44082,how to require login for django generic views i want to restrict access to urls serves by django generic views for my views i know that login required decorator does the job also createupdatedelete generic views takes login requied argument but i could not find a way to do this for other generic views,['python'] +44095,are net property setters ever called implicitly i am on an aspnet 20 project in c i have some data that gets stored in session state for ease of use it is wrapped in a property like thisprotected iliststuff relevantsessiondata get return iliststuff sessionrelevant key set sessionrelevant key value getting and setting the value works exactly as youd expect if i want to clear the value i just set it to null and there are no problems however in another developers page he calls the collections clear method i thought this would be a bug but it seems to work and i do not understand why it works like sodebugwritelinerelevantsessiondatacount outputs say 3relevantsessiondatacleardebugwritelinerelevantsessiondatacount outputs 0why does this work my naive expectation would be that the middle line loads the serialized value from session deserializes into an object calls clear on that object and then lets the unnamed object fall out of scope that would be a bug because the value stored in session would remain unchanged but apparently it is smart enough to instead call the property setter and serialize the newly changed collection back into session this makes me a little nervous because there are places in our legacy code where property setters have side effects and i do not want those getting called if it is not intendeddoes the property setter always get called in a situation like this is something else going on or do i completely misunderstand whats happening hereadded to explain answerit turns out did misunderstand i knew that objects stored in session must be serializable and based on that i made too many assumptions about how the collection behaves internally i was overthinkingthere is only one instance of the stored object my ilist each call to the getter returns a reference to that same instance so the quoted code above works just as it appears with no special magic requiredand to answer the title question no setters are not called implicitly,"['c#', '.net', 'asp.net']" +44105,javascript variable number of arguments to function is there a way to allow unlimited vars for a function in javascriptexampleloadvar1 var2 var3 var4 var5 etcloadvar1,['javascript'] +44116,any php code to detect the browser with version and operating system i tried to search in google but cannot find a complete solution i only find something detects only the browsers type like firefox opera i want a php class or code to check the users browser including the version and also the operating system thanks,['php'] +44118,php encoding with domdocument tagon tagwhen i try to get the content of the following code using domdocument functions it returns something likeaoa aai have tried setting domdocument encoding to different values utf8 iso88591 using mb convert encoding iconv and utf8 encode but without success how can i get on instead of aoa aa edit the input is coming from a page loaded with curl when i output the page content to my browser the characters are thisplayed correctly so i doubt the input is the problem,['php'] +44136,registry access error when migrating aspnet application to iis7 i am running windows 7 64bit and iis7 i am trying to setup a web application that was previously in iis6 on xp it is giving me the error below i have added the network service user to the performance monitor users group to no availaccess to the registry key global is denied description an unhandled exception occurred during the execution of the current web request please review the stack trace for more information about the error and where it originated in the code exception details systemunauthorizedaccessexception access to the registry key global is denied aspnet is not authorized to access the requested resource consider granting access rights to the resource to the aspnet request identity aspnet has a base process identity typically machineaspnet on iis 5 or network service on iis 6 that is used if the application is not impersonating if the application is impersonating via the identity will be the anonymous user typically iusr machinename or the authenticated request user to grant aspnet access to a file rightclick the file in explorer choose properties and select the security tab click add to add the appropriate user or group highlight the aspnet account and check the boxes for the desired access,['asp.net'] +44142,whats the difference between urihost and uriauthority systemuri has host authority and dnssafehost ms provides a nice example of when host and dnssafehost are different herei would like a similar exampleexplanation for host and authority,"['c#', '.net']" +44144,why cannot i inherit from int in c i would love to be able to do thisclass myint public intwhy cannot iwhy would i want to stronger typing for example i could define two classes inta and intb which let me do inta inta or intb intb but not inta intbints are not classes so whatints do not have any member data yes they do they have 32 bits or whateverints do not have any member functions well they have a whole bunch of operators like and,['c++'] +44147,how can i have decimaltryparse parse 00 is there a way to get decimaltryparse to parse a string value of 00 or 0 or 0 as 0 i have tried setting numberstyles to any,"['c#', '.net']" +44151,c datetimenow precision i just ran into some unexpected behavior with datetimeutcnow while doing some unit tests it appears that when you call datetimenowutcnow in rapid succession it seems to give you back the same value for a longerthanexpected interval of time rather than capturing more precise millisecond incrementsi know there is a stopwatch class that would be better suited for doing precise time measurements but i was curious if someone could explain this behavior in datetime is there an official precision documented for datetimenow for example precise to within 50 ms why would datetimenow be made less precise than what most cpu clocks could handle maybe it is just designed for the lowest common denominator cpupublic static void mainstring args var stopwatch new stopwatch stopwatchstart for int i0 i10 i var now datetimenow consolewritelinestringformat ticks 0tmilliseconds 1 nowticks nowmillisecond stopwatchstop consolewritelinestopwatchelapsedmilliseconds 0 stopwatchelapsedmilliseconds consolereadline,"['c#', '.net']" +44156,multiple inheritance design issue in java how do you deal with having only single inheritance in java here is my specific problemi have three simplified classespublic abstract class abstractword string kind eg noun verb etc public string getkind return kind public class word extends abstractword public final string word ctor public void setkind based on the variable word calculate kind public class worddescriptor extends abstractword ctor public void setkindstring kindthiskind kindthis is what i consider my most basic implementation but i want to make other implementations lets say that i want to add a new variable say wordlength but i want to add it using inheritance meaning i do not want modify that original abstractword class ie something along the lines of thispublic class length private int length public int getlengthreturn lengthpublic class betterword extends abstractword and length public void setlength based on the variable word calculate length public class betterworddescriptor extends abstractword and length public void setlengthint lengththislength lengthi know that java does not let me do this but it has made my code very ugly right now whenever i add a field i am just adding it to abstractword but then i either need to rename that abstractword and word and worddescriptor i cannot just add the field to the other one because of backwards compatibility it break equals methods and stuff like thatthis seems like a pretty common design issue but i have racked my head and i cannot come up with any beautiful solutions is there a design pattern that addresses this i have some potential solutions but i wanted to see if there was something that i was missing thanksjakeupdate length refers to the number of syllables in the word sorry about the lack of clarity,['java'] +44158,opengl glflush vs glfinish i am having trouble thistinguishing the practical difference between calling glflush and glfinishthe docs say that glflush and glfinish will push all buffered operations to opengl so that one can be assured they will all be executed the difference being that glflush returns immediately where as glfinish blocks until all the operations are completehaving read the definitions i figured that if i were to use glflush that i would probably run into the problem of submitting more operations to opengl than it could execute so just to try i swapped out my glfinish for a glflush and lo and behold my program ran as far as i could tell the exact same frame rates resource usage everything was the sameso i am wondering if there is much difference between the two calls or if my code makes them run no different or where one should be used vs the otheri also figured that opengl would have some call like glisdone to check whether or not all the buffered commands for a glflush are complete or not so one does not send operations to opengl faster than they can be executed but i could find no such functionmy code is the typical game loopwhile running process stuff render stuff,"['c++', 'c']" +44161,protecting the content of public in a rails app i am maintaining a rails app that has content in the public folder that will now need to be protected by a login were considering moving those folders of files into a path outside of public and writing a rails controller to serve up the contentbefore we begin writing this i was curious if anyone else has ran into this sort of problem i looked for some gems plugins that might already do this but did not find anything has anyone created a gem for this,"['ruby-on-rails', 'ruby']" +44165,methods to convert c code to a powershell script i regularly have to convert an existing c code snippetcs file to a powershell script can anyone offer any tools or methods that would allow some automation of thisnote while i am aware that there are methods that can convert a cs file to a cmdlet i am only interested in converting the c code to a script or module thanks magicandi,['c#'] +44171,is it possible to achieve maxasad opengl blending i am working on a game where i want to create shadows under a series of sprites on a grid the shadows are larger than the sprites themselves and the sprites are animated ie move and rotatei cannot simply render them into the sprite png or the shadows will overlap adjacent spritesi also cannot simply put shadows on a lower layer by themselves because when they overlap they will create dark bands at their intersectionthese sprites are animated so it is not feasible to render these en massebasically i want the sprites shadows to blend together such that they max out at a set opacity examplei believe this is equivalent to an opengl blending of rsgsbsmaxasds where i do not really care about rg and b as it will always be the same color in src and dsthowever this is not a valid opengl blending mode is there an easy way to accomplish this especially in cocos2diphonei would be able to approximate this by making the shadow sprites opaque then applying them both to a parent sprite and making the parent sprite 40 opacity however the way cocos2d works this only sets the opacity of each child to 40 rather than the combined sprite image which results in the same stripe,['iphone'] +44172,schedule scripts without using cron i know there are many posts about using cron to run a php file but in the world of shared hosting and ease of setup for a user i do not want to have to mess with thati found another solution online that has to do with sockets just wanted to get everyones take on this and tell me if this is a good or bad idea sounds like it works wellthoughtsopen socket connection to cronphpsocketcon fsockopen serverhttp host80errornoerrorstr10ifsocketcon socketdata get cronphp http 11rnhost serverhttp hostrnconnection closernrnfwritesocketconsocketdatanormally you would get all the data back with fgets and wait until socketcon reaches feofin this case we just do thisfclosesocketcon else something went wrong put your error handler herecronphpthis script does all the worksleep200to prove that this works we will create an empty file here after the sleep is donemake sure that the webserver can write in the directory youre testing this file inhandle fopentesttxtwfclosehandlefound the script from a blog post,['php'] +44174,right shift to perform divide by 2 on 1 i know that i can perform divide by 2 using right shift for simplicity take a 4 bit number system1 12 103 11014 11005 10116 10107 10018 107 016 01105 01014 01003 00112 00101 010 0if i try to perform6 2 0110 1 0011 36 2 1010 1 1101 3is valid for both ve and ve numberhowever when come to 11 2 01 1 0 01 2 1 1 1 1seems like there is a special case in 1 as right shift then to move it to negative infinitycurrently i need to put a special if check for this as i am expecting 1 2 0i was wondering how do you guy handle this exception in your code you guy put an if check,['java'] +44177,is there a way to extend background color of unordered list items to go behind bullets i have an unordered list and i want to have the list items have alternating background colors i am using bullets in the list is there a way to extend the background of the color horizontally to get under the bulletmargin and padding just push the bullet away,['css'] +44186,iphone allow landscape orientation on just one viewcontroller i have a navigationbased application in which i would like just one of the viewcontrollers to support landscape orientation for that viewcontroller vc1 in shouldautorotate i am returning yes for all orientations and in the other controllers i am returning yes only for portrait modebut even then if the device is in landscape mode and i go to the next screen from vc1 the next screen also comes up rotated in landscape mode i assumed that if i return a yes only for portrait mode the screen should show up only in portraitis this the expected behavior how do i achieve what i am looking forthanks,['iphone'] +44197,are all temporaries rvalues in c i have been coding in c for past few years but there is one question that i have not been able to figure out i want to ask are all temporaries in c rvaluesif no can anyone provide me an example where temporary produced in the code is an lvalue,['c++'] +44201,is openid too complicated i am beginning to seriously doubt the openid community despite that fact that it worksi am in the process of currently evaluating openid as an authentication service for this site and while the promises are great i just cannot get it to work and i am really losti ask of the so community to help me out here give me answers and show me examples so i can leverage this in the way it was meant to bemy scenario is very typical i want to authenticate users through a specific google apps domain if you have access to this google apps domain then you have access to my web applicationwhere i get lost is all the prerequisites and dependencies involvedwhat is xrd what is yathiswhy do i need xrd and yathiswhat do i need to do to deploy openid authentication on my websitealso this is really important to mewhen i login to so i use my google account when i click the login button i am presented with this confirmation page where i am granting so the right to use my google account credentialssomehow google knows that it is stackoverflowcom that is asking me if it is okay to login and i wish to know what manner of control i have over this little text i intend to deploy openid on several different domains but i would prefer if they would all work without having to be individually configured with special parameters such as secret api keys and what not however i do not know for sure if this is a prerequisite of openid that or the federated login api that google provides,['.net'] +44206,random is barely random at all i did this to test the randomness of randint from random import randint uniques for i in range4500 you can see i was optimistic x randint500 50 if x in uniques raise exceptionwe duped d at iteration number d x i uniquesappendxtraceback most recent call last file stdin line 4 in moduleexception we duped 887 at iteration number 7i tried about 10 times more and the best result i got was 121 iterations before a repeater is this the best sort of result you can get from the standard library,['python'] +44212,making a reusable predicate for entityset iqueryable and ienumerable in my linq to sql setup i have various tables which are mapped to classes which basically support the same interface to support versioning iepublic interface ivalid int validto get int validfrom get the linq to sql classes derive from this interface like thispublic partial class representationrevision ivalidnow i would like to define a dry do not repeat yourself way of filtering entitysett ienumerablet and iqueryablet so that the resulting lists are valid for a specific revision i have tried doing thispublic static class extensionmethods public static iqueryablet validfortthis iqueryablet v int revision where t ivalid return vwherecr crvalidfrom revision crvalidto null crvalidto revision revision null crvalidto null but this gives problems on entitysett i added a special implementation for entityset which first calls asqueryable but this throws an exception undeterred i tried making a predicate so i could use the wherepredicate approach public static expressionfunccontentrevision bool isvalidforint revision return cr crvalidfrom revision crvalidto null crvalidto revision revision null crvalidto null when used with wherecontentrevisionisvalidforrevision it gives errors likeerror 5 systemdatalinqentityset does not contain a definition for where and the best extension method overload systemlinqenumerablewhere systemcollectionsgenericienumerable systemfunc has some invalid argumentsnote that this is even without using the ivalid interface i have been trying all kinds of variations on this theme like adding the int parameter but they all invariably seem to fail any pointers to get me in the right direction,"['c#', '.net']" +44213,change style of surrounding border on mouse over i have a grid with a border around it upon mouse over on the grid i want to change the style on the border how would i go about doing this this is what i have tried without any success so farborder nameborder borderbrushtransparent borderthickness1 cornerradius2 grid gridstyle style targettypextype grid styletriggers trigger propertyismouseover valuetrue setter targetnameborder propertyborderbrush valueffb9d7fc trigger styletriggers style gridstyle gridcolumndefinitions columndefinition columndefinition gridcolumndefinitions gridborderupon attempting to build this xaml i get the error targetname property cannot be set on a style setterbut i cannot think of any other way to do this help would be much appreciated using any codebehind is out of the question,['.net'] +44220,rails how do i write tests for a ruby module i would like to know how to write unit tests for a module that is mixed into a couple of classes but do not quite know how to go about itdo i test the instance methods by writing tests in one of the test files for a class that includes them does not seem right or can you somehow keep the tests for the included methods in a separate file specific to the modulethe same question applies to the class methodsshould i have a separate test file for each of the classes in the module like normal rails models do or do they live in the general module test file if that exists,"['ruby-on-rails', 'ruby']" +44231,how to programmatically call a maventask i am using maven in the context of another buildtool leiningen for clojure but this should not matter and i would like to know how i would call a plugin like dependencybuildclasspath programmatically ie via the mavenapi not via the mvncommand,['java'] +44233,is this possible to write a marker interface i have gone through the following tutorial and after reading the above article i feel that it is not possible towrite a marker interface because how can you instruct compiler that what tagit embed in the class file for your marker interfaceplease correct me if i am wrongcheers,['java'] +44237,importing orgapachecommons into android applications hay how do i import orgapachecommons packages into android so i can use them in my applicationsthanks,"['java', 'android']" +44248,are there any downsides with using make shared to create a shared ptr are there any downsides with using make sharedt instead of using shared ptrtnew tboost documentation states there have been repeated requests from users for a factory function that creates an object of a given type and returns a shared ptr to it besides convenience and style such a function is also exception safe and considerably faster because it can use a single allocation for both the object and its corresponding control block eliminating a significant portion of shared ptrs construction overhead this eliminates one of the major efficiency complaints about shared ptr,['c++'] +44249,android read error log from handset how can i read the error log applications make is there any software which reads the error log from the handset and thisplays iti do not want to debug the app using eclipse i am looking for a handset based error log viewer,['android'] +44253,hide labels in pie charts ms chart for net i cannot seem to find the property that controls visibility of labels in pie charts i need to turn the labels off as the information is available in the legendanyone know what property i can use in code behindi tried setting the series labels to nothing chart1seriesilabel stringempty but the labels seem to show up anyway,"['c#', 'asp.net']" +44256,defining c enums with descriptions what would the folowing vbnet enum definition look like in cpublic enum someenum as integer descriptionname one nameone 1end enum,['c#'] +44267,how can get unique values from data table using dql i am having a table in which there is a column in which various values are storedi want to retrieve unique values from that table using dql doctrine querycreate selectrecschool fromrecords rec wherereccitycity execute now i want only unique values can anybody tell me how to do thatedittable structurecreate table if not exists records id int11 not null auto incrementstate varchar255 collate utf8 unicode ci default null city varchar255 collate utf8 unicode ci default null school varchar255 collate utf8 unicode ci default null primary key id engineinnodb default charsetutf8 collateutf8 unicode ci auto increment16334 this is the query i am using doctrine querycreate selectthistinct reccity fromrecords rec whererecstate state getsql execute generting sql for this gives meselect thistinct rid as r id rcity as r city from records r where rstate arnow check the sql generated thistinct is on id column where as i want thistinct on city column anybody know how to fix thisedit2id is unique cause its an auto incremental valueya i have some real duplicates in city column like delhi and delhi right now when i am trying to fetch data from it i am getting delhi two times how can i make query like this select thistinct reccity where statexyzcause this will give me the proper outputedit3anybody who can tell me how to figure out this query,['mysql'] +44271,how do i find the shortest overlapping match using regular expressions i am still relatively new to regex i am trying to find the shortest string of text that matches a particular pattern but am having trouble if the shortest pattern is a substring of a larger match for exampleimport restring ababcdefgmy pattern abcmy regex recompilemy pattern redotallreignorecasematches my regexfindallstringfor match in matches print matchprints ababcbut i would want it to returnabcis there a way to do this without having to loop over each match to see if it contains a substring that matches,['python'] +44272,jquery ui dialog and textarea focus issue i am working on a modal comment system using jquery and jquery ui but i am having some issues with focus i have a series of divs inside the modal to switch between login and add comment as below div idmodal titleloading div idmodalcontentdiv div idmodallogin div classloginboxdiv div classaddcommentboxdiv div classcommentreviewdiv divdivinside of the addcommentbox div i have got the comment code form actioncommentsadd classaddcommentform nameaddcommentform methodpost textarea namecontent classaddcommentcontenttextarea button valueadd comment typesubmit classcommentpost button valueclear comment typesubmit idclearcomment formthe issue is that about half the time after opening the dialog the textarea inside the addcommentbox div does not react to keyboard inputs when selected the mouse works correctly and will allow text to be selected but keyboard control does nothing i have no event listeners on the textarea i have got some on the buttons but they are targeting only the buttonsthe only thing that happens in the html seems to be the fact that every time i click on the modal the zindex increases for the overall modal div i have set the addcommentbox div to have a zindex of 9 greater than the zindex of the modal any suggestions or directions to research would be greatly appreciated thanks,"['javascript', 'jquery']" +44277,sql server 2005 converting varchar value 123e4 to decimal fails declare a varchar40set a123e4declare b decimal2712if isnumerica 1begin select bcasta as decimal2712endelsebegin select b1endselect bwhen exeucting above sql code under sql 2005 environment i am getting following errorerror converting data type varchar to numericanyone knows whythanks,['sql'] +44284,proper avaudiorecorder settings for recording voice i am adding a voice memo capability using avaudiorecorder and i need to know the best settings for the recorder for recording voice unfortunately i know nothing about audio to the extent i am not even sure what terms to google for currently i am using the following which i copied from somewhere for testing purposesrecordersettingsdictnsdictionary alloc initwithobjectsandkeysnsnumber numberwithintkaudioformatappleima4avformatidkey nsnumber numberwithint4410avsampleratekey nsnumber numberwithint 2avnumberofchannelskey nsnumber numberwithint16avlinearpcmbitdepthkey nsnumber numberwithboolnoavlinearpcmisbigendiankey nsnumber numberwithboolnoavlinearpcmisfloatkey nilordefaultsettings avformatidkey 1768775988 avlinearpcmbitdepthkey 16 avlinearpcmisbigendiankey 0 avlinearpcmisfloatkey 0 avnumberofchannelskey 2 avsampleratekey 44100this works but i do not know if it is optimal for voice in terms of quality speed file size etc the avaudiorecorder class reference list many settings constants but i have no clue which ones to use for voicebaring that if someone knows of a good audioformats for dummys resource i will take that as well notei have been through the apple docs and they assume a knowledge base in digital audio that i do not posses,['iphone'] +44296,regex date format validation on java i am just wondering if there is a way maybe with regex to validate that an input on a java desktop app is exactly an string formated as ymmddi have searched but with no successthank you,['java'] +44310,finding signed angle between vectors how would you find the signed angle theta from vector a to band yes i know that theta arccosababhowever this does not contain a sign ie it does not thistinguish between a clockwise or counterclockwise rotationi need something that can tell me the minimum angle to rotate from a to b a positive sign indicates a rotation from xaxis towards yaxis conversely a negative sign indicates a rotation from xaxis towards yaxisassert angle1001 pi2assert angle0110 pi2,"['java', 'python']" +44321,converting file path from nsstring to nsurl i am working through cocoa smoothly but this problem seems so basic it cancels out all the cool stuff i learned i have a generated file path and it needs to be in nsurl format from research this is the code i wrotenslogold path pathtofilensurl xmlurl nsurl alloc init fileurlwithpathpathtofilenslognew path xmlurl absolutestringand the output20100127 153922105 musiclibrarystats28574a0f old path filelocalhostusersusernamemusicitunesitunes20music20libraryxml20100127 153922105 musiclibrarystats28574a0f new path nullfirst off the allocinit should not even be necessary other people seem to get away with it in this case if i do not allocinit i get an unrecognized selector error on that line of course now i am just getting plain old nullwhere did i goofthanks,['objective-c'] +44324,what is best aproach to get sql data from c i am trying to find optimal fast vs easiest way to access sql server code thru code in c as i was learning from books i have encountered multiple suggestions usually telling me to do it via drag and drop however since i wanted to do it in code first aproach was to get data by column numbers but any reordering in sql query like addingremoving columns was pain for me to fixfor example do not laugh some code is like 2 years old i even coded special function to pass sqlqueryresult and check if it is null or notpublic static void examplebycolumnnumberstring varvalue string preparedcommand select top 1 somecolumnsomecolumn2 from databasedbotable where someothercolumn varvalue sqlcommand sqlquery new sqlcommandpreparedcommand localesqldataconnection sqlqueryprepare sqlqueryparametersaddwithvaluevarvalue varvalue sqldatareader sqlqueryresult sqlqueryexecutereader if sqlqueryresult null while sqlqueryresultread string var1 localecheckfornullreturnstringsqlqueryresult 0 string var2 localecheckfornullreturnstringsqlqueryresult 1 sqlqueryresultclose later on i found out it is possible thru column names which seems easier to read with multiple columns and a lot of changing order etc public static void examplebycolumnnamesstring varvalue string preparedcommand select top 1 somecolumnsomecolumn2 from databasedbotable where someothercolumn varvalue sqlcommand sqlquery new sqlcommandpreparedcommand localesqldataconnection sqlqueryprepare sqlqueryparametersaddwithvaluevarvalue varvalue sqldatareader sqlqueryresult sqlqueryexecutereader if sqlqueryresult null while sqlqueryresultread string var1 string sqlqueryresultsomecolumn string var2 string sqlqueryresultsomecolumn2 sqlqueryresultclose and 3rd example is by doing it by column names but using tostring to make sure it is not null value or by doing ifelse on the null check public static void examplebycolumnnamesagainstring varvalue string preparedcommand select top 1 somecolumnsomecolumn2 somecolumn3 from databasedbotable where someothercolumn varvalue sqlcommand sqlquery new sqlcommandpreparedcommand localesqldataconnection sqlqueryprepare sqlqueryparametersaddwithvaluevarvalue varvalue sqldatareader sqlqueryresult sqlqueryexecutereader if sqlqueryresult null while sqlqueryresultread string var1 string sqlqueryresultsomecolumntostring datetime var2 datetimetryparsesqlqueryresultsomecolumn2tostring int varint int sqlqueryresultsomecolumn3 null 0 int sqlqueryresultsomecolumn3 sqlqueryresultclose please bare in mind that i have just created this for sake of this example and there might be some typos or some slight syntax error but the main question is which approach is best which is the worst i know first one is the one that i thislike the most i will soon have to start rewrtiting some portion of my little 90k lines app which has at least those 3 examples used widely so i would like to get best method for speed and preferably easiest to maintain hopefully it will be same aproachprobably there are some better options out there so please share,"['c#', 'sql']" +44338,how to increment a version number programmatically how do i programmatically increment a given versions number to the next version of the highest onefor example if i have a file programexe with the following version numbers programexe 10programexe 1004programexe 11076programexe 10066the next version number in this case would be 11077 whats the easiest way to implement thatthanks for any help in advance,['c#'] +44339,c auto highlight text in a textbox control how do you auto highlight text in a textbox control when the control gains focus,['c#'] +44348,how do you add a generic item to a combobox bound to a collection in wpf i have a combobox in a wpf application that is bound to an observablecollection of department objects in a c viewmodel class i want to use the combo box to filter another collection by department and indeed it works for that now the problem is that i want to add an additional option all to the top of the list is there a correct way to do this making a fake department feels wrong in so many waysthe comboboxcombobox itemssourcebinding pathdepartments selectedvaluebinding pathdepartmenttoshow modetwoway,['c#'] +44359,php trouble with concurrent sessions and ajax i have a session handler class that calls session write close at the end of the script this insures that even if a header or exit is issued the session data is savedpublic function destruct session write closehowever i have noticed that for one of my ajax pages two session updates are committed by the database layermy guess is that the 1 page loads and sends an 2 ajax request that 2 ajax request must start the session before the 1 page has a chance to call session write closeafter the 2 ajax page has loaded the session then the 1 page finally saves the session and then shortly after the 2 ajax request saves it is session which overwrites the first oneit might look like this1 page loads session1 page sends output2 ajax loads session1 page saves session2 ajax sends output2 ajax saves sessionwhat do i do to make sure one page is not loading a session before another has a chance to save the session,['php'] +44360,iphone what are reuseidentifiers uitableviewcell from the official documentationthe reuse identifier is associated with a uitableviewcell object that the tableviewas delegate creates with the intent to reuse it as the basis for performance reasons for multiple rows of a table view it is assigned to the cell object in initwithframereuseidentifier and cannot be changed thereafter a uitableview object maintains a queue or list of the currently reusable cells each with its own reuse identifier and makes them available to the delegate in the dequeuereusablecellwithidentifier method classreferencereferencehtmlapple refoccinstpuitableviewcellreuseidentifieri do not understand this well i understand the basic idea i think that you create uitableviewcells and try to reuse as many as you can instead of making new ones or something like that but what exactly decides whether or not a cell is reusable if i have got two identical visually cells but with different texts well i suppose they are not entirely identical can they both have the same identifier or should they have different ones or in what situation are you supposed to use different identifierscan anyone clarify or link to a place where it is,"['iphone', 'objective-c']" +44374,python looping idiomatically comparing successive items in a list i need to loop over a list of objects comparing them like this 0 vs 1 1 vs 2 2 vs 3 etc i am using pysvn to extract a list of diffs i wound up just looping over an index but i keep wondering if there is some way to do it which is more closely idiomatic it is python should not i be using iterators in some clever way simply looping over the index seems pretty clear but i wonder if there is a more expressive or concise way to do itfor revindex in xrangelendm revisions 1 summary svndiff summarizesvn path revision1dm revisionsrevindex revision2 dm revisionsrevindex1,['python'] +44380,most flexibilities rule engine for net my upcoming project is relate to sales system so one of the main requirement is user can modify promotion by themselves promotions is vary they give me some of thembuy 1 get 1 free buy 2 get 3one for 30 two for 50 three for 80buy product a will thiscount 30 for product b20 off for more than 20 per transactioni know a little of rule engine please suggest me a book to learn it too,"['c#', '.net']" +44386,multiple instances of jquery autocomplete on one page i would like to style each instance of jquerys autocomplete plugin differently on each page except i cannot figure out how to set the styles to be different for each instance i cannot seem to wrap the ac styles inside a div to identify them from the css every change i make affects both any ideasthank you,['jquery'] +44388,lazymultistage construction in c whats a good existing classdesign pattern for multistage constructioninitialization of an object in ci have a class with some data members which should be initialized in different points in the programs flow so their initialization has to be delayed for example one argument can be read from a file and another from the networkcurrently i am using boostoptional for the delayed construction of the data members but it is bothering me that optional is semantically different than delayconstructedwhat i need reminds features of boostbind and lambda partial function application and using these libraries i can probably design multistage construction but i prefer using existing tested classes or maybe there is another multistage construction pattern which i am not familiar with,['c++'] +44389,what is in php 53 possible duplicatewhat are the php operators aa and aa called and what do they dofrom php require dir cphp if is callablec getc function echo woah throw new exceptionerror ctwitto uses several new features available as of php 53the dir constantthe operatoranonymous functionswhat does number 2 do with the in php 53also what do they mean by anonymous functions was not that something that has existed for a while,['php'] +44402,how to make windows service start as automatic delayed start scenarioa wcf service running as a windows service account is userwhat is donei have overridden the onbeforeinstall in the projectinstaller to be able to set username and password from a config filewhat i would be able to doi would like to be able to set the starttype as automatic delayed startwhat i have triedi put the following coderow in the overridden onbeforeinstallserviceinstaller1starttype servicestartmodeautomatic 1figured i would trick the servicestartmode enum into representing automatic delayed start did not work have not tried anything more simply because i could not find anything to trywhat i have found on the neti found out that automatic delayed start will be available in net 4 but that does not help me right nowmsdni found out that delayedautostart could be added to the services configuration key but this feels like a hack if i should do this from code but maybe this is the only solution available for me at this pointws2008 startup processes and delayed automatic startany ideasrobert persson sweden,['c#'] +44407,how to start a getpostputdelete request and judge request type in php i never see how is putdelete request senthow to do it in phpi know how to send a getpost request with curlch curl initcurl setoptch curlopt cookiejar cookiefilecurl setoptch curlopt cookiefilecookiefilecurl setoptch curlopt returntransfer 1curl setoptch curlopt followlocation 1curl setoptch curlopt ssl verifypeer falsecurl setoptch curlopt post 0curl setoptch curlopt timeout 4but how to do putdelete request,['php'] +44412,getting smtpclient to work with a self signed ssl certificate i am attempting to use the systemnetmailsmtpclient class to relay an email through my companys email server all smtp connections to the mail server have to be ssl and it uses a self signed certificate that is fine for outlook where you can just click ok on the warning dialogue but does anyone know a way to get smtpclient to accept a self signed certificatei am planning on using this app on the windows azure platform so i would not be able to install the self signed certificate as a trusted root,['c#'] +44417,returning the first and characters of a unicode string i have a string in unicode and i need to return the first and charactersi am doing thisresult unistring5but of course the length of unicode strings length of charactersany ideas the only solution is using reedit more infounistring i1ioi metallica written in greek lettersresult unistring1returns i think that unicode strings are two bytes char that is why this thing happens if i doresult unistring2i get mwhich is correctso should i always slice2 or should i convert to something,['python'] +44426,truncate a multibyte string to and chars i am trying to get this method in a string filter workingpublic function truncatestring chars 50 terminator ai would expect this in abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwyxz1234567890out abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuv aand also thisin a a a2a3a a a1aoaa14a12a34aout a a a2a3a a a1aoaa14a12a34a athat is chars minus the chars of the terminator string in addition the filter is supposed to cut at the first word boundary below the chars limit egin answer to the ultimate question of life the universe and everythingout answer to the ultimate question of life the ai am pretty certain this should work with these stepssubstract amount of chars in terminator from maximum charsvalidate that string is longer than the calculated limit or return it unalteredfind the last space character in string below calculated limit to get word boundarycut string at last space or calculated limit if no last space is foundappend terminator to stringreturn stringhowever i have tried various combinations of str and mb functions now but all yielded wrong results this cannot be so difficult so i am obviously missing something would someone share a working implementation for this or point me to a resource where i can finally understand how to do itthanksps yes i have checked before,['php'] +44432,an ear java ee application which listen to a socket request i want to build a java ee application ear which not only provides web servicewar or direct jms request ejb but i would like to also accept the socket request eg udp packeti have tried writing a listener with javanetdatagramsocket letting it run as separate process and redirecting the request to my ear applicationthe question ishow can i build such socket listener into my java ee ear applcation seamlesslythanks,['java'] +44434,run nsrunloop in a cocoa commandline program is it possible to initialize a nsrunloop without loading any nib files ie without calling nsapplicationmainthanks,['objective-c'] +44441,php loop through all months in a date range if i have a start date say 20090201 and an end date say 20100101 how can i create a loop to go through all the dates months in the range,['php'] +44444,howto start writing ipad applications i know objectivec from desktop apple programmingbut i want to jump on the ipad bandwagon and start developing some small edutainment appletsis the ipad api the same as iphone just with more powerdo i need to join the iphone developer program and does it still start with 100 is there any ipad emulator yet,['iphone'] +44447,two equality operators in same if condition are not working as intended i am trying to establish equality of three equal variables but the following code is not printing the obvious correct answer which it should print can someone explain how the compiler is parsing the given ifcondition internallyincludestdiohint main int i 123 j 123 k 123 if i j k printfequaln else printfnot equaln return 0outputmanavworkstation gcc wall pedantic calcalcc in function amainacalcc5 warning suggest parentheses around comparison in operand of aamanavworkstation aoutnot equalmanavworkstationeditgoing by the answers given below is the following statement okay to check above equalityif ij jk,"['c++', 'c']" +44453,how do c compilers implement functions that return large structures the return value of a function is usually stored on the stack or in a register but for a large structure it has to be on the stack how much copying has to happen in a real compiler for this code or is it optimized awayfor example struct data unsigned values256data createdata data data initialize data values return dataassuming the function cannot be inlined,['c'] +44457,fixing the breakpoint will not currently be hit no symbols have been loaded for this document c desktop application on express edition worked then did not work 5 seconds lateri tried the followingensure debug configuration debug flag and full debug info are set on all assembliesdelete all bin and obj folders and all dlls related to the project from my entire machinerecreate projects causing the problem from scratchrebooti have two winforms projects in the solution one of them loads the debug info one does not they both refer to the assembly i am trying to get debug info on in exactly the same way in the project file any ideasi want to add in here mostly for myself when i come back to review this question that symbols are not loaded until the assembly is loaded and the assembly is not loaded until it is needed if the breakpoint is in a library that is only used in one function in your main assembly the symbols will not be loaded and it will show the breakpoint as not being hit until that function is called,"['c#', '.net']" +44460,java recommended solution for deep cloningcopying an instance i am wondering if there is a recommended way of doing deep clonecopy of instance in javai have 3 solutions in mind but i can have miss some and i would like to have your opinionedit include bohzo propositon and refine question it is more about deep cloning than shallow cloningdo it yourselfcode the clone by hand properties after properties and check that mutable instances are cloned toopro control of what will be performed quick executioncons tedious to write and maintain bug prone copypaste failure missing property reassigned mutable property use reflectionwith your own reflection tools or with an external helper like jakarta commonbeans it is easy to write a generic copy method that will do the job in one linepro easy to write no maintenancecons less control of what happens bug prone with mutable object if the reflection tool does not clone sub objects too slower executionuse clone frameworkuse a framework that do it for you like commonslang serializationutilsjava deep cloning librarydozerkryopro same as reflection more control over what will be exactly be clonedcons every mutable instance is fully cloned even at the end of the hierarchy could be very slow to executeuse bytecode instrumentation to write clone at runtimejavassit bcel or cglib might be use to generate a dedicated cloner as fast as one hand writed someone knows a lib using one of these tools for this purpose what i have missed here which one would you recommend thanks,['java'] +44463,why does not attempting to add to a null value throw an invalidoperationexception int x nullx x 1 works but x remains nulli would expect the compiler to attempt to cast x as an int but apparently it does notedit by 280z28 changed nullreferenceexception to invalidoperationexception which is what nullabletvalue throws when hasvalue is false,"['c#', '.net']" +44481,wcf 504 the server did not return a response for this request i have a jsonp wcf endpoint and am trying to track down why i am getting a 504 errorhttp11 504 fiddler receive failure contenttype texthtml connection close timestamp 1145459580 readresponse failed the server did not return a response for this requesti can set a breakpoint anywhere inside of my endpoint step through code see it successfully gather the data required for the response hit the final line of code then as soon as i step out of the wcf call i get a 504 error this was working last weekaspnetcompatibilityrequirementsrequirementsmode aspnetcompatibilityrequirementsmodeallowedservicecontractname negotiateservice namespace public class negotiateservice svccontractsinegotiateservice public negotiateservice operationcontract webgetresponseformat webmessageformatjson public dataobjectsnegotiatesetup getsetupstring method string jsoninput dataobjectsnegotiatesetup resultset new dataobjectsnegotiatesetup using rivfeedsentities1 dbfeed new feedstorereadonlyappsettingsfeedautosentities connstring readonlyentities using riventities dbriv new rivworksstoreappsettingsrivworkentities connstring negotiationentities deserialize the input and get all the data we need newtonsoftjsonlinqjobject o newtonsoftjsonlinqjobjectparsejsoninput string urlref stringformat0 orefreplace string clientdate stringformat0 odtreplace string productid stringformat0 oproductidreplace string sku stringformat0 oskureplace string env stringformat0 oenvreplace ilistproduct efproductlist null product workingproduct null vwcompanydetails workingcompany null bool founditem false if stringisnulloremptysku efproductlist dbrivproductincludecompanywherea asku skutolist else if stringisnulloremptyproductid efproductlist dbrivproductincludecompanywherea aproductid new guidproductidtolist foreach product product in efproductlist if stringisnulloremptyproducturldomain var efcompany dbrivvwcompanydetails wherea adefaulturldomain null acompanyid productcompanycompanyid firstordefault if efcompany null urlrefcontainsefcompanydefaulturldomain founditem true workingproduct product workingcompany efcompany else if urlrefcontainsproducturldomain founditem true workingproduct product workingcompany dbrivvwcompanydetails wherea acompanyid productcompanycompanyid firstordefault if founditem try update the resultset if workingproduct null workingcompany null string rooturl stringempty try rooturl appsettingsrooturl catch rooturl env resultsetbutton workingproductbuttonconfig resultsetswfsource stringformat0flashnegotiationplayerswf rooturl resultsetgateway rooturl resultsetproductid workingproductproductidtostring resultsetbuttonpositioncss workingproductbuttonpositioncss catch exception ex logwriteline error exmessage logwritelinestack trace exstacktrace return resultset my webconfig wcf configuration systemservicemodel behaviors endpointbehaviors behavior namejsonpservicebehavior webhttp behavior endpointbehaviors behaviors services service namerivworkswebservicenegotiateservice endpoint address bindingcustombinding bindingconfigurationjsonpbinding behaviorconfigurationjsonpservicebehavior contractrivworkswebservicenegotiateservice service services extensions bindingelementextensions add namejsonpmessageencoding typerivworkswebservicejsonpbindingextension rivworkswebservice version10 cultureneutral publickeytokennull bindingelementextensions extensions bindings custombinding binding namejsonpbinding jsonpmessageencoding httptransport manualaddressingtrue binding custombinding bindings systemservicemodelas i said the code runs all the way through so i am trying to figure out why it is not sending a response,"['c#', 'asp.net']" +44484,onclick open window and specific size i have a link like thisa hrefindex2phpoptioncom jumiampfileid3ampitemid11 onclickwindowopenthishreftargetwindowtoolbarnolocationnostatusnomenubarnoscrollbarsyesresizableyesi want the new opening window to open in a specific size how do i specify the height and width,"['javascript', 'html']" +44495,deploying aspnet mvc applications to staging and production with sql we have been a coldfusion shop for 10 years and are now switching over to aspnet mvc our target framework is net 40 beta 2 using vs 2010 beta 2 we set up two instances of windows server 2008 staging and production and will be using our existing database server sql server 2008none of us really have much experience in aspnet itself though we are all very comfortable in c and the mvc pattern the coding itself is not much of an issue but the deployment process is our goal is to be able to have a ci setup that will automatically pull down and test our applications into staging on commit then have the option to tag then switch the checkouts on our production sites when websites pass qasome of the things i am having issues with here is the concept of an aspnet application and how it integrates into svn cf like php or ror are all scripting languages and as such require no build process checking out the source into production is very straightforward but in this case applications need to be compiled which is where we start to have problems will we need to create another server or use an existing one that has some sort of application that pulls down code compiles it then somehow pushes it on the live servers if so what is considered the best way to accomplish this i imagine if we end up using a build tool such as nant adding additional steps to migrate the database would be trivial but what is the best way to accomplish this as wellanother slightly unrelated problem is how our designers will work with our code most of them are on macs and using vs is not much of an option how will they be able to edit the aspx css and image files easily our goal is to make this as transparent as possible to themwe have done a lot of shopping around and aspnet mvc seems to be the best option as far as our familiarity with the language and our current platform we just need to figure out a good build process so everything is as transparent as possible i understand there are a ton of resources available on this but i wanted to get the opinions of the people here from firsthand experience,['asp.net'] +44496,const cast to allow read lock does this smell bad i want to execute a readonly method on an object marked as const but in order to do this threadsafely i need to lock a readerswriter mutexconst value objectlist const scopedread lockchildren but this breaks because the compiler complains about children being const and such i went up to the scopedread class and up to the rwmutex class which children is a subclass to allow read lock on a const object but i have to write thisinline void read lock const pthread rwlock rdlockconst castpthread rwlock trwlock i have always learned that const cast is a code smell any way to avoid this,['c++'] +44497,c new line and tab characters in strings stringbuilder sb new stringbuildersbappendline 1insert new line characterinsert tab charactersbappendline 2using streamwriter sw new streamwriterexampletxt sqwritesbtostringhow can insert a new line and tab character in this example,['c#'] +44504,convert psd to website hi therei am learning web dev and i am already stucked at some point how do i convert a psd template to a htmlcss website i have cropped all part of the image and saved them in gif separately but then do i have to manually place them in a dreamweaver empty template i thought there was an automated way to do so also i have tried save for web and devices but when saving it creates a html file and a single image which contains every element i expected several images so that i could rearrange them in dreamweaver,['html'] +44512,is linqxml always so messy var subset from item in documentdescendantsid where itemvalue itemidtostring select new purchaseitem id intparseitemparentelementidvalue name itemparentelementnamevalue description itemparentelementdescriptionvalue price intparseitemparentelementpricevalue the structure of the xml is as followsitems item idid namename descriptiondescription priceprice itemitemsid and price are both integer values name and description are stringsi have found linq to xml great for what i have used it for this is just a snippet but on the other hand i get the feeling it should or could be cleaner the casting seems the most obvious issue in this snippetany advice,"['c#', '.net']" +44518,what is the or operator in an if statement in c how do i specify orifthis or that do the other thingi could not find it in the helpupdatemy code isif title user greeting user name do stuffand my error iserror 1 operator cannot be applied to operands of type bool and string cdocuments and settingssky view barnsmy documentsvisual studio 2005projectsfol ministryfol ministrydownloadercs 63 21 fol ministry,['c#'] +44520,why does not objectivec support private methods i have seen a number of strategies for declaring semiprivate methods in objectivec but there does not seem to be a way to make a truly private method i accept that but why is this so every explanation i have essentially says you cannot do it but heres a close approximationthere are a number of keywords applied to ivars members that control their scope eg private public protected why cannot this be done for methods as well it seems like something the runtime should be able to support is there an underlying philosophy i am missing is this deliberate,['objective-c'] +44523,php maths logic i am trying to set a variable based on some maths logic to wrap specific html around elementsi worked half the problem to hit 0 3 6 9 12ifi 3 0 blah now i need to hit the following numbers 2 5 8 11 14 etcwhat possible maths operation could i do to hit this sequence,['php'] +44535,how to size an android view based on its parents dimensions how can i size a view based on the size of its parent layout for example i have a relativelayout that fills the full screen and i want a child view say an imageview to take up the whole height and 12 the widthi have tried overriding all on onmeasure onlayout onsizechanged etc and i could not get it to work,['android'] +44537,in c is it possible to forward declare a class as inheriting from another class i know that i can doclass foobut can i forward declare a class as inheriting from another likeclass bar class foo public baran example use case would be covariant reference return types somewherehclass ra class rb public ra and then in another header that does not include somewhereh otherhclass raclass a public virtual ra foo this only needs the forward decelerationclass rb public ra invalid butclass b public virtual rb foo the only information the compiler should need to process the declaration of rb bfoo is that rb has ra as a public base class now clearly you would need somewhereh if you intend to do any sort of dereferencing of the return values from foo however if some clients never calls foo then there is no reason for them to include somewhereh which might significantly speed compilation,['c++'] +44551,what is the benefit of a promise abstraction in commonjs i am reading this article and the section on the promise abstraction seems a little overly complicated to me the following is given as an examplerequestsomedata returns a promise for the response thenfunctionresponse athena is used to provide a promise handler return jsonparseresponsebody parse the body returns a promise for the parsed body thenfunctiondata return dataprice get the price returns a promise for the price thenfunctionprice print out the price when it is fulfilled printthe price is price it seems to me that the following could provide the same result with fewer lines of coderequestsomedata requesthandlerfunctionresponse parse the body var data jsonparseresponsebody get the price var price dataprice print out the price printthe price is price,['javascript'] +44553,mimic uialertview bounce whats the best way to mimic the bouncing animation from the uialertview on the iphone is there some builtin mechanism for this the uialertview itself would not work for my needsi looked into animation curves but from what i can tell the only ones they provide are easein easeout and linear,['iphone'] +44558,how to find the memory used by any object class helppublic help help typedef stdsetstring terms typedef stdmapstring stdpairintterms termmap typedef stdmultimapint string greaterint termsmapprivate termmap terms termsmap termsmaphow can we find the memory used in bytes by the objects term and termsmap do we have any library,['c++'] +44563,automatically creating a collection in the dictionary lot of times i have to create a dictionarykeytype listvaluetypebefore i can start using the dictionary i have to first verify that list has been created for that keycan i remove these two linesifdictcontainskeykey dictkey new listvaluetypenow use the keydictkeyaddvaluei know its only 2 lines of code but it annoys me and i think it can be removedi can extend dictionary in someway but before i do it i want to know if someone has found a clever way to remove the above if statementbasically i want to create a dictionarykeytype collectionvaluetype and start using it right away like dictkeyaddvalue,"['c#', '.net']" +44564,what is the difference between these two functionsapproaches i use only jquery for writing javascript code one thing that confuses me is these two approaches of writing functionsfirst approachvote function actionfeedbackidresponsediv alerthi return feedbackidsecond approachfunction voteaction feedbackidresponsediv alerthi return feedbackidwhat is the difference between the two and why should one use the first approach or the second approach,['javascript'] +44569,enum in hibernate persisting as an enum in my mysql database there is the column gender enummalefemalei have created my enum commydomainmyappenumsgender and in my person entity i am defined gender gender now i would want to keep the enum type in my mysql database but when i launch my application i getwrong column type in myaperson for column gender found enum expected integerwhy is this this would be the equivalent as if i would annotated my gender gender with enumeratedenumtypeordinal which i have not enumtype seems only to be able to be either ordinal or string so how do i specify that it should treat the field as an enum not as an int not that there is much difference but enough for it to get upset about it,"['java', 'mysql']" +44571,any smarter way to extract from array of bits i have areas of memory that could be considered array of bits they are equivalent tounsigned char arr256but it would be better thought of asbit arr2048i am accessing separate bits from it withdefine getbitxin in x8 17x8but i do it a lot in many places of the code often in performancecritical sections and i wonder if there are any smarter more optimal methods to do itextra info architecture arm9 32 bit gcclinux the physical data representation cannot be changed it is externally provided or mapped for external use,"['c++', 'c']" +44573,mysql whats the difference between float and double checking in the new database structure i saw that someone changed a field from float to double wondering why i checked the mysql documentation but honestly did not understand what the difference iscan someone explain,['mysql'] +44576,what changes are there in the iphone developer program license agreement recently the iphone developer program license agreement has been changedsadly there is no previous version officialy available for us to compare as far is i knowgoogling the search term does not reveal very useful results to me and only very old versions of the license agreementif anyone of you has a good understanding of the license agreement and its recent changes i would be glad to learn from you,['iphone'] +44577,how do you append rows to a table using jquery hi i was trying to add a row to a table using jquery but it is not working what might be the reasonand can i put in some value to the newly added rowhere is the codehtmlheadscript typetextjavascript srcjqueryjsscriptscript typetextjavascript aclickfunction mytablechildstrappendtr classchildtdblahblahtdtrscripttitletitleheadbodya hreflinkatable idmytable tbody tr td test td tr tbodytablebodyhtml,"['jquery', 'html']" +44578,why cannot we declare a stdvector having spent quite some time developping in c i noticed that if you declare an abstract class for the purpose of using it as an interface you cannot instantiate a vector of this abstract class to store instances of the children classespragma onceinclude iostreaminclude vectorusing namespace stdclass ifunnyinterfacepublic virtual void iamfunny 0class funnyimpl ifunnyinterfacepublic virtual void iamfunny cout insert joke here class funnycontainerprivate stdvector ifunnyinterface funnyitemsthe line declaring the vector of abstract class causes this error in ms vs2005error c2259 ifunnyinterface cannot instantiate abstract classi see an obvious workaround which is to replace ifunnyinterface with the followingclass ifunnyinterfacepublic virtual void iamfunny throw new stdexceptionnot implemented is this an acceptable workaround c wise if not is there any third party library like boost which could help me to get around this thank you for reading this anthony,['c++'] +44582,binding dropdownlist to listitemcollection and the value not being added to the ddl i have this code in a business class internal listitemcollection getallagents datatable table daogetallagents listitemcollection list new listitemcollection foreach datarow row in tablerows listaddnew listitemrowagent nametostring rowidtostring return list i get the table back from the dao without issue i watch the text and values properties populate properly1 for some awesome illiteration and returned to the presentation and i bind like this helper helper new helper listitemcollection agentlist helpergetallagents agentlistinsert0 thisddlagentdatasource agentlist thisddlagentdatabindwhen i make get the selected valuethisddlagentselectedvaluei would expect to see the agent id but what i get is the text agent name so i tried thisthisddlagentselecteditemvaluebut i got the same results i then took a look at the html source being generated and it looks like thisselect namectl00contentplaceholder1ddlagent onchangejavascriptsettimeout dopostbackctl00contentplaceholder1ddlagent 0 idctl00 contentplaceholder1 ddlagent option selectedselected valueoption option valueagent1 nameagent1 nameoption option valueagent2 nameagent2 nameoptionthis pattern continues for all the agents i am hoping i am just doing something bone headed and you can all snicker as you solve my problem thanks guys edit if i do it like thislistitemcollection agentlist helpergetallagentsagentlistinsert0foreach listitem agent in agentlist thisddlagentitemsaddagentit works fine,"['c#', 'html']" +44584,spring 30 unable to locate spring namespacehandler for xml schema namespace any ideas what could be the cause of thisunable to locate spring namespacehandler for xml schema namespace orgspringframeworkwebcontextcontextloader initwebapplicationcontext context initialization failedorgspringframeworkbeansfactoryparsingbeandefinitionparsingexception configuration problem unable to locate spring namespacehandler for xml schema namespace offending resource servletcontext resource webinfapplicationcontextxmlthis is my applicationcontextxmlxml version10 encodingutf8beansbeans xmlns xmlnsxsi xmlnsbeans xmlnscontext xsischemalocation beansbeansin my pomxml i havedependency groupidorgspringframeworksecuritygroupid artifactidspringsecuritycoreartifactid version301releaseversiondependencydependency groupidorgspringframeworksecuritygroupid artifactidspringsecurityopenidartifactid version301releaseversiondependency,['java'] +44590,jaxb xjc code generation schemalocation missing in xml generated by marshaller i use xjc tool to generate java classes for my xsd schema when i use jaxb marshaller to marshall classes into xml payloads i am missing schemalocation parameter in the output xml but i declare this parameter in xsd file how to enforce schemalocation parameter in the output xmlbelow is the beggining of my xsd schema file used for code generationxml version10 encodingutf8xsschema xmlnsxs xmlnsxsdns xmlnsmessages xmlnsdatatypes xmlnsxsi xsischemalocation messagesxsd targetnamespace elementformdefaultunqualified versiontruexsinclude schemalocationdatatypesxsdxscomplextype nameexecutesystemcommandstruct xsannotation xsdocumentationthe request for system command executionxsdocumentation xsannotation xssequence xsattribute nameaction typedatatypessystemactionkindenum userequired xsannotation xsdocumentationthe action that the voice system has to proceedxsdocumentation xsannotation xsattributeregards,['java'] +44605,android controlling a task with timer and timertask i am currently trying to set up a wifi scan in my android application that scans for wifi access points every 30 secondsi have used timer and timertask to get the scan running correctly at the intervals which i requirehowever i want to be able to stop and start the scanning when the user presses a button and i am currently having trouble stopping and then restarting the timer and timertaskhere is my codetimertask scantaskfinal handler handler new handlertimer t new timerpublic void dowifiscanscantask new timertask public void run handlerpostnew runnable public void run wifimanagerscancontext logdtimer timer set off tschedulescantask 300 30 public void stopscan ifscantasknull logdtimer timer canceled scantaskcancel so the timer and task start fine and the scan happens every 30 seconds however i cant get it to stop i can stop the timer but the task still occurs and scantaskcancel does not seem to work eitheris there a better way to do this or am i missing something in the timertimertask classes,['android'] +44608,can i thisplay the value of an enum with printf is there a oneliner that lets me output the current value of an enum,['c'] +44611,two enums have some elements in common why does this produce an error i have two enums in my codeenum month january february march april may june july august september october november decemberenum shortmonth jan feb mar apr may jun jul aug sep oct nov decmay is a common element in both enums so the compiler saysredeclaration of enumerator maywhy does it say so and how can i circumvent this,['c'] +44615,xmlhttprequest xml response woes with jquery 141 how to force the request response to be processed as plain text i am just playing around with jquery and trying something that ought be simple but it just am not working documentreadyfunction ajax url data a proutes transport id tram t xml l ee error functionxhr stat alerterror success functiondata alertsuccess alertdata the snippet is in a testjs file and included in a testhtml file which is opened in firefox 36 like filectesthtml and altough success is shown the data is empty and through firebug the response for xml thisplaysxml parsing error no element found location moznullprincipal5ac44e502cb645d19cfe0b9850ecdb line number 1 column 1alternatively i tried that addingdatatype texthas no effect the result is still processed as xml probably because the response has contenttype textxml charsetutf8i am able to see the response results through firebug if i setdatatype scriptbut then as it is not actually a valid js script it simply fails firebug thisplays invalid regular expression flag txml version10 encodingutf8 daystypestype routes85 citytit gets better if do the above request in browser and through view source copy the xml to be validated here validateasp it thisplays no errors found so why would not it work through xmlhttprequestwhat am i doing wrongwould it be possible to somehow force the xmlhttprequests response to be processed as textplainbrigesps i have tired the suggested datatype html option forgot to mention initially but the html also does not work and in firebug i can see the same error about parsingmoznullprincipalalso the service providing the xml data is controlled by a third party to which i do not have access either there is a way to do this or i will have to kiss my idea goodbye,['jquery'] +44616,jtextarea new line on shift enter i have added a keylistener to my jtextarea field but it does not behave as i expectedinputtextareaaddkeylistenernew keyadapter public void keypressedkeyevent k if the return button is hit only set to a new line if shift is also down ifkgetkeychar keyeventvk enter ifkisshiftdown inputtextareaappend n else send the message boolean cleantextfield false try sendmessageinputtextareagettext cleantextfield true msgscrollpanesetautoscrollstrue jscrollbar vbar msgscrollpanegetverticalscrollbar if vbargetvalue vbargetvisibleamount vbargetmaximum msgpanesetcaretpositionmsgdocgetlength catch exception ex exprintstacktrace cleantextfield false finally ifcleantextfield inputtextareasettext i want this if the return button is hit and shift is down add a new line if the return button is hit and the shift button is not down no new line but submitnow it behaves like this if i hit the return button and shift is down no line added nothing happens if i hit the return button and shift is not down submitted but if i start typing again it begins on new linedoes someone know how to do what i wantediti tried some other code to detect if the shift button is down ifkgetmodifiersex keyeventshift down mask kgetmodifiers keyeventshift down mask this does not work as well,['java'] +44619,library like fakeweb for python i really like the way fakeweb in ruby can be used to fake http requests when testing is there a similar library or an alternative for python,['python'] +44626,alter mysql table to add comments on columns i have been checking the mysql documentation for alter table and it does not seem to include a way to add or modify a comment to a column how can i do this for tablealter table mytable comment hello world for columns,['mysql'] +44630,view native code from eclipse i have a java application which makes use of native method callsis there a way to view this code in eclipsei can get the source code for this native library but do not know how to link in the ideit will also be helpful if someone tells me how to debug this native method,['java'] +44635,can we resign the already signed jars in java i mean i have jar with old signature and i want it to resign with the new signature so is it possible if yes need little info about how,['java'] +44644,when i kill a pthread in c do destructors of objects on stacks get called i am writing a multithreaded c program i plan on killing threads however i am also using a refcounted gc i am wondering if stack allocated objects get destructed when a thread gets killed,['c++'] +44648,whats the easiest way to find out if two files are different programmatically whats the easiest way to find out if two text files are different programmatically given two files i just need to know whether they are different or not this is for a quick tool to help with a particularly nasty merge switched languages from vb to c in one branch yay and made many changes in the other it would not be going into productionpossible solutionshash both files and compare the hashpull the files in and just do a string comparecall out to an external diff tool unfortunately winmerge does not have a cli for thisif possible ignoring white space would be awesome but i do not care that much about it the main thing is this it needs to be quick and easyi am using net 35sp1 by the way thanks for any ideas or pointers,['.net'] +44652,open source alternatives to oracle coherence are there any open source alternatives to oracle coherencebtw how much does coherence cost anyways,['java'] +44658,a beginner question on database design this is a followup question on my previous onewe junior year students are doing website development for the univeristy as volunteering workwe are using phpmysql techniquenow i am mainly responsible for the database development using mysqlbut i am a mysql designeri am now asking for some hints on writing my first tableto get my hands on itthen i could work well with other tablesthe quesiton is like thisthe first thing our website is going to do is to present a survey to the user to collect their preference on when they want to use the bus serviceand this is where i am going to start my database developmentthe user requirement document specifies that for the surveythere should be customer sidesurvery will be available to customerswith a set of predefined questions and answers and should be easy to fill outbusiness sidesurvery info will be storedoutputed and thisplayable for analysisit doesnt sound too much workand i dont need to care about any php thingbut i am just confused on should i just creat a single table called surveryor two tables survey business and survey customerand how can the database store the infoi would be grateful if you guys could give me some help so i can work alongbecause the first step is always the hardest and most importantthanks,['mysql'] +44665,should i seal all classes i know should not ever be used as a base class should i seal all classes i know should not ever be used as a base class even when there are no tangible performance or security concerns or is this just adding cruft,['c#'] +44667,if you flush the content ob flush of an ajax request the content will get loaded i mean let us that we just make an ajax request and inser the result inside a divresultin the backend the script use ob flush to send the header but not terminate the request until it is terminated with exit or ob flush endthe content will be loaded into the result only when the request terminate exit or ob flush end or it will be loaded every time the script send the header by ob flushupdatei will use jquery load to make the request php to answer it,"['php', 'javascript', 'jquery']" +44673,reprojecting polar to cartesian grid i have a polar rtheta grid which means that each cell is an annulus section containing values of some physical quantity eg temperature and i would like to regrid or reproject these values onto a cartesian grid are there any python packages that can do thisi am not interested in converting the coordinates of the centers of the cells from polar to cartesian this is very easy instead i am looking for a package that can actually regrid the data properlythanks for any suggestions,['python'] +44677,collisions in a real world application heres my problem i am creating a game and i am wondering about how to do the collisions i have several case to analyze and to find the best solution for i will say it beforehand i am not using any third party physics library but i am gonna do it in house as this is an educational project i do not have schedules and i want to learni have 2 types of mesh for which i have to make the collisions for 1 static meshes that move around the screen but does not have any animation2 skinnedboned meshes animatedactually i have this solution quite hacky first of all i have a test against some bounding volume that enclose the full mesh capsule in my case after 1 for the static meshes i divide them manually in blocks on the modeler and for each of these blocks i use a sphereaabb test works fine but its a little messy to slice every mesh p i tried an automatic system to divide the mesh through planes but it gives bad results 2 for the animated mesh atm i am dividing the mesh at runtime into x blocks where x is the number of bones each block contain the vertex for which that bone is the major influencer sometimes works sometimes gives really bad results please note that the divide of the mesh is done at loading time and not each time otherwise it would run like a slideshow dand heres the question what is the most sane idea to use for those 2 case any material for me to study these methods with some sourcecode and explanations would be even better language is not important when i understand the algorithm the implementation is easycan you argument why that solution is better than othersi heard a lot of talk about kdtree octree etcwhile i understand their structure i miss their utility in a collision detection scenariothanks a lot for the answersedit trying to find a kdop example with some explanation on the net still have not found anything any cluesi am interested on how the kdop can be efficiently tested with other type of bounding volumes etcbut the documentation on the net seems highly lacking,"['c#', 'c++']" +44688,method resolution order suppose we havepublic class foobase public void writebyte value something public void writeint value something public class foo foobase public void writedecimal value something than this var writer new foo writerwrite5 calls writedecimal writerwritebyte6 calls writedecimal will call writedecimal overload why and how can i call writeint or writebyte,['c#'] +44690,use boost to get arity and paramerter types of member function boostfunction traits it works just fine for plain vanilla functions the code below works just fine it prints just what is shouldint cdeclint char2intcharinclude boosttype traitshppinclude boostfunctionhppinclude boosttypeofstdutilityhppinclude iostreamusing stdcoutusing stdendlint fooint char return 0int main typedef boost typeoffoo foo type typedef boostfunction traitsfoo type function traits cout typeidfoo typename endl cout function traitsarity endl cout typeidfunction traitsarg1 typename cout typeidfunction traitsarg2 typename endl return 0so the question is how can one do this if foo is a member function of class barstruct bar int fooint char return 0 i have tried countless combinations of these constructs boost typeof increment registration group boost typeof register type boostref boostremove pointer boostbind boostmem fnetc etc no joy,['c++'] +44692,view all todo items in visual studio using ghostdoc i am also using ghostdoc in visual studio 2008 how do i view all todo items and if that is a function already in visual studio or in ghostdoc documentation tool that i use,['c#'] +44696,should i use directinput or windows message loop i am working on a c directx 2d game and i need keyboard and mouse inputwikipedia saysmicrosoft recommends that new applications make use of the windows message loop for keyboard and mouse input instead of directinputso how should i use iti have a gamescreen class whice take care of the drawing and the updatinggame logic i call the draw and the update methods inside a windows message loop thanks,['c++'] +44706,is it possible to close java sockets on both client and server sides i have a socket tcp connection between two java applications when one side closes the socket the other side remains open but i want it to be closed and also i cannot wait on it to see whether it is available or not and after that close it i want some way to close it completely from one sidewhat can i do,['java'] +44727,how can i fool a site that looks at the javascript object navigator to see that i am not on windows i am trying to browse a website however it only works under windows and mac because they use the navigatorplatform from javascript to find out the architecture i am running on of course they also use the browsers user agent but that was easy to spoofhere is the js in question the code responsible for browser detection is at the top is there any way of changing the js file before the site runs or something similar so i can eliminate the checkusing the javascript console yieldsnavigatorplatformlinux i686evidently i changed the browsers user agent but navigatorplatform does not seem to take it is value from the user agentmaybe someone knows how to change the value returned by navigatorplatform because i hate running windows under virtualbox to use this siteeditthis could be of interest because linux users might be artificially denied access to websites and can do nothing about it,['javascript'] +44729,potential pitfalls in using a jms queue i have been asked to design and implement a system for receiving a high volume of automated sensor data from a large number of devices this data will be produced at regular intervals and sent to the server as xml in an http post the devices will keep resending the same data if they do not receive a specific acknowledgment from the server some potentially heavy duty processing of this data will need to occur before it is inserted to a number of tables in the main database via a transaction and additionally some data points will need to be enqueued to be redirected to other external urlsi am planning on using a java application server leaning towards glassfish with a servlet to receive the incoming data i would like to implement some kind of queuing mechanism to store the data temporarily so that the response back to the sensor is not dependent on all the intermediate processing separate independent queues are also a requirement for the data redirection piece after doing some research the two main options seem to be1 install a database on the app server and use tables for the various queues the queues would be processed by a java application either running in the app server or standalone as it is own service2 use a database backed jms solution to implement the queuingi am not that familiar with jms but from what i have read it seems to be the better solution in this case the primary requirement is that no sensor data ever be lost or dropped from the queue before being processed and that it be processed more or less sequentially wed also like to make it easy to halt the processing of some of the queues at certain times but still have them accumulate data and for these messages to never automatically expirewith strategy 1 it is obvious to me how to meet these requirements but it may be less robust and scalable and more complex to develop than strategy 2 since i will need to write my own multithreaded code to handle the various independent queues i am wondering what the potential pitfalls could be in using jms queues for this purpose since i have never worked with them before data integrity is a big issue so i need to make sure jms can guarantee no data loss in the event of a server reboot power outage or if the queue gets very large for some reason for instance could a problem completing transactions to the main database for a period of time potentially cause the jvm to run out of memory crash and lose all accumulated data this would be the nightmare scenario also i was wondering if there would be any way to pause the jms queue processing via an app server admin tool or to easily see whats in the queue i would be enqueuing an object which would be the message xml plus some other data including timestamp received etc i have read a few posts on here that deal with related issues but wanted to get some direct feedback basically i would like to know of instances if any where jms is not an appropriate queuing solution and if this is one of those cases any advice is greatly appreciated,['java'] +44734,sqlite equivilant of postgresqls greatest function postgresql has a useful function called greatest it returns the largest value of those passed to it as documented hereis there any equivalent in sqlite as a note i only need it to work with 2 arguments,['sql'] +44744,if i use class name attribute to has one what do i put in the migration i have a model in my rails app that uses the class name attribute for has oneclass foo activerecordbase has one main bar class name bar endi am a bit unsure what to put in the migration for this class now can i use references what will rails be looking for as the column name for main bar can i do it like thisclass createfoos activerecordmigration def selfup create table foos do t treferences main bar end end def selfdown drop table foos endendthanks,['ruby-on-rails'] +44749,how to show a message only if cookies are thisabled in browser how to show a message only if cookies are thisabled in browser like show if javascript is thisabled,"['javascript', 'html']" +44775,is jaxrs suitable as a mvc framework jaxrs has some mvc support but i wonder if jaxrs is really a good choice to build web application for human useif a user enters wrong or incomplete information in a form it should be thisplayed again like with grails or wicket is there a comfortable way to do this with jaxrsas far as i know the uri mapping does not work correctly if not all required parameters are given or there are type conversion problems with date for example is that correctis there support for internationalized templateshere is an example for a simple jaxrs based gui application but it is really simple and thing like i18n and validation are not thiscussed,['java'] +44780,java charset problem on linux problem i have a string containing special characters which i convert to bytes and vice versathe conversion works properly on windows but on linux the special character is not converted properlythe default charset on linux is utf8 as seen with charsetdefaultcharsetgetthisplaynamehowever if i run on linux with option dfileencodingiso88591 it works properlyhow to make it work using the utf8 default charset and not setting the d option in unix environmentedit i use jdk1613editcode snippetworks with cs iso88591 or csutf8 on win but not in linux string x a12 systemoutprintlnx byte ba xgetbytescharsetfornamecs for byte b ba systemoutprintlnb string y new stringba charsetfornamecs systemoutprintlnyregardsdaed,['java'] +44781,how to render bitmap into canvas in wpf i have subclassed canvas so that i can override its render function i need to know how i can load a bitmap in wpf and render that to the canvas i am completely new to wpf and i have not found any tutorials that show you how to do something so seemingly trivial stepbystep instructions with examples would be great,"['c#', '.net']" +44785,which html parser is the best i code a lot of parsers up until now i was using htmlunit headless browser for parsing and browser automationnow i want to separate both the tasksas 80 of my work involves just parsing i want to use a light html parser because it takes much time in htmlunit to first load a page then get the source and then parse iti want to know which html parser is the best the parser would be better if it is close to htmlunit parsereditby best i want at least the following featuresspeedease to locate any htmlelement by its id or name or tag typeit would be ok for me if it does not clean the dirty html code i do not need to clean any html source i just need an easiest way to move across htmlelements and harvest data from them,"['java', 'html']" +44790,wpf making the entire block of a path clickable i have a special controltemplate for some of my buttonscontroltemplate targettypextype button path namethepath fillwhite stretchuniformtofill width12 height12 strokewhite strokethickness4 datam1515 l105105 m15105 l10515 controltemplatetriggers trigger propertyisfocused valuetrue setter propertyfill valueafa targetnamethepath trigger controltemplatetriggerscontroltemplatethis works fine but since i am using a path in this case it is just shaped like a fat x exactly the path is clickable not the small space between the corners of the x is there any automagic thing i can use to make the entire block of the x clickablei have considered wrapping the path in a rectangular object but i would just like to make sure i am not missing something trivial,['c#'] +44793,subdomains and locally installed rails app i cannot figure out what i am overlooking perhaps it is obvious or lack of understanding the app i am working with uses subdomains which on the hosting server work properly i figured locally installing would kick up some issues around routing so i read up on making changes to etchosts and using the ghost gem both seem to work fine ie localhost30 becomes myapplocal30 but i do not understand how to go about logging into a subdomain account heres an example myapplocal30sessionnew the default login page for the appmyapplocal30signup default signup pagei can create an account here eg sub1 the thank you page is shown w the reference to sub1myappcom which points to the hosted app the local db shows this domain as wellsub1myapplocal manually added to etchosts and dscacheutil flushcachesub1myapplocal30sessionnew is the subdomainlogin attempts return that this is not a valid domain this seems to make sense because the local db shows the url as sub1myappcom on the hosting server so my question is whether there is a local workaround that i can use for development or have i totally missed a fundamental concept along the way,['ruby-on-rails'] +44794,mysql alter a column to be auto increment i am trying to modify a table to make it is primary key column auto increment after the fact i have tried the following sql but got a syntax erroralter table documentalter column document id auto incrementam i doing something wrong or is this not possible version 50750ubuntu102,"['sql', 'mysql']" +44798,example of builder pattern in java api joshua blochs effective java describes a builder pattern that can be used to build objects with several optionally customizable parameters the naming convention he suggests for the builder functions which simulates named optional parameters as found in ada and python does not seem to fall in line with javas standard naming convention java functions tend to rely on a having a verb to start the function and then a nounbased phrase to describe what it does the builder class only has the name of the variable that is to be defined by that functionare there any apis within the java standard libraries that makes use of the builder pattern i want to compare the suggestions in the book to an actual implementation within the core set of java libraries before pursuing its use,['java'] +44802,java junit capture the standard input output for use in a unit test i am writing integration tests using junit to automate the testing of a console based application the application is homework but this part is not the homework i want to automate these tests to be more productive i do not want to have to go back and retest already tested parts of the application standard reasons to use unit testsanyway i cannot figure out or find an article on capturing the output so that i can do assertequals on it nor providing automated input i do not care if the outputinput goes to the consoleoutput pane i only need to have the test execute and verify the the output is what is expected given the input anyone have an article or code to help out with this,['java'] +44806,polymorphism by function parameter ok this may be a very stupid question but it is been bothering meis there a language whereclass animalclass ape public animalvoid dostuffanimal animalptr cout doing animal stuff endlvoid dostuffape apeptr cout doing ape stuff endlanimal ape new apedostuffapewould yield doing ape stuff please bear with me using c syntaxto clarify i want a function that accepts an argument and acts on it according to the type of the argumentand would it make sense of course as a developer youd need to take care since instances that look just like an animal pointer might actually call ape code because at runtime it is an ape instance being pointed to,['c++'] +44807,any tool to show you all elementspages in a site that are affected by a particular css rule of course we can use tools like firebug to highlight portions of html and see what all css is being appliedbut what about the reverse is there some kind of tool which would allow you to highlight a particular css rule and show you all the pages on a site either static html pages or their dynamic templates that it applies toexample i have come to work on a new site very large and i need to edit css on a particular page but in doing so i have no idea how many other pages on the site might also have these class names and hence be affected of course i can try to search the whole site for the class names but this can be time consuming or tricky this site has a class named ba for example guess how many irrelevant pages will turn up if i just search for ba so how about including a double quote ba well it could be in the middle of a few other classes classhz ba top at the end classhz ba etc more so it could be dynamically plugged in via server side code making it even harder to find a tool that could somehow spider your site and be able to identify all the places your css change will affect would be great,"['html', 'css']" +44818,how to serialize a class that contains objects of other classes recursive serializing how can i do this or will the serializer automatically go with recursion and serialize all those child objects into xmlgive me an example how would you serialize classes that contain other classes objects in themselves that was the core of this questioni have tried this and it did not output anything except the xml header to the targeted xml filemy problem is that i need to serialize a simple class that just holds a list object but those entities also hod list objects another plus would be if i could avoid the serialization of some components because some are derived and have dictionaries in thempublic void savecurrentstring mapfilename string mappath world game contentrootdirectory maps mapfilename xml streamwriter mapwriter new streamwritermappath map savedmap new map savedmapentities world entities xmlserializer xserializer new xmlserializersavedmapgettype xserializerserializemapwriter savedmap mapwriterclosethat is the piece of code that does the serializationpublic class map internal string mapname internal string mapdescription internal string mapauthor public listentity entities new listentityand this is the class that is serialized could internals be counted as publics if the serialization is called from the same assembly the code throws exception at the savedmapgettype function and i have tried typeofmap too but without success i guess it is because i need some other way to handle each new class deep serialization how do i do thatalso i have found on some examples that there are no interface inheritance or attributes therefore i did not add those either but i am planning to use ixmlserializable though i do not know how to call another serialization inside writexml implementation,"['c#', '.net']" +44828,php split string into array like explode with no delimiter i have a string such as0123456789and need to split each character into an arrayi for the hell of it triedexplode 123545789but it gave me the obvious warning no delimiter defined in explode how would i come across this i cannot see any method off hand especially just a function,['php'] +44831,rails how to have an image for the submit tag i have been using submit tag helpers submit tag submit i have an image called my imagepng how can i make the submit button be an image i tried submit tag image taglogin smallpng width70 but that does not work,['ruby-on-rails'] +44834,why do abstract classes in java have constructors why does an abstract class in java have a constructorwhat is it constructing as we cannot instantiate an abstract classany thoughts,['java'] +44835,inter thread communication in java how do threads that rely on one another communicate in javafor example i am building a web crawler with threads that need data that comes from other threads,['java'] +44837,access elementtree node parent node i am using the builtin python elementtree module it is straightforward to access children but what about parent nor sibling nodes can this be done efficiently without traversing the entire tree,['python'] +44843,get first list index containing sub string in python for lists the method listindexx returns the index in the list of the first item whose value is x but if i want to look inside the list items and not just at the whole items how do i make the most pythoninc method for thisfor example withl the cat ate the mousethe tiger ate the chickenthe horse ate the strawthis function would return 1 provided with the argument tiger,['python'] +44851,copy folder from iphone resources directory to document directory bool successnsfilemanager filemanager nsfilemanager defaultmanagerautoreleasenserror errornsarray paths nssearchpathfordirectoriesindomains nsdocumentdirectory nsuserdomainmask yesnsstring documentsdirectory paths objectatindex0nsstring documentdbfolderpath documentsdirectory stringbyappendingpathcomponentdbsuccess filemanager fileexistsatpathdocumentdbfolderpathif success returnelse nsstring resourcedbfolderpath nsbundle mainbundle resourcepath stringbyappendingpathcomponentdb filemanager createdirectoryatpath documentdbfolderpath attributesnil filemanager copyitematpathresourcedbfolderpath topathdocumentdbfolderpath errorerror like thisresourcesdbwordscsv db folder copy documentdbwordscsvi want to copy db subdirectory at resources folder i thought that source is good but that source makes folder and does not copy files in db folder at resources folder i really want to copy files in db folder at resources folder please help me,"['iphone', 'objective-c']" +44876,can i get tomcat running as a service to dump heap i am attempting to have tomcat which is currently running as a service on a windows 2003 box dump heap on an outofmemoryerrortomcat is running hudson which is reporting a heap space problem at the tail end of my build running the build manually produces no such error the hudson guys need a heap dump to get startedas instructed elsewhere i have told the apache service monitor to configure the jvm it uses to run tomcat to dump heap when an outofmemoryerror is encountered by adding the following to the jvm optionsxxheapdumponoutofmemoryerrorthen i run the build again sure enough it reports there was a heap error i scan the entire thisk looking for the default java pid123hprof file where obviously 123 is replaced by the pid of the jvm no hprof files exist anywherei am caught in a catch 22 i need the heap dump for the hudson guys to fix their memory leak but i cannot get the heap dump if i run hudson under tomcatis there some special way when tomcat is running as a windows service to get a heap dump from it on an outofmemoryerrorthe other thing i have tried is to tell it on the startup and shutdown tabs to use the java option instead of the jvm option i believe this should tell the service manager to attempt to start tomcat with a java executable command instead of launching the jvmdll directly when i do this the service would not startsurely someone else has had a similar problem,['java'] +44877,are there any objectivec web frameworks are there any objectivec web frameworks the only frameworks i have found is frothkiti am primary looking for a way to write restful json web services in objectivec,['objective-c'] +44883,how important is it to select the smallest possible data type when designing a database how much of a difference does using tinyint or smallint when applicable instead of just int do or restricting a char field to the minimum characters neededdo these choices affect performance or just allocated space,['mysql'] +44884,aspnet subdomain cookie parent and one subdomain i have an app with multiple subdomains suboneparentcom subtwoparentcom i have a logon page at parentcomlogin when a user logs in i redirect them to the proper domain based on which one they are a member of this works fine formsauthenticationticket ticket new formsauthstring encticket formsauthenticationencryptticketvar cookie new httpcookieformsauthenticationformscookiename encticketcookiedomain suboneparentcomresponsecookiesaddcookiethis properly authenticates the user for suboneparentcom and not subtwoparentcom however i would like to do the followingif the user goes back to parentcom i would like to know that they are logged in and redirect them back to suboneparentcomis there a best practice for accomplishing this or do i have to set another cookie for parentcomi am working in aspnet mvc if it mattersthanks,['asp.net'] +44885,how to organize all js css php and html code now i know that you can use oop and mvc to organize but that is just for phplet us say i add a new window that pops up when a user clicks on a link and it thisplays a form with js validations and it is css styledhere we got 4 codes js css php and html with some php snippetshow would you organize all these codes because when i got 50 windows codes are spreaded everywhere and for me to change behaviour of delete a window i have to play detective i crunch everytime i have to add a new window with js css and so oni have thought about the structure wouldnt it be better if you got a separate module for each one of the window eg a folder for each one of the window in that map you place one css one js one php and one htmlfile then you got a very nice structure that are not messy and you dont mix all windows with each other in one big js and css filewhat do you think and i would appreciate suggestions of how to organize these 4 kind of codes,"['php', 'javascript', 'html', 'css']" +44886,how to use winapi functions in java i am doing a project in java which has the function to add files in database and i want to use winapi functions to select fileshow would i do that,['java'] +44894,automatically detect web browser window width change i know that you with windowwidth can get the size of the web browseri want to detect when the user change the size of his web browser so i could readjust the columns width is there a way to automatically detect this or do i have to use settimeinterval to loop and see if it has changed,"['javascript', 'jquery']" +44898,how to differentiate between http and cli requests the title is quiet straightforward i have to know on server side if the script called through http request or by command line i could examine the serverargv or serverargcwhat is the pragmatic way to do that,['php'] +44901,jquery position problem with chrome when i alert the value positionleft it returns 0 on chrome with other browsers it returns the actual number why does this happen,['jquery'] +44917,what is difference between header and include where which one should be used i am confused with two terms 1header locationhomepage php2includehomepagephpi am guessing that header is used after checking password procedure and about include you can use it anywhere but i am not sure what is actual difference between them and at what place out of these two one should be used,['php'] +44923,how can i determine the type of object an arraylist iterator will return next i have an arraylist and i am using an iterator to run through it i need to find out what type of object is nextiterator vehicleiterator vehiclearraylistiteratorwhilevehicleiteratorhasnext how do i find the type of object in the arraylist at this point for example is it a car bus etc thanks,['java'] +44932,function template overloading can anybody summarize the idea of function template overloading what matters template parameter or function parameter what about the return valuefor example given a function template templatetypename x typename y void funcx x y y whats the overloaded function template1 templatetypename x void funcx x int y 2 templatetypename x typename y x funcx x y y 3 templateclass x class y class z void funcx x y y z z,['c++'] +44941,hittesting svg shapes the browsers which have implemented parts of the svg spec firefox etc do hittesting for us for free if i attach a mousedown listener on an svg object i get notified whenever the shape is clicked this is amazing especially for complex polygon shapesi am wondering if there is a way i can utilize this feature for a bit more hit testing i want to know if a given rectangle intersects any of my svg shapes for example i add 3 complex polygons to my element now i want to know if rectangle 40 40 100 100 intersects any of them does anyone have an idea how i could possibly hook into the already great hittesting support available instead of adding all this code myselfthanks,['javascript'] +44949,migrating from javadoc to python documentation so i have gotten somewhat used to javadoc style documentation looking through various examples of python code i am finding that at first blush the documentation seems to be missing a lot of informationthe good vary rarely do you see selfevident bits of documentation docstrings are usually a paragraph or less of english markup that integrates instead of standing out on separate linesthe bad in conjunction with pythons ducktyping i find that many functions are unclear about the parameters they expect there is no type hinting duckhinting and often times it would be nice to have some idea that the parameter should be listlike stringlike streamlikeof course javadoc was designed for a lowerlevel language without great introspection abilities of python which might account for the less verbose documentation philosophyany advice on python documentation standards and bestpractices,['python'] +44950,sscanf in python i am looking for an equivalent to sscanf in python i want to parse procnet files in c i could do something like thisint matches sscanf buffer d 6409afafx 6409afafx x xx xx x d d ld 512sn local addr local port rem addr rem port inodei thought at first to use strsplit however it does not split on the given characters but the sep string as a whole lines openprocnetdevreadlines for l in lines2 cols lsplitstringwhitespace print lencols1which should be returning 17 as explained aboveis there a python equivalent to sscanf not re or a string splitting function in the standard library that splits on any of a range of characters that i am not aware of,['python'] +44986,why would margin not be contained by parent element when an element with a margin is contained within another element the parent does not consistently wrap that marginmany things will cause the parent to wrap the childs marginbordersolidpositionabsolutethisplayinlineblockoverflowautoand this just from small testing no doubt there is morei would assume this has to do with collapsing margins butthe w3c spec page has no description of such behaviorthere is no overlapping margins herebehavior of all browsers seems to be consistent on this issuethe behavior is affected by triggers that are not related to the margins what is the logic by which an element which defaults to overflowauto should contain different material than the one where the overflow is set to autowhy should everything but the default behavior of a regular div assume that the margin is contained by the parent and why should the regular default not include the marginedit the final answer is that the w3c really does specify this behavior but thatthe specs do not really make any sensethe specs mix without any word of explanationfree margins margins that would touch the top or bottom of their parent are not contained by the parent andcollapsed margins adjacent margins are allowed to overlapdemodoctype htmlhtmlheadtitlemargins overextending themselvestitlemeta httpequivcontenttype contenttexthtmlcharsetutf8 style typetextcss body margin0 divb backgroundcolorgreen divib thisplayinlineblock backgroundcolorred divpa backgroundcoloryellow positionabsolute bottom0 right0 divoa backgroundcolormagenta overflowauto divbrdr backgroundcolorpink bordersolid h1margin100px width250px bordersolidstyleheadbodydiv classb h1is the margin containedh1divdiv classib h1is the margin containedh1divdiv classpa h1is the margin containedh1divdiv classoa h1is the margin containedh1divdiv classbrdr h1is the margin containedh1divbodyhtml,"['html', 'css']" +44989,how to run all tests belonging to a certain category in junit 4 junit 48 contains a nice new feature called categories that allows you to group certain kinds of tests together this is very useful eg to have separate test runs for slow and fast tests i know the stuff mentioned in junit 48 release notes but would like to know how i can actually run all the tests annotated with certain categorythe junit 48 release notes show an example suite definition where suiteclasses annotation selects the tests from certain category to run like thisrunwithcategoriesclassincludecategoryslowtestsclasuiteclasses aclass bclass note that categories is a kind of suitepublic class slowtestsuite will run ab and bc but not aadoes anyone know how i could run all the tests in slowtests category it seems that you must have the suiteclasses annotation,['java'] +45004,is there any difference between date sub and using arithmetic operators for datetime calculation after i have seen a lot of questions here using the date sub or date add functions instead of the arithmetic operators or i was wondering if there was any differencequote from the mysqlmanualdate arithmetic also can be performed using interval together with the or operatordate interval expr unitdate interval expr unitso basically these two statements return the same resultselect date addnow interval 7 dayandselect now interval 7 daynow my questionis there any difference between date sub and using the operator in mysql besides readability,['mysql'] +45009,filter files in a very large folder i have a folder with 100k text files i want to put files with over 20 lines in another folder how do i do this in python i used oslistdir but of course there is not enough memory for even loading the filenames into memory is there a way to get maybe 100 filenames at a timeheres my codeimport osimport shutildir somedirdef file lenfname f openfnamer for i l in enumeratef pass fclose return i 1filenames oslistdirdirlabelsi 0for filename in filenames flen file lendirlabelsfilename print flen if flen 15 i i1 shutilcopyfilediroriginalsfilename5 dirfilteredorigsfilename5print iand outputtraceback most recent call last file filterimagepy line 13 in module filenames oslistdirdirlabelsoserror errno 12 cannot allocate memory somedirheres the modified scriptimport osimport shutilimport globtopdir somedirdef filelenfname many f openfnamer for i l in enumeratef if i many fclose return true fclose return falsepath ospathjointopdir labels i0for filename in globiglobpath print filename if filelenfilename5 i 1print iit works on a folder with fewer files but with the larger folder all it prints is 0works on linux server prints 0 on mac oh well,['python'] +45014,how can i reorder a list in python if i have a list abcde how can i reorder the items in an arbitrary manner like dcabeedit i do not want to shuffle them i want to reorder them in a predefined manner for example i know that the 3rd element in the old list should become the first element in the new list,['python'] +45021,guid null should not be allowed by the compiler possible duplicatec okay with comparing value types to null the behaviour described below is specific to net35 onlyhelloi just ran across the most astonishing behavior in the c compileri have the following codeguid g1 guidemptybool b1 g1 nullwell guid is not nullable therefore it can never be equal to nullthe comparison i am making in line 2 always returns falseif you make the same thing for an integer the compiler issues an warning saying the result will always be falseint x0bool b2 xnullmy question is why does the compiler lets you compare a guid to nullaccording to my knowledge it already knows the result is always falseis the builtin conversion done in such a way that the compiler does assume null is a possible valueam i missing anything herethanks,"['c#', '.net']" +45024,using a database table as a queue i want to use a database table as a queue i want to insert in it and take elements from it in the inserted order fifo my main consideration is performance because i have thousands of these transactions each second so i want to use a sql query that gives me the first element without searching the whole table i do not remove a row when i read itdoes select top 1 help hereshould i use any special indexes,['sql'] +45026,sql server in statement item order for performance given the sql statementselect from my tablewhere somenumberfield in 09if i can guarantee that the majority of rows in my table have somenumberfield set to 9 and can project that this will remain the case indefinately is it better to write the above query like thisselect from my tablewhere somenumberfield in 90,['sql'] +45033,how do i group windows form radio buttons how can i group the radio buttons in windows form application a lot like aspnets radiobuttonlist so i can switch between each case chosen from the options,"['c#', '.net']" +45035,async httpwebrequest with no wait from within a web application in my web application aspnet i have a block of code that uses httpwebrequest to make a call to a rest service and continue execution right now it is taking longer than i would like to complete the full web request the thing is that what the rest service returns is not useful ideally i would like to send an async web request to the rest service and then not wait for a response the problem is that i have tried it out using requestbegingetresponsenew asynccallbackaddressof myfunc nothingto start an async request and instead of not waiting which i would assume would be the default behavior of an async request it continuously executes the callback function before executing the next line of code after begingetresponsei am suspecting that aspnet may convert it to a sync request when it is within a web application i am led to believe this because there is a iasyncresult result object that is passed into the callback function and when i examine its completedsynchronously property it is always set to true does anyone know if it is possible to do an async httpwebrequest with no wait from within an aspnet web application or is it always converted to a synchronous request,['asp.net'] +45039,sql update undo is there a way we can undo a sql update query,['sql'] +45040,defining a structure in c with malloc i asked a question earlier on defining a structure using mallocthis was the answer i was given by the majoritystruct retvalue st mallocsizeofsti was showing a friend my code and we came to a stumbling blockcould someone please explain why this code works from my viewpoint st has not been defined when you malloc it so there could be any kind of garbage in there it should be mallocsizeofstruct retvalue thanks for any help,['c'] +45043,is there a way to save the java jit information for the next run so that i do not have to warm up the code every day i have a java process that runs every day and takes about 10 or 20 hits before it is fully optimized by the jit what i would like to do is save the jit info so that the next day it can start in an optimized state it seems like this should be possible but i have not been able to find any method for doing so,['java'] +45053,how to generate android testing report in html automatically i would like to automatically generate unit testing report in html format for android application on hudson continuous integration servertherefore i try to run test cases first and gather test result files in xml format then i use junitreport task to transform the xml result files into html format i run test cases through android instrumentation framework however it only provides verbose output information rather than the standard junit xml format i have no idea how to generate html unit test report without junit xml result filesif i run test cases using eclipse it can export results in xml files with time consumed information per test case those xml files can be transformed into html by junitreport task correctly as a result it seems that it is possible to collect the test result with time consumed informationis there any way to get the standard junit xml result file automatically after running test cases on android instrumentation framework,['android'] +45059,get image height and width as integer values i have tried to use the php function getimagesize but i was unable to extract the image width and height as an integer valuehow can i achieve this,['php'] +45061,jquery innerfade fading weirdly on ie7 i am wrapping up a new site and i am using the innerfade plugin on the sites homepage for some reason the fading is slow and choppythe only other thing javascriptwise is the fancy zoom but i have already removed it etc with no changeany thoughts other posts are pointing to css issues,"['jquery', 'css']" +45062,pass c string to c and pass c result string char whatever to c i tried different things but i am getting mad with interophere the word string is not referred to a variabile type but a collection of chari have an unmanaged c function defined in a dll that i am trying to access from c this function has a string parameter and a string return value like thisstring myfunctionstring inputstringwhat should be string in c side and c one and what parameters need dllimport for this,"['c#', 'c++']" +45065,whats the best way to do user authentication in php i have been simply writing 2 cookies 1 containing the user id and the 2nd containing 12 the sh1 hash of the password salted the way it works is selfevident i realized that i wasnt doing this in the most secure way whats a better way of doing this preferably using a single authentication cookiealso is there a point to using hard to calculate hashes by that i mean using bcrypt or hashing each item 10 times with whirlpool to make it a relatively slow hash function 200 ms vs less than 1 ms just plain sha1 i mean if someone breaches your db and gets the hashes what is there left to protect since all your data is in the same db unless you have some sort of a decentralized setup which i dont,['php'] +45069,experiences with escape analysis enabled on the jvm i have just tried the xxdoescapeanalysis option enabled on a jdk6u18 vm on solaris and had a rather thisappointing experience i am running a scala application which has rather a lot of actors 20 of them this is a recipe for garbagecreationtypically the app can run with 256mb of heap but generates huge amounts of garbage in its steady state itspends 10 of time in gcgenerates 150mb of garbage in 30s which then gets gcdi thought that escape analysis might help so i enabled the option and reran the app i found that the app became increasingly unable to clear away the garbage it had collected until it seemed eventually to spend the entire time doing gc and the app was flatlining at its full allocationat this point i should say that the app did not throw a outofmemoryerror which i would have expected perhaps jconsole which i was using to perform the analysis does not properly thisplay gc stats with this option on i am not convincedi then removed the option and restarted and the app became normal again anyone have any idea what might be going on,['java'] +45074,why does the controllers action have httprequestbase and the viewpage has httprequest my methods take httprequestbase as arguements and i am finding it strange as to why the actions in controllers have access to httprequestbase but the view pages have httprequestis there a reason for this or just something that was not thought through,"['c#', 'asp.net']" +45083,setting up a deployment build ci cycle for php projects i am a lone developer most of my time working on a number of big mainly phpbased projects i want to professionalize and automate how changes to the code base are handled and create a continuous integration process that makes the transition to work in a team possible without having to make fundamental changes what i am doing right now is i have a local test environment for every project i use svn for each project changes are tested locally and then transferred to the online version usually via ftp api documentation is generated manually from the source code unit tests are something i am getting into slowly and it is not yet part of my daily routinethe build cycle i am envisioning would do the followinga changeset gets checked into svn after having been tested locallyi start the build process the svn head revision gets checked out modified if necessary and made ready for uploadapi documentation gets generated automatically if i have not set it up in detail yet using a default template scanning the whole code basethe new revision is deployed to the remote location via ftp including some directory renaming chmodding importing databases and the likes this is something i already like phing for very much but i am open for alternatives of courseunit tests residing in a predefined location are run i am informed about their failure or success using email rss or preferably html output that i can grab and put into a web pageoptionally a enduser changelog text file in a predefined location gets updated with a predefined part of the commit message it is now possible to filter for both foo and bar at the same time this message is not necessarily identical with the svn commit message which probably contains much more internal informationstuff like code metrics code style checking and so on are not my primary focus right now but on the long run they certainly will solutions that bring this outofthebox are very kindly looked uponi am looking forfeedback and experiences from people who are or were in a similar situation and have successfully implemented a solution for thisespecially good stepbystep tutorials and walkthroughs on how to set this upsolutions that provide as much automation as possible for example by creating a skeleton api test cases and so on for each new projectand alsoproduct recommendations what i know so far is phingant for building and phpundercontrol or hudson for the reporting part i like them all as far as i can see but i have of course no detailed experience with themi am swamped with work so i have a strong inclination towards simple solutions on the other hand if a feature is missing i will cry about it being too limited pointandclick solutions are welcome too i am also to commercial product recommendations that can work with php projectsmy setupi am working on windows locally 7 to be exact and most client projects are run on a lamp stack often on shared hosting no remote sshi am looking for solutions that i can run in my own environment i am ready to set up a linux vm for this no problem hosted solutions are interesting for me only if they provide all of the aspects described or are flexible enough to interact with the other parts of the processbounty i am accepting the answer that i feel will give me the most mileage there is a lot of excellent input here i wish i could accept more than one answer thanks everyone,['php'] +45086,how do you vertically align images within a list or a div i have the following code for showing some imageshtmldiv classfooterlogos ul liimg srcsitesdefaultfilesimagefield thumbsall ears cambodia logo 1png alt classfirstli liimg srcsitesdefaultfilesimagefield thumbsmlf revjpg alt classli liimg srcsitesdefaultfilesimagefield thumbstamtf ajpg alt classli liimg srcsitesdefaultfilesimagefield thumbsunltdlogopng alt classli liimg srcsitesdefaultfilesimagefield thumbscecilys high resjpg alt classli liimg srcsitesdefaultfilesimagefield thumbsstreet child africajpg alt classlastli uldivcssfooterlogos textaligncenterfooterlogos img marginleft20pxmarginright20pxfooterlogos imgfirst footerlogos imglast footerlogos ul footerlogos ul li thisplay inline liststylenonethis produces images that look likebut i would like it to center the logos vertically so it looks likei have tried vertically aligning everything through css but that does not really work unless i am using a table so anyway i can get the desired effect without using a table rowupdate 1the images that are produced can be of different heights thus cannot use a fixed height css element,"['html', 'css']" +45102,php zend framework how to get request uri fragment from request object say eg i have a uri that takes me to the someaction action of the somecontroller controller from there i am able to retrieve the request object via thisgetrequesti am also able to retrieve various information regarding the uri from the request objectbut how can i retrieve the fragment ie the 12345 part after the in the eg neither getrequesturi nor getparams turn up the fragment partthanks,['php'] +45106,c compiler error with crtp i have the following class hierarchytemplate typename tclass basepublic void f class class a public baseclass a class class b public baseclass b public class a using baseclass bf int main class b b bf return 0comeu and intel c v11 claim all is well however gcc 441 and vc 2008 seem to complain egg pedantic wall o test testcpp testcpp in function aint mainatestcpp5 error avoid basetf with t class ba is inaccessibletestcpp14 error within this context i believe the code is well formed as it is however i could be wrong i am hoping someone from the so c community could provide some insight into this issuenote adding public before the using directive in class b resolves the issue for both gcc and vs should the accessor section of the class in which the using directive is applied override the derivation mode public private of the base classin short is thisa compiler error if so which compiler gccvs or comeuintelis the above code well formeddoes the accessor section in which a using directive is called override the derivation mode of the base,['c++'] +45112,need basic help parsing a string in c c is not my preferred languagei have a file that contains this e 225370 3575i want to separate e 225 370 35 and 75 from each other into a char and ints but i am having trouble i tried doing everything i found online and in my c book and still it is not working out please helpi would have an easier time doing this in java,['c++'] +45127,the application cannot be opened because its executable is missing i have an application that i have been developing for some time now recently launching the application via a double click presents a dialog that says you cannot open the application repowatch because it may be damaged or incompletelaunching the application via open repowatchapp gives me the application cannot be opened because its executable is missingi usually launch the application via repowatchappcontentsmacosrepowatch simply out of habit which does work so i am unsure how long this has been happening or what change happened immediately before hand the most likely change is that i put cp infoplist repowatchappcontents into my make file in order to version infoplist without versioning everything in the app bundlei have looked at infoplist many times and cannot find anything wrong with it the file opens up with property list editor without any errors saving from property list editor does not make the file work if it is to blame in the first placethe permissions as far as i can tell also look sane ls lrepowatchappcontentsinfoplistrwrwr 1 dgrace staff 789 feb 1 2320 repowatchappcontentsinfoplist ls lapplicationsadiumappcontentsinfoplistrwrwr 1 dgrace staff 5750 aug 21 1541 applicationsadiumappcontentsinfoplisti am at a loss as to what to try nextand here are the contents of infoplist even though nothing has really changed in quite a whilexml version10 encodingutf8doctype plist public appledtd plist 10en plist version10dict keycfbundleinfodictionaryversionkey string60string keycfbundledevelopmentregionkey stringenglishstring keycfbundleexecutablekey stringrepowatchstring keycfbundleidentifierkey stringcomdoomstickrepowatchstring keycfbundlenamekey stringrepowatchstring keycfbundleshortversionstringkey string100string keylsminimumsystemversionkey string106string keycfbundleversionkey stringbeta26string keynsmainnibfilekey stringmainmenustring keynsprincipalclasskey stringnsapplicationstringdictplist,['objective-c'] +45135,multi language support in jspservlet how to provide multi language support through jspservlet how to include static data of different languages at run time on basis of language selected,['java'] +45149,how to define index by several columns in hibernate entity morningi need to add indexing in hibernate entity as i know it is possible to do using index annotation to specify index for separate column but i need an index for several fields of entityi have googled and found jboss annotation table that allows to do this by specification but i do not know why this functionality does not work may be jboss version is lower than necessary or maybe i do not understant how to use this annotation but complex index is not created why index may not be createdjboss version 423gaentity examplepackage somepackageimport orghibernateannotationsindeximport javaxpersistencecolumnimport javaxpersistenceentityimport javaxpersistencegeneratedvalueimport javaxpersistenceidentityorghibernateannotationstableappliesto housetable name indexes indexname idx xdn dfn columnnames housexdn housedfn public class house public final static string table name house public final static string xdn xdn public final static string dfn dfn id generatedvalue private long id columnname xdn private long xdn columnname dfn private long dfn column private string address public long getid return id public void setidlong id thisid id public long getxdn return xdn public void setxdnlong xdn thisxdn xdn public long getdfn return dfn public void setdfnlong dfn thisdfn dfn public string getaddress return address public void setaddrestring address thisaddress address when jbosshibernate tries to create table house it throws following exceptionreason orghibernateannotationexception orghibernateannotationstable references an unknown table house,['java'] +45156,java integer to byte array i got an integer 1695609641when i use method string hex integertohexstring1695609641systemoutprintlnhex gives6510f329but i want a byte arraybyte bytearray new byte byte 0x65 byte0x10 byte0xf3 byte0x29how can i make this,['java'] +45165,backgroundworkers never stop being busy for do it a bunch of times while backgroundworker1isbusy backgroundworker2isbusy backgroundworker3isbusy backgroundworker4isbusy backgroundworker5isbusy systemthreadingthreadsleep01 if backgroundworker1isbusy backgroundworker1runworkerasync else if backgroundworker2isbusy backgroundworker2runworkerasync else if backgroundworker3isbusy backgroundworker3runworkerasync else if backgroundworker4isbusy backgroundworker4runworkerasync else if backgroundworker5isbusy backgroundworker5runworkerasync it runs five times every bgworker once and gets stuck in the while do not the backgroundworkers ever stop being busy how do i check availability note there are 5 worker threads this assures none of them is ever stopped always assigning work to them but they refuse to tell me when they are available i thought that would have a simple solutionedit requestactually it was only a dummy parameter i removed it and forgot to get it out i only use it to call the dowork who does the dirty jobprivate void backgroundworker1 doworkobject sender doworkeventargs e timeconsumingfunctionpublicstringand the timeconsumingfunction does end stepping into it in the debugger and running line per line it goes until the end and arrives in the final that means it ends right edit answerit worked by just replacing the linesystemthreadingthreadsleep01withapplicationdoeventsi guess it would run the background but not receive the answer and not update the isbusy tagsthanks everybody great answers helped a lot,"['c#', '.net']" +45168,android how to thisable list items on list creation i am pretty new to android dev and still working out a lot of thingsi have got a main menu showing using the following code but cannot work out how to thisable selected items in the menu can anybody help me with some sample codepublic class listtest extends listactivity override public void oncreatebundle savedstate superoncreatesavedstate setlistadapterarrayadaptercreatefromresourcethis rarraymainmenu androidrlayoutsimple list item 1 not sure how to thisable list items here protected void onlistitemclicklistview list view view int position long id can thisable items when they are clicked on viewsetenabledfalse and i have a stringarray in my stringsxml filexml version10 encodingutf8resources stringarray namemainmenu itemitem 1item itemitem 2item itemitem 3item stringarray resourcesthank you,"['java', 'android']" +45178,how to optimize net applications to 64bit in visual studio build configuration manager you can choose the target platformwhat does it changeis there any other way i can optimize my net app when targeting x64 platforms,['.net'] +45195,find out what classes implement an interface in netdocumentation this might be a bit silly but where can i find a reference not code that tells me what classes in the netframework implement an interface is this even availablei am thinking of the list one gets in the javaapidocumentation unter all known implementing classes like here for example currently i am wondering what classes implement idictionary if this matters but i had this problem a few times nowby the way i found threads explaining how to do this in code like this one kind regards,['.net'] +45196,difference between getcwd and dirname file which should i use in php what is the difference betweengetcwddirname file they both return the same result when i echo from cliecho getcwdnecho dirname file nreturnshomeuserdesktoptestinghomeuserdesktoptestingwhich is the best one to use does it matter what to the more advanced php developers prefer,['php'] +45205,how to enable php short tags i have a web application on a linux server which starts with i needed to copy this application to a windows environment and everything is working fine except that an sql statement is being rendered differently i do not know if this has to do with the script beginning with php instead of because i do not know from where to enable the from the phpini so i changed it to phpi know that these 2 statements are supposed to mean the same but i need to test it with in order to ensure that the application is exactly the same this way i can eliminate another possibilitythanks,['php'] +45215,how to get design mockup as a overlay for quicker development without using firefoxs pixel perfect plugin this is ff pluginpixel perfect is a firefoxfirebug extension that allows web developers and designers to easily overlay a web composition over top of the developed htmlread more how to get mockup image behind all div like this plugin does this tool only shows design behind layout only on firefox and i want to see on all browser,"['html', 'css']" +45216,jquery does remove really remove i am trying to remove a table row using jquery and while it thisappears from the screen and therefore appears to work in firebug i can still see the code for it there are form elements in this row and so i want to understand whether the row is truly being deleted or not because i wouldnt want those values submitted so does remove really remove below is the code i am using maybe i am doing it wrongifdelete deleteliveclick functionevent thisclosesttrremove,['jquery'] +45219,drag elements around with gravity effect i want to accomplish something similar to what photoshopcom has and this site here gravitydoes anyone know how to do this with javascript preferably jquery,['javascript'] +45227,usage of automapper when property names are different we are using automapper from codeplex and for me the destination object has all the properties ending with field ie cityfield and the source object has just cityi can use the below code to achieve but all of the properties are just suffixed with field and there are 20 propertiesformemberdest destcityfield opt optmapfromorigin origincityis there any other way to ignore field word when mapping and so that it can map without using formember 20 times,['c#'] +45231,when to use an autoincremented primary key and when not to i am trying to figure out the best practices for deciding whether or not to add an autoincrementing integer as the primary key to a tablelet us say i have a table containing data about the chemical elements the atomic number of each element is unique and will never change so rather than using an autoincrementing integer for each column it would probably make more sense to just use the atomic number correctwould the same be true if i had a table of books should i use the isbn or an autoincrementing integer for the primary key or a table of employees containing each persons ssn,['sql'] +45232,thisable autocomplete via css is it possible to use css to thisable autocomplete on a form element specifically a textfieldi use a tag library which does not permit the autocomplete element and i would like to thisable autocomplete without using javascript,"['html', 'css']" +45243,feed rendered jsp pages through htmltidy i have a java project running on glassfish that renders some ugly looking html its a side effect from using various internal and external jsp libraries i would like to set up some sort of postrender filter that would feed the final html through htmltidy so that the source is nice and neat to aid debugging is this possibleis there a built in mechanism to perform some action after the server renders the jsps into html can that action get the generated html as a string and manipulate it is there some easy builtin option to do this without extra coding,['java'] +45251,using google maps without api keys i am developing a cms that will use more than one domain and i have to use only one google map script in my page is there a way to use google maps without api key otherwise it is not working,['asp.net'] +45255,using phpapache to restrict access to static files html css img etc lets say you have lots of html css js img and etc files within a directory on your server normally any user in internetland could access those files by simply typing in the full url like so now what if you only want authorized users to be able to load those files for this example lets say your users log in first from a url like this how would you allow the logged in user to view the indexhtml file or any of the files under staticfiles but restrict the file to everyone elsei have come up with two possible solutions thus farsolution 1create the following htaccess file under staticfilesoptions followsymlinks rewriteengine on rewriterule authorizephpfile1 ncand then in authorizephpif isloggedinuser readfilestaticfiles requestfileelse echo deniedthis authorizephp file is grossly over simplified but you get the ideasolution 2create the following htaccess file under staticfilesorder denyallowdeny from allallow from 0and then my login page could append that htaccess file with an ip for each user that logs in obviously this would also need to have some kind of cleanup routine to purge out old or no longer used ipsi worry that my first solution could get pretty expensive on the server as the number of users and files they are accessing increases i think my second solution would be much less expensive but is also less secure due to ip spoofing and etc i also worry that writing these ip addresses to the htaccess file could become a bottleneck of the application if there are many simultaneous users which of these solutions sounds better and why alternatively can you think of a completely different solution that would be better than either of these,['php'] +45283,differences between methods of reloading pages windowlocationreloadhistorygo0windowlocationhrefwindowlocationhrefi noticed a website commenting that all 3 of these methods could be used to reload a page not content to trust it i tried all 3 methods in ie8 ff3 and opera 10 i noticed firefox performed a cache reload instead of a true reload for historygo0 but otherwise saw no differences however i thought i would ask the community here what differences they were aware of between these methods,['javascript'] +45287,static library inspector for windows i know there are tools like pe explorer for inspecting the contents of dlls on windows exported symbols etc is there something similar for static libraries i am linking against a third party library that is generating some linking errors and i want to double check that the symbols i expect are indeed being provided,['c++'] +45290,how do i thistribute a opensource vala project one of the only languages that compiles to a high level language such as c vala has interested me for quite a bit i have been wanting to start a small project with it but i have been wondering how i would thistribute itthe fact is that it compiles to c code c99 i suppose can i thistribute the c code insteadof the vala codeif i do is the c code compatible with all platformsor does it for example when using sockets include the appropriate stuff winsockh for windows automatically,['c'] +45291,convert short to byte in java how can i convert a short 2 bytes to a byte array in java egshort x 233byte ret new byte2it should be something like this but not sure0xff 8 x 0editalso you can usejavaniobyteordernativeorderto thiscover to get whether the native bit order is big or small in addition the following code is taken from javaiobits which doesbyte arrayoffset to booleanbyte array to charbyte array to shortbyte array to intbyte array to floatbyte array to longbyte array to doubleand visa versa,['java'] +45292,is fastcall really faster is the fastcall calling convention really faster than other calling conventions such as cdeclare there any benchmarks out there that show how performance is affected by calling convention,['c++'] +45298,net xsd importer creates unserializable class i am using the net xsdexe importer to generate c classes from a collection of xsd files when i tried to serialize one of the classes to xml it failed invalidoperationexception and when i dug into it i thiscovered it one of the created classes appears to be wrong here is the pertinent xsd codexsdcomplextype namesuccesstype xsdannotation xsddocumentationindicates in a response message that a request was successfully processedxsddocumentation xsdannotation xsdsequence xsdelement refwarnings minoccurs0 maxoccursunbounded xsdsequencexsdcomplextype snip xsdelement namewarnings typewarningstype xsdannotation xsddocumentationthe processing status of a business message and any related warnings or informational messagesxsddocumentation xsdannotationxsdelement snip xsdcomplextype namewarningstype xsdannotation xsddocumentationa collection of warnings generated by the successful processing of a business messagexsddocumentation xsdannotation xsdsequence xsdelement refwarning maxoccursunbounded xsdsequencexsdcomplextype snip xsdelement namewarning typewarningtype xsdannotation xsddocumentationdefines details of a warning that occurred during message processingxsddocumentation xsdannotationxsdelement snip xsdcomplextype namewarningtype xsdannotation xsddocumentationdefines details of a warning that occurred during message processingxsddocumentation xsdannotation xsdsequence xsdelement refwarningcategory xsdelement refwarningcode xsdelement refwarningshortmessage xsdelement refwarningmessage xsdsequencexsdcomplextypeand here is the c code generated from itpublic partial class successtype private warningtype warningsfield remarks systemxmlserializationxmlarrayitemattributewarning typeofwarningtype isnullable false public warningtype warnings get return thiswarningsfield set thiswarningsfield value it made warnings an array of an array of warningtype when i attempt to serialize that to xml i get an invalidoperationexception exceptionunable to generate a temporary class result1error cs0030 cannot convert type warningtype to warningtypeerror cs0030 cannot convert type warningtype to warningtypeerror cs0029 cannot implicitly convert type warningtype to warningtypeerror cs0029 cannot implicitly convert type warningtype to warningtypebut if i change the generated code from warningtype to warningtype then it serializes fineshort of editing the generated c class whenever i regenerate this which hopefully will be less frequently going forward is there any other solution is this a bug in xsdexe or is the xsd file incorrect maybe there is a problem in the xmlserializerwhat i want is c code that correctly serializes to xml that validates against the xsd right now the jagged array seems to be wrong because if i remove it then it generates the xml i am using visual studio 2008,"['c#', '.net']" +45305,get router mac without system call for arp in objectivec ok i am writing a daemon in objective c that checks the connected router mac address every 5 seconds i am completely new to objective c and i am looking for a better way to do what i am already doing i am currently calling arp a and parsing the results via tasknstask tasktask nstask alloc inittask setlaunchpath usrsbinarpnsarray argumentsarguments nsarray arraywithobjects a niltask setarguments arguments nspipe pipepipe nspipe pipetask setstandardoutput pipensfilehandle filefile pipe filehandleforreadingtask launchnsdata datadata file readdatatoendoffilei am afraid that this is not very efficient any suggestions i am running this codeblock once every 5 seconds,['objective-c'] +45310,how is generic function implemented in java as per my understanding the following generic function in javapublic static t t ft x integer arr new integer4 t ret t arr2 return retis compiled to the following form as it is unboundedpublic static object fobject x integer arr new integer4 object ret object arr2 return rethowever when i run the following statement the compiler is able to figure out the return value to be integer type how does the compiler figure it outinteger i fnew integer4should not the function be written as following for the above statement to work public static t extends integer t ft x integer arr new integer4 t ret t arr2 return ret,['java'] +45318,how do i pass in config info to ckeditor using the jquery adapter i am using the latest ckeditor with jquery adapteri have successfully got it to work and thisplay however as i am completely new to ckeditor how do i pass in config variables using the jquery methodthis is what i have got inputcontent ckeditor toolbar basici think from what i have read the first argument is meant to be a callback and the 2nd the config but doing this has not changed the editor at allhow do i use these config properties etc using the jquery adapter,"['javascript', 'jquery']" +45320,how to make a generic list equal another generic list this is my set upclass costperioddto iperiodcalculation public decimal a get set public decimal b get set public decimal c get set public decimal d get set interface iperiodcalculation decimal a get set decimal b get set class mydto public listcostperioddto costperiodlist get set public listiperiodcalculation periodcalclist get return thiscostperiodlist compile error what would be the best way of doing this,['c#'] +45322,length of an integer in python in python how do you find the number of digits in an integer,['python'] +45325,safe casting in objective c is there anything like cs safe casts in objectivec i know that they are in objective c but i am unsure about possible side effects using objective c may slow compilation time are there any other reasons not to use it,['objective-c'] +45339,can i use facebooks hiphop with frameworks like zend framework cakephp symfony yesterday facebook launched hiphop a sourcecodeconverter from php to c the set of php functions and constructions is more limited than in standard phpare the current popular php frameworks zf cakephp symfony compatible with hiphop if not which parts of these frameworks are not usable,['php'] +45341,how to start and stop an tomcat container with java i have a maven project that starts a tomcat container for preintegrationtests junit tests most of my tests require that the webapplication under tests is restarted so i would like to restart the tomcat container before each junit test is executed as for now i use the cargomaven2plugin to configure the tomcat containerso is it possible to start and stop the container with a java statement,['java'] +45344,how to fix the requested resource is in use exception from hresult 0x800700aa how can i solve this errorthe requested resource is in use exception from hresult 0x800700aa this appears while navigating to a different website using the webbrowser control in c net why,"['c#', '.net']" +45345,limit how many characters can be pasted in textarea is it possible to detect how many characters are being pasted into a html textarea and cancel the paste if beyond a limitedit what i am trying to do is prevent the user pasting a massive amount of characters 3 million because it crashes some browsers so i want to cancel the paste before their browser locks up i am making a document editor where users are likely to try this but they can type as much as they want,"['jquery', 'html']" +45348,websockets served by a servlet container i was taking a look at websockets last week and made a few thoughts on how to implement the server side with the java servlet api i did not spend too much time but ran into the following problems during a few tests with tomcat which seem impossible to solve without patching the container or at least making container specific modifications to the httpservletresponse implementationthe websocket specification mandate a defined message in the 101 http response httpservletresponsesetstatusint code string message is deprecated without mentioning a usable replacement after changing the default tomcat configuration i made tomcat honor my message string but since the method is deprecated i am not sure if this will work with other servlet containersthe websocket specification require a specified order of the first few headers in the http response to the connection upgrade request the servlet api does not offer a method to specify the order of the response headers and tomcat adds its own headers to the response placing a few of them before any headers which are added by the servlet implementationsince the content length of the response is not known when committing the header tomcat automatically switches to chunked transfer encoding for the response which is incompatible with the websocket specificationam i missing something obvious or is it really not possible to integrate websocket server endpoints in a servlet based web app,['java'] +45350,textboxes in html table how to autosize i want to add a row at the bottom of my html table or at the top whatever with a textbox in each column to allow filtering of content of each columnfwiw the table is based on the jquery datatables pluginthe problem is that the textboxes widen the columns i want each textbox to fill the width of its column without enlarging it how can i do this,"['html', 'css']" +45360,create a custom callback in javascript all i need to do is to execute a callback function when my current function execution endsfunction loaddata alertthe data has been loaded call my callback with parameters for example callbackloadeddata currentobjecta consumer for this function should be like thisobjectloaddatasuccessfunction successloadeddata currentobject todo some action here how do i implement this,['javascript'] +45362,how can i generate a guid for a string i am having a problem generating a guid for a string for exampleguid g new guidmeharhow can i compute a guid for mehar i am getting an exception,['c#'] +45372,net datetime to sqldatetime conversion while converting net datetime when is defaultdatetime to sqldatetime should i always check if the net date is between sqldatetimeminvalue and sqldatetimemaxvalue or is there a good way to do this,"['c#', '.net']" +45380,are all class files in my java application loaded into memory after appliaction start i am making an app for android in my activity i need to load an array of about 10 strings loading it from database was slow so i decided to put it directly into one java file as a private field i have about 20 of these classes containing string arrays and my question is are all the classes loaded into memory after my application is started if so the activity in which i need these strings would be loaded quickly but the application as a whole would have a slow startis there other way how to very quickly load an 10 string array from a fileupdatewhy i need these strings my android app allows you to find journeys in pragues public transit you choose departure stop arrival stop and it finds your journey have a look here my app has a suggestions feature you enter leter c as your departure stop and a suggestions listview appears with stops starting with c for these suggestions i need the strings fetching the suggestions from database is slow about 400ms on g1,"['java', 'android']" +45386,conditional operator in python do you know if python supports some keyword or expression like in c to return values based on if condition all in the same line the c if expressed with the question mark cvalue a 10 b c,['python'] +45387,what is the difference between window based and view based iphone apps what is the difference between window based and view based iphone apps thanks,"['iphone', 'objective-c']" +45393,how to remove part of a string how to trim a part of a string and save it in a particular string in mysql using phpexampleif a string has the value register 11223344 herehow can i cut 11223344 from the string,['php'] +45394,how to use the keyword references in mysql how is the references keyword used when creating a tablelet us say i want to create two tables person and hobby and i want the hobby table id to reference the id of personperson table id namehobby id person id hobby namehow do i do that,['mysql'] +45396,select countthistinct value returns 1 i am designing a query in ssms 2005 which looks something like thisselect countthistinct columnname from table where columnname is not nullwhen i run the query with count it returns the value 1 when i run it without count ssms reports the correct value eg 212 recordsthe column in question is of datatype numeric16 0for those who might ask the query in full isselect countthistinct o id from vemployersinner join venrolment on o id e enrolmentemployerwhere e start 01aug2008 and e start 01aug2009and o id is not null and o id in select o id from vemployers inner join venrolment on o id e enrolmentemployer where e start 01aug2008 and e start 01aug2007this query basically gives a repeat business figure between two 12month periodsso i am wondering why countthistinct columnname is returning 1 when columnname is not null has been specifiedhere is a sample of the data when select top 10 thistinct columnname from etc is run1346116134613113464251346923134993513501151350153259478728219442879631,['sql'] +45406,insert record into table if entry does not exist in another table with an extra twist hi to all you mighty sqlsuperheros out therecan anyone rescue me from imminent thisaster and ruini am working with microsoft access sql i would like to select records in one table table1 that do not appear in another table2 and then insert new records into table2 that are based on records in table1 as followstable1file index filename table2file index celeb namei want to select all records from table1 where filename is like audand whose corresponding file index value does notexist in table2 with with field celeb name audrey hepburnwith that selection i then want to insert a new record into table2file index table1file indexceleb name audrey hepburnthere is a one to many relationship between file index in table1 and table2one record in table1 to many in table2many thanks,['sql'] +45408,array of and pointers to functions returning pointers to functions this was asked to me in an interviewi really got confusedhow do i declare an array of npointers to functions returningpointers to functions returningpointers to characterscould anybody please help,['c'] +45410,macro keyword which can be used to print out method name file and line are well known there is a func since c99include iostreamstruct foo void do stdcout func stdendl int main stdcout func stdendl foo foo foodo return 0will outputmaindois there any macro keyword that would output method name like foodo,"['c++', 'c']" +45411,how to set a breakpoint on a method within the net framework i wish to set a breakpoint on the systemthreadingsynchronizationcontextsetsynchronizationcontext static method so i can find out when the synchronization context is being set however i canat find how to set a breakpoint in a method i donat have the source code tothis should be easy but when i try to set the breakpoint on a method from the breakpoints window it does recognise the method,['.net'] +45415,worst side effects from chars signedness explanation of signedness effects on chars and casts i frequently work with libraries that use char when working with bytes in c the alternative is to define a byte as unsigned char but that not the standard they decided to use i frequently pass bytes from c into the c dlls and cast them to char to work with the librarywhen casting ints to chars or chars to other simple types what are some of the side effects that can occur specifically when has this broken code that you have worked on and how did you find out it was because of the char signednesslucky i have not run into this in my code used a char signed casting trick back in an embedded systems class in school i am looking to better understand the issue since i feel it is relevant to the work i am doing,['c++'] +45425,efficient number of threads i want to optimize my application number of threadsalmost all of them have io beside cpu usage in an equal valuehow much is the efficient number of threads when there are no other applications running in systemi want the answer for windows and under jvm,['java'] +45428,why java provides two methods to remove element from queue the queue implementation in java has two methods to remove element one is remove which throws exception and other one is poll which returns null for an empty queue i have two doubtswhy queue has different implementation to remove elementwhich implementation to use when,['java'] +45429,building php competencies in an organization this is not really a technical programming question but has more to do with best practices and programming project management processes heres some background informationi am a consultant with an agile scrum software development company that specializes in the java j2ee flex technology stackhere it is generally perceived by many that the quality of php related people projects etc is not up to the mark as compared to java while i often contest that claim i do accept that there is an overall low barrier to entry into php which does occasionally attract lower quality people who then produce lower quality workfor us quality comes first over the course of the next few quarters we also are looking to develop a very high level of competency in php and we want to achieve the highest level of quality and our processes should be such that we are constantly improving all the time while starting off as a high levelour new recruits are going through a rigorous selection process where there is a very hands on technical assignment we evaluate how they code we evaluate how they test their code we evaluate their skills with industry standard frameworks zend cakephp codeigniterkohana symphonywe have a bimonthly twice a month knowledge exchange event where individuals are encourages to present we have hands on events as welli would request you to share your experience on how we as individuals and an a flat agile relatively small organization can instill good php development practices and constantly improve ourselvesthankssri,['php'] +45432,catching sqlalchemy exceptions what is the upper level exception that i can catch sqlalechmy exceptions with from sqlalchemy import exc direxcargumenterror circulardependencyerror compileerror concurrentmodificationerror dbapierror dataerror databaseerror thisconnectionerror flusherror identifiererror integrityerror interfaceerror internalerror invalidrequesterror noreferenceerror noreferencedcolumnerror noreferencedtableerror nosuchcolumnerror nosuchtableerror notsupportederror operationalerror programmingerror sadeprecationwarning sapendingdeprecationwarning sawarning sqlalchemyerror sqlerror timeouterror unboundexecutionerror unmappedcolumnerror builtins doc file name package,['python'] +45435,in python how do i exclude files from a loop if they begin with a specific set of letters i am writing a python script that goes through a directory and gathers certain files but there are a number of files i want excluded that all start the sameexample codefor name in files if name doc1html and name doc2html and name doc3html print namelet us say there are 100 hundred html files in the directory all beginning with doc what would be the easiest way to exclude themsorry i am new to python i know this is probably basicthanks in advance,['python'] +45436,clr assembly will not load in 64 bit sql server 2005 we use an assembly with some user defined functions in our installation of sql server 2005 32 bit we deploy this to production with a script like thiscreate assembly ourfunctionsauthorization dbofrom 0x4d5a90with permission set safegocreate function dboglobal formatstringinput nvarchar40returns nvarchar40 with execute as calleras external name ourfunctionsuserdefinedfunctionsglobal formatstringgowe have never experienced any problems with these functions now when we tried to upgrade one of our servers to x64 we got errors when calling any of the functions sample stack tracesystemdatasqlclientsqlexception an error occurred in the microsoft net framework while trying to load assembly id 65549 the server may be running out of resources or the assembly may not be trusted with permission set external access or unsafe run the query again or check documentation to see how to solve the assembly trust issues for more information about this error systemiofileloadexception could not load file or assembly ourfunctions version0 cultureneutral publickeytokennull or one of its dependencies the given assembly name or codebase was invalid exception from hresult 0x80131047 systemiofileloadexception at systemreflectionassemblynloadassemblyname filename string codebase evidence assemblysecurity assembly locationhint stackcrawlmark stackmark boolean throwonfilenotfound boolean snipthe error mentions the permission sets external access and unsafe whereas we use the level safe the dll file is build with target platform set to any cpu and we get the same results when we try to load the dll from file instead of the varbinary syntax we already tried the suggestions in we have tried the exact same procedure on a 32 bit machine and everything just worked it must be a difference between x86 and x64 any ideassolution we finally found the solution it turns out that our assembly was indeed a 32 bit compiled one in visual studio we used the target any cpu but on inspecting the underlying csproj i found the following snippet propertygroup condition configurationplatform debuganycpu other elements platformtargetx86platformtarget propertygroupso our any cpu target was actually building an x86 assembly argh i have traced back this line in subversion but it was already there at first checkin in 2006 maybe this was a bug in some early template of the database project anyway thanks for your help i will accept rus answer as i suspect that many who experience the same problems will be helped most by his answer,['.net'] +45450,how do remove the border around a coreplot graph i am trying to remove the border around a core plot graph on the iphone but seem to be struggling on what should be simple in my mindpointers please,['iphone'] +45451,getting 32 bit words out of 64bit values in cc and not worrying about endianness it is my understanding that in cc bitwise operators are supposed to be endian independent and behave the way you expect i want to make sure that i am truly getting the most significant and least significant words out of a 64bit value and not worry about endianness of the machine heres an exampleuint64 t tempuint32 t msw lswmsw temp 0xf0 32lsw temp 0x0fwill this work,"['c++', 'c']" +45475,memcached rubygem rlibmemcached argument error with memcache mget i am getting an exception when using evan weavers memcached gem as memcachedrailsnew and calling get multiargumenterror wrong of arguments2 for 4from usrlocallibrubygems18gemsmemcacheauth101libmemcachedmemcachedrb384in memcached mgetfrom usrlocallibrubygems18gemsmemcacheauth101libmemcachedmemcachedrb384in get origfrom usrlocallibrubygems18gemsmemcacheauth101libmemcachedrailsrb40in get multii noticed that memcached geth defines memcached mget asmemcached return memcached mgetmemcached st ptr const char const keys const size t key length size t number of keysso it would seem key length and number of keys are missing my c is a bit rusty but i am presuming those would be required argumentshowever it looks like the associated ruby code in railsrb is only passing 2 argsdef get multikeys rawfalse get origkeys rawendupdate turns out it was a bug in the ruby gem which has now been patched,"['c', 'ruby']" +45479,calculating averages with performance counters i have a service process and i want to use performance counters to publish the average time that it takes to complete tasks i am using the averagetimer32 counter to do thisit is almost working the way i want but not quite when i increment the counter it will briefly bump up to the value that i expect watching in performance monitor but then it drops right back down to zero so the counter is zero i run a task the task completes the counter briefly bumps up to the correct value but then it almost immediately falls back to zeroi am using the averagetimer32 counter with an averagebase as the denominator i increment the averagebase by 1 every time i start a task and then i increment the averagetimer32 by the number of ticks to complete every time i finish the task can anyone give me a push,"['c#', '.net']" +45481,why does java code slow down in debugger some cpu intensive routines get dramatically slower when run through a debugger why is this currently i am just using intellij to step through code running in jboss when i start jboss i use these options set java optsxms512m xmx1024m xxmaxpermsize256m xdebug xrunjdwptransportdt socketaddress5005serverysuspendn java optsis there a way to speed up the execution or to speed up certain method executions that i do not need to step throughupdate seems if i do not step overinto the cpu intensive routines ie just run til a breakpoint set right after the routine then the execution time is as if not in a debugger,['java'] +45482,check domain availability java is there a relatively simple way in java to check if a domain is available or noti need a reliable method so only checking if the connection can be made is not enough,['java'] +45496,what is the best way to detect internet explorer 6 using javascript what is the best way to detect internet explorer 6 using javascriptif browser ie6 alerthi,"['javascript', 'jquery']" +45538,getting python mysqldb to run on ubuntu i created a virtualbox with a fresh install of ubuntu 910i am trying to get mysqldb to run on python but i am failing at the import mysqldbi first tried sudo easy install mysql python123c1py26linuxi686egg and then sudo aptget install pythonmysqldbboth apparently installed ok but gave me the following error message when in python i have the import linetraceback most recent call lastfile stdin line 1 in modulefile usrlocallibpython26thistpackagesmysql python123c1py26linuxi686eggmysqldb init py line 19 in modulefile usrlocallibpython26thistpackagesmysql python123c1py26linuxi686egg mysqlpy line 7 in modulefile usrlocallibpython26thistpackagesmysql python123c1py26linuxi686egg mysqlpy line 6 in bootstrap importerror libmysqlclient rso15 cannot open shared object file no such file or directoryi have already installed mysql and it is running if that matters at alli tried following this but failed in step 2,"['python', 'mysql']" +45541,how to change title of activity in android i am using window w getwindowwsettitlemy titleto change title of my current activity but it does not seem to workcan anyone guide me on how to change this,['android'] +45542,javascript uploading a file without a file i am trying to fake a file upload without actually using a file input from the user the files content will be dynamically generated from a stringis this possible have anyone ever done this before are there examplestheory availableto clarify i know how to upload a file using ajax techniques using a hidden iframe and friends the problem is uploading a file that is not in the formi am using extjs but jquery is feasible as well since extjs can plug into it extjquerybase,['javascript'] +45548,php script not working in html file i am new to php i installed xampp and have apache running i created helloworldphp in xampps htdocs and got php to thisplay in my browser my question is why does my php script in my html file not thisplay in my browser ive never installed php on its own should i also install it would it conflict with xampp my code is below any assistance will be appreciated thanks in advance htmlbodyphpecho hello php worldbodyhtml,['php'] +45555,how does printf work i looked over but could not find a decent answeri was wondering how printf works in case like thischar arr2 56printf ddarr0arr1i was thinking that printf just walks through the format and when it encouter d for example it reads 4 bytes from the it is current position however that is gotta be misconcepition cause that above works perfectlyso where am i wrong,['c'] +45556,why is void 0 a no operation in c and c i have seen debug printfs in glibc which internally is defined as void 0 if ndebug is defined likewise the noop for visual c compiler is there too the former works on both gcc and vc compilers while the latter only on vc now we all know that both the above statements will be treated as no operation and no respective code will be generated but heres where i have a doubtin case of noop msdn says that it is a intrinsic function provided by the compiler coming to void 0 why is it interpreted by the compilers as no op is it a tricky usage of the c language or does the standard say something about it explicity or even that is something to do with the compiler implementation,"['c++', 'c']" +45558,how to get last key in array in javascript this is similar to this questiononly phpjavascript,['javascript'] +45584,iterate multiple stdvector i have read here and other places that when iterating a stdvector using indexes you shouldstdvector int x201for stdvectorintsize type i 0 i xsize i xi3but what if you are iterating two vectors of different typesstdvector int x201stdvector double y2010for stdvectorintsize type i 0 i xsize i xi3 yi30is it safe to assume that stdvectorintsize type is of the same type as stdvectordoublesize type would it be safe just to use stdsize tthanks,['c++'] +45590,which ioc runs in medium trust hi i am trying to get a website running with mosso that has castle windsor as my ioc however i am getting the following errorsecurityexception that assembly does not allow partially trusted callers goldminewindsorcontrollerfactoryctor in windsorcontrollerfactorycs33 goldminemvcapplicationapplication start in globalasaxcs70my questions are does castle windsor run under medium trust can i download the dlls without having to recompile with nant as i do not have this set up and do not know nant at allor is there another ioc that i can use that i can download and works in medium trustthanks,['.net'] +45592,how bad is it to override a method from a thirdparty module how bad is it to redefine a class method from another thirdparty module in pythonin fact users can create numpy matrices that contain numbers with uncertainty ideally i would like their code to run unmodified compared to when the code manipulates float matrices in particular it would be great if the inverse of matrix m could still be obtained with mi despite the fact that mi has to be calculated with my own code the original i method does not work in generalhow bad is it to redefine numpymatrixi for one thing it does tamper with thirdparty code which i do not like as it may not be robust what if other modules do the samea another problem is that the new numpymatrixi is a wrapper that involves a small overhead when the original numpymatrixi can actually be applied in order to obtain the inverse matrixis subclassing numpy matrices and only changing their i method better this would force users to update their code and create matrices of numbers with uncertainty with m matrix with uncerta instead of keeping using numpymatrixa as for a matrix of floats but maybe this is an inconvenience that should be accepted for the sake of robustness matrix inversions could still be performed with mi which is gooda on the other hand it would be nice if users could build all their matrices of floats or of numbers with uncertainties with numpymatrix directly without having to bother checking for data typesany comment or additional approach would be welcome,['python'] +45596,should i map a dto tofrom a domain entity on both client and server sides i have got a rich domain model where most classes have some behaviour and some properties that are either calculated or expose the properties of member objects which is to say that the values of these properties are never persistedmy client speaks to the server only via wcfas such for each domain entity i have a corresponding dto a simple representation that contains only data as well as a mapper class that implements dtomapperdtoentity and can convert an entity to its dto equivalent or viceversa through a static gateway var employee mapemployeefrom dtoemployeedtothe server side of this application is mostly about persistence where my dtos come in from the wcf service are deserialized and then an arbitrary orm persists them to the database or a query request comes in from wcf and the orm executes that query against the db and returns objects to be serialized and sent back by wcfgiven this scenario does it make any sense to map my persistence store to the domain entities or should i just map directly to the dtosif i use domain entities the flow would be client requests objectwcf transmits request to serverorm queries database and returns domain entitiesdomain entities transformed into dtos by mapperwcf serializes dto and returns to clientclient deserializes dtodto transformed into domain entity by mapperviewmodels created etcsimilar on the return tripif i map straight to dto i can eliminate one mapping per object per request what do i lose by doing thisthe only thing that comes to mind is another opportunity to validate before insertupdate because i have no guarantee that the dto was ever subject to validation or even existed as a domain entity before being sent across the wire and i guess a chance to validate on select if another process might have put invalid values in the database are there other reasons are these reasons sufficient to warrant the additional mapping stepsediti did say arbitrary orm above and i do want things to be as ormandpersistenceagnostic as possible but if you have anything special to add that is specific to nhibernate by all means do,['.net'] +45598,how to select multiple rows filled with constants selecting constants without referring to a table is perfectly legal in an sql statementselect 1 2 3the result set that the latter returns is a single row containing the values i was wondering if there is a way to select multiple rows at once using a constant expression something kind ofselect 1 2 3 4 5 6 7 8 9i would want something like the above that works and returns a result set with 3 rows and 3 columns,['sql'] +45600,generate properties programatically i want to load a properties file it is a csv file having on each line a name and associated numeric value and then access those property values like so fileloaderpropertyone or fileloaderpropertytwo the problem is i do not want to have to write a property for each value i want them to be generated from the file sopublic class fileloader public int property1 get private set is not what i am looking for is this possible i cannot see any way to do it because obviously the compiler wouldnt know about the property names perhaps something similarupdate thanks to all for their answers very illuminating,['c#'] +45601,how to ignore case with linqtosql i am having problems with getting data using linqtosql i use the following piece of code to look up a user for our web app user name is email addressvar referenceuser dbreferenceusers singleordefaultrf rfemail valuesemailaddressif i type i get a referenceuser however if i type i do not how can i get linq to ignore the case when selecting a user,['c#'] +45612,css floating div to right causes container div to stretch full width of screen in ie i saw a similar question here and did not see an answer i am having an issue where an element is floated right inside a parent div and it is causing the div to stretch the entire width of the page in ie7 this does not happen in any other browsers firefox and chrome i have also posted pictures after the question for reference the html i am using is belowdiv idjournal classjournalie div classtitle bar div testing div div classactionsdiv div classcleardiv divdivthe css i am using for these tags is below as well one thing i noticed consistent between the other persons question referenced above and my issue is that both parent divs have positioning applied person above has absolute i have fixedjournal zindex 1journalie right 1px bottom 18px position fixedjournal title bar background f3f3f3 border 1px solid c5d6e8 color 363638 fontsize 11pt fontweight bold height 20px padding 4px marginbottom 4pxjournal title bar actions float rightclear clear bothnotice that the actions class is floated right if i take away that float my box looks like this but with the float added it stretches the entire screen and looks like this is this a known ie bug because it is not happening in any other browser and it is driving me crazyfor those wondering i did have content in the actions div but have stripped away everything down to the root problemany assistance would be greatly appreciated thanks very much,"['css', 'html']" +45621,convert ascii byte to string i am trying to pass a byte containing ascii characters to log4j to be logged into a file using the obvious representation when i simply pass in the byt it is of course treated as an object and the logs are pretty useless when i try to convert them to strings using new stringbyte data the performance of my application is halvedhow can i efficiently pass them in without incurring the approximately 30us time penalty of converting them to stringsalso why does it take so long to convert themthanksediti should add that i am optmising for latency here and yes 30us does make a difference also these arrays vary from 100 all the way up to a few thousand bytes,['java'] +45635,createobject equivalent in cc com interop what would the equivalent in cc,"['c++', 'c']" +45643,windbgsos explanation of syncblk output i am looking of a description of the output generated by the syncblk command of sosparticularly i found no useful explanation on the column monitorheld this column shows high values in a series of crash dumpsexample0 syncblkindex syncblock monitorheld recursion owning thread info syncblock owner 44 05a5c228 1 1 0e7a6740 2304 273 019f858cd0 systemobject 48 0579bae8 1 1 0e7a72e0 2370 275 015f900 systemobject 52 0579b9c8 1 1 011bbd3b0 1e98 295 0ff89fe08 systemobject 54 0579b938 1 1 0e7a38c0 1be4 249 013f8aa8 systemobject 108 05a5bfe8 1 1 0e79f300 224c 242 0ff8a5828 systemobject 110 05a5c078 1 1 0e79ca50 2290 262 015f9a8020 systemobject 112 05a5c108 1 1 011bb70e0 1d38 236 015f99e408 systemobject 114 0579b620 1 1 011bb93c0 1884 304 01bf974a90 systemobject 124 05a44d48 1 1 0e7a6170 2300 272 019f853fe8 systemobject 146 05a44688 99 1 0588cbf0 13e0 38 017f71c4f8 systemobject 155 05a44f88 1 1 011bba530 2274 301 019f82f120 systemobject 157 05a45018 1 1 011bbf0c0 2034 290 015f952980 systemobjectcan anyone explain the 99 in column monitorheldhas anyone a a link to a complete reference documentation of this commandthanksalex,"['c#', '.net']" +45644,throwing a linked list of exceptions in java i have a function that loops while doing something that could throw an exception looks something like thispublic void myfunction throws myexception whilestuff try dosomething throws an exception catch exception ex throw new myexceptionsome stuff of mine ex the error causing the exception is recoverable it can be something like an sql error in a single update statement where the while loop executes a series of update statements or a parsing error in a single piece of data where the loop is processing multiple pieces of data i need to pass the exception further up the chain so the gui part of the program can process it handle it and pass on the error to the user but i do not want to kill the loop in this particular function the other things it is doing might not be invalid the error that caused the exception might not be fatal to the functionso my question is this is it an acceptable practice to build linked lists of custom exceptions where each exception is a node and the exception thrown is the head of the list and then throw the head of the list if any once the loop finisheshas anyone ever seen this done can anyone think of any potential problems with doing this can anyone think of other better ways to handle the root problem the need to pass up multiple unrelated exceptions with out exiting the function until it is done heres an example of how the linking and throw might be implemented very simplypublic void myfunction throws myexception myexception head null whilestuff try dosomething throws an exception catch exception ex myexception tmp new myexceptionsome stuff of mine ex tmpnexthead head tmp ifhead null throw head,['java'] +45647,check if a variable is of type mysqli object how do i check if a variable is of a type mysqli object,['php'] +45648,how do i play a tone in linux using c i am trying to write a program to randomly generate music based on a simple set of rules i would like the program to be able to generate its own sounds as opposed to having a file with audio for each note does anyone know a simple way of doing this it would be nice but not essential for the sound to be polytonal and i would like a solution for linux using c,['c'] +45651,building an aspnet mvc master page menu dynamically based on the current users role i have seen some similar questions but none that look like what i am trying to dothis is my current implementation wout any securitydiv idmenucontainer ul idmenu li htmlactionlinkmain list index acontrollerli li htmlactionlinkproduct list index bcontrollerli li htmlactionlinkcompany list index ccontrollerli li htmlactionlinkuser list index dcontrollerli uldivthis is fine and the above works i have authorize attributes setup on the actions for ccontroller and dcontroller to prevent unauthorized access but i would like to remove those items from the menu for users who do not have the correct role because when they see it and click on it and it tells them they do not have permission they will want it if they do not know it is there that is just better for everyone involvedsomething like this is ultimately the goal i am trying to get at but i am looking for the more mvc flavored aproach where the view is dumbdiv idmenucontainer ul idmenu li htmlactionlinkmain list index acontrollerli li htmlactionlinkproduct list index bcontrollerli ifrole rolesadmin li htmlactionlinkcompany list index ccontrollerli li htmlactionlinkuser list index dcontrollerli uldiv,"['c#', '.net', 'asp.net']" +45653,what is the fastest way to create mass habtm associations in rails i have two tables with a habtm relationship in rails something like the followingclass foo lt activerecordbase has and belongs to many barsendclass bar lt activerecordbase has and belongs to many foosendnow i have a new foo object and want to massassign thousands of bars to it which i have preloadedfoo foocreatebars barfind all by some attributeawhats the fastest way to do this i have triedfoobars barsfoobars ltlt barsand both run really slow with an entry like the following for each barbars foos columns 11ms show fields from bars foos sql 06ms insert into bars foos bar id foo id values 100 117200i looked at arextensions but the import function does not seem to work without a model modelimport which precludes its use for a join table do i need to write the sql or does rails have a prettier way,['ruby-on-rails'] +45654,posting form fields with same name attribute if you have a form containing text inputs with duplicate name attributes and the form is posted will you still be able to obtain the values of all fields from the post array in php,['php'] +45656,programmatically connect to a bluetooth headset from an android application i am looking for a way to initiate the audio connection between the android phone and my headset within my application the idea is to simplify the connection process in such a way that the user does not have to go through the different settings menus anymore apps settings wireless networs bluetooth settings both devices are supposed to be already paired and the bluetooth address of the headset to be known as far as i learned the bluetooth capabilities available since version 20 of the android sdk are restricted to bluetooth thiscovery and the connection of rfcomm channels hostclient between the android phone and a bluetooth device is there another way to request bluetooth profiles on the android system to initiate a connection to a known device from an app or is this impossible,['android'] +45657,sinatra whats the correct way to serve a plain old file this works but it was a stab in the dark i know little rubywhats the accepted way to serve a plain old file for a given resourceget xyz do fileread abchtmlend,['ruby'] +45669,how to use nsurlrequest nsurlconnection to download an mp3 file to app the situationin my app i am currently downloading an mp3 file to docs directory using nsdata datawithcontentsofurlurl a method that works fine but ties down the cpu thissallowing screen updates of download status so i want to download using a different method so that i can update the screen while downloading to alert the user that the download has begun questionhow do i set up my viewcontroller to use nsurlrequest or nsurlconnection to download an mp3 file please give source,['iphone'] +45670,codeigniter handling errors when using active record i am putting together a few models for my codeigniter site and cannot seem to find any word in the documentation of how to handle errors that could occur when using the active record systemthe documentation demonstrates how to perform crud along with some relatively involved queries but no where along the line is error handling thiscussed i have done a quick google search and it would appear that the active record classes do not throw exceptions is this the case no try catch thenso how do you code to handle database errors in codeigniter failed connection duplicate key broken referential integrity truncation bad data types etc etc,['php'] +45671,iphone core data cascading delete across a manytoone relationship i have two classes a and b with a manytoone relationship from a to b multiple a objects may reference the same b the question is if the delete rule on the a side is cascade will b be deleted only when the last referencing a is deleted or will it be deleted the first time an associated a is deleted the delete rule for the b side of the relationship is nullify if that matters also i read in the core data docs that the optional flag matters in some cases but it was not clear how the relationships they were illustrating related to my case they were talking about a containment case b is owned by a whereas my case is one of subscriptionassociation b is related to ai could simply manage deletion programmaticaly in the code but wanted to allow core data to do the right thing if possible but it is not clear that the garbage collection semantics that i am looking for are supported in core dataany suggestions,['iphone'] +45673,how does jquery hijack this i am just curious to know how jquery is able to hijack the this keyword in javascript from the book i am reading javascript the definitive guide it states that this is a keyword and you cannot alter it like you can with an identifier now say you are in your own object constructor and you make a call to some jquery code how is it able to hijack this from youfunction myobject at this point this is referring to this object diveachfunction now this refers to the currently matched div my only guess would be that since you are providing a callback to the jquery each function you are now working with a closure that has the jquery scope chain and not your own objects scope chain is this on the right trackthanks,"['javascript', 'jquery']" +45674,check if checkbox is checked with jquery how can i check if a checkbox in a checkbox array is checked using the id of the checkbox arrayi am using the following code but it always returns the count of checked checkboxes regardless of idfunction ischeckedbyidid alertid var checked inputid id checkedlength alertchecked if checked 0 return false else return true,['jquery'] +45713,how to convert a string literal to unsigned char array in visual c how to convert a string to unsigned char in ci haveunsigned char m test8i want to assign a string hello world to m testhow to do it,['c++'] +45716,how to tell if user has modified data using bindingsource i have a datagridview bound to a bindingsource which is bound to a listt the user clicks a row that goes to a form with textboxes etc the textboxes are databound like soif txtiddatabindingscount 0 txtiddatabindingsaddtext bindingsource titlei want to be able to detect if the user has modified any data in the controls when they click the close button so i can prompt them to say you have unsaved work do you want to savehow do i detect this on the binding sourceupdate i have worked out that i can do bindingsourceendedit which pushes the changes to my item in the list in my item i can then say if dirty throw a messagebox but if they click no to saving the information the canceledit does not work,['c#'] +45724,plugin dlls that depend on other dlls i am writing a dll to plug into another 3rd party application the dll will need to depend on another set of dlls for license reasons i cannot link staticallyi would like my dll to be xcopydeployable to any directory i would also like not to require adding this directory to the pathif i just build the dll the usual way windows will refuse to load the dll since it cannot find the dlls next to the current processare there any good options for helping windows locate the dllto answer some questionsthe dll is written in cthe extra dlls are qtdlls i would like to place the extra dlls in the same folder as my plugin dll i can get the name of that folder from getmodulefilenamethe application is firefox the dll is a pkcs11 security modulethe application loads the dll using the full path to the dll the user supplies it when installing the pluginrequiring that the dlls be placed in system32 or next to the application would work but it is a bit messy and could cause problems with uninstallersloadlibrary and getprocaddress would of course work but is not really feasible in my case i am using hundreds if not thousands of methods in the other dlls i really need to use the importlibrariesi had thought about using delayloaded dlls combined with setdlldirectory in dllmain have anyone tried anything like this,['c++'] +45741,iboutlet declarations i have seen the code below written 3 different ways with regards to iboutlet does it matter i would say adding iboutlet to both the declaration and the property was more concisejust propertyclass switchviewcontrollerinterface iphone switcherappdelegate nsobject uiapplicationdelegate uiwindow window switchviewcontroller switchviewcontrollerpropertynonatomic retain iboutlet uiwindow windowpropertynonatomic retain iboutlet switchviewcontroller switchviewcontrollerendjust declarationclass switchviewcontrollerinterface iphone switcherappdelegate nsobject uiapplicationdelegate iboutlet uiwindow window iboutlet switchviewcontroller switchviewcontrollerpropertynonatomic retain uiwindow windowpropertynonatomic retain switchviewcontroller switchviewcontrollerendbothclass switchviewcontrollerinterface iphone switcherappdelegate nsobject uiapplicationdelegate iboutlet uiwindow window iboutlet switchviewcontroller switchviewcontrollerpropertynonatomic retain iboutlet uiwindow windowpropertynonatomic retain iboutlet switchviewcontroller switchviewcontrollerendcheers gary,['objective-c'] +45746,junit ignore test methods from base class let us say i have a test class called testfixturea with several methods testa testb testc etc each with test annotation let us now say i subclass testfixturea into class called testfixtureab and i do not overwrite anything testfixtureab is empty as for now when i run tests from testfixtureab methods testa testb and testc are executed by test runner because test runner does not thistinguish between test methods from class and baseclass how can i force test runner to leave out tests from baseclass,['java'] +45755,can i forbid calling static methods on object instance i have class with lots of conversion functionsclass something public string toxml string tojson static something fromxmlstring factory static something fromjsonstring factory because static functions can be called on instanceit is easy to write code like thissomething s initializing s string xml1 stoxmlsfromxmlxml1 does nothingstring xml2 stoxmlassertxml1 xml2 always trueso i want to forbid calling fromx on objects orat least make them do something differentis there a way to do this,['c++'] +45777,jquery ui datepicker to show month year only i am using jquery date picker to thisplay the calendar all over my app i want to know if i can use it to thisplay the month and year may 2010 and not the calendar,['jquery'] +45785,invoke notifyicons context menu i want to have it such that left clicking on the notifyicon also causes the context menu set with the contextmenustrip property to open as well how would i achieve this do i have to handle click and figure out the positioning myselfedit showing the menu with trayiconcontextmenustripshow results is a few undesirable behaviorsthe menu is not shown at the same location as if right click the notifyicon it appears that you cannot set the x and y coords to where the taskbar is at least on windows 7 which is what i am running it will appear above the task bar not that big of a deal but consistency would be nicewhile the menu is shown there is an extra icon added to the task barclicking somewhere other than the menu does not close it whereas if you right click to bring up the context menu clicking else where automatically closes the context menuis it at all possible to just invoke the menu however the built in right click handler is doing it,['c#'] +45787,is there an addon which you can test css selectors in firefox i was wondering if there is such an addon in firefox where you can test out css paths to check if they are finding the correct element i was looking for something similar to xpather for xpath locations,['css'] +45790,how do i capture commandline text that is not sent to stdout i am using the lame command line mp3 encoder in a project i want to be able to see what version someone is using if i just execute lameexe with no paramaters i get for exampleclamelameexelame 32bits version 3982 usage blah blahblah blahclameif i try redirecting the output to a text file using to a text file the text file is empty where is this text accessable from when running it using systemprocess in c,['c#'] +45792,is it possible to specify a class name for spring framework in an external file i have an application built on the spring framework that uses an external properties file for some things like database host string username and password so that we can check the configuration file into our repository it is open source and not compromise the security of the db it also is great because developers can keep their own copy of this file and the application will automatically use the configuration on their system rather than having to reconfigure manually i would like to be able to specify a bean in the same manner were working with some classes that could change from developer to developer and it would be great if we could allow them to specify this information in a different file so they do not have to mess with the main configuration file to give you an idea we have something likeproperty nameurl valuedbhostvaluepropertywhere dbhost is specified in another file what we want is something likebean nameourbean classclassweneed the above syntax does not actually work but that demonstrates what we want to dothanks in advancechris,['java'] +45809,in gtk when using drag and drop in a treeview how do i keep from dropping between rows i am testing a window that looks something like thisdragging a tag to a card links the tag to the card so does dragging a card to a tagit is meaningless to drop a tag between two cards or a card between two tags i can ignore these outcomes in the handledatareceived function like thisif droppos treeviewdroppositionintoorafter droppos treeviewdroppositionintoorbefore returnhowever when dragging the user still sees the option to inserthow do i prevent this from happening,['c#'] +45817,whats the difference between an abstract class and a class with only protected constructors net what are all the difference between an abstract class and a class with only protected constructors they seem to be pretty similar to me in that you cannot instantiate either oneedit how would you create an instance in a derived class with a base class with a protected constructor for instancepublic class protectedconstructor protected protectedconstructor public static protectedconstructor getinstance return new protectedconstructor this is fine public class derivedclass protectedconstructor public void createinstance protectedconstructor p new protectedconstructor does not compile public static protectedconstructor getinstance return new protectedconstructor does not compile,['c#'] +45827,uinavigationcontroller when does a pushed view receive the dealloc message i would expect that after i push a view controller i then need to release my ownership of the view controller like i did below customviewcontroller nextviewcontroller customviewcontroller alloc initwithnibnamecustomview bundlenilself navigationcontroller pushviewcontrollernextviewcontroller animatedyesnextviewcontroller releaseafter i do that i assume that the navigation controller has ownership of that object and will release it when done which would then call dealloc on my customviewcontroller i would expect that to happen when i tap the back button on the navigation bar and the view is no longer thisplayed that does not happen though i added an nslogcustomviewcontroller did receive dealloc into the dealloc method of customviewcontroller but it never gets printed is this normal behavioris the navigation controller just doing something like keeping that object in case it needs it at some point will it get rid of it when memory starts to run out i tried simulating a low memory warning but nothing happens i have a feeling the answer to this question will be that i should just not worry so much and follow the standard procedure for retainreleaseautorelease that said though has any one else delved into this a little bit further and found out an absolute answer,['iphone'] +45832,are single quotes valid in htmlxhtml are single quotes valid in html and more specifically xhtml stricttable width100table width100,['html'] +45839,how to analyse a noclassdeffounderror caused by an ignored exceptionininitializererror today i spent my afternoon with analysing a noclassdeffounderror after verifying the classpath again and again it turned out that there was a static member of a class that threw an exception that was ignored the first time after that every use of the class throw a noclassdeffounderror without a meaningful stacktraceexception in thread main javalangnoclassdeffounderror could not initialize class initializationproblema at initializationproblemmaininitializationproblemjava19that is all no more linesreduced to the point this was the problempublic class initializationproblem public static class a static int foo 1 0 static string getid return 42 public static void main string args try new a catch error e ignore the initialization error here an error is being thrown again without any hint what is going wrong agetid to make it not so easy all but the last call of agetid was hidden somewhere in the initialization code of a very big projectquestionnow that i have found this error after hours of trial and error i am wondering if there is a straight forward way to find this bug starting from the thrown exception any ideas on how to do this i hope this question will be a hint for anyone else analysing an inexplicable noclassdeffounderror,['java'] +45852,composing a controller class with dependency injection in php how to solve the problem of composing a controller class in php which should beeasily testable by employing dependency injection provide shared objects for end programmerprovide a way to load new user librarieslook down for controller instantiation with a dependency injection frameworkthe problem is that derived controllers may use whatever resources the programmer wants to eg the framework provides how to create a unified access to shared resources db user storage cache helpers user defined classes or another libraries elegant solutionthere are several possible solutions to my problem but neither one looks to be a eleganttry to pass all shared objects by constructor may create constructor even with 10 placeholderscreate getters seters bloated code controllersetapplicationappapply singletons on shared resources usergetinstance or databasegetinstanceuse dependency injection container as a singleton for object sharing inside the controllerprovide one global application singleton as a factory this one looks very used in php frameworks hovewer it goes strongly against di principles and demeters lawi understand that creating strongly coupled classes is thiscouraged and banished for however i do not know how this paradigm applies to a starting point for other programmers a controller class in which they should be able to access shared resources provided to the mvc architecture i believe that breaking up the controller class into smaller classes would somehow destroy the practical meaning of mvcdependency injection frameworkdi framework looks like a viable choice however the problem still persists a class like controller does not reside in the application layer but in the requesthandlerresponse layer how should this layer instantiate the controllerpass the di injector into this layerdi framework as a singletonput isolated di framework config only for this layer and create separate di injector instance,['php'] +45865,what is a good way to read stl and boost documentation in emacs i am familiar with using info and man commands in emacs however boost and default stl do not come with man or info pages instead they come as html documentation especially boost does not seem to have any documentation besides html i could be wrongright now i am trying to put together w3m for quick searching of boost and stl documentation from local documentation directoryis there a different way you use emacs to read html documentation is there info pages for boostthanks,['c++'] +45869,how to implement an efficient infinite generator of prime numbers in python this is not a homework i am just curiousinfinite is the key word herei wish to use it as for p in primes i believe that this is a builtin function in haskellso the answer cannot be as naive as just do a sievefirst of all you do not know how many consecutive primes will be consumed well suppose you could concoct 100 of them at a time would you use the same sieve approach as well as the frequency of prime numbers formulai prefer nonconcurrent approachthank you for reading and writing,['python'] +45873,how do i define and use an enum in objectivec i declared an enum in my implementation file as shown below and declared a variable of that type in my interface as playerstate theplayerstate and used the variable in my methods but i am getting errors stating that it is undeclared how do i correctly declare and use a variable of type playerstate in my methodsin the m fileimplementation view1controller typedef enum playerstatetypes player off player playing player paused playerstatein the h fileinterface view1controller uiviewcontroller playerstate theplayerstatein some method in m filevoiddosomethintheplayerstate player off,"['iphone', 'objective-c', 'c']" +45878,how to create a domain like in a j2ee web application i am a web application developer just a beginneri am designing a small j2ee web application for example the service name would be like it uses apache tomcatspec when a user sign up into the web application he will get a custom domain like how can i accomplish this in my web application i am still developing the app i have not hosted it yet thanks,['java'] +45908,dynamically enabling or thisabling a widget does not work we would like to enable or thisable widgets via code when we say thisable we mean that a widget which is registered in an application should not show up in the list of widgets available to the user when they try to add a widget to their home screen this question has been asked unfortunately many times without answer there was one response by dianne hackborn to a separate widget question which suggested that it was possible to use the package manager to thisable widgets packagemanager pm contextgetpackagemanager pmsetcomponentenabledsettingnew componentnamecomexampleandroidapis appwidgetexamplebroadcastreceiver packagemanagercomponent enabled state enabled or thisabled packagemanagerdont kill app this however does not work the widget component will still appear in the list of widgets it may be that the appwidgetservice located in the android sources basegit at srcbaseservicesjavacomandroid server which loads the list of available widgets caches this list of available widgets if that were the case though then the above code which enables or thisables the widget component would work after a device reset because there would be no cache it does not i have also tried looking into overriding some methods of the appwidgetprovider such as filtering out any events i do not think this will go anywhere because the appwidgetservice which populates the list uses the package manager to find all components which catch the action appwidget update action on startup and when a package is added ie a new app is installed the only time that a provider is removed from this list is on a action package removed broadcast so given that the providers will always be there regardless of the enabledthisabled state of the component i have looked into the actual list activity which is shown from the launcher app when the user long clicks the desktop and adds a widget appwidgetpickactivity in settingsgit in comandroidsettings this unfortunately populates the list directly from the appwidgetservice without any filtering for the components enabled status void putinstalledappwidgetslist items list installed mappwidgetmanagergetinstalledproviders putappwidgetitemsinstalled null items i would love to see if anyone has overcome this hurdle perhaps i am going about it the wrong way all i want is to be able to remove a widget from the list of widgets available to the user when they try to add a widget to their home screen,['android'] +45913,what is daemon thread in java can anybody tell me what daemon threads are in java,['java'] +45914,usage of decimalformat for the following case i have the following decimal format previously private static final decimalformat decimalformat new decimalformat0soit can change 01 0101 00101 0what i wish is01 0101 00101 01is it possible i can achieve so using decimalformat,['java'] +45919,is there any way to write hebrew in the windows console is there any way to write hebrew in the windows consolei tried the followingconsoleoutputencoding new utf8encodingfalseconsolewritelineu05d0u05d1consolereadlinebut instead of it writes some other unicode character thatre not in the hebrew abcany ideas why,['.net'] +45931,what is the easiest way to draw texture with opengl es i saw this google io session he says that the draw texture function is the fastest and vbo is 2nd fasterbut i do not understand how to use itthe draw texture method or the vbo way any suggestion,"['java', 'android']" +45941,rackspace cloud files image upload to rackspace cloud files using php i am doing a project where user can upload images like profile image or image for their image gallary right now its uploading all the images to my server now i want to upload all this image to my rackspace cloud files directly using php script for exampleuser select a filepress submit with some informationthe selected file will be uploaded to the rackspace server and return the file location then the file location along with other information will be saved in my database then i will show the file or image from that locationso do you have any idea exactly how i can do this i am usingcodeigniter frameworkjquery as javascript librarythanks in advance for any answer,['php'] +45964,trouble installing ruby gem json on my mac i get this warning when trying to install the json module via ruby gemsany ideasmacmini poulh sudo gem install jsonpasswordwarning file systemlibraryframeworksrubyframeworkversions18usrlibrubygems18 specificationsjson120gemspec does not evaluate to a gem specificationbuilding native extensions this could take a whileerror error installing jsonerror failed to build gem native extensionsystemlibraryframeworksrubyframeworkversions18usrbinruby extconfrb install json mkmfrb cannot find header files for ruby at systemlibraryframeworksrubyframeworkversions18usrlibrubyrubyh,['ruby'] +45978,checking for empty arrays count vs empty this question on how to tell if a php array is empty had me thinking of this questionis there a reason that count should be used instead of empty when determining if an array is empty or notmy personal thought would be if the 2 are equivalent for the case of empty arrays you should use empty because it gives a boolean answer to a boolean question from the question linked above it seems that countvar 0 is the popular method to me while technically correct makes no sense eg q var are you empty a 7 hmis there a reason i should use count 0 instead or just a matter of personal tasteas pointed out by others in comments for a now deleted answer count will have performance impacts for large arrays because it will have to count all elements whereas empty can stop as soon as it knows it is not empty so if they give the same results in this case but count is potentially inefficient why would we ever use countvar 0,['php'] +45981,how can i validate a date in python 3x i would like to have the user input a date something likedate inputdate mddy and then make sure that the input is a valid date i do not really care that much about the date formatthanks for any input,['python'] +45983,c auto conversions for two unrelated classes class a and class band a function b convertconst ais there a way to tell c to automatically for any function that takes class b as argument to auto convert a class athanks,['c++'] +45984,the advantage thisadvantage between global variables and function parameters in php sorry i am a beginner and i cannot determine how good a question this is maybe it sounds utterly obvious to some of youif our use of these two below is the same which is betterfunction dosomething var1var2 orfunction dosomething global var1var2 by our use i mean that i know that in the second scenario we can also alter the global variables value but what if we do not need to do that which is the better way of writing this function does passing variables take less memory than announcing globals in a function,['php'] +45988,whats the meaning of line in c language whats the meaning of line in the c language where would it be used,['c'] +45998,how do you do a 301 permanant redirect route in aspnet mvc how do you do a http 301 permanant redirect route in aspnet mvc,['asp.net'] +46004,is ruby 191 actually ready and faster for a new rails deployment i am not going to make this into a rails vs framework x thiscussion there is plenty of those already after seriously contemplating what framework i am going to use for my next deployment i decided it is very difficult to pass up the out of the box rest exposure rails gives you for minimal work back this is something that requires slightly more work in django and considering i am putting mostly emphasis on the api portion of the app rails makes more sense this time around considering how important it is for me to write an app that contains heterogeneous clients iphoneandroidtablets that can access not just web browsers i need to be able to build restful apis with minimal resistance from whatever framework i am usingmy question is is rails ready to handle not a twitter sized app but something that does roughly 750 unique hits a day does ruby 191 really improve things there is plenty of nightmare stories and equally as many success stories depending on who you ask joel spolsky one of the founders of stackoverflowcom believes ruby itself is just not ready for prime time because it is still considerably slower than other interpreted languages i am not worried about getting to twitters size that is a problem i wish to have one day but on the same token i do have a site with an average of 750 unique users a day i am wondering what kind of scaling issues i will run into by deciding to use ruby 191 latest rails cpu costs memory footprint as part of my api stack vs just taking the time to actually do a little extra work in django to build a restful api as joel mentions in his article i do not want to buy 100 servers when i can buy 10 i would love to be convinced as to why rails is now ready to meet my requirements,"['ruby-on-rails', 'ruby']" +46006,java settings for netbeans 68 on osx 1058 to optimize cpu usage sorry i have several question relative to the same problemi am using netbeans 68 on osx 1058 with java 160 17 and after about 5 minutes of work the cpu usage of netbeans process and java are around 100it is often due to go to declaration command completion command more or less doing 2 or 3 basic actions such as entering texti already do the following to enhance performance without success specific php netbeans remove all unnecessary plugin and modulesso my question is how to solve this problem and enhance java and netbeans performance on osxmore precisely will a change in garbage collection policy enhance performance and how to do this will a change in default java look and feel enhance performance which lf is the lightest how can i backtrace this problem more preciselysorry for all this questions in the same post but i am running out of idea concerning this problem thank you in advance for your advices hints and help,['java'] +46008,delete all values from an array while keeping keys intact do i really have to do this to reset an array foreach array as i value unsetarrayieditthis one makes more sense as the previous one is equivalent to arrayarrayforeach array as i value arrayinull,['php'] +46013,getting name of the class from an instance in objectivec i have the following problem i get an instance of a class passed and want to know the name of the class of this instance any guess how to get thisthank you very much,"['iphone', 'objective-c']" +46016,android how to detect doubletap hi guys i am having problems with implementing the double tap well i implemented the ongesturelistener and i had the gesturedetector but i am not sure where is the problem here is my code public class home extends tabactivity implements ongesturelistener called when the activity is first created private edittext querytext private resultsadapter m adapter private progressdialog pd final handler h new handler private tabhost mtabhost private arraylistsearchitem sresultsarr new arraylistsearchitem private string querystr private jsonobject searchresponse private gesturedetector gesturescanner final runnable mupdateresults new runnable public void run updatelistui override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain button search buttonfindviewbyidridsearch button testbutt buttonfindviewbyidridtestbutt querytext edittextfindviewbyidridquery listview lvr listviewfindviewbyidridsearch results initialise the arrayadapter thism adapter new resultsadapterhomethis rlayoutlistrow sresultsarr lvrsetadapterthism adapter lvrsetonitemclicklistenernew onitemclicklistener override public void onitemclickadapterview arg0 view arg1 int arg2 long arg3 todo autogenerated method stub pd progressdialogshowhomethis nuloading products from server true false gesturescanner new gesturedetectorthisthis gesturescannersetondoubletaplistenernew ondoubletaplistener public boolean ondoubletapmotionevent e viewasettext ondoubletap pd progressdialogshowhomethis nuloading products from server true false return false public boolean ondoubletapeventmotionevent e viewasettext ondoubletapevent return false public boolean onsingletapconfirmedmotionevent e viewasettext onsingletapconfirmed return false initialise tab contents mtabhost gettabhost mtabhostaddtabmtabhostnewtabspectab1setindicatorhomesetcontentridhomepage mtabhostaddtabmtabhostnewtabspectab2setindicatorsearch resultssetcontentridtab2 mtabhostsetcurrenttab0 sets the respective listeners testbuttsetonclicklistenernew viewonclicklistener public void onclickview arg0 ifmtabhostgettabwidgetgetvisibilityviewgone mtabhostgettabwidgetsetvisibilityviewvisible else mtabhostgettabwidgetsetvisibilityviewgone searchsetonclicklistenernew viewonclicklistener public void onclickview arg0 sresultsarrclear querystr querytextgettexttostring pd progressdialogshowhomethis nuloading products from server true false gosearch updates the listui whenever after receiving the response from the server public void updatelistui ifsresultsarrsize 0 try string ptypename int count linearlayout ptypebar linearlayoutfindviewbyidridproductcat ptypebarremoveallviews jsonarray ptypes searchresponsegetjsonarrayptypes forint index 0index ptypeslengthindex jsonobject ptype ptypesgetjsonobjectindex count ptypegetintcount ptypename ptypegetstringptypename add into tab 2s ui imageview icon new imageviewthis textview t new textviewhomethis tsettextptypename count ptypebaraddviewt catchjsonexception e ifm adaptergetitems sresultsarr arraylistsearchitem a m adaptergetitems a sresultsarr m adapternotifydatasetchanged pdthismiss public void gosearch mtabhostsetcurrenttab1 separate thread for making http request and updating the arraylist thread t new thread public void run searchresponse sendsearchqueryquerystr try jsonarray results searchresponsegetjsonarrayresults this is stupid i probably have to see how to make a json adapter forint index 0index resultslengthindex jsonobject product resultsgetjsonobjectindex gets the searched products from the json object url imgurl new urlproductgetstringimage string productname productgetstringproductname string ptypename productgetstringptypename int pid productgetintpid int positive productgetintpos int negative productgetintneg int neutral productgetintneu searchitem item new searchitemimgurlproductnameptypenameneutralpositivenegativepid sresultsarradditem catchjsonexception e catchexception e returns back to ui therad hpostmupdateresults tstart sends a request with qry as url and receives back a jsonobject as response public jsonobject sendsearchquerystring qry httprequest r new httprequest jsonobject response rsendhttprequestqry return response override public boolean ondownmotionevent arg0 return gesturescannerontoucheventarg0 override public boolean onflingmotionevent arg0 motionevent arg1 float arg2 float arg3 todo autogenerated method stub return false override public void onlongpressmotionevent arg0 todo autogenerated method stub override public boolean onscrollmotionevent arg0 motionevent arg1 float arg2 float arg3 todo autogenerated method stub return false override public void onshowpressmotionevent arg0 todo autogenerated method stub override public boolean onsingletapupmotionevent arg0 todo autogenerated method stub return false oh another question if my listview has an onitemclicklistener can android detect between single tap or double tap for it,['android'] +46019,how to replace ereg i am getting the following message for some php i have to use but did not writedeprecated function ereg is deprecated in optlampphtdocswebechangesiteweb v5inchtml2fpdfphp on line 466this is line 466iferegva3i tried simply replacing with preg match but it could not recognize the modifier in the regular expression i am not too good with regular expression yet and solving this requires that i learn the regexp ereg needs and the regexp preg match needs which if i am not mistaken is different could you guys help me out with this onethanks,['php'] +46025,what requires me to declare using namespace std this question may be a duplicate but i cannot find a good answer short and simple what requires me to declareusing namespace stdin c programs,['c++'] +46027,concatenate char array in c i have a a char arraychar name helloi want to add an extension to that name to make ithellotxthow can i do thisname txt would not work,['c'] +46028,profiling of python threads i am trying to figure out how to measure the performance of several python threads in my application i currently have several tasks that are executing on different threads based on user input and i would like to measure the execution time maybe even memory consumption of each of the threads i have tried to use cprofile on each instantiation of the thread then i would write the data to a file and then aggregate all results with limited success also i have an added problem of having some blocking io which is skewing my results is there anyway to effectively profile my application,['python'] +46063,how to select columns from a table which have non null values i have a table containing hundreds of columns many of which are null and i would like have my select statement so that only those columns containing a value are returned it would help me analyze data better something likeselect non null columns from tablenamei want to select all columns which have at least one nonnull valuecan this be done,['sql'] +46068,html copy form fields to another form including file input field i came to see that form file input field value cannot be set with javascript for security reasonsi just want to copy a file input to another form and post it i searched for a work around and could not find anything is it possibleupdate my codefunction prepareupload filevalue documentgetelementbyidlogovalue filevaluevar mform documentgetelementbyidsleeker ajaxupload mformphp echo base url a methods to uploadinput classinputfileupload typefile size20 namelogodummy idlogodummy onchangeprepareupload thisvalue form action methodpost namesleeker idsleeker enctypemultipartformdata onbeforesubmitreturn false pinput typehidden namelogo idlogo p formanything other thatn file input are working fine and i could receive with post but files does not have values and this code alone working fine too i think this coe is enough,"['javascript', 'html']" +46070,test for my documents folder redirection is it possible to test for folder redirection in net i do not mean reparse pointsjunctions i mean when a folder usually my documents is redirected to a server in such cases if you are traversing the folder system of a pc youll encounter an io error if you reach the local version of the folder so it would be useful to be able to test for my documents folder redirection so as to be able to take action skip the folder jump onto the server etci know i can get the location of my documents but only for the current user using environmentgetfolderpathenvironmentspecialfoldermydocuments but that does not help me test for it in advance across potentially multiple usersdo i need to use something like shgetknownfolderpath,['.net'] +46071,is a member of an rvalue structure an rvalue or lvalue a function call returning a structure is an rvalue expression but what about its membersthis piece of code works well with my g compiler but gcc gives a error saying lvalue required as left operand of assignmentstruct a int vstruct a fun struct a tmp return tmpint main funv 1gcc treats funv as rvalue and i can understand thatbut g does not think the assignment expression is wrong does that mean fun1v is lvalue in cnow the problem is i searched the c9803 standard finding nothing telling about whether funv is lvalue or rvalueso what is it,['c++'] +46076,how do i make my string comparison case insensitive i created one java program to compare two stringsstring s1 hellostring s2 helloif s1equalss2 systemoutprintlnhai else systemoutprintlnwelcomeit thisplays welcome i understand it is case sensitive but my problem is that i want to compare two strings without case sensitivity ie i expect the output to be hai,['java'] +46082,can an android toast be longer than toastlength long when using setduration for a toast is it possible to set a custom length or at least something longer than toastlength long,['android'] +46096,how to change a css class style through javascript according to the book that i am reading it is better to change a css by class when you are using javascript for changing css but how can someone give a sample snippet for this,"['javascript', 'html', 'css']" +46102,problem any hidden field in update panel does not get updated i am using c for my programmingi am facing issue that my hidden variable value is not being updated when it is in update panel please see below code for aspxaspscriptmanager idscriptmanager1 runatserveraspscriptmanager asptimer idtimer1 runatserver interval10 onticktimer1 tick asptimer input typehidden runatserver idhidcurrentdate value input typehidden runatserver idhidtripids value input typehidden runatserver idhidtripdetails value aspupdateprogress iduprogtrips runatserver progresstemplate span stylethisplay block textalign center p stylefontfamily verdana fontsize larger fontweight bold img srcimagesajaxloadergif altprocessing br br processingp span progresstemplate aspupdateprogress aspupdatepanel iduptripsgrid runatserver updatemodealways contenttemplate aspgridview idgvalltrips runatserver onrowdataboundgvalltrips rowdatabound onpageindexchanginggvalltrips pageindexchanging allowpagingtrue autogeneratecolumnsfalse pagersettings modenumericfirstlast pagebuttoncount35 positiontopandbottom pagerstyle cssclassgridpager aspgridview contenttemplate triggers aspasyncpostbacktrigger controlidtimer1 eventnametick aspasyncpostbacktrigger controlidsortby eventnameselectedindexchanged aspasyncpostbacktrigger controlidfilterby eventnameselectedindexchanged aspasyncpostbacktrigger controlidcbpageoptions eventnamecheckedchanged triggersaspupdatepaneland below is the code where i am trying to update one of the hidden field with my cs codeinteresting when i am trying to debug its showing all the values however when i see it f on page source it does not give any valuehere is my aspxcs codeprotected void timer1 tickobject sender eventargs e datatable dttrips null wexprototypedatatripda tripda new wexprototypedatatripda string tid hidtripidsvalue string tripids new string10 tripids tidsplit foreach string tripid in tripids tripsummarybo tripsummarybo tripdagettripsummaryconverttoint32tripid if tripsummarybotriplasteditedondate converttodatetimehidcurrentdatevalue wexprototypeservicewsproxies wsproxies new wexprototypeservicewsproxies dttrips wsproxiesbuild sessionalltrips dttrips dttrips datatablesessionalltrips if dttrips null if cnt0 hidtripdetailsvalue trip name tripsummarybotripname was modified by user tripsummarybotriplasteditedby else hidtripdetailsvalue hidtripdetailsvalue br trip name tripsummarybotripname was modified by user tripsummarybotriplasteditedby buildgridviewcontroldttrips cnt cnt 1 else uptripsgridtriggersclear pageinit please suggestthanks,['asp.net'] +46103,automatic stylecop stylecop is an awesome little addon for visual studio but it does not show you live hints or provide any automated fixes along comes resharper and stylecop for resharper this is the ideal solution however it costs too much is there an open source way to achieve the live code hints and automated fixes for style copor is resharper the only way to do this at presentthanks in advance,['.net'] +46112,ways to accidentally create temporary objects in c years ago i believed that c was absolutely pure compared to c because the compiler could not generate any code that you could not predict i now believe counter examples include the volatile keyword and memory barriers in multiprocessor programming or device drivers for memorymapped hardware devices where plain assembly language would be even more pure than the optimizations of a c compilerat the moment i am trying to enumerate the unpredictable things a c compiler can do the main complaint that sticks in my mind about c is that the compiler will implicitly instantiate temporary objects but i believe these cases can all be expected the cases i am thinking of arewhen a class defines a copy constructor for a type other than itself without using the explicit keywordwhen a class defines an overloaded conversion operator operator when a function accepts an object by value instead of by referencewhen a function returns an object by value instead of by referenceare there any others,['c++'] +46122,maven build failed unable to locate the javac compiler in jre or jdk issue i have my java home set to cprogram files x86javajdk160 18after i run maven install i get this message from eclipsereasonunable to locate the javac compiler in cprogram files x86javajre6libtoolsjarplease ensure you are using jdk 14 or above andnot a jre the comsuntoolsjavacmain class is requiredin most cases you can change the location of your javainstallation by setting the java home environment variablei am certain that this is the tricky part please ensure you are using jdk 14 or above and not a jrewhen i run configuration its set to jre6 how do i change it to jdk 16 which i have already installedediti even tried to modify the plugin plugin groupidorgapachemavenpluginsgroupid artifactidmavencompilerpluginartifactid version202version configuration source16source target16target executablecprogram files x86javajdk160 18binexecutable configuration pluginstill i get the same errormaybe i forgot to say i use eclipse maven plugin how can i change from jre to jdk in eclipse,['java'] +46130,how to make a splash screen screen visible when app starts i have a simple application it starts loads xml feed from the net you can browse a list of news and then read details for a chosen news item what i would like to do is have a splash screen meaning as soon as you click application it should thisplay an image app name in my case and then thisplay news list only after they have loadedi read about similar i think problems and usually people say to use framelayout but i cannot really sort it out i am not sure if this can be done in the first activity that is launched maybe i should just thisplay this splash image in one activity and only then call activity thisplaying my news listi know that on iphone you can set splash screen in app settings while developing would be nice to have this functionality in androids apps manifest,['android'] +46133,convert an orgw3cdomnode into a string sorry i am a javaxml newbie and cannot seem to figure this one out it seems it is possible to convert a document object to a string however i want to convert a node object into a string i am using orgccilcowantagsoup parser for my purposei am retrieving the node by something like parser new orgccilcowantagsoupparser parsersetfeaturenamespaceaware false transformer transformer transformerfactorynewinstancenewtransformer domresult domresult new domresult transformertransformnew saxsourceparser new inputsourcein domresult node and domresultgetnode i am interested in the first child so node mynode ngetchildnodesitem0 convert mynode to string what to do herethe answer may be obvious but i cannot seem to figure out from the core java libraries how to achieve this any help is much appreciated,['java'] +46160,unicodeencodeerror when redirecting stdout i am having a problem regarding unicode in python i can print the output fine in a regular terminal but if i redirect stdout elsewhere or capture it with the subprocess module i get a unicodeencodeerror cat examplepy print uexample u00f1 python examplepy example a python examplepy devnulltraceback most recent call last file examplepy line 1 in module print uexample u00f1unicodeencodeerror ascii codec cannot encode character uxf1 in position 9 ordinal not in range128why is this how can i fix it,['python'] +46168,default visibility of class methods in php i look at the manual but cannot seem to find the answerwhat is the default visibility in php for functions without a visibility declaration does php have a package visibility like in java exampleclass test is go public or private function go the reason i asked because i have seen many constructors code writtenfunction construct and some public function construct are they equivalent,['php'] +46176,how do i check if a string has at least one number in it using ruby i need to check to see if a string contains at least one number in it using ruby and i assume some sort of regexhow would i do that,['ruby'] +46177,list all tables containing a given column name how do a i list all tables containing a given column name i am using mysql version 4113ntlog i know versions less than 5 dont have an information scheme db,['mysql'] +46196,trie implementation i am attempting to implement a very simple trie in java that supports 3 operations i would like it to have an insert method a has method ie is a certain word in the trie and a tostring method to return the trie in string form i believe i have insertion working properly but has and tostring are proving to be difficult heres what i have so farthe trie classpublic class caseinsensitivetrie implements simpletrie root node private trienode r public caseinsensitivetrie r new trienode public boolean hasstring word throws invalidargumentuosexception return rhasword public void insertstring word throws invalidargumentuosexception rinsertword public string tostring return rtostring public static void mainstring args caseinsensitivetrie t new caseinsensitivetrie systemoutprintlntesting some strings tinserttest tinserttatter systemoutprintlnthastest and the node classpublic class trienode make child nodes private trienode c flag for end of word private boolean flag false public trienode c new trienode26 1 for each letter in alphabet protected void insertstring word int val wordcharat0 64 if the value of the child node at val is null make a new node there to represent the letter if cval null cval new trienode if word length 1 then word is not finished being added otherwise set the flag to true so we know a word ends there if wordlength 1 cvalinsertwordsubstring1 else cvalflag true public boolean hasstring word int val wordcharat0 64 if cvalnull wordlength1 cvalhaswordsubstring1 else if cvalflagtrue wordlength1 return true return false public string tostring return so basically when creating a trie a trienode is created as the root with 26 children when an insert is attempted insert is called on that root node which recursively creates a new node at the correct position and continues until the word is complete i believe that method is working properlymy has function is very broken because i have to have that return statement outside of the brackets for some reason i cannot contain it within an else clause or the compiler complains other than that i am thinking that method should work with some tweaks but i cannot figure it out for the life of metostring is a beast i have tried to tackle but nothing i throw at it works so i will leave that be until i solve the has problem if i get has working i may be able to figure a way to reformat it into a tostring functionthe purpose of the int val wordcharat0 64 is because each string entered must be all caps i will create a string formatting function to ensure this afterwards so the first letters int value 64 will be it is position in the array ie array index 0 is a so a 64 a 64 0 b 65 b 64 1 and so on,['java'] +46198,whats the difference between opening a file with iosbinary or iosout or both i am trying to figure out the difference between opening a file likefstream filenamefiledatiosbinaryorfstream filenamefiledatiosoutorfstream filenamefiledatiosbinary iosouti found that all of these forms are identical in all cases the same output on the file is produced using either filename or filenamewrite,['c++'] +46202,why does cryptblowfish generate the same hash with two different salts this question has to do with phps implementation of crypt for this question the first 7 characters of the salt are not counted so a salt 2a07a would be said to have a length of 1 as it is only 1 character of salt and seven characters of metadatawhen using salt strings longer than 22 characters there is no change in the hash generated ie truncation and when using strings shorter than 21 characters the salt will automatically be padded with characters apparently this is fairly straightforward however if given a salt 20 characters and a salt 21 characters where the two are identical except for the final character of the 21length salt both hashed strings will be identical a salt 22 characters long which is identical to the 21 length salt except for the final character the hash will be different again example in codefoo barsalt xx 2a07salt 19 salt xx b1b2ee48991281a439dsalt 20 salt 19 asalt 21 salt 20 2salt 22 salt 21 bvar dump cryptfoo salt 19 cryptfoo salt 20 cryptfoo salt 21 cryptfoo salt 22will producestring60 2a07b1b2ee48991281a439ddeudhuoqxvquieltcp0cfvolhfcbunistring60 2a07b1b2ee48991281a439dauxgyn739wlkv5pgor1xa4evnvpjwylgstring60 2a07b1b2ee48991281a439da2uxgyn739wlkv5pgor1xa4evnvpjwylgstring60 2a07b1b2ee48991281a439da2o4ah0yasouzmpif4sbs8e2hqjpuqqwhy is thiseditsome users are noting that there is a difference in the overall string which is true in salt 20 offset 28 4 is da while in salt 21 offset 28 4 is da2 however it is important to note that the string generated includes the hash the salt as well as instructions to generate the salt ie 2a07 the part in which the difference occurs is in fact still the salt the actual hash is unchanged as uxgyn739wlkv5pgor1xa4evnvpjwylgthus this is in fact not a difference in the hash produced but a difference in the salt used to store the hash which is precisely the problem at hand two salts are generating the same hashrembmer the output will be in the following format2asaltsaltsaltsaltsaltsahashhashhashhashhashhashhashhash hash starts here offset 2832where is the logbase2 determining the number of iterations the algorithm runs foredit 2in the comments it was requested that i post some additional info as the user could not reproduce my output execution of the following codevar dump php version php os crypt salt length crypt std des crypt ext des crypt md5 crypt blowfishproduces the following outputstring5 530string5 winntint60int1int1int1int1hope this helps,['php'] +46205,c c how to copy a multidimensional char array without nested loops i am looking for a smart way to copy a multidimensional char array to a new destination i want to duplicate the char array because i want to edit the content without changing the source arrayi could build nested loops to copy every char by hand but i hope there is a better wayupdatei do not have the size of the 2 level dimension given is only the length rowsthe code looks like thischar tmpchar realdestint length somefunctionthatfillstmptmpnow i want to copy tmp to realdesti am looking for a method that copies all the memory of tmp into free memory and point realdest to itupdate 2somefunctionthatfillstmp is the function crethis lrange from the rethis c lib crethiscinside the lib tmp is created withrhndreplymultibulkbulks mallocsizeofchar cr multibulk sizeupdate 3i have tried to use memcpy with this linesint cb sizeofchar size 8 string inside 2 level has 8 charsmemcpyrealdesttmpcbcout realdest0 endlprints mystringbut i am getting a program received signal exc bad access,"['c++', 'c']" +46208,why does the following class have a virtual table suppose i have a diamond inheritance situation as follows class a public virtual void fooclass b public virtual a public virtual void fooclass c public virtual a public virtual void fooclass d b cthe last line yields a compilation error citing ambiguity as i understand it the problem is that the compiler does not know which foo to place in ds vtbl but why would there even be a vtbl for d if it does not define any virtual functions of its own,['c++'] +46216,instantiate a python class from a name so i have a set of classes and a string with one of the class names how do i instantiate a class based on that stringclass foo def init self left right selfleft left selfright rightstr foox initstr a bi want x to be an instantiation of class foo,['python'] +46218,encode nsarray or nsdictionary using nscoder i was wondering whether or not it is possible to use the nscoder method voidencodeobjectidobjv forkeynsstring keyto encode either an instance of nsarray or nsdictionary if not how do you go about encoding them i am trying to use nskeyedarchived nskeyedunarchiver to send data between phones using gamekit i tried it and cannot seem to retrieve the string i stored in my array the packet class i made comes through along with the packet type integer but not the data in the array it seemsthanks in advance,['iphone'] +46221,closures in c event handler delegates i am coming from a functionalprogramming background at the moment so forgive me if i do not understand closures in ci have the following code to dynamically generate buttons that get anonymous event handlersfor int i 0 i 7 i button newbutton new button newbuttontext click me newbuttonclick delegateobject sender eventargs e messageboxshowi am button number i thiscontrolsaddnewbuttoni expected the text i am button number i to be closed with the value of i at that iteration of the for loop however when i actually run the program every button says i am button number 7 what am i missing i am using vs2005edit so i guess my next question is how do i capture the value,['c#'] +46222,how to create an array of selectors i am using the iphone sdk 30 and i am trying to create an array of selectors to invoke a variety of methods within one classobviously i am doing something wrong i think selector is not considered a class and so stuffing them into an nsarray is not workingi tried this but it is obviously wrong is there a simple way to have an array of selectors like this or is there a better way to iterate through a collection of methodsselectors nsarray arraywithobjects selectormethod1 selectormethod2 selectormethod3 selectormethod4 selectormethod5 selectormethod6 selectormethod7 nilfor int i 0 i selectors count i if self performselectorselectors objectatindexi do stuff,"['iphone', 'objective-c']" +46225,how to delete all files in a specified directory on the app given a directory self documentsdirectory stringbyappendingpathcomponentphotos how do i delete all files in this folderassume a correct documents directory path,"['iphone', 'objective-c']" +46232,how to monitor clipboard content changes in c i want to have this feature in my c program when the user do ctrlc or copy anywhere ie when the clipboard content changes my program will get notified and check whether the content met certain criteria if so become the active program and process the content etci can get the contents out from systemwindowsformsclipboard however i do not know how to monitor the content changes from the clipboardcheersedit if using vista or later use addclipboardformatlistener as in john knoellers answer for xp have to use the older more fragile setclipboardviewer api as in the accepted answer,"['c#', '.net']" +46236,determine if a character is alphabetic having problems with thislet us say i have a parameter composed of a single character and i only want to accept alphabetic characters how will i determine that the parameter passed is a member of the latin alphabet aazby the way im using php kohana 3thanks,['php'] +46244,currency validation please help with me writing a javascript validation for currencymoney fieldso please provide any regular expressions if you have also for my region do not need any currency symbols like in the fieldonly decimals are to be included for validation as special chars along with numbers,['javascript'] +46245,how to update nsmutabledictionary i have an nsmutabledictionarynsmutabledictionary plistdict nsmutabledictionary alloc initwithcontentsoffilepathi have to update an element in that dictionary how i can do that,"['iphone', 'objective-c']" +46248,how to set vertical scroll bar in win form i am very new to win formi want to develop a form which has a height of around 9921403i tried to give the size of the win form as 9921403 but its taking only 992876i am setting an image of size 9921403 as the background i need to put a vertical scroll bar i put that scroll bar but i dnt know how to write the code when the user scrolls that scroll barplease give me some sample codes or links,['c#'] +46274,why does pylint give error e0702 raising nonetype on this raise statement say i have the following codedef foo foobar none if foobar is not none raise foobarwhen i run this code through pylint i get the following errore07024foo raising nonetype while only classes instances or string are allowedis this a bug in pylint is my pylint too oldpylint 0180 astng 0191 common 0450python 251 r25154863 aug 25 2008 092326 note i know this code does not make any sense it is thistilled to its bare bones to expose the issue at hand normally stuff happens in between line 2 and 3 which could make foobar not be none and no i cannot just raise an exception there because that happens in another thread that has restrictions on it,['python'] +46277,add spring 300 java based ioc to junit 47 tests there is a doc how to add ioc support to junit tests using xmlconfiguration but i can not find example for javabased configurationfor example i have javabased beanpublic class appconfig bean public test gettest return new test and testrunwithspringjunit4classrunnerclasspublic class ioctest autowired private test test test public void testioc assertassertnotnulltest what should i add to enable javabased beans to my junit test without using xmlconfigsnormally i usenew annotationconfigapplicationcontextappconfigclassbut it does not work for tests,['java'] +46278,deserialization not working on memorystream serialize the objectmemorystream ms new memorystreamiformatter formatter new binaryformatterformatterserializems objecttoserializebyte arrbyte new bytems lengthmsreadarrbyte 0 intms lengthmsclosedeserialize the objectstream s new memorystreamarrbytesposition 0object obj formatterdeserializesthrows an exceptionscloseif i try to deserialize with the above way it gives the exception as binary stream 0 does not contain a valid binaryheader possible causes are invalid stream or object version change between serialization and deserializationwhere below code is workingserialize the objectiformatter formatter new binaryformattermemorystream ms new memorystreamformatterserializems objecttoserializemsseek0 seekoriginbeginbyte arrbyte mstoarraydeserialize the objectstream s new memorystreambytstream1position 0object obj formatterdeserializesstream1closethe only difference is the first approach uses the read method to populate the byte array where as the second one uses the seek toarray to populate the byte arraywhat is the reason for the exception,['c#'] +46290,database for superfast querying we have a 300 gb data array wed like to query as fast as possible traditional sql databases specifically sql server cannot handle this volume as effectively as we need like perform a select with 1020 conditions in where clause in less than 10 sec so i am investigating other solutions for this problemi have been reading about nosql and this whole thing looks promising but i would prefer to hear from those who have used it in real lifewhat can you suggest hereedit to clarify what were afterwere a company developing an app whereby users can search for tours and perform bookings of said tours paying for them with their plastic cards this whole thing can surely be russiaspecific so bear with mewhen a user logs on to the site she is presented with a form similar to thishere user selects where she leaves from and where she goes to dates duration and all thatafter hitting search a request goes to our db server which with cannot handle such load queries include various kinds of parameters sharding does not work well eitherso what i am after is a some kind of a pseudodatabase which can do lightning fast queries,['sql'] +46291,create excel charts in java i have been using apache poi to create and modify excel spreadsheets but i am wondering if there is a way even if it is with a different library preferably open source to create charts in excel in the new xlsx format it looks like poi has an hssfchart but i believe that is for the older format please correct me if i am wrong has anyone used a java solution to create charts in excel,['java'] +46293,accessing a div with class using jquery i have a div with classfor example div classbutton checkdivthe css is defined for both buttoncheck i want to access the above div through jquery and write something in the divi tried with button checkhtmlsample datai do not see anything being written when i run the pageplease help me,['jquery'] +46309,whats log4j actually doing when we turn on or off some log places we know we can config log4j to turn off log on specific places class or package in java via its propertiesconfiguration file my questions are followedwhats log4j actually doing for those flags is the log statement in log4j still called but just not being written to file or console because of that flag so still have performance impactis it like ifdef in c which take effect at compile time then can limit the performance impactthanks,['java'] +46323,jquery javascript find first visible element after scroll i have code like belowdiv idcontainerdiv classitem id1blah blahdivdiv classitem id2blah blah 2divdivbut actually there are lots and lots of with classitem basically as the user scrolls this great long list of items i want to change the style of the current top visible one like google reader have looked around for solution in jquery or plain javascript but cannot seem to find one anyone have any ideasthanksmark,"['javascript', 'jquery']" +46328,spring mvc 3 validation unable to find a default provider i get an error when trying to set up spring mvc validationjavaxvalidationvalidationexception unable to find a default provideri read in the documents that the default provider they use is the hibernatevalidator do i need to include this library to get validation to work is it okay to include this library even though i am not using hibernate for my project,['java'] +46347,escaping jquery data being sent via post i am using jqueryajax to extract form data from a page and send it to my database via another php pagethe form information is collected byvar xdiv1valvar ydiv2valthis is used to build the post string ievar datavarxxvaryyobviously this is problematic if an ampersand character is used what is the best method to escape the variables particularly so that the user can safely use an ampersand thanks,"['javascript', 'jquery']" +46349,since strings are immutable do variables with identical string values point to the same string object a string s value string s1 valuedo s and s1 reference variables point to same string object iam assuming this due to the fact that strings are immutable b i realize equality operators etc have been redefined to compare the values of string objects but is the same true when comparing two strings using static methods objectequals and objectreferenceequalsthanx,"['c#', '.net']" +46353,pdo mysql server has gone away i have a script that does a lot of legwork nightlyit uses a pdo prepared statement that executes in a loopthe first few are running fine but then i get to a point where they all fail with the errormysql server has gone awaywe run mysql 5077php version 5212the rest of the site runs fine,"['php', 'mysql']" +46359,coredata predicate for tomany relationships i have a coredata model with 4 entitiesmodel screenshot statestatenamelocationlocationname attributelocationdescriptionlocationactivities relatinshipstate relationshiplocationactivitieslocation relationshipactivity relationshipactivitiesactivitynameattributelocationsactivities relationshiphow can i write a query that selects all locations that have activity golf or activity swimming and state la,"['iphone', 'objective-c']" +46361,how to mount a network directory using python i need to mount a directory dir on a network machine data using python on a linux machinei know that i can send the command via command linemkdir mntdata dirmount t datadir mntdata dirbut how would i send those commands from a python script,['python'] +46363,how to make css width to fill parent i am sure this problem has been asked before but i cannot seem to find the answeri have the following markupdiv idfoo div idbar here be dragons divdivmy desire is to make foo to have width of 600px width 600px and to make bar have the following behaviors paddingleft 2pxpaddingright 2pxmarginleft 2pxmarginright 2pxouterwidth 100in other words instead of setting width of bar to 592px i would like to set the outer width of bar to 100 so that it is computed to 592px the importance here is that i can change foos width to 800px and bar will calculate when rendered instead of me having to do the math for all these instances manuallyis this possible in pure csome more fun with itwhat if bar is a table what if bar is a textarea what if bar is an inputwhat if foo is a table cell td does this change the problem or is the problem identicalso far the tablebar inputbar has been thiscussed i have not seen a good solution for textareabar i think a textarea with no bordermarginpadding with a div wrap might work with the div styled to work as borders for the textarea,['css'] +46370,how to limit concurrent connections used by curl i made a simple web crawler using php and curl it parses rougly 60 0 html pages and retreive product information it is a tool on an intranetmy main concern is the concurrent connection i would like to limit the number of connection so whatever happens the crawler would never use more than 15 concurrent connections the server block the ip whenever the limit of 25 concurrent connections by ip is reached and for some reason i cannot change that on the server side so i have to find a way to make my script never use more than x concurrent connectionsis this possibleor maybe i should rewrite the whole thing in another languagethank you any help is appreciated,['php'] +46373,python newbie having a problem using classes im just beginning to mess around a bit with classes however i am running across a problemclass myclassobject def fself return hello worldprint myclassfthe previous script is returning unbound method myclassf instead of the intended value how do i fix this,['python'] +46399,in javascript how do i call a class method from another method in the same class i have thisvar test new function thisinit new function alerthello thisrun new function call init here i want to call init within run how do i do this,['javascript'] +46403,iphone splash defaultpng thisplays on simulator but not the iphone i am trying to give my iphone a splash screeni have placed defaultpng in my resources group when i run the simulator it is thisplayed as expected however when i install my application to the iphone no splash screen is thisplayeddoes anyone know what the causesolution to this problem isthanks,"['iphone', 'objective-c']" +46407,rails actioncontroller execute same code for every action to the rails experts out there i was wondering wherehow you would execute the same code for every action in your web application if you can point me to an article or provide a short code snippet i would greatly appreciate itthanks in advance to anyone who can help,['ruby-on-rails'] +46418,can excessive use of final hurt more than do good why are people so emphatic about making every variable within a class final i do not believe that there is any true benefit to adding final to private local variables or really to use final for anything other than constants and passing variables into anonymous inner classes i am not looking to start any sort of flame war i just honestly want to know why this is so important to some people am i missing something,['java'] +46426,are anonymous types in c accessible through reflection as the name of the anonymous type is compiler generated so is it accessible through reflection,['c#'] +46431,accessing a web service from your browser i am relatively new to how web services work so i have gone though a tutorial from which sets up a web service that prints hellothe code to print out hello is here in the same project here there is another web service that adds two numbers togetherto access the hello web service i just go to my browser and go to httplocalhost8080bridgeservicesversiongetversion but how do i do that for the calculator web service whats the url or do i have to do something extra to register that as a service first,['java'] +46439,image resized error cgbitmapcontextcreate unsupported parameter i am using the following code from a blog post to resize an image if inimagesizewidth inimagesizeheight portrait ratio inimagesizeheight inimagesizewidth resizedrect cgrectmake0 0 width width ratioelse landscape ratio inimagesizewidth inimagesizeheight resizedrect cgrectmake0 0 height ratio heightcgimageref imageref inimage cgimagecgimagealphainfo alphainfo cgimagegetalphainfoimagerefif alphainfo kcgimagealphanone alphainfo kcgimagealphanoneskiplastcgcontextref bitmap cgbitmapcontextcreate null resizedrectsizewidth width resizedrectsizeheight height cgimagegetbitspercomponentimageref really needs to always be 8 4 resizedrectsizewidth rowbytes cgimagegetcolorspaceimageref alphainfo but for some reason depending on the size i am try to resize to i get the following error generatedcgbitmapcontextcreate unsupported parameter combination 8 integer bitscomponent 32 bitspixel 3component colorspace kcgimagealphanoneskipfirst x bytesrowwhere x differs depending on which imagethe rect i am creating is propotional to the image i take a ratio from the widthheight depending on aspect and multiple that be target widthheighthere are some examples x errors doesnt the resize size will be 50xx or xx50 depending on aspectsource 50x50 69x69430x320 x240x320 272x320 480x419 x426x320 x x480x256 x x,"['iphone', 'objective-c']" +46441,influencing aop with attributes via ioc codesmell or elegant i am using structuremap at the moment generally with conventionbased scan autoconfiguration and i am looking to add decoratorbased caching into the pipelineif i configure it manually that is fine but scan is just so convenient when you get lots of dependencies i am toying with noting cache suggestions on the interfaces for examplepublic interface ifoo cacheduration20 cache for 20 minutes string dosomethingreusable sometype dosomethingnonreusableint key not cachedwith the idea being that by adding a custom convention to structuremaps scanning pretty easy it can spot that oneormore methods are decorated for caching and automatically inject a generated caching decorator into that types pipeline generating a cache key from the interfacemethod name and parameter valueson the plus side it makes adding caching very painless just decorate the interface a little but is is a code smell andor am i duplicating something that is already solved,"['c#', '.net']" +46445,making a borderless window with for qt i am new to qt c i downloaded the latest windows version did some tutorials and its greati saw some styling options that the qt framework has and its great but now i need to build my application that its main windows form it designedskinned with image without the rectangle borders borderlesshow can i do it with qt,['c++'] +46451,how do i write a logger class with cout style interface logger error val endl i want to create a logger class such that with a functionality like thislogger loglog error value seen endlthis should print me a custom formatted message eg 12092009 112233 error 5 seenmy simple class currently looks like thisclass logger private ostringstream oss public template typename t logger operatort atemplate typename tlogger loggeroperatort a oss a return thisvoid functiontestvoid logger log log error 5 seenthis will cause oss to correctly have the buffer error 5 seen but i dont know what other function i need to writemodify so that something prints on the screendoes anyone know how to get this to work or is there another way to design this class to have my functionality work,['c++'] +46462,inotifypropertychanged and calculated property suppose i have simple class order that have a totalprice calculated property which can be bound to wpf uipublic class order inotifypropertychanged public decimal itemprice get return thisitemprice set thisitemprice value thisraisepropertychangeditemprice thisraisepropertychangedtotalprice public int quantity get return thisquantity set thisquantity value thisraisepropertychangedquantity thisraisepropertychangedtotalprice public decimal totalprice get return thisitemprice thisquantity is it a good practice to call raisepropertychangedtotalprice in the properties that affect to totalprice calculation what is the best way to refresh totalprice property the other version to do this of course is to change property like thispublic decimal totalprice get return thisitemprice thisquantity protected set ifvalue 0 throw argumentexceptionset method can be used for refresh purpose only and call totalprice 1 instead of thisraisepropertychangedtotalprice in other properties please suggest solutions betterthanks a lot,['c#'] +46468,how to attach back the android emulator to adb after i start the emulator by hitting debug in eclipse after certain time it thisconnects from the adb but the emulator stays open it is responsive i can navigate and start appshow can i attach back the emulator to adb to be able to debug from eclipsethe current workaround is the terminate the emulator close eclipse and restart both of them which takes 10 minutes as you know the emulator needs time to start upedit 1check out this imageedit 2after i kill and restart server one emulator process shows up in devices tab in eclipse but that cannot be expanded and i do not see subprocessesi cannot hit debug already as it says debug already running how to i stop the debugif i managed to start the debugging of another project it hangs out in the emulator telling me waiting for the debugger to attach nothing happens,['android'] +46482,f vs haskell vs lisp which language to learn i have heard a lot about functional programming languages and i am willing to learn one i guess it will be mostly for fun however i hope it will improve my programming skillsi have mostly cnet background so my first choice is to learn f because of net and familiarity with visual studio on the on other hand i wonder if f has features like lisp macros or haskell higher order functionscould you compare f haskell and lisp which one will be the language of your choice,['c#'] +46493,how to increase a decimals smallest fractional part by one i want to increase a decimals smallest fractional part with one so that for exampledecimal d 001dd 002ordecimal d 012349dd 012350how do i do this,['c#'] +46500,d enum like entities i have the following db modelperson tableid name stateid1 joe 12 peter 13 john 2state tableid desc1 working2 vacationand domain model would be simplifiedpublic class person public int id get public string name get set public state state get set public class state private int id public string name get set the state might be used in the domain logic egifpersonstate stateworking some logicso from my understanding the state acts like a value object which is used for domain logic checks but it also needs to be present in the db model to represent a clean ermso state might be extended topublic class state private int id public string name get set public static state new get return new statehardcodedidhere hardcodenameherebut using this approach the name of the state would be hardcoded into the domain do you know what i mean is there a standard approach for such a thing from my point of view what i am trying to do is using an object which is persisted from the erm design perspective as a sort of value object within my domain what do you thinkquestion updateprobably my question was not clear enoughwhat i need to know is how i would use an entity like the state example that is stored in a database within my domain logic to avoid things like ifpersonstateid stateworkingid some logicorifpersonstateid working id some logic,"['c#', '.net']" +46501,c linq where date between 2 dates i am trying to get my linq statement to get me all records between two dates and i am not quite sure what i need to change to get it to work astart startdate enddatevar appointmentnoshow from a in appointments from p in properties from c in clients where aid poid astartdate startdatedate enddate,['c#'] +46507,how do i load external fonts into an html document how do i load external font files into an html documentexample make the text blah blah blah blah blah blah blah a custom font from a ttf file in the same directory using html css andor javascript,['html'] +46514,what is an objects hash code if hashcode is not overridden if the hashcode method is not overridden what will be the result of invoking hashcode on any object in java,['java'] +46519,trigger documentready so ajax code i cannot modify is executed my requirements are the followingi have got a rich webpage that at a certain moment loads a bunch of html in a div via ajaxthe html i retrieve does have javascript scriptscriptthe retrieved javascript contains documentready partsi can not modify the retrieved javascript it comes from an external libi have got a javascript function that is called when the ajax is loaded i am trying to trick it into executing by doingfunction ajaxloaded documenttriggerreadythat does not cut it i am afraidi have seen several responses on stack overflow that evade this question by changing the code that is returned on the ajax make it a function and call it after loading or just remove the documentready i need to stress out that i cannot change the retrieved code on this case,"['javascript', 'jquery']" +46523,forward declaration of nested enum i have code similar to the followingclass bclass a enum eone etwo emyenum b mybi want to declare a member of type emyenum in class b which is declared before a is this possible i realise the solution is to declare class b second but for clarity i would prefer not to,['c++'] +46525,how can i get past does not appear to be a repository error message question 828421 asked similar question but received only one real answer update rubygems and that attempt results in the same errorruby version 191p243 on windows included gem version 135never installed any gems before never did any special config for this rubyruby itself works as does irb and gem operates but cannot do install and maybe other opstried this from a bookgem install rspecgot thiserror does not appear to be a repository error while executing gem gemremotefetcherfetcherror socketerror getaddrinfo the storage control blocks were destroyed when i go to that url without yaml using msie7 i get a page titled gemcutter awesome gem hosting and have no problem wandering around that site so i do not think it is a proxy problem though this is all from inside corporate firewallproxiesetcwhen i go to that url with yaml it goes to and shows what i assume is an update specification page starting with this rubyobjectgemsourceindexi did not destroy any storage control blocks so what is preventing gem from installing a gemweb search shows many people having this same problem over a long span of time but i have yet to see anyone say it is because of this so do this to fix it well someone suggested updating gem but trying that gets same errorhelp please,['ruby'] +46530,factory girl and has one heres my models class audition belongs to videoendclass video has one auditionendand my factories factorydefine video do v vfilename shamfilename vvideo url shamurlendfactorydefine audition do a avideo a aassociationvideo alabel shamlabelendhow could i create a video factory that have an auditioni mean be able to v factorycreatevideovaudition i would like this to be not nil because i have an observer on my video that try to access the audition from the video objecti tried several things but i always end with a stack level too deep or audition nildo you have an idea thanksmike,['ruby-on-rails'] +46534,what is the difference between access specifiers and access modifiers in java are access specifiers and access modifiers the same thing,['java'] +46542,how do i find out the error count in a aspnet mvc view i want to format the title of my validationsummary using a string something likethere are 0 errors on this pagehow do i find out the number of errors without doing it in the controller and adding it to viewdata,['asp.net'] +46547,use rackcommonlogger in sinatra i have a small webserver that i wrote with sinatra i want to be able to log messages to a log file i have read through and wsinatrarbcomintrohtml and i see that rack has something called rackcommonlogger but i cannot find any examples of how it can be accessed and used to log messages my app is simple so i wrote it as a toplevel dsl but i can switch to subclassing it from sinatrabase if that is part of whats required,['ruby'] +46549,how to increase storage for android emulator install failed insufficient storage i get this sometimesnot often for one of my projects couple of classes onlyinstallation error install failed insufficient storagehow do i increase emulators storage,['android'] +46552,what does the operator string some code do i have the following code in a classoperator string return formatcnd fdand wanted to know what this operator doesi am familiar with the usual string operatorsbool operatorconst string c1 const string c2bool operatorconst string c1 const string c2bool operatorconst string c1 const string c2bool operatorconst string c1 const string c2bool operatorconst string c1 const string c2bool operatorconst string c1 const string c2string operatorconst string s1 const string s2 string operatorconst char s const string s2 string operator char c const string s2 string operator const string s1 const char s string operator const string s1 char c string operatorconst string appendstring operatorconst char appendstring operatorconst char appendostream operator ostream os const string s istream operator istream is string s string operator const string s string operator const char s string operator char ch char operator size type index const char operator size type index const but not this one,['c++'] +46559,how can i iterate over cookies using jquery or just javascript i am using the cookie plugin by klaus hartl to add or update cookies at documentready i have another event that is supposed to iterate all the cookies and do something with the value of each cookie how can i iterate over the collection of cookies and get the id and value of eachi am thinking something like thiscookieeachfunctionid value alertidid valvalue,"['javascript', 'jquery']" +46580,in emacs how can i use imenu more sensibly with c i have used emacs for a long time but i have not been keeping up with a bunch of features one of these is speedbar which i just briefly investigated now another is imenu both of these were mentioned ininemacshowcanijumpbetweenfunctionsinthecurrentfileusing imenu i can jump to particular methods in the module i am working in but there is a parse hierarchy that i have to negotiate before i get the option to choose with autocomplete the method nameit goes like this i type mx imenu and then i get to choose using or types the using choice allows me to jump to any of the using statements at the top level of the c file something like imports statements in a java module for those of you who do not know c not super helpful i choose types then i have to choose a namespace and a class even though there is just one of each in the source module at that point i can choose between variables types and methods if i choose methods i finally get the list of methods to choose from the hierarchy i traverse looks like this usingtypes namespace class types variables methods method namesonly after i get to the 5th level do i get to select the thing i really want to jump to a particular methodimenu seems intelligent about the source module but kind of hard to use am i doing it wrong,['c#'] +46591,is cherrypy a robust webserver ie is it reliable under a huge load like apache i am wondering because cherrypy is from my knowledge built purely in python which is obviously slower than c et al does this mean that it is only good for dev testing environments or could i use it behind nginx like i use apache with fast cgi currently,['python'] +46602,c does visual studio 2008 have a tool to show which exceptions could be raised by a piece of code for example if i am opening a file i know a filenotfoundexception might happen or if i am converting a string to double a formatexception may happen obviously if a method does both both can be raised is there a way to quickly see all possible exceptions raised by a method though keeping track of it myself seems error prone,['c#'] +46604,is it possible to declare a function without arguments but then pass some arguments to that function without raising exception in python is it possible to have the above code without raising an exception def myfunc pass typeerror myfunc takes no arguments 1 givenmyfuncparamusually in php in some circumstances i launch a function without parameters and then retrieve the parameters inside the functionin practice i do not want to declare arguments in myfunc and then passing some arguments to it the only one solution i found is myfuncarg are there any other methods,['python'] +46610,android import export database there i am trying to implement a feature into my app to copy the current database unto the sdcard are there any tutorials or code snippets to achieve this i have already looked at this site but i wont be able to import the data with this method,['android'] +46618,python regex r prefix can anyone explain why example 1 below works when the r prefix is not usedi thought the r prefix must be used whenever escape sequences are usedexample 2 and example 3 demonstrates this example 1import reprint resubs hello there there prints hello there there not expected as r prefix is not used example 2import reprint resubrbws1b r1 hello there there prints hello there as expected as r prefix is used example 3import reprint resubbws1b 1 hello there there prints hello there there as expected as r prefix is not used,['python'] +46622,jformattedtextfield using a regular expression formatter after much frustration with getting a jformattedtextfield to work with my custom formats i was wondering if there was a formatter or formatterfactory that uses regular expressionsmy idea is that if there is one then i could wrap it in a static class and invoke it like somformattedtextfieldsetformatterfactory somestaticclassgetregexformatfactoryd1hs0509msee my previous question for more background i want to use a jformattedtextfield to allow the user to input time duration values into a form sample valid values are 2h 30m 72h 15m 6h 0h,['java'] +46625,how to programmatically retrieve information from ldap i am running an aspnet page on iis7 and developing in vs 2008 currently i have user authentication being done through an ldap connection once the user logs in on one page they have a form with some basic information about them such as their name email address country and the like and i wish to pre populate some of these fields from information already stored in the ldap in particular their given name and email addresses the question is using c how do i actually retrieve this information,['asp.net'] +46653,how to use tabhostontabchangelistener in android how to use tabhostontabchangelistener in androidgive me some example code thanks,['android'] +46654,changing background color of the form with hexadecimal code i have one method named changeformbackgroundcolor colorname which changes the form background with the colorname which is the parameter of the methodnow when i call this method i have not color name but the hexadecimal code of the color and i want to change the background color of the form with that hexadecimal code using that method then what should i do,"['c#', '.net']" +46672,list vs bindinglist advantagesthisadvantages can someone describe what the difference between the two are for my projectcurrently i have a listmyclass and set the bindingsource to that and a datagridview to the bindingsourcei have implemented ieditableobject so when canceledit is called i revert my object back to what it was with a memberwiseclonewill changing my list to a bindinglist solve any of this and what are the advantages of using a bindinglist,"['c#', '.net']" +46680,get a try statement to loop around until correct value obtained i am trying to get a user to enter a number between 1 and 4 i have code to check if the number is correct but i want the code to loop around several times until the numbers is correct does anyone know how to do this the code is belowdef release try print please select one of the followingncompletion 0nrelease id 1nversion id 2nbuild id 3n a intinputplease select the type of release required if a 0 filesa elif a 1 filesa elif a 2 filesa elif a 3 filesa else raise incorrect except incorrect print try again except print errorreleasei am also getting an error about the exception i have enteredkillpy20 deprecationwarning catching of string exceptions is deprecated except incorrecterrorthanks for any help,['python'] +46681,jquery click event propagation i have a table with click events bound to its rows tr there are a elements inside those rows with their own click events assignedproblem is when i click on the a element it also fires the click event from the parent tr i do not want this behavior i just want to fire the a click eventcode event row tr trnotfirstclickfunction window backfundo closeremove var position thisoffsettop position position 0 20 position bodyappend divdivaddclassbackfundo bodyappend divdivaddclasswindow htmlspan classcloseimg srcimagesclosepng idfechar span append span classtituloo que deseja fazerspan span classcruda href idediteditaraspan span classcruda href iddelete codigo thischildrentdfirsthtml excluiraspan csstop20px fadeinslow documentscrolltop0 a element event aliveclickfunction alertclicked whenever you click the anchor it fires event from it parent row any ideas,['jquery'] +46686,string comparison in net vs i always assumed that net compares strings lexicographically according to the current culture but there is something strange when one of the strings ends on comparetoreturns 11compareto1returns 1i get it an all cultures i tried including the invariant onecan anyone explain what is going on and how can i get the consistent characterbycharacter ordering for the current locale,"['c#', '.net']" +46688,does anyone know of a spell checker plugin for ckeditor that uses aspell or a similar local service instead of spellcheckernet we are using ckeditor on our cms product and does not want to use the built in spell checker from spellcheckernet does anyone know of other plugins like eg the old fckeditor plugin which used aspell serverside,"['php', 'javascript']" +46690,find boost bgl vertex by a key i am looking for a way to access vertex properties by using a key instead of vertex reference itselffor example if i haveclass data public stdstring name unsigned int value typedef boostadjacency list boostvecs boostvecs boostdirecteds data graphtypedef boostgraph traitsgraphvertex descriptor vertexinstead of usingvertex vertex1 boostadd vertex g gvertex1name alphagvertex1value 10i would like to havegalphaname alphagalphavalue 10does a ready to use mechanism exist,['c++'] +46705,dynamic programming algorithm n k problem an algorithm which will take two positive numbers and and k and calculate the biggest possible number we can get by transforming and into another number via removing k digits from n for ex let say we have n12345 and k3 so the biggest possible number we can get by removing 3 digits from and is 45 other transformations would be 12 15 35 but 45 is the biggest also you cannot change the order of the digits in and so 54 is not a solution another example would be n621542 and k3 so the solution will be 654 i know this is a dynamic programming related problem and i cannot get any idea about solving it i need to solve this for 2 days so any help is appreciated if you do not want to solve this for me you do not have to but please point me to the trick or at least some materials where i can read up more about some similar issuesthank you in advance,['c++'] +46710,blocking recv call hangs if server is down another socket problemin my client code i am sending some packet and expectign some response from the server side send recv it is blockingimmediately after send the server crashes and rebooted itself in the meantime the recv is waiting but even after the server is up the receive call is hanging i have added sigpipe signal handling but its still not able to recognize that the socket is brokenwhen i cancel the operation i got the error from recv that interrupt has been issued anyone could help me how to rectify this errorthis is in a shared library running on solaris machine,['c'] +46718,order of operator overload resolution involving temporaries consider the following minimal exampleinclude iostreamusing namespace stdclass myostream public ostream public myostreamostream const other ostreamotherrdbuf int main cout hello world endl myostream scout s hello world endl myostreamcout hello world endlthe output both on g and on visual c ishello worldhello world0x4012a4the version that writes to a temporary object myostreamcout appears to prefer the member operator ostreamoperatorvoid instead of the free operator operatorostream char it seems to make a difference whether or not the object has a namewhy does this happen and how do i prevent this behaviouredit why it happens is now clear from various answers as to how to prevent this the following seems appealingclass myostream public ostream public myostream operatorchar const str stdoperatorthis str return this however this results in all kinds of ambiguities,['c++'] +46746,how do i write to a hidden file i am using the textwriter to try to write to a hidden file and it is throwing an exception i cannot seem to figure out how to write to a hidden fileusing textwriter tw new streamwriterfilename twwritelinefoo twcloseexceptionunhandled exception systemunauthorizedaccessexception access to the path emediaphotos200608picasaini is deniedhow can i write to a hidden file,['c#'] +46749,how can i filter a pcap file by specific protocol using python i have some pcap files and i want to filter by protocol ie if i want to filter by http protocol anything but http packets will remain in the pcap file there is a tool called opendpi and it is perfect for what i need but there is no wrapper for python languagedoes anyone knows any python modules that can do what i needthanksedit 1http filtering was just an example there is a lot of protocols that i want to filteredit 2i tried scapy but i do not figure how to filter correctly the filter only accepts berkeley packet filter expression ie i cannot apply a msn or http or another specific filter from upper layer can anyone help me,['python'] +46756,how do i list all tables in a schema in oracle sql how do i list all tables in a schema in oracle sql,['sql'] +46757,jvm crashes under stress on rhel 52 i have got the currently latest jdk 16018 crashing while running a web application on the currently latest tomcat 6024 unexpectedly after 4 to 24 hours 4 hours to 8 days of stress testing 30 threads hitting the app at 6 mil pageviewsday this is on rhel 52 tikangathe crash report is at and the consistent parts of the crash area sigsegv is being thrownon libjvmsoeden space is always full 100jvm runs with the following optionscatalina optsserver xms512m xmx1024m djavaawtheadlesstruei have also tested the memory for hardware problems using for 48 hours 14 passes of the whole memory without any errori have enabled verbosegc xxprintgcdetails xxprintgctimestamps to inspect for any gc trends or space exhaustion but there is nothing suspicious there gc and full gc happens at predicable intervals almost always freeing the same amount of memory capacitiesmy application does not directly use any native codeany ideas of where i should look nextedit more info1 there is no client vm in this jdkfoolocalhost java version serverjava version 160 18javatm se runtime environment build 160 18b07java hotspottm 64bit server vm build 160b13 mixed modefoolocalhost java version clientjava version 160 18javatm se runtime environment build 160 18b07java hotspottm 64bit server vm build 160b13 mixed mode2 changing the os is not possible3 i do not want to change the jmeter stress test variables since this could hide the problem since i have got a use case the current stress test scenario which crashes the jvm i would like to fix the crash and not change the test4 i have done static analysis on my application but nothing serious came up5 the memory does not grow over time the memory usage equilibrates very quickly after startup at a very steady trend which does not seem suspicious6 varlogmessages does not contain any useful information before or during the time of the crashmore info forgot to mention that there was an apache 2214 fronting tomcat using mod jk 1228 right now i am running the test without apache just in case the jvm crash relates to the mod jk native code which connects to jvm tomcat connectorafter that if jvm crashes again i will try removing some components from my application caching lucene quartz and later on will try using jetty since the crash is currently happening anytime between 4 hours to 8 days it may take a lot of time to find out whats going on,['java'] +46780,java generics collectionsmax signature and comparator i understand the get and put principle for collections if a method takes in a collection that it will write a type t to the parameter has to be collection super t whereas if it will read a type t from the parameter has to be collection extends tbut could someone please explain the collectionsmax signaturepublic static t t maxcollection extends t coll comparator super t compin particular why is it comparator super t instead of comparator extends t,['java'] +46785,how can i determine if a geopoint is thisplayed in currently viewable area say i have mapview control in my android app if i know a landmark exists at a certain latitude and longitude how can i determine if that landmark is currently viewable on the users screen is there a method for getting the coordinates for the top left and bottom right corners of the visible area,['android'] +46789,play flv in html can anyone give a concise instruction on how i can have a flv play from my html page please,['html'] +46797,how do i make a portable isnanisinf function i have been using isinf isnan functions on linux platforms which worked perfectlybut this did not work on osx so i decided to use stdisinf stdisnan which works on both linux and osxbut the intel compiler does not recognize it and i guess its a bug in the intel compiler according to so now i just want to avoid the hassle and define my own isinf isnan implementationdoes anyone know how this could be doneediti ended up doing this in my source code for making isinfisnan workinginclude iostreaminclude cmathifdef intel compilerinclude mathimfhendifint isnan localdouble x ifdef intel compiler return isnanxelse return stdisnanxendifint isinf localdouble x ifdef intel compiler return isinfxelse return stdisinfxendifint mychkdouble a stdcerrval is a t ifisnan locala stdcerrprogram says isnan ifisinf locala stdcerrprogram says isinf stdcerrn return 0int main double a 0 mychka mychkloga mychkloga mychk0loga mychklogaloga return 0,"['c++', 'c']" +46798,nested forms in rails accessing attribute in has many relation i have a user and a profile model one user can have many profiles i need to access only one information from the profiles section viz the phone number in my user model during the user creation process hence i am trying to get it done through attr accessible my userrb looks like thishas many profilesattr accessible handle email password profile mobile numberattr accessor profile mobile numberthe problem that i am facing is that when i try to call the getter method profile mobile number in a method in userrb the method is private though i think it does not matter i am getting a null value i use the following in my usersnewhtmlerb form form for user do f ffields for profile do ff my question is what is the right way to do this should i use ffields for profile do ff or ffields for profiles do ff notice that the second one is plural when i use the plural profiles i do not even see the fields on the form what am i missing here and what is the tense that needs to be used in model userrb profile phone number or profiles phone number thanks,"['ruby-on-rails', 'ruby']" +46802,how can i swallow all exceptions and protect my application from crashing i have found several c application crashes in response to error conditions such as obj null or objmember null a lot of time the obj from the interface of 3rdpartyappand caused both 3rdpartyapp and mycsapp crashed togetherhow could i add exception handling in all possible areas so that my application can survive in these thisastrous situations it is a challenge to add trycatch to all places and recover from the situation how could i accomplish this in a way which is realistic reliable and bulletproofupdate industry automation controlstructureguiaspnet c runtimeapp c mycsappcs 3rdpartyappcsnormal procedurehostapp connect through ethernet cabelemycsappoperator gui runtimeapp mycsappabnormal conditionssome nonstandard operation proceduresome hardware issue occurredetci would better handle all the abnormall conditions and most importantly i must think how to recover from the situations,['c#'] +46803,if name main equivalent in ruby i am new to ruby i am looking to import functions from a module that contains a tool i want to continue using separately in python i would simply do thisdef a def b if name main a bthis allows me to run the program or import it as a module to use a andor b separately whats the equivalent paradigm in ruby,"['python', 'ruby']" +46810,how to use javascript regex to check for empty form fields i am working on a phpjavascript based project and have already made up a mockup page at my websitei knew how to use javascript or php to check whether a particular field of form is emptyor not that is whether it contains alphanumerical characters other than whitepsace charactersfor instance space tab and newlinehowever my normal apporach no longer works since the jquery plugin that i am using now relies on regex to validate the fieldsif you go to the third tab3 fill up shipping info and make payment you can enter something into the firstname field and it does the check automatically fine however ifyou just simply put some space characters there and jump to the next field well it still feels okay for that which is not correct since no ones first name is nothingthe problem at the back it has a regex like this nospecialcaracters regex09azaz alerttext no special caracters allowedthis would not filter out empty characters i searched online and tried my best to make up another regex to match i tried regexfor matching nonempty characters but that will not docan anyone help me out many thanks in advance,"['javascript', 'jquery']" +46812,javas collectionsshuffle is doing what i recently found myself needing to be sure my list was not in order hibernate was nice enough to return it in perfect order silly hibernate not reading my mindi looked at my java api and it tells me its shuffle method does thisrandomly permutes the specified list using a default source of randomnessbeing the curious george that i am i want to know what exactly this means is there a math course i can take to learn this can i see the code java what are you doing to my arraylistto be more specific which math concepts are being used here,['java'] +46817,concurrentnonblocking console keyboard input i am working on a mud in java i read player input every tick but i am using scanner which uses blocking operations i want to have nonblocking input i have looked at the nio package which has a selector class but i am not sure how to use it with regard to systemin i figure i will definitely need it once i am running a server but for now everything is offlinei have tried extending the main class from applet and overriding keydown but that just meant input was no longer accepted after the first one sure i was not blocking anything anymore but then there was no more input keydown never got called again i guessperhaps threads can be interrupted even when they are executing blocking operationsthanks for any insight into this problem,['java'] +46829,c immutability and public readonly fields i have read in many places that exposing fields publicly is not a good idea because if you later want to change to properties you will have to recompile all the code which uses your classhowever in the case of immutable classes i do not see why you would ever need to change to properties youre not going to be adding logic to the set after allany thoughts on this am i missing somethingexample of the difference for those who read code more easily than text immutable tuple using public readonly fieldspublic class tuplet1t2 public readonly t1 item1 public readonly t2 item2 public tuplet1 item1 t2 item2 item1 item1 item2 item2 immutable tuple using public properties and private readonly fieldspublic class tuplet1t2 private readonly t1 item1 private readonly t2 item2 public tuplet1 item1 t2 item2 item1 item1 item2 item2 public t1 item1 get return item1 public t2 item2 get return item2 of course you could use autoproperties public t1 item1 get private set but this only gets you agreed immutability as opposed to guaranteed immutability,['c#'] +46853,how to refresh android listview how to refresh an android listview after addingdeleting dynamic data,['android'] +46855,java email extraction regular expression i would like a regular expression that will extract email addresses from a string using java regular expressionsthat really works,['java'] +46866,storing money amounts in mysql i want to store 350 into a mysql table i have a float that i store it in but it stores as 35 not 350 how can i get it to have the trailing zero,['mysql'] +46867,why is is implemented as as given that this is a very natural use case if you do not know what as actually doesif x is bar bar y x as bar somethingis effectively equivalent that is the compilergenerated cil from the above code will be equivalent tobar y x as barif y null y x as bar the conversion is done twice somethingediti guess i had not made my question clear i wouldnt ever write the second snippet as it is of course redundant i am claiming that the cil generated by the compiler when compiling the first snippet is equivalent to the second snippet which is redundant questions a is this correct b if so why is is implemented like thatthis is because i find the first snippet a lot clearer and prettier than the actually wellwrittenbar y x as barif y null somethingconclusionoptimizing the isas case is not the compilers responsibility but the jit isalso as with a null check it has fewer and less expensive instructions than both of the alternatives is and as and is and castaddendumcil for as with nullcheck net 35l 01 ldarg1l 02 isinst stringl 07 stloc0l 08 ldloc0l 09 ldnul 0a ceql 0c stloc1l 0d ldloc1l 0e brtrues l 0019l 0011 ldarg0l 0019 retcil for is and cast net 35l 01 ldarg1l 02 isinst stringl 07 ldnul 08 cgtunl 0a ldci40l 0b ceql 0d stloc1l 0e ldloc1l 0f brtrues l 0021l 0012 ldarg1l 0013 castclass stringl 0018 stloc0l 0019 ldarg0l 0021 retcil for is and as net 35l 01 ldarg1l 02 isinst stringl 07 ldnul 08 cgtunl 0a ldci40l 0b ceql 0d stloc1l 0e ldloc1l 0f brtrues l 0021l 0012 ldarg1l 0013 isinst stringl 0018 stloc0l 0019 ldarg0l 0021 retthese have been edited for shortness method declarations nops and calls to something removed,"['c#', '.net']" +46871,sphinx python pdf generator i use sphinx python documentation generator creating pdf documents are very easy and simple but i have one problem all generated pdf documents have english words like chapter release part is it possible change it how set another words or remove it,['python'] +46891,in c main need not be a function this code compiles but no surprises it fails while linking no main foundlisting 1void mainlink error mingwliblibmingw32amainomainctext0x106 undefined reference to winmain16but the code below compiles and links fine with a warninglisting 2void mainwarning main is usually a functionquestionsin listing 1 linker should havecomplained for missing main whyis it looking for winmain16the executable generated fromlisting 2 simply crashes what isthe reasonthanks for your time,['c'] +46898,efficent way to bulk insert with get or create in django sql python django is there a more efficent way for doing thisfor item in item list e new entryobjectsget or create field1 itemfield1 field2 itemfield2,['python'] +46910,benefits of using sql ordinal position notation background informationordinal position notation aka ordinals is column shorthand based on the column order in the list of columns in the select clause instead of either the column name or column alias commonly supported in the order by clause some databases mysql 323 postgresql 80 support the syntax for the group by clause as wellheres an example of using ordinalsgroup by 1 2order by 1 2it is not good to use because it makes the query brittle if the column order changes the ordinals need to be updated or your query would not return what you thought it would very likely youd get an error when used in the group by if the columns at those locations are wrapped within aggregatesthe questionthe only benefit i can think of is less data to send over the wire if you are not using stored procedures or functions which make ordinal usage moot to me anyways are there any other benefits i am missingthisclosurethis might sound like a homework assignment but it is really research for an educational lunch the office puts on every month they pay for lunch we have to provide a small topic of interest,['sql'] +46912,managing css explosion i have been heavily relying on css for a website that i am working on right now all the css styles are being applied on a per tag basis and so now i am trying to move it to more of an external styling to help with any future changesbut now the problem is that i have noticed i am getting a css explosion it is becoming difficult for me to decide how to best organize and abstract data within the css filei am using a large number of div tags within the website moving from a heavily tablebased website so i am getting a lot of css selectors that look like thisdivtitle backgroundcolor blue color white textalign centerdivfooter styles here divbody styles here and many more it is not too bad yet but as i am a beginner i was wondering if recommendations could be made on how best to organize the various parts of a css file i do not want to have a separate css attribute for every element on my website and i always want the css file to be fairly intuitive and easy to readmy ultimate goal is to make it easy to use the css files and demonstrate their power to increase the speed of web development this way other individuals that may work on this site in the future will also get into the practice of using good coding practices rather than having to pick it up the way i did,['css'] +46926,how to manage two jradiobuttons in java so that only one of them can be selected at a time how to manage two jradiobuttons in java so that only one of them can be selected at a time is there any method in java to take care of this or you need to build your own logic,['java'] +46927,what makes stl fast if one implements an array class the way it is commonly implemented its performance is slower compared to its stl equivalent like a vector so what makes stl containersalgorithms fast,['c++'] +46929,compare two json objects in java i am looking for a json paring library that supports comparing two json objects ignoring child order specifically for unit testing json returning from a web service against an expected valuedo any of the major json libraries support this the orgjson simply does a reference comparison,['java'] +46933,generics and ducktyping xml in net i am working with some xml representations of data instances i am deserializing the objects using net serialization but something in my soul is thisturbed by having to write classes to represent the xml below is what i would love to do but i do not know if the syntax or if it is even possibleconsider the followingdim xmlobject somexmlfunction where some function returns an objectstring representation of xmlxmlobjectsomepropertydefinedinthexml somefunctionany suggestions on approachs with this,"['.net', 'asp.net']" +46935,unit testing private method in resource managing class c i previously asked this question under another name but deleted it because i did not explain it very welet us say i have a class which manages a file let us say that this class treats the file as having a specific file format and contains methods to perform operations on this fileclass foo stdwstring filename public fooconst stdwstring filename filename filename construct a foo here int getchecksum open the file and read some part of it long method to figure out what checksum it is return the checksum let us say i would like to be able to unit test the part of this class that calculates the checksum unit testing the parts of the class that load in the file and such is impractical because to test every part of the getchecksum method i might need to construct 40 or 50 filesnow lets say i would like to reuse the checksum method elsewhere in the class i extract the method so that it now looks like thisclass foo stdwstring filename static int calculatechecksumconst stdvectorunsigned char filebytes long method to figure out what checksum it is public fooconst stdwstring filename filename filename construct a foo here int getchecksum open the file and read some part of it return calculatechecksum something void modifythisfilesomehow perform modification int newchecksum calculatechecksum something apply the newchecksum to the file now i would like to unit test the calculatechecksum method because it is easy to test and complicated and i do not care about unit testing getchecksum because it is simple and very difficult to test but i cannot test calculatechecksum directly because it is privatedoes anyone know of a solution to this problem,['c++'] +46938,php best way to md5 multidimensional array i was wondering what is the best way to generate an md5 or any other hash of a multidimensional array i could easily write a loop which would traverse through each level of the array concatenating each value into a string and simply performing the md5 on the string however this seems cumbersome at best and i wondered if there was a funky function which would take a multidimensional array and hash itthanks for your time,['php'] +46943,eclipse galileo sql editor is there a code formatter tidy function i do like the sql editor now bundled with eclipse but i cannot seem to find a way for it to format my code like eclipse will with my java did i miss something or does anybody have any alternativesthanksediti would also be happy if there was an alternate plugin that someone could recommend,['sql'] +46947,is there a way with rails form helper to produce a button tag for submit i am trying to create buttons ala wufoo rethiscovering the button elementi would like to write the following code like the followingform tag search path method get class search do text field tag search paramssearch button tag search name nilendto generate the following html instead of the inputtypesubmit tagbutton typesubmit classpositive img srcimagesiconstickpng alt savebuttondoes a method exist already or should i roll my own helper,['ruby-on-rails'] +46956,how to parse a json and turn its values into an array public static void parseprofilesjsonstring the json try jsonobject myjson new jsonobjectthe json jsonarray namearray myjsonnames jsonarray valarray myjsontojsonarraynamearray forint i0ivalarraylengthi string p namearraygetstringi valarraygetstringi logipp catch jsonexception e eprintstacktrace as you can see this sample code will print out the key of the jsons followed by the values of the jsonsit would print profiles john if the json was like thisprofilesjohnthat is cool that is fine as i can work with those variables however what if the json was like thisprofiles namejohn age 44 namealexage11in this case the entire value would be the array basically i just want to grab that array which is the value in this caseand turn it into an actual array that java could use how can i do that thanks,['java'] +46960,can i multiply strings in java to repeat sequences i have something like the followingint i 3string somenum 123i would like to append i 0s to the somenum string does it have some way i can multiply a string to repeat it like python doesso i could just gosomenum sumnum 0 3or something similarwhere in this case my final result would be1230,['java'] +46963,mysql reshape data from long tall to wide i have data in a mysql table in long tall format described below and want to convert it to wide format can i do this using just sqleasiest to explain with an example suppose you have information on country key value for m countries and keys eg keys can be income political leader area continent etclong format has 3 columns country key value mn rows eg usa president obama usa currency dollarwide format has n16 columns county key1 keyn m rowsexample country president currency usa obama dollaris there a way in sql to create a new table with the data in the wide formatselect thistinct key from table this will get me all the keys1 how do i then create the table using these key elements2 how do i then fill in the table valuesi am pretty sure i can do this with any scripting language i like python but wanted to know if there is an easy way to do this in mysql many statistical packages like r and stata have this command built in because it is often usedto be more clear here is the desired input output for a simple caseinputcountry attrname attrvalue key these are column namesus president obama 2us currency dollar 3china president hu 4china currency yuan 5outputcountry president currency newpkeyus obama dollar 1china hu yuan 2,"['sql', 'mysql']" +46964,is there a generic way to synchronize an asynchronous method we have this common scenario where we have a method that performs some action asyncronously and raises an event when it is done there are times where we want it done synchronously instead so we have code that looks similar to thismanualresetevent reset new manualreseteventfalsesomeobjectasyncactiondone sender args resetsetsomeobjectperformasyncactionresetwaitoneis there a way to write a helper method to do this i can pass in the action to perform but i am not sure how to pass in something that lets the helper method know which event to listen to since it does not look like you can pass in an eventhandler as a parameterpreferably a solution that does not require reflectionthere seems to be some confusion this is a sample of what someobjects class is likepublic class someclass private externalserver someserveroverthenetwork new externalserver public event eventhandler asyncactiondone public data somedata get set public void performasyncaction someserveroverthenetworkgetsomedataondataretrived public data ondataretriveddata somedata asyncactiondonethis new dataeventargssomedata,['c#'] +46970,is there javaconcurrentutil or equivalent for weakhashmap can the following piece of code be rewritten wo using collectionssynchronizedmap yet maintaining correctness at concurrency collectionssynchronizedmapnew weakhashmapclass objectie is there something from javautilconcurrent one can use instead note that merely replacing with new concurrenthashmapclass objectnew weakhashmapclass objectobviously would not work,['java'] +46973,javascript extends class what is the rightbest way to extend a javascript class so class b inherits everything from the class a class b extends a,['javascript'] +46976,is it reasonable to use stdbasic string as a contiguous buffer when targeting c03 i know that in c03 technically the stdbasic string template is not required to have contiguous memory however i am curious how many implementations exist for modern compilers that actually take advantage of this freedom for example if one wants to use basic string to receive the results of some c api like the example below it seems silly to allocate a vector just to turn it into a string immediatelyexampledword valuelength 0dword typelong errorcheck regqueryvalueexw hwin32 valuec str null type null valuelengthif errorcheck error success windowsapiexceptionthrowerrorcheckelse if valuelength 0 return stdwstringstdwstring bufferdo bufferresizevaluelengthsizeofwchar t errorcheck regqueryvalueexw hwin32 valuec str null type buffer0 valuelength while errorcheck error more dataif errorcheck error success windowsapiexceptionthrowerrorcheckreturn bufferi know code like this might slightly reduce portability because it implies that stdwstring is contiguous but i am wondering just how unportable that makes this code put another way how may compilers actually take advantage of the freedom having noncontiguous memory allowsedit i updated this question to mention c03 readers should note that when targeting c11 the standard now requires that basic string be contiguous so the above question is a non issue when targeting that standard,['c++'] +46977,calloc usefulness of zeroing out memory what is the advantage of zeroing out memory ie calloc over malloc would not you change the value to something else anyways,['c'] +46978,getting text from a url in aspnet i am looking for a reliable way of extracting text given the web address in aspnetc can anyone point me the right directionalso the web address could be say a news site that might have a lot of ads and menus etc i need some intelligent way of extracting only the relevant content not sure how this could be done as how would i define what relevance isshould i maybe read from a rss feed any thoughts on thisediti have added a bounty i am looking to extract relevant text from a url from relevant i mean it should exclude text from ads and other irrelevant info the input will be similar to a news site i need to extract only the news info and get rid of the extraneous text,"['c#', 'asp.net']" +46980,fading elements in and out without changing the layout of the page the normal behavior when using fadein and fadeout is to use the thisplay property however this changes the layout of the pagehow can i make fadein and fadeout not modify the layout of the page,"['jquery', 'css']" +46987,using mtrace for c when i use mtrace in my c programmei get output like the followingmemory not freed address size caller 0x0804a3c8 0x4 at 0x400b159f how do i know where in the code is 0x400b159f,['c++'] +46989,how to check the valid youtube url using jquery in jquery i want to check the specific url from youtube alone and show success status and others i want to skip by stating it as not valid urlvar videourl youtubecomwatchvfhnmnwigg5mif videourlcontainsyoutubecom alertvalid else alertnot valid how to check with contains or any other option to check the valid youtube url alone,"['javascript', 'jquery']" +46991,openssl ignore selfsigned certificate error i am writing a small program with the openssl library that is suppose to establish a connection with an sslv3 server this server thispenses a selfsigned certificate which causes the handshake to fail with this message sslv3 alert handshake failure self signed certificate in certificate chainis there a way i can force the connection to proceed i have tried calling ssl ctx set verify like sossl ctx set verifyctx ssl verify none nullbut it does not seem to change anythingany suggestions,"['c++', 'c']" +46992,c multiple inheritance i would like to achieve this in cpseudocodeclass aclass b aclass c a ba ac acb bc bcis this possible,['c#'] +46994,detect numbers or letters with jqueryjavascript i want to use an ifstatement to run a code only if the user types in a letter or a numberi could use ifeventkeycode 48 eventkeycode 49 eventkeycode 50 run code but is there an easier way to do this maybe some keycodes dont work in all web browsers,"['javascript', 'jquery']" +47005,why does php have a sign in front of variables in php and some other scripting languages have the var syntax while java and other languages we can do just var is there any theory behind it does it help them to parse if not why would they choose to tack on an extra character in front,['php'] +47024,nstextfield white text on black background but black cursor i have setup an nstextfield with text color as white and the background color as black despite not rendering the background color so its transparent all in interface builderthe problem i am having is the cursor is black and hardly visible does the cursor not represent the text color any ideas how i can fix thisotherwise the nstextfield looks like it cannot be edited,['objective-c'] +47025,get an idatareader from a typed list i have a listmyobject with a million elements it is actually a subsonic collection but it is not loaded from the database i am currently using sqlbulkcopy as followsprivate string fastinsertcollectionstring tablename datatable tabledata string sqlconn configurationmanagerconnectionstringssubsonicconfigdefaultdataproviderconnectionstringnameconnectionstring using sqlbulkcopy s new sqlbulkcopysqlconn sqlbulkcopyoptionstablelock sdestinationtablename tablename sbatchsize 50 swritetoservertabledata sbulkcopytimeout sproctimeout sclose return sqlconni use subsonics myobjectcollectiontodatatable to build the datatable from my collection however this duplicates objects in memory and is inefficient i would like to use the sqlbulkcopywritetoserver method that uses an idatareader instead of a datatable so that i do not duplicate my collection in memory whats the easiest way to get an idatareader from my list i suppose i could implement a custom data reader like here but there must be something simpler i can do without writing a bunch of generic codeeditit does not appear that one can easily generate an idatareader from a collection of objects accepting current answer even though i was hoping for something built into the framework,"['c#', 'sql']" +47037,thispatchertimer vs a regular timer in wpf app for a task scheduler please explain the difference between thispatchertimer and a regular timer that kent boogaart meant for using in a multithreading wpf app as a task sheduler in this topicin the commentaries to one of the post quoteif all the thispatchertimer does is kick off another thread what is the point of using the thispatchertimerthose threads do not need to be started on the ui thread you could just use a regular timer and avoid interrupting the ui altogetherwhat is a regular timer that is meant how they thispatchertimer and a regular timer differ regarding their impact on ui until reading this post i thought about thispatchertimer as a natural way of using timers in wpf what is the cases when this is not true,['.net'] +47046,trycatch for division by zero i am a java newbie my question is about trycatch blocks on a simple division by zero example you see the first line of try if i cast any of those two variables to the double the program does not recognize the catch block in my opinion whether i cast or not only the catch block must be executed what is wrong on this code thankspublic static void mainstring args int pay8payda0 try double resultpaydoublepayda if i cast any of the two variables program does not recognize the catch block why is it so systemoutprintlnresult systemoutprintlninsidetry catch exception e systemoutprintlndivision by zero exception systemoutprintlninsidecatch,['java'] +47048,pickle or json i need to save to thisk a little dict object which keys are strs and values are ints and then recover it something like thisjuanjo 2 pedro99 other 3what is the best option and why serialize it with pickle or with simplejsoni am using python 26,['python'] +47051,how coarse grained should the model be in an mvc framework i have been reading a few questions previously asked and i have not come across one that answers my question in black and white for me so apologies if this is repetitive the question is probably similar to asking how long is a piece of string but bear with mefor a registration system i have a user model with functions such asadd userdelete useractivate userthe above user model deals with one table the users table in the mysql databaseyou can guess what each function does but is this coarse enough i mean should my model contain methods that are much broader such asadd recorddelete recordupdate recordwhere i pass in the table and a unique identifier of the record to delete add or updatei am using codeigniter but i am interested in how things should be done in a pure mvc frameworki apologise if this question is too pickythanks all,['php'] +47054,impact of instanceof in android java code does the instanceof keyword bear with it a relatively heavier impact on the android platform and more speciffically the mobile phones running the dalvik vm,['android'] +47056,nstimer with a menu bar app i am working on a simple timer app and i have created a nsstatusitem with a menu and i have some nstextfield labels that updates the timer labels but when i click on the status item the nstimer stops and stops updating the labels how can i get around this problem edit heres the code that starts the timertimer nstimer scheduledtimerwithtimeinterval1 targetself selectorselectortimerdidupdate userinfonil repeatsyes,['objective-c'] +47059,how to get the arrow keys on the keyboard to trigger navigation previousnext page links within a blog the script i have pieced together so far looks like thisscript typetextjavascript keynav documentonkeydown functione if e var e windoweventvar code echarcode echarcode ekeycodeif eshiftkey ectrlkey ealtkey emetakey if code eventkey left if previous page link locationhref previous page linkhref else if code eventkey right if next page link locationhref next page linkhref scriptand my html looks like thispblockpreviouspagea idprevious page link hrefpreviouspageprevious pagea blockpreviouspageblocknextpagea idnext page link hrefnextpagenext pageablocknextpagepthe previouspage nextpage code represents dynamic page links which are different depending on which page you are on this particular question is specific to tumblr but generally as wellis there a way to get my left and right arrow keys to trigger these dynamic linksthank you for reading and any help with this is greatly appreciated,"['javascript', 'jquery']" +47062,using sizeof on mallocd memory possible duplicatenewbie questions about malloc and sizeof i am trying to read strings into a program when i noticed that the strings were sometimes being corrupted i tried the following code void mallocated malloc100 printfsizeofmallocated dn sizeofmallocatedaccording to my program the size of mallocated was 8 even though i allocated 100 bytes for it because of this whenever i try to store a string longer than 8 bytes everything after the 8th byte will sometimes thisappear why is this happening and how can i prevent it,['c'] +47070,c findall vs where speed anyone know any speed differences between where and findall on list i know where is part of ienumerable and findall is part of list i am just curious whats faster,['c#'] +47072,testing if jqueryui has loaded i am trying to debug a website and i think that jqueryui may not have loaded properly how can i test if jqueryui has loaded,['javascript'] +47088,com object that has been separated from its underlying rcw cannot be used i have some com component which i call from some c dlli also have a winforms app that uses that dllwhen i close the app i get this exceptioncom object that has been separated from its underlying rcw cannot be usedthe stack trace shows this exception comes from a destructor in the dll i implemented this destructor to call some cleanup method in the comwhy does this happen how is it best to solve it,['c#'] +47098,how do i pass information from a servlet to a jsp page is it possible to have a servlet that contains an object an arraylist in this case that then does the equivalent of thisplaying a jsp page and passing that object to the jsp page in this case the arraylist contains database results an i want to iterate through and thisplay the results on the jsp pagei am not using any mvc framework is it possible to do this with the basic servletjsp architecture,['java'] +47100,in jodatime set datetime to start of month my api allows library client to pass datemethodjavautildate dateworking with jodatime from this date i would like to extract the month and iterate over all days this month containsnow the passed date is usually new date meaning current instant my problem actually is setting the new datemidnightjdkdate instance to be at the start of the monthcould someone please demonstrates this use case with jodatime,['java'] +47102,fix malformed xml in php before processing using domdocument functions i am needing to load an xml document into php that comes from an external source the xml does not declare it is encoding and contains illegal characters like if i try to load the xml document directly in the browser i get errors like an invalid character was found in text content also when loading the file in php i get lots of warnings like xmlparseentityref no name in entity and input is not proper utf8 indicate encoding bytes 0x9c 0x31 0x21 0x3cit is clear that the xml is not well formed and contains illegal characters that should be converted to xml entitiesthis is because the xml feed is made up of data supplied by lots of other users and clearly it is not being validated or reformatted before i get iti have spoken to the supplier of the xml feed and they say they are trying to get the content providers to sort it out but this seems silly as they should be validating the input firsti basically need to fix the xml correcting any encoding errors and converting any illegal chars to xml entities so that the xml loads problem when using phps domdocument functionsmy code currently looks like feedurl 3704017 14022010 0504xml dom new domdocument domloadfeedurlexample xml file showing encoding issue click to download feedxmlexample xml that contains chars that have not been converted to xml entitiesxml version10feedrecordid117387idadvertisernametestadvertisernameaid10544740aidnamethis thisnamedescriptionfor one day only this is than thisdescriptionrecordfeed,['php'] +47116,which unit testing framework i wondered which unit testing framework would be a good one to get really familiar with i know this might be a question of opinion but i thought i would ask anyways i know that i will need to do it someday so i might as well learn to use it i know that there is quite a few out there but which one is effective for c developmentfrom this question i can see that unit testing is necessary but personally i have not used it so that is why i ask this question,"['c#', '.net']" +47117,rgb int to rgb python how can i convert an rgb integer to the corresponding rgb tuple rgb seems simple enough but i cannot find anything on googlei know that for every rgb rgb you have the integer n r2562 g256 b how can i solve the reverse in python ie given an n i need the rgb values,['python'] +47120,symbolicatecrash in iphone sdk 32 beta 2 returns error error cannot parse os version string iphone os 312 in the latest symbolicatecrash for iphone sdk 32 beta 2 i am getting the error error cannot parse os version string iphone os 312 when trying to symbolicate crash logs build on older crashlog formatsthe latest symbolicate crash has introduced a build and version string for the os version for older versions of the crash log you will need to edit symbolicate crash to retain the older regex logicmodify the following subroutinesub parse osversion my log ref my section parse sectionlog refos version if section s09sbuild w return 1 2 if section s09sw return 1 2 die error cannot parse os version string sectionto the followingsub parse osversion my log ref my os parse sectionlog refos version os build w os w new format return 1that solved the issue for me,['iphone'] +47123,jquery live hover i am using the following jquery code to show a contextual delete button only for table rows we are hovering with our mouse this works but not for rows that have been added with jsajax on the flyis there a way to make this work with live eventstable trhover function function,['jquery'] +47127,what does bootstrapperpackage mean inside the csproj project i am upgrading lots of c projects from vsnet 2008 to vsnet 2010 rc i notice that the upgrade creates a bootstrapperpackage section inside the csproj file include microsoftnetframework35 and 35sp1 i wonder what the bootstrapperpackage does and do i need them,['c#'] +47128,how to find the number of objects in the heap how can i find the number of live objects on the heap in java program,['java'] +47129,is it worth waiting a couple of milliseconds on a textchanged event i have a textfield for a filter customers action on a mobile devicei am wondering if i should wait for a few milliseconds before launching my code when the user typed in less then 3 chars and only execute the code if the text is longer or equal than 3 charsthe executed code takes longersql like syntax on a larger database and the user sees hangouts on the listviewwhat do you think,"['c#', 'iphone', 'android']" +47145,how do i download a binary file over http how do i download and save a binary file over http using rubythe url is i am on the windows platform and i would prefer not to run any external program,['ruby'] +47147,tips to help debug could not load file or assembly x or one of its dependencies i am looking for tipssuggestionsinsights to help debug an on application load issue could not load file or assemblythe solutionproject where i am experiencing this issue is a conversion from a working copy in visual studio 2008 to the visual studio 2010 release candidate the conversion process appeared to be successful and all the solution projects are set to framework 4the exception is on a 3rd party component a graphics processing library but any answers could possibly help others with any troublesome dllcould not load file or assembly aurigmagraphicsmilldll or one of its dependencies is not a valid win32 application exception from hresult 0x800700c1whats confusing about this exception is the additional text is not a valid win32 application the full exception stack trace is up on pastebin but does not seem to shed much more light on the issuewhat i have tried so far with no succesimple clean rebuild restart combinations of visual studio 2010 rcremoving and readding the dll in questiontoggling copy local to true and false on the dll in questionconfirming that after a successful build the dll in question appears in the bindebug folderchecking for any unnecessary references to the dll in question none foundthe associated licence file for the dll in question is in the same directory with iti have also had no luck with it hitting any debugger breakpoints on application load,['.net'] +47152,in java what are the boolean order of operations let us take a simple example of an object cat i want to be sure the not null cat is either orange or greyifcat null catgetcolor orange catgetcolor grey do stuffi believe and comes first then the or i am kinda fuzzy though so here are my questions can someone walk me through this statement so i am sure i get what happensalso what happens if i add parentheses does that change the order of operationswill my order of operations change from language to language,['java'] +47155,skipping php end tag while i was developing with magento i found out that i do not need to put php end tag if i do not use html below php code is it safe and why do not we just put end tag is it useful,['php'] +47159,downloading files from multiple directory in one ftp connection with ftpwebrequest in net is it possible to change the path of the ftp session once the session is open the reason i want to do this is to avoid to open the multiple ftp connection the whole purpose is to download the files located in the ftp site in a single ftp connection for example in single ftp connection i want download the contens from all the directory located in the ftp site currently i have project that is failing everyday because it makes multiple connections to the ftp site to download files from different directory for example making more than 80 connections in 1 minutes what are restrictions of the ftpwebrequest in net,['.net'] +47162,libtomcrypt and libtommathadevelopment status libtomcrypt in the past has seemed like a very viable and useful option for encryption and the associated libtommath could be a useful math library but lately i cannot see any development on it and it is ambiguous as to what is the current web site for it egwhich points to old page now looks like it is been taken over by a domain squatterin the past wayback machinewhats the status and is there a future for libtomcrypt,['c'] +47179,poll database schema what is the best database schema for polls is onetomany relationship good for this i am thinking about having two tablespoll questions int id varchar body datetime created at datetime updated atpoll answers int id varchar body int votes default 0 int question id foreign key to poll questionsid datetime created at datetime updated atthen there would also be third table for tracking who voted for an answer so users are able to vote only oncepoll voting history int id int question id foreign key to poll questionsid int answer id foreign key to poll answersid int user id foreign key to the id in the users table datetime created at datetime updated atwhat are your thoughts am i thinking about it right,['mysql'] +47180,efficient way of finding thistance between two 3d points i am writing a code in c and want to compute thistance between two points question 1 i have two points px1 y1 z1 and qx2 y2 z2 where x y and z are floatsdoubles i want to find the thistance between these two points one way to do it is square rootx diffx diff y diffy diff z diffz diff but this is probably not the most efficient way eg a better formula or a ready made utility in mathh etc question 2 is there a better way if i just want to determine if p and q are in fact the same points my inputs are x y and z coordinates of both the points thank you,['c++'] +47186,ruby class object garbage collection in ruby all classes are objects of class class since classes are also objects does a ruby vm follow the same garbage collection strategy for class objects what determines that a class object is safe for garbage collection thanks,['ruby'] +47190,failed binder transaction when returning camera image i get the failed binder transaction error in the logcat when returning the image taken with the camera from the camera intent back to the parent intent as a byte using putextra i do not understand why its not like its a big bitmap or anything it only happens when i take pictures with lots of light because then the byte is bigger the error occurs when leaving the camera intent does anyone see a mistake in my code here is the code of the camera intentpackage exampleimagingapeimport javaioioexceptionimport javautiliteratorimport javautilsetimport androidappactivityimport androidcontentintentimport androidgraphicsbitmapimport androidgraphicsbitmapfactoryimport androidgraphicspixelformatimport androidhardwarecameraimport androidhardwarecameraautofocuscallbackimport androidosbundleimport androidutillogimport androidviewmotioneventimport androidviewsurfaceholderimport androidviewsurfaceviewimport androidviewviewimport androidviewwindowimport androidviewwindowmanagerimport androidviewviewontouchlistenerpublic class takepicture extends activity implements surfaceholdercallback camera mcamera boolean mpreviewrunning false int imagelayoutheight int imagelayoutwidth override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setup camera surface getwindowsetformatpixelformattranslucent requestwindowfeaturewindowfeature no title getwindowsetflagswindowmanagerlayoutparamsflag fullscreen windowmanagerlayoutparamsflag fullscreen setcontentviewrlayoutcameralayout surfaceview msurfaceview surfaceview findviewbyidridhist surface camera surfaceholder msurfaceholder msurfaceviewgetholder msurfaceholderaddcallbackthis msurfaceholdersettypesurfaceholdersurface type push buffers bundle extras getintentgetextras imagelayoutheight extrasgetintlayoutheight imagelayoutwidth extrasgetintlayoutwidth ontouchlistener touchlistener new viewontouchlistener public boolean ontouchview v motionevent e systemoutprintlnmaking picture mcameraautofocuscb return false setup touch listener msurfaceviewsetontouchlistenertouchlistener autofocuscallback cb new autofocuscallback public void onautofocusboolean success camera c ctakepicturenull null mpicturecallback camerapicturecallback mpicturecallback new camerapicturecallback public void onpicturetakenbyte imagedata camera c systemoutprintlnpicture taken now returning intent resultintent new intent resultintentputextracameraimage imagedata systemoutprintlnput extra setresultactivityresult ok resultintent finish initialize camera public void surfacecreatedsurfaceholder holder mcamera cameraopen public void surfacechangedsurfaceholder holder int format int w int h if mpreviewrunning mcamerastoppreview cameraparameters p mcameragetparameters psetpreviewsizeh w systemoutprintlnpreviewsize h w psetpicturesizeh3w3 is around 1200x900 psetrotation 90 mcamerasetparametersp try mcamerasetpreviewthisplayholder catch ioexception e eprintstacktrace mcamerastartpreview mpreviewrunning true public void surfacedestroyedsurfaceholder holder mcamerastoppreview mpreviewrunning false mcamerarelease and here is the code that calls the camera intentintent intent new intentexamplethis takepictureclassintentputextralayoutwidthlayoutwidthintentputextralayoutheightlayoutheight startactivityforresultintent0,['android'] +47191,why does not my service work in android i just want to log something ever 5 seconds i created a new class called helloservicei added this to the android manifestxmlpublic class helloservice extends service private timer timer new timer private long interval 50 public void oncreate superoncreate startservice private void startservice timerscheduleatfixedrate new timertask public void run logdservy this proves that my service works 0 interval private void stopservice if timer null timercancel override public ibinder onbindintent arg0 return null my other activity calls it like this intent helloservice new intentthis helloserviceclass startservicehelloservicefor some reason i put a breakpoint in my new helloservicebut it is not even hitting it is not logging eithereditunable to start service intent cmp comexampleshellohelloservice not found what does that mean i created helloservicejava in the same place as everything elsesolved i fixed my manifest filethanks nikola smiljanicservice androidnamehelloserviceto service androidnamehelloserviceservice,"['java', 'android']" +47201,how can i make a user control extend a class that extends usercontrol i want to attempt an mvc design for my little appi have a normal csharp class viewbase which extends usercontrol it is a single cs filei have multiple classes that i want to extend viewbase these are actual usercontrols so they have a code behind cs file and a xaml filehowever csharp tells me that for these classes their base class differs from declared in other partsis what i want to do possible at all what am i doing wrongnote that i did not modify my xaml files so they still use tagshere is the relevant code this gives the error in question and viewbase is underlined base class of loginview differs from declared in other partspublic partial class loginview viewbase public loginviewshell shell controllerbase controller baseshell controller initializecomponent this one is a single cs filepublic abstract class viewbase usercontrol public shell shell get set public controllerbase controller get set protected viewbaseshell shell controllerbase controller shell shell controller controller,['c#'] +47202,net assembly dependencies perhaps i am missing something obvious here buti have built a reusable generic c class library project say adll which references 3 other assemblies say bdll cdll and ddllhowever if i want to reuse my component adll in another project i still have to include the references to bdll cdll and ddllis there any way you can configure adll to build all its dependencies into the adll so i do not have to include the other 3 assembliescheers,"['c#', '.net']" +47219,convert an image to grayscale is there a way to convert an image to grayscale 16 pixels per bit format rather than setting each of the rg and b components to luminance i currently have a bmp from file bitmap c new bitmapfilenamei want a bitmap d that is grayscale version of c i do see a constructor that includes systemdrawingimagingpixelformat but i do not understand how to use that i am new to image processing and the relevant c libraries but have a moderate experience with c itselfany help reference to an online source hint or suggestion will be appreciated thank youedit d is the grayscale version of c,['c#'] +47242,wpf treeviewitem bound to an icommand i am busy creating my first mvvm application in wpf basically the problem i am having is that i have a treeview systemwindowscontrolstreeview which i have placed on my wpf window i have decide that i will bind to a readonlycollection of commandviewmodel items and these items consist of a thisplaystring tag and a relaycommandnow in the xaml i have my treeview and i have successfully bound my readonlycollection to this i can view this and everything looks fine in the ui the issue now is that i need to bind the relaycommand to the command of the treeviewitem however from what i can see the treeviewitem does not have a command does this force me to do it in the isselected property or even in the code behind treeview selecteditemchanged method or is there a way to do this magically in wpf this is the code i havetreeview borderbrushxnull horizontalalignmentstretch verticalalignmentstretchtreeviewitems treeviewitem headernew commands itemssourcebinding commands thisplaymemberpaththisplayname isexpandedtrue treeviewitemtreeviewitemsand ideally i would love to just go treeview borderbrushxnull horizontalalignmentstretch verticalalignmentstretchtreeviewitems treeviewitem headernew trade itemssourcebinding commands thisplaymemberpaththisplayname isexpandedtrue commandbinding pathcommand treeviewitemtreeviewitemsdoes someone have a solution that allows me to use the relaycommand infrastructure i havethanks guys much appreciatedrichard,['c#'] +47251,rails app templates script generators with haml is there any way to create an app template in rails that generates the views in haml rather than erbapp templates if not are there any pluginsgems that i can use to have all my generator scripts output haml instead of erb,['ruby-on-rails'] +47252,domain model financial trading application my company is thinking about implementing a new financial compliance trading application which is an application that would check all trades that would be executed by the company a very simple check might be do not invest in stocks that sell alcohol for example we need to define a financial business object model and then design the actual rule engine some potential data models would be security trade derivative etcmy question does any one know where i could look at some financial domain model already written that would be a good starting place for us to begin our analysiswe do not want to reinvent the wheel and coming up with an existing financial object model would be very helpfulthanks all,['java'] +47262,how are arrays implemented in java arrays are implemented as objects in java right if so where could i look at the source code for the array class i am wondering if the length variable in arrays is defined as a constant and if so why it is not in all capital letters length to make the code more understandable,['java'] +47265,how to make an progress bar for an nsurlconnection when downloading a file i want to show up an progress bar while a download with nsurlconnection is happening as i am getting data from the server i could update the ui for every received package but the problem is how do i figure out how much data i have already and how much data has to be downloaded probably in bytes and then i have to do some math to get the percentage,['iphone'] +47267,execute sql from file in sqlalchemy how can i execute whole sql file into database using sqlalchemy there can be many different sql queries in the file including begin and commitrollback,['sql'] +47270,algorithm to choose random letters for word search game that allows many words to be spelled i am making a bogglelike word game the user is given a grid of letters like thiso v z w xs t a c ky r f l qthe user picks out a word using any adjacent chains of letters like the word stack across the middle line the letters used are then replaced by the machine eg new letters in lowercaseo v z w xz e x o py r f l qnotice you can now spell overflow by using the new letters my problem is what algorithm can i use to pick new letters that maximizes the number of long words the user can spell i want the game to be fun and involve spelling eg 6 letter words sometimes but if you pick bad letters games involve the user just spelling 3 letter words and not getting a chance to find larger wordsfor exampleyou could just randomly pick new letters from the alphabet this does not work welikewise i found picking randomly but using the letter frequencies from scrabble did not work well this works better in scrabble i think as you are less constrained about the order you use the letters ini tried having a set of lists each representing one of the dies from the boggle game and each letter would be picked from a random die side i also wonder whether i can legally use this data in a product i did not notice this working well i imagine the boggle dice sides were chosen in some sensible manner but i cannot find how this was donesome ideas i have consideredmake a table of how often letter pairs occur together in the dictionary for the sake of argument say e is seen next to a 30 of the time when picking a new letter i would randomly pick a letter based on the frequency of this letter occurring next to a randomly chosen adjacent letter on the grid for example if the neighboring letter was e the new letter would be a 30 of the time the should mean there are lots of decent pairs to use scattered around the map i could maybe improve this by making probability tables of a letter occurring between two other letterssomehow do a search for what words can be spelt on the current grid taking the new letters to be wildcards i would then replace the wildcards with letters that allowed the biggest words to be spelt i am not sure how you would do this efficiently howeverany other ideas are appreciated i wonder if there is a common way to solve this problem and what other word games use edit thanks for the great answers so far i forgot to mention i am really aiming for low memorycpu requirements if possible i am probably going to use the sowpods dictionary about 250 and my grid will be able 6 x 6,['java'] +47275,jquery fancybox but i do not want scrollbars i am using jquery fancybox for a popup registration form herei would like the form to come up at the size of 450px by 700px but no matter what i set the height and width at i get scrollbarsscript typetextjavascript documentreadyfunction aregformfancybox titleshow false autoscale true width 450 height 700 transitionin elastic transitionout elastic scriptthere must be something i am doing wrong but i cannot figure out what it is i would appreciate a helpful hand here thanks,['jquery'] +47277,check if a file exist in the server in aspnet string jsfile resolveurlmyprojectjavascriptsdirtestjs if systemiofileexistsjsfile this code does not work and i guess it is the jsfile that does not work well with the iofileexists but i know the jsfile has a valid path because when i use few line later pageclientscriptregisterclientscriptincludemyfilejsfile it does attach the javascript file to the aspx and all work fineany idea of how to check if the file exist,"['asp.net', 'javascript']" +47282,trim whitespaces new line and tab space in a string in oracle i need to trim new line chr13 and chr10 and tab space from the beginning and end of a string in an oracle query i learnt that there is no easy way to trim multiple characters in oracle trim function trims only single character it would be a performance degradation if i call trim function recursivelly in a loop using a function i heard regexp replace can match the whitespaces and remove them can you guide of a reliable way to use regexp replace to trim multiple tabspaces or new lines or combinations of them in beginning and end of a string if there is any other way please guide me,['sql'] +47288,how can i add new root element to a c xmldocument i have outside of my control an xmldocument which has a structure like the followingparent1minor amount of dataparent1i have another xmldocument also outside of my control which has the following structureparent2very large amount of dataparent2i need an xmldocument in the formatparent1minor amount of dataparent2very large amount of dataparent2parent1i do not want to make a copy of parent2 how can i get the structure i need without copying parent2 i believe this means oparent1documentelementappendchildoparent1importnodeoparent2documentelement trueis out of the questionany good solutions out there,['c#'] +47291,thinking of moving from textmate to vim for rails dev what do i need i do ruby on rails development pretty much exclusively i currently develop in os x using textmate i have a virtual machine running to emulate as closely as possible the environment my app will be deployed into and i mount the code on a samba share into os x from the vm guest from there i open with textmate and code awayi am beginning to think that with the proper plugins and time spent learning i could be much more productive in vim directly on the vm right now my textmate is basically stock though i do find the projectplus plugin inthispensable what i am looking for are some suggestions of vim resources and plugins if that is the right terminology to closely emulate the features i am unwilling to give up in textmate or at least compelling reasons why i should be willing to give them up heres a short listability to have a preferably collapsible project tree visible either at all times or easily toggleableability to see scm status at a glance either within this project tree preferable or otherwise i use git almost exclusively if this makes any differencebeing able to view a sidebyside diff from within vim would be great tooability to search through the entire project at will i suppose stop grep nr fg would accomplish this unless there is a better way to do itcode completion if possible,['ruby-on-rails'] +47295,httphandler fire only if file does not exist i am trying to create a http handler to handle all requests to a folder but i only want it to fire if the files requested do not exist eg request comes in for file x if x exists i would like to serve the file otherwise the handler should deal with itthe files will only be static content not scripts themselves which i assume makes it a bit easier but i cannot seem to find anything that will do the trick anyone have any ideas i assume it can be done since the iis7 rewrite module can manage it but i cannot see howedit just to clarify the handler is the typical case and it is not an errorhandling routine but actually delivering appropriate content i just want the ability to add new files to the folder either as separate things or as overloads to what the handler would deliver,"['c#', 'asp.net']" +47302,cocoa how to morph a drag image while dragging in interface builderapp and some other cocoa apps image dragging has a very nicesexy effect of morphing the drag image while you drag a draggable item out of its window for example in interface buildlerappshow the library palette aal or tools menu librarydrag an item out of the library palettenote as you drag the item out of the library palette window it morphs from an image of the original list item to an image of the icon of the dragged itemi have fully implemented drag and drop in my application using the normal cocoa nsdragsourcensdragdestination facilities however i cannot find a hook for doing this image morph while dragging i am returning the initial drag image by overridingnsview dragimageatoffseteventpasteboardsourceslidebackbut this is only called at the beginning of the drag how do you signal that you would like to replace the current drag image ideally using the sexy morph effect,['objective-c'] +47309,how to apply bindvalue method in limit clause here is a snapshot of my codefetchpictures pdoprepareselect from pictures where album albumid order by id asc limit skip maxfetchpicturesbindvaluealbumid getalbumid pdoparam intifisset getskip fetchpicturesbindvalueskip trim getskip pdoparam int else fetchpicturesbindvalueskip 0 pdoparam int fetchpicturesbindvaluemax max pdoparam intfetchpicturesexecute or dieprint rfetchpictureserrorinfopictures fetchpicturesfetchallpdofetch associ get you have an error in your sql syntax check the manual that corresponds to your mysql server version for the right syntax to use near 15 15 at line 1it seems that pdo is adding single quotes to my variables in the limit part of the sql code i looked it up i found this bug which i think is relatedis that what i am looking at this bug has been opened since april 2008what are we supposed to do in the meantimei need to build some pagination and need to make sure the data is clean sql injectionsafe before sending the sql statement,"['php', 'mysql', 'sql']" +47316,how to rotate bitmap in windows gdi how would i go about rotating a bitmap in windows gdic,['c++'] +47320,how to find with java if a certain font is installed correctly on a machine i have a pc notebook running win vista when i first bought it certain chinese fonts would not show up i could only see rectangles but i played with the control setting for a while changed some properties and now it shows chinese fonts correctly but i do not remember what i didnow some of my programs thisplays both english and chinese something like this enter e34a the chinese here also means enter but if a user does not have chinese fonts installed properly on his machine he will see something like this enter my question is in java how to detect if those characters will show up correctly on a certain machine if not just thisplay enter if it is show enter e34afrank,['java'] +47331,how can i set the badge in tab bar in objectivec i want to put the notification in the tab bar of the app to show the number of item selected for the shopping list is there any way to add the notification in the tab bar of app,"['ios', 'objective-c']" +47334,how to convert sequence of numbers in an array to range of numbers in javascript how to convert sequence of numbers in an array to range of numberseg 234510181920 to 25101820,['javascript'] +47341,django calendar freebusyavailabilitty i am trying to implement a calendar system with the ability to schedule other people for appointments the system has to be able to prevent scheduling a person during another appointment or during their unavailable timei have looked at all the existing django calendar projects i have found on the internet and none of them seem to have this builtinto them if i missed it somehow please let me knowperhaps i am just getting too tired but the only way i can think of doing this seems a little messy here goes in pseudo codewhen a user tries to create a new appointment grab the new appointments start time and end timefor each appointment on that same day check ifexisting start time new start time and existing end time new start time is the new appointments start time in between any existing appointments start and end timesexisting start time new end time and existing end time new end time is the new appointments end time in between any existing appointments start and end timesif no objects were found then go ahead and add the new appointmentconsidering django has no filtering based on time this must all be done using extra on the querysetso i am asking if there is a better way a pythonic trick or module or anything that might simplify this or an existing project that has what i need or can lead me in the right directionthanks,['python'] +47345,architecture queuing aspnet msmq problem some 300 candidates make a test using flex a test consist of some 100 exercises after each exercise a net service is called to store the result if a candidate finishes a test all the data of hisher test is denormalized by aspnet this denormalization can take some cpu and can take 5 to 10 seconds now most of the times some of the candidates have finished their test earlier than the rest but still some 200 of them wait until their time is up at that moment 200 candidates finish their test and 200 sessions are denormalized at the same time at this point server load cpu is too high and cause calls to the webserver to go wrong now instead of all these sessions being normalized concurrently i would like to add them to a queue using msmq question how do you process the queuedo you start a separate thread in the application start of globalasax that listens to the queue if there are messages they are dealt one at the timeis it necessary to do this in a separate thread what if in the globalasax you just call a singleton for instance that starts listening to the queue in what thread will this singleton run whats the thread that calls globalasaxwhat are best practices to implement this links resources tutorials examplesi do not like the idea but could you put an exe on the root of your website an exe that starts a process listening to the queueif you get a message out of the queue do you remove it when you pull it out or do you remove it if denormalization for this session was successful if you remove it when you pull it out and something goes wrongi could also create my own queue in memory but restarting the webserver would empty the queue and a lot of sessions would end up not being normalized so i guess this is really a bad ideais msmq a good choice or are there better alternatives,['asp.net'] +47347,expected constructor destructor or type conversion before token i honestly have no idea why this is happening i checked doublechecked and triplechecked curly braces semicolons moved constructors around etc and it still gives me this errorrelevant code followsbintreehifndef bintree hdefine bintree hclass bintreeprivate struct node float data node n2 node r node make float public bintree bintree float bintree void add float void remove float bool has float node find float endifand bintreecppinclude bintreehbintreebintree r make 1 node bintreemake float d node t new node tdata d tn0 null tn1 null return t,['c++'] +47349,android findviewbyid finding view by id when view is not on the same layout invoked by setcontentview i have an activity myactivity that extends from mapactivity in the xml file containing the layout i can only include the mapviewcomgoogleandroidmapsmapview xmlnsandroid androidididtrail map view androidlayout widthfill parent androidlayout heightfill parent androidclickabletrue androidapikeykeyhowever i do need to find another view that is located in another xml fileunfortunately findviewbyid returns nullhow can i get the view i am looking forthanks a lot,['android'] +47351,optimize nginx phpfpm for faster response times for openx adserving i am currently running nginx phpfpm for serving ads on openx currently my response times are horrible even during times of low load however my cpu and memory resources are fine so i cannot seem to figure out what the bottleneck ismy current config for nginx and phpfpm isworker processes 20worker rlimit nofile 50error log varlognginxerrorlogpid varrunnginxpidevents worker connections 150 multi accept off use epollhttp include etcnginxmimetypes access log varlognginxaccesslog sendfile on tcp nopush off keepalive timeout 0 keepalive timeout 65 tcp nodelay on gzip on gzip thisable msie 16sv1 gzip comp level 2 gzip proxied any gzip types textplain texthtml textcss applicationxjavascript textxml applicationxml applicationxmlrss textjavascript include etcnginxconfdconf include etcnginxsitesenabledserver listen 80 server name localhost access log varlognginxlocalhostaccesslog default location location root varw index indexphp parse all php file in the varw directory location php fastcgi pass localhost90 fastcgi index indexphp fastcgi param script filename varwfastcgi script name include fastcgi params fastcgi param query string query string fastcgi param request method request method fastcgi param content type content type fastcgi param content length content length fastcgi ignore client abort off phpfpmrlimit files 50max children 500i only included the phpfpm paramaters i have changed for phpfpmdoes anyone have any tips on how i can optimize it so i can serve more requests i am seeing horrendous response times right now,['php'] +47368,uploadify plugin does not call java servlet i just started using uploadify flash plugin instead of standard html uiand met the next problemwhen i click upload files linkthat progress is shown and completed status is appeared but in reality it did not happened anythingjava servlet is not called from backendthere is upload servlet and uploading performed next way earlier form enctypemultipartformdata methodpost targetuploadframeaction requestgetcontextpath uploadfileportletidportletidremotefolderremotefolderafter providing uploadify plugin ui now looks likeplugin partconfiguration script oscripttext juploadifyuploadify oscripttext uploader kneportletsjslibuploadifyscriptsuploadifyswf oscripttext script requestgetcontextpath uploadfileportletidportletidremotefolder decodedstring oscripttext cancelimg kneportletsjslibuploadifycancelpng oscripttext folder decodedstring oscripttext queueid filequeue oscripttext auto false oscripttext multi false oscripttext sizelimit 10 oscripttext oscripttext scriptscripts parameter here points to java servlet on backend decodedstring is folder path which value is filesrvdemopart for uploadinginput typefile nameuploadify iduploadify a hrefjavascriptjuploadifyuploadifyuploadupload filesawhere is my faultscript param in plugin config points to java servlet on backend and it is donebut servlet is not triggerederror when script param is not correctthank you for assistance,"['java', 'jquery']" +47381,neat code to convert bool false true true false how would you convert an array of booleans to a string like false true true false using as few lines of code as possiblepython allows me to use the following very nice and clean joinmapstr false true true falsein c stringjoin only allows me to join an array of stringsso what is a short way to do the same in c,['c#'] +47382,why should you avoid to iterate over immutable valuetype collections using foreach in a coding standards document i found this statement avoid using foreach to iterate over immutable valuetype collections eg string arrayswhy should this be avoided,"['c#', '.net']" +47384,how to bundle images in jar file i made a java applicationand bundled all classes in jar filewen i run the project from netbeans my app is running successfullybut wen i place my jar file at another place and run from therei am not getting the icons used by my applicationin the code i get my icons from images directory present in project foldernowi wanted to know how can we present these image files to the end user like we present jar filethanks in advance,['java'] +47387,how to write javadoc of properties i often find myself with a dilemma when writing javadoc for propertiesmembers of a simple pojo class holding only properties and getters and setters dtostyle1 write javadoc for the propertyor2 write javadoc for the getter if i write javadoc for the property my ide eclipse will naturally not be able to thisplay this when i later access the pojo via code completion and there is no standard javadoc tag that lets me link the getterjavadoc to the actual property javadocan examplepublic class somedomainclass the name of bla bla bla private string name return insert some smart javadoc tag linking to names javadoc public string getname return name so basically it would be interesting to hear how others go about for having your eclipse ide thisplay the javadoc property description for your getters without having to duplicate the javadoc commentas of now i am considering making my practise to only document the getters and not the properties but it does not seem like the best solution,['java'] +47391,how to get the last path in a url i would like get the last path segment in a urlhttpblablablawcenewsphp orhttpblablablablabladut2anewsphpfor example in these two urls i want to get the path segment wce and dut2ai tried to use serverrequest uri but i get the whole url path,['php'] +47394,restore the state of stdcout after manipulating it suppose i have a code like thisvoid printhexstdostream x xstdhex123int main stdcout100 prints 100 base 10 printhexstdcout prints 123 in hex stdcout73 problem prints 73 in hexmy question is if there is any way to restore the state of cout to its original one after returning from the function somewhat like stdboolalpha and stdnoboolalpha thanksiyer,['c++'] +47397,how to open the keyboard automatically on uitextfield i have a very simple table and when tocuh a cell it opens a new view with one uitextfield all i want is that the keyboard will automatically opens without the user have to touch the uitextfieldits all done in interface builder so i am not sure how i do this i guess i need to set the focus at some point thanks,"['iphone', 'objective-c']" +47398,net parameterizedthreadstart wrong return type i just started experimenting with threads and i ran in to a problem i am not able to solve on my own i get the error error 1 bool projektftpuploadfil object has the wrong return typei use this code to start a thread using the method ftpuploadfilethread ftpuploadfile new threadnew parameterizedthreadstartftpuploadfileftpuploadfilestartefullpathand this is the method i used public static bool uploadfileobject filename string file converttostringfilename blah blah fricken blah snip return false,['c#'] +47399,lambda expression vs equals this is a purely academic question but whats the difference between using and equals within a lambda expression and which one is preferred code examplesint categoryid 1listofcategoriesfindallo ocategoryid categoryidorint categoryid 1 listofcategoriesfindallo ocategoryidequalscategoryid,['c#'] +47400,obfuscating cbased binaries to avoid decompilation is there some way to obfuscate cbased executables or libraries to prevent decompilation,['c'] +47416,socketserverthreadingtcpserver cannot bind to address after program restart as a followup to cannotbindtoaddressaftersocketprogramcrashes i was receiving this error after my program was restartedsocketerror errno 98 address already in usein this particular case instead of using a socket directly the program is starting its own threaded tcp serverhttpd socketserverthreadingtcpserverlocalhost port customhandlerhttpdserve foreverhow can i fix this error message,['python'] +47420,how to merge gwt google web toolkit project and dynamic web project ie java web appservlets in eclipse i currently have a primary java web app project which houses some servlets jsps and static html pages later on i also created a second eclipse google web toolkit project gwt now after finishing the gwt project i want to integrate or merge the gwt project while retaining its rpc capabilities with servlets with the primary java web app project in which directory do i need to copypaste the files and folders from gwt project to java web app project keep in mind that i want to export the fully compiled javascript code rather than java byte code,['java'] +47426,does extends object have a purpose or is it redundant following a tutorial on the internet regarding soap development with java i found this link with a rather unusual code for myselfthe codepublic class soapservice extends object creates new soapservice public soapservice this is the soap exposes method public string saygreetingstring name return hello name whats with the extends object syntax i have never encountered this kind of syntax only on generics does this syntax has any purpose or is plain dumb,['java'] +47427,download xlsx file using responsetransmitfile i am working on some code that generates an excel spreadsheet serverside and then downloads it to the user i am using excelpackage to generate the filethe generation is working just fine i can open the generated files using excel 2007 with no issues but i am having trouble downloading the file with responsetransmitfileright now i have the following codegenerate the file using excelpackagestring filename generateexcelfiledatalist myreportdataresponseaddheadercontentthisposition attachmentfilenamefilenamexlsresponsecontenttype applicationvndxlsresponsecharset responsetransmitfilefilenamewhen excel 2007 opens the file downloaded as above it gives the file format does not match extension warning after clicking past the warning excel thisplays the raw xml contents of the fileif i change the file extension like soresponseaddheadercontentthisposition attachmentfilenamefilenamexlsxexcel 2007 gives an excel found unreadable content in the file error followed by a dialog that offers to locate a converter on the web if i click no on this dialog excel is able to load the datai have also experimented with different mime types like applicationvndmsexcel and applicationvndopenxmlformatsofficedocumentspreadsheetmlsheet combined with file extensions of xls and xlsx all combinations result in one of the two behaviors mentioned abovewhat is the correct combination of file extension and mime type to use in this scenario what else could cause this failure other than an improper mime type or extensionfyi this is occurring with visual studios builtin development web server i have not yet tried this with iis,"['c#', 'asp.net']" +47457,program web applications in python without a framework i am just starting python and i was wondering how i would go about programming web applications without the need of a framework i am an experiance php developer but i have an urge to try out python and i usually like to write from scratch without the restriction of a framework,['python'] +47460,changing default encoding of python i have many cannot encode and cannot decode problems with python when i run my applications from the console but in the eclipse pydev ide the default character encoding is set to utf8 and i am finei searched around for setting the default encoding and people say that python deletes the syssetdefaultencoding function on startup and we can not use itso whats the best solution for it,['python'] +47482,easing c to objectiveccocoa bridging via metaprogramming in a pure c world we can generate interfacing or glue code between different components or interfaces at compile time using a combination of templatebased compiletime and runtimetechniques to eg mostly automatically marshall tofrom calls using legacy types when having to interface c applications with objectiveccocoa for gui system integration or ipc though things become harder due to the less strict typing yet often not more then a flat repitive interface layer is needed thin bridging delegates have to be defined or conversion code to language bridging calls has to be written if you have to deal with interfaces of nontrivial size and want to avoid scriptbased code generation this quickly becomes cumbersome and is just a pain every time refactorings have to take place using a combination of template metaprogramming and the objectivec runtime library it should be possible to reduce the amount of code considerably before i go to reinvent the wheel and possibly waste time does anyone know about techniques bestpractices or examples in that directionas for an example lets say we need a delegate that supports this informal protocol nsstringconcatstringnsstrings1 withstringnsstrings2 nsnumber indexofcustomclassobjinstead of implementing an objc class now that explicitly bridges to a cinstance i would like to do something like this insteadclass cppobj objcdelegate m delpublic cppobj m delthis m deladdhandler nsstring nsstring nsstring concatstring cppobjconcat m deladdhandler nsnumber customclass indexof cppobjindexof stdstring concatconst stdstring s1 const stdstring s2 return s1appends2 size t indexofconst convertedcustomclass obj return 42 all that should be needed from the user to support additional types would be to specialize a conversion template functiontemplateclass to class from to convertconst fromtemplate nsstring convertnsstring stdstringconst stdstring s the example above of course does ignore support for formal protocols etc but should get the point across also due to the typeinformation for objcruntimetypes being mostly decayed into somenativetypes or classtype i do not think the explicit specification of parameter and return types for the delegatemethods can be avoided,"['c++', 'objective-c']" +47483,how to configure tomcat to not encode the session id into the url when httpservletresponseencodeurl is invoked seems like a stupid question to which the answer would be do not use encodeurl but i am working with a codebase that uses netui anchor tags in the jsps and i need to thisable the writing of jsessionid into the urls as it is a security risk in weblogic you can configure this by configuring urlrewritingenabled in weblogicxml i know because i wrote that feature in the weblogic server however i cannot find an equivalent config option for tomcat,['java'] +47506,simple fast sql queries for flat files does anyone know of any tools to provide simple fast queries of flat files using a sqllike declarative query language i would rather not pay the overhead of loading the file into a db since the input data is typically thrown out almost immediately after the query is runconsider the data file animalstxtdog 15cat 20dog 10cat 30dog 5cat 40suppose i want to extract the highest value for each unique animal i would like to write something likecat animalstxt foo select 1 maxconvert2 using decimal group by 1i can get nearly the same result using sortcat animalstxt sort t k11 k22nrand i can always drop into awk from there but this all feels a bit awkward could not resist when a sqllike language would seem to solve the problem so cleanlyi have considered writing a wrapper for sqlite that would automatically create a table based on the input data and i have looked into using hive in singleprocessor mode but i cannot help but feel this problem has been solved before am i missing something is this functionality already implemented by another standard toolhalp,['sql'] +47520,how do i add an outer glow to a uiimage or uiimageview or uiview i want to add a faded shadowouter glow to a uiimageuiimageviewuiview but i know no core graphics at all editplease help,['iphone'] +47522,can somebody explain this c typedef i have just started working with c after not having worked with it for quite a while while most of it makes sense there are some bits that i am finding a bit confuddling for example could somebody please explain what this line doestypedef bool optionmanager optionhandlerconst abstring value,['c++'] +47525,maxlength in textarea using jquery using the script off i am trying to limit the input of a textarea to 10 characters prototype is also included in the page it works fine in chrome but in firefox the following error is given and the input is not limitedtextareamaxlength is nulli am completely stumped any help would be appreciated the code snippets followthe textarea text area project description cols 60 rows 8 maxlength 10 the javascript javascript include tag jquery jquerymaxlength script typetextjavascript jquerynoconflict jquerydocumentreadyfunction maxlength scriptjquerymaxlengthjsjqueryfnmaxlength function textareamaxlengthkeypressfunctionevent var key eventwhich all keys including return ifkey 33 key 13 var maxlength thisattrmaxlength var length thisvaluelength iflength maxlength eventpreventdefault,"['javascript', 'jquery', 'ruby-on-rails']" +47540,type list vs type arraylist in java 1 list mylist new arraylist2 arraylist mylist new arraylisti understand that with 1 implementations of the list interface can be swapped it seems that 1 is typically used in an application regardless of need myself i always use this i am wondering if anyone uses 2 also how often and can i please get an example does the situation actually require using 1 over 2 ie where 2 wouldnt sufficeaside coding to interfaces and best practices etcthanks,['java'] +47546,does c have with keyword like pascal with keyword in pascal can be use to quick access the field of a record anybody knows if c has anything similar to thatexi have a pointer with many fields and i do not want to type like thisif pointerfield1 pointerfield2 pointerfieldnwhat i really want is something like this in cwith pointer if field1 field2 fieldn,['c++'] +47549,how can i edit a view using phpmyadmin 324 i need to simply edit a very complicated view in phpmyadmin 324 but i cannot figure how to do that any suggestionsthanks,['mysql'] +47552,consuming java webservice with date and time elements in wcf i need to consume a java webservice which has elements of type date and timeexample from the wsdlxsdelement namefromtime nillabletrue typexsdtime xsdelement namedateofinspection typexsddate when consuming the webservice via add service reference visual studio 2008 generates the following codesystemxmlserializationsoapelementattributedatatypetime isnullabletruepublic systemnullablesystemdatetime fromtime systemxmlserializationsoapelementattributedatatypedatepublic systemdatetime dateofinspection sending a message results in an reflection error with the innerexceptiontime is an invalid value for the soapelementattributedatatype property the property may only be specified for primitive typeswhen removing the datatypetime and datatypedate attributes everything seems to work but modifying generated code is an anti pattern so is there any other way to get this workingupdatethe problem only exist if the date or time elements are nullablei reported a bug on microsofts connect site if you have the same problem you can vote it up hereupdate 2microsoft confirmed it is a bug and unlikly to be fixedupdate 3i checked with vs2010 and it still generates the wrong code btw we ended up modifying the generated code,['c#'] +47562,how to reset all checkboxes using jquery or javascript how can i reset all checkboxes in a document using jquery or javascript,"['javascript', 'jquery']" +47591,iphone setting navigation bar title hey all i am still pretty new to iphone development and i am having a bit of trouble figuring out how to change the title of my navigation bar on another question on this site somebody recommended using viewcontrollertitle title textbut that is not working for medo i need to add a uinavigationcontroller to accomplish this or maybe just an outlet from my uiviewcontroller subclass if it helps i defined the navigation bar in ib and i am trying to set its title in my uiviewcontroller subclass this is another one of those simple things that gives me a headache putting selftitle title text in viewdidload and initwithnibname did not work either anybody know whats happening and how to get it happening rightthanks,"['iphone', 'objective-c']" +47594,is explicit transaction rollback necessary many examples out there advocate explicit rollback of database transactions along the lines ofusing var transaction try do some reading andor writing here transactioncommit catch sqlexception ex explicit rollback transactionrollback however i tend to do thisusing var transaction do some reading andor writing here transactioncommitwhen an exception occurs i am just relying on the implicit rolling back of transactions that are not committedis there any problem relying on this implicit behavior does anyone have a convincing reason why i should not be doing it this way,"['c#', 'sql']" +47596,is there a way to enforce using tabs instead of spaces stylecop offers to check for consistent use of spaces but sadly lacks the opposite idea force source code to use tabs is there some way to add this functionality it does not have to be stylecop other tools are welcome as well,['c#'] +47600,testing multiple concurrent browser sessions i am developing a cardgame in ruby on rails and trying to work out how best to test it when a player joins a game their player object is stored in the session obviously in order for the game to work i need more than one player in a game at once since sessions are the same for different tabs in one browser i am currently testing a 2player game by having the app open in firefox and internet explorer at the same timebefore i go off and download chrome in order to test a third player is there an easier way of doing thisedit to clarify i am not yet at the stage where i want to run automated tests to see if it breaks i am at the stage where i want to be able to hack the backend db then refresh the page and see how it looks now or click a button to see the usually failure response or whether the behaviour is looking right,['ruby-on-rails'] +47607,how to add a custom log level to logger in ruby i need to add a custom log level like verbose or traffic to ruby logger how to do,['ruby'] +47618,timeout function if it takes too long to finish i have a shell script that loops through a text file containing urls that i want to visit and take screenshots ofall this is done and simple the script initializes a class that when run creates a screenshot of each site in the list some sites take a very very long time to load and some might not be loaded at all so i want to wrap the screengrabberfunction in a timeout script making the function return false if it could not finish within 10 secondsi am content with the simplest solution possible maybe setting a asynchronous timer that will return false after 10 seconds no matter what actually happens inside the function,['python'] +47620,can i create view with parameter in mysql i have a view like thiscreate view myview as select column from table where value 2i would like to make it more generic it means to change 2 into a variable i tried thiscreate view myview as select column from table where value myvariablebut mysql does not allow thisi found an ugly workaroundcreate function getmyvariable returns integer deterministic no sqlbegin return myvariable endand then view iscreate view myview as select column from table where value getmyvariablebut it looks really crappy and the usage is also crappy i have to set the myvariable before each usage of the viewis there a solution that i could use like thisselect column from myview2 where the concrete situation is as followsi have a table storing information about denied requestcreate table denial id integer unsigned auto increment primary keyid datetime datetime not null featureid mediumint unsigned not null foreign key featureid references feature id on update cascade on delete restrict userhostid mediumint unsigned not null foreign key userhostid references userhost id on update cascade on delete restrict multiplicity mediumint unsigned not null default 1 unique index denialindex featureid datetime userhostid engine innodbmultiplicity is number of identical requests recorded in the same second i want to thisplay a list of denials but sometimes when application gets denied it retries couple times just to make sure so usually when the same user gets denial 3 times on the same feature in couple seconds it is actually one denial if wed have one more resource to fulfill this request next two denials would not happen so we want to group the denials in report allowing user to specify the timespan in wich denials should be grouped eg if we have denials for user 1 on feature 1 in timestamps 1224262745 and user wants to group denials that are closer to each other than 4 sec he should get something like this 1 x2 24 x3 45 x1 we can assume that spaces between real denials are much bigger than between duplications i solved the problem in following waycreate function getdenialmergingtime returns integer unsigned deterministic no sqlbegin if isnulldenialmergingtime then return 0 else return denialmergingtime end ifendcreate view mergeddenialsviewhelper as select minseconddatetime as grouptime firstfeatureid firstuserhostid sumsecondmultiplicity as multiplicitysum from denial as first join denial as second on firstfeatureid secondfeatureid and firstuserhostid seconduserhostid and firstdatetime seconddatetime and firstdatetime seconddatetime getdenialmergingtime group by firstdatetime firstfeatureid firstuserhostid firstlicensescreate view mergeddenials as select grouptime featureid userhostid maxmultiplicitysum as multiplicitysum from mergeddenialsviewhelper group by grouptime featureid userhostidthen to show denials from user 1 and 2 on features 3 and 4 merged every 5 seconds all you have to do isset denialmergingtime 5select grouptime featureid userhostid multiplicitysum from mergeddenials where userhostid in 1 2 and featureid in 3 4i use view because in it it is easy to filter data and to use it explicit in jquery grid automatically order limit number of records and so on but it is just an ugly workaround is there a proper way to do this,['mysql'] +47626,crossplatform defining define for macros function and func compiling with gcc 442 and winxp visual studio c 2008 if defined win32 define function func endifas i want to use the macro to thisplay the function name i have done the above so i can crossplatform and use the same func when compiling on linux or windowshowever when i am compiling on winxp i get the following error func undeclared identifiercan i not define a macro like thismany thanks for any suggestions,['c'] +47631,whats the yield keyword in javascript i heard about a yield keyword in javascript but i found very poor documentation about it can someone explain me or recommend a site that explains its usage and what it is used for,['javascript'] +47633,c smo backup of remote database to local machine i have an application which performs backups and restores of sql databases this works fine on the local machine however if i run this against a sql server hosted on another machine i get the following errormicrosoftsqlservermanagementsmofailedoperationexception backup failed for server 25983079 microsoftsqlservermanagementcommonexecutionfailureexception an exception occurred while executing a transactsql statement or batch systemdatasqlclientsqlexception cannot open backup device cprogram filesstate managerarchivecapture20100217152147productdatabasesdatabasedatabaseback operating system error 3the system cannot find the path specifiedthis appears to be being caused by the sql server attempting to write this file to its local drive i cannot setup a shared area into which the backup can be placed due to security restrictionsdoes anyone know how i can move this data back to the machine the code is being called frommy code is below private string name private string server private string dbname private string user private string password public boolean performcapturestring archivedir string destination archivedir name if systemiodirectoryexistsdestination systemiodirectorycreatedirectorydestination server sqlserver connect if sqlserver null databasecollection dbc sqlserverdatabases if dbccontainsdbname backup bkpdatabase new backup bkpdatabaseaction backupactiontypedatabase bkpdatabasedatabase dbname backupdeviceitem bkpdevice new backupdeviceitemdestination dbname back devicetypefile bkpdatabasedevicesaddbkpdevice bkpdatabaseincremental false bkpdatabaseinitialize true perform the backup bkpdatabasesqlbackupsqlserver if systemiofileexistsdestination dbname back return true else return false else return false else return false,"['c#', 'sql']" +47635,is return autorelease a bug in objective c i am new to objective c and am trying to understand howwhen autorelease is called i understand the simple use case of void foo bar b bar alloc init autorelease self dosomethingb what about this next case is this a bug because the object will be immediately released upon leaving the scope of makebarbar makebar return bar alloc init autoreleasewhat if the caller does a retain bar b self makebar retainthankseric,['objective-c'] +47649,passing a 256bit wire to a c function through the verilog vpi i have a 256bit value in verilogreg 2550 vali want to define a system task foo that calls out to external c using the vpi so i can call foo like thisfoovalnow in the c definition for the function foo i cannot simply read the argument as an integer pli int32 because i have too many bits to fit in one of those but i can read the argument as a string which is the same thing as an array of bytes here is what i wrotestatic int foochar userdata vpihandle systfref args iter argh struct t vpi value argval pli byte8 value systfref vpi handlevpisystfcall null args iter vpi iteratevpiargument systfref argvalformat vpistringval argh vpi scanargs iter vpi get valueargh argval value argvalvaluestr int i for i 0 i 32 i vpi printf2x valuei vpi printfn vpi free objectargs iter return 0as you can see this code reads the argument as a string and then prints out each character aka byte in the string this works almost perfectly however the byte 00 always gets read as 20 for example if i assign the verilog reg as follows val 256h0102030405060708090a0b0c0d0e0f1012131415161718191a1b1c1d1e1fand call it using fooval then the c function prints this at simulation timevpi 20 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1fi have tested this with many different values and have found that the byte 00 always gets mapped to 20 no matter where or how many times it appears in valalso note that if i read the value in as a vpihexstrval and print the string it looks fineso two questionsis there a better way to read in my 256bit value from the verilogwhats going on with the 20 is this a bug am i missing somethingnote i am using aldec for simulation,['c'] +47652,what is mozusetextcolor i understand it is deprecated in firefox and its replacement is currentcolor my impression is that it is used for svgrelated stuff but what the heck is it,['css'] +47657,python function pointer i have a function name stored in a variable like thismyvar mypackagemymodulemyfunctionand i now want to call myfunction like thismyvarparameter1 parameter2whats the easiest way to achieve this,['python'] +47671,accessing parent class property from child see the following example phpclass parent protected property protected anotherp public function constructvar this property var thissomemethod sets anotherp protected function somemethod class child extends parent protected parent public function constructparent thisparent parent private function mymethod return thisparent anotherp note this line i am new to oop and am a bit ignoranthere to access the parents property i am using an instance of that class which seems wrong s no need of being i child then is there an easy way so that i can sync the parent properties with the child properties and can directly access thisanotherp without having to use thisparentanotherp,['php'] +47695,what is declspec and when do i need to use it i have seen instances of declspec in the code that i am reading what is it and when would i need to use this construct,['c++'] +47700,what are these extra parameters in my asmx proxy methods if i add a web reference from a net 11 client to a wcf service the proxy methods generated at the client contain an extra parameter ending with the suffix specified for each service method parameter egoperationcontractstring helloworldstring foo int barresults inservice1helloworldstring foo bool foospecified int bar bool barspecifiedmy service parameters are not optional so what are these extra parameters at the client and how can i get rid of them,"['c#', '.net']" +47702,how does c compute sin and other math functions i have been poring through net thisassemblies and the gcc source code but cannot seem to find anywhere the actual implementation of sin and other math functions they always seem to be referencing something elsecan anyone help me find them i feel like it is unlikely that all hardware that c will run on supports trig functions in hardware so there must be a software algorithm somewhere right edit i am aware of several ways that functions can be calculated and have written my own routines to compute functions using taylor series for fun i am curious about how real production languages do it since all of my implementations are always several orders of magnitude slower even though i think my algorithms are pretty clever obviously they are not,"['c++', 'c']" +47704,php setcookie domain some application not written by me and not in php creates a cookie for the domain wdomaincomi am trying to replace that cookie so in php i didsetcookiemycookiemydatatime 27246060wdomaincom falsehowever the resulting cookie is created for domain wdomaincom note the dot ahead of the domainso it does not replace it it creates another cookiewhat can i do,['php'] +47710,layout buttons so each divides up the space equally im using a linearlayout to put two buttons horizontally sidebyside but i want to each button to size itself to use 50 of the horizontal space i thought layout weight of 1 for each button would do the trick but maybe my layout width needs to be changed,['android'] +47716,how to log into facebook programmatically using java i am trying to write a java program that can automatically log into facebooki have got the below code so far that downloads the home html page into a string but do not know how to send the email and password to log into facebook also will the java program need to handle cookies returned to remain logged inpublic static void mainstring args throws exception url url new url urlconnection yc urlopenconnection bufferedreader in new bufferedreadernew inputstreamreaderyc getinputstream string inputline string allinput while inputline inreadline null allinput inputline rn systemoutprintlnallinput inclose updatei have tried the below code using htmlunit however i get the following exceptionexception in thread main comgargoylesoftwarehtmlunitelementnotfoundexception elementnameform attributenamename attributevaluelogin form at comgargoylesoftwarehtmlunithtmlhtmlpagegetformbynamehtmlpagejava588anyone know why this is final webclient webclient new webclient final htmlpage page1 webclientgetpage final htmlform form page1getformbynamelogin form final htmlsubmitinput button htmlsubmitinput formgetinputsbyvalueloginget0 final htmltextinput textfield formgetinputbynameemail textfieldsetvalueattribute final htmltextinput textfield2 formgetinputbynamepass textfield2setvalueattributeah final htmlpage page2 buttonclick,"['java', 'html']" +47717,is there a way to get the count size for a jpa named query with a result set i like the idea of named queries in jpa for static queries i am going to do but i often want to get the count result for the query as well as a result list from some subset of the query i would rather not write two nearly identical namedqueries ideally what i would like to have is something likenamedqueryname getaccounts query select a from account query q emcreatenamedquerygetaccounts list r qsetfirstresultssetmaxresultsmgetresultlist int count qgetcountso let us say m is 10 s is 0 and there are 400 rows in account i would expect r to have a list of 10 items in it but i would want to know there are 400 rows total i could write a second namedquerynamedqueryname getaccountcount query select counta from accountbut it seems a dry violation to do that if i am always just going to want the count in this simple case it is easy to keep the two in sync but if the query changes it seems less than ideal that i have to update both namedqueries to keep the values in linea common use case here would be fetching some subset of the items but needing some way of indicating total count thisplaying 110 of 400,['java'] +47720,net entityframework an error occurred while starting a transaction on the provider connection see the inner exception for details using entity framework in net i want to loop through a list of items returned from the database and make updates var qry from c in dbentitiescustomer select cforeach object item in qry itemfirstname etc other code here dbentitiessavechangesaccording to s hargroves suggests converting to a ilist and that is the solutionhave not tried that i am sure it will work but even it works i want to know why i cannot update the item during the loop this is occuring on my local development environment with no other users hitting the databasethanks,['.net'] +47723,how to iterate by row through a mysql query in php ok so i am trying to query my database and select all rows that have a certain valueafter that i turn the query into an array with mysql fetch array then i tried iterating by row through the fetched array using a for each loopphpquery mysql queryselect from users where pointsavailable 0 order by pointsavailable descqueryresultarray mysql fetch arrayqueryforeachqueryresultarray as row echo rowpointsavailablethough when i do this for any column besides the pointsavailable column say a column named name of type text it only returns a single letterhow do i iterate through a returned query row by row and be allowed to fetch specific columns of data from the current row,"['php', 'sql', 'mysql']" +47725,when to use a service or asynctask or handler can someone tell me the true difference,"['java', 'android']" +47762,how to run a codeigniter file through cron i have tried the following method in the pastphpset time limit0 serverpath info croncontrollerindex serverrequest uri croncontrollerindexrequire onceindexphpand putting this in a file in the codeigniter installation directory calling it cronphp and then invoking it viaphp homeusernamepublic htmlmy projectcronphpif i type the url to cronphp in my browser it works perfectly however whenever its run via cron i get a 404 error putting the following code in the show 404 function of codeigniterfunction show 404page print r server echo nn die pageresults in getting the following output emailed to mearray shell binsh mailto user me path usrbinbin pwd homeme shlvl 1 home homeme logname me usrbinphp php self request time 1266479641 argv array 0 homemepublic htmlmy projectcronphp argc 1 path info croncontrollerindex request uri croncontrollersindexhomemehere i have me in place of my actual usernameany ideas,['php'] +47763,access photo album from iphone code iphone apps like picture map access all the photos in my iphones camera album and thisplay them without ever showing an image picker controldoes anyone know how this is donethanksg,['iphone'] +47801,how to create a java application which can be run by a click i would like to have a java application which can be easily startedso far i have managed to create a jar file but i do not see any advantages yet before i run my application by java helloworldswing and now i use java jar helloworldswingjar which is even more complicated than the previous command and as far as i understood the usage of a jar file requires presence of mf file in the same directoryi would like to have one of the two following situationsjust one single file which can be copied to another operation system and that the project can be started just by click on this file in a file browser at the moment if click on my jar file ubuntu starts to extract archive because jar is an archive i knowcreate a pictogram which can be put on a desktop and clicking on which initiates my java program,['java'] +47805,problems using classgetresourceasstream in java i am a bit stuck on a project i am working on where i want to load in a text file from another folder i am using netbeans and have for the purposes of this problem two folders one with my class in and one with the resource in the class is in miscclassname and the text file i want to load is in resourcesnametxtthis sounds unbelievably simple and having done java for quite a while i really should know this i assumed the best way of loading this file rather than using just a filereader would be to use getresourceasstream as showninputstream is thisgetclassgetclassloadergetresourceasstream filename txtideally saving me time and not having to hardcode in a filepath now my problem is i constantly keep getting null returned from the above code and indeed any other permutation i can put on it i have tried resourcefilenametxt or resourcefilenametxt as parameters using getclassgetresourceasstream as opposed to getclassloader everything is still returning the same result just to avoid any confusion i have checked the filename and its definitely right and in the right case etc as well so that is not the issue any ideas i know i could just use filereader to accomplish the same goal but its kind of a principle thing now,['java'] +47819,c how to build strings char i am new to c i want to make a char but i do not know howin java is it just thisint player 0int cpu 0string s you player cpu cpuhow can i do this i need a chari am focusing on pasting the integer after the string,['c++'] +47830,what is the method memberwiseclone doing i am confused with this code belowdeveloper devcopy developerdevcloneclone method of developer class just creating a employee clone then how developer get another clone of developer public abstract class employee public abstract employee clone public string name get set public string role get set public class typist employee public int wordsperminute get set public override employee clone return employeememberwiseclone public override string tostring return stringformat0 1 2wpm name role wordsperminute public class developer employee public string preferredlanguage get set public override employee clone return employeememberwiseclone public override string tostring return stringformat0 1 2 name role preferredlanguage developer dev new developerdevname bobdevrole team leaderdevpreferredlanguage cdeveloper devcopy developerdevclonedevcopyname sueconsolewritelinedevconsolewritelinedevcopy outputbob team leader csue team leader ctypist typist new typisttypistname kaytypistrole typisttypistwordsperminute 120typist typistcopy typisttypistclonetypistcopyname timtypistcopywordsperminute 115consolewritelinetypistconsolewritelinetypistcopy outputkay typist 120wpmtim typist 115wpm,['c#'] +47839,closure does not work if a block is a closure why does this code does not work and how to make it workdef rarg classnew do def foo puts arg end endendclass a rhelloendanewfoo throws undefined local variable or method arg for a0x2840538,['ruby'] +47841,android layout is reusable component ui possible i will preface this with i have just started learning android so be gentlei come from an aspnet silverlight background so i was looking for something along the lines of controlsi want to reuse a layout a listview item template in other layoutssuch that in my other layouts i can just add mylistitem to show itis this or anything like it possible or are there better ways,['android'] +47846,sort lines in text file but only use the first and characters i have a text file with lines like this20100218 1146461287 bla20100218 11464613 foo20100218 11464613 bar20100218 1146461467 blaa simple sort would swap lines 2 and 3 bar comes before foo but i would like to keep lines that have the same datetime in their original orderhow can i do this in pythonbonus question can gnu sort also do this,['python'] +47848,how can i allow a user to resort items in a list i have an android app where users can add items to a list and i would like them to be able to reorder the items in the list however they want as opposed to just offering them different sort orders it is easy enough to add a position setting for the items they come from the db but what kind of ui elements are available for the user to indicate the desired orderingis there a pattern anyone has seen implemented for this i have not seen anything on android that does anything like this except the home screen which is similar but looks a little bit beyond my expertise at this point the best i can think of is to use a long click and context menu to move up or move down,['android'] +47863,pkix path building failed while making ssl connection i am integrating with a merchant account called commweb and i am sending an ssl post to their url when i try to send the post i get the following exceptionsunsecurityvalidatorvalidatorexception pkix path building failed sunsecurityprovidercertpathsuncertpathbuilderexception unable to find valid certification path to requested targetthe code which i did not write and that already exists in our codebase that performs the post ispublic static httpresponse sendhttppostsslstring url mapstring string params throws ioexception postmethod postmethod new postmethodurl for mapentrystring string entry paramsentryset postmethodaddparameterentrygetkey stringutilsnzentrygetvalue httpclient client new httpclient int status clientexecutemethodpostmethod if status 200 stringbuilder resultbuffer new stringbuilder resultbufferappendpostmethodgetresponsebodyasstring return new httpresponseresultbuffertostring else throw new ioexceptioninvalid response code status the documentation for the merchant account integration says nothing about certificates they did provide some sample jsp code that seems to blindly accept certificates define static constants public static x509trustmanager s x509trustmanager nullpublic static sslsocketfactory s sslsocketfactory nullstatic s x509trustmanager new x509trustmanager public x509certificate getacceptethissuers return new x509certificate public boolean isclienttrustedx509certificate chain return true public boolean isservertrustedx509certificate chain return true javasecuritysecurityaddprovidernew comsunnetsslinternalsslprovider try sslcontext context sslcontextgetinstancetls contextinitnull new x509trustmanager s x509trustmanager null s sslsocketfactory contextgetsocketfactory catch exception e eprintstacktrace throw new runtimeexceptionegetmessage write output to vpc sslsocket ssl sslsockets sslsocketfactorycreatesockets vpc host vpc port true sslstarthandshake os sslgetoutputstream get response data from vpc is sslgetinputstreamour webapp has a keystore and i tried adding the certificate which i exported from firefox using the keytool command but that did not work and i got the same error i have tried solutions on the web importing the key and using systemsetproperty but that seems kind of clunky and it did not work gave me a nosuchalgorithmerror any help is appreciated,['java'] +47877,how do i improve breaking substitution ciphers programmically i have written am writting a program to analyze encrypted text and attempt to analyze and break it using frequency analysisthe encrypted text takes the form of each letter being substituted for some other letter ie am bz ct etc etc all spaces and non alpha chars are removed and upper case letters made lowercase an example would be orginal input thisisasamplemessageitonlycontainslowercaseletters encrypted output ziololqlqdhstdtllqutozgfsnegfzqoflsgvtkeqltstzztkl attempt at cracking omieieaeanuhtnteeawtiorshylrsoaisehrctdlaethtootdehere it has only got i a and y correctlycurrently my program cracks it by analysing the frequency of each individual character and mapping it to the character that appears in the same frequency rank in a non encrypted texti am looking for methods and ways to improve the accuracy of my program as at the moment i do not get too many characters right for example when attempting to crack x amount of characters from pride and prejudice i get1600 10 letters correct 800 7 letters correct 400 2 letters correct 200 3 letters correct 100 3 letters correcti am using romeo and juliet as a base to get the frequency datait has been suggested to me to look at and use the frequency of character pairs but i am unsure how to use this because unless i am using very large encrypted texts i can imagine a similar approach to how i am doing single characters would be even more inaccurate and cause more errors than successes i am hoping also to make my encryption cracker more accurate for shorter inputsany suggestions would be very helpfulthanks,['c++'] +47878,how to find out what sql queries are being blocked and whats blocking them i am trying to optimize some slow web pages and my guess is that the problem has to do with sql blocking does not seem to be a matter of cpu or io utilization on the web server or database server whats the quickest way to find out what queries are getting blocked and what queries are doing the blocking,['sql'] +47880,silverlight 4 relativesource findancestor binding will there be relativesource findancestor ancestortype in silverlight 4,['.net'] +47883,why is the finalize method in javalangobject protected out of curiositywhy is the finalize methods access modifier is made as protected why cant it be public can someone explain me any specific reason behind thisalso i came to know that finalize method is called only once if i call it twice in my program internally what is happening will the garbage collector call this againprivate void dummycall try finalize finalize catch throwable e eprintstacktracenot reaches exception,['java'] +47887,modifying a textbox control on the leave event prevents tabbing out of the control i have got a standard textbox control which i am trying to have mimic the soft descriptions like those found in the title and tags boxes on stackoverflow essentially when the users focus enters the control it hides the description username in this case and sets alignment and color to be that of a standard text control when the user leaves the textbox i want to check if the user actually entered anything and put the username thisplay back up otherwisefor example private void tbusername enterobject sender eventargs e if tbusernametextalign horizontalalignmentcenter tbusernametextalign horizontalalignmentleft tbusernameforecolor systemcolorscontroltext tbusernametext stringempty private void tbusername leaveobject sender eventargs e if tbusernametext stringempty tbusernametextalign horizontalalignmentcenter tbusernameforecolor systemcolorsinactivecaption tbusernametext username unfortunately when i setup these events the user cannot tab out of the username control the control simply flickers and control returns to the textbox control itself until the user has entered something skipping over the event bodyif i call thisselectnextcontrol in the event then the event enters an infinite loopdoes anybody see what i am doing wrong,"['c#', '.net']" +47892,how to add marquee behaviour to jlabel how to add marquee behaviour to text of jlabeli have tried thisjlabel search new jlabelhtmlmarqueesearchmarqueehtmlbut its not working,['java'] +47900,handling file uploads with javascript and google gears is there a better solution so i have been using this method of file uploading for a bit but it seems that google gears has poor support for the newer browsers that implement the html5 specs i have heard the word deprecated floating around a few channels so i am looking for a replacement that can accomplish the following tasks and support the new browsers i can always fall back to gears standard file posts but these following items make my process much simplerusers must to be able to select multiple files for uploading in the dialogi must be able to receive status updates on the transmission of a file progress barsi would like to be able to use put requests instead of posti would like to be able to easily attach these events to existing html elements using javascript ie the file selection should be triggered on a button clicki would like to be able to control responserequest parameters easily using javascripti am not sure if the new html5 browsers have support for the desktoprequest objects gears uses or if there is a flash uploader that has these features that i am missing in my google searchesan example of uploading code using gears select some filesvar desktop googlegearsfactorycreatebetadesktopdesktopopenfilesselectfilescallbackfunction selectfilescallbackfiles eachfilesfunctionkfile this code actually goes through a queue and creates some status bars but it is unimportant to show here sendfilefile function sendfilefile googlegearsfactorycreatebetahttprequest requestopenput uplurl requestsetrequestheaderfilename filename requestuploadonprogress functione gives me status updates allows eloadedetotal requestonreadystatechange function if requestreadystate 4 completed the upload requestsendfileblob return requestedit apparently flash is not capable of using put requests so i have changed it to a like instead of a must,"['javascript', 'html']" +47903,how to control the scroll position of a listbox in a mvvm wpf app i have got a big listbox with vertical scrolling enabled my mvvm has new and edit icommandsi am adding new item to the end of the collection but i want the scrollbar also to auto position to the end when i call my mvvmaddcommandi am also making an item editableby calling editcommand with a particular row item from some other part of the application so that my listboxitem getting in to edit mode using datatrigger but how will i bring that particular rowlistboxitem to the view by adjusting the scroll positionif i am doing it in the view side i can call listboxscrollintoviewlstboxitembut what is the best way to solve this common scroll issue from an mvvm perspective,['c#'] +47906,xmlserializer list item element name i have a class personlistxmlrootpersonspersonlist listhumanwhen i serialize this to xml by default it will produce something like thispersons humanhuman humanhumanpersonsmy question is what needs to be done in order to change element human to person in the output so the output would be persons personperson personpersonpersonsand how to deserialize the above xml to the personlist class objectper nicks advice here is my testing codexmlrootpersonspublic class persons listhumanxmlrootpersonpublic class human public human public humanstring name name name xmlelementname public string name get set void testxmlserialize persons personlist new persons personlistaddnew humanjohn personlistaddnew humanpeter try using stringwriter writer new stringwriter xmlserializer serializer new xmlserializertypeofpersons xmlwritersettings settings new xmlwritersettings settingsomitxmldeclaration true xmlserializernamespaces namespaces new xmlserializernamespaces namespacesaddstringempty stringempty xmlwriter xmlwriter xmlwritercreatewriter settings serializerserializexmlwriter personlist namespaces consoleoutwritelinewritertostring catch exception e consoleoutwriteline etostring the output of the testing code ispersons human namejohnname human human namepetername humanpersonsas the output shows the xmlrootperson on human does not change the tag to person from human,['c#'] +47910,c what does 0 equate to i am playing with pex and one of the parameters it passes into my method is 0what does that mean my guess is an empty string based on the content of my method however if it is the same then why not just use instead of 0anyone know what it is,['c#'] +47934,is there a very lightweight lightbox available i am looking for an extremely lightweight lightbox for jquery i am trying to create my own but i suck and my fist is about to go through the screen i am talking like 5kb or less i know it can be done and if i knew what i was doing i would do it but i am just done for the day so does anyone know of one something just for images and nothing else no fancy crap no extra weight one that simply centers the lightbox in the center of the screen with whatever picture was loaded by the link,['jquery'] +47944,css3 transparency gradient rgba is extremely fun and so is webkitgradient mozgradient and uh progiddximagetransformmicrosoftgradient yeah is there a way to combine the two rgba and gradients so that there is gradient of alpha transparency using the currentlatest css specs,['css'] +47945,error expected unqualifiedid before afora the following code returns this error expected unqualifiedid before aforai cannot find what is causing the error thanks for the helpincludeiostreamusing namespace stdconst int num months 12struct month string name int and daysmonth months new month num monthsstring m jan feb mar apr may jun jul aug sep oct nov decint n 31 29 31 30 31 30 31 31 30 31 30 31for int i0 inum months i will initialize the monthsint main will print namei daysi return 0,['c++'] +47947,long polling netty nio framework java how can i do longpolling using netty framework say for example i fetch httplocalhostwaitforxbut waitforx is asynchronous because it has to wait for an event say for example it fetches something from a blocking queuecan only fetch when data in queue when getting item from queue i would like to sent data back to client hopefully somebody can give me some tips how to do this many thanks,['java'] +47951,calling a method in a javascript constructor and accessing its variables i am trying to call a method from the constructor of my javascript constructor is this possible and if so i cannot seem to get it working any insight would be great thanksfunction validatefieldspformid var aform documentgetelementbyidpformid thiserrarray new arrayerror tracker thiscreateerrorlist createerrorlist creates a list of errors ul idformerrors li you must provide an email li ul returns nothing validatefieldsprototypecreateerrorlist functionformstatid consolelogcreate error list editi got it to work with what is above but i cannot seem to access the errarray variable in createerrorlist function,['javascript'] +47972,example of volatile preventing a compiler optimization in c from what i understand the volatile modifier in c has two effectsinserts fences as necessary for the target processorprevents certain compiler optimizationson x86 amd64 1 is irrelevant those processors do not require fences for volatile semantics ia64 is different thoughso we are down to 2 but for examples that i tried volatile does not make any difference to the jitted assemblymy question is can you give an example of a c code sample where adding a volatile modifier on a field results in different jitted assembly code,"['c#', '.net']" +47974,what do lambda function closures capture in python recently i started playing around with python and i came around something peculiar in the way closures work consider the following codeadders 0123for i in 0123 addersilambda a iaprint adders13it builds a simple array of functions that take a single input and return that input added by a number the functions are constructed in for loop where the iterator i runs from 0 to 3 for each of these number a lambda funciton is created which captures i and adds it to the functions input the last line calls the second lambda function with 3 as a parameter to my surprise the output was6i expected a 4 my reasoning was in python everything is an object and thus every variable is essential a pointer to it when creating the lambda closures for i i expected it to store a pointer to the integer object currently pointed to by i that means that when i assigned a new integer object it should not effect the previously created closures sadly inspecting the adders array within a debugger shows that it does all lambda functions refer to the last value of i 3 which results in adders1 returning 6which me the followingwhat does the closures capture exactlywhat is the most elegant way to convince that lambda functions to capture the current value of i and in a way that will not be affected when i changes it is value,['python'] +47976,aspnet mvc solutionproject layouts this is more of an open question rather than looking for one specific answeras we all know there is no one answer that fits all solutions but i am curious to find out how you structure you aspnet mvc solutions and any pitfalls you may have come across in your design or things that you would do differently if you could start againthe standard aspnet mvc template is just a basic template and i am sure i have readheard in a podcast that scott hanselman stated the only reason the model folder is there is so people did not ask wheres the model this already implies that maybe it should be moved to its own separate classpersonally in the small mvc apps i have done i have separated out the model into its only class that holds the model and the repository while the mvc project has the controller and the views this has generally workout without any issues but as i said these have only been small appsso what are most people doing just using the standard template separating out just the model separating out the model and the controller separating out even move so all the data access is done through web services or some sort of data portal or something totally differentfinally how are people creating unit tests just one unit test class that test each of the projects or a unit test class for each project,['asp.net'] +47987,mocking extension methods with moq i have a preexisting interfacepublic interface isomeinterface void somemethodand i have extended this intreface using a mixinpublic static class someinterfaceextensions public static void anothermethodthis isomeinterface someinterface implementation here i have a class thats calling this which i want to testpublic class caller private readonly isomeinterface someinterface public callerisomeinterface someinterface thissomeinterface someinterface public void main someinterfaceanothermethod and a test where i would like to mock the interface and verify the call to the extension method test public void main basiccall callsanothermethod arrange var someinterfacemock new mockisomeinterface someinterfacemocksetupx xanothermethodverifiable var caller new callersomeinterfacemockobject act callermain assert someinterfacemockverify running this test however generates an exceptionsystemargumentexception invalid setup on a nonmember methodx xanothermethodmy question is is there a nice way to mock out the mixin call,['c#'] +47991,determine number of decimal place using bigdecimal i was interested to have the following getnumberofdecimalplace function systemoutprintln0 utilsgetnumberofdecimalplace0 0 systemoutprintln10 utilsgetnumberofdecimalplace10 0 systemoutprintln101 utilsgetnumberofdecimalplace101 2 systemoutprintln1012 utilsgetnumberofdecimalplace1012 3 systemoutprintln001 utilsgetnumberofdecimalplace001 2 systemoutprintln0012 utilsgetnumberofdecimalplace0012 3may i know how can i implement getnumberofdecimalplace by using bigdecimalthe following code does not work as expected public static int getnumberofdecimalplacedouble value final bigdecimal bigdecimal new bigdecimal value final string s bigdecimaltoplainstring systemoutprintlns final int index sindexof if index 0 return 0 return slength 1 indexthe following get printed 0 11010 1101101 210121012 3001001 200120012 3however for case 0 10 it does not work well i expect 0 as result but they turned out to be 00 and 10 this will return 1 as result,['java'] +48004,two columns must not equal each other in rails i am creating a social network in rails and i have a model like thiscreate table friendships force true do t tinteger user1 id tinteger user2 id tboolean hasaccepted tdatetime created at tdatetime updated atendthe problem is that you cannot add yourself as friend so i tried this in my modeldef validate if user1 id user2 id recorderrorsadd you cannot add yourself as a friend return false endendand i have this in my controllerdef addfriend if paramsid friendship friendshipnew friendshipuser1 id sessionuser friendshipuser2 id paramsid respond to do format if friendshipsave formathtml redirect to yes so users i will fix this redirect later and it is not important for now formatxml render xml friendship status created else formathtml redirect to formatxml render xml friendshiperrors status unprocessable entity end end endendwhere sessionuser is the uid of the currently signed in userhowever when i go to httplocalhost30profileaddfriend2xml while i am signed in as user 2 rails returns me the new friendship instead of an error message and when i take a look at my database the friendship is also there and it should not can someone please explain me how to fix this thanks,['ruby-on-rails'] +48012,iphone uitextfield not showing edit caret or clearing placeholder text when tapped i have a window within an iphone application which is thisplayed modally to allow the user to enter their settings for a web service upon first run the text fields have helper text set and when you tap them the keyboard shows and allows you to enter textunfortunately the text fields do not clear the helper text show the edit caret or show the text being entered as in the screenshot belowany suggestions the window is being thisplayed with self presentmodalviewcontrollercontroller name animatedyes which may or may not be the cause of this issue when i run the ui via the interface builder test application the text boxes respond like normalclear when editing begins has been set for both fieldsthanks in advanceedited more informationafter the info bart gottschalk provided i thought i should add some more information first the application is a navigation based applicationsecondly the test app bart recommended worked fine so that takes the modal window and the view out of the equationthird i was presenting the modal view when the voidviewwillappear delegate method was being called which may very well be the wrong place however i am not 100 sure if i should be presenting the modal view from within the didfinishlaunchingwithoptions of the app delegatethis is happening on simulator and iphone 313,['iphone'] +48022,wcf operationcontract which generic collection type should i expose i have a wcf web service that has a method that returns a generic collection now my question is should i expose it as icollectiont listt ilistt ienumerablet or something else i suppose that listt is out of the question since i want to avoid ca1002 errors but the underlying type will be a listti am really interested in hearing your takes on this preferably with a good explanation of why you think what you thinkthanks in advance,['c#'] +48023,java linkedlist previous next is there anything similar to nets linkedlistnodeof tnext and linkedlistnodeof tprevious properties in javas javautillinkedlist,"['java', '.net']" +48033,do simple things with a google wave robot i wanted to add 3 features to the robot from the tutorial herebefore adding all these features my robot is working as intendednow the odd features still shows up with v2 at the bck of the blip content but neither of the new features shows upi tried different ways alr still does not work so frustrating below is the code tt i think looks more logicallycan someone tell me why none seems to work thanksfeature 1 wanted to try out appendtextfeature 2 wanted the robot to detect a blip is submittedfeature 3 wanted the robot to add a blip with the content of the old blip deletedfrom waveapi import eventsfrom waveapi import modelfrom waveapi import robotdef onparticipantschangedproperties context invoked when any participants have been addedremoved added propertiesparticipantsadded for p in added notifycontextdef onrobotaddedproperties context invoked when the robot has been added root wavelet contextgetrootwavelet feature 1 root waveletcreateblipgetdocumentsettexti am alive v2getdocumentappendtextxdef notifycontext root wavelet contextgetrootwavelet root waveletcreateblipgetdocumentsettexthi everybody v2 feature 2def onblipsubmittedproperties context blip contextgetblipbyidpropertiesblipid blipgetdocumentappendtextx feature 3def onblipdeletedproperties context blip contextgetblipbyidpropertiesblipid contents blipgetdocumentgettext root wavelet contextgetrootwavelet root waveletcreateblipgetdocumentsettextcontentsif name main myrobot robotrobotappname image url version1 profile url myrobotregisterhandlereventswavelet participants changed onparticipantschanged myrobotregisterhandlereventswavelet self added onrobotadded myrobotregisterhandlereventsblip sumbitted onblipsubmitted myrobotregisterhandlereventsblip deleted onblipdeleted myrobotrunedit importanti just noticed that it seems to hv different behaviour on normal mode vs sandbox mode in normal mode i see both blips i am alive v2 and hi everybody v2 but in sandbox mode i can only see the 1st one werid in neither case i see the appended text the reason why i commented this part myrobotregisterhandlereventsblip sumbitted onblipsubmitted myrobotregisterhandlereventsblip deleted onblipdeletedis cos without commenting it the robot does not do anything at all,['python'] +48038,what am i misunderstanding about how htmltextboxfor works i am just trying to get back into net mvc with the new release and i cannot get my head round the way may view is binding to the datamodeli have a model with a property first name and within an html form i have the following htmltextboxfirst name modelfirst name htmltextboxformodel modelfirst name input typetext namefirst name idfirst name classmylabel valuemodelfirst name in an action on a controller if i set the first name property on my model and domymodelobjectfirst name testreturn viewmymodelobjectwhat is the reason only the third textbox picks up on this first name value and the other two do notediti probably have not explained this well enough sorry imagine i have 2 controller methods public actionresult register registration model new registration modelfirst name test return viewmodelwith this one either binding worksafter this has been thisplayed i then click a button on the form and try and run thishttppostpublic actionresult registerregistration viewdata model modelfirst name steve return viewmodelwhat i am asking is why does the 3rd but not the first 2 bind to steve as the new name,['asp.net'] +48046,jvm outofmemory error death spiral not memory leak we have recently been migrating a number of applications from running under redhat linux jdk160 03 to solaris 10u8 jdk160 16 much higher spec machines and we have noticed what seems to be a rather pressing problem under certain loads our jvms get themselves into a death spiral and eventually go out of memory things to notethis is not a case of a memory leak these are applications which have been running just fine in one case for over 3 years and the outofmemory errors are not certain in any case sometimes the applications work sometimes they do notthis is not us moving to a 64bit vm we are still running 32 bitin one case using the latest g1 garbage collector on 160 18 seems to have solved the problem in another moving back to 160 03 has workedsometimes our apps are falling over with hotspot sigsegv errors this is affecting applications written in java as well as scalathe most important point is this the behaviour manifests itself in those applications which suddenly get a deluge of data usually via tcp it is as if the vm decides to keep adding more data possibly progressing it to the tg rather than running a gc on newspace until it realises that it has to do a full gc and then despite practically everything in the vm being garbage it somehow decides not to collect it it sounds crazy but i just do not see what else it is how else can you explain an app which one minute falls over with a max heap of 1gb and the next works just fine never going about 256m when the app is doing exactly the same thingso my questions arehas anyone else observed this kind of behaviourhas anyone any suggestions as to how i might debug the jvm itself as opposed to my app how do i prove this is a vm issueare there any vmspecialist forums out there where i can ask the vms authors assuming they are not on so we have no support contractif this is a bug in the latest versions of the vm how come noone else has noticed it,['java'] +48056,fitting a line in 3d are there any algorithms that will return the equation of a straight line from a set of 3d data points i can find plenty of sources which will give the equation of a line from 2d data sets but none in 3dthanks,['python'] +48061,oracle any vs in i just stumbled upon something in oracle sql not sure if it is in others that i am curious about i am asking here as a wiki since it is hard to try to search symbols in google i just found that when checking a value against a set of values you can do where x any a b cas opposed to the usual where x in a b cso i am curious what is the reasoning for these two syntaxes is one standard and one some oddball oracle syntax or are they both standard and is there a preference of one over the other for performance reasons or just curious what anyone can tell me about that any syntax cheerz,['sql'] +48065,find html element which id starts with i have html code in multiple pages on each of them i used a jqgrid jquery grid for thisplay some data i knew that on each of those pages the element that holds the jqgrid is named as list x now i need to make a javascript that takes that element list x on each page and does some stuff how could i search for an element by id but only knowing its initial part of the id like i mentioned previouslylist x the part surrounded by is variable on each page i want to thiscriminate thati hope i made myself clear thanks,['jquery'] +48080,java vm reproducable sigsegv on both 160 17 and 160 18 how to report edit this reproducible sigsegv happens on a linux machine with more than one proc and more than 2gb of mem so java is defaulting to the server mode interestingly enough if i force client there is no crash anymore i am still not too sure what to do with my reproducible sigsegv but it is interesting nonethelessfirst note that this is a bit related but not identical to the following because in our case it is only a sigsegv that happens and we can reliably trigger itit is related because it happens when we feed our app with a deluge of data data are coming from text files and then numbercrunched yes financial number crunching in javai can reliably trigger a jvm to sigsegv using only valid java codenote i can invariably crash both jvm 160 17 adn jvm 160 18 and this question is not about how to workaround this issue for example playing with vm parameters may fix the issue but i am not after that i want to know what to do with this alwaysreproducable sigsegvi have got a workaround which simply consists in using java 15 when launching our app while still using java 16 to run intellij idea etc on the same machine simultaneously but my question is if this should be reported or not and if it should how to report it knowing that the log itself contains proprietary information the full hs err loghardware error can be ruled out forthis is happening on a workstation that regularly reaches months of uptime i only reboot it when critical security patches affecting my trimmed down and hardened debian linux are issued which really does not happen often and on which applications never crash making it very unlikely that it is an hardware issue on that machine more belowsame application works perfectly on that same machine under a jvm 15 under the same load this is how i am testing the app i simply launch it under a 15 vmsame application works perfectly fine on more than one hundreds clients machine under the same gigantic load never crashed once on windows jvm 15 or 16 and never crashed once on os x jvm 15 or 16 a crash would mean an instant phone call from the clientother application on that same machine and same 160 17 or 160 18 jvm never crash for example i have got two instances of intellij idea running as two different users on that same machine and they do not crashmachine is tested with memtest regularly before installing a new os which last happened when i installed debian lenny not that long agoheres the reproducibleondemand sigsegv uname alinux saturn 26262686 1 smp wed nov 4 204537 utc 2009 i686 gnulinux export homewizardjdk160 17binpath java versionjava version 160 17javatm se runtime environment build 160 17b04java hotspottm server vm build 143b01 mixed modelaunch the app feed it a deluge of data wait a few secondsthen invariably for 160 17 a fatal error has been detected by the java runtime environment sigsegv 0xb at pc0xb76d0080 pid30793 tid2514328464 jre version 60 17b04 java vm java hotspottm server vm 143b01 mixed mode linuxx86 problematic frame v libjvmso0x4bc080 an error report file with more information is saved as homewizardhs err pid30793log if you would like to submit a bug report please visit note that the line libjvmso0x4bc080 is consistent for 160 17 at every sigsegvor for 160 18 a fatal error has been detected by the java runtime environment sigsegv 0xb at pc0xb77468f0 pid722 tid2514516880 jre version 60 18b07 java vm java hotspottm server vm 160b13 mixed mode linuxx86 problematic frame v libjvmso0x4d88f0 an error report file with more information is saved as homewizardhs err pid722log if you would like to submit a bug report please visit abortednote that the line libjvmso0x4d88f0 is consistent for 160 18 at every sigsegvthe problem is that the log file contains proprietary informationthat cannot be sharedreproducing a tiny test case that reproduce the issue am not realistic either it is similar to the issue linked above this only happens when a deluge of data is feeded to the appnote that the exact same application on exactly the same hardware with exactly the same jvm but another version of linux i had debian etch previously did not trigger that sigsegv oncebut this does not mean the jvm is not at fault it could still be a jvm issueshould i report this and how keeping in mind that writing a reproducible tiny test case is delusional and that the log contains proprietary information that should not be leaked should i just edit the log and send itwhats the procedure to report such reproducible sigsegv when your log contains proprietary information and when a test case reproducing the issue am not realistically doabledid any of you have success opening such a bug and then see it solved in a subsequent java releasedo you think it is good for the java community to report such an issue or i just should not bother because it is not important,['java'] +48083,comparison of performance between scala etc and ccfortran i wonder if there is any reliable comparison of performance between modern multithreadingspecialized languages like eg scala and classic lowerlevel languages like c c fortran using parallel libs like mpi posix or even openmpany links and suggestions welcome,['c++'] +48097,how much memory can an iphone app use can anyone link me to a page that describes memory allocations for iphone appsi have heard that you are limited to a sandbox of 20 megs depending on the state of the phone but i cannot find the source for this,"['iphone', 'objective-c']" +48111,unique ptr v shared ptr in regards to destruction policy i have been teaching myself the smart pointers that are part of c0x and came across something that feels inconsistent to me specifically how the destruction policy of unique ptr and shared ptr are handledfor unique ptr you can specialize stddefault delete and from then on unless you explicitly request a different destruction policy the new default will be usedconsider the followingstruct some c typesome c type construct some c typevoid destruct some c typesome c type namespace std template struct default deletesome c type void operatorsome c type ptr destruct some c typeptr now once that is in place unique ptr will use the appropriate destruction policy by default because of the specialization this will use destruct some c typestdunique ptrsome c type varconstruct some c typenow compare this to shared ptr with shared ptr you need to explicitly request the appropriate destruction policy or it defaults to using operator delete error will use operator delete stdshared ptrsome c type varconstruct some c type correct must explicitly request the destruction policystdshared ptrsome c type varconstruct some c type stddefault deletesome c typetwo questionsam i correct that shared ptr requires the destruction policy to be specified every time it is used or am i missing somethingif i am not missing something any idea why the two are differentps the reason i care about this is my company does a lot of mixed c and c programming the c code often needs to use cstyle objects so the ease of specifying a different default destruction policy is quite important to me,['c++'] +48122,warnings in java when casting to a generic type i have some generic code which i cannot figure out how to legitimately prevent getting warnings from i am using suppresswarningsunchecked for the moment since it seems that casting a generic type cannot be done without warningshow can i get rid of the annotationwhat i have ispublic myobjectsharedcontextobject ctx superctx set protected field context contextsetinput fields collectionssynchronizedmapnew treemapstringpairstringbooleanstringcase insensitive order contextsetoutput fields collectionssynchronizedmapnew treemapstringstring stringcase insensitive order contextsetevent registrynew eventregistrylog suppresswarningsuncheckedprotected void startup inputfields mapstringpairstringbooleancontextgetinput fields null outputfields mapstringstring contextgetoutput fields null eventregistry eventregistry contextgetevent registrynull the protected variable context is type sharedcontextobjectwithout the annotation the compiler gives warningsmyclassjava94 warning unchecked unchecked castfound javalangobjectrequired javautilmapjavalangstringcommycompanypairjavalangstringjavalangboolean inputfields mapstringpairstringbooleancontextgetinput fields null myclassjava95 warning unchecked unchecked castfound javalangobjectrequired javautilmapjavalangstringjavalangstring outputfields mapstringstring contextgetoutput fields null,['java'] +48124,javascript syntaxhighlighting lost when ajax call is made i have a page on my website that i am making a call to using a jquery ajax call it loads in a div but whenever i the page is loaded it loses the snytax highlighting that it should be thisplaying ex htmlhead syntax highlighting script script typetextjavascript srcsyntaxhighlighterjsscriptheadbody div that thisplays ajax page cal div idawesomeodivbodyhtmlit works on the initial page load if i have something in awesomeo but if a page is loaded via ajax into the div the syntax thisappears editthe following is the code that is in the headerscript typetextjavascript srcscriptsshcorejsscriptscript typetextjavascript srcscriptsshbrushbashjsscriptscript typetextjavascript srcscriptsshbrushcppjsscriptscript typetextjavascript srcscriptsshbrushcsharpjsscriptscript typetextjavascript srcscriptsshbrushcssjsscriptscript typetextjavascript srcscriptsshbrushjavajsscriptscript typetextjavascript srcscriptsshbrushjscriptjsscriptscript typetextjavascript srcscriptsshbrushphpjsscriptscript typetextjavascript srcscriptsshbrushplainjsscriptlink typetextcss relstylesheet hrefstylesshcorecsslink typetextcss relstylesheet hrefstylesshthemedefaultcscript typetextjavascript syntaxhighlighterconfigclipboardswf scriptsclipboardswf syntaxhighlighterallscriptthis is from that is all that is used for syntax highlighting suggestions,"['javascript', 'jquery']" +48127,should my webpage compatible with outdated ie6 still as a web developer it is tough to do web design which is compatible with ie6 is it required to make webpages compatible with css i heard the usage of ie6 is lowmy question is whether i should still check compatibility of the webpage that i make in internet explorer 6,"['html', 'css']" +48131,what is the optimal winning strategy for this modified blackjack game questionsis there a best value to stay on so that i win the greatest percentage of games possible if so what is itedit is there an exact probability of winning that can be calculated for a given limit independent of whatever the opponent does i have not done probability statistics since college i would be interested in seeing that as an answer to contrast it with my simulated resultsedit fixed bugs in my algorithm updated result tablebackgroundi have been playing a modified blackjack game with some rather annoying rule tweaks from the standard rules i have italicized the rules that are different from the standard blackjack rules as well as included the rules of blackjack for those not familiarmodified blackjack rulesexactly two human players dealer is irrelevanteach player is dealt two cards face downneither player ever knows the value of any of the opponents cardsneither player knows the value of the opponents hand until both have finished the handgoal is to come as close to score of 21 as possible outcomesif players a b have identical score game is a drawif players a b both have a score over 21 a bust game is a drawif player as score is 21 and player b has busted player a winsif player as score is greater than player bs and neither have busted player a winsotherwise player a has lost b has woncards are worthcards 2 through 10 are worth the corresponding amount of pointscards j q k are worth 10 pointscard ace is worth 1 or 11 pointseach player may request additional cards one at a time untilthe player does not want any more staythe players score with any aces counted as 1 exceeds 21 bustneither player knows how many cards the other has used at any timeonce both players have either stayed or busted the winner is determined per rule 3 aboveafter each hand the entire deck is reshuffled and all 52 cards are in play again what is a deck of cardsa deck of cards consists of 52 cards four each of the following 13 values2 3 4 5 6 7 8 9 10 j q k ano other property of the cards are relevanta ruby representation of this iscards 211to a1034algorithmi have been approaching this as followsi will always want to hit if my score is 2 through 11 as it is impossible to bustfor each of the scores 12 through 21 i will simulate and hands against an opponentfor these and hands the score will be my limit once i reach the limit or greater i will staymy opponent will follow the exact same strategyi will simulate and hands for every permutation of the sets 1221 1221print the difference in wins and losses for each permutation as well as the net win loss differencehere is the algorithm implemented in rubyusrbinenv rubyclass array def shuffle sort by rand end def shuffle selfreplace shuffle end def score sorteach with indexinject0sci sc 21 size i 1 c11 s1 sc endendnargv0100 0to indecks argv11to icards 211to a1034ndeckscardsshufflemy limits 1221to aopp limits my limitsdupputs 55 opponent limitprintf my limit opp limitseach do result printf 10s resultto sendprintf 10s netputsprintf 8 print 8opp limitseach do result print 8endputswin totals arraynew10win totalsmap arraynew10 my limitseach do my limit printf 8s my limit stdoutflush opp limitseach do opp limit if my limit opp limit will be a tie skip win totalsmy limit12opp limit12 0 print stdoutflush next elsif win totalsmy limit12opp limit12 if previously calculated print printf 10d win totalsmy limit12opp limit12 stdoutflush next end win 0 lose 0 draw 0 ntimes cards cardsdupshuffle my hand cardspop cardspop opp hand cardspop cardspop hit until i hit limit while my handscore my limit my hand cardspop end hit until opponent hits limit while opp handscore opp limit opp hand cardspop end my score my handscore opp score opp handscore my score 0 if my score 21 opp score 0 if opp score 21 if my handscore opp handscore draw 1 elsif my score opp score win 1 else lose 1 end win totalsmy limit12opp limit12 winlose win totalsopp limit12my limit12 losewin shortcut for the inverse printf 10d winlose stdoutflush end printf 10d win totalsmy limit12inject putsendusageruby blackjackrb num iterations num decksthe script defaults to 10 iterations and 4 decks 10 takes about 5 minutes on a fast macbook prooutput n 100 0 opponent limitmy limit 12 13 14 15 16 17 18 19 20 21 net 12 76 13315 15799 15586 10445 2299 12176 30365 65631 43062 13 76 6962 11015 11350 8925 975 101 27924 60037 66511 14 13315 6962 6505 9210 7364 2541 8862 23909 54596 82024 15 15799 11015 6505 56 6849 4281 4899 17798 45773 84993 16 15586 11350 9210 56 6149 5207 546 11294 35196 77492 17 10445 8925 7364 6849 6149 7790 5317 2576 23443 52644 18 2299 975 2541 4281 5207 7790 11848 7123 8238 12360 19 12176 101 8862 4899 546 5317 11848 18848 8413 46690 20 30365 27924 23909 17798 11294 2576 7123 18848 28631 116526 21 65631 60037 54596 45773 35196 23443 8238 8413 28631 255870interpretationthis is where i struggle i am not quite sure how to interpret this data at first glance it seems like always staying at 16 or 17 is the way to go but i am not sure if it is that easy i think it is unlikely that an actual human opponent would stay on 12 13 and possibly 14 so should i throw out those opponent limit values also how can i modify this to take into account the variability of a real human opponent eg a real human is likely to stay on 15 just based on a feeling and may also hit on 18 based on a feeling,['ruby'] +48143,can i send a fax using php i have fax numbers and i would like to send a fax message to each of the numbers programaticallywhat is the code to send fax message using php,['php'] +48148,rails select helper adding style i am trying to do something like this select model attribute style somestyle add style to the select helper in rails but it is not working,['ruby-on-rails'] +48154,java how much logic to put in the main class how much logic do you normally put in the main class should logic in the main class be at minimum only instantiating other specialized classes and running all the tasks from thereif you have any suggestions on this topic or external articles i would appreciate it,['java'] +48157,extract method to already existing interface with resharper i am adding a new method to a class that implements an interface and i like to use the extract interface refactoring and just add the method to the interface but it does not seem like resharper supports adding a method signature to an already existing interfaceit feels like i am missing something i am sure it can be done somehow maybe i should add the method signature to the interface first but this is the way i am working sometimes am i missing some shortcut feature or using resharper wrong,['c#'] +48171,how to handle exceptions from a backgroundworker thread in a wpf app i have a sheduled database access task periodically run by a timer and this task have been executed in a backgroundworker threadwhen connection attempt failed i raise an exception by try catch construction and i want to update a status bar text in a ui thread is there some prebuild event construction in a backgroundworker for implementing this something like doworkeventhandler or runworkercompletedeventhandler which can be used for this if not how to do it betteredited addedif i want to handle the exception inside runworkercompletedeventhandler using eerror parameter it does not work in case i leave exception unhandled in the backgroundworker thread application hangs on and debugger points to the string of code which is excuted inside backgroundworker thread saying that exception was unhandled by user code so in this case thread does not just stop signalling to runworkercompletedeventhandler that it stopped with error but the whole application stop working,"['c#', '.net']" +48173,android a vertical gallery i am looking for a widget that behaves similar to the gallery widget but scrolls vertically instead of horizontally i googled all around and apparently the answer is no such premade widget existsso i said myself oh well i will look at the gallery class in the android source and modify that to scroll vertically instead not so easy the android sdk hides a lots away understandably for framework maintenance but it also makes it very hard to extend the widgets the gallery class for example use a lots of member variable from its parent absspinner mselectedposition etcetc and its parents parent etc which are not at all accessible from the appdevelopers standpoint without access to those member variable i cannot use similar code from gallery class for my own useshort of moving up the inheritance chain and put the source code of those parent classes all in my project or writing the widget all from scratch without using the existing framework widgets that already solved the problem i cannot find a way to get a vertical scrolling gallery is there a better way around why does the android framework make extending widget so difficult,['android'] +48187,why cannot the linker prevent the c static initialization order fiasco edit changed example below to one that actually demonstrates the siofi am trying to understand all of the subtleties of this problem because it seems to me to be a major hole in the language i have read that it cannot be prevented by the linker but why is this so it seems trivial to prevent in simple cases like this ahextern int x acppinclude cstdlibint x rand bcppinclude ahinclude iostreamint y xint main stdcout y prints the random value or garbagehere the linker should be able to easily determine that the initialization code for acpp should happen before bcpp in the linked executable because bcpp depends on a symbol defined in acpp and the linker obviously already has to resolve this referenceso why cannot this be generalized to all compilation units if the linker detects a circular dependency cannot it just fail the link with an error or perhaps a warning since it may be the programmers intent i suppose to define a global symbol in one compilation unit and initialize it in anotherdoes the standard levy any requirements on an implementation to ensure the proper initialization order in simple cases what is an example of a case where this would not be possiblei understand that an analogous situation can occur at global destruction time if the programmer does not carefully ensure that the dependencies during destruction are symmetrical to construction a similar problem occurs could the linker not warn about this scenario as well,['c++'] +48194,resizing an image in an html5 canvas i am trying to create a thumbnail image on the client side using javascript and a canvas element but when i shrink the image down it looks terrible it looks as if it was downsized in photoshop with the resampling set to nearest neighbor instead of bicubic i know its possible to get this to look right because this site can do it just fine using a canvas as well i have tried using the same code they do as shown in the source link but it still looks terrible is there something i am missing some setting that needs to be set or somethingediti am trying to resize a jpg i have tried resizing the same jpg on the linked site and in photoshop and it looks fine when downsizedhere is the relevant codereaderonloadend functione var img new image var ctx canvasgetcontext2d var canvascopy documentcreateelementcanvas var copycontext canvascopygetcontext2d imgonload function var ratio 1 ifimgwidth maxwidth ratio maxwidth imgwidth else ifimgheight maxheight ratio maxheight imgheight canvascopywidth imgwidth canvascopyheight imgheight copycontextdrawimageimg 0 0 canvaswidth imgwidth ratio canvasheight imgheight ratio ctxdrawimagecanvascopy 0 0 canvascopywidth canvascopyheight 0 0 canvaswidth canvasheight imgsrc readerresultedit2seems i was mistaken the linked website was not doing any better of a job of downsizing the image i tried the other methods suggested and none of them look any better this is what the different methods resulted inphotoshopcanvasimage with imagerendering optimizequality set and scaled with widthheightimage with imagerendering optimizequality set and scaled with moztransformcanvas resize on pixastici guess this means firefox is not using bicubic sampling like its supposed to i will just have to wait until they actually add itedit3original image,['javascript'] +48195,have you replaced makefiles with ruby scripts i appreciate makefiles and make in all their glory but i wonder if there is not a more intuitive way to maintain my cc buildshas anyone tried replacing their makefiles with ruby scripts to allow for complex and adaptive builds without sacrificing readability are there gems that make this easier,['ruby'] +48196,c program always crashes while doing a stdstring assign i have been trying to debug a crash in my application that crashes ie asserts a glibc detected free invalid pointer 0x070f0c0 while i am trying to do a simple assign to a string note that i am compiling on a linux system with gcc 424 with an optimization level set to o2 with o0 the application no longer crashesegstdstring abcabc teststringbut if i changed the code as follows it no longer crashes stdstring abcteststringso again i scratched my head but the interesting pattern was that the crash moved later on in the application again at another string i found it weird that the application was continuously crashing on a string assign a typical crash backtrace would look as follows0 0x07f2c2663bfb5 in raise from lib64libcso6gdb bt0 0x07f2c2663bfb5 in raise from lib64libcso61 0x07f2c2663dbc3 in abort from lib64libcso62 0x04d8cb7 in people streamingserver sighandler signum6 at srcpeoplestreamingservercpp4873 signal handler called4 0x07f2c2663bfb5 in raise from lib64libcso65 0x07f2c2663dbc3 in abort from lib64libcso66 0x07f2c26680ce0 in from lib64libcso67 0x07f2c270ca7a0 in stdstringassign this0x7f2c21bc8d20 strvalue optimized out at homebbazsothirdpartysourcesgcc424x86 64pclinuxgnulibstdcv3includebitsbasic stringh2388 0x07f2c21bd874a in peoplesprotocolgetstreamname thisvalue optimized out prawpath0x2342fd8 rtmp127001mp4popmp4 lstreamname0x7f2c21bc8d20 at opttrxheadgcc424libgccx86 64pclinuxgnu424includec424bitsbasic stringh4919 0x07f2c21bd9daa in peoplesprotocolsignalprotocolcreated pprotocol0x233a4e0 customparameters0x7f2c21bc8de0 at peoplestreamersrcpeoplesprotocolcpp240this was really weird behavior and so i started to poke around further in my application to see if there was some sort of memory corruption either heap or stack error that could be occurring that could be causing this weird behavior i even checked for ptr corruptions and came up empty handed in addition to visual inspection of the code i also tried the following toolsvalgrind using both memcheck and expptrcheckelectric fencelibsafei compiled with fstackprotectorall in gcci tried malloc check set to 2 i ran my code through lint checks as well as cppcheck to check for mistakesand i stepped through the code using gdbso i tried a lot of stuff and still came up empty handed so i was wondering if it could be something like a linker issue or a library issue of some sort that could be causing this problem are there any know issues with the stdstring that make is susceptible to crashing in o2 or maybe it has nothing to do with the optimization level but the only pattern that i can see thus far in my problem is that it always seems to crash on a string and so i was wondering if anyone knew of any issues that my be causing this type of behaviorthanks a lot,['c++'] +48217,jquery onclick pass post variables and reload page can i pass post variables and reload a page on clicking an hyperlinkto be clear i have something like this a hreftestphpnametestclickaif javascript is enabledi think i can use eventpreventdefault to suppress passing as get variable so now onclick name should be passed as post variable instead of getif javascript is thisabledthen the above should work,"['javascript', 'jquery']" +48220,how to delete object from array inside foreach loop i iterate through an array of objects and want to delete one of the objects based on it is id property but my code does not workforeacharray as element foreachelement as key value ifkey id value searched value delete this particular object from the array unsetelementthis does not work unsetarrayelementneither does this any suggestions thanks,['php'] +48224,can an object automatically delete itself in javascript once it has achieved its purpose i am wondering if it is possible for an object in javascript to delete itself once it has finished its taskfor example i have the following objectvar myobject objectcreatebaseobjectmyobjectinit function do some stuff delete thismyobjectinitdoes this work if not is there another way,['javascript'] +48228,summing the values of an array of hashes in ruby i am having trouble figuring out the elegant way to add an array of hashesa1b2c3a1b2c3a1b2c3should returna3b6c9i know it would probably involve mappingreducing but i cannot figure out the right syntax does not help that rubydoc dot org does not match my versioni am using 187,['ruby'] +48235,how to resize the original image into a common size of image in java in java how can i resize an image into a default size for any kind or size of image,['java'] +48237,efficiency arrays vs pointers memory access through pointers is said to be more efficient than memory access through an array i am learning c and the above is stated in kr specifically they sayany operation that can be achieved by array subscripting can also be done with pointers the pointer version will in general be fasteri thisassembled the following code using visual cmine is a 686 processor i have thisabled all optimizationsint a10 p a tempvoid foo temp a0 temp pto my surprise i see that memory access through a pointer takes 3 instructions to the two taken by memory access through an array below is the corresponding code 5 temp a0 mov eax dword ptr a mov dword ptr temp eax 6 temp p mov eax dword ptr p mov ecx dword ptr eax mov dword ptr temp ecxplease help me understand what am i missing hereas pointed out by many answers and comments i had used a compile time constant as the array index thus making it arguably easier for the access through an array below is the assembly code with a variable as the index i now have equal number of instructions for access through pointer and arrays my broader questions still holds good the memory access through a pointer is not lending itself as being more efficient 7 temp ai mov eax dword ptr i mov ecx dword ptr aeax4 mov dword ptr temp ecx 8 9 10 temp p mov eax dword ptr p mov ecx dword ptr eax mov dword ptr temp ecx,['c'] +48240,rails 3 can not find sqlite3ruby i am trying to learn rails3i tried folowing the installation guide from guidesrailsinfo i installedsudo gem install rake racktest rackmount erubis mailsudo gem install tzinfo builder i18n memcacheclientsudo gem install textformat thor and rails 3 via sudo gem install rails prenow i create a new apprails abcand try rake dbcreatewhich fails with could not find gem sqlite3ruby 0 runtime in any of the sourcesso i try installing sqlite3rubysudo gem install sqlite3rubywhich fails with could not create makefile due to some reason probably lack ofnecessary libraries andor headers check the mkmflog file for moredetails you may need configuration optionsso i install it via aptgetsudo aptitude install libsqlite3ruby18and still get same error on rake dbcreate,['ruby-on-rails'] +48247,java desktop application swt vs swing i am a web developer at day and thinking about building my first real desktop application the idea is to build a tool that automates a very repetitive task in a web application where no api is availablei know i want to use java i used it before for web stuff know the syntax pretty well and want the application to be cross plattform as easy as possible where i am not so sure is if i should use swt or swing as my main audience uses windows i want to look it as native as possible there linux and mac should work but the looks are not so important hereso what are the arguments for and against each ui framework swing or swtthanksps i develop on windows using eclipse but was thinking about playing with netbeans,['java'] +48248,jspjsf conversion to aspnet i have a pretty big jsf web application i must convert the application to aspnet i already converted the java code to c code manually and also using jcla java language conversion assistant from microsoftwhat is the best way to convert the jsf part to aspnet is there any tool that can help shorten the workfor example convert jsf tdatalist to aspnet datagrid or converting panelgroup to asppanel etc,['asp.net'] +48253,getting the day for current day in php i want to get the date for current date in php what i tried is hereecho xbrecho datedxbrbut the output was 210210thuit is giving correct date but not the correct day valuewhywhat i want day is the date for monday for the current week which can be generated on any day of the week so what i did was i am taking the todays day and comparing with montue sun and respectively creating a timestamp using case monstartdate1datedmyparts explodestartdate1startdate2 datedmymktime0parts1parts01parts2startdate3 datedmymktime0parts1parts02parts2startdate4 datedmymktime0parts1parts03parts2startdate5 datedmymktime0parts1parts04parts2 startdate6 datedmymktime0parts1parts05parts2startdate7 datedmymktime0parts1parts06parts2datesarray1 startdate1startdate2startdate3startdate4startdate5startdate6startdate7i1while i 7 echo datesiibreakdate is the final array respective to today that has to be returned is there any other better method to do this operation,['php'] +48263,django form validation making required conditional i am new to django and python and am trying to figure out how to conditionalize certain aspects of form validation in this case there is a html interface to the application where the user can choose a date and a time from widgets the clean method on the form object takes the values of the time and date fields and turns them back into a datetimein addition to the html interface there is also an iphone client making calls into the application and i would like to pass a unix timestampstyle time value inmy form code looks like thisclass fooformformsmodelform foo date formscharfieldrequiredtrue widgetformsradioselectchoicesdate choices foo time formscharfieldrequiredtrue widgetselecttimewidget foo timestamp formscharfieldrequiredfalsehow do i make foo date and foo time required unless foo timestamp is provided,['python'] +48265,operator does not behave like compilergenerated equals override for anonymous type according to the msdnbecause the equals and gethashcode methods on anonymous types are defined in terms of the equals and gethashcode of the properties two instances of the same anonymous type are equal only if all their properties are equalhowever the following code demonstrates the compiler generated implementation for equals is not behaving as expected datetime start new datetime200911 datetime end new datetime2010 1231 months since year 0 int startmonth startdateyear 12 startdatemonth 1 int endmonth enddateyear 12 enddatemonth 1 iterate through monthyear pairs for int i startmonth i endmonth i var yearmonth new year intmathtruncatei12d month i 12 1 if yearmonthyear 2009 yearmonthmonth 2 consolewritelineboom if yearmonth newyear 2009 month 2 consolewritelinei am never called consolewritelineyearmonth am i missing something i am looking at the generated msil but do not see an obvious error is there a way for msil level debugging besides windbg maybe am i overlooking something i have tested net 35 vs 2008 sp1 compiler for reference heres the generated equals methodpublic override bool equalsobject value var type value as f anonymoustype3yearj tpar monthj tpar return type null equalitycompareryearj tpardefaultequalsthisyeari field typeyeari field equalitycomparermonthj tpardefaultequalsthismonthi field typemonthi field,"['c#', '.net']" +48267,ruby changing the date part of a time instance i have a time instance curr time with the value of timenow and another string target date with the value say apr 17 2010 how do i get the date part in the variable curr time change to the value of target date curr time sun feb 21 233727 0530 2010 target date apr 17 2010i want curr time to change like this curr time sat apr 17 233727 0530 2010how to achieve this,['ruby'] +48268,is there a way to pause a cabasicanimation i have a basic spinning animation of the iphone is there any way that i can pause the animation so that the position of the view will be maintained i guess one way of doing this would be to cause the animation to complete instead of calling remove on it how would i do thatcabasicanimation rotationanimationrotationanimation cabasicanimation animationwithkeypathtransformrotationzrotationanimationtovalue nsnumber numberwithfloat m pi 2rotationanimationduration 100rotationanimationcumulative yesrotationanimationrepeatcount huge valfrotationanimationremovedoncompletion norotationanimationfillmode kcafillmodeforwardsmyviewlayer addanimationrotationanimation forkeyrotationanimation,['iphone'] +48270,paperclip and xhrsendasbinary i use paperclip to add a file to my modeli want to use the new feature of firefox 36 xhrsendasbinary to send a file with an ajax requesthere is how i build my request var xhr new xmlhttprequestxhropenpost photosauthenticity token token photoname imgname photosize imgsizexhroverridemimetypetextplain charsetxuserdefinedbinaryxhrsendasbinarybinname and size are saved in my model without problem but the file itself is not catched by paperclipmy modelclass photo activerecordbase has attached file photo styles medium 300x300 thumb 100x100 endthe migrationdef selfup add column photos photo file name string add column photos photo content type string add column photos photo file size integer add column photos photo updated at datetimeendand my controller post photos post photosxml def create photo photonewparamsphoto respond to do format if photosave formathtml redirect tophoto notice photo was successfully created formatxml render xml photo status created location photo else formathtml render action new formatxml render xml photoerrors status unprocessable entity end end endany idea how to solve this issuethanks,"['javascript', 'ruby-on-rails']" +48273,is there an alternative to html tidy i have embedded html tidy in my application to clean incoming html but tidy has a huge amount of bugs and fixing them directly in the source is my worst nightmare tidy source code is an unreadable abomination thousand line functions poor variable naming spaghetti code etc it is truly horribleworse yet official development seems to have ceased in the last 12 months there have been three write transactions to the official cvs repo but it is been dead and buried for much longer than thatso i am looking for an oss c or c applicationlibrary that can do what tidy can when it feels like it fix bad html markup and transform it into valid xhtml this is the part i am interested in and i mean all sorts of bad markupis there something like that out thereedit i need it both for manipulations on the dom tree by an xml handling tool and for general compliance with the xhtml spec my app needs to accept html from users which is often invalid in all sorts of ways and output valid xhtml it needs to be able to handle even html that would normally not thisplay in a browser because the user edited it by hand and did not check afterwardsa dropin replacement for tidys errorcorrecting parser that does not suck i do not mind bugs if the source is readable and i can fix problems myself or if there are active developers who provide bugfixes on a timely basis,"['c++', 'html', 'c']" +48277,iphone keyboard hides textfield i am using uitextfield to receive user inputs however since my textfields are towards the middlebottom of the nib it gets hidden when the keyboard pops up is there any way sort of slide it along with the keyboard so that it is on the top of the keyboard during selection also since i am also using the numberpad is there an easy way to include a done button somewherethanks for the help,['iphone'] +48279,pass array of structs from python to c update problem solved see bottom of the posti need to allow python developers to pass an array of packed data in this case vertices into my api which is a series of c interfaces exposed manually through the python c api my initial impression with this is to use the ctypes structure class to allow for an interface like thisclass vertexstructure fields x c float y c float z c float u c float v c float color c int verts vertex 3verts0 vertex00 05 00 00 05 0xff0ffverts1 vertex05 05 00 05 05 0x00ff00ffverts2 vertex05 05 00 05 05 0x0fdevicereadverticesverts 3 this is the interfaces to the c objectwhere the function i am trying to pass to has the following signaturevoid devicereadverticesvertex verts int countand the python wrapper looks something like thisstatic pyobject device readverticespy device self pyobject args pyobject py verts int count ifpyarg parsetupleargs oi py verts count return null this does not work vertex verts static castvertexpycobject asvoidptrpy verts selfdevicereadverticesverts count py return noneof course the biggest issue i have is this i can retrieve the pyobject for the struct but i have no idea how i would cast it to the correct type the above code fails miserably so how exactly would i go about allowing the user to pass me this kind of data from pythonnow a couple of things to consider first is that i already have quite a bit of my pythonc layer written and am perfectly happy with it i moved away from swig so i could have more flexibility i do not want to recode it so i would prefer a solution that works with the c api natively second i do intend to have the vertex structure be predefined in my c code so i would prefer to not have the user need to redefine it in the python cuts down on errors that way but i am not sure how to expose a contiguous structure like that third i have no reason for trying the ctypes structure aside from not knowing another way to do it any suggestions are welcome finally since this is as you may have guessed for a graphics app i would prefer a faster method over a convenient one even if the faster method takes a little bit more workthanks for any help i am still feeling my way around python extensions so it is a great help to get community input on some of the stickier partssolutionso first off thanks to everyone who pitched in their ideas it was a lot of little tidbits that added up to the eventual answer in the end here is what i found sams suggestion of using structpack ended up being right on the money seeing that i am using python 3 i had to tweak it ever so slightly but when all was said and done this actually got a triangle showing up on my screenverts bytesverts structpackfi 00 05 00 00 05 0xff0ffverts structpackfi 05 05 00 05 05 0x00ff00ffverts structpackfi 05 05 00 05 05 0x0fdevicereadverticesverts 3with my tuple parsing now looking like thisstatic pyobject device readverticespy device self pyobject args void py verts int len count ifpyarg parsetupleargs yi py verts len count return null works now vertex verts static castvertexpy verts selfdevicereadverticesverts count py return nonenote that even though i do not use the len variable in this example though i will in the final product i need to parse the tuple using y instead of just y or else it will stop at the first null according to the documentation also to be considered void casts like this are quite dangerous so please do loads more error checking than i show hereso job well done happy day pack up and go home yeswait not so fast there is morefeeling good about how that all worked out i decided on a whim to see if my previous attempt still blew up on me and reverted back to the first snippet of python in this post using the new c code of course and it worked the results were identical to the structpack version wow so this means your users have a choice in how they are going to provide this kind of data and your code can handle either with no changes personally i am going to encourage the ctypestructure method since i think it makes for easier readability but really it is whatever the user is comfortable with heck they could manually type out a string of bytes in hex if they wanted to it works i tried honestly i think this is the best possible outcome so i am ecstatic thank you all again and good luck to anyone else who runs into this problem,['python'] +48298,workaround for the mono privatefontcollectionaddfontfile bug when i call the privatefontcollectionaddfontfile method in mononet it always returns a standard fontfamily this bug has already been reported on several websites but as far as i know without a way to solve it the bug itself is not fixed in the monolibraries yet is there any workaround for itedit as a reaction on henchmans answer i will post the codeprivatefontcollection pfc new privatefontcollectionpfcaddfontfilemyfontfamilyttfmyfontfamily pfcfamilies0x00font myfont new fontmyfontfamily140fi know this code will work fine on the microsoftnet framework but when executing on mono it just gives a standard fontfamily i think it is arial with the name of myfontfamilyttf,['c#'] +48300,can c attributes access the target class i want to access the properties of a class from the attribute class by using reflection is it possiblefor exampleclass myattribute attribute private void accesstargetclass do some operations myattributeclass targetclass,['c#'] +48311,what can i use the hmvc architecture for the php framework i am using kohana recently implemented the hmvc architecture i have read that it is a layered mvc where requests are made on top of each other it is a bit like ajax just purely serverside i have applied it a bit on some experiments but i cannot apply it to any of my projects because i cannot find a need for it have you ever used hmvc in a project before how did it help you,['php'] +48314,why is binaryformatter trying to serialize an event on a serializable class i have a simple class that is marked as serializable and it happens to have an event i tried to mark the event member as nonserialized however the compiler complains yet when i go to serialize the class instance the binaryformatter throws an exception that the event is non serializable does that mean you cannot serialize classes that have events if so then the compiler should say so up frontstream file fileopenf filemodeopenbinaryformatter bf new binaryformatterobject obj nulltry obj bfdeserializefilecatch systemruntimeserializationserializationexception e messageboxshowdeserialization failed 0 emessagefileclosesystemcollectionsarraylist nodelist obj as systemcollectionsarraylistforeach treenode node in nodelist treeviewnodesaddnodefails to work on the following claserializableclass simple private int myint private string mystring public event someothereventdefinedelsewhere theevent,"['c#', '.net']" +48330,which one is the best facebox thickbox jquery ui dialog others which one is the best to use forimagesregular div contentajax loaded contentforms to post to server,['jquery'] +48344,threadexclusive data how to store and access is there a possibility in net to bind an object instance to a current execution context of a threadso that in any part of the code i could do something like currentthreadmyobjectdatadooperation and be sure that i access threadspecific datathanks,"['c#', '.net']" +48351,proper location to install android sdk on mac what is the best most proper location to install the android sdk on maci have seen in some posts that somewhere in the home directory is advantageous some seem to have placed the sdk in the applications directory,['android'] +48352,named parameters in jdbc are there named parameters in jdbc instead of positional ones like the name city in the adonet query belowselect from customers where namename and city city,['java'] +48358,how to write gui in python i would like to try to write a gui application in python i found out that there are a lot of ways to do it different toolkits and in this context i have several basic and i think simple questionis it in general a good idea to write a gui application in pythonwhat is the standard easiest and most stable way to create a gui applications in pythondoes anybody can give me a link to a simple hello world gui application written in python,['python'] +48363,jquery find closest previous sibling with class heres the rough html i get to work withli classpar catlili clasub catlili clasub catlili classpar catli this is the single element i need to selectli clasub catlili clasub catlili clasub cat current subli this is where i need to start searchingli classpar catlili clasub catlili classpar catlii need to traverse from the current sub find the closest previous par cat and do stuff to itfindlipar cat returns the whole load of par cat i have got about 30 on the page i need target the single onewould really appreciate any tips,"['jquery', 'html']" +48384,jquery concatenate values from two elements bit stuck try to achieve something in jquery and wondered if anyone can assisti am creating my own edit in place function where you click on an edit button and the content of my definition list gets swapped for a formprefilled with data similar to thisall is fine apart from each editable section user comments is tagged and can have multiple tags much like here on stackoverflowso my html to output the tag for each comment is as so dl idcomment id dt classcomment titleigetstitleadt other info dd classcategories dl dttagsdt cfloop arrayigetcategory indexii dd classcategorya hrefiigetscategoryadd cfloop dl ddso i nest my categories or tags in an a definition list controlled by a loop what i have tried to do so far is grab the content of these catergories using jquery so that when you click to edit the category form field will be prefilled with the existing tags for that commenteditclickfunction grab the text for all categories var scategory thisparentsdlfindcategories dl ddcategorytext build a form and prefill the category form field with the scategory variable form other data to build form form dlinput namescategory typetext value scategory dl show edit form prefilled with appropriate content dlcomment idformthis works but it thisplays all the categories for that entry next to each other with no spaceseg jquerycoldfusionvalidation was wondering how to thisplay it as so jquerycoldfusionvalidationim guessing the each function is required here but a bit stuck on how to implementmany thanks,['jquery'] +48397,getting a machines external ip address looking for a better way to get a machines current external ip below works but would rather not rely on an outside site to gather the information i am restricted to using standard python 251 libraries bundled with mac os x 105ximport osimport urllib2def check in fqn osuname1 ext ip urllib2urlopenread print asset s fqn checking in from ip s ext ip,['python'] +48414,efficiently traverse directory tree with opendir readdir and closedir the c routines opendir readdir and closedir provide a way for me to traverse a directory structure however each dirent structure returned by readdir does not seem to provide a useful way for me to obtain the set of pointers to dir that i would need to recurse into the directory subdirectoriesof course they give me the name of the files so i could either append that name to the directory path and stat and opendir them or i could change the current working directory of the process via chdir and roll it back via chdirthe problem with the first approach is that if the length of the directory path is great enough then the cost to pass a string containing it to opendir will overweight the cost of opening a directory if you are a bit more theoretical you could say your complexity could increase beyond linear time in the total character count of the relative filenames in the directory treealso the second approach has a problem since each process has a single current working directory all but one thread will have to block in a multithreaded application also i do not know if the current working directory is just a mere convenience ie the relative path will be appended to it prior to a filesystem query if it is this approach will be inefficient tooi am accepting alternatives to these functions so how is it one can traverse a unix directory tree efficiently linear time in the total character count of the files under it,['c'] +48417,should i implement ithisposable for a user control i am creating a net user control do i need to implement the ithisposable interface for my user control,"['c#', '.net']" +48420,window icon of exe in pyqt4 i have a small program in pyqt4 and i want to compile the program into an exe i am using py2exe to do that i can successfully set icon in the windows title bar using the following code but when i compile it into exe the icon is lost and i see the default windows application here is my programimport sysfrom pyqt4 import qtguiclass iconqtguiqwidget def init self parentnone qtguiqwidget init self parent selfsetgeometry300 300 250 150 selfsetwindowtitleicon selfsetwindowiconqtguiqiconcpython26 repy26iconsiqor1icoapp qtguiqapplicationsysargvicon iconiconshowsysexitappexec here is the setuppy for py2exefrom thistutilscore import setupimport py2exesetupwindowsscripticonqtpy icon resources 1 iqor1ico optionspy2exeincludessip pyqt4qtcore,['python'] +48428,ansic grammar array declarations like et alii the ansi c grammar from link give me the following rules for array declarations 1 direct declarator type qualifier list assignment expression 2 direct declarator type qualifier list 3 direct declarator assignment expression 4 direct declarator static type qualifier list assignment expression 5 direct declarator type qualifier list static assignment expression 6 direct declarator type qualifier list 7 direct declarator 8 direct declarator now i have a some questions about thesecan i use 1 6 except 3 only in c99what are 4 and 5 for the keyword static confuses mewhere to use 6whats the difference between the following two function prototypesvoid fooint andvoid fooint thank you,['c'] +48440,correct idiom for stdstring constants i have a map that represents a db object i want to get well known values from it stdmapstdstring stdstring dbo stdstring val mapfooall fine but it strikes me that foo is being converted to a temporary string on every call surely it would be better to have a constant stdstring of course its probably a tiny overhead compared to the thisk io that just fetched the object but its still a valid question i think so what is the correct idiom for stdstring constantsfor example i can have const stdstring foo fooin a hdr but then i get multiple copiesedit no answer yet has said how to declare stdstring constants ignore the whole map stl etc issue a lot of code is heavily stdstring oriented mine certainly is and it is natural to want constants for them without paying over and over for the memory allocationedit2 took out secondary question answered by pdf from manuel added example of bad idiomedit3 summary of answers note that i have not included those that suggested creating a new string class i am thisappointed becuase i hoped there was a simple thing that would work in header file only like const char const anywaya from mark b stdmapint stdstring dict const int foo idx 1 dictfoo idx foo stdstring val dbodictfoo idxb from vlad strh extern const stdstring foo strcpp const stdstring foo fooc from roger p really you cant do itb seems the closest to what i wanted but has one fatal flaw i cannot have static module level code that uses these strings since they might not have been constructed yet i thought about a and in fact use a similar trick when serializing the object send the index rather than the string but it seemed a lot of plumbing for a general purpose solution so sadly c wins there is not simple const idiom for stdstring,['c++'] +48447,find out divs height and setting div height i am quite new to javascriptjquery stuff but i would like to do this kind of thing with iti have four divs sidebyside like this and content in each one now if one has more content it gets stretched higher i would like to make the other divs as high too even if they do not have as much content so basically i want the script goes through the divs and check the heights and sets all of divs heights to same as the highest div has hopefully you understand,"['javascript', 'jquery', 'css']" +48448,c how to create a nondetectable infinite loop this is just an i am curious questionin cindepth jon skeet says about lambda expressionsif there is a nonvoid return type every code path has to return a compatible value page 233the footnote then sayscode paths throwing exceptions do not need to return a value of course and neither do detectable infinite loops page 233i am wondering what constitutes a nondetectable infinite loopcan this be done by only logic or it is done by using external factors like a database or file system,['c#'] +48457,should i include the when using sqlcommandparametersaddwithvalue i have always included the at sign in the parameter name when using addwithvalue but i just noticed some code written by someone else that does not use it is one way more correct than the othercmdparametersaddwithvalueixcustomer ixcustomerorcmdparametersaddwithvalueixcustomer ixcustomer,"['c#', '.net']" +48459,is it possible to retrieve the last modified date of a file using javascript i have a set of links on a web page that link to pdf forms and doc forms these files are not stored in a database simply stored as they are locally on the server is it possible to retrieve the last modified date of a pdf or doc file using javascript i do not have any specific need to use javascript but it is preferableupdate now that i realize that javascript cannot access the filesystem is there an alternative method,['javascript'] +48460,ajax check if a string is json my javascript sometimes crashes on this linevar json eval thisresponsetext crashes are caused when the argument of eval is not json is there any way to check if the string is json before making this calli do not want to use a framework is there any way to make this work using just eval there is a good reason i promise,['javascript'] +48490,aspnet ajax toolkit asyncfileupload the file is attached is invalid error i am trying to use the asyncfileupload control from the aspnet ajax control toolkit sept 30 2009 stable build 30930 i have created a demo application and the control works fine files upload and all is well when i try to use the control in my real application i am always receiving an error stating the file attached is invalid the asyncfileupload control returns this when the file uploaded is null to isolate the problem i created a new master page exactly like the master page in my demo app i also created an aspx page exactly like the page in my demo app the upload still fails with a the file attached is invalid errori also compared the webconfig for the real app and the demo app and could not identify any differences that should matterthe code below is the test code in my real app this code is exactly the same as the functioning code in the demo app with the exception of having different class names and file names the webconfig listed below is from the real app with the appsettings and connectionstrings removedat this point i am completely stumped real app test master page master languagec autoeventwireuptrue codefileamasterpagemastercs inheritsl1adminamasterpage doctype html public w3cdtd xhtml 10 transitionalen html xmlnshead runatserver titleuntitled pagetitle script typetextjavascript srcjsjquery132minjsscript aspcontentplaceholder idhead runatserver aspcontentplaceholderheadbody form idform1 runatserver aspscriptmanager idscriptmanager enablepartialrenderingtrue runatserver asyncpostbacktimeout180 div aspcontentplaceholder idcontent runatserver aspcontentplaceholder div formbodyhtmltest page page languagec masterpagefileamasterpagemaster autoeventwireuptrue codefileafileuploadtest2aspxcs inheritsafileuploadtest2 titleuntitled page register assemblyajaxcontroltoolkit namespaceajaxcontroltoolkit tagprefixajax aspcontent idcontent1 contentplaceholderidhead runatserver script typetextjavascript function pageloadsender args function startuploadsenderargs uploadmessage phtml uploadmessagehide function uploadcompletesenderargs showuploadmessageargsget filename uploaded succesfully argsget length bytes function uploaderrorsender args showuploadmessagean error occurred during uploading argsget errormessage ff0 function showuploadmessagetext color uploadmessage phtmltextcsscolor color uploadmessageshow script aspcontent aspcontent idcontent2 contentplaceholderidcontent runatserver div iduploadmessageppdiv ajaxasyncfileupload idpagebannerupload cssclassfile upload onclientuploaderroruploaderror onclientuploadstartedstartupload onclientuploadcompleteuploadcomplete onuploadedcompleteupload uploadedcomplete runatserver aspcontentreal app test page code behindusing systemusing systemiousing systemcollectionsusing systemconfigurationusing systemdatausing systemlinqusing systemwebusing systemwebsecurityusing systemwebuiusing systemwebuihtmlcontrolsusing systemwebuiwebcontrolsusing systemwebuiwebcontrolswebpartsusing systemxmllinqpublic partial class afileuploadtest2 systemwebuipage protected void page loadobject sender eventargs e protected void upload uploadedcompleteobject sender ajaxcontroltoolkitasyncfileuploadeventargs e if pagebanneruploadhasfile string path mappath pathgetfilenameefilename pagebanneruploadsaveaspath real app test webconfigxml version10 note as an alternative to hand editing this file you can use the web admin tool to configure settings for your application use the websiteaspnet configuration option in visual studio a full list of settings and comments can be found in machineconfigcomments usually located in windowsmicrosoftnetframeworkv2xconfig configuration configsections sectiongroup namesystemwebextensions typesystemwebconfigurationsystemwebextensionssectiongroup systemwebextensions version3500 cultureneutral publickeytoken31bf3856ad364e35 sectiongroup namescripting typesystemwebconfigurationscriptingsectiongroup systemwebextensions version3500 cultureneutral publickeytoken31bf3856ad364e35 section namescriptresourcehandler typesystemwebconfigurationscriptingscriptresourcehandlersection systemwebextensions version3500 cultureneutral publickeytoken31bf3856ad364e35 requirepermissionfalse allowdefinitionmachinetoapplication sectiongroup namewebservices typesystemwebconfigurationscriptingwebservicessectiongroup systemwebextensions version3500 cultureneutral publickeytoken31bf3856ad364e35 section namejsonserialization typesystemwebconfigurationscriptingjsonserializationsection systemwebextensions version3500 cultureneutral publickeytoken31bf3856ad364e35 requirepermissionfalse allowdefinitioneverywhere section nameprofileservice typesystemwebconfigurationscriptingprofileservicesection systemwebextensions version3500 cultureneutral publickeytoken31bf3856ad364e35 requirepermissionfalse allowdefinitionmachinetoapplication section nameauthenticationservice typesystemwebconfigurationscriptingauthenticationservicesection systemwebextensions version3500 cultureneutral publickeytoken31bf3856ad364e35 requirepermissionfalse allowdefinitionmachinetoapplication section nameroleservice typesystemwebconfigurationscriptingroleservicesection systemwebextensions version3500 cultureneutral publickeytoken31bf3856ad364e35 requirepermissionfalse allowdefinitionmachinetoapplication sectiongroup sectiongroup sectiongroup configsections appsettings appsettings connectionstrings connectionstrings systemweb set compilation debugtrue to insert debugging symbols into the compiled page because this affects performance set this value to true only during development compilation debugtrue assemblies add assemblysystemcore version3500 cultureneutral publickeytokenb77a5c561934e089 add assemblysystemwebextensions version3500 cultureneutral publickeytoken31bf3856ad364e35 add assemblysystemxmllinq version3500 cultureneutral publickeytokenb77a5c561934e089 add assemblysystemdatadatasetextensions version3500 cultureneutral publickeytokenb77a5c561934e089 add assemblysystemtransactions version20 cultureneutral publickeytokenb77a5c561934e089 add assemblysystemdatalinq version3500 cultureneutral publickeytokenb77a5c561934e089 assemblies codesubdirectories add directorynamecscode add directorynamevbcode codesubdirectories compilation the authentication section enables configuration of the security authentication mode used by aspnet to identify an incoming user authentication modewindows the customerrors section enables configuration of what to do ifwhen an unhandled error occurs during the execution of a request specifically it enables developers to configure html error pages to be thisplayed in place of a error stack trace customerrors moderemoteonly defaultredirectgenericerrorpagehtm error statuscode403 redirectnoaccesshtm error statuscode404 redirectfilenotfoundhtm customerrors pages controls add tagprefixasp namespacesystemwebui assemblysystemwebextensions version3500 cultureneutral publickeytoken31bf3856ad364e35 add tagprefixasp namespacesystemwebuiwebcontrols assemblysystemwebextensions version3500 cultureneutral publickeytoken31bf3856ad364e35 add tagprefixannsa namespaceannsacontrols assemblyannsacontrols controls namespaces add namespacemicrosoftvisualbasic add namespacesystemdata add namespacesystemdrawing namespaces pages httphandlers remove verb pathasmx add verb pathasmx validatefalse typesystemwebscriptservicesscripthandlerfactory systemwebextensions version3500 cultureneutral publickeytoken31bf3856ad364e35 add verb path appserviceaxd validatefalse typesystemwebscriptservicesscripthandlerfactory systemwebextensions version3500 cultureneutral publickeytoken31bf3856ad364e35 add verbgethead pathscriptresourceaxd validatefalse typesystemwebhandlersscriptresourcehandler systemwebextensions version3500 cultureneutral publickeytoken31bf3856ad364e35 httphandlers httpmodules add namescriptmodule typesystemwebhandlersscriptmodule systemwebextensions version3500 cultureneutral publickeytoken31bf3856ad364e35 httpmodules identity impersonatetrue trace enabledfalse requestlimit10 pageoutputfalse tracemodesortbytime localonlytrue session state settings modeoffinprocstateserversqlserver by default aspnet uses cookies to identify which requests belong to a particular session if cookies are not available a session can be tracked by adding a session identifier to the url to thisable cookies set sessionstate cookielesstrue sessionstate modeinproc stateconnectionstringtcpip12700142424 sqlconnectionstringdata source127001user idsapassword cookielessfalse timeout20 globalization this section sets the globalization settings of the application xhtmlconformance modelegacy systemweb location pathpages systemweb xhtmlconformance modetransitionalxhtmlconformance systemweb location systemcodedom compilers compiler languageccscsharp extensioncs typemicrosoftcsharpcsharpcodeprovidersystem version20 cultureneutral publickeytokenb77a5c561934e089 warninglevel4 provideroption namecompilerversion valuev35 provideroption namewarnaserror valuefalse compiler compiler languagevbvbsvisualbasicvbscript extensionvb typemicrosoftvisualbasicvbcodeprovider system version20 cultureneutral publickeytokenb77a5c561934e089 warninglevel4 provideroption namecompilerversion valuev35 provideroption nameoptioninfer valuetrue provideroption namewarnaserror valuefalse compiler compilers systemcodedom systemwebserver validation validateintegratedmodeconfigurationfalse modules remove namescriptmodule add namescriptmodule preconditionmanagedhandler typesystemwebhandlersscriptmodule systemwebextensions version3500 cultureneutral publickeytoken31bf3856ad364e35 modules handlers remove namewebservicehandlerfactoryintegrated remove namescripthandlerfactory remove namescripthandlerfactoryappservices remove namescriptresource add namescripthandlerfactory verb pathasmx preconditionintegratedmode typesystemwebscriptservicesscripthandlerfactory systemwebextensions version3500 cultureneutral publickeytoken31bf3856ad364e35 add namescripthandlerfactoryappservices verb path appserviceaxd preconditionintegratedmode typesystemwebscriptservicesscripthandlerfactory systemwebextensions version3500 cultureneutral publickeytoken31bf3856ad364e35 add namescriptresource verbgethead pathscriptresourceaxd preconditionintegratedmode typesystemwebhandlersscriptresourcehandler systemwebextensions version3500 cultureneutral publickeytoken31bf3856ad364e35 handlers systemwebserver runtime assemblybinding xmlnsurnschemasmicrosoftcomasmv1 dependentassembly assemblyidentity namesystemwebextensions publickeytoken31bf3856ad364e35 bindingredirect oldversion101100 newversion3500 dependentassembly dependentassembly assemblyidentity namesystemwebextensionsdesign publickeytoken31bf3856ad364e35 bindingredirect oldversion101100 newversion3500 dependentassembly assemblybinding runtimeconfigurationedit i am no longer working for this company so i cannot test any new answers to see if they fix the problem,['asp.net'] +48507,jquery load google visualization api with ajax there is an issue that i cannot solve i have been looking a lot in the internet but found nothingi have this javascript that is used to do an ajax request by php when the request is done it calls a function that uses the google visualization api to draw an annotatedtimeline to present the data the script works great without ajax if i do everything inline it works great but when i try to do it with ajax it does not workthe error that i get is in the declaration of the data datatable in the google chrome developer tools i get a uncaught typeerror cannot read property datatable of undefinedwhen the script gets to the error everything on the page is cleared it just shows a blank pageso i do not know how to make it workdocumentreadyfunction get tier1tickets divtendencyaddclassloading ajax type post url gettier1ticketsphp data success functionhtml succesful load visualization api and send data googleloadvisualization 1 packages annotatedtimeline googlesetonloadcallbackdrawdatahtml function drawdataresponse divtendencyremoveclassloading data comes from php like csv ticket count for each daycsv dates for ticket countstotal number of days counted so it has to be split first by then by var dataarray responsesplit var datatickets dataarray0 var datadates dataarray1 var datacount dataarray2 the comma separation now splits the ticket counts and the dates var dataticketarray dataticketssplit var datadatesarray datadatessplit visualization data var data new googlevisualizationdatatable dataaddcolumndate date dataaddcolumnnumber tickets dataaddrowsdatacount var datesplit new array forvar i 0 i datacount i separating the data because must be entered as new dateymd datesplit datadatesarrayisplit datasetvaluei 0 new datedatesplit2datesplit1datesplit0 datasetvaluei 1 parseintdataticketarrayi var annotatedtimeline new googlevisualizationannotatedtimelinedocumentgetelementbyiddivtendency annotatedtimelinedrawdata thisplayannotations true,['jquery'] +48514,in python how do i loop through the dictionary and change the value if it equals something if the value is none i would like to change it to empty stringi start off like this but i forgetfor k v in mydictitems if v is none right,['python'] +48515,how do you force a java swt program to move itself to the foreground currently with swt i sometimes want a program to arbitrarily come to the foreground like an alarm clock mighttypically the following works jrubyshellsetminimizedfalseshellforceactivethis brings the shell to the front if it was minimizedcreating a new shell at any time also brings the new shell to the frontso far so good however if the shell is not minimized the above code just flashes blinks the apps icon in the taskbar well actually the first time you run it it brings it to the front after that it just blinks in the taskbar that is windows on linux it appears to only blink in the taskbar ubuntu defaultdoes anybody know of a cross platform way of getting the app to come to the front in swtit seems that no incantation of forceactive setactive setminimizedfalse setfocus forcefocus and setvisible can accomplish this thingi am pretty sure it is possible at least in windows as the e text editor does it well that is not swt but at least some other apps have been known to do iti am thinking maybe this is swt bug 192036many thanksrelatedhow to bring a window to the front opening a shellkeep window in foreground even if it loses focusbug 244597 cannot activate shell programatically on gtkneed to bring application to foreground on windowshow to bring a window to the front this swing example might be some type of clue too,['java'] +48517,jquery getting the text value of a table cell in the same row as a clicked element i click a link in a table cell i need to get the value of a specific cell within this same table rowtr td classonethistd td classtwothattd td classthreeheretd td classfoura hrefthereatdtrtr td classoneqwqwtd td classtwodfghtd td classthreeuitdtd classfoura hrefthereatdtri have a click handler attached to the link in the fourth cell that click handler calls a function that opens a modal window when a form in the modal is submitted i want to also pass the value of td classtwo from the row in which the link was clicked to this modal here is the function that sends the modal the problem area is getting the correct value for var somethingvar send function var name name val var something thisclosesttdsiblingstwotext version 1 does not work var something thisclosesttrsiblingstdtwotext version 2 also does not work var something thisattrclass version 3 just a test but also does not work ajax async false data name name somedata something type post url the url the problem is that i cannot get the correct value for something it should be the value of td classtwo in the same row as the clicked elementthe way this all comes together is click the target link that calls a method called send click send click does some validations and then calls send but the value for something is never populated is this because this is not what i am thinking it is hjelp,['jquery'] +48533,java override object equals method how do i override the equals method in the object classie i haveclass personneed to override herepublic boolean equals object obji want to convert the parameter obj to a type person but if i do person obj it would not work,['java'] +48538,what does the php syntax var1var2 mean what is the explanation for the following syntaxvar1var2 note the second,['php'] +48543,the algorithm to find the point of intersection of two 3d line segment finding the point of intersection for two 2d line segment is easy the formula is straight forward but finding the point of intersection for two 3d line segment is not i afraidwhat is the algorithm in c preferably that finds the point of intersection of two 3d line segmentsi found a c implementation here but i do not trust the solution because it makes preference of a certain plane look at the way perp is implemented under the implementation section it assumes a preference for z plane any generic algorithm must not assume any plane orientation or preferenceis there a better solution,['c#'] +48547,php files are downloaded by browser instead of processed by local dev server mamp everything was going great until i added addhandler applicationxhttpdphp5s php to the htaccess file in my local servers document root which i change frequently depending on the site i am working with since i did that when i visit httplocalhost8 my browser just downloads the indexphp and it is not processed at all just the raw code now i removed that line from the htaccess file but i am still having this problemi have found that if i add an alternative entry to my hosts file for 127001 the new entry behaves like localhost used to but if i add the line above to my htaccess it knocks out that new host as well i have tried reinstalling mamp and clearing its caches and all the temporary files i could find i surfed through apache is httpdconf file all to no availso to be clear httplocalhost8 is experiencing the above problem if i add a new entry to my hosts file for 127001 say goomba and the above line is not in the root htaccess and has never been for that hostaliaswhatever then i can access httpgoomba8 just fine but if i do add that line to the htaccess then i have to add yet another entry to my hosts file to get around it even if i remove that line from the the htaccess filei am fine with using a different 127001 alias host what is that called but it is bugging me that this is still brokenjust to be clear i am on mac os leopard but i am not using the built in apache setup but mamp,['php'] +48551,msvc dependencies vs references i have always used the visual studio dependencies option to ensure that for example when building my c projects any dependent lib or dll projects are also built however i keep hearing people mention references and wondered with vs 2010 on the horizon i should be changing how i do thisare there any benefits to using references to dependencies or is the former a net feature only i am currently using vs2008,['c++'] +48567,pip installing only the dependencies i have a script that creates a virtualenv installs thistribute and pip in it and then optionally clones a git reponow i have the project i will be working on installed but its dependencies are not installed how can i make pip install all the dependencies as if i have issued a pip install myappedit appareantly my question is a duplicate of this onenot exactly sure but pip install e seems to do what i want without too many extra stuff lying around i would prefer if my code was not linked from sitepackages though,['python'] +48577,setting global sql mode in mysql i am trying to set sql mode in mysql but it throws an errorcommand set global sql modeno backslash escapesstrict trans tableno auto create userno engine substitutionis this not the proper way to set multiple modeswhat are the advantages of setting session and global modes which is prefferedi have different users trying to update the database with different unc values and insted od setting the session mode to no backslash escapes i though it would make sense to et a gloabl mode for this does this make senseplease let me knowthanks,['mysql'] +48586,merging two images i need to merge two images bufferedimage in java it wouldnt be a problem if there was no transparency the base image already has some transparency i want to keep this as it is and apply a mask to it the second image this second image has no opaque pixels in fact it is almost completely transparent just has some less transparent pixels to give some sort of light effect like a reflex important detail i do not want to do this on screen with graphics i need to obtain a bufferedimage with the resultant merge can anyone help methanksdetails merge two images maintaining transparency this is what i need to donote this does not do what i need because it does not handle well with the two images having transparency it modifies first picture transparency,['java'] +48591,how to detect via java whether a particular process is running under windows well the title pretty much sums the question the only thing i found is thisbut i am not sure if thats the way to go,['java'] +48593,how to connent to a remote mysql database with java i am trying to create a jsf application using the eclipse ide i am using a remote mysql server as my database how do i connect to this remote database for creating tables and accessing them,"['java', 'mysql']" +48595,advice on change tracking in sql server 2008 my client is looking for a way to do a full audit trails full view of historical data on all tables on the applicationother than using the old fashioned way of having table copies or storing field name field value modified by modified on etc i was looking at using sql server 2008 change trackingfound a howto article on msdn on the samehas anyone used or done a poc sql server 2008 change tracking feature and found it to be worth italso if possible please specify what you wanted out of it and what you foundconcludedany tips on the same are welcomeeditits been a week still no answer,['sql'] +48597,how can i call wifi settings screen from my application using android normally i am getting wifi setting screen on the emulator by clicking on the settings wireless controls wifi settings i need to go directly to the wifi settings screen from my program when pressing on the wifi button which i have created contacts call logs we can handle by using intentsetdataandroidprovidercontacts is there any way to open settings sub menusmenu from an android program please give me advise or sample code on this,['android'] +48607,is no parentheses on a constructor with no arguments a language standard i was compiling a c program in cygwin using g and i had a class whose constructor had no arguments i had the linesmyclass myobjmyobjfunction1and when trying to compile it i got the messageerror request for member function1 in myobj which is of nonclass type myclass after a little research i found that the fix was to change that first line to myclass myobji could swear i have done empty constructor declarations with parentheses in c before is this probably a limitation of the compiler i am using or does the language standard really say do not use parentheses for a constructor without arguments,['c++'] +48608,activemq jms ping apache activemq 520my application listens to messages on three topics and sends messages on 2 topics when my application is webpinged i want to check if these topics are alive i would like to know if this is possible here are my observationsadvisory messages can be used for this but they send messages only when a producerconsumer joins this is not quite what i want i just want to check if i can send messages to outbound topics and can receive messages on the inbound topiccustom heartbeat solution i can make every producer send a heartbeat message say every 5 seconds and the listener to not process heartbeat messages but update a flagtimestamp that way i know the topic is up and runningis there a heartbeat kinda thingi inbuilt in the apache activemq or a ping for a topic i understand jms is not for monitoring but if i am a producer for a topic it will be good to know if i can produce on the topic with reasonable comfort level i also agree between a ping and a message the channel can go down and that is an acceptable failure for mei just want a health check systempage which can say yes topics are there and the activemq is running,['java'] +48612,mvc with jquery handling session expire how could i handle the session expire on a mvc application that has jquery ajax method calls on certain pages the issue is the followingwhen the client reaches the session timeout each of my controllers inherits a class that checks if the session is alive looking up on some stuff like the site session database session etc and redirects the client to a new page saying that the session expires but the case is different when i am using jquery ajax to call methods of the controllers on some button clicks cause it skips the validation of the inherited class and allows me to stay on the page but when the controller tries to end the execution of method obviously it throws net errors objects are not created as instance of objects session variables not found etc all because of the expired session that was not handled because of the asynchronic method callhow could i handle this behaviour and which is the best way to handle it trying as much as possible to not modify so much parts of the code of the applicationthanks in advancepd it might be useful to tell that i am using post from jquery,['jquery'] +48614,using php gettext extension vs php arrays in multilingual websites so far the only 2 good things that i have seen about using gettext instead of arrays is that i do not have to create the greeting subarray or whatever its called and i do not have to create a folder for the default languageare there other pros and cos of using gettext and php arrays for multilingual websitesusing gettextspanishmessagespo testphp3msgid hello worldmsgstr hola mundoindexphpphp echo hello world indexphplangspanishphp echo hello world turns to hola mundousing php arrayslangenphpphplang array greeting hello worldlangesphpphplang array greeting hola mundoindexphpphp echo langgreeting greeting turns to hello worldindexphplangspanishphp echo langgreeting greeting turns to hola mundoi first started with gettext but it was not supported in my shared free hosting zymic i did not want to use zend translate i found it too complicated to my simple task so i finally ended up using php define but later on someone told me i should use arrays,['php'] +48620,using sqlite with qt i am thinking of using sqlite as a backend db for a c applicatiojn i am writing i have read the relevant docs on both teh trolltech site and sqlite but the information seems a little thisjointed there is no simple snippet that shows a complete crud examplei want to write a set of helper functions to allow me to execute crud actions in sqlite easily from my appthe following smippet is pseudocode for the helper functions i envisage writing i would be grateful for suggestions on how to fill up the stub functions one thing that is particularly frustrating is that there is no clear mention in any of the docs on the relationship between a query and the database on which the query is being run thus suggesting some kind of default connectiontable in my application i need to be able to explicitly specify the database on which queries are run so it would be useful if any answers spell out how to explicitly specify the databasetable involved in a query or other database action for that mattermy pseudocode follows belowinclude boostshared ptrhhtypedef boostshared ptrqsqldatabase dbptrdbptr createconnectionconst qstring conn type qsqlite const qstring dbname memory dbptr db new qsqldatabaseqsqldatabase if dbget dbadatabaseconn type dbsetdatabasenamedbname if dbgetopen dbreset return dbbool runqueryconst qstring sql how does sqlite know which database to run this sql statement against how to iterate over the results of the run querybool runpreparedstmtqueryconst qstring query name const qstring params how does sqlite know which database to run this sql statement against how do i pass parameters say a comma delimited list to a prepared statement how to iterate over the results of the run querybool dobulkinsertwithtranconst qstring tablename const mydatarows rows how does sqlite know which database to run this sql statement against how to startcommitrollbackin case what i am asking is not clear i am asking what would be the correct wat to implement each of the above functions possibly with the exception of the first unless it can be bettered of courseeditclarified question by removing requirement to explicitly specify a table this is already done in the sql query i forgot thanks for pointing that out tom,['c++'] +48639,how do i set a cookie header with xmlhttprequest in javascript i am trying to set a cookie in a xss request using xmlhttprequesti found the xmlhttprequest specification and section 4625 does seem to suggest that setting cookie cookie2 and some other headers are not allowed but i was hoping there was a work aroundmy jquery code is below but the resulting query fails as the cookie is not setajax type post url url data soap inbox mail query datatype xml async false beforesend functionxhr var cookie credentialscookie consoleinfo adding cookie cookie xhrsetrequestheadercookie cookie success functiondata textstatus xmlhttprequest error functionxhr ajaxoptions thrownerror credentials null,['javascript'] +48641,in python whats a good pattern for thisabling certain code during unit tests in general i want to thisable as little code as possible and i want it to be explicit i do not want the code being tested to decide whether it is a test or not i want the test to tell that code hey btw i am running a unit test can you please not make your call to solr instead can you please stick what you would send to solr in this spot so i can check it i have my ideas but i do not like any of them i am hoping that there is a good pythonic way to do this,['python'] +48645,how can i determine the current exception in a catch block possible duplicatedetermining exception type after the exception is caught following up on this question i would like to print out the current exception in a catch block just for logging one answer there says that there is no standard way of doing this but i do not like taking no for an answer current exception is a function mentioned in various places on the web but apparently not wellsupported any thoughts on this after all even c has errnobecause it can be rethrown with a simple throw the exception object must be available somehowi am using msvs 90edit the conclusion seems to be that this is not possible,['c++'] +48646,forcing cache expiration from a javascript file i have an old version of a js file cached on users browsers with expiration set to 10 years since then i have learned how to set expires headers correctly on my web server i have made updates to the js file and i want my users to benefit from themis there any way my web server can force users browsers to clear the cache for this one file short of serving a differently named js filein the future if expires headers are not set correctly paranoia can my js file automatically expire itself and force a reload after say a day has passed since it was cachededit ideally i want to solve this problem without changing html markup on the page that hosts the script,['javascript'] +48660,applicationproductname equivalent in wpf i have a class library that is nested two layers under a main gui application within that nested class library i want to be able to access the main applications nameunder net 35 you could call applicationproductname to retrieve the value from the assemblycs file but i cannot identify an equivalent in wpf if i use reflection and getexecutingassembly then it returns the class libraries detailsthanks,['c#'] +48669,php proxy script for indirect browsing i am looking for a php script that i can install on my own server that allows indirect http browsing with my server as a proxy i want it to automatically convert all tags within document to redirect to my server as well so that once i am on a site i can still click through any of the links and see all imagesin the past i have used which is amazing and does exactly what i want but for my current purposes i need a php script that does that same or similar functioni was planning on spending time converting the above cgi proxy script to php but thought i would ask around before reinventing the wheel,['php'] +48672,eachcollection vs collectioneach both methods appear to produce the same results but i have been hardpressed to actually convince people that the second method works since it is apparently not commonly known create some datavar foo vals idfoo idbar a common method eachfoovals functionio alertthisid alternative lesserknown methodfoovalseachfunctionio alertthisid upon checking the source these two appear to be oneinthesame the second method followseach function callback args return jqueryeach this callback args this method demonstrably calls the more commonlyknown method meaning it is just as legitimate is this understanding correct or am i missing something herei have typically trusted this method since it did not cause me to deviate from standard practices with regards to selectors let us face it were trained to dopeachso it seems only natural to doobjeacham i mistaken,['jquery'] +48676,how do i layout my c program where should i put the h and cpp files currently i program in java and use maven quite a bit as so i have become accustom to the naming schemes and folder structures that i have used over the past 4 or 5 years as i have recently started to learn c i am realizing that i have no idea where to put all my files should i keep everything broken down by namespace or by what tier it is in where for example would i keep a series of files devoted to ui as apposed to files meant to help store dataare there any standards for this sort of thingclearly there is no definitive answer to this question i am simply looking for a good guide i do not want to start learning c by spending too much time worrying about how my files are laid out i would rather have some good models and just get to the coding,['c++'] +48681,is it possible to use cin with qt is it possible to use cin in qt i can use cout but cannot find examples of how to use cin within a qt console application,['c++'] +48689,android row becomes unclickable with button i have a listview where each row has a button in the row layout however this seems to make the row itself unclickable how can i make both the button and row clickable thanks,"['java', 'android']" +48703,how can i thisable the webbrowser message in python in my python program when i send the user to create a gmail account by use of the webbrowser module python thisplaysplease enter your gmail username created new window in existing browser sessionis there any way to get rid of created new window in existing browser session as it takes up the space where the user types in their gmail accountthe code for this is webbrowseropen gmail user raw inputplease enter your gmail username edit after trying out both of alex martellis suggestions the code is edit 2 i have decided just to tell users to go to the gmail registration page instead of actually sending them there as that is much simpler to do and results in no currentlyunsolvablebyme errors,['python'] +48704,how can i open an html file in the default browser from a java swing application my java swing application generates an html file and i want to open it with the default browser when it is generated and saved how can i do this,['java'] +48713,c editor and compiler preference for those of you that are quick to answer some questions with code snippets i must say that i have been beaten to the punch a few times because loading up visual studio file new project does take some time does anyone out there particularly for those that are contributing answers here have a good quick editor on windows that allows you to enter some c code compileit basically whats the fastest way of writing sample code for you,['c#'] +48715,python drawing on screen i am coding an application that needs to select an area of the screen i need to change the cursor to a cross and then draw a rectangle on the user selection the first thing i searched for is how to manipulate the cursor and i came across wxpython with wxpython i could easily do this on a frame with a panel the thing is that i would need the window to be transparent so the user can see his screen while is selecting the desired area but if i make the frame and the panel objects transparent everything gets buggyso i am open to any solution either using wxpython or not using it because i do not really know if i am using it righti am new to python and i am not a native english speaker so i am sorry if you cannot understand somethingthis is what i codedimport wxclass selectableframewxframe c1 none c2 none def init self parentnone id1 title wxframe init self parent id title sizewxthisplaysize stylewxtransparent window selfpanel wxpanelself sizeselfgetsize stylewxtransparent window selfpanelbindwxevt motion selfonmousemove selfpanelbindwxevt left down selfonmousedown selfpanelbindwxevt left up selfonmouseup selfpanelbindwxevt paint selfonpaint selfsetcursorwxstockcursorwxcursor cross def onmousemoveself event if eventdragging and eventleftisdown selfc2 eventgetposition selfrefresh def onmousedownself event selfc1 eventgetposition def onmouseupself event selfsetcursorwxstockcursorwxcursor arrow def onpaintself event if selfc1 is none or selfc2 is none return dc wxpaintdcselfpanel dcsetpenwxpenred 1 dcsetbrushwxbrushwxcolor0 0 0 wxtransparent dcdrawrectangleselfc1x selfc1y selfc2x selfc1x selfc2y selfc1y def printpositionself pos return strposx strposyclass myappwxapp def oninitself frame selectableframe frameshowtrue selfsettopwindowframe return trueapp myapp0appmainloop,['python'] +48726,java thread reuse i have always read that creating threads is expensivei also know that you cannot rerun a threadi see in the doc of executors classcreates a thread pool that creates new threads as needed but will reuse previously constructed threads when they are availablemind the word reusehow do thread pools reuse threads,['java'] +48727,is it better to filter a resultset using a where clause or using application code ok here is a simple abstraction of the problem2 variablesmale users and female users to store 2 groups of user ie male and female1 way is to use two queries to select them select from users where gender male and then store the result in male usersselect from users where gender female and then store the result in female usersanother way is to run only one queryselect from users and then loop over the result set to filter the male users in the programphp code snippet would be sth like thisresult mysql queryselect from userswhile rowmysql fetch assocresult null if rowgender male add to male users else if rowgender female add to female userswhich one is more efficient and considered as a better approachthis is just a simple illustration of the problem the real project may have lager tables to query and more filter optionsthanks in advance,"['php', 'sql', 'mysql']" +48731,stylethisplaynone doesnt work on option tags in chrome but it does in firefox anyone know why or a workaround ok heres some sample code that demonstrates the problemif i click the button in firefox the first option thisappearsif i click the button in chrome nothing happens or rather if i inspect the first option it does have the attribute stylethisplaynone but the option itself on the html page is not hiddenformselectoption1optionoption2optionoption3optionselectinput typebutton onclickdocumentgetelementsbytagnameoption0stylethisplaynone valuehide option 1formdoes anyone know why this doesnt work in chrome and does anyone know of a workaround,['javascript'] +48739,titanium vs the native tools i am still checking everything outi am wondering what the limitations are if we develop the app using titaniumwhat cannot be done using titanium for iphone and for androidwhat things can only be done using only the the native toolsi heard that performance could be an issue how bad is this going to bethank you in advance,"['iphone', 'android']" +48747,are ilists passed by value passing value type parameters to functions in c is by value unless you use the ref or out keyword on the parameter but does this also apply to reference types specifically i have a function that takes an ilistfoo will the list passed to my function be a copy of the list with copy of its contained objects or will modifications to the list also apply for the caller if so is there a clever way i can go about passing a copy public void somefunction ilistfoo list new listfoo listaddnew foo dosomethingwithcopyofthelistlist public void dosomethingwithcopyofthelistilistfoo list do something,['c#'] +48761,c increase heap size is it possible i have an out of memory exception using c when reading in a massive filei need to change the code but for the time being can i increase the heap size like i would in java as a shaort term fix,['c#'] +48764,default net runtime version i have a few net versions under cwindowsmicrosoftnetframeworkwhat system variable controls what gets run by default,['.net'] +48766,sorting files by creationmodification date in php possible duplicatefile creation time in php how to retrieve the files contained into a folder sorted by creation date or any other sorting mechanismaccording to the doc the readdir functionthe filenames are returned in the order in which they are stored by the filesystem,['php'] +48767,draw polygon using mouse on google maps i need to draw polygon using mouse and mark a particular area on google maps the purpose is to mark an area on google maps and then showing hotels and attractions on that area the user will mark the hotels on google map while creating them so the db will have their latitude and longitudes how can i draw the polygon and fill it with a color as background to mark the area in google maps i have read the api manual ahow to draw polygonsa basically you would need to mark multiple points and then combine them into a polygon but i will need to do this using mouse drag just like drawing a shape kindly help me out how to achieve this,['javascript'] +48772,how to set the tab bar item 1 to be selected by default in iphone i am new to iphone developmenti am creating a view based applicationi have added a tab bar in my viewand not a tab bar controllerby setting the tag vale of the tab bar item to 1 2 i have loaded the view for each tab bar on tabbar item click eventi want the tab bar 1 to be selected by defaultwhat should i do for thathere is my code voidtabbaruitabbar tabbar didselectitemuitabbaritem item nslogdidselectitem d itemtag self activatetabitemtag voidactivatetabintindex switch index case 1 selftab1viewcontroller tab1 alloc initwithnibnametab1 bundlenil selfview insertsubviewtab1viewcontrollerview belowsubviewtabbar1 if currentviewcontroller nil currentviewcontrollerview removefromsuperview currentviewcontroller tab1viewcontroller break case 2 selftab2viewcontroller tab2 alloc initwithnibnametab2 bundlenil selfview insertsubviewtab2viewcontrollerview belowsubviewtabbar1 if currentviewcontroller nil currentviewcontrollerview removefromsuperview currentviewcontroller tab2viewcontroller break default breaki added the the tab bar in interface buildercan i do any thing in interface builderplease help me outthanks,['iphone'] +48776,h1h6 font sizes in html in html and in typography in general i suppose there appears to be some defined sizes for h1h6 elementsie if the baseline font size is 16px or 100 then h1 wcould be 225em 36pxand h2 wcould be 15em 24px et ceterawhere do these variables come from the h136px h224px h321px h418px h516px h614px that is or if you like h12em h215em h3117em etc the point is not the numbers themselves but the relation between themis there some mathematical formula for them does it have something to do with golden ratio or fibonacci i have not been able to find information on thisedit to be more specific what is the pattern why does it go from 36 to 24 to 21 or start from 36 to begin with or if you like from 2em to 15em to 117em etcoh i forgot to specify where i came up with the original numbers they are from here,['html'] +48792,can i ask vc linker to ignore unresolved externals i am trying to build a very complex opensource project with vc the project consists of dozens of libraries and one executable depending on those librariesfor some reasons vc linker does not want to see about 40 functions implemented in one of those libraries and reports unresolved external reference on each so i cannot link i do not want to waste time resolving the problem those functions are likely never calledi would like to just ask the linker to link what it sees and insert some reasonable error handling like reporting an error and terminating the program instead of missing functions how can i do that,['c++'] +48793,should there be a service layer in aspnet mvc should there be a service layer in aspnet mvc between controller and repository as repository is there for only data access some business logic is leaked into controller this might create a problem if the same operation is used by classic aspnet client as we have to duplicate the logic in controller,['asp.net'] +48811,oracle jdbc intermittent connection issue i am experiencing a very strange problemthis is a very simple use of jdbc connecting to an oracle databaseos ubuntujava version 150 16b02 160 17b04database oracle 11g release 1060when i make use of the jar fileojdbc14jar it connects to the database everytimewhen i make use of the jar fileojdbc5jar it connects some times and other times it throws an error shown belowif i recompile with java 6 and useojdbc6jar i get the same results as ojdbc5jari need specific features in jodb5jar that are not available in ojdbc14jarany ideaserror connecting to oracle javasqlsqlexception io exception connection reset at oraclejdbcdriversqlstatemappingnewsqlexceptionsqlstatemappingjava74 at oraclejdbcdriverdatabaseerrornewsqlexceptiondatabaseerrorjava110 at oraclejdbcdriverdatabaseerrorthrowsqlexceptiondatabaseerrorjava171 at oraclejdbcdriverdatabaseerrorthrowsqlexceptiondatabaseerrorjava227 at oraclejdbcdriverdatabaseerrorthrowsqlexceptiondatabaseerrorjava494 at oraclejdbcdrivert4cconnectionlogont4cconnectionjava411 at oraclejdbcdriverphysicalconnectioninitphysicalconnectionjava490 at oraclejdbcdrivert4cconnectioninitt4cconnectionjava202 at oraclejdbcdrivert4cdriverextensiongetconnectiont4cdriverextensionjava33 at oraclejdbcdriveroracledriverconnectoracledriverjava474 at javasqldrivermanagergetconnectiondrivermanagerjava525 at javasqldrivermanagergetconnectiondrivermanagerjava171 at testconnectmaintestconnectjava13codebelow is the code i am usingimport javaioimport javasqlpublic class testconnect public static void mainstring args try systemoutprintlnconnecting to oracle connection connull classfornameoraclejdbcdriveroracledriver condrivermanagergetconnection jdbcoraclethin17216481001535sample john 9090 systemoutprintlnconnected to oracle conclose systemoutprintlngoodbye catchexception e eprintstacktrace,['java'] +48822,equivalent of ruby enumerablecollect that returns an enumerable in this code i create an array of strings 1 to 10array of strings 110collect i stringidoes the ruby core api provide a way to get an enumerable object that lets me enumerate over the same list generating the string values on demand rather than generating an array of the stringsheres a further example which hopefully clarifies what i am trying to dodef find me an awesome username awesome names 110xform i hacker stringi awesome namesfind n not stackoverflowuserexistsn endwhere xform is the method i am looking forawesome names is an enumerable so xform is not creating a 1 million element array of strings but just generating and returning strings of the form hacker n on demandby the way heres what it might look like in cvar awesomenames from i in range1 10 select hacker ivar name awesomenamesfirstn stackoverflowuserexistsnone solutionhere is an extension to enumerator that adds an xform method it returns another enumerator which iterates over the values of the original enumerator with a transform applied to itclass enumerator def xformblock enumeratornew do yielder selfeach do val yielderyield blockcallval end end endend this prints out even numbers from 2 to 10110eachxform i i2each i puts i,['ruby'] +48824,ie8 getjson cached data simply one really ie8 is caching my data so it works first time but not afterwards i need to stop it using cached data when i call getjson ps im currently debuging my site in ie so expect lots of posts from me thanks for all that have helped so far truely are a great help,"['asp.net', 'javascript']" +48825,where does phpinfo get its info if you run a phpinfo does it show exactly what is in the phpini or if settings are changed on the fly via php with methods like ini set or via htaccess will they be shown in phpinfo,['php'] +48832,getting text data from c using jni through stdostream into java i have a class in c which takes an stdostream as an argument in order to continuously output text trace information i need to get this text over to the java side as efficiently as possible whats the best way to do this i was thinking of using a direct buffer but another method would be to take all the function calls across to java and do all the processing there but it seems that i would need a lot of jni callsif an example could be shown of the exact implementation method it would be very helpful or if some code exists already to do this perhaps part of another project another help would be to connect it up directly to a standard java streaming construct such that the entire implementation was completely transparent to the developeredit i found which seems to be a duplicate but not really of much help he did not seem to find the answer he was looking forcheerschris,['java'] +48833,how much leeway do i have to leave myself to learn a new language i am a relatively new hire and i am starting on a small fairly simple project the language that this project will be implemented in is still to be determined the question basically boils down to java or python heres the dilemma my manager would prefer it to be done in python i do not object to that but i have no experience in python i would really love to learn python and think i could manage it fairly quickly especially as it is a small project but the project is due at the end of march and must be ready by then so they would rather have it in java and on time than in python and late and they do not want to pressure me to do it in python if i think i cannot make it on timesorry about the background but my question basically is how long does it take on average to adapt to a new language i know this is subjective and personalized and depends on how fast the particular programmer is but talking about an average programmer or even a somewhat fast one that picks up things quickly what percentage of an increase does programming in a nonnative language but with similar concepts cause as in if this project would take me about 2 weeks in java or a net language how much longer can it take me in python can i assume that having double the amount of time ie a new unfamiliar language causes a 50 increase in programming time is adequateand included in this question from what i have heard it seems to be pretty easyintuitive to switch over from java to python is this truethanks everyone for all the answers i did not realize there are so many sides to this question i will try to choose an answer soon each response made me look at it a different way and it is hard to choose one answer,"['java', 'python']" +48837,choosing gems to work with aws suppose a service written with ror starts to use aws s3 to store some data what is the best library to use for working with aws s3 currently the main two alternatives for me arerightscale aws ruby gems awsawss3 what are their main advantages and thisadvantages what if later service will need to use other aws like ec2 what other gems do you use and whythanks,"['ruby-on-rails', 'ruby']" +48845,how can i detect if an android mapview has been panned or zoomed i am creating an android app that searches for items based on the visible area of the mapview is there a way to set up a listener on my mapview to detect when a map has been panned or zoomed,['android'] +48851,service has zero application noninfrastructure endpoints i recently created a wcf service dll and a service host exe i know my wcf service is working correctly since i am able to successfully add the service to wcftestclient however i seem to be running into an issue when i comes to utlizing my wcf from a service host exe i can add a reference to the wcf dll to my service host exe and create the necessary componets to the exe such as the service installer service host and the appconfig compile and then finally install the exe using installutil but when i tried to start the service in the microsoft management console the service immediately stops after being started so i began investigating what could exactly be causing this issue an came up with this error from the application log in the event viewer description service cannot be started systeminvalidoperationexception service service has zero application noninfrastructure endpoints this might be because no configuration file was found for your application or because no service element matching the service name could be found in the configuration file or because no endpoints were defined in the service elementthis error is actually generated in the onstart of my exe when i perform this call servicehostopen i have seen numerous posts where other individuals have run into this issue however most if not all of them claim that the service name or contract namespace and class name are not being specified i checked both of these entries in my config file in the exe as well as in the dll and they match up perfectly i have had other people in the office double check behind me to make sure i was not going blind at one point but of course they came to the same conclusion as me that everything looked like it was specified correctly i am truly at a lost as to what is going on at this point could anyone help me with this issue another thing that came up as a possible reason this may be happening is that the appconfig is never being read at least not the one i think should be getting read could this be the issue if so how can i go about addressing this issue again any help would be appreciated,['.net'] +48854,c constructors fun constructing foo with a copy of itself i haveclass fooclass bar foo foo bar foofoo bar barat this point isbarfoo how is this initializedthis question arose from a buggy refcounted pointer implemntation i could have sworn that i ensured each pointer was pointing at something nonnull but i ended up with a pointer that pointed at something null,['c++'] +48873,how to exit a child process exit vs exit consider this code snippetpid t cpid forkif cpid 1 perrorfork exitexit failureif cpid 0 in child execvpargv1 argv 1 perrorexecvp exitexit failure in parenthow shall i exit the child process if execvp returns shall i use exit or exit,['c'] +48891,c or c how to compare two strings given char pointers i am sorting my array of car two ways one by year which is shown below and another one by make make is a char how do i compare strings when i just have pointers to themint i jfori0 i100 i forj0 j100i j ifcararrayinull cararrayj null cararrayj1null ifcararrayiyear cararrayj1year swapcararrayj cararrayj1 the above method works for ints year how can i make it work for char pointers,"['c++', 'c']" +48894,common c idioms including coalesce operator everyone knows at least two common c idioms including coalesce operator a singleton onereturn staticfield staticfield new singletonconstructorand a chain onenotnullableresult nullable1 nullable2 nullable3 defaultsometypeit is readable consistent worth using and recognizable in code but unfortunately this is all sometimes it will need expanding or change sometimes i use them when i see a particular case and always i hesitate to use it because i dont know if any other programmer will really read it easy do you know any others i would love to have more specific usages eg aspnet ef linq anything where coalesce is not only acceptable but remarkable,['c#'] +48897,codeigniter pagination problem i am using codeigniter and its pagination class it works perfectly and it looks something like thisa first 1 2 3 4 5 last ahere is my codethisloadlibrarypaginationconfigbase url base urlcontrolpanelconfigfirst link firstconfigtotal rows countconfigper page 3 thispaginationinitializeconfig datapagination thispaginationcreate linksthisloadviewcontrolpanel datai have this in my routesroutecontrolpanelnum controlpanelindex1however whenever i get to a differentpage ie controlpanel3 the number 1 is always bold it should change to 2 or 3 etc why does not itwhen i change the configbase url to base urlcontrolpanelpage then does the pagination work correctly by boldening the correct number but the link 1 points to the url controlpanelpage which is the wrong page for me as the base is just controlpanelthanks all for any help,['php'] +48906,mysql invalid use of group function i am using mysql here is my schemasupplierssid integer sname string address stringpartspid integer pname string color stringcatalogsid integer pid integer cost realprimary keys are boldedi am trying to write a query to select all parts that are made by at least two suppliers find the pids of parts supplied by at least two different suppliersselect c1pid select the pidfrom catalog as c1 from the catalog tablewhere c1pid in where that pid is in the set select c2pid of pids from catalog as c2 from catalog where c2pid c1pid and countc2sid 2 where there are at least two corresponding sidsfirst off am i even going about this the right waysecondly i get this error 1 invalid use of group functionwhat am i doing wrong,"['mysql', 'sql']" +48914,how to render a partial from javascript i have a select that gets populated depending on the selection in a different selectto do this i did what is recommended in railscast 88 on dynamic select menusbut now i need to render a partial passing in the value selected in each of those selectsi cannot figure out how to simply trigger a method call from the onchange event in the select so i am thinking i need to call render partial from within the javascript handler that detects the selects change event but i cannot figure out how i tried the following in the javascript method in the jserb file but it does not work as hopedfunction staffselected date areashow render partial calendar anyone have a good solution,"['javascript', 'ruby-on-rails', 'ruby']" +48921,differences between how c and vb handle named parameters now that c supports named parameters i was checking to see if it was implemented the same way vb did it and found that there is a slight difference take for example a library function like thispublic static void foostring a string b consolewritelinestringformata 0 b 1 a bin c if you call it like thisfooa a b bthe compiler produces the following il instructionslocals init 0 string cs0 1 string cs01l 0 nop l 01 ldstr al 06 stloc0 l 07 ldstr bl 0c stloc1 l 0d ldloc0 l 0e ldloc1 l 0f call void testlibrarytestlibrarytestfoostring stringl 0014 nop l 0015 ret which translates to the following c codestring cs0 astring cs01 btestfoocs0 cs01in vb if you call it like thisfooaa bbthe compiler produces the following il instructionsl 0 nop l 01 ldstr al 06 ldstr bl 0b call void testlibrarytestlibrarytestfoostring stringl 0010 nop l 0011 nop l 0012 ret which translates to the following vb codefooa bthe way vb does it requires much fewer instruction calls so is there any advantage to the way c implements it if you do not use the named parameters c produces the same thing as vbedit now that weve determined that the extra instructions go away in release mode is there a particular reason for them to be present in debug mode vb acts the same in both modes and c does not insert the extra instructions when calling the method normally without named parameters including when you use optional parameters,"['c#', '.net']" +48949,null id in myentitytype entry do not flush the session after an exception occurs when trying to sesisongetall after an genericadoexception was catched i catch the genericadoexception with innerexceptionmessage unique key violation for telling the user that the login entered is already in useafter that i am trying to get some date sessioncreatecriteria i get this errornull id in myentitytype entry do not flush the session after an exception occurs,"['c#', '.net']" +48952,how to judge whether a timedate is today in ruby i have a settlement i want to judge if the return service date is today how to do thisthis is my code railsif settlementreturn service date settlementreturn service dateto sdate timenowto sdateis there a better way to do this,"['ruby-on-rails', 'ruby']" +48973,what can be the reasons of connection refused errors i am trying to write a server program in c using another client i get this error when i try to connect through port 2080 for exampleconnection refusedwhat can be the reasons of this error,['c'] +48977,lambda explanation and what it is as well as a good example can anyone give me a good explanation of how to use lambda and give a good example i have seen it but i dont know what it is or does,"['c#', '.net']" +48981,android schedule action to make some action for some time i found that there are several choicesuse alarmmanageruse scheduledexecutorserviceuse handlers method postdelayedwhat is big difference of all this what is the best practice of making schedule action,['android'] +48987,persistent smtp connection in phpmailer how to enable persistent smtp connections in phpmaileri will send many emails so with persistent connections probably i will get performance gain,['php'] +48988,why and when is cast to char volatile needed in boostdetailaddressof implf a series of reinterpret casts is done to obtain the actual address of the object in case class t has overloaded operatortemplateclass t struct addressof impl static inline t f t v long return reinterpret castt const castcharreinterpret castconst volatile charv whats the purpose of cast to const volatile char instead of just casting to char,['c++'] +48989,rails activerecord conditions is there a way to create a condition like thisproducts productfindall limit 5 conditions products locale en id not 1 tags name abi would like to list all products not including product 1thx,['ruby-on-rails'] +49008,reasons why you wouldnt use a foreign key php mysql i am working on an old web application my company uses to create surveys i looked at the database schema through the mysql command prompt and thought the tables looked pretty solid though i am not a db guru i am well versed in the theory behind it having taken a few database design courses in my software engineering programthat being said i dumped the create statements into an sql file and imported them in mysql workbench and saw that they make no use of any actual foreign keys they will store another tables primary key like you would with a fk but they do not declare it as oneso seeing how their db is designed the way i would through what i know minus the fk issue i am left wondering that maybe there is a reason behind it is this a case of lazy programming or could you get some performance gains by doing all the error check programmaticallyin case youd like an example they basically have surveys and a survey has a series of questions a question is part of a survey so it holds it is pk in a column that is pretty much it but they use it everywherei would appreciate any insight i understand that this question might not have a rightwrong answer but i am looking more for some information on why they would do this as this system has been pretty solid ever since we started using it so i am led to believe that these guys knew what they were doing,"['php', 'mysql']" +49011,submit button not focused even though tabindex is properly set i have defined tab index for the input fields in a form when tabbing through the input fields the submit button is never getting the focus some other input fields in a different form on the page gets the focus those are all having tab indexes higher than 3 how comeform actionsubscriptionphp namesubscribe methodpost onsubmitreturn isvalidemailandequalp idformlabelemailp input typetext nameemail1 tabindex1brp idformlabelrepeat emailp input typetext nameemail2 tabindex2 brinput idinputsubmit typesubmit valuesubscribe tabindex3formcssinput backgroundcolor 3 border 1px solid e color e marginbottom 6px margintop 4px padding 1px width 200pxinputsubmit backgroundcolor d7e6f1 border 1px solid e color 0ff marginbottom 6px margintop 4px padding 1px width 200pxinputsubmithover cursor pointer cursor hand backgroundcolor d7e6f1 border 1px solid 0ff color 0ff marginbottom 6px margintop 4px padding 1px width 200pxpformlabel width 100,['html'] +49019,visual c express 2010 and setting env variables solution wide i am c dev migrating to visual 2010 c from vimg here blog i have read that vc directories are no more and that i should use property pages in vs 2010 but i do not know how here is what i need to do i have w solution 50 projects strong and all of them use boost pthreads xercesc and few other libs i have env variables that point to those libs on my hard drive how can i tell vs to use them as additional include paths again it is 2010 version so no vs per solution setup available i do not want to set it manually in every project,['c++'] +49022,what is the scope of a defaulted parameter in python when you define a function in python with an array parameter what is the scope of that parameterthis example is taken from the python tutorialdef fa l lappenda return lprint f1print f2print f3prints11 21 2 3i am not quite sure if i understand whats happening here does this mean that the scope of the array is outside of the function why does the array remember its values from call to call coming from other languages i would expect this behavior only if the variable was static otherwise it seems it should be reset each time and actually when i tried the followingdef fa l lappenda return li got the behavior i expected the array was reset on each callso it seems to me that i just need the line def fa l explained what is the scope of the l variable,['python'] +49032,unable to instantiate function templates which uses decltype to deduce return type if called from inside a lambda i am trying to use c0x and in particular lambda expression and decltype to simplify some of my code using the msvc10 rc compileri have run into the following very odd problemtemplate typename fauto foof f decltypef return ftemplate typename fvoid barf f fint main bar foo error c2893 failed to specialize function template unknowntype foof as indicated in the comment the compiler generates an error on the line foo i hate to shout compiler bug but i really cannot see any good explanation for this errorapparently while inside the outer lambda expression the compiler can not specialize the foo function template for the inner lambdahowever if the definition of foo is changed to hardcode the return type like thistemplate typename fvoid foof f return fthen everything compiles just fineis there some obscure quirk of decltype when used to deduce the return type of lambda expression parameters inside the scope of another lambda that i am not aware of,['c++'] +49039,how do i output compressed css from compass how do i configure compass to output smaller or compressed css files i tried compass s compressed but that did not work,['css'] +49044,difference between const pointer and reference what is the difference between a constant pointer and a reference constant pointer as the name implies can not be bound again same is the case with the referencei wonder in what sort of scenarios would one be preferred over the other how different is their c standard and their implementationscheers,['c++'] +49064,transaction within transaction i want to know if open a transaction inside another is safe and encouragedi have a methoddef foo sessionbegin try stuffs except exception e sessionrollback raise e sessioncommitand a method that calls the first one inside a transactiondef bar stuffs try foo there it is stuffs except exception e sessionrollback raise e sessioncommitif i get and exception on the foo method all the operations will berolled back and everything else will work just finethanks,['python'] +49071,managing highly repetitive code and documentation in java highly repetitive code is generally a bad thing and there are design patterns that can help minimize this however sometimes it is simply inevitable due to the constraints of the language itself take the following example from javautilarrays assigns the specified long value to each element of the specified range of the specified array of longs the range to be filled extends from index ttfromindextt inclusive to index toindextt exclusive if ttfromindextoindextt the range to be filled is empty param a the array to be filled param fromindex the index of the first element inclusive to be filled with the specified value param toindex the index of the last element exclusive to be filled with the specified value param val the value to be stored in all elements of the array throws illegalargumentexception if ttfromindex gt toindextt throws arrayindexoutofboundsexception if ttfromindex lt 0tt or toindex gt alengthtt public static void filong a int fromindex int toindex long val rangecheckalength fromindex toindex for int ifromindex itoindex i ai valthe above snippet appears in the source code 8 times with very little variation in the documentationmethod signature but exactly the same method body one for each of the root array types int short char byte boolean double float and objecti believe that unless one resorts to reflection which is an entirely different subject in itself this repetition is inevitable i understand that as a utility class such high concentration of repetitive java code is highly atypical but even with the best practice repetition does happen refactoring does not always work because it is not always possible the obvious case is when the repetition is in the documentationobviously maintaining this source code is a nightmare a slight typo in the documentation or a minor bug in the implementation is multiplied by however many repetitions was made in fact the best example happens to involve this exact classgoogle research blog extra extra read all about it nearly all binary searches and mergesorts are broken by joshua bloch software engineerthe bug is a surprisingly subtle one occurring in what many thought to be just a simple and straightforward algorithm int mid low high 2 the bug int mid low high 1 the fixthe above line appears 11 times in the source codeso my questions arehow are these kinds of repetitive java codedocumentation handled in practice how are they developed maintained and testeddo you start with the original and make it as mature as possible and then copy and paste as necessary and hope you did not make a mistakeand if you did make a mistake in the original then just fix it everywhere unless youre comfortable with deleting the copies and repeating the whole replication processand you apply this same process for the testing code as wellwould java benefit from some sort of limiteduse source code preprocessing for this kind of thingperhaps sun has their own preprocessor to help write maintain document and test these kind of repetitive library codea comment requested another example so i pulled this one from google collections comgooglecommonbasepredicates lines 276310 andpredicate vs lines 312346 orpredicatethe source for these two classes are identical except forandpredicate vs orpredicate each appears 5 times in its classand vs or in the respective tostring methodsand vs or in the see javadoc commentstrue vs false in apply can be rewritten out of the expression1 all bits on vs 0 all bits off in hashcode vs in hashcode,['java'] +49078,ruby can i write multiline string with no concatenation is there a way to make this look a little betterconnexec select attr1 attr2 attr3 attr4 attr5 attr6 attr7 from table1 table2 table3 etc etc etc etc etc where etc etc etc etc etc etc etc etc etc etc etc etc etclike is there a way to imply concatenation,['ruby'] +49079,when should you use the this keyword in c possible duplicatesis excessive use of this in c a code smell years ago i got in the habit of using this when accessing member variables i knew it was not strictly necessary but i thought it was more clearthen at some point i started to prefer a more minimalistic style and stopped this practice recently i was asked by one of my more junior peers whether i thought it was a good idea and i found that i did not really have a good answer for my preference is this really a wholly stylistic choice or are there real reasons why not prefixing this on member variable accesses is better,['c++'] +49081,find html element nearest to position relative or absolute given absolute or relative position top left is there any way to get the nearest html element to these coordinatesor alternately is there any way to craft a selector or use some jquery construct to enumerate elements and then find which is closes to the provided coordinates assume that the set of elements is small and finite,"['javascript', 'jquery', 'html']" +49086,c calculate min date max date from a list i have a list which contains dates liststring stringdates 0 04032010 1 09032010 2 11032010 3 12032010 4 16032010 5 18032010 6 19032010 7 23032010 8 25032010 9 26032010using c what is the bestshortest way to find out min date max date from this list,['asp.net'] +49091,is there a java se sensor api does anyone know of a standardized java api for working with sensors and which is closely tied to java me as is the case with jsr 256i am writing a java library for interfacing with a sensor network consisting of several different types of sensors mostly simple stuff such as temperature humidity gps etcso far i have rolled my own interface and users have to write apps against this i would like to change this approach and implement a standard api so that implementations are not that closely tied to my libraryi have looked at jsr 256 but that really is not a great solution as it is for java me and my library is mostly used by android devices or laptops running the full java se,['java'] +49093,how do i automap namevaluecollection to a strongly typed class i have the configuration details of my application stored in a table like below settingname settingvalue postsperpage 10 emailerrors trueadminemailaddress my dataaccess class say returns a namevaluecollection keyvaluepair of settings stored in the table what would be best way to map the namevaluecollection keyvaluepair to a strongly typed class like the one below that has the properties named the same as in settingname column public class settings public int postsperpagegetset public bool emailerrorsgetset public string adminemailaddressgetset,['c#'] +49109,how to specify qt plugin constructor i wonder if it is possible to specify a constructor in a qt plugin interface extending an appi want to force the plugins using the interface to take a parameter in the constructor,['c++'] +49111,get int from string also containing letters in java how can i get the int value from a string such as 423e ie a string that contains a number but also maybe a letterintegerparseint fails since the string must be entirely a number,['java'] +49137,uitableview add content offset at top i need to add some blank space to the top of my uitableview that does not effect the size of the content area shifting the content down or adding a blank cell is not what i want to do instead i just want an offsetany idea,['iphone'] +49155,how to keep xmlserializer from killing newlines in strings suppose i have a simple class with just one member a string public class abc private string text public string text get return thistext set thistext value now when i serialize and then deserialize it with the questionable xmlserializer any text containing newlines rn or environmentnewline are transformed to nhow do i keep the newlines,"['c#', '.net']" +49165,difference between fflush and fsync i thought fsync does fflush internally so using fsync on a stream is ok but i am getting unexpected result when executed under network iomy code snippet file fp fopenfilewb multiple fputs call like fputsbuf fp fputsbufc str fp get fd of the file pointer fd filenofp ifndef win32 ret fsyncfd else ret commitfd fclosefp but it seems commit is not flushing the data i tried on windows and the data was written on linux exported filesystemwhen i changed the code as file fp fopenfilewb multiple fputs call like fputsbuf fp fputsbufc str fp fflush the data fflushfp fclosefp this time it flushes the datai am wondering if commit does the same thing as fflush any inputs,['c'] +49167,are there c equivalents for the protocol buffers delimited io functions in java i am trying to read write multiple protocol buffers messages from files in both c and java google suggests writing length prefixes before the messages but there is no way to do that by default that i could seehowever the java api in version 210 received a set of delimited io functions which apparently do that job parsedelimitedfrommergedelimitedfromwritedelimitedtoare there c equivalents and if not whats the wire format for the size prefixes the java api attaches so i can parse those messages in c,"['java', 'c++']" +49170,nunit conflict with debugassert i am using nunit to write unit tests for a libary a colleague of mine has written his library contains a lot of debugasserts which triggers on invalid input when i am writing the unit tests and give invalid input to his library his debugassert throws up a message box complaining about the bad inputi feel that it is a good thing that his library throws up an assert on invalid input but at the same time i want the unit tests to cover bad input but when i do this the message box shows up and i have to manually click ok to continue with the remaining unit testsin case it is not clear my problem is that the unit test process stops on the debugassert people are supposed to run their unit tests prior to any checkin and it is supposed to be automatic and should not throw up messages unless a test has failedwhats the best approach in this case,['c#'] +49172,stray 342 in c program i am getting these errors in my program after pasting in some codeshowdatacpp66 error stray a342a in programshowdatacpp66 error stray a200a in programshowdatacpp66 error stray a235a in programshowdatacpp66 error stray aa in programshowdatacpp66 error stray a342a in programshowdatacpp66 error stray a200a in programshowdatacpp66 error stray a235a in programshowdatacpp67 error stray a342a in programshowdatacpp67 error stray a200a in programshowdatacpp67 error stray a235a in programshowdatacpp67 error stray aa in programshowdatacpp67 error stray a342a in programshowdatacpp67 error stray a200a in programshowdatacpp67 error stray a235a in programhere are the two lines that are causing the errors size t startpos strfind first not ofa ta size t endpos strfind last not ofa ta how to fix this,['c++'] +49173,after i remove the apk whenever i start debug it tells me the package is not installed i have my emulator open and using command prompt i remove my application i did not closed the emulatorthen i go to eclipse and hit debug but does not deploy the apk to the emulator just tells me the package not yet registered with the systemnew package not yet registered with the system waiting 3 seconds before next attemptrestarting the emulator is not an option as that takes 1015 minutes what i am doing wrong,['android'] +49178,textwritertracelistener and trace filenames with guids i use textwritertracelistener systemdiagnostics in my application to trace several things like exceptionsthe application is running on a terminal server and if there are many users using it simultaneously the listener starts to create many tracefiles with random guids in the filename are there possibilities or workarounds to avoid this behaviour,['.net'] +49187,calculate mean and variance with one iteration i have an iterator of numbers for example a file objectf opendatafiledatnow i want to computemean get meanfsigma get sigmaf meanwhat is the best implementation suppose that the file is big and i would like to avoid to read it twice,['python'] +49192,highlighting long sentences using jquery i would like to highlight long sentences say 50 words or greater contained in an array of paragraph objects on a page ie content p i am not sure how to tackle thisi originally tried to highlight all sentences but ran in trouble when they contained html tags example highlighting code on the net seem to be for individual words only so they do not take child nodes into account i am aware that splitting sentences is difficult i would like to use followed either by a space then a capital letter or nothing at all ie the end of the paragraphthanks in advance for any helpadvice,['jquery'] +49193,safely removing datarow in foreach i do not understand why this code does not workforeach datarow datarow in datatablerows if true datarowdelete,['c#'] +49196,how to compare nullable types i have a few places where i need to compare 2 nullable values to see if they are the samei think there should be something in the framework to support this but cannot find anything so instead have the followingpublic static bool isdifferenttothis bool x bool y return xhasvalue yhasvalue true xhasvalue xvalue yvaluethen within code i have if xisdifferenttoy i then have similar methods for nullable ints nullable doubles etcis there not an easier way to see if two nullable types are the sameupdateturns out that the reason this method existed was because the code has been converted from vbnet where nothing nothing returns false compare to c where null null returns true the vbnet code should have used equals instead,['c#'] +49205,how to add more details in mkannotation in ios i want to add more details in mkannotation like location title description date location name so it will be four lines that are needed but i found that only 2 parameters can be passed to mkannotation which are title and subtitle how can i add more details on the map plz help methanks in advance,"['iphone', 'objective-c', 'ios']" +49209,difference between loggerinfo and loggerdebug what is the difference between loggerdebug and loggerinfo when will loggerdebug be printed,['java'] +49216,static member initialization for specialized template class class atemplate typename a int sclass bpublic static int as b a0 0 template int ba 1a1int main ba 1 t tit compiles under gcc 41 but does not linkstaticcpptext zn1bi1ali1eec1evba 1b0x5 undefined reference to ba 1ai would prefer to keep initialisation specialised if it is possible since the array holds some data specific to the type,['c++'] +49218,how to hide keyboard after typing in edittext in android i have a edittext and button aligned to parents bottomwhen i enter text in it and press the button to save data the virtual keyboard does not thisappearcan any one guide me how to hide the keyboard,['android'] +49237,how to write unit tests in plain c i have started to dig into the glib documentation and thiscovered that it also offers a unit testing frameworkbut how could you do unit tests in a procedural language or does it require to program oo in c,['c'] +49241,is there a way to automatically override tostring on a class i find it useful to override tostring on many of the simple dtopoco classes i write to show some good information when hovering over instances within the debugger here is one example public class idvalue t public idvalue int id t value id id value value public int id get private set public t value get private set public override string tostring return stringformat id 0 value 1 id value is there a way in net to automatically have a tostring override that lists out public properties or is there a good convention to follow,"['c#', '.net']" +49244,linkedlist remove an object is this a valid way to find and remove item from a linkedlist in java using a for each loop is it possible that inconsistency may ariseforobjecttype ob oblist ifobgetid id oblistremoveob break,['java'] +49255,how to do delphilike frames in c slight bit of background i am a delphi programmer relearning c learned in school originally have not hardly touched until recently and am trying to get some of my delphi concepts transferred over the current situation is i need to create an application that can use data from a variable list of similar data controls depending on location need etc and in order to thisplay that information in delphi i would simply use a scroll box and frames the scroll box i can easily replace with the c panel class but i am not finding anything i can use that will tell me how to create my frame class for use inside the panel all i can find is some stuff for web developmentcan anyone point me in a good direction for learning the c frame equivalent thankseditfor nondelphi programmers a frame is a formlike control that allows other controls buttons boxes grids etc to be placed on it then the frame gets used as a control itself on a form to reduce codereuse as all frames do similar functionality and streamline development for a probably better more indepth description see aboutcoms or delphi basics descriptions,['c#'] +49258,iphone sdk how to record voices with ambient noise supression can anyone point me in the right direction on how i would minimize ambient noise while recording someone speaking using the iphone sdk core audio i am guessing a bandpass filter that eliminates any frequencies above and below the human vocal range might work i have no idea how i would implement band filters on audio in the sdk though the optimum solution would be one that eliminates the noise from the stream before it is written to memorythisk some sample code would be appreciated,['iphone'] +49261,what is relation between gc finalize and thispose gc is for managed objects and finalize is for unmanaged objects thats what i have been reading thispose is implicit and finalize is explicit is what i have been reading can somebody give me one example of one module in which all three thing have been used for different reasons,"['c#', '.net']" +49262,comparing strings with tolerance i am looking for a way to compare a string with an array of strings doing an exact search is quite easy of course but i want my program to tolerate spelling mistakes missing parts of the string and so onis there some kind of framework which can perform such a search i am having something in mind that the search algorithm will return a few results order by the percentage of match or something like this,"['c#', '.net']" +49263,algorithm to add or subtract days from a date i am trying to write a date class in an attempt to learn ci am trying to find an algorithm to add or subtract days to a date where day starts from 1 and month starts from 1 it is proving to be very complex and google does not turn up muchdoes anyone know of an algorithm which does this,['c++'] +49265,how do i transform rows into columns in sql server 2005 there is a question here in stackoverflow with the same title but that is not what i am looking fori have a table like the one below name count chery 257 drew 1500morgon 13 kath 500 kirk 200 matt 76 i need to trasform this result set into something like this chery drew morgon kath kirk matt 257 1500 13 500 200 76how do i acheive this using sql server 2005,['sql'] +49280,extra generic parameter in generic extension methods i would like make an extension method for the generic class a which takes yet another generictype in this example tc but i guess that aint possible class program static void mainstring args var a new ab b adoitb static class ext public static ata tb doitta tb tcthis ata tb a return a class ata tb class b,['c#'] +49288,why is post save being raised twice during the save of a django model i am attaching a method to the post save signal of my django model this way i can clear some cached items whenever the model is modified the problem i am having is that the signal is being triggered twice when the model is saved it does not necessarily hurt anything the code will just gracefully error out but it cannot be righta quick example just printing the model to the console using the dev serverfrom blogmodels import postfrom djangodbmodels import signalsdef purge cachesender kwargs print purging s sendersignalspost saveconnectpurge cache senderpostthis is using the stable 1 release of djangoupdated informationwith feedback from everyones comments i have modified my question because the issue is now thiscovering why the post save is being triggered twice my guess at the moment is that my modelspy code is imported twice and that the post save is getting connected multiple timeswhat would be the best way to figure out why it is being importedran twice,['python'] +49294,alternative to allow service to interact with desktop i have a windows service c installed on a server that launches every 10 minutes an executable file c to process some images from one directory to another no interaction is required with any user nevertheless since the executable file as an output window to make the service run i have to enable the allow service to interact with desktop checkbox which is considered as an insecure and bad practice how would i go about this problem i like to have the executable separated from my windows service becauseit makes it easier to debug anddoes not require a full windows service redeploysometimes i use the same windowsservice to launch severalexecutable files at differentintervals but all related to the sameprojecteditwhen the interaction with the desktop is not enabled the console application does not get executed correctly and the following error appears inside the windows logsfaulting application myappexe version 10 time stamp 0x4b8304c3 faulting module kernel32dll version 60600218005 time stamp 0x49e03821 exception code 0xc0142 fault offset 0x09eed process id 0x10ec application start time 0x01cab736950a64b5once the desktop interaction is enabled application gets executed normallyany thoughts thanks a lot for your time,['c#'] +49297,php domdocument get html source of body i am using phps domdocument to parse and normalize usersubmitted html using the loadhtml method to parse the content then getting a wellformed result via savehtmldom new domdocumentdomloadhtmldivphello worldwell formed domsavehtml echowell formedthis does a beautiful job of parsing the fragment and adding the appropriate closing tags the problem is that i am also getting a bunch of tags i do not want such as doctype html head and body i understand that every wellformed html document needs these tags but the html fragment i am normalizing is going to be inserted into an existing valid document,"['php', 'html']" +49310,calling lua function without executing script i am embedding lua into a cc application is there any way to call a lua function from cc without executing the entire script first i have tried doing thiscall lua script from cc programlual loadfilelhelloluacall lua function from cc programlua getgloballbarlua cal00but it gives me thispanic unprotected error in call to lua api attempt to call a nil valuei can only call bar when i do thiscall lua script from cc programlual dofilelhellolua this executes the script once which i do not likecall lua function from cc programlua getgloballbarlua cal00but it gives me thishellostackoverflowi am wanting this stackoverflowthis is my lua scriptprinthellofunction bar printstackoverflowend,"['c++', 'c']" +49326,assemblyinfocs is there any point in specifying a guid when using comvisiblefalse when you create a new c project in visual studio the generated assemblyinfocs file includes an attribute specifying an assembly guid the comment above the attribute states that it is used if this project is exposed to comnone of my assemblies contain types which need to be visible to com so i have marked my assembly with assembly comvisiblefalse is there any point in specifying a guidmy feeling is that the answer is no so why does the default assemblyinfocs file contain both assembly comvisiblefalse and assembly guideditto summarize the responsesbetween them the answers explain that specifying a guid is required if and only if com interop is being used so in my situation a guid is not necessarysharptooth further explains that assembly comvisiblefalse does not imply not using com interop since it is possible to override comvisible for individual types it is for this reason that the default assembyinfocs contains both assembly comvisiblefalse and a guid,"['c#', '.net']" +49333,sql select speed int vs varchar i am in the process of creating a table and it made me wonderif i store say cars that has a make fx bmw audi ect will it make any difference on the query speed if i store the make as an int or varcharso isselect from table where make 5 and fasterslower thanselect from table where make audi and or will the speed be more or less the same,['sql'] +49338,html css how to create multiple column list i have an ordered list which contains about 100 list items this ol makes my page very long and users have to scroll too muchhow can i get the ul to show like this1 6 112 7 123 8 134 9 145 10 15,"['html', 'css']" +49344,when must we use extern alias keyword in c when must we use extern alias keyword in c,['c#'] +49354,how to use dataannotations errormessageresourcename with custom resource solution i am building a mvc web application with c since the site will be multilingual i have implemented my own resourcemanager this class is responsible for fetching the required resource strings from a databasecache depending on the currents thread culture and works fine so far my problem is i would like to use the my custom resourcemanager solution to fetch validation error messages when for example using the required attribute on a property can this be done,['c#'] +49355,c equivalent of the ruby symbol i am developing a little c application for the fun i love this language but something thisturb me is there any way to do a define c mode or a symbol ruby modethe ruby symbol is quite useful it is just some name preceded by a example guy every symbol is unique and can be use any where in the codein my case i would like to send a flag connect or thisconnect to a functionwhat is the most elegant c way to do that here is what i would like to do bgworkerrunworkersasyncconnectprivate void bgworker doworkobject sender doworkeventargs e if earguement connect do the jobat this point the my favorite answer is the enum solution,"['c#', 'ruby']" +49358,how do you clear console screen in c is there a proper way of clearing a screen in c for a console applicationbesides usingsystemcls,['c'] +49363,colors in c win32 console stdcout blblabla done stdendlis it possible to make done be in another color and possibly bold i am using windows 7,['c++'] +49370,uinavigationbar barbuttonitem with plain style i got the following code idinit if self super init selftitle please wait uibarbuttonitem favorite uibarbuttonitem alloc initwithimageuiimage imagenamedstarpng styleuibarbuttonitemstyleplain targetself actionselectorbuttonfavoriteclicked selfnavigationitemrightbarbuttonitem favorite return selfbut my button looks still like a button with uibarbuttonitemstyleborderedis there a way to set a button with plain style at this position,['iphone'] +49371,why does my irc bot not connect public static string server ircrizonnetprivate static int port 67private static string user test c irc botprivate static string nick testingprivate static string channel test0x40 public static void mainstring args networkstream stream tcpclient irc streamreader reader streamwriter writer irc new tcpclientserver port stream ircgetstream reader new streamreaderstream writer new streamwriterstream writerwritelinenick nick writerflush writerwritelinejoin channel writerflush consolereadkeytruewhy does my irc bot not connect,"['c#', '.net']" +49372,select and thisable each input field within a form wrapped in a table in jquery i am thisabling a form based on a checkboxi am having trouble adding the thisabled attributehere is what i got so farhtmltable idshipinfotable tr tdnametd tdinput typetext namename td tr tablejavascript selectorattribute manipulationjqueryshipinfotable tbody tr td inputeachfunctionindex item itemattrthisabled truechrome dev console erroruncaught typeerror object an htmlinputelement has no method attrwhen i alert out the item within the each it alerts object htmlinputelementnot quite sure how to select the input element properly what am i doing wrong,['jquery'] +49386,jquery minified uncompressed files i new with jquery and i can do simple coding with itand i want to know about these files more minified uncompressed and when i should use each one,['jquery'] +49399,simple expression parser example using boostspirit is anyone aware of an online resource where i can find out how to write a simple expression parser using boostspiriti do not necessarily need to evaluate the expression but i need to parse it and be able to return a boolean to indicate whether the expression is parsable or not eg brackets not matching etci need the parser to be able recognise function names eg foo and foobar so this would also be a useful example to help me learn writing bnf notationthe expressions will be normal arithmetic equations ie comprising of the following symbolsopeningclosing bracketsarithmetic operatorsrecognized function names and check for their required arguments,['c++'] +49402,c is there any way to easily findupdate all references to an object i have been reading rockford lhotkas expert c 2008 business objects where there is such a thing as a data portal which nicely abstracts where the data comes from when using the dataportalupdatethis which as you might guess persists this to the database an object is returned the persisted this with any changes the db made to it eg a timestamplhotka has written often and very casually that you have to make sure to update all references to the old object to the new returned object makes sense but is there an easy way to find all references to the old object and change them obviously the gc tracks references is it possible to tap into thatcheers,"['c#', '.net']" +49417,building an interleaved buffer for pyopengl and numpy i am trying to batch up a bunch of vertices and texture coords in an interleaved array before sending it to pyopengls glinterleavedarraysgldrawarrays the only problem is that i am unable to find a suitably fast enough way to append data into a numpy array is there a better way to do this i would have thought it would be quicker to preallocate the array and then fill it with data but instead generating a python list and converting it to a numpy array is faster although 15ms for 4096 quads seems slowi have included some example code and their timingsusrbinpythonimport timeitimport numpyimport ctypesimport randomuse randomtrueuse static buffertruestatic buffer numpyempty409620 dtypenumpyfloat32def renderi pretend these are different each time if use random tex left tex right tex top tex bottom randomrandom randomrandom randomrandom randomrandom left right top bottom randomrandom randomrandom randomrandom randomrandom else tex left tex right tex top tex bottom 00 10 10 00 left right top bottom 10 10 10 10 ibuffer tex left tex bottom left bottom 00 lower left corner tex right tex bottom right bottom 00 lower right corner tex right tex top right top 00 upper right corner tex left tex top left top 00 upper left return ibuffer create python list convert to numpy array at enddef create array 1 ibuffer for x in xrange4096 data renderx ibuffer data ibuffer numpyarrayibuffer dtypenumpyfloat32 return ibuffer numpyarray placing individually by indexdef create array 2 if use static buffer ibuffer static buffer else ibuffer numpyempty409620 dtypenumpyfloat32 index 0 for x in xrange4096 data renderx for v in data ibufferindex v index 1 return ibuffer using slicingdef create array 3 if use static buffer ibuffer static buffer else ibuffer numpyempty409620 dtypenumpyfloat32 index 0 for x in xrange4096 data renderx ibufferindexindex20 data index 20 return ibuffer using numpyconcat on a list of ibuffersdef create array 4 ibuffer concat for x in xrange4096 data renderx converting makes a diff data numpyarraydata dtypenumpyfloat32 ibuffer concatappenddata return numpyconcatenateibuffer concat using numpy arrayputdef create array 5 if use static buffer ibuffer static buffer else ibuffer numpyempty409620 dtypenumpyfloat32 index 0 for x in xrange4096 data renderx ibufferput xrangeindex index20 data index 20 return ibuffer using ctype arrayctypes array ctypesc float409620def create array 6 ibuffer for x in xrange4096 data renderx ibuffer data ibuffer ctypes arrayibuffer return ibufferdef equalsa b for iv in enumeratea if bi v return false return trueif name main number 100 if random do not try and compare arrays if not use random and not use static buffer a create array 1 assert equals a create array 2 assert equals a create array 3 assert equals a create array 4 assert equals a create array 5 assert equals a create array 6 t timeittimer testing2create array 1 import testing2 print from list ttimeitnumbernumber10 ms t timeittimer testing2create array 2 import testing2 print array indexed ttimeitnumbernumber10 ms t timeittimer testing2create array 3 import testing2 print array slicing ttimeitnumbernumber10 ms t timeittimer testing2create array 4 import testing2 print array concat ttimeitnumbernumber10 ms t timeittimer testing2create array 5 import testing2 print array put ttimeitnumbernumber10 ms t timeittimer testing2create array 6 import testing2 print ctypes float array ttimeitnumbernumber10 mstimings using random numbers python testing2pyfrom list 150486779213 msarray indexed 248184704781 msarray slicing 502214789391 msarray concat 441691994667 msarray put 735879898071 msctypes float array 206674289703 msedit note changed code to produce random numbers for each render to reduce object reuse and to simulate different vertices each timeedit note2 added static buffer and force all numpyempty to use dtypefloat32note 1apr2010 still no progress and i do not really feel that any of the answers have solved the problem yet,['python'] +49435,how to read using c c sound stream sent by flash i need to read sound stream sent by flash audio in my c application c is not a real limitation it may be c or any other desktop language now flash app sends audio to another flash app but i need to receive the same audio by desktop applicationso is there a standard or best way how to do itthank you for your answers,"['c#', 'c++']" +49440,java consumes too much memory my java written application consumes way too much memoryhow does program work user selects a date from calendar gui and application loads data into jtable component everytime data is loaded new tablemodel is created and set no new jtable is created just modelwhat is the problem every new day selection from calendar and loading to jtable consumes about 23 mb of memory on start app consumes cca 5060 mb of ram after few clicks on calendar like 20 application consumes full heap size 128mb application crashes of course what should i do i am pretty sure database querys are ok i might somehow set bigger heap size i googled but that would be only solution for my computer users wont do this or i should somehow remove old tablemodel with db data but should not this be garbage collectors work i am able to force it systemgc but that does not help thank you for any adviceedit code for handling events of calendar i deleted javadoc it is in my mother tonguepackage timesheethandlersimport javautilcalendarimport javautildateimport javautilgregoriancalendarimport javautillistimport orgjdesktopswingxjxmonthviewimport orgjdesktopswingxeventdateselectioneventimport orgjdesktopswingxeventdateselectionlistenerimport timesheetdatabaseworkeroperationsimport timesheetframesworkerframeimport timesheetlogictrierpublic class workermonthviewhandler private jxmonthview monthview private workerframe workerframe private workeroperations wops private date week new date5 private workertaskstablehandler wtth public workermonthviewhandlerworkerframe workerframe thisworkerframe workerframe thismonthview workerframegetworkermonthview wops workerframegetworkeroperations for db usage public void initmonthview listtask tasks wopsgetworkertasksworkerframegetworker db select for task task tasks if monthviewgetselectioncontainstaskgetplannedstart monthviewaddflaggeddatestaskgetplannedstart monthviewaddflaggeddatestaskgeplannedend not really important monthviewsetselectiondatenew date monthviewgetselectionmodeladateselectionlistenernew dateselectionlistener public void valuechangeddateselectionevent dse date d monthviewgetselectiondate for int i0 iweeklength i if dequalsweeki return calendar cal new gregoriancalendar calsettimed long dayms 24 60 60 10 switch calgetcalendarday of week casecalendarmonday week0 new datecalgettimeinmillis week1 new datecalgettimeinmillisdayms week2 new datecalgettimeinmillis2dayms week3 new datecalgettimeinmillis3dayms week4 new datecalgettimeinmillis4dayms break case calendartuesday week0 new datecalgettimeinmillisdayms week1 new datecalgettimeinmillis week2 new datecalgettimeinmillis1dayms week3 new datecalgettimeinmillis2dayms week4 new datecalgettimeinmillis3dayms break case calendarwednesday week0 new datecalgettimeinmillis2dayms week1 new datecalgettimeinmillisdayms week2 new datecalgettimeinmillis week3 new datecalgettimeinmillis1dayms week4 new datecalgettimeinmillis2dayms break case calendarthursday week0 new datecalgettimeinmillis3dayms week1 new datecalgettimeinmillis2dayms week2 new datecalgettimeinmillis1dayms week3 new datecalgettimeinmillis week4 new datecalgettimeinmillis1dayms break case calendarfriday week0 new datecalgettimeinmillis4dayms week1 new datecalgettimeinmillis3dayms week2 new datecalgettimeinmillis2dayms week3 new datecalgettimeinmillisdayms week4 new datecalgettimeinmillis break case calendarsaturday week0 new datecalgettimeinmillis5dayms week1 new datecalgettimeinmillis4dayms week2 new datecalgettimeinmillis3dayms week3 new datecalgettimeinmillis2dayms week4 new datecalgettimeinmillisdayms break case calendarsunday week0 new datecalgettimeinmillis6dayms week1 new datecalgettimeinmillis5dayms week2 new datecalgettimeinmillis4dayms week3 new datecalgettimeinmillis3dayms week4 new datecalgettimeinmillis2dayms break wtth new workertaskstablehandlerworkerframeweek wtthcreatetable sets model on jtable public void reporttask wtthreporttasks simple db insert using netbeans profiler date taken sun feb 28 142516 cet 2010 file cprivateprofilerjava pid4708hprof file size 722 mbtotal bytes 62 323 264total classes 3 304total instances 1 344 586classloaders 18gc roots 2 860number of objects pending for finalization 0,['java'] +49447,stateless and stateful enterprise java beans i am going through the java ee 6 tutorial and i am trying to understand the difference between stateless and stateful session beans if stateless session beans do not retain their state in between method calls why is my program acting the way it ispackage mybeansimport javaxejblocalbeanimport javaxejbstatelesslocalbeanstatelesspublic class mybean private int number 0 public int getnumber return number public void increment thisnumber the clientimport javaioioexceptionimport javaxejbejbimport javaxservletimport javaxservlethttpimport javaxservletannotationwebservletimport mybeansmybeanimport javaioprintwriterwebservletname servletclient urlpatterns servletclient public class servletclient extends httpservlet private static final long serialversionuid 1l ejb mybean mybean protected void dogethttpservletrequest request httpservletresponse response throws servletexception ioexception printwriter out responsegetwriter mybeanincrement outprintlnmybeangetnumber i was expecting getnumber to return 0 every time but it is returning 1 and reloads of the servlet in my browser increase it more the problem is with my understanding of how stateless session beans work and not with the libraries or application server of course can somebody give me a simple hello world type example of a stateless session bean that behaves differently when you change it to stateful,['java'] +49471,sqlite on android how to create a sqlite thist db function to be used in the app for thistance calculation using lat long we are building an android app that will use users current location lat long and show top 50 venues around the current location sorted by thistancewe have these venues stored in an sqlite db we plan to ship with the sqlite db with the appin order to fetch only the relevant top 50 closest venues we want to define a db function thist to calculate thistance between two points and use it in our queryhow can i define a custom sqlite function for android apps what will be the java api call to do thiswe have successfully implemented this approach in our iphone app using objective c,"['java', 'android']" +49474,endianness in programming languages well the endianness theme was always a little bit confusing to me but i have never faced any problems which required me to even think about the default behaviour of binary writersreaders that i used i am writing a png decoder in c right now png file format specification states that all numbers are stored in a big endian notation which i find very natural however i was very surprised when i noticed that nets binaryreaderwriter works with a little endian notation what confused me even more was the fact that javas binary io works with a big endian notation a am not a java programmer so maybe i am wrong so i started to think about the following questions1 why are things as they are i mean a base class library default behaviour2 why there is no way to choose a preferred notation when using nets systemio i am currently using jon skeets miscutil and it works like a charm thanks man but it would be cool to see this functionality in a base class library,"['c#', 'java', '.net']" +49479,parsing broken xml with lxmletreeiterparse i am trying to parse a huge xml file with lxml in a memory efficient manner ie streaming lazily from thisk instead of loading the whole file in memory unfortunately the file contains some bad ascii characters that break the default parser the parser works if i set recovertrue but the iterparse method does not take the recover parameter or a custom parser object does anyone know how to use iterparse to parse broken xmlthis works but loads the whole file into memoryparser lxmletreexmlparserrecovertrue recovers from bad characterstree lxmletreeparsefilename parserhow do i do the equivalent with iterparse using iterparse so the file can be streamed lazily from thiskcontext lxmletreeiterparsefilename tagrecordrecord contains 6 elements that i need to extract the text fromthanks for your helpedit here is an example of the types of encoding errors i am running intoin 17 dataout17 tarticletextltpgtthe cafeteria rang with excited voices our barbershop quartet the bell r tones was asked to perform at the local home for the blind in the next town we of course were glad to entertain such a worthy group and immediately agreed one wag joked which uniform should we wear followed with oh that is right they will never notice the others did not respond to this in fact one said that we should wear the nicest outfit we hadltpgtltpgta small stage was set up for us and a pretty decent pa system was donated for the occasion the audience was made up of blind persons of every age from the thirties to the nineties some sported sighted companions or nurses who stood or sat by their side sharing the moment equally i observed several german shepherds lying at their feet adoration showing in their eyes as they wondered what was going on after a short introduction in which we identified ourselves stating our voice part and a little about our livelihood we began our program some songs were completely familiar and others called oh yeah songs only the chorus came to mind we did not mind at all that some sang along x1e they enjoyed it so muchltpgtltpgtin fact a popular part of our program is when the audience gets to sing some of the old favorites the harmony parts were quite evident as they tried their voices to the different parts i think there was more group singing in the old days than there is now but to blind people sound and music is more important we received a big hand at the finale and were made to promise to return the following year everyone was treated to coffee and cake our quartet going around to the different circles of friends to sing a favorite song up close and personal as we approached a new group one blind lady amazed me by turning to me saying youre the baritone are not you previously no one had ever been able to tell which singer sang which part but this lady was listening with her whole heartltpgtltpgtretired portrait photographer main hobby quartet singingltpgtarticletextnin 18 lxmletreefromlxmletreefromstring lxmletreefromstringlist in 18 lxmletreefromstringdataxmlsyntaxerror traceback most recent call lastmntarticlesipython console in moduleusrlibpython25sitepackageslxml224py25linuxi686egglxmletreeso in lxmletreefromstring srclxmllxmletreec48270usrlibpython25sitepackageslxml224py25linuxi686egglxmletreeso in lxmletree parsememorydocument srclxmllxmletreec71812usrlibpython25sitepackageslxml224py25linuxi686egglxmletreeso in lxmletree parsedoc srclxmllxmletreec70673usrlibpython25sitepackageslxml224py25linuxi686egglxmletreeso in lxmletree baseparser parsedoc srclxmllxmletreec67442usrlibpython25sitepackageslxml224py25linuxi686egglxmletreeso in lxmletree parsercontext handleparseresultdoc srclxmllxmletreec63824usrlibpython25sitepackageslxml224py25linuxi686egglxmletreeso in lxmletree handleparseresult srclxmllxmletreec64745usrlibpython25sitepackageslxml224py25linuxi686egglxmletreeso in lxmletree raiseparseerror srclxmllxmletreec64088xmlsyntaxerror pcdata invalid char value 30 line 1 column 1190in 19 chardetdetectdataout19 confidence 10 encoding asciias you can see chardet thinks it is an ascii file but there is a x1e right in the middle of this example which is making lxml raise an exception,['python'] +49491,python 3 object construction which is the most pythonic the accepted way having a background in java which is very verbose and strict i find the ability to mutate python objects as to give them with fields other than those presented to the constructor really uglytrying to accustom myself to a pythonic way of thinking i am wondering how i should allow my objects to be constructedmy instinct is to have to pass the fields at construction time such asdef init self foo bar baznone selffoo foo selfbar bar selfbaz bazbut that can become overly verbose and confusing with many fields to pass to overcome this i assume the best method is to pass one dictionary to the constructor from which the fields are extracteddef init self field map selffoo field mapfoo selfbar field mapbar selfbaz field mapbaz if baz in field map else nonethe other mechanism i can think of is to have the fields added elsewhere such asclass blahobject def init self passblah blahblahfoo var1but as that feels way too loose for mei suppose the issue in my head is how i deal with interfaces in pythonso to reiterate the question how i should construct my objects in python is there an accepted convention,['python'] +49502,how to capture a backspace on the onkeydown event i have a function that is triggered by the onkeydown event of a textbox how can i tell if the user has hit either the backspace key or the del key,['javascript'] +49504,handling fatal exceptions in viewmodelmodel i have an application written using the mvvm approachthe data access is done in the model if a fatal error occurs here for example the connection to the data source is lost and exception is thrown this exception bubbles up to the viewmodelhowever because the original trigger of the data access was a data binding wpf swallows this exception it is only logged in the output window when the app is run under the debuggeri would rather this exception remained unhandled so my applicationwide unhandled exception handler could pick it up log it and gracefully exit how can i achieve this,"['c#', '.net']" +49507,how would you make a dynamic formset in django heres the way i am doing it formsetmanagement form table for form in formsetforms form endfor tablea hrefjavascriptvoid0 idadd formadd forma and heres the jsvar form count formsettotal form countadd formclickfunction form count var form formsetempty formescapejsreplace prefix g form count formsappendform id formtotal formsvalform countwhat specifically bothers me is that i had to write that escapejs template tag myself it just strips all newlines and escapes any single quotes so that it does not mess up my string but what exactly did the django makers expect us to do in this situation and why do they have this total forms hidden field when they could have just used an array like input namemy form field0 and then counted its length instead,['javascript'] +49514,at what exact moment is a local variable allocated storage suppose we have the followingvoid print int a declaration a 9 cout a endlint main printis the storage for variable a allocated at the moment function print is called in main or is it when execution reaches the declaration inside the function,['c++'] +49520,can a c class member function template be virtual i have heard that c class member function templates cannot be virtual is this true if they can be virtual what is an example of a scenario in which one would use such a function,['c++'] +49542,jpa property javaneturl hi i have an object which has a piece of urlinformation associated with itcurrently i save this url in a simple string property but javaneturl wouldprovide me with additional goodies such as detection of malformed urls etcon the other hand i would consider it very ugly if jpa simply created a lob for the urlobject does anyone know how a property of the type javaneturl will be persisted tothe database by compliant jpa providers,['java'] +49545,how do i define a preprocessor symbols in c visual studios sorry if my terminology is wrong i wrote if test app in my code now i would like to define test app how do i set it using visual studios 2010 this is a windows form applicationbonus if you can tell me the name of the symbol that is set in a winform project and in a web project,['c#'] +49562,what is html code that causes captionscomments pop up when mouse is rolled over a hyperlink what is that peice of the html code that allows me to provide comments to links before the user is actually clicking on themdo you know what i meani mean on my web page i have some hyperlinks and i want to know some information about it what i will be taken to if i click on this link so i just roll over my mouse on that link and a certain kind of caption appears providing me with all necessary info about this link i know how to make hyperlinks in html but i have no idea how to make these selfpopping up captions can anyone here please share with me how to do that which tags do i need to use for that a simple example would be highly appreciated thank you all in advance,['html'] +49568,documenting preprocessor defines in doxygen is it possible to document preprocessor defines in doxygen i expected to be able to do it just like a variable or function however the doxygen output appears to have lost the documentation for the define and does not contain the define itself eitheri tried the followingmy preprocessor macrodefine test definex xxanddef test define my preprocessor macrodefine test definex xxi also tried putting them within a group tried defgroup addtogroup and ingroup rather than just at the file scope however that had no effect either although other items in the group were documented as intendedi looked through the various doxygen options but could not see anything that would enable or prevent the documentation of defines,['c++'] +49569,starting multiple threads and keeping track of them from my net application i would like to start x number of threads from my net application and i would like to keep track of them as i will need to terminate them manually or when my application closes my application later onexample start thread alpha start thread beta then at any point in my application i should be able to say terminate thread beta what is the best way to keep track of opened threads in net and what do i need to know an id about a thread to terminate it sample code tutorial would be helpful,['c#'] +49578,css3 use onhover event to set semitransparent overlay on an image i need an on hover semitransparent div which causes some text to appear over the top of a thumbnail image is it possible to do this without using javascript and using just cascading style sheet,"['html', 'css']" +49581,timeout a task with javas swingworker i am trying to implement a swingworker class within my application is there a way to set a length of time that after which the swingworker times out i was thinking that maybe throwing an outoftime exception that i can catch and then deal with i am just not sure how to implement itthanks for all your help,['java'] +49583,what browsers currently support javascripts let keyword i am developing an app and do not have to ever worry about internet explorer and was looking into some of the features present in a grade browsers that are not in internet explorer1one of these features i wanted to play around with is javascripts let keywordi cannot seem to get any of their let examples to work in firefox 36 useragent string mozilla50 windows u windows nt 51 enus rv192 gecko20100115 firefox36 net clr 3530729 i get syntaxerror missing before statement when executing let foo barso what browsers support the let keyword or am i doing something wrong,['javascript'] +49590,how to force coredata to rebuild sqlite database model in my app i sometimes need to rebuild and repopulate database file sqlite databse is created and managed by coredata stackwhat i am trying to do is drop the file and then simply recreate persistentstorecoordinator objectit works under simulator but not on device where i am getting such an errornsfilepath varmobileapplications936c6cc7423a46f4adc07184eab0cadocumentsmydbsqlitensunderlyingexception io error for database at varmobileapplications936c6cc7423a46f4adc07184eab0cadocumentsmydbsqlite sqlite error code1 table zx already existsi cannot find the cause of this in any way it indicates two different problems cocoa error 256 indicates that file does not exist or is not readable but file is created after creating persistenstorecoordinator although it is empty but after executing some queries it thisappearssecond message indicating attempt to create alredy existing table is quite strange in that casei am quite confused and cannot get the point whats going on here my code looks like thisnsstring path wllocalservice datastorepath relativepathnserror error nilwllogabout to remove file pathnsfilemanager defaultmanager removeitematpath path error errorif error nil wllogerror removing the db errorself persistentstorecoordinatorwllogrebuild db result d nsfilemanager defaultmanager fileexistsatpath pathafter this code is exectued db file exists but is empty when then first query and all following is executed it gives me the error above and file thisappearsdoes anybody has an idea whats wrong with itbig thanks for pointing me the right way,['iphone'] +49597,what is the proper way to comment functions in python is there a generally accepted way to do this is this acceptable create a new userdef addself,['python'] +49599,invalid state err dom exception 11 i am developing a simple auxiliary class to send requests using xmlhttprequest code below but i cant make it work at google chrome for example i get the error invalid state err dom exception 11 and at the other browsers i get a status 0method xrequest object constructor as this implements a singleton the object cannot be created calling the constructor getinstance should be called insteadfunction xrequest thisxhr xrequestcreatexhrxrequestinstance nullmethod static getinstance creates a singleton object of type xrequest should be called whenever an object of that type is requiredreturn an instance of a xrequest objectxrequestgetinstance function ifxrequestinstance null xrequestinstance new xrequest return xrequestinstancemethod static createxhr implments a basic factory method for creating a xmlhttprequest objectreturn xmlhttp object or nullxrequestcreatexhr function var xhr null var factory function return new xmlhttprequest function return new activexobjectmsxml2xmlhttp function return new activexobjectmicrosoftxmlhttp forvar i 0 i factorylength i var f factoryi xhr f ifxhr return xhr return nullxrequestprototypesetrequestheader functionname value ifthisxhr thisxhrsetrequestheadername value xrequestprototypesendrequest functionargs var async true var type var url var username var password var body null var success null var failure null fore in args switche case async async argse break case type type argse break case success success argse break case failure failure argse break case url url argse break case username username argse break case password password argse break case body body argse break case setheader var h argsesplit ifhlength 2 thissetrequestheaderh0 h1 break var that this thisxhronreadystatechange function alertreadystate thatxhrreadystate status thatxhrstatus ifthatxhrreadystate 4 ifthatxhrstatus 200 thatxhrstatus 0 ifsuccess successthatxhr else iffailure failure thisxhropentype url async username password thisxhrsendbodyexample of usagescript languagejavascript function onload var x xrequestgetinstance xsendrequesttypeget setheaderaccepttexthtml imagepng image url httpyour servercomgetdataparam1test successonsuccess failureonfail function onsuccessobj alertok function onfail alertnot at this time script,['javascript'] +49605,maxlengthfield in mysql if i sayselect maxlengthname from my tablei get the result as 18 but i want the concerned data also so if i sayselect maxlengthname name from my tableit does not work there should be a self join i guess which i am unable to figure it outcan anyone please provide me a clue,"['sql', 'mysql']" +49625,making django development server faster at serving static media i am using the django managepy runserver for developing my application obviously but it takes 10 seconds to completely load a page because the development server is very very slow at serving static mediais there any way to speed it up or some kind of workaround i am using windows 7,['python'] +49626,how to copy a smaller bitmap into a larger one hopefully this should be an easy question i am trying to copy a series of small bitmaps into a larger one arranging them side by side without any gaps or overlap in their pixels for example if i have 3 square bitmaps i would like to copy them into one long and thin rectangle i know how to do the opposite namely creating a small bitmap out of a larger one but not this way around whats the right commandif anyones curious i want to do this to be able to reuse some code i wrote for handling animation with a single bitmapthanks,['android'] +49635,python lexical analysis and tokenization i am looking to speed along my thiscovery process here quite a bit as this is my first venture into the world of lexical analysis maybe this is even the wrong path first i will describe my problemi have got very large properties files in the order of 10 properties which when thistilled are really just about 15 important properties and the rest can be generated or rarely ever change so for examplegeneral name myname ip 127001component1 key value foo barthis is the type of format i want to create to tokenize something likepropertygeneralnameblahhomedirectory blahpropertygeneralnameip generalippropertycomponent1ip generalippropertycomponent1foo component1foointopropertymynameblahhomedirectory blahpropertymynameip 127001propertycomponent1ip 127001propertycomponent1foo barlexical analysis and tokenization sounds like my best route but this is a very simple form of it it is a simple grammar a simple substitution and i would like to make sure that i am not bringing a sledgehammer to knock in a naili could create my own lexer and tokenizer or antlr is a possibility but i do not like reinventing the wheel and antlr sounds like overkilli am not familiar with compiler techniques so pointers in the right direction code would be most appreciatednote i can change the input format,['python'] +49640,how do i prevent iis from compiling website i have an asp net web application which on the backend is talking to an asmx web service we have counted and the average wait time for the initial request is 20s i am wondering if there is a way i can send the web service up to the server precompiled thus negating the need for compilationwe have also noticed that iis tends to recycle its worker threads and this also causes a compilation the process itself is not accessed terribly often but it needs to be much quicker when it isany thoughtsthanks in advanceupdate thanks to all the suggestions i have tried a number of them and here is what i have found recycle time shutdowntinkering is dangerous cause i dont want threads to just sit around doing nothing upon further inspection the site is going up precompiled so my question is why is there an initial spin up time for a web serviceright now leaning towards the warmup script suggestion belowupdate the service is being hit from a web server on a different machine we are seeing problems with the initial request only,['asp.net'] +49644,wxpython change field on tab i apologize for a simple question but i did not see this in the tutorialsi have a very simple gui but i would like the user to be able to press the tab key and have it move from one input field to another i am using wxpython with python 26,['python'] +49649,what is the most semantic way to thisplay a street address in html i have an address that is going to be thisplayed on a webpage but it is not the address for the author of the page how should this be coded to be semantic given the w3c recommendation ofthe address element may be used by authors to supply contact information for a document or a major part of a document such as a form this element often appears at the beginning or end of a document,['html'] +49650,using generics in abstract classes i am working on an abstract class where the implementing class needs to implement a list of t the problem is that this does not workpublic class abstractclass public int id get set public int name get set public abstract listt items get set public class container abstractclass public listwidgets items get set i am sure that there is an obvious answer that i am missing and i know that i can build an abstract base type to put in the list but when i use my linq command to build the list the abstract type itembase does not play nicely with the tolist method is what i am trying to do so unique,['c#'] +49652,hibernate mysql glassfish v3 and jta datasource i am attempting to use hibernate entity manager with mysql and glassfish i am getting the following error when attempting to use a jta datasource caused by orghibernatehibernateexception the chosen transaction strategy requires access to the jta transactionmanager at orghibernateimplsessionfactoryimplinitsessionfactoryimpljava376 at orghibernatecfgconfigurationbuildsessionfactoryconfigurationjava1367 at orghibernatecfgannotationconfigurationbuildsessionfactoryannotationconfigurationjava858 at orghibernateejbejb3configurationbuildentitymanagerfactoryejb3configurationjava733 37 morehere is how i have configured my persistencexmlxml version10 encodingutf8persistence version10 xmlns xmlnsxsi xsischemalocation 1 0xsd persistenceunit namemypu transactiontypejta providerorghibernateejbhibernatepersistenceprovider jtadatasourcejdbcmysqljtadatasource classcommysharedentitymyfileclass classcommysharedentitymyroleclass classcommysharedentitymyuserclass excludeunlistedclassestrueexcludeunlistedclasses properties property namehibernatehbm2ddlauto valuecreatedrop property namehibernateshowsql valuetrue propertieshowever when i configure a nonjta datasource it works finexml version10 encodingutf8 persistence version10 xmlns xmlnsxsi xsischemalocation 1 0xsd persistenceunit namemypu transactiontypejta providerorghibernateejbhibernatepersistenceprovider nonjtadatasourcejdbcmysqlnonjtadatasource classcommysharedentitymyfileclass classcommysharedentitymyroleclass classcommysharedentitymyuserclass excludeunlistedclassestrueexcludeunlistedclasses properties property namehibernatehbm2ddlauto valuecreatedrop property namehibernateshowsql valuetrue propertiespersistenceunitpersistencethat is all well and good but i would really like to useempersistmyobjectinstead ofemgettransactionbeginempersistmyobjectemgettransactioncommitam i missing something with the hibernate configuration or is it even possible to use a jta datasource,['mysql'] +49657,how do i thisplay a gif animation to the user while a picture is loading in the web the problemi have set of pictures when the user presses on one of them it is grow to an area in the page the exchange of the pictures is done with the help of js tthe picture is weigh about 05m therefore it is take about 3 sec until the picture is showedi would like to present a type of animation while the picture is not thisplayed how can i do this with the help of js,"['javascript', 'jquery', 'html']" +49685,what is the use of a pre tag in xhtml what is the use of a pre tag in xhtml,['html'] +49697,how to save application options before exit i have made an application and i need to save some options before exitsomething like window dimension that will be written in a filethe main frame has set thisframesetdefaultcloseoperationjframeexit on closehow can i save options that interests mebefore exiting of coursethanks,['java'] +49701,servertransfer throws error executing child request how to resolve i have a httpmodule in c 20 which handles exceptions thrown whenever the exception is thrown an error page aspx with some querystring will be called it is done through servertransferbut when the control tries to execute servertransfer the following exception is thrownerror executing child request for pagenameaspxwhereas requestredirect works fine i tried setting enableviewstatemacfalse in page directive of the page to which request is transferred still problem persistshere is the code i triedstring errorpage errorpageaspxid someerroridhttpcontextcurrentservertransfererrorpagetrueany idea how this can be resolved,['asp.net'] +49724,thiscovering derived types using reflection using reflection is it possible to thiscover all types that derive from a given typepresumably the scope would be limited to within a single assembly,"['c#', '.net']" +49728,mysql group by return the first record i far as i know mysql group by grouping to the last find recordis there any solution to group by the first recordi have setup the order in sql command and i need group by return the first record and not the lastedithere is the queryselect thistinctmastermasterid langdata master from master table as master inner join lang table as langdata on langdatamasteridmastermasterid group by mastermasterid order by case when langdatalangcurrentlang then 1 else 9 end mastername desc limit 010 the query above select the masterid for multi language table and suppose to return first the records in currentlang and order them by name and then all other languages dont ask me with i dont set the language in jointhis is the way to be doneso everything works fine so far expect the scenario that i have a record with languages en and frif currentlang is en then based on langdatalangcurrentlang then 1 else 9 endthe en order is 1 and fr order is 9 and instead of getting the value of en i get the value of frthats why i want group to the first row,['mysql'] +49730,why does not a get flattened to d when removing accentsdiacritics i am using this method to remove accents from my stringsstatic string removeaccentsstring input string normalized inputnormalizenormalizationformformkd stringbuilder builder new stringbuilder foreach char c in normalized if chargetunicodecategoryc unicodecategorynonspacingmark builderappendc return buildertostringbut this method leaves a as a and does not change it to d even though d is its base charyou can try it with this input string aa aoa3a a aoaa14a12awhats so special in letter a,"['c#', '.net']" +49737,how to enable html5 elements in ie 8 that were inserted by ajax call see the solution at the bottom of the questionie 8 and lower does not work good with unknown elements ie html5 elements one cannot style them or access most of their props their are numerous work arounds for this for example the problem is that this works great for static html that was available on page load but when one creates html5 elements afterward for example ajax call containing them or simply creating with js it will mark these newly added elements them as htmlunknownelement as supposed to htmlgenericelement in ie debuggerdoes anybody know a work around for that so that newly added elements will be recognizedenabled by ie 8here is a test pagehtmlheadtitletime testtitle if ie script srcscriptendif script src typetextjavascriptscriptheadbody timesome timetime hr script typetextjavascript timetextworks great bodyappendtimenew elementtime simulates ajax callback insertion timetextupdate scriptbodyhtmlin ie you will see the update and new elementin any other modern browser you will see update and update,"['javascript', 'jquery']" +49747,mysql update query to remove spaces hione of my clients has added a number of account numbers in one of our applicationswhile trying to make a transaction the transaction fails due to the spaces at the end of the account numberhow do i update his records in the mysql database to remove all the spaces from accounts that have them at the end without making him delete the clients and readding the accounts the structure of the tables is as followsnot sure how to structure the query or the function of the mysql the account table the account tablecustomer id accountnumber txt currency no user id active flag user date ben bic address int bic address the admin table adm user id location cd lang user name user login user password group code user id user date active counter connected ipand the customer tablecustomer id country no user id customer name active flag,['mysql'] +49759,principalcontextvalidatecredentials always returns false i have an mvc application that needs to login and verify a user against active directory i am using the principalcontextvalidatecredentials method but always get a authentication of falseconnecting to the server is fine the problem seems to occur in the validatecredentialshere is my codepublic static bool isauthenticatedstring domain string username string pwd bool isauthenticated false try principalcontext insprincipalcontext new principalcontextcontexttypedomain domain dcc1wdccom username c1w username isauthenticated insprincipalcontextvalidatecredentialsusername pwd catch exception ex rethrow this exception exceptionpolicyhandleexceptionex exception policy return isauthenticatedanyone know why this would be happening,['c#'] +49761,javasqlsqlexception io exception got minus one from a read call during jdbc connection with oracle hi i am new to java when i tried to connect oracle with my java sample code i got the above exceptionmy code isimport javasqlimport javaioioexceptionimport javaxservletservletexceptionimport javaxservlethttphttpservletimport javaxservlethttphttpservletrequestimport javaxservlethttphttpservletresponsepublic class dbconnectivity extends httpservlet protected void dogethttpservletrequest request httpservletresponse response throws servletexception ioexception try classfornameoraclejdbcdriveroracledriver connection con drivermanagergetconnectionjdbcoraclethinlocalhost8080orcl system tiger the exception thrown here statement stmt concreatestatement resultset rst stmtexecutequeryselect from users systemoutprintlnrstgetstring1 stmtclose conclose catch classnotfoundexception e eprintstacktrace catch sqlexception e eprintstacktrace and the exception thrown isjavasqlsqlexception io exception got minus one from a read callat oraclejdbcdriverdatabaseerrorthrowsqlexceptiondatabaseerrorjava112at oraclejdbcdriverdatabaseerrorthrowsqlexceptiondatabaseerrorjava146at oraclejdbcdriverdatabaseerrorthrowsqlexceptiondatabaseerrorjava255at oraclejdbcdrivert4cconnectionlogont4cconnectionjava387at oraclejdbcdriverphysicalconnectioninitphysicalconnectionjava441at oraclejdbcdrivert4cconnectioninitt4cconnectionjava165at oraclejdbcdrivert4cdriverextensiongetconnectiont4cdriverextensionjava35at oraclejdbcdriveroracledriverconnectoracledriverjava801at javasqldrivermanagergetconnectionunknown sourceat javasqldrivermanagergetconnectionunknown sourceat comwiproconectiondbconnectivitydogetdbconnectivityjava16at javaxservlethttphttpservletservicehttpservletjava690at javaxservlethttphttpservletservicehttpservletjava803at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava290at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava206at orgapachecatalinacorestandardwrappervalveinvokestandardwrappervalvejava233at orgapachecatalinacorestandardcontextvalveinvokestandardcontextvalvejava191at orgapachecatalinacorestandardhostvalveinvokestandardhostvalvejava127at orgapachecatalinavalveserrorreportvalveinvokeerrorreportvalvejava102at orgapachecatalinacorestandardenginevalveinvokestandardenginevalvejava109at orgapachecatalinaconnectorcoyoteadapterservicecoyoteadapterjava298at orgapachecoyotehttp11http11processorprocesshttp11processorjava852at orgapachecoyotehttp11http11protocolhttp11connectionhandlerprocesshttp11protocoljava588at orgapachetomcatutilnetjioendpointworkerrunjioendpointjava489at javalangthreadrununknown sourcehelp me to sort out this,['java'] +49766,how to use or condition in a javascript if statement i understand that in javascript you can writeif a b do something but how do i implement an or such asif a or b do something,['javascript'] +49774,linq query list contains a list i have 2 a claspublic class objecta public int id public string namepublic class objectb public int id public string name public listobjecta listofobjectaso i have two lists one of objectb listobjectb and another contains a list of ids of objecta called listofidsaif this i want to get a list of objectb where objectblistofobjecta is in the listofidsamy first and wrong approach waslistobjectbwherep listofidsacontainsplistofobjectaselectbbidbut this obviously throws an exception i google it stackoverflowed but i am thinking that my search skills are not going so well in this can anybody give a ninja awser of this prefereably in lambda expression,['c#'] +49781,gaej datastore backup what is the easiest way to do a gaej datastore backup it looks like there is python bulkloaderpy tool to do backup for python apps but what should i do to backup java app is there any way to use python tool,['java'] +49783,how can i avoid flicker in a wpf fullscreen app i have a wpf application that is a fullscreen kiosk app it is actually a pretty complicated app at this point but heres some code that shows the basic idea essentially whenever the user goes from one screen to the next there is some serious flicker going on bringing up the new window in severe cases the desktop is thisplayed for a few seconds before the new screen shows up that does not happen in this sample code because it is so simple but add a few more buttons and styles and youll see itappxamlcspublic partial class app application manager mmanager public app mmanager new manager window1 screen1 new window1mmanager mmanagerscreen1 screen1 try thisrunscreen1 catch exception e systemconsolewritelineetostring finally applicationcurrentshutdown window1xamlcspublic partial class window1 window manager managerget set public window1manager inmanager initializecomponent manager inmanager private void onchangescreenobject sender routedeventargs e manageropenscreen2 window2xamlcspublic partial class window2 window manager managerget set public window2manager inmanager initializecomponent manager inmanager private void onchangescreenobject sender routedeventargs e manageropenscreen1 managercspublic class manager public window1 screen1 get set public window2 screen2 get set public manager screen1 new window1this public void openscreen2 screen2 new window2this screen2show if screen1 null screen1hide public void openscreen1 screen1 new window1this screen1show if screen2 null screen2hide window1xaml essentially mimicked by window2xamlwindow xclasswpfapplication1window1 xmlns xmlnsx titlewindow1 windowstylenone windowstatemaximized width1280 height1024 fontfamilyglobal user interface resizemodenoresize grid gridcolumndefinitions columndefinitioncolumndefinition columndefinitioncolumndefinition columndefinitioncolumndefinition columndefinitioncolumndefinition gridcolumndefinitions gridrowdefinitions rowdefinitionrowdefinition rowdefinitionrowdefinition rowdefinitionrowdefinition rowdefinitionrowdefinition gridrowdefinitions button namechangescreenbutton clickonchangescreen gridrow2 gridcolumn2 contenttoggle screen 2button gridwindowinterleaving the thisplays of the two windows ie showing window 1 before deleting window 2 etc does not change the flickering behavior in this simple app it would be possible to just hide the other screens that are not shown but in the more complicated app there is just too much state information to manage screen information properly and easilyis there some magic codeword or technique to avoid flicker that would work in this simple app that also scales to the more complex app i am worried that i will be forced to rewrite the entire ui at this point to support hiding and showing and that is just not feasible in my timeframeedit i have tried the hideshow thing on some dialogs and it just does not seem to matter maybe it is because the main kiosk app is style heavy,['.net'] +49790,rspec spec fails when invoked via rake spec passes when invoked via spec spec one of my specs fails when i run it via rake spec but passes when i use the rspec executable specthe spec fails when i use a url helper in a actionmailer view the error message is auction url failed to generate from actionshow stateasd slugasd controllerauctions expected actionshow controllerauctions diff stateasd slugasdstate and slug are required attributes for the url thoughthe route looks like thismapauction stateslug controller auctions action showi set the host which is needed to use the url helpers in actionmailer views in the environment filesactionmailerbasedefault url optionshost myhostcomwhat could be the problemwhy is rake spec behaving differently from spec specanything that is loadednot loaded when using one or the other,['ruby-on-rails'] +49796,where is the temp folder in android device where is located the temp folder in the android phones,['android'] +49797,what is the size limit of a post request sorry if this is duplicatei would think it would be but could not find anythingi have a flex application that i am posting data back to a phpmysql server via ie i have not run into any problems yet but knowing this ahead of time might save me a bunch of frustration and work is there a size limit to posting data via http this article says no form submithtmlthis thiscussion says yesand it all goes back and forth what i am able to find online so please limit answers to personally testedverified numbersi am wanting to post back an xml string that can be quite large say up to 5mbif it makes any difference browser will always be ie our product requires it post is coming from and httpservice in flex web server is php db is mysql,['php'] +49800,can i use assert on android devices i want to use the assert keyword in my android apps to destroy my app in some cases on the emulator or my device during testing is this possible it seems that the emulator just ignores my asserts,['android'] +49802,measure string inside richtextbox control can somebody please explain how i would go about measuring the string inside a richtextbox control so that the i can automatically resize the richtextbox control according to its contentthank youediti have thought about it and since the below answer would not work if there are different fonts in the richtextbox control what if i could get the upperleft coords of the richtextbox control and then get the bottomright coords of the very last line of text inside the rtb that would essentially give me the width and height of the string inside the richtextbox control is this possible or is this a bad idea to do it this way,['c#'] +49815,iphone super viewdidunload calling order i would like to know if there is any difference between calling super viewdidunload before realeasing properties or after itthank you selfwebview nil selffulltext nil super viewdidunloador super viewdidunload selfwebview nil selffulltext nil,"['iphone', 'objective-c']" +49833,what does uri has an authority component mean i am attempting to build a java web project on netbeans 68 but i get get the following errorthe module has not been deployedit points to my buildimplxml file line 577nbdeploy clienturlpartclienturlpart debugmodefalse forceredeployforceredeploythe glassfish v3 error log sayssevere exception in command execution javalangillegalargumentexception uri has an authority componentjavalangillegalargumentexception uri has an authority component at javaiofileinitfilejava368 etcwhat does uri has an authority component mean,['java'] +49847,is there a way to conditionally use default column values in an insertselect statement i have got code similar to the following in a stored procedure that inserts a row into a table i would like to set the last column fieldd to prmsomevalue unless it is null otherwise just use the default value defined for that column if prmsomevalue is null insert into mytable fieldafieldbfieldc select abc from myothertableelse insert into mytable fieldafieldbfieldcfieldd select abcprmsomevalue from myothertablethis works but violates the dry principle i am trying to find some way to do this with a single insert statement something along the lines of the following pseudocode insert into mytable fieldafieldbfieldcfieldd select abcisnullprmsomevaluedefault from myothertableanyone have any ideasupdate one more twistthe default constraint is not a literal value but a function as shown belowdefault suser sname for fielddupdatei finally punted and chose the lesser of evils and just copied the default value function into my query instead of falling through to the default configured for the column i do not love it but it gets the job done with less repetition in my query insert into mytable fieldafieldbfieldcfieldd select abcisnullprmsomevaluesuser sname from myothertable,['sql'] +49855,how to do an inner join on multiple columns i am working on a homework project and i am supposed to perform a database query which finds flights either by the city name or the airport code but the flights table only contains the airport codes so if i want to search by city i have to join on the airports tablethe airports table has the following columns code citythe flights table has the following columns airline flt no fairport tairport depart arrive farethe columns fairport and tairport are the from and to airport codesthe columns depart and arrive are dates of departure and arrival i came up with a query which first joins the flights on the fairport column and the airportscode column in order for me to match the tairport i have to perform another join on the previous matches from the first joinselect airline flt no fairport tairport depart arrive fare from select from flights inner join airports on flightsfairport airportscode where airportscode or airportscity as matches inner join airports on matchestairport airportscode where airportscode or airportscity my query returns the proper results and it will suffice for the purpose of the homework but i am wondering if i can join on multiple columns how would i construct the where clause so it matches the departure and the destination citycodebelow is a pseudoquery on what i want to acheive but i cannot get the syntax correctly and i do not know how to represent the airports table for the departures and the destinationsselect from flightsinner join airportson flightsfairport airportscode and flightstairport airportscodewhere airportscode departurecode or airportscity departurecity and airportscode destinationcode or airportscity destinationcityupdatei also found this visual representation of sql join statements to be very helpful as a general guide on how to construct sql statements,['sql'] +49883,how to link access card reader with php i want to use an access card reader with php i am doing this to monitor attendance at a college is there any intermediate technology which can be used to take the readings from access card reader to the database,['php'] +49901,cakephp recommendation to iterate a huge table and generate a sitemap i am trying to create an xml sitemap using cakephp from a table which has more than 50 records at the moment each record equivalent to a uri in the sitemap now the problem i am facing is cakephp is running me out of memory while generating it for two reasonsa findall is building a huge associative array of the entire set of 50 uris since i do not want to output html from the controller itself i am transferring the associative array containing uri priority change frequency etc to the view with a thisset call which again is huge containing 50 indicesis it possible at all to do this while following mvc and cakephp guidelines,['php'] +49905,webview double tap zoom not working on a motorola droid a855 zoomin in my webview will not work on a double tab i am using motorola droid a855,['android'] +49913,how to delete all blank lines in the file with the help of python for example we have some file like thatfirst line second line third lineand in result we have to getfirst line second line third lineuse only python,['python'] +49923,create a random int number that differ from previous run of program i use this code to generate a random number random r new random0 int rand rnext7but i get the same random number in each run of program,['c#'] +49931,how to rescue timeout issues ruby rails most of my apps have a lot to do with web services and often due to the third party site i get timeout issuesthis is the error that i get execution expired usrlibruby18timeoutrb54in rbuf fillhow do i rescue this kind of error in a rails app,"['ruby-on-rails', 'ruby']" +49957,generate an html response in a java servlet how do i generate an html response in a java servlet,['html'] +49972,how to declare abstract method in nonabstract class in php class absclass abstract public function fucreportsphp fatal error class absclass contains 1 abstract method and must therefore be declared abstract or implement the remaining methods absclassfuci want to know what it means by implement the remaining methodshow,['php'] +49985,how to get the ip address and port number from addrinfo in unix c i need to send some data to a remote server via udp in a particular port and get receive a response from it however it is blocking and i get not response i needed to check if the addrinfo value that i get from the getaddrinfoserver name port hints servinfo is correct or not how do i get the ip address and port number from this data structure i know that inet ntoppai family get in addrstruct sockaddr pai addrs sizeof s gives me server ip address but i also need to make sure the port number is correct i am using the method in beejs guide,['c'] +50003,enable debug logging in maven jetty 7 plugin i am running a java webapp with a simple mvn jettyrun using the latest jetty plugin but i cannot seem to find a way to tell jetty to output debug messages to console for the embedded jetty instance not the plugin itself it is currently outputting only warn and info messages i have tried setting ddebug and dverbose but they do not do anything i have already had a look at the documentation but it does not seem to cover this,['java'] +50013,reading file content changes in net in linux a lot of ipc is done by appending to a file in 1 process and reading the new content from another processi want to do the above in windowsnet too messy to use normal ipc such as pipes i am appending to a file from a python process and i want to read the changes and only the changes each time filesystemwatcher reports an event i do not want to read the entire file content into memory each time i am looking for changes the file will be hugeeach append operation appends a row of data that starts with a unique incrementing counter timestampkey and ends with a newline,"['c#', '.net']" +50018,how clear is this interview question we are interviewing for a senior java development role and all three people that we have asked to complete this question gave us the same incorrect answer the question was done before the interview so they had a lot of time their solutions seemed to sort the input by parentid and then childid instead of creating a tree and from the input and then traversing the tree to find the correct order is the question not clear enoughquestionthe following is a simple skills and presentation test for the java developer role which must be completed before the telephone interviewrequiredjunit testimplementation of nodesorter interfacequestionwe have a java object that looks something like thispublic class node public int id public integer parentid public nodeint id integer parentid thisid id thisparentid parentid for example the following list of nodes might be thisplayed graphically asnode id 1 parentid null node id 2 parentid 1 nodeid 3 parentid 1 nodeid 4 parentid 2 nodeid 5 parentid 3 node id 1 node id 2 node id 3 node id 4 node id 5assumptionsthere will be always at least one nodethere will be one and only one node with a null parentidevery node will have a valid parentid except for the node which has a null parentidrequirementswrite a class that implements the following interface that will receive a list of nodes and order them from top to bottom nodes that are higher in the tree must be before the nodes lower in the tree eg node 1 on the top of the tree must be before node 4 which is on the bottom of the tree nodes on the same level will be in order of their id so the node with id2 will appear before the node with id3 in the diagram aboveinterface public interface nodesorter public listnode sortlistnode unsortednodes test datatest case 1diagram of input node id 1 node id 2 node id 3 node id 4 node id 5input node id 2 parentid 1 nodeid 4 parentid 2 node id 1 parentid null nodeid 3 parentid 1 nodeid 5 parentid 3output node id 1 parentid null node id 2 parentid 1 nodeid 3 parentid 1 nodeid 4 parentid 2 nodeid 5 parentid 3test case 2diagram of input node id 1 node id 5 node id 2 node id 4 node id 3input node id 5 parentid 1 nodeid 4 parentid 5 node id 1 parentid null nodeid 3 parentid 2 nodeid 2 parentid 1output node id 1 parentid null node id 2 parentid 1 nodeid 5 parentid 1 nodeid 3 parentid 2 nodeid 4 parentid 5,['java'] +50021,override opaque text in a transparent div with css i am trying to make text inside a transparent div have no opacity aka be completely blackdiv styleopacity06background3cc p stylebackground0opacity1this text should be all blackpdivis this possible to do with only cssthanks in advance,"['html', 'css']" +50051,how do i calculate percentiles with pythonnumpy is there a convenient way to calculate percentiles for a sequence or singledimensional numpy arrayi am looking for something similar to excels percentile functioni looked in numpys statistics reference and could not find this all i could find is the median 50th percentile but not something more specific,['python'] +50068,determine logical line from char index winforms textbox if i call textboxgetlinefromcharindexint in a textbox with wordwrap true it returns the line index as the user sees it wrapped lines count as multiple lines not the line according to the line breaksline one extends to word wrappedhere logical line 1 getlinefromcharindex returns line 2this is line two logical line 2 getlinefromcharindex returns line 3does anyone know of a solution to find the logical line from a character index rather than the thisplayed line,"['c#', '.net']" +50070,iphone catransition adds a fade to the start and end of any animation so i am just beginning recently developing some simple apps for the iphone i will say that i am fairly sure i do not have a strong understanding of programming for multiple views yet but i am trying to learn as i goi have a program that started as a plain window based application so i could hand write everything in hopes of learning more about what i am doing i have a single view controller that acts to load and release views as requested from each of the other view controllers no elements persist from one view to the otheri have that working fine currently but i wanted to add animations to the view changing a simple push animation was my goal one view pushes out as the new view pushes inlooking into catransitions and trying that i have a working version currently for pushing topbottom thisviewview removefromsuperview thisview release thisview menuviewcontroller alloc initwithnibnamemenuview bundlenil selfview addsubviewthisviewview catransition animation catransition animation animation setduration63 animation settypekcatransitionpush animation setsubtypekcatransitionfromtop animation setremovedoncompletionyes animation settimingfunctioncamediatimingfunction functionwithnamekcamediatimingfunctionlinear selfview layer addanimationanimation forkeynilas far as i can tell this is pretty standard code for using catransition and it works to do what i need one view gets pushed up as the other view comes in however my problem is that there seems to be a fade that happens to each view as they come in or go out respectivelyas such in this example as the menu pushes up from the bottom it will very slowly fade in from white and as the previous view leaves the screen it will slowly fade to white note that the duration is set to 6 so that the fading is dramatic is there a way to remove the fading here so that each view remains solid on the way in and the way out or have i missed the mark completely in this route that i am takingi appreciate any help apologies i have been long winded,['iphone'] +50072,getting rid of django ioerrors i am running a django site via apachemod python and i use djangos facilities to inform me and other developers about internal server errors sometimes errors like those appeartraceback most recent call last file optwebappexternalslibdjangocorehandlersbasepy line 92 in get response response callbackrequest callback args callback kwargs file optwebappcsiteappscustomersviewspy line 29 in feedback form feedbackformrequestpost file optwebappexternalslibdjangocorehandlersmodpythonpy line 113 in get post self load post and files file optwebappexternalslibdjangocorehandlersmodpythonpy line 96 in load post and files self post self files httpquerydictselfraw post data encodingself encoding datastructuresmultivaluedict file optwebappexternalslibdjangocorehandlersmodpythonpy line 163 in get raw post data self raw post data self reqreadioerror client read error timeoutas far as i found out those ioerrors are generated by clients that thisconnect in the wrong moment and that it is not a problem of my siteif that is the case can i thisable the emails for those errors somehow i really do not want to know about errors that i cannot fix and that are not really errors,['python'] +50078,custom fonts and xml layouts android i am trying to define a gui layout using xml files in android as far as i can find out there is no way to specify that your widgets should use a custom font eg one youve placed in assetsfont in xml files and you can only use the system installed fontsi know that in the java code i could change the font of each widget manually using unique ids alternatively i could iterate over all the widgets in java to make this change but this would probably be very slowwhat other options do i have is there any better ways to making widgets that have a custom look i do not particularly want to have to manually change the font for every new widget i add,"['java', 'android']" +50082,send email from a form only html javascript send email from a form here is the the link to basic html codew3 schoolsafter writing a comment name and email and clicking send button the outlook express startsis it possible to send message immediately using only html maybe javascriptor maybe is there something that can be done so that the outlook express doesnt ask again to submit a name and emailregards,['html'] +50097,how to put uislider vertical i want to put uislider in verticalyi have no idea about thisso please help me for this,['iphone'] +50121,c way to convert char into 8x8 binary can you help me look for a way to convert char into 8x8 binary am not sure how to call itlike for example an a011010010100101010010101101101am actually doing this manually suggestions are still open deditanyway if you guys are wondering what am trying to do am trying to make this led wave thisplay but since i do not have a computer interfacing knowledge i just want to try it in windows mobile lol,['c#'] +50129,how to embed a graphical interactive ironpython shell in an application i have tried the obvious path in my pet open source project revitpythonshell a plugin for the building modeling software autodesk revit architecture 2010 codeinteract with the ironpython engine set up to use net streams for stdin and stdout these i then redirect to a textbox control it kinda works but really is only an ugly hackthe main problem is getting all the shell stuff to work uparrow and downarrow for history editing copy paste eof syntax highlighting tool tips etc it takes a lot of work to get this right and it is not really the problem i am trying to solve i am trying to get an interactive shell hosted in revit not make the perfect shell guiif this werent a net project i would probably look into reusing pycrustpywrap but i am not sure if that can be done from a winforms project is there anything similar for nethas anyone ever implemented the iconsole interface and can show an example of what i would need to do it seems this would be the proper route to go as opposed to using the code module but for the life of me i cannot figure it out ironpython source code has no comments whatsoeverupdate after trying out some stuff i eventually settled on the superb ironlab code it includes an example shell with syntax highlighting and all the code was nice and easy to integrate check the revitpythonshell code on hints on how to embed it,['python'] +50138,jquery find if element has any text i am dealing with some generated spans and i would like to find which one of them does not contain any textthe markup isspan idlayer6 span classdrag col some textspan span classdrag col more textspan span classdrag col span span classdrag col i also have textspanspani can get get the ones that have some text with this code but i can not get the empty onesif layer6 spancolcontainssome textlength 0 alert i have texthow to get the empty ones i am thinking in using length to do it but i did not manage,['jquery'] +50139,convert 24bit bmp to 16bit i know that the net framework comes with an image conversion class the systemdrawingimagesave methodbut i need to convert a 24bit r8g8b8 bitmap image to a 16bit x1r5g5b5 and i really got no idea on this kind of conversion and a 24to16bit change in the bmp header wouldnt work since we need to convert the entire image dataalso i would like to know if i can control over the image dither etcideasany kind of help would be appreciated,['c#'] +50141,register a cvbnet com dll programatically question i have a net dll which i use from a c programnow i have to register the dll programmatically on a deployment computerhow do i do that programmatically not using regasm i remember when i once called a vb6 dll from a c dll i had to use dllregisterserver and dllunregisterserveris that still so with a net dll it seems i have to somehow add the dllregisterserver function to the net dll,['c#'] +50142,clicking urls opens default browser i have loaded an external url in my webview now what i need is that when the user clicks on the links on the page loaded it has to work like a normal browser and open the link in the same webview but it is opening the default browser and loading the page therei have enabled javascript but still it is not working have i forgotten something,['android'] +50160,udp and sockets recvfrom returning 1 and resource temporarily unavailable i am pretty new at programming and esp network programming so if it is stupid do not bash too hard please thanksi have client and server communicating with diagrams udp in c client sends 5 msgs and upon receiving msgs server sends msgs back receiving and sending messages are great until client has finished receiving the msgs after server sending all msgs back it terminates using close so recvfrom from client should return 0 rightassuming recvfrom should return 0 upon close from server side it returns 1 instead with error resource temporarily unavailable is this resource reference to closed socket from server or is it for something else entirely different like running out of buffer or something which i do not think is trueand assuming my assumption was wrong and 1 is returned because server terminated i probably should handle the error with ifsomemacro do something but how do i find out what somemacro is i print out the error but it says resource temp unavailable and recvfrom description does not mention about unavilable resourcebtw this is a non blocking socket if that makes any difference since i read that if o nonblock is set and no msgs are available it would set errno to eagain or ewouldblock o nonblock is not set but msg dontwait is set are they basically the same thing where o nonblock is for general file descriptors and msg dontwait is socket specificmy brain is not working all that great now if someone could enlighten me and clarify what my confusion is about i would deeply appreciate it thanks,['c'] +50163,android record exists in database i am looking to the fastest and the correct way to check if a record exists in the databasepublic boolean existsstring id cursor cdbquerytablename new string 1 id id null null null null if cequalsnull return cmovetofirst return falsedo you see any problem with it,"['java', 'android']" +50165,cnet analysis tool to find race conditionsdeadlocks is there a tool that analyses net code and finds race conditionsi have a bit of code that has a public static property that gets or creates a private static field it also has a public static method that sets this field to null yes i knowas there are no locks around either of these methods it is a safe bet that thingsll go horribly wrong in the future i need a tool thatll recursively go through things that call either of these methods and see if anything was spawned on another threadi am looking for a tool or perhaps an ndepend sql script if this is possible,"['c#', '.net']" +50169,why in aspnet is a button click event executes when page is refreshed in my aspnet web site i have a buttonwhen i click the button and then reload the page via browserthe click event of the button fireswhere is a problemplease help me,['asp.net'] +50180,dbunit automatic dataset generation i have seen a couple of question regarding creating datasets in dbunit here on stackoverflow but all of them were regarding export data from existing tablesmy question is can dbunit create some dummy dataset basing on my database schema i do not care whether the strings would be like zdsffdsdgf and blobs would be just garbage i just need some test data and i would prefer to spend my time developing instead of populating my tablesany solutions pointers a netbeans plugin doing that would be just great but i guess this is just a wishful thinking,['java'] +50181,get selected option from select element i am trying to get the selected option from a dropdown and populate another item with that text as follows ie is barking up a storm and it does not work in firefoxddlcodeschangefunction txtentry2textddlcodes optionselectedtextwhat am i doing wrong,['jquery'] +50187,hosting a vstdx instrument in cc i am trying to get a read on the effort level involved in building a barebones virtual instrument host in c or c but i have not been able to get any hard information does anybody know any good starter apps tutorials helper libraries for this sort of thingif it matters the goal would be to a accept incoming midi events and b thispatch them to the virtual instrument in c or c if possiblethanks,"['c#', 'c++']" +50195,is not a const variable at namespace scope implicitly static i know that static const int x 42 at namespace scope is equivalent to const int x 42 because const variables are implicitly static they must be declared extern to be given external linkage every translation unit that includes this declaration gets a local copy of xdoes this only apply to certain perhaps integer types i have the following code in a header filenamespace x static const char a a static const char b b static const char c c and so onplease spare me the comments on why i should not be using cstyle strings this is legacy codethis header is included from several source files and all is fine each compilation unit gets its own copy of these chars i would have thought that i could remove the static from these as it is redundant but when i do i get link errors about the symbols being already defined in another object what am i missing here are these const chars not implicitly static,['c++'] +50198,prevent id autogeneration on copypaste in visual studio 2008 aspnet web form if i have the following in an aspnet web formasptextbox runatserver idtbxuserand i copy and paste that line in the same page i usually get the followingasptextbox runatserver idtextbox1obviously nobody is going to name their controls in that way if you do not want to name a textbox simply do not asign an id to it and it is not nice having to change the ids of pasted controls the same happens if i copy a control without an explicit id vs simply generates one for meis there any way of preventing vs from autogenerating ids when i copypaste aspnet code,['asp.net'] +50201,toolstripstatuslabel doubleclick does not work does toolstripstatuslabel doubleclick ever work private sub mytoolstripstatuslabel doubleclickbyval sender as systemobject byval e as systemeventargs handles mytoolstripstatuslabeldoubleclick messageboxshowworkingend subonly click works doubleclick does not even if click is present or not,['.net'] +50210,what does do while 0 do exactly in kernel code possible duplicateswhats the use of do while0 when we define a macrowhy are there sometimes meaningless dowhile and ifelse statements in cc macros c multiline macro dowhile0 vs scope block i have seen a lot of usages like this previously i though that the programmer wanted to break out of a block of code easily why do we need a do while 0 loop here are we trying to tell the compiler somethingfor instance in linux kernel 2625 includeasmia64systemh clearing psri is implicitly serialized visible by next insn setting psri requires data serialization we need a stopbit before reading psr because we sometimes write a floatingpoint register right before reading the psr and that writes to psrmfl define local irq savex do ia64 stop x ia64 getreg ia64 reg psr ia64 stop ia64 rsmia64 psr i while 0,['c'] +50211,how well do java and scala work together i have been learning scala for the past couple of months and now i feel i can start using into real work apart from solving some simple problems my question here is how well do these two work together i have a couple of java projects which i am working on now how easy wiil it be to start using scala in them are there any gotchas to be aware of are there any tutorials or kind of stuff available on doing it if i want to use scala in web projects how to do it other than lift all ideas and suggestions welcome,['java'] +50214,entity framework savechanges error details when saving changes with savechanges on a data context is there a way to determine which entity causes an error for example sometimes i will forget to assign a date to a nonnullable date field and get invalid date range error but i get no information about which entity or which field it is caused by i can usually track it down by painstakingly going through all my objects but it is very time consuming stack trace is pretty useless as it only shows me an error at the savechanges call without any additional information as to where exactly it happenednote that i am not looking to solve any particular problem i have now i would just like to know in general if there is a way to tell which entityfield is causing a problemquick sample of a stack trace as an example in this case an error happened because createdon date was not set on iacomment entity however it is impossible to tell from this errorstack trace sqltypeexception sqldatetime overflow must be between 1753 120 am and 12319 115959 pm systemdatasqltypessqldatetimefromtimespantimespan value 2127345 systemdatasqltypessqldatetimefromdatetimedatetime value 232 systemdatasqlclientmetatypefromdatetimedatetime datetime byte cb 46 systemdatasqlclienttdsparserwritevalueobject value metatype type byte scale int32 actuallength int32 encodingbytesize int32 offset tdsparserstateobject stateobj 4997789 systemdatasqlclienttdsparsertdsexecuterpc sqlrpc rpcarray int32 timeout boolean inschema sqlnotificationrequest notificationrequest tdsparserstateobject stateobj boolean iscommandproc 6248 systemdatasqlclientsqlcommandrunexecutereadertdscommandbehavior cmdbehavior runbehavior runbehavior boolean returnstream boolean async 987 systemdatasqlclientsqlcommandrunexecutereadercommandbehavior cmdbehavior runbehavior runbehavior boolean returnstream string method dbasyncresult result 162 systemdatasqlclientsqlcommandrunexecutereadercommandbehavior cmdbehavior runbehavior runbehavior boolean returnstream string method 32 systemdatasqlclientsqlcommandexecutereadercommandbehavior behavior string method 141 systemdatasqlclientsqlcommandexecutedbdatareadercommandbehavior behavior 12 systemdatacommondbcommandexecutereadercommandbehavior behavior 10 systemdatamappingupdateinternaldynamicupdatecommandexecuteupdatetranslator translator entityconnection connection dictionary2 identifiervalues list1 generatedvalues 8084396 systemdatamappingupdateinternalupdatetranslatorupdateientitystatemanager statemanager ientityadapter adapter 267updateexception an error occurred while updating the entries see the inner exception for details systemdatamappingupdateinternalupdatetranslatorupdateientitystatemanager statemanager ientityadapter adapter 389 systemdataentitycliententityadapterupdateientitystatemanager entitycache 163 systemdataobjectsobjectcontextsavechangessaveoptions options 609 iadaliacontrollersaveiaheader head in cprojectsiaiadaliacontrollercs61 iaiaformsaveformboolean validate in cprojectsiaiaiaformaspxcs198 iaiaformadvance clickobject sender eventargs e in cprojectsiaiaiaformaspxcs287 systemwebuiwebcontrolsbuttononclickeventargs e 118 systemwebuiwebcontrolsbuttonraisepostbackeventstring eventargument 112 systemwebuiwebcontrolsbuttonsystemwebuiipostbackeventhandlerraisepostbackeventstring eventargument 10 systemwebuipageraisepostbackeventipostbackeventhandler sourcecontrol string eventargument 13 systemwebuipageraisepostbackeventnamevaluecollection postdata 36 systemwebuipageprocessrequestmainboolean includestagesbeforeasyncpoint boolean includestagesafterasyncpoint 5019,['c#'] +50215,how to group a 3x3 grid of radio buttons as the title describes i am trying to group up a grid of 3x3 radio buttons into a single radio group in a previous question asked i learned that for radio buttons to correspond to a single group they had to be the immediate children of the radio group to which they will correspond i learned this the hard way when i attempted to encapsulate an entire table layout with the radio buttons in the table rows in a radio group running into that wall i tried the followingtablelayout androidididtable radbuttons androidlayout widthwrap content androidlayout heightwrap content androidlayout belowidtitle radgroup buffer tablerow radiogroup androidlayout widthfill parent androidlayout heightwrap content androidorientationhorizontal androidididradgroup1 radiobutton androidididrad1 androidtextbutton1 androidlayout width105px androidlayout heightwrap content androidtextsize13pxradiobutton radiobutton androidididrad2 androidtextbutton2 androidlayout width105px androidtextsize13px androidlayout heightwrap contentradiobutton radiobutton androidididrad3 androidtextbutton3 androidlayout width105px androidtextsize13px androidlayout heightwrap contentradiobutton radiogroup tablerow tablerow radiogroup androidlayout widthfill parent androidlayout heightwrap content androidorientationhorizontal androidididradgroup1 snippet tablerow snippet tablelayoutobviously i did not learn the first time because i ran into a wall again i was hoping that the radio buttons in different table rows would notice that they were part of the same radio group gave each group the same id but this did not workis there any way i can group all of these buttons into a single radio group and still maintain my 3x3 structure 3 rows 3 radio buttons in each row,['android'] +50223,is it reasonable to enforce that unit tests should never talk to a live databasewebservice my team continues to find more and more value in the unit tests we write we do not generally unit test the data access layers of our applications as they do not contain logic in my experience weve run into significant performance issues and nonreproducible errors as a result of letting developers write unit tests that talk to live databases or webservices and as a result more and more developers are creating mocks that feed data to these unit tests taking this approach has increased the speed of the tests and isolated testing to the logic rather than testing the connectionretrieval at the same time i am wondering if this sounds reasonable to enforce as a coding standard what are the proscons regarding unit testing live databaseswebservices that i am missing,['.net'] +50237,how does truefalse work in php i wonder how php handles truefalse comparison internally i understand that true is defined as 1 and false is defined as 0 when i do ifa echo true it echos true how does php recognize a as 1,['php'] +50251,c allocate block of t without calling constructor i do not want constructor called i am using placement newi just want to allocate a block of tmy standard approach ist data mallocsizeoft numhowever i do not know if datai is taligned furthermore i do not know if this is the right c wayhow should i allocate a block of t without calling its constructor,['c++'] +50267,how do i load a contact photo i am having trouble loading a photo for a contact in android i have googled for an answer but so far have come up empty does anyone have an example of querying for a contact then loading the photo so given a contacturi which comes from an activity result called usingstartactivityforresultnew intentintentaction pickcontactscontractcommondatakindsphonecontent uripick contact request is contentcomandroidcontactsdata1557the loadcontact works fine however when i call the getphoto method i get a null value for the photo inputstream it is also confusing because the uri values are different the contactphotouri evaluates tocontentcomandroidcontactscontacts1557see the comments inline in the code belowclass contactaccessor retrieves the contact information public contactinfo loadcontactcontentresolver contentresolver uri contacturi contacturi contentcomandroidcontactsdata1557 contactinfo contactinfo new contactinfo load the thisplay name for the specified person cursor cursor contentresolverquerycontacturi new stringcontacts id contactsthisplay name phonenumber contactsphoto id null null null try if cursormovetofirst contactinfosetidcursorgetlong0 contactinfosetthisplaynamecursorgetstring1 contactinfosetphonenumbercursorgetstring2 finally cursorclose return contactinfo returns info for contactpublic bitmap getphotocontentresolver contentresolver long contactid uri contactphotouri contenturiswithappendedidcontactscontent uri contactid contactphotouri contentcomandroidcontactscontacts1557 inputstream photodatastream contactsopencontactphotoinputstreamcontentresolvercontactphotouri always null bitmap photo bitmapfactorydecodestreamphotodatastream return photopublic class contactinfo private long id private string thisplayname private string phonenumber private uri photouri public void setthisplaynamestring thisplayname thisthisplayname thisplayname public string getthisplayname return thisplayname public void setphonenumberstring phonenumber thisphonenumber phonenumber public string getphonenumber return phonenumber public uri getphotouri return thisphotouri public void setphotouriuri photouri thisphotouri photouri public long getid return thisid public void setidlong id thisid id clearly i am doing something wrong here but i cannot seem to figure out what the problem is thanks,['android'] +50269,how to add all items in a string array to a vector in java my code looks like this vectorstring my vectornew vectorstringstring my arraynew string100for int i0i100i my arrayiitem imy vectoraddallmy arraybut i got an error message whats the right way to do it without looping to add each item frank,['java'] +50270,what is a good way to test that a java method is synchronized i have several classes that implement some interface the interface has a contract that some methods should be synchronized and some should not and i want to verify that contract through unit tests for all the implementations the methods should use the synchronized keyword or be locked on this very similar to the synchronizedcollection wrapper that means i should be able to observe it externallyto continue the example of collectionssynchronizedcollection if i have one thread calling iterator i should still be able to get into methods like add with another thread because iterator should not do any locking on the other hand i should be able to synchronize on the collection externally and see that another thread blocks on addis there a good way to test that a method is synchronized in a junit test i want to avoid long sleep statements,['java'] +50289,how is my id being generated with jpa using hibernate with the oracle 10g dialect i have some codeidsequencegeneratorname something seqgeneratedvaluestrategy generationtypesequence generator something seqcolumnname something nullable falseprivate long idhow is hibernate providing my id i see in my database there a single sequence named hibernate sequence and no other hibernate special tables,['java'] +50295,loop reversal in c speeds up app we are working on a video processing application using emgucv and recently had to do some pixel level operation i initially wrote the loops to go across all the pixels in the image as followsfor int j 0 j imgwidth j for int i 0 i imgheight i pixel operation code the time to execute the loops was pretty bad then i posted on the emgucv forum and got a suggestion to switch the loops like thisfor int j imgwidth j 0 for int i imgheight i 0 pixel operation code i was very surprised to find that the code executed in half the timethe only thing i can think of is the comparison that takes place in the loops each time accesses a property which it no longer has to is this the reason for the speed up or is there something else i was thrilled to see this improvement and would love it if someone could clarify the reason for this,['c#'] +50302,how to alter a column datatype for derby database i am trying to alter a datatype for a derby db column the current price column is set as decimal50 i would like to alter it to decimal72 i did this alter table item alter column price set data type decimal72but it did not work and showing the errorerror only columns of type varchar may have their length altered may i know how is it possible to alter it thank you,['sql'] +50324,sorting only using the lessthan operator compared to a trivalue compare function in cstl sorting is done by using only the lessthan operator altough i have no idea how the sorting algorithms are actually implemented i assume that the other operations are created implicitea b equals b a truea b equals a b b acompared to using a trivalue compare function like for example java is this good for performance or why was this design decision mademy assumption is that any trivalue compareto function still has to implement these comparissons in itself resulting in the same performanceby trivalue compare function i mean a compare function which returns 1 0 and 1 for less than equal and higher than,['c++'] +50328,how to get all input elements in a form with htmlagilitypack without getting a null reference error example html htmlbody form idform1 input namefoo1 valuebar1 other elements form form idform2 input namefoo2 valuebar2 other elements form bodyhtmltest codehtmldocument doc new htmldocumentdocloaddtesthtmlforeach htmlnode node in docgetelementbyidform2selectnodesinput consolewritelinenodeattributesvaluevalue the statement docgetelementbyidform2selectnodesinput gives me a null reference anything i did wrong thanks,"['c#', 'html']" +50330,return statements at the end of a javascript function i have seen in many times in javascript code people add a return true at the end although not necessary does anyone know why var globalstringfunction dosomething globalstring globalstring do something some codes to do something more finally adding a return true return true,['javascript'] +50333,objectivec when to use self this is unmodified code from apples iphone utility aplication template voidapplicationdidfinishlaunchinguiapplication application mainviewcontroller acontroller mainviewcontroller alloc initwithnibnamemainview bundlenil selfmainviewcontroller acontroller acontroller release mainviewcontrollerviewframe uiscreen mainscreenapplicationframe window addsubviewmainviewcontroller view window makekeyandvisiblewhen mainviewcontroller is assigned to acontroller the self keyword is specified selfmainviewcontroller acontrollerhowever when the mainviewcontrollers frame is set the self keyword is not required mainviewcontrollerviewframe uiscreen mainscreenapplicationframeif i remove the self keyword from the first example the program crashes with the messageobjc1296 freedid message view sent to freed object0x3b122d0if i add the self keyword to the second example the program runs finecan anyone explain why self is needed in the first case but not the second i am assuming that in both cases mainviewcontroller is referring to the same instance variable,"['iphone', 'objective-c']" +50343,thisplayinlineblock and textindent i am experiencing a problem with the following code in some versions of internet explorericonautente backgroundimageurlstyleimagesspritecommonpng icona utentepngbackgroundposition117px 15pxtextindent90pxwidth20pxheight23pxthisplayinlineblocka idiconautente hrefadminindexphpadminain firefox ie7 and ie8 under vista i see background and no text as expected in ie6 and ie8 under xp the whole image is indented not text so the image is not shownwhat should be the right behavior is there a workaround,['css'] +50345,embedding mercurial revision information in visual studio c projects automatically original problemin building our projects i want the mercurial id of each repository to be embedded within the products of that repository the library application or test applicationi find it makes it so much easier to debug an application being run by customers 8 timezones away if you know precisely what went into building the particular version of the application they are using as such every project application or library in our systems implements a way of getting at the associated revision informationi also find it very useful to be able to see if an application has been compiled with clean unmodified changesets from the repository hg id usefully appends a to the changeset id when there are uncommitted changes in a repository so this allows us to easily see if people are running a clean or a modified version of the codemy current solution is detailed below and fulfills the basic requirements but there are a number of problems with itcurrent solutionat the moment to each and every visual studio solution i add the following prebuild event command line commandscd projectdirhgidi also add an hgidbat file to the project directoryecho offtype hgidpre hgidcsfor f delims a in hg id do nul hgidcs set p aecho hgidcsecho hgidcsecho hgidcsalong with an hgidpre file which is defined asnamespace mynamespace summary auto generated mercurial id class summaryinternal class hgid summary mercurial version id is modified named branchsummary public const string version when i build my application the prebuild event is triggered on all libraries creating a new hgidcs file which is not kept under revision control and causing the library to be recompiled with with the new hg id string in versionproblems with the current solutionthe main problem is that since the hgidcs is recreated at each prebuild so every time we need to compile anything all projects in the current solution are recompiled since we want to be able to easily debug into our libraries we usually keep many libraries referenced in our main application solution this can result in build times which are significantly longer than i would likeideally i would like the libraries to compile only if the contents of the hgidcs file have actually changed as opposed to having been recreated with exactly the same contentsthe second problem with this method is it is dependence on specific behaviour of the windows shell i have already had to modify the batch file several times since the original worked under xp but not vista the next version worked under vista but not xp and finally i managed to make it work with both whether it will work with windows 7 however is anyones guess and as time goes on i see it more likely that contractors will expect to be able to build our apps on their windows 7 boxenfinally i have an aesthetic problem with this solution batch files and bodged together template files feel like the wrong way to do thismy actual questionshow would you solvehow are you solving the problem i am trying to solvewhat better options are out there than what i am currently doingrejected solutions to these problemsbefore i implemented the current solution i looked at mercurials keyword extension since it seemed like the obvious solution however the more i looked at it and read peoples opinions the more that i came to the conclusion that it was not the right thing to doi also remember the problems that keyword substitution has caused me in projects at previous companies just the thought of ever having to use source safe again fills me with a feeling of dread 8also i do not particularly want to have to enable mercurial extensions to get the build to complete i want the solution to be self contained so that it is not easy for the application to be accidentally compiled without the embedded version information just because an extension is not enabled or the right helper software has not been installedi also thought of writing this in a better scripting language one where i would only write hgidcs file if the content had actually changed but all of the options i could think of would require my coworkers contractors and possibly customers to have to install software they might not otherwise want for example cygwinany other options people can think of would be appreciatedupdatepartial solutionhaving played around with it for a while i have managed to get the hgidbat file to only overwrite the hgidcs file if it changesecho offtype hgidpre hgidcstfor f delims a in hg id do nul hgidcst set p aecho hgidcstecho hgidcstecho hgidcstfc hgidcs hgidcst nulif errorlevel0 goto okcopy hgidcst hgidcsokdel hgidcstproblems with this solutioneven though hgidcs is no longer being recreated every time visual studio still insists on compiling everything every time i have tried looking for solutions and tried checking only build startup projects and dependencies on run in toolsoptionsprojects and solutionsbuild and run but it makes no differencethe second problem also remains and now i have no way to test if it will work with vista since that contractor is no longer with us if anyone can test this batch file on a windows 7 andor vista box i would appreciate hearing how it wentfinally my aesthetic problem with this solution is even stronger than it was before since the batch file is more complex and this there is now more to go wrongif you can think of any better solutions i would love to hear about them,['c#'] +50361,javascript date difference bug edit it is not a bug as martin pointed out i am just crossing the daylight saving time hence the 1h differencei want to calculate the difference in days between mar 29 2010 and mar 09 2010 so i have the following codenew date2010 2 29gettime new date2010 2 8gettime 86408640 is the number of milliseconds in a day and the difference between the dates is returned in milliseconds so this should work only it does not quite i get2095832it is the difference between those 2 dates that is wrong it is supposed to be 181440 21 days times 8640 but it actually is 181080moreover if i change the difference tonew date2010 2 28gettime new date2010 2 7gettime 8640the same difference only shifted one day back i get normal resultsthis happens only if we try to get xy where x is after march 29 2010 and y is before march 29 2010i get this on safari 4 and firefox 36 on mac as well as ie 8 on windows 7 have not tried other browsersam i doing something wrong or is this a known bug,['javascript'] +50370,seeking stdout in php i have a php script that is running in cli and i want to thisplay the current percent progress so i was wondering if it is possible to update the stdout to thisplay the new percentwhen i use rewind or fseek it just throws an error message,['php'] +50374,multimodule maven project if i have 6 modules in my project is it possible to build only one out of six without commenting out others editsubmodule will not work itselft because or parent tags i need to install the parent first to make it build how can i do it without installing parent,['java'] +50379,accessing functions bound to event handlers with jquery with jquery you can bind functions to an event triggered on a dom object using bind or one of the event handler helper functionsjquery have to store this internally somehow and i wonder if is it possible given a dom object to find out which events have been bound to the object and access those functions etc the desired return result could look something like this click function1 function2 change function3 blur function4 function5 function6,['jquery'] +50382,android is it possible to have 3g and wifi connections at the same time i was wondering does anyone know if its possible to open a wifi and a 3g connection at the same time on androidis there any way to control access to both wifi and 3ggprs data connections and use them at the same time,['android'] +50391,do spurious wakeups affect threadsleep do spurious wakeups affect calls to threadsleepx obviously the timer is not 100 precise leading to minor inaccuracies in wakeup times but is it affected by the spurious wakeup problem,['java'] +50392,zodb in real life writing an app in python and been playing with various orm setups and straight sql all of which are ugly as sini have been looking at zodb as an object store and it looks a promising alternative would you recommend it what are your experiences problems and criticism particularly regarding developers perspectives scalability integrity longterm maintenance and alternatives anyone start a project with it and ditch it whywhilst the ideas behind zodb pypersyst and others are interesting there seems to be a lack of enthusiasm around for them,['python'] +50394,accentinsensitive sorting in mysql i am trying to achieve accent and caseinsensitive sorting in mysql following the instructions in the manual this is supposed to work with the utf8 character set and utf8 general ci collation when i follow the example in the manual under collations for unicode multibyte character sets i do not get the same resultswelcome to the mysql monitor commands end with or gyour mysql connection id is 679877server version 5141log mysql community server gpl by remitype help or h for help type c to clear the current input statementmysql set names utf8 collate utf8 general ciquery ok 0 rows affected 0 secmysql select a a a a a a a a a a a a 1 0 0 1 row in set 0 secmysql in the example in the manual those are all 1it also fails to treat accented characters equally when i try to set the collation directly in a query in this example the table is using latin1 and i am converting to utf8mysql select from test k cardenas cardozo corbin cabrero mysql select k from test order by convertk using utf8 collate utf8 general ci k cabrero cardozo corbin cardenas 4 rows in set 0 secit should be ignoring the accent over the a in the last entry and sorting it second any ideas what i am doing wrong,['mysql'] +50404,visual studio can be a breakpoint called from code i have a unit test project based on unittest i usually put a breakpoint to the last line of the code so that the i can inspect the console when one of the tests fails and unittestrunalltests if and 0 place breakpoint here return n return nbut i have to reinsert it each time i checkout the code anew from svn is it possible tosomewhat place the breakpoint by the compiler and unittestrunalltests if and 0 place breakpoint here ifdef msvc breakpointendif return n return n,['c++'] +50405,how to load a separate application settings file dynamically and merge with current settings there are questions pertaining to reading settings from a separate config file and others similar to it but my question is specific to application property settings ie myapplicationpropertiessettings see xml file below and how to load them dynamically i tried the method in this post which involved refreshing the entire appsettings section of the main config file but my adaptation threw exceptions because i was not replacing the appsettings sectionvar config configurationmanageropenexeconfigurationconfigurationuserlevelperuserroamingandlocal have tried the other configurationuserlevels to no availconfigappsettingsfile myruntimeconfigfilepathconfigsaveconfigurationsavemodemodified throws configurationerrorsexceptionconfigurationmanagerrefreshsectionusersettingsthe configurationerrorsexceptionmessage is the root element must match the name of the section referencing the file appsettings cmyfilexml line 2 the file isxml version10 encodingutf8configuration usersettings myapplicationpropertiessettings setting namesinewavefrequency serializeasstring value6value setting setting namesinewaveamplitude serializeasstring value6value setting myapplicationpropertiessettings usersettingsconfigurationis there a way to import the values from this file into the myapplicationpropertiessettingsdefault class with the framework handling all xml deserialization like it does when the config file is loaded on application startup,['.net'] +50412,should i set the cachecontrol header when serving up files or not i am serving up some files via an httpmodule in aspnet i want to know if there are any benefits to setting or not setting the cachecontrol header to something like nocacheedit the reason i am curious about this is because we ran in to a problem where serving up office documents over an ssl session in ie results in an error with cache control set to nocache that is to say you cannot download office docs over ssl in ie if you have set cachecontrol to nocachebasically i want to not include the cachecontrol header but wonder if it will cause problemsedit 2 well the cachecontrol header is out i tried the suggestions below but had some problems any time i add an expires header or change cachecontrol at all when i try and open an office 2007 document it tries to open it as a zip i know that they are really zip files under the covers but when i do not use an expires header or cachecontrol ie opens them just fine as office documents unfortunately i do not have time to try and figure all this out as code freeze is ten minutes from now thanks everyone for trying to help,"['c#', 'asp.net']" +50413,jquery hasparent the jquery has method effectively selects all elements where they have particular descendantsi want to select elements based on the fact they have particular ancestors i know about parentselector and parentsselector but these select the parents and not the children with the parentsso is there an ancestor equivalent of hasnote i already have the context of an element further down the hierarchy and i will be selecting based on this so i cannot do a top down queryupdatei have obviously explained myself really badly here so i will try and clarifyul classx li1li li2li li3liulul classy li4li li5li li6liuli have a jquery object that already consists of elements 234 and 5 i want to select those elements who have a parent with the class xhope that makes more sense,"['javascript', 'jquery']" +50427,how do i specify css classes for specific rows in a gridview i am creating a sharepoint web part in c and part of it outputs a gridview control to the page while i can get fairly extensive control over the way it is thisplayed by setting the css class of the gridview itself what i would really like to do is be able to specify classes to certain specific td elements i am not sure how to go about doing this or if it would be done at the time that the gridview is being populated with rows or at the time the gridview is added to the pagein pseudocode what i had essentially envisioned was to be able to say something like gridviewrow4cssclass header which would set the td of the fifth row in the gridview to the class headeri have looked into using the rowdatabound event so i just used the following to test itprotected void outputgrid1 rowdataboundobject sender gridviewroweventargs e erowcssclass outputheaderit is probably my misunderstanding of how to use that properly but it does not appear to do anything i thought it would set all of the rows to the class header and if it had i was going to work on my logic from there but i cannot even get that to work thanks for any help anyone can provide,"['asp.net', 'css']" +50434,marker recognition on android recognising rubiks cubes i am developing an augmented reality application for android that uses the phones camera to recognise the arrangement of the coloured squares on each face of a rubiks cubeone thing that i am unsure about is how exactly i would go about detecting and recognising the coloured squares on each face of the cube if you look at a rubiks cube then you can see that each square is one of six possible colours with a thin black border this lead me to think that it should be relativly simply to detect a square possibly using an existing marker detection apimy question is really has anybody here had any experience with image recognition and android ideally i would like to be able to implement and existing api but it would be an interesting project to do from scratch if somebody could point me in the right direction to get startedmany thanks in advance,['android'] +50437,java scanning string for a pattern this is probably a quicky why does this code not return anythingimport javautilscannerpublic class mainclass public static void mainstring args try scanner sc new scannerasda asa adad string pattern az while schasnextpattern systemoutprintlnscnextpattern scclose catch exception e eprintstacktrace,['java'] +50438,how can i start the rails console and use the testing database exclusively i would like to start the rails console and create database entries in a database that is not the default database such as the testing database i would appreciate any help,['ruby-on-rails'] +50439,slider control for volume jqueryjavascript i am looking for a fancy slider control using jqueryjavascript the native jquery slider is rather bland for this requirement the slider will be used to specify the volume in the increments of 5 so this slider should only let user slide in increments of 5one nice to have feature is to be able to show label above the slider position indicating what volume the user has selected,"['javascript', 'jquery']" +50442,is there a class like dictionary in c but for just keys no values i guess another way to phrase this would be is there a class like list in c but optimized for checking whether a particular value is present i am sure for a small set of values listcontains would probably be fine but what if i have a set of thousands or millions of values and wanted to find out whether a certain value was in iti have implemented this kind of thing in the past by creating a dictionaryobject int and setting the value to 0 for every key but this feels really clunky and now there is stack overflow where my stupid question can be transformed into education for thousands dozens even so here it isi am not even sure what such a class would be called other than maybe set so obviously searches on the topic have been challenging,['c#'] +50443,xsdexe schema to class for use with wcf i have created a schema as an agreed upon interface between our company and an external company i am now creating a wcf c web service to handle the interface i ran the xsd utility and it created a c class the schema was built in biztalk and references other schemas so allinall there are over 15 classes being generated i put datacontract attribute in front of each of the classes do i have to put the datamember attribute on every single propertywhen i generate a test client program the proxy does not have any code for any of these 15 classes we used to use this technique when using asmx services but not sure if it will work the same with wcf if we change the schema we would want to regenerate the wcf class and then we would haev to each time redecorate it with all the datamember attributes is there an newer tool similar to xsdexe that will work better with wcf thanksneal walters solution buried in one of saunders answercomments add the xmlserializerformat to the interface definition operationcontract xmlserializerformat add this line transaction submittransactiontransaction transactionintwo notes 1 after i did this i saw a lot more xsds in the my proxy service reference test client program but i did not see the new classes in my intellisense 2 for some reason until i did a build on the project i did not get all the classes in the intellisense not sure why,['c#'] +50465,how to pass variable arguments to another method i have googled and came to know that how to use the variable arguments but i want to pass my variable arguments to another method i m getting errors how to do that void amethodnsstring a self anothermethoda i m doing this but getting error how to pass complete vararg to anothermethod,"['iphone', 'ios', 'objective-c']" +50481,jquery loading images with complete callback i saw a comment on ben nadels blog where stephen rushing posted a loader but i cannot figure out how i can pass the selectors and parameteri think i also need a completecallback errorcallback functionsfunction imgloadimg completecallback errorcallback if img null completecallback null var loadwatch setintervalwatch 500 function watch if imgcomplete clearintervalloadwatch completecallbackimg else if typeof errorcallback function errorcallback then call this from anywhereimgloadimgselector0 functionimg imgfadeinhtmla href classtnclick img idmyimage srcimages001jpg ajsdocumentreadyfunction var newimage images002jpg myimagecssthisplaynone atnclickclickfunction imgload here,['jquery'] +50487,centralized logging for many java apps syslog vs jms vs http vs local file i what all my applications logs to be centralized ideally in near realtime we will use a log4 appender which one should i usesend log event in a jms queuesyslog syslogng write to a localfile and use rsync every 3second to replicate the log do a post to a centralized rest http servicewhich one are you using,['java'] +50496,seeking good sources for icons artwork etc has anyone got a good source for icons that can be used in an applicationi am thinking of things like pushpins scope sights house car shop and other small graphics you might overlay on a map or picturemost people just rip them off from the web but i am looking for an honest sourcea while ago i found a website marketplace where you could commission stuff from graphic artists does anyone have any links for these the sort of thing i mean is like this but those guys have not got critical mass yet or these guys but they seem a bit high endthanks for any leads,"['iphone', 'android']" +50503,using memcache with php i want to start using memcache with php on ubuntu 910 there are lots of info online which appear to show how to do this suprisingly though none of the articles i have seen so far explicitly state whether you need to run the memcache process before attempting to use it or whether by simply calling new memcache via the php client library a process will be spawned if not already runningfrom the various docs i have read on this so far these are the steps that i think make senseinstall memcache on your machine there are several docs showing how to do thismodify your phpini file and set the memcache related constsflags to the values that make sense for your environmentcreate an init script in inid to start memcache as a daemonrestart apache daemonnumber 3 is the part that i need confirmation on because none of the docs i have seen so far mentions the lifespan of the memcache processcan someone experienced in this confirm if this is the correct stepsalso if i have missed a step let me knowas an aside since i am relatively new to linux i would be grateful if someone could post an example of an init script that would be needed to run the memcache daemon process assuming that the steps i have outlined above are correct,['php'] +50509,are there any mature p2p frameworkslibraries in c i am looking for a reliable p2p framework or library preferrably natively written in c but can also work with something c can interface with have you came across or have worked with a solid one,['c#'] +50521,searching stdstring between a limit if you know the start and end positions in string from where to begin and end the search for example string s stringstringstrings t r i n g s t r i n g s t r i n g 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17how would you find tr in the string specifying the the position to begin search is at index 6 and the position to end the search is index 9i am trying a set a limit of search so it wouldnt go beyond it,['c++'] +50534,ftp server written in c i stumbled accross this site todaywhich is a c command line ftp server unfortunately the download points to the old gotdotnet site which is now closed does anybody know where i could find it or another ftp server implementation written in c thanks,['c#'] +50543,cssjavascripthacking detect visited styling on a link without checking it directly or do it faster than me this is for research purposes on consider the following codestyle divcsshistory a thisplay none color 00ff00 divcsshistory avisited thisplay inline color ff0stylediv idbatch classcsshistory a id1 hrefanything you want herea a id2 hrefanything you want herea etc 20divmy goal is to detect whether foo has been rendered using the visited stylingi want to detect whether foocom is visited without directly looking at 1getcomputedstyle or in internet explorer currentstyle or any other direct method on that elementthe purpose of this is to get around a potential browser restriction that would prevent direct inspection of the style of visited links for instance maybe you can put a subelement in the a tag or check the styling of the text directly etc any method that does not directly or indierctly rely on 1anything is acceptable doing something clever with the child or parent is probably necessarynote that for the purposes of this point only the scenario is that the browser will lie to javascript about all properties of the a element but not others and that it will only render color in visited therefore methods that rely on eg text size or backgroundimage will not meet this requirementi want to improve the speed of my current scraping methodsthe majority of time at least with the jquery method in firefox is spent on documentbodyappendchildbatch so finding a way to improve that call would probably most effective see and for current speed test resultsthe methods i am currently using can be seen at scrapejsto summarize for tldr they areset color or thisplay on visited per above and check each one directly w getcomputedstyleput the id of the link plus a space inside the a tag and using jquerys visible selector extract only the visible text the visited link idsfwiw i am a white hat and i am doing this in consultation with the eff and some other fairly well known security researchers if you contribute a new method or speedup youll get thanked at if you want to be p and potentially in a future published papereta the bounty will be rewarded only for suggestions thatcan on firefox avoid the hypothetical restriction described in point 1 above orperform at least 10 faster on any browser for which i have sufficient current data than my best performing methods listed in the graph at in case more than one suggestion fits either criterion the one that does best winseta 2 i have added widthbased variants of two previousbest test methods reuse noinsert best on firefoxmozilla and mass insert its very close competitor please visit several times from different browsers i will automatically get the speed test results so well find out if it is better than the previous methods and if so by how much thankseta 3 current tests indicate a speed savings using offsetwidth rather than getcalculatedstylecurrentstyle of 2ms 18 in chrome and 24ms 43 in firefox which is not the 10 i wanted for a solid bounty win got an idea how to eke out the rest of that 10,"['javascript', 'css']" +50547,how do clang blocks work looks really coolhoweveri do not understand iti do not see examples iti do not see examples of ideas hard to express in c as is but trivial to express in blockscan anyone enlighten me on this,"['c++', 'objective-c']" +50551,what is the correct syntax for else if i am a new python programmer who is making the leap from 264 to 311 everything has gone fine until i tried to use the else if statement the interpreter gives me a syntax error after the if in else if for a reason i cannot seem to figure outdef functiona if a 1 print 1a else if a 2 print 2a else print 3afunctioninputinputi am probably missing something very simple however i have not been able to find the answer on my own,['python'] +50564,fastest way to draw a screen buffer on the iphone i have a software renderer that i am porting from pc to the iphone what is the fastest way to manually update the screen with a buffer of pixels on the iphone for instance in windows the fastest function i have found is setdibitstodevicei do not know much about the iphone or the libraries and there seem to be so many layers and different types of ui elements so i might need a lot of explanationfor now i am just going to constantly update a texture in opengl and render that to the screen i very much doubt that this is going to be the best way to do it updatei have tried the opengl screen sized texture methodi got 17fpsi used a 512x512 texture because it needs to be a power of twojust the call ofgltexsubimage2dgl texture 2d0512512gl rgbagl unsigned byte basewindowguigetbufferseemed pretty much responsible for all the slow downcommenting it out and leaving in all my software rendering gui code and the rendering of the now non updating texture resulted in 60fps 30 renderer usage and no notable spikes from the cpunote that getbuffer simply returns a pointer to the software backbuffer of the gui system there is no regigging or resizing of the buffer in anyway it is properly sized and formatted for the texture so i am fairly certain the slowdown has nothing to do with the software renderer which is the good news it looks like if i can find a way to update the screen at 60 software rendering should work for the time beingi tried doing the update texture call with 512320 rather than 512512 this was oddly even slower running at 10fps also it says the render utilization is only like 5 and all the time is being wasted in a call to untwiddle32bpp inside opengles i can change my software render to natively render to any pixle format if it would result in a more direct blitfyi tested on a 221 ipod touch g2 so like an iphone 3g on steroidsupdate 2i have just finished writting the coreanimationgraphics method it looks good but i am a little worried about how it updates the screen each frame basically ditching the old cgimage creating a brand new one check it out in somerandomfunction belowis this the quickest way to update the image any help would be greatly appreciated catestappdelegatem catest created by user on 31410 copyright mycompanyname 2010 all rights reservedimport catestappdelegatehimport catestviewcontrollerhimport quartzcorequartzcorehconst void getbytepointervoid info this is currently only called once return info info is a pointer to the buffervoid releasebytepointervoidinfo const void pointer do not care just using the one static buffer at the momentsize t getbytesatpositionvoid info void buffer off t position size t count i do not think this ever gets called memcpybuffer charinfo position count return countcgdataproviderdirectcallbacks providercallbacks 0 getbytepointer releasebytepointer getbytesatposition 0 static cgimageref cgimstatic cgdataproviderref dataproviderunsigned char imagedata const size t imagedatasize 320 480 4nstimer animationtimernstimeinterval animationinterval 10f600fimplementation catestappdelegatesynthesize windowsynthesize viewcontroller voidapplicationdidfinishlaunchinguiapplication application window makekeyandvisible const size t byterowsize 320 4 imagedata mallocimagedatasize forint i0iimagedatasize4i unsigned intimagedatai 0xf00ff just set it to some random init color currently yellow cgcolorspaceref colorspace cgcolorspacecreatedevicergb dataprovider cgdataprovidercreatedirectimagedata imagedatasize providercallbacks currently global cgim cgimagecreate 320 480 8 32 3204 colorspace kcgimagealphanone kcgbitmapbyteorder32little dataprovider 0 false kcgrenderingintentdefault also global probably does not need to be selfwindowlayercontents cgim set the uiwindows calayers contents to the image yay works cgimagereleasecgim we should do this at some stage cgdataproviderreleasedataprovider animationtimer nstimer scheduledtimerwithtimeintervalanimationinterval targetself selectorselectorsomerandomfunction userinfonil repeatsyes set up a timer in the attempt to update the imagefloat col 0voidsomerandomfunction update the original buffer forint i0iimagedatasizei imagedatai unsigned charintcol col2560f600f and currently the only way i know how to apply that buffer update to the screen is to create a new image and bind it to the layer cgcolorspaceref colorspace cgcolorspacecreatedevicergb cgim cgimagecreate 320 480 8 32 3204 colorspace kcgimagealphanone kcgbitmapbyteorder32little dataprovider 0 false kcgrenderingintentdefault cgcolorspacereleasecolorspace selfwindowlayercontents cgim and that currently works updating the screen but i do not know how well it runs voiddealloc viewcontroller release window release super deallocend,['iphone'] +50565,returning an nsstring from an nserror i am using the nsurlrequest class in my iphone app and the method that calls it returns an nsstring which is great for when the connection goes through ok but the issue is i need to convert the nserror into an nsstring so i can either return it back or run some if statements on itany ideas,['objective-c'] +50574,transparent background in grouped uitableview iphone i want to make the grouped uitableview transparent i partially succeded with the following codeuicolor bgcolor uicolor alloc initwithwhite1 alpha00historytablebackgroundcolor bgcolorunfortunately black corners appeared in the rounded cells how to get rid of them,['iphone'] +50576,how check if today is sunday with java calendar i wrote few lines of code which does not work correctly why could sb explain me calendar date calendargetinstance dateset2010 03 7 ifdategetcalendarday of week calendarsunday systemoutprintlnok,['java'] +50579,how to make googletest classes friends with my classes i heard there is a possibility to enable googletest testcase classes friends to my classes thus enabling tests to access my privateprotected membershow to accomplish that,['c++'] +50580,how to use lock in openmp i have two piece of c code running on 2 different coresboth of them wirte to the same file how to use openmp and make sure there is no crash,['c++'] +50593,throttling requests to a ruby on rails api trying to google around for an a rails plugin that will allow for throttling the amount of requests a particular resource gets consumed djangos piston has some open source code for this is there something available out of the box for rails or is it safe to assume that looking at how piston does it and porting it as a rails plugin is something that can be worked on,"['ruby-on-rails', 'ruby']" +50601,suppressing postsharp multicast with attribute i have recently started experimenting with postsharp and i found a particularly helpful aspect to automate implementation of inotifypropertychanged you can see the example here the basic functionality is excellent all properties will be notified but there are cases where i might want to suppress notificationfor instance i might know that a particular property is set once in the constructor and will never change again as such there is no need to emit the code for notifypropertychanged the overhead is minimal when classes are not frequently instantiated and i can prevent the problem by switching from an automatically generated property to a fieldbacked property and writing to the field however as i am learning this new tool it would be helpful to know if there is a way to tag a property with an attribute to suppress the code generation i would like to be able to do something like thisnotifypropertychangedpublic class myclass public double somevalue get set public double modifiedvalue get private set suppressnotify public double onlysetonce get private set public myclass onlysetonce 10,['c#'] +50604,how to change the link color of the current page with css how do i thisplay the link for the current page different from the others i would like to swap the colors of the text and backgroundthis is what i currently havethe html div idheader ul idnavigation li classbioa hrefhomeali li classtheatrea hreftheatreali li classproga hrefprogrammingali li classresumea hrefreacutesumeacuteali li classportfa hrefportfolioali li classcontacta hrefcontactali ul divthe cssnavigation margin0 padding0 background0 height34px liststylenone position relative top 80pxnavigation li floatleft clearnone liststylenonenavigation li a colora60500 thisplayblock fontsize12px textdecorationnone fontweightbold padding10px 18pxnavigation li ahover color640200 backgroundcolor0,"['html', 'css']" +50609,detecting singularities in a graph i am creating a graphing calculator in java as a project for my programming class there are two main components to this calculator the graph itself which draws the lines and the equation evaluator which takes in an equation as a string and well evaluates itto create the line i create a path2ddouble instance and loop through the points on the line to do this i calculate as many points as the graph is wide eg if the graph itself is 500px wide i calculate 500 points and then scale it to the window of the graphnow this works perfectly for most any line however it does not when dealing with singularitiesif when calculating points the graph encounters a domain error such as 10 the graph closes the shape in the path2ddouble instance and starts a new line so that the line looks mathematically correct examplehowever because of the way it scales sometimes it is rendered correctly sometimes it is not when it is not the actual asymptotic line is shown because within those 500 points it skipped over x 20 in the equation 1 x2 and only did x 198 and x 204 which are perfectly valid in that equation examplein that case i increased the window on the left and right one unit eachmy question is is there a way to deal with singularities using this method of scaling so that the resulting line looks mathematically correcti myself have thought of implementing a binary searchesque method where if it finds that it calculates one point and then the next point is wildly far away from the last point it searches in between those points for a domain error i had trouble figuring out how to make it work in practice howeverthank you for any help you may give,['java'] +50614,mono project why is mono faster than net i am surprised to observe that mono is faster than net does anyone know why is it so i was expecting mono to be slower than net but wasnt the case atleast with my experimentsi have a windows xp laptop with net framework i am running centos on vmware vmplayer on top of windows xp i wanted to try mono so grabbed the mono 261 sources and installed it on centos in vmplayer i have writen a test webservice application using net 20 executed it on wndows it worked i transferred the binary to the centos in the vmplayer without any recompilation and executed it on centos hurray it worked life is good but then something else lured my attention the execution of the application on centos seemed to be faster i did not believe my eyes to confirm my observation i eliminated network out of the equation because network reponse depends on lot of external factorsi grabbed small dummy loop code from internet compiled it in visual studio executed in windows as well as centos the results are as followsoutput on windows console is helloconsolebindebughelloconsoleexeresult 2646712e243744360769661 msoutput on centos console is rupertbagvapp mathpow mono helloconsoleexeresult 2646712e24287906286 msif anyone can explain this behaviorthat would be great my laymans understanding is monos implementation is more efficient than net framework even if i assume monos math implementation is only efficient but lot of implementations like processing financial data graphics calculations depend lot on math library it would be more interesting to perform the test on monocentos directly without vmware but that needs some time i will give it a try may be next weekend public static void dummyloop double sumofpowers 0 int count converttoint32configurationmanagerappsettingscount for int i 0 i count i sumofpowers mathpowi 2 consolewritelineresult sumofpowers static void mainstring args stopwatch stopwatch new stopwatch stopwatchstart dummyloop stopwatchstop double ms stopwatchelapsedticks 10 stopwatchfrequency consolewritelinestringconcatmstostring ms consolereadline,"['c#', '.net']" +50618,c winforms smart textbox control to autoformat path length based on textbox width does a smart textbox control winforms exists that can thisplay a path depending on the textbox width for example if the path is short it will thisplay the entire path cmyfiletxt but if the path is long it will thisplay the start and end csomefolderfoomyfiletxt the length of the characters thisplayed should be calculated dynamically by the textbox using its width any commercial or open source suggestions are welcome thank you very much,['c#'] +50628,fancybox resize width i am able to resize the height with the fancyboxresize part but the width just does not update according to the new content thoughts,"['javascript', 'jquery']" +50638,linking a qtdesigner ui file to pythonpyqt so if i go into qtdesigner and build a ui it will be saved as a ui file how can i make this as a python file or use this in python,['python'] +50647,convert rgb value to hsv i have found a method on the internet to convert rgb values to hsv valuesunfortunately when the values are rgb i am getting a nan because of the 00 operationdo you know if there is an implemented method for this conversion in java or what do i have to do when i get the 00 division to get the right value of the hsvhere comes my method adapted from some code on the internetpublic static double rgbtohsvdouble r double g double b double h s v double min max delta min mathminmathminr g b max mathmaxmathmaxr g b v v max delta max min s if max 0 s delta max else s 0 h 1 return new doublehsv h if r max h g b delta between yellow magenta else if g max h 2 b r delta between cyan yellow else h 4 r g delta between magenta cyan h 60 degrees if h 0 h 360 return new doublehsv,['java'] +50659,what is the difference between copy and retain what is the difference between copy and retain for nsstring voidsetstringnsstringnewstring string newstring copy,['objective-c'] +50663,java what does the colon operator do i would look it up myself but i do not even know what it is called would anyone mind explaining what it does i did not know there were multiple times the appeared what does it do in this case herepublic string tostring string cardstring for playingcard c thislist cardstring cardstring c n how would you write this foreach loop a different way so as to not incorporate the,['java'] +50665,what are some of the best javascript memory detecting tools our team is faced with slow but serious javascript memory leak we have read up on the normal causes for memory leaks in javascript eg closures and circular referenceswe tried to avoid those pitfalls in the code but it likely we still have unknown mistakes lefti started my search for available tools but would like input from people with actual experience with these toolssome of the tools i found so far but have no idea how good and useful they would be for our problemsievedripjavascript memory leak detectorour search is not limited to free tools it will be a bonus but more importantly something that will get the job donewe do the following in our javascript code ajax calls to a net wcf backend that send back json datamanipulate the domkeep a fairly sized object model in the javascript to store current state,['javascript'] +50667,how to get type of tkey and tvalue given a dictionary type i want to get type of tkey and tvalue given a dictionarytkeytvalue typeeg if type is dictionaryint32string i want to know how to get keytype typeofint32 and valuetype typeofstring,['c#'] +50691,why callback functions needs to be static when declared in class i was trying to declare a callback function in class and then somewhere i read the function needs to be static but it did not explain whyinclude iostreamusing stdcoutusing stdendlclass testpublic test void my funcvoid f cout in my function endl f invoke callback function static void callback func cout in callback function endlint main test obj objmy funcobjcallback func,['c++'] +50696,python differences between elements of a list given a list of numbers how to find differences between every ith and i1th of its elements should one better use lambda or maybe lists comprehensionexamplegiven a list t136 it is to find a list v23 because 312 633 etc,['python'] +50702,how to set the tabs in the bottom of the screen in android i am working on tabactivityi wanna show my tabwidget below the tabcontentframelayouti done it by setting the tabwiget tab attribute as androidgravitybottombut the framelayout cant align with those tabsthat is the tabs are shown at the bottom of the screen and overlap the framelayouthow to do that if set some height value to the framelayout it not optimized for all screens of android what can i do any idea,['android'] +50718,0 in 1 2 true why excerpt from my javascript console 0 in 1 2truewhy,['javascript'] +50729,what is the advantage of currying in c achieving partial function what is the advantage of currying in cwhat is the advantage of achieving partial function application on a curried function,['c#'] +50742,why does this extension method throw a nullreferenceexception in vbnet from previous experience i had been under the impression that it is perfectly legal though perhaps not advisable to call extension methods on a null instance so in c this code compiles and runs code in static clastatic bool isnullthis object obj return obj null code elsewhereobject x nullbool exists xisnullhowever i was just putting together a little suite of example code for the other members of my development team we just upgraded to net 35 and i have been assigned the task of getting the team up to speed on some of the new features available to us and i wrote what i thought was the vbnet equivalent of the above code only to thiscover that it actually throws a nullreferenceexception the code i wrote was this code in module extension function isnullbyval obj as object as boolean return obj is nothingend function code elsewhere dim exampleobject as object nothingdim exists as boolean not exampleobjectisnullthe debugger stops right there as if i would called an instance method am i doing something wrong eg is there some subtle difference in the way i defined the extension method between c and vbnet is it actually not legal to call an extension method on a null instance in vbnet though it is legal in c i would have thought this was a net thing as opposed to a languagespecific thing but perhaps i was wrongcan anybody explain this one to me,['.net'] +50750,why does not the c default destructor destroy my objects the c specification says the default destructor deletes all nonstatic members nevertheless i cannot manage to achieve thati have thisclass and public n stdcout destroying object of type n class m public m and new n m this should happen by default delete n private n nthen this should print the given message but it does notm m new mdelete m this should invoke the default destructor,['c++'] +50769,determine processor support for sse2 i need to do determine processor support for sse2 prior installing a software from what i understand i came up with thisbool testsse2char szerrormsg try asm xorpd xmm0 xmm0 executing sse2 instruction pragma warning suppress 6320 except exception execute handler if exception code status illegal instruction tcscpy sszerrormsgmsgsize tstreaming simd extensions 2sse2 is not supported by the cpurn unable to launch app return false tcscpy sszerrormsgmsgsize tstreaming simd extensions 2sse2 is not supported by the cpurn unable to launch app return false return truewould this work i am not really sure how to test since my cpu supports it so i do not get false from the function callhow do i determine processor support for sse2,['c++'] +50778,html colspan in css i am trying to construct a layout similar to the following where the bottom is filling the space of the upper rowif this were an actual table i could easily accomplish this with td colspan3 but as i am simply creating a tablelike layout i cannot use table tags is this possible using css,['css'] +50790,does filehandle get closed automatically in python after it goes out of scope if i do the following does filehandle get closed automatically as it goes out of scope in pythondef read contentsfile path return filefile pathreadif it does not how can i write this function to close the scope automatically,['python'] +50791,is there an open source depository of custom classes for the iphone i am trying to learn objectivec for xcodei was wondering if there was an open source depository for custom classesthings that programmers reuse ie playing card class or peer to peer methods i have searched google but so far have not seen any type of site,"['iphone', 'objective-c']" +50805,iphone perform action when uitextfield uisearchbars clear button is pressed is it possible to gain access to a delegate method that will allow additional actions to be performed when the clear button is pressed on a uitextfield uisearchbarthanks,['iphone'] +50808,how to test for the appearance of a toast message would anyone know how to test for the appearance of a toast message on an activityi am using code similar to what the op posted on this question for testing my program flow from one activity to the next i would also like to be able to test for toast messages on particular activities,['android'] +50809,how to start an intent by passing some parameters to it i would like to pass some variables in the constructor of my listactivity i start activity via this codestartactivitynew intent this viewcontactsclassi would like to use similar code but to pass two strings to the constructor how is possible,['android'] +50810,post xml to spring rest server returns unsupported media type i am trying to create a simple spring based webservice that supports a post with xml contentin spring i define an annotationmethodhandlerbean idinboundmessageadapter classorgspringframeworkwebservletmvcannotationannotationmethodhandleradapter property namemessageconverters utillist bean classorgspringframeworkhttpconverterxmlmarshallinghttpmessageconverter property namemarshaller refxmlmarshaller property nameunmarshaller refxmlmarshaller bean utillist property beanand a jaxb based xml marshallerbean idxmlmarshaller classorgspringframeworkoxmjaxbjaxb2marshaller property namecontextpaths array valuecomcompanyschemavalue array property property nameschemas array valueclasspathcorexsdvalue array property beanmy controller is annotated as follows where resource is a class autogenerated by jaxbrequestmappingmethod post value resource public resource createresourcerequestbody resource resource do work the result of a webservice call is always http11 415 unsupported media type here is an example service callhttppost post new httpposturipostaddheaderaccept applicationxmlpostaddheadercontenttype applicationxmlstringentity entity new stringentityrequest utf8entitysetcontenttypeapplicationxmlpostsetentityentityit seems to me that i am setting the correct media type everywhere possible anyone have an ideasedit after further debugging it looks as though it never gets as far as trying to unmarshal the object i do not quite understand the black magic behind how the annotationmethodhandler knows that something of type applicationxml should go to the marshallinghttpconverter can anyone shed any light on that,['java'] +50814,can i get parameter namesvalues procedurally from the currently executing function i would like to do something like thispublic myfunctionint integerparameter string stringparameter do this logparameters instead of this logdebugintegerparameter integerparameter stringparameter stringparameterpublic logparameters look up 1 level in the call stack if possible programmatically loop through the functions parametersvalues and log them to a file with the function name as well if i can pass a methodinfo instead of analyzing the call stack greati am not even sure what i want to do is possible but it would be very nice to be able to automatically output parameter namesvalues at runtime to a file without explicitly writing the code to log themis it possible,"['c#', '.net']" +50819,how do i override getattr in python without breaking the default behavior i want to override the getattr method on a class to do something fancy but i do not want to break the default behaviorwhats the correct way to do this,['python'] +50825,jquery validate that text field is numeric i have simple issue i would like to check a field to see if its an integer if it is not blank i am not using any additional plugins just jquery my code is as followsiffieldval iffieldvalmatch01909 errors field must be numericbr success false it does not seem to work where am i going wrongthe error i receive is val is not an objectupdate turned out that the real issue was that i had my element name set and not the id,['jquery'] +50845,accented characters in matplotlib is there a way to get matplotlib to render accented chars aetcfor instance i am trying to use accented characters on set yticklabels and matplotlib renders squares instead and when i use unicode it renders the wrong charactersis there a way to make this workit turns out you can use uaa but first you have to set the file encoding using the magic encoding coding utf8 after that matplotlib correctly rendersuai also learned that you can useimport matplotlibfont manager as fmfp1fmfontpropertiesfnamepathtosomefontfaxtitleafontpropertiesfp1in case you need to render a characters that matplotlib does not have,['python'] +50864,add safari bookmark from iphone app i would like to have my application be able to add bookmarks to safari programmatically is this possible,"['iphone', 'objective-c']" +50874,javascript regex hangs using v8 im using this regex to get the contents of a tag in a filevar regex new regexptagmainstagmainthis causes the v8 engine to hang indefinitelynow if i use new regexptagmainsstagmain all is goodanyone have an idea why the first one takes too long,['javascript'] +50887,confused about getchar function i am confused about getchars role in the following code i mean i know it is helping me see the output window which will only be closed when i press the enter keyso getchar is basically waiting for me to press enter and then reads a single characterwhat is that single character this function is reading i did not press any key from the keyboard for it to readnow when it is not reading anything why does it not give an error saying hey you did not enter anything for me to readinclude stdiohint main printf blah n getchar return 0,['c'] +50896,increase the size of sql compact 35 sdf file using c i am using sql compact35 as my db with c net what is the maximum size of sdf that i can give is there any way to programatically increase the maximum size of the sdf file if so how,['c#'] +50897,is there a standard way to implement software activation for net i have been looking at software activation systems for net and frankly found the websites out there underwhelming i am wondering if there is a standard way to do it in net if not does anyone with experience of them have a recommendationi understand the arguments for and against activation systems but still need to evaluatethanks,['.net'] +50898,python nonblocking console input i am trying to make a simple irc client in python as kind of a project while i learn the languagei have a loop that i use to receive and parse what the irc server sends me but if i use raw input to input stuff it stops the loop dead in its tracks until i input something obviouslyhow can i input something without the loop stoppingthanks in advancei do not think i need to post the code i just want to input something without the while 1 loop stoppingedit i am on windows,['python'] +50910,c using keyword nested in single line usually i was doing something like that just a exampleusing stream xmlstream clientopenreadxmlurl using xmltextreader xmlreader new xmltextreaderxmlstream is not better to do justusing xmltextreader xmlreader new xmltextreaderclientopenreadxmlurlbut i am not sure if in this short syntax all resources will be thisposed stream or only xmltextreaderthanks in advance for your answer,['c#'] +50917,is it possible to format a number to 2 decimal places with smarty php is it possible to format a number to 2 decimal places with smarty phpthanks,['php'] +50927,get application path without using httpcontext aspnet how to do iti do not want to use thishttpcontextcurrentservermappathis there a similar function that i can call without requiring a httpcontextfor example if a start a thread doing some stuff i cant use the httpcontext but i still need to get the path of the app and no i cannot pass the context as an argument or read it from a shared var,['asp.net'] +50943,orderby not ordering numbers correctly c i am writing an app for my company and am currently working on the search functionality when a user searches for an item i want to thisplay the highest version which is stored in a databasethe problem is the version is stored as a string instead of int and when i do an orderbyqqversion on the results they are returned like1101123obviously 2 comes before 10is there a way for me to cast the version as an integer or is there a simple icomparer out there i could not find anything substantial thus fari tried doing thisvar items from r in results select rorderbyq int32parseqversionthis compiles but does not work,['c#'] +50974,when should i use this in a class i know that this refers to a current object but i do not know when i really need to use it for example will be there any difference if i use x instead of thisx in some of the methods may be x will refer to a variable which is local for the considered method i mean variable which is seen only in this methodwhat about thismethod can i use it should i use it if i just use method will it not be by default applied to the current object,['java'] +50978,cancelling background tasks in c when my c application closes it sometimes gets caught in the cleanup routine specifically a background worker is not closing this is basically how i am attempting to close it private void app formclosingobject sender formclosingeventargs e backgroundworker1cancelasync while backgroundworker1isbusy gets stuck here is there a different way that i should be doing this i am using microsoft visual c 2008 express edition thanksadditional informationthe background worker does not appear to be exiting this is what i haveprivate void backgroundworker1 doworkobject sender doworkeventargs e while backgroundworker1cancellationpending do something i have also modified the cleanup codeprivate void app formclosingobject sender formclosingeventargs e while backgroundworker1isbusy backgroundworker1cancelasync systemthreadingthreadsleep10 is there something else that i should be doing,['c#'] +50979,thread deadlock example in c can someone give an example of how thread deadlock can be caused in the c language,['c#'] +50985,programmatic reading of pdfs in c i see many questions and answers about using c to generate pdf files i have a related but different taski have a large number of pdf files already created and i would like to validate certain parts of the content with regular expressions regexs i want to open the pdfs in c and be able to read out the text in something approaching a linear fashionif headers footers any sidebars etc get skipped or read out of order it does not matter i am just after as much of the mainbody text as i can retrievecan you point me towards tools libraries apis etc that will enable me to programmatically read text in pdf files,['c#'] +50987,how to preprocess csv data for fastercsv were having a significant number of problems creating a bulk upload function for our little app were using the fastercsv gem to upload data to a mysql database but he faster csv is so twitchy and precise in its requirements that it constantly breaks with malformed csv errors and time out errorsthe csv files are generally created by users pasting text from their web sites or from microsoft word docs so it is not reasonable to expect that there will never be odd characters like smart quotes or accents in the data also users are not going to be readily able to identify whether their data is perfect enough for fastercsv or not we need to find a way to fix it for them automaticallyis there a good way or a reliable tool for preprocessing csv data to fix any nits in the data before having the fastercsv gem process it,['ruby-on-rails'] +50994,how do you scope activerecord associations in rails 3 i have a rails 3 project with rails 3 came arel and the ability to reuse one scope to build another i am wondering if there is a way to use scopes when defining a relationship eg a has many i have records which have permission columns i would like to build a default scope that takes my permission columns into consideration so that records even those accessed through a relationship are filteredpresently in rails 3 default scope including patches i have found do not provide a workable means of passing a proc which i need for late variable binding is it possible to define a has many into which a named scope can be passedthe idea of reusing a named scope would look likeordersscope my orders lambdawhereuser id usercurrent useridhas many orders scope ordersmy ordersor implicitly coding that named scope in the relationship would look likehas many orders scope lambdawhereuser id usercurrent useridi am simply trying to apply default scope with late binding i would prefer to use an arel approach if there is one but would use any workable option since i am referring to the current user i cannot rely on conditions that are not evaluated at the last possible moment such ashas many orders conditions user id usercurrent userid,['ruby-on-rails'] +51006,how to make a basic finite state machine in objectivec i am attempting to build an fsm to control a timer in iphone sdk objective c i felt it was a necessary step because i was otherwise ending up with nasty spaghetti code containing pages of ifthen statements the complexity nonreadability and difficulty of addingchanging features lead me to attempt a more formal solution like this in the context of the application the state of the timer determines some complex interactions with nsmanagedobjects core data and so forth i have left all that functionality out for now in an attempt to get a clear view of the fsm code the trouble is i cannot find any examples of this sort of code in objc and i am not so confident about how i have translated it from the c example code i was using i do not know c at all so there is some guessing involved i am basing this version of a state pattern design on this article driventut state1html i am not making a game but this article outlines concepts that work for what i am doing in order to create the code posted below i had to learn a lot of new concepts including objc protocols and so forth because these are new to me as is the state design pattern i am hoping for some feedback about this implementation is this how you work with protocol objects effectively in objc here is the protocolclass timerprotocol timerstate void entertimerstatetimertimervoid executetimerstatetimertimervoid exittimerstatetimertimerendhere is the timer object in its most stripped down form header fileinterface timer nsobject idtimerstate currenttimerstate nstimer secondtimer id timerviewdelegate viewdelegate idtimerstate setupstate idtimerstate runstate idtimerstate pausestate idtimerstate resumestate idtimerstate finishstateproperty nonatomic retain idtimerstate currenttimerstateproperty nonatomic retain nstimer secondtimerproperty assign id timerviewdelegate viewdelegateproperty nonatomic retain idtimerstate setupstateproperty nonatomic retain idtimerstate runstateproperty nonatomic retain idtimerstate pausestateproperty nonatomic retain idtimerstate resumestateproperty nonatomic retain idtimerstate finishstatevoidstoptimervoidchangestateidtimerstate timerstatevoidexecutestateidtimerstate timerstatevoid setuptimeridtimerstate timerstateand the timer object implementationimport timerhimport timerstatehimport setup tshimport run tshimport pause tshimport resume tshimport finish tshimplementation timersynthesize currenttimerstatesynthesize viewdelegatesynthesize secondtimersynthesize setupstate runstate pausestate resumestate finishstateidinit if self super init idtimerstate s setup ts alloc init selfsetupstate s s release idtimerstate r run ts alloc init selfrunstate r r release idtimerstate p pause ts alloc init selfpausestate p p release idtimerstate rs resume ts alloc init selfresumestate rs rs release idtimerstate f finish ts alloc init selffinishstate f f release return selfvoidchangestateidtimerstate newstate if newstate nil selfcurrenttimerstate exittimerstateself selfcurrenttimerstate newstate selfcurrenttimerstate entertimerstateself self executestateselfcurrenttimerstate voidexecutestateidtimerstate timerstate selfcurrenttimerstate executetimerstateself void setuptimeridtimerstate timerstate if timerstate iskindofclassrun ts class secondtimer nstimer scheduledtimerwithtimeinterval10 targetself selectorselectorcurrenttime userinfonil repeatsyes else if timerstate iskindofclassresume ts class secondtimer nstimer scheduledtimerwithtimeinterval10 targetself selectorselectorcurrenttime userinfonil repeatsyes void stoptimer secondtimer invalidatevoidcurrenttime this is just to see it working not formatted properly or anything nsstring text nsstring stringwithformat nsdate date if selfviewdelegate null selfviewdelegate respondstoselectorselectorupdatelabel selfviewdelegate updatelabeltext todo releases here voiddealloc super deallocenddo not worry that there are missing things in this class it does not do anything interesting yet i am currently just struggling with getting the syntax correct currently it compiles and works but the iskindofclass method calls cause compiler warnings method is not found in protocol i am not really sure that i want to use iskindofclass anyway i was thinking of giving each idtimerstate object a name string and using that instead on another note all those idtimerstate declarations were originally timerstate declarations it seemed to make sense to retain them as properties not sure if it makes sense with idtimerstates here is an example of one of the state classes import timerstatehinterface setup ts nsobject timerstateendimport setup tshimport timerhimplementation setup tsvoid entertimerstatetimertimer nslogsetup entering statevoid executetimerstatetimertimer nslogsetup executing statevoid exittimerstatetimertimer nslogsetup exiting stateendagain so far it does not do anything except announce that what phase or substate it is in but that is not the point what i am hoping to learn here is whether this architecture is composed correctly in the objc language one specific problem i am encountering is the creation of the id objects in the timers init function as you can see i commented out the releases because they were causing a release not found in protocol warning i was not sure how to handle that what i do not need is comments about this code being overkill or meaningless formalism or whatever it is worth me learning this even it those ideas are true if it helps think of it as a theoretical design for an fsm in objc thank you in advance for any helpful comments this did not help too much finite state machine in objectivec,['objective-c'] +51008,good ways to sort a queryset django what i am trying to do is thisget the 30 authors with highest score authorobjectsorder byscore30 order the authors by last nameany suggestions,['python'] +51024,64bit quicktime question does anyone out there know if there is a way to pull raw stillcompressed audio and video samples out of a quicktime mov file using an apple api framework targeting the mac that can be compiled natively in 64bit ie qtkit i know this functionality is available in apples quicktime framework that targets the mac but this framework can only be compiled under 32bitif anyone is familiar with such a framework and any related sample code some insight would be much appreciatedthanksjosh,['objective-c'] +51031,why cannot wia see my scanner i am trying to use wia microsoft windows image acquisition library v20 to build a c 35 winforms app in vs2008 running on a vista rig to aquire images from a scanneri know there are plenty of sdks out there that do this accusoft bytescout knowledge lake etc but we wanted some control over the ui or lack of and the ability to customize the processing and handling of the images which is why were trying the wia anglehowever i have been unable to get wia to see my scannerthe microsoft windows image acquisition library v20 dll has been referenced in the vs project and i have included using wia at the top of the pagehere is the section of codechoose scannercommondialogclass class1 new commondialogclassdevice d class1showselectdevicewiadevicetypeunspecifieddevicetype true falseif d null thisdeviceid ddeviceidelse no scanner chosen returncomplies fine but line 2 device d kicks the following error when runexception from hresult 0x80210015from what i can tell this usually means your device is unpluggednot turned on or the device is not wia compatiblebut the scanner in question shows up in control panelscanners and cameras means it is wia compatible and works when accessed via photoshop means it is turned on i have plugged in other devices digital slr and the above code can see them so the code is workingdoes anyone have any suggestions as to what is going wrong and how to fix itupdate 1i have tried a couple of different scanners canon 50f benq 5250c but same problem update 2i have been unable to find definitive proof of this but i am thinking that the scanners i have been testing with or maybe most scanners are not wia compatiblesupported i am am now looking into using twain but would still love to hear of anyone who has had some success with wiaupdate 3ended up ditching wia and using a net twain sdk eztwain all sorted now thanks to everyone for thier input,['c#'] +51037,cannot install any gems i have been doing javascript and some erlang for around six months and i have not done any rails programming lately today on my new pc i went to install rails but got this errorgem install railswarning rubygems 12 index not found for rubygems will revert to legacy indexes degrading performancebulk updating gem source index for htpgemsrubyforgeorgerror while executing gem gemremotesourceexception error fetching remote gem cache socketerror getaddrinfo the system cannot find the file specified a friend of mine said gem v to which i responded 135 he suggested i update to 136 but i had the same problem then i installed a few gems for testing purposes from githubi do not know if i am missing a source or something or if something changed drastically in gemsalsogem sources a htpgemcutterorgerror fetching htpgemcutterorg socketerror getaddrinfo the system cannot find the file specified,['ruby'] +51039,how relevant are oo design patterns to web development in php singleton decorator abstract factory and the list goes on how relevant are oo design patterns in developing php applications for the web does it do anything for performance or is it just to keep code lean for agile development practices who is the major benefactor for implementing these design patterns is it the customer or the developeri realize i am asking multiple questions but they all relate to the same topic i am not certain there is a necessity for oo design patterns with a scripting language since it is compiled at run time what do you all think is it important,['php'] +51042,how does one refresh the contents of a node in an exttreetreepanel i have an ext treepanel which i am trying to add some serverside pagination to were using ext 220we have a customized tree which only has two tiers we are listing 25 items under the tree itself the root but each item node can have an unlimited amount of children i am guessing these are the leafs the item nodes are using a custom uiprovider as are all of the childreni have added some images for prevnext page to the itemnodeui and added handlers which updates the item nodes attributes with the pagenumber the dataurl php file grabs these attributes and basically appends limit to the sql queryeverything works as it should except when you click on the nextprev images the item node collapses if you expand the node everything is as it should be but i either need the node to stay expanded or have it automagically reexpand after load i have tried using expand fireeventexpand expandchildnodes the whole nine yards nothingheres the function that is called when clicking on the previous page button onpaginationprevbuttonclick functionet var parentel extgettfindparentnodextreenodect 10 falseprevioussibling var treenodeid parentelgetattributeexttreenodeid var treenode thistreegetnodebyidtreenodeid var currentpage parseinttreenodeattributespagenumber if currentpage 0 treenodeattributespagenumber currentpage 1 treenodegetloaderloadtreenode another issue i am having is that the itemnodeui which extends treenodeui is not being refreshed when the above function is called so the text which shows how many results are being shown does not change from the first page is there a way to refresh this node as well and have it expand without reloading the whole treeif there is a better or easier way i should be doing this i appreciate any input you have i am an extnewb so pretty much everything i do is a hack editi am almost embarrassed to admit this but i was completely able to resolve the collapsing issue by using treenodereload instead of reloading the loader itself sightreenodegetloaderloadtreenodeshould have beentreenodereloadi still do however need to figure out how to refresh the node itself so that the text showing the results and the prevnext buttons show correctly i have tried usingtreenodeparentnodereloadbut all that does is refresh the whole tree i just want the itemnode itself to be updated any thoughtsmany thanks in advance,['javascript'] +51048,calling multiple javascript functions on a button click how to call multiple functions on button click eventhere is my buttonasplinkbutton idlbsearch runatserver cssclassregular onclicklbsearch click onclientclickreturn validateviewshowdiv1but my showdiv1 does not get calledmy javascript functionsfunction showdiv1 documentgetelementbyidreportdivstylethisplay block return falsefunction validateview if documentgetelementbyidctl00 contentplaceholder1 dlcategoryselectedindex 0 documentgetelementbyidctl00 contentplaceholder1 errormsginnerhtml please select your category documentgetelementbyidctl00 contentplaceholder1 dlcategoryfocus return false if documentgetelementbyidctl00 contentplaceholder1 dlempnameselectedindex 0 documentgetelementbyidctl00 contentplaceholder1 errormsginnerhtml please select your employee name documentgetelementbyidctl00 contentplaceholder1 dlempnamefocus return false return trueif the validateview function returns true i should call showdiv1,['javascript'] +51055,difference between domcontentloaded and load events what is the difference between the domcontentloaded and the load event,['javascript'] +51065,why is line 17 of this java program not being executed as an exercise for my java course in uni this morning i had to write a small program to ask the user to input some details then print them back i have since finished writing it but i ran into a strange problem along the waysee the code belowimport javautilscannerpublic class scanner exercise public static void main string args scanner keyboardin new scannersystemin int accountid string accountname float accountbalance systemoutprintlnaccount id line 13 accountid keyboardinnextint line 14 systemoutprintlnaccount name line 16 accountname keyboardinnextline line 17 systemoutprintlnaccount balance accountbalance keyboardinnextfloat when this program runs line 17 refer to comments is skipped account name is printed but the user is not given the opportunity to enter the information as if that line of code was commented out no errors are thrown the output looks like thisaccount id 2 account name account balancehowever if i switch lines 13 and 14 with 16 and 17 like as follows the program runs fine and no lines are skippedsystemoutprintlnaccount name line 16accountname keyboardinnextline line 17systemoutprintlnaccount id line 13accountid keyboardinnextint line 14why is the line 17 being skipped in the first case but not the secondif it is somehow relevant i am using jdk 6 update 18 and textpad 531,['java'] +51077,why do not more projects use ruby symbols instead of strings when i first started reading about and learning ruby i read something about the power of ruby symbols over strings symbols are stored in memory only once while strings are stored in memory once per string even if they are the samefor instance rails params hash in the controller has a bunch of keys as symbolsparamsid orparamstitlebut other decently sized projects such as sinatra and jekyll do not do thatjekyllpostdatatitle orpostdatatagssinatraparamsid orparamstitlethis makes reading new code a little tricky and makes it hard to transfer code around and to figure out why using symbols is not working there are many more examples of this and it is kind of confusing should we or should not we be using symbols in this case what are the advantages of symbols and should we be using them here,['ruby'] +51105,why it could not find the main class i have a very simple codepackage mygamepublic class rungame public static void mainstring args systemoutprintlnargs0 i can compile that code but i cannot run it when i type java rungame in the command line i getexception in thread main javalangnoclassdeffounderror rungame wrong name mygamerungame could not find the main class rungame program will exit,['java'] +51107,configuring a custom event log for log4net i am using log4net for logging duh using the eventlogappender i can configure my application name so that my events will show up in the applicationmy application name event log however i would like to log events to some other event logmy application name how do i configure thatcurrent configappender nameeventlogappender typelog4netappendereventlogappender applicationname valuemy application name layout typelog4netlayoutpatternlayout conversionpattern valuedate thread 5level logger messagenewline layoutappenderfor an eventloginstaller the code would look like thiseventloginstallerlog some other event log default applicationeventloginstallersource my application name,"['c#', '.net']" +51112,configurationexception in java decided to use apache is common configuration package to parse an xml filei decided to do axmlconfiguration xmlconfig new xmlconfigurationfileto which eclipse complained that i have not caught an exceptionunhandled exception type configurationexception so i hit the trusty surround with trycatch and it added the following codetry xmlconfiguration xmlconfig new xmlconfigurationfile catch configurationexception ex exprintstacktrace however now it is complainingno exception of type configurationexception can be thrown an exception type must be a subclass of throwablei do not understand why it is gave me that error when eclipse is the one that suggested to add it,['java'] +51114,how to align two divs horizontally i need to align 2 divs next to each other so that each contains a title and a list of items similar to div spansource listspan select size10 option option option selectdivdiv spandestination listspan select size10 option option option selectdivcan anyone suggest how to solve this problem it is remarkably easy to do with tables but i do not want to use tablesthanksdave,"['html', 'css']" +51129,populating a combobox using c i would like to populate a combobox with the followingvisible item item valueenglish enitalian itspainish sp etcany help pleasealso it is possible that after populating the combobox to make it read only,"['c#', '.net']" +51137,c get a list of files excluding those that are hidden directorygetfiles returns all files even those that are marked as hidden is there a way to get a list of files that excludes hidden files,"['c#', '.net']" +51142,testing warnings with doctest i would like to use doctests to test the presence of certain warnings for example suppose i have the following modulefrom warnings import warnclass fobject instantiating foo always gives a warning foo foo testdocspy14 userwarning boo warnboo userwarning def init self warnboo userwarningif i run python m doctest testdocspy to run the doctest in my class and make sure that the warning is printed i gettestdocspy14 userwarning boo warnboo userwarningfile testdocspy line 7 in testdocsfoofailed example foo fooexpected testdocspy14 userwarning boo warnboo userwarninggot nothing1 items had failures 1 of 1 in testdocsfootest failed 1 failuresit looks like the warning is getting printed but not captured or noticed by doctest i am guessing that this is because warnings are printed to sysstderr instead of sysstdout but this happens even when i say sysstderr sysstdout at the end of my moduleso is there any way to use doctests to test for warnings i can find no mention of this one way or the other in the documentation or in my google searching,['python'] +51148,mike ash singleton placing synchronized i came accross this on the mike ash care and feeding of singletons and was a little puzzeled by his commentthis code is kind of slow though taking a lock is somewhat expensive making it more painful is the fact that the vast majority of the time the lock is pointless the lock is only needed when foo is nil which basically only happens once after the singleton is initialized the need for the lock is gone but the lock itself remainsidsharedfoo static foo foo nil synchronizedfoo class iffoo foo self alloc init return foomy question is and there is no doubt a good reason for this but why cannot you write see below to limit the lock to when foo is nilidsharedfoo static foo foo nil iffoo synchronizedfoo class foo self alloc init return foocheers gary,['objective-c'] +51151,osx defining a new url handler that points straight at a python script i am trying to define a new url handler under osx that will point at a python scripti have wrapped the python script up into an applet rightclicked on the py and gone open with build appleti have added the following into the applet us infoplistkeycfbundleurltypeskeyarray dict keycfbundleurlnamekey stringdo my thingstring keycfbundleurlschemeskey array stringdmtstring array dictarrayi have also used the more internet preferences pane to specify dmt as a protocol but when i try to get it to link the protocol to my applet it says that there was a problem setting the app as the helperanyone know where i should go from herethanks,['python'] +51154,how can i combine several expressions into a fast method suppose i have the following expressionsexpressionactiont stringbuilder expr1 t sb sbappendtnameexpressionactiont stringbuilder expr2 t sb sbappend expressionactiont stringbuilder expr3 t sb sbappendtdescriptioni would like to be able to compile these into a methoddelegate equivalent to the followingvoid methodt t stringbuilder sb sbappendtname sbappend sbappendtdescriptionwhat is the best way to approach this i would like it to perform well ideally with performance equivalent to the above methodupdateso whilst it appears that there is no way to do this directly in c3 is there a way to convert an expression to il so that i can use it with systemreflectionemit,['c#'] +51155,ruby on rails access controller variable from model i am trying to access an instance variable which is set in the controller in the model the controller is the products controller and the model is the products model the instance variable is a instance of another model called accountthe instance variable is current accountwhen i run the code nothing happens i do not get an error does anyone know where i can find something read about access instance variables set in the controller from the modelthankseef,"['ruby-on-rails', 'ruby']" +51157,c what is the size of unmanaged object read definition of marshalsizeof it says this the size returned is the size of the unmanaged object the unmanaged and managed sizes of an object can differ is that means marshalsizeof will return you the definition size but not the actual memeory allocated size because there are may have some padding for alignmentfor examplestruct mystruct char cthe size will be 1 byte for unmanaged object unmanaged size if i use marshalsizeof but may be 2 or 4 bytes for managed object managed size if i use sizeof am i right,['c#'] +51160,passing this in java constructor look into the following codepublic class classa private boolean classaattr false public classa classahandler handler new classahandlerthis public class classahandler extends generalhandler classa ca null public classahandlerclassa classa thisca classa i need to access classaattr on some classahandler methods among other attributes is there a way to do so without passing the origin class in the handler constructor i do not really like how this solution looksthank a lotbruno,['java'] +51166,should i use a dictionary for collections with 10 items or less or is there a better alternative i have a list of objects and i need to find an object as quickly as possible by it is name property what datastructure should i use i know i can use a dictionary but there wont ever be more than 10 items in the list and if i remember correctly the dictionary is implemented as an array if the collection contains 10 items or lessthanks,"['c#', '.net']" +51170,cc macrotemplate blackmagic to generate unique name macros are finetemplates are finepretty much whatever it works is finethe example is opengl but the technique is c specific and relies on no knowledge of openglprecise problemi want an expression e where i do not have to specify a unique name such that a constructor is called where e is defined and a destructor is called where the block e is in endsfor example considerclass gltranslate gltranslatefloat x float y float z glpushmatrix gltranslatefx y z gltranslate glpopmatrix manual solution gltranslate foo10 00 00 i had to give it a name auto popmatrixnow i have this not only for gltranslate but lots of other pushattribpopattrib calls too i would prefer not to have to come up with a unique name for each var is there some trick involving macros templates or something else that will automatically create a variable whos constructor is called at point of definition and destructor called at end of blockthanks,['c++'] +51175,how to get one value from a generator in python very basic question how to get one value from a generator in pythonso far i found i can get one by writing gennext i just want to make sure this is the right way,['python'] +51176,can nullptr be emulated in gcc i saw that nullptr was implemented in visual studio 2010 i like the concept and want to start using it as soon as possible however gcc does not support it yet my code needs to run on both but does not have to compile with other compilersis there a way to emulate it something likedefine nullptr nullthat obviously wouldnt work well at all it is just to show what i mean,['c++'] +51179,how can i compare any numeric type to zero in c i would like to create a function that checks if a numeric value passed as an argument has a value greater than zero something like thispublic bool isgreaterthanzeroobject value ifvalue is int return intvalue 0 else ifvalue is float similar code for float return falsecan i try to cast the object passed as the functions argument to one numeric data type so i can then compare it to zero rather than checking for each type in my if statement if the cast fails i would return false is there a betterread shorter more readable way to do thiseditsome have asked about if i know the type will be a numeric why the object etc i hope this makes things clearerthis function would be part of a silverlight converter that implements the ivalueconverter interface which has a convert signature ofpublic object convertobject value type targettype object parameter systemglobalizationcultureinfo culturea first i only wanted the converter to work with ints but my imagination started to run wild and think what if i have floating point numbers and other numeric types i wanted to make the converter as flexible as possible initially i thought all this extra information would get in the way of what i wanted to do so i did not include it in my question,"['c#', '.net']" +51208,how can i get selector from jquery object clickfunction this how can i get selector from this is there easy way to get selector from this or something like that there is a way how to select element by selector but how about getting selector from elementthanx for any help,"['javascript', 'jquery']" +51214,inner div locked to lower right hand corner of outer div given the following htmldiv stylewidth 500px height 500px border 1px solid red div stylewidth 200px height 100px border 1px solid green float right verticalalign bottom divdivi would like the inner div to lock into the lower right hand corner of the outer div what do i need to do css wise to make that happenthanksjohn,['css'] +51235,raw image processing in python are there any pythonic solutions to reading and processing raw images even if it is simply accessing a raw photo file eg cr2 or dng and then outputting it as a jpeg ideally a dcraw bindings for python but anything else that can accomplish the came would be sufficient as well,['python'] +51237,opensided android stroke is it possible to create an android shape object with stroke on only certain sideseg i havestroke androidwidth3dip androidcolor0 androiddashwidth10dip androiddashgap6dip which is similar to this cssborder 3px dashed blackhow can i set the stroke on just one side this is how i would do it in cssborderleft 3px dashed blackhow do you do this in android xml,['android'] +51254,why does my performance slow to a crawl i move methods into a base class i am writing different implementations of immutable binary trees in c and i wanted my trees to inherit some common methods from a base classunfortunately classes which derive from the base class are abysmally slow nonderived classes perform adequately here are two nearly identical implementations of an avl tree to demonstrateavltree derivedavltree the two trees have the exact same code but i have moved the derivedavltreeinsert method in base class heres a test appusing systemusing systemcollectionsgenericusing systemdiagnosticsusing systemlinqusing julietcollectionsimmutablenamespace consoleapplication1 class program const int value count 50 static void mainstring args var avltreetimes timeittestavltree var derivedavltreetimes timeittestderivedavltree consolewritelineavltreetimes 0 derivedavltreetimes 1 avltreetimes derivedavltreetimes static double timeitfuncint int f var seeds new int 314159265 271828183 231406926 141421356 161803399 266514414 15485867 122949829 198491329 42 var times new listdouble foreach int seed in seeds var sw stopwatchstartnew fseed swstop timesaddswelapsedtotalmilliseconds throwing away top and bottom results timessort timesremoveat0 timesremoveattimescount 1 return timesaverage static int testavltreeint seed var rnd new systemrandomseed var avltree avltreedoublecreatex y xcomparetoy for int i 0 i value count i avltree avltreeinsertrndnextdouble return avltreecount static int testderivedavltreeint seed var rnd new systemrandomseed var avltree2 derivedavltreedoublecreatex y xcomparetoy for int i 0 i value count i avltree2 avltree2insertrndnextdouble return avltree2count avltree inserts 50 items in 121 msderivedavltree inserts 50 items in 2182 msmy profiler indicates that the program spends an inordinate amount of time in basebinarytreeinsert anyone whose interested can see the eqatec log file i have created with the code above youll need eqatec profiler to make sense of filei really want to use a common base class for all of my binary trees but i cannot do that if performance will sufferwhat causes my derivedavltree to perform so badly and what can i do to fix it,['c#'] +51261,java for each vs regular for are they equivalent are these two constructs equivalent char arr new char5 for char x arr code goes here compared to char arr new char5 for int i 0 i arrlength i char x arri code goes here that is if i put exactly the same code in the body of both loops and they compile will they behave exactly the samefull thisclaimer this was inspired by another question java are these 2 codes the same my answer there turned out not to be the answer but i feel that the exact semantics of java foreach has some nuances that needs pointing out,['java'] +51267,c class object memory map when we create an object of a class what does it memory map look like i am more interested in how the object calls the non virtual member functions does the compiler create a table like vtable which is shared between all objectsclass apublic void f0 int int in b1a a new awhat will be the memory map of a,['c++'] +51281,how good is oracle universal connection pool ucp does anybody have experience with using oracle ucp under real production loaddoes it handle database reconnects wellare there any multithreading issueshas anybody compared it with c3p0 or apache dbcp,['java'] +51292,read and overwrite a file in python currently i am using thisf openfilename rtext freadtext resubfoobar bar textfseek0fwritetextfclosebut the problem is that the old file is larger than the new file so i end up with a new file that has a part of the old file on the end of it,['python'] +51294,how do i add months to a current timestamp in sql how can i add months to the current timestamp in sql serverthe solution probably lies in dateadd but this works with a date only not a datetimethanks,['sql'] +51307,i am confused about some reflection code and looking for insight i am developing for the iphone using c and monos full aot technology according to their limitations page link text unlike traditional mononet code on the iphone is statically compiled ahead of time instead of being compiled on demand by a jit compilerwhen running on the hardware the following exception occursexecutionengineexception attempting to jit compile method systemreflectionmonopropertygetteradapterframeimage unityenginecolor systemreflectionmonopropertygetter2image unityenginecolorobject while running with aotonly systemreflectionmonopropertygetvalue systemobject obj systemobject index 0x0 anianivalueget anicreateanimations systemobject obj systemcollectionshashtable properties single duration systemcollectionshashtable options anitype type animethod anitype type systemobject obj single duration systemcollectionshashtable properties systemcollectionshashtable options anifrom systemobject obj single duration systemcollectionshashtable properties xobjectc compilergenerated5movenext unityenginemonobehaviourstartcoroutineienumerator xobjectstartanimationanimate gameobject object object scenesplashcreatebackground scenesplashonsetup scenesplashonsceneactivatecallback gamecontrolleractivatescene gamecontrollerdeactivatescene gamecontrollersceneloadedscene gameobject scenebase scenebasestartaccording to the limitations document systemreflectionemit is not supported but they state that as side from reflectionemit the entire reflection api including typegettypesomeclass listing methods listing properties fetching attributes and values works just finei have included the code that is causing the exception void createanimationssystemobject obj hashtable properties float duration hashtable options anitype type foreach dictionaryentry item in properties name stringitemkey extract name and value systemobject value itemvalue anivalue foo new anivalueobj name create value object to exception occurs inside get systemobject current fooget get current value the above method grabs a property name from a hashtable and uses it along with obj to create an instance of anivalue just afterward fooget is called to retrieve the value of the property the exception occurs on propertyinfogetvalueobj nullusing systemreflectionpublic class anivalue static bindingflags bflags bindingflagspublic bindingflagsnonpublic bindingflagsinstance bindingflagsstatic systemobject obj object a field or property is animated on string name name of the field or property systemtype objtype type object fieldinfo fieldinfo fieldinfo object propertyinfo propertyinfo propertyinfo object public anivaluesystemobject o string n obj o name n objtype objgettype fieldinfo objtypegetfieldn anivaluebflags propertyinfo objtypegetpropertyn anivaluebflags if fieldinfo null propertyinfo null throw new systemmissingmethodexceptionproperty or field n not found on obj get field or property public systemobject get if propertyinfo null the next line causes the exception return propertyinfogetvalueobj null else return fieldinfogetvalueobj although i have limited experience with c jit aot and reflection should getvalue trigger jit unityenginecolor is a struct and the image class is as subclass of xobject which is a subclass of unityenginemonobehaviour color is a property of image and that is what the code could be getting the value of when the exception occursinterestingly you can compile the code using net 11 and everything executes fine only when you compile using net 21 does the exception occuri do not know if there is a solution or work around to this but i would be interested in any insight as to the cause,"['c#', 'iphone']" +51330,how to look ahead one element in a python generator i cannot figure out how to look ahead one element in a python generator as soon as i look it is gonehere is what i meangen iter123next value gennext okay i looked forward and see that next value 1 but nowlistgen is 2 3 the first value is gonehere is a more real examplegen element generatorif gennext value stop quit applicationelse processgennextcan anyone help me write a generator that you can look one element forwardthanks boda cydo,['python'] +51345,oracle old joins a toolscript for conversion i have been porting oracle selects and i have been running across a lot of queries like soselect elast name ddepartment name from employees e departments dwhere edepartment id ddepartment idandselect last name ddepartment id from employees e departments d where edepartment id ddepartment idare there any guidestutorials for converting all of the variants of the syntax what is that syntax even called so i can scour google even better is there a toolscript that will do this conversion for me preferred free an optimizer of some sort i have around 500 of these queries to portwhen was this standard phased out any info is appreciated,['sql'] +51347,why did not c have a boolean data type prior to c99 i realise you can just define some integers but why did not c have a dedicated boolean data type before c99it is such a common occurence in programming and logic i do not understand the absense of an explicit type and notation,['c'] +51352,how to read file binary in c i want to make a method that takes any file and reads it as an array of 0s and 1s ie its binary code i want to save that binary code as a text file can you help me thanks,['c#'] +51357,uses of a c arithmetic promotion header i have been playing around with a set of templates for determining the correct promotion type given two primitive types in c the idea is that if you define a custom numeric template you could use these to determine the return type of say the operator function based on the class passed to the templates for example custom numeric classtemplate class tstruct complex complext real t imag rreal iimag t r i other implementation stuff generic arithmetic promotion templatetemplate class t class ustruct arithmeticpromotion typedef typename x type i realize this is incorrect but the point is it would figure out what x would be via trait testing etc specialization of arithmetic promotion templatetemplate class arithmeticpromotionlong long unsigned long typedef typename unsigned long long type arithmetic promotion template actually being usedtemplate class t class ucomplextypename arithmeticpromotiont utypeoperator complext lhs complexu rhs return complextypename arithmeticpromotiont utypelhsr rhsr lhsi rhsiif you use these promotion templates you can more or less treat your user defined types as if they are primitives with the same promotion rules being applied to them so i guess the question i have is would this be something that could be useful and if so what sorts of common tasks would you want templated out for ease of use i am working on the assumption that just having the promotion templates alone would be insufficient for practical adoptionincidentally boost has something similar in its mathtoolspromotion header but it is really more for getting values ready to be passed to the standard c math functions that expect either 2 ints or 2 doubles and bypasses all of the integral types is something that simple preferable to having complete control over how your objects are being convertedtldr what sorts of helper templates would you expect to find in an arithmetic promotion header beyond the machinery that does the promotion itself,['c++'] +51374,jquery ui accordion resize on window resize i am using the jquery ui accordion modulescript typetextjavascriptfunction sidebar column accordionaccordion fillspace true icons header uiiconplus headerselected uiiconminus scriptby using the fillspace option the accordion takes up the entire height of the window which i want problem is it calculate the height on page load and if the user resizes their browser it does not adjustis there a way to have the accordion recalculate the heightsize when the browser window is resizedthanks,['jquery'] +51376,how to update two columns in a mysql database this does not workupdate customers set firstnamejohn and lastnamesmith where id1,['mysql'] +51379,threadsafe equivalent to pythons timestrptime something i wrote throws a lot of attributeerror exceptions when using timestrptime inside a thread this only seems to happen on windows not on linux but whatever upon agoogling it seems that timestrptime is not considered threadsafeis there a better way to create a datetime object from a string current code looks likeval datefromticksmktimestrptimeval b d ybut that yields the exceptions as it is run inside a threadthanks,['python'] +51391,do a database query on textbox onblur event i am using aspnet 35 with c i need to do a database lookup when a user enters productid in txtproductid i guess doing javascript is out of the question since this will have to be server side call i wrote this code in the page load event of the webpage protected void page loadobject sender eventargs e txtproductidattributesaddonblur lookupproduct protected void lookupproduct lookup product information on onblur event i get an error message microsoft jscript runtime error object expectedhow can i resolve this,['c#'] +51393,external xmpp component anyone know a tutorial or open source example please i want to run an xmpp server openfire and register an external component to handle the messages it will recieve using the whack library the external component will run my game logic and i will be using xmpp to send player moves to the server and status updates in the other direction the bonus with xmpp is that we get built in chat for freethe trouble is although ignite look fairly established i cannot find a tutorial on how to write register and debug an external xmpp component written with whack there are very few in general for that matteri am not invested in either the server implementation or the external component library java is just my language of choice if i was to move to erlang or scala or something it would have to be a very simple in that languagea single tutorial or example would go a long way here i just need an basic external xmpp component pretty pleasekind regardsgavin,['java'] +51419,freezing a listboxitem while items are being added we have a listbox that has a number of items items are inserted into the listbox via an observablecollection some of these items can be edited right in the listbox however if an item is added at an index the edited items index the entire content of the listbox moves down what wed like to do is the following if an item is in edit mode wed like to freeze its position on the screen it is fine if items are added to the collection and the ui around the item changes but the position of the item should remain constant on the screenthe only thing i have been able to do so far is attach to the scrollchanged event and at most use either bringintoview or scrollintoview methods to ensure that the item is always thisplayed somewhere in the ui but i am unable to lock down its positionhas anyone done something like this and help out,['c#'] +51420,what is the difference between systemdrawingcolor and systemwindowsmediacolor basically why the need for two abstractions of a pretty simple concept,['.net'] +51426,automatically raise propertychanged when an inner object property got changed i got a scenario like thisclass parent property a class a property x how can i get a propertychangednotification on property a when x changes i donat want to refer aparenta in class a or any kind of event which spoils my decoupling what i basically want is to make the parentisdirtytrue this is a very simplified version of my story i got tens of classes like parent so i am looking for some generic way to handle thisplease note that this is not the actual code i got all inotifypropertychanged implementation i am just wondering any easy mechanism like raisepropertychangedax,['c#'] +51436,python for loop question i was wondering how to achieve the following in pythonfor int i 0 cond i if cond i to skip an runthroughi tried this with no luckfor i in rangewhatever if cond i 1,['python'] +51442,how to make webkit or ie call your application net from html page opened in browser i have a net application running on windows i want clicking on some page element button link flash app etc to launch my app with some special parameters it should run not just in ie but on webkit based windows browsers too during app install we suppose that user is admin and is running vista or windows 7 or laterso my question is where to get examples of such interaction with source of course so how to make webkit based browser or ie call your net application,['.net'] +51443,geting selectlist to mvc view using ajaxjquery i have a c mvc application which is populating a dropdown based on a date selected once the date is selected i am sending it to an action via ajaxjquery the action gets a list of items to return for that datehere is where my problem is i have done it previously where i render a partial view from the action and pass it the selectlist as the model however i really just want to do it inline in the original view so i am hoping there is some way i can return the selectlist and from there do some magic javascriptjquery to put it into a dropdownhas anybody ever done this before if so what do i on the client end after calling the load to return the selectlisti have done something like this previously when i was just returning a string or other value to be rendered as straight textreturntriprowloadtripaspxgettripsforgivendatedate escapeselectionbut i am not sure how to intercept the data and morph it into am htmldropdown call or equivalentany ideasthankschris,"['javascript', 'jquery']" +51450,determine if string is in list in javascript in sql we can see if a string is in a list like socolumn in a b cwhats a good way to do this in javascript it is so clunky to do thisif expression1 expression2 str a str b str c do somethingand i am not sure about the performance or clarity of thisif expression1 expression2 a1 b1 c1str do somethingor one could use the switch functionvar str a flag falseswitch str case a case b case c flag true defaultif expression1 expression2 flag do somethingbut that is a horrible mess any ideasupdatei did not think to mention that in this case i have to use ie as it is for a corporate intranet page so a b cindexofstr 1 would not work natively without some syntax sugarfor browsers that do not support indexof heres a fully standards compliant version of the indexof function and heres my version since i do not care about list position or mind traversing in reverse this should be fasterif arrayprototypeindexof arrayprototypeindexof functionitem var i thislength while i if thisi item return i return 1 buyer bewareif you do modify arrayprototype for older browsers be aware that youre adding an extra property to every array this means that the following code will iterate over an indexof property in addition to the expected numeric onesvar arr alpaca bear caribouvar indexfor index in arr consolelogitem 0 1 2 indexofworking around this requires a more defensive coding style something like thisfor index in arr if arrhasownpropertyindex do something modern javascript code linters will warn you about this but it can definitely be a pitfall for the unwaryof course it is not normal to iterate over the properties of an arrayathat is how one normally works only with an object you should use var length indexlength for index 0 index length index 1 however this is still a real issue that occurs occasionally and users of the prototypemodifying technique for adding backward support should be aware of it,['javascript'] +51464,get mysql query results as their native data type i have tried fetching mysql query results using mysql fetch row and mysql result and numeric values are being returned as strings is there any way to fetch the data as its datatype stored in the tablethe application will be querying many different queries so i will be unable to cast the values as the intended datatype on a 1 by 1 basis,"['php', 'mysql']" +51474,how to pausesuspend a thread then continue it i am making an application in c which uses a winform as the gui and a separate thread which is running in the background automatically changing things expublic void run whiletrue printmessageonguihey threadsleep20 do more work how would i make it pause anywhere in the loop because one iteration of the loop takes around 30 seconds so i wouldnt want to pause it after its done one loop i want to pause it on time,['c#'] +51480,java outofmemoryerror with stringbuilder i am getting a java outofmemoryerror when i call this method i am using it in a loop to parse many large files in sequence my guess is that resulttostring is not getting garbage collected properly during the loop if so how should i fix itprivate string matchhelperstring buffer string regex string method pattern abbrev p patterncompileregexnorms usa bs phd phd matcher abbrev matcher abbrev pmatcherbuffer stringbuffer result new stringbuffer while abbrev matcherfind abbrev matcherappendreplacementresult abbrevhelperabbrev matcher abbrev matcherappendtailresult string tempresult resulttostring error occurs here return tempresult,['java'] +51497,garbage collection behaviour for stringintern if i use stringintern to improve performance as i can use to compare interned string will i run into garbage collection issues how does the garbage collection mechanism of interned strings differ from normal strings,['java'] +51501,how does garbage collection in java work i was wondering how the garbage collector in java deals with the following situationobject a has a reference to object b and object b has a reference to object c the main program has a reference to object a so you can use object b trough object a and object c trough object b trough object awhat happens to object b and object c if the link between object a and object b is set to nullshould object b and object c now been collected by the garbage collector i mean there is still a connection between object b and object c,['java'] +51514,c timer getting fired before their interval time were getting following problem while using systemthreadingtimer net 20 from a windows servicethere are around 12 different timer objectseach timer has due time and interval this is set correctlyit is observed that after 3 to 4 hours the timers start signaling before their interval elapses for example if the timer is supposed to signal at 45959 it gets signaled at 45952 7 seconds earliercan someone tell me what is the cause for this behavior and what is the solution for that thanksswati,"['c#', '.net']" +51537,what wrapper class in c should i use for automated resource management i am a c amateur i am writing some win32 api code and there are handles and weirdly compositely allocated objects aplenty so i was wondering is there some wrapper class that would make resource management easierfor example when i want to load some data i open a file with createfile and get a handle when i am done with it i should call closehandle on it but for any reasonably complex loading function there will be dozens of possible exit points not to mention exceptionsso it would be great if i could wrap the handle in some kind of wrapper class which would automatically call closehandle once execution left the scope even better it could do some reference counting so i can pass it around in and out of other functions and it would release the resource only when the last reference left scopethe concept is simple but is there something like that in the standard library i am using visual studio 2008 by the way and i do not want to attach a 3rd party framework like boost or something,['c++'] +51540,tapestry loop through hashmap i am trying to loop through a hashmap and thisplay a number checkboxes with id the key of the hashmap and label the value of the hashmap anyone knows how the tapestry syntax for that ischeersdimitris,['java'] +51588,how do i alias the scala setter method myvar eqmyval to something more pleasing when in java i have been converting some code from java to scala lately trying to teach myself the languagesuppose we have this scala classclass person var namestring joebobnow i want to access it from java so i cannot use dotnotation like i would if i was in scalaso i can get my vars contents by issuingperson personnewsystemoutprintlnpersonnameand set it viaperson personnewpersonname eqsallysuesystemoutprintlnpersonnamethis holds true cause our person class looks like this in javapcompiled from personscalapublic class person extends javalangobject implements scalascalaobject public person public void name eqjavalangstring public javalangstring nameyes i could write my own getterssetters but i hate filling classes up with that and it does not make a ton of sense considering i already have them i just want to alias the eq method better this actually gets worse when you are dealing with stuff like antlr because then you have to escape it and it ends up looking like personname eqnewnamenote i would much rather have to put up with this rather than fill my classes with more setter methodsso what would you do in this situation,['java'] +51589,one class per file rule in net i follow this rule but some of my colleagues thisagree with it and argue that if a class is smaller it can be left in the same file with other classesanother argument i hear all the time is even microsoft does not do this so why should wewhats the general consensus on this are there cases where this should be avoided,"['c#', '.net']" +51601,pdf viewer for pyqt4 application i am writing a pythonqt4 application that would ideally need to pop up a window every once in a while to thisplay pdf documents and allow very basic operations namely scrolling through the different pages and printing the documenti have found the reportlab to create pdf files but nothing about pdf viewers does anyone knows anything that might help i was really hoping for the existence of something like the qwebview widgetthanks in advance to all,['python'] +51603,ms chart with aspnet chart type column not showing axis x label if there are more than 9 bar in the chart i have a problem with an ms chart chart type column if there are more than 9 bars in the chart the axisx labels would not show up properly some of them just thisappearheres my markup for the chartaspchart idchtnbachampionships runatserver series aspseries namechampionships yvaluetypeint32 paletteberry charttypecolumn chartareamainchartarea isvalueshownaslabeltrue points aspdatapoint axislabelceltics yvalues17 aspdatapoint axislabellakers yvalues15 aspdatapoint axislabelbulls yvalues6 aspdatapoint axislabelspurs yvalues4 aspdatapoint axislabel76ers yvalues3 aspdatapoint axislabelpistons yvalues3 aspdatapoint axislabelwarriors yvalues3 aspdatapoint axislabelmara yvalues4 aspdatapoint axislabelsaza yvalues9 aspdatapoint axislabelbuha yvalues6 points aspseries series chartareas aspchartarea namemainchartarea aspchartarea chartareasaspchartwith only 9 bars it works but i do not know why it fails with more than 9 bars is there any way to make the chart work properly also if possible how to make each bar have different color,"['.net', 'asp.net']" +51611,objective c default parameters possible duplicatesoptional arguments in objectivec 20objectivec default argument value i am writing a c function in objective c i want a default value for my last parameter i have triedfooint a int b int c 0but that is ci have also triedfooint a int b int cfooint a int b fooa b 0but that is also c is there a way to do this in objective c,['objective-c'] +51629,can i do a maxcount in sql heres my code select yrcount from moviejoin casting on castingmovieidmovieidjoin actor on castingactorid actoridwhere actorname john travoltagroup by yrheres the questionwhich were the busiest years for john travolta show the number of movies he made for each yearheres the table structuremovieid title yr score votes directoractorid namecastingmovieid actorid ordthis is the output i am gettingyr count1976 11977 11978 11981 11994 1etcetci need to get the rows for which count is maxhow do i do this,['sql'] +51630,how to calculate next friday at 3am how can you calculate the following friday at 3am as a datetime objectclarification ie the calculated date should always be greater than 7 days away and less than or equal to 14going with a slightly modified version of marks solutiondef next weekdayday of week4 time of daydatetimetimehour3 dtnone if dt is none dt datetimedatetimenow dt datetimetimedeltadays7 if dttime time of day dt dtcombinedtdate time of day else dt dtcombinedtdate time of day datetimetimedeltadays1 return dt datetimetimedeltaday of week dtweekday 7,['python'] +51633,how to get objects to react to touches in cocos2d alright so i am starting to learn more about coco2d but i am kinda frusterated a lot of the tutorials i have found are for outdated versions of the code so when i look through and see how they do certain things i cannot translate it into my own program because a lot has changed with that being said i am working in the latest version of coco2d version 099what i want to do is create a sprite on the screen done and then when i touch that sprite i can have something happen for now let us just make an alert go off now i got this code working with the help of a friend here is the header file when you import this file you import all the cocos2d classesimport cocos2dh helloworld layerinterface helloworld cclayer cgrect sprect returns a scene that contains the helloworld as the only childid sceneendand here is the implementation file cocos2d hello world example import the interfacesimport helloworldscenehimport customccnodeh helloworld implementationimplementation helloworldid scene scene is an autorelease object ccscene scene ccscene node layer is an autorelease object helloworld layer helloworld node add layer as a child to scene scene addchild layer return the scene return scene on init you need to initialize your instanceid init always call super init apple recommends to reassign self with the super return value if selfsuper init create and initialize a label cclabel label cclabel labelwithstringhello world fontnametimes new roman fontsize64 ask director the the window size cgsize size ccdirector shareddirector winsize position the label on the center of the screen labelposition ccp sizewidth 2 sizeheight2 add the label as a child to this layer self addchild label ccsprite sp ccsprite spritewithfiletest2png spposition ccp300200 self addchildsp float w sp contentsizewidth float h sp contentsizeheight cgpoint apoint cgpointmakesp positionx w2 sp positiony h2 sprect cgrectmakeapointx apointy w h ccsprite sprite2 ccsprite spritewithfiletest3png sprite2position ccp100100 self addchildsprite2 self registerwithtouchthispatcher selfistouchenabled yes return self on dealloc you need to release all your retained objects void dealloc in case you have something to dealloc do it in this method in this particular example nothing needs to be released cocos2d will automatically release all the children label do not forget to call super dealloc super dealloc voidcctouchesendednsset touches witheventuievent event uitouch touch touches anyobject cgpoint location ccdirector shareddirector convertcoordinatetouch locationinviewtouchview cgpoint location touch locationinviewtouch view location ccdirector shareddirector converttogllocation if cgrectcontainspointsprect location uialertview alert uialertview alloc initwithtitlewin messagetesting delegatenil cancelbuttontitleokay otherbuttontitlesnil alert show alert release nslogtouches nslogtouch gothowever this only works for 1 object the sprite which i create the cgrect for i cannot do it for 2 sprites which i was testing so my question is this how can i have all sprites on the screen react to the same event when touchedfor my program the same event needs to be run for all objects of the same type so that should make it a tad easier i tried making a subclass of ccnode and over write the method but that just did not work at all so i am doing something wrong help would be appreciatedgoing through the touches project in cocos2d and seeing if i see how they did it it looks like they made a subclass and overwrote the methods boolcctouchbeganuitouch touch witheventuievent event voidcctouchmoveduitouch touch witheventuievent event voidcctouchendeduitouch touch witheventuievent eventso now i get to figure out why mine does not work hmm,"['ios', 'iphone', 'objective-c']" +51645,serving static files with sinatra i have one page website only using html css and javascript i want to deploy the app to heroku but i cannot find a way to do it i am now trying to make the app working with sinatra applicationcss applicationjs indexhtml jqueryjs myapprband the following is the content of myapprbrequire rubygemsrequire sinatraget do what should i write here to point to the indexhtmlend,['ruby'] +51657,how do i implement tag searching with lucene i havent used lucene last time i ask many months ago maybe a year people suggested lucene if i shouldnt use lucene what should i use as am example say there are items tagged like thisapples carrotsapplescarrotsapple bananaif a user search apples i dont care if there is any preference from 12 and 4 however i seen many forums do this which i hated is when a user search apple carrots 2 and 3 have high results while 1 is hard to find even though it matches my search more closelyalso i would like the ability to do search carrots apples which will only get me 3 i am not sure what should happen if i search carrots banana but anyways as long as more items tagged with 2 and 3 results are lower ranking then 1 when i search apples carrots i will be happycan lucene do this and where do i start i tried looking it up and when i do i see a lot of classes and i will see tutorials talking about documents webpages but none were clear about what to do when i like to tag something if not lucene what should i use for tagging,"['c#', '.net']" +51668,reset push notification settings for app i am developing an app with push notifications to check all possible ways of user interaction i would like to test my app when a user declines to have push notifications enabled for my app during the first start the dialog initiated by registerforremotenotificationtypes however appears only once per app how do i reset the iphone oss memory of my app deleting the app and reinstalling does not help,['iphone'] +51670,ihierarchydata and ihierarchicalenumerable in winforms currentlyi know how to do a lazy implementation of the loading procedure of the nodes in a treeview control and read the related questions in stackoverflow but i am also reading about ihierarchydata and ihierarchicalenumerable interfaces in aspnet i did not know to code aspnet that allow to bind a collection to a treeview in order to thisplay the items automaticallyit would like to know if i can do the same in winforms and c i think that the interfaces previous mentioned are not available in winformsthanks,['c#'] +51681,wheres the iphone mime type database i have a program for the iphone that is supposed to be doing intelligent things picking out appropriate icons for file types given a list of filenames i am looking for the iphone take on something like etcmimetypes or something similar an api call is what i am assuming would be available for the phone does this exist,"['iphone', 'objective-c']" +51684,how to selfupdate phpmysql cms i am writing a cms on phpmysql i want it to be selfupdatable throw one click in admin panel what are the best practiceshow to compare current version of cms and a version of the update application itself and database should it just download zip archive upzip it and overwrite files but what to do with files that are no longer used how to check if an update is downloaded correctly also it supports modules and i want this modules to be downloadable from the admin panel of cmsand how should i update mysql tables,"['php', 'mysql']" +51685,ruby and ruby on rails offline api documentation in the past i used railsbraincom to have a nice and handy offline api documentationbut they stop at version 232is there any other solution with latest version,"['ruby-on-rails', 'ruby']" +51696,as a newbie where should i go if i want to create a small gui program i am a newbie with a little experience writing in basic python and of all things a smidgeon of assembler as part of a videogame rom hack i wanted to create small tool for modifying the hex values at particular points in a particular file that would have a gui interfacewhat i am looking for is the ability to create small gui program that i can thistribute as an exe or at least a standalone directory i am not keen on the idea of the net languages because i do not want to force people to download a massive net framework package i currently have python with idle and boa constructor set up and the application runs there i have tried looking up information on compiling a python app that relies on wxwidgets but the search results and the information i have found has been confusing or just completely incomprehensible my questions areis python a good language to use for this sort of projectif i use py2exe will wxwidgets already be included or will my users have to somehow install wxwidgets on their machines am i right in thinking at py2exe just produces a standalone directory thist that has the necessary files for the user to just double click and run the applicationif the program just relies upon tkinter for gui stuff will that be included in the exe py2exe produces if so are their any visual gui builders ides for python with only tkinterthankyou for your timejbmk,['python'] +51708,whats the best way to test sql server connection programmatically i need to develop a single routine that will be fired each 5 minutes to check if a list of sql servers 10 to 12 are up and running i can try to obtain a simple query in each one of the servers but this means that i have to create a table view or stored procedure in every server even if i use any already made sp i need to have a registered user in each server too the servers are not in the same physical location so having those requirements would be a complex task is there a way to simply ping from c one sql server thanks in advance,['c#'] +51717,compare equality of char in c i have two variables char chartime timechar buf somethingelsei want to check if these two are equal using chartime buf does not workwhat should i use and can someone explain why using does not workwould this action be different in c and c,"['c++', 'c']" +51724,function to get the file name of an url i have some source code to get the file name of an urlfor examplei hope to get apdfbecause the way to join 2 nsstrings i can get is appendstring which only for adding a string at right side so i planned to check each char one by one from the right side of string when it reach at the char stop the checking return string fdpa after that i change fdpa to apdfsource codes are belownsmutablestring getsubstringafterh originalstringnsstring s0 nsinteger il ls0 length nsmutablestring hnsmutablestring alloc init nsmutablestring tnsmutablestring alloc init foril1i0i check each char one by one from the right side of string when it reach at the char stop ts0 substringwithrangensmakerangei 1 ift isequaltostring break else h appendstringt t release nsmutablestring h1nsmutablestring alloc initwithformat autorelease for ih length1i0i nsmutablestring t1nsmutablestring alloc init t1h substringwithrangensmakerangei 1 h1 appendstringt1 t1 release h release return h1h1 can reuturn the coorect string apdf but if it returns to the codes where it was called after a while system reportsdouble free set a breakpoint in malloc error break to debugi checked a long time and foudn that if i removed the code ts0 substringwithrangensmakerangei 1everything will be ok of course getsubstringafterh can not returns the corrent result i expected no error reportedi try to fix the bug a few hours but still no cluewelcome any commentthanks interdev,['iphone'] +51726,get formatted html from ckeditor i am using ckeditor in my web app and i am at a loss as to how to get the contents of the editor with html formattingvar objeditor ckeditorinstancessectiontextareavar q objeditorgetdatathis will get me the text entered in ckeditor without any markuphowevervar q objeditorgethtmlwill return a null value what am i doing wrong,"['javascript', 'html']" +51727,reordering arrays say i have an array that looks like thisvar playlist artistherbie hancock titlethrust artistlalo schifrin titleshifting gears artistfazeo titleriding highhow can move an element to another positioni want to move for example artistlalo schifrin titleshifting gears to the endi tried using splice like thisvar tmp playlistsplice21playlistsplice20tmpbut it does not workany help would be appreciated,['javascript'] +51732,could extra imports in java slow down code loading time is it possible that adding more import statements to your java code could slow down the time it takes to load your classes into the jvm,['java'] +51742,json serialization of enum as string i have a class that contains an enum property and upon serializing the object using javascriptserializer my json result contains the integer value of the enumeration rather than its string name is there a way to get the enum as a string in my json without having to create a custom javascriptconverter perhaps there is an attribute that i could decorate the enum definition or object property withas an exampleenum gender male female class person int age get set gender gender get set desired json result age 35 gender male,"['c#', 'asp.net']" +51748,stack allocation in c is it bad style to design your simple c programs to allocate everything or most everything on the stack,['c'] +51754,differences between classpath and sourcepath options of javac i read the sun documentation and a lot of posts on stack overflow but i am still confused about the differences between the java compiler options cp and sourcepath let say i have this directory structurecjavaproject1src where the java source files are cjavaproject1bin where the java class files will be or already are let us also say i have a source file mainclassjava in a package commypackage and that the directory structure is ok in the source folderi am in the project1 directory and runjavac d bin sourcepath src srccommypackagemainclassjava orjavac d bin classpath src srccommypackagemainclassjava and i obtain the same result in verbose mode the search path for source files is src in both cases it would be great if anybody could help me figure out the specifics of these options,['java'] +51766,php getting unique values of a multidimensional array possible duplicatephp multidimensional array remove duplicate i have an array like thisa array 0 array value america 1 array value england 2 array value australia 3 array value america 4 array value england 5 array value canada how can i remove the duplicate values so that i get thisa array 0 array value america 1 array value england 2 array value australia 4 array value canada i tried using array unique but that does not work due to this array being multidimensional i thinkedit i also need this array to be multidimensional and in this format i cannot flatten itthanksthanks,['php'] +51777,rails or sinatra which is good to start learning for a php programmer i have been working far too long with php and getting bored with it i also want to learn a new language i have been using ruby and like it i have to decide between rails and sinatra so which one would you recommend is it true that sinatra cannot be used to build complex apps and it is only for simple apps,"['ruby-on-rails', 'ruby']" +51792,what are the ruby equivalent of python itertools esp combinationspermutationsgroupby pythons itertools module provides a lots of goodies with respect to processing an iterableiterator by use of generators for examplepermutationsrange3 012 021 102 120 201 210combinationsabcd 2 ab ac ad bc bd cdlistg for k g in groupbyabccd a b cc dwhat are the equivalent in rubyby equivalent i mean fast and memory efficient pythons itertools module is written in c,['ruby'] +51796,set form field values in extjs i am using extjs to create a formpanelnew extformpanel labelalign top title loading contact bodystylepadding5px width 600 autoscroll true closable true items layoutcolumn borderfalse items columnwidth5 layout form borderfalse items xtypetextfield fieldlabel first name name first name id first name anchor95 xtypedatefield fieldlabel birthdate name birthdate width 150 columnwidth5 layout form borderfalse items xtypetextfield fieldlabel last name name last name anchor95 xtypetextfield fieldlabel email name email vtypeemail anchor95 xtypetabpanel plaintrue activetab 0 height300 by turning off deferred rendering we are guaranteeing that the form fields within tabs that are not activated will still be rendered this is often important when creating multitabbed forms deferredrender false defaultsbodystylepadding10px items titleaddress layoutform defaults width 230 defaulttype textfield items fieldlabel line1 name line1 allowblankfalse fieldlabel line2 name line2 fieldlabel city name city allowblank false xtypecombo fieldlabelstate namestate hiddennamecombovalue fieldlabel zipcode name zipcode allowblank false titlephone numbers layoutform defaults width 230 defaulttype textfield items fieldlabel home name home phone fieldlabel cell name cell phone fieldlabel emergency name emergency phone clsxplain titlenotes layoutfit items xtypehtmleditor namenotes fieldlabelnotes buttons text save text cancel how do i access the form fields by the name to set their value manually thanks,['javascript'] +51799,add jquery colorbox plugin to a dynamically created element the usual way to assign color box functionality on a link is like thisacolorboxcolorbox transition elastic newly added items are not bound in this way thoughhow can i add colorbox to dynamically created a classcolorboxaelements too,['jquery'] +51801,reusing named scope to define another named scope the problem essence as i see itone day if i am not mistaken i have seen an example of reusing a named scope to define another named scope something like this cannot remember the exact syntax but that is exactly my questionnamed scope billable conditions named scope billable by tom conditions billable true user userfind by nametomthe question is what is the exact syntax if it is possible at all i cannot find it back and google was of no help eithersome explanationswhy i actually want it is that i am using searchlogic to define a complex search which can result in an expression like thiscarduser group managers salary greater than100but it is too long to be put everywhere because as far as i know searchlogic simply defines named scopes on the fly i would like to set a named scope on the card class like thisnamed scope from big guys user group managers salary greater than100 this is where i would use that long searchlogic method inside my named scope but again what would be the syntax cannot figure it outresumeso is named scope nesting and i do not mean chaining actually possible,['ruby-on-rails'] +51812,naming my application in android i think i am getting senile because i was convinced that to give a name to your application you had to fill this part of the manifestapplication androidicondrawableicon androidlabelmyapplicationnamehowever for a reason i do not understand my application gets the name of my first activity in which i load data thus it is called loading defined as follows in the manifest activity androidnameaccueilsplash androidlabelloadingany idea why that is,['android'] +51815,ruby script as service well the title say it all i have a ruby script i want running as a service one i can start and stop on my linux box i was able to find how to do it on windows heresome readings point to creating daemons or cron tasksi just need something simple i can call on my boxs reboot and can stopstart whenever i please my script has an internal sleep call and runs in eternal loopthanks in advance,['ruby'] +51825,how to get a word under cursor using javascript if i for example have p some long text pon my html page how can i know that cursor of mouse is for example above the word text,['javascript'] +51828,syndicationitemcontent is null i am trying to pull the contents of an rss feed into an object that can be manipulated in code it looks like the syndicationfeed and syndicationitem classes in net 35 will do what i need except for one thing every time i have tried to read in the contents of an rss feed using the syndicationfeed class the content element for each syndicationitem is nulli have run my feed through feedvalidator and have tried this with feeds from several other sources but to no availxmlreader xr xmlreadercreatesyndicationfeed feed syndicationfeedloadxrforeach syndicationitem item in feeditems consolewritelineitemtitletext consolewritelineitemcontenttostringconsolereadlinei suspect i may just be missing a step somewhere but i cannot seem to find a good tutorial on how to consume rss feeds using these classesedit thanks to slaks i have figured out that the issue is with wordpres use of as the content tag this does not appear to be a problem with the wp atom feeds so i will go with that as a solution for now thanks slaks,['c#'] +51830,handling multiple exceptions i have written a class which loads configuration objects of my application and keeps track of them so that i can easily write out changes or reload the whole configuration at once with a single method call however each configuration object might potentially throw an exception when doing io yet i do not want those errors to cancel the overall process in order to give the other objects still a chance to reloadwrite therefore i collect all exceptions which are thrown while iterating over the objects and store them in a superexception which is thrown after the loop since each exception must still be handled and someone has to be notified of what exactly went wrong however that approach looks a bit odd to me someone out there with a cleaner solution here is some code of the mentioned classpublic synchronized void store throws multiplecauseexception multiplecauseexception me new multiplecauseexceptionunable to store some resources forresource resource thisresourcesvalues try resourcestore catchstoreexception e meaddcausee ifmehascauses throw me,['java'] +51831,colour instead of color i am working on a game engine in c and i have methods like setcolour and things that use british grammar while i was thinking how c compilers mostly use the english language correct me if i am wrong and how most apis use american grammar should i go with the flow and continue the unofficial standard in the grammar programmer high council or be a rebeli am not sure which,['c++'] +51837,how to make strtotime parse dates in australian ie uk format ddmmy i cannot beleive i have never come across this one beforebasically i am parsing the text in humancreated text documents and one of the fields i need to parse is a date and time because i am in australia dates are formatted like ddmmy but strtotime only wants to parse it as a us formatted date also exploding by is not going to work because as i mentioned these documents are handtyped and some of them take the form of d m yyi have tried multiple combinations of setlocale but no matter what i try the language is always set to us englishi am fairly sure setlocale is the key here but i do not seem to be able to strike upon the right code tried theseauauenen auaustraliaausanything else i can tryfor clarity i am running on iis with a windows boxthanks so much iainexamplemydatetime strtotime90210 200pmecho datej f y hi mydatetimeproduces2 september 2010 1400i want it to produce9 february 2010 1400my solutioni am giving the tick to one of the answers here as it is a much easiertoread solution to mine but heres what i have come up withdatetime 90210 200pmusdatetime preg replace03091s s102009s sd4d2 213 datetime echo datej f y histrtotimeusdatetimebecause i cannot rely on users to be consistent with their date entry i have made my regex a bit more complex0 or 1 digit between 0 and 31 digit between 0 and 9 yes this will match 37 as a valid date but i think the regex is already big enoughcould be some whitespacedelimiting character a a or a could be some whitespaceeithera number between 10 and 12 ora number between 1 and 9 with an optional leading 0could be some whitespacedelimiting character a a or a could be some whitespaceeithera number 2 digits long ora number 4 digits longhopefully this will match most styles of date writing,['php'] +51844,how different is objectivec from c what are the main differences between objectivec and c in terms of the syntax features paradigms frameworks and librariesimportant my goal is not to start a performance war between the two languages i only want real hard facts in fact my question is not related to performance please give sources for anything that may seem subjective,"['c++', 'objective-c']" +51847,actionmailer default from address googled for this to no avail did not find anything in the api either i was expecting some kind of class method or configuration option to set itso rather than calling from for every method it could be called automatically,['ruby-on-rails'] +51857,use linq and c to make a new list from an old list this should be pretty simple but i am new at linq i have a listfillstruct of filist structs i would like to use linq to create a new listnewfillstruct where instead of having the number of buys and sells i would have one variable containing the sum for example if the fillstruct structure has buy 4 and sell 2then the newfillstruct structure will have numlong 2if the fillstruct structure has buy 2 and sell 4then the newfillstruct structure will have numlong 2here are the structuresstruct fillstruct int buy int sell string datestruct newfillstruct int numlong string date,['c#'] +51884,android ratingbar change star colors how can i change the star colors and how can i change the size of the stars,['android'] +51893,entities equals hashcode and tostring how to correctly implement them i am implementing equals hashcode and tostring of my entities using all the available fields in the beani am getting some lazy init exception on the frontend when i try to compare the equality or when i print the obj state that is because some list in the entity can be lazy initializedi am wondering whats the correct way to for implementing equals and tostring on an entity object,['java'] +51899,postloading check if an image is in the browser cache short version question is there navigatormozislocallyavailable equivalent function that works on all browsers or an alternativelong version hihere is my situation i want to implement an htmlhelper extension for aspnet mvc that handle image postloading easily using jqueryso i render the page with empty image sources with the source specified in the alt attributei insert image sources after the windowonload event and it works greati did something like this windowbindload function var plimages postload plimageseachfunction thisattrsrc thisattralt the problem is after the first loading postloaded images are cached but if the page takes 10 seconds to load the cached postloaded images will be thisplayed after this 10 secondsso i think to specify image sources on the documentready event if the image is cached to thisplay them immediatlyi found this function navigatormozislocallyavailable to check if an image is in the cache here is what i have done with jquery specify cached image sources on dom readydocumentreadyfunction var plimages postload plimageseachfunction var source thisattralt var thisponible navigatormozislocallyavailablesource true if thisponible thisattrsrc source specify uncached image sources after page loadingwindowbindload function var plimages postload plimageseachfunction if thisattrsrc thisattrsrc thisattralt it works on mozillas dom but it does not works on any other one i tried navigatorislocallyavailable same resultis there any alternative,"['javascript', 'jquery']" +51907,why does sorted list have to have a key value pair if i just want a sorted list of just dates integers or doubles is it really necessary to have to define a sortedlistof integer integerseems intriguing to me but may just be trival i would prefer just to use a sortedlistof integerthis question is in relation to the net generic collections,['.net'] +51913,finding temporary file storage in java so i am writing a java application that uses simple to store data as xml file but it is hellishly slow with big files when it stores on a network drive compared to on a local hard drive so i would like to store it locally before copying it over to the desired destinationis there some smart way to find a temporary local file storage in java in a system independent way eg something that returns something such as ctemp in windows tmp in linux and likewise for other platforms such as mac i could use application path but the problem is that the java application is run from the network drive as well,['java'] +51924,recaptcha on iphone app using sdk has anyone used recaptcha on their iphone application i am trying to figure out how to embed it in my app,['iphone'] +51935,change name of import in java or import two classes with the same name in python you can do afrom a import b as chow would you do this in java as i have two imports that are clashing,['java'] +51937,how to declare a generic delegate with an out parameter funca out b bool just do not compile how to declare that i want the second parameter be an out onei want to use it like this public class foo public funca out b bool detectmethod,"['c#', '.net']" +51946,c expected constant expression include iostreaminclude fstreaminclude cmathinclude mathhinclude iomanipusing stdifstreamusing namespace stdint main voidint count0float sum0float maximum10float sumofxfloat sumofyint sizeint negativey0int positivex0int negativex0ifstream points the points to be imported from filepointsopen datadatpointssizecoutsizeendlsize100float xsize2while countsize pointsxcount0coutx xcount0 read in x valuepointsxcount1couty xcount1endlread in y valuecountthis program is giving me expected constant expression error on the line where i declare float xsize2 why,['c++'] +51956,different users get the same cookie value in aspxanonymous my site allows anonymous usersi saw that under heavy load anonymous users get sometimes profile values from other usersi first delete my cookies and get a valid unique value in the cookie value aspxanonymous after a couple of requests i get a new value for aspxanonymous which is already used by another user i see in my loggs that there are always a couple of users who share the same value in aspxanonymousi can see in the my logs that 2 or more users realy get the same cookievalue for aspxanonymous even if they have different iphere is the htp traffic in the second image the changing cookie is shown you have to thisplay the image full size do be able to read the logone of the many requests that work okthen there is this one request that changes the cookiethen the new cookie is usedjust to be safe i removed dependency injectioni dont use outputcachingmy webconfig has this setting for authentication anonymousidentification enabledtrue cookielessusecookies cookienameaspxanonymous cookietimeout30 cookiepath cookierequiresslfalse cookieslidingexpirationtrue authentication modeforms forms loginurldeaccountlogin authenticationdoes anybody have an idea what else i could log or what i should have a look atupdatei saw now that the httptraffic i showed is perfectly valid a changing value in aspxanonymous is something that happens because the cookie gets refreshed the value contains anonymousid and a timestamp this does not lead to users having the same value in aspxanonymous under normal conditions the problem realy is that whenever the cokies get set from the anonymousidentificationmodule then there is a chance that a couple of user get this cookie setting a cookie in my application doesnt have this strange sideefect,['asp.net'] +51957,given a type instance how to get generic type name in c given a generic type includingliststringnullableint32how do i get a generic name for cvar t typeofnullabledatetime var s tgetgenerictypedefinitionname tgetgenericarguments0name this yieldsnullable1datetime but i neednullabledatetime,['c#'] +51959,what type is systembyte i am being passed an object that returns systembyte when converted to string this apparently is not a standard one dimensional array of byte objects systembyte so what is it,['c#'] +51960,how can i improve this design let us assume that our system can perform actions and that an action requires some parameters to do its work i have defined the following base class for all actions simplified for your reading pleasurepublic abstract class basebusinessactiontactionparameters where tactionparameters iactionparameters protected basebusinessactiontactionparameters actionparameters if actionparameters null throw new argumentnullexceptionactionparameters thisparameters actionparameters if parametersarevalid throw new argumentexceptionvalid parameters must be supplied actionparameters protected tactionparameters parameters get private set protected abstract bool parametersarevalid public void commonmethod only a concrete implementation of basebusinessaction knows how to validate that the parameters passed to it are valid and therefore theparametersarevalid is an abstract function however i want the base class constructor to enforce that the parameters passed are always valid so i have added acall to parametersarevalid to the constructor and i throw an exception when the function returns false so far so good right well nocode analysis is telling me to not call overridable methods in constructors which actually makes a lot of sense because when the base clas constructor is called the child clas constructor has not yet been called and therefore the parametersarevalid method may not have access to some critical member variable that the child clas constructor would setso the question is this how do i improve this design do i add a funcbool tactionparameters parameter to the base class constructor if i didpublic class myactionmyparameters public myactionmyparameters actionparameters bool something baseactionparameters validateit thissomething something private bool something public static bool validateit return something this would work because validateit is static but i do not know is there a better waycomments are very welcome,"['c#', '.net']" +51961,visual studio sql server 2008 server project vs sql server 2008 database project i cannot see to find a quick explanation of the differences so i can figure out which to use one is for a server one is for a database im not sure what that meansbasically we are doing a new web app and i want to see what these project types can offer me in terms of tracking the db codeschema etc,['sql'] +51968,jquery uses new functionreturn data instead of evaldata to parse json why this link shows you that jquery uses new functionreturn data for older browsers to parse a json string instead of evalwhat are the benefits of this what if the json string is not safe,"['javascript', 'jquery']" +51970,any way to assign terminal output to variable with python i need to grab the duration of a video file via python as part of a larger script i know i can use ffmpeg to grab the duration but i need to be able to save that output as a variable back in python i thought this would work but it is giving me a value of 0cmd ffmpeg i s 21 grep duration cut d f 4 sed s videomovduration ossystemcmdprint durationam i doing the output redirect wrong or is there simply no way to pipe the terminal output back into python,['python'] +51973,how can i work with dates before 1900 in php i am using php and jquery to build an interactive timeline which needs to thisplay dates between 1500 and 2020 i usually use phps strtotime function when working with dates but it does not work for dates pre1900the dates will come from a mysql database and are formatted as strings such as january 31 1654 this may not be the ideal format but i cannot change how they are stored i am using php to parse the dates basically converting them into pixel values which determine where they are thisplayed on the timelinewhat is the easiest way to parse these historical dates,['php'] +51975,what happens when value types are created i am developing a game using xna and c and was attempting to avoid calling new struct type code each frame as i thought it would freak the gc out but wait i said to myself struct is a value type the gc should not get called then right well that is why i am asking herei only have a very vague idea of what happens to value types if i create a new struct within a function call is the struct being created on the stack will it simply get pushed and popped and performance not take a hit further would there be some memory limit or performance implications if say i need to create many instances in a single calltake for instance this codespritebatchdrawtex new rectanglex y width height colorwhiterectangle in this case is a struct what happens when that new rectangle is created what are the implications of having to repeat that line many times say thousands of times is this rectangle created a copy sent to the draw method and then thiscarded meaning no memory getting eaten up the more draw is called in that manner in the same functionps i know this may be premature optimization but i am mostly curious and wish to have a better understanding of what is happening,['c#'] +51983,how to find a web hosting service for running compojure i am very interested in building a website using clojure and compojure like sohowever due to my limited experience with the java environment and java culture i am not sure where to begin when shopping for a webhosting servicedo i simply need to find a service that gives me full root access and has the jdkjvm or are there other requirements as well,['java'] +51998,what is the purpose of finalization in java different websites are giving different opinionsmy understanding is thisto clean up or reclaim the memory that an object occupies the garbage collector comes into action automatically is invokedthe garbage collector then dereferences the object sometimes there is no way for the garbage collector to access the object then finalize is invoked to do a final clean up processing after which the garbage collector can be invokedis this right,['java'] +52001,write gui programatically or using an advanced gui editor java swing i am planning to write a swingbased application using netbeans 68it seems that netbeans has a very advanced gui editor still i have my doubts regarding the code generated by it additionally i do not like the fact the part of the code is locked still i understand the need has anybody used netbeans gui editor with success does it scale,['java'] +52009,read and write to a file while keeping lock i am making a simple page load counter by storing the current count in a file this is how i want to do thislock the file flockread the current count freadincrement it write new count fwriteunlock fileclose it flockfclosecan this be done without losing the lockas i understand it the file cannot be written to without losing the lock the only way i have come up with to tackle this is to write a character using r mode and then counting characters,['php'] +52033,how do i apply the foreach loop to every character in a string so i want to iterate for each character in a stringso i thoughtfor char c xyzbut i get a compiler errormyclassjava20 foreach not applicable to expression typehow can i do this,['java'] +52036,using different numeric variable types im still pretty new so bear with me on this one my questions are not meant to be argumentative or petty but during some reading something struck me as oddim under the assumption that when computers were slow and memory was expensive using the correct variable type was much more of a necessity than it is today now that memory is a bit easier to come by people seem to have relaxed a bit for example you see this sample code everywherefor int i 0 i length iint 2147483648 to 2147483648 for length isnt byte 0255 a better choice so im curious of your opinion and what you believe to be best practice i hate to think this would be used only because the acronym int is more intuitive for a beginneror has memory just become so cheap that we really dont need to concern ourselves with such petty things and therefore we should just use long so we can be sure any other numberstypeswithin reason used can be cast automagicallyor am im just being silly by concerning myself with such things,['c#'] +52037,what happened to android aapt i downloaded the most recent version of android for linux androidsdk r05linux 86tgz i was trying to use the the android ant tasks for packaging building and deploying my code i should mention that i am running amd64 but have the 32bit libraries installed the android ant tasks are all brokenfirst the startemulator task never gets the emulator running it does get past starting adb but then just sits theresecond the sdk is missing the aapt binary in the tools directory so the example notepad sample application will not even package correctlyjavalangillegalstateexception cannot find aapt inside the sdk at homeuserbinandroidsdklinux 86 at comgooglecodeautoandroidlibandroidtoolslocatetoolandroidtoolsjava116 at comgooglecodeautoandroidlibandroidtoolsstarttoolandroidtoolsjava103 at comgooglecodeautoandroidlibandroidtoolsstarttoolandroidtoolsjava91 at comgooglecodeautoandroidlibunixandroidtoolsaaptunixandroidtoolsjava9i have all the dependencies configured for android i can run it from the command line just finei assume the ant code is out of sync with the recent sdk updates can anyone shed some light on this problem at this point i am considering writing my own python scripts to interact with the android sdk ugh,"['java', 'android']" +52040,setopaquetruefalse java in java2d when you use setopaque i am a little confused on what the true and false doesfor example i know that in swing opaque means that when painting swing wont paint what is behind the component or is this backwards which one is itthanks,['java'] +52043,ruby platform independent way to determine ips of all network interfaces is there an easy way in ruby for me to get a list of the ip addresses for all network interfaces it needs to work in linuxwinosx and i would prefer to not have to parse ifconfigipconfig unless i absolutely have to,['ruby'] +52045,download binary without triggering onbeforeunload i want to kick off a file download for a user when he clicks a link but i have an onbeforeunload handler that i do not want to get invoked when the download begins to downloads i currently have an a with the href set to the file location but clicking it results in onbeforeunload being invoked in chrome not in ff though i know i can set a private flag and check that in the onbeforeunload handler but is there some way to kick off the download using ajax i still want the user to see the usual dialogs when they download the file opensave etcideas,['javascript'] +52050,how to vertically align images in i got a td where two images reside shown as follows one is much higher than the other how do i let the shorter one align to the top of td td stylepaddingleft 0px cursor pointer verticalalign topimg width85px srcxyzpngimg srcicon livegif shorter onetd,"['html', 'css']" +52062,what are the differences between msi and exe installers and which should i choose possible duplicatewhat are the specific differences between msi and setupexe file i am working on an installer for a new version of my project cpreviously i have used inno setup to create exe files for installing my projects on other computers in the workplace while reading through some tutorials though i came across windows installer xml which uses xml files to build a msi installermy project will be available on a network share that all the employees have access to so they can install the software i am currently working on an update checker as wellwhat are the major differences between exe and msi installers why would i want to chose one over the other would either make more sense given my specific environmenti found some of the information at this question but there was not a lot of information,"['c#', '.net']" +52080,inheritance or identifier does anyone here have opinions about when to user inheritance and when to use an identifier instead inheritance example class animal public int name get set class dog animal class cat animal identifier example class animal public int name get set public animaltype get set in what situations should i prefer which solution and what are the pros and cons for them lina,"['c#', 'java']" +52088,android how to find the position clicked from the context menu i have a list view filled with data i set up a context menu for the listview using the following codelistsetoncreatecontextmenulistener new viewoncreatecontextmenulistener public void oncreatecontextmenucontextmenu menu view view contextmenucontextmenuinfo menuinfo adaptercontextmenuinfo mi adaptercontextmenuinfo menuinfo menuadd0 0 0 delete item i have the following method override to control de contextmenu menuitem selectedoverridepublic boolean oncontextitemselectedmenuitem item switchitemgetitemid case 0 showalerthello from delete item break default return superoncontextitemselecteditem return true in this overrided method how could i find the item of the list view that was clickedthanks in advancebest regardsjose,['android'] +52096,bundle net dlls to run application in netless machine afaik ngen turns msil into native code also reffered to as prejit however i never payed too much attention at it is startup performance impact ngend applications still require the net base class libraries the runtimesince the base class libraries have everything our net assemblies need correct would it be possible to ship the frameworks dlls with my ngend application so that it does not require the runtime to be installed eg the scenario for most windows xp machinesoh and please do not bother mentioning remotesofts salamander linker or xenocodes postbuild they are not for my and manys current budget and they seem to simply bundle the framework in a virtualized enviroinment which means big download sizes and slow startup times i believeediti know now ngen does not do what i thought it didbut is it possible to bundle the net files with an application without using a vm,['.net'] +52121,font family selection with google charts is it possible to set fontfamily for any of the nonflash google chart visualizations specifically for things like the text on the chart axis google charts is powerful but ugly and unfortunately i canat move to something nicer like graphael,['javascript'] +52127,how to add an integer into string using objective c i am a java programer i found that the java is very gd at doing string if i want to do this objective c how can i do in objective csystemoutprintlnthis is a 123 test,['objective-c'] +52133,how to do linq aggregates when there might be an empty set i have a linq collection of things where thing has an amount decimal propertyi am trying to do an aggregate on this for a certain subset of thingsvar total mythingssumt tamountand that works nicely but then i added a condition that left me with no things in the resultvar total mythingswheret totherproperty 123sumt tamountand instead of getting total 0 or null i get an errorsysteminvalidoperationexception the null value cannot be assigned to a member with type systemdecimal which is a nonnullable value typethat is really nasty because i did not expect that behavior i would have expected total to be zero maybe null but certainly not to throw an exceptionwhat am i doing wrong whats the workaroundfixedit examplethanks to all for your comments heres some code copied and pasted not simplified it is linqtosql perhaps that is why you could not reproduce my problemvar claims claimwherecl clid 0var count claimscount count0var sum claimssumcl clclaimedamount throws exception,['c#'] +52152,how to organize infinite while loop in sql server i want to use infinite while loop in sql server 2005 and use break keyword to exit from it on certain conditionwhile true does not work so i have to use while 11is there a better way to organize infinite loop i know that i can use goto but while 11 begin end looks better structurally,['sql'] +52153,utf8 html and css files with bom and how to remove the bom with python first some background i am developing a web application using python all of my text files are currently stored in utf8 with the bom this includes all my html templates and css files these resources are stored as binary data bom and all in my dbwhen i retrieve the templates from the db i decode them using templatedecodeutf8 when the html arrives in the browser the bom is present at the beginning of the http response body this generates a very interesting error in chromeextra html encountered migrating attributes back to the original html element and ignoring the tagchrome seems to generate an html tag automatically when it sees the bom and mistakes it for content making the real html tag an errorso using python what is the best way to remove the bom from my utf8 encoded templates if it exists i cannot guarantee this in the futurefor other textbased files like css will major browsers correctly interpret or ignore the bom they are being sent as plain binary data without decodeutf8note i am using python 25thanks,['python'] +52166,problem with jqueryajax with delete method in ie i have a page where the user can edit various content using buttons and selects that trigger ajax calls in particular one action causes a url to be called remotely with some data and a put request which as i am using a restful rails backend triggers my update action i also have a delete button which calls the same url but with a delete request the update ajax call works in all browsers but the delete one does not work in ie i have got a vague memory of encountering something like this beforecan anyone shed any light heres my ajax callsupdate action works in all browsersjqueryajax asynctrue datadata datatypescript typeput urlquizzesquizidquiz questionsquizquestionid success functionmsg initializequizquestions setpublishbuttonstatus delete action fails in ie function deletequizquestionquizquestionid quizid send ajax call to back end to change the difficulty of the quiz question back end will then refresh the relevant parts of the page progress bars flashes quiz status jqueryajax asynctrue datatypescript typedelete urlquizzesquizidquiz questionsquizquestionid success functionmsg alertsuccess initializequizquestions setselectstatusquizquestionid true jquerytridquiz question quizquestionidremoveclaselected error functionmsg alerterror msg i put the alerts in success and error in the delete ajax just to see what happens and the error part of the ajax call is triggered but with no call being made to the back end i know this by watching my back end server logs so it fails before it even makes the call i cannot work out why the msg i get back from the error block is blankany ideas anyone is this a known problem i have tested it in ie6 and ie8 and it does not work in eitherthanks maxedit the solution thanks to nick craver for pointing me in the right direction rails and maybe other frameworks has a subterfuge for the unsupported put and delete requests a post request with the parameter method note the underscore set to put or delete will be treated as if the actual request type was that string so in my case i made this change note the data option jqueryajax asynctrue data methoddelete datatypescript typepost urlquizzesquizidquiz questionsquizquestionid success functionmsg alertsuccess initializequizquestions setselectstatusquizquestionid true jquerytridquiz question quizquestionidremoveclaselected error functionmsg alerterror msg rails will now treat this as if it were a delete request preserving the rest system the reason my put example worked was just because in this particular case ie was happy to send a put request but it officially does not support them so it is best to do this for put requests as well as delete requests,"['javascript', 'jquery']" +52170,use of properties vs backingfield inside owner class i love autoimplemented properties in c but lately there is been this elephant standing in my cubicle and i do not know what to do with himif i use autoimplemented properties hereafter aip then i no longer have a private backing field to use internally this is fine because the aip has no sideeffects but what if later on i need to add some extra processing in the get or set now i need to create a backingfield so i can expand my getters and setters this is fine for external code using the class because they would not notice the difference but now all of the internal references to the aip are going to invoke these sideeffects when they access the property now all internal access to the once aip must be refactored to use the backingfieldso my question is what do most of you do do you use autoimplemented properties or do you prefer to always use a backingfield what do you think about properties with sideeffects,['c#'] +52184,implementing a cc style union as a column in mysql friendsi have a strange need and cannot think my way through the problem the great and mighty google is of little help due to keyword recycling as youll see can you helpwhat i want to do is store data of multiple types in a single column in mysqlthis is the database equivalent to a c union and if you search for mysql and union you obviously get a whole bunch of stuff on the union keyword in sqlcontrived and simplified case follows so let us say that we have people who have names and stormtroopers who have tk numbers you cannot have both a name and a tk number youre either bob smith or tk409in c i could express this as a union like sounion char name int tkno emperialpersonnelrecordthis makes it so that i am either storing a pointer to a char array or an id in the type emperialpersonnelrecord but not bothi am looking for a mysql equivalent on a column my column would store either an int double or varchar255 or whatever combination but would only take up the space of the largest elementis this possibleof course anything is possible given enough time money and will i mean is it possible if i am poor lazy and on a deadline aka out of the box,"['mysql', 'c']" +52185,can we overload a function based on only whether a parameter is a value or a reference i got the answer no because passing by value and passing by reference looks identical to the callerhowever the code below compiles rightclass a publicvoid fint i void fint i but when i try to use it there is compile errorint main a a int i 9 int j i af1 afi afj return 0why does not the compiler thisable it even without knowing it is going to be used,['c++'] +52194,executable war file that starts jetty without maven i am trying to make an executable war file java jar mywarfilewar that will start up a jetty webserver that hosts the webapp contained in the war file i executedi found a page that described how to make what i am looking forhowever following that advice along with how i think i am supposed to make an executable jar war is not workingi have an ant task creating a war file with a manifest that looks likemanifestversion 10antversion apache ant 171createdby 150 18b02 sun microsystems incmainclass startthe contents of the war file look like startclass jsp buildjsp metainf manifestmf webinf lib jetty6122jar jettyutil6122jarwhen i try to execute the war file the error isexception in thread main javalangnoclassdeffounderror orgmortbayjettyhandlercaused by javalangclassnotfoundexception orgmortbayjettyhandler at javaneturlclassloader1runurlclassloaderjava202 at javasecurityaccesscontrollerdoprivilegednative method at javaneturlclassloaderfindclassurlclassloaderjava190 at javalangclassloaderloadclassclassloaderjava307 at sunmisclauncherappclassloaderloadclasslauncherjava301 at javalangclassloaderloadclassclassloaderjava248could not find the main class start program will exitthere appears to be two errors here one where it seems the jar files cannot be found and one where the start class cannot be foundto fix the first one i put the jetty jar files in the base of the war file and tried again same error i also tried adding the webinflibspecificjarfiles to the classpath attribute of the manifest that did not work eitherdoes anyone have any insight as to what i am doing rightwrong and how i can get this executable war file up and running,['java'] +52202,early or reordered reuse of derived columns in a query is this valid ansi sql is this valid ansi sqlselect 1 as x 2 x as y 3 y as zbecause teradata 12 can do this as well as this yes crazy is not itselect 3 y as z 2 x as y 1 as xbut sql server 2005 requires something like thisselect x y 3 y as zfrom select x 2 x as y from select 1 as x as x as y,['sql'] +52217,create a ruby proc from a string i want to define the block as a string then create the lambda the following example does not work is something like this possiblecode string xx2l lambda evalcode stringlcall3 6,['ruby'] +52218,how to edit a link within a contenteditable div does anyone have any suggestions on how to edit an link in a contenteditable div it would be ideal once the link is either clicked with mouse or the cursor hits the link that the a small prompt would pop up and allow the user to change the href property of the link the prompt is not the issue but how is it possible to detect the link has been either clicked or that the cursor has arrived at the link onfocus does not seem to work in a contenteditable div on firefox safari any ideas,"['javascript', 'html']" +52228,localizing concatenated or dynamic strings i am familiar with using nslocalizedstring to localize strings but the problem i have today requires a little more finesse my situation is like thisnsstring username the users name entered by the user does not need localizednsstring favoritefood the users favorite food also entered by user and not needing localizednsstring summary nsstring stringwithformats favorite food is username favoritefoodthis works fine for english but not every language uses the same word ordering as english for example a wordbyword translation of the same sentance from japanese into english would readusernames favorite food pizza isnot to mention that s is does not make a possessive in every languagewhat techniques are available for localizing this type of concatenated sentenceupdate for the benefit of othersjon reed is right positional specifiers are very important to localization the document he linked only contains a reference to the fact that they can be used with nsstring nslog an others the link does not really tell how to use themi found this link that explains it well it also explains my question better than i did from the linkformat strings for printf and sprintf see printf present a special problem for translation consider the following1 printf string s has d charactersn string lengthstring a possible germantranslation for this might be d zeichen lang ist die zeichenkette sn the problemshould be obvious the order of the format specifications is different from the original even though gettext can return the translated string at runtime it cannot change the argument order in the call to printfto solve this problem printf format specifiers may have an additional optional element which we call a positional specifier for example 2d zeichen lang ist die zeichenkette 1sn here thepositional specifier consists of an integer count which indicates which argument to use and a aa counts are onebased and the format string itself is not included thus in the following example astringa is the first argument and alengthstringa is the second gawk begin string dont panic printf 2d characters live in 1sn string lengthstring 10 characters live in dont panic,['objective-c'] +52231,how do i set and get uibuttons tag how do i set a tag for a button programmaticallyi later want to compare to tags for a conclusionive tried thisibactionbuttonpressedidsendernslogd sender tagbut that just crashes the app any other ideascheers guyssam,['iphone'] +52240,how to echo something in c in an aspx file i know you can do this requestform0 but how do you do something like this ifrequestform0null echo abc,"['c#', 'asp.net']" +52246,remove the complete styling of an html buttonsubmit is there a way of completely removing the styling of a button in internet explorer i use a css sprite for my button and everything looks ok but when i click the button it moves to the top a little it makes it look out of shape is there a css click state or mousedown i do not know what triggers that statei know it is not a really big deal but sometimes it is the small things that matter,"['html', 'css']" +52249,c defines for a better release mode build in vs i currently use the following preprocessor defines and various optimization settings win32 lean and mean vc extraleannominmax crt secure no warnings scl secure no warnings secure scl0 has iterator debugging0my question is what other things do fellow soers use add define in order to get a release mode build from vs c 20082010 to be as performant as possible btw i have tried pgo etc it does help a bit but nothing that comes to parity with gcc also i am not using streams the c i am talking about its more like c but making use of templates and stl algorithms etcas it stands now very simple code segments pale in comparison wrt performance when compared to what gcc produces on say an equivalent x86 machine running linux 26 kernel using 02sidenote i believe a lot of the issues relate directly to the stl version dinkum provided by ms could people please elaborate on experiences using stlport etc with vs c,['c++'] +52253,why do i need the isset function in php i am trying to understand the difference between thisif isset postsubmit do somethingandif postsubmit do somethingit seems to me that if the postsubmit variable is true then it is set why would i need the isset function in this case,['php'] +52262,gpssatellitegetsnr what is the value range i am building a satview that draws a small barchart for available satellites and their signal strength or better their signaltonoiseratio snrthe javadoc does not say what valuerange to expect for the snr the nmeastandard says 099 but even in best conditions my g1 does not reach that value i also read that different manufacturers use different valueranges for the snr so is that true for androiddevices too or is there a unified value range on that plattform and if so what is it the lack of information in the docs leads me to suspect i just get the raw snr from the driver in which case i would like to know what do you think is the best approach to visualize that unknown valuerange in a barchart,['android'] +52281,check how much a string sounds like another one in java i would like to know if there is any class in java able to check using its own criteria how much a string is equal to another oneexample william shakespeare william shakespeare might be 100william shakespeare william shakespeere might have above 90william shakespeare shakespeare william might have above 70 just examples,['java'] +52295,why this works templates sfinae c referring to yesterdays post this woke me up this morning why does this actually work as long as the function test is concerned this function has no body so how can it perform anything i want to know why and how this works i am really interested to see your answerstemplatetypename t class isclasst private typedef char one typedef struct char a2 two templatetypename c static one testint c no body here templatetypename c static two testa nor here public enum yes sizeofisclasstemplate testt0 sizeofone enum no yes thanks in advance with help to understand this very interesting phenomenon,['c++'] +52301,writing a makefileam to invoke googletest unit tests i am trying to add my first unit test to an existing open source project specifically i added a new class called audio managersrcaudioaudio managerhsrcaudioaudio managercci created a srctest directory structure that mirrors the structure of the implementation files and wrote my googletest unit testssrctestaudioaudio managerccnow i am trying to set up my makefileam to compile and run the unit testsrctestaudiomakefileami copied makefileam fromsrcaudiomakefileamdoes anyone have a simple recipe for me or is it to the cryptic automake documentation for me,['c++'] +52307,c get ip address from domain name how can i get an ip address given a domain namefor example wtestcom,['c#'] +52310,interacting with java code from c weve written a java program which we are looking to use and interact with from c what are our options optimally it would be possible to compile the java application as a library dll that we could reference from c perhaps using pinvoke this however does not appear to be an option according to the first few searches onlinewe opt to be able to use aspnet to built a search engine powered by the java code so if this opens up for any other options please let us know,"['c#', 'java', '.net']" +52311,is there a javascript equivalent of for self concatenating rather than doingmy var my varextra stringis there a shorthand method like in php,['javascript'] +52316,automockcontainer with support for automocking classes with noninterface dependencies i have a constructor which has a noninterface dependencypublic mainwindowviewmodeliworkitemprovider workitemprovider weeknavigatorviewmodel weeknavigatori am using the moqcontrib automockcontainer if i try to automock the mainwindowviewmodel class i get an error due to the weeknavigatorviewmodel dependency are there any automocking containers which supports mocking of noninterface typesas mark has shown below yes you can i replaced the moqcontrib automockcontainer with the stuff mark presents in his answer the only difference is that the autogenerated mocks are registered as singletons but you can make this configurable here is the final solution summary automocking factory that can create an instance of the class under test and automatically inject mocks for all its dependencies summary remarks mocks interface and class dependencies remarkspublic class automockcontainer readonly icontainer container public automockcontainermockfactory factory var builder new containerbuilder builderregistersourcenew anyconcretetypenotalreadyregisteredsource builderregistersourcenew moqregistrationsourcefactory container builderbuild summary gets or creates a mock for the given type with the default behavior specified by the factory summary public mockt getmockt where t class return containerresolvet as imockedtmock summary creates an instance of a class under test injecting all necessary dependencies as mocks summary typeparam nametrequested object typetypeparam public t createt where t class return containerresolvet public t resolvet return containerresolvet summary registers and resolves the given service on the container summary typeparam nametserviceservicetypeparam typeparam nametimplementationthe implementation of the servicetypeparam public void registertservice timplementation var builder new containerbuilder builderregistertypetimplementationastservicesingleinstance builderupdate container summary registers the given service instance on the container summary typeparam nametserviceservice typetypeparam param nameinstanceservice instanceparam public void registertservicetservice instance var builder new containerbuilder if instancegettypeisclass builderregisterinstanceinstance as objectastservice else builderregisterc instanceastservice builderupdate container class moqregistrationsource iregistrationsource private readonly mockfactory factory private readonly methodinfo createmethod public moqregistrationsourcemockfactory factory factory factory createmethod factorygettypegetmethodcreate new type public ienumerableicomponentregistration registrationsforservice service funcservice ienumerableicomponentregistration registrationaccessor var swt service as iservicewithtype if swt null yield break if swtservicetypeisinterface yield break var existingreg registrationaccessorservice if existingregany yield break var reg registrationbuilderfordelegatec p var createmethod createmethodmakegenericmethodswtservicetype return mockcreatemethodinvoke factory nullobject asswtservicetypesingleinstancecreateregistration yield return reg public bool isadapterforindividualcomponents get return false,['c#'] +52324,mvc localization of default model binder i am currently trying to figure out how to localize the error messages generated by mvc let me use the default model binder as an example so i can explain the problemassuming i have a form where a user enters thier age the user then enters ten in to the form but instead of getting the expected error of age must be beween 18 and 25the message the value ten is not valid for ageis thisplayed the entitys age property is defined below range18 25 errormessageresourcetype typeof errors errormessageresourcename age errormessage range errormessage public int age get set after some digging i notice that this error text comes from the systemwebmvcresourcesdefaultmodelbinder valueinvalid in the mvcresourcesresx filenow how can create localized versions of this fileas a solution for example should i download mvc source and add mvcresourcesen gbresx mvcresourcesfr frresx mvcresourceses esresx and mvcresourcesde deresx and then compile my own version of mvcdllbut i do not like this idea any one else know a better way,['asp.net'] +52327,how do i create a dynamic key to be added to a javascript object variable i am trying something like this but this example does not workjsobj for var i 1 i 10 i jsobjkey i example 1what can i do to make a dynamic key like this,['javascript'] +52334,how expensive are method calls in net what is the relative performance cost of calling a method over inline code,['.net'] +52336,boosting my ga with neural networks andor reinforcement learning as i have mentioned in previous questions i am writing a maze solving application to help me learn about more theoretical cs subjects after some trouble i have got a genetic algorithm working that can evolve a set of rules handled by boolean values in order to find a good solution through a mazethat being said the ga alone is okay but i would like to beef it up with a neural network even though i have no real working knowledge of neural networks no formal theoretical cs education after doing a bit of reading on the subject i found that a neural network could be used to train a genome in order to improve results let us say i have a genome group of genes such as1 0 0 1 0 1 0 1 0 1 1 1 0 0how could i use a neural network i am assuming mlp to train and improve my genomein addition to this as i know nothing about neural networks i have been looking into implementing some form of reinforcement learning using my maze matrix 2 dimensional array although i am a bit stuck on what the following algorithm wants from mefrom 1 set parameter and environment reward matrix r 2 initialize matrix q as zero matrix 3 for each episode select random initial state do while not reach goal state o select one among all possible actions for the current state o using this possible action consider to go to the next state o get maximum q value of this next state based on all possible actions o compute o set the next state as the current state end do end for the big problem for me is implementing a reward matrix r and what a q matrix exactly is and getting the q value i use a multidimensional array for my maze and enum states for every move how would this be used in a qlearning algorithmif someone could help out by explaining what i would need to do to implement the following preferably in java although c would be nice too possibly with some source code examples it would be appreciated,['java'] +52343,question about debugger security can an attacker attach a debugger to my app after installing it to the market or does the app have to be marked as debuggable first how secure is this are there ways to get around it,['android'] +52354,python inmemory zip library is there a python library that allows manipulation of zip archives in memory without having to use actual thisk files the zipfile library does not allow you to update the archive the only way seems to be to extract it to a directory make your changes and create a new zip from that directory i want to modify zip archives without thisk access because i will be downloading them making changes and uploading them again so i have no reason to store them something similar to javas zipinputstreamzipoutputstream would do the trick although any interface at all that avoids thisk access would be fine,['python'] +52356,how to optimize this code hi i class carit has a propertystring codeand 10 othercommon codes is list of stringsstring cars a list of carscarfilteredlistofcars is listfor int index 0 index carslength index car car carsindex if commoncodescontainscarcode filteredlistofcarsaddcar unfortunately this piece of methodexecutes too longi have about 50k recordshow can i lower execution time,['c#'] +52357,iphone coredata how can i trackobserve all changes within a subgraph i have a nsmanagedobjectcontext in which i have a number of subclasses of nsmanagedobjects such that some are containers for others what i would like to do is watch a toplevel object to be notified of any changes to any of its properties associations or the propertiesassociations of any of the objects it containsusing the contexts haschanges does not give me enough granularity the objects isupdated method only applies to the given object and not anything in its associations is there a convenient perhaps kvobased was i can observe changes in a context that are limited to a subgraph,['iphone'] +52367,how do i remove the resize gripper image from a statusstrip control in c i need to show a statusstrip control docked top instead of bottomuser requirement long storyhow do i get the statusstrip to thisplay without the dots in the right corner,['c#'] +52372,passing null child object from parent object to a partial view i have an object which contains models for my aspnet mvc web app the model that is being passed into the view has sub models for gadgets on that particular view each of these sub models gets passed to a partial view gadgetthe problem is when i have a null model in the view model see example belowview modelpublic class foobarholder public foobar1 foobar1 get set public foobar2 foobar2 get set we pass foobarholder into the view and inside the view we make calls such as htmlrenderpartialfoo modelfoobar1 htmlrenderpartialfoo2 modelfoobar2 now say for instance that modelfoobar2 was null what i am experiencing from the strongly typed partial view is an error that says this view expected a model of type foobar2 but got a model of type foobarholderwhy is this happening instead of just passing in a null,['c#'] +52378,fancybox iframe dimension in the fancybox homepage there is an example that opens an iframe dimensioned as the 75 of the screeni cannot get it by modifying the width and height properties on the js file as described on the site,['jquery'] +52381,enumvalues vs enumsetallof which one is more preferable i looked under the hood for enumsetallof and it looks very efficient especially for enums with less than 64 valuesbasically all sets share the single array of all possible enum values and the only other piece of information is a bitmask which in case of allof is set in one swoopon the other hand enumvalues seems to be a bit of black magic moreover it returns an array not a collection so in many cases it must be decorated with arraysaslist to be usable in any place that expects collectionso should enumsetallof be more preferable to enumvaluesmore specifically which form of for iterator should be usedfor final myenum val myenumvalues orfor final myenum val enumsetallof myenumclass,['java'] +52384,using lambda expressions for event handlers i currently have a page which is declared as followspublic partial class mypage systemwebuipage protected void page loadobject sender eventargs e snip mybuttonclick o i snip i have only recently moved to net 35 from 11 so i am used to writing event handlers outside of the page load my question is are there any performance drawbacks or pitfalls i should watch out for when using the lambda method for this i prefer it as it is certainly more concise but i do not want to sacrifice performance to use it thanks,['c#'] +52390,aspnet charting control transparency i am working with the aspnet charting library and i have got it generating a pie chart but i am having a problem configuring it to generate the pie chart with semitransparent slices if you look at the image youll see what i am talking about of the 4 pie charts the top 2 and the bottom left chart have the pie slice transparency i am talking aboutwhat settings of the chart do i tweak to render the slices with a certain of transparencythanks,"['c#', 'asp.net']" +52408,twisted why is it that passing a deferred callback to a deferred thread makes the thread blocking all of a sudden i unsuccessfully tried using txrethis the non blocking twisted api for rethis for a persisting message queue i am trying to set up with a scrapy project i am working on i found that although the client was not blocking it became much slower than it could have been because what should have been one event in the reactor loop was split up into thousands of stepsso instead i tried making use of rethispy the regular blocking twisted api and wrapping the call in a deferred thread it works great however i want to perform an inner deferred when i make a call to rethis as i would like to set up connection pooling in attempts to speed things up further below is my interpretation of some sample code taken from the twisted docs for a deferred thread to illustrate my use case usrbinenv pythonfrom twistedinternet import reactorthreadsfrom twistedinternettask import loopingcallimport timedef main loop print doing stuff in main loop do not block medef ablockingrethiscall print doing lookup this may take a while timesleep10 return results from rethisdef resultres print resdef main lc loopingcallmain loop lcstart2 d threadsdefertothreadablockingrethiscall daddcallbackresult reactorrunif name main mainand here is my alteration for connection pooling that makes the code in the deferred thread blocking usrbinenv pythonfrom twistedinternet import reactordeferfrom twistedinternettask import loopingcallimport timedef main loop print doing stuff in main loop do not block medef ablockingrethiscallx if x5 all connections are busy try later print s is less than 5 get a rethis client later x x1 d deferdeferred daddcallbackablockingrethiscall reactorcalater10dcallbackx return d else print got a rethis client doing lookup this may take a while timesleep10 this is now blocking any ideas d deferdeferred daddcallbackgotfinalresult dcallbackx return ddef gotfinalresultx return final result is s xdef resultres print resdef ablockingmethod print going to sleep timesleep10 print woke updef main lc loopingcallmain loop lcstart2 d deferdeferred daddcallbackablockingrethiscall daddcallbackresult reactorcallinthreaddcallback 1 reactorrunif name main mainso my question is does anyone know why my alteration causes the deferred thread to be blocking andor can anyone suggest a better solution,['python'] +52435,is there a java map keyset equivalent for cs stdmap is there a java map keyset equivalent for cs stdmap the java keyset method returns a set view of the keys contained in this map,"['java', 'c++']" +52436,looking for a java grammar in lexyacc format does anyone know an online repository for lexyacc format grammars i am looking for a java grammar to make a quicky sourcecode converterthank youedit i am preferably looking for lexyacc because i want to use fslexfsyacc with as little grammar rewriting as possible,['java'] +52437,onexit event for a swing application i am developing a simple application to manage the operational part of a business using swing but i need that when the application exits it performs thisupdatezonasdbclosebut how can i do this,['java'] +52450,dynamically evaluating simple boolean logic in python i have got some dynamicallygenerated boolean logic expressions likea or b and c or da or a and baempty evaluates to truethe placeholders get replaced with booleans should iconvert this information to a python expression like true or true or false and eval itcreate a binary tree where a node is either a bool or conjunctionthisjunction object and recursively evaluate itconvert it into nested sexpressions and use a lisp parsersomething elsesuggestions welcome,['python'] +52462,whats the difference between calling myclassclass and myclassgetclass myclassclass and myclassgetclass both seem to return a javalangclass is there a subtle thistinction or can they be used interchangeably also is myclassclass a public property of the superclass class class i know this exists but cannot seem to find any mention of it in the javadocs,['java'] +52464,android listview click howto how do i listen to click event on a listviewthis is what i have nowlistview list listviewfindviewbyidridlistview01 listsetadapteradapter when i do the following listsetonitemselectedlistenernew adapterviewonitemselectedlistener public void onitemselectedadapterview parentview view childview int position long id setdetailposition public void onnothingselectedadapterview parentview that does not seem to do anything on clickand all those code live within a class that extends activity,['android'] +52494,stored procedure output parameter set back to pojo by ibatis i am using ibatis to call a stored procedure on mssql server the input parameters are properties on a pojo that is put to the mapmapstring object savemap new hashmapstring objectsavemapputobj myarticleupdatesave savemapall parameters are set correctly as input to the procedure so nothing wrong there but one of the parameters is a outputparameter and and i was expecting it to be set back to the pojo but instead one extra mapping objnewfalse is put the map by ibatisheres a simplified version of the mapping showing the basic idea procedure idsave include refidcorereturned value call sprc article name save include refid corecommon fields particle id objart id partname objartname pnewarticlename flg objnewmodeinout procedureafter calling the procedure i have two mappings in map passed to ibatisobjpojoobjnewfalsenow i see that ibatis documentation saids when executing stored procedures a ibatis will create objects for output parameters so it makes sense but my question is if there a way to instruct ibatis put back the boolean value to the pojo after the procedure is called i rather do not do the extra work of getting the value out of the map and set it to the pojo my self uhlan,['java'] +52529,force application to restart on first activity for an unknown reason i cannot get my application leaving properly so that when i push the home button and the app icon again i resume where i was in the app i would like to force the application to restart on the first activityi suppose this has something to do with ondestroy or maybe onpause but i do not know what to do,['android'] +52530,how to add url to the trusted zone in internet explorer how can i add an url to the trusted site it seems that there are stored in the registry but where exactlythe hints i have googled so far werent helpfullthe net programm will run locally on each clientedit clarification i want to do this programmaticly running c code,"['c#', 'asp.net']" +52534,php function array key exists and regular expressions is it possible to use a regular expression with the php function array key existsfor exampleexp my regex array key existsexp arraythank you,['php'] +52569,downsides to using fakeweb compared to writing mocks for testing i never liked writing mocks and a while ago someone here recommended to use fakeweb i immediately fell completely in love with fakeweb however i have to wonder if there is a downside to using fakeweb it seems like mocks are still much more common so i wonder what i am missing that is wrong with using fakeweb instead is there a certain kind of error you cannot cover with fakeweb or is it something about the tdd or bdd process,['ruby-on-rails'] +52575,good htmlcssphp editor that is free and multiplatform i have recently given up on using visual studio for windows editing see php is not really important as i have hardly any pages that use it but in vs if it smells php then it would not treat it as html and thus will all be plainly formatted soi am looking for some sorta htmlcssphp editor that is free and multiplatformso i can also use it at my home openbsd computer and please do not suggest emacs or vi i am learning more and more of nvi but i am looking for a graphical editor right now can anyone suggest a good editor for my needs,"['php', 'html', 'css']" +52579,in java is there any thisadvantage to static methods on a class lets assume that a rule or rule of thumb anyway has been imposed in my coding environment that any method on a class that does not use modify or otherwise need any instance variables to do its work be made static is there any inherent compile time runtime or any other thisadvantage to doing thisedited for further clarificationsi know the question was somewhat open ended and vague so i apologize for that my intent in asking was in the context of mostly helper methods utility classes with private ctors so they cannot be instantiated as holders for static methods we already do my question here was more in line of these little methods that help out the main class apii might have 4 or 5 main apiinstance methods on a class that do the real work but in the course of doing so they share some common functionality that might only be working on the input parameters to the api method and not internal state these are the code sections i typically pull out into their own helper methods and if they do not need to access the class state make them staticmy question was thus is this inherently a bad idea and if so why or why not,['java'] +52586,why does phps uniqid function return only 13 digits and not 14 uniqid function returns a 13 digits long hexadecimal number according to the spec in phpnet site the function uses microtime to generate the unique valuebut microtime returns numbers in string format as the following one070352700 12689396875which are basically the microseconds and the seconds elapsed since 1970this is a 911 digits decimal numberconverting a 20 decimal number into hex would result in a 16 digits hexadecimal not a 13 digits onei also thought to take out the 0 part that seem to never change and the last two digits of the microsec part that seem to remain always 00 doing this the decimal number would be only 9113 digits long but still a decimal number of 17 digits when converted into hex would result in 14 digits hexadecimal number not 13i am not interested in getting a unique id in another way or a longershorter unique id i am only asking if someone knows why does uniqid returns only 13 digitsit seems nosense if uniqid returns one digit less than microtime it means that microtime gives out results that are more unique of the ones returned by uniqid,['php'] +52601,good data structure for efficient insertquerying on arbitrary properties i am working on a project where arrays are the default data structure for everything and every query is a linear search in the form ofneed a customer with a particular name customerfindx xname nameneed a customer with a particular unique id customerfindx xid idneed a customer of a particular type and age customerfindx x is preferredcustomer xage ageneed a customer of a particular name and age customerfindx xname name xage agein almost all instances the criteria for lookups is welldefined for example we only search for customers by one or more of the properties id type name or age we rarely search by anything elseis a good data structure to support arbitrary queries of these types with lookup better than on any outofthebox implementations for net,['c#'] +52606,python speed up removal of every nth element from list i am trying to solve this programming riddle and although the solution see code below works correctly it is too slow for succesful submissionany pointers as how to make this runfaster removal of every nth element from a listor suggestions for a better algorithm to calculate the same seems i cannot think of anythingelse than bruteforce for nowbasically the task at hand isgivenl 23456789101 take the first remaining item in list l in the general case n move it to the lucky number list then drop every nth item from the list2 repeat 1taskcalculate the nth number from the lucky number list 1 and 30my original code it calculated the 30 first lucky numbers in about a second on my machine unfortunately too slowspoj problem set classical 1798 assistance requiredurl sieve range3 33900 2luckynumbers 2while true wanted and input if wanted and 0 break while lenluckynumbers wanted n item sieve0 luckynumbersappenditem items to delete setsieveitem sieve filterlambda x x not in items to delete sieve print luckynumberswanted n1edit thanks to the terrific contributions of mark dickinson steve jessop and gnibbler i got at the following which is quite a whole lot faster than my original code and succesfully got submitted at with 058 secondssieve range3 33810 2luckynumbers 2while lenluckynumbers 30 if lensieve sieve0 luckynumbersextendsieve break luckynumbersappendsieve0 del sievesieve0while true wanted and input if wanted and 0 break else print luckynumberswanted n1,['python'] +52623,how do i handle ties when ranking results in mysql how does one handle ties when ranking results in a mysql query i have simplified the table names and columns in this example but it should illustrate my problemset rank0 select student namesstudents rank rank 1 as rank scoresgrades from student names left join scores on student namesstudents scoresstudents order by scoresgrades descso imagine the the above query producesstudents rank gradesal 1 90amy 2 90george 3 78bob 4 73mary 5 nullwilliam 6 nulleven though al and amy have the same grade one is ranked higher than the other amy got rippedoff how can i make it so that amy and al have the same ranking so that they both have a rank of 1 also william and mary did not take the test they bagged class and were smoking in the boys room they should be tied for last placethe correct ranking should bestudents rank gradesal 1 90amy 1 90george 2 78bob 3 73mary 4 nullwilliam 4 nullif anyone has any advice please let me know,"['mysql', 'sql']" +52624,precomputed kernels with libsvm in python i have been searching the net for 3 hours but i could not find a solution yet i want to give a precomputed kernel to libsvm and classify a dataset buthow can i generate a precomputed kernel for example what is the basic precomputed kernel for iris datain the libsvm documentation it is stated thatfor precomputed kernels the first element of each instance must bethe id for example samples 1 0 0 0 0 2 0 1 0 1 3 0 0 1 1 4 0 1 1 2 problem svm problemlabels samples param svm parameterkernel typeprecomputedwhat is a id there is no further details on that can i assign ids sequentiallyany libsvm help and an example of precomputed kernels really appreciated,['python'] +52627,library to write javascript code is there a c library that can help to write and indent javascript codeit is because i am writing some c code that generated some javascript code something like this js script typetextjavascriptnjs functionnand i find that generated a lot of ugly codeso i thought that maybe a existing library can help me doing that,"['c#', 'javascript']" +52645,problem adding uibarbuttonitems to a toolbar i have a uinavigationcontroller with a uitableviewcontroller in it i want to show a toolbar on the bottom with uibarbuttonitems the toolbar is showing up but the buttons would not appear anyone knows why voidviewdidload super viewdidload self navigationitem settitleselections list self navigationitem setrightbarbuttonitemuibarbuttonitem alloc initwithbarbuttonsystemitemuibarbuttonsystemitemadd targetself actionselectoraddprojectsearch autorelease self navigationitem setleftbarbuttonitemself editbuttonitem super tableview setdatasource self super tableview setdelegate self toolbar uibarbuttonitem logoutbutton uibarbuttonitem alloc initwithtitlelog out styleuibarbuttonitemstyleplain targetself actionselectorlogoutautorelease nsmutablearray arr nsmutablearray arraywithobjectslogoutbutton nil self navigationcontroller settoolbarhidden no animatedyes self navigationcontroller settoolbaritemsarr animatedyes,"['iphone', 'objective-c']" +52646,c 40 dynamic does not set refout arguments i am experimenting with dynamicobject one of the things i try to do is setting the values of refout arguments as shown in the code below however i am not able to have the values of i and j in main set properly even though they are set correctly in tryinvokemember does anyone know how to call a dynamicobject object with refout arguments and be able to retrieve the values set inside the methodclass program static void mainstring args dynamic proxy new proxynew target int i 10 int j 20 proxywrapref i ref j consolewritelinei j print 1020 while expect 2010 class proxy dynamicobject private readonly target target public proxytarget target thistarget target public override bool tryinvokememberinvokememberbinder binder object args out object result int i int args0 int j int args1 targetswapref i ref j args0 i args1 j result null return true class target public void swapref int i ref int j int tmp i i j j tmp update 715microsoft claims to have fixed the issue for the next release of net update 982012tested using vsnet 2012 with both net 40 and 45 confirm it is already fixed,['c#'] +52654,getting the day from a unix timestamp php how do i get the day 17 from a unix timestamp in php i also need the day date 131 and month 112,['php'] +52676,thisable javascript error in webbrowser control i am developing a windows application with a webbrowser control that navigates to a sharepoint sitemy problem is that i am getting javascript errorhow can i thisable the javascript error i do not want them to pop up,"['c#', '.net']" +52709,c stringsubstr function problem i want to make a program that will read some number in string format and output it like this if the number is 12345 it should then output 12 23 34 45 i tried using the substr function from the c string library but it gives me strange results it outputs 1 23 345 45 instead of the expected result why include iostreaminclude stringinclude cstdlibusing namespace stdint mainvoid string acin a string bint c forint i0iasize1i b asubstrii1 c atoibc str cout c cout endl return 0,['c++'] +52722,how can i protect my net assemblies from decompilation one if the first things i learned when i started with c was the most important one you can decompile any net assembly with reflector or other tools many developers are not aware of this fact and most of them are shocked when i show them their source codeprotection against decompilation is still a difficult task i am still looking for a fast easy and secure way to do it i do not want to obfuscate my code so my method names will be abc or so reflector or other tools should be unable to recognize my application as net assembly at all i know about some tools already but they are very expensive is there any other way to protect my applicationseditthe reason for my question is not to prevent piracy i only want to stop competitors from reading my code i know they will and they already did they even told me somaybe i am a bit paranoid but business rivals reading my code does not make me feel good,"['c#', '.net']" +52745,how to print pdf file in a java application how do i print a pdf file from a java application,['java'] +52751,not receiving touchesendedmovedcancelled after adding subview title more or less says it all in response to a touchesbegan event my uiviewcontroller recolours itself and adds some subviews it never receives the touchesended i guess because the added subviews are somehow intercepting the event i tried calling resignfirstresponder on the subviews to no availthe code works fine when i do not add the child views and the touch events are called as normalany ideasthanksedit bit of detail and how i fixed itbasically i had a master view with some subviews when i touched the subview the event would be passed through to the master view however on this event i was removing the subviews and adding new ones in their place the fact that the touch originated on a subview which no longer existed meant that the rest of the touch was losti fixed this by overriding hittestwithevent in my master view to stop touches ever getting tested against the subviews,['iphone'] +52758,migrate from oracle to mysql we ran into serious performance problems with our oracle database and we would like to try to migrate it to a mysqlbased database either mysql directly or more preferably infobrightthe thing is we need to let the old and the new system overlap for at least some weeks if not months before we actually know if all the features of the new database match our needsso here is our situationthe oracle database consists of multiple tables with each millions of rows during the day there are literally thousands of statements which we cannot stop for migrationevery morning new data is imported into the oracle database replacing some thousands of rows copying this process is not a problem so we could in theory import in both databases in parallelbut and here the challenge lies for this to work we need to have an export from the oracle database with a consistent state from one day we cannot export some tables on monday and some others on tuesday etc this means that at least the export should be finished in less than one dayour first thought was to dump the schema but i was not able to find a tool to import an oracle dump file into mysql exporting tables in csv files might work but i am afraid it could take too longso my question now is what should i do is there any tool to import oracle dump files into mysql does anybody have any experience with such a largescale migrationps please do not suggest performance optimization techniques for oracle we already tried a lot edit we already tried some etl tools before only to find out that they were not fast enough exporting only one table already took more than 4 hours 2nd edit come on folks did nobody ever try to export a whole database as fast as possible and convert the data so that it can be imported into another database system,['mysql'] +52759,how long does the android emulator take to start do you need to closestart if every time you change java code when developing for android do you typically need to stop the emulator and restart it every time you make a change to your java code or is there a faster way the emulator takes about 15 minutes to start for me is this normal,['android'] +52763,inconsistency in modifiedcreatedaccessed time on mac i am having trouble using osutime to correctly set the modification time on the mac mac os x 1062 running python 261 from usrbinpython it is not consistent with the touch utility and it is not consistent with the properties thisplayed in the finders get info windowconsider the following command sequence the created and modified times in the plain text refer to the attributes shown in the get info window in the finder as a reminder osutime takes arguments filename atime mtime import os opentempfilewclosecreated and modified are both the current time osutimetempfile 10 150 created is the current time modified is july 13 2017 osutimetempfile 10 10 created and modified are both september 8 2001 ospathgetmtimetempfile10 ospathgetctimetempfile12690219390 ospathgetatimetempfile12690219510but the ospathgettime and osstat do not reflect it osutimetempfile 150 10 created and modified are still both september 8 2001 osutimetempfile 150 150 created is september 8 2001 modified is july 13 2017i am not sure if this is a python problem or a mac stat problem when i exit the python shell and runtouch a t 2011221234 tempfileneither the modification nor the creation times are changed as expected then i runtouch m t 2011221234 tempfileand both created and modified times are changeddoes anyone have any idea whats going on how do i change the modification and creation times consistently on the mac yes i am aware that on unixy systems there is no creation timeresult from running chris johnsens scriptsethlocal usrbinpython timetestpy tempfile 5initial12696312810 12696312810 12696312810 1269631281 1269631281 1269631281test 10 1010 10 12696312810 10 10 126963128112696312810 10 12696312810 1269631281 10 1269631281test 10 15010 150 12696312860 10 150 126963128612696312860 150 12696312860 1269631286 150 1269631286test 150 10150 10 12696312910 150 10 126963129112696312910 10 12696312910 1269631291 10 1269631291test 150 150150 150 12696312960 150 150 126963129612696312960 150 12696312960 1269631296 150 1269631296at the end of the exercise the created date as visible in the finder is 9801 and the modified date is 71317 the access date thanks to presumably spotlight as you suggest and as i have read about is roughly now the created and modified dates visible in the finder still make no sense,['python'] +52764,wrapping malloc c i am a beginner in c while reading git is source code i found this wrapper function around mallocvoid xmallocsize t size void ret mallocsize if ret size ret malloc1 if ret release pack memorysize 1 ret mallocsize if ret size ret malloc1 if ret dieout of memory malloc failed ifdef xmalloc poison memsetret 0xa5 sizeendif return retquestionsi could not understand why are they using malloc1what does release pack memory does and i cannot find this functions implementation in the whole source codewhat does the ifdef xmalloc poison memsetret 0xa5 size doesi am planning to reuse this function on my project is this a good wrapper around mallocany help would be great,['c'] +52780,global importusing aliasing in net using import aliasing in one fileclass we can reference class library namespaces by assigning our own custom alias like this vbimports db companylibdataobjects cusing db companylibdataobjectsand then we are able to reference the classes inside of companylibdataobjects by using the db alias that we assignedis it possible to do this at the global level so that the alias is applied to the entire solution instead of just one fileclasscurrently we are working with web applications so i was hoping we could add something to webconfig but i am also interested in whether or not this is possible with windows forms console apps andor class libraries,"['.net', 'asp.net']" +52806,absmiddle works differently on firefox and chrome i have an icon image and text like the following the code source of everything isimg src alignabsmiddle my title herethe problem is that the icon is not aligned vertically with the title in chrome compared to firefoxi think the absmiddle does not work at all is there any solution i do not want to use a table with 2 columns to fix this issue,"['html', 'css']" +52815,how to get scrollbar position with javascript i am trying to detect the position of the browser scrollbar with javascript to decide where in the page the current view is my guess is that i have to detect where the thumb on the track is and then the height of the thumb as a percentage of the total height of the track am i overcomplicating it or does javascript offer an easier solution than that any ideas codewise,['javascript'] +52819,javanetsockettimeoutexception read timed out i have an application with client server architecture the client use java web start with java swing awt and the sert uses http server servlet with tomcat the communication is made from the serialization of objects create a objectoutput serializes a byte array and send to the server respectively called the objectinputstream and deserializes the application follows communicating correctly to a certain time of concurrency where starting to show error socketexception read timeout the erro happens when the server invoke the method objectinputstreamgetobject in my servlet dopost method the tomcat will come slow and the errors start to decrease server response time until the crash time where i must restart the server and after everything works someone went through this problem client codeurlconnection conn urlopenconnectionconnsetdooutputtrueoutputstream os conngetoutputstreamobjectoutputstream oss new objectoutputstreamososswriteutfprotocol header sampleosswriteobject parametersossflushosscloseserver codeobjectinputstream input new objectinputstream requestgetinputstreamstring method inputreadutfparameters inputreadobjectinputreadobject is where the error is,['java'] +52821,how to protect yourself from xss when you allow people to post raw embed codes tumblr and other blogging websites allows people to post embeded codes of videos from youtube and all video networksbut how they filter only the flash object code and remove any other html or scripts and even they have an automated code that informes you this is not a valid video codeis this done using regex expressions and is there a php class to do that thanks,['php'] +52836,nsfetchedresultscontroller changing predicate not working i am writing an app with two tables on one screen the left table is a list of folders and the right table shows a list of files when tapped on a row on the left the right table will thisplay the files belonging to that folderi am using core data for storage when the selection of folder changes the fetch predicate of the right tables nsfetchedresultscontroller will change and perform a new fetch then reload the table data i used the following code snippetnspredicate predicate nspredicate predicatewithformatlist selflistfetchedresultscontrollerfetchrequest setpredicatepredicatenserror error nilif self fetchedresultscontroller performfetcherror nslogunresolved error error error userinfo aborttable reloaddatahowever the fetch results are still the same i have nsloged predicate before and after the fetch and they were correct with updated information the fetch results stay the same as initial fetch when view is loadedi am not very familiar with the way core data fetches objects is there a caching system but i have done similar things beforechanging predicates refetching data and refreshing table with single table views and everything went wellif someone could gave me a hint i would be very appreciatedthanks in advance,['iphone'] +52838,send an email using python script today i needed to send email from a python script as always i searched google and found the following script that fits to my needimport smtplibserver localhostfrom to must be a listsubject hellotext this message was sent with pythons smtplib prepare actual messagemessage from sto ssubject ss from jointo subject text send the mailserver smtplibsmtpserverserversendmailfrom to messageserverquitbut when i tried to run the program i got the following error messagetraceback most recent call last file cpython26emailpy line 1 in module import smtplib file cpython26libsmtplibpy line 46 in module import emailutils file cpython26emailpy line 24 in module server smtplibsmtpserverattributeerror module object has no attribute smtphow can i solve this problem any one can help methanks in advancenimmychanged the name to emailsendin py but i got the following errortraceback most recent call last file cpython26emailsendingpy line 24 in module server smtplibsmtpserver file cpython26libsmtplibpy line 239 in init code msg selfconnecthost port file cpython26libsmtplibpy line 295 in connect selfsock self get sockethost port selftimeout file cpython26libsmtplibpy line 273 in get socket return socketcreate connectionport host timeout file cpython26libsocketpy line 512 in create connection raise error msgerror errno 10061 no connection could be made because the target machine actively refused it,['python'] +52839,how can i create my own form designer i am starting my first c project and i want to make a form designer like the one in vsthe idea is there will be a visual form designer with a limited toolbox which will generate python code later more to create the same formproblem is i have no idea how to even get started first of all i have the form designer in vs how do i make a formwithinaformnext i have no idea how complicated this is going to be i suppose i could just make little boxes appear beside each control created on the form when it is clicked for resizing and make a textbox appear on it when double clicked or something to change the text in it things like thisso another thing i would like to know is thisi do have programming experience in c and c i have done php for a number of years and am starting with python as of recently i have generated forms dynamically in vb6 given this experience am i in way over my head with this project,['c#'] +52840,attaching linq to sql datacontext to httpcontext in business layer i need my linq to sql datacontext to be available across my businessdata layer for all my repository objects to access however since this is a web app i want to create and destroy it per request i am wondering if having a singleton class that can lazily create and attach the datacontext to current httpcontext would work my question is would the datacontext get thisposed automatically when the request ends below is the code for what i am thinking would this accomplish my purpose have a threadsafe datacontext instance that is lazily available and is automatically thisposed when the request endspublic class singletondc public static northwinddatacontext default get northwinddatacontext defaultinstance northwinddatacontextsystemwebhttpcontextcurrentitemsdatacontext if defaultinstance null defaultinstance new northwinddatacontext systemwebhttpcontextcurrentitemsadatacontext defaultinstance return defaultinstance,['asp.net'] +52842,easiest way of unit testing c code with python i have got a pile of c code that i would like to unit test using pythons unittest library in windows but i am trying to work out the best way of interfacing the c code so that python can execute it and get the results back does anybody have any experience in the easiest way to do itsome ideas includewrapping the code as a python c extension using the python apiwrap the c code using swigadd a dll wrapper to the c code and load it into python using ctypesadd a small xmlrpc server to the ccode and call it using xmlrpclib yes i know this seems a bit faroutis there a canonical way of doing this i am going to be doing this quite a lot with different c modules so i would like to find a way which is least effort,"['python', 'c']" +52850,where can i find reference barcodes to verify barcode library output this question is not about best barcode library recommendation we use various products on different platforms and need a simple way to verify if a given barcode is correct according to its specificationwe have found cases where a barcode is rendered differently by different barcode libraries and free online barcode generators in the internet for example a new release of a delphi reporting library outputs nonnumeric characters in code128 as 0 or simply skips them in the text area before we do the migration we want to check if these changes are caused by a broken implementation in the new library so we can report this as a bug to the authorwe mainly need code128 and uccean128 with abc subcodesonline resources i checked so far areidautomationcom thisplays abc123 as 0123 with code128cmoroviacombarcodesinc does not accept commatecitthey show different results too for example in support for characters like comma or plus signs at least in the human readable text,"['java', '.net']" +52860,oracle how to group by over a range if i have a table like thispkey age 1 8 2 5 3 12 4 12 5 22i can group by to get a count of each ageselect agecount and from tbl group by ageage n 5 1 8 1 12 2 22 1what query can i use to group by age ranges age n 110 21120 220 1,['sql'] +52869,playing sounds in iphone sdk does anyone have a snippet that uses the audiotoolbox framework that can be used to play a short sound i would be grateful if you shared it with me and the rest of the community everywhere else i have looked does not seem to be too clear with their codethanks,['iphone'] +52892,how do i supress keypress being printed to console in net i am porting a small c console game to c and it seems that i cannot stop key presses from being printed to the consolein c i get the keystroke with this method which also suppress the keystrokes from being printed to the consolebool gamegetinputchar c if kbhit c getch return true return falsei tried to do the equivalent in c by doingkey consolereadkeybut this does not suppress the character from being printed to the console causing obvious problems any ideas on how to remedy this,"['c#', '.net']" +52910,why is volatile not considered useful in multithreaded c or c programming as demonstrated in this answer i recently posted i seem to be confused about the utility or lack thereof of volatile in multithreaded programming contextsmy understanding is this any time a variable may be changed outside the flow of control of a piece of code accessing it that variable should be declared to be volatile signal handlers io registers and variables modified by another thread all constitute such situationsso if you have a global int foo and foo is read by one thread and set atomically by another thread probably using an appropriate machine instruction the reading thread sees this situation in the same way it sees a variable tweaked by a signal handler or modified by an external hardware condition and thus foo should be declared volatile or for multithreaded situations accessed with memoryfenced load which is probably a better a solutionhow and where am i wrong,"['c++', 'c']" +52931,stack overflow when calculating the 101st prime number in java i am doing problem 7 of project euler what i am supposed to do is calculate the 101st prime number a prime number is an integer greater than one that is only divisible by itself and onehere is my current programpublic class problem7 public static void mainstring args long numberofprimes 0 long number 2 while numberofprimes 101 if isprimenumber numberofprimes number systemoutprintln101st prime number public static boolean isprimelong n if n 1 return false else return primen and 1 public static boolean primelong x long y if y 1 return true else if x y 0 return false else return primex y 1 it works okay with finding say the 100th prime number but running with very large inputs such as 101 results in stack overflow why and how can i fix this,['java'] +52939,how can i run nhibenate queries asynchronously one way to increase scalability of the server application is to run iobound operation reading files sockets web requests database requests etc asynchronously this does not mean run them in the threadpool which will just block threads while operation is being executed the correct way is to use asynchronous api beginread begingetresponse beginexecutereader etc the problem is well described in clr vi c bookhere is some article about asynchronous queries in linq to sqlare any ways to execute nhibernate query asynchonously what about linq to nhibernatethank youandrey,['.net'] +52943,tips on how to deploy c code to work every where i am not talking about making portable code this is more a question of thistribution i have a mediumsized project it has several dependencies on common libraries eg openssl zlib etc it compiles fine on my machine and now it is time to give it to the worldessentially build engineering at its finest i want to make installers for windows linux macosx etc i want to make a downloadable tar ball that will make the code work with a configure and a make probably via autoconf it would be icing on the cake to have a make option that would build the installersmaybe even crosscompile so a windows installer could be built in linuxwhat is the best strategy where can i expect to spend the most time should the prime focus be autoconf or are there other tools that can help,['c++'] +52947,java virtual methods how does virtual functions work behind the scenes in inheritance does the compiler treat virtual functions specially,['java'] +52950,implementing getenumerator for a collection inherited from list i am trying to implement filepathcollection its items would be simple file names without a path such as imagejpg once the collection is used via foreach cycle it should return the full path created by concatenating with basedirectory how can i do that public class filepathcollection liststring string basedirectory public filepathcollectionstring basedirectory thisbasedirectory basedirectory new public systemcollectionsienumerator getenumerator foreach string value in this items this does not work because list is private yield return basedirectory value,['c#'] +52953,extra leading zeros when printing float using printf i would like to be able to write a time string that looks like this 104021 hours using printfwhen i try to write something like this printfd02d021f hoursn 1 4 2123456i get10421 hoursis it possible to add leading zeros to a float formatting,"['c++', 'c']" +52960,how to connect to sql server from another computer i want to connect from home using sql server 2005 to another pci had a look on the msdbut before connecting it says i should connect to another computerusing the computer management and it did not work outi can only connect to computers from my workgroup thanksluisa,['sql'] +52966,linux c how to profile time wasted due to cache misses i know that i can use gprof to benchmark my codehowever i have this problem i have a smart pointer that has an extra level of indirection think of it as a proxy objectas a result i have this extra layer that effects pretty much all functions and screws with cachingis there a way to measure the time my cpu wastes due to cache missesthanks,['c++'] +52988,progressdialog not working in external asynctask i am beginning to think that to get a progressdialog to work the asynctask has to be an inner class within an activity class true edited much laterthe answer is false and i am not sure if this is a bug or what i am using android 15 i am going to read up on servicesi have an activity the uses a database to manipulate information if the database is populated all is well if it is not populated then i need to download information from a website populate the database then access the populated database to complete the views in oncreateproblem is without some means to determine when the asynctask thread has finished populating the database i get the following force close error message sorry the application has stopped unexpectedly i click on the force close button the background asynctask thread continues to work the database gets populated and everything works oki need to get rid of that error message and need some help on how to do this heres some psuedo codepublic class viewstuff extends activity oncreate ifdatabase is populated do stuff else filldb task null iftask null taskgetstatusequalsasynctaskstatusfinished task new filldbcontext taskexecutenull continue with oncreate using information from database to properly thisplay end oncreate end classin a separate filepublic class filldb extends asynctaskvoid void void private context context public filldb context c pass the context in the constructor context c public void filldb doinbackground override protected void onpreexecute progressdialog progressdialog new progressdialogcontext crashes with the following line progressdialogshowcontext working retrieving info override protected void doinbackgroundvoid params todo autogenerated method stubtry etc etc etc heres the stack trace from the emulator pid 846 at 20100321 195825 cmd line comtrialdalvik threadsmain prio5 tid3 native groupmain scount1 dscount0 s0 obj0x40018e70 systid846 nice0 sched00 handle1098855268 at androidosbinderproxytransactnative method at androidappactivitymanagerproxyhandleapplicationerroractivitymanagernativejava2103 at comandroidinternalosruntimeinitcrashruntimeinitjava302 at comandroidinternalosruntimeinituncaughthandleruncaughtexceptionruntimeinitjava75 at javalangthreadgroupuncaughtexceptionthreadgroupjava887 at javalangthreadgroupuncaughtexceptionthreadgroupjava884 at dalviksystemnativestartmainnative method binder thread 3 prio5 tid15 native groupmain scount1 dscount0 s0 obj0x43733d88 systid852 nice0 sched00 handle1486928 at dalviksystemnativestartrunnative methodbinder thread 2 prio5 tid13 native groupmain scount1 dscount0 s0 obj0x437313c8 systid851 nice0 sched00 handle1492472 at dalviksystemnativestartrunnative methodbinder thread 1 prio5 tid11 native groupmain scount1 dscount0 s0 obj0x4372b9b0 systid850 nice0 sched00 handle1492664 at dalviksystemnativestartrunnative methodjdwp daemon prio5 tid9 vmwait groupsystem scount1 dscount0 s0 obj0x4372a2a0 systid849 nice0 sched00 handle1490176 at dalviksystemnativestartrunnative methodsignal catcher daemon prio5 tid7 runnable groupsystem scount0 dscount0 s0 obj0x4372a1e8 systid848 nice0 sched00 handle14878 at dalviksystemnativestartrunnative methodheapworker daemon prio5 tid5 vmwait groupsystem scount1 dscount0 s0 obj0x427d03c0 systid847 nice0 sched00 handle1487592 at dalviksystemnativestartrunnative method end 846 what am i doing wrongmr snowflaketriedoverrideprotected void onpreexecuteactivitythisrunonuithreadnew runnable public void run progressdialog progressdialog new progressdialogcontext crashes with the following line progressdialogshowcontext working retrieving info activitythis is flagged as an errorno enclosing instance of the type activity is accessible in scopei am thinking i need to filldb extends activity then create a private class within filldb extending asynctask that wont work no assurance when the filldb activity will start and cannot use startactivityforresult since no result is returned from asynctask when it is completedupdate tried creating a private class in the calling class still cannot show a progressdialog one of the errors is unable to add window token null is not for an application i have no idea what token is being referred to,['android'] +52989,how do i determine what is touched in 3d space from the screen how do i use glgluunproject in my opengl es 11 android app to determine what is selected when the user touches the screenmy understanding is that the touch event results in a line and i have to find the first thing it intersects withare there any tutorials on how to do this,['android'] +52998,converting iphone xib to ipad xib how do you do it i saw one video tutorial on it but the screen was too small also other than changing the view size are there any other major changes i would have to make to my iphone apps to convert to ipad,['iphone'] +53008,pyopengl could it replace c i am starting a computer graphics course and i have to choose a languagechoices are between c and python i have no problem with c python is a work in progress so i was thinking to go down the python road using pyopengl for graphics parti have heard though that performance is an issueis python pyopengl mature enough to challenge c on performancei realize its a long shot but i would like to hear your thoughts experiences on uses of pyopenglthanks in advance,['python'] +53010,gettype and unknown type in php i just start to practice with php builtin gettype and its return value this function is capable to return testing result such as boolean integer unknown type etc but among those testing result there is one caught my eyes unknown type after reading gettype and try to find some reference here i can not get any so the question is what kind of type can be categorized as unknown type is it possible or am i just missing reading something,['php'] +53012,how to clone a project on heroku i have a project on heroku working fine now i want to create same project with different url same code as the one i have working now so that i can give the new url to the customer as a test site i know in heroku i can just rename the url but i want to completely separate development from test database wise what is the best solution do i start from scratch cd into new folder on my machineclone project from githubmake new database test push to herokuetc etc,['ruby-on-rails'] +53018,passing empty list as parameter to jpa query throws error if i pass an empty list into a jpa query i get an error for examplelistmunicipality municipalities mydaofindall returns empty listemcreatequeryselect p from profile p join pmunicipality m where m in municipalities setparametermunicipalities municipalities getresultlistbecause the list is empty hibernate generates this in sql as in which gives me error with hypersonic databasethere is a ticket for this in hibernate issue tracking but there are not many commentsactivity there i do not know about support in other orm products or in jpa spec eitheri do not like the idea of having to manually check for null objects and empty lists every time is there some commonly known approachextension to this how do you handle these situations,['java'] +53020,removing inline styles using php i am using php to output some rich text how can i strip out the inline styles completelythe text will be pasted straight out of ms word or openoffice and into a which uses tinymce a richtext editor which allows you to add basic html formatting to the text however i want to remove the inline styles on the tags see below but preserve the tags themselves p stylemarginbottom 0cma patrol of zograth apes came round the corner causing rosette to pull rufus into a small alcove where she pressed her body against his ldquosorryrdquo she said breathing warm air onto the shy mans neck rufus trembledpp stylemarginbottom 0cmnbsp stylemarginbottom 0cmrosette checked the coast was clear and pulled rufus out of their hidey hole they watched as the zograth walked down a corridor almost out of sight and then collapsed next to a phallic fountain as their bodies hit the ground their guns clattered across the floor rosette stopped one with her heel and picked it up immediately tossing the other one to rufus ldquomost of these apes seem to be dying but you might need this just to give them a helping handrdquop,['php'] +53022,how do i remove the top margin in a web page i have had this problem with every web page i have created there is always a top margin above the main container div i use to place my content in the center of the page i am using a css style sheet and have set margins and padding in the body to 0px and set the margin and padding to 0 in the div body margintop 0px marginbottom 0px marginleft 0px marginright 0px padding 0 color black fontsize 10pt fontfamily trebuchet ms sansserif backgroundcolor e2e2e2divmaincontainer height auto width 68em backgroundcolor f margin 0 auto padding 0i have looked online many times but all i can see to do is set these margin and padding attributes is there something else i should be doing the margin exists in ie and firefoxhere is a more thorough look at the code it is in the beginning stages of creation so there is not much in itdoctype html public w3cdtd xhtml 10 transitionalen html xmlns head meta httpequivcontenttype contenttexthtml charsetutf8 templatebegineditable namedoctitle titletitle templateendeditable templatebegineditable namehead templateendeditable link hrefstyleskb styles1css relstylesheet typetextcss head body div classmaincontainer phere is the informationp div bodyhtmlhere is the csscharset utf8 css document body margintop 0px marginbottom 0px marginleft 0px marginright 0px padding 0 color black fontsize 10pt fontfamily trebuchet ms sansserif backgroundcolor e2e2e2 section dividers divmaincontainer position relative height auto width 68em backgroundcolor f margin 0 auto padding 0divheader padding 0 margin 0divleftsidebar float left width 22 height 40em margin 0divmaincontent marginleft 25divfooter clear both paddingbottom 0em margin 0 hide from ie5mac only iewin sees this html divleftsidebar marginright 5px html divmaincontent height 1 marginleft 0 end hide from ie5mac,"['html', 'css']" +53032,strikethrough font in objective c how can i use strikethrough font in objective c more specifically in uitableviewcellcelltextlabeltext namecelldetailtextlabeltext quantity cellx,"['iphone', 'objective-c']" +53035,tricky model inheritance django i think this is a bit tricky at least for me so i have 4 models person singer bassist and ninjasinger bassist and ninja inherit from personthe problem is that each person can be any of its subclasses eg a person can be a singer and a ninja another person can be a bassist and a ninja another one can be all threehow should i organise my modelshelp would be much appreciated,['python'] +53042,how to set text in a uitextview as a link to a url i have some text in a uitextview that i would like to have show as blue and serve as a link to a website how do i do that in interface builder,['iphone'] +53051,regular expression for checking website url i need to check the web address using regular expression if user type url aswtestcomi have a regular expression likehttpazaz09 azaz09 azaz24azaz09 azaz09 azaz24azaz09 azaz09 azaz09 azaz09 but it will only allow the second option only how can i modify the regular expression so that it should accept 1st and 3rd option too,['php'] +53060,iphone floats cast to unsigned ints get set to 0 if they are negative try it outvolatile float bob 3440funsigned int fred unsigned intbobprintfdnfredoutput will be 0obviously i am expecting it to wrap around just as if i had cast from a signed int to an unsgined int which does wrap and act as expected on the iphonewe assume it is something to do with the floating point settingsany ideas,['iphone'] +53068,how to reduce the size of my iphone application alternative titles to aid searchescompressing pngsreduce the size of an iphone archive ipaadding a build rule to compress images in xcodeios apps can only be downloaded via 3g if they are less than 100mb what are the best strategies for reducing the size of an appareas i would like to focus on areimagesdatabasescode static libraries nb the original question can be viewed in the revisions of this question,['iphone'] +53074,obtaining excel worksheet reference by worksheet name via c i am currently obtaining a handle to a excel worksheet by using the below c codeexcelworksheet worksheet excelworksheetsheetsget item15get the worksheet subsignoff numberis there any way that i can obtain the same by using the worksheet name subsignoff many thanks for your helpchapax,['c#'] +53081,branchless memory manager anyone thought about how to write a memory manager in c that is completely branch free i have written a pool a stack a queue and a linked list allocating from the pool but i am wondering how plausible it is to write a branch free general memory managerthis is all to help make a really reusable framework for doing solid concurrent inorder cpu and cache friendly developmentedit by branchless i mean without doing direct or indirect function calls and without using ifs i have been thinking that i can probably implement something that first changes the requested size to zero for false calls but have not really got much more than thati feel that it is not impossible but the other aspect of this exercise is then profiling it on said unfriendly processors to see if it is worth trying as hard as this to avoid branching,['c++'] +53082,how to process boosttest output with eclipse i am using eclipse cdt and boosttestwith boostbuild i would like eclipse to parse output of boosttest generated during by run of test suites during builddoes anybody know how to achieve this thanks in advance,['c++'] +53083,get current url of uiwebview i already tried getting the current url of my uiwebview with webviewrequesturlunfortunately the nsurl was empty anything wrong here i am working with xcode 322 beta 5the code above should be executed in the uiwebview delegate didstartload,['iphone'] +53085,jquery intercept links created by ajax request i have some jquery code that intercepts links clicked on a pagedocumentreadyfunction aclickfunction do something here my problem is there are certain parts of the page that have not finished loading on document ready they are populated via ajax calls the links in these sections are not intercepted by my jquery function abovei need the function to be run on document ready initially but then i need the new links to also have the same logic applied to themany help would be very much appreciated this is an area that i am very unfamiliar with i have written the jquery stuff but the ajax code is an external component that i have no control over,"['javascript', 'jquery']" +53088,why do i need to use inject0 rather than inject to make this work i am creating a rails app and have used this code in one of my methodsitem numbersinject0 sum i sum iamountitem numbers is an array of objects from my item numbers table the amount method that i apply to them looks up the value of an item number in a separate table and returns it as a bigdecimal object obviously the inject method then adds all of the returned iamount objects and this works just finei am just curious as to why it did not work when i wrote this statement asitem numbersinject sum i sum iamountaccording to my trusty pickaxe book these should be equivalent is it because iamount is a bigdecimal if so why does it now work if not then why does not it work,"['ruby-on-rails', 'ruby']" +53091,class diagram in eclipse is there a visual studio like plugin for eclipse that will allow me create a classdiagram preferable something that is actually up to date most of what google finds is dead projects who have not been updated in 26 years,['java'] +53097,how to color and alignment spinner item on android i am try to change text color and align item in spinner to center of it how can i do thishere is my code string li123final spinner combo spinnerfindviewbyidridwidget30arrayadapterstring a new arrayadapterstringthisandroidrlayoutsimple spinner item licombosetadapterathanks,['android'] +53098,how to view contents of stl containers using gdb 7x i have been using the macro solution as it is outlined here however there is a mention on how to view them without macros i am referring to gdb version 7 and abovewould someone illustrate howthanks,['c++'] +53100,query to find tables modified in the last hour i want to find out which tables have been modified in the last hour in a mysql database how can i do this,['mysql'] +53104,how to persist an entity which contains a field of user type using jpa2 i am looking for a way to persist an entity which contains a field of a user type in this particular example i would like to persist the ts field as number of millisecondsimport orgjodatimedatetimeentitypublic class foo id private long id private datetime ts,['java'] +53113,webkit browser in a java app i was wondering if there was a java swing component that uses webkitis it possible to create a webkit browser in java must i use javafx,['java'] +53118,how do i introspect things in ruby for instance in python i can do things like this if i want to get all attributes on an object import sys dirsys thisplayhook doc excepthook name package stderr stdin stdout clear type cache current frames getframe api version argv builtin module names byteorder call tracing callstats copyright thisplayhook dont write bytecode exc clear exc info exc type excepthook exec prefix executable exit flags float info getcheckinterval getdefaultencoding getdlopenflags getfilesystemencoding getprofile getrecursionlimit getrefcount getsizeof gettrace hexversion maxint maxsize maxunicode meta path modules path path hooks path importer cache platform prefix ps1 ps2 py3kwarning pydebug setcheckinterval setdlopenflags setprofile setrecursionlimit settrace stderr stdin stdout subversion version version info warnoptionsor if i want to view the documentation of something i can use the help function helpstris there any way to do similar things in ruby,['ruby'] +53119,merge vs upsert i have an application iam writing in access with a sql server backend one of the most heavily used parts is where the users selects an answer to a question a stored procedure is then fired which sees if an answer has already been given if it has an update is executed if not an insert is executedthis works just fine but now we have upgraded to sql server 2008 express i was wondering if it would be betterquickermore efficient to rewrite this sp to use the new merge commanddoes anyone have any idea if this is faster than doing a select followed by either an insert or update,['sql'] +53133,undocumented mac calls i am working on a couple of mac products and in order to do what i need to do i am using some calls to undocumented methods on mac classes like ikimageviews dorotateidand pdfdocumentsnsprintoperation getprintoperationforprintinfonsprintinfo printinfo autorotatebooldorotatehow common is it for objective c programmers to use methods like this how do you find out about them other than google how dangerous is it to use them is there a danger other than that apple will make them nolonger available in some future rev and so your program will break,['objective-c'] +53136,remove specific objects from a list i have a class that has an listbook in it and those book objects has many many propertieshow can i remove from that list every book that his level value is different than for example 5,['c#'] +53143,how can i tell the data annotations validator to also validate complex child properties can i automatically validate complex child objects when validating a parent object and include the results in the populated icollectionvalidationresultif i run the following codeusing systemusing systemcollectionsgenericusing systemcomponentmodeldataannotationsnamespace consoleapplication1 public class person required public string name get set public address address get set public class address required public string street get set required public string city get set required public string state get set class program static void mainstring args person person new person name null address new address street 123 any st city new york state null var validationcontext new validationcontextperson null null var validationresults new listvalidationresult var isvalid validatortryvalidateobjectperson validationcontext validationresults consolewritelineisvalid validationresultsforeachr consolewritelinererrormessage consolereadkeytrue i get the following outputfalsethe name field is requiredbut i was expecting something similar tofalsethe name field is requiredthe state field is requiredi offered a bounty for a better child object validation solution but did not get any takers ideallyvalidating child objects to an arbitrary depthhandling multiple errors per objectcorrectly identifying the validation errors on the child object fieldsi am still surprised the framework does not support this,['c#'] +53146,can we control linq expression order with skip take and orderby i am using linq to entities to thisplay paged results but i am having issues with the combination of skip take and orderby callseverything works fine except that orderby is assigned too late it is executed after result set has been cut down by skip and takeso each page of results has items in order but ordering is done on a page handful of data instead of ordering of the whole set and then limiting those records with skip and takehow do i set precedence with these statementsmy example simplifiedvar query ctxentitysetwhere filter orderbydescendinge echangeddateint total querycountvar result queryskipntakextolistone possible but a bad solutionone possible solution would be to apply clustered index to order by column but this column changes frequently which would slow database performance on inserts and updates and i really do not want to do thatediti ran totracestring on my query where we can actually see when order by is applied to the result set unfortunately at the end select columnsfrom select columns from select columns from select columns from table1 as extent1 where exists select single constant column from table2 as extent2 where extent1id extent2id and extent2userid p linq 4 as project2 limit 010 as limit1 left outer join select columns from table2 as extent3 as project3 on limit1id project3idunion all select columns from select columns from select columns from table1 as extent4 where exists select single constant column from table2 as extent5 where extent4id extent5id and extent5userid p linq 4 as project6 limit 010 as limit2 inner join table3 as extent6 on limit2id extent6id as unionall1order by unionall1changeddate desc unionall1id asc unionall1c1 asc,['mysql'] +53147,how to switch position of two items in a python list i havenat been able to find a good solution for this problem on the net probably because switch position list and python are all such overloaded wordsitas rather simple aa i have this listtitle email password2 password1 first name last name next newsletteriad like to switch position of password2 and password1 aa not knowing their exact position only that theyare right next to one another and password2 is firstiave accomplished this with some rather longwinded listsubscripting but i wondered its possible to come up with something a bit more elegant,['python'] +53159,sshrsa public key validation using a regular expression what regular expression can i use if any to validate that a given string is a legal ssh rsa public keyi only need to validate the actual key i do not care about the key type the precedes it or the username comment after itideally someone will also provide the python code to run the regex validationthanks,['python'] +53162,alternate cause of badimageformatexception in net assembly i am working on a net 35 console application in c which uses a vc unmanaged dll it ran without a problem when i worked on it a few weeks ago but i am coming back to it today and am now getting a badimageformatexception an attempt was made to load a program with an incorrect format exception from hresult 0x80070bmy development workstation is running 64bit windows 7 and i do a fair amount of work with unmanaged code so i immediately checked that the net assembly and the vc library both had x86 targets they did just to be sure i cleaned and rebuilt the vc library and the net assembly to no avail neither system is doing anything particularly unusual the vc library loads a binary data file and does some mathematical processing on its contents the net assembly has the dllimports for the library and some code to wire it up this all worked a few weeks agoso now i am left wondering if there is some other cause of badimageformatexception that is less common than an x86x64 conflict that i might be running intothanksedit i get the same error regardless of x86 or x64 mode but when set to any cpu execution gets past that point but execution aborts on a later call to the vc library with no exception regardless of whether that is related to this problem is there something that any cpu does differently from both x86 and x64 which could shed some light on this,"['c#', 'c++']" +53168,how do i find the return type of a method with systemreflectionmethodbase in c how do i find out the return type of a method from the methodbase i am using postsharp and trying to override the compiletimevalidatemethodbase method method to make sure the attribute is applied to a method with the correct signaturethanks,"['c#', '.net']" +53175,settings variable values in a moq callback call i think i may be a bit confused on the syntax of the moq callback methods when i try to do something like thisifilter filter new filterlistifoo objects new listifoo new foo new foo iqueryable myfilteredfoos nullmockobjectsetupm mgetbyfilteritisanyifilter callback ifilter filter myfilteredfoos filterfiltercollectionobjects returnsmyfilteredfooscastifoobarthis throws a exception because myfilteredfoos is null during the castifoobar call is this not working as i expect i would think filtercollection would be called and then myfilteredfoos would be nonnull and allow for the cast filtercollection is not capable of returning a null which draws me to the conclusion it is not being called also when i declare myfilteredfoos like thisqueryable myfilteredfoosthe return call complains that myfilteredfoos may be used before it is initialized,"['c#', '.net']" +53177,optimal eclipse cdt c experience in march of 2010 i am a student who will be using c next quarter i really enjoyed using the galileo release of eclipse with java and i would like to continue using eclipse for for c developmenti am now experimenting with c development on eclipse i am running eclipse 35 sr2 with cdt 602 my operating system is windows 7 and i have installed mingw516 version 63 of gdb is installedi have it compiling and stepping through code however i have the suspicion that i am just crawling along and have yet to shift the car out of first gear i have spent about a week poking around on the web to learn what constitutes and optimal c eclipse experience in particular i am interested in roundtripping with uml and unit testingmy exploration of the web became an archeological dig i turned up howto articles from 2003 alternative mingw thistros references to plugins deadlinks more references to plugins passionate thiscussions on gdb bugs and more references to plugins i no longer have any idea what might constitute an optimal c eclipse environment would members of the community like to weighin on what they consider to be the current optimal experience for c development using eclipse,['c++'] +53186,is there any lame c wrapersimplifier working on linux mac and win from pure code so i want to create simple pcm to mp3 c project i want it to use lame i love lame but it is realy big so i need some kind of opensource working from pure code with pure lame code workflow simplifier so to say i give it file with pcm and dest file call something like lamesimpletomp3file with pcm file with mp3 44100 16 mp3 vbr ore such thing in 4 5 lines examples ofcourse should exist and i have vhat i needed it should be light simple powerfool opensource crossplatformis there any thing like this,"['c++', 'c']" +53191,define a method that is a closure in ruby i am redefining a method in an object in ruby and i need the new method to be a closure for exampledef mess it upo x blah blah def oto s puts x wrong x does not exists here a method is not a closure endendnow if i define a proc it is a closuredef mess it upo x blah blah xp procnew puts x this works end but how do i set it to oto s def oto s xpcall same problem as before endendany ideas how to do itthanks,['ruby'] +53195,c where does the dbml file come from i am currently learning c and linq i have lots of questions about them basically i need a step by step tutoriali suppose the dbml file is the configuration file of the database if i double click the dbml file vs will open it in a design diagram can i createdeletemodify tables here i can use add new item to add the linq to sql classes to get a dbml filewhats next generate tables in database generate sql script generate cs files when how,['c#'] +53197,how to parse wsdl in java i need parser for wsdl to get the messages porttypes operations bindings servicesi hope some parser already exists so any guidlines,['java'] +53203,net and p2p writing a p2p messenger does anyone have any advice how to write such app or maybe knows some nice tutorial i would like to use systemnetpeertopeer namespace but everything i can find about it is msdn which i cannot read without getting mad or maybe using oldschool tcpip would more efficienti will appreciate every piece of advice every sample code i will shower with gold and please do not send me back to google for i have searched for a long time for sth useful maybe inaccurately but time is running out and i really need some helpeditwhat about the brunet library has anyone used it,"['c#', '.net']" +53209,css is it possible to get a div that is 100 height less a top and bottom margin i can get a 100 height div like this doctype html public w3cdtd html 401en html xmlns xmllangen langen head titlet5title meta httpequivcontenttype contenttexthtml charsetutf8 link relstylesheet typetextcss href link style typetextcss padding 0 margin 0 html body height 100 body fontfamily lucida sans verdana arial helvetica sansserif fontsize 75 h1 fontweight bold fontsize 14em padding 10px 10px 0 p padding 0 10px 1em container minheight 100 backgroundcolor d borderleft 2px solid 6 borderright 2px solid 6 width 280px margin 0 auto html container height 100 style head body div idcontainer h1100 height divh1 plorem ipsum p div bodyhtmlit looks like this when i say 100 height i mean it stays full height regardless of how much content is in the div and regardless of how the window gets resizedbut is it possible to get a div with a height of almost 100 height if i want margins at the top and bottom can i do that i want it to look like this i can do this with javascriptcss can i do it with just css answeryes it is possible with absolute positioning container width 380px backgroundcolor d border 2px solid 6 position absolute top 20px margin from top bottom 20px margin from bottom left 50 start left side in middle of window marginleft 190px then reverse indent overflow auto scrollbar as necessary result thanks to keithjgrant for the answer see all the code at,"['html', 'css']" +53216,what is the best way to generate kml files in c what is the best way to generate kml files using cis there a class library that i can use i have looked and struggled to find anything interesting libkml does not have a c implementation or wrapper any help would be great,['c#'] +53224,accessing array values without square brackets in php in php how can i access an arrays values without using square brackets around the key my particular problem is that i want to access the elements of an array returned by a function say functionargs returns an array why is var functionargs0yelling at me about the square brackets can i do something like var functionargsvalue0or am i missing something very basic,['php'] +53226,setting library include paths in c i just installed gd2 using mac ports sudo install gd2 which installed libraries in the following placesoptlocalincludegdhoptlocalliblibgddylib linkoptlocalliblibgdlaoptlocalliblibgdahere is my make file alsodev maino g loptlocallib ioptlocalinclude lgd lpng lz ljpeg lfreetype lm maino o heatmapmaino maincpp g c maincppso when i create my c app i add include gdh which throwsmaincpp416 error gdh no such file or directoryif i set gdh as an absolute path as abovenot a solution but was curious i am throwng loptlocalinclude loptlocallib maino o heatmapundefined symbols gdimagepng referenced from main in maino gdimageline referenced from main in maino gdimagecolorallocate referenced from main in maino main in maino gdimagedestroy referenced from main in maino gdimagecreate referenced from main in maino gdimagejpeg referenced from main in mainold symbols not foundso i understand this means that ld can not find the libraries it needs hence trying to give it hints with the l values so after giving g the l hints and the absolute path in include i can get it to work but i do not think i have to do this how can i make gld search int eh right places for the librariesdrew j sonneps using osx 1062 gcc version 421 apple inc build 5646 dot 1editok so after taking into account stfanb and michaels answer i have recompiled gd into a local directory libraries and thus i have changed that first line of my makefile i will def check out cmake to g llibrarieslib ilibrariesinclude lgd lpng lz ljpeg lfreetype lm maino o heatmapbut i am still getting maincpp316 error gdh no such file or directoryeditthanks all for the answers heres my final working makefile for anyone else who many want an answerdev maino g ilibrariesinclude llibrarieslib lgd lpng lz ljpeg lfreetype lm maino o heatmapmaino maincpp g ilibrariesinclude c maincpp,['c++'] +53227,how to thisable excels auto recognition of numbers and text i used python to generate a csv file but when i open it in excel excel will auto recognize a string into a number if it could be converted eg33e105 becomes 3310105 which is actually an id not a number how to thisable this in excel while opening a csv file or i need to resort to a excelpython library to output a excel file and specify the format myselfi also found a similar question without good answers on the web thanks,['python'] +53233,how to listen for changes to the title element in javascript is there a technique to listen for changes to the title element,['javascript'] +53240,why does intval199 100 equal 1989 boy this one is really weird i expect the following code to print 1990 but it prints 1989val 199val preg replacedvalval intvalval 100echo valwhy on earth is this happeningedit and this codeval 199val preg replacedvalecho val brval val 100echo val brval intvalvalecho valprints19919901989why does intval1990 equal 1989,['php'] +53246,memory leak of javalangrefweakreference objects inside jdk classes the following simple code reproduces the growth of javalangrefweakreference objects in the heappublic static void mainstring args throws exception while true javautilloggingloggergetanonymousloggerthreadsleep1here is the output of jmap command within a few seconds intervalusert1007 jmap d64 histolive 29201grep weakreference8 22493 1079664 javalangrefweakreference31 1 32144 ljavalangrefweakreference106 17 952comsunjmxmbeanserverweakidentityhashmapidentityweakreferenceusert1007 jmap d64 histolive 29201grep weakreference8 23191 13168 javalangrefweakreference31 1 32144 ljavalangrefweakreference103 17 952comsunjmxmbeanserverweakidentityhashmapidentityweakreferenceusert1007 jmap d64 histolive 29201grep weakreference8 23804 1142592 javalangrefweakreference31 1 32144 ljavalangrefweakreference103 17 952 comsunjmxmbeanserverweakidentityhashmapidentityweakreferencenote that jmap command forces fullgcjvm settingsexport jvm optd64 xms200m xmx200m xxmaxnewsize64m xxnewsize64m xxuseparnewgc xxuseconcmarksweepgc xxmaxtenuringthreshold10 xxsurvivorratio2 xxcmsinitiatingoccupancyfraction60 xxusecmsinitiatingoccupancyonly xxcmsparallelremarkenabled xxthisableexplicitgc xxcmsclassunloadingenabled xxprintgctimestamps xxprintgcdetails xxprinttenuringthistribution xxprintgcapplicationconcurrenttime xxprintgcapplicationstoppedtime xxprintgcapplicationstoppedtime xxprintclasshistogram xxparallelrefprocenabled xxsoftreflrupolicymspermb1 verbosegc xloggcgclogfilejava version 160 18javatm se runtime environment build 160 18b07java hotspottm server vm build 160b13 mixed modesolaris 10sun firetm t10,['java'] +53247,python overriding class not instance special methods how do i override a class special methodi want to be able to call the str method of the class without creating an instance exampleclass foo def str self return barclass staticfoo staticmethod def str return staticbarclass classfoo classmethod def str cls return classbarif name main printfoo printfoo printstaticfoo printstaticfoo printclassfoo printclassfooproducesclass main foobarclass main staticfoostaticbarclass main classfooclassbarshould bebarbarstaticbarstaticbarclassbarclassbareven if i use the staticmethod or classmethod the str is still using the builtin python definition for str it is only working when it is foo str instead of foo str,['python'] +53263,sql sort order with null values last i have the following testcodecreate table foo foo intinsert into foo select 4insert into foo select nullinsert into foo select 2insert into foo select 5insert into foo select 1select from foo order by case when foo is null then foo desc else foo enddrop table fooi am trying to produce the following output12345nullif null then put it lasthow is that done using sql 2005 m,['sql'] +53268,when is an autoreleased object actually released i am new in objectivec and i am trying to understand memory management to get it rightafter reading the excellentmemory management programming guide for cocoa by apple my only concern is when actually an autoreleased object is released in an iphoneipod application my understanding is at the end of a run loop but what defines a run loop in the applicationso i was wondering whether the following piece of code is right assume an objectimplementation test nsstring functiona nsstring stringa stringa nsstring alloc initwithstringhello autorelease return stringa nsstring functionb nsstring stringb stringb self functiona return stringb nsstring functionc nsstring stringc stringc self functionb return stringc voidviewdidload super viewdidload nsstring p self functionc nslogstring is pendis this code valid from the apple text i understand that the nsstring returned from functiona is valid in the scope of functionb i am not sure whether it is valid in functionc and in viewdidloadthanks,"['objective-c', 'iphone']" +53296,how to thisplay result of subquery rows as one column in mysql hi i have three tables category movies and relcatmovcategorytable categoryid categoryname1 thriller2 supsense3 romantic4 action5 scifimoviestablemovieid moviename1 avataar2 titanic3 ninjaassassinrelcatmovtablecategoryid movieid1 12 23 24 25 2now i want to thisplay a the record asmoviename categoriestitanic suspenseromanticscifiactionhow to do thisi am writing a queryselect movienameselect categoryname from category brelcatmov c where bcategoryidccategoryid and cmovieidamovieid as categories from movies aerror subquery returns more than one rowhow to thisplay the result of rows in one columnplease help,['mysql'] +53304,php crc32 only numbers i have a md5 hash 10f86782177490f2ac970b8dc4c51014result c74e16d9but php crc3210f86782177490f2ac970b8dc4c51014result 951183655i do not understand,['php'] +53305,struts2 trim all string obtained from forms i develop web application using struts2 i want to improve getting string from forms for this need trim all string and if obtained string is empty then set null to fieldfor this i created stringconverterpublic class stringconverter extends strutstypeconverter override public object convertfromstringmap context string strings class toclass if strings null stringslength 0 return null string result strings0 if result null return null result resulttrim if resultisempty return null return result override public string converttostringmap context object object if object null object instanceof string return objecttostring return null next i added row to xworkconversionpropertiesjavalangstringcommypackagestringconverterthats all but i did not get the desired resultconverttostring method is called when jsp build form but convertfromstring does not invokewhat i do wrong how can i get the same behaviour using another wayplease not offer solutions such asremove the value of such form elements using javascriptcreate util method which will make it using reflection then call it for each form beanthanks in advancealexey,['java'] +53309,which loop configuration will take more time to run code ifori0 i100 i forj0 j10 j x y code iifori0 i10 i forj0 j100 j x y can you explain why one of these loop configurations will take more time to run than the other,['c'] +53311,how to find the worst performing queries in sql server 2008 how to find the worst performing queries in sql server 2008i found the following example but it does not seem to workselect top 5 objname max logical reads max elapsed timefrom sysdm exec query stats across apply sysdm exec sql textsql handle hndinner join syssysobjects obj on hndobjectid objidorder by max logical reads desctaken from,['sql'] +53312,how to create pdfs in an android app is there any way to create pdf files from an android application,['android'] +53313,the following code prints true true false true should not it be true true true true integer i 127integer j 127systemoutprintlni jsystemoutprintlniequalsjinteger i1 128integer j1 128systemoutprintlni1 j1systemoutprintlni1equalsj1i do not understand why its not print true true true true please give answer,['java'] +53317,when to use javascript object literals when should object literals be used in javascript sometimes i get confused i am trying to apply oop concepts and pattern to the language i am trying to not just use procedural programming concepts because i know the language has amazing capabilities,['javascript'] +53322,invalidcastexception for two objects of the same type i have this weird problem that i cannot handle myself a class in the model of my mvpproject designed as singleton causes an invalidcastexception the source of error is found in this code line where the deserialised object is assigned to the instance variable of the class engineobject enginexserializerdeserializestr it occurs whenever i try to add one of my usercontrols to a form or to a different uc all of my ucs have a special presenter that access the above mentioned instance variable of the singleton class this is what i get when trying to add a uc somewheresystemtypeinitializationexception the type initializer for mvpmodelenginedata threw an exception systeminvalidcastexception aengine cannot be cast to bengine type a originates from mvpmodel version10 cultureneutral publickeytokennull in the context loadneither at location appdataroamingmicrosoftvisualstudio90projectassembliesuankw1hh01mvpmodeldll type b originates from mvpmodel version10 cultureneutral publickeytokennull in the context loadneither at location appdataroamingmicrosoftvisualstudio90projectassembliesu hge2de01mvpmodeldllso i somehow have two assemblies and they are not accessed from my project folder but from a vs temp folder i googled a lot and only found this ironpython exception aperson cannot be cast to bperson there is a solution offered but first it concerns ironphyton and second i do not know where to use it within my project it would be just great if you could help me out here thx,['c#'] +53328,fake serial communication under linux i have an application where i want to simulate the connection between a device and a modem the device will be connected to a serial port and will talk to the software modem through thatfor testing purposes i want to be able to use a mock software device to test send and receive dataexample python codedevice devicemodem modemdeviceconnectmodemdevicewritehellomodem reply devicereadnow in my final app i will just pass devttys1 or com1 or whatever for the application to usebut how can i do this in software i am running linux and application is written in pythoni have tried making a fifo mkfifo my fifo and that does work but then i will need one fifo for writing and one for reading what i want is to open my fake serial port and read and write to thati have also lpayed with the ptymodule but cannot get that to work either i can get a master and slave file descriptor from ptyopenpty but trying to read or write to them only causes ioerror bad file descriptor error messageupdatecomments pointed me to the so question which uses socat to setup a virtual serial connectioni used it like thissocat ptylinkhomecom1 ptylinkhomecom2to the rest of you thank you for giving me valuable informationi chose to accept vinay sajipss answer since that is the solution which i went for before the socat suggestion showed up it seems to work well enough,['python'] +53333,reset element color to default stylesheet color jquery javascript i need to be able to reset an input field back to its original color after it has been possibly changed via javascript to a different value the problem is i do not want to hard code the value in case the stylesheet changes i would like to use the default color used on the pageis resetting the color like this fine or is there a better way to do thistheinputcsscolor,"['javascript', 'jquery', 'css']" +53341,aspnet dynamically register an httphandler in code not in webconfig possible duplicateany way to add httphandler programatically in net is there a way i can dynamically register an ihttphandler in c code instead of having to manually add it to the systemwebhttphandlers section in the webconfigthis may sound crazy but i have good reason for doing this i am building a widgetlibrary that a website owner can use just by dropping a dll file into their bin directory and want to support this with minimal configuration to the webconfig,"['c#', 'asp.net']" +53343,using url routing for web forms and stoproutinghandler for favicon i have a website where i need to add a faviconico the site is written using aspnet 35 web forms with routing the issue is that the favicon link always returns a page not found error this is because the routing does not know where the link for faviconico should go to so it returns the not found page i have tried to add a stoproutinghandler for the the favicon but none of them seem to work below are the ones i have tried so farroutesaddnew routemasterpagesfaviconico new stoproutinghandlerroutesaddnew routefaviconico new stoproutinghandlerroutesaddnew routefaviconico new stoproutinghandlerroutesaddnew routefaviconicopathinfo new stoproutinghandlerdoes anyone know what i should be using my faviconico links i have tried look like thislink relshortcut icon hreffaviconico typeimagexicon link relicon hreffaviconico typeimagexicon and they are inside of my htmlhead tagsalso as one final note i am not using mvc because if i was i could use thisroutesignoreroutefavicon new faviconfaviconicounfortunately ignoreroute does not work for routing web forms though because it is not an mvc application,"['c#', 'asp.net']" +53365,android release version and waiting for debugger i know this has been asked before but i still do not have a solutionmy first app developed and debugged on my moto droid and then followed all the release steps exported from eclipse using my key to sign including removing the debug in the manifest xmli copied the resulting apk to the droid thisconnected the usb and installed it by double clicking on the file using astroi get the waiting for debugger message like when i am debugging but it never goes awaydoing something real stupid i know but i cannot figure it out any help would be appreciatedthankstom,['android'] +53385,html tag how to correctly escape html and javascript content thisplayed in there i have a html tag textareafootextarea and the foo variable will be filled with arbitrary html and javascript content to be thisplayed and edited within the textarea what kind of escaping do i neet to apply to fooi first tought of escaping it html but this didnt work as i will then get shown not the original html code of foo but rather the escaped content this is of course not what i want i want to be thisplayed the unescaped htmljs content of the variableis it impossible to thisplay html content within a textarea tag and also allow it to be editable as full htmlthanksjens,['html'] +53388,destructors not called when native c exception propagates to clr component we have a large body of native c code compliled into dllsthen we have a couple of dlls containing ccli proxy code to wrap the c interfaceson top of that we have c code calling into the ccli wrappersstandard stuff so farbut we have a lot of cases where native c exceptions are allowed to propagate to the net world and we rely on nets ability to wrap these as systemexception objects and for the most part this works finehowever we have been finding that destructors of objects in scope at the point of the throw are not being invoked when the exception propagatesafter some research we found that this is a fairly well known issue however the solutions workarounds seem less consistent we did find that if the native code is compiled with eha instead of ehsc the issue thisappears at least in our test case it did however we would much prefer to use ehsc as we translate seh exceptions to c exceptions ourselves and we would rather allow the compiler more scope for optimisationare there any other workarounds for this issue other than wrapping every call across the nativemanaged boundary in a native trycatchthrow in addition to the ccli layer,['.net'] +53391,the extern alias x was not specified in a reference option i have two assemblies that unfortunately define the same type in the same namespace i am trying to use a an extern alias to work around the problem in the visual studio ide i have set the aliases property of the reference to my alias this is supposed to change the c compiler command line to be something like thisreferencemyaliasmyassemblydllbut it does not actually do that the visual studio ide seems to just ignore the aliases property setting on the reference so when i go and add the line extern alias myalias at the top of my c code file i get the error that the alias was not specified in a reference option to the compiler i cannot figure out what i am doing wrong any ideas,"['c#', '.net']" +53394,c language standard collections where are they i have committed to learning c now i am good with pythonphpbash but i have decided i am limited by not being fluent in c however i cannot imagine working in a language without lists and hashes maybe i am just jumping a gun but surely there are standard collection libraries i do not see any in the gnu standard lib though any suggestions,['c'] +53396,tabwidget height is it possible to set the tabwidget height and have the tab labels adjust if i set the tabwidget height too small then the labels are hidden from view tabhost xmlnsandroid androididandroididtabhost androidlayout widthfill parent androidlayout heightfill parent linearlayout androidorientationvertical androidlayout widthfill parent androidlayout heightfill parent androidpadding5dp tabwidget androididandroididtabs androidlayout widthfill parent androidlayout height30px framelayout androididandroididtabcontent androidlayout widthfill parent androidlayout heightfill parent androidpadding5dp linearlayouttabhostthanks,['android'] +53404,does there exist a jquery plugin or javascript library that allows venn diagram presentation i am writing a jquery application to allow analysis of data with the help of visual cues my data is retrieved via xmlhttprequest in the form of json the visual cues include histograms spark lines and various other graph types the idea is that the user is able to narrow their data via these various visual viewsmy question is thus aside from the google charts api does there exist a javascript way of presenting a venn diagramrequirement no flashcanvas is acceptable,"['javascript', 'jquery']" +53405,create text file without bom i tried this aproach without any success the code i am using file namestring filename stringformat0ddmmyyhhmm dtfilecreatedstring filepath pathcombineservermappathapp data filename txt process myobject pbs new myobject pbsgeneratefile pbsgeneratedfile is a stringbuilder object save fileencoding utf8withoutbom new utf8encodingtruetextwriter tw new streamwriterfilepath false utf8withoutbomforeach string s in pbsgeneratedfiletoarray twwritelinestwclose push generated file into clientresponseclearresponsecontenttype applicationvndtextresponseappendheadercontentthisposition attachment filename filename txtresponsetransmitfilefilepathresponseendthe resultit is writing the bom no matter what and special chars like a a a are not correct i am stuckmy objective is create a file using utf8 as encoding and 88591 as charsetis this so hard to accomplish or i am just getting a bad dayall help is greatly appreciated thank you,['c#'] +53418,does a version control database storage engine exist i was just wondering if a storage engine type existed that allowed you to do version control on row level contents for instance if i have a simple table with id name value and id is the pk i could see that row 354 started as 354 zak testv1 then was updated to be 354 zak this is version 2 of the valuev2 and could see a change history on the row with something like select history value where id 354it is kind of an esoteric thing but it would beat having to keep writing these separate history tables and functions every time a change is made,"['sql', 'mysql']" +53420,howto install jogl for eclipse in mac osx 106 i got snow leopard 64 bit and i am wondering how i am to install jogl in order to develop with eclipsea nice tut from az would have been nice since i am suspecting some of my steps are very wrongedit 28aug2012jogl 11 is only compatible with java jdk 16 not jdk 17 tested on osx mountain lion 1081,['java'] +53432,css gradients in ie7 ie8 is causing text to become aliased i am attempting to use a css gradient in a div containing some text with gecko and webkit the text thisplays fine in ie7 ie8 the text appears aliased jaggyi came across this blog stating we decided to thisable cleartype on elements that use any dxtransformie blogthat was back in 2006 35 years later i assume this bug would be fixed but it is not is there a way to do this in ie8 without resorting to stuffing a repeating background image in the divheres an example of what i meanstyle div height 50px background mozlineargradienttop f d background webkitgradientlinear left top left bottom fromf tod filter progiddximagetransformmicrosoftgradientstartcolorstrf endcolorstrffd styledivhello worlddivpnormal textpin ie the text in the div is aliased jaggy and the text in the paragraph is not any solution that does not involve images would be greatly appreciated,['css'] +53453,how do i set up a python development environment on linux i am a net developer who knows very little about python but want to give it a test drive for a small project i am working onwhat tools and packages should i install on my machine i am looking for a common somewhat comprehensive development environmenti will likely run ubuntu 910 but i am flexible if windows is a better option that is fine tooedit to clarify i am not looking for the bare minimum to get a python program to run i wouldnt expect a newbie net dev to use notepad and a compiler i would recommend visual studio nunit sql server etc,['python'] +53458,are variable length arrays possible with javascript i want to make a variable length array in javascriptis this possible a quick google search for javascript variable length array does not seem to yield anything which would be surprising if it were possible to do thisshould i instead have a string that i keep appending to with a separator character instead or is there a better way to get a varible length arraylike variable,['javascript'] +53483,using the submit button to link to another page in rails i am sure this is easy once you know rails but i am new to iti want to redirect to another pageaction after the submit button fsubmit is pressed and only after it is pressed how do you determine the link that you go to after the submit button is pressed,['ruby-on-rails'] +53490,to find an execution linecounter for java ide is there any plugin to some ide that show the number of times a line is run in the codeeclipses eclemma does not seem to have a setting to show execution times at the lefthandside bar like in the service webcat,['java'] +53499,how to compile and run c files from within notepad using nppexec plugin how can i configure the nppexec plugin for notepadi would like nppexec to compile my c files run them and show their output all within notepad,['c'] +53501,when should i use mysql compressed protocol i have learned that mysql can compress communication between servers and clientscompression is used if both client and server support zlib compression and the client requests compressionfrom mysql forge wikithe most obvious pros and cons arepros reduced payload sizecons increased computation timeso is compressed protocol something i should enable whenever i can afford servers with adequate specs are there other factors i should consider,['mysql'] +53505,visual query builder if been using dbforge query builder lately and i am gotten used to the ease of building and testing a query specially for those complex ones with inner joins aliases and multiple conditionalsthe expiry date of the trial is about to come and while wanting to remain on the legal side for this i would rather not pay the 50usd it costs although i must say it is pretty cheap for what it doesso my question would be are there any free alternatives to replace this visual query builder i have failed to find any and fear that my only two options are paying for it or going to the dark side,['mysql'] +53518,email validation using jquery i am new to jquery and was wondering how to use it to validate email addresses,['jquery'] +53540,ruby regexp vs special behaviour using ruby regexp i get the following results foobaro oo foobaro but foobarfo foo foobarfo foothe documentation says zero or more repetitions of the preceding one or more repetitions of the precedingso i expect that foobaro returns the same result as foobarodoes anybody have an explanation for that,['ruby'] +53546,does android keep the apk files if so where after android installs an application from the marketplace does it keep the apk fileis there a standard location where android would keep such files,['android'] +53548,give appconfig another name after build as you all know when you build a project with an appconfig file it gets copied to the bin directory and renamed targetfilenameconfigis it possible for it to be called something else for example if my executable is called myapplicationexe can i have the config file called settingsconfig as opposed to myapplicationexeconfigcheers,['.net'] +53563,orientation in a uiview added to a uiwindow i have a uiview which is supposed to cover the whole device uiwindow to support an image zoom inout effect i am doing using core animation where a user taps a button on a uitableviewcell and i zoom the associated imagethe zooming is performing flawlessly what i have not been able to figure out is why the subview is still in portrait mode even though the device is in landscape an illustration belowi do have a navigation controller but this view has been added to the uiwindow directly,['iphone'] +53576,jvm embarrasingly parallel processing librariestools i am looking for something that will make it easy to run correctly coded embarrassingly parallel jvm code on a cluster so that i can use clojure incanteri have used parallel python in the past to do this we have a new pbs cluster and our admin will soon set up ipython nodes that use pbs as the backend both of these systems make it almost a nobrainer to run certain types of code in a clusteri made the mistake of using hadoop in the past hadoop is just not suited to the kind of data that i use the latency made even small runs execute for 12 minutesis jppf or gridgain better for what i need does anyone here have any experience with either is there anything else you can recommend,['java'] +53577,is there an easy way to concatenate several lines of text into a string without constantly appending a newline so i essentially need to do thisstring text line1ntext line2ntext line3nusestring text there is more involved but that is the basic idea is there anything out there that might let me do something more along the lines of this thoughdesiredstringthinger text new desiredstringthingertextappend line1 textappend line2 textappend line3 usestring texttostring obviously it does not need to work exactly like that but i think i get the basic point across there is always the option of writing a loop which processes the text myself but it would be nice if there is a standard java class out there that already does something like this rather than me needing to carry a class around between applications just so i can do something so trivialthanks,['java'] +53582,saving multiple objects in a single call in rails i have a method in rails that is doing something like thisa foonewbarasaveb foonewbazbsavex foonew123 parent id aidxsavez foonewzxy parent id bidzsavethe problem is this takes longer and longer the more entities i add i suspect this is because it has to hit the database for every record since they are nested i know i cannot save the children before the parents are saved but i would like to save all of the parents at once and then all of the children it would be nice to do something likea foonewbarb foonewbazsaveallabx foonew123 parent id aidz foonewzxy parent id bidsaveallxzthat would do it all in only two database hits is there an easy way to do this in rails or am i stuck doing it one at a time,['ruby-on-rails'] +53593,grouping rows with client side html table sorting are there any existing table sorting libraries or is there a way to configure tablesorter to sort every two rows alternatly is there a better way to semantially express my table such that standard row sorting will worki have an html table that looks something like thistable thead tr thheader 1th thheader 2th tr thead tbody tr tdsome data 1td tdsome more data1 td tr tr td colspan2some text about the above data that puts it in context and visually spans under both of the cells above so as not to create a weird looking tabletd tr tr tdsome data 2td tdsome more data 2td tr tr td colspan2some text about the above data 2 set that puts it in context and visually spans under both of the cells above so as not to create a weird looking tabletd tr tbodytablei am looking for a way to sort the table such that the table is sorted by the data rows but the row with the colspan travels with its data and is not sorted separately,"['javascript', 'jquery', 'html']" +53594,switch to mysqli a good idea i am considering switching to mysqli for all my php projects the way my code is written i run very simple websites and built my own basic framework which i use across all of them i should not have too many problems modifying the functions and classeshowever i have only heard positive things about prepared statements bar a few grumblings about the php functions available most notably the lack of a simple replacement for using mysql fetch array in a whilethis sounds a bit too good to be true so i wondered if anyone could highlight some of the issues with using prepared statements such as speed and resource usage,['php'] +53614,pdf library for java does anyone know a good pdf library for java my specific requirement is to find coordinates of the text in pdf file if anyone knows some pointers will be helpful,['java'] +53624,cannot resolve targetname silverlight4 c i am getting the error cannot resolve targetname grdgeneral what i am trying to do is have a fade out function which accepts a grid and fades the opacity to zero i have this function called on mouseleftbuttondown and is loaded after the xaml and form has loadedcalling the fade outprivate void imgnext mouseleftbuttondownobject sender mousebuttoneventargs e fadeoutgrdgeneral the fade out functionprivate void fadeoutgrid pgrid storyboard stb new storyboard doubleanimation da new doubleanimation dafrom 10 dato 00 stbduration new durationtimespanfromseconds75 stbchildrenada storyboardsettargetnameda pgridname storyboardsettargetpropertyda new propertypathgridopacityproperty stbbegin i have been on a handful of tutorial sites and my code seems to follow the same order i also have been on this stackoverflow question before you say repost that question has to deal with mutlipages and i am merely trying to start a animation the stack tracesysteminvalidoperationexception was unhandled by user code messagecannot resolve targetname grdgeneral stacktrace at msinternalxcpimportsmethodexintptr ptr string name cvalue cvdata at msinternalxcpimportsmethodexdependencyobject obj string name at systemwindowsmediaanimationstoryboardbegin at metertestingquarterreportguifadeoutgrid pgrid at metertestingquarterreportguiimgnext mouseleftbuttondownobject sender mousebuttoneventargs e at msinternalcoreinvokehandlerinvokeeventhandlerint32 typeindex delegate handlerdelegate object sender object args at msinternaljolthelperfireeventintptr unmanagedobj intptr unmanagedobjargs int32 argstypeindex string eventname innerexception,['c#'] +53631,why does xy zipzipab work in python ok i love pythons zip function use it all the time it is brilliant every now and again i want to do the opposite of zip think i used to know how to do that then google python unzip then remember that one uses this magical to unzip a zipped list of tuples like thisx 123y 456zipped zipxyunzipped x unzipped y zipzippedunzipped x out30 1 2 3unzipped y out31 4 5 6what on earth is going on what is that magical asterisk doing where else can it be applied and what other amazing awesome things in python are so mysterious and hard to google,['python'] +53635,curl follow location error i got this error messagecurlopt followlocation cannot be activated when in safe mode or an open basedir is set insafe mode is turned off on my web hostingopen basedir is how do i resolve this,['php'] +53652,android checkbox restoring state after screen rotation i have come across some very unexpected and incredibly frustrating functionality while trying to restore the state of a list of checkboxes after a screen rotation i figured i first would try to give a textual explanation without the code in case someone is able to determine a solution without all the gory details if anyone needs more details i can post the codei have a scrolling list of complex views that contain checkboxes i have been unsuccessful in restoring the state of these check boxes after a screen rotation i have implemented onsaveinstancestate and have successfully transfered the list of selected check boxes to the oncreate method this is handled by passing a long of database ids to the bundlein oncreate i check the bundle for the array of ids if the array is there i use it to determine which check boxes to check when the list is being built i have created a number of test methods and have confirmed that the check boxes are being set correctly based on the id array as a last check i am checking the states of all check boxes at the very end of oncreate everything looks good unless i rotate the screenwhen i rotate the screen one of two things happens 1 if any number of the check boxes are selected except for the last one all check boxes are off after a rotation 2 if the last check box is checked before rotation then all check boxes are checked after rotationlike i said i check the state of the boxes at the very end of my oncreate the thing is the state of the boxes at the end of oncreate is correct based on what i selected before the rotation however the state of the boxes on the screen does not reflect thisin addition i have implemented each check boxs setoncheckchangedlistener and i have confirmed that my check boxes states are being altered after my oncreate method returnsanyone have an idea of what is going on why would the state of my check boxes change after my oncreate method returnsthanks in advance for your help i have been trying to degub this for a couple days now after i found that my check boxes were apparently changing somewhere outside my own code i figured it was time to ask around,['android'] +53653,size of an nsarray how do you get the size of an nsarray and print it in the console using nslog,"['ios', 'objective-c']" +53656,foreign keys vs partitioning since foreign keys are not supported by partitioned mysql databases for the moment i would like to hear some pros and cons for a readheavy application that will handle around 1400 0 rows per table unfortunately i dont have enough experience yet in this area to make the conclusion by myselfthanks a lotreferences,['mysql'] +53658,time zones for different users i am creating a script that allows the user to choose their own timezoneif i am to make this work how do i store dates in the database so that every timezone will read it and show the correct date in their timezonedo i store the date as gmt and then when a user with the timezone gmt 10 selected views the item within my script i show that date in gmt 10 timeis there a better way to do thisexamples would be great,['php'] +53663,timenow created at are different ruby on rails my site is deployed on heroku timenow will return today but the created at field of a record created right now will say its tomorrow i assume this has to do with server timeis there a way to make sure they are the samebestelliotupdate so i did this heroku rake timezonesusit gave me utc 10 hawaii utc 0900 alaska utc 0800 pacific time us canada utc 0700 arizonamountain time us canada utc 0600 central time us canada utc 0500 eastern time us canadaindiana easthowever when i set configtime zone utc 0500 in my environment the app fails to start any ideas,['ruby-on-rails'] +53668,need thoughts on my interview question net c one of the questions i was asked was that i have a database table with following columnspid unique identifierorderid varchar20documentid int documentpath varchar250currentlocation varchar250newlocation varchar250status varchar15i have to write a c app to move the files from currentlocation to newlocation and update status column as either success or failurethis was my answercreate a list of all the records using linqcreate a command object which would be perform moving filesusing foreach invoke a delegate to move the files use endinvoke to capture any exception and update the db accordinglyi was told that command pattern and delegate did not fit the bill here i was aksed to think and implement a more favorable gof pattern not sure what they were looking for in this day and age do candidates keep a lot of info on head as one always has google to find any answer and come up with solution,"['c#', '.net']" +53669,hopping from a c to a perlunix job i have been a c linux developer till now and i am adept in this stack of late i have been getting opportunities that require perl unix with knowledge of cshell scripting expertise organizations are showing interest even though i do not have much scripting experience to boast off the role is more in a support maintenance project involving sql as well off late i am in a fix whether to forgo these offers or noti do not know the dynamics of an it organization and thus on one hand i fear that my c experience will be nullified and on the positive side i am getting to work on a new technology stack which will only add to my skill set i am sure most of you at some point of time have encountered such dilemmas and would have taken some decision i want you to share your perspectiveson such a scenario where a person isrequired to change hisher technologystack when changing hisher jobwhat are the merits and demerits ingoing with either of the choicesalso i know that c is not goinganywhere in the near future whatabout perl i have no clue as to whatthe future holds for perl developerwhether there are enoughopportunities for a perl developeri am asking this question here because most of my fellow programmers face this career choice dilemmaeditsince the last time i asked this question i made up my mind to switchi was just about to sign on the dotted line but some divine intervention made me seek some clarification about the working hours and to my horror the profile required me to work inshifts which i am never comfortable with i was all the more livid because they did not clarify this point earlier it was a reputed organisation but still i gave them my piece of mind and said thank you very much thanks,['c++'] +53701,how to update a uniform variable in glsl i am trying to get update the eye position in my shader from my appliaction but i keep getting error 1281 when i attempt this i have no problems after the initialization just when i subsequently try to update the values here is my codevoid graphicsobjectsendshadersddschar vertfile char fragfile char filename char vs nullfs null vert glcreateshadergl vertex shader frag glcreateshadergl fragment shader vs textfilereadvertfile fs textfilereadfragfile const char ff fs const char vv vs glshadersourcevert 1 vv null glshadersourcefrag 1 ff null freevs freefs glcompileshadervert glcompileshaderfrag program glcreateprogram glattachshaderprogram frag glattachshaderprogram vert gllinkprogramprogram gluseprogramprogram loadcubetexturefilename compressedtexture glint location glgetuniformlocationprogram tex gluniform1ilocation 0 glactivetexturegl texture0 eyepos glgetuniformlocationprogram eyeposition gluniform4feyepos eyepositionxeyepositiony eyepositionz 10 dword bob glgeterror all is fine here glenablegl depth testand heres the function i call to update the eye positionvoid graphicsobjectupdateeyepositionvector3d eyepositiongluniform4feyepos eyepositionxeyepositiony eyepositionz 10dword bob glgeterrorbob equals 1281 after this call i have tried a few ways now of updating the variable and this is the latest incarnation thanks for viewing all comments welcomeupdate the error is not actually happening here at all my fault for assuming it was the error actually occurs when i draw a number of spring forint i 0 i 2 i springsidrawwhen i draw the first one it is fine but i get an error when calling the second at the point where call glend in response to glbegingl line strip sorry for the inconvenience as it was not the error i posted but atleast if anyone wants to know how to update uniform variables then it is here,['c++'] +53710,c ide for linux with smart reference searching is there an ide supporting c with really smart searching of references by reference i mean usage of a class or its member variable function in the whole project or workspacethere is lots of ide providing it some of them seem just to search for the text with same name giving lots of stuff others are smarter and check the context like class boundaries namespace but are not accurate enoughthe best i have tried so far was visual slickedit but still there is more to wishclass c1 int fooclass c2 int foofor example in this situation when searching for c1foo references i do not want c2foo to be shown tooso is there an ide that would be so smartedit210x everybody for the answers so fari tried eclipse reference searching seems relatively good but it takes it 20 minutes to index medium size project and 4 times of 5 it runs out of memory and crashes i tried increasing it and some other advice and it got a little better but still quite slow and annoying with these crashesi tried kdevelop3 but the feature mentioned in this question is not very advanced seems to be just very advanced grep based text searchingedit4kdevelop4 i tried to make it work but latest beta it is quite unusable for custom makefile projects i was unable to do anything with itedit5i was surprised but qt creator did really well in my tests it does not seem to create some tagindex files but somehow manages to show very precisely the usage of variablefunctionsclasses unfortunately it seems to not work very correctly with templates when following definitions of functionsnone of the mentioned ides could compete visual slickedit in working with references virtual functions etc qt creator was the closest though so i will choose it as an answer to my question,['c++'] +53716,jquery ui buttonset icons i am having trouble adding icons to jquery uis buttonsetsadding icons to buttons work finedoes anyone have a example of this workingthanksmarkupdiv idradio classdemo input typeradio idradio1 nameradio label forradio1top 10 faqslabel input typeradio idradio2 nameradio label forradio2last 30 dayslabeldivscriptradiobuttonset icons primary uiicontriangle1ne,"['javascript', 'jquery']" +53732,create android applications using xcode i am using xcode for a while and i would like to start developing android applications however the sdk is for eclipse i personally do not like eclipse because of the ui and it starts to suck on my imac i was wondering if it is possible to create android applications with the xcode tools so i can stay with my old friend xcode and maybe even interface builder very unlikely a can anyone tell me thanks,['android'] +53737,injecting variables into the callers scope can i define a function which when called inserts new locals into the callers scope i have a feeling that passing the callers locals into the function might work but is there a way to do what i want without having to do this,['python'] +53742,can i call a stored procedure with hibernate criteria this is my problem i have to use a big sp and there is no time to rewrite in javaso i am using hibernate criteria and i do not know if i can call it thanks to all,['java'] +53746,are there alternatives to ultrawingrid i have been using the infragistics ultrawingrid for a while in a c project and while it is very spiffy it is sometimes a bit heavy to run and editing it in visual studio can be hazardousi am looking for a lighter alternative looks always a big plus with infragistics are not as important as functionality namely i am looking for a beefed up datagridview whichhas data binding duhhas lock control over editingallows for subtables on opening a rowcan have multiple headers to group columns together say header 1 is composed of group a and group b and header 2 has various columns under each grouphas sorting by column and can sort numbers properly even if it does not have a stock method at firsthas filtering by column perhaps the most demanding spec a la ultrawingridexcel text field with a way to specify if the filter is equal not equal greater lesser starts with ends with etcsupports check box text box or data bound listcombo box cellsallows cells to be merged not the control cells of coursecan have events bound to each row say double click,['c#'] +53747,in the fullcalendar dayclick event can i get the events that already exist in clicked date in the fullcalendar dayclick event can i get the events that already exist in clicked datelet me explain a little about my project i am writing a simple php site that allow user to addedit event on calendaronly single event can add to a date if user click on empty date new event popup will show i use dayclick eventif user click date with existing event edit event popup will show i use eventclick eventthe problem is when user click outside of event area upper area or bottom area of a date with existing event it raise dayclick instead of eventclickhow can i trigger eventclick event and skip dayclick event if there is existing event in the date,['javascript'] +53762,jquery autocomplete pass null parameter to the controller in aspnet mvc 2 i am using jquery autocomplete plugin from jquery websitecalling the controller url which return json in return the problem is the parameter sent to the controller is always nullhere is the inbrowser jquery code for the autocompletedocumentreadyfunction var url buildinggetmatchedcities cityautocompleteurland here is the aspnet mvc controller signature in cpublic jsonresult getmatchedcitiesstring city return thisjsonquery jsonrequestbehaviorallowgetthanks in advancemohammad,['jquery'] +53775,c using this pointer in constructors in c during a class constructor i started a new thread with this pointer as a parameter which will be used in the thread extensively say calling member functions is that a bad thing to do why and what are the consequencesmy thread start process is at the end of the constructor,['c++'] +53777,c construction and initialization order guarantees i have some doubts about construction and initialization order guarantees in c for instance the following code has four classes x y z and w the main function instantiates an object of class x which contains an object of class y and derives from class z so both constructors will be called additionally the const char parameter passed to xs constructor will be implicitly converted to an object of class w so ws constructor must also be calledwhat are the guarantees the c standard gives on the order of the calls to the copy constructors or equivalently what this program is allowed to printinclude iostreamclass z public z stdcout z stdendl class y public y stdcout y stdendl class w public wconst char stdcout w stdendl class x public z public xconst w stdcout x stdendl private y yint mainint char x xx return 0edit is this correct w z y x v,['c++'] +53792,wrapping a c service in a console app to debug it i want to debug a service written in c and the old fashioned way is just too long i have to stop the service start my application that uses the service in debug mode visual studio 2008 start the service attach to the service process and then navigate in my aspnet application to trigger the service i basically have the service running in the background waiting for a task the web application will trigger a task to be picked up by the service what i would like to do is to have a console application that fires the service in an effort for me to debug is there any simple demo that anybody knows aboutthank youjack,['c#'] +53798,possible to auto zoom out if users resolution x my site is aimed purely at the laptop market dont ask why or argue all my users or 95 we on a screen width of 1200netbooks are now taking off with a resolution of 1024 widemy site still looks great on a netbook if you zoom out once ctrlminus but i do not want to rely on users knowing about ctrlminuswhat are my options besides redesign i am keen not to have zoom buttons on my pageis there a javascript zoomer outer,"['javascript', 'jquery', 'html', 'css']" +53805,recommendations for an in memory database vs thread safe data structures tldr what are the proscons of using an inmemory database vs locks and concurrent data structuresi am currently working on an application that has many possibly remote thisplays that collect live data from multiple data sources and renders them on screen in real time one of the other developers have suggested the use of an in memory database instead of doing it the standard way our other systems behaves which is to use concurrent hashmaps queues arrays and other objects to store the graphical objects and handling them safely with locks if necessary his argument is that the db will lessen the need to worry about concurrency since it will handle readwrite locks automatically and also the db will offer an easier way to structure the data into as many tables as we need instead of having create hashmaps of hashmaps of lists etc and keeping track of it alli do not have much db experience myself so i am asking fellow so users what experiences they have had and what are the pros cons of inserting the db into the system,['java'] +53812,is memory allocated in jna or jni by the c code limited by jvm param xmx or architecture 3264 that is could a malloc asking for 5 mb in the c part fail due tojvm was run with xmx32m and jvm heap is already 30 mbsomething to do with jvm being 32 bits in a 64 bits windows,['java'] +53818,what is the prefered or accepted method for testing proxy settings i have a lot of trouble with the internet connectivity in the program i am working on and it all seems to spawn from some issue with the proxy settings most of the issues at this point are fixed but the issue i am having now is that my method of testing the proxy settings makes some users wait for long periods of timehere is what i dosystemnetwebclient webclnt new systemnetwebclientwebclntproxy proxywebclntcredentials proxycredentialsbyte tempbytestry tempbytes webclntdownloaddataurladdresscatch invalid proxy settings code to handle the exception goes herethis is the only way that i have found to test if the proxy settings are correct i tried making a web service call to our web service but no proxy settings are needed when making the call it will work even if i have bogus proxy settings the above method though has no timeout member that i can set that i can find and i use the downloaddata as opposed to the downloaddataasync because i need to wait til the method is done so that i can know if the settings are correct before continuing on in the programany suggestions on a better method or a work around for this method is appreciatedmikeedit i tried something else but no luck i used the downloaddataasync method to download the data in a separate thread which raises the downloaddatacompleted event of the webclient when finished while i wait for the event to get called i have a loop whiledatetimenow downloadstartaddminutestimeout testisdone the downloaddatacompleted event sets the testisdone member to true when the event is called the problem here is if the proxy settings are bad the event never gets called no exception is thrown and the program waits for the entire timeout period before continuing here is the code for this approachpublic static bool testproxysystemnetwebproxy proxy proxysettingstestdone false public static var string address url to some arbitrary data on our server systemnetwebclient webclnt new systemnetwebclient webclntproxy proxy webclntcredentials proxycredentials try webclntdownloaddatacompleted new systemnetdownloaddatacompletedeventhandlerdownloaddatacallback webclntdownloaddataasyncnew uriaddress timeout period datetime dnldstarttime datetimenow while datetimenow dnldstarttimeaddminutes10 proxysettingstestdone if proxysettingstestdone exceded timeout throw new systemnetwebexceptioninvalid proxy settings catch systemnetwebexception e if estatus systemnetwebexceptionstatusproxynameresolutionfailure proxy failed server may or may not be there utilconnectivityerrormsg emessage return false else if estatus systemnetwebexceptionstatusprotocolerror file not found server is down but proxy settings succeded serverup false utilconnectivityerrormsg emessage return true return false utilconnectivityerrormsg return trueprivate static void downloaddatacallbackobject sender systemnetdownloaddatacompletedeventargs e if ecancelled eerror null proxysettingstestdone true else throw new systemnetwebexceptioninvalid proxy settingssorry about the long post i wanted to update this question with the information that i found after testing this new approachthanksmike,['c#'] +53820,why does not gcc remove this check of a nonvolatile variable this question is mostly academic i ask out of curiosity not because this poses an actual problem for meconsider the following incorrect c programinclude signalhinclude stdiohstatic int running 1void handlerint u running 0int main signalsigterm handler while running printfbyen return 0this program is incorrect because the handler interrupts the program flow so running can be modified at any time and should therefore be declared volatile but let us say the programmer forgot thatgcc 433 with the o3 flag compiles the loop body after one initial check of the running flag down to the infinite loopl7 jmp l7which was to be expectednow we put something trivial inside the while loop like while running putcharand suddenly gcc does not optimize the loop condition anymore the loop bodys assembly now looks like this again at o3l7 movq stdoutrip rsi movl 46 edi call io putc movl runningrip eax testl eax eax jne l7we see that running is reloaded from memory each time through the loop it is not even cached in a register apparently gcc now thinks that the value of running could have changedso why does gcc suddenly decide that it needs to recheck the value of running in this case,['c'] +53839,uislider with increments of 5 how do i have my uislider go from 1100 in increments of 5,"['iphone', 'ios']" +53841,convertcast base type to derived type i am extending the existing net framework class by deriving it how do i convert an object of base type to derived typepublic class results framework methods public class myresults results nothing here i call the framework methodpublic static myresults getresults results results new results results results new myresults tried this as well results callframeworkmethod return myresultsresults throws runtime exceptioni understand that this happens as i am trying to cast a base type to a derived type and if derived type has additional properties then the memory is not allocated when i do add the additional properties i do not care if they are initialized to nullhow do i do this without doing a manual copy,"['c#', '.net']" +53843,are strings pooled in python does python have a pool of all strings and are they strings singletons theremore precise in the following code one or two strings were created in memorya strnumb strnum,['python'] +53849,android how to use dexclassloader to dynamically replace an activity or service i am trying to do something similar to this stackoverflow posting what i want to do is to read the definition of an activity or service from the sd card to avoid manifest permission issues i create a shell version of this activity in the apk but try to replace it with an activity of the same name residing on the sd card at run time unfortunately i am able to load the activity class definition from the sd card using dexclassloader but the original class definition is the one that is executed is there a way to specify that the new class definition replaces the old one or any suggestions on avoiding the manifest permission issues without actually providing the needed activity in the package the code sample classloader cl new dexclassloadersdcardmypathmyapk getfilesdirgetabsolutepath null mainactivityclassgetclassloader try class c clloadclasscomandroidmypathtoaloadedactivity intent i new intentgetbasecontext c startactivityi catch exception e intead of launching the comandroidmypathtoaloadedactivity specified in sdcardmypathmyapk it launches the activity statically loaded into the project,['android'] +53856,declare 2 types inside using statement gives compile error i want to use this line of codeusing adatacontext dc new adatacontextconnectionstring bdatacontext dc2 new brdatacontextconnectionstring this gives a compile errorcannot use more than one type in a for using fixed or declartion statementi thought this was possible msdn says it is in the msdn sample code font is used which is class and thereby a reference type as well as my two datacontext classeswhat went wrong here how does my attempt differ from the msdn sample,['c#'] +53868,how to create a folder in eclipse i would like to create a folder under a package in eclipse the purpose of this folder is merely for organizational purposes meaning i do not want it to be another package every time i try to add a folder under a package it just creates a package instead i would like to have the following structureprojectsrcpackage1someclassjavaprojectsrcpackage1somefolderanotherclassjavaprojectsrcpackage1package2anotherfolderoneotherclassjavais it possible to do this without adding a package i come from a netc and c background here i would just add a folder and the reference to that class would be updated in the project how can i just add an organizational folder in eclipse thanks,['java'] +53875,how do you clear the focus in javascript i know this should not be that hard but i could not find the answer on googlei want to execute a piece of javascript that will clear the focus from whatever element it is on without knowing ahead of time which element the focus is on it has to work on firefox 2 as well as more modern browsersis there a good way to do this,['javascript'] +53882,portable end of line is there any way to automatically use correct eol character depending on the os usedi was thinking of something like stdeoli know that it is very easy to use preprocessor directives but curious if that is already availablewhat i am interested in is that i usually have some messages in my applications that i combine later into a single string and i want to have them separated with a eol i know that i could use stdstringstream endl but it seems to be an overkill sometimes instead of a regular append,['c++'] +53887,core data nspredicate to filter tomany relationship i have 2 entities task and list each task has a toone relationship to a list object called list and there is an inverse relationship with list which has a tomany relationship with task called tasks i am trying to use a fetch request with an nspredicate to get all the task objects that belong to a specified listnspredicate predicate nspredicate predicatewithformatlist thelistfetchrequest setpredicatepredicatewhere theparent is a reference to a list object however this returns no fetched objects if i take out the predicate then the objects are returned so i do know they exist and by nslogging thelist i know it has task objects associated with itthanks,['iphone'] +53897,how to access a static method in c when we have a static method in a class it access only static members right andthe static method can access only with class name so i am not able to access the static method in my exampleclass myclass int i static int j static void get j 101 consolewritelinejtostring public void test i 11 j 12 consolewritelineitostring consolewritelinejtostring class program static void mainstring args myclass clsmyclas new myclass clsmyclastest consolereadline,['c#'] +53902,listaddrange inline declaration this may seem an easy question but not to me also a search has led to nothing up until now the only net programming i have done is with delphi prism with prism i can do things likevar l new liststringabcorvar l new liststringladdrangeabcbut can i do a similar thing in c or do i have to do it likevar a new string abcvar l new liststringa,"['c#', '.net']" +53911,what are advantages of using a onetoone table relationship mysql what are advantages of using a onetoone table relationship as opposed to simply storing all the data in one table i understand and make use of onetomany manytoone and manytomany all the time but implementing a onetoone relationship seems like a tedious and unnecessary task especially if you use naming conventions for relating php objects to database tablesi could not find anything on the net or on this site that could supply a good realworld example of a onetoone relationship at first i thought it might be logical to separate users for example into two tables one containing public information like an about me for profile pages and one containing private information such as loginpassword etc but why go through all the trouble of using unnecessary joins when you can just choose which fields to select from that table anyway if i am thisplaying the users profile page obviously i would only select idusernameemailaboutme etc and not the fields containing their private infoanyone care to enlighten me with some realworld examples of onetoone relationships,"['php', 'mysql']" +53913,multithreading or task parallel library i have an application which performs 30 independent tasks simultaneously using multithreadingeach task retrieves data over http performs a calculation and returns a result to the ui threadcan i use tpl to perform the same tasksdoes tpl create 30 new threads and spread them over all the available cores or does it just split the tasks over the available cores and use one thread per corewill there be a performance boost using tpl over multithreading in this case,['.net'] +53914,changing dbml how to change sql database a have an app with that uses an sql database the application is already released but now i am working on an update in the update i have added an extra column in a table of my databasei have create the database from my dmbl using datacontextcreatedatabase not the other way around as i found out to be the more common scenario lateri there a facility in linq in which i can update my sql database scheme,"['c#', '.net', 'sql']" +53927,if i want the jdk for my mac where should i look for it i want java to be installed on my leopard macbook but i could not find the jdk kit for mac on suns java site where should i look for it,['java'] +53936,how to check user password in ldap whith java with given ldapcontext i do have a webapplication where users must log in the password is stored in a ldap server all information about the ldap server are stored in the application server glassfish as external jndi resource so my application does no know anything about the ldap server and only gets a ldapcontext like this resourcename ldapusersprivate ldapcontext ctxwith this context it is easy to change or read the information stored for the users but how do i check their passwordsnormally i would just do a new connection to check a users password like this hashtable env new hashtableenvputcontextinitial context factory comsunjndildapldapctxfactoryenvputcontextprovider url ldaplocalhost389ojnditutorialenvputcontextsecurity authentication simpleenvputcontextsecurity principal cns user ounewhires ojnditutorialenvputcontextsecurity credentials mysecretdircontext ctx new initialdircontextenvbut since i do not know the this parameters i cannot do this so how do i check if the password of a user is correct with my ldapcontextthe passwords are stored encrypted ssha so i can not just compare the attributesthanksraffael,['java'] +53947,can hibernate be used as the jpa provider in google app engine can hibernate 35x be used as the jpa provider instead of the default provider in the latest version of google app engine 132,['java'] +53959,custom header using php soap functions i am having a problem getting a custom soap header to work with php5 can anybody guide me pleasewhat i require is something like thissoapenvheader usermyusernameuser passwordmypasswordpasswordsoapenvheader what i get is soapenvheader ns2null usermyusernameuser passwordmypasswordpassword ns2nullsoapenvheader i would like to remove the namespace tags the code i use to get this is class authstuff public user public password public function constructuser pass thisuser user thispassword pass auth new authstuffmyusername mypasswordparam arrayauthstuff authauthvalues new soapvarauthsoap enc objectheader new soapheadernullauthvaluesnull does not seem to pass with null i still get name space as in second example how to exclude this ns thanks for your help in advanceheaders arrayheaders new soapheadernull user usernameheaders new soapheadernull password passwordclient setsoapheadersheaderstry result clientgetavailablelicenseddncountasx01 print rresultfatal error soapheadersoapheader invalid parameters invalid namespace in usrhomedeepeshsoapcallsdeepesh7php on line 29,['php'] +53981,how do i join three tables with sqlalchemy and keeping all of the columns in one of the tables so i have three tablesthe class defenitionsengine create enginesqlitetestdb echofalsesqlsession sessionmakerbindenginebase declarative baseclass channelbase tablename channel id columninteger primary key true title columnstring description columnstring link columnstring pubdate columndatetimeclass userbase tablename user id columninteger primary key true username columnstring password columnstring sessionid columnstringclass subscriptionbase tablename subscription userid columninteger foreignkeyuserid primary keytrue channelid columninteger foreignkeychannelid primary keytruenote i know userusername should be unique need to fix that and i am not sure why sqlalchemy creates some row names with the doublequotesand i am trying to come up with a way to retrieve all of the channels as well as an indication on what channels one particular user identified by usersessionid together with userid has a subscription onfor example say we have four channels channel1 channel2 channel3 channel4 a user user1 who has a subscription on channel1 and channel4 the query for user1 would return something likechannelid channeltitle subscribed1 channel1 true2 channel2 false3 channel3 false4 channel4 truethis is a bestcase result but since i have absolutely no clue as how to accomplish the subscribed column i have been instead trying to get the particular users id in the rows where the user has a subscription and where a subscription is missing just leave it blankthe database engine that i am using together with sqlalchemy atm is sqlite3i have been scratching my head over this for two days now i have no problem joining together all three by way of the subscription table but then all of the channels where the user does not have a subscription gets omittedi hope i have managed to describe my problem sufficiently thanks in advanceedit managed to solve this in a slightly clunky way involving a subquery what a messy sql querystmt querysubscriptionfilter byuserid uidjoinuser subscriptionuserid useridfilter bysessionid idsubquerysubs aliasedsubscription stmtresults querychannelid channeltitle subsuseridouterjoinsubs subschannelid channelidhowever i will be continuing to search for a more elegant solution so answers are still very much welcomed,"['python', 'sql']" +53983,check whether the string is a unix timestamp i have a string and i need to find out whether it is a unix timestamp or not how can i do that effectivelyi found this thread via google but it does not come up with a very solid answer i am afraid and yes i cribbed the question from the original poster on the aforementioned thread,['php'] +53984,in ruby what structures can a rescue statement be nested in in ruby to catch an error one uses the rescue statement generally this statement occurs between begin and end one can also use a rescue statement as part of a block do end or a method def end my question is what other structures loop while if if any will rescue nest within,['ruby'] +53987,why do not i need to check if references are invalidnull reading it saysin general references should always be valid because you must always initialize a reference this means that barring some bizarre circumstances see below you can be certain that using a reference is just like using a plain old nonreference variable you do not need to check to make sure that a reference is not pointing to null and you would not get bitten by an uninitialized reference that you forgot to allocate memory formy question is how do i know that the objects memory has not been freeddeleted after youve initialized the referencewhat it comes down to is that i cannot take this advice on faith and i need a better explanationcan anyone shed some light,['c++'] +53988,android development on windows 7 has anyone tried to develop an android app on windows 7 it says that it is not a supported os but sometimes that does not stop people from trying to develop on it anyways,['android'] +53994,jquery width returns 0 for a span element created on the fly i am trying to determine the width of a string i am using the following code but it always return 0 it seems to be that as the span element is created and not already present in the page body jquery width returns 0 is there a way such that i can get the width of the text without resorting to creating dummy html code in the pagethanks spantestspanwidth width 0spanwidthwidth returns a width valuebodyspan classwidthtestspanbody,['jquery'] +53999,uiscrollview with pages enabled and device rotationorientation changes madness i am having a hard time getting this righti have got a uiscrollview with paging enabled it is managed by a view controller mainviewcontroller and each page is managed by a pageviewcontroller its view added as a subview of the scrollview at the proper offset scrolling is leftright for standard orientation iphone app works well basically exactly like the sample provided by apple and also like the weather app provided with the iphonehowever when i try to support other orientations things do not work very well i have supported every orientation in both mainviewcontroller and pageviewcontroller with this method boolshouldautorotatetointerfaceorientationuiinterfaceorientationinterfaceorientation return yeshowever when i rotate the device my pages become quite skewed and there are lots of drawing glitches especially if only some of the pages have been loaded then i rotate then scroll more etc very messyi have told my views to support autoresizing with theviewautoresizingmask uiviewautoresizingflexiblewidth uiviewautoresizingflexibleheightbut to no avail it seems to just stretch and thistort my viewsin my mainviewcontroller i added this line in an attempt to resize all my pages views voiddidrotatefrominterfaceorientationuiinterfaceorientationfrominterfaceorientation selfscrollviewcontentsize cgsizemakeselfscrollviewframesizewidth selfviewcontrollers count selfscrollviewframesizeheight for int i 0 i selfviewcontrollers count i pageviewcontroller controller selfviewcontrollers objectatindexi if nsnull controller nsnull null continue nslogchanging frame d i cgrect frame selfscrollviewframe frameoriginx framesizewidth i frameoriginy 0 controllerviewframe frame but it did not help too much because i lazily load the views so not all of them are necessarily loaded when this executesis there any way to solve this problem,"['objective-c', 'ios']" +54000,how to define and work with an array of bits in c i want to create a very large array on which i write 0s and 1s i am trying to simulate a physical process called random sequential adsorption where units of length 2 dimers are deposited onto an ndimensional lattice at a random location without overlapping each other the process stops when there is no more room left on the lattice for depositing more dimers lattice is jammedinitially i start with a lattice of zeroes and the dimers are represented by a pair of 1s as each dimer is deposited the site on the left of the dimer is blocked due to the fact that the dimers cannot overlap so i simulate this process by depositing a triple of 1s on the lattice i need to repeat the entire simulation a large number of times and then work out the average coverage i have already done this using an array of chars for 1d and 2d lattices at the moment i am trying to make the code as efficient as possible before working on the 3d problem and more complicated generalisations this is basically what the code looks like in 1d simplifiedint main define lattice array charmallocn sizeofchar total c 0 carry out rsa multiple times for i 0 i 10 i rand seq ads calculate average coverage efficiency at jamming printfcoverage efficiency lf total c10 return 0void rand seq ads initialise array initial conditions memseta 0 and sizeofchar available sites n count 0 while the lattice still has enough room whileavailable sites 0 generate random site location x rand deposit dimer if site is available ifarrayx 0 arrayx 1 arrayx1 1 count 1 available sites 2 mark site left of dimer as unavailable if its empty ifarrayx1 0 arrayx1 1 available sites 1 calculate coverage and add to total c countn total c cfor the actual project i am doing it involves not just dimers but trimers quadrimers and all sorts of shapes and sizes for 2d and 3d i was hoping that i would be able to work with individual bits instead of bytes but i have been reading around and as far as i can tell you can only change 1 byte at a time so either i need to do some complicated indexing or there is a simpler way to do itthanks for your answers,['c'] +54012,what happens to other users if the net worker process crashes my knowledge of how processes are handled by the aspnet worker process is woefully inadequate i am hoping some of the experts out there can fill me inif i crash the worker process with a systemoutofmemoryexception what would the user experience be for other users who were being served by the same process would they get a blank screen 503 error i am going to attempt to test this scenario with some other folks in our lab but i thought i would float this out there i will update with our resultsupdate our results varied if we artificially induced a oom exception for example by loading larger and larger pdfs into memory other threads being served by that worker process would hang temporarily and then complete while others seemingly would never return thank you for your responses,"['c#', 'asp.net']" +54017,set android datepicker date limits i am using datepicker in android to thisplay images based on user selected dates i need to limit said dates to certain days for instance jan 1st 2010 to dec 31st 2010 simple as that i thought but no where can i find the answer on how to limit these datesdoes anyone know how to limit the dates for android datepicker,['android'] +54033,whats the most minimal way to achieve dependency injection i have been reading about spring and although it is claimed to be a less complex alternative to ejb i am having a hard time wrapping my head around it is there a more minimal way of achieving dependency injection than adopting the spring approach,['java'] +54036,assigning an event or command to a datatemplate in resourcedictionary i have the following classpublic class day public int date get set public string dayname get set public day public dayint date string dayname date date dayname dayname commandmanagerregisterclasscommandbindingtypeofday new commandbindingdayclick new executedroutedeventhandleronexecuteddayclick new canexecuteroutedeventhandleroncanexecutedayclick public static readonly routedcommand dayclick new routedcommanddayclick typeofday private static void oncanexecutedayclickobject sender canexecuteroutedeventargs e daysenderoncanexecutedayclicke private static void onexecuteddayclickobject sender executedroutedeventargs e daysenderonexecuteddayclicke protected virtual void oncanexecutedayclickcanexecuteroutedeventargs e ecanexecute true ehandled false protected virtual void onexecuteddayclickexecutedroutedeventargs e string content stringformatday 0 which is 1 was clicked datetostring dayname messageboxshowcontent ehandled true i am using the following datatemplate that is in a resourcedictionary to render itdatatemplate datatypextype localday grid gridcolumndefinitions columndefinition columndefinition gridcolumndefinitions rectangle gridcolumnspan2 xnamerecthasentry fillwhitesmoke textblock gridcolumn0 xnametextblockdayname textbinding dayname fontfamilyjunction fontsize11 backgroundtransparent horizontalalignmentcenter verticalalignmentcenter margin0200 textblock gridcolumn1 xnametextblockdate textbinding date fontfamilyjunction fontsize11 backgroundtransparent horizontalalignmentcenter verticalalignmentcenter margin0200 rectangle gridcolumnspan2 xnamerectmouseover filla2c0da opacity0 stylestaticresource dayrectanglemouseoverstyle rectangle griddatatemplateno problems so far i can get it on screenwhat i want to be able to do is assign a command or use an event so that when the user clicks on the day it will notify the parent of the day object that it has been clickedi have tried the followingrectanglecommandbindings commandbinding commandxstatic localdaynextday executedxstatic localdayonexecuteddayclick canexecutexstatic localdayoncanexecutedayclickrectanglecommandbindingsto try and bind the commands that are in the day class but it did not work i got an error statingresourcedictionary root element requires a xclass attribute to support event handlers in the xaml file either remove the event handler for the executed event or add a xclass attribute to the root elementwhich i think means that there is no codebehind file for a resourcedictionary or something to that effectin any event i am not sure if i should be using commands here or somehow tying events to the rectangle in question or if this is even possible i have seen various places where it sure looks like it is possible i am just unable to translate what i am seeing into something that actually works hence this postthanks in advance,['c#'] +54064,how to make a page with an https iframe appear secure i have a page on a website that contains a secure form inside an iframe although the form data submitted is secure the page does not appear secure as the url in the browser is just http is there anything i can do to show the users that the form is secure,['html'] +54066,change color of text within a winforms richtextbox i have a richtextbox that i write a string to every time i click a form button each string begins with the string long or short and ends with a newline each time i add a string it appends to the bottom of the richtextbox i would like to color each line red if it beings with long and blue if it begins with short how can i do this,['c#'] +54068,confused about cs stdwstring utf16 utf8 and thisplaying strings in a windows gui i am working on a english only c program for windows where we were told always use stdwstring but it seems like nobody on the team really has much of an understanding beyond thati already read the question titled stdwstring vs stdstring it was very helpful but i still do not quite understand how to apply all of that information to my problemthe program i am working on thisplays data in a windows gui that data is persisted as xml we often transform that xml using xslt into html or xslfo for reporting purposesmy feeling based on what i have read is that the html should be encoded as utf8 i know very little about gui development but the little bit i have read indicates that the gui stuff is all based on utf16 encoded stringsi am trying to understand where this leaves me say we decide that all of our persisted data should be utf8 encoded xml does this mean that in order to thisplay persisted data in a ui component i should really be performing some sort of explicit utf8 to utf16 transcoding processi suspect my explanation could use clarification so i will try to provide that if you have any questions,['c++'] +54071,ruby calling class method from instance in ruby how do you call a class method from one of that clas instances say i haveclass truck def selfdefault make class method mac end def initialize instance method truckdefault make gets the default via the clas method but i wish to avoid mentioning truck seems i am repeating myself endendthe line truckdefault make retrieves the default but is there a way of saying this without mentioning truck it seems like there should be,['ruby'] +54085,javascript array length incorrect on array of objects could someone explain this strange behavior why is the length in the first example 3 and not 2 and most importantly why is the length in the second example 0 as long as the keys are numerical length works when they are not length is 0 how can i get the correct length from the second example thank youa a1 string1stringstring2stringa2 string1stringstring2stringalertalength returns 3b bkey1 string1stringstring2stringbkey2 string1stringstring2stringalertblength returns 0,['javascript'] +54103,thisable jmx in activemq network of brokers spring xbean since i have struggled a lot with this problem i am posting my solutionthisabling jmx in an activemq network of brokers removes race conditions about the registration of the jmx connector when starting multiple activemq servers on the same machinefailed to start jmx connector cannot bind to url rmilocalhost1099jmxrmi javaxnamingnamealreadyboundexception jmxrmi root exception is javarmialreadyboundexception jmxrmianother problem with this is that even if you do not cause a race condition this exception can still occur even when starting one broker after another while waiting for them to initialize properly in between if one process is run by root as the first instance and the other as a normal user somehow the user process tries to register its own jmx connector though there already is one or another exception which happens when the broker that successfully registered the jmx connector goes downfailed to start jmx connector cannot bind to url rmilocalhost1099jmxrmi javaxnamingserviceunavailableexception root exception is javarmiconnectexception connection refused to host localhost nested exception is javanetconnectexception connection refusedthose exceptions cause the network of brokers to stop working or to not work at allthe trick to thisable jmx was that jmx had to be thisabled in the connectionfactory aswellthe documentation does not say that this is needed explicitly so i had to struggle for 2 days until i found the solutionbeans xmlns xmlnsamqxmlnsxsixsischemalocation spring jms template bean idjmstemplate classorgspringframeworkjmscorejmstemplate constructorarg refconnectionfactory bean caching sodass das jms template a14berhaupt nutzbar ist in sachen performance bean idconnectionfactory classorgspringframeworkjmsconnectioncachingconnectionfactory constructorarg refamqconnectionfactory property nameexceptionlistener refjmsexceptionlistener property namesessioncachesize value1 bean jeder client verbindet sich mit seinem eigenen broker broker sind untereinander vernetzt nur wenn hier nochmals jmx deaktiviert wird bleibt es auch deaktiviertamqconnectionfactory idamqconnectionfactory brokerurlvmbrokerdefaultusejmxfalse broker suchen sich einen eigenen port und sind gegenseitig verbunden ergeben dadurch ein grid dies zwar etwas langsamer aber dafa14r ausfallsicherer siehe amqbroker usejmxfalse persistentfalse wird benatigt um jmx endga14ltig zu deaktivieren amqmanagementcontext amqmanagementcontext connectorhostlocalhost createconnectorfalse amqmanagementcontext nun die normale konfiguration fa14r network of brokers amqnetworkconnectors amqnetworkconnector networkttl1 duplextrue dynamiconlytrue urimulticastdefault amqnetworkconnectors amqpersistenceadapter amqmemorypersistenceadapter amqpersistenceadapter amqtransportconnectors amqtransportconnector uritcplocalhost0 thiscoveryurimulticastdefault amqtransportconnectorsamqbrokerbeanswith this there is no need to specify dcomsunmanagementjmxremotefalse for the jvm which somehow also did not work for me because the connectionfactory started the jmx connectoredittonys answer brought me to rethinking the configuration and i found a simplified version which works aswellbeans xmlns xmlnsamqxmlnsxsixsischemalocation caching sodass das jms template a14berhaupt nutzbar ist in sachen performance bean idconnectionfactory classorgspringframeworkjmsconnectioncachingconnectionfactory constructorarg refamqconnectionfactory property nameexceptionlistener refjmsexceptionlistener property namesessioncachesize value1 bean jeder client verbindet sich mit seinem eigenen broker broker sind untereinander vernetzt nur wenn hier nochmals jmx deaktiviert wird bleibt es auch deaktiviertamqconnectionfactory idamqconnectionfactory brokerurlvmdefaultbrokerpersistentfalse broker suchen sich einen eigenen port und sind gegenseitig verbunden ergeben dadurch ein grid dies zwar etwas langsamer aber dafa14r ausfallsicherer siehe amqbroker usejmxfalse persistentfalse amqnetworkconnectors amqnetworkconnector networkttl1 conduitsubscriptionstrue duplextrue dynamiconlytrue urimulticastdefault amqnetworkconnectors amqpersistenceadapter amqmemorypersistenceadapter amqpersistenceadapter amqtransportconnectors amqtransportconnector uritcplocalhost0 thiscoveryurimulticastdefault amqtransportconnectorsamqbroker,['java'] +54108,sql count in view as column i am trying to get the result of a count as a column in my viewplease see the below query for a demo of the kind of thing i want this is just for demo purposesselect productid name description price select count from ord where ordproductid prodproductid as totalnumberofordersfrom tblproducts prodleft join tblorders ord on prodproductid ordproductidthis obviously is not working but i was wondering what the correct way of doing this would bei am using sql server,['sql'] +54115,activerecord date format i have run into a spot of bother with date formats in our rails applicationi have a date field in our view which i want to be formatted as ddmmyy this is how the user will expect to enter their dates and the datepicker control uses this formathowever active record seems to be expecting mmddyy if i enter 01032010 this gets put in as 03 january 2010if i enter 25032010 this gets put in a nullhow do i get activerecord to expect her majesties date format,['ruby-on-rails'] +54128,java web start vs embedded java applet i am going to deploy my java game to show it to my friends and whatnot but i am having trouble deciding between java web start and appletsunder what conditions is one preferable over another and what advantagesthisadvantages are there,['java'] +54143,c sleep for 500 milliseconds could you please tell me how do i go about pausing my program for 500 milliseconds and then continuei read threadsleep500 is not good as it holds up the gui threadusing a timer it fires a callback i just want to wait 500ms and then continue to the next statementplease adviseedit i need to thisplay a status bar message for 500ms and then update the message with a different one sorry i meant 500 not 50edit i do understand what all you have said but i just want to wait 500ms and then continue to the next statement i think because it is such a short interval i am going do a threadsleep500 on the main gui thread otherwise i would have to rewrite a lot of code to accomodate this brief interval of 500 millisecondsedit i will try to reformat my status message so the pause is not needed,['c#'] +54158,starting an animation from the viewmodel in wpfmvvm i am writing a mvvm app and have started putting in a few animations i want to call something on the viewmodel which starts the a storyboard this blog had a promising approach to it but it does not actually work the idchanged handler never fires for some reasoni also found that you could start animations on eventtriggers but i do not know how to raise one on the viewmodel,['c#'] +54160,default maven compiler setting right now i am writing a small java application by my own with few maven pomxml files i want to make all my maven packages to compile with jdk 16 and i cannot find a good way to do it without manually setting it on every single poms i am sick of copyandpastinggroupidorgapachemavenpluginsgroupidartifactidmavencompilerpluginartifactidconfiguration source16source target16targetconfigurationin every single pomxml file i generateis there a simpler way to resolve this issue,['java'] +54167,how do you implement async operations in c and mvvm hi what is the easiest way to implement asynch operations on wpf and mvvm lets say if user if user hits enter when on a field i want to launch a command and then return back while a thread will do some search operations and then come back and update the properties so notification can update the bindingsthanks,['c#'] +54172,fancybox getting fancybox to bind using live to items being loaded onto the page after load i have a page that loads and after it loads it pulls in a list of lis to populate a news feedlia hrefurl classquickviewquick viewalilia hrefurl classquickviewquick viewalilia hrefurl classquickviewquick viewalii am trying to get fancy box to trigger when a user clicks on quick view but have not had any luck any ideasdocumentreadyfunction quickviewfancyboxalso trieddocumentreadyfunction aquickviewliveclick function thisfancybox thanks for any ideas,['jquery'] +54188,what is better in wpf for ui layout using one grid or nested grids i am making a ui in wpf i have a bunch of functional areas and i use a grid to organize itnow the grid that i want is not uniform as in some functional area will span multiple cells in the grid i was wondering what the best practise is in solving this should i create one grid and then for each functional area set it to span multiple cells or should i split it up into multiple nested gridsin this image the leftmost panel panels separated by the gray bar is what i want the middle panel shows one grid where the blue lines are overlapped by a functional area the rightmost panel shows how i could do it with nested grids you can see the green grid has one horizontal split in the bottom cell is the yellow grid with a vertical split in side the left cell is the red grid with again a horizontal spliti was just wondering what is best practise the middle or the right panelupdate just for clarification a more code oriented examplethe middle panelgrid gridrowdefinitions rowdefinition height25 rowdefinition height rowdefinition height gridrowdefinitions gridcolumndefinitions columndefinition width200 columndefinition width gridcolumndefinitions menu gridrow0 gridcolumn0 gridcolumnspan2 ucinfo gridrow1 gridcolumn0 uccontrol gridrow2 gridcolumn0 ucsimulation gridrow1 gridcolumn1 gridrowspan2 gridthe right panelgrid gridrowdefinitions rowdefinition height25 rowdefinition height gridrowdefinitions menu gridrow0 grid gridrow1 gridcolumndefinitions columndefinition width200 columndefinition width gridcolumndefinitions grid gridcolumn0 gridrowdefinitions rowdefinition height rowdefinition height gridrowdefinitions ucinfo gridrow0 uccontrol gridrow1 grid ucsimulation gridcolumn1 gridgridupdate i have to admit that now that i wrote out the code for both approaches the span solution looks a lot better,['c#'] +54197,show default value for editing on python input possible is it possible for python to accept input like thisfolder name downloadbut instead of the user typing download it is already there as a initial value if the user wants to edit it as downloads all he has to do is add a s and press enterusing normal input commandfolderinputfolder name all i can get is a blank promptfolder nameis there a simple way to do this that i am missing,['python'] +54198,how can i get rid of ora01489 result of string concatenation is too long in this query this query gets the dominating sets in a network so for example given a networkabbcbdcedcdefeit returns be bf aebut it does not work for large data because i am using string methods in my result i have been trying to remove the string methods and return a view or something but to no availwith t as select a as per1 b as per2 from dual union all select bc from dual union all select bd from dual union all select cb from dual union all select ce from dual union all select dc from dual union all select de from dual union all select ec from dual union all select ed from dual union all select fe from dual t2 as select thistinct leastper1 per2 as per1 greatestper1 per2 as per2 from t union select thistinct greatestper1 per2 as per1 leastper1 per2 as per1 from t t3 as select per1 per2 row number over partition by per1 order by per2 as rn from t2 people as select per row number over order by per rn from select thistinct per1 as per from t union select thistinct per2 from t comb as select sys connect by pathper as p from people connect by rn prior rn find as select p per2 count over partition by p as cnt from select thistinct combp t3per2 from comb t3 where instrcombp t3per1 0 or instrcombp t3per2 0 rnk as select p rank over order by lengthp as rnk from find where cnt select count from people order by rnk select thistinct trim from p as p from rnk where rnkrnk 1,['sql'] +54201,any way to colorize specific days in fullcalendar using fullcalendar is there any way i can programmatically colorize specific days differently than the rest of the days for example in the month or week views i would like to colorize days with no events on them red and days with some events but not yet a full schedule yellow days with a full schedule would be colorized normally white background are there any callbacks or css tags i can take advantage of to add this behavior thank you,['jquery'] +54203,remove duplicates from left outer join my question is quite similar to restricting a left join with a variationassuming i have a table shop and another table location location is a sort of child table of table shop that has two columns of interest one is a division key calling it just key and a shop number this matches to the number no in table shopi tried this left outer joinselect sno lkeyfrom shop sleft outer join locatn l on sno lshopbut i am getting a lot of duplicates since there are many locations that belong to a single shop i want to eliminate them and just get a list of shop key entries without duplicates the data is correct but duplicates appear as followsshop key 1 x 1 x 2 y 3 z 3 z etci would like the data to appear like this insteadshop key 1 x 2 y 3 z etcshop table no 1 2 3 location table location shop key l1 1 x l2 1 x l3 2 y l4 3 y l5 3 y oracle 10g database,['sql'] +54208,drawable folders in res folder what is the difference between the three drawable folders in the res folder in the project hierarchy if i have an image to put into a folder which folder do i put it in,['android'] +54221,how to get an age from a dob field in mysql i need to calculate the age of a customer from their date of birthi have tried to use the followingdatediffyear customerdob 20100101but it does not seem to workany ideas i know it is going to be something simplethanks,['mysql'] +54230,var undefined true i am doing some experimenting with this malicious javascript line var undefined trueevery uninitialized variable in javascript has the value of undefined which is just a variable that holds the special value of undefined so the following should execute the alertvar undefined true xif x alertokbut it does not and my question is whyon further experimentation i tried the followingvar undefined true x undefinedif x alertokthis time the alert is executedso my question issince in the first snippet x holds undefined because it is not initialized why did not the alert execute the strange thing is that when explicitly stating that x is undefined x undefined the alert executed,['javascript'] +54234,proper way to reload a python module from the console i am debugging from the python console and would like to reload a module every time i make a change so i do not have to exit the console and reenter it i am doing from projectmodeluser import reloaduserbut i receivenameerror name user is not definedwhat is the proper way to reload the entire user class is there a better way to do this perhaps autoupdating while debuggingthanks,['python'] +54236,int or nsinteger as object for method argument objectivec i am having some trouble passing a number as an argument for a methodvoid meth2intnext intand to call that method i need thisint next int 1self performselectoronmainthreadselectormeth2 withobjectnext int waituntildonenoupdate next int and call meth2 againat this point i get a pointer from integer without a cast error and would happen the same with a nsinteger a nsnumber is not useful because it is immutable and i need to change the value constantlyany idea how can i do thisthanks,"['iphone', 'objective-c']" +54243,how to i get the class name when i am passing in a generic in my method my method looks likepublic string doobjectpropertiestt obj string textnow from within the method i need to get the string value of the class name that i pass into the methods obj parameterso if i pass in the user object i need the text userto get the properties i am using typeoftgetpropertieshow can i get the classes name,['c#'] +54248,struct constructor fields must be fully assigned before control is returned to the caller here is a struct i am trying to write public struct attacktraits public attacktraitsdouble probability int damage float thistance probability probability thistance thistance damage damage private double probability public double probability get return probability set if value 1 value 0 throw new argumentoutofrangeexceptionprobability values must be in the range 0 1 probability value public int damage get set public float thistance get set this results in the following compilation errorsthe this object cannot be used before all of its fields are assigned to field attacktraitsprobability must be fully assigned before control is returned to the callerbacking field for automatically implemented property attacktraitsdamage must be fully assigned before control is returned to the caller consider calling the default constructor from a constructor initializerbacking field for automatically implemented property attacktraitsthistance must be fully assigned before control is returned to the caller consider calling the default constructor from a constructor initializerwhat am i doing wrong,['c#'] +54249,objectivec optimization are there standard optimization tricks for objectivec to make for faster execution along the lines of inlining frequent methods as in c or the g fast tagedit does anyone have a short example using sel and imp when themethod has two or more integers for input,['objective-c'] +54268,loading dll in java eclipse jni i am trying to load a dll in java using the following code systemloadlibrarymydllthe project is placed in ddevelopmentproject and i have placed the dll on d i then gave following vm argument in eclipse configuration djavalibrarypathdbut when i run i get unsatisifiedlinkererror after googling a bit i used systemloaddmydlldllbut again getting the same problem could someone can help,['java'] +54271,python tryexcept comma vs as in except what is the difference between and as in except statements egtry passexcept exception exception passandtry passexcept exception as exception passis the second syntax legal in 26 it works in cpython 26 on windows but the 25 interpreter in cygwin complains that it is invalidif they are both valid in 26 which should i use,['python'] +54297,is there any good reason to use false in jsp tags is there any good reason to thisallow scriptlet or el expression to be inserted as attribute valuelet us say we have tagtag namemytagname tagclassorgapachebeehivenetuitagstreetreetagclass attribute nameattrname requiredfalserequired rtexprvaluefalsertexprvalue typebooleantype attributetagwhat could be a good reason for thissallowing the belowmymytag attrsetting,['java'] +54305,why i cannot get the output of ftpexe by code i execute the ftpexe cmd through a c systemdiagnosticsprocess type and i use the following code to get the ftpexe output after i programmatically enter a help command but i can only get the first line of the result and i never get to the end output part the whole program seems blocked process p new process pstartinfofilename cwindowssystem32ftpexe pstartinfocreatenowindow true pstartinforedirectstandardinput true pstartinforedirectstandardoutput true pstartinforedirectstandarderror true pstartinfouseshellexecute false pstart pstandardinputwritelinehelp int32 c int pstandardoutputread while c int 1 char c charc int consolewritec c int pstandardoutputread consolewritelineendhowever i write a simple program which only use consolewriteline to write some output to its stdout stream and i test it with the above code it works fine i just cannot figure out why the above code cannot work with ftpexe the only difference between my simpleconsoleoutput program and the ftpexe is that the ftpexe has its own interactive command prompt new progress herere some progress of my personal investigationi write 2 threads to write to the stdin and read from stdout of ftpexe and the output is like thiscommands may be abbreviated commands arecommands may be abbreviated commands arecommands may be abbreviated commands areexactly 16 times of above lines and then exactly 16 times of the following cmds list delete literal prompt send debug ls put statusappend dir mdelete pwd traceand the last commands list is not even completeit seems that the help command output is divided into two parts the 1st part iscommands may be abbreviated commands arethe 2nd part is delete literal prompt send debug ls put statusappend dir mdelete pwd traceand all the 1st parts are wrtten to the stdout stream of ftpexe before all the 2nd partshow coud this be thanks for your commentsi tested with other command of the ftpexe and it seems normal except the help command,['c#'] +54312,what is the modern equivalent c style for the older clike fscanf method what is the best option if i want to upgrade old ccode to newer c when reading a file with a semicolon delimiter reading in from file clike fscanftfile d mypostnr delimiter fscanftfile mypostaftername delimiter fscanftfile mypostforename delimiter fscanftfile mypostdeptdelimiter fscanftfile mypostposition delimiter fscanftfile d mypostnr2eqivalent best c method achieving the same thing,"['c++', 'c']" +54313,immutable type and property in c what is meant by immutable type and immutable property in c can you give simple example,['c#'] +54333,what does with do in javascript i saw javascript code which begins with with that is a bit confusing what does it do and how can it be used correctlywith sobj return optionsselectedindexvalue,['javascript'] +54334,how to thisplay list of resource drawables i would like to thisplay all resource drawables in a list so that the user can select one is there any way to loop through all rdrawable items so i do not have to hard code them into my program,['android'] +54349,is there an are you sure for stored procedure execution i have a stored procedure which is doing a lot of delete hundreds of thousands of records it is not going to be runnable from the application but still i am concerned that one of my clients accidentally runs it i had problems earlier due to their curiosity dyes there are backups and stuff like that but i was thinking not to scare them is there a way to ask the user are you sure before executing itthanks,['sql'] +54358,how can i determine if a uilabel was touched i am trying to determine if a uilabel was touched and if so do something give uilabel site uilabel alloc initwithframecgrectmake0 185 320 30sitetext retrieverplistdict valueforkeyurlsitetextalignment uitextalignmentcentersitebackgroundcolor uicolor clearcolorsitetextcolor uicolor whitecolorsiteuserinteractionenabled yesthebgview addsubviewsitesite release then i write the callback voidtouchesendednsset touches witheventuievent event retriever plistretriever sharedinstance cgpoint pt touches anyobject locationinview self nsurl target nsurl alloc initwithstringretrieverplistdict valueforkeyurl uiapplication sharedapplication openurltarget the problem is right now no matter where i touch in the view the url is being opened how do i determine if only just my label was touched,"['iphone', 'objective-c']" +54360,settings file vs appconfig possible duplicatewhat is the difference between appconfig file and xyzsettings file i am not really understanding the interactiondifferences between settings and config files if i add an entry to the settings file it gets added to the appconfig as well does this mean that changing the value in the appconfig will update the settings if not how do i update settings in a live application whats the general purpose of using a settings file instead of putting things directly in appconfig,['.net'] +54361,implementing icomparable this might be a trivial question but i did not find any information about this is it harmful or considered bad practice to make a type t implement icomparables t and s being two different typesexampleclass foo icomparableint public int comparetoint other if other i return 1 if other i return 1 return 0 private int ishould this kind of code be avoided and if yes why,['c#'] +54371,getting a pid of a process created in c lets say that i am trying to create a new process with the following codesystemdiagnosticsprocess p new systemdiagnosticsprocesspstartinfoworkingdirectory systemiopathgetdirectorynamesystemreflectionassemblygetexecutingassemblygetnamecodebasepstartinfofilename systemiopathgetdirectorynamesystemreflectionassemblygetexecutingassemblygetnamecodebase awesomefileexepstartinfoarguments parameter1 parameter2pstartinfocreatenowindow truepstartand right in the next line i will try to get a pid of that process with the following linemessageboxshowpidthis line is giving me the no process is associated with this object error any idea as to why this error occurs,['c#'] +54379,how is list implemented in c i was thinking about the performance of calling listtindexofitem i am not sure if it will be a on performance for a sequential algorithm or ologn performance for a binary treethanks,"['c#', '.net']" +54392,tell if a given login exists in linux using python in python under linux what is the easiest way to check the existence of a user given hisher loginanything better than issuing ls loginname and checking the exit codeand if running under windows,['python'] +54393,how to detect the active itunes store on the iphoneipod touchipad i would like to be able to determine which store the user connects to from inside my app so that i can direct them to some appropriate content for their device and store does anyone know how to get this informationbasically if the user is in the uk and connects to the uk store i want my functionmethod to return gb if in korea i want kr australia au etc any help would be appreciated,"['iphone', 'objective-c']" +54400,load picturebox image from memory i cannot seem to figure out how to load a picturebox image from a bitmap in memory is it possible or do i have to create temp file for the bitmap,['c#'] +54407,access an element in a set with a vector i can do the followingvectorint myvec 4100int first myvecat0i have the following setsetint mysetmysetinsert100int setint how can i access the the element i inserted in the set,['c++'] +54408,versioning friendly extendible binary file format in the project i am currently working on there is a need to save a sizable data structure to thisk edit think dozens of mbs being an optimist i thought that there must be a standard solution for such a problem however up to now i have not found a solution that satisfies the following requirementsnet 20 support preferably with a foss implementationversion friendly this should be interpreted as reading an old version of the format should be relatively simple if the changes in the underlying data structure are simple say addingdropping fieldsability to do some form of random access where part of the data can be extended after initial creation without the need to deserialize the collection created up to this point in time think of this as extending intermediate resultsspace and time efficient xml has been excluded as option given this requirementoptions considered so farxmlserializer was turned down since xml serialization does not meet requirement 3 and 4serializableattribute does not support requirements 2 and 3protocol buffers was turned down by verdict of the documentation about large data sets since this comment suggested adding another layer on top this would call for additional complexity which i wish to have handled by the file format itselfhdf5exi do not seem to have net implementationssqlitesql server compact edition the data structure at hand would result in a pretty complex table structure that seems too heavyweight for the intended usebson does not appear to support requirement 3fast infoset only seems to have paid net implementationsany recommendations or pointers are greatly appreciated furthermore if you believe any of the information above is not true please provide pointersexamples to prove me wrong,['.net'] +54410,how do i pass in empty values in fitnesse test i am using fitfitnesse i have a column fixture that looks like thisget stepstools medication id from vocab and string concept as stringvocabulary name abbrvocabulary concept idstepstools med id amoxicillinrxnorm7231 amoxicillin 1 augmentinrxnorm1513928 augmentin 8 amoxicillin 10 mg clavulanate 625 mg extended release tablet 8i am trying to pass in empty string values by using but the test when i run it takes the value from the previous row and uses that insteadmy fixture code looks like thispublic class getstepstoolsmedicationidfromvocabandstring columnfixture public string vocabularynameabbr public string vocabularyconceptid public string conceptasstring public string stepstoolsmedid medicationmapping mapping medicationmappergetstepmedidfromvocabnameidandstringmed vocabularynameabbr vocabularyconceptid conceptasstring if mappingsuccessfullymapped return mappingstepstoolsmedicationidtostring else return mappingerrormessage how do i get the test to use the empty string values,"['c#', '.net']" +54411,are there any security vulnerabilities in this php code i just got a site to manage but am not too sure about the code the previous guy wrote i am pasting the login procedure below could you have a look and tell me if there are any security vulnerabilities at first glance it seems like one could get in through sql injection or manipulating cookies and the m parameterdefine current time time current time define online time min current time botnet timeout minimum time for the status of online define default language en default language define theme path theme folder for the theme http requests define query script basename server php self define query script html query script define query var module m variable contains the current module define query string blank query script m an empty query string define query string blank html query script html m empty query string in html define cp http root str replace empty server script name dirname server script name root of cp the session cookie define cookie user p username in the cookies define cookie pass u user password in the cookies define cookie livetime current time 25920 lifetime cookies define cookie session ref variable to store the session define session livetime current time 1300 lifetime of the session initialize connect to the database if connecttodb die mysql error ex connecting topic require once theme path indexphp manage login if empty get query var module login form if strcmp get query var module login 0 unlocksessionanddestroyallcokies if isset post user isset post pass user post user pass md5 post pass check login if mysql query select id from cp users where name addslashes user and pass addslashes pass and flag enabled 1 limit 1 mysql affected rows 1 if isset post remember post remember 1 setcookie cookie user md5 user cookie livetime cp http root setcookie cookie pass pass cookie livetime cp http root locksession session name user session pass pass unlocksession header location query string blank home else showloginform true die showloginform false die output if strcmp get m logout 0 unlocksessionanddestroyallcokies header location query string blank login die check the login data logined 0 flag means we zalogininy log in session locksession if empty session name empty session pass if r mysql query select from cp users where name addslashes session name and pass addslashes session pass and flag enabled 1 limit 1 logined mysql affected rows login through cookies if logined 1 empty cookie cookie user empty cookie cookie pass if r mysql query select from cp users where md5 name addslashes cookie cookie user and pass addslashes cookie cookie pass and flag enabled 1 limit 1 logined mysql affected rows unable to login if logined 1 unlocksessionanddestroyallcokies header location query string blank login die get the user data user data mysql fetch assoc r if user data false die mysql error ex session name user data name session pass user data pass connecting language if strlen user data language 2 safepath user data language file exists system lng user data language php user data language default language require once system lng user data language php unlocksession,['php'] +54436,how do i set order by params using prepared pdo statement i am having problems using params in the order by section of my sql it does not issue any warnings but prints out nothing order columnnamedirection ascstmt dbprepareselect field from table where column my param order by order directionstmtbindparammy param is live pdoparam strstmtbindparamorder order pdoparam strstmtbindparamdirection direction pdoparam strstmtexecutethe my param works but not order or direction is it not being internally escaped correctly am i stuck inserting it directly in the sql like soorder columnnamedirection ascstmt dbprepareselect from table where column my param order by order directionis there a pdoparam column name constant or some equivalentthanks,"['php', 'mysql']" +54441,find elements based on xsd type with lxml i am trying to get a list of elements with a specific xsd type with lxml 2x and i cannot figure out how to traverse the xsd for specific typesexample of schemaxsdelement nameserverowner typesrvrsstring90 minoccurs0xsdelement namehostname typesrvrsstring35 minoccurs0example xml datasrvrsserverownerjohn doesrvrsserverownersrvrshostnamebox01examplecomsrvrshostnamethe ideal function would look like elements getelemsxml doc string90 def getelemsxml doc xsd type xpath or something to find the elements and build a dict return elements,['python'] +54443,pythondaemon does not kill its kids when using pythondaemon i am creating subprocesses likesoimport multiprocessingclass workermultiprocessingprocess def init self queue selfqueue queue we wait for things from this in workerrun q multiprocessingqueuewith daemondaemoncontext for i in xrange3 workerq while true let the workers do their thing qput something we wait forwhen i kill the parent daemonic process ie not a worker with a ctrlc or sigterm etc the children do not die how does one kill the kidsmy first thought is to use atexit to kill all the workers likeso with daemondaemoncontext workers list for i in xrange3 workersappendworkerq atexitregister def kill the children for w in workers wterminate while true let the workers do their thing qput something we wait forhowever the children of daemons are tricky things to handle and i would be obliged for thoughts and input on how this ought to be donethank you,['python'] +54454,objective c coding guidelines is there any pdf which tells about coding guidelines in objective cfor example 1 breaking the function names checkifhitthetrack 2 member variables must be like mvariablename 3 giving better names to subclass please share the related links,"['iphone', 'objective-c']" +54456,deadlock sample in net can anybody give a simple deadlock sample code in c and please tell the simplest way to find deadlock in your c code sample may be the tool which will detect the dead lock in the given sample codenote i have vs 2008,['c#'] +54465,sort string 13584219 in ascending order 12458913 in java how can i sort a string 13584219 in ascending order to get 12458913,['java'] +54474,finding the direction of scrolling in a uiscrollview i have a uiscrollview with only horizontal scrolling allowed and i would like to know which direction left right the user scrolls what i did was to subclass the uiscrollview and override the touchesmoved method voidtouchesmovednsset touches witheventuievent event super touchesmovedtouches witheventevent uitouch touch touches anyobject float now touch locationinviewselfx float before touch previouslocationinviewselfx nslogf f before now if now before right no nslogleft else right yes nslogright but this method sometimes does not get called at all when i move what do you think,"['iphone', 'ios']" +54476,whats the difference between calayer drawincontext and renderincontext whats the difference between calayer drawincontext and renderincontext,['iphone'] +54497,using nsurlrequest to pass keyvalue pairs to php script with post i am fairly new to objectivec and am looking to pass a number of keyvalue pairs to a php script using post i am using the following code but the data just does not seem to be getting posted through i tried sending stuff through using nsdata as well but neither seem to be working nsdictionary data nsdictionary dictionarywithobjectsandkeys bob sender aaron rcpt hi there message nil nsurl url nsurl urlwithstring nsmutableurlrequest request nsmutableurlrequest requestwithurlurl request sethttpmethodpost request sethttpbodynsdata datawithbytesdata lengthdata count nsurlresponse response nserror err nsdata responsedata nsurlconnection sendsynchronousrequestrequest returningresponseresponse errorerr nslogresponsedata contentthis is getting sent to this simple script to perform a db insertphp sender postsender rcpt postrcpt message postmessage script variables include varsphp con mysql connecthost user pass if con diecould not connect mysql error mysql select dbmydb con mysql queryinsert into php test sender rcpt message values sender rcpt message echo completeany ideas,"['php', 'iphone', 'objective-c']" +54498,mixing secure unsecure channels i am unable to use an unsecure channel once a secure channel has already been registered the code below works only if on the client side the unsecured channel is registered beforeis it possible to mix secure and unsecure channels without any constraint on the registration order using systemusing systemcollectionsusing systemruntimeremotingusing systemruntimeremotingchannelsusing systemruntimeremotingchannelstcppublic class sampleobject marshalbyrefobject public datetime gettest return datetimenow public class sampleobject2 marshalbyrefobject public datetime gettest2 return datetimenow static class programclient private static tcpclientchannel registerchannelbool secure string name int priority idictionary properties new hashtable propertiesaddsecure secure propertiesaddname name propertiesaddpriority priority var clientchannel new tcpclientchannelproperties null channelservicesregisterchannelclientchannel false return clientchannel private static void secure registerchanneltrue clientsecure 2 var testsecure sampleobject2activatorgetobjecttypeofsampleobject2 tcp1270018081securedrem consolewritelinesecure testsecuregettest2tolongtimestring private static void unsecure registerchannelfalse clientunsecure 1 var test sampleobjectactivatorgetobjecttypeofsampleobject tcp1270018080unsecuredrem consolewritelineunsecure testgettesttolongtimestring internal static void mainclient consolewritepress enter to start consolereadline works only in this order unsecure secure consolewritelinepress enter to end consolereadline static class programserver private static tcpserverchannel registerchannelint port bool secure string name idictionary properties new hashtable propertiesaddport port propertiesaddsecure secure propertiesaddname name propertiesaddimpersonate false var serverchannel new tcpserverchannelproperties null channelservicesregisterchannelserverchannel secure return serverchannel private static void startunsecure registerchannel8080 false unsecure remotingconfigurationregisterwellknownservicetypetypeofsampleobject unsecuredrem wellknownobjectmodesingleton private static void startsecure registerchannel8081 true secure remotingconfigurationregisterwellknownservicetypetypeofsampleobject2 securedrem wellknownobjectmodesingleton internal static void mainserver startunsecure startsecure consolewritelineunsecure 8080n secure 8081 consolewritelinepress the enter key to exit consolereadline class program static void mainstring args if argslength 1 args0 server programservermainserver else programclientmainclient edit no change with net 4 and vs 2010,"['c#', '.net']" +54500,how i can get rid of none values in dictionary something likefor ab in kwargsiteritems if not b del kwargsathis code raise exception because changing of dictionary when iteratingi thiscover only non pretty solution with another dictionaryres resupdateab for ab in kwargsiteritems if b is not nonethanks,['python'] +54509,find the number of days in a month in java how do you find the number of days in a month in java,['java'] +54512,java utf8 to ascii conversion with supplements we are accepting all sorts of national characters in utf8 string on the input and we need to convert them to ascii string on the output for some legacy use we do not accept chinese and japanese chars only european languageswe have a small utility to get rid of all the diacriticspublic static final string tobasecharactersfinal string stext if stext null stextlength 0 return stext final char chars stexttochararray final int isize charslength final stringbuilder sb new stringbuilderisize for int i 0 i isize i string sletter new stringnew char charsi sletter normalizernormalizesletter normalizerformnfc try byte bletter slettergetbytesutf8 sbappendchar bletter0 catch unsupportedencodingexception e return sbtostringthe question is how to replace all the german sharp s a a a and other characters that get through the above normalization method with their supplements in case of a supplement would probably be ss and in case od a supplement would be either d or djis there some simple way to do it without million of replaceall callsso for example aonardan djonardan blaa blass and so onwe can replace all problematic chars with empty space but would like to avoid this to make the output as similar to the input as possiblethank you for your answersbozo,['java'] +54520,error default argument given for parameter 1 i am getting this error message with the code belowclass money public moneyfloat amount int moneytype string asstringbool shortversiontrueprivate float amount int moneytypefirst i thought that default parameters are not allowed as a first parameter in c but it is allowed,['c++'] +54521,optimization techniques in python recently i have developed a billing application for my company with pythondjango for few months everything was fine but now i am observing that the performance is dropping because of more and more users using that applications now the problem is that the application is now very critical for the finance team now the finance team are after my life for sorting out the performance issue i have no other option but to find a way to increase the performance of the billing application so do you guys know any performance optimization techniques in python that will really help me with the scalability issueguys we are using mysql database and its hosted on apache web server on linux box secondly what i have noticed more is the over all application is slow and not the database transactional part for example once the application is loaded then it works fine but if they navigate to other link on that application then it takes a whole lot of timeand yes we are using html css and javascript,['python'] +54526,php using browscapini on shared host ini set failing i am trying to use get browser unfortunately my page is on a shared host and i have no access to phpinii have downloaded the latest version of browscapini and placed in my document root i have then added the followingif ini setbrowscap homeprivate stuffbrowscapini echo failed to set browscap else echo browscap ini getbrowscap exitbut this fails nb the echo statement for the failed condition always shows even if i didnt have the browscapini file the setting should still show up in the ini get should not iti have looked at the previous questions on this and they do not seem to help any ideas,['php'] +54535,using partcover 23 with net 40 runtime i have successfully got partcover 23 working with vs 2008 on my 64bit machinei am now trying to get it to work with vs 2010 and nunit 253 i have got nunit using the correct clr version but i cannot get partcover to produce any output all i get is an empty report xml filepartcoverreport date20100330t16090510090990100 how do i get partcover 23 or 22 i guess to work with nunit 253 on net 40,['.net'] +54540,enum exeeding the 65535 bytes limit of static initializer whats best to do i have started a rather large enum of so called descriptors that i have wanted to use as a reference list in my model but now i have come across a compilervm limit the first time and so i am looking for the best solution to handle thishere is my error the code for the static initializer is exceeding the 65535 bytes limitit is clear where this comes from my enum simply has far to much elements but i need those elements there is no way to reduce that setinitialy i have planed to use a single enum because i want to make sure that all elements within the enum are unique it is used in a hibernate persistence context where the reference to the enum is stored as string value in the database so this must be uniquethe content of my enum can be devided into several groups of elements belonging together but splitting the enum would remove the unique safety i get during compile time or can this be achieved with multiple enums in some waymy only current idea is to define some interface called descriptor and code several enums implementing it this way i hope to be able to use the hibernate enum mapping as if it were a single enum but i am not even sure if this will work and i loose unique safetyany ideas how to handle that case,['java'] +54546,python animation with matplotlibpyplot how can one create animated diagrams using popular matplotlib library i am particularly interested in animated gifs,['python'] +54555,removing unwanted newline characters when adding in ckeditor when loading content with a set of paragraphs in ckeditor it replaces my p tags with px9that means the editor converts thispparagraph 1paragraph 2paragraph 3pinto what ends up like thisp paragraph 1pp paragraph 2pp paragraph 3phow do i fix it so that ckeditor does not add the extra newline characters when it sees the paragraph tags,['javascript'] +54587,how do i access gui gtk from multi threads i have a worker thread spawned from a gui for gui performance how do i access gui such as spawning new windowswidgets from the thread itselfi tried using delegates but it does not seem to be working any ideas possibly examples thank you,['c#'] +54602,heroku problem during database pull of rails app mysqlerror mysql server has gone away attempting to pull my database from heroku gives an error partway through the process belowusing snow leopard heroku182 taps0226 rails235 mysql5142 database is smallish as you can see from the error messageheroku tech support says it is a problem on my system but offers nothing in the way of how to solve iti have seen the issue reported before for example here how can i get around this problemthe error heroku dbpullautodetected local database mysqllocalhostencodingutf8receiving schemareceiving data17 tables 9609 recordslibraryrubygems18gemssequel300libsequeladaptersmysqlrb166in query mysqlerror mysql server has gone away sequeldatabaseerror from libraryrubygems18gemssequel300libsequeladaptersmysqlrb166in execute from libraryrubygems18gemssequel300libsequeladaptersmysqlrb125in execute from libraryrubygems18gemssequel300libsequelconnection poolrb101in hold from libraryrubygems18gemssequel300libsequeldatabaserb461in synchronize from libraryrubygems18gemssequel300libsequeladaptersmysqlrb125in execute from libraryrubygems18gemssequel300libsequeldatabaserb296in execute dui from libraryrubygems18gemssequel300libsequeldatasetrb276in execute dui from libraryrubygems18gemssequel300libsequeladaptersmysqlrb365in execute dui from libraryrubygems18gemssequel300libsequeldatasetconveniencerb126in import from libraryrubygems18gemssequel300libsequeldatasetconveniencerb126in each from libraryrubygems18gemssequel300libsequeldatasetconveniencerb126in import from libraryrubygems18gemssequel300libsequeladaptersmysqlrb144in transaction from libraryrubygems18gemssequel300libsequelconnection poolrb108in hold from libraryrubygems18gemssequel300libsequeldatabaserb461in synchronize from libraryrubygems18gemssequel300libsequeladaptersmysqlrb138in transaction from libraryrubygems18gemssequel300libsequeldatasetconveniencerb126in import from libraryrubygems18gemstaps0226libtapsclient sessionrb211in cmd receive data from libraryrubygems18gemstaps0226libtapsclient sessionrb203in loop from libraryrubygems18gemstaps0226libtapsclient sessionrb203in cmd receive data from libraryrubygems18gemstaps0226libtapsclient sessionrb196in each from libraryrubygems18gemstaps0226libtapsclient sessionrb196in cmd receive data from libraryrubygems18gemstaps0226libtapsclient sessionrb175in cmd receive from libraryrubygems18gemsheroku182binlibherokucommandsdbrb17in pull from libraryrubygems18gemsheroku182binlibherokucommandsdbrb119in taps client from libraryrubygems18gemstaps0226libtapsclient sessionrb21in start from libraryrubygems18gemsheroku182binlibherokucommandsdbrb115in taps client from libraryrubygems18gemsheroku182binlibherokucommandsdbrb16in pull from libraryrubygems18gemsheroku182binlibherokucommandrb45in send from libraryrubygems18gemsheroku182binlibherokucommandrb45in run internal from libraryrubygems18gemsheroku182binlibherokucommandrb17in run from libraryrubygems18gemsheroku182binheroku14 from usrbinheroku19in load from usrbinheroku19,"['mysql', 'ruby-on-rails']" +54604,get information about autocompletetextview from resulting autocompletetextviewdropdownlistview i am using 3 autocompletetextviews to suggest entries from a databasei subclassed autocompletetextview to handle setting the default text to null when clicked and setting back to the default instructions if moved away and nothing is enteredi was using a simplecursoradapter to bind to the view but i thiscovered that there was no way i could get the id of the autocompletetextview from an onitemclicklistener which i needed to put additional information from the selected row in a variable depending on which autocompletetextview it was from all i could access was the autocompletetextviewdropdownlistview which is an undocumented inner class that appears to offer no real functionality neither was there a way to go up the view hierarchy to get the original autocompletetextviewso i subclassed simplecursoradapter and added an int to the constructor to identify which autocompletetextview the adapter was from and i was able to access this from the view passed into onitemclick so although my solution works fine i wonder if it is possible to get the id of an autocompletetextview from its dropdownlistviewi am also using another database query which gets the id from the onitemclick and then looks up the data for that item because i could not find a way of converting more than one column to a string should i be using cursoradapter for this to save initiating another query oh and another thing do i need a database cursor initially all cursor when all i am doing is filtering on it to get a new cursor seems like overkillactivity dbseopendatabase cursor all cursor dbseautocomplete query startmanagingcursorall cursor string from all new stringdbadapterkey name int to all new int androidridtext1 from adapt new autocompleteadapterfrom dbadapter thisandroidrlayoutsimple dropdown item 1line all cursor from all to all from adaptsetstringconversioncolumn1 from adaptsetfilterqueryproviderthis to adapt new autocompleteadapterto dbadapter thisandroidrlayoutsimple dropdown item 1line all cursor from all to all to adaptsetstringconversioncolumn1 to adaptsetfilterqueryproviderthis from auto complete autocomplete findviewbyidridentry fromfrom auto completesetadapterfrom adaptfrom auto completesetonitemclicklistenerthisto auto complete autocomplete findviewbyidridentry toto auto completesetadapterto adaptto auto completesetonitemclicklistenerthispublic void onitemclick adapterview parent view view int position long id cursor selected row cursor dbsedata from idid selected row cursormovetofirst string lat selected row cursorgetstring1 string lon selected row cursorgetstring2 int source autocompleteadapter parentgetadaptergetsourceautocomplete classpublic class autocomplete extends autocompletetextview implements ontouchlisteneronfocuschangelistenerstring textcontentcontext mycontext nullint viewid thisgetidpublic autocompletecontext context attributeset attrs supercontext attrstextcontent thisgettexttostringmycontext contextthissetonfocuschangelistenerthis thissetontouchlistenerthispublic boolean ontouchview v motionevent event if textcontentequalsmycontextgetstringrstringfrom textbox textcontentequalsmycontextgetstringrstringto textbox textcontentequalsmycontextgetstringrstringvia textbox thissettextreturn falsepublic void onfocuschangeview v boolean hasfocus if hasfocus false int a thisgettextlengthif a 0if viewid ridentry from thissettextrstringfrom textboxif viewid ridentry to thissettextrstringto textboxif viewid ridentry via thissettextrstringvia textboxadapterpublic class autocompleteadapter extends simplecursoradapter int sourcepublic autocompleteadapterint query source context context int layout cursor c string from int to supercontext layout c from to source query sourcepublic int getsource return source sorry that is a lot of code thanks for your helpstephen,['android'] +54618,looping through an object tree recursively is there a way in jquery or javascript to loop through each object and it is children and gandchildren and so onif so can i also read their nameexamplefoo bar child grand greatgrand and so on so the loop should do something like thisloop start ifnameof child do something ifnameof bar do something ifnameof grand do something loop endi know this is stupid code but i tried to make it understandable btw this is for a jquery ui as i am clueless how to go on about thisthanks,"['javascript', 'jquery']" +54620,how to manually add a cookie to mechanize state i am working in ruby but my question is valid for other languages as welli have a mechanizedriven application the server i am talking to sets a cookie using javascript rather than standard setcookie so mechanize does not catch the cookie i need to pass that cookie back on the next get request the good news is that i already know the value of the cookie but i do not know how to tell mechanize to include it in my next get request,['ruby'] +54632,how to enable automatic sorting of ienumerable data in gridview how can i enable automatic sorting of my bll which returns a list customerlistlist in a gridviewcustomer is my own strongly typed class and customerlist is a list of customersi know one approach is to set the allowsorting property to true in the gridview and handle the onsorting event and calling a sorting method defined in my customerlist classhowever i would like a solution which is automatic in the sense that i do not have to handle the onsorting event it should be like how gridview handles automatic sorting for dataview datatable and dataset is there an interface i need to implement on my customerlist or customer class that will enable that functionality,"['c#', 'asp.net']" +54640,can a main method of class be invoked in another class in java can a main method of class be invoked in another class in java,['java'] +54650,jquery getting post action url i am trying to access the post target action in a jquery functionexampleform actionpageusers idsignup methodposti would like to access the action part pageusers in this casesignuplivesubmit functionevent get this submitted actionseems like i am missing something very simple i see the value in the dom but do not know where it is stored in jquerythanks,['jquery'] +54671,algorithm build a recommendation for movies you might like i need help designing an algorithm for recommendations on moviesevery user in the system grades movies on a score between 1100tables consist oftable moviesid name year rating runtimetable con moviestogenresmovieid genreidtable con movietousermovieid userid gradei am trying to build a select query to return 5 most recommended movies for a specific moviebearing in mind i want to integrate in some way similar genres highest grades movie rating so you want be recommended an r rated movie for a pg rated movie unless it is really recommended in every other aspect also if movie matches more than one genre it will increase its recommendation ratiobonus if a user gives a low grade to a movie it will lose recommendation ratioupdatei meant for one user and one title whenever a user enters a movie page he will get recommendations for other movies he might like,['sql'] +54681,how to submit a table with dynamic rows of data via aspnet mvc or jquery i am totally noob to aspnet mvc and currently i am writing an web app which allows user to select multiple product from a listbox and add them to a dynamic table with rows that can be added or removedthus i am thinking of using jquery to add and remove the table row thus the table row will be added via appendxbut the thing is i am not that familiar with aspnet mvc form submission from my understanding thus far i can retrieve the value later via formid but if i were to create the table row via that method i am thinking it is either going to be with the same id or i can use a running no id and a hidden input to keep track of how many products that is addedalso i probably want to hide the whole product table when all the products were removedps kinda feel that my way is sort like a big fugly messy hack which will come back and bite me one dayquestionsdoes aspnet mvc has a good way tohandle all of this i have readsomething about mvc tempdataand is there a better way for me tohandle the dynamic productgeneration to make things easierlater for form submission in aspnetmvc and also i found that you can actually submit the form via jquery too is there any pros and cons between the two method in terms of maybe performance security maintenance etcthanks,"['jquery', 'asp.net']" +54691,composite operations in android canvas i am just starting with android development and i am coming from javascripthtml world so i am currently investigating the possibilities of the android sdkthe html 5 canvas supports composite operations see hereis this possible in an android canvas i scanned the api of the canvas class but could not find anything useful i need at least the composite operation sourcein or if this is not possible sourceatop,"['java', 'android']" +54692,how can i add methods from a java class as global functions in javascript using rhino i have a simple java class that has some methodspublic class utils public void dealstring price int amount public void bidstring price int amount public void offerstring price int amount i would like to create an instance of this class and allow the javascript code to call the methods directly like sodeal13736 10bid13735 50the only way i could figure out for now was to use scriptengine engine new scriptenginemanagergetenginebynamejsenginepututils new utilsand then use utilsdeal in the javascript code i can also write wrapper functions in javascript for each method but there should be a simpler way to do this automatically for all the public methods of a class,"['java', 'javascript']" +54695,stringisnullorempty check for space what is needed to make stringisnullorempty count whitespace strings as emptyeg i want the following to return true instead of the usual falsestringisnullorempty is there a better approach than stringisnullorempty trimnote that the original question asked what the return would be normally hence the unsympathetic comments this has been replaced with a more sensible question,['c#'] +54696,converting list to string in java how do i convert a list into an array the following code returns an errorpublic static void mainstring args liststring strlist new arrayliststring strlistaddsdfs1 strlistaddsdfs2 string strarray string strlisttoarray systemoutprintlnstrarrayerrorexception in thread main javalangclasscastexception ljavalangobject cannot be cast to ljavalangstring at testmaintestjava10,['java'] +54710,executing certain code for every method call in c i have a c class i want to inspect so i would like to all methods print their parameters and the return just before getting outthe latter looks somewhat easy if i do return for everything a macrodefine returna cout a endl return awould do it might be wrong if i padronize all returns to parenthesized or whatever this may be called if i want to take this out just comment out the define however printing inputs seems more difficult is there a way i can do it using c structures or with a workaroud hack,['c++'] +54716,boxshadow not working on webkit i am creating multiple borders to element using boxshadow but they do not show at webkit whats wrong with this code i am using this four times to create shadow on each side then border for extra borderboxshadow 1px 1px 0px rgba01martti laine,['css'] +54725,nullpointerexception in itemizedoverlaygetindextodraw i have a relatively simple mapactivity that i am trying to make thisplaya list of camps within a given map region i have created a customsubclass of overlayitem called campoverlayitem a customitemizedoverlay called campsoverlay that returns campoverlayitems andof course a mapactivity subclass that populates the mapi am pulling the overlay data from a database using an asynctask ascreated in my activity the asynctask is triggered from aviewtreeobserverongloballayoutlistener attached to the mapviewin the onpostexecute method of the asynctask i create a new instanceof my campsoverlay class and pass it a list of the camps returned fromthe database which are fetched in doinbackground i then callmapviewgetoverlaysaddnewoverlaywhere newoverlay is the campsoverlay i just created all of this coderuns without error but when the map tries to draw itself i get anullpointerexception with the following stack tracejavalangnullpointerexception atcomgoogleandroidmapsitemizedoverlaygetindextodrawitemizedoverlayjava211 atcomgoogleandroidmapsitemizedoverlaydrawitemizedoverlayjava240 at comgoogleandroidmapsoverlaydrawoverlayjava179 at comgoogleandroidmapsoverlaybundledrawoverlaybundlejava42 at comgoogleandroidmapsmapviewondrawmapviewjava476 at androidviewviewdrawviewjava6274 at androidviewviewgroupdrawchildviewgroupjava1526 at androidviewviewgroupthispatchdrawviewgroupjava1256 at androidviewviewgroupdrawchildviewgroupjava1524 at androidviewviewgroupthispatchdrawviewgroupjava1256 at androidviewviewdrawviewjava6277 at androidwidgetframelayoutdrawframelayoutjava352 at androidviewviewgroupdrawchildviewgroupjava1526 at androidviewviewgroupthispatchdrawviewgroupjava1256 at androidviewviewgroupdrawchildviewgroupjava1524 at androidviewviewgroupthispatchdrawviewgroupjava1256 at androidviewviewgroupdrawchildviewgroupjava1524 at androidviewviewgroupthispatchdrawviewgroupjava1256 at androidviewviewgroupdrawchildviewgroupjava1524 at androidviewviewgroupthispatchdrawviewgroupjava1256 at androidviewviewgroupdrawchildviewgroupjava1524 at androidviewviewgroupthispatchdrawviewgroupjava1256 at androidviewviewdrawviewjava6277 at androidwidgetframelayoutdrawframelayoutjava352 at androidviewviewgroupdrawchildviewgroupjava1526 at androidviewviewgroupthispatchdrawviewgroupjava1256 at androidviewviewdrawviewjava6277 at androidwidgetframelayoutdrawframelayoutjava352 at comandroidinternalpolicyimplphonewindowdecorviewdrawphonewindowjava1883 at androidviewviewrootdrawviewrootjava1332 at androidviewviewrootperformtraversalsviewrootjava1097 at androidviewviewroothandlemessageviewrootjava1613 at androidoshandlerthispatchmessagehandlerjava99 at androidoslooperlooplooperjava123 at androidappactivitythreadmainactivitythreadjava4203 at javalangreflectmethodinvokenativenative method at javalangreflectmethodinvokemethodjava521 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava791 at comandroidinternaloszygoteinitmainzygoteinitjava549 at dalviksystemnativestartmainnative methodbecause it seems particularly relevant here is the code for myitemizedoverlay subclasspublic class campsoverlay extends itemizedoverlaycampoverlayitem private arraylistcamp camps null public campsoverlaydrawable defaultmarker arraylistcamp thecamps superdefaultmarker thiscamps thecamps override protected campoverlayitem createitemint i camp camp campsgeti campoverlayitem item new campoverlayitemcamp return item override protected boolean ontapint index todo autogenerated method stub return superontapindex override public int size return campssize does anyone have any idea what could be happening here i have attemptedto verify that everything i have control over is nonnull i canprovide more code if necessary,['android'] +54731,problem registering a com server written for excel registered on client machine cannot set full path to mscoreedll in this previous question how to get com server for excel written in vbnet installed and registered in automation servers list there is an example of how to create the full path to a registry key using vs 2008 everything in the previous answer works correctly except the full path that i am setting using the registry editor in vs for mscoreedll is not working meaning it seems to do nothingthe full registry path ishkey classes rootclsidmy guidinprocserver32defaultand the value i am setting issystemfoldermscoreedlli can put anything including hardcoding the full path but the setting does not seem to matter and the registry always contains mscoreedll without any pathi have tried adding another value to the registry path via vs and that works correctly including having the full path as specified by systemfolderthe reason i need the full path as explained in the previous question is that without the path excel generates an error when the automation server is selected as it cannot find mscoreedll interestingly even though i receive an error the registration works oki am doing the install via a setup project which otherwise works finei am installing on a vista64 system but have gotten the same error on other ossdoes anyone know what i am doing wrong,['.net'] +54746,new line and returns ignored in setmessagebody am i doing something dumb i can prefill and email ok but the rn is ignored in the emailbody void sendeventinemail mfmailcomposeviewcontroller picker mfmailcomposeviewcontroller alloc init pickermailcomposedelegate self nsstring emailsubject eventdictionary objectforkeyevent name key picker setsubjectemailsubject fill out the email body text nsstring ituneslink link to itune app link nsstring content eventdictionary objectforkeydescription nsstring emailbody nsstring stringwithformatrnsent using a href whats on readinga for the iphone content ituneslink picker setmessagebodyemailbody ishtmlyes pickernavigationbarbarstyle uibarstyleblack self presentmodalviewcontrollerpicker animatedyes picker releaseregardsdave,['iphone'] +54747,how to check if all values in array are identical in php how can i quickly tell if all values in array are identical,['php'] +54749,learning c as a perl programmer i am a perl5 programmer for 7 years and i am trying to learn c nowsome of the c syntax is hard for me to understand and to think in c wayfor examplein perl you can mix the data in the arraysarray 1string5355you can assign any value to a scalar variablevar 1var stringvar reference to scalarthere are many examplesa friend of mine recommend me the book thinking of c by bruce eckel but i have not any c background and it is hard for me to understand some thingsso my question is could you recommend me a book for this situation i do not want to learn c i understand oop i am getting more familiar with c oop aswell i understand the point of the pointers and some arithmetic and references widely used in perli do not need manuals for dummies what is int bool double if while i just need a direction how to learn c from the perspective of a perl programmer because i am sure that there are many like methank you in advanceedit thank you for all the recommended books and the answers i will try with accelerated c i will start from the beginning and try to change my mindflow to c i have added the beginner tag,['c++'] +54757,dynamically enable or thisable requiredfieldvalidator based on value of dropdownlist i have an aspnet form with three text inputs one each for work phone home phone and cell phone each of these text inputs has a requiredfieldvalidator associated with it i also have a dropdownlist where the user can select the preferred phone type i want to only require the field that is selected in the dropdownlist for example if the user selects work phone from the dropdownlist i want to thisable the requiredfieldvalidator for home phone and cell phone thereby only making the work phone field requiredi have a method that enables and thisables these validators based on the value of the dropdownlist but i cannot figure out when to call it i want this method to run before the validation takes place on the page how would i do that,['asp.net'] +54781,how to tell when a socket has been thisconnected on the client side i need to know whenif my socket connection has been broken however the socketconnected property always returns true even after the server side has been thisconnected and i have tried sending data through it can anyone help me figure out whats going on here i need to know when a socket has been thisconnected socket serversocket null tcplistener listener new tcplistener1530 listenerstart listenerbeginacceptsocketnew asynccallbackdelegateiasyncresult result debugwritelineaccepting socket connection tcplistener currentlistener tcplistenerresultasyncstate serversocket currentlistenerendacceptsocketresult listener socket clientsocket new socketaddressfamilyinternetwork sockettypestream protocoltypetcp debugwritelineclient socket connected clientsocketconnectedshould be false and it is clientsocketconnectlocalhost 1530 debugwritelineclient socket connected clientsocketconnectedshould be true and it is threadsleep10 serversocketcloseclosing the server socket here threadsleep10 clientsocketsendnew byte0sending data should cause the socket to update its connected property debugwritelineclient socket connected clientsocketconnectedshould be false but its always true,"['c#', '.net']" +54786,binary comparison operators on generic types i have a generic class that takes a type t within this class i have a method were i need to compare a type t to another type t such aspublic class myclasst public t maxvalue implimentation for maxvalue public t mymethodt argument ifargument thismaxvalue then do something the comparison operation inside of mymethod fails with compiler error cs0019 is it possible to add a constraint to t to make this work i tried adding a where t icomparablet to the class definition to no avail,"['c#', '.net']" +54790,how do you keep your business rules dry in the perfect application every business rule would exist only once i work for a shop that enforces business rules in as much as possible in the database in many cases to achieve a better user experience were performing identical validations on the client side not very dry being a spot purist i hate thison the other end of the spectrum some shops create dumb databases the rails community leans in this direction and relegate the business logic to a separate tier but even with this tack some validation logic ends up repeated client sideto further complicate the matter i understand why the database should be treated as a fortress and so i agree that validations be enforcedrepeated at the databasetrying to enforce validations in one spot is not easy in light of conflicting concerns stay dry keep the database a fortress and provide a good user experience i have some idea for overcoming this issue but i imagine there are bettercan we balance these conflicting concerns in a dry manner,['ruby-on-rails'] +54792,cancelling listbox selectedindexchange event is it possible to cancel the selectedindexchange event for a listbox on a winforms application this seems like such a logical thing to have that i must be overlooking some easy feature basically i have been popping up a message box asking if the user really wants to move to another item as this will change the ui and i do not want their changes to be lost i would like to be able to cancel the event in case the user has not saved what they are working on is there a better way of doing this,['c#'] +54798,do fluent interfaces significantly impact runtime performance of a net application i am currently occupying myself with implementing a fluent interface for an existing technology which would allow code similar to the following snippetusing var directory opendirectorypathtosomedirectory using var file openfilefoobarhtmlindirectory in order to implement such constructs classes are needed that accumulate arguments and pass them on to other objects for example to implement the openfilein construct you would need two classes handles openxpublic static class openphrase handles openfilex public static openfilephrase filestring filename return new openfilephrasefilename handles opendirectoryx public static directoryobject directorystring path handles openfilexpublic class openfilephrase internal openfilephrasestring filename filename filename handles openfilexinx public fileobject indirectoryobject directory private readonly string filenamethat is the more constituent parts statements such as the initial examples have the more objects need to be created for passing on arguments to subsequent objects in the chain until the actual statement can finally executequestioni am interested in some opinions does a fluent interface which is implemented using the above technique significantly impact the runtime performance of an application that uses it with runtime performance i refer to both speed and memory usage aspectsbear in mind that a potentially large number of temporary argumentsaving objects would have to be created for only very brief timespans which i assume may put a certain pressure on the garbage collectorif you think there is significant performance impact do you know of a better way to implement fluent interfaces,['.net'] +54799,why is the base constructor not necessary i have a class structure likeabstract class animal public animal init stuff class cat animal public catbool is keyboard base note here other init stuff now then look at the noted line if you remove base then it will compile without an error why is this is there a way to thisable this behavior,['c#'] +54800,net do you get a transaction object working with sql ado got me thinking about something that i think should logically be included with the net framework and i was wondering if such a thing exists let me explain is there an object that is essentially a transaction manager that you pass commands work items to and at the same i would imagine it would be necessary also pass the rollback actions for each work item in the transactionfor examplelets say i wanted to perform the following actionscreate a foldercreate a file in this folderperform some other misc tasks like editing reg keys or really action you can think of that can be rolled back now currently if something fails i need to manually implement a roll back strategy so perhaps a way exists to manage these work items as a transaction using oob net functionalitymy considerations are that it would be asking a lot to have items rollback automatically but having the ability to manually control what happens during a rollback per work item seems practical another thing is what microsoft have done with linq is really great effectively having sql like queries for all kinds of stuff not only for sql tables so perhaps there is some transaction model with linqthanks if you know of anything like this,['.net'] +54811,is the rails default csrf protection insecure by default the form post csrf protection in rails creates an authenticity token for a user that only changes when the users session changes one of our customers did a security audit of our site and flagged that as an issuethe auditors statement was that if we also had a xss vulnerability that an attacker could grab another users authenticity token and make use of it for csrf attacks until the users session expired but is seems to me that if we had an xss vulnerability like that an attacker could just as easily grab another users session cookie and login as that user directly or even just make calls to our rest api from script as the user being attacked being able to mount a csrf attack does not seem any worse in such a situation the problem would be the xss vulnerabilityhave i missed something is there a real problem with the default csrf protection in rails,['ruby-on-rails'] +54813,what to put in a python module docstring ok so i have read both pep 8 and pep 257 and i have written lots of docstrings for functions and classes but i am a little unsure about what should go in a module docstring i figured at a minimum it should document the functions and classes that the module exports but i have also seen a few modules that list author names copyright information etc does anyone have an example of how a good python docstring should be structured,['python'] +54815,why do i get garbage output when printing an int my program is suppose to count the occurrence of each character in a file ignoring upper and lower case the method i wrote is public int getchartimesfile textfile throws filenotfoundexception scanner infile new scannertextfile int lower new int26 char current int other 0 whileinfilehasnext string line infilenextline string line2 linetolowercase for int ch 0 ch line2length ch current line2charatch ifcurrent a current z lowercurrenta else other return lower and is printed out usingforint letter 0 letter 26 letter systemoutprintchar letter a systemoutprintln tsgetchartimesfile where ts is a textstatistic object created earlier in my main method however when i run my program instead of printing out the number of how often the character occurs it printsa if84386 b i1194a4e c i15d56d5 d iefd552 e i19dfbff f i10b4b2f and i do not know what i am doing wrong,['java'] +54822,refresh reload a page once using jquery i am wondering how to refreshreload a page or even specific div once using jquery ideally in a way right after the dom structure is available cf onload event and not negatively affecting back button or bookmark functionality please note replace is not allowed due to thirdparty restrictions,['jquery'] +54835,why protected superclass member cannot be accessed in a subclass function when passed as an argument i get a compile error which i am slightly confused about this is on vs2003error c2248 ay cannot access protected member declared in class aclass apublic a x0 y0 protected int x int yclass b public apublic b a z0 bconst a item a z1 x itemyprivate int zthe problem is with x itemythe access is specified as protected why does not the constructor of class b have access to ay,['c++'] +54844,appending strings to nsmutablestring been looking at this for a bit now and not understanding why this simple bit of code is throwing an error shortened for brevitynsmutablestring outputproperty nonatomic retain nsmutablestring outputsynthesize output logs output start as expectedoutput nsmutablestring stringwithcapacity0output appendstringoutput startnslog output error happens here this is later on in a different methodoutput appendstringdoing roll for playercan anyone spot my mistake,['objective-c'] +54858,doing a diff on an associative array in javascript jquery if i have two associative arrays what would be the most efficient way of doing a diff against their valuesfor example given array1 foreground red shape circle background yellow array2 foreground red shape square angle 90 background yellow how would i check one against the other such that the items missing or additional are the resulting array in this case if i wanted to compare array1 within array2 it would returnarray3 shape circlewhilst if i compared array2 within array1 it would returnarray3 shape square angle 90thanks in advance for your help,"['javascript', 'jquery']" +54861,aspnet mvc jquery ajax input parameters are null i am trying to post some data with jquery ajax but the parameters in my ajax method are nullthis is simple test to send data var datapost titel titel message msg tagids hello jqueryajax type post url create contenttype applicationjson charsetutf8 data tojsondatapost datatype json success functionresult alertdata returned and my ajax method looks like thishttppostpublic actionresult createstring title string message string tagids there is something basic wrong with the data i send but i cannot figure out what all the time the title message and tagids are null so there is something wrong with the encoding i just do not know whatoptimally the parameter tagids should be an array or list of guidsnote the jquerytojson is this plugin,['jquery'] +54864,how to test a site rigorously i recently created a big portal site it is time for putting it to testhow do you guys test a site rigorouslywhat are the ways and tools for thatcan we sort of mimic hundreds of virtual users visiting the site to see its load handlingthe test should be for both security and speed,['php'] +54872,programmatically change the tab order how do i programmatically reorder the tabs in a tabcontrol i need to sort the tabs depending on some conditionsif it is possible to do the reordering through the designer i guess we must be able to do it through code at runtime too,['c#'] +54880,selecting a specific div from a extern webpage using curl hi can anyone help me how to select a specific div from the content of a webpagelet us say i want to get the div with idwrapper content from webpage my current code looks something like this not workingreg exps searchfor dont know what to put hereui curlch curl inittimeout 5 set to zero for no timeoutcurl setopt ch curlopt url curl setopt ch curlopt returntransfer 1curl setopt ch curlopt connecttimeout timeoutifpreg matchs searchfor ch file contents curl execchcurl closech thisplay fileecho file contentsso i would like to know how i can use reg expressions to find a specific div and how to unset the rest of the webpage so that file content only contains the div,"['php', 'html']" +54888,handling multiple uiswitch controls in a table view without using tag property i have a table view controller with multiple uiswitch controls in them i set the delegate to the table view controller with the same action for all switches i need to be able to determine what switch was changed so i create an array of strings that contains the name of each switch the indexes in the array will be put in the tag property of each uiswitchhowever i am ready using the tag property for something else namely to find the right control in the cell in cellforrowatindexpath with viewwithtag there are several things i need to set within each cellso am i thinking along the right lines here i feel i am rather limited in how i find out exactly which uiswitch changed its value so i can do something useful with it,"['objective-c', 'iphone']" +54889,private destructor for singleton class is it compulsory to have a private destructor for a singleton class,['c++'] +54896,having public properties in c class how do i have properties in c class as you have in a c class i do not want to have getter and setter methods,['c++'] +54900,multiple appconfig files i want to separate my appconfig file for example i want to move servicemodel part to another config file in the same project how can i do thatthanks,['c#'] +54902,mysql return deadlock with insert row and fk is locked for update i get deadlock error in my mysql transactionthe simple example of my situationthread1 beginquery ok 0 rows affected 0 secthread1 select from a where id10 for update1 row in set 0 secthread2 beginquery ok 0 rows affected 0 secthread2 insert into b aid name values 10 hello worldhangsthread1 insert into b aid name values 10 hello world2error 1213 401 deadlock found when trying to get lock try restarting transactionthread2 query ok 1 row affected 10 secbaid is a foreign key referring to aidi see three solutionscatch deadlock error in code and retry queryuse innodb locks unsafe for binlog in mycnflock for update table a in thread2 before insertis there any other solutions,['mysql'] +54904,connectionsetrequestproperty and excplicitly writing to the urloutputstream are they same url url new urlhttpurlconnection connection httpurlconnection urlopenconnectionconnectionsetdooutputtrueconnectionsetrequestmethodpostis connectionsetrequestpropertykey valuethe same as outputstreamwriter writer new outputstreamwriterconnectiongetoutputstreamwriterwritekey valuewritercloseif not please correct me,['java'] +54909,heavy usage of python at google googles heavy usage of python is it just a matter of taste or does it give them a competitive advantage,['python'] +54910,oracle does not remove cursors after closing result set note we reuse single connectionpublic connection connection try if connection null connectionisclosed if connectionnull logsevereconnection was closed connection drivermanagergetconnectionjdbcurl username password catch sqlexception e logseverecannot connect egetmessage return connection public ingisobject selectstring query string idcolumnname string columns connection con connection vectoringisobject objects new vectoringisobject try statement stmt concreatestatement string sql query resultset rs stmtexecutequerysqloracle increases cursors count here whilersnext ingisobject o new ingisobjectnew result osetidcolumnnameidcolumnname osetdatabasethis forstring column columns oattrsputcolumn rsgetobjectcolumn objectsaddo rsclose oracle do not decrease cursor count here while it is expected stmtclose catch sqlexception ex systemoutprintlnquery exprintstacktrace,['java'] +54911,how to load images just when are needed jquery and js like in this site it only loads the image when you are rally seeing it this is something i would want to implement in my website thanksand a preloader if possible i use jquery,['jquery'] +54913,hibernate or jpa or jdbc or i am developing a java desktop application but have some confusions in choosing a technology for my persistence layertill now i have been using jdbc for db operations now recently i learnt hibernate and jpa but still i am a novice on these technologiesnow my question is what to use for my java desktop application from the followingjpahibernate jdbcdaoany other suggestion from youi know that there is no best choice from them and it totally depends on the complexity and the requeirements of the project so below are the requirements of my projectit is not a complex application it contains only 5 tables and 5 entitiesi want to make my code flexible so that i can change the database later easilythe size of the application should remain as small as possible as i will have to thistribute it to my clients through internetit must be free to use in commercial development and thistribution edited on the basis of the below answers i would like to go with jpa so as to prevent myself from writing vendorspecific sql codebut i have some problems in jpa which are mentioned at,['java'] +54914,datetime parsing of custom date format in net i have a string of the form order20100322194007 it 20100322194007 date and time 20100322 1940070 how to parse a string and get the contained object datetime,['c#'] +54917,hibernate ordering a set i have a class person who has a set of books it is not meaningful in the particular case to have an ordered or sorted collectionsay now that i have a search page with a table showing the join of person and book i want to be able to sort the results by fields from both person and book and then get a list from hibernate and iterate over itbecause the collection is a set the ordering of the books has vanished persistentset of hibernate wraps a hashset of books which is not orderedso with this approach i cannot have results also ordered by book fieldsif i change the collection from set to list my model is semantically incorrect there is no meaning for keeping order in the modelis there an approach to keep the ordering of books perhaps there is a way for the persistentset to wrap a linkedhashset which is ordered where the order is defined by my search criteriacheers,['java'] +54920,find last index of by regex in java i have a string o i want to find the last to split the string first attemp was pol but that gets it inclusive the o which is obvious has somebody a tip,['java'] +54921,are there any ipythonlike shells for ruby or rails i love ipython and am learning ror along with some libraries like mechanize and i would like to be able to easily see what i am working with in terms of introspection i would like to be able to type tab and see,"['ruby-on-rails', 'ruby']" +54924,android declarative vs programmatic ui has anyone seen or compiled benchmarks comparing declarative xml versus programmatically created uis in androidthere are things that google has done to speed up the declarative approach but you still do have the layout inflation step done at runtimehave you ever switched or considered changing your ui from declarative to programmatic for any reason,['android'] +54928,is it possible to email the contents of vim using html i like to view the current differences in the source files i am working on with a command likevim svn diff dubwhat i would really like to be able to do is to email that colorized diff i know vim can export html with the tohtml but how do i pipeline this output into an html email ideally i would like to be able to send an html diff with a single shell script command,['html'] +54929,c reflection find the generic type of a collection i am reflecting a property blah its type is icollection public icollectionstring blah get set private void button1 clickobject sender routedeventargs e var pi gettypegetpropertyblah messageboxshowpipropertytypetostring this gives me as youd expect icollectionstring but really i want to get the collection type ie icollection rather than icollectionstring does anyone know how i would do this please,['c#'] +54930,javascript to make input field in edit modeinsert mode how is it possible to make a input field editable in javascript i mean onfocus putting it in insert mode so that values can be overwritten any suggestions,['javascript'] +54938,css opacity and child elements style typetextcssdivfoo background 0ff width 200px height 200px opacity 030 filter alphaopacity 30divfoodiv color black opacity1 filter alphaopacity 100stylediv idfoo divloremdiv divipsumdiv divdolordivdivin the above example the opacity of divfoo is inherited by child elements causing the text to become nearly unreadable i suppose it is wrong to say it is inherited the opacity is applied to the parent div and the children are part of that so attempting to override it for the child elements does not work because technically they are opaquei typically just use an alpha png background image in such cases but today i am wondering if there is a better way to make a background of a div semitransparent without affecting the contents,['css'] +54939,netbeans gui editor generating its own incomprehensible code when creating a new project in netbeans if i select java desktop application it creates some code which i do not recognise at all as what i had learnt in swingit imports packages such as orgjdesktopapplicationsingleframeapplicationalso the declaration for main looks like this public static void mainstring args launchdesktopapplication2class args this really does not make any sense to my knowledge of jframe jpanel etcif i try to code a netbeans application from scratch i can write my own swing app but i cannot find the gui editorhow do i bring the gui editor when creating java application from scratch can anyone explain to me this orgjdesktopapplicationsingleframeapplication and other classes please help this is really frustrating,['java'] +54944,placing component on glass pane i have a subclass of jlabel that forms a component of my gui i have implemented the ability to drag and drop the component from one container to another but without any visual effects i want to have this jlabel follow the cursor during the drag of the item from one container to another i figured that i could just create a glass pane and draw it on there however even after i add the component to the glass pane set the component visible and set the glass pane visible and set the glass pane as opaque i still so not see the component i know the component works because i can add it to the content pane and have it show uphow do i add a component to the glass panefinally figured how to get the simple example working thanks akf i was able to adapt this solution to my original problem allowing me to remove 60 lines of java2d code that manually rendered a representation of the jlabelpackage testimport javaawtcolorimport javaxswingjframeimport javaxswingjlabelimport javaxswingjpanelimport javaxswingborderlineborderpublic class mainframe extends jframe param args public static void mainstring args mainframe mf new mainframe mfsetsize400 400 mfsetlocationrelativetonull mfsetdefaultcloseoperationthispose on close mfsetglasspanenew jpanel jlabel l new jlabel lsettexthello lsetbordernew linebordercolorblack 1 lsetbounds10 10 50 20 lsetbackgroundcolorred lsetopaquetrue lsetpreferredsizelgetsize mfaddl jpanelmfgetglasspaneaddl mfgetglasspanesetvisibletrue mfsetvisibletrue,['java'] +54958,specializing a template on a lambda in c0x i have written a traits class that lets me extract information about the arguments and type of a function or function object in c0x tested with gcc 450 the general case handles function objectstemplate typename fstruct function traits template typename r typename a struct internal template typename r typename a struct internalr fa typedef typename internaldecltypefoperatornested types go herethen i have a specialization for plain functions at global scopetemplate typename r typename astruct function traitsr a this works fine i can pass a function into the template or a function object and it works properlytemplate typename fvoid foof f typename function traitsfwhatever int fint x foofwhat if instead of passing a function or function object into foo i want to pass a lambda expressionfooint x the problem here is that neither specialization of function traits applies the c0x draft says that the type of the expression is a unique unnamed nonunion class type demangling the result of calling typeidname on the expression gives me what appears to be gccs internal naming convention for the lambda mainlambdaint1 not something that syntactically represents a c typenamein short is there anything i can put into the template heretemplate typename r typename astruct function traits that will allow this traits class to accept a lambda expression,['c++'] +54973,combine stored procedure and query in tsql how do i combine executing of a stored procedure and using its result or parameters in a regular sql query for example i would like to do something like the following passing result of select to spselect a b from texec my sp a b passing result of sp to insert insert into texec my sp a betc,['sql'] +55001,adding ids to google map markers i have a script that loops and adds markers one at a timei am trying to get the current marker to have an info window and and only have 5 markers on a map at a time 4 without info windows and 1 withhow would i add an id to each marker so that i can delete and close info windows as neededthis is the function i am using to set the markerfunction codeaddressaddress contentstring var infowindow new googlemapsinfowindow content contentstringif geocoder geocodergeocode address address functionresults status if status googlemapsgeocoderstatusok mapsetcenterresults0geometrylocation var marker new googlemapsmarker map map position results0geometrylocation infowindowopenmapmarker else alertgeocode was not successful for the following reason status,['javascript'] +55004,android market search results position mystery how is an apps position in the android market search results determined is it as mysterious and complex as google web search resultswe obviously do not want to change any words in our apps title or description that would hurt our position same question applies for not only search results but when clicking on a category in the android market how is the order of the list determinedhopefully someone here can help i would think that google would have published some guidelines at least that could help but i have not found anything yet,['android'] +55038,fastest way to calculate a 128bit integer modulo a 64bit integer i have a 128bit unsigned integer a and a 64bit unsigned integer b whats the fastest way to calculate a b that is the 64bit remainder from dividing a by bi am looking to do this in either c or assembly language but i need to target the 32bit x86 platform this unfortunately means that i cannot take advantage of compiler support for 128bit integers nor of the x64 architectures ability to perform the required operation in a single instructioneditthank you for the answers so far however it appears to me that the suggested algorithms would be quite slow wouldnt the fastest way to perform a 128bit by 64bit division be to leverage the processors native support for 64bit by 32bit division does anyone know if there is a way to perform the larger division in terms of a few smaller divisionsre how often does b changeprimarily i am interested in a general solution what calculation would you perform if a and b are likely to be different every timehowever a second possible situation is that b does not vary as often as a there may be as many as 200 as to divide by each b how would your answer differ in this case,['c'] +55043,html how to create a div with only vertical scrollbars for long paragraphs i want to show terms and condition note on my website i dont want to use text field and also dont want to use my whole page i just want to thisplay my text in selected area and want to use only vertical scrollbar to go down and read all textcurrently i am using this codediv stylewidth10height10overflowscroll text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text textdivtwo problemsit is not fixing the width and height and spread until the all text appears second it is showing horizontal scrollbar and i do not want to show it,"['css', 'html']" +55045,how to always run a service in the background i am in the process of creating an app that is similar to the builtin sms appwhat i need a service that is always running in the background every 5 min the service checks the current location of the device and calls a web service if certain criteria are met the service should generate a notification just like the sms app when the notification is clicked the user is taken to the app just like the sms app when the app is installed the service should be started when the device is rebooted the service should be started what i have tried running a regular service which worked just fine until android kills the service using the alarmmanager to make the 5 min interval call to a service but i was not able to make this work,['android'] +55049,sharedpreferences file does somebody knows where the file with the actual stored sharedpreferences is located,['android'] +55062,mysql and group concat maximum length i am using group concat in a mysql query to convert multiple rows into a single stringhowever the maximum length of the result of this function is 1024 charactersi am very well aware that i can change the param group concat max len to increase this limitset session group concat max len 10however on the server i am using i cannot change any param not by using the preceding query and not by editing any configuration fileso my question isis there any other way to get the output of a multiple row query into a single string,['mysql'] +55078,how to set xmlns when serializing object in c i am serializing an object in my aspnet mvc program to an xml string like thisstringwriter sw new stringwriterxmlserializer s new xmlserializertypeofmytypesserializesw mydatanow this give me this as the first 2 linesxml version10 encodingutf16getcustomername xmlnsxsi xmlnsxsdmy question is how can i change the xmlns and the encoding type when serializingthanks,['c#'] +55086,ruby jsonpretty generate is pretty unpretty i cannot seem to get jsonpretty generate to actually generate pretty output in railsi am using rails 235 and it seems to automatically load the json gem awesome while using scriptconsole this does indeed produce jsonsome data foo 1 bar 20 cow 1 2 3 4 moo dog woof cat meowsome datato json cow1234moocatmeowdogwooffoo1bar20but this does not produce pretty outputjsonpretty generatesome data cow1234moocatmeowdogwooffoo1bar20the only way i have found to generate it is to use irb and to load the pure versionrequire rubygemsrequire jsonpuresome data foo 1 bar 20 cow 1 2 3 4 moo dog woof cat meowjsonpretty generatesome data n cow n 1n 2n 3n 4n n moo n cat meown dog woofn n foo 1n bar 20nbut what i really want is rails to produce this does anyone have any tips why i cannot get the generator in rails to work correctlythanks,"['ruby-on-rails', 'ruby']" +55093,why is giving a fixed width to a label an accepted behavior there are a lot of questions about formatting forms so that labels align and almost all the answers which suggest a pure css solution as opposed to using a table provide a fixed width to the label elementbut is not this mixing content and presentation in order to choose the right width you basically have to see how big your longest label is and try a pixel width value until it fits this means that if you change your labels you also have to change your css,"['html', 'css']" +55116,is it possible to use javascript to change the metatags of the page if i put a div in the head and thisplaynone than use javascript to thisplay it will this workediti have stuff loaded in ajax and as my ajax changes the main portion of the site i want to change the metatags as well,"['javascript', 'jquery']" +55131,respond to and protected methods it may not be so obvious how respond to works in rubyconsider thatclass a def public method end protected def protected method end private def private method endendobj anewobjrespond topublic method true that is pretty obviousobjrespond toprivate method false as expectedobjrespond toprotected method true wtfso if obj responds to protected method we should expectobjprotected methodnot to raise an exception should not webut it raises obviouslydocumentation points that calling respond to with 2nd argument set to true check private method as wellobjrespond toprivate method true trueand that is far more reasonableso the question is how to check if object responds to public method onlyis there a solution better than thatobjmethodsincludepublic method trueobjmethodsincludeprotected method false,['ruby'] +55134,socketaccept error 24 to many open files i have a problem with open files under my ubuntu 910 when running server in python26and main problem is that that i do not know why it so i have set ulimit n 9netcoresomaxconn 9fsfilemax 9and lsof gives me about 120 open files when server is runningand also i am using epollbut after some time it is start giving exeptionfile usrlibpython26socketpy line 195 in accepterror errno 24 too many open filesand i do not know how it can reach file limit when it is not reachedthanks for help,['python'] +55143,gd converting a png image to jpeg and making the alpha by default white and not black i tried something like this but it just makes the background of the image white not necessarily the alpha of the image i wanted to just upload everything as jpgs so if i could somehow flatten a png image with some transparently to default it to just be white so i can use it as a jpg instead appreciate any help thanksold imagecreatefrompnguploadbackground imagecolorallocateold255255255imagefillold 0 0 backgroundimagealphablendingold falseimagesavealphaold true,['php'] +55152,how to send sms in java what are the possible ways to send and receive sms from java application note i am expecting a list of possible waysalso your opinion about each which is better how,['java'] +55161,xdebug how to thisable remote debugging for single php file i am using eclipse ide remote xdebugeclipseide is listening 90 port for some kind of xdebug informationthere are some php scripts running by cron on server so every cron execution xdebug is sending information to my workstation and eclipseide is trying to find this file in my project but file could not be find because cron running scrits do not relate to the project i am working with so every cron run eclipse ide is alerting this message i have tried to add to cron executed php scripts some stringsif function existsxdebug thisable xdebug thisable but it did not helpedany ideasthank you,['php'] +55162,python algorithm to randomly select a key based on proportionalityweight i am a bit at a loss as to how to find a clean algorithm for doing the followingsuppose i have a dict k k a 68 b 62 c 47 d 16 e 81i now want to randomly select one of these keys based on the weight they have in the total ie sum amount of keys sumkvalues 274so that there is a 6802740 0248175182481751832481 percent change that a is selectedhow would you write an algorithm that takes care of this in other words that makes sure that on 10 random picks a will be selected 2481 times,['python'] +55169,check if a filedirectory exists is there a better way i find myself doing this a lot just to ensure the filename is not in use is there a better waydirectoryexistsname fileexistsname,"['c#', '.net']" +55171,is it possible to refactor this c if statement simple question i have the following simple if statements if foo animalcat foo animaldog if baa 1 baa 69 is it possible to refactor these into something like thisclaimer i know this does not compile but this is sorta what i am trying to getif foo animalcat animaldog if baa 1 69 cheers editi wonder if a lambda expression extension could do this p,['.net'] +55183,how i set the background color in uiview using cgcontext i have developed the application in which i want to set the background color of uiview which is already set on uiviewcontrollerthe code is belowimplementation frmgraphview idinitwithframecgrectframe if self super initwithframeframe initialization code return self voiddrawrectcgrectrect cgcontextref ctx uigraphicsgetcurrentcontext cgcontextclearrectctx rect cgcontextsetcmykfillcolorctx 350 560 340 300 10 cgcontextsetrgbfillcolorctx 920f 950f 970f 10f cgcontextfillrectctx cgrectmake0 0 300 280 cgcontextsetrgbstrokecolorctx 20 20 20 10 cgcontextsetlinewidthctx 20 float fltx1fltx2flty1flty20 nsarray hoursindays nsarray alloc initwithobjects01 234567891012 nil fltx1 30 flty1 5 fltx2 fltx1 flty2 270 dividing the yaxis cgcontextmovetopointctx fltx1 flty1 cgcontextaddlinetopointctx fltx2 flty2 float y 275 forint intindex 0 intindex hoursindays count flty220 intindex cgcontextsetrgbstrokecolorctx 20 20 20 10 cgcontextmovetopointctx fltx13 flty2 cgcontextaddlinetopointctx fltx13 flty2 cgcontextselectfontctx helvetica 140 kcgencodingmacroman cgcontextsettextdrawingmodectx kcgtextfill cgcontextsetrgbfillcolorctx 0 255 255 1 cgaffinetransform xform cgaffinetransformmake 10 00 00 10 00 00 cgcontextsettextmatrixctx xform const char arraydataforyaxis hoursindays objectatindexintindex utf8string cgcontextshowtextatpointctx fltx118 flty218 arraydataforyaxis strlenarraydataforyaxis cgcontextstrokepathctx cgcontextsetrgbstrokecolorctx 20 20 20 10 cgcontextsetlinewidthctx 20 fltx1 5 flty1 250 fltx2 270 flty2 flty1 nsarray weekdays nsarray alloc initwithobjectssun mon tus wed thu fri sat nil dividing the xaxis cgcontextmovetopointctx fltx1 flty1 cgcontextaddlinetopointctx fltx2 flty2 float y 275 forint intindex 0 intindex weekdays count fltx133 intindex cgcontextsetrgbstrokecolorctx 20 20 20 10 cgcontextmovetopointctx fltx152 flty23 cgcontextaddlinetopointctx fltx152 flty23 cgcontextselectfontctx arial 150 kcgencodingmacroman cgcontextsettextdrawingmodectx kcgtextfill cgcontextsetrgbfillcolorctx 0 255 255 1 cgaffinetransform xform cgaffinetransformmake 10 00 00 10 00 00 cgcontextsettextmatrixctx xform const char arraydataforxaxis weekdays objectatindexintindex utf8string cgcontextshowtextatpointctx fltx137 flty218 arraydataforxaxis strlenarraydataforxaxis cgcontextstrokepathctx end,['iphone'] +55184,encryptdecrypt sqlitedatabase and use it on the fly heres the thingin my qt46project i use a sqlitedatabase this database should not be unencrypted on my harddrive so i want that on every start of my program the user gets asked to enter a password to decrypt the database of course the database never should appear in clear not encrypted on my harddriveso is there any possibility to decrypt a sqlitedatabase on the fly and read and write data what algorithm is here the best maybe aeswhen it is not possible or very slow maybe it is better to encrypt every string in the database and decrypt the string when the password was right so that a user could open the database but has no clue what all the entrys could mean,['c++'] +55187,what is the lightest way to make a huge chesslike grid i am working on a browsergame and i cannot help but wonder about whats the lightest way to make the gridboard on which the game takes placeright now as a mere sample i will show you thislink no longer active it was basically a 25x25 tabletrtd gridnow as the grid gets bigger and bigger the table and its tds create a very heavy filepage which in turnsucks in more resources from the browser engine and computerso is a table with tds the most lightweight way to craft a huge gridlike board or is there something lighter that you recommendcheerssotkra,['html'] +55191,why does enable shared from this have a nonvirtual destructor i have a pet project with which i experiment with new features of c11 while i have experience with c i am fairly new to c to train myself into best practices besides reading a lot i have enabled some strict compiler parameters using gcc 441stdc0x werror wall winline weffc pedanticerrorsthis has worked fine for me until now i have been able to resolve all obstacles however i have a need for enable shared from this and this is causing me problems i get the following warning error in my case when compiling my code probably triggered by weffcbase class aclass stdenable shared from thispackagea has a nonvirtual destructorso basically i am a bit bugged by this implementation of enable shared from this becausea destructor of a class that is intended for subclassing should always be virtual imhothe destructor is empty why have it at alli cannot imagine anyone would want to delete their instance by reference to enable shared from thisbut i am looking for ways to deal with this so my question is really is there a proper way to deal with this and am i correct in thinking that this destructor is bogus or is there a real purpose to it,['c++'] +55200,how to build a json response made up of multiple models in rails first the desired resulti have user and item models i would like to build a json response that looks like this user usernamebobfoowhateverbarhello items id1 nameone zimplanet girearth id2 nametwo zimplanet girmars however my user and item model have more attributes than just those i found a way to get this to work but beware it is not pretty please helpupdatethe next section contains the original question the last section shows the new solutionmy hackshome controllerrbclass homecontroller applicationcontroller def observe respond to do format formatjs render json observationnewcurrent user itemsto json end endendobservationrb note this is not a subclass of activerecordbase this class just serves as a container to aggregate all observable objectsclass observation attr accessor user items def initializeuser items selfuser user selfitems items end the json needs to be decoded before it is sent to the to json method in the home controller otherwise the json will be escaped what a mess def to json user activesupportjsondecodeuserto jsononly username methods foo bar items activesupportjsondecodeauctionsto jsononly id name methods zim gir endendlook ma no more hacksoverride as json insteadthe activerecordserializationas json docs are pretty sparse heres the brief as jsonoptions nil show sourcefor more information on to json vs as json see the accepted answer for overriding to json in rails 235the code sans hacksuserrbclass user activerecordbase def as jsonoptions options only username methods foo bar mergeoptions superoptions endenditemrbclass item activerecordbase def as jsonoptions options only id name methods zim gir mergeoptions superoptions endendhome controllerrbclass homecontroller applicationcontroller def observe items itemsfind respond to do format formatjs do render json user current user items items end end endend,['ruby-on-rails'] +55202,c system calls open read write close and o creato excl given the following code it is supposed to write helloworld in a helloworld file and then read the textinclude fcntlhinclude systypeshinclude sysstathdefine fname helloworldint main int filedes nbytes char buf128 creates a file iffiledesopenfname o creat o excl o wronly o append s irusr s iwusr 1 write2 error1n 7 writes hello world to file ifwritefiledes fname 10 10 write2 error2n 7 close file closefiledes iffiledes openfname o rdonly1 write2 error3n 7 prints file contents on screen ifnbytesreadfiledes buf 128 1 write2 error4n 7 ifwrite1 buf nbytes nbytes write2 error5n 7 close file after read closefiledes return 0the first time i run the program the output ishelloworldafter that every time i to run the program the output iserror1error2helloworldi do not understand why the text is not appended as i have specified the o append fileis it because i have included o creat it the file is already created should not o creat be ignored,['c'] +55222,httputilityurlencode in windows phone 7 the regular net framework contains httputilityurlencode in the systemweb assembly and in silverlight it appears it was moved to systemwindowsbrowser but in windows phone 7 which i thought was the same as silverlight i cannot seem to find a proper way to urlencode anything neither of the previously mentioned assemblies are available in the windows phone 7 environment,['c#'] +55224,when is nscopying needed i know it is needed if your object will be used as a key in an nsdictionary are there any other times like this that nscopying is requiredif i think i do not need my model objects to conform to nscopying am i probably wrong,['objective-c'] +55229,how to get a cell value in jqgrid how to get a cell value in jqgridif i use the following syntax avar ret jquerymygridjqgridgetrowdata idret retproductidit returns the following htmlinput classeditable name productid id0 productid stylewidth 98 typetexti actually need the value of the cellthanksdev,['jquery'] +55238,sorting a list of dot sparated numbers like software versions i have a list containing version strings such as thingsversions list 112 100 133 1012 102i would like to sort it so the result would be something like thisversions list 100 102 1012 112 133the order of precendece for the digits should obviously be from left to right and it should be descending so 123 comes before 223 and 2 comes before 223how do i do this in python,['python'] +55267,jquery mouseout problem div idparentdiv idchildcxdivdivwhen i use jquery parentmouseoutfunctionsomething herei wonder why when my mouse enter the child div the function fires i am still inside parent divi want that mouseout function to fire only when i leave the parent div not when i am on any child div examplecheers,['jquery'] +55277,python lookup hostname from ip with 1 second timeout how can i look up a hostname given an ip address furthermore how can i specify a timeout in case no such reverse dns entry exists trying to keep things as fast as possible or is there a better way thank you,['python'] +55282,entity framework lazy loading does not work from other thread i just found out that lazy loading in entity framework only works from the thread that created the objectcontext to illustrate the problem i did a simple test with a simple model containing just 2 entities person and address heres the code private static void testsinglethread using var context new testdbcontext foreach var p in contextperson consolewriteline0 lives in 1 pname paddresscity private static void testmultithread using var context new testdbcontext foreach var p in contextperson person p2 p to avoid capturing the loop variable threadpoolqueueuserworkitem arg consolewriteline0 lives in 1 p2name p2addresscity the testsinglethread method works fine the address property is lazily loaded but in testmultithread i get a nullreferenceexception on p2addresscity because p2address is nullit that a bug is this the way it is supposed to work if so is there any documentation mentioning it i could not find anything on the subject on msdn or googleand more importantly is there a workaround other than explicitly calling loadproperty from the worker threadany help would be very appreciatedps i am using vs2010 so it is ef 40 i do not know if it was the same in the previous version of ef,['c#'] +55297,c incompatible types in assignment problem with pointers hi i am working with c and i have a question about assigning pointers struct foo int bar char carsome number this is meant to be an array of char so that it can hold pointers to names of carsint foofunc void arg int bar char carsome number struct foo thing struct foo arg bar thing bar this works fine car thing car this gives compiler errors of incompatible types in assignmentcar and car have same declaration so why am i getting an error about incompatible types my guess is that it has something to do with them being pointers because they are pointers to arrays of char right but i do not see why that is a problemwhen i declared char car instead of char carmaxint it compiles fine but i do not see how that would be useful to me later when i need to access certain info using index it would be very annoying to access that info later in fact i am not even sure if i am going about the right way maybe there is a better way to store a bunch of strings instead of using array of char edit i did not mean to use int max maximum value of int it is just some other int which is about 20,['c'] +55299,how can i create a methodinfo from an action delegate i am trying to develop an nunit addin that dynamically adds test methods to a suite from an object that contains a list of action delegates the problem is that nunit appears to be leaning heavily on reflection to get the job done consequently it looks like there is no simple way to add my actions directly to the suitei must instead add methodinfo objects this would normally work but the action delegates are anonymous so i would have to build the types and methods to accomplish this i need to find an easier way to do this without resorting to using emit does anyone know how to easily create methodinfo instances from action delegates,"['c#', '.net']" +55300,how can join a query result set with an existing table is there any way to avoid using tmp tablei am using a query with aggregate function sum to generate the sum of each product the result looks like this product name sumqty product 1 100 product 2 200 product 5 300 now i want to join the above result to another table called products so that i will have a summary like this product name sumqty product 1 100 product 2 200 product 3 0 product 4 0 product 5 300 i know 1 way of doing this is the dump the 1st query result to a temp table then join it with products table is there a better way,"['sql', 'mysql']" +55302,what situations does a monostate pattern model i know what both a singleton or a monostate are and how to implement them although i can see many uses for a singleton i cannot imagine a situation where i would want to let the user create as many instances of my class although in reality only one really exists behind the scenescan anybody help me here i know that for several reasons one should stay away from both patterns but in theory what kind of problems does the monostate modelthanks,"['c#', 'java']" +55305,how to convert a dynamic dll to static lib i write a program helloworldexe it depends on adll i do not have the source code of the adll which is a dynamic dll how can i change it to static library so i can link it into helloworldexe,['c++'] +55318,select proper columns from join statement i have two tables table1 table2 table1 has 10 columns table2 has 2 columnsselect from table1 as t1 inner join table2 as t2 on t1id t2idi want to select all columns from table1 and only 1 column from table2 is it possible to do that without enumerating all columns from table1,['sql'] +55322,error starting modern compiler in my servlet i m using tomcat 50 and jre is 150 but it is giving error when i click on the url as when i created a war file of my project and deployed in tomcat than it is working fine it means that only problem with my eclipse configuration error is apr 5 2010 32022 pm orgapachejaspercompilercompiler generateclasevere javac exception error starting modern compiler at orgapachetoolsanttaskdefscompilersjavac13executejavac13java69 at orgapachetoolsanttaskdefsjavaccompilejavacjava942 at orgapachetoolsanttaskdefsjavacexecutejavacjava764 at orgapachejaspercompilercompilergenerateclasscompilerjava382 at orgapachejaspercompilercompilercompilecompilerjava472 at orgapachejaspercompilercompilercompilecompilerjava451 at orgapachejaspercompilercompilercompilecompilerjava439 at orgapachejasperjspcompilationcontextcompilejspcompilationcontextjava511 at orgapachejasperservletjspservletwrapperservicejspservletwrapperjava295 at orgapachejasperservletjspservletservicejspfilejspservletjava292 at orgapachejasperservletjspservletservicejspservletjava236 at javaxservlethttphttpservletservicehttpservletjava802 at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava237 at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava157 at orgapachecatalinacorestandardwrappervalveinvokestandardwrappervalvejava214 at orgapachecatalinacorestandardvalvecontextinvokenextstandardvalvecontextjava104 at orgapachecatalinacorestandardpipelineinvokestandardpipelinejava520 at orgapachecatalinacorestandardcontextvalveinvokeinternalstandardcontextvalvejava198 at orgapachecatalinacorestandardcontextvalveinvokestandardcontextvalvejava152 at orgapachecatalinacorestandardvalvecontextinvokenextstandardvalvecontextjava104 at orgapachecatalinacorestandardpipelineinvokestandardpipelinejava520 at orgapachecatalinacorestandardhostvalveinvokestandardhostvalvejava137 at orgapachecatalinacorestandardvalvecontextinvokenextstandardvalvecontextjava104 at orgapachecatalinavalveserrorreportvalveinvokeerrorreportvalvejava118 at orgapachecatalinacorestandardvalvecontextinvokenextstandardvalvecontextjava102 at orgapachecatalinacorestandardpipelineinvokestandardpipelinejava520 at orgapachecatalinacorestandardenginevalveinvokestandardenginevalvejava109 at orgapachecatalinacorestandardvalvecontextinvokenextstandardvalvecontextjava104 at orgapachecatalinacorestandardpipelineinvokestandardpipelinejava520 at orgapachecatalinacorecontainerbaseinvokecontainerbasejava929 at orgapachecoyotetomcat5coyoteadapterservicecoyoteadapterjava160 at orgapachecoyotehttp11http11processorprocesshttp11processorjava799 at orgapachecoyotehttp11http11protocolhttp11connectionhandlerprocessconnectionhttp11protocoljava705 at orgapachetomcatutilnettcpworkerthreadrunitpooltcpendpointjava577 at orgapachetomcatutilthreadsthreadpoolcontrolrunnablerunthreadpooljava683 at javalangthreadrununknown sourcecaused by javalangreflectinvocationtargetexception at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokeunknown source at sunreflectdelegatingmethodaccessorimplinvokeunknown source at javalangreflectmethodinvokeunknown source at orgapachetoolsanttaskdefscompilersjavac13executejavac13java61 35 morecaused by javalangverifyerror class comsuntoolsjavacjvmtarget overrides final method at javalangclassloaderdefineclass1native method at javalangclassloaderdefineclassunknown source at javasecuritysecureclassloaderdefineclassunknown source at orgapachecatalinaloaderwebappclassloaderfindclassinternalwebappclassloaderjava1634 at orgapachecatalinaloaderwebappclassloaderfindclasswebappclassloaderjava860 at orgapachecatalinaloaderwebappclassloaderloadclasswebappclassloaderjava1307 at orgapachecatalinaloaderwebappclassloaderloadclasswebappclassloaderjava1189 at javalangclassloaderloadclassinternalunknown source at comsuntoolsjavacmaincompilemainjava42 40 more nested exception javalangreflectinvocationtargetexception at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokeunknown source at sunreflectdelegatingmethodaccessorimplinvokeunknown source at javalangreflectmethodinvokeunknown source at orgapachetoolsanttaskdefscompilersjavac13executejavac13java61 at orgapachetoolsanttaskdefsjavaccompilejavacjava942 at orgapachetoolsanttaskdefsjavacexecutejavacjava764 at orgapachejaspercompilercompilergenerateclasscompilerjava382 at orgapachejaspercompilercompilercompilecompilerjava472 at orgapachejaspercompilercompilercompilecompilerjava451 at orgapachejaspercompilercompilercompilecompilerjava439 at orgapachejasperjspcompilationcontextcompilejspcompilationcontextjava511 at orgapachejasperservletjspservletwrapperservicejspservletwrapperjava295 at orgapachejasperservletjspservletservicejspfilejspservletjava292 at orgapachejasperservletjspservletservicejspservletjava236 at javaxservlethttphttpservletservicehttpservletjava802 at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava237 at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava157 at orgapachecatalinacorestandardwrappervalveinvokestandardwrappervalvejava214 at orgapachecatalinacorestandardvalvecontextinvokenextstandardvalvecontextjava104 at orgapachecatalinacorestandardpipelineinvokestandardpipelinejava520 at orgapachecatalinacorestandardcontextvalveinvokeinternalstandardcontextvalvejava198 at orgapachecatalinacorestandardcontextvalveinvokestandardcontextvalvejava152 at orgapachecatalinacorestandardvalvecontextinvokenextstandardvalvecontextjava104 at orgapachecatalinacorestandardpipelineinvokestandardpipelinejava520 at orgapachecatalinacorestandardhostvalveinvokestandardhostvalvejava137 at orgapachecatalinacorestandardvalvecontextinvokenextstandardvalvecontextjava104 at orgapachecatalinavalveserrorreportvalveinvokeerrorreportvalvejava118 at orgapachecatalinacorestandardvalvecontextinvokenextstandardvalvecontextjava102 at orgapachecatalinacorestandardpipelineinvokestandardpipelinejava520 at orgapachecatalinacorestandardenginevalveinvokestandardenginevalvejava109 at orgapachecatalinacorestandardvalvecontextinvokenextstandardvalvecontextjava104 at orgapachecatalinacorestandardpipelineinvokestandardpipelinejava520 at orgapachecatalinacorecontainerbaseinvokecontainerbasejava929 at orgapachecoyotetomcat5coyoteadapterservicecoyoteadapterjava160 at orgapachecoyotehttp11http11processorprocesshttp11processorjava799 at orgapachecoyotehttp11http11protocolhttp11connectionhandlerprocessconnectionhttp11protocoljava705 at orgapachetomcatutilnettcpworkerthreadrunitpooltcpendpointjava577 at orgapachetomcatutilthreadsthreadpoolcontrolrunnablerunthreadpooljava683 at javalangthreadrununknown sourcecaused by javalangverifyerror class comsuntoolsjavacjvmtarget overrides final method at javalangclassloaderdefineclass1native method at javalangclassloaderdefineclassunknown source at javasecuritysecureclassloaderdefineclassunknown source at orgapachecatalinaloaderwebappclassloaderfindclassinternalwebappclassloaderjava1634 at orgapachecatalinaloaderwebappclassloaderfindclasswebappclassloaderjava860 at orgapachecatalinaloaderwebappclassloaderloadclasswebappclassloaderjava1307 at orgapachecatalinaloaderwebappclassloaderloadclasswebappclassloaderjava1189 at javalangclassloaderloadclassinternalunknown source at comsuntoolsjavacmaincompilemainjava42 40 moreapr 5 2010 32022 pm orgapachejaspercompilercompiler generateclasevere env compile javafilenamedoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0workcatalinalocalhostsamplesaloniorgapachejsppageform jspjava classpathdoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinfclassesdoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibantlauncherjardoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibantjardoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibcommonscollections31jardoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibcommonsdbcp121jardoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibcommonseljardoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibcommonspool12jardoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibjaspercompilerjardoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibjasperruntimejardoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibjspapijardoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibnamingcommonjardoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibnamingfactoryjardoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibnamingjavajardoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibnamingresourcesjardoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibtoolsjardoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0workcatalinalocalhostsamplesalonidoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinfclassesdoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibantlauncherjardoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibantjardoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibcommonscollections31jardoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibcommonsdbcp121jardoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibcommonseljardoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibcommonspool12jardoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibjaspercompilerjardoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibjasperruntimejardoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibjspapijardoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibnamingcommonjardoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibnamingfactoryjardoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibnamingjavajardoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibnamingresourcesjardoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibtoolsjardsoftware setupsjakartatomcat5028commonclassesdsoftware setupsjakartatomcat5028commonlibantlauncherjardsoftware setupsjakartatomcat5028commonlibantjardsoftware setupsjakartatomcat5028commonlibcommonscollections31jardsoftware setupsjakartatomcat5028commonlibcommonsdbcp121jardsoftware setupsjakartatomcat5028commonlibcommonseljardsoftware setupsjakartatomcat5028commonlibcommonspool12jardsoftware setupsjakartatomcat5028commonlibjaspercompilerjardsoftware setupsjakartatomcat5028commonlibjasperruntimejardsoftware setupsjakartatomcat5028commonlibjspapijardsoftware setupsjakartatomcat5028commonlibnamingcommonjardsoftware setupsjakartatomcat5028commonlibnamingfactoryjardsoftware setupsjakartatomcat5028commonlibnamingjavajardsoftware setupsjakartatomcat5028commonlibnamingresourcesjardsoftware setupsjakartatomcat5028commonlibservletapijardsoftware setupsjakartatomcat5028commonlibtoolsjardsoftware20setupsjakartatomcat5028binbootstrapjarcprogram20filesjavajre150 09libextdnsnsjarcprogram20filesjavajre150 09libextsunjce providerjarcprogram20filesjavajre150 09libextsunpkcs11jar cpdsoftware setupsjakartatomcat5028binbootstrapjar cpdoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinfclasses cpdoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibantlauncherjar cpdoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibantjar cpdoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibcommonscollections31jar cpdoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibcommonsdbcp121jar cpdoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibcommonseljar cpdoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibcommonspool12jar cpdoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibjaspercompilerjar cpdoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibjasperruntimejar cpdoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibjspapijar cpdoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibnamingcommonjar cpdoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibnamingfactoryjar cpdoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibnamingjavajar cpdoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibnamingresourcesjar cpdoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibtoolsjar cpdoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0workcatalinalocalhostsamplesaloni cpdoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinfclasses cpdoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibantlauncherjar cpdoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibantjar cpdoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibcommonscollections31jar cpdoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibcommonsdbcp121jar cpdoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibcommonseljar cpdoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibcommonspool12jar cpdoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibjaspercompilerjar cpdoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibjasperruntimejar cpdoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibjspapijar cpdoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibnamingcommonjar cpdoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibnamingfactoryjar cpdoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibnamingjavajar cpdoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibnamingresourcesjar cpdoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0wtpwebappssamplesaloniwebinflibtoolsjar cpdsoftware setupsjakartatomcat5028commonclasses cpdsoftware setupsjakartatomcat5028commonlibantlauncherjar cpdsoftware setupsjakartatomcat5028commonlibantjar cpdsoftware setupsjakartatomcat5028commonlibcommonscollections31jar cpdsoftware setupsjakartatomcat5028commonlibcommonsdbcp121jar cpdsoftware setupsjakartatomcat5028commonlibcommonseljar cpdsoftware setupsjakartatomcat5028commonlibcommonspool12jar cpdsoftware setupsjakartatomcat5028commonlibjaspercompilerjar cpdsoftware setupsjakartatomcat5028commonlibjasperruntimejar cpdsoftware setupsjakartatomcat5028commonlibjspapijar cpdsoftware setupsjakartatomcat5028commonlibnamingcommonjar cpdsoftware setupsjakartatomcat5028commonlibnamingfactoryjar cpdsoftware setupsjakartatomcat5028commonlibnamingjavajar cpdsoftware setupsjakartatomcat5028commonlibnamingresourcesjar cpdsoftware setupsjakartatomcat5028commonlibservletapijar cpdsoftware setupsjakartatomcat5028commonlibtoolsjar cpdsoftware20setupsjakartatomcat5028binbootstrapjar cpcprogram20filesjavajre150 09libextdnsnsjar cpcprogram20filesjavajre150 09libextsunjce providerjar cpcprogram20filesjavajre150 09libextsunpkcs11jar work dirdoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0workcatalinalocalhostsamplesaloni extension dircprogram filesjavajre150 09libext srcdirdoffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0workcatalinalocalhostsamplesaloni includeorgapachejsppageform jspjavaapr 5 2010 32022 pm orgapachejaspercompilercompiler generateclasevere error compiling file doffvivjava ideworkspacemetadatapluginsorgeclipsewstservercoretmp0workcatalinalocalhostsamplesaloniorgapachejsppageform jspjava javac compiling 1 source file,['java'] +55329,render web page to picture i have the string with url for example is there are any way to download and render this page to picture file testjpgi tried to use webbrowser control to download and render picture but it only works when webbrowser placed in thisplayed form in other ways it is render only black rectangle but i want to render picture without any visual effect creating activating form etc,"['c#', '.net']" +55337,java jpa basic and embedded annotations i am learning jpa from this tutoriali have some confusions in understanding the following annotationsbasicembeddedfields of an embeddable type default to persistent as if annotated with embeddedif the fields of embeddable types default to persistent then why would we need the embedded annotation,['java'] +55338,php frameworks codeigniter yii cakephp vs django i have to develop a site which has to accomodate around 20 users a day and speed is a criterion for it moreover the site is a user oriented one where the user will be able to log in and check his profile register for specific events heshe wants to participate in the site is to be hosted on a vps serveralthough i have pretty good experience with python and php but i have no idea how to use either of the framework we have plenty of time to experiment and learn one of the above frameworkscould you please specify which one would be preferred for such a scenario considering speed features and security of the site thanksniting,['python'] +55340,multiple classes with same methods best pattern i have a few classes in my current project where validation of emailwebsite addresses is necessary the methods to do that are all the same i wondered whats the best way to implement this so i do not need to have these methods copy pasted everywherethe classes themselves are not necessarily related they only have those validation methods in common,['c#'] +55341,decoupling the view presentation and aspnet web forms i have an aspnet web forms page which the presenter needs to populate with controls this interaction is somewhat sensitive to the pagelife cycle and i was wondering if there is a trick to it that i do not know abouti wanna be practical about the whole thing but not compromise testabilitycurrently i have thispublic interface isomecontract void instantiateinsystemwebuicontrol container this contract has a dependency on systemwebuicontrol and i need that to be able to do things with the aspnet web forms programming model but neither the view nor the presenter may have knowledge about aspnet server controlshow do i get around this how can i work with the aspnet web forms programming model in my concrete views without taking a systemwebuicontrol dependency in my contract assembliesto clarify things a bit this type of interface is all about ui composition using mef it is known throughout the framework but it is really only called from within the concrete view the concrete view is still the only thing that knows about aspnet web forms however those public methods that say instantiateinsystemwebuicontrol exists in my contract assemblies and that implies a dependency on aspnet web formsi have been thinking about some double thispatch mechanism or even visitor pattern to try and work around this but i do not yet know in which direction i want to go and i would really like some input on the matter,"['c#', 'asp.net']" +55343,what is the best way to convert a zope datetime object into python datetime object i need to convert a zope 2 datetime object into a python datetime object what is the best way to do that thanks erika,['python'] +55346,how do i make a uialertview appear only once at the first startup of an iphone app i am using the uialertview to make a popup happen once the app has started up it works fine but i only want the pop up to appear on the first startup of the app at the moment i have got the uialertview in the appdelegate class in applicationdidfinishlaunching method here is my code boolapplicationuiapplication application didfinishlaunchingwithoptionsnsdictionary launchoptions sleep4uialertview alert uialertview alloc initwithtitlewelcome messagesample delegatenil cancelbuttontitleok otherbuttontitlesnilalert showalert releasei am new to app development so sorry if this is simple,['iphone'] +55347,how do i backup and restore the system clipboard in c i will do my best to explain in detail what i am trying to achieve i am using c with intptr window handles to perform a ctrlc copy operation on an external application from my own c application i had to do this because there was no way of accessing the text directly using get text i am then using the text content of that copy within my application the problem here is that i have now overwritten the clipboardwhat i would like to be able to do isbackup the original contents of the clipboard which could have been set by any application other than my ownthen perform the copy and store the value into my applicationthen restore the original contents of the clipboard so that the user still has access to hisher original clipboard datathis is the code i have tried so farprivate void getclipboardtext text idataobject backupclipboad clipboardgetdataobject keyboardinput input new keyboardinputthis inputcopydialoghandle performs a ctrlc copy operation idataobject clipboard clipboardgetdataobject if clipboardgetdatapresentdataformatstext retrieves the text from the clipboard text clipboardgetdatadataformatstext as string if backupclipboad null clipboardsetdataobjectbackupclipboad true throws exception i am using the systemwindowsclipboard and not the systemwindowsformsclipboard the reason for this was that when i performed the ctrlc the clipboard class from systemwindowsforms did not return any data but the system clipboard didi looked into some of the low level user32 calls like openclipboard emptyclipboard and closeclipboard hoping that they would help my do this but so far i keep getting com exceptions when trying to restore i thought perhaps this had to do with the openclipboard parameter which is expecting an intptr window handle of the application which wants to take control of the clipboard since i mentioned that my application does not have a gui this is a challenge i was not sure what to pass here maybe someone can shed some light on thatam i using the clipboard class incorrectly is there a clear way to obtain the intptr window handle of an application with no gui does anyone know of a better way to backup and restore the system clipboard,['c#'] +55357,signedness of enum in cc99ccxgnu cgnu c99 is enum type signed or unsigned is the signedness of enums differ in cc99ansi cxgnu c gnu c99thanks,"['c++', 'c']" +55369,do you use the getset pattern in python using getset seems to be a common practice in java for various reasons but i hardly see python code that uses thiswhy do you use or avoid getset methods in python,['python'] +55377,listview with images and text whats the way to create a listview with images on the left side and text right after itnote the images were previously downloaded from the netthanks in advance,['android'] +55389,does a cc compiler optimize constant divisions by poweroftwo value into shifts question says it all does anyone know if the followingsize t divsize t value const size t x 64 return value xis optimized intosize t divsize t value return value 6do compilers do this my interest lies in gcc are there situations where it does and others where it does noti would really like to know because every time i write a division that could be optimized like this i spend some mental energy wondering about whether precious nothings of a second is wasted doing a division where a shift would suffice,"['c++', 'c']" +55394,why are my rails tests so slow is it normal for my test suite to take 5 seconds just to launch even when running an empty suite it still takes this long is it because it is firing up a new instance of rails on each run if so is there anyway to keep it persistentexamplerlepidirlepidiprojectsrailsmy project time rake testusrbinruby191 ilibtest varlibgems191gemsrake087librakerake test loaderrb testunitrelease testrb loaded suite varlibgems191gemsrake087librakerake test loaderstartedfinished in 0181867 seconds0 tests 0 assertions 0 failures 0 errors 0 pendings 0 omissions 0 notifications0 passedreal 0m4173suser 0m3820ssys 0m0288sas you can see this empty test is really fast but there is still 4 seconds of overhead for some reason i am using testunit with shoulda,['ruby-on-rails'] +55420,nhibernate transaction management in aspnet mvc how should it be done i am writing a simple aspnet mvc using session per request and transaction per request patterns custom httpmoduleit seems to work properly but the performance is terrible a simple page loads 7 seconds for every http request graphical resources incuding all images on the site a transaction is created and that seems to delay the loading times without the transactions loading times per one image are 110 ms with transactions they are over 1 secondwhat is the proper way to manage transactions in aspnet mvc nh stackwhen i have put all transactions into my repository methods for some obscure reasons i got implicit transactions warning in nhprof the sql statements were executed outside transaction even that in code sessionsaveupdateetc methods were invoked within transaction using scope and before transactioncommit call btw are implicit transactions really bad,['asp.net'] +55448,python mechanize select a form with no name i am attempting to have mechanize select a form from a page but the form in question has no name attribute in the html what should i do when i try to usebrselect formname i get errors that no form is declared with that name and the function requires a name input there is only one form on the page is there some other way i can select that form,"['python', 'html']" +55454,android passing parameters between classes i have a class2 which is involved by class1 when clicks are made i have to pass some parametersobjects from class1 to class2 i only know the standard way which does not have an option of passing parameters launch the full articleintent i new intentthis class2clastartactivityi,['android'] +55462,how often do you create implicit conversions for your classes i have been developing net applications for 4 years so far i did not need to create any implicit conversions for the classes i authoredcould you provide reallife situations when you could not do without creating implicit conversionsthank you,['.net'] +55476,dynamically create class attributes i need to dynamically create class attributes from a defaults dictionarydefaults default value1true default value2true default value3trueclass settingsobject default value1 some complex init functiondefaultsdefault value1 default value2 some complex init functiondefaultsdefault value2 default value3 some complex init functiondefaultsdefault value3 i could also achive this by having sth like init for class creation in order to dynamically create these attributes from dictionary and save a lot of code and stupid workhow would you do thisthank you very much in advance,['python'] +55480,how to deploy a visual studio custom tool i have a my own custom tool for visual studio 2008 sp1 it consists of 5 assemblies 3 assemblies with code that used heavily in my other projects 1 assemblywrapper above vs2008 sdk and assembly with the toolif i would debug my tool from visual studio using run external program option with command line cprogram files x86microsoft visual studio 90common7idedevenvexe and arguments ranu rootsuffix exp all work perfectlyafter that i trying to deploy it to my working vs copy not to experimental hive doing gacutil i asm1dll for all my assemblies and doing regasm asm1dll only for assembly with custom tool neither of utils prints any error all work as planned even registry keys appeared but my tool do not work error occured cannot find custom tool transportgeneratortool on this system even after pc restart what did i do wrongwrapper looks like thatcomvisibletruepublic abstract class customtoolbase ivssinglefilegenerator iobjectwithsite region ivssinglefilegenerator members int ivssinglefilegeneratordefaultextensionout string pbstrdefaultextension pbstrdefaultextension cs return 0 int ivssinglefilegeneratorgeneratestring wszinputfilepath string bstrinputfilecontents string wszdefaultnamespace intptr rgboutputfilecontents out uint pcboutput ivsgeneratorprogress pgenerateprogress generationeventargs gea new generationeventargs bstrinputfilecontents wszinputfilepath wszdefaultnamespace new serviceprovidersite as microsoftvisualstudiooleinteropiserviceprovider getservicetypeofprojectitem as projectitem new generationprogressfacadepgenerateprogress if ongeneratecode null ongeneratecodethis gea byte bytes geagetoutputcodebytes int outputlength byteslength rgboutputfilecontents0 marshalalloccotaskmemoutputlength marshalcopybytes 0 rgboutputfilecontents0 outputlength pcboutput uintoutputlength return vsconstantss ok endregion region iobjectwithsite members void iobjectwithsitegetsiteref guid riid out intptr ppvsite intptr punk marshalgetiunknownforobjectsite intptr intpointer intptrzero marshalqueryinterfacepunk ref riid out intpointer ppvsite intpointer void iobjectwithsitesetsiteobject punksite site punksite endregion region public members public object site get private set public event eventhandlergenerationeventargs ongeneratecode comregisterfunction public static void registertype type using var parent registrylocalmachineopensubkeysoftwaremicrosoftvisualstudio90 true foreach customtoolregistrationattribute ourdata in typegetcustomattributestypeofcustomtoolregistrationattribute false ourdataregisterx parentcreatesubkeyx x name value xsetvaluename value comunregisterfunction public static void unregistertype type using var parent registrylocalmachineopensubkeysoftwaremicrosoftvisualstudio90 true foreach customtoolregistrationattribute ourdata in typegetcustomattributestypeofcustomtoolregistrationattribute false ourdataunregisterx parentdeletesubkeyx false endregionmy tool codecomvisibletrueguid55a6c192d29f4e2284dadbaf314ed5c3customtoolregistrationtoolname typeoftransportgeneratortoolprovideobjecttypeoftransportgeneratortoolpublic class transportgeneratortool customtoolbase private const string toolname transportgeneratortool public transportgeneratortool ongeneratecode generatecode private static void generatecodeobject s generationeventargs e try var serializer new xmlserializertypeof parsersystem using var reader new stringreadereinputtext using var writer new stringwritereoutputcode generatorsystem parsersystem serializerdeserializereader generatorsystemnamespace enamespace generatorgeneratesourcewriter catch exception ex eprogressgenerateerrorextostring resulting registry keyswindows registry editor version 500hkey local machinesoftwaremicrosoftvisualstudio90generatorshkey local machinesoftwaremicrosoftvisualstudio90generatorsfae04ec1301f11d3bf4b00c04f79efbchkey local machinesoftwaremicrosoftvisualstudio90generatorsfae04ec1301f11d3bf4b00c04f79efbctransportgeneratortooltransportgeneratortoolclsid55a6c192d29f4e2284dadbaf314ed5c3generatesdesigntimesourcedword01generatesshareddesigntimesourcedword01here is code of my custom attribute it is in wrapper assemblyattributeusageattributetargetsclass allowmultiple true inherited truepublic class customtoolregistrationattribute registrationattribute public customtoolregistrationattributestring name type customtooltype name name customtooltype customtooltype summary the type that implements the custom tool this starts as mycustomtool by default in the template summary public type customtooltype get set public string name get set region registrationattribute abstract member implementations public override void registerregistrationcontext context registerx contextcreatekeyx x key value xsetvaluekey value public void registertfuncstring t keycreator actiont string object valuecreator var keyname createkeynamename var key keycreatorkeyname valuecreatorkey stringempty name valuecreatorkey clsid customtooltypeguidtostringb valuecreatorkey generatesdesigntimesource 1 valuecreatorkey generatesshareddesigntimesource 1 var thisposable key as ithisposable if thisposable null thisposablethispose private static string createkeynamestring name return stringformatgenerators01 vscontextguidsvscontextguidvcsproject name public override void unregisterregistrationcontext context unregistercontextremovekey public void unregisteractionstring keyremover keyremovercreatekeynamename endregion,['c#'] +55483,private iphone app without app store i am developing an iphone app for a private company it contains business critical data and should only be able to use for this companydo i still need to go via the app store is there not a private way to do this,['iphone'] +55503,easiest way to remove keys from a 2d array i have an array that looks like thisarray 0 array key1 a key2 b key3 c 1 array key1 c key2 b key3 a i need a function to get an array containing just a variable number of keys ie reduce arrayarraykey1 key3 should returnarray 0 array key1 a key3 c 1 array key1 c key3 a what is the easiest way to do this if possible without any additional helper function like array filter or array map as my coworkers already complain about me using too many functionsthe source array will always have the given keys so it is not required to check for existancebonus points if the values are unique the keys will always be related to each other meaning that if key1 has value a then the other keys will always have value bmy current solution which works but is quite clumsy even the name is horrible but cannot find a better onefunction get unique values from array by keysarray array array keys result array found array if countkeys 0 foreach array as item if in arrayitemkeys0 found continue array pushfound itemkeys0 result item array foreach keys as key result itemkey itemkey array pushresult result item return resultadditionphp version is 516,['php'] +55514,how to avoid black screen on starting an application when i start my application initially i get a black screen which stays for a few seconds before my main activity starts in case of iphone an image with name default is thisplayed for that split second i am not sure how to do the same in android i tried as below in vain activity androidnameindex androidlabelstringapp name androidscreenorientationportrait androidthemedrawabledefaultimage intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity,['android'] +55537,is catching a null pointer exception a code smell recently a coworker of mine wrote in some code to catch a null pointer exception around an entire method and return a single result i pointed out how there could have been any number of reasons for the null pointer so we changed it to a defensive check for the one resulthowever catching nullpointerexception just seemed wrong to me in my mind null pointer exceptions are the result of bad code and not to be an expected exception in the systemare there any cases where it makes sense to catch a null pointer exception,['java'] +55561,javascript trycatch errors or exceptions ok i may be splitting hairs here but my code is not consistent and i would like to make it so but before i do i want to make sure i am going the right way in practice this does not matter but this has been bothering me for a while so i figured i would ask my peersevery time i use a try catch statement in the catch block i always log a message to my internal console however my log messages are not consistent they either look likecatcherr dftoolsconsolelogsomemethod caught an error errmessageorcatchex dftoolsconsolelogsomemethod caught an exception exmessageobviously the code functions properly either way but it is starting to bother me that i sometimes refer to errors and sometimes to exceptions like i said maybe i am splitting hairs but which is the proper terminology exception or error,['javascript'] +55582,simplify my jquery code which is growing huge and redundant i am no jquery expert but i am learning i am using a bit growing to a lot of jquery to hide some images and show a single image when a thumb is clicked while this bit of jquery works it is horribly inefficient but i am unsure of how to simplify this to something that works on more of a universal levelscriptdocumentreadyfunction changing the materialsashirtredclickfunction selectmaterials imgremoveclassvisible imgselectshirtredaddclassvisibleashirtgreyclickfunction selectmaterials imgremoveclassvisible imgselectshirtgreyaddclassvisibleashirtgreenclickfunction selectmaterials imgremoveclassvisible imgselectshirtgreenaddclassvisibleashirtblueclickfunction selectmaterials imgremoveclassvisible imgselectshirtblueaddclassvisible changing the collarsacollarredclickfunction selectcollar imgremoveclassvisible imgselectcollarredaddclassvisibleacollargreyclickfunction selectcollar imgremoveclassvisible imgselectcollargreyaddclassvisibleacollargreenclickfunction selectcollar imgremoveclassvisible imgselectcollargreenaddclassvisibleacollarblueclickfunction selectcollar imgremoveclassvisible imgselectcollarblueaddclassvisible changing the cuffsacuffredclickfunction selectcuff imgremoveclassvisible imgselectcuffredaddclassvisibleacuffgreyclickfunction selectcuff imgremoveclassvisible imgselectcuffgreyaddclassvisibleacuffblueclickfunction selectcuff imgremoveclassvisible imgselectcuffblueaddclassvisibleacuffgreenclickfunction selectcuff imgremoveclassvisible imgselectcuffgreenaddclassvisible changing the pocketsapocketredclickfunction selectpocket imgremoveclassvisible imgselectpocketredaddclassvisibleapocketgreyclickfunction selectpocket imgremoveclassvisible imgselectpocketgreyaddclassvisibleapocketblueclickfunction selectpocket imgremoveclassvisible imgselectpocketblueaddclassvisibleapocketgreenclickfunction selectpocket imgremoveclassvisible imgselectpocketgreenaddclassvisiblescrip thumbnails which can be clicked on to toggle the larger preview image div classmaterials a hrefjavascript idshirtgreyimg srcgrey shirtpng height122 width122 a a hrefjavascript idshirtredimg srcred shirtpng height122 width122 a a hrefjavascript idshirtblueimg srchblue shirtpng height122 width122 a a hrefjavascript idshirtgreenimg srcgreen shirtpng height122 width122 a div div classcollars a hrefjavascript idcollargreyimg srcgrey collarpng height122 width122 a a hrefjavascript idcollarredimg srcred collarpng height122 width122 a a hrefjavascript idcollarblueimg srcblue collarpng height122 width122 a a hrefjavascript idcollargreenimg srcgreen collarpng height122 width122 a div div classcuffs a hrefjavascript idcuffgreyimg srcgrey cuffpng height122 width122 a a hrefjavascript idcuffredimg srcred cuffpng height122 width122 a a hrefjavascript idcuffblueimg srcblue cuffpng height122 width122 a a hrefjavascript idcuffgreenimg srcgreen cuffpng height122 width122 a div div classpockets a hrefjavascript idpocketgreyimg srcgrey pocketpng height122 width122 a a hrefjavascript idpocketredimg srcpng height122 width122 a a hrefjavascript idpocketblueimg srcblue pocketpng height122 width122 a a hrefjavascript idpocketgreenimg srcgreen pocketpng height122 width122 a div the larger images where one from each set should be viewable at one time triggered by the thumb clicked above div claselectionimg div idselectshirt img srcgrey shirtpng height250 width250 claselectshirtgrey show img srcred shirtpng height250 width250 claselectshirtred hide img srcblue shirtpng height250 width250 claselectshirtblue hide img srcgreen shirtpng height250 width250 claselectshirtgreen hide div div idselectcollar img srcgrey collarpng height250 width250 claselectcollargrey show img srcred collarpng height250 width250 claselectcollarred hide img srcblue collarpng height250 width250 claselectcollarblue hide img srcgreen collarpng height250 width250 claselectcollargreen hide div div idselectcuff img srcgrey cuffpng height250 width250 claselectcuffgrey show img srcred cuffpng height250 width250 claselectcuffred hide img srcblue cuffpng height250 width250 claselectcuffblue hide img srcgreen cuffpng height250 width250 claselectcuffgreen hide div div idselectpocket img srcgrey pocketpng height250 width250 claselectpocketgrey show img srchred pocketpng height250 width250 claselectpocketred hide img srcblue pocketpng height250 width250 claselectpocketblue hide img srcgreen pocketpng height250 width250 claselectpocketgreen hide div div,"['javascript', 'jquery']" +55612,how can i remove all words that end in from a string in python i am wondering how to remove a dynamic word from a string within pythonit will always have a at the end of the word and sometimes there is more than one within the string i would like to remove all occurrences of wordthanks,['python'] +55621,relative path to absolute path in vbnet i am writing a vbnet console application where it takes relative paths and spits out all file names or an error for invalid input i am having trouble getting physicalpath from relative pathexamplei am in folder cdocuments and settingsmehdianisultimatebanglamy documentsvisual studio 2005projectssp solsp projbindebugmy application spexe is also in the same folderi run spexe the output will be a list of all files in the folder cdocuments and settingsmehdianisultimatebanglamy documentsvisual studio 2005projectssp solsp projbini run spexe the output will be a list of all files in the folder cdocuments and settingsmehdianisultimatebanglamy documentsvisual studio 2005projectssp solsp proji run spexe the output will be a list of all files in the folder cdocuments and settingsmehdianisultimatebanglamy documentsvisual studio 2005projectssp solcurrently i am handling one relative path but no more if sourceindexof 0 then dim sibling as string directorygetparentdirectorygetcurrentdirectorytostring source sourcereplace sibling end ifhow can i easily handle multiple,['.net'] +55628,creating a method that is simultaneously an instance and class method in python i would like to be able to create a function that behaves both as a class function and an instance method but with the ability to change behaviors the use case for this is for a set of serializable objects and types as an example class thingobject thingto jsona thingto jsonbi know that given the definition of classmethod in funcobjectc in the python source this looks like it would be simple with a c module is there a way to do this from within pythonthankswith the hint of descriptors i was able to do it with the following codeclass combomethodobject def init self method selfmethod method def get self objnone objtypenone functoolswrapsselfmethod def wrapperargs kwargs if obj is not none return selfmethodobj args kwargs else return selfmethodobjtype args kwargs return wrapperthank you alex,['python'] +55634,uisplitviewcontroller remove divider line when using uisplitviewcontroller on the ipad there is a black vertical divider line between the root and detail view is there any way to remove this linethanks,['objective-c'] +55645,can i use boostmake shared with a private constructor consider the followingclass directoryiteratornamespace detail class filedataproxy class directoryiteratorimpl friend class directoryiterator friend class filedataproxy win32 find dataw currentdata handle hfind stdwstring root directoryiteratorimpl explicit directoryiteratorimplconst stdwstring pathspec void increment bool equalconst directoryiteratorimpl other const public directoryiteratorimpl class filedataproxy serves as a proxy to the win32 find data struture inside the iterator friend class directoryiterator boostshared ptrdirectoryiteratorimpl iteratorsource filedataproxyboostshared ptrdirectoryiteratorimpl parent iteratorsourceparent public stdwstring getfolderpath const return iteratorsourceroot class directoryiterator public boostiterator facadedirectoryiterator detailfiledataproxy stdinput iterator tag friend class boostiterator core access boostshared ptrdetaildirectoryiteratorimpl impl void increment implincrement bool equalconst directoryiterator other const return implequalotherimpl detailfiledataproxy dereference const return detailfiledataproxyimpl public directoryiterator impl boostmake shareddetaildirectoryiteratorimpl it seems like directoryiterator should be able to call boostmake shareddirectoryiteratorimpl because it is a friend of directoryiteratorimpl however this code fails to compile because the constructor for directoryiteratorimpl is privatesince this class is an internal implementation detail that clients of directoryiterator should never touch it would be nice if i could keep the constructor privateis this my fundamental misunderstanding around make shared or do i need to mark some sort of boost piece as friend in order for the call to compile,['c++'] +55649,how do i remove those rotation artefacts from my catiledlayer i have a catiledlayer into which i render content in the following method voiddrawlayercalayer layer incontextcgcontextrefctxi used the quartzdemo code to draw a pattern this works very well until i apply a rotation transform to the layers parentlayer a uiviewrotatedthese zigzag artefacts become worse when i start drawing lines and texts into the catiledlayeri applied the transform as follows i also tried using an affine transform on the view itselfselfcontainerviewlayertransform catransform3dmakerotationangleradians 00f 00f 10fi transform the containerview rather than the layer itself as i have several layers in that view that i would like to rotate at the same time without changing the relative positionsi did not have problems when rotating uiimageviews in the pastis there a way that i can rotate the catiledlayer without these problemsany help would be greatly appreciatedyoursfelix,['iphone'] +55653,why cannot a class variable be passed to instanceof could anyone tell me why this code would not compile public boolean isofclass clazz object obj ifobj instanceof clazz return true else return false why i cannot pass a class variable to instanceofthanks in advance,['java'] +55660,is there a way to use template specialization to separate new from new i have an auto pointer class and in the constructor i am passing in a pointer i want to be able to separate new from new in the constructor so that i can properly call delete or delete in the destructor can this be done through template specialization i do not want to have to pass in a boolean in the constructor template typename t class myautoptr public myautoptrt aptr in usemyautoptrint ptrnew intmyautoptrint ptr2new int10,['c++'] +55664,parsing multibyte string in php i would like to write a html parser based on state machine but i have doubts how to acctually readuse an input i decided to load the whole input into one string and then work with it as with an array and hold its index as current parsing positionthere would be no problems with singlebyte encoding but in multibyte encoding each value does not represent a character but a byte of a characterexamplemb string a34a 4 multibyte characters in utf8fori0 i 4 i echo mb stringi php eoloutputsa1a34a1athis means i cannot iterate through the string in a loop to check single characters because i never know if i am in the middle of an character or notso the questions are how do i multibyte safe read asingle character from a string in aperformance friendly wayis it good idea to work with thestring as it was an array in thiscasehow would you read the input,['php'] +55690,can i force the android back button to go two steps back in the activity stack i know that i can override the onkeydown method but i want back to do it is thing just twice,['android'] +55694,commenting c code header and source files i am looking for a best practice to document my c code like in any project i have some header files h and the respective source file cin the header file what kind of comment you put in and in source filesthe question arise up because since i commented well my header files the c files looks like a messwhats your best practices in keeping the code well commented,['c'] +55696,how to create context menu using xml file i am using xml file for creating context menu for my listview please see below i also want to set a header for this context menu i read at that i can use menusetheadertitlemycontextmenutitle in oncreatecontextmenu method but i need to set this in xml file how can i accomplish thisfollowing is code for oncreatecontextmenu method correct me if i am doing anything wrongthis is my context menuxml filexml version10 encodingutf8menu xmlnsandroid item androidididopen androidtitleopenmenuthis is my oncreatecontextmenu methodoverridepublic void oncreatecontextmenucontextmenu menu view v contextmenuinfo menuinfo menuinflater inflater getmenuinflater inflaterinflatermenucontext menu menu superoncreatecontextmenumenu v menuinfo this is my oncreate methodoverride public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain extras getintentgetextras registerforcontextmenugetlistview,['android'] +55702,use jquery to show a div only when scroll position is between 2 points i am trying to work out how to get a div tips to appear when the user scrolls into the 2nd quarter of its containing divs height wrap and then have it thisappear when the user scrolls into the last quarter so it would be like this1st quarter tips is hidden 2nd quarter tips is visible 3rd quarter tips is visible 4th quarter tips is hidden i am almost completely new to jquery but what i have got so far is thisfunction addkeyboardnavigation get the height of wrap var wrapheight wrapouterheight get 14 of wrapheight var quarterwrapheight wrapheight4 get 34 of wrapheight var threequarterswrapheight 3wrapheight check if were over a quarter down the page if windowscrolltop quarterwrapheight if we are show keyboardtips tipsfadeinslow this is where i get confused how can i check if the scroll position is quarterwrapheight but threequarterswrapheightto make it run i have been using run addkeyboardnavigation on scrollwindowscrollfunction addkeyboardnavigationany help or suggestions would be greatly appreciatedthanks,['jquery'] +55706,how do i prevent sql injection with coldfusion how do i prevent sql injection when it comes to coldfusion i am quite new to the languageframeworkhere is my example querycfquery namersrecord datasourcedatasource select from table where id urlidcfqueryi see passing in urlid as a risk,['sql'] +55725,representing sparse data in postgresql whats the best way to represent a sparse data matrix in postgresql the two obvious methods i see arestore data in a single a table with a separate column for every conceivable feature potentially millions but with a default value of null for unused features this is conceptually very simple but i know that with most rdms implementations that this is typically very inefficient since the null values ususually takes up some space however i read an article cannot find its link unfortunately that claimed pg does not take up data for null values making it better suited for storing sparse datacreate separate row and column tables as well as an intermediate table to link them and store the value for the column at that row i believe this is the more traditional rdms solution but there is more complexity and overhead associated with iti also found postgredynamic which claims to better support sparse data but i do not want to switch my entire database server to a pg fork just for this featureare there any other solutions which one should i use,['sql'] +55754,extension methods not recognized what is necessary to have an extension method honored when it exists in an imported assembly i built one in a class library project but it is not recognized in my web project which references the library all the other classes and methods in the library are honored and visible but this extension method is not the extension method is visible when used within the library,['c#'] +55762,how to write a shell in python i have written a small console application that can perform certain tasks the user interface is similar to things like version control systems or yum etc so basically you can think of it as a domain specific language now i would like to write a bash like shell that can execute and autocomplete this language and has a command history so i do not have to load and save the quite large xml files on each command in a nutshell i want something like ipython but not for executing python code but my own dslare there any libraries that help me doing this i see that there is a readline and rlcompleter module in python but its documentation seems to indicate that this is only for use with the python shell itself or did i miss something there,['python'] +55766,removing nonbreaking spaces from strings using python i am having some trouble with a very basic string issue in python that i cannot figure out basically i am trying to do the following read file into a string mystring fileread attempt to remove non breaking spaces mystring mystringreplaceu00a0 however when i print my string to output to console i get foo c2a0 bari thought that the u00a0 was the escape code for unicode non breaking spaces but apparently i am not doing this properly any ideas on what i am doing wrong,['python'] +55770,behavior of object in set operations i am trying to create a custom object that behaves properly in set operationsi have generally got it working but i want to make sure i fully understand the implications in particular i am interested in the behavior when there is additional data in the object that is not included in the equal hash methods it seems that in the intersection operation it returns the set of objects that are being compared to where the union operations returns the set of objects that are being comparedto illustrateclass myobject def init selfvaluemeta selfvalue value selfmeta meta def eq selfother return selfvalue othervalue def hash self return hashselfvaluea myobject1leftb myobject1rightc myobject2leftd myobject2righte myobject3leftprint a b trueprint a c falsefor i in setaceintersectionsetbd print s s ivalueimetareturns1 right2 right for i in setaceunionsetbd print s s ivalueimetareturns1 left3 left2 leftis this behavior documented somewhere and deterministic if so what is the governing principle,['python'] +55772,best practice to implement secure remember me sometimes i come across certain web development frameworks which do not provide an authentication feature such as in authentication aspneti was wondering what security measures need to be considered when implementing remember me login features by hand codinghere are the things i usually dostore the user name in cookie the user name is not encryptedstore a secret key in a cookie the secret key is generated using one way function based on user name the server will verify secret key against user name to ensure this user name is not being changeduse httponly in cookie anything else i have missed which could possibly lead a security holes,['asp.net'] +55782,how to dynamically replace a method implementation in objc2 i am trying to learn how to write plugins using simbl i got my plugin to load with the target application and also know the method that i wish to override however i am not able to use class getinstancemethod correctly based on snippets on the internet have things changed in osx 106 andor objc2the following code from culaternet gives dereferencing pointer to incomplete type on the secondlast statementbool dtrenameselectorclass class sel oldselector sel newselector method method nil first look for the methods method class getinstancemethod class oldselector if method nil return no methodmethod name newselector return yesis there a complete example of how to override a method using simbl plugins thanks,['objective-c'] +55783,how can i set transferencoding to chunked explicitly or implicitly in an aspnet response can i simply set the transferencoding header will calling responseflush at some point cause this to occur implicitly editno i cannot call responseheadersaddtransferencodinganything that throws any other suggestionsrelatedenable chunked transfer encoding in aspnet,['asp.net'] +55785,can you make aspnet mvc view wireup compile time safe take the standard return statement for a controllerreturn viewindexis there a way to make this thing compile time safe using static reflection or some other trick,"['c#', '.net']" +55788,calendargetinstance or calendarclone i need to make a copy of a given date 100s of times i cannot passbyreference i am wondering which of the below two are better optionsnewtimecalendargetinstancesettimeoriginaldateornewtimeoriginaldatecloneperformance is of main conern herethx,['java'] +55789,persist an object that is not marked as serializable i need to persist an object that is not marked with the serializable attribute the object is from a 3rd party library which i cannot changei need to store it in a persist place like for example the file system so the optimal solution would be to serialize the object to a file but since it is not marked as serializable that is not a straight forward solution it is a pretty complex object which also holds a collection of other objectsdo you guys have any input on how to solve this the code will never run in a production environment so i am ok with almost any solution and performance,"['c#', '.net']" +55792,exposing an iso c class to c i need to expose some c classes to c i am building on linux using mono so com is not an optionthe evidence i have gathered so far suggests that the best way to approach this iswrite a wrapper cnet class around the iso c classconsume the cnet classes from ci have the following questionsfirst is this the best way of achieving the goal of exposing iso c classes to c so far though i have not seen any examples that actually show how to do this can anyone suggest some links or a code snippet to show how this is done for a dummy classhow may i send asynchronous message notifications from the c code to the c code ideally i would like to cause the c class to raise an event with the received data as an argument,"['c#', 'c++']" +55799,pdo prepare silently fails i am experimenting with phps session set save handler and i would like to use a pdo connection to store session datai have this function as a callback for write actionsfunction writeid data logger write id data try access time sql replace into sessions set idid accessaccess datadata loggerthis is the last line in this function that appears in the log stmt globalsdbpreparesql loggerthis never gets logged stmtbindparamid id pdoparam str stmtbindparamaccess access pdoparam int stmtbindparamdata data pdoparam str stmtexecute stmtclosecursor return true catch pdoexception e loggerthis is never executed loggeregettraceasstring the first two log messages always show up but the third one right after stmt globalsdbpreparesql never makes it to the log file and there is no trace of an exception eitherthe sessions db table remains emptythe log message from the close callback is always presentheres how i connect to the databasedb new pdomysqlhost dbhost dbname dbname dbuser dbpassdbsetattributepdoattr errmode pdoerrmode exceptioni have php 5210i tried to simply run globalsdbexecsql with a manually prepared sql content but it still failed silently the query itself is all right i was able to execute it via the db consoleeditafter volkerk has identified the problem i have found this article which explains the reason behind this weird phenomena perhaps it could be informative to others as well2nd editthe least painful magic solution is that i had to add the below function call to the very end of my front controller the main indexphp filesession write close,['php'] +55800,c allocators specifically passing constructor arguments to objects allocated with boostinterprocesscached adaptive pool this is an embarrassing question but even the wellwritten documentation provided with boostinterprocess has not been enough for me to figure out how to do thiswhat i have is a cached adaptive pool allocator instance and i want to use it to construct an object passing along constructor parametersstruct test testfloat argument bool flag test normal constructiontest obj10 true normal dynamic allocationtest obj2 new test20 falsetypedef managed unique ptr test boostinterprocessmanaged shared memorytype unique ptr dynamic allocation where allocator instance cached adaptive pool using the default constructorunique ptr obj3 allocator instanceallocate one as above but with the nondefault constructorunique ptr obj4 allocator instance this may very well be a failure on my part on how to use allocator objects in general but in any case i cannot see how to use this specific allocator with the interface specified in cached adaptive pool to pass constructor arguments to my objectcached adaptive pool has the method void constructconst pointer ptr const reference v but i do not understand what that means and i cannot find examples using itmy head has been swimming in templates all day so a helping hand even if the answer is obvious will be greatly appreciated,['c++'] +55809,how does switch compile in visual c and how optimized and fast is it as i found out that i can use only numerical values in cs switch statements i thought that there then must be some deeper difference between it and a bunch of ifelsestherefore i asked myselfhow does switch differ from ifelseifelseif in terms of runtime speed compile time optimization and general compilation i am mainly speaking of msvc here,['c++'] +55832,loop through all subviews of an android view iam working on a game for android to help implement it my idea is to create a subclass of a view i would then insert several instances of this class as children of the main view each instance would handle detecting when it was pressed via ontouchlistener the problem iam having now is how do i loop through all these subviews so i can read their statuses and process them ie when they all reach a certain state something should happen or is there a better way to have several objects on the screen that respond to touch and whose status i can check,['android'] +55841,how can i tell if a closed path contains a given point in android i have a path object which i happen to know defines a closed path and i need to figure out if a given point is contained within the path what i was hoping for was something along the lines of pathcontainsint x int ybut that does not seem to existthe specific reason i am looking for this is because i have a collection of shapes on screen defined as paths and i want to figure out which one the user clicked on if there is a better way to be approaching this such as using different ui elements rather than doing it the hard way myself i am open to suggestionsi am open to writing an algorithm myself if i have to but that means different research i guess,['android'] +55848,how to get the nth root of big numbers in c is there a c library that can take nth roots of big numbers numbers than cannot fit in an unsigned long long,['c++'] +55849,can i set largeaddressaware from within visual studio i have a net assembly that needs to be 32bit and needs to be largeaddressawarei know how to do this with editbin but i wonder if there is a builtin way in visual studio 2010 or alternatively did someone write an msbuild task for thisedit this is for a c app so no linker options sadly,"['c#', '.net']" +55851,why automatically implemented properties must define both get and set accessors when we define a property like public string name get setdot net can make our properties code but when we use public string name get public string name setwe face with hajloosomethingpropertynameset must declare a body because it is not marked abstract or extern automatically implemented properties must define both get and set accessorsactually why the compiler cannot determine the property and make code automatically whats the problem,['c#'] +55856,phpexcel set specific headers for file format while googling i found two different sets of headers that need to be set when outputting excel generated in different file formatfor egfor type excel5 headers areheaderpragma publicheaderexpires 0headercachecontrol mustrevalidate postcheck0 precheck0headercontenttype applicationforcedownloadheadercontenttype applicationoctetstreamheadercontenttype applicationdownloadheadercontentthisposition attachmentfilenamefilenameheadercontenttransferencoding binary for type excel2007 headers areheadercontenttype applicationvndopenxmlformatsofficedocumentspreadsheetmlsheetheadercontentthisposition attachmentfilenamemyfilexlsxheadercachecontrol maxage0my question is there need to set up different headers for each file type as there are other file types also csv html and pdf,['php'] +55858,question regarding to valuereference type of events on the msdn i have found followingpublic event eventhandlermyeventargs sampleeventpublic void demoeventstring val copy to a temporary variable to be threadsafe eventhandlermyeventargs temp sampleevent is it referenceif so i do not understand its meaning as when sampleevent became null so does the temp if temp null tempthis new myeventargsval,['c#'] +55874,gtk get usable area of each monitor excluding panels using gdk screen get monitor geometry i can get the total area in pixels and the relative position of each monitor even when there are two or more used as a single screenhowever i want to get the usable area that is excluding panels of each monitor the only thing i have found is net workarea but that is one giant area stretching across all monitors depending on the resolution and arrangement there may be panels inside this areahow can i get the actual usable area of each monitor ideally using only gtkgdk nothing x11specific,['c'] +55887,repository pattern with lazying loading using poco i am in the process of starting a new project and creating the business objects and data access etc i am just using plain old clr objects rather than any orms i have created two class libraries1 business objects holds all my business objects all this objects are light weight with only properties and business rules2 repository this is for all my data accessthe majority of my objects will have child list in and my question is what is the best way to lazy load these values as i do not want to bring back unnecessary information if i dont need toi have thought about when using the get on the child property to check if its null and if it is call my repository to get the child information this has two problems from what i can see1 the object knows how to get itself i would rather no data access logic be held in the object2 this required both classes to reference each other which in visual studio throws a circular dependency errordoes anyone have any suggestions on how to overcome this issue or any recommendations on my projects layout and where it can be improvedthanks,['c#'] +55891,what are the typical reasons javascript developed on firefox fails on ie i developed some javascript enhanced pages that run fine on recent firefox and safari i missed to check in internet explorer and now i find the pages do not work on ie 6 and 7 so far the scripts are somehow not executed the pages show as if javascript was not there although some javascript is executed i am using own libraries with dom manipulation from yui 2 i use yuiloader and the xmlhttprequest and on one page i use psupload which depends on jqueryi am installing microsoft script editor from office xp and will now debug i will also write specific tests nowwhat are the typical failing points of ie what direction i can keep my eyes openi found this page which shows some differences visit quirksmodecan you from your experience name some typical things i should look for firsti will also ask more questions here for specific tasks later but for now i am interested in your experience why ie usually fails on scripts that run fine in firefoxedit thank you for all those great answersin the meantime i have adapted the whole code so that it also works with internet explorer i integrated jquery and built my own classes on top of it now this was my basic mistake that i did not build all my stuff on jquery from the beginning now i havealso jslint helped me a lotand many of the single issues from the different answers helped,"['jquery', 'javascript']" +55892,gzipstream or deflatestream class the msdn documentation tells me the following the gzipstream class uses the gzip data format which includes a cyclic redundancy check value for detecting data corruption the gzip data format uses the same compression algorithm as the deflatestream classit seems gzipstream adds some extra data to the output relative to deflatestream i am wondering in what type of a scenario would it be essential to use gzipstream and not deflatestream,"['c#', '.net']" +55901,how can i access a private constructor of a class i am a java developer in an interview i was asked a question about private constructorscan you access a private constructor of a class and instantiate iti answered no but was wrongcan you explain why i was wrong and give an example of instantiating an object with a private constructor,['java'] +55908,i have caught an exception now what i have started using try catch blocks a bit late i know but now i am not sure what to do with the exception once i have caught it what should i dotry connectionopen dim sqlcmd as new sqlcommanddo some sql connection dim sqlda as new sqldataadaptersqlcmd sqldafilldtcatch ex as sqlexception ah what to do nowfinally connectioncloseend try,['sql'] +55919,how to determine base of a number given a integer number and its reresentation in some arbitrary number system the purpose is to find the base of the number system for example number is 10 and representation is 010 then the base should be 10 another example number 21 representation is 0010101 then base is 2 one more example is number is 6 and representation os 10100 then base is sqrt2 does anyone have any idea how to solve such problem,['c++'] +55935,how i can design a cache system using pdo and memcached i am using pdo for connect to the database in a system where i want implement memcachedi do not know what keys use for caching the results because i cannot get the string of the final query with pdo because the prepared statements any good idea for resolve thisthanks in advance,"['php', 'mysql']" +55938,multiple levels of collectiondefaultdict in python thanks to some great folks on so i thiscovered the possibilities offered by collectionsdefaultdict notably in readability and speed i have put them to use with successnow i would like to implement three levels of dictionaries the two top ones being defaultdict and the lowest one being int i do not find the appropriate way to do this here is my attemptfrom collections import defaultdictd defaultdictdefaultdicta key1 a122 a233 key2 a132 a255 key3 a143 a244for i in a di0 i1now this works but the following which is the desired behavior does notdkey4a1 1i suspect that i should have declared somewhere that the second level defaultdict is of type int but i did not find where or how to do sothe reason i am using defaultdict in the first place is to avoid having to initialize the dictionary for each new keyany more elegant suggestionthanks pythoneers,['python'] +55952,do overlaystooltips work correctly in emacs for windows i am using flymake on c code emacs v21 on windows the flymake stuff has been working well for me for those who do not know you can read an overview of flymake but the quick story is that flymake repeatedly builds the source file you are currently working on in the background for the purpose of doing syntax checking it then highlights the compiler warnings and erros in the current buffer flymake did not work for c initially but i monkeypatched it and it works nicely now if you edit c in emacs i highly recommend using flymake the only problem i have is with the ui flymake highlights the errors and warnings nicely and then inserts overlays with tooltips containing the full error or warning text if i hover the mouse pointer over the highlighted line in code the overlay tooltip pops up but as you can see the overlay tooltip is clipped and it does not thisplay correctly flymake seems to be doing the right thing it is the overlay part that seems broken and overlay seems to do the right thing it is the tooltip that is thisplayed incorrectly do overlays tooltips work correctly in emacs for windows where do i look to fix this after some research i found that the effect is demonstrable with tooltipshow reallylongstring it has nothing to do with overlays or flymake,['c#'] +55960,is there any reason to throw a dividebyzeroexception are there any cases when it is a good idea to throw errors that can be avoidedi am thinking specifically of the dividebyzeroexception and argumentnullexceptionfor exampledouble numerator 10double denominator getdenominatorif denominator 0 throw new dividebyzeroexceptionyou cannot divide by zeroare there any reasons for throwing an error like thisnote i am not talking about catching these errors but specifically in knowing if there are ever good reasons for throwing themjust to reiteratei know that in the example i gave youd probably be better off handling the error perhaps the question should be rephrased are there any reasons to throw one of these errors instead of handling it at this location,['c#'] +55965,embedding html5 in a mobilesafari webapp is it possible to load an image in place of the quicktime logo in the modal player i have not be able to find a resource explaining if this is possible at all the apple documentation found here html5 audio videoaudioandvideotagbasicsaudioandvideotagbasicshtmlapple refdocuidtp409523ch2sw1 does not mention such features i also tried embedding audio with the tag which pulls up the same modal quicktime playeris there a way to do this or alternatively a is there a way to play audio files in an iphone webapp without opening a modal external playerthanks,['iphone'] +55978,url valid characters java to validate a string like wtestcom is gooda string like w8com is gooda string like stackoverflowcom is good a string like googlecom is good why because those are valid urls it does not necessarely matter if they have been registered or not now bad strings are googdx manydotscom why because you cannot register those urls if i have a string in java which is supposed to be a good url whats the best way to validate it thanks a lot,['java'] +55990,javascript locationhash refreshing in ie i need to modify the hash remove it after certain processing takes place so that if the user refreshes they do not cause the process to run again this works fine in ff but it seems that ie is reloading every time i try to change the hash i think it is related to other things that are loading on the page though i am not certain i have an iframe that loads related to the process as well as some scripts that are still being fetched in the parent windowi cannot seem to figure out a good way to change the hash after all the loading completes and at the same time am not even positive that it is related to the loadingany ideas on how to solve thismore odd behaviorthe hash is coming from else where in the web app via a redirect i have found if i simply add the hash by hand adding myid to the url it does not reload it does not matter if i enter the hash on a page that has already loaded adding myid to the already existing url or by entering the complete url in a new tab,['javascript'] +55992,methods in ruby objects or not inspired by this thiscussion after some googling i was not able to find an answer to a pretty simple question regarding methods in ruby are methods objects or notthere are different opinions here and there and i would really like to hear let us say an indepth explanationi am aware of objectmethod method which takes a method name and returns a method instance but on the other hand there is a similar thing you can do with blocks to make them into proc instances and blocks are not objects so what makes methods any different,['ruby'] +55993,is it possible for beautifulsoup to work in a caseinsensitive manner i am trying to extract meta description for fetched webpages but here i am facing the problem of case sensitivity of beautifulsoup as some of the pages have meta namedescription and some have meta namedescription my problem is very much similar to that of question on stackoverflowthe only difference is that i cannot use lxml i have to stick with beautifulsoup,['python'] +55999,how to implement gmail oauth api to send email especially via smtp i am developing a web application that will send emails on behalf of a loggedin user i am trying to use the new gmail oauth protocol announced described here to send these emails through the users gmail account preferably using smtp rather than imap but i am easy however the sample php code gives me a couple of problemsall of the sample code is based on imap not smtp why support the smtp protocol if youre not going to show people how to use itthe sample code gives me a fatal error from an uncaught zend exception it cannot find the inbox folderfatal error uncaught exception zend mail storage exception with message cannot change folder maybe it does not exist in pathtoxoauthphpsampleszendmailstorageimapphp467 stack trace 0 pathtoxoauthphpsampleszendmailstorageimapphp248 zend mail storage imapselectfolderinbox 1 pathtoxoauthphpsamplesthreeleggedphp184 zend mail storage imap constructobjectzend mail protocol imap 2 main next exception zend mail storage exception with message cannot select inbox is this a valid transport in pathtoxoauthphpsampleszendmailstorageimapphp254 stack trace 0 pathtoxoauthphpsamplesthreeleggedphp184 zend mail storage imap constructobjectzend mail protocol imap 1 main in pathtoxoauthphpsampleszendmailstorageimapphp on line 254i have verified that i am getting good oauth tokens back i just do not know how to make the actual email transaction happen this protocol is still rather new so there is not much unofficial community documentation about it out there and the official docs are unhelpfully dry stuff about the smtp rfc so if anyone can help get this going i would greatly appreciate itnote i have already been able to connect to gmails smtp server via ssl and successfully send an email provided that the user has given my application hisher gmail username and password i would like to avoid this method because it encourages phishing and securityminded users would not accept it this question is not about that,['php'] +56007,force scope bar below uisearchbar i have a uisearchbar and uisearchthisplaycontroller everything works great but my scope selector thisplays beside the text field instead of below it i know that this is the expected action when the device is in landscape but since i have the uisearchbar in the master view of a uisplitviewcontroller it ends up looking like thisis there any way to force the scope bar to thisplay below the text field in all interface orientations i know that this works nicely in mailapp on the ipad so its possibly but who knows if apple decided to hide the option to do so,['iphone'] +56009,how to use a naming convention for large databases i am busy developing 2 web based systems with mysql databases and the amount of tablesviewsstored routines is really becoming a lot and it is more and more challenging to handle the complexity now in programming languages we have namespacing eg java packages c namespaces to partition the software grouping it together to make things more understandable databases on the other hand have more of a flat structure mysql at least eg tables and stored procedures are on the same level so one have to be more creative creating naming conventions perhaps use more than one database or using tools to visualize thingswhat methods do you use to ease the pain to be effective while developing your databases to not get lost in a sea of tables and fields and stored procsfeel free to mention tools you use also but try to restrict it to open source and preferably linux solutions if thats okbtw how many tables would a database have to be considered large in terms of design,['mysql'] +56019,sti and polymorphs i have problem with my codeclass post activerecordbaseendclass newsarticle post has many comments as commentable dependent destroy order created atendclass comment activerecordbase belongs to commentable polymorphic true counter cache trueendand on attempt go get comments for some newsarticle i see in logs something like comment load 09ms select comments from comments where commentscommentable id 1 and commentscommentable type post order by created atstrange that commentable type postwhats wrongps rails 235 ruby 187 20100110 patchlevel 249 i686darwin10,['ruby-on-rails'] +56021,how to align 3 divs leftcenterright inside another div i want to have 3 divs aligned inside a container div something like thisleft center rightcontainer div is 100 wide no set width and center div should remain in center after resizing the containerso i setcontainerwidth100leftfloatleftwidth100pxrightfloatrightwidth100pxcentermargin0 autowidth100pxbut it becomesleft center rightany tips,"['html', 'css']" +56027,android layout with 2 evenly spaced buttons i have this layout that works correctly a relative layout with a text view and two buttons spaced evenly below itrelativelayout androidididentrypopup androidlayout widthfill parent androidlayout heightwrap content androidpadding5px androidvisibilitygone androidlayout belowidad androidbackground80 textview androidididtitle androidlayout widthfill parent androidlayout heightwrap content androidtextentry popup androidtextcolorf androidtextsize20sp tablelayout androidididtablelayout01 androidlayout widthfill parent androidlayout heightwrap content androidlayout belowidtitle tablerow androidlayout weight1 button androidididbuttonvisit androidtextview androidlayout heightfill parent androidlayout width0dip androidlayout weight1 button androidididbuttoncancel androidtextcancel androidlayout width0dip androidlayout weight1 androidlayout heightfill parent tablerow tablelayoutrelativelayoutbut running layoutopt it says that this tablerow layout or its tablelayout parent is possible useless is there a way to do this layout then without the tables,['android'] +56033,how to create a jquery clock timer i have a simple quiz application and i want thisplay a nice timer clock at the top of the page which shows the user how long they have been going for if i could somehow show them a timer for total quiz time and also a second one for this question time that would be even cooler but i should be able to figure out how to do myself that once i have got one timer workingmy question iswhats a nice easy way to show a simple timer clock using jquery straight js is also ok i know how to check time but how do i get incrementing secondsmy own searches keep leading me to jquery plugins i want to roll my own and also event timers which are not what i am looking for,"['javascript', 'jquery']" +56037,why does easy install extract some python eggs and not others looking in my usrlocallibpythonthistpackage directory i have egg directories and egg files why does the installer choose to extra packages to the egg directory yet leave other files with egg extensions,['python'] +56050,redirecting exec output to a buffer or file i am writing a c program where i fork exec and wait i would like to take the output of the program i execed to write it to file or bufferfor example if i exec ls i want to write file1 file2 etc to bufferfile i do not think there is a way to read stdout so does that mean i have to use a pipe is there a general procedure here that i have not been able to find,['c'] +56060,systemdatasqlite net 4 is there a net 4 version of systemdatasqliteat the moment i get this errormixed mode assembly is built against version v2050727 of the runtime and cannot be loaded in the 40 runtime without additional configuration information what is the additional configuration information that is needed or alternatively is there another version that i can use,['.net'] +56063,c where to initialize static const i have a classclass foo public foo foo int private static const string swhere is the best place to initialize the string s in the source file,['c++'] +56065,having a destructor take different actions depending on whether an exception occurred i have some code to update a database table that looks liketry dbexecutebegin lots of delete and insert dbexecutecommitcatch dbexception dbexecuterollbacki would like to wrap the transaction logic in an raii class so i could just write dbtransaction transdb lots of delete and insertbut how would i write the destructor for it,['c++'] +56084,why are my basic heroku apps taking two seconds to load i created two very simple heroku apps to test out the service but it is often taking several seconds to load the page when i first visit themcropify basic sinatra app on githubtextile2html even more basic sinatra app on githuball i did was create a simple sinatra app and deploy it i have not done anything to mess with or test the heroku servers what can i do to improve response time it is very slow right now and i am not sure where to start the code for the projects are on github if that helps,['ruby'] +56091,unexpected resume of package name while already resumed in package name error in android if changing the orientation of my phone or the emulator i get the following output in logcat0409 115526290 infowindowmanager52 setting rotation to 1 animflags00409 115526300 infoactivitymanager52 config changed scale10 imsi310260 locen us touch3 keys211 nav31 orien2 layout180409 115526460 infousagestats52 unexpected resume of client while already resumed in client0409 115526579 infosearchposition807 activity is paused0409 115526689 infosearchposition807 activity is resumingsearchposition is the activity that is thisplayed activity is paused is written in the onpause method and activity is resuming in the onresume method of the activityi googled a little bit for the error message but i do not fully understand the meaning of it i think it could mean that the old activity is not properly destroyed after changing the screen orientation is this correct if yes what causes the errorif this is not correct what is the meaning of this output,['android'] +56098,gmail like url scheme i am working on a ticket system having the following requirementthe home page is divided into two sectionssec1 some filter options are shown herelike closedtickets opentickets alltickets ticketsassignedtome etc you can select one or more of these filterssec2 list of tickets satisfying above filters will be thisplayed herenow this is what i want as i change the filters the change should be reflected in the url so that one is able to bookmark it an ajax request will go and list of tickets satisfying the selected filters will be updated in sec2 i want the same code to be used to load the tickets in both waysa by selecting that set of filters andb by using the bookmark to reload the pagei have little idea on how to do itthe url will contain the selected filtersappended after changing filters on the page will modify the hash part of url and call a function say ajaxhandler to parse the url to get the filters and then make an ajax request to get the list of tickets to be thisplayed in section2andi will call the same function ajaxhandler in windowonloadi feel this is what yahoo maps doeswhats the best way to implement such url schemeam i headed in the right direction,['javascript'] +56104,set up the server side of push notification im my app i need to include push notifications but i do not understand how to start settings things up on the server side does anyone know of an example of server side code that implements a push notification which language is preferred for the server implementation,['iphone'] +56107,linux how to capture screen and simulate mouse movements i need to capture screen as print screen in the way so i can access pixel color data to do some image recognition after that i will need to generate mouse events on the screen such as left click drag and drop moving mouse while button is pressed and then release it once its done image will be deleted note i need to capture whole screen everything that user can see and i need to simulate clicks outside window of my program if it makes any differencespec linux ubuntulanguage cperformance is not very importantprint screen function will be executed once every 10 sec duration of the process can be up to 24 hours so method needs to be stable and memory leaks free as usuall i was able to do in windows with win gdi and some windows events but iev no idea how to do it in linuxthanks a lot,['c++'] +56112,mysql treats a as aao these two querys gives me the exact same resultselect from topics where nameharligtselect from topics where nameharligthow is this possible seems like mysql translates a to aao when it searches is there some way to turn this offi use utf8 encoding everywhere as far as i know the same problem occurs both from terminal and from php,['mysql'] +56113,php profiling with microtime negative time for a very simple profiling i use microtime like thisnow microtimefor do something echo microtime now now microtimenow the output of the echo line seems completely random that is i expected fluctuations but i did not expect negative numbers showing uphowever a typical result contains 13 negative numbers i confirmed this on solaris php 50x and winvista php 523what the heck is going on here have i invented accidently a time machine,['php'] +56145,problems with umlauts in python appdata environvent variable i cannot find a correct way to get the environment variable for the appdata path in pythonthe problem is that my user name includes special characters the german ae and uei made a workaround wit pyqt for vista and windows 7 but it does not work for xp systemsdoes anybody know the correct encoding of these environment variables or another solution for this problem,['python'] +56146,check if firsttime user of my app in android in my app first it shows a splash screen after that another activity then my main activity must be shown this is my design plan the second activity ie before main activity must be shown for the firsttime user of the app if heshe closes the app splash screen will redirect to main activity automatically how do i do this any ideas i am developing my app for android phones,"['java', 'android']" +56170,converting local timestamp to utc timestamp in java i have a millisecondssincelocalepoch timestamp that i would like to convert into a millisecondssinceutcepoch timestamp from a quick glance through the docs it looks like something like this would workint offset timezonegetdefaultgetrawoffsetlong newtime oldtime offsetis there a better way to do this,['java'] +56204,how to drop all stored procedures at once in sql server database currently we use separate a drop statements for each stored procedure in the script file if exists select from sysobjects where object id object idndbomysp and type in np npc drop procedure dbomysp is there a way to drop them all at once or maybe in a loop,['sql'] +56216,how can i effectively test against the windows api i am still having issues justifying tdd to myself as i have mentioned in other questions 90 of the code i write does absolutely nothing butcall some windows api functions andprint out the data returned from said functionsthe time spent coming up with the fake data that the code needs to process under tdd is incredible i literally spend 5 times as much time coming up with the example data as i would spend just writing application codepart of this problem is that often i am programming against apis with which i have little experience which forces me to write small applications that show me how the real api behaves so that i can write effective fakesmocks on top of that api writing implementation first is the opposite of tdd but in this case it is unavoidable i do not know how the real api behaves so how on earth am i going to be able to create a fake implementation of the api without playing with iti have read several books on the subject including kent becks test driven development by example and michael feathers working effectively with legacy code which seem to be gospel for tdd fanatics feathers book comes close in the way it describes breaking out dependencies but even then the examples provided have one thing in commonthe program under test obtains input from other parts of the program under testmy programs do not follow that pattern instead the only input to the program itself is the system upon which it runshow can one effectively employ tdd on such a project i am already wrapping most of the api inside c classes before i actually use that api but sometimes the wrappers themselves can become quite complicated and deserve their own tests,['c++'] +56233,call a function in an extjs xtemplate i am familiar with using a function to determine a specific condition using xtemplate but not sure how to directly call a function without the conditional if statementmy code for example wants to append some characters to a string that i am using within my xtemplate i think the best way to do it is append the characters when the xtemplate is renderedvar mytpl new extxtemplate tpl for tpl ifthisisthumbnailedthumbnailed true img srcthisgetthumburlrawthumburl this call to function does not work also tried variations of this tpl tpl isthumbnailed functionthumbnailed return getthumburl functionrawthumburl this function does not get called return,['javascript'] +56235,python desktop application with the browser as an interface i want to create an application that runs on the users computer a standalone application with installation and whatnot but i want the interface to be a browser either internal and thisplayed as an os window or external accessible using the browser ie some http serverthe reason would be because i know a little about python but i think i can manage as long as i have some basic roots that i can use and manipulate and those would be html css and javascripti have yet to find a good gui tool which i can use and always abandon the idea after trying to mess around and eventually not getting anything,['python'] +56238,return value from nested function in javascript i have a function that is set up as followsfunction mainfunction function subfunction var str foo return str var test mainfunctionalerttestto my logic that alert should return foo but instead it returns undefined what am i doing wrongupdate heres my actual code it is a function for reversegeocoding with the google apifunction reversegeocodelatitudelongitude var address var country var countrycode var locality var geocoder new gclientgeocoder var latlng new glatlnglatitude longitude return geocodergetlocationslatlng functionaddresses address addressesplacemark0address country addressesplacemark0addressdetailscountrycountryname countrycode addressesplacemark0addressdetailscountrycountrynamecode locality addressesplacemark0addressdetailscountryadministrativeareasubadministrativearealocalitylocalityname return country,['javascript'] +56251,how to access object attribute given string corresponding to name of that attribute how do you setget the values of attributes of t given by x class test attr1 int attr2 intt testx attr1,['python'] +56253,how to do bitwise exclusive or of two strings in python i would like to perform a bitwise exclusive or of two strings in python but xor of strings are not allowed in python how can i do it,['python'] +56258,double split in c ok for example i have this line in my txt file127196481922as you can see it has 2 parts separated by i have no problems getting both parts and separating second part 1127196481922 using separator but i do have problems with separating further by to get first and second number of each setthis is my current code result strtokresult whileresult null printfsn result result strtoknull it outputs me112 719 64 819 22 ok great but when i try to strtok i am using this method for splittinglike this result strtokresult whileresult null printfsn result help strtokresult whilehelp null printfs help help strtoknull result strtoknull i only get 112 like there is only one set in this set of numbers i dont understand where are the rest of the numbers instead output should be 1127196481922 could someone please give a solution how to get each number of each set this set of numbers maybe there are other methods or i am doing something wrong thank you,['c'] +56268,i have heard global variables are bad what alternative solution should i use i have read all over the place that global variables are bad and alternatives should be used in javascript specifically what solution should i choosei am thinking of a function that when fed two arguments function globalvariablesvariablevalue looks if variable exists in a local array and if it does set it is value to value else variable and value are appended if the function is called without arguments function globalvariables it returns the array perhaps if the function is fired with just one argument function globalvariablesvariable it returns the value of variable in the arraywhat do you think i would like to hear your alternative solutions and arguments for using global variableshow you would use globalvariablesfunction append globalvariablesvariable1value1 globalvariables would append variable1 to it is local arrayfunction retrieve var localvariable1 globalvariablesvariable1 globalvariables would return value1function retrieveall var localvariable1 globalvariables globalvariables would return the globalvariables entire local persistently stored between calls arrayfunction set globalvariablesvariable1value2 globalvariables would set variable1 to value2is this a singleton pattern btwin this specific scenario a function may set a variable at one point in time and much later another function maybe when a user submits a form will need to get that variable therefore the first function could not pass the variable as an argument to the later function as it would never be called from the firstthank you i appreciate all your help,['javascript'] +56297,smart reversing of compressed javascript with obscured variable function names i want to know if there exists a tool to help in reversing a compressed javascript that has obscure variable names i am not looking for a prettyprinting beautifier but for a tool that actually knows how to change propagate variable name choiceslet me be more specific some of the functions belong to the public api and i want to impose readable argument names in their prototypes there are intermediary variables for document window and other browser idiomsi would like to give this knowledge to the tool and then let it create another javascript where the knowledge would have been correctly propagatedthanksjerome wagner,['javascript'] +56303,javalangvoid in c i am currently working with net 20 and have an interface whose generic type is used to define a methods return type something likeinterface iexecutort t execute my problem is that some classes that implement this interface do not really need to return anythingin java you can use javalangvoid for this purpose but after quite a bit of searching i found no equivalent in c more generically i also did not find a good way around this problem i tried to find how people would do this with delegates but found nothing either which makes me believe that the problem is that i suck at searching so whats the best way to solve this how would you do itthanks,['c#'] +56308,resource mapping in a ruby on rails url restful api i am having a bit of difficulty coming up with the right answer to this so i will solicit my problem here i am working on a restful api naturally i have multiple resources some of which consist of parent to child relationships some of which are stand alone resources where i am having a bit of difficulty is figuring out how to make things easier for the folks who will be building clients against my api the situation is this hypothetically i have a street resource each street has multiple homes so street has many to homes and homes belongs to street if a user wants to request an http get on a specific home resource the following should workhttpmymapstreets5homes10that allows a user to get information for a home with the id 10 straight forward my question is am i breaking the rules of the book by giving the user access tohttpmymaphomes10technically that home resource exists on its own without the street it makes sense that it exists as its own entity without an encapsulating street even though business logic says otherwise whats the best way to handle thisedit in spirit of becoming a good stackoverflow citizen i have come back with a supported code block for how to implement they above mapresources streets has many homes shallow truethis will create both types of routes that i was looking for,"['ruby-on-rails', 'ruby']" +56313,storing urls while spidering i created a little web spider in python which i am using to collect urls i am not interested in the content right now i am keeping all the visited urls in a set in memory because i do not want my spider to visit urls twice of course that is a very limited way of accomplishing thisso whats the best way to keep track of my visited urls should i use a databasewhich one mysql sqlite postgresql how should i save the urls as a primary key trying to insert every url before visiting itor should i write them to a fileone filemultiple files how should i design the filestructurei am sure there are books and a lot of papers on this or similar topics can you give me some advice what i should read,['python'] +56316,get position of the viewport in mobile safari is there a way to determine the position of the viewport in mobile safari on a web page like x y w h pixel positions of what the phone is currently seeing on the page,['iphone'] +56338,can i use array push on a session array in php i have an array that i want on multiple pages so i made it a session array i want to add a series of names and then on another page i want to be able to use a foreach loop to echo out all the names in that arraythis is the session sessionnamesi want to add a series of names to that array using array push like thisarray push sessionnamesnamei am getting this error array push functionarraypush first argument should be an arraycan i use array push to put multiple values into that array or perhaps there is a better more efficient way of doing what i am trying to achieve,['php'] +56346,uitableview section index overlaps search bar hi i want to thisplay a section index in an uitableview with a search bar in the table view header not section headerbut the index strip is now overlapping the search bar is there an elegant solution to avoid this and let the index start below the table header,"['iphone', 'objective-c']" +56353,what characters are widely supported in css class names as detailed here among other places the only valid characters in a htmlcss class name is az az 09 hyphen and underscore and the first character should be a letter but in practice what characters are in fact supported by most browsers more specifically i wonder what browsers properly understands a slash in a class name and what browsers support class names starting with a numberi am primarily interested in getting an answer for html rather than xhtml in case there is a differencethank you,"['html', 'css']" +56362,how to get all elements which name starts with some string i have an html pagei would like to extract all elements which name starts with q1 how can i achieve this in javascript thanks,"['javascript', 'html']" +56406,sample xml configuration for log4j have a main java application and want to write to file are there any example log4j configuration files xmli have a java main applicationi want log4j to output to console and write to fileany examples of this would be greatly appreciatedi am using netbeans if that matters,['java'] +56410,javascript ignoring case sensitivity of strings in javascript i am trying using the users input to search my database for example user input is monster and my databases data is monster how can i have it match regardless of it is casing,['javascript'] +56455,automatically reporting javascript errors to the developer as most production environments we have setup something to send us a notification if there is an error in our web application the problem is ofcourse that this only covers errors on the server sidemy question to the community is what are you doing about client side errors especially in javascriptand what about other quality of service issues such as slow processing and other things that might be due to the client machine,['javascript'] +56459,generic list view raises attribute error function object has no attribute clone an odd error here perhaps someone can help track down source as it is attempting to extend the django cms project attempts to use uses some logic written as part of that project which i am not fully clear on in short usingurlspyfrom djangoconfurlsdefaults import from cmsplugin flat newsmodels import newsreturning clone error when implementeddef get news return newspublishedallnews dict queryset get newsnews list dic queryset get news paginate by 50 next section functions but needs server restart to see new postschanging to just newspublishedall raises same issue as using wrappersolution above see example here news dict queryset newspublishedallnews list dic queryset newspublishedallsame issue paginate by 50urlpatterns patternsdjangoviewsgenericlist detail r object list news list dic rppage09 object list dictnews list dic urlrpslugw object detail news dict namenews viewmodelspyclass publishednewsmanagermodelsmanager filters out all unpublished news and news with a publication date in the future def get query setself return superpublishednewsmanager selfget query set filteris publishedtrue filterpub date ltedatetimedatetimenowclass newsmodelsmodel title modelscharfield title max length255 slug modelsslugfield slug unique for datepub date author modelsforeignkeyuser description modelstextfield description blanktrue image genericgenericrelationnewsimage blanktrue nulltrue content modelstextfield content blanktrue tags tagfield is published modelsbooleanfield published defaultfalse pub date modelsdatetimefield publication date defaultdatetimedatetimenow created modelsdatetimefieldauto now addtrue editablefalse updated modelsdatetimefieldauto nowtrue editablefalse published publishednewsmanager objects modelsmanagersee issue in comments basically error raised by implementing the correct solution to add extra context to the views error is attribute error function object has no attribute clonetrying newspublishedall instead of newspublishedall raises the error whether used as part of a wrapper function or directly in the queryset part of the urlpatternmust be missing something obvious think it is to do with the publishednewsmanager not returning objects as a dictionary or tweaking the code to correctly return the objects to the view,['python'] +56460,operators computing direction i encountered something that i cannot understandi have this codecout f1 f1 f2 f1 f1 f2 is f1 f1 f2 f1 f1 f2 endlall the fs are objects and all the operators are overloadedthe weird this is that the first computation is of the operatorthen the second and then the first after that the operator and at last operator so basically the and worked from right to leftand the and operators worked from left to righti made another testi checked this code cout f1 f1 f2 is f1 f1 f2 endlnow the first operator was and only then operator so now it worked from left to rightcan someone help me understand why is there difference in the directions10x,['c++'] +56468,return reference from class to this i have the following member of class foofoo foobar return thisbut i am getting compiler errors what stupid thing am i doing wrongcompiler error gcc error invalid initialization of nonconst reference of type foo from a temporary of type foo const,['c++'] +56477,is there any way to automatically break into debugger when my class library functions are getting called i have a managed class library say mylibdll and a 3rd party managed app say appexe which is using mylibdll i have the code of mylibdll but not of the appexe so currently what i do is i build mylibdll copy it to appexes directory start appexe and attach to the process that way if i put breakpoints in code mylibdll i see them being hit but is there anyway to automatically break in code of mylibdll whenever any external application calls one of its exposed methods ie only for entrypoints of the dllthanksmishal,['c#'] +56482,exceptions silently caught by windows how to handle manually were having problems with windows silently eating exceptions and allowing the application to continue running when the exception is thrown inside the message pump for example we created a test mfc mdi application and overrode ondrawvoid ctestviewondrawcdc pdc int0 0 crash ctestdoc pdoc getdocument assert validpdoc if pdoc return todo add draw code for native data hereyou would expect a nasty error message when running the application but you actually get nothing at all the program appears to be running perfectly well but if you check the output window you will seefirstchance exception at 0x13929384 in testexe 0xc05 access violation writing location 0x0 firstchance exception at 0x77c6ee42 in testexe 0xc0150010 the activation context being deactivated is not active for the current thread of executioni know why i am receiving the application context exception but why is it being handled silently it means our applications could be suffering serious problems when in use but well never know about it because our users will never report any problems,['c++'] +56485,java inheritance and object casting i am quite new to programming i have a question please help me this question is java question but i cannot remember the syntax but what i write here is mostly ita class person speaks i am a persona class student speaks i am a studentstudent extends from personperson p new studentthen what is p speaking then,['java'] +56492,in app purchase can we refund the in app purchase is there a programatical way in which an in app purchase is refunded back to the useri have an application with a certain buyable feature the user buys it but somehow doesnt like it is there any programatical way in which i can make the user get back his spent money,['iphone'] +56495,parameter index is out of range i am getting the following error when trying to update an object using nhibernate i am attempting to update a field which is a foreign key any thoughts why i might be getting this error i cannot figure it out from that error and my log4net log does not give any hints eitherthanks systemindexoutofrangeexception was unhandled by user code messageparameter index is out of range sourcemysqldata stacktrace at mysqldatamysqlclientmysqlparametercollectioncheckindexint32 index at mysqldatamysqlclientmysqlparametercollectiongetparameterint32 index at systemdatacommondbparametercollectionsystemcollectionsilistget itemint32 index at nhibernatetypeint32typesetidbcommand rs object value int32 index at nhibernatetypenullabletypenullsafesetidbcommand cmd object value int32 index at nhibernatetypenullabletypenullsafesetidbcommand st object value int32 index isessionimplementor session at nhibernatepersisterentityabstractentitypersisterdehydrateobject id object fields object rowid boolean includeproperty boolean includecolumns int32 table idbcommand statement isessionimplementor session int32 index at nhibernatepersisterentityabstractentitypersisterupdateobject id object fields object oldfields object rowid boolean includeproperty int32 j object oldversion object obj sqlcommandinfo sql isessionimplementor session at nhibernatepersisterentityabstractentitypersisterupdateorinsertobject id object fields object oldfields object rowid boolean includeproperty int32 j object oldversion object obj sqlcommandinfo sql isessionimplementor session at nhibernatepersisterentityabstractentitypersisterupdateobject id object fields int32 dirtyfields boolean hasdirtycollection object oldfields object oldversion object obj object rowid isessionimplementor session at nhibernateactionentityupdateactionexecute at nhibernateengineactionqueueexecuteiexecutable executable at nhibernateengineactionqueueexecuteactionsilist list at nhibernateengineactionqueueexecuteactions at nhibernateeventdefaultabstractflushingeventlistenerperformexecutionsieventsource session at nhibernateeventdefaultdefaultflusheventlisteneronflushflushevent event at nhibernateimplsessionimplflush at nhibernatetransactionadotransactioncommit at dataaccesslayernhibernatedataproviderupdateitem tempitems temp item temp in cdocuments and settingsusermy documentsvisual studio 2008projectsmysolutiondataaccesslayernhibernatedataprovidercsline 225 at inventorydatacleancontrollersimportcontrollereditint32 id formcollection formvalues in cdocuments and settingsusermy documentsvisual studio 2008projectsmysolutioninventorydatacleancontrollersimportcontrollercsline 101 at lambda methodexecutionscope controllerbase object at systemwebmvcactionmethodthispatcherexecutecontrollerbase controller object parameters at systemwebmvcreflectedactiondescriptorexecutecontrollercontext controllercontext idictionary2 parameters at systemwebmvccontrolleractioninvokerinvokeactionmethodcontrollercontext controllercontext actiondescriptor actiondescriptor idictionary2 parameters at systemwebmvccontrolleractioninvokerc thisplayclassainvokeactionmethodwithfiltersb 7 at systemwebmvccontrolleractioninvokerinvokeactionmethodfilteriactionfilter filter actionexecutingcontext precontext func1 continuation innerexception here is my item mapping xml version10 encodingutf8 hibernatemapping xmlnsurnnhibernatemapping22 assemblydatatransfer namespacedatatransfer class namedatatransferitems temp datatransfer tableitems temp id nameid unsavedvalueany generator classassigned id property nameassetid property namedescription property namecaretaker property namecategory property namestatus property namevendor manytoone namestatusname clastatus columnstatus classhibernatemappinghere is my status mapping xml version10 encodingutf8 hibernatemapping xmlnsurnnhibernatemapping22 assemblydatatransfer namespacedatatransfer class namedatatransferstatus datatransfer tablestatus id nameid unsavedvalue0 generator classassigned id property namename property namedef classhibernatemappingand here is my update function public void updateitem tempitems temp item temp itransaction t sessionbegintransaction try sessionsaveorupdateitem temp tcommit catch exception trollback throw finally tthispose,['c#'] +56515,custom form helpers is there a way that i can create a custom form helper so that instead ofspecial field tag object methodi can achieve something likeformspecial field method,"['ruby-on-rails', 'ruby']" +56521,output without new line how can i output text to the console without new line at the endfor exampleprint temp1print temp2outputtemp1 temp2and i needtemp1temp2,['python'] +56526,php script to generate a file with random data of given name and size does anyone know of one i need to test some uploaddownload scripts and need some really large files generated i was going to integrate the test utility with my debug script,['php'] +56528,subtracting days in a calendar object possible duplicateanyone know a simple way using java calendar to subtract x days to a date i need to minus 365 days in a given date givendatecalendar calendar calendargetinstancecalendarsettimegivendatecalendaraddcalendardate 365 am i right,['java'] +56549,what is the purpose of javas unary plus operator javas unary plus operator appears to have come over from c via c int result 1 it appears to have the following effectsunboxes its operand if it is a wrapper objectpromotes its operand to int if it is not already an int or widercomplicates slightly the parsing of evil expressions containing large numbers of consecutive plus signsit seems to me that there are betterclearer ways to do all of these things in this so question concerning the counterpart operator in c someone said that it is there to be overloaded if you feel the need however in java one cannot overload any operator so does this unary plus operator exist in java only because it existed in c,['java'] +56573,membership generate password alphanumeric only password how can i use membershipgeneratepassword to return a password that only contains alpha or numeric characters the default method will only guarantee a minimum and not a maximum number of non alphanumeric passwords,['asp.net'] +56575,long press in javascript is it possible to implement long press in javascript or jquery howhtmla href titlelong pressajavascriptamouseupfunction clear timeout return falsemousedownfunction set timeout return false,['javascript'] +56585,java and c how close are they i have been using cc and python but i now i see that a lot of new programming books use java or c as examplesi do not think i will use java or c for the time being but i guess i have to study one of the languages or both of them in order to readunderstand the books how similar java and c if i learn java is learning c almost free or vice versa if i have to choose only one of the two languages which would be better which has wider coverage in terms of programming language,"['c#', 'java']" +56588,what are the best workarounds for known problems with hibernates schema validation of floating point columns when using oracle 10g i have several java classes with double fields that i am persisting via hibernate for example i haveentitypublic class node private double valuewhen hibernates orghibernatedialectoracle10gdialect creates the ddl for the node table it maps the value field to a double precision typecreate table mdbnode value double precision not null it would appear that in oracle double precision is an alias for float so when i try to verify the database schema using the orghibernatecfgannotationconfigurationvalidateschema method oracle appears to describe the value column as a float this causes hibernate to throw the following exception orghibernatehibernateexception wrong column type in dboacl rule for column value found float expected double precisiona very similar problem is listed in hibernates jira database as h1961 i would like to avoid doing anything that will break mysql postgres and sql server support so extending the oracle10gdialect appears to be the most promising of the workarounds mentioned in h1961 but extending a dialect is something i have never done before and i am afraid there may be some nasty gotchas what is the best workaround for this problem that would not break our compatibility with mysql postgres and sql server,['java'] +56591,internet explorer 8 timeout too quick on page posts we have an aspnet site running which has been working fine for some time but recently i have been experiencing some issues with ie8on posting some pages mainly on our development server although on staging too we get an occasional internet explore cannot thisplay the webpage error along with the button asking to diagnose connection problems ie only seems to wait 10 seconds before timing out i know that the page itself may take longer to load the first time on dev and staging so press f5 and everything then works fineis there anything that should be done in the aspx page to tell ie to wait a bit longeri thought i had read that the default timeout supposed to be 90 seconds or something for browsersa bit more infoit mostly happens on a posting a signup page but that is just because i test that page and it starts the iis app makes the first connection to sql and precaches some information that first time the page can take 1015 seconds to come back ie8 times out after 10 seconds as it has had nothing backthis happens on a dev w7x64 machine with 8gb ram as well as on a staging server win2008having googled around a bit some people are seeing the same problem but no conclusive pointers to the problem or a solutionit is not a connection problem everything works fine in firefox chrome and even ie7 i have tried with addons thisabled and resetting ie settings still happensideas welcome,['asp.net'] +56599,iframe for ad loading good or bad according to yahoos best practices for speeding up your site the pros for using iframeshelps with slow thirdparty content like badges and ads download scripts in parallelbut the cons arecostly even if blankblocks page onload i want to use an iframe to load ads using the technique mentioned on this sitedoes using this technique mean that as soon as the html contents requested by the iframe are returned to the client it will load the ad script potentially blocking the rest of the pages rendering and downloading or will the iframe request get processed concurrently while rest of the document is downloaded and renderedi am however not looking for a thiscussion on the philosophy of whether ads are good or bad,"['javascript', 'html']" +56606,chaining css classes in ie6 trying to find a jquery solution tldr anyone know how to apply chained classes for ie6 using jquery or similarrightperhaps i ask the impossible i consider myself fairly new to javscript and jquery but that being said i have written some fairly complex code recently so i am definitely getting there however i am now possed with a rather interesting issue at my current freelance contractthe previous web coder has taken a grid960 approach to the html and as a result has used chained classes to style many of the elements the example below is typical of what can be found in the codediv classblocks fourcol1 orange highlightsome contentdivand in the css there will be different declarations for not actual css but close enoughblocks marginright10pxorange backgroundimageurlsomeimagejpghighlight fontweightboldfourcol1 width300pxand to make matters worse this is in the cssblocksorangehighlight backgroundcolourdd00ffanyone not familiar with this particular bug can read more on it here it is very real and very annoyingwithout wanting to go into the merrits of not chaining classes i told them this but it is no longer feasible to change their approach 100 hand coded pages into a 150 page website no cms sigh and without the luxury of being able to change the way these blocks are styled can anyone advise me on the complexity and benefits between any of my below proposed approaches or possible other options that would adequately solve this problempotential solution 1using conditional comments i am considering loading a jquery script only for ie6 thatreads the class of all divs in a certain section of the page and pushes to an arraycreates empty boxes off screen with only one of the classes applied at a timereads the applied css values for each boxreapplies these styles to the individual box somehow bearing in mind the order in which they are called and overwriting conflicting instructions as requiredpotential solution 2read the class of all divs in a certain section of the page and push to an arrayscan the document for links to style sheetsajax grab the stylesheets and traverse looking for matching names to those in class arrayapply styles as neededpotential solution 3create an ie6 only stylesheet containing the exact style to be applied as a unique name ie classblocks orange highlight becomes classblocksorangehighlighttraverse the document in ie6 and convert all spaces in class declarations to hyphens and reapply classes based on new style namesummary solution 1 allows the people at this company to apply any styles in the future and the script will adjust as needed however it does not allow for the chained style to be added only the individual style it is also processor intensive and time consuming but also the most likely to be converted into a plugin that could be used the world oversolution 2 is a potential nightmare to code but again will allow for an endless number of updates without breakingsolution 3 will require someone at the companty to hardcode the new styles every time they make a change and if they do not ie6 will breakironically the site whilst needing to conform to ie6 in a limited manner does not need to run wihtout javascript they have made the call have js or go away so consider all jquery and js solutions to be game ondid i mention how much i hate ie6anyway any thoughts or comments would be appreciatedi will continue to develop my own solution and if i thiscover one that can be turned into a jquery plugin i will post it here in the commentsregardsmikeedit added tldr to the top,"['javascript', 'jquery', 'html', 'css']" +56608,c communication between threads i am using net 35 and am trying to wrap my head around a problem not being a supreme threading expert bear with mei have a windows service which has a very intensive process that is always running i have put this process onto a separate thread so that the main thread of my service can handle operational tasks ie service audit cycles handling configuration changes etc etci am starting the thread via the typical threadstart to a method which kicks the process off call it workerthreadon this workerthread i am sending data to another server as is expected the server reboots every now and again and connection is lost and i need to reestablish the connection i am notified by the lost of connection via an event from here i do my reconnect logic and i am back in and running however what i easily started to notice to happen was that i was creating this worker thread over and over again each time not what i wantnow i could kill the workerthread when i lose the connection and start a new one but this seems like a waste of resourceswhat i really want to do is marshal the call ie my thread start method back to the thread that is still in memory although not doing anythingplease post any examples or docs you have that would be of usethanks,['c#'] +56634,what is the string volumename argument of mediastoreaudioplaylistsmembersgetcontenturi referring to i am wanting to query the members of a given playlist i have the correct playlist id and want to use a managedquery to look at the playlist members in questionwhat i have is thisprivate string columns mediastoreaudioplaylistsmembersplaylist id mediastoreaudioplaylistsmemberstitle uri membersuri mediastoreaudioplaylistsmembersgetcontenturivolume playlistidcursor tcursor managedquerymembersuri columns null null nulli do not know what the volume argument needs to be i have tried thismediastoreaudioplaylistsexternal content uritostring for the volume argumentthat gives me back a valid content uri that looks likecontentmediaexternalaudioplaylists2membershowever my cursor comes back null i probably am way off base i know what i want to do is very simple,['android'] +56640,why is the destructor of the class called twice apologies if the question sounds silly i was following experts in so and trying some examples myself and this is one of them i did try the search option but did not find an answer for this kindclass a public acouta contructionendl acouta destructionendlint main vectora t tpush backa after this line when the scope of the object is lostwhy is the destructor of the class called twice,['c++'] +56642,why javascript gettime is not a function i used the following functionfunction datediff var dat1 documentgetelementbyiddate1value alertdat1i get 20100401var dat2 documentgetelementbyiddate2value alertdat2 i get 20100413var oneday 24606010 hoursminutessecondsmillisecondsvar diffdays mathabsdat1gettime dat2gettimeonedayalertdiffdaysi get the error dat1gettime is not a function,['javascript'] +56649,what can explain stdcout not to thisplay anything for whatever reason stdcout does not thisplay anything with my application the description of my development environment followsi am working on a qt application using qt creator since qt creator cannot be launched from my station xp64 i am currently developping it with visual studio 2008 and the qt plugin by importing the pro project file everything seems fine and the application worksin some cases depending on command line arguments i do not want to launch the him just to thisplay a few sentences in the cli command line required arguments for instance i do not get any error but nothing is thisplayedthe corresponding code which i am sure is run is the classical following stdcout is this going to be thisplayed stdendldo you have any idea why nothing is thisplayed,['c++'] +56651,remove html tags from record need help to form the mysql query from table one column having the bellow contentrow1 this is first a hrefmytexttxtrowa from the tablerow 2 this is the second row img src mytextjpg my image is thererow 3 pthis is the third row my mytext is there prow 4 p classte mytextthis is the third row my text is there pthis is the table rows i try to search the keyword as mytext my query is select from table where colmn name like mytext i will get all the 4 rows as result but the result is wrong i need to get the correct output as only row 3 the reason this row only having the mytext inside the content all other are not in content but mytext having in all rowshow can i write the mysql query,['mysql'] +56654,ignore whitespace in html is there anything in htmlcss that tells the browser to ignore whitespace completelyso many times when you want to put say two images next to each other you try desperately to keep the html readable but the browser puts a space between themso instead of something like thisimg srcimagesminithingjpg altmy mini thing img srcimagesminithingjpg altmy mini thing img srcimagesminithingjpg altmy mini thing img srcimagesminithingjpg altmy mini thing you end up with thisimg srcimagesminithingjpg altmy mini thing img srcimagesminithingjpg altmy mini thing img srcimagesminithingjpg altmy mini thing img srcimagesminithingjpg altmy mini thing which is just so horrible,"['html', 'css']" +56655,iphoneos sdk remove corner rounding from views ipad problem hi guysthis might be a little bit picky but in the ipad splitviewcontroller setup there are 2 views each of the views has a very small black corner rounding this is probably the same with iphone apps toothis rounding is visible in the image below what i would like to do is remove the black rounding so the ui doesnt get these two little bumps along the bottom has anyone done this or know how to its surely possiblehopefully some one has seen this beforethanksimage link mirror,['iphone'] +56664,memory allocation for const in c how is memory allocated when i usepublic class myclass public const string myevent event other code,['c#'] +56683,java gc is there a way to determine which objects collected i am trying to monitor the gc activity in my app using verbosegc flag i can see there are full and minor collections but is there a way to determine subscrbing to eventsvm flagswhatever which objects actually collectedthanks,['java'] +56694,deciding among subprocess multiprocessing and thread in python i would like to parallelize my python program so that it can make use of multiple processors on the machine that it runs on my parallelization is very simple in that all the parallel threads of the program are independent and write their output to separate files i do not need the threads to exchange information but it is imperative that i know when the threads finish since some steps of my pipeline depend on their outputportability is important in that i would like this to run on any python version on mac linux and windows given these constraints which is the most appropriate python module for implementing this i am trying to decide between thread subprocess and multiprocessing which all seem to provide related functionalityany thoughts on this i would like the simplest solution that is portablethanks,['python'] +56696,debug windows service scenarioi have got a windows service written in ci have read all the google threads on how to debug it but i still cannot get it to worki have run pathtonetframeworkinstallutilexe cmyserviceexe it said the install was successful however when i run servicesmsc the service is not thisplayed at all anywhere if i go into task manager there is a process called myservicevshostexe pretty sure that is not it because it is a service not a processcan someone explain to meif i am supposed to see the service when i run servicesmscbearing in mind this is all being done on a local machine with no servers at allotheri am running vs2008editthis is all being done on my local machine i have no servers or access to anyalso i do not even know what the service does i want to debug it so i can walkthrough the code and see how it all works the code inside the service not the service itself for any of you smarty pants that might suggest i look at a templateedit 2none of these are workingeverytime i try something i get some message about having to use net start or install the serviceedit 3i am running vs2008i typed thiscwindowsmicrosoftnetframeworkv2050727installutilexe cdevrestarterbinreleaserestarterexei got thismicrosoft r net framework installation utility version 20507273053copyright c microsoft corporation all rights reservedrunning a transacted installationbeginning the install phase of the installationsee the contents of the log file for the cdevrestarterbinreleaserestarterexe assemblys progressthe file is located at cdevrestarterbinreleaseedtrestarterinstaloginstalling assembly cdevrestarterbinreleaserestarterexeaffected parameters are logtoconsole assemblypath cdevrestarterbinreleaserestarterexe logfile cdevrestarterbinreleaserestarterinstalogthe install phase completed successfully and the commit phase is beginningsee the contents of the log file for the cdevrestarterbinreleaserestarterexe assemblys progressthe file is located at cdevrestarterbinreleaserestarterinstalogcommitting assembly cdevrestarterbinreleaserestarterexeaffected parameters are logtoconsole assemblypath cdevrestarterbinreleaserestarterexe logfile cdevrestarterbinreleaserestarterinstalogthe commit phase completed successfullythe transacted install has completedcprogram filesmicrosoft visual studio 90vci then went to run servicesmsci can see nothing in therethere is a process in task manager called restartervshostexethat is iti only wanted to install and debug iti know it works as it it runs and does not crashbut the code was written by a friend and i want to understand the underlying code by walking through it in debug mode,['c#'] +56701,calling a gwt service in a different context than the gwt module base i have a gwt module with the xgwtmodulebase httphost8080foo and would like to call a gwt service which is located at httphost8080bar the reason is for example that i want to be able to share a gwt service between two different gwt client projectsall i have gotten to work so far is if the service is located within the module context ie httphost8080foobar works fine using remoteservicerelativepathbar in my service interfaceit seems that the remoteservicerelativepath only allows a value relative to the module base urlso is there some other way to accomplish what i am trying to accomplish,['java'] +56702,how to layer views i have a custommade view that extends the view class i would like 2 instances of my custom view layered directly on top of each other how should my layout file look to achieve this,['android'] +56710,ipad thismissing a uipopovercontroller i have a button inside the content of a uipopovercontroller this button runs a method called myactionmyaction has the form void myactionidsender so myaction receives the id of the caller buttonnow inside this method i would like to thismiss the uipopovercontroller but the only thing i have is the id of the caller button remember that the button is inside the uipopovercontrolleris there a way to thiscover the id of the uipopovercontroller given the button id i already havethanks,['iphone'] +56716,how to set pdf paragraph or font lineheight with itextsharp how can i change the lineheight of a pdf font or paragraph using itextsharp,"['c#', 'asp.net', 'css']" +56717,how to delete duplicates on a mysql table i need to delete duplicated rows for specified sid on a mysql tablehow can i do this with an sql querydelete duplicated titles from table where sid 1something like this but i do not know how to do it,['mysql'] +56732,a regex to match a substring that is not followed by a certain other substring i need a regex that will match blahfooblah but not blahfoobarblahi want it to match only foo and everything around foo as long as it is not followed by bari tried using this foobar which is fairly close but it matches blahfoobarblah the negative look behind needs to match anything and not just barthe specific language i am using is clojure which uses java regexes under the hoodedit more specifically i also need it to pass blahfooblahfoobarblah but not blahfoobarblahblah,['java'] +56734,com interface guid i am not much into com interfaces so i have a small question say i have this codeguid148bd528a2ab11ceb11f00aa00530503 interfacetypecominterfacetypeinterfaceisiunknowninternal interface ienumworkitems preservesig int nextin uint requestcount out out systemintptr names out out uint fetched void skipin uint count void reset void cloneout marshalasunmanagedtypeinterface out ienumworkitems enumworkitemshow do i know that 148bd528a2ab11ceb11f00aa00530503 corresponds to ienumworkitems vs85aspxlike if i want to know this interfaces guid vs85aspx where do i find it,"['c#', '.net']" +56741,is the ipad page turn transition included in the sdk is there a page turn transition included in the ipad sdk that i can use or is that all coded by hand with core graphics,"['ios', 'iphone']" +56755,i am storing click coordinates in my db and then reloading them later and showing them on the site where the click happened how do i make sure it loads in the same place that is it basically storing the click coordinates is obviously the simple step but once i have them if the user comes back and their window is smaller or larger the coordinates are wrong am i going about this in the wrong way should i also store an element iddom reference or something of that naturealso this script will be run over many different websites with more than one layout is there a way to do this where the layout is independent of how the coordinates are storedthanks,['javascript'] +56771,looping through macro varargs values if i define some macrodefine fooargs do somethingis there some way to actually loop through args rather than pass it along to another function something likedefine fooargs for int i 0 i sizeofargs i do something with argsi,['c'] +56776,what is the fastest way to send 10 http requests in python i am opening a file which has 10 urls i need to send an http request to each url and print the status code i am using python 26 and so far looked at the many confusing ways python implements threadingconcurrency i have even looked at the python concurrence library but cannot figure out how to write this program correctly has anyone come across a similar problem i guess generally i need to know how to perform thousands of tasks in python as fast as possible i suppose that means concurrentlythank youigor,['python'] +56791,limiting characterswords in view ruby on rails i am thisplaying recent comments on the home page of a very simple blog application i am building in ruby on rails i want to limit the number of characters that are thisplayed from the body column of the comments table i am assuming i can just add something to the end of the code for h commentbody but i do not know what that would be yet as i am new to both ruby and rails here is the code i have in the viewspostsindexhtmlerb file commentfindall order created at desc limit 5each do comment p h commentname commented on link to hcommentposttitle commentpost br h commentbody i time ago in wordscommentcreated at agoi p end,"['ruby-on-rails', 'ruby']" +56794,find a string within another string search backwards int dd some stringindexofsomething10i want indexof to search some string starting at position 10 and searching backwards is this possible,['c#'] +56795,microsoft c language reference whenever any question is asked and a reference text is needed i never see msdn c language reference being referredi was browsing through it and i personally feel that it is extremely well writtenis there some specific reason it is not used as often as a standardis it because it contains some vc specific features,"['c++', 'c']" +56796,cc efficient bit array can you recommend efficientclean way to manipulate arbitrary length bit arrayright now i am using regular intchar bitmask but those are not very clean when array length is greater than datatype lengthstd vectorbool is not available for methanks,"['c++', 'c']" +56822,what is the fastest collection in c to implement a prioritizing queue i need to implement a fifo queue for messages on a game server so it needs to as fast as possible there will be a queue for each user the queue will have a maxiumem size lets say 20 the size would not change during runtimei need to prioritize messages only if the queue reaches its maximum size by working backwards and removing a lower priority message if one exists before adding the new messagea priority is an int with possible values of 1 3 5 7 10there can be multiple messages with the same prioritya message cannot change its priority once allocatedthe application is asynchronous so access to the queue needs to be lockedi am currently implementing it using a linkedlist as the underlying storage but have concerns that searching and removing nodes will keep it locked for too longheres the basic code i have at the momentpublic class actionqueue private linkedlistclientaction actions new linkedlistclientaction private int maxsize summary initializes a new instance of the actionqueue class summary public actionqueueint maxsize maxsize maxsize public int count get return actionscount public void enqueueclientaction action lock actions if count maxsize actionsaddlastaction else linkedlistnodeclientaction node actionslast while node null if nodevaluepriority actionpriority actionsremovenode actionsaddlastaction break node nodeprevious public clientaction dequeue clientaction action null lock actions action actionsfirstvalue actionsremovefirst return action,['c#'] +56825,good hash function for a 2d index i have a struct called point point is pretty simplestruct point row row column column some other code for addition and subtraction of points is there toorow and column are basically glorified ints but i got sick of accidentally transposing the input arguments to functions and gave them each a wrapper classright now i use a set of points but repeated lookups are really slowing things down i want to switch to an unordered setso i want to have an unordered set of points typically this set might contain for example every point on a 80x24 terminal 1920 points i need a good hash function i just came up with the followingstruct pointhash public stdunary functionpoint stdsize t result type operatorconst argument type val const return valrowvalue 10 valcolvalue however i am not sure that this is really a good hash function i wanted something fast since i need to do many lookups very quickly is there a better hash function i can use or is this ok,['c++'] +56830,android dialog width i cannot seem to control the dialog width i have a simple layout like soxml version10 encodingutf8linearlayout xmlnsandroid androidorientationvertical androidlayout widthfill parent androidlayout heightfill parent androidthemeandroidstylethemedialog scrollview androidorientationvertical androidlayout widthfill parent androidlayout heightfill parent linearlayout androidorientationvertical androidlayout widthfill parent androidlayout heightfill parent textview androidididname prompt view androidlayout widthfill parent androidlayout heightwrap content androidtextstringname prompt androidpadding10dip edittext androidididname inp androidlayout widthfill parent androidlayout heightwrap content androidlines1 androidmaxlines1 androidmaxlength48 androidinputtypetext textview androidididt1 prompt view androidlayout widthfill parent androidlayout heightwrap content androidtextstringt1 prompt androidpadding10dip spinner androidididt1 inp androidlayout widthfill parent androidlayout heightwrap content androidlines1 androidmaxlines1 androidmaxlength48 androidinputtypetext androidsinglelinetrue androidlayout weight1 androidentries arrayt1 allowed values linearlayout scrollviewlinearlayoutfor some reason the dialog is only wide enough for the text input field about 11 chars wide how do i make the dialog width fill the screen,['android'] +56844,how to stop page redirect i need to stop all the page redirection thro javascripti have some script which will redirect the page to some other locationhow can i stop all the page redirection in my page thro jquery or javascript,"['javascript', 'jquery']" +56859,recognize objects in image hello i am in the process of doing a school project where we have a robot driving on the ground in between flamingo plates we need to create an algorithm that can identify the locations of these plates so we can create paths around them we are using a star for thatso far have we worked with aforged library and we have created the following class the only problem with this is that when it create the rectangles dose it not take in account that the plates are not always parallel with the camera border and it that case will it just create a rectangle that cover the whole plate so we need to some way find the rotation on the object or another way to identify thisi have create an image that might help explain thisimage the describe the problem any help on how i can do this would be greatly appreciatedany other information or ideers are always welcomepublic class pastemap private bitmap image private bitmap processedimage private rectangle rectangels public void initializebitmap image thisimage image public void process processedimage image processedimage applyfiltersprocessedimage processedimage filterwhiteprocessedimage rectangels extractrectanglesprocessedimage rectangels filterrectanglesrectangels processedimage drawrectangelstoimageprocessedimage rectangels public bitmap getprocessedimage get return processedimage public rectangle getrectangles get return rectangels private bitmap applyfiltersbitmap image image new contrastcorrection2applyimage image new gaussianblur10 10applyimage return image private bitmap filterwhitebitmap image bitmap test new bitmapimagewidth imageheight for int width 0 width imagewidth width for int height 0 height imageheight height if imagegetpixelwidth heightr 200 imagegetpixelwidth heightg 200 imagegetpixelwidth heightb 200 testsetpixelwidth height colorwhite else testsetpixelwidth height colorblack return test private rectangle extractrectanglesbitmap image blobcounter bc new blobcounter bcfilterblobs true bcminwidth 5 bcminheight 5 process binary image bcprocessimage image blob blobs bcgetobjectsimage false process blobs listrectangle rects new listrectangle foreach blob blob in blobs if blobarea 10 rectsaddblobrectangle return rectstoarray private rectangle filterrectanglesrectangle rects listrectangle rectangles new listrectangle foreach rectangle rect in rects if rectwidth 75 rectheight 75 rectanglesaddrect return rectanglestoarray private bitmap drawrectangelstoimagebitmap image rectangle rects bitmapdata data imagelockbitsnew rectangle0 0 imagewidth imageheight imagelockmodereadwrite pixelformatformat24bpprgb foreach rectangle rect in rects drawingfillrectangledata rect colorred imageunlockbitsdata return image,['c#'] +56862,may i use comgooglecode prefix for my packages i have a hobby opne source java project hosted at google code linksetmay i use a prefix comgooglecodelinkset as a package name for this projectpsi dont own orglinkset domain but i like the name,['java'] +56887,why no replace method defined on the set interface currently i have to write the following to update an element already contained in a setset myset element e1 new element element e2 new element e1 and e2 are different instances but equalsupdate the element contained into the setif mysetcontainse2 mysetremovee2 mysetadde2 that doesnt look nice is there an alternative,['java'] +56901,python string formatting too slow i use the following code to log a map it is fast when it only contains zeroes but as soon as there is actual data in the map it becomes unbearably slow is there any way to do this fasterlog file opentestfile wfor i x in i start i interval for i in rangelength log filewrite5d 83f 13g 13g 13g 13g 13g 13gn i x map0i map1i map2i map3i map4i map5i,['python'] +56907,is it possible to roll a significantly faster version of sqrt in an app i am profiling i found that in some scenarios this function is able to take over 10 of total execution timei have seen thiscussion over the years of faster sqrt implementations using sneaky floatingpoint trickery but i do not know if such things are outdated on modern cpusmsvc 2008 compiler is being used for reference though i would assume sqrt is not going to add much overhead thoughsee also here for similar thiscussion on modf functionedit for reference this is one widelyused method but is it actually much quicker how many cycles is sqrt anyway these days,['c++'] +56909,how do i match contents of an element in xpath lxml i want to parse html with lxml using xpath expressions my problem is matching for the contents of a tagfor example given the a hrefhttpsomethingexampleaelement i can match the href attribute using ahrefhttpsomethingbut the given the expressionaexampleor evenacontainsexamplelxml throws the invalid node predicate exceptionwhat am i doing wrongeditexample codefrom lxml import etreefrom cstringio import stringiohtml a hrefhttpsomethingexampleaparser etreehtmlparsertree etreeparsestringiohtml parserprint treefindatextexampletagexpected output is a i get syntaxerror invalid node predicate,['python'] +56916,high memory usage for dummies i have just restarted my firefox web browser again because it started stuttering and slowing down this happens every other day due to my understanding of excessive memory usagei have noticed it takes 40m when it starts and then by the time i notice slow down it goes to 1g and my machine has nothing more to offer unless i close other applicationsi am trying to understand the technical reasons behind why its such a difficult problem to solvemozilla have a page about high memory usagebut i am looking for a slightly more in depth and satisfying explanation not super technical but enough to give the issue more respect and please the crowd heresome questions i am already pondering they could be silly so take it easywhen i close all tabs why does not the memory usage go all the way downwhy is there no limits on extensionsthemesplugins memory usagewhy does the memory usage increase if it is left open for long periods of timewhy are memory leaks so difficult to find and fixapp and language agnostic answers also much appreciated,['c++'] +56917,can i change the size of uiactivityindicator whatever size i give to it while allocation it shows fixed size only is it possible to increase it codeactivityindicator uiactivityindicatorview alloc initwithframe cgrectmake14200 21200 800 800self view addsubviewactivityindicatoractivityindicator sizetofitactivityindicatorautoresizingmask uiviewautoresizingflexibleleftmargin uiviewautoresizingflexiblerightmargin uiviewautoresizingflexibletopmargin uiviewautoresizingflexiblebottommarginactivityindicatorhideswhenstopped yesactivityindicatoractivityindicatorviewstyle uiactivityindicatorviewstylewhitelarge,['iphone'] +56920,android how to hide a listview item how can you hide an item in a listview or at least set its height to zeroi have tried setting the visibility of the view to gone but it still maintains the items space height,['android'] +56921,how to get a token from a lucene tokenstream i am trying to use apache lucene for tokenizing and i am baffled at the process to obtain tokens from a tokenstreamthe worst part is that i am looking at the comments in the javadocs that address my question 0 1apicoreorgapacheluceneanalysistokenstreamhtmlincrementtoken2829somehow an attributesource is supposed to be used rather than tokens i am totally at a loss can anyone explain how to get tokenlike information from a tokenstream,['java'] +56931,gwt layout panels vs css layout i read an article entitled tags first gwt in which the writer suggests using gwt for eventhandling and css for layout i just do not know whether the benefit of gwts crossbrowser compatibility goodness outweighs the flexibility offered by pure css layoutgwtgwt 20 has some snazzy layout panels but to get them to resize properly you really need to build the entire panel containment tree from the root panel down it is an allornothing thing it seemscssyou can use css to layout an application too and i am inclined to do just that if only to justify my purchase of several books touting the semantic markup gospel the downside might be crossbrowser incompatibilities the prevalence of which i have yet to determinewhich way to gowhat is your opinion are crossbrowser problems bad enough and prevalent enough to warrant ditching my css books and building with gwt layout panels,['css'] +56933,best way of invoking getter by reflection i need to get the value of a field with a specific annotation so with reflection i am able to get this field object the problem is that this field will be always private though i know in advance it will always have a getter method i know that i can use setaccesibletrue and get its value when there is no permissionmanager though i prefer to invoke its getter methodi know that i could look for the method by looking for getfieldname though i know for example for boolean fields are sometimes named as isfieldnamei wonder if there is a better way to invoke this getter many frameworks use getterssetters to access the attributes so maybe they do in another waythanks,['java'] +56938,jquery datepicker mindate maxdate i have the two following datepicker objects but i cannot get what i want as i am getting stuck with the mindate and maxdate optionsthis is to restrict the dates to future dateswhat i want restrict the dates from current date to 30 years timewhat i get restrict the dates from current date to 10 years time datepickerfuturedatepicker showon button buttonimage calendargif buttontext click to select a date durationfast changemonth true changeyear true dateformat ddmmyy constraininput true mindate 0 maxdate 30y buttonimageonly true this is to restrict to select only past dateswhat i want restrict the dates from current date to 120 years ago timewhat i get restrict the dates from current date to 120 years ago time but when i select a year the maximum year will reset to selected year eg what i would get when page load from fresh is 18902010 but if i select 20 the year select box reset to 188020 datepickerpastdatepicker showon button buttonimage calendargif buttontext click to select a date durationfast changemonth true changeyear true dateformat ddmmyy constraininput true yearrange 1200 maxdate 0 buttonimageonly truei need help with both datepicker object any help would be very much appreciated,['jquery'] +56947,get the full uri from the href property of a link i would like to have a confirmation on some pointmy goal is to always get the same string which is the uri in my case while reading the href property from a link examplea hreftesthtm with base url a hreftesthtm with base url a href with base url any folder from i need to get from the 3 situations above or any other identical stringafter some tests it appears that my a dom nodehref always return the fullqualified uri including the which should be okay for what i want jquery has a different behaviour and my a dom nodeattrhref returns the content text that appears inside the html so my trick is to use my a dom nodeget0href to get the full urithe question is can i rely on this,['javascript'] +56954,how to thismisspopoveranimated on ipad with uipopovercontroller in mkmapview sdk32 i have a mkmapview also a uipopovercontrollerdelegate with annotations this mapview has in the mktestmapviewh file a uipopovercontroller popovercontroller defined in the interface and a property nonatomic retain uipopovercontroller popovercontroller defined outside of the interface section this controller is synthesized in the mktestmapviewm file and it is released in the voiddealloc section the annotations in this mapview have rightcalloutaccessoryviews defined to the following voidmapviewmkmapview mapview2 annotationviewmkannotationview aview calloutaccessorycontroltappeduicontrol controlcgpoint lefttoppoint mapview2 convertcoordinateaviewannotationcoordinate topointtoviewmapview2int boxdylefttoppointyint boxdxlefttoppointxnslogndxddydnboxdxboxdypopovercontroller uipopovercontroller alloc initwithcontentviewcontrollercontrollerpopovercontrollerdelegate selfcgsize maximumlabelsize cgsizemake3200f60fpopovercontrollerpopovercontentsize maximumlabelsizecgrect rect cgrectmakeboxdx boxdy 3200f 60fpopovercontroller presentpopoverfromrectrect inviewselfview permittedarrowdirectionsuipopoverarrowdirectionright animatedyesnow here comes the fun part first of all i am not sure if i need maximumlabelsize and the rect to be the same size i am new to the popovercontroller so i am playing this by earokay the popover shows now to thismissing it i can click anywhere on mapview2 and the popover goes awaybut i need the user to click a button in the view if they change anything urghthe docs showto thismiss a popover programmatically call the thismisspopoveranimated method of the popover controllerwell here is the problem by definition of how the popovercontroller works you are clicking inside the view of the thisplayed popover to click the button but have to trigger the thismisspopoveranimated method of the controller that launched this popover view in my case the popovercontroller inside the mktestmapviewm filenow having said all that remember popovercontroller release does not happen until voiddealloc popovercontroller release mapview release super deallocso do i just do the following inside the button messy but may workassuming my popover view is a tableview in the voidtableviewuitableview tableview didselectrowatindexpathnsindexpath indexpath mktestmapview mktestmapview mktestmapview alloc initmktestmapview popovercontrollerthismisspopoveranimatedyeshere is my issue i cannot figure out whether doing the above gives me a reference if there is such a thing to the existing view that is on the screen and therefore the view that is the owner of that popovercontroller if it is as simple as self parentview popovercontrollerthismisspopoveranimatedyesi will shoot myself cos i do not think that is the correct syntax eitherthis should be easyyet i am lost probably just frustrated with so many ipad differences that i am learningcan anyone explain more,['iphone'] +56967,why does casting a nan to a long yield a valid result in the sample code below i am dividing by zero which when i step through it with the debugger the dividend divisor yields an infinity or nan if the divisor is zero when i cast this result to a long i get a valid result usually something like 9223372036854775808 why is this cast valid why does not it stop executing throw an exception for example rather than assign an arbitrary valuedouble divisor 0double dividend 7long result longdividend divisor,['c#'] +56970,how come you cannot catch code contract exceptions systemdiagnosticscontractscontractexception is not accessible in my test project note this code is purely myself messing around with my shiney new copy of visual studio but i would like to know what i am doing wrongi am using the professional edition of vs therefore i do not have static checking in order to still use code contracts which i like i figured the only way my method can work is to catch the exception that is thrown at runtime but i am not finding this possibletestmethodtestmethod expectedexceptiontypeofsystemdiagnosticscontractscontractexceptionpublic void returning a value less than one throws exception var person new person personnumbermethodpublic int number contractensurescontractresultint 0 return 1errorerror 1 systemdiagnosticscontractscontractexception is inaccessibledue to its protection leveleditafter some more thought i have come to the conclusion thiscussed in the comments as well as the following given a method if this had a requirement which could be expressed in code contract form i would write tests as suchtestmethodexpectedexceptiontypeofargumentexceptionpublic void value input must be greater than zero arrange var person new person act personnumber1this would ensure the contract is part of the code and will not be removed this would require the code contract to actually throw the specified exception however in some cases this would not be required however,['c#'] +56988,how do i add a function to an element via jquery i want to do something like thisdynamichtmlformvalidate function return truedynamichtmlform savebuttonclickfunction if thisclosestdynamichtmlformvalidate return false return trueand then when i have a form of class dynamichtmlform i want to be able to provide a custom validate functionmydynamichtmlformvalidate function do some validation if there are errors return false return truebut i get this when i do thisthisclosestdynamichtmlformvalidate is not a functionis what i have described even possible if so what am i doing wrong,"['javascript', 'jquery']" +56991,read json text file into net application i have a configuration file in the following json format key1 value1 key2 value2 key3 false key4 10 the user can setunset the configuration values using a text editor i however need to read it in my c application whats the best way to do so for json the above keys are not associated with a class,['c#'] +56992,what is best way to pass multiple query parameters to a restful api i am designing restful apis and would like some advice on designing an api where the caller wants to query records based on more than one search parameteri have only seen restful apis that use one parameterhow should i do thiseg if i have created a restful api for a list of contacts how would i format a call that returned all contacts with firstnamebob surnamesmithi guess it should be a get because i am retrievingmy only thoughts aresurnamesmithbut that does not seem right please advicealso do any of the php frameworks support this eg symfony konstrukt etc,['php'] +57011,how big of a jump will it be to go from c to objective c how hard will it be to transfer from my existing expertise in c to building apps for the ipadiphone in objective c,"['c#', 'objective-c']" +57015,ffmpeg c api documentationtutorial i am trying to find documentation to use the ffmpeg c api it seems that only command line documentation is availableis there any good documentationtutorialslinks available,['c'] +57016,how to make a cell on a uitableview not selectable i have a cell that i am inserting to the top of a uitableview how can i make sure that when the user clicks on the cell it does not show the blue selected indicator,"['iphone', 'objective-c']" +57028,transferring binary data through a soap webservice i have a web service that returns the binary array of an object is there an easier way to transfer this with soap or does it need to be contained in xml it is working but i had to increase the send and receive buffer to a large value how much is too muchtransferring binary in xml as an array seems really inefficient but i cannot see any way to add a binary attachment using net,"['c#', '.net']" +57033,customizing number of page links rendered with will paginate i am using the will paginate gem for my rails project and it is working beautifully unfortunately on paginated result sets with a larger number of pages the link section is too wide instead ofa previous 1 2 a 5 6 7 8 9 10 11 12 13 a 18 19 next ai would like to show a previous 1 2 a 5 6 7 8 9 a 18 19 next ahow can i reduce the number of page links being rendered i looked at the will paginate docs on github but could not find a solution thanksmoe,['ruby-on-rails'] +57040,how to evaluate a custom math expression in python i am writing a custom dice rolling parser snicker if you must in python basically i want to use standard math evaluation but add the d operatorxdysum 0for each in rangex sum randint1 yreturn sumso that for example 1d62d62d6724d100 51162725393859 84i was using regex to replace all ds with the sum and then using eval but my regex fell apart when dealing with parentheses on either side is there a faster way to go about this than implementing my own recursive parsing perhaps adding an operator to evaledit i seem to have given a bad example as the above example works with my current version what i am looking for is some way to evaluate say 56d6d721d4by fell apart i just meant that my current regex expression failedi have been too vague about my failure sorry for the confusion heres my current codedef evaldiceroll matchgroup roll split roll matchgroupgrouprollsplitd print roll split roll list for die in rangeintroll split0 roll randomrandint1introll split1 roll listappendrolldef evalrollroll if not roll return 0 rollpattern recompileprolld roll string rollpatternsubevaldice rolowerfor this 1d64d100 works just fine but 1d64d100 or even 1d64d100 fails,['python'] +57041,javalangreflectproxy returning another proxy from invocation results in classcastexception on assignment so i am playing with geotools and i thought i would proxy one of their dataaccess classes and trace how it was being used in their codei coded up a dynamic proxy and wrapped a featuresource interface in it and off it went happily then i wanted to look at some of the transitive objects returned by the featuresource as well since the main thing a featuresource does is return a featurecollection featuresource is analogous to a sql datasource and featurecollection to an sql statementin my invocationhandler i just passed the call through to the underlying object printing out the target classmethodargs and result as i went but for calls that returned a featurecollection another interface i wrapped that object in my proxy the same class but a new instance should not matter should it and returned it bam classcast exceptionjavalangclasscastexception proxy5 cannot be cast to orggeotoolsfeaturefeaturecollection at proxy4getfeaturesunknown source at myclassmytestmethodmyclassjava295 the calling codefeaturesourcesimplefeaturetype simplefeature featuresource create the fsfeaturesource featuresourcesimplefeaturetype simplefeature featuresourceproxynewinstancefeaturesource featuresfeaturesourcegetbounds okfeaturesourcegetsupportedhints okdefaultquery query1 new defaultquerydefaultqueryallfeaturecollectionsimplefeaturetype simplefeature results featuresourcegetfeaturesquery1 explosion herethe proxypublic class featuresourceproxy implements javalangreflectinvocationhandler private object targetprivate listsimplefeature featurespublic static object newinstanceobject obj listsimplefeature features return javalangreflectproxynewproxyinstance objgetclassgetclassloader objgetclassgetinterfaces new featuresourceproxyobj featuresprivate featuresourceproxyobject obj listsimplefeature features thistarget objthisfeatures featurespublic object invokeobject proxy method m object argsthrows throwableobject result nulltry ifgetfeaturesequalsmgetname result interceptgetfeaturesm args else result minvoketarget args catch exception e throw new runtimeexceptionunexpected invocation exception egetmessage e return resultprivate object interceptgetfeaturesmethod m object args throws exception return newinstanceminvoketarget args featuresis it possible to dynamically return proxies of interfaces from a proxied interface or am i doing something wrongcheers,['java'] +57048,problem with stdmap and stdpair i have a small program i want to execute to test somethinginclude mapinclude iostreamusing namespace stdstruct pos float xi float xf bool operator pos other return thisxi otherxi struct val float fint main map pos val m struct pos k1 010 struct pos k2 1015 struct val v1 55 struct val v2 123 minsertstdpair pos valk1v1 minsertstdpair pos valk2v2 return 0the problem is that when i try to compile it i get the following error g m2cpp o mtestin file included from usrincludec44bitsstl treeh64 from usrincludec44map60 from m2cpp1usrincludec44bitsstl functionh in member function abool stdless tpoperatorconst tp const tp const with tp posausrincludec44bitsstl treeh1170 instantiated from astdpairtypename std rb tree key val keyofvalue compare allociterator bool std rb tree key val keyofvalue compare alloc m insert uniqueconst val with key pos val stdpairconst pos val keyofvalue std select1ststdpairconst pos val compare stdless pos alloc stdallocatorstdpairconst pos val ausrincludec44bitsstl maph500 instantiated from astdpairtypename std rb tree key stdpairconst key tp std select1ststdpairconst key tp compare typename allocrebindstdpairconst key tp otheriterator bool stdmap key tp compare allocinsertconst stdpairconst key tp with key pos tp val compare stdless pos alloc stdallocatorstdpairconst pos val am2cpp30 instantiated from hereusrincludec44bitsstl functionh230 error no match for aoperatora in a x yam2cpp9 note candidates are bool posoperator pos i thought that declaring the operator on the key would solve the problem but its still therewhat could be wrongthanks in advance,['c++'] +57055,project euler question 14 collatz problem the following iterative sequence is defined for the set of positive integersn n2 n is evenn 3n 1 n is oddusing the rule above and starting with 13 we generate the following sequence13 40 20 10 5 16 8 4 2 1it can be seen that this sequence starting at 13 and finishing at 1 contains 10 terms although it has not been proved yet collatz problem it is thought that all starting numbers finish at 1which starting number under one million produces the longest chainnote once the chain starts the terms are allowed to go above one millioni tried coding a solution to this in c using the bruteforce method however it seems that my program stalls when trying to calculate 113383 please advise include stdiohdefine limit 10int iterationint value ifvalue20 return value2 else return 3value1int count iterationsint value int count1 printfdn value whilevalue1 valueiterationvalue printfdn value count return countint main int iteration count0 max0 int icount for i1 ilimit i printfcurrent iteration dn i iteration countcount iterationsi if iteration countmax maxiteration count counti iteration countcount iterations113383 printfcount dni dnmaxcount,['c'] +57059,customizing section indexes in uitableview in iphone application does any one have tried to customize default section index thisplayed in uitableviewi want to modify the appearance of uitableview sectionindexis it possible to customize it is there any delegate methods available for this what delegate methods should i use if above questions answer is yes,"['iphone', 'objective-c']" +57061,building a nspredicate for a filter just wondering what the best way to build a nspredicate is if some filters are optionalthis is basically for a filter so if some options are not selected i do not to filter by themeg if i have option1 and option2 set for the filternspredicate predicate nspredicate predicatewithformatoption1 and option2 otherwise if just option1nspredicate predicate nspredicate predicatewithformatoption1 the key being there are 10 different options to filter so i do not want to have to code for the 10x10 possible combinationsthanks,"['iphone', 'objective-c']" +57069,what is a good way to do countif in python i want to count how many members of an iterable meet a given condition i would like to do it in a way that is clear and simple and preferably reasonably optimalmy current best ideas aresummeets conditionx for x in my listandlenx for x in my list if meets conditionxthe first one being iterator based is presumably faster for big lists and it is the same form as youd use for testing any and all however it depends on the fact that inttrue 1 which is somewhat uglythe second one seems easier to read to me but it is different from the any and all formsdoes anyone have any better suggestions is there a library function somewhere that i am missing,['python'] +57072,how to implement properly plugins in c i am trying to add plugins to my game and what i am trying to implement is thisplugins will be either mine or 3rd partys so i would like a solution where crashing of the plugin would not mean crashing of the main application methods of plugins are called very often for example because of drawing of game objectswhat i have found so far1 simple concept that seems like it should work nicely since plugins are used in my game for every round i would suffice to add the restart method and if a plugin is no longer needed unload method gc should take care of that2 managed extensibility framework my program should work on net 35 and i do not want to add any other framework separately i want to write my plugin system myself therefore this solution is out of question 3 microsoft provides but according to a few articles i have read it is very complex4 different appdomains for plugins according to marc gravell different appdomains allow isolation unloading of plugins would be easy what would the performance load be i need to call methods of plugins very often to draw objects for exampleusing application domains a few tutorials on java2scomcould you please comment on my findings new approaches are also welcomed thanks,['c#'] +57083,simplifying fully qualified names in eclipse does someone know a plugin for eclipse that replaces fully qualified java class names with the simple one and the corresponding import where possible it would be even better if it could be performed as a save action,['java'] +57087,how to center drawabletop and text vertically on the button in android i have the button defined as followsbutton androiddrawabletopdrawableico androidgravitycenter androidididstartbutton2x2 androidtextstringwidget2x2startbtnlabel androidlayout width0dip androidlayout heightfill parent androidlayout weight1 androidbackgrounddrawablewidgetbtn bgthe problem is that drawabletop image is aligned to the top border of the button view i would like to center it together with text label vertically on the button androidgravity seems to work only on text label it does not affect drawabletop positioningi was able to center it vertically using androidpaddingtop but that does not seem to be a good idea i guess it would not work properly on different screen resolutionsize,['android'] +57108,clickonce start menu icon how do i set the icon for my start menu shortcut when i deploy and install my application with clickonceplatform visual studio 2010 professional beta 1,"['c#', '.net']" +57112,sending a json object to an aspnet web service using jquery ajax function i want to create object on the client side of aspx page and i want to add functions to these javascript classes to make easier the life actually i can get and use the objects derived from the server side classes which returns from the services when i wanted to send objects from the client by jquery ajax methods i could not do it this is my javascript classesfunction classandmark mark lesson thislesson lesson thismark markfunction student name surname classandmark thisname name thissurname surname thisclassandmark classandmarkand this is a method for student class to call web servicejsclassprototypefsavetodb ajax type post contenttype applicationjson charsetutf8 url wssaveobjectasmxfsavetodb data this might be jsonstringifythis web service method has a parameter name is obj if i do not send data with parameter i am getting this error invalid web service call missing value for parameter obj should i send it like that data obj jsonstringifythis i tried to wrap this with parameter like that data jsonstringify obj this but i got this error cannot convert object of type systemstring to type systemcollectionsgenericidictionary2systemstringsystemobject datatype json to create javascript object and call its method to send it toward web serviceactually i do not know what should be definition of classes and methods on the server side but i thinkclass classandmark public string lesson public string mark class student public string name public string surname public classandmark classandmark web service is below but again i could not get what should be instead of the webmethodpublic student fsavetodb obj how can i convert input parameterparameters of method in the server side object sql operations srting qinsert insert into tablename values return new student name deserialize obj and pass its name value surname deserialize obj and pass its surname value classandmark deserialize obj and pass its classandmark value,"['c#', 'jquery']" +57150,struct bitfield max size c99 c what is maximal bit width for bit struct fieldstruct i long long i127can i define a bit field inside struct with size of bitfield up to 128 bit or 256 bit or larger there are some extrawide vector types like sse2 128bit avx1avx2 256bit avx512 512bit for next xeon phis registers and also extensions like int128 in gcc,"['c++', 'c']" +57152,how to scale a php application servers mysql memcache i am currently creating a website for a social project in switzerlandand before there is an overflow of user i want to prepare the application to scalei answered by myself many questions but some are lefti explain what i want to dofirstat the begining the application will have only one server short time with dns php mysql data and memcachesecondthen i will split them in twodns mysql memcachedata phpthirdhere is the problem i do not know how to do it exactly here to keep the application running welli could do front load balancer memcache dnsweb 1 php dataweb 2 php datamysqlthis would be the scheme all php sessions are kept in the dbbut how do i sync the datado i run a rsync to keep them up to datedo i put them on a separate thisk network thisk to be sure but in this case how can i do in case of user uploads and if the website gets more success and we have to go on greater structures wouldnt it create some latency on updates or would it be a good thing to go directly to amazons web services some infosi use codeigniter as frameworki use linux as webserver thistribution not chosen now but should be debianthanks in advance for your answers,['php'] +57179,encrypting cookies in php how can i encrypt and later decrypt a value of a cookie in php how secure will the encryption be,['php'] +57186,implementing a soap 12 server with rails 3 soap why would you use thati am using ruby enterprise edition and rails 3 to write my web application the application uses ustreams watershed white label broadcasting services to provide live streaming for my users unfortunately i have hit a snag during development watershed allows an application to provide it is own authentication layer through the implementation of a soap service on the application side of things this authentication layer must be implemented in soap 12 to work with watershed to my great thismay it seems that the ruby community has moved on past yeold soap towards a brighter future filled with rest and unicornsthis makes me happy 9 of the time however right now i need to make a soap 12 endpoint in my shiny new rails 3 applicationif anyone has any suggestions or libraries that i can use i would be very thankfulthings i have done alreadytried the built in soap support in ruby unfortunatly it seems that it does not support soap 12looked at wso2 but did not want to build an extensive set of ruby extensions on my server just to support soapthought about hardcoding xml responses before deciding that i am a lazy programmer,"['ruby-on-rails', 'ruby']" +57187,allocating unmanaged memory in c i am writting a program in c that uses a c library and for some reason i need to allocate an unmanaged buffer to pass it to the lib is there a way to do this in c basically i would just need to do a malloc in cthanks,['c#'] +57201,how do ruby and python implement their interactive consoles when implementing the interpreter for my programming language i first thought of a simple console window which allows the user to enter some code which is then executed as a standalone program as a shellbut there are severe problems if every line of code the user enters is handled as a standalone program it has to go through the tokenizer and parser and is then just executed by the interpreter what about functions then how can the pythonruby interactive consoles idle irb share the code how is the code entered handledexample def x printblah xwhere is the function stored so it can be called at any time againhow can the interactive console take everything entered as obviously one program without executing everything over and over again,"['python', 'ruby']" +57212,named and optional parameters and wcf so net 4 added named and optional parameters which are pretty sweet i do not need to make as many 1 line overload methodswill that work over wcf,['.net'] +57217,is there a gui framework that uses html and css to build guis i mean other than a browser of course i am talking about building native applications with html and css not web applications but real native guisi wonder if such a thing existsand what do you think of such a beast what would the proscons of such a system be,"['html', 'css']" +57219,how to get c enum description from value possible duplicategetting attributes of enumas value i have an enum with description attributes like thispublic enum myenum name1 1 descriptionhere is another hereisanother 2 descriptionlast one lastone 3i found this bit of code for retrieving the description based on an enumpublic static string getenumdescriptionenum value fieldinfo fi valuegettypegetfieldvaluetostring descriptionattribute attributes descriptionattributefigetcustomattributes typeofdescriptionattribute false if attributes null attributeslength 0 return attributes0description else return valuetostringthis allows me to write code likevar myenumdescriptions from myenum and in enumgetvaluestypeofmyenum select new id intn name enumerationsgetenumdescriptionn what i want to do is if i know the enum value eg 1 how can i retrieve the description in other words how can i convert an integer into an enum value to pass to my getdescription method,['c#'] +57224,objectivec and use of selimp another question of mine about optimizing objective c programs inspired the following does anyone have a short example using sel and imp when themethod has two or more integers for input,['objective-c'] +57225,python fabric how to handle arbitrary remote shell prompt for input this is related to this question here but with a slight twist instead of just passing yes or no i need fabric to pass an arbitrary string to the remote shellfor instance if the remote shell prompts for what is your name then i need to feed it firstlastclarification i know i said arbitrary input but i was really trying to use it for the ssh key passwd prompt when i try to do a git pullupdate 1 got a response from jeff forcier bitprophetthatas like the 1 wart right now either tunnelling to send a key agent outofband or remote prompting is neededi meant adding support for those things in fabric is what we need to do to get networkborne git ops workingadding an easy way to kick off an oob ssh agentfriendly tunnel is going to be easierfaster most likely soon probably,['python'] +57232,c typeof operator is c typeof operator standard de facto standardwhich compilers do not provided it besides microsoft c,['c++'] +57239,printing the structure of an array without its contents i was wondering if there is a way to print just the structure of the array without the contents i generally use print r to examine the structure but because my array contains some binary data i would rather not use this,['php'] +57255,firefox addon for examining zindexes i am working on a fairly large site and am having trouble managing zindexes is there a firefox addon that will look at a page and give me an ordered list of every element with a zindex declared that would save a ton of times for the cases where a zindex was wrong or hard to find,['css'] +57257,immutable classes in c in one of my projects i have some classes that represent entities that cannot change once created aka immutable classesexample a class rsakey that represent a rsa key which only has const methods there is no point changing the existing instance if you need another one you just create onemy objects sometimes are heavy and i enforced the use of smart pointers to avoid deep copyso far i have the following pattern for my classesclass rsakey public boostnoncopyable public boostenable shared from thisrsakey public brief some factory param member a member value return an instance static boostshared ptrconst rsakey createfrommemberint member brief get a member return the member int getmember const private brief constructor param member a member rsakeyint member brief member const int m memberso you can only get a pointer well a smart pointer to a const rsakey to me it makes sense because having a nonconst reference to the instance is useless it only has const methodsdo you guys see any issue regarding this pattern are immutable classes something common in c or did i just created a monster thank you for your advices,['c++'] +57259,systemexit0 in java i am writing an application program using swing i need to exit from the application by clicking the jbutton for that can i use systemexit or should i use some other methods which is the best practice if calling systemexit is not best practice then tell the reason and tell the alternative way to exit from the application,['java'] +57264,how to provide animation when calling another activity in android i have two activities a and b i want to have the shrink animation when activity a calls b and maximize animation when activity b calls a i do not need the animation xml files for thiswhen we call another activity in android it gives its default animation and then it calls shrink animation what i want is that the default animation should not occur and the animation that i want should occurcan we actually give the animation when calling another activity,['android'] +57275,read email using pop3 client on aspnet web page i want to read emails through pop3on my aspnet web page how to do let me knowwhich control should i use for showing email,['c#'] +57277,are variables in the main methods static its a well known fact that a static method can work only on static memberspublic static void main test t1 new testhere the main method is static but i have not declared t1 as static is it implicitly static,"['c#', '.net']" +57280,can func get the lineno who call itself cc i have a problem as the following code thiscribe itself 1 includestdlibh2 includestdioh3 void log4 5 printflog linedn line 6 7 int main8 9 log10 log11 the expected result is log line9 log line10 but the fact islog line5 log line5 no surprising line has been substituted at the preprocess stage as 5 my question is how to design the log function to get the expected result thanks,"['c++', 'c']" +57291,how to get the name of the current method from code i know you can dothisgettypefullnameedit courtesy of pasi savolainento getmycurrentclassbut what can i call to getmycurrentclasscurrentmethod,['c#'] +57292,email regular expression validation can anyone correct the expression below to also not allow blank fieldaspregularexpressionvalidator idexpemail runatserver controltovalidatetxtemail errormessagevalid email address required validationexpressionazazwazaz09azaz09wazaz09azazazazazaz170aspregularexpressionvalidator,"['c#', 'asp.net', '.net']" +57297,how to convert a ginormous integer in string format to hex format c given a potentially huge integer value in c string format i want to be able to generate its hex equivalent normal methods do not apply here as we are talking arbitrarily large numbers 50 digits or more the techniques i have seen which use a technique like this store integer 182int decvalue 182 convert integer 182 as a hex in a string variablestring hexvalue decvaluetostringx convert the hex string back to the numberint decagain intparsehexvalue systemglobalizationnumberstyleshexnumberwould not work because the integer to convert is too largefor example i need to be able to convert a string like this843370923007003347112437570992242323 to its hex equivalentthese do not workc convert integer to hex and back againhow to convert numbers between hexadecimal and decimal in c,['c#'] +57306,how to get size and location of a control placed on a dialog in mfc i have got the pointer to the control with functioncwnd cwndgetdlgitemint item idso i have got cwnd pointer which points to the control but simply cannot find any method within cwnd class that will retrieve the size and location of a given controlany help,['c++'] +57324,innertexttextcontent vs retrieving each text node i have heard that using elinnertexteltextcontent can yield unreliable results and that is why i have always insisted on using the following function in the pastfunction gettextnode if nodenodetype 3 return nodedata var txt if node nodefirstchild do txt gettextnode while node nodenextsibling return txtthis function goes through all nodes within an element and gathers the text of all text nodes and text within descendantsegdiv idxfoo emfooem foodivresultgettextdocumentgetelementbyidx foo foo fooi am quite sure there are issues with using innertext and textcontent but i have not been able to find a definitive list anywhere and i am starting to wonder if it is just hearsaycan anyone offer any information about the possibly lacking reliability of textcontentinnertextedit found this great answer by kangax,['javascript'] +57326,trigger flash button object via javascript is it possible to trigger for example flash uploading button via javascriptfor example i have made empty image wrappers and by clicking on them they trigger flash button to open as select windowthanks,['javascript'] +57334,how can i run a static constructor i would like to execute the static constructor of a class ie i want to load the class without creating an instance how do i do thatbonus question are there any differences between net 4 and older versionseditthe class is not statici want to run it before creating instances because it takes a while to run and i would like to avoid this delay at first accessthe static ctor initializes private static readonly fields thus cannot be run in a method instead,"['c#', '.net']" +57339,inconsistent syntax c private string getroles string foo test return foo the above compiles butprivate string getroles return test does notreplacing it withreturn new string test will obviously compile though is this inconsistancy or am i being stupid or am i just wrong s,['c#'] +57348,writing bmp image in pure cc without other libraries in my algorithm i need create information output i must to write boolean matrix in bmp fileit must be monocromic image where pixel is white if matrix on such element is truemain problem is bmp header and how to write this,"['c++', 'c']" +57349,readfile in php i hate that google can not search for symbols i saw this in some sample code and wondered why there is an sign before the readfile functionreadfilefilenamewhat does it mean different to without an symbol,['php'] +57356,where should i put wpf specific code when using mvvm i am just getting up to speed on mvvm but all the examples i have seen so far are binding view controls to simple nonwpf specific data types such as strings and ints however in our app i want to be able to set a buttons border brush based on a number in the model at the moment i translate the number into a brush in the viewmodel to keep the view xaml only but is that right i do not like putting wpf specific code in the viewmodel but equally i do not like the idea of putting codebehind on my view panel which is the best waythanks,['c#'] +57357,multiple aggregate functions in one sql query from the same table using different conditions i am working on creating a sql query that will pull records from a table based on the value of two aggregate functions these aggregate functions are pulling data from the same table but with different filter conditions the problem that i run into is that the results of the sums are much larger than if i only include one sum function i know that i can create this query using temp tables but i am just wondering if there is an elegant solution that requires only a single queryi have created a simplified version to demonstrate the issue here are the table structuresemployee tableempid123absence tableempid date hours absent1 612009 31 912009 12 312010 2and here is the queryselect eempid sumatotalhours absent as absent total sumayearhours absent as absent yearfrom employee e inner join absence atotal on atotalempid eempid inner join absence ayear on ayearempid eempidwhere ayeardate 112010group by eempidhaving sumatotalhours absent 10 or sumayearhours absent 3any insight would be greatly appreciated,['sql'] +57376,how do i perform a batch insert in django in mysql you can insert multiple rows to a table in one query for and 0insert into tbl name abc values123456789 n2 n1 nis there a way to achieve the above with django queryset methods heres an examplevalues 1 2 3 4 5 6 for value in values somemodelobjectscreatefirstvalue0 secondvalue1 thirdvalue2i believe the above is calling an insert query for each iteration of the for loop i am looking for a single query is that possible in django,['sql'] +57400,common mercator projection formulas for google maps not working correctly i am building a tile overlay server for google maps in c and have found a few different code examples for calculating y from latitude after getting them to work in general i started to notice certain cases where the overlays were not lining up properly to test this i made a test harness to compare google maps mercator lattoy conversion against the formulas i found online as you can see below they do not match in certain casescase 1zoomed out the problem is most evident when zoomed out up close the problem is barely visiblecase 2point proximity to top bottom of viewing bounds the problem is worse in the middle of the viewing bounds and gets better towards the edges this behavior can negate the behavior of case 1the testi created a google maps page to thisplay red lines using the google map apis built in mercator conversion and overlay this with an image using the reference code for doing mercator conversion these conversions are represented as black lines compare the differencethe resultscheck out the topmost and bottommost linesthe problem gets visually larger but numerically smaller as you zoom inand it all but thisappears at closer zoom levels regardless of screen orientationthe codegoogle maps client side code var lat 0 for lat 80 lat 80 lat 5 mapaddoverlaynew gpolylinenew glatlnglat 180 new glatlnglat 0 ff0033 2 mapaddoverlaynew gpolylinenew glatlnglat 0 new glatlnglat 180 ff0033 2 server side codetile cutter cutteropenstreetmap wiki protected override void imageoverlay composeimageref bitmap zipcodebitmap graphics linesgraphic graphicsfromimagezipcodebitmap int32 mapwidth converttoint32mathpow2 zoom 255 point offset cartographermercator2tozoomedpixelcoordsnorth west zoom trimpointref offset mapwidth for double lat 80 lat 80 lat 5 point startpoint cartographermercator2tozoomedpixelcoordslat 179 zoom point endpoint cartographermercator2tozoomedpixelcoordslat 1 zoom trimpointref startpoint mapwidth trimpointref endpoint mapwidth startpointx startpointx offsetx endpointx endpointx offsetx startpointy startpointy offsety endpointy endpointy offsety linesgraphicdrawlinenew pencolorblack 2 startpointx startpointy endpointx endpointy linesgraphicdrawstring lattostring new fontverdana 10 new solidbrushcolorblack new point converttoint32width 30 20 startpointy protected void trimpointref point point int32 mapwidth pointx mathmaxpointx 0 pointx mathminpointx mapwidth 1 pointy mathmaxpointy 0 pointy mathminpointy mapwidth 1 so anyone ever experienced this dare i ask resolved this or simply have a better c implementation of mercator project coordinate conversionthanks,['c#'] +57405,internet explorer console is there a console logger for ie i am trying to log a bunch of testsassertions to the console but i cannot do this in ie,['javascript'] +57411,php file get contents and i am trying to use phps file get contenta urlthe thing is if the url has in it for examplefile get contentsvar22 it automatically make a requests to wgooglecomvar11ampvar22 how do i prevent that from happening,['php'] +57420,setting headers in xdomainrequest or activexobjectmicrosoftxmlhttp i am trying to do something like this w3 compliant domxhrsetrequestheader xrequestedwith xmlhttprequest for activexobjectmicrosoftxmlhttp and xdomainrequest ie8 i am having no such luck finding it anywhere in microsoft documentation or even google any idea how i can achieve this,['javascript'] +57429,how does gmail do comet on opera i would like to know how gmail or anyone else does comet on operahere is what i know so far from my experimentsit does not use the eventsource tag which is broken in opera 1051it does not use iframe which thisplays a spinning throbber and a busy mouse cursorit does not use responsetext on xmlhttprequest when readystate 3 which is known to be broken on operai tried seeing how it was done in mibbit and etherpad and i found that they both use longpollingbountythe bounty goes to whoever can tell me a method better than eventsource for opera comet streaming or how gmail does streaming or longpolling if it does that,['javascript'] +57435,deep copy vs shallow copy possible duplicatewhat is the difference between a deep copy and a shallow copy what is the difference between deep and shallow copy what type of a copy does a copy constructor do,['c++'] +57446,set inner table border in html how do i set the inner border the border between different cellsby setting style attributes i manage to control the outer border but the inner border just stays the same gray color and the same width what attributes should i tweak to control the inner border,"['html', 'css']" +57449,how can i copy unmanaged data in c and how fast is it i have two unmanaged pointers in the form of intptr and want to copy data between them how can i do this i know the method marshalcopy but it can only copy between unmanaged and managedand the second part is copying unmanaged data from c slower than doing it in unmanaged cc using memcpyedit i would be especially interested in a platform independet implementation,['c#'] +57466,import json data into google spreadsheet i am pulling data down from a webservice and it is formated as json i am writing a google apps script for google spreadsheet that will populate the data for me my problem is i cannot seem to get it to parse outdoingvar dataset myjsontextbrowsermsgboxdatasetitem0key errors out saying item0 is not definedis there some built in way i should be doing thisany help would be apreciated,['javascript'] +57467,java how to find the redirected url of a url i am accessing web pages through java as followsurlconnection con urlopenconnectionbut in some cases a url redirects to another url so i want to know the url to which the previous url redirectedbelow are the header fields that i got as a responsenullhttp11 200 okcachecontrolpublicmaxage3600lastmodifiedsat 17 apr 2010 134535 gmttransferencodingchunkeddatesat 17 apr 2010 134535 gmtvaryacceptencodingexpiressat 17 apr 2010 144535 gmtsetcookiecl def hpcopenhagen domaincraigslistorg path expiressun 17 apr 2011 134535 gmt cl def langen domaincraigslistorg path expiressun 17 apr 2011 134535 gmtconnectionclosecontenttypetexthtml charsetiso88591serverapacheso at present i am constructing the redirected url from the value of the setcookie header field in the above case the redirected url is copenhagencraigslistorgis there any standard way through which i can determine which url the particular url is going to redirecti know that when a url redirects to other url the server sends an intermediate response containing a location header field that tells the redirected url but i am not receiving that intermediate response through the urlopenconnection method,['java'] +57474,ienumerable does not have a count method i have the following methodpublic bool isvalid get return getruleviolationscount 0 public ienumerableruleviolation getruleviolations code herewhy is it that when i do count above it is underlined in redi got the following errorerror 1 systemcollectionsgenericienumerable does not contain a definition for count and no extension method count accepting a first argument of type systemcollectionsgenericienumerable could be found are you missing a using directive or an assembly reference cusersadocumentsvisual studio 2010projectsnerddinnernerddinnermodelsdinnercs 15 47 nerddinner,"['c#', 'asp.net']" +57478,automatically sizing uiview after adding to window note this may be a duplicate of subview doesnt autosize when added to root view controlleri have an ipad app that switches between different views in its main window the viewswitching code looks like this voidswitchtoviewcontrolleruiviewcontrollerviewcontroller if currentviewcontroller viewcontroller currentviewcontrollerview removefromsuperview currentviewcontroller viewcontroller window addsubviewviewcontrollerview the problem is that when the new view a uisplitview appears in landscape orientation it is not sized to fill the entire window there is a large empty black space on the right it looks like the view is only 768 pixels wide rather than the 1024pixel width of the landscape windowif i rotate the device to portrait and then back to landscape the view sizes itself properlyif the device is in portrait orientation everything works fine the uisplitview also gets sized properly if it is the first view i show the problem only occurs if i switch to it after another view has been shown in landscapeso is there some way to force iphone os to resize the view after it has been added to the windowi have tried calling sizetofit and setneedslayout i have also tried setting the views bounds to the windows bounds and i have tried setting the frame to match the previous views frame,['iphone'] +57482,pipe implementation i am trying to implement a linux shell that supports piping i have already done simple commands commands running in background redirections but piping is still missingi have already read about it and seen some snippets of code but still have not been able to sort out a working solutionwhat i have so farint fd2pipefdpid t pid forkif pid 1 return 1 if pid 0 closefd1 close write to pipe in child execlpcat cat namestxt nullelse closefd0 close read from pipe in parent execlpsort sort null i am a novice programmer as you can probably tell and when i am programming something i do not know much about this being obviously the case i like to start with something really easy and concrete and then build from there so before being able to implement three and more different commands in pipeline i would like to be able to compute ls namestxt sort or something similiar in which namestxt is a file of names alfabetically unorderedupdated code but still does not workthanks,['c'] +57489,python slicing a list into and nearlyequallength partitions i am looking for a fast clean pythonic way to divide a list into exactly and nearlyequal partitionspartition12345512345partition12345212345 or 12345partition12345312345 there are other ways to slice this one toothere are several answers in here that run very close to what i want except they are focused on the size of the list and i care about the number of the lists some of them also pad with none these are trivially converted obviously but i am looking for a best practicesimilarly people have pointed out great solutions here for a very similar problem but i am more interested in the number of partitions than the specific size as long as it is within 1 again this is trivially convertible but i am looking for a best practice,['python'] +57521,is it bad to explicitly compare against boolean constants eg if b false in java is it bad to writeif b false while b true is it always better to instead writeif b while b presumably there is no difference in performance or is there but how do you weigh the explicitness the conciseness the clarity the readability etc between the twoupdateto limit the subjectivity i would also appreciate any quotes from authoritative coding style guidelines over which is always preferable or which to use whennote the variable name b is just used as an example ala foo and bar,['java'] +57522,algorithm for source control system i need to write a simple source control system and wonder what algorithm i would use for file differencesi do not want to look into existing source code due to license concerns i need to have it licensed under mpl so i cannot look at any of the existing systems like cvs or mercurial as they are all gpl licensedjust to give some background i just need some really simple functions binary files in a folder no subfolders and every file behaves like it is own repository no metadata except for some permissionsoverall really simple stuff my single concern really is how to store only the differences of a file from revision to revision without wasting too much space but also without being too inefficient maybe store a full version every x changes a bit like keyframes in videos,"['c#', '.net']" +57532,php syntax error aunexpected enda i have 3 files1 show createtablehtml2 do showfielddefphp3 do showtblephp1 first file is for creating a new table for a data base it is a fom with 2 inputs table name and number of fields this works finehtml xmlnsheadmeta httpequivcontenttype contenttexthtml charsetutf8 titleuntitled documenttitleheadbodyh1step 1 name and numberh1form methodpost actiondo showfielddefphp pstrongtable namestrongbr input typetext nametable name size30 ppstrongnumber of fieldsstrongbr input typetext namenum fields size30 ppinput typesubmit namesubmit valuego to step2 pformbodyhtml2 this script validates fields and createa another form to enter all the table rowsthis for also works finephpvalidate important inputif posttable name postnum fields header location show createtablehtml exitbegin creating form for thisplayform block form actiondo createtablephp methodpostinput nametable name typehidden value posttable nametable cellspacing5 cellpadding5 tr thfield nameththfield typeththtable lengthth trcount from 0 until you reach the number fo fieldsfor i 0 i postnum fields i form block tr td aligncenterinput typetexr namefield name size30td td aligncenter select namefield type option valuecharcharoption option valuedatedateoption option valuefloatfloatoption option valueintintoption option valuetexttextoption option valuevarcharvarcharoption select td td aligncenterinput typetext namefield length size5 tdtrfinish up the form form block tr td aligncenter colspan3input type submit valuecreate table tdtrtableformhtmlheadmeta httpequivcontenttype contenttexthtml charsetutf8 titlecreate a database table step 2titleheadbodyh1defnie fields for echo posttable name h1 echo form block bodyhtmlproblem is here 3 this form creates the tables and enteres them into the databasei am getting an error on line 37 parse error syntax error unexpected end in homeadmindomainsdomainacomaupublic htmldo createtablephp on line 37db name testdbconnection mysql connectlocalhost admin user pass or diemysql errordb mysql select dbdb name connection or diemysql errorsql create table posttable name for i 0 i count postfield name i sql postfield namei postfield typei if postfield lengthi sql postfield lengthi else sql sql substrsql 0 1sql result mysql querysql connection or diemysql errorif result msg p posttable name has been createdphtmlheadmeta httpequivcontenttype contenttexthtml charsetutf8 titlecreate a database table step 3titleheadbodyh1adding table to echo db name h1 echo msg bodyhtml,['php'] +57533,where can i write a temp file from aspnet i have an access denied problem on an aspnet web application where the user uploads an excel file and i try and write it to a folder i do not have access to the host except ftp so i cannot set permissions i thought that aspnet would be able to write to a folder that is under the web app root but it is not sois there anywhere i can write the file to that does not require me to set permissions,['asp.net'] +57537,downloading javascript without blocking the context my question relates to improving webpage loading performance and in particular the effect that javascript has on pageloading resourceselements below the script are blocked from downloadingrenderingthis problem is usually avoidedmitigated by placing the scripts at the bottom eg just before the tag the code i am looking at is for web analytics placing it at the bottom reduces its accuracy and because this script has no effect on the pages content ie it is not rewriting any part of the pagei want to move it inside the head just how to do that without ruining pageloading performance is the cruxfrom my research i have found six techniques w support among all or most of the major browsers for downloading scripts so that they do not block downpage content from loadingrenderingi xhr evalii xhr injecti download the htmlwrapped script as in iframeiv setting the script tags async flag to true html 5 only v setting the script tags defer attribute and vi script dom elementit is the last of these i do not understand the javascript to implement the pattern vi is function var q1 documentcreateelementscript q1src sitecomq1js documentdocumentelementfirstchildappendchildq1seems simple enough and anonymous function is created then executed in the same block inside this anonymous functiona script element is createdits src element is set to it is location thenthe script element is added to the dombut while each line is clear it is still not clear to me how exactly this pattern allows script loading without blocking downpage elementsresources from renderingloading,"['javascript', 'html']" +57541,easily position an element over another element in jquery i need to position a div over an image with jquery i can create it with using position fixed and use top and left to position it using elements offset but it sucks because the element will not be on top of the element if user scrollsany other ideas,['jquery'] +57549,how to measure running time of algorithms in python possible duplicatesaccurate timing of functions in pythonaccurately measure time python function takes how can i mesure and compare the running times of my algorithms written in python also point me to a nice algorithms siteforum like stackoverflow if you can,['python'] +57555,formatting time in milliseconds using boostdate time library i have a time duration in milliseconds which i ideally would like to format using the formatting functionality present in the boostdate time library however after creating a boostposix timetime duration i cannot seem to find a way to actually apply the formatting string to it,['c++'] +57560,iphone nshttpcookie is not saved across app restarts in my iphone app i want to be able to reuse the same serverside session when my app restarts a session on the server is identified by a cookie which is sent on each request when i restart the app that cookie is gone and i cannot use the same session anymorewhat i noticed when i used the nshttpcookiestorage to look up the cookie i got from the server is that cookie issessiononly returns yes i get the impression that this is why cookies are not saved across restarts of my app what would i have to do to make my cookie not session only what http headers do i have to send from the server,['iphone'] +57565,making the android emulator run faster the android emulator is a bit sluggish for some devices like the motorola droid and the nexus one the app runs faster in the actual device than the emulator this is a problem when testing games and visual effectshow do you make the emulator run as fast as possible i have been toying with its parameters but have not found a configuration that shows a noticeable improvement yet,['android'] +57584,stdvector capacity after copying does vectoroperator change vector capacity if so howdoes vectors copy constructor copy capacityi looked through documentation but could not find a specific answer is it implementation dependent,['c++'] +57600,how does mysqls order by rand work i have been doing some research and testing on how to do fast random selection in mysql in the process i have faced some unexpected results and now i am not fully sure i know how order by rand really worksi always thought that when you do order by rand on the table mysql adds a new column to the table which is filled with random values then it sorts data by that column and then eg you take the above value which got there randomly i have done lots of googling and testing and finally found that the query jay offers in his blog is indeed the fastest solutionselect from table t join select ceilmaxidrand as id from table as x on tid xid limit 1while common order by rand takes 3040 seconds on my test table his query does the work in 01 seconds he explains how this functions in the blog so i will just skip this and finally move to the odd thingmy table is a common table with a primary key id and other nonindexed stuff like username age etc heres the thing i am struggling to explainselect from table order by rand limit 1 3040 secondsselect id from table order by rand limit 1 025 secondsselect id username from table order by rand limit 1 90 secondsi was sort of expecting to see approximately the same time for all three queries since i am always sorting on a single column but for some reason this did not happen please let me know if you any ideas about this i have a project where i need to do fast order by rand and personally i would prefer to useselect id from table order by rand limit 1select from table where idid from previous query limit 1which yes is slower than jays method however it is smaller and easier to understand my queries are rather big ones with several joins and with where clause and while jays method still works the query grows really big and complex because i need to use all the joins and where in the joined called x in his query sub requestthanks for your time,['mysql'] +57602,what is the name keyword in javascript when i typed this apparently innocent snippet of codevaluesnamegedit highlighted name as a keyword however name is not listed by the pages linked to by an answer to a question about reserved keywords i also did a couple trivial tests in spidermonkey but name seemed to act like an ordinary identifiera google search did not tell me much either however i did find a page listing name in other javascript keywords my guess is that name is a function or a member of some dom element and does not intrude on the namespaceis name really a keyword in javascript if so what does it do,['javascript'] +57607,why do i get an enum constant reference cannot be qualified in a case label why does the following code fail to compile while changing the case statement tocase enum1 dosomestuffworkspublic enum enumtype enum1 enum2 enum3 void dosomestuff switchthis case enumtypeenum1 dosomestuff,['java'] +57609,value of c define changes unexpectedly i have a lot of defines in my code now a weird problem has crept upi have thisdefine immsign 010100i am trying to simulate a binary numberobviously i expect the number to become 10100 but when i use the number it has changed into 4160what is happening here and how do i stop itadditionalokay so this is due to the language interpreting this as an octal is there some smart way however to force the language to interpret the numbers as integers if a leading 0 defines octal and 0x defines hexadecimal now that i think of it,['c'] +57610,counting longest occurence of repeated sequence in python whats the easiest way to count the longest consecutive repeat of a certain character in a string for example the longest consecutive repeat of b in the following stringmy str abcdefgfaabffbfgbbwould be 6 since other consecutive repeats are shorter 3 and 2 respectively how can i do this in pythonthanks,['python'] +57612,problems with routing urls using cgi and bottlepy i have been having difficulty getting anything more than a simple index to return correctly using bottlepy in a cgi environment when i try to return hello i get a 404 response however if i request indexpyhelloimport bottlefrom bottle import routeroutedef index return indexroutehellodef hello return helloif name main from wsgirefhandlers import cgihandler cgihandlerrunbottledefault appand here is my htaccess filedirectoryindex indexpyifmodule mod rewritecrewriteengine onrewritebase rewritecond request filename frewriterule indexpy1 lifmodulei copied much of the code from here as i am using dh and it seemed relevant thanks for helping,['python'] +57621,reading csv files in numpy where delimiter is i have got a csv file with a format that looks like thisfieldname1 fieldname2 fieldname3 fieldname4 04132010 144507008 759484916392 10 6552373 04132010 144522010 655478493312 9 35378543 note that there are double quote characters at the start and end of each line in the csv file and the string is used to delimit fields within each line the number of fields in the csv file can vary from file to filewhen i try to read this into numpy viaimport numpy as npdata npgenfromtxtcsvfile dtypenone delimiter namestrueall the data gets read in as string values surrounded by doublequote characters not unreasonable but not much use to me as i then have to go back and convert every column to its correct typewhen i use delimiter instead everything works as i would like except for the 1st and last fields as the start of line and end of line characters are a single doublequote character this is not seen as a valid delimiter for the 1st and last fields so they get read in as eg 04132010 144507008 and 6552373 note the leading and trailing doublequote characters respectively because of these redundant characters numpy assumes the 1st and last fields are both string types i do not want that to be the caseis there a way of instructing numpy to read in files formatted in this fashion as i would like without having to go back and fix the structure of the numpy array after the initial read,['python'] +57625,linq to sql does not update when data has changed in database i have this problem where after a field say field3 in table mytable is updated on the database mytablefield3 in c is still returning the old valuei suspect there is some cachinghow do i force it toread the value from the databaseorupdate the value in the mytable classor is there anything i miss i am new to linqthank you in advance,"['c#', '.net']" +57627,uiscreen applicationframe returning incorrect rectangle on landscape application launch iphoneipad having trouble getting the correct bounds for my ipad application when launching it in landscape mode i have the proper keys set in my infoplist file and my view controllers launch properly in landscape and portrait natchin my applicationdidfinishlaunching method i am calling a selector after a 3 second delay and that method makes a call to uiscreen mainscreen applicationframe but it is returning me a portrait frame ie height widthdoes anyone know how to fix this it smells like a bug to me if so i will file a radar but if it is intended behaviour where is it documented,['iphone'] +57639,is there any good book for boost library c and for object oriented design in c this post is about 2 questions in onegood books for boost c libraryoo design in c i come from java background and tend to think in terms of interfaces singletons etc how do i translate it to c or how to start thinking differently for cajay,['c++'] +57654,filling an iframe with dynamic content from javascript i have an iframe that should be filled with content from javascript had the content be on the server all i had to do is function oniframefill myiframelocationhref helloworldhtml but the content i have is a html page generated on the client and represented as a string i have not much influence on it how can i populate the content of the my iframe programatically,['javascript'] +57661,how can i gzip my javascript and css files i have a problem i have to gzip a prototype lib but i totaly have no idea how to do this where to start and how does it works i find some tutorials but that was not helpfulso i have a folder with my js filescompressedjs1js2js3jsi am calling these files for a test in this filecompressesindexphplink reljavascript typetextjs hrefjstabsjs link reljavascript typetextjs hrefjsfbjs so what do i have to do,"['javascript', 'css']" +57663,odd behavior when recursively building a return type for variadic functions this is probably going to be a really simple explanation but i am going to give as much backstory as possible in case i am wrong advanced apologies for being so verbose i am using gcc45 and i realize the c0x support is still somewhat experimental but i am going to act on the assumption that there is a nonbug related reason for the behavior i am seeingi am experimenting with variadic function templates the end goal was to build a conslist out of stdpair it was not meant to be a custom type just a string of pair objects the function that constructs the list would have to be in some way recursive with the ultimate return value being dependent on the result of the recursive calls as an added twist successive parameters are added together before being inserted into the list so if i pass 1 2 3 4 5 6 the end result should be 12 34 56my initial attempt was fairly naive a function build with two overloads one took two identical parameters and simply returned their sum the other took two parameters and a parameter pack the return value was a pair consisting of the sum of the two set parameters and the recursive call in retrospect this was obviously a flawed strategy because the function is not declared when i try to figure out its return type so it has no choice but to resolve to the nonrecursive version that i understand where i got confused was the second iteration i decided to make those functions static members of a template class the function calls themselves are not parameterized but instead the entire class is my assumption was that when the recursive function attempts to generate its return type it would instantiate a whole new version of the structure with its own static function and everything would work itself outthe result was error no matching function for call to buildstructdouble double char chargoconst char const charthe offending code static auto goconst type t0 const type t1 const types rest stdpairtype decltypebuildstructtypesgorestmy confusion comes from the fact that the parameters to buildstruct should always be the same types as the arguments sent to buildstructgo but in the error code go is missing the initial two double parameters what am i missing here if my initial assumption about how the static functions would be chosen was incorrect why is it trying to call the wrong function rather than just not finding a function at all it seems to just be mixing types willynilly and i just cannot come up with an explanation as to why if i add additional parameters to the initial call it always burrows down to that last step before failing so presumably the recursion itself is at least partially working this is in direct contrast to the initial attempt which always failed to find a function call right awayultimately i have gotten past the problem with a fairly elegant solution that hardly resembles either of the first two attempts so i know how to do what i want to do i am looking for an explanation for the failure i saw full code to follow since i am sure my verbal description was insufficient first some boilerplate if you feel compelled to execute the code and see it for yourself then the initial attempt which failed reasonably then the second attempt which did notinclude iostreamusing stdcoutusing stdendlinclude utilitytemplatetypename t1 typename t2stdostream operator stdostream str const stdpairt1 t2 p return str pfirst psecond insert code here int main execute5 6 43 22 c d execute5 6 43 22 execute5 6 return 0nonstruct solutiontemplatetypename typetype buildfunctionconst type t0 const type t1 return t0 t1templatetypename type typename restauto buildfunctionconst type t0 const type t1 const rest rest stdpairtype decltypebuildfunctionrest return stdpairtype decltypebuildfunctionrest t0 t1 buildfunctionresttemplatetypename typesvoid executeconst types t cout buildfunctiont endlresulting errorstestcpp in function void executeconst types with types int int double double char chartestcpp35 instantiated from heretestcpp283 error no matching function for call to buildfunctionconst int const int const double const double const char const charstruct solutiontemplatetypename typesstruct buildstructtemplatetypename typestruct buildstructtype type static type goconst type t0 const type t1 return t0 t1 templatetypename type typename typesstruct buildstructtype type types static auto goconst type t0 const type t1 const types rest stdpairtype decltypebuildstructtypesgorest return stdpairtype decltypebuildstructtypesgorest t0 t1 buildstructtypesgorest templatetypename typesvoid executeconst types t cout buildstructtypesgot endlresulting errorstestcpp in instantiation of buildstructint int double double char chartestcpp3 instantiated from void executeconst types with types int int double double char chartestcpp3841 instantiated from heretestcpp2415 error no matching function for call to buildstructdouble double char chargoconst char const chartestcpp2415 note candidate is static stdpairtype decltype buildstructtypes gobuildstructtype type types gorest buildstructtype type types goconst type const type const types with type double types char char decltype buildstructtypes gobuildstructtype type types gorest chartestcpp in function void executeconst types with types int int double double char chartestcpp3841 instantiated from heretestcpp3 error go is not a member of buildstructint int double double char char,['c++'] +57683,how to modify code so that it adheres to the law of demeter public class bigperformance public decimal value get set public class performance public bigperformance bigperf get set public class category public performance perf get set if i call category cat new category catperfbigperfvalue 10 i assume this this breaks the law of demeter principle of least knowledgeif so how do i remedy this if i have a large number of inner class properties,['c#'] +57687,how to round cgfloat i made this method cgfloat round cgfloatf int a f cgfloat b a return bit works as expected but it only rounds down and if it is a negative number it still rounds downthis was just a quick method i made it is not very important that it rounds correctly i just made it to round the cameras x and y values for my gameis this method okay is it fast or is there a better solution,"['ios', 'objective-c']" +57692,i just do not get the c pointerreference system i have never had problems with references as in python implicit or php explicit in php you write p myvar and you have p as a reference pointing to myvarso i know in c you can do thisvoid settosomething int var var 123int myintsettosomething myint myint is now 123 whydoes not mean memory address of x in c what do i do then if var is only the adress to myint and not a pointervoid settosomething int var var 123int myintint myintptr myintsettosomething myintptr does the above work as expectedi do not understand the difference between and in c fully they tell you is used to get the adress of a variable but why does that help you in functions etc like in the first example,['c++'] +57702,how do i add some inserts in rails migration after creating a table by migration i want to insert some entries directly how must i write a migration for thisthanks,['ruby-on-rails'] +57708,why use mysql over flatfiles a friend and i were debating about whether he should use mysql or a flatfile database for his websites backend i told him to go with mysql because it was structured held records well and was consistent he on the other hand said that he would rather go for speed reading files is a lot quicker than connecting to mysql and it made me wonder whether he was right for example why not just create a folder for each table like so users groups posts within the folders have the files named by id 1 2 3 and then for the data use a format like so username johnnpassword e2fc714c4727ee9395f324cd2e7f331fnemail in other words what are the advantages of mysql over flatfiles,['mysql'] +57723,generically creating objects in c what i am trying to do is load in objects from an xml save file the problem is those objects are configurable by the user at runtime meaning i had to use reflection to get the names and attributes of those objects stored in an xml filei am in the middle of a recursive loop through the xml and up to the part where i need to create an object then thought ah no idea how to do that i have an array stuffed with empty objects m menudatatypes one of each possible type my recursive loading function looks like thisprivate void loadmenudataxmlnode menudatanode foreach object menudataobject in m menudatatypes type menudataobjecttype menudataobjectgettype if menudataobjecttypename menudatanodename create object i need to put some code where my comment is but i cannot have a big switch statement or anything the objects in my array can change depending on how the user has configured the app,['c#'] +57725,in c how can i make typedefs visible to every file in my project i have a typedef typedef unsigned int my typeused in a file i would like to make it visible across all my files withoutputting it in a header file included by everything i do not want to go the header fileroute because as it stands this will be the only declaration in the header fileand it seems unnecessary to add a file just for thisis there a way to do thisif instead i hadtypedef x my typewhere x was a class would i need to include xh everywhere and have the typedef at the endof xh,['c++'] +57740,jquery ui sortable determining in what order the items are here is an interesting use of javascript reordering items with drag and drop the implementation itself in my page works fine but is there a way to determine in which order the user put the itemsi am asking because i want to load and save the item order in a cookie,"['javascript', 'jquery', 'html']" +57759,why does google prepend while1 to their json responses why does google prepend while1 to their private json responsesfor example heres a response while turning a calendar on and off in google calendarwhile1usmssentflagfalsehideinvitationsfalse remindonrespondedeventsonlytrue hideinvitations remindonrespondedeventsonlyfalse true calendar id stripped for privacyfalsesmsverifiedflagtruei would assume this is to prevent people from doing an eval on it but all youd really have to do is replace the while and then youd be set i would assume the eval prevention is to make sure people write safe json parsing codei have seen this used in a couple of other places too but a lot more so with google mail calendar contacts etc strangely enough google docs starts with start instead and google contacts seems to start with while1 startwhats going on here,['javascript'] +57760,avoiding accidentally catching keyboardinterrupt and systemexit in python 24 in python scripts there are many cases where a keyboard interrupt ctrlc fails to kill the process because of a bare except clause somewhere in the codetry fooexcept barthe standard solution in python 25 or higher is to catch exception rather than using bare except clausestry fooexcept exception barthis works because as of python 25 keyboardinterrupt and systemexit inherit from baseexception not exception however some installations are still running python 24 how can this problem be handled in versions prior to python 25i am going to answer this question myself but putting it here so people searching for it can find a solution,['python'] +57774,tiny mce set fullscreen when editor is loaded i use tiny mce as wordlike editor in textareas that are in iframes i want to use whole iframe space tinymce has a fullscreen button but i need to set fullscreen mode automatically when plugin has loaded is there a functiontrigger to call this mode or the button thanks for help,['javascript'] +57778,mixed alignment with java swings grouplayout i am trying to build a gui window in my application what i am trying to do is have a window with a few buttons at the top and a large text area something like this button1 button2 button3 text area i am almost there using grouplayout layoutsethorizontalgroup layoutcreateparallelgroup addgrouplayoutcreatesequentialgroup addcomponentbutton1 addcomponentbutton2 addcomponentclosewindow addcomponenttextarea1 layoutsetverticalgroup layoutcreatesequentialgroup addgrouplayoutcreateparallelgroup addcomponentbutton1 addcomponentbutton2 addcomponentbutton3 addcomponenttextarea the problem is that this ends up with button3 aligned to the left with the other two i cannot seem to figure out how i can specify the alignment on just that one button i can do grouplayoutalignmenttrailing on the entire button bar but that hits all 3 buttons which is also not quite rightso whats the correct approach since the alignment only applies for parallel groups i do not think having a horizontalgroup with two sequential groups in it will helpwhat am i missing,['java'] +57791,where is the best place to store globals in rails app i was wondering if there is the best practice on where to store global settings in a rails app what i mean by that is ie i have a few globals defined that may change but not likely and it seems inappropriate to store them in db since they are used so much for instance i have system email system email signature system storage root right now i keep them in environmentrb but i am not sure if this is the right palce to store themthank youeditaccepted answer still stands as appropriate however i since moved on to using there are other options but i like configatron the most,"['ruby-on-rails', 'ruby']" +57796,visual studio missing warnings anyone find where when you open a certain solution that contains multiple projects and compile that youre not seen some warnings that your colleagues see when compiling the exact same solution at the exact same state the code is the samei depend highly on the warnings as a shortcut to find unused methods etc but i get nothing during compile only a couple based on references to user controls etc,['c#'] +57808,java programs using nio framework i am doing some research related to java nio i need to find some representative applications that are based on this framework please feel free to suggest the more the merrier thanks,['java'] +57814,php plus sign with get query i have a php script that does basic encryption of a string through the method belowphpkey secretkeystring getstrif getmethod decrypt output rtrimmcrypt decryptmcrypt rijndael 256 md5key base64 decodestring mcrypt mode cbc md5md5key 0if getmethod encrypt output base64 encodemcrypt encryptmcrypt rijndael 256 md5key string mcrypt mode cbc md5md5keyecho outputan example of a url to encrypt a string would look like thisencryptphpmethodencryptstrthe quick foxwhich would return this as the encrypted stringlcutieva6cl34vtzejd9qpt3kvhyyjfqg6ty3p0qnow to decrypt the string all you have to do is change the method query to decrypt like soencryptphpmethoddecryptstrlcutieva6cl34vtzejd9qpt3kvhyyjfqg6ty3p0qthe only problem is that when that encrypted string is decrypted it returns thisaaryvaa35ana x8abi have narrowed down the problem to the plus sign that is in the encrypted string phps get method seems to translate a plus sign into a blank space i have searched this bug and found out that it has already been filed here i have tried different methods listed on that page and others with no success the closest i got is by using thisfixedstring str replace stringand then using fixedstring in the encryption methods the problem is upon decryption all blank spaces are converted to plus signs any ideasi know using post would make more sense but i am using get for specific reasons i will spare the details,['php'] +57817,is there javascript to convert html to markdown there is showdownjs to convert markdown to html and php markdown to convert markdown to and from html my question is is there javascript library to convert html to markdown,"['javascript', 'html']" +57819,can i develop android on mac i want to develop applications on android can the sdk be installed on mac,['android'] +57825,how do i check if a javascript array value is empty or null will this work for testing whether a value at position index exists or not or is there a better wayifarraynameindex do stuff,['javascript'] +57829,is there an object in c that allows for easy management of html dom if i have a string that contains the html from a page i just got returned from an http post how can i turn that into something that will let me easily traverse the domi figured htmldocument object would make sense but it has no constructor are there any types that allow for easy management of html domthanksmatt,['c#'] +57840,how to cancel any event in winforms i want to cancel an event from within that function scopeeg i pressed button click event and on false validation i want to cancel this event likewise i want to cancel other events also how can i do this in c,"['c#', '.net']" +57841,sort an array by a child arrays value in php i have an array composed of arrays i want to sort the parent array by a property of the child arrays heres an examplearray2 0 array3 0 string6 105945 1 string10 first name 2 float0080878465391 1 array3 0 string6 109145 1 string11 second name 2 float00504154818384i would like to sort the parent array by 2 ascending in the child arrays so in this case the result would be the child arrays reversed 05 08 is this possible using any of the numerous php sort functions,['php'] +57851,most efficient way to get next letter in the alphabet using php given any character from a to z what is the most efficient way to get the next letter in the alphabet using php,['php'] +57858,problems with binding to window height and width i have some problems when i try to bind the height and width of a window to properties in my view model here is a small sample app to illustrate the problem this is the code in appxamlxspublic partial class app application protected override void onstartupstartupeventargs e baseonstartupe mainwindow mainwindow new mainwindow mainwindowviewmodel mainwindowviewmodel new mainwindowviewmodel mainwindowdatacontext mainwindowviewmodel mainwindowshow this is mainwindowxamlwindow xclasstestappmainwindow xmlns xmlnsx heightbinding windowheight widthbinding windowwidth borderthicknessbinding windowborderthicknesswindowand this is the view modelpublic class mainwindowviewmodel public int windowwidth get return 100 public int windowheight get return 200 public int windowborderthickness get return 8 when the program is started the getters of windowheight and windowborderthickness but not windowwidth are called so the height and the border of the window is set properly but not the widthi then add button that will trigger propertychanged for all properties so that the view model now looks like thispublic class mainwindowviewmodel inotifypropertychanged public event propertychangedeventhandler propertychanged public void triggerpropertychanges if propertychanged null propertychangedthis new propertychangedeventargswindowwidth propertychangedthis new propertychangedeventargswindowheight propertychangedthis new propertychangedeventargswindowborderthickness public icommand buttoncommand get return new relaycommanddelegate triggerpropertychanges public int windowwidth get return 100 public int windowheight get return 200 public int windowborderthickness get return 8 now when i click the button the getter of windowborderthickness is called but not the ones for windowwidth and windowheight it all just seems very weird and inconsistent to me what am i missing,"['c#', '.net']" +57863,validaterequestfalse does not work in aspnet 4 i have a form at which i use ckeditor this form worked fine at aspnet 20 and 35 but now it does not work in aspnet 4 i have validaterequestfalse directive any suggestions,['asp.net'] +57875,how does aspnet mvc compare to java mvc frameworks i have started my career as a java developer then moved to aspnet and recently to the aspnet mvc which i like a lot when developing in java i used struts1 which i remember as a hideous framework with loads of xml now i suspect that java mvc frameworks have moved on from the struts times so how do modern java mvc frameworks compare to the aspnet mvc which one of them is the most similar to the aspnet mvc,"['c#', 'java']" +57892,how to sort string as number in datagridview in winforms i have string column with numbers in a datagridviewit is not bound i would like to sort it number wise i used colidvaluetype typeofintgridsortcolid listsortdirectiondescendingbut is sorts like string eg122378081while the expected is 712238081,['c#'] +57894,is there a way to check if int is legal enum in c i have read a few so posts and it seems most basic operation is missingpublic enum logginglevel off 0 error 1 warning 2 info 3 debug 4 trace 5if s loglevel logloglevel logginglevelconverttoint3278 logloglevel logginglevelenumparsetypeoflogginglevel 78 logwritedebug loglogleveltostringthis causes no exceptions it is happy to store 78 is there a way to validate a value going into an enum,['c#'] +57897,how does the bitwise operator xor work i am a little confused when i see the output of following codex ay bx yy xx yecho x got becho y got ahow does the operator work here,['php'] +57906,android emulator system partition no space from start i have a weird problem with the android emulator i have created a virtual device through android avd manager newly created emulator with platform 21 and api level 7 i have tried with standard settings and with added hardware parameter for larger 256 mb device ram size but nothing changedi need to come files to the system partition to test a project called haggle but for some reason the system partition has no space from startaa a homehaggle02android adb s emulator54 shell dfdfdev 47084k total 0k used 47084k available block size 4096sqlite stmt journals 4096k total 0k used 4096k available block size 4096system 73600k total 73600k used 0k available block size 4096data 65536k total 18464k used 47072k available block size 4096cache 65536k total 1156k used 64380k available block size 4096as you can see the system partition has 0k space available when a connect a nonrooted htc nexus one and do the same i get these valuesdev 108896k total 0k used 108896k available block size 4096sqlite stmt journals 4096k total 0k used 4096k available block size 4096system 148480k total 116364k used 32116k available block size 4096data 200960k total 296k used 178664k available block size 4096cache 97280k total 1852k used 95428k available block size 4096sdcard 3864064k total 118496k used 3745568k available block size 32768why does the system partition on the emulator have 0k free space from beginning and what can i do to change that even if i make the partition writeable with mountremount i get the same 0k valuesany tips,['android'] +57911,jquery dynamically build form action on submit i am trying to have the action of a html form built when the user clicks the submit buttonso the user fills in a form clicks submit then the action gets built then it actually gets submitted the reason being is because the form has a load of options on it which will be passed to a scripthow would i go about doing this with jquery,['jquery'] +57918,using other log4net logging levels than the usual ones i have realised that there is more levels than all debug info warn error and fatal they are listed in the log4netcorelevel classbut how can i use them i mean in the ilog interface you have methods to use the usual ones but what if you want to use fine or emergency etccheers,['.net'] +57924,how to know who kills my threads i got a thread that is just banishing i would like to know who is killing my thread and why it occurs to me my thread is being killed by the os but i would like to confirm this and if possible to know why it is killing itas for the thread i can assert it has at least 40 min of execution before dying but it suddenly dies around 5 minpublic void runworker thread worker new threaddelegate try dosomethingforalonglongtime catchexception e nothing is never logged logexceptione throw e workerisbackground true workersetapartmentstatesystemthreadingapartmentstatesta workerstartedit addressing answerstrycatch possible exceptionsit is implemented and it catches nothing main thread dyingthis thread is created by the web server which continues to runwork completionthe work is not completed as it finally affects the database i can check whether it is done or not when the thread dieshaving thought of these things brought me to this question who is killing my threads ps it is not lady goldent in the living room with the candle stick,"['c#', '.net', 'asp.net']" +57932,setting width of textview in a linearlayout i am using a header for a listview listview header has three columns say abc i am using two linearlayouts to design listview header as shown belowxml version10 encodingutf8 linearlayout xmlnsandroid androidlayout widthfill parent androidlayout height40dip androidpadding0dip linearlayout androidorientationhorizontal androidbackground1e90ff androidlayout width0dip androidlayout weight1 androidpadding5dip androidlayout height40dip textview androididida androidlayout widthfill parent androidlayout heightfill parent androidtextcolor0 androidlayout weight1 androidgravitycenter vertical androidtextstringa textview androidlayout widthfill parent androidlayout heightfill parent androidtextcolor0 androidlayout weight1 androidgravitycenter vertical androidididb androidsinglelinetrue androidtextstringb textview androidlayout widthfill parent androidlayout heightfill parent androidtextcolor0 androidlayout weight1 androidgravitycenter vertical androidididc androidsinglelinetrue androidtextstringc linearlayout linearlayoutnow i want to fix the width of columns a b c respectively how to set width of these columns again is it a good practise to use linearlayout for this please advise,['android'] +57933,why cannot your switch statement data type be long java heres an excerpt from suns java tutorialsa switch works with the byte short char and int primitive data types it also works with enumerated types thiscussed in classes and inheritance and a few special classes that wrap certain primitive types character byte short and integer thiscussed in simple data objects there must be a good reason why the long primitive data type is not allowed anyone know what it is,['java'] +57935,azure table storage maximum variable size i will be using the table storage to store a lot of blob names in a single string appended to each other using some special character this string will sky rockets pretty soon but is there a maximum size to the length of a property for a particular entity in my case the string,"['c#', '.net']" +57937,good way to cache data during android application lifecycle keeping my question short i have created an application with 3 activities where a list of categories b list of items c single item data thisplayed in b and c is parsed from online xml but if i go through a b1 c then back to a and then back to b1 i would like to have its data cached somewhere so i wouldnt have to request the xml againi am new to android and java programming i have googled a lot and still cannot find or simply do not have an idea where to look a way to do what i wantwould storing all received data in main activity a hashmaps contentproviders and then passing to b and c if they get same request that was before be a good idea,['android'] +57954,overriding inherited generic methods i have this code in base class protected virtual bool hasanystufftobjecttobject obj where tobjectclass return false in child class i am overridingprotected override bool hasanystuffcustomercustomer obj some stuff if customersth etc return false i am getting this errortype parameter declaration must be an identifier not a typewhat is it i am doing wrong here,['c#'] +57955,is it a good idea to apply some basic macros to simplify code in a large project i have been working on a foundational c library for some time now and there are a variety of ideas i have had that could really simplify the code writing and managing process one of these is the concept of introducing some macros to help simplify statements that appear very often but are a bit more complicated than should be necessary for example i have come up with this basic macro to simplify the most common type of for loopdefine loopvn forunsigned long v0 vn vthis would enable you to replace those clunky for loops you see so much offor int i 0 i max things iwith something much easier to write and even slightly more efficientloop i max thingsis it a good idea to use conventions like this are there any problems you might run into with different types of compilers would it just be too confusing for someone unfamiliar with the macros,['c++'] +57968,any pretty data visualization libraries for python there are plenty of prettyprinting visualization libraries for javascript eg those listed heregoogling for python visualization libraries only turns up stuff like vtk and mayavi which are primarily more for nononsense scientific useso do you know of any python libraries similar to those javascript ones in the above link i particularly like the javascript infovis toolkit,['python'] +57977,replace number in a string using regex or something else i am not so good with regex i am struggling to find a solution for a small functionalityi have a ajax response which returns a string like your ticket has been successfully logged please follow the link to view details 123432all i have to do is replace that number 123432 with a hrefblablablacomticket123432 using javascript,['javascript'] +57988,how does dropbox use python on windows and os x in windows the dropbox client uses python25dll and the ms c runtime libraries msvcp71dll etc on os x the python code is compiled bytecode pycmy guess is they are using a common library they have written then just have to use different hooks for the different platformswhat method of development is this it clearly is not ironpython or pyobjc this paradigm is so appealing to me but my cs foo and google foo are failing me,['python'] +57991,how to getting browser current locale preference using javascript does anyone know how to obtain the browser culture from firefox and google chrome using javascript note this is an aspnet 35 web applicationthe requirement is to try and set the applications thisplay culture based on the browser culture i have found very few bits and pieces of information for the other browsers but they do not seem to worki am able to get it in ie with the following snippet of codevar browserculture thisclientinformationbrowserlanguageany info would be great,['javascript'] +57996,how do i construct a slightly more complex filter using or or and in sqlalchemy i am trying to do a very simple search from a list of terms terms term1 term2 term3how do i programmatically go through the list of terms and construct the conditions from the list of terms so that i can make the query using filter and or or andeg queryfilteror something constructed from terms,['python'] +58009,this null how can it be possible recently i came across some strange behaviour of my application it has been developed mainly in c but clic was also used to achieve better performance i was getting a systemnullreferenceexception in a very simple method at the timespan comparisontimespan timestampvoid updateframetimespan timestamp iftimespanequals timestamp timestamp false it was obvious that the only reference used in this expression was implicit this this timestamp i added an assert statement and it turned out that this is actually null after short investigation i managed to prepared short program presenting this phenomenon it is ccliusing namespace systemusing namespace systemreflectionpublic class unmanagedpublic int valuepublic ref class managedpublic int value unmanaged getunmanaged samplemethod return new unmanaged void samplemethod systemdiagnosticsdebugassertthis nullptr thisvalue 0 public ref class managedaccessorpublic property managed mint mainarraysystemstring args managedaccessor ma gcnew managedaccessor confirm that mam null systemdiagnosticsdebugassertmam nullptr invoke method on the null reference delete mamgetunmanaged return 0does anybody know how can it be possible is it a bug in the compiler,['.net'] +58012,setresult does not work when back button pressed i am trying to setresult after the back button was pressed i call in ondestroyintent data new intentsetresultresult ok data but when it comes toonactivityresultint requestcode int resultcode intent data the resultcode is 0 result canceled and data is nullso how can i pass result from activity terminated by back button,['android'] +58014,catching javalangoutofmemoryerror documentation for javalangerror saysan error is a subclass of throwable that indicates serious problems that a reasonable application should not try to catchbut as javalangerror is a subclass of javalangthrowable i can catch this type of throwablei understand why it is not good idea to catch this sort of exception as far as i understand if we decide to catch it the catch handler should not allocate any memory by itself otherwise outofmemoryerror will be thrown againso my question isis there any real word scenarios when catching javalangoutofmemoryerror may be a good ideaif we decide to catch javalangoutofmemoryerror how can we sure that catch handler does not allocate any memory by itself any tools or best practices,['java'] +58019,how to serialize list i am writing common functions to serialize the given object and listobject as followspublic string serializeobjectobject pobject for given object try string xmlizedstring null memorystream memorystream new memorystream xmlserializer xs new xmlserializertypeofpobject xmltextwriter xmltextwriter new xmltextwritermemorystream encodingutf8 xsserializexmltextwriter pobject memorystream memorystreamxmltextwriterbasestream xmlizedstring utf8bytearraytostringmemorystreamtoarray return xmlizedstring catch exception e systemconsolewritelinee return null public string serializeobjectlistobject pobject for given listobject try string xmlizedstring null memorystream memorystream new memorystream xmlserializer xs new xmlserializertypeofpobject xmltextwriter xmltextwriter new xmltextwritermemorystream encodingutf8 xsserializexmltextwriter pobject memorystream memorystreamxmltextwriterbasestream xmlizedstring utf8bytearraytostringmemorystreamtoarray return xmlizedstring catch exception e systemconsolewritelinee return null first one is working fine if i pass any type it is successfully returning xml string correction compilation error has occurred for second one error cannot convert from listmytype to listobjecti rewrite the second one as follows which solves my problem now it is serializing the given listgeneric typesprivate string serializeobject source memorystream memorystream new memorystream xmlserializer xs new xmlserializertypeoft xmltextwriter xmltextwriter new xmltextwritermemorystream encodingutf8 xsserializexmltextwriter source memorystream memorystreamxmltextwriterbasestream string xmlizedstring utf8bytearraytostringmemorystreamtoarray return xmlizedstring,['c#'] +58035,correct way of showing consecutive modalviews i have two views that need to be shown modally one after the other this does not work if we thismiss and show consecutively like thisrootcontroller thismissmodalviewcontrolleranimated yesrootcontroller presentmodalviewcontroller psvc animated yesthe second modal view simply does not show upi have seen a fix that was something like thisrootcontroller thismissmodalviewcontrolleranimated yesuiapplication sharedapplication beginignoringinteractioneventsself performselector selectorseekmodal withobject nil afterdelay 05uiapplication sharedapplication endignoringinteractioneventsthe problem is that this would not work all the time the delay needed is superior sometimesanother possible fix would be to eliminate the animationrootcontroller thismissmodalviewcontrolleranimated norootcontroller presentmodalviewcontroller psvc animated yesbut i would really like to keep the animation to keep the feel that the first modal is out of the way any suggestions,['iphone'] +58038,uitableviewindex grows to incorrect bounds unexpectedly i have a standard uitableview uisearchthisplaycontroller uitableviewindex setup everything works like a champexcept under very specific conditions the index grows too long to thisplay on the screen specifically after ending a search and rethisplaying the unfiltered indexed table the index sometimes grows too longmore specifically this does not happen if i search then cancel it only happens if i search then push a view controller from the search table then pop that view controller back to the stillsearching table then cancel the search then research and then cancel that final search after the end of the final search the index is too longin portrait the table view is reporting a height of 416 and the index a height of 404 under normal conditions if i log from searchthisplaycontrollerdidendsearch when the index is sized incorrectly it is reporting a height of 620i have tried everything from setlayout on the table and the index to manually resizing the frame nothing works the manual resize causes the correct height to be logged but it does not change the thisplay on screen i was about to try resizing after a delay in case the cancel animation was interfering but then i realized what an absurd situation i am in and thought seeking help might be wise,['iphone'] +58042,case insensitive string columns in sqlalchemy can i create a case insensitive string column in sqlalchemy im using sqlite and theres probaby a way to do it through db by changing collation but i want to keep it in sqlalchemypython,['python'] +58043,how can i tell which button was clicked in a php form submit i have several buttons on my page but i am not sure how to tell which one was clickedheres the markup for my two buttonsinput typesubmit idbtnsubmit valuesave changes input typesubmit idbtndelete valuedelete,['php'] +58075,what does that java construct do i new to java so bear with me if this is a ridiculously simple question but i am curious about this method call which has code being taken in see code below for an example in the method addselectionlistener what is the purpose of this i have been looking through docs for an explaination but cant seem to find what this practice is called never mind any useful information setstatuslineaddselectionlistenernew selectionadapter public void widgetselectedselectionevent e string message i would like to say hello to you if pressed message thank you for using me setstatuslinemessage pressed pressed thanks for any help or insights that can be offered,['java'] +58076,how to store user settings username password in a windows application for the current logged in user now my team is working on a project involving a windows application cthe application has a option for saving the username and password in the client machine for the current logged in user the user can start the application without entering username and password please check the snapshot of my requirementplease suggest a good example or reference,"['c#', '.net']" +58079,how to add a button in android can anybody tell how to add a button in android,['android'] +58098,net json parser comparison i have been looking into several json parsers for net litjson jsonexserializer and jsonnet and was wondering if anyone has any experience with them and can shed some light on the differences and the pros and cons for each of them,['.net'] +58099,get classic asp variable from posted json i am trying to post json via ajax to a classic asp page which retrieves the value checks a database and returns json to the original pagei can post json via ajax i can return json from asp i cannot retrieve the posted json into an asp variablepost you use requestform get you use requestquerystring what do i use for jsoni have json libraries but they only show creating a string in the asp script and then parsing that i need to parse json from when being passed an external variablejavascriptvar thing thisvalajax type post url ajaxcheck usernameasp data username thing contenttype applicationjson charsetutf8 datatype json cache false async false success function alertsuccess asp file check usernameasp responsecontenttype applicationjson semail requestform the problem set ors servercreateobjectadodbrecordset sql select sysuserid from dbot sys user where usernamesemail orsopen sql oconn if not orseof then sstatus new jsontojsonusername true false else sstatus new jsontojsonusername false false end ifresponsewrite sstatus,['jquery'] +58105,need advice with html table i would like to code an html table with messages like thisthe table will contain messages that will spread over first and columns n may changelets call these and columns the message areaeach message is located on x contiguous cells in the message area x may also changeeach message has a name that contains words separated with underscoreshow would you recommend to code this table in javascriptjquery such thatit would be easy to define a message start cell end cell color namethe name will break only after underscores rather than in the middle of the word,"['javascript', 'jquery', 'html']" +58137,looping through the days of the week inside of c timespan class i am trying to loop through each dayof the week between 2 time periods datetime start new datetime2010 1 1 datetime end new datetime2011 12 12i have managed to get the number of days between these dates using the following code timespan range end startturn out to be 710i am now looking to get for each month the days of the weekfor instancejan1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 171 18 19 20 with the matchingm t w t f s s m t w t f s s mi understand c has a property from datetime class dayofweek which gets the day of the weekmy problem is constructing a loop to do the aboveanyone,['c#'] +58144,greatest not null column i need to update a row with a formula based on the largest value of two datetime columns i would normally do thisgreatestdate one date twohowever both columns are allowed to be null i need the greatest date even when the other is null of course i expect null when both are null and greatest returns null when one of the columns is nullthis seems to workgreatestcoalescedate one date two coalescedate two date onebut i wonder am i missing a more straightforward method,['sql'] +58158,mysql date add usage 5 day interval i am trying to select the order total sum and invoice count over a 5 day period in a single query i cannot seem to get this to happen though the current query i have is hereselect countid as invoice count sumordertotal as orders sum unix timestampcreated as createdfrom ids invoicewhere date addcreated interval 1 dayand userid 23 limit 5i am not entirely sure date add is the right function i am looking forcurrently i am gettingarray 0 array invoice count 420 orders total 9790290 created 1252596560 array 0 array invoice count 68 orders total 1419320 created 1262900809 i would like to get something more likearray 0 array invoice count 18 orders total 490290 date 04192010 array 0 array invoice count 12 orders total 519320 date 04202010 i am fairly new to mysql date functions so perhaps i just missed the function i needed when going through mysql docsupdatei have updated my query this still does not pull a row for each day that there were invoices for it is only pulling invoices from the 19th when there are invoices from the 20th that meet the userid criteriaselect countid as invoice count sumordertotal as orders sum unix timestampcreated as createdfrom ids invoicewhere created between 20100419 0 and date add20100419 0 interval 5 day and userid 17,['mysql'] +58160,how can i make a method return an argument that was passed to it consider a method signature likepublic string myfunctionstring abccan mockito help return the same string that the method received,['java'] +58167,make http11 request with php my code is using file get contents to make get requests to an api endpoint it looks like it is using http10 and my sysadmin says i need to use http11 how can i make an http11 request do i need to use curl or is there a bettereasier wayupdatei decided to use curl since i am using php 516 i ended up forcing http11 by doing thiscurl setoptch curlopt http version curl http version 1 1if i was using 53 or later i would have tried doing something like thisctx stream context createarray http arraytimeout 5 protocol version 11 res file get contentsurl 0 ctxecho resnote php prior to 530 does not implement chunked transfer decoding if this value is set to 11 it is your responsibility to be 11 compliantanother option i found which might provide http11 is to use the http extension,['php'] +58176,wpf or windows forms i have been playing around with c console applications for about a year and i want to move on to creating gui applications i have never done any gui development besides basic java applications but i want to continue using c should i start learning windows forms or jump straight to wpf is there a huge difference does wpf build on top of windows forms or are they totally different,['c#'] +58211,jquery how do i count the number of elements selected by a selector i am using fadeout to fade items out in a list li li when the list is empty i wish to hide a parent objecti plan on doing this by checking in my trigger event that fades the list if the count of the objects is 0 then hide the parent element i can use the fadeout callback to remove the elements if necessarythe to the point questionhow do i select li tags inside a ul and then get the total count of them using jquery,"['javascript', 'jquery']" +58240,jpa 2 and hibernate 351 member of query doesnt work i am trying the following jpql and it fails misserablyquery query emcreatequeryselect you from user you where admin member of uroleslist users queryquerygetresultlisti get the following exception error main parsererror454 ast00 unexpected end of subtreejavalangillegalargumentexception orghibernatehqlastquerysyntaxexception unexpected end of subtree select you from comonlinedatauser you where admin member of uroles error main parsererror454 ast00 expecting from found astnullcaused by orghibernatehqlastquerysyntaxexception unexpected end of subtree select you from comonlinedatauser you where admin member of urolesi have spring 301release hibernate 351final and maven to glue dependenciesuser classentitypublic class user id columnname user id generatedvaluestrategy generationtypeidentity private long id columnunique true nullable false private string username private boolean enabled elementcollection private setstring roles new hashsetstringspring configurationxml version10 encodingutf8beans xmlns xmlnsxsi xmlnscontext xmlnstx xmlnsp xmlnsaop xsischemalocation reading annotation driven configuration txannotationdriven transactionmanagertransactionmanager bean classorgspringframeworkdaoannotationpersistenceexceptiontranslationpostprocessor bean classorgspringframeworkormjpasupportpersistenceannotationbeanpostprocessor bean iddatasource classorgapachecommonsdbcpbasicdatasource destroymethodclose property namedriverclassname valuejdbcdriverclassname property nameurl valuejdbcurl property nameusername valuejdbcusername property namepassword valuejdbcpassword property namemaxactive value100 property namemaxwait value10 property namepoolpreparedstatements valuetrue property namedefaultautocommit valuetrue bean bean idtransactionmanager classorgspringframeworkormjpajpatransactionmanager property nameentitymanagerfactory refentitymanagerfactory property namedatasource refdatasource bean bean identitymanagerfactory classorgspringframeworkormjpalocalcontainerentitymanagerfactorybean property namedatasource refdatasource property namejpavendoradapter bean classorgspringframeworkormjpavendorhibernatejpavendoradapter property nameshowsql valuetrue property namedatabaseplatform valuehibernatedialect bean property property nameloadtimeweaver bean classorgspringframeworkinstrumentclassloadinginstrumentationloadtimeweaver property property namejpaproperties props prop keyhibernatehbm2ddlautoupdateprop prop keyhibernatecurrent session context classthreadprop prop keyhibernatecacheprovider classorghibernatecachenocacheproviderprop prop keyhibernateshow sqltrueprop prop keyhibernateformat sqlfalseprop prop keyhibernateshow commentstrueprop props property property namepersistenceunitname valuepunit bean bean idjpatemplate classorgspringframeworkormjpajpatemplate property nameentitymanagerfactory refentitymanagerfactory beanbeanspersistencexmlxml version10 encodingutf8persistence xmlns xmlnsxsi xsischemalocation persistenceunit namepunit transactiontyperesource local persistencepomxml maven dependencies dependency groupidorghibernategroupid artifactidhibernateartifactid versionhibernateversionversion typepomtype dependency dependency groupidorghibernategroupid artifactidhibernatecoreartifactid versionhibernateversionversion dependency dependency groupidorghibernategroupid artifactidhibernateannotationsartifactid versionhibernateversionversion dependency dependency groupidorghibernategroupid artifactidhibernateentitymanagerartifactid versionhibernateversionversion dependency dependency groupidcommonsdbcpgroupid artifactidcommonsdbcpartifactid version122version typejartype dependency dependency groupidorgspringframeworksecuritygroupid artifactidspringsecuritywebartifactid versionspringversionversion dependency dependency groupidorgspringframeworksecuritygroupid artifactidspringsecurityconfigartifactid versionspringversionversion dependency dependency groupidorgspringframeworksecuritygroupid artifactidspringsecuritytaglibsartifactid versionspringversionversion dependency dependency groupidorgspringframeworksecuritygroupid artifactidspringsecurityaclartifactid versionspringversionversion dependency dependency groupidjavaxannotationgroupid artifactidjsr250apiartifactid version10version dependency properties application settings springversion301releasespringversion hibernateversion351finalhibernateversionim running a unit test to check the configuration and i am able to run other jpql queries the only ones that i am unable to run are the is empty member of conditionsthe complete unit test is as followstestintegrationrunwithspringjunit4classrunnerclasscontextconfigurationlocations springdatalayerxmltransactionaltransactionconfigurationpublic class testuserdaoimplintegration persistencecontext private entitymanager em test public void shouldtest throws exception try worksquery query emcreatequeryselect you from user you where admin in elementsuroles list users queryquerygetresultlist catch exception e eprintstacktrace throw e try does not workquery query emcreatequeryselect you from user you where admin member of uroles list users queryquerygetresultlist catch exception e eprintstacktrace throw e,['java'] +58241,how can i make php thisplay the error instead of giving me 500 internal server error this has never happened before usually it thisplays the error but now it just gives me a 500 internal server error of course before when it thisplayed the error it was different servers now i am on a new server i have full root so if i need to configure it somewhere in the phpini i can or perhaps its something with apachei have been putting up with it by just transferring the file to my other server and running it there to find the error but that is become too tedious is there a way to fix this,['php'] +58244,how to accomplish covariant return types when returning a shared ptr using namespace boostclass a class b public a class x virtual shared ptra fooclass y public x virtual shared ptrb foothe return types are not covariant nor are they therefore legal but they would be if i was using raw pointers instead whats the commonly accepted idiom to work around this if there is one,['c++'] +58266,performance of net ilmerged assemblies i have two net libraries foobar and foobazfoobar is selfcontained while foobaz references foobarassuming i do the followinguse ilmerge to merge foobardll with foobazdll into foo1dllcreate a new solution containing the entirity of both foobar and foobaz since i have access to their source code and compile this into foo2dllwill there be any differences in the performance of foo1dll and foo2dll when using their functionality from an external project if so how significant is this performance difference and is it a onceoff on load or ongoing difference are there any other advantages or thisadvantages with either approach,['.net'] +58285,how to track changes in many sql server databases from net application problemthere are a lot of different databases which is populated by many different applications directly without any common application layer data can be accessed only through sp by policytask application needs to track changes in these databases and react in minimal timepossible solutions1 create trigger for each table in each database which will populate one table with events application will watch this table through sqldependency2 watch each table in each database through sqldependency3 create trigger for each table in each database which will notify application using managed extensionwhich is the best way,['.net'] +58297,good practices for multiple language data in core data i need a multilingual coredata db in my iphone app i could create different database for each language but i hope that in iphone sdk exist an automatically way to manage data in different language core data like for resources and stringsomeone have some hints,['iphone'] +58317,live vs bind i want to know the main difference betweenlive vs bind methods in jquery,['jquery'] +58340,spring security http basic authentication i am trying to do a really simple basic authentication with spring security i have configured the namespace properly and there are no exceptions in the server in my servletxml i have got the next for spring securitysecurityhttp securityhttpbasicsecurityhttpbasic securityintercepturl methodpost pattern accessrole user securityhttpsecurityauthenticationmanager aliasauthenticationmanager securityauthenticationprovider securityuserservice securityuser namecucu passwordtas authoritiesrole user securityuser namebob passwordbobspassword authoritiesrole user securityuserservice securityauthenticationprovidersecurityauthenticationmanagerit nearly all goes perfect the methods that are not post does not prompt any login form and the post method prompt it the problem is that nor cucu neither bob can login there can anyone see what am i doing wrongthanks in advance,['java'] +58348,android how to properly handle onpauseonresume methods i have an app that starts playing sounds and beginsresumes gameplay in the onresume method but what i am noticing is that if my app was the last run application when i put the phone into standby screen off and i just press the menu button to check the time then the phone starts playing the game and sounds in the background the app is not actually visible only the screen with the datetime is yet onresume must have been called in my app what am i to do here is there a way to thiscern what is reactivating the app and then add a conditional statement that only starts the game when the app is actually visiblehere is a snippet from my onresumeoverride protected void onresume mysavegame utilitiesloadsavegamethis check the savegame ifmysavegamenull start game using savegame values thisstartfromsavedgamemysavegamegetislevelcomplete else run the 1strun components thisstartfirstrun superonresume the only thing i can think of doing to prevent the game from starting whenever the screen gets turned on even when the app is not visible is to put thisfinish as the last line in onpause but that forces you to restart the app every time you want to go back to it because the precess itself was killed which is fine because my onpause saves persistent data but it is not an elegant solutionplease help,['android'] +58371,mysql count all rows per table for in one query is there a way to query the db to find out how many rows there are in all the tablesietable1 1234table2 2table3 78hope you can advise,"['sql', 'mysql']" +58384,adding css rules with text method to style element does not work in ie it works fine in firefox and chrome but does not work in ie8 here is the html structuredoctype htmlhtml head meta httpequivcontenttype contenttexthtml charsetutf8 script typetextjavascript srcscript script typetextjavascript function this does not work in ie style typetextcstyletextbody margin 0appendtohead script head body bodyhtmland what s the alternative to do this in ie,['jquery'] +58396,what is unchecked cast and how do i check it i think i get what unchecked cast means casting from one to another of a different type but what does it mean to check the cast how can i check the cast so that i can avoid this warning in eclipsethanks,['java'] +58410,how to use mkdir and rmdir commands in a java program i want to use system commands like mkdir and rmdir while running a java programhow can i do that,['java'] +58412,extract images from pdf without resampling in python how might one extract all images from a pdf document at native resolution and format meaning extract tiff as tiff jpeg as jpeg etc and without resampling layout is unimportant i do not care were the source image is located on the pagei am using python 27 but can use 3x if required,['python'] +58427,returning a shared library symbol table for instancevoid sdl library dlopenlibsdlso rtld lazyvoid initializer dlsymsdl librarysdl initassuming no errors initializer will point to the function sd init in the shared library libsdksohowever this requires knowing the symbol sdl init exists is it possibly to query a library for all its symbols eg in this case it would return sdl init the function pointer and any other symbols exported by libsdlso,['c'] +58435,aspnet mvc 2 need to add a default property to a strongly typed htmltextbox helper in aspnet mvc 2 i am having a problem with something that i am sure is very simple i have been using aspnet mvc and i decided to start using aspnet mvc 2 something has changed and now i need a little help the strongly typed helpers are now written like this htmltextboxformodel modelstate i need to add a default value to a textbox in the prior version of aspnet mvc it was easy to assign a default value i thought doing the following would work in mvc 2 htmltextboxformodel modelcountyid new value 840 this however does not work for me in aspnet mvc 2 the value is still blank for the textbox i want to make sure that this is not some random error that i am having has anyone else encountered the same problem i have searched and searched to find more information on the default property for the html helpers in mvc 2 but i cannot find anything does anyone out there know how to correctly assign a default value to a textbox in aspnet mvc 2,['asp.net'] +58436,find an element in dom based on an attribute value can you please tell me if there is any dom api which search for an element with given attribute name and attribute valuesomething likedocfindelementbyattributemyattribute avalue,['javascript'] +58437,no main in wpf i am very beginner when it comes to programming but i was sure that one of the universal rules was that an program starts with main i do not see one when i create a wpf project is main simply named something differently in wpf,['c#'] +58443,how to deserialize xmldocument to object in c i have a net webserivce that accepts xml in string format xml string sent into the webserivce can represent any object in the system i need to check the first node to figure out what object to deserialize the xml string for this i will have to load the xml into an xmldocument do not want to use regex or string compare i am wondering if there is a way to deserialize the xmldocumentxmlnode rather that deserializing the string to save some performance is there going to be any performance benefit serializing the xmlnode rather that the stringmethod to load xmldocumentpublic void loadfromstringstring s m xmldoc new xmldocument m xmldocloadxmls thanks,"['c#', '.net']" +58449,how can i get the first element in an nsdictionary i have an array of nsdictionaries how can i pull out the first element in the dictionary nsarray messages results objectforkeymessages valueforkeymessage for nsdictionary message in messages stobject mystobject stobject alloc init mystobjectstid message valueforkeyid stid mystobjectstid,"['iphone', 'objective-c']" +58466,how to test website for ipad without having ipad in both condition portrait and landscape how to test website compatibility for ipad without having ipad in both condition portrait and landscape on windows pc,['css'] +58484,how does the compiler choose which method to call when a parameter type is ambiguous i have the following code testmethod public void testfoo foonull private void foo object bar consolewritelinefoo object private void foo string bar consolewritelinefoo string and when i run the test testfoo the console output is foo string how does the compiler decide which method to call,['c#'] +58489,python list and string matching i have followingtemp ab123xyzlists abc 12335 xyz andfor list in lists if rematchlist temp rei print the s is within s listtempthe rematch is only match the beginning of the string how to i match substring in between too,['python'] +58504,how to draw an uilabel in drawrect must i also do all this crazy coordinate system conversion stuff here or is an uilabel different from an uiimageview drawing in drawrect there is a method called voiddrawtextinrectcgrectrect for thatbut the documentation says you should not call this method directly this method should only be overridden by subclasses that want to modify the default drawing behavior for the labelas textso how to draw it then in drawrect,['iphone'] +58508,python syntax error cannot assign to operator in module but works in interpreter i have a string a and i would like to split it in half depending on its length so i haveafront lena 2 lena 2this works fine in the interpreter but when i run the module from the command line python gives me a syntaxerror cannot assign to operator what could be the issue here,['python'] +58510,multiprocessing bomb i was working the following example from doug hellmann tutorial on multiprocessingimport multiprocessingdef worker worker function print worker returnif name main jobs for i in range5 p multiprocessingprocesstargetworker jobsappendp pstartwhen i tried to run it outside the if statementimport multiprocessingdef worker worker function print worker returnjobs for i in range5 p multiprocessingprocesstargetworker jobsappendp pstartit started spawning processes nonstop and the only way to stop it was rebootwhy would that happen why it did not generate 5 processes and exit why do i need the if statement,['python'] +58526,strange unexpected behavior thisappearingchanging values when using hash default value eg hashnew consider this codeh hashnew0 new hash pairs will by default have 0 as valuesh1 1 11h2 2 22thatas all fine buth hashnew empty array as default valueh1 1 11 a okh2 2 112 212 a why did 1 changeh3 3 1123 2123 a where is 3at this point i expect the hash to be11 22 33but itas far from that what is happening and how can i get the behavior i expect,['ruby'] +58528,how do i make my code easier for the next developer to understand i have been at my very first programming job for about 8 months now and i have learned incredible amounts so farunfortunately i am the sole developer for a small startup company for internal applicationsfor the first time ever though i will be handing off some of my projects to someone else when i leave this job i have documented all my projects thoroughly at least i think so but i still feel nervous about someone else reading my codefor example i have always done this sort of thingfor int i 0 i blahlength ido stuffshould i name i something descriptive it is only a temporary variable and will only exist within that loop and it seems that it is pretty obvious what the loop does with ithis is just one example another one is that i name variables differently i do not really conform to a standard of naming besides starting all private members with an underscoreare there any resources that could show me how to make it easier for the next developer are there standards for this type of thing,['c#'] +58529,what issues might i have in opening net 20 projects in visual studio 2010 the small software team i work on recently got approved to upgrade to visual studio 2010 were currently using vs 2005 we have several aspnet 20 and winforms in net 20 projects in productioni have been tasked with downloading vs 2010 and seeing how well it plays with our current projects what issues should i be aware of when targeting older applications in vs 2010 if i open a vs 2005 project in vs 2010 will it still place nicely when my teammate goes back to open the project in vs 2005 will we have to upgrade projects to work in vs 2010 assuming the projects themselves are not upgraded to net 4 can i use vs 2010 to edit legacy vb6 apps just kiddingi am excited to work with the newest software but were concerned about running into development snags on production applications that are already working just finenote i started a bounty in hopes of getting a more detailed answer to this question perhaps the answer really is as simple as those already provided but i am interested in more feedback regarding our options to transition from using vs 2005 to vs 2010,['.net'] +58535,can an x64 application use x86 assemblies and vice versa my application is built as a x64 application after moving to vs2010 i got some problems which seems to be related to some x64x86 mismatch in referenced dlls now i am moving to target net4 and i get even more similar problems my question is what precautions do i need to take regarding mixing x64 and x86 can it be done at all i thought x64 applications should be able to use x86 dlls without problems no what about the other way can a x86 application reference an x64 dll as long as it is being run on an x64 platform what are the pitfalls i need to be aware of,['.net'] +58543,stl map sort by value i wonder how can i implement the stl map sorting by valuefor example i have a map mmapint intm1 10m2 5m4 6m6 1and then i would like to sort that with the ms valueso if i print the map i would like to get the result likem6 1m2 5m4 6m1 10thishow can i sort like this wayis there any way that i can deal with the key and value with sorted values,['c++'] +58547,execute javascript in php i am generating your typical web 20 html page with php it contains a lot of script tags and javascript code that will substantially change the dom after the load eventis there a way to get the final html code directly from php without opening the page with any browserfor example let us say the html for the page is it is just an examplehtmlheadscriptthe jquery library codescriptscriptdocumentreadyfunction bodyappendphipscriptheadbodybodyhtmlthis html is saved in the html php variable now i want to pass that variable to some function that will return result htmlbodyphipbodyhtmlis this possibleedit since many of you were perplexed by my request i will explain the reason unfortunately everything user facing was made in javascript and this makes the website uncrawlable by search engines so i wanted to send them the postready event html code instead,"['php', 'javascript', 'html']" +58550,jquery script tags in the html are parsed out by jquery and not executed i have an html page like sohtmlbodydiv idsomething script var x hello world script divbodyhtmlon another page i am doing thisajax url examplehtml type get success functiondata mydivhtmldatafindsomethinghtml alertx jquery however is not executing the javascript in the first file even though the documentation says it does how can i make it do thatedit unfortunately in the real world application i am working on i do not have control over what the included page has we are on the same domain but i cannot modify the code that it outputs as it is a packaged product our it department will not let us modify,"['javascript', 'jquery']" +58555,difference between unchecked exception or runtime exception this was an interview question what is the main difference between unchecked exception and error as both are not caught they will terminate the program,['java'] +58558,stdlist iterator get next element i am trying to build a string using data elements stored in a stdlist where i want commas placed only between the elements ie if elements are abcd in list result string should be abcdthis code does not worktypedef stdlist shared ptreventdataitem dataitemlist stdstring composedataitemlist dillist stdstringstream ssdatasegment foriteritems dillistbegin iteritems dillistend iteritems lookahead in list to see if next element is end ifiteritems 1 dillistend ssdatasegment iteritemstostring else ssdatasegment iteritemstostring return ssdatasegmentstrhow do i get at thenextitem in a stdlist using an iterator i would expect that it is a linkedlist why cannot i get at the next item,['c++'] +58559,is there a method missing for rake tasks if my rakefile does not find a task with a particular name i would like rake to instead create a new task by that name according to certain rules if a file with the missing task name exists but if it does not i want to fall back to the default do not know how to build task fooin short is there a method missing for rake,['ruby'] +58570,how to thisable text selection using jquery does jquery or jqueryui have any functionality to thisable text selection for given document elements,"['javascript', 'jquery']" +58591,table per subclass inheritance relationship how to query against the parent class without loading any subclass hibernate suppose a table per subclass inheritance relationship which can be described bellow from wikibooksorg see herenotice parent class is not abstractentityinheritancestrategyinheritancetypejoinedpublic class project id private long id other propertiesentitytablenamelargeprojectpublic class largeproject extends project private bigdecimal budgetentitytablenamesmallprojectpublic class smallproject extends project i have a scenario where i just need to retrieve the parent class because of performance issues what should i do to run a hql query in order to retrieve the parent class and just the parent class without loading any subclass,['java'] +58596,avoiding the tedium of optional parameters if i have a constructor with say 2 required parameters and 4 optional parameters how can i avoid writing 16 constructors or even the 10 or so constructors i would have to write if i used default parameters which i do not like because it is poor selfdocumentation are there any idioms or methods using templates i can use to make it less tedious and easier to maintain,['c++'] +58601,problem changing java version using alternatives i am not quite sure how i got into this mess but for some reason i am not able to change the current version of java using alternatives i can run alternatives config java and type my selection but when i echo the version number for either java or javac it spits back out 15 every time despite alternatives showing the current version is 16 the server i am working with is running rhel5 by the wayi have verified that the paths used in alternatives are pointing to the correct directories heres some output from my sessionbrilewismyserver sudo usrsbinupdatealternatives config javathere are 3 programs which provide javaselection command 1 usrlibjvmjre142gcjbinjava 2 usrjavajdk150 10binjava 3 usrjavajdk160 16binjavaenter to keep the current selection or type selection number 3 brilewismyserver java version java version 150 10 javatm 2 runtime environment standard edition build 150 10b03 java hotspottm server vm build 150 10b03 mixed modebrilewismyserver sudo usrsbinupdatealternatives config javathere are 3 programs which provide javaselection command 1 usrlibjvmjre142gcjbinjava 2 usrjavajdk150 10binjava 3 usrjavajdk160 16binjavaenter to keep the current selection or type selection number update the following is the output of echo pathusrjavajdk150 10binusrlocalapacheant171binusrlocalapachetomcat6024usrkerberosbinusrlocalbinbinusrbinusrnxbinhomebrilewisbinupdate 42610 i followed berts suggestion and removed java home from the path environment var in etcprofile after doing this i was able to use alternatives to change the version of java the only problem is that when i try to run javac i get bash javac command not found this does not happen when the version is set to 15,['java'] +58617,java generics and the addall method what is the correct type of argument to the addall method in java collections if i do something like thislist extends mapstring object currentlist new arraylistmapstring objectcollectionhashmapstring object addall new arraylisthashmapstring object add some hashmaps to the listcurrentlistaddalladdall i understand i need to initialize both variables however i get a compilation error from eclipsemultiple markers at this line the method addallcollection extends capture1of extends mapstringobject in the type listcapture1of extends mapstringobject is not applicable for the arguments listcapture2of extends mapstringobject the method addallcollection extends capture1of extends mapstringobject in the type listcapture1of extends mapstringobject is not applicable for the arguments collectionhashmapstringobjectwhat am i doing wrong,['java'] +58623,a generic list of generics i am trying to store a list of generic objects in a generic list but i am having difficulty declaring it my object looks likepublic class fieldt public string name get set public string description get set public t value get set i would like to create a list of these my problem is that each object in the list can have a separate type so that the populated list could contain something like this fielddatetime fieldint fielddouble fielddatetime so how do i declare thatlistfieldi would like to stay as typesafe as possible so i do not want to use an arraylist,['c#'] +58631,how to stop net httpwebrequestgetresponse raising an exception surely surely surely there is a way to configure the net httpwebrequest object so that it does not raise an exception when httpwebrequestgetresponse is called and any 300 or 400 status codes are returnedjon skeet does not think so so i almost dare not even ask but i find it hard to believe there is no way around this 300 and 400 response codes are valid responses in certain circumstances why would we be always forced to incur the overhead of an exceptionperhaps there is some obscure configuration setting that evaded jon skeet perhaps there is a completely different type of request object that can be used that does not have this behaviorand yes i know you can just catch the exception and get the response from that but i would like to find a way not to have tothanks for any help,"['.net', 'asp.net']" +58638,iphone horizontal scrolling table i need to create a view on the iphone that scrolls horizontally through a gallery of images the issue is that this gallery has the potential to have 100s to 10s of images that needs to be presented so i would like to avoid loading them all into a single uiscrollview at once and destroying performance i need to create a view that recycles the view objects like uitableview to increase performance and reduce memory overhead but it needs to scroll in a horizontal fashionany ideas is it possible to make uitableview operation horizontallythanks,['iphone'] +58655,how to make animated gifs work from android webview animated gif images rendered by androids webview do not seem to animate has anyone figured out how to make them work i am testing on an n1 with 21u1 none of the web settings available seem applicable,['android'] +58660,java loop every minute i want to write a loop in java that firs starts up and goes like thiswhile x wait one minute or two execute codei want to do this so that it does not use up system resources what is actually going on in the code is that it goes to a website and checks to see if something is done if it is not done it should wait another minute until it checks again and when its done it just moves on is their anyway to do this in java,['java'] +58670,list comprehension map and numpyvectorize performance i have a function fooi that takes an integer and takes a significant amount of time to execute will there be a significant performance difference between any of the following ways of initializing aa fooi for i in xrange100a mapfoo range100vfoo numpyvectorizefooa vfoorange100i do not care whether the output is a list or a numpy arrayis there a better way,['python'] +58681,process list on linux via python how can i get running process list using python on linux,['python'] +58690,jquery add table row after the row which calling the jquery i have got a tabletable idservers section namei loopownsitestr idsite id ownsitesiidtdownsitesiphonetdtd classicona idownsitesiid onclickreturn makedeleterowthisgetattributeid atdtr sectiontbodytableand this java scriptscript typetextjavascriptfunction makedeleterowid deleteremove serversappenddocumentcreateelementtrattrid delete deleteappenddocumentcreateelementtdattrcolspan 9 id deleter deletertextbiztosan taralni szeretnad ezt a weblapod deleterappenddocumentcreateelementinputattrtype submit id id onclick return truedeleterowthisgetattributeid deleterappenddocumentcreateelementinputattrtype hidden name website del value id scriptit is working fine it makes a tr after the tables last tr and put the info to it and the delete function also works finebut i would like to make this append after the tr with td classicon which calling the script how can i do this,"['jquery', 'html']" +58699,returning from method inside a synchronized block i would just like to know if it is advised to return from a method within a synchronized block for example idtest synchronizedself if a return a else return b as opposed to idtest nsstring value synchronizedself if a value a else value b return valuethis sample is rather simplistic but sometimes in a complex method it would make things simpler to be able to return from within a synchronized block,"['ios', 'objective-c']" +58701,what are cdn best practices i have recently started using the rackspace cloudfiles cdn limelight about which i have some questionsi am using jquery jquery ui and jquery tools in addition to custom js code also my site is written in aspnet which means there is some aspnet generated js coderight now what i have done is that i have combined all of the js including the jquery code except the aspnet generated js into one file i am hosting this on the rackspace cdni am wondering if it would make more sense to just get the jquery jquery ui files from the google hosted cdn which i suspect would work very well in serving these files since they will be in many users cache already this would mean one extra http request so i am not sure if it will helpright now i have multiple containers for my assets for example in rackspace i have 3 containers js css and images the url subdomain for all 3 is different will that lead to a performance penalty should i just use one container and thus one domain for the cdnis there a way of having the ms aspnet generated js loaded from ms cdn would this have a performance hit as per the above question,['jquery'] +58702,autounboxing fail for compound assignment thanks to the implicit casting in compound assignments and incrementdecrement operators the following compilesbyte b 0b b b bb b b b b bb b b bb b b band thanks to autoboxing and autounboxing the following also compilesinteger ii 0ii ii ii i ii ii ii ii i ii ii i ii ii iiand yet the last line in the following snippet gives compiletime errorbyte bb 0bb bb bb bb okay so farbb bb does not compile the operator is undefined for the argument types byte bytecan anyone help me figure out whats going on here the byte b version compiles just fine so should not byte bb just follow suit and do the appropriate boxing and unboxing as necessary to accommodateextra questionso is there a way to make compound assignment operators work with byte character and short on the left hand side or are they simply illegal for these types,['java'] +58705,java rest implementation jersey vs cxf what do you think is the advantagesthisadvantages between this two libraries which of these two are best suited for production environment by the way i will be using json instead of xmli also would like to know what library is most supported by the community eg tutorials documentation,['java'] +58750,why write my understanding is that mime types are set by the web server why do we add the typetextjavascript or typetextcss attribute is not this a useless and ignored attribute,"['javascript', 'html', 'css']" +58757,how do i generate a random int number in c how do i generate a random int number in c,['c#'] +58775,how to show hidden divs on mouseover how to simply show a set of hidden divs on mouseover so if div1div2 div3all need to be shown on mouseover how to i do this,"['javascript', 'css', 'html']" +58784,whats the bestpractice way to update an adapters underlying data i am running into an illegalstateexception updating an underlying list to an adapter might be an arrayadapter or an extension of baseadapter i do not remember i do not have or remember the text of the exception at the moment but it says something to the effect of the lists content changing without the adapter having been notified of the changethis list may be updated from another thread other than the ui thread main after i update this list adding an item i call notifydatasetchanged the issue seems to be that the adapter or listview attached to the adapter attempts to update itself before this method is invoked when this happens the illegalstateexception is thrownif i set the listviews visibility to gone before the update then visible again no error occurs but this is not always practicali read somewhere that you cannot modify the underlying this from another threadthis would seem to limit an mvc pattern as with this particular list i want to add items from different threads i assumed that as long as i called notifydatasetchanged i would be safethat the adapter did not revisit the underlying list until this method was invoked but this does not seem to be the casei suppose what i am asking is can it be safe to update the underlying list from threads other than the ui additionally if i want to modify the data within an adapter do i modify the underlying list or the adapter itself via its add etc methods modifying the data through the adapter seems wrongi came across a thread on another site from someone who seems to be having a similar problem to mine this is from where i grabbed the visibilitygone and visible ideato give you a better idea of my particular problem i will describe a bit of how my list adapter etc are set upi have an object named queue that contains a linkedlist queue extends observable and when things are added to its internal list through its methods i call setchanged and notifylisteners this queue object can have items added or removed from any number of threadsi have a single queue view activity that contains an adapter this activity in its oncreate method registers an observer listener to my queue object in the observers update method i call notifydatasetchanged on the adapteri added a lot of log output and determined that when this illegalstateexcption occurs that my observer callback was never invoked so it is as if the adapter noticed the lists change before the observer had a chance to notify its observers and call my method to notify the adapter that the contents had changedso i suppose what i am asking is is this a good way to rigup an adapter is this a problem because i am updating the adapters contents from a thread other than the ui thread if this is the case i may have a solution in mind give the queue object a handler to the ui thread when it is created and make all list modifications using that handler but this seems improperi realize that this is a very openended post but i am a bit lost on this and would appreciate any comments on what i have written,['android'] +58798,get a css value from external style sheet with javascriptjquery is it possible to get a value from the external css of a page if the element that the style refers to has not been generated yet the element is to be generated dynamicallythe jquery method i have seen is elementcssproperty but this relies on element being on the page is there a way of finding out what the property is set to within the css rather than the computed style of an elementwill i have to do something ugly like add a hidden copy of the element to my page so that i can access its style attributes,"['javascript', 'jquery', 'css']" +58802,whats the difference between z and z in a regular expression and when and how do i use it from z the end of the input but for the final terminator if anyz the end of the inputbut what does it mean in practice can you give me an example when i use either the z or zin my test i thought that stackoverflownmatchesstackoverflowz will return true and stackoverflownmatchesstackoverflowz returns false but actually both return false where is the mistake,['java'] +58806,how to convert a char pointer into a c string i have a c string i need to pass this string to a function accepting a char parameter for example strchr a how do i get that pointer b is there some function equivalent to strschr that works for c strings,['c++'] +58811,recursive linq calls i am trying to build an xml tree of some data with a parent child relationship but in the same tablethe two fields of importance arecompetitionidparentcompetitionidsome data might becompetitionid1parentcompetitionidnullcompetitionid2parentcompetitionid1competitionid3parentcompetitionid1the broken query i have simply thisplays results in a flat format seeing that i am working with xml some sort of recursive functionality is required i can do this using normal for loop recursion but would like to see the linq version any help appreciatedvar results from c1 in comps select new ccompetitionid subcomps from sc in compswhere c2 c2competitionid c1competitionid select sc updatei found an interesting article by chris eargle here that shows you how to call lambda delegates recursively here is the code thanks chrisfuncint int factoral x x 1 1 x factoralxfuncint int factoral nullfactoral x x 1 1 x factoralx added code formatting to show the lamba funcsthe trick is to assign null to the func delegate first,['c#'] +58816,xcodebuild how to define preprocessor macro how can i define a preprocessor macro when using xcodebuildi need to build my app using a bunch of different configurations and i would like to do this using a shell script which runs xcodebuild a number of times with different preprocessor macros,['iphone'] +58843,how do i keep jtextfields in a java swing boxlayout from expanding i have a jpanel that looks something like thisjpanel panel new jpanelpanelsetlayoutnew boxlayoutpanel boxlayouty axispaneladdjtextfield1paneladdboxcreateverticalstrut10paneladdjbutton1paneladdboxcreateverticalstrut30paneladdjtextfield2paneladdboxcreateverticalstrut10paneladdjbutton2 etcmy problem is that the jtextfields become huge vertically i want them to only be high enough for a single line since that is all that the user can type in them the buttons are fine they do not expand verticallyis there any way to keep the jtextfields from expanding i am pretty new to swing so let me know if i am doing everything horribly wrong,['java'] +58849,count number of bits in a 64bit long big integer i have read through this so question about 32bits but what about 64bit numbers should i just mask the upper and lower 4 bytes perform the count on the 32bits and then add them together,['c#'] +58862,how to pickle yourself i want my class to implement save and load functions which simply do a pickle of the class but apparently you cannot use self in the fashion below how can you do this self cpickleloadf cpickledumpselff2,['python'] +58865,how to speed up calculation of length of longest common substring i have two very large strings and i am trying to find out their longest common substringone way is using suffix trees supposed to have a very good complexity though a complex implementation and the another is the dynamic programming method both are mentioned on the wikipedia page linked aboveusing dynamic programmingthe problem is that the dynamic programming method has a huge running time complexity is onm where n and m are lengths of the two stringswhat i want to know before jumping to implement suffix trees is it possible to speed up the algorithm if i only want to know the length of the common substring and not the common substring itself,['c++'] +58867,rails upload file to ftp server i am on rails 235 and ruby 186 and trying to figure out how to let a user upload a file to a ftp server on a different machine via my rails app also my rails app will be hosted on heroku which does not facilitate the writing of files to the local filesystem indexhtmlerb form tag ftpupload method post multipart true do label forfilefile to uploadlabel file field tag file submit tag upload end ftp controllerrbrequire netftpclass ftpcontroller applicationcontroller def upload file paramsfile ftp netftpnewremoteftpserver ftploginuser passwd ftpputbinaryfilefileread filebasenamefileoriginal filename ftpquit end def index endendcurrently i am just trying to get the rails app to work on my windows laptop with the above code i am getting this error errnoenoent in ftpcontrolleruploadno such file or directory followed by a dump of the file contentsi am trying to upload a csv file if that makes any difference anyone knows whats going on,['ruby-on-rails'] +58870,how can i pass more than one command line argument via c i need to pass more than one command line argument via c for a process called handleexeieutf8qhandleexefirst i need to run the executable file via administrator permissions this post has helped me achieve just thatbut then comes the next problem of calling the actual line arguments such as p explorehow can i specify the command line arguments together or maybe consecutivelycurrent code is as follows process p new process procestartinfo procestartinfo new procestartinfofilepath procestartinfocreatenowindow true procestartinfouseshellexecute false procestartinforedirectstandardoutput true procestartinforedirectstandardinput true procestartinfoverb runas procestartinfoarguments env user administrator cmd pstartinfo procestartinfo pstart string output pstandardoutputreadtoend pwaitforexit consolewritelineoutput thanks,['c#'] +58876,why do we need break after case statements why does not the compiler automatically put break statements after each code block in the switch is it for historical reasons when would you want multiple code blocks to execute,['java'] +58883,calling finish after starting a new activity the first activity that loads in my application is an initialization activity and once complete it loads a new activity i want to ensure if the user presses back they go straight to the launcher and not the initialization screen side note is this even the best approach or would this be better done with some kind of intent flagis it correct to call finish after calling startactivity on the new activityoncreate startactivitynew intentthis nextactivityclassfinishi am still taking in the whole message queue method of doing things in android and my assumption is that calling startactivity and then finish from my first activitys oncreate will log each respective message in the message queue but finish execution of oncreate before moving on to starting the next activity and finishing my first one is this a correct understanding,['android'] +58896,python if x is not none or if not x is none i have always thought of the if not x is none version to be more clear but googles style guide implies based on this excerpt that they use if x is not none is there any minor performance difference i am assuming not and is there any case where one really does not fit making the other a clear winner for my conventioni am referring to any singleton rather than just noneto compare singletons like none use is or is not,['python'] +58903,adding text over existing pdfs using reportlab i am interested in filling out existing pdf forms programatically all i really need to do is pull information from user input and then place the appropriate text over an existing pdf in the appropriate locations i can already do this with reportlab by feeding the same sheet of paper into a printer twice but this just really rubs me the wrong wayi am tempted to just personally reverse engineer each existing pdf and draw every line and character myself before adding the userinputted text but i wanted to check to see if there was an easy way to take an existing pdf and set it as a background for some extra text i would really prefer to use python as it is the only language i feel comfortable withi also realize that i could just scan the document itself and use the resulting raster image as a background but i would prefer the precision of vector graphicsit seems like reportlab has a commercial product with this functionality and the specific function i am looking for is in it copypages but it seems like overkill to pay for a 4 figure product for a single simple function for a nonprofit use,['python'] +58908,changing the text on a uiswitch the uiswitch currently says on and off can i change the text to yes and nowould it be hard or do i just rephrase the question i ask the user,['iphone'] +58944,ulcss for grid layout i have a servergenerated html likeul li few nested elements that form a block li li few nested elements that form anaother block li li etc x times liulall blocks have known width 200px and unknown height i want li to be arranged in tablelike fashion like thiswhat i have for now is following cssli thisplay block width 200px float left margin 10pxall is fine except that columns do not get equal height and in example above block 4 asnatcha at 1 and the result is not what i am trying to achieveis there any purecss crossbrowser way that will allow grid layout i want and will not enforce markup change,"['html', 'css']" +58947,which framework exceptions should every programmer know about i have recently started a new project in c and as i was coding some exception throw in a function i figured out i did not really know which exception i should usehere are common exceptions that are often thrown in many programs argumentexception argumentnullexceptioninvalidoperationexceptiondividebyzeroexceptionfilenotfoundexceptionare there any framework exceptions you often use in your programs which exceptions should every net programmer know about when do you use custom exception edit in order to clarify the topic the original question was more about which exception can i throw than what kind of exceptions should i catch,"['c#', '.net']" +58964,get maven artifact version at runtime i have noticed that in a maven artifacts jar the projectversion attribute is included in two filesmetainfmavengroupidartifactidpompropertiesmetainfmavengroupidartifactidpomxmlis there a recommended way to read this version at runtime,['java'] +58966,why does not pythons resplit split on zerolength matches one particular quirk of the otherwise quite powerful re module in python is that resplit will never split a string on a zerolength match for example if i want to split a string along word boundaries resplitrsb split along words preserve punctuationsplit along words preserve punctuationinstead of split along words preserve punctuation why does it have this limitation is it by design do other regex flavors behave like this,['python'] +58969,ambiguous access to base class template member function in visual studio 2008 the compiler cannot resolve the call to setcustomer in tmain below and make it unambiguoustemplate typename tconsumerstruct producer void setconsumertconsumer consumer consumer consumer tconsumer consumer struct appleconsumerstruct meatconsumerstruct shillyshallyproducer public producerappleconsumer public producermeatconsumerint tmainint argc tchar argv shillyshallyproducer producer appleconsumer consumer producersetconsumerconsumer ambiguous call return 0this is the compilation error error c2385 ambiguous access of setconsumer could be the setconsumer in base producerappleconsumer or could be the setconsumer in base producermeatconsumeri thought the template argument lookup mechanism would be smart enough to deduce the correct base producer why is not iti could get around this by changing producer totemplate typename tconsumerstruct producer template typename tconsumer2 void setconsumertconsumer2 consumer consumer consumer tconsumer consumer and call setconsumer as producersetconsumerappleconsumerconsumer unambiguous callbut it would be nicer if i did not have to,['c++'] +58970,how to remove border around buttons i have a jpanel with the gridlayout in every cell of the grid i have a button i see that every button is surrounded by a gray border i would like to remove these borders does anybody know how it can be done,['java'] +58987,comment associative array in php documentor i use several associative arrays in my php application and i am using php documentor to comment my sources i never really did specify comments for the arrays in an array but now i need to do that and do not know howarray arrayid test class tester options arrayoption1 1 option2 2how do i comment this array in the correct way for var and param commentsi could do this like this but i do not know if this is correctparam string arrayidparam string arrayclassparam int arrayoptionsoption1but how to do this for the var part,['php'] +58991,access the path to the appconfig programmatically i am looking for a way to programmatically obtain the path to the appconfig file from within a windows service executablethe build process changes appconfig to programnameexeconfig and i could do something likevar configfile pathcombineappdomaincurrentdomainbasedirectory programnameexeconfighowever i am looking for some way of obtaining the config file name at runtime that does not involve hard coding the exe name into the application configurationmanager has some way of doing it so it must be possible,['c#'] +58995,how to determine if a net type is a custom struct how to write a simple method that checks whether a concrete type is a custom struct created with public struct or notchecking typeisvaluetype is not enough because it is also true to int long etcand adding a check to isprimitivetype would not exclude decimal datetime and maybe some other value types i know that most of the built in value types are actually structs but i only want to check for custom structsthese questions are mostly the same but without the answer i need123edit from the answers mentioned the check for the system prefix was the most stable although it is still a hack i finally decided to create an attribute that you have to decorate the struct with in order the framework to pick it up as a custom struct the other choice i thought was to create an empty interface and let the struct implement that empty interface but the attribute way seemed more eleganthere is my original custom struct checker if someone if interestedtypeisvaluetype typeisprimitive typenamespacestartswithsystem typeisenum,"['c#', '.net']" +58997,eclipse java profiler i am trying to find a free profiler for eclipse that works well i would like a graphical breakdown of execution time in particular i have tried tptp but have had no luck at all with gui apps it took almost a minute for a gui app to start and was virtually unusable on screen it uses a lot of java opengl so i am not sure if it has to do with that i liked yourkit but unfortunately it is not free i even tried switching to netbeans since they have a built in profilerif anyone has had success with particular profilers even if it was tptp i would like to hear about it any recommendations would be greatly appreciatednote i know this has been asked before but i have not found anything recent that really gives a good answer,['java'] +59012,why should i not use autodual up to now i have always decorated my net classes that i want to use from vb6 with the autodual attribute the point was to gain intellisense on net objects in the vb6 environment however the other day i googled autodual and the first answer is do not use autoduali have looked for coherent explanation of why i should not use it but could not find itcan someone here explain it,['c#'] +59020,byte to image android my issue is as follows i have stored a few pictures into the sqlite database using the blob format which seems to work ok now i want to get my pictures out of the db and put then back into images to complicate the matter their format is variable png jpg maybe something else im not sureis there a way of doing so in androidthank you,['android'] +59030,jquery change name attribute i have got a jquery function that attempts to change the id name and class of an element the id and class change seems to work but for some curious reason trying to change the name of the element never worksdocumentreadyfunction table selectlivechange function var id thisattrid if thisattrclassname selected var rowindex thisclosesttrprevalength getjsoncategorygetsubcategories thisval function data if datalength 0 idattrclassname selected idattrid sel rowindex idattrname sel rowindex this never works var position tableget0 var tr positioninsertrowrowindex 1 var td1 trinsertcell1 var td2 trinsertcell1 td1appendchilddocumentcreatetextnodesubcategory var sel documentcreateelementselect selname parent id selid parent id selsetattributeclass unselected td2appendchildsel eachdata function getsubcatergories category parent idappendoptionoption attrvalue categorycategory id textcategoryname,['jquery'] +59036,htmlcss set div to height of sibling i have 2 divs contained in a third one of the contained divs is floated left the other floated right i would like the 2 sibling divs to always be at the same height but am having a problem with this so far i am only viewing the page in firefox and figured i would worry about any crossbrowser issues after i get it working in at least one browserhere is the markupdiv idmaincontainer classborder clearfix div idleftdiv classborder div div idrightdiv classborder divdivhere is the cssmaincontainer position relative minheight 500px leftdiv position relative float left width 700px minheight inherit rightdiv position relative float right width 248px minheight inherit height inherit clearfixafter content thisplay block height 0 clear both visibility hidden clearfix thisplay inlineblock height 1 clear both clearfix thisplay block clear both border border solid 1px 0 if the content in the leftdiv is longer than 500px the rightdiv does not expand to match in an example i tried firefox said the computed style height of the maincontainer was 804px the computed style height of the leftdiv was 800px and the computed style height of the rightdiv was 5862px as it had expanded to fit it is own contenti understand i might be going about this the wrong way and if this is a duplicate questions then i apologize but i was not quite sure what to search under,"['html', 'css']" +59048,unit testing aspnet mvc 2 routes with areas bails out on arearegistrationregisterallareas i am unit testing my routes in aspnet mvc 2 i am using mstest and i am using areas as well testclasspublic class routeregistrartests classinitialize public static void classinitializetestcontext testcontext routetableroutesclear routetableroutesignorerouteresourceaxdpathinfo routetableroutesignoreroutefavicon new favicon faviconico arearegistrationregisterallareas routesmaproute default controlleractionid new controller home action index id urlparameteroptional testmethod public void routemaps verifymappings match routeshouldmaptohomecontrollern nindex when it executes arearegistrationregisterallareas however it throws this exceptionsysteminvalidoperationexception systeminvalidoperationexception this method cannot be called during the applications prestart initialization stageso i reckon i cannot call it from my class initializer but when can i call it i obviously do not have an application start in my test,['.net'] +59049,any way to change the color of a radio button i am working on an android form with a radio group containing a set of radio buttons from what i can tell there is no way to set the color a radio button highlights when you select it it seems to always default to some bright green color is this something that is editable or nothanks,['android'] +59052,call parent constructor in ruby how can i call parents constructor module c attr accessor c cc def initialization c cc c cc c cc end endclass b attr accessor b bb def initialization b bb b bb b bb end endclass a b include c attr accessor a aa def initialization a b c aa bb cc call binitialization call cinitialization a aa a aa endendthanks,['ruby'] +59053,convert file system website to iis website we recently migrated from vs 2008 to vs 2010 the migration went fine except for our web project before in vs 2008 the site showed up as httplocalhostwebsite now it appears as cwebsite it appears that when we did the migration vs started to treat it as a file system websitei have tried removing the existing site and readding it as an existing website but it still thisplays it as cwebsite is there any way to convert it back to show it as a httplocalhostwebsite and run through iis as opposed to the default aspnet development server,['asp.net'] +59072,hashing a python function to regenerate output when the function is modified i have a python function that has a deterministic result it takes a long time to run and generates a large outputdef time consuming function lots of computing time to come up with the result return the resulti modify time consuming function from time to time but i would like to avoid having it run again while it is unchanged time consuming function only depends on functions that are immutable for the purposes considered here ie it might have functions from python libraries but not from other pieces of my code that i would change the solution that suggests itself to me is to cache the output and also cache some hash of the function if the hash changes the function will have been modified and we have to regenerate the outputis this possible or ridiculousupdated based on the answers it looks like what i want to do is to memoize time consuming function except instead of or in addition to arguments passed into an invariant function i want to account for a function that itself will change,['python'] +59077,convert a time to a formatted string in c timetostring00 shows up as a decimal 15 for instead of 130 how can i get it to thisplay in a time formatprivate void xtripseventymilesradiobutton checkedchangedobject sender eventargs e calculation for the estimated time label time miles seventymph thisxtripestimatelabelvisible true thisxtripestimatelabeltext driving at this speed the estimated travel time in hours is timetostring00 hrs,['c#'] +59082,jquery how to determine if slide event is up or down i have the following codeabtnslidetogglefunction divtoslideslideupfast function divtoslideslidedownfast later in my code i want to find out if divtoslide is in either the up or down position how do i do that,"['javascript', 'jquery']" +59092,css selector for first element with class i have a bunch of elements with a class name redp classredpdiv classreddivi cannot seem to select the first element with the classred using the following css ruleredfirstchild border5px solid redwhat is wrong in this selector and how do i correct itupdatethanks to the comments i figured out that the element has to be the first child of its parent to get selected which is not the case that i have i have the following structurediv classhome spanblahspan p classredfirstp p classredsecondp p classredthirdp p classredfourthpdivand this rule fails as mentioned in the commentshome redfirstchild border1px solid redhow can i target the first child with class red,['css'] +59095,sqlite upsert on duplicate key update mysql has something like thisinsert into visits ip hitsvalues 127001 1on duplicate key update hits hits 1as far as i am know this feature does not exist in sqlite what i want to know is if there is any way to archive the same effect without having to execute two queries also if this is not possible what do you preferselect insert or update orupdate insert if update fails,"['sql', 'mysql']" +59097,should include and using statements be repeated in both header and implementation files c i am fairly new to c but my understanding is that a include statement will essentially just dump the contents of the included file into the location of that statement this means that if i have a number of include and using statements in my header file my implementation file can just include the header file and the compiler would not mind if i do not repeat the other statementswhat about people thoughmy main concern is that if i do not repeat the include using and also typedef now that i think of it statements it takes that information away from the file in which it is used which could lead to confusioni am just working on small projects at the moment where it would not really cause any issues but i can imagine that in larger projects with more people working on them it could become a significant issuean example followsupdate my function prototypes for unit have string ostream and stringset among their return types and parameters i am not including anything in my header file that is used only in the implementation fileunithinclude stringinclude ostreaminclude stringsethusing stdstringusing stdostreamclass unit public public members with string ostream and stringset in their return valuesparameter listsprivate private members unrelated sidequestion should private members even be included in the header file unitcppinclude uniththe following are all redundant from a compiler perspectiveinclude stringinclude ostreaminclude stringsethusing stdstringusing stdostreamimplementation goes here,['c++'] +59102,c memory allocation and deallocation patterns since c uses garbage collection when is it necessary to use thispose to free the memoryi realize there are a few situations so i will try to list the ones i can think ofif i close a form that contains gui type object are those objects dereferenced and therefore will be collectedif i create a local object using new should i thispose of it before the method exits or just let the gc take care of it what is good practice in this caseare there any times in which forcing a gc is understandableare events collected by the gc when it is object is collected,"['c#', '.net']" +59123,why is the synchronized keyword in java called synchronized instead of the more precise mutexed i have heard that choosing to use the word synchronized to describe mutexed statements is simply a mistake edit mistake was a bad choice of words here please see edit in java but i am wondering if there is actually a reason behind the choiceeditprodded by safyans comments i would like to add that synchronization is a general term for establishing timing relationships between threads it can include mutual exclusion and things like rate control eg two threads doing something at the same rate it appears unnecessarily ambiguous to use synchronized to mean mutual exclusion instead of a more specific keyword like mutexed,['java'] +59125,free static checker for c99 code i am looking for a free static checker for c99 code including gcc extensions with the ability to explicitly say these preprocessor macros are always defined i need that last part because i am compiling embedded code for a single target processor the compiler microchips c32 gcc based sets a macro based on the selected processor which is then used in the pic32 header files to select a processorspecific header file to include cppcheck therefore fails because it detects the 30 different ifdefs used to select one of the many possible pic32 processors tries to analyse all possible combinations of these plus all other defines and failsfor example if splint could process c99 code i would usesplint d pic32 feature set 460 d 32mx460f512l d language c ipathtomyincludes sourcecan additional problem is that the pic32 toolchain compiler is called pic32gcc and not just gcc although i have not yet gotten to the point of needing to account for thisupdate 1 one thing i am interested in but is orthogonal to this question is eclipse integration it would be nice not to have to write a makefile for 30 compilation units i asked about this on the eclipse forums although the thiscussion there is more about integration into eclipse nothing groundbreakingupdate 2 just tried scanbuild from clang usingscanbuild useccusrlocalbinpic32gcc make b k allalso without the usecc flag but all i got was the typical build output an example of which isbuilding file srcmoremathcinvoking pic c32 c compilerpic32gcc d debug iusrlocalpic32libsinclude o0 wall c fmessagelength0 stdgnu99 werrorimplicitfunctiondeclaration mmd mp mfsrcmoremathd mtsrcmoremathd mprocessor32mx460f512l d debug g osrcmorematho srcmoremathcfinished building srcmoremathcand at the endbuilding target mybinaryelfinvoking pic c32 c linkerpic32gcc wlmapmybinarymap mprocessor32mx460f512l defsym mplab debug1 omybinaryelf all of my o files herefinished building target mybinaryelfscanbuild removing directory tmpscanbuild201006211 because it contains no reportsso either my code is perfect according to scanbuild or it is not doing anything i am not sure what a good test might be to see if it is working,['c'] +59126,upload photo to album with facebooks graph api i am trying to familiarize myself with facebooks new graph api and so far i can fetch and write some data pretty easilysomething i am struggling to find decent documentation on is uploading images to an albumaccording to you need to supply the message argument but i am not quite sure how to construct it older resources i have read are photo uploadsif someone has more information or could help me tackle uploading photos to an album using facebook graph api please reply,['php'] +59147,why does heroku log using the server time rather than the rails time zone update ok i did not formulate a good q to be answered i still struggle with heroku being on 0700 utc and i at 0200 utcq how do i get the log written in the correct timezone the 9 hours difference heroku us west norway is thistracting to work with i get this in my productionlog using heroku logsprocessing productioncontrollercreate to xml for 81265135 at 20100428 230012 posthow do i get it to write 20100429 080012 0200 gmt note that i am running at heroku and cannot set the server time myself as one could do at your amazon ec2 servers below is my previous question i will leave it be as it holds some interesting information about time and zoneswhy does timenow yield the server local time when i have set the another time zone in my environmentrbconfigtime zone copenhageni have put this in a viewp timezone timezone pp timenow timenow pp timenowutc timenowutc pp timezonenow timezonenow pp timezonetoday timezonetoday prendering this result on my app at heroku timezone gmt0100 copenhagentimenow mon apr 26 082821 0700 2010timenowutc mon apr 26 152821 utc 2010timezonenow 20100426 172821 0200timezonetoday 20100426timezonenow yields the correct result do i have to switch from timenow to timezonenow everywhere seems cumbersome i truly do not care what the local time of the server is it is giving me loads of trouble due to extensive use of timenow am i misunderstanding anything fundamental here,['ruby-on-rails'] +59155,waitforsingleobject and waitformultipleobjects equivalent in linux i am migrating an applciation from windows to linux i am facing problem with respect to waitforsingleobject and waitformultipleobjects interfacesin my application i spawn multiple threads where all threads wait for events from parent process or periodically run for every t secondsi have checked pthread cond timedwait but we have to specify absolute time for this how can i implement this in unix,['c'] +59159,iphone uitextfield only integer i have a uitextfield in my ib and i want to check out if the user entered only numbers no charand get the integer valuei get the integer value of the uitextfield like that int integer myuitexrtfieldtext intvaluewhen i put a character it return me 0 and i do not know how to detect that it is not only numbershow can i do,"['iphone', 'objective-c']" +59189,how to write clean code in c language and improve quality of code how i can improve our code quality and write clean code if i write a unclean ugly code then how i can migrate as a good code beautiful and clean,['c#'] +59199,how to create small spaces in html there is em dash and en dash is there an en equivalent to nbsp is there an en equivalent to pure ascii 32i want a better way to write this123span claspanennbspspan456span claspanennbspspan789or this123span claspanen span456span claspanen span789,['html'] +59208,jquery change method on input typefile i am trying to embrace jquery 100 with it is simple and elegant api but i have run into an inconsistency between the api and straightup html that i cannot quite figure outi have an ajax file uploader script which functions correctly that i want to run each time the file input value changes heres my working codeinput typefile size45 nameimagefile idimagefile onchangeuploadfilewhen i convert the onchange event to a jquery implementationimagefilechangefunction uploadfile the result is not the same with the onchange attribute the uploadfile function is called anytime the value is changed as is expected but with the jquery api change event handler the event only fires the first time a value is change any value change after that is ignored this seems wrong to me but surely this cannot be an oversight by jquery righthas anyone else encountered the same issue and do you have a workaround or solution to the problem other than what i have described above,['jquery'] +59214,how to add two javalangnumbers i have two numbers egnumber a 2number b 3following is an errornumber c a bwhy arithmetic operations are not supported on numbers anyway how would i add these two numbers in java of course i am getting them from somewhere and i do not know if they are integer or float etc,['java'] +59217,how to create touch interactive charts for android i need charts for my application where the user use gesture to redraw the charts in android could you suggest any charting apitool or software which supports,['android'] +59225,jquery ajax not working in ie8 but it works on firefox chrome i have the following ajax call which works perfectly in firefox and chrome but not iefunction getajaxdates startdate numberofnights opts var month startdategetmonth 1 var day startdategetdate var year startdategetfullyear var d new date var randnum mathfloormathrandom10 ajax type get datatype json url availabilityajaxbookingsrandrandnum cache false data monthmonthdaydayyearyearnightsnumberofnights contenttype applicationjson charsetutf8 success functiondata consolelogdata data insertcelldatadata opts startdate errorfunctionxhr status errorthrown consolelogerror errorthrown consolelogstatus status consolelogstatus text xhrstatustext i know for a fact that all the variables are passing the right content and ajax is indeed passing all the paramatervalues this is what i get on errorlog error undefinedlog status parsererrorlog status text oki am aware of the cache issue on ie and implemented a random paramater to clear it uphere is the json i get back i am able to see it using charles availability inventory id5 booking id21 start date05012010 number nights4 textdefrancisco martin 50 active typebooking finally these are the headers that are sent back from the backendheadercontenttype applicationjson charsetutf8headercachecontrol nocacheheaderexpires 0headeraccesscontrolmaxage 3628800headeraccesscontrolallowmethods get post put deleteany ideas,"['javascript', 'jquery']" +59247,ajax datatype what is the difference between contenttype applicationjson charsetutf8datatype jsonvscontenttype applicationjsondatatype text,['jquery'] +59253,validating url with jquery without the validateplugin i need to validate a url in variable with jquery but cannot use validateplugin is there a simple way to do this,['jquery'] +59266,capturing key event for backspace i am having difficulty capturing the backspace key as a keyboard event in javascriptjquery in firefox safari opera chrome and on the iphoneipad i capture a keyup event on a text input box like thisid inputkeyupfunctionevent thatgethintsthisvaltrim event fieldnamethis event captures user keystrokes then sends them to a function to issue an ajax lookup call my problem comes when a user wishes to backspace over a character heshe already typed in all the browsers to which i have access except for my droid phone when i press the backspace key this keyup event captures the value returned by thisvaltrim and sends it on to process in function gethints on the droid however neither this keyup nor an equivalent keydown event fires until the user backspaces over every character in this so for example if i type cu then backspace over the u leaving only c in the input field in all browsers except droid the keyup event will fire and call function gethintsc event fieldname on the droid the keyup event never fireswhat am i missing howwhy does this backspace key on either the soft keyboard or the hard keyboard on my droid not function as expected how do i work around this,"['javascript', 'jquery', 'android']" +59279,opengl texture randomly not shown i have got a very very strange problem in my c opengl application i simply load a texture and apply it to a quadricglgentextures1 texglbindtexturegl texture 2d texglteximage2dgl texture 2d 0 3 width height 0 gl rgb gl unsigned byte imagegltexparameterigl texture 2d gl texture min filter gl nearestgltexparameterigl texture 2d gl texture mag filter gl nearestthenglenablegl texture 2dglbindtexturegl texture 2d texgluquadricdrawstylequadglu fillgluquadrictexturequadgl trueglucylinderquad102201glthisablegl texture 2dnow it works perfectly 9 times out of ten but sometimes the texture is not shown the quadric stays whitethe image is correctly loaded so the problem should be with opengl i have tried with several different images too always gl no errorany idea it is driving me crazy,['c++'] +59283,why does pythons import require fromlist in python if you want to programmatically import a module you can domodule import module nameif you want to import a submodule you would think it would be a simple matter ofmodule import module namesubmoduleof course this does not work you just get module name again you have to domodule import module namesubmodule fromlistblahwhy the actual value of fromlist do not seem to matter at all as long as it is nonempty what is the point of requiring an argument then ignoring its valuesmost stuff in python seems to be done for good reason but for the life of me i cannot come up with any reasonable explanation for this behavior to exist,['python'] +59325,slicing arrays in numpyscipy i have an array likea array123345456whats the most efficient way to slice out a 1x2 array out of this that has only the first two columns of aiearray234556 in this casethanks,['python'] +59341,do hibernate table classes need to be serializable i have inherited a websphere portal project that uses hibernate 30 to connect to a sql server databasethere are about 130 hibernate table classes in this project they all implement serializable none of them declare a serialversionuid field so the eclipse ide shows a warning for all of these classesis there any actual need for these classes to implement serializableif so is there any tool to add a generated serialversionuid field to a large number of classes at once just to make the warnings go away,['java'] +59348,creating a transparent bitmap with gdi i want to implement a layering system in my application and was thinking of creating a bunch of transparent bitmaps adding content to them then blitting them on top of each other how can this be done without setting each pixel to 0 i am using pure win32 not mfc thanks,"['c++', 'c']" +59354,c xor on two byte variables will not compile without a cast why does the following raise a compile time error cannot implicitly convert type int to byte byte a 25 byte b 60 byte c a bthis would make sense if i were using an arithmentic operator because the result of a b could be larger than can be stored in a single bytehowever applying this to the xor operator is pointless xor here it a bitwise operation that can never overflow a byteusing a cast around both operands worksbyte c bytea b,['c#'] +59358,what is use of exp and what is the difference between lib and dll during compilation and linking what is use of exp what is the difference between lib and dll i know that lib will be used while linking and dll will be used when running the program but what exactly is the difference between lib and dlldoes lib file not contain the code for the functions coming from dll fileswhat is the need for using two separate filesplease clarify thanks in advance,['c'] +59369,mysql finding time overlaps i have 2 tables in the database with the following attributesbookingbooking idbooking startbooking endresource bookedbooking idresource idthe second table is an associative entity between booking and resource ie 1 booking can contain many resources attributes booking start and booking end are timestamps with date and time in itmay i know how i might be able to find out for each resource id resource booked if the datetime overlaps or clashes with other bookings of similar resource idi was doodling the answer on paper pictorially to see if it might help me visualize how i could solve this and i got thisjoining the 2 tables booking booked resource into one table with the 4 attributes neededfollow the answer suggested here i did step 1 but step 2 is leaving me baffledi would really appreciate any help on this thanks editi was reading mr renshaws answer and tried doing one on my own to see if i understood and i got the conceptselect a from select bcreation date bbooking id r bresource id bbooking start bbooking end from booking b inner join resource booked r b on bbooking id r bbooking id as a select bbooking id r bresource id bbooking start bbooking end from booking b inner join resource booked r b on bbooking id r bbooking id aswhere aresource id bresource id and abooking id bbooking id and abooking start between bbooking start and bbooking end and acreation date bcreation datei think i was trying to create 2 identical tables and join them up with resource id find records with similar resource id but different booking id and see if the booking start datetime of one booking id is between the booking start and booking end of another booking idit is really messy and i was not even sure if my query was asking what i had in mind but by some miracle i got the same answer as mr renshaw,"['sql', 'mysql']" +59370,how can i make a noisy background image using php i am looking to make an image that is just noise maybe something like thisideally i would like to be able to change the colour as well any ideas on how to generate this,['php'] +59373,destruction of a variable or array in c i have a variable or array which i no longer needed how to destroy themsorry for noobquestion,['c#'] +59374,log4j vs systemoutprintln logger advantages i am using log4j for the first time in a project a fellow programmer told me that using systemoutprintln is considered a bad style and that log4j is something like standard for logging matters nowadayswe do lots of junit testing systemout stuff turns out to be harder to testtherefore i began utilizing log4j for a console controller class that is just handling commandline parameters log4j logger config orgapachelog4jbasicconfiguratorconfigurelogger logger loggerfactorygetloggerconsoleclasscategory cat categorygetroot seems to work loggerdebugstringproduces1 main debug projectprototypecontrollerconsole stringi got two questions regarding thisfrom my basic understanding using this logger should provide me comfortable options to write a logfile with timestamps instead of spamming the console if debug mode is enabled at the loggerwhy is systemoutprintln harder to test i searched stackoverflow and found a testing recipe so i wonder what kind of advantage i really get by using log4j,['java'] +59376,jquery unbindhover does not work my unbind does not workimghoverablehoverchangeimage changebacka imghoverableunbindhoverthe html could be like thisimg classhoverable srcsomethingjpga hrefimg classhoverable srcsomethingjpgawhen i hover over the second html changeimage is still firedi am not sure if i am using it correctly can anyone please advise,['jquery'] +59378,common elements between two lists not using sets in python i want count the same elements of two lists lists can have duplicate elements so i cannot convert this to sets and use operatora2211b1133seta setb worka b do not work it is possible to do it withoud set and dictonary,['python'] +59380,how do you use java 16 annotation processing to perform compile time weaving i have created an annotation applied it to a dto and written a java 16 style annotationprocessor i can see how to have the annotationprocessor write a new source file which is not what i want to do i cannot see or find out how to have it modify the existing class ideally just modify the byte code the modification is actually fairly trivial all i want the processor to do is to insert a new getter and setter where the name comes from the value of the annotation being processedmy annotation processor looks like thissupportedsourceversionsourceversionrelease 6supportedannotationtypes comknsalogannotationaggregatefield public class salogdtoannotationprocessor extends abstractprocessor override public boolean processfinal set extends typeelement annotations final roundenvironment roundenv do some stuff,['java'] +59384,what is most seo optimized image html code for so far i was doing it like thisa href titlekeywordimg srcimagepng altkeyword anow i thiscovered that images can have title attribute tooa href titlekeywordimg srcimagepng altkeyword titlekeywordais there any other optimization i could pull off to boost image links value,['html'] +59387,where does the mysql database files actually reside im just curious as i am beginning to learn php and mysql as to where the database and other files of mysql reside on the hard drive i have installed wamp on a windows xp sp2 platform,['mysql'] +59395,how are iterators and pointers related code with iterators looks pretty much like code with pointers iterators are of some obscure type like stdvectorintiterator for examplewhat i do not get is how iterators and pointer are related to each other is an iterator a wrapper around a pointer with overloaded operations to advance to adjacent elements or is it something else,['c++'] +59400,hashset versus dictionary wrt searching time to find if an item exists hashsett t new hashsett add 10 million itemsdictionaryk v t new dictionaryk v add 10 million itemswhose contains method will return quickerjust to clarify my requirement is i have 10 million objects well strings really that i need to check if they exist in the data structure i will never iterate,['.net'] +59402,badimageformatexception when loading 32 bit dll target is x86 i have a dll freetype which is certainly 32bit header image file machine i386i want to use it from c code using dllimporttarget of my application is x86 intptrsize is 4 process is 32bitbut i get badimageformatexception exception from hresult 0x80070b what can be wrong of course i use 64bit windows 7,['c#'] +59406,what does throw by itself do possible duplicatedifference between throw and throw new exception what would be the point of just havingcatch exception throwwhat does this do,"['c#', '.net']" +59413,is it possible to do have capistrano do a checkout over a reverse ssh tunnel i am developing an application that resides on a public host but whose source i must keep in a git repository behind a corporate firewall i am getting very tired of the slowness of deploying via scp copying the whole repository and shipping it over ssh on each deploy and would like to have the remote host simply do a git pull to update the problem is that the firewall prohibits incoming ssh connectionswould it be possible for me to set up an ssh tunnel from my computer to the deployment computer and use my repository as the source for the git pull after all git is thistributed so my copy is just as valid a repository as the central one if this is possible what would the tunnel command and the capistrano configuration bei think the tunnel will look something likessh r somethingdeployservercomsomething,['ruby-on-rails'] +59416,how to change the color of an indefinite progressbar i have a progressbar with the following style styleandroidattrandroidprogressbarstylesmall sadly the bar is nearly white and in my case thisplayed on a white backgroundthe progressbar is nearly invisible because of thathow can i change the color of the progressbar a darker grey would be great,['android'] +59423,why do i get this unexpected result using atoi in c i do not understand the results of the following c codemain char s a advancestringsvoid advancestringp3 int val atoip printfthe atoi val is dnvalhere the atoi value is shown as 0 but i could not figure out the exact reasonas per my understanding it should be the summation of decimal equivalent of each values in the array please correct me if i am wrong,['c'] +59426,how to get the parameter names of an objects constructors reflection say i somehow got an object reference from an other classobject myobj anobjectnow i can get the class of this objectclass objclass myobjgetclassnow i can get all constructors of this classconstructor constructors objclassgetconstructorsnow i can loop every constructorif constructorslength 0 for int i 0 i constructorslength i systemoutprintlnconstructorsi this is already giving me a good summary of the constructor for example a constructor public teststring paramname is shown as public testjavalangstringinstead of giving me the class type however i want to get the name of the parameter in this case paramname how would i do that i tried the following without successif constructorslength 0 for int icon 0 icon constructorslength icon class params constructorsicongetparametertypes if paramslength 0 for int ipar 0 ipar paramslength ipar field fields paramsipargetdeclaredfields for int ifields 0 ifields fieldslength ifields string fieldname fieldsigetname systemoutprintlnfieldname unfortunately this is not giving me the expected result could anyone tell me how i should do this or what i am doing wrong thanks,['java'] +59432,linq to sql dynamicinvokesystemobject has no supported translation to sql i have a class usersusers has a userid propertyi have a method that looks something like thisstatic iqueryableuser filterbyidthis iqueryableuser p funcint bool sel return pwherem selmuseridinevitably when i call the functionvar users usersfilterbyidm m 10i get the following exceptionmethod systemobject dynamicinvokesystemobject has no supported translation to sqlis there any solution to this problem how far down the rabbit hole of expressionkillmeandmyfamily might i have to goto clarify why i am doing this i am using t4 templates to autogenerate a simple repository and a system of pipes within the pipes instead of writingnew userpipewherem muserid 10 musernamecontainsoo mlastname weei would like to generate something likenew userpipe useridm m 10 usernamem mcontainsoo lastnamewee,['c#'] +59439,membershipvalidateuser always returns false after upgrade to vs 2010 net 40 not sure whether this pertains to vs 2010 or to the upgraded framework but we are using the oracle membership provider to authenticate users prior to the upgrade everything worked fine but now membershipvalidateuseruser password returns false despite valid credentials there is no exception thrown so it is hard to determine what the problem might be the website administration tool in vs 2010 is still able to manage users and roles more or less so i have no reason to question connectivity what might the problem be,"['c#', 'asp.net']" +59443,how to index bigdecimal values in lucene 301 i have some bigdecimal values which should be indexed for searching lucene has numericfield but it has setters only for long double float and int i could store it as a string but then i would not benefit from numericrangequeryhow you have stored your bigdecimals any best practices to share,['java'] +59456,how can i use spinner setonitemlongclicklistener i am trying to make the spinner behave different way when the user clicked on an item for a long time i have spinner with some project and i want two thingswhen the user simple click on an item i want to normal select itwhen the user have long clicked on an item i want to show dialog with options like edit item delete itemthe first step works well ofcourse but when i am trying to do the second task i can not make spinner to generate longclicked eventhere is my code thisprojectspinner spinner thisfindviewbyidridspinnerprojects thisprojectspinnersetlongclickabletrue thisprojectspinnersetonitemlongclicklistenernew adapterviewonitemlongclicklistener public boolean onitemlongclickadapterview arg0 view arg1 int arg2 long arg3 toastmaketext androidtimetrackermainactivitythis long click toastlength shortshow this toast does not show up return false,['android'] +59477,net4 inprocess sidebyside execution explained overview i am interested in learning more about the net4 inprocess sidebyside execution of assemblies and need additional information to help me demystify itmotivation the application in question is built against net2 and uses two thirdparty libraries that also work against net2 the application is deployed via file copy to client machines in a virtual environment that includes net2 not my architecture please bear with megoal to see if it is possible to rebuild the application assemblies or a subset against net4 and ship the application as before without changing the thirdparty libraries and including the net4 client profile as described here in the deploymentsteps taken the following articles were read but did not quite provide me enough informationinprocess sidebyside execution browsed this article and scenario two is the closest it comes to describing something that resembles my situation but does not really cover it with any depthaspnet sidebyside execution overview this article covers a web application but i am dealing with a client winforms applicationclr team blog inprocess sidebyside this is useful to explain how plugins to host processes function under net4 but i do not know if this applies to the thirdparty librariesfurther steps i am also unclear on how to proceed upgrading a single net2 assembly to net4 with the executable remaining in net2 ie how to configure the solutionproject files if any special code needs to be included etc,"['c#', '.net']" +59480,using sizeof with a dynamically allocated array gcc 441 c89i have the following code snippetinclude stdlibhinclude stdioh char buffer malloc10240 check for memory error ifbuffer fprintfstderr memory errorn return 1 printfsizeofbuffer d n sizeofbufferhowever the sizeofbuffer always prints 4 i know that a char is only 4 bytes however i have allocated the memory for 10kb so should not the size be 10240 i am wondering am i thinking right heremany thanks for any suggestions,['c'] +59498,in java when i call outputstreamclose do i always need to call outputstreamflush before if i just call close in a output stream the output is guaranteed or need i call flush always,['java'] +59513,sending a tuple object over wcf is the systemtuple class supported by wcfs data contract serializer ie can i pass tuple objects to wcf calls andor receive them as part or all of the result i found this page but not the clear definitive you can send and receive tuples with wcf answer i was hoping fori am guessing that you can as long as all of the types within the tuple itself are supported by the data contract serializer can anyone provide me with a more definitive answer thanks,"['c#', '.net']" +59516,32 and 64 bit assemblies in one windows installer i have an application written in c which depends on sqlite managed provider the sqlite provider is platform dependent there are two dlls for 32 and 64 bit applications with the same name the application loads the desired one at runtime based on osthe problem is that while creating an installer i cannot add 64 bit mode dll to the setup project as i am getting the following error file targeting is not compatible with the projects target platform i would use other installer but i have a custom action which must be invoked during the setupso i wanted to know if there is an installer which will let me add 32 and 64 bit dll to it and execute custom action written in cone possible solution is to have two installers but i would like to avoid it if possibleany suggestions,['.net'] +59517,is learning winforms worthwhile is it outdated i just completed two winform applications as part of an intensive course just wondering about the technology overall should i move onto something new or is winforms still viable for the future,"['c#', '.net']" +59530,is there a logging facade for the net world i am somewhat new to the net stack and i was wondering if there is an equivalent to slf4j for the net platform for me logging to a facade and being able to swap out logging implementations as needed just makes sense furthermore the wrapper apis available in slf4j have saved me many times when i needed to use a thirdparty library that was coded against a single logging framework that i was not usingis there a project out there that acts as a facade between loggers like log4net nlog and enterprise library are there wrappers that allow me to shortcut calls to those libraries and direct them to another library should i start out an open source project to do this myself is this question a duplicate because i do not know the right way to ask conversely is the common way to do this using aspect orient programming,"['c#', '.net']" +59549,pointeraddress type casting i have the following variableschar pint l65why do the following casts failint plandpchar l,['c'] +59560,how do i make links in a textview clickable i have the following textview defined textview androidlayout widthwrap content androidlayout heightwrap content androidtextstringtxtcredits androidautolinkweb androidididinfotxtcredits androidlayout centerinparenttrue androidlinksclickabletruetextviewwhere stringtxtcredits is a string resource that contains a hrefsome sitelink textaandroid is highlighting the links in the textview but they do not respond to clicks can someone tell me what i am doing wrong do i have to set an onclicklistener for the textview in my activity for something as simple as thislooks like it has to do with the way i define my string resourcethis does not workstring nametxtcreditsa hrefgoogleastringbut this doesstring nametxtcreditswgooglecomstringwhich is a bummer because i would much rather show a text link than show the full url,['android'] +59574,how to hide nested form from jquery under ie8 an html segment with a div containing a form containing a tabledoctype htmlhtml xmlns langen head style typetextcss contentpositionrelative table bordercolor9borderstylesolid stylescript typetextjavascript srcscriptheadbody button onclickjavascriptcontentpaneltoggletogglebutton div idcontent div classcontentpanel form action methodpost select optiona option select table trtdabcdeftdtr table form div divbodyhtmlthe toggle button should hide the form and its nested table but does not do so under ie8 version 80601 the form content gets hidden but the table border continues to show and retains its size it is related to standards mode it thisappears in quirksmodedoes anybody have a workaround for thisthis example page is reduced about as far as i can reduce it if i remove the select or either of the divs the problem thisappears the the select must be present and the table needs to be nested in the form as it will contain form elementsthe page itself is ati posted this problem earlier with an overly simplified example which was not reproducible thank you if you looked at it then,['jquery'] +59583,what are the thisadvantages of using templates some of the thisadvantages would be its syntax is complexcompiler generates extra code,['c++'] +59611,lexical cast int to string is it safe to ignore exception of boostlexical cast when converting int to stdstring,['c++'] +59621,write text onto image in java is there a java library to write text to images same as phps gd library,['java'] +59631,listbox selecteditems binding i want to bind listbox selecteditems to array but net throws exception at runtimedsetbindinglistboxselecteditemsproperty new binding source somearray where d is some listbox from xamlexception selected item cannot be boundwhy,['c#'] +59637,wpf global styles problem with net4 i have just changed my wpf application from net35 to net4 doing this caused all my global styles to stop working only the styles explicitly set using a key did work i have done some research and figured out what causes this and reproduced it in a simple app i have a simple wpf app containing only a button with text no style or anything else i define a style for all buttons in the resourcedictionary of appxaml style targettypextype button setter propertybackground valueredsetterstylemy button is now red all fine i now move this to a separate resourcedictionary in a separate project this is where i want to hold all my shared styles the button is still red and my reference from appxaml to sharedstylesxaml looks like this applicationresources resourcedictionary resourcedictionarymergeddictionaries resourcedictionary sourcestylelibcomponentsharedstylesxaml resourcedictionarymergeddictionaries resourcedictionaryapplicationresourcesnow i want sharedstylesxaml of stylelib to hold all specific style definitions so i create a new file in the same project called buttonstylesxaml and i add the resource there actually i add another style too with a key to be used explicitly technically i added this later so this does not have anything to do with the problem that occurs resourcedictionary xmlns xmlnsx style targettypextype button setter propertybackground valueredsetter style style xkeyexplicit targettypextype button setter propertybackground valuebluesetter style resourcedictionarybuttonstylesxaml is referenced from sharedstylesxaml resourcedictionary xmlns xmlnsx resourcedictionarymergeddictionaries resourcedictionary sourcestylelibcomponentbuttonstylesxaml resourcedictionarymergeddictionaries resourcedictionarynow my button control is not styled any more actually it is still shown as styled in the previewwindow in vs2010 but when i run the application they are not styled if i explicitly reference the style with key explicit they get this style so the file is successfully included another funny thing is that if i now add another style in sharedstylexaml eg a global style for stackpanel which was what i tried then the global style inside buttonstylexaml magically starts working my question now is if i am doing something wrong or if this sounds like a bug in net4 sounds like a bug to me this did work just fine in net35,['.net'] +59639,generate number sequences with linq i try to write a linq statement which returns me all possible combinations of numbers i need this for a test and i was inspired by this article of eric lippert the methods prototype i call looks likeienumerablecollectionint allsequences int start int end int size the rules areall returned collections have a length of size number values within a collection have to increaseevery number between start and end should be usedso calling the allsequences 1 5 3 should result in 10 collections each of size 31 2 31 2 41 2 51 3 41 3 51 4 52 3 4 2 3 52 4 5 3 4 5now somehow i would really like to see a pure linq solution i am able to write a non linq solution on my own so please put no effort into a solution without linqmy tries so far ended at a point where i have to join a number with the result of a recursive call of my method something likereturn from i in enumerablerange start end size 1 select buildcollectioni allsequences i end size 1but i cannot manage it to implement buildcollection on a linq base or even skip this method call can you help me here,['c#'] +59649,chrome back button page refresh aspnet i have an aspnet application cwhen a user is on a specific page they click a link on this page that takes them to a child page thisplaying the product detailsif the user clicks the browser back button i need the parent page to be refreshed to its initial state ie all text boxes that had data typed need to be blank any hidden fields reset etc basically i need a ctrlf5 when a user clicks backthisabling the back button is not an optioni need this only on certain pagesin ie and firefox i can get this working without an issue but with chrome the textboxes still contain their values as do the hidden fields if i hit ctrlf5 in chrome the page is correctly reset to its initial statethis is the code i have tried outputcache locationnone varybyparamnone and this responsebuffer true responsecachesetcacheabilityhttpcacheabilitynocache responsecachesetallowresponseinbrowserhistoryfalse responsecachesetnostoreand this responsecachesetexpiresdatetimeutcnowadays1 responsecachesetvaliduntilexpiresfalse responsecachesetrevalidationhttpcacherevalidationallcaches responsecachesetcacheabilityhttpcacheabilitynocache responsecachesetnostorei have also tried a variety of these in different combination but with no successthanks,['asp.net'] +59652,how to set up default schema name in jpa configuration i found that in hibernate config file we could set up parameter hibernatedefault schemahibernateconfiguration sessionfactory property namehibernatedefault schemamyschemaproperty sessionfactoryhibernateconfigurationnow i am using jpa and i want to do the same otherwise i have to add parameter schema to each table annotation likeentitytable name projectcategory schema schemanamepublic class category implements serializable as i understand this parameter should be somewhere in this part of configurationbean iddomainentitymanagerfactory classorgspringframeworkormjpalocalcontainerentitymanagerfactorybean property namepersistenceunitname valuejiramanager property namedatasource refdomaindatasource property namejpavendoradapter bean classorgspringframeworkormjpavendorhibernatejpavendoradapter property namegenerateddl valuefalse property nameshowsql valuefalse property namedatabaseplatform valuehibernatedialect bean propertybeanbean iddomaindatasource classcommchangev2c3p0combopooleddatasource destroymethodclose property namedriverclass valuedbdriver property namejdbcurl valuedatasourceurl property nameuser valuedatasourceusername property namepassword valuedatasourcepassword property nameinitialpoolsize value5 property nameminpoolsize value5 property namemaxpoolsize value15 property namecheckouttimeout value10 property namemaxstatements value150 property nametestconnectiononcheckin valuetrue property nameidleconnectiontestperiod value50bean but i cannot find its name in google any ideas,['java'] +59673,object reference set in java i need to create a set of objects the concern is i do not want to base the hashing or the equality on the objects hashcode and equals implementation instead i want the hash code and equality to be based only on each objects reference identity ie the value of the reference pointeri am not sure how to do this in javathe reasoning behind this is my objects do not reliably implement equals or hashcode and in this case reference identity is good enough,['java'] +59674,false sense of security with snprintf s msvcs secure sprintf funcions have a template version that knows the size of the target buffer however this code happily paints 567890 over the stack after the end of byteschar bytes5 snprintf s bytes truncate s 1234567890 any idea what i do wrong or is this a known bugi am working in vs2005 did not test in 2008 or 2010,['c++'] +59685,using multithreading for loop i am new to threading and want to do something similar to this questionhowever i am not sure if that solution is the best one for me as i want them to keep running and never finish i am also using net 35 rather than 20 as for that questioni want to do something like thisforeach agent agent in agentlist i want to start a new thread for each of these agentdoprocesslooppublic void doprocessloop while true do the processing this is things like check folder for new files update database if new files found would a threadpool be the best solution or is there something that suits this betterupdate thanks for all the great answers i thought i would explain the use case in more detail a number of agents can upload files to a folder each agent has their own folder which they can upload assets to csv files images pdfs our service it is meant to be a windows service running on the server they upload their assets to rest assured i will be coming back with questions about windows services sometime soon will keep checking every agents folder if any new assets are there and if there are the database will be updated and for some of them static html pages created as it could take a while for them to upload everything and we want them to be able to see their uploaded changes pretty much straight away we thought a thread per agent would be a good idea as no agent then needs to wait for someone else to finish and we have multiple processors so wanted to use their full capacity hope this explains itthanksannelie,['c#'] +59693,are there function pointers in c i am trying to learn some c coding and wondering if the c concept of function pointers is included in c i see there are such things as delegates are they the same concept or do they differ on a more fundamental level,['c#'] +59694,how to set a limit to inner query in hibernate i have hql like thisfrom table1 t1 where t1name not in select t2name from table2 t2 order by t2date limit 10the problem is it does not understand limit keyword is there a way to run such query without splitting it into two subqueries,"['java', 'mysql']" +59695,background image for input typebutton i have been trying to change the background image of the input button through css but it does not work searchhtmlbody form namemyform classwrapper input typetext nameq onkeyupshowuser input typebutton namebutton valuesearch onclickshowuser classbutton p div idtxthintdiv p formbodysearchcssbutton backgroundimage url imagebtnpng norepeat cursorpointerwhat could be wrongeven inlineing the css did not seem to work,"['html', 'css']" +59700,how can i use ocmock to verify that a method is never called at my day job i have been spoiled with mockitos never verification which can confirm that a mock method is never calledis there some way to accomplish the same thing using objectivec and ocmock i have been using the code below which works but it feels like a hack i am hoping there is a better way voidtestsomemethothisnevercalled id mock ocmockobject mockforclassmyobject class mock stub andcallselectorfail onobjectself forbiddenmethod more test things here which hopefully never call mock forbiddenmethod voidfail stfailthis method is forbidden,['objective-c'] +59717,android is there a way to implement the barcode scanner into an app so i am working on a project and i am wondering if there is a way i can implement the barcode scanner into my android app so it would go from my app open the camera and take the picture get the info and go back to my app with that info,['android'] +59722,finding app id under ipa or app i am building an application that search and recognizes any iphone apps that user has in hisher computer i would like to know a way to extract the id of the application from the ipa filei was trying to do the recognition using only the app file name but i thiscovered that the file name is not the name of the app in apple storelive poker 6k free by zynga live poker 37ipathe id i am talking about is the app id like inthe id is 354901953does any body has a clue how can i manage to find this information,['iphone'] +59724,extract list of attributes from list of objects in python i have an uniform list of objects in pythonclass myclassobject def init self attr selfattr attr selfother noneobjs myclass i for i in range10now i want to extract a list with some attribute of that class let us say attr in order to pass it so some function for plotting that data for examplewhat is the pythonic way of doing itattroattr for o in objsmmaybe derive list and add a method to it so i can use some idiom likeobjsgetattributeattr,['python'] +59729,c stl array vs vector raw element accessing performance i am building an interpreter and as i am aiming for raw speed this time every clock cycle matters for me in this raw casedo you have any experience or information what of the both is faster vector or arrayall what matters is the speed i can access an element opcode receiving i do not care about inserting allocation sorting etci am going to lean myself out of the window now and sayarrays are at least a bit faster than vectors in terms of accessing an element iit seems really logical for me with vectors you have all those security and controlling overhead which does not exist for arrayswhy am i wrongno i cannot ignore the performance difference even if it is so small i have already optimized and minimized every other part of the vm which executes the opcodes,['c++'] +59730,add record to a has and belongs to many relationship i have two models users and promotions the idea is that a promotion can have many users and a user can have many promotionsclass user activerecordbase has and belongs to many promotionsendclass promotion activerecordbase has and belongs to many usersendi also have a promotions users tablemodel with no id of its own it references user id and promotions idclass promotionsusers activerecordbaseendso how do i add a user to a promotion i have tried something like thisuser userfindparamsidpromotion promotionfindparamspromo idpromo userpromotionsnewpromothis results in the following errornomethoderror undefined method stringify keys for promotion0x10514d420if i try this line insteadpromo userpromotionsnewpromoidi get this errortypeerror cannot dup fixnumi am sure that there is a very easy solution to my problem and i am just not searching for the solution the right way,['ruby-on-rails'] +59733,mvc2 editortemplate for dropdownlist i have spent the majority of the past week knee deep in the new templating functionality backed into mvc2 i had a hard time trying to get a dropdownlist template working the biggest problem i have been working to solve is how to get the source data for the drop down list to the template i saw a lot of examples where you can put the source data in the viewdata dictionary viewdatadropdownsourcevalueskey then retrieve them in the template itself var sourcevalues viewdatadropdownsourcevalueskey this works but i did not like having a silly string as the lynch pin for making this workbelow is an approach i have come up with and wanted to get opinions on this approachhere are my design goalsthe view model should contain the source data for the drop down listlimit silly stringsnot use viewdata dictionarycontroller is responsible for filling the property with the source data for the drop down listheres my view model public class customerviewmodel scaffoldcolumnfalse public string customercode get set uihintdropdownlist dropdownlistdropdownlisttargetproperty customercode thisplaynamecustomer code public ienumerableselectlistitem customercodelist get set public string firstname get set public string lastname get set public string phonenumber get set public string address1 get set public string address2 get set public string city get set public string state get set public string zip get set my view model has a customercode property which is a value that the user selects from a list of values i have a customercodelist property that is a list of possible customercode values and is the source for a drop down list i have created a dropdownlist attribute with a dropdownlisttargetproperty dropdownlisttargetproperty points to the property which will be populated based on the user selection from the generated drop down in this case the customercode propertynotice that the customercode property has scaffoldcolumnfalse which forces the generator to skip the field in the generated outputmy dropdownlistascx file will generate a dropdown list form element with the source data from the customercodelist property the generated dropdown list will use the value of the dropdownlisttargetproperty from the dropdownlist attribute as the id and the name attributes of the select form element so the generated code will look like thisselect idcustomercode namecustomercode optionselectthis works out great because when the form is submitted mvc will populate the target property with the selected value from the drop down list because the name of the generated dropdown list is the target property i kinda visualize it as the customercodelist property is an extension of sorts of the customercode property i have coupled the source data to the propertyheres my code for the controllerpublic actionresult create retrieve customercodes from a datasource of your choosing listcustomercode customercodelist modelservicegetcustomercodelist customerviewmodel viewmodel new customerviewmodel viewmodelcustomercodelist customercodelistselects new selectlistitem text scustomercode value scustomercode selected scustomercode viewmodelcustomercode asenumerable return viewviewmodelheres my code for the dropdownlistattributenamespace autoformattributes public class dropdownlistattribute attribute public string dropdownlisttargetproperty get set heres my code for the template dropdownlistascx control languagec inheritssystemwebmvcviewusercontrolienumerableselectlistitem import namespaceautoformattributesscript runatserver dropdownlistattribute getdropdownlistattribute var dropdownlistattribute new dropdownlistattribute if viewdatamodelmetadataadditionalvaluescontainskeydropdownlistattribute dropdownlistattribute dropdownlistattributeviewdatamodelmetadataadditionalvaluesdropdownlistattribute return dropdownlistattribute script dropdownlistattribute attribute getdropdownlistattributeselect id attributedropdownlisttargetproperty name attributedropdownlisttargetproperty foreachselectlistitem item in viewdatamodel if itemselected true option value itemvalue selectedtrue itemtext option else option value itemvalue itemtext option selecti tried using the htmldropdownlist helper but it would not allow me to change the id and name attributes of the generated select elementnote you have to override the createmetadata method of the dataannotationsmodelmetadataprovider for the dropdownlistattribute heres the code for thatpublic class metadataprovider dataannotationsmodelmetadataprovider protected override modelmetadata createmetadataienumerableattribute attributes type containertype funcobject modelaccessor type modeltype string propertyname var metadata basecreatemetadataattributes containertype modelaccessor modeltype propertyname var additionalvalues attributesoftypedropdownlistattributefirstordefault if additionalvalues null metadataadditionalvaluesadropdownlistattribute additionalvalues return metadata then you have to make a call to the new metadataprovider in application start of globalasaxcsprotected void application start registerroutesroutetableroutes modelmetadataproviderscurrent new metadataproviderwell i hope this makes sense and i hope this approach may save you some time i would like some feedback on this approach please is there a better approach,['asp.net'] +59742,nested bind expressions this is a followup question to my previous question include functionalint foovoid return 2class bar public int operator void return 3 int somethingint a return atemplate class c auto funcc c decltypec return c template class c int doitc c return ctemplate class c void func wrapperc c func stdbinddoitc stdforwardcc int mainint argc char argv call with a function pointer funcfoo func wrapperfoo error call with a member function bar b funcb func wrapperb call with a bind expression funcstdbindbarsomething b 42 func wrapperstdbindbarsomething b 42 error call with a lambda expression func voidint return 42 func wrapper voidint return 42 return 0i am getting a compile errors deep in the c headers functional1137 error invalid initialization of reference of type aint a from expression of type aint afunctional1137 error conversion from ainta to nonscalar type astd bindstd mem fnint barintbar inta requestedfunc wrapperfoo is supposed to execute funcdoitfoo in the real code it packages the function for a thread to execute func would the function executed by the other thread doit sits in between to check for unhandled exceptions and to clean up but the additional bind in func wrapper messes things up,['c++'] +59751,video game bots something i have always wondered especially since it inspired me to start programming when i was a kid was how video game bots work i am sure there are a lot of different methods but what about automation for mmorpgs or even fpstype botsi am talking about playermade automation bots,['c++'] +59754,can ruby access output from shell commands as it appears my ruby script is running a shell command and parsing the output from it however it seems the command is first executed and output saved in an array i would like to be able to access the output lines in real time just as they are printed i have played around with threads but have not got it to work any suggestions,['ruby'] +59760,can elementtree be told to preserve the order of attributes i have written a fairly simple filter in python using elementtree to munge the contexts of some xml files and it works more or less but it reorders the attributes of various tags and i would like it to not do thatdoes anyone know a switch i can throw to make it keep them in specified ordercontext for thisi am working with and on a particle physics tool that has a complex but oddly limited configuration system based on xml files among the many things setup that way are the paths to various static data files these paths are hardcoded into the existing xml and there are no facilities for setting or varying them based on environment variables and in our local installation they are necessarily in a different placethis is not a thisaster because the combined source and buildcontrol tool were using allows us to shadow certain files with local copies but even thought the data fields are static the xml is not so i have written a script for fixing the paths but with the attribute rearrangement diffs between the local and master versions are harder to read than necessarythis is my first time taking elementtree for a spin and only my fifth or sixth python project so maybe i am just doing it wrongabstracted for simplicity the code looks like thistree elementtrelementtreeparseinputfilei treegetiteratorfor e in i etext filteretexttreewriteoutputfilereasonable or dumbrelated linkshow can i get the order of an element attribute list using python xmlsaxpreserve order of attributes when modifying with minidom,['python'] +59761,winform without net framework i have to create few forms and give it as direct exe instead of installer which installs net framework which the end user is not happy they want something they can directly open and worki know it can be done as web but am looking for winformsplease suggest which tooltechnology can handle thisthankskarthick,"['.net', 'c++']" +59776,jframesetbackground not working why jframe mainframe new jframe mainframesetsize100 100 mainframesetbackgroundcolorcyan mainframesetvisibletruemy intent is to create a window with a cyan background what is wrong with this my window does not get cyan as i would expectalso could anyone point out why i seem to have all the colors in duplicate there is a colorcyan and a colorcyan is there any difference at all between the two maybe the older one was a constant from before there were enums in java and the second one is from the enumthanks,['java'] +59777,what is the best way to copy a folder and all subfolders and files using c i need to copy a folder from one drive to a removable hard thiskthe folder which needs to be copied will have many sub folders and files in itthe input will be source path and target pathlikesource path csourcefolder target path eafter copying is done i shud be able to see the folder sourcefolder in my e drivethanks,['c#'] +59780,how to convert string date to timestamp in java i want to convert string date into timestamp in java the following coding i have writteni have declare the date for date1 is 71 121314simpledateformat datetimeformatter1 new simpledateformat ymmdd hhmmssdate lfromdate1 datetimeformatter1parsedate1systemoutprintlngpsdate lfromdate1timestamp fromts1 new timestamplfromdate1gettimei want to convert 71 121314 this string date into timestamp now i got the output is 071 0013140 0530 but i want 71 121314 this format timestamp date can anyone please help me thank you,['java'] +59788,scalability of ruby on rails versus php can anyone comment on which is more scalable between ror and php i have heard that ror is less scalable than php since ror has a little more overhead with its mvc framework while php is more low level and lighter this is a bit vague can anyone explain better,"['php', 'ruby-on-rails']" +59793,what is the equivalent of regexp substr in mysql i want to extract a word from a string column of a tabledescriptionabc order id 2 x y aam order id 3 nn kk ywexpected result setorder id23table will at most have 100 rows text length is 256 char and column always has one order id present so performance is not an issuein oracle i can use regexp substr for this problem how would i solve this in mysqledit 1i am using locate and substr to solve the problem the code is ugly ten minutes after writing the code i am cursing the guy who wrote such an ugly code i did not find the regexp substr function in mysql docs but i am hoping that it existsanswer to why cant the table be optimized why is the data stored in such a dumb fashionthe example i gave just denotes the problem i am trying to solve in real scenario i am using a db based 3rd party queuing software for executing asynchronous tasks the queue serializes the ruby object as text i have no control over the table structure or the data format the tasks in the queue can be recurring in our test setup some of the recurring tasks are failing because of stale data i have to delete these tasks to prevent the error such errors are not common hence i do not want to maintain a normalized shadow table,"['sql', 'mysql']" +59804,virtualenv yolk problem yolk l gives me information that i have got 114 packages installed on my ubuntu 1004 after creating new virtualenv directory using virtualenv virt envvirt1 nositepackages cleari switched to that my prompt changed and then yolk l gives me again the same 114 packages what is going on there,['python'] +59809,remove nonascii characters from a string using python django i have a string of html stored in a database unfortunately it contains characters such as ai want to replace these characters by their html equivalent either in the db itself or using a find replace in my python django codeany suggestions on how i can do this,['python'] +59812,ipad keyboard dimensions i have found the iphones keyboard bounds in the apple documentation but i cannot find the ipads keyboard bounds could you please help me,['objective-c'] +59817,is it possible to write to the console in colour in net writing a small command line tool it would be nice to output in different colours is this possible,"['c#', '.net']" +59825,uniqueidentifier equivalent datatype in c what is uniqueidentifier sql server 2005 equivalent in c 35 datatype,"['c#', 'sql']" +59832,why do i get procedure expects parameter statement of type ntextncharnvarchar when i try to use sp executesql why do i get this errorprocedure expects parameter statement of type ntextncharnvarcharwhen i try to use sp executesql,['sql'] +59840,express any number as the sum of four prime numbers i was give a problem to express any number as sum of four prime numbersconditions not allowed to use any kind of database maximum execution time 3 secondsnumbers only till 10if the splitting is not possible then return 1what i did using the sieve of eratosthenes i calculated all prime numbers till the specified numberlooked up a concept called goldbach conjecture which expresses an even number as the summation of two primeshowever i am stuck beyond thatcan anyone help me on this one as to what approach you might takethe sieve of eratosthenes is taking two seconds to count primes up to 10,['c++'] +59844,why data function of jquery is better to prevent memory leaks regarding to jquery utility function jquerydata the online documentation saysthe jquerydata method allows us to attach data of any type to dom elements in a way that is safe from circular references and therefore from memory leaks why to usedocumentbodyfoo 52 can result a memory leak or in what conditions so that i should usejquerydatadocumentbody foo 52should i always prefer data instead of using expandos in any casei would appreciate if you can provide an example to compare the differencesthanksburak ozdogan,"['javascript', 'jquery']" +59851,preventing fixed footer from overlapping content i have fixed my footer div to the bottom of the viewport as followsfooter position fixed bottom 0this works well if there is not much content on the page however if the content fills the full height of the page ie the vertical scroll bar is visible the footer overlaps the content which i do not wonthow can i get the footer to stick to the bottom of the viewport but never overlap the content,"['html', 'css']" +59853,generic method to create deep copy of all elements in a collection i have various observablecollections of different object types i would like to write a single method that will take a collection of any of these object types and return a new collection where each element is a deep copy of elements in the given collection here is an example for a specifc class private static observablecollectionpropertyvaluerow deepcopyobservablecollectionpropertyvaluerow list observablecollectionpropertyvaluerow newlist new observablecollectionpropertyvaluerow foreach propertyvaluerow rec in list newlistaddpropertyvaluerowrecclone return newlist how can i make this method generic for any class which implements icloneable,['c#'] +59857,invoking a url c i m trying to invoke a url in c i am just interested in invoking and dont care about response when i have the following does it mean that i m invoking the url httpwebrequest request httpwebrequestwebrequestcreateurl,"['c#', '.net']" +59859,c copy file to another directory using other domainusernamepassword in c 2008i am trying to copy a file to a destination path for example newserverdestinationfolder that can be in another domain or using a different usernamepassword than the current user how can i specify these new network credentials before doing the filecopy thank you,['c#'] +59864,enumtryparse with flags attribute i have written code to tryparse enum either by value or by its name as shown below how can i extend this code to include parsing enums with flags attribute public static bool tryparsetthis t enum type object value out t result where t struct return enum typetryparsetvalue true out result public static bool tryparsetthis t enum type object value bool ignorecase out t result where t struct result defaultt var is converted false var is valid value for conversion new funct object bool bool e v i egettypeisenum e v i v null e v i enumgetnamesegettypeanyn stringcomparen vtostring i 0 enumisdefinedegettype v ifis valid value for conversionallrule ruleenum type value ignorecase result tenumparsetypeoft valuetostring ignorecase is converted true return is converted currently this code works for the following enumsenum someenum a b c can parse either by a or aenum someenum1 int a 1 b 2 c 3 can parse either by a or a or 1 or 1does not work forflagsenum someenum2 a 1 b 2 c 4 can parse either by a or a cannot parse for abthanks,"['c#', '.net']" +59865,c destructor issue with stdvector of class objects i am confused about how to use destructors when i have a stdvector of my class so if i create a simple class as followsclass testprivate int bigpublic test big new int10 test delete big then in my main function i do the followingtest tobj testvectortest tvectvecpush backtobji get a runtime crash in the destructor of test when i go out of scope why is this and how can i safely free my memory,['c++'] +59888,why is the base class being called heres my situationinterface icontainer string nameabstract class fuzzycontainer icontainer string name return fuzzy container class specialcontainer fuzzycontainer string name return basename special container icontainer cont new specialcontainercontname i expected fuzzy container special container as the outputwhen i run my code as described above the output is simply fuzzy container what am i missing here is there a better way to get the desired results,['c#'] +59902,reusable view components in html can you create reusable components in html let us say i want to encapsulate some css html and js into a tidy reusable component how do web developers do this i am coming from the flex c side of the planet,['html'] +59908,syntax for specializing function templates is there a difference between the following approaches approach 1namespace std template void swapfoofoo x foo y note the foo xswapy approach 2namespace std template void swapfoo x foo y xswapy i stumpled upon this when i tried to specialize swap for my own string type and noticed that swapstring does not work but for a completely different reason,['c++'] +59919,is there any way to tell which gems and plugins are loaded at runtime for a rails process is there any command either in debugger or rubydebug to get a list of all gems andor plugins loaded in memory for a rails process i understand only the require gems are loaded but i would like to quickly see what got loaded during runtime,['ruby-on-rails'] +59934,clickable widgets in android the developer documentation has seemed to have failed me here i can create a static widget without thinking i can even create a widget like the analogue clock widget that will update itself however i can not for the life of me figure out how to create a widget that reacts to when a user clicks on it here is the best code sample that the developer documentation gives to what a widget activity should contain the only other hint being the api demos which only creates a static widgetpublic class exampleappwidgetprovider extends appwidgetprovider public void onupdatecontext context appwidgetmanager appwidgetmanager int appwidgetids final int and appwidgetidslength perform this loop procedure for each app widget that belongs to this provider for int i0 in i int appwidgetid appwidgetidsi create an intent to launch exampleactivity intent intent new intentcontext exampleactivityclass pendingintent pendingintent pendingintentgetactivitycontext 0 intent 0 get the layout for the app widget and attach an onclick listener to the button remoteviews views new remoteviewscontextgetpackagename rlayoutappwidget provider layout viewssetonclickpendingintentridbutton pendingintent tell the appwidgetmanager to perform an update on the current app widget appwidgetmanagerupdateappwidgetappwidgetid views from the android developer documentations widget pageso it looks like pending intent is called when the widget is clicked which is based off of an intent i am not quite sure what the difference between an intent and a pending intent is and the intent is for the exampleactivity class so i made my sample activity class a simple activity that when created would create a mediaplayer object and start it it wouldnt ever release the object so it would eventually crash here is it is codeoverridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate mediaplayer mp mediaplayercreategetapplicationcontext rrawsound mpstarthowever when i added the widget to the home screen and clicked on it nothing played in fact nothing played when i set the update timer to just a few hundred milliseconds in the appwidget provider xml file furthermore i set break points and found out that not only was it never reaching the activity but no break points i set would ever get triggered i still have not figured out why that is however logcat seemed to indicate that the activity class file was being runso is there anything i can do to get an appwidget to respond to a click as the onclickpendingintent method is the closest i have found to a onclick type of methodthank you very much,"['java', 'android']" +59942,how to change background color in android app i want to be able to change the background color to white in my android app in the simplest way possible,['android'] +59945,how is java platformindependent when it needs a jvm to run i just started learning java and i am confused about the topic of platform independencedoes not independent imply that java code should run on any machine and need no special software to be installed yet the jvm needs to be present in the machinefor example we need to have the turbo c compiler in order to compile cc source code and then execute it the machine has to have the c compilercould somebody please what is meant when java is described as platform independent,['java'] +59950,wpf custom control itemscontrol template not being applied i am building a custom wpf control that derives from tabcontrol in the controltemplate i am using a itemscontrol to thisplay a list that is being bound from the template an observable collection of type filemenuitem during program execution i am getting the following error in the output windowitemtemplate and itemtemplateselector are ignored for items already of the itemscontrols container type typefilemenuitemthe type filemenuitem is derived from menuitem if i change the base class to dependencyobject the code actually runs and the template is applied so that is an option i googled the error and could not find anything about it has anyone run into this while developing custom controls even though i have a workaround i would like to understand whats happening and i think using the menuitem as a base class is a cleaner implementationi can post more code if it would help thanks,['c#'] +59954,unzip failedaccess is denied error while adding android sdk components to eclipse eclipse 35 windowandroid sdk and avd managerwhen adding sdk components there is the following error messagedownloading documentation for android sdk api 7 revision 1installing documentation for android sdk api 7 revision 1unzip failed cprogram filesandroid sdktempdocpackagenew01navtree datajs access is deniedthis is followed by another message nothing is installedi use windows 7 64bit systemcould anyone please help to get around this thank you in advancevmitsura,['android'] +59960,why does jqueryajax add a parameter to the url i have a data fetching method that uses jqueryajax to fetch xml files data function debug try var url arguments0 var type arguments1 var scope arguments2 var callback arguments3 var self this ifthiscacheurl callbackthiscacheurl else ifthiscacheurl ajax type get url url datatype type cache false success functiondata iftype textxml var myjson auxjson var jsonstring myjsonbuilddatascopenull var jsonobject parsejsonjsonstring selfcacheurl jsonobject callbackurl else iftype json selfcacheurl data callbackurl error function throw ajax call failed debug catche debug alert caller signtutordatan e debug my problem is jquery somehow adds a parameter 1272708280072 to the url if there are escaped hexadecimal notation or unescaped utf8 characters outside of the ascii range i believe in the file name it all works well if the file name does not contain characters in that rangetype is set to xml so there should not be a confusion of types headers of the xml files are also set adequatelyi can see from the console that jquery throws an error but i am not sure as to where the problem really isprobably a problem with file name formatting but i did not find any resources on the web as to ajax file name specifications any ideasthanks for you help,"['javascript', 'jquery']" +59971,cc struct vs class after finishing my c class it seemed to me the structsclasses are virtually identical except with a few minor differencesi have never programmed in c before but i do know that it has structs in c is it possible to inherit other structs and set a modifier of publicprivateif you can do this in regular c why in the world do we need c what makes classes different from a struct,['c++'] +59976,rails db migration undefined method to sym cannot figure out syntax the original migration looks like thisclass createusers true do t tstring login limit 40 tstring name limit 100 default null true tstring email limit 100 tstring crypted password limit 40 tstring salt limit 40 tstring remember token limit 40 tdatetime remember token expires at tstring activation code limit 40 tdatetime activated at datetime tstring state null no default passive tdatetime deleted at tinteger occupation id null yes tdatetime paid up to date date ttimestamps endand i am trying to change the default of state to be active instead of passiveso my attempt at a migration looks like this still learning be gentle class changeuserstatedefault activerecordmigrationdef selfupchange column users state null no default activeend,['ruby-on-rails'] +59979,how to find the phpini file used by the command line i need to enable pdo mysql in my easyphp environment so i went to phpini file and uncommented the following lineextensionphp pdo mysqldllunfortunately i still have the same problemi am using the cli so i suppose i need to locate the phpini file used by the cli how can i find it,['php'] +60002,why camerasetparameterscameraparameters does not work on sonyericsson x10 and droid has anyone come across a strange behaviour with the camera api when used on sonyericsson x10 or droidfor example the following code does not work on those devices as a result i am getting a lot of negative feedback on the market translating into many cancelled ordersmparameterssetrotation orientationmparameterssetjpegquality img qualitymparameterssetpicturesize 1024x768mcamerasetparametersmparameterscould you suggest an alternative way of achieving the same thanks,['android'] +60009,how exactly does the doublestringize trick work at least some c preprocessors let you stringize the value of a macro rather than its name by passing it through one functionlike macro to another that stringizes itdefine str1x xdefine str2x str1xdefine the answer 42define the answer str str2the answer 42 example use cases herethis does work at least in gcc and clang both with stdc99 but i am not sure how it works in cstandard termsis this behavior guaranteed by c99if so how does c99 guarantee itif not at what point does the behavior go from cdefined to gccdefined,['c'] +60033,why this c program outputs a negative number i have assigned the complement value in an unsigned variablethen why this c program outputs a negative numberincludestdiohincludeconiohint main unsigned int value 4 4 0 0 0 0100 unsigned int result 0 result value 5 1 1 1 1011 printfresult d result 5 getch return 0,['c'] +60038,who architected designed cs iostreams and would it still be considered welldesigned by todays standards first off it may seem that i am asking for subjective opinions but that is not what i am after i would love to hear some wellgrounded arguments on this topicin the hope of getting some insight into how a modern streams serialization framework ought to be designed i recently got myself a copy of the book standard c iostreams and locales by angelika langer and klaus kreft i figured that if iostreams was not welldesigned it wouldnt have made it into the c standard library in the first placeafter having read various parts of this book i am starting to have doubts if iostreams can compare to eg the stl from an overall architectural pointofview read eg this interview with alexander stepanov the stls inventor to learn about some design decisions that went into the stlwhat surprises me in particularit seems to be unknown who was responsible for iostreams overall design i would love to read some background information about this does anyone know good resourcesonce you delve beneath the immediate surface of iostreams eg if you want to extend iostreams with your own classes you get to an interface with fairly cryptic and confusing member function names eg getlocimbue uflowunderflow snextcsbumpcsgetcsgetn pbasepptrepptr and there is probably even worse examples this makes it so much harder to understand the overall design and how the single parts cooperate even the book i mentioned above does not help that much imhothus my questionif you had to judge by todays software engineering standards if there actually is any general agreement on these would cs iostreams still be considered welldesigned i wouldnt want to improve my software design skills from something that is generally considered outdated,['c++'] +60043,different small js files per page vs 1x sitewide js file different pages of my site have different js needs plugins mainly some need a lightbox some dont some need a carousel some dont etcwith regards to pageloading speed should i option 1 reference each js file when it is neededso one page might havescript typetextjavascript srcjscarouselscrollablejsscript script typetextjavascript srcjsjqueryeasydragjsscriptscript typetextjavascript srcjscolorboxjquerycolorboxminjsscriptand another havescript typetextjavascript srcst wd assetsjscarouselscrollablejsscript script typetextjavascript srcst wd assetsjstypewatchjsscriptoption 2 combine and compress into one site widejs fileso each page would referencescript typetextjavascript srcjssite widejsscriptthere would be unused selectorsevent listeners though how bad is thisi would include any plugin notesaccreditations at the top of the site widejs file,"['javascript', 'jquery']" +60045,how to get last full ms sql server error message i am aware ofselect errorbut it will give me only an error code a number and i need a full text message likecannot insert duplicate key row in object dbotable name with unique index ix id uniquethe statement has been terminatedhow can i do that in ms sql server 2005 edit i need to acquire this error message on linux and windows platforms,['php'] +60048,how to make shell output redirect write while script is still running i wrote a short script that never terminates this script continuously generates output that i have to check on every now and then i am running it on a lab computer through ssh and redirecting the output to a file in my public html folder on that machinepython scriptpy public htmlresultstxthowever the results do not show up immediately when i refresh the address the results show up when i terminate the program but as i said it does not halt by itself is that redirect being lazy with with writing is there a way to continuously or with an interval update the results in the fileor is it the webserver that does not update the file while it is still being written,['python'] +60074,question about spring transaction propagation i have a question about spring transaction propagation if i use transactionalpropagation propagationrequired to annotate a method m1 when execution logic enter m1 if there is already a transaction m1 will use that one when after m1 what about the transaction it ends or still openif i call m1 in another method and after the invocation there is still other things to doin summary i want to know when exiting an annotated method the transaction ends or still opengreat thanks,['java'] +60079,inet aton and inet ntoa in php i want to store ip addresses in my database but i also need to use them throughout my application i read about using inet aton and inet ntoa in my mysql queries to get a 32bit unsigned integer out of an ip address which is exactly what i want as it will make searching through the database faster than using char15the thing is i cannot find a function that does the same sort of thing in php the only thing i came across isso i tested itip serverremote addrecho ip2longipand it outputs nothing in the example they gave it seems to work but then again i am not exactly sure if ip2long does the same thing as inet atondoes someone know a php function that will do this or even a completely new solution to storing an ip address in a databasethanks,"['php', 'sql', 'mysql']" +60080,mysql database design for a quiz i am making an online quiz with php and mysql and need a bit of help deciding how to design the database for optimal insert of questionsanswers and to select questions for the quiz the table will hold 80 questions each with 4 possible options plus the correct answerwhen retrieving the questions and options from the database i will randomly select 25 questions and their optionsis it better to make a single column for all questions options and correct answers for exampleid q opt1 opt2 opt3 opt4 ansor would it be better to make a column for each individual question option and correct answer for exampleq1 q1 opt1 q1 opt2 q1 opt3 q1 opt5 q1 ans q2 q2 opt1 q2 opt2,"['php', 'mysql']" +60083,how to compile opengl with a python c extension using thistutils on mac osx when i try it i getimporterror dlopenlibraryframeworkspythonframeworkversions25libpython25sitepackagescscalelibso 2 symbol not found glbindframebufferext referenced from libraryframeworkspythonframeworkversions25libpython25sitepackagescscalelibso expected in dynamic lookupi have tried all sort of things in the setuppy file what do i actually need to put in it to link to opengl properly my code compiles fine so there is no point putting that on there here is setuppyfrom thistutilscore import setup extensionmodule1 extensioncscalelib extra compile args framework opengl lm lgl lglu sources cscalelibcppsetup name cscalelib version 01 description test for setup framebuffer ext modules module1,"['c++', 'python']" +60084,mysql count how many queries per second are executed is there any way i have a busy web server with lamp installed and i was wondering is there any way to count how many queries per second mysql are executed in the server thank you,['mysql'] +60090,getting value of stdlistiterator to pointer how can i loop thru a stllist and store the value of one of the objects for use later in the functionparticle closestparticleforlistparticleiterator p1 mparticlesbegin p1 mparticlesend p1 extra stuff removed closestparticle p1 fails to compile edit from comments,['c++'] +60102,inplacebitmapmetadatawritertrysave returns true but does nothing on some jpg files eps previews generated by adobe illustrator in windows 7 inplacebitmapmetadatawritertrysave returns true after some setquery calls but does nothingcode samplebitmapdecoder decoderbitmapframe framebitmapmetadata metadatainplacebitmapmetadatawriter writerdecoder bitmapdecodercreates bitmapcreateoptionspreservepixelformat bitmapcreateoptionsignorecolorprofile bitmapcacheoptiondefaultframe decoderframes0metadata framemetadata as bitmapmetadatawriter framecreateinplacebitmapmetadatawritertry writersetquerysystemtitle title writersetqueryapp1ifdushort exiftagids0 title 0tochararray writersetqueryapp13irb8bimiptciptcobject name title return writertrysavecatch return falseimage sampleyou can reproduce problem if you have windows 7 by downloading image sample and using this code sample to set title on this imageimage has enough room for metadata and this code sample works fine on my winxpsame code works fine on win7 with other jpg filesany ideas are welcome,['c#'] +60115,php require class call from inside method from my understanding require pastes code into the calling php filewhat if you were requiring from inside a methodit would paste the entire codeclass inside the method blocking the next statement in the methodeg function test require pathtosomeclasscode somestatement any code after the require is blocked how do i get around this to be able to require code whereever without it being pasted in that exact spot,['php'] +60120,diamond square algorithm i am trying to write the diamondsquare algorithm in java to generate a random map but cannot figure out the implementationanyone with some java code or other language so i can check how the loop is made would be greatly appreciatedthanks,['java'] +60124,how to thisable cache in internetexplorer 8 how can i thisable cache in ie8 we are doing javascript development and testing it in ie8 but we have to clear the cache every time we make changes to the javascript files,['javascript'] +60128,how to use regular expression in lxml xpath i am using construction like thisdoc parseurlgetrootlinks docxpathatextsome textbut i need to select all links which have text beginning with some text so i am wondering is there any way to use regexp here did not find anything in lxml documentation,['python'] +60130,testing performance of queries in mysql i am trying to setup a script that would test performance of queries on a development mysql server here are more detailsi have root accessi am the only user accessing the servermostly interested in innodb performancethe queries i am optimizing are mostly search queries select like xywhat i want to do is to create reliable testing environment for measuring the speed of a single query free from dependencies on other variablestill now i have been using sql no cache but sometimes the results of such tests also show caching behaviour taking much longer to execute on the first run and taking less time on subsequent runsif someone can explain this behaviour in full detail i might stick to using sql no cache i do believe that it might be due to file system cache andor caching of indexes used to execute the query as this post explains it is not clear to me when buffer pool and key buffer get invalidated or how they might interfere with testingso short of restarting mysql server how would you recommend to setup an environment that would be reliable in determining if one query performs better then the other,['mysql'] +60136,how to pull a method out of its class and into a new or existing what is the easiest way of pulling an excisting method out of its class and into a new class using visual studio 2010 resharperedit i use resharper version 5,['c#'] +60146,implicit and explicit implementation of interface while working on a upgrade i happened to come across a code like thisinterface icustomization immcolumnsdefinition getcolumnsdefinition class customization icustomization private readonly columndefinition columndefinition more code here public columnsdefinition getcolumnsdefinition return columndefinition columnsdefinition icustomizationgetcolumnsdefinition redundant return getcolumnsdefinition my question isis there any needuse of explicit implementation of interface in this piece of codewill it create any problem if i remove the method explicit implementation of interface that i have marked redundant aboveps i understand that explicit implementation of interface is very important and it can be used when we need to give access to a method at interface level only and to use two interface with same signature of method,"['c#', '.net']" +60175,should we denormalize database to improve performance we have a requirement to store 500 measurements per second coming from several devices each measurement consists of a timestamp a quantity type and several vector values right now there is 8 vector values per measurement and we may consider this number to be constant for needs of our prototype project we are using hnibernate tests are done in sqlite thisk file db not inmemory but production will probably be mssql our measurement entity class is the one that holds a single measurement and looks like thispublic class measurement public virtual guid id get private set public virtual device device get private set public virtual timestamp timestamp get private set public virtual ilistvectorvalue vectors get private set vector values are stored in a separate table so that each of them references its parent measurement through a foreign keywe have done a couple of things to ensure that generated sql is reasonably efficient we are using guidcomb for generating ids we are flushing around 500 items in a single transaction adonet batch size is set to 100 i think sqlite does not support batch updates but it might be useful laterthe problemright now we can insert 150200 measurements per second which is not fast enough although this is sqlite we are talking about looking at the generated sql we can see that in a single transaction we insert as expected1 timestamp1 measurement8 vector valueswhich means that we are actually doing 10x more single table inserts 150020 per secondif we placed everything all 8 vector values and the timestamp into the measurement table adding 9 dedicated columns it seems that we could increase our insert speed up to 10 timesswitching to sql server will improve performance but we would like to know if there might be a way to avoid unnecessary performance costs related to the way database is organized right noweditwith inmemory sqlite i get around 350 itemssec 3500 single table inserts which i believe is about as good as it gets with nhibernate taking this post for reference but i might as well switch to sql server and stop assuming things right i will update my post as soon as i test itupdatei have moved to sql server and flattened my hierarchy i tested it by storing 30 measurementssec for several hours and it seems to be working fine,['.net'] +60183,how are net 4 guids generated i am aware of the multitude of questions here as well as raymonds excellent as usual post however since the algorithm to create guids was changed apparently i found it hard to get my hands on any uptodate information the msdn seems to try and provide as few information as possiblewhat is known about how guids are generated in net 4 what was changed and how does it affect the security randomness and integrity uniquenessone specific aspect i am interested in in v1 it seems to be about impossible to generate the same guid on a single machine again since there was a timestamp and counter involved in v4 this is no longer the case i was told so the chance to get the same guid on a single machine increased,['.net'] +60190,how to sort stl vector i want to sort a vector vectormyclass objectwhere as myclass contains many int data variables how can i sort my vector on any specific data variable of myclass,['c++'] +60206,uimodaltransitionstylepartialcurl not rotating i have got a modal view controller that is being thisplayed using uimodalpresentationfullscreen with the transitionstyle set as uimodaltransitionstylepartialcurl this works beautifully my problem is that when the device is rotated my view rotates as intended but the curl effect does not does anyone know if this is by design or is there something else that needs to be done thanks,['iphone'] +60215,invoking proc with instance eval with arguments i know this worksproc procnew do puts selfhi worldendclass usa def hi hello endendusanewinstance eval prochowever i want to pass arguments to proc so i tried this which does not workproc procnew do greeting puts selfhi greetingendclass usa def hi hello endendusanewinstance eval proc world does not workusanewinstance eval procworld does not workcan anyone help me make it work,['ruby'] +60218,how to programmatically add view in viewflipper i have following main layoutlinearlayout androidididlinearlayout01 androidlayout widthfill parent androidlayout heightfill parent xmlnsandroid androidorientationvertical viewflipper androidididviewstack androidlayout widthfill parent androidlayout heightfill parent here i want to add my views which are located in separated xml files viewflipperlinearlayouthere is example of my viewview urlxmllinearlayout androidididlinearlayout01 androidlayout widthfill parent androidlayout heightfill parent xmlnsandroid androidorientationvertical androidgravitycenter edittext androidtextidedittext01 androidididedittext01 androidlayout widthfill parent androidlayout heightwrap content button androidlayout widthwrap content androidlayout heightwrap content androidididbtngenerate androidtextgeneratelinearlayoutview textxmllinearlayout androidididlinearlayout01 androidlayout widthfill parent androidlayout heightfill parent xmlnsandroid androidorientationvertical edittext androidtextidedittext01 androidididedittext01 androidlayout heightwrap content androidcontentdescriptionenter your text here androidlayout widthfill parent androidheight200dplinearlayouti am trying to add viewsviewstack viewflipper findviewbyidridviewstackview viewtext view findviewbyidrlayoutview textviewstackaddviewviewtext emulator is crashing at this lineview viewurl view findviewbyidrlayoutview urlviewstackaddviewviewurli dont have any idea what is wrong with my code i decided to put all my views in one file but i still want to know how to fix my initial code,['android'] +60221,can i use const in vectors to allow adding elements but not modifications to the already added my comments on this answer got me thinking about the issues of constness and sorting i played around a bit and reduced my issues to the fact that this codeinclude vectorint main stdvector const int v will not compile you cannot create a vector of const ints obviously i should have known this and intellectually i did but i have never needed to create such a thing before however it seems like a useful construct to me and i wonder if there is any way round this problem i want to add things to a vector or whatever but they should not be changed once added there is probably some embarrassingly simple solution to this but it is something i would never considered beforei probably should not have mentioned sorting i may ask another question about that see this for the difficulties of asking questions my real base use case is something like thisvector const int v ok ie i want it to be okvpush back 42 okint and v0 okv0 1 not allowed,['c++'] +60229,how to learn about iphone jailbroken programming i am interested in learning about what additional features and apis an app has access to when an iphone is jailbroken can someone provide me with some basic resources to learn about this i would be most interested indocumentation on the private apisfilesystem layoutapp configuration eg how did winterboard replace springboard apps that replace the lockscreentools neededsuggestions appreciated,['iphone'] +60232,windows identity framework with windows xp how can use the windows identity foundation sdk with windows xp,['.net'] +60246,can i get an audio session apply audio units to playback from mpmusicplayercontroller i would like to take control of the audio coming from mpmusicplayercontroller ie playing from the ipod library for example i would like to apply eq to it or do dsp reverb that kind of thingis this possible is there an audio session that i can grab a handle on or perhaps is there some way to play back files from the ipod library using an avaudioplayer,['iphone'] +60254,what does the add drop table view procedure function checkbox do in phpmyadmin under the structure tab when exporting a database using phpmyadmin there is a check box labeledadd drop table view procedure functionwhat does this do,"['php', 'mysql']" +60256,why is passing a string literal into a char argument only sometimes a compiler error i am working in a c and c program we used to be compiling without the makestringswritable option but that was getting a bunch of warnings so i turned it offthen i got a whole bunch of errors of the form cannot convert const char to char in argmuent 3 of function foo so i went through and made a whole lot of changes to fix those however today the program crashed because the literal was getting passed into a function that was expecting a char and was setting the 0th character to 0 it was not doing anything bad just trying to edit a constant and crashing my question is why was not that a compiler error in case it matters this was on a mac compiled with gcc40edit added codechar host findargdefaultemaillinkhost stripcrlflinkhost nwherechar findargdefaultchar argname char defval simplified char val defval returnvalandvoid stripcrlfchar str char delim char p q for p q str p p if p 0xd p 0xa if p1 p 7 p if delim 1 p delim q p q 0 dies herethis compiled and ran until it tried to set q to 0edit 2most people seem to be missing the point of my question i know why char foo bar works i know why char foo bar does not work my question is mostly with respect to passing parameters one thing that occures to me is is it possible that this is a c vs c issue because i have some c files and some cpp files and it is quite possible that c allows it but c does not or vice versa,"['c++', 'c']" +60274,select most recent records using linq to entities i have a simple linq to enities table to query and get the most recent records using date fieldso i tried this codeiqueryablealert alerts getalertsiqueryablealert latestalerts from a in alerts group a by aupdatedatetime into g select gorderbya aidentifierfirsterror notsupportedexception the method groupby is not supportedis there any other way to get do itthanks a lot,['c#'] +60275,html5 canvas how to make a loading spinner by rotating the image in degrees i am making a loading spinner with html5 canvas i have my graphic on the canvas but when i rotate it the image rotates off the canvas how do i tell it to spin the graphic on its center pointdoctype htmlhtml head titlecanvas testtitle script typetextjavascript windowonload function var drawingcanvas documentgetelementbyidmydrawing check the element is in the dom and the browser supports canvas ifdrawingcanvas drawingcanvasgetcontext initaliase a 2dimensional drawing context var context drawingcanvasgetcontext2d load the image object in js then apply to canvas onload var myimage new image myimageonload function contextdrawimagemyimage 0 0 27 27 myimagesrc imgloadingpng contextrotate45 script head body canvas idmydrawing width27 height27 canvas bodyhtml,['javascript'] +60284,could i ever want to access the address zero the constant 0 is used as the null pointer in c and c but as in the question pointer to a specific fixed address there seems to be some possible use of assigning fixed addresses is there ever any conceivable need in any system for whatever low level task for accessing the address 0if there is how is that solved with 0 being the null pointer and allif not what makes it certain that there is not such a need,"['c++', 'c']" +60292,making a call to a net 4 library from 35 i have the need to make a call to the systemxaml library in net 40 is it possible to make a call to this library if your project is targeted to 35,['.net'] +60306,detecting a url using preg match without http in the string hey therei was wondering how i could check a string broken into an array against a preg match to see if it started with w i already have one that check for httpw function isvalidurlurlreturn preg matchhttpsaz09az0909i urlstringtoarray explode posttext foreachstringtoarray as keyval urlvalid isvalidurlval ifurlvalid sessionmessages no urls allowed headerlocation postpostid exit thanksstefan,['php'] +60323,make all types constant by default in c what is the simplest and least obtrusive way to indicate to the compiler whether by means of compiler options defines typedefs or templates that every time i say t i really mean t const i would prefer not to make use of an external preprocessor since i do not use the mutable keyword that would be acceptable to repurpose to indicate mutable stateedit since the intent of this was mistaken entirely and since i was not around for a few hours to clarify let me explain in essence i just want to know what systems are available for manipulating the type system at compile time i do not care if this creates nonstandard bad unmaintainable useless code i am not going to use it in production it is just a curiositypotential suboptimal solutions so far i presume redefinition of keywords is implementationdefined or illegaldefine int int constdefine ptr constint i0int ptr jitypedef int const inttypedef int const const intpint i0intp jitemplateclass tstruct c typedef t const type typedef t const const ptr cinttype i0cintptr ji,['c++'] +60326,is there a way to put relationshipscontraints into css in every design tool or art principle i have heard of relationships are a central theme by relationships i mean the thing you can do in adobe illustrator to specify that the height of one shape is equal to half the height of another you cannot express this information in css css hardcodes all values using a language like less that allows variables and arithmetic you can get closer to relationships but it is still a css variantthis inability in my mind is the biggest problem with css css is supposed to be a language that describes the visual component of a web page but it ignores relationships and contraints ideas that are at the core of arthow possible is it to imagine a new web design language that can express relationships and contraints that can be implemented in javascript using the current css properties,['css'] +60344,selenium webdriver example in python i had written a scipt in java with webdriver and it worked fine and below is the code for the sampleimport orgjunitafterimport orgjunitafterclassimport orgjunitbeforeimport orgjunitbeforeclassimport orgopenqaseleniumwebdriverimport orgopenqaseleniumwebdriverbackedseleniumimport orgopenqaseleniumfirefoxfirefoxdriverimport comthoughtworksseleniumseleniumimport javautilimport javalangthreadpublic class login beforeclass public static void setupbeforeclass throws exception afterclass public static void teardownafterclass throws exception before public void setup throws exception after public void teardown throws exception public static void mainstring args webdriver driver new firefoxdriver selenium selenium new webdriverbackedseleniumdriver seleniumopen seleniumkeypressnameuser id admin but my requirement is to implement the same in python with webdriver can you please let me know how this can be done with the above example and webdriver binaries and how to do setup for the same,['python'] +60350,log4j log output of a specific class to a specific appender i use log4j and would like to route the output of certain loggers to specific files i already have multiple appenders in place now to make debugging easier i want to tell log4j that the output generated by a specific class eg foobarbaz should be written to a specific log filecan this be done,['java'] +60351,how to replace only part of the match with python resub i need to match two cases by one reg expression and do replacementlongfilenamejpg longfilename suffjpglongfilename ajpg longfilename suffjpgi am trying to do the followingresub a sufflongfilenamejpgbut this is cut the extension jpg and i am gettinglongfilename suff instead of longfilename suffjpgi understand that this is because of part but i cannot exclude it becausei have to find last occurance of a to replace or last is there a way to replace only part of the match,['python'] +60358,kohana 3 get current controlleractionarguments in kohana 2 you could easily get that information like thisecho routercontrollerecho routermethodecho routerarguments0xany idea how that works in kohana 3thanks in advance,['php'] +60378,not enough arguments for format string i have such code in pythondef send startself player for p in selfplayers playersocketsend cmdplayer ids names yous avatarpng banks selfplayersindexp1 pname intplayerpidppid 0 playersocketsend cmdgame playerids selfturnnow playersocketsend cmdstart and the error is in the title of this post whats wrong,['python'] +60389,why use a singleton instead of static methods i have never found good answers to these simple questions about helperutility classeswhy would i create a singleton stateless instead of using static methodswhy would an object instance be needed if an object has no state,['java'] +60396,ternary operators in c with the ternary operator it is possible to do something like the following assuming func1 and func2 return an intint x x y func1 func2however is there any way to do the same thing without returning a value for example something like assuming func1 and func2 return voidx y func1 func2i realise this could be accomplished using an if statement i just wondered if there was a way to do it like this,"['c#', '.net']" +60400,how to create zebra stripes on html table without using javascript and evenodd classes generation i want to zebrastripe a html table without using any js stuff or writing serverside code to generate evenodd classes for table rows is it ever possible to do using raw css,['css'] +60405,what is the time complexity of linkedlistgetlast in java i have a private linkedlist in a java class will frequently need to retrieve the last element in the list the lists need to scale so i am trying to decide whether i need to keep a reference to the last element when i make changes to achieve o1 or if the linkedlist class does that already with the getlast callwhat is the bigo cost of linkedlistgetlast and is it documented ie can i rely on this answer or should i make no assumptions cache it even if it is o1,['java'] +60408,how to programmatically answer a call i know this has been asked before but at this time the answer of the post is not true vringo and other apps does answer the phone by pressing a button on their app so there must be a way to do itanyone has a suggestion,['android'] +60425,utf8 character encoding in java i am having some problems getting some french text to convert to utf8 so that it can be thisplayed properly either in a console text file or in a gui elementthe original string ishandicapaeswhich is supposed to be handicapaeshere is a code snippet that shows how i am using the jackcess database driver to read in the acess mdb file in an eclipselinux environmentdatabase database databaseopennew filefilepathtable table databasegettabletablename trueiterator rowiter tableiteratorwhile rowiterhasnext mapstring object row thisrowiternext convert fields to utf mapstring object rowutf new hashmapstring object try for string key rowkeyset object o rowgetkey if o null string valuecp850 otostring string nameutf8 new stringvaluecp850getbytescp850 utf8 does not work string valueiso new stringvaluecp850getbytescp850 iso88591 string valueutf8 new stringvalueisogetbytes utf8 works rowutfputkey valueutf8 catch unsupportedencodingexception e systemerrprintlnencoding exception e in the code youll see where i want to convert directly to utf8 which does not seem to work so i have to do a double conversion also note that there does not seem to be a way to specify the encoding type when using the jackcess driverthankscam,['java'] +60426,why does opera parse my web page as xml i just tried viewing my website in opera version 1050 it gives me an xml parsing failed error and refuses to thisplay the web page i can choose to reparse the document as html and then the page works fine but that is hardly a solution to my problemthe weird thing is that the error still occurs after setting a html instead of xthml doctypedoctype html public w3cdtd html 401 transitionalen i checked the source output from the browser to make sure i did not make any mistake with the doctype i even viewed the same web page in firebug and it shows a contenttype of texthtml so why does opera still try to parse my web page as xmlthanksadrianedit just to clarify i am not asking what the error on my web page is i understand why this is not valid xhtml however i am also using the javascript micro templating engine and it is templates are never valid xml which is why i need the browser to parse my entire web site as html not xhtml in order to demonstrate this i just inserted an example template into the web pagescript typetexthtml idstopwatchtemplate h1a href onclicktimeentrieslistedittimeentrytimeentryidcurrentlyrunningaktuellerletzter stoppuhrzeiteintragah1 stoppuhr endescriptwhen opening the page in opera you can see that the template now produces xml parsing errors even though the doctype for the page is still htmledit 2 just to make this even clearer i am not asking why my web page is not valid xhtml i am asking why opera tries to parse it as xhtml despite the html doctypeedit3 please do not post any more answers i have found the cause of this and documented it below,['html'] +60435,is there a srcjar in osx in windows there is was a srcjar file that contains the java source files of the java platform is there something similar for java 16 in osx i would like to specify this to my ide so i can navigate to that source,['java'] +60438,generating javadoc comments for existing code in eclipse i know it is possible to generate comments for classes interface etc in the wizard screen when creating them but i have not found an option to generate javadoc comments for an existing file is it possiblethanks,['java'] +60441,how does my aspnet app get the smtp settings automatically from webconfig i noticed that we always just are likesmtpclient msmtpclient new smtpclient send the mail messagemsmtpclientsendmmailmessageand the only place the credentials are set are in webconfig systemnet mailsettings smtp network hostx229 usernamex passwordx smtp mailsettings systemnetso my question is how does it automagically get them out,"['c#', 'asp.net']" +60442,how do i write a java ejb singleton a day ago my application was one ear containing one war one ejb jar and a couple of utility jar files i had a pojo singleton class in one of those utility files it worked and all was well with the worldear war ejb jar util 1 jar util 2 jar etcthen i created a second war and found out the hard way that each war has its own classloader so each war sees a different singleton and things break down from there this is not so goodear war 1 war 2 ejb jar util 1 jar util 2 jar etcso i am looking for a way to create a java singleton object that will work across wars across classloaders the singleton ejb annotation seemed pretty promising until i found that jboss 51 does not seem to support that annotation which was added as part of ejb 31 did i miss something can i use singleton with jboss 51 upgrading to jboss as 6 is not an option right nowalternately i would be just as happy to not have to use ejb to implement my singleton what else can i do to solve this problem basically i need a semiapplicationwide hook into a whole bunch of other objects like various cached data and app config info as a last resort i have already considered merging my two wars into one but that would be pretty hellishmeaning available basically anywhere above a certain layer for now mostly in my wars the view and controller in a loose senseedit i should really be calling it java ee rather than j2ee should not iedit 2 many thanks again to yishai for all the help after some trialanderror it looks like i have figured out how to use a single classloader across wars under jboss 5 i am detailing this below for my own sake and hopefully others will find this useful as wellnb this is rather different from doing this under jboss 4 see yishais answer or my links belowinstead of writing a jbosswebxml for each war and a jbossxml for ear ejbjar put a jbossclassloadingxml file in each war in the same location as the dd webxml the contents of jbossclassloadingxml should bexml version10 encodingutf8classloading xmlnsurnjbossclassloading10 namemywarwar domaindefaultdomain parentdomainignored exportallnon empty importalltrueclassloadingthis follows from the jboss cw here whereas what i think works for jboss 4x is described here more general info on jboss classloadingersoverviewhistoryuse casesas best i can tell the jboss community wiki docs are pretty lacking for jboss 5 in comparison to jboss 4,['java'] +60448,how do you use selenium to execute javascript within a frame i have a page indexhtml which has a framehtmlbodyiframe srcotherpagehtml bodyhtmland the otherpagehtml has the contentshtmlheadlink srcjqueryminjs typetextjavascript headbodydiv idmaincontentsdivbodyhtmli am attempting to use the following selenium code on indexhtmlseleniumopenindexhtmlseleniumselectframeiframeseleniumgetevalwindowjquerydividmainhowever this fails miserably it says that the jquery object does not exist if i attempt to execute the selenium test on the otherpage like soseleniumopenotherpagehtmlseleniumgetevalwindowjquerydividmaineverything is hunky doryright now this is pseudo code if people want me to make it compile i will do that and put it on github,"['java', 'javascript']" +60451,possible to set broadcastreceiver priority programmatically is it possible to set the priority attribute of a broadcastreceiver programmatically or can it only be done in xmlrelevant documents includeit does not seem so but i do not fully understand the relationship of androidrstyleable to a given application and its activities,['android'] +60452,google app engine python download file i am trying to figure out a way where i can create a tabdelimited file containing data from userdefined fields and allow the user to download that file on google app enginethe sandbox environment that the app runs in does not allow the application to write to thisk is there another way where i can create a downloadable file,['python'] +60453,where should i store my application data i have an application that needs to store data currently i am using the builtin application settings to do it but it only gives me two choices application and user scopes ideally i want a local scope that allows the application to run under another user and still find its data rather than recreate it for that user the application scope can do this but it is read only the application data will be changed by the user it is ok if only the administrator is allowed to make changes to the data as you probably can guess i have an administration tool that allows the user to change the data and windows service runner that reads the data and does something with it it would be great if the windows service runner access the data created by the administration tool,['.net'] +60472,how to make a private property i tried to make a private property in my m fileinterface myclass privateproperty nonatomic retain nsmutablearray stuffendimplementation myclasynthesize stuff not okcompiler claims that there is no stuff property declared but there is a stuff just in an anonymous category let me guess impossible other solutions,['objective-c'] +60479,how to combine two 32bit integers into one 64bit integer i have a count register which is made up of two 32bit unsigned integers one for the higher 32 bits of the value most significant word and other for the lower 32 bits of the value least significant wordwhat is the best way in c to combine these two 32bit unsigned integers and then thisplay as a large numberin specificleastsignificantword 4294967295 2321printfcounter uu mostsignificantwordleastsignificantwordthis would print finewhen the number is incremented to 4294967296 i have it so the leastsignificantword wipes to 0 and mostsignificantword 0 initially is now 1 the whole counter should now read 4294967296 but right now it just reads 10 because i am just concatenating 1 from mostsignificantword and 0 from leastsignificantword how should i make it thisplay 4294967296 instead of 10,['c'] +60481,request for the permission of type systemwebaspnethostingpermission failed when compiling web site on a network share or intranet project i have been using windows 7 for a while but have not had to work with a particular legacy intranet application since my upgrade unfortunately this application is setup as an aspnet website project hosted on an intranet server when i have the website open in visual studio 2008 and try to debug it i receive the following compiler errorrequest for the permission of type systemwebaspnethostingpermission failed to resolve this issue on windows vista machines i would change the machines net security configuration trust level to full for the local intranet fix outlined here i believe this configuration utility relied upon the mscorcfgmsc which from some cursory research appears to be apart of the net 20 sdk i have tried to follow the instructions from this microsoft support article running the command below to no availdrivewindowsmicrosoftnetframeworkv2050727caspolexe m ag 1 urlfilecomputernamesharename fulltrust exclusive onpresently i have the following net aspnet and net sdk components installed on my machinemicrosoft net compact framework 20 sp2microsoft net compact framework 35microsoft net framework 4 client profilemicrosoft net framework 4 extendedmicrosoft net framework 4 multitargeting packmicrosoft aspnet mvc 10microsoft aspnet mvc 2microsoft aspnet mvc 2 visual studio 2008 toolsmicrosoft aspnet mvc 2 visual studio 2010 toolsmicrosoft windows sdk for visual studio 2008 net framework tools enumicrosoft windows sdk for visual studio 2008 headers and librariesmicrosoft windows sdk for visual studio 2008 sdk reference assemblies and intellisensemicrosoft windows sdk for visual studio 2008 sp1 toolsmicrosoft windows sdk for visual studio 2008 sp1 win32 toolsmicrosoft windows sdk for windows server 2008 6001180367do i need to install the net 20 sdk am i issuing the caspol command incorrectly is there something else that i am missing,"['.net', 'asp.net']" +60482,how to encode custom http headers in c is there a class similar to httputility to encode the content of a custom header ideally i would like to keep the content readable,"['c#', '.net']" +60483,how to quickly search an array of objects in objectivec is there a way in objectivec to search an array of objects by the contained objects properties if the properties are of type stringfor instance i have an nsarray of person objects person has two properties nsstring firstname and nsstring lastnamewhats the best way to search through the array to find everyone who matches ken anywhere in the firstname or lastname properties,['objective-c'] +60520,round an integer to the nearest int that is lower than or equal to it and a multiple of 64 given an integer x how would you return an integer y that is lower than or equal to x and a multiple of 64,['c'] +60527,ipad simulator rotating i am testing an application on ipad simulator and i need it to start my app in the position the simulator is but every time i run the app the simulator rotates to portraitis there a way to stop this behavior thanks last time edit i thiscovered now that if i return no on shouldautorotatetointerfaceorientation the problem stops but this is insane because shouldautorotatetointerfaceorientation should rotate the interface to match the ipad position not the contrary,['iphone'] +60533,ruby less gem equivalent in python the ruby less gem looks awesome and i am working on a pythonpylons web project where it would be highly useful css is as someone were all familiar with recently wrote about clunky in some important ways so i would like to make it easier on myselfis there an existing python module or library that provides parallel functionality,"['python', 'css', 'ruby']" +60535,mysql select the last inserted row easiest way i simply need to select the last entered row specified by condition egselect id from bugs where usermei need to return only the very last id entered by user me is there a simple way to do this thank you,['mysql'] +60536,pdofetchall vs pdofetch in a loop just a quick questionis there any performance difference between using pdofetchall and pdofetch in a loop for large result setsi am fetching into objects of a userdefined class if that makes any differencemy initial uneducated assumption was that fetchall might be faster because pdo can perform multiple operations in one statement while mysql query can only execute one however i have little knowledge of pdos inner workings and the documentation does not say anything about this and whether or not fetchall is simply a phpside loop dumped into an arrayany help,"['php', 'mysql']" +60538,multiple models in a single django modelform is it possible to have multiple models included in a single modelform in django i am trying to create a profile edit form so i need to include some fields from the user model and the userprofile model currently i am using 2 forms like thisclass usereditformmodelform class meta model user fields first name last nameclass userprofileformmodelform class meta model userprofile fields middle name home phone work phone cell phoneis there a way to consolidate these into one form or do i just need to create a form and handle the db loading and saving myself,['python'] +60541,how to orderby on a generic ienumerable ienumerable using linq in c in my generic repository i have below methodpublic virtual ienumerablet getallt where t class using var ctx new datacontext var table ctxgettablettolist return table t is a linq to sql class and i want to be able to orderby on a particular property ie int sortorder say if t has property name sortorder then do orderby on this property but i am not sure how i can achieve this so i need some helps thank you i feel like dynamic languages really shines in doing this kind of jobsquote from scottguwhile writing typesafe queries is great for most scenarios there are cases where you want the flexibility to dynamically construct queries on the flyand this is exactly the problem i am facing and i am wondering if this linq dynamic helper can be made into official net library,['c#'] +60545,read resources from a dll file i have two visual basic 2008 projects one is a class library project and another is a windows forms project in the class library project i have defined some strings in the project resources project properties resources tabi build that class library project and get the dll file from the debug folder and added up as a reference in my windows forms project how do i read those strings from the referenced dll file,['c#'] +60570,download content of the page using ajax jquery greetings how can i download some page content using ajax and jqueryi am doing something like that 2 versions inside one scriptpclickfunction resultload ajax urlwgooglecom success functiondata resulthtmldata alertload was performed var url wppl divresultloadurl var content loadurl alertcontent resulthtmltest but it does not return any content,['jquery'] +60571,unit testing am i doing it right basically i have been programing for a little while and after finishing my last project can fully understand how much easier it would have been if i would have done tdd i guess i am still not doing it strictly as i am still writing code then writing a test for it i do not quite get how the test becomes before the code if you do not know what structures and how your storing data etc but anywaykind of hard to explain but basically lets say for example i have a fruit objects with properties like id color and cost all stored in textfile ignore completely any database logic etc fruitid fruitname fruitcolor fruitcost 1 apple red 12 2 apple green 14 3 apple halfhalf 15this is all just for example but lets say i have this is a collection of fruit it is a listfruit objects in this structure and my logic will say to reorder the fruitids in the collection if a fruit is deleted this is just how the solution needs to beeg if 1 is deleted object 2 takes fruit id 1 object 3 takes fruit id2now i want to test the code ive written which does the reordering etchow can i set this up to do the testhere is where i have got so far basically i have fruitmanager class with all the methods like deletefruit etc it has the list usually but ive changed hte method to test it so that it accepts a list and the info on the fruit to delete then returns the list unittesting wise am i basically doing this the right way or have i got the wrong idea and then i test deleting different valued objects datasets to ensure method is working properlytestpublic void deletefruit var fruitlist createfruitlist var fm new fruitmanager var resultlist fmdeletefruittestapple 2 fruitlist assert that fruitobject with x properties is not in list howprivate static listfruit createfruitlist build test data var f01 new fruit name appleid 1 etc var f02 new fruit name appleid 2 etc var f03 new fruit name appleid 3 etc var fruitlist new listfruit f01 f02 f03 return fruitlist,['c#'] +60573,why is my begininvoke method not async in order to avoid freezing of gui i wanted to run method connecting to db asynchronously therefore i have written thisdelegatloginu dl connectdb iasyncresult ardlbegininvokenull null bool result booldlendinvokearbut it is still freezing and i do not understand why i though begininvoke assures that method it references is run in another thread thank you,['c#'] +60582,map operator operands hi all i have the following in a member functionint tt 6 vectorsetint temp m egresscandidatesbydestandotmodett setint egresscandidatestops tempatdestand the following declaration of a member variable mapint vectorsetint m egresscandidatesbydestandotmodehowever i get an error when compiling intel compiler 1101cprojectssvnbdksourcezenithassignmentsrciterationptbranchandbounditerationoriginrunnercpp85 error no operator matches these operands1 operand types are const stdmapint stdvectorstdsetint stdlessint stdallocatorint stdallocatorstdsetint stdlessint stdallocatorint stdlessint stdallocatorstdpairconst int stdvectorstdsetint stdlessint stdallocatorint stdallocatorstdsetint stdlessint stdallocatorint const int 1 vectorsetint temp m egresscandidatesbydestandotmodett 1 i know it is got to be something silly but i cannot see what i have done wrong update i am calling this from a const member function which is why the member variables type is const so i thought that something like the following should fix it int dest 0 tt 6 const setint egresscandidatestops m egresscandidatesbydestandotmodettatdest but no dice still the same error,['c++'] +60589,how does php interface with apache i have almost finished writing a http10 compliant web server under java no commercial usage as such this is just for fun and basically i want to include php support i realize that this is no easy task at all but i think it will be a nice accomplishmentso i want to know how php exactly interfaces with the apache web server or any other web server really so i can learn from it and write my own php wrapper it does not necessarily have to be mod php i do not mind writing a fastcgi wrapper which to my knowledge is capable of running php as welli wouldve thought that all that php needs is the output that goes to client so it can interpret the php parts the full http request from client so it can extract post variables and such and the clients host name and then you simply take the parsed php code and write that to the output stream there will probably be more things but in essence that is how i would have thought it worksfrom what i have gathered so far apache2handler provides an api which php makes use of to connect to apache i guess it is an idea to look at the source code for apache2handler and php5apache2dll or so but before i do that i thought i would ask so firstif anyone has more information experience or some sort of specification that is relevant to this then please let me knowthanks in advance,['php'] +60590,how to introduce multicolumn constraint with jpa annotations i am trying to introduce a multikey constraint on a jpamapped entitypublic class inventoryitem id private long id version private long version manytoone joincolumnproductid private product product columnnullablefalse private long serialbasically product serial pair should be unique but i only found a way to say that serial should be unique this obviously is not a good idea since different products might have same serial numbers is there a way to generate this constraint via jpa or am i forced to manually create it to db,['java'] +60601,programmatically sync the db in django i am trying to sync my db from a view something like thisfrom django import httpfrom djangocore import managementdef syncdbrequest managementcall commandsyncdb return httphttpresponsedatabase syncedthe issue is it will block the dev server by asking for user input from the terminal how can i pass it the noinput option to prevent asking me anythingi have other ways of marking users as superuser so there is no need for the user input but i really need to call syncdb and flush programmatically without logging on to the server via ssh any help is appreciated,['python'] +60609,can i add an alphabet jump list to a tableview like the contact list i would like to create a custom contact list in my app offering a similar az jump list like the standard contact list doesis this possible with a tableview,['iphone'] +60612,vbnet how to prevent user input in a combobox how do you prevent user input in a combobox so that only one of the items in the defined list can be selected by the user,['.net'] +60618,can i do android programming in c c can i do android programming in c c if the answer is yes then please tell how and whats the procedure to set upi do not know objc java but wellversed in c c flash as3 sdk released by googleplease do not tell about nvdia sdk it is not fully developed,"['c++', 'android']" +60622,why do arrays in net only implement ienumerable and not ienumerable i was implementing my own arraylist class and was left surprised when i realised thatpublic systemcollectionsgenericienumeratort getenumerator return arraygetenumeratordid not work what is the reason arrays do not implement ienumerator in netis there any workaroundthanks,"['c#', '.net']" +60632,increase the tcp receive window for a specific socket how to increase the tcp receive window for a specific socket i know how to do so for all the sockets by setting the registry key tcpwindowsize but how do do that for a specific oneaccording to msfts documents the way is calling the windows sockets function setsockopt which sets the receive window on a persocket basisbut in setsockopt it is mentioned about so rcvbuf specifies the total persocket buffer space reserved for receives this is unrelated to so max msg size and does not necessarily correspond to the size of the tcp receive windowso is it possible howthanks,['c++'] +60634,parallelfor update variable outside of loop i am just looking in to the new net 40 features with that i am attempting a simple calculation using parallelfor and a normal forx loop however i am getting different results about 50 of the time long sum 0parallelfor1 10 y sum y consolewritelinesumtostringsum 0for int y 1 y 10 y sum yconsolewritelinesumtostringmy guess is that the threads are trying to update sum at the same timeis there an obvious way around it,"['c#', '.net']" +60635,how to thisplay the uiactionsheet view from above tab bar controller i need to thisplay the action sheet above the tab bar controller i mean i would be able to see the tab bar controller even the action sheet view is in visible modeso please suggest how to view from above the tab bar controller is it possiblesecondly how to change the back ground color of action sheet and cancel button back ground colourplease help me thank youmadan mohan,"['iphone', 'objective-c']" +60636,how to know if a string contains accents how to know if a string contains accents,['java'] +60637,how do i install the gson module in java i downloaded the google json module aka gson i am ona windows system could you tell me how to install the gson module i extracted the jar into the following folder which was in my classpathcprogram filesjavajdk160 07libbut when i typeimport comgooglegsongsonimport comgooglegsongsonbuilderi still get a module not found errorwhat am i doing wrongthanks,['java'] +60654,how do i use macros for the command line arguments for debugging a net project in the visual studio debug property page for a net 4 project i want to be able to specify macros eg outdir like i can in the build events but it does not work the macros are not replacedis it just not supported is there a work around,['.net'] +60657,jquery sortable stange mouse offset i am working with the jquery sortable plugin 2 connected lists and have a strange bug when you drag the picture the mouse is above the dragged item screenshot html for one of the lists ul classflickr key ul uisortable liimg stylethisplay inline src a8816f42f5 sjpg altup the ginnel titleup the ginnel classflickr imageli liimg stylethisplay inline src 7e625a461b sjpg altdown the ginnel titledown the ginnel classflickr imageli liimg stylethisplay inline src 75f2c0bd0e sjpg altentering the ginnel titleentering the ginnel classflickr imageli liimg stylethisplay inline src 6023b070a7 sjpg altup bachelor lane titleup bachelor lane classflickr imageli liimg stylethisplay inline src 3116d900ce sjpg altdown bachelor lane titledown bachelor lane classflickr imageli liimg stylethisplay none src 0a32a6492a sjpg altflower titleflower classflickr imageli liimg stylethisplay none src e37de6bcc0 sjpg altsteps titlesteps classflickr imageli liimg stylethisplay none src 23a4909300 sjpg althopwood bridle way titlehopwood bridle way classflickr imageli liimg stylethisplay none src beaf20476b sjpg altcat sleeping titlecat sleeping classflickr imageli liimg stylethisplay none src af19a5dac2 sjpg altroad cones hiding titleroad cones hiding classflickr imageli ulsortable configuration horizontal helper clone instead of dragging the real image a copy will be dragged connectwith flickr sidebar ul to be able to drag and drop an image to another image gallery they need to be connected cursor pointer change the cursor when dragging appendto body when dropped the images need to be appended to the image gallery where they are dropped containment rootel make sure the user cannot drag the images outside the widget revert true if the user releases the image ouside the dropbox it will return to it is original position zindex 9 anyone know how to get the mouse in the middle or something cursorat does not work,['jquery'] +60662,visual studio 2010 remote debugging is very slow across domains over vpn overall debugging works but each step through code takes dosens of seconds i have already closed all additional windows like stack tracewatchesautos deleted all breakpointsserver and dev machine are located in different domains so i set up local user on both with matching password remote debugger is running as servicelooking at security log i found quite a lot of entries about remote debugging account logging in record about every minuteany suggestions on how i can speed up remote debuggingdev computer quad core 8 gb mem win 7 x64 visual studio 2010 ultimatetarget server aspnet website 2xdual core xeon 2gb mem remote debugger 2010communication channel vpn 5 mbit latency about 20ms seems that debbugging never uses more than 20 kbs,['asp.net'] +60667,xcode unit testing accessing resources from the applications bundle i am running into an issue and i wanted to confirm that i am doing things the correct wayi can test simple things with my sentestingkit tests and that works okay i have set up a unit test bundle and set it as a dependency on the main application target it successfully runs all tests whenever i press cmdbheres where i am running into issues i have some xml files that i need to load from the resources folder as part of the application being a good unit tester i want to write unit tests around this to make sure that they are loading properlyso i have some code that looks like thisnsstring filepath nsbundle mainbundle pathforresourcefoo oftypexmlthis works when the application runs but during a unit test mainbundle points to the wrong bundle so this line of code returns nilso i changed it up to utilize a known class like this nsstring filepath nsbundle bundleforclassconfig class pathforresourcefoo oftypexmlthis does not work either because in order for the test to even compile code like this it config needs to be part of the unit test target if i add that then the bundle for that class becomes the unit test bundle ugham i approaching this the wrong way,"['iphone', 'objective-c']" +60676,unit testing with data access layer what is a good way to write unit tests with a linq to sql dalcurrently i am doing some database testing and need to create helper methods that access the database but i do not want those methods in my main repos so what i have is two copies of the dal one in my main project and one in the test project is it easier to manage these things if i create a separate project for the data layer i am not sure which way is a better way to approach thisif i do create a data layer project would i move all my repos to that project as well i am not sure how to properly setup the layersthanks,['c#'] +60677,how to pass model from a view to a partial view i have a view that is not strongly typed however i have in this view a partial view that is strongly typedhow do i do i pass the model to this strongly typed viewi tried something like public actionresult test mydata new data mydataone 1 return viewtestmydata in my testview htmlrenderpartialpartialviewmodel this give me a stackoverflow exception so i am not sure how to pass it on of course i do not want to make the test view strongly typed if possible as what happens if i had like 10 strongly typed partial views in that view i would need like some sort of wrapper,"['c#', '.net', 'asp.net']" +60688,is devise compatible with declarative authorization just asking whenever devise authentication mechanism for rails does not conflict with declarative authorizationmaybe someone tried this combo and can share their knowledge so i and other coders do not waste time trying to tie these ones up,['ruby-on-rails'] +60693,biginteger or not biginteger in java most of the primitive types are signed one bit is used to represent the and therefore when i exceed the limits of the type i can get unexpected results like negative numbersis there any better solution than using biginteger for this since biginteger has performance issues and you need to use the class methods for basic arithmetic instead of the language operators ruins readability,['java'] +60705,android moving back to first activity on button click i am writing a application where i am dealing with 4 activities let us say a b c d activity a invokes b b invokes c c invokes d on each of the activity i have a button called home button when user clicks on home button in any of the b c d activities application should go back to a activity screen how to simulate home button in this case,['android'] +60708,outputstream is not available when a custom textwriter is used this is my function which converts pdf to png image it is throwing an error onthis line streamwritetoresponseoutputstream is there some thing wrongprotected void createpngfrompdf try string pdflocation stringformatx012pdf yr locsubstring0 4 locsubstring4 4 utilitieswebpdfpdf webpdf new docuvaultmvcutilitieswebpdfpdf webpdfcredentials new networkcredentialxyz xyz byte png webpdfstreampdfpageaspngresizepdflocationpagenumber 612 792 memorystream ms new memorystreampng memorystream stream new memorystream int newwidth 612 int newheight 792 systemdrawingimage newimg systemdrawingimagefromstreamms bitmap temp new bitmapnewwidth newheight newimgpixelformat graphics newimage graphicsfromimagetemp newimagedrawimagenewimg 0 0 newwidth newheight newimgthispose tempsavestream imageformatpng streamwritetoresponseoutputstream tempthispose streamthispose catch exception ex responsewriteexmessagetostring,"['c#', 'asp.net']" +60714,loading js files and other dependent js files asynchronously i am looking for a clean way to asynchronously load the following types of javascript files a core js file hmm let us just call it oh i do not know jquery haha x number of js files that are dependent on the core js file being loaded and y number of other unrelated js files i have a couple ideas of how to go about it but not sure what the best way is i would like to avoid loading scripts in the document bodyso for example i want the following 4 javascript files to load asynchronously appropriately namedjsmycontactpagejsfunctionsjs unrelatedindependent scriptjsjquery132minjs the core scriptjsjquerycolorminjs dependent on jquery being loaded another unrelatedindependent scriptbut this would not work because it is not guaranteed that jquery is loaded before the color plugin function var a jsmycontactpagefunctionsjs jsjquery142minjs jsjquerycolorjs ddocument hdgetelementsbytagnamehead0 s i lalength fori0ili sdcreateelementscript stypetextjavascript sasynctrue ssrcai happendchilds is it pretty much not possible to load jquery and the color plugin asynchronously since the color plugin requires that jquery is loaded firstthe first method i was considering is to just combine the color plugin script with jquery source into one filethen another idea i had was loading the color plugin like sowindowreadyfunction getscriptjsjquerycolorjsanyone have any thoughts on how youd go about this thanks,"['javascript', 'jquery']" +60733,howto ignore specific undefined variables in pydev eclipse i am writing a crossplatform python script on windows using eclipse with the pydev plugin the script makes use of the ossymlink and osreadlink methods if the current platform is not nt since the ossymlink and osreadlink methods are not available on the windows platform pydev flags them as undefined variableslike so questionis there a way to ignore specific undefined variable name errors without modifying my source file edit i found a way to ignore undefined variable errors from this answer on stackoverflowi will leave the question open in case there is a way to solve this using project file or pydev setting,['python'] +60739,change innerhtml of a php domelement how to change innerhtml of a php domelement,['php'] +60761,socketerror errno 10013 an attempt was made to access a socket in a way forbidden by its access permissions i am trying to create a custom tcp stack using python 265 on windows 7 to serve valid http page requests on port 80 locally but i have run into a snag with what seems like windows 7 tightened up security this code worked on vistaheres my sample codeimport socketserverimport structclass mytcphandlersocketserverbaserequesthandler def handleself headertext http10 200 ok date fri 31 dec 19 235959 gmt contenttype texthtml contentlength 1354 bodytext htmlbodysome pagebodyhtml selfrequestsendheadertext n bodytextif name main host port localhost 80 server socketservertcpserverhost port mytcphandler serverserve forevercpythonpython testserverpy traceback most recent call last file testserverpy line 19 in server socketservertcpserverhost port mytcphandler file cpython26libsocketserverpy line 400 in init selfserver bind file cpython26libsocketserverpy line 411 in server bind selfsocketbindselfserver address file line 1 in bindsocketerror errno 10013 an attempt was made to access a socket in a way forbidden by its access permissionshow exactly do i get this to work on windows 7edit on 552010 2344 pdt this answer explains that the error is caused by the need for elevated superuser privileges when accessing ports lower than 1024 i am going to try using a higher port number to see if that works however i still would like to know why my local admin account cannot access port 80,['python'] +60770,does c compile code inside an iffalse block i am just wondering if these code blocks gets compiled into dlli do not think this one gets compiled at allif something undefined some code this is ignored by the compilerendifnow what about these1iffalse some code is this compiled2const bool f falseiff some code is this compiled3bool f falseiff some code is this compilededit sorry i was talking about visual studio,"['c#', '.net']" +60772,how to get selected row index in jsf datatable i have a databale on indexxhtmlhdatatable styleborder solid 2px black valueindexbeanbooklist varitem bindingindexbeandatatablebooks hcolumn hcommandbutton valueedit actionlistenerindexbeaneditbook fparam nameindex valueindexbeandatatablebooksrowindex hcommandbutton hcolumnhdatatablemy beanmanagedbeannameindexbeanviewscopedpublic class indexbean implements serializable private htmldatatable datatablebooks public htmldatatable getdatatablebooks return datatablebooks public void setdatatablebookshtmldatatable datatablebooks thisdatatablebooks datatablebooks public void editbook throws ioexception int index integerparseintfacescontextgetcurrentinstancegetexternalcontextgetrequestparametermapgetindextostring systemoutprintlnindex my problem is that i always get the same index in server log even though i click the different edit buttons imagine that there is one collection which is supplied to the datatable i have not shown that in beanif i change scope from viewscope to requestscope it works fine what can be the problem with viewscoped thanks in advance edithcolumn hcommandbutton valueedit actionlistenerindexbeaneditbook hcolumnpublic void editbookactionevent ev throws ioexception if evgetsource null evgetsource instanceof htmldatatable htmldatatable objhtmldatatable htmldatatable evgetsource systemoutprintlnobjhtmldatatablegetrowindex,['java'] +60780,how did it happen that static denotes a functionvariable without external linkage in c and c in c static can mean either a local variable or a global functionvariable without external linkage in c it can also mean a perclass member variable or member functionis there any reference to how it happened that the static keyword that seems totally irrelevant to lack of external linkage is used to denote lack of external linkage,"['c++', 'c']" +60782,get raw html of node in jquery i have used parenthtml to get the inner html of parent but how do i get the html of the parent itselfthe use case is i grab an input node like thisvar field inputi would like to be able to get the raw html of that node input typetext with something like fieldhtml but that returns empty is this possible,"['jquery', 'html']" +60790,jquery get elements by name hi there can i get code to get a list dropdown of elements in a form by nameand also rename them at the same timethanks,['jquery'] +60803,is there any limit on stack memory i was going through one of the threadsa program crashed becauseit had declared an array of 106 locally inside a functionreason being given was memory allocation failure on stack leads to crashwhen same array was declared globally it worked wellmemory on heap saved itnow for the moment let us supposestack grows downward and heap upwardswe havestackheapnow i believe that if there is failure in allocation on stackit must fail on heap tooso my question is is there any limit on stack sizecrossing the limit caused the program to crashor am i missing something,['c'] +60805,php what does mean in the following code from what does the symbol meanphpclass simpleclass invalid property declarations public var1 hello world public var2 eodhello worldeod public var3 12 public var4 selfmystaticmethod public var5 myvar valid property declarations public var6 myconstant public var7 arraytrue false this is allowed only in php 530 and later public var8 eodhello worldeod,['php'] +60822,sorting an array of objectivec objects so i have a custom class foo that has a number of membersinterface foo nsobject nsstring title bool taken nsdate datecreatedand in another class i have an nsmutablearray containing a list of these objects i would very much like to sort this array based on the datecreated property i understand i could write my own sorter for this iterate the array and rearrange based on the date but i was wondering if there was a proper objectivec way of achieving this some sort of sorting mechanism where i can provide the member variable to sort by would be great in c i used to overload the operators and this allowed me to sort by object but i have a funny feeling objectivec might offer a nicer alternativemany thanks,"['iphone', 'objective-c']" +60826,how to add support for resizing when using an undecorated jframe i would like to customize my titlebar minimize maximize and the closebutton so i used setundecoratedtrue on my jframe but i still want to be able to resize the window what is the best way to implement thati have a border on the rootpane and i could use mouselisteners on the border or the rootpane any recommendationsimport javaawtcolorimport javaxswingjframeimport javaxswingjmenuimport javaxswingjmenubarimport javaxswingjmenuitemimport javaxswingborderlineborderpublic class undecoratedframe extends jframe private lineborder border new linebordercolorblue2 private jmenubar menubar new jmenubar private jmenu menu new jmenufile private jmenuitem item new jmenuitemnothing public undecoratedframe menuadditem menubaraddmenu thissetjmenubarmenubar thissetundecoratedtrue thisgetrootpanesetborderborder thissetsize400340 thissetvisibletrue public static void mainstring args new undecoratedframe,['java'] +60835,editing code in visual studio 2008 in debug mode i am curious to know if there is a way to edit code in c vs 2008 right when it has hit a breakpoint and i am walking thru the code can i modify the code such as the value in a variable or if my stepthrough line is about to hit an if statement can i modify the if statementetcso far i have to stop running vs modify the code then hit f5 and wait till the breakpoint is hit againwhen the breakpoint hits and i am walking thru the code and i attempt to edit the code i get a message changes are not allowed when the debugger has been attached to an already running process of the code being debugged was optimized at build or run time,['c#'] +60839,missing status bar in visual studio note this question and answer is a full copy from kelly brownsbergers blog i do post it as a convenience to othersfrom time to time my status bar thisappears i used to believe this was due to a botched install or addin i recently upgraded to team system test edition and my status bar again thisappeared for the last few weeks iave been trying to figure out a time to do a full reinstall,['.net'] +60871,aspnet 35 password recovery control in an mvc app can i use the aspnet 35 password recovery control in an mvc application we need to provide password retrieval capability for our mvc app and i would like to use the password recovery control which only works with a web form app,['asp.net'] +60879,django test failing i am experiencing an error running django unit tests i have not experienced this before and have been googling it all afternooni am getting this error in terminal after running django managepy testerror database test unconvention could not be flushed possible reasons the database is not running or is not configured correctly at least one of the expected database tables does not exist the sql was invalidhint look at the output of djangoadminpy sqlflush that is the sql this command was not able to runthe full error 1146 table test unconventionmedia image does not existthe media images table is referenced when running djangoadminpy sqlflush and generates ok when i run django managepy syncdbthis is the image model which appears to be troublesomefrom djangodb import modelsfrom djangocontribcontenttypesmodels import contenttypefrom djangocontribcontenttypes import genericclass imagemodelsmodel local image modelsimagefieldupload touploadsymd height fieldheight width fieldwidth max length255 nulltrue blanktrue remote image modelscharfieldeditablefalse max length255 nulltrue blanktrue thirdparty page modelscharfieldeditablefalse max length255 blanktrue nulltrue size modelscharfieldeditablefalse max length25 blanktrue nulltrue content type modelsforeignkeycontenttype object id modelspositiveintegerfield content object genericgenericforeignkeycontent type object id height modelspositiveintegerfieldeditablefalse blanktrue nulltrue width modelspositiveintegerfieldeditablefalse blanktrue nulltrue created at modelsdatetimefieldeditablefalse auto now addtrue updated at modelsdatetimefieldeditablefalse auto nowtrue def unicode self if selflocal image return selflocal imagename else return selfremote imagei appreciate any help please let me know if i should provide more information,"['python', 'mysql']" +60887,mysql how to copy rows but change a few fields i have a large number of rows that i would like to copy but i need to change one fieldi can select the rows that i want to copyselect from table where event id 120now i want to copy all those rows and create new rows while setting the event id to 155 how can i accomplish this,"['sql', 'mysql']" +60895,why is use custom server option thisabled in visual studio 2010 i have dotnetnuke loaded in visual studio 2010 the use custom server option under start options is thisabled why is it thisabled what does use default web server default to how do i change what the default isin earlier versions of vs i was able to switch between iis and the internal web server cassini now it is more confusing in vs 2010would the project type web application project vs web site project affect the setting,['asp.net'] +60897,creating delegates with lambda expressions in f why doestype intdelegate delegate of int unittype listhelper static member applydelegate l int list d intdelegate l listiter fun x dinvoke xlisthelperapplydelegate 110 fun x printfn d xnot compile whentype intdelegate delegate of int unittype listhelper static member applydelegate l int list d intdelegate l listiter fun x dinvoke xlisthelperapplydelegate 110 fun x printfn d xdoesthe only difference that is that in the second one applydelegate takes its parameters as a tuplethis function takes too many arguments or is used in a context where a function is not expected,['.net'] +60907,javascriptjquery onhashchange event workaround until all browsers support the onhashchange event what is the best workaround for thisis there something for this in jquery or as a plugin,"['javascript', 'jquery']" +60923,javascript how do you sort an array on multiple columns i have a multidimensional array the primary array is an array of publicationidpublication nameownderidowner name what i am trying to do is sort the array by owner name and then by publication name i know in javascript you have arraysort into which you can put a custom function in my case i havefunction mysortfunctiona b var x a3tolowercase var y b3tolowercase return x y 1 x y 1 0this is fine for just sorting on the one column namely owner name but how do i modify it to sort on owner name then publication name,['javascript'] +60929,database mirroring witness server what is it for what is a witness server used for why use it,['sql'] +60934,how to send a simple string between two programs using pipes i tried searching on the net but there are hardly any resources a small example would sufficeediti mean two different c programs communicating with each other one program should send hi and the other should receive it something like that,['c'] +60941,forcedirected layout implementation in java i have been looking around for a java implementation of the forcedirected graph layout algorithm but got no fruits so far any help will be appreciated,['java'] +60948,at what point should you understand references i asked a question like this in an interview for a entry level programmervar instance1 new myobjectvalue hellovar instance2 instance1instance1value byeconsolewritelineinstance1valueconsolewritelineinstance2valuethe applicant responded with hello bye as the outputsome of my coworkers said that pointers are not that important anymore or that this question is not a real judge of abilityare they rightedit the point was made that myobject could have been a struct that is a good point however i did not post the full question i gave the interviewee the full question had a class that was clearly a class not a struct it can be found here,['c#'] +60959,file glob in c whats the c way of perls idiommy files globfiletxtforeach my file files process file,['c++'] +60964,optimizing iphone opengl es fill rate i have an open gl es game on the iphone my framerate is pretty sucky 20fps using the xcode opengl es performance tool on an iphone 3g it showsrenderer utilization 95 to 99tiler utilization 27i am drawing a lot of pretty large images with a lot of blending if i reduce the number of images drawn framerates go from 20 to 40 though the performance tool results stay about the same renderer still maxed i think i am being limited by the fill rate of the iphone 3g but i am not suremy questions are how can i determine with more granularity where the bottleneck is that is my biggest problem i just do not know what is taking all the time if it is fillrate is there anything i do to improve it besides just drawing lessi am using texture atlases i have tried to minimize image binds though it is not always possible drawing order not everything fits on one 1024x1024 texture etc every frame i do 10 image binds this seem pretty reasonable but i could be mistakeni am using vertex arrays and gldrawarrays i do not really have a lot of geometry i can try to be more precise if needed each image is 2 triangles and i try to batch things were possible though often maybe half the time images are drawn with individual gldrawarrays calls besides the images i have 60 triangles worth of geometry being rendered in 6 gldrawarrays calls i often gltranslate before calling gldrawarrayswould it improve the framerate to switch to vbos i do not think it is a huge amount of geometry but maybe it is faster for other reasonsare there certain things to watch out for that could reduce performance eg should i avoid gltranslate glcolor4g etci am using glscissor in a 3 places per frame each use consists of 2 glscissor calls one to set it up and one to reset it to what it was i do not know if there is much of a performance impact hereif i used pvrtc would it be able to render faster currently all my images are gl rgba i do not have memory issuesone of my fullscreen textures is 256x256 would it be better to use 480x320 so the phone does not have to do any scaling are there any other general performance advice for texture sizeshere is a rough idea of what i am drawing in this order1 switch to perspective matrix2 draw a full screen background image3 draw a full screen image with translucency this one has a scrolling texture4 draw a few sprites5 switch to ortho matrix6 draw a few sprites7 switch to perspective matrix8 draw sprites and some other textured geometry9 switch to ortho matrix10 draw a few sprites eg game hudsteps 16 draw a bunch of background stuff 8 draws most of the game content 10 draws the hudas you can see there are many layers some of them full screen and some of the sprites are pretty large 14 of the screen the layers use translucency so i have to draw them in backtofront order this is further complicated by needing to draw various layers in ortho and others in perspectivei will gladly provide additional information if reqested thanks in advance for any performance tips or general advice on my problemediti added some logging to see how many gldrawarrays calls i am doing and with how much data i do about 20 gldrawarray calls per frame usually about 1 to up to 6 of these has about 40 vertices each the rest of the calls are usually just 2 vertices one image i am just using glvertexpointer and gltexcoordpointer,['iphone'] +60965,best way to get an application context into a static method in android i am working on an android application that has several activities in it i have a class with several static methods i would like to be able to call these methods from the different activities i am using the static methods to load data from an xml file via a xmlresourceparser to create a xmlresourceparser requires a call on the application context so my question is what is the best way to get a reference to the application context into the static methods have each activity get it and pass it in store it somehow in a global variable,['android'] +60984,question about pure methods is the following method pure i would say so as it does not change in anyway the current class thus everything we can now currenly see in the class before running this method will still be exactly the same after am i correctclass set public isett unionwithisett set isett unionset foreach element element in this unionsetaddelement foreach element element in set unionsetaddelement return unionset,['c#'] +60993,aspnet outputcache varybyparam and varybyheader with ajax i am trying to do some caching using varybyparam and varybyheader when an ajax request comes in i return a partial xhtml when a regular request comes in i send the partial xhtml page with header footeri tried to cache the page by doingoutputcache duration 5 varybyparam nicknamepage varybyheader xrequestedwith however this does not work if i do a regular request first then run the ajax call i get the full cached page instead of the partial and viceversa seems like varybyheader is being ignored is it because xrequestedwith is omitted on normal requests or perhaps it is doing varybyparam or varybyheadermy obvious way around this is for ajax requests to call a different method which only returns partial pages however i would like to avoid that if possiblei am using aspnet mvc 10 with the outputcacheattribute,['asp.net'] +60994,android service ping url how can i use android service to do a ping callback i need to open a webpage on a button click but in the background go ping another url for stats collection code snippets will be greatly helpfulthankschris,['android'] +60999,does visual studio run tests with a less privileged process i have an application that is supposed to read from the registry and when executing a console application my registry access works perfectlyhowever when i move it over to a test this returns nullvar masterkey registrylocalmachineopensubkeypath to my keyso my question isdoes visual studio run tests with a less privileged processi tested to see what user this gave me var x windowsidentitygetcurrentname and it gives me the same as in the console application so i am a bit confused herei am using ms test framework and the machine is windows 2003 64 bit,['c#'] +61003,jqueryajax success callback function not executed i have a javascript ajax call jqueryajax that does not execute the success callback function ajax url target contenttype applicationjson charsetutf8 type post type get datatype jsonp error function xhr status alertstatus success function result alertcallback done griddatabindresultresults griddatabindresult i see in firebug that the request is posted and the correct result in terms of the json is returned as expected what is wrong,"['javascript', 'jquery']" +61007,how to reduce the space between tags i have a page that i am converting to pdf this page contains a number of paragraphs and they do not all fit onto a single page if i could reduce the spacing between the p tags this would help fit more is this possible thanks,"['html', 'css']" +61018,guaranteeing the onmouseout event to fire i am currently developing a web application and have run into a little problem i am using extjs but i believe this to be a general js questionwhen the cursor enters an html element the onmouseover event is fired when the cursor leaves that element onmouseout is triggered so far so good unfortunately it seems one cannot fully rely on this behaviour very quick mouse movements can cause the event not to fire as does repositioning the cursor with a pen tablet for examplewhat are the best practices to handle these issues do i need to monitor all onmousemove events and manually keep track of where the cursor was last and fire the appropriate onmouseout event myself,['javascript'] +61021,why does mysql autoincrement increase on failed inserts a coworker just made me aware of a very strange mysql behaviorassuming you have a table with an auto increment field and another field that is set to unique eg a usernamefield when trying to insert a row with a username thats already in the table the insert fails as expected yet the auto increment value is increased as can be seen when you insert a valid new entry after several failed attemptsfor example when our last entry looks like thisid 10username mynameand we try five new entries with the same username value on our next insert we will have created a new row like soid 16username mynewnamewhile this is not a big problem in itself it seems like a very silly attack vector to kill a table by flooding it with failed insert requests as the mysql reference manual statesthe behavior of the autoincrement mechanism is not defined if the value becomes bigger than the maximum integer that can be stored in the specified integer typeis this expected behavior,['mysql'] +61024,spring maven libraries i would like to know why some of the libraries are not released during a normal release cycle for example from while springcore have 303release springremoting and springjmx were released only in 208 can someone tell me what this would mean i agree that if there are no changes in the component say springjmx then they do not have to release it but since 90 of the world uses maven for dependency management can they not just rerelease the same libs of springremoting and springjmxi ask this because i declare my deps likedependency groupidorgspringframeworkgroupid artifactidspringcoreartifactid versionspringversionversiondependencydependency groupidorgspringframeworkgroupid artifactidspringremotingartifactid versionspringversionversiondependencyand i would prefer supplying one springversion instead of keeping version numbers upto date for all componentsthe four libraries of interest to me are springdao springsupport springjmx springremoting,['java'] +61029,java how to read a text file i want to read a text file containing space separated values values are integershow can i read it and put it in an array listhere is an example of contents of the text file1 62 4 55 5 6 77i want to have it in an arraylist as 1 62 4 55 5 6 77 how can i do it in java,['java'] +61031,java efficiency of the readline method of the bufferedreader and possible alternatives we are working to reduce the latency and increase the performance of a process written in java that consumes data xml strings from a socket via the readline method of the bufferedreader class the data is delimited by the end of line separater n and each line can be of a variable length 6kbits 32kbits our code looks likesocket sock connectioninputstream in sockgetinputstreambufferedreader inputreader new bufferedreadernew inputstreamreaderindo string input inputreaderreadline executor call to parse the input thread in a seperate threadwhiletrueso i have a couple of questionswill the inputreaderreadline method return as soon as it hits the and character or will it wait till the buffer is fullis there a faster of picking up datafrom the socket than using abufferedreaderwhat happens when the size of the input string is smaller than the size of the sockets receive buffer what happens when the size of theinput string is bigger than the sizeof the sockets receive bufferi am getting to grips slowly with javas io libraries so any pointers are much appreciatedthank you,['java'] +61032,what happens when user click net assembly exe consider we have net winforms application or console applicationcan anyone tell me what will happen stepbystep until the winform or console application is launched i would like know the internals like how exe will communicate with framework what is the role of clr what happens in case of exception while launching applicaiton itselfetc,"['c#', '.net']" +61034,how many records can i store in a sql server table before it is getting ugly i have been asked to do some performance tests for a new systemit is only just running with a few client but as they expect to grow these are the numbers i work with for my test200 clients 4 years of data and the data changes per 5 minutes so for every 5 minutes for every client there is 1 recordthat means 3652412 1050 records per client per year that means 80 milion records for my testit has one fk to another table one pk uniqueidentifier and one index on the clientidis this something sqlserver laughs about because it is not scaring him is this getting too much for one quad core 8 gb machine is this on the edge orhas anybody had any experience with these kind of numbers,['sql'] +61051,find which child view was tapped when using uitapgesturerecognizer how do i know on which of the the child views an event occurred when using uigesturerecognizersaccording to the documentationa gesture recognizer operates on touches hittested to a specific view and all of that viewas subviewsas far as i can see the view property isthe view the gesture recognizer is attached towhich will be the parent view,['objective-c'] +61053,net reflection how to call method of interface without creating instance i have situation where i have to call method of interface using reflection like thisobject x nullmethodinfo method interfaceexistsgetmethodshutdownmethodinvokex new object 4 as you can see i do not create instance of object and as i can supposed i receive exceptionnonstatic method requires a targetand question can i call method of interface using reflection without creating instance of interface and if yes how i can do it,"['c#', '.net']" +61065,can events be declared as static if yes how and why i want to know can we declare the events as static if yes why and application of such declarationsample please as seeing is believing,['c#'] +61066,python add to a function dynamically how do i add code to an existing function either before or afterfor example i have a class class aobject def testself print herehow do i edit the class wit metaprogramming so that i do this class aobject def testself print here print and heremaybe some way of appending another function to testadd another function such as def test2self print and hereand change the original to class aobject def testself print here selftest2is there a way to do this,['python'] +61095,is it bad to throw exceptions to return server errors eg 404 page not found i am working on a php framework and am currently designing error handling based on what i have read on so i should only use exceptions for well exceptional situations therefore throwing an exception when an incorrect password is entered is wrongshould i avoid using exceptions when i want to return a server error code to the user eg 404 page not found if so should i write my own error handling class,['php'] +61112,how to get option titlesample using jquery i am trying to update a hidden field based on the a title attribute on a select option i have tried the code bellow and cannot seem to get it to work thanks for any helpformselect idselectboxoption nametest valueone titletitle selectedselectedoneoptionoption nametest2 valuetwo titletitle2twooptionselectforminput idupdate typehidden valuedefaultold scriptupdatevaldefault selectboxchangefunction updatevalthisattrtitlescript,['jquery'] +61118,microsoft master data services when to utilize i am wondering if anyone is currently utilizing microsofts master data services how you are utilizing it whether you find it useful when you believe it would be useful thanks,['sql'] +61141,what is better for php developers unicode or utf8 what is better for php developers unicode or utf8 i am going to create an international cms so i am going to have clients all over the world they will speak all possible languages what encoding format is better for browser recognition and for db data storage,['php'] +61142,uibuttons custom image and frame i have the following code uiimage cancelimg uiimage imagenamedcanceljpeg uibutton btncancel uibutton buttonwithtypeuibuttontypecustom btncanceluserinteractionenabled yes btncancel setframecgrectmake0 280 280 btncancel setimagecancelimg forstateuicontrolstatenormal cellaccessoryview btncancelcanceljpeg currently is bigger than 28 x 28 and it is actually 100 x 100why does the button thisplay 100 x 100 size of the image when i have set the uibuttons size to 28 x 28,['iphone'] +61145,python3 error import error no module name urllib2 heres my codeimport urllib2requestresponse urllib2urlopenhtml responsereadprinthtmlany help,['python'] +61151,how do i sort a hash table in javascript i have a javascript hash table like sovar things thingshello name z i fell asleep number 7thingsone name something number 18thingstwo name another thing number 2i want to sort these into order by name so if i iterate through the hash table it will go in orderanother thingsomethingz i fell asleepi tried doing thisfunction comparethingsthing1 thing2 var name1 thing1nametolowercase var name2 thing2nametolowercase if name1 name2 return 1 if name1 name2 return 1 return 0thingssortcomparethingsbut it does not seem to workedit it occurs to me that perhaps a sorted hash table is an oxymoron if so whats the best way to get access to a sorted list of the things here,['javascript'] +61153,java cannot find file when running through eclipse when i run a java application that should be reading from a file in eclipse i get a javaiofilenotfoundexception even though the file is in the correct directory i can compile and run the application from the command line just fine the problem only occurs in eclipse with more than one project and application is there a setting i need to change in the run configurations or build paths to get it to find the file correctly,['java'] +61163,using javaneturlconnection to fire and handle http requests use of javaneturlconnection is asked about pretty often here and the oracle tutorial is too concise about it that tutorial basically only shows how to fire a get request and read the response it does not explain anywhere how to use it to among others perform a post request set request headers read response headers deal with cookies submit a html form upload a file etc so how can i use javaneturlconnection to fire and handle advanced http requests,['java'] +61169,weird overlay draw behaviour when zooming in the mapview i have extended overlay and implemented draw in order to draw some stuff onto the mapwhen zooming is done through mapcontrollerzoomin called when doubletapping the mapthe overlay is drawn properly onto the mapbut whenever i zoom inout with the built in zoom controller the overlay is not drawn properly and panning the map is needed to get the overlay refreshed,['android'] +61190,when can argv0 have null what i have understand about passing arguments to main from command line is that argc has a minimum value of 1 and argv0 will always have the program name with its path in itif arguments are provided at the command line then argc will have a value greater than one and argv1 to argvargc1 will have those argumentsnow a paragraph at this link says thatargv0 will be a string containing the programs name or a null string if that is not availablenow how and when can argv0 have null string i mean program name with its path will always be available so when can it be null writer says that if that is not available but when and how it is possible that program name will not be availablethanks for your time and supportregards,['c'] +61194,webclient the remote server returned an error 403 forbidden opening a public page from browser works finedownloading same page using webclient throws 403 forbiddenwhat is going on here here is quick copypaste example used on console app to specific page on webtry webclient webclient new webclient string content webclientdownloadstring d7a2d7a8d795d79a d790d795d7a8d797 d797d799d799d79d d790 d790catch exception ex throw,['c#'] +61199,what do the columns in the object alloc instrument mean i was unable to find the documentation for this there is no quick infothe columns have these opaque titlescategorylive bytes living transitoryoverall bytes overall allocations net overallis there a document that shows what these columns mean without having to read 600 pages,['iphone'] +61202,specific stylesheet for ie8 how can i make a specific css stylesheet for internet explorer 8i mean how can i load it only if the browser is ie8 and not ie7 and ie6,['css'] +61211,java collectionsrotate with an array does not work i have the following java codeimport javautilarraysimport javautilcollectionspublic class test public static void mainstring args int test 12345 collectionsrotatearraysaslisttest 1 forint i 0 i testlength i systemoutprintlntesti i want the array to be rotated but the output i get is12345why is thisand is there an alternative solutioneditso this worksimport javautilarraylistimport javautilcollectionsimport javautillistpublic class test public static void mainstring args int test 12345 listinteger testlist new arraylistinteger forint i 0 i testlength i testlistaddtesti collectionsrotatetestlist 1 forint i 0 i testlength i systemoutprintlntestlistgeti but arraysaslist is supposed to return a list that when written to copies the changes to the array is there any way to fix this without manually doing the conversion from array to listi think that i cannot afford to waste that much cpu time and memory to do the conversion,['java'] +61220,best way to detect ironpython i need to write a module which will be used from both cpython and ironpython whats the best way to detect ironpython since i need a slightly different behaviour in that casei noticed that sysplatform is win32 on cpython but cli on ironpythonis there another preferredstandard way of detecting it,['python'] +61223,how to implement a custom alertdialog view in the android docs on alertdialog it gives the following instruction and example for setting a custom view in an alertdialogif you want to thisplay a more complex view look up the framelayout called body and add your view to itframelayout fl framelayout findviewbyidridbodyfladdmyview new layoutparamsfill parent wrap contentfirst off it is pretty obvious that add is a typo and is meant to be addviewi am confused by the first line using ridbody it seems that it is the body element of the alertdialog but i cannot just enter that in my code bc it gives a compile error where does ridbody get defined or assigned or whateverheres my code i tried to use setviewfindviewbyidrlayoutwhatever on the builder but it did not work i am assuming because i did not manually inflate italertdialogbuilder builder new alertdialogbuilderthisbuildersettitletitle setcancelablefalse setpositivebuttongo new dialoginterfaceonclicklistener override public void onclickdialoginterface dialog int id edittext textbox edittext findviewbyidridtextbox dostuff framelayout f1 framelayoutfindviewbyidridbody currently an errorf1addviewfindviewbyidrlayoutdialog viewalertdialog alert buildercreatealertshow,['android'] +61224,net diagnostics best practices we initially did not use any logging or debug tracing but after spending few weeks to trace down some data corruption we decided to put required debugwrite and trace for production and debugassertso now question is what is the best practice to use debug and trace logging i am just looking for some thing genericpublic void addrectodatabaseobject record debugwritelinerecordtostring tracewritelinerecordtostring add it to databse debugasserttrue use this on case by case basisis this good enough for general purpose am i doing anything wrong in therewe want to stick with net systemdiagnostics over other alternatives like log4netis there any thing else useful in systemdiagnostics,['.net'] +61225,httpprotocolparamssetuseexpectcontinueparams false when to set true i am using orgapachehttpimplclientdefaulthttpclient to retrieve xml from a webservice and am trying to determine whether to set httpprotocolparamssetuseexpectcontinueparams true or httpprotocolparamssetuseexpectcontinueparams falsei am not clear on how to determine this can anyone offer a best practices guideline on when this should be true and when it should be false and also the possible implications of each setting,['java'] +61228,how to put a scanner input into an array for example a couple of numbers scanner scan new scannersystemindouble numbers scannextdoubledouble avg,['java'] +61240,removing rows from mysql table where the timestamp is over one day old i found the exact same question herebut it is not working for me i have modified it a bit manipulated it and i cannot figure it out i am trying to remove rows that are over a day old here is my codeif isset postprune sql delete from logs where time datenow 1 days mysql querysql echo logs older than one day removed fairly simple question i suppose but its bugging the hell out of me i would appreciate any helpin case it makes a difference the column is a timestamp typeedit apparently i am an idiot the question i linked you to relates to sqlite3 so now my question is how can i do this in mysql,"['php', 'mysql']" +61243,how can i get the uitableview scroll position so i can save it is there any way to find out which uitableviewcell is at the top of the scroll window i would like to get the current scroll position so that i can save it when the app exits when the app gets started i want to scroll to the position it was at when it last exited,"['iphone', 'objective-c']" +61264,netbeans autocompletion when using singleton to retrieve object instead of new operator when i use the new operator to instantiate a class netbeans has no problem to autocomplete the members of the objectinstance new singletoninstance shows test methodbut when i use a singleton to retrieve an object it cannot autocomplete the members in the object retrievedthe getinstance code looks like thispublic function test echo hellopublic static function getinstance if is objectself instance self instance new self self instanceinitializereturn self instanceso i useinstance singletongetinstanceinstance no autocompletiondoes anyone have the same problemhow do i work around itthanks,['php'] +61269,rest authentication in php codeigniter i writing rest api form my web application application is written using codeigniter framework application itself is working fine but i am stuck on making rest authentication i think that basic http authentication will be good enough for some time public api is not yet plannedis there any code example how to achieve rest authentication so after user is authenticated he can freely call all protected methods,['php'] +61271,ruby gem not found although it is installed i found some similar problems here on so but none seem to match my case sorry if i overlooked heres my problem i installed oauthplugin gem to ruby gems dir but trying to use it in rails app tells me that it is not being found heres the output of relevant commandsinstallation s gem install oauthpluginsuccessfully installed oauthplugin03141 gem installedinstalling ri documentation for oauthplugin0314installing rdoc documentation for oauthplugin0314gem which oauthplugin output gem which oauthpluginusrlibrubygems18gemsoauthplugin0314liboauthpluginrbgem env output gem envrubygems environment rubygems version 136 ruby version 187 20091224 patchlevel 248 i686darwin1020 installation directory usrlibrubygems18 ruby executable usrbinruby executable directory usrbin rubygems platforms ruby x86darwin10 gem paths usrlibrubygems18 userseimantasgemruby18 gem configuration update sources true verbose true benchmark false backtrace true bulk threshold 10 gem nori nordoc sources remote sources doing ls l usrlibruby shows this ls l usrlibruby lrwxrxrx 1 root wheel 76 aug 14 2009 usrlibruby systemlibraryframeworksrubyframeworkversionscurrentusrlibrubyand the gem in question is in intended location heres the error that rails give me when i try running rake specmissing these required gems oauthplugin 0314youre running ruby 187173 at systemlibraryframeworksrubyframeworkversions18usrbinruby rubygems 136 at userseimantasgemruby18 libraryrubygems18 systemlibraryframeworksrubyframeworkversions18usrlibrubygems18run rake gemsinstall to install the missing gemsthis is not a single gem that is not being found by rubygems although it is located where it should be any guidance towards the solution is much appreciated,['ruby'] +61283,c callback functions defined in an unnamed namespace i have a c project that uses a c bison parser the c parser uses a struct of function pointers to call functions that create proper ast nodes when productions are reduced by bisontypedef void nodestruct actions node newintlitint val node newasgnexprnode left node right now in the c part of the project i fill those pointersclass astnode class intlit public astnode extern c node newintlitint val return nodenew intlitval actions createactions actions a anewintlit newintlit return anow the only reason i put them within extern c is because i want them to have c calling conventions but optimally i would like their names still be mangled they are never called byname from c code so name mangling is not an issue having them mangled will avoid name conflicts since some actions are called like error and the c callback function has ugly names like the following just to avoid name clashes with other modules extern c void uglynameerrorchar const str aerror uglynameerrori wondered whether it could be possible by merely giving the function type c linkageextern c void ftychar const strnamespace fty error declared but i can i define it with that type any ideas i am looking for standardc solutions,['c++'] +61289,set a callback function to a new window in javascript is there an easy way to set a callback function to a new window that is opened in javascript i would like to run a function of the parent from the new window but i want the parent to be able to set the name of this particular function so it should not be hardcoded in the new windows pagefor example in the parent i havefunction dosomething alertsomething input typebutton onclickopennewwindowlinktonewwindowdosomething and in the child window i want toinput typebutton onclickruncallbackfunction the question is how to create this opennewwindow and runcallbackfunction functions i though about sending the functions name as a query parameter to the new window where the server side script generates the appropriate function calls in the generated childs html which works but i was thinking whether there is another or better way to accomplish this maybe something that does not even require server side tinkeringpure javascript server side solutions and jquery or other frameworks are all welcomed,"['javascript', 'html']" +61295,sorting tree with a materialized path i have a tree structure in a table and it uses materialized paths to allow me to find children quickly however i also need to sort the results depthfirst as one would expect with threaded forum replies id parent id matpath created 2 1 1 20100508 151837987544 3 1 1 20100508 173814125377 4 1 1 20100508 17385726743 5 1 1 20100508 174328211708 7 1 1 20100508 181811849735 6 2 12 20100508 175043288759 9 5 15 20100509 140243818646 8 6 126 20100509 140117632695so the final results should actually be sorted like this id parent id matpath created 2 1 1 20100508 151837987544 6 2 12 20100508 175043288759 8 6 126 20100509 140117632695 3 1 1 20100508 173814125377 4 1 1 20100508 17385726743 5 1 1 20100508 174328211708 9 5 15 20100509 140243818646 7 1 1 20100508 181811849735how would i work that out can i do that in straight sql this is postgresql 84 or should additional information be added to this tableupdate trying to explain sort criteria betterimagine that id 1 is the root post to a forum and everything with a matpath beginning with 1 is a child of that post so ids 2 through 5 are direct replies to 1 and get matpaths of 1 however id 6 is a reply 2 not directly to 1 so it gets a matpath of 12 this means that for a threaded forum with proper nesting with all ids shown in the tables the structure of the forum would look like this hence the ordering requirement id 1 root post id 2 id 6 id 8 id 3 id 4 id 5 id 9 id 7,['sql'] +61301,xpath and innerhtml what xpath expression can i use to find all the anchor just a elements whose actual text the innerhtml is logoutsomething likeainnerhtmllogoutwould that be correct,['html'] +61303,maximum memory which malloc can allocate i was trying to figure out how much memory i can malloc to maximum extent on my machine1 gb ram 160 gb hd windows platformi read that the maximum memory malloc can allocate is limited to physical memory on heapalso when a program exceeds consumption of memory to a certain level the computer stops working because other applications do not get enough memory that they requireso to confirm i wrote a small program in cint main int p while1 pint malloc4 ifpbreak i was hoping that there would be a time when memory allocation would fail and the loop would break but my computer hung as it was an infinite loopi waited for about an hour and finally i had to force shut down my computersome questionsdoes malloc allocate memory from hd alsowhat was the reason for above behaviourwhy did not loop break at any point of timewhy was not there any allocation failure,['c'] +61319,worth it to use jquery ui hosted by google so i heard good reasons why to use the jquery hosted on google because of caching but i am not sure about jquery ui thoughi am guessing that the jquery ui file hosted on google has every single extension and plugin such as draggable etcso is that not kind of a waste if say your only using only jquery ui tabs to get all that other stuff with italso i see they have some of the templates up for the css files i am guessing the caching would be the main advantage of using the hosted file,['jquery'] +61323,any good google visualization annotated timeline tutorials i have been playing with google visualization annotated timeline and so far i am comfortable thisplaying the data and adding annotations but i am fairly confused about how to implement getting additional data when the user zooms the chart using either the zoom links at the top of the chart or the timeline belowa great example of the implementation i am after is google finance when you zoom the scale at the bottom shifts and shows the overall trend for the range that is appropriate to the userthe documentation google provides is fairly basic and dry for a novice such as myselfdoes anyone know of a good tutorial on this subject a pythonbased tutorial would be awesome,['python'] +61340,python dictionary to variable assignments based on key value to variable name basically i want to take a dictionary like abar bblah cabc dnada and use it to set variables in an object which have the same name as a key in the dictionaryclass fobject selfa selfb selfc so in the the end selfa bar selfb blah etc and key d is ignoredany ideas,['python'] +61352,ipadhow to convert iphone apps into ipad compatible i have several iphone apps which i want to convert them to ipad is there a link where i can have a look at simple procedures about how to convert iphons apps into ipad compatible i already installed 32 sdk etc having development environment readyforgive me if it is a repeated question,['iphone'] +61353,possible to get list item label with javascript if i have got a ul with 3 items in it and the liststyletype is set to loweralpha i end up with thisa item 1b item 2c item 3with jquery i can easily get the value of any item you click item 1 if i click the first but can i get the list item label in this case a,"['javascript', 'jquery']" +61358,shared ptr as class member it is common to declared contained objects as a pointers to that class while forward declarating them in header file this in order to reduce physical dependencies in codefor exampleclass b forward declaration class a private b pbwould it be good idea to declare such a member as shared ptr instead of naked pointeri would prefer scoped ptr but afaik it it would not be in standard,['c++'] +61372,does pressing back always cause activity to finish i have heard that pressing the back button will essentially cause the current activity to finish is this always the case seems like it would be with the way it pops the activity off the stackthe one situation i am not so sure about is when the root activity in a task has back pressed i am currently experiencing a very weird effect described as followson loading my application the first activity is for initialization and once it finishes it calls my main activity a tabactivity this first init activity has androidnohistorytrue set in the manifest so pressing back from my main activity would not go back to that it goes to the launcher when i click on my app in the launcher a second time the initialization activity loads again and loads the main activity when done almost immediately after it loads a second instance of my main activity but only after the application has already been run once and was exited by pressing back from the main activity it does it every subsequent time until i force quit the app or load a new version from the idebased on this i am suspecting some kind of activity instance is lying around and being reused since it only happens on the second time i run the application and exit with back using home just returns to the last state of the app no big deal anyone have any thoughts,['android'] +61401,asynchronous nsurlconnection throws exc bad access i am not really sure why my code is throwing a exc bad access i have followed the guidelines in apples documentationvoidgetmessagesnsstringstream nsstring myurl nsstring stringwithformat nsurlrequest therequest nsurlrequest requestwithurlnsurl urlwithstringmyurl nsurlconnection theconnectionnsurlconnection alloc initwithrequesttherequest delegateself if theconnection receiveddata nsmutabledata data retain else nslogconnection failed and my delegate methodspragma mark nsurlconnection delegate methods voidconnectionnsurlconnection connection didreceiveresponsensurlresponse response this method is called when the server has determined that it has enough information to create the nsurlresponse it can be called multiple times for example in the case of a redirect so each time we reset the data receiveddata is an instance variable declared elsewhere receiveddata setlength0 voidconnectionnsurlconnection connection didreceivedatansdata data append the new data to receiveddata receiveddata is an instance variable declared elsewhere receiveddata appenddatadata voidconnectionnsurlconnection connection didfailwitherrornserror error release the connection and the data object connection release receiveddata is declared as a method instance elsewhere receiveddata release inform the user nslogconnection failed error error localizeddescription error userinfo objectforkeynserrorfailingurlstringkey voidconnectiondidfinishloadingnsurlconnection connection do something with the data receiveddata is declared as a method instance elsewhere nslogsucceeded received d bytes of datareceiveddata length release the connection and the data object connection release receiveddata releasei get an exc bad access on didreceivedata even if that method simply contains an nslog i get the errornote receiveddata is an nsmutabledata in my header file,"['iphone', 'objective-c']" +61408,how to intercept raw soap requestresponse data from wcf client this question seems to be pretty close to what i am looking for i was able to setup tracing and i am looking at the log entries for my calls to the servicehowever i need to see the raw soap request with the data i am sending to the service and i see no way of doing that from the svctraceviewer only log entries are shown but no data sent to the service am i just missing configurationheres what i got in my webconfig systemdiagnostics sources source namesystemservicemodel switchvalueverbose propagateactivitytrue listeners add namesdt typesystemdiagnosticsxmlwritertracelistener initializedataapp datalogswcftracesvclog listeners source sources systemdiagnosticsany help appreciatedupdate this is all i see in my tracee2etraceevent xmlns system xmlns eventid262163eventid type3type subtype nameinformation0subtype level8level timecreated systemtime20100510t1310466713553z source namesystemservicemodel correlation activityid015010080f6 execution processnamew3wp processid3492 threadid23 channel computermy computer namecomputer systemapplicationdata tracedata dataitem tracerecord xmlns severityinformation traceidentifiertraceidentifier descriptionsent a message over a channeldescription appdomainmy domainappdomain sourcesystemservicemodelchannelshttpoutputwebrequesthttpoutput50416815source extendeddata xmlns messageproperties encodertextxml charsetutf8encoder allowoutputbatchingfalseallowoutputbatching viavia messageproperties messageheadersmessageheaders extendeddata tracerecord dataitem tracedataapplicationdata,['asp.net'] +61412,is it possible to get a stored cookies path quick question one can set the path where a cookie is valid but is it also possible to get read this path from the cookie in phpor else is it possible to extend a cookies time without knowing what path it is on but keeping the path the same,['php'] +61419,what is a qt plugin what is a qt plugin what are differences between a qt plugin and a custom made qt librarythanks,['c++'] +61431,iphone app submission status bar and screenshots i have read somewhere that the screenshots you send to apple should not contain the status bar however my app shows the status bar during runtime after having a look around the app store i have noticed quite a few app screenshots contain the status barso my question is is including the status bar in application screenshots a rejectable offence nb the google app screenshots contains the status bar so i am guessing nomany thanks,['iphone'] +61441,net windows forms intercepting the close x event this must be a dumb question but i cannot figure it out i also cannot use the designer because coders before me managed to throw gui and logic all in one so now it is confused i have got to do it the old school wayi have a form which can be closed in 3 ways close button file close menu and the x icon i want them all to do the same thing intercepting the button and the menu events is easy in fact both are hooked up to an oncloseconfig method btw is there a better name for this methodprivate void oncloseconfigobject sender systemeventargs e if m configcontrolmodified applicationexit or should it be thisclose else present a dialog ask if they want to saveso to intercept the x i tried thisformclosing new formclosingeventhandlerthisoncloseconfig i believe this is what causes an infinite loop i do not want that formclosed is another option but it seems too late i just want to intercept the fact that the x was clicked not the fact that the form is closing,['.net'] +61442,is there a way to get a textarea to stretch to fit its content without using php or javascript i am filling a textarea with content for the user to editis it possible to make it stretch to fit content with css like overflowshow for a divthanks,"['html', 'css']" +61443,net api for hid usb is there an api in net c for using usb hid human interface devices,"['c#', '.net']" +61446,get gprof to profile based on wallclock time my understanding is that by default gprof takes into account cpu time is there a way to get it to profile based on wallclock timemy program does a lot of thisk io so the cpu time it uses only represents a fraction of the actual execution time i need to know which portions of the thisk io take up the most time,['c++'] +61450,how to check if iis is in 32bit or 64bit mode i am trying to deploy a site to a 64bit os i am deploying to iis6 the site was developed on a 32bit server the site deployed correctly however it is trying to access a com component and that is failingi believe the error is occurring because the com component is a 64bit version on the 64bit os and iis6 is running in 32bit mode on the 64bit serveri would like to confirm this but i cannot seem to find a definitive way to check if iis6 is in 32bit mode or 64bit modewould someone know the best way to check if iis6 is in 64bit or 32bit modeedit i am using iis6,['asp.net'] +61472,in c what is the scope resolution order of precedence for shadowed variable names in c what is the scope resolution order of precedence for shadowed variable names i cannot seem to find a concise answer onlinefor exampleinclude iostreamint shadowed 1struct foo foo shadowed2 void barint shadowed 3 stdcout shadowed stdendl what does this output int shadowed 4 stdcout shadowed stdendl what does this output int shadowedint main foobari cannot think of any other scopes where a variable might conflict please let me know if i missed onewhat is the order of priority for all four shadow variables when inside the bar member function,['c++'] +61477,custom color my uiactivityindicatorview i would like to have my uiactivityindicatorview be colored a custom color is there any way to set this property,"['ios', 'objective-c']" +61481,opening pdf string in new window with javascript i have a formatted pdf string that looks like pdf173 0 obj type group s transparency cs devicergb resources 2 0 rcontents 4 0 r endobj4 0 obj streamxi12i12roi120i12i12i12i12vli12ri12i12i12li12i12i12ui12i12i12gei12jki12i12i12i12i12i12i12y5i12i12i12i12i12ze ki12vfi12ai12i12goui12i12asfi12zi12i14i12i12i12i12aii12i12ti12i12i12gdi12i12i12i12i12i12i12i12bi12bi12i120 and 0703 0 and 0820 0 and 0926 0 and 01206 0 and 01649 0 and trailer size 11 root 10 0 r info 9 0 r startxref2015eofi am trying to open up this string in a new window as a pdf file whenever i use windowopen and write the string to the new tab it thinks that the text should be the contents of an html document i want it to recognize that this is a pdf fileany help is much appreciated,['javascript'] +61502,how do i determine which cc compiler to use i am trying to figure out which cc compiler to use i found this list of cc compilers at wikipedia of compilersc2fc2b2b compilersi am fairly certain that i want to go with an open source compiler i feel that if it is open source then it will be a more complete compiler since many programmer perspectives are used to make it better please tell me if you thisagree i should mention that i plan on learning cc mainly to program 2d3d game applications that will be compatible with windows linux mac and iphone operating systems i am currently using windows vista x64 os,"['c++', 'c']" +61508,java program to get the current date without timestamp i need a java program to get the current date without timestampdate d new dategives me date and timestampbut i need only date without timestamp i use this date to compare with another date object that does not have timestamp on printing systemoutprintlncurrent date dof d it should print may 11 2010 0,['java'] +61516,what is the proper way to use a logger in a serializable java class i have the following doctored class in a system i am working on and findbugs is generating a se bad field warning and i am trying to understand why it would say that before i fix it in the way that i thought i would the reason i am confused is because the description would seem to indicate that i had used no other nonserializable instance fields in the class but barmodelfoo is also not serializable and used in the exact same way as far as i can tell but findbugs generates no warning for itimport barmodelfooimport javaiofileimport javaioserializableimport javautillistimport orgslf4jloggerimport orgslf4jloggerfactorypublic class demo implements serializable private final logger logger loggerfactorygetloggerthisgetclass private final file file private final listfoo originalfoos private integer count private int primitive 0 public demo for foo foo originalfoos thisloggerdebug my initial blush at a solution is to get a logger reference from the factory right as i use itpublic thispositionfile logger logger loggerfactorygetloggerthisgetclass for foo foo originalfoos thisloggerdebug that does not seem particularly efficient thoughthoughts,['java'] +61522,why do i need an intermediate conversion to go from struct to decimal but not struct to int i have a struct like this with an explicit conversion to floatstruct twfix32 public static explicit operator floattwfix32 x i can convert a twfix32 to int with a single explicit cast intfix32but to convert it to decimal i have to use two casts decimalfloatfix32there is no implicit conversion from float to either int or decimal why does the compiler let me omit the intermediate cast to float when i am going to int but not when i am going to decimal,['c#'] +61527,same il code different output how is it possible i have a piece of code which outputs different results depending on the c compiler and the runtimethe code in question isusing systempublic class program public static void main consolewritelinestringcomparealo0alo0 alo0alo00 false systemglobalizationcultureinfoinvariantculture the results are compiling with mono gmcs compiling with net cscrunning with mono 1 1running with net 1 0how can it output different values when running with the net frameworkbtw according to the output should be 0 so monos answer is incorrect but that is unrelated to my questioneven the generated il code is almost the samecompiling with netmethod public hidebysig static void main cil managed entrypoint code size 29 0x1d maxstack 8 il 0 nop il 01 ldstr bytearray 61 00 6c 00 6f 00 00 00 61 00 6c 00 6f 00 00 00 aloalo il 06 ldstr bytearray 61 00 6c 00 6f 00 00 00 61 00 6c 00 6f 00 00 00 aloalo 00 00 il 0b ldci40 il 0c call class mscorlibsystemglobalizationcultureinfo mscorlibsystemglobalizationcultureinfoget invariantculture il 0011 call int32 mscorlibsystemstringcomparestring string bool class mscorlibsystemglobalizationcultureinfo il 0016 call void mscorlibsystemconsolewritelineint32 il 001b nop il 001c ret end of method programmaincompiling with monomethod public hidebysig static void main cil managed entrypoint code size 27 0x1b maxstack 8 il 0 ldstr bytearray 61 00 6c 00 6f 00 00 00 61 00 6c 00 6f 00 00 00 aloalo il 05 ldstr bytearray 61 00 6c 00 6f 00 00 00 61 00 6c 00 6f 00 00 00 aloalo 00 00 il 0a ldci40 il 0b call class mscorlibsystemglobalizationcultureinfo mscorlibsystemglobalizationcultureinfoget invariantculture il 0010 call int32 mscorlibsystemstringcomparestring string bool class mscorlibsystemglobalizationcultureinfo il 0015 call void mscorlibsystemconsolewritelineint32 il 001a ret end of method programmainthe only difference is the two extra nop instructions in the net versionhow is it possible how can the two output values be differentalso if anyone has both net and mono installed can you reproduce itedit i do not care what the correct result is and i do not care that mono and net produces different results i will probably never encounter embedded nulls and sort them and the sorting order will be importantmy problem is that the same runtime net 20 produces different results when compiled by different compilersedit 2 i added a table and tried to clarify the question it should be easier to understand now,"['c#', '.net']" +61528,ipad cover flow i use flowcoverview for cover flowhowever the textures this library creates are limited to 256 pixels maximum and i would like to show bigger images in an ipad cover flowwhat do you use for cover flow on the ipad is it possible to modify this library to make the textures bigger,['iphone'] +61531,screenshot of the nexus one from adb my goal is to be able to type a one word command and get a screenshot from a rooted nexus one attached by usbso far i can get the framebuffer which i believe is a 32bit xrgb8 raw image by pulling it like thisadb pull devgraphicsfb0 fb0from there though i am having a hard time getting it converted to a png i am trying with ffmpeg like thisffmpeg vframes 1 vcodec rawvideo f rawvideo pix fmt rgb8 s 480x800 i fb0 f image2 vcodec png imagepngthat creates a lovely purple image that has parts that vaguely resemble the screen but it is by no means a clean screenshot,['android'] +61555,subscript operator on pointers if i have a pointer to an object that has an overloaded subscript operator why cannot i do this myclass a new myclass a1but have to do this instead myclass a new myclass a1,['c++'] +61567,407 proxy authentication required i am getting the following exception while making a call using xmlhttp object asynchronously in mozilla firefox407 proxy authentication requiredthe isa server requires authorization to fulfill the requestaccess to the web proxy filter is denieddescription of causeactually i am trying to make an asynchronous request to using get in javascript it is working fine using ie 6 but for ie 7 and firefox 35 it will it would not get any data using asynchronous request so how to overcome this problemwhen i debug in firefox 35 using firebug it shows 407 proxy authentication required the isa server requires authorization to fulfil the request access to the web proxy filter is deniedexception at console so how to tackle this issuenote our network has proxy server,['javascript'] +61573,div with absolute position behind the normal flow i am trying to get a div to be my background and am using absolute positioning to achieve it everything works fine except for the fact that it appears above anything in the normal flow and fiddling with zindexes does absolutely nothing div idblind div idblindbackgrounddiv div idblindcontainer div classloader img classloader srcimgloadergif div div div idblindclosecontainer img idblindclose srcimgclosegif divdivand this is the cssblind position absolute width100 zindex 2 borderbottom 1px silver solidblindclosecontainer textalign rightblindbackground positionabsolute top0 width100 height100 backgroundcolor white filteralphaopacity60 opacity06blindcontainer marginauto width500px backgroundcolor white padding10pxloader margin auto width18px margintop10px marginbottom 5px,"['html', 'css']" +61574,extjs handling browser exit event click on crossexit first of all thank you for reading my questioni would like to know if there is any way to handle the browser exit eventfor example i would like to send a query when the user click on the crossexit or simply close his browserthanks a lott0rm,['javascript'] +61577,given a list of ip address how do you find min max in java i have an arraylist of ip address how do i find the min and max i have used the collectionmin but it doesnt work given a case like 19216801 min 192168025019216809 maxhow do i return19216801 min1921680250 maxinstead arraylist is retrieve from the database i would need to do this operation per tick each tick is at 5 sec interval the number of ip address would hit a max of probably 300,['java'] +61583,how does rails 3s datamethoddelete degrade gracefully rails 3 does some cool stuff to make javascript unobtrusive so they have done things like this link to logout user session path method deleteconverts toa hreflogout datamethoddelete relnofollowlogoutabut it just occurred to me when i turn off javascript the method is not delete anymore it is get as expected so are there plans to or is there some way to allow these data attributes to degrade gracefully so that link still is a delete request,['ruby-on-rails'] +61585,gc output clarification i am running a java application with the following settingsxxcmsparallelremarkenabledxxuseconcmarksweepgcxxuseparnewgcxxprintgcapplicationstoppedtimexxprintgcapplicationconcurrenttimexxprintgcdetailsxxprintgctimestampsxxprintgcdatestampsxxprintheapatgcxxprinttenuringthistribution i am not sure how to interpret the related gc logsbelow in particularheap after gc invocations31 full 3 does this mean there were 31 minor gcs and 3 full gcs what triggers the several consecutive lines of total time for which the application threads were stopped and application time is it possible to get the time stamps associated with each of these lines gc logstotal time for which application threads were stopped 046910 seconds application time 07946670 seconds total time for which application threads were stopped 02900 seconds application time 10153640 seconds total time for which application threads were stopped 02780 seconds application time 10161890 seconds total time for which application threads were stopped 02760 seconds application time 10145990 seconds total time for which application threads were stopped 02950 seconds application time 09800 seconds total time for which application threads were stopped 02770 seconds application time 10151640 secondstotal time for which application threads were stopped 02730 secondsapplication time 096590 seconds total time for which application threads were stopped 02880 seconds application time 09624290 seconds heap before gc invocations30 full 3 par new generation total 131008k used 130944k 0x0eac0 0x0f2c0 0x0f2c0 eden space 130944k 100 used 0x0eac0 0x0f2be0 0x0f2be0 from space 64k 0 used 0x0f2bf0 0x0f2bf0 0x0f2c0 to space 64k 0 used 0x0f2be0 0x0f2be0 0x0f2bf0 concurrent marksweep generation total 131072k used 48348k 0x0f2c0 0x0fac0 0x0fac0 concurrentmarksweep perm gen total 30k used 19518k 0x0fac0 0x0fc94c0 0x010 20100511t09301380100 384955 gc 384955 parnew desired survivor size 32768 bytes new threshold 0 max 0 130944k0k131008k 052470 secs 179292k48549k262080k 053030 secs times user0 sys0 real001 secs heap after gc invocations31 full 3 par new generation total 131008k used 0k 0x0eac0 0x0f2c0 0x0f2c0 eden space 130944k 0 used 0x0eac0 0x0eac0 0x0f2be0 from space 64k 0 used 0x0f2be0 0x0f2be0 0x0f2bf0 to space 64k 0 used 0x0f2bf0 0x0f2bf0 0x0f2c0 concurrent marksweep generation total 131072k used 48549k 0x0f2c0 0x0fac0 0x0fac0 concurrentmarksweep perm gen total 30k used 19518k 0x0fac0 0x0fc94c0 0x010 total time for which application threads were stopped 056410 seconds application time 00475220 seconds total time for which application threads were stopped 01800 seconds application time 10174830 seconds total time for which application threads were stopped 03820 seconds application time 10126350 seconds total time for which application threads were stopped 02750 seconds application time 10155910 secondstotal time for which application threads were stopped 02680 secondsapplication time 101580 seconds total time for which application threads were stopped 02880 seconds application time 10155480 seconds total time for which application threads were stopped 02970 seconds application time 09896810 seconds,['java'] +61606,close window xcodes installation alert that has no kind of closing elements is there a tool with which i can click on a window and the tool will tell me which process that window belongs to explanationi was working in xcode 323 for iphone os 40beta3wanted to install old xcode all old sdks got removed with beta3did not want to waste time so i kept working in new xcode for iphone os 40beta3 while downloading and then starting the installation of xcode 322 with iphone sdk 32after sometime there came this windowinstallation alertin order to continue installation please close the following applicationxcodebut by then i did not want to interrupt my programming session as i was near a next milestonewell next day and after a macbook standby i finally wanted to close the xcode with sdk 4beta3 and finally install the old sdkbut the installation alert wouldnt thisappear even though xcode was closed now so i thought ok then lets just stop and restart the xcode installation so i went to the activity monitor and stopped the xcode installation the xcode installation window got closed but the installation alert is still thereso how do you get rid of such a window it has no buttons no menu in which to select a close windoweditwell a restart of course solves this problem and i never faced this problem again,['iphone'] +61616,how to store a 64 bit integer in two 32 bit integers and convert back again i am pretty sure its just a matter of some bitwise operations i am just not entirely sure of exactly what i should be doing and all searches return back 64 bit vs 32 bit,['c++'] +61635,countering a div opacity if i have a div that acts like a box and i make it real sexy with 10 opacity how do i counter it since everything in the div also gets the opacity lets say i have a boxdiv with a 1px border and text putting opacity on it will make it look bad and i only want opacity on the background,['css'] +61637,rails routes matching query parameters rails routes are great for matching restful style separated bits of a url but can i match query parameters in a mapconnect config i want different controllersactions to be invoked depending on the presence of a parameter after the i was trying something like thismapconnect apimypathappleapplecode controller apples controller action my actionmapconnect apimypathbananabananacode controller bananas controller action my actionfor routing purposes i do not care about the value of the parameter as long as it is available to the controller in the params hash,['ruby-on-rails'] +61663,best way to detect similar email addresses i have a list of 20 email addresses some of which i know to be fraudulent attempts to get around a 1 per email limit such as etc i want to find similar email addresses for evaluation currently i am using a levenshtein algorithm to check each email against the others in the list and report any with an edit thistance of less than 2 however this is painstakingly slow is there a more efficient approachthe test code i am using now isusing systemusing systemcollectionsgenericusing systemlinqusing systemtextusing systemiousing systemthreadingnamespace levenshteinanalyzer class program const string input file cinputtxt const string output file coutputtxt static void mainstring args var inputwords filereadalinesinput file var outputwords new sortedsetstring for var i 0 i inputwordslength i if i 100 0 consolewritelineprocessing record i var word1 inputwordsitolower for var and i 1 and inputwordslength n if i n continue var word2 inputwordsntolower if word1 word2 continue if outputwordscontainsword1 continue if outputwordscontainsword2 continue var thistance levenshteinalgorithmcomputeword1 word2 if thistance 2 outputwordsaddword1 outputwordsaddword2 filewritealinesoutput file outputwordstoarray consolewritelinefound 0 words outputwordscount edit some of the stuff i am trying to catch looks like,['c#'] +61668,why does gcc need extra declarations in templates when vs does not templatetypename tclass baseprotected base t get return t t ttemplatetypename tclass derived public basetpublic basetget line a basett line b void foo t 4 get int main return 0 if i comment out lines a and b this code compiles fine under visual studio 2008 yet when i compile under gcc 41 with lines a and b commented i get these errorsin member function avoid derivedfooa error ata was not declared in this scope error there are no arguments to ageta that depend on a template parameter so a declaration of ageta must be availablewhy would one compiler require lines a and b while the other does not is there a way to simplify this in other words if derived classes use 20 things from the base class i have to put 20 lines of declarations for every class deriving from base is there a way around this that does not require so many declarations,['c++'] +61670,pip dealing with multiple python versions is there any way to make pip play well with multiple versions of python for example i want to use pip to explicitly install things to either my site 25 installation or my site 26 installationfor example with easy install i use easy install256and yes a i know about virtualenv and no a it is not a solution to this particular problem,['python'] +61677,print tchar on console i am quite sure that it is a stupid issue but it drives me crazyhow could i print on the console a tchar arraydword error wsagetlasterrortchar errmsg512int ret formatmessageformat message from system 0 error 0 errmsg 511 nulli need to print errmsg,['c++'] +61678,add centered text to the middle of a like line i am wondering what options one has in xhtml 10 strict to create a line on both sides of text likesosection one next section section twoi have thought of doing some fancy things like thisdiv stylefloatleft width 44hrdivdiv stylefloatright width 44hrdivnext sectionor alternatively because the above has problems with alignment both vertical and horizontaltabletrtd stylewidth47hrtdtd styleverticalalignmiddle textalign centernext sectiontdtd stylewidth47hrtdtrtablethis also has alignment problems which i solve with this messtabletrtd styleborderbottom 1px solid gray width 47nbsptdtd styleverticalalignmiddletextaligncenter rowspan2next sectiontdtd styleborderbottom 1px solid gray width 47nbsptdtrtrtdnbsptdtdnbsptdtrtablein addition to the alignment problems both options feel fudgy and i would be much obliged if you happened to have seen this before and know of an elegant solution,"['html', 'css']" +61679,how to use map element as text of a jcombobox i am populating a jcombobox using additem with all the elements of a collection each element in the collection is a hashmap so its a combobox of hashmapsmy question is given that i need each item to be a hashmap how do i set the text to apear in the combobox on the gui it needs to be the value of a certain key in the map normally if i am populating a combobox with my own type i would just overide the tostring methodbut i am not sure how to acheive this since i am using a java hashmap any ideas if possible without implementing my own hashmapupdate it seems like there is not anyway to avoid having the object int the jcombobox overide tostring if i want custom functionalityi wish there was a way to 1 specify the objects to be loaded into the jcombobox and 2 specify how these objects are to appear in the gui,['java'] +61690,how do i get the host and port in a rails application in a rails model i want to be able to find out the host and port for example if i am in a test environment it would return httplocalhost30 and if i was in production it would return something like,['ruby-on-rails'] +61705,ajax loading icon with updatepanel postbacks i have a form that is being dynamically built depending on user selection using ajax built in net ajax with updatepanelhow can i insert a standard ajax loading icon maybe have it attached to the mouse pointer while the postback is happening then remove it when the post back is finishedi do have the ajaxtoolkit installed if that helps,"['c#', 'asp.net']" +61724,is it bad practice to assign a css class for the sole purpose of finding it with jquery i am using aspnet not the newest one with that clientidmode stuff so the control ids are generated and funkythere are lots of ways of passing ids around but lately i have been assigning a fake css class to the control i am interested in then in a js file i use jquery to find the controlis this bad practice it seems a lot like the ajaxcontroltoolkit is behaviorid to me is the behaviorid bad practice as well,"['asp.net', 'jquery']" +61727,where are the readonlyconst in net in c youll see void funcconst t t everywhere however i havent seen anything similar in net whyi have notice a nice amount of parameters using struct but i see no functions with readonlyconst in fact now that i tried it i couldnt use those keywords to make a function that promises to not modify a list being passed in is there no way to promise the caller that this function will never modify the contents of list is there no way to say to call code and say this list should never be modified i know i can clone the list or look at documentation but i like compile errors sometime,['.net'] +61743,how to check if letter is upper or lower in php i have texts in utf8 with diacritic characters also and would like to check if first letter of this text is upper case or lower case how to do this,['php'] +61744,using weakreference to resolve issue with net unregistered event handlers causing memory leaks the problem registered event handlers create a reference from the event to the event handlers instance if that instance fails to unregister the event handler via thispose presumably then the instance memory will not be freed by the garbage collector example class foo public event action anevent public void doevent if anevent null anevent class bar public barfoo l lanevent l anevent void l anevent if i instantiate a foo and pass this to a new bar constructor then let go of the bar object it will not be freed by the garbage collector because of the anevent registrationi consider this a memory leak and seems just like my old c days i can of course make bar ithisposable unregister the event in the thispose method and make sure to call thispose on instances of it but why should i have to do thisi first question why events are implemented with strong references why not use weak references an event is used to abstractly notify an object of changes in another object it seems to me that if the event handlers instance is no longer in use ie there are no nonevent references to the object then any events that it is registered with should automatically be unregistered what am i missingi have looked at weakeventmanager wow what a pain not only is it very difficult to use but its documentation is inadequate see noticing the notes to inheritors section that has 6 vaguely described bulletsi have seen other thiscussions in various places but nothing i felt i could use i propose a simpler solution based on weakreference as described here my question is does this not meet the requirements with significantly less complexityto use the solution the above code is modified as follows class foo public weakreferenceevent anevent new weakreferenceevent internal void doevent aneventinvoke class bar public barfoo l lanevent l anevent void l anevent notice two things1 the foo class is modified in two ways the event is replaced with an instance of weakreferenceevent shown below and the invocation of the event is changed2 the bar class is unchangedno need to subclass weakeventmanager implement iweakeventlistener etcok so on to the implementation of weakreferenceevent this is shown here note that it uses the generic weakreferencet that i borrowed from here class weakreferenceevent public static weakreferenceevent operator weakreferenceevent wre action handler wre delegatesaddnew weakreferenceactionhandler return wre listweakreferenceaction delegates new listweakreferenceaction internal void invoke listweakreferenceaction toremove null foreach var del in delegates if delisalive deltarget else if toremove null toremove new listweakreferenceaction toremoveadel if toremove null foreach var del in toremove delegatesremovedel it is functionality is trivial i override operator to get the syntactic sugar matching events this creates weakreferences to the action delegate this allows the garbage collector to free the event target object bar in this example when nobody else is holding on to itin the invoke method simply run through the weak references and call their target action if any dead ie garbage collected references are found remove them from the listof course this only works with delegates of type action i tried making this generic but ran into the missing where t delegate in cas an alternative simply modify class weakreferenceevent to be a weakreferenceeventt and replace the action with actiont fix the compiler errors and you have a class that can be used like so class foo public weakreferenceeventint anevent new weakreferenceeventint internal void doevent aneventinvoke5 the full code with t and the operator for removing events is shown hereclass weakreferenceeventt public static weakreferenceeventt operator weakreferenceeventt wre actiont handler wreaddhandler return wre private void addactiont handler foreach var del in delegates if deltarget handler return delegatesaddnew weakreferenceactionthandler public static weakreferenceeventt operator weakreferenceeventt wre actiont handler wreremovehandler return wre private void removeactiont handler foreach var del in delegates if deltarget handler delegatesremovedel return listweakreferenceactiont delegates new listweakreferenceactiont internal void invoket arg listweakreferenceactiont toremove null foreach var del in delegates if delisalive deltargetarg else if toremove null toremove new listweakreferenceactiont toremoveadel if toremove null foreach var del in toremove delegatesremovedel hopefully this will help someone else when they run into the mystery event caused memory leak in a garbage collected world,"['c#', '.net']" +61755,when do you decide to use a visitors for your objects i always thought an object needs the data and the messages to act on it when would you want a method that is extrinsic to the object what rule of thumb do you follow to have a visitor this is supposing that you have full control of the object graph,['java'] +61762,find location using only thistance and bearing triangulation works by checking your angle to three known targetsi know the that is the lighthouse of alexandria it is located here xy on a map and it is to my right at 90 degrees repeat 2 more times for different targets and anglestrilateration works by checking your thistance from three known targetsi know the that is the lighthouse of alexandria it is located here xy on a map and i am 100 meters away from that repeat 2 more times for different targets and rangesbut both of those methods rely on knowing what youre looking at say youre in a forest and you cannot differentiate between trees but you know where key trees are these trees have been hand picked as landmarks you have a robot moving through that forest slowly do you know of any ways to determine location based solely off of angle and range exploiting geometry between landmarks note you will see other trees as well so you would not know which trees are key trees ignore the fact that a target may be occluded our prealgorithm takes care of that1 if this exists whats it called i cannot find anything2 what do you think the odds are of having two identical location hits i imagine it is fairly rare3 if there are two identical location hits how can i determine my exact location after i move the robot next i assume the chances of having 2 occurrences of exact angles in a row after i reposition the robot would be statistically impossible barring a forest growing in rows like corn would i just calculate the position again and hope for the best or would i somehow incorporate my previous position estimate into my next guessif this exists i would like to read about it and if not develop it as a side project i just do not have time to reinvent the wheel right now nor have the time to implement this from scratch so if it does not exist i will have to figure out another way to localize the robot since that is not the aim of this research if it does lets hope it is semieasy,"['java', 'c++']" +61763,where will log4net create this log file when i set the file value to logslogfiletxt where exactly will it create this folder in the bin directorymy webconfig looks like thislog4net appender namefileappender typelog4netappenderfileappender file valuelogslogfiletxt appendtofile valuetrue lockingmodel typelog4netappenderfileappenderminimallock layout typelog4netlayoutpatternlayout conversionpattern valuedate thread 5level logger propertyndc messagenewline layout appenderlog4netis this the correct way to logilog logger logmanagergetloggertypeofcontrollerloggererrorsome page ex where ex is the exception instance,['c#'] +61767,determine complex type from a primitive type using reflection i am writing a tool where i need to reflect upon methods and if the parameters of the methods are complex type then i need to certain type of actions such as instantiating them etcnow i saw the isprimitive property in the type variable however it shows string and decimal as complex types which technically is not incorrect however what i really want is to be able to thistinguish developer created class types from system defined data typesis there any way that i can do this,['c#'] +61784,taming the mallocfree beast tips tricks i have been using c on some projects for a masters degree but have never built production software with it net javascript are my bread and butter obviously the need to free memory that you malloc is critical in c this is fine well and good if you can do both in one routine but as programs grow and structs deepen keeping track of whats been mallocd where and whats appropriate to free gets harder and harderi have looked around on the interwebs and only found a few generic recommendations for this what i suspect is that some of you longtime c coders have come up with your own patterns and practices to simplify this process and keep the evil in front of you so how do you recommend structuring your c programs to keep dynamic allocations from becoming memory leaks,['c'] +61786,how do i create a random image name in c when i add a picture i want it to create a new random file name because if you add a picture with the same name it will just overwrite,['c#'] +61798,is possible to make sexy gui with javafx swing i would like to do a sexy userfriendly appealing gui in java swing is a limited in terms of skin customisation i am thinking about javafx but i do not it yet what can i achieve with this technology how hard is it do you have examples of reallife examples of swingjavafx integration i would like to do something in this spirit of this which is built on the net frameworkoriginal link edit is their any getting started overview sample code that i can read to get a general feeling of the work needed to be done to achieve something in the spirit of the screenshot maybe something like the miglayouts swing demo edit2 i found it is really basic though linked from,['java'] +61804,wpf wrappanel all items should have the same width i have a listbox whose itemspanel i have replaces with a wrappanelthe wrappanel now hosts the databound listboxitems each item has a variable sized text in it giving each item a different widthhowever i want the width to be constant so that all items have the same width as the item with the longest textis that possible,"['c#', '.net']" +61805,mac event tap just delays thiscarded events i am trying to write some code that thiscards all keyboard and mouse events when enabled on mac osx 106 my code runs as the root user the approach i am taking is to create an event tap that thiscards all events passed to it while enabled the event tap callback function looks like thiscgeventref mytapcallbackcgeventtapproxy proxy cgeventtype type cgeventref event void refcon return ckeylockerisenabled null eventand the code i am using to enable and thisable the event tap looks like thisvoid ckeylockerenablebool benable if benable m benabled return if benable which events are we interested in cgeventmask evmask kcgeventmaskforallevents cfmachportref mp cgeventtapcreatekcghideventtap kcgheadinserteventtap kcgeventtapoptiondefault evmask mytapcallback null if mp qdebug tap created and active mp mp m enabledtap mp m benabled true else cgeventtapenablem enabledtap false cfreleasem enabledtap m enabledtap 0 m benabled false qdebug tap destroyed and inactive this approach works very well while the event tap is active i can hammer on the keyboard and mouse as much as i want and no events make it through the system however when the tap is thisabled all the keys i pushed while the tap was active appear in the current window it is like the event tap is just delaying the events rather than destroying them which is odd since the mac documentation clearly statesif the event tap is an active filter your callback function should return one of the followingthe possibly modified event that is passed in this event is passed back to the event systema newlyconstructed event after the new event has been passed back to the event system the new event will be released along with the original eventnull if the event passed in is to be deletedi am returning null but the event does not seem to be deleted any ideas,['c++'] +61840,net remoting switching channels by itself we are having an odd problem with net remoting basically we have a server which registers two tcpchannels with channelservicesregisterchannel one listens on port 50other one listens on port 150 we then have a client that registers a tcpchannel to be able to communicate with the server we retrieve a an object from the server by calling activatorgetobject with the uri tcpserverip50objectnameand this works fine the client connects to the server on port 50 and gets the object however when we start calling methods on that object the connection to the channel on port 50 is dropped and a new connection is made to the channel on port 150 automatically this poses a real problem for us since we do not want traffic on port 150 because that channel may not be bound to the same network adapter as the port 50 channel on the server or that port may not be open in the firewall which causes the remoting calls to fail naturallythis is very strange to us since the client has no knowledge in our code that there exists another channel on the server on port 150 or what ip it listens on yet it attempt to connect to itany help on this is greatly appreciatedthankscasperthis is the code that sets up one of the server channels the one usually on port 50idictionary props new hashtablepropsport m tcpportpropsname stringemptybinaryserverformattersinkprovider serverprovider new binaryserverformattersinkproviderserverprovidertypefilterlevel systemruntimeserializationformatterstypefilterlevelfullbinaryclientformattersinkprovider clientprovider new binaryclientformattersinkproviderm tcpchannel new tcpserverchannel props clientprovider serverprovider channelservicesregisterchannel m tcpchannel false m wellknownobjref remotingservicesmarshal this server m tcpporttostring this is the code that sets up the other server channel usually on port 150idictionary props new hashtablepropsname stringemptypropsport ipportpropsbindto ipaddresstostring propstimeout remoting timeout timeout to prevent hung remoting callsif stringisnullorempty machinename propsmachinename machinename binaryserverformattersinkprovider serverprovider new binaryserverformattersinkprovider serverprovidertypefilterlevel systemruntimeserializationformatterstypefilterlevelfull binaryclientformattersinkprovider clientprovider new binaryclientformattersinkprovider m channel new tcpchannel props clientprovider serverprovider channelservicesregisterchannel m channel false m objref remotingservicesmarshal this queuename queuename is a guidthis is the code in the client that connects to the first server channel the one that is usually on port 50idictionary props new hashtablepropsport 0remotingconfigurationcustomerrorsmode customerrorsmodesoffbinaryserverformattersinkprovider serverprovider new binaryserverformattersinkproviderserverprovidertypefilterlevel systemruntimeserializationformatterstypefilterlevelfullbinaryclientformattersinkprovider clientprovider new binaryclientformattersinkproviderm tcpchannel new tcpclientchannelprops clientprovider serverproviderchannelservicesregisterchannelm tcpchannel false string address tcp profileremoteip profileremotetcpm server kernelactivatorgetobjecttypeofserver address server port,"['c#', '.net']" +61844,rails initializer for development and production i have the following code in configinitializerschargifyrbchargifyconfigure do c csubdomain example capi key 123xyzendbut i have different settings for development and productionso how would i have a different set of variables values based on environment,['ruby-on-rails'] +61877,get name of property as a string see below solution i created using the answer i acceptedi am trying to improve the maintainability of some code involving reflection the app has a net remoting interface exposing among other things a method called execute for accessing parts of the app not included in its published remote interface here is how the app designates properties a static one in this example which are meant to be accessible via executeremotemgrexposepropertysomesecret typeofsomeclass somepropertyso a remote user could call string response remoteobjectexecutesomesecretand the app would use reflection to find someclasomeproperty and return its value as a stringunfortunately if someone renames someproperty and forgets to change the 3rd parm of exposeproperty it breaks this mechanismi need to the equivalent of someclasomepropertygetthenameofthispropertyasastringto use as the 3rd parm in exposeproperty so refactoring tools would take care of renamesis there a way to do this thanks in advanceokay heres what i ended up creating based upon the answer i selected and the question he referenced summary get the name of a static or instance property from a property access lambda summary typeparam namettype of the propertytypeparam param namepropertylambdalambda expression of the form classproperty or objectpropertyparam returnsthe name of the propertyreturnspublic string getpropertynametexpressionfunct propertylambda var me propertylambdabody as memberexpression if me null throw new argumentexceptionyou must pass a lambda of the form classproperty or objectproperty return memembername usage static propertystring name getpropertyname someclasomeproperty instance propertystring name getpropertyname someobjectsomepropertynow with this cool capability it is time to simplify the exposeproperty method polishing doorknobs is dangerous workthanks everyone,['c#'] +61879,mobile webkit browsers settimeout and inactive pages i have a question regarding how mobile webkit browsers ie mobile safari and android browser handle settimeout function when the page becomes inactive and is reactivated againlet us assume the page becomes inactive ie the phone screen goes to sleep we open another application we open another webpage and the settimeout function should have been activated before the page becomes active againnow to me it seems thatmobile safari executes the function as soon as the page is activatedandroid browsermight execute the function as usual ie javascript continues running even if the page is inactivemight execute as soon as the page is activated a la mobile safarimight not execute at alli was wondering if someone knows the exact rules,['javascript'] +61885,how do i wait for a c event to be raised i have a sender class that sends a message on a ichannelpublic class messageeventargs eventargs public message message get private set public messageeventargsmessage m message m public interface ichannel public event eventhandlermessageeventargs messagereceived void sendmessage mpublic class sender public const int maxwaitinms 50 private ichannel c public message sendmessage m csendm wait for maxwaitinms to get an event from cmessagereceived return the message or null if no message was received in response when we send messages the ichannel sometimes gives a response depending on what kind of message was sent by raising the messagereceived event the event arguments contain the message of interesti want sendersend method to wait for a short time to see if this event is raised if so i will return its messageeventargsmessage property if not i return a null messagehow can i wait in this way i would prefer not to have do the threading legwork with manualresetevents and such so sticking to regular events would be optimal for me,['c#'] +61889,casting doubles to integers in order to gain speed in rethis there are scores associated to elements in order to take this elements sorted this scores are doubles even if many users actually sort by integers for instance unix timeswhen the database is saved we need to write this doubles ok thisk this is what is used currently snprintfcharbuf1sizeofbuf117gvaladditionally infinity and notanumber conditions are checked in order to also represent this in the final database fileunfortunately converting a double into the string representation is pretty slow while we have a function in rethis that converts an integer into a string representation in a much faster way so my idea was to check if a double could be casted into an integer without lost of data and then using the function to turn the integer into a string if this is truefor this to provide a good speedup of course the test for integer equivalence must be fast so i used a trick that is probably undefined behavior but that worked very well in practice something like thatdouble x some value if x doublelong longx use the fast integer functionlong longxelse use the slow snprintfxin my reasoning the double casting above converts the double into a long and then back into an integer if the range fits and there is no decimal part the number will survive the conversion and will be exactly the same as the initial numberas i wanted to make sure this will not break things in some system i joined c on freenode and i got a lot of insults so i am now trying hereis there a standard way to do what i am trying to do without going outside ansi c otherwise is the above code supposed to work in all the posix systems that currently rethis targets that is archs where linux mac os x bsd solaris are running nowadaywhat i can add in order to make the code saner is an explicit check for the range of the double before trying the cast at allthank you for any help,['c'] +61890,how do i get the time difference between two datetime objects using c how do i get the time difference between two datetime objects using c,['c#'] +61895,calling a getter multiple times or calling once and assigning to a variable say suppose i have class as public class age private int age public int getage return thisage in my main class i am calling the getage method many timesso i wanted to know is it advisable to call so many times or call once and assign it to some variable and use that variable which is best and why,['java'] +61903,how to include the total number of returned rows in the resultset from select tsql command i would like to ask if there is a way to include the total number of rows as an additional column in the returned result sets from a tsql query using also the row number sql 2005 command for example getting the results set from a query against book table in a form similar to thisrownum bookid booktitle totalrows1 1056 title1 5 2 1467 title2 5 3 121 title3 5 4 1789 title4 5 5 789 title5 5the query is part of custom paging functionality implemented in a stored procedure the goal is to return back only the records for the current page index and limited to the page size but also the amount of total number of records in the select statement in order to determine the total number of resultset pages,['sql'] +61912,different behaviour of method overloading in c i was going through c brainteasers and came across one question what should be the output of this codeclass base public virtual void fooint x consolewriteline basefooint class derived base public override void fooint x consolewriteline derivedfooint public void fobject o consolewriteline derivedfobject class test static void main derived d new derived int i 10 dfooi it prints derivedfobject but if i change the code to class derived public void fooint x consolewritelinederivedfooint public void fobject o consolewritelinederivedfobject class program static void mainstring args derived d new derived int i 10 dfooi prints derivedfooint consolereadkey i want to why the output is getting changed when we are inheriting vs not inheriting why is method overloading behaving differently in these two cases,['c#'] +61919,system call to map memory to a file descriptor inverse mmap i want to be able to map memory to a file descriptor so i can use some existing functions that need a file descriptor heres essentially what i am looking forvoid do operation1int fdchar datadata max embedded binary data int fd addr to fddata data maxdo operation1fd operate on fd what system call or calls can i use to accomplish this,['c'] +61929,selenium how to click an html button element i have button on the page that being used as a link to another page so when the user clicks the button they are redirected to the right pagei am using the selenium extension for phpunit and i would like to test that the button is correctly redirecting the user here is the html that i am trying to testbutton onclickwindowlocationsponsor valuecontinue typebutton idsponsorcontinue namesponsorcontinuecontinuebuttoni have tried a lot of different approaches to click the button but i cannot seem to get any of them to workthisclickbuttonidsponsorcontinuethis command executes and does not throw any errors but the page is not redirected it works fine when i manually click the button what should i do,['php'] +61942,showing a diff between two bodies of text in rails is there an easy way to do this create marked up text that shows the changes between two pieces of text a builtin helper maybe looked but could not find,['ruby-on-rails'] +61946,c objectivec preprocessor output is there a way to get preprocessed cobjectivec code i have some files i acquired and would like to see the code produced by some defines,"['objective-c', 'c']" +61947,make square image how to resample an image to square padding with white background in c preferable without using any 3rd party libraries net framework onlythanks,"['c#', '.net']" +61954,troubleshooting net fatal execution engine error summaryi periodically get a net fatal execution engine error on an application which i cannot seem to debug the dialog that comes up only offers to close the program or send information about the error to microsoft i have tried looking at the more detailed information but i do not know how to make use of iterrorthe error is visible in event viewer under applications and is as followsnet runtime version 20507273607 fatal execution engine error 7a09795e 80131506the computer running it is windows xp professional sp 3 intel core2quad q6600 24ghz w 20 gb of ram other netbased projects that lack multithreaded downloading see below seem to run just fineapplicationthe application is written in cnet 35 using vs2008 and installed via a setup projectthe app is multithreaded and downloads data from multiple web servers using systemnethttpwebrequest and its methods i have determined that the net error has something to do with either threading or httpwebrequest but i have not been able to get any closer as this particular error seems impossible to debugi have tried handling errors on many levels including the following in programcs handle ui thread exceptionsapplicationthreadexception application threadexception handle nonui thread exceptionsappdomaincurrentdomainunhandledexception currentdomain unhandledexceptionapplicationenablevisualstylesapplicationsetcompatibletextrenderingdefaultfalse force all windows forms errors to go through our handlerapplicationsetunhandledexceptionmodeunhandledexceptionmodecatchexceptionmore notes and what i have triedinstalled visual studio 2008 on the target machine and tried running in debug mode but the error still occurs with no hint as to where in source code it occurredwhen running the program from its installed version release the error occurs more frequently usually within minutes of launching the application when running the program in debug mode inside of vs2008 it can run for hours or days before generating the errorreinstalled net 35 and made sure all updates are appliedbroke random cubicle objects in frustrationrewritten parts of code that deal with threading and downloading in attempts to catch and log exceptions though logging seemed to aggravate the problem and never provided any dataquestionwhat steps can i take to troubleshoot or debug this kind of error memory dumps and the like seem to be the next step but i am not experienced at interpreting them perhaps there is something more i can do in the code to try and catch errors it would be nice if the fatal execution engine error was more informative but internet searches have only told me that it is a common error for a lot of netrelated items,['.net'] +61960,php image resize on the fly vs storing resized images i am building a image sharing site and would like to know the pros and cons of resizing images on the fly with php and having the resized images stored which is faster which is more reliablehow big is the gap between the two methods in speed and performance please note that either way the images go through a php script for statistics like views or if hotlinking is allow etc so is not like it will be a direct link for images if i opt to store the resize imagesi will appreciated your comments or any helpful links on the subject,['php'] +61964,what kinds of questions are technical support incidents for last year i received two technical support incidents in the iphone developer program but when i went to renew i found that i would lose them i have another two for this year but i am not really sure about the kind of problems that can be solved by using them what kinds of questions are the best use of these technical support incidents what is the kind of problem i can use them for what do you receive when you use them thanks,"['iphone', 'objective-c']" +61973,how to convert an nsstring to an unsigned int in cocoa my application gets handed an nsstring containing an unsigned int nsstring does not have an mystring unsignedintegervalue method i would like to be able to take the value out of the string without mangling it and then place it inside an nsnumber i am trying to do it like sonsstring myunsignedintstring self somemethodreturningastringnsinteger myinteger myunsignedintstring integervaluensnumber mynsnumber nsnumber numberwithintegermyinteger put mynumber in an nsdictionary time passes pull it out later onunsigned int myunsignedint mynsnumber unsignedintvaluewill the above potentially cut off the end of a large unsigned int since i had to convert it to nsinteger first or does it look ok to use if it will cut off the end of it how about the following a bit of a kludge i thinknsstring myunsignedintstring self somemethodreturningastringlong long mylonglong myunsignedintstring longlongvaluensnumber mynsnumber nsnumber numberwithlonglongmylonglong put mynumber in an nsdictionary time passes pull it out later onunsigned int myunsignedint mynsnumber unsignedintvaluethanks for any help you can offer,['objective-c'] +61977,conditionally add htmlattributes to aspnet mvc htmlactionlink i am wondering if it is possible to conditionally add a parameter in a call to a methodfor example i am rendering a bunch of links six total for navigation in my sitemaster htmlactionlinkabout about pages htmlactionlinkcontact contact pages etc etc i would like to include a css class of selected for the link if it is on that page so in my controller i am returning thisviewdataaddcurrentpage aboutreturn viewand then in the view i have an htmlattributes dictionary dictionarystringobject htmlattributes new dictionarystringobject htmlattributesaddclaselectednow my only question is how do i include the htmlattributes for the proper actionlink i could do it this way for each link htmlattributesclear if viewdatacurrentpage contact htmlattributesaddclaselected htmlactionlinkcontact contact pages htmlattributes but that seems a little repetitive is there some way to do something like this psuedo code htmlactionlinkcontact contact pages ifviewdatacurrentpage contact htmlattributes that is obviously not valid syntax but is there a correct way to do that i am open to any totally different suggestions for rendering these links i would like to stay with something like actionlink that takes advantage of using my routes though instead of hard coding the tag,['c#'] +61982,how to generate android styled javadocs is it possible to generate android styled javadocs for my android project like instead of is it something regarding using of some custom doclet instead of standard doclet if yes then which one i have to use,['android'] +61983,generate a polygon from line i want to draw a line with thickness in j2me this can easily be achieved in desktop java by setting pen width as thickness value however in j2me pen class does not support width my idea is to generate a polygon from the line i have that resembles the line with thickness i want to draw in picture on the left is what i have a line with points on the right is what i want a polygon that when filled a line with thickness could anyone know how to generate a polygon from line,['c#'] +61994,how to use an output parameter in java could someone please give me some sample code that uses an output parameter in function i have tried to google it but just found it just in functions i would like to use this output value in another functionthe code i am developing intended to be run in android,"['java', 'android']" +62020,log client side errors to the server possible duplicatelogging clientside javascript errors on server how can i log client side javascript errors to the server i am using jquery and mvc,"['javascript', 'jquery']" +62027,sending email with attachments from c attachments arrive as part 12 in thunderbird i have a c application which emails out excel spreadsheet reports via an exchange 2007 server using smtp these arrive fine for outlook users but for thunderbird and blackberry users the attachments have been renamed as part 12i found this article which describes the problem but does not seem to give me a workaround i do not have control of the exchange server so cannot make changes there is there anything i can do on the c end i have tried using short filenames and html encoding for the body but neither made a differencemy mail sending code is simply thispublic static void sendmailstring recipient string subject string body string attachmentfilename smtpclient smtpclient new smtpclient networkcredential basiccredential new networkcredentialmailconstusername mailconstpassword mailmessage message new mailmessage mailaddress fromaddress new mailaddressmailconstusername setup up the host increase the timeout to 5 minutes smtpclienthost mailconstsmtpserver smtpclientusedefaultcredentials false smtpclientcredentials basiccredential smtpclienttimeout 60 5 10 messagefrom fromaddress messagesubject subject messageisbodyhtml false messagebody body messagetoaddrecipient if attachmentfilename null messageattachmentsaddnew attachmentattachmentfilename smtpclientsendmessagethanks for any help,['c#'] +62030,does in array use a binary search algorithm i have a largish array of string that i want to use as a lookupi am using in array but i suspect its doing a simple loop through does anyone know whether the in array algo uses a bsearch algo,['php'] +62083,c configuration manager connectionstrings i have a console app containing an application configuration file containing one connection string as shown belowconfiguration connectionstrings add nametarget connectionstringservermyserver databasemydb integrated securitysspi connectionstringsconfigurationwhen i pass this to my connection usingconfigurationmanagerconnectionstrings1tostringi have two values in there hence using the second in the collection my question is where is this second coming fromi have checked the bin version and original and its not mine its obviously a system generated one but i have not seen this before can anyone enlighten methe mystery connection string isdata sourcesqlexpress integrated securitysspiattachdbfilenamedatadirectoryaspnetdbmdf user instancetruethis is not a problem as such i would just like to know why this is occuring thanks in advancefor future reference to those who may or may not stumble on this after thiscovering the machineconfig it is become apparent it is bad practice to refer to a config by its index as each stack will potentially be different which is why keys are usedin this instance my code would beconfigurationmanagerconnectionstringstargettostringcheers all,['c#'] +62085,sql for sorting boolean column as true null false my table has three boolean fields f1 f2 f3 if i doselect from table order by f1 f2 f3the records will be sorted by these fields in the order false true null i wish to order them with null in between true and false the correct order should be true null falsei am using postgresql,['sql'] +62088,friend functions and operator overloading what is the proper way to overload an operator for a class in a project i am working on i have a score class defined below in scoreh i am trying to overload it so when a operation is performed on it points name is printed heres what i tried to doostream scoreoperator ostream os score right os rightgetpoints rightscoregetname return oshere are the errors returnedscoreh30 error c2804 binary operator has too many parametersthis error appears 4 times actuallyi managed to get it working by declaring the overload as a friend functionfriend ostream operator ostream os score rightand removing the score from the function declaration in scorecpp effectively not declaring it as a memberwhy does this work yet the former piece of code does notthanks for your timeediti deleted all mentions to the overload on the header file yet i get the following and only error binary no operator found which takes a righthand operand of type score or there is no acceptable conversion how come my test in main cannot find the appropriate overload it is not the includes i checkedbelow is the full scorehifndef score h define score h include stringinclude iostreaminclude iostreamusing stdstringusing stdostreamclass scorepublic scorestring name score virtual score void addpointsint n string scoregetname const int getpoints const void scoresetnamestring name bool operatorconst score right constprivate string name int pointsendif,['c++'] +62111,mktime php datetimestamp ymmdd i need to query mysql for the current date from php in ymmdd format anyone,['php'] +62139,c referencing a type in a dynamically generated assembly i am trying to figure out if it is possible when you are dynamically generating assemblies to reference a type in a previously dynamically generated assemblyfor exampleusing systemusing systemcodedomcompilerusing systemreflectionusing microsoftcsharpcodedomprovider provider new csharpcodeprovidercompilerparameters parameters new compilerparametersparametersgenerateinmemory truecompilerresults results providercompileassemblyfromsourceparameters namespace dynamic public class a assembly assem resultscompiledassemblycodedomprovider provider2 new csharpcodeprovidercompilerparameters parameters2 new compilerparametersparameters2referencedassembliesaddassemfullnameparameters2generateinmemory truecompilerresults results2 provider2compileassemblyfromsourceparameters2 namespace dynamic public class b a if results2errorshaserrors foreach compilererror error in results2errors consolewritelineerrorerrortext else assembly assem2 results2compiledassemblythis code prints the following on the console the type or namespace name a could not be found are you missing a using directive or an assembly referencei have tried it lots of different ways but nothing seems to be working am i missing something is this even possibleedit fixing the bug in the code provides this error insteadmetadata file l0livsmn version0 cultureneutral publickeytokennull could not be foundedit2 bit of a side note but changing generateinmemory to false and doing parameters2referencedassembliesaddassemlocation will cause it to compile correctly but i would greatly prefer to reference the assembly that is directly in memory rather than outputting temporary files,['c#'] +62147,jquery noconflict not working in ie8 only i have a website using the prootype framework and i am looking to use a jquery plugin everything works just not in ie8 it works in ie7 which amazes me any idea what maybe wrong ie8 gives me object doesnt support this property or method where line jquerynoconflict isscript srcmydocsjqueryjs typetextjavascriptscriptscript srcmydocsjquerysimplyscrolljs typetextjavascript scriptscript typetextjavascriptjquerynoconflictfunction openupsurl windowopensurlnullheight560width820statusyestoolbaryesmenubaryeslocationyesresizableyesscrollbarsyesfalse jquerydocumentreadyfunction headappendlink css headchildrenlast cssattr rel stylesheet type textcss href mydocsjquerysimplyscrollcss scrollersimplyscroll automode loop framerate 1 speed 1 scripti also tired the following var j jquerynoconflict var j jquerynoconflicteverythig works just not in ie8 alone,"['javascript', 'jquery']" +62148,matching ids in beautifulsoup i am using beautifulsoup python module i have to find any reference to the divs with id like postfor examplediv idpost45divdiv idpost334divhow can i filter thishtml div idpost45div div idpost334divsouphandler beautifulsouphtmlprint souphandlerfindalldiv idpost,['python'] +62154,force a uiview to redraw immediately instead of during next run loop i have created a uiimagepicker camera view with a toolbar and custom button for taking a snapshot i cannot really change to using the default way because of the custom button and i am drawing on top of the viewwhen you hit the button i want to take a screenshot using uigetscreenimage however the toolbar is showing up in the image even if i hide it firsthide the toolbarselftoolbarhidden yes capture the screen pixelscgimageref screencap uigetscreenimagei am pretty sure this is because even though the toolbar is hidden it gets redrawn once the function returns and we enter the next run loop after uigetscreenimage is calledi tried making the following addition but it did not helphide the toolbarselftoolbarhidden yes selftoolbar drawrectcgrectmake0 0 320 52 capture the screen pixelscgimageref screencap uigetscreenimagei also tried using setneedsthisplay but that does not work either because once again the draw happens after the current function returnsany suggestions thanks,['iphone'] +62157,does a multithreaded crawler in python really speed things up was looking to write a little web crawler in python i was starting to investigate writing it as a multithreaded script one pool of threads downloading and one pool processing results due to the gil would it actually do simultaneous downloading how does the gil affect a web crawler would each thread pick some data off the socket then move on to the next thread let it pick some data off the socket etc basically i am asking is doing a multithreaded crawler in python really going to buy me much performance vs single threadedthanks,['python'] +62158,wanting a simple overview on how to connect to a sqlite database in cocoaobjectivec everyone i have been experimenting with cocoa and objectivec programming on the mac for a few months now and i am wanting to start developing applications that manage large amounts of data the trouble is i am not really sure where to start with databases i have a good background in java programming with sqlite i have read a bit about coredata and i have not been able to find any good resources for just manually connecting to the database i am looking for recommendations should i try coredata and if so can anyone recommend a good tutorial for someone new to the language or should i try to manually connect and query an sqlite database somehow and if so any tutorials any help would be greatly appreciatedthanks,['objective-c'] +62195,what is output buffering what is output buffering and why is one using it in php,['php'] +62207,how do i track the visitors country and redirect them to appropriate sites i want to track the country of the visitors and then redirect them to appropriate subdomains of my site like what google doesand upto what extent i can rely on the data of the api if i should use anyi am using php,['php'] +62211,how to return an error in an ajax scenario i am using aspnet mvc with jquery i have the following mvc action that returns a partial page on success on application error i am not sure what to send it for correctly handling it at the client sidepublic actionresult loadfiltersetint filtersetid try breadcrumbmanager bcmanager thisresetbreadcrumbmanagerthisbreadcrumbmanagerid generalhelperloadbreadcrumbmanagerbcmanager filtersetid viewdatabreadcrumbmanager bcmanager return viewloadfilterset catch exception ex return content following is my jquery ajax call notice that i am checking for the data length to make sure there are no errors please suggest me a better way of doing thisajax type get datatype html async true data filtersetid selectedid url link contenttype texthtml charsetutf8 success functiondata textstatus if datalength 0 clear the local filters first clearlocalfilters tdselectedfilters tablefiltersthisplayappenddata,"['jquery', 'asp.net']" +62218,does c99 guarantee that arrays are contiguous following an hot comment thread in another question i came to debate of what is and what is not defined in c99 standard about c arraysbasically when i define a 2d array like int a55 does the standard c99 garantee or not that it will be a contiguous block of ints can i cast it to int a and be sure i will have a valid 1d array of 25 intsas i understand the standard the above property is implicit in the sizeof definition and in pointer arithmetic but others seems to thisagree and says casting to int the above structure give an undefined behavior even if they agree that all existing implementations actually allocate contiguous valuesmore specifically if we think an implementation that would instrument arrays to check array boundaries for all dimensions and return some kind of error when accessing 1d array or does not give correct access to elements above 1st row could such implementation be standard compilant and in this case what parts of the c99 standard are relevant,['c'] +62236,calling template function without type inference if i have a function template with typename t where the compiler can set the type by itself i do not have to write the type explicitly when i call the function liketemplate typename t t min t v1 t v2 return v1 v2 v1 v2int i1 1 i2 2 int i3 min i1 i2 no explicit type but if i have a function template with two different typenames liketemplate typename tout typename tin tout round tin v return tout v 05 double d 154int i roundintd explicit intis it true that i always have to specify at least 1 typename i assume the reason is because c can not thistinguish functions between different return typesbut if i use a void function and handover a reference again i must not explicitly specify the return typenametemplate typename tout typename tin void round tout vret tin vin vret toutvin 05 double d 154 int i roundi d no explicit intshould the conclusion be to avoid functions with return and more prefer void functions that return via a reference when writing templates or is there a possibility to avoid explicitly writing the return type something like type inference for templates is type inference possible in c0x,['c++'] +62241,how are developers using source control i am trying to find the most efficient way to do source control in a small dev environment i work in a group of 4 net developers we rarely work on the same project at the same time but it does happen from time to timewe use tfs for source control my most recent example is a project i just placed into production last night that included 2 wcf services and a web application front end i worked out of a branch called prod because the application is brand new and has never seen the light of day now that the project is live i need to branch off the prod branch for features bugs etcso what is the best way to do this do i simple create a new branch and sort of archive the old branch and never use it again do i branch off and then merge my branch changes back into the prod branch when i want to deploy to productionand what about the file and assembly version they are currently at 10 when do they change and why if i fix a small bug which number changes if any if i add a feature which number changes if anywhat i am looking for is what you have found to be the best way to efficiently manage source control most places i have worked always seem to bang heads with the source control system in on way or another and i would just like to find out what you have found that works the best,"['c#', '.net', 'asp.net']" +62258,get checkbox value in jquery how can i get a checkboxs value in jquery,"['jquery', 'html']" +62270,how to make a horizontal ui table view on iphone normally the uitableview is something like this cell 1 cell 2 cell 3 cell 4 but i want to make my own uitableview like this c c c e e e l l l l l l 1 2 3 and i want the user swipe left and right to have the similar behavior like the original uitableview how can i do this thank you,"['objective-c', 'iphone']" +62272,what c container is most resourceefficient for existence for only one operation i find myself often with a situation where i need to perform an operation on a set of properties the operation can be anything from checking if a particular property matches anything in the set to a single iteration of actions sometimes the set is dynamically generated when the function is called some built with a simple linq statement other times it is a hardcoded set that will always remain the same but one constant always exists the set only exists for one single operation and has no use before or after itmy problem is i have so many points in my application where this is necessary but i appear to be very very inconsistent in how i store these sets some of them are arrays some are lists and just now i have found a couple linked lists now none of the operations i am specifically concerned about have to care about indices container size order or any other functionality that is bestowed by any of the individual container types i picked resource efficiency because it is a better idea than flipping coins i figured since array size is configured and it is a very elementary container that might be my best choice but i figure it is a better idea to ask around alternatively if there is a better choice not out of resourceefficiency but strictly as being a better choice for this kind of situation that would be nice as well,['c#'] +62279,is there thing like pass by value pass by reference in javascript when i started learning function in c its all around pass by value and reference is there something similar we have in javascript if yesnot how it works in case of javascriptthanks all,['javascript'] +62280,how to establish a connection pool in jdbc can anybody provide examples or links on how to establish a jdbc connection poolfrom searching google i see many different ways of doing this and it is rather confusingultimately i need the code to return a javasqlconnection object but i am having trouble getting startedany suggestions welcomeupdate does not javaxsql or javasql have pooled connection implementations why wouldnt it be best to use these,['java'] +62284,how do i link to part of a page hash how do you link with a so that the browser goes to certain subheading on the target page as opposed to the top,['html'] +62289,case insenstive string replace that correctly works with ligatures like a ss i have build a litte aspnet form that searches for something and thisplays the results i want to highlight the search string within the search results examplequery presults abpbple banana bpblumthe code that i have goes like thispublic static string highlightsubstringstring text string substring var index textindexofsubstring stringcomparisoncurrentcultureignorecase ifindex 1 return httputilityhtmlencodetext string p0 p1 p2 textsplitatindex index substringlength out p0 out p1 out p2 return httputilityhtmlencodep0 b httputilityhtmlencodep1 b httputilityhtmlencodep2i mostly works but try it for example with highlightsubstringa ss this crashes because in germany a and ss are considered to be equal by the indexof method but they have different lengthnow that would be ok if there was a way to find out how long the match in text is remember that this length can be substringlengthso how do i find out the length of the match that indexof produces in the presence of ligatures and exotic language characters ligatures in this case,['.net'] +62290,how do i configure structuremap to use a generic repository i have an interface igenericrepositorytentity where tentity ientity and an implementation genericrepositorytentity where tentity entityi am trying to inject a specific igenericrepositorysection into a class using structuremap objectfactoryinitializex xfortypeofigenericrepositoryusetypeofgenericrepository but when i try to use objectfactorygetinstanceigenericrepositorysection i getstructuremap exception code 202 no default instance defined for pluginfamily systemdatacommondbconnectionany ideas why this is or what i am doing wrongthanks in advancesimon,['c#'] +62301,how to use boostbind with noncopyable params for example boostpromise some c objects have no copy constructor but have move constructorfor example boostpromisehow can i bind those objects using their move constructors include boostthreadhppvoid fullfil 1boostpromiseint prom int x promset valuexboostfunctionvoid get functor boostpromise is not copyable but movable boostpromiseint pi compilation error boostfunctionvoid f set one boostbindfullfil 1 pi 1 compilation error as well boostfunctionvoid f set one boostbindfullfil 1 stdmovepi 1 ps i know it is possible to bind a pointer to the object instead of the object itself but it is weird solution in this case i will have to take cake about lifetime of the object instead of delegating that to boostbind by moving object into boostfunction object weird pi will be destroyed on leaving the scope boostfunctionvoid f set one boostbindfullfil 1 boostrefpi 1 return f set one,['c++'] +62302,c how to efficiently find out if any string in a vector can be assembled from a set of letters i am implementing a textbased version of scrabble for a college projecti have a vector containing around 400k strings my dictionary and at some point in every turn i am going to have to check if there is still a word in the dictionary which can be formed with the pieces in the players hand i am checking if the player has any move left if not it is game over for the player in questionmy only solution to this is iterating through the string one by one and using a subroutine i have to check if the string in question can be formed from the players pieces i will implement a quickfail checking if the user has any vowels but it will still be woefully inefficientthe textfile containing the dictionary is already alphabetically ordered so the vector is sortedany suggestionsa problem was presented in the comments below any suggestion on how do i take the letters already on the board into account,['c++'] +62318,jquery intercepting out going link and adding parameters when a user clicks a link on my page i need to before it gets actioned by the browser add the param hellotrue to the urlso the user clicks mypageaspx in and gets sent to mypageaspxhellotrue insteadhas to be client side preferably using jqueryi can add an attribute to the tags if neededian,['jquery'] +62320,how would you start automating my job part 2 followup to this questionafter surviving the first wave of incoming shipments 9 hours of copypaste i now believe i have all the requirementshere is the updated workflowmonkey collects email attachments 4 excel spreadsheets 1 pdfmonkey creates central database does complex calculations right now this is also an excel spreadsheetmonkey sends data to two bosses who set the retail prices independently first one to reply winsmonkey sends order form to our other warehouses also excelmonkey sends spreadsheets to vip customers carefully sanitized and formatted 4 different thiscount categoriesjurily enters the data into the accounting system i have given up on automating this part there is too much business logic involved and the database is a pile of shw legacymy question what technologies would you use for a quick and dirty solution i am mostly sold on c but coming from a linuxc background i am horribly confused about my choices in microsoftlandfor bonus points how would you redesign the whole system from the ground upclarification i am looking for basically anything that has the potential to get me reading the right things just give me the keywords and a short description google will guide me from thereps in case you were wondering my job title is system administrator,['c#'] +62327,why does not java warn about a something this might sound stupid but why does not the java compiler warn about the expression in the following if statementstring a somethingifa something systemoutprintlna is equal to somethingelse systemoutprintlna is not equal to somethingi realize why the expression is untrue but afaik a can never be equal to the string literal something the compiler should realize this and at least warn me that i am an idiot who is coding way to late at night clarificationthis question is not about comparing two string object variables it is about comparing a string object variable to a string literal i realize that the following code is useful and would produce different results than equalsstring a ireturnastringstring b ireturnadifferentstringifa b systemoutprintlna is equal to belse systemoutprintlna is not equal to bin this case a and b might actually point to the same area in memory even if it is not because of interning in the first example though the only reason it would be true is if java is doing something behind the scenes which is not useful to me and which i cannot use to my advantage follow up questioneven if a and the stringliteral both point to the same area in memory how is that useful for me in an expression like the one above if that expression returns true there is not really anything useful i could do with that knowledge is there if i was comparing two variables then yes that info would be useful but with a variable and a literal it is kinda pointless,['java'] +62334,open existing file append a single line i want to open a text file append a single line to it then close it,['c#'] +62336,lock statement vs monitorenter method i suppose that this is an interesting code example we have a class let us call it test with a finalize method in the main method there are two code blocks where i am using a lock statement and a monitorenter call also i have two instances of the test class herethe experiment is pretty simple null the test variable within locking block and then try to collect it manually with the gccollect method callso to see the finalize call i am calling the gcwaitforpendingfinalizers method everything is very simple as you can seeby the definition of the lock statement it is opened by the compiler to the tryfinally block with a monitorenter call inside of the try block and monitor then it exits in the finally block i have tried to implement the tryfinally block manuallyi have expected the same behaviour in both cases that of using lock and that of using monitorenter but surprise surprise it is different as you can see belowpublic class test private string name public teststring name thisname name test consolewritelinestringformatfinalizing class name 0 name class program static void mainstring args var test1 new testtest1 var test2 new testtesst2 lock test1 test1 null consolewritelinemanual collect 1 gccollect gcwaitforpendingfinalizers consolewritelinemanual collect 2 gccollect var locktaken false systemthreadingmonitorentertest2 ref locktaken try test2 null consolewritelinemanual collect 3 gccollect gcwaitforpendingfinalizers consolewritelinemanual collect 4 gccollect finally systemthreadingmonitorexittest2 consolereadline the output of this example ismanual collect 1 manual collect 2 manual collect 3 finalizing class name test2 manual collect 4 and null reference exception in last finally block because test2 is null referencei was surprised and thisassembled my code into il so here is the il dump of main methodentrypointmaxstack 2locals init 0 class consoleapplication2test test1 1 class consoleapplication2test test2 2 bool locktaken 3 bool s locktaken0 4 class consoleapplication2test cs20 5 bool cs401l 0 nop l 01 ldstr test1l 06 newobj instance void consoleapplication2testctorstringl 0b stloc0 l 0c ldstr tesst2l 0011 newobj instance void consoleapplication2testctorstringl 0016 stloc1 l 0017 ldci40 l 0018 stloc3 l 0019 ldloc0 l 001a dup l 001b stlocs cs20l 001d ldlocas s locktaken0l 001f call void mscorlibsystemthreadingmonitorenterobject booll 0024 nop l 0025 nop l 0026 ldnull l 0027 stloc0 l 0028 ldstr manual collectl 002d call void mscorlibsystemconsolewritelinestringl 0032 nop l 0033 call void mscorlibsystemgccollectl 0038 nop l 0039 call void mscorlibsystemgcwaitforpendingfinalizersl 003e nop l 003f ldstr manual collectl 0044 call void mscorlibsystemconsolewritelinestringl 0049 nop l 004a call void mscorlibsystemgccollectl 004f nop l 0050 nop l 0051 leaves l 0066l 0053 ldloc3 l 0054 ldci40 l 0055 ceq l 0057 stlocs cs401l 0059 ldlocs cs401l 005b brtrues l 0065l 005d ldlocs cs20l 005f call void mscorlibsystemthreadingmonitorexitobjectl 0064 nop l 0065 endfinally l 0066 nop l 0067 ldci40 l 0068 stloc2 l 0069 ldloc1 l 006a ldlocas locktakenl 006c call void mscorlibsystemthreadingmonitorenterobject booll 0071 nop l 0072 nop l 0073 ldnull l 0074 stloc1 l 0075 ldstr manual collectl 007a call void mscorlibsystemconsolewritelinestringl 007f nop l 0080 call void mscorlibsystemgccollectl 0085 nop l 0086 call void mscorlibsystemgcwaitforpendingfinalizersl 008b nop l 008c ldstr manual collectl 0091 call void mscorlibsystemconsolewritelinestringl 0096 nop l 0097 call void mscorlibsystemgccollectl 009c nop l 009d nop l 009e leaves l 00aal 00a0 nop l 00a1 ldloc1 l 00a2 call void mscorlibsystemthreadingmonitorexitobjectl 00a7 nop l 00a8 nop l 00a9 endfinally l 00aa nop l 00ab call string mscorlibsystemconsolereadlinel 00b0 pop l 00b1 ret try l 0019 to l 0053 finally handler l 0053 to l 0066try l 0072 to l 00a0 finally handler l 00a0 to l 00aai do not see any difference between the lock statement and the monitorenter call so why do i still have a reference to the instance of test1 in the case of lock and the object is not collected by gc but in the case of using monitorenter it is collected and finalized,['c#'] +62346,css borderleft 50 height i want the left border of my div to show only to the half of the div the same i would like to do to my right border but is should be set from the bottom of the div to the middle of the div how can i achieve it,['css'] +62353,dimension reduction in categorical data with missing values i have a regression model in which the dependent variable is continuous but ninety percent of the independent variables are categoricalboth ordered and unordered and around thirty percent of the records have missing valuesto make matters worse they are missing randomly without any pattern that is more that forty five percent of the data hava at least one missing value there is no a priori theory to choose the specification of the model so one of the key tasks is dimension reduction before running the regression while i am aware of several methods for dimension reduction for continuous variables i am not aware of a similar statical literature for categorical data except perhaps as a part of correspondence analysis which is basically a variation of principal component analysis on frequency table let me also add that the dataset is of moderate size 50 observations with 200 variables i have two questionsis there a good statistical reference out there for dimension reduction for categorical data along with robust imputation i think the first issue is imputation and then dimension reductionthis is linked to implementation of above problem i have used r extensively earlier and tend to use transcan and impute function heavily for continuous variables and use a variation of tree method to impute categorical values i have a working knowledge of python so if something is nice out there for this purpose then i will use it any implementation pointers in python or r will be of great helpthank you,['python'] +62357,use aspnet profile or not i need to store a few attributes of an authenticated user i am using membership api and i need to make a choice between using profiles or adding a new table with userid as the pk it appears that using profiles is quick and needs less work upfront however i see the following downsidesthe profile values are squished into a single ntext column at some point in the future i will have sql scripts that may update users attributes querying a ntext column and trying to update a value sounds a little buggy to meif i choose to add a new user specific property and would like to assign a default for all the existing users would it be possiblemy first impression has been that using profiles may cause maintainance headaches in the long run thoughts,['asp.net'] +62359,pysqlite2 programmingerror you must not use 8bit bytestrings i am currently persisting filenames in a sqlite database for my own purposes whenever i try to insert a file that has a special character like a etc it throws the following error pysqlite2dbapi2programmingerror you must not use 8bit bytestrings unless you use a text factory that can interpret 8bit bytestrings like text factory str it is highly recommended that you instead just switch your application to unicode stringswhen i do switch my application over to unicode strings by wrapping the value sent to pysqlite with the unicode method like unicodefilename it throws this error unicodedecodeerror ascii codec cannot decode byte 0xc3 in position 66 ordinal not in range128is there something i can do to get rid of this modifying all of my files to conform is not an option updateif i decode the text via filenamedecodeutf8 i am still getting the programmingerror above my actual code looks like thiscursorexecuteselect from musiclibrary where absolutepath filenamedecodeutf8what should my code here look like,['python'] +62367,preprocessor macro function vs function pointer best practice i recently started a small personal project rgb value to bgr value conversion program in c and i realised that a function that converts from rgb to bgr can not only perform the conversion but also the inversion obviously that means i do not really need two functions rgb2bgr and bgr2rgb however does it matter whether i use a function pointer instead of a macro for exampleint rgb2bgr const int rgb should i do this because it allows the compiler to issue appropriate error messages using the proper function name not to mention possible debugging benefits int bgr2rgb const int bgr rgb2bgr or should i do this since it is merely a convenience and they are really the same function anyway define bgr2rgbbgr rgb2bgr bgri am not necessarily looking for a change in execution efficiency as it is more of a subjective question out of curiosity i am well aware of the fact that type safety is neither lost nor gained using either method would the function pointer merely be a convenience or are there more practical benefits to be gained of which i am unaware,['c'] +62373,table name as variable i am trying to execute this querydeclare tablename varchar50set tablename testselect from tablenamethis produces the following errormsg 1087 level 16 state 1 line 5must declare the table variable tablenamewhats the right way to have table name populated dynamically,['sql'] +62386,kalman filter for android is there a kalman filter implementation i can use to fliter my gyroscope and acceleration data from an android phone,['android'] +62401,converting a bash script to python small script iave a bash script iave been using for a linux environment but now i have to use it on a windows platform and want to convert the bash script to a python script which i can runthe bash script is rather simple i think and iave tried to convert it by google by way around but canat convert it successfullythe bash script looks like thisruns5queries50outfileoutputfiletxtdate outfileecho e necho e n normal echo e necho e n normal outfilefor r 1 r runs 1 rdo echo e run r of runsn db2 flush package cache dynamic python readspy r1 pquery1sql qqueries shotelspec k6 a5 outfiledonethe main command the python readpy a etc is another python file iave been given and have the arguments as you seei know it is a lot to ask for but it would really help me out if someone could convert this to a python script i can use or at least give me some hints and directionssincerelymestikaadded per requestthis is what i have written but without successruns5queries50outfilereadsagaintxtfile openresultstxt abprint nprint n normal print nfilewriten normal nprint n query without index filewriten query without index nfor r 1 r s 1 r runs print run s of s n r runs db2 flush package cache dynamic output python readspy r1 pquery1sql qqueries shotelspec k6 a5 filewriteoutputfileclose,['python'] +62411,java convert 4 bytes to int i was wondering if the solution for this documented here is still the solution or is there any other way getting an int from 4 bytesthank youedit im getting the byte from sockets readedit int recvmsgsize inreaddata 0 buffersize if recvmsgsize is 1 i know the connection has been droppedhow do i detect this when im using datainputstream instead of inputstreamthanksedit apologies for being a yoyo regarding accepting the right answer but after mihis updated final response it would appear that the method is solid and cuts down extended coding and in my opinion best practice,['java'] +62416,java interface and abstract class issue i am reading the book hadoop the definitive guidein chapter 2 page 25 it is mentioned the new api favors abstract class over interfaces since these are easier to evolve for example you can add a method with a default implementation to an abstract class without breaking old implementations of the class what does it mean especially what means breaking old implementations of the class appreciate if anyone could show me a sample why from this perspective abstract class is better than interfacethanks in advancegeorge,['java'] +62417,objectivec calling one constructor from another say you had the following two constructors idinitwithtitlensstring title idinitwithtitlensstring title pagensstring pagethe second constructor is no different from the first except that it sets up the member variable pagesince it basically has to do the same thing is there a way to call the first one from the second one to reduce code duplication or do you have to set up a third method to do the common tasksi am talking about something similar to this though i doubt this will work idinitwithtitlensstring title ifself super init selftitle title return self idinitwithtitlensstring title pagensstring page ifself self initwithtitle title selfpage page return self,['objective-c'] +62419,how can this ambient context become null can anyone help me explain how timeprovidercurrent can become null in the following classpublic abstract class timeprovider private static timeprovider current defaulttimeproviderinstance public static timeprovider current get return timeprovidercurrent set if value null throw new argumentnullexceptionvalue timeprovidercurrent value public abstract datetime utcnow get public static void resettodefault timeprovidercurrent defaulttimeproviderinstance observationsall unit tests that directly reference timeprovider also invokes resettodefault in their fixture teardownthere is no multithreaded code involvedonce in a while one of the unit tests fail because timeprovidercurrent is null nullreferenceexception is thrownthis only happens when i run the entire suite but not when i just run a single unit test suggesting to me that there is some subtle test interdependence going onit happens approximately once every five or six test runswhen a failure occurs it seems to be occuring in the first executed tests that involves timeprovidercurrentmore than one test can fail but only one fails in a given test runfwiw heres the defaulttimeprovider class as wellpublic class defaulttimeprovider timeprovider private readonly static defaulttimeprovider instance new defaulttimeprovider private defaulttimeprovider public override datetime utcnow get return datetimeutcnow public static defaulttimeprovider instance get return defaulttimeproviderinstance i suspect that there is some subtle interplay going on with static initialization where the runtime is actually allowed to access timeprovidercurrent before all static initialization has finished but i cannot quite put my finger on itany help is appreciatedfwiw i just threwconsolewritelinethreadcurrentthreadmanagedthreadidin the getter and it consistently reports the same id for all test cases in a test run so the issue seems not related to threading,"['c#', '.net']" +62421,how to loop through a boostmpllist this is as far as i have gotteninclude boostmpllisthppinclude algorithmnamespace mpl boostmplclass runaround class hopupanddown class sleep templatetypename instructions int dothistemplate int dothisrunaround run run run return 3 template int dothishopupanddown hop hop hop return 2 template int dothissleep z return 2 int main typedef mpllistrunaround hopupanddown sleep acts stdfor eachmplbeginactstype mplendactstype dothis return 0how do i complete this i do not know if i should be using stdfor each just a guess based on another answer here,['c++'] +62426,ruby on rails vs grails vs spring roo vs spring app i am planning on writing a simple web application that will be used by lots of users as complicated as a simple bookmarking app and i am trying to decide which frameworklanguage to usei am very experienced with springhibernate and java in general but new to both grails and ror and spring roo the only reason i am considering ror is because java hosting is much more expensive than ror hosting which is supported by almost any hosting vendor for 5 per monthassuming the price was not an issue which one of the frameworkslanguages mentioned above would you recommend for a java developer who knows how to configure springhibernate etci am afraid that by using ror i would not be able to easily support many users who are using the website at the same timethanks,"['java', 'ruby-on-rails']" +62427,is it secure to use malloc somebody told me that allocating with malloc is not secure anymore i am not a cc guru but i have made some stuff with malloc and cc does anyone know about what risks i am intoquoting him but indeed the weak point of cc it is the security and the achilles heel is indeed malloc and the abuse of pointers cc it is a well known insecure language there would be few apps in what i would not recommend to continue programming with c,"['c++', 'c']" +62432,core location in iphone simulator 32 ipad soi am trying to port my app to ipadi am using corelocationapple says the ipad does havelocationwifidigital compassassisted gps wifi 3g modelcellular wifi 3g modelso it should be possible to get the position of my ipad at least with 3g model about 3km radius would be enoughtbut it doesnt work in simulator 32 ipad running 313 in simulator simulates me cupertinois there a way to get the position in simulator 32 ipad i live in germany and here the ipad isnt released yet so i cannot test it on my devicethankseditthats how i am trying to get my connectionlocationmanager cllocationmanager alloc initlocationmanagerdesiredaccuracy kcllocationaccuracythreekilometerslocationmanagerdelegate selflocationmanager startupdatinglocationand always on 32 locationmanagercllocationmanager manager didfailwitherrornserror error gets called not on 313error object looks like thiserror domainkclerrordomain code0 operation could not be completed kclerrordomain error 0editso i handled it something like this voidlocationmanagercllocationmanager manager didfailwitherrornserror error ifdef target iphone simulator cupertino cllocation simulatorlocation cllocation alloc initwithlatitude3733168900 longitude12203073100 self locationmanagerlocationmanager didupdatetolocationsimulatorlocation fromlocationnil simulatorlocation release else nsnotificationcenter defaultcenter postnotificationnameerrornotification objectnslocalizedstringgpscoordinates could not be detected endifit is very messy but worksedit2 try enabling your airport this could also solve the problem,"['ios', 'iphone']" +62433,how to add an extra button to the windows title bar i have seen that some apps maybe not net apps that have an extra button on the left from the minimize button on the forms title bar how can i achieve this in c,"['c#', '.net']" +62442,what does d mean in regular expression terms i am new to regular expressions and came accros the following d i do not exactly know what this means please point me in the right direction,['php'] +62452,android bindservice i get null pointer exception at line mservicestart when i try to bind to an already started service i do the same thing from different activitywhere the service gets started everythig goes right all these activities are part of one applicationwhat do you think i do wrongpublic class routeonmap extends mapactivity private static final int new location 1 private static final int gps off 2 private mapview mmapview private ilocservice mservice private boolean mservicestarted private boolean mbound private intent mserviceintent private double mlatitude mlongitude private serviceconnection connection new serviceconnection public void onserviceconnectedcomponentname classname ibinder iservice mservice ilocservicestubasinterfaceiservice mbound true public void onservicethisconnectedcomponentname classname mservice null mbound false public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmapview mmapview mapview findviewbyidridmapview mmapviewsetbuiltinzoomcontrolstrue mserviceintent new intent mlatitude 00 mlongitude 00 mbound false override public void onstart superonstart mserviceintentsetclassthis locationserviceclass startservicemserviceintent ifmbound mbound true thisbindservicemserviceintent connection contextbind auto create override public void onresume superonresume try mservicestart catch remoteexception e eprintstacktrace override public void onpause superonpause ifmbound thisunbindserviceconnection override protected boolean isroutethisplayed todo autogenerated method stub return false,['android'] +62458,iphone apps webapps or native i am planning to create an iphone apps version for our online webapps i am still new to iphone apps development so i do not know whether to choose iphone native or a webapps that runs on iphone browser the requirement is actually pretty basic the iphone apps need to submit data and get data from the database that is also used by the webapps user would have the same access to the webapps only i want this specific to iphone as the user experience would be different using a webapps and iphone apps i am also interested to sell the application on apple store based on your experience what would be better for this kind of requirement iphone native or webapps what are the drawbacks building a native iphone apps and webapps that runs on iphone browser also am i only limited to objectivec to build a native iphone apps or is there any other framework for thatplease be gentle on me i am not starting a flamewar,"['iphone', 'objective-c']" +62473,webconfig put an comment inside xml attributes i want to put an comment in webconfig file something like this httpruntime requestvalidationmode20 require for validateinputfalse in net40 requestpathinvalidcharacters include character in the url enableversionheaderfalse thisable xaspnetversion header is there any way to put comments in this way using serverside comments like or something,['asp.net'] +62484,graphstructured databases and php i want to use a graph database using php can you point out some resources on where to get started is there any example code tutorial out there or are there any other methods of storing data that relate to each other in totally randomabstract situations very abstract example of the relations needed john relates to mary both relate to school john is tall mary is short john has blue eyes mary has green eyes query i want is which people are related to short people that have green eyes and go to school answer johnanother example tracka artista artistb albuma label albumb a trackaremix genrehouse album label trackb c b example queries which genre is trackb closer to answer house because it is related to album c which is related to tracka and is related to genrehouseget all genrehouse related albums of label a result albuma albumb because they both have tracka which is related to genrehouseit is possible in mysql but it would require a fixed set of attributescolumns for each item and a complex nonflexible query instead i need every attribute to be an item by itself and instead of belonging to something to be related to something,['php'] +62486,how to run terminal command in android application how to send a command to the terminal through android app and get the output back for example sending ls and getting the output to print it in the gui,"['java', 'android']" +62504,c standard library exception list is there a reference about c standard library exceptions i just want to know that which functions may throw an exception or not,['c++'] +62511,why the vertical scroll bar moves automatically i do not understand why the vertical scroll bar moves automatically to the most top position when line 9 clicked for example further clicks does not move the scroll bar could anyone explain why and how to fix this i work with firefox 363html html head link relstylesheet hreftestcss typetextcss script srcscript script languagejavascript srctestjsscript head body div table tr row0td classcolumn1line 0tdtr tr row1td classcolumn1line 1tdtr tr row2td classcolumn1line 2tdtr tr row3td classcolumn1line 3tdtr tr row4td classcolumn1line 4tdtr tr row5td classcolumn1line 5tdtr tr row6td classcolumn1line 6tdtr tr row7td classcolumn1line 7tdtr tr row8td classcolumn1line 8tdtr tr row9td classcolumn1line 9tdtr table div bodyhtmljsdocumentreadyfunction column1eachfunctionindex thisaftertd classcolumn2details index td thistogglefunction row index column2fadeinfast function row index column2fadeoutfast cssdiv overflow auto height 100px width 300px border 1px solid bluecolumn1 cursor pointer width 100px backgroundcolor green color whitecolumn2 thisplay none width 200px backgroundcolor blue color white,"['javascript', 'jquery', 'html', 'css']" +62514,any way to find number of days in month using objective c instead of calculating the month and leap year to do this calculation is there any way to check using some apple internal apis to do soi found that the java have something like thiscalendargetactualmaximumcalendarday of month is there any similar thing for objective c thz u,['objective-c'] +62531,doubletryparse input decimal separator different than system decimal separator i have a source xml that uses a dot as a decimal separator and i am parsing this on a system that uses a comma as a decimal separator as a result value of 07 gets parsed with doubletryparse or doubleparse as 70what are my options to parse correctly one of them is to replace dots in source with commas with stringreplace but i do not think i like this very much,"['c#', '.net']" +62535,xcode for iphone exc bad access error only occurs when stepping through the debugger i am working on a project in xcode for iphone where i am receiving an exc bad access error however i only receive the error when stepping through a function i am trying to debug when i take my breakpoint off the function but still run the project in debug mode i never receive this error is there anyway to solve this or find out what is causing the exc bad access errorthe error comes on the line for beucharacteraibehavior behavior in behavior behaviors however when stepping through the value behavior behaviors is allocated and retained nszombiesenabled is set but still get the cryptic error messagecodebeucharacteraibehavior gethighestvaluebehaviorfrombehaviorbeucharacteraibehavior behavior if the behavior is a leaf then stop checking because there are no sub behaviorsifbehavior isleaf return behavior temp variable for highest value behavior so farbeucharacteraibehavior highest nilnslogbehaviorsbehavior behaviorsfor beucharacteraibehavior behavior in behavior behaviors if there is a highest value behavior check if the highest value behavior has a larger value than the new one ifhighest ifhighestlastvalue behaviorvalue continue if there is no current behavior then the highest is now the behavior were checking because we have nothing to check against ifcurrentbehavior highest behavior make sure the current behavior is not the same behavior as the new one else ifcurrentbehavior behavior can the new behaviors parent run multiple times in a row ifbehaviorparentcanrunmultipletimesinarow make sure the current and new behaviors parents arent the same if they are continue to next behavior ifcurrentbehaviorparent behaviorparent continue highest behavior if current behavior and new behavior are the same make sure they can run multiple times else ifcurrentbehaviorcanrunmultipletimesinarow highest currentbehavior nsloggoing to get highest value behavior from behavior dhighestretaincountifhighest return nilreturn self gethighestvaluebehaviorfrombehaviorhighesthighesterror stack0 0x02aebdcb in object getclass1 0x02ac0 in 2 0x014bb9 in beucharacterai gethighestvaluebehaviorfrombehavior at beucharacteraim1153 0x014b6b in beucharacterai gethighestvaluebehavior at beucharacteraim1034 0x014904 in beucharacterai update at beucharacteraim685 0x08975 in beucharacter step at beucharacterm2296 0x022aeb in eskimocharacter step at eskimocharacterm287 0x0ed2b in beuobjectcontroller step at beuobjectcontrollerm3818 0x03651 in beugame step at beugamem639 0x07cc42 in cctimer fire at ccschedulerm8710 0x07d846 in ccscheduler tick at ccschedulerm21211 0x0500b3 in ccdirector mainloop at ccdirectorm20812 0x0532b3 in ccthisplaylinkdirector premainloop at ccdirectorm105513 0x00796f06 in cathisplaythisplaylinkthispatch14 0x0079704b in cathisplayemulatorthisplaylinkcallback15 0x029810f3 in cfrunloop is calling out to a timer callback function16 0x02982734 in cfrunloopdotimer17 0x028df689 in cfrunlooprun18 0x028dec00 in cfrunlooprunspecific19 0x028deb21 in cfrunloopruninmode20 0x03e96378 in gseventrunmodal21 0x03e9643d in gseventrun22 0x0083bf89 in uiapplicationmain23 0x02b50 in main at mainm13,['iphone'] +62544,writing at the end of file i am working on a system that requires high file io performance with cbasically i am filling up large files 100mb from the start of the file until the end of the fileevery 5 seconds i am adding 5mb to the file sequentially from the start of the file on every bulk i am flushing the streamevery few minutes i need to update a structure which i write at the end of the file some kind of metadatawhen flushing each one of the bulks i have no performance issuehowever when updating the metadata at the end of the file i get really low performancemy guess is that when creating the file which also should be done extra fast the file does not really allocates the entire 100mb on the thisk and when i flush the metadata it must allocates all space until the end of fileguysgirls any idea how i can overcome this problemthanks a lotfrom commentin general speaking the code is as follows first the file is opened m stream new filestreamfilename filemodecreatenew fileaccesswrite filesharewrite 8192 false m streamsetlength10010241024every few seconds i am writing 5mb m streamseekm lastposition seekoriginbegin m streamwritebuffer 0 bufferlength m streamflush m lastposition bufferlength hh guessed the m streamseekm metadatasize seekoriginend m streamwritemetadata 0 metadatalength m streamflush takes too long on the first time1 sec,['c#'] +62565,thread safety with heapallocated memory i was reading this safetyis the following function threadsafevoid fooint y int x new int50 do some stuff with the allocated memory delete xin the article it says that to be threadsafe you can only use variables from the stack really why wouldnt subsequent calls of the above function allocate memory elsewhereedit ah looks like i misread this part of the articlea subroutine is reentrant and thus threadsafe ifthe only variables it uses are from the stacki took it to meana subroutine is reentrant and thus threadsafe if and only ifthe only variables it uses are from the stack which according to the answers below is not the case,['c++'] +62570,placing php array values into a javascript array is these a way i can loop through a php array and have the data outputted into a javascript arrayfor example the js script below will not work var mon loop php echo rowcount mon var mon events new arrayfori 0 i mon loop i mon eventsi php divmoni i know its because the i is not a php variable so therefore invalid inside the php section but its just an way to show what i would like to achieve the rowcount variable count the number of rows and is then used to for the loop lets say for example that i want to place the contents of the php array divmon0 into the javascript array mon events0i know that i can do it manually like below mon events0 php echo divmon0 but i have lots of these and therefore need the loop is there some js or php that could do thischeers,"['php', 'javascript', 'sql']" +62575,are dll files loaded once for every program or once for all programs i have a simple small question which someone who knows will be able to answer easily i searched google but could not find the answerthere are many programs running at once on a computer and my question is when a program loads a dll does it actually load the dll file or does it find the memory in which the dll is already loaded for example is ws2 32dll winsock 2 loaded for every program that uses winsock or is it loaded once and all programs that use it use the same memory addresses to call the functions,['c++'] +62603,goal of cs auto keyword what is the goal of the auto keyword in c with c 0x it got new meaning but does it mean that my code will break if i port c code over to a c 0x compiler,"['c++', 'c']" +62611,spring aop pointcut that matches annotation on interface this is my first post here so i apologize in advance for any stupidity on my sidei have a service class implemented in java 6 spring 3 that needs an annotation to restrict access by rolei have defined an annotation called requiredpermission that has as its value attribute one or more values from an enum called operationtypepublic interface requiredpermission one or more link operationtypes that map to the permissions required to execute this method return operationtype valuepublic enum operationtype type1 type2package commycompanymyservicepublic interface myservice requiredpermissionoperationtypetype1 void mymethod myparameterobject obj package commycompanymyserviceimplpublic class myserviceimpl implements myservice public mymethod myparameterobject obj do stuff here i also have the following aspect definition security advice around methods that are annotated with link requiredpermission param pjp param param param requiredpermission return throws throwable aroundvalue executionpublic commycompanymyserviceimpl argsparam parameter object annotation requiredpermission permission annotation argnames paramrequiredpermissionpublic object processrequestfinal proceedingjoinpoint pjp final myparameterobject param final requiredpermission requiredpermission throws throwable ifuserserviceuserhasrolesparamgetusernamerequiredpermissionvalues return pjpproceed else throw new sorrybutyouarenotallowedtodothatexception paramgetusernamerequiredpermissionvalue the parameter object contains a user name and i want to look up the required role for the user before allowing access to the methodwhen i put the annotation on the method in myserviceimpl everything works just fine the pointcut is matched and the aspect kicks in however i believe the annotation is part of the service contract and should be published with the interface in a separate api package and obviously i would not like to put the annotation on both service definition and implementation dryi know there are cases in spring aop where aspects are triggered by annotations one interface methods eg transactional is there a special syntax here or is it just plain impossible out of the boxps i have not posted my spring config as it seems to be working just fine and no those are neither my original class nor method namesthanks in advance seanpps actually here is the relevant part of my spring configaopaspectjautoproxy proxytargetclassfalse bean classcommycompanyaspectmyaspect property nameuserservice refuserservice bean,['java'] +62613,c build systems i will start a new c project it may have some c components as well soon and i am looking for a modern industrialstrength ie nonbeta build system the software will be created by several developers in 35 years and will run on linux mac os x and windows might be supported later i am looking for something that has better comprehensibility easeofuse and maintainability than eg make but is still powerful enough to handle a complex project open source software is preferredi started looking into boostbuild cmake maven and scons so far and liked features and concepts of all of those but i am lacking the experience to make a decision for a large project,['c++'] +62618,dual or triple or even multiple comparison in javascript almighty gurusplease tell me i want to know can comparison sm set of variables in row like thisx y z or i need to do it in two stepsx y y z,['javascript'] +62638,generic list to entityset conversion how do i convert a systemcollectionsgenericlistt to a systemdatalinqentitysett,['c#'] +62647,output unicode to console using c i am still learning c so bear with me and my sloppy code the compiler i use is dev c i want to be able to output unicode characters to the console using cout whenver i try things like include directive here include iostream using namespace stdint main cout hello worldn cout blah blah blah some gibberish unicode an systempause return 0it outputs strange characters to the console like a gg why does it do that and how can i get to to thisplay a or is this not possible with windows,['c++'] +62655,how to remove duplicates from a list i want to remove duplicates from a list but what i am doing is not workinglistcustomer listcustomer new arraylistcustomer for customer customer tmplistcustomer if listcustomercontainscustomer listcustomeraddcustomer,['java'] +62656,html how to create a save as button in your browser when you want to save an html page that you are currently viewing you normally go to the file menu and click save ascan i have a little button at the bottom of an html page that does the same thing so instead of going to the file menu save as i want my user to be able to click the button to save the page on to the thiskthere is a solution exists using javascript as far as i know but it only works for ie see here link text,"['javascript', 'html']" +62669,oowrite is to latex as oodraw is to i am looking for a tool to nicely generate singlepage pdfs my needs areable to put a pdfeps as a backgroundabsolute positioningable to define tables listsable to rotate blocksreasonably easy syntax will be used to automatically generate many similar looking documentseasily usable from pythonfree or very cheapin essence i am looking for the tool x that is to oodrawcoreldraw as latex is to oowritems wordi have looked at webkit2pdf and a headless oodraw but both seem a bit of an overkill xmlfo has some limitations such as not being able to predict how many pages your document spans reportlab is priceyany ideasthanks,['python'] +62678,very simple file appender logging not working heres my webconfig information configsections section namelog4net typelog4netconfiglog4netconfigurationsectionhandler log4net configsections log4net root level valueall root appender namerollingfileappender typelog4netappenderrollingfileappender file valuectemplogfiletxt appendtofile valuetrue rollingstyle valuesize maxsizerollbackups value10 maximumfilesize value1mb staticlogfilename valuetrue layout typelog4netlayoutsimplelayout appender log4netheres the code that initializes the loggerprotected void sendmessage log4netconfigxmlconfiguratorconfigure ilog log logmanagergetloggertypeofcontact loginfohere we go logdebugdebug afasf it does not work no matter what i seem to do i am referencing the log4netdll correctly and by debugging the application i can see that the log object is getting initiated properly this is an aspnet 35 framework web project any ideassuggestionsi thought originally this error may be due to a file write permission constraint but that does not seem to be the case or so i think,"['c#', 'asp.net']" +62689,how to read verbose vc linker output trying to debug some linker errors i turned on verbose and i am trying to make sense of the output it occurs to me that i really do not know how to read itfor example1compiling version info1linking1starting pass 11processed defaultlibmfc80lib1processed defaultlibmfcs80lib1processed defaultlibmsvcrtlib1processed defaultlibkernel32lib1processed defaultlibuser32lib1processed defaultliblibgslcblasmdlib1searching libraries1 searching vsrcsolutionscommonwin32libplxapilib1 searching outwin32releaselibcamerageometrylib1 searching outwin32releaselibgeometrylib1 found public thiscall visionmapgeometrybox2doperator class visionmapgeometrybox2dintvoidconst bbox2dgeometryvisionmapqbeavbox2dint12xz1 referenced in focusdlgobj1 loaded geometrylibbox2dobj1processed defaultlibcgalvc80mtlib1processed defaultlibboost threadvc80mt1 33 1libwhats going on herei think i understand this bit1processed defaultliblibgslcblasmdlib1searching libraries1 searching vsrcsolutionscommonwin32libplxapilib1 searching outwin32releaselibcamerageometrylib1 searching outwin32releaselibgeometrylib1 found public thiscall visionmapgeometrybox2doperator class visionmapgeometrybox2dintvoidconst bbox2dgeometryvisionmapqbeavbox2dint12xz1 referenced in focusdlgobj1 loaded geometrylibbox2dobjit is trying to find the implementation of the above operator which is used somewhere in focusdlgcpp and it finds it in geometrylibbut what does 1processed defaultliblibgslcblasmdlib mean what determines the order of symbol resolution why is it loading this particular symbol while processing libgslcblasmdlib which is a 3rd party library or am i reading it wrongit seems that the linker is going through the symbols referenced in the projects various object files but i have no idea in what order it then searches the static libraries the project uses by project reference explicit import and automatic default library imports but it does so in an order that again seems arbitrary to me when it finds a symbol for example in geometrylib it then continues to find a bunch of other symbols from the same lib1 searching vsrcsolutionscommonwin32libplxapilib1 searching outwin32releaselibcamerageometrylib1 searching outwin32releaselibgeometrylib1 found public thiscall visionmapgeometrybox2doperator class visionmapgeometrybox2dintvoidconst bbox2dgeometryvisionmapqbeavbox2dint12xz1 referenced in focusdlgobj1 loaded geometrylibbox2dobj1processed defaultlibcgalvc80mtlib1processed defaultlibboost threadvc80mt1 33 1lib1 found public thiscall visionmapgeometrybox2dintbox2dintintintintint 0box2dintgeometryvisionmapqaehz1 referenced in focusdlgobj1 referenced in imageviewobj1 referenced in geometrylibbox2dobj1 loaded geometrylibbox2dintobj1 found public virtual thiscall visionmapgeometrypoint3dpoint3dvoid 1point3dgeometryvisionmapuaexz1 referenced in gpsfrmobj1 referenced in mainfrmobj1 loaded geometrylibpoint3dobj1 found void cdecl visionmapgeometryserializeclass boostarchivebinary oarchiveclass boostarchivebinary oarchive class visionmapgeometrypoint3d unsigned int serializevbinary oarchivearchiveboostgeometryvisionmapyaxaavbinary oarchivearchiveboostaavpoint3d01iz1 referenced in gpsfrmobj1 referenced in mainfrmobj1 loaded geometrylibgeometryserializationimplobjbut then for some reason it goes on to find symbols that are defined in other libs and returns to geometry later on a bunch of times so clearly it is not doing look in geometry and load every symbol that is references in the project and then continue to other libraries but it is not clear to me what is the order of symbol lookup and whats the deal with all those libraries being processed at the beginning of the linkers work but not finding any symbols to load from them does this project really not use anything from msvcrtlib kernel32lib seems unlikelyso basically i am looking to decipher the underlying order in the linkers operation,['c++'] +62705,write to xcode build transcript is there any way to write to the xcode build transcript what i want to do is throw a warning if a device is not attached to the computer instead of an assertion failure in my unit test cases some cases rely on an attached ipodi thought of something like the standard compiler warnings only with custom messagethanks,['objective-c'] +62716,warning mysql query 3 is not a valid mysqllink resource i got this odd error and i cannot figure out where it came fromwarning mysql query 3 is not a valid mysqllink resource in whats up with the 3 i do not get it has anyone experienced this error themselves,"['php', 'mysql']" +62727,whats the best way to debug css on ie in firefox i can usee firebug in chrome i can use the css console both to make live changes to css for troubleshooting purposes however i do not know of a way to do this in ie which is where i have the most css issuesso whats the best way to troubleshoot css issues in iethanks,['css'] +62732,priority queue clear method how do i delete all elements from a priority queue that means how do i destroy a priority queueadvanced thanks for your answer is there any clear or eraselike method,['c++'] +62736,how to test a net application against a proxy i need to support the use of proxy on our application that is using wcf connectionswe do not have any proxy server on our network and i do not want to thisrupt our corporate network by requesting a proxy installation i was thinking of installing a proxy server on a local virtual machine and configurating internet explorer so that it will challenge that proxyi do not know what proxy software to use i do not want to install isa server and i do not know how to configure onedoes someone have any suggestion for a easy to use software that will require an authentication for any wcf services and do you have any guideline that would be helpful to know when testing a software against a proxy,"['c#', '.net']" +62738,using scanf in cc to read an int using scanf we usescanfdiwhat if i is long not int note when using d with long it gives me an irritating warningthanks,"['c++', 'c']" +62739,using an initializer list on a map of vectors i have been trying to initialize a map of ints vectorints using the new 0x standard but i cannot seem to get the syntax correct i would like to make a map with a single entry with keyvalue 134include initializer listinclude mapinclude vectorusing namespace stdmapint vectorint a 134it dies with the following error using gcc 443error no matching function for call to stdmapintstdvectorintstdallocatorint stdlessintstdallocatorstdpairconst intstdvectorintstdallocatorint mapbraceenclosed initializer listeditfollowing the suggestion by cogwheel and adding the extra brace it now compiles with a warning that can be gotten rid of using the fnodeduceinitlist flag is there any danger in doing so,['c++'] +62759,do fields need to be explicitly final to have a proper immutable object you often read about immutable objects requiring final fields to be immutable in java is this in fact the case or is it simply enough to have no public mutability and not actually mutate the statefor example if you have an immutable object built by the builder pattern you could do it by having the builder assign the individual fields as it builds or having the builder hold the fields itself and ultimately return the immutable object by passing the values to its private constructorhaving the fields final has the obvious advantage of preventing implementation errors such as allowing code to retain a reference to the builder and building the object multiple times while in fact mutating an existing object but having the builder store its data inside the object as it is built would seem to be dryerso the question is assuming the builder does not leak the object early and stops itself from modifying the object once built say by setting its reference to the object as null is there actually anything gained such as improved thread safety in the immutability of the object if the objects fields were made final instead,['java'] +62763,update a column based on a field from another table i would like to update values in one table based on corresponding values from other tables say you want to update prices of pieces provided by one specific manufacturer whose name is in the table manufacturers with the pieces table containing only the id of the manufactureri have seen several solutions for mysql here and for ms sql server here but none of them seems to work in sqliteany suggestion,['sql'] +62776,for django models is there a shortcut for seeing if a record exists say i have a table people is there a way to just quickly check if a people object exists with a name of fred i know i can querypeopleobjectsfilternamefredand then check the length of the returned result but is there a way to do it in a more elegant way,['python'] +62777,magento limiting number of returned items in product collection call im trying to limit the number of returned results manually in a copy of the listphtml template but its turning out to be alot harder than i anticipated ive tried manually setting the collection size but ya once again nothing working can someone show me how to do this would be nmuch appreciated,['php'] +62794,html form hidden fields added with javascript not posting i have a form where the user can enter a link click the add link button and that link is thenvia jquery added to the form as a hidden field the problem is it is not posting when i submit the form it is really starting to confound me the thing is that if i hardcode a hidden field into the form it is posted but my function is not working for some reason the hidden field does get added to my form as i can see with firebug but it is just not being sent with the post datajust to note i am using an array in javascript to hold the elements until the form is submitted which also posts them visibly for the user to see what they have added i am using notation on the name field of the element because i want the links to feed into an array in phphere is the link creation which is being appended to my form function make hidden element tagitem type item content item id return input typehidden name item type idhidden link item id value item content does anyone have an idea why this might not be posting as stated above any hardcoded tags that are nearly identical to the above works fine it is just that this tag is not working here is how i am adding the tag to the form with jquerylink tdappend make hidden element taglinks link link arraylength 1i am using the kohana 3 framework although i am not sure that has any bearing on this because it is not really doing anything from the time the html is added to the page and the submit button is pressed,"['javascript', 'jquery', 'html']" +62804,difference between tryfinally and trycatch whats the difference betweentry foobar finally barfooandtry foobar catchthrowable throwable barfoothrowable does something with throwable logs it or handles iti like the second version better because it gives me access to the throwable is there any logical difference or a preferred convention between the two variationsalso is there a way to access the exception from the finally clause,['java'] +62809,android no icon for notification i wanted to create a notification without the icon in the status bar the state that is not expanded i tried the custom expanded view and set the icon for this view only but it did not work when i give 0 as icon to the constructor the icon thisappears but notification also does not appear in the expanded view notification notification new notification0 0i tried a lot of combinations but did not come out with a solution by the way i know it is working because i saw this feature in some apps thanks,['android'] +62814,uncaught syntaxerror unexpected token illegal may i know whats wrong in thisi am new to world of programing so if you help me it would be wonderfulthe error comes on the line arricount11employemailawaiting for your responsethe entire code as followsfunction var arr new array arr0new array4 arr00sathis arr01 arr02namakkal arr0321 arr1new array4 arr10ganesh arr11 arr12karaikudi arr1322 arr2new array4 arr20karthik arr21 arr22trichy arr2325 var strtabletrthnameththemailththcityththagethtrtrtd emp namechangefunction var ithisval strstrarri10tdtdarri11tdtdarri12tdtdarri13tdtrtable viewerhtmlstr alertstr,['jquery'] +62828,call tinymce in a wordpress plugin is there a way to add tinymce into my own wordpress plugini have a textarea in my back end script and want to make this area into a tinymce wysiwyg editable field is there a way to do thatthis code does not work for mephp wp tiny mcefalsearrayeditor selector testtextarea classtest idtest nametesttextareait shows the javascript errorf is undefinedfirebug screenshotthis did not work eithertextarea classtheeditor idvideogalerieadd description namevideogalerieadd descriptiontextarea,"['php', 'javascript']" +62841,how to setup a cms as a backend for iphone app i would like my iphone app to get dynamic content off the net this content should be managed using a cms i would like to know in particular if i can setup drupal or joomla or other cms as a backend for my iphone app to get the contentany advice on how this can be achieved would be helpfuli am completely new to setting upusing cms,['iphone'] +62846,hibernate does not generate cascade i have a set hibernatehbm2ddlauto to create so that hibernate creates the tables in mysql for mehowever it does not seem that hibernate correctly adds cascade on the references in the table it does however work when i for instance delete a row and i have a delete cascade as hibernate annotation so i guess that means that hibernate reads the annoation on runtime and perform cascading manuallyis that normal behaviorfor instanceentityclass report onetoonecascade cascadetypeall public file getpdf return pdfhere i have set cascade to all however when running show create table reportreport create table report id bigint20 not null auto increment pdf id bigint20 default null primary key id key fk91b14154fde6543a pdf id constraint fk91b14154fde6543a foreign key pdf id references file id engineinnodb default charsetutf8 it does not say anything about cascading other then the foreign key in my opinion it should have added the on delete cascade on delete update,['mysql'] +62848,resizing a imageicon in a jbutton i am creating a jbutton which includes a specific imageicon the main issue is that the original icon size is much bigger than the button size as result when the button is thisplayed only part of the icon can be seen what is the method that resize an imageicon i and order to make it fit inside a jbutton,['java'] +62851,paypal ipn security paypal ipn sends a post request with a variable number of fields to the notify url in order to confirm that the post request is legit we need to resubmit the same request along with a additional cmd notifyvalidate field to paypal which then replies verified or invalidmy question is why do we need to resend the request to paypal wouldnt something like this sufficeif preg matchpaypalcomi gethostbyaddr serverremote addr 0 request came from paypal it is legitiff we can trust the server to correctly resolve ips i assume we can trust all requests from paypal no,['php'] +62853,path to wordpress template directory inside jquery my header is calling a javascript file which sends out an emailscript typetextjavascript srcphp bloginfotemplate directory csseffectsjsscriptbut inside this file i have a jquery code that calls a php file that does the actual sending of the emailajax type post url csendmailphp data datastringbut the script does not work unless the url isphp bloginfotemplate directory csendmailphpand not justcsendmailphpis there any way to include a path to the wordpress template directory inside js,"['javascript', 'jquery']" +62860,date relative to current in the dbunit dataset i am wondering if there is any way to specify for example tomorrow as date in the dbunit xml dataset sometimes code logic is different for dates in future and dates in the past and i want to test both cases for sure i can specify something like the 5th of november 2239 and be sure that test will work till this date but are there more elegant wayi have not yet faced such situation during my java development but once i had experience when code logic was different for one day before dates two days before dates and more than two days before dates in this case the only possible solution to write database driven test is to insert relative dates during data importare there any facilities provided by the dbunit for this,['java'] +62876,using saveorupdate in hibernate creates new records instead of updating existing ones i have a class user class user int id string namewhere id is native generator in userhbmxml and name is primarykey in db in my database i saved some information about users than i want to connect with this information about userfor example in my db i have a row insert into user values billmainjavauser bill new userbillsetnamebillsessionsaveorupdatebillthis code always tries to insert a new bill row into the table rather than update the existing bill row,['java'] +62877,iphones os how to programmatically differentiate ipad 3g from ipad wifi is there any property or other mechanism in iphone os to check during runtime whether application is running on ipad 3g or ipad wifiseems like uidevice class does not provide anything like thatmy application is using internet access extensively and i would like to explicitly warn user that on 3g delays or additional costs can be expected or even ban application from running on ipad 3g with some fancy popup,['iphone'] +62886,command pattern vs visitor pattern is it generally acceptable to allow a visitor to modify state of the receiver or should that be a command pattern instead,"['c#', '.net']" +62887,onhide type event in jquery does anyone know of an onhide event or something similar in jquery i tried thisbindhide function consolelogasdasdabut apparently that does not work editjust to clarify it is being hidden using css thisplaynonei am aware of the callback function but as i am not hiding it the css is i cannot use it for what it is worth i need to check when a dropdown is visible it is being shown by the following css ul lihover ul thisplay block,['jquery'] +62892,django inlines user permissions view only permissions issues i am not sure if this is a bug or i am just missing something although i have already parsed the documentation about inlines butlet us say i have a model a model a is an inline of model b user you has full access to model b but only change permissions to model a so no add nor deletehowever when editing model b user you can still see the add another a link at the bottom although you has not add permissions for that respective modelwhats wrong why does that link keep on showing my logic says that if you does not have permissions to add a the link should not appear anymorealso ideally i would like to give you only view rights to model a so no add delete or change only view but i have read about that strange if you ask me philosophy according to which if you do not trust u just deny him access to the admin area all together kind of a stupid doctrineright now i am trying to simulate this view only permissions by leaving you with just change rights and set all fields as read only but i think this is kind of a stupid approach and may also cause problems like the permissions thing abovehow does an average django programmer like me achieve viewonly permissions and most of all how should i get rid of the add another a link at the bottom of the admin edit formthanks in advance,['python'] +62900,javascript inner function scope chain in this examplevar a 1 functionx function inner alerta alertx alerty var y 3 inner2when does function inner get created during execution time or parsing time of outer anonymous function what is in the scope chain of function innerwhat is the difference between the execution context and scope chain of function innerthanks for enlighting me in advance,['javascript'] +62901,jquery width and height strange behaviour why in the following code height returns 95 rather than 100 while width returns 200 as expected i work with firefox 363htmltabletr td idmytdtrtablediv idlogdivcssmy border 5px solid redjsmywidth200height100logappendwidth mywidth br logappendheight myheighti tried outerwidth and outerheight and also innerwidth and innerheight but none of them returns the expected result code examplebut if i set position absolute it looks much better can anyone explain this behavior,"['javascript', 'jquery', 'html', 'css']" +62904,how can i reorder columns in a datagridview so i fill my dgv with some data and set some columns invisible var part inventoryespiromex productwherep pdescriptionsmall cmbmainptextfirstpartnumberp dtgassydatasource inventoryespiromex productsubwherep ppartnumberp part dtgassycolumnsidproductsubvisible false dtgassycolumnspartnumberpvisible false dtgassycolumnspartnumbersubpvisible true dtgassycolumnsquantityvisible true dtgassycolumnscommentsvisible true dtgassycolumnsassemblynovisible false dtgassycolumnsassemblynodescvisible false dtgassycolumnsuomidvisible true dtgassycolumnssubassemblylevelnumbervisible false dtgassycolumnsscrappercentvisible truethis is just fine but columns are sorted alphabetically how can i reorder columns programmaticallynote that inventory is an entitie and i am using linq to entities,['c#'] +62906,what is the reason of transaction context in use by another session i am looking for a description of the root of this error transaction context in use by another sessioni get it sometimes in one of my unittests so i cannot provider repro code but i wonder what is by design reason for the errorupdate the error returns as sqlexception from sql server 2008 a place where i get the error seems to be singlethreaded but probably i have unittests interaction as i get the error where run several tests at once mstest in vs2008sp1but the failing test looks likecreate an object and save it inside dbtransaction commitcreate transactionscopetrying to open a connection here i get sqlexception with such stacktracesystemdatasqlclientsqlexception transaction context in use by another session at systemdatasqlclientsqlconnectiononerrorsqlexception exception boolean breakconnection at systemdatasqlclientsqlinternalconnectiononerrorsqlexception exception boolean breakconnection at systemdatasqlclienttdsparserthrowexceptionandwarningtdsparserstateobject stateobj at systemdatasqlclienttdsparserrunrunbehavior runbehavior sqlcommand cmdhandler sqldatareader datastream bulkcopysimpleresultset bulkcopyhandler tdsparserstateobject stateobj at systemdatasqlclienttdsparsertdsexecutetransactionmanagerrequestbyte buffer transactionmanagerrequesttype request string transactionname transactionmanagerisolationlevel isolevel int32 timeout sqlinternaltransaction transaction tdsparserstateobject stateobj boolean isdelegatecontrolrequest at systemdatasqlclientsqlinternalconnectiontdspropagatetransactioncookiebyte cookie at systemdatasqlclientsqlinternalconnectionenlistnonnulltransaction tx at systemdatasqlclientsqlinternalconnectionenlisttransaction tx at systemdatasqlclientsqlinternalconnectiontdsactivatetransaction transaction at systemdataproviderbasedbconnectioninternalactivateconnectiontransaction transaction at systemdataproviderbasedbconnectionpoolgetconnectiondbconnection owningobject at systemdataproviderbasedbconnectionfactorygetconnectiondbconnection owningconnection at systemdataproviderbasedbconnectionclosedopenconnectiondbconnection outerconnection dbconnectionfactory connectionfactory at systemdatasqlclientsqlconnectionopeni have found these postsbut i cannot understand what multiple threads sharing the same transaction in a transaction scope will cause the following exception transaction context in use by another session means all words are understandable but not the point i actually can share a system transaction between threads and there is even special mechanism for this dependenttransaction class and transactiondependentclone methodi am trying to reproduce a usecase from the first postmain thread creates dtc transaction receives dependenttransaction created using transactioncurrentdependentclone on the main threadchild thread 1 enlists in this dtc transaction by creating a transaction scope based on the dependent transaction passed via constructorchild thread 1 opens a connectionchild thread 2 enlists in dtc transaction by creating a transaction scope based on the dependent transaction passed via constructorchild thread 2 opens a connectionwith such codeusing systemusing systemthreadingusing systemtransactionsusing systemdatausing systemdatasqlclientpublic class program private static string connectionstring initial catalogdbdata sourceuser iduserpwdpwd public static void main int max 100 forint i 0 i maxi usingvar ctx new transactionscope var tx transactioncurrent make the transaction thistributed using sqlconnection con1 new sqlconnectionconnectionstring using sqlconnection con2 new sqlconnectionconnectionstring con1open con2open showsystranstatus dependenttransaction dtx transactioncurrentdependentclonedependentcloneoptionblockcommituntilcomplete thread t1 new threado workcallbackdtx thread t2 new threado workcallbackdtx t1start t2start t1join t2join ctxcomplete traceroot transaction completes private static void workcallbackdependenttransaction dtx usingvar txscope1 new transactionscopedtx using sqlconnection con2 new sqlconnectionconnectionstring con2open traceconnection opened showdbtranstatuscon2 txscope1complete tracedependant tran completes private static void tracestring msg consolewritelinethreadcurrentthreadmanagedthreadid msg private static void showsystranstatus string msg if transactioncurrent null msg transactioncurrenttransactioninformationthistributedidentifiertostring else msg no sys tran trace msg private static void showdbtranstatussqlconnection con var cmd concreatecommand cmdcommandtext select 1 var c cmdexecutescalar tracetrancount c it fails on completes call of root transactionscope but error is differentunhandled exception systemtransactionstransactionindoubtexception the transaction is in doubt pired the timeout period elapsed prior to completion of the operation or the server is not respondingto sum up i want to understand what transaction context in use by another session means and how to reproduce it,['.net'] +62917,how to get table cells evenly spaced i am trying to create a page with a number of static html tables on them what do i need to do to get them to thisplay each column the same size as each other column in the tablethe html is as followsspan classemphasisinterest ratesspanbr table cellpadding0px cellspacing0px classperformancetable trth classtableheaderthth classtableheadercurrent rate as at 31 march 2010thth classtableheader31 december 2009thth classtableheader31 march 2009thtr tr classtablerowtdindex1tdtd classperformancecell100tdtd100tdtd150tdtr tr classtablerowtdindex2tdtd classperformancecell050tdtd050tdtd050tdtr tr classtablerowtdindex3tdtd classperformancecell025tdtd025tdtd025tdtrtablespansource btspanbr br span classemphasisstock marketsspanbr table cellpadding0px cellspacing0px classperformancetable trth classtableheaderthth classtableheaderas at 31 march 2010thth classtableheader1 month changethth classtableheaderqtd changethth classtableheader12 months changethtr tr classtablerowtdindex1tdtd classperformancecell116943tdtd classperformancecell588tdtd classperformancecell487tdtd classperformancecell4657tdtr tr classtablerowtdindex2tdtd classperformancecell195834tdtd classperformancecell768tdtd classperformancecell527tdtd classperformancecell5831tdtr tr classtablerowtdindex3tdtd classperformancecell567964tdtd classperformancecell607tdtd classperformancecell493tdtd classperformancecell4466tdtr tr classtablerowtdindex4tdtd classperformancecell294392tdtd classperformancecell830tdtd classperformancecell098tdtd classperformancecell4452tdtr tr classtablerowtdindex5tdtd classperformancecell97881tdtd classperformancecell947tdtd classperformancecell785tdtd classperformancecell2652tdtr tr classtablerowtdindex6tdtd classperformancecell317tdtd classperformancecell1058tdtd classperformancecell682tdtd classperformancecell4484tdtrtablespansource bspanbr br i am also open to suggestion on how to tidy this up if there are any edit i should add that the cellpadding cellspacing attributes are require by a 3rd party pdf conversion app that we use,"['html', 'css']" +62935,the request was aborted could not create ssltls secure channel we are unable to connect to an https server using webrequest because of this error messagethe request was aborted could not create ssltls secure channelwe know that the server does not have a valid https certificate with the path used but to bypass this issue we use the following code that weve taken from another stackoverflow postprivate void somewhere servicepointmanagerservercertificatevalidationcallback new remotecertificatevalidationcallbackallwaysgoodcertificateprivate static bool allwaysgoodcertificateobject sender x509certificate certificate x509chain chain sslpolicyerrors policyerrors return truethe problem is that server never validates the certificate and fails with the above error does anyone have any idea of what should i doi should mention that a colleague and i performed tests a few weeks ago and it was working fine with something similar to what i wrote above the only major difference weve found is that i am using windows 7 and he was using windows xp does that change something,"['c#', 'asp.net']" +62942,any advantages of hover over mouseover in jquery i am fairly new to jquery apii have been using mouseover but i have never used hover beforeso i am wondering if i should use hover instead,['jquery'] +62947,iphone app launch times and core data migration i have a core data application which i plan to update with a new schema the lightweight migration seems to work but it takes time proportional to the amount of data in the database this occurs in the didfinishlaunchingwithoptions phase of the appi want to avoid app failed to launch in time problems so i assume i cannot keep the migration in the didfinishlaunchingwithoptions methodi assume the best method would involve performing the migration in a background thread i assume also that i would need to defer loading of the main viewcontroller until the loading completes to avoid using the managedobjectcontext until initialization completesdoes this make sense and is there example code maybe in apple sample projects of this sort of initialization,['iphone'] +62949,cannot refer to a template name nested in a template parameter i have the following codetemplate typename providerinline void use typedef providerdataint dwhere i am basically trying to use a template class member data of some provider class applied to int but i get the following errors utilcpp5 error expected initdeclarator before tokenutilcpp5 error expected or before tokeni am using gcc 433 on a solaris system,['c++'] +62959,rails i18n and routes in javascript sometimes it would be really handy to have the rails localization files available in javascript same is true for for the routes helpersi found these two plugins which are exactly doing thisexposing i18n to javascript rails routes in javascript routesmy questionsare there any other plugins gems doing similar things like the two abovewhats the right approach in rails meta tag additional data attributesthanks for any input,"['javascript', 'ruby-on-rails']" +62965,i want close a cfsocket i have create a socket with cfsocketmy program is correct but now i wanna close the socket client sidethere is a istructionthanks and sorry for my english xpmy codecfsocketref ss cfsocketcreate null pf inet sock stream ipproto tcp kcfsocketdatacallback acceptdatacallback contextcfsocketconnecttoaddres address 0here i wanna close the socket,"['iphone', 'objective-c']" +62967,why does the checkboxfor render an additional input tag and how can i get the value using the formcollection in my aspnet mvc app i am rendering a checkbox using the following code htmlcheckboxforiireceiversvpnotifications now i see that this renders both the checkbox input tag and a hidden input tag the problem that i am having is when i try retrieve the value from the checkbox using the formcollectionformvaluesreceiversvpnotificationsi get the value truefalse when looking at the rendered html i can see the following input idreceiversvpnotifications namereceiversvpnotifications valuetrue typecheckbox input namereceiversvpnotifications valuefalse typehiddenso the formvalues collection seems to join these two values since they have the same nameany ideas,['asp.net'] +62976,what is the best approach using jdbc for parameterizing an in clause say that i have a query of the formselect from mytable where mycol in and i want to parameterize the arguments to inis there a straightforward way to do this in java with jdbc in a way that could work on multiple databases without modifying the sql itself the closest question i have found had to do with c i am wondering if there is something different for javajdbc,"['java', 'sql']" +62977,returning an abstract class from a function is it possible to return an abstract classclass itself or a reference does not matter from a function,['c++'] +62978,can rails unit tests be run on a different environment than test we have a large multideveloper project under rails in which we are using tests for both models and controllers right now the developers have to switch the db parameters for the test environment to match their local dev environments before running tests i am wondering if there is a way to run those tests on any environment other than testfor example we have in databaseymltest database host username password devone devtwo i cannot find anything in the docs on this but maybe i am looking in the wrong place any ideasthanks,['ruby-on-rails'] +62981,weakhashmap iteration and garbage collection i am using a weaekhashmap to implement a cache i am wondering if i am iterating over the keys of this map and at the same time garbage collector is actively removing keys from this map would i receive a concurrentmodificationexception i do not think so because as far as i understand concurrentmodificationexception happens because of bugs in the application code where the developer forgot to understand that the same map is sharedused by other threads and in this case it should not happen but wondering how would jvm handle this when weakhashmap is not synchronized,['java'] +62990,how do i subtract two dates in djangopython i am working on a little fitness tracker in order to teach myself django i want to graph my weight over time so i have decided to use the python google charts wrapper google charts require that you convert your date into a x coordinate to do this i want to take the number of days in my dataset by subtracting the first weighin from the last weighin and then using that to figure out the x coords for example i could 100 by the result and increment the x coord by the resulting number for each y coordanyway i need to figure out how to subtract django datetime objects from one another and so far i am striking out on both google and here at the stack i know php but have never gotten a handle on oo programming so please excuse my ignorance here is what my models look like class goalmodelsmodel goal weight modelsdecimalfieldgoal weight max digits4 decimal places1 target date modelsdatetimefieldtarget date to reach goal set date modelsdatetimefieldwhen did you set your goal comments modelstextfieldblanktrue def unicode self return unicodeselfgoal weightclass weightmodelsmodel weight at a given date and time goal modelsforeignkeygoal weight modelsdecimalfieldcurrent weight max digits4 decimal places1 weigh date modelsdatetimefielddate of weighin comments modelstextfieldblanktrue def unicode self return unicodeselfweight def recorded todayself return selfdatedate datetimedatetodayany ideas on how to proceed in the view thanks so much,['python'] +62998,does net have a built in ienumerable for multiple collections i need an easy way to iterate over multiple collections without actually merging them and i could not find anything built into net that looks like it does that it feels like this should be a somewhat common situation i do not want to reinvent the wheel is there anything built in that does something like thispublic class multicollectionenumerablet ienumerablet private multicollectionenumeratort enumerator public multicollectionenumerableparams ienumerablet collections enumerator new multicollectionenumeratortcollections public ienumeratort getenumerator enumeratorreset return enumerator ienumerator ienumerablegetenumerator enumeratorreset return enumerator private class multicollectionenumeratort ienumeratort private ienumerablet collections private int currentindex private ienumeratort currentenumerator public multicollectionenumeratorienumerablet collections thiscollections collections thiscurrentindex 1 public t current get if currentenumerator null return currentenumeratorcurrent else return defaultt public void thispose if currentenumerator null currentenumeratorthispose object ienumeratorcurrent get return current public bool movenext if currentindex collectionslength return false if currentindex 0 currentindex 0 if collectionslength 0 currentenumerator collections0getenumerator else return false while currentenumeratormovenext currentenumeratorthispose currentenumerator null currentindex if currentindex collectionslength return false currentenumerator collectionscurrentindexgetenumerator return true public void reset if currentenumerator null currentenumeratorthispose currentenumerator null thiscurrentindex 1,"['c#', '.net']" +62999,in proper html must an be in a i need a few input elements but their values would not be submitted anywhere they are just going to be manipulated by some clientside javascript do i have to place them in a form to have legit html or can they just be freestanding,['html'] +63000,sql return true if list of records exists an alternative title might becheck for existence of multiple rowsusing a combination of sql and c i want a method to return true if all products in a list exist in a table if it can be done all in sql that would be preferable i have written a method that returns whether a single productid exists using the following sqlselect productid from products where productid productidif this returns a row then the c method returns true false otherwisenow i am wondering if i have a list of product ids not a huge list mind you normally under 20 how can i write a query that will return a row if all the product ids exist and no row if one or more product ids does not existmaybe something involving in likeselect from products where productid in 1 10 100 abcedithow the result is expressed is not important to me whether the query returns a 1 or 0 an empty resultset or a nonempty one true or false does not matter i would prefer the answer that is 1 easy to read and understand and 2 performanti was envisioning concatenating the list of product ids with the sql obviously this opens the code up to sql injection the product ids are actually varchar in this case the chance is slim but still want to avoid that possibility so if there is a way around this that would be better using sql server 2005product ids are varchar,"['c#', 'sql']" +63001,best way to programmatically detect ipadiphone hardware the reason i need to find out is that on an ipad a uipickerview has the same height in landscape orientation as it does in portrait on an iphone it is different the ipad programming guide introduces an idiom value to uidevice uidevice thisdevice uidevice currentdevice ifthisdeviceuserinterfaceidiom uiuserinterfaceidiompad ipad else iphone which works ok while youre in ipad 32 but not iphone 313 so it looks like there also needs to be an ifdef to conditionally compile that check likeif iphone os version min required 30200 uidevice thisdevice uidevice currentdevice ifthisdeviceuserinterfaceidiom uiuserinterfaceidiompad etc endifto me that is starting to look very clumsy whats a better way,['iphone'] +63005,nosql or ehcache caching i am building a route planner webapp using springhibernatetomcat and a mysql database i have a database containing read only data such as bus stop coordinates bus times which is never updated i am trying to make the app run faster each time the application is run it will preform approx 10 reads to the database to calculate a route i have setup a ehcache which greatly improves the read from database timesi am now setting terracotta ehcache thistributed caching to share the cache with multiple tomcat jvms this seems a bit complicated i have tried memcached but it was not performing as fast as ehcachei am wondering if a mongodb or rethis would be better suited i have no experience with nosql but i would appreciate if anyone has any ideas what i need is quick access to the read only database,['mysql'] +63009,javascript library to obfuscate or not to obfuscate that is the question i need to write a gui related javascript library it will give my website a bit of an edge in terms of functionality i can offer up until my competitors play with it long enough to figure out how to write it by themselves or finally hack the downloaded script i can accept the fact that it will be emulated over time thats par for the course its part of business i just want to have a few months breathing space where people go wow how the f did they do that which gives me a few months of free publicity and some momentum to move onto other thingsto be clear i am not even concerned about hard core hackers who will still hack the source thats a losing battle not worth fighting and in any case i accept that my code is not so precious however what i cannot bear is the idea of effectively simply handing over all the hard work that would have gone into the library to my competitors by using plain javascript that anyone can download and use if someone is going to use what i have worked on then i sure as hell do not want to simply hand it over to them i want them to work hard at decoding it if they can decode it they deserve to have the code they will most likely find out they could have written better code themselves they just did not have the business sense to put all the plain vanilla components in that particular order so i am not claiming that no one could have written this which would be a preposterous claim in any case but rather what i am saying is that no one up to now has made the functionality i am talking about available to this particular industry and i thinking as an entrepreneur rather than a geekcoder want to milk it for all its worth while it lasts ie until it inevitably gets hackedit is an established fact that not one website in the industry i am attacking has this functionality so the value of such a library is undeniable and is not up for thiscussion ie thats not what i am asking herewhat i am seeking to find out are the pros and cons of obfuscating a javascript library so that i can come to a final decision two of my biggest concerns are debugging and subtle errors that may be introduced by the obfuscator i would like to knowhow can i manage those risks being able to debug faulty code ensuringminimizing against obfuscation errorsare there any good quality industry standard obfuscators you can recommend preferably something you use yourselfwhat are your experiences of using obfuscated code in a production environment,['javascript'] +63016,do you know of a bleedingedge html5 leveraging legacyignoring javascript framework whats the best framework sort of jquery extjs etc like to use if i would like to intensively use all the freshest technologies of the html5 stack provided by modern browsers firefox 7 safari 5 chrome 14 and have absolutely no need to support any legacy browsers incl no need in ie support at all and no need in firefox or chrome prior to the latest stable releases i would like to get all the newest available goodness without having even abstracted by a library layer a line of code meant just fore legacy compatibility or keeping any legacyinduced things in mindto soften the filter taking very humble hope of such an ideally fresh framework to exist the least the maximum level of legacy support i would like to agree is not supporting ie versions older than ie8 or better just not supporting ie at all,"['javascript', 'jquery']" +63034,c console output in netbeans when i run a c program in netbeans on a mac that has cout or printf statements the output is thisplayed in a terminal opened using x11 is there a console built into netbeans if yes how do i change the output to itthanksspencer,['c++'] +63044,how can i keep track of the index path of a button in a table view cell i have a table view where each cell has a button accessory view the table is managed by a fetched results controller and is frequently reordered i want to be able to press one of the buttons and obtain the index path of that buttons table view cell i have been trying to get this working for days by storing the row of the button in its tag but when the table gets reordered the row becomes incorrect and i keep failing at reordering the tags correctly any new ideas on how to keep track of the buttons cells index path,['iphone'] +63055,how do i use googles gson api to deserialize json properly in short this is a sketch of the json object i want to parse in java object1 item1 string array object item2 more items object2 more objectsthese are the pojo s i created for parsing i will leave out the import statements for brevitys sake 1 the representation of the complete json objectpublic class jobjectcontainer private listjobject jobjects public jobjectcontainer get set methods2 the representation of the nested objects public class jobject private string id private listjnode jobjects public jobject get set methods3 the representation of the items public class jnode private jsonelement item1 private jsonelement item2 more item fields public jnode get set methodsnow creating a gson instance filereader for importing the jsonfile gson gson new gson jobjectcontainer joc gsonfromjsonjsonfilejobjectcontainerclass i get a nullpointerexception whenever i try to access the parseable object eg through a listiterator gson does however create an object of the class i specified and does not throw any subsequent errorsi know that this has been done before so what am i missingtia,['java'] +63059,what happens if the first part of an ifstructure is false i was wondering what happens when a program processes an ifstructure with multiple conditions i have an idea but i am not sure about it i will give an example liststring mytestlist nullif mytestlist null mytestlistcount 0 processthe list is null when processing the if statement will it go from left to right exiting the if as soon as one condition is falsei have tried it and seems to throw no errors so i assume the above explains it but i am not sure,['c#'] +63062,difference between page refresh and page postback my question is what is the difference between page refresh if i press f5 and postback if i press a buttoncan anyone please tell methanks in advance,['asp.net'] +63069,treemap sort by value i want to write an comparator that will let me sort treemap by value instead of the default natural sorting i tried something like this but cannot find out what went wrongimport javautilclass treemap public static void mainstring args systemoutprintlnthe main byvalue cmp new byvalue mapstring integer map new treemapstring integercmp mapputde10 mapputab 20 mapputa5 for mapentrystringinteger pair mapentryset systemoutprintlnpairgetkeypairgetvalue class byvalue implements comparatormapentrystringinteger public int comparemapentrystringinteger e1 mapentrystringinteger e2 if e1getvalue e2getvalue return 1 else if e1getvalue e2getvalue return 0 else return 1 i guess what am i asking is what controls what gets passed to comparator function can i get an mapentry passed to comparator,['java'] +63075,using cassandra instead of memcache i keep reeding those articles from different sources that big sites are switching from memcache to cassandra coming from a mysql background i will get a slight headache trying to see the proscons when compared to each othercan you help me out to learn more about this,['mysql'] +63084,how to round an float value and convert it into nsinteger value in the iphone sdk i need to round a float value and convert it into an nsinteger valuefor examplefloat f 90909088i want the result to be 91 how to get rid of this,['objective-c'] +63088,how do i center align horizontal menu i need to center align a horizontal menui have tried various solutions including the mix of inlineblock block centeralign etc but have not succeededhere is my codediv classtopmenudesign top menu content start ul idtopmenu firstlevel li classfirstli idnode id 64diva hrefspanom kampanjenspanadivli li idnode id 65diva hrefspanfakta om inneklimaspanadivli li classlastli idnode id 66diva hrefspanstatistikkspanadivli ul top menu content end divupdatei know how to center align the ul within the div that can be accomplished using sarfrazs suggestionbut the list items are still floated left within the uldo i need javascript to accomplish this,['css'] +63094,crossplatform way to change java process priority i need to invoke jar file in separate jvm from another java application and it very cpuconsuming so it should run with background priority in order not to affect the rest of the system is there any crossplatform method to do this,['java'] +63097,does waitpid yield valid status information for a child process that has already exited if i fork a child process and the child process exits before the parent calls waitpid then is the exit status information that is set by waitpid still valid if so when does it become not valid ie how do i ensure that i can call waitpid on the child pid and continue to get valid exit status information after an arbitrary amount of time and how do i clean up tell the os that i am no longer interested in the exit status information for the finished child processi was playing around with the following code and it appears that the exit status information is valid for at least a few seconds after the child finishes but i do not know for how long or how to inform the os that i would not be calling waitpid againinclude asserthinclude pthreadhinclude stdiohinclude stdlibhinclude unistdhinclude syswaithint main pid t pid fork if pid 0 fprintfstderr failed to forkn return exit failure else if pid 0 code for child process exit17 else code for parent sleep3 int status waitpidpid status 0 waitpidpid status 0 call waitpid again just to see if the first call had an effect assertwifexitedstatus assertwexitstatusstatus 17 return exit success,['c'] +63104,performselectorwithobjectafterdelay not working from scrollviewdidzoom i feel like i should know this but i have been stumped for hours now and i have run out of ideasthe theory is simple the user manipulates the zoom and positioning in a scrollview using a pinch if they hold that pinch for a short period of time then the scrollview records the zoom level and content offsetsso i thought i would start a performselectorwithobjectwithdelay on the scrollviewdidzoom delegate method if it expires then i record the settings i delete the scheduled call every time scrollviewdidzoom is called and when the pinch gesture finishesthis is what i have voidscrollviewdidzoomuiscrollview scrollview nslogresetting timer nsobject cancelpreviousperformrequestswithtargetself selectorselectorpositionlock objectnil self performselectorselectorpositionlock withobjectnil afterdelay04 voidpositionlock nslogposition locked voidscrollviewdidendzoominguiscrollview scrollview withviewuiview view atscalefloatscale nslogdeleting timer nsobject cancelpreviousperformrequestswithtargetself selectorselectorpositionlock objectnilthis is the output20100519 224301931 resetting timer20100519 224301964 resetting timer20100519 224302231 resetting timer20100519 224302253 resetting timer20100519 224302269 resetting timer20100519 224302298 resetting timer20100519 224305399 deleting timer as you can see the delay between the last and second last events should have been more than enough for the delayed selector call to executeif i replace performselectorwithobjectwithdelay with plain old performselector i get this20100519 2308303 resetting timer20100519 2308303 position locked20100519 230830366 resetting timer20100519 230830367 position locked20100519 230830688 deleting timer which is not what i want but serves to show that it is only the delay that is causing it to not function not something to do with the selector not being declared in the header being misspelt or any other reasonany ideas as to why it is not working,['iphone'] +63120,how can i time a code segment for testing performance with pythons timeit i have a python script which works just as it should but i need to write the time for the execution i have googled that i should use timeit but i cannot seem to get it to workmy python script looks like thisimport sysimport getoptimport timeitimport randomimport osimport reimport ibm dbimport timefrom string import maketransmyfile openresults updatetxt afor r in range100 rannumber randomrandint0 100 update update table set val i where mycount 2010 and mycount 2012 and number 250 rannumber print rannumber conn ibm dbpconnectdsnmydbusrnamesecretpwdfor r in range5 print run sn r ibm dbexecutequery stmt query stmt ibm dbprepareconn updatemyfilecloseibm dbcloseconnwhat i need it the time it takes the execution of the query and written to the file results updatetxt the purpose is to test an update statement for my database with different indexes and tuning mechanisms,['python'] +63140,debugging php in aptana 20 i am a real newbie when it comes to php debugging so forgive my stupidity i have a simple html form that submits to a php script and i want to debug that script and see whats being sent from the formmy aptana has two two php interpreters installedzend debugger on port 101 and xdebug on 90i have the firefox aptana addon installedi have my html page on the following url running locallyhttp3ilatesthtmlin the ide i open the php script and add some breakpoints i then open the latesthtml and i click on the debug button it launches the html page in a local webserver running ati then fill out the form and submit at which point the debugger tells me the js debugger has terminated but it does not stop at my break pointsi have had a good read around and i cannot find anything which helps me which makes me think it is something pretty easy and i am being a bit dumb,['php'] +63148,php explode and set to empty string the missing pieces whats the best way to accomplish the followingi have strings in this format s1 name1type1 pipe is the separators2 name2type2s3 name3 in some of them type can be missinglet us assume namen typen are strings and they can not contain a pipesince i need to exctract the name type separetly i dotemp explode s1name temp0type issettemp1 temp1 is there an easier smarter whatever faster way to do this without having to do issettemp1 or counttempthanks,['php'] +63151,how to make one aspnet mvc site derive from another my question is similar to aspnet 2 projects to share same files but with an aspnet mvc slantbasically we have two sites one being based mostly on the other roughly 90 views controllers images in the second are identical to the first however in some cases the views may be different or a controller in the second site may be different to the firstare there any simple ways of achieving this in aspnet mvcso far weve looked at using linked files to have two totally seperate projects where the second project shares the files it needs from the firstone problem with this approach is that most pages in the second project do not literally exist in the virtual directory it makes debugging a pain you have to publish in order to generate the files so you can debugdoes anyone have any better approaches or ways this approach can be simplified,"['c#', 'asp.net']" +63152,subtracting from a datetime i want to subtract from a datetime exampledate1 13012004 1220result subtractdate115expected output13012004 120500how do i do this,['c#'] +63154,how to remove duplicate entries from a mysql db i have a table with some ids titles i want to make the title column unique but it has over 600k records already some of which are duplicates sometimes several dozen times overhow do i remove all duplicates except one so i can add a unique key to the title column after,['mysql'] +63164,500 worker threads what kind of thread pool i am wondering if this is the best way to do this i have about 500 threads that run indefinitely but threadsleep for a minute when done one cycle of processing executorservice es executorsnewfixedthreadpoollistsize1 for int i 0 i listsize i esexecutecoreappvectorelementati coreappvector is a vector of extends thread objects the code that is executing is really simple and basically just thisclass athread extends thread public void run whiletrue threadsleepone minute lots of computation every minute i do need a separate threads for each running task so changing the architecture is not an option i tried making my threadpool size equal to runtimegetruntimeavailableprocessors which attempted to run all 500 threads but only let 8 4xhyperthreading of them execute the other threads wouldnt surrender and let other threads have their turn i tried putting in a wait and notify but still no luck if anyone has a simple example or some tips i would be grateful well the design is arguably flawed the threads implement geneticprogramming or gp a type of learning algorithm each thread analyzes advanced trends makes predictions if the thread ever completes the learning is lost that said i was hoping that sleep would allow me to share some of the resources while one thread is not learningso the actual requirements are how can i schedule tasks that maintain state and run every 2 minutes but control how many execute at one time,['java'] +63171,what is a crossplatform way to get the current directory i need a crossplatform way to get the current working directory yes getcwd does what i want i thought this might do the trickifdef win32 include directh define getcwd getcwd stupid msft deprecation warningelif include unistdhendifinclude stringinclude iostreamusing namespace stdint main string s cwdgetcwdnull0 cout cwd is s cwd endli got this reading getcwd at msdngetcwd at kernelorggetcwd at applecomthere should be no memory leaks and it should work on a mac as well correctupdate i fear something is still wrong here i am trying to avoid creating a char array with a determined length as there is no proper way to get a decent length for getcwdchar a cwd getcwdnull0string s cwda cwdfreea cwd or delete a cwd,['c++'] +63175,c assignment stylish or performance having been writing java code for many years i was amazed when i saw this c statementint abint c a1 ba2 b3my question is is this a choice of coding style or does it have a real benefit i am looking for a practicle use casei think the compiler will see it the same as the followingint a1 ba2int c b3whats the offical name for this i assume it is a standard cc syntax,['c'] +63195,is there a way to specify the local port to used in tcpclient i am currently using this function call to create my tcpclientclientsocket new tcpclientlocalhost clientportbut the clientport is the servers portis there a way for me to specify the client port using tcpclientthanks,['c#'] +63205,remove favicon using javascript in google chrome how can you remove the favicon using javascript in google chrome the goal is to return it to the browser default which is in this case a blank imagei found this question but it does not work if you leave the linkhref attribute as emptyeven if the favicon is set because there is a faviconico file on the server i would like to remove it and set it back to the defaultthis only needs to work in chromethanks,['javascript'] +63215,cnet generic methods and inheritance is it possible to do the following with generics in cnetpublic abstract class a public abstract t methodbtstring spublic class c a public override datetime methodbstring s ie have a generic method in a base class and then use a specific type for that method in a sub class,['c#'] +63218,horizontal uitableview i want implement a layout in my ipad application that has a uitable view that scrolls left and right rather then up and down so rather than row 1row 2row 3 scrolling vertically it would be row 1 row2 row 3scrolling horizontally i have seen that uitableview is designed to only do vertical scrolling so doing a transform does not give the desired effect is there a standard way to do this taking advantage of a datasource provider like uitableview providesi basically want to do somthing similar to what the bbc news reader app on the ipad does with the list of stories to select from thanks,['iphone'] +63220,python raw strings and trailing backslash i ran across something once upon a time and wondered if it was a python bug or at least a misfeature i am curious if anyone knows of any justifications for this behavior i thought of it just now reading code like a pythonista which has been enjoyable so far i am only familiar with the 2x line of pythonraw strings are strings that are prefixed with an r this is great because i can use backslashes in regular expressions and i do not need to double everything everywhere it is also handy for writing throwaway scripts on windows so i can use backslashes there also i know i can also use forward slashes but throwaway scripts often contain content cutpasted from elsewhere in windowsso great unless of course you really want your string to end with a backslash there is no way to do that in a raw stringin 9 rnout9 nin 10 rabcnout10 abcnin 11 rabc file ipython console line 1 rabc syntaxerror eol while scanning string literalin 12 rabcout12 abcso one backslash before the closing quote is an error but two backslashes gives you two backslashes certainly i am not the only one that is bothered by thisthoughts on why raw strings are raw except for backslashquote i mean if i wanted to embed a single quote in there i would just use double quotes around the string and vice versa if i wanted both i would just triple quote if i really wanted three quotes in a row in a raw string well i guess i would have to deal but is this considered proper behaviorthis is particularly problematic with folder names in windows where the backslash is the path delimeter,['python'] +63231,how do i practice c programming at home i have took c programming class while back ago since i am done with the class and do not have any access to the school lab anymore can anybody give me suggestion how do i practice my c at home thanks,['c'] +63244,systemexit in servlet what would happen if someone writes systemexit in a servlet would the server or the application crash,['java'] +63254,how to localize bundle thisplay name in iphone app how can i localize bundle thisplay name of an iphone appthe name thisplayed in iphone main screen under app iconi wish a single binary bundle package which will be thisplayed multilingually,['iphone'] +63258,how to check if a custom protocol supported we are using software that registers its own protocol we can run application from browser then by link likecustomprotocoldo thisbut is there a way to check is such custom protocol supported by users system if not we would like to ask user to install software firstegif canhandle customprotocol run softwareelse ask to installediti know about protocollong property but it works only in ie,['javascript'] +63260,exceptionhandler does not handle the thrown exceptions i have a method in my controller which will handle the exceptions thrown by the application so i have a method like this onecontrollerpublic class exceptioncontroller requestmappingvalueerror exceptionhandlervalueexceptionclass nullpointerexceptionclass public string showerrorexception e model model return tileserror and to try i if it works i throw a nullpointerexception in another method in other method controllerboolean a trueifa throw new nullpointerexceptionafter the exception is thrown it is printed in the jsp but it does not go throw my showerror method i have set a breakpoint there and it never enters showerror method will catch the exception and will show different error pages depending on the exception type though now it always shows the same error page if i go to the url error it shows the error page so the showerror method is oki am using spring 3what can be the problemthanks,['java'] +63269,most efficient way to update with linq to sql can i update my employee record as given in the function below or do i have to make a query of the employee collection first and then update the data public int updateemployeeapp3 employee employee dbcontextdatacontext db new dbcontextdatacontext dbapp3 employeesattachemployee dbsubmitchanges return employeepkey or do i have to do the followingpublic int updateemployeeapp3 employee employee dbcontextdatacontext db new dbcontextdatacontext app3 employee emp dbapp3 employeessinglee epkey employeepkey dbapp3 employeesattachemployemp dbsubmitchanges return employeepkeybut i do not want to use the second option is there any efficient way to update datai am getting this error by using both waysan attempt has been made to attach or add an entity that is not new perhaps having been loaded from another datacontext this is not supported,"['c#', 'asp.net']" +63275,suntlsrsapremastersecret keygenerator not available i encountered an error when my application tries to load a rsa algorithm provider class from java the exception stack is as followjavaxjmsjmsexception rsa premaster secret errorat orgapacheactivemqutiljmsexceptionsupportcreatejmsexceptionsupportjava49at orgapacheactivemqactivemqconnectionsyncsendpacketactivemqconnectionjava1255at orgapacheactivemqactivemqconnectionensureconnectioninfosentactivemqconnectionjava1350at orgapacheactivemqactivemqconnectionsetclientidactivemqconnectionjava388at comtrendmicrotmsmtmsmagentopentmsmagentjava63caused by javaxnetsslsslkeyexception rsa premaster secret errorat comsunnetsslinternalsslrsaclientkeyexchangeinitrsaclientkeyexchangejava97at comsunnetsslinternalsslclienthandshakerserverhellodoneclienthandshakerjava634at comsunnetsslinternalsslclienthandshakerprocessmessageclienthandshakerjava226at comsunnetsslinternalsslhandshakerprocessloophandshakerjava516at comsunnetsslinternalsslhandshakerprocess recordhandshakerjava454at comsunnetsslinternalsslsslsocketimplreadrecordsslsocketimpljava884at comsunnetsslinternalsslsslsocketimplperforminitialhandshakesslsocketimpljava12at comsunnetsslinternalsslsslsocketimplwriterecordsslsocketimpljava623at comsunnetsslinternalsslappoutputstreamwriteappoutputstreamjava59at orgapacheactivemqtransporttcptcpbufferedoutputstreamflushtcpbufferedoutputstreamjava115at javaiodataoutputstreamflushdataoutputstreamjava106at orgapacheactivemqtransporttcptcptransportonewaytcptransportjava167at orgapacheactivemqtransportinactivitymonitoronewayinactivitymonitorjava237at orgapacheactivemqtransportwireformatnegotiatorsendwireformatwireformatnegotiatorjava168at orgapacheactivemqtransportwireformatnegotiatorsendwireformatwireformatnegotiatorjava84at orgapacheactivemqtransportwireformatnegotiatorstartwireformatnegotiatorjava74at orgapacheactivemqtransportfailoverfailovertransportdoreconnectfailovertransportjava715at orgapacheactivemqtransportfailoverfailovertransport2iteratefailovertransportjava115at orgapacheactivemqthreadpooledtaskrunnerruntaskpooledtaskrunnerjava122at orgapacheactivemqthreadpooledtaskrunner1runpooledtaskrunnerjava43at javautilconcurrentthreadpoolexecutorworkerruntaskthreadpoolexecutorjava886at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava908at javalangthreadrunthreadjava637caused by javasecuritynosuchalgorithmexception suntlsrsapremastersecret keygenerator not availableat javaxcryptokeygeneratorinitdashoa13at javaxcryptokeygeneratorgetinstancedashoa13at comsunnetsslinternalssljssejcegetkeygeneratorjssejcejava223at comsunnetsslinternalsslrsaclientkeyexchangeinitrsaclientkeyexchangejava89 22 morei have googled the error message and most of posts says it is because jvm cannot find sunjce providerjar however i can find the file in libraryjavahomelibext folderthe platform is mac os x 106 and java version is 160 17my questions arewhy jvm does not search libraryjavahomelibext for jar filescan we change classpath or javaextdirs property by modify any config fileany suggestion to solve this problemthanks in advance,['java'] +63281,warning while installing the rails plugin i am getting the following warning while installing any plugin in my rails applicationusrlocallibrubygems191gemsactivesupport235libactive supportcore extkernelagnosticsrb7 warning insecure world writable dir usrlocalbin in path mode 0407can someone please tell me how to solve this problemthanks,"['ruby-on-rails', 'ruby']" +63283,can net convert yes no to boolean without if you would think there would be a way using directcast trycast ctype etc but all of them seem to choke on it egctypeyes booleanyou getsysteminvalidcastexception conversion from string yes to type boolean is not valid,['.net'] +63311,is there an equivalent in c for c templates in the code i am writing i need fooint char and fooint int functionsif i was coding this in c i would use templates is there any equivalent for c or should i use void pointers how,['c'] +63316,api for webm video conversion does anyone know about any prototype c apis for converting video to googles new webm video format,['c#'] +63329,cannot declare an abstract method private i want to do this yet i cannot here is my scenario and rational i have an abstract class for test cases that has an abstract method called test the test method is to be defined by the subclass it is to be implemented with logic for a certain application such as crmapptestcase extends companytestcase i do not want the test method to be invoked directly i want the super class to call the test method while the sub class can call a method which calls this and does other work too such as setting a current datetime right before the test is executed for example example codepublic abstract class companytestcase i wish this would compile but it cannot be declared private private abstract void test public testcaseresult performtest do some work which must be done and should be invoked whenever this method is called it would be improper to expect the caller to perform initialization testcaseresult result new testcaseresult resultsetbegintimenew date long time systemcurrenttimemillis test invoke test logic resultsetdurationsystemcurrenttimemillis time return result then to extend thispublic class crmapptestcase extends companytestcase public void test test logic here then to call ittestcaseresult result new crmapptestcaseperformtest,['java'] +63339,fast read of certain bytes of multiple files in cc i have been searching in the web about this question and although there are many similar questions about readwrite in cc i have not found about this specific taski want to be able to read from multiple files 256x256 files only sizeofdouble bytes located in a certain position of each file right now my solution is for each fileopen the file read binary modefstream ftestcurrent file ios baseout ios basebinaryseek the position i want to readftestseekgpositionsizeoftest value ios basebegread the bytesftestreadchar outputij sizeoftest valueand close the fileftestclosethis takes about 350 ms to run inside a for for structure with 256x256 iterations one for each fileq do you think there is a better way to implement this operation how would you do it,"['c++', 'c']" +63354,c how to test if proxy is working or not ia ve got a pretty big list with proxy servers and their corresponding ports how can i check if they are working or not,['c#'] +63369,permanently set postgresql schema path i need to set schema path in postgres so that i do not every time specify schema dot table eg schema2table set schema path set schema path abconly seems to work for one query session on mac after i close query window the path variable sets itself back to default how can i make it permanent,['sql'] +63370,android how to post app ratingcomments to market from within app this is a simple question is there a way to allow users to enter in a comment and or rating for my app from directly within my app and have that data posted back to the android market if so what would the code for that look like if i used an edittext view to allow user input if not then is my only other option directly linking to my app in the market ie the user clicks the link in my app or a button and the market app launches with my app page thisplayed for exampleviewsetonclicklistener new onclicklistener public void onclickview v startactivity new intent intentaction view uriparsemarketdetailsidpackagename where packagename is replaced by my apps package name from the manifestthanks,['android'] +63371,should i learn a operating system specific language or something like java i am torn i want to start making applications for os x there is a specifically underserved market that i would like to tap but i do not know if i should develop it only for the mac with cocoa and objective c or if i should develop it with java and javafxi guess my question is is java robust enough to handle the same things as objective c on mac and c net on windows,"['c#', 'java', 'objective-c']" +63377,is it feasible to do net development using eclipse how feasible is it to use eclipse to develop net applications is it best just to go with visual studioupdate i am not especially concerned with the cost and i am using windows not linux i am mostly trying to avoid having to use two different idesanother way of asking this question is are there any good eclipse plugins for doing net development unfortunately the answer appears to be no,['.net'] +63382,my iphone app gets memory warning and killed at 68mb my app has a thread that does some time consuming job for more than a minute and the app consumes around 68mb of memory i receive a memory warning after sometime and then it gets killed there is nothing that i can release and i am using not even 7mb of memorydriving me crazyany advice please,['iphone'] +63392,tomcat cachecontrol jetty has a cachecontrol parameter can be specified webdefaultxml that determines the caching behavior of clients by affecting headers sent to clientsdoes tomcat has a similar optionin short i want to turn off caching of all pages delivered by a tomcat server andor by a specific webappupdateplease note that i am not referring to serverside caching i want the server to tell all clients browsers not to use their own cache and to always fetch the content from the server i want to do it for all resources including static resources css js etc at once,['java'] +63404,c library to load excel xls files i am looking for a free c library that can load xls files in both windows and linux if i had to make a choice linux would be the bare minimumi have tried libxl but got this amazing errorcannot read more cells in trial versionso now i am on the hunt for a free version unfortunately xlslib does not provide the ability to load existing xls filesthanks,['c++'] +63411,python newstyle classes and subclasses function can somebody explain to me why this works in python 25 class fobject passclass barfoo passprintfoo subclasses but this does not class foo passclass barfoo passprintfoo subclasses the latter returns attributeerror class foo has no attribute subclasses but i am not sure why i know this is related to oldstyle vs newstyle classes but i am not clear on why that would make this functionality unavailable clarification i am looking to understand why subclasses is not available in oldstyle i get that the method does not exist for oldstyle classes but i do not get what it is about newstyle that makes these new functions possible,['python'] +63420,python store a dict in a database whats the best way to store and retrieve a python dict in a database,['python'] +63425,how to compare two strings using a if in a stored procedure in sql server 2008 i want to do something like thisdeclare temp as varchar set tempmeasureiftemp measure select measure from measuretableelse select othermeasure from measuretable,['sql'] +63427,composite key dictionary i have some objects in list let us say listmyclass and myclass has several properties i would like to create an index of the list based on 3 properties of of myclass in this case 2 of the properties are ints and one property is a datetimebasically i would like to be able to do something likedictionary compositekey myclass myclasslistindex dictionary compositekey myclass populate dictionary with items from the listmyclass myclasslistmyclass amyclass dicitonarykeytripletherei sometimes create multiple dictionaries on a list to index different properties of the classes it holds i am not sure how best to handle composite keys though i considered doing a checksum of the three values but this runs the risk of collisions,['c#'] +63447,how to delete old image when update imagefield i am using django to create a stock photo site i have a imagefield in my model the problem is that when the user update the image field the original image file is not deleted from the hard thiskhow can i make to delete those images after an updatethanks,['python'] +63454,debugging the return value of a jquery selector i am looking for a way to debug what a jquery selector returns i have tried using tostring but that only ever returns object objectwhat i am actually trying to do is to attach a callback to radio buttons and onclickon one of the buttons i want to submit the enclosing formtherefore i try to do something like thisratingstars cancelshow false callback functionui type value event thisclosestformajaxsubmit unfortunately nothing happenshere is a complete example of what i am trying to doscript typetextjavascript srchttplocalhost80mediajsjqueryjsv142scriptscript typetextjavascript srchttplocalhost80mediajsjqueryformjsv243scriptscript typetextjavascript srchttplocalhost80mediajsjqueryuicustomminjsv18scriptscript typetextjavascript languagejavascript srchttplocalhost80mediajsjqueryuistarsjsv300b38scriptlink relstylesheet typetextcss mediaall hrefhttplocalhost80mediacssjqueryuistarscssv300b38 body script typetextjavascript function ratingchildrennotradiohide ratingstars cancelshow false callback functionui type value event alertnodename thisnodename thiseachfunction alertthishtml alertthislength script ul classlist li form classrating idrating1 actionsniphunterrate1 methodpost input typeradio namescore value1 idrating11 input typeradio namescore value2 idrating12 input typeradio namescore value3 idrating13 input typeradio namescore value4 idrating14 input typeradio namescore value5 idrating15 input typesubmit valuerate form li ulbody,['jquery'] +63460,transform search string into fulltext compatible search string i am working with the fulltext search engine of mssql 2008 which expects a search string like thiskeyword1 and keyword2 or keyword3my users are entering things like thisengine 2009san francisco hotel december xyzstuff in miami 1234something or something elsei am trying to transform these into fulltext engine compatible strings like theseengine and 2009san francisco and hotel and december and xyzstuff in miami 1234something or something elsei have a really difficult time with this tried doing it using counting quotation marks spaces and inserting etc but my code looks like horrible forandif vomitcan someone help,['c#'] +63477,mysqli do i really need to do resultclose mysqliclose just started using mysqli if i am working with small data sets on small websites trafficwise do i really need to use these all the timeresultclose mysqliclosealso for someone doing custom php and mysql work without a framework is mysqli the general preferred way of interacting with mysql,"['php', 'mysql']" +63485,c array of pointers in c if i want an array of pointers so that i may have them point to different objects at a latter stage what does the syntax look likeediti need to clarify what i am trying to do i guess i have a class foo that has and add method in the add method i take a reference to class bar i want to save that reference into a pointer array of bar the array of pointer bar will need to be expanded all the time this i have no problems with it is creating and array on the heap of pointers so that i may assign bar objects to them later what i have tried seems to fail as class bar does not have a default constructor which the compiler is complaining about this lead me to think that i was creating and array of actual objects which i did not want to doplease no stl and no i do not want to hear about how you think this is crazy etc that is your opinion,['c++'] +63494,listening to another window resize events in c i am implementing a small application observer that needs to attach itself to the bottom of another window observed the latter is not a window inside the application at this moment i solved by getting the hwnd of the window and querying periodically in a thread the location of the observed window moving the observer window accordingly however this is a very inelegant solution what i would like to do is to listen to the resize event of the observed window so that the observer will react only when necessaryi assume i should use a hook and i found plenty of ways of doing it but my lack of knowledge of the c winapi is blocking me in understanding which hook i need to create and how pinvokeparametersetci am pretty sure this is quite trivial and some of you familiar with cc and winapi will have the answer ready at hand thanks,['c#'] +63516,create graphic and save it as bitmap i have two questions1 i have a picturebox and its dock is set to fill when i resize the form i cannot create a graphic on the part of the picturebox that is extended what is the problem2 i want to convert the graphic that is created on the picturebox to bitmap and save it asjpg or bmp how can i do this,"['c#', '.net']" +63529,linux can recvmsg be used to receive the ip tos of every incoming packet can one use recvmsg to obtain the ip tos field of every incoming packet or does it just show the ip tos value that is set for the particular socket if not does anyone know of a solution to obtain the ip tos values of every incoming packets i am using a udp application and therefore do not get to view the ip tos field at the application layer as is the case with tcp thanks adding the code that i have written so far incase it helpsstruct msghdr msg struct iovec iov1 memsetmsg 0 sizeofmsgmsgmsg iov iovmsgmsg iovlen 1iov0iov base char pktiov0iov len sizeofpktstruct cmsghdr cmsgcmsg1 msgmsg control cmsgcmsgmsgmsg controllen sizeofstruct cmsghdrnret recvmsgudpsocket msg 0if nret 0 struct cmsghdr cmsg for cmsg cmsg firsthdrmsg cmsg null cmsg cmsg nxthdrmsgcmsg if cmsgcmsg level ipproto ip cmsgcmsg type ip tos cmsgcmsg len int tos uint8 t cmsg datacmsg int isecn tos inet ecn mask inet ecn ce printfthe tos i is ecn d n tos isecn,['c'] +63540,how to convert a table column to another data type i have a column with the type of varchar in my postgres database which i meant to be integers and now i want to change them unfortunately this does not seem to work using my rails migrationchange column table1 columnb integerwhich seems to output this sqlalter table table1 alter column columnb type integerso i tried doing thisexecute alter table table1 alter column columnb type integer using castcolumnb as integerbut cast does not work in this instance because some of the column are nullany ideaserrorpgerror error invalid input syntax for integer alter table table1 alter column columnb type integer using castcolumnb as integerpostgres v83,['ruby-on-rails'] +63542,in c are methods private by default if i have a method that does not specify its accessibility level will it be private by defaultvoid item propertychangedobject sender systemcomponentmodelpropertychangedeventargs e throw new notimplementedexception is the above method private,['c#'] +63558,datareader hardcode ordinals when returning data from a datareader i would typically use the ordinal reference on the datareader to grab the relevant columnif drhasrows consolewritelinedr0tostringor drgetstring0 or stringdr0i have always done this because i was advised at an early stage that using drcolumnname or a more elegant way of indexing causes a performance hithowever while all references to data entities are becoming increasingly stronglytyped i feel more uncomfortable with this i am also aware that the above does not check for dbnullwhat is the most robust way to return data from a datareader,"['c#', '.net']" +63564,html table td meaning in html table what does td stands for i mean literally what is it acronym for table division table data,['html'] +63572,custom collection implementing ienumerable i know that technically an interface is used for reading and not writting or editing however i want to add an add and addrange function to the following class here is what i currently have which is not workingpublic class hrefcollection ienumerablehref private ienumerablehref hrefs public ienumerablehref add href href yield return href public ienumerablehref addrange listhref hrefs foreach href href in hrefs yield return href public ienumeratorhref getenumerator return hrefsgetenumerator systemcollectionsienumerator systemcollectionsienumerablegetenumerator return hrefsgetenumerator i am not quite sure how to associate the yield return with the private listthanks for your help,['c#'] +63574,capturing mac os x system audio output with python i have been trying to hijack the mac os x system audio using pyaudio and save to a wav in python that is i do not want to record from an input device such as a microphone i want to grab the sound output from any or all applicationsi have followed the tutorials on the pyaudio site but these do not appear to cover my use case and when i try to read from the output stream i unsurprisingly get the pacannotreadfromanoutputonlystream exception fair enough is there a way to do what i am proposing with the pyaudio or other foss python library,['python'] +63575,vector vs collectionssynchronizedlistarraylist vector is synchronized arraylist is not synchronized but we can synchronize an arraylist by collectionssynchronizedlistalist so which will perform better and faster,['java'] +63591,what effect does static const have on a namespace member myclasshnamespace mynamespace static const double gasconstant 1987 class myclass constructors methods etc i previously had gasconstant declared within the myclass declaration and had a separate definition in the source file since c does not support const initialization of nonintegral types i however need to access it from other files and also logically it seems like it should reside at the namespace levelmy questions is what effect does static const have in this case clearly const means i cannot assign a new value to gasconstant but what does a static member at the namespace mean is this similar to static at file scope where the member is not accessible outside of the unit,['c++'] +63595,why is ii valid in python i accidentally came across this weird but valid syntaxi3print ii outputs 6print ii outputs 6print ii outputs 0print ii outputs 6 for every even no of minus symbol it outputs 6 else 0 whydoes this do anything usefulupdate do not take it the wrong wayi love pythonone of pythons principle says there should be one and preferably only one obvious way to do it it seems there are infinite ways to do i1,['python'] +63602,zeroing out memory gcc 4 c89i am just wondering what most c programmers do when they want to zero out memoryfor example i have a buffer of 1024 bytes sometimes i do thischar buffer1024 0which will zero all byteshowever should i declare it like this and use memsetchar buffer1024memsetbuffer 0 sizeofbufferis there any real reason you have to zero the memory what is the worst that can happen by not doing it,['c'] +63604,java increase xmx dynamically at runtime i have a jvm server in my machine now i want to have 2 apservers of mine sitting in same machine however i want the standby one to have a really low amount of memory allocated with xmx because its passive one the main server active goes down i want to allocate more memory to my passive server which is already up without restarting it i have have them both having too much xmx note they would consume memory at startup and i cant allow possibility of outofmemoryso i want passive low xmxonce active goes down i want my passive to receive much more xmxis there a way for me to achieve thatthanks,['java'] +63606,force all aspnet cache to expire is there a method or something to force the expiration of all of the entries in the cache collection of the httpcontext,"['c#', 'asp.net']" +63615,using camera in the android emulator i wish to simulate camera in the android emulator using the webcam basically i need to only take photos with the camera in the emulator live preview is not needed ie if it makes it any easieri followed the tutorial here which is the only one i could find that was close to my requirements but many of the libraries used in that tutoriallike androidhardwarecameradevice are not available in present sdk and are replaced by new librarieslike androidhardwarecameraany help on how to do this in the present sdk21 or 22 would be much appreciated,['android'] +63624,c stop and continue i need some way to do the following efficiently in cmake program execution stop until certain value is changednote i do not want to make it with a while loop to avoid wasting cpu powereditand i want it to respond as quickly as possible after value has changededit this will be inside my class method that is called by another code however the value to be checked is inside my class the method is supposed to wait until others code evaluate and change my value then it must continue to do its work unfortunately this is done many timesso i need to care for performance,['c#'] +63628,replace in java rhino jsr223 with actual file name in my code all of the scripts are contained in js files whenever one of the scripts contains an error i get thisjavaxscriptscriptexception sunorgmozillajavascriptinternalecmaerror referenceerror nonexistant is not defined unknown source5 in unknown source at line number 5what bugs me is the unknown source multiple files are in one scriptcontext and it can be hard to track down an error it also looks horribleis there a way to replace unknown source with the actual file name none of the methods i see support passing a file object so i am really confused here,['java'] +63634,using pythons configparser to read a file without section name i am using configparser to read the runtime configuration of a scripti would like to have the flexibility of not providing a section name there are scripts which are simple enough they do not need a section configparser will throw the nosectionerror exception and will not accept the filehow can i make configparser simply retrieve the key value tuples of a config file without section names for instancekey1val1key2val2i would rather not write to the config file,['python'] +63654,hibernate criteria query to match against all child collection elements this question is very similar to this one but the responses were minimal to that questioni have a parent class with a set of child entities the child entities are just a wrapper for a string and live in a different table to the parent entity i want to have a criteria query that returns the parent entities when all the members of the set of child entities return true to a condition this condition is matching against one of a list of strings heres where i amcriteria c criteriacriteria ands ccreatecriteriaandsthisjunction this restrictionsthisjunctionfor string value values thisaddrestrictionslikevalue value andsaddthisreturn listcands is the set of entities with a value field that is a stringcriteria creates a criteria for the parent class list just calls criterialistthis is just matching against any of the elements rather than allhope this makes sense any help much appreciated,['java'] +63662,does changing the background also change the padding of a linearlayout i have the following linearlayout what i do not understand is if i set the background to another image the padding information are reset is there a way to prevent thislinearlayout androidididapanel androidorientationhorizontal androidlayout widthfill parent androidlayout heightwrap content androidbackgrounddrawablebkground androidpaddingleft15dp androidpaddingright15dp some children here linearlayouti see the position of the children get shifted when i change the background drawable of the linearlayout apanel,['android'] +63672,concatenate all list content in one string in c how do i concatenate all content of a list in one string in c,['c#'] +63695,tipsresourcespatterns for learning to implement a basic orm i have seen various mvc frameworks as well as standalone orm frameworks for php as well as other orm questions here however most of the questions ask for existing frameworks to get started with which is not what i am looking for i have also read this so question but i am not sure what to make of it as the answers are vagueinstead i figured i would learn best by getting my hands dirty and actually writing my own orm even a simple one except i do not really know how to get started especially since the code i see in other orms is so complicatedwith my php 52x this is important mvc framework i have a basic custom database abstraction layer that hasvery simple methods like connecthost user pass base querysql binds etcsubclasses for each dbms that it supportsa class and respective subclasses to represent sql result setsbut does not haveactive record functionality which i assume is an orm thing correct me if i am wrongedit to clarify i only have a database abstraction layer i do not have models yet but when i implement them i want them to be native orm models so to speak hence this questioni have read up a little about orm and from my understanding they provide a means to further abstract data models from the database itself by representing data as nothing more than phpbased classesobjects again correct me if i am wrong or have missed out in any waystill i would like some simple tips from anyone else whos dabbled more or less with orm frameworks is there anything else i need to take note of simple academic samples for me to refer to or resources i can read,['php'] +63697,unsupportedoperationexception on collection while studying the collection api we find that some methods add remove may throw a javalangunsupportedoperationexception if the current implementation of the collection does not support those functionalitiesis thereactually in the jdk a concrete collection that does not support those methods thanks a lot for your answers,['java'] +63733,is it possible to write vertically in a textview in android let us say you have a normal textview with stackoverflow written in it is it possible to rotate the textview by 90a to have the s at the bottom and the w at the top of the screenof course i could write my text as an image rotate it and use it that way but i am interested in the text right nowthanks,['android'] +63740,jquery hide table rows i am hiding a bunch of textboxes and it works fine the problem is the textboxes are in a table so i also need to hide the corresponding labelsthe structure is something like thistrtdlabeltdtdinputfiletdtrin fact its just easier if i hide the rows that have a fileinput can someone help please,['jquery'] +63757,ddms not showing threads from device i would like to check for memory leaks in my android app using the ddms feature in eclipse when i launch an emulated device the threads thisplay properly for the emulated device starting with 8600 and uphowever when i connect my droid to the pc the device shows up just fine in ddms the logcat is generated correctly and i can view the file structure however threads do not thisplay i get no client selected in the threads pane and there is no dropdown icon next to the device listingdo i need to change some particular setting in eclipse is this maybe a driver issue,['android'] +63764,one liner in ruby for thisplaying a prompt getting input and assigning to a variable often i find myself doing the followingprint input text input getsstripis there a graceful way to do this in one line something likeputs input text input getsstripthe problem with this is that it waits for the input before thisplaying the prompt any ideas,['ruby'] +63767,javascript input onchange not working why this doesna t workinputbuttonaddeventlisteneronchange jsfunction falsei change the inputbox and it doesna t call jsfunction,['javascript'] +63771,implementing gethashcode possible duplicatewhat is the best algorithm for an overridden systemobjectgethashcode what constitutes a good implementation of the gethashcode method i did some googling and found some goodlines msdn but it seems like the logic just manipulates two numbers stored as fields in the class is the actual logic this simple to implement this method,['c#'] +63775,is there any good universal php mysql http tunnel many windows mysql tools like navicat or ems have this thing you just put a php file on a shared hosting and can connect local running program to the remote mysql server on the web via the web service exposed by that php fileare there any good popular free solutions to expose full mysql as a web service using php,"['php', 'mysql']" +63779,whats the difference between process and procestartinfo in c whats the difference between process and procestartinfo ive used both to launch external programs but there has to be a reason there are two ways to do it here are two examplesprocess notepad new processnotepadstartinfofilename notepadexenotepadstartinfoarguments procestartcsnotepadstartandprocestartinfo startinfo new procestartinfostartinfofilename notepadexestartinfoarguments procestartcsprocestartstartinfothanks,['c#'] +63782,what is this fieldbyfield copy done by objectclone in effective java the author states thatif a class implements cloneable objects clone method returns a fieldbyfield copy of the object otherwise it throws clonenotsupportedexceptionwhat i would like to know is what he means with fieldbyfield copy does it mean that if the class has x bytes in memory it will just copy that piece of memory if yes then can i assume all value types of the original class will be copied to the new objectclass point implements cloneable private int x private int y override public point clone return pointsuperclone if what objectclone does is a field by field copy of the point class i would say that i wouldnt need to explicitly copy fields x and y being that the code shown above will be more than enough to make a clone of the point class that is the following bit of code is redundantoverridepublic point clone point newobj pointsuperclone newobjx thisx redundant newobjy thisy redundantam i right i know references of the cloned object will point automatically to where the original objects references pointed to i am just not sure what happens specifically with value types if anyone could state clearly what objectclones algorithm specification is in easy language that would be great,['java'] +63787,google maps place number in marker how can i thisplay a number in the marker on a google map i want to do server side clustering and i need to thisplay how many points the cluster represents,['javascript'] +63789,backreferences syntax in replacement strings why dollar sign in java and it seems in a few other languages backreferences in the pattern are preceded by a backslash eg 1 2 3 etc but in a replacement string they preceded by a dollar sign eg 1 2 3 and also 0heres a snippet to illustratesystemoutprintln leftrightreplaceall 21 wrong prints 21systemoutprintln leftrightreplaceall 21 correct prints rightleftsystemoutprintln you want million dollarreplaceallw dollar us 1 prints you want us millionsystemoutprintln you want million dollarreplaceallw dollar us 1 throws illegalargumentexception illegal group referencequestionsis the use of for backreferences in replacement strings unique to java if not what language started it what flavors use it and what do notwhy is this a good idea why not stick to the same pattern syntax wouldnt that lead to a more cohesive and an easier to learn languagewouldnt the syntax be more streamlined if statements 1 and 4 in the above were the correct ones instead of 2 and 3,['java'] +63795,c error astringa has not been declared in my header file i am getting the error astringa has not been declarederror but at the top of the file i have include string so how can i be getting this error,['c++'] +63813,closure and nested lambdas in c0x using c0x how do i capture a variable when i have a lambda within a lambda for examplestdvectorint c1int v 10 i want to capture this variablestdfor each c1begin c1end vint num this is fine stdvectorint c2 stdfor each c2begin c2end vint num error on this line how do i recapture v do something,['c++'] +63815,prettyprinting of numpyarray i am curious whether there is any way to print formatted numpyarrays eg in the way similar to thisx 123456print 3f xif i want to print the numpyarray of floats it prints several decimals often in scientific format which is rather hard to read even for lowdimensional arrays however numpyarray apparently has to be printed as a string ie with s is there any solution for this purpose,['python'] +63823,getting default value for java primitive types i have a java primitive type at handclass c intclass or longclass or booleanclassi would like to get a default value for this class specifically the value is assigned to fields of this type if they are not initialized eg 0 for a number false for a booleanis there a generic way to do this i triedcnewinstancebut i am getting an instantiationexception and not a default instance,['java'] +63835,where can i get a list of abbreviations for timezonewithabbreviation i would like to do some timezone calculation using the following apinstimezone some time zone nstimezone timezonewithabbreviationnamehowever i am not sure where to find the supported list of abbreviation names for example what is the name for the timezone of siena italy,['iphone'] +63840,passing arguments by value or by reference in objective c i am kind of new with objective c and i am trying to pass an argument by reference but is behaving like it were a value do you know why this does not workthis is the function void checkredcolortextuilabel labeltochange nscomparisonresult startlaterthanend startdate compareenddate if startlaterthanend nsordereddescending labeltochangetextcolor uicolor redcolor else labeltochangetextcolor uicolor blackcolor and this the calluilabel starthourlabel this is properly initialized in other part of the codeself checkredcolortextstarthourlabelthanks for your help,['objective-c'] +63851,problems with json serialize dictionary whenever i try to serialize the dictionary i get the exceptionsystemargumentexception type systemcollectionsgenericdictionary2foodictionaryserializationtesttestenum foo version10 cultureneutral publickeytokennullsystemint32 mscorlib version20 cultureneutral publickeytokenb77a5c561934e089is not supported for serializationdeserialization of a dictionarykeys must be strings or objectmy testcase ispublic class dictionaryserializationtest public enum testenum a b c tried with numbers too public enum testenum a 1 b 2 c 3 public void serializationtest dictionarytestenum int32 data new dictionarytestenum int32 dataaddtestenuma 1 dataaddtestenumb 2 dataaddtestenumc 3 javascriptserializer serializer new javascriptserializer string result serializerserializedata throws public void serializationtoobjecttest dictionaryobject int32 data new dictionaryobject int32 dataaddenumtoobjecttypeoftestenum testenuma 1 dataaddenumtoobjecttypeoftestenum testenumb 2 dataaddenumtoobjecttypeoftestenum testenumc 3 javascriptserializer serializer new javascriptserializer string result serializerserializedata throws public void serializationstringtest dictionarystring int32 data new dictionarystring int32 dataaddtestenumatostring 1 dataaddtestenumbtostring 2 dataaddtestenumctostring 3 javascriptserializer serializer new javascriptserializer string result serializerserializedata succeeds of course i could use tostring whenever i enter something into the dictionary but since it is used quite often in performance relevant methods i would prefer using the enummy only solution is using tostring and converting before entering the performance critical regions but that is clumsy and i would have to change my code structure just to be able to serialize the datadoes anyone have an idea how i could serialize the dictionary as enum int32i use the systemwebscriptserializationjavascriptserializer for serializationupdatei switched to dictionarystring int32 now and it works but i hope someone shows a solution as i do not really like using strings in place of a type safe enum,['c#'] +63852,how to combine widget webapp framework with seofriendly css and js files i am writing a webapp using zend framework and a homebrew widget system every widget has a controller and can choose to render one of many views if it chooses this really helps us modularize and reconfigure and reuse the widgets anywhere on the site the problem is that the views of each widget contain their own js and css code which leads to very messy html code when the whole page is put together you get pockets of style and script tags everywhere this is bad for a lot of different reasons as i am sure you know but it has a profound effect on our seo as well several solutions that i have been able to come up with separate the css and js of every view of every widget into its own file this has serious drawbacks for load times many more resources have to be loaded separately and it makes coding very difficult as now you have to have 34 files open just to edit a widget combine the all the widget css into a single file same with js would also lead to a massive load when someone enters the site mixes up the css and the js for all widgets so it is harder to keep track of them and other problems that i am sure you can think of create a system that uses method 1 separate css and js for every widget when delivering the page stitches all css and js together this obviously needs more processing time and of course the creation of such a system etc my question is what you guys think of these solutions or if there are preexisting solutions that you know of or any tech that might help solve this problem i really appreciate all of your thoughts and comments thanks guys ali,"['javascript', 'css']" +63861,jquery select iframe children i am using the editarea library and jquery to do what i needsess2b8243f679e0d472397bfa959e1d3841so in my html there is an iframe tag that editarea uses what i need is to access something like so with jqueryiframe textareakeydownfunction e number 17 any number really ifewhich number do something alertdone i tried the above but it looks like it is not detecting that key but it works if selector was documenttherefore the rest of the function works it is just it is not picking up the iframes textarea keydownany ideas thanks,"['javascript', 'jquery']" +63863,how to launch the google play intent in give feedback mode on android i have just written a game for the google play and would like to remind my customers to leave feeback on the market for the application especially the demo version is there any way to launch the market intent in a mode that will take the user to the feedback comments section of the pagei already use this approach for linking my demo to the paid application intent gotomarket nullgotomarket new intent intentaction view uriparsemarketdetailsidcompaulmaidmentgamesflagsoftheworldstartactivitygotomarketis there a best practiceadditionally is there any way to track referalls from my demo application so that i can try to calculate some kind of a conversion rate that is how effective the demo application is at generating sales,['android'] +63869,printing to stdout and log file while removing ansi color codes i have the following functions for colorizing my screen messagesdef errorstring return 0311m string 0330mdef standoutstring return 0341m string 0330mi use them as followsprint errorthere was a problem with the programprint this is normal standoutand this stands outi want to log the output to a file in addition to stdout without the ansi color codes hopefully without having to add a second logging line to each print statementthe reason is that if you simply python programpy out then the file out will have the ansi color codes which look terrible if you open in a plain text editorany advice,['python'] +63878,is web development moving too fast i find myself constantly learning new things in web development and there is always soo much to learn in general currently i work with php and have tried to keep up with ruby on railsror but it is moving so fast i am not sure i can keep up with the latest changesdoes anyone else have trouble keeping up with so much innovation in web development or is it just me and how do you guys cope with the never ending learning process especially with rails just looking for tips tricks and personal experiences reallythanks in advance,"['php', 'ruby-on-rails']" +63890,blank space on google home page 2 questions i was doing nothing productive and tried selecting the google home page a left click drag and select whole page on googlecomi see that beside the search box on the left side there is an empty space nbsp i looked up the source code and there indeed was a td width25nbsptdstupid as it may sound but i was still curious to know why the blank space is out thereor is it just a simple typo also any idea what windowlollol does curious yet again google search didnt get me any result and i thought i would turn to stackoverflow to enlighten methanksivar,['html'] +63937,debugging php mail andor phpmailer i am quite stuck with a problem sending mail from a php scriptsome datashared hosting no ssh access only hosting provider panelphp version 525last year i built a site which had no problems sending mail with the same hostinglet us say the domain is adomaincoma and my private address is aa for anonimitys sake in the following codeheres the codephperror reportinge all ini setthisplay errors 1to subject hibody test 1ntest 2ntest 3headers from rn errorsto rn xmailer php phpversionif mailto subject body headers echomessage successfully sent else echomessage sending failedrequireclassphpmailerphpmessage hello worldmail new phpmailermailcharset utf8mailaddaddress agosmailsetfrommy sitemailsubject test messagemailbody messagemailsendand here is what i getmessage sending failed could not instantiate mail functionwhich is baffling to say the least is there anything i can do to get at least some more meaningful errors why is code from the class showing up in my file,['php'] +63944,set theory and net recently i came across a situation where set theory and set math fit what i was doing to the letter granted there was an easier way to accomplish what i needed ie linq but i did not think of that at the time however i did not know of any generic set libraries granted ienumerables provide some set operations union etc but nothing like intersection or set comparison can anyone point out something that fits here something that implements set math using a generic type,['.net'] +63948,how to replace all occurrences of a character in string what is the effective way to replace all occurrences of a character with another character in stdstring,['c++'] +63969,deleting locked files folders i am writing an application that updates some drivers however the drivers are in use and cannot be deleted unless i restart my computerso how can i write an application to delete these locked drivers without restarting the pc if restarting must occur then how can i relaunch my application automatically when the computer restarts and delete those files,['c#'] +63974,receiving error domainkcferrordomaincfnetwork code2 when attempting to read from readstream i am attempting to synchronously read from a cfreadstream objected created by cfstreamcreatepairwithsockettohost the stream opened fine but when i attempt to invoke cfreadstreamread on it in a loop cfreadstreamread returns 1 and the resulting error is error domainkcferrordomaincfnetwork code2 the operation couldnat be completed kcferrordomaincfnetwork error 2 userinfo0x14a920 kcfgetaddrinfofailurekey8i am also receiving this same exact error when using this readstream asynchronously the first callback i receive is this error,['iphone'] +63979,how to determine jet database engine type programmatically i have a program which needs to upgrade any access jet database it opens to jet version4x if it is not already that version this enables use of sql92 syntax featuresupgrading is relatively easy a call to the jrojetengine objects compactdatabase method as described here should do the trick but before i do this i need to determine whether an upgrade is required how do i determine the jet oledbengine type of an existing database can this be determined from an open oledbconnectionnotei am talking about database versions not jet library versions c or net solution greatly appreciatedthis is an application which uses the jet engine not an access application,"['c#', '.net']" +63984,implementing sub fields in a propertygrid alright so my terminology when it comes to c is not great so i will attempt to explain this with a small example if you create a class which you are using within a propertygrid and you have the following valuesclass test public point example get set this will produce a propertygrid which has an expandable object example which has fields x and y in order to create a pointi am attempting to create an object name which has fields firstname and lastname so i haveclass test public name example get set public struct name public string firstname get set public string lastname get set this however is not working as intendedi think i need to override some methods in order to get this working however since i do not really have the terminology down for propertygrids it is difficult for me to find a solutionany help would be great,['c#'] +63989,creating a new log file each day as the title implies how can i create a new log file each day in c now the program may not necessarily run all day and night but only get invoked during business hours so i need to do two thingshow can i create a new log file each day the log file will be have the name in a format like mmddytxthow can i create it just after midnight in case it is running into all hours of the night,"['c#', 'asp.net']" +64007,iphone safari web app opens links in new window i have problem with web after adding icon to home screen if the web is launched from home screen all links will open in new window in safari and lose full screen functionality how can i prevent it i could not find any help only the same unanswered question,['iphone'] +64011,suggestions on syntax to express mathematical formula concisely i am developing functional domain specific embedded language within c to translate formulas into working code as concisely and accurately as possiblei posted a prototype in the comments it is about two hundred lines longright now my language looks something like this well actually is going to look like implies two nested loops j0n i0jrangei j ntij tij tjieij implies summation over above expressionsumrangei j ntij tjieiji am looking for possible syntax improvementsextensions or just different ideas about expressing mathematical formulas as clearly and precisely as possible in any language not just ccan you give me some syntax examples relating to my question which can be accomplished in your language of choice which consider useful in particular if you have some ideas about how to translate the above code segments i would be happy to hear them thank youjust to clarify and give an actual formula my shortterm goal is to express the followingexpression concisely where values in are already computed as 4dimensional arrays,['c++'] +64013,split nsdata objects into other nsdata objects with a given size i am having an nsdata object of approximately 10kb big now i want to transfer this via bluetooth this would be better if i have let us say 10 objects of 100kb it comes to mind that i should use the subdatawithrange method of nsdatai have not really worked with nsrange well i know how it works but then to read from a given location with the length to end of file i have no idea how to do thatsome code on how to split this into multiple 100kb nsdata objects would really help me out here it probably involves the length method to see how many objects should be madethank you in advance,['iphone'] +64035,proper way to hide dynamic elements with jquery i have a div element which my code will fill with a dynamic amount of links using jquery i want to hide all the links except the first one this is what i came up with and it works i was just wondering if this is the best way to do itpanelcontainereachfunctionn thischildrenhide panelcontainer afirstshow,['jquery'] +64045,php and barcode scanners if i have a website running php and apache what do i need to be able to attach a scanner to it how do i get the scanner to fill in a value on one of the webforms on my page,['php'] +64055,why does ruby 192 remove from load path and whats the alternative the latest changesets to ruby 192 no longer make the current directory part of your load path i have a nontrivial number of rakefiles that assume that is part of the load path so this broke them they reported no such file to load for all require statements that based off the project path was there a particular justification for doing thisas for a fix adding everywhere works but seems incredibly hacky and i do not want to do that whats the preferred way to make my rakefiles 192 compatible,['ruby'] +64058,r equivalent of select thistinct on two or more fieldsvariables say i have a dataframe df with two or more columns is there an easy way to use unique or other r function to create a subset of unique combinations of two or more columnsi know i can use sqldf and write an easy select thistinct var1 var2 varn query but i am looking for an r way of doing thisit occurred to me to try ftable coerced to a dataframe and use the field names but i also get the cross tabulations of combinations that do not exist in the datasetuniques asdataframeftabledfvar1 dfvar2,['sql'] +64062,how do i give php write access to a directory i am trying to use php to create a file but it is not working i am assuming this is because it does not have write access it is always been the problem before i tried to test if this was the problem by making the folder chmod 07 but that just ended up making every script in that directory return a 500 error message until i changed it backhow do i give php write access to my file system so it can a create a fileedit it is hosted on hostgator shared hosting using apacheedit 2 someone asked for the codethe code is a gd image script i know the rest of it works as previously i was creating the image every ime it was called now i am trying to create them when new text is added and save them to a folder the write line i have isimagejpegnullfile85i also created a test file to check if it was just a broken script mainly copied from tizag i do not know ifhow to post the code here properly here is the contents of the php script minus php tagsit returns 13131 separate lines so it looks as if it thinks it wrote something but the testfiletxt is blank i uploaded a blank one or nonexistent if i delete itedit 3 the server runs centos,['php'] +64068,the correct way to define an exception in python without pylint complaining i am trying to define my own very simple exception class in python 26 but no matter how i do it i get some warningfirst the simplest wayclass myexceptionexception passthis works but prints out a warning at runtime deprecationwarning baseexceptionmessage has been deprecated as of python 26 ok so that is not the way i then triedclass myexceptionexception def init self message selfmessage messagethis also works but pylint reports a warning w0231 myexception init init method from base class exception is not called so i tried calling itclass myexceptionexception def init self message superexception self init message selfmessage messagethis works too but now pylint reports an error e1003 myexception init bad first argument exception given to super classhow the hell do i do such a simple thing without any warnings,['python'] +64073,getting current culture day names in net is it possible to get the currentcultures weekdays from datetimeformatinfo but returning monday as first day of the week instead of sunday and if the current culture is not english ie the iso code is not en then leave it as defaultby default cultureinfocurrentculturedatetimeformatdaynames returns0 sunday1 monday2 tuesday3 wednesday4 thursday5 friday6 saturday but i need0 monday1 tuesday2 wednesday3 thursday4 friday5 saturday 6 sunday,"['c#', '.net']" +64079,how to make jtable column contain checkboxes preface i am horrible with java and worse with java ui componentsi have found several different tutorials on how to add buttons to tables however i am struggling with adding checkboxes i need to have a column that draws a text box ticked on default cell renderer i think handles that then on click of tickbox unticks the box redraws said box and fires off an event somewhere i can trackcurrently i have a custom cellrendererpublic class graphbuttoncellrenderer extends jcheckbox implements tablecellrenderer public graphbuttoncellrenderer public component gettablecellrenderercomponentjtable table object value boolean isselected boolean hasfocus int row int column ifisselected setselectedtrue else setselectedfalse setmarginnew insets0 16 0 0 seticontextgap0 setbackgroundnew color2552552550 return thiswhich currently handles drawing the tick box but only ticks and unticks the box if that row is selected but i do not know how to handle the events really what i am asking is possibly a link to a good tutorial on how to add checkboxes cleanly to a jtableany assist is greatly appreciated,['java'] +64081,speed up math code in c by writing a c dll i have a very large nested for loop in which some multiplications and additions are performed on floating point numbers for int i 0 i length1 i double aa 0 forint h 0 h 10 h aa omegaioutsidegeneratedaddressh double alphaold alpha alpha mathsqrtalpha alpha aa aa s aa alpha c alphaold alpha forint j 0 j i j double oldu uj uj c oldu s omegaij omegaij c omegaij s oldu this loop is taking up the majority of my processing time and is a bottleneck would i be likely to see any speed improvements if i rewrite this loop in c and interface to it from cedit i updated the code to show how s and c are generated also the inner loop actually goes from 0 to i though it probably does not make much difference to the questionedit2 i implemented the algorithm in vc and linked it with c through a dll and saw a 28 speed boost over c when all optimisations are enabled the argument to enable sse2 works particularly well compiling with mingw and gcc44 only gave a 15 speed boost just tried the intel compiler and saw a 49 speed boost for this code,"['c#', '.net', 'c']" +64087,beginner sql section avoiding repeated expression i am entirely new at sql but let us say that on the stackexchange data explorer i just want to list the top 15 users by reputation and i wrote something like thisselect top 15 thisplayname id reputation reputation10 as repinkfrom userswhere repink 10order by reputation desccurrently this gives an error invalid column name repink which makes sense i think because repink is not a column in users i can easily fix this by saying where reputation10 10 essentially repeating the formulaso the questions arecan i actually use the repink column in the where clausedo i perhaps need to create a virtual tableview with this column and then do a selectwhere query on itcan i name an expression eg reputation10 so i only have to repeat the names in a few places instead of the formulawhat do you call this a substitution macro a function a stored procedureis there an sql quicksheet glossary of terms language specification anything i can use to quickly pick up the syntax and semantics of the languagei understand that there are different flavors,['sql'] +64089,is there a c library that will perform the excel norminv function i am running some monte carlo simulations and making extensive use of the excel function norminv using office interrop this functions takes three arguments probability average standard deviation and returns the inverse of the cumulative thistribution i would like to move my code into a web app but that will require installing excel on the server does anybody know of a c statistics library that has an equivalent function to norminv,['c#'] +64090,why did this work php dot notation i was writing some php code after a long sint doing ruby and i accidently wrote thisrootip101604798 test cat runphpphpclass mytest public function run var dumpthistest object new mytestobjectrunrootip101604798 test php runphpstring8 thistestrootip101604798 testnow thistest should have been thistest but the compiler was actually happy to let this rundoes anyone know how thistest got converted into a string thistestcompiled and run on php 532 amazon instance amie32273a6 centos 54daniel,['php'] +64097,documentation on writing buildout recipes i am trying to find tutorials on how to write buildout recipes i have not found any except the one on buildout site but it is very rudimentary is there a good tutorial for writing buildout recipes,['python'] +64115,android get the screen resolution pixels as integer values this is a really simple question on which i have found no answer how can i quickly access the screen resolution width height as integer valuesi have tried this one but it always shows zero on my emulatorthisplaymetrics dm new thisplaymetricsint width dmwidthpixels 2in my case i want to dynamically create a table with tablerows each containing two cols this cols all shall fill half of the screen in widthcan someone give me a hint,['android'] +64118,check if date is within time range using joda or standart java api i have first time as string 120 and another 190 how to check time portion of the day is within these time values,['java'] +64128,android using dexclassloader to load apk file i have hit a bit of a wall any help would be appreciated i have an app that i want to use dexclassloader to load another apk filehere is my codedexclassloader dloader new dexclassloadersdcarddownloadtestapksdcarddownloadnullclassloadergetsystemclassloadergetparentclass calledclass dloaderloadclasscomtestclassnameintent itnew intentthis calledclassitsetclassnamecomtest comtestclassnamestartactivityitnow i had already installed testapk so when i ran the above code itworked fine and launched the application however i want to be able torun this without testapk being installed already as that woulddefeat the entire point of the application so i uninstalled it andwhen i ran the my app again i get this errorandroidcontentactivitynotfoundexception unable to find explicitactivity class comtestcomtestclassname have you declared thisactivity in your androidmanifestxmlso i am a bit stumped here this activity is declared in the manifestof the apk i am trying to run i cannot declare it in my applicationsmanifest any ideasthankscraig,['android'] +64133,using c and vbnet in one solution i am busy on a small project to convert an access2003 db to net i am trying to integrate my functionality in an existing project that is being used for administration of some kind the code in this project is vbnet i started by setting up my data access layer which seems to work fine i can make new web pages that access the data i need however when i start to use class files to set up my business logic layer i cannot build my project when using c instead of vb i thislike vb and like to program in c as i know the syntax a lot better etc is it possible to program using c knowing that vbnet was the language chosen to build the entire project onif not what will be the smartest way to integrate my module into the project using my favorite programming language make a project and reference to the dlledit so the next step in my question would be if i set up a new project within the existing solution can i make that new project contain my business logic layer data access layer and reference from my existing one,['c#'] +64137,visual studio reset user settings when debugging in a c winformsapp i have several user settings storedis there an easy way to clear those settings each time i start debugging the project from visual studio 2008otherwise it always starts up with the settings from the last debugsession,['c#'] +64148,what is the difference between c java and javascript exception handling they are very different kind of languages and the way they handle exceptions might be rather different how is exception handling implemented and what are the implementation difference within these languagesi am asking this question also because i noticed that c exception handling seems to be very slow compared to the javascript version,"['java', 'javascript', 'c++']" +64161,show or hide elements in pdf via javascript in pdf files it is quite easy to interact with form fields via the javascript apiis it possible to do this specifically showinghiding to arbitrary elements on a page say not just form fields but text graphical elements embedded images is there an api to interact with thoseif yes how do i identify an object,['javascript'] +64162,performance of c method polymorphism with generics i noticed in c unlike c you can combine virtual and generic methods for exampleusing systemdiagnosticsclass base public virtual void concrete debugwritelinebase concrete public virtual void generict debugwritelinebase genericclass derived base public override void concrete debugwritelinederived concrete public override void generict debugwritelinederived genericclass app static void main base x new derived xconcrete xgenericperformancecounter given that any number of versions of generict could be instantiated it does not look like the standard vtbl approach could be used to resolve method calls and in fact it is not heres the generated code xconcretemov ecxdword ptr ebp8 mov eaxdword ptr ecx call dword ptr eax38h xgenericperformancecounterpush 989a38h mov ecxdword ptr ebp8 mov edx989914h call 76a874f1 mov dword ptr ebp4eax mov ecxdword ptr ebp8 call dword ptr ebp4 the extra code appears to be looking up a dynamic vtbl according to the generic parameters and then calling into it has anyone written about the specifics of this implementation how well does it perform compared to the nongeneric case,['c#'] +64166,how does java serialization deserialize final fields when no default constructor specified i have an class defining an immutable value type that i now need to serialize the immutability comes from the final fields which are set in the constructor i have tried serializing and it works surprisingly but i have no idea howheres an example of the classpublic class myvaluetype implements serializable private final int value private transient int derivedvalue public myvaluetypeint value thisvalue value thisderivedvalue derivedvaluevalue getters etcgiven that the class does not have a no arg constructor how can it be instantiated and the final field set an aside i noticed this class particularly because idea was not generating a no serialversionuid inspection warning for this class yet successfully generated warnings for other classes that i have just made serializable,['java'] +64175,aspnet intellisense does not work in attributes it seems that intellisense just does not work within attributes in an aspnet page i really like strong typing because i like intellisense and so i generally make sure to bind to a strongly typed object in aspnetrepeater idrep runatserver itemtemplate div idmydiv class typedobjectclass runatserver typedobjectname div itemtemplaterepeaterintellisense just works within the body of the div but no matter what i do it will not work to set that class attribute this is very annoying since attributes are pretty fundamental in html and many of the built in controls use them heavilyi cannot find anything about this but i cannot believe this is not a pretty fundamental need is there any way to get this to work,['asp.net'] +64243,cakephp data model with multiple foreign keys to same table based on cakephps data model conventions to setup a foreign key i would specify a column with the source table followed by an idi have an accounts and an account messages table now the complication arises when i need 2 foreign key references to the same accounts table specifically i need to keep track of the account id in the to field and the account id in the from field on a messagefrom the docsbackery i would specify account id however what would i specify for the second referenceis this possible and still benefit from cakephps magic codeany insight would be appreciatedry,['php'] +64258,external usb devices to android phones i would like to use android phones as a way to do some processing and visualization of a sensor that would be attached to the usb port on the phone the sensor would plug into the micromini usb and then i would need to read the incoming data from the usb serial portis this possible i have heard of people using android to steer robots and other applications but i have never seen android being used as a host for a usb sensor i cannot seem to find any official documentation on the subject either but it seems like it would be a very useful tool any thoughts links or information on this matter thanks,['android'] +64263,how to get only tables not views using show tables show tables gives you tablesviews how do i retrieve only tables,['mysql'] +64277,android webview seems to ignore viewport information on web pages i have a website that is using the viewport meta tag to tell mobile browsers how to thisplay content viewing the page in the android browser looks correct and iphone etcwhen i load the page into a webview component in an android application the webview ignores the viewport tag and renders the page at full resolution which is zoomedin in this case,['android'] +64282,using bundle files 1 with py2exe is not working after some big frustration i did it i converted my django app to an exe one to run as a single standalone app on windows using cherrypy as a wsgi serverbut when i try to to set py2exes option bundle files to 1 ie bundle the python interpreter python25dll inside the generated exe the generated exe crashes with a message talking about kernel32dllbut when i use bundle file 2 the generated exe is runing like a charm but must of course have python25dll as a separate file beside itanyone experienced a similar behavior can you please tell me what i am missingthank you,['python'] +64287,eclipse add unimplemented methods method ordering eclipse has a feature add unimplemented methods that adds the unimplemented methods for a class such as when implementing an interfacewhen eclipse adds the methods it adds them in alphabetical order is there a way to configure eclipse to add them in the order that they appear in the interface or abstract class,['java'] +64318,best practices regarding equals to overload or not to overload consider the following snippetimport javautilpublic class equalsoverload public static void mainstring args class thing final int x thingint x thisx x public int hashcode return x public boolean equalsthing other return thisx otherx listthing mythings arraysaslistnew thing42 systemoutprintlnmythingscontainsnew thing42 prints false note that contains returns false we seems to have lost our thingsthe bug of course is the fact that weve accidentally overloaded instead of overridden objectequalsobject if we had written class thing as follows instead then contains returns true as expected class thing final int x thingint x thisx x public int hashcode return x override public boolean equalsobject o return o instanceof thing thisx thing ox effective java 2nd edition item 36 consistently use the override annotation uses essentially the same argument to recommend that override should be used consistently this advice is good of course for if we had tried to declare override equalsthing other in the first snippet our friendly little compiler would immediately point out our silly little mistake since it is an overload not an overridewhat the book does not specifically cover however is whether overloading equals is a good idea to begin with essentially there are 3 situationsoverload only no override almost certainly wrongthis is essentially the first snippet aboveoverride only no overload one way to fixthis is essentially the second snippet aboveoverload and override combo another way to fixthe 3rd situation is illustrated by the following snippet class thing final int x thingint x thisx x public int hashcode return x public boolean equalsthing other return thisx otherx override public boolean equalsobject o return o instanceof thing thisequalsthing o here even though we now have 2 equals method there is still one equality logic and it is located in the overload the override simply delegates to the overloadso the questions arewhat are the pros and cons of override only vs overload override combois there a justification for overloading equals or is this almost certainly a bad practice,['java'] +64329,animating a calayers mask size change i have a uiview subclass which uses a cashapelayer mask on its calayer the mask uses a thistinct shape with three rounded corners and a cut out rectangle in the remaining cornerwhen i resize my uiview using a standard animation block the uiview itself and its calayer resize just fine the mask however is applied instantly which leads to some drawing issuesi have tried animating the masks resizing using a cabasicanimation but did not have any luck getting the resizing animatedcan i somehow achieve an animated resizing effect on the mask do i need to get rid of the mask or will i have to change something about the way i currently draw the mask using voiddrawincontextcgcontextrefctxcheersalex,"['iphone', 'objective-c']" +64368,custom buttons in android how to get borderedgeframe when i read the background from xml using android shapes in xml i have defined a gradient which i use as the background for a buttonthis all works nice but there is no edge surrounding the button i would like it to look similar to the normal android button but i need more flexibility to control the color and lookthe shape is defined as followsxml version10 encodingutf8shape xmlnsandroid androidshaperectangle gradient androidstartcolorf androidendcolor00ff00 androidangle270 corners androidradius3dp stroke androidwidth5px color0 shapei would expect the border to be set in the xml why does not stroke fix it stroke does not seem to do anythingi checked the android developer spec but could not find the answer therei have also looked through all the properties of the android button but as expected there is no such parameter probably since it is built into the normal android button btw i checked imagebutton properties toocan someone please helpi know there is the alternative to make an image with proper edges and use an imagebutton but there really should be a way to fix this programmaticallythanksanna,['android'] +64373,read filecontents into a string in c possible duplicatewhat is the best way to slurp a file into a stdstring in c in scripting languages like perl it is possible to read a file into a variable in one shot openfilehandlefile contentfilehandlewhat would be the most efficient way to do this in c,['c++'] +64391,hibernate count collection size without initializing is there a way i can count the size of an associated collection without initializingegselect countpchildren from parent pthere is a good reason why i cant do this any other way as my where clause is more complicated and my from clause is a polymorphic querythanks,['java'] +64411,download pdf programatically how can i download a pdf and store to thisk using vbnet or cthe url of the pdf has some rediection going on before the final pdf is reachedi tried the below but the pdf seems corrupted when i attempt to open locallydim pdffile as filestream fileopenwritesavetodim pdfstream as memorystream getfilestreampdfurlpdfstreamwritetopdffilepdfstreamflushpdfstreamclosepdffileflushpdffileclosemany thanksks,['c#'] +64428,unit test sessions window closes when debugging when i select an nunit test in the unit test sessions window and click debug the window thisappears my breakpoints are hit but if i hit f5 the unit test sessions window does not return until the test returns a result or i stop the debugging session this is preventing me from viewing any console output during tests any ideas,"['c#', 'asp.net']" +64431,php reading mysql bit field returning weird character i am using mysql fetch assocquery one of the bit field returns out to be which is supposedly to be truethe problem is that i also need to output this to xml and it is an illegal xml characterthe charset for the db table is utf8 why does this happen,"['php', 'mysql']" +64440,log4j support in android i am attempting to shoehorn an existing sdk onto an android device and one of the dependencies of said sdk is apache log4j i am able to load my test program onto the android emulator but when the log4j object propertysetter is called the program fails with a verification exception is there a way to ameliorate this issue,['android'] +64441,how do i abort a socketrecv from another thread in python i have a main thread that waits for connection it spawns client threads that will echo the response from the client telnet in this case but say that i want to close down all sockets and all threads after some time like after 1 connection how would i do if i do clientsocketclose from the main thread it would not stop doing the recv it will only stop if i first send something through telnet then it will fail doing further sends and recvsmy code look like this echo server programimport socketfrom threading import threadimport timeclass clientthreadthread def init self clientsocket thread init self selfclientsocket clientsocket def runself while 1 try it will hang here even if i do close on the socket data selfclientsocketrecv1024 print got data data selfclientsocketsenddata except break selfclientsocketclosehost port 60serversocket socketsocketsocketaf inet socketsock streamserversocketsetsockoptsocketsol socket socketso reuseaddr 1serversocketbindhost portserversocketlisten1clientsocket addr serversocketacceptprint got a new connection from addrclientthread clientthreadclientsocketclientthreadstarttimesleep1 this would not make the recv in the clientthread to stop immediately nor will it generate an exceptionclientsocketclose,['python'] +64446,openmp num threads1 executes faster than no openmp iave run my code in a variety of circumstances which has resulted in what i believe to be odd behavior my testing was on a dual core intel xeon processor with htno openmp pragma statement total runtime 507 secondswith openmp pragma statement specifying 1 core total runtime 117 secondswith openmp pragma statement specifying 2 core total runtime 150 secondswith openmp pragma statement specifying 3 core total runtime 157 secondswith openmp pragma statement specifying 4 core total runtime 144 secondsi guess i canat figure out why commenting out my openmp line makes the program slow down so much between 1 thread without openmp and 1 thread with openmpall i am changing is betweenpragma omp parallel for sharedsegs privatei j p hough num threads1 scheduleguidedandpragma omp parallel for sharedsegs privatei j p hough num threads1234 scheduleguidedanyways if anyone has any idea why this may be happening please let me knowthanks for any helpbrettedit i will address some of the comments herei am using num threads1 num threads2 etcwith further investigation it turns out that my results are inconsistent based upon whether or not the scheduleguided line is included in the codewhen i am utilizing the scheduleguided line i generate the fastest solution regardless of the number of threads when i am using the default scheduler my results are significantly slower and different valueswith scheduleguided improvement is not gained with increased threadswithout the scheduleguided i gain improvement with addition of threadsi guess i have not found a good enough description of what scheduleguided does for me i do understand that it tries to split up the loop so that the most time intensive iterations happen first which should have an effect of the least amount of time that one thread waits for the others to complete their iterationsit appears that for my 900 iteration loop when i use scheduleguided i am only processing 200 iterations where as without the scheduleguided i am processing all 900 iterations any thoughts,"['c++', 'c']" +64448,is deep java knowledge needed for android i am c developer interested in android as i understand the only possibility to develop applications for android is java there is ndk also but as i can see it is just something like jni for java is it mandatory to learn java or to have deep knowledge in java then try android sdk or it would be possible to learn java while developing for android thank you,"['java', 'android']" +64460,reset an aspnet validation control via javascript how do i reset an aspnet validation control via javascript the current code sample clears the error message text but does not reset the validation control for the next form submissionvar cv documentgetelementbyid myvalidationcontorlclientid cvinnerhtml updatehere is the full code sample of the form i can not seem to get the validation controls fire off on another form submissionfunction cleardata var cv documentgetelementbyid myvalidationcontorlclientid cvinnerhtml html form asptextbox idmytextcontrol runatserver aspcustomvalidator idmyvalidationcontorl runatserver input typebutton onclickjavascriptclearccdata return false runatserver formhtml,"['asp.net', 'javascript']" +64479,too many left outer joins in entity framework 4 i have a product entity which has 0 or 1 bestseller entities for some reason when i saydbproductsorderbyp pbestsellerratingtolistthe sql i get has an extra outer join below and if i add on a second 0 or 1 relation ship and order by both then i get 4 outer joins it seems like each such entity is producing 2 outer joins rather than one linq to sql behaves exactly as youd expect with no extra joinhas anyone else experienced this or know how to fix itselect extent1id as id extent1productname as productnamefrom dboproducts as extent1left outer join dbobestseller as extent2 on extent1id extent2idleft outer join dbobestseller as extent3 on extent2id extent3idorder by extent3rating asc,['c#'] +64491,python what is the hard recursion limit for linux mac and windows pythons sys module provides a function setrecursionlimit that lets you change pythons maximum recursion limit the docs saythe highest possible limit is platformdependentmy question is what is the highest possible limits for various platforms under cpython i would like to know the values for linux mac and windowsupdate can we please avoid youre doing it wrong answers i know that trying to do very deep recursion is usually a bad idea i have considered the pros and cons in my specific situation and decided that i want to do it,['python'] +64495,in djangopython how do i set the memcache to infinite time cachesetkey value 9but this is not infinite time,['python'] +64521,can my thread help the os decide when to context switch it out i am working on a threaded application on linux in c which attempts to be real time doing an action on a heartbeat or as close to it as possiblein practice i find the os is swapping out my thread and causing delays of up to a tenth of a second while it is switched out causing the heartbeat to be irregularis there a way my thread can hint to the os that now is a good time to context switch it out i could make this call right after doing a heartbeat and thus minimize the delay due to an ill timed context switch,['c++'] +64524,when is it ok to use javascript and when not is it good practice not to use much javascriptjquery should we avoid it as much as possible for good accessibilitywhen is it ok to use javascript and when is it not in web design and development in what scenarios and with what conditionsupdatei am asking regarding public websites,"['javascript', 'css']" +64531,test if an object is an enum i would like to know if theobject is an enum of any enum type foreach var item in enumgetvaluestheobjectgettype do something,['c#'] +64535,decode html entities in android i need to decode html entities eg from 246 to o and amp to urlencoderdecodestr does not do the job convert from notations textutils has a htmlencode but not a htmldecodeare there any function for decoding html entities,"['html', 'android']" +64539,dynamic comparison operators in php is it possible in any way to pass comparison operators as variables to a function i am looking at producing some convenience functions for example and i know this would not workfunction isandvar value operator ifissetvar var operator value return trueifisand1 1 echo workedthanks in advance,['php'] +64551,example of when the culture parameter of stringequals c actually makes a difference i donat fully understand the second parameter of stringequals and this is because i canat find any examples of when it would actually make a difference for example the example given here is the same regardless of the value of the second parameter aside from ignorecasei am just talking about the values stringcomparisoncurrentculture invariantculture or ordinali can understand the difference between these and their ignorecase equivalents,['c#'] +64553,how to get record created today by rails activerecord how should i write the conditional statement for when i want to get all the records which were created today,['ruby-on-rails'] +64559,table with 100 width with equal size columns a variable name first of all i am not quite good at web design i have to dynamically create a table with a variable number of columns determined at runtime can somebody tell me if it is possible to have a html table with equal size columns that are fully stretched any hints,"['html', 'css']" +64566,insert text at cursor in a content editable div i have a contenteditable div where i need to insert text at the caret positionthis can be easily done in ie by documentselectioncreaterangetext banana is there a similar way of implementing this in firefoxchromei know a solution exists here but it cannot be used in contenteditable div and looks clumsythank you,['javascript'] +64573,i get nan when i try to insert some html into a div element with jquery i am tring to thisplay a text box when a element of class numobj is clicked for some reason i get nannananannannananan where i expect to the see the result of the searchform variable in the code belowi know that nan stands for not a number what i do not understand is why is javascript expecting a number i cannot understand why it caresnumobjliveclickfunction var preid thisattrpreid var arraypos thisattrnumarraypos alertpreid arraypos var searchform table border0 cellspacing0 cellpadding4 idaddtag2 tr classnormaltd bgcolore valignbottom nowrapnowrapspan classnormalsmall input namepredicatename2 typetext classnormal idpredicatename2 size4 spantd td bgcolore valignbottom nowrapnowrapspan classnormalsmaltspantd td bgcolore valignbottom nowrapnowrapxtd td valignbottom bgcolorelttd td valignbottom bgcolorespan classnormalsmall input typetext nameobjectobject2 idobjectobject2 classnormal size4 spantd tr table numobjfilterpreidpreidfilternumarrayposarrayposhtmlsearchform the generated code that has the numobj class looks something like thistddiv classnumobj preid73 numarraypos5span classnormal5850spandivtd,"['javascript', 'jquery']" +64592,pocket sphinx on android what are the steps required to use pocketsphinx on androidi have found various hints around the web that it is possible but not real answers and hence i ask my question here,['android'] +64601,ironruby as a scripting language in net i want to use ironruby as a scripting language as lua for example in my net projectfor example i want to be able to subscribe from a ruby script to specific events fired in the host application and call ruby methods from iti am using this code for instantiating the ironruby enginedim engine rubycreateenginedim source enginecreatescriptsourcefromfileindexrbcompile execute itsourceexecutesupposing indexrb containssubscribebuttonclick handlerdef handler puts hello thereendhow do imake c method subscribe defined in host application visible from indexrbinvoke later handler method from the host application,"['c#', '.net', 'ruby']" +64603,java profiling tool for linux i want to run a java program on a linux server in profiling modeis there any profiling tool that can profile a java program on a linux server in command prompt,['java'] +64619,transactionscope prematurely completed i have a block of code that runs within a transactionscope and within this block of code i make several calls to the db selects updates creates and deletes the whole gamut when i execute my delete i execute it using an extension method of the sqlcommand that will automatically resubmit the query if it deadlocks as this query could potentially hit a deadlock i believe the problem occurs when a deadlock is hit and the function tries to resubmit the query this is the error i receive the transaction associated with the current connection has completed but has not been thisposed the transaction must be thisposed before the connection can be used to execute sql statementsthis is the simple code that executes the query all of the code below executes within the using of the transactionscopeusing sqlcommandconnection new sqlconnectionconnectionstringsapp sqlcommandconnectionopen sqlcommandexecutenonquerywithdeadlockhandlinghere is the extension method that resubmits the deadlocked querypublic static class sqlcommandextender private const int deadlock error 1205 private const int maximum deadlock retries 5 private const int sleep increment 100 public static void executenonquerywithdeadlockhandlingthis sqlcommand sqlcommand int count 0 sqlexception deadlockexception null do if count 0 threadsleepcount sleep increment deadlockexception executenonquerysqlcommand count while deadlockexception null count maximum deadlock retries if deadlockexception null throw deadlockexception private static sqlexception executenonquerysqlcommand sqlcommand try sqlcommandexecutenonquery catch sqlexception exception if exceptionnumber deadlock error return exception throw return null the error occurs on the linesqlcommandexecutenonquery,['c#'] +64622,how do i change sql server column names in tsql i have a table with 600 columns imported from a csv file with special chars in the column namesis there a way to change the column names to remove these special charsthe code can be in tsql,['sql'] +64625,reading text file from server on android i have a text file on my server i want to open the text file from my android app and then thisplay the text in a textview i cannot find any examples of how to do a basic connection to a server and feed the data into a stringany help you can provide would be appreciated,['android'] +64629,mockito arraylist problem i have a method that i am trying to unit test this method takes a parameter as an arraylist and does things with it the mock i am trying to define isarrayliststring mocked mockarraylistclasswhich gives a unchecked unchecked conversion warning arrayliststring mocked mockarrayliststringclassgives me an error anyone care to enlighten me as to what i am doing wrong,['java'] +64643,how do i include a webconfig custom section schema without having to update each dev machine i have added a new custom section to the webconfig of an application i have also created a corresponding schema file for the new section definitionhow do i include the schema reference in the webconfig so that any developer editing the section has intellisense enabled when dealing with my new custom config sectioni have seen solutions whereby i include the schema reference within the webconfig by having to update the ide installation directorypackagesschemasxml location this works but i want to ensure that any new developer checking out the code on a fresh development machine automatically has the intellisense enabled without having to also update their development machine,['asp.net'] +64659,conditional compilation and framework targets there are a few minor places where code for my project may be able to be drastically improved if the target framework were a newer version i would like to be able to better leverage conditional compilation in c to switch these as neededsomething likeif net40using fooxx foo40elif net35using fooxx foo35else net20using fooxx foo20endifdo any of these symbols come for free do i need to inject these symbols as part of the project configuration seems easy enough to do since i will know which framework is being targeted from msbuildpdefineconstantsnet40update my question is how are people handling this situation are you creating different configurations are you passing in the constants via the command line,['c#'] +64662,is there a way to make a console window flash in the task bar programatically basically i made console app that performs some task that takes a few minutes i would like to have it flash in the taskbar to let me know when it is done doing its thing,['c#'] +64667,finding the sql output of a parameterized query i am making a parameterized query using c against a sql server 2005 instance and i would like to take a look at the sql that is run against the database for debugging purposes is there somewhere i can look to see what the output sql of the parameterized command is either in the database logs or in the visual studio debugger,['c#'] +64668,what is a simple fuzzy string matching algorithm in python i am trying to find some sort of a good fuzzy string matching algorithm direct matching does not work for me a this is not too good because unless my strings are a 100 similar the match fails the levenshtein method does not work too well for strings as it works on a character level i was looking for something along the lines of word level matching egstring a the quick brown foxstring b the quick brown fox jumped over the lazy dogthese should match as all words in string a are in string bnow this is an oversimplified example but would anyone know a good fuzzy string matching algorithm that works on a word level,['python'] +64670,what is a practical usage of code contracts in net 40 in order to fully understand and take advantage of the new features and enhancements provided with the coming of the new net framework 40 i would like to get an example of realworld application of code contractsanyone has a good example of application of this featurei would like to get a code sample with a brief explanation to help me get up and running with it,['.net'] +64671,what is the best way to find the digit at and position in a decimal number backgroundi am working on a symmetric rounding class and i find that i am stuck with regards to how to best find the number at position x that i will be rounding i am sure there is an efficient mathematical way to find the single digit and return it without having to resort to string parsingproblemsuppose i have the following c psuedocodevar position 3var value 10243587m i want this no a that is 5protected static int findndigitdecimal value int position this snippet is what i am searching foralso it is worth noting that if my value is a whole number i will need to return a zero for the result of findndigitdoes anyone have any hints on how i should approach this problem is this something that is blaringly obvious that i am missing,['c#'] +64678,why do firefox and opera ignore maxwidth inside of thisplay tablecell the following code thisplays correctly in chrome or ie the image is 200px wide in firefox and opera the maxwidth style is ignored completely why does this happen and is there a good work around also which way is most standards compliantnoteone possible work around for this particular situation is to set maxwidth to 200px however this is a rather contrived example i am looking for a strategy for a variable width containerdoctype htmlhtmlhead style div thisplay tablecell padding 15px width 200px div img maxwidth 100 styleheadbody div img src b9c887b979jpg p lorem ipsum dolor sit amet consectetur adipiscing elit donec facilisis ante facilisis posuere ligula feugiat ut fusce hendrerit vehicula congue at ligula dolor lorem ipsum dolor sit amet consectetur adipiscing elit leo metus aliquam eget convallis eget molestie at massa p divbodyhtmlupdateas stated by mvchr below the w3org spec states that maxwidth does not apply to inline elements i have tried using div img maxwidth 100 thisplay block but it does not seem to correct the issueupdatei still have no solution for this issue however i am using the following javascript hack to fix my problems essentially it recreates the situation above and checks if the browser supports maxwidth within thisplay tablecell using a data uri prevents an extra http request the one below is a 3x3 bmpjquery function var img img stylemaxwidth100 src dataimagebmpbase64qk1kad4aoawa amabaaeawadedgaaxa4ap wawaka3d appendto div stylethisplaytablecellwidth1pxdiv appendto body supporttablecellmaxwidth imgwidth 1 imgparentremove,"['html', 'css']" +64697,whats a good equivalent to pythons subprocesscheck call that returns the contents of stdout i would like a good method that matches the interface of subprocesscheck call ie it throws calledprocesserror when it fails is synchronous c but instead of returning the return code of the command if it even does that returns the programs output either only stdout or a tuple of stdout stderrdoes somebody have a method that does this,['python'] +64699,how can i rate limit how fast a javascript function allows itself to be called i have a javascript function which actually ends up making a serverside call i want to limit the rate at which this function can be calledwhat is an easy way i can limit how fast my javascript function will get called by say 200500 milliseconds or so should i use a javascript timer control,['javascript'] +64700,comparing xmldocument for equality content wise if i want to compare the contents of a xmldocument is it just like thisxmldocument doc1 getdoc1xmldocument doc2 getdoc2ifdoc1 doc2i am not checking if they are both the same object reference but if the contents of the xml are the same,['c#'] +64703,advice on mocking system calls i have a class which calls getaddrinfo for dns look ups during testing i want to simulate various error conditions involving this system call whats the recommended method for mocking system calls like this i am using boosttest for my unit testing,['c++'] +64704,best ways to format linq queries before you ignore votetoclose this question i consider this a valid question to ask because code clarity is an important topic of thiscussion it is essential to writing maintainable code and i would greatly appreciate answers from those who have come across this beforei have recently run into this problem linq queries can get pretty nasty real quick because of the large amount of nestingbelow are some examples of the differences in formatting that i have come up with for the same relatively noncomplex queryno formattingvar allinventory systeminventorysourcesselectsrc new inventory srcvaluegetinventoryproductoriginalproductid true region srcvalueregion groupbyi iregion i iinventoryelevated formattingvar allinventory systeminventorysources selectsrc new inventory srcvaluegetinventoryproductoriginalproductid true region srcvalueregion groupby i iregion i iinventoryblock formattingvar allinventory systeminventorysources select src new inventory srcvaluegetinventoryproductoriginalproductid true region srcvalueregion groupby i iregion i iinventory list formatting var allinventory systeminventorysources selectsrc new inventory srcvaluegetinventoryproductoriginalproductid true region srcvalueregion groupbyi iregion i iinventoryi want to come up with a standard for linq formatting so that it maximizes readability understanding and looks clean and professional so far i cannot decide so i turn the question to the professionals here,['.net'] +64708,clustered index multipart vs singlepart index and effects of insertsdeletes this question is about what happens with the reorganizing of data in a clustered index when an insert is done i assume that it should be more expensive to do inserts on a table which has a clustered index than one that does not because reorganizing the data in a clustered index involves changing the physical layout of the data on the thisk i am not sure how to phrase my question except through an example i came across at workassume there is a table junk and there are two queries that are done on the table the first query searches by name and the second query searches by name and something as i am working on the database i thiscovered that the table has been created with two indexes one to support each query like sodrop table junk1create table junk1 name char5 something char5 whocares intcreate clustered index ix name on junk1 namecreate nonclustered index ix name something on junk1 name somethingnow when i looked at the two indexes it seems that ix name is redundant since ix name something can be used by any query that desires to search by name so i would eliminate ix name and make ix name something the clustered index insteaddrop table junk2create table junk2 name char5 something char5 whocares intcreate clustered index ix name something on junk2 name somethingsomeone suggested that the first indexing scheme should be kept since it would result in more efficient insertsdeletes assume that there is no need to worry about updates for name and something would that make sense i think the second indexing method would be better since it means one less index needs to be maintainedi would appreciate any insight into this specific example or directing me to more info on maintenance of clustered indexes,['sql'] +64717,jquery equivalent of getting the context of a canvas i have the following working codectx documentgetelementbyidcanvasgetcontext2dis there any way to rewrite it to use doing this failsctx canvasgetcontext2d,"['javascript', 'jquery', 'html']" +64721,get 235pm instead of 0235pm from python datetime i am still a bit slow with python so i have not got this figured out beyond whats obviously in the docs etc i have worked with django a bit where they have added some datetime formatting options via template tags but in regular python code how can i get the 12hour hour without a leading zero is there a straightforward way to do this i am looking at the 25 and 26 docs for strftime and there does not seem to be a formatting option there for this case should i be using something else feel free to include any other timeformatting tips that are not obvious from the docs,['python'] +64727,calling a native callback from managed net code when loading the managed code using com i am really confused by the multitude of misinformation about native managed interopi have a regular c exe which is not built using clr stuff it is neither managed c nor ccli and never will be this c exe is in charge there is no managed wrapper for iti would like to access some code i have in a c assembly from my c exe i can access the c assembly from my c code using com however when my c code detects an event i would like it to call back into my c code the c function pointer to call back into will be provided at runtime note that the c function pointer is to a function found in the exes execution environment it may use static members from there i do not want the managed code to try and load up some dll to call a function there is no dllhow do i pass this c function pointer to my c code through comnet and have my c code successfully call itthanks,"['c#', '.net']" +64741,how can i edit on my server files without restarting nodejs when i want to see the changes i am trying to setup my own nodejs server but i am having a problem i cannot figure out how to see changes to my application without restarting it is there a way to edit the application and see changes live with nodejs,['javascript'] +64759,why does pythons for in work differently on a list of values vs a list of dictionaries i am wondering about some details of how for in works in pythonmy understanding is for var in iterable on each iteration creates a variable var bound to the current value of iterable so if you do for c in cows c cowswhatever but changing c within the loop does not affect the original value however it seems to work differently if youre assigning a value to a dictionary keycows012345for c in cows c2cows is now the same 012345cowscow0cow1cow2cow3cow4cow5for c in cows ccow2 cows is now cow 2 cow 3 cow 4 cow 5 cow 6 cow 7so it is changed the original unlike the previous examplei see one can use enumerate to make the first example work too but that is a different story i guesscows012345for ic in enumeratecows cowsi1 cows is now 1 2 3 4 5 6why does it affect the original list values in the second example but not the firsteditthanks for the answers i was looking at this from a php point of view where you can use the symbol in foreach to specify whether you are operating on a reference to or a copy of the iterable i see now that the real difference is a basic detail of how python works regarding immutable objects,['python'] +64762,why is t t allowed i believe the expression t creates an rvalue by the standard however the following code compiles at least on gcc40class t int main t ti know technically this is possible because member functions can be invoked on temporaries and the above is just invoking the operator on the rvalue temporary created from the first tbut conceptually this is like assigning a new value to an rvalue is there a good reason why this is allowededit the reason i find this odd is it is strictly forbidden on builtin types yet allowed on userdefined types for example int2 int3 would not compile because that is an invalid lvalue in assignmentso i guess the real question is was this somewhat inconsistent behavior built into the language for a reason or is it there for some historical reason eg it would be conceptually more sound to allow only const member functions to be invoked on rvalue expressions but that cannot be done because that might break some existing code,['c++'] +64780,how to write a flexible modular program with good interaction possibilities between modules i went through answers on similar topics here on so but couldt find a satisfying answer since i know this is a rather large topic i will try to be more specifici want to write a program which processes files the processing is nontrivial so the best way is to split different phases into standalone modules which then would be used as necessary since sometimes i will be only interested in the output of module a sometimes i would need output of five other modules etc the thing is that i need the modules to cooperate because the output of one might be the input of another and i need it to be fast moreover i want to avoid doing certain processing more than once if module a creates some data which then need to be processed by module b and c i do not want to run module a twice to create the input for modules bc the information the modules need to share would mostly be blocks of binary data andor offsets into the processed files the task of the main program would be quite simple just parse arguments run required modules and perhaps give some output or should this be the task of the modulesi do not need the modules to be loaded at runtime it is perfectly fine to have libs with a h file and recompile the program every time there is a new module or some module is updated the idea of modules is here mainly because of code readability maintaining and to be able to have more people working on different modules without the need to have some predefined interface or whatever on the other hand some guidelines on how to write the modules would be probably required i know that we can assume that the file processing is a readonly operation the original file is not changedcould someone point me in a good direction on how to do this in c any advice is wellcome links tutorials pdf books,['c++'] +64825,regex for files in a directory is it possible to use a regular expression to get filenames for files matching a given pattern in a directory without having to manually loop through all the files,['java'] +64847,simple inheritance in c i was going over some sample questions for an upcoming test and this question is totally confusing meconsider the following codeclass graduatestudent public student if the word public is omitted graduatestudent uses private inheritance which means which of the followinggraduatestudent objects may not use methods of student graduatestudent does not have access to private objects of studentno method of graduatestudent may call a method of studentonly const methods of graduatestudent can call methods of student,['c++'] +64868,appconfig and 64bit machines i have an app that works fine on 32bit systems but fails on xp 64 bit systems i have tracked it down to the connection string defined in my appconfig thus connectionstrings clear add nameifdsconnectionstring connectionstringdata sourcefdsdatainitial catalogifds trusted connectiontrueconnect timeout0 providernamesystemdatasqlclient connectionstringswhen i try to reference it in code i find that the configurationmanagerconnectionstrings collection only contains the localsqlserver connection string from the machineconfig file and not my custom stringanother oddity is that it works fine when i run the app out of visual studio it is only when i run out of the release folder that the connection string does not get defined the applications execonfig file is there in the release folder along with the exe file and is up to date,['.net'] +64872,zend session zend auth randomly throws error message ps files cleanup dir opendirvarlibphp5 failed permission denied 13 i am currently working on a new application using among other things zend auth but for whatever reason this error message is showing up at any location totally randomly or so it seams zend sessionstart homehannesworkspacedeveloplibraryzendsessionphpline480 error 8 session start functionsessionstart ps files cleanup dir opendirvarlibphp5 failed permission denied 13 array 0 homehannesworkspacedeveloplibraryzendsessionnamespacephp143 zend sessionstarttrue1 homehannesworkspacedeveloplibraryzendauthstoragesessionphp87 zend session namespace constructzend auth2 homehannesworkspacedeveloplibraryzendauthphp91 zend auth storage session construct3 homehannesworkspacedeveloplibraryzendauthphp141 zend authgetstorage4 homehannesworkspacedevelopxapplicationcontrollersadmincontrollerphp10 zend authhasidentity5 homehannesworkspacedeveloplibraryzendcontrolleractionphp133 admincontrollerinit6 homehannesworkspacedeveloplibraryzendcontrollerthispatcherstandardphp262 zend controller action constructobjectzend controller request http objectzend controller response http array7 homehannesworkspacedeveloplibraryzendcontrollerfrontphp954 zend controller thispatcher standardthispatchobjectzend controller request http objectzend controller response http8 homehannesworkspacedeveloplibraryzendapplicationbootstrapbootstrapphp97 zend controller frontthispatch9 homehannesworkspacedeveloplibraryzendapplicationphp366 zend application bootstrap bootstraprun10 homehannesworkspacedevelopxpublicindexphp26 zend applicationrun11 main,['php'] +64880,does variable null set it for garbage collection help me settle a thispute with a coworkerdoes setting a variable or collection to null in java aid in garbage collection and reducing memory usage if i have a long running program and each function may be iteratively called potentially thousands of times does setting all the variables in it to null before returning a value to the parent function help reduce heap sizememory usage,['java'] +64899,modify a methodfunction at runtime i have been looking at the php reflection methods what i want to do is inject some code after the method is opened and before any return value for example i want to changefunction foobar foo bar return foo and inject some code into it likefunction foobar some code here foo bar some code here return foo possible,['php'] +64908,dynamic module creation i would like to dynamically create a module from a dictionary and i am wondering if adding an element to sysmodules is really the best way to do this egcontext a 1 b 2 import typestest context module typesmoduletypetestcontext module created to provide a context for teststest context module dict updatecontextimport syssysmodulestestcontext test context modulemy immediate goal in this regard is to be able to provide a context for timing test executionimport timeittimeittimera b from testcontext import it seems that there are other ways to do this since the timer constructor takes objects as well as strings i am still interested in learning how to do this though since a it has other potential applications and b i am not sure exactly how to use objects with the timer constructor doing so may prove to be less appropriate than this approach in some circumstanceseditsrevelationsphooeyseurekaei have realized that the example code relating to running timing tests would not actually work because import only works at the module level and the context in which that statement is executed is that of a function in the testit module in other words the globals dictionary used when executing that code is that of main since that is where i was when i wrote the code in the interactive shell so that rationale for figuring this out is a bit botched but it is still a valid questioni have thiscovered that the code run in the first set of examples has the undesirable effect that the namespace in which the newly created modules code executes is that of the module in which it was declared not its own module this is like way weird and could lead to all sorts of unexpected rattlesnakeic sketchiness so i am pretty sure that this is not how this sort of thing is meant to be done if it is in fact something that the guido doth shine uponthe similarbutsubtlydifferent case of dynamically loading a module from a file that is not in pythons include path is quite easily accomplished using impload sourcenewmodulename pathtomodulemodule to loadpy this does load the module into sysmodules however this does not really answer my question because really what if youre running python on an embedded platform with no filesystemi am battling a considerable case of information overload at the moment so i could be mistaken but there does not seem to be anything in the imp module that is capable of thisbut the question essentially at this point is how to set the global ie module context for an object maybe i should ask that more specifically and at a larger scope how to get python to do this while shoehorning objects into a given module,['python'] +64918,how do i pass references as method parameters across appdomains i have been trying to get the following code to workeverything is defined in the same assembly namespace someapublic class a marshalbyrefobject public byte getsomedata public class b marshalbyrefobject private a remoteobj public void setaa remoteobj thisremoteobj remoteobj public class c a somea new a public void init appdomain domain appdomaincreatedomainchilddomain string currentassemblypath assemblygetexecutingassemblylocation b remoteb domaindomaincreateinstancefromandunwrapcurrentassemblypathsomeappb as b remotebsetasomea this throws an argumentexception object type cannot be converted to target type what i am trying to do is pass a reference of an a instance created in the first appdomain to the child domain and have the child domain execute a method on the first domain in some point on b code i am going to call remoteobjgetsomedata this has to be done because the byte from getsomedata method must be calculated on the first appdomain what should i do to avoid the exception or what can i do to achieve the same result,"['c#', '.net']" +64922,use html markup into webconfig file i have to thisplay a messagge in my homepage defaultaspx different for each installation of my web app i would like to avoid to make a call to database to show this message so i have thougth to use webconfig to store something like this add keywelcomestring valuelorem ipsus bdoloret sit amenb but i have noticed i cannot use html markup into webconfig is there a better approach or is there a way to insert html markup into webconfig thank you again stack overflow gurus i am learning from you a lot of things,['asp.net'] +64936,textareas scroll by themselves on ie8 every time you type one character ie8 has a known bug per connectmicrosoftcom where typing or pasting text into a textarea element will cause the textarea to scroll by itself this is hugely annoying and shows up in many community sites including wikipedia the repro is thisopen the html below with ie8 or use any long page on wikipedia which will exhibit the same problem until they fix itsize the browser fullscreenpaste a few pages of text into the textareamove the scrollbar to the middle positionnow type one character into the textareaexpected nothing happensactual scrolling happens on its own and the insertion point ends up near the bottom of the textareabelow is repro html can also see this live on the web here boxactionedit doctype html public w3cdtd xhtml 10 transitionalen html xmlns body div stylewidth 80 textarea rows20 cols80 stylewidth100 textarea divbodyhtmli know i can avoid this by forcing the website into ie7 compatibility mode but whats the best other way to work around this bug while causing as few sideeffects as possible,['css'] +64940,how do i call setattr on the current module what do i pass as the first parameter object to the function setattrobject name value to set variables on the current modulefor examplesetattrobject some constant 42giving the same effect assome constant 42within the module containing these lines with the correct objecti am generate several values at the module level dynamically and as i cannot define getattr at the module level this is my fallback,['python'] +64955,how can i make named scope in rails return one value instead of an array i want to write a named scope to get a record from its id for example i have a model called event and i want to simulate eventfindid with use of named scope for future flexibilityi used this code in my modelnamed scope from id lambda id conditions id id and i call it from my controller like eventfrom idid but my problem is that it returns an array of event objects instead of just one objectthus if i want to get event name i have to writeevent eventfrom ididevent0namewhile what i want is event eventfrom idideventnameam i doing something wrong here,"['ruby-on-rails', 'ruby']" +64989,how can i use in if in ruby on rails i tried the following conditional for my if statement and i get a bad range error if from todaycontact calldays 07 show statuscontact call no status why and how can i fix it the only other way i could do it was to have a second nested if statement and break it apartnot pretty,['ruby-on-rails'] +64997,how to show sql queries run in the rails console when i run queries eg mymodelwhere or recordassociated things in the console how can i see the actual database queries being run so i can gain more understanding of what is happening,['ruby-on-rails'] +65003,checking if a function has clinkage at compiletime unsolvable is there any way to check if a given function is declared with clinkage that is with extern c at compiletimei am developing a plugin system each plugin can supply factory functions to the pluginloading code however this has to be done via name and subsequent use of getprocaddress or dlsym this requires that the functions be declared with clinkage so as to prevent namemangling it would be nice to be able to throw a compiler error if the referredto function is declared with clinkage as opposed to finding out at runtime when a function with that name does not existheres a simplified example of what i meanextern c void my funcvoid my other func replace this struct with one that actually workstemplatetypename tstruct is c linkage static const bool value truetemplatetypename tvoid assertclinkaget func static assertis c linkagetvalue supplied function does not have clinkageint main assertclinkagemy func should compile assertclinkagemy other func should not compileis there a possible implementation of is c linkage that would throw a compiler error for the second function but not the first i am not sure that it is possible though it may exist as a compiler extension which i would still like to know of thanks,['c++'] +65006,bitwise or of constants while reading some documentation here i came across thisunsigned unitflags nsyearcalendarunit nsmonthcalendarunit nsdaycalendaruniti have no idea how this works i read up on the bitwise operators in c but i do not understand how you can fit three or more constants inside one int and later being able to somehow extract them back from the int digging further down the documentation i also found this which is probably relatedtypedef enum kcfcalendarunitera 1 1 kcfcalendarunityear 1 2 kcfcalendarunitmonth 1 3 kcfcalendarunitday 1 4 kcfcalendarunithour 1 5 kcfcalendarunitminute 1 6 kcfcalendarunitsecond 1 7 kcfcalendarunitweek 1 8 kcfcalendarunitweekday 1 9 kcfcalendarunitweekdayordinal 1 10 cfcalendarunithow do the 1 3 statements variables work i am sorry if this is trivial but could someone please enlighten me by either explaining or maybe posting a link to a good explanation,['c'] +65009,visual studio keyboard shortcut to complete default accessors get set i am looking for a keyboard shortcut to complete creating the default accessors for a property in a c clasomething likei start typingpublic int id then i press one or more keys and i endup withpublic int id get set,['c#'] +65010,c generic static constructor will a static constructor on a generic class be run for every type you pass into the generic parameter such as this class somegenericclasst static listt somelist static somegenericclass somelist new listt are there any draw backs to using this approach,['c#'] +65022,google maps api load the us i am new to google maps api i would like suggestions on achieving the following functionality whenever the page loads the map will load centered around the us imagine a box around the us with given latlongs specifying the minimum and maximum boundaries i need the map to load at the appropriate zoom and zoom needs to be thisabled such that this box composes the entire mapbasically i am wondering if there is a function that loads the map based on latlong boundaries or some way to acheive this rather then loading the map given a zoom level,['javascript'] +65024,how to get javascript object references or reference count how to get reference count for an objectis it possible to determine if a javascript object has multiple references to it or if it has references besides the one i am accessing it with or even just to get the reference count itselfcan i find this information from javascript itself or will i need to keep track of my own reference countersobviously there must be at least one reference to it for my code access the object but what i want to know is if there are any other references to it or if my code is the only place it is accessed i would like to be able to delete the object if nothing else is referencing itif you know the answer there is no need to read the rest of this question below is just an example to make things more clearuse casein my application i have a repository object instance called contacts that contains an array of all my contacts there are also multiple collection object instances such as friends collection and a coworkers collection each collection contains an array with a different set of items from the contacts repositorysample codeto make this concept more concrete consider the code below each instance of the repository object contains a list of all items of a particular type you might have a repository of contacts and a separate repository of events to keep it simple you can just get add and remove items and add many via the constructorvar repository functionitems thisitems items repositoryprototypeget functionid for var i0lenthisitemslength ilen i if itemsiid id return thisitemsi repositoryprototypeadd functionitem if tostringcallitem object array thisitemsconcatitem else thisitemspushitem repositoryprototyperemove functionid for var i0lenthisitemslength ilen i if itemsiid id thisremoveindexi repositoryprototyperemoveindex functionindex if itemsindex if itemsi has more than 1 reference to it only remove item from repository if nothing else references it thisitemsspliceindex1 return note the line in remove with the comment i only want to remove the item from my master repository of objects if no other objects have a reference to the item heres collectionvar collection functionrepoitems thisrepo repo thisitems items collectionprototyperemove functionid for var i0lenthisitemslength ilen i if itemsiid id remove object from this collection thisitemssplicei1 tell repo to remove it only if no other references to it reporemoveindxei return and then this code uses repository and collectionvar contactrepo new repository id 1 name joe id 2 name jane id 3 name tom id 4 name jack id 5 name sue var friends new collection contactrepo contactrepoget2 contactrepoget4 var coworkers new collection contactrepo contactrepoget1 contactrepoget2 contactrepoget5 contactrepoitems contains item ids 1 2 3 4 5 friendsitems contains item ids 2 4coworkersitems contains item ids 1 2 5coworkersremove2contactrepoitems contains item ids 1 2 3 4 5 friendsitems contains item ids 2 4coworkersitems contains item ids 1 5friendsremove4contactrepoitems contains item ids 1 2 3 5 friendsitems contains item ids 2coworkersitems contains item ids 1 5notice how coworkersremove2 did not remove id 2 from contactrepo this is because it was still referenced from friendsitems however friendsremove4 causes id 4 to be removed from contactrepo because no other collection is referring to itsummarythe above is what i want to do i am sure there are ways i can do this by keeping track of my own reference counters and such but if there is a way to do it using javascripts builtin reference management i would like to hear about how to use it,['javascript'] +65035,rails dates with json i am implementing a facebook application and using ajaxjsonhowever the json structures that are returned have this format 20100530t061400zi am calling gameallto json in controller actionhow can i convert them to a normal date formatis it easier to do it from the server side or the client side using fbjsthere are a lot of bugs with fbjsso i would prefer using a solution from the server side using active records like converting the data before sending the json structures,['ruby-on-rails'] +65063,scrapy follow rss links i was wondering if anyone ever tried to extractfollow rss item links usingsgmllinkextractorcrawlspider i cannot get it to worki am using the following rule rules rulesgmllinkextractortagslink attrsfalse followtrue callbackparse article having in mind that rss links are located in the link tagi am not sure how to tell sgmllinkextractor to extract the text ofthe link and not to search the attributes any help is welcomethanks in advance,['python'] +65064,porting djangos templates engine to c i recently wrote a simple and tiny embedded http server for my c app qt and i played a little bit with rys httpparser and loved it this guy is crazyso i told to myself hey why not port the django template engine to c that would be awesome i know it would not be an easy task not at all i know but i would really love to implement this so i came here for inspiration ideas opinions i would really love to have some pointers on the subject ideas what is already done which major problems i will encounter and how to solve them how not to reinvent the wheel anyway you got the idea thanks a million timesps simple code snippets and links to tools and libs are very welcomepps i am already aware of grantlee i took a look into its sources well that is c and it is specific to qt,"['python', 'c']" +65084,how to enable curl installed ubuntu lamp stack i have installed ubuntu lamp stack but the curl is not enabled neither can i can find the extension listed in the ini file i added manually but it did not work eitherhow should i enable curl then,['php'] +65085,need a virtual template member workaround i need to write a program implementing the visitor design pattern the problem is that the base visitor class is a template class this means that basevisitedaccept takes a template class as a parameter and since it uses this and i need this to point to the correct runtime instance of the object it also needs to be virtuali would like to know if there is any way around this problemtemplate typename tclass basevisitor public basevisitor t visitbasevisited visited virtual basevisitorclass basevisited basevisited template typename t virtual void acceptbasevisitort visitor visitorvisitthis problem virtual basevisited,['c++'] +65089,jquery how to sleep or delay i want move up the object delay 10ms then hide iti get the codetestanimatetop80px1500 animatetop0px10 animateopacity0500i use animatetop0px10 to implement delay it is not goodi wanttestanimatetop80px1500 sleep10 animateopacity0500any idea,"['javascript', 'jquery']" +65093,are these two functions overkill for sanitization function sanitizestringvar var stripslashesvar var htmlentitiesvar var strip tagsvar return varfunction sanitizemysqlvar var mysql real escape stringvar var sanitizestringvar return vari got these two functions from a book and the author says that by using these two i can be extra safe against xssthe first function and sql injections2nd func are all those necessaryalso for sanitizing i use prepared statements to prevent sql injections i would use it like thisvariable sanitizestring postuser inputvariable sanitizemysql postuser inputedit get rid of strip tags for the 1st function because it does not do anything would using these two functions be enough to prevent the majority of attacks and be okay for a public site,"['php', 'mysql']" +65106,better c syntax coloring for visual studio 2010 coming from eclipse i am thisappointed with the very limited syntax coloring capabilities offered for c by visual studio all versions up to 2010in particular i am interesting in thistinct coloring for methods fields locals static stuffi am aware visual assist can enhance the coloring but i have failed to find any free alternative capable of doing that so i am turning to so i hope it is programmingrelated enough is there any free or at least cheaper than visual assist solution capable of enhancing the syntax coloring for c,['c#'] +65110,how to persist objects between requests in php i have been using rails merb django and aspnet mvc applications in the past what they have common that is relevant to the question is that they have code that sets up the framework this usually means creating objects and state that is persisted until the web server is recycled like setting up routing or checking which controllers are available etc as far as i know php is more like a cgi script that gets compiled to some bytecode each time it is run and after the request it is thiscarded of course you can have sessions to persist data between requests from the same user and as i see there are extensions like apc with which you can persist objects between requests at the server levelmy question is how can one create a php application that works like rails and such i mean an application that on the first requests sets up the framework then on the 2nd and later requests use the objects that are already set up is there some built in caching facility in mod php for example that stores the compiled bytecode of the executed php applications or is using apc or some similar extensions the only way to solve this problem how would you do itthanksedit alternative question if i create a large php application that has a very large set up time but minor running time like in the frameworks mentioned above then how should i cache the things that are already set up this might mean a lot of things except for maybe the database connections because for that you have persistent connections in php alreadyto justify large set up time what if i am using php reflection to check what objects are available and set the runtime according to that doing a lot of reflection is usually slow but one has to do it only once and reevaluate only if the source code is modifiededit2 it seems it is apc then the fact that it caches bytecode automatically is good to know,['php'] +65111,how to treat ram data as if it was a real file so i have some temp data in my program in ram i want to somehow make it seem as it is a file for example for sending it into another program which takes a file link as argumentis it possiblehow to do such thing,"['c++', 'c']" +65142,c enum in foreach possible duplicatesenumerate over an enum in cc iterate through an enum i have have a card class for a blackjack game with the following enumsenum rank ace two three four five six seven eight nine ten jack queen king enum suit clubs diamonds hearts spades when i create the deck i want to write the code like this foreach suit in cardsuit foreach rank in cardrank add new cardrank suit to decki believe there is no foreach in c however how do i traverse an enumthanksspencer,['c++'] +65143,is it wrong to use deprecated methods or classes in java i am using eclipse to develop a web application just today i have updated my struts version by changing the jar file i am getting warnings at some places that methods are deprecated but the code is working finei want to know some thingsis it wrong to use deprecated methods or classes in javawhat if i do not change any method and run my application with warnings that i have will it create any performance issue,['java'] +65144,a call to pinvoke function has unbalanced the stack i am getting this weird error on some stuff i have been using for quite a while it may be a new thing in visual studio 2010 but i am not surei am trying to call a unamanged function written in c from cfrom what i have read on the internet and the error message itself it is got something to do with the fact that the signature in my c file is not the same as the one from c but i really cannot see itfirst of all this is my unamanged function below tengine gcreateengineint widthint heightint depthint devicetypeand here is my function in c dllimportenginedll entrypoint gcreateengine callingconvention callingconventionstdcall public static extern intptr createengineint widthint heightint depthint devicewhen i debug into c i see all arguments just fine so thus i can only think it is got something to do with transforming from tengine which is a pointer to a class named cengine to intptr i have used this before in vs2008 with no problem,"['c#', 'c++']" +65147,passing zero arguments as params where the behaviour is defined c spec allows you to call a function void fooparams int xwith zero parameters however i did not find in c lang spec a word on further behaviour will foo get empty array or null reference i checked also msdn nothing where the behaviour is definednote i am not asking how vs behaves i am asking about design of the language,['c#'] +65167,how to style a standard gwt component tabbar differently i am using a tabbar and i want to style the component in different ways so one time this style another time that style i thought this will work but it did nottabbar t new tabbartaddtab 1 taddtab 2 taddstylename myresourcesinstancecslicktab andpublic interface myresources extends clientbundle public static final myresources instance gwtcreatemyresourcesclass sourcestylecss mycssresource csspublic interface mycssresource extends cssresource string slicktabin the cslicktab gwttabbar gwttabbaritem backgroundcolor ff0 fontweight normalbut the appearance do not change what i am doing wrong,['css'] +65178,which webserver to use with bottle bottle can use several webserversbuildin http development server and support for paste fapws3 flup cherrypy or any other wsgi capable serveri am using bottle for a desktopapp and i guess that the development server is enough in this case i would like to know if some of you have experience with one of the alternative serverwhich server for which purpose,['python'] +65184,how to swap html elements in javascript i am using classic javascript for dom scripting i have a set of divs in a container divon click event of child divs i want that the child div which has caused event to be swaped with the div above itmy code goes here div idcontainer div onclickswapdivevent1div div onclickswapdivevent2div div onclickswapdivevent3div divif div 2 has been clicked it should be swap with div 1,['javascript'] +65196,fastest way to copy a table in mysql i want to copy a table in mysql what is the fastest way like thiscreate table copy like originalinsert into copy select from originalorcreate table copy select from originalalter table copy add primary key idor is there another wayedit i am worried about the indexes being recreated how does mysql proceed executing these statements ps cannot use commandline tools like mysqldump must be onthefly,"['sql', 'mysql']" +65203,how to thisplay an image in a java application i want to thisplay an image in my java application i found a code to download the image from the webserver and show it in the jframe i want to use a label to show the image or something else it should not be jframehere is my codeimage image nulltry url url new url image imageioreadurl catch ioexception e use a label to thisplay the imagejframe frame new jframejlabel lblimage new jlabelnew imageiconimageframegetcontentpaneaddlblimage borderlayoutcenterframesetsize300 400framesetvisibletruecan someone help me,['java'] +65206,can i create my own database from php i have a working php server now i want to use databases mysql or something similar is it possible to create a database from phpi would like to emphasize that in my case i do not have any username and password which i can use to connect to mysql server i also do not have a controlpanel where i could create a database or a table in an existing databaseaddedi think sqlite is what i need but if i try to create a new database from php i see that php tries to create a file in a directory which is different from the directory where my files are supposed to be then it reports that it is unable to create the database and i think it is because it tries to create in the directory to which i have no permission to write can i force php to create sqlite in a specific directory,"['php', 'mysql']" +65226,javascript array best practice to use instead of new array i read at many tutorials that the current best practices to create a new javascript array is to use var arr instead of var arr new arraywhats the reasoning behind that,['javascript'] +65228,cancel a keystroke in jquery is is possible crossbrowser compatible to cancel a keystroke after a user has made it for example on a textboxthe code i currently use edits the textbox value after the keystroke has been thisplayednumberkeypressfunction thisvalue thisvaluereplace09g,"['javascript', 'jquery']" +65232,possible to rewrite url clientside with javascript without reloading page is it possible to rewrite the url in the urlfield on the clients browserso when a person clicks on a link on my page something ajax happens eg a tab shows up i want the url to thisplay the action without refreshing the page is this possible,['javascript'] +65246,debugging phpcli scripts with xdebug and netbeans i have managed to initiate phpcli script debug session from the ide itself but i need to start the debugging session from the shell command line these are rather complex maintenance php scripts which take a lot of input parameters so entering arguments from within netbeans is a bit cumbersomei have done it before with zend studio entryid130 but now i need to get it working with netbeansthanks in advance,['php'] +65254,how do i dynamically load raw assemblies that contains unmanaged codebypassing unverifiable code failed policy check exception i am going to give an example of using systemdatasqlitedll which is a mixed assembly with unmanaged code if i execute this var assembly assemblyloadfromsystemdatasqlitedllno exceptions are thrown but if i do this var rawassembly filereadallbytessystemdatasqlitedll var assembly assemblyloadrawassemblythe clr throws a fileloadexception with unverifiable code failed policy check exception from hresult 0x80131402 let us say i am trying to load this assembly on a child appdomain how can i customize the appdomains security to allow me pass the policy check,"['c#', '.net']" +65282,skipped when looking for precompiled header so some reason my cpp file is missing it is header file but i am not including the header file anywhere else i just started so i checked all the files i madeenginuityhifndef engine define engine class enginuitypublic void initwindowenginuitycppinclude enginuityhvoid enginuityinitwindowmaincppinclude stdafxhinclude gameproject1hdefine max loadstring 100 global variableshinstance hinst current instancetchar sztitlemax loadstring the title bar texttchar szwindowclassmax loadstring the main window class name forward declarations of functions included in this code moduleatom myregisterclasshinstance hinstancebool initinstancehinstance intlresult callback wndprochwnd uint wparam lparamint ptr callback abouthwnd uint wparam lparamint apientry twinmainhinstance hinstance hinstance hprevinstance lptstr lpcmdline int ncmdshowcodeendifdont know whats going on the error i get is1cusersnumerical25desktopintro todirectxgameprojectgameproject1gameproject1enginuitycpp1 warning c4627 include enginuityh skipped when looking for precompiled header use1 add directive to stdafxh or rebuild precompiled header1cusersnumerical25desktopintro todirectxgameprojectgameproject1gameproject1enginuitycpp8 fatal error c1010 unexpected end of file while looking for precompiled header did you forget to add include stdafxh to your source,['c++'] +65301,google visualization api line and scatter on one chart does any one know if it is possible to use the default google scatter chart in the google visualizations gallery to draw a scatter chart that has both a series with points only a series with a line of best fit and on top of this a set of lines across the chart indicating limits ie at 20 etcthe chart we need is actually a control chart with multiple series and individual formatting of each series thisplayed on the chart ie some series with only points other series with a line of best fitdoes any one know of a control chart that has already been done using the google visualization api,['javascript'] +65309,pushing app to heroku problem i am trying to push my app to heroku and i get the following message heroku createcreating electricmeadow15 donecreated electricmeadow15git git push heroku master no such app as fiercefog63fatal the remote end hung up unexpectedlyit is weird that i am getting this now i have pushed the app to heroku many times without issue the especially weird thing is fiercefog63 is an old app that i made and deleted a long time ago why is it now that heroku is trying to push to this app that does not exist anymore especially when i have created a new one any suggestions,"['ruby-on-rails', 'ruby']" +65314,adding an ilist item to a particular index number our clients database returns a set of prices in an array but they sometimes do not include all prices ie they have missing elements in their array we return what we find as an ilist which works great when we retrieve content from the database however we are having difficulties setting the elements in the proper position in the arrayis it possible to create an ilist then add an element at a particular position in the ilistvar mylist new listmodelvar mymodel new modelmylist3 mymodel something like what we would want to do,['c#'] +65316,copy a directory to a different drive how do i copy a directory to a different drive in c,['c#'] +65322,foreign keys vs joins is it better to use foreign keys in tables or can the same results be achieved with joins,['sql'] +65323,is there a thrift or cassandra client for nodejsjavascript i would like to start using cassandra with a nodejs deployment but i cannot find a thrift or cassandra client for nodejs andor javascriptis there oneis there a simple means of generating thrift connections update the short answer to this question turns out to be no there is no js client for thrift that is compatible with cassandrafurther update the next release of cassandra 08 at time of writing is going to have support for an avro api there is already nodejs module for avro support,['javascript'] +65333,how to hide parent tabbar when pushing controller in navigationcontroller i have an application with a tab bar controller and each view contains a navigation controller my mainwindow looks as follows everything works fine as it is but i noticed a problem when pushing a details view to the navigation controller in the didselectrowatindexpath for a tableviewcontroller that belongs to the tab bar controller the one called latest in the image i am doing this voidtableviewuitableview tableview didselectrowatindexpathnsindexpath indexpath articleviewcontroller articlecontroller articleviewcontroller alloc initwithnibnamearticleview bundlenilselfnavigationcontroller pushviewcontrollerarticlecontroller animatedyesarticlecontroller releasearticlecontroller nilthe articleviewcontroller has its own tabbar because it needs to thisplay different things the problem is that when i push the articleviewcontroller into the navigationcontroller i see both tabbars at the bottom of the view is there any way i can solve this problemthanks in advance,['iphone'] +65335,how to read from an xmlreader without moving it forwards hey guys i have got this scenariowhile readerread if readernodetype xmlnodetypeelement readername itemelementname xelement item null try item xelementreadfromreader as xelement catch xmlexception ex log line number and stuff from xmlexception class in the above loop i am transforming a certain node itemelementname into an xelementsome nodes will be good xml and will go into an xelement however some will notin the catch i would like to not only catch the standard xmlexception stuff i would also like to catch an extract of the current xml and a stringhowever if i do any kind of read operation on the node before i pass it to the xelement it moves the reader forwardhow can get a snapshot of the contents of the outerxml of the reader without interfering with it is position,"['c#', '.net']" +65338,c predicatebuilder entities the parameter f was not bound in the specified linq to entities query expression i needed to build a dynamic filter and i wanted to keep using entities because of this reason i wanted to use the predicatebuilder from albaharii created the following codevar invoerdatums predicatebuildertrueonderzoeksvragenvar inner predicatebuilderfalseonderzoeksvragenforeach var filter in setrapportinvoerfiltertolist iffilterisdate var date datetimeparsefilterwaarde invoerdatums invoerdatumsoro ovan date otot date else string temp filterwaarde inner inneroro oonderzoektype temp invoerdatums invoerdatumsandinnervar onderzoeksvragen entitiesonderzoeksvragen asexpandable whereinvoerdatums tolistwhen i ran the code there was only 1 filter which was not a date filter so only the inner predicate was filled when the predicate was executed i got the following errorthe parameter f was not bound in the specified linq to entities query expressionwhile searching for an answer i found the following page but this is already implemented in the linqkit does anyone else experienced this error and know how to solve it,['c#'] +65354,auto expand a textarea using jquery how can i make a textarea automatically expand using jquery,['jquery'] +65356,why fontstretch does not work in wpf i am trying setting fontstretch property on a textblock in wpf but it seems that it does not work i tried expanded condensed etc but the text appearance does not changei am working on windows xp with framework 40 and tested both with verdana and arialdoes it work only on windows 7 or only with some specific fontsedit if it does not work with all fonts is there a list of fonts that support this feature or is it possible to modify a font like verdanaarial to support it,['.net'] +65371,how to measure a website bandwidth uploaddownload in mb using cvbnet programmatically hope that everybody is fine herei am writing a windows service in cvbnet that aims at measuring bandwidth consumption for all websites on localhost and store their statistics for upload download etc on localremote database target platforms include only windows server 2003 2003 r2 2008 and 2008 r2i have searched a bit on this thing and found the followingusing snmp mgmtapidll which is found in windows 2003using a custom network driver to collect statisticsplease guide on the most appropriate secure and effective methodologytechnique or set of such techniques which can be used to measure the bandwidth consumption for each different website please also share any code in this regardregardssteve,['c#'] +65373,how to add data to google calendar programmatically in android hi i need to add particulars to google calendar from my application is it possible to add data to google calendar i am new to android help me to solve this,['android'] +65382,how to resize a uiswitch i have made a custom uiswitch from this post but the problem is my custom texts are a bit long is there any way to resize the switch i tried setbounds did not workedithere is the code i usedinterface customuiswitch uiswitch void setleftlabeltext nsstring labeltext void setrightlabeltext nsstring labeltext endimplementation customuiswitch uiview slider return self subviews lastobject uiview textholder return self slider subviews objectatindex2 uilabel leftlabel return self textholder subviews objectatindex0 uilabel rightlabel return self textholder subviews objectatindex1 void setleftlabeltext nsstring labeltext self leftlabel settextlabeltext void setrightlabeltext nsstring labeltext self rightlabel settextlabeltext endmyswitch customuiswitch alloc initwithframecgrectzerotried these but did not workcgrect aframe myswitchframeaframesizewidth 200aframesizeheight 100myswitchframe aframemyswitch setleftlabeltext longvalue1myswitch setrightlabeltext longvalue2,['iphone'] +65385,mysqldump more than one table how can i use mysqldump to dump certain tables that start with common prefix,['mysql'] +65387,what happens at os level when a net program exits due to an uncaught exception actual questionswhat happens in windows when a program crashes from an uncaught exceptionis there a dll function which i can hook to log some basic information about a crashcontexti am planning to write a program which will collect some very basic information about any applications which crash on my local pc i was hoping that i could execute a simple method to log some information about a crash in a similar manner to the way visual studio produces a dialog offering to let you debug a program when it crashes,['.net'] +65390,nsurlconnection nsurlrequest untrusted cert and user authentication morning everyonei have been attempting to write an application that does some gets from a remote web service that requires authentication my main problem is that the majority of these remote servers and there are a lot of them do not have valid certificates i have got code to accept the invalid certificate and code to respond to the challenge with the correct uname pass below the problem i am having is getting the two to play together i cannot seem to find a way to send the challenge both nsurlcredentials or a way to chain the callbacks correctly when i try to chain them i cannot get my nsurlrequest to call didreceiveauthenticationchallenge twiceany thoughts would be appreciatedcode for authenticationvoidconnectionnsurlconnection connection didreceiveauthenticationchallengensurlauthenticationchallenge challenge ifhascanceled if challenge previousfailurecount 0 nsurlcredential newcredential newcredentialnsurlcredential credentialwithuser username password password persistencensurlcredentialpersistencenone challenge sender usecredentialnewcredential forauthenticationchallengechallenge else challenge sender cancelauthenticationchallengechallenge nslogbad username or password badusernameandpassword yes finished yes,['iphone'] +65402,how to simulate a corrupt state exception in net 4 well in net 4 microsoft added the handleprocesscorruptedstateexceptions attributehandleprocesscorruptedstateexceptionsattribute classi want to test this feature how can i bring my application to a corrupt state,['.net'] +65405,alternative to c exception i am writing a reactive software which repeatedly recieves input processes it and emits relevant output the main loop looks something likeinitializewhile true message msgout recievemsg processmsgout no global state is saved between loop iterations sendouti want that whatever error occured during the proccess phase whetehr it is out of memory error logical error invalid assertion etc the program will clean up whatever it did and keep running i will assume it is invalid input and simply ignore itcs exception are exceptionally good for that situation i could surround process with trycatch clause and throw exception whenever something goes wrog the only thing i need to make sure that i clean up all my resources before throwing an exception this could be verified by raii or by writing a global resource allocator for instance if your destructor might throw an exception and use it exclusively for all resourcessocket s globalresourcehandlermanagesocketnew sockettry processmsgoutcatch globalresourcehandlercleanuphowever using exception is forbidden in our coding standard also in googles c standard btw as a result all the code is compiled with exceptions off and i believe nobodys going to change the way everything work just for my design problemalso this is code for embedded platform so the less c extra feature we use the faster the code becomes and the more portable it isis there an alternative design i can considerupdatei appreciate everyones answer about idiotic code standard the only thing i can say is in big organizations you have to have strict and sometimes illogical rules to make sure no idiot would come and make your good code unmaintainable the standard is more about people than about technicalities yes bad man can make every code a mess but it is much worse if you give him extra tools for the taski am still looking for a technical answer,['c++'] +65416,are private members inherited in c just seen one tutorial saying thatclass dog private string nameclass superdogdog private string moodthen there was an uml thisplaying that superdog will inherit name as well i have tried but to me it seems that only public members are inherited at least i could not access name unless it was declared as public,['c#'] +65438,how do i compile variadic templates conditionally is there a macro that tells me whether or not my compiler supports variadic templatesifdef variadic templates availabletemplatetypename args void coolstuffargs argselseendifif they are not supported i guess i would simulate them with a bunch of overloads any better ideas maybe there are preprocessor libraries that can ease the job,['c++'] +65462,is javascript only available for web browsers i would like to know about javascript is javascript available only for web browsers because i used some javascript code for firefox plugin development and thunderbirdhelp me to find out more about this where can i use javascript other than web browsers and how,['javascript'] +65466,problems trying to format currency with python django i have the following code in djangoimport locale localesetlocale localelc all def format currencyi return localecurrencyfloati groupingtrueit work on some computers in dev mode but as soon as i try to deploy it on production i get this errorexception type templatesyntaxerrorexception value caught valueerror while rendering currency formatting is not possible using the c localeexception location usrlibpython26localepy in currency line 240the weird thing is that i can do this on the production server and it will work without any errorspython managepy shell import locale localesetlocale localelc all en cautf8 localecurrency1 groupingtrue100i do not get iti,['python'] +65482,binaryformatter with memorystream question i am testing binaryformatter to see how it will work for me and i have a simple questionwhen using it with the string hello and i convert the memorystream to an array it gives me 29 dimensions with five of them being the actual data towards the end of the dimensions binaryformatter bf new binaryformatter memorystream ms new memorystream byte bytes string originaldata hello bfserializems originaldata msseek0 0 bytes mstoarrayreturns bytes dimensions29 byte 0 0 byte 1 1 byte 2 0 byte 3 0 byte 4 0 byte 5 255 byte 6 255 byte 7 255 byte 8 255 byte 9 1 byte 10 0 byte 11 0 byte 12 0 byte 13 0 byte 14 0 byte 15 0 byte 16 0 byte 17 6 byte 18 1 byte 19 0 byte 20 0 byte 21 0 byte 22 5 byte 23 72 byte 24 69 byte 25 76 byte 26 76 byte 27 79 byte 28 11 byteis there a way to only return the data encoded as bytes without all the extraneous information,['c#'] +65484,python pep8 blank lines convention i am interested in knowing what is the python convention for new lines between the program for example consider thisimport osdef func1def func2what should be the ideal new line separation betweenthe import modules and thefunctionsthe functions themselves i have read pep8 but i wanted to confirm the above two points,['python'] +65485,taking intersection of nmany lists in python whats the easiest way to take the intersection of nmany lists in pythonif i have two lists a and b i know i can doa setab setbintersect aintersectionbbut i want to do something like a b c d for an arbitrary set of lists ideally without converting to a set first but if that is the easiest most efficient way i can deal with thatie i want to write a function intersectargs that will do it for arbitrarily many sets efficiently whats the easiest way to do thatedit my own solution is reducesetintersection abc is that goodthanks,['python'] +65493,unique ptr boost equivalent is there some equivalent class for c1xs stdunique ptr in the boost libraries the behavior i am looking for is being able to have an exceptionsafe factory function like sostdunique ptrbase create base return stdunique ptrbasenew derivedvoid some other function stdunique ptrbase b create base do some stuff with b that may or may not throw an exception now b is destructed automagicallyedit right now i am using this hack which seems like the best i can get at this pointbase create base return new derivedvoid some other function boostscoped ptrbase b create base do some stuff with b that may or may not throw an exception now b is deleted automagically,['c++'] +65503,jsonignore attributes not working in aspnet i have got an object in my project with circular references i have put jsonignore above the field like so jsonignore public virtual foobar childobject get set i am still getting circular reference errors when i serialize the object the only fields that do not have jsonignore are string fields and should not cause this is there something else i need to do to get jsonignore to workthanks,"['c#', 'asp.net']" +65519,execute a string of php code on the command line i would like to be able to run a line of php code on the command line similar to how the following options work perl e print hi python c print hi ruby e puts hii would like to be able to do php echo hii have read that there is a r option that can do what i need for php however it does not appear to be available when i try to use it i have tried using php 5213 and php 449 and neither have an r option availablei wrote this script that i called run phpphp which works but i am not a huge fan of it just because i feel like there should be a more correct way to do itusrbinphp5 qphp echo evalargv1 my question is is there a r option if so why is it not available when i run help if there is no r option what is the best way to do this without writing an intermediary script if possiblethanks edit because i do not think it was very clear above the r option is not available to me here is the php h output for both versions of php that i am runningphp 449usage php q h s v i f file php file args a run interactively c do not chdir to the scripts directory c pathfile look for phpini file in this directory n no phpini file will be used d foobar define ini entry foo with value bar e generate extended information for debuggerprofiler f file parse file implies q h this help i php information l syntax check only lint m show compiled in modules q quietmode suppress http header output s thisplay colour syntax highlighted source v version number w thisplay source with stripped comments and whitespace z file load zend extension filephp 5213usage php q h s v i f file php file args a run interactively c do not chdir to the scripts directory c pathfile look for phpini file in this directory n no phpini file will be used d foobar define ini entry foo with value bar e generate extended information for debuggerprofiler f file parse file implies q h this help i php information l syntax check only lint m show compiled in modules q quietmode suppress http header output s thisplay colour syntax highlighted source v version number w thisplay source with stripped comments and whitespace z file load zend extension filethere is no r option when i try to use the r option i geterror in argument 1 char 2 option not found rsorry for the confusion,['php'] +65520,can bad stuff happen when dividing 1a very small float if i want to check that positive float a is less than the inverse square of another positive float b in c99 could something go wrong if b is very smalli could imagine checking it likeifa1but if b is small enough would this possibly result in infinity if that were to happen would the code still work correctly in all situationsin a similar vein i might doif1abb which might be slightly better because bb might be zero if b is small is this truefinally a solution that i cannot imagine being wrong isifsqrt1abwhich i do not think would ever result in zero division but still might be problematic if a is close to zeroso basically my questions arecan 1x ever be infinity if x is greater than zero but small can xx ever be zero if x is greater than zero will comparisons with infinity work the way i would expect them toedit for those of you who are wondering i ended up doingifbab1 i did it in that order as it is visually unambiguous which multiplication occurs first,['c'] +65524,javascript get the current executing i need to know if it is possible to obtain the current execution node examplehtmlscript idx consolelogdocumentcurrentnodeid this must return xscripthtmlthanks,['javascript'] +65530,simple multithread safe log class what is the best approach to creating a simple multithread safe logging class is something like this sufficient how would i purge the log when it is initially createdpublic class logging public logging public void writetologstring message object locker new object locklocker streamwriter sw swfileappendtextdatalogtxt swwritelinemessage swclose public partial class mainwindow window public static mainwindow instance get private set public logging log get set public mainwindow instance this log new logging,['c#'] +65532,best way to handle integer overflow in c handling integer overflow is a common task but whats the best way to handle it in c is there some syntactic sugar to make it simpler than with other languages or is this really the best wayint x fooint test x commoniftest common x consolewritelineoh noeselse consolewritelinesafe,"['c#', '.net']" +65542,mxmlc and 64bit jre are there any workarounds to get the flex compiler to work with a 64bit jre if i use an mxmlc task in an ant buildfile in eclipse it works fine but if i try to use mxmlc from the command line or try the run command from fdt in eclipse it fails telling me error loading cprogram filesjavajrrt160jrebinjrockitjvmdllthis is with a 64bit jrockit runtime but that should not matter,['java'] +65556,how does operator behaves differently with numbers and strings in java java does not have concept of operator overloadingstill operator behaves as addition operator with numbers and concatenate operator with strings this is similar to the operator overloading behavior so does java have operator overloading,['java'] +65563,checking to see if a string is a valid date ruby on rails say i have a string 31022010 and i want to check see whether or not it is a valid date or notwhat is the best way to do iti need a method which i can call on string which returns true if the string is a valid date and false if it is not,"['ruby-on-rails', 'ruby']" +65577,android is there a universal way to send the mms on any android devices this code works on the plain google devices with native android system but there is no mms app in the list on htc sense devices and i do not know about motorola blur etc final intent emailintent new intentandroidcontentintentaction send emailintentsettypeimagepng emailintentputextraintentextra stream uri contextstartactivityintentcreatechooseremailintent contextgetstringrstringsend intent namethis code works on the htc sense but not from the chooser what i really need intent sendintent new intentandroidintentactionsend msg sendintentputextraintentextra stream uri sendintentsettypeimagepng contextstartactivitysendintentbut i do not know how to combine this code samples together and i do not know how to determine htc sense ui programmatically is it right way to support different type of devicesthank you for answers,['android'] +65584,setting the cores to use in parallelism i have a feeling the answer to this is no but using net 40s parallelism can you set the amount of cores on which to run ie if your running a quad core can you set your application to only use 2 of themthanks,"['c#', '.net']" +65610,quickactions like the twitter app i want to add pattern 6 quickactions from androids blog to my appany code snippetanyone try to do it already should this work on android 15,['android'] +65629,php form post automatically mapping to an object model binding i do a lot of aspnet mvc 2 development but i am tackling a small project at work and it needs to be done in php is there anything builtin to php to do model binding mapping form post fields to a class some of my php code currently looks like thisclass entryform public firstname public lastname entryform new entryformif post postsubmit submit entryformfirstname trim postfirstname entryformlastname trim postlastnameis there anything builtin to a typical php install that would do such mapping like youd find in aspnet mvc or does it require an additional framework,['php'] +65631,implementing drilldown navigation in android app ui i am trying to learn how to do stuff in android and i am not sure of the best way to build the interfacei have been working on porting an iphone app which uses navigation controllers and table views for looking at the different sections basically someone touches a cell in the table which drills down to another table when they touch a cell on that table it drills down to a webview that thisplays the information i want to do something similar for the android app but i do not know how or if there is a better way native to android i have figured out how to use the webview to my purposes but moving forward and backward in the table tree is unclear,['android'] +65636,can tsql store ulongs i want to store a cnet ulong into a tsql database i do not see any provisions for doing this as the sql bigint has the same minmax values as a normal long is there any way i can do this or is catching an overflowexception my only hope,"['c#', '.net', 'sql']" +65638,service and a broadcastreceiver i have seen several examples of how to implement a broadcastreceiver but how should i implement a service that has to react to some pending intent for example incoming phone callactually i was wondering about the same problem but in an activityyou obviously have a class which extends a service or an activity so it cannot also extend broadcastreceiverit looks like we cannot make platformaware services andor activties,['android'] +65640,removing shinegloss effect on the iphone through uiprerenderedicon not working on device i have tried to use the uiprerenderediconicon already includes gloss and bevel on the infoplist of my app and it worked perfectly on the simulator but not on the real device ipod touch 2g i have even tried to uninstall the app from the device clean all builds but i still got the shinegloss that is really ruining my icon any thoughtsbest regardsmuffie,"['iphone', 'objective-c']" +65643,how to get the domain value for a cookie in javascript using javascript i would like to get the domain value for a specific cookieis this possible if so howto clarify i am not looking for the value of the cookie i am on subdomaindomaincom and i need to remove a cookie whose name is known but its domain value is something like domaincom in short i would like to get the value of domaincom,['javascript'] +65647,remove characters before character how effectively remove all character in string that placed before character inputamerikausaoutputusa,['c#'] +65650,ship maritime ais information api is there an api or web service that can be used to read ais data most links i read starting at wikipedia identification system say that ais data is freely available but i am having a hard time finding a provider of the data a c example or language agnostic web service would be helpful,['c#'] +65652,failing android junit tests not breaking my ant script like i expect failing junit tests not breaking my ant script like i expectmy continuous integration server runs an ant script which calls something liketestsant runtestsmy junit tests run but with errorsruntests echo runtestshelper echo running tests exec exec comzedraystufoobartest exec comzedraystufoobartestinstrumentation result shortmsgsome error in your code exec instrumentation result longmsgjavasecurityinvalidparameterexception some error in your code exec instrumentation code 0the errors are ok but my build script keeps going eventually publishing my broken app to my testers bad what i would expect is for the instrimentaiton to throw a build error so my continuous integration server teamcity in this case realises that something has gone wrong and reports a broken build the failonerror is already set in the relevant macrodef so i am not sure what else i can dotestsbuildxml running tests any ideassuggestions on how to fix thisregardsmark,['android'] +65654,stop duplicate ajax submisions i am wondering what is the best way to stop duplciate submissions when using jquery and ajaxi come up with 2 possible ways but not sure if these are the only 2on ajax start thisable all buttons till request is done 2 problems i see with this though is i use jquery model dialog so i do not know how easy it would be to thisable those button as i not sure if they have ids second i if the the request hangs the user has really no way to try again since all the buttons are thisabledi am looking into something called ajaxqueue at this time i have no clue if it is what i need or how it works since the site where the plugin is apparently down for maintenanceediti think this is a spin off of what i was looking atthe only problem i see with this ajaxmanager is that i think i have to change all my post get and ajax ones to their typebut what happens if i need a special parameter from ajax or that fact i like using post and getedit 2i think it can take in all ajax options i am still looking into it however what i am unsure about now is can i use the same constructor for all requests that will use the same optionsfirst you have to constructconfigure a new ajaxmanagercreate an ajaxmanager named someajaxprofilenamevar somemanagedajax manageajaxcreatesomeajaxprofilename queue true cacheresponse trueor do i have to make the above every single time,['jquery'] +65658,convert existing project into android project in eclipse how do you convert an existing project into an android project in eclipsein particular i want to convert a plain old java project into an android library projectthanks,['android'] +65663,autoload with namespacessubmodules i am using modules as namespaces in ruby how would i go about autoloadingsomething like autoload appmodulea appmodule a that does not throw a must be constant name error,['ruby'] +65700,ehcache default cache in java i have this configuration for ehcacheehcache defaultcache namedefaut maxelementsinmemory5 eternalfalse timetoidleseconds20 timetoliveseconds20 overflowtothiskfalse thiskpersistentfalse memorystoreevictionpolicylru ehcachehow can i get access to default cache of ehcachecachemanagergetinstancegetcachedefault returns null,['java'] +65704,what happens if i do not specify targetframework40 in my aspnet 40 webconfig i had the following attributecompilation targetframework40if i remove the targetframework attribute everything appears to carry on as normal under what circumstances does this attribute help me,['asp.net'] +65711,jsdoc adding real code in documentation do you know if there is a some sort of code tag in jsdoci need to add pieces of code in my documentation like this this function does something see example below var x footest it will show test message param string str string argumnet that will be shown in messagefunction foostr alertstri need the code in the comments to be thisplaied by jsdoc as code if not sintax highlighetd at least like preformatted or something with grey backgroundthanks,['javascript'] +65712,java hashset is allowing dupes problem with comparable i have got a class accumulator that implements the comparable compareto method and i am trying to put these objects into a hashsetwhen i add to the hashset i do not see any activity in my compareto method in the debugger regardless of where i set my breakpoints additionally when i am done with the adds i see several duplicates within the setwhat am i screwing up here why is it not comparing and therefore allowing the dupesthanksivr avenger,['java'] +65716,my android html application is losing values stored in localstorage when it shuts down anyone else see this issue i have a native android 21 application that hosts a web view i load up a site that contains javascript that uses the localstorage feature when the application is running localstorage works fine when some users exit the application and restart it all the values are gone i am not seeing this problem in my motrola droid or sprint evo but there is a report of users in the field with this issuedoes anyone know what i am missing i am setting the following flag to truesettingssetdomstorageenabledtrue,['android'] +65727,include and table aliasing i am suffering from a variant of the problem described hereactiverecord assigns table aliases for association joins fairly unpredictably the first association to a given table keeps the table name further joins with associations to that table use aliases including the association names in the path but it is common for app developers not to know about other joins at coding timein my case i am being bitten by a toxic mix of has many and include many tables in my schema have a state column and the has many wants to specify conditions on that column has many foo conditions state 1 however since the state column appears in many tables i thisambiguate by explicitly specifying the table name has many foo conditions this tablestate 1 this has worked fine until now when for efficiency i want to add an include to preload a fairly deep tree of data this causes the table to be aliased inconsistently in different code paths my reading of the tickets referenced above is that this problem is not and will not be fixed in rails 2x however i do not see any way to apply the suggested workaround to specify the aliased table name explicitly in the query i am happy to specify the table alias explicitly in the has many statement but i do not see any way to do so as such the workaround does not appear applicable to this situation nor i presume in many named scope scenariosis there a viable workaround,['ruby-on-rails'] +65736,compile javascript to native code with v8 is it really possible with googles v8 engine to compile javascript into native code save it as a binary file and execute it whenever i want through my software envorinment on any machine,"['javascript', 'c++']" +65741,cloud sync between ipadiphone app i have a core data app that will end up being an iphoneipad universal applicationi would like to implement cloud syncing so that an iphone and an ipad both running the app could share data i am planning to use the recently released dropbox api does anyone have any thoughts on the best way to go about doing this the dropbox api allows for apps to store files on the cloud what i was thinking was to original store the database sqlite for the app on the cloud and then download that database but i then realized that using that method would make it painfully difficult to merge changes rather than replacing the whole databaseany thoughts are appreciated thanks,['iphone'] +65746,what algorithm does python employ in fractionsgcd i am using the fractions module in python v31 to compute the greatest common divisor i would like to know what algorithm is used i am guessing the euclidean method but would like to be sure the docs do not help can anybody clue me in,['python'] +65748,regexismatch vs stringcontains is there any difference in speedmemory usage for these two equivalent expressionsregexismatchmessage 10vsmessagecontains10any situations where one is better than other the context of this question is as followsi was making some changes to legacy code which contained the regex expression to find whether a string is contained within another string being legacy code i did not make any changes to that and in the code review somebody suggested that regexismatch should be replaced by stringcontains so i was wondering whether the change was worth making,['.net'] +65753,silverlight typedescriptorgetconverter substitute i am trying to use the linq to csv project in silverlight its a great project because its open sourced i figured i could just recompile as a silverlight class library but unfortunately it appears to use a feature not available in silverlight the typedescriptorgetconverter methodit uses this to find type converters to properly parse the csv columns to their corresponding clr types i have no problem making changes to the linqtocsv sources to make it work in silverlight but i just do not know what an equivalent operation would be in silverlight various google searches have brought me to this page but all that says is that the xaml parser has a way of doing this but it does not say how to access this functionalityin a nutshell the question ishow do i replicate the functionality of typedescriptorgetconverter i do not necessarily need an exact drop in replacement i just want to know a good way to do this without hardcoding a bunch of type typeconverter associations,['c#'] +65754,best way to change the background color for an nsview i am looking for the best way to change the backgroundcolor of an nsview i would also like to be able to set the appropriate alpha mask for the nsview something likemyviewbackgroundcolor nscolor colorwithcalibratedred0227f green0251f blue0337 alpha08i notice that nswindow has this method and i am not a big fan of the nscolorwheel or nsimage background options but if they are the best willing to use,['objective-c'] +65757,is a primary key automatically indexed is it true that in mysql the primary key is automatically indexed,"['sql', 'mysql']" +65767,how do i autoreload a chrome extension i am developing i would like for my chrome extension to reload every time i save a file in the extension folder without having to explicitly click reload in chromeextensions is this possibleedit i am aware i can update the interval at which chrome reloads extensions which is a halfway solution but i would rather either making my editor emacs or textmate trigger onsave a reload or asking chrome to monitor the directory for changes,['javascript'] +65775,how to store passwords in database i use jsp and servlets in my web application i need to store passwords in the database i found that hashing will be the best way to do thati used this code to do it page importcomjsurveyentity page importjavasecuritymessagedigest page importjavasecuritynosuchalgorithmexception page importjavamathbiginteger page importcomjsurveycontroller page importsunmiscbase64encoder try string user requestgetparameterusername string pass requestgetparameterpassword1 string name requestgetparametername string mail requestgetparameteremail string phone requestgetparameterphone string add1 requestgetparameteraddress1 string add2 requestgetparameteraddress2 string country requestgetparametercountry login login new login account account new account loginsetiduser loginsetpasswordpass if add1equals accountsetaddress1add1 if add2equals accountsetaddress2add2 if countryequals accountsetcountrycountry accountsetiduser accountsetmail idmail if phoneequals accountsetphone nolongparselongphone accountsetnamename javasecuritymessagedigest d null d javasecuritymessagedigestgetinstancesha1 dreset dupdatepassgetbytesutf8 byte b ddigest string tmp new base64encoderencodeb accountsetpasswordtmp accountsetprivilege1 loginjpacontroller logcon new loginjpacontroller accountjpacontroller acon new accountjpacontroller logconcreatelogin aconcreateaccount sessionsetattributeuser user responsesendredirectdashboardjsp catch numberformatexception ex outprintlninvalid data when i tried to print the value of tmp i get some other valuei guess its the hash value of the password but when i persist this data to the database the original password gets saved there other than the value in tmpi am using java derby as the databasewhat is the problem,['java'] +65780,deploying to heroku with sensitive setting information i am using github for code and heroku for the deployment platform for my rails appi do not want to have sensitive data under git such data include database file settings databaseyml and some other files that have secret api keyswhen i deploy to heroku how can i deal with files that are not under revision controlwhen i use capistrano i can write some hook methods but i do not know what to do with heroku,['ruby-on-rails'] +65781,passing event args and sender to the relaycommand how do you get event sender when using relaycommand,['.net'] +65785,rails engines extending functionality i have an engine which defines some models and controllers i want to be able to extend functionality of some modelscontrollers in my application eg adding methods without loosing the original modelcontroller functionality from engine everywhere i read that you simply need to define controller with the same name in your application and rails will automatically merge them however it does not work for me and controller in engine is simply ignored i do not think it is even loaded,"['ruby-on-rails', 'ruby']" +65793,adding an annotation to a runtime generated methodclass using javassist i am using javassist to generate a class foo with method bar but i cannot seem to find a way to add an annotation the annotation itself is not runtime generated to the method the code i tried looks like thisclasspool pool classpoolgetdefault create the classctclass cc poolmakeclassfoo create the methodctmethod mthd ctnewmethodmakepublic integer getinteger return null caddmethodmthdclassfile ccfile ccgetclassfileconstpool constpool ccfilegetconstpool create the annotationannotationsattribute attr new annotationsattributeconstpool annotationsattributevisibletagannotation annot new annotationmyannotation constpoolannotaddmembervaluevalue new integermembervalueccfilegetconstpool 0attraddannotationannotccfileaddattributeattr generate the classclazz cctoclass length is zerojavalangannotationannotation annots clazzgetannotationsand obviously i am doing something wrong since annots is an empty arraythis is how the annotation looks likeretentionretentionpolicyruntimetargetelementtypemethodpublic interface myannotation int value,['java'] +65801,best tutorial for learning wordpress plugin development i am new to wordpress can any one suggest me a best tutorial for learning wordpress plugin development and some simple examples i have done some searches in google and got some informations,['php'] +65826,netbeans shortcut key for collapsingexpanding a method java netbeansthis is an ide questioni am always working with collapsed methods because i want to be able to see my methods all together this is a little time consuming because i have to use the mouse to scroll up to the declaration of the method and click on the minus icon and then respectively go to the method i want to work on and click on the plus iconis there a way through a keyboard shortcut to do the collapse and respectively the expand,['java'] +65860,how do i bind a click to an anchor without a framework javascript i know this is easily done in jquery or any other framework but that is not really the point how do i go about properly binding a click event in pure javascript i know how to do it inline i know this is terriblea hrefdochtml onclickmyfunc return falseclick hereaand this causes my javascript to execute for a js enabled browser and the link to behave normally for those without javascriptnow how do i do the same thing in a noninline manner,['javascript'] +65868,why does javascripts or return a value other than truefalse i saw this construction in order to get the browser viewport widthfunction return windowinnerwidth documentdocumentelementclientwidth documentbodyclientwidth i understand the browser quirks involved what i do not understand is why returns the value so i tried this alertundefined 0 3 and sure enough it alerts 3 i find this bizarre because i expect true or false could anyone explain whats going on,['javascript'] +65872,can i see the exact commands intellij uses to build a java project can i see the exact commands intellij uses to build a java project,['java'] +65879,can i use the decorator pattern to wrap a method body i have a bunch of methods with varying signatures these methods interact with a fragile data connection so we often use a helper class to perform retriesreconnects etc like somyhelperperformcall dostuffwithdataparameters and this works fine but it can make the code a little cluttery what i would prefer to do is decorate the methods that interact with the data connection like sointeractswithdataprotected string dostuffwithdataparameters do stuffand then essentially whenever dostuffwithdata is called the body of that method would be passed in as an action to myhelperperformcall how do i do this,['c#'] +65898,using nspredicate to determine if a string equals another string i have an nsarray of calevents returned with the calcalendarstore eventpredicatewithstartdate method from the events returned i am trying to keep only those in which the title of the event on call caseinsensitivei am able to keep in the array those events whose title includes on call with the following code where events is a nsarray populated with caleventsnspredicate oncallpredicate nspredicate predicatewithformatselftitle containsc on callevents filteredarrayusingpredicateoncallpredicatei have tried using a predicate format string likeselftitle on call but this does not seem to workis there an easier way to do this,['objective-c'] +65916,how to select saxon transformerfactory in java in my web application i need to use saxon transformerfactory in order to use xslt 20 but i cannot use setproperty method because i do not have this right on the web server and there is a security managerso i have read that it should be possible to do thisuse the services api as detailed in the jar specification if available to determine the classname the services api will look for a classname in the file metainfservicesjavaxxmltransformtransformerfactory in jars available to the runtimei found this file in webinflibsaxon9jar but when i istantiate a transformerfactory the default factory is always selected instead of a saxon factoryhow can i select saxon transformer factorythanks,['java'] +65917,why was not c designed with const for variables and methods possible duplicateconst correctness in c i suspect const was simplified for the c spec for general language simplicity was there a specific reason we cannot declare variable references or methods as const like we can with c egconst myobject o new myobject want const cast referenece of myobjectosomemethod theoretically legal because somemethod is constochangestuff theoretically illegal because changestuff is not constclass myobject public int val 0 public void somemethod const do stuff but cannot mutate due to const declaration public void changestuff code mutates this instance cannot call with const reference val,['c#'] +65918,is there an r equivalent of the pythonic if name main main the objective is to have two simple ways to source some code say funcr containing a function calling r cmd batch funcr initializes the function and evaluates is within a session issuing sourcefuncr simply initializes the functionany idea,['python'] +65931,multiline strings in objectivec localized strings file i have a template for an email that i have put in a localized strings file and i am loading the string with the nslocalizedstring macroi would rather not make each line its own string with a unique key in objectivec i can create a humanreadable multiline string like sonsstring email hello n n check out n n sincerelyn n i tried to put that in a strings file withemail hello n n check out n n sincerelyn n but i get the following error at build timecfpropertylistcreatefromxmldata oldstyle plist parser missing semicolon in dictionaryemailtemplatestrings unexpected character at line 1command developerlibraryxcodepluginscorebuildtasksxcplugincontentsresourcescopystrings failed with exit code 1i can concatenate it all together like thisemail hello nncheck out nnsincerelynnbut that will be a mess to maintain particularly as the email gets longeris there a way to do this in a localized strings file i have already tried adding backslashes at the end of each line to no avail,"['objective-c', 'iphone']" +65932,get windows username with javascript i am working a firefox addon which is written in javascript and need to determine the windows user currently logged on is there a way to do this,['javascript'] +65960,sharepoint 2010 client object model add attachment to listitem i have a sharepoint list to which i am adding new listitems using the client object model adding listitems is not a problem and works great now i want to add attachments i am using the savebinarydirect in the following mannerfilesavebinarydirectclientctx urlabsolutepath attachments31 filename inputstream trueit works without any problem as long as the item that i am trying to add the attachment to already has an attachment that was added through the sharepoint site and not using the client object model when i try to add an attachment to a item that doesnt have any attachments yet i get the following errors both happen but not with the same files but those two messages appear consistently the remote server returned an error 409 conflictthe remote server returned an error 404 not foundi figured that maybe i need to create the attachment folder first for this item when i try the following codeclientctxloadticketlistrootfolderfoldersclientctxexecutequeryclientctxloadticketlistrootfolderfolders1 1 attachment folderclientctxloadticketlistrootfolderfolders1foldersclientctxexecutequeryfolder folder ticketlistrootfolderfolders1foldersadd33clientctxexecutequeryi receive an error message saying cannot create folder liststicket systemattachment33i have full administrator rights for the sharepoint sitelist any ideas what i could be doing wrong thanks thorben,['c#'] +65968,postgresql how to index all foreign keys i am working with a large postgresql database and i am trying to tune it to get more performance our queries and updates seem to be doing a lot of lookups using foreign keyswhat i would like is a relatively simple way to add indexes to all of our foreign keys without having to go through every table 140 and doing it manuallyin researching this i have come to find that there is no way to have postgres do this for you automatically like mysql does but i would be happy to hear otherwise there too,['sql'] +65984,string count with overlapping occurrences whats the best way to count the number of occurrences of a given string including overlap in python is it the most obvious waydef functionstring str to search for count 0 for x in xrangelenstring lenstr to search for 1 if stringxxlenstr to search for str to search for count 1 return countfunction10101returns 5or is there a better way in python,['python'] +65990,aio network sockets and zerocopy under linux i have been experimenting with async linux network sockets aio read et al in aiohlibrt and one thing i have been trying to find out is whether these are zerocopy or not pretty much all i have read so far thiscusses file io whereas its network io i am interested inaio is a bit of a pain to use and i suspect is nonportable so wondering whether its worth persevering with it zerocopy is just about the only advantage albiet a major one for my purposes it would have over nonblocking selectepoll,['c'] +65991,pythonic way to do something and times without an index variable every day i love python more and more today i was writing some code likefor i in xrangen do somethingi had to do something and times but each time did not depend on the value of i index variablei realized that i was creating a variable i never used i and i thought there surely is a more pythonic way of doing this without the need for that useless index variableso the question is do you know how to do this simple task in a more pythonic beautiful way,['python'] +65996,using scanf in a while loop probably an extremely simple answer to this extremely simple questioni am reading c primer plus by pratta and he keeps using the examplewhile scanfd num 1is the 1 really necessary it seems like one could just writewhile scanfd numit seems like the equality test is unnecessary since scanf returns the number of objects read and 1 would make the while loop true is the reason to make sure that the number of elements read is exactly 1 or is this totally superfluous,['c'] +66007,is there something like phps preg replace callback in javascript what i want to do is strreplacepattern callbacknot simply strreplacepattern replace patternis it possible to do it in javascript,['javascript'] +66009,android show mediacontroller i am adding mediacontroller to a videoview but it does not show up unless i tap the phone the controller thisappears after a whileis there a way i can have the mediacontroller show alwaysthankschris,['android'] +66011,what does nsbinarysearchingfirstequal 1ul 8 mean in an enumeration definition i saw this in nsarrayh header file in the framework directoryenum nsbinarysearchingfirstequal 1ul 8 nsbinarysearchinglastequal 1ul 9 nsbinarysearchinginsertionindex 1ul 10typedef nsuinteger nsbinarysearchingoptionswhats the point of nsbinarysearchingfirstequal 1ul 8and whats the relationship between this enumeration and the nsbinarysearchingoptions typedefinition thanks,['objective-c'] +66028,c warning suggest parentheses around arithmetic in operand of i have a code like a bcdethrowing the warning suggest parentheses around arithmetic in operand of expecting that expression needs high priority paranthesis for operators tried the following waysabcdeone more as abcdestill the same warning persists please help me in resolving thisthankssujathab cd are enums and e is an integer,['c++'] +66035,dql query fails i have got 2 tables in an mysql db im using doctrine 12 and symfony 144installedbase and spareinstalledbaseib idapp idlocationandsparespare idapp idamountnow i want to join the to tables to show how many of the app are in the spareegq selfcreatequerylselecti sfrominstalledbase i spare sexecutereturn qdoctrine knows there is a relation between the tables on the app id field but i get the error 500 internal server error doctrine hydrator exception spare with an alias of s in your query does not reference the parent component it is related toyamli cant figure this one out does anybody know what doctrine is complaining about,['mysql'] +66038,extract from string in java i have a stringstring value 55 58 854524how can i splitextract logical values from this string inside parenthesis as854 as one58 one as twotwo524 as three55 three as fourany idea all is welcome,['java'] +66041,no connection could be made because the target machine actively refused it sometimes i get the following error while i was doing httpwebrequest to a webservice i copied my code below toosystemnetwebexception unable to connect to the remote server systemnetsocketssocketexception no connection could be made because the target machine actively refused it 12700180 at systemnetsocketssocketdoconnectendpoint endpointsnapshot socketaddress socketaddress at systemnetsocketssocketinternalconnectendpoint remoteep at systemnetservicepointconnectsocketinternalboolean connectfailure socket s4 socket s6 socket socket ipaddress address connectsocketstate state iasyncresult asyncresult int32 timeout exception exception end of inner exception stack trace at systemnethttpwebrequestgetrequeststreamservicepointmanagercertificatepolicy new trustallcertificatepolicyhttpwebrequest request httpwebrequestwebrequestcreateurlrequestpreauthenticate truerequestcredentials networkcredentialslarequestmethod webrequestmethodshttppostrequestcontenttype applicationxwformurlencodedrequesttimeout v timeout 10if urlindexofasmx 0 parstartindex 0 apphelperloggerappend slaservicename using streamwriter reqwriter new streamwriterrequestgetrequeststream while true int index01 parlistlength int index02 parlistindexof if parlistindexof 0 index01 parlistindexof string parname parlistsubstring0 index02 string parvalue parlistsubstringindex02 1 index01 index02 1 reqwriterwrite01 httputilityurlencodeparname httputilityurlencodeparvalue if index01 parlistlength break reqwriterwrite parlist parlistsubstringindex01 1 else requestcontentlength 0 response httpwebresponserequestgetresponse,['.net'] +66042,getting jstorage to work so i think jstorage is what i need to solve one of my problems it needs json to be working with jquery so i have tried including it but it does not seem to work i have no idea what json is actually heres my code jquery is loaded higher it does not even show the alert windowscript typetextjavascript srcjqueryjson22minjsscriptscript typetextjavascript srcjstoragejsscriptscript typetextjavascriptjstoragesetkey test value jstoragegetkeyalerttestvaluescriptwhat could cause this,"['javascript', 'jquery']" +66052,linq query expressions that operate on types monads other than ienumerable possible uses i am reading the book realworld functional programming by tomas petricek and jon skeet and i am having a hard time digesting the section on computation expressions1 aka monadsthrough this book i learnt that contrary to my previous experiences linq query expressions are not restricted to ienumerablet but can work on other custom types as well this seems very interesting to me and i am wondering if there are scenarios where the query expression syntax from x in select would be a nice fitsome background infoapparently such custom types are called computation types which are portrayed as being essentially the same thing as monads in haskell i have never been able to grasp what exactly monads are but according to the book they are defined through two operations called bind and returnin functional programming the type signatures of these two operations would be i think bind ma a b mb return a mawhere m is the monadic types namein c this corresponds tofunc ma funcab mb bindfunc a ma returnit turns out that linqs enumerableselect the projection operator has exactly the same signature as the bind operation with m ienumerablemy custom linq computation typeusing this knowledge i can now write a custom computation type which is not ienumerable my custom computation typeclass wrappeda this corresponds to the return operation public wrappeda value thisvalue value public readonly a valuestatic class wrapped this corresponds to the bind operation public static wrappedb selecta bthis wrappeda x funcab selector return new wrappedbselectorxvalue and now i can use wrappedt in linq query expressions egwrappedint wrapped new wrappedint41wrappedint answer from x in wrapped works on int values instead select x 1 of wrappedint valuesof course this example is not very useful but it demonstrates how query expressions can be made to do something else than working with collections eg wrapping and unwrapping values with some typequestionthe above computation type does not seem very useful therefore i wonder what other reasonable uses besides processing collections could there be that make use of linq query expressions1 section 124 introducing alternative workflows starting on page 334,['c#'] +66057,using a custom typeface in android i want to use a custom font for my android application which i am creatingi can individually change the typeface of each object from code but i have hundreds of themsois there a way to do this from the xml setting a custom typefaceis there a way to do it from code in one place to say that the whole application and all the components should use the custom typeface instead of the default onethankscodevalley,['android'] +66059,check wifi and gps isconnected or not in android i would need to check the wifi is on or off in the phone at the runtimeif it is not connected i want to show dialog and goto directly settingwireless controls to enable it by userits for both wifi and gps staus of the phone how to do it which intent to wake for this any idea,['android'] +66073,how do you find out about new java technologies tools and specifications one of the major challenges for any java developer is try to keep in pace of development of the language and new tools java is evolving all the time and it happens often that i hear from a friend or colleague about some useful tool i had never heard of beforei would love to hear about how people find out when new java specs come out or an interesting new tool is released for example what java blogs do you follow,['java'] +66077,is pythons logging module thread safe if you call the same logging handler from two different python threads is there a need for locking,['python'] +66083,question on gwt cookies and webpage directing i am using gwt to create a website this question is regarding a login page and cookies to save login details gwt allows you to create a website within a single webpagemy application runs on one webpage i have the application set up as there is a login box with a login button and if the details are correct it will load up the underlying ui and removes the login box so that means every time i refresh my page the application brings me to the login page is there anyway to set up a cookie that hold the information of the user for example a day that would input the details into the login box and sign in automatically also the logout button within the web app would remove the information in the cookie and bring you to the login page remove the cookie information and direct you to the login part of the webpageor would there be a different approach,['java'] +66091,webrat and rails using assert contain after click button gives me you are being redirected i am writing an integration test for a rails application using webrat after filling out a form the user presses submit and an account is createdclick button submitassert contain your account has been createdhowever the test fails expected the following elements content to include your account has been createdyou are being redirectedfalse is not truenormally to follow a redirect i would use post via redirect but from just looking at webrats examples click button followed by assert contain should worki just started using webrat so am i missing something obvious here why am i stuck with the redirect responsethanksdeb,['ruby-on-rails'] +66095,efficiency of the stl priority queue i have an application c that i think would be well served by an stl priority queue the documentation sayspriority queue is a container adaptor meaning that it is implemented on top of some underlying container type by default that underlying type is vector but a different type may be selected explicitlyandpriority queues are a standard concept and can be implemented in many different ways this implementation uses heapsi had previously assumed that top is o1 and that push would be a ologn the two reasons i chose the priority queue in the first place but the documentation neither confirms nor denies this assumptiondigging deeper the docs for the sequence concept saythe complexities of singleelement insert and erase are sequence dependentthe priority queue uses a vector by default as a heap which supports random access to elements constant time insertion and removal of elements at the end and linear time insertion and removal of elements at the beginning or in the middlei am inferring that using the default priority queue top is o1 and push is onquestion 1 is this correct top access is o1 and push is onquestion 2 would i be able to achieve ologn efficiency on push if i used a set or multiset instead of a vector for the implementation of the priority queue what would the consequences be of doing this what other operations would suffer as a consequencenb i am worried about time efficiency here not space,['c++'] +66098,does c have direct flexyacc port or what lexerparser people use for c i might be wrong but it looks like that there is no direct flexbison lexyacc port for cnet so far for lalr parser i found gppggplex and for ll parser there is the famous antlr but i want to reuse my flexbison grammar as much as possible is there any direct port of flexbison for cwhat lexerparser people normally use for c is there any reason for that choice,"['c#', '.net']" +66106,shortcut to create automatic properties using visual studio 20082010 or resharper 5 i have a class that contains a load of properties that contain results of some calculations egpublic class results public double result1 get set public double result2 get set in a different class i am doing calculations to populate the above properties egpublic class calc private results calc results res new results resresult1 some calculation resresult2 some other calculation resresult3 not yet defined in results class return res when i am writing the calc class result3 will be highlighted in red as it is not yet defined in the results classcurrently i am using the resharper alt enter shortcut selecting create property result3 which will create the following code int the results classpublic double result3 get throw new notimplementedexception set throw new notimplementedexception which i need to manually change topublic double result3 get set then i use the ctrl shift backspace shortcut to take me back to the calc classhow can i easily create automatic properties in the results class if they are not yet defined directly from the calc class,['c#'] +66116,cgcontextdrawpdfpage taking up large amounts of memory i have a pdf file that i want to draw in outline form i want to draw the first several pages on the document each in their own uiimage to use on a button so that when clicked the main thisplay will navigate to the clicked pagehowever cgcontextdrawpdfpage seems to be using copious amounts of memory when attempting to draw the page even though the image is only supposed to be around 100px tall the application crashes while drawing one page in particular which according to instruments allocates about 13 mb of memory just for the one pageheres the code for drawingnote this is always called in a background thread but the autorelease pool is setup elsewhere void drawpagecgpdfpagerefm page inrectcgrectrect incontextcgcontextref g cgpdfbox box kcgpdfmediabox cgaffinetransform t cgpdfpagegetdrawingtransformm page box rect 0yes cgrect pagerect cgpdfpagegetboxrectm page box start the drawing cgcontextsavegstateg clip to our bounding box cgcontextcliptorectg pagerect now we have to flip the origin to topleft instead of bottom left first flip yaxix cgcontextscalectmg 1 1 second move origin cgcontexttranslatectmg 0 rectsizeheight now apply the transform to draw the page within the rect cgcontextconcatctmg t finally draw the page the important bit commenting out the following line fixes the crashing issue cgcontextdrawpdfpageg m page cgcontextrestoregstategis there a better way to draw this image that does not take up huge amounts of memory,['iphone'] +66119,comet vs ajax polling i need to create a chat like facebook chatwith comet i need more memory to keep the connectionwith ajax polling there is a latency problem if i send request every 34 secondsso if the latency 34 seconds does not matter is ajax polling better for my case,['javascript'] +66122,how do you indent preprocessor statements when there are many preprocessor statements and many ifdef cascades it is hard to get an overview since normally they are not indented egifdef win32 include pansen win32elseinclude ifdef someotherstmtsendifmaybe stmtsendifwhen i consider also indenting those preprocessor statements i fear of getting confused with the general indentation level so how do you solve this in a beautiful way,['c++'] +66162,redirect a tcp connection i have something like a proxy server written in java running between my clients and the actual video server made in c everything the clients send goes through this proxy and is then redirected to the serverit is working fine but i have some issues and think it would be better if i could make this proxy server only to listen to the clients requests and then somehow tell the server that a request has been made from the client side and that it is supposed to create a connection with the client directlybasically in the tcp level what i want to happen is something like this1 whenever a client sends a syn to my proxy the proxy just sends a message to the real server telling the ip and port of the client2 the server would then send the corresponding synack to the specified client creating a direct connection between client and serverthe proxy would then be just relaying the initial requests but not the later data transfer to the actual server i just do not know if that is possiblethank you very muchnelson r perez,"['java', 'c++']" +66185,wcf instance already exists in counterset error when reopening servicehost i have a working servicehost with a single nettcpbinding and a single endpointi close it then i create a new servicehost instance with the exact same configuration as the first one then when i try to open the new instance i am getting this very awkward exceptionsystemargumentexception occurred messageinstance localhost2718game already exists in counterset e829b6db21ab453b83c9d980ec708eddparameter name instancename sourcesystemcore paramnameinstancename stacktrace at systemdiagnosticsperformancedatacountersetinstancectorcounterset countersetdefined string instancenamehas anybody seen that before is it a bug in the net framework i am using 40 by the wayprobably relevant info about my servicehostno clients are connected to the host when it is first closeda custom iinstanceprovider is used to create instancesthe bindings reliablesession is turned onthe service type is marked with the servicebehavior belowservicebehaviorincludeexceptiondetailinfaults trueinstancecontextmodeinstancecontextmodepersessionconcurrencymodeconcurrencymodereentrantusesynchronizationcontext falsei am open to reveal any extra info you might want to know about the applicationupdate 1 i compiled the application targeting net 35 and the error did not happened unfortunately i have to deactivate everything that relied in tasksupdate 2 i logged a bug at microsoft connect about this issue i guess this question is already answered now,['.net'] +66204,androids edittext is hidden when the virtual keyboard is shown and a surfaceview is involved i have a simple user interface an edittext should be located below a surfaceviewi use a relativelayout to arrange these two views now when i tap on the edittext to open the virtual keyboard the surfaceview slides up but the edittext is hidden and does not show the typed stringto reproduce use the following layout xml codexml version10 encodingutf8relativelayoutxmlnsandroid androidididrelativelayout01androidlayout heightfill parent androidlayout widthfill parentsurfaceviewandroidididsurfaceview01androidlayout widthfill parent androidlayout heightwrap contentsurfaceviewedittext androidididedittext01androidlayout heightwrap contentandroidlayout widthfill parentandroidlayout alignparentlefttrue androidlayout alignparentbottomtrue androidselectallonfocustrueandroidtextstylenormalandroidsinglelinetrueedittext relativelayoutthe main activity class only needs to show the layout when i start the program and tap the edittext the virtual keyboard appears but the edittext field is gonemaybe the relativelayout is causing the problems but i do not know how to reproduce the same layout with another layout classany suggestions are welcome i really appreciate your helpthanksedithere are two screenshots one showing the edittext at the bottom without virtual keyboard one with virtual keyboard but with no edittext it is interesting to note that the surfaceview and the edittext actually shift upward the edittext just thisappears btw this also happens to a button if it is next to the edittextedittext below a surfaceview left edittext is gone right,['android'] +66209,practical rules for premature optimization it seems that the phrase premature optimization is the buzzword of the day for some reason iphone programmers in particular seem to think of avoiding premature optimization as a proactive goal rather than the natural result of simply avoiding thistraction the problem is the term is beginning to be applied more and more to cases that are completely inappropriatefor example i have seen a growing number of people say not to worry about the complexity of an algorithm because that is premature optimization eg frankly i think this is just laziness and appalling to thisciplined computer sciencebut it has occurred to me that maybe considering the complexity and performance of algorithms is going the way of assembly loop unrolling and other optimization techniques that are now considered unnecessarywhat do you think are we at the point now where deciding between an onn and on complexity algorithm is irrelevant what about on vs onnwhat do you consider premature optimization what practical rules do you use to consciously or unconsciously avoid itediti know my description is a bit general but i am interested in specific practical rules or best practices people use to avoid premature optimization particularly on the iphone platformanswering this requires you to first answer the question of what is premature optimization since that definition clearly varies so greatly any meaningful answer requires the author to define the term that is why i do not really think this is a cw question again if people thisagree i will change it,['iphone'] +66248,how can use iframe in html what is iframe and how can we use it in html,['html'] +66264,rails logging for code in the lib directory what is the besteasiest way to configure logging for code kept in the lib directory,"['ruby-on-rails', 'ruby']" +66277,javascript getelementbyname does not work this simple js script cannot set the value of para i guess getelementbyname does not work but why scriptfunction fn documentgetelementbyidparasetattributenamehi documentgetelementbynamehisetattributevaluemy value is high scripthtmlinput typebutton onclickfn valueclick meinput idpara typetext,['javascript'] +66279,strict pointer aliasing any solution for a specific problem i have a problem caused by breaking strict pointer aliasing rule i have a type t that comes from a template and some integral type int of the same size as with sizeof my code essentially does the followingt x some other tif reinterpret cast int x 0 because t is some arbitary other than the size restriction type that could have a constructor i cannot make a union of t and int this is allowed only in c0x only and is not even supported by gcc yetis there any way i could rewrite the above pseudocode to preserve functionality and avoid breaking strict aliasing rule note that this is a template i cannot control t or value of some other t the assignment and subsequent comparison do happen inside the templated codefor the record the above code started breaking on gcc 45 if t contains any bit fields,['c++'] +66297,mysql trigger to prevent insert under certain conditions i want to make a trigger that will prevent the insertion if the birthdate one of the columns is in the future i have thiscreate trigger foobefore insert on tablefor each rowbegin if newbirthdate current date then how do i prevent the insert right here end ifendhow can i cancel the insert inside the if statement,"['sql', 'mysql']" +66305,css 100 percent height body and element i am having an issue making one of my elements 100 within an overall layout that is 100i have tried different positioning solutions and i either end up with hidden content the floats behind the footer at the bottom or the content ends up going behind the footer and carrys on after the footerhere is what i have for the page layoutdoctype html public w3cdtd xhtml 10 stricten html xmlns langenusheadstyle margin0 htmlbodymargin0 padding0 height100 wrapperpositionrelative margin0 auto 200px heightauto important height100 minheight100 containerwidth930px margin0 auto textalignleft rightfloatright width680px backgroundf margin60px 10px 0 0 padding0 leftfloatleft width240px contentpadding10px footerpositionabsolute width100 footerpushheight200pxstyleheadbodydiv classwrapperdiv classcontainerdiv idleft leftdivdiv classrightdiv classcontent contentdivdivdiv classpushdivdivdiv classfooter footerdivdivbodyhtmlthe layout for the page being 100 height and footer at the bottom works it just the div with the class name content that i would like to be 100 as well and push the footer further down if the content reaches the footer and not thisappearany help most appreciated,['css'] +66315,strict doctype form and input element does anyone know the reasoning behind the strict doctype not allowing input elements to be direct descendents of a form element i find it annoying that i have to wrap a submit button which is a block level element inside another block level element say a fieldset or a div however i cannot find an answer anywhere as to why this actually is,['html'] +66319,what is strong name in net possible duplicatewhat is strong naming and how do i strong name a binary actually yesterday i attended an intrviewin that they asked 1 question about strong namei cannot able to guess what it ispls explain about thisthanks,"['c#', '.net']" +66334,custom event listener on android app i need to set up a simple event listener to refresh a listview once in a while the problem is i do not know how could i generate an eventi know that for events like key or button pressing i just need to implement the handler but in this specific case i actually need to generate the event which will be fired every time another running thread of my app wakes up and refreshes its list of news from an rss feedi have done everything but got stuck in here can i get any suggestion or link with some more info on how to implement this,['android'] +66351,thisplay date and time in user locale i know i can use androidtextformatdateformatgetdateformat to format my dates and androidtextformatdateformatgettimeformat to format my times but how do i format a datetime similar to the getdatetimeinstance method from javatextdateformati am currently just concatenating the result of both the getdateformat and gettimeformats formatters but i do not know which way around the user prefers to have their dates and times shown,['android'] +66356,configure listbox in wpf so that i will be possible to select multiple items without holding ctrl key i have a listbox that allows user to select multiple items normally user can do that by holding ctrl key and clicking the item he or she wants to selectis it possible to configure this listbox so that the user will not have to hold the ctrl key when selecting items so that he or she will just click the item without holding anything and the item will be selectedthiselected if it was selected previously thank you,['c#'] +66360,how to pass an xml file to lxml to parse i am trying to parse an xml file using lxml xmletree allowed me to simply pass the file name as a parameter to the parse function so i attempted to do the same with lxmlmy codefrom lxml import etreefrom lxml import objectifyfile cprojectspythoncbxmltree etreeparsefilebut i get the errortraceback most recent call last file cbpy line 5 in module tree etreeparsefile file lxmletreepyx line 2698 in lxmletreeparse srclxmllxmletreec49590 file parserpxi line 1491 in lxmletree parsedocument srclxmllxmletreec71205 file parserpxi line 1520 in lxmletree parsedocumentfromurl srclxmllxmletreec71488 file parserpxi line 1420 in lxmletree parsedocfromfile srclxmllxmletreec70583 file parserpxi line 975 in lxmletree baseparser parsedocfromfile srclxmllxmletreec67736 file parserpxi line 539 in lxmletree parsercontext handleparseresultdoc srclxmllxmletreec63820 file parserpxi line 625 in lxmletree handleparseresult srclxmllxmletreec64741 file parserpxi line 565 in lxmletree raiseparseerror srclxmllxmletreec64084lxmletreexmlsyntaxerror attvalue or expected line 2 column 26what am i doing wrong,['python'] +66369,do you use python mostly for its functional or objectoriented features i see what seems like a majority of python developers on stackoverflow endorsing the use of concise functional tools like lambdas maps filters etc while others say their code is clearer and more maintainable by not using them what is your preferencealso if you are a diehard functional programmer or hardcore into oo what other specific programming practices do you use that you think are best for your stylethanks in advance for your opinions,['python'] +66381,is contextannotationconfig an alternative to autowired is it correct that i can put contextannotationconfig in my xml config and it will automatically inject the bean class without needing any annotationsso instead of using these annotation typespublic class mailman private string name autowired private parcel parcel public mailmanstring name thisname name autowired public void setparcelparcel parcel thisparcel parcel autowired public void directionstoparcelparcel parcel thisparcel parcel i would just need to write thisbeans bean idmailman classmailman constructorarg valuejohn doebeanbean idparcel classparcel contextannotationconfig beansand then my mailman class would look a lot simpler without the need for annotationspublic class mailman private string name private parcel parcel public mailmanstring name thisname name,['java'] +66383,how to reuse a thread in java i am a building a console sudoku solver where the main objective is raw speedi now have a managerthread that starts workerthreads to compute the neibhbors of each cell so one workerthread is started for each cell right now how can i reuse an existing thread that has completed its workthe thread pool pattern seems to be the solution but i do not understand what to do to prevent the thread from dying once its job has been completedps i do not expect to gain much performance for this particular task just want to experiment how multithreading works before applying it to the more complex parts of the codethanks,['java'] +66385,format string integer with leading zeros nsstring strname nsstring stringwithformatimg 00djpg ppand works fine but if pp took the value of 10 for example i wish have img 010jpg as result and not img 0010jpghow can i format the stringthanks,['objective-c'] +66396,how do i use css transformations to slide a div on screen my web page has two divs on it a and b div a is visible div b is hiddenwhen the user clicks a link in div a i want to slide div a off screen leaving via the left edge and slide div b on screen entering via the right edgei have found that jquery animations are very slow on the ipad so i want to use the webkit css animations instead which i believe are rendered in hardware how do i do this,['css'] +66398,how good is the rails sanitize method can i use actionviewhelperssanitizehelpersanitize on userentered text that i plan on showing to other users eg will it properly handle all cases described on this sitealso the documentation mentionsplease note that sanitizing userprovided text does not guarantee that the resulting markup is valid conforming to a document type or even wellformed the output may still contain eg unescaped aa aa aa characters and confuse browserswhats the best way to handle this pass the sanitized text through hpricot before thisplaying,['ruby-on-rails'] +66400,nonreentrant c timer i am trying to invoke a method f every t time but if the previous invocation of f has not finished yet wait until it is finishedi have read a bit about the available timers this is a useful link but could not find any good way of doing what i want save for manually writing it all any help about how to achieve this will be appreciated though i fear i might not be able to find a simple solution using timersto clarify if t is one second and f runs the arbitrary durations i have written below thenstep operation time taken1 wait 1s2 f 06s3 wait 04s because f already took 06 seconds4 f 10s5 wait 0s were late6 f 03s7 wait 07s we can thisregard the debt from step 4notice that the nature of this timer is that f will not need to be safe regarding reentrance and a thread pool of size 1 is enough here,['c#'] +66405,listview items not clickable with horizontalscrollview inside i have quite a complicated listview each item looks something like this linearlayout vertical linearlayout horizontal include horizontal linearlayout with two textviews include ditto include ditto textview horizontalscrollview this guy is my problem linearlayout horizontalin my activity when an item is created getview is called i add dynamic textviews to the linearlayout inside the horizontalscrollview besides filling the other simpler stuff out amazingly performance is pretty goodmy problem is that when i added the horizontalscrollview my list items became unclickable they do not get the orange background when clicked and they do not fire the onitemclickedlistener i have set up to do a simple logd callhow can i make my list items clickable againedit setting androiddescendantfocusabilityblocksdescendants on the topmost linearlayout seems to work i would like to know if there are other ways though what if i want focusable items in my list items,['android'] +66409,python floating number i am kind of confused why python add some additional decimal number in this case please help to explain mylist list item 1 2 314 print mylist list item 1 2 31401,['python'] +66414,how to assert on number of html table rows in ruby using capybara cucumber i am trying to get to grips with bdd web development in ruby using cucumber capybara and i am stuck at what should be an easy task just to check the number of rows in a table the intention of what i am trying to achieve is something along the lines ofpageshould have xpathtableidmytablefindtableidmytabletrlengthshould 3but this does not work missing method length and i cannot find a way to assert against the table lengthany ideas anyone please be easy on me tho i am a ruby noobythanks in advanceneil,['ruby'] +66426,is it allowed to load swing classes in nonedt thread after the introduction of java memory model the swing guidelines were changed to state that any swing components need to be instantiated on the edt in order to avoid nonpublished instance state what i could not find anywhere is whether the classloading is also mandated to be on the edt or can we preload key swing classes in a background thread is there any official statement from sunoracle on this are there any classes that are known to hold nonthreadsafe static state hence need to be loaded on edt clarification to address nemis question this is a practical issue a sizable portion of our applications startup time is spent classloading and fontimageloading on the edt most of this can be attributed to swing and related libraries here is som background as many other swing apps on startup we are preconstructing many forms in order to make the ui more responsive after profiling we found that the actual time for form construction is relatively fast whats slow is loading of all classes and fonts thisk reads are slow in corporate setup with onaccess virus scanner surveilance scanner audit tracker and god knows what else tacked on the hdd driver we tried to construct the same forms in a background thread violating swings rules and then throw them away once we are done we construct the same forms on the edt which is much faster as all classes are loaded and any other files are in the thisk cache it works for us and well probably keep doing it unless something really bad happens what i am asking is whether this is a safe practice a good practice or a hack,['java'] +66434,redirect all routing errors to root url of the application for example typing localhost30absurdnonexistingroutehow do i get invalid routes to point to the main page of the application in rails,['ruby-on-rails'] +66454,how to use google calendar api in android hi all i am new to android i parsed the calendar file i need to add events to google calendar from my application i am using eclipse ide in eclipse how to use the google calendar api any jar file is needed to use the calendar api,['android'] +66461,parallelism in python what are the options for achieving parallelism in python i want to perform a bunch of cpu bound calculations over some very large rasters and would like to parallelise them coming from a c background i am familiar with three approaches to parallelismmessage passing processes possibly thistributed across a cluster eg mpiexplicit shared memory parallelism either using pthreads or fork pipe et alimplicit shared memory parallelism using openmpdeciding on an approach to use is an exercise in tradeoffsin python what approaches are available and what are their characteristics is there a clusterable mpi clone what are the preferred ways of achieving shared memory parallelism i have heard reference to problems with the gil as well as references to tasklets in short what do i need to know about the different parallelization strategies in python before choosing between them,['python'] +66463,html5 audio player jquery toggle click playpause i wonder what i am doing wrong player audioclickfunction if player audiopaused false player audiopause alertmusic paused else player audioplay alertmusic playing i cannot seem to start the audio track if i hit the player audio tagdiv classthumb audioaudio classplayer audio srcpathvalueaudiodivany idea what i am doing wrong or what i have to do to get it working,['jquery'] +66477,what does double mean in c possible duplicatec newbie whats the difference between bool and bool hi while reading the code of the nunit projects assert class i came across this particular construct public static void areequaldouble expected double actual double delta assertdoublesareequalexpected doubleactual delta null nullin this function the second input parameter is entered as doublethe interesting thing is that this code compiles without issue in vs2010 c 40 anyone know why this is not throwing an error why is double considered a valid keyword and is there any special significance to the,['c#'] +66481,java ssh2 libraries in depth trileadganymedorion other i have been searching for a pure java ssh library to use for a project the single most important needed feature is that it has to be able to work with commandline git but remotecontrolling commandline tools is also importanta pretty common choice eg used in the intellij idea git integration which works very well seems to be trilead ssh2 looking at their website it is not being maintained any moretrilead seems to have been a fork of ganymed ssh2 which was a eth zurich project that did not see releases for a while but had a recent release by its new owner christian plattnerthere is another actively maintained fork from that code base orion ssh that saw an even more recent release but which seems to get mentioned online much less than the other 2 forkshas anybody here worked with any of or if possible both of ganymed and orion and could kindly describe the development experience with eitherbothaccuracy of documentation existence of documentation stability buggyness all of these would be highly interesting to me performance is not so important for my current projectif there is another purejava ssh implementation that should be used instead please feel free to mention it but please do not just mention a namedescribe your judgment from actual experiencesorry if this question may seem a bit do my homeworky but i have really searched for reviews everything out there seems to be either a listing of implementations or short use this it is great snippets,['java'] +66494,interview question any vs if length 0 for testing if a collection has elements in a recent interview i was asked what the difference between any and length 0 was and why i would use either when testing to see if a collection had elementsthis threw me a little as it seems a little obvious but feel i may be missing somethingi suggested that you use length when you simply need to know that a collection has elements and any when you wish to filter the resultspresumably any takes a performance hit too as it has to do a loop query internally,['c#'] +66497,why do a1 and a1 give different results when a is an int array int main int a1234567890 printfa u a unaa printfa1 u a1 una1a1how a and a are internally interpreted,['c'] +66505,how to get the fields in an object via reflection i have an object basically a vo in java and i do not know its typei need to get values which are not null in that object how can this be done,['java'] +66511,which cross platform preprocessor defines win32 or win32 or win32 i often see win32 win32 or win32 i assume that this depends on the used preprocessor either one from visual studio or gcc etcdo i now have to check first for os and then for the used compiler we are using here g 44x visual studio 2008 and xcode which i assume is a gcc again and atm we are using just win32 apple and linux,['c++'] +66516,auto resize text font size when resizing window i have been tryingin vain to build a page whose elements would resize as i changed the window size i have it working in css for images no problem but i cannot seem to accomplish the same for text and i am not sure it is even possible in css and i cannot seem to find a jquery script that accomplishes thiswhen a user resizes the window i essentially want the page to scale dynamically and fluidly without the user having to invoke page zoom this works fine on my img divs via css but not for the text which stays the same sizeany ideas,"['jquery', 'css']" +66518,qt qpushbutton text formatting i have a qpushbutton and on that i have a text and and icon i want to make the text on the button to be bold and red looked at other forums googled and lost my hope seems there is no way to do that if the button has an icon of course if you do not creat a new icon wich is textformer icon is that the only way anyone has a better idea,['c++'] +66537,is assignment of bracedinitlist to an array correct the standard says under 5179a bracedinitlist may appear on the righthand side of an assignment to a scalar an assignment defined by a userdefined assignment operator while in gcc 451pre9 i can compile this using stdc0x not stdgnu0xinclude iostreamint main int test 123 stdcout test0 test1 test2 test 456 stdcout test0 test1 test2 stdendland it prints 123456 is gcc correct here,['c++'] +66544,uiviewcontroller with background image how can i insert into my uiviewcontroller an image from the resources as background imagethanks in advance,['iphone'] +66548,android how to stretch an image to the screen width while maintaining aspect ratio i want to download an image of unknown size but which is always roughly square and thisplay it so that it fills the screen horizontally and stretches vertically to maintain the aspect ratio of the image on any screen size here is my nonworking code it stretches the image horizontally but not vertically so it is squashedimageview mainimageview new imageviewcontext mainimageviewsetimagebitmapmainimage downloaded from server mainimageviewsetscaletypescaletypefit xy mainimageviewsetadjustviewboundstrue with this line enabled just scales image down addviewmainimageviewnew linearlayoutlayoutparams layoutparamsfill parent layoutparamsfill parent,"['java', 'android']" +66559,systemdrawing bad text rendering using drawstring on top of transparent pixels when rendering text into a bitmap i find that text looks very bad when rendered on top of an area with nonopaque alpha the problem is progressively worse as the underlying pixels become more transparent if i had to guess i would say that when underlying pixels are transparent the text renderer draws any antialiased gray pixels as solid blackhere are some screenshotstext drawn on top of transparent pixelstext drawn on top of semitransparent pixelstext drawn on opaque pixelshere is the code used to render the text gsmoothingmode smoothingmodehighquality gdrawstringpress the spacebar font brushesblack textleft texttop,['c#'] +66577,oneway flight trip problem you are going on a oneway indirect flight trip that includes billions an unknown very large number of transfers you are not stopping twice in the same airport you have 1 ticket for each part of your trip each ticket contains src and dst airport all the tickets you have are randomly sorted you forgot the original departure airport very first src and your destination last dstdesign an algorithm to reconstruct your trip with minimum bigo complexityattempting to solve this problem i have started to use a symmetric difference of two sets srcs and dsts1sort all src keys in array srcs 2sort all dst keys in array dsts 3create an union set of both arrays to find nonduplicates they are your first src and last dst 4now having the starting point traverse both arrays using the binary searchbut i suppose there must be another more effective method,['c'] +66588,how to accommodate for the iphone 4 screen resolution according to apple the iphone 4 has a new and better screen resolution35inch diagonal widescreen multitouch thisplay 960by640pixel resolution at 326 ppithis little detail affects our apps in a heavy way most of the demo apps on the net have one thing in common they position views in the believe that the screen has a fixed size of 320 x 480 pixels so what most if not all developers do is they designed everything in such a way that a touchable area is for example 50 x 50 pixels big just enough to tap it things have been positioned relative to the upper left to reach a specific position on screen let us say the center or somewhere at the bottomwhen we develop highresolution apps they probably would not work on older devices and if they do they would suffer a lot from 4times the size of any image having to scale them down in memory,['iphone'] +66618,returnconsume dynamic anonymous type across assembly boundaries the code below works great if the get and use methods are in different assemblies the code fails with a runtimebinderexception this is because the net runtime system only guarantees commonality of anonymous types string int in this case within assemblies is there any way to fool the runtime system to overcome this i can inspect the object in the debugger on the use side and the debugger can see the relevant propertiesclass program static void mainstring args useperson consolereadline public static void useperson var person getperson consolewritelinepersonname public static dynamic getperson return new name foo age 30,"['c#', '.net']" +66622,can a lambda expression be passed as function pointer i am trying to pass a lambda expression to a function that takes a function pointer is this even possiblehere is some sample code i am using vs2010include iostreamusing namespace stdvoid funcint icout iv been called i endlvoid fptrfuncvoid fptrint i int jfptrjint main fptrfuncfunc10 this is ok fptrfuncint icout lambda call i endl 20 does not compile return 0,['c++'] +66639,android browse sqlite database on phone how can i browse the sqlite database that i am creating in my app on my android mytouch phonewhen i log in through adb shell sqlite3 gives me a permission denied is there another way to check if my database and tables are actually being created and if rows are being insertedi am not able to use the emulator since it does not play videos etc very well that is the main feature of my app so i can only test on phonethankschris,['android'] +66642,function that converts hex color values to an approximate color name i do not suppose anyone knows of a function php preferably that can take a hex color code and give an approximate color name for that hex value i do not need a solution with 100s of colors even if it just amounted to the colors white black red green blue brown orange and yellow i would be pretty well in shapeif you do not know of an existing resource does anyone know of a good way to approach this problemthanks in advance for the help,['php'] +66646,can you open a form or window in an outlook addin vsto i am new to vsto programming i have created a basic addin for outlook 2007 that monitors a folder containing xml text files which it opens and then sends them as an email then deletes them this all works finei want the user to be able to configure certain settings for the way the addinprogram will operate such as the folder that it will monitor and other things the logical way to do this is to create a menu item in the addin which i have also done that opens a windows form or xaml window that allows them to enter the parametersin my addin i added a new item windows form which worked and the designer opened however in my addin code i cannot open the form the show method normally associated with form objects is not availableis this simply something you cannot do or am i just doing it the wrong wayi have read about outlook form regions but these seemed to be attached to outlook items such as a new email task appointment etc there doesnt seem to be a way to create a form region that can be opened in the main window of outlookideally i would like to go with my original method of opening a new window from a menu item but if this isnt possible i would like to hear other solutionsthankswill,['c#'] +66660,jquery what is it forbidden to do in plain javascript a jquery best practices questioni am writing a very jquery intensive web page i am new to jquery and notice its power but as i come with heavy javascript experience and knowledge my question is what should be done in jquery and what in plain javascriptfor example there are callbacks that send a plain dom object as an argument should i use that or should i wrap it like thisdoes it matter if i do thisxy or thisattrx y,"['javascript', 'jquery', 'html']" +66663,accessing html 5 video progress event with jquery the below is for an html5 video player eventmy partner and i have been stumped for a very large portion of the day on this issue and hope someone can lend some insight on the issue we have been able to access the progress event with plain js as seen below but when trying to access this with jquery we get undefined in console any help recommendations are greatly appreciated js works like a charmdocumentaddeventlistenerdomcontentloaded init falsefunction init var v documentgetelementbyidtestvid consolelogv vaddeventlistenerprogress progress falsefunction progresse consolelogelengthcomputable etotal eloaded jquery no bueno undefined rendered in console var vid testvid vidbindprogress functione consolelogetotal eloaded elengthcomputable thanks in advancejn,"['javascript', 'jquery']" +66681,possible to view php code of a website is it possible to somehow view another websites php filescodesor to rephrase the question can my php codes be viewed by anybody except for those who have access to the fileif so how can i best prevent thisps server os is ubuntu 910 and php version is 5 apache2,"['php', 'html']" +66689,svg to jpg png is there any working module to convert a svg image into a pixel format like jpeg or png,['php'] +66699,how to find the row id from datagridview given a row value can anyone help me please i have to find the row number from 1 selected array which i stored in one separate array and randomly i am trying to get the row number from datagridviewin other wordsif i know a column value for a given row in a datagridview eg for this row firstname bud how can i get the row id,['c#'] +66707,what is the difference between a module and a script in python think the title summarizes the question,['python'] +66742,curl init undefined i am importing the contacts from gmail to my page the process does not work due to this error curl init is not definedthe suggestion i got is to uncomment destination curldll copy the following libraries to the windowssystem32 dir ssleay32dll and libeay32dllcopy php curldll to windowssystem32after trying all these i refreshed my xampp but even then error occursthis is my page where i am trying to import the gmail contactsphpresource curl init string url null ch curl initcurl setoptch curlopt url curl setoptch curlopt header 0curl execchcurl closechphpecho hiif postsubmit echo hi clientlogin url clientlogin post array accounttype hosted or google email postemail echo passwd postpasswd service cp source tutsmore12 curl curl initclientlogin url curl setoptcurl curlopt post true curl setoptcurl curlopt postfields clientlogin post curl setoptcurl curlopt httpauth curlauth any curl setoptcurl curlopt ssl verifypeer false curl setoptcurl curlopt returntransfer 1 response curl execcurl preg matchauthaz09 i response matches auth matches1 headers arrayauthorization googlelogin auth auth curl curl init curl setoptcurl curlopt httpheader headers curl setoptcurl curlopt returntransfer 1 feed curl execcurl echo contactscontactsarray docnew domdocument if emptyfeed docloadhtmlfeed xpathnew domxpathdoc queryentry dataxpathqueryquery foreach data as node entry nodesnodechildnodes temparrayarray foreachentry nodes as child domnodesnamechildnodename switchdomnodesname case title temparrayfullnamechildnodevalue break case email if strposchildgetattributerelhomefalse temparrayemail 1childgetattributeaddress elseifstrposchildgetattributerelworkfalse temparrayemail 2childgetattributeaddress elseifstrposchildgetattributerelotherfalse temparrayemail 3childgetattributeaddress break if emptytemparrayemail 1contactstemparrayemail 1temparray ifemptytemparrayemail 2 contactstemparrayemail 2temparray ifemptytemparrayemail 3 contactstemparrayemail 3temparray foreachcontacts as keyval echo keybr else form actionphp self methodpost table tr tdemailtdtdinput typetext nameemail td tr tr tdpasswordtdtdinput typepassword namepasswd td tr trtd colspan2 aligncentertutsmore do not save your email and password trust ustdtr trtd colspan2 aligncenterinput typesubmit namesubmit valueget contacts tdtr tableform phpthis code is completely provided for debugging if any optimization is needed i will try to optimize the code,['php'] +66748,the importance of knowing c for web application development i am a php developer and i want to broaden my knowledge base by learning a higher language java c c my specialty is in building web applications ria etc i am trying to think of the appropriate path to take hedging my bets so to speak in terms of which language i should be focusing on i love open source technology but at the same time c seems to be getting a lot of notoriety despite the newer technologies available there still remains c which is the staple for many popular vendors including google and facebook hip hop in building scalable and robust cross platform appscan anyone offer suggestions as to how i should be looking at this should i go java c or c they all take time to master and i just want to choose a specialtythanks,"['c#', 'java', 'c++']" +66766,java assigning object reference ids for custom serialization for various reasons i have a custom serialization where i am dumping some fairly simple objects to a data file there are maybe 510 classes and the object graphs that result are acyclic and pretty simple each serialized object has 1 or 2 references to another that are serialized for exampleclass foo final private long id public foolong id other stuff class bar final private long id final private foo foo public barlong id foo foo other stuff class baz final private long id final private listbar barlist public bazlong id listbar barlist other stuff the id field is just for the serialization so that when i am serializing to a file i can write objects by keeping a record of which ids have been serialized so far then for each object checking whether its child objects have been serialized and writing the ones that have not finally writing the object itself by writing its data fields and the ids corresponding to its child objectswhats puzzling me is how to assign ids i thought about it and it seems like there are three cases for assigning an iddynamicallycreated objects id is assigned from a counter that incrementsreading objects from thisk id is assigned from the number stored in the thisk filesingleton objects object is created prior to any dynamicallycreated object to represent a singleton object that is always presenthow can i handle these properly i feel like i am reinventing the wheel and there must be a wellestablished technique for handling all the casesclarification just as some tangential information the file format i am looking at is approximately the following glossing over a few details which should not be relevant it is optimized to handle a fairly large amount of dense binary data tenshundreds of mb with the ability to intersperse structured data in it the dense binary data makes up 9 of the file sizethe file consists of a series of errorcorrected blocks which serve as containers each block can be thought of as containing a byte array which consists of a series of packets it is possible to read the packets one at a time in succession eg it is possible to tell where the end of each packet is and the next one starts immediately afterwardsso the file can be thought of as a series of packets stored on top of an errorcorrecting layer the vast majority of these packets are opaque binary data that has nothing to do with this question a small minority of these packets however are items containing serialized structured data forming a sort of archipelago consisting of data islands which may be linked by object reference relationshipsso i might have a file where packet 2971 contains a serialized foo and packet 12083 contains a serialized bar that refers to the foo in packet 2971 with packets 02970 and 297212082 being opaque data packetsall these packets are all immutable and therefore given the constrains of java object construction they form an acyclic object graph so i do not have to deal with mutability issues they are also descendents of a common item interface what i would like to do is write an arbitrary item object to the file if the item contains references to other items that are already in the file i need to write those to the file too but only if they have not been written yet otherwise i will have duplicates that i will need to somehow coalesce when i read them back,['java'] +66777,thistinguishing between net exception types for the love of all things holy how do you thistinguish between different exception flavors within the predefined net exception classesfor example a piece of code might throw an xmlexception under the following conditionsthe root element of the document is nullinvalid chars are in the documentthe document is too longall of these are thrown as xmlexception objects and all of the internal tell me more about this exception fields such as exceptionhresult exceptiondata etc are usually empty or nullthat leaves exceptionmessage as the only thing that allows you to thistinguish among these exception types and you cannot really depend on it because you guessed it the exceptionmessage string is glocabilized and can change when the culture changes at least that is my read on the documentationexceptionhresult and exceptiondata are widely ignored across the net libraries they are the redheaded stepchildren of the worlds net errorhandling code and even assuming they werent the hresult type is still the worst downright nastiest error code in the history of error codes why we are still looking at hresults in 2010 is beyond me i mean if youre doing interop or pinvoke that is one thing but hresults have no place in systemexception hresults are a wart on the proboscis of systemexceptionbut seriously it means i have to set up a lot of detailed specific errorhandling code in order to figure out the same information that should have been passed as part of the exception data exceptions are useless if they force you to work like this what am i doing wrongedit a day laterthanks for all the comments and responses i am learning a general lesson here error messages suck even if i have not quite solved the specific problem heres the specific scenario i am deaing withour application consumes xml files produced by a third party these xml files sometimes contain illegal characters that really have no business being in an xml file these illegal chars cause a validating xmlreader to blow up with an illegal char on line x exception we have to process these files however we cannot simply tell the user sorry that file does not conform to the official xml spec our users do not even really know what xml ismicrosoft has an official and quite strange to me recommendation in this case the case where an xml document contains illegal characters to load the file into a stream iterate to the specific line containing the error as provided ironically in the xmlexception object and to customreplace the offending char with a legal one then try loading the doc into the validating xmlreader again and seeing if it blows up heres the knowledge base article describing the techniqueso fine were doing that and it works well enough the problem is that sometimes these xml files we get are malformed in other ways they might be empty they might be missing a closing tag etc so if you follow the ms recommendation youre actually hooking your replace illegal chars logic into the catch block where you catch the original exception thrown by the validating readerthat is fine if the exception is in fact an illegal char exception but if it is a root element missing or missing closing tag exception you find that the ms technique to go in and replace the offending char itself blows up because not only is there not an offending char there are no chars at all or there are but they are invalidlyformed xml or whatever at this point youre in a doublynested catchinsideacatch your hairs turning gray and falling out your eyes are crimson red with caffeine fatigue and youre questioning the sanity let alone the utility of using validating readers against realworld xmlso what i need is a way of telling in that initial catchxmlexception block whether this is a root element missing or a invalid char exception so i can take the appropriate action one thing we cannot do is prevent our users to open a document that contains a few invalid chars we have to process those documents regardless and i guess it is looking like the only solution is to iterate through every char in the document ahead of time viewing it as a text stream rather than as xml find the illegal chars replace them then load the thing with the validating xmlreader and if it blows up we know it is not an illegal char exception because we stripped illegal chars beforehandbefore doing that i thought i would at least ask 1 can we get better information out of the xmlexception object and i was hoping somebody would tell me 2 it is okay to key off the xmlexceptionmessage string they say it is localized but it is not really this string will be the same across all versions and cultures of windowsbut nobody has told me that,['.net'] +66783,xdocument containing namespaces i have the following xml which i am trying to query with xdocumente2etraceevent xmlns system xmlns eventid589828eventid type3type subtype nameinformation0subtype level8level timecreated systemtime20100601t0945158102117z source namesystemservicemodel correlation activityid0 execution processnamew3wp processid5012 threadid5 channel computertestserver3acomputer system applicationdata tracedata dataitem tracerecord xmlns severityinformation traceidentifiertraceidentifier descriptionwebhost compilationdescription appdomainlmw3svc257188508root1129198591101343437appdomain sourcesystemservicemodelactivationserviceparser39498779source extendeddata xmlns virtualpathservicesvcvirtualpath extendeddata tracerecord dataitem tracedata applicationdatae2etraceeventexecuting the following code returns null for xel1 except when i manually remove the namespacesxdocument xdoc xdocumentparsecurrentstringxelement xel1 xdocelemente2etraceeventxelement xel2 xel1elementsystemxelement xel3 xel2elementcorrelationxattribute xatt1 xel3attributeactivityidstring svalue xatt1valuehow do you write code to extract the guid in xdocument,['c#'] +66786,how to update attributes without validation i have got a model with its validations and i found out that i cannot update an attribute without validating the object beforei already tried to add on create syntax at the end of each validation line but i got the same resultsmy announcement model have the following validations validates presence of title validates presence of description validates presence of announcement type id validate validates publication date validate validates start date validate validates start end dates validate validates category validate validates province validates length of title in 6255 on save validates length of subtitle in 0255 on save validates length of subtitle in 0255 on save validates length of place in 050 on save validates numericality of vacants greater than or equal to 0 only integer true validates numericality of price greater than or equal to 0 only integer truemy rake task does the following task announcements expiration environment do announcements announcementexpired announcementseach do a gets the user that owns the announcement user userfindauser id puts atitle astate deactivated if aupdate attributesstate astate puts state changed to deactivated else aerrorseach do e puts e end end endthis throws all the validation exceptions for that model in the outputdoes anybody how to update an attribute without validating the model,['ruby-on-rails'] +66792,does python work in larger teams i read this post last night and it got me thinking i like python and batteries pypi and such but i have only done python solo never tried it in a teamare the points that ted mentions valid if they are how do teams cope with them does python work in teams or even large teams or it kills productivityi personally see the problems he mentions when i come back to my old code even when working with other modules sometimes i need to peek inside i would like to hear people with experience on this,['python'] +66801,httpurlconnection getting locked i have a thread running under tomcat which creates a httpurlconnection and reads it through bufferedinputstreamafter fetching data for some urls it stalls i got the jstack of the process which says httpurlconnection is locked and bufferedinputstream is also lockedhttp80801 daemon prio10 tid0x08683400 nid0x79c9 runnable 0x8f6180 javalangthreadstate runnable at javanetsocketinputstreamsocketread0native method at javanetsocketinputstreamreadsocketinputstreamjava129 at javaiobufferedinputstreamfillbufferedinputstreamjava218 at javaiobufferedinputstreamread1bufferedinputstreamjava258 at javaiobufferedinputstreamreadbufferedinputstreamjava317 locked 0x956ef8c0 a javaiobufferedinputstream at sunnetwhttphttpclientparsehttpheaderhttpclientjava687 at sunnetwhttphttpclientparsehttphttpclientjava632 at sunnetwprotocolhttphttpurlconnectiongetinputstreamhttpurlconnectionjava1072 locked 0x956ef910 a sunnetwprotocolhttphttpurlconnectioncould somebody help herethanks,['java'] +66804,any success with sinatra working together with eventmachine websockets i have been using sinatra for sometime now and i would like to add some realtime features to my webapp by pushing the data via websocketsi have successfully used the gem emwebsocket on its own but have not been able to write one ruby file that has a sinatra web server and a websocket serveri have tried spinning the run or start methods off in separate threads with no successhas anyone gotten this to worki want to have them in the same file as i can then share variables between the two serversthanks,['ruby'] +66806,unit tests architecture question so i have started to layout unit tests for the following bit of codepublic interface myinterface void myinterfacemethod1 void myinterfacemethod2public class myimplementation1 implements myinterface void myinterfacemethod1 do something void myinterfacemethod2 do something else void subroutinep other functionality specific to this implementation public class myimplementation2 implements myinterface void myinterfacemethod1 do a 3rd thing void myinterfacemethod2 do something completely different void subroutineq other functionality specific to this implementation with several implementations and the expectation of more to comemy initial thought was to save myself time rewriting unit tests with something like thispublic abstract class myinterfacetester protected myinterface m object setup public void setup m object gettestedimplementation public abstract myinterface gettestedimplementation test public void testmyinterfacemethod1 use m object to run tests test public void testmyinterfacemethod2 use m object to run tests which i could then subclass easily to test the implementation specific additional methods like sopublic class myimplementation1tester extends myinterfacetester public myinterface gettestedimplementation return new myimplementation1 test public void testsubroutinep use m object to run tests and likewise for implmentation 2 onwardsso my question really is is there any reason not to do this junit seems to like it just fine and it serves my needs but i have not really seen anything like it in any of the unit testing books and examples i have been readingis there some best practice i am unwittingly violating am i setting myself up for heartache down the road is there simply a much better way out there i have not consideredthanks for any help,['java'] +66832,best way to save to nsuserdefaults for custom class if i have a custom class person which has three variables which are propertized and synthesizednsstring thenamefloat theheightint theageperson instances are stored in an nsarray group there is only one group what is the best way of storing and loading the group in nsuserdefaults bearing in mind that float and int are not legal for nsuserdefaults,"['iphone', 'objective-c']" +66836,whats the most straightforward way in php to create an associative array from two parallel indexed arrays given the following two indexed arraysa arraya b cb arrayred blue greenwhat is the most straighforwardefficient way to produce the following associative arrayresult i want arraya red b blue c greenthanks,['php'] +66839,why are stack and queue implemented with an array i am reading c 40 in a nutshell by the albahari brothers and i came across thisstacks are implemented internally with an array that is resized as required as with queue and list pg 288 paragraph 4i cannot help but wonder why linkedlist provides o1 head and tail inserts and deletes which should work well for a stack or queue a resizable array has o1 amortized insert if i remember right but on worst case i am not sure about delete and it probably uses more space than the linked list for large stacksqueuesis there more to it than that what is the downside to a doubly linked list implementation,"['c#', '.net']" +66840,is there commons annotationutils like library java i cannot find a general utilities static methods library for querying for annotations other than either using the annotations api directly and writing my own or using springssprings annotation utilsnormally i would not mind using springs but its a rather big dependency just for dealing with annotations maybe commons lang will have annotationutils some daywhat are people using to query for annotations,['java'] +66858,how to detect client timezone any ideas how to get clientrequest timezone in jsp,"['java', 'javascript']" +66881,include in h or c cpp when coding in either c or c where should i have the includescallbackhifndef callback h define callback h include sndfilehinclude mainhvoid on button apply clickedgtkbutton button struct user data s datavoid on button cancel clickedgtkbutton button struct user data s dataendifcallbackcinclude stdlibhinclude mathhinclude confighinclude callbackhinclude playhvoid on button apply clickedgtkbutton button struct user data s data gint page page gtk notebook get current pagegtk notebookdatanotebook should all includes be in either the h or c cpp or both like i have done here,"['c++', 'c']" +66906,how can i match on but exclude a regex pattern i have this url 1aspxcid876xyz964d293cfsnaptruejlkjkjhkjhand this regex patterncidwhich produces this resultcid87b6xyz964d293cfhow do i remove the cidthanks,['javascript'] +66915,application start gets called more than once i have an application made on aspnet mvc 2 and it is on iis 75 on my pc i tried profiling it and i noticed that application start gets called more than onceanybody knows why is this happening,['asp.net'] +66921,whitespaces in classpath i am working on a windows pc and have cygwin on iti have organized all my jars under a directory within a few directoriesi am writing a bash script to set the classpath by iterating through the directory that is passed as a parameter as followsfor jar file in ls jardo classpathdirectory to look for jarsjar fileclasspathdonewhenever there are spaces in the directory that is passed like cygdrivecdocuments and settingsusermy jars and i run java cp classpath somepackagesomeclass it throws an error stating that the class and is not found because the classpath variable is getting split after cygdrivecdocumentscan someone help me to solve this issue,['java'] +66933,execute a default task in ant in case of failure i am currently using ant for building my java project on a windows xp machinein my buildxml file i have defined 3 task and i would like thatin case of faila default task be executed before closing the building and exiting like a recovery procedure i would like to know if it is possiblethanks,['java'] +66934,contravariant delegates value types can anyone shed light on why contravariance does not work with c value typesthe below does not workprivate delegate asset assetdelegateint minternal string dome assetdelegate aw new assetdelegatedelegatemethod aw32 return class1private static house delegatemethodobject m return null,['c#'] +66945,insert xml node before specific node using c this is my xml file employee name refa1 typexname name refa2 typeyname name refa3 typeznameemployeeusing c i need to insert this nodename refb2 typeanamebetween the a2 and a3 nodes any pointer how to sort this out,['c#'] +66946,what is the advantage of the srcmainjava convention i have noticed that a lot of projects have the following structureprojectabinlibsrcmainjavarootlevelpackageclassjavai currently use the following convention as my projects are 100 javaprojectabinlibsrcrootlevelpackageclassjavai am not currently using maven but am wondering if this is a maven convention or not or if there is another reason can someone explain why the first version is so popular these days and if i should adopt this new convention or notchris,['java'] +66959,2 basic but interesting questions about net when i first saw c i thought this must be some joke i was starting with programming in c but in c you could just drag and drop objects and just write event code to them it was so simplenow i still like c the most because i am very attracted to the basic low level operations and c is just next level of assembler with few basic routines so i like it very much even more because i write little apps for microcontrollersbut yesterday i wrote very simple control program for my microcontroller based led cube in asm and i needed some way to simply create animation sequences to the cube so i remembered c i have practically no c skills but still i created simple program to make animation sequences in about hour with gui just with help of google and help of the embedded function descriptions in c so to get to the point is there some other reason then top speed to use any other language than c i mean it is so effective i know that java is a bit of similar but i expect c to be more windows effective since its directly from microsoftthe second question is what is the advantage of compiling into cil and than run by clr than directly compile it into machine code i know that portability is one but since c is mainly for windows wouldna t it be more powerful to just compile it directly thanks,"['c#', '.net']" +66970,how to remove sub views i have added uibuttonuitextview as subview to my view programaticallynotesdescriptionview uiview allocinitwithframecgrectmake00320460notesdescriptionviewbackgroundcoloruicolor redcolorselfview addsubviewnotesdescriptionviewtextview uitextview alloc initwithframecgrectmake00320420 selfview addsubviewtextview printfn description button nbutton uibutton buttonwithtypeuibuttontyperoundedrectbutton addtargetself actionselectorcancel forcontroleventsuicontroleventtouchdownbutton settitleok forstateuicontrolstatenormalbuttonframe cgrectmake800 4200 1600 400selfview addsubviewbuttonhere if we click the button i need to remove the all the sub viewsi am tryingselfview removefromsuperviewbut its not workingany help,['objective-c'] +66986,how to check if a date object equals yesterday right now i am using this codecalendar cal calendargetinstancesimpledateformat sdf new simpledateformatymmddcalsetcalgetcalendaryear calgetcalendarmonth calgetcalendardate 1 12 0 0 sets calendar to yeserday 12amifsdfformatgetdatefromlinelineequalssdfformatcalgettime getdatefromline returns a date object that is always at 12pmcodethere is got to be a smoother way to check if the date returned by getdatefromline is yesterdays date only the date matters not the time that is why i used simpledateformatthanks for your help in advance,['java'] +66990,does google app engine supports jdbc i have heard the google app enginejava do not support jdbc and hibernate is it trueif yes then how do we access the database in google app engine also is there any basic sample application which can help me understand how to perform crud operations in gae,['java'] +67006,is it a bad programming practice to have public members inside an internal class wouldnt it be more specific and appropriate if i only keep protected internal and private members field method property event in a class which is declared as internali have seen this practice having public members in an internal class in various code so just wanted to know is it a bad practice or does it has some benefit or advantageonly concerned about cthanks for your interest,['c#'] +67017,should i use qt signalslot mechanisms over traditional callbacks a senior developer in my team used traditional cstyle callbacks in our qt application instead of using qt signalslot mechanisms my first reflex would be to replace his code and use qt signalslot insteadis there any good reasons to use callbacks in a qt applicationlibrarythanks,['c++'] +67019,xml comparison in python building on another so question how can one check whether two wellformed xml snippets are semantically equal all i need is equal or not since i am using this for unit testsin the system i want these would be equal note the order of startand endxml version10 encodingutf8 standaloneyesstats start1275955200 end1276041599stats reordered start and endxml version10 encodingutf8 standaloneyesstats end1276041599 start1275955200 statsi have lmxl and other tools at my thisposal and a simple function that only allows reordering of attributes would work fine as well working snippet based on ianbs answerfrom formencodedoctest xml compare import xml compare have to strip these or fromstring carpsxml1 xml version10 encodingutf8 standaloneyes stats start1275955200 end1276041599statsxml2 xml version10 encodingutf8 standaloneyes stats end1276041599 start1275955200statsxml3 xml version10 encodingutf8 standaloneyes stats start1275955200statsfrom lxml import etreetree1 etreefromstringxml1striptree2 etreefromstringxml2striptree3 etreefromstringxml3stripimport sysreporter lambda x sysstdoutwritex nassert xml comparetree1tree2reporterassert xml comparetree1tree3reporter is false,['python'] +67024,javascript check if anonymous object has a method how can i check if an anonymous object that was created as suchvar myobj prop1 no prop2 function return false does indeed have a prop2 definedprop2 will always be defined as a function but for some objects it is not required and will not be definedi tried what was suggested here but i do not think it works for anonymous objects,['javascript'] +67025,custom sort logic in orderby using linq what would be the right way to sort a list of strings where i want items starting with an underscore to be at the bottom of the list otherwise everything is alphabeticalright now i am doing something like thisautolistorderbya astartswith za a,"['c#', '.net']" +67026,determine if user navigated from mobile safari i have an app and i would like to redirect the users to different pages based on where they are navigating fromif navigating from web clip do not redirectif navigating from mobile safari redirect to safariaspxif navigating from anywhere else redirect to unavailableaspxi was able to use to determine if the user was navigating from a web clip but i am having trouble determining if the user navigated from mobile safari on an iphone or ipodheres what i haveif windownavigatorstandalone user navigated from web clip do not redirectelse if logic for mobile safari user navigated from mobile safari redirect to safari page windowlocation safariaspxelse user navigated from some other browser redirect to unavailable page windowlocation unavailableaspx,"['javascript', 'iphone']" +67069,user defined conversions in c recently i was browsing through my copy of the c pocket reference from oreilly media and i was surprised when i came across a brief section and example regarding userdefined conversion for userdefined typesinclude iostreamclass account private double balance public account double b balance b operator double void return balance int main void account acc10 double balance acc stdcout balance stdendl return 0i have been programming in c for awhile and this is the first time i have ever seen this sort of operator overloading the books description of this subject is somewhat brief leaving me with a few unanswered questions about this featureis this a particularly obscure feature as i said i have been programming in c for awhile and this is the first time i have ever come across this i have not had much luck finding more indepth material regarding thisis this relatively portable i am compiling on gcc 41can userdefined conversions to user defined types be done egoperator stdstring code,['c++'] +67078,jquery hover pass variable to callback function i am trying to remove a title attribute for a link on hover and then add it back on mouse out i would like to pass var hovertext to the hover outhere is the code i have any ideasicon ahoverfunction this this var hovertext datathis title thisattrtitle thisfindemanimateopacity show top 35 slow thisfindemtexthovertext thisremoveattrtitle functionhovertext thisfindemanimateopacity hide top 45 fast thisattrtitle hovertext,['jquery'] +67090,mysql friends table i have a mysql db in which i store data about each useri would like to add a list of friends for each user should i create a table of friends for each user in the db or is there a better way,['mysql'] +67103,flow 2 columns of text automatically with css i have the code similar to the followingpthis is paragraph 1 lorem ipsum ppthis is paragraph 2 lorem ipsum ppthis is paragraph 3 lorem ipsum ppthis is paragraph 4 lorem ipsum ppthis is paragraph 5 lorem ipsum ppthis is paragraph 6 lorem ipsum pi would like to without markup if possible cause this text to flow into two columns 13 on the left 46 on the right the reason for my hesitation to add a column using a div is that this text is entered by the client via a wysiwyg editor so any elements i inject are likely to be killed later or inexplicably,"['javascript', 'html', 'css']" +67108,php mysql javascript mindate and maxdate in net there are the static properties datetimemindate and datetimemaxdate that conveniently return the minimum and maximum valid dates for a datetime objecti am dabbling in web programming right now using php mysql javascript there does not seem to be the same convenient minmax date values in that programming environment for example the max value of a date object in mysql is 91231 but the php function strtotime does not like that value i would like a crosslanguage minimum date to be used to mean not set yet for example and a crosslanguage maximum date to be used to mean good forever that means there could be those min dates and max dates stored in a database which php would retrieve and it would have to differentiate between normal dates and minmax date and eventually they would trickle down to some javascript which again would have to differentiate between normal dates and minmax dateso which date value do you use for minmax dates when working in php mysql javascript and how do you store these constants it would be nice to define them only in one place and have them be available in each of php mysql javascriptthanks,"['php', 'javascript', 'mysql']" +67116,is there an easy way to setup the android emulator to access the lan of the host machine i would like to access a web service provided by one of the machines on my lan from the android emulatorif the service was running on the same machine where the emulator is running called host i could add a network redirection and access the 10022 host loopback interface in the emulator with the correct porthowever it is running on another machine on the lan i guess i could add another redirection on the host additionally to the above one would have to fight with iptables though but does a more simple solution exist,['android'] +67119,unsafe javascript attempt to access frame with url error being continuously generated in chrome webkit inspector chrome or any other webkit browser throws a ton of these unsafe javascript attempt to access frame with url when working with the facebook api for exampleit does not interfere with actual operation but it does make the javascript console basically unusablei would like to know if there is a way to suppress these errors specifically in the console or if there are other solutions you guys can think of i would really appreciate itthanks,['javascript'] +67130,forcing images to not wrap i cannot touch the html theme but i have access to the css filesdiv classphotos img srcajpg alt alignleft img srcbjpg alt alignleft img srccjpg alt alignleft align makes the images wrapdivunfortunately i cannot remove alignleft from the images otherwise this css snippet would have done the jobphotos whitespace nowrapphotos img thisplay inline verticalalign topany ideas is it even possible to make these images lineup horizontally without using the force of a table and only with cssmany thank in advance,"['html', 'css']" +67133,loop through an array in javascript in java you can use a for loop to traverse objects in an array as followsstring mystringarray hello worldfor string s mystringarray do somethingcan you do the same in javascript,['javascript'] +67152,clear javascript console in google chrome i was wondering if i could clear up the console with some commandconsolelog can print is there a command to clear up consolei have tried to consolelogconsole and got this functions below assert function assert native code constructor function console native code count function count native code debug function debug native code dir function dir native code dirxml function dirxml native code error function error native code group function group native code groupend function groupend native code info function info native code log function log native code marktimeline function marktimeline native code profile function profile native code profileend function profileend native code time function time native code timeend function timeend native code trace function trace native code warn function warn native code proto object i guess there is no way to clear up the console but i wanted someone to say it to me,['javascript'] +67157,download a file with defaulthttpclient and preemptive authentication after i had a lot of problems with preemptive authentication i got it finally workingnow the next problem i want to get a file with it but i do not know howi thought the file data might be in the variable response but it is notany ideas how this might work i am trying it since days without success basically i am trying to download an jpeg file which is on a server protected by prem auth basic auth licensed to the apache software foundation asf under one or more contributor license agreements see the notice file thistributed with this work for additional information regarding copyright ownership the asf licenses this file to you under the apache license version 20 the license you may not use this file except in compliance with the license you may obtain a copy of the license at unless required by applicable law or agreed to in writing software thistributed under the license is thistributed on an as is basis without warranties or conditions of any kind either express or implied see the license for the specific language governing permissions and limitations under the license this software consists of voluntary contributions made by many individuals on behalf of the apache software foundation for more information on the apache software foundation please see httpclient new defaulthttpclient httpclientgetcredentialsprovidersetcredentials new authscopehost port new usernamepasswordcredentialsusername password generate basic scheme object and stick it to the local execution context basichttpcontext localcontext new basichttpcontext basicscheme basicauth new basicscheme localcontextsetattributepreemptiveauth basicauth first request interceptor httpclientaddrequestinterceptornew preemptiveauth 0 httphost targethost new httphosthost port http httpget httpget new httpget httpget httpget new httpgethttpurl systemoutprintlnexecuting request httpgetgetrequestline httpresponse response httpclientexecutetargethost httpget localcontext httpentity entity responsegetentity systemoutprintln systemoutprintlnresponsegetstatusline,['android'] +67161,how to add a method to an existing class in php i am using wordpress as a cms and i want to extend one of its classes without having to inherit from another class ie i simply want to add more methods to that classclass a function do a echo a thenfunction insert this function into class a echo bsome way of inserting the latter into a classandainsert this function into class a bis this even possible in tenacious php,['php'] +67164,initialize pointer through function i was browsing my teachers code when i stumbled across thisorder order1 nullthenorder1 ordercustomer1 product2which calls order ordercustomer customer product product return new ordercustomer productthis looks like silly code i am not sure why but the teacher initialized all pointers to null instead of declaring them right awaylooking at the code it is entirely possible but he chose not tomy question is is this good or acceptable code does the function call have any benefits over calling a constructor explicitely and how does new work in this case can i imagine the code now as kind of likeorder1 new ordercustomer product,['c++'] +67167,how do i add an extra separator to the top of a uitableview i have a view for the iphone that is basically split in two with an informational thisplay in the top half and a uitableview for selecting actions in the bottom half the problem is that there is no border or separator above the first cell in the uitableview so the first item in the list looks funny how can i add an extra separator at the top of the table to separate it from the thisplay area above itheres the code to build the cells it is pretty straightforward the overall layout is handled in a xib uitableviewcell tableviewuitableview tableview cellforrowatindexpathnsindexpath indexpath static nsstring cellidentifier cell uitableviewcell cell tableview dequeuereusablecellwithidentifiercellidentifier if cell nil cell uitableviewcell alloc initwithstyleuitableviewcellstyledefault reuseidentifiercellidentifier autorelease cellaccessorytype uitableviewcellaccessorythisclosureindicator switchindexpathrow case 0 celltextlabeltext action 1 break case 1 celltextlabeltext action 2 break etc return cell,"['iphone', 'objective-c']" +67182,any suggestion for mobile datepicker i am building mobile widget based on javascript and html for which i need a calendar module build on javascript i tried ui datepicker but its quite slow when runs on phone any suggestion is going to help me alot,['javascript'] +67189,how to get pids that are using given file name in c how to get pids of processes that are using a given file name and mutex namenot by custom kernel driver but in c in user modeupdate thanks to daniel renshaw i found a script that lists all handles with pids using a not undocumented and unfrozen functions,['c#'] +67194,when where and how can i change the class attr of an object in python i would like to be able to do class astr pass b a b class strtraceback most recent call last file stdin line 1 in moduletypeerror class assignment only for heap types,['python'] +67199,android dealing with a dialog on screen orientation change i am overriding the oncreatedialog and onpreparedialog methods or the dialog classi have followed the example from reto meiers professional android application development book chapter 5 to pull some xml data and then use a dialog to thisplay the infoi have basically followed it exactly but changed the variables to suit my own xml schema as followsoverridepublic dialog oncreatedialogint id switchid case settings dialog layoutinflater li layoutinflaterfromthis view settingsdetailsview liinflaterlayoutdetails null alertdialogbuilder settingsdialog new alertdialogbuilderthis settingsdialogsettitleprovisioned settings settingsdialogsetviewsettingsdetailsviewreturn settingsdialogcreate return nulloverridepublic void onpreparedialogint id dialog dialog switchid case settings dialog string afpuntext ifsettinggetaddforpublicusernames 1 afpuntext yes else afpuntext no string text login settings n password settinggetpassword n server settinggetserveraddress n alertdialog settingsdialog alertdialogdialog settingsdialogsettitlesettinggetusernametv textviewsettingsdialogfindviewbyidriddetailstextviewif tv null tvsettexttext break it works fine until i try changing the screen orientation when i do this onpreparedialog gets call but i get null pointer exceptions on all my variablesthe error still occurs even when i tell my activity to ignore screen orientation in the manifestso i presume something has been left out of the example in the book do i need to override another method to save my variables in or somethingi have now added the followingoverridepublic void onsaveinstancestatebundle savedinstancestate save ui state changes to the savedinstancestate this bundle will be passed to oncreate if the process is killed and restarted savedinstancestateputstringusername settinggetusername savedinstancestateputstringpassword settinggetpassword savedinstancestateputstringserver settinggetserveraddress superonsaveinstancestatesavedinstancestateoverridepublic void onrestoreinstancestatebundle savedinstancestate superonrestoreinstancestatesavedinstancestate settingsclear restore ui state from the savedinstancestate this bundle has also been passed to oncreate username savedinstancestategetstringusername password savedinstancestategetstringpassword serveraddress savedinstancestategetstringserversettings setting new settingsusername password serveraddressaddnewsettingssettingbut i am still getting the null pointer exception,['android'] +67215,dependency injection scoping by region guice spring whatever heres a simplified version of my needsi have a program where every b object has its own c and d object injected through guice in addition an a object is injected into every c and d objects what i want that for each b object its c and d objects will be injected with the same a object editstart1 guice supports singleton and prototype modes however what i need is something in between i need a to be singleton wrt to a given b object so that the c and d injected into a b object will share an a object for another b object i want another a so it is a singleton but for a limited scope of the program actually a limited scope of a data structure2 i do not mind a solution that uses method setter or field injection3 i tried several times to achieve this and it always felt that i only need to implement some custom thingy of the di container to make this work but it never worked thus i am looking for a detailed solution not just hand wavingeditendspecifically i want the output of the program below to becreated c0 with a0created d0 with a0created b0 with c0 d0created c1 with a1created d1 with a1created b1 with c1 d1where it currently produces the following outputcreated c0 with a0created d0 with a1 should be a0created b0 with c0 d0created c1 with a2 should be a1created d1 with a3 should be a1created b1 with c1 d1i am expecting di containers to allow this kind of customization but so far i had no luck in finding a solution below is my guicebased code but a springbased or other di containersbased solution is welcome import javautilarrays import comgoogleinject public class main public static class super private static mapclassinteger map new hashmapclassinteger private integer value public superobject args value mapgetgetclass value value null 0 value mapputgetclass value ifargslength 0 systemoutprintlncreated this with arraystostringargs override public final string tostring return getclassgetsimplenamecharat0 value public interface a public static class aimpl extends super implements a public interface b public static class bimpl extends super implements b inject public bimplc c d d supercd public interface c public static class cimpl extends super implements c inject public cimpla a supera public interface d public static class dimpl extends super implements d inject public dimpla a supera public static class mymodule extends abstractmodule override protected void configure bindaclasstoaimplclass bindbclasstobimplclass bindcclasstocimplclass binddclasstodimplclass public static void mainstring args injector inj guicecreateinjectornew mymodule injgetinstancebclass injgetinstancebclass,['java'] +67218,dependency injection and factory trying to figure out how to best handle the following scenarioassume a requestcontext class which has a dependency to an external service such aspublic class requestcontext irequestcontext private readonly servicefactoryiweatherservice weatherservice public requestcontextservicefactoryiweatherservice weatherservice userlocation location string query weatherservice weatherservice what sort of dependency should i require in the class that will ultimately instantiate requestcontext it could be servicefactoryiweatherservice but that does not seem right or i could create an irequestcontextfactory for it along the lines ofpublic class requestcontextfactory irequestcontextfactory private readonly servicefactoryiweatherservice weatherservice public requestcontextfactoryservicefactoryiweatherservice weatherservice weatherservice weatherservice public requestcontext createuserlocation location string query return new requestcontext weatherservice location query and then pass the irequestcontextfactory through constructor injectionthis seems like a good way to do it but the problem with this approach is that i think it hinders thiscoverability devs must know about the factory and implement it which is not really apparent is there a bettermore thiscoverable way that i am missing,['c#'] +67232,is there a combination of like and in in sql in sql i sadly often have to use like conditions due to databases that violate nearly every rule of normalization i cannot change that right now but that is irrelevant to the questionfurther i often use conditions like where something in 1123581321 for better readability and flexibility of my sql statementsis there any possible way to combine these two things without writing complicated subselectsi want something as easy as where something like bla foo batz instead ofwhere something like blaor something like for something like batzi am working with sql server and oracle here but i am interested if this is possible in any rdbms at all,['sql'] +67234,get just the hour of day from datetime using either 12 or 24 hour format as defined by the current culture net has the built in toshorttimestring function for datetime that uses the cultureinfocurrentculturedatetimeformatshorttimepattern format it returns something like this for enus 500 pm for a 24 hour culture such as dede it would return 1700what i want is a way to just return just the hour so 5 pm and 17 in the cases above that works with every culture whats the bestcleanest way to do thisthanks,"['c#', '.net']" +67243,how to correctly present a popover from a uitableviewcell with uipopoverarrowdirectionright or uipopoverarrowdirectionleft i always try to present a popover from a cell inside a tableview this waymypopover presentpopoverfromrectcellframe inviewselftableview permittedarrowdirectionsuipopoverarrowdirectionany animatedyesbut i cannot use uipopoverarrowdirectionright or left because depending on the positionof the ipad portrait or landscape the popover appears someplace elseam i presenting the popover the right wayps the table view is in the detailview of a splitview,['objective-c'] +67286,a more condensed way of doing the following loop i have the following forloop it uses the values 06 form mondaysunday respectivelyis there a more condensed way to do this as opposed to listing out the if iday i 0 is monday i 6 is sundayfori0i7i if i0 echo input namerepeat on week typecheckbox value0 monday if i1 echo input namerepeat on week typecheckbox value1 tuesday if i2 echo input namerepeat on week typecheckbox value2 wednesday if i3 echo input namerepeat on week typecheckbox value3 thursday if i4 echo input namerepeat on week typecheckbox value4 friday if i5 echo input namerepeat on week typecheckbox value5 saturday if i6 echo input namerepeat on week typecheckbox value6 sunday,['php'] +67290,pagination in google app engine with java i need to create simple pagination of objects but when i read manual i found out that querysetrange5 10 will fetch 10 objects even when only 5 objects are neededis there anyway to fetch just needed objectsedit i started bounty so fi you can show me simple example code in java that works then i will accept you answer,['java'] +67303,how to embed a view with buttons etc inside an edittext i am trying to figure out how to embed things other than drawables inside an edittext widget specifically the example i am thinking of is from the google buzz widgetscreenshotno inline image sorry i am a newbit appears to the casual observer that there is an entire layout object pinned to the bottom of the edittext containing an imageview a textview and a buttonanyone have any idea how to pull this off or do we think this is a custom subclass of edittext,['android'] +67330,why the current working directory changes when use the open file dialog in windows xp i have found an strange behavior when use the open file dialog in c if use this code in windows xp the current working directory changes to the path of the selected file however if you run this code in windows 7 the current working directory does not change private void button1 clickobject sender eventargs e messageboxshowstringformatcurrent directory 0directorygetcurrentdirectory my applicationmessageboxbuttonsok messageboxiconasterisk dialogresult result openfiledialog1showdialog show the dialog and get result if result dialogresultok messageboxshowstringformatcurrent directory 0 directorygetcurrentdirectory my application messageboxbuttonsok messageboxiconasterisk anybody know the reason for this behavior why the current directory changes in xp and not in windows 7,"['c#', '.net']" +67383,rss feed parser library in java is there any java helper utilslibraries available for parsing rssatom feed i checked rssutils but it looks like outdated,['java'] +67390,how to check hasrole in java code with spring security how to check user authority or permission in java code for example i want to show or hide button for user depending on role there are annotations likepreauthorizehasrolerole userhow to make it in java code something like ifsomethingherehasrolerole manager layoutaddcomponentnew buttonedit users,['java'] +67416,which sha256 is correct the java sha256 digest or the linux commandline tool when i calculate in java an sha256 of a string with the following method public static void mainstring args throws nosuchalgorithmexception messagedigest md messagedigestgetinstancesha256 byte hash mddigestpasswordgetbytes stringbuffer sb new stringbuffer forbyte b hash sbappendintegertohexstringb 0xff systemoutprintlnsbtostringi get 5e884898da2847151d0e56f8dc6292773603dd6aabbdd62a11ef721d1542d8on the commandline i do the following i need the n to not add a newline echo n password sha256sumand get5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8if we compare these more closely i find 2 subtle differences5e884898da2847151d0e56f8dc6292773603dd6aabbdd62a11ef721d1542d85e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8or 5e884898da28 47151d0e56f8dc6292773603d d6aabbdd62a11ef721d1542d85e884898da28 0 47151d0e56f8dc6292773603d 0 d6aabbdd62a11ef721d1542d8which of the 2 is correct hereresult both are but i was wrongfixed it by using stringbuffer sb new stringbuffer forbyte b hash sbappendstringformat02x b thanks,['java'] +67424,c constreference semantics consider the sample application below it demonstrates what i would call a flawed class designinclude iostreamusing namespace stdstruct b b m value1 long m valuestruct a const b getb const return m b void fooconst b b assertthis b m bm value bm value m bm value bm value protected b m bint mainint argc char argv a a cout original value agetbm value endl cout expected value 3 endl afooagetb cout actual value agetbm value endl return 0outputoriginal value 1expected value 3actual value 4obviously the programmer is fooled by the constness of b by mistake b points to this which yields the undesired behaviormy question what construles should you follow when designing getterssettersmy suggestion never return a reference to a member variable if it can be set by reference through a member function hence either return by value or pass parameters by value modern compilers will optimize away the extra copy anyway,['c++'] +67433,a c refactoring question i came accross the following code today and i did not like it it is fairly obvious what it is doing but i will add a little explanation here anywaybasically it reads all the settings for an app from the db and the iterates through all of them looking for the db version and the app version then sets some variables to the values in the db to be used lateri looked at it and thought it was a bit ugly i do not like switch statements and i hate things that carry on iterating through a list once they are finished so i decided to refactor itmy question to all of you is how would you refactor it or do you think it even needs refactoring at allheres the code using var sqlconnection new sqlconnectionlfepaitrsframeworkconfigurationconnectionstring sqlconnectionopen var datatable new datatablesettings var selectcommand new sqlcommandlfepaitrsdatadatabasecommandsdbosettingsselall sqlconnection var reader selectcommandexecutereader while readerread switch readersettingkeycolumnnametostringtoupper case databaseversionkey databaseversion new versionreadersettingvaluecolumnenametostring break case applicationversionkey applicationversion new versionreadersettingvaluecolumnenametostring break default break if databaseversion null throw new applicationexceptioncolud not load database version setting from the database if applicationversion null throw new applicationexceptioncolud not load application version setting from the database,"['c#', '.net']" +67434,mysql showing null values for group by statements i am doing select sumclicks date from stats group by datehowever when the sum is null for some date the whole row is thiscarded i want to see null some date how to do so,"['sql', 'mysql']" +67435,thisposing the members that implement ithisposable in my thispose methods like the one below everytime i want to call someobjthispose i also have a check for someobjnullis that because of bad design on my part is their a cleaner way to ascertain that thispose of all the members implementing ithisposable being used in an object is called without having a risk of nullreference exception protected void thisposebool thisposing if thisposing if splittradepopupmanager null splittradepopupmanagerthispose thanks for your interest,['c#'] +67452,how to make mysql utilize available system resources or find the real problem this is a mysql 5026 server running on suse enterprise 10 this may be a serverfault question the web user interface that uses these particular queries below is showing sometimes 30 even up to 120 seconds at the worst to generate the pages involved on development when the queries are run alone they take up to 20 seconds on the first run with no query cache enabled but anywhere from 2 to 7 seconds after that i assume because the tables and indexes involved have been placed into ram from what i can tell the longest load times are caused by readupdate locking these are myisam tables so it looks like a long update comes in followed by a couple 7 second queries and they are just adding up and i am fine with that explanation what i am not fine with is that mysql does not appear to be utilizing the hardware it is on and while the bottleneck seems to be the database i cannot understand why i would say throw more hardware at it but we did and it does not appear to have changed the situation viewing a top during the slowest times never shows much cpu or memory utilization by mysqld as if the server is having no trouble at all but then why are the queries taking so long how can i make mysql use the crap out of this hardware or find out what i am doing wrongextra details on the memory health tab in the mysql administrator for windows the key buffer is less than 18th used so all the indexes should be in ram i can provide a screen shot of any graphs that might help so desperate to fix this issue suffice it to say there is legacy code generating these queries and they are pretty much stuck the way they are i have tried every combination of indexes on the tables involved but any suggestions are welcome heres the current create table statement from development the experimental key i have added seems to help a little for the example query only create table registration task id varchar36 not null default date entered datetime not null default 0 0 date modified datetime not null default 0 0 assigned user id varchar36 default null modified user id varchar36 default null created by varchar36 default null name varchar80 not null default status varchar255 default null date due date default null time due time default null date start date default null time start time default null parent id varchar36 not null default priority varchar255 not null default 9 description text order number int11 default 1 task number int11 default null depends on id varchar36 default null milestone flag varchar255 default null estimated effort int11 default null actual effort int11 default null utilization int11 default 100 percent complete int11 default 0 deleted tinyint1 not null default 0 wf task id varchar36 default 0 reg field varchar8 default date offset int11 default 0 date source varchar10 default date completed date default 0 completed id varchar36 default null original name varchar80 default null primary key id key idx reg task p deletedparent id key by assignee assigned user iddeleted key status assignee statusdeleted key experimental deletedstatusassigned user idparent iddate due enginemyisam default charsetlatin1 and one of the ridiculous queries in question select usersuser name assigned user name registrationfield001 parent name registration taskstatus status registration taskdate modified date modified registration taskdate due date due registrationfield240 assigned wf iflengthregistration taskdescription010 has description registration task from registration task left join users on registration taskassigned user idusersid left join registration on registration taskparent idregistrationid where registration taskstatus completed and registrationfield001 like and registration taskname like and registrationfield060 like gn001472 and registration taskdeleted0 order by date due asc limit 020mycnf mysqld sectionmysqldport 3306socket varlibmysqlmysqlsockskiplockingkey buffer 384mmax allowed packet 100mtable cache 2048 sort buffer size 2m net buffer length 100m read buffer size 2m read rnd buffer size 160m myisam sort buffer size 128mquery cache size 16mquery cache limit 1mexplain above query without additional index id select type table type possible keys key key len ref rows extra 1 simple registration task ref idx reg task pstatus assignee idx reg task p 1 const 1067354 using where using filesort 1 simple registration eq ref primarygbl primary 8 sugarcrm401registration taskparent id 1 using where 1 simple users ref primary primary 38 sugarcrm401registration taskassigned user id 1 explain above query with experimental index id select type table type possible keys key key len ref rows extra 1 simple registration task range idx reg task pstatus assigneenewindex1tcg experimental tcg experimental 259 null 103345 using where using filesort 1 simple registration eq ref primarygbl primary 8 sugarcrm401registration taskparent id 1 using where 1 simple users ref primary primary 38 sugarcrm401registration taskassigned user id 1 show indexes from registration taskmysql show indexes from registration task table non unique key name seq in index column name collation cardinality sub part packed null index type comment registration task 0 primary 1 id a 1445612 null null btree registration task 1 idx reg task p 1 deleted a 2 null null btree registration task 1 idx reg task p 2 parent id a 57824 null null btree registration task 1 by assignee 1 assigned user id a 5295 null null yes btree registration task 1 by assignee 2 deleted a 5334 null null btree registration task 1 status assignee 1 status a 18 null null yes btree registration task 1 status assignee 2 deleted a 23 null null btree registration task 1 newindex1 1 deleted a 2 null null btree registration task 1 newindex1 2 assigned user id a 5334 null null yes btree registration task 1 newindex1 3 parent id a 180701 null null btree registration task 1 tcg experimental 1 date due a 1919 null null yes btree registration task 1 tcg experimental 2 deleted a 3191 null null btree registration task 1 tcg experimental 3 status a 8503 null null yes btree registration task 1 tcg experimental 4 assigned user id a 53541 null null yes btree registration task 1 tcg experimental 5 parent id a 722806 null null btree 15 rows in set 0 secsolutioni think i may have solved the problem that to some will seem so embarrassingly obvious but was somehow overlooked until now the definition of registrationid is id bigint20 unsigned not null auto incrementwhile the registration taskparent id fk to registrationid was parent id varchar36 not nullchanging this via alter table sugarcrm401registration task change parent id parent id bigint20 unsigned not null causes the explain to show only 25 rows examined where it was earlier 651903 and 103345 at it is best when forcing crazy indexing had i posted the table definition of the registration table i am sure someone might have spotted it i am going to verify this and post followup after the weekend,['mysql'] +67463,why use shorter varcharn fields it is frequently advised to choose database field sizes to be as narrow as possible i am wondering to what degree this applies to sql server 2005 varchar columns storing 10letter english words in a varchar255 field will not take up more storage than in a varchar10 fieldare there other reasons to restrict the size of varchar fields to stick as closely as possible to the size of the data i am thinking ofperformance is there an advantage to using a smaller and when selecting filtering and sorting on the datamemory including on the application side cstylevalidation how important do you consider restricting colunm size to force nonsensical data imports to fail such as 200character surnames anything else background i help data integrators with the design of data flows into a databasebacked system they have to use an api that restricts their choice of data types for character data only varcharn with and 255 is available char nchar nvarchar and text are not were trying to lay down some good practices rules and the question has come up if there is a real detriment to using varchar255 even for data where real maximum sizes will never exceed 30 bytes or so typical data volumes for one table are 110 mio records with up to 150 attributes query performance select with frequently extensive where clauses and applicationside retrieval performance are paramount,['sql'] +67464,shoulda vs remarkable for rspec and rails i am using rspec and cucumber for bbdnow i am migrating to rails 3 and rspec 2 and as i could see both of frameworks shoulda and remarkable support rails 3 and rspec 2i have never used shoulda or remarkablewhat should i prefer to use with rspec shoulda or remarkable and why,['ruby-on-rails'] +67474,runtimeexception native typeface cannot be made when loading font i am attempting to use a custom font for a textview on android following the guide here and here using the same font same code same everything i get this in adb logcatwdalvikvm 317 threadid1 thread exiting with uncaught exception group0x4001d800eandroidruntime 317 fatal exception maineandroidruntime 317 javalangruntimeexception unable to start activity componentinfoorgevilxquacklockorgevilxquacklockmainactivity javalangruntimeexception native typeface cannot be madeeandroidruntime 317 at androidappactivitythreadperformlaunchactivityactivitythreadjava2663eandroidruntime 317 at androidappactivitythreadhandlelaunchactivityactivitythreadjava2679eandroidruntime 317 at androidappactivitythreadaccess2300activitythreadjava125eandroidruntime 317 at androidappactivitythreadhhandlemessageactivitythreadjava2033eandroidruntime 317 at androidoshandlerthispatchmessagehandlerjava99eandroidruntime 317 at androidoslooperlooplooperjava123eandroidruntime 317 at androidappactivitythreadmainactivitythreadjava4627eandroidruntime 317 at javalangreflectmethodinvokenativenative methodeandroidruntime 317 at javalangreflectmethodinvokemethodjava521eandroidruntime 317 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava868eandroidruntime 317 at comandroidinternaloszygoteinitmainzygoteinitjava626eandroidruntime 317 at dalviksystemnativestartmainnative methodeandroidruntime 317 caused by javalangruntimeexception native typeface cannot be madeeandroidruntime 317 at androidgraphicstypefaceinittypefacejava147eandroidruntime 317 at androidgraphicstypefacecreatefromassettypefacejava121eandroidruntime 317 at orgevilxquacklockmainactivityoncreatemainactivityjava24eandroidruntime 317 at androidappinstrumentationcallactivityoncreateinstrumentationjava1047eandroidruntime 317 at androidappactivitythreadperformlaunchactivityactivitythreadjava2627eandroidruntime 317 11 morewactivitymanager 59 force finishing activity orgevilxquacklockmainactivitywactivitymanager 59 activity pause timeout for historyrecord43e80368 orgevilxquacklockmainactivityddalvikvm 247 gc explicit freed 711 objects 53160 bytes in 20922mshmm okay i am using the font molototf which was successfully used in one of the blogs i am also using predatorttf another custom font but in truetype formatrelevant codepublic class mainactivity extends activity called when the activity is first created override public void oncreatebundle icicle superoncreateicicle typeface tf typefacecreatefromassetgetassets fontsmolototf textview tv textview findviewbyidridcustomfonttext tvsettypefacetf and xml version10 encodingutf8linearlayout xmlnsandroid androidorientationvertical androidlayout widthfill parent androidlayout heightfill parent textview androidididcustomfonttext androidlayout widthwrap content androidlayout heightwrap content androidtextsize30sp androidtexthere is some text textviewlinearlayoutwhat would be causing this it worked for the people in the blogs so why not me did something significant change in the api that is preventing me from doing this,"['java', 'android']" +67475,create or update method in rails if classnameexistsid selfid object classnamefind by nameselfname objectupdate attributes street address selfstreet address city name selfcity name name selforg unit name state prov id selfstate prov id zip code selfzip codeelse classnamecreate street address selfstreet address city name selfcity name federalid selffederalid name selforg unit name state prov id selfstate prov id zip code selfzip codeendi have code like this i would like to improve it so that it uses a method something like create or update classnamecreate or update by namename selfname street address selfstreet address city name selfcity name federalid selffederalid name selforg unit name state prov id selfstate prov id zip code selfzip codeif the name exists in the database then it should update that object otherwise it should create a new objectis there is any method that exists that i can do this with,"['ruby-on-rails', 'ruby']" +67476,what is the fastest way to get a datatable into sql server i have a datatable in memory that i need to dump straight into a sql server temp tableafter the data has been inserted i transform it a little bit and then insert a subset of those records into a permanent tablethe most time consuming part of this operation is getting the data into the temp tablenow i have to use temp tables because more than one copy of this app is running at once and i need a layer of isolation until the actual insert into the permanent table happenswhat is the fastest way to do a bulk insert from a c datatable into a sql temp tablei cannot use any 3rd party tools for this since i am transforming the data in memorymy current method is to create a parameterized sqlcommandinsert into table col1 col2 col200 values col1 col2 col200and then for each row clear and set the parameters and executethere has to be a more efficient way i am able to read and write the records on thisk in a matter of seconds,"['c#', '.net']" +67485,how to fix codesign when it says user cancelled the operation and i did not i am compiling an iphone app meant to be thistributed it is my first app so i followed the iphone provisioning profiles instructions unfortunately it fails with thiscodesign build appcd usersvideojuegosdocuments setenv ignore codesign allocate radar 7181968 developerplatformsiphoneosplatformdeveloperusrbincodesign allocatesetenv path developerplatformsiphoneosplatformdeveloperusrbindeveloperusrbinusrbinbinusrsbinsbinusrbincodesign f s iphone thistribution resourcerulesusersvideojuegosdocuments build appresourcerulesplist entitlements usersvideojuegosdocuments buildunityiphonebuildthistributioniphoneosunityiphonebuild xcent usersvideojuegosdocuments build appusersvideojuegosdocuments build app the operation was cancelled by the usercommand usrbincodesign failed with exit code 1i thought keychain was not allowing codesign to work but as far as i can tell that is not the casei also attempted running these commands from a terminal and it failed with this messageusersvideojuegosdocuments buildunityiphonebuildthistributioniphoneosunityiphonebuild xcent cannot read entitlement datai have made the xcode setting from scratch three times googled it no results i do not have any idea what else to try any suggestions,"['iphone', 'ios']" +67494,how can i add a column to this union result i have this query which i removed some keys from for brevitys sake select id as in id out id recipient sender read flag from received where recipient1union all select in id id as out id recipient sender read flag from sent where sender1 which combines the results from two tables showing messages sent and received by a given user what i would like to do is add a columnflag to the result to thistinguish which table the row belongs to so when i thisplay them i can show a relevant icon for sent or received messages how would i add this,['mysql'] +67504,error initializer element is not constant when trying to initialize variable with const i get an error on line 6 initialize my foo to foo init of the following program and i am not sure i understand whytypedef struct foo t int a b c foo tconst foo t foo init 1 2 3 foo t my foo foo initint main return 0keep in mind this is a simplified version of a larger multifile project i am working on the goal was to have a single constant in the object file that multiple files could use to initialize a state structure since it is an embedded target with limited resources and the struct is not that small i do not want multiple copies of the source i would prefer not to usedefine foo init 1 2 3 i am also trying to write portable code so i need a solution that is valid c89 or c99does this have to do with the orgs in an object file that initialized variables go into one org and are initialized by copying the contents of a second orgmaybe i will just need to change my tactic and have an initializing function do all of the copies at startup unless there are other ideas out there,['c'] +67510,draw a jbutton to look like a jlabel or at least without the button edge i have got a jbutton that for various reasons i want to act like a button but look like a jlabel it does not actually have to be a jlabel under the hood i just do not want the raised button edge to show upis there an easy way to turn off the button look for jbuttons but keep all the button functionalityi could build some kind of composed subclass hyperbutton that delegated to a jlabel for thisplay purposes but i am really hoping there is something along the lines of buttonlooklikeabuttonfalse,['java'] +67511,get uiviews viewcontroller iphone i have done this to get the viewselfsuperview viewwithtag10but how can i get that views viewcontroller just like you can get the the viewcontrollers view i want to go the other way so i can send a message call a method to that viewcontroller egselfsuperview viewwithtag10viewcontroller dosomethingobviously that not actual code but i want something like that,"['objective-c', 'iphone']" +67540,opengl how to clear only a part of the screen is it possible to not clear entire screen when using glclear function i need to clear only a part of the screen to save some rendering time otherwise i would have to redraw half of the screen every frame even if nothing is happening on the other halfof course this should be done as quickly or quickier as the glclear is now,['c++'] +67553,trigger jquery accordion menu by an event is it possible to open the next panel in a jquery accordion menu through a seperate button onclick event that is instead of clicking the heading to open another panel use a button not connected to the accordion,['jquery'] +67554,how to make iphone app compatible with multiple sdk firmware versions with ios4 coming out soon i have already planned to include an iad in a future update of an app of mine i assume that this will make my app unusable for anyone on a firmware lower than 40 is there a way to change that variables and the xib file based on the users firmwarecheers,['iphone'] +67589,how to convert biginteger to string in java i converted a string to biginteger as followsscanner scnew scannersysteminsystemoutprintlnenter the messagestring msgscnextbyte bytemsgmsggetbytesbiginteger mnew bigintegerbytemsg now i want my string back i am using mtostring but that is giving me the desired resultwhy where is the bug and what can i do about it,['java'] +67593,calling a java servlet from javascript i am trying to create a web application using the mvc design pattern for the gui part i would like to use javascript and for the controller java servletsnow i have never really worked with javascript so i am having a hard time figuring out how to call a java servlet from javascript and how to get the response from the servlet can anybody help me out,"['java', 'javascript']" +67623,good notification plugin for jquery i am looking at pines notify and it looks good but it seems to have little actual documentation so i am wondering is there anything more established and worked on out therelike i do not want to spend time trying to figure out how to use pines and then find out it is missing some feature that i needed a few months later that i needed to change to a different pluginthis happened to me with tablesorter 20 i was using it then i needed the filtering but theirs kinda sucked so i found datatables what had such a bigger api and developed moreso i am wondering if there is something like datatablesin terms of development and features just for notifications insteadeditso i am looking at jgrowl and kinda confused with how to use the theme roller with itso i took once of the example files and stripped it down with everything i thought was junkdoctype html public w3cdtd xhtml 10 transitionalen html langenus xmllangenus xmlns debugtrue head titlejgrowl meet twittertitle link relstylesheet hrefjqueryjgrowlcss typetextcss link typetextcss hrefcsslefrogjqueryui172customcss relstylesheet script typetextjavascript function uistatedefaulthover functionthisaddclassuistatehover functionthisremoveclassuistatehover mousedownfunctionthisaddclassuistateactive mouseupfunctionthisremoveclassuistateactive mouseoutfunctionthisremoveclassuistateactive script script typetextjavascript srcjqueryui172customminjsscript script typetextjavascript srcjquery132jsscript script typetextjavascript srcjqueryjgrowljsscript script typetextjavascript documentreadyfunction this value can be true false or a function to be used as a callback when the closer is clciked jgrowldefaultscloser function consolelogclosing everything this jgrowlsticky notification with a header header a header sticky true script head body div idtrdevtool contain classuiwidget uiwidgetcontent uicornerall div classuiwidgetheader uicornertop h1jquery ui themeroller spandeveloper toolspanh1 div div bodyhtmli do not understand what this is for script typetextjavascript function uistatedefaulthover functionthisaddclassuistatehover functionthisremoveclassuistatehover mousedownfunctionthisaddclassuistateactive mouseupfunctionthisremoveclassuistateactive mouseoutfunctionthisremoveclassuistateactive scriptit seems to have nothing to do with applying the themes i took it away and the theme was still applied also if you look at my jgrowjgrowlsticky notification with a header header a header sticky true i make no mention of theme yet it still some how used the theme why is it taking the theme,['jquery'] +67631,jquery serialize does not register checkboxes i am using jqueryserialize to retrieve all data fields in a formmy problem is that it does not retriev checkboxes that is not checkedit includes thisinput typecheckbox idevent allday nameevent allday classcheckbox checkedchecked but not thisinput typecheckbox idevent allday nameevent allday classcheckbox how can i get values of checkboxes that is not checked,['jquery'] +67635,is it expensive to hold on to preparedstatements java jdbc i am trying to figure out if it is efficient for me to cache all of my statements when i create my database connection or if i should only create those that are most used and create the others ifwhen they are neededit seems foolish to create all of the statements in all of the client threads any feedback would be greatly appreciated,"['java', 'mysql']" +67644,numpy array how to select indices satisfying multiple conditions suppose i have a numpy array x 5 2 3 1 4 5 y f o o b a r i want to select the elements in y corresponding to elements in x that are greater than 1 and less than 5i triedx array5 2 3 1 4 5y arrayfoobaroutput yx 1 x 5 desired output is ooabut this does not work how would i do this,['python'] +67656,html5 tags not working at all in firefox 363 okay so i am trying to get into this whole html 5 thing and this tutorial says that these tags should move the content around without any kind of css at all but all i am getting is a line of text that looks like this header tag nav tag artical section tags aside tag footer tag here is the codedoctype htmlhtml langen head titlehtml5 test1title meta charsetutf8 head body header header tag header nav nav tag nav article section artical section tags section article aside aside tag aside footer footer tag footer body html,['html'] +67657,set default value for datetime in optional parameter how can i set default value for datetime in optional parameterpublic someclassinitguid docid datetime addedon datetimenow init codes here,['c#'] +67662,threading in android i am currently developing android app it needs download content from internet i use thread to do that and then call runonuithread method to update gui i placed a refresh menu on it if user tried to refresh the content the download thread will be created and started the problem is that how can i control the thread order i need to accept the latest requests response and abandon previous thread requests if there were some other requests still running because the request parameters may have been changed by user currently i was using a threadid to do this thing when a thread finished it will check its threadid if it was the latest recored one it then takes control and render the response my question is that is there any other proper better solution for thisdo i need to stop threads when user exit the app i remember that some book said that do not try stop thread manually and wait itself finish is a good practice is that true should i stop them by calling stop or interrupt method i read some documents around threading in android and found the class handlerthread what is it in what kind of situation i need to use it,"['java', 'android']" +67690,how to hideshow a process using c while executing my program i want to hideminimize microsoft speech recognition applicationand at the end i want to showmaximize using cthis process is not started by me so i cannot give control the process startinfoi have tried to use user32dll methods such asshowwindowanimatedwindowsanimatedwindowssetforegroundwindowsetwindowposwith all of them i have the same problemi can hide the windows althought i have to call one of the methods two times with sw hide option but when i call the method with a sw show flag it simply does not showshow can i maximizeshow after hiding the processthanks in advancehere is some pieces of the code now implemented to use setwindowplacement dllimportuser32dll return marshalasunmanagedtypebool public static extern bool getwindowplacementintptr hwnd ref windowplacement lpwndpl dllimportuser32dll setlasterror true return marshalasunmanagedtypebool static extern bool setwindowplacementintptr hwnd in ref windowplacement lpwndpl dllimportuser32dll public static extern boolean showwindowasyncintptr hwnd int32 ncmdshow dllimportuser32dll public static extern boolean setforegroundwindowintptr hwnd dllimportuser32dll public static extern boolean showwindowintptr hwnd int32 ncmdshow dllimportuser32dll public static extern boolean animatewindowintptr hwnd uint dwtime uint dwflags dllimportdwmapidll public static extern int dwmsetwindowattributeintptr hwnd uint dwattribute intptr pvattribute intptr loldefinitions for different window placement constantsconst uint32 sw hide 0const uint32 sw shownormal 1const uint32 sw normal 1const uint32 sw showminimized 2const uint32 sw showmaximized 3const uint32 sw maximize 3const uint32 sw shownoactivate 4const uint32 sw show 5const uint32 sw minimize 6const uint32 sw showminnoactive 7const uint32 sw showna 8const uint32 sw restore 9public sealed class animatewindowflags public const int aw hor positive 0x01 public const int aw hor negative 0x02 public const int aw ver positive 0x04 public const int aw ver negative 0x08 public const int aw center 0x010 public const int aw hide 0x010 public const int aw activate 0x020 public const int aw slide 0x040 public const int aw blend 0x080public struct windowplacement public int length public int flags public int showcmd public systemdrawingpoint ptminposition public systemdrawingpoint ptmaxposition public systemdrawingrectangle rcnormalposition this works param new windowplacement paramlength marshalsizeoftypeofwindowplacement paramshowcmd intsw hide lol setwindowplacementtheprocessmainwindowhandle ref param this does not work windowplacement param new windowplacement paramlength marshalsizeoftypeofwindowplacement paramshowcmd sw show lol getwindowplacementtheprocessmainwindowhandle ref paramnotedoes the sapi api has a command to minimize this minimize and maximize this window,['c#'] +67706,structs interfaces and boxing possible duplicateis it safe for structs to implement interfaces take this codeinterface isomeinterface public int someproperty get struct somestruct isomeinterface int somevalue public int someproperty get return somevalue public somestructint value somevalue value and then i do this somewhereisomeinterface somevariable new somestruct2is the somestruct boxed in this case,['c#'] +67716,contenteditable div thisabling drag and drop is it possible to thisable the draganddrop functionality on elements which have the contenteditable attribute set to truei have the following html pagedoctype htmlhtmlmeta charsetutf8headtitlecontenteditabletitleheadbody div contenteditabletruethis is editable contentdiv spanthis is not editable contentspan img srcbookmarkpng titleclick to do foo onclick foo spanbodyhtmlthe main problem i am facing is that it is possible to drag and drop the image into the div and it gets copied along with the title and the click handler,['javascript'] +67722,has anyone used hiphop for php i was wondering if anyone here has used hiphop if so what do you think about the technology is it real world what problems have you run into should i compile my production application using hiphop,['php'] +67723,websites that archive crossbrowser crossplatform cssjs bugs i am about to develop my own browser inconsistencybug compendium site but i am wondering if i really need to can we get a wiki of sites that do this already i am aware of a lot of them but i hope i am not missing out on some major onesi wanted mine to be more intuitive and sociallike for most people powered by tags and screenshots and testcase pages,"['javascript', 'css']" +67725,how to set a property of a c 4 dynamic object when you have the name in another variable i am looking for a way to modify properties on a dynamic c 40 object with the name of the property known only at runtimeis there a way to do something like expandoobject is just used as an example this could be any class that implements idynamicmetaobjectproviderstring key testkeydynamic e new expandoobjectekey valuewhich would be equivalent todynamic e new expandoobjectetestkey valueor is the only way forward reflection,"['c#', '.net']" +67737,jquery how to dynamically add a validation rule heyi am trying to dynamically add a validation rule to some dynamic controlsinputidhoursrulesadd requiredhowever this line gives me the following errordataelementform validator is nulldefining rules the static way with the validate function works fine what am i doing wrongthanksjustin,['jquery'] +67746,deactivate or remove the scrollbar on html i want to deactivate or remove the vertical scrollbar in an html pagehow to do that thanks,"['html', 'css']" +67748,php print all properties of an object i have an unknown object in php page how can i printecho it so i can see what propertiesvalues do it havewhat about functions is there any way to know what functions an object have,['php'] +67757,determine android phones proximity to known point while conserving power i am trying to determine if an android user has had a close proximity to a list of predetermined locations i would like to do this with the least amount of drain on the phones battery the two mechanisms i see for accomplishing this are proximity alerts and requesting location updates what are the pros and cons of the two methods will one have less affect on the battery than the other in either case i would guess the specific location manager used would have some affect power usage existing stack overflow answer,['android'] +67758,whats the best way to migrate a django db from sqlite to mysql i need to migrate my db from sqlite to mysql and the various toolsscripts out there are too many for me to easily spot the safest and most elegant solutionthis seemed to me nice but appears to be 3 years since getting an update which is worryingcan you recommend a solution that is known to be reliable with django 1,['mysql'] +67779,unable to rename file with ftp methods when current user directory is different from root remark due to spam prevention mechanizm i was forced to replace the beginning of the uris from ftp to ftpi have got following problem i have to upload file with c ftp method and afterwards rename it easy right ok let us say my ftp host is like this ftpcontosocom and after logging in current directory is set to usersnameso what i am trying to achieve is to log in upload file to current directory as fileexttmp and after upload is successful rename the file to fileextthe whole difficulty is as i guess to properly set the request uri for ftpwebrequest msdn states the uri may be relative or absolute if the uri is of the form 2f is an escaped then the uri is absolute and the current directory is path if however the uri is of the form first the net framework logs into the ftp server using the user name and password set by the credentials property then the current directory is set to userlogindirectorypathok so i upload file with the following uri ftpcontosocomfileexttmpgreat the file lands where i wanted it to be in directory usersnamenow i want to rename the file so i create web request with following uri ftpcontosocomfileexttmp and specify rename to parameter as fileextand this gives me 550 error file not found no permissions etci traced this in microsoft network monitor and it gave mecommand rnfr rename from commandparameter fileexttmp ftp response to port 53724 550 file fileexttmp not found as if it was looking for the file in the root directory not in the current directoryi renamed the file manually using total commander and the only difference was that commandparameter was without the first slash commandparameter fileexttmp i am able to successfully rename the file by supplying following absolute uriftpcontosocom2fusers2fnamefileexttmp but i do not like this approach since i would have to know the name of current users directory it can probably be done by using webrequestmethodsftpprintworkingdirectory but it adds extra complexity calling this method to retrieve directory name then combining the paths to form proper uri what i do not understand is why the uri ftpcontosocomfileexttmp is good for upload and not for rename am i missing something herethe project is set to net 40 coded in visual studio 2010editok i place code snippetplease note that ftp host username and password should be filled out for this sample to work that is produce an error user directory must be different from root pwdcommand should return something different than class program private const string filename testext private const string tempfilename filename tmp private const string ftphost 127001 private const string ftpusername anonymous private const string ftppassword private const int buffersize 524288 static void mainstring args try string path pathcombineenvironmentgetfolderpathenvironmentspecialfoldermydocuments filename if fileexistspath filewritealltextpath ftp rename sample string requesturi ftp ftphost tempfilename upload ftpwebrequest uploadrequest ftpwebrequestwebrequestcreaterequesturi uploadrequestusebinary true uploadrequestusepassive true uploadrequestcredentials new networkcredentialftpusername ftppassword uploadrequestkeepalive true uploadrequestmethod webrequestmethodsftpuploadfile stream requeststream null filestream localfilestream null localfilestream fileopenreadpath requeststream uploadrequestgetrequeststream byte buffer new bytebuffersize int readcount localfilestreamreadbuffer 0 buffersize long bytessentcounter 0 while readcount 0 requeststreamwritebuffer 0 readcount bytessentcounter readcount readcount localfilestreamreadbuffer 0 buffersize systemthreadingthreadsleep100 localfilestreamclose requeststreamclose ftpwebresponse response ftpwebresponseuploadrequestgetresponse ftpstatuscode code responsestatuscode string description responsestatusdescription responseclose if code ftpstatuscodeclosingdata consolewritelinefile uploaded successfully rename ftpwebrequest renamerequest ftpwebrequestwebrequestcreaterequesturi renamerequestusebinary true renamerequestusepassive true renamerequestcredentials new networkcredentialftpusername ftppassword renamerequestkeepalive true renamerequestmethod webrequestmethodsftprename renamerequestrenameto filename try ftpwebresponse renameresponse ftpwebresponserenamerequestgetresponse consolewritelinerename ok status code 0 rename status description 1 responsestatuscode responsestatusdescription renameresponseclose catch webexception ex consolewritelinerename failed status code 0 rename status description 1 ftpwebresponseexresponsestatuscode ftpwebresponseexresponsestatusdescription catch exception ex consolewritelineextostring finally consolereadkey,['c#'] +67780,how to achieve conditional resource import in a spring xml context what i would like to achieve is the ability to dynamically ie based on a property defined in a configuration file enablethisable the importing of a child spring xml contexti imagine something likeimport conditionsomepropertyname resourcesomecontextxmlwhere the property is resolved to a boolean and when true the context is imported otherwise it is notsome of my research so farwriting a custom namespacehandler and related classes so i can register my own custom element in my own namespace for example mynsimport conditionsomepropertyname resourcesomecontextxmlthe problem with this approach is that i do not want to replicate the entire resource importing logic from spring and it is not obvious to me what i need to delegate to to do thisoverriding defaultbeandefinitiondocumentreader to extend the behaviour of the import element parsing and interpretation which happens there in the importbeandefinitionresource method however i am not sure where i can register this extension,['java'] +67786,how can i create a bar in the bottom of a java app like a status bar i am in the process of creating a java app and would like to have a baron the bottom of the app in which i thisplay a text bar and a status progress baronly i cannot seem to find the control in netbeans neither do i know the code to create in manuallythank you so much for helpingpaintrick,['java'] +67798,method vs function vs procedure vs class i know the basics of this methodsproceduresfunction and classes but i always confuse to differentiate among those in contrast of object oriented programming so please can any body tell me the difference among those with simple examples,"['c', 'objective-c']" +67806,hide public method used to help test a net assembly i have a net assembly to be released its release build includesa public documented api of methods which people are supposed to usea public but undocumented api of other methods which exist only in order to help test the assembly and which people are not supposed to usethe assembly to be released is a custom control not an application to regressiontest it i run it in a testing frameworkapplication which uses in addition to the publicdocumented api some advancedundocumented methods which are exported from the controlfor the public methods which i do not want people to use i excluded them from the documentation using the exclude tag supported by the sandcastle help file builder and the editorbrowsable attribute for example like this summary gets a see crefieditortransaction instance which helps to combine several dom edits into a single transaction which can be undone and redone as if they were a single atomic operation summary returnsa see crefieditortransaction instancereturnsieditortransaction createeditortransaction excludeeditorbrowsableeditorbrowsablestatenevervoid debugdumpblockstextwriter outputthis successfully removes the method from the api documentation and from intellisense however if in a sample application program i rightclick on an instance of the interface to see its definition in the metadata i can still see the method and the editorbrowsable attribute as well for example summary gets a modeltextmodeldomnodesieditortransaction instance which helps to combine several dom edits into a single transaction which can be undone and redone as if they were a single atomic operation returns a modeltextmodeldomnodesieditortransaction instanceieditortransaction createeditortransactioneditorbrowsableeditorbrowsablestatenevervoid debugdumpblockstextwriter outputquestionsis there a way to hide a public method even from the meta dataif not then instead for this scenario would you recommend making the methods internal and using the internalsvisibleto attribute or would you recommend some other way and if so what and whythank you,['.net'] +67816,prefer extension methods for encapsulation and reusability edit4 wikified since this seems to have morphed more into a thiscussion than a specific questionin c programming it is generally considered good practice to prefer nonmember nonfriend functions instead of instance methods this has been recommended by scott meyers in this classic dr dobbs article and repeated by herb sutter and andrei alexandrescu in c coding standards item 44 the general argument being that if a function can do its job solely by relying on the public interface exposed by the class it actually increases encapsulation to have it be external while this confuses the packaging of the class to some extent the benefits are generally considered worth it now ever since i have started programming in c i have had a feeling that here is the ultimate expression of the concept that they are trying to achieve with nonmember nonfriend functions that are part of a class interface c adds two crucial components to the mix the first being interfaces and the second extension methods interfaces allow a class to formally specify their public contract the methods and properties that they are exposing to the world any other class can choose to implement the same interface and fulfill that same contract extension methods can be defined on an interface providing any functionality that can be implemented via the interface to all implementers automatically and best of all because of the instance syntax sugar and ide support they can be called the same way as any other instance method eliminating the cognitive overheadso you get the encapsulation benefits of nonmember nonfriend functions with the convenience of members seems like the best of both worlds to me the net library itself providing a shining example in linq however everywhere i look i see people warning against extension method overuse even the msdn page itself states in general we recommend that you implement extension methods sparingly and only when you have to edit even in the current net library i can see places where it wouldve been useful to have extensions instead of instance methods for example all of the utility functions of listt sort binarysearch findindex etc would be incredibly useful if they were lifted up to ilistt getting free bonus functionality like that adds a lot more benefit to implementing the interfaceso whats the verdict are extension methods the acme of encapsulation and code reuse or am i just deluding myselfedit2 in response to tomas while c did start out with javas overly imo oo mentality it seems to be embracing more multiparadigm programming with every new release the main thrust of this question is whether using extension methods to drive a style change towards more generic functional c is useful or worthwhileedit3 overridable extension methodsthe only real problem identified so far with this approach is that you cannot specialize extension methods if you need to i have been thinking about the issue and i think i have come up with a solutionsuppose i have an interface myinterface which i want to extend i define my extension methods in a myextension static class and pair it with another interface call it myextensionoverrider myextension methods are defined according to this patternpublic static int mymethodthis myinterface obj int arg bool attemptcasttrue if attemptcast obj is myextensionoverrider return myextensionoverriderobjmymethodarg regular implementation herethe override interface mirrors all of the methods defined in myextension except without the this or attemptcast parameters public interface myextensionoverrider int mymethodint arg string myothermethodnow any class can implement the interface and get the default extension functionality public class myclass myinterface anyone that wants to override it with specific implementations can additionally implement the override interfacepublic class myspecializedclass myinterface myextensionoverrider public int mymethodint arg specialized implementation for one method public string myothermethod fallback to default for others myextensionmyothermethodthis attemptcast false and there we go extension methods provided on an interface with the option of complete extensibility if needed fully general too the interface itself does not need to know about the extension override and multiple extension override pairs can be implemented without interfering with each other i can see three problems with this approach it is a little bit fragile the extension methods and override interface have to be kept synchronized manually it is a little bit ugly implementing the override interface involves boilerplate for every function you do not want to specialize it is a little bit slow there is an extra bool comparison and cast attempt added to the mainline of every methodstill all those notwithstanding i think this is the best we can get until there is language support for interface functions thoughts,"['c#', 'c++']" +67818,why is the output like this class another public void methodobject o systemoutprintlnthis is in method which takes object public void methodstring s systemoutprintlnthis is method which takes string public class newclass public static void mainstring args another an new another anmethodnull when i try to execute this i get this is method which takes stringas the output why not this is in method which takes object object can also be null and string can also be null why does not it invoke first method,['java'] +67824,construct a unique number for a string in java we have a requirement of readingwriting more than 10 million strings into a file also we do not want duplicates in the file since the strings would be flushed to a file as soon as they are read we are not maintaining it in memorywe cannot use hashcode because of collisions in the hash code due to which we might miss a string as duplicate two other approaches i found in my googling1use a message digest algorithm like md5 but it might be too costly to calculate and store2use a checksum algorithm i am not sure if this produces a unique key for a string can someone please confirmis there any other approach avaiablethanks,['java'] +67832,objectivec nsmutablearray foreach loop with objects of multiple classes i have the nsmutablearray children in the datastructureclass foo which is the superclass of many others like bar1 and bar2that array stores bar1 and bar2 objects to get a treelike recursive parentchildrenstructure of subclasses from footo access the objects in the array i loop through them using the foreach loop in objectivecforfoo afoo in children but often i only need to loop through the objects in the array that have a certain class in this case i want to perform a task for each object of the class bar1 in the array children using forbar1 anobject in children again loops through all objects and not only the ones with the class bar1 is there a way to achieve what i need,"['c', 'objective-c']" +67833,iphone coredata how to group fetched results by day i am developing an iphone app with coredata one of my entities has an nsdate property named time it stores times to the minutesecond as my sections i would like to have the date to the day so if there are to entries 20100614 800 and 20100614 1100 i would like them to be grouped to 20100614currently i just use time as my sectionnamekeypathnsfetchedresultscontroller afetchedresultscontroller nsfetchedresultscontroller alloc initwithfetchrequestfetchrequest managedobjectcontextmanagedobjectcontext sectionnamekeypathtime cachenamerootis there a trick to group by the time to the day or do i have to use plain sql and something like group by datetime ymd,['iphone'] +67843,detailed android activity lifecycle onattachedtowindow i am interested in android activity lifecycle and i would like to get more detailed descriptiondocumentationreference than widely available basic oncreateonstartonresume one my need comes from realizing that starting new activity themedialog styled from onattachedtowindow greatly improves response time if comparing to starting it from oncreate i wonder how this onattachedtowindow fits into whole android activity lifecycle official api ref description called when the window has been attached to the window manager does not help a lot,['android'] +67844,how to determine windows java installation location i am trying to dynamically run a jar from a c assembly using procestartinfo now from a console application i am able to just runprocestartinfo info new procestartinfojava jar somerandomjarin an assembly however i keep getting a win32exception of the system cannot find the file specified and have to change the line to the full path of java like soprocestartinfo info new procestartinfocprogram filesjavajre6binjavaexe jar somerandomjarthis obviously would not do i need a way to dynamically but declaratively determine the installed location of javai started thinking of looking to the registry but when i got there i noticed that there were specific keys for the versions and that they could not even be guaranteed to be numeric eg hkey local machinesoftwarejavasoftjava runtime environment16 and hkey local machinesoftwarejavasoftjava runtime environment160 20what would be the most reliable longhaul solution to finding the most uptodate javaexe path from a c applicationthanks much in advance edit thanks to a combination of generictypeteas and stephen clearys answers i have solved the issue with the followingprivate string getjavainstallationpath string javakey softwarejavasoftjava runtime environment using var basekey registrykeyopenbasekeyregistryhivelocalmachine registryviewregistry64opensubkeyjavakey string currentversion basekeygetvaluecurrentversiontostring using var homekey basekeyopensubkeycurrentversion return homekeygetvaluejavahometostring,"['c#', 'java']" +67847,is the windows dev environment worth the cost i recently made the move from linux development to windows development and as much of a linux enthusiast that i am i have to say c is a beautiful language visual studio is terrific and now that i have bought myself a trackball my wrist has stopped hurting from using the mouse so muchbut there is one thing i cannot get past the cost windows 7 visual studio sql server expression blend viemu telerik msdn were talking thousands for each developer on the project youre definitely getting something for your money my question is is it worth it not every developer needs all the aforementioned tools but have you ever heard of anyone writing c code without visual studio i have worked on pretty large software projects in linux without having to pay for any development tool whatsoever now obviously if youre already a windows shop it does not pay to retrain all your developers and if youre looking to develop a windows desktop app you just cannot do that in linux but if you were starting a new web application project and could hire developers who are experts in whatever languages you want would you still choose windows as your development platform despite the high cost and if yes whyupdate i did not intend to start any arguments and i gained some valuable insights from the answerscommentsthe cost of setting up a dev environment in windows does not have to be so greatthe cost of the dev environment is really just a drop in the bucket when compared to the cost of the developers themselves this does not help a small startup or a freelance programmer though,['c#'] +67865,user signup with email verification i am developing a website with using struts2 and jsp pages in many sites after you signup a link will be sent to your email and after clicking on that the registration is complete i want this feature on my webstie but i do not have any idea how to do this and how is this working should i save users information on my database until heshe is verified or not i searched web but there is learning for php formsany tutorialthanks in advance,['java'] +67868,tsql call a stored procedure from another stored procedure and read the result i have a stored procedure that ending with a select returns a recordset i can call it within anoher stored procedure like thisexec procedure paramhow to get the returning recordset thanks,['sql'] +67873,how do i clear the text contents of a div in javascript i am temporarily adding contents to a divtempdiv and adding that to a link which is appended to a div contenthere that is thisplayed i need to clear the contents of tempdiv so that the links are not appended to each other creating a string of urls that do not link to anywheredocumentreadyfunction getjsondataphp functiondata fori 0 i 5 i tempdivappenddatajustinidatalink contenthereappenda hreftempdivclick to go to the div linka i need to clear the contents of tempdiv here solutions to clearing the temporary contents of the div as i go,"['javascript', 'jquery', 'html']" +67880,ruby bigdecimal sanity check floating point newb is my understanding correct that with ruby bigdecimal types even with varying precision and scale lengths should calculate accurately or should i anticipate floating point shenanigansall my values within a rails application are bigdecimal type and i am seeing some errors they do have different decimal lengths hoping it is just my methods and not my object types,"['ruby-on-rails', 'ruby']" +67889,controlling read and write access width to memory mapped registers in c i am using and x86 based core to manipulate a 32bit memory mapped register my hardware behaves correctly only if the cpu generates 32bit wide reads and writes to this register the register is aligned on a 32bit address and is not addressable at byte granularitywhat can i do to guarantee that my c or c99 compiler will only generate full 32bit wide reads and writes in all casesfor example if i do a readmodifywrite operation like thisvolatile uint32 t p reg 0xcafe0p reg 0x01i do not want the compiler to get smart about the fact that only the bottom byte changes and generate 8bit wide readwrites since the machine code is often more dense for 8bit operations on x86 i am afraid of unwanted optimizations thisabling optimizations in general is not an option edit an interesting and very relevant paper,['c'] +67896,c passing objects and list of objects by reference i have a delegate that modifies an object i pass an object to the delegate from a calling method however the calling method does not pickup these changes the same code works if i pass a list as the object i thought all objects were passed by reference so any modifications would be reflected in the calling methodi can modify my code to pass a ref object to the delegate but am wondering why this is necessarypublic class binder protected delegate int mybindertobject reader t myobject public void bindittobject reader t myobject m binders is a hashtable of binder objects mybindert binder m binderstest as mybindert int i binderreader myobject public class myobjectbinder public myobjectbinder m delegatestest new mybindermyobjectbindmyobject private int bindmyobjectobject reader myobject obj obj new myobject update properties return 1 calling method in some other classpublic void callingmethod myobject obj new myobject myobjectbinder binder new myobjectbinder binderbinditmyreader obj do not worry about myreader obj should show reflected changesupdatedi passed objects by ref to the delegate as i was instantiating a new object inside bindmyobjectprotected delegate int mybindertobject reader ref t myobject,['c#'] +67906,c template function compiles in header but not implementation i am trying to learn templates and i have run into this confounding error i am declaring some functions in a header file and i want to make a separate implementation file where the functions will be defined heres the code that calls the header dumcppinclude iostreaminclude vectorinclude stringinclude dumper2hint main stdvectorint v for int i0 i10 i vpush backi test stdstring s dumpvectorvsnow heres a working header file dumper2hinclude iostreaminclude stringinclude vectorvoid testtemplate class t void dumpvector stdvectort vstdstring septemplate class t void dumpvectorstdvectort v stdstring sep typename stdvectortiterator vi vi vbegin stdcout vi vi for vivendvi stdcout sep vi stdcout n returnwith implementation dumper2cppinclude iostreaminclude dumper2hvoid test stdcout olleh dlrownthe weird thing is that if i move the code that defines dumpvector from the h to the cpp file i get the following errorg c dumper2cpp wall wnodeprecatedg dumcpp o dum dumper2o wall wnodeprecatedtmpcckd2e3go in function maindumcpptext0xce undefined reference to void dumpvectorintstdvectorint stdallocatorint stdbasic stringchar stdchar traitschar stdallocatorchar collect2 ld returned 1 exit statusmake dum error 1so why does it work one way and not the other clearly the compiler can find test so why cannot it find dumpvector,['c++'] +67936,determine if on product page programmatically in magento i want to insert tracking codes on all of the pages of a magento site and need to use a different syntax if the page is a cms page a category browsing page or a product view page i have a custom module set up with a block that inserts a generic tracking code on each page for now from within the block how can i thistinguish between cms pages category pages and product pages i started with mageappgetrequesti can see that mageappgetrequestgetparamidreturns the product or category id on product and category pages but does not thistinguish between those page types mageappgetrequestgetroutenamereturn cms for cms pages but returns catalog for both category browsing and product view pages so i cannot use that to tell category and product pages apart is there some indicator in the request i can use safely or is there a better way to accomplish my goal of different tracking codes for different page types,['php'] +67953,fastest way to put contents of set to a single string with words separated by a whitespace i have a few setstrings and want to transform each of these into a single string where each element of the original set is separated by a whitespace a naive first approach is doing it like thissetstring set 1setstring set 2stringbuilder builder new stringbuilderfor string str set 1 builderappendstrappend thisstring 1 buildertostringbuilder new stringbuilderfor string str set 2 builderappendstrappend thisstring 2 buildertostringcan anyone think of a faster prettier or more efficient way to do this,['java'] +67955,in javascript event handling why return false or eventpreventdefault and stopping the event flow will make a difference it is said that when we handle a click event returning false or calling eventpreventdefault makes a difference in which the difference is that preventdefault will only prevent the default event action to occur ie a page redirect on a link click a form submission etc and return false will also stop the event flowdoes that mean if the click event is registered several times for several actions usingclickmeclickfunction a returning false will stop the other handlers from runningi am on a mac now and so can only use firefox and chrome but not ie which has a different event model and tested it on ff and chrome by adding 3 handlers and all 3 handlers ran without any stoppinga so what is the real difference or is there a situation where stopping the event flow is not desirablethis is related toand,"['javascript', 'jquery']" +67965,home key press behaviour while developing a sample android application i have constructed two activities1activity 12activity 2now activity 2 is the foreground activity whereas activity 1 is the background one now user presses home key the applicationie both the activities thissappear now is we relaunch the application we see activity 1 as the foreground activity my question is1does the platform maintain any history entry when pressed home key2how do we take the user to the last launch activity on relaunching the application,['android'] +67966,what log4j alternative logging libraries are available what logging libraries do you recommend as alternatives to log4j do these libraries work with spring and hibernate are they compatible with slf4j or jakarta commons logging,['java'] +67974,spring roo and aspectoriented programming i have been running some experiments of my own with spring roo and it seems to be pretty cool but i noticed that this tool makes heavy use of aop on the model layeri am thinking about creating a real project using roo and what i would like to know iswhy aop is everywhere is that okwhat are advantages and thisadvantages of this approachi am quite new to aspectoriented programming and some guidance would be greatly appreciated,['java'] +67985,how to get the linux folder and file icons and names in java i am creating a tree of folders and files in java windows and osx return the system icons and name with the following codenew jfilechoosergeticonfile fnew jfilechoosergetnamefile fis there any possibility to get the icons and name of unix systems a system command would be ok toothanks,['java'] +67990,retrieving the second most highest value from a table how do i retrieve the second highest value from a table,['sql'] +67992,java inputstream encodingcharset running the following example codeimport javaiopublic class test public static void mainstring args throws exception byte buf 27 inputstream is new bytearrayinputstreambuf bufferedreader r new bufferedreader new inputstreamreaderis iso88591 string s rreadline systemoutprintlntestjava9 byte char charsgetbytes0 int intsgetbytes0 systemoutprintlntestjava10 char char charscharat0 int intscharat0 systemoutprintlntestjava11 string below systemoutprintlns systemoutprintlntestjava13 string above gives me this outputtestjava9 byte char int63testjava10 char char int229testjava11 string belowtestjava13 string abovehow do i retain the correct byte value 27 in the line9 printout and consequently receive the expected output of the systemoutprintlns command a,['java'] +67993,strange messages in log file i have a application server for network operations written with java based on apache mina recently i encounter a strange behavior in my log files i noticed that the log file is full of characters i mean those unexpected characters are vast amount of as such the log file gets hundreds of gb in a couple of hours i have no clue about this problem and it is almost impossible to google it what could be the reason are those set of characters any familiar to anybodyi can give more details about the application if neededthanks in advance,['java'] +68001,how do i execute a function from ram on a cortexm3 stm32 i am trying to execute a function from ram on a cortexm3 processor stm32 the function erases the and rewrites the internal flash so i definitely needs to be in ram but how do i do that what i have tried is this copy the function to a byte array in ram using memcpy checking that it gets aligned correctly setting a function pointer to point to the byte array an then calling the the functionpointer this works fine for maybe 10 instructions i can follow the execution with the debugger but then i get a buss error and the processor resets the buss error occurs on the second pass through a loop so the code should be fine as it works the first pass i am thinking that the faster ram access mucks up the buss timing in some way anyway is there a correct way to do this how would a scatter file look like that places a function in ram automatically i am using keil uvision for cortexm3 edit more infotoolchain realview mdkarm v 410compiler armcc v400728assembler armasm v400728linker armlink v400728processor stm32f103zethe impreciserr bit is set in the buss fault register when the reset happens,['c'] +68010,difference between screenavailheight and windowheight i am executing the following javascript on my browser firefoxconsoledebugscreen height screenavailheight outputs 770consoledebugwindow height windowheight outputs 210 i am using jquery as wellwhat is the difference between the two is 770 in pixels and 210 in mmsimilarly when i write documentheight and windowheight there is a difference what is the reason,"['javascript', 'jquery']" +68019,java resource closing i am writing an app that connect to a website and read one line from it i do it like thistry urlconnection connection new urlwexamplecomopenconnection bufferedreader rd new bufferedreadernew inputstreamreaderconnectiongetinputstream string response rdreadline rdclose catch exception e exception handling is it good i mean i close the bufferedreader in the last line but i do not close the inputstreamreader should i create a standalone inputstreamreader from the connectiongetinputstream and a bufferedreader from the standalone inputstreamreader than close all the two readersi think it will be better to place the closing methods in the finally block like thisinputstreamreader isr nullbufferedreader br nulltry urlconnection connection new urlwexamplecomopenconnection isr new inputstreamreaderconnectiongetinputstream br new bufferedreaderisr string response brreadlinecatch exception e exception handlingfinally brclose isrclosebut it is ugly because the closing methods can throw exception so i have to handle or throw it which solution is better or what would be the best solution,['java'] +68020,multiprocessing vs threading python i am trying to understand the advantages of multiprocessing over threading i know that multiprocessing gets around the global interpreter lock but what other advantages are there and can threading not do the same thing,['python'] +68023,python vs java performance runtime speed possible duplicateis python slower than javac ignoring all the characteristics of each languages and focusing solely on speed which language is better performancewiseyoud think this would be a rather simple question to answer but i have not found a decent onei am aware that some types of operations may be faster with python and viceversa but i cannot find any detailed information on this can anyone shed some light on the performance differences,"['java', 'python']" +68024,operator stdstring const can somebody tell me what precisely operator stdstringstands for,['c++'] +68028,remove all child nodes from a parent i have a list i just want to remove all child nodes from it whats the most efficient way using jquery this is what i haveul idfoo liali libliulvar thelist documentgetelementbyidfoo while thelisthaschildnodes thelistremovechildthelistlastchildis there a shortcut rather than removing each item one at a time edit each list element has some data attached to it and a click handler like thisfoodelegateli click function alerthi adds element to the list at runtimefunction addlistelement var element lihihi elementdatagrade new gradeeventually i might add buttons per list item too so it looks like empty is the way to go to make sure there are no memory leaksthanksthanks,['jquery'] +68032,constructors in inner classes implementing interfaces how would i go about writing a constructor for an inner class which is implementing an interface i know i could make a whole new class but i figure there is got to be a way to do something along the line of thisjbutton b new jbuttonnew abstractaction public abstractaction superthis is a button public void actionperformedactionevent e systemoutprintlnbutton clicked when i enter this it does not recognize the abstractaction method as a constructor compiler asks for return type does anyone have an idea,['java'] +68037,full gc real time is much more that usersys times we have a web java based application running on jboss with allowed maximum heap size of about 12 gb total machine physical memory is 2 gb at some point the application stops responding to clients for several minutes after some analysis we found out that the culprit is the full gc heres an excerpt from the verbose gc log74477402 full gc psyounggen 3648k0k332160k psoldgen 778476k589497k819200k 782124k589497k1151360k pspermgen 102671k102671k171328k 6461546860 secs times user384 sys372 real64617 secs what i do not understand is how is it possible that the real time spent on full gc is about 11 minutes 646 seconds while usersys times are just 75 seconds 75 seconds sound to me much more logical time to spend for cleaning 200 mb from the old generation where does all the other time gothanks a lot,['java'] +68039,aes acceleration for java i want to encryptdecrypt lots of small 210kb pieces of data the performance is ok for now on a core2duo i get about 90 mbytess aes256 when using 2 threads but i may need to improve that in the future or at least reduce the impact on the cpuis it possible to use dedicated aes encryption hardware with java using jce or maybe a different apiwould java take advantage of special cpu features sse5 if i get a better cpuor are there faster jce providers i tried sunjce and bouncycastle no big differenceother possiblilities,['java'] +68042,what are the rails best practices for javascript templates in restfulresourceful controllers first 2 common basic approaches returning from some fooscontroller methodrespond to do format 1 render the out a json representation formatjson render json foo 2 render an rjs template say updatejserb formatjs render end in updatejserbfoohtml escape javascriptrenderfoo these are obviously simple cases but i wanted to illustrate what i am talking about i believe that these are also the cases expected by the default responder in rails 3 either the actionnamed default template or calling to format on the resourcethe issueswith 1 you have total flexibility on the view side with no worries about the template but you have to manipulate the dom directly via javascript you lose access to helpers partials etcwith 2 you have partials and helpers at your thisposal but youre tied to the one template by default at least all your views that make js calls to fooscontroller use the same template which is not exactly flexiblethree other approaches none really satisfactory1 escape partialshelpers i need into javascript beforehand then inserting them into the page after using string replacement to tailor them to the results returned subbing in name id etc2 put view logic in the templates for example looking for a particular dom element and doing one thing if it exists another if it does not3 put logic in the controller to render different templates for example in a polymorphic belongs to where update might be called for either commentsfoo or postsfoo rendering commntsfoosupdatejserb versus postsfoosupdatejserbi have used all of these and probably others i am not thinking of often in the same app which leads to confusing code are there best practices for this sort of thing it seems like a common enough usecase that youd want to call controllers via ajax actions from different views and expect different things to happen without having to do tedious things like escaping and stringreplacing partials and helpers client sideany thoughts,"['javascript', 'ruby-on-rails']" +68076,best rethis library for java the official rethis homepage lists jdbcrethis and jrethis what are the advantages thisadvantages of each are there any other options,['java'] +68084,is int thread safe i know that in net all 32bit types eg int bool etc are thread safe that is there would not be a partial write according to the specificationsbut does the same apply for int nullable int,"['c#', '.net']" +68085,using context provider and contextresolver in jaxrs i am just getting acquainted with implementing rest web services in java using jaxrs and i ran into the following problem one of my resource classes requires access to a storage backend which is abstracted away behind a storageengine interface i would like to inject the current storageengine instance into the resource class serving the rest requests and i thought a nice way of doing this would be by using the context annotation and an appropriate contextresolver class this is what i have so farin myresourcejavaclass myresource context storageengine storage in storageengineproviderjavaproviderclass storageengineprovider implements contextresolverstorageengine private storageengine storage new inmemorystorageengine public storageengine getcontextclass type if typeequalsstorageengineclass return storage return null i am using comsunjerseyapicorepackagesresourceconfig to thiscover the providers and the resource classes automatically and according to the logs it picks up the storageengineprovider class nicely timestamps and unnecessary stuff left out intentionallyinfo root resource classes found class myresourceinfo provider classes found class storageengineproviderhowever the value of storage in my resource class is always null neither the constructor of storageengineprovider nor its getcontext method is called by jersey ever what am i doing wrong here,['java'] +68093,rails how to test state machine please help me i am confused i know how to write statedriven behavior of model but i do not know what should i write in specsmy modelrb file look class ratification activerecordbase belongs to user attr protected status events state machine status initial boss do state boss state owner state declarant state done event approve do transition boss owner owner done end event divert do transition boss owner declarant end event repeat do transition declarant boss end endendi use state machine gemplease show me the course,['ruby-on-rails'] +68095,how can i update only certain fields in a django model form i have a model form that i use to update a modelclass turtlemodelsmodel name modelscharfieldmax length50 blankfalse description modelstextfieldblanktrueclass turtleformformsmodelform class meta model turtlesometimes i do not need to update the entire model but only want to update one of the fields so when i post the form only has information for the description when i do that the model never saves because it thinks that the name is being blanked out while my intent is that the name not change and just be used from the model turtle form turtleformrequestpost instanceobject if turtle formis valid turtle formsaveis there any way to make this happen thanks,['python'] +68101,how to inherit from a generic parameter i am basically wanting to do thisclass uilockablet t where t uiwidgethowever this does not work i have seen people recommend that you do thisclass uilockablet where t uiwidget private t basethis would require me to override each function uilockable would need and forward it to t this is impossible since t may derive from uiwidget and have unique abstractvirtual methods of its ownis there no way to simply inherit from t,['c#'] +68123,when are database triggers bad possible duplicateare database triggers evil there is lot of negative information on database triggers just want to get the communitys take on when is it good vs bad,['sql'] +68130,spring roo issue with urlrewrite in sts eclipse i am having trouble figuring out how to solve this issue i have a file called urlrewritexml which was automatically generated by spring roo after running the controller command in roo shell however i still get the following error referenced file contains errors for more information right click on the message in the problems view and select show detailsheres the content of the urlrewritexml filexml version10 encodingutf8doctype urlrewrite public tuckeyorgdtd urlrewrite 30en urlrewrite defaultmatchtypewildcard rule fromresourcesfrom to lasttrueresources1to rule rule fromstaticwebinffrom set typestatus403set to lasttruestaticwebinf1to rule rule fromstaticfrom to lasttrue1to rule rule fromfrom to lasttrueappindexto rule rule fromappfrom to lasttrueapp1to rule rule fromfrom toapp1to rule outboundrule fromappfrom to1to outboundrule urlrewriteany thoughts on how to get rid of this error,['java'] +68133,how can i send multiple types of objects across protobuf i am implementing a clientserver application and am looking into various ways to serialize and transmit data i began working with xml serializers which worked rather well but generate data slowly and make large objects especially when they need to be sent over the net so i started looking into protobuf and protobufnetmy problem lies in the fact that protobuf does not sent type information with it with xml serializers i was able to build a wrapper which would send and receive any various serializable object over the same stream since object serialized into xml contain the type name of the objectobjectsocket socket new objectsocketsocketaddtypehandlertypeofstring tells the socket the typessocketaddtypehandlertypeofint of objects we will wantsocketaddtypehandlertypeofbool to send and receivesocketaddtypehandlertypeofperson when it gets data it looks forsocketaddtypehandlertypeofaddress these types in the xml then uses the appropriate serializersocketconnect host portsocketsendnew person socketsendnew address object o socketreadtype otype ogettypeif otype typeofperson handlepersono as personelse if otype typeofaddress handleaddresso as addressi have considered a few solutions to this including creating a master state type class which is the only type of object sent over my socket this moves away from the functionality i have worked out with xml serializers though so i would like to avoid that directionthe second option would be to wrap protobuf objects in some type of wrapper which defines the type of object this wrapper would also include information such as packet id and destination it seems silly to use protobufnet to serialize an object then stick that stream between xml tags but i have considered it is there an easy way to get this functionality out of protobuf or protobufneti have come up with a third solution and posted it below but if you have a better one please post it tooinformation on field bounds bug using systemstringhashingprotected static int computetypefieldtype type systemstring byte data asciiencodingasciigetbytestypefullname md5cryptoserviceprovider md5 new md5cryptoserviceprovider return mathabsbitconvertertoint32md5computehashdata 0serializationusing memorystream stream new memorystream serializernongenericserializewithlengthprefix stream o prefixstylebase128 field field 600542181 byte data streamtoarray pipewritedata 0 datalengthdeserializaionusing memorystream stream new memorystream bufferpeek lock maplock success serializernongenerictrydeserializewithlengthprefix stream prefixstylebase128 field mappingsfield out o if success bufferclearintstreamposition else int len if serializertryreadlengthprefixstream prefixstylebase128 out len bufferclearlen field mappingsfield throws a keynotfoundexception while looking for 63671269if i replace toint32 with toint16 in the hash function the field value is set to 29723 and it works it also works if i explicitly define systemstrings field to 1 explicitly defining the field to 600542181 has the same effect as using the hash function to define it the value of the string being serialized does not change the outcome,['c#'] +68138,how can i set visual studio to use kr style bracketing i really do not like this style of formattingclass awesomeclass private static void awesomemethod can i make it format my code like thisclass awesomeclass private static void awesomemethod,['c#'] +68149,obtaining the min and max of a twodimensional array using linq how would you obtain the min and max of a twodimensional array using linq and to be clear i mean the minmax of the all items in the array not the minmax of a particular dimensionor am i just going to have to loop through the old fashioned way,['c#'] +68150,entity framework query builder methods why it and not lambdas i am just getting started with ef and a query like the following strikes me as oddvar departmentquery schoolcontextdepartmentsincludecourses orderbyitnamespecifically what sticks out to me is itname when i was tooling around with linq to sql pretty much every filter in a querybuilder query could be specified with a lambda like in this case d dnamei see that there are overrides of orderby that take lambdas that return an iorderedqueryable or an iorderedenumable but those obviously do not have the execute method needed to get the objectresult that can then be databoundit seems strange to me after all i have read about how lambdas make so much sense for this kind of stuff and how they are translated into expression trees and then to a target language why do i need to use itname,['c#'] +68154,how to find an image within another image using python i am trying to use python to determine if one small image is within another large image any suggestions before i take myself completely down the wrong pathedit ok some ideas i am using pil and i am converting each image to the p mode so i can compare each pixel as an integer i am trying to implement something like a boyeramoore string search or the knuthamorrisapratt algorithm but in 2 dimensionsmaybe this will help instead of searching for abc in xabcx answer4 we are searching for abc def ghi in x xabcx xdefx xghix x answer22,['python'] +68158,what tools does your company use to manage application performance of aspnet applications i am not talking about application profilers or debuggers but more specific to managing the applications in production environment so essentially monitor identify bottlenecks deploy fixes,['asp.net'] +68170,ruby on rails cucumber how to reset the db after each scenario so i am in my test environment now in the terminial rake dbtestprepare clears the db but not when i run it from the codeand i have this in featuressupportenvrbbefore do task build all do debug release each do t build type t raketaskdbtestpreparereenable raketaskdbtestprepareinvoke end endendbut my data remains in the project test db when my tests are done runningthis is in my databaseymltest adapter mysql encoding utf8 database projectname test username root passwordive also trieddbtestpurgeand dbtestresetand i know that it is using my test db because i check mysqlworkbench and it inserts data into the tables but does not delete the data when its done i have to delete it manuallywhen the tables are empty the test cases pass,['ruby-on-rails'] +68178,nhibernate manytoone on joined subclass with filter i have a class setup that looks something like thispublic abstract class parent public virtual bool isdeleted get set public class child parentpublic class other public virtual icollectionchild children get set child is mapped as a joinedsubclass of parentchilden is mapped as a manytoone bag the bag has a filter applied to it named softdeletablefilter the filter mapping looks like filterdef namesoftdeleteablefilter conditionisdeleted 0 or isdeleted is null that problem is that when otherchildren is loaded the filter is being applied to the child table and not the parent table is there any way to tell nhibernate to apply the filter to the parent classeditheres the parent mappingclass nameparent id property nameisdeleted typesystemboolean column nameisdeleted property joinedsubclass namechild key column nameparentid key joinedsubclassclass,['c#'] +68190,how do i register multiple paths for a httphandler in iis7 i have a httphandler that resizes images based on the querystring so requesting something likehttpserverimagejpgwidth320height240will give you a resized image that is 320x240in the iis manager under handler mappings i mapped my handlers path as jpggifbmppng however this does not activate the handler if i change it to just jpg then it worksmy question is do i have to create 4 separate mapping entries one for each image type or is there some way to combine multiple extensions in one path,['asp.net'] +68194,resources for learning c unix linux and embedded systems i want to learn c unix and linux and more about embedded systems very much interested in them are there any online courses or websites which can guide me and please suggest books to read in learning themthanks for your timeya please lets your answers and comments come in they are invaluable to me,['c'] +68197,reorder list elements jquery is it possible to reorder li elements with javascript or pure jquery so if i have a silly list like the followingul lifooli libarli licheeseliulhow would i move the list elements around like put the list element with cheese before the list element with foo or move foo to after bar is it possible if so how,"['javascript', 'jquery']" +68211,save uiviews representation to file what is the easiest way to save uiviews representation to filemy solution is uigraphicsbeginimagecontextsomeviewframesize someview drawrectsomeviewframe uiimage image uigraphicsgetimagefromcurrentimagecontext uigraphicsendimagecontext nsstring pathtocreate samplepng nsdata imagedata nsdata datawithdatauiimagepngrepresentationimage imagedata writetofilepathtocreate atomicallyyesbut it seems tricky and i think there must be more efficient way to do this,['iphone'] +68214,final and private static i read that doingpublic final void foo is equals toprivate static void foo both meaning that the method is not overridablebut i do not see the equivalence if a method is private it is automatically notaccessible,['java'] +68215,how to get a list of points from a uibezierpath i have a uibezierpath that i need to take a list of points fromin qt there is a function called pointatpercent that would fit my needs but i cannot find anything equivalent in objectivecdoes anyone know how to do this,"['ios', 'objective-c', 'iphone']" +68220,getting the substring from a certain character in nsstring if i have an nsstring that is initiallyabcdefghihow do i make it turn into fghiin other words everything from the asterisk onwards is keptlikewise how would i turn it intoabcdeeverything up to the asterisk is keptthanks,"['iphone', 'objective-c']" +68226,how can i create an editable combo box in htmljavascript i need to let users select an item from a dropdown list but also allow them to instead enter any text even if it does not match an item in the list how can i achieve this on a web page with html and javascriptthe select field does not let users enter text and the input text field does not show the preferred alternativesall items must show if the user opens the dropdown so it cannot be a simple autocomplete that only shows matching items,"['javascript', 'html']" +68232,understanding the concept of inheritance in java i am just refreshing the oops features of the java so i have a little confusion regarding inheritance concept for that i have a following sample code class super int index 5 public void printval systemoutprintlnsuper class sub extends super int index 2 public void printval systemoutprintlnsub public class runner public static void mainstring args super sup new sub systemoutprintlnsupindex supprintval now above code is giving me output as 5subhere we are overriding printval method so that is understandable that it is accessing child class method onlybut i could not understand why it is accessing the value of x from super classthanks in advance,['java'] +68235,trouble sending html in email with pony gem i have found this gem to be a great and easy way to send mail but i cannot seem to send any html in it if i write the followingponymail to messageto from accountfrom subject messagesubject content type texthtml html body h1hey thereh1 via smtp smtp host my host port port auth auth user my user password my password tls true the code above send a mail but the message appears to be empty in gmail any help would be greatly appreciated on thisthanks,['ruby'] +68243,how to escape and characters to html entities in oracle plsql i need to send html emails directly from oracle plsql package this works almost finei have problem with the fact that some of the data fetched from a table contain things like s l and similar fragments which sometimes ar treated as html tags and even if not they are always ignored and never thisplayed so i need to escape this column before inserting into email bodyis there a function to escape html special chars into entities automaticly or do i need to replace lt string manually all the special characters,['html'] +68255,parsing a string for dates in php given an arbitrary string for example i am going to play croquet next friday or gadzooks is it 17th june already how would you go about extracting the dates from thereif this is looking like a good candidate for the toohard basket perhaps you could suggest an alternative i want to be able to parse twitter messages for dates the tweets i would be looking at would be ones which users are directing at this service so they could be coached into using an easier format however i would like it to be as transparent as possible is there a good middle ground you could think of,['php'] +68266,sql alter column to shorter charn type i am working with ms sql server 2003 i want to change a column in one of my tables to have fewer characters in the entries this is identical to this question except for the fact that i want fewer characters instead of morei have a column in one of my tables that holds ninedigit entries a developer previously working on the table mistakenly set the column to hold tendigit entries i need to change the type from char10 to char9following the instructions from the thiscussion linked above i wrote the statementalter table my table alter column my column char9this returns the error message string or binary data would be truncated i see that my ninedigit strings have a space appended to make them ten digitshow do i tell sql server to thiscard the extra space and convert my column to a char9 type,['sql'] +68274,monotouch deploy to iphone i have developed a number of apps using monotouch and been using the emulator for the iphone now i need to deploy me application to my iphone for further testingi have purchased the iphone sdk from apple but i cannot find how to deploy and activate the monotouch application to my iphoneany pointers please,['iphone'] +68283,possible to call a managed dll from unmanaged c is it possible to call clr dll one for example which is made with c from unmanaged c codei need a dll that is not managed to call into it somehow maybe even via some proxy c process that is built with c cli,"['.net', 'c++']" +68327,php security scanner is there any easy to use php security scanner,['php'] +68353,where can i find the phpini for phpcli it appears that the php command line is using a different phpini from the main php interpreter i am using ubuntu 104 my problem is that in the main phpini i have included an extra path for an external library but in the cli version this is not present and so i have a path inclusion errorthanks,['php'] +68354,shared variable among ruby processes i have a ruby program that loads up two very large yaml files so i can get some speedup by taking advantage of the multiple cores by forking off some processes i have tried looking but i am having trouble figuring how or even if i can share variables in different processesthe following code is what i currently haveproteins decoyproteins fork do proteins yamlload filedatabase exitendfork do decoyproteins yamlload filedatabase exitendp proteinslvdkp thisplays nil though because of the forkso is it possible to have the forked processes share the variables and if so how,['ruby'] +68381,is there a way to give a subquery an alias in oracle 11g sql is there a way to give a subquery in oracle 11g an alias likeselect from select client ref id request from some table where message type 1 abc select client ref id response from some table where message type 2 defgwhere abcclient ref id defclient ref idotherwise is there a way to join the two subqueries based on the client ref id i realize there is a self join but on the database i am running on a self join can take up to 5 min to complete there is some extra logic in the actual query i am running but i have determined the self join is what is causing the issue the individual subqueries only take a few seconds to complete by them selves the self join query looks something likeselect strequest st1requestfrom some table st some table st1where stclient ref id st1client ref id,['sql'] +68393,how to find a random point in a quadrangle i have to be able to set a random location for a waypoint for a flight sim the maths challenge is straightforwardto find a single random location within a quadrangle where there is an equal chance of the point being at any location visually like this an example abcd quadrangle is a2141778 3710597 b3819732 2400974 c136419 2454 d1227 3737881thanks in advance for any help you can provide editthanks all for your replies i will be taking a look at this at the weekend and will award the accepted answer then btw i should have mentioned that the quadrangle can be convex or concave sry bout dat,['c#'] +68398,which is the best isolation framework for java jmock easymock mockito or other i realize this has been asked before but the last time was in mid 2008 if you were starting a new project right now which one would you use and why what are their strengthsweaknesses regarding readability usability maintainability and overall robustness,['java'] +68423,django adminsite customize search fields query in the django admin you can set the search fields for the modeladmin to be able to search over the properties given there my model class has a property that is not a real model property means it is not within the database table the property relates to another database table that is not tied to the current model through relationsbut i want to be able to search over it so i have to somehow customize the query the admin site creates to do the filtering when the search field was filled is this possible and if howi can query the database table of my custom property and it then returns the ids of the model classes fitting the search this then as i said has to flow into the admin site search querythanks,['python'] +68424,compiling c source with makefile in windows i am trying to compile a downloaded program in windows the program is usually run in linux but is programmed to also run in windows the code has if defined win32s in it and claims to work with borland free tools when i try to use make from the command line it tells me incorrect command line argument c in the makefile there are many lines that say make c followed by a directory name does this syntax not work in windows what is a correct way to do this is there any way to compile this for native use in windows with this makefile,['c'] +68447,how do you flush a buffered log4j fileappender in log4j when using a fileappender with bufferediotrue and buffersizex properties ie buffering is enabled i want to be able to flush the log during normal shutdown procedure any ideas on how to do this,['java'] +68461,calculating total width of all list items i have a standard ul as followsul lia hreflinkali lia hreflinkali lia hreflinkali lia hreflinkali lia hreflinkaliuli am trying to find a quick efficient way to calculate the combined with of all the li tags currently i havevar width 0ul lieachfunction width thisouterwidthi am just wondering if there is a quicker way to get the same result without using a loopthanks for your help,['jquery'] +68471,how to get ip address from sock structure in c i am writing simple serverclient and trying to get client ip address and save it on server side to decide which client should get into critical section i googled it several times but could not find proper way to get ip address from sock structurei believe this is a way to get ip from sock struct after server accept request from client more specifically in c after server execute csock acceptssock struct sockaddr client addr clen thanks,['c'] +68483,does junit 3 have something analogous to ignore i am forced to use junit 3 if i were using junit 4 i would occasionally use ignore since several of my tests take a bit of timeis there anything analogous in junit 4 commenting out tests is sloppy and changing the name from testx could lead to forgotten tests ignore is great because it always reminds you which tests were not rundoes anyone have a best practice for running some of a test classes methods in junit 3,['java'] +68490,how to set unit for paintsettextsize is it possible to change the unit for paintsettextsize as far as i know it is pixel but i like to set the text size in dip for multiple screen supportthanks,"['java', 'android']" +68495,how to download a webpage in php i was wondering how i could download a webpage in php for parsing,['php'] +68508,django auto minifying cssjs files before release i have following case i want to use uncompressed jscss files during development to debug js for example but on production i want to switch automatically to minified versions of that filessome simple solution is to put in your templatescript srcsome js if not debug min endif jsbut this require manully providing that such file exist and to do minifaction manullay after original file changehow do you accomplish this in your projects is there any tool for this,['html'] +68519,why does accessing a com object from net without going through the interop class sometimes work when you interface a com object from net code vs creates an interop dll with interop classesexampleyou have a foodll the implements a com library foo that includes an implementation of the com interface ibar you add a reference to foodll to a net project in bin youll see an interopfoolibdll in the object browser youll see interopfoolib under that youll see foolib under that youll see barclass under that youll see base types under that bar and ibarin your net code when declaring a variable you can type foolib and intellisense will give you the options of either bar or barclassfrom what i understood it really does not matter which you use in a variable declaration but it very much does matter which you used for its constructorthat is both of these should workfoolibbarclass thebar new foolibbarclassfoolibbar thebar new foolibbarclassbut this should not workfoolibbar thebar new foolibbarheres the problem we just tracked down an odd bug where code that was working for some customers and worked in our development and testing environments did not work at one customer site turned out to have been a programmer using the bar constructorso can anyone explain exactly what the difference is between the two constructors bar and barclasscan anyone explain why the bar constructor seems to work sometimescan anyone provide a method for ensuring that no one is mistakenly calling the wrong constructors without reading every line of code added it was suggested that the problem was in our com implementation this is what were doingthe idl object uuid dual helpstringibar interface pointer defaultunique nonextensibleinterface ibar ithispatch id1 helpstringmethod barify hresult barifyout retval variant bool rval uuid version10 helpstringfoo 10 type librarylibrary foolib importlibstdole32tlb importlibstdole2tlb uuid helpstringbar class coclass bar default interface ibar the implementationclass atl no vtable cbar public ccomobjectrootexccomsinglethreadmodel public ccomcoclasscbar clsid bar public ithispatchimplibar iid ibar libid foolib public isupporterrorinfoimpl iid ibarpublic cbar declare registry resourceididr bar declare protect final construct begin com mapcbar com interface entryibar com interface entryithispatch com interface entryisupporterrorinfo end com map added later decompile via net reflectorcomimport coclasstypeofbarclass guidpublic interface bar ibari do not care that the reflector ui calls this a thisassembly if it is outputting a hll it is a decompile,['.net'] +68522,net xml pretty printer is there a method in the net framework or a free open source library to pretty print xml,['.net'] +68523,get the current operating system during runtime in c i need to figure out the operating system my program is running on during runtimei am using qt 462 mingw and eclipse with cdt my program shall run a commandline qprocess on windows or linux now i need a kind of switch to run the different code depending on the operating systemthx,['c++'] +68529,combobox adding text and value to an item no binding source in c winapp how can i add both text and value to the items of my comboboxi did a search and usually the answers are using binding to a source but in my case i do not have a binding source ready in my programhow can i do something like thiscombo1item1 thisplaytextcombo1item1value useful value,['c#'] +68532,child activity in android so i have two activities the main is called main and the child one is called child when a button is clicked in the main activity it triggers the following piece of codeintent i new intentmainthis childclassmainthisstartactivityithat opens the child activityas soon as i call finish or press the back button within the child activity instead of going back to the main one the app just closes can you give me a hint where the problem might be ps by trial and error i found out that if edit androidmanifestxml and add androidthemeandroidstylethemedialogwithin the declaration of child the back button and calling finish behaves as expected closes the child activity and brings the main into focus the problem is that when i start typing in an edittext the screen starts flickering rather bizzare so i cannot use it as a dialog my main activity uses the camera so that might be making problems although when the child activity is started the onpause event is fired and it stops the camera until onresume is callededitso i tried using startactivityforresult and addedtoastmaketextthis onpause toastlength shortshowto the onpause and a similar one to the onresume methods when the child returns onresume does not get triggered i even overrided onactivityresult and even that does not get triggered so bizarrei think i found the problem but i cannot solve it myselfwhen the child activity is activated onstop and immediately after that ondestroy are invoked within the main activity but why,"['java', 'android']" +68536,java nio servlet to file is there a way without buffering the whole inputstream to take the httpservletrequest from a java servlet and write it out to a file using all nio is it even worth trying will it be any faster reading from a normal javaio stream and writing to a javanio channel or do they both really need to be pure nio to see a benefit thankseditso i just did a quick and dirty benchmark reading a file from one thisk and writing to a different thisk so i am actually testing the code and not the thisk averagesinputstream outputstream 321 msfilechannel filechannel 3 msinputstream filechannel 600 msi actually got worse performance trying to use a hybrid javaio javanio the nionio was faster by a lot but i am stuck with the servlet inputstream,['java'] +68539,problems with uinavigationcontroller inside of uitabbarcontroller viewwillappear not called as an overview i am having issues with a uinavigationcontroller inside of a uitabbarcontroller calling viewwillappear whenever a view is popped from the stack from the delegate a uitabbarcontroller is made programmatically create views for tab bar uinavigationcontroller view1 uinavigationcontroller alloc initwithrootviewcontrollernewsfeednavigationcontroller alloc initwithstyleuitableviewstyleplain resizedtabbatitem tabbaritem1 resizedtabbatitem alloc initwithtitlenil imageuiimage imagenamednewspaperpng tag0 view1 settabbaritemtabbaritem1 tabbaritem1 release uiviewcontroller view2 uiviewcontroller new resizedtabbatitem tabbaritem2 resizedtabbatitem alloc initwithtitlenil imageuiimage imagenamedspeechbubblepng tag1 view2 settabbaritemtabbaritem2 tabbaritem2 release create the tab bar controller booktabbarcontroller booktabbarcontroller new booktabbarcontroller view setframecgrectmake0 0 320 460 add the views to it nsarray viewcontrollers nsarray arraywithobjectsview1 view2 view3 view4 view5 nil booktabbarcontroller tabbarcontroller setviewcontrollersviewcontrollersmy newsfeednavigationcontroller is just a subclassed uitableviewcontroller and the subclass is not interfering with viewwillappear as it is never called in newsfeednavigationcontroller in it items that when clicked will push a new uiviewcontroller into the stack the problem is that whenever views are popped off the stack viewwillappear is never called in newsfeednavigationcontroller and the items in the list remain highlighted i have been messing with this for a few hours am at the point where i need some help to find out what i am doing wrongin my newsfeednavigationcontroller i tried to add an nslog to see if it is called or i did something but it is never even called voidviewwillappearboolanimated nslogis viewwillappear called super viewwillappearanimatededitokay now here is something weird i noticedif i run self presentmodalviewcontrollerany uiview animatedyesand then thismiss it viewwillappear begins to work properly when popping and pushing views so now i am stumped it is not really a solution but maybe an inside of something that is going on,['iphone'] +68568,winforms combobox dropdown and autocomplete window both appear i have got a combobox on a winforms app with this code combobox1autocompletemode autocompletemodesuggestappend combobox1autocompletesource autocompletesourcelistitems datatable t new datatable tcolumnsaddid typeofint tcolumnsaddthisplay typeofstring for int i 1 i 20 i trowsaddi itostringn0 combobox1datasource t combobox1valuemember id combobox1thisplaymember thisplayi then follow these steps when the window opensclick the combobox drop down button this thisplays the list of items and selects the text in the comboboxtype 5 1 ie i am looking to use autocomplete to search for 515 516 etcyoull see that the autocomplete window now appears on top of the drop down list however if i mouse over it is the obscured drop down window behind the autocomplete window that is receiving the mouse events including the click so i think i am clicking on an autocomplete item but actually clicking on something totally random that i cannot seeis this a bug in the combobox i am using windows 7 if that matters am i configuring the combobox wrong somehownote also that using the keyboard uses the autocomplete drop down so updown arrow keys are using the front window but the mouse is using the back window,['c#'] +68575,communicate multiple times with a process without breaking the pipe it is not the first time i am having this problem and it is really bugging mewhenever i open a pipe using the python subprocess module i can only communicate with it once as the documentation specifies read data from stdout and stderr until endoffile is reachedproc subpopenpsql h darwin d main dbsplitstdinsubpipestdoutsubpipeprint proccommunicateselect abresult from experiment 1412n0print proccommunicateselect thetazetaresult from experiment 2099n0the problem here is that the second time python is not happy indeed he decided to close the file after the first communicatetraceback most recent call lastfile apy line 30 in module print proccommunicateselect thetazetaresult from experiment 2099n0file usrlib64python25subprocesspy line 667 in communicate return self communicateinputfile usrlib64python25subprocesspy line 1124 in communicate selfstdinflushvalueerror io operation on closed fileare multiple communications allowed,['python'] +68577,how to overlay a div or any element over a table row tr i would like to overlay a div or any element thatll work over a table row tr tag that happens to have more than one columni have tried a few methods which do not seem to work i have posted my current code belowi do get an overlay but not directly over just the row i tried setting the overlay top to divbottomcsstop but that is always autoso am i on the right track or is there a better way of doing it utilizing jquery is fine as you can seeif i am on the right track how do i get the div placed correctly is the offsettop an offset in the containing element the table and i need to do some math any other gotchas i will run into with thatdocumentreadyfunction lnkdoitclickfunction var divbottom rowbottom var divoverlay divoverlay var bottomtop divbottomattroffsettop var bottomleft divbottomattroffsetleft var bottomwidth divbottomcsswidth var bottomheight divbottomcssheight divoverlaycsstop bottomtop divoverlaycssleft bottomleft divoverlaycsswidth bottomwidth divoverlaycssheight bottomheight infotexttop bottomtop left bottomleft rowbottom outlinered solid 2px divbottom margin1em fontsizexxlarge positionrelative divoverlay backgroundcolorsilver textaligncenter positionabsolute zindex10 opacity05 script srcscripthtml head titleoverlay teststitle head body p aligncentera idlnkdoit hrefdo itap table width100 border0 cellpadding10 cellspacing3 stylepositionrelative tr tdplorem ipsum dolor sit amet consectetur adipiscing elitptd tr tr idrowbottom tddiv iddivbottomp aligncenterthis is the bottom textpdivtd tr tr tdplorem ipsum dolor sit amet consectetur adipiscing elitptd tr table div iddivoverlay stylepthis is the overlay divpp idinfopdiv bodyhtml,"['javascript', 'jquery', 'html', 'css']" +68583,html where will the focus go next if i press tab is there some way of knowing where will the focus jump to when the tab key key will be pressed and certain element has the focusi am thinking on something to be used this wayvar nextelement wherewillfocusjumptocurrentelementthanks,"['javascript', 'html']" +68585,tool for checking java resource bundles i18n i am searching for a tool anttask ide plugin which helps with i18n of a java application using the standard messageproperties resource bundles both open source and commercial solutions are welcomespecifically i am searching for support in the following tasks1 extract the used keys from javacode jsps and other artifacts since custom frameworks are involved the extraction should allow customizationmapping of the source artifact to a certain message bundle also with custom rulesreport used keys which are not in the bundle report keys which are in the bundle but in none of the source artifact which map to this bundle2 check the property files of each bundle and report missing key definitions and also default translations uses the english text3 compare the current svncvsgitwhatever version with an old version and report cases where one translation or maybe only the default one changed but not the other translation covers 2 to a large part however i did not found something for 1 and 3 any pointers,['java'] +68592,how to start and stop a continuously running background worker using a button let us say i have a background worker like thisprivate void backgroundworker1 doworkobject sender doworkeventargs e whiletrue kill zombies how can i make this background worker start and stop using a button on a winform,['c#'] +68600,using jquery to make a post how to properly supply data parameter i would like to make an ajax call as a post it is going to go to my servlet i want to send parameterized data like the followingvar mydata param0some textparam1some more texti supply this as the data parameter of my jquery ajax call so this should be inserted in the body of the post right i mean not appended to my mysitesave urlajax url mysitesave type post data mydatait appears to work correctly in my servlet i am just dumping all received parameters and i see them all come through nicelyprivate void printparamshttpservletrequest req enumeration paramnames reqgetparameternames while paramnameshasmoreelements print each param keyval here also i should url encode my data string manually before use right likevar mydata param0 urlencodehi theremydata param1 urlencodeblah blahmydata param2 urlencodewe get itthanks,['jquery'] +68606,extending django flatpages to accept template tags i use django flatpages for a lot of content on our site i would like to extend it to accept django template tags in the content as welli found this snippet but after much larking about i could not get it to work am i correct in assuming that you would need too subclass the django flatpages app to get this to work is this best way of doing it i am not quite sure how to structure it as i do not really want to directly modify the django thistribution,['python'] +68612,gui not working after rewriting to mvc i am practicing mvc style programming i have a mastermind game in a single file working fine maybe apart of the fact that check button is invisible at startbut when i have rewritten it to model view controller files and when i click on empty pin that should be updated and repainted with new color noting happens can anybody see any problems here i have tried placing repaint in different places but it simply does not work at all main public class main public static void mainstring args model model new model view view new viewmastermind 400 590 model controller controller new controllermodel view viewsetvisibletrue model import javautilrandompublic class model static final int line 5 score 10 options 20 pin pins new pin21line int combination new intline int curpin 0 int turn 1 random generator new random int repaintpin boolean pinsrepaintfalse int pinstorepaint boolean isupdate true isplaying true isrowfull false static final int hit x 270290310290310 hit y 506496496516516 public model for int i0 i score i for int j 0 j line j pinsij new pin200 pinsijsetpositionj5030510i50 pinsiscorej new pin80 pinsiscorejsetpositionhit xjhit yji50 for int i0 i line i pinsoptionsi new pin 20 i2 pinsoptionsisetposition 370i 50 56 void fillholeint color pinsturn1curpinsetcolorcolor1 pinsrepaint true pinstorepaint turn curpin curpin1 line if curpin 0 isrowfull true pinsrepaint false pinstorepaint 0 void check int junkpins new intline junkcode new intline int pincount 0 pico 0 for int i 0 i line i junkpinsi pinsturn1igetcolor junkcodei combinationi for int i 0 i line i if junkpinsijunkcodei pinsturnscorepincountsetcolor1 pincount pico junkpinsi 98 junkcodei 99 for int i 0 i line i for int j 0 j line j if junkpinsijunkcodej pinsturnscorepincountsetcolor2 pincount junkpinsi 98 junkcodej 99 j line pinsrepaint true pinstorepaint turn score pinsrepaint false pinstorepaint0 if pico line isplaying false else if turn 10 isplaying false else curpin 0 isrowfull false turn void combination for int i 0 i line i combinationi generatornextint6 1 class pin private int color x y radius public pin x 0 y 0 radius 0 color 0 public pin int rint c x 0 y 0 radius r color c public int getx return x public int gety return y public int getradius return radius public void setradiusint r radius r public void setposition int xint y thisx x thisy y public void setcolor int c color c public int getcolor return color view import javaawtimport javaxswingpublic class view extends frame model model jbutton checkanswer private jpanel button private static final color colors colorblack colorwhite colorred coloryellow colorgreen colorblue new color7 254 250 public viewstring name int w int h model m model m settitle name setsize wh setresizable false thissetlayoutnew borderlayout button new jpanel buttonsetsize new dimension400 100 buttonsetvisibletrue checkanswer new jbuttoncheck checkanswersetsize new dimension200 30 buttonadd checkanswer thisadd button borderlayoutsouth buttonsetvisibletrue override public void paint graphics g gsetcolor new color238 238 238 gfillrect 00400590 for int i0 i modelpinslength i paintpinsmodelpinsi0g paintpinsmodelpinsi1g paintpinsmodelpinsi2g paintpinsmodelpinsi3g paintpinsmodelpinsi4g override public void update graphics g if modelisupdate paintg else modelisupdate true paintpinsmodelpinsmodelrepaintpin10g paintpinsmodelpinsmodelrepaintpin11g paintpinsmodelpinsmodelrepaintpin12g paintpinsmodelpinsmodelrepaintpin13g paintpinsmodelpinsmodelrepaintpin14g void repaintpins int pin modelrepaintpin pin modelisupdate false repaint public void paintpinspin p graphics g int x pgetx int y pgety int color pgetcolor int radius pgetradius int x xradius int y yradius if color 0 gsetcolor colorscolor gfilloval xy2radius2radius else gsetcolor new color238 238 238 gdrawoval xy2radius12radius1 gsetcolor colorblack gdrawoval xy2radius2radius controllerimport javaawtimport javaawteventpublic class controller implements mouselistener actionlistener private model model private view view public controllermodel m view v model m view v viewaddwindowlistener new windowadapter public void windowclosingwindowevent e systemexit0 viewaddmouselistenerthis viewcheckansweraddactionlistenerthis modelcombination public void actionperformed actionevent e ifegetsource viewcheckanswer ifmodelisrowfull modelcheck public void mousepressedmouseevent e point mouse new point mouse egetpoint if modelisplaying if mousex 350 int button 1 intmousey 32 50 if button 1 button 5 modelfillholebutton ifmodelpinsrepaint viewrepaintpins modelpinstorepaint public void mouseclickedmouseevent e public void mousereleasedmouseevent e public void mouseenteredmouseevent e public void mouseexitedmouseevent e,['java'] +68613,performance comparison of memcached with thisk caching i would like to know the performances of memcached on remote serveron same lan with thisk cachingbesides memcached is a scalable cache solution would there be any advantage of using memcached with respect to performance when compared to thisk caching regardsmugil,['php'] +68618,simulating brush strokes for painting application i am trying to write an application that can be used to create pictures that look like paintings using simulated brush strokes are there any good sources for simple ways of simulating brush strokes for example given a list of mouse positions that the user has dragged the mouse through a brush width and a brush texture how do i determine what to draw to the canvasi have tried angling the brush texture in the direction of the mouse movement and dabbing several brush texture images along the path but it does not look great i think i am missing something where the brush texture should shrink and grow on cornersany simple to follow links would be appreciated i have found complex academic papers on simulating eg oil paints but i just want a basic algorithm to use that produces ok results if possible,['c'] +68658,finalizing a cursor that has not been deactivated or closed nonfatal error i am getting a finalizing a cursor that has not been deactivated or closed error on this piece of code the code is used to fill a listview since it is a nonfatal error there is no crash and all seems to works finebut i do not like the error if i close the cursor at the end of this codethe listview stays empty if i close the cursor in onstop i get the same error how do i fix this private void updatelist dbadapter db new dbadapterthis dbopen load all waiting alarm mcursordbgettitlesstate2 setlistadapternew mycursoradapterthis mcursor registerforcontextmenugetlistview dbclose error ecursor 2318 finalizing a cursor that has not been deactivated or closed database datadataxdb table alerts query select id alert id ecursor 2318 androiddatabasesqlitedatabaseobjectnotclosedexception application did not close the cursor or database object that was opened here ecursor 2318 at androiddatabasesqlitesqlitecursorinitsqlitecursorjava210 ecursor 2318 at androiddatabasesqlitesqlitedirectcursordriverquerysqlitedirectcursordraiverjava 53 ecursor 2318 at androiddatabasesqlitesqlitedatabaserawquerywithfactorysqlitedatabasejaava 1345 ecursor 2318 at androiddatabasesqlitesqlitedatabasequerywithfactorysqlitedatabasejavaa 1229,['android'] +68666,scala class to implement two java interfaces how i have just started learning scala and i am now wondering how i could implement two different java interfaces with one scala class let us say i have the following interfaces written in javapublic interface eventrecorder public void abstract recordevent event public interface transactioncapable public void abstract commitbut a scala class can extend only one class at a time how can i have a scala class that could fulfill both contracts do i have to map those interfaces into traits note my scala classes would be used from java as i am trying to inject new functionality written in scala into an existing java application and the existing framework expects that both interface contracts are fulfilled,['java'] +68676,does anyone actually use the phrase dhtml anymore i am not sure if this is exactly appropriate but i have what i think is a interesting questiondoes anyone actually use the phrase dhtml anymore in a professional environmenti came across the the word the other day for the first time in years and shuddered at the thought of it to me the acronym dynamic html just sounds so 19 it brings me back to the days when i first thiscovered programming and web development and thought it was awesome to have scripts which modified the status bar and made things fly around the pagei for one have never used the phrase recently and would never dream of saying it in a professional environment to clients or colleges as i feel there is an amateur and dated stigma attached to itwhat are your thoughts,"['javascript', 'html']" +68681,a pathfinder obstacle collision problem i am working on a project with a robot that has to find its way to an object and avoid some obstacles when going to that object it has to pick upthe problem lies in that the robot and the object the robot needs to pick up are both one pixel wide in the pathfinder in reality they are a lot bigger often the a pathfinder chooses to place the route along the edges of the obstacles sometimes making it collide with them which we do not wish to have to doi have tried to add some more nonwalkable fields to the obstacles but it does not always work out very well it still collides with the obstacles also adding too many points where it is not allowed to walk results in that there is no path it can run ondo you have any suggestions on what to do about this problemeditso i did as justin l suggested by adding a lot of cost around the obstacles which results in the follinghere you can see the cost around the obstacles initially the middle two obstacles should look just like the ones in the corners but after running our pathfinder it seems like the costs are overriddenpicture above shows what things are found on the picturethis is the path found which as our problem also was before is hugging the obstacleand another picture with the cost map with the path onso what i find strange is why the a pathfinder is overriding these field costs which are very highwould it be when it evaluates the nodes inside the open list with the current field to see whether the current fields path is shorter than the one inside the open listand here is the code i am using for the pathfinderpathfindercs fieldcs and gridcs,['c#'] +68718,what inclient caching options work well with cassandra and java i am currently architecting a system that must be capable of dealing with tens of thousands of writes per second i am moreorless settled on using apache cassandra for the persistence layer and will be using java for the application layer but there are situations where i need to quickly access data in a way that picks up any changes within secondshitting cassandra every single time i need to check this data for changes will be too slow which means i need to use some kind of application layer cachingto ensure that the cached data remains current ideally it would support some kind of multicastbased cache invalidationwhat are my options,['java'] +68719,jquery buttonclick event is triggered twice i have the following problem with this codebutton iddeleteremove itemsbuttondeletebutton icons primary uiicontrash clickfunction alertclickedif i click this button the alert show up two times it is not only with this specific button but with every single button i createwhat am i doing wrong,['jquery'] +68720,oracle locking with selectfor update of i am selecting from tables foo and bar i would like to lock the records of foo which are being returned but i do not want the records of bar to be lockedcursor c foobar is select foo bar fromfoo barwhere fooid barfoo idfor update of what should i put hereit seems like i need to specify individual columns but i want the entire record of foo to be locked eg i wish i could do something likecursor c foobar isselect foo bar fromfoo barwhere fooid barfoo idfor update of foodo i have to enumerate every column of foo in the for update of section in order to lock them all or can i arbitrarily choose any column in foo even those which are not its primary key and it will lock the entire record,['sql'] +68728,video thisplay with opengl i want to thisplay very high resolution video directly with openglthe image data is going to be processed on the gpu and i want to avoid a roundtrip back to the pc to show the video in a standard bitmap based windowcross platform is nice windows only would be ok so would nvidia onlyanyone have any links to ways doing this there is a poor nehe tutorial and a few examples for embedded opengl widgets in qt but i need much better performance and much larger images,['c++'] +68748,what is the c static fields naming convention i have recently started using resharper which is a fantastic tool today i came across a naming rule for static fields namely prefixing with an underscore ie private static string mystringis this really the standard way to name static variables if so is it just personal preference and style or does it have some sort of lower level impact eg compilation jit etcwhere does this style originate from i have always associated it with c is that correct,"['c#', '.net']" +68761,why cannot my subclass access a protected variable of its superclass when it is in a different package i have an abstract class relation in package databaserelation and a subclass of it join in package databaseoperations relation has a protected member named mstructure in joinpublic joinfinal relation relleft final relation relright super mrelleft relleft mrelright relright mstructure new linkedlistheader thiscopystructuremrelleftmstructure for final header header mrelrightmstructure if mstructurecontainsheader mstructureaddheader on linesthiscopystructuremrelleftmstructureandfor final header header mrelrightmstructure i get the following errorthe field relationmstructure is not visibleif i put both classes in the same package this works perfectly can anyone explain this issue,['java'] +68762,ssh connection with java how can i connect to an ssh server in java i do not needwant a shell i just want to connect to the ssh server and get the content of say filetxt how can i do that,['java'] +68767,external delaration for an array i have an array defined in a file and in another i have to use it for eg ac defines an array int a 123456789 bc declare and use it define count sizeof asizeof intextern int a size of arrayint ifori0 icount i printfd ainow when i try to compile it it gave me error saying that sizeof cannt be used on incomplete typecan anybody tell me how to handle such case in cc i do not want to array subscript in acthanks in advance,['c'] +68787,java virtual machines jvm and their performance comparison i was wondering if there somebody knows if there are some benchmarks which compare the following jvmssun jvm vs openjdk jvm vs rockit jvm vs j9 jvm vs apache harmonywhich one is has the best performance,['java'] +68793,where can i download a nonminified version of jquery ui i am trying to customize the autocomplete comboboxwith the intent of using it for nested lists with flyouts starting this with the minified version of jquery ui is obviously not ideal the download builder only provides minified downloads,['jquery'] +68805,calling original method with moq i have a productrepository with 2 methods getallproducts and getproductbytype and i want to test the logic at getproductbytype internally getproductbytype makes a call to getallproducts and then filters the correct onespublic virtual ienumerableproduct getallproducts returns all products in memory db etcpublic virtual ienumerableproduct getproductsbytypestring type return from p in getallproducts where ptype type select ptolistso in my test i would like to mock the call to getallproducts so it returns a list of products defined at my test and then call the original getproductsbytype which will consume the mocked getallproductsi am trying something like the code below but the original getproductbytype is not executed it is mockedout as well in typemock i have a calloriginal method that fixes this but i cannot figure it out with moq any ideasvar mock new mockproductrepositorymocksetupr rgetallproductsreturnsnew listproduct p1 p2 p3var result mockobjectgetproductsbytypetype1assertareequal2 resultcount,['c#'] +68813,create and use html full text search index c i need to create a search index for a collection of html pages i have no experience in implementing a search index at all so any general information how to build one what information to store how to implement advanced searches such as entire phrase ranking of results etci am not afraid to build it myself though i would be happy to reuse an existing component or use one to get started with a prototype i am looking for a solution accessible from c preferrably without requiring additional installations at runtime the content is static so it makes sense to aggregate search information but a search might have to accumulate results from multiple such repositoriesi can make a few educated guesses though create a map word pages for all relevant words a rank can be assigned to the mapping by promincence h1 h2 p and proximity to top advanced searches could be built on top of that searching for phrase homo sapiens could list all pages that contain homo and sapiens then scan all pages returned for locations where they occur together however there are a lot of problematic scenarios and unanswered questions so i am looking for references to what should be a huge amount of existing work that somehow escapes my googlefuedit for bountythe best resource i found until now is this and the links from there i do have an imlementation roadmap for an experimental system however i am still looking forreference material regarding index creation and individual steps available implementations of individual stepsreusable implementations with above environment restrictions,"['c++', 'html']" +68844,submit search query get search result without refresh i want to submit search query form get search result without redirectingreloadingrefreshing on the same pagemy content is dynamic so can not use those submit contact form without refreshing page which replies back on success,"['php', 'javascript', 'jquery']" +68849,finding matching string from javascript array i have one array of strings i need to find all strings starting with a keyfor eg if there is an array appleapeopensoapwhen searched with a key api should get apple and ape only and not soap this is in javascript,"['javascript', 'jquery']" +68867,how can i get href links from html using python import urllib2website websiteopenwebsite urllib2urlopenwebsitehtml getwebsitereadprint htmlso far so good but i want only href links from the plain text html how can i solve this problem,"['python', 'html']" +68877,how do i change column type in heroku i am trying to rake the dbmigrations into my heorku instance and i get an error the faq described my error as belowcannot change column typeexample pgerror error column averified ata cannot be cast to type adateacause postgresql doesnat know how to cast all the rows in that table to the specified type most likely it means you have an integer or a string in that columnsolution inspect your records and make sure they can be converted to the new type sometimes itas easier to just avoid using change column renamingcreating a new column insteadhow do i change this migration now this is the problem that i have for my contacts table i created the following tstring date enteredin a later migration i do the following change column contacts date entered datethis change column appears to be the problemshould ichange by hand that migration is there a way i can clean the data in my tables i did not know heroku would recognize the data in the table because i am doing a rakei obviously need to change this value and it is used throughout my application thanksthis is what i am tryingthoughtsdef selfup change column contacts date entered date this fails in postgres so trying the same outcome rename column contacts date entered date entered old add column contacts date entered date remove column contacts date entered oldenddef selfdown add column contacts date entered old remove column contacts date entered rename column contacts date entered old date enteredend,"['ruby-on-rails', 'ruby']" +68880,accessing class member variables inside an event handler in javascript i have a quick question regarding the proper way to access javascript class member variables from inside of an event handler that class uses for examplefunction map thisx 0 thisy 0 bodymousemove functionevent thisx eventpagex is not able to access maps member variable x thisy eventpagey is not able to access maps member variable y rather than changing the member variable of the map class the thisx in the event handler tries to affect the x member variable of the element that triggered the event what is the proper way to access the member variables of the map class from within the event handlersany help would be greatly appreciated i have been sort of scratching my head at this onecheerscharlie,"['javascript', 'jquery']" +68888,how to thiscover network devices with cocoa touch i want to be able to enumerate the names of devices on a local network from a device running iphone os 3x iphoneipadi have tried using nsnetservicebrowser to find all services like soservicebrowser searchforservicesoftype services dnssd udp indomainlocalthis returns results but when i try and resolve the addresses i get the following errors backnsnetserviceserrorcode 72004nsnetserviceserrordomain 10i have looked up the error and it appears there is a bad argumentkcfnetserviceerrorbadargumenta required argument was not provided or was not validif i do a service specific search like servicebrowser searchforservicesoftype ipp tcp indomain resolutions works fineso am i on the right track with nsnetservicebrowser or is there some other method that will allow me to enumerate the names of devices connected to my network,"['iphone', 'objective-c']" +68889,where to look up the date format specifiers used in cocoa cocoa touch for example dateformatter setdateformatymmdd hhmmssi guess there is a list somewhere that shows all those date format specifiers but cannot find any the nsdateformatter docs seem to not mention these,['iphone'] +68909,generic builtin eventargs to hold only one property i have a number of eventargs classes with only one field and an appropriate property to read itpublic class someeventargs eventargs private readonly foo f public someeventargsfoo f thisf f public foo foo get return thisf is there any builtin generic class to implement such behavior or i have to roll my ownpublic class genericeventargst eventargs private readonly t value public genericeventargst v thisvalue v public t value get return thisvalue psi wrote a suggestion on microsoft connect,"['c#', '.net']" +68937,query a subcollection of a collection with linq i have got a collection of products and each product object has it is own productimages collection each productimage object has a ismainimage bool field i am having a hard time building a linq query like thisselect productsproductimagesimagename where productsproductid 1 and productproductimagesismainimage truecan anyone help me figure this out point me to an online resource where i can learn about writing linq queries like this or boththank you for your help,['c#'] +68938,is there a mature way to interface erlang and postgresql or mysql i have searched the internet for drivers to connect to either database and all the projects i have seen have either been dead for a long time look incomplete or do not have good enough documentation to be usable without reading all the sourcehas anyone used erlang to talk to either mysql or postgresql before and what sort of package did you use to do this,['mysql'] +68941,userselect none and strange behaviour in firefox i am trying to prevent text highlighting in firefox for some but not all elements on the page consider the followingdiv stylemozuserselect nonei cannot be highlighted div stylemozuserselect text i should be highlightable but am not divdivas i understand it using the above css rules the text of the inner div should be highlightable however this does not appear to work in practice none of the text can be highlightedi am wondering if i am doing something wrong if not does anyone know of a workaround for this situationthanksps i should add that using the alternatewebkituserselect nonein the above example works just fine in webkit browsers,"['javascript', 'css']" +68943,echo command does not do anything i have been started studying php in my spare time and the first code example i was given was thisdoctype html public w3cdtd html 401 transitionalenhtml body php echo hello world bodyhtmlfrom what i understand this should write out hello world however all i see is a blank webpage any ideas why this is and how i should go about fixing it,['php'] +68946,xcode no debug symbols for certain subclass i am using xcode 323 and iphone sdkso i am trying to debug a uiview subclass i hit a breakpoint in an overridden method and i cannot see any symbols in either the gui or gdb just globals and registersthis is what i seegdb po selfno symbol self in current contextyet when i set a breakpoint in a uiviewcontroller subclass all the symbols are theregdb po selfmyviewcontroller 0x5c18ae0current language auto currently objectivecsome things i have triedclean allrebuild restart xcodechange between debug and releaseconfig these options in projectsettingsgcc debugging symbols allsymbols debug information format dwarf dwarf w dsym filebuild variants normal debugthreatening xcode by swearing at it and typingrm rf developer into a root bash promptplease help my fingers are bleeding from debugging with nslog,['iphone'] +68959,adding printf to the starting of all functions in a file i have some very large c files having lots of functions i need to trace the execution path at run time there is no way i can trace it through debugging as its a hypervisor code currently running over qemu and doing a lot of binary translationscan anyone point me to some script in perl or python which can add a printf at the starting of all functions and the text could be something like i am in function name,"['python', 'c']" +68968,auto screen rotation thisabling widget remoteview onclick event i have a bit of a strange bug with a widget i have coded after the screen rotates the widget stops responding to onclick events the code is exactly the same as in the android developer documentation for app widgets here i have noticed other widgets from the market do not have this problem is there a known workaround perhaps i have tried tapping all over the place after a rotation so i do not think its the onclickpendingintent not being resized after a rotation it does not seem to be present at alli cannot find an onrotation kind of trigger for the appwidgetprovider to redo the listening code in the event of a rotation so i am quite unsure how to proceedthanks,['android'] +68974,update java code during runtime about a year ago i stumbled across a nice feature in java that i cannot for the life of me find againthrough some magic interface it was apparently possible to declare some classes or functions replaceable during runtimei found a nice example guide of someone who ran a simple little program that printed a certain message he then updated the program using a method i cannot remember anymore and all of a sudden the program had replaced that old print function with a new onei have tried looking through the java api to spark my memory as well as googling but without success can anyone here help,['java'] +68975,css3 fade effect a float left width 32px height 32px textalign left textindent9px background urlimgbuttonpng norepeat 0 0 webkittransition background 300ms easein 2s property duration timingfunction delay moztransition background 300ms easein 2s otransition background 300ms easein 2s transition background 300ms easein 2s webkittransitionproperty background webkittransitionduration 300ms webkittransitiontimingfunction easein webkittransitiondelay 100ms moztransitionproperty background moztransitionduration 300ms moztransitiontimingfunction easein moztransitiondelay 100ms otransitionproperty background otransitionduration 300ms otransitiontimingfunction easein otransitiondelay 100ms transitionproperty background transitionduration 300ms transitiontimingfunction easein transitiondelay 100msahover backgroundposition 0 32px currently it has scroll updown effect but i want the background to change with fade effect what should i change in the cssthanks,['css'] +68986,what is the best way to free browser memory when working with large arrays in javascript this is how i have things setupcontainerhtmldatabase1js contains large array called database1database2js contains large array called database2heres a sample of the array shortened from 60 rows to 2var database1 20100103 074520100103 1100534ainstalled washing machine011indeed 20100320 150020100320 1600571finstalled oven051indeed etcetcetcwhen i append database1js to the head on the container the memory used for ie in windows jumps from 77mb to 219mb this is fine i can now loop though the array called database1 first row and column is at database100the problem is that i need to reappend the database file from time to time and in doing so the memory usage increases i thought the database array would be overwrittenso the first reappend pushes memory usage in ie up to 304mb but then continues to increase on each reappend 304mb 339mb 395mb 421mb etcto prevent this from happening i now clear each item in the array before i reappend the database1 filefor var i0 ildatabase1length iil i delete database1iappend database1js to head code herethis does help the memory usage does not decrease to the initial 77mb but does however decrease from 219mb to 141mb the next reappend increases the memory to 259mb clearing with the loop 188mb the next reappend increases the memory to 293mb clearing with the loop 245mbi am glad the memory usage is not climbing as fast but perhaps this can be optimized further unfortunately reloading the html page is not an option,['javascript'] +69007,nonsequential substitution in sympy i am trying to use sympy1 to substitute multiple terms in an expression at the same time i tried the subs function2 with a dictionary as parameter but found out that it substitutes sequentiallyin asubsab bcout cthe problem is the first substitution resulted in a term that can be substituted by the second substitution but it should not for my cause any idea on how to perform the substitutions simultaneously without them interfering with each othereditthis is a real examplein 1 i x i y i z symboli x symboli y symboli zin 2 s x s y s z symbols x symbols y symbols zin 3 j is symbolj isin 4 t symboltin 5 substitutions 2 i x s z 2 i x s z cos2 pi j is t i y sin2 pi j is ti x i x cos2 pi j is t 2 i x s z sin2 pi j is ti y i y cos2 pi j is t 2 i x s z sin2 pi j is tin 6 2 i x s zsubssubstitutionsout7 i ycos2pij ist 2i xs zsin2pij istsin2pij ist 2s zi xcos2pij ist 2i xs zsin2pij istcos2pij istonly the appropriate substitution should happen in this case only the first one so the expected output should be the followingin 6 2 i x s zsubssubstitutionsout7 i ysin2pij ist 2i xs zcos2pij ist,['python'] +69009,shorten the touch delay in a uiscrollview i am looking to shorten the touch delay on a uiscrollview but i do not want to use setdelayscontenttouchesno i still want there to be a slight delay but my users are complaining about it being too longis there a way to do this,"['iphone', 'ios']" +69011,finding maximum numeric value in nsarray i have an nsarray of nsnumbers and want to find the maximum value in the array is there any built in functionality for doing so i am using ios4 gm if that makes any difference,"['iphone', 'objective-c']" +69013,whats the best java web framework for my needs i am creating an web application for company intranet because other parts of this system are written in java so for integration purposes java was chosen as a web frontendthere are the requirementsit has to be simple to learn in short period of time it has to support mvc pattern no extended xml configuration application will consist of many form that user will fill and some js to help with it good ide plugins that will help with developmenti was thinking of wicketspring mvcstripeswhat are your recommendations regarding those requirements what other frameworks that are probably better for my application should i look atalso can you comment those three frameworks on how do they meet my requirements,['java'] +69024,sql sub queries is there a better way this is an sql efficiency question a while back i had to write a collection of queries to pull data from an erp system most of these were simple enough but one of them resulted in a rather ineficient query and its been bugging me ever since as there is got to be a better way the problem is not complex you have rows of sales data in each row you have quantity sales price and the salesman code among other informationcommission is paid based on a stepped sliding scale the more they sell the better the commission steps might be 10 10 10 and so forth the real world problem is more complex but thats it essentially itthe only way i found of doing this was to do something like this obviously not the real queryselect qty price salesman select top 1 percentage from comissions where comisionessalesman saleslinessalesman and saleslinesqty comisionesqty order by comissionesqty desc percentagefrom saleslines this results in the correct commission but is horrendously heavy is there a better way of doing this i am not looking for someone to rewrite my sql more take a look as foobar queries and i can take it from therethe real life commission structure can be specified for different salesmen articles and clients and even sales dates it also changes from time to time so everything has to be driven by the data in the tables ie i cannot put fixed ranges in the sql the current query returns some 340 rows and takes around 2030 secs luckily its only used monthly but the slowness is kinda bugging methis is on mssqlianediti should have given a more complex example from the beginning i realize now that my initial example is missing a few essential elements of the complexity apologies to allthis may better capture itselect clientcode product productfamily qty price thiscount salesman select top 1 percentage from comissions where comisionessalesman saleslinessalesman and saleslinesqty comisionesqty and a collection of conditions which may or may not apply exclude rows if the salesman has offered thiscounts above max thiscounts which appear in each row in the commissions table there may be a special scale for the product family there may be a special scale for the product there may be a special scale for the client a few more cases order by the user can control the order though a table which can prioritize by client family or product it normally goes from most to least specific percentage from saleslines needless to say the real query is not easy to follow just to make life more interesting its naming is multi language thus for every row of salesline the commission can be different it may sound overly complex but if you think of how you would pay commission it makes sense you do not want to pay someone for selling stuff at high thiscounts you also want to be able to offer a particular client a thiscount on a particular product if they buy x units the salesman should earn more if they sell morein all the above i am excluding date limited special offers i think partitions may be the solution but i need to explore this more indepth as i know nothing about partitions its given me a few ideas,['sql'] +69034,alertdialogbuilder no items for checkboxes are shown i have a problem with the alertdialogbuilder in the following code public void showsettingsbox final charsequence items item1 item2 item3 final boolean checked new booleanfalsefalsefalse alertdialogbuilder builder new alertdialogbuilderflabyrinthgame buildersetmessagefmessage setcancelablefalse setmultichoiceitemsitems checked new onmultichoiceclicklistener override public void onclickdialoginterface dialog int which boolean ischecked charsequence text item number which int duration toastlength short toast toast toastmaketextflabyrinthgame text duration toastshow setpositivebuttonapply new dialoginterfaceonclicklistener public void onclickdialoginterface dialog int id dialogcancel buildersettitleftitle builderseticonrdrawableicon exclamation alertdialog alert buildercreate alertshow the three items and checkboxes are not thisplayed there is just one white line between the title bar and the applybutton does anybody know why this does not work,['android'] +69060,why are private virtual methods illegal in c coming from a c background this came as a surprise to me in c it is good practice to make virtual functions private from guideline 2 prefer to make virtual functions privatei also quote eric lipperts blog from knightsknavesprotectedandinternal private virtual methods are illegal in c which irks me to no end i would totally use that feature if we had iti understand that in c you wouldnt be able to override a private virtual method in a derived but not nested class why is this the case in c the access specifier has nothing to do with whether you can override a function or not,['c#'] +69066,what are the good and bad points of transactionscope what are the good and bad points of the transactionscope class in cthanks,"['c#', '.net']" +69074,preventing compilers from defining copy constructors and operator overload for c classes is there a way by which we can prevent compilers from defining copy constructors operator overload for c classes,['c++'] +69075,how to define a class in only one line i tried class x begin endand class x neight correct what is the right code,['ruby'] +69076,when are global static const variables being initialized i tried to search the site for this question but did not find this exactly although this subject is being thiscussed a loti have this declaration in a cpp file not within any functionstatic const char gtext xalthough it has a fixed size i get a warning from a static analysis tool klocwork when i am trying to copy it to another char variable about possible out of bounds violationchar xtext32securezeromemoryxtext 32memcpyxtext gtext strlengtextis it a false positive or is the global variable being initialized laterthanks,['c++'] +69096,sql performance comparison for exclusion join vs not in i am curious on the most efficient way to query exclusion on sql eg there are 2 tables tablea and tableb which can be joined on 1 column col1 i want to thisplay the data of tablea for all the rows which col1 does not exist in tableb so in other words tableb contains a subset of col1 of tablea and i want to thisplay tablea without the data that exists in tableblet us say tableb has 100 rows while tablea is gigantic more than 1m rows i know not in not exists can be used but perhaps there are more efficient ways less comp time to do it i do not maybe with outer joinscode snippets and comments are much appreciated,['sql'] +69110,facebook pythonsdk vs pyfacebook i am starting to develop a facebook application using djangoi am trying to choose the appropriate api wrapper for my application and i cannot decide whether to use pyfacebook very well documented but no official release or the official facebook python sdk which is surprisingly poorly documented are there any major differences between the two that i am missingthank youliz,['python'] +69119,the importance of using instead of in php today only i have noticed and found out the importance of using operator you can see it in the following examplevar0if varfalse echo true else echo false prints truevarfalseif varfalse echo true else echo false prints truevar0if varfalse echo true else echo false prints falsevarfalseif varfalse echo true else echo false prints true the question is that are there any situations where it is important to use operator instead of using operator,['php'] +69125,what is the idiomatic way of performing an integer conversiontypecast in javascript another question asked about the meaning of the code snippet a 0 in javascript it turns out that it is a clever way of ensuring that a variable is a unsigned 32bit integerthis is pretty neat but i do not like it for two reasons the intent of the expression is not clear at least not to meit does not work for negative numbersthis leads me to ask what is the most idiomatic way of converting an arbitrary value to an integer in javascript it should work for signed integers not just nonnegative numbers cases where this breaks due to the fact that integers are just floats in thisguise in javascript are acceptable but should be acknowledged it should not return undefined or nan in any case these are not integers but return 0 for nonnumeric values,['javascript'] +69136,how often should i save to core data i am working on an application backed by core dataright now i am saving the object context as and when i add or delete an entity to and from the context i am afraid it will affect the performance so i was thinking of delaying the savein fact i could delay it all the way until the application is gonna terminateis it too risky to save the data only when the application is about to close how often should i call the save on object contexti was thinking of having a separate thread handle the save it will wait on a semaphore every time any part of the application calls a helperutil method to save the core data it will decrement the semaphore when it is down to zero the save thread will do a save once and it increments the semaphore to a say 5 and then sleep againany good recommendationthanks,['iphone'] +69141,configure ssl to work with java web app on tomcat 55 server this is a bit of a noob question but what do i need to get ssl working in my java web application standard sort of java web app using stripes for its mvc implementation spring and hibernatei am deploying my war file on tomcat 55 i only want ssl to be used for certain urls any that are transferring the users password so account registration change password and logindo i just need to get an ssl cert and install it in tomcat how do i ensure https is used for only some urls,['java'] +69151,remove i want to remove this google analytics block using jqueryscript typetextjavascript var gajshost https documentlocationprotocol httpsl httpw documentwriteunescape3cscript src gajshost googleanalyticscomgajs typetextjavascript3e3cscript3escriptscript typetextjavascript try var pagetracker gat gettrackerx pagetracker trackpageview catcherr scriptthe reasonbecause i am creating a bespoke screen reader convertor for jquery based on a client specification it is the google analytics that is bugging methe problemit works with remove until you navigate away then press back google analytics hangs,"['javascript', 'jquery', 'html']" +69161,is there a good frequently updated well written news site for c developers preferably with a altnet bent i would love to visit a web site and catch up on the latest c news microsoft framework and other altnet newsis there something out there that offers a bit of editorial or is aggregating blog feeds into google reader the only solutionthe only thing that i am aware of that comes close to my requirements isdotnetkicks lack of editorial no ability to customise a home page to filter interests to create pseudo editorialvisual c developer center team and community blogs again no real editorialrelated postswhere to read about programming not c specific,['c#'] +69163,post a file string using curl in php i was wondering if it is possible to post a file along with other form data when the file is just a stringi know that you can post a file that is already on the filesystem by prefixing the filepath with however i would like to bypass creating a temporary file and send just the file as a string but i am unsure how to construct the request using curl in phpcheers postfields array otherfields yes filename my filecsv data comma seperated content options array curlopt returntransfer true curlopt ssl verifypeer false curlopt ssl verifyhost 1 curlopt postfields postfields curlopt httpheader array contenttype multipartformdata,['php'] +69183,what algorithms to use for image downsizing what algorithms to use for image downsizing what is fasterwhat algorithm is performed for image resizing specially downsizing from big 600x600 to super small 6x6 for example by such giants as flash and silver player and html5,"['c++', 'c']" +69193,sql server how to grant read access to all databases to a login i need to give a new login read access to all 300 databases on a server how can i accomplish this without checking 300 checkboxes in the user mapping area,['sql'] +69198,the source file is different from when the module was built this is driving me crazy i have a rather large project that i am trying to modify i noticed earlier that when i typed dbcommand visual studio did not do any syntax highlighting on it and i am using using systemdatacommoneven though nothing was highlighted the project seemed to be running fine in my browser so i decided to run the debugger to see if things were really working as they should beevery time the class that did not do the highlighting is called i get the the source file is different from when the module was built message i cleaned the solution and rebuilt it several times deleted tmp files followed all the directions here getting the source file is different from when the module was built restarted the web server and still it tells me the source files are different when they clearly are not i cannot test any of the code i have written today because of this how can the source be different than the binary when i just compliedit is there any way to knock some sense into visual studio or ami just missing something,['c#'] +69202,opencv findcontours function problem i am trying to use the findcontours function in opencv but vs 2008 gives an error saying opencv error bad flag parameter or structure field unrecognized or unsupported array type in unknown function file ocvopencvsrccxcorecxarraycpp line 2476this application has requested the runtime to terminate it in an unusual wayplease contact the applications support team for more informationpress any key to continue heres the codemat vecfloat3 originalimagemat vecfloat3 resultingimagevectorvectorcvpoint voriginalimage cvimreadoriginalppmcvfindcontoursoriginalimagevcv retr listcv chain approx nonethanks in advance,['c++'] +69254,using aspnet mvc data annotation outside of mvc i was wondering if there is a way to use aspnets data annotation without the mvc sitemy example is that i have a class that once created needs to be validated or will throw an error i like the data annotations method instead of a bunch of if blocks fired by the initaliseris there a way to get this to worki thought it would be something likeadd data annotationsfire a method in the initialiser that calls the mvc validator on the classany ideas i must admit i havent added the mvc framework to my project as i was hoping i could just use the data annotations class systemcomponentmodeldatavalidation,['c#'] +69263,in jquery what does fn mean in jquery what does fn mean i looked this up on google but could not find any concrete examplesfnsomething function,['jquery'] +69267,less css and font shorthand i noticed an issue when using less css with font shorthandfontweight 300 size 22px height 32px font weight sizeheight helvetica neue arial liberation sans freesans sansserifthe above fails withthisatocss is not a functionhttplocalhosttumblrmodern1cstyleless on line 1 column 01 highlight cb1e162 shade1 cb1e16when i split the properties up it worksfontweight 300 size 22px height 32px fontweight weight fontsize size lineheight height fontfamily yanone kaffeesatz helvetica neue arial liberation sans freesans sansserifi think its because of the slash thats causing the problem i think since less css can do calculations eg 2px 5 7px its trying to do a divide,['css'] +69268,store multiline text in a javascript variable ho to store multiline text in a javascript variablei am using php to assign value to javascript variableplease see a sample code belowhtml head title new document title php foo this is a multiline statement script bar php print foo alertbar script head body bodyhtmli do not want to loose any whitespace charactershow can this be done,['javascript'] +69276,android loading an image from the web with asynctask how do i replace the following lines of code with an asynctask how do you get back the bitmap from the asynctask thank youimageview mchart imageview findviewbyidridchartstring url httpwanything mchartsetimagebitmapdownload imageurlpublic static bitmap download imagestring url bitmap bm null try url aurl new urlurl urlconnection conn aurlopenconnection connconnect inputstream is conngetinputstream bufferedinputstream bis new bufferedinputstreamis bm bitmapfactorydecodestreambis bisclose isclose catch ioexception e logehuberror getting the image from server egetmessagetostring return bm i thought about something like this replace mchartsetimagebitmapdownload imagegraph urlby something like mchartsetimagebitmapnew downloadimagestaskexecutegraph urland public class downloadimagestask extends asynctaskstring void bitmap overrideprotected bitmap doinbackgroundstring urls return download imageurls0overrideprotected void onpostexecutebitmap result mchartsetimagebitmapresult how do i pass a reference to mchart here private bitmap download imagestring url bitmap bm null try url aurl new urlurl urlconnection conn aurlopenconnection connconnect inputstream is conngetinputstream bufferedinputstream bis new bufferedinputstreamis bm bitmapfactorydecodestreambis bisclose isclose catch ioexception e logehuberror getting the image from server egetmessagetostring return bm but how do i pass a reference to mchart in onpostexecutebitmap result do i need to pass it with the url in some way i would like to replace all my lines of code mchart1setimagebitmapdownload imageurl 1mchart2setimagebitmapdownload imageurl 2with something similar but in asynctask way mchart1setimagebitmapnew downloadimagestaskexecutegraph url 1mchart2setimagebitmapnew downloadimagestaskexecutegraph url 2is there an easy solution for this do i get something wrong here,['android'] +69278,jquery based file explorermanager is there a demo of jquery based file explorer or manager similar to windows explorer,['jquery'] +69280,getting the value of a html5 number input i am using one of the new html5 input types numberinput typenumber in opera which is the only desktop browser i know of which currently recognises it it renders it as suchthe problem i am facing is one of validation if a user types something invalid into the field eg abc the value returned by myinputvalue is an empty string this makes it impossible to tell whether the user left the field blank or if they entered some incorrect data is there any way to get the real value of the field,['javascript'] +69291,recv socket function returning data with length as 0 i am having an application which established a socket connection on a port number 5005 with another devicehardware device with a web server now if my hardware device thisconnects then i loose connection with the device does this mean that the socket i wasusing until now becomes invaliddo i get any special message likenull character or something whenthis thisconnect happensif the socket connection i washaving became invalid then whydoesnt the recv socket functionthrow and socket error insteadwhy do i receive data of 0lengththanks,['c++'] +69292,why do we use rtjar in a java project what is the necessity of rtjar,['java'] +69297,jqgrid horizontal scrollbar i developed ajax interface with jquery and jqgridhow i can remove horizontal scrollbar from my jqgrid tableif i set autowidth true then i get width of table sum width of columns but i need width of table width of parent element with id returned by function getselectedtabhrefso i make functionwindowbindresize function taskssetgridwidthgetselectedtabhrefwidth taskssetgridheightwindowheight190triggerresizeand here is how i create jqgrid tabletasksjqgrid datatype local colnameslabelstasksnumlabelstasksaddedlabelstasksacceptedlabelstasksoperatorlabelstasksclientlabelstasksmanagerlabelstasksdesc colmodel nametaskid indextaskid width1 alignright nametaskadded indextaskadded width3 nametaskoperator indextaskoperator width4 nametaskclient indextaskclient width7 nametaskmanager indextaskmanager width4 nametaskdesc indextaskdesc width8,['jquery'] +69304,jquery find all elements with text what would be the best way to scan trough all the dom find any element that have text and wrap it in a span classthanx,['jquery'] +69340,what is the best way to store binary data images pdfs mp3s videos ect in mysql and why what is the best way to store binary data images pdfs mp3s videos ect in mysql and why what i would love to know is how you do itas developers and why also how the big sites do itthank you in advance,"['php', 'mysql', 'sql']" +69343,system idle detection i want to detect if the system is idle ie user not using the system i want it like the windows live messenger it changes automatically to away when i leave the computer for a time like 3 minutes i want to set this time within the codeim working on the wpf under c environment using both visual studio 2008 and 2010 so if here is a way that work on both thatll be great,['c#'] +69348,how to check for key in a map irrespective of the case i want to know whether a particular key is present in a hashmap so i am using containskeykey method but it is case sensitive ie it does not returns true if there is a key with name and i am searching for name so is there any way i can know without bothering the case of the keythanks,['java'] +69359,browser extension to replace javascript file on a live site for testing i am looking for a browser extension firefox chrome allowing to replace a javascript file on a live web site to do some testinghackingbasically it should take a url and load another one instead locally or on a http development serverany idea,['javascript'] +69364,check for linebreaks in textarea with jquery i want something like a counter for every linebreaks in a textarea this is used when uploading a huge number of webbanners so i need a simple counter for how many a user has added right now the counter works only when a user presses a link with a special bannersizethis is my code as it is right nowvar i 0sizeclickfunctiontotalnumbertextireturn false,['jquery'] +69399,iphone nsdateformatter timezone conversion i am trying to create a formatter that will convert the date format shown to an nsdate objectnsstring datestr 20100621t190500nsdateformatter dateformat nsdateformatter alloc initdateformat setdateformatymmddthhmmssznsdate date dateformat datefromstringdatestr the issue is the timezone 0500 which is not parsed properly with the format above any suggestions,['iphone'] +69405,how to monitorshow progress during a c sort i am planning to write an interactive c geometry processing plugin that will frequently sort large amounts of data although preliminary indications are that the sort will take only a second or two i would prefer to show progress during that time ie i would like to update a progress indicator a few times per second this would be preferable to turning on a wait cursor and leaving the user with a program the freezes for an indeterminate length of time even if that is just a few secondsif i were to use something like stdsort i could use the comparison function to update the progress indicator every now and then but i would have no idea of percentage complete i could also break the sort down into subsorts updating progress between subsorts and then merging my best bet may be to write own sort method although i do not know how much effort it would require to get performance as good as stdsort and ensure correctness in any case that sort method would occasionally send a percentage complete to a callback method i was wondering whether other people have encountered and solved this problem i am hoping that maybe there is a sort method in a standard library that does what i want or some other technique that i have not thought ofupdate thanks for the great answers so far there have been a few very good suggestions and i am going to hold off on choosing the accepted answer until i have had a chance to test out the ideas in my upcoming projectupdate 2 i completed my project and this turned out to be a nonissue at least for the customer since they will be selling the software they may still get feedback from their customers that will change their minds about this choosing an accepted answer was difficult because there were many good answers but in the end the one i chose pointed to a wiki article on merge sort that had a very evocative animation so that is the first strategy i would have pursued had i needed to go ahead with this,['c++'] +69409,create image from viewscreen in android is it possible to create a bitmap image from a view or the screen in android,['android'] +69413,convert plain text urls to html hyperlinks in ruby on rails i have a text area into which users enter a lot of text that potentially includes hyperlinks how can i thisplay the text and have the urls automatically appear as hyperlinks is there a gem plugin or existing method that does this i am looking to be able to do something likeh my objectdescriptionwith links in my view,['ruby-on-rails'] +69419,what exactly is super in objectivec as far as i know it is a pointer to the superclass it is hardwired with the superclass and not dynamically figured out at runtime would like to know it more in detailanyone,['objective-c'] +69421,creating a user in active directory a device attached to the system is not functioning consider this code attempting to create an active directory account it is generating an exception here with a certain set of data it is not clear right now whats causing the exception var user new userprincipalsomevalidusercontext xxyztfoofoobartest somepwd true useruserprincipalname usersamaccountname xxyztfoofoobartest userthisplayname some string 16 chars long username some string 16 chars long userdescription foo barbaz 12 more characters useraccountexpirationdate somedateinfuture userusercannotchangepassword true usersave exception thrown on save a device attached to the system is not functioningprincipaloperationexception was unhandled by user code a device attached to the system is not functioningwhats causing this exception and how can you work around it,['c#'] +69424,why would bufferedstreamwrite throw this stream does not support seek operations this one puzzles me i get an error about seek when i am not even calling iti have code that looks something like this send 42uint value 42byte msg bitconvertergetbytesvaluestreamwritemsg 0 sizeofuintand i get this exception systemnotsupportedexception was unhandledmessagethis stream does not support seek operationssourcesystemstacktrace at systemnetsocketsnetworkstreamseekint64 offset seekorigin origin at systemiobufferedstreamflushread at systemiobufferedstreamwritebyte array int32 offset int32 countstream is of type systemiobufferedstream what could possibly be going onedit with more infosizeofuintmsglength in this casethe stream is declared as stream new bufferedstreamnew networkstreamsocket 1024editthat was it while one can read and write on a single networkstream when switching to a bufferedstream it is necessary to have a separate one for reading and writing one can apparently just call the networkstream constructor twice on the same socket to get thati would accept both justin and hans answers if i could because one let me exactly understand what was wrong and the other led me to the solution thanks everyone,['c#'] +69460,add a temporary column with a value i have a select statement like thisselect field1 field2 from table1what i want is to have a newfield with only value examplenewfield does not exist in the table but when i run this query it kinda makes a virtual column with the values of example field,"['sql', 'mysql']" +69469,what are the best lightweight solutions for drag and drop i love and use jquery quite a lot but i am hoping to find an alternate solution for a special projecti am creating a bookmarklet which will interface with my application to allow users to enter information much quicker one of the greatest pains in my application at the moment is uploading images users understandly hate the process of downloading images to their computers in an organized fashion and then uploading them to the appwhat i would love the bookmarklet to do is load in a small div overlay with a couple small controls in it including one which would allow the user to drag and drop images from the current page into the control the script would then collect the uris of those img tags and submit them along with the form to the app and then they would automatically be downloaded by the server into the appso for this task loading jquery and jquery ui into the page every time you click the bookmarklet seems like a very heavyhanded approachcan anyone recommend a nice lightweight javascript toolkit that handles drag and drop functionality and nothing elsei was excited to read about the new dragdealer tool which looks awesome just today on ajaxian but it seems that it is built to handle only dragging and not dropping ie not targets,['javascript'] +69481,ios 4 wireless app thistribution for inhouse applications according to the apple website ios 4 should support wireless app thistribution i have been unable to find any documentation at all on how to host your applications for users to download them over wifi3g we are currently enrolled in the standard iphone dev program as we do not have over 500 employees is this limited feature limited to the enterprise program only,['iphone'] +69485,how to deal with duplicated function name within c i have a little project in which i named two same name function in two different source file but while i building the project the compiler failed with func name already defined in filenameobjwhy could not i have two functions with the same name in two different source files i thought the function should be local to the source file only if when we declared it in the header file will it become globaland except for changing the filename are there any other elegant solution to duplicated function name in the c programming language,['c'] +69498,thisplayinline vs thisplayblock what is the basic difference between this cssthisplayinlineand thisthisplayblockusing these separately on an element i get the same result,['css'] +69516,is the following code a rock solid way of creating objects from a singleton i have stumbled accross this code in production and i think it may be causing us problemsinternal static readonly myobject instance new myobjectcalling the instance field twice returns two objects with the same hash code is it possible that these objects are differentmy knowledge of the cli says that they are the same because the hash codes are the samecan anyone clarify please,['c#'] +69519,which javascript files are not being used on page load is it possible to find out which javascript files are not used on a web page without having to add console logs or debug or removing them to see if things breaki am looking for a tool or a command line script or firefox plugin etcfor example lets say i have these included in the headerscript typetextjavascript srcjsjqueryjsscriptscript typetextjavascript srcjsfunctionsjsscriptscript typetextjavascript srcjsvalidationjsscriptscript typetextjavascript srcjssomethingjsscripton the page calls are only made to functions in functionsjs validationjs and jqueryjs how can i know that somethingjs is not used and therefore can be safely removed from the headeri have tried rooting through things like firebug chromes console yslow and server logs but these all tell me which scripts have been loaded eg all of them not which ones have been used,['javascript'] +69520,clickonce error the deployment identity does not match the subscription i am using visual studio 2008 sp1i have a windows forms application deployed internally using clickonce in a shared folder on the local networkthe test certificate pfx expires in 2035i have published the update to the internal shared folder several timesnote that the project is only set to sign the clickonce manifests and does not sign the assemblynow i again publish a new version of my applicationwhen users click on their icons to run the application we get this error it had always updated prior to deploying with the test certificatedireccia3n url de la implementacia3n filecdocuments20and20settingsusuarionotarias3menc3ba20inicioprogramasgrupobackupexpediente20electrc3b3nicoapprefms7c direccia3n url del proveedor de la implementacia3n file192168131compartidaadministradorwinapplication la activacia3n de cdocuments and settingsuseuarionotarias3menao inicioprogramasgrupobackupexpediente electra3nicoapprefms dio como resultado una excepcia3n se detectaron los siguientes mensajes de error the deployment identity does not match the subscription operation progress status 2202008 112321 am activation of cdocuments and settingsusuarionotarias3menao inicioprogramasgrupobackupexpediente electra3nicoapprefms has started 2202008 112321 am performing necessary update check as specified by the deployment error details21062010 203310 systemdeploymentapplicationdeploymentexception subscriptionstate la identidad de la implementacia3n no coincide con la suscripcia3n origen systemdeployment seguimiento de la pila en systemdeploymentapplicationsubscriptionstorecheckupdateinmanifestsubscriptionstate substate uri updatecodebaseuri assemblymanifest deployment version currentversion en systemdeploymentapplicationapplicationactivatorperformdeploymentupdatesubscriptionstate substate string errorpageurl en systemdeploymentapplicationapplicationactivatorprocessorfollowshortcutstring shortcutfile string errorpageurl tempfile deployfile en systemdeploymentapplicationapplicationactivatorperformdeploymentactivationuri activationuri boolean isshortcut string textualsubid string deploymentproviderurlfromextension browsersettings browsersettings string errorpageurl en systemdeploymentapplicationapplicationactivatoractivatedeploymentworkerobject state i use regedit to search for this keyhkey current usersoftwaremicrosoftwindowscurrentversionuninstall7e3a7433abfe6213pc non updatedappidfile192168131compartidaadministradorwinapplicationadministradorwinapp cultureneutralpublickeytoken4b005ceeffd565b0 processorarchitecturemsilversion 10014filename expediente electra3nicopublisher grupobackupfolder name grupobackuppc updated uninstallreinstall but i want to avoid itappidfile192168131compartidaadministradorwinapplicationadministradorwinapplication cultureneutralpublickeytoken4b005ceeffd565b0 processorarchitecturemsilversion 10030filename expediente electra3nicopublisher grupobackupfolder name grupobackupsuitename ogf suitechanges pc non updated pc updated are1suite name is new value i set it in properties publish tab in visual studio2versionand 3administradorwinappfrom file192168131compartidaadministradorwinapplicationadministradorwinappvsadministradorwinapplicationfromfile192168131compartidaadministradorwinapplicationadministradorwinapplicationif i uninstall and then reinstall the app from scratch it all works however i was trying to avoid having to do thisi get this error when i try to deploy a project that was previously successfuli retried after deleting all the manifests but still no joyis there a way to fix thisin publish options manifestsuse application manifest for trust information is un checked,['.net'] +69529,what is concrete implementation i saw lot of posts in stackoverflow and elsewhere talking about concrete implementation while fiddling with wcf i came through the linetying your service implementation or any aservice baseda class to a concrete implementation is never a good ideacan anyone explain what concrete implementation is,['.net'] +69565,jquery tristate checkbox i am trying to find a tristate checkbox plugin however every plugin i find relies on a hierarchy like a folder structure of elements i just have a single checkbox element that i want to make a threeway checkbox does anyone know of a jquery plugin that will do this i am really surprised i did not find one that works on thank you for your input,['jquery'] +69593,inject array of interfaces in ninject consider the following codepublic interface ifoo public class bar public barifoo foos public class mymodule ninjectmodule public override void load bindifootoconstantnew ifoo0 toconstant is just an example public class program private static void mainstring args var kernel new standardkernelnew mymodule var bar kernelgetbar when i try to run the program i get the following exceptionerror activating ifoo no matching bindings are available and the type is not selfbindable activation path 2 injection of dependency ifoo into parameter foos of constructor of type bar 1 request for barhow can i inject bind to an array in ninjectthanks for your timeeditmy application imports data which is created by a third party componentthe import process applies different kind of filters eg implementations of different filter interfaces the rules for filtering change quite often but are too complex to be done with pure configuration and a master filteri want to make addingediting filters as easy as possible what i have is an assembly where all the filter implementations are located in i tried to bind every filter interface to the following method which provides an instance of every implementation of that filter type basically i want to avoid the need to change my ninject module when i addremove filter classes private ienumerabletinterface getinterfaceimplementationstinterfaceicontext context return gettypeassemblygettypes wheret typeof tinterfaceisassignablefromt isconcreteclasst selectt kernelgettcasttinterface i am feeling a bit guilty in terms of bypassing the containers di mechanism is this a bad practice is there a common practice to do such thingsresolutioni use a wrapper class as bsnote suggested,"['c#', '.net']" +69600,net vs aspnet vs clr vs asp although i know the terms i used to forget the differences sometimesso just to maintain a place for referencethanks all for your answers,"['.net', 'asp.net']" +69606,html title image i want to have an image on the title in an html page ie on the tab along with the title how can i do thatthank you for reading,['html'] +69612,is there a elegant way to parse a word and add spaces before capital letters i need to parse some data and i want to convertautomatictrackingsystemtoautomatic tracking systemessentially putting a space before any capital letter besides the first one of course,"['c#', '.net']" +69613,how do i get first element rather than using 0 in jquery i am new to jquery apologies if this is a silly questionwhen i use it find an element using the id i know theres always one match and in order to access it i would use the index 0 is there a better way of doing thisfor egvar gridheader grid gridheader0,"['javascript', 'jquery']" +69614,how do you load a local jpeg or png image file into an iphone app or i should ask why is it so difficult for me the answer is probably that i am new to iphone development and i am trying to ditch my old methods and step into the new platform of the future from start to finish i have a few questions about this processif i create a png image where does it go in my projects directory ie my computers hard drive can i put it anywhere on my hard drive and xcode will copy it in the right place when i load it into xcodeonce it exists on my hard drive somewhere how do i add it to my xcode project can i just drag the file into any folder in the groups files treeonce i drag it into xcode what copy settings do i want to use in that copy file dialog box that pops up copy items into destination groups folder checkbox reference type recursively create groups for added foldersonce the png image has properly been added to my project whats the easiest way to get it into an cgimageref the documentation shows an example using the cgimagecreatewithpngdataprovider helper method but says it is not supported by the ios sdk i would like to use the cgimageref for repeatedly drawing the image to a bitmap contextthanks so much in advance and i apologize for the lengthy question i am just surprised it is such a convoluted process compared to some other platforms,['iphone'] +69645,output values found in cursor to logcat android i am trying to debug an issue myself may post it later if i fail my logcat log states androiddatabasecursorindexoutofboundsexception index 1 requested with a size of 2i would like to use logvdesc cursor to show what the cursor returns is there a way to specify a value from it like cursor0,['android'] +69659,pattern for wrapping shell commands in a class despite its inadvisability using phps shell commands to interact with nonphp system commands remains a common way of quickly achieving certain results in web applicationshas anyone abstracted out the common use cases into a class library something in zend maybe that offers a more sanecommon way of handling this every time i encounter or have to produce this kind of code it is a bunch of procedural spaghetti copypasted over and over again i was wondering if hoping that the php community had come up with a better way of handling using command line applications in your webphp applications,['php'] +69662,how can i break referential integrity briefly within a transaction without thisabling the foreign key constraint i have a table with 3 columnsid parent id nameparent id has a foreign key relationship with id in the same table this table is modeling a hierarchysometimes the id of a record will change i want to be able to update a records id then update the dependent records parent id to point to the new idthe problem is when i attempt to update the id of a record it breaks the integrity and fails immediatelyi realize i could insert a new record with the new id then update the children then delete the old record but we have a lot of triggers in place that would get screwed up if i did thatis there any way to temporarily update the parent with the promise of updating the children obviously it would fail on commit without thisabling the foreign key briefly,['sql'] +69670,what are move semantics i just finished listening to the software engineering radio podcast interview with scott meyers regarding c0x most of the new features made sense to me and i am actually excited about c0x now with the exception of one i still do not get move semantics what are they exactly,['c++'] +69673,when is it ok to use an xml file to save information what reason could there be for using an xml to save information,"['c#', '.net']" +69675,align icons with text whats the best way to align icons left and text right or the opposite text on left and icon on rightdoes the icon image and text have to be the same size ideally i would like them to be different but be on the same vertical alignmenti am using backgroundposition css property to get the icons from a larger imagehere is how i do it now but i am struggling with either getting them to be on the same line or be vertically aligned to the bottom text this is what i get after i try your suggestionsthough the text is now aligned with the icon it is superimposed over the icon to the right of the icon that i want please note that i am using the background position to show the icon from a larger set of images basically i am getting icon10pxtext and unwanted icon to the right under itspan classgroup3 drops icon group3 l icon style50spangroup3 drops icon backgroundposition50px 1pxgroup3 l icon mozbackgroundclipbordermozbackgroundinlinepolicycontinuousmozbackgroundoriginpaddingbackgroundtransparent urlimagesgroup3png norepeat scroll left centerheight35pxoverflowhiddenpaddingleft55px,['css'] +69678,how is ruby fully object oriented so i am curious as to how ruby is a fully object oriented language i stumble over one problem that is not really clear to me if i define a function as followsdef footext print textendand i define the function outside of a class how is this function an object i realize that i can callfooclassand i get nilclass does this mean that foo is an instance of nilclass and if it is what does it mean exactly when i callfoo hello worldif foo is an object what method am i calling when i make the statement as above also if it an object does that mean i can modify it and add another method to it say bar where i could possibly make the following statmentfoobarsome variablessorry i am just a little confused on this point any clarification is very much appreciated thanks,['ruby'] +69680,really simple way to deal with xml in python musing over a recently asked question i started to wonder if there is a really simple way to deal with xml documents in python a pythonic way if you willperhaps i can explain best if i give example let us say the following which i think is a good example of how xml is misused in web services is the response i get from http request to xml api reply version1 weather module id0 tab id0 mobile row0 mobile zipped1 row0 section0 forecast information city datamountain view ca postal code data94043 latitude e6 data longitude e6 data forecast date data20100623 current date time data20100624 0254 0 unit system dataus forecast information current conditions condition datasunny temp f data68 temp c data20 humidity datahumidity 61 icon dataigimagesweathersunnygif wind condition datawind nw at 19 mph current conditions forecast conditions day of week datasat low data59 high data75 icon dataigimagesweatherpartly cloudygif condition datapartly cloudy forecast conditions weatherxml api replyafter loadingparsing such document i would like to be able to access the information as simple as say xmlxml api replyweatherforecast informationcitydatamountain view caor xmlxml api replyweathercurrent conditionstemp fdata68from what i saw so far seems that elementtree is the closest to what i dream of but it is not there there is still some fumbling to do when consuming xml otoh what i am thinking is not that complicated probably just thin veneer on top of a parser and yet it can decrease annoyance of dealing with xml is there such a magic and if not whyps note i have tried beautifulsoup already and while i like its approach it has real issues with empty elements see below in comments for examples,['python'] +69691,convert to stream from a url i was trying to convert an url to stream but i am not sure whether i am right or wrongprotected stream getstreamstring gazouurl stream rtn null httpwebrequest arequest httpwebrequestwebrequestcreategazouurl httpwebresponse aresponse httpwebresponsearequestgetresponse using streamreader sreader new streamreaderaresponsegetresponsestream systemtextencodingdefault rtn sreaderbasestream return rtnam i on the right track,['c#'] +69700,what is the maximum size of a cookie file are there any limitations on the size of the cookie also is this browser dependent,['asp.net'] +69712,in ruby is there a way to print out all the global variables and constants defined predefined in ruby is there a way to print out all the global variables and constants defined predefined,['ruby'] +69723,how do different retention policies affect my annotations can anyone explain in a clear way the practical differences between the javalangannotationretentionpolicy constants source class and runtimei am also not exactly sure what the phrase retaining annotation means,['java'] +69726,php53 call to undefined method error when calling invoke from class variable i have been doing some tests to replace old code with the invoke magic method and i am not sure this is a bug or notlets suppose we have a classclass calc function invokeab return ab the following is possible and works without any problemc new calck cecho k45 outputs 20however if i want to have another class to store an instance of that object this does not workclass test public k function construct c new calc thisk c just to show a similar situation than before thisk new calc produces the same error the error occurs when we try to call it liket new testecho tk45 error call to undefined method testki know that a solution could be to have a function inside the class test named k to forward the call using call user func array but that is not elegant i need to keep that instance inside a common class for design purposes and be able to call it as function from other classes any suggestionupdatei found something interesting at least for my purposesif we assign the class variable into a local variable it workst new testm tkecho m45,['php'] +69736,multitenant versus multiple dbs i am developing a custom crm solution which will be sold via the websaas model i anticipate tens or hundreds of clients using this solution i will be using ms sql as the db engine option 1 is to have a single db and include a tenantid column on tables a suitable index and use where tenantid on each db accessoption 2 is to have an individual db for each client avoiding the need for the tenantid and where clausesi anticipate that each client will have hundreds of thousands of records not millionsas i see it there will be a total number of data pages whichever option i go for the decision seems centered on whether sql is better at managing multiple dbs or a single db with tenantid and index initially the solution will run on a single db server but will eventually move to sandoes anyone have any views on this,['sql'] +69740,attacks on wpf applications what attacks or security vulnerabilities are specific to wpf applicationsto clarify i am not asking how to do sql injection on wpf apps or what kind of crypto should i use or i am also not specifically asking about flaws in the framework or in wpf itself rather flaws that might manifest based on improper implementationvery specifically i am interested on new attacks or new vectors that are particular to a client application implemented in wpf not specifically xbap clickonce related issues would be great too would be a good example though not particularly relevant to my specific need yet still a valid answer,['.net'] +69749,using 3digit color codes rather than 6digit color codes in css i recently went through my css file and switch all my 6digit hexadecimal codes to simple 3digit codes for example my fdfeff got shortened to f it renders pretty much the exact same color as before it seems to me that the in between parts are fairly useless and removing them saved me an entire 300 bytes in my css filedoes it matter which version you use i rarely ever run across websites that use only the 3digit codes or i guess i just never run across ones that do is it still perfectly valid to use 3digit codes over 6digit codes or are we supposed to use the full 6digit codes,['css'] +69756,logging in multithreaded application in java whats the best way and best tool for logging in multithreaded environment so that each thread has it is own logger instance and separate file is this even possible,['java'] +69767,user preferences in java ee application i have a growing web application which now needs to be able to store user and system preferences settings in the past i have always rolled my own preferences system for web applications but i was wondering what other people do to solve this problem are there any preference libraries for web applications that people could recommendideally user preferences should have a default value which the user can then override not all preferences should be exposed to the user though as some will be for things such as the last position of a dialog boxif i go the rollmyown route i think it will be a separate preferences table with all the preferences stored as strings converted to their true primitive data type as required eg a table something like keyuser keysetting namesetting value i favour this approach to a column per data type because it stops a setting from accidently ending up with two values and the consumer of a setting should know what data type they want,['java'] +69770,generate random numbers with probabilistic thistribution ok so heres my problem we are looking at purchasing a data set from a company to augment our existing data set for the purposes of this question let us say that this data set ranks places with an organic number meaning that the number assigned to one place has no bearing on the number assigned to another the technical range is 0 to infinity but from sample sets that i have seen it is 0 to 70 based on the sample it is most definitely not a uniform thistribution out of 10 there are maybe 5 places with a score over 40 50 with a score over 10 and 10 with a score over 1 before we decide to purchase this set we would like to simulate it so that we can see how useful it may beso to simulate it i have been thinking about generating a random number for each place about 150 random numbers but i also want to keep to the spirit of the data and keep the thistribution relatively the same or at least reasonably close i have been racking my brain all day trying to think of a way to do it and have come up emptyone thought i had was to square the random number between 0 and sqrt70 but that would favor both less than 1 and larger numbers i am thinking that he real thistribution should be hyperbolic in the first quadrant i am just blanking on how to turn a linear even thistribution of random numbers into a hyperbolic thistribution if hyperbolic is even what i want in the first placeany thoughtsso to sum heres the thistribution i would like approximately40 70 002 00510 40 05 11 10 10 200 1 remainder 7895 8948,['php'] +69772,should i use net systemnetmail to batch send my web applications emails or sql msdbsp send dbmail scenario1 my application is a net 35 c web app and the database is sql 20082 emails will be in the region of 100 to 10 a day and are triggered by various web user interactions with the app3 most emails will contain attachments between 50kb and 5mb some emails will be html and some will be plain text4 all attachments will be sourced from a directory on the web server5 the sql server is a separate machine to the web server all sql connections from the application are via sql logins not windows authentication6 for a scalable solution emails to be sent will be queued in a database table ready for a batch process to pickup failed emails should be retried up to 4 timesdilemma i am not sure whether to write a web server solution to send emails eg a windows service which polls the emails ready to send or maybe to use sql database mail which is easy to setup and use and does not require much developmentthe fact the attachments sit on the web server suggests to me to use a web server solution but i would be interested to see if i have missed something,"['c#', '.net', 'sql']" +69778,codestyle put javadoc before or after annotation i know that it is not the most vital of issues but i just realised that i can put the javadoc comment block before or after the annotation what would we want to adopt as a coding standard this is a javadoc comment before the annotation componentpublic class myclass autowired this is a javadoc comment after the annotation private myotherclass other,['java'] +69780,google maps api v3 no labels is there a way to turn off all labels street names state names country names etc from google maps using the api v3 or are these built directly into the map images,['javascript'] +69782,using web user controls instead of web forms i have been using aspnet c for the past two years i have learned so much but there is still much more to learn i have used masterpages web user controls for things like headers navigation footers etcone thing i have never truly understood is the practice of using web user controls for your content and logichomeaspx homeascxaboutusaspx aboutusascxorderingaspx orderingacsxi have been working with a few projects over the last few months that use this structure i am aware that this is actually common practice but i do not really understand the full benefitsi remember when i tried this approach before and ended up having awful viewstate problems with controls like the gridview once i took all the logic out and placed it into a aspx page everything worked finei realise now that maybe i needed to add the gridview to the viewstate collection but this only reinforces my difficulty into understanding why this approach is used given the viewstate problemi fully understand the advantages of web user controls in relation to things like headers menus footers etc anywhere that involves duplication but the projects i have seen have pagescontrols that are pretty specific in other words its unlikely to be reused anywhere else the aspx page just contains a control ascx with the content and logic and it will only be used on that page nowhere elseignoring code reuse what other benefits does this approach provide,['asp.net'] +69788,how to use reflection to call method by name hi i am trying to use c reflection to call a method that is passed a parameter and in return passes back a result how can i do that i have tried a couple of things but with no success i am used to php and python where this can be done on a single line so this is very confusing to mein essence this is how the call would be made without reflectionresponse servicecreateambiencerequestrequest has these objectsrequestuserid longconstantsdefaultambienceuseridrequestambiencecountryid longconstantsdefaultambiencecountryidrequestambiencenamedefaulttext stringconstantsdefaultambiencenamedefaulttextrequestambiencenamelanguagetext getculturetextlanguagetextstringconstantsdefaultambiencenameculture stringconstantsdefaultambiencenametextrequestambiencedescriptiondefaulttext stringconstantsdefaultambiencedescriptiontextrequestambiencedescriptionlanguagetext getculturetextlanguagetextstringconstantsdefaultambiencedescriptionculture stringconstantsdefaultambiencedescriptiondefaulttextthis is my function to implement the reflection where serviceaction for the case above would be createambiencepublic static r responsehelpertrt request string serviceaction icmscorecontentservice service new contentservicerefcmscorecontentserviceclient r response defaultr response,['c#'] +69803,jquery zip masking for multiple formats i have a requirements for masking a zip field so that it allows the classic 5 digits zip x or 5 4 format x i could so something likemyzipfieldmask9but the complication comes from the fact that dash should not be showing if the user puts in only 5 digitsthis is the best i came up with so far i could extend it to autoinsert the dash when they insert the 6th digit but the problem with this would be funny behavior on deletion i could stop them from deleting the dash but it would patching the patch and so forth it becomes a nightmaremaskdefinitionsmyzipfieldmask9 placeholderis there any out of the box way of doing this or do i have to roll my own,"['javascript', 'jquery']" +69826,is anyone using sencha touch for mobile development were evaluating sencha touch for mobile development has anyone used this yet i realize that it is still in beta and if so what are its strengths weaknesses how does it compare to alternativesit certainly sounds compellingthanks,"['iphone', 'android']" +69835,using jquery and ajax to save a file in aspnet i have a button that uses jquery and ajax to call a server side script to create a text file and sends back the following responseresponsecontenttype csvresponseaddheadercontentthisposition attachment filename fnameresponsecontenttype applicationoctetstreamresponsebinarywritebtfileresponseendhowever the save dialog does not appearif i do not use ajax and perform a full postback with the same code it works any ideashere is the jquery codefunction reportbuttonclickfunction ajax type post url generatereportaspx data id0 success function,"['asp.net', 'jquery']" +69839,do background applications ever quit in ios 4 i do not fully understand apples ios 4 model i have been poring through documentation for hours but i still appreciate some helpdo backgrounded iphone apps ever quit for example when i close a locationtracking app such as loopt it will be backgrounded but will it subscribe to the oss significant locations service according to apple if i understand it correctly even it is suspended or closed it will be notified of my current location does that mean in effect that it will always be aware of my location as long as it is on my phone or until i restart my phonethanksrob,['iphone'] +69852,android wifi permission i do not understand why i need to add wake lock permission to the application manifest when i toggle wifi with setwifienabled any idea,['android'] +69872,algorithm for finding a painted region on a canvas update i am attempting to pull a little clutter out of this post and sum it up more concisely please see the original edit if neededi am currently attempting to trace a series of single colored blobs on a bitmap canvas eg an example of the bitmap i am attempting to trace would look like the followingafter successfully tracing the outlines of the 3 blobs on the image i would have a class that held the color of a blob tied to a point list representing the outline of the blob not all the pixels inside of the blobsthe problem i am running into is logic in instances where a neighboring pixel has no surrounding pixels other than the previous pixel eg the top example would trace fine but the second would fail because the pixel has no where to go since the previous pixels have already been usedi am tracing lefttoright toptobottom favoring diagonal angles over right angles i must be able to redraw an exact copy of the region based off the data i extract so the pixels in the list must be in the right order for the copy to workthus far my attempt has been riddled with failure and a couple days of pulling my hair out trying to rewrite the algorithms a little different each time to solve the issue thus far i have been unsuccessful has anyone else had a similar issue like mine who has a good algorithm to find the edges,['c#'] +69880,add an onblur to all form elements so on a specific page i have some number of form elements anywhere between 3 and 8 depending upon the user and their action on the pagehow can i add a specific onblur event to all of the form elements dynamically on the pageif i havefunction dothisonblur stuff how can i add that same function to all of these once the page loads no elements are created after the page loads but different elements may appear for different usersinput typetext idxinput typetext idyselect idzselectis that possible,"['javascript', 'jquery']" +69884,double buffering when not drawing in onpaint why does not it work i am working on a simple vector drawing app in cnet the drawing is done in a panel but i am not using the onpaint event for all of it in fact the onpaint even just calls another method which actually draws everything in the documenti tried to add double buffering but when i set doublebuffered to true the flicker issue is even worse why is this if i want to double buffer the control do i absolutely have to do all my drawing in the onpaint event with the supplied graphics object instead of using panelcreategraphics and then drawing to thatedit this is the basic code i am usingprivate void doc paintobject sender painteventargs e g doccreategraphics renderscalefactor offset private void renderfloat scalefactor pointf offset foreach line x in documentlines drawlinexpointa xpointb xcolor xlinewidth private void drawlinepointf a pointf b color color float width pen p new pencolor width pointf pa new pointfax offsetx scalefactor ay offsety scalefactor pointf pb new pointfbx offsetx scalefactor by offsety scalefactor gsmoothingmode systemdrawingdrawing2dsmoothingmodeantialias gdrawlinep pa pbthe general idea is that the two variables scalefactor and offset refer to the zoom level and pan level in the ui g is a graphics object,"['c#', '.net']" +69918,python init takes exactly 2 arguments 3 given this is my first question on stackoverflow so please tell me how i can improve it in the commentsi am writing a program to find adapters and have made a class called adapter when i pass in two arguments idle gives me an error saying i passed in three here is the code and stack tracethis is the adapter class for the adapter finder scriptclass adapter side1 nonenone side2 nonenone the class that holds both sides of the adapter def init ptype1pmf1ptype2pmf2 initiate the adapter keyword arguments ptype1 the passed type of one side of the adapter ex bnc rca pmf1 the passed gender of ptype1 ex m f ptype2 the passed type of one side of the adapter ex bnc rca pmf2 the passed gender of ptype2 ex m f print assigining now side1 ptype1pmf1 print side1 side2 ptype2pmf2 print side2sidex rcamsidey bncfx adaptersidexsideyprint xside1print xside2errortraceback most recent call last file cuserscodydocumentscodepythonadapter finderadapterpy line 28 in module x adaptersidexsideytypeerror init takes exactly 2 arguments 3 giveni dont understand what the problem is because i have only entered two argsedit im new to the python language though i know javaim using this page as a tutorial,['python'] +69921,how to escape regular expression special characters using javascript i need to escape the regular expression special characters using java scripthow can i achieve thisany help should be appreciatedthanks for your quick replybut i need to escape all the special characters of regular expressioni have try by this codebut i cannot achieve the resultregexpescapefunctionstr if argumentscalleesre var specials argumentscalleesre new regexp specialsjoin gim return strreplaceargumentscalleesre 1 function regexpfind var regex new regexpmuneesgim var regex new regexpregexpescapemuneeswaran var regexregexpescapeenter code heremuneeswaran alertreg regex what i am wrong with this codeplease guide me,['javascript'] +69927,multiline string insert using jquery addselectclickfunction optionsformafterhello world this worksaddselectclickfunction optionsformaftertr tdinput typetext classoptionfield valueoptions td td ul classoption liselectoptionvalueoptionselectli ul tdtr something like this does not in chrome i get the error unexpected token illegal after googling i have thiscovered my teeny brain does not know much about javascript and multilines so i added to then end of each line yet i now get the error unexpected identifieri would like this to not be as difficult as i am making it,"['javascript', 'jquery']" +69944,how to create an mkmapview the documentation does not talk much about it and there seems to be no init method for this how would i create one and set the longitude and latitude or region to thisplay in the map view,['iphone'] +69950,recursive categories with a single query i have a website with articles and sectionseach sections can have a parent section as much as they likefor examplesubject 1 subject 2 subject 3 subject 4 subject 5 subject 6 subject 7subject 8subject 9etcnow i want to fetch them recursively what is the most efficient way to do it via php and mysqltnx in advanced,"['php', 'mysql']" +69963,avoid duplicating code let us say i have switch choice case a stmt do stmt related2a break case b stmt do stmt related2b break case c something different how could i avoid duplicating stmt code but is there any workaroundgcc extension label as value looks quite good for such situation switch choice do case a ptr a label break case b ptr b label while0 stmt goto ptr case c is there any trick that can do the same in ansicedit of course i have thought of functionmacroinline but anything elseit is not about performance either just for educational purpose,['c'] +69976,why does not it remove the table i have this piece of code tr fading when deleteddeleteliveclick function ajax type post url historydeleteidthisattrid thisclosesttrfadeoutslow function thisremove ifthisclosesttablefindtbodyisempty latestremove return falseit triggers when i want to delete a table row through the delete button as shows the imageit may happen that the table becomes empty of table rows i want to delete the whole table when this occurs but the table is not being removed the line code thisremove works and this seems to refer to the tr element in that scope because the whole row is being removed but the next 2 lines does not work the table is not being removedediti changed the ifthisclosesttablefindtbodyisempty to ifthisclosesttablefindtbodyisempty exclamation mark to see if it removes and it removed the whole table but i inspected the table element before and after deleting the last row and got thisjs says that tbody is not empty google chrome says otherwise i do not know how to fix it,"['jquery', 'javascript']" +69979,alarmmanager and broadcastreceiver instead of service is that bad timeout background infoi need to update some data from the web about every hour or so even when my app is closed the update of the data itself takes about 40 seconds to 1 minute it is then saved as a serializable to a file this file is read when my app startsthis is the approach i took for the moment not using a serviceuse the alarmmanager and broadcastreceiver like this private void set refresh data alarm mcontext mainthis alarmmanager alarmmanager getsystemservicealarm service broadcast intent new intentmcontext repeatingalarmreceiver refresh dataclass pendingintent pendingintentgetbroadcastmcontext 0 broadcast intent 0 do a refresh every hour starting for the first time in 30 minutes from now calendar now calendargetinstance long triggerattime nowgettimeinmillis 1 30 60 10 starts in 30 minutes long repeat alarm every 1 60 60 10 repeat every 60 minutes alarmmanagersetrepeatingalarmmanagerrtc wakeup triggerattime repeat alarm every pendingintentmy repeatingalarmreceiver refresh dataclass takes care of updating the data from the webpublic class repeatingalarmreceiver refresh data extends broadcastreceiver public static context mcontext connectivitymanager mconnectivity override public void onreceivecontext context intent intent mcontext context if network connection is ok wifi or mobile then load data mconnectivity connectivitymanager context getsystemservicecontextconnectivity service logihub mconnectivitygetnetworkinfo0 mconnectivitygetnetworkinfo0 logihub mconnectivitygetnetworkinfo1 mconnectivitygetnetworkinfo1 if mconnectivitygetnetworkinfo0getstate networkinfostateconnected mconnectivitygetnetworkinfo1getstate networkinfostateconnected logihub connectivity ok refresh hist data else else show dialog no network connection logihub no network connection for the moment will try again later private void refresh hist data logihub refresh hist data starting etc in the manifest i have receiver androidnamecomcousinhubmyapprepeatingalarmreceiver refresh data androidprocessremote problem the alarm gets fired on time and the update starts but then after about 10 seconds it stops timeout0625 115505278 warnactivitymanager76 timeout of broadcast broadcastrecord44bb4348 null receiverandroidosbinderproxy44bcc6700625 115505278 warnactivitymanager76 receiver during timeout resolveinfo44bb42c0 comcousinhubmyapprepeatingalarmreceiver refresh data p0 o0 m0x00625 115505278 infoprocess76 sending signal pid 819 sig 90625 115505298 infoactivitymanager76 process comcousinhubmyappremote pid 819 has diedps strangely enough this timeout does not happen after about 10 seconds on my htc hero still on android 15 api level 4 but well on my nexus one 21update1questions why this timeout any easy way to avoid this did i set up my broadcastreceiver correctly in the manifest do i need to add something to avoid this timeout should i absolutely go for a service for this kind of refresh from web functionality considering this article if yes i should switch to a service any good snippets of codetutorial for this as allways thanks for your helph,['android'] +69986,will things run quicker if i make my variables final i am writing for android javai am declaring ints and floats as part of an ongoing loopsome of them do not need to be changed after declarationif i set them all to final when declaring will things run quickereditthanks everyone i did not actually expect it to make any improvements i just noticed after browsing the source of various large projects it was fairly common cheers,"['java', 'android']" +70003,getting each individual digit from a whole integer let us say i have an integer called score that looks like thisint score 1529587now what i want to do is get each digit 1 5 2 9 5 8 7 from the score using bitwise operators i am pretty sure this can be done since i have once used a similar method to extract the red green and blue values from a hexadecimal colour valuehow would i do thiseditit does not necessarily have to be bitwise operators i just thought it would be simpler that way,['c'] +70021,help need to get spring mvc project going with intellij idea so i downloaded a trial of idea ultimate and i want to get spring mvc going with tomcatso i setup a new project configured it to use sun jdki chose a spring application and it created and downloaded the followingi do not see any springmvc libraries are they included in there or do i have to do something about thatcan someone outline what i have to do to get this to build like a spring mvc web application,['java'] +70025,how to set recaptcha key settings at runtime i am implementing the recaptcha control from googlei built a simple c test project from their example and all works now instead of having the publickey and privatekey in the aspx page i would rather assign these values at run time as they will most likely be pulled from either the webconfig or a database tablei tried the following in the page load protected void page loadobject sender eventargs e recaptchapublickey deleted for obvious reasons recaptchaprivatekey ditto but i get an error stating recaptcha needs to be configured with a public private keyi also tried overriding the oninit method of the page and assigning the values there but no joyany ideas on where this needs to go,"['c#', 'asp.net']" +70053,anyone knows something like rspec for php rspec is a great ruby test framework for test driven developmentanyone knows something like rspec but for php,"['php', 'ruby']" +70069,googlemaps v3 how to change the map style based on zoom level i am using the new google maps v3 styled mapi want to change how the map is styled based on the zoom level i have the following pseudocode how do change my mapstyle based on the zoom level var myoptions zoom zoom center latlng thisabledefaultui true navigationcontrol true scrollwheel false navigationcontroloptions style googlemapsnavigationcontrolstylesmallposition googlemapscontrolpositiontop right maptypeid googlemapsmaptypeidroadmap var mapstylezoomedout featuretype landscape elementtype all stylers visibility off var mapstylezoomedin featuretype landscape elementtype all stylers visibility off featuretype poi elementtype all stylers visibility off map new googlemapsmapdocumentgetelementbyidfindmap myoptions var styledmapoptions map map var stylemaptype new googlemapsstyledmaptypemapstyle mapstylezoomedout mapmaptypessetminimial stylemaptype mapsetmaptypeidminimial googlemapseventaddlistenermap zoom changed function if zoom level 8 use mapstylezoomedin if zoom level 8 use mapstylezoomedout thanks in advance,['javascript'] +70075,how to prevent starting the activity at the first tab in a tabactivity i have a tabactivity which contains 4 activities my code sets the second tab as the current tabpublic class mytabactivity extends tabactivity tabhost tabhost gettabhost tabhosttabspec spec resusable tabspec for each tab intent intent reusable intent for each tab textview tabview create an intent to launch an activity for the tab to be reused intent new intentsetclassthis activity1class spec tabhostnewtabspectab 1 specsetcontentintent tabview textview inflaterinflaterlayoutff tab indicator null tabviewsettexttab 1 specsetindicatortabview tabhostaddtabspec intent new intentsetclassthis activity2class spec tabhostnewtabspectab 2 specsetcontentintent tabview textview inflaterinflaterlayoutff tab indicator null tabviewsettexttab 2 specsetindicatortabview tabhostaddtabspec intent new intentsetclassthis activity3class spec tabhostnewtabspectab 3 specsetcontentintent tabview textview inflaterinflaterlayoutff tab indicator null tabviewsettexttab 3 specsetindicatortabview tabhostaddtabspec intent new intentsetclassthis activity4class spec tabhostnewtabspectab 4 specsetcontentintent tabview textview inflaterinflaterlayoutff tab indicator null tabviewsettexttab 4 specsetindicatortabview tabhostaddtabspec tabhostsetcurrenttab1the problem is when the mytabactivity starts it starts both activity in the first tab and the activity in the second tab i just want it to start the activity in the second tab since it is set to be the current tab what should i dothanks,['android'] +70085,how can i make a wpf window maximized on the screen with the mouse cursor according to the msdn documentation for the windowstartuplocation propertysetting centerscreen causes a window to be positioned in the center of the screen that contains the mouse cursoralthough the msdn doc for the centerscreen field itself defines it somewhat less clearly asthe startup location of a window is the center of the screen on which it is openeda simple test shows this working as it shouldmainwindowxamlwindow xclasscenterscreentestmainwindow xmlns xmlnsx button clickbutton clickopen windowbuttonwindowmainwindowxamlcsusing systemwindowsnamespace centerscreentest public partial class mainwindow public mainwindow initializecomponent void button clickobject sender routedeventargs e window window new window windowwindowstartuplocation windowstartuplocationcenterscreen windowshow if you test this out on a dual monitor system you can see that the new window will be centered on the screen where the mouse cursor is when you click the button that is exactly how it should workhowever if you try to set the window to maximize before you show it the new window will only maximize on the thisplay from which you launched the application change the button click event handler to the following to see what i meanvoid button clickobject sender routedeventargs e window window new window windowwindowstartuplocation windowstartuplocationcenterscreen windowwindowstate windowstatemaximized windowshownow the window will only maximize on the screen from which the application is launched no matter where the mouse cursor is when you click the button if you set the window state to maximized after you show it centerscreen works properly this is equivalent to the user maximizing the window for instancevoid button clickobject sender routedeventargs e window window new window windowwindowstartuplocation windowstartuplocationcenterscreen windowshow windowwindowstate windowstatemaximizedthe problem here of course is that maximizing the window after showing it takes much longer and in an app such as mine the window needs to pop into place immediatelyanyone know of a solution,['.net'] +70086,how can i get eclipse to index code inside ifdef endif i am using eclipse to work on some c code and it is not indexing code inside conditional compilation blocks like thisifdef use feature aint feature a some codehereendifhow can i get eclipse to index the feature a function,['c'] +70100,what do you call a single header whose purpose is to include other header files i have seen this done before in various c libraries namely qt qtcore qtgui etc and irrlicht irrlichth file mylibraryhinclude someclass1hinclude someclass2hinclude someclass3h and so onobviously this exists for convenience a programmer wishing to use the library only has to include one header instead of lots of different ones my question is is there a special name for this type of header file even if there is not an official name what you you refer to it as a convenience header or module header or somethingnames given so far with sourcesconvenience header boostmaster header apple official documentation an msdn blogmetaheader the game programming wikiuser contributions no sourcesheader header larry watanabeumbrella header chuck,"['c++', 'c']" +70123,retain nonatomic and nonatomic retain any difference what is the difference between retain nonatomic and nonatomic retain in code such as thisproperty retain nonatomic yellowviewcontroller yellowviewcontroller,"['iphone', 'objective-c']" +70145,handle keyboard done pressed event on iphone i am moving my view when a text field is pressed in order to get proper view when keyboard appears now when the done keyboard button is pressed i would like to return the view to its initial state how do i handle an action when the done keyboard button is pressed,['iphone'] +70146,find the location of my applications executable in wpf c or vbnet how can i find the location of my applications executable in wpf c or vbneti have used this code with windows formsapplicationexecutablepathtostringbut with wpf i received this error from visual studio systemwindowapplication does not contain a definition for executablepath,['c#'] +70155,app store link for ratereview this app i want to put a ratereview this app feature into my appis there a way to link directly to the screen in the app store where they review the app so the customer does not have to click through the main app link thanksedit starting a bounty on this due to the lack of response just to make sure it is crystal clear i am aware that i can link to my apps page in the store and ask the user to click from there to the review this app screen the question is whether it is possible to link directly to the review this app screen so they do not have to click through anything,['iphone'] +70156,what is the significance of the order of statements in mysql explain output this is mysql explain plan for one of the query i am looking into id select type table type possible keys key key len ref rows extra 1 simple table2 index null primary 4 null 6 1 simple table3 all null null null null 23 1 simple table1 all null null null null 8 1 simple table5 index null primary 4 null 1 4 rows in set 0 secwhat is the significance of the order of statements in this output does it mean that table5 is read before all others,['mysql'] +70170,is synchronized really just syntactic sugar i am new to multithreading and i wrote this code which prints the numbers 110 by having concurrently running threads increment and print a variableheres the code i am usingpackage threadtestpublic class main static int i0 static object locknew object private static class incrementer extends thread override public void run while true synchronizedlock if i10 break i systemoutprintlni public static void mainstring args new incrementerstart new incrementerstart new incrementerstart new incrementerstart new incrementerstart new incrementerstart this works i wrote up a test program to check the output and the numbers printed are exactly 110 in ordermy question is this i have heard that synchronized is only syntactic sugar but i cannot seem to achieve a successful result without using it what am i missing,['java'] +70175,how can you nibble nybble bytes in c i am looking to learn how to get two nibbles high and low from a byte using c and how to assembly two nibbles back to a bytei am using c and net 40 if that helps with what methods can be done and what libraries may be available,"['c#', '.net']" +70177,objectivec how can i get class instance in class method i have 2 classes parent and child and parent has a class method named funcnow i want to get class instance in func method to thistinguish which class is callerinterface parent nsobject voidfuncendimplementation parent voidfunc class class howtogetclass nslog call func classendinterface child parentendint main child func call func from childis there any way to get class instance or class name in class method,['objective-c'] +70181,conflicting with my own stringh i have a project that was compiling ok within gi cannot see the version right now and now on xcode it is noti think that i got the problem now i have a stringh file in my project and it seems tha the xcode compilerthat is gcc is trying to add my own string file from the cstring i am not sure of it but take a look at this picturefrom what it looks like it is including my own instead of the system file i was wondering should not include file be a system include because of the and should not the system include a file within its own path and not the original path of my applicationas i said i am not sure if this is what happening because i am just migrating to osx these past 2 daysi was going to change my class and file name to not conflict so it would work if this is really the problem but i was wondering there should be another way to do this because now my project is not that big so i can do this in some time but what if the project was bigger it would be dificult to change all includes and class namesany help is appreciatedthanksjonathan,['c++'] +70190,trying to digitally sign via hmacsha1 with php i am trying to setup some google maps premier api action and to do so i need to sign my urls to authenticate if you go down to signature examples there is some python c and java code to show you how to do the signature via hmacsha1 there is also an example so that i can to test my php implementation however i just cannot seem to get it to work heres my codekey vnixe0xscrmjlyv12nj bvupawdata mapsapigeocodejsonaddressnewyorksensorfalseclientclientidmy sign hash hmacsha1 data base64 decodekeymy sign base64 encodemy signvalid sign kru1tzvqm7ur0i8i7k3huiw3msawhen i run this i get a signature ofzdrlngmwzjiymta1mwm1zjk0nzc4m2nkyjlmndqzndbkyzk4ndi4zgwhich totally does not match things i have thought aboutthe key is in modified url encoded format so changing and to and also does not workthe python example code does indeed work so this is a valid examplecompletely rewriting our codebase in python instead of php i inherited it,['php'] +70201,c weird syntax spotted in boost template parameters i was having a look at the function class documentation in boost and stumbled across this boostfunctionfloat int x int y fi must admit this syntax is highly confusing for me how can this be legal c is there any trick under the hood is this syntax documented anywhere,['c++'] +70208,extending singletons in php i am working in a web app framework and part of it consists of a number of services all implemented as singletons they all extend a service class where the singleton behaviour is implemented looking something like thisclass service protected static instance public function service if issetselfinstance throw new exceptionplease use servicegetinstance public static function getinstance if emptyselfinstance selfinstance new self return selfinstance now if i have a class called fileservice implemented like thisclass fileservice extends service lots of neat stuff in here calling fileservicegetinstance will not yield a fileservice instance like i want it to but a service instance i assume the problem here is the self keyword used in the service constructoris there some other way to achieve what i want here the singleton code is only a few lines but i would still like to avoid any code redundance whenever i can,['php'] +70210,insert hex values into mysql i have a table with a varbinary column i need to insert a string such as 4d2aff which represents the hex values 0x4d 0x2a and 0xff respectively how do i construct this statement,['mysql'] +70214,no such method error immutablelistcopyof i am using guava05snapshot with suns jdk 16the code blows up executing this snippetliststring badpasswords listsnewarraylist passwordbadwordscollectionssortbadpasswordsimmutableliststring tmp immutablelistcopyofbadpasswordsspecifically on the immutablelistcopyof callthis code has worked for months using the old googlecollections codejavalangnosuchmethoderror comgooglecommoncollectimmutablelistcopyofljavautilcollectionlcomgooglecommoncollectimmutablelistthe passwordbadwords is an immutablesetstring and the creation of the writable array and the sort work perfectly but attempts to convert the array into an immutablelist fail,['java'] +70215,ci filter to create black white image i have a ciimage i need to convert from color to black and white within my cocoa objective c program peter h previously pointed me to this link as a potential solution but i am having trouble compiling the kernel routine there see separate thread if interested so i am wondering if one of the other builtin cifilters will accomplish what i am trying to do i do not want a grayscale image i want each pixel in the result image to be either black or white i just need to be able to tell the filter how to determine which pixels should become black and which should become white the threshold filter in photoshop does exactly this it lets me specify the threshold and then it uses this value to decide which pixels become white and which become black this is what i am trying to replicate via code in my xcode projectany ideas if one of the other built in filters can be used for this thanks,['objective-c'] +70228,query to get records based on radius in sqlite i have this query which does work fine in mysqlselect acossin12345 pi 180 sinlat pi 180 cos12345 pi 180 coslat pi 180 cos6789 lon pi 180 180 pi 60 11515 1609344 as thistance poi from poiwhere langeng having thistance30thistance is in kilometers the input is lat12345 and lon6789the sqlite is 3 and i cannot run custom functions with it as it is on android i also do not have acos etc as that is not part of the standard sqlitehow would be the above query in sqlite,"['sql', 'android']" +70247,why do these regular expressions execute slowly in java i am trying to use regular expressions to determine what format the user have applied when entering input in a textboxthe regular expressions are as followss alphabet 99to determine whether the input is one or more strings of length 9 in a given alphabet possibly separated by whitespacewsn alphabet sto check if the input is in fasta formatthe regular expressions run terribly slow when matching with inputstringmatchesregexstring why is thisi figured this may be due to java storing all potential matches which i do not need at this point but adding in every parenthesis breaks the regex how should this be donethank youmartinedit 1 i was unable to reproduce this issue it only happens on one computer this could suggest something wrong with that particular vm setupwe need something more robust and so we will be implementing this differently i have picked joels answer as the right one since i believe that some special case in pattern may be the cause,['java'] +70261,what is the proper error message to supply to google guavas preconditions methods for example when using preconditionscheckargument is the error message supposed to reflect the passing case or the failing case of the check in questionimport static comgooglecommonbasepreconditionsvoid dostuffint a int b checkargumenta b a b or checkargumenta b a b,['java'] +70267,usage of maven tychop2plugin with swt how do i build a swt application using the eclipse p2 repository and the maven tychop2plugin,['java'] +70273,optimized version of strstr search has constant length my c program had a lot of strstr function calls the standard library strstr is already fast but in my case the search string has always length of 5 characters i replaced it with a special version to gain some speedint strstr5const char cs const char ct while cs4 if cs0 ct0 cs1 ct1 cs2 ct2 cs3 ct3 cs4 ct4 return 1 cs return 0the function returns an integer because itas enough to know if ct occurs in cs my function is simple and faster than standard strstr in this special case but iam interested to hear if anybody has some performance improvements that could be applied even small improvements are welcome summarycs has length of 10 but otherwise it can vary length is known before not used in my function length of cs is usually from 100 to 200ct has length of 5content of strings can be anythingedit thank you for all answers and comments i have to study and test ideas to see what works best i will start with maks idea about suffix trie,['c'] +70275,rails exception handling how can i send the error messages that are happening in the model code back to the view i mean i have abegin some coderescue exception handlingendnow error occurs and in the rescue i would like to send a message back to the controller so that it ll get thisplayed in the view do i have to use a variable which has to contain a number of error messages that occurs in one request concatenate them and send it back to controller so that i can thisplay it in the view rails already shows some error messages like field cannot be blank i am asking about the other exceptions which occurs in the functions that are present in the model code,['ruby-on-rails'] +70289,jquery validation allow number without the leading zero i am using jquery validation like so var field selector if fieldisvisible fieldrulesadd required true fieldrulesadd number true if the user enters a number without a leading zero eg 5 then jquery validation says please enter a valid number how can i change the validation to allow number entry without requiring the leading zero,['jquery'] +70293,c prime number task from the book i am a c beginner how good is the code below as a way of finding all prime numbers between 210int i jfor i2 i10 i for j2 jij j if ij break if j ij cout i is primen,['c++'] +70295,counting unique users using mapreduce for java appengine i am trying to count the number of unique users per day on my java appengine app i have decided to use the mapreduce framework mapreduceappspotcom for java appengine to do this calculation offline i have managed to create a map reduce job that goes through all of my entities which represent a single users session event i can use a simple counter as well i have several questions though1 how do i only increment a counter once for each user id i am currently mapping over entities which contain a user id property but many of these entities may contain the same user id so how do i only count it once2 once i have these results of the job stored in these counters how can i persist them to the datastore i see the results of the counters on the mapreduces status page but i want these results automatically persisted to the datastoreideas,['java'] +70309,what is operator in this code i am using threadpool with the follwoing codethreadpoolqueueuserworkitem o myfunction i am not sure what does o does in this code can anyone help me out,['c#'] +70344,why tuples items are readonly i was thinking to use tuple class to store 2 integer information startaddress endaddress i need in my programbut i thiscover that tuple items are readonly so if i need to set a value for an item i need to reinstantiate a tuplewhat is the reason behind this design decision,['.net'] +70348,how to show a menu on top of the windows title bar i was trying for some time now to show a menu like this one on my wpf title bar the orange one in the upper left corner windows theme20 mockupslarge button modei have extended the aero glass into the client area by using the dwmextendframeintoclientarea methodthe application icon in the upper left is not visible and i can show the menu but one cannot click on it it does not open and if i put for example a textbox in the title bar i cannot edit its contenti think that my controls are not on top of the title bar how can i draw them on top of the title bar so that the menu is clickable,['c#'] +70372,findbugs and database password security issue i am using the following code to initialize database connection public connection getconnection try if null connection string drivername commysqljdbcdriver mysql mm jdbc driver classfornamedrivername create a connection to the database string servername localhost string database database string url jdbcmysql servername mydatabase a jdbc url string username username string password password connection drivermanagergetconnectionurl username password return connection catch classnotfoundexception cnfe cnfeprintstacktrace catch sqlexception sqle sqleprintstacktrace throw new nullpointerexceptioncannot establish database connection and i know it is bad practice to do it also i ran findbugs against the code and got the security issue saying the followingthis code creates a database connect using a hardcoded constant password anyone with access to either the source code or the compiled code can easily learn the passwordwhats the best way to initialize database connection without having this security breach,['java'] +70395,can webconfig transformations be used with appconfig files possible duplicateappconfig transformation for none web projects in visual studio 2010 basically the question above the new config transformations that are provided for a webconfig file for different environments are really nicehowever i would like the same functionality for appconfigs that vary across testing environmentsdoes anyone know of a way to make this workthanks in advance,['.net'] +70408,how to change jquery autocomplete plugin default querystring key term to that i want jquery autocomplete plugin sent request like thismysitecomsuggestiontermsadeghis there any way to change term querystring key to another i cannot find option that provide this for me,['jquery'] +70410,android intent to open users preferred browser i have been trying to find out how to create an intent that will open the users preferred browser without specifying the url i know how to open it by giving a specific url like thisintent intent new intentintentsetactionintentaction viewintentsetdataandroidneturiparsecontextstartactivityintenti do not want to open the browser to any page in particular just the set homepage or whatever page the user was on last i have thought about looking up the homepage set within the app but you cannot do it with the default browser app because it is private does anybody know of a way to do this,['android'] +70411,lambda variable scope examplemyobjectstubs smymethodnullignoreargumentsreturnblehvar s sa variable s is defined in a lambda and another variable s as a local variable within the same method visual studio tells me a conflicting variable is defined below when i hover over the first s why are these conflicting the s in the lambda is not available outside of its enclosing brackets surely,['c#'] +70416,how to find out if the value contained in a string is double or not in java i am trying to find out if the value contained in a string is double or not,['java'] +70417,local aspnet mvc suddenly very slow load times 1 minute over the last few weeks i have been subject to a sudden and significant performance deterioration when browsing locally hosted aspnet 35 mvc web applications c load times for a given page are on average 20 seconds regardless of content start up is usually over a minute these applications run fast on production and even test systems test system is comparable to my development environmenti am running iis 60 vs2008 vista ultimate sql2005 net 35 mvc 10 and we use visualsvn 17my sql db is local and ipv6 does not seem to be the cause i browse in firefox and ie8 outside of debug mode using loopback machine name and localhost and get the exact same results every time hence dns does not seem to be the issue eitherbelow are screen shots of my dottrace output image28100108l3123jpg062010img4glowfotothis issue has made it near impossible to debugtest any web app any suggestions very much appreciatedsolution complete reinstallation of windows iis visual studio etc it was not the preferred solution but it worked,['c#'] +70420,what is the tinymce jquery package i have been asked to use the tinymce editor in a project on the download page there is a main package and then a jquery packagethis package contains special jquery build of tinymce and a jquery integration plugintinymce 3 3 7 jqueryzipwhat is the jquery build of tinymce is it just tinymce with the same features built on top of jquery is it standard tinymce but with some kind addon that makes manipulating tinymce with jquery easier something else a quick internet search told me it is tiny mce with jquery functionality but i am curious what the means,"['javascript', 'jquery']" +70435,how to throttle or prioritize a query in mysql is there anyway to prioritize or throttle a query at all in mysqli am a dba on a server that sees a lot of unoptimized queries come into the server and they just destroy the cpu i am looking at throttling certain users that hit on the database in poor fashionclarificationi realize that mysql has facilities built in to limit number of queries connections etc but those are not really the issue it is that once in a blue moon a user will send an unoptimized query and i would need to time it out or something similar,['mysql'] +70456,ways to find a race condition i have a bit of code with a race condition in it i know that it is a race condition because it does not happen consistently and it seems to happen more often on dual core machinesit never happens when i am tracing although there is a possibility that it could be a deadlock as well by analyzing stages of completion of logs where this does and does not occur i have been able to pinpoint this bug to a single function however i do not know where in the scope of the function this is happening it is not at the top leveladding log statements or breakpoints is going to change the timing if it is a race condition and prevent this from happening is there any technique that i can use aside from getting a race condition analyzer that will allow me to pinpoint where this is happeningthis is in visual studio 9 with c of the nonmanaged variety,['c++'] +70472,specify data type with column alias in sql server 2008 imagine i have the following select statement in a view sql server 2008select select case when historyoutofserv y or historyoutofserv y then 1 else 0 end as oos from historythe column oos ends up being of type int but i would like it to be of type bit how can i accomplish this,['sql'] +70476,cors not working on chrome i have set up crossorigin resource sharing on a server jetty using the crossoriginfilter and it works perfectly on ie8 and firefox on chrome it just does not ajax url crossoriginurl type get error functionreq message alertmessage datatype json the error function is invoked with the helpful message error it seems to be making the request but without any of the headers youd expect if the url is from the same origin it works fine,"['javascript', 'jquery']" +70483,difference between attr accessor and attr accessible in rails what is the difference between attr accessor and attr accessible from my understanding using attr accessor is used to create getter and setter methods for that variable so that we can access the variable like objectvariable or objectvariable some valuei read that attr accessible makes that specific variable accessible to the outside worldcan someone please tell me whats the difference,"['ruby-on-rails', 'ruby']" +70484,determine if map contains a value for a key what is the best way to determine if a stl map contains a value for a given keyinclude mapusing namespace stdstruct bar int iint main mapint bar m bar b 0 bar b1 1 m0 b m1 b1 bar b2 m2 mapint bariterator iter mfind2 bar b3 itersecondexamining this in a debugger it looks like iter is just garbage data if i uncomment out this linebar b2 m2the debugger shows that b2 is i 0 i am guessing it means that using an undefined index will return a struct with all emptyuninitialized valuesneither of these methods is so great what i would really like is an interface like thisbool getvalueint key bar out if map contains value for key out mapkey return true return falsedoes something along these lines exist,['c++'] +70489,in java type arguments does extends e mean strictly subtypes only or would e also suffice in java type arguments does mean strictly subtypes only or would e also suffice,['java'] +70495,matplotlib one line plotted against two related x axes in different units i have one y variable which i am trying to plot against two related x axes on the top and bottom of the figure eg ynumber of things in cube x1side length of cube x2volume of cube i have y x1 x2 in numpy arrays the relationship between my x1 and x2 is onetoone and monotonic but not simple and they increase in different directions like side length and inverse volume i have tried using twiny and twin but these seem to be designed for plotting different y variables any ideas thanks everyonebelow is an example of the kind of thing i am trying to do except with a single line rather than symbols the idea is that say sigma04 and m2e15 are equivalent and interchangeable labels for one point,['python'] +70513,how to spin an android icon on its center point i have written the following to spin my icon on the center of the screen and instead it rotates around the upperleft corner ie origin x0 y0 of the imageview it should be simple to set some attributes of the imageview or the rotateanimation but i cannot figure it outpublic class iconpromoactivity extends activity private static final float rotate from 00f private static final float rotate to 100f 3600f 3141592654f 320f called when the activity is first created override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain imageview favicon imageview findviewbyidridfavicon rotateanimation r new rotateanimationrotate from rotate to r new rotateanimationrotate from rotate to 0 0 40 0 rsetdurationlong 21500 rsetrepeatcount0 faviconstartanimationr,['android'] +70524,how to get visual studio publish functionality to include files from post build event i am currently attempting to use visual studio 2010 publish and msdeploy functionality to handle my web deployment needs but have run into a roadblock with regards to customizing the package depending on my build configurationi develop in a 32bit environment but need to create a release package for a 64bit environment so in the release configuration i have a post build event that copies the 64bit version of a thirdparty dll into the bin directory overwriting the 32bit version when i use the publish functionality even though the correct 64bit dll is being copied to the bin directory it does not get included in the packageis there a way to get the publish to include files that have been copied into the bin directory during a post build event,['asp.net'] +70545,why does mpmovieloadstate have state 5 i find mpmovieplayercontrollerhthere is enum mpmovieloadstateunknown 0 mpmovieloadstateplayable 1 0 mpmovieloadstateplaythroughok 1 1 playback will be automatically started in this state when shouldautoplay is yes mpmovieloadstatestalled 1 2 playback will be automatically paused in this state if startedtypedef nsinteger mpmovieloadstatebut when i didnslogdplayerloadstateit prints out 5 or sometimes 3how did it happenas i know the loadstate has value of 0124 refer to developer documentationthank you,['iphone'] +70566,transaction comes back after finishtransaction has been called on it i am using inapp purchase for an iphone app i have a class that acts as skproductsrequestdelegate and skpaymenttransactionobserver and it is all working fine in the currently released version available on ituneshowever after recently adding a new nonconsumable product and testing it within the sandbox environment i am now encountering a strange problem every time i launch the app the purchase i made yesterday reappears in the transactions list passed to me by paymentqueueupdatedtransactions despite the fact that i had called skpaymentqueue defaultqueue finishtransactiontransaction already several times it is undeadin my paymentqueueupdatedtransactions implementation i havefor skpaymenttransaction transaction in transactions switch transactiontransactionstate case skpaymenttransactionstatepurchased case skpaymenttransactionstaterestored ddlogtransaction for occurred originally on transactionpaymentproductidentifier transactionoriginaltransactiontransactiondate i then process the purchase download the user content and finally in another method do thisfor skpaymenttransaction transaction in skpaymentqueue defaultqueue transactions if transactionpaymentproductidentifier isequaltostringtheparsercurrentproductid transactiontransactionstateskpaymenttransactionstatepurchased transactiontransactionstateskpaymenttransactionstaterestored ddlog transaction will finish product id date transactionpaymentproductidentifier transactiontransactiondate skpaymentqueue defaultqueue finishtransactiontransaction as you may have noticed i am not holding on to the original transaction object for the sake of simplicity and it is relatively easy to find it later from the call to skpaymentqueue defaultqueue transactions regardless i do indeed see the expected output that the transaction is completed and that it precisely matches the product id and date of the original transaction however next time i run the app the whole things starts over it is like the itunes store was never notified that the transaction completed or refuses to acknowledge it,['iphone'] +70567,programming in presence of watchdog timer i am new to embedded systems programming although i have done courses during studies practical programming is still a bit further awayhere is the problem i have to program a small system on nxp lpc2103 microcontroller arm 7 based without an operating system it has a watchdog timer which needs to be regularly updated the system has a gprs modem with tcpip stack embedded and initializing this takes time longer than the watchdog needs to timeout when i call the initialization function the system resetsi spoke to a more experienced colleague and he suggested that i need to exit and reenter the same initialization function from the main function in which i bite the watchdog timer so long until the function finishes executing the idea sounds good but i would like to also hear some other experiences also a reference book or website could be also useful because i could not find anything specific to thisi wouldnt like to call watchdog timer from the initialization function i do not find this good,['c'] +70584,when is this this in c i have a very strange questioni have a classfunction class mcbsystem template class receiver void setcallbackint i receiver receiver voidreceiverfunctionvoid icallbacksati new callbackreceiverreceiver function this and i inherit it multiply in another class class menubox public overlaybox public hidlistener public fanlibmcbsystem now if i call the setcallback function menuboxsetcallbackmenuboxclicked this submainwidgetclickedthen menubox has a value say 0x06cf22b8 but inside setcallback this is 0x06cf2370can someone explain what on earth is going onedit the true question is if i need to store this inside setcallback how can i check later that menubox thismany thanks in advace,['c++'] +70585,sqlite database security i am developing an application which will be storing user sensitive data my issue is using other applications that a user can view that stored data with then i need to provide better security for the data in generalis there any way to provide better security for sqlite database and tables,['android'] +70604,getting a foreach to run once so the question is this i have a for each loop that i am currently using to retrieve data from a query of an xml file which then gets put into a string like soforeach var value in datequery date valueelementhistorycreationvaluei know for a fact based on the way the xml file stores values and the query being used that there will only be one value in datequerythus i would like to know for the purposes of making my program more efficient and learning how to code better is there a better way to do this or are foreachs the only way,['c#'] +70607,conditional beans using spring i am trying to write a validatorfactory which will give me a validator based on its type public validator getnewvalidatorvalidatortype type switch case a new validator1 break case b new validator2 breaki want to write using spring xml beans definitioni can use method injection but it will let me create only one object and the method does not take any argumentsi do not want to use factorybean i am just looking whether we can do this using spring xml bean definition,['java'] +70612,ninject with aspnet webforms and mvc i want to use ninject in a project which combines aspnet webforms and aspnet mvc i am using ninject 2 but when i use ninjecthttpapplication from ninjectwebmvc it complains when i use somethings like a pagebase that the kernel is not created i have the following in the globalasax and am unsure what to addpublic class mvcapplication ninjectwebmvcninjecthttpapplication protected override void onapplicationstarted arearegistrationregisterallareas registerroutesroutetableroutes registerallcontrollersinassemblygetexecutingassembly protected override ninjectikernel createkernel return new standardkernelnew servicemodule does somebody has this working somewhere who could share some thoughts or code on this,['asp.net'] +70634,aes ctr 256 encryption mode of operation on openssl im new to openssl can anybody give me a hint in how to initialize aes ctr mode from a c file i know this is the methoda s signature but i am having problems with the parameters therea s not many documentation neither a clear example how to make a simple encryption i would appreciate if somebody could exemplify a call to this method thanks in advancevoid aes ctr128 encryptconst unsigned char in unsigned char out const unsigned long length const aes key key unsigned char ivecaes block size unsigned char ecount bufaes block size unsigned int numhi caf i really appreciate your quick answer it has been really useful and defenetly the best example i have found on the web i am trying to open a file with undetermined length encrypt it and write another file with the ciphertext generated then open the ciphered file and recover the plaintext i need to use a file of a considerable amount of mb cause i would like to benchmark the performance of the cpu however im still having a problem while decrypting somehow when decrypting a considerable txt files 1504kbit wont decrypt it complete and i get half of it in plaintext and the other half still ciphered i think this might be related to the size of the iv or the way i am calling the counter here is what i have so far include opensslaeshinclude stdiohinclude stringhstruct ctr state unsigned char ivec16 unsigned int num unsigned char ecount16 file fpfile rpfile opsize t count char buffer aes key key int bytes read bytes written unsigned char indataaes block size unsigned char outdataaes block size unsigned char ckey thiskeyisverybad it is 128bits thoughunsigned char iv8 0this should be generated by rand bytes i will take into consideration your previous poststruct ctr state state int init ctrstruct ctr state state const unsigned char iv8 statenum 0 memsetstateecount 0 16 memsetstateivec 8 0 8 memcpystateivec iv 8 void encrypt opening files where text plain text is read and ciphertext stored fpfopeninputtxtab opfopenoutputtxtw if fpnull fputs file errorstderr exit 1 if opnull fputs file errorstderr exit 1 initializing the encryption key aes set encrypt keyckey 128 key encrypting blocks of 16 bytes and writing the outputtxt with ciphertext while 1 init ctrstate iv counter call bytes read freadindata 1 aes block size fp aes ctr128 encryptindata outdata bytes read key stateivec stateecount statenum bytes written fwriteoutdata 1 bytes read op if bytes read aes block size break fclose fp fclose op free buffer void decrypt opening files where text cipher text is read and the plaintext recovered rpfopenrecoveredtxtw opfopenoutputtxtab if rpnull fputs file errorstderr exit 1 if opnull fputs file errorstderr exit 1 initializing the encryption key aes set encrypt keyckey 128 key encrypting blocks of 16 bytes and writing the outputtxt with ciphertext while 1 init ctrstate ivcounter call bytes read freadindata 1 aes block size op aes ctr128 encryptindata outdata bytes read key stateivec stateecount statenum bytes written fwriteoutdata 1 bytes read rp if bytes read aes block size break fclose rp fclose op free buffer int mainint argc char argv encrypt decrypt systempause return 0each encrypt and decrypt function are called in different runs so everything is initialized always with the same values thanks again for the hints you can provide me in advance regards,['c'] +70635,restful zend framework api i am developing a zend framework based application and i found myself writing a skeleton for the api module i read a bit on the web and i started writing the skeleton based on zend rest controller turned out ok key login required to use the apithe questions started when a colleague of mine started implementing the skeleton in a proper api for one of our applications he told me he thinks it would be better if we only had an usual zend controller action extended in an api controller and in indexaction a zend rest server that handles the objecti am a bit confused about this from my personal point of view i would want to have a largerthanaverage controller containing each of the 4 actions get post put delete and a bit of logic in each action rather than one action ruled by zend rest servermy problem is that i cannot figure which of the 2 solutions is better from an architecture point of view and of course the most easily maintainable over time,['php'] +70649,implementation of string literal concatenation in c and c afaik this question applies equally to c and cstep 6 of the translation phases specified in the c standard 5112 in the draft c99 standard states that adjacent string literals have to be concatenated into a single literal ie printfhelloworldc d hello worldn 10is equivalent syntactically to printfhelloworldc d hello worldn 10however the standard does not seem to specify which part of the compiler has to handle this should it be the preprocessor cpp or the compiler itself some online research tells me that this function is generally expected to be performed by the preprocessor source 1 source 2 and there are more which makes sensehowever running cpp in linux shows that cpp does not do itelibenelibendesktoptest cat cpptestc int a 5string 1 string 2string 3elibenelibendesktoptest cpp cpptestc 1 cpptestc 1 builtin 1 commandline 1 cpptestcint a 5string 1 string 2string 3so my question is where should this feature of the language be handled in the preprocessor or the compiler itselfperhaps there is no single good answer heuristic answers based on experience known compilers and general good engineering practice will be appreciatedps if youre wondering why i care about this i am trying to figure out whether my python based c parser should handle string literal concatenation which it does not do at the moment or leave it to cpp which it assumes runs before it,"['c++', 'c']" +70650,how do i detect touch input on the android right now all i am trying to do is detect when the screen is pressed and then thisplay a log message to confirm it happened my code so far is modified off of the camerapreview sample code it will eventually take a picture so the bulk of the code is in a class that extends surfaceview api for the example code from the sdk is 7,['android'] +70651,inline styles vs classes in my head i have always known to use classes over inline styles for any project but are there any articlespostingsblogs defining the proscons of each i am in a debate about this and i cant seem to find the blog post i read a long time ago about this,['css'] +70658,jquery replace inputs with spans i am trying to replace inputs with spans containing the input values in such a way as to be able to switch them back upon clicking a button i figure this would be most easily done in two stages adding spaninput valuespan in front of the inputs and then hiding the inputs the only problem is i am having trouble with the first part i am trying things like containerfindinput parent prependspanspan this effectively creates spanspaninput value however inside the prepend statement this seems to be undefined so i cannot do prependspanthischildreninputvalspansince there are several inputs i cannot simply put the input value into a variable how would i do this,['jquery'] +70661,javascript regex iso datetime does anyone have a good regex pattern for matching iso datetimesie 20100615t0,['javascript'] +70666,how to with miglayout i am trying to create a layout that will looking like central cell should be twice as wide as other i am trying achieve this with such code val panel new jpanelnew miglayoutdebug growgrow paneladdnew jpanel paneladdnew jpanel span 2 2 paneladdnew jpanel wrap paneladdnew jpanel paneladdnew jpanelbut as result all my cells have same width what i do wrong i am using scala but i do not think that problem is hereinupdatemaybe someone can explain why this did not work even if i try reproduce example from quickstart guide it did not work my code val panel new jpanelnew miglayoutdebug growgrow wraptabaddnew jpanel wraptabaddnew jpanel span 2 2 wraptabaddnew jpanel wrap wraptabaddnew jpanel wraptabaddnew jpanel wrap wraptabaddnew jpanel wraptabaddnew jpaneland as result all cols has equal size,['java'] +70674,where and how to use nested classes i am thinking that if a class will be instantiated only in another class so it is right to use it nested in that classi think this will help us good designwhen i look at my project i have almost never seen such nested structurebut if i try to nested classes so this time another questions appear in my mindfor examplei have board class move classes such as shortcastlelongcastleenpassantpromote and pieces like pawnqueenrookknight etc so it is clear board classes will instantiate piece classes and piece classes will instantiate move classes for a good designpromote move class should to be nested of pawn because only pawn can promote itselfshort and long castles should to be nested of king because only king can have such type movestrying to put all piece classes into board class is not looking good design because 89 class will be inside of board class and it will really annoying one board class file will be too large and hardly readablei prefer keep each piece class in another file good that we can create partial board class but still is not it annoying 89 partial board class files will hold each piece class is it better to not make them nested same about pieces create another partial piece file just for another move type class if nested class just take small space so it wouldnt be any problem but if it takes many methods,"['c#', '.net']" +70679,net framework from a low level programmers point of view when i was learning net i saw it as a platform that runs my net programs which has its own stack heap but now after learning more about things i see a net application as just like any other cc native application it is in portable executable pe file format with new data directory text section is filled with msil code instead of machine code the only difference is few dlls which are considered as net platform like any other dll dependency are loadedi guess at the very entry point there is some machine code which calls into the loaded dllnet platform and functions of those dll read the msil from text section segment to be more correct and generate equivalent machine code and put it in some kind of buffer i do not know which area would it be it i cannot be text data as they are readonly will they be stack or heap then make the eip point to this buffer of instructions last few instructions again call back into dlls to repeat the process for rest of msilas of managed heap managed stack they are just some portion of the processes heap stack its just that few functions referred to as gc will keep track of the memory allocations deallocations from this portions of memoryi like this realistic view i do not know how far i am true i am just guessing these things please correct me tell me more about this how far will is it similar to this view where can i learn more about net platform from this point of view,"['c#', '.net']" +70682,spring optimistic lockinghow to retry transactional method till commit is successful i use spring 25 and hibernate jpa implementation with java and container managed transactions i have a after user commit method that updates data in background and need to be committed regardless of concurrencyfailureexception or staleobjectstateexception exception because it will never be shown to client in other words need to make optimistic lock to pessimistic could happen if methods execution will take little bit longer and someone changed data in other transaction i read a a lot about idempotent stuff retry if exception in search for default max retries or 627 example or chapter 145 retry i also found in stackoverflow here and here i tried thispublic aspect retryonconcurrencyexceptionaspect private static final int default max retries 20 private int maxretries default max retries object around execution annotationretryonconcurrencyexception annotationtransactional int numattempts 0 runtimeexception failureexception null do numattempts try return proceed catch optimisticlockingfailureexception ex failureexception ex catchconcurrencyfailureexception ex failureexception ex catch staleobjectstateexception ex failureexception ex while numattempts thismaxretries throw failureexception retryonconcurrencyexception is my annotation to mark methods that need to be retried if a exception occurrs did not work i also tried several ways like select for update entitymanagerlockwhat is the best way to avoid stale data dirty reads etc such a strategy with spring retry synchronized jpa lock isolation select for update i could not get it to work and i really happy about any helphere is some pseudo code what i like to dovoid dosomethingitemid select something into a select anotherthing into b x item getitemformdb itemid takes long for one user and for other concurrent user it could take less time itemsetaa itemsetbb y update item between x and y another session could modify the item then the staleobjectstateexception gets thrown,['java'] +70684,use css to make a span not clickable htmlheadheadbodydiva href spantitlebrspan spandescriptionbrspan spansome urlspanadivbodyhtmli am pretty new to css i have a simple case like the above i would like to make the title and some url clickable but want to make description as nonclickable is there any way to do that by applying some css on the span so that whatever inside that span it is not clickablemy constraint is that i do not want to change the structure of the div instead just applying css can we make a span which is inside an anchor tag not clickable,['css'] +70685,flurry analytics vs google analytics on the mobile platform i am working on a mobile app on the android platform and going forward for the iphone and am evaluating the flurry analytics and google analytics platforms for the app both platforms have sdks for the android and the iphone and seem very similar in most ways do any of you have experience with both or either and could you highlight some of the noticeable differences between the twothanks,"['iphone', 'android']" +70693,how to connect an existing sql server login to an existing sql server database user of same name is there a sql server command to connect a user of a single database to a login for the database server of the same nameheres the exampledatabase server default instancedatabase testdbserver login testuserexisting user on testdb testuserif i try to make the testuser login a user of the testdb database the user group or role already exists does anybody know of an easy way to assign the user to the login,['sql'] +70695,integer division how do you produce a double for this code blockint num 5int denom 7double d num denomthe value of d is 00 it can be forced to work by castingdouble d double num denombut is there another way to get the correct double result i do not like casting primitives who knows what may happen,['java'] +70697,exc bad access when using sqlite fmdb and threads on ios 40 i am using fmdb to deal with my database which works fine the app uses a background thread which is doing some work and needs to access the database at the same time the main thread needs to run some queries on the same database fmdb itself has a little locking system however i added another to my classesevery query is only performed if my class indicates that the database is not in use after performing the actions the database gets unlocked this works as expected as long as the load is not too high when i access a lot of data with the thread running on the main thread an exc bad access error occurshere is the looking boolisdatabaselocked return isdatabaselocked pile lockdatabase isdatabaselocked yes return self fmdatabase lockeddatabase synchronizedself while self isdatabaselocked usleep20 nslogwaiting until database gets unlocked isdatabaselocked yes return selfdatabase pile unlockdatabase isdatabaselocked no return self the debugger says that the error occurs at fmresultset next at the linerc sqlite3 stepstatementstatementi double checked all retain counts and all objects do exist at this time again it only occurs when the main thread starts a lot of queries while the background thread is running which itself always produce heavy load the error is always produced by the main thread never by the background threadmy last idea would be that both threads run lockeddatabase at the same time so they could get a database object that is why i added the mutex locking via synchronizedself however this did not helpdoes anybody have a clue,"['iphone', 'objective-c']" +70699,glassfish as an osgi container i am evaluating osgi containers and the subject came up of using glassfish to contain my osgi application components my question is is glassfish good for this does anybody have any experience using it in this waybackground the application is not a java ee application it is a spring application i have been evaluating felix tomcat i have never used glassfish but it has some features that our operations people are interested inthanks,['java'] +70705,set imageview width and height programmatically how can i set an imageviews width and height programmatically,['android'] +70706,convert integer into its character equivalent in javascript i want to convert an integer into its character equivalent based on the alphabet for example0 a1 b2 c3 detc i could build an array and just look it up when i need it but i am wondering if there is a built in function to do this for me all the examples i have found via google are working with ascii values and not a characters position in the alphabetcheers,['javascript'] +70718,can i pass a parameter directly to a js file and how do i get the value i want to pass a parameter to some javascript using a single line of code like thisscript languagejavascript srccourselistjssubjmath typetextjavascript inside the javascript file how can i get the value of the parameter subjthanks,['javascript'] +70719,javascript inheritance instanceof not working i am writing a simple platform game using javascript and html5 i am using javascript in an oo manner to get inheritance working i am using the following function copyprototypedescendant parent var sconstructor parenttostring var amatch sconstructormatchsfunction if amatch null descendantprototypeamatch1 parent for var m in parentprototype descendantprototypem parentprototypem for the sake of this post consider the following examplefunction a thisname class aaprototypeprintname function alertthisnamefunction b thisacopyprototypeb afunction c thisbcopyprototypec bvar instc new cif instc instanceof a alert horrayas i understand it i would expect to see a horray alert box because c is an instance of c b a am i wrong or am i just using the wrong method to check or has copyprototype knackered the instanceof operatorthanks as always for taking the time to read thisshaw,['javascript'] +70724,how does typeof work i am curious what the method body for typeof in c would look like pretty sure i cannot get to it in reflector as it is a keyword not a methodi am guessing it is equivalent to gettypemagic convert symbol to stringlooking at gettypestring in reflector it calls a method privategettype which calls runtimetypehandlegettypebyname and runtimetypehandle seems to have a lot of the logic behind types in it but the gettypebyname stuff does not show up in reflector,['c#'] +70743,why use heap memory in java why do we use heap memory can we use stack memory for the sameeditedone more question came in my mind after reading answers1 is there any other kind of memory which we can think of alternative to heap and stackeditedi came across the string pool is that memory associated with the heap or stack,['java'] +70752,how to append data to json in rubyrails say i have this short codeitem itemfindparamsidrender json itemto jsonbut i needed to insertpush extra information to the returned json object how do i do that lets say i need to insert this extra infomessage it worksthanks,"['ruby-on-rails', 'ruby']" +70772,javascript optional arguments in function i have a typical javascript function with some parametersmy function functioncontent options action if i call the function as such my function optionsthe argument options is passed as contenthow do i go around this so i can either have both arguments passed or just one thank you,['javascript'] +70779,how can i change the doctype anyone here know how i can dynamically change the doctype with javascripti have tried with this function documentdoctypedoctype html public w3cdtd html 32 finalen but it does not work,"['javascript', 'html']" +70804,java userhome to return in local language when i run systemgetpropertyuserhome on turkish windows 7 i get cusersa even though users folder does not exist in my computer i have the turkish translation of users how can i get the correct userhome informationthank you,['java'] +70831,how to select a radio button by default aspnet mvc strongly typed html helpers i have a radio button list like thishtmlradiobuttonform mgendermalei want this button selected by default how do i do this,['html'] +70832,python splitting list based on missing numbers in a sequence i am looking for the most pythonic way of splitting a list of numbers into smaller lists based on a number missing in the sequence for example if the initial list wasseq1 1 2 3 4 6 7 8 9 10the function would yield1 2 3 4 6 7 8 9 10orseq2 1 2 4 5 6 8 9 10would result in1 2 4 5 6 8 9 10,['python'] +70833,why is typeof needed something i have been thinking about from time to time why is the typeof operator needed in c does not the compiler know that public class animal is a type just by the very definition why do i need to specify somemethodtypeofanimal when i need to reference a type,['c#'] +70839,comandroidinternalpolicyimplphonelayoutinflater sometimes remaining in memory hprof dumps i am inspecting memory trying to find eventual memory leaks via hprof dumpsi find that sometimes when i leave an activity via back button which would finish the activity the activity would still remain in memory but it would only have two gc root which do not seem to be very strong thoughthis is my activity flow the way i click and testa b c being activities1 a b back to a2 do a hprof dump with the following resultb is still in memory the only elements in gc root of b activity are commyappandroidactivitydirectorybmcontext of comandroidinternalpolicyimplphonelayoutinflatermlayoutinflater of androidappcontextimpl stack locallocal variable of javalangthread thread mainmoutercontext of androidappcontextimpl stack locallocal variable of javalangthread thread mainthread main seems to be the ui threadcontinue from a3 a c back to a4 do a hprof dump with the following result as expectedb is not in memory anymore c is not in memory anymore only anow my question iswhere does this phonelayoutinflater come from why does it remain in memory when i return from b to a but it would be gone after went further on to c and return back to aobviously the phonelayoutinflater is for inflating views i am aware of it is purpose i just do not see why it would be kept in memory via the gc root from the main ui threadwhen i check the gc roots of above listed local variable of javalangthread thread mainit would have the followingmuithread of commyappandroidactivitymaina stack localthis0 of androidviewinputmethodinputmethodmanagercontrolledinputconnectionwrapper jni globalthe way i call the activities b and c from a is via a regular startactivityintentwhy would the main ui thread of activity a somehow be related and referenced from activity b,['android'] +70843,how to implement search like stack overflow i have implemented the full text search using sphinx and thinking sphinxi want to add column wise search some thing liketaking an example of stack overflowsuppose you want to see actvities related to you just type usermethen it will return a result with all the questions and answers related to piemesonsif you type votes15then it will return a result with all the questions tagged with having more than 15 votesand if you type userme votes15then it will return all the questions and answers belonging to you with more than 15 voteshow can i implement this thingright now my search results are based upon full text search how can these kinds of features be includedany options avaliable in sphinx or solr or any other search engines,['ruby-on-rails'] +70851,strange things in javascript for i am using jquery and i have a strange thing that i do not understand i have some codefor i 1 i some number i some button iclickfunction alerti some button as the name says they are some buttons when clicked they should popup a box with it is number correct but they do not if there is 4 buttons they always popup 5 buttons count 1 why is that so,"['javascript', 'jquery']" +70859,c virtual override functions with same name i have something like that simplifiedclass a public virtual void function 0class b public virtual void function 0class impl public a public b public how can i implement the function for a and the function for b visual c lets you only define the specific function inline ie not in the cpp filebut i suppose it is an extension gcc complains about thisis there a standard c way to tell the compiler which function i want to overridevisual c 2008class impl public a public b public void afunction cout afunction endl void bfunction cout bfunction endl thank you,['c++'] +70861,html list tag not working in android textview what can i do html list tag not working in android textview this is my string contentstring stra dressy take on classic gingham in a soft textured weave of stripes that resembles twill take a closer look at this oneullitrim tailored fit for a bespoke feellilimedium spread collar onebutton mitered barrel cuffsliliapplied placket with genuine motherofpearl buttonslilisplit back yoke rear side pleatslilimade in the usa of 100 imported cottonliuli loaded it in a text view like thistextviewsettexthtmlfromhtmlstrthe output looks like a paragraph what can i do is there any solution for iteditwebviewloaddatastrtexthtmlutf8,['android'] +70874,android encryption i am working on an android application and i need to use encryption for one aspect of it i am really indifferent to which algorithm i use aes des rsa etc i am aware that java has a crypto package but i am not familiar with it at all can someone post an example on how to do an encryptdecrypt function,"['java', 'android']" +70888,jquery function when a textbox loses focus i have textbox that i want to run some jquery when the textbox loses focus so after the user clicks out of the text boxi have tried to do thistextboxfocusoutfunction alerthellobut i get an error saying object does not support this property or methodhow can i do this then,['jquery'] +70890,please will you help tune a 7tablejoin mysql count query where tables contain 30 rows i have an sql query that counts the number of results for a complex query the actual select query is very fast when limiting to 20 results but the count version takes about 45 seconds on my current tables after lots of optimizingif i remove the two joins and where clauses on site tags and gallery tags the query performs at 15 seconds if i create 3 separate queries one to select the pay sites one to select the names and one to pull everything together i can get the query down to 6 seconds which is still not good enough this would also force me to use a stored procedure since i will have to make a total of 4 queries in hibernatefor the query as is here is some infothe handler read key is 17469the handler read next is 1546324the gallery table has 40 rowsthe site table has 900 rowsthe name table has 800 rowsthe tag table has 3560 rowsi am pretty new to mysql and tuning and i have indexes on the term column in the tag table published column in the gallery table value for the name tableany help to get this query to 01 millseconds would be appreciated because i am at a total loselect countthistinct galleryidfrom gallery gallery inner join site site on gallerysite id siteid inner join site to tag p2t on siteid p2tsite id inner join tag site tag on p2ttag id site tagid inner join gallery to name g2mn on galleryid g2mngallery id inner join name name on g2mnname id nameid inner join gallery to tag g2t on galleryid g2tgallery id inner join tag tag on g2ttag id tagidwhere gallerypublished true and namevalue like sometext or tagterm sometext or sitename like sometext or site tagterm sometext explain data id select type table type possible keys key key len ref rows extra 1 simple site index primarynameindex nameindex 258 null 950 using index using temporary 1 simple gallery ref primarypublishedindexfkf44c775296eece37publishedsiteidindex fkf44c775296eece37 9 productionsiteid 20 using where 1 simple g2mn ref primaryfk3effd7f8afad7a5efk3effd7f832c04188 fk3effd7f8afad7a5e 8 productiongalleryid 1 using index thistinct 1 simple name eq ref primaryvalueindex primary 8 productiong2mnname id 1 thistinct 1 simple g2t ref primaryfk3ddb4d63afad7a5efk3ddb4d63e210fba6 fk3ddb4d63afad7a5e 8 productiong2mngallery id 2 using where using index thistinct 1 simple tag eq ref primarytermindex primary 8 productiong2ttag id 1 thistinct 1 simple p2t ref primaryfk29424ab796eece37fk29424ab7e210fba6 primary 8 productiongallerysite id 3 using where using index thistinct 1 simple site tag eq ref primarytermindex primary 8 productionp2ttag id 1 using where thistinct individual count speedssql select count from galleryaffected rows 0time 0014msresults 40385sql select count from gallery to nameaffected rows 0time 0012msresults 35615sql select count from gallery to tagaffected rows 0time 0055msresults 165104sql select count from tagaffected rows 0time 02msresults 3560 sql select count from siteaffected rows 0time 01msresults 901sql select count from site to tagaffected rows 0time 03msresults 7026,"['sql', 'mysql']" +70892,google geolocation api use longitude and latitude to get address i have noticed a lot of information about how to get your location using google geolocation looks based on ip but i am wondering if and how i could use this service to input a location longitude and latitude and get back the current address or at least a city statei would like to do this in c but i will work with any languageany advice,['c#'] +70914,java how can i dynamically create an array of a specified type based on the type of an object i would like to take a passed list that i know is homogeneous and from it create an array of the same type as the elements within itsomething likelistobject lst new arraylistobjectlstaddnew integer3 somewhere else assertmy array instanceof integer,['java'] +70915,what are the advantage of using a genericswhereclause call over a nongeneric call i have seen some examples where they transformed a call likevoid addidrawing itemintovoid addtdrawingtdrawing item where tdrawing idrawingbeside tricking the intellisense into thisplaying the name of your class instead of the interface name when calling the function because of inferred type usage in c4 are there any other advantage to using the second approachto answer jon skeet the code our programmer used ispublic observablecollectionidrawing items get private set public void addtdrawingtdrawing item where tdrawing idrawing thisitemsadditemi do not see any advantage here for using a generic instead of just using a parameter of the idrawing type i presume there must be some case where its very appropriate i was curious to see if i was missing something,['c#'] +70916,ambiguous pow function i am trying to make a simple call to the pow function from mathh someihing similar toincludemathhint main float vw w30 vpoww05i think this is float powfloatfloat return 0but visual studio says it is an error1cusersuserdocumentsvisual studio 2008projectsdeodeomaincpp7 error c26 pow 6 overloads have similar conversions1 cprogram files x86microsoft visual studio 90vcincludemathh575 could be long double powlong doubleint1 cprogram files x86microsoft visual studio 90vcincludemathh573 or long double powlong doublelong double1 cprogram files x86microsoft visual studio 90vcincludemathh527 or float powfloatint1 cprogram files x86microsoft visual studio 90vcincludemathh525 or float powfloatfloat1 cprogram files x86microsoft visual studio 90vcincludemathh489 or double powdoubleint1 cprogram files x86microsoft visual studio 90vcincludemathh123 or double powdoubledouble1 while trying to match the argument list float doublei thought i had the format float powfloat float,['c++'] +70922,how can i make a class in c that i can initialize just like a string i want to be able to initialize a class just like i initialize a stringstring str hellomyclass class helloi really do not know what exactly string str hello does i assume hello gets translated by the compiler into new systemstringhello but i am not sure maybe is just not possible or maybe i am missing something very elemental if that is the case excuse my ignorance what i am trying to make is a class that works just like a string but stores the string in a file automaticallyok heres my code after reading you answersclass stringonfile private static string extension htm private string fullpath public bool preserve false public string fullpath get return fullpath public static implicit operator stringonfilestring value stringonfile this new stringonfile int path 0 do path this fullpath pathgetfullpathpathtostring extension whilefileexiststhis fullpath using streamwriter sw filecreatetextthis fullpath swwritevalue return this public static implicit operator stringstringonfile stringonfile using streamreader sr fileopentextstringonfile fullpath return srreadtoend stringonfile ifpreserve filedeletefullpath what do you think,"['c#', '.net']" +70931,what type of webservice works best with ios i am going to be creating an internal app for the iphone and ipad that will keep track of sales calls the associated quotes photos and drawings for those quotes i am still in the concept design phase and i am trying to read up on the different ways to communicate between my app and the webservice obviously since this will be used mostly over 3g or edge i want an efficient protocol so my gut reaction is to stay away from xml based things like xmlrpc or soap i would like to use php and mysql on the server and plan on using core data on iosso i have a couple specific questionswhat scheme should i use for performancewhat scheme should i use for ease of working with on the serverwhat scheme should i use for ease of working with on ioswhat scheme should i use considering the project as a wholeis using an xml based scheme better despite the network overhead why,"['php', 'iphone', 'ios']" +70945,html5 files and filelists path i am wondering where the file path is stored in a file object in html javascripti used the webkit devtools and got thisfilelist0 file filename scriptjs filesize 71268 name scriptjs size 71268 type applicationxjavascript proto filelength 1 proto filelistthe file name size and types are thereanyone knows why name and size have 2 variables but the path is notis there any way to find path of the file and if not how does the browser and javascript read the filesuch as post methods determining the type and size,"['javascript', 'html']" +70956,iphone reading from localizablestrings file as a keyvalue in a dictionary i want to read the text from the localizablestrings file i am collecting the strings for translation from several directories and file in one strings file but then i have several copies of the same translation strings i want to remove this programmatically so i need to read the strings only not the comments from the strings file and then sort them remove repeated stringsthen create a new strings file is it possible to read the strings file and keep the key string and translated value in a dictionary i mean any builtin method to read a text file only the key value part avoiding or comments part like reading a config file,['iphone'] +70962,trying to output my logcat to a file i have been told it is a command line option but eclipses runrun configurationstargetadditional emulator command line options field is already occupied withsdcard candroidsdkwindowstoolssd9mimgif i wanted to write something like adb logcat s messagebox cusersmedocumentslogcatoutputtxtthen where do i write it and how ie is the syntax even correct i need to output only a filtered tag not verbose messagebox is my tag again i do not know if any of this punctuation is right or even where the command goesthanks for any help,['android'] +70965,what is the best way to efficiently calculate which points are close to a given latlong using mysql i am trying to design a mysql schema that can store a list of users with an associated latitude and longitude i would then for a given user like to build a query which can return the nearest 50 users to himher and sort those users by thistance with the nearest being presented firstgiven that there may be many thousands of users in this table what is the most efficient way to store and query this data,['mysql'] +70971,python xlwt adjusting column widths i am enormously impressed with the ease of use of xlwt but there is one thing i have not figured out how to do i am trying to adjust certain rows to the minimum width they would need to thisplay all characters in other words what excel would do if you double clicked on the divider between cells i know how to adjust the column widths to a predetermined amount but i am not certain how to determine the minimum width needed to thisplay everything,['python'] +70978,how to find out dcs dimensions let us say i have a handle to device context naturally in windows environmenthdc hdchow can i get the width and height of it,['c++'] +71008,algorithm challenge merging date range i am facing an interesting problem i have several date ranges that can overlapeach of them has a nameis it possible to desoverlap theses ranges that is to generatea new set of ranges where none overlaps the otherseach of this new range has a list of corresponding namesmaybe i can make this a bit more graphical this is what i have firsta b c this is what i would like to obtain a ac abc ab bi found a solution that kind of works but which is not eleganti transform each range from to into a list of days d1 d2 d3 etci group names by dayi aggregate groups that contain the same names to recreate rangescan you think of a better solution i am working with c but any language independent idea would be much appreciated thanks,['c#'] +71021,sql inner join 2 tables with multiple column conditions and update i am using this script trying to join 2 tables with 3 conditions and update t1 update t1 set t1inci t2inci on t1brands t2brands and t1category t2categoryand t1date t2datebut i encounterincorrect syntax near the keyword oncannot figure it out why,['sql'] +71029,turn nsstring into integer sorry guys i am a noob i know that some languages support type casting but when i tried to do that here it failed miserably i have got an uitextfield with number only pad so i am only getting numbers and i need the output from that in my int diff heres what i triednsstring outputnumber nsstring stringwithformatd textboxtext diff outputnumber intvalue not so muchwhat happens is my diff goes to some incredibly high number instead of the single digets i tested with any help i could get is great thanks,"['iphone', 'objective-c']" +71030,why are ajax requests limited to same domain something i find really confusing is why are ajax requests limited to the same domain what is the reasoning behind thisi do not see any problem with requesting files from external locations also servers making xmlhttp requests seem to get and post to external locations fine,['javascript'] +71033,how do i prevent exclamations via a regex public static final string regex address zip 09 the above regex for validating zip code seems to allow exclamation even though i have not allowed it here not sure what the mistake is do i need to change the regex pattern,['java'] +71045,iphone etc how to tell if the device has a camera version 313 if its relevantthere is this suggestion which may work now but in the futurensstring device uidevice currentdevicemodelifdevice isequaltostringiphone,['iphone'] +71050,performance of systemruntimecaching i have compared the performance of systemruntimecaching in net 40 and the enterprise library caching block and to my surprise it performs terribly in comparison when fetching large data collections from cache itemsenterprise library fetches 100 objects in about 015ms 10 objects in about 025ms this is fast and natural for an inprocess cache because no data actually needs to be copied only referencesthe net 40 caching fetches 100 objects in about 25ms 10 objects in about 1500ms this is terribly slow in comparison and it makes me suspect the caching is done outofprocessam i missing some configuration option for example to enable inprocess caching or is the enterprise library caching block really this much fasterupdateheres my benchmarkfirst i load the data from the database to the cache separate from the benchmarki use a timer around the get methods to measure the time in millisecondsenterpriselibrary cachingmicrosoftpracticesenterpriselibrarycachingcachemanager cachepublic void initcache cache cachefactorygetcachemanagermycachenamepublic void benchmark highperformancetimer timer new highperformancetimer timerstart myobject o myobject cachegetdatamycachekey timerstop responsewritetimergetasstringinmillisecondsnet 40 caching systemruntimecachingmemorycache cache public void initcache cache new memorycachemycachename public void benchmark highperformancetimer timer new highperformancetimer timerstart myobject o myobject cachegetmycachekey timerstop responsewritetimergetasstringinmilliseconds the benchmark is executed 10 times to compute average time to fetch the object to ensure reliability of the test the timer is a custom timer i use any timer counting milliseconds should dothe interesting thing is that the myobject has numerous references if there was any serialization involved i would understand why the performance differs for this object like in thistributed caching but these are both inprocess caches that theoretically should work without many major differences at all,['.net'] +71070,entity framework how to update database when modifying model in entity framework 4 there are the options update model from database and generate database from model but what i am missing is an option likeupdate database from modelwhich reflects the changes made in the model eg adding a new property or navigationproperty by modifying the database schema eg adding a new column without losing its contentdoes someone know a way to achieve this or is there a t4 template that can perform a schema update without dropping existing tables i am using visual studio 2010 net 40 and sql server 2008thanks,['c#'] +71080,java 3 dots in parameters what do the 3 dots in the following method meanpublic void mymethodstring strings method body,['java'] +71132,draw a rounded uiview with gradient and drop shadow editi finally found a real simple solution to this problem using the cagradientlayer class and the calayer drawing functionalitiesole begemann released a great uiview wrapper for cagradientlayer class named obgradientviewthis class allows you to easily create a gradient uiview in your applicationyou then use the calayer drawing functionalities to add the rounded corners and drop shadow values create the gradient viewobgradientview gradient obgradientview alloc initwithframesomerectnsarray colors nsarray arraywithobjectsuicolor redcolor uicolor yellowcolor nilgradientcolors colors set rounded corners and drop shadowgradientlayercornerradius 50gradientlayershadowcolor uicolor graycolorcgcolorgradientlayershadowopacity 10gradientlayershadowoffset cgsizemake20 20gradientlayershadowradius 30selfview addsubviewgradientgradient releasedont forget to add the quartzcore framework to your projectoriginal questioni have been working on a custom control that is a rounded rectangle button filled with a linear gradient and having a drop shadowi have filled the two first steps using this answer link textmy problem is now to add a drop shadow under the resulting shapeactually the context has been clipped to the rounded rect path so when i use the cgcontextsetshadow function it does not draw iti tried to solve this problem by drawing the rounded rect twice first with a plain color so it draws the shadow and then redraw it with the gradient fillit kinda worked but i still can see a few pixels at the corners of the shape resulting from the first draw with a plain color as you can see on this zoomed version it is almost good but not perfect yethere is my drawrect implementation static void addroundedrecttopathcgcontextref context cgrect rect float ovalwidth float ovalheight float fw fh if ovalwidth 0 ovalheight 0 cgcontextaddrectcontext rect return cgcontextsavegstatecontext cgcontexttranslatectm context cgrectgetminxrect cgrectgetminyrect cgcontextscalectm context ovalwidth ovalheight fw cgrectgetwidth rect ovalwidth fh cgrectgetheight rect ovalheight cgcontextmovetopointcontext fw fh2 cgcontextaddarctopointcontext fw fh fw2 fh 1 cgcontextaddarctopointcontext 0 fh 0 fh2 1 cgcontextaddarctopointcontext 0 0 fw2 0 1 cgcontextaddarctopointcontext fw 0 fw fh2 1 cgcontextclosepathcontext cgcontextrestoregstatecontext voiddrawrectcgrectrect cgcontextref context uigraphicsgetcurrentcontext cgsize shadowoffset cgsizemake100 100 cgfloat blur 50 rectsizewidth shadowoffsetwidth blur rectsizeheight shadowoffsetheight blur cgcontextsavegstatecontext addroundedrecttopathcontext rect radius radius cgcontextsetshadow context shadowoffset blur cgcontextdrawpathcontext kcgpathfill cgcontextrestoregstatecontext addroundedrecttopathcontext rect radius radius cgcontextclipcontext cgfloat colors gradientstartcolorred gradientstartcolorgreen gradientstartcolorblue gradientstartcoloralpha gradientendcolorred gradientendcolorgreen gradientendcolorblue gradientendcoloralpha size t num locations 2 cgfloat locations2 00 10 cgcolorspaceref rgb cgcolorspacecreatedevicergb cggradientref gradient cggradientcreatewithcolorcomponentsrgb colors locations num locations cgrect currentbounds selfbounds cgpoint gstartpoint cgpointmakecgrectgetmidxcurrentbounds 00f cgpoint gendpoint cgpointmakecgrectgetmidxcurrentbounds cgrectgetmaxycurrentbounds cgcontextdrawlineargradientcontext gradient gstartpoint gendpoint 0 cgcolorspacereleasergb cggradientreleasegradientany ideas on how to do this in another way thanks,['iphone'] +71162,sql correlated subquery in a case clause is it possible to write a subquery within a case clause for the when statementie select cola colb case when select cola from tab2 where tab2cola tab1cola then 1 case when select cola from tab3 where tab3cola tab3cola then 2 else 0 end as colc from tab1extended questionis it possible to do something based on that value column pretty sure yes but would like confirmationiecase when colc 1 then select colr from when colc 2 then select cols from else does not work end as coldfurthermore is the above case allowed to return multiple and different columns depending on which value colc isie case when colc 1 then select colr colv colx from when colc 2 then select cols cold from else does not work end as coldthanks,['sql'] +71169,how to you abortcancel a request using the prototype js library using this codevar pendingrequest new ajaxrequestmyurl method post postbody soapmsg contenttype textxml onsuccess functiontransport dosomethingtransport onfailure functiont onajaxfailuret onexception functionreqexception onajaxexceptionreq exception how can i cancel the request and thiscard the data or failing that how could i identify the request using a nameguidwhatever inside my onsuccess method so that i can tell which request is completingi was thinking of doing an arraypushpendingrequest to keep track of pending requestsi want to allow the user to interrupt their request change the input values and resubmitsometimes the original request ends after the new request and i am replacing the correct data with the old data search results return 50 records on the first query and 5 in the second for examplethanks,['javascript'] +71182,difference between angle bracket and double quotes while including header files in c possible duplicatewhat is the difference between include filename and include afilenamea what is the difference between angle bracket and double quotes while including header files in ci mean which files are supposed to be included using eg include qpushbutton and which files are to be included using eg include myfileh,"['c++', 'c']" +71186,whats a quick way to convert a list to string toarray does not do it,['c#'] +71191,background worker c winform is it a bad idea to load everything in from the background workercurrent code is executed on form load we are pulling a lot of data from webservice some long running works are in background worker would it be a bad idea to load everything from background worker no matter how small or big the code isevery function to run in background worker or is this going to make this code messy and treading nightmarethank you,['c#'] +71196,unstructured text to structured data i am looking for references tutorials books academic literature concerning structuring unstructured text in a manner similar to the google calendar quick add buttoni understand this may come under the nlp category but i am interested only in the process of going from something like levi jeans size 32 a0b293to brand levi size 32 category jeans code a0b293i imagine it would be some combination of lexical parsing and machine learning techniquesi am rather language agnostic but if pushed would prefer python matlab or c referencesthanks,['python'] +71198,how to make gcc search for headers in a directory before the current source files directory i am using gcc precompiled headers in my project with multiarchitecture build but things break down when i try to place it in a directory different from current sources directory the file is included with double quotes and it works if i change it to angle brackets but the problem is that i have a lot of other projects that use the same precompiled header name so changing all of them to angle brackets is not desirable as it may create ambiguity about which header to include in visual studio build of the same filesgcc searches current directory for doublequote includes before its search path i can work around it using i option eg ipch diri686 i so that precompiled headers directory is searched before the current directory but this option is deprecated gcc suggests i use iquote but it does not have the same effect as iso the question is how do i make it work without changing all precompiled headers include directives to angle brackets and using a deprecated gcc switch,['c++'] +71205,differences between runtimecheckeduncheckederrorexception what are the runtime exceptions and what are checkedunchecked exceptions and difference between errorexceptionwhy these many types instead java may simply follow a simple designjust trycatch all types to handle an abnormal condition in a program,['java'] +71207,stop evaluation within a module i have gotten used to writing functions that work like thisdef f if sunny return do nonsunny stuffi am trying to figure out the equivalent syntax to use within a module i want to do something like thisif sunny import tshirt do something here to skip the rest of the fileimport raincoatimport umbrellacontinue defining the module for nonsunny conditionsi know i can write this as an ifelse but it seems silly to indent the entire rest of my modulei could move the rest of the code into a separate module and conditionally import it but that seems painful,['python'] +71210,which border radius property will work in ie9 in ie9 which border radius property will work borderradius20pxwebkitborderradius 20pxmozborderradius 20pxborderradius20px or msborderradius20px,['css'] +71215,javascript thisplaying a float to 2 decimal places i wanted to thisplay a number to 2 decimal placesi thought i could use toprecision2 in javascript however if the number is 005 i get 00500 i would rather it stay the samesee it on jsbinwhat is the best way to do thisi can think of coding a few solutions but i would imagine i hope something like this is built in,['javascript'] +71221,what is the different between isenabled and startstop of thispatchertimer i think that isenabled falsetrue is equally the same with stopstart method of class systemwindowsthreadingthispatchertimeram i righteditstart begin timer with a full interval countdownisenabled false pause the timer the interval countdown remainsisenabled true resume the timer continue with the last used interval countdownstop stop the timer will the interval countdown reset,['c#'] +71234,select the rows affected by an update how can you get the exact rows affected by an sql update statement in mysqli have many clients on many computers that can be updating rows in the same table based on where clauses at any time and each client needs to do something in another system for each row that they affect so getting the list of affected items must be accurate and not vulnerable to raceconditionssome databases support update output updatedid where eg sql serverhow can you do this atomic updateselect in mysqli have seen suggestions of doing the select first and then using the ids as an in clause in the update but another client might run the same select and retrieve the same rows whilst the first client is queuing its update etc,"['sql', 'mysql']" +71253,cherrypy multithreading example i do know that cherrypy is a multithreaded and also has a threadpool implementationso i wanted to try an example showing multithreaded behaviournow lets say i have my some function in the root class and rest all things are configureddef testpageself args kwargs current threadingcurrentthread print starting current timesleep5 print ending current return htmlhello worldhtmlnow lets say i run my page as httplocalhost6060roottestpage in 34 tabs of browserwhat result i get isstarting workerthreadcp wsgiserver thread10 started 4844ending workerthreadcp wsgiserver thread10 started 4844starting workerthreadcp wsgiserver thread7 started 4841ending workerthreadcp wsgiserver thread7 started 4841starting workerthreadcp wsgiserver thread10 started 4844ending workerthreadcp wsgiserver thread10 started 4844the thing i can clearly understand that it is creating new threads for processing every new request but i cannot figure out why every time i get startingendingstartingendingand why not startingstartingendingending sometimesbecause what my assumption is that timesleep will make some thread to suspend and other one can execute at that time,['python'] +71258,can jquery change css style definition not individual css of each element i have not seen any docs saying jquery can change any css definition such as changingtd padding 02em 12em to td padding 032em 2em but either have to change a whole style sheet or change class of each element or change css of each element is changing the style definition possible,"['javascript', 'jquery', 'css']" +71274,how to call stopservice method of service class from the calling activity class i am trying to call my service clas stopservice method from my activitybut i dont know how to access stopservice method from my activity classi have the below code but its not workingthis is homescreen class public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain enablecheck checkboxfindviewbyidridenablecheck enablechecksetoncheckedchangelistenernew oncheckedchangelistener override public void oncheckedchangedcompoundbutton buttonview boolean ischecked todo autogenerated method stub ifenablecheckischecked startservicenew intenthomescreenthis autoserviceclass else stopservicenew intenthomescreenthis autoserviceclass this is service classpublic class autoservice extends service private static final string tag autoservice private timer timer private timertask task override public ibinder onbindintent intent return null override public void oncreate toastmaketextthis auto service created toastlength longshow logdtag oncreate int delay 50 delay for 5 sec int period 50 repeat every sec timer new timer timerscheduleatfixedratetask new timertask public void run systemoutprintlndone delay period override public boolean stopserviceintent name todo autogenerated method stub timercancel taskcancel return superstopservicename any suggestion highly appreciablethanks and regardsmintu,['android'] +71279,how to parsing json object in iphone sdk xcode using jsonframework i have json object like this data array 2 array clientid1clientnameandyjobdeveloper clientid2clientnamepeterjobcarpenter messagemsg01success statusoki want to get the array0 value 2 and array1 value clientid clientname job using jsonframework do you have any idea how to do that,['iphone'] +71282,to use or not to use c0x features possible duplicatehow are you using c0x today i am working with a team on a fairly new system were talking about migrating to msvc 2010 and weve already migrated to gcc 45 these are the only compilers were using and we have no plans to port our code to different compilers any time sooni suggested that after we do it we start taking advantage of some of the c0x features already provided like auto my coworker suggested against this proposing to wait until c0x actually becomes standard i have to thisagree but i can see the appeal in the way he worded it nevertheless i cannot help but think that this counterargument comes more out of fear and trepidation of learning c0x than a genuine concern for standardizationgiven the new state of the system i want for us to take advantage of the new technology available just auto for instance would make our daily lives easier just writing iteratorbased for loops until rangebased loops come along egam i wrong to think this it is not as though i am proposing we radically change our budding codebase but just start making use of c0x features where convenient we know what compilers were using and have no immediate plans to port if we ever port the code base by then surely compilers will be available with c0x features as well for the target platform otherwise it seems to me like avoiding the use of iostreams in 1997 just because the iso c standard was not published yet in spite of the fact that all compilers already provided them in a portable fashionif you all agree could you provide me arguments i could use to strengthen my position if not could i get a bit more details on this until the c0x is standard idea btw anyone know when that is going to be,['c++'] +71295,inserting multiple rows using jdbctemplate how can i execute the following sql in a scalable way using jdbctemplate running on mysql in this case scalable meansonly one sql statement is executed on the serverit works for any number of rowsheres the statementinsert into mytable foo bar values asdf asdf qwer qwerassume that i have a list of pojos with foo and bar fields i realize that i could just iterate over the list and executejdbctemplateupdateinsert into mytablefoo bar values parammapbut that does not does not accomplish the first criterioni believe i could also executejdbctemplatebatchupdateinsert into mytablefoo bar values parammaparraybut from what i can tell that will just compile the sql once and execute it multiple times failing the first criterion againthe final possibility which seems to pass both criteria would be to simply build the sql myself with a stringbuffer but i would like to avoid that,"['java', 'sql']" +71319,what is the difference between casting and conversion eric lipperts comments in this question have left me thoroughly confused what is the difference between casting and conversion in c,['c#'] +71331,aspnet file upload i am trying to make a server page c aspnet 20 to save an uploaded file from another page specifically i have an html page with a form actionuploadaspx and i cannot figure out how to handle saving the file on the server in uploadaspxi found a few examples one being but that requires the input typefile element to be on the same page i am having difficulties with grabbing the posted file on my uploadaspx pageanyone have any pointers how can i grab a posted file in aspx and save it to the server when the file is posted from another pagemany thanksbrett,"['c#', 'asp.net']" +71359,begin rescue not catching error i am using some ruby code wrapped in a begin rescue block but somehow it manages to still crash the block of code looks like this retrieve messages from serverdef get messages connectionselectinbox connectionuid searchalleach do uid msg connectionuid fetchuidrfc822firstattrrfc822 begin process messagemsg add to processed folderuid if processed folder rescue handle bogus messagemsg end mark message as deleted connectionuid storeuid flags seen deleted endendgiven this code i would assume that if process message or add to processed folder could not execute then rescue would kick in and call handle bogus message that being said i am running this code in a production environment and sometimes when i get an email message this is run from a rake task it dies with a syntaxerror for a look at the error message check out and not that process message that it is referring to is the same process message above is there any reason why begin rescue would not catch this exception,"['ruby-on-rails', 'ruby']" +71361,ruby insert spaces every x number of characters in a ruby string how can i insert a space every x number of charactersas an example i would like to insert a space every 8 characters of a given string,['ruby'] +71367,countdownlatch interruptedexception i am using the countdownlatch to synchronize an initialization process between two threads and i was wondering about the proper handling of the interruptedexception that it might throwthe code i initially wrote was this private countdownlatch initwaithandle new countdownlatch1 this method will block until the thread has fully initialized this should only be called from different threads ensure that the thread has started before this is called public void ensureinitialized assert thisisalive the thread should be started before calling this method assert threadcurrentthread this this should be called from a different thread potential deadlock whiletrue try we wait until the updater thread initializes the cache that way we know initwaithandleawait breakif we get here the latch is zero and we are done catch interruptedexception e logwarnthread interrupted e does this pattern make sense basically is it a good idea to ignore the interruptedexception just keep waiting until it succeeds i guess i just do not understand the situations under which this would get interrupted so i do not know if i should be handling them differentlywhy would an interruptedexception get thrown here what is a best practise for handling it,['java'] +71389,get folder size do you know how can i get the folder size in javathe length method in the file class only works for files using that method i always get a size of 0,['java'] +71403,why does this sql query do a key lookup i have a table user with a bunch of indexes one of them is a unique index on the accountidentifier columnsince this is a unique index why is a key lookup required in addition to the index seek the index seek tooltip reports that only one record is returned i have also tried converting the index to a unique key type,['sql'] +71454,long constructor initialization lists how do you deal with them i have some classes usually classes that hold stats etc with some 20 variable members and the initialization lists end up very long extending beyond the page width if i do not manually wrap around do you try and break down such classes or do you deal with this in some other way it does not look very tidy but sometimes i write the variables in the list on top of each other like somyconstructorvar1 var2 var3 varn member1var1 member2var2 member3var3 membernvarn,['c++'] +71457,dropdown menu with scrollbar in net i am trying to make a user control similar to the windows vista7 breadcrumb bar used in windows explorerhowever when i show the drop down menu for a breadcrumb with many sub items i get a very long list that sometimes exceeds the screen sizein the windows vista7 example however there are a maximum of 18 items thisplayed at a time and a scrollbar appears at the right when the number of sub items exceeds this number 18i wanted to know if anyone out there knows a way to replicate what microsoft doesthat is how to place a drop down menu in a control with autoscroll capabilitythanksalex,"['c#', '.net']" +71462,iphone check for existence of constant how can you check if a constant is set at runtime for instance in ios 4 uiapplicationdidenterbackgroundnotification is available but when running on ios 3 it will through an error if you try to use it,['iphone'] +71464,html drag and drop on mobile devices when you add drag and drop to a web page using javascript such as jquery ui draggable and droppable how do you get this to work when viewed via a browser on a mobile device where the touchscreen actions for dragging are intercepted by the phone for scrolling around the page etcall solutions welcome my initial thoughts arehave a button for mobile devices that lifts the item to be dragged and then get them to click the zone they want to drop the item onwrite an app that does this for mobile devices rather then try and get the web page to work on themyour suggestions and comments pleaseupdate bountyif someone can tell me how to make drag and drop work in a web page on a mobile device without resorting to points 1 and 2 above i will swing a wonderful bounty of 50 rep your way,"['javascript', 'html']" +71475,actual meaning of shelltrue in subprocess i am calling different processes with the subprocess module however i have a questionin the following codescallprocess subprocesspopenls l shelltrueand callprocess subprocesspopenls l without shellboth work after reading the docs i came to know that shelltrue means executing the code through the shell so that means in absence the process is directly started so what should i prefer for my case i need to run a process and get its output what benefit do i have from calling it from within the shell or outside of it,['python'] +71476,how can i do digest authentication with httpwebrequest various articles 1 2 i thiscovered make this look easy enoughwebrequest request httpwebrequestcreateurlvar credentialcache new credentialcachecredentialcacheadd new uriurl request url digest authentication type new networkcredentialuser password credentialsrequestcredentials credentialcachehowever this only works for urls without url parameters for example i can download just fine but when i attempt to download the result is a 400 bad request message with the following in the servers logs running apache 22digest uri mismatch test does not match requesturi testpagexyzmy first idea was that the digest specification requires url parameters to be removed from the digest hash but removing the parameter from the url passed to credentialcacheadd did not change a thing so it must be the other way around and somewhere in the net framework is wrongly removing the parameter from the url,['c#'] +71477,best practices for input validation in aspnet what is the common practice of input validation in other words do you check for input validation on clientside on serverside or on both sides also if performance is crucial to me would just the clientside input validation be sufficient for my website without presenting any security risks,['asp.net'] +71481,using where to specify different generics i am writing a bijective dictionary class but i want to ensure the two generic types are not the same type for two reasonsfirstly i would like it to implement the idictionary interface in both directions but public class bijectivedictionarytkey tvalue idictionarytkey tvalue idictionarytvalue tkeygives me bijectivedictionarytkeytvalue cannot implement both idictionarytkeytvalue and idictionarytvaluetkey because they may unify for some type parameter substitutions which is understandable but undesirablesecondly i would like to write an optimized solution if both types are the samepublic class bijectivedictionarytkey tvalue idictionarytkey tvalue where tvalue tkey optimized solutionpublic class bijectivedictionarytkey tvalue idictionarytkey tvalue idictionarytvalue tkey where tvalue tkey standard solutionis this possibleif not i can consider not implementing idictionary but i could not guarantee tvalue thistkey key and tkey thistvalue key would be different which would be unfortunateit looks like the problem here is that when the two types are the same the special cases arisemy original intent was to create a dictionary which maps exactly one key to exactly one value and visa versa such that for every keyvaluepairtkey tvaluex y a keyvaluepairtvalue tkeyy x exists as wellwhen tkey tvalue then this can be simplified down to a single dictionarypublic t thist key get return thiskey set baseaddkey value baseaddvalue key in this case you cannot add23 add34 because add23 maps 3 to 2 as well and 3 would return 2however jaroslav jandeks solution proposed using a second dictionary to do this for cases when tkey tvalue and although this works wonderfully for those cases and what i decided to implement in the end it does not quite follow my original intent when tkey tvalue by allowing add23 add34 to map a single key 3 to two values 2 in one direction and 4 in the other though i believe strictly speaking is still a valid bijective function,"['c#', '.net']" +71492,opencvdotnet and ffmpeg are there any integration options opencvdotnet or its analogs and ffmpeg are there any integration options like open flv flie or save to some exotic format please provide a simple code example,"['c#', '.net']" +71502,text progress bar in the console is there a good way to do the followingi wrote a simple console app to upload and download files from an ftp server using the ftplibeach time some data chunks are downloaded i want to update a text progress bar even if it is just a numberbut i do not want to erase all the text that is been printed to the console doing a clear and then printing the updated percentage,['python'] +71509,nested class access control in c can inner class access a private member variable of its enclosing class there seems to be some contradictions on the internet and compiler compile g on cygwin allows it but some technical documents say that it is not allowed,['c++'] +71511,can a javascript object property refer to another property of the same object i recently tried to create an object like thisvar carousel slider carousel1 slider panes carouselsliderchildrenlength my intentions were to improve jquerys selector performance by caching the results of carousel1 slider in an object property and to keep the code concise and relatively dryhowever this did not work when the code executed it threw an exception when trying to parse the value of panes complaining that carousel was undefinedthis makes sense since i would assume that carousel is not fully declared until the assignment statement has been fully executed however i would like to avoid resorting to thisvar carousel carouselslider carousel1 slidercarouselpanes carouselsliderchildrenlengththat is not too much worse but the carousel object will have several more properties that rely on the values of other properties so that could quickly become verbosei tried using this but to no avail i may well not have been using it correctly or that may not be a valid approach anywayis there a way for properties of an object to refer to other properties of the same object while that object is still being declaredbased on matthew flaschen and casablancas answers thanks guys i think these are the versions of my actual code that i would end up with based on each approach matthew flaschenvar carousel new function thiscarousel carousel thiscarousel window thiscarouselfindwindow thiscarousel slider thiscarouselfindslider thisfirst pane thiscarouselfindsliderchildrenfirstchild thispanes thiscarousel sliderchildrenlength thispane gap thisfirst panecssmarginrightand casablancavar carousel carousel carousel slider carouselfindslider first pane carouselfindsliderchildrenfirstchildvar properties carousel window carouselfindwindow panes carousel sliderchildrenlength pane gap first panecssmarginrightpropertiescarousel carouselpropertiescarousel slider carousel sliderpropertiesfirst pane first paneassuming those are both correct i have not tested them it is kind of a tough call i think i slightly prefer matthew flaschens approach since the code is contained to a structure that more closely resembles an object declaration there is also ultimately only one variable created however there is a lot of this in there which seems repetitive although that may be just the price to pay,['javascript'] +71540,is there any limit on number of html elements that browser can thisplay without problems basically i have got a huge table which gets even bigger as user scrolls down auto preloading subsequent rows at some point browser becomes sluggish it starts to hang for a moment as i click around or try to scroll and more sluggish it becomes the more rows it gets i wonder if there is any limit on number of elements that page can hold or maybe it is just my javascript leaking somewhere although i have got only one event handler attached to the tbody of the table and a script that parses bubbled mousedown eventsupdate delay becomes noticeable after a thousand of loaded rows the speed of scroll itself is pretty bearable but for example highlighting of the clicked row with the help of single event handler on tbody is painful it takes at least 23 seconds and delay grows with the number of rows i observe delay on all browsers it is not only me but almost everyone who visits the page so i guess at some extent it affects every platformupdate i came up with simple example here you can pass whatever number you want to num basically it renders a table with num rows and has a single event handler attached to a parent table i should conclude from this that there actually is no noticeable dropdown in performance caused by number of child elements so it is probably a leak somewhere else,['html'] +71552,type for array index in c99 what type for array index in c99 should be used it have to work on lp32 ilp32 ilp64 lp64 llp64 and more it does not have to be a c89 typei have found 5 candidatessize tptrdiff tintptr t uintptr tint fast t uint fast tint least t uint least tthere is simple code to better illustrate problem what is the best type for i and j in these two particular loops if there is a good reason two different types are fine toofor i0 iimax i do somethingai jmin can be less than 0 for jjmin jjmax j do somethingajpsin the first version of question i had forgotten about negative indexesppsi am not going to write a c99 compiler however any answer from a compiler programmer would be very valuable for mesimilar questionsize t vs intptr tthe context of this question if different though,['c'] +71570,push notification error unable to set local cert chain file i wrote a test php page that just sends out a generic push notification and it works intermittently sometimes it delivers the message and other times i get this errormessage stream socket client functionstreamsocketclient unable to set local cert chain file varwninerobotcompublicmlbcertsmlbtrpushdevpem check that your cafilecapath settings include details of your certificate and its issuerdo you know how i can solve this issuei see that on apples docs it says note to establish a tls session with apns an entrust secure ca root certificate must be installed on the provideras server if the server is running mac os x this root certificate is already in the keychain on other systems the certificate might not be available you can download this certificate from the entrust ssl certificates website does this mean anything that i need to do,['iphone'] +71574,how can i download an xml file using c given this urlhow can i download the resulting xml file and have it loaded to memory so i can grab information from it using linqthanks for the help,"['c#', '.net']" +71581,jquery if children with specific class i wonder how i can determine if a ul has more than 2 children and if there are two children with two specific classes inside this ul aifthischildrenlength 2 thischildrensectiontitle active thisappendli classdotshellipli,['jquery'] +71586,cannot change font to helvetica in matplotlib in python on mac os x 106 i am trying to change the matplotlib font to helvetica which i would like to use in a pdf plot i try the followingimport matplotlibmatplotlibusepdfimport matplotlibpylab as pltfrom matplotlib import rcpltrcparamspsuseafm truercfontfamilysansserifsansserifhelveticapltrcparamspdffonttype 42this does not work when i run my code with verbosedebug i get the errorbackend wxagg version 28101libraryframeworkspythonframeworkversions62libpython26sitepackagesmatplotlib init py833 userwarning this call to matplotlibuse has no effectbecause the the backend has already been chosenmatplotlibuse must be called before pylab matplotlibpyplotor matplotlibbackends is imported for the first timefindfont could not match familysansserifstylenormalvariantnormalweightnormalstretchnormalsizemedium returning libraryframeworkspythonframeworkversions62libpython26sitepackagesmatplotlibmpldatafontsttfverattfassigning font f1 libraryframeworkspythonframeworkversions62libpython26sitepackagesmatplotlibmpldatafontsttfverattfembedding font libraryframeworkspythonframeworkversions62libpython26sitepackagesmatplotlibmpldatafontsttfverattfwriting truetype fontso apparently it cannot find helvetica i am not sure why i have helvetica in the afm directory of mpldata and when matplotlib initiates it reads it and outputscreatefontdict libraryframeworkspythonframeworkversions62libpython26sitepackagesmatplotlibmpldatafontsafmhelveticaafmdo i need a special ttf helvetica font in addition if so how can i get it i know i have helvetica on my system since i see it in illustrator and many other programs i am using enthought python thistribution as follows pythonenthought python thistribution version 622 32bitpython 265 epd 622 32bit r26579063 may 28 2010 151303 gcc 401 apple inc build 5488 on darwintype help copyright credits or license for more information import matplotlib matplotlib version 0993any ideas how this can be fixedthanks,['python'] +71595,is there a good javascript based html parsing library available my goal is to take html entered by an end user remove certain unsafe tags like script and add it to the document does anybody know of a good javascript library to sanitize htmli searched around and found a few online including john resigs html parser erik arvidssons simple html parser and googles caja sanitizer but i have not been able to find much information about whether people have had good experiences using these libraries and i am worried that they are not really robust enough to handle arbitrary html would i be better off just sending the html to my java server for sanitization,"['javascript', 'html']" +71621,android customizing the spinner widget look and feel is it possible to change the color of the radio button in the android spinner widget by default it thisplays the green color for the radio button i need to change it to some other color is it possible and how,['android'] +71639,javascript comments are security risk during a recient pci audit the auditor said that we had major security risks because it was possible to download static resources from our website such as images css and javascript without prior authenticationour javascript had comments in itpersonally i think that this is not a security risk at all the images css and javascript where not dynamically created and they contained no data on our backend our customer details and on mechanismsthe comments within the javascript were just simply explaining what the methods in the javascript file did which anyone who reads js could have found out anyway how does that show information leakage are comments within javascript really a security risk,['javascript'] +71656,how do i install the ruby ri documentation i have recently installed ruby 191 on windows 7 and apparently it does not come with the standard ri documentation so when i do ri array i getcri arraynothing known about arrayis there a way i can install this documentation so that the above works,['ruby'] +71659,complex tsql order by clause is it possible to craft an order by clause to ensure the following criteria for two fields both of type int called child and parent respectively for this exampleparent references child but can be nulla parent can have multiple children a child only one parenta child cannot be a parent of itselfthere must exist at least one child without a parenteach value of child must appear before it appears in parent in the ordered result seti am having difficulty with point 5sample unordered datachild parent1 null3 54 22 55 nullobviously neither order by a b or order by b a work in fact the more i think about it i am not sure it can even be done at all given the restrictions obvious cases such aschild parent1 22 1are not allowed because it violates rule 3 and 4 and obviously 5so is what i am trying to achieve possible and if so how platform is sql server 2005update desired sort order for the sample datachild parent1 null5 null2 53 54 2for each row that defines a nonnull value in the parent column the value has already been present int the child column,['sql'] +71670,multithread debugging techniques i was wondering if anyone knows of a nice survey of debugging techniques for multithreaded applications ideally i am looking for a casebased analysis deadlocks starvation corrupted shared state net specific or generic,['.net'] +71672,how to receive multicast packets on android i am trying to receive data from a multicast address but the call to multicastsocketreceive blocks until a timeout takes place i did some network sniffing and found out that my device and the emulator never send a multicastsocketjoingroup request i tried running the same java code from my pc as a standalone application and it worked well could it be that the android platform blocks igmp join requestshas anyone succeeded with multicast on android beforemy manifest file contains the following permissioni am running my application on 21 both emulator deviceany ideas anyonethanks,['android'] +71678,representing x of y in sql in my database i have a lot of courses that are compulsory some are elective however there are courses of a third kind a list from which you have to choose x courses the list and the number x is different for each study program how would you represent this relationally,['sql'] +71681,c dictionary values to hashset conversion please suggest the shortest way to convert dictionarykey value to hashsetvalueis there builtin tohashset linq extension for ienumerables thank you in advance,['c#'] +71690,recommended jsf 20 crud frameworks can somebody recommend any framework to facilitate crud development in jsf 20aspects i value mostas lightweight as possible limited dependencies on third party librariessupport for an evolving domain modellimited need for repetitive coding support for scaffolding andor metaannotations any hints highly appreciatedyoursj,['java'] +71697,php json encode returning null array secho 1 itotalrecords 7521 itotalthisplayrecords 1 aadata array 0 array 0 nordic capital buys sic processing 1 20100621nordiccapitalbuyssicprocessing 2 pehub media 3 business 4 completed 5 nordic capital has acquired a 70 stake in sic processing ag a german industrial recycling company from frog capital no sale price was thisclosed sic processingas founding family retains a 25 holding while former lead investor zouk ventures retains a 5 stake 6 admin china frog capital germany italy iyad omari manufacturing norway pehub media photovoltaic wafer manufacturing renewable energy semiconductor united states echo json encodemyarrsecho1itotalrecords7521itotalthisplayrecords1aadata nordic capital buys sic processingadiv 20100621nordiccapitalbuyssicprocessingdivpehub mediabusinesscompletednull admin china frog capital germany italy iyad omari manufacturing norway pehub media photovoltaic wafer manufacturing renewable energy semiconductor united statesnote the null in the middle of the string after completedwhy is this what escapemanipulation do i need to perform in order to encode thisi have tried addslashes,['php'] +71711,how to detect onlineoffline event crossbrowser i am trying to accurately detect when the browser goes offline using the html5 online and offline eventsheres my codescript firefox windowbindonline applicationbackonline windowbindoffline applicationoffline ie windowonload function documentbodyononline ieconnectionevent documentbodyonoffline ieconnectionevent scriptit works fine when i just hit work offline on either firefox or ie but it is kind of randomly working when i actually unplug the wire whats the best way to detect this change i would like to avoid repeating ajax calls with timeouts,"['javascript', 'jquery']" +71715,iterating over jquery thisattrclasplit gives odd results i have got a page where i am trying to fetch arrays of classes for lots of divs which share a common class for example div classcommon lorem ipsumdivdiv classcommon dolor sitdivdiv classcommon hello worlddivi want to fetch each common class div and get an array of it is classes at the moment i am doing it by using this bit of jquerycommoneachfunctionindex var classes thisattrclasplit forvar i in classes alertclassesi looking at the first resulting classes variable gives thisclasses array 30 common1 lorem2 ipsumlength 3 proto arraythe problem is that the forvar i in classes seems to be iterating over the proto array and delving down into that as well has anybody ever come across this before i am using the latest version of chrome 604531,"['javascript', 'jquery', 'css']" +71744,javaiostreamcorruptedexception invalid type code ac i am trying to read some objects from a file the code works fine for the first iteration and at the second iteration it gives a streamcorruptedexception here is my codeprivate arraylistcheque cheques nullobjectinputstream ois null try cheques new arraylistcheque4 ois new objectinputstreamnew fileinputstreamsrceasychequedatatemplatesdat object o null try o oisreadobject int i1 while o null chequesaddcheque o systemoutprintlni prints the number of the iteration o oisreadobject exception occurs here catch classnotfoundexception ex for ois readobject loggergetloggertemplatereaderclassgetnameloglevelsevere null ex catch eofexception ex for ois readobject end of the file reached stop reading systemoutprintlnois closed oisclose catch ioexception ex loggergetloggertemplatereaderclassgetnameloglevelsevere null ex below is part of the exception before printing this 1 is printed because of the soutsevere nulljavaiostreamcorruptedexception invalid type code ac at javaioobjectinputstreamreadobject0objectinputstreamjava1356 at javaioobjectinputstreamreadobjectobjectinputstreamjava351 i cannot figure out why this is happening in few forum posts i came across that this happens when you append to a file during writing it is it the real reason i am appending to the file during writing phaseif so is there a proper way to read an appended file here is the code i use to write to the file objectoutputstream objectout new objectoutputstreamnew fileoutputstreamsrceasychequedatatemplatesdat true objectoutwriteobjectcheque objectoutflush objectoutclosewriting is not an iterative processthank you,['java'] +71762,removing or replacing a stylesheet a with javascriptjquery how can i do thisi triedlinktitlemystyleremoveand although the element is removed the styles are still applied to the current page in both opera and firefoxis there any other way,"['javascript', 'jquery', 'css']" +71774,uitoolbar with rounded corners i want to thisplay a uitoolbar with rounded corners on top what would be the easiest way the toolbar is not topaligned on the window it has a margin all around thanks,['iphone'] +71802,how to insert tag every 5 characters in a ruby string i would like to insert a wbr tag every 5 characters input s helloworldhello guysexpected outcome hellowbrworldwbrhellwbro guys,['ruby'] +71810,where can i get the full api doc of rails 3 it seems is not for rails 3 where can i get the api doc of rails 3,['ruby-on-rails'] +71838,linq to entity get a date from datetime var islemlist from isl in entitiesislemler where islkayittarihidate dbas islkayittarihivaluedate dbit select islit gives error date is not supported in linq to entities how can i get date in linq,"['c#', '.net']" +71859,dynamically evaluating string conditions in c i have a collection of strings i need to find out from this collection strings which satisfies some condition eg that string contains a and b or c these criteria are specified by the user so they are dynamic in linq it should be something likeliststring items new liststring sdsdsd sdsd abcvar query from item in items where itemcontainsa itemcontainsb itemcontainsc select itemi want to make the where condition dynamic so that it can work for any input by the user is it possible to do this in c without using any external library maybe using linq or something else which is builtin into net frameworkthanksgary,"['c#', '.net']" +71861,hide toast i am developing an application that uses system activity to add a contact to phones memory this external activity launches a toast after saving the contact is there any possibility to get rid of it it would be perfect if i could get a reference to it to call cancel or cancel all queued toasts is there any toast manager,['android'] +71862,swt table auto resize all columns qt solution is a single call to resizecolumnstocontent in net one can use textrenderermeasuretext jtable could use auto resize all columnsin swt is there a way to programmaticaly resize columns after populating them calling computesizeswtdefault swtdefault returns the same value thus thisregarding character left overs in columnstablecolumn has setwidth but how do i obtain the size hint for the current content taking into account font face etc,['java'] +71867,why is computehash not acting deterministically i have run into an interesting issue it seems that computehash for a hmacsha256 hash is not behaving deterministically if i create two instances of hashalgorithm using hashalgorithmcreatehmacsha256 and run computehash i get two different results below is an example static class that exhibiting this behaviorinternal static string hashpasswordbyte ball using hashalgorithm s hashalgorithmcreatehmacsha256 return converttobase64stringscomputehashball i have also tried to make the call non static actually it started non static and i have double and triple and quadrudruple checked my input array its absolutely the same on each call i have even done stuff in the immidiate window like converttobase64stringhashalgorithmcreatehmacsha256computehashballand running that twice in the immidiates window via a breakpoint in the method returns two different hashes i know hash is suppose to be deterministic so what gives is something going on with running in a debugger or any other ideas really this is just two weird for words right now p thanksjosh,"['c#', '.net']" +71878,sql server change a nullable column to not null with default value i came across an old table today with a datetime column called created which allows nulls now i would want to change this so that it is not null and also include a constraint to add in a default value getdateso far i have got the following script which works fine provided that i have cleaned up all the nulls beforehandalter table dbomytable alter column created datetime not null is there any way to also specify the default value as well on the alter statement,['sql'] +71879,chrome reordering object keys if numerics is that normalexpected i noticed that certain code that evaluates some shoe sizes json for an ecommerce site and outputs them on screen is messing up the order in chromethe josn string given can be791499139104551720875914091501045617209826849141104571721085914210410458172119268591431045917212951044391441046017213which increments sizes in halves through mootools or any framework i do not think that is relevant the json is converted into an object which i can then loop throughthe trouble is that in any browser bar chrome the natural order of the object keys is being preserved hence i can output them 1 by 1 and get size 7 75 8 85 etcbut in chrome round integers always come on top of the obejct so output is 7 8 9 75 85 95 insteadhere is the test caseit is not about floats either as demonstrated by the replacement of the with it is treating them as stringsif you prefix the json keys with a letter so they become strings the order remains unaffected and as intendedi think i recall reading that there are no guarantees on the order of properties of an object but at the same time this is annoying to the extreme and would cause a considerable amount of effort in fixing it for chrome users alone any ideas is this likely a bug that will get fixed ps in the example if you are not familiar with mootools i use hash which is just a way of extending object so methods can be applied to them such as each but a simple for key in object does the sameedit additionally i have now thiscovered this as an issue on the v8 bug trackeralso mentioned here elements order in a for a in a looplooks like google do not want to fix this and will remain the only browser that will do itupdate whatever hash table optimisation chromewebkit had has now made its way into gecko ff 2701 results in 789758595 applying before the keys returns the correct expected order,['javascript'] +71883,video streaming using rtsp android i am trying to install a wowza server on my linux machine to enable the rtsp streaming for my android application on android client side what sort of changes do i need to make in my application i am using videoview to simply play a video file stored locally now i want to get the video content get streamed through the server that i have installed if necessary i can move to any other streaming server as right now i am doing a research on streaming servers,['android'] +71887,executing stored proc from dotnet takes very long but in ssms it is immediate i have a stored proc on sql server 20 that takes 3 parameters when i call the stored proc from dotnet using sqlcommandexecutereader it takes about 28 secondswhen i run the same query inside ssms directly it returns immediatelywhen i take the query out of the stored proc and run it directly using dotnet it also returns immediatelythese are the results from a sql profiler sessionsp inside dot netduration 28030reads 2663365writes 0sp inside ssmsduration 450reads 23535writes 65query directly inside dot netduration 360reads 24865writes 57the following things stand out to methe stats for the ssms and direct query in dot net are very similarthe dot net sp one does a huge amount of reads but no writesthe other two make very few reads but a couple of writesany help would be appreciatedhere is a slightly obviscated version of the spi doubt that it is a query plan issue because even if i run it repeatedly from dotnet i always get the same resultshere is a version of the sp that is been altered slightly because of ip issues i hope it still makes senseselect t1pkiorderidt1fkibasketidt1soriginbasketcodet1dtdatecreatedt1sordercodet1fkiusercdet1fkiorgcdet1sapprovalpersont1dtdateapprovedt1srequestnot1dtrequireddatet1requestort1onbehalfoft1orderdesct1ordertypeidt1fkiagentidt1fkiagentregionidstatistatuscountoipkiorderitemid as orderitemscountwffkiorderid as workflowcountt1currency idt1exchangeratet1ref odr idnt2sordercode as ref odr cdet1ref rfq nbrt1ref rfs nbrt1ref doc nbrt1ref rsnt1ref forip cdet1ref fa nbrt1odr sub typfrom tbl1 t1 inner join tbl1status stat ont1pkiorderid statfkiorderid andstatdtdatestatuschanged select maxstat2dtdatestatuschanged from tbl1status stat2where stat2fkiorderid t1pkiorderid left outer join tbl1item oi ont1pkiorderid oifkiorderid left outer jointbl1workflows wf ont1pkiorderid wffkiorderid left outer join tbl1 t2 on t1ref odr idn t2pkiorderidwhere t1fkiusercde xor t1fkiusercde in select fkiusercde from tbl1 where fkiorgcde in select sys org cde from tbl3 t3 where t3sys lnk org cde 123and t1fkiorgcde 123and 123 not in select sys org cde from tbl3 t3 or t1ordertypeid 1 or statistatus in 234567or t1fkiorgcde in select sys org cde from tbl3 t3 where t3sys lnk org cde 123and t1ordertypeid 1 and statistatus not in 234567 and t1ordertypeid 2 group by t1pkiorderid t1fkibasketid t1soriginbasketcode t1dtdatecreated t1sordercode t1fkiusercde t1fkiorgcde t1sapprovalperson t1dtdateapproved t1srequestno t1dtrequireddate t1requestor t1onbehalfof t1orderdesc t1ordertypeid t1fkiagentid t1fkiagentregionid statistatus t1currency id t1exchangerate t1ref odr idn t2sordercode t1ref rfq nbr t1ref rfs nbr t1ref doc nbr t1ref rsn t1ref forip cde t1ref fa nbr t1odr sub typ order by t1dtdatecreated descsorry about the formatting i struggled to get it readable at all on the forum,"['c#', '.net']" +71909,how does a recursive cte run line by line i think i have got the format of recursive ctes down well enough to write one but still find myself frustrated to no end that i cannot manually process one pretend to be the sql engine myself and reach the result set with pen and paper i have found this which is close to what i am looking for but not detailed enough i have no problem tracing through a c recursive function and understanding how it runs but for sql i do not understand why or how the engine knows to stop does the anchor and recursive block get called everytime or is the anchor skipped in later iterations i doubt it but i am trying to expression my confusion about the way it seems to jump around if the anchor is called each time how does the anchor not appear multiple times in the final result i hope someone can just do a break down line 1 line 2 etc what happens and what is in memory as the result set accumulatesi have taken the liberty of stealing my example from this page since it seems to be the easiest to understanddeclare tbl table id int name varchar20 parentid int insert into tbl id name parentid values 1 europe null 2 asia null 3 germany 1 4 uk 1 5 china 2 6 india 2 7 scotland 4 8 edinburgh 7 9 leith 8 with abcd as anchor select id name parentid castname as varchar10 as path from tbl where parentid is null union all recursive member select tid tname tparentid castapath tname as varchar10 as path from tbl as t join abcd as a on tparentid aid select from abcd,['sql'] +71917,how do i trigger the drop event with jquery ui droppable without actually dragging and dropping i have a droppable with a drop event handlerthisdroppable dropfunction consolelogomg you dropped it i have a draggablethisdraggablewhat i want to do is trigger the drop event handler on the droppable without actually dragging and dropping the draggable i want to simulate the actual behavior without physically performing the behaviori thought something like this would dodroppabletriggerdrop draggableunfortunately it is not quite that simple does anyone know how i can accomplish this,"['javascript', 'jquery']" +71927,one time initialization for nunit where should i place code that should only run once and not once per class an example for this would be a statement that initializes the db connection string and i only need to run that once and i do not want to place a new method within each testfixture class just to do that,"['c#', '.net']" +71939,xsd for xml documentation generated for c does anyone know if there is an xsd file somewhere that can be used to validate the xml documentation that gets generated when you compile a c project with the doc optioni want to modify that file manually after it is been generated and i am looking for an easy way to confirm that i have not damaged the structure of the filethanks,['c#'] +71941,what is the maximum length of a string in php so how big can a variable in php get i have tried to test this but i am not sure that i have enough system memory 2gb i figure there has to be some kind of limit what happens when a string gets too large is it concatenated or does php throw an exception,['php'] +71944,php compiler for windows i have a command line php app that i need to thistribute to a client i just want to give them an executable not instructions for installing php what is a good php compiler for windows that includes support for php 5 curl tls and a few other libs i usei need to control memory and time limit usage so i must be able to use a custom phpini this should be packaged in the exe as well not a separate fileadditionally i do not want the code to be easily extracted this is not a huge requirement but i would rather not have the source viewable in a hex editori have got a few hits on google but if anyone has actually used one your feedback would be invaluableeditif i knew i was going to thistribute this to the client when i started i would have used c but i did not now they want to buy it it needs to be dead simple one executable containing the php interpreter and my script plus an entry point to start my script when the exe is run it would also be great if i did not have to rethistribute dlls eitheredit2i am look for somthing along the lines of phc or roadsend phc does not support windows and roadsend does not support php5 in windows,['php'] +71954,expandable list indicator i have an expandable list so two question i have seen somme similar questionbut never found the answer how do ihide the arrow group indicatorwhen there is no childreni tried to do it in the adapterpublic view getgroupviewint groupposition boolean isexpanded view convertviewviewgroup parent ifgetchildrencountgroupposition0 how do i hide the group indicator but i am stuck so how can modify thegroup indicator for empty groups how to have different behavior whenyou click on the arrow expands thegroup vs you click on the title ofthe group go to an activity,['android'] +71955,how do i maximize the browser window in selenium webdriver selenium 2 using c is there any way to maximize the browser window using webdriver selenium 2 with c,['c#'] +71977,how do i troubleshoot autotest infinite loop problems i am using cucumber rails3 rspec2 and autotest i am trying to figure out why my features are infinitely looping i suspect it some file being changed during the tests but i am not sure which one i have added some exceptions to my autotest with no diceare there any steps i can take to troubleshoot this problemit would be cool if i could see what files are triggering a rerun or at run time what files are being watchednot watchedheres my autotest contentsrequire autotestgrowlautotestgrowlclear terminal false skip some pathsautotestadd hook initialize do autotest wgit ds store db log tmp reruntxteach e autotestadd exceptione end,['ruby-on-rails'] +71989,const string vs static readonly string in c in c whats the difference betweenstatic readonly string mystrandconst string mystr,['c#'] +72002,is it possible to make part of the browser transparent to thisplay underlying desktopwindows in a web app i am developing a web application meant to run work as a rich client and able to afford requiring any even nightly build version of firefox of chromiumthe application interface background is meant to be transparent showing underlying windows or desktop how can i achieve this following standards does not matter but would be niceprimary target platform is linuxupdate addressing comments and answers received to the moment of 20100707t0144ztechnically it is nothing about code interaction and breaking the sandbox it is about window composition i even think it can be implemented pretty easy in a compositive window manager without a browser even knowing of this just replace some useless colour for example fuchsia was widely used for this during windows 9x age with the underlying layer contentpolitically this can and should be a restrictable function like local file and webcam access for example which can be allowed for trusted intranet applications local webtechbased rich client applications seem to be a trend beginning firefox and chromium implement more and more features to facilitate this and forbidden for unknown 3rd party websites but this would require more complex interaction between a browser and a window managerthe reason why would i like it is that i want to build a crossplatform linux windows mac zeroinstall fancylooking rich client application not meant to be served as an internet website with web technologies like html5 css3 and javascript i even will probably seek to use some browserwindowless tech to run it i have heard about mozilla prism and xulrunner kde and windows offer to use html for desktop widgets chromium is meant to offer something alike etc,"['html', 'css']" +72016,how can you play music from the ipod app while still receiving remote control events in your app ok i am trying to let a user choose songs from their ipod library to listen to but i still want to receive remote control notifications headphones lock screen osd etc in my app so i can do some extra things so far i can get either ipod music playing or headphone events but not both simultaneouslyheres what i know so farif you use the mpmusicplayer you can easily have programmatic access to the entire music library however it not your app receives the remote notifications regardless if you use applicationmusicplayer or ipodmusicplayerif you use avaudioplayer apples recommended player for most sounds in your app you can easily get remote notifications but it does not natively have access to the ipod libraryavaudioplayer can be initialized with an asset url and tracks in the ipod library type mpmediaitem do have a url property that returns a nsurl instance which the documentation says its explicitly for use with avasset objects but when you try initializing the avaudioplayer with that nsurl it fails i used the now playing track in ipod which was a mp3 and it did return a valid nsurl object but initialization failed even worse when it was an audiblecom file the nsurl property flatout returned nilif you try using an instance of the avaudioplayer to get remote events say with a blank sound file then simultaneously use the mpmusicplayer class to play ipod music you have remote control access until you actually start ipod playback at which time you lose it since your audio session gets deactivated and the system audio session becomes activeif you try the same as 4 but you instead set the audio sessions category to a mixable variant your session does not get deactivated but you still lose remote control capability once the ipod starts playingin short whenever mpmusicplayer is playing i cannot seem to get remote events and i do not know of any other way to play content from the ipods library other than by using mpmusicplayerany suggestions on how to get around this would be welcome creative or flatout crazy do not care so long as it worksanyone anyone bueller buellerm,['iphone'] +72022,how long should my password salt be and is sha256 good enough i am in the process of creating a gaming community site that i am aiming to release to the public soon currently i am working on passwords and logins i have only used md5 before but i have read about password safety and heard that salting is currently the way to goheres my plan every user has their own unique salt of 12 random characters a etc stored in the users table the salt is hashed using sha256 along with the password on registration and rehashed on loginhow does this sound to you anything i can improve should i go for sha512 and a longer salt or is this enough,['php'] +72025,linq intersect multiple lists some empty i am trying to find an intersect with linqsamplelistint int1 new listint 12 listint int2 new listintlistint int3 new listint 1 listint int4 new listint 1 2 listint int5 new listint 1 want to return 1 as it exists in all lists if i runvar intresult int1 intersectint2 intersectint3 intersectint4 intersectint5tolistit returns nothing as 1 obviously is not in the int2 list how do i get this to work regardless if one list is empty or not use the above example orlistint int1 new listint 12 listint int2 new listintlistint int3 new listintlistint int4 new listintlistint int5 new listinthow do i return 1 2 in this case i do not know ahead of time if the lists are populated,['c#'] +72028,delayed job not processed in rspec i am trying to run rspecs for a custom delayed job getpagegetpagejob but i have a problemwhen i run them the jobs are well enqueued that is to say well inserted in the delayed jobs table but they are not processed by the job workerindeed after launching rake jobswork rails envtest in a first terminal and after running the specs in a second terminal i do not see any output from the job worker in the first terminalon the other hand the jobs are well processed if i enqueue them via scriptconsole testso i am a bit confusedwith both the specs and the scriptconsole the line i use to enqueue my jobs is delayedjobenqueue getpagegetpagejobnewany idea,['ruby-on-rails'] +72062,catch specific http error in python i want to catch a specific http error and not any one of the entire familywhat i was trying to do is import urllib2try urllib2urlopensome urlexcept urllib2httperror whateverbut what i end up is catching any kind of http error but i want to catch only if the specified webpage does not exist probably that is http error 404but i do not know how to specify that catch only error 404 and let the system run the default handler for other eventsny suggestions,['python'] +72064,converting pdf to tiff or text in c i need a library to convert pdf to text or tiff in c preferably open source under a permissive licence currently using xpdf but as i understand the gpl i cannot compile it into a dll and link to it without releasing the rest of my code under the gpldoes such a library exist if not what is the best value tool which would suit my needs thanks,['c#'] +72079,lightweight sql editor for eclipse is there any simple sql editor plugin for eclipseby simple i mean the editor does not connect to any db does syntax highlighting and preferably formatting sql is a bonus,['sql'] +72080,css make textbox fill all available width i have the following line in my web pagediv stylewidth100some text dropdown some more text textbox button buttondivthe dropdown control i do not really have control over the width as it sizes to fit whatever the longest option value is the buttons are fixed width how can i get the textbox to fill all available remaining widthi tried putting it in a table but run into the same problem ie how do i make all other columns as small as possible to fit their content and then the textbox column fill remaining widthhacky solutions are fine if necessary i have long ago given up any pretence of even caring about css standards when it is so difficult to do the simplest thingedit to clarify by textbox i mean input typetext,['css'] +72082,using jquery datatable for server side processing with paging filtering and search i need to use the jquery datatable serverside processing for my aspnet mvc c applicationmy application has thousands of records to show in the table as list i am using jquery datatable to enable paging filtering and search is there any good referencearticles for jquery datatable serverside processing to use with aspnet mvc c,['jquery'] +72092,why cant there be classes inside methods in ruby can i create ruby classes within functions bodies i seem to be getting error which tells me its not allowed but i think it should be as classes are too objects hereclass a def method class b end endendthis fails with error class definition inside method bodyif we cant why cant we create classes inside methods,['ruby'] +72110,thread timeout in c i am new to threading in cis there anyway of setting a timeout for a thread without blocking the calling thread in c 35if not is it logical to execute a function using a thread and within that function create a thread and join it to overcome this main thread blocking issue to illustrateinstead ofpublic void main thread thrd1 new threadnew threadstarttargetobjtargetfunc thrd1start thrd1join using something likepublic void main thread thrd1 new threadnew threadstartmiddleobjwaiter thrd1start and in the middleobjwaiterpublic void waiter thread thrd2 new threadnew threadstarttargetobjtargetfunc thrd2start thrd2join,['c#'] +72116,iphone icon size i am developing an application for iphone to support multiple devices iphone 24 i had an issue with the app icon as it was shown pixelated in the iphone 4 simulator so i have used a new image with higher resolution 300 x 300 to be precise on the simulator its showing fine for both iphone 4 and the iphone device simulators however when i ported my app to an iphone 3 actual device the icon did not show at all and instead i get a blank white icon i do not have an iphone 4 yet so i cant tell if the same issue will happen on the physical devicei am not sure what is the best dimensionsdpi to use for an icon to thisplay perfectly on an iphone 4 and older devices would appreciate a help if possible,['iphone'] +72130,how to use numpy array with ctypes i am still writing on a python interface for my c code with ctypes today i substituted my file reading function with a python version which was programmed by somebody else usind numpy the old c version was called with a byrefp data while p datapfloat see below the main function takes the p dataold file readingp datapointerc floatfooreadfilenamebyrefp dataresultfoopymainp datathe python file reading function on the other hand returns a numpy array my question now is how do i convert a numpy array to pointerc floati googled but only found the other way around c arrays through ctypes accessed as numpy arrays and things i did not understand ctypes foreign function interface numpyctypeslibupdatecorrected a mistake in the example code,['python'] +72144,how to enable ipod controls in the background to control nonipod music in ios 4 a good example of what i am trying to accomplish is implemented in the latest version of the spotify iphone application for pandora seems to have the same feature when spotify is in the background double tapping opens the multitask dock where the ipod controls playpause forward etc allow to control the music playback of spotify not the ipod application also when the iphoneipod touch is locked double tapping thisplays similar playback controlsif you do not know what i mean heres an article that has screenshots in my current application music is streamed from a server using matt gallaghers audiostreamer i have managed to keep the music playing in the background now i would like to link my playback to the multitask docklock screen should i be using mpmusicplayercontroller ipodmusicplayer how should i proceed bonus question if you can tell me how to change the ipod icon to my application icon in the multitask dock spotify pulled that trick as well that whould be awesomeany help appreciated thanks,['iphone'] +72155,python sorted list search are there any python builtins or widely used python libraries to perform a search in a sorted sequence,['python'] +72172,position a css background image x pixels from the right i think the answer is no but can you position a background image with css so that it is a fixed amount of pixels away from the rightif i set backgroundposition values of x and y it seems those only give fixed pixel adjustments from the left and top respectively,['css'] +72175,sitemesh still active v2 vs v3 i am evaluating sitemesh for use in our web applications i have found two websites for sitemeshversion 24 jan 2009 version 30 sep 2009 looks like the same author is involved in both joe walnesso my question is is sitemesh still in active development are the two versions i found both stable is one deprecated are there any other alternatives to sitemesh we are looking for a tool that can act as a reverse proxy to a number of different web applications to apply a consistent look and feel controlled separately from the apps sitemesh appears to be able to do that i think,['java'] +72215,java executors how can i set task priority is there a possibility to set priority to tasks which are executed by executors i have found some statements in jcip about it is possible but i cannot find any example and i cannot find anything related in docsfrom jcipan execution policy specifies the what where when and how of task execution includingin what order should tasks be executed fifo lifo priority orderupd i realized that i asked not exactly what i wanted to ask what i really wanted ishow to useemulate setting threads priority ie what was threadsetpriority with executors framework,['java'] +72217,new types may not define a return type c i am confused i think on c class structurei have a h called fxmathfunctionsh and a cpp called fxmathfunctionscppthe h starts likeclass fxmathfunctions public fxmathfunctions fxmathfunctionsand in the cppi have include fxbasictypeshinclude fxmathfunctionshfxmathfunctionsfxmathfunctions fxmathfunctionsfxmathfunctions i am getting errors likeerror new types may not be defined in a return typeerror return type specification for constructor invalidthis must be something to do with definition someplace but i just dont see where this might occur,['c++'] +72239,cross domain get request in jsjquery is there a way without using a server proxy to perform a cross domain get or post request,"['javascript', 'jquery']" +72249,android sharedpreferences limitations i developed a game on android i am currently saving most of the game stats in a database however the app does not utilize more than a single row in the db i am now interested in introducing some new stats but this will cause my db to reinstall and thus clear out everyones progress in order to avoid this in the future i am considering storing the game stats with sharedpreferences instead my question is how many different things can be stored that way before it becomes a problem in total i would be storing around 40 values all integers,['android'] +72251,jquery ui modal dialog stripe issue i have this extremely basic jquery ui modal dialog that i wrote for testing here unless i am missing something i cannot figure out why their is that grey strip across the middle of the page i am trying to manipulate the modal background color and opacity as well as seen in the css markup,"['jquery', 'css']" +72298,keep div at the bottom of another div css div idouterdiv idcopyright span idyra 1965 2010span span idfspan span iddspan divdivi want the copyright to be at the bottom of outerhere is the css for copyrightcopyright positionrelative marginbottom0px width672px height20px colorfyr marginautof positionabsolute right0px textaligncenterthanksjean,['css'] +72306,exit code from windows forms app how do i return a nonzero exit code from a windows forms applicationapplicationexit is the preferred way to exit the application but there is no exit code argumenti know about environmentexit but that is not a nice way to close the application loop,"['c#', '.net']" +72309,are selfclosing input tags valid in html 4 according to an input element should end with a single and not a though that most browsers can handle an input element that ends with is such an input element valid according to html syntax rules in other words are elements like input and br valid in html 4this question is about html and not xhtml,['html'] +72325,why would my machine need a full iis reset to see code changes to an aspnet project i have noticed that a vs2010 c website project i am working on seems to always need an iisreset to be able to see changes i make to the code behind files in the project i notice that it does not have the right version of the assembly because when i try to debug visual studio would not let me put break points in the code files i have changedi would have thought that doing a application pool restart would be enough but our post build steps do that and it does not seem to be enough might there be something not configured incorrectly on my machine or in the project to make this happen,"['c#', 'asp.net']" +72330,android matrix what does getvalues return i am having trouble working out the returned values of the below code pmeasure pathmeasure m matrix thistcount is the thistance along the pathpmeasuregetmatrixthistcount m 0x01 0x02 mgetvaluesfloat valuesfloat2 float5 are position x y respectively but i cannot figure out the restany help once again appreciated,['android'] +72332,c memory leak testing with crtdumpmemoryleaks does not output line numbers i am working on a game with sdl in visual studio 2010 i came across the crtdumpmemoryleaks macro and thought i would give it a go invoking crtdumpmemoryleaks does print memory leaks to the output window but it does not show where it happensi have read the msdn article at memory leak detection enabling and it explains that if i define crtdbg map alloc it should output the line number of the offending statement this does not happen in my case i was however able to get it to work if i use malloc directly not by using newthe codedefine crtdbg map allocinclude crtdbghinclude stdlibhint mainint argc char argv int var new int5 crtdumpmemoryleaks return 0the output is the followingdetected memory leaksdumping objects 58 normal block at 0x007d1510 4 bytes long data 05 00 00 00 object dump completeif crtdumpmemoryleaks is unable to output line numbers when allocating using new then suggestions for other ways to achieve similar behavior is appreciated,['c++'] +72354,convert php site to exe desktop app i have developed a phpmysql web application which is a school based projectmy client wants this application to be converted into a exe file such that it can be installed on his desktop and use ithow the php website can be converted to a exe file and can it be run without the need of a databaseserver software please advice,['php'] +72364,accessing the content of other tabs in browser i am using mozilla firefox and i am trying to figure out a way to access the content of other tabs in the same window using javascript and dom i am open to other techniques if exist eg i want to run a javascript in tab1 which can find the title of some other tab basically i need this so that i can identify a tab which has opened due an href in my current page without using windowopen method all i want is a simple hyper link which opens a page belonging to the same domain as the current page the page should be opened in a new tab now i want to be able to access this new tab from the current tab,['javascript'] +72371,parsing pdf files especially with tables with pdfbox i need to parse a pdf file which contains tabular data i am using pdfbox to extract the file text to parse the result string later the problem is that the text extraction does not work as i expected for tabular data for example i have a file which contains a table like this 7 columns the first two always have data only one complexity column has data only one financing column has data aih value complexity financing medium high not applicable macother fae xyz 1243 1234 1234 abc 156 156 156then i use pdfboxpddocument document pddocumentloadpathtofilepdftextstripper s new pdftextstripperstring content sgettextdocumentthose two lines of data would be extracted like thisxyz 1243 12431243abc 156 156156there are no white spaces between the last two numbers but this is not the biggest problem the problem is that i do not know what the last two numbers mean medium high not applicable macother fae i do not have the relation between the numbers and their columnsit is not required for me to use the pdfbox library so a solution that uses another library is fine what i want is to be able to parse the file and know what each parsed number means,['java'] +72378,most efficient way to play a sound when button is clicked right now i have two buttons each one needs to produce a different sound in the future there will probably be about 8 buttons but for now just two public class myactivity extends activity public void oncreatebundle savedinstancestate superoncreatesavedinstancestate final button btndrum1 button findviewbyidridbtndrum1 btndrum1setonclicklistenernew onclicklistener public void onclickview v mediaplayer mp mediaplayercreatethis rrawdrum1 mpstart mprelease final button btncym1 button findviewbyidridbtncym1 btncym1setonclicklistenernew onclicklistener public void onclickview v mediaplayer mp mediaplayercreatethis rrawcym1 mpstart mprelease originally i did not have mprelease and it would play the sound properly but eventually the app would crash due to running out of memory now with the mprelease it does not crash but sometimes it does not play the sound when clickedis this the most efficeient way to play a sound when button is clicked is it extensible,['android'] +72381,ef4 update entity without first getting entity how can i update an entity without having to make a call to select it if i supply the key for the entity should it not know to update after savechanges is called on the objectcontexti currently do thisvar user contextuserssingleu uid 2userusername usernameusername abc 123contextsavechangesthat works but forces a select because i know the id why cannot i do something like thisvar user new useruserid 2userusername usernameusername abc 123contextupdateobjectusercontextsavechangesthanks in advanceedit also it is important that only the affected properties that are changed be updated is this possible,['c#'] +72398,how do i get the int ascii value of a character in cocoa how do i get the ascii value as an int of a character in cocoa i found an answer for doing this in python but i need to know how to do this in cocoa i am still a noob in cocoapython methoduse function ord like this orda 97and also chr for the other way around chr97 ahow do i do this in cocoa,"['objective-c', 'c']" +72399,how do i use a datapager with server side paging i am trying to use a datapager to do server side paging here is my codeaspdatapager idpgrfoobars pagedcontrolidlvfoobars querystringfieldpage runatserver fields aspnumericpagerfield fieldsaspdatapagercode behindprotected void page loadobject sender eventargs e configureblogpostlistviewprivate void configureblogpostlistview int pagenum inttryparserequestparamspage out pagenum int pagesize 20 pagedlistifoobar foobars fooservicegetpagedfoobars new pagingsettingspagenum pagesize listviewpageddatasource ds new listviewpageddatasource dsallowserverpaging true dsdatasource foobars dsmaximumrows pagesize dsstartrowindex pagenum totalcount is the total number of records in the entire set not just those loaded dstotalrowcount foobarstotalcount lvfoobarsdatasource ds lvfoobarsdatabind pgrfoobarspagesize pagesize pgrfoobarssetpagepropertiespagenum foobarstotalcount truepagedlist comes from robconerys useful post the problem is that the datapager appears to be using the count property of the listview to determine the total number of records which in this case is 20 somehow it needs to know that there are 1500 not 20 total records the datapager has a property totalrowcount but this is readonlyi have never seen a datapager example with server side paging but assumed that it could do server side paging otherwise what good is the querystringfield attributei am aware that you can do a custom paging solution using methodology like the 4guysfromrolla did here but i would first like to know if a solution with the datapager is possible before creating a custom solutionupdatethe more i look at this the more that i am coming to the conclusion that this is not possible and that unfortunately the datapager is a control meant for small web sites only what i want to do should really be quite simple if the control were built correctly i want to be able to saydpfoobarstotalrowcountcomputed falsedpfoobarstotalrowcount anynumberthatisochoosei have been looking for some hack to accomplish the same thing but it appears that the datapagers totalrowcount is computed from the actual number of items in the datasource that it is bound to it seems very odd to me that microsoft would create a listviewpageddatasource class and a datapager at the same time and not have them work correctly together but this appears to have been what has happenedupdate 2 aha momentit seems that it has been possible to do server side paging since net 20 by using an objectdatasource and customizing the selectcountmethod i believe it should be possible to customize objectdatasource to suit my needs hm i am going away for the weekend so it will be a couple of days for me to see if this works stay tuned true believers,['asp.net'] +72426,javascript parsefloat 50 returns 500 when i need 50 how would it be a nice way of handling thisi already thought on removing the comma and then parsing to float do you know a bettercleaner waythanks,['javascript'] +72430,how to show ajax requests in url what i want is to have links which change a part of the page and a dynamic url for it where i can specify variables such like calendar10 2010tabviewtab2check this for an exact example click here for exact demoso here is the link format what i needcalendar10 2010tabviewtab2i need to have variables in the links like calendar and tabview so i can change multiple things on a single page without realoadingor another format such like on this is exactly what i want however the first format is good too but this is much more beautifulrequirementsneeds to be accessed from anywherefrom example a mail or if i justwrite in the url barthe link should be in the history so if if i push the back or forward button the page needs to be accessedpage refresh needs to work toosome recourcesexampleswdeveloperyahoocomwfacebookcom the sidebar links on your profile pagewbhomescomau 100 close to what i wantwflickrcomwyoutubecomsome tutorialswajaxpatternsorgwcontentwithstylecoukplease help me i have never found any solution to do this but i do not want to use jquery or any api or any library i want to have a working javascriptajax and php script,['php'] +72431,jquery remove plugin from element i have got something similar to the following codeaclickfunction elementpluginis there a way to remove a plugin from an element other than using pluginremove not sure if i have the terminology correct but basically i want to reset the element to it is original statethanks,['jquery'] +72437,push item to associative array in php i have been trying to push an item to an associative array like thisnew inputname array type text label first name show true required truearray pushoptionsinputs new inputhowever instead of name as the key in adds a number is there another way to do it,['php'] +72459,change the stored procedure definer i have a around one hundred stored routines in my mysql database with with most of them have root as the defineri have another mysql account named abc how to change the definer of all routines to abcis it possible to do the same if i have access to mysql server only as abc user and not as root,['mysql'] +72460,historygo1 going back doesnt work in chrome href onclickcloseorcancel and historygo1 in that js method doesnt work in chrome neither historybackit works with hrefjavascriptcloseorcancel but opera does not allow hrefjavascripthow to make history go back using onclick myfunction edit closeorcancel returns false,['javascript'] +72470,how to link third party libraries in ants javadoc task i have a project that uses a third party library in the form of a jar file and i am using ant to build the project javadocs i cannot get ant to link to the thirdparty library javadocs when using the javadoc task here is the javadoc taskjavadoc excludepackagenames accessprivate destdirjavadoc authortrue versiontrue usetrue windowtitletitle useexternalfiletrue fileset dir defaultexcludesyes include namesrccomjava fileset link href link hrefjavadocthe output from the task says that the simian package does not existjavadoc cdevelopmentjavatoolssrccomcnameduplicatecodeidentifierjava15 package aucomredhillconsultingsimian does not existjavadoc import aucomredhillconsultingsimiancheckerjavadoc running the ant task creates all the links to the sun website correctly but not to the redhillconsulting site both urls lead to a packagelist file and appropriate paths matching the packagelist contentshow do i configure the javadoc ant task to generate the links to the thirdparty sitenote the simian jar file is in toolslib i have not seen it specified that any sort of classpath is an option so i have not explored that avenue but i have tried adding the jar file to the fileset include path and that was not any good,['java'] +72480,implementation of lazy for net 35 net 40 has a nice utility class called systemlazy that does lazy object initialization i would like to use this class for a 35 project one time i saw an implementation somewhere in a stackoverflow answer but i cannot find it anymore does someone have an alternative implementation of lazy it does not need all the thread safety features of the framework 40 versionupdatedanswers contain a non thread safe and a thread safe version,['c#'] +72485,creating square subplots of equal height and width in matplotlib when i run this codefrom pylab import figureax1 subplot121plot1 2 3 1 2 3subplot122 sharexax1 shareyax1plot1 2 3 1 2 3drawshowi get two subplots which are squished in the xdimension how do i get these subplots such that the height of the yaxis equals the width of the xaxis for both subplotsi am using matplotlib v09912 on ubuntu 1004update 20100708 let us look at some things that do not workafter googling around all day i thought that it might be related to autoscaling so i tried fiddling with thatfrom pylab import figureax1 subplot121 autoscale onfalseplot1 2 3 1 2 3subplot122 sharexax1 shareyax1plot1 2 3 1 2 3drawshowmatplotlib insists on autoscalingfrom pylab import figureax1 subplot121 autoscale onfalseplot1 2 3 1 2 3subplot122 sharexax1 shareyax1 autoscale onfalseplot1 2 3 1 2 3drawshowin this one the data completely thisappears wtf matplotlib just wtfokay well maybe if we fix the aspect ratiofrom pylab import figureax1 subplot121 autoscale onfalseplot1 2 3 1 2 3axesset aspectequalsubplot122 sharexax1 shareyax1plot1 2 3 1 2 3drawshowthis one causes the first subplot to thisappear entirely that is hilarious who came up with that onein all seriousness now should this really be such a hard thing to accomplish,['python'] +72488,does guarding a variable with a pthread mutex guarantee it is also not cached consider a simple global in my case variableint isomewhere this variable is accessedpthread mutex locki mutexifi other value do somethingpthread mutex unlocki mutexanother thread updates i while it holds i mutex could the compiler cache the value of i so i do not get the recent value must i be volatile,['c'] +72493,how to generate an hmac in java equivalent to a python example i am looking at implementing an app getting twitter authorization via oauth in java the first step is getting a request token here is a python example for app engine to test my code i am running python and checking output with java here is an example of python generating a hashbased message authentication code hmacusrbinpythonfrom hashlib import sha1from hmac import new as hmackey qnscadgrlkihaupy44oiexbktqbgy0orf7ov1i50message fooprint s hmackey message sha1digestencodebase641output foopy3h2gpjf4xcynjcgu5lbdmbwgochow does one replicate this example in javai have seen an example of hmac in javatry generate a key for the hmacmd5 keyedhashing algorithm see rfc 2104 in practice you would save this key keygenerator keygen keygeneratorgetinstancehmacmd5 secretkey key keygengeneratekey create a mac object using hmacmd5 and initialize with key mac mac macgetinstancekeygetalgorithm macinitkey string str this message will be digested encode the string into bytes using utf8 and digest it byte utf8 strgetbytesutf8 byte digest macdofinalutf8 if desired convert the digest into a string string digestb64 new sunmiscbase64encoderencodedigest catch invalidkeyexception e catch nosuchalgorithmexception e catch unsupportedencodingexception e it uses javaxcryptomac all good however the secretkey constructors take bytes and an algorithm whats the algorithm in the python example how can one create a java secret key without an algorithm,['java'] +72501,adding a user control using windows form designer this is probably an incredibly obvious question but i just cannot figure it outi have a windows form managed by the form designer i would like to include a custom user control also managed by the form designer but i am unable to get the custom control to show up in the toolbox even if i try manually adding it under the choose items dialogboth form and control are in the same assembly i have tried separating the control into a separate assembly in order to follow the instructions here to the letter to no avail i am also using ccli if that changes anythingis there an attribute or such i should be setting to my control in order for it to appear in the designer toolbox,['.net'] +72508,creating tasks for other users using exchange web services ews managed api as an ews managed api newbie i am having some problems finding examples and documentation about creating and managing tasksi have managed to create a task for myself without a problem however i really need to be able to do the following if anyone could give me any pointers i would really appreciate itcreate a task and assign it to another userbe able to interrogate the status of that task percent complete etc whilst it is assigned to that userupdate the notes on the task at any timethanks in advance for any pointers,['.net'] +72523,whats the best way to parse a string for bad words in c i am thinking of something likeforeach var word in paragraphsplit if badwordarraycontainsword do something about it but i am sure there is a better waythanks in advanceupdatei am not looking to remove obscenities automatically for my web app i want to be notified if a word i deem bad is used then i will review it myself to make sure it is legit an auto flagging system of sorts,['c#'] +72539,how to calculate free thisk space i am working on an installer project where i need to extract files to the thisk how can i calculatefind the thisk space available on hard thisk using c,"['c#', '.net']" +72563,isolated named pipes in terminal server sessions if my application starts i check first if there is already an instance of the app and if yes i give focus to the running instance and terminate the newly created process i make this with a named pipe that is registered through wcf that works fine so farnow my app will also be used in a terminal server environment is it right that named pipes are system wide so that i must change the startup logic to not give focus to instances of other users what certainly not will work but break my application or does terminal server 2003r2 isolate wcfbindings for each tssessioni cannot access the productive environment yet thatas why i post this question maybe someone can give me an answer to this questionupdatethrough another post i did concerning the app startup i learned that there is a more convenient way to manage the single application startup using a mutex which can be used system wide or on a terminal session basisthe question however is open anyhow and perhaps someone that has good wcf aknowledge can answer it it would be interesting,['.net'] +72578,lambda expression msvc vs g i have the following codeinclude algorithminclude iostreaminclude vectorinclude functionalint main typedef stdvectorint vector int sum0 vector v forint i1i10i vpush backi stdtr1functiondouble ldouble stdfor eachvbeginvendint nsum n error here in msvc return sum stdcoutl stdcingetthe above code produces an error on msvc 10 whereas it compiles fine with g 45the error produced is 1 intellisense invalid reference to an outerscope local variable in a lambda body cuserssuper userdocumentsvisual studio 2010projectslambdalambdacpp 19 46 lambdaso is there any other way to access the outerscope variable sum without explicitly creating a new variable inside the local lambda expressioninside stdfor eachon g 45 the code compiles finedoes the standardn30 draft say anything about iti do not have a copy of c0x1x standard at present,['c++'] +72581,aspnet custom control when is loadpostdata called i have developed a custom control that extends listbox the idea is that the control remembers modifications to its elements which occurred clientside eg as a result of an ajax requestthe way it works is that the control also renders a hidden input and the result of the ajax request is stored in the hidden input this is posted back and the controls loadpostdata method looks for the hidden input and if the hidden input has data creates the listitem collection from itthis works perfectly so long as the user has made a selection from the list box if they have not the loadpostdata method does not get called and consequently the new listitem collection is not created i have established this using the debuggeri assume that the loadpostdata method is only called if the post data collection includes data corresponding to the controls uniqueid ie name attribute in html if the user has not made a selection from the list box nothing is included in the post data for the list boxs uniqueid and loadpostdata is not called is that correctcan anyone suggest how i can ensure that my custom listboxs loadpostdata method is called every postback regardless of whether the user has made a selectionthanks in advance i am really stuck with this onedavid,['asp.net'] +72636,how to set zorder of a control using winforms i am writing a custom textbox that upon gaining focus changes its border styleas adding a border causes the control to overlap with those neighbouring it i temporarily bring the text box to the front of the dialog using textboxbringtofronthowever once editing is complete and focus is lost i would like to send the control back to its original position in the zorderis this possible preferably in a simple way,['c#'] +72650,how to manage user roles in a database i am creating a website in which i will be managing users and their permissions i am looking to implement user roles and cannot seem to wrap my head around how things should work i want to be able to assign a user a certain role and have each role contain one to several permissions that can be read easily by my script just want to know how i should go about setting up my database to do this easily and efficientlyin my head i picture 3 tables users roles and permissions i could give each user a role id that joins the roles table i just do not know how i can link roles to several permissions,"['php', 'mysql']" +72657,why does file extension affect write speed c streamwriter i am currently testing the performance of different methods for logging text data into a file it seems that when i openwriteclose a large amount of times the extension used affects the performance txt and log are 7 times fastercode usedprivate static void testwritespeedfileinfo file stopwatch watch new stopwatch watchstart for int i 0 i 50 i using streamwriter writer fileappendtext writerwritethis is a test consolewritelinefilename watchelapsedstatic void mainstring args testwritespeednew fileinfoabctxt testwritespeednew fileinfoabctxt01564611564 testwritespeednew fileinfoabc01564611564txt testwritespeednew fileinfoabcxml testwritespeednew fileinfoabcxml01564611564 testwritespeednew fileinfoabcconfig testwritespeednew fileinfoabcconfig01564611564 testwritespeednew fileinfoabcexe testwritespeednew fileinfoabcexe01564611564 testwritespeednew fileinfoabclog testwritespeednew fileinfoabclog01564611564 consolereadlineresultsabctxt 083826847 abctxt01564611564 0597401633abc01564611564txt 080069698 abcxml 0582031820abcxml01564611564 0593956204abcconfig 0584861308abcconfig01564611564 01012474287abcexe 010924401abcexe01564611564 01007371805abclog 0809934 abclog01564611564 0598029448why is this happening,['c#'] +72675,aspnet extending iprincipal i would like to extend iprincipal in aspnet to allow me to get the usertype that i will define i would like to make it possible to do this in a controllerstring type userusertype then in my extension method i will have a method likepublic string usertype do some database access return usertypehow can i do this is it possiblethanks,['c#'] +72687,why javascript says that a number is not a number i have a piece of javascript code which is expected to set an integer value to a variablesomething is broken so when i try to do alerta it returns nan isnana returns true but if i alerttypeofa it says numberso how can a variable be a number and not a number at the same time maybe i misunderstood what nan really isedit thanks to the answers i see that i was wrong becausethe type of nan is numbernan does mean not a number which is not the same thing as not of type number00 is a good example of nan it is still a number but javascript and nobody else can say what is the real value of zero divided by zero 10 on the other hand returns infinity which is not nan,['javascript'] +72695,removing nodes from xdocument this removes all elements from the document xdocument document xdocumentloadinputfile foreach xelement element in documentelements elementremove documentsaveoutputfilethis does not have any effect xdocument document xdocumentloadinputfile foreach xelement element in documentelements elementremove foreach xelement child in elementelements childremove documentsaveoutputfileam i missing something here since these are all references to elements within the xdocument should not the changes take effect is there some other way i should be removing nested children from an xdocumentthanks,['c#'] +72705,extract meta keywords from webpage i need to extract the meta keywords from a web page using python i was thinking that this could be done using urllib or urllib2 but i am not sure anyone have any ideasi am using python 26 on windows xp,['python'] +72712,how to use dockstylefill for standard controls in wpf i am very new to wpf i am used from windows forms that i create a panel place controls inside it and give them dockstylefill to max out their size to the surrounding panelin wpf i want to have the same i have a tabcontrol and i want its size to fill as much of the form as possiblei have a ribbon control ribboncontrolslibrary and want the rest of the form to be filled with the tab control at max sizei do not want to dock controls like docking in visual studio just old docking mechanisms,['c#'] +72722,jquery recreate slidedown effect using the animation function how can i do that d,['jquery'] +72725,how to represent an enum in an interface when you cannot ok so the basis of this post and to explain the title is simple i have an interface with a method that method on the user side will take in an enum as a param but you cannot define enums in an interface therefore i do not see how i can even define this method then if i am expecting a type enum as one of the incoming paramsso how do you handle this situation how can you still get that method in your interface you do not know what enum they will require to be sent in but you know for sure you want it to be an enum instead of magic stringsan enum is not a reference type so you cannot use object as the type for the incoming param so not sure what to do here,['c#'] +72729,is any mainstream compiler likely to support c0x unrestricted unions in the near future i keep looking but it seems like there is zero interest from compiler developers in supporting theseto me it seems odd basically current c has restrictions on unions that were always an irritation and never appropriate youd think that basically removing a few error checks would be a relatively simple way to tick an extra c0x support box but afaict no compiler developers have done so yetwhy i am interested is because it provides a simple solution to a recurring problem in data structure coding how to reserve memory for an instance of some unknown template parameter type preferably with as much type safety as possible in the circumstances but without invoking any constructor that happens to be defined on that type the really important point is that alignment rules must be followedan unrestricted union is perfect for this it gives you a type which has no constructors or destructors but which has the right size and alignment to allow any member there are of course ways to explicitly construct and destruct when needed and when you need typesafe access you just use the appropriate union member to access it support for proper unions can be useful too but you get huge benefits even for a singlemember union such asunion memory for item t item t m itemeven with the standardized alignment handling features in c0x this approach wins for convenience and safety when eg you want space for x items in a node not all of which will be in use or constructed at any time without c0x we are still in the dark ages wrt alignment issues every compiler does it its own nonstandard waythe only problem with unrestricted unions there is no support for them that i can find,['c++'] +72738,problem reloading a jar using urlclassloader i need to add plugin functionality to an existing application for certain parts of the application i want to be able to add a jar at runtime and the application should be able to load a class from the jar without restarting the app so far so good i found some samples online using urlclassloader and it works finei also wanted the ability to reload the same class when an updated version of the jar is available i again found some samples and the key to achieving this as i understand is that i need to use a new classloader instance for each new loadi wrote some sample code but hit a nullpointerexception first let me show you guys the codepackage testmiscimport javaiofileimport javaneturlimport javaneturlclassloaderimport pluginmiscipluginpublic class testjarloading public static void mainstring args iplugin plugin null whiletrue try file file new filecpluginstestjar string classtoload jartesttestplugin url jarurl new urljar file filegetabsolutepath urlclassloader cl new urlclassloadernew url jarurl testjarloadingclassgetclassloader class loadedclass clloadclassclasstoload plugin iplugin loadedclassnewinstance plugindoproc catch exception e eprintstacktrace finally try threadsleep30 catch interruptedexception e eprintstacktrace iplugin is a simple interface with just one method doprocpublic interface iplugin void doprocand jartesttestplugin is an implementation of this interface where doproc just prints out some statementsnow i package the jartesttestplugin class into a jar called testjar and place it under cplugins and run this code the first iteration runs smoothly and the class loads without issues when the program is executing the sleep statement i replace cpluginstestjar with a new jar containing an updated version of the same class and wait for the next iteration of while now heres what i do not understand sometimes the updated class gets reloaded without issues ie the next iteration runs fine but sometimes i see an exception thrownjavalangnullpointerexceptionat javaiofilterinputstreamclosefilterinputstreamjava155at sunnetwprotocoljarjarurlconnectionjarurlinputstreamclosejarurlconnectionjava90at sunmiscresourcegetbytesresourcejava137at javaneturlclassloaderdefineclassurlclassloaderjava256at javaneturlclassloaderaccess0urlclassloaderjava56at javaneturlclassloader1runurlclassloaderjava195at javasecurityaccesscontrollerdoprivilegednative methodat javaneturlclassloaderfindclassurlclassloaderjava188at javalangclassloaderloadclassclassloaderjava307at javalangclassloaderloadclassclassloaderjava252at testmisctestjarloadingmaintestjarloadingjava22i have searched on the net and scratched my head but cannot really arrive at any conclusion as to why this exception is thrown and that too only sometimes not alwaysi need your experience and expertise to understand this whats wrong with this code please helplet me know if you need any more info thanks for looking,['java'] +72747,whats wrong with my include in relativelayout i want to create an activity with a title bar at top and a navigation bar at bottom i used include to include the title bar layout and the navigation bar layout into the main layout as you can see below the result is that both the title bar and navigation bar go to the top of the screen could someone tell me why thanksxml version10 encodingutf8relativelayout xmlnsandroid androidididhome widget androidlayout widthfill parent androidlayout heightfill parent androidbackgrounddrawablebackground include androidididtitle bar layoutlayouttitle bar androidlayout alignparenttoptrue include androidididnavigation bar layoutlayoutnavigation bar androidlayout alignparentbottomtrue relativelayoutediti did not find the root cause but the following worksxml version10 encodingutf8relativelayout xmlnsandroid androidididhome widget androidlayout widthfill parent androidlayout heightwrap content androidbackgrounddrawablebackgroundrelativelayout androidlayout widthfill parent androidlayout heightwrap content androidlayout alignparenttoptrue androidididtitle bar include layoutlayouttitle bar relativelayoutrelativelayout androidlayout widthfill parent androidlayout heightwrap content androidlayout alignparentbottomtrue androidididnavigation bar include layoutlayoutnavigation bar relativelayout,['android'] +72749,sample c code for canon edsdk liveview is there anyone with a working piece of sample c code that implements liveview using the canon edsdk the sample code in the documentation looks great until you get to this bit thisplay image yup that is it they do not show how to blt an image to a window using the data retrieved from the camera they just say thisplay image thanks canoni have hunted the internet including this forum but i have yet to find a c code sample that shows how to do this i am looking to avoid mfc vb managed code or c surely it is possible to do this in vanilla c right vanilla c is fine as wellthanksfredp,['c'] +72750,clean c granular friend equivalent answer attorneyclient idiom why does c have public members that anyone can call and friend declarations that expose all private members to given foreign classes or methods but offer no syntax to expose particular members to given callersi want to express interfaces with some routines to be invoked only by known callers without having to give those callers complete access to all privates which feels like a reasonable thing to want the best i could come up with myself below and suggestions by others so far revolve around idiomspattern of varying indirectness where i really just want a way to have single simple class definitions that explicitly indicate what callers more granularly than me my children or absolutely anybody can access which members what is the best way to express the concept below can i grant yusesx selective xrestricted access more cleanlyvoid yusesxint n x x int m xattorneyyrestrictedx nstruct x class attorneyy proxies restricted state to part or all of yprivate void restrictedint something preferably selectively available friend class attorneyy give trusted member class private access int personal truly private state single abstract permission can add more friends or forwardsclass xattorneyy friend void yusesxint x int inline static void restrictedx x int n xrestrictedn i am nowhere near being a software organization guru but it feels like interface simplicity and the principle of least privilege are directly at odds in this aspect of the language a clearer example for my desire might be a person class with declared methods like takepillmedicine tellthetruth and forfeitdollarsunsigned int that only physician judge or taxman instancesmember methods respectively should even consider invoking needing onetime proxy or interface classes for each major interface aspect sits ill with me but please speak up if you know i am missing somethinganswer accepted from drew hall dr dobbs friendship and the attorneyclient idiomthe code above originally called the wrapper class proxy instead of attorney and used pointers instead of references but was otherwise equivalent to what drew found which i then deemed the best generally known solution not to pat myself on the back too hard i also changed the signature of restricted to demonstrate parameter forwarding the overall cost of this idiom is one class and one friend declaration per permission set one friend declaration per set approved caller and one forwarding wrapper per exposed method per permission set most of the better thiscussion below revolves around the forwarding call boilerplate that a very similar key idiom avoids at the expense of less direct protection,['c++'] +72756,how can i find the socket type from the socket descriptor i am writing a program to capture socket network flow to thisplay network activityfor this i was wondering if there is any way i can determine the socket type from the socket descriptori know that i can find socket family using getsockname but i could not find a way to find socket typefor instance i want to find if this socket was open as udp or tcpthanks for any advice in advanceyeh,['c'] +72771,nullcoalescing operator and lambda expression take a look at the following code i attempted to write inside a constructorprivate predicatestring isvalidpredicatestring isvalid this isvalid isvalid s truethe code does not compile just invalid expression terms and so onein contrast that does compile and i could just use itthis isvalid isvalid new predicatestrings truehowever i still wonder why this syntax is not allowedany ideas,"['c#', '.net']" +72775,google closure compiler with jquery applications i have a lot of time invested in jquery and a large application built with it recently i have been reviewing google closure library but at this time have found it to be not nearly as elegant as jquery i believe it may have some potential and will look into it more but for now i intend to continue using jquery as my base frameworkhowever i am extremely impressed with google closure compiler i would love to start using it during the build process of my application unfortunately it is not exactly clear how easy it will be to use it for projects that do not follow the standard google closure standardsare there any bestpractices or good resources on developing jquerybased projects and using the google closure compiler for instancedoes it make sense to compile jquery and jqueryui with it or should i continue pointing to these resources on the google cdn i am sure my jquery and jqueryui will be smaller since i do not use all features of the libraries but pointing to a cdn increases the the chances the file is already be in a visitors cachemy application is split into many files with a file per function i would like to combine them in a specific order and minify them into a file per section on my site i would like to automate this process currently my project has a java backend and is built with maven does it make sense to add google closure compiler to this build processbasically i am looking for any good resources that are specific to using google closure compiler with jquery,['jquery'] +72791,rename a file in c how do i rename a file using c,['c#'] +72818,nsmutablearray addobject nsarrayi addobject unrecognized selector sent to instance i have tried to initialize my nsmutablearray 100 ways from sunday and nothing is working for me i tried setting it equal to a newly allocated and initialized nsmutablearray just allocating initializing the variable by itself every combination i could think of and always the same resultheres the codeobjecthnsmutablearray arrayproperty copy nsmutablearray arrayobjectmsynthesize arrayif selfarray selfarray addobjectanobjectelse selfarray nsmutablearray arraywithobjectsanobject nilnote in debug anobject is not nil at time of executioni have tested anobject and it isthe initialization works just fine but i keep getting the error below when i try to addobject to selfarray20100710 115255499 myapp43471807 nsarrayi addobject unrecognized selector sent to instance 0x18448020100710 1152508 myapp43471807 terminating app due to uncaught exception nsinvalidargumentexception reason nsarrayi addobject unrecognized selector sent to instance 0x184480does anyone have any idea whats going wrong,['iphone'] +72823,how do i install an old version of django on virtualenv this may sound like a stupid question since the very purpose of virtualenv is to this exactly installing some specific version of a package in this case django inside the virtual environment but it is exactly what i want to do and i cannot figure it outi am on windows xp and i created the virtual environment successfully and i am able to run it but how am i supposed to install the django version i want into it i mean i know to use the newlycreated easy install script but how do i make it install django 107 if i do easy install django it will install the latest version i tried putting the version number 107 into this command in various ways but nothing workedhow do i do this,['python'] +72829,if a is a template for actual type then why is typeofa allowed class program static void mainstring args type t typeofa consolewritelinetypeofa prints a2t1t2 class at1t2as far as i know generic type at1 t2 is not an actual type but rather a blueprinttemplate for an actual type so why does typeof accept it as a parameter since as far as i know typeof accepts as parameter actual typesthank you,['c#'] +72830,instead of error why do not both operands get promoted to float or double 1 if one operand is of type ulong while the other operand is of type sbyteshortintlong then compiletime error occurs i fail to see the logic in this thus why would it be bad idea for both operands to instead be promoted to type double or float long l 100 ulong ul 10 double d l ul error saying operator cannot be applied to operands of type ulong and longb compiler implicitly converts int literal into byte type and assigns resulting value to bbyte b 1but if we try to assign a literal of type ulong to type longor to types int byte etc then compiler reports an errorlong l 10uli would think compiler would be able to figure out whether result of constant expression could fit into variable of type long thank you,['c#'] +72834,local storage vs cookies i want to reduce load times on my websites by moving all cookies into local storage since they seem to have the same functionality are there any proscons especially performancewise in using local storage to replace cookie functionality except for the obvious compatibility issues,['html'] +72835,read all the contents in ini file into dictionary with python normally i code as follows for getting a particular item in a variable as followstry config configparserconfigparser configreadselfinipathnameexcept configparsermissingsectionheadererror e raise wronginiformaterroretry selfmakedb configgetdbmakedbexcept configparsernooptionerror selfmakedb 0is there any way to read all the contents in a python dictionary for exampleax1y2z3bx1y2z3is written into valax 1valbz 3,['python'] +72839,how to insert jsf page rendering time and response size into the page itself at least partially i realize it is a chicken and egg problem and that it is not possible to accurately resolve the time it took to render a page or the size of response and insert that number into the page itself without affecting either measure nevertheless i am looking for a way to insert either number partially in a page of a jsffaceletsseam applicationeg at the bottom of a jsf page somewhere page size 103kb render time 02s i have come across jsfunit is jsftimer which is really handy however the phase listener approach does not allow the results of render response phase to be inserted into the page not sure how to access the size of the response encoded so far eitheris there a quick and dirty way to hook up to some sort of postprocessing event at or after the end of render response and to inject both numbers into the page about to be rendered one way of approaching this is perhaps through servlet filters but i am looking for something simpler perhaps a trick with seam or faceletsthanksa,['java'] +72847,buffering nsoutputstream used as nsinputstream i have this consumer class that takes an nsinputstream as argument which will be processed async and i want to push data that comes from a producer class that requires that it has an nsoutputstream provided as its output source now how could i set up a buffering or transparent stream that acts as the output stream for the producer and at the same time as the nsinputstream for my consumer classi have looked a bit at the nsoutputstream outputstreamtomemory and outputstreamtobuffercapacity but have not really figured out how to use it as input for an nsinputsourcei had some idea of setting up a middleman class that holds the actual buffer then creating two subclasses one for each nsinputoutputstream which holds a reference to this buffering class and having these subclasses delegate most calls to that class eg output subclass methods hasspaceavailable writemaxlength and for the input hasbytesavailable readmaxlength etcany tips on how to approach this situation are appreciated thanks,['iphone'] +72849,alternative to fiddler hi i use fidder to test bug fixes directly on non development environments it allows you to intercept the bogus javascript file and replace it by any other content you specify without needing to deploy any filesthe problem is that i just use this feature from fiddler and the interface is not very user friendly specially if you need to replaceintercept more than one file it gets quickly tediousis there an alternative software with the same feature and more user friendlyproductive or even better one that integrates easily with your ide personaly i use eclipe,['javascript'] +72852,how to turn a hex string into an unsigned char array for example i have a cstring e8 48 d8 ff ff 8b 0d including spaces which needs to be converted into the equivalent unsigned char array 0xe80x480xd80xff0xff0x8b0x0d whats an efficient way to do this thanksedit i cannot used the std library so consider this a c question i am sorry,['c'] +72881,pointer increment and chaining precedence in c i saw this piece of c code in one of the msdn articles using system class test public static unsafe void main int fib stackalloc int100 int p fib p p 1 for int i2 i100 i p p p1 p2 for int i0 i10 i consolewriteline fibi i am fairly new to pointers i understand most of this code but it would be great if someone can help me understand this line in the above code in more detailp p 1,['c#'] +72889,callstack for exceptions in c today in my c multiplatform code i have a trycatch around every function in every catch block i add the current functions name to the exception and throw it again so that in the upmost catch block where i finally print the exceptions details i have the complete call stack which helps me to trace the exceptions causeis it a good practice or are there better ways to get the call stack for the exception,['c++'] +72916,get a subset of a generator i have a generator function and want to get the first ten items from it my first attempt wasmy generator10this does not work because generators are not subscriptable as the error tells me right now i have worked around that withlistmy generator10this works since it converts the generator to a list however it is inefficient and defeats the point of having a generator is there some builtin pythonic equivalent of 10 for generators,['python'] +72964,erroneous private base class inaccessible compiling this code using g 421struct s templatetypename t struct st templatetypename basetypeclass ref count private basetype templatetypename refcounttypeclass rep base public refcounttype class wrap rep public rep baseref counts typedef rep baseref counts base type line 11i getbugcpp1 error astruct sa is inaccessiblebugcpp11 error within this contexthowever if i change the wrap rep class to use stclass wrap rep public rep baseref count stint typedef rep baseref count stint base typeit compiles fine alternatively if i change the original code toclass wrap rep public rep baseref counts typedef rep baseref count s base type now using it also compiles fine to me the original code seems fine asis is this a g bug if not then why does using a template work and for the other case why is the s necessary,['c++'] +72965,i seem to have fallen into some massive massive trouble with nullreferenceexceptions recently i am developing a software that parses and thisplays xml information from a website simple enough righti am getting loads of nullreferenceexceptions for example this methodprivate void setuserfriendslistfriend list int x 40 int y 3 if list null foreach friend friend in list friendcontrol control new friendcontrol controlid friendid controlurl friendurl controlsetidfriendid controlsetnamefriendname controlsetimagefriendphoto controllocation new pointx y panel2controlsaddcontrol y y controlheight 4 i had to wrap an ugly as sin if around the actual foreach loop in order to prevent an exceptioni feel i am just putting bandaids on a flat tire instead of actually fixing the problem is there any way i can tackle this problem maybe a book i should read regarding programming patterns or what notreally i am lost i am probably asking the wrong questions,"['c#', '.net']" +72986,two different synchronized methods of the same object i have 2 synchronized methods in a class say method1 and method2 a thread say thread 1 holds the lock on that object of the class by executing the synchronized method1can another thread say thread 2 access the lock via method2 at the same time while thread 1 holding the lockthis case is analogs to javautilvector class having synchronized add and remove methodsplease explain this case too,['java'] +73000,how to give name to a callable thread i am executing a callable object using executorservice thread pool i want to give a name to this threadto be more specific in older version i did this thread thread new threadrunnable taskthreadsetnamemy thread namei use thread name in log4j logging this helps a lot while troubleshooting now i am migrating my code from java 14 to java 16 i have written thisgiven below but i dont know how to give name to this threadprivate final executorservice executorpool executorsnewcachedthreadpoolfuturestring result executorpoolsubmitcallable taskplease give me some idea to give name to this thread,['java'] +73003,local notification didreceivelocalnotification calls twice i am handling local notifications using voidapplicationuiapplication app didreceivelocalnotificationuilocalnotification notifand to schedule a local notification voidschedulenotificationwithintervalintminutesbefore uilocalnotification localnotif uilocalnotification alloc init if localnotif nil return nsdate firedate nsdate date localnotiffiredate firedate datebyaddingtimeintervalminutesbefore60 localnotiftimezone nstimezone defaulttimezone localnotifrepeatinterval kcfcalendarunitminute localnotifalertbody nsstring stringwithformatnslocalizedstringlocalevent notification in i minutes nilminutesbefore localnotifalertaction nslocalizedstringview details nil localnotifapplicationiconbadgenumber 1 nsdictionary infodict nsdictionary dictionarywithobjectsandkeysthis is dict you can pass info for your notificationinfonil localnotifuserinfo infodict uiapplication sharedapplication schedulelocalnotificationlocalnotif localnotif release nslogevent scheduledwhen i receive a notification didreceivelocalnotification is called twiceam i doing something wrongplease helpthanks,"['iphone', 'ios']" +73005,why is using thread locals in django bad i am using thread locals to store the current user and request objects this way i can have easy access to the request from anywhere in the programme eg dynamic forms without having to pass them aroundto implement the thread locals storage in a middleware i followed a tutorial on the django sitethis document has since been modified to suggest avoiding this techniquefrom the articlefrom a design point of view threadlocals are essentially global variables and are subject to all the usual problems of portability and predictability that global variables usually entailmore importantly from a security point of view threadlocals pose a huge risk by providing an data store that exposes the state of other threads you provide a way for one thread in your web server to potentially modify the state of another thread in the system if the threadlocal data contains descriptions of users or other authenticationrelated data that data could be used as the basis for an attack that grants access to an unauthorized user or exposes private details of a user while it is possible to build a threadlocal system that is safe from this sort of attack it is a lot easier to be defensive and build a system that is not subject to any such vulnerability in the first placei understand why global variables can be bad but in this case i am running my own code on my own server so i cannot see what danger two global variables posecan someone explain the security issue involved i have asked many people how they would hack my application if they read this article and know i am using thread locals yet no one has been able to tell me i am starting to suspect that this is an opinion held by hairsplitting purists who love to pass objects explicitly,['python'] +73011,jaxrs jersey custom exception with xml or json i have a rest service built using jerseyi want to be able to set the mime of my custom exception writers depending on the mime that was sent to the server applicationjson is returned when json is received and applicationxml when xml is receivednow i hard code applicationjson but that is making the xml clients left in the darkpublic class mycustomexception extends webapplicationexception public mycustomexceptionstatus status string message string reason int errorcode superresponsestatusstatus entitynew errorresponseconvertermessage reason errorcode typeapplicationjsonbuild what context can i tap into to get the current requests contenttypethanksupdate based on answerfor anyone else interested in the complete solutionpublic class mycustomexception extends runtimeexception private string reason private status status private int errorcode public mycustomexceptionstring message string reason status status int errorcode supermessage thisreason reason thisstatus status thiserrorcode errorcode getters and setterstogether with an exceptionmapperproviderpublic class mycustomexceptionmapper implements exceptionmappermycustomexception context private httpheaders headers public response toresponsemycustomexception e return responsestatusegetstatus entitynew errorresponseconverteregetmessage egetreason egeterrorcode typeheadersgetmediatype build where errorresponseconverter is a custom jaxb pojo,['java'] +73021,how do i get the context from the intent accountauthenticatorjavaintent intent new intentcontext accountactivityclassaccountactivityjavain oncreatebundle abundle i want to saygetintentgetcontextbut getcontext does not existhow do i get the context from the intent since it is passed in the intent constructor i was expecting it to be available on arrival in the accountactivity,['android'] +73051,python how does inspectismethod work i am trying to get the name of all methods in my classwhen testing how the inspect module works i extraced one of my methods by obj myclass dict mymethodname but now inspectismethodobj returns false while inspectisfunctionobj returns true and i do not understand why is there some strange way of marking methods as methods that i am not aware of i thought it was just that it is defined in the class and takes self as its first argument,['python'] +73062,how can i use rhino mocks to inspect what values were passed to a method i am new to mocking and i am having a hard time solving an issue with unittestingsay i have this codepublic class myclass private idostuff doer public myclassidostuff doer doer doer public void gosomeclass object do some crazy stuff to the object doerdostuffobject this method is void too ok so i want to unit test the go method i do not care what the doer object does to the object once is gets ithowever i do want to inspect what the doer object has receivedin pseudo code i want to achieve thistestpublic void mytest idostuff doer mockermockidostuff guid id guidnewguid test go method new myclassdoergonew someclassid id assertareequalidmockingframeworkmethoddostuffgetreceivedsomeclassidis this possible using rhino and if so how do i achieve itcheers,['c#'] +73071,deleting specific node in xml i need to delete specific employee node and also its child node based on the value of idfor example here i need to delete employee tag with id2company employee id1id namesaname employee employee id2id namessaname employeecompany,['c#'] +73096,how to know if a pointer points to the heap or the stack examplebool isheapptrvoid ptr int istack 35int ptrstack istackbool isheappointer1 isheapptrptrstack should be falsebool isheappointer2 isheapptrnew int5 should be true i know it is a memory leak why i want to know thisif i have in a class a memberpointer and i do not know if the pointing object is newallocated then i should use such a utility to know if i have to delete the pointerbutmy design is not made yet so i will program it that way i always have to delete it i am going to avoid rubbish programming,['c++'] +73106,nsmutablearray removeobjectatindex throws invalid argument exception i am writing an application to show some news from a portal the news are fetched using a json file from the internet and then stored into a nsmutablearray using the coredata model obviously a user cannot delete the news from the json file on the internet but he can hide them locally the problems come out here where i have the following code voidtableviewuitableview tableview commiteditingstyleuitableviewcelleditingstyleeditingstyle forrowatindexpathnsindexpath indexpath if editingstyle uitableviewcelleditingstyledelete if moc moc newsfetcher sharedinstance managedobjectcontext dataset objectatindexindexpathrow seteliminatansnumber numberwithboolyes nserror error if moc saveerror nslog ca stato un errore dataset removeobjectatindexindexpathrow selftableview deleterowsatindexpathsnsarray arraywithobjectindexpath withrowanimationyes the linedataset removeobjectatindexindexpathrowcause my apps to crash with the following error20100712 190816021 provavideo284207 pfarray removeobjectatindex unrecognized selector sent to instance 0x451c820 20100712 190816022 provavideo284207 terminating app due to uncaught exception nsinvalidargumentexception reason pfarray removeobjectatindex unrecognized selector sent to instance 0x451c820i am trying to understand why it does not work but i cannot if i relaunch the app the new is correctly logically cancelledany suggestions thanks in advanceinterfaceinterface listofvideo uitableviewcontroller nsfetchedresultscontrollerdelegate nsmutablearray dataset property nonatomic retain nsmutablearray dataset in the m filesynthesize datasetinitialization in viewdidloaddataset nsmutablearray newsfetcher sharedinstance fetchmanagedobjectsforentitynews withpredicatepredicate withdescriptortitolo dataset retain updatedatabase this is when checking for new news from the net i add them in the mutablearraydataset addobjectthenews,"['iphone', 'objective-c']" +73121,iphone nesting uiscrollviews for horizontal paging and vertical scrolling i am developing my first iphone app and i would greatly appreciate you guys input on a problem i am havingi am looking to implement scrolling both horizontally and vertically i want the horizontal scrolling to be paged without the vertical one being paged scrolling normally a single uiscrollview with pagingenabled set to yes will page in both directions the natural solution would be to nest a uiscrollview inside another one however when i do that i cannot get the inner uiscrollview to scroll at all seems the outer one is eating up all the tap events like ini read something about inner scrolling being improved upon in sdk 30 and actually when i add an inner uitableview instead of a uiscrollview the scrolling works flawlessly since uitableview subclasses uiscrollview i imagine that my desired behavior should be achievable by making my own subclass of uiscrollview is this the right approach if so what should this subclass look like,['iphone'] +73122,python list comprehension for dictionaries in dictionaries i just learned about list comprehension which is a great fast way to get data in a single line of code but somethings bugging mein my test i have this kind of dictionaries inside the listy 72 x 94 fname test1420 y 72 x 94 fname test277the list comprehension s r for r in list if rx 92 and rx 95 and ry 70 and ry 75 works perfectly on that it is in fact the result of this lineanyway i then realised i am not really using a list in my other project i am using a dictionary like sotest1420 y 060 x 070 fname test1420that way i can simply edit my dictionary with vartest1420 but list comprehensions do not work on thatand i cannot edit lists this way because you cannot assign an index like thatis there another way,['python'] +73133,inner shadow in uilabel is it possible to create such a uilabel with inner and outer shadowi only know shadowcolor and shadowoffsetzoomedthanks,"['iphone', 'objective-c']" +73141,python ftplib cannot get size of file before download i am using ftplib to transfer files everything is working great now i am trying to get the size of the target file before downloadingfirst i tried just getting size with ftpsizefilename server complained that i cannot do that in ascii modethen i tried setting binary mode using ftpsendcmdbinary and ftpsendcmdbin in both cases the server complained 500 binary not understoodcan ftplib get size of a file before downloading in this instance i do not control the ftp server and cannot change how it is behavingthanks,['python'] +73151,jquery check if query string present on url is it possible using jquery or just javascript to check for the existence of a query string on the url,"['javascript', 'jquery']" +73186,ms updatepanels not really ajax i keep hearing that the server side asp net ajax controls like updatepanels are not truly ajax though they seem like it because rendering is not completely on the client side i am trying to understand this with more clarity could someone elaboratethanks,"['c#', '.net']" +73196,in c is it faster to use the standard library or write your own function for example in ctypeh there are functions like isalphai want to know if writing an isalpha function on my own is faster than calling isalphathanks for all your instant replies just want to make clearer to my questionso even for the isalpha function because you can simply pass a character and check if the character is between a and z a and zanother question when you include a std library like ctypeh and just call one function like isalpha will the filei mean all lines of code be loaded my concern is that the bigsize will make program slower,['c'] +73207,how to determine the file extension of a file from a uri assuming i am given a uri and i want to find the file extension of the file that is returned what do i have to do in javafor example the file at is when i do uri uri new uriaddress url url uritourl string file urlgetfile systemoutprintlnfilei am not able to see the full file name with owl extension just 200108baseballbaseballont how do i get the file extension as well,['java'] +73214,is there a program to convert assembly to c is there a program that will convert assembly to c or ci did a lot of searching but i could not find anything that worksthere is a program called boomerang it looks great and just want i wanted but it is very unstable and crashes when i try to use it boomerangare there any other free programs that will do that,['c++'] +73216,is there a way to detect when a visitor comes back to your page after opening a new window is there a way using javascript or jquery to detect when someone goes back to your page after opening a new window or tabi want to create a script that opens a new window or tab and then does something when the user comes back to the pagethanks,"['javascript', 'jquery']" +73218,read a file backwards line by line using fseek how do i read a file backwards line by line using fseekcode can be helpful must be cross platform and pure phpmany thanks in advanceregardsjera,['php'] +73229,how to thisable google translate original text tooltips i have used google translate as a language converter in my site but it thisplays annoying tool tips called original text how do i thisable this and any other better ideastoolsapis to do thisthanksthe code used isdiv idgoogle translate elementdivscriptfunction googletranslateelementinit new googletranslatetranslateelement pagelanguage en google translate elementscriptscript src aelementjscbgoogletranslateelementinitscript,"['javascript', 'jquery', 'html']" +73230,no aspnet features on iis 75 i thought i could see an aspnet features panel i do not know the exact name though some of them are net compilation net roles net users and so on on the iis7 manager when i click a site node in the nodes list of the iis7 manager now i can see only iis and management but no aspneti first installed net framework 40 so after installing iis7 i used the aspnet regiis tool and seemed it worked well my environment iswindows 7 proiis 757600net framework 40,['asp.net'] +73247,whats design pattern principle in the android development i was a jave developer recently i joined an android development team the structure of android confused me the mvc design pattern does not seem to suit for android development so what is the design pattern principle for android development i mean is there any hint about how to write a clean easy reading and effective android code,['android'] +73263,find the 5th element with a specified class in a list and add another class in jquery i would like to addclass green to the 5th lihr in every ul containers in my siteul lihreachfunction if thislength 5 thisaddclassgreen ps if its possible with css only tell me how pleasenote that the ul has mixed elements likeli classafoolili classbfoolili classhrfoolili classcfoolili classafoolili classhrfoolii need the 5th lihr,"['jquery', 'html', 'css']" +73266,margintop under a floated div css i have a div under a floatright div for some reason the top margin cannot be applied to the first div here is the cssover width80 floatright colore68200 under clearboth backgroundurlimagesanazitisipng norepeat margin10px auto does not work width95px height20px does anyone know whats going on,['css'] +73277,how do i dynamically insert an iframe in a div how do i dynamically insert an iframe in a div using jquerydocumentreadyfunction divhtmliframe srciframe i tried the above code but it does not work,"['javascript', 'jquery']" +73281,are static const variables threadsafe i am wondering whether static constant variables are threadsafe or notexample code snippetvoid fooint n static const char a foobareggspam if,['c'] +73289,spring using builder pattern to create a bean i use ektorp to connect to couchdb the way to build an ektorp httpclient instance is to use builder patternhttpclient httpclient new stdhttpclientbuilder hostmychouchdbhost port4455 buildi am relatively new to spring please advice me on how i can configure an httpclient in my context to create it via the builderone way to do this is with configuration are any other options,['java'] +73291,assert list in junit how to assert list in junit test case i mean not only the size of the list but also the contents of the list,['java'] +73336,subclassing int in python i am interested in subclassing the builtin int type in python i am using v 25 but having some trouble getting the initialization workingheres some example code which should be fairly obviousclass testclassint def init self int init self 5however when i try to use this i get a testclass a0where i would expect the result to be 5what am i doing wrong google so far has not been very helpful but i am not really sure what i should be searching for,['python'] +73344,accessing colors in a resource dictionary from a value converter i defined several colors in a resourcedictionary egresourcedictionary color xkeygray1f7f1f3color color xkeygray2ffd8dacolorltresourcedictionaryso i can reuse them everywhere in applicationnow i wrote a value converter to convert the items inner state to the related color how can i access the defined colors in the code of the value converter my first thought was to pass the dictionary as converter parameter but i do not know how to achieve that regardseditapplicationcurrentresources is not an option because i would not have access to it later,['c#'] +73368,jquery dynamic canvas creation ctxgetcontext is not a function when i try to execute this in jquery i get ctxgetcontext is not a function in firebugvar ctx canvas width100 height100 widgetappendctx ctxgetcontext2d any idea why i get this error how do i dynamically create and initialize a canvas element,['jquery'] +73393,how to use the multiply and accumulate intrinsics in arm cortexa8 how to use the multiplyaccumulate intrinsics provided by gccfloat32x4 t vmlaq f32 float32x4 t float32x4 t float32x4 tcan anyone explain what three parameters i have to pass to this function i mean the source and destination registers and what the function returnshelp,['c'] +73412,how to capture part of a screen i am using the win32 printwindow function to capture a screen to a bitmap object if i only want to capture a region of the window how can i crop the image in memoryhere is the code i am using to capture the entire windowsystemruntimeinteropservicesdllimportstruser32dll charset charsetauto setlasterror truepublic static extern int printwindowintptr hwnd intptr hbltdc uint iflagspublic enum enprintwindowflags uint summary summary pw all 0x0 summary only the client area of the window is copied by default the entire window is copied summary pw clientonly 0x01public systemdrawingbitmap capturewindowintptr hwnd enprintwindowflags eflags systemdrawingrectangle rctform systemdrawingrectangleempty usingsystemdrawinggraphics grfx systemdrawinggraphicsfromhdcgetwindowdchwnd rctform systemdrawingrectangleroundgrfxvisibleclipbounds systemdrawingbitmap pimage new systemdrawingbitmaprctformwidth rctformheight systemdrawinggraphics graphics systemdrawinggraphicsfromimagepimage intptr hdc graphicsgethdc paint control onto graphics using provided options try printwindowhwnd hdc uinteflags finally graphicsreleasehdchdc return pimage,['c#'] +73418,sql pivot with multiple columns need help with the pivot clause in sql server 2008i have a table with this infoweekno dayofweek fromtime totime1 2 10 14001 3 10 14002 3 0800 13002 4 0900 13002 5 1400 22003 1 0600 13003 4 0600 13003 5 1400 2200i want to convert this into a table that looks like thisweek start1 end1 start2 end2 start3 end3 start4 end4 start5 end5 start6 end6 start7 end71 10 1400 10 14002 0800 1300 0900 1300 1400 22003 0600 1300 0600 1300 1400 2200is there any way to do with a pivot queryplease write respond with an example on how to do it i appreciate any kind of help on this thanks in advance,['sql'] +73432,how do i remove redundant namespace in nested query when using for xml path update i have thiscovered there is a microsoft connect item raised for this issue herewhen using for xml path and with xmlnamespaces to declare a default namespace i will get the namespace decleration duplicated in any top level nodes for nested queries that use for xml i have stumbled across a few solutions online but i am not totally convinced heres an complete exampledrop table t1drop table t2create table t1 c1 int c2 varchar50create table t2 c1 int c2 int c3 varchar50insert t1 values 1 mouse2 chicken3 snakeinsert t2 values1 1 front right2 1 front left3 1 back right4 1 back left5 2 right6 2 leftwith xmlnamespaces default urianimalselect ac2 as species select lc3 as text from t2 l where lc2 ac1 for xml pathleg type as legsfrom t1 afor xml pathanimal rootzoowhats the best solution,['sql'] +73433,mysql how to add a column if it does not already exist i want to add a column to a table but i do not want it to fail if it has already been added to the table how can i achieve this add column fails if it already exists alter table tablename add columnname int1 not null default 0,['mysql'] +73437,how to turn off break line in eclipse does anybody know how to turn line breaking in eclipse after you press ctrl shift f code format ex systemerr printlnincorrect file name make sure you include extension with your file name,['java'] +73441,problem using openstruct with erb edit forgot to include my environment info win7x64 rubyinstaller ruby v191p378edit 2 just updated to v191 patch 429 and still getting this same erroredit 3 running this same code in ruby v187 patch 249 works fine so it is v191 that broke it apparentlyi am new to using erb and the samples i could find are um less than helpful having played around with erb for about an hour i got some basic examples working finally but i have no idea why this does not work require ostructrequire erbdata bar barvars openstructnewdatatemplate foo erb erbnewtemplatevars binding varssendbindingputs erbresultvars bindingthis code produces the following errorirbmain0070 puts erbresultvars bindingnameerror undefined local variable or method bar for mainobject from erb1 from crubyv191libruby191erbrb753in eval from crubyv191libruby191erbrb753in result from irb7 from crubyv191binirb12in why is it looking at the mainobject binding i told it to use the binding from the openstruct by passing in vars bindingcan someone fill me in on why it does not work and help me get it to work,['ruby'] +73447,how to change the name of a database model and table in rails lots out there about changing model names only or mapping new models to existing tables but nothing about renaming both at the same time for now i am starting with the db table and working my way out with findreplace in my code but i am surprised there is not something better or at least someone whos tried it and written about it,['ruby-on-rails'] +73448,detecting iphone app running on ipad in compatibility mode my iphone app is not universal but it has a feature that i would like to enable for people playing on ipads is there some way to detect that youre running on an ipad in compatibility mode the uidevice methods for detecting machine specs all return the values you would get on an iphone on the simulator at least the only thing i can think of is detecting os 32 but that technique would not work for long,"['iphone', 'objective-c']" +73454,move content from one hidden div to another thisplayed div how do i move content from one hidden div to another thisplayed div using jquerysay i have div1 with thisplay style is none and another div div2 with thisplay style blockhow do i move the content from div1 to div2 and clear div1,['jquery'] +73459,cannot see my own application methods in java visualvm i am trying to profile my java app just to find out the methods in which most time is being spent given the poor reactions here to tptp i thought i would give java visualvm a goit all seemed rather simple to use except that i cannot seem to get anything consistent or useful out of iti cannot seem to see anything relating to my own code all i get is a whole bunch of calls to things like java methodsi have tried restricting instrumentation to only my own packages which seems to cut down the number of methods instrumented but still i do not ever seem to see my owneach time i run i get varying numbers of methods instrumented ranging from 10s to 10si have tried putting in a sleep at the start of my app to make sure i get visualvm up and running before my app starts to do anything interesting to make sure it is profiling when the interesting stuff is runningis there something i have to do to ensure my classes get instrumented are there timing issues like have to wait for classes to be loaded etc i have also tried running the guts of the code twice to make sure all the code does get exercisedi am just running an app with a main from eclipse i have tried using the eclipse integration so that visualvm starts up when i start the app results are the samei have also tried exporting the app as a runnable app and running it standalone from the command line rather than through eclipse same resultmy app is not a long running web app etc just a main that calls some other of my own classes to do some processing then quitsi would be grateful for any advice about what i might be doing wrong thanks,['java'] +73465,how to include a external jar in a gwt google web toolkit project i have a external jar file named xjar i use xjar in my gwt projectwhen i attempt to build the javascript version of my project in ant i get one of the following type of errors at every location in which i use x i get a error of this kind when doing the gwtc task in ant the javac compilation process proceeds just fineerror line 45 no source code is available for type orgxobjectname did you forget to inherit a required moduleok so clearly it is not able to seeuse the xjar fixing this problem however is not as simple in gwt as it is in plain java from the internet ref1 i gather that i need to include all the source java files from xjar in a source directoryadd this source directory in some sort of new gwtxml filehope and pray that all the java files are translatable by gwt so what exactly do i do what is this gwtxml file i need to generate step 2 where do i put the source directory and how to i reference it step 1 what exactly are the mechanical steps necessary to add a external jar file in gwt,['java'] +73469,how do i format a double to a string and only show decimal digits when necessary i have code likelblfranshizshowinvwnoskhehedittext stringformat0n doubleintparsedrdarmanfranshizdarsadtostring converttoint64radnumerictxtpayinvwnoskhehedittext 100but 0n0 string format forces the labels text to not have decimal digits and 0n string format forces the labels text to have 2 decimal digits defaultin my scenario i just want decimal digits when necessary without rounding them how can i do that,['c#'] +73482,convertcast an stdclass object to another class i am using a third party storage system that only returns me stdclass objects no matter what i feed in for some obscure reason so i am curious to know if there is a way to castconvert an stdclass object into a full fledged object of a given type for instance something along the lines ofstdclass is an stdclass instanceconverted businessclass stdclassi am just casting the stdclass into an array and feed it to the businessclass constructor but maybe there is a way to restore the initial class that i am not aware ofnote i am not interested in change your storage system type of answers since it is not the point of interest please consider it more an academic question on the language capacitiescheers,['php'] +73494,socket using in a swing applet i should made a server client in javabased on swing and guii ned to make somehow a socket that will go from the server to the client and from the client to the server and will pass some kind of a stringi would like to have later a function that would do several things according to the string that would be in the socketfor some reason i could not find a simple example for code that shows how it is done in a simple wayanyone has any simple example or can explain how is it being done,['java'] +73511,change image onconfigurationchanged hi allis there a way to change imageview drawable with its corresponding drawable for landscape mode without destroying the whole activity i tried to set the drawable again in onconfigurationchanged callback but it does not work something like this overridepublic void onconfigurationchangedconfiguration conf superonconfigurationchangedconf mimageviewsetimagedrawablegetresourcesgetdrawablerdrawableivwhen i star the activity in landscape mode to correct drawable is thisplayed so resources are located correctly,['android'] +73516,ways of scheduling tasks without writing windows scheduler in aspnet i am into shared hosting and they do not allow me to use windows scheduler so what are the ways of achieving scheduled tasks ietimed mail in aspnet i just saw background process by jeff atwood blog is it relaible or any other ways of doing scheduled tasks then i found quartznet but i cannot find a simple example that embeds quartznet into an aspnetwithout installing a quartznet server as a standalone windows service any suggestion on quartznet,"['c#', 'asp.net']" +73526,whats equivalent to long data type in postgresql greetings alli want to know whats equivalent to long data type in postgresqlwhich i can retrieve in a long variable,['java'] +73563,do you need to thisplay an eula when using flurrygoogle analytics i hear different things from different people on that topic and nobody is really sure also a quick google search does not reveal anything informativethe question is when using flurry analytics or google analytics or whatever analytics tool in an android app do i need to inform the users in form an eula or something similar that is shown on first app start and has to be acceptedthe stats collected are completely anonymous so most people say you do not have to show an eula but whats the truth now,['android'] +73583,mysql group by age range including null ranges i am trying to count the number of people by age ranges and i can almost do it with 2 problemsif there are no people in a given age range null then that age range does not appear in the results for example in my data there is no entries for over 80 so that date range does not appear basically it looks like a mistake in the programming when there are missing date rangesi would like to order the results in a specific way in the query below because the order by is by age range the results for 20 29 come before the results for under 20heres a sample of the db table inquiriesinquiry id birth date1 196002012 196203043 197003084 198003025 19900208heres the queryselect case when age 20 then under 20 when age between 20 and 29 then 20 29 when age between 30 and 39 then 30 39 when age between 40 and 49 then 40 49 when age between 50 and 59 then 50 59 when age between 60 and 69 then 60 69 when age between 70 and 79 then 70 79 when age 80 then over 80 when age is null then not filled in null end as age range count as count from select timestampdiffyear birth date curdate as age from inquiries as derived group by age range order by age rangeheres a simple solution based on the suggestion by wrikkenselect sumifage 2010 as under 20 sumifage between 20 and 2910 as 20 29 sumifage between 30 and 3910 as 30 39 sumifage between 40 and 4910 as 40 49 sumifage between 50 and 5910 as 50 59 sumifage between 60 and 6910 as 60 69 sumifage between 70 and 7910 as 70 79 sumifage 80 1 0 as over 80 sumifage is null 1 0 as not filled in nullfrom select timestampdiffyear birth date curdate as age from inquiries as derived,['mysql'] +73587,capturing log4j output when executing testng tests i am executing testng tests and the logging output is set to debug so in case of a failure i can get to inspect exactly what goes wrongthe problem is that the output is extremely verbose and it is bothering everyone when it runs i would like to capture all log4j logging events which is easy and only print them when the test fails also i need to take into account beforeafter methods and also print output for themassuming that i already have a list of log4j loggingevents how can i print those only when the testafterbefore methods fail,['java'] +73621,openid authentication in c multiplayer network game i am planning is an openid client in a multiplayer network c game the hoster will have the option to allow only logins from people who can authenticate via openid also i want to make it possible to allow only certain people to loginwe already have some simple html viewer in our code and we plan to migrate to webkit so thisplaying html for the openid endpoint login is not really a problemwe also have code for http requests we have already migrated to libcurl herei have not found any c code for doing the rest the actual openid endpoint handshake is there any c code for thisif not where is a good point to start i do not really have much ideas about the openid internals is it complicated to code that myselfis it possible at all like this i think i have seen that i must put some authentication site url or so to the openid endpoint where it will return to if the login is successful in this case there is no site where you login via openid it is a gameserverif that is really a problem to do it this way we also have our own webserver one for our forum and we have the sourceforge one so we could also do all the stuff there however this has the huge drawback that the game depends on some website for the openid login which is very bad one of the nice advantages of openid is gone,['c++'] +73640,convert degreesminutesseconds to decimal coordinates in one part of my code i convert from decimal coordinates to degreesminutesseconds and i use thisdouble coord 59345235int sec intmathroundcoord 3600int deg sec 3600sec mathabssec 3600int min sec 60sec 60how would i convert back from degreesminutesseconds to decimal coordinates,['c#'] +73641,accuracy of mathsin and mathcos in c i am terribly annoyed by the inaccuracy of the intrinsic trig functions in the clr it is well know that mathsinmathpi012246063538223773instead of 0 something similar happens with mathcosmathpi2 but when i am doing a long series of calculations that on special cases evaluate to mathsinmathpi2xmathcosxand the result is zero for x02 but not zero for x01 try it another issue is when the argument is a large number the inaccuracy gets proportionally large so i wonder if anyone has coded some better representation of the trig functions in c for sharing with the world does the clr call some standard c math library implementing cordic or something similar linkwikipedia cordic,['c#'] +73646,parsing commandline arguments from a string in clojure i am in a situation where i need to parse arguments from a string in the same way that they would be parsed if provided on the commandline to a javaclojure applicationfor example i need to turn foo bar baz fooy barish foo into foo bar baz fooy barish fooi am curious if there is a way to use the parser that java or clojure uses to do this i am not opposed to using a regex but i suck at regexes and i would fail hard if i tried to write one for thisany ideas,['java'] +73649,what doctype should i target today i am refactoring a net web application that is in doctype html public w3cdtd html 40 transitionalen right now the approach is just to aim for the stars and go for the latest doctype just because it is latest i would like to make a wiser choice and target a specific one and for good reasonsthere are similar questions existing but the answers might be outdated nowwhat is the difference advantages thisadvantages between standards and quirks mode what are some quirks i may run into with differently set doctypesi have been told that an xhtml doctype is preferable to integrate ajax since the upadtepanel serializes it and to do so needs to have a xhtml do type to what extent is this trueand for browser compatibility in which direction are browsers going in terms of doctype is there a common thrend or do they differ,"['asp.net', 'html']" +73665,making a div that covers the entire page i would like to make a div that covers the entire page i put a css style with height100 but this covers only the viewable area i want it to also cover the area when i scroll down,"['html', 'css']" +73683,how do i get first name and last name as whole name in a mysql query i want to be able to do something like thisselect first name last name as whole name from usersso basically i get one column back whole name which is first name and last name concatenated together with a spacehow do i do that in sql or more specifically mysql,"['sql', 'mysql']" +73690,aspnet mvc 2 how to ignore an entire directory using ignoreroute i have tried the following two methods to try and ignore my assets folder but i keep coming up with errors can anyone tell me exactly how the ignore regex is supposed to look routesignorerouteassets routesignorerouteassets new with assets assets,['asp.net'] +73704,preventing nokogiri from escaping characters i have created a text node and inserted into my document like sonokogirixmltext0x3fcce081481c stylesheet link tag stylewhen i try to save the document with thisfileopennghtml wf f pageto htmli get this in the actual documentlt stylesheet link tag stylegtis there a way to thisable the escaping and save my page with my erb tags intactthanks,"['ruby-on-rails', 'ruby']" +73715,python finding a string key in a dictionary that contains a substring in my script i build a dictionary of keysalbums mapped to artistsvalues so that i can do a quick lookup of what artists made what albums however i want the user to be able to find all albums which contain a substring for example a search on light should return light chasers cloud cult and also night light au revoir simonewhats the best way to do this should i even be using a dictionary,['python'] +73718,how to prevent a click on a link from jumping to top of page in jquery warning this may be a very stupid questioni am currently using a tags with jquery to initiate things like click events etc example is a href clasomeclasstextabut i hate how the makes the page jump to the top of the pagewhat can i do instead,"['javascript', 'jquery', 'html']" +73739,python 2x or 3x since there is a python 3x why do not we use itwhy do we still use 2xwhats the difference,['python'] +73747,javascript get elements current onclick contents i have a page with the following codea idtest hrefsomeurl onclicksomefunctionlinkai need to actually read the onclick data as such i would like something to the effect ofalertdocumentgetelementbyidtestonclicksadly it returns undefined what do i need to do to get somefunction,['javascript'] +73773,sql azure what will happen if size of my sql azure get 5gb i need to know what will happen when a database in sql azure exeeds its size for example i defined a 1gb database and this is going over its size limit will it change to a 5gb database,['sql'] +73774,c string splitting breaking string up at second comma i have a string like somystring test1 1 anotherstring 5 yetanother 400myarray can be of varying length what i would like to do is split the string up like sotest1 1 anotherstring 5yetanother 400is this possible i tried string newarray mystringsplit but that splits it at every comma and not the second comma which is what i would like to dothanks for your helpzaps,['c#'] +73785,problems showing uimenucontroller one after another i am using the new customization abilities of the uimenucontroller to add things other than copy to the menu for cutpaste into a webviewwhat i do is getting the reference to the shared uimenucontroller setting my nsarray of uimenuitems into the menuitems and everything work fine as long as i add a single item for instance i see copyfoobarinstead if i try adding more than a single item what happen is that i see copymore if i press into more than finally the other items will show upis possible to show directly copyfoobarthreefour instead i saw a few applications that are able to do this notably ibooksany help very appreaciated thank youcheerssissensio,['iphone'] +73787,how to give focus property to text box in ruby on rails i have a problem with setting the focus to the textbox for a login page in ruby on rails i want to give focus to a user text field is there any way to give focus property to text field,['ruby-on-rails'] +73803,apply an appconfig to my dll assembly i am writing a class library as an abstraction to use for logging in any application service etc that i write i am making it decently robust by making it very configurable to suit my needs for most applicationservice logging scenarios that i come acrossthe config is designed to specify things such aswhat logging level to writewrite to one log file for all levelswrite to separate files per levellogging cutoff periodic app event byte size restrictedlog file expiration delete log files after file agewrite as flat text or xmllog file name format specificationwhether to prefix filename with dateparent apps nameetc etc etci have read some other stackoverflow questions regarding configs for dll assemblies and it causing conflict between the appconfig for the hosting assemblyapp i believe that my assembly has just cause to provide a config fileis this a good scenario for that occasion is it perhaps a better idea to backe my own config into my project so that my logger reads from xml files to retrieve config values,['c#'] +73823,how to ajaxsubmit a form textarea input from ckeditor i am using ckeditor jquery and jquery form plugin and i would like to submit contents of the ckeditor form via an ajax query here is my code form idarticleform namearticleform methodpost actionmyprojectsave textarea namebodytext stylevisibility hidden thisplay nonetextarea script typetextjavascript ckeditorreplacebodytext script a onclickarticleformajaxsubmitsubmitaformunfortunately it seems that the ajax request does not pass the bodytext parameter what did i do wrong or how can i achieve what i needthank you,"['javascript', 'jquery']" +73837,how do i dynamically create a test suite in junit 4 i would like to create a junit test suite using junit 4 where the names of the test classes to be included are not known until the test suite is runin junit 3 i could do thispublic final class mastertester extends testcase used by junit to specify what testcases to run return a suite containing what testcases to run public static testsuite suite testsuite suite new testsuite forclass klass gathertestclasses suiteaddtestsuiteklass return suite and let the gathertestclasses method deal with figuring out what test classes to runin junit 4 the documentation says to use an annotation suiteclassestestclass1class testclass2class to build up my test suite there are numerous so answers showing how to do this unfortunately the examples i see do not seem to allow for passing a dynamically generated list of testclassesthis so answer suggested i would have to subclass blockjunit4classrunner which i do not want to dodynamically specified test suites seem like something that must be in junit 4 somewhere does anyone know where,['java'] +73839,html helper takes a dictionary how to use this parameter if a html helper takes a idictionary as a parameter how do i use iti tried htmlblah new id blah but that does not work,"['c#', 'asp.net']" +73845,new date is working in chrome but not firefox i am creating a datetime string that looks like this 20100715 115421and with the following code i get invalid date in firefox but works just fine in chromevar todaydatetime year month day hour minute secondsvar date1 new datetodaydatetimein firefox date1 is giving me an invalid date but in chrome its working just fine what would the main cause be,['javascript'] +73857,executing blocks from nsarray i was just thinking as you can treat blocks like objects if i create two of them and then add them to an nsarray is there a way to execute them from the arrayint block 001void return 101 int block 002void return 202 nsarray array nsarray arraywithobjectsblock 001 block 002 niledit update for clarity per davedelongs excellent answerint block 001void return 101 copyint block 002void return 202 copynsarray array nsarray arraywithobjectsblock 001 block 002 nilblock 001 releaseblock 002 release,"['iphone', 'objective-c']" +73860,why do inputs and selects use different box models it appears at least in ie 8 and firefox 3 that for input elements the width refers to the content but for select elements the width refers to the content borders i am explicitly specifying the width in the css stylewhats the deal i would have thought that both are inline replaced elements and would behave identically is this behavior consistent with w3c standards does it work this way in all major browsers,['css'] +73865,ruby require file and relative location so i am writing some rspec tests and i am embarrassed at my lack of ruby understandingi have a file structure that looks like the followinggui teststeststest specrb gui testswindows guirb gui testsupload toolrbwhen i run spec for the test specrb file i require the upload tool file to be included like sospec r upload tool fs test specrbthen the upload tool requires windows guirb like sorequire windows guimy question is why so i have to reference windows guirb relative to test specrb requiring the rather than the upload toolrb this feels wrong to me i will want to use the upload toolrb out of context of the test specs which means changing the requires each timeclearly i am missing something but if i do not reference relative to the test spec i get a file not found errorsorry for being so ignorant here but i am coming up empty handed any thoughts appreciatedbb,['ruby'] +73868,converting from hex to binary without losing leading 0s python i have a hex value in a string like h 00112233aabbccddeei know i can convert this to binary withh bininth 162however this loses the leading 0s is there anyway to do this conversion without losing the 0s or is the best way to do this just to count the number of leading 0s before the conversion then add it in afterwards,['python'] +73869,safari prevent two print dialogs when printing an iframe my site has a print this page buttoni load a static print template html file into a hidden iframe copy the html into that page using jquery and call windowprint from the iframe page all is well except on safari which wants to print the parent frame as well so i get two print dialogs openingi have tried calling windowprint from within the iframe and calling it from the parent targetting the iframe documentprintframewindowprint but i get two dialogs regardlessdoes anyone know a way around this i only want to print the iframe not the parent,"['javascript', 'html']" +73888,get the first letter of each word in a string using objectivec example of what i am trying to dostring this is my sentencei am looking to get this as a result timsi am struggling with objectivec and strings for some reason,['objective-c'] +73893,cannot access data folder in the file explorer of ddms using a nexus one i have my nexus one connected with the usbwhen i visit the file explorer of the ddms if i click on the data folder the little plus near the name data thisappear for 26 seconds and then reappear but the contenct of the folder data is not showedhere some other informationthe folder data has permissions drwxrwxxthe os of my pc is windows xpeclipse v 352android sdk 16,['android'] +73897,performance effect of joining tables from different databases i have a web site using a database named lets say site1 i am planning to put another site on the same server which will also use some of the tables from site1 so should i use three different databases like site1 for first site specific data site2 for second site specific data and general for common tables in which there will be join statements between databases general and site1 and site2 or should i put all tables in one databasewhich is the best practice to do how performances differ in each situationi am using mysql so how is the situation especially for mysqlthanks in advance,['mysql'] +73900,example of using exceptions to control flow what would a piece of code which uses exceptions to control flow look like i have tried to find a direct c example but cannot why is it badthanks,['c#'] +73903,resize android datepicker control how can one resize the initial size of android datepicker control to be smaller or bigger is there only way to reimplement it,['android'] +73909,uitableviewcell swipe for drawer this is really more of a curiosity than a hard coding questionboth facebook and twitter both have a feature where swiping a uitableviewcell animates the cell off the side to reveal a drawer with more controls underneath how is something like that accomplished,['iphone'] +73910,why are the unsigned clr types so difficult to use in c i came from a mostly cc background before i began using c one of the things i did with my first project in c was make a class like thisclass element public uint size public ulong bigthingi was then mortified by the fact that this requires castingint xmyelementsizeas doesint x5uint totalmyelementsizexwhy did the language designers decide to make the signed and unsigned integer types not implicitly castable and why are the unsigned types not used more throughout the net library for instance stringlength can never be negative yet it is a signed integer,"['c#', '.net']" +73927,any way to keep track of the last 5 data points in python so i have an array that holds several numbers as my script runs more and more numbers are appended to this array however i am not interested in all the numbers but just want to keep track of the last 5 numberscurrently i just store all the numbers in the array however this array gets really big and it is full of unnecessary information i have thought about making a function that when it adds an element to the array also removes the last element if the array already contains 5 numbers i also thought about making a new class to create a data structure that does what i want however i only need to reference this array occasionally and is only a small part of the script so i think it is overkill if i create a whole new class to do this what is the best way to do this,['python'] +73935,is main thread the same as ui thread the android doc says like activities and the other components services run in the main thread of the application processis the main thread here the same thing as ui thread,['android'] +73958,gwt 21 celltable column header click events is there any way to add clickhandlers or any type of handler to the headers of the columns in a celltable i want to add some sorting functionality to my celltable and i dont see any methods in the column or header classes that will allow this i used this post to figure out how to use the celltable,['java'] +73960,remotely profiling a jvm i need to remotely profile a jvm for cpu usage io stats and file descriptorhandler count and support both nix and windows platforms while doing so i tried using the sigar api which abstracts the platforms very well using an underlying native code implementation but it does not support remote profiling is there an alternative api which can do this alternatively is it feasible to extend the sigar framework for remote jvm monitoring any hints on where to look at would be helpful thanks in advance,['java'] +73978,javalangruntimeexception error failed to recover corrupt cache entry i just had this error message from one of my users ie8 java 1620 it is from an applet which receives instructions from javascript and executes certain processes on the clientrangeerrorjavalangruntimeexception error failed to recover corrupt cache entryat comsundeploycachecacheentryrecoverat comsundeploycachecacheentrygetsignermapat comsundeploycachecachedjarfilegetsignermapat comsundeploycachecachedjarfileaccess100any iddeas what could be causing this,['java'] +73995,upload max size in php is it possible for the upload of 100 mb files using phpif so what changes need to occur in the configuration file phpinisri,['php'] +73996,sysloadergetresource problem in java i am having following lines of codesysloader urlclassloaderthreadcurrentthreadgetcontextclassloaderurl sysloadergetresourcetempfiletxtit is giving an weird problem if i run this from a path where there is no space in the path folder names then it is running fine but if the path contains any spaces line cnew foler then it is not workinghow to solve thisedit in more detail i inspected the sysloader object sysloader ucp path is having a path with character 20 instead of space and therefore all the urls are null how to resolve this,['java'] +74022,replace and with actual new line character code i am pulling content from a db that has been sanitized using mysql real escape stringaccordingly the new line characters now appear as nthe issue is that this content is thisplayed to users inside a pre tag so i cannot replace and with br for instancei suppose i could replace and with the actual utf8 character code before inserting the result inside the precan somoneone assist here not using mysql real escape string is not really an option due to security policythanks,['php'] +74024,stretching tag to fill entire heres a simple menu structureul idmenu lia hrefjavascripthomeali lia hrefjavascripttestaliuli want the a to be stretched so that it fills the entire li i tried using something like width 100 height 100 but that had no effect how do i stretch the anchor tag correctly,"['html', 'css']" +74025,can i monitor performance of particular table in sql server 2008 profiler i want to monitor all the dml commands that run on a particular table of my database in sql server profiler im using sql server 2008 r2,['sql'] +74026,lifetime of qt objects what are the lifetimes of qt objectssuch asqtcpsocket socketnew qtcpsocketwhen socket will be destroyed should i use delete socketis there any difference withqtcpsocket socketi could not find deep infromation about this any comment or link is welcomed,['c++'] +74031,findviewbyid returns null first of all yes i read all the other threads on this topic and not only those from this site you see i am a little frustratedmost of them come with the advice to use androidid instead of just id in the xml file i didfrom others i learned that viewfindviewbyid works different than activityfindviewbyid i handled that tooin my location layoutxml i useframelayout somepackagemycustomview linearlayout textview androidididtxtlat linearlayoutframelayoutin my activity i dosetcontentview rlayoutlocation layout and in my custom view class textview tv textview findviewbyid ridtxtlat which returns null doing this my activity works fine so maybe it is because of the activityfindviewbyid and viewfindviewbyid differences so i stored the context passed to the customs view constructor locally and triedtextview tv textview activity contextfindviewbyid ridtxtlat which also returned nullthen i changed my custom view to extend viewgroup instead view and changed the location layoutxml to let the textview be a direct child of my custom view so that the viewfindviewbyid should work as supposed suprise it did not solve anythingso what the heck am i doing wrong i will appreciate any comments,['android'] +74052,best way to change widthheight of a widget programmatically possible duplicateandroid how to resize a custom view programmatically whats the best way to change widthheight of a widget i mean a ui widget subclass of androidviewview programmaticallydoing something like this works but it does not seem quite rightviewgrouplayoutparams params msomeviewgetlayoutparamsparamsheight 10msomeviewsetlayoutparamsparams,['android'] +74060,why threadgroup is being criticised i am aware of current practice of using executors instead of threadgroupgenerally preferred way to deal with threadscatching exceptions from threads etchowever what are the inherent flaws of threadgroup as such i have heard a vague criticism for that classthanks for answerps this does not seem to answer this question,['java'] +74072,rails app logging duplicate requests i have a rails app that is generating duplicate requests for every request in development the app is running rails 235 with my primary development machine running ubuntu 104 however the same code runs fine without showing duplicate requests on my os x 106 box it also runs in production mode on either machine without problems processing dashboardcontrollerindex for 127001 at 20100716 102308 get parameters actionindex controllerdashboardrendering template within layoutsapplicationrendering dashboardindex term load 19ms select from date ranges where 20100716 between begin date and end date and date rangestype term staticdata load 11ms select from static data where static dataname esite name limit 1 cache 00ms select from static data where static dataname esite name limit 1rendered dashboard news 01ms cache 00ms select from static data where static dataname esite name limit 1 cache 00ms select from static data where static dataname esite name limit 1 staticdata load 09ms select from static data where static dataname etag line limit 1completed in 67ms view 58 db 5 200 ok httplocalhostdashboard sql 04ms set client min messages to panic sql 04ms set client min messages to noticeprocessing dashboardcontrollerindex for 127001 at 20100716 102308 get parameters actionindex controllerdashboardrendering template within layoutsapplicationrendering dashboardindex term load 19ms select from date ranges where 20100716 between begin date and end date and date rangestype term staticdata load 11ms select from static data where static dataname esite name limit 1 cache 00ms select from static data where static dataname esite name limit 1rendered dashboard news 01ms cache 00ms select from static data where static dataname esite name limit 1 cache 00ms select from static data where static dataname esite name limit 1 staticdata load 09ms select from static data where static dataname etag line limit 1completed in 67ms view 58 db 5 200 ok httplocalhostdashboard sql 04ms set client min messages to panic sql 04ms set client min messages to noticenotice that the requests are exactly the same even down to the timestampsi have tried using ruby 187 191 as well as swapping between mongrel webrick and it always processes each request twice or at least it generates two log entries i tried removing most of the routes to see if i had something weird going on but the problem persists i tried different browsers chrome safari elinks from different machines to see if that would help but the problem persists i removed all of my gems and only replaced the necessary ones but to no availdoes anyone have any idea why rails would cause duplicate requests like this i am about at my wits end and am grasping at straws the only bright spark is that this behavior does not happen under the production environment only development,['ruby-on-rails'] +74077,can iterators be reset in python can i reset an iterator generator in python i am using dictreader and would like to reset it from the csv module to the beginning of the file,['python'] +74084,needed a windows service that executes jobs from a job queue in a db wanted example code neededa windows service that executes jobs from a job queue in a dbwantedexample code guidance or best practices for this type of applicationbackgrounda user will click on an ashx link that will insert a row into the dbi need my windows service to periodically poll for rows in this table and it should execute a unit of work for each rowemphasis this is not completely new terrain for meedit you can assume that i know how to create a windows service and basic data accessbut i need to write this service from scratchand i would just like to know upfront what i need to consideredit i am most worried about jobs that fail contention for jobs and keeping the service running,"['c#', '.net']" +74086,jdbc resultset getdate losing precision i am losing precision in my resultsetgetdatex calls basicallyrs psexecutequeryrsgetdatemodifiedis returning dates truncated to the day where modified is an oracle timestamp field of default precision i think there may be some jdbc tweak i am missing usually timestamp is compatible with date but i am hoping i do not have to redefine the entire table,['java'] +74088,extern struct i am using extern to fetch variables from another class and it works fine for ints floats etcbut this does not work and i do not know how to do itclass1cppstruct mystruct int xmystruct thevarclass2cppextern mystruct thevarvoid test int t thevarxit does not work because class2 does not know what mystruct ishow do i fix this i tried declaring the same struct in class2cpp and it compiled but the values were wrong,['c++'] +74095,jquery tools how to close an overlay arelgetoverlayclosearelcloseboth do not workdocumentreadyfunction areloverlay mask 3b5872 effect apple onbeforeload function var wrap thisgetoverlayfindcontentwrap wraploadthisgettriggerattrhref onload function contentwrap formsubmitfunction event eventpreventdefault areloverlayclose hijackthis update employees html function hijackform callback format ajax url formaction type formmethod datatype format data formserialize success callback function update employeesresult gridcontainerhtmlresult any suggestionsi use chrome because the onload event seems not work correctly in ff,['jquery'] +74114,data from two tables into one view is it possible to grab data from two tables that have the same fields into one view basically so the view sees the data as if it was one table,['sql'] +74164,how to get hwnd of window opened by shellexecuteex hprocess this simple issue seems to be fraught with side issues eg does the new process open multiple windows does it have a splash screen is there a simple way i am starting a new instance of notepadstdtstring tstrnotepad exe tstrprogramfiles tnotepadnotepadexeshellexecuteinfo sei0seicbsize sizeofshellexecuteinfoseifmask see mask nocloseproceseihwnd hwndme this apps window handleseilpverb topenseilpfile tstrnotepad exec str seilpparameters t multiinst noplugins nosession notabbar seilpdirectory nullseinshow sw showseihinstapp null if shellexecuteexsei i have seihprocess but how best to utilize it from here,['c++'] +74202,how does python compare string and int the following snippet is annotated with the output as seen on ideonecomprint 100 2 trueprint 5 9 falseprint 100 2 falseprint 100 2 trueprint 5 9 falseprint 5 9 truecan someone explain why the output is as suchimplementation detailsis this behavior mandated by the language spec or is it up to implementorsare there differences between any of the major python implementationsare there differences between versions of the python language,['python'] +74206,find the intersection between line and grid in a fast manner is there anyway that allows me to find all the intersection points between a line and a grid the intersection circles are not drawn to scale with each other i knowa brute force way is to compute very intersection for the xy grid with the line but this algorithm is awfully inefficient omn where m is the number of x grid and n is the number of y gridi am looking for a better algorithm on this,['c#'] +74222,how to create a new map with constructor i am wanting to do two thingscreate a private instance variable which is a mapto create an empty instance in my constructor that impliments a map and assigns it to the previous private instance variablethe private instance i have isprivate final mapcharacter sortedsetstring thesaurus new hashmap character sortedsetstringbut how would create an instance variable in the constructor that would reference the private variable thesaurus upon the constructors creationfor example public class book private final mapcharacter sortedsetstring thesaurus new hashmap character sortedsetstringpublic book super what do i put here as an empty instance variable that implements a map and how do i assign it to thesaurus,['java'] +74225,how to thisable autoload in jqgrid how to thisable autoload in jqgrid and load data manually when i need itthanks,['javascript'] +74230,can i install python windows packages into virtualenvs virtualenv is great it lets me keep a number of thistinct python installations so that different projects dependencies are not all thrown together into a common pilebut if i want to install a package on windows that is packaged as a exe installer how can i direct it to install into the virtualenv for example i have pycuda094rcwin32py26exe when i run it it examines the registry and finds only one python26 to install into the common one that my virtualenv is based off ofhow can i direct it to install into the virtualenv,['python'] +74233,how to add where clause to query on android i would like to limit the results to those whose key homeid is equal to journalidi have been on this for a couple days any help would be appreciatedpublic cursor fetchallnotesstring journalid return mdbquerydatabase table new string key rowid key height key body key homeidfrom database table where key homeid journalidnull null null nullnull,['android'] +74242,how to use logical or in sparql regex i am using this line in a sparql query in my python programfilter regexname s i where s is the search text entered by the useri want this to match if either name or featurename contains s but i cannot seem to find any documentation or tutorial for using regex i tried a couple things that seemed reasonablefilter regexname featurename s i filter regexname featurename s i filter regexname or featurename s i filter regexname featurename s i and each of those without the filter regexname s i regexfeaturename s i whats the right way to do thisthanksupdate using union works but i figured out that it also works if you just repeat the regex part like sofilter regexname s i regexfeaturename s i both solutions seem a little messy in that you have to use a 2element tuple with copies of the same string to fill in both ss,['python'] +74251,android exception did you forget to call public void setup localactivitymanager activitygroup mycodepublic class mainactivity extends activity override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain final tabhost tabhost tabhost findviewbyidridtabhost localactivitymanager mlocalactivitymanager new localactivitymanagerthis false tabhostsetup tabspec tabspeccheckin tabhostnewtabspecgetresourcesgettextrstringbutton check intostring tabspeccheckinsetindicatorgetresourcesgettextrstringbutton check intostring getresourcesgetdrawableandroidrdrawablestar off tabspeccheckinsetcontentridcheck in tabhostaddtabtabspeccheckin tabspec tabspecreview tabhostnewtabspecgetresourcesgettextrstringbutton reviewtostring tabspecreviewsetindicatorgetresourcesgettextrstringbutton reviewtostring getresourcesgetdrawableandroidrdrawablestar off tabspecreviewsetcontentridreview tabhostaddtabtabspecreview tabspec tabspecmycircles tabhostnewtabspecgetresourcesgettextrstringbutton my circlestostring tabspecmycirclessetindicatorgetresourcesgettextrstringbutton my circlestostring getresourcesgetdrawableandroidrdrawablestar off tabspecmycirclessetcontentridmy circle tabhostaddtabtabspecmycircles tabspec tabspecmysettings tabhostnewtabspecgetresourcesgettextrstringbutton settingstostring tabspecmysettingssetindicatorgetresourcesgettextrstringbutton settingstostring getresourcesgetdrawableandroidrdrawablestar off tabspecmysettingssetcontentnew intentthischeckinactivityclass tabhostaddtabtabspecmysettings tabhostsetcurrenttab0 xmlxml version10 encodingutf8linearlayout xmlnsandroid androidorientationvertical androidlayout widthfill parent androidlayout heightfill parent tabhost androidididtabhost androidlayout widthfill parent androidlayout heightfill parent tabwidget androidlayout widthfill parent androidlayout heightwrap content androididandroididtabs androidlayout gravitybottom framelayout androididandroididtabcontent androidlayout widthfill parent androidlayout heightfill parent androidpaddingtop65px linearlayout androidididcheck in androidorientationvertical androidlayout widthfill parent androidlayout heightfill parent androidpadding5px textview androidlayout widthwrap content androidlayout heightwrap content androidtextdate androidtextstylebold linearlayout linearlayout androidididreview androidorientationvertical androidlayout widthfill parent androidlayout heightfill parent androidpadding5px textview androidlayout widthwrap content androidlayout heightwrap content androidtextlieu androidtextstylebold linearlayout linearlayout androidididmy circle androidorientationvertical androidlayout widthfill parent androidlayout heightfill parent androidpadding5px linearlayout linearlayout androidididsetting androidorientationvertical androidlayout widthfill parent androidlayout heightfill parent androidpadding5px linearlayout framelayout tabhostlinearlayoutwhen i click the button of setting exctptiondid you forget to call public void setup localactivitymanager activitygroupwho can help me i try to extends from tabactiviy or activitygroup still other exceptionsi want to put the buttons of tabhost at bottom and when i click the button invoke different activities,['android'] +74256,how do i switch out views in a cocoa application so i am beginning to learn how to use cocoa i think i have pretty much got it but i am hung up on creating and switching views i am rewriting a game i made a little bit ago for practice all i want is one window preferably not resizable and i want to be able to switch out views for different screens in the gamefirst i have the main menu start game high scores exit then i need a window for each screen gameplay screen highscore screen what i am getting confused with is how to design this i looked up nsviewcontroller thinking it manages views but it does not it only manages one view by loading it really i do not understand why i would need to use nsviewcontroller then could not i just have a window class that contains multiple subclasses of nsview and load them like that i am not sure i understand the purpose of the viewcontrollerdoes my window class really need to subclass nswindowcontroller i was trying to follow the example of apples viewcontroller example and it has a window controller class that is a subclass of nswindowcontroller i do not see what the purpose was of subclassing that all nswindowcontroller seems to add is initwithpathnsstring newpath but i fail to see the use in that either when i can just edit the plist file to open the window on start up apples example also has an nsview variable and an nsviewcontroller variable do not you only need one variable to store the current viewthanks in advance guys i am really confused as to how this works,['objective-c'] +74271,entity framework v4 preventing storage model overwrites by update model wizard in my entity framework v4 project i have a table with two columns that are computed by the database via triggers etc in order to get ef to properly insert records into the table i have to manually mark the columns as computed in the ef storage model the storegeneratedpattern attribute which is not supported by the designer so i have to make the edits by hand to the xml in the edmx filethe problem is that whenever my database schema changes and i need to update the storage model in my project the update model wizard overwrites the whole storage model section of the edmx eliminating my manual changes this means that i have to keep a special list of such changes and manually reapply them every time i do an update for the love of god this has got to be one of the dumbest glitches in efanyway my question for the hive is this is there any way to prevent the storage model overwrites is there a way to flag the columns in the database so that ef will automatically mark them as computed as a last resort is the some really easy xml tooltechnique that can automatically apply the changes for me after every refreshthank you oh learned stackoverflow contributors for easing my pain and helping me with this problem even though i do not yet have any status on the site someday when i have a 4 digit reputation i will remember youbrianupdatei have been told by an insider that one solution might be to check out the designer power pack link below which allows you to customize generation of the storage model i have only skimmed the info so far but it looks to me like there may be a day or two learning curve to figure that out does anyone have any experience with the designer power pack or any other ideasthanks againbrian,"['.net', 'asp.net', 'sql']" +74273,javascript closures variable scope question i am reading the mozilla developers site on closures and i noticed in their example for common mistakes they had this codep idhelphelpful notes will appear herep pemail input typetext idemail nameemailp pname input typetext idname namenamep page input typetext idage nameagep andfunction showhelphelp documentgetelementbyidhelpinnerhtml helpfunction setuphelp var helptext id email help your email address id name help your full name id age help your age you must be over 16 for var i 0 i helptextlength i var item helptexti documentgetelementbyiditemidonfocus function showhelpitemhelp and they said that for the onfocus event the code would only show help for the last item because all of the anonymous functions assigned to the onfocus event have a closure around the item variable which makes sense because in javascript variables do not have block scope the solution was to use let item instead for then it has block scopehowever what i wonder is why could not you declare var item right above the for loop then it has the scope of setuphelp and each iteration you are assigning it a different value which would then be captured as its current value in the closure right,['javascript'] +74274,javascript windowstatus hi this is my first attempt at javascriptthe following function is used to thisplay window status bar messages it works fine on the local machine but when i upload it too the server the messages are not thisplayed at allwhat am i doing wrong please helpwebsitelink removedfunction thisplaymsgmsgwindowstatus msgwhat should happen is when you hover over the image it should thisplay a message to click it and the image is then updatedi saw this but if this is no longer possible then why does it work locallyedit thank you for your answer i am wondering if it is possible to thisplay a tooltip once the image over event happens thanksedit i have added a title attribute and it seems to thisplay a tooltip what you are seeing would be most welcome input thanksedit google chrome works fine safari does not run javascript im on win7,['javascript'] +74275,jquerys click pass parameters to user function i am trying to call a function with parameters using jquerys click but i cannot get it to workthis is how i want it to workleadtoscoreclickadd eventshotwhich callsfunction add eventevent blah blah blah it works if i do not use parameters like thisleadtoscoreclickadd eventfunction add event blah blah blah but i need to be able to pass a parameter through to my add event functionhow can i do this specific thingi know i can use clickfunction blah but i call the add event function from multiple places and want to do it this way,['jquery'] +74277,a boot loader in c i have messed around a few times by making a small assembly boot loader on a floppy thisk and was wondering if it is possible to make a boot loader in c and if so where might i begin for all i know im not sure it would even use int mainthanks for any help,['c++'] +74294,how do i force matplotlib to write out the full form of the xaxis label avoiding scientific notation i have created a simple hexbin plot with matplotlibpyplot i have not changed any default settings my xaxis information ranges from 2003 to 2009 while the y values range from 15 to 35 rather than writing out 2003 2004 etc matplotlib collapses it into 0 1 2 2003e03 is there a simple way to force matplotlib to write out the full numbersthanksmark c,['python'] +74297,whats the best way to create a javascript namespace i have not yet found a common way on the internet for creating a namespace in javascriptwhats the best way to create a namespace and please list any downfalls that particular approach might have,['javascript'] +74316,javahl not loading noclassdeferror i have reinstalled windows and unzipped a fresh copy of eclipse despite this i have been unable access an ssh repository via subclipse the issue seems to be with javahl and the tests from the tigris web site give noclassdeferror although this could be considered as a software issue i hope someone has come accross this before is there a way to fix this it is quite urgentps things were set up such that subclipse would look in the config file to forward a call to the plink client of tortoisesvn which in turn gets a key that is loaded in pageantedit heres the output from java jar javahltestsjar now after reinstalling a jdke a fatal error has been detected by the java runtime environment exception access violation 0xc05 at pc0xffbadd11 pid752 tid656 jre version 60 21b06 java vm java hotspottm client vm 170b16 mixed mode sharing windowsx86 problematic frame c 0xffbadd11 an error report file with more information is saved as chs err pid752log if you would like to submit a bug report please visit the crash happened outside the java virtual machine in native code see problematic frame for where to report the bugand heres the output i had previouslyetime 0047there were 50 errors1 testcreateorgtigrissubversionjavahlsvnadmintestsjavalangunsatisfiedlinkerror no svnjavahl1 in javalibrarypath at javalangclassloaderloadlibraryunknown source at javalangruntimeloadlibrary0unknown source at javalangsystemloadlibraryunknown source at orgtigrissubversionjavahlnativeresourcesloadnativelibrarynativeresourcesjava79 at orgtigrissubversionjavahlsvnadminclinitsvnadminjava32 at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava12 testsetrevproporgtigrissubversionjavahlsvnadmintestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava13 testlogdateorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava14 testversionorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava15 testpathvalidationorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava16 testpathisurlorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava17 testmergeinfoparserorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava18 testbasicstatusorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava19 testoodstatusorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava10 testbasiccheckoutorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava1 testbasiccommitorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava12 testbasicpropertiesorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava13 testbasicupdateorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava14 testbasicmkdirurlorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava15 testcopyorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava16 testmoveorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava17 testbasicmergingupdateorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava18 testbasicconflictorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava19 testbasiccleanuporgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava120 testbasicrevertorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava121 testbasicswitchorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava122 testbasicdeleteorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava123 testbasiccheckoutdeletedorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava124 testbasicnodekindchangeorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava125 testbasicimportorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava126 testbasiccatorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava127 testbasiccatstreamorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava128 testbasiclsorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava129 testbasicaddignoresorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava130 testbasicimportignoresorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava131 testbasicinfoorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava132 testbasiclogmessageorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava133 testbasicversioninfoorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava134 testbasiclockingorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava135 testbasicinfo2orgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava136 testbasicchangelistorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava137 testbasicmergeorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava138 testmergeusinghistoryorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava139 testmergereintegrateorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava140 testmergeconflictresolutionorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava141 testrecordonlymergeorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava142 testdifforgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava143 testdiffsummarizeorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava144 testbasicisadmindirectoryorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava145 testbasiccanceloperationorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava146 testdatatransferprogressreportorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava147 testtreeconflictorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava148 testobstructiontoleranceorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava149 testbasicblameorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava150 testcommitrevpropsorgtigrissubversionjavahlbasictestsjavalangnoclassdeffounderror could not initialize class orgtigrissubversionjavahlsvnadmin at orgtigrissubversionjavahlsvntestssetupsvntestsjava218 at orgtigrissubversionjavahlruntestsmainruntestsjava1failurestests run 50 failures 0 errors 50finally heres what i get in the eclipse idefailed to load javahl librarythese are the errors that were encounteredfeclipse helioseclipsejeehelioswin32eclipsepluginsorgtigrissubversionclientadapterjavahlwin32 1612libsvnjavahl1dll cannot find dependent librariesno svnjavahl1 in javalibrarypathno svnjavahl in javalibrarypathjavalibrarypath feclipse helioseclipsejeehelioswin32eclipseplugins,['java'] +74318,rounded corners for using borderradiushtc for ie i want to create an input fields with rounded corners htmldiv idrightcolumninput typetext classinputform divcssinputform mozborderradius10px firefox webkitborderradius 10px safari chrome khtmlborderradius 10px khtml borderradius 10px css3 behaviorurlborderradiushtcrightcolumn backgroundcolorwhitebut ie does not show any borders for input fields neighter rounded nor simple borderswhen i remove cstyle for rightcolumn ie shows an input fields with rounded cornersbut i need background for rightcolumnhow can i create it,['css'] +74319,saving a c struct with a char string into a file i am trying to save a struct with a char string into a file struct d object int flags int time int offset char filenamethe problem is that when doing that i will obviously only save the address of that pointer rather than the string so what i have done is simply use a character array and but i am forced to set the maximum size of the string this works fine however i was wondering if there is anyway of storing the struct with a char that i malloc at some point in a file and then retrieve it i can save the string and the struct separate and then retrieve them but it is quite a mess it would be preferable if i could load and save the entire struct the one above into the file thanksthe code with the char array is belowinclude stdiohinclude stringhinclude fcntlhstruct d object int flags int time int offset char filename255int mainint argc char argv struct d object fcb fcbflags5 fcbtime10 fcboffset220 strncpyfcbfilenamemyfile255 int fdopentestfileo rdwr writefdfcbsizeoffcb closefd int fd2 opentestfileo rdonly struct d object new fcb readfd2new fcbsizeofnew fcb printfread from file testfile snnew fcbfilename return 0ps i am not using the stream functions simply because this is actually meant to be run on an embedded os that does not have them i have just adapted the code for bsdlinux so it makes more sense when asking the question,['c'] +74320,how can i find out when a pinch gesture is finished uigesturerecognizer i want to get a callback when my uipinchgesturerecognizer finished a pinchgesture moreover it would be great to know if the finished gesture was a zoom in or a zoom outdoes anyone know a method to use or the approach to dothanks,['iphone'] +74324,c background worker i have a task running in backgroundworker on clicking the start button user starts the process and have got one cancel button to cancel the processing when user clicks on cancel i would like to show a message box that process has not been completed do you want to continue here i want the processing which is left to be done only after user input till then want to halt the back ground thread can anyone help me on this is there anyway to halt the background worker for some time any kind of help will be appreciated,['c#'] +74331,i am having problems understanding iqueryable so i am trying to understand iqueryablet a tutorial i am reading suggests using it but not really sure why the code simply returns some values using linq to sql i have done this plenty of times in the past but not using iqueryabletwhy use it with my functions that return more than 1 valueheres my codepublic iqueryableitems getitems return from item in dbitems where itemisactive true orderby itemitemnumber select item,"['c#', 'asp.net']" +74346,set a div height equal with of another div i have two divs sidebar and content and i want to set sidebar to keep the same height with the contenti have tried the followingsidebarcssheightcontentheightpxsidebarheightcontentheightvar highestcol mathmaxsidebarheightcontentheightsidebarheighthighestcolnone of these are working for the content i do not have any height since will increase or decrease based on the contentplease help me i have to finish up a web page today and this simple thing is giving me headachesthank you,['jquery'] +74350,how can i use the python htmlparser library to extract data from a specific div tag i am trying to get a value out of a html page using the python htmlparser library the value i want to get hold of is within this html elementdiv idremository20divthis is my htmlparser class so farclass linksparserhtmlparserhtmlparser def init self htmlparserhtmlparser init self selfseen def handle starttagself tag attributes if tag div return for name value in attributes if name id and value remository print value return def handle dataself data print datap linksparserf urlliburlopenhtml freadpfeedhtmlpclosecan someone point me in the right direction i want the class functionality to get the value 20,"['python', 'html']" +74351,rails 3 validation on uniqueness on multiple attributes i use rails 300beta4i want to add a validation on uniqueness on two attributes that means that my model is valid if the couple of recorded at and zipcode is uniqueon one attribute here is the syntaxvalidates zipcode uniqueness truethanks,['ruby-on-rails'] +74353,extracting date from a string in python how can i extract the date from a string like monkey 20100710 love banana thanks,['python'] +74359,android wordwrap edittext text i have been trying to get my edittext box to word wrap but cannot seem to do iti have dealt with much more complicated issues while developing android applications and this seems like it should be a straightforward processhowever the issue remains and i have a large text box that is only allowing me to enter text on one line continuing straight across scrolling horizontally as i enter texthere is the xml code for the edittext object from my layout filexml version10 encodingutf8linearlayout androidididmywidget48 androidlayout widthfill parent androidlayout heightwrap content androidorientationvertical xmlnsandroid scrollview androidididmyscrollview androidlayout widthfill parent androidlayout heightwrap content androidlayout weight1 linearlayout androidididwidget37 androidlayout widthfill parent androidlayout heightwrap content androidorientationvertical edittext androidididtxtnotes androidlayout width300px androidlayout height120px androidscrollbarsvertical androidtextsize18sp androidgravityleft androidlayout margintop10dip androidinputtypetextcapsentences edittextlinearlayoutscrollviewlinearlayout,['android'] +74363,what is the clojure equivalent of a public static final constant in java i am writing some clojure code that depends upon a number of constantsthey will be used within tight inner loops so it is important that they will be used and optimised as efficiently as possible by the clojure compilerjvm combination i would normally used a public static final constant in java for the same purposewhat is the best way to declare these,['java'] +74366,how to work with dynamically created fields i have web layout which can contains several links on it those links are dynamically created using ajax functions and it works okbut i do not know how can i work with those dynamically created links ie how to call some js or jquery function if i click on them i guess that browser can not recognize them since there are created after page is loadedis there some function that can rerender my page and elements on ittnx in adv on your help,"['javascript', 'jquery']" +74371,mysql foreign key question does defining a foreign key also defines a index i have mysql v5146 i am looking at the mysql administrator tool and its shows the foreign key as an index so i wanted to confirm,"['sql', 'mysql']" +74373,rvm does not switch rubies i am running ruby 191p243 on centos and i decided to install rvm to handle upgrading to 192 or downgrading to 187 whichever turns out to work better for rails3i followed the instructions here and everything installed correctly i was able to compile and install ruby 187 191 and 192however if i try to actually switch to one of the rvm installed rubies with rvm use 187 for example nothing works my system still uses the ruby i have installed in usrlocalbinrubyan example of the output i get rvm use 187 ruby vruby 191p243 20090716 revision 24175 i686linux which rubyusrlocalbinruby rvm use 192 ruby vruby 191p243 20090716 revision 24175 i686linux which rubyusrlocalbinrubyi have no idea why this is happening and i cannot seem to find anything online about the issue either any help would be appreciated,['ruby'] +74384,how to check whether ckeditor has some text in it i have an html form with a few fields one of them is a textarea managed by ckeditor when the user wants to submit the form i want to check whether he entered values in all the fields i know how i can check if ckeditor control has anything in it but it could be empty html tags without any text in it how do i check for textserver side i am using something like phps trimstrip tagscontent so i would like to have the same in javascript a solution using jquery would also be usable,['javascript'] +74389,sql server lack of natural join x join y usingfield i have just been reading up on natural join using sql92 features which are sadly missing from sql servers current repertoirehas anyone come from a dbms that supported these to sql server or another nonsupporting dbms were they as useful as they sound or a can of worms which also sounds possible,['sql'] +74410,uiimage implementing an auto levels algorithm i would like to implement an auto levels option for a uiimage that i am thisplaying in my iphone app before i try to implement it myself i was wondering if there are any image processing methods in the apis i should be using for histograms etc or should i just grab the underlying cgimage and process it i am new to iphone devthanksmv,['iphone'] +74420,optional parameter in sql server i have a user defined function which is used in many stored procedures which will return me some value if it possible for me to add a new optional parameter to the sameif i do not pass any value it should be null and if i pass some value it should take it i do not want to go and change all the stored procedures to do soexample codedbocalculateaverageforuseruserid intcan i use dbocalculateaverageforuseruserid int type nvarchar10 null,['sql'] +74421,standalone fabfile for fabric is it possible to make the fabfile standalonei am not very fond of running the external tool fab if i manage to get the fabfile standalone i can run the file from within the eclipse pydev ide easily debug it use project configurations and paths etcwhy does not this workfrom fabricapi import rundef host type rununame sif name main host type,['python'] +74423,httpservletrequest setcharacterencoding seems to do nothing i am trying to read utf8 info from the requesti used requestsetcharacterencodingutf8 but it seems to do nothing the info read is non utf8what am i doing wrong,['java'] +74442,pure wbxml encoding for php is there a native php wbxml api that can be used platformindependently perhaps a loadable modulei have seen the pecl implementations but i have not been able to successfully work with the builds on win32 platforms,['php'] +74445,invert colormap in matplotlib i would like to know how to simply reverse the color order of a given colormap in order to use it with plot surface,['python'] +74448,understanding code what is the best way to get acquainted with c codebase of approximate size 200k loc are there any tools available it seems there is an event going for a long time for this purposethanks,['c#'] +74465,why does not delete destroy anything i am playing a little with memory dynamic allocation but i do not get a point when allocating some memory with the new statement i am supposed to be able to destroy the memory the pointer points to using deletebut when i try this delete command does not seem to work since the space the pointer is pointing at does not seem to have been emptiedlet us take this truly basic piece of code as an exampleinclude iostream using namespace stdint main i create a pointertointeger ptest make it point to some new space and fulfill this free space with a number int ptest ptest new int ptest 3 cout ptest endl things are working well so far let us destroy this dynamically allocated space delete ptest ok now i guess the data ptest pointed to has been destroyed cout ptest endl oh well i was mistaking return 0 any clue,['c++'] +74482,jqueryjavascript reload current page with an appended querystring i have got a dropdown menu on my form which when something is selected i need to reload the current page but with an appended querystringhow would i go about doing this,"['javascript', 'jquery']" +74483,semantics and structure of namevalue pairs this is a question i have been struggling with for a while what is the proper way to mark up namevalue pairsi am fond of the dl element but it presents a problem there is no way to separate one pair from another they have no unique container visually the code lacks definition semantically though i think this is the correct markupdl dtnamedt ddvaluedd dtnamedt ddvaluedlin the above code it is difficult to properly offset the pairs visually both in code and rendered if i wanted to for instance but a border around each pair that would be a problemwe may point to tables it could be argued that namevalue pairs are tabular data that seems incorrect to me but i see the argument however the html does not differentiate the name from the value except in position or with the addition of class namestable tr tdnametd tdvaluetd tr tr tdnametd tdvaluetd trtablethis makes much more sense from a visual standpoint both in code and in css styling the aforementioned border is trivial however as mentioned above the semantics are fuzzy at bestthoughts comments questionseditupdateperhaps this was something i should have explicitly mentioned in relation to structure but a definition list also has the problem of not semantically grouping the pairs the ordering and implicit border between a dd and a dt is easily understood but they still feel slightly off to me,"['html', 'css']" +74486,moving projects files in a net project it is not coderelated but ide related i am working on a net solution with about 35 different projects these projects need to be reorganized into a new folder structure why because about 10 of those will be removed and the rest will be divided in more logical unitsone way to do this is by creating a new solution dragdrop the projects into a new folder tree within the windows explorer and then just add them to the new solutionto be honest that sounds dumbis there a way to just move projects into different folders from within the ide i have tried to save as the projects but the ide would not accept a different folderit is irritating but because there have been a few wrong choices in folder names i am now stuck with those namesexample right now i have a project main folder which contains child folders named client server business database and whatever more within those child folders there are more child folders each a threedigit number within each numbered folder there is a project which is named in some logical way like companybusinesscustomers with additional logic within this projectthe problem is that not all projects now follow this naming convention and i consider it obsoletea project like companybusinesscustomers should just be in a folder named companybusinesscustomers in the project root so it is easier to recognize the name already makes it clear that it is a business class for this project the clear division within client classes business classes and whatever more just needs to be arranged within the solution but i want to flatten the file structure and remove some obsolete projects basically i am not refactoring i am just cleaning upvs2008 does not seem to have such an option though,['c#'] +74506,tableviewcontroller does not flash scroll indicators even if the table is bigger that the view i have got a weird problem with a tableviewcontrollerin the doc it says that a tableviewcontroller deals also with the method flashscrollindicators when the table is oversized respect the visible areamy app consists in 3 nav controller loaded in a tab controller each nav controller has as root view controller a subclass of a table view controllereach model is populated from a plist file that loads its contents into an array in the viewdidload later everything is passed to the table everything is loaded programmatically no ibi have found out in my app that when it loads the first view a nav controller with a table view controller as root the scroll bar is not flashing even if the number of cell it is great enoughif i choose another tab that loads another nav controller with a tvc as root scroll bar is not shown again when i press the tab corresponding to the first nav controller loaded the scrollbar flashesso i have tried to make it flash programmatically but no way the code seems simpleselftableview flashscrollindicatorsi have tried to put it almost everywhere first in the viewdidload as suggested in the doc then in viewdidappear and in viewwillappearalso tried use that code tring to cast the view of the tvc as a table viewuitableviewselfview flashscrollindicatorswithout resulti have started looking at apple sample and i have found that in apples table view custom sample the one with different times scroll bar does not flash also theretested both on sim and deviceis a bug is there a correct way to show it programmaticallycan someone help meregardsandrea,['iphone'] +74508,jquery how to get value of file upload input field is it possible to determine if the user has selected a file for a particular input typefile field using javascriptjqueryi have developed a custom fieldtype for expressionengine phpbased cms that lets users upload and store their files on amazon s3 but the most popular ee hosting service has set a max file uploads limit of 20 i would like to allow the user to upload 20 files edit the entry again to add 20 more etc unfortunately upon editing the entry the initial 20 files have a replace this image file input field that appears to be knocking out the possibility of uploading new images i would like to remove any unused file input fields via javascript when the form is submitted,"['php', 'javascript', 'jquery']" +74515,add floating point value to android resourcesvalues i am trying to add a little space between lines to my textviews using androidlinespacingmultiplierfrom the documentationextra spacing between lines of text as a multiplier must be a floating point value such as 12as i am using this in a few different textviews i would like to add a global dimensionvalue to my resources but i do not know which tag to use if it even existsi have tried all resource types that make sense to me but none of them workswhat i would like to have would be something like thisresources dimen nametext line spacing14dimenresourcesedit i am aware of androidlinespacingextra which needs a dimension with an appended unit but i would like to use androidlinespacingmultiplier if possible,['android'] +74523,microsofthttphttpclient sending http authentication parameters properly on redirects i am making a request to a 3rd party restful service using microsofts httpclient it works flawlessly and is very easy to implement except for this one instance here is a breakdown from the provider as to what is occurring during the error the way the post to the group resource works is that when it completes it does a http 302 redirect to the group instance resource what appears to be happening is that your http client is sending the proper authentication information to the post which creates the group resource but when it handles the get for the http 302 request it is not sending the right credentials and is getting a 401 response can you check your client library and make sure its sending http auth parameters properly on redirectshere is my post codehttpclient http new httpclientbase urlhttptransportsettingscredentials new networkcredentialaccount sid account tokenhttpresponsemessage httpresponse httppostgroupuri applicationxml httpcontentcreatexmltostringresult httpresponsecontentreadasstringwhich brings me to my question how do i get the authentication parameters to send on this get redirect using the httpclient class,"['c#', '.net']" +74535,set color of textview span in android is it possible to set the color of just span of text in a textviewi would like to do something similar to the twitter app in which a part of the text is blue see image below,['android'] +74536,database design guidance needed a dairy farmer who is also a parttime cartoonist has several herds of cows he has assigned each cow to a particular herd in each herd the farmer has one cow that is his favorite often that cow is featured in a cartoon a few malcontents in each herd mainly those who feel they should have appeared in the cartoon thisagree with the farmers choice of a favorite cow whom they thisparagingly refer to as the sacred cow as a result each herd now has elected a herd leaderthis is what i think the tables should look like can you let me know if it can be done better so far i am doing a many to many using the favorite table as the intermediate is this the best possible solution also no sql statements are needed this is just for design purposesthank you in advancetable herd table favorite table cartoon table cowpk herdid intermediate table pk cartoonid pk cowid herdname cartoontitle cowname herdleader cartoontype cartoondateedited image 301pmest is this correctadded new image 857am 7202010 can some one critique this erd pleaseadded new image 1247pm 7202010 unless there is any objections this is the final draft per marks explanation,['sql'] +74546,assert that a webelement is not present using selenium webdriver with java in tests that i write if i want to assert a webelement is present on the page i can do a simpledriverfindelementbylinktexttest searchthis will pass if it exists and it will bomb out if it does not exist but now i want to assert that a link does not exist i am unclear how to do this since the code above does not return a booleanedit this is how i came up with my own fix i am wondering if there is a better way out there stillpublic static void assertlinknotpresent webdriver driver string text throws exception listwebelement bob driverfindelementsbylinktexttext if bobisempty false throw new exception text link is present,['java'] +74549,fetch an email with imaplib but do not mark it as seen i want to parse some emails from a user s inbox but when i dotyp msg data imap connfetchuid rfc822it marks the email as seen or read this is not the desired functionality do you know how can i keep the email at its previous stare either seen or not seen,['python'] +74552,convert month from name to number is there an easy way to change month july so that nmonth 7 07 would be fine tooi could do a case statement but surely there is already a function to convertediti wish i could accept multiple answers cause two of you basically gave me what i needed by your powers combinednmonth datemstrtotimemonththat will give the numerical value for monththanks,['php'] +74563,using mysql with entity framework 4 and the codefirst development ctp i thought i would experiment a bit with scott guthries latest post on codefirst dev with entity framework 4 instead of using sql server i am trying to use mysql here are the relevant parts of my webconfig this is an aspnet mvc 2 appconnectionstrings add namenerddinners connectionstringserverlocalhost databasenerddinners uidroot pwd providernamemysqldatamysqlclient connectionstrings systemdata dbproviderfactories add namemysql data provider invariantmysqldatamysqlclient descriptionnet framework data provider for mysql typemysqldatamysqlclientmysqlclientfactory mysqldata version6230 cultureneutral publickeytokenc5687fc88969c44d dbproviderfactories systemdatajust like the tutorial i am expecting ef4 to generate the db for me automatically instead it throws a providerincompatibleexception with an inner exception complaining that the nerddinners database does not exist fair enough i went and created the mysql db for it just to see if things would work and got another providerincompatibleexception instead this time databaseexists is not supported by the provideri will admit this is the first time i am really delving into entity framework i have stuck mostly to linq to sql and this is all running on the codefirst ctp released only last week that said is there something i am doing wrong here or a known problem that can be worked around,['mysql'] +74572,compare two arrays or arraylists find similar and different values i have two arrays or arraylists if it is easier of strings i need to compare these find which only exist in the first array which exist in both and which only exist in the second array these arrays are different lengths and may be in different orders if necessary i suppose i could sort themi know i could hack this together but i think this might have a fairly standard and efficient best solution and i am curious more than anythingi am using c for this but if you want to write your solution in another language any help is welcomethanks for the help,['c#'] +74573,oauth storing access token and secret we have a number of clients that use our api to power their websites i have started a conversation at work about using oauth to make authenticated api callswe will have both two and three legged flowsfor the 3legged flow we still have not come to a consensus on how to store the access token and secret the common approach to this problem would be to have the clients store the access token and secret in their own db but that is out of the question as the clients do not want to deal with code changes and implementation issuesthe other options we are considering 1 saving the access token and secret in a cookie2 saving them in the sessioni am not sure whether either of these is a good idea does anyone have any suggestionsthank you,['php'] +74579,embed a console window inside a wpf window is it possible to embed a console window inside a wpf windowas a little background at first i tried to implement a console window from scratch in wpf which was successful except for one huge problem its extremely slow see the question heresince that does not seem to be an option i am instead looking at hosting an actual console window in my wpf application which i have learned how to do as described hereand that is great by ideally i would like to have that console window look like it is a part of the rest of the wpf application i know it is possible with a winforms app as i have seen it done involving using the setparent win32 api you can see an example net project that does it with this commandbar project that embeds a console window into the shellso i am hopeful it can be done with wpf as well but i have no idea how youd do that help is much appreciated also if you have any brilliant solutions to my original problem of creating a terminal window from scratch in wpf since that would solve my needs tooupdate with help reed copseys help i was able to get the console window embedded however of course it needed to be styled and moved or else it just looked like a regular console window inside a wpf window i need the title bar and large borders removed doing research i figured out how to use the win32 apis to do that like thisuint style getwindowlongconsolemanagerconsolewindowhandle gwl stylestyle uintwindowstylesws captionstyle uintwindowstylesws thickframestyle uintwindowstylesws dlgframestyle uintwindowstylesws popupsetwindowlongconsolemanagerconsolewindowhandle gwl style stylemovewindowconsolemanagerconsolewindowhandle 0 0 intwindowsformshostactualwidth intwindowsformshostactualheight truehowever there is one big problem for some reason the console window has a rendering artifact it is as if it is not repainting itself on the bottom left and top right sides the width of the artifact is similar to the width of the title bar and the thick border and in fact if i leave the thick border in the size of the artifact goes down but simply repainting it would not help since it reappears i can for example move the window off the screen and back again to fix it but it soon reappears on its own update 2 the effect happens even if i do not parent it into the windowsformshost control all i need to do to reproduce it is launch the console using allocconsole and then remove it is title bar with setwindowlong this is a win7 machineupdate 3 it seems messing with other windows like this is not supported the console window calculates its textarea assuming there is a caption so there is no way around this i think my only option to get consolelike behavior in wpf is going to be to write a custom winforms control and then embed that into wpf,['.net'] +74580,returning an objects subclass with generics with an abstract class i want to define a method that returns this for the subclassespublic abstract class foo public t extends foo t eatstring eatcake return this public class cakeeater extends foo i want to be able to do things likecakeeater phil new cakeeaterphileatwacky cakeeatchocolate cakeeatbanana breadarguably banana bread would throw an illegalargumentexception with the message not a cake,['java'] +74584,aspxdesignercs how does it work i am a really beginner so my question may be appear ridiculous but i wonder how the files aspxdesignercs worksit is the first time i work with a solution containing files aspxdesignercs for each pages so i understand it is declaration of controls used in the aspx for codebehindhere is my questionswhy sometimes solutions doent have aspxdesignercs files is the files hidden or does not existsi often have problems with this files they do not automatically recreate declarations of controls when i add some in the aspx code what am i doing wrong,['asp.net'] +74603,how to periodically scan for bluetooth devices on android hi this may sound as a stupid questionbut i was unable to find any answers for this thus posting herei am building an indoor application which continuously scans the bluetooth dongles located at different locations in a place like a mall or libraryas i move in the mall with android phone in my hand i should be able to get the nearest dongle which i can connect tostupid idea but i want to do something else with thisfor this i should be able to continuously scan for the bluetooth devicesplease can someone tell me how do i make android scan the available bluetooth devices periodically,['android'] +74604,what is the jquery equivalent to documentforms0elementsivalue what is the jquery equivalent to documentforms0elementsivaluei do not know how to travel through a form and its elements in jquery and would like to know how to do it,"['javascript', 'jquery']" +74612,dynamically generate css file from database in aspnet mvc i am looking to add some basic theme support to my web application with users being able to customise various parts of the look these include things like colours text sizes fonts other basic things i will be storing these in the database and loading them each time a page is accessedmy question is how do i go about generating a dynamic css file based upon these database values i would prefer to do something that is cacheable but extensible so that if i want to add more editable styles then it wouldnt be a bit issue,['css'] +74652,how to gettype of list in c possible duplicate how can i get generic type from a string representationhow can i get the type of liststring in c using typegettypei have already tried typegettypeliststring typegettypesystemcollectionsgenericliststring or stringnote that i cannot use typeof since the value i am getting the type of is a string,['c#'] +74654,there are any guides on implementing an inapp tutorial for iphone do you know some resource url pdf etc that can help me to do an inapp tutoriallet me explain better the first time that the user uses my iphone app i want to put bubble messages pointingdescribing each part of the interfacethe problem is that i do not know where to start dany help will be appreciated thanks in advance,"['iphone', 'objective-c']" +74657,are web services truly stateless its a well know fact that webservices are stateless its written in every text that deals with wcf basics but i need to know are they truely statelessi was reading about the percall wcf webservice which destroy the service instance for every call i am not able to comprehend the use of percall service if webservices are stateless then what is the need of destroying service instance for each call,['.net'] +74696,how to use jqueryvalidate plugin in cakephp form my jquery code isdocumentreadyfunction studentregisterformvalidate rules email requiredtrue emailtrue and in my form emailtdphp echo forminputemailarrayclass required email tdthe problem is jquery validate plugin works on the input fields attribute name but cakephp names it as datastudentemail if i use this name in jquery its throwing an error if i rename the field in cakephp the email value is not passed to the database is there any other round about way,['jquery'] +74699,eclipse system property i need to set the value of a system property javalibrarypath to csomepath i know that i need to add this in the vm args section could some please provide the actual syntax,['java'] +74703,cannot add a reference to systemweb to my windows service aplication i am trying to create a windows service in vs2010 but cannot seem to add systemweb as reference when i browse for it and add it manually i get an exclamation mark over the reference i have tried adding it for other projects and it works fine just not for a windows service project is there a reason for this i need it to call systemwebhttputilityurlencode is there alternative method i can usethanks in advancechristo,['.net'] +74710,maximum level of recursion in python whats the maximum level of recursion and how do i change it in python,['python'] +74711,why was iequatable t not made contravariant in t for c 40 iequatablet could have been declared to be contravariant in t since it only uses t in an input position or equivalently you being a subtype of t should imply that iequatablet is a subtype of iequatableuso why did the bcl team not annotate it for c 40 with the in keyword as they did with many other generic interfaces like the entirely analogous icomparable,['c#'] +74717,java object id in jvm there is an object id is thisplayed near the object value in eclipse while debuggingfor example 28332 is an id of session objectthis id is neither a hash code nor a systemidentityhashcodedoes anybody knows how to get this id of object,['java'] +74722,my android app is damaging sd cards i released an app on the android market that i have since had to take down because approximately half of the comments were people complaining of damaged sd cards i have gone over the code a few times and cannot find anything that could damage an sd card all that happens that involves external storage is the saving of streams as images which then get read into imageviewsthis is what is called in the root activity to create the folders the directory paths are stored in public static variablesget the sd card directory string external environmentgetexternalstoragedirectorygetabsolutepath appfolder cache directory external cache saved directory external saved file cache new filecache directory file saved new filesaved directory cachemkdirs savedmkdirsand the following is the code for downloading images and copying them for when they are being moved to the saved directorypublic static void saveimagefile file url url throws ioexception bufferedinputstream bis new bufferedinputstreamurlopenstream bufferedoutputstream bos new bufferedoutputstreamnew fileoutputstreamfile int bytes while bytes bisread 1 boswritebytes bosclose bisclosepublic static void copyfile filein file fileout throws ioexception bufferedinputstream bin new bufferedinputstreamnew fileinputstreamfilein bufferedoutputstream bout new bufferedoutputstreamnew fileoutputstreamfileout int bytes while bytes binread 1 boutwritebytes binclose boutcloseand this is a background thread for network iopublic void run for string url thumbnails if url null string urlparts urlsplit string imagename urlpartsurlpartslength 1 file file new filemaincache directory imagename if fileexists filelength 0 try imagesaveimagefile new urlurl catch ioexception e actxrunonuithreadreload where reload is a runnable to update an adapter thumbnails is an array of string urls and image name is a unique 1011 digit number with an image extension jpeg png gif specificallyand this is similar code run in the background of an asynctaskstring imageurl stringparams0 string imageurlparts imageurlsplit string imagename imageurlpartsimageurlpartslength 1 url fullimageurl try fullimageurl new urlimageurl catch malformedurlexception me canceltrue return null file file new filemaincache directory imagename try urlconnection ucon fullimageurlopenconnection int requestedsize ucongetcontentlength long filesize filelength either the file does not exist or it exists but was cancelled early due to user or ioexception so it needs to be redownloaded if fileexists fileexists filesize requestedsize 08 mloadsetmaxrequestedsize bufferedinputstream bis new bufferedinputstreamucongetinputstream bufferedoutputstream bout new bufferedoutputstreamnew fileoutputstreamfile int bytes int count 0 while bytes bisread 1 boutwritebytes count updates in increments of 2kb if count 2048 0 publishprogresscount bisclose boutclose if save file savefile new filemainsaved directory imagename copyfile savefile catch ioexception e canceltrue return null catch outofmemoryerror e canceltrue return null the only instance i could find of damaged sd cards is the app is built on android 16 and the bug is not recreatable via emulator or personal testing on 21update1 with htc desireedit i have looked at some other questions and could the problems be arising from me not flushing the buffered output streams is that a big deal,['android'] +74729,how to report progress from within a class to a backgroundworker my winform calls a class which performs some copying actions i would like to show the progress of this on a formi would like to use the backgroundworker but i do not know how to report progress from the class to the form backgroundworker,['c#'] +74732,getting an image object from a byte array i have got a byte array for an image stored in the database i want to create an image object create several images of different sizes and store them back in the database save it back to a byte arrayi am not worried about the database part or the resizing but is there an easy way to load an image object without saving the file to the file system and then put it back in a byte array when i am done resizing it i would like to do it all in memory if i cansomething likeimage myimage new imagebyteormyimageloadbyte,['.net'] +74742,super fuzzy name checking i am working on some stuff for an inhouse crm the companys current frontend allows for lots of duplicates i am trying to stop endusers from putting in the same person because they searched for bill johnson and not william johnson so the user will put in some information about their new customer and well find the similar names including fuzzy names and match them against what is already in our database and ask if they meant those things does such a database or technology exist,"['c#', 'javascript', 'asp.net']" +74764,is order of items read from a xdocument by linq guaranteed so what i am doing is using an xml document to determine the order in which certain sql scripts need to be ran by a database updatethe xml follows this formatscriptrules database databasename astringa folder folderpath astringa executeallfiles boolean file orderafirst or lastaafilenameafile folder databasescriptrulesso the class that executes all of the sql files on the database looks at this at changes it is connection and executes files from folders depending on what the config file has told it to donow my question is thislet us say that i have a document that has 4 database nodes and each of them have n number of folder nodes inside with an assortment of file nodes inside of thatis it logical of me to assume that if inside of a for each loop over the database nodes that i have retrieved into a xelement using databaseelementsdatabase that they will be pulled in the order that they appear in the xml file same for the file nodesas far as i have been able to tell this is the case but i just wanted to verify before i start using this on production databases,['.net'] +74775,common class for asynctask in android i have a common class say for eg class a which extends asynctask and has all the methods implemented ie onpreexecute doinbackground and onpostexecutenow there are other classes which want to use class a objectsay class b uses class a in the below mannera a new acontextaexecuteurlthen i fetch the result in get method but get method is not the proper way of using asynctask i will like to get the result in onpostexecute for that i tried using a boolean parameter which will get true only in onpostexecute the class b will check till it gets true and when it gets true it will fetch the resultbut this is somehow blocking the applicationi have placed the code for asynctask belowimport javaioioexceptionimport orgapachehttpclientclientprotocolexceptionimport orgapachehttpclienthttpclientimport orgapachehttpclientresponsehandlerimport orgapachehttpclientmethodshttpgetimport orgapachehttpimplclientbasicresponsehandlerimport orgapachehttpimplclientdefaulthttpclientimport androidaprogressdialogimport androidcontentcontextimport androidosasynctaskpublic class a extends asynctaskstring void string private context context nullprivate final httpclient httpclient new defaulthttpclientprivate string content nullprivate string error nullprivate string finalresult nullprivate static boolean isresult falseprivate progressdialog progressdialog null public babblevillesynctaskcontext context thiscontext context progressdialog new progressdialogthiscontextprotected void onpreexecute progressdialogsetmessageplease wait progressdialogshowprotected string doinbackgroundstring urls try urls0 urlencoderencodeurls0 utf8 httpget httpget new httpgeturls0 responsehandlerstring responsehandler new basicresponsehandler content httpclientexecutehttpget responsehandler catchunsupportedencodingexception ue error uegetmessage catch clientprotocolexception e error egetmessage canceltrue catch ioexception e error egetmessage canceltrue httpclientgetconnectionmanagershutdown return contentprotected void onpostexecutestring result finalresult result progressdialogthismiss systemoutprintlnon post execute called isresult true public boolean getisresult return isresultpublic void setisresultboolean flag isresult flagpublic string getresult return finalresultcan someone let me know what the issue may beregardssunil,['android'] +74784,jquery syntax when to use dollar vs jquery whats difference between this twospanidhtmlsome textjqueryspanidhtmlsome textis it something prototype vs jquery,['jquery'] +74791,c generic serialization utility class i have an existing class for serializing and deserializing objects tofrom xml it is a generic class with a single type parameter t whose only constraint is where t ixmlserializable however i want to still be able to use this class on classes that do not implement ixmlserializable but have the serializable attribute how could i go about doing thisfrom my generic classpublic static class xmlserializationutilst where t ixmlserializable public static t deserializexmlxmldocument xml public static xmldocument serializetoxmlt toserialize i found this thiscussion but there was no solution given just that i cannot do where t serializable trying to do where t serializableattribute makes visual studio say cannot use sealed class systemserializableattribute as type parameter constraintedit based on stephens answer i removed the constraints on xmlserializationutilst and added this static constructorstatic xmlserializationutils type type typeoft bool hasattribute null attributegetcustomattributetype typeofserializableattribute bool implementsinterface null typegetinterfacetypeofixmlserializablefullname if hasattribute implementsinterface throw new argumentexception cannot use xmlserializationutils on class typename because it does not have the serializable attribute and it does not implement ixmlserializable,['c#'] +74793,how to make sure a website is suitable for all screen resolutions just spent several hours writing up for a new site looks great in my resolution 1366x768 however even going down to 1024x768 means that not everything fits inside the screen widthtried style typetextcss body width100stylethis does have some effect on my resolution but no effect on smaller resolutionshow can i make sure my webpage will fit 100 in all screen resolutions,"['html', 'css']" +74794,equivalent of phps crypt function in java i am migrating my php code to google app engine javaso i need an equivalent of phps crypt function in javasince i have stored all the passwords of registered usersusing crypt in my db edit 1 here is my php code for encrypting passwords password test123pwd cryptpasswordpasswordecho pwd output is on windows as well as a linux based server on hostmonsertemjccsjbecmu can someone give me equivalted java codei have tried various permutations combinations withmessagedigest class but cannot get it right edit 2here is sample code which i thought would work but did not try string password test123 messagedigest digest messagedigestgetinstance md5 byte passwordbytes passwordgetbytes digestreset digestupdate passwordbytes digestupdate passwordbytes byte message digestdigest stringbuffer hexstring new stringbuffer for int i0 i messagelength i hexstringappend integertohexstring 0xff message i string encrypted hexstringtostring systemoutprintlnencrypted catch nosuchalgorithmexception e1 todo autogenerated catch block e1printstacktrace,"['java', 'php']" +74815,android how to put an enum in a bundle how do you add an enum object to an android bundle,['android'] +74822,union all geometry in a sql server table like geomunion in postgres just to clarify upfront i am talking about unioning geometry not the sql keyword unioni am trying to move some spatial data from postgres with postgis to sql server 2008 it was fine until i saw a statement like thisselect geomunionthe geom from some tablethis unions all geometry in that column and return it as one result similar to how count works as far i know sql server only has the stunion function which unions one geometry with another is there any way to do something similar to the postgres wayif it helps the stunion function works like thisselect first geometry columnstunionsecond geometry column from some table,['sql'] +74824,what is the meaning of the terms normal flow and out of flow in terms of html css and browser what is the meaning of the terms normal flow and out of flow in terms of html css and browser,"['html', 'css']" +74826,access cancans can method from a model you can get the current users permissions from a view or controller using can in this fashion if can update article link to edit edit article patharticle end how can i access this functionality from a model using this syntaxusercanupdate article,['ruby-on-rails'] +74830,multiple replaces with javascript in php you do this to replace more then one value at a timephpstring i am the foobarnewstring str replacearrayi the arrayyou a stringecho newstringhow do you do this in javascript,['javascript'] +74832,hide scrollbar while still able to scroll with mousekeyboard possible duplicatehow to thisable browser or element scrollbar but allow scrolling with wheel or arrow keys i want to know if it is possible to hide the scrollbar while scrolling is still enabled with mousekeyboard i tried to use css overflow hiddenthe effect is scrollbar thisabled and scrolling thisabled,"['javascript', 'jquery', 'html', 'css']" +74842,a way to find the size and location of padding in a struct i am trying to write a tool that will take as input some c code containing structs it will compile the code then find and output the size and offset of any padding the compiler decides to add to structs within it this is pretty straightforward to do by hand for a known struct using offsetof sizeof and some addition but i cannot figure out an easy way to do it automatically for any input struct if i knew how to iterate through all elements in a struct i think i could get the tool written with no problems but as far as i know there is no way to do that i am hoping some stackoverflow people will know a way however i am not stuck in my approach and i am certainly open to any alternate approaches to finding padding in a struct,['c'] +74846,how to differentiate between iphone4 and iphone 3 i am trying to build a game for the iphone using cocos2d engine i wanted to know how can i tell a difference whether the user is using iphone 4 or iphone 3 as i wanted to load hiresolution graphics for the iphone4 and lowresolution for iphone 3 i know if i use 2xpng at the end of the image file name uiimage loads the hiresolution image by itself if i am using an iphone 4 but for the game i am using cocos2d engines ccsprite class to load the graphics i would really appreciate the replyregardsankur,['ios'] +74848,linear gradient brush fade wpf i have a brush that colors the background of a header i like the way the brush looks but would like it to fade to transparent in the bottom third any ideas how to do thislineargradientbrush xkeyheaderbackgroundbrush endpoint51 startpoint10 gradientstop color006699 offset1 gradientstop color80a8cc offset05lineargradientbrush,['c#'] +74855,set the absolute position of a view is it possible to set the absolute position of a view in android i know that there is an absolutelayout but it is deprecatedfor example if i have a 240x320px screen how could i add an imageview which is 20x20px such that its center is at the position 100100,['android'] +74867,nodejs would not return data to jquerygetjson i have set up nodejs and it is returning data when i browse to the url however when i try to call that url using getjson the callback shows null for the data variable and success for the textstatus variablei imagine this could be a crossdomain thing but i am surprised that the textstatus says success if that is the casein case it is helpful heres the serverside jshttpcreateserverfunctionreq res var output message hello world var body jsonstringifyoutput reswritehead200 contenttype applicationjson contentlength bodylength resendbodylisten80 184106206235any ideas,['jquery'] +74869,retrieving value of edittexts in alertdialog builder using layout using the following code snippets i am trying to get the text value which has been typed in to the edittextslayoutinflater factory layoutinflaterfromthisfinal view loginview factoryinflaterlayoutlogin nullbsetonclicklistenernew onclicklistener public void onclickview v dialog d new alertdialogbuilderneworderthis seticonrdrawableicon settitlelog in setviewloginview setpositivebuttonlog in new dialoginterfaceonclicklistener public void onclickdialoginterface dialog int whichbutton mspinner progressdialogshowmcontext authenticating user new logintaskexecute setnegativebuttoncancel new dialoginterfaceonclicklistener public void onclickdialoginterface dialog int whichbutton user clicked cancel so do some stuff create dshow my loginxml is pretty standard and straight forwardxml version10 encodingutf8linearlayout xmlnsandroid androidlayout widthfill parent androidlayout heightwrap content androidorientationvertical textview androidididusername view androidlayout heightwrap content androidlayout widthwrap content androidlayout marginleft20dip androidlayout marginright20dip androidtextemail address androidgravityleft androidtextappearanceandroidattrtextappearancemedium edittext androidididusername androidlayout heightwrap content androidlayout widthfill parent androidlayout marginleft20dip androidlayout marginright20dip androidscrollhorizontallytrue androidautotextfalse androidcapitalizenone androidgravityfill horizontal androidtextappearanceandroidattrtextappearancemedium textview androidididpassword view androidlayout heightwrap content androidlayout widthwrap content androidlayout marginleft20dip androidlayout marginright20dip androidtextpassword androidgravityleft androidtextappearanceandroidattrtextappearancemedium edittext androidididpassword androidlayout heightwrap content androidlayout widthfill parent androidlayout marginleft20dip androidlayout marginright20dip androidscrollhorizontallytrue androidautotextfalse androidcapitalizenone androidgravityfill horizontal androidpasswordtrue androidtextappearanceandroidattrtextappearancemedium linearlayoutwhen someone clicks the positivebutton how do i get the value of the edittext fields,['android'] +74872,overriding tkinter x button control the button that close the window when the user presses a close button that i created some tasks are performed before exiting however if the user clicks on the x button in the topright of the window to close the window i cannot perform these tasks how can i override what happens when the user clicks x button,['python'] +74882,developing a private iphone tethering app recently an app was released on the appstore that secretly allowed wifitethering from your iphone it quickly got pulled by apple out of curiosity are there any libraries for the iphone sdk that helps developers write an application that does the same thing i am assuming you can deploy the app to your iphone for testing purposes without publishing to the appstore is that correctupdatei found this link as i was writing the question so it looks like deploying the app to your own iphone is not a problem as long as you have a developer certificate so my only question then is regarding any libraries or code examples that can help with this tetheringproxy solution,"['objective-c', 'iphone']" +74890,why are not my sqlite3 foreign keys working i run the following code from a python interpreter and expect the insert statement to fail and throw some kind of exception but it is not happeningpython 265 r26579096 mar 19 2010 214826 msc v1500 32 bit intel on win32type help copyright credits or license for more information import sqlite3 conn sqlite3connecttestdb connexecutescript pragma foreign keyson begin transaction create table t1 i integer primary key a create table t2 i a foreign key i references t1i commit sqlite3cursor object at 0x0229daa0 c conncursor cexecuteinsert into t2 values 6 8sqlite3cursor object at 0x0229dad0 conncommit cexecuteselect from t2sqlite3cursor object at 0x0229dad0 cfetchall6 8 but whydoes anyone know why this does not want to work my understanding is that the insert should fail since the value i gave for t2i is not a primary key in t1 but it happily does it anyway,['python'] +74893,draw horizontal divider in winforms in the standard windows installer there is a divider between the control buttons on the bottom and the main part of the form does anyone know how this would be done in winformsnet i have tried fiddling around with the border settings on panel controls etc but have not been able to get the same result,['.net'] +74911,how do i transfer an image from its url to the sd card how can i save an images to the sd card that i retrieve from the images url,['android'] +74918,bundle install fail while install rspec i am trying to install rspecrails on ubuntu but i am encountering some problemshere are my exact steps1 changed my gemfile tosource gem rails 300beta4gem sqlite3ruby 125 require sqlite3group development do gem rspecrails 200beta17endgroup test do gem rspec 200beta17end2 type bundle install and i get the following errorusrlibruby18fileutilsrb243in mkdir permission denied homestevegemspecs errnoeacces3 if i continue with my installation instructions and type rails generate rspecinstalli get the following error but it might have been caused by 2 failingcould not find gem rspec 200beta17 runtime in the gems available on this machinei was unable to find a solution for this on google this is the link to the tutorial i am trying to follow my dev enviroment is ubuntu 1004 ruby 187 rails 300 beta 4thanks,['ruby-on-rails'] +74954,c generic type is boxed i executed the following codeusing systemusing systemcollectionsgenericnamespace testreleaseanddebug public class gclasst1 t2 public t1 name get set public t2 age get set public void thisplay consolewritelinename name consolewritelineage age class program static void mainstring args gclastring int person new gclastring int personname ram personage 34 string name ram int age 34 consolewritelinename name consolewritelineage age personthisplay consoleread i am having two local variables in the main function they are name and age i am printing them using consolewriteline method it prints without any problem the il of the main method is as shown belowmethod private hidebysig static void mainstring args cil managed entrypoint code size 90 0x5a maxstack 2 locals init 0 class testreleaseanddebuggclass2stringint32 person 1 string name 2 int32 age il 0 nop il 01 newobj instance void class testreleaseanddebuggclass2stringint32ctor il 06 stloc0 il 07 ldloc0 il 08 ldstr ram il 0d callvirt instance void class testreleaseanddebuggclass2stringint32set name0 il 0012 nop il 0013 ldloc0 il 0014 ldci4s 34 il 0016 callvirt instance void class testreleaseanddebuggclass2stringint32set age1 il 001b nop il 001c ldstr ram il 0021 stloc1 il 0022 ldci4s 34 il 0024 stloc2 il 0025 ldstr name il 002a ldloc1 il 002b call string mscorlibsystemstringconcatstring string il 0030 call void mscorlibsystemconsolewritelinestring il 0035 nop il 0036 ldstr age il 003b ldloc2 il 003c box mscorlibsystemint32 il 0041 call string mscorlibsystemstringconcatobject object il 0046 call void mscorlibsystemconsolewritelinestring il 004b nop il 004c ldloc0 il 004d callvirt instance void class testreleaseanddebuggclass2stringint32thisplay il 0052 nop il 0053 call int32 mscorlibsystemconsoleread il 0058 pop il 0059 ret end of method programmaini have another generic class gclass in the generic class i have two properties and one method thisplay in the thisplay method i thisplay the two properties the same way i thisplayed the local variables in the main method the il of the generic class thisplay method is given belowmethod public hidebysig instance void thisplay cil managed code size 56 0x38 maxstack 8 il 0 nop il 01 ldstr name il 06 ldarg0 il 07 call instance 0 class testreleaseanddebuggclass2t1t2get name il 0c box t1 il 0011 call string mscorlibsystemstringconcatobject object il 0016 call void mscorlibsystemconsolewritelinestring il 001b nop il 001c ldstr age il 0021 ldarg0 il 0022 call instance 1 class testreleaseanddebuggclass2t1t2get age il 0027 box t2 il 002c call string mscorlibsystemstringconcatobject object il 0031 call void mscorlibsystemconsolewritelinestring il 0036 nop il 0037 ret end of method gclass2thisplayi am passing string as the type parameter to t1 and using this type to declare name property when the name property is thisplayed using consolewriteline it is boxing the name il 0c box t1 you can find this in il why boxing happens eventhough it is a string type,"['c#', '.net']" +74958,how to create synthetic fields in java how can synthetic fields be created in java can synthetic fields in java only be created at runtimeif not is there a standardcompliant way to this at compile time without changing some bytes in the class file,['java'] +74966,android alpha animation fadein fadeout with delays i want to do a very simple alpha animation but i cannot find a valid waythe idea is to perform this animation over a viewalpha from 0 to 1 of 1 secondhold alpha at 1 for 5 secondsalpha from 1 to 0 of 1 secondhold alpha at 0 for 5 secondsstart again on 1i have tried to implement that with an animationset asanimationset animationset new animationsettrueanimation animation1 new animationutilsloadanimationthis androidranimfade inanimation1setduration10animation animation2 new animationutilsloadanimationthis androidranimfade outanimation2setduration10animation2setstartoffset50animation animation3 new alphaanimation00f 00fanimation3setduration40animation3setstartoffset60animationsetaddanimation1animationsetaddanimation2animationsetaddanimation3etcbut it seams that the third animation do a mess with all the alpha animations i supose that this cause an internal incoherence in the way that android manage this type of animationany ideathank you,['android'] +74970,unique identifier for html elements besides of the id if you say you want a unique identifier for an html element let say a divi browsed the dom for something like a number or string that is unique for each element but the dom is big and i failed to find that in the internetis there any property in the dom obviously that is unique only to that element other than the id and also you do not specify it but comes when the dom is constructed,"['javascript', 'html']" +74974,reading aspnet text box value with javascript i am using a aspnet35 page and i have a text box called txtnamei want to read the value with javascript like so but it does not workvar name documentgetelementbyidtxtnamevaluealertnameeven this does not want to workvar name documentformnametxtnamevaluealertnamethis work with plain html pages but not with my aspnet page why,"['javascript', 'asp.net']" +74975,is it possible to scan for wifi using python i am interested in writing a script in python that is able to scan and show a list of nearby wifi networks how could one do this if possiblethanksjake,['python'] +74978,css position absolute screen resolution problem css codetop45left98floatrightpositionabsolutezindex2i have done the above coding for a floating div when i was working on 1024 resolution but when i tested the same on a different resolution it is out of alignmenthow can we fix it,"['html', 'css']" +74993,jquery datatables change value of a cell not just thisplay value using datatables i want to change the value of the data before rendering the table i used thisfnrowcallback function nrow adata ithisplayindex if adata2 0 tdeq1 nrowhtml b6b but i found that although i changed the thisplayed text to be 0 to 6 when i sort by the column it is still sorting by the data and not the thisplayed text does anyone know how i can actually change the data in the cell so that when i sort it will correctly sort by 06,['jquery'] +74994,sql is it possible to group by according to like functions results i am using oracle sql and i want to group some different rows that like function results to elaborate with an examplelet us assume i have a table mesa with one of the columns is a huge string and i am counting the number of rows matching particular patternsselect mstr countfrom mesa mwhere mstr like fruitand mstr like apple or mstr like orangeso let us assume the result of this query isfruitafsafafasfared apple 20fruitafsafafasfayellow apple 12fruitafsafafasfagreen apple 3fruitafsafafasfapurple orange 4fruitafsafafasfared orange 45but i want my results to beapple 35orange 49is this possible to do if so how so comments and code snippets are much appreciatedps of course the query and the results are more complicated than the above example i just wrote it like for the sake of simplicity to explaincheers,['sql'] +75014,looking to design a tool to translate business logic from stored procedures to c business layer without getting into a thiscussion about whether the business logic should be in the database or at the application layer since it has been covered elsewheremy team is translating 100k lines of plsql code and moving the logic from the database into the application we were using vb6 with straight calls to oracle 9i stored procedures and adhoc queries and are now using c net 35 winforms with nhibernate to an oracle 9i databasewe have already found a wonderful tool to assist in converting the adhoc queries smartcode but it only creates code based on tables and views we are looking for a tool to assist in converting the stored proceduresthe stored procedures have most of the business logic in them that we want to migrate to the application layer we are wondering if there are any tools to convert the stored procedures into c code assuming there are none what would be the best place to start if we develop the tool inhouseopen source is there another similar system with similar goals that could be used as a starting placeaccepted answer updatei have selected scopecreeps answer because it appears to be the best method for implementing the issue presented in the question for those that deal with this same issue i heartedly recommend adams response as he has strongly advocated against the use of a tool and provides a strong rationale he has also provided the most interaction with this question and had the most upvoted responsethank you to everyone for your help and dialog,['c#'] +75017,vs 2010 configuration transformation produces unwanted white space during deployment i use the new vs 2010 configuration transformations to deploy websites to replace a single setting of my applicationsettings i use the following configuration transformationsetting nametemppath serializeasstring xdttransformreplace xdtlocatormatchname valuectempvaluesettingremark there is no white space between ctemp and the end tagthis transformation results in a setting with unwanted white space like thissetting nametemppath serializeasstring valuectemp valuesettingif i use this setting without trimming it i get faulty behaviourany idea,['asp.net'] +75022,filter list contained in entity returned by jpahibernate query i have a simple jpa entity applicationform with a one to many list in it onetomanycascadecascadetyperemove mappedbytextquestion private listdictionary questionsthe variable dictionary contained in applicationform is just another plain entity with just the text of the question the corresponding database table mapped by dictionary islocale text formiden my question 123 it mia domanda 123i was wondering if it is possible with jpa or hibernate to build a query for retrieving an applicationform entity with a dictionary for a specific locale for example it onlythat would be easy enough to do with standard sql but i cannot translate in hqlif not possible could you suggest an alternative way i have tried to manually iterate the dictionary questions list and remove the not required locale but is not really elegant and also i got a jpahibernate errori hope i made myself clear and code supplied is enoughthanks,['java'] +75023,cast to int vs floor is there any difference between thesefloat foo1 intbar 30float foo2 floorbar 30as i understand both cases have the same result is there any difference in the compiled code,"['c++', 'c']" +75029,webdriver file upload is there a way to interact with a file upload box in webdriver the form field where the path gets put in is read only so i cannot write to that,['c#'] +75032,how do i center an image if it is wider than its container normally you center images with thisplay block margin auto but if the image is larger than the container it overflows to the right how do i make it overflow to the both sides equally the width of the container is fixed and known the width of the image is unknown,['css'] +75034,does reflection breaks the idea of private methods because private methods can be access outside of the class does reflection break the idea of private methods because private methods can be accessed from outside of the class maybe i do not understand the meaning of reflection or miss something else please tell me 28computer science29editif relection breaks the idea of private methods do we use private methods only for program logic and not for program securitythanks,"['c#', 'java', 'php']" +75067,using throw in a catchblock and nothing else possible duplicatedifference between throw and throw new exception i am a programmer working on adding new functionality to legacy code while debugging i parsed over this catch block which got an angry object not set to reference of object notice from visual studiocatchexception ex sporeloglogfailed to create new saveddocumentlist with name name ex throw what does it mean to throw i am familiar with throw new exceptiontype but what does it mean to just throw is this good practice or should i alter this code to ease the trials of the developers after meand why does visual studio yell at me for doing this,['c#'] +75071,event not bubbling in some browsers when clicked on flash environmentwindows 7internet explorer 8flash activex 1015364wmodetransparentjust wrote a small test page that you can load in ie and firefox or any other browserdoctype html public w3cdtd xhtml 10 transitionalen html xmlns head titleevent bubbling testtitle head body onclickalertbody stylemargin0borderwidth0padding0backgroundcolor00ff00 div onclickalertdiv stylemargin0borderwidth0padding0backgroundcolorff0 span onclickalertspan stylemargin0borderwidth0padding0backgroundcolor0ff object classidclsidd27cdb6eae6d11cf96b84553540 codebase width159 height91 idflashabout small alignabsmiddle param namemovie value info smallswf param namequality valuehigh param namebgcolor valuef param namewmode valuetransparent embed src info smallswf qualityhigh bgcolorf width159 height91 wmodetransparent nameflashabout small alignabsmiddle typeapplicationxshockwaveflash pluginspage object span div bodyhtmlso clicking any colored shape should produce an alert except for the green one in ie not sure why but i hope that is off topic and not related to my issueclicking the flash container in firefox will work perfectly fine you should get alert boxes in this order containing span div and body flash bubbles the event to the html but this is not happening in ieso why is flash in ie not bubbling events to htmledit as mentioned by andy e this behavior can also bee seen in google chrome which to my knowledge is not using activex to embed the flash movie into the page,"['javascript', 'html']" +75073,how to use visual studio for wordpress development does anyone use visual studio to do wordpress development if so how do you do it,['php'] +75076,learn ejb 30 really fast i am in an urgent need to put myself up to speed with ejb 30 like in a couple of days or so please do not aski have some years behind me as a programmer and worked with different technologies rmi jndi ejb 1 ejb 2 hibernate etc so i am not a stranger to all of this but that was some time agoi need a tutorial not your friendly 800 pages book that will introduce me into all the features of ejb 3 as fast as possible maybe provide like a features reference or somethingdoes something like this existthank you,['java'] +75090,celery get task id for current task how can i get the task id value for a task from within the task heres my codefrom celerydecorators import taskfrom djangocorecache import cachetaskdef do jobpath performs an operation on a file code to perform the operation cachesetcurrent task id operation resultsthe idea is that when i create a new instance of the task i retrieve the task id from the task object i then use the task id to determine whether the task has completed i do not want to keep track of the task by the path value because the file is cleaned up after the task completes and may or may not existin the above example how would i get the value of current task id,['python'] +75095,how to fail the build when there is new uncovered code do any code coverage tools for java allow you to cause the build to fail when new uncovered code gets introduced i do not want to fail the build based on an arbitrary cutoff like 80 because in a large codebase the actual coverage percentage rarely fluctuates also if coverage falls by 01 it is hard to tell which are the new uncovered linesediti am convinced not to fail the build the other part of the question still stands how can i find only the uncovered code that was recently checked in,['java'] +75105,what is the prototype equivalent of jquerys elementtext given the following snippetdiv idmydiv this is my text spanwith a spanspandiv jquery can get the interior string with mydivtextis there a more intuitive way in prototype than mydivpluckinnerhtmlfirststriptags,"['javascript', 'jquery']" +75119,regex to remove all special characters from string i am completely incapable of regular expressions and so i need some help with a problem that i think would best be solved by using regular expressionsi have list of strings in cliststring lstnames new liststringlstnamesaddtra9423lstnamesaddtra42101lstnamesaddtra109adforeach string and in lstnames logic goes here that somehow uses regex to remove all special characters string regexp no idea string tmp regexreplacen regexp i need to be able to loop over the list and return each item without any special characters for example item one would be tra9423 item two would be tra42101 and item three would be tra109ad is there a regular expression that can accomplish this for mealso the list contains more than 40 items so i need the search and replace to be efficient and quick if possiblethanks in advance for any help that i receive on thiseditsorry i should have specified that any character beside az az and 09 is special in my circumstance,['c#'] +75123,use my own main loop in twisted i have an existing program that has its own main loop and does computations based on input it receives let us say from the user to make it simple i want to now do the computations remotely instead of locally and i decided to implement the rpcs in twisted ideally i just want to change one of my functions say docomputation to make a call to twisted to perform the rpc get the results and return the rest of the program should stay the same how can i accomplish this though twisted hijacks the main loop when i call reactorrun i also read that you do not really have threads in twisted that all the tasks run in sequence so it seems i cannot just create a loopingcall and run my main loop that way,['python'] +75126,volatile variables as argument to function having this codetypedef volatile int count count functionone count number int functiontwo int number i cannot get rid of some warningsi get this warning 1 at functionone prototypewarning type qualifiers ignored on function return typeand i get this warning 2 wherever i call functiontwo with a count pointer argument instead of an int pointerwarning cast thiscards qualifiers from pointer target typeobviously variablespointers cannot be cast to volatileunvolatile but every arguments must be specified as volatile too so how can i use any library function if it is already defined for nonvolatile variable edit using gcc stdc99 pedantic wall wshadow wpointerarith wcastqual wextra wstrictprototypes wmissingprototypes aedit after jukka suomela advice this is a code sample for warning twotypedef volatile int count static int functiontwoint number return number 1int mainvoid count count 10 count functiontwocount return 0,['c'] +75136,php strtotime function wrong by 1 hour i am converting dates and times into timestamps using php before they are inserted into my mysql databasemy problem is that when i use phps strtotime function the output timestamp is 1 hour behind my actual timefor example considering todays date 07212010 when i use php code likephpmy timestamp strtotime07212010echo my timestampthe timestamp sent back is the gmt equivilent minus 1 hour ie i get back 20 jul 2010 230 gmt instead of 21 jul 2010 0 gmti live in the uk so my timezone is gmt i have declared my timezone in the script using date default timezone seteuropelondon and i have also ensured that the phpini file is set to europelondonis this something to do with daylight savings time perhaps how can i fix the problem without adding 1 hour to all my dates,"['php', 'mysql']" +75143,is there a way to make the generated gui code from idea visible i have made an extremely simple project in intellijs idea basically just a form with a jtoolbar containing a jbutton and when i try to launch it i get an npe in formsetupui but no such thing is reflected in the actual formjava so i have no way to debug it or track down the bugis there a way to make idea show and maybe even let me change the magically generated code,['java'] +75153,present modal view controller i am just getting started with iphone developmenti have a tabbed application and i wanted to thisplay a log in form modallyso i looked here apple dev and did this inside one of my view controllersi connected a button to the following action import loginformhibactionshowloginloginform lf loginform allocinitwithnibnameloginform bundlenillfdelegate selflfmodalpresentationstyle uimodaltransitionstylecrossthissolveself presentmodalviewcontrollerlf animatedyeswhen i build i get request for member delegate in something not a structure or unionif i get rid of the second line it builds but pressing the button does nothingwhat am i missing here,"['iphone', 'objective-c']" +75157,using an iframe in a div kills rest of page if i put a simple iframe within a div any divs below it do not show up the page stops there if i just type some text with no iframe it works fineaso it is the adding of the iframe that causes itthe file loaded by the iframe is dummied right down and just thisplays the word testbefore i start posting a lot of code and stuff is this generally an issueacan an iframe be used within a div statementthanks,['html'] +75158,iphoneipad webview example where can i find a simple compilable example on how to create and use a uiwebviewany noninterface builder examples,"['objective-c', 'iphone']" +75160,net exception logging monitoring whats the best way to monitor exception logging in production environment i have an application where in exceptions are logged to a text file everytime i need access to these log files i got to request backoffice team to send me a copyto improvise this process i have thought of few options1 email the error logs on a regular basis2 store the log file in database3 create some sort of listener objects to monitor logs is this even possibleis there a better option how to implement onetia,['.net'] +75164,python urllib vs httplib when would someone use httplib and when urllibwhat are the differencesi think i ready urllib uses httplib i am planning to make an app that will need to make http request and so far i only used httplibhttpconnection in python for requests and reading about urllib i see i can use that for request too so whats the benefit of one or the other,['python'] +75168,how do 32bit applications make system calls on 64bit linux some many all 64bit1 linux thistros allow running 32bit applications by shipping parallel collections of 32bit and 64bit libraries including libc so a 32bit application can link against 32bit libs and be run by a 64bit kerneli would like to know the mechanics of how 32bit applications make system calls on a 64bit kernel i suspect the answer is somewhere in libc andor the kernel source but it would be timeconsuming for me to dive into the source since i do not know where to lookand a more important question is there any performance overhead2 logically a call from a 32bit app system call will have to translate to 64bit internal kernel environment how and where is this accomplished1 32bit ia32 and 64bit amd642 in your answer make an assumption that it matters,['c'] +75180,static memory in python do loops create new instances of variables in memory i have been running python scripts that make several calls to some functions say f1x and f2x that look a bit like thisx loaddatafor j in rangen y f1xj zj f2y del ysavedatazperformance is a lot faster if i keep the del y line but i do not understand why this is true if i do not use del y then i quickly run out of ram and have to resort to virtual memory and everything slows to a crawl buy if i use del y then i am repeatedly flushing and reallocating the memory for y what i would like to do is have y sit as static memory and reuse the memory on every f1x call but from what i can tell that is not whats happeningalso not sure if it is relevant but my data consists of numpy arrays,['python'] +75184,please recommend a view technology to be used in spring mvc 3 applications i am looking for what view technology would be considered the best approach for spring mvc 30 which is flexible maintainable and allows multiple rendering technologies such as html pdf etcwere looking to develop our next web application using spring mvc 30 and have settled on hibernate for persistence but are still trying to decide which is the most appropriate view technologywe will require support for pdf reports but would most likely write these using itextare there any maven archtypes which would setup a recommended application complete with persistence and view technologythe spring samples use a bunch of different technologies from jstl to apache tiles weve only ever used jsp in the past since we moved to net in 2003 and are moving back to java now,['java'] +75197,how to send email with attachment using gmailsender in android i want to know about how to send email with attachment using gmailsender in android,['android'] +75204,c how to take a screenshot of a portion of screen like takescreenshotnew rectangle00100100 outputjpg,"['c#', '.net']" +75212,what is the correct way to stop form input boxes autocompleting i have a form which includes a jquery datepicker attatched to an input on the form my problem at the moment is that since the input is a textbox most major browsers attempt to autocomplete entries for the user which looks very silly over the datepickerbrowsing the internet i thiscovered that way back in the days of ie5 microsoft had an attribute for input tags called autocomplete which could thisable it however that was way back then and that was ie checking on w3schools revealed that html5 also includes an autocomplete attribute for input tags yes i was equally surprised that microsoft was supporting html5 way back in 19 however our website is not on html5 yet so i cannot rely on using the tag and assuming it will work taking these into consideration how then does one thisable autocomplete for a single input box in html4 expected browsers are chrome latest firefox 36 firefox 20 and god help us perhaps ie6 although we have warned everyone that we are not promising anything will actually work if they use ie6 by the way for anybody worrying out there i know that this is attempting to change a users personal browser settings which is a naughty thing to do normally however in this case i believe it is justified especially considering 90 of my users would not know what autocomplete is or that it even can be turned off,['html'] +75217,how to add background image to activity using theme or imageview,['android'] +75228,using joda date time api to parse multiple formats i am parsing third party log files containing datetime using joda the datetime is in one of two different formats depending on the age of the log files i am parsingcurrently i have code like thistry return datetimeformatforpatternymmdd hhmmssparsedatetimedatepart catch illegalargumentexception e return datetimeformatforpatterne m dd y hhmmparsedatetimedatepartthis works but contravenes joshua blochs advice from effective java 2nd edition item 57 use exceptions only for exceptional conditions it also makes it hard to determine if an illegalargumentexception occurs due to a screwed up datetime in a log filecan you suggest a nicer approach that does not misuse exceptions,['java'] +75230,detect gridview scrolling speed android i have a custom view subclassed from gridview that i use in order to thisplay some custom 3d animationeffect the way i do this is by overriding thispatchdrawideally i would want to know the current speed of the scrolling when doing the draw currently i use gesturedetectorongesturelistener and capture onscroll events and this works very well except that it does not also detect flings as scrolling eventsone idea that comes to mind would be to capture onfling events and then do future processing on my own in order to detect the speed at a later timeis there any better way to achieve this any simple way to query the current scrolling speed of a gridviewthanks,['android'] +75232,postgresql recursive with i need help with a recursive query assuming the following tablecreate temporary table tree id integer primary key parent id integer not null name varchar50 insert into tree id parent id name values 3 0 peter 20 thomas 52 david 1 0 rob 8 0 briani can retrieve a list of all people and their children with the following querywith recursive recursetreeid parent id as select id parent id from tree where parent id 0 union select tid tparent id from tree t join recursetree rt on rtid tparent id select from recursetreehow can i list them in order and also sort the first level items by name for example the desired output would beid parent id name 8 0 brian3 0 peter1 0 rob2 0 thomas5 2 davidthanksedit please note that adding an order by would not work with recursive recursetreeid parent id path name as select id parent id arrayid as path name from tree where parent id 0 union all select tid tparent id rtpath tid tname from tree t join recursetree rt on rtid tparent id select from recursetree order by paththe above will retain the parent child relationship children follow their parents but applying any other order by clause ie name like some have suggested will cause the result to lose it is parentchild relationships,['sql'] +75239,determining if a javascript object is a complex object or just a string i want to be able to pass either a string literalthis is a stringor a javascript objectone this two is three a four string as argument to a function and take different actions depending on whether it is a string or an object how do i determine which is trueto be specific i want to iterate over the properties of an object and do some parsing if a property is a string but nest recursively if the property is an object i have figured out how to use each to iterate over the properties of the object but if i just do this with the string it treates the string as an array of letters rather than as a single thing can i get around this some other way,"['javascript', 'jquery']" +75242,how can i get my very large program to link our next product has grown too large to link on a machine running 32bit windows the sum total of all the lib files exceeds 2gb and can only be linked on a 64bit windows machine eventually we will exceed that boundary since our software tends to grow rather than contract and we are using a 32bit linker ms visual studio 2005 we expect to hit trouble when our lib size total exceeds 3gbhow can i reduce the size of the lib files or the obj files without trimming code for example we use a lot of templates is there any way of reducing their footprint is there any way of finding out whats causing the bloat from examining the libobj files can this be automated rather than inspected by eye 25gb is a lot of text to peer through and compareexternal constraints prevent us from shipping as anything other than a single exe so a dll solution is not available,['c++'] +75243,how to query lucene with like operator the wildcard can only be used at the end of a word like useri want to query with a like user how to do that,['java'] +75246,what is the ignoring innerclasses attribute warning output during compilation i am new to android and am using the ical4j library for parsing ics outlook calendar fileshowever when i build my application in eclipse the following warning appears many times in the console20100722 155831 google calendar upload warning ignoring innerclasses attribute for an anonymous inner class that does not come with an associated enclosingmethod attribute this class was probably produced by a broken compilerwhich implications does this have how can i resolve this,['android'] +75250,is there a performance difference between between and in with mysql or in sql in general i have a set of consecutive rows i want to get based upon their primary key which is an autoincrementing integer assuming that there are no holes is there any performance between betweenselect from thetable where id in n nk andselect from thetable where id between and and nk,"['sql', 'mysql']" +75255,run interactive command line exe using c i can run a command line process using procestarti can provide input using standard input after that when the process demands user input again how can my program know and pass the input to that exe,['c#'] +75258,php strip a specific tag from html string i have the following htmlhtml body bla bla bla bla div idmydiv more text div idanotherdiv and even more text div div bla bla bla bodyhtmli want to remove everything starting from div idanotherdiv until its closing div how do i do that,['php'] +75278,how to make a less than comparison in template metaprogramming i had this question asked of me on monday and for the life of me i do not know how to answer since i do not know i now want to very much find out curiosity is killing this cat given two integers return the lesser at compile timetemplateint m int nstruct smallerofmandn and magic happenes heregot pointers or how to do it will start reading boost mpl tonight,['c++'] +75281,command line parsing commons cli alternatives for command line parsing in java i typically use apache commons clican anybody recommend any alternative libraries,['java'] +75292,is there a hashmap library for javascript in javascript all objects act a bit like hashmaps however the keys to these hashmaps must be strings if they are not they are converted with tostring that meansvar a foo 1var b bar 2var o oa 100ob 100jsonstringifyo object object100that is since the tostring of any plain object is object object they all address the same valuei would like to create a hashmap where objects with the same properties and values address the same value but objects with different properties or values address different values that isvar a foo 1var b bar 2 baz 3var c baz 3 bar 2var hash new hashhashseta 100hashgetb undefinedhashsetb 200hashgetb 200hashgetc 200my first instinct was to use jsonstringify to turn objects into strings butvar hash var b bar 2 baz 3var c baz 3 bar 2hashjsonstringifyb 100hashjsonstringifyb 100hashjsonstringifyc undefinedjsonstringifyb bar2baz3jsonstringifyc baz3bar2that is json serialization is orderdependentis there a good library or technique to implement a hashmap like thisupdateequivalently is there a good hashing function such thathashfoo 1 bar 2 hashbar 2 foo 1,['javascript'] +75318,how to make correct date format when writing data to excel iam exporting a datatable to an excelfile using office interop the problem is that excel does not recognize dates as such but instead it thisplays numbers in another case i pass a string which it then recognizes as a date in both cases the data is messed upi tried numberformat which is supposed to store the cell in text format but it did not work either application app new application appvisible false appscreenupdating false appthisplayalerts false appenableanimations false appenableautocomplete false appenablesound false appenabletipwizard false apperrorcheckingoptionsbackgroundchecking false workbook wb appworkbooksaddxlwbatemplatexlwbatworksheet worksheet ws worksheetwbworksheets1 for int j 0 j dtrowscount j for int i 0 i dtcolumnscount i range rng wscellsj2 i1as range rngvalue2 dtrowsjitostring rngnumberformat wbsaveasfilename missingvalue missingvalue missingvalue missingvalue missingvalue xlsaveasaccessmodexlexclusive missingvalue missingvalue missingvalue missingvalue missingvalue wbclosefalse missingvalue missingvalue appworkbooksclose appapplicationquit appquit systemruntimeinteropservicesmarshalreleasecomobjectws systemruntimeinteropservicesmarshalreleasecomobjectwb systemruntimeinteropservicesmarshalreleasecomobjectapp ws null wb null app null gccollectwhy does not my numberformat work should not textformat thisplay everything the same as i put it in,"['c#', '.net']" +75320,method resolution order in c consider the following class hierarchybase class object with a virtual method fooan arbitrary hierarchy with multiple inheritance virtual and nonvirtual each class is a subtype of object some of them override foo some do nota class x from this hierarchy not overriding foohow to determine which method will be executed upon a call of foo on an object of class x in ci am looking for the algorithm not any specific case,['c++'] +75321,taking screenshot of android opengl i am trying to take a screenshot of android openglthe code i found is as followsnt size width height bytebuffer buf bytebufferallocatedirectsize 4 buforderbyteordernativeorder glcontextglreadpixels0 0 width height gl10gl rgba gl10gl unsigned byte buf int data new intsize bufasintbuffergetdata buf null bitmap bitmap bitmapcreatebitmapwidth height bitmapconfigrgb 565 bitmapsetpixelsdata sizewidth width 0 0 width height data null short sdata new shortsize shortbuffer sbuf shortbufferwrapsdata bitmapcopypixelstobuffersbuf for int i 0 i size i bgr565 to rgb565 short v sdatai sdatai short v0x1f 11 v0x7e0 v0xf800 11 sbufrewind bitmapcopypixelsfrombuffersbuf try fileoutputstream fos new fileoutputstreamsdcardscreeshotpng bitmapcompressbitmapcompressformatpng 100 fos fosflush fosclose catch exception e handle i tried also a code from that sitelink textin each case the result is a png file which is completely blacki found there is some problem with glreadpixels method but i do not know how to bypass it,['android'] +75335,segregating debug and release code in c i am writing an application wherein i have some debug code that i do not wish to delete but i wish it to be modified or removed when compiling for releasepublish for example i would like something like this in a debug buildmessageboxshowextostring error messageboxbuttonsok messageboxiconerrorto become this in a release buildmessageboxshowexmessage error messageboxbuttonsok messageboxiconerrorideally i was hoping to do something like thisif debug build messageboxshowextostring error messageboxbuttonsok messageboxiconerrorelse messageboxshowexmessage error messageboxbuttonsok messageboxiconerrorendifi would prefer to not have to addremove a conditional compilation symbol in the project properties every time i change the build type it should happen automatically is there a way to do this in microsoft visual c 2008 express edition thanks,['c#'] +75375,jquery abort ajax request before sending another based on in inventory search before the ajax request is made how can i check for any current requests and abort them before making a new request or is there a better way to do thisscript typetextjavascript function forminternal catalogchangefunction inventory search function inventory search var search data forminternal catalogserialize var a ajax type post url testphp data search data success functiondata cataloghtmldata script,"['javascript', 'jquery']" +75376,write x509 certificate into pem formatted string in java is there some high level way to write an x509certificate into a pem formatted stringcurrently i am doing x509certencode to write it into a der formatted string then base 64 encoding it and appending the header and footer to create a pem string but it seems bad especially since i have to throw in line breaks too,['java'] +75390,check for presence of a sublist in python i want to write a function that determines if a sublist exists in a larger list list1 10100list2 1010101should return truesublistexistslist1 1should return falsesublistexistslist2 1is there a python function that can do this,['python'] +75398,php bootstrapping basics i am writing my first php app everyone talks about having a bootstrapphp to initialize your app this makes sense and i have put together one that i am happy with there is two things i do not understand and which no one seems to mentionwhere do i call my boostrap from do i include it in every page please tell me there is a better wayhow do i make it so my bootstrap is not called more often than needed i assume it only needs to be called either at the start of the app or the start of a new session,['php'] +75400,should small simple structs be passed by const reference i have always been taught that nonprimitive types should be passed by const reference rather than by value where possible ievoid foostdstring strbadvoid fooconst stdstring strgoodbut i was thinking today that maybe actually some simple user defined types may actually be better passed by value egclass vector2public float x y constructors operators overloads utility methods etcvoid foovector2 posvoid fooconst vector2 posis this really better than by valuevoid foofloat x float yafter all is not by value effectively doing thismy thought is that by passing the vector2 by reference it is actually more expensive than passing by value since the compiler is now using a pointer and dereferencing to access the const vector2 pos versionis this the case are simple objects best off passed by value where should the line be drawn,['c++'] +75403,whats the learning curve for android what has peoples experience been in learning androidi would be interested in how long it takes to get to the point where youre writing your first app and how the experience compares to learning some other programming apii know several professional programmers who have tried to learn android and failed is it inherently more difficult or larger than you might expect but there is a survey herethat claims android has the shortest learning curve of all smartphone platforms i wonderhow the survey guys could have got such a perverse and unlikely resulti have my own views and observations on this which i will mention as a dialog develops i do not want to bias the thiscussion with my perspective at this point thankspeter,['android'] +75405,how to read embedded resource text file how do i read an embedded resource text file using streamreader and return it as a string my current script uses a windows form and textbox that allows the user to find and replace text in a text file that is not embedded private void button1 clickobject sender eventargs e stringcollection strvaluestosearch new stringcollection strvaluestosearchaddapple string stringtoreplace stringtoreplace textbox1text streamreader filereader new streamreadercmyfiletxt string filecontents filecontents filereaderreadtoend filereaderclose foreach string s in strvaluestosearch if filecontentscontainss filecontents filecontentsreplaces stringtoreplace streamwriter filewriter new streamwritermyfiletxt filewriterwritefilecontents filewriterclose,"['c#', '.net']" +75407,detecting autocomplete on form input with jquery i have a form that detects if all the textfields are valid on each keyup and focus if they are all valid it will enable the submit button for the user to press however if the user fills in one of the text inputs with a browsers autocomplete feature it prevents the submit button from being enabledis there a way to detect if any of the input has changed regardless of how it is been changed using jquery,"['javascript', 'jquery']" +75409,how do i use a standalone class in cakephp 13 i have a standalone class i wrote in php for some very basic ldapad functions and i would like to use this class in a project i am working on in cakephpit looks like in cakephp 12 i could just add the class as a vendor however it looks like cakephp 13 removed support for vendors so how would i go about calling a few function from this classi would like to try to keep the class itself the same and not turn it into a plugin as that seems unnecessarythankscode belowphpclass userscontroller extends appcontroller var name users commented out because it breaks the script appimportlib ldapfunction index thisuserrecursive 0 thissetusers thispaginate function login if emptythisdata if ldapauththisdatauseruserthisdatauserpassword thissessionsetflash the user has been saved true thissessionwriteuser thisdatauseruser thisredirectarrayaction index else thissessionsetflash login failed true function logout thissessiondeleteuser thisredirectthisreferer function viewid null if id thissessionsetflash invalid user true thisredirectarrayaction index thissetuser thisuserreadnull idfunction add if emptythisdata thisusercreate if thisusersavethisdata thissessionsetflash the user has been saved true thisredirectarrayaction index else thissessionsetflash the user could not be saved please try again true projects thisuserprojectfindlist thissetcompactprojectsfunction editid null if id emptythisdata thissessionsetflash invalid user true thisredirectarrayaction index if emptythisdata if thisusersavethisdata thissessionsetflash the user has been saved true thisredirectarrayaction index else thissessionsetflash the user could not be saved please try again true if emptythisdata thisdata thisuserreadnull id projects thisuserprojectfindlist thissetcompactprojectsfunction deleteid null if id thissessionsetflash invalid id for user true thisredirectarrayactionindex if thisuserdeleteid thissessionsetflash user deleted true thisredirectarrayactionindex thissessionsetflash user was not deleted true thisredirectarrayaction index,['php'] +75420,jquery trigger event when click outside the element documentclickfunctionevt var target evtcurrenttarget var inside menuwraper if target inside alertbleep i am trying to figure out how to make it so that if a user clicks outside of a certain div menuwraper it triggers an event i realized i can just make every click fire an event then check if the clicked currenttarget is same as the object selected from menuwraper however this does not work currenttarget is html object and menuwraper is object object i am very confused,"['javascript', 'jquery']" +75427,stop app name from flashing in title bar i made a custom title bar for my app which works however when the app first loads the app name is thisplayed in the title bar for a moment before my text appears how do i stop this from happeningi set my custom title bar in my main activity herepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate requestwindowfeaturewindowfeature custom title setcontentviewrlayoutmain getwindowsetfeatureintwindowfeature custom title rlayoutmytitlemytitlexml is where i set my textxml version10 encodingutf8 textview xmlnsandroid androidididmytitle androidtextmy text androidlayout widthfill parent androidlayout heightfill parent androidgravitycenter androidtextappearanceandroidattrtextappearance my title bar background does not flash just the textthanks,['android'] +75435,otherbuttontitles in uialertview i was just curious about how can i attach some different task to the otherbuttontitle of uialertviewthe cancel button automatically take you out of the application but if i want to attach a different task with the otherbuttontitle what should i dothanks,['objective-c'] +75459,single quotes or double quotes for variable concatenation is it better to concatenate a variable say name into an existing string say string like thisstringhi my name is nameor to embed the variable in the string like thisstringhi my name is nameor is it better to use a function like thisstringsprintfhi my name is snamewhich is better in terms of processor timeefficiency,['php'] +75462,is oscommerce outdated is oscommerce outdated i recently started working for a web development company that uses it a lot and i noticed the code base is really messy and has a lot of older php code in there being used to something nice like cakephp or drupal i was not too impressed with itis it worth using any moreis there a decent port of osc that is updated and easy to transfer existing stores to bonus points if it has a plug in system that is not a hack festright now i am looking at zencart ubercart and magento as alternatives would you recommend anything elsethankyou,['php'] +75473,sql error errno 121 create table users uid int unsigned not null auto increment username varchar45 not null password varchar100 null name varchar100 null gender bit null email varchar255 null phone varchar30 not null verified bit not null default 0 time zone int null time register datetime null time active datetime null primary key uid unique index username unique username asc index verified index verified asc engine innodbdefault character set utf8 table companies create table companies cid int unsigned not null auto increment name varchar45 not null address varchar100 null email varchar255 null phone varchar30 null link text null image small text null image large text null yahoo varchar100 null linkin varchar100 null twitter varchar20 null description text null shoutout varchar140 null verified bit not null default 0 primary key cid index name index name asc index verified index verified asc engine innodbdefault character set utf8 table products create table products pid int unsigned not null auto increment cid int unsigned not null name varchar100 null description text null image small text null image large text null tag varchar45 null price decimal112 null primary key pid index tag index tag asc index companycid fk cid asc constraint companycid fk foreign key cid references companies cid on delete no action on update no actionengine innodbdefault character set utf8 table users companies create table users companies uid int unsigned not null cid int unsigned not null role int unsigned null primary key cid uid index usersuid fk uid asc index companycid fk cid asc constraint usersuid fk foreign key uid references users uid on delete no action on update no action constraint companycid fk foreign key cid references companies cid on delete no action on update no actionengine innodbdefault character set utf8i got error1005 cannot create table wewusers companies errno 121 a hrefserver enginesphpengineinnodbamppagestatusamptoken3f35afdea97dd11f6b4ec1b669816738detailsa can anyone tell me which one is the problem,"['mysql', 'sql']" +75482,thistinguish between panning and normal screen modes in code windows i am writing a fullscreen 3d game and i have created a menu in which the user may select the screen resolution to match his hardware capacityi am enumerating all the available screen modes with enumthisplaysettingsexa like thisstdvectordevmodea modesdevmodea modeinfoint modenum 1while enumthisplaysettingsexa0 modenum modeinfo 0 if modeinfodmbitsperpel 16 continue modespush back modeinfo the problem is i am getting panningmodes as well i cannot thistinguish which are which for example my ati laptop has a maximum normal mode of 1280x800 but also contains a panningmode of 1024x600anyone knows of a way to thistinguish between the 2 so i can reject panningmodes from my menu,['c++'] +75492,create if not exists view is there any way to create view if not exists in mysql or h2 database,"['sql', 'mysql']" +75517,putting a php variable in a html form value i have got a php variable like so name requestname i would like to put it in a html form fields value eg in here input typetext namename valuephp variable here how would i do sothanks,"['php', 'html']" +75518,checking data availability before calling stdgetline i would like to read some data from a stream i have using stdgetlinebelow a sample using the stdcinstdstring linestdgetline stdcin line this is a blocking function ie if there is no data or line to read it blocks executiondo you know if exists a function for checking data availability before calling stdgetline i do not want to block how can i check whether the stream buffer is full of data valid for a successful call to stdgetlinewhatever looks like the code belowif dataavailableinstream stdstring line stdgetline stdcin line,['c++'] +75526,how do i remove the required rules from all form inputs in jquery validate as above how can i remove all of the required rules from a form using jquery validatethis is what i have at presentvar settings formvalidatesettingsalertsettingsrulestosourcefor var i in settingsrules alerti delete settingsrulesi not sure about how to do this properly and how to just delete the required rule and keep the rest intactthe function native to jquery validate returns an undefined errorinput select textarearulesremoverequired,['jquery'] +75530,getting first day of the week in mysql using week no how do i get the first day of a given week whose week number is availablefor example as i write this post we are at week 29i would like to write a mysql query that will return sunday 18 july using this weekno 29 as the only available parameter,"['mysql', 'sql']" +75534,application start versus oninit versus constructor i have gone rounds with this ever since i started programming classic asp 12 or so years ago and i have never found a great solution because the architecture of asp and aspnet has always been a swamp of bad practices magic shared singletons etc my biggest issue is with the httpapplication object with its nonevent events application start application end etcif you want to do stuff once for the entire lifespan of an http application application start is the obvious place to do it right not exactly firstly this is not an event per se it is a magic naming convention that when followed causes the method to be called once per appdomain created by iisbesides magic naming conventions being a horrible practice i have started to think it might be a reason there exist no such thing as a start event on the httpapplication object so i have experimented with events that do exist such as init well this is not really an event either it is an overridable method which is the next best thingit seems that the init method is called for every instantiation of an httpapplication object which happens a lot more than once per appdomain this means that i might as well just put my startup logic inside the httpapplication objects constructornow my question is why should not i put my startup logic in the constructor why does even init exist and do i need to care about application start if i do can anyone explain why there is no proper event or overridable method for this pseudoevent in the httpapplication objectand can anyone explain to me why in a typical aspnet application 8 instances of my httpapplication are created which causes the constructor and init to run just as many times of course this can be mitigated with locking and a shared static boolean called initialized when my application only has a single appdomain,['asp.net'] +75541,pragma pack effect i was wondering if someone could explain to me what the pragma pack preprocessor statement does and more importantly why one would want to use iti checked out the msdn page which offered some insight but i was hoping to hear more from people with experience i have seen it in code before though i cannot seem to find where anymore,['c'] +75544,turn off pagelevel caching in a user control i have a page with the following caching defined outputcache duration60 varybyparamnone i have a user control inside that page that i do not want cached how can i turn it off just for that control,['asp.net'] +75548,should dealloc do anything other than release memory i inherited an iphone app at work and i am new to objectivec so i do not have my bearings just yet i encountered code similar to this void dealloc staticobject sharedobject showsomedialog super dealloci know this is frowned upon in other languages my spider sense is going crazy looking at that code is this a common objectivec idiom or do i have a crappy codebase to fix,['objective-c'] +75550,why do threads share the heap space threads each have their own stack but they share a common heapits clear to everyone that stack is for localmethod variables heap is for instanceclass variableswhat is the benefit of sharing heap among threadsthere are several number of threads running simultaneously so sharing memory can lead to issues such as concurrent modification mutual exclusion etc overheadwhat contents are shared by threads in heap why is this the case why not have each thread own its own heap as well can anyone provide a real world example of this how shared memory is utilized by threads,['java'] +75567,c class method pointers there is a class class a public a private void func1int void func2int i want to add a function pointer which will be set in constructor and points to func1 or func2so i can call this pointer as class member from every class procedure and set this pointer in constructorhow can i do it,['c++'] +75572,java language design with tostring we did they make the decision to not implement a tostring method for int but instead let it inherit the tostring method from object,['java'] +75573,can eclipse indent new line with 1 tab after javascript array initializer i am using eclipse to edit javascript files and i guess i am doing it wrong given the following code where a represents a taba represents a space and represents the cursorfunctionafooaa varabazaaif i hit enter at this point i getfunctionafooaa varabaza ayuck i would much rather getfunctionafooaa varabaza a i have dug through the various typing and formatter preferences to no success did i overlook something or is there a particular incantation that i must chant or spell i can cast on eclipse to make it behave this way thanks,['javascript'] +75580,problem with python logging rotatingfilehandler in django website i have a django powered website and i use standard logging module to track web activitythe log is done via rotatingfilehandler which is configured with 10 log files 10 byte each the log system works but this are the log files i getrwrr 1 apache apache 83 jul 23 1330 hrlogrwrr 1 apache apache 446276 jul 23 1303 hrlog1rwrr 1 apache apache 910 jul 23 0600 hrlog10rwrr 1 apache apache 415 jul 23 1624 hrlog2rwrr 1 apache apache 479636 jul 23 1603 hrlog3rwrr 1 apache apache 710 jul 23 1530 hrlog4rwrr 1 apache apache 892179 jul 23 1503 hrlog5rwrr 1 apache apache 166 jul 23 1430 hrlog6rwrr 1 apache apache 890769 jul 23 1403 hrlog7rwrr 1 apache apache 977 jul 23 1230 hrlog8rwrr 1 apache apache 961 jul 23 0801 hrlog9as you can see it is a mess last log has been written to file hrlog2 jul 23 1624 instead of hrlog and logging documentation states thatfor example with a backupcount of 5 and a base file name of applog you would get applog applog1 applog2 up to applog5 the file being written to is always applog when this file is filled it is closed and renamed to applog1 and if files applog1 applog2 etc exist then they are renamed to applog2 applog3 etc respectivelywhat am i doing wrongmy logging configuration file isloggerconfloggerskeysroothandlerskeysfilehandlerformatterskeyssimple formattersformatter simpleformatasctimes names levelnames messages handlershandler filehandlerclasshandlersrotatingfilehandlerleveldebugformattersimpleargsdatadjangohrhrloga1010 loggerslogger rootleveldebughandlersfilehandlerand my python module to set up the log system isloggerpyimport os logging load config filelogger config file ospathjoinospathabspathospathdirname file loggerconfloggingconfigfileconfiglogger config file create loggerlogger logginggetloggerhr logger log start messageloggerinfologging system startedthen at the top of my viewspy i haveimport loggingfrom hr import loggerlog logginggetloggerhrviewsloginfoload hrviews,['python'] +75581,is there a framework for multiplayer board game in javascript i will probably use javascript to develop an online boardcard gamemy approach will be to have a client that will be able to work in standalone mode so it must enforce rules that means for example if a player cannot play a card he or she should not even be able to play it this is to enhance the user experiencethe idea here is to add hooks to send and receive events to and from the server and share the code that implements the game rules between the server and the client i do not see the point of writing them twiceso if i play in server mode the client will update the server with my actions verifying them as well and the server will send me updates about the rest of the playersis there any framework to leverage this workfor the server side my options seem to be nodejs unstable but everything would be js and that is neat erlang erlang js and maybe some of those weird frameworks that compile into javascript that i am no really fond of,['javascript'] +75596,to prevent a memory leak the jdbc driver has been forcibly unregistered i am getting this message when i run my web application it runs fine but i get this message during shutdownsevere a web application registered the jbdc driver oraclejdbcdriveroracledriver but failed to unregister it when the web application was stopped to prevent a memory leak the jdbc driver has been forcibly unregisteredany help appreciated,['java'] +75612,most robust way to convert a cvs repository containing eclipse projects to git i have a situation where i have an elderly cvs repository which we would like to convert to git once and for all while keeping full history etcall folders at the root of the repository contains eclipse projects either plain or dynamic web projects including classpath and project we use team projectsets to check out the projects we need for a given task where the project set is located in the project containing the main and the rest are library projectswhen the team projectset is checked out the workspace is fully populatedthis approach has worked pretty well for many years except the project set part which came with 35 and we would like to work in a similar way with git if possible but we are uncertain how i have played somewhat with git cvs import but it failed probably due to us not using moduleshow would you suggest we do this and how should we work with git to allow our current usage of shared library projects would we have to introduce maven and create maven modules for our library projects or just ant ivyedit i have now managed to convert our cvs repository to subversion with a suitable cvs2svn invocation and found that eclipse recognizes the resulting subversion repository nicely unfortunately after cloning and trying to run binsvn2git i gettrasandboxcvsgitsvn2gitsvn2git binsvn2gitbinsvn2git35in initialize wrong number of arguments 2 for 1 argumenterror from binsvn2git35in new from binsvn2git35this is with ubuntu 10041 lts server and i have tried various sudo things with ruby and its gems without fully understanding what i did as i am not a ruby programmer so i may have messed up things a bit i would appreciate advice if the easiest is to install another linux variant to do the conversion that is fineeditedit my first try with the default svn2git completed successfully after a while and i get a nice repository where git branch a reports roughly trasandboxgitrootsvnroot git branch a master remotesxx64 deployed code remotesbeta1 remotesbeta2 remotessv46 lots morewe are interested in being able to check out the sv46 branch and work with it we basically do not care about the tags just actual branches i have set up gitosis and pushed this repository to gitosis and cloned it to another computer to find out how to do the work with sv46 bit with eclipse that repository does not know of all the branchestratra gitgit00 master git branch a master remotesoriginhead originmaster remotesoriginmasterdo i need to massage the original result from svn2git to get the information into the gitosis repository do i need to clone with an argument should i redo the svn2git step with the suggested version instead of the one shipping with ubuntuedit it turned out that publishing the svn2git generated repository with git push mirror made things shown up in the gitosis repository i now see the following inside gitosis trimmedtrasandboxsrvgitosisrepositoriesgit01git git branch a master remotesxx64 deployed code remotesbasic beta1 remotesbeta1 remotesbeta2 remotessv46 lots moretrasandboxsrvgitosisrepositoriesgit01git git branch mastertrasandboxsrvgitosisrepositoriesgit01git git tag ltrasandboxsrvgitosisrepositoriesgit01gittrying to clone this repository with git clone gitosissandboxgit01 b remotessv46 or git clone gitosissandboxgit01 b sv46 both tell me that the remote branch is not found upstream origin using head insteadam i barking up the wrong tree,['java'] +75613,performing get request before leaving page javascript if a get request is made as followswindowbindbeforeunload function get requestand the page is abandoned before the get request is completedwill the destination server still process the request or will it somehow vanishi would like to send a server data on beforeunload firing but without stealing useless ms from the userit would be very useful if someone could help me,['javascript'] +75659,how do i connect to a udp port in python like everyone else i can say i have tried everything i kind of did i looked all over stackoverflow and tried all the answers but got nothing anyways i am jetting to at least get some code printed by python before i get even further in developing thisi want to receive udp packets from my garrys mod server logaddress add myip7131 and i do not seem to be receiving any of those packets it is most likely not a router firewall problem as i can use hlsw on my other computer i have used wireshark and did not see any data from my servers ip i used the python interpreter made some code although example was tcp to see if i got any datato make sure wireshark was not doing anything wrongand nothing came to it either am i doing something sillyimport socketsock socketsocketsocketaf inet socketsock dgramsockbind0 7131socksettimeout10sockrecv1024edit i was doing some testing with hlsw and found out it seems to be doing some kind of magic when you try to logaddress add the certain port that is not hlsw say 7135 it would not do anything wireshark would not do anything at all does not show any logs anything but when you change hlsw to use the port that you just added 7135 wireshark suddenly gets a flow of data including the console data that i am jetting for is it some kind of configuration hlsw is changing,['python'] +75666,start ipython running a script my use case is i want to initialize some functions in a file and then start up ipython with those functions defined is there any way to do something like ipython run scriptmyscriptpy,['python'] +75678,character detection in a text file in python using the universal encoding detector chardet i am trying to use the universal encoding detector chardet in python to detect the most probable character encoding in a text file infile and use that in further processingwhile chardet is designed primarily for detecting the character encoding of webpages i have found an example of it being used on individual text fileshowever i cannot work out how to tell the script to set the most likely character encoding to the variable charenc which is used several times throughout the scriptmy code based on a combination of the aforementioned example and chardets own documentation is as followsimport chardet rawdataopeninfilerreadchardetdetectrawdatacharacter detection is necessary as the script goes on to run the following as well as several similar usesinfopeninfilerbsunicodeinfreadcharencinfcloseany help would be greatly appreciated,['python'] +75683,what is consolelog in jquery possible duplicatewhat is the consolelog used for in jquery what is consolelog what is it used for in jquery,"['javascript', 'jquery']" +75700,is there an elegant way to invert a bit value in an sql insert statement i am converting some data in sql serverinsert into mytable alloweditselect preventedit from sourcetableso i need to inverse the bit value from source table i expected not to work as this is how i would do it in code but it does not the most elegant way i can think of isinsert into mytable alloweditselect abspreventedit 1 from sourcetableis there a more standard way to do it,['sql'] +75701,creating a plist using java is there an easy way to create a plist with java the result should be the same as serializing a dictionary in objective c,"['java', 'objective-c']" +75707,i do not understand collation mysql rdbms character sets i understand character sets but i do not understand collation i know you get a default collation with every character set in mysql or any rdbms but i still do not get it can someone please explain in layman termsthank you in advance,"['sql', 'mysql']" +75708,use of properties in python like in example c i currently work with python for a while and i came to the point where i questioned myself whether i should use properties in python as often as in cin c i have mostly created properties for the majority of my classesit seems that properties are not that popular in python am i wronghow to use properties in pythonregards,"['c#', 'python']" +75711,using uidocumentinteractioncontroller to thisplay presentpreviewanimated via uiwebview i would like to intercept the clicks from any of the supported file types of the uidocumentinteractioncontroller and thisplay them in a modal view provided by presentpreviewanimated method of uidocumentinteractioncontroller this modal view also provides the open in functionality to open any of these documents in other compatible applications on the device the code below will intercept these clicks detect if the url string has any of the appropriate suffixes load this data write it to the directory read it again and finally use the data with the presentpreviewanimated method i have to write the data to the file system first because the uidocumentinteractioncontroller requires local data and cannot use the data directly from the url as far as i have read boolwebviewuiwebviewwebview shouldstartloadwithrequestnsurlrequestrequest navigationtypeuiwebviewnavigationtypenavigationtype if navigationtype uiwebviewnavigationtypelinkclicked ilogurl loading for navigationtypelinkclicked requesturlabsolutestring if requesturlabsolutestring hassuffixpdf requesturlabsolutestring hassuffixdoc requesturlabsolutestring hassuffixxls requesturlabsolutestring hassuffixppt requesturlabsolutestring hassuffixrtf requesturlabsolutestring hassuffixkey requesturlabsolutestring hassuffixnumbers requesturlabsolutestring hassuffixpages if nsclassfromstringuidocumentinteractioncontroller nsarray parts requesturlabsolutestring componentsseparatedbystring selfpreviewdocumentfilename parts lastobject nslogthe file name is previewdocumentfilename get file online nsdata fileonline nsdata alloc initwithcontentsofurlrequesturl write file to the documents directory nsarray paths nssearchpathfordirectoriesindomainsnsdocumentdirectory nsuserdomainmask yes nsstring documentsdirectory paths objectatindex0 if documentsdirectory nslogdocuments directory not found nsstring appfile documentsdirectory stringbyappendingpathcomponentpreviewdocumentfilename fileonline writetofileappfile atomicallyyes nslogresource file has been written to the documents directory from online previewdocumentfilename fileonline release get file again from documents directory nsurl fileurl nsurl fileurlwithpathappfile uidocumentinteractioncontroller doccontroller uidocumentinteractioncontroller interactioncontrollerwithurlfileurl doccontrollerdelegate self doccontroller retain bool result doccontroller presentpreviewanimatedyes if result doccontroller release return no do lots of other urldetecting stuff herei also implement the following delegate methods to use the appropriate view and to delete the file after the view has been thismissed previewdocumentfilename is a class variablepragma mark pragma mark document interaction controller delegate methods uiviewcontroller documentinteractioncontrollerviewcontrollerforpreviewuidocumentinteractioncontroller controller return self voiddocumentinteractioncontrollerdidendpreviewuidocumentinteractioncontroller controller nsarray paths nssearchpathfordirectoriesindomainsnsdocumentdirectory nsuserdomainmask yes nsstring documentsdirectory paths objectatindex0 nsstring appfile documentsdirectory stringbyappendingpathcomponentpreviewdocumentfilename nsfilemanager filemanager nsfilemanager defaultmanager filemanager removeitematpathappfile errornull controller release release here was causing crashesplease note that the apple documentation made specific mention of the fact that the document controller needed to be retained manually so i did that i also needs to be released so i do that if the controller was not used top method and attempted to release it after it was used delegate method but that release was causing crashes so i removed it and things seem to be working fine from that standpointwith the background out of the way my question has to do with the fact that while this code seems to work in the iphone simulator the online document is thisplayed correctly in the presentpreviewanimated view although without the open in dialogue that cannot be used in the sim it is not showing the presentpreviewmethod on the ipad sim or my actual iphone or ipad devices i believe the method is being called correctly but the presentpreviewanimated method is returning no which means it was not able to thisplay the document previewwhy would this be am i not saving the file properly and thus it is not being detected as a pdf or doc etc what else could i be doing wrong there is very little documentation or example code out there besides the apple documentation so i hope that at the very least this code will be helpful to someone although i would like to get it working 100 first thanks in advance,['iphone'] +75721,linq remove item from object array where property equals value if i haveienumberablecar listand i want to remove an item from this list based on a property of the cari want something likelistremovewhererryear 20does something like this exist i am doing this over and over so i want to avoid copying the list each time to just remove one item,['c#'] +75733,are there any huge differences between objectivec and java or iphone and android edit my bad i meant objectivec not c some reason i got it into my head it was c the iphone used so the answers for c were great thanks but theyre a bit irrelevant sorry about thati have had a look but cannot find anything that answers this though a few have shortened the question by answering parts of it between a small group we were planning on doing some work on iphone and android the 2 seperate for the most part but helping each other out and with some guys doing graphics work split between thembut we were thinking about the possibilities of moving things between the two not necessarily apps maybe just useful classes or something looking at objectivec and java they seem to have about the same features that the biggest obstacle would be system interface stuff so we were wondering whether if we created an abstraction over these on each system so they could be given the same input which unless i am wrong wouldnt put too much strain on the system would there be any problems in writing something to convert between objectivec and java worse than the locations of methods in the sdks or are there key features or something in one language that the other does not have which weve missed that would mean the only way to do it would be rewriting from scratch,"['java', 'iphone', 'objective-c', 'android']" +75737,stateoftheart c projects i like to go through existing software projects as a source of learning and new ideasdoing so i thiscover things that i did not think were possiblein your opinion what is the top state of the art c project that you have useddevelopextended can you state reasons why you consider it state of the art and what you can learn from itmy latest craze is boostphoenix 43 0libsspiritphoenixdochtmlindexhtml which is very comprehensive functional programming librarydespite its capabilities it is straightforward and easy to extend after some tweaking i was able to write multithreaded lambda parallel loops and mathematical domain specific language probably within 2 weekswhat is yours please do not just say boost as it is huge collection of project,['c++'] +75746,lastchild style working firstchild style not working why i am creating an inset border effect between paragraphs by using a light border as the bordertop on the paragraphs and a dark border as the border bottom on themi am trying to use pfirstchild to remove the top border on the first paragraph and plastchild to remove the border on the bottom one they have a class of intro fyithe style to remove the bottom border on the lastchild is working properly but for some reason the style to remove the top border on the firstchild is not it must be a typo or something silly because i cannot figure out why it is working for the lastchild but not the firstchildmarkupdiv idintro div classwrap h1 classintrohi i am a hrefieutf8qjoelandrewglovierjoel andrew glovierah1 p classintroi am a a hrefweb designera and a href and back endsfrontend developera currently working for a hrefcure internationala full time i also do some a hreffreelance worka i a hreftweet a littlea a hrefbloga can be found on a hrefother social mediaa i have a hreflots of projectsa going on at once and i like it that wayp p classintroi am a a hrefgoodnewsfollower of jesusa and a proud father and husband i am also a a hrefum1ieutf8sourceuniveidopgtid9jokklwfv1vwfbasaxoiimage result groupcttitleresnum4ved0cdoqsaqwawbiw1920bih1102bboya i a hrefskateboarda and did i mention that i am a diehard a hrefpittsburgh steelersa fan oh and i have been to a hrefkenya three timesap p classintrowell it is nice to meet you now that you know so much about me a href target blankwhy do not you say hiap divwrapdivcssdivintro pfirstchild bordertopnonedivintro plastchild borderbottomnone,['css'] +75747,console is undefined error for internet explorer i am using firebug and have some statements likeconsolelogin my page in ie8 probably earlier versions too i get script errors saying console is undefined i tried putting this at the top of my pagescript typetextjavascript if console console log function scriptstill i get the errors any way to get rid of the errors,['javascript'] +75758,how to get rid of unsafe warnings errors in visual studio strcpy sprintf strdup i am trying to get rid of some compiler warnings that say strcpy sprintf etc are unsafei get why they are unsafe but i cannot think of a good way to fix the code in a c styleheres a excerpt of the codeextlistnamesichar malloclengthsizeofcharstrcpyextlistnamesiextname unsafe strncpyextlistnamesiextnamelength also unsafeheres the messagec4996 strcpy this function or variable may be unsafe consider using strcpy s instead to thisable deprecation use crt secure no warnings see online help for detailsi cannot think of a safe way to copy the data over in c without knowing the length of the stuff to copyi know there is strlen but that is also unsafe since it assumes maybe incorrectly that the data is nullterminatedalso used to concatenatesprintfextstrssplatextstrglextstrc4996 sprintf this function or variable may be unsafe consider using sprintf s instead to thisable deprecation use crt secure no warnings see online help for detailsusing stdstring to concatenate is easy enough but then i need to get the data into extstr somehow and not using strcpy lol the stringc str function returns a pointer to unmodifiable data so i cannot just set extstr equal to it and i am not even sure if the c str pointer needs delete called on it later does it allocate space using newany advice on this stuffthis is part of a 10 line file that is not mine so i am not exactly keen on rewriting the thing in the c way,['c++'] +75759,whats the point of signing code like jars what is the point of signing your code like javas jars when everyone can do it with jarsignerhow does it provide security,['java'] +75783,removeobserver with nsnotification what am i doing wrong basically i have a view1 which at some point calls view2 via presentmodalviewcontrolleranimated when a certain uibutton in view2 is pressed view2 is calls a notification method in view1 and immediately afterward is thismissed the notification method pops up an alertthe notification method works fine and is called appropriately the problem is every time view1 is created only one view1 should exist at a time i presumably get another nsnotification being created because if i go from view0 the menu to view1 then back and forth a few times i get a series of the same alert message one after another from the notification method as many times as i opened a view1here is my code please tell me what i am doing wrong view1mvoid viewdidload nsnotificationcenter defaultcenter addobserverself selectorselectorshowalert namealert objectnilvoid showalertnsnotificationnotification i have also tried to swap the removeobserver method from dealloc to here but it still fails to remove the observer uialertview code to pop up a message here void dealloc nsnotificationcenter defaultcenter removeobserverself super deallocview2mibaction buttonwastapped nsnotificationcenter defaultcenter postnotificationnamealert objectnil self thismissmodalviewcontrolleranimatedyesvoid dealloc nsnotificationcenter defaultcenter removeobserverself super dealloc,"['ios', 'objective-c']" +75786,jquery alternative for documentactiveelement what i wanted to do is figure out whenever the user is engaged with an input or textarea element and set a variable flag to true and set that flag to false immediately after the user is no longer engaged with them ie they have clicked out of the inputtextarea elements i used jquerys docuemntready function to add the onclick attribute to my body element and assign it to my getactive functionthe code for the getactive function is as followsfunction getactive activeobj documentactiveelement var infocus false if activeobjtagname input activeobjtagname textarea infocus true i would really like to keep by project withing the jquery framework but cannot seem to find a way of accomplishing the same logic above using just jquery syntax,"['javascript', 'jquery']" +75794,how to highlight a div for a few seconds using jquery i want to be add the following to a a pagewhen a div is clicked i want tochange the background color of the clicked on div for a few secondsrevert back to the original background color after a few secondsi want to do this by using only jquery available functions ie not using a plugin or anything else i am relatively new to jquery but i think a possible solution involves the use of changing the class of the selected div and using a timeri am not sure how to put it all together though can anyone provide a few lines that show how to do itthis is what i have so farfunction divhighlightableclickfunction change background color via css class thisaddclasshighlighted set a timer to remove the highlighted class after and seconds how,['jquery'] +75799,ienumerablecontains with predicate i need just to clarify that given collection contains an element i can do that via collectioncountfoo foobar bar 0 but it will do the unnecessary job iterate the whole collection while i need to stop on the first occurrencebut i want to try to use contains with a predicate eg foo foobar barcurrently ienumerabletcontains has two signaturesienumerabletcontainstienumerabletcontainst iequalitycomparertso i have to specify some variable to checkvar collection new listfoo foo bar collectioncontainsfor write my custom iequalitycomparerfoo which will be used against my collectionclass foocomparer iequalitycomparerfoo public bool equalsfoo f1 foo f2 return f1bar f2bar my predicate public int gethashcodefoo f return fgethashcode so are there any other methods to use predicate,['c#'] +75804,i netbeans can i somehow store the rsa key fingerprint of the remote server or not have netbeans confirm the key before taking action i am currently using netbeans 69 with the php plugin and a php application from remote server project however every time i upload or download with it i am prompted with a warning that readsthe authenticity of host x cannot be established rsa key fingerprint is y are you sure you want to continue connectingi am connecting to my own server so yes i always trust it getting that popup is annoying and i would like to be able to simply have a way of either checking the key against a stored key and telling me if the key changes or just connecting to the server i tell it to regardless of the rsa key fingerprint,['php'] +75805,c get line number which threw exception in a catch block how can i get the line number which threw an exception,['c#'] +75806,hashset slow performance in big set i have encountered a problem i cannot find a solutioni am using a hashset to store values the values i store is of the custom type cycles where i have overridden the hashcode and equals as following in order to make sure the slow performance is not cuased by the hascode or the equal methodsalso i have set the initial capacity of the hashset to 10overridepublic int hashcode final int prime 31 int result 1 result prime result int cycleid cycleid 32 return resultoverridepublic boolean equalsobject obj if this obj return true if obj null return false if getclass objgetclass return false cycle other cycle obj if cycleid othercycleid return false return trueafter the first 150 first values when i try to add a new value with the add method of the hashset class the program is very slow eventually i am going to have java out of memory exception exception in thread thread0 javalangoutofmemoryerror java heap space before the stored values reach the 160the ide i use is eclipse so the next step was to increase the jvm heap size from the default value to 1 giga using the commnads xmx10m and xms10mnow the elipse starts with 10 times more memory available i can see that in the bottom right where the total heap size memory and used memory is shown but again i have the same slow performance and the same out of memory error in the same values as before after the 150 and before 160 which is very odoes anyone has an idea what it might be the problemthank you in advance,['java'] +75817,difference between goto and throw many people accused me recently for just mentioning a single word gotoit makes me wonder why it is considered such a nasty wordi am aware of several previous thiscussions on the topic but it does not convince me some of the answers just says it is bad not even trying to explain and some bring reasons irrelevant for scripting languages like php imo anyway i am going to ask a very particular questionlet us compare goto and throw statementsboth in my opinion do the same thing avoiding execution of some portion of code based on some conditionif so do throw have same thisadvantages as goto if anyif not whit is the difference then anyone experienced enough who can tell the fundamental conceptual difference between code structures of the two following code snippetsregarding these very code snippets not in theory or in general or here is a nice xkcd comicwhy the first one considered to be brilliant and latter one considered to be deadliest of sins a1b2 snippet 1 try if isseta throw new exceptiona is not set if issetb throw new exceptionb is not set echo a b a bbrn catch exception e echo caught exception egetmessage brn snippet 2 if isseta message a is not set goto endif issetb message b is not set goto endecho a b a bbrnendif emptymessage echo caught exception message brnnote that i am aware of the fact that throw is more powerful and flexible in making spaghetti it does not make the principal difference for me it is matter of use not conceptediti have been told by many people that first example should be newer usedreason exceptions should be used to handle errors only not to implement business logicit looks sensibletherefore the only way left to stop useless code execution is goto not to mention some substitutes such as while return etc which are the same matter but harder to implement,['php'] +75819,can a safari extension react on the creation of a new tab i am currently writing my first extension for safari 5 i cannot find a reference on what events an extension can react i want my extension to react on these events when a new tab is createdwhen a new browser windows is createdwhen the url inside a tab changes is this possible,['javascript'] +75821,jquery sortable plugin with sliding effect jqueryui has got a nice plugin sortable i am very pleased with that plugin but i am only missing one thing and that is instead of let the elements that changes position popjump to its new position i would like them to slide to that new position instead by other words make it a bit more smootheri have searched the net for three days now and havnt found one plugin that does that i mean come on there must be one righti have also tried to modify the code a bit on my own and i got it to work sort of by cloning the element slide the clone to the new position then delete the clone meanwhile i am hiding the original element and unhide it after deleting the clone but it does not work very well and i thought there must be a better one out there somewhereso i am really begging for help either modifying help or if youve seen a plugin that does this please,['jquery'] +75841,state of derived class object when base class constructor calls overridden method in java please refer to the java code belowclass base base systemoutprintlnbase constructor method void method class derived extends base int var 2 derived systemoutprintlnderived constructor override void method systemoutprintlnvar var class test2 public static void mainstring args derived b new derived the output seen isbase constructorvar 0derived constructori think var 0 occurs because derived object is half initialized similar to what jon skeet says here my questions arewhy does the overridden method get called if the derived class object is not created yetat what point in time is var assigned value 0are there any use cases where such behavior is desired,['java'] +75842,does java have support for multicore processorsparallel processing i know that now that most processors have two or more cores multicore programming is all the rage is there functionality to utilize this in java i know that java has a thread class but i also know this was around a long time before multicores became popular if i can make use of multiple cores in java what classtechnique would i use,['java'] +75853,prepend prefix to list elements with list comprehension having a list like thisfoospambaris it possible using list comprehension to obtain this list as resultfokfoo spam okspam bar okbar,['python'] +75885,regex how to match the last dot in a string i have two example filename stringsjqueryuiminjsjqueryuimincsswhat regex can i use to only match the last dot i do not need anything else just the final dota little more on what i am doing i am using phps preg split function to split the filename into an array the function deletes any matches and gives you an array with the elements between splits i am trying to get it to split jqueryuiminjs into an array that looks like thisarray0 jqueryuiminarray1 js,['php'] +75894,contentlength header already present i am using the apache httpclient 41 included in android to execute a httpput i have verified that i only have 1 contentlength header however every time i send the request i get a protocol exception about the contentlength header already specifiedhttpclient client new defaulthttpclientputmethod new httpputurl encodedfilenameputmethodaddheader once for each headerputmethodsetentitynew bytearrayentitydataclientexecuteputmethod throws exceptioncaused by orgapachehttpprotocolexception contentlength header already present at orgapachehttpprotocolrequestcontentprocessrequestcontentjava70 at orgapachehttpprotocolbasichttpprocessorprocessbasichttpprocessorjava290any ideas,"['java', 'android']" +75899,safe conversion from double to unsigned 64 bit integer on my platform this prints 9223372036854775808double x 1e19stdcout static castunsigned int64x ni tried boostnumericconversion but got the same resultsplitting x into 2 equal part then adding together converted halves give the correct result but i need a generic solution to use in a template codethank you in advanceeditthis problem shows up on visual studio 2008 but not mingw casting 40e9 into unsigned long works fine,"['c++', 'c']" +75915,how to get started with google appengine i m starting to build python application in windows platform using google appenginewhats the steps to debug and run my application,['python'] +75929,how to deal with unicode in mako i constantly get this error using makounicodeencodeerror ascii codec cannot encode character uxe0 in position 6 ordinal not in range128i have told mako i am using unicode in any possible way mylookup templatelookup directoriespluginsstltemplates input encodingutf8 output encodingutf8 default filtersdecodeutf8 encoding errorsreplace selftemplate templateselfgettemplate lookupmylookup module directorytempfilegettempdir input encodingutf8 output encodingutf8 default filtersdecodeutf8 encoding errorsreplace html selftemplaterender unicodedataselfstuffall my template files starts with coding utf8 and inside them all costant strings are prefixed with ui know the selfstuff parameter contains unicode strings but the way i instantiate the mako objects should take care of it otherwise what those arguments are good foris there anything i forgot to doone more question whats the point of encoding errorsreplaceediti left only a single unicode string and this is the tracebacktraceback most recent call last file cmy dropboxsrcflucsosrcpluginsstlmainpy line 240 in updateview flagsselfmakoflags file cpython26libsitepackagesmako034py26eggmakotemplatepy line 198 in render unicode as unicodetrue file cpython26libsitepackagesmako034py26eggmakoruntimepy line 403 in render render contexttemplate callable context args kwargs for callablecallable data file cpython26libsitepackagesmako034py26eggmakoruntimepy line 434 in render context exec templateinherit lclcontext argsargs kwargskwargs file cpython26libsitepackagesmako034py26eggmakoruntimepy line 457 in exec template callable context args kwargs file memory0x41317f0 line 89 in render body file cpython26libsitepackagesmako034py26eggmakoruntimepy line 278 in lambda return lambda args kwargscallable selfcontext args kwargs file friendfeed mako line 49 in render inlist entry file cpython26libencodingsutf 8py line 16 in decode return codecsutf 8 decodeinput errors trueunicodeencodeerror ascii codec cannot encode character uu263c in position 8 ordinal not in range128,['python'] +75950,why is listorderby linq faster than icomparablelistsort in debug mode i was interested in whether it would be faster to sort my classes using linq or by implementing the icomparable interface and listsort i was quite surprised when the linq code was fasterto do the test i made a very simple class with the notsoapt name of testsort implementing icomparableclass testsort icomparabletestsort private int age private string givenname public int age get return age set age value public string givenname get return givenname set givenname value public testsortint age string name thisage age thisgivenname name public int comparetotestsort other return thisagecomparetootherage then a simple program to sort it many times the sort was much more expensive than copying the list so the effect of that can be ignoredclass program static void mainstring args create the test data string name mr bob random r new random var ts2 new listtestsort for int i 0 i 100 i ts2addnew testsortrnext name datetime start end test listsort start datetimenow for int i 0 i 10 i var l ts2tolist lsort end datetimenow consolewritelineicomparablet consolewritelineend starttotalmilliseconds test linq orderby start datetimenow for int i 0 i 10 i var l ts2tolist l lorderbyitem itemagetolist end datetimenow consolewritelinenlinq consolewritelineend starttotalmilliseconds consolewritelinefinished consolereadkey i was quite surprised to receive the following outputicomparablet29651696linq21811248sometimes linq would go below 20 and sometimes icomparable would go about 30when i tested it with a normal listint the listsort was 14 the speed of linq which remained at about 20so why is linq only about 66 the speed of the normal sort for my class am i doing something wrong with my implementation of icomparableupdatei just thought to try doing it in release mode and yes the results were differenticomparablet15930911linq195819but i am still very interested to know why icomparable is slower in debug mode,['c#'] +75953,is there python clang wrapper in the vein of pygccxml which wraps gccxml for a long time now i have been using pygccxml to parse and introspect my c source code it helps me to do some clever codegeneration during our build processrecently i have read a lot about the benefits of the llvm stack and especially the benefits that the llvm clang parser brings to c compilation i am now wondering if there is any python interface to clang such that i could use it as the basis for some of my existing code generation tasks,"['c++', 'python']" +75959,why is there a private access modifier in an abstract class in java even though we cannot create an instance of an abstract class i know it is not a good coding practice to declare a method as private in an abstract class even though we cannot create an instance of an abstract class why is the private access modifier available within an abstract class and what is the scope of it within an abstract class in which scenario is the private access specifier used in an abstract classcheck out this code where vehicle class is abstract and car extends vehiclepackage comvehicleabstract class vehicle what is the scope of the private access modifier within an abstract class even though method below cannot be accessed private void onlights systemoutprintlnswitch on lights public void startengine systemoutprintlnstart engine within is the same package creating a car class package comvehicle car class extends the abstract class vehicle public class car extends vehicle public static void mainstring args car c new car cstartengine only startengine can be accessed,['java'] +75971,inner workings of the net garbage collector i have read detailed papers about the inner workings of the various garbage collectors in the jvm but i have had trouble finding the same level of details for nets runtime anyone have links to good articlesresearchpages on nets garbage collector,['.net'] +76031,how to play mp3 file from resources in c i put musicmp3 in resources and then i added windows media player to references i wrote this codewindowsmediaplayer wmp new windowsmediaplayer wmpurl musicmp3 wmpcontrolsplayit does not work how can i play mp3 file from resources,"['c#', '.net']" +76036,learning springs requestbody and requestparam i am editing a web project that uses spring and i need to adding some of springs annotations two of the ones i am adding are requestbody and requestparam i have been poking around a little and found this but i still do not completely understand how to use these annotations could anyone provide an example,['java'] +76046,is it possible to tile images in a uiscrollview without having to manually create all the tiles in the iphone sample code photoscroller from wwdc 2010 they show how to do a pretty good mimmic of the photos app with scrolling zooming and paging of images they also tile the images to show how to thisplay high resolution images and maintain good performancetiling is implemented in the sample code by grabbing pre scaled and cut images for different resolutions and placing them in the grid which makes up the entire imagemy question is is there a way to tile images without having to manually go through all your photos and create tiles how is it the photos app is able to thisplay large images on the flyedithere is the code from deepas answer below uiimage tileforscalefloatscale rowintrow colintcol sizecgsizetilesize imageuiimage inimagecgrect subrect cgrectmakecoltilesizewidth row tilesizeheight tilesizewidth tilesizeheightcgimageref tiledimage cgimagecreatewithimageinrectinimage cgimage subrectuiimage tileimage uiimage imagewithcgimagetiledimage return tileimage,"['iphone', 'objective-c']" +76066,is there a css selector by class prefix i want to apply a css rule to any element whose one of the classes matches specified prefixeg i want a rule that will apply to div that has class that starts with status a and c but not b in following snippetdiv ida classfooclass statusimportant barclassdivdiv idb classfooclass barclassdivdiv idc classfooclass statuslowpriority barclassdivsome sort of combination ofdivclastatus and divclastatusis it doable under css 21 is it doable under any css specnote i do know i can use jquery to emulate that,['css'] +76067,select a specific column based on another columns value i have a table like thisid type val0 val11 0 a null2 1 null bi need to select val0 when the type is 0 and val1 when the type is 1 and valn when type is nhow can i do that,['sql'] +76078,java does linkedblockingqueue take into account order of consumers i have 3 threads 2 consumers consumera and consumerb and a produceri also have a linkedblockingqueue queueat t1 consumera calls queuetakeat t2 consumerb calls queuetakeat t3 producer calls queueputfoois it guaranteed that consumera receives foo before consumerb in other words the order in which the consumers invokes take is the order in which each is notifiedif not is there an alternative data structure that will give higher priority based on order,['java'] +76082,net tablelayoutpanel a clearing controls is very slow this is really simplei have a tablelayoutpanel that is populated with controls just labels buttons and some panels with buttons based on a database query when the data needs to be refreshed i use tablelayoutpanelcontrolsclear unfortunately this is a very slow operation i would expect it to be faster than the code populating the table but it is at least 3 or 4 times sloweri definitively proved that the slowness is when executing controlsclear by executing this as the single thing done to the tablelayoutpanel after a message box is thisplayed then the procedure returns the controls visibly thisappear from the bottom up when the recordset is used to repopulate the tablelayoutpanel the speed of the controls appearing from top to bottom is almost faster than i can seei am already doing tablelayoutpanelsuspendlayout and resumelayoutusing thisdoublebuffered true on the form does not appear to do anythingi could just thispose the entire control and recreate it through code but this is a big pain and makes having a nice form designer gui pointless i would have to dig into every property i have set on the control and create a line of code for it though i guess i could get this out of the designer code itself it still feels wrongany ideas on how to do the job faster i am even open to using other methods besides a tablelayoutpanel i just need the freedom to put multiple buttons per cell or barring that to be able to span columns in the table headercan c at least freeze the whole form while it redraws and then paint all at once,"['c#', '.net']" +76086,application launcher icon is not deleted from home screen when uninstalling android app i am using a similar codesnippet as shown below to add an application shortcut on the homescreen intent shortcutintent new intentintentaction main shortcutintentsetclassnamethis thisgetclassgetname shortcutintentputextraextra key apidemos provided this shortcut then set up the container intent the response to the caller intent intent new intent intentputextraintentextra shortcut intent shortcutintent intentputextraintentextra shortcut name getstringrstringshortcut name parcelable iconresource intentshortcuticonresourcefromcontext this rdrawableapp sample code intentputextraintentextra shortcut icon resource iconresource now return the result to the launcher setresultresult ok intentthere is no problem with creating the shortcut but when uninstalling the app the shortcut remains on the homescreen when uninstalling other apps they all seem to also remove their corresponding homescreen shortcuts this is what i try to achive with my createdbycodeshortcuticondoes any of you android experts here on stackoverflow know whats needed to remove the app shortcut from the homescreen when the app is uninstalled i found some related threads but they do not provide me the solution for my problem but please feel free to catch up 0 1 2,['android'] +76091,change default python version from 24 to 26 i am wanting to use some newer software that requires python 26 and we currently have both 24 and 26 installed on our dedicated centos server which looks like this which pythonusrlocalbinpython which python26usrbinpython26 which python24usrlocalbinpython24 ls l usrlocalbinpyrwxrxrx 1 root root 81 aug 9 2007 usrlocalbinpydocrwxrxrx 2 root root 3394082 aug 9 2007 usrlocalbinpythonrwxrxrx 2 root root 3394082 aug 9 2007 usrlocalbinpython24how can i switch it to start using 26 as the default python,['python'] +76092,possible to simulate the mysql functionality on duplicate key update with sql server i am using sql server 2008 and would like to be able to take advantage of something like mysqls on duplicate key update clause for insert statementscurrent legacy code does a delete and subsequent insert that is running into concurrency issues with duplicate key inserts from separate threadshere is the error i see in my production environmentviolation of primary key constraint pk audience cannot insert duplicate key in object dboaudiencesp contentupdateprimary keyaudienceid versionidoffending sqldelete from dboaudiencewhere versionid versionidif audiencexml is not null begin insert into dboaudience versionid audienceid createddate createdbypersonid select versionid audienceid getutcdate personid from dboaudience join audiencexmlnodesaudiencesaudience nodec on audienceaudiencename cvaluename nvarchar50 endwrapping this tsql in a transaction seems to either remove the concurrency issue or mask the issue by changing the timings however i do not think wrapping in a transaction has actually solved the concurrency perhaps i am going about this wrong your suggestions are appreciated,['sql'] +76100,android secure storage i want to store some small but critical piece of information such as aes keys in my android application what would be the recommended way to do this i do not want to hardcode keys as part of my applicationi look at keystore but it does not really solve my problem it can store my keys given that i can provide a password then i need to find a secure place to store this password which is same as my original problemis there a built in android class to perform this task or should i look for third party libraries using ndk is also acceptable for meupdatei was hoping to find an android api for storage such that guarantees that only the application that stored some information can retrieve it back android os could have enforced this based on signing signatures of the application this way my application can generate a random key on first run and store it in secure storage for later use are there any api for this,['android'] +76106,springs json not being resolved with appropriate response i have tried to have a controller in spring return a json response to no avail using the jackson classes as recommended with 30 i have got the jackson jar filesjacksoncoreasl155jar jacksonmapperasl155jar in my class path of courseas for the appconfigxml entries i am not sure i need these i have put them in there as a last act of desperation before returning to ol fashion nonjson ajax in debug i watch the controller get the request return the foo and then in firebug get a 406the error messages are as follows from the logger when set to debugorgspringframeworkwebhttpmediatypenotacceptableexception could not find acceptable representationfrom the response406 the resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request accept headers my appconfigxml is here configures support for controllers mvcannotationdriven resolves view names to protected jsp resources within the webinfviews directory bean classorgspringframeworkwebservletviewcontentnegotiatingviewresolver property namemediatypes map entry keyhtml valuetexthtml entry keyjson valueapplicationjson map property property nameviewresolvers list bean classorgspringframeworkwebservletviewbeannameviewresolver bean classorgspringframeworkwebservletviewinternalresourceviewresolver property nameprefix valuewebinfviews property namesuffix valuejsp bean list property property namedefaultviews list bean classorgspringframeworkwebservletviewjsonmappingjacksonjsonview list propertybean bean idmessagesource classorgspringframeworkcontextsupportresourcebundlemessagesource property namebasename valuemessagesproperty beanmy controllerrequestmappingvaluefoobar methodrequestmethodgetpublic responsebody foo getfoorequestparam string fooid return new foofooid on the jsp where the ajax call is madefunction addrow getjsonfoobar fooid 1 functiondata alertit worked let me know if there is any more info that is needed,['java'] +76109,post to page to login using beautiful soup i am using python and beautifulsoup new to both and i want to login to a suppliers websiteso their form looks like simplifiedform nameloginform actionindexhtml methodpostinput nameuserinput namepassformis there a way to keep track for cookies,['python'] +76116,a simple mysql query taking forever more than 20 minutes maybe you can help me i need to query 3 tables in order to get data for a financial stockthe idea is to go to the instruments table find the index for each instrument and then bring all the prices for that particular instrument together with the indicators that are on a separate tabletables stockdata and indicators are both almost 50 records instruments just 30this is the query that is not workingselect indicatorsddate instrumentsname indicatorssma 14 indicatorssma 5 stockdataclosefrom indicators inner join instruments on indicatorsinstrument idinstrumentsid inner join stockdata on instrumentsnamestockdatanamehere is the explain result id select type table type possible keys key key len rows extra 1 simple instruments index primaryinstruments index01 instruments index01 61 25 using index 1 simple indicators ref indicators index01 indicators index01 5 973 using where 1 simple stockdata ref stockdata index01 stockdata index01 31 1499 using where i really appreciate any help you can providethis is the schema for the parts of the tables that are involved in my questiontable indicators id int auto increment not nullbr instrument id int date date sma 5 float103 sma 14 float103 ema 14 float103 keys primary key idtable instruments id int auto increment not null name char20 country char50 newsquery char100 keys primary key idtable stockdata id int auto increment not null name char10 date date open float high float low float close float volume int adjclose float keys primary key id,"['sql', 'mysql']" +76119,rails scriptconsole vs scriptconsole sandbox whats the difference between just firing up a rails console with scriptconsole and a rails console in sandbox mode with scriptconsole sandbox,['ruby-on-rails'] +76123,php assign array to variables i am not sure if my memory is wrong but when i last used php years ago i vaguely remember doing something like thisfirstvariable secondvariable explode foo barnote that the above is incorrect syntax however in this example it would assign foo to firstvariable and bar to secondvariablewhat is the correct syntax for thisthanks,['php'] +76137,using an iphone audio dongle to transmit data i have just started working at a biomedical company and we need to communicate data from a device we are making to an iphone obviously using the made for iphone program would suffice but for prototyping and for a simpler solution i was wondering if we could use an existing bluetooth audio transmitter such as but instead of streaming audio program it to stream data i am not so good with the hardware side and wouldnt be designing the hardware on our end only the software so just wondering if with the current sdk we can send data through an audio streaming deviceany help is greatly appreciated,"['ios', 'iphone']" +76153,click event for option does not work in ie i have a multiple select tag and i need to write the function onclick of it is options because i need to get the value of last clicked option but when i wrote the followingmultiple select optionclickfunction var val thisval alertvalit does not work in iewhat is the problemupdatei need exactly click event because i wrote a function onclick event alreadydemo here and i need to fix last changed elements value which is impossible to make without click eventi think,['jquery'] +76160,use cases for implementing annotations what are valid use cases for implementing annotations when designing primarily annotation based configuration systems i occasionally need to create classes which implement annotations for code generation or programmatic configurationthe alternative involves mirroring the data contained in annotations into dtos which seems like an overheadhere is an examplepublic enum idtype local uri resourcedocumentedtarget method field retentionretentionpolicyruntimeinheritedpublic interface id return idtype value default idtypelocalwith the implementationpublic class idimpl implements id private final idtype idtype public idimplidtype idtype thisidtype idtype override public idtype value return idtype override public class extends annotation annotationtype return idclass i get compiler warnings for this but it seems to be a valid tool for many use casesthe warning for the example above is the annotation type id should not be used as a superinterface for idimpledited i just found this example from guice bindcreditcardprocessorclass annotatedwithnamesnamedcheckout tocheckoutcreditcardprocessorclasee this javadoc from nameshas anyone some information why this restriction exists or has some other use cases in mind,['java'] +76177,how to count in coredata aggregation i am learning core data and particularly working on aggregationcurrent what i want to do count the number of records from the table which is in tomany relationship with inverse relationship on some criteria currently i am doing this nsexpression ex nsexpression expressionforfunctioncount argumentsnsarray arraywithobjectnsexpression expressionforkeypathddname nspredicate pred nspredicate predicatewithformatddtype home nsexpressiondescription ed nsexpressiondescription alloc init ed setnamecountddevents ed setexpressionex ed setexpressionresulttypensinteger16attributetype nsarray properties nsarray arraywithobjected nsfetchrequest request nsfetchrequest alloc init request setpredicatepred request setpropertiestofetchproperties request setresulttypensdictionaryresulttype nsentitydescription entity nsentitydescription entityfornameddevent inmanagedobjectcontextselfcurrentaccount managedobjectcontext request setentityentity nsarray results selfcurrentaccount managedobjectcontext executefetchrequestrequest errornil nsdictionary dict results objectatindex0 nslogaverage birthdate for female heroes dict objectforkeycountddeventsits from jeff lemarcheedit and i have found my solution as nsfetchrequest request nsfetchrequest alloc init nspredicate pred nspredicate predicatewithformatddtype home request setpredicatepred nsentitydescription entity nsentitydescription entityfornameddevent inmanagedobjectcontextselfcurrentaccount managedobjectcontext request setentityentity nserror error nil nsuinteger count selfcurrentaccount managedobjectcontext countforfetchrequestrequest errorerrorit is working nicely but i want to do more request of such type at a time so i think this cannot be a preferred way of getting the count edit so i think the approach would be the appropriate one so can anyone tell me more efficient an preferred way of doing this thanks,['iphone'] +76193,why is ef4 code first so slow when storing objects i am currently doing some research on usage of db4o a storage for my web application i am quite happy how easy db4o works so when i read about the code first approach i kinda liked is because the way of working with ef4 code first is quite similar to working with db4o create your domain objects pocos throw them at db4o and never look backbut when i did a performance comparison ef 4 was horribly slow and i could not figure out whyi use the following entities public class recipe private list recipepreparations public int id get set public string name get set public string description get set public list tags get set public icollection preparations get return recipepreparationsasreadonly public void addpreparationrecipepreparation preparation this recipepreparationsaddpreparation public class recipepreparation public string name get set public string description get set public int rating get set public list steps get set public list tags get set public int id get set to test the performance i new up a recipe and add 50 recipeprepations then i stored the object in db4o like so iobjectcontainer db db4oembeddedopenfiledb4oembeddednewconfiguration recipedbdb4odbstorerecipe1dbclosethis takes around 130 msi store the stuff with ef4 in sql server 2008 express locally like this cookrecipesrecipesaddrecipe1cookrecipessavechangesand that takes 20 msnow how on earth is db4o 15 times faster that ef4sql am i missing a secret turbo button for ef4 i even think that db4o could be made faster since i do not initialize the database file i just let it grow dynamically,['c#'] +76197,how can i get all usb drives plugged in possible duplicateget list of usb devices im making a wpf appim looking for a way to list all plugged in usb devices thisks in my comboboxi can list all drives using driveinfogetdrives but is there a simple way to filter that to usb devicesthanx,['c#'] +76219,c object termination notification in a c program i have two reference counted objects king and heir heir needs to block until king is destroyed king is a reference counted object which will be destroyed when it is reference count goes to zero if heir holds a reference to king then kings reference count will never go to zero how can have heir block until king is destroyed,['c++'] +76223,or possible duplicatesare php short tags acceptable to usewhat does mean when seen in php is there any difference in using to signify a php block or using php if there is not why would anyone use php figure the file extension of php would give plenty of info about what type of code you are looking at,['php'] +76236,easy creation of properties that support indexing in c in c i find indexed properties extremely useful for examplevar myobj new myclassmyobj42 hello consolewritelinemyobj42however as far as i know there is no syntactic sugar to support fields that themselves support indexing please correct me if i am wrong for example var myobj new myclassmyobjfield42 hello consolewritelinemyobjfield42the reason i need this is that i am already using the index property on my class but i have getnumx getx and setx functions as follows public int numtargetslots get return makernumrefs public referencetarget gettargetint n return referencetargetcreate makergetreferencenpublic void settargetint n referencetarget rt makerreplacereferencen rt target trueas you can probably see exposing these as one indexable field property would make more sense i could write a custom class to achieve this every time i want the syntactic sugar but all of the boilerplate code just seem unnecessary so i wrote a custom class to encapsulate the boilerplate and to make it easy to create properties that can be indexed this way i can add a new property as followspublic indexedpropertyreferencetarget targetarray get return new indexedpropertyint referencetarget int n gettargetn int n referencetarget rt settargetn rt the code for this new indexedproperty class looks likepublic class indexedpropertyindext valuet actionindext valuet setaction funcindext valuet getfunc public indexedpropertyfuncindext valuet getfunc actionindext valuet setaction thisgetfunc getfunc thissetaction setaction public valuet thisindext i get return getfunci set setactioni value so my question is is there a better way to do all of this well to be specific is there a more idiomatic way in c to create an indexable field property and if not how could i improve my indexedproperty class edit after further research jon skeet calls this a named indexer,['c#'] +76238,moq using verifyset to check number of times called i am trying to use verifyset with moq to check the number of times a setter on a collaborating object is being called but when i put in the times portion of the call i get an error that the assignment operator is not valid in an expression treemocktimerverifysettimer timerprop value works finemocktimerverifysettimer timerprop value timesonce compile error,['c#'] +76245,jquery live event on ipadwhy does not it work i am using jquery to develop webapps on the ipad and it seems the jquery live event does not work this was the case when i was working with the sdk ipad emulator and now that i have the ipad to work on its still the same i was hoping it was an emulator fault running the same code on a web kit build works finei am just wondering if anyone else is having this problem if there is a fix or if it is me hoping someone can help as my code is becoming really bloated having to rebind clicks etc after ajax callsthanks,['jquery'] +76248,splitting a string separated by rn into a list of lines i am reading in some data from the subprocess modules communicate method it is coming in as a large string separated by rns i want to split this into a list of lines how is this performed in python,['python'] +76250,is there a difference between readonly and get do these statements mean the same thing int x get readonly int x,['c#'] +76258,fixing gaps in streamed usb data we have a hardware system with some fpgas and an ftdi usb controller the hardware streams data over usb bulk transfer to the pc at around 5mbs and the software is tasked with staying in sync checking the crc and writing the data to filethe ftdi chip has a busy pin which goes high while its waiting for the pc to do its business there is a limited amount of buffering in the ftdi and elsewhere on the hardwarethe busy line is going high for longer than the hardware can buffer 50100ms so we are losing data to save us from having to redesign the hardware i have been asked to fix this issuei think my code is quick enough as weve had it running up to 15mbs so that leaves an io bottleneck somewhere are we just expecting too much from the pcoshere is my data entry point occasionally we get a dropped bit or byte if the checksum does not compute i shift through until it does byte data is nearly always 4k void ftdi ondatabyte data listbyte buffer new listbytedatalength int index 0 while index rawfileheaderpacketlength 1 datalength if checksumcrc16data index rawfileheaderpacketlength 2 packet length 2 for 16bit checksum bufferaddrangedatasubarraybyteindex rawfileheaderpacketlength index rawfileheaderpacketlength 2 skip the two checksums we dont want to save them else index shift through rawfileadatabuffertoarray 0 buffercount,"['c#', '.net']" +76272,android references to a context and memory leaks i have read that it is a mistake and a source of memory leaks in android application to keep a longlived references to a contextbut i do not understand if it is ok to create an class that looks like this onepublic class helperclass private context context public helperclasscontext context thiscontext context public void myhelpermethod uses thiscontext and call it from an activitypublic class myactivity extends activity public void oncreatebundle savedinstancestate helperclass h new helperclassthis hmyhelpermethod,['android'] +76273,iphone performselectoronmainthread with return value i have the following method nsmutablearray getelementsnsstring theurland i wanted to know if there is a way to call that method using performselectoronmainthread so that i can get the return value so far i have tried withmyarray object performselectoronmainthreadselectorgetelements withobjecturl waituntildoneyesbut it does not work since performselectoronmainthread returns void how could i solve this,['iphone'] +76278,wrap long lines in python how do i wrap long lines in python without sacrificing indentation for example def fun print 0 here is a really long sentence with 1format3 5suppose this goes over the 79 character recommended limit the way i read it here is how to indent itdef fun print 0 here is a really long sentence with 1format3 5however with this approach the indentation of the continued line matches the indentation of the fun this looks kinda ugly if someone was to go through my code it would look bad to have uneven indentation because of this print statementhow do i indent lines like this effectively without sacrificing code readability,['python'] +76281,xcode 4 connecting outlets this page shows how easily i can connect outlets in xcode 4 but i cannot get it i right click and drag an outlet from the new referencing outlet circle and into my header where the object is declared but nothing happens has anyone used this thanks a lot,['iphone'] +76283,what is the most efficient way to get first and last line of a text file i have a text file which contains a time stamp on each line my goal is to find the time range all the times are in order so the first line will be the earliest time and the last line will be the latest time i only need the very first and very last line what would be the most efficient way to get these lines in pythonnote these files are relatively large in length about 12 million lines each and i have to do this for several hundred files,['python'] +76284,what is the difference between i and i i have seen them both being used in numerous pieces of c code and i would like to know when to use i or i i being a number variable like int float double etc anyone who knows this,['c#'] +76285,how to generate xsischemalocation attribute correctly when generating a dynamic sitemapxml with linq to xml i am generating a dynamic sitemapxmlaccording to sitemapsorg this is the header for a sitemapxmlxml version10 encodingutf8urlset xmlnsxsi xsischemalocation xmlns url urlurlsetso i am using linq to xml to generate the sitemapxmlxnamespace ns return new xelementns urlset new xattributexmlns new xattributexnamespacexmlns xsi new xattributexsischemalocation from node in new getnodes select new xelementns url new xelementns loc nodeloc new xelementns lastmod nodelastmod new xelementns priority nodepriority tostringthe commented line is the one i cannot get righthow can i set the xsischemalocation attributethanks,['c#'] +76291,making a dll com accessible i have a class library written in net that i would like to make available to vb6vba what i tried did not work obviously as i am asking this question here is what i didi created a class library project in visual studio 2010 express and put the code in a class modulei opened the project properties and went to assembly information and checked make com visible i went to advanced compile options and targeted net 20 it is very simple codei then removed all references expect for systemi built the project no warnings or errors and copied the dll out of the bin folder into cwindowssystem32i ran regsvr32 to register the dll and got the errorthe module mydlldll was loaded but the entrypoint dllregisterserver was not foundmake sure that mydlldll is a valid dll or ocx file and then try againclearly my first attempt was a bit naive could someone offer guidance,['.net'] +76302,starting with android java or python sl4a i just ordered an android smartphone and want to start playing around with creating my own applications now the question is which language to use the native java or python using sl4a former asei tend to python as i know it much better than java but i am wondering what i would be missing using a second class language on android on the sl4a website it is also stated to be alpha quality software which is not exactly encouragingi am also not quite sure what the limitations of the scripting environment are and if they would be problematic,"['java', 'python', 'android']" +76336,csv file written with python has blank lines between each row import csvwith openthefilecsv rb as f data listcsvreaderf import collections counter collectionsdefaultdictint for row in data counterrow10 1with openpythonworkthefile subset11csv w as outfile writer csvwriteroutfile for row in data if counterrow10 504 writerwriterowrowthis code reads thefilecsv makes changes and writes results to thefile subset1however when i open the resulting csv in microsoft excel there is an extra blank line after each recordis there a way to make it not put an extra blank line,['python'] +76345,javascript coding examples i am looking for an opensource javascript project from which i can learn about good coding practices patterns etcfor example the equivalent awesome code example from java would probably be the spring project internalsi have thought about taking a look at prototype jquery but are there any better ones by better i mean greater return on time invested i am talking proper substance as you would find in a java ruby project as opposed to a 50 line snippet of code to animate my buttons sorry that is probably a bit javascriptist,['javascript'] +76358,iphoneipad app using keyboard shortcuts with the availability of keyboards for ipads and iphones it makes sense to add keyboard shortcuts to apps now is it possible to do this in an app what are the relevant apis,['iphone'] +76360,stuck in a rut need help breaking through to the next level i am working on a humble website with my mediocre selftaught php skills and the current interface structure is like thisphp if a output somefunca else if b output anotherfuncb else if c output yetanotherfuncc else output default stuff html template top halfphp echo output html template bottom halfthis worked ok at first and seemed pretty well organized but the functionality required has grown by a factor of 10 and it is rapidly turning into an unmaintainable embarrassing mess and i do not know how to get out of iti feel that the functions being called for each situation are fairly wellwritten and focused but am at a loss as to how to handle the middlestep between the user and the functions that creates the layout and handles the returni have a feeling that mvc is one solution but i am having a hard time grasping how to go from here to therei apologize for any headaches or unpleasant memories the above code may have prompted thank you for your time,['php'] +76366,jqueryproxy usage i was reading the api about jqueryproxy it looks promising but i was wondering in what situation is this best use can anyone enlighten me,"['javascript', 'jquery']" +76369,throwing exceptions in switch statements when no specified case can be handled i have been writing c for the last 8 years and have become quite the defensive oop programmer working in a staticallytyped language you do things like validate arguments in methods and throw exceptions where you wouldnt in languages that are dynamic and more liberal i consider myself an expert in c and am looking for feedback from other wellversed c developers on best practiceslet us say we have a function that changes a password for a user in a system in an mvc apublic jsonresult changepassword string username string currentpassword string newpassword switch thismembershipservicevalidateloginusername currentpassword case uservalidationresultbasusername case uservalidationresultbadpassword abort return jsonresult with localized error message for invalid usernamepass combo case uservalidationresulttrialexpired abort return jsonresult with localized error message that user cannot login because their trial period has expired case uservalidationresultsuccess break now change password now that user is validatedmembershipservicevalidatelogin returns a uservalidationresult enum that is defined asenum uservalidationresult badusername badpassword trialexpired successbeing a defensive programmer i would change the above changepassword method to throw an exception if there is an unrecognized uservalidationresult value back from validateloginpublic jsonresult changepassword string username string currentpassword string newpassword switch thismembershipservicevalidateloginusername currentpassword case uservalidationresultbasusername case uservalidationresultbadpassword abort return jsonresult with localized error message for invalid usernamepass combo case uservalidationresulttrialexpired abort return jsonresult with localized error message that user cannot login because their trial period has expired case uservalidationresultsuccess break default throw new notimplementedexception unrecognized uservalidationresult value or notsupportedexception break change password now that user is validatedi always considered a pattern like the last snippet above a best practice for example what if one developer gets a requirement that now when users try to login if for thisorthat business reason they are suppose to contact the business first so uservalidationresults definition is updated to beenum uservalidationresult badusername badpassword trialexpired contactus successthe developer changes the body of the validatelogin method to return the new enum value uservalidationresultcontactus when applicable but forgets to update changepassword without the exception in the switch the user is still allowed to change their password when their login attempt should not even be validated in the first placeis it just me or is this default throw new exception a good idea i saw it some years ago and always after groking it assume it to be a best practice,['c#'] +76395,international phone number max and min what is the max and min digits for an international telephone numbercountry code area code phone number,"['java', 'c#', 'php']" +76404,how to convert trycast in c how to convert following vb code in to cdim request as httpwebrequest trycastwebrequestcreateaddress httpwebrequesti tried it using as operator in c but its not workingthank you in advance,"['c#', 'asp.net']" +76416,c0x lambda to function pointer in vs 2010 i am trying to use a lambda to pass in place of a function pointer but vs2010 cannot seem to convert it i have tried using stdfunction like this and it crashes and i have no idea if i am doing this rightinclude windowshinclude coniohinclude functionalinclude iostreaminclude concrthvoid main stdfunctionvoidvoid f void void stdcout hellon concurrencycurrentschedulerscheduletaskftargetvoidvoid 0 getchit seems strange to me that the compiler cannot convert such a lambda to a simple function pointer as it captures no variables also in the case that it did i wonder what can be doneis the type of each lambda unique so i could hack around with a template function using the lambdas type as a template argument to generate a unique static function that could be called instead and hopefully optimised outupdatedthe below seems to work but is it safeinclude windowshinclude coniohinclude iostreaminclude concrthtemplatetypename signaturestruct bind static signature method static void callvoid parameter methodparameter templatetypename signaturesignature bindsignaturemethodtemplatetypename signaturevoid scheduletasksignature method bindsignaturemethod method concurrencycurrentschedulerscheduletaskbindsignaturecall0void main scheduletask void stdcout hello scheduletask void stdcout theren getchupdated againso with the help given i have come up with the shortertemplatetypename signaturevoid lambdabindsignaturevoid struct detail static void bindvoid parameter signature method methodparameter return detailbindthis can be used to wrap a lambda with no closure of voidvoid into the equivalent function pointer it appears that this will become unnecessary in a later version of vs2010so how to get this to work for a lambda with closuresupdated againworks for closures in vs2010 no idea if it is safe thoughtemplatetypename signaturestruct detail2 static stdfunctionvoidvoid method static void bindvoid parameter methodparameter templatetypename signaturestdfunctionvoidvoid detail2signaturemethodtemplatetypename signaturevoid lambdabind2signature methodvoid detail2signaturemethod method return detail2signaturebind,['c++'] +76434,detecting the memory page size is there a portable way to detect programmatically the memory page size using c or c code,"['c++', 'c']" +76436,what is the best way to set a global variable in javascript i am wondering what the best way is to set a global variable with jquery javascript that can be used and updated by multiple functions i have a fairly over complex site that uses sliders i want to add a dynamic breadcrumb and thought that restructuring the code so that the various functions can read from one shared global variable would be much better than continuously passing the current clicked object name around,"['javascript', 'jquery']" +76489,are these two queries the same group by vs thistinct these two queries seem to return the same results is that coincidental or are they really the same1select titemnumber select top 1 itemdescription from transactions where itemnumber titemnumber order by datecreated desc as itemdescriptionfrom transactions tgroup by titemnumber2select thistincttitemnumber select top 1 itemdescription from transactions where itemnumber titemnumber order by datecreated desc as itemdescriptionfrom transactions ta bit of explanationi am trying to get a thistinct list of items from a table full of transactions for each item i am looking for the itemnumber the identifying field and the most recent itemdescription,['sql'] +76491,difference between string and text in rails i am making a new web app using rails and was wondering whats the difference between string and text and when should each be used,['ruby-on-rails'] +76493,storing user variables in database vs session in aspnet i am working with an aspnet application that stores most data in a database and not session i am wondering of the pros and cons of each and which is the better way to go for example you have a pretty busy site and instead of storing user specific variables in session there is a db table called user data and it can store all user specific data that can be accessed from any page by querying the database which is the better way to go session or database,['asp.net'] +76515,android how can i make a drawable array how can i make an array that handles some of my images so that i can use it like thisimageviewsetimageresourceimage1i hope i explained well,['android'] +76528,open uri in new tab silverlight hey so is there anyway i can use htmlpagewindownavigatenew urilink blank to open a uri in a new tab not new window which is in the same instance of internet explorercurrently using sl3 and it seems that whether its a new tab vs new window is based on browser optionsany help thanks,['c#'] +76541,using java to wrap over c i have a project written in c and i am looking to write a java gui as an interface to it the choice of java is fixed so i would need to learn how to be able to call the c code from java rewriting the c code is not an option i would like input on what tools can i use to achieve this wrappinghow much of the c code would i have to necessarily modify if any any other insightsfollow up questions that youd havethanks,"['java', 'c++']" +76547,is there an online interpreter for python 3 possible duplicatepython 3 online interpreter shell where can i find an online interpreter for python 3 i am learning python but cannot install it at work where i would like to do some practicethankssorry to repeat the question i cannot bump earlier posts and was just hoping there is one out there now,['python'] +76548,operator with events public void bar foo foo new foo foomyevent foo myevent foofireevent void foo myeventobject sender eventargs e foosendermyevent foo myeventhey i am a bit unfamiliar with events could someone tell me what the operator does with events,['c#'] +76559,need cursor at beginning of text in textarea i have this in my body and it works onloaddocumentformspostmessagefocusbut i need the cursor to be placed in the textarea at the beginning of any existing text not at the end this puts it at the endnote that i know nothing about javascript so be gentlethanks,['javascript'] +76560,emitting unencoded strings in a razor view as scottgu says in his blog post aby default content emitted using a block is automatically html encoded to better protect against xss attack scenariosamy question is how can you output a nonhtmlencoded stringfor the sake of simplicity pls stick to this simple case var html a hrefclick mea i want to emit the previous string as pure html code,['asp.net'] +76582,test if session is started how do you test to see if sessions are on this is not the waysession startifisset session echo sessions onbrelse echo sessions offbrsession destroyifisset session echo sessions onbrelse echo sessions offbr,['php'] +76584,does forms authentication work with web load balancers i am working on a web application that is using forms authentication authentication modeforms forms slidingexpirationtrue loginurluseraspxlogon timeout15 nameauthtoken authenticationi am seeing this cookie set in my browser when i log inthe question is what happens when i put this website in a load balanced model where is the aspnet session cookie being set i did not explicitly do it in code so i assume it is happening behind the scenes somewhere in aspnetalso if the session cookie is set by web server a i assume web server b would not recognize it and treat it as an invalid session if this is the case i probably do not want to use it right,['asp.net'] +76606,testing paperclip file uploading with rspec i do not really care about testing file uploads but since i have validates attachment presence etc in my model rspec is complainingso now i am creating my model with these attributes in the spec to try and shut it upattr name value for name title value for title content value for content pic file name examplejpg pic content type imagejpg pic file size 8192 pic updated at nilthis does not work thoughi found this so i tried something like thispostshould receivesave attached filesand returntruewhich does not work either how do i appease rspec,['ruby-on-rails'] +76609,google chrome inset boxshadow bug on windows not on mac better workaround this is still current on chrome 50375125 which is the latest windows release at the time of this writingbug is tracked hereso the problem is if youre on windows or linux and someone uses inset boxshadow on an element that also has borderradius you get a bug the borderradius is preserved but the inset boxshadow spills out of it as if it were still a square box it works as expected in chrome on mac os xpeople using textured backgrounds cannot use this hack because it requires an opaque border color it also only really works well on smaller radiustwo parts to this hack a little javascript jquery jqueryclient pluginif clientbrowser chrome clientos mac htmladdclassinsetradiushackand cssdiv mozborderradius 7px webkitborderradius 7px borderradius 7px mozboxshadow rgba0 0 0 04 1px 1px 4px 0 inset webkitboxshadow rgba0 0 0 04 1px 1px 4px 0 inset boxshadow rgba0 0 0 04 1px 1px 4px 0 inset padding 5px 10px marginbottom 10px maxwidth 120px htmlinsetradiushack div border 2px solid f cover the edges with the border margin 0 2px 0 2px and take back the extra pixels the border adds can i take a shower now this hack makes me feel grosshas anyone come up with a better workaround for this,"['jquery', 'css']" +76611,a forgiving dictionary i am wondering how to create forgiving dictionary one that returns a default value if a keyerror is raisedin the following code example i would get a keyerror for examplea one1two2print athreein order not to get one i would 1 have to catch the exeption or use geti would like to not to have to do that with my dictionary,['python'] +76615,in net development what is the breakdown of winformsdesktop developers versus aspnet developers what is the proportion of net developers who do winformsdesktop development vs aspnet development is there very much overlap are they very different skillsets,"['.net', 'asp.net']" +76616,how to cut the string in javascript so that it fits exactly two lines add at the end i have a requirement where in i have to thisplay the text for two lines add if its overflowingmy div width is fixedeven height can be considered as fixedactual text looks like this1lorem ipsum is simplydummy text of the printingand typesetting industry 2lorem ipsum is simply text of the printing and typesindustry expected1lorem ipsum is simply dummy text of the print2lorem ipsum is simply text of the printing and typi do not want to overload with pluginsthree dots jquery plugin does thati am planning to do just by cuttingsplit the string as div width is fixedthanks in advance,"['javascript', 'jquery']" +76618,python dictionary is thread safe some stated that python dictionary is thread safe does it mean i can or cannot modify the items in a dictionary while iterating over it,['python'] +76620,optimize managed to native calls what can be done to speed up calling native methods from managed codei am writing a program which needs to be able to manage arbitrarilysized lists of objects and retrieve information from them at high speed which it feeds into scripts scripts are bits of compiled c code i am writing a basic interface layer from the c native dllsoetc to the c net or mono management layernow i have been doing some testing and i have found that on average pinvoking a native method from managed code is something like 100 times slower than doing it all in managed all native and all managed are identically fast for referencethe syntax i was using isdllimporttestdllextern static public string test methodstring valuestring returnedvalue test methodhello worldis there a way to cache a pointer to the function some code of fast invoker that would increase speed after loading the native library that would solve the problem quite neatly so i doubt it exists pedit i did not specify but this needs to work on windows linux ubuntu at least and mac os x all for both x86 and x64 otherwise i wouldve gone with a ccli interface and been done with it but unless that works for all 3 platforms i cannot use it,['c#'] +76637,android number picker dialog does anyone have any dialogs that will allow a user to pick a number within a certain range it seems like this would be a fairly common need but i cannot find a common dialog for it and i would rather not have to spend the time creating my ownany help,['android'] +76654,iterate list of objects in ibatis i have a list of object where i want to iterate and access a particular field in ibatis sqlex public class studentstring idstring namei will pass as parameter a list of student objectliststudentand do iteration accessing the id for each object bean how do i do this,"['java', 'sql']" +76665,refactor namespace in visual studio i have a class in a namespace that i have used extensively throughout my solution as the number of classes in this namespace has grown i realize that it wouldve been a better design decision to place this class and a few others into a subnamespace is there any easy way to do this in visual studioc i am thinking something like the classrefactorrename featureperhaps an extension,['c#'] +76703,how would i use on duplicate key update in my codeigniter model i have a codeigniterphp model and i want to insert some data into the databasehowever i have this set in my raw sql queryon duplicate key update duplicateduplicate1i am using codeigniter and am converting all my previous incontroller sql queries to activerecord is there any way to do this from within the activerecordbased modelthanksjack,['mysql'] +76720,rotating a calayer 90 degrees how do i rotate a calayer 90 degrees i need to rotate everything include sublayers and the coordinate system,['objective-c'] +76722,how to make c datatable filter my datatable dtdata id id2 1 2 1 3dtdataselectid 1 one more rowsi want row id 1 and id2 3 how to make,['c#'] +76727,how to send email attachments with python i am having problems understanding how to email an attachment using python i have successfully emailed simple messages with the smtplib could someone please explain how to send an attachment in an email i know there are other posts online but as a python beginner i find them hard to understand,['python'] +76729,why are most string manipulations in java based on regexp in java there are a bunch of methods that all have to do with manipulating stringsthe simplest example is the stringsplitsomething methodnow the actual definition of many of those methods is that they all take a regular expression as their input parameters which makes then all very powerful building blocksnow there are two effects youll see in many of those methodsthey recompile the expression each time the method is invoked as such they impose a performance impacti have found that in most reallife situations these methods are called with fixed texts the most common usage of the split method is even worse it is usually called with a single char usually a a or a to split byso it is not only that the default methods are powerful they also seem overpowered for what they are actually used for internally weve developed a fastsplit method that splits on fixed strings i wrote a test at home to see how much faster i could do it if it was known to be a single char both are significantly faster than the standard split methodso i was wondering why was the java api chosen the way it is nowwhat was the good reason to go for this instead of having a something like splitchar and splitstring and a splitregexstring update i slapped together a few calls to see how much time the various ways of splitting a string would take short summary it makes a big differencei did 10 iterations for each test case always using the inputaapnootmieswimzusjetteun and always using or as the split argumentthis is what i got on my linux system it is an atom d510 box so it is a bit slowfastsplit stringtest 1 11405 milliseconds split in several piecestest 2 3018 milliseconds split in 2 piecestest 3 4396 milliseconds split in 3 pieceshomegrown fast splitter based on chartest 4 9076 milliseconds split in several piecestest 5 2024 milliseconds split in 2 piecestest 6 2924 milliseconds split in 3 pieceshomegrown splitter based on char that always splits in 2 piecestest 7 1230 milliseconds split in 2 piecesstringsplitregextest 8 32913 milliseconds split in several piecestest 9 30072 milliseconds split in 2 piecestest 10 31278 milliseconds split in 3 piecesstringsplitregex using precompiled patterntest 11 26138 milliseconds split in several pieces test 12 23612 milliseconds split in 2 piecestest 13 24654 milliseconds split in 3 piecesstringtokenizertest 14 27616 milliseconds split in several piecestest 15 28121 milliseconds split in 2 piecestest 16 27739 milliseconds split in 3 piecesas you can see it makes a big difference if you have a lot of fixed char splits to doto give you guys some insight i am currently in the apache logfiles and hadoop arena with the data of a big website so to me this stuff really matters something i have not factored in here is the garbage collector as far as i can tell compiling a regular expression into a patternmatcher will allocate a lot of objects that need to be collected some time so perhaps in the long run the differences between these versions is even bigger or smallermy conclusions so faronly optimize this if you have a lot of strings to splitif you use the regex methods always precompile if you repeatedly use the same patternforget the obsolete stringtokenizerif you want to split on a single char then use a custom method especially if you only need to split it into a specific number of pieces like 2ps i am giving you all my homegrown split by char methods to play with under the license that everything on this site falls under i never fully tested them yet have funprivate static string stringsplitcharfinal string input final char separator int pieces 0 first we count how many pieces we will need to store separators 1 int position 0 do pieces position inputindexofseparator position 1 while position 1 then we allocate memory final string result new stringpieces and start cutting and copying the pieces int previousposition 0 int currentposition inputindexofseparator int piece 0 final int lastpiece pieces 1 while piece lastpiece resultpiece inputsubstringpreviousposition currentposition previousposition currentposition 1 currentposition inputindexofseparator previousposition resultpiece inputsubstringpreviousposition return resultprivate static string stringsplitcharfinal string input final char separator final int maxpieces if maxpieces 0 return stringsplitcharinput separator int pieces maxpieces then we allocate memory final string result new stringpieces and start cutting and copying the pieces int previousposition 0 int currentposition inputindexofseparator int piece 0 final int lastpiece pieces 1 while currentposition 1 piece lastpiece resultpiece inputsubstringpreviousposition currentposition previousposition currentposition 1 currentposition inputindexofseparator previousposition resultpiece inputsubstringpreviousposition all remaining array elements are uninitialized and assumed to be null return resultprivate static string stringchopfinal string input final char separator string result find the separator final int separatorindex inputindexofseparator if separatorindex 1 result new string1 result0 input else result new string2 result0 inputsubstring0 separatorindex result1 inputsubstringseparatorindex 1 return result,['java'] +76744,enumerations why when i am an almostgraduating computer science student and throughout my coding career i have found very few instances where enumerations except for canonical cases such as representing the faces of a standard deck of cards are useddo you know of any clever ways that enums are used in everyday codingwhy are enumerations so important and in what situations should one be able to identify that building an enumeration is the best approach,['java'] +76753,do any tools use the hamcrest factory annotation i sat down to write a matcher today and decided to take a quick look at the jmock documentation to refresh my memory on the process and noticed a reference to the orghamcrestfactory annotation the documentation for the annotation statesmarks a hamcrest static factory method so tools recognise them a factory method is an equivalent to a named constructordo any tools actually use this annotation,['java'] +76766,fill list with default values possible duplicateautoinitializing c lists i have a list of integers that has a certain capacity that i would like to automatically fill when declared listint x new listint10is there an easier way to fill this list with 10 ints that have the default value for an int rather than looping through and adding the items,['c#'] +76767,android animation flip i need to create an animation flip a view and show another onethe width of currently shown view is decreased slowly to zero and after that the width of the viewtobeshown must be increased from zeroduring this time the height goes from the currentlyshownheight to slightlydecreasedheight and back againhow can i achieve this using a viewflipper,['android'] +76809,is wrapping stl idioms for readability a good idea i am currently working on a c project that needs to have as few external dependencies as possible and thus i am pretty much sticking to stl and boost until now i have been almost exclusively living in qtland when it comes to c in general i tend to use c and python when i cantoday i wanted to check whether a stdvector contained a certain item with qt i would do this like soqlist int listlistappend 1 listappend 2 listappend 3 if listcontains 2 do somethingnice and readable but stdvector has no contains method which was a surprise ok what would the stl idiom for something like that be searching around it seems to be thisstdvector int listlistpush back 1 listpush back 2 listpush back 3 stdvector int const iterator result stdfind listbegin listend 2 if result listend do somethingthat to me is hardly readable and much too verbose so i found myself writing a utility function that takes a vector and a value and returns bool depending on whether the value was found or not basically a templated contains method a wrapper for the above stdfind call i can then use that in a way that is similar to the qt examplei have several similar utility functions in mind that would wrap other stl idioms for no other reason but a perceived increase in readability what i want to know is is this a bad idea do other people do the same am i missing something crucial the code will be oss at one point and i would rather not do something idiosyncratic that other c devs would find strange,['c++'] +76825,how to import all submodules i have a directory structure as follows mainpy scripts init py script1py script2py script3pyfrom mainpy the module scripts is imported i tried using pkgutilswalk packages in combination with all but using that i can only import all the submodules directly under main using from scripts import i would like to get them all under scripts what would be the cleanest way to import all the submodules of scripts so that i could access scriptsscript1 from mainedit i am sorry that i was a bit vague i would like to import the submodules on runtime without specifying them explicitly in init py i can use pkgutilswalk packages to get the submodule names unless someone knows of a better way but i am not sure of the cleanest way to use these names or maybe the impimporters that walk packages returns to import them,['python'] +76834,add elements in a list of dictionaries i have a very long list of dictionaries with string indices and integer values many of the keys are the same across the dictionaries though not all i want to generate one dictionary in which the keys are the union of the keys in the separate dictionaries and the values are the sum of all the values corresponding to that key in each of the dictionaries for example the value for the key apple in the combined dictionary will be the sum of the value of apple in the first plus the sum of the value of apple in the second etci have the following but it is rather cumbersome and takes ages to execute is there a simpler way to achieve the same resultcomb dict for dictionary in list dictionaries for key in dictionary comb dictsetdefaultkey 0 comb dictkey dictionarykey return comb dict,['python'] +76838,prevent soft keyboard from being thismissed there are many questions related to how to programatically showhide the soft keyboardhowever as we all know the android back button will cause the keyboard to be thismissedis there a way to prevent the user from thismissing the keyboard with a back button pressi tried to capture the back button but when the keyboard is thisplayed onkeydown in my activity is not invoked when the back key is pressed and soft keyboard is visibleany suggestions would be greatly appreciated,['android'] +76869,how to read pdf form data using itextsharp i am trying to find out if it is possible to read pdf form data forms filled in and saved with the form using itextsharp how can i do this,['c#'] +76881,jsf hdatatable vs hpanelgrid in jsf hdatatable and hpanelgrid both create html tabletagswhat is the difference between both when to use one or the other,['java'] +76920,how to populate a toolstripcombobox i find it hard binding data to a toolstripcombobox it seems it does not have the valuemember and thisplaymember propertieshow to bind it,"['c#', '.net']" +76945,when is using call a good idea what are peoples opinions on using the call i have only very rarely seen it used but i think it is a very handy tool to use when you know that a class is going to be used for some default behaviour,['python'] +76949,sunspot highlights not appearing i have gone through the docs in github to find solutions for highlighting but it does not seem to work for memy job model has something like this block omitted some fields on purpose searchable do text name string name stored true time updated at time created at time expires oni have this which returns resultssearch sunspotsearchjob do keywords senior fields name highlight trueend 0 fl score hlsimpleprehl qfname text rows30 hlsimplepostendhl hlon qsenior fqtypejob deftypethismaxand getting the hits as such searchhits and here were the results of the query thisplaying the name searchresultscollectx xname senior associate executive membership senior international costing analyst senior process engineer deputy senior process manager senior engineer rotating equipment senior technical expert indonesia senior combustion engineer senior project engineer engineering manager senior substructure design specialist bangladesh senior supervision engineer superstructure bangladesh senior program and strategy development advisor consultant senior associate natural resource management specialist senior manager agriculture market development afghanistan senior material engineer main bridge bangladesh senior resident engineer main bridge bangladesh senior resident engineer main bridge bangladesh senior material engineer main bridge bangladeshand here comes my problem when i get the highlights none were returned searchhitscollectx xhighlightname nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil niland even this does not return highlight hits searchhitscollectx xhighlights am i missing other flags or arguments,['ruby-on-rails'] +76958,what are lifted operators i was looking at this article and am struggling to follow the vbnet example that explains lifted operators there does not seem to be an equivalent c example or tutorial i do not have much experience with operator overloading in general so trying to come to terms with the vbnet equivalent whilst reading up on nullable types probably is not the best place to startwould anyone be able to provide an explanation of lifted operators and how they are used by nullable types does it just mean that the nullable type does not itself overload operators and will use the operators from the underlying type that it representsthere does not seem to be much information on so about lifted operators so hopefully this can help some others out toothanks,"['c#', '.net']" +76971,list all currently open file handles possible duplicatecheck what files are open in python hellois it possible to obtain a list of all currently open file handles i presume that they are stored somewhere in the environment i am interested in theis function as i would like to safely handle any files that are open when a fatal error is raised ie close file handles and replace potentially corrupted files with the original filesi have the handling working but without knowing what file handles are open i am unable to implement this ideaas an aside when a file handle is initialised can this be inherited by another imported methodthank you,['python'] +76988,technical differences between aspnet and java servlets jsp my understanding of jsp is that every jsp page on first load is compiled into a java servlet is this the same for aspx pages of course not into a servlet but whatever the aspnet equivilant iswhat other technical differences should i be aware of with jsp and aspnet mvc 2,"['c#', 'java', 'asp.net']" +76992,c enablethisable debug messages of stdcouts on the fly is there a way to defineundefine debug messages using stdcout whenever inside a programi am aware that there are such things such as define ifndef but i was thinking is there a cleaner way to having a variable say debug onthat prints all of my debug data using stdcout consequently well have code like this for debugifndef debug do something usefulendifi find the above code cumbersome when you write 100s of debug codethankscarlo,['c++'] +77004,facebook integration in android application is there any api for facebook to integration in androidi got a requirement to publish images to facebook through android application please give links or suggestions regarding this,['android'] +77013,how to force keyboard with numbers in mobile website in android i have a mobile website and it has some html input elements in it like thisinput typetext nametxtaccessorycost size6 i have embedded the site into a webview for possible android 21 consumption so that it will also be an android applicationis it possible to get the keyboard with numbers instead of the default one with letters when this html input element is focusedor is it possible to set it for the whole application maybe something in the manifest file if it is not feasible for an html element,"['android', 'html']" +77020,qt eclipse integration and custom widget plugin what is the correct procedure to compile a custom widget with the eclipse integration plugin under windows with mingwi tried the following steps but i cannot see the widget in the widget barinstalled qt 461 for win32 with mingwinstalled eclipse helios 32bit tried with galileo tooinstalled qt eclipse integrator 161reconfigured qt for integration configure release qtnamespace qtcppintegrationcompiled plugin in release using eclipse tried with creator toocopied dll file e a file in folder ceclipsepluginscomtrolltechqtcppdesignerpluginswin32x86 161launched eclipse clean to reset plugins naturally the widget works well under qt designer and i can use it there correctly,['c++'] +77047,maximum value of unsigned char include stdiohint main unsigned char i0x80 printfdi1 return 0why does this program print 256 as i understand this since 0x80 0b10 and unsigned char has 8 bits the 1 should overflow after left shift and the output should be 0 not 256,['c'] +77051,end the ellipse problem with textviews whoa sdk whoaso i am attempting to add an ellipse to the end of my textview single line before it runs off screen i have read that ellipses are broke developing for 21 after google searching everyone seems to suggest setting inputtype to text and maxlines to 1 and you will get an ellipsethere are two problems with this1 the text runs off the screen but does not ellipse i can tell the text is running off the screen because only a half of a character is showing at the edge of the screen but it is not printing instead2 when i have inputtype set on my textview clicking my list item no longer works there is no highlighting when you click and the onlistitemclick handler does not firesowhat can i do herei would like to note that there are two ways one could ellipse if the entire word does not fit on the screen hide the entire word and add an ellipse or just take off enough characters so an ellipse will fit ideally the latter is what i wantthanks for your help,['android'] +77052,convert a bitmap to grayscale in android i am new to this site and i come with a question about androidis there any way to convert a bitmap to grayscale i know how to draw a grayscale bitmap using canvas operations but i really need the actual bitmap in gray colors or at least something that could be converted to a bitmap later ondo i have to implement it by hand pixel by pixel operationsi have searched a lot and still could not find anyone knows a easyefficient way to do itthanks a lot,['android'] +77056,aspnet mvc first access after some minutes slow then every following request is fast when i access any page of my aspnet mvc website first time then this first request is slow it needs about 45 seconds to load but every following request to any page is fastwhen i wait some minutes or a hour then every first request is slow again every following request is fasti think that iis 7 is compiling the code and keep it in memory after some time it will delete it from memory so it needs to compile it againwhat can i do that every first request is as fast as every following requestwithout precompiling my source if possiblethank you very much in advance,['asp.net'] +77058,url for sending a user to the app review page on devices app store whats the url to launch in order to bring the itunes app store to the front and open it to show the reviews page of an appi want to send my users to the write a review pagesome other so answers provided urls like the one below but it does not seem to workitmsappsitunesapplecomwebobjectsmzstorewoawaviewcontentsuserreviewsid12345678pagenumber0sortordering1any suggestions for a url thatll work on iphone and ipad,['iphone'] +77086,how to redefine a ruby constant without warning i am running some ruby code which evals a ruby file every time its date changes in the file i have constant definitions liketau 2 piand of course they make the interpreter thisplay the unwanted already initialized constant warning every time so i would like to have the following functionsdef if not definedtau 2 piredef without warningtau 2 pii could avoid the warning by writing all my constant definitions like thistau 2 pi unless definedtaubut it is inelegant and a bit wet not dryis there a better way to def if not defined and how to redef without warningsolution thanks to steveclass object def def if not definedconst value mod selfis amodule self selfclass modconst setconst value unless modconst definedconst end def redef without warningconst value mod selfis amodule self selfclass modsendremove const const if modconst definedconst modconst setconst value endenda 1redef without warning a 2fail unit test unless a 2module m b 10 redef without warning b 20endfail unit test unless mb 20this question is old the above code is only necessary for ruby 18 in ruby 19 p3t3ru5s answer produces no warning and is simply better,['ruby'] +77104,exception in initializer error i am using netbeans i did some things with bindings and now whenever i start my program before it even intializes the form it gives me an error the exception in thread main is ocuring before the form is even an intialized object yet the form is not even an object yet every line in my main causes an exception random stuff i do not understand it at all here is the error exception in thread main javalangexceptionininitializererror at obd2nermainobd2nerjava26caused by javalangclasscastexception at javalangclasscastclassjava2990 at orgjdesktopbeansbindingbindingconvertforwardbindingjava1312 at orgjdesktopbeansbindingbindinggetsourcevaluefortargetbindingjava844 at orgjdesktopbeansbindingbindingrefreshunmanagedbindingjava12 at orgjdesktopbeansbindingbindingrefreshbindingjava1207 at orgjdesktopbeansbindingautobindingtryrefreshthensaveautobindingjava162 at orgjdesktopbeansbindingautobindingbindimplautobindingjava199 at orgjdesktopbeansbindingbindingbindunmanagedbindingjava959 at orgjdesktopbeansbindingbindingbindbindingjava944 at orgjdesktopbeansbindingbindinggroupbindbindinggroupjava143 at obd2nerforminitcomponentsobd2nerformjava731 at obd2nerforminitobd2nerformjava75 at statusclinitstatusjava41 1 morejava result 1obd2nerform line 731 is bindinggroupbindsometimes it errors out on packthe exception in main does not even seem relevant because it occurs as soon as the program is run and every time i comment out a line it jumps to the next public void actionperformedactionevent evt jformattedtextfield2actionperformedevt jlabel8settextdata in que jlabel9setfontnew fontdejavu sans 0 14 jlabel9settextf grouplayout jpanel5layout new grouplayoutjpanel5 jpanel5setlayoutjpanel5layout jpanel5layoutsethorizontalgroup jpanel5layoutcreateparallelgroupgrouplayoutleading addjpanel5layoutcreatesequentialgroup addjpanel5layoutcreateparallelgroupgrouplayoutleading addjpanel5layoutcreatesequentialgroup add19 19 19 addjpanel5layoutcreateparallelgroupgrouplayouttrailing addjlabel7 addjlabel5 addjlabel6 add18 18 18 addjpanel5layoutcreateparallelgroupgrouplayoutleading addgrouplayouttrailing jformattedtextfield1 grouplayoutpreferred size 22 grouplayoutpreferred size addgrouplayouttrailing jcheckbox1 addgrouplayouttrailing jcheckbox11 addpreferredgaplayoutstylerelated addjpanel5layoutcreateparallelgroupgrouplayouttrailing addjformattedtextfield2 grouplayoutpreferred size 22 grouplayoutpreferred size addjcheckbox12 addjcheckbox2 addpreferredgaplayoutstylerelated addjpanel5layoutcreateparallelgroupgrouplayouttrailing addjformattedtextfield3 grouplayoutpreferred size 22 grouplayoutpreferred size addjcheckbox13 addjcheckbox3 addpreferredgaplayoutstylerelated addjpanel5layoutcreateparallelgroupgrouplayouttrailing addjformattedtextfield4 grouplayoutpreferred size 22 grouplayoutpreferred size addjcheckbox14 addjcheckbox4 addpreferredgaplayoutstylerelated addjpanel5layoutcreateparallelgroupgrouplayouttrailing addjformattedtextfield5 grouplayoutpreferred size 22 grouplayoutpreferred size addjcheckbox15 addjcheckbox5 addpreferredgaplayoutstylerelated addjpanel5layoutcreateparallelgroupgrouplayouttrailing addjformattedtextfield6 grouplayoutpreferred size 22 grouplayoutpreferred size addjcheckbox16 addjcheckbox6 addpreferredgaplayoutstylerelated addjpanel5layoutcreateparallelgroupgrouplayouttrailing addjformattedtextfield7 grouplayoutpreferred size 22 grouplayoutpreferred size addjcheckbox17 addjcheckbox7 addpreferredgaplayoutstylerelated addjpanel5layoutcreateparallelgroupgrouplayouttrailing addjformattedtextfield8 grouplayoutpreferred size 22 grouplayoutpreferred size addjcheckbox18 addjcheckbox8 addpreferredgaplayoutstylerelated addjpanel5layoutcreateparallelgroupgrouplayoutleading addgrouplayouttrailing jformattedtextfield9 grouplayoutpreferred size 22 grouplayoutpreferred size addgrouplayouttrailing jcheckbox19 addgrouplayouttrailing jcheckbox9 addpreferredgaplayoutstylerelated addjpanel5layoutcreateparallelgroupgrouplayoutleading addjcheckbox20 addjcheckbox10 addjformattedtextfield10 grouplayoutpreferred size 22 grouplayoutpreferred size addjpanel5layoutcreatesequentialgroup add4 4 4 addjpanel5layoutcreateparallelgroupgrouplayoutleading addjpanel5layoutcreatesequentialgroup addjlabel8 addpreferredgaplayoutstylerelated addjlabel9 grouplayoutpreferred size 256 grouplayoutpreferred size addjseparator1 grouplayoutpreferred size 474 grouplayoutpreferred size addcontainergapgrouplayoutdefault size shortmax value addgrouplayouttrailing jpanel5layoutcreatesequentialgroup addcontainergap346 shortmax value addjtogglebutton3 grouplayoutpreferred size 132 grouplayoutpreferred size addcontainergap jpanel5layoutsetverticalgroup jpanel5layoutcreateparallelgroupgrouplayoutleading addjpanel5layoutcreatesequentialgroup addcontainergap addjpanel5layoutcreateparallelgroupgrouplayoutbaseline addjlabel5 addjformattedtextfield1 grouplayoutpreferred size grouplayoutdefault size grouplayoutpreferred size addjformattedtextfield2 grouplayoutpreferred size grouplayoutdefault size grouplayoutpreferred size addjformattedtextfield3 grouplayoutpreferred size grouplayoutdefault size grouplayoutpreferred size addjformattedtextfield4 grouplayoutpreferred size grouplayoutdefault size grouplayoutpreferred size addjformattedtextfield5 grouplayoutpreferred size grouplayoutdefault size grouplayoutpreferred size addjformattedtextfield6 grouplayoutpreferred size grouplayoutdefault size grouplayoutpreferred size addjformattedtextfield7 grouplayoutpreferred size grouplayoutdefault size grouplayoutpreferred size addjformattedtextfield8 grouplayoutpreferred size grouplayoutdefault size grouplayoutpreferred size addjformattedtextfield9 grouplayoutpreferred size grouplayoutdefault size grouplayoutpreferred size addjformattedtextfield10 grouplayoutpreferred size grouplayoutdefault size grouplayoutpreferred size addpreferredgaplayoutstylerelated addjseparator1 grouplayoutpreferred size 0 grouplayoutpreferred size addpreferredgaplayoutstylerelated addjpanel5layoutcreateparallelgroupgrouplayoutleading addjcheckbox3 addjcheckbox1 addjcheckbox2 addjcheckbox4 addjcheckbox5 addjcheckbox6 addjcheckbox7 addjcheckbox8 addjcheckbox9 addjlabel6 addjcheckbox10 addpreferredgaplayoutstylerelated addjpanel5layoutcreateparallelgroupgrouplayouttrailing addjpanel5layoutcreateparallelgroupgrouplayoutleading addjlabel7 addjpanel5layoutcreateparallelgroupgrouplayouttrailing addjcheckbox13 addjcheckbox12 addjcheckbox11 addjcheckbox14 addjcheckbox15 addjcheckbox16 addjcheckbox17 addjcheckbox18 addjcheckbox19 addjcheckbox20 addpreferredgaplayoutstylerelated 42 shortmax value addjpanel5layoutcreateparallelgroupgrouplayoutbaseline addjtogglebutton3 addjlabel8 addjlabel9 addcontainergap jtabbedpane1addtabtab6 jpanel5 addjtabbedpane1 borderlayoutcenter bindinggroupbind pack editorfold please help i do not understand what information do you need from meedit it seems to all be code which i cannot touch i should probly add that this started with netbeans adding about 200 invalid imports import jcheckbox1 which i deleted,['java'] +77106,apache 41 httpclient post and get can anyone provide an example of how i could use get and post apache 41 httpclientbecause most of the example that i found are using 3x,['java'] +77108,removing the from windowlocationhash i have this simple scriptdocumentreadyfunctionvar yoyo windowlocationhashalertyoyobut i need to get rid of the symbol as i will be using the variable to locate div ids i have tried using remove but that does not seem to be working many thanks in advance,['jquery'] +77134,how to hidethisable only the first uinavigationbar i have been wandering how to hide remove thisable only the main or first navigation bar in the navigation controller so that i could put an image as a whole background screen but i could not find any solution did try hide the titleview in viewdidload of the main navigation controller but did not work tried using navigationbarhidden but it hides the whole navigation bar for the next stack of controllerso i am not sure how to do this to give you an example i would like to have something like this app the masters golf tournament if you look at screen 1 it does not have any nav bar at the top but when you touch any options it will push to a new view controller and have the nav bar appear as in screen 34 and 5hope anyone could help me with thisthanks a lot,['iphone'] +77142,possible to replace windowlocationhash i am wondering whether it is possible to change the hash in windowlocationhash and replace it with thisid or would i need to change the entire windowlocation,"['javascript', 'jquery']" +77162,how to put multiple widget sizes in one apk what i am trying to do is have a clock widget of different sizes ie 2x2 3x3 4x4 etc in one apk and a configuration activity to be able to select which size to addfrom what i have learned from documentationwidget size is specified in appwidgetprovider tag in respective xml filealso in that file i set up the configuration activity for that providerso it seems that size is a property of appwidgetprovider and i will need to somehow create another provider from the code in configuration activity of the first oneor am i getting this wrong and there is another wayis this possible at all i have been told that some widgets can do this thanks in advanceps i have read this and this first one explains how to put multiple wigets in one apk but it is not clear how to select between them in runtime second one is about changing layouts but not size,['android'] +77166,how to invoke non virtually the original implementation of a virtual method i have the following situationin a 3rd party library can not be modifiedclass a public virtual void m class b a public override void m in my own codeclass c b public override void m from cs implementation of method m i want to call as but not bs can iany tricks accepted reflection included i tried reflection already but using the methodinfo that i get from typeofa still generates a virtual call calling cs implementation with subsequent stack overflowderiving c from a is out of the question due to the complexity of reimplementing b,"['c#', '.net']" +77170,custom memory manager i am trying to implement a custom memory manager and i am wondering if there is a better way to implement this function as when i am asked about void pointer arithmetic several people thought that if i had a void in c something was very wrong allocates a page of memoryvoid objectallocatorallocatepage ifoastats pagesinuse config maxpages throw exception void buffer operator newoastats pagesize allocate memory no constructor call setup the pagelist genericobject pnewnode newbuffer genericobject construct genericobject for the pagelist pnewnodenext pagelist next pnewnode points to wherever pagelist pointed to pagelist next pnewnode pagelist points to pnewnode pnewnode null dont need this handle anymore buffer static castcharbuffer sizeofgenericobject move pointer to point after the generic object setup the freelist forint i0iconfig objectsperpage i static genericobject ppreviousnode null static variable to hold the previous node pnewnode newbuffer genericobject construct genericobject for the freelist pnewnodenext ppreviousnode ppreviousnode pnewnode buffer static castcharbuffer oastats objectsize move pointer by objectsize oastats freeobjects freelist next pnewnode oastats pagesinuse oastats allocations,['c++'] +77175,replacing a number in a string with jquery i have a string which has a number in it that i would like to replace with another numberiea href idmy linkblah blah 32 blah blahai know there is only going to be 1 number in this stringi can get this farvar my string amy linktextbut basically i do not know how to then perform a search on my string for a numeral and replace that number with something elseis that possible with jquerythanks for any ideas,['jquery'] +77183,how to make boostmake shared a friend of my class i have written a class with protected constructor so that new instances can only be produced with a static create function which returns shared ptrs to my class to provide efficient allocation i would like to use boostmake shared inside the create function however the compiler complains that my class constructor is protected inside boostmake shared i decided to my boostmake shared a friend of my class but i am puzzled about the syntax i triedtemplate class t class a1 class a2 friend boostshared ptrconnection boostmake sharedconst connectionmanagerptr const stdstringbut the compiler gived me syntax errors please help,['c++'] +77185,android crash reporting library pre froyo do you know any crash reporting library for androidi do not want to spend a lot of time to write my own reporting systemthe output can be send to the email or some kind of serveri know that google introduced crash reporting in froyo but i want something for older versions of the systemlet us sum up the answersandroidremotestacktrace sends raports to mail or php scriptacra sends reports to google docsandroid error reporter sends reports via http post request,['android'] +77186,how to thisable gcc warnings for a few lines of code in visual c it is possible to use pragma warning thisable also i found that in gcc you can override per file compiler flags how can i do this for next line or with pushpop semantics around areas of code using gcc,['c'] +77189,how can i get the number of queued jobs of a particular type in gearman i have a number of gearman clients sending a job say job1client new gearmanclientclientaddserverclientdobackgroundjob1 workloadit takes say 10 seconds to process this jobi want to track how many job1 jobs are waiting for a worker to work on them at any given time how can i do that,['php'] +77196,avoiding the main entry point in a c program is it possible to avoid the entry point main in a c program in the below code is it possible to invoke the func call without calling via main in the below program if yes how to do it and when would it be required and why is such a provision given int funcvoid printfthis is func n return 0int mainvoid printfthis is main n return 0,['c'] +77197,how to limit a table cell to one line of text using css i have a table of users where each row contains their names email address and such for some users this row is one text line high for some others two etc but i would like that each row of the table be one text line high truncating the resti saw these two questionsin fact my question is exactly similar to the first one but since the link is dead i cannot study it both answers say to use whitespace nowrap however this does not work maybe i am missing somethingsince i cannot show you the code i reproduced the problemstyle typetextcsstd whitespace nowrap overflow hidden width 125px height 25pxstylediv stylewidth500pxtable tr tdlorem ipsum here blablablablablablablablablablatd tdlorem ipsum here blablablablablablablablablablatd tdlorem ipsum here blablablablablablablablablablatd tdlorem ipsum here blablablablablablablablablablatd trtabledivwithout whitespace the table is 500px wide and the text takes more than one linebut whitespace nowrap makes the browser simply ignore the width directive and increase the width of the table until all data fits in one linewhat am i doing wrong thanks,['css'] +77208,can python be good alternative for web app that would otherwise be done in java ee can python be a good alternative to a web app that would otherwise be developed with java ee if so which python web app frameworks may be a good choice please see details about the app below i have asked a few people individually about this who have worked for a good amount of time on either or both of java ee and python web apps and got a few answers that indicated python might not such a good choice mainly due to ease of scaling which is one of the needs the other reason given was relative lack of python developers in the part of the world where the app is being developed we might be able to overcome the second one but not sure about the firstthe app in question is a financial domain b2b one with a few different types of users as in actors having different reallife roles eg buyers sellers some admin users will use an rdbms will have crud createreadupdatedelete plus search functionality for master tables some types of transactions involving both master and transaction tables with fairly straightforward not very complex logic and some reports to pdf for most all of the search screens queries around 80 or so features where the features mostly map to screens in the app not all though it will have a few types of batch jobs too for which the plan is to run them at times when the users are not permitted to use the app will have javascript and ajax on the front end will have the feature of sending emails to users not just for signup or resetting passwords but for transactionrelated info as well no programmatic reading of incoming emails thoughthe aim is for it to eventually to get a medium level of scale in terms of numbers of paying users and transactions not very high but not too small a number say in the range of 10 users of which 20 may be concurrently accessing the app in a time frame of 15 to 20 minutes it will be a saas software as a service appi know the question is very general and open ended and i expect some answers on the lines of it depends but still want to get some views from people who have worked on such thingsfeel free to ask more questions if needed to answer i will answer them except for anything that is confidentialthanksedit 1really appreciate all the answers i will take a little time to think about them and then get back with further questions original or in response to answers or comments if any,"['java', 'python']" +77224,how do i use glulookat properly i do not want to get into complex trigonometry to calculate rotations and things like that for my 3d world so glulookat seems like a nice alternative according to the documentation all i need to do is place 3 coordinates for the cameras position three for what i should be looking at and an up position the last made no sense until i assumed it had to be at right angles with the line of sight in the direction the top of the screen should beit does not work like that at all i have some python code this is the code which initialises some data and some mode code for when i enter this part of the gamedef initself selfgame over false selfz 30 selfx 0def transferself make opengl use 3d gameengage 3d4501100 glulookat003010gameengage 3d4501100 basically sets up the projection matrix to have a 45 degree angle of view and near and far coordinates of 01 and 100the first glulookat puts the camera in the correct position nicelyi have a cube drawn with the centre of 0 and it works fine without glulookat before i draw it i have this codeglulookatselfx0selfz010if gamekeykey up selfz 20gameget fpsif gamekeykey down selfz 20gameget fpsif gamekeykey left selfx 20gameget fpsif gamekeykey right selfx 20gameget fpsnow from that the up position should always be the same as it is always at right angles what i would have thought it would do is move forward and back the zaxis with the up and down keys and left and right through the xaxis with the left and right keys what actually happens is when i use the left and right keys the cube will rotate around the eye being accelerated by the keys the up key causes another cube from nowhere to slice through the screen and hit the first cube the down key brings the mysterious cloned cube back this can be combined with the rotation to give a completely different outcome as the documentation said would arisewhat on earth is wrongthank you,['python'] +77236,changing jquery ui button size i have been using the jquery ui button all over my page however i have not found a way around what seems to be a simple problem i want some of my buttons to be smaller than the other this should be as simple as setting the css of the button text to something like font 8em however jquery ui takes your dom element and wraps itbutton classuibutton uibuttontextonly uiwidget uistatedefault uicornerall span classuibuttontextbutton labelspanbuttonso if i have a button clasmallbuttonsmall buttonbutton jquery will place the text in a child span any font size given to the smallbutton class will be ignoredthere is got to be a way around this without hacking at how jquery makes its buttons any ideas,"['javascript', 'jquery']" +77245,php calculate persons current age i have birth dates on my site in format 12011980person date string daymonthyearwant to add an oldness of the person like currently 30 years 2010 1980 30 yearsbut makin the function just on years cannot give the perfect resultif person birth date is 12121980 and current date is 01012010 the person does not have 30 years old it is a 29 years and one monththere must be a calculation on targeting both year month and day of birth with comparison of current date0 parse the datesbirth date daymonthyearday birth daymonth birth monthyear birth yearcurrent date daymonthyearday current daymonth current monthyear current year1 year comparison 2010 1980 write 30 let it be total year variable2 compare the months if birth date month is bigger than current month like 12 in birth and 01 current do minus one year from total year variable 30 1 29 if do minus happened finish the calculations at this point else go the next 3 step3 else if birth month current month total year total year 30 4 else if birth month current month total year total year 30 and check the day in this step ifbirth day current day total year total year else if birth day current day total year total year 1 else if birth day current day total year total year 5 echo total year my php knowledge is not good hope you can helpthanks,['php'] +77256,changing the url without reloading the page i would like to know if it is possible to change the contents of the url in the browser without reloading the pagei use jquery and ajax to load new parts of my page when i choose product one the direct link would be mysitecomproduct1 and for product two would be mysitecomproduct2 but i do not want to reload the site to these pages,"['javascript', 'jquery', 'html']" +77266,google maps v3 loading infowindow content via ajax what is the best way to load content into my infowindow using ajaxright now i am getting a similar effect using iframes but i am not that that happy with iti thought this would be straight forward but its confusing me for some reason this is how its working right nowvar markers var infowindow new googlemapsinfowindow eachjsonparseaulas functioni a var latlng new googlemapslatlngaaulalat aaulalng var marker new googlemapsmarker position latlng title aaulatitle googlemapseventaddlistenermarker click function infowindowclose infowindowsetcontentdiv classinfowindow contentiframe srcaulasshow aaulaid iframediv infowindowopenmap marker markerspushmarker it would be easy to grab the content via ajax just before the infowindowsetcontent call but i want to make the ajax call only when the infowindow opens any thoughtsbtw i am using jqueryas was suggested in the answer i decided to move the calls to setcontent and open to a separate function for those interested the code that solved this wasfunction load contentmarker id ajax url aulasshow id success functiondata infowindowsetcontentdata infowindowopenmap marker then change the listener googlemapseventaddlistenermarker click function infowindowclose load contentmarker aaulaid markerspushmarker,['jquery'] +77271,how can i pass attribute value from iframe to parent in javascript how can i pass attribute value from iframe to parentie iframe frame1 has a ida1 href how can i get value of href in my parent page,['javascript'] +77278,programming for android as a blind person i have a friend who is quite a capable programmer especially considering that he is blind now he would like to start developing for android but the problem i see him running into is that there appears to be no accessibility features for the android emulator ideally he would be able to have his computer read the contents of the android emulation screen to him however at least from what i have seen the contents of the android screen and the buttons that can be used to manipulate the emulation android etc are all invisible to a screen readerdoes anyone know of a workaround for thisupdate i found what looks like a promising resource here it is a texttospeech library for android developed by t v raman of google i am still looking for more information from the community though,['android'] +77283,override private function in javascript i am monkeypatching some of the jquerys draggable codethe goal is to avoid modifying the original source files and patch dynamically one of the internal functionsthe function generateposition is declared like thisfunction widgetuidraggable uimouse generateposition functionevent jqueryis it possible to achieve the dynamic replacement of itso it calculates the snapping grid relative to the top of parent element and not relative to the top of element being dragged see here for more details,"['javascript', 'jquery']" +77307,is returning void valid code i found out that the following code gets accepted by visual c 2008 and gcc 43 compilersvoid foovoid bar return fooi am a bit surprised that it compiles is this a language feature or is it a bug in the compilers what do the cc standards say about this,"['c++', 'c']" +77309,c compiler nostdlib option how is this possible not to include stdlib mscorlibdll to my c application when compiling it as far as i know all classes inherit systemobject class which is defined in mscorlibdll what is more types such as int are just aliases eg for systemint32 which are also defined in mscorlib is this option ever used,"['c#', '.net']" +77314,mkmapview with address is there a way to make the mkmapview place a pin with a given address without using the coordinatesthanks,['iphone'] +77316,foreign key to one of many tables the usual way of setting a foreign key constraint is to choose which table the foreign key will point toi am having a polymorphic relation between 1 table and a set of tablethat means that this table will have a relation with one of those tables in the setegimages person id person typesubordinates id col1 col2col9products id cola colbcolzin the above example if person type is subordinates then person id should be a foreign key to subordinatesid and the same goes with productsso i wonder is it possible to have a foreign key to one of many tables or do you have to specifically set which table it points to when you assign onethis question is for both mysql and postgresqlthanks,['mysql'] +77318,odd situation for cannot reference this before supertype constructor has been called why does not this code compilepublic class a public class b extends a public ba a void foo a a new a new ba ajava717 cannot reference this before supertype constructor has been calledcompilation is successful if either of these changes are madeb is private instead of publicline 7 reads new ba instead of new ba using javac version 160 20,['java'] +77334,why does the android emulator report unknown virtual device when the device is in my user directory i installed all the prerequisites for android development i created a virtual device through eclipse and tried to run the hello world sample application in that device i received the following error messageemulator error unknown virtual device name android21device emulator could not find virtual device named android21devicei get the same error when i try to start the device from the command line and through the sdk programi can see the device directory and files at dusersanthonyandroidavdandroid21deviceavd,['android'] +77349,how do you set the default device in the iphone simulator every time i switch xcode between debugging on my iphone and running in the simulator it resets the simulated device i want to run the simulator as an iphone device but it keeps changing back to ipad does anyone know how to set the configuration so that the simulator defaults to an iphone devicei can switch the hardware to iphone inside the simulator but when i go back to xcode and run a build debug it reopens the app inside an ipad the only way i can get it to switch is by using the overview menu in xcode the choices i see are ipad simulator 32 and iphone simulator 40and when i switch between device and simulator then it always goes back to ipad,['iphone'] +77351,what is the difference between what is the difference between the tag and the tag in t4,['.net'] +77357,want html form submit to do nothing i want an html form to do nothing after it has been submitted action is no good because it causes the page to reload basically i want an ajax function to be called whenever a button is pressed or someone hits enter after typing it data yes i could drop the form tag and add just call the function from the buttons onclick event but i also want the hitting enter functionality without getting all hackish,"['javascript', 'html']" +77358,java gpu programming is it possible to do gpu programming in java i mean without using native librariesand how much of a performance improvement can one expect when we switch over to gpus editi am not looking at game programming i want to do hard core number crunching,['java'] +77364,how to open url from string in webview for iphone i want to just open a url from my stringmy string is already having url i just want to show in uiwebviewmystringsensorfalselcitransitlayertrafficsaddr131224103865daddr1310664103857132nsstring urlstring mystring absolutestringnsstring urladdress mystring nsurl url nsurl urlwithstringurlstring nslog url is url its null url requst objectnsurlrequest requestobj nsurlrequest requestwithurlurlnslog url req is urlload the request in the uiwebviewwebe loadrequestrequestobji am getting this errorselcitransitlayertrafficsaddr131224103865daddr131066410385713220100802 132008253 wat2eat5332207 nscfstring absolutestring unrecognized selector sent to instance 0x1ac57020100802 132008267 wat2eat5332207 terminating app due to uncaught exception nsinvalidargumentexception reason nscfstring absolutestring unrecognized selector sent to instance 0x1ac57020100802 132008283 wat2eat5332207 stack,"['ios', 'iphone']" +77385,differences and advantages of surfaceview vs glsurfaceview on android i am currently playing around with 2d graphics in android and have been using a plain old surfaceview to draw drawables and bitmaps to the screen this has been working alright but there is a little stutter in the sprite movement and i am wondering the feasibility to do a real time but not terrible fast game with this i know glsurfaceview exists which uses opengl but i am curious as to the extent to which this makes a difference is a plain surfaceview hardware accelerated or do i need to use opengl what type of speed difference could i expect from switching to opengl and how much altering of code would it require to switch the game logic is all in a separate object that provides an ordered array of drawables to the surfaceview,['android'] +77396,using image created with cgbitmapcontextcreate as an opengl texture i am generating an image using quartz 2d and i want to use it as an opengl texturethe tricky part is that i want to use as few bits per pixel as possible so i am creating cgcontext as followingint bitspercomponent 5int bytesperpixel 2int width 1024int height 1024void imagedata mallocwidth height bytesperpixelcgcolorspaceref colorspace cgcolorspacecreatedevicergbcgimagecontext context cgbitmapcontextcreateimagedata width height bitspercomponent width bytesperpixel colorspace kcgimagealphanoneskipfirstdraw things into context release memory etcas stated in the documentation here this is the only supported rgb pixel format for cgbitmapcontextcreate which uses 16 bits per pixelso now i want to upload this imagedata which looks like 1 bit skipped 5 bits red 5 bits green 5 bits blue into an opengl texture so i should do something like thisglgentextures1 textureglbindtexturegl texture 2d textureglteximage2dgl texture 2d 0 gl rgba width height 0 gl rgba gl unsigned short 5 5 5 1 imagedata that would not work because in this call i have specified pixel format as 5 red 5 green 5 blue 1 alpha that is wrong but it appears that there is no format that would match core graphics outputthere are some other options like gl unsigned short 1 5 5 5 rev but those wont work on the iphonei need some way to use this imagedata as a texture but i really do not want to swap bytes around manually using memset or such because that seems terribly inefficient,['iphone'] +77398,using on sqldatareader i know i asked a related question earlier i just had another thought using sqlconnection conn new sqlconnectionblah blah usingsqlcommand cmd new sqlcommandsqlstatement conn connopen do i need to put this in using as well sqldatareader dr cmdexecutereader whiledrread read here the argument is that since the sqldatareader dr object is not a new object like the connection or command objects its simply a reference pointing to the cmdexecutereader method do i need to put the reader inside a using now based on my previous post it is my understanding that any object that uses ithisposable needs to be put in a using and sqldatareader inherits from ithisposable so i need to put it am i correct in my judgement i am just confused since its not a new object would it cause any problems in thisposing an object that simply is a reference pointer to the commandmany thanks,['c#'] +77418,how to create a hardlink in c how to create a hardlink in c any code snippet please,"['c#', '.net']" +77452,aspnet mvc ajax with htmlvalidationmessagefor i am used to the aspnet webforms easy way of doing ajax with updatepanels i understand the process is much more artisanal with mvcin a specific case i am using data annotations to validate some form inputs i use the htmlvalidationmessagefor helper to show an error message if i want to use ajax to post this form and show this error message what would be the process is it possible to keep the htmlvalidationmessagefor and make it work with ajaxthank you,['jquery'] +77470,can you use static constants in php i expected the following to work but it does not seem tophpclass patterns public static const email az09 az09 az09az26ix public static const int d public static const username wi get syntax error unexpected t const expecting t variable,['php'] +77471,will new operator return null possible duplicatewill new return null in any case say i have a class car and i create an object car newcar new carifnewcarnull is it valid to check for null if new runs out of memory,['c++'] +77488,problem using abstract factory i am using an abstract factory to create user interface components such as dialogs the abstract factory used is returned from a currently selected generic inode which is the base class for several different types of node so for instance if i want to add a new node of the same type as the selected node the scenario goes something like thisplease note this is semipseudo codeuser clicks node and the node gets stored for later usevoid ontreenodeselectedinode node selectednode nodeuser clicks add on the user interfacevoid onaddclicked ifactory factory selectednodegetfactory dialog dialog factorycreateadialogparentwidget dialogshowwhich all seems fine the problem comes when i want to edit the selected nodevoid oneditclicked ifactory factory selectednodegetfactory dialog dialog factorycreateeditdialogselectednode parentwidget dialogshowoh dear i am passing in an inode object at some point i am going to have to downcast that to the correct node type so the dialog can use it properlyi have studied the postgresql admin 3 source code and they do something similar to this they get round it by doing something like thisfobjectfactoryclasscreatedialogiobject object fobjectdialog dialog new fobjectdialogfobjectobjectyeck castthe only way i can think around it and still able to use my factories is to inject the node itself into the factory before it is returnedfoonode inode foonodefactory foonodegetfactory foonodefactorysetfoonodethis return foonodefactory so then my edit event can do thisvoid oneditclicked ifactory factory selectednodegetfactory dialog dialog factorycreateeditdialogparentwidget dialogshowand it will use the injected node for contexti suppose if there is no injected code the createeditdialog could assert false or somethingany thoughtsthanks,['c++'] +77490,android memory leak in notification service i have a service which creates a notification and then updates it with certain information periodically after about 12 mins or so the phone crashes and reboots i believe it is caused by a memory leak in the following code to do with how i am updating the notification could someone please checkadvise me if this is the case and what i am doing wrongoncreatemnotificationmanager notificationmanager getsystemservicenotification servicecreatenotificationprivate void createnotification intent contentintent new intentthismainscreenclass contentintentsetflagsintentflag activity clear top intentflag activity single top pendingintent appintent pendingintentgetactivitythis0 contentintent 0 contentview new remoteviewsgetpackagename rlayoutnotification contentviewsetimageviewresourceridimage rdrawableicon contentviewsettextviewtextridtext notification new notification notificationwhensystemcurrenttimemillis notificationcontentview contentview notificationcontentintent appintentupdatenotificationprivate void updatenotificationstring text contentviewsettextviewtextridtext text mnotificationmanagernotify0 notificationthanks in advance,['android'] +77492,why does this do what it does i found this interesting item in a blog todaydef abc try return true finally return falseprint abc is abccan anyone tell why it does what it doesthankskr,['python'] +77496,event onbrowserclose for google chrome extension i am developing an extension for google chrome my background script everytime authorizes on a server that uses the xmpp api and subscribes for a pubsub node i need to unsubscribe on the exit otherwise the dummy subscriptions will remain on the server is there any onbrowserclose event in the google chrome extension apis,['javascript'] +77500,how to use inttryparse with nullable int i am trying to use tryparse to find if the string value is an integer if the value is an integer then skip foreach loop here is my codestring strvalue 42 if inttryparsetrimstrvalue intval false break intval is a variable of type intnullable int how can i use tryparse with nullable int,['c#'] +77507,any way to make jqueryinarray case insensitive title sums it up,['jquery'] +77516,paste text on android emulator is there anyway to copypaste desktops clipboard content to editview on android emulator just for the sake to ease developmenttest,['android'] +77518,css pagebreakbefore always except the first time i am trying to create a prettyprint html page i need to force a pagebreak between toplevel constructs so i added a css class to the toplevel element of each construct and set pagebreakbeforealways in the css for that class egbodydiv classprettyprint div classtoplevel div div classtoplevel divdivbodyprettyprint toplevel pagebreakbeforealways my problem is i get a blank page before the first toplevel element which makes perfect sense considering what pagebreakbeforealways is supposed to do but i do not want itso one option is to not include the toplevel class in the first element or to provide a new firsttoplevel class that does not set pagebreakbeforealways and set it for the first toplevel element and then use toplevel for all the others i could do it easily enough but it seems like it is violating separation of concernsso i was wondering if there was a way to do this in css to set a rule that would apply only to the first toplevel child of prettyprintany ideas would be appreciated,['css'] +77536,ruby on rails before filter and prepend before filter ordering is in the following example before filter foobefore filter barbefore filter wahprepend before filter heeheeprepend before filter hahaso then the execution orders will behaha heehee foo bar wah note that haha is actually before heeheeand is there a reason not to list haha and heehee first in the first place but actually use prepend,['ruby-on-rails'] +77538,why is reflection so expensive in net possible duplicatewhat is the cost of reflection does anyone have a good explanation of the generally accepted mantra that reflection bad performance for example how expensive is it to iterate over a types properties collection and extract all property values from an instance of this type compared to just accessing all the properties directly one level of magnitude two what does it depend on is it predictable at all what is happening under the hoodedit thanks for the answers so far i have looked into some the links you provided and it seems that there is a vast gap of estimates out there regarding reflection on properties compared to direct access from 25 times slower to 200 times slower this does not seem very reasonable to me some of you mentioned performance improvements in later versions of net so let be narrow my question to net 40 does anyone have any benchmarks for that,['.net'] +77550,converting latitudelongitude into city name reverse geolocating i am working on a job board in codeigniter php jquery where employers enter their location and we use google maps api to plot it while this has had awesome usability results the problem is when we try to thisplay these locations to job seekers they are muddled and hard to visually thiscern they read like this 02905 2 miles away171 john st 4 miles away providence ri 10 miles awayi want to be able to reverse geolocate from a longitudelatitude to a set level ideally city name so that in the search results i can have the locations be listed like this providence ri 10 miles away providence ri 5 miles away cranston ri 16 miles awayis there a way to reverse geocode to city i see many examples for ways to reverse geocode to nearest addressable location but no way to control the levelhope that is clear feel free to comment with any questions you need clarification on,"['php', 'jquery']" +77554,smart jscrollpane autoscrolling i am attempting to implmement smart autoscrolling on a jscrollpane containing a jtextpane the jtextpane is used for logging my app in color however i am running into a wall trying to do smart autoscrolling by smart autoscrolling i do not mean blindly autoscrolling every time something changes i mean checking to see if your scrolled all the way down then autoscroll however no matter what i do it either always autoscrolls or does not at allas a test script heres the setup the jframe has been left outfinal jtextpane textpane new jtextpanetextpaneseteditablefalsefinal jscrollpane contentpane new jscrollpanetextpanecontentpanesetverticalscrollbarpolicyjscrollpanevertical scrollbar alwaysand heres the ugly auto add test loopwhile true try threadsleep10 swingutilitiesinvokelaternew runnable override public void run try jscrollbar scrollbar scroll boolean precheck scrollbargetvisibleamount scrollbargetmaximum scrollbargetvalue scrollbargetvisibleamount scrollbargetmaximum systemoutprintlnvalue scrollgetvalue visible scrollbargetvisibleamount maximum scrollbargetmaximum combined scrollbargetvalue scrollbargetvisibleamount vismax scrollbargetvisibleamount scrollbargetmaximum combmax scrollbargetvalue scrollbargetvisibleamount scrollbargetmaximum eval precheck styleddocument doc textpanegetstyleddocument docinsertstringdocgetlength fagahsidfnjasdkfjsdn docgetstyle if precheck textpanesetcaretpositiondocgetlength catch badlocationexception ex exprintstacktrace catch exception e eprintstacktrace its not pretty but it gets the job done heres though the relevant check boolean precheck scrollbargetvisibleamount scrollbargetmaximum scrollbargetvalue scrollbargetvisibleamount scrollbargetmaximum if precheck textpanesetcaretpositiondocgetlengththats the part thats been giving me trouble there is first a check to see if the bar is visible but unusable not enough text making the bar the full length then if the bottom of the bar is equal to the maximum in theory that should work however nothing including moving the check around has gotten the results i would likeany suggestions not a duplicate of this or this as they are wanting it to always scroll not just sometimes,['java'] +77556,using multiple nsuinteger enums as a parameter to a method i am trying to make a method with a similar format to the setautoresizingmask method of nsview i want to have someone be able to specify multiple values that i declared in my enum nsheightsizable nswidthsizable like in autoresizing mask how can i do this,['objective-c'] +77568,data structure for matching sets i have an application where i have a number of sets a set might be4 7 12 18unique numbers and all less than 50i then have several data items1 1 2 4 7 8 12 18 23 292 3 4 6 7 15 23 34 383 4 7 12 184 1 4 7 12 13 14 15 16 17 185 2 4 6 7 13 15data items 1 3 and 4 match the set because they contain all items in the seti need to design a data structure that is super fast at identifying whether a data item is a member of a set includes all the members that are part of the set so the data item is a superset of the set my best estimates at the moment suggest that there will be fewer than 50 setsmy current implementation has my sets and data as unsigned 64 bit integers and the sets stored in a list then to check a data item i iterate through the list doing a set data set comparison it works and it is space efficient but it is slow on and i would be happy to trade some memory for some performance does anyone have any better ideas about how to organize thiseditthanks very much for all the answers it looks like i need to provide some more information about the problem i get the sets first and i then get the data items one by one i need to check whether the data item is matches one of the setsthe sets are very likely to be clumpy for example for a given problem 1 3 and 9 might be contained in 95 of sets i can predict this to some degree in advance but not wellfor those suggesting memoization this is this the data structure for a memoized function the sets represent general solutions that have already been computed and the data items are new inputs to the function by matching a data item to a general solution i can avoid a whole lot of processing,"['c++', 'c']" +77569,jquery ui tabs minimal styling in my application i have so far avoided needing to load any jquery stylesheets at all but the uitabs plugin seems to need some css to work at all ok fine but the examples have you loading all the ui styles and perhaps more important the tab styling totally ruins my own look and feelis there any place to learn how i can provide just enough css for the tabs to work so i can retain my own styling i do not mind a minimal amount of styling help to arrange the tabs nicely or something but the background image the colors they clash really bad with my own stylingoh and no thanks to the theme roller which i am sure is nice for some people just not in this case thanks,"['jquery', 'css']" +77598,is plain vanilla javascript better than using frameworks like jquery or mootools i am wondering if it is a good idea to rely on frameworks like jquery or mootools or should we just use plain javascriptapart from avoiding the reinvention of wheel do they add any specific valuesince the frameworks are open to the public can there be possibility of exploitation of any security holes that might appear of course unintentionally in the frameworksare there any other points that are to be considered when choosing a framework or otherwise,"['javascript', 'jquery']" +77626,jquery ajax timeout undefined i was trying out example jquery examples and to my surprise i got an error state for an ajax call mentioning that timeout is not defined when i removed timeout attribute it worked finei downloaded jquery few days back so i am pretty sure it is not a version problemi was trying with firefox368 and not any other browser why would this occuredit code snippet moved from the comments to the questionajax type get datatype json url phpserviceproxy timeout 50 success functionreply note original code snippet provided was missing a comma here error function xhr textstatus errorthrown,['jquery'] +77627,how to store key value pair in two dimensional array and hashtable using jquery can someone please redirect me to the right link or give an example of how to work with two dimensional array or hashtable in jquery i tried google but did not get the answer i want to avoid using any plugins all i want to do it store some information and retrieve them like hashtable way,['jquery'] +77628,how to get the first inner element so i want to get the first a tag in this div this is really driving me nuts thanks for any help div idpgd classalbum onmouseoverloadthis a classdl hrefdownloadadivjavascriptfunction loaddl var id dlattrid var elemnt idfirstattrid,"['javascript', 'jquery']" +77642,what is an iterators default value for any stl container that i am using if i declare an iterator of this particular container type using the iterators default constructor what will the iterator be initialised to for example i have stdlistvoid address liststdlistvoiditerator iterwhat will iter be initialised to,['c++'] +77651,content is not allowed in prolog i am trying to convert xml to html using xslt am using javaxmltransform to do this in javait was working fine until i bumped into some xml it said the following error fatal error 11 content is not allowed in prolog javaxxmltransformtransformerconfigurationexception javaxxmltransformtransformerconfigurationexception javaxxmltransformtransformerexception orgxmlsaxsaxparseexception content is not allowed in prologso i made sure there is no character before the xml declaration i even took care of bom using the solution still no luck and it happens only for one xml i even opened the xml in editor and saved it in a file with utf8 encoding this is driving me crazy any idea update you get this error when you have given the wrong path for the xsl file and a file not found exception happensthis was my case it might help somebody thanks for your responses,['java'] +77656,md5sum of file in linux c i want to find md5sum of a file in linux c is there any api where i can send file name to get md5sum of that file,['c'] +77673,get type name without full namespace in c i have the following codereturn inserted new typeofttostring but typeofttostringreturns the full name including namespaceis there anyway to just get the class name without any namespace qualifiers,['c#'] +77674,where to put boost class export for boostserialization i am trying to serialize a pointer to a polymorphic class shape so i need to use the boost class export macro to define a guid for each subclass the problem where to put itlet me show a minimal test case firstshapeshppinclude boostserializationaccesshppinclude boostserializationbase objecthppinclude boostserializationexporthppclass shape friend class boostserializationaccess templatetypename archive void serializearchive ar unsigned int const version nothing to do public virtual shape class rect public shape friend class boostserializationaccess templatetypename archive void serializearchive ar unsigned int const version ar boostserializationbase objectshapethis public virtual rect ifdef export in header boost class exportrectendifexportcppinclude boostserializationexporthppinclude shapeshppifdef export in object boost class exportrectendifmaincppinclude iostreaminclude boostarchivetext oarchivehppinclude boostserializationexporthppinclude shapeshppifdef export in main boost class exportrectendifint main shape shape new rect boostarchivetext oarchive arstdcout ar shapeon gcc i compile these withg omain maincpp exportcpp wlbstatic lboost serializationmt wlbdynamic dexport in xhere exportcpp may look a bit silly in my actual situation it contains an enclosing class that uses the pimpl idiom and tries to serialize its polymorphic shape implementation the important point is the boost class export could be in a different object file than the code that invokes the serializationso heres the problem where to use boost class export i have three options which can be enabled using the export in x macrosexport in main works but is not what i want the code invoking the serialization should not need to know about the implementation details of the pimpl classexport in object compiles but does not work it results in a boostarchivearchive exception with the message unregistered void cast according to the documentation this should be solved by serializing base classes using boostserializationbase object like i did but it does not helpexport in header does not even compile the macro boost class export expands to a template specialization which wed like to be in the header file but also to the definitiof of a static member therein so i get a linker error about a multiple definition of boostarchivedetailinit guidrectguid initializerif it matters i am using g 443 and boost 140,['c++'] +77691,how can i pass a class as parameter and return a generic collection in java i am designing a simple data access object for my java application i have a few classes records that represents a single row in tables like user and fruiti would like to have a single method for getting all records of a specific typefor the moment i have it like thispublic listuser getallusers public listfruit getallfruits but i would like to have a single polymorphic method like this wrongpublic listt getallrecordsclasst type iftype instanceof user use jdbc and sql select from user else iftype instanceof fruit use jdbc and sql select from fruit return collectionexample for useslistfruit fruits mydataaccessobjectgetallrecrodsfruitclasslistuser users mydataaccessobjectgetallrecordsuserclasshow can i do this in java,['java'] +77693,css how to target 2 attributes ok if i want to target an input tag with typesubmit i can do so likeinputtypesubmitalso if i want to target an input tag with valuedelete i can do so likeinputvaluedeletebut how can i target an input tag with both,['css'] +77696,translateanimated imageview not clickable after animation android i have 2 imageviews that i translate from the top of the screen to the bottom these views are infalted from xml and the animation is added from java code the animation works perfectly but the onclicklistener i added in java code does not seem to work i used fillafter attribute of the animation to make the iamges stay at their arrival after the translation but these images are not clickable anymore however their position before translation remains clickablei cannot see the logic of this could anyone give me some piece of advice about that,['android'] +77709,relationship like twitter followersfollowed in activerecord i am trying to represent a relationship between users in my application where a user can have many followers and can follow other usersi would like to have something like userfollowers and userfollowed bycould you please tell me in details how to represent this using activerecordthanks,"['ruby-on-rails', 'ruby']" +77720,why am i finding javascriptjquery so difficult to get right my background is in c and i have picked up php mysql html css without too much issuebut i am finding javascriptjquery surprisingly difficult to get rightvery frustratingwhyit seems to violate a number of traditional programming principles eg variable scope undefined variables seem to appear out of nowhere and already have values associated with them for example from the jquery docs aclickfunctionevent eventpreventdefault div appenddefault eventtype prevented appendtologwhat exactly is event do i have to use this variable name should i just assume that this object is magically instantiated with the right stuff and i can use any of the methods list at the jquery apithere seems to be bunch of random rules eg return false to stop a default action but sometimes this does not work nondeterministic behavior when debugging eg i refresh the browser try something and get result x for js variables i am watching in firebug i refresh again and i get result yvery messy looking code that is hard to follow what happens when i am using firebug and chrome developer tools but i am not getting enough visibilityit seems like everyday there is some random js rule that comes up that i have never seen before in any of my js books or tutorials what do i need to do to make javascriptjquery more deterministic controlled and logical to meare there any resources that explain javascripts quirksgotchasthanks,"['javascript', 'jquery']" +77727,udids in provisioning profile given a provisioning profile does anyone know how to determine what udids are in that profile,['ios'] +77750,how do i implement a bipartite graph in java updatesome answers so far have suggested using an adjacency list how would an adjacency list look like in java no pointers right i am trying to implement a bipartite graph in java to sort into 2 groups information from a file i found this example and it actually does the job fileshtmljavabipartitejavahtmlhowever i would like to implement my own version if you look at a previous post of mine youd understand why i want to do this myself so i have to read a file from which i can get the number of vertices easily but the number of edges not so easily an example line would be persona personb which can be read as persona says personb so reading these linesa says bc says bd says bb says de says a c produces this groupingadc and behow would i go about implementing this bipartite graph what is a good resource for this task what things algorithms should i be considering and thinking about when creating the bipartitegraph class perhaps traversingsorting algorithms,['java'] +77768,purpose of connectionstring element in net config files what is the difference between storing and reading your applications connection string in the appsettings and connectionstrings sections of webconfig,['.net'] +77810,after array filter how can i reset the keys to go in numerical order starting at 0 i just used array filter to remove entries that had only the value from an array and now i want to apply certain transformations on it depending on the placeholder starting from 0 but unfortunately it still retains the original index i looked for a while and could not see anything perhaps i just missed the obvious but my question ishow can i easily reset the indexes of the array to begin at 0 and go in order in the new array rather than have it retain old indexesthanks a million for any help,['php'] +77811,how to show open in when a user tries to open email attachments in ios i have seen some ios apps have this functionwhen a user tries to open an email attachment they can press and hold on the attachment for a couple of seconds and a popup menu will appear thisplaying two buttons one button reads open in ibooks for example when user clicks it then the app will be run and open the attachmenti would like to know how to register my application to be associated with a particular document type also what happens to the document when it is opened is it copied to a location that can be read by the application or does the application receive some sort of object representing the documentif anyone knows how to do this please let me know thx very much,"['iphone', 'ios']" +77819,server push vs client pull for agentserver topology i need to create a system comprising of 2 componentsa single server that process and stores data it also periodically sends out updates to the agentsmultiple agents that are installed at remote endpoints these collect data in often but not always longrunning operations and this data needs to get to the serveri am using c net and ideally i want to use a standards compliant communications method ie one that could theoritically work with java too as we may well also use java agents in the future are there any alternatives to web services what are my optionsthe way i see it i have 3 options using web services and have made the following observationsclient pullno open port required at the agent as it acts like a clientwould need to poll the server for updatesserver pushopen port at the agent as it acts like a serverserver must poll agents for resultshybridopen port at the agent as it acts like both a client and a serverno polling server pushes out updates when required client sends results when they are availablethe hybrid where agents are both client and server seems the obvious choice but this application will typically be installed in enterprise and government environments and i am concerned they may have an issue with opening a port at the agent am i dwelling too much on thisare there any other pros and cons i have missed out,"['c#', '.net']" +77820,hyperlink in tkinter text widget i am re designing a portion of my current software project and want to use hyperlinks instead of buttons i really did not want to use a text widget but that is all i could find when i googled the subject anyway i found an example of this but keep getting this error tclerror bitmap blue not definedwhen i add this line of code using the idlehyperlink tkhyperlinkmanagerhyperlinkmanagertextthe code for the module is located here and the code for the script is located hereanyone have any ideas the part that is giving problems says foregroundblue which is known as a color in tkinter is not it,['python'] +77826,alter table add before code alter table tada prodaction 6 weekly add column id int null auto increment unique after member idworksso i thought to add the column as the first column i could do alter table tada prodaction 6 weekly add column id int null auto increment unique before codebut i get a syntax errorwhat is the correct syntax,['mysql'] +77834,is there a way to force lxml to parse unicode strings that specify an encoding in a tag i have an xml file that specifies an encoding and i use unicodedammit to convert it to unicode for reasons of storage i cannot store it as a string i later pass it to lxml but it refuses to ignore the encoding specified in the file and parse it as unicode and it raises an exceptionhow can i force lxml to parse the document this behaviour seems too restrictive,['python'] +77850,memory allocation to functions in c i am still a c newbie just came to read that the static member function of a class is not object specific there is a single copy of the member functions for all the objectsnow two questions arise in my mind what is the difference between an ordinary function and a static function in terms of memory allocation only what if the member function contains some local variables in that case the function should have a separate copy of that variable specific to the object invoking the function how is this problem solved in c thanks,['c++'] +77885,what are the supported image file formats for thisplay on the iphone i have an image in jpg format is that readable within an iphone application what are all of the image file extensions that can be loaded natively within an iphone application,['iphone'] +77886,how do i simulate text input to a wpf textbox i want to simulate user input to a wpf textbox i want to input a character such that the onpreviewtextinput event is triggered i tried setting the text through the text property but this did not trigger the event public void somefunction var textbox new textbox textboxtext a can i trigger the event explicitly somehow,['.net'] +77888,hibernate dynamicupdate dynamicinsert performance effects using dynamicupdate or dynamicinsert has positive though generally slight only on performance as also mentioned by but the reference documentation mentions that this could have negative performance effects also as mentioned below in although these settings can increase performance in some cases they can actually decrease performance in otherscan anybody please suggest some examplescenario mentioning negative performance impact of the same,['java'] +77901,change the master page from code behind i have a web page named mypageaspx and two master page named homemaster and blankmasterby default mypageaspx uses homemasterbut based on some condition i need to change the master page from homeaspx to blankmasterso how to do this from code behind in ci mean how change the master page from code behind,"['c#', 'asp.net']" +77960,is it possible to forward or redirect from a servlet filter after the response has been comitted the logic is that the filter gets hit the condition is not true so it goes through the filter chain after the response is committed the filter gets hit and the condition is now true a request attribute was set it goes in to execute the forward but the page never forwards i know this has something to do with the response being committed because i tested different logic where it forwards before it hits the chain for the first time and it does forward successfullypublic void dofilterservletrequest request servletresponse response filterchain chain throws ioexception servletexception httpservletrequest httpservletrequest httpservletrequestrequest if some condition equals true httpservletrequestgetrequestthispatcherhomejspforwardrequest response return else chaindofilterrequest response example from my deployment descriptorfilter filternamemyfilterfiltername filterclasscomfiltersmyfilterfilterclassfilterfiltermapping filternamemyfilterfiltername urlpatternjspurlpattern thispatcherrequestthispatcher thispatcherforwardthispatcher filtermapping,['java'] +77977,only show tables with certain patterns in mysql show tables there are too many tables in a db how can i only show tables with certain patterns or is there a way i can do paging like more in shell command,['mysql'] +77986,add attribute checked on click jquery i have been trying to figure out how to add the attribute checked to a checkbox on click the reason i want to do this is so if i check off a checkbox i can have my local storage save that as the html so when the page refreshes it notices the checkbox is checked as of right now if i check it off it fades the parent but if i save and reload it stays faded but the checkbox is uncheckedi have tried doing thisattrchecked but it does not seem to want to add checkededit after reading comments it seems i was not being clearmy default input tag isinput typecheckbox classdonei need it top be so when i click the checkbox it adds checked to the end of that exinput typecheckbox classdone checkedi need it to do this so when i save the html to local storage when it loads it renders the checkbox as checked doneliveclick functionifthisparentfindeditorisvisible var editvar thisparentfindinputnametestervalthisparentfindeditorfadeoutslowthisparentfindcontenttexteditvarthisparentfindcontentfadeinslowif thisischecked thisparentfadetoslow 05thisattrchecked this lineelsethisparentfadetoslow 1thisremoveattrchecked,"['javascript', 'jquery']" +78002,does anyone have considerable proof that char is faster than varchar any benchmark graph anything at all its all academic and theoretical across the web ok its not the first time that this question has been asked they all say that using char results in faster selects i even read in mysql books its all the same but i have not come across any benchmark that proves thiscan any one shed some light over this,['mysql'] +78037,how to create a random float in objectivec i am trying to create a random float between 015 and 03 in objectivec the following code always returns 1int randn random 1515float pscale floatrandn 100what am i doing wrong,['objective-c'] +78049,how to get an attribute with simplexml i am using simplexml load filepath xml file it works good if i do print rxml it printssimplexmlelement object attributes array message login successful token 1 dataformat csv how can i get token valuethank you,['php'] +78050,when to use each of t list ienumerable i usually find myself doing something likestring things arrayreturningmethodint index thingstoliststringfindindexs sequalsfoodo something with indexreturn thingsthistinct which returns an ienumerablestringand i find all this mixup of typesinterface a bit confusing and it tickles my potential performance problem antennae which i ignore until proven right of course is this idiomatic and proper c or is there a better alternative to avoid casting back and forth to access the proper methods to work with the dataedit the question is actually twofoldwhen is it proper to use either the ienumerable interface or an array or a list or any other ienumerable implementing type directly when accepting parametersshould you freely move between ienumerables implementation unknown and lists and ienumerables and arrays and arrays and lists or is that non idiomatic there are better ways to do it non performant not typically relevant but might be in some cases just plain ugly unmaintable unreadable,['c#'] +78057,how to use setmultichoiceitems with a custom alertdialog that uses an efficiency arrayadapter i am writing a music player that uses a custom adapter extending baseadapter efficiency adapter that i want to thisplay in an alertdialog using setadapter where the user can either click on one of the songs to switch to that position in the playlist or check songs to remove from the playlist i tried using a custom click listener so that a user could just long click to remove the item from the list but the listview just does not work right it was removing the wrong items the ones at the end even though the arraylist contained the correct playlist items when i removed the item from the arraylist i passed it to the adapter which called notifydatasetchanged but that just did not work as i mentioned there is definitely a bug in the alertdialog listview because there is no reason for it to have popped off the results from the end rather than the correct itemso the next method i would like to try is to use the setmultichoiceitems method of the alertdialog but it appears that it does not work with a custom adapter only simple arrays will i have to subclass alertdialog and override the setmultichoiceitems method or is there a way i can make it work with an arrayadapterbasically i cannot figure out how to even iterate the list that the alertdialog creates or whether it even passes that view somehow in addition i do not think i can even listen to clicks on checkboxes if i add those to the row any help will be greatly appreciatededit asking questions here is like magic i answered my own question this is how i did it i added a hint to each checkbox which is the position of the item in the arraylist then i used oncheckedchangelistener to capture the selections when you set a hint it adds text to the checkbox since the background of the alertdialog is white even for clicked items i just set the hint text color to transparentholderchecksethinttextcolorcolortransparentholderchecksethintstringvalueofpositionholderchecksetoncheckedchangelistenernew oncheckedchangelistener public void oncheckedchangedcompoundbutton buttonview boolean ischecked int position integerparseintstring buttonviewgethint logvoncheckedchanged checked ischecked returned position which should be getitempositionname,['android'] +78059,graceful way to tell users of ie7 and below to go away tldr tell ie67 users to leave in a nice way whilst blocking them from all content basically i do not need people using ie76 lower on my web app was thinking of just doing a docwrite after load to wipe the page with a message of sorry your browser is outdated has anyone done similar and found a nice friendly way to tell them to come back with a better browseram currently using jquery so jquery solutions viable1 most reliable way to detect browser2 opinion on what to present to the userthe scenario is not the question here they will have access to upgrade if need bei have legit reasons for doing so so stay ontopic to the question and do not voice opinions about the general topic of ie6 and how much you love it,"['javascript', 'jquery']" +78071,how to resume an interrupted download i am trying to download a large file from my yahoo web site server which apparently is setup not by me to thisconnect downloads if they are not completed within 100 seconds the file is small enough to usually successfully transfer on the occasions when the data rate is slow and the download gets thisconnected is there a way to resume the urlconnection at the file offset where the thisconnection occurred heres the code setup connectionurl url new urlstrurl0urlconnection cx urlopenconnectioncxconnect setup streams and buffersint lengthfile cxgetcontentlengthinputstream input new bufferedinputstreamurlopenstreamoutputstream output new fileoutputstreamstrurl1byte data new byte1024 download filefor total0 countinputreaddata 0 1024 1 totalcount publishprogressinttotal100lengthfile outputwritedata 0 count logdasyncdownloadfile bytes total close streamsoutputflushoutputcloseinputclose,"['java', 'android']" +78091,how to determine which button pressed on android i need to know how to recognize which button is pressedlike if i have two buttons say button 1 and button2and both of them performing the same method say methodhow to determine which button pressed regards,['android'] +78092,net decimalnegate vs multiplying by 1 are there any differences between decimalnegatemydecimal and mydecimal 1 except maybe readability,"['c#', '.net']" +78098,scala comet and mobile applications i am exploring using scala with its comet facilities for my next project and was curious if anyone had experience using comet not necessarily scala withwebosandroidiosall these phones are webkit which should mean that my chrome tests would work equally well but i do not know how longpolling connections work over 3g or whether they eat the battery alivethoughts,"['android', 'ios']" +78102,css grid with perfect squares need some help with the css for generating a grid of perfect squares divs look like this but i would like to have each of them look like a perfect square not a rectangle setting width and height in css does not do it div clasquare div clasquare div classlinebreak div clasquare div clasquare div classlinebreak,['css'] +78116,how can i publish site from command line with some publish profile something like msbuild tpublish use publishprofilename someprojectcsproj,['asp.net'] +78122,initializing stdtuple from initializer list i am wondering whether the tuple can be initialized by initializer list to be more precise by initializer list of initializer lists considering the tuple definitiontypedef stdtuple stdarrayshort 3 stdarrayfloat 2 stdarrayunsigned char 4 stdarrayunsigned char 4 vertexis there any way of doing the followingstatic vertex const nullvertex 0 0 0 00 00 0 0 0 0 0 0 0 0 i just want to achieve same functionality i got using struct instead of tuple thus only arrays are initialized by initializer liststatic struct vertex stdarrayshort 3 m vertex coords stdarrayfloat 2 m texture coords stdarrayunsigned char 4 m color 1 stdarrayunsigned char 4 m color 2 const nullvertex 0 0 0 00 00 0 0 0 0 0 0 0 0there is no reason i must use tuples just wondering i am asking because i am unable to go through g templates errors which are generated by my attempt of such tuple initializationmotti so i missed the proper syntax for uniform initialization static vertex const nullvertex vertex 0 0 0 00 00 0 0 0 0 0 0 0 0 and static vertex const nullvertex 0 0 0 00 00 0 0 0 0 0 0 0 0 but it seems that all the trouble lies in arrays which got no constructor for initializer list and wrapping arrays with proper constructor seems not so easy task,['c++'] +78127,buttons to run maven targets in netbeans i would like to have a button to run custom maven targets in netbeans 69 hotkeys would also be nice is this possibleif it is not possible is there something like a console where i could maven commands directly,['java'] +78133,what is stdmove and when should it be used what is itwhat does it dowhen should it be usedgood links are appreciated,['c++'] +78145,what does phps underscore function do what does this function do can you link me to the relevant documentation as searching for is nigh on impossible,['php'] +78164,listview not updating after filtering i have a listview with settextfilterenabledtrue and a custom adapter extends arrayadapter which i update from the main ui thread whenever a new item is addedinserted everything works fine at firstnew items show up in the list immediately however this stops the moment i try to filter the listfiltering works but i do it once and all of my succeeding attempts to modify the contents of the list add remove do not thisplay anymore i used the log to see if the adapters list data gets updated properly and it does but it is no longer in sync with the listview shownany ideas whats causing this and how best to address the issue,['android'] +78178,how to get a char from an ascii character code in c im trying to parse a file in c that has field string arrays separated by ascii character codes 0 1 and 2 in visual basic 6 you can generate these by using chr0 or chr1 etci know that for character code 0 in c you can do the followingchar separator 0but this doesnt work for character codes 1 and 2,['c#'] +78185,forward request from a filter i need to forward my request to a jsp but i do not think it is matter from an httpfilterif the uri of the original request pass some validation that my filter runsi found this page that faced similar task still i need to figure the following how can i get servletcontext in dofilter method in order to call forward api getservletcontext is not recignizeddo i have to call chaindofilter before the forward after the forward or not at allin addition do i have to call chaindofilter if my validation passed or only if it fails because in this case i would not continue to forward my pagethis question actually continue this thread to be more obvious the code could be something likepublic void dofilterservletrequest request servletresponse response filterchain chain throws ioexception servletexception if request instanceof httpservletrequest httpservletrequest httpservletrequest httpservletrequestrequest string requesturi httpservletrequestgetrequesturi string contextpath httpservletrequestgetcontextpath if this is my implementation of the validation of this filter getservletcontextgetrequestthispatcher myspecificjspforwardrequestresponse chaindofilterrequestresponse,['java'] +78212,how to not select empty string we have the following jpqlselect thistinct sysipaddress from systemlog sys where sysipaddress is not null and sysipaddress is not emptyand this generates the following mysql statement select thistinct systemlog0 ipaddress as col 0 0 from systemlog systemlog0 where systemlog0 ipaddress is not null and exists select systemlog0 id from systemlog systemlog0 this obviously does not work and returns empty string instead of omitting it however i am looking for something like this to be generatedselect thistinct ipaddress from systemlog where ipaddress is not null and ipaddress however i cannot figure out why our jpa query does not generate something simliar like thatany ideas,"['java', 'mysql']" +78216,listviews with multiple item layouts i have a listview on my listactivity and i would like the rows of the listview to be 1 of 3 different layouts the first item in my list is always going to use layout a the second item in my list is always going to use layout b and all subsequent items are going to use layout chere is my getview functionoverridepublic view getviewint position view convertview viewgroup parent get the view for this list item view v convertview if v null layoutinflater vi layoutinflatergetcontextgetsystemservicecontextlayout inflater service switch position case 0 v viinflaterlayoutlayout a parent false break case 1 v viinflaterlayoutlayout b parent false break default v viinflaterlayoutlayout c parent false break switch position case 0 textview txtlabel1 textviewfindviewbyidridlabel1 textview txtlabel2 textviewfindviewbyidridlabel2 if txtlabel1 null txtlabel1settextsdfasd if txtlabel2 null txtlabel2settextdasgfadsasd break default break return the created view return vridlabel1 and ridlabel2 are textviews on rlayoutlayout a however txtlabel1 and txtlabel2 are null after trying to set them why i stepped through this code in the debugger and it inflated the correct layout rlayoutlayout a and fell into the correct case below to set the ridlabel1 and ridlabel2 textalso if there is a better way to do this please let me know,['android'] +78217,render a partial from jquery and haml the functionality i plan on doing is to insert some form elements depending on a number chosen from a select tagi have a select tag called for number of passengers and i plan to dynamically append new passenger fields for the number chosen say i select 2 from number of passengers then 2 forms should appear in a fieldset these forms contain name age weight etci tried following thisand just converted it to hamlspeak but i get errors whenever i use the javascript tag also i do not think i can escape the javascript tag once i am in itjavascript number of passengerschangefunction var num of passengers thisval fori0 inum of passengersi passengerinfo ulappend escape javascript render partial new passenger locals booking booking also since i am in a form for how do i pass the booking variable to the local it seems really complicated and i am planning of doing the dirty way out of just looping 20 times20 max passengers then just hideshow them depending on the selected number but that is too dirty do not you think,"['jquery', 'ruby-on-rails']" +78232,what is gc collecting here this might be pretty basic but was very curious to know heres the code snippet and the outputpublic class plainsystemgc public static void mainstring strings systemoutprintlnfree memory before gc runtimegetruntimefreememory systemgc systemoutprintlnfree memory after gc runtimegetruntimefreememory and the outputfree memory before gc 1859640free memory after gc 1911768i am interested to know what is gc collecting here since no objects are created whats the memory thats being freed up and that too 52kb jsauer it gives exactly the same results even if run 100 times,['java'] +78236,exotic names for methods constants variables and fields bug or feature after some confusion in the comments tois it safe to have 1 letter class names in php eg a b ci thought i make into a question according to the php manual a valid class name should match against azaz x7fxffazaz09 x7fxff but apparently this is not enforced nor does it apply for anything elsedefinei pivar dumpiclass a private a true public function a return thisa a new avar dumpa var dumpaaworks fine even though my ide cannot show a can some erudite person clear this up for me can we use any unicode and if so since when not that i would actually want to use anything but azaz but i am curiousclarification i am not after a regex to validate class names nor do i know if php internally uses the regex it suggests in the manual the thing that confused me and apparently the other guys in the linked question is why things like a 1 can be used in php at all php6 was suposed to be the unicode release but php6 is in hiatus but if there is no unicode support why can i do this then,['php'] +78241,how do i determine if a request is the result of a postback updatei am implementing a custom page caching solution and i do not want the request to be cached or retrieved from the cache if it is in response to a form submission or some sort of aspnet postbacki am trying to figure out if the current httprequest is a postback is there a way of doing this outside the context of a page or other usercontrol in otherwords if i am inside an httpmodule i do not have access to thisispostback but i still need to determine if it is in fact a postbackalso are postbacks always post requests or is that determined by containing formthanks,['asp.net'] +78252,how to sort a python dict by value i have a dict that looks like this keyword13 keyword21 keyword35 keyword42 and i would like to convert it desc and create a list of just the keywords eg this would returnkeyword3 keyword1 keyword4 keyword2all examples i found use lambda and i am not very strong with that is there a way i could loop through this and sort them as i go thanks for any suggestionsps i could create the initial dict differently if it would help,['python'] +78258,trouble adding footer to listview i have a listview that i am trying to add a footer to for some reason it would not show up my footer is defined in a separate xml layout called layout footerview v getlayoutinflaterinflaterlayoutlayout footer getlistview falsegetlistviewaddfooterviewvhere is the code in my listactivitys oncreate method please note that it is the last thing i do in oncreatei want this item to scroll with the rest of the list and according to the resources i have found i believe this is how you do it unfortunately the footer does not show help would be much appreciated,['android'] +78259,month name to month number and vice versa in python i am trying to create a function that can convert a month number to an abbreviated month name or an abbreviated month name to a month number i thought this might be a common question but i could not find it online i was thinking about the calendar module i see that to convert from month number to abbreviated month name you can just do calendarmonth abbrnum i do not see a way to go the other direction though would creating a dictionary for converting the other direction be the best way to handle this or is there a better way to go from month name to month number and vice versa,['python'] +78282,aspnet mvc adding css to editorfor i would like to change style of the editor for textbox from mvc specifically i want to make the textbox larger i have tried adding css a few ways to no availincluding td classmycsshtmleditorforx xnicknametdandtd classmycsshtmleditorforx xnickname new class mycss tdhelp pls,['html'] +78284,ruby select a hash from inside an array i have the following arrayresponse labelcat namekitty id189955 label dog namerex id 550081how do i select the hash that contains the label cat i know responsefirst will give me the same result but i want to search the by labelthanksdeb,['ruby'] +78294,benchmarking rails activerecord queries i am looking to benchmark a couple of my activerecord requests in my app whats the simplest way in the console to benchmark something likeuserfind by namejoeidversususerfindfirst select id conditions name joeidthanks,['ruby-on-rails'] +78297,threadpoolexecutor policy i am trying to use a threadpoolexecutor to schedule tasks but running into some problems with its policies heres its stated behaviorif fewer than corepoolsize threads are running the executor always prefers adding a new thread rather than queuingif corepoolsize or more threads are running the executor always prefers queuing a request rather than adding a new threadif a request cannot be queued a new thread is created unless this would exceed maximumpoolsize in which case the task will be rejectedthe behavior i want is thissame as aboveif more than corepoolsize but less than maximumpoolsize threads are running prefers adding a new thread over queuing and using an idle thread over adding a new threadsame as abovebasically i do not want any tasks to be rejected i want them to be queued in an unbounded queue but i do want to have up to maximumpoolsize threads if i use an unbounded queue it never generates threads after it hits coresize if i use a bounded queue it rejects tasks is there any way around thiswhat i am thinking about now is running the threadpoolexecutor on a synchronousqueue but not feeding tasks directly to it instead feeding them to a separate unbounded linkedblockingqueue then another thread feeds from the linkedblockingqueue into the executor and if one gets rejected it simply tries again until it is not rejected this seems like a pain and a bit of a hack though is there a cleaner way to do this,['java'] +78298,real world typo statistics where can i find some real world typo statistics i am trying to match peoples input text to internal objects and people tend to make spelling mistakesthere are 2 kinds of mistakes typos helo instead of hello satudray instead of saturday etc spelling shikago instead of chicago i use dameraulevenshtein thistance for the typos and double metaphone for spelling python implementations here and herei want to focus on the dameraulevenshtein or simply editthistance the textbook implementations always use 1 for the weight of deletions insertions substitutions and transpositions while this is simple and allows for nice algorithms it does not match reality realworld probabilities examples i am sure the likelihood of helo hello is greater than helzlo yet they are both 1 edit thistance awaygello is closer than qello to hello on a qwerty keyboardunicode transliterations what is the real thistance between ma14nchen and munchenwhat should the real world weights be for deletions insertions substitutions and transpositions even norvigs very cool spell corrector uses nonweighted edit thistancebtw i am sure the weights need to be functions and not simple floats per the above examplesi can adjust the algorithm but where can i learn these weights i do not have access to googlescale data should i just guess themedit trying to answer user questionsmy current nonweighted algorithm fails often when faced with typos for the above reasons return on tursday every real person can easily tell thursday is more likely than tuesday yet they are both 1editthistance away yes i do log and measure my performancei am developing an nlp travel search engine so my dictionary contains 25k destinations expected to grow to 100k time expressions 200 expected 1k people expressions 100 expected 300 money expressions 100 expected 500 glue logic words from beautiful apartment 2k expected 10k and so onusage of the edit thistance is different for each of the above wordgroups i try to autocorrect when obvious eg 1 edit thistance away from only 1 other word in the dictionary i have many other handtuned rules eg double metaphone fix which is not more than 2 edit thistance away from a dictionary word with a length 4 the list of rules continues to grow as i learn from real world inputhow many pairs of dictionary entries are within your threshold well that depends on the fancy weighting system and on real world future input does not it anyway i have extensive unit tests so that every change i make to the system only makes it better based on past inputs of course most sub6 letter words are within 1 edit thistance from a word that is 1 edit thistance away from another dictionary entrytoday when there are 2 dictionary entries at the same thistance from the input i try to apply various statistics to better guess which the user meant eg paris france is more likely to show up in my search than paraz iranthe cost of choosing a wrong word is returning semirandom often ridiculous results to the enduser and potentially losing a customer the cost of not understanding is slightly less expensive the user will be asked to rephraseis the cost of complexity worth it yes i am sure it is you would not believe the amount of typos people throw at the system and expect it to understand and i could sure use the boost in precision and recall,['python'] +78318,whats better configobj or configparser which is better for creating a settings file for python programs the builtin module configparser or the independent project configobj,['python'] +78321,how do i detect a doubleheight status bar the hig p47 says that i have to be able to handle the doubleheight status bar that appears during phone calls or voice recordings how exactly do i handle this situationi really only have 1 screen where a keyboard with toolbar over it underlaps a textfield when the doubleheight status bar shows on other screens things are just a bit scrunched up but useableif i could detect that a doubleheight status bar exists i could maybe adjust the placement of the textfields or make them temporarily shorter but is it possible to detect when the doubleheight status bar is thereedit maybe if there were a way to get the absolute coordinates of a known thing like the nav bar and if it was 20 pixels off i would assume that the doubleheight status bar is present thoughtsand a secondary question if this or anything works i would just like to hide the regular status bar using uiapplication sharedapplication setstatusbarhiddenyes animatednobut i do not want to hide both basically a lazy way not to have to touch any of my screens if the double is there make it a single again by hiding the regular status bar will the above code hide both,['iphone'] +78324,monkey patching in rails 3 what is the preferred way to monkey patch in rails 3i just want to add a method to the string class i am more looking at where to place the file,['ruby-on-rails'] +78342,python global name time is not defined i am writing a silly program in python for a friend that prints we are the knights who say ni then sleeps for 3 seconds and then prints ni twenty times at random intervals using the random modules uniform method heres my codefrom time import sleepimport randomdef knights of ni generator randomrandom print we are the knights who say ni sleep3 for i in range020 print ni sleepgeneratoruniform02i have tried to import this module by typing in the interpreter from silly import knights of ni and import silly then calling the function with either knights of ni or sillyknights of ni respectively but i always get the same exception nameerror global name time is not definedwhat is causing this error and how can i fix my codeedit quite frankly i am not sure what problem i was having either i ran the code the next morning and it worked just fine i swear that the code produced errors last night anyway thanks for your insight,['python'] +78343,passing a byte in java to a function in c through jni how to use jarraybyte this is the first time that i use the jni and also the first time that i have to write some lines in cwhat i am trying to do is very simple i am just trying to switch the endiannes of a byte using a c routine in java it is done like thispublic void switchendiannessbyte array byte byte1 byte byte2 forint i 0 i arraylength i2 byte1 arrayi byte2 arrayi1 arrayi byte2 arrayi1 byte1 so to do this using jni i have tried to imlpement the same routine in the jnicall but it does not compile what i have written so far is thisjniexport void jnicall java cendianness switchendiannessjnienv env jobject obj jbytearray array jint offset jint length char byte1 char byte2 int i fori offset i length i2 byte1 arrayi byte2 arrayi1 arrayi byte2 arrayi1 byte1 i have no clue how to use the jbytearray type of data is it possible to store a jbyte in a char another question is when this routine is overwill the byte in java be modified or is it only modified inside the c callany helpthanks to everybody,"['java', 'c']" +78370,is find faster than basic descendant selecting method slide 30 in paul irishs blog mentionedcontainerfinddivrobotarm is faster than container divrobotarmis this true,['jquery'] +78372,how to use servermappath to get location outside website folder in aspnet when my aspnet site uses documents eg xml i normally load the document as followsservermappathdocumentsmydocumentxmlhowever i would like to move the documents folder out of the website folder so that it is now a sibling of the website folder this will make maintaining the documents considerably easierhowever rewriting the document load code as followsservermappathdocumentsmydocumentxmlresults in a complaint from aspnet that it cannot exit above the top directoryso can anyone suggest how i can relatively specify the location of a folder outside the website folder i really do not want to specify absolute paths for the obvious deployment reasonsthanksdavid,['asp.net'] +78375,why does removechild need a parent node after answering this question i am left wondering why removechild needs a parent element after all we could simply donodeparentnoderemovechildnodeas the parent node should be always directly available to the javascriptdom engine it is not strictly necessary to supply the parent node of the node that is to be removedof course i understand the principle that removechild is a method of a dom node but why does not something like documentremovenode exist that merely accepts an arbitrary node as parameteredit to be more clear the question is why does the js engine need the parent node at all if it already has the unique node that is to be removed,['javascript'] +78376,retrieve only static fields declared in java class i have the following classpublic class test public static int a 0 public int b 1is it possible to use reflection to get a list of the static fields only i am aware i can get an array of all the fields with testclassgetdeclaredfields but it seems there is no way to determine if a field instance represents a static field or not,['java'] +78377,android measuredetect covered area by a finger touch on screen not only touch coordinates i would like to get access to the area covered by a finger for each touch event on an androidevery touch event will result in a coordinate pair x and y independent of how big the finger and consequently the touch area is that triggered the eventi was wondering if there is a way to get the area data which triggered the touch event eg size or coordinates notany help is much appreciatedthanks in advance for you answer or redirectschristian,['android'] +78385,what opcodes were introduced in clr 40 are there any il opcodes that are new in net 40 as compared to 35 and if so where can i find a list of them,['.net'] +78386,looking for the best aspnet survey application please give suggestions for best aspnet survey application with source code commercial is fine,['asp.net'] +78410,java xml dom how are id attributes special the javadoc for the document class has the following note under getelementbyidnote attributes with the name id or id are not of type id unless so definedso i read an xhtml doc into the dom using xerces 291 the doc has a plain old p idfribble in iti call getelementbyidfribble and it returns nulli use xpath to get idfribble and all is wellso the question is what causes the documentbuilder to actually mark id attributes as so defined,['java'] +78417,jquery ui datapicker how to add nextprevious year buttons i use the feature of selecting a year with a dropdown i use it to set birthdays of people at least 18 years old so far it works perfectly i have set it up using theseg parameters datepickerdatepicker changemonth true changeyear true dateformat ddmmyy mindate 100y maxdate 18y however i would like to have year navigation is it possible to add a nextprevious year buttonthanks in advance for any help,['jquery'] +78426,using xpath to access xml elements was good tutorial to learn xpath i am trying to learn xpath the theory seems extremely simple except for the fact that it does not worki am trying to get the content of every target elementxpathdocument doc new xpathdocumentspathxpathnavigator nav doccreatenavigatorxpathexpression exprexpr navcompiledocfilebodytransunittargetxpathnodeiterator iterator navselectexprwhile iteratormovenext xpathnavigator nav2 iteratorcurrentclone sbdocappendnav2innerxmlthe xml doc looks like thisxml version10 encodingutf8doc version12 file originalaffiliatephp sourcelanguageenus targetlanguagefrfr datatypephp header skl externalfile hrefaffiliatephp skl header body transunit idtu1 source xmllangenusyour program detailssource target xmllangfrfryour program detailstarget transunit transunit idtu2 source xmllangenusstatussource target xmllangfrfrstatustarget transunitthis is nearly word for word from a tutorial but i cannot get it to work when the iterator is created in debug mode i can see that the document is loaded but iterator finds no result and skips the while loopi am probably doing something extremely stupid but whatanyone knows where i can find a good reliable xpath tutorialthanks all turns out i ignored the fact that there was a namespace which i removed while simplifying the xml code as i did not realize it was important and with the addition of a namespace manager the code works fine i am now studying the xpath tutorials proposed and they look good,['c#'] +78453,what characters are allowed in the html name attribute inside input tag i have a php script that will generate inputs dynamically so i was wondering if i needed to filter any characters in the name attributei know that the name has to start with a letter but i do not know any other rules i figure square brackets must be allowed since php uses these to create arrays from form data how about parentheses spaces,['html'] +78459,what should a developer know before building cellphone apps i want to start making cellphone apps with android as first choice but not the only one i have 10 years of experience with java c c in commercial applications and i know that many things and practices for this applications are not valid for cellphones where do i start reading how do i adapt my way of thinking to this new environment as quickly as posible i plan to make some money with it sometime in the future as an extra income or a career change maybe who know any resource or advice you could recommend will be very welcome thanks in advance,"['java', 'c', 'android']" +78466,sqlite3programmingerror you must not use 8bit bytestrings unless you use a text factory that can interpret 8bit bytestrings using sqlite3 in python i am trying to store a compressed version of a snippet of utf8 html codecode looks like thisc connectioncursorcexecutecreate table blah cid integer primary keyhtml blobcexecuteinsert or ignore into blah values cid zlibcompresshtmlat which point at get the errorsqlite3programmingerror you must not use 8bit bytestrings unless you use a text factory that can interpret 8bit bytestrings like text factory str it is highly recommended that you instead just switch your application to unicode stringsif i use text rather than blob and do not compress the html snippet it works all fine db is to large though when i use blob and compress via python zlib library i get the above error message i looked around but could not find a simple answer for this one,['python'] +78492,how do you make strings xmlsafe i am responding to an ajax call by sending it an xml document through php echos in order to form this xml document i loop through the records of a database the problem is that the database includes records that have symbols in them so naturally the browser throws an error at that particular spot how can this be fixed,['php'] +78501,microsoft azure storage vs azure sql database i saw that there was a similar question asked several months back but it really did not address my situation well here it goesi am in the process of building from scratch a webbased net application that has the potential to become a highvolume site several hundred thousand page views a month to start and am strongly considering using microsoft azure to host it i have not built anything yet and am still researching my different optionsthe application itself is at its core a standard crud application that acts upon a number of different types of entities eg user order item etc there are probably some background processes that may be running and some queuing of data for nonrealtime updates like getting a so badge for example but most of the interactions with the user will be your typical crud type of actionsregarding azure i have read a number of articles about using microsoft azure storage to store transactional data and am strongly considering doing that instead of using azure sql db however i have not seen or read a number of success stories of real people andor real companies doing that so i thought i would reach out to the so community to see if anyone has had any experience with using microsoft azure storage what kind of luck have you had any gotchas i should look out for and any best practices that youve come up withi have read through a lot of the microsoft azure msdn section and the programming microsoft azure table api document from microsoft i am looking for practical advice lessons learned best practices etc thanks in advance,['.net'] +78504,when to thispose of systemthreadingtask with child tasks i have a task that launches several child tasks eg task a creates bcdef i also create a systemthreadingtimer to poll a database every 10 seconds to check if the scheduled item was cancelled by request if it does it sets cancellationtokensource so that the task knows to cancel each subtask in this case bcdef will cancel when appropriate they are looping thru files and moving them aroundsince task implements ithisposable i want to know if it is a good idea to call taskwaitall again from the catch block to wait for the cancellations to propogate while the cancellation request will be processed the subtasks may be in the middle of a loop and cannot cancel until that completeshowever per msdnalways call thispose before you release your last reference to the task otherwise the resources it is using will not be freed until the garbage collector calls the task objects finalize methodshould i call wait again on my task array in order to properly call thispose on each task in the arraypublic class mycancelobject cancellationtokensource source getset int databaseid getset private void checktaskcancelledobject state mycancelobject sourcetoken mycancelobjectstate if sourcetokencanceltokeniscancellationrequested check database to see if cancelled if so set to cancelled sourcetokencanceltokencancel private void somefunc taskstartnew mycancelobject mycancelobject new mycancelobject databaseid new cancellationtokensource systemthreadingtimer canceltimer new timer new timercallbackcheckiftaskcancelled mycancelobject 10 10 task sometasks new tasksomenumberoftasks for int i 0 i somenumberoftasks i sometasksi taskfactorystartnew dosomeworksomeobject mycancelobjectcanceltokentoken taskcreationoptionsattachedtoparent taskcreationoptionslongrunning mycancelobjectcanceltokentoken try taskwaitallsometasks cts catch aggregateexception do stuff to handle catch operationcanceledexception should i call taskwaitallsometasks again i want to be able to thispose,['c#'] +78505,problem with ie and setinterval not refreshingupdating i am using javascriptjquery to make a page autoupdate with a value from a database although it does not seem to update in internet explorer it works fine in firefox chrome can anyone explain whats wrong it looks like ie is just thisplaying a cached version of the page how can i prevent this happening thanksfunction updatecomm var urlcommandsysphp jquerytheelementloadurl setintervalupdatecomm 10,"['javascript', 'jquery']" +78511,calculating time difference at the start and end of my program i have from time import strftimeprint intstrftimeymd hmsy1intstrftimeym1intstrftimemd1intstrftimedh1intstrftimehm1intstrftimems1intstrftimesy2intstrftimeym2intstrftimemd2intstrftimedh2intstrftimehm2intstrftimems2intstrftimesprint difference isstry2y1strm2m1strd2d1 strh2h1strm2m1strs2s1but when i tried to get the difference i get syntax errors i am doing a few things wrong but i am not sure what is going onbasically i just want to store a time in a variable at the start of my program then store a 2nd time in a second variable near the end then at the last bit of the program compute the difference and thisplay it i am not trying to time a function speed i am trying to log how long it took for a user to progress through some menus what is the best way to do this,['python'] +78516,if yield return never occurs is null returned the method returns ienumerable via a yield return statementif the yield statement never occurs it is inside conditional logic will the method return null or will it return an enumerable with a count of 0,['c#'] +78529,writing huge amounts of text to a textbox i am writing a log of lots and lots of formatted text to a textbox in a net windows form appit is slow once the data gets over a few megs since i am appending the string has to be reallocated every time right i only need to set the value to the text box once but in my code i am doing linedata tens of thousands of timesis there a faster way to do this maybe a different control is there a linked list string type i can use,['c#'] +78530,how to integrate scala into core android platform i am interested in integrating scala or some other nonjava jvmlanguage into the android platform i am not referring to writing an android application with scala that i did early early on but actually hooking into the build process that builds the android platform source tree i imagine this will be a matter of hooking into the makefiles and such does anyone have insight into thiswhat i have so farthe platform source treefrom gitandroidgitkernelorgplatformmanifestgit built in its virgin form guided by download and build the google android1buildcorecomboscalacmk configures scala compiler related variables included by configmkadded definitions in buildcoredefinitionsmk for an allsubdirscalafiles and an allscalafilesunderadded definition in definitionsmk to build scala files such that they are included in the packagewhats left include scalalibraryjarensure changes to bootclasspath has not broken anythingfigure out how to handle case where scala classes depend on java classes and visa versamajor cleanup of codetestingfigure out what to do other than just posting them here with the changes i have madelooks like i am almost theresome notes from the pastlatest i have found where the java source files are compiled in definitionsmk see define transformjavatoclassesjar the latest idea is to write a transformscalatoclasses definition and then have it store those classes in the directly that gets packaged i will call transformscalatoclass right before this step in transformjavatoclassesjar support for eclipse and cygwin will for now be dropped as it clutters up the code with workarounds and therefore increases my chances of failurethe build process starts out by the root makefile running buildcoremainmkbuildcoremainmk includes buildcoreconfigmk which includes buildcorecombojavacmk which sets host javac target javac and common javac common javac is the java compiler command with common arguments by the look of it the other two variables get these values by default unless in a special environment openjdk or eclipse common javac is not used outside this file the other two are only used in buildcoredefinitionsmkbuildcorejava librarymk included by configmk seems to only be concerned with building jars this is out of the scope of us caring any interaction with jars presupposes class files which presuppose that we were already successful in building our scala filesthere are checks in mainmk regarding the version of java we will ignore these and assume that our version of scala is compatible right now in comboscalacmk i am using the same target arg used in javacmk this should perhaps be stored in a variablemainmk also includes buildcoredefinitionsmk which in turns defines some useful functions the one we care about here is alljavafilesunder and allsubdirjavafiles the latter is used in androidmk files to find java files the former is used in the implementation of the latter i will write scala equivalents of themto figure out how the build process works i am now running make with n and others i got this idea from the stackoverflow article tool for debugging makefiles2 i am also investigating debugging with remakebuildcoreconfigmk definitionsmk gives us light as to which make filescommands are used to do whatas a possible way of hacking in support on a per project bases additional code could most likely be added to the projects androidmk file from platformbuildcorebuildsystemhtml we read androidmk is the standard name for the makefile fragments that control the building of a given module only the top directory should have a file named makefile you could create a new target like scalabuild and run that make packagename scalabuild before the final make one could perhaps also hide it sneakily in a variable assignment mitigating the need for a target to be called explicitlyanother way far far more hackish is to hijack the command being used for javac this is set in buildcorecombojavacmk your projects androidmk will have to include scala files in local src files along with the java files,['android'] +78552,is it possible to hide show table columns by changing the css class on the col element only i am trying to hide show columns in a table based on users choices during runtime i defined two css classeshide visibility collapse show visibility visible i tried to set these styles on the col element corresponding to the column i want to hide showtable thead tr thcolumn 1th thcolumn 2th tr thead colgroup col classhide col colgroup tbody tr tdrow 1 column 1td tdrow 1 column 2td tr tbodytablehowever it only seems to work in firefox but not in safari or chrome does safari and chrome require special handling i try to avoid looping through all the rows and modifying the css class style on each corresponding td and the number of columns in the table is large so i would like to avoid creating one css class per column as well is there any reliable way to hide show columns across browsers just by changing the css class on col,['css'] +78557,memory leak with stdstring when using stdlist i am working with stdliststdstring in my current project but there is a memory leak somewhere connected with this so i have tested the problematic code separatelyinclude iostreaminclude stringinclude listclass line public line line stdstring mstringlineline mstring new stdstringxlineline mstringclear should not be neccessary delete mstringint mainint argc char argv no memory leak while 11 stdstring test new stdstringx delete test leak this causes a memory overflow because the string thats added to the list is not deleted when the list is deleted while 11 stdliststdstring sl new stdliststdstring stdstring s new stdstringx slpush backs slpop back does not delete the string just the pointer delete sl leak here the string is deleted but the memory does still fill up but slower while 11 stdlistline sl new stdlistline line s new line slpush backs slpop back does delete the lineelement slclear delete sl return 0 this does not cause any noticable memory leak while 11 stdlistint sl new stdlistint int i 0xf slpush backi slclear delete sl return 0 this does not cause any overflow or leak while 11 int i i new int 9 delete i why does my string list cause a memory leak should not deleting the list cause the destructors to be called on each contained string,['c++'] +78566,determining running programs in python how would i use python to determine what programs are currently running i am on windows,['python'] +78571,pythonic way to convert a list of integers into a string of commaseparated ranges i have a list of integers which i need to parse into a string of rangesfor example 0 1 2 3 03 0 1 2 4 8 0248and so oni am still learning more pythonic ways of handling lists and this one is a bit difficult for me my latest thought was to create a list of lists which keeps track of paired numbers 0 3 4 4 5 9 20 20 i could then iterate across this structure printing each sublist as either a range or a single valuei do not like doing this in two iterations but i cannot seem to keep track of each number within each iteration my thought would be to do something like thisheres my most recent attempt it works but i am not fully satisfied i keep thinking there is a more elegant solution which completely escapes me the stringhandling iteration is not the nicest i know it is pretty early in the morning for me def createrangestringzones rangeidx 0 ranges zones0 zones0 for zone in listzones if rangesrangeidx1 in zone zone1 rangesrangeidx1 zone else rangesappendzone zone rangeidx 1 rangestr for range in ranges if range0 range1 rangestr sdd rangestr range0 range1 else rangestr sd rangestr range0 return rangestr1is there a straightforward way i can merge this into a single iteration what else could i do to make it more pythonic,['python'] +78572,how do i get placeholder text in firefox and other browsers that do not support the html5 tag option this works in chrome and any other browser that supports placeholder text in html5input idname namename typetext placeholderplease enter your name required br but it does not work in 35 and earlier of firefox and obviously ie8 and possibly other browsershow do i achieve the same thing preferably in htmlcss if not i am open to suggestions to support all the older browsers if not every single browser at least firefox and iesafari and chrome already support it or the latest versions anywaythanks,"['html', 'css']" +78577,how to initialize with multiple return values in c0x tuple in boost and tr1c0x provides a convenient for the writer of the function method to return two values from a functionhowever it seems to damage one major feature of the language for the caller the ability to simply use the function to initialize a variablet happyconst auto meaningful namehappy rvo means no excess copiesbut fortupletu sadwe either have to surrender the ability to pick a meaningful name for our return values and use getn everywhereconst auto two unrelated thingssador make a temporaryconst auto unwanted named temporarysadconst auto one nameget0unwanted named temporaryconst auto two nameget1unwanted named temporaryor switch from initialization to assignment which only works when the types are assignable and breaks autotuple element0 decltypesadtype one mutable there might be a lesstuple element1 decltypesadtype two mutable verbose waytieone mutabletwo mutable sador do something unnatural to a local classconst struct ugh ugh decltypesad rhs one nameget0rhs two nameget1rhs const tuple element0 decltypesadtype one name const tuple element1 decltypesadtype two name stuffsad at least we avoid the temporary and get initializationis there a better way i am using vc10 compatible constructs above would anything in full c0x or boost help ideally it wouldallow me to use initialization not just assignmentlet the caller pick the names for the returnedinto variablesnot make extra copieswork for both stack variables and class memberspossibly be a big crazy template library but have sane syntax for caller and function writer,['c++'] +78589,has anyone created a 3d website that works on a 3d monitor i stumbled upon this site and i think that in the future we will have a new hype word 3d website that is used heavily in marketing however what i am interested in is how to create such designslayouts how is that funnylooking effect actually applied and are there any w3 specs describing ways to detect 3ddevice or are there a media query for 3d devices likemedia 3d 3d related css i am just so curious,['css'] +78593,how to create a 2 way map in java i need a data structure to store stringint value pairs in an 11 relationship and being able too look up from either way their counterparti wrote a class with a hashtable and a string array and stored the data 2 times and used the built in functions for lookupmy question is that is there a nicer way to accomplish this and by nicer i mean being efficient and not storing the data 2 times and preferably without writing a ton of code either p,['java'] +78594,how does object id assignment work i am playing around with rubys object id and noticed that in several sequential sessions of irb i get these identical resultsfalseobject id 0trueobject id 2nilobject id 4100object id 201in fact every integers object id seems to be value 2 1on the other hand a given strings object id is never the same after exiting and rerunning irbthis raises several questions for meis there a known scheme by which certain object ids are determined are others basically randomthe ids for true false and nil are not sequential is there a way to ask what object is represented by a given id i am curious what the other singledigit and ids are tied tocould you not that you should write obfuscated ruby where you use known object ids to refer to objects without naming them like object of id 201 object of id 19 to mean 100 9updateusing andrew grimms suggestion i tried thiscovering other low id objects but found thatthere do not appear to be any more evennumbered objects in this sequence ids 6 8 10 etc do not point to anythingas implied by my earlier experiment all the oddnumbered ids belong to numbers specifically id 1 points to the number 0 3 points to 1 5 points to 2 and so forth,['ruby'] +78597,how can i pass parameters to a jquery getjson callback method i am trying to use jquery to call some custom api via ajaxgetjson i am trying to pass a custom value into the ajax callback method but that value is not getting passed through and is actually getting overwritten this is my codevar locationtype 3var url blah blah blah locationtype locationtypeloading statusshowgetjsonurl null functionresults locationtype searchresultsresults locationtypenow the value of locationtype before i call the url using ajax is 3 but after the ajax returns the data successfully the value for locationtype is now success this is because the method signature of the callback iscallbackdata textstatusa callback function that is executed if the request succeedshm ok so how can i pass 1 or more parameters to a callback method please,"['javascript', 'jquery']" +78603,well documented open source project in net im seaching some good quality open source project in net according this topic i found intresting open source projects like sharp develop its great because i can build run it without problem but i would like learn how it was developed in deep learning from only source code without well documented classes pattern used in project techniques etc is difficult task can anyone provide information about project which i can understand easierthanks for suggestions,"['c#', '.net']" +78604,add application launch shortcut in eclipse i have been programming android in eclipse for about a year now and i have always launched my app by right clicking on my project name in the project explorer followed by run as then android application there has to be a better way is there a way to change this three mouse clicks right click on project run as android applicationto this one hotkey press my favorite hotkeyso i can just press one button to launch my app thanks,['android'] +78615,php send cookie with file get contents the example on php manual shows how you can use stream contexts to send a cookie here is the excerpt create a streamopts array httparray methodget headeracceptlanguage enrn cookie foobarrn context stream context createopts open the file using the http headers set abovefile file get contents false contexthow do you send more than one cookie like 1 or 2 or what1cookie user3345passabcdrn2cookie user3345rn cookie passabcdrn,['php'] +78628,java how do i override a method of a class dynamically class is eventually not in classpath how do i call a method of a class dynamically conditionallyclass is eventually not in classpathlet us say i need the class nimbuslookandfeel but on some systems it is not available ie openjdk6so i must be able toget to know it that class is available at runtimeif it is not the case skip the whole thinghow do i manage to override a method of a dynamicallyloaded classthus creating an anonymous inner subclass of itcode examplepublic static void setnimbusuifinal imethoduidefaults method throws unsupportedlookandfeelexception nimbuslookandfeel may be now available uimanagersetlookandfeelnew nimbuslookandfeel override public uidefaults getdefaults uidefaults ret supergetdefaults methodperformret return ret editnow i edited my code as it was suggested to intercept noclassdeffounderror using trycatch it fails i do not know if it is openjdks fault i get invocationtargetexception caused by noclassdeffounderror funny that i cannot catch invocationtargetexception it is thrown anywayedit2cause found i was wrapping swingutilitiesinvokeandwait around the tested method and that very invokeandwait call throws noclassdeffounderror when loading nimbus failsedit3can anyone please clarify where noclassdeffounderror can occur at all because it seems that it is always the calling method not the actual method which uses the nonexisting class,['java'] +78636,rijndael 256 encryptdecrypt between c and php updatedi have made the changes to the c code so it uses a block size of 256 but now the hello world looks like this and i cant figure out what i should use with rtrim to get ride of the mess at the endalso when you say the iv should be random by this do you mean do not use the same iv more then once or is the way i have coded it wrongthanks againhii am trying to decrypt a string with php that was encrypted in c i cannot seem to get php to decrypt it using mcrypt and could do with some help please i get the following error with php so i am guessing i am not setting the iv correctlyerror the iv parameter must be as long as the blocksizeboth functions use the same cipher key iv and set to cbc modeencrypted text from c umzucnazthh0nmkiumisqgkey 32 long qwertyuiopasdfghjklzxcvbnmqwerty iv 16 long 1234567890123456c public static string encryptstringstring message string keystring string ivstring byte key asciiencodingutf8getbyteskeystring byte iv asciiencodingutf8getbytesivstring string encrypted null rijndaelmanaged rj new rijndaelmanaged rjkey key rjiv iv rjmode ciphermodecbc try memorystream ms new memorystream using cryptostream cs new cryptostreamms rjcreateencryptorkey iv cryptostreammodewrite using streamwriter sw new streamwritercs swwritemessage swclose csclose byte encoded mstoarray encrypted converttobase64stringencoded msclose catch cryptographicexception e consolewritelinea cryptographic error occurred 0 emessage return null catch unauthorizedaccessexception e consolewritelinea file error occurred 0 emessage return null catch exception e consolewritelinean error occurred 0 emessage finally rjclear return encrypted phpvar mcrypt cipher mcrypt rijndael 256var mcrypt mode mcrypt mode cbcfunction decryptkey iv encrypted encrypted base64 decodeencrypted decrypted rtrimmcrypt decryptthismcrypt cipher key encrypted thismcrypt mode iv 0 return decryptedthanks,"['c#', 'php']" +78663,how does one remove duplicate elements in place in an array in on in c or c is there any method to remove the duplicate elements in an array in place in cc in on suppose elements are a512234then resulting array should contain 1234the solution can be achieved using two for loops but that would be on2 i believe,"['c++', 'c']" +78666,visual studio professional 2010 stop new from autocompleting into new object c in visual studio professional 2010 whenever i type the followingnew it automatically changes tonew object is there a way to make it not do this object does not have the properties of the object i want to anonymously create,"['c#', 'asp.net']" +78667,list comprehension for running total i want to get a running total from a list of numbersfor demo purposes i start with a sequential list of numbers using rangea range20runningtotal for and in rangelena new runningtotaln1 an if and 0 else an runningtotalappendnew this one is a syntax error runningtotal an for and in rangelena if and 0 else runningtotaln1 anfor i in zipa runningtotal print 0315formatiyields 0 0 1 1 2 3 3 6 4 10 5 15 6 21 7 28 8 36 9 45 10 55 11 66 12 78 13 91 14 105 15 120 16 136 17 153 18 171 19 190as you can see i initialize an empty list then append in each loop iteration is there a more elegant way to this like a list comprehension,['python'] +78676,what is the getcsscanvascontext method of an html5 element what is the getcsscanvascontext method i saw it in chromeas debuging console but i cannot find any decent documentation for itdoes it mean we can draw using canvas commands on any element,['javascript'] +78680,correct way to uninstall a windows service i have got a windows service built using c that is installed via a vs2008 setup project and am having a couple of problems occurring with the uninstall proceservice is not stopped prior to uninstallingwhen the uninstall routine runs it throws up an error about files being in use clicking continue completes the installer correctly but the service still shows up in the list so it is not being uninstalled properlyat present i have to resort to deleting it manually using sc delete servicenamei am trying to stop the service before uninstalling using the following code but it does not seem to be taking effectprotected override void onbeforeuninstallidictionary savedstate baseonbeforeuninstallsavedstate servicecontroller servicecontroller new servicecontrollermyinstallerservicename servicecontrollerstopwhen is this code called and how can i stop the service prior to uninstallinginstallation folder not deleted after uninstallingthe application also creates some files within it is installation folder when executed after uninstalling the installation folder cprogram filesmyapp is not deleted and contains the files created by the application though all other files that were actually installed by the installer have been deleted successfullyis it possible for the uninstall process to delete the installation folder including all generated files within that folder and if so howthanks,['c#'] +78684,what can cause invalid binary with no email followup from itunes connect i am trying to submit an update of an existing application on behalf of one of my clients and i am getting invalid binary failures from itunes connect with no explanation of the error i am leaving on a 2 week vacation without network access tomorrow so i am a bit desperate for a solution any insights are greatly appreciatedthis update changes the name of the application and fixes a few minor bugs i did previous submissions via the itunes connect but i am submitting this update via xcode as apple now requiresi set myself up as the technical contact for this client so i receive a notification when i put the new version into a waiting for upload state via itunes connect when i then validate the binary via the xcode organizer the tool eventually reports that the binary is valid when i submit the binary via the xcode organizer it eventually comes back and says that the binary has been successfully uploaded both of these steps take a while maybe 15 minutes each probably because the app bundle is 63 megabytes with thousands of resourcesfor the next hour or two the itunes connect portal still reports that the application is in a waiting for upload state i believe some latency is normal between the time when the upload completes in xcode and when the state changes in itunes connect these hours of latency seem excessive but not entirely surprising i suppose given the size of the appeventually the state just silently changes to invalid binary in itunes connect i understand that itunes connect is supposed to send out an email explaining the error when this happens but i am not receiving anything nor is my client i assume it should go out to all users flagged for notification of app state changes in itunes connect is this assumption correcthere are the build settings copied and pasted from my app store thistribution configurationadditional sdks archs archs standard 32 bitsdkroot iphoneos40only active arch yesvalid archs armv6 armv7symroot userscduhndocumentsworkspacexcode build outputobjroot symrootconfiguration build dir build dirconfigurationeffective platform nameconfiguration temp dir project temp dirconfigurationeffective platform nameshared precomps dir cache rootsharedprecompiledheadersbuild variants normaldebug information format dwarfwithdsymenable openmp support nogenerate profiling code noprecomps include headers from built products dir yesrun clang static analyzer noscan all source files for includes novalidate product nocode sign entitlements entitlementsplistcode sign identity code sign identitysdkiphoneos iphone thistribution capturing momentscode sign resource rules path other code sign flags stripflags alternate group install groupalternate owner install owneralternate mode install mode flagalternate permissions files deployment location nodeployment postprocessing noinstall group groupinstall owner userinstall mode flag uwgowarxdstroot tmpproject namedstinstall path homeapplicationsmacosx deployment target inheritedskip install yescopy phase strip yesstrip installed product strip style alltargeted device family 1separate strip noiphoneos deployment target 30module name module start module stop module version bundle loader standard c plus plus library type dynamicdylib compatibility version dylib current version linker thisplays mangled names nopreserve dead code inits and terms nold dylib install name exported symbols file init routine link with standard libraries yesmach o type mh executeld openmp flags fopenmporder file other ldflags all load objcld map file path target temp dirproduct namelinkmapcurrent variantcurrent archtxtgenerate master object file noprebinding noprelink libs keep private externs nold runpath search paths separate symbol edit noprelink flags sectorder flags unexported symbols file warning ldflags ld generate map file nocompress png files yesapply rules in copy files noexecutable extension executable prefix infoplist expand build settings yesgenerate pkginfo file yesframework version ainfoplist file irevealmauiinfoplistinfoplist other preprocessor flags infoplist output format binaryinfoplist preprocessor definitions infoplist prefix header infoplist preprocess nocopying preserves hfs data noprivate headers folder path contents folder pathprivateheadersproduct name irevealmauiplist file output format binarypublic headers folder path contents folder pathheadersstrings file output encoding binarywrapper extension appalways search user paths noframework search paths header search paths sdkrootusrincludelibxml2 three20buildproductsthree20library search paths inherited srcrootdesiccantclassesexternalgoogleanalyticsrez search paths excluded recursive search path subdirectories nib lproj framework gch cvs svn xcodeproj xcode pbproj pbxprojincluded recursive search path subdirectories other test flags test host test rig current project version version info file product name verscversion info export decl version info prefix version info suffix versioning system version info builder usergcc fast objc thispatch yesgcc auto vectorization nogcc objc call cxx cdtors yesgcc enable sse3 extensions nogcc enable sse41 extensions nogcc enable sse42 extensions nogcc enable supplemental sse3 instructions nogcc strict aliasing nogcc feedback directed optimization offgcc enable fix and continue nogcc generate debugging symbols yesgcc dynamic no pic yesgcc generate test coverage files nogcc inlines are private extern yesgcc model tuning g4gcc instrument program flow arcs nogcc enable kernel development nogcc debugging symbols defaultgcc reuse strings yesgcc no common blocks nogcc enable objc gc unsupportedgcc optimization level sgcc fast math nogcc enable symbol separation yesgcc threadsafe statics yesgcc symbols private extern yesgcc unroll loops nogcc model ppc64 nogcc char is unsigned char nogcc enable asm keyword yesgcc c language standard c99gcc check return value of operator new nogcc cw asm syntax yesgcc input filetype automaticgcc altivec extensions nogcc enable cpp exceptions yesgcc enable cpp rtti yesgcc link with dynamic libraries yesgcc enable objc exceptions yesgcc enable trigraphs nogcc enable floating point library calls nogcc use indirect function calls nogcc use register function calls nogcc increase precompiled header sharing noother cplusplusflags other cflagsgcc precompile prefix header yesgcc prefix header irevealmaui prefixpchgcc enable builtin functions yesgcc enable pascal strings yesgcc force cpu subtype all nogcc short enums nogcc one byte bool nogcc use standard include searching yesgcc preprocessor definitions gcc preprocessor definitions not used in precomps gcc warn check switch statements nogcc warn effective cplusplus violations nogcc warn four character constants nogcc warn about global constructors nogcc warn shadow nogcc warn 64 to 32 bit conversion nogcc warn allow incomplete protocol yesgcc warn inhibit all warnings nogcc warn initializer not fully bracketed nogcc warn about return type yesgcc warn missing parentheses nogcc warn about missing field initializers nogcc warn about missing prototypes nogcc warn about missing newline nogcc warn multiple definition types for selector nogcc warn non virtual destructor nowarning cflags gcc warn hidden virtual functions nogcc warn pedantic nogcc warn about pointer signedness yesgcc warn prototype conversion nogcc warn sign compare nogcc warn strict selector match nogcc treat implicit function declarations as errors nogcc treat nonconformant code errors as warnings nogcc treat warnings as errors nogcc warn typecheck calls to printf yesgcc warn undeclared selector nogcc warn uninitialized autos nogcc warn unknown pragmas nogcc warn unused function nogcc warn unused label nogcc warn unused parameter nogcc warn unused value nogcc warn unused variable yesgcc warn about deprecated functions yesgcc warn about invalid offsetof macro yesibc flatten nibs yesibc other flags ibc plugin search paths ibc plugins ibc errors yesibc notices yesibc warnings yeshere are the contents of my infoplistany insights are greatly appreciatededit apparent status change latency explainedbased on my status history it appears that the invalid binary status is actually being established within minutes but itunes connect is concealing this fact with a poorly designed caching strategy to monitor for a change in state i have been refreshing and clicking around between four pages manage your applications the app information page view details and status history when the status history finally updates it shows that the app went into an invalid binary state around an hour prioras an experiment i tried changing my app id and submitting the binary as a new app this time i clicked into the view details page a few minutes after submitting the binary its status showed upload received apparent progress a couple minutes later i clicked into status history and it showed invalid binary mere minutes after my upload finished then i went back and refreshed my view details page it still shows upload received despite the fact that the status history shows invalid binary this is pretty clear evidence that all these pages are being cached and showing stale data for long periods of time i only caught this when i resubmitted the binary as a new app because i was loading the pages for that app for the first timethis does not solve my invalid binary problem nor does it explain why i am not getting any emails but it does help rule out some hypotheses,['iphone'] +78687,what can i do to avoid tcp zero window tcp window full on the receiver side i have a small application which sends files over the network to an agent located on a windows oswhen this application runs on windows everything works fine the communication is ok and the files are all copied successfullybut when this application runs on linux redhat 53 the receiver is still windows i see in wireshark network trace messages of tcp zero window and tcp window full to appear on each 12 seconds the agent then closes the connection after some minutesthe windows linux code is almost the same and pretty simple the only nontrivial operation is setsockopt with so sndbuf and value of 0xf removing this code did not helpcan someone please help me with this issueedit adding the sending code it looks that it handles properly partial writesint totalsent0whiletotalsent datalen int bytessent send socketchar datatotalsent datalentotalsent 0 if bytessent 0 return totalsent else ifbytessent socket errorifdef win32 int errcode wsagetlasterror if errcodewsaewouldblock else if errno ewouldblock errno eagain endif else if totalsent totalsent socket error break else totalsentbytessent thanks in advance,['c++'] +78692,how to check this url is image url i need to check the url is image url or not how can i do thisexample if i put is not image urlbut if i put or is is image url,['php'] +78703,ios mkmapview zoom to show all markers i am working with mkmapview and have plotted several points on the map i have used the mkcoordinateregion and mkcoordinatespan to enable zooming etc around one of the points but that is not what i wanti am trying to use something similar to the javascript zoom to bounds function so all my points should be visible to the user there will be around 10 points around the uk i would like to show them all or if most of them were in the london area zoom to there is there a way to work this out programatically,['iphone'] +78712,are there any instances when the destructor in php is not called this is my first time posting to stackoverflow but i these threads have helped me tremendouslyanywho onto my question are there any instances when the destructor in php is not called the reason i ask is because i have a mapper class which maps data to objects and in the constructor i start a transaction and in the destructor i will call a commit i will also have a member function which can also do the committal if necessary if there are any instances when the destructor is not called i would like to know so i can anticipate it happening and plan appropriatelythanks very much,['php'] +78714,what is best orm with these requirements i am looking for a good orm for an upcoming projectthe database will have around 10 to 1200 tables and it will be in both sql server and oracle which will be used depending of customers enterprise needsalso a few part of the project will work with wcf servicesi want a designer or something like thatgood support of linqacceptable performancei have tried dataobjectsnet but it does not have any designer we cannot code all that tables nor use code generator and i am not sure if dataobjectsnet supports switching databasealso i am familiar with ef4 but it cannot support both databases together and switching databases manuallymodifying the edmx file is such a pain in for maintenance jobthanks in advanceedit seems openaccess and llblgen pro have designer but i do not have experience with them,"['c#', '.net']" +78728,mod operator on x86 vs x64 i need help for resolve a strange bug a when i use mod operator on x86 all good but on x64 i get sometimes nan as remainder it usually happens with angle 0 i managed to reproduce that bug outside my code but only with angle doubleepsilon at my code it also happens with angle 0class program public const double m pi 314159265358979323846 static void mainstring args double m 2pi 2 m pi double m angle doubleepsilon double mod m angle m 2pi x86 mod 494065645841247e324 x64 mod nan if doubleisnanmod debugwritemod regards shay,['c#'] +78729,vs in this tutorial there is headeri know that in html there is headbut what is header thanks,['html'] +78738,embed raw data in html to parse in jquery i have been living in the desktop world for most of my career so forgive me for asking such a basic question but i am not quite sure where to start lookingi want to return some raw data along with my html and parse and thisplay the data using jquery as soon as the html is ready i know roughly what my js code should look like but i am not sure how i should embed the raw data in my htmli could use getjson but it would be better if i could have the data right in my htmli think either json or xml would work but whats the proper way to escapeembedparse these when they are embedded in htmlthanks in advance,"['javascript', 'html']" +78754,bundle id suffix what is it i am new to the iphone submission process apple asks for the bundle id suffix what is this not sure what to put here and what the significance of it is,"['iphone', 'ios']" +78755,start stop builtin wifi usb tethering from code how can i start or stop the builtin tethering in android 22 from my application,['android'] +78757,use of boost bimap in c c boost has bimap container that is a bidirectional map 43 0libsbimapdochtmlindexhtmldoes anyone know the performance of boostbimap i mean whats the time complexity of accessing an element in the map is it as quick as unordered map access which is o1thanks,['c++'] +78773,what benefit is there of allowing a variable to be left uninitialized in many languages youre allowed to declare a variable and use it before initializing itfor example in c you can write a snippet such asint xcout xthis would of course return unpredictable well unless you knew how your program was mapping out memory results but my question is why is this behavior allowed by compilersis there some application for or efficiency that results from allowing the use of uninitialized memoryedit it occurred to me that leaving initialization up to the user would minimize writes for memory mediums that have limited lifespans writecycles just a specific example under the aforementioned heading of performance thanks,['c++'] +78779,why does c support memberwise assignment of arrays within structs but not generally i understand that memberwise assignment of arrays is not supported such that the following will not workint num13 123int num23num2 num1 error invalid array assignmenti just accepted this as fact figuring that the aim of the language is to provide an openended framework and let the user decide how to implement something such as the copying of an array however the following does workstruct mystruct int num3mystruct struct1123mystruct struct2struct2 struct1the array num3 is memberwise assigned from its instance in struct1 into its instance in struct2 why is memberwise assignment of arrays supported for structs but not in general edit roger pates comment in the thread stdstring in struct copyassignment issues seems to point in the general direction of the answer but i do not know enough to confirm it myselfedit 2 many excellent responses i choose luther blissetts because i was mostly wondering about the philosophical or historical rationale behind the behavior but james mcnelliss reference to the related spec documentation was useful as well,"['c++', 'c']" +78787,bundle name executable name product nameanything else bundle name executable name product name any morecan someone please help clarify the use of each of these in xcode on an iphone project they never fail to confuse the living bajezus out of meand im tired of getting them wrongsomeone please explain why the hell do we need this many different naming schemes for one app environment and what do i use each of these for so i can stick them in the right cubby hole in my head,['iphone'] +78791,c extension and operators i observed that there was at some point a and operator in gcc how can i use these under gcc 45 have they been removed and if so whenoffset block count cpfsgeoblock size block offset countcpfsc473 error expected expression before aa token,['c'] +78808,how to extract zip file using dotnet framework 40 without using third party dlls i am in a fix i need to download a zip file from network location and then decompress it on local machine and use the files the only constraint is that i cannot use any third party dll,"['c#', '.net']" +78816,how to create the union of many sets using a generator expression suppose i have a list of sets and i want to get the union over all sets in that list is there any way to do this using a generator expression in other words how can i create the union over all sets in that list directly as a frozenset,['python'] +78819,is it possible to access a profile without updating lastactivitydate in aspnet using mvc but this happens in regular tooprofilegetprofileusernamewill update the lastactivitydate for that user this is not intended when someone else is viewing that users profilein the membership class you can specify whether to update this date with a second param like somembershipgetuserusername false does not update lastactivitydatemembershipgetuserusername true updates lastactivitydateis there anyway to do something similar in the profile provider without writing my own provider,['asp.net'] +78823,convert to ucs2 is there any function in vbnet or c that encodes a string in ucs2thanks,['c#'] +78832,identify which file has included some particular header file sometimes with a complex header structure it happens some header is included but it is hard to tell where fromis there some tool depedency viewer or a method how to find the inclusion stack which source which header which header is including one particular header fileif the header file is included multiple times finding first inclusion is sufficient finding all inclusions is a welcome bonus,"['c++', 'c']" +78837,how does this function with a yield work in detail i got this method inside a unity c script but i do not understand how the yield part actually worksi know from the msdn that the function will return an ienumerator which i could iterate throught but this code waits 15 seconds and does not get iterated because this would mean the objects created inside were created multiple timesanyone here who can explain me how this code worksienumerator destroyship create new gameobject instantiateexplosionprefab transformposition transformrotation make current gameobject invisible gameobjectrendererenabled false set new position for the current gameobject transformposition new vector30f transformpositiony transformpositionz wait for 15 seconds yield return new waitforseconds15f make the current gameobject visible again gameobjectrendererenabled true,['c#'] +78850,why does adding two decimals in javascript produce a wrong result possible duplicateis javascripts math broken why does js screw up this simple mathdocumentwrite1 2 0304documentwrite3 6 089the first example is greater than the correct result while the second is less how do you fix this do you have to always convert decimals into integers before performing operations do i only have to worry about adding and do not appear to have the same problem in my testsi have looked in a lot of places for answers some tutorials like shopping cart forms pretend the problem does not exist and just add values together gurus provide complex routines for various math functions or mention js does a poor job in passing but i have yet to see an explanation,['javascript'] +78875,why lock when reading from a dictionary i am confused by a code listing in a book i am reading c 3 in a nutshell on threadingin the topic on thread safety in application servers below code is given as an example of a usercachestatic class usercache static dictionary intuser users new dictionary int user internal static user getuserint id user you null lock users why lock this if userstrygetvalueid out u return u you retrieveuserid method to retrieve from databse lock users usersid u why lock this return u the authors explain why the retrieveuser method is not in a lock this is to avoid locking the cache for a longer periodi am confused as to why lock the trygetvalue and the update of the dictionary since even with the above the dictionary is being updated twice if 2 threads call simultaneously with the same unretrieved id what is being achieved by locking the dictionary readmany thanks in advance for all your comments and insights,['c#'] +78896,serializing dictionary when dictionary was initialized with case insensitive string comparer i am serializing a dictionary to xml when i create a new dictionary i use the constructor to provide equalitycomparer without casing for instancevar tabs new dictionarystringtabstringcomparerordinalignorecasei then serialize to xml and when i deserialize information about casing is lost the deserialization is made to the dictionary with genericequalitycomparer which apparently is case sensitive because it does not find my keys if they are not cased correctlyany ideas how can i change it one way would be to create a new dictionary and copy the data from the deserialized over to the new one but this seems troublesomeupdatethe deserialization worked the whole time it is just that it deserializes the serialized dictionary to one that does not use case insensitive keys,['c#'] +78927,how can i remove standard controls in an openlayersmap i use openlayers and want to create another navigationcontrol in the upperleft side i know how to add controls but this navigation is added at default while creating the openlayersmap so i want to remove that control to add an own i know already that the defaultcontrol is an openlayerscontrolpanzoom,['javascript'] +78934,get users os and version number i have spent a day on and off googeling for this no luck so farhow can i get the users os and version mine would me mac os x 1064 the spare pc in the office would be windows xp sp3 you see what i am getting ati have seen a million and one methods to get the users platform alone just not the versionjs would be ideal but a serverside php solution is ok too,"['javascript', 'php']" +78937,linq foreach performance i am iterating over an anonymous type with about 10 elementsthe question here is how is it possible that my loop takes almost 3 seconds to complete while what inside the loops happens takes less than 1 ms with a thousand elements i figure the loop must finish within the second not 3is there a way to make it iterate faster takes 1ms to complete var x ttwherep pmethodscount 0 pperweek thisprojectworkdayscount pismanual takes almost 3 seconds to complete foreach var item in x do stuff that takes 1 ms,['asp.net'] +78940,java what is this ljavalangobject i get this when i call tostring on an object i received from a function call i know the type of the object is encoded in this string but i do not know how to read it what is this type of encoding called,['java'] +78953,how copy from one stringstream object to another in c i have stringstream object ss1now i would like to create another copy from this onei try this stdstringstream ss2 ss1or stdstringstream ss2ss1neither worksthe error message is like thisstdiosbasic iosconst stdios is not accessible from bslbasic stringstream bslallocatorbasic stringstreamconst bslbasic stringstream bslallocator,['c++'] +78962,android bluetooth software caused connection abort ioexception possible duplicateofficial reasons for software caused connection abort socket write error i have problems with bluetoothchat i cannot connect droid i always get this ioexception0809 205824889 infobluetoothchat17378 message state change 30809 205851053 debugbluetoothservice17378 bt send message0809 205851108 errorbluetoothservice17378 thisconnected0809 205851108 errorbluetoothservice17378 javaioioexception software caused connection abort0809 205851108 errorbluetoothservice17378 at androidbluetoothbluetoothsocketreadnative native method0809 205851108 errorbluetoothservice17378 at androidbluetoothbluetoothsocketreadbluetoothsocketjava2860809 205851108 errorbluetoothservice17378 at androidbluetoothbluetoothinputstreamreadbluetoothinputstreamjava960809 205851108 errorbluetoothservice17378 at javaioinputstreamreadinputstreamjava1330809 205851108 errorbluetoothservice17378 at mytestbluetoothchatserviceconnectedthreadrunbluetoothchatservicejava356how can i solve this problem,['android'] +78979,how do i set thisabled attribute on html textbox in aspnetmvc i am trying to dynamically set the thisabled attribute on the html textbox and having issuesi tried this in my view string thisabledstring if somelogic thisabledstring thisabled htmltextboxnew dictionarystring object maxlength 50 thisabled readonlystate as you can see i am setting the thisabled attribute to or thisabled but when i test it seems to be thisabled in either caseam i missing something,['html'] +78983,create custom exception or use builtin exceptions currently i am in the process of writing a client class that utilizes dns sockets and ssl among other classes that love to throw exceptions other people will be implementing this class so i was wondering what the best practice is for throwing exceptionsshould i create my own custom exception so they know that it is my class throwing the exception or should i allow the classes and methods i call dns sockets etc to throw their own exceptions currently the code is in the hundreds of lines and growing with many different method calls what is the best practice for throwing exceptions in this situation,"['c#', '.net']" +78985,reset the row number count in sqlite3mysql i am using sqlite3 i load a table with say 30 rows using integer as primary id and it autoincrementsnow i delete all the rows from the table and then reload some new information onto the tableproblem is the row count my primaryid now starts with 31 is there any way that i can start loading new rows from the number 1 onwards,"['mysql', 'sql']" +79007,java email message parser is anyone familiar with a java library that helps with parsing the fields date subject from to of the email belowmessageid 1981530310758610295javamailsskkdate wed 6 mar 2010 123220 0800 pstfrom to subject some subjectmimeversion 10contenttype textplain charsetusasciicontenttransferencoding 7bitxfrom one some xto onexcc xbcc xfolder bobinboxxorigin bobrxfilename rbob nonprivilegedpstsome message,['java'] +79017,direct access to datagridview combobox in one click i am getting annoyed with clicking once to select a row in the datagridview and then clicking again to click on a control in that row in this case a comboboxis there a way configure this thing so that all this can be done in one mouse click instead of two,['c#'] +79021,jquery ajax returning 404 error but correct response i am posting some data to a php script via jquery ajax and everything executes correctly but it returns a 404 error in my firebug console the response from the php script is correct i do not understand how the script can respond and it is still throwing a 404 error the jquery error callback method triggers and the success method does notall statements performed by the php script work accurately because i can see the database being updated etci am using jquery 142 on a wordpress 3x website hosted by dreamhostmore infook i have figured out that when i include wordpres wpblogheaderphp file in the ajax script i get the error also once upon a time these scripts work and i am 90 sure they stopped working after the wp 30 update i will paste in the response headers from firebugthis header response from php that includes the wpblogheaderphp and returns a 404 error in firebugdate tue 10 aug 2010 014 gmtserver apachexpoweredby php526xpingback expires wed 11 jan 1984 050 gmtcachecontrol nocache mustrevalidate maxage0pragma nocachelastmodified tue 10 aug 2010 014 gmtvary acceptencodingcontentencoding gzipcontentlength 36keepalive timeout2 max98connection keepalivecontenttype texthtml charsetutf8this header response from php that does not include the wpblogheaderphp and returns a 200 ok in firebugdate tue 10 aug 2010 014458 gmtserver apachexpoweredby php526vary acceptencodingcontentencoding gzipcontentlength 36keepalive timeout2 max100connection keepalivecontenttype texthtml,['jquery'] +79035,is it possible to get jquery objects from an html string thats not in the dom for example in javascript code running on the page we have something likevar data htmln bodyn i want this text n bodynhtmli would like to use and at least know if its possible to get the text in the body of that html string without throwing the whole html string into the dom and selecting from there,"['javascript', 'jquery', 'html']" +79042,can you explain this sql injection the website i worked was recently attempted to be hacked by the following sql injection scriptboys and 38 union select 1 concat0x232425ifnulltable name0x30char9ifnulltable rows0x30 char90x2524233456789 from information schematables where table schema0x62646b3032 limit 441 and 88this injection returned the mysql table name this was reported by the error reporting system on that website and we managed to fix that part however i am not able to understand what does the above injection meananyone can explain thispenuel,['sql'] +79050,escape string for use in javascript regex possible duplicateis there a regexpescape function in javascript i am trying to build a javascript regex based on user inputfunction findstringinput var reg new regexp input snip perform searchbut the regex will not work correctly when the user input contains a or because they are interpreted as regex specials in fact if the user puts an unbalanced or in their string the regex is not even validwhat is the javascript function to correctly escape all special characters for use in regex,['javascript'] +79060,what is the difference between dvm and jvm what is difference between java virtual machine and dalvik virtual machine,"['java', 'android']" +79075,accessing rails restful routes in the model to clean up my code i would like access to the restful helpers in my rails model something likeusers pathetcthanks,['ruby-on-rails'] +79114,how can i read a text file without locking it i have a windows service writes its log in a text file in a simple formatnow i am going to create a small application to read the services log and shows both the existing log and the added one as live viewthe problem is that the service locks the text file for adding the new lines and at the same time the viewer application locks the file for readingthe service codevoid writeinlogstring logfilepath data fileappendalltextlogfilepath stringformat0 1rn datetimenow datathe viewer codeint index 0private void form1 loadobject sender eventargs e try using streamreader sr new streamreaderlogfilepath while srpeek 0 reading the old data addlinetogridsrreadline index srclose timer1start catch exception ex messageboxshowexmessage private void timer1 tickobject sender eventargs e using streamreader sr new streamreaderlogfilepath skipping the old data it has read in the form1 load event handler for int i 0 i index i srreadline while srpeek 0 reading the live data if exists string str srreadline if str null addlinetogridstr index srclose is there any problem in my code in reading and writing wayhow to solve the problem,['c#'] +79139,using net to validate xml against a schema i want to test true or false whether an arbitrary xml file matches a given schemafor what it is worth the schema is the word 2003 wordml schema which microsoft defines using a list of about 7 xsd filesone of these files also includes the w3c xmlxsd file by including the following statementxsdimport idxml namespace schemalocationxsdimporti am using net code like the following to do the validation public static void validatestring filename xmlreadersettings settings new xmlreadersettings settingsschemasadd to get this file i downloaded office 2003 xml reference schemas ie office2003xmlschemaexe cprogram filesmicrosoft office 2003 developer resourcesmicrosoft office 2003 xml reference schemaswordprocessingml schemaswordnetxsd settingsvalidationtype validationtypeschema settingsvalidationeventhandler new validationeventhandlervalidationeventhandler xmlreader xmlreader xmlreadercreatefilename settings while xmlreaderread my problem is that if i run this code on a machine which is not connected to the internet then i get a xmlschemavalidationexception error to the effect that it cannot find xmlxsdto fix this i downloaded a copy of xmlxsd and add it explicitly using the settingsschemasadd method the validation now works correctly when the machine is not connected to the internethowever when the machine is connected to the internet i now get an error saying that the global attribute has already been declaredso apparently i either need to add it explicitly or i do not depending on whether the machine is able to silently download it from the internet or even perhaps has previously been able to download it and has it cached somewhereso it is damned if i do and damned if i do not do i need to try it one way catch the exception and then try it the other way or is there a more elegant solution,['.net'] +79169,bool operator and today while writing some visual c code i have come across something which has surprised me it seems c supports increment for bool but not decrement it this just a random decision or there is some reason behind thisthis compiles static hmodule hmod null static bool once false if once hmod loadlibraryxthis does not static hmodule hmod null static bool once true if once hmod loadlibraryx,['c++'] +79170,xdebug profiling in php cannot get output i have got a strange issue i have setup xdebug to profile a php application were working on i believe everything is setup correctly but i get no output when i run it my configuration looks like thiszend extensionusrlocallibphpextensionsnodebugnonzts20060613xdebugsoxdebugxdebugprofiler append 1xdebugprofiler enable 0 i have tried this both on and offxdebugprofiler enable trigger 1xdebugprofiler output dir debugxdebugprofiler output dirxdebugprofiler output name cachegrindoutpall the phpinfo settings match up like they should the permissions on the output directory are set to 7 right now just so i can test it i have tried using a directory under public html as well but no luck the url i am using to launch the profiler is pagephpxdebug profileor pagephpxdebug profile1neither works any help would be greatly appreciated this app has a 56 second page load time and i have not been able to trace it through codesolutionthis was a bit difficult to read in the comments but i wanted to provide it for everybody the full path was required not just the path i had access too many thanks to hamid xdebugprofiler append1xdebugprofiler output dir homeusernamedebugxdebugprofiler output dirxdebugprofiler output name cachegrindoutsh,['php'] +79182,check if a stdvector contains a certain object possible duplicatehow to find an item in a stdvector is there something in algorithmh which allows you to check if a std container contains something or a way to make one exifax bx ay byreturn truereturn falsecan this only be done with stdmap since it uses keysthanks,['c++'] +79202,java aes and using my own key i want to encrypt a string using aes with my own key but i am having trouble with the bit length of the key can you review my code and see what i need to fixchangepublic static void mainstring args throws exception string username string password password1 string secretid blahblahblah string salt2 deliciously salty get the key byte key salt2 username passwordgetbytes systemoutprintlnsalt2 username passwordgetbyteslength need to pad key for aes todo best way generate the secret key specs secretkeyspec secretkeyspec new secretkeyspeckey aes instantiate the cipher cipher cipher ciphergetinstanceaes cipherinitcipherencrypt mode secretkeyspec byte encrypted cipherdofinalsecrectidgetbytes systemoutprintlnencrypted string ashexencrypted cipherinitcipherdecrypt mode secretkeyspec byte original cipherdofinalencrypted string originalstring new stringoriginal systemoutprintlnoriginal string originalstring noriginal string hex ashexoriginalright now i get an exception invalid aes key length 86 bytes do i need to pad my key how should i do italso do i need to set anything for ecb or cbcthanks,['java'] +79204,autogenerate an interface implementation in c i know this is quite lazy but is there any way on visual c 2010 express to autogenerate an interface implementation i do not mean at runtime but at design time like a code snippet perhaps with a third party utility,['c#'] +79234,overriding cmp eq and hash for sqlalchemy declarative base i want to override cmp eq and hash so i can do set operations on a sqlalchemy declarative base model will this cause any conflicts with the declarative base implementation,['python'] +79235,how to detect if consolein stdin has been redirected i want to write a console application that have a different behavior depending if the input is coming from keyboard or from say a fileis it possible whats the most elegant way to do it in c,['c#'] +79244,append class if condition is true in haml if postpublishedpost post stuffotherwisepostgray post stuffi have implemented this with rails helper and it seems ugly content tag div class post gray unless postpublishedto s do post stuffsecond variant content tag div class post postpublished gray do post stuffis there a more simple and hamlspecific wayupd hamlspecific but still not simpledivclass post gray unless postpublishedto s post stuff,['ruby'] +79246,add milliseconds to java date when milliseconds is long i am looking for the best way to add milliseconds to a java date when milliseconds is stored as a long java calendar has an add function but it only takes an int as the amountthis is one solution i am proposing calendar now calendargetinstancecalendar timeout calendargetinstancetimeoutsettimetokengetcreatedontimeoutsettimeinmillistimeoutgettimeinmillis tokengetexpiresinany other suggestions,['java'] +79248,xdebug loaded correctly in ubuntu but var dumperror handling not being overridden i have recently upgraded to ubuntu 1004 and as usual installed xdebug from the package manager i have never had a problem after that with getting the formatted error messages and var dumps to show up but this time they do noti ran phpinfo and it is definitely loading it and i even tried running some of the custom xdebug functions and all is working fine but when i do a var dump it comes up as though xdebug is not installed any ideas why this is happening,['php'] +79272,how to determine if an android device has a touchscreen i am spending considerable time in making my ui to work with keyboard input only but in the end i am not sure whether i can rely on the assumption that android devices all have touch screens is there a way to determine if an android device has a touch screen,['android'] +79275,onkeydown in a service global hot keys what i am basically trying to achieve is custom global hot keys or in other words things will happen when i push certain buttons no matter which program is currently on topi assume a service is neededi have a quick and dirty test that just tells me what has been pressed that will work if it is the active windowpublic boolean onkeydownint keycode keyevent event char pop pop chareventgetunicodechar toastmaketextthis charactertostringpop toastlength shortshow return superonkeydownkeycode event but obviously if i change window or go into a text box it does not work if i stick it directly into a service or an imputmethodservice and launch said service nothing happens some permissions required maybeany suggestions where i am going wrong or a better way of capturing which button is pressedthanks,['android'] +79292,size for storing ipv4 ipv6 addresses as a string what should be the ideal size for storing ipv4 ipv6 addresses as a string in the mysql database should varchar32 be sufficient,['mysql'] +79296,calling code in a string without execeval python i have this code that executes when a player attempts to eat somethingdef eattargetobject global current room global locations global inventory if target in inventory itemstargeton eat this is showing no results else print you have no target to eatand this code for itemstrimmeditems strawberry weight 1 text the strawberry is red on eat normal eatstrawberry pretty good but not as sweet as you expected trees weight 50 text the trees are tall with large leaf filled branches blocking out a majority of sunlight on eat forcesayeating trees what the hell is your problem is there a valid way of calling itemswhateveron eat without doing something silly like exec or eval if not alternative formatting as an example would also be appreciatedbefore this the itemseveryitemson eat values were not strings but that executed the on eat for every item as soon as the code was rani have seen many answers to similar questions but they do not deal with arguments for functions unique to better put that they were more like this,['python'] +79327,ldap user password authentication using jndi public static void mainstring args string initctx comsunjndildapldapctxfactory string my host ldaplocalhost1389 string mgr dn cnjohnouusersoitdcquizportal string mgr pw password identify service provider to use hashtable env new hashtable envputcontextinitial context factory initctx envputcontextprovider url my host envputcontextsecurity authentication simple envputcontextsecurity principal mgr dn envputcontextsecurity credentials mgr pw try create the initial directory context initialdircontext initialcontext new initialdircontextenv systemoutprintlncontext sucessfully initialized catchexception e systemerrprintlne i would like to ask when i set the mgr dn cnjohnouusersoitdcquizportal to mgr dn uid103ouusersoitdcquizportal basically changing from cn to uid i would encounter an error javaxnamingauthenticationexception ldap error code 49 invalid credentialsi am authenticated when is specified as cnjohn but not uid103 am i not allowed to specify by uid,['java'] +79332,how to write a program in c such that it will delete itself after execution how to write a program in c such that it will delete itself after execution,['c++'] +79365,syntax highlight in structured text editor jsp in eclipse is there a way to edit my color options for syntax highlighting in structured text editor in eclipse like i can do for java source code the maximum i could do was change the fontthanks for the help,['java'] +79371,is there anything like jrebel for net jrebel is a tool for java that can automatically swap in new versions of classes to a running jvm not only can method implementations be changed it is also possible to change their signatures to add new or remove existing methods and also addremove fields about the only thing that cannot do is allow the class hierarchy to be altered onthefly it is a real boon for web app development in particularcould i find anything similar for net,['.net'] +79383,deserializing json array using gson continuing from this questioni am having trouble deserializing the following json array sorry for the sizegeometry type polygon coordinates 771230894373 4422896962001 804804852796 4451159130080 8768285639 4417873954498 959794979827 4430944287708 910992515063 4372980866944 932488308736 4357684778349 918573372386 4115663286966 834059614976 4013708358795 929360231044 38335241529 1008029715188 3776446653183 1061663445852 3533717758754 1035703740599 3519308069656 1095348723766 3396028487184 1108462159782 3230455268230 1083571121640 3163122508021 1103953720405 3082716041755 1045722494771 3020215642212 17367719045 2915275458735 1141268013718 2827405304519 1286729192338 2790314754276 1334329406601 2695307513404 829417592210 2374337277646 6470428704 2207530090128 370914873531 2152159656850 3469488436 2173360227237 359905375891 2251757174668 1905871774 2309591361246 129963835709 2361036252651 130208738589 2404106913263 964785432600 3159802671416 964829960396 38713127631 851005781060 3424742002477 616522405653 3491025523892 547749224241 3569019334331 403724067052 3628920873754 423973082428 3724062779415 3893350478 3741450793542 317696364567 3774909265404 131414328674 37826527844 112467751341 3830221719769 185682580436 3930014456814 194499084106 4129581855629 245950952751 4175549526399 42303076294 4287174981681 112674464 4271148905617 131633628071 4371332547494 433220392528 4427574250017 593119709103 4389089571176 719645442339 4451856882422 771230894373 4422896962001 if i paste it into a jsonviewer i get this structuregeometrycoordinates array 0 array 0 array 0 771230894373 1 4422896962001 1 array 0 804804852796 1 445115913008 n array n arraynow the array containing the arrays with the coordinates has a variable size so i figured that in java this whole object whould be an array containing a collection of arrays with each array containing a collectiondouble something like collectiondoublebut gson does not accept this i get the following error messageexception in thread main comgooglegsonjsonparseexception expecting object but found array 2963610which seems weird as 2963610 doesnt look like an array to me but it might have confused me to the point where i am lost more or less,['java'] +79392,exec always returns 1 or 127 i am using php 529 on a production server and it seems that the exec function behaves nonstandardif i run execls output return var then output will contain the list of files in the current folder as expected but return var will be set to 1 instead of 0 as expectedi am using the return var to determine wherever the command finished successfully and on every other server tested this works as expectedanyone ever hit a situation like thiseditphpcommand asdt1 timeoutput arrayresult 5r execcommand output resultt2 timeecho prevar exportarray commandcommand resultresult outputimploden output rr t2t1t2t1echo prewhatever command i put in command result will always be 1 even for nonexistent commandsthis is very weird,['php'] +79398,pad with leading zeros how can i pad my integer variable with leading zeroslike i have an integer abc with value 20 but i want it to be 020codequarterlyreportdatacmmsqrtrailerrecordfilerecordcount converttoint32refeligibleclaimantscount,['c#'] +79410,subprocesspopen has inconsistent behavior between eclipsepycharm and terminal execution the problem i am having is with eclipsepycharm interpreting the results of subproces popen differently from a standard terminal all are using python261 on osxheres a simple example scriptimport subprocessargs usrbinwhich gitprint will execute s joinargstry p subprocesspopenusrbinwhich git shellfalse stdoutsubprocesspipe stderrsubprocesspipe tuple of stdout stderr is the responses so ret pcommunicate if ret0 and ret1 msg cmd s failed s fullcmd ret1 if fail on error raise nameerrormsgexcept oserror e print sysstderr execution failed ewith a standard terminal the lineret pcommunicategives mepdb print retusrlocalbingitn eclipse and pycharm give me an empty tupleret tuple changing the shell value does not solve the problem either on the terminal setting shelltrue and passing the command in altogether ie argsusrbinwhich git gives me the same result ret usrlocalbingitn and eclipsepycharm both give me an empty tupleany ideas on what i could be doing wrong,['python'] +79414,is there a way to wake a sleeping thread is there a way to wake a sleeping thread in c so have it sleep for either a long time and wake it when you want work processed,['c#'] +79421,asking is hashable about a python value i am interested in taking an arbitrary dict and copying it into a new dict mutating it along the wayone mutation i would like to do is swap keys and value unfortunately some values are dicts in their own right however this generates a unhashable type dict error i do not really mind just stringifying the value and giving it the key but i would like to be able to do something like thisfor key in olddict if hashableolddictkey newdictolddictkey key else newdictstrolddictkey keyis there a clean way to do this that does not involve trapping an exception and parsing the message string for unhashable type,['python'] +79430,httpurlconnection implementation i have read that httpurlconnection supports persistent connections so that a connection can be reused for multiple requests i tried it and the only way to send a second post was by calling openconnection for a second time otherwise i got a illegalstateexceptionalready connectedi used the followingtryurl url new urlcatchexception ehttpurlconnection con httpurlconnection urlopenconnectionset output input etcsend postreceive responseread whole responseclose input streamconthisconnecthave also tested commenting this outcon httpurlconnection urlopenconnectionsend new postthe second request is send over the same tcp connection verified it with wireshark but i can not understand why although this is what i want since i have called thisconnecti checked the source code for the httpurlconnection and the implementation does keep a keepalive cache of connections to the same destinations my problem is that i can not see how the connection is placed back in the cache after i have send the first request the thisconnect closes the connection and without the thisconnect still i can not see how the connection is placed back in the cache i saw that the cache has a run method to go through over all idle connections i am not sure how it is called but i can not find how the connection is placed back in the cache the only place that seems to happen is in the finished method of httpclient but this is not called for a post with a responsecan anyone help me on thiseditmy interest is what is the proper handling of an httpurlconnection object for tcp connection reuse should inputoutput stream be closed followed by a urlopenconnection each time to send the new request avoiding thisconnect if yes i can not see how the connection is being reused when i call urlopenconnection for the second time since the connection has been removed from the cache for the first request and can not find how it is returned backis it possible that the connection is not returned back to the keepalive cache bug but the os has not released the tcp connection yet and on new connection the os returns the buffered connection not yet released or something similaredit2the only related i found was from jdk keepalivewhen the application calls close on the inputstream returned by urlconnectiongetinputstream the jdks http protocol handler will try to clean up the connection and if successful put the connection into a connection cache for reuse by future http requestsbut i am not sure which handler is this sunnetwprotocolhttphandler does not do any caching as i sawthanks,['java'] +79431,how to tell when a java objects memory is released i have a swing browser application with a bug that as i addremove tofrom the gui the memory is not released for those objects and i am trying to track down what is holding onto them problem is i do not know how to tell when something has actually be fully released from memoryis there a way to tell if an object has been released from memory i am used to objectivec where there are several ways to tellthanks,['java'] +79438,using datetime in a for loop incrementing date is not working i have this loop its purpose is to loop through a range of dates and perform some logic to automate adding entries into the database the issue is that the incrementing portion dateadays10 is not working and is always the same result causing an infinite loop any insight for datetime date datetimenow futuredatecomparetodate 0 dateadays10 logic here,"['c#', 'asp.net']" +79440,how can i bind a datasource to an initialcontext for junit testing i am trying to run junit tests on database worker classes that do a jndi lookup on an initialcontext to get a datasource the worker classes are usually running on a glassfish v3 app server which has the appropriate jdbc resources definedthe code runs just fine when deployed on the app server but does not run from the junit testing environment because obviously it cannot find the jndi resources so i tried to setup an initialcontext in the test class that binds a datasource to the appropriate context but it does not workhere is the code i have in the testbeforeclasspublic static void setupclass throws exception try create initial context systemsetpropertycontextinitial context factory orgapachenamingjavajavaurlcontextfactory systemsetpropertycontexturl pkg prefixes orgapachenaming initialcontext ic new initialcontext iccreatesubcontextjava iccreatesubcontextjavacomp iccreatesubcontextjavacompenv iccreatesubcontextjavacompenvjdbc construct datasource sqlserverconnectionpooldatasource testds new sqlserverconnectionpooldatasource testdssetservernamesqlserveraddress testdssetportnumber1433 testdssetdatabasenamedbname testdssetuserusername testdssetpasswordpassword icbindjavacompenvjdbctestds testds dataworker dw dataworkergetinstance catch namingexception ex loggergetloggertitletestclassgetnameloglevelsevere null ex then the dataworker class has a method with the following code more or less initialcontext ic nulldatasource ds nullconnection c nullpreparedstatement ps nullresultset rs nullstring sql select column from tabletry ic new initialcontext ds datasource iclookupjdbctestds c dsgetconnection ps cpreparestatementsql setup the prepared statement rs psexecutequery ifrsnext process results catchnamingexception e throw new runtimeexceptionefinally close the resultset preparedstatement connection initialcontextif i change theiccreatesubcontextjavacompenvjdbcicbindjavacompenvjdbctestdstestdslines toiccreatesubcontextjdbcicbindjdbctestdstestdsthe worker class is able to find the datasource but fails giving an error saying that username failed to login to the serverif i pass the datasource that i create in the junit method directly into the worker it can connect and run queries so i would like to know how to bind a datasource that can be looked up by the worker class without being in the web container,['java'] +79479,check if onetoonefield is none in django i have two models like thisclass type1profilemodelsmodel user modelsonetoonefielduser uniquetrue class type2profilemodelsmodel user modelsonetoonefielduser uniquetrue i need to do something if the user has type1 or type2 profileif requestusertype1profile none do somethingelif requestusertype2profile none do something elseelse do something elsebut for users that do not have either type1 or type2 profiles executing code like that produces the following errortype1profile matching query does not existhow can i check the type of profile a user hasthanks,['python'] +79487,python coerce newstyle class i want this code to just workdef main c castable print c3 print 2c print c7 print c2 print s c print i c print f cof course the easy way out is to write intc3 but i would like to enable a simpler perlish syntax for a configuration minilanguageit is notable that if i use an oldstyle class do not inherit from object i can do this quite simply by defining a coerce method but oldstyle classes are deprecated and will be removed in python3when i do the same thing with a newstyle class i get this errortypeerror unsupported operand types for castable and inti believe this is by design but then how can i simulate the oldstyle coerce behavior with a newstyle class you can find my current solution below but it is quite ugly and longwindedthis is the relevant documentation i thinkcoercion rulesnewstyle special method lookupbonus points print powc 2 100,['python'] +79493,django combobox ok so im makeing an app that has a file name field upload file field and a combobox lets say i have smth like this for the comboboxselect namemenu option value0 selected select imp option option value1 imp 1 option option value2 imp 2 option option value3 imp 3 option option value4 imp 4 optionselectinput typesubmit valueupload i have the file upload working i made this classclass uploadfileformformsform title formscharfieldmax length50 file formsfilefieldwidgetformsfileinputhow should the class look with the combobox added to it or how can i use the file upload form and get the value from combobox and based on that value to do an action regards void,['python'] +79496,round money to nearest 10 dollars in javascript how can i round a decimal number in javascript to the nearest 10 my math is pretty rubbish today it could be the 2 hour sleep some sample cases282366 282014211 140949 10i understand i probably need a combination of mathroundfloor but i cannot seem to get expected resultany helppointers appreciatedm,['javascript'] +79497,how to round the minute of a datetime object python i have a datetime object produced using strptime tmdatetimedatetime2010 6 10 3 56 23what i need to do is round the minute to the closest 10th minute what i have been doing up to this point was taking the minute value and using round on itmin roundtmminute 1however as with the above example it gives an invalid time when the minute value is greater than 56 ie 360what is a better way to do this does datetime support this,['python'] +79500,relationship between appdelegate and mainm ok i am totally new to objc cocoa so this is probably obvious but here goesi have been moving from command line apps to cocoa apps in learning how to work with objectivec in xcode one thing i do not really understand is the role of the appdelegate and how it connects to mainmit seems like you could put your entire program in the appdelegate and it would run fine and you do not even need mainm but not the other way around if youre making a cocoa app you have to at least have the appdelegatei have done a lot of php web development and commandline tools so i guess what i am looking for is the file that the program will execute first and is intended to control the rest of themcan anyone help me understand whats going on in a cocoa program how appdelegate and mainm are or are not related and what the flow of the program is supposed to be,['objective-c'] +79518,why spinlocks are used in interrupt handlers i would like to know why spin locks are used instead of semaphores inside an interrupt handler,['c'] +79519,postgres upsert insert or update only if value is different i am updating a postgres 84 database from c code and the basic task is simple enough either update an existing row or insert a new one if one does not exist yet normally i would do thisupdate my tableset value1 newvalue1 updated time now updated username evgenywhere criteria1 criteria1 and criteria2 criteria2and if 0 rows were affected then do an insertinsert into my tablecriteria1 criteria2 value1 values criteria1 criteria2 newvalue1 there is a slight twist though i do not want to change the updated time and updated username columns unless any of the new values are actually different from the existing values to avoid misleading users about when the data was updatedif i was only doing an update then i could add where conditions for the values as well but that would not work here because if the db is already up to date the update will affect 0 rows and then i would try to insertcan anyone think of an elegant way to do this other than select then either update or insert,['sql'] +79537,android managing multiple notifications i am trying to create multiple notifications in my application to identify each notification uniquely i have given them an unique identificationid following is my codeprivate void updatenotificationint notificationid int clockstatusid charsequence text notificationmanagercancelnotificationid throws up an ongoing notification that the timer is runninglogitimercount notification id notificationidnotification not new notificationclockstatusid the icon for the status bar text the text to thisplay in the ticker systemcurrenttimemillis the timestamp for the notification to appearintent intent new intentintentputextranotificationid notificationidintentsetactionactionstring systemcurrenttimemillisintentsetclassnamecomchandertimeandroidactivitiescomchandertimeandroidactivitiestabsnotsetlatesteventinfoself gettextrstringtimer notification title gettextrstringtimer on notification text pendingintent getactivitythis 0 intent pendingintentflag update currentnotflags notificationflag ongoing eventnotflags notificationflag no clearnotificationmanagernotifynotificationid notproblemwhen a notification is selected tabs activity is called passing the intent i want to access the unique notificationid of the notification that was selected in tabs i tried intentputextra to save the notificationid in the intent but for multiple notifications its overwriting the notificationid and returns the latest one i dont understand as to why this is happening and how can i avoid this overwriting of notificationidthankschander,"['java', 'android']" +79547,how to alter mulitple columns datatype in sql server i have 10 columns in a table and i need to alter the datatypes of that columnsso how should i go with iti had tried for thisalter table tblcommodityohlc alter column cc commoditycontractid numeric180 cm commodityid numeric180for single column is finealter table tblcommodityohlc alter column cc commoditycontractid numeric180 need help for mulitple ones,['sql'] +79553,javascriptvoid0 or onclickreturn false for which is better there is a javascriptbased interface so i need not to support work without javascripti have an asomethingaelements with js code which binds on click event so i do not want page reload after users clickwhich way is better1 a hrefjavascriptvoid0somethinga2 a href onclickreturn falsesomethingawhat advantages and thisadvantages of each method,['javascript'] +79566,time of strings creation in java i am writing an app for j2me devices and pretty much care about unnecessary string creationas working with strings is builtin ie it is not necessary to create them explicitly i am not sure if i understand it rightfor instance returning a string just by using the double quotes creates the string when it is being returned ie if i have several return statements returning different strings only one of the would be created is that rightalso when using strings for printing messages with exceptions these strings never get created if the exception does not get thrown rightsorry to bother you with such a newbie question,['java'] +79574,how to set keep alive interval for http connection in wcf http transport channel in wcf uses persistent http connections by default how to control keep alive timeout for those connections default value is 100s i found that value by monitoring application in procmon i have not found any setting in http transport binding element which configures this timeout is there any net class which can control that timeout,['.net'] +79576,how to set return url for dotnetopenauth i am using dotnetopenauth to sign in to facebookhere is the codevar facebookclient new facebookclient clientidentifier appid clientsecret appsecretiauthorizationstate authorization facebookclientprocessuserauthorizationif authorization null kick off authorization request facebookclientrequestuserauthorizationelse var request webrequestcreate token uriescapedatastringauthorizationaccesstoken using var response requestgetresponse using var responsestream responsegetresponsestream var graph facebookgraphdeserializeresponsestream lblfacebookusernametext httputilityhtmlencodegraphname since i am using custom url rewriter i am receiving an error after login because return url is something like foofooaspxlabgenand i want it to hard code it to foofooany help would be appreciated,"['c#', 'asp.net']" +79589,enter key in aspnet firing wrong button i have a text box and many buttons when user is in some text box and presses the enter key then specific button click event is raised i read on the internet that there are some problems with the enter key and i tried few solutions but still it always enters that button event that button is the first button in the pagei tried creating a button which does nothing and writing this in the page loadidtextboxfaattributesaddonkeydownifeventwhich eventkeycodeif eventwhich 13 eventkeycode 13 documentgetelementbtid noenterbuttonuniqueid clickreturn false else return true all my page controls are in a form and i tried giving the form defaultbutton property to that button i created that didnt work eitherany idea why this is not working and what am i doing wrong,['asp.net'] +79594,direct call using gccs inline assembly if you want to call a cc function from inline assembly you can do something like thisvoid callee void caller asmcall 0 rcalleegcc will then emit code which looks like thismovl callee eaxcall eaxthis can be problematic since the indirect call will destroy the pipeline on older cpussince the address of callee is eventually a constant one can imagine that it would be possible to use the i constraint quoting from the gcc online docsian immediate integer operand one with constant value is allowed this includes symbolic constants whose values will be known only at assembly time or laterif i try to use it like thisasmcall 0 icalleei get the following error from the assemblererror suffix or operands invalid for callthis is because gcc emits the codecall calleeinstead ofcall calleeso my question is whether it is possible to make gcc output the correct call,"['c++', 'c']" +79615,where to find good resources to learn xaml i am looking for online resources to learnlookup xaml constructscan you recommend any good blogs tutorials references for xaml,['.net'] +79618,c elegant way to check if a propertys property is null in c say that you want to pull a value off of propertyc in this example and objecta propertya and propertyb can all be nullobjectapropertyapropertybpropertychow can i get propertyc safely with the least amount of coderight now i would checkifobjecta null objectapropertya null objectapropertyapropertyb null safely pull off the valueint value objectapropertyapropertybpropertycit would be nice to do something more like this pseudocodeint value objectapropertyapropertyb objectapropertyapropertyb defaultvalpossibly even further collapsed with a nullcoalescing operatoredit originally i said my second example was like js but i changed it to psuedocode since it was correctly pointed out that it would not work in jsthanks muchjon,['c#'] +79624,detect overall average color of the picture i have a jpg imagei need to know overall average the color of the image at first glance there can use the histogram of the image channel rgbat work i use mostly javascript and php a little python therefore welcomed the decision in these languages maybe ther are library for working with images that address similar problemsi do not need to dynamically determine the color of the picture i need just once go through the entire array of images and determine the color of each separately this information i will remember for future use,"['php', 'javascript', 'python']" +79626,jquery get this form input i am trying to get the values of multiple form inputs but the problem is i have several identical forms on the same page and only want to get the inputs from the form that was submitted so i am using the this keyword this is my codeformcontact formsubmitfunctione var fname thischildreninputfnameval var email thischildreninputemailval var comment thischildreninputcommentvalhowever when i try to log the variables to test they are returning the wrong values it says they are all undefined what would be the right way to do thisthanks for any help d,"['javascript', 'jquery']" +79662,how do i get a link to open a specific tab on a page i am working on a site for a client that has jquery driven tabbed contentlinking to the correct page is easy enough but the challenge is to open to the correct tab when you get there on the about page scroll to the bottom and click on the move it icon the one with the truck this takes you to the move it page this works fine but i would like it to be able to open the specialty tab here is the code that links to the pagelia idmoveit hrefservices move ithtmlmove italii tried this but it does not work correctlylia idmoveit hrefservices move ithtmlspecialtymove italihere is the code for the tabs on the destination pagediv idspecialtycontent classcontent p classintromoving simplified specializes in moving items such items as pool tables pianos antiques and anything else you can throw at usp div classvideolink a hrefwatch the move it specialty videos nowa div p moving such items is more complicated than most would understand and is an art form in itself we take pride in making sure that your priceless possessions are delivered damage free the employees sent to move your belongings are highly experienced in these types of items they will always be well equipped to complete the move with the most up to date technology in the moving industrypp we will always pad and wrap each individual piece as well as provide custom crates to ensure the safety of your pool table slatep div classmsg pstrongwant to download the move it specialty guidestrong go here a hrefnowap divdivhere is the jquery for operating the tabsdocumentreadyfunction this is for the tabbed content atabclickfunction evt evtpreventdefault activeremoveclassactive thisaddclassactive contentslideup var content show thisattrid content show contentslidedownbecause i will need to do this on multiple linktab combos i would like to find a systematic approachthanks for any help,['jquery'] +79663,how can i stop text from being selected in my web app the user can sometimes click the same button a number of times skipping through messages and things causing the a to be selectedso how can i prevent this using javascript jquery,"['javascript', 'jquery']" +79683,is it possible to evenly thistribute buttons across the width of an android linearlayout i have a linear layout oriented horizontally that contains 3 buttons i want the 3 buttons to have a fixed width and be evenly thistributed across the width of the linear layouti can manage this by setting the gravity of the linearlayout to center and then adjusting the padding of the buttons but this works for a fixed width and would not work for changing devices or orientationslinearlayout androidididlinearlayout01 androidlayout heightwrap content androidorientationhorizontal androidlayout widthfill parent androidgravitycenterbutton androidididbtnoneandroidlayout widthwrap content androidlayout heightwrap content androidwidth120dipbuttonbutton androidididbtntwoandroidlayout widthwrap content androidlayout heightwrap content androidwidth120dipbuttonbutton androidididbtnthreeandroidlayout widthwrap content androidlayout heightwrap content androidwidth120dipbuttonlinearlayout,['android'] +79705,is microoptimization worth the time i am a php developer and i have always thought that microoptimizations are not worth the time if you really need that extra performance you would either write your software so that it is architecturally faster or you write a c extension to handle slow tasks or better yet compile the code using hiphop however today a work mate told me that there is a big difference in is arrayarrayandarray array arrayand i was like eh that is a pointless comparison really but he wouldnt agree with me and he is the best developer in our company and is taking charge of a website that does about 50 million sql queries per day for instance so i am wondering here is that could he be wrong or microoptimization really worth the time and when,['php'] +79726,rgb value to hsl converter google maps api v3 allows styles to be applied to the map including setting the color of various features however the color format it uses is hsl or what seems like ithue an rgb hex stringlightness a floating point value between 100 and 100saturation a floating point value between 100 and 100from the docsi managed to find rgb to hsl converters online but i am unsure how to specify the converted values in a way that google maps will accept for instance a typical hsl value given by a converter would be 209a 72 49how does that hsl value map to the parameters i specified from the google maps api ie how does a hue degree value map to an rgb hex string and how does a percentage map to a floating point value between 100 and 100i am still uncertain how to do the conversion i need to given an rgb value quickly convert it to what google maps expects so that the color will be identical,['android'] +79736,how can i make setuptools install a package that is not on pypi i have just started working with setuptools and virtualenv my package requires the latest pythongearman that is only available from github the pythongearman version that is on pypi is an old one the github source is setuptoolscompatible ie has setuppy etc is there a way to make setuptools download and install the new version instead of looking for it on pypi and installing the old onefyi the new pythongearman is,['python'] +79738,creating a window manager for linux i want to create a simple stacking window manager in c for private use mainly for the purpose of learning and challenging myselfi have looked through twms source code which has relatively few bells and whistles but it seems very low level since it is not based on a widget toolkit1 would using a toolkit such as gtk be preferable i am afraid that some of the code and libraries in twm might be too antiquated edit deprecated and i want the window manager to use relatively modern libraries for the sake of understanding i would also be interested in suggestions how to start a window manager from scratch a there are not many tutorials for this purposeupdate for those thinking of similar projects i ended up using common lisp and the clx library tinywmlisp served as a basis and the brilliant clfswm and stumpwm were a great help for reference i used the clx a common lisp x interface pdf warning and xlib on freenode,['c'] +79744,restrict file access only read through php i am using a godaddy web hosting plan on a windows platform this was not my choice it has to do with a different part of the actual site using aspnet also not my choice i have a sql database with a bunch of entries with some nonsensitive customer information the primary key on this is an autoincrement integer and i have a series of pdf files that match up with each of those integers eg 5pdf 7891pdf etcmy goal is to restrict direct access to these files i want users to have to go through a search and login process php first originally i planned to put the files above the public html folder but godaddy refuses to give me root access without a dedicated server 20 a month from them the next thing i looked into was htaccess i was going to restrict access to the files to only php scripts by only allowing access to the servers ip address or localhost127001 unfortunately this does not work because godaddy does not run apache on its windows serversi could put the files into blobs in the database but that gets really messy when i need to work with them quickly plus i have had some trouble with that approachany suggestions to restrict access to the files only to a php script readfile,['php'] +79760,jquery delay not delaying the html function i am trying to do a little javascript trick to fade out a div replace its content and fade it back in the html event is replacing the content before the fadeout is completeproductsfadeout500 delay600 htmlproductpage pagenumhtml fadein500it appears that the html is not being delayed by the delay method,['jquery'] +79769,changing the background color of an intellij pane i have changed the color scheme in intellij so that the background of the java editor pane is dark and the text is light i am not sure if this is directly related however in other windows such as the run window the background stays white but any system messages are thisplayed as white text this is obviously a problem as i cannot read white text on a white background unless i manually highlight the text to have the background a different coloris there a way to change the background color of other panes other than the editor pane in intellij,['java'] +79793,how to set up a cron job to run an executable every hour i need to set up a cron job that runs an executable compiled using gcc once every houri logged in as root and typed crontab ethen i entered the following and saved the file0 path to executablehowever the cron job does not worki see that when i type path to executable i get a segmentation faulti can only execute the executable from the folder it is located inis there a way i can solve this problem,['c'] +79803,in net are static constructors called when a new appdomain is created when i create a new appdomain using appdomaincreatedomain in c will static constructors be called as asseblies are loaded inside the newly created appdomainthe assemblies in question have already been loaded into the current domain,['c#'] +79811,how can i sort a version number column generically using a sql server query i wonder if the sql geniuses amongst us could lend me a helping handi have a column versionno in a table versions that contains version number values likeversionno12310311472etci am looking to sort this but unfortunately when i do a standard order by it is treated as a string so the order comes out as versionno1103112311472intead of the following which is what i am afterversionno1231147211031so what i need to do is to sort by the numbers in reverse order eg in abcd i need to sort by dcba to get the correct sort ourder but i am stuck as to how to achieve this in a generic way sure i can split the string up using the various sql functions eg left right substring len charindex but i cannot guarantee that there will always be 4 parts to the version number i may have a list like thisversionno12311314721710316801can does anyone have any suggestions your help would be much appreciated,['sql'] +79813,generic approach to nsmanagedobjectcontext in multithreaded application i have read a number of posts here about nsmanagedobjectcontext and multithreaded applications i have also gone over the coredatabooks example to understand how separate threads require their own nsmanagedobjectcontext and how a save operation gets merged with the main nsmanagedobjectcontext i found the example to be good but also too application specific i am trying to generalize this and wonder if my approach is soundmy approach is to have a generic function for fetching the nsmanagedobjectcontext for the current thread the function returns the nsmanagedobjectcontext for the main thread but will create a new one or fetch it from a cache if called from within a different thread that goes as followsnsmanagedobjectcontext managedobjectcontext myappdelegate delegate myappdelegate uiapplication sharedapplication delegate nsmanagedobjectcontext moc delegatemanagedobjectcontext nsthread thread nsthread currentthread if thread ismainthread return moc a key to cache the context for the given thread nsstring threadkey nsstring stringwithformatp thread delegatemanagedobjectcontexts is a mutable dictionary in the app delegate nsmutabledictionary managedobjectcontexts delegatemanagedobjectcontexts if managedobjectcontexts objectforkeythreadkey nil create a context for this thread nsmanagedobjectcontext threadcontext nsmanagedobjectcontext alloc init autorelease threadcontext setpersistentstorecoordinatormoc persistentstorecoordinator cache the context for this thread managedobjectcontexts setobjectthreadcontext forkeythreadkey return managedobjectcontexts objectforkeythreadkeysave operations are simple if called from the main thread save operations called from other threads require merging within the main thread for that i have a generic commit functionvoidcommit get the moc for this thread nsmanagedobjectcontext moc self managedobjectcontext nsthread thread nsthread currentthread if thread ismainthread no only observe notifications other than the main thread nsnotificationcenter defaultcenter addobserverself selectorselectorcontextdidsave namensmanagedobjectcontextdidsavenotification objectmoc nserror error if moc saveerror fail if thread ismainthread no nsnotificationcenter defaultcenter removeobserverself namensmanagedobjectcontextdidsavenotification objectmoc in the contextdidsave function we perform the merge if called by the notification in commitvoidcontextdidsavensnotificationsavenotification myappdelegate delegate myappdelegate uiapplication sharedapplication delegate nsmanagedobjectcontext moc delegatemanagedobjectcontext moc performselectoronmainthreadselectormergechangesfromcontextdidsavenotification withobjectsavenotification waituntildoneyesfinally we cleanup the cache of nsmanagedobjectcontext with thisvoidinitialize nsnotificationcenter defaultcenter addobserverself selectorselectorthreadexit namensthreadwillexitnotification objectnil voidthreadexit myappdelegate delegate myappdelegate uiapplication sharedapplication delegate nsstring threadkey nsstring stringwithformatp nsthread currentthread nsmutabledictionary managedobjectcontexts delegatemanagedobjectcontexts managedobjectcontexts removeobjectforkeythreadkeythis compiles and seems to work but i know threading problems can be tricky due to race conditions does anybody see a problem with this approachalso i am using this from within the context of an asynchronous request using asihttprequest which fetches some data from a server and updates and inserts the store on the iphone it seems nsthreadwillexitnotification does not fire after the request completes and the same thread is then used for subsequent requests this means the same nsmanagedobjectcontext is used for separate requests on the same thread is this a problem,"['iphone', 'objective-c']" +79831,apache php output caching i am working on a php script which generates large multimb output on the fly without knowing the length in advance i am writing directly to phpoutput via fwrite and have tried both standard output and using transferencoding chunked encoding the chunks as required but no matter what i try the browser waits until all the data is written before thisplaying a download dialog i have tried flushing too after the headers and after each chunk but this also makes no differencei am guessing that apache is caching the output as the browser would normally thisplay after receiving a few kb from the server does anyone have any ideas on how to stop this caching and flush the data to the browser as it is generatedthanksj,['php'] +79832,posix api call to list all the pthreads running in a process i have a multithreaded application in a posixlinux environment i have no control over the code that creates the pthreads at some point the process owner of the pthreads receives a signalthe handler of that signal should abortcancel or stop all the pthreads and log how many pthreads where runningmy problem is that i could not find how to list all the pthreads running in process,['c'] +79838,using class member function as callback in portaudios c bindings there is a memfuncallbackstream constructior that can be called asportaudiomemfuncallbackstreammyclass streamrecordparamsrecord aninstanceofmyclass myclassmemberfunctionwhere last parameter is the callback function however without using the operator on that parameter compiler fails but as far as i know parameter is omitable when obtaining address of functions to use in function pointers is this somehow different from c callback function and ptr to func syntax,['c++'] +79841,javascript key handling and browser compatibility i am working on key handling in java script i have done some research and i would like to know whether i have a correct understanding of key handlingkeydownkeyup eventthe key down and key up events are supported by ie7 and firefox 35 i did not check the earlier versions of the browsers but i guess that they also support these eventsis it correct to say that each key on the keyboard will always have a keycodecharcodecharcode value is available on the keypressmajority of the keys will have the charcodes that represent the actual value some keys would not have a charcode associated with them eg backspace delete arrow keys am i correct to say that on the keypress the charcode will be the same as the keycodeorder of the eventskeydownkeypresskeyupdoes this order differ from browser to browser for example i have two functions first is bound to keydown event second is bound to the keypress event calling a keypress event means that the keydown event will also be called when i want only one of these events to workfinally i have been considering on using different key handling routines depending on the version browser for examplecheck browser versionget key handling routine depending on the browser versionthis will introduce additional code but should simplify the maintenance also in the future when i want to provide a support for a different browser i can simply add another routine and it would not affect existing character handling routineso far i have been reading,['javascript'] +79848,how to get a resource id with a known resource name i want to access a resource like a string or a drawable by its name and not its int idwhich method would i use for this,['android'] +79851,would it break the language or existing code if wed add safe signedunsigned compares to cc after reading this question on signedunsigned compares they come up every couple of days i would say i wondered why we do not have proper signed unsigned compares and instead this horrible mess take the output from this small program include stdiohdefine ct1t2 signed t1 a1 unsigned t2 b1 printfsigned 5sd unsigned 5sd dnt1intat2intbab define c1t printfsdntintsizeoft ctcharctshortctintctlongint main c1char c1short c1int c1long compiled with my standard compiler gcc 64bit i get thischar1signed char1 unsigned char1 1signed char1 unsigned short1 1signed char1 unsigned int1 0signed char1 unsigned long1 0short2signed short1 unsigned char1 1signed short1 unsigned short1 1signed short1 unsigned int1 0signed short1 unsigned long1 0int4signed int1 unsigned char1 1signed int1 unsigned short1 1signed int1 unsigned int1 0signed int1 unsigned long1 0long8signed long1 unsigned char1 1signed long1 unsigned short1 1signed long1 unsigned int1 1signed long1 unsigned long1 0if i compile for 32 bit the result is the same except that long4signed long1 unsigned int1 0the how of all this is easy to find just goto section 63 of the c99 standard or chapter 4 of c and dig up the clauses which describe how the operands are converted to a common type and this can break if the common type reinterprets negative valuesbut what about the why as we can see the fails in 50 of all cases also it depends on the concrete sizes of the types so it is platform dependent here are some points to considerthe convert compare process is not really a prime example for the rule of least surprisei do not believe that there is code out there which relies on the proposition that short1 unsigned1 and is not written by terroriststhis is all terrible when youre in c with template code because you need type trait magic to knit a correct after all comparing signed and unsigned value of different types is easy to implement signed x unsigned y ax0 zazb where zxy the precheck is cheap and can also be optimized away by the compiler if a0 can statically be proven so heres my question would it break the language or existing code if wed add safe signedunsigned compares to ccwould it break the language means would we need to make massive changes to different parts of the language to accommodate this changeupdatei have ran this on my good old turboc 30 and got this output char1signed char1 unsigned char1 0why is signed char1 unsigned char 0 here,"['c++', 'c']" +79852,why are these permissions being refused just for the heck of it i requested all the permissions from my application hello world to see what are the types of permissions that are granted and what are those that are refused to my amusement i found about 40 of the permissions not granted two were returned as unknown permissionshere is the log of all the permissions that were denied to me wpackagemanager 61 not granting permission androidpermissionaccess checkin properties to package comrobosoftlinuxtop protectionlevel3 flags0x84wpackagemanager 61 not granting permission androidpermissionaccess surface flinger to package comrobosoftlinuxtop protectionlevel2 flags0x84wpackagemanager 61 not granting permission androidpermissionaccount manager to package comrobosoftlinuxtop protectionlevel2 flags0x84wpackagemanager 61 not granting permission androidpermissionbind appwidget to package comrobosoftlinuxtop protectionlevel3 flags0x84wpackagemanager 61 not granting permission androidpermissionbind device admin to package comrobosoftlinuxtop protectionlevel2 flags0x84wpackagemanager 61 not granting permission androidpermissionbind input method to package comrobosoftlinuxtop protectionlevel2 flags0x84wpackagemanager 61 not granting permission androidpermissionbind wallpaper to package comrobosoftlinuxtop protectionlevel3 flags0x84wpackagemanager 61 not granting permission androidpermissionbrick to package comrobosoftlinuxtop protectionlevel2 flags0x84wpackagemanager 61 not granting permission androidpermissionbroadcast package removed to package comrobosoftlinuxtop protectionlevel2 flags0x84wpackagemanager 61 not granting permission androidpermissionbroadcast sms to package comrobosoftlinuxtop protectionlevel2 flags0x84wpackagemanager 61 not granting permission androidpermissionbroadcast wap push to package comrobosoftlinuxtop protectionlevel2 flags0x84wpackagemanager 61 not granting permission androidpermissioncall privileged to package comrobosoftlinuxtop protectionlevel3 flags0x84wpackagemanager 61 not granting permission androidpermissionchange component enabled state to package comrobosoftlinuxtop protectionlevel2 flags0x84wpackagemanager 61 not granting permission androidpermissionclear app user data to package comrobosoftlinuxtop protectionlevel2 flags0x84wpackagemanager 61 not granting permission androidpermissioncontrol location updates to package comrobosoftlinuxtop protectionlevel3 flags0x84wpackagemanager 61 not granting permission androidpermissiondelete cache files to package comrobosoftlinuxtop protectionlevel3 flags0x84wpackagemanager 61 not granting permission androidpermissiondelete packages to package comrobosoftlinuxtop protectionlevel3 flags0x84wpackagemanager 61 not granting permission androidpermissiondevice power to package comrobosoftlinuxtop protectionlevel2 flags0x84wpackagemanager 61 not granting permission androidpermissiondiagnostic to package comrobosoftlinuxtop protectionlevel2 flags0x84wpackagemanager 61 not granting permission androidpermissionfactory test to package comrobosoftlinuxtop protectionlevel2 flags0x84wpackagemanager 61 not granting permission androidpermissionforce back to package comrobosoftlinuxtop protectionlevel2 flags0x84wpackagemanager 61 not granting permission androidpermissionglobal search to package comrobosoftlinuxtop protectionlevel3 flags0x84wpackagemanager 61 not granting permission androidpermissionhardware test to package comrobosoftlinuxtop protectionlevel2 flags0x84wpackagemanager 61 not granting permission androidpermissioninject events to package comrobosoftlinuxtop protectionlevel2 flags0x84wpackagemanager 61 not granting permission androidpermissioninstall location provider to package comrobosoftlinuxtop protectionlevel3 flags0x84wpackagemanager 61 not granting permission androidpermissioninstall packages to package comrobosoftlinuxtop protectionlevel3 flags0x84wpackagemanager 61 not granting permission androidpermissioninternal system window to package comrobosoftlinuxtop protectionlevel2 flags0x84wpackagemanager 61 not granting permission androidpermissionmanage app tokens to package comrobosoftlinuxtop protectionlevel2 flags0x84wpackagemanager 61 not granting permission androidpermissionmaster clear to package comrobosoftlinuxtop protectionlevel3 flags0x84wpackagemanager 61 not granting permission androidpermissionread frame buffer to package comrobosoftlinuxtop protectionlevel2 flags0x84wpackagemanager 61 unknown permission androidpermissionread history bookmarks in package comrobosoftlinuxtopwpackagemanager 61 not granting permission androidpermissionread input state to package comrobosoftlinuxtop protectionlevel2 flags0x84wpackagemanager 61 not granting permission androidpermissionreboot to package comrobosoftlinuxtop protectionlevel3 flags0x84wpackagemanager 61 not granting permission androidpermissionset activity watcher to package comrobosoftlinuxtop protectionlevel2 flags0x84wpackagemanager 61 not granting permission androidpermissionset orientation to package comrobosoftlinuxtop protectionlevel2 flags0x84wpackagemanager 61 not granting permission androidpermissionset preferred applications to package comrobosoftlinuxtop protectionlevel2 flags0x84wpackagemanager 61 not granting permission androidpermissionset time to package comrobosoftlinuxtop protectionlevel3 flags0x84wpackagemanager 61 not granting permission androidpermissionstatus bar to package comrobosoftlinuxtop protectionlevel3 flags0x84wpackagemanager 61 not granting permission androidpermissionupdate device stats to package comrobosoftlinuxtop protectionlevel2 flags0x84wpackagemanager 61 not granting permission androidpermissionwrite gservices to package comrobosoftlinuxtop protectionlevel3 flags0x84wpackagemanager 61 unknown permission androidpermissionwrite history bookmarks in package comrobosoftlinuxtopwpackagemanager 61 not granting permission androidpermissionwrite secure settings to package comrobosoftlinuxtop protectionlevel3 flags0x84now for a fact i know level two permissions are not granted to third party application developers and are reserved only for oems but i am surprised as a lot of level three permissions have been denied to me if not all hence my question would be why is it so do i need to add something else to my manifest for those permissions to be accepted also is not the system supposed to grant my permissions on the emulator because after all its for development and is it intelligent as in it would reject permissions that it deems unreasonable of my application is android system that advanced that it understands code i would much appreciate it if you could actually explain me this concept in a couple of lines instead of pointing me to the regular permissions and security documentations i have read through it a couple of times and i guess my understanding is lacking in some perspective hence i would much prefer to read some other attempt at explaining it to me thanks,['android'] +79866,htc sense copypaste apis is there a way to access the copypaste apiui in an android htc sense based phonei really like the way a long press works in a large canvas while using sense is there a way to programmatically detect code is running on a sensebased phone and call out to those apis,['android'] +79869,is there a lib to generate data according to a regexp python or other given a regexp i would like to generate random data x number of time to test somethingeg print generate dated2313 print generate dated23422of course the objective is to do something a bit more complicated than that such as phone numbers and email addressesdoes something like this exists if it does does it exists for python if not any cluetheory i could use to do that,['python'] +79883,dynamically get changed select value i need to get the value of the selected option when changed in a select list and change the text in a span next to the select list the problem is i do not know the id of the select list there are a lot of different select lists on the page 525 and they are all created dynamically and so i cannot have the id specified in the change here is what i havejavascriptselectchangefunction var str str select optionselectedtext outtextstrtriggerchangeof course this does not work puts all of the select values in each spanhtmlselect nameanimal option valuedogdogoption option valuecatcatoption option valuebirdbirdoption option valuesnakesnakeoptionselectspan classoutspanwhat am i missing,"['javascript', 'jquery']" +79885,best practice for warning the user they will lose data i have a site which uses a lot of javascript mainly jquery and i need a nice global way to let the user know that they will lose unsaved changes when they navigate away from a particular pageat the moment i have an onchange event placed on the inputs and wrap my main navigation in a function which will thisplay the warning when clickedthis feels really clunky and does not scale well navigation which is not part of the main navigation needs to be manually wrapped which is far from ideal,"['javascript', 'jquery']" +79890,c interface without static typing is there way to do something along these linesinterface iface anytype prop1 get anytype prop2 get class class1 iface public string prop1 get public int prop2 get class class2 iface public int prop1 get public bool prop2 get i do not care about the type of the properties i just need the properties to be available this does not have to be implemented with an interface just using that as an example,['c#'] +79908,what are the fundamental differences between garbage collection in c and java i had some very wrong sounding advice recently from a senior developercoworker regaurding the c garbage collector such asyou need to use destructorseverywhere in c because the garbagecollector cannot be relied uponthe c garbage collector cannot bethought of like the java garbagecollectorthis sounds extremely fishy to me as far as i know the differences between the c and java garbage collectors are as followsthe c is a generational garbagecollector java is concurrent marksweep in 16 with g1 being the newdefault generational garbagecollector featuring java 7 and hasbeen optional since 1621 as faras i knowc as a language has the ability tomanaully thispose of objects thatimplement ithisposable java mustalways use garbage collectionalthough some frameworks like swtrequire you manually call methods torelease memory in the underlyingnative codei realize that java and c are just the languages and the garbage collectors are a component of the runtime however for this case i am specifically speaking about the sunoracle jvm and the microsoft net runtimedoes anybody have feedback,"['c#', 'java']" +79932,regex match any sequence of characters except a particular word in a url i want to match a url that contains any sequence of valid url characters but not a particular word the url in question and i want to match anything but the word gateway so would match would match would match would matchbut would not matchsomething like the followinghttpaz09gatewayovidcombut it does not seem to workupdate sorry forget to mention the language it is cnet,['c#'] +79935,how is malloc implemented internally can anyone explain how malloc works internallyi have sometimes done strace program and i see a lot of sbrk system calls doing man sbrk talks about it being used in malloc but not much more,['c'] +79949,warning assignment thiscards qualifiers from pointer target type i wrote the following codevoid buildarrayschar plastletterint length int size const char str int i int strindex 0 int lettercounter 0 for i0 isize i while strstrindex seperator strstrindex 0 lettercounter strindex plastletteri strstrindex1 lengthi lettercounter lettercounter 0 strindex and i am getting the above warning on plastletteri strstrindex1plastletter is a pointers array that points to a char in stranyone knows why i am getting it and how to fix it,['c'] +79950,creating audio using javascript in i cannot find anything through net searches but is there any plans to make an api to generate audio chunks to be played in an html5 audio tagedit this is the examplepseudocodevar music new songarray of hertz levels or notesvar box documentcreateelementaudiodocumentbodyappendchildboxboxsrc musicconvertboxplay,['javascript'] +79954,select all unique combinations of a single list with no repeats using linq i have a list of numbers and i need to create every possible unique combination of the numbers in the list without repeats using a linq query so for example if i have 1 2 3 the combinations would be 12 13 and 23i currently use two for loops like sofor int i 0 i slotidscount i for int j i 1 j slotidscount j expressioninfo info1 expressionsi expressioninfo info2 expressionsj etc is it possible to convert these two for loops to linqthanks,['c#'] +79956,css thisplaytablerow does not expand when width is set to 100 i am having a bit of a problem i am using firefox 36 and have the following dom structurediv classviewrow div classviewtypetypediv div classviewnamenamediv divand the following cssviewrow width100thisplaytablerowviewname thisplay tablecellfloatrightviewtype thisplay tablecellif i take off the thisplaytablerow it will appear correctly with the viewrow showing a width of 100 if i put it back it shrinks down i have put this up on js binwhats going on,['css'] +79959,what is a javascript bootloader i have seen this mainly in the source of facebook bootloadersetresourcemapbmxb7name what is exactly a bootloader in javascript what is its use and purpose,['javascript'] +79960,jquery ui combining sortable with droppable i am trying to combine jquery ui sortable with droppable to create multiple pages for dropping and sorting things i have setup a blog entry with a standalong demo hereand here is a jsfiddlenote that you can drag to sort the boxes even into other columns you can also click the page buttons to switch pages my problem lies in combining these two featuresby using droppable i have allowed the user to drag a box to a page button the page will then switch and the user can finish dragging it onto the newly revealed page the problem is that when the page switches the first column which appears under the dragged box does not have it is over event fire you have to drag to another column and then back to the first column to get the placeholder to appeari am not sure but i think i need to somehow clear the events or fire them manually the problem seems to stem from the fact that the dragged box is over the column when it is made visiblecan you assist with this esoteric dilemmathanksupdateso i have been considering possible work arounds for this michal suggested firing the refresh method which indeed does not solve the problem but made me think about event issuesit seems that when you mouse away and then back again the proper events fire perhaps if i can manually fire the mouseout event for the first column the reset will allow the mouseover event to fire properlyi tried thiscolumnfirsttriggermouseout but i do not think that is the same as sortables out event perhaps i should fire that event,"['javascript', 'jquery']" +79961,unionwithinstructure syntax in ctypes quick question about ctypes syntax as documentation for unions is not clear for a beginner like mesay i want to implement an input structure see heretypedef struct taginput dword type union mouseinput mi keybdinput ki hardwareinput hi input pinputshould i or do i need to change the following codeclass inputtypeunion fields mi mouseinput ki keybdinput hi hardwareinputclass inputstructure fields type dword inputtypenot sure i can have an unnamed field for the union but adding a name that is not defined in the win32api seems dangerousthanksmike,['python'] +79964,what does the mean in c void weight datarev seqstring seq todostdreverseseqbegin seqendin this c method i think this method does not return anything so the prefix is void what does tell the relationships between weight data and rev seqstring seq thanks,['c++'] +79968,aspnet counting visitors not bots i have got an aspnet 4 web site i am counting visitors at background but my code counts search engines bots too how can i understand my client is a bot or human i do not want to count botsregards,['asp.net'] +80000,custom environment variables in php is there a way to set a custom variable such as environment name in my apache vhost file that can be read via env or ini getenvironment name,['php'] +80001,android how much space is free on the sd card what is an effective way to determine how much free space is on the sd card,['android'] +80008,why would not int variable come before char array in terms of addressing no matter how i code it in c i am reading hacking the art of exploitation 2nd edition and i am currently on the section about buffer overflowsin the first example the variables are declaredinitialized in this orderint auth flag 0char password buffer16the example goes on to explain that you can use gdb to examine auth flag and password buffers addresses and youll notice that auth flags address is higher than password buffers things to keep in mind i am running all of this in ubuntu within virtualbox on a macbook pro intel processor 64biti compiled the first examples code like this gcc g fnostackprotector o auth overflow auth overflowcas expected auth flags address is higher than password buffersto remedy the problem presented above the author explains you should switch the ordering of the declarationschar password buffer16int auth flag 0i compiled the code the same way gcc g fnostackprotector o auth overflow2 auth overflow2cunfortunately i did not see auth flags address being lower than password buffers in fact it was still higher why is this what am i doing wrong,['c'] +80036,set font at runtime textview how to set font to textview which is created at runtimei created textviewtextview tv new textviewthis tvsettextsize20like i can change the sizei want to set font style to verdanahow to do thisregardsshishir,['android'] +80050,use cases for the setdefault dict method the addition of collectionsdefaultdict in python 25 greatly reduced the need for dicts setdefault method this question is for our collective educationwhat is setdefault still useful for today in python 2627what popular use cases of setdefault were superseded with collectionsdefaultdict,['python'] +80057,expandablelistview sample from google i just tried the current google sample for expandablelistiewthis sample seem very simple and easy to use but what i would like to do is to say that one of the category has no child i removed all the children but the problem is that the arrow still appears on this current linefor instance imagine that i remove all cat names the arrow is still there and when i click on it the arrow just change how to remove this arrow and launch an activity instead,['android'] +80065,php exit or return which is better i would like to know in the following case which is a better solutionin the php script if the filesize is larger than 100 then i stop the scriptphpif filesize 100 case i resultsmsg filesize is too big echo json encoderesults exitphpif filesize 100 case ii resultsmsg filesize is too big exit json encoderesults phpif filesize 100 case i resultsmsg filesize is too big return json encoderesults which is a best solutionthank you,['php'] +80069,similar syntax but one shows error but another does not hi alli made this program todayint main int a 12 shows error int b 12 no error why first one shows error while second one does not just makes one program compile whyshruti,['c'] +80070,opengl line width in my opengl app it would not let me draw a line greater then ten pixels wide is there a way to make it draw more than ten pixelsvoid ogl rendererdrawlineint x int y int x2 int y2 int r int g int b int a int line width glcolor4ubr g b a gllinewidthglfloatline width glbegingl lines glvertex2ix y glvertex2ix2 y2 glend gllinewidth10f,['c++'] +80094,nsstring initwithdata returns null i am pulling data from a website via nsurlconnection and stashing the received data away in an instance of nsmutabledata in the connectiondidfinishloading delegate method the data is convert into a string with a call to nsstrings appropriate methodnsstring result nsstring alloc initwithdatadata encodingnsutf8stringencodingthe resulting string turns out to be a null if i use the nsasciistringencoding however i do obtain the appropriate string albeit with unicode characters garbled up as expected the servers contenttype header does not specify the utf8 encoding but i have attempted a number of different websites with a similar scenario and there string conversion happens just fine it seems like the problem only pertains to the given web service but i have no clue whyon a side note is pulling web pages and data from an api good practice ie buffering the data converting into a string and manipulating the string afterwardsmuch appreciated,"['iphone', 'objective-c']" +80109,which html5 reset css do you use and why which html5 reset css do you use and why is there one that youve found to cover more casesi have started using html5 doctors it seems to work but i am wondering if there is something better out there,['css'] +80111,how safe is it to assume that most users will have js enabled possible duplicatesis it reasonable to assume my visitors have javascript enabledhow many people thisable javascript i know that js should only be used to enhance functionality and users with js thisabled should still be able to use your website but how often does that really happen nowadays a majority of modern web 20 pages need js for added functionality in other words how safe is it to assume that most of your users will have js enableddoes anyone have concrete data on this,['javascript'] +80117,make a list item clickable htmlcss so i am trying to make each listitem on my site clickable but i am not sure what is the best way to do it please help me outso here is the relevant htmlul libackpack a href titlebuy on amazon target blankimg srcimgbasketpng height16 width16 altbuy classbuy onclickpagetracker trackeventamazon school supplies backpackali more list items uland here is the relevant csscontent ul li thisplayblock liststylenone padding5px 10px 5px 15pxcontent li li this is for when there are subcategories borderbottom none bordertop 1px solid f8d9d0 margin 3px 10px 3px 15px padding 5px 0px 5px 30pxbuy float right margintop 2px the next ones all deal with the shopping cart icon that appears only on hoverslistblock ul li img visibility hiddenlistblock ul lihover img visibility visiblelistblock ul li ul li img visibility hidden important marginright 10pxlistblock ul li ul lihover img visibility visible important marginright 10pxhow can i make the whole listitem clickable and still have the shopping cart icon and google analytics event tracking still work is there some jquery magic i can usei have tried using thisplayblock for the amazon links but that seems to mess up the image placementthank you so much,"['html', 'css']" +80119,massive database w fulltext search sphinx lucene cassandra mongodb couchdb our company is working on a project that requires a database with 3050 million rows of product data these rows contain text that needs to be searched concurrently thousands of times per second moreover each search needs to take less than one second to executeso all in all we have a 50m row database that needs to be searched thousands of times per second keep in mind that these are fulltext searches i know mysql or any relational database alone can not handle this type of job so were looking for someone who can design the right setup for us and help us implement for a price you specifyfirst off wed like to know what our best options here are i have personally been researching things such as sphinx lucene cassandra mongodb couchdb solr etc but really do not know which should be used in conjuction with another to give us the most efficient setup possibleso if anyone could just give some advice or take up our job offer it would be greatly appreciatedyou can contact me via pm here and i will give you my emailimphone number to further thiscussthanks,['mysql'] +80141,how to avoid jquery ui draggable from also triggering click event a have a large div a map that is draggable via jquery ui draggable the div has child divs which are clickablemy problem is that if you drag the map on mouse up the click event is fired on whatever child div you started the drag fromhow do i stop the mouse up from triggering the click event if its part of a drag as opposed to someone just clicking without a drag in which case the click event is desired,['jquery'] +80191,why is there no explicit emptyness check for example is empty in python the zen of python says explicit is better than implicit yet the pythonic way to check for emptiness is using implicit booleanessif not some sequence some sequencefill sequencethis will be true if some sequence is an empty sequence but also if it is none or 0compare with a theoretical explicit emptiness checkif some sequence is empty some sequencefill sequencewith some unfavorably chosen variable name the implicit booleaness to check for emptiness gets even more confusingif saved mess upcompare withif saved is not empty mess upsee also python what is the best way to check if a list is empty i find it ironic that the most voted answer claims that implicit is pythonicso is there a higher reason why there is no explicit emptiness check like for example is empty in python,['python'] +80211,wait until images in background css are loaded let us say we have a slideshow of pictures the thumbnails of those pictures are showed in div wrapper with a slider that i created with jquery and each image is included in a li with a css background set which of course represents the image i chose to use a backgroundimage for a layout matter because they all are different in size and aspect ratiothe images comes from a db and are dynamically createdwhat i wanna do isshow a loading message over every li and wait until the backgroundimage is loaded in the cache and then show it with a fadeinthey only way i can think of not that i can since i am not very sure how and if its doable istemporally unset the background for every li while showing the loading messagemake a loop for every background to get the image urluse the get function to load it and then do whatever i want after loadingbeside the doable thing this would imply they would load in sequence so if one would not load for some reason the script will never continuei have seen some sites that use js to load images only when its visible by the browser maybe this could be the same case i am looking for since i am using a scroller and only a part of the images are showed at once and when the page loads,"['jquery', 'css']" +80218,how to get visitors location ie country using javascript geolocation i am looking for a javascript library to extend the native geolocation functionifnavigatorgeolocation navigatorgeolocationgetcurrentpositionfunctionposition var latitude positioncoordslatitude var longitude positioncoordslongitude so that i could use the visitors country name perhaps return an informative arrayso far all i have been able to find are functions that thisplay a google maps interface but none actually gave what i want except for this library which worked well in this example but for some reason did not work on my computer i am not sure why that went wrong thereanyways do you know a javascript library that can simply return an array containing information like country city etc from latitude and longitude valuesthanks,['javascript'] +80220,python gtk widget name how do i get a widgets namewhen i define a gui using glade i can name the widgets of the window but how do i recover that property when i have a widget object instancei have tried get property get name and widgetname to no availupdate i am using gtkbuilder file format ie xml formatresolution a fix i have used use the set propertyname name method on the widget just after getting it from gtkbuilder,['python'] +80226,making ruby 19 default on os x how do i make ruby 19 the default version to use instead of the 18x that is by default installed on os x thanks,['ruby'] +80260,which is faster try catch or ifelse in java wrt performance which one is fastereither this try nfoo catchnullpointerexception ex orif n null nfoo,['java'] +80290,c definition of dllimport static data member i do have a class which looks like belowh fileclass declspecdllimport myclass public stuff private static int myint cpp fileint myclassmyint 0i get the following compile errorerror c2491 myclassmyint definition of dllimport static data member not allowedwhat should i do,['c++'] +80299,combining a uilongpressgesturerecognizer with a uipangesturerecognizer i dlike to combine a uilongpressgesturerecognizer with a uipangesturerecognizer the uipangesturerecognizer should start with a long press is there a simple way to do this or do i really have to write my own gesture recognizeri want something like on the home screen you press on an icon and after some time the icons start wobbling afterwards without releasing my finger from the screen i can start dragging the icon under my finger around,['objective-c'] +80316,find the largest value smaller than x in a sorted array suppose i have a sorted array of integers int and i want to search the closest smaller value to some input numberfor example if the array contains 1 23 57 59 120 and the input is 109 the output should be 59i am just trying to see suggestions and compare to the approaches i already have,['c#'] +80325,constricting scrolling in coreplot i would like to have my user scroll inside a cpxygraph i have a cpxygraph as part of a cphostinglayer like in the tutorials i enabled allowsuserinteraction which is cool and allows scrolling but i do not want to allow my user to scroll to infinity which it seems like it allowsyou can keep dragging further and further away from where the data is on a plothow do i constrain this so that the user can only scroll within a certain boundsi also enabled maskstoborder and set the outerborderpath and innerborderpath to something arbitarily small but i saw no changes so i am not sure how those are supposed to worki could not set maskingpath and sublayermaskingpath because they seem to be read onlyno setters though i feel like these two properties might be what i am looking foranyone has run into this situation would be glad if someone could shed some light thanks,['iphone'] +80359,dealing with large amounts of data in c i have an application that sometimes will utilize a large amount of data the user has the option to load in a number of files which are used in a graphical thisplay if the user selects more data than the os can handle the application crashes pretty hard on my test system that number is about the 2 gigs of physical ramwhat is a good way to handle this situation i get the bad alloc thrown from new and tried trapping that but i still run into a crash i feel as if i am treading in nasty waters loading this much data but it is a requirement of this application to handle this sort of large data loadedit i am testing under a 32 bit windows system for now but the application will run on various flavors of windows sun and linux mostly 64 bit but some 32the error handling is not strong it simply wraps the main instantiation code with a try catch block the catch looking for any exception per another peers complaint of not being able to trap the bad alloc everytimei think you guys are right i need a memory management system that does not load all of this data into the ram it just seems like itedit2 luther said it best thanks guy for now i just need a way to prevent a crash which with proper exception handling should be possible but down the road i will be implementing that acception solution,['c++'] +80376,springbatch for a massive nightly hourly hive mysql data processing i am looking into replacing a bunch of python etl scripts that perform a nightly hourly data summary and statistics gathering on a massive amount of datawhat i would like to achieve isrobustness a failing job step should be automatically restarted in some cases i would like to execute a recovery step insteadthe framework must be able to recover from crashes i guess some persistence would be needed heremonitoring i need to be able to monitor the progress of jobs steps and preferably see history and statistics with regards to the performancetraceability i must be able to understand the state of the executionsmanual intervention nice to have being able to start stop pause a job from an api ui command linesimplicity i prefer not to get angry looks from my colleagues when i introduce the replacement having a simple and easy to understand api is a requirementthe current scripts do the followingcollect text logs from many machines and push them into hadoop dfs we may use flume for this step in the future see perform hive summary queries on the data and insert overwrite to new hive tables partitionsextract the new summaries data into files and load merge into mysql tables this is data needed later for online reportsperform additional joins on the newly added mysql data from mysql tables and update the datamy idea is to replace the scripts with springbatch i also looked into scriptella but i believe it is too simple for this casesince i saw some bad vibes on springbatch mostly old posts i am hoping to get some inputs here i also have not seen much about springbatch and hive integration which is troublesome,['mysql'] +80381,way to detect broken images in javascript i need to be able to detect if an image is broken and replace with a default image if the image link is broken i know i could do this with an image proxy but was hoping to do it on the fly with javascript,"['javascript', 'jquery']" +80389,image from uiview is there any possibility to create a image out of a uiviewthanksandreas,['objective-c'] +80404,how can i put a listview into a scrollview without it collapsing i have searched around for solutions to this problem and the only answer i can find seems to be do not put a listview into a scrollview i have yet to see any real explanation for why though the only reason i can seem to find is that google does not think you should want to do that well i do so i didso the question is how can you place a listview into a scrollview without it collapsing to its minimum height,['android'] +80408,why is it not ok to pass char to a function that takes a const char in c possible duplicatewhy cant i convert char to a const char const in c i am curious why cannot i pass a char to const char function where as it is ok to pass char to a const char function it seems not to be ok to do it with double pointers i thought it was always ok to add constness but not ok to drop constness but now it seems i have been wronggcc compiler is giving me the erornote expected aconst char a but argument is of type achar ahere is the code snippetint fconst char a int main char a faany ideas,['c'] +80415,set text of anchor tag in javascript how do i set the text of an anchor tag in javascript this does not seem to work i am using firefoxvar link documentcreateelementalinkinnerhtml remove,"['javascript', 'html']" +80419,cucumber step definition for given that i am logged in i have got a cucumber step given that i am logged ini do not understand how i should implement it as a step definitioncould someone point me into right direction tutorials blogs etc,"['ruby-on-rails', 'ruby']" +80424,how to set focus on a textview when an activity starts there are an edittext and a textview in my activity i want to set focus on the textview when the activity starts i used the following code textview mytextview textview findviewbyidridmy text vew mytextviewsetfocusabletrue mytextviewsetonclicklistenerthis mytextviewrequestfocusbut the code does not work the edittext always receives focus when the activity startscan anyone helpthanks,['android'] +80426,a 2147483648 a compiler optimization i am trying to learn how to reverse engineer software and all the tricks to understand how the code looks like before the compiler optimizationsi found something like this several times if a 0 a 2147483648 ai originally thought it was an abs a underflows so you get the positive value but since a is negative see the if this is equivalent to if a 0 a 2147483648 absawhich will be a very small negative number and not the absolute value of a at all what am i missing,['c'] +80438,android not market managed error working on trying out the market licensing service and i am running into a few problems with the sample applicationwhen i first ran the sample i got an error saying that the application was not licensed i linked my account to the simulator in order to get it to get the test response and now i get an error saying application error not market manageddoes this mean that i have to upload the app to the market in order to test to see if it works,['android'] +80460,jquery child selector without parent i was looking at some code from a tutorial for creating a carousel menu and noticed parent child selectors without the parent never seen this before and confused to what it is actually doing see following code var wrapper div thiscssoverflow hidden slider wrapperfind ul items sliderfind li single itemsfilterfirst singlewidth singleouterwidth visible mathceilwrapperinnerwidth singlewidth note does not include padding or border currentpage 1 pages mathceilitemslength visibletutorial here,['jquery'] +80467,changing project requirements should client pay not sure where to put this but a site filled with working programmers is a good beti built a website for a client that included on the home page a fancy jquery image slider with controls this was specified in the original project scope i also implemented a simple jquery slider on one of the inner pagesnow that the site is up for final review the client reviewed the site and wants a few edits here and there one being the removal of the fancy jquery i spent hours working on and modifying and replaced with the simpler slider on the inner pagesmy questionshould the client still pay for home jquery slider i worked on and charged to implement the other jquery slider on the home pagei charge per featurefunctionality when building a site therefore if i just remove the slider i will lose money and time i am thinking they should pay for it since it was specified in the original scopenot my faultsecond question how should i present them with the charge if i am charging them for it,['jquery'] +80472,organising classes and modules in python i am getting a bit of a headache trying to figure out how to organise modules and classes together coming from c i am used to classes encapsulating all the data and methods required to process that data in python there are modules however and from code i have looked at some people have a lot of loose functions stored in modules whereas others almost always bind their functions to classes as methodsfor example say i have a data structure and would like to write it to thiskone way would be to implement a save method for that object so that i could just typemyobjectsavefilenameor something like that another method i have seen in equal proportion is to have something likefrom myutils import readwritereadwritesavemyobjectfilenamethis is a small example and i am not sure how python specific this problem is at all but my general question is what is the best pythonic practice in terms of functions vs methods organisation,['python'] +80482,php get called class alternative i have got an abstract php superclass which contains code that needs to know which subclass its running underclass foo static function get class name return get called class works in php 53 but not in php 52 static function other code needs to know echo self get class name class bar extends foo class foobar extends foo barother code i need barfoobarother code i need foobarthis would work if i called the function get called class however this code is going to be run in php version 52 so that function is not availablethere is some custom php implementations of get called class out there but they all rely on going thru the debug backtrack parsing a file name line number and running a regex as the coder is not aware that php 52 has reflection to find the class name this code needs to be able to be run with php ie not only from a php file it needs to work from a php a shell or an eval statementideally a solution would work without requiring any code to be added to the subclassesa the only potential solution i can see though is adding the following code to each subclass which is obviously a thisgusting hackclass foobar extends foo static function get class name return foobar edit wait this does not even seem to work it wouldve been my last resort can anybody think of something similar to this solution that would get me the required functionality ie i am willing to accept a solution that requires me to add one function or variable to each subclass telling it what its class name is unfortunately it seems that calling self get class name from the superclass calls the parent class implementation even if the subclass has overridden it,['php'] +80489,is c an object oriented language i have always heard that c is not object oriented but rather c with classes so when i mentioned to an interviewer that c was not really object oriented he asked me why i did not consider it an oo language i have not done any c since university and i did not have much of an answer is c object oriented or not and why,['c++'] +80496,nl2br not working for me please help i cannot get nl2br function to work after fetching data from my dbresult mysql queryselect commentsetcetcwhile row mysql fetch arrayresult echo nl2brrowcommentsin db row commentsrnthanksrnoutputsame as in dbrnthanksrnif i simply test this out like so it works finephpmystring rnthanksrnecho nl2brmystringoutputconverts r and to br,['php'] +80537,getting delayed job to log here is how i have delayed job set updelayedworkerbackend active recorddelayedworkerlogger railsloggerdelayedworkerlogger activesupportbufferedloggernewlograilsenv delayed jobslog railsloggerleveldelayedworkerloggerauto flushing 1class delayedjob def logger delayedworkerlogger endendif jobscommoncheck job existsperiodicjobblank delayedjobenqueue periodicjobnew 0 30secondsfrom nowendendhere is my simple jobclass periodicjob def perform railsloggerinfo periodic job writing timenow delayedjobenqueue periodicjobnew 030secondsfrom now endendi do not see any log messages from delayed job in my rails logs or delayed job log file the only messages i see are jobs startingsuccessfailure in the delayed jobslog file this is causing big problems including detecting bugs and memory leaks in workers almost impossible please help,['ruby-on-rails'] +80543,detect development server in aspnet visual studio can you programatically detect if the development server in visual studio is used instead of iis,['asp.net'] +80550,how can i use metadot m in python with emacs is there an equivalent of slime for python for example if i position the cursor on foo and do m jump to definition i would like to see the source definition of the function foothis should work regardless of whether foo is in1 the local project directory 2 in some virtualenvsbarlibsitepackages 3 in some other pythonpath4 virtual env is in use ie it should look in my current virtualenvdoes the pymacsropemacs combination do any of this,['python'] +80551,can parent and child class in java have same instance variable consider these classesclass parent int aclass child extends parent int a errorshould the declaration of a in child not give compilation error due to multiple declarations of int a,['java'] +80560,how to convert a hash value returned from a date select in rails to a date object i have a date select in my view inside a form however on submit the value returned is in a hash form like so1i2010 2i8 3i16how can i convert that in to a date format in rails so i can use it as a condition when querying the database eg condition dates some date from date select i tried calling dateparsesome date from date select but it did not work because its expecting a string and not a hash map is there a rails way to do this thanks,['ruby-on-rails'] +80568,blocking device rotation on mobile web pages is it possible to detect on my page for example using javascript when user visit it using mobile device in portrait mode and stop orientation changing when user rotate its phone to landscape there is game on my page optimized for portrait thisplay only and i do not want it in landscape,['javascript'] +80575,can we have a return type for a constructor in java the following code gives a compilation errorclass parent parentint aclass child extends parenterrormainjava6 cannot find symbolsymbol constructor parentlocation class parentclass child extends parent1 errori was trying to do different things and found that adding a return type to the parent constructor got rid of the errorclass parent int parentint aclass child extends parenti have read that constructors should not have return type which clearly is not correct all the times so my question is when should we have return type for constructor,['java'] +80577,pointer to member question 4112 states an rvalue of type apointer to member of b of type cv ta where b is a class type can be converted to an rvalue of type apointer to member of d of type cv ta where d is a derived class clause 10 of b if b is an inaccessible clause 11 ambiguous 102 or virtual 101 base class of d a program that necessitates this conversion is illformedmy question is why we have the restriction of b not being a virtual base class of d,['c++'] +80599,stop and start iis programatically quickly and safe way my situation when i deploy assemblies net in gac i get errors cannot access to xdll because is in use for another process the iis use those dll assemblieswhich is the best way more performancequick and safe way or all ways to stop start iis 60 windows 2003 for c net 35options i thinkdetect iis installed in machineprocestart using commands iisreset stop andiisreset startuse servicecontroller class for get world wide web publishing service w3svc and do stopcontrollerstopcontrollerwaitforstatusservicecontrollerstatusstopped timespanfromsecondstimeoutsecondsand do startcontrollerstartcontrollerwaitforstatusservicecontrollerstatusrunning timespanfromsecondstimeoutsecondsprocestart using command taskkill im aspnet wpexe f use w3wpexe in win2003another options that i do not know,"['.net', 'asp.net']" +80601,using visual studio project properties effectively for multiple projects and configurations i have always used visual studios built in gui support for configuring my projects often using property sheets so that several projects will use a common setone of my main gripes with this is managing multiple projects configurations and platforms if you just do everything with the main gui right click the project properties it quickly becomes a mess difficult to maintain and prone to bugs like failing to correctly define some macro or using the wrong runtime library etc dealing with the fact that different people put there dependency libraries in different places eg mine all live in clibscclibname and then often manage the different versions of those libraries differently as well release debug x86 x64 etc is also a large problem since it vastly complicates the time to set it up on a new system and then there is issues with versioncontrol and keeping everyones paths separateproperty sheets make this a bit better but i cant have one sheet have separate settings for different configurations and platforms the drop down boxes a greyed out resulting in me having many sheets which if inherited in the correct order do what i want x86 x64 debug release common directories deals with the previously mentioned dependency issue by defining user macros like boostx86libdir etc and if inherited in the wrong order eg common before x64 and debug lead to issues like trying to link an incorrect library version or incorrectly naming the outputwhat i want is a way of dealing with all these scattered dependencies and setting up a set of rules which are used by all my projects in the solution like naming an output library as mylibvc90vc100x86x64dlib without having to do all this for each individual project configuration and platform combination and then keep them all correctly in synci am aware of moving to entirely different systems like cmake that create the needed files however this then complicates things elsewhere by making it so even simple tasks like adding a new file to the project then requires additional changes elsewhere which is not something i am entirely happy with either unless there is some with vs2010 integration which can keep track of these sorts of changes,['c++'] +80602,building using multiple machines i have a huge windows c project that takes a lot of time to be compiled do you know if there is some free tool being able to build using multiple pc connected togetherdo you know if there is some free tool doing the same in linux using gccat least there is something that i can do to split the work myselfthanks,['c++'] +80639,make python ignore pyc files is there a way to make python ignore any pyc files that are present and always interpret all the code including imported modules directly google has not turned up any answers so i suspect not but it seemed worth asking just in casewhy do i want to do this i have a large pipeline of python scripts which are run repeatedly over a cluster of a couple hundred computers the python scripts themselves live on a shared nfs filesystem somehow rarely after having been run hundreds of times over several hours they will suddenly start crashing with an error about not being able to import a module forcing the regeneration of the pyc file fixes the problem i want of course to fix the underlying causes but in the meantime we also need the system to continue running so it seems like ignoring the pyc files if possible would be a reasonable workaroundps i am using python 25 so i cannot use b,['python'] +80649,nsstring question rangeofstring method i am having an issue that i cannot figure outi am trying to run the rangeofstring method on a string and i am not sure how to determine if the string was not found for examplensrange range abc rangeofstringd optionsnscaseinsensitivesearch rangensmakerange03clearly d is not contained in the string abc i would like to be able to do thisifthe range is empty since d is not in abc do somethingwhat is the code for this thanks,['iphone'] +80658,decimal precision and scale in ef code first i am experimenting with this codefirst approach but i am find out now that a property of type systemdecimal gets mapped to a sql column of type decimal18 0 how do i set the precision of the database column,"['c#', '.net']" +80664,regex replacements inside a stringbuilder i am writing the contents of a text file to a stringbuilder and i then want to perform a number of findreplace actions on the text contained in the stringbuilder using regular expressionsi have run into a problem as the stringbuilder replace function is not capable of accepting regular expression arguments i could use regexreplace on a normal string but i am under the impression that this is inefficient due to the fact that two copies of the string will need to be created in memory as net strings are immutableonce i have updated the text i plan to write it back to the original filewhats the best and most efficient way to solve my problemedit in addition to the answers below i have found the following questions that also shed some light on my problem memoryefficiencyandperformanceofstringreplacenetframeworkisstringbuilderreplacemoreefficientthanstringreplaceatwhatpointdoesusingastringbuilderbecomeinsignificantoranoverhead,['c#'] +80665,how to test if one java class extends another at runtime how to i test if a is a subclass of bclass a aclassclass b bclass,['java'] +80672,calling a base class constructor from derived class in java i have a class as followspublic class polygon extends shape private int nosides private int lenghts public polygonint idpoint centerint nosidesint lengths superid center thisnosides nosides thislenghts lengths now a regular polygon is a polygon whose all sides are equal what should be the constructor of my regular polygonpublic regularpolygon extends polygonconstructor,['java'] +80675,format timespan greater than 24 hour say i convert some seconds into the timespan object like thisdim sec 1254234568dim t as timespan timespanfromsecondssechow do i format the timespan object into a format like the following105hr 56mn 47secis there a builtin function or do i need to write a custom function,['c#'] +80693,sqliteopenhelper onupgrade confusion android i am doing my first app with a database and i am having a little trouble understanding the onupgrade function my database has a table with an items and a favorite column so that the user can favorite an item most implementations i see simply drop the table and reconstruct it but i do not want to do this i want to be able to add more items to the table when the app is upgraded through the android marketplace does the database know its version number so could i increment the version number in the code and then export it to the marketplace and when the user boots up the upgraded version for the first time then onupgrade will be called if this is the case my onupgrade would simply pull from a file and add the database items in is this a standard way of doing things or is there a better way of handling this in android i am trying to stay as standard as possiblethanks,['android'] +80694,make an http request with android i have searched everywhere but i could not find my answer is there a way to make an simple http request i want to request an php page script on one of my website but i do not want to show the webpageif possible i even want to do it in the background in an broadcastreceiver,['android'] +80698,how to reset the style properties to their css defaults in javascript on a php generated page there are several elements like thistd classdefaulttdstyle stylecoloruserdefinedcustomcolor idmytdidtdso there is a default style and i apply several extra styles that override the style defined in the cssis there a way to remove these added styles from javascriptit seems the objstylecolordefault and objstylecolorauto not works how can i reset the color to the css default from javascript,"['javascript', 'html', 'css']" +80701,jquery move an inner element to the first position lets say you have a list of itemsul idimportantnumbers li idoneli li idtwoli li idtopnumberli li idfourliulevery five seconds these list items get reorderedusing jquery whats the best way to keep topnumber at the top of the list during the reordering,"['jquery', 'html']" +80702,static class members python so i am using static class members so i can share data between class methods and static methods of the same class there will only be 1 instantiation of the class i understand this fine but i am just wondering when the static members get initialized is it on import on the first use of the class because i am going to be calling the static members of this class from more than 1 module therefore more than 1 import statement will all the modules accessing the static methods share the same static data members and if my main client deletes the instance of my class and then recreates it without terminating altogether or reimporting stuff will my data members be preserved,['python'] +80710,making a webservice secure im wrapping up my iphone app im just worried about security at our web server level the data is being pulled over to the iphone app via web services what security measures can i put on the web services so that i am not vulnerablethanks,"['.net', 'iphone']" +80725,order of destruction using virtual can some one please help what the order of destruction is when i am using virtual functions does it start with base class and then derived class,['c++'] +80731,java xml parsing and original byte offsets i would like to parse some wellformed xml into a dom but i would like know the offset of each nodes tag in the original mediafor example if i had an xml document with the content something likehtmlbodydivtextdivbodyhtmli would like to know that the node starts at offset 13 in the original media and more importantly that text starts at offset 18is this possible with standard java xml parsers jaxb if no solution is easily available what type of changes are necessary along the parsing path to make this possible,['java'] +80735,qobjectqobject cannot access private member declared in class qobject class chiprojectdata public qobjectpublic chiprojectdata chiprojectdataqmapqstringqstring aprojectdata chiakmmetadata apakmmetadata 0 qobject parent 0private qmap qstringqstring m strprojectdata chiakmmetadata m pakmmetadatachiprojectdatachiprojectdataqmapqstringqstring aprojectdata chiakmmetadata apakmmetadata qobject aparent qobjectaparent m strprojectdata aprojectdata m pakmmetadata apakmmetadatawhy does it give the qobjectqobject cannot access private member declared in class qobject error,['c++'] +80745,write to a file from multiple threads asynchronously c here is my situation i would like to make writing to the file system as efficient as possible in my application the app is multithreaded and each thread can possibly write to the same file is there a way that i can write to the file asynchronously from each thread without having the writes in the different threads bang heads together so to speaki am using c and net 35 and i do have the reactive extensions installed as well,['c#'] +80753,fetching the comment history for a work item in tfs in most defect trackers there is a comment history associated with a ticketincidentissuework itemi wish to get this same information from tfs via the sdk for a work item ideallywho created the commentthe text of the commentwho last updatededited the comment if that is event possible in tfsi have determined that a workitem has a collection of revisions availabe via the revisions property and that you can loop through each revision but a revision does not have a history property where i assume i could find the comment created by the user also i do not believe it is compulsory to record a comment with each change so i suspect i will need to ignore revisions that do not have any history property informationrevisions property on msdnany thoughts on the best way to fetch this comment history information for a work item in tfs is the revisions list the correct way or should i be using some other part of the api,['.net'] +80754,how can i get a list of trusted root certificates in java i would like to be able to get access to all trusted root certificates programmatically in a java app i was looking at the keystore interface but i am hoping to get the list of trusted roots that is implicit with the jreis this accessible anywhere,['java'] +80764,python how to check if a unicode string contains a cased character i am doing a filter wherein i check if a unicode utf8 encoding string contains no uppercase characters in all languages it is fine with me if the string does not contain any cased character at all for example hello will not pass the filter but should pass the filter since is not a cased characteri planned to use the islower method but in the example above islower will return falseaccording to the python docs the python unicode method islower returns true if the unicode strings cased characters are all lowercase and the string contained at least one cased character otherwise it returns falsesince the method also returns false when the string does not contain any cased character ie i want to do check if the string contains any cased character at allsomething like thisstring unicode utf8check first if it contains cased charactersif not contains casedstring return truereturn stringislowerany suggestions for a contains cased functionor probably a different implementation approachthanks,['python'] +80768,http array parameters with struts 2 via an ajax call i am having an issue sending array parameters to a struts 2 action class i am using struts 2181here is some example codepublic class myaction extends actionsupport private string types public string execute return success public string gettypes return types public void settypesstring types thistypes types the problem is when sending an array via the jquery ajax methodajax type post url myactionaction data types this is a test causes an exception to occurognlparseexception encountered at line 1 column 7how can i use jquery to send the array to my struts2 action class is there something along the lines of an interceptor that i need to include or is there an option in jquery to remove thisi also encountered this problem with the jquery ui sortable control but i solved that using a regex to remove the characters i would like to avoid that because that solution bothers me i suppose i could just build the string myself instead of using the object notation but unless you can convince me otherwise i would like to use the object notation instead,['jquery'] +80787,rails high memory usage i am planning on using delayed job to run some background analytics in my initial test i saw tremendous amount of memory usage so i basically created a very simple task that runs every 2 minutes just to observe how much memory is is being usedthe task is very simple and the analytics eligbile method always return false given where the data is now so basically none of the heavy hitting code is being called i have around 200 posts in my sample data in development post has one analytics facetregardless of the internal logicbusiness here the only thing this task is doing is calling the analytics eligible method 200 times every 2 minutes in a matter of 4 hours my physical memory usage is at 110mb and virtual memory at 200mb just for doing something this simple i cannot even begin to imagine how much memory this will eat if its doing real analytics on 10 posts with real production data granted it may not run evevery 2 minutes more like every 30 still i do not think it will fly this is running ruby 197 rails 235 on ubuntu 10x 64 bit my laptop has 4gb memory dual core cpuis rails really this bad or am i doing something wrong delayedworkerloggerinforam usage job start pmap processpid tail 11040strippostnot expiredeach do p if panalytics eligible this method is never called postfind for analytics updatepidupdate analytics endenddelayedworkerloggerinforam usage job end pmap processpid tail 11040stripdelayedjobenqueue periodicanalyticsjobnew 0 2minutesfrom nowpost modeldef analytics eligible vf selfanalytics facet if selftotal ratings 0 vfnil return true elsif vfnil vflast update tv 0 ratio selftotal ratings vflast update tv if ratio 1 constantsfacet update eligibility delta return true end end return false end,['ruby-on-rails'] +80790,get the last insert id with doctrine 2 how can i get the last insert id with doctrine 2 orm i did not find this in the documentation of doctrine is this even possible,['php'] +80825,how to create quickhelp entry for custom functions in xcode i still searched for this but without successi would like to create quick help entries in xcode for custom classesdo not know quick helpselect a functionname rightclick and choose quick helpthen you can see functiondescription etcsomebody an idea how to accomplish this,['iphone'] +80832,why should not i use immutable pojos instead of javabeans i have implemented a few java applications now only desktop applications so far i prefer to use immutable objects for passing the data around in the application instead of using objects with mutators setters and getters also called javabeansbut in the java world it seems to be much more common to use javabeans and i cannot understand why i should use them instead personally the code looks better if it only deals with immutable objects instead of mutate the state all the time immutable objects are also recommended in item 15 minimize mutability effective java 2edif i have an object person implemented as a javabean it would look likepublic class person private string name private place birthplace public person public setnamestring name thisname name public setbirthplaceplace birthplace thisbirthplace birthplace public string getname return name public place getbirthplace return birthplace and the same person implemented as an immutable objectpublic class person private final string name private final place birthplace public personstring name place birthplace thisname name thisbirthplace birthplace public string getname return name public place getbirthplace return birthplace or closer to an struct in cpublic class person public final string name public final place birthplace public personstring name place birthplace thisname name thisbirthplace birthplace i could also have getters in the immutable object to hide the implementation details but since i only use it as a struct i prefer to skip the getters and keep it simplesimply i do not understand why it is better to use javabeans or if i can and should keep going with my immutable pojosmany of the java libraries seem to have better support for javabeans but maybe more support for immutable pojos gets more popular over time,['java'] +80833,mocking enterprise lib 5 database is it possible to mock the enterprise library 5 version of database if so howthere is no idatabase interface which is a mystery as i though microsoft pp would be more on the ball about testability benefits of exposing such an interfacei have a repository class which used entlib 5 data access application blocki am retro fitting unit tests into this class and need to mock out the dependency on the database object this class is now passed the database via its constructor and uses a database object to perform operations on the db i use the following to resolve an instance of the database to be passed to my repositorycontainerregistertypeifoorepository foorepository new injectionconstructor enterpriselibrarycontainercurrentgetinstancedatabasefoodbconnstr i do not wish these unit tests to become integration testsi have tried using moq to create a dynamic mock of the database type but this has proved tricky as database requires a connection string and a dbproviderfactory in its constructor maybe if there was such a thing as a mockdbproviderfactorythis is the form that the unit test is takingaside i also find the use of a static logger class very difficult to test hopefully i am missing some trick here but i must say i am thisappointed with testability thus far,"['c#', '.net']" +80836,new image how to know if image 100 loaded or not i am creating new image usingimg new imageimgsrc image urlthen i am assigning imgsrc to the img tags src in dommy imgattrsrc imgsrchow can i know that imgsrc has 100 loaded what is the best practiceimgcomplete seem to me little buggy in some browsersso in another words i need to assign imgsrc to my img only after img it was 100 loadedthank you,"['javascript', 'jquery']" +80837,how to make a uiview that can cover the navigation bar i want to show the uiview in full screen but show the status bar other things like the navigation bar need to cover by the uiview how can i do that,"['iphone', 'ios', 'objective-c']" +80856,what will happen to existing connections when switch between 3gwifi assume that i have a tcp connection that doing heavy data transmitting on my 3g network and i walked home android switch to my home wifi automatically now what happen to the existing connection is it simply thisconnect or it will keep going only new connections will use wifiin addition what if i walk away from home wifi lost signal and switch to 3g it should be safe to guess the connection is dropped for my application do i need to handle the reconnection or there is a auto fall back solutionthanks in advancehongbo,['android'] +80863,fastest json readerwriter for c i need a c json parser writer speed and reliability are very critical i do not care if the interface is nice or not if it is boostbased or not even a c parser is fine if it is considerably faster than c onesif somebody has experience with the speed of available json parsers please advise,"['c++', 'c']" +80864,dynamically change the background linearlayout how to dynamically change the background linearlayout,['android'] +80879,androids viewdidload and viewdidappear equivalent does android have an equivalent to cocoas viewdidload and viewdidappear functions if not then how would i go about performing an action when a view appears my app is a tabbed application in which one of the tabs is a list of forum topics i would like the topic list to be refreshed every time the view appears is such a thing possible in android,"['iphone', 'android']" +80883,autogenerate variable name to match parameter youre providing r 45 answers to 5 are welcomevs2008 answers to vs2010 are welcomec fwiwi am using a constructor the question applies for methods too and there is intellisensei do not yet have a value to specify for this first parameter firstname today i type firstname then let the ide create that variable for me which i initialize to some valuei understand that the ide will create the variable for me i want it to create the variable name for mei do not want to have to type firstname i like the variable name the parameter author chose and i want to use that variable name in my calling codeis there a way to have these acceptable variable names regenerated for me the calling code automatically as i move parameter by parameter through this line of calling code,['c#'] +80890,has the use of c to implement other languages constrained their designs in any way it seems that most new programming languages that have appeared in the last 20 years have been written in c this makes complete sense as c can be seen as a sort of portable assembly language but what i am curious about is whether this has constrained the design of the languages in any way what prompted my question was thinking about how the c stack is used directly in python for calling functions obviously the programming language designer can do whatever they want in whatever language they want but it seems to me that the language you choose to write your new language in puts you in a certain mindset and gives you certain shortcuts that are difficult to ignore are there other characteristics of these languages that come from being written in that language good or bad,['c'] +80906,hiding nstableview header how do i hide an nstableview header completely so that it does not take any space up,['objective-c'] +80920,how to split an array into a group of and elements each what is the best way to group an array into a list of array of and elements each in c 4egstring testarray s1 s2 s3 s4 s5 s6 s7 s8 should be split into if we take n3string a1 s1 s2 s3string a2 s4 s5 s6string a3 s7 s8may be a simple way using linq,['c#'] +80932,entry point not found exception i am trying to use a c unmanaged dll in a c project and i am getting an error when trying to call a function that says that entry point cannot be foundpublic class program static void mainstring args intptr testintptr aaeonapiopen0 consolewritelinetestintptrtostring dllimportaonapidll public static extern unsafe intptr aaeonapiopenuint reservedhere is the dumpbin for the function5 4 01020 aaeonapiopenyapaxkzi changed the dll import to dllimportaonapidll entrypointaaeonapiopen and dllimportaonapidll entrypoint aaeonapiopen and no luck,['c#'] +80943,net binary file read performance i have a very large set of binary files where several thousand raw frames of video are being sequentially read and processed and iam now looking to optimize it as it appears to be more cpubound than ioboundthe frames are currently being read in this manner and i suspect this is the biggest culpritprivate byte framebuf binaryreader binread new binaryreaderfs initialize a new buffer of sizeofframe framebuf new bytevariable buffer size read sizeofframe bytes from the file framebuf binreadreadbytesvariable buffer size would it make much of a difference in net to reorganize the io to avoid creating all these new byte arrays with each framemy understanding of netas memory allocation mechanism is weak as i am coming from a pure cc background my idea is to rewrite this to share a static buffer class that contains a very large shared buffer with an integer keeping track of the frameas actual size but i love the simplicity and readability of the current implementation and would rather keep it if the clr already handles this in some way i am not aware ofany input would be much appreciated,"['c#', '.net']" +80957,any pitfalls of converting mysql text field to mediumtext i understand the sizestorage constraints of mysql text and mediumtext fields but i just wanted to make absolutely sure before i sign off on a change that i am not looking at any adverse effects from converting a field with existing data from text to mediumtextmy concerns are mainly performance integrity and thisk storagethanks,['mysql'] +80965,making edittext and button same height in android i have an edittext and a button in my linearlayout and i want to align them closely together so they see seem to belong together edittext micbutton for speech input now they do not have the same height and they are not really aligned well button seems to be a little lower than the edittext i know i can apply a negative margin like 5dip to make them come closer together but is there perhaps a better way to do this set them in a specific containerlayout so that they will automatically have the same height and no margin between them,['android'] +80970,set source of imageview dynamically android i have an imageview on my scene that i would like to set the source of dynamically based on user inputlet us say i have 4 images in my drawable folder apng bpng cpng and dpngwhen my application loads i set the image to apngmyimageviewsetimageresourcerdrawableanow i have an edittext where a user can type in b and i want to change the image source to be the bpng or user enters c change source to cpng etchow can i dynamically set the parameter in setimageresource i tried playing around with the drawable object to no avail,['android'] +80971,coming from c how should i learn python i have got a good grasp on c my first programming language i know a reasonable number of tricks and techniques and have written quite a few programs mostly for scientific stuff now i would like to branch out and understand oop and python seems like a good direction to goi have seen several questions on how to learn python but most of them were from folks who were looking to start programming for the first time i do not need a tutorial that will tell me what a string is but i do need one that can tell me how to make a string in python any help on some good sources to look through bonus points if the source is free,"['python', 'c']" +80979,java regular expression main block nested block main block nested block nested block i want to get data within main blocks including its nested blocks with java regex is it possiblethanks in advance,['java'] +80994,session hijacking and php lets just consider the trust that the server have with the usersession fixation to avoid the fixation i use session regenerate id only in authentication loginphpsession sidejacking ssl encryption for the entire siteam i safe thanks,['php'] +80995,rotating the viewing platform in java3d the following code puts a cube at 0 0 0 and another at 0 5 5 and each cube is 5 5 5 in dimension i am trying to rotate the view that the screen gets to one like this but instead i get this view also i realize i got the colors backwardsanyway this is my code so farimport comsunj3dutilsgeometryimport comsunj3dutilsuniverseimport javaxmediaj3dimport javaxvecmathpublic class positioning private color3f lightblue private color3f aquagreen private color3f white private color3f teal private branchgroup group private simpleuniverse universe public positioning lightblue new color3f00f 0749019608f 10f aquagreen new color3f0439215686f 0858823529f 0576470588f white new color3f10f 10f 10f teal new color3f0196078431f 06f 08f universe new simpleuniverse group new branchgroup addcube05f 05f 05f new vector3f00f 00f 00f lightblue addcube05f 05f 05f new vector3f05f 00f 05f aquagreen add light directionallight light1 new directionallightwhite new vector3f00f 70f 120f light1setinfluencingboundsnew boundingspherenew point3d00 00 00 10 groupaddchildlight1 look at the right spot transform3d lookat new transform3d lookatlookatnew point3d00 00 30 new point3d00 00 00 new vector3d10 10 00 lookatinvert universegetviewingplatformgetviewplatformtransformsettransformlookat universeaddbranchgraphgroup public void addcubefloat x float y float z vector3f position color3f color transformgroup tg new transformgroup transform3d trans new transform3d appearance app new appearance material mat new material matsetdiffusecolorcolor matsetspecularcolorcolor appsetmaterialmat box b new boxx y z app move into position and add to the branch group transsettranslationposition tgsettransformtrans tgaddchildb groupaddchildtg public static void mainstring args new positioning so right now the canvas is black and i think it might be my positioning on the lookat function i am also not exactly for sure what the up vector is for any ideas on how to fix this,['java'] +81000,why am i getting a serialization error i have the following codeclass program static void mainstring args string xml arrayofusersetting usersetting valueproposalsvalue namelastgroupname usersetting usersetting valuevisiblevalue namewidgetsvisibilityname usersetting arrayofusersetting listusersetting settings getobjfromxmldocumentlistusersettingxml public static t getobjfromxmldocumenttstring xml t customtype xmlserializer serializer new xmlserializertypeoft xmldocument xmldocument new xmldocument xmldocumentloadxmlxml using xmlnodereader xmlnodereader new xmlnodereaderxmldocument customtype tserializerdeserializexmlnodereader return customtype serializablepublic class usersetting public string value get set public string name get set the code works fine and the call to getobjfromxmldocument yields a list collection however i always get a first chance exception of type systemiofilenotfoundexception in mscorlibdll when xmlserializer serializer new xmlserializertypeoft is executedso i went into debugexception and turned on managed debugging assistants i got the following on that linethe assembly with thisplay name mscorlibxmlserializers failed to load in the loadfrom binding context of the appdomain with id 1 the cause of the failure was systemiofilenotfoundexception could not load file or assembly mscorlibxmlserializers version20 cultureneutral publickeytokenb77a5c561934e089 or one of its dependencies the system cannot find the file specified file name mscorlibxmlserializers version20 cultureneutral publickeytokenb77a5c561934e089can someone explain why this is happening is there something i could do to the usersetting class to make the problem thisappear the application is quite performance sensitive and i would rather not have the exception,['c#'] +81029,can jquery create an element by a selector normally i would create an element in jquery like this div iderrors classreddivcan i create an element given a selector using something like creatediverrorsred where that would return a jquery object representing a div with the id of errors and the class of red,['jquery'] +81065,how can i make a more rounded uitextfield like the search field in safari on ipad hi i am trying to get a uitextfield to look like the google search field available in the safari app on ipad the purpose of the field will be the same a search boxi know i could use a uisearchbar but i would have to use hackish code to get rid of the magnifying glass icon and the background and i do not want thati am attaching an image with the textfield used by apple as their search box how can i modify an uitextfield to look and behave like the search field in this screenshoti tried to modified the uitextfields layer roundedcorners property but this does not work as expectedany help is very much appreciatedthank you,['iphone'] +81090,when is windowonload fired i am a bit confused as to when the windowonload event is fired for example i have a page that has lots of external js files and even an ondemand loading of the script dynamically creating a tag all of this code is in the page ie it does not get fired on click or smth it should execute while loading now let us say that i have windowonload somefunction in the last ondemand javascript is it possible that windowonload will fire before all the scripts actually get loaded,['javascript'] +81091,zoom and center a google map according to its markers javascript api v3 i think the title is enough i do not even see how to do this for the v2 and v1 api thanks,['javascript'] +81103,is there a switch to ignore undefined namespace prefixes in lxml i am parsing a noncompliant xml file sphinxs xmlpipe2 format and would like lxml parser to ignore the fact that there are unresolved namespace prefixes an example of the sphinx xml sphinxschema sphinxfield namesubject sphinxfield namecontent sphinxattr namepublished typetimestamp sphinxattr nameauthor id typeint bits16 default1sphinxschemai am aware of passing a parser keyword option to try and recover broken xml eg parser etreexmlparserrecovertruetree etreeparsesphinxtestxml parserbut the above does not ignore the prefix it removes iti could create a target which adds in the removed prefix eg parser etreexmlparsertarget addprefixwhere addprefix is a class which adds in the prefix to every attribute tagis there a simpler way to do this eventually i want to programmatically write sphinxs xmlpipe2 format cleanly,['python'] +81105,synchronizing nsmutablearray for thread security i have a threaded application in which there is a nsmutablearray which contains the nsmanagedobjects now i want my array to be accessed once at a time by any thread so how do i synchronize that array or may be put locking mechanism on it thanks in advance,['iphone'] +81109,is jbpm dying what is the future of jbpm and activiti bpmn i have heard that the developers of jbpm have transferred to activiti bpmn 2 in recent times ex tomi am wondering about is whether the support for jbpm will be over or not besides i would be glad to hear your ideas about if the improvements of activiti bpmn will make it better or useful than jbpm as time goes oni would also like to know what are the proscons between them,['java'] +81112,trimend not working i want to trim the end off a string if it ends in that is a comma and a spacei have tried trimend but this does not work it has to be only if the string ends this way so i cannot just use remove to remove the last two characters how can i do it,"['c#', 'asp.net']" +81113,how to increase the uitableview separator height i want more space10px between each cell how can i do thisand i have added this codetableviewseparatorstyle uitableviewcellseparatorstylenone,['iphone'] +81133,event when windowlocationhref changes i am writing a greasemonkey extension for a site which at some point modifies locationhrefhow can i get an event via windowaddeventlistener or so when windowlocationhref changes on a page i also need access to the dom of the document pointing to the newmodified urli have seen other solutions which involves timeouts and polling it would like to avoid that if possible,['javascript'] +81137,how to get execution time in rails console i want compare time of execution postall and select from posts or some other statements how can i get execution time of postall,"['sql', 'ruby-on-rails']" +81141,python 2 or python 3 as the students first language which is more suited as the platform for a first course in computing python 2 or python 3 reason for asking your opinion python 2 is used in the vast majority of installations worlwide but python 3 is the coming thing,['python'] +81176,whats an actual use of variable variables variable variables seem pretty cool but i cannot think of a scenario where one would actually use them in a production environment what would such a scenario be how were they used,['php'] +81180,how can i get the corresponding table header th from a table cell td given the following table how would i get the corresponding table header for each td elementtable thead tr th idnamenameth th idaddressaddressth tr thead tbody tr tdbobtd td1 high streettd tr tbodytablegiven that i currently have any of the td elements available to me already how could i find the corresponding th elementvar td ivegotthiscoveredvar th gettableheadertd,['jquery'] +81197,is it possible to thisable javacs inlining of static final variables the java static compiler javac inlines some static final variables and brings the values directly to the constant pool consider the following example class a defines some constants public static final variablespublic class a public static final int int value 10 public static final int string value fooclass b uses these constantspublic class b public static void mainstring args int i aint value systemoutprintlni string s astring value systemoutprintlns when you compile class b javac gets the values of these constants from class a and inlines these values in bclass as a result the dependency b had to class a at the compile time is erased from the bytecode this is a rather peculiar behavior because you are backing in the values of these constants at the time of compilation and you would think that this is one of the easiest things that the jit compiler can do at runtimeis there any way or any hidden compiler option that lets you thisable this inlining behavior of javac for the background were looking into doing bytecode analysis for dependency purposes and it is one of the few cases where bytecode analysis fails to detect compiletime dependencies thanksedit this is a vexing issue because normally we do not control all the source eg thirdparty libraries that define constants were interested in detecting these dependencies from the perspective of using the constants since the reference is erased from the code that uses the constants there is no easy way to detect them short of doing source code analysis,['java'] +81224,in python looking for an alternative to shelve too slow for large dictionaries i am storing a table using python and i need persistanceessentially i am storing the table as a dictionary string to numbers and the whole is stored with shelveselfdbshelveopenssmoleculelibraryshelvedirectoryossepwritebacktrue i use writeback to true as i found the system tend to be unstable if i do notso after the computations the system needs to close the database and store it back now the database the table is about 540mb and it is taking ages the time exploded after the table grew to about 500mb but i need a much bigger table in fact i need two of themi am probably using the wrong form of persistance any suggestions,['python'] +81229,binding a generic list of type struct to a repeater i have had a bit of a problem trying to bind a generic list to a repeater the type used in the generic list is actually a structi have built a basic example belowstruct fruit public string fruitname public string price string for simplicityprotected void page loadobject sender eventargs e listfruit fruitlist new listfruit create an apple and orange fruit struct and add to listfruit fruit apple new fruit applefruitname apple appleprice 399 fruitlistaddapple fruit orange new fruit orangefruitname orange orangeprice 599 fruitlistaddorange now bind the list to the repeater repfruitdatasource fruitlist repfruitdatabindi have a simple struct to model fruit we have two properties which are fruitname and price i start by creating an empty generic list of type fruitlisti then create two fruits using the struct apple and orange these fruits are then added to the listfinally i bind the generic list to the datasource property of the repeaterthe markup looks like thisasprepeater idrepfruit runatserveritemtemplate name evalfruitname br price evalprice br hr itemtemplatei expect to see the fruit name and price printed on the screen separated by a horizontal ruleat the moment i am getting an error relating to actual bindingexception details systemwebhttpexception databinding defaultfruit does not contain a property with the name fruitnamei am not even sure if this can work any ideasthanks,"['c#', 'asp.net']" +81284,how do browsers read and interpret css two part questiondo browsers have a builtin css interpreter like they do for javascriptwhen exactly does a browser read the css and when does it apply the cspecifically i would like clarification on how or why javascript and css are different in that with javascript you need to specifically wait until windowonload so the interpreter can correctly getelementbyid however in css you can select and apply styles to classes and ids all wily nilyif it even matters assume i am referring to a basic html page with an external stylesheet in the head,['css'] +81297,why do we need interfaces in java in java to implement multiple inheritance we use interfaces is it the only use of interfaces if yes what is the main use of interface in java why do we need interfaces in java,['java'] +81301,how to send http request by get method in php to another website i am developing a web application for sending sms to mobile from website like 160by2i can prepare the url required for the http get request as mentioned in the api provided by the sms gateway provider smslanecom here is the link for the apihow to send the http request from phpi used curl for that purpose but the response is not thisplayed here is the code i usedphp urlpasswordxyzmsisdn919898123456sidwebsmsmsgtest message from smslanefl0ch curl initcurl setopt ch curlopt useragent mozilla50 windows u windows nt 51 rv173 gecko20041001 firefox0101 curl setopt ch curlopt url url content curl exec ch response curl getinfo ch curl close ch echo contentfsockopen was not used because port number unknown mailed the support team for port number if any code for fsockopen through get method is invited are there any other methods for doing thisany help is welcomethanks in advance editcould any one tell me is there any other way to send this http request except curl and if possible give code for thati am asking this because the current curl code taking too much time for execution and fails after 60 seconds i increased max execution time to 120 in phpini on my local system even though it is not doing good for me,['php'] +81312,textviewgetlinecount always 0 in android i am trying to dynamically resize my textview but getlinecount method always returns me 0 even after settext and invalidate i am using the following code ifconvertview null convertview linflaterinflaterlayoutlistview null holder new viewholder holdertext2 textviewconvertviewfindviewbyidridtextview02 convertviewsettagholder else holder viewholderconvertviewgettag holdertext2settextarr2position holdertext2invalidate int linecnt holdertext2getlinecountholder is a static class as follows static class viewholder textview text2 holder contains non null text2 and the content set is also non null can anybody please helpthanx in advance,['android'] +81326,how do i get a stdexception error description when calling a c dll from c i have a c application which calls a function in a c dll this function can throw various exceptions which inherits stdexception i currently catch these exceptions like thistry call to c dllcatch systemexception exception some error handling codemy first question is will this code catch all stdexception my second question is how can i retrieve the stdexceptionwhat string if i examine exceptionmessage i only get external component has thrown an exceptionedit the function in question is in a non managed c dll and imported like this in the c classdllimportsomedlldllpublic extern static void somefunction,"['c#', 'c++']" +81329,cannot click uibutton when it is added to uiimageview guys i want to click my uibutton after it is added to uiimageview but it does not workthis is my code uibutton btndetail uibutton buttonwithtypeuibuttontypedetailthisclosureretainbtndetailframe cgrectmake00100100btndetail addtargetself actionselectorbuttonclicked forcontroleventsuicontroleventalltoucheventsselfimageview addsubviewbtndetailthe button cannot click when i add it to uiimageview but if i do not add it to uiimageview it works properlyplease somebody help me,['iphone'] +81336,how do i create a ruby date object from a string how do i create a ruby date object from the following string ddmmy,['ruby'] +81345,some necessary libraries are missing in warfile after export from eclipse why i took over a project of a college which contains some web services and by exporting the project as warfile some libraries are contained in the file eg axis2 and some arenat hibernate jdbc driver also a jar which is added to the class path has not been exported all libraries are located in folders on the hard drive which means that they are not in located somewhere in the eclipse folderif i open the warfile after export with winrar and add the libraries manually to the file the web service will work well but that is not a good solutionawhat could be the reason for that problem and how can i solve it,"['java', 'javascript']" +81364,how to tell screen resolution in dp i am working on an application based on galaxy s at the moment i know that galaxy s is 480 px wide and 800 px tall but how much is that in dplets say if i want to have two layout side by side i will have them setting to 240 px but how do i know what value i should use in dp unit,['android'] +81378,android is there any free pdf library for android i need a pdf library for manipulating a pdf documents creating pdf image convertinng to pdf and things like that but in androidi tried the android itext port but the library project generates compile errors after i added it to my project looks like it is still using some affinetransformation classes that are defined in awt,['android'] +81380,domain object in views weve been having a thiscussion at work about whether to use domain objects in our views aspnet mvc 2 or should every view that requires data be sent a viewmodeli was wondering if anyone had any proscons on this subject that they could shed some light onthank you,['asp.net'] +81387,how to initialize a static const member in c is it possible to initialize a static const value outside of the constructor can it be initialized at the same place where member declarations are foundclass a private static const int a 4,['c++'] +81394,how can i force maven to package my project against 15 i am trying to compile a maven project the source code uses generics and other featuers of java 15 thus causing my build to failin my pomxml i have configured the build configuration against 15 for the source and target properties but this does not solve my issueis my pomxml correct or am i missing somethingthanksxml version10 encodingutf8project xmlns xmlnsxsi xsischemalocation modelversion400modelversion namemyclassname groupidukcomydomaingroupid artifactidmyclassartifactid version10version build finalnamemyclassfinalname plugins plugin artifactidmavenassemblypluginartifactid configuration source15source target15target descriptors descriptorsrcmainresourcesthistxmldescriptor descriptors archive manifestfilesrcmainresourcesmetainfmanifestmfmanifestfile archive configuration plugin plugins build repositories repository idsunrepo2id urlurl releases enabledtrueenabled releases snapshots enabledfalseenabled snapshots repository repositoriesprojectoutput when attemtping to buildgenerics are not supported in 13 use source 5 or higher to enable generics,['java'] +81401,creating nondeterministic functions in sql server using rand after a bit of searching and reading the documentation it is clear that you can write user defined functions in sql server that are marked as either deterministic or nondeterministic depending on which builtinfunctions are used within the bodyrand is listed under the nondeterministic functions see msdn article so why cannot i use it in a function,['sql'] +81407,is it worth upgrading to c 40 possible duplicatewhy should i upgrade to c 40 our projects are currently all c 3 if we dont have a specific requirement for features that c 4 provides would there be any other reasons for us to upgrade thanksedit there seems to be more of an advantage with using the new clr and not just the new language features,['c#'] +81414,how to get name of wifinetwork out of android using android api i thought that i should use networkinterfacegetthisplayname i got some name but this name is different that this name which i can see when i choosing to which network i want to connectplease helpeditacording to loxley answerwifimanager wifimgr wifimanager getactivitygetsystemservicecontextwifi servicewifiinfo wifiinfo wifimgrgetconnectioninfostring name wifiinfogetssid,['android'] +81416,how to format unsigned int into 8 digit hexadecimal number i want to format an unsigned int to an 8 digit long string with leading zeroesthis is what i have so far unsigned int number 260291273 char output9 sprintfoutput x number printfsn output or write it into a file with fputsprints f83bac9 but i want 0f83bac9 how can i achieve the formatting,['c'] +81417,how to migrate from virtualenv to buildout i am attempting to move a project from virtualenv to buildout but i do not think i have grasped the whole concept of buildout all the tutorials i have found thiscuss buildout in the context of using it with zope which i am not using and therefore cannot see how to continuemy file structure with virtualenv is as followsmyapp apywhich is run using pathtovenvsmyappbinpython pathtomyappscriptpywith buildout my file structure ismyapp apy bootstrappy buildoutcfgrunning python bootstrappy and binbuildout gives me these additional filesmyapp bin buildout eggs setuptools06c12dev r80622py26egg tornado101py26egg partsat this point i am unsure how to run my appadvice,['python'] +81439,most concise way to insert array of bytes into list in some code i am creating a list of bytes and want to insert an array of bytes into the list as i am building it what is the cleanest way of doing this see code below thankspublic class listinsert public static byte getdata return new byte0x01 0x02 0x03 public static void mainstring args final listbyte list new arraylistbyte listaddbyte0xaa listaddgetdata i want to insert an array of bytes into the list here listaddbyte0x55,['java'] +81442,extra padding on linked images in every broswer hello i am having a problem with getting extra padding on link element with an image inside it happens in all browsers safari firefox iei have a reset stylesheet applied so there should not be any extra margins on padding but upon inspection it is clear that the a element has some extra bottom padding from nowhere any ideasheres the markup and css div classmoviea hrefimg srcimgvideo01jpg alt adivdivhomecol movie padding 0 0 11px 0background urlimgbgshadowmoviepng bottom norepeatdivhomecol movie a thisplay blockbackground urlimgbgzoommoviepng 50 5px norepeatdivhomecol movie img padding 4pxmargin 0border 1px solid d0d0d0,"['html', 'css']" +81455,sql server remove end string character 0 from data i have a column in the database sql server 2005 that has data with a 0 at the end when querying in sql server this character is not visible and does not seem to exist when i look in my c code the character is there this character is causing an error on our website and we need it removed from all the affected rowsis there a sql query i can write to easily remove this character from all the records that are affected i can get all the affected records but i do not have a way to update the record to a new value without the 0updatethis seems to workselect from tablewhere unicodesubstringnaughtyfield lennaughtyfield 1 0soupdate tableset naughtyfield substringnaughtyfield 1 lennaughtyfield 1where unicodesubstringnaughtyfield lennaughtyfield 1 0,['sql'] +81456,android activity not found exception i am using startactivity to call another activity and i get the activity not found exception here is my code textview textview textview itemclicked string strtext textviewgettexttostring string key symptom intent mintent new intentsymptomactivitythis symptomremedyactivityclass bundle mbundle new bundle mbundleputstringkey strtext mintentputextrasmbundle startactivitymintenthere is the logcat outputinfoactivitymanager59 thisplayed activity comandroidhomeopathyhomeopathyactivity 5542 ms total 39089 msinfoarmassembler59 generated scanline 07703545404 04 0 47 ipp 67 ins at 0x3283e00x3284ec in 6270 nsinfoactivitymanager59 starting activity intent cmpcomandroidhomeopathysymptomactivity infoactivitymanager59 thisplayed activity comandroidhomeopathysymptomactivity 2706 ms total 2706 msinfoactivitymanager59 starting activity intent cmpcomandroidhomeopathysymptomremedyactivity has extras here is the debug window output thread 1 main suspended exception activitynotfoundexception instrumentationcheckstartactivityresultint object line 1404 instrumentationexecstartactivitycontext ibinder ibinder activity intent int line 1378 symptomactivityactivitystartactivityforresultintent int line 2817 symptomactivityactivitystartactivityintent line 2923 symptomactivity1onitemclickadapterview view int long line 67 listviewadapterviewperformitemclickview int long line 284 listviewperformitemclickview int long line 3382 abslistviewperformclickrun line 1696 viewroothandlerhandlecallbackmessage line 587 viewroothandlerthispatchmessagemessage line 92 looperloop line 123 activitythreadmainstring line 4627 methodinvokenativeobject object class class class int boolean line not available native method methodinvokeobject object line 521 zygoteinitmethodandargscallerrun line 868 zygoteinitmainstring line 626 nativestartmainstring line not available native method symptomremedyactivity is another activity in my project is there something i need to do like importing symptomremedyactivity so that startactivity can see symptomremedyactivity to remove this activity not found exception,['android'] +81468,rails 3 routing passing params from routesrb in rails 235 you could do something like this inside the routesrb filemaproot controller pages action show id 3in rails 3 i have not found any way to pass a specific parameter like in rails 235 with id 3 i know i can handle it from the controller and have the same result which i did but i was wondering if there is a way to do the same thing in rails 3 from the routesrb or has it changed because it is better practice for some reason,['ruby-on-rails'] +81470,fix antivirus detection of my software i have written a program mimer 11 and after 30 downloads i found out that my own nod32 antivirus detects my program as a win32agentnfiwjlp trojan my program has a c sub program that makes a system hook to watch the keyboard and mouse movements and events in the system similar to a key logger but that is not what it is made for does anyone recommend anything for me to do so that my program does not get deleted by the users antivirus softwarethe thing that my program does is that it can mimic the users interactions with the pc at a scheduled time,"['java', 'c++']" +81471,what does define stra a do i am reading the phonemes source code it is a foss javame implementation it is written in c and i stumbled upon this makes a string of the argument which is not macroexpandeddefine stra ai know c and c but i never read something like this what does the in a doalso in the same file there is makes a string of the macro expansion of adefine xstra strai mean whats the use of defining a new macro if all it does is calling an existing macrothe source code is in featuremr2relb23cldcsrcvmshareutilitiesglobaldefinitionshpprev5525viewmarkup you can find it with a ctrlf,"['c++', 'c']" +81492,sql server legacy database to clustered index or not we have a legacy database which is a sql server db 2005 and 2008 all of the primary keys in the tables are uniqueidentifiers the tables currently have no clustered index created on them and we are running into performance issues on tables with only 750k records this is the first database i have worked on with unique identifiers as the sole primary key and i have never seen sql server be this slow with returning datai do not want to create a clustered index on the uniqueidentifier as they are not sequential and will therefore slow the apps down when it comes to inserting datawe cannot remove the uniqueidentifier as that is used for remote site record identity management purposesi had thought about adding a big integer identity column to the tables and creating the clustered index on this column and including the unique identifier columnie int identity first column to maintain insert speedsunique identifier to ensure the application keeps working as expectedthe goal is to improve the identity query and joined table query performanceq1 will this improve the query performance of the db or will it slow it down q2 is there an alternative to this that i have not listedthankspeteedit the performance issues are on retrieving data quickly through select statements especially if a few of the more transactional changing tables are joined togetheredit 2 the joins between tables are generally all between the primary key and foreign keys for tables that have foreign keys they are included in the nonclustered index to provide a more covering indexthe tables all have no other values which would provide a good clustered indexi am leaning more towards adding an additional identity column on each of the high load tables and then including the current guid pk column within the clustered index to provide the best query performance edit 3 i would estimate that 80 of the queries are performed on primary and foreign keys alone through the data access mechanism generally our data model has lazy loaded objects which perform the query when accessed these queries use the objects id and the pk column we have a large amount of user driven data exclusion inclusion queries which use the foreign key columns as a filter based on the criteria of for type x exclude the following ids the remaining 20 is where clauses on enum int or date range columns very few text based queries are performed in the systemwhere possible i have already added covering indexes to cover the heaviest queries but as yet i am still thissapointed by the performance as bluefooted says the data is being stored as a heap,['sql'] +81505,assign multiple values to array in c is there any way to do this in a condensed formglfloat coordinates8coordinates0 10fcoordinates1 00fcoordinates2 10fcoordinates3 10fcoordinates4 00fcoordinates5 10fcoordinates6 00fcoordinates7 00freturn coordinatessomething like coordinates 10f,['c'] +81507,what advantages does scala have over java for concurrent programming how can scala make writing multithreaded programs easier than in java what can scala do that java cannot to facilitate taking advantage of multiple processors,['java'] +81509,good wysiwyg web editor php css html javascript for ubuntu i am looking for suggestions as to what good easy to use web editors it needs to edit phpjavascripthtmlcss i am looking for something thatll speed up my development currently i am using nano,"['php', 'html']" +81512,opposite of viewbringtofront in android i was wondering if there is some opposite method of viewbringtofrontwhen i call bringtofront my whole screen get locked cause i have some problem with overriding the onmeasure methodwhen i implement onmeasure my custom view does not draw itself even it enters ondraw method and my custom view takes up the whole screeni badly need bringtofront but i need to start some animation that lasts for 3 seconds and by calling bringtofront user input does not work anymorecan i reset that bringtofrontthx in advance for help,['android'] +81537,do you debug c code in vim how the question is to all you people who use vim to develop c appsthere was a period in my life which can be described asi hate vimvim is nicehowever having grown up mostly on ms dev ide i have got used to those f5f11 shortcuts when debugging code watch window call stack and the main code all visible vithout need to type any gdb commandsso here is the questiondo you use vim as well for debugging or you switch to some ide for this purpose which one for those who use vim to debug code are there plugins to set breakpoints in editor highlight the line were currently debugging autonavigation during step step into step out please do not tell me you use gdb as command line see only one line which is debugged etcand thanks for all your answersandrey,['c++'] +81538,how to change a module variable from another module suppose i have a package named bar and it contains barpya nonedef foobar print aand init pyfrom bar import a foobarthen i execute this scriptimport barprint barabara 1print barabarfoobarheres what i expectnone11heres what i getnone1nonecan anyone explain my misconception,['python'] +81540,do i have to manually stop threads in java when my application is ready to exit either by closing a window or invoking the systemexit method do i have to manually stop the threads i may have created or will java take care of that for methanks,['java'] +81542,mysql selecting rows where a column is null i am having a problem where when i try to select the rows that have a null for a certain column it returns an empty set however when i look at the table in phpmyadmin it says null for most of the rowsmy query looks something like thisselect pid from planets where userid nullempty set every timea lot of places said to make sure it is not stored as null or null instead of an actual value and one said to try looking for just a space userid but none of these have worked there was a suggestion to not use myisam and use innodb because myisam has trouble storing null i switched the table to innodb but now i feel like the problem may be that it still is not actually null because of the way it might convert it i would like to do this without having to recreate the table as innodb or anything else but if i have to i can certainly try that,['mysql'] +81548,same origin policy ajax using public apis i know if on my own webpage if my user is on and i make an ajax request from that page to it will fail because of the same origin policy subdomain is different what i am trying to understand is how is it that ajax requests can pull data from apis like flickr when the request and server are obviously differentedit eg why does this code workgetjsonmethodflickrreferred this community wikiis it using cross origin resource sharingthanks,['javascript'] +81552,twitters new official tweet button whos tested it i am working on a website where a tweet this type button is essential as is a facebook likeabout a week ago twitter launched their own official tweet button i am curious to hear anyones experiences with using it particularly in comparison to tweetmeme and john resigs retweet scripti am interested in any performance issues any general tips or things not to do when implementing a tweet button,"['javascript', 'jquery', 'html']" +81564,calculating binomial coefficient nck for large and k i just saw this question and have no idea how to solve it can you please provide me with algorithms c codes or ideas this is a very simple problem given the value of and and k you need to tell us the value of the binomial coefficient cnk you may rest assured that k and and the maximum value of and is 10 since the value may be very large you need to compute the result modulo 1009 inputthe first line of the input contains the number of test cases t at most 10 each of the next t lines consists of two space separated integers and and k where 0 k and and 1 and 10 outputfor each test case print on a new line the value of the binomial coefficient cnk modulo 1009 exampleinput 3 3 1 5 2 10 3output 3 10 120,['c++'] +81582,production settings file for log4j here is my current log4j settings file are these settings ideal for production use or is there something i should removetweak or change i ask because i was getting all my threads being hung due to log4j blocking i checked my open file descriptors i was only using 113 set root logger level to warn and its two appenders to stdout and rlog4jrootloggerwarn stdout r stdout is set to be a consoleappenderlog4jappenderstdoutorgapachelog4jconsoleappender stdout uses patternlayoutlog4jappenderstdoutlayoutorgapachelog4jpatternlayout pattern to output the callers file name and line numberlog4jappenderstdoutlayoutconversionpattern5p t fl mn r is set to be a rollingfileappenderlog4jappenderrorgapachelog4jrollingfileappenderlog4jappenderrfilelogsmyapplog max file size is set to 100kblog4jappenderrmaxfilesize102400kb keep one backup filelog4jappenderrmaxbackupindex5 r uses patternlayoutlog4jappenderrlayoutorgapachelog4jpatternlayoutlog4jappenderrlayoutconversionpatternp t d c mnset httpclient debug levelslog4jloggerorgapachecomponenterrorstdout log4jloggerhttpclientwireerrorstdout log4jloggerorgapachecommonshttpclienterrorstdout log4jloggerorgapachehttpclientprotocolerrorstdoutupdateadding thread dump sample from all my threads 100pool1thread5 thread t25 javalangthreadstate blocked on orgapachelog4jspirootlogger1d45a585 owned by pool1thread35 at orgapachelog4jcategorycallappenderscategoryjava201 at orgapachelog4jcategoryforcedlogcategoryjava388 at orgapachelog4jcategoryerrorcategoryjava302,['java'] +81586,how to capture complete words using substr in php limit by word when i use substrstring0100 it gives first 100 characters sometimes it left the last word incomplete that looks odd can i do limit by word rather than char,['php'] +81588,standard for typedefing gcc 4 c89i am just wondering is there any standard that should be followed when creating typesfor exampletypedef struct date date ti have also seen people put a capital like thistypedef struct date dateor for variablestypedef unsigned int ageor thistypedef unsigned int age tis there any standard that should be followed personally i prefer post fixing with a tmany thanks for any suggestions,['c'] +81590,trigger resize event on print i have a div in which i create a chart using protovis the div has width 100 and height 100 and the code to create the chart uses chartwidth and chartheight to get the size of the div at render time and fill the page with the chart i capture the resize event on the window and adjust the div and the chart so that it resizes when the window resizes now i need to print i would have hoped that when the browser is rendering the page for the printer it issues a resize but it does not at least safari and firefox do not chrome does something strange in which it resizes only the height but not the width is there a way to trigger this behavior just before printedit consider the following htmlhtml head titleresizetitle script typetextjavascript srcscript script typetextjavascript documentreadyfunction chartresizefunction thishtmlchart size is chartwidth x chartheight windowresizefunction resizableresize script style typetextcss chart width 100 height 100 background gray border 1px solid black style head body div idchart classresizable div bodyhtml when i resize the window the content of the div changes when i print it the render process does not fire the resize event,"['javascript', 'jquery', 'html']" +81611,what does aspnet regiisexe do what does aspnet regiisexe do exactly other than updating the document mappings to correct aspnet isapidll version is updating the aspnet version from inetmgr same as running aspnet regiis i could not find any blog post or article describing the steps this particular batch command does please give any links you know of detailing the steps of aspnet regiisexe,['asp.net'] +81615,rendering a different javascript file in respond to i am stuck in an apparently simple problemin my event controller i have the i like it action def i like it event eventfindparamsid logic respond to do format formatjs end endin my case i like it is called with method put it is an ajaxcall i like itjserb will be returned as a script and it wil beexecuted on the browseri would like render a javascript file with a different name noti like itjserb but i have not found any option in the rails apidocsrespond to do format formatjs render endrails can render vanilla javascript with js option but i do not wantuse javascript in the controllerdo you have any suggestion thank youalessandro ds,"['javascript', 'jquery', 'ruby-on-rails', 'ruby']" +81618,using cython with django does it make sense is it possible to optimize speed of a mission critical application developed in django with cythonsorry in advance if it does not make senseas i am new to django recently i have read on the internet that you can use cython and turn a python code to c like speedso i was wondering is this possible with django,['python'] +81632,uitextview inputview i am making a custom input method for the ipad i want to be able to replace the system keyboard with my input method and enter text via that input methodaccording to the documentation all i need to do is to set the inputview property with my view and it will be used instead of the system keyboard i did that and it works as far as showing the keyboard but how do i actually enter text into the text viewsupposedly the text view needs to adopt the uikeyinput and i can use the protocols methods to enter the text but in reality uitextview does not adopt this protocol conformstoprotocolprotocoluikeyinput returns no and deletebackwards is not implemented inserttext and hastext are implemented in addition to that inserttext does not cause the textviewdidchange delegate method to be invoked obviously i need to send the uikeyinput method to some other object a field editor but how do i get itany ideas,['iphone'] +81637,java buffered image detecting black pixels i have this simple code to go through a 24bit color windows bmp filebufferedimage mapa bmpdecoderreadnew filemapsmapbmpfinal int xmin mapagetminxfinal int ymin mapagetminyfinal int ymax ymin mapagetheightfinal int xmax xmin mapagetwidthfor int i xminixmaxi for int j yminjymaxj int pixel mapagetrgbi j if pixel 0 systemoutprintlnblack at ij however when testing on a completely black image i get this value at pixel 167216i was hoping to get a 0x0how can i test for black pixels or any other color for that reason updateim testing against pixel 0xff 0 is this rightthanks in advance,['java'] +81650,phpinternal server error using wamp at startup i had a problem wth phpit thisplay error like below it work well in other computer but when i tried to run it in another computer it thisplay error like below i think i had a problem with my wampserver 20 configurationinternal server errorthe server encountered an internal error or misconfiguration and was unable to complete your requestplease contact the server administrator webmasterlocalhost and inform them of the time the error occurred and anything you might have done that may have caused the errormore information about this error may be available in the server error log,['php'] +81652,how can i apply css on all buttons which are present in that page i have created a css style classbtn color050 font bold 84 trebuchet mshelveticasansserif backgroundcolorfed border1px solid bordercolor 696 363 363 696 how can i apply this css style class to all buttons which are present in the page without adding classbtn to every button,['css'] +81661,java protected access across packages i would like to understand whats happening in the example below where a protected member is being accessed from outside the package through a subclassi know for classes outside the package the subclass can see the protected member only through inheritancethere are two packages package1 and package2package1 protectedclassjavapackage orgtestpackage1public class protectedclass protected void foo systemoutprintlnfoo package2 extendsprotectedclassjavapackage orgtestpackage2import orgtestpackage1protectedclasspublic class extendsprotectedclass extends protectedclass public void boo foo this works since protected method is visible through inheritance public static void mainstring args extendsprotectedclass epc new extendsprotectedclass epcfoo why is this working since it is accessed through a reference foo should not be visible right package2 usesextendedclassjavapackage orgtestpackage2public class usesextendedclass public static void mainstring args extendsprotectedclass epc new extendsprotectedclass epcfoo compilationerror the method foo from the type protectedclass is not visible it is understood that the boo method in extendsprotectedclass can access foo since protected members can be accessed through inheritance onlymy question is why is the foo method working fine when accessed through a reference in the main method of extendsprotectedclass but will not work when accessed through the epc reference in usesextendedclass,['java'] +81668,how to escape a string to be passed into decimalformat may i know how i can escape a string to be passed into decimal format currencysymbolprefix can be any stringnumberformat numberformat new decimalformatcurrencysymbolprefix 0how can i escape currencysymbolprefix so that it may contains any characters including and will not be interpreted as one of the patternplease do not suggestnumberformat numberformat new decimalformat0final string output currencysymbolprefix numberformatformatnumberas my vendors method only accept single numberformat,['java'] +81673,getting syswow64 directory using 32bit application i am trying to find a file inside the system directorythe problem is that when usingenvironmentsystemdirectoryon a x64 machine i am still getting the system32 directory instead of the systemwow64 directoryi need to get the system32 directory on x86 machines and systemwow64 directory on x64any ideaseditto find the syswow64 i am using the getsystemwow64directory more information here pinvokenotice that on nonx64 machines result is 0hope this helps someone,['.net'] +81678,php array comparison how to compare 2 arrays with each otherfor example i have arraya b c and arraya c b it would return true when they are compared but if one of the letters if not found in one of them it would return false order is not important,['php'] +81679,c multiple inheritance with polymorphism pardon the noob question in advancei have 4 classesclass person class student public person class employee public person class studentemployee public student public employee essentially person is the base class which are directly subclassed by both student and employee studentemployee employs multiple inheritance to subclass both student and employeeperson pat personpatstudent sam studentsamemployee em employemilystudentemployee sen studentemployeesiennaperson ppl3 pat sam emcompile time error ambiguous base classperson ppl4 pat sam em sen when i use an array of person the base class i can put person and all of its subclasses inside this array except for studentemployee given the reason ambiguous base classgiven that studentemployee is guaranteed to have all the methods and attributes of person is studentemployee considered a subclass of person if so why does the compiler not allow me to assign an object to a variable of the type of its superclassif not why not and what would be the proper way to accomplish thischeersedit preemptively this question is not the same as either of the following,['c++'] +81695,strange casting behaviour cannot cast object int to long i have the following codeint intnumber1 100object intnumber2 100bool arenumberofthesametype intnumber1gettype intnumber2gettype truebool areequal intnumber1equalsintnumber2 truelong longnumber1 long intnumber1 oklong longnumber2 long intnumber2 invalidcastexception whywhy does not the second cast work i realize that it might be because the object doesnat have an explicit cast to a long but if we look at its type on runtime it is systemint32if i use var or dynamic instead of object it worksany thoughts,"['c#', '.net']" +81698,is there a php function for swapping the values of two variables say for instance i have var1 abcvar2 123and under certain conditions i want to swap the two around like sovar1 123var2 abcis there a php function for doing this rather than having to create a 3rd variable to hold one of the values then redefining each like sovar3 var1var1 var2var2 var3for such a simple task its probably quicker using a 3rd variable anyway and i could always create my own function if i really wanted to just wondered if something like that exists,['php'] +81709,extending c string member functions i had a need to do a case insensitive find and found the following code which did the trickbool ci equalchar ch1 char ch2 return toupperunsigned charch1 toupperunsigned charch2size t ci findconst string str1 const string str2 stringconst iterator pos stdsearchstr1 begin str1 end str2 begin str2 end ci equal if pos str1 end return stringnpos else return pos str1 begin that got me to wondering what it would take to make this a member function of string so it could be called like thisstring sabcdefghijklmnopqrstuvstring fghisci findfi realize that there are many problems with case conversions in nonenglish languages but that is not the question i am interested inbeing a neophyte i quickly got lost among containers and templatesis there anyway to do this could someone point to me an example of something similar,['c++'] +81710,cannot assign a value to 64bit integer on 32bit platform after switching from 64bit to 32bit platform both of them are centos i get integer constant is too large for alonga type error for the following line of codeuint64 t key 0x10casting the value does not help what am i doing wrongthanks,['c'] +81711,how to make fill height this questions answer needs an update since browsers have changedoriginal questioni have looked through several posts on stackoverflow but have not been able to find an answer to this rather simple questioni have an html construct like thistable tr td classthatsetsabackground div classthatsetsabackgroundwithanicon dl dtyada dt ddyada dd dl div td td classthatsetsabackground div classthatsetsabackgroundwithanicon dl dtyada dt ddyada dd dl div td trtablewhat i need is for the div to fill the height of the td so i can be able to position the divs background the icon at the bottomright corner of the tdhow do you suggest i go about that,"['html', 'css']" +81721,ios sdk how to get the status bar back when using uiimagepickercontroller as soon as i add a uiimagepickercontroller sub view to my view the status bar thisappears and i cannot get it back is there any way to keep the status bar visibleuiimagepickercontroller imagepicker uiimagepickercontroller alloc initimagepickersourcetype uiimagepickercontrollersourcetypecameraselfview addsubviewimagepickerviewimagepicker viewwillappearyesimagepicker viewdidappearyesuiapplication sharedapplication setstatusbarhiddenno animatedno,['iphone'] +81729,get description for http status code in aspnet you can set the responsestatuscode to for example 404 should the status line description always be set to in this case 404 page not foundhow do you get the description if you only have the code 404 is this somewhere in the framework or do you manually have to hardcode the descriptions,"['.net', 'asp.net']" +81744,whats the right way to compare an ntext column with a constant value if i use something likentext2 10325i get this errorthe data types ntext and varchar are incompatible in the not equal to operatorthe best possible solution would be if comparison is implemented in the same way for any column type operator is applicable for both nvarchar and int,['sql'] +81763,conditional ctypedef with cython i need access to the uint64 t typedef from stdinth in some wrapper code that i am writing and i cannot figure out how to get it done the problem is that from what i can tell from the docs my ctypedef will have to take the formctypedef unsigned long uint64 torctypedef unsigned long long uint64 tdepending on if wordsize from bitswordsizeh is 64 or 32 i have not been able to find out out how to get access to this preprocessor definition from cython and if i could cython does not seem to like ctypedef statements in if statements and when i try to put an if statement in a cdef block it seems to confuse it with a declaration any ideas hopefully i am just missing something really basic here,"['python', 'c']" +81770,how do i remove checkbox border is it possible to remove the borders around a checkbox so that it appears invisible i have it placed in a div with a color background,"['html', 'css']" +81786,simulate mouse clicks on python i am currently in the process of making my nintendo wiimote kinda sad actually to work with my computer as a mouse i have managed to make the nunchuks stick control actually move the mouse up and down left and right on the screen this was so exciting now i am stucki want to leftright click on things via python when i press a when i went to do a search all it came up with was tkinterso my question is what do i call to make python leftright click on the desktop and if it is possible maybe provide a snippetthank you for your helpnote i guess i forgot to mention that this is for linux,['python'] +81787,prevent a c application from running more than one instance i wrote a program in cnow i would like to know what is the proper way to prevent the program from starting if it is already runningso if it is already running and doubleclick on the program it will not start because it is already runningi can do that but i was thinking of a standard and proper way,['c#'] +81793,how to initialize a shared ptr that is a member of a class i am not sure about a good way to initialize a shared ptr that is a member of a class can you tell me whether the way that i choose in cfoo is fine or is there a better solutionclass a public aclass b public ba paclass c boostshared ptra ma boostshared ptrb mb void foovoid cfoo a pa new a ma boostshared ptrapa b pb new bpa mb boostshared ptrbpb,['c++'] +81796,how do i split a string and rejoin it without creating an intermediate list in python say i have something like the followingdest njoin line for line in srcsplitn if line1 ie strip any lines starting with from the multiline string srcsrc is very large so i am assuming split will create a large intermediate list i can change the list comprehension to a generator expression but is there some kind of xsplit i can use to only work on one line at a time is my assumption correct whats the most memory efficient way to handle thisclarification this arose due to my code running out of memory i know there are ways to entirely rewrite my code to work around that but the question is about python is there a version of split or an equivalent idiom that behaves like a generator and hence does not make an additional working copy of src,['python'] +81800,how much overhead do decorators add to python function calls i have been playing around with a timing decorator for my pylons app to provide on the fly timing info for specific functions i have done this by creating a decorator simply attaching it to any function in the controller i want timedit is been pointed out however that decorators could add a fair amount of overhead to the call and that they run 23x slower than an undecorated functionfirstly i would expect that executing a decorated function would take a smite longer than an undecorated one but i would expect that overhead to be in the thousandths of seconds be negligible compared to a sql insert call the decorator itself does simple simple timing calculations using timetime some very simple aggregationdo decorators add significant overhead to a system i cannot find anything to back that up,['python'] +81825,include include once require or require once i have php file where i have defined the server access variables as well as the mysql connect and mysql select db as this functions are regularly used in almost every page in backend while i am using include which is perfectly working for me now which method or function would you suggest and i would like to know if there is any flaw if i use include or is it safe to use itedit keeping in mind i will be using session variable too,['php'] +81830,what is the expected behavior below is a purely academically invented class hierarchystruct x void f1 void f2 void f3struct y private x void f4struct z xstruct d y z using xf2 using zxf3int maini expected using declaration for xf2 to be ambiguous as x is an ambiguous base of d visbility vs accessibility of x however g ideonecom compiles it finei checked with online comeau and it gives error in using declaration for xf2 as expected however it gives ambiguity for using declaration for zxf3 as wellso what is the expected behavioredit 1 a reference to the appropriate section of the standard would be helpful pleaseedit 2i checked with vs 2010 and it has objections only with the using declaration xf2 however it is not about ambiguity of x as in the case of gcc and comeau it is about error c2876 x not all overloads are accessibleedit 3struct x void fstruct y x struct trouble void f struct trouble xstruct letscheck y trouble using troublefint mainhere i have attempted purposefully to create an issue with types in using declaration gcc still compiles this fine and so does vs2010 comeau still gives error as expected about ambiguous types trouble going by explanations given for the initial queries it appears gcc and vs2010 are wrong is that correct,['c++'] +81835,why is it not possible to catch missingmethodexception i have a dependency on net 20 sp2 in my clickonce deployed applicationthe applicationdeploymentcurrentdeploymentcheckfordetailedupdatefalse method is sp2 onlyi would like to check whether sp2 is present during app startup i have tried to detect this by catching missingmethodexception after calling a sp2only method summary the sp2 bootstrapper does not allow homesite installation so we only advice the user to download net 20 sp2 manually summary private void checkdotnet2sp waithandle wh new autoreseteventtrue try whwaitone1 this method is net 20 sp2 only note this catch does not catch the missingmethodexception catch exception change to catchmissingmethodexception does not help report that net 20 sp2 is missing finally whclose the code in catch never executes when this runs on net 20 without sp2 the exception is only caught by the appdomaincurrentdomainunhandledexception event handlerhow is it possible that the missingmethodexception is not caught i can imagine that this is a special case the clr hits a method that does not exist and somehow it is not possible to pass this to the catch block i would like to understand the principle behind thisanyone has any resources on this issue are there any other exceptions that cannot be caught in a catch block,"['c#', '.net']" +81845,iphone uitableviewcell layer shadow i am trying to add a shadow to a uitableviewcell using the layershadowcolor offset radius but it does not seem to affect it in any way the table is grouped style any ideas whyhere is the code i am usingcelayershadowcolor uicolor blackcolorcgcolorcelayershadowradius 50celayershadowoffset cgsizemake10 10,['iphone'] +81846,jquery get text as number this code does not workvar number thisfindnumbertextvar current 600if current number do somethinghtmldiv classnumber400divseems there is some problem with converting text from textlike value to numberwhat is the solution,['jquery'] +81852,semaphorewaitonerelease vs monitorpulsewait for me now it looks like functionally semaphorewaitonerelease is equal to monitorwaitpulse skipping interprocess capabilities speed yes monitor is managed other nonfunctional differences what is real difference then,['.net'] +81872,ef generic repository get id from new inserted generic entity all my entities has property id all my tables in database has autogenerated integer identity id as primary keyi have generic method to create entitiesis there any way to get entity id after entity inserted in to database public override int creatett entity string entityset getentitysetnamet contextaddobjectentityset entity contextsavechanges return id here todo return id here in simplenot generic repository i may just return entityid but how to get the same behavior in generic repository i may have base entity class for all entities which contains int property id but is there any way to get it work without implementing this inheritance,"['c#', 'asp.net']" +81876,how to open and save using java i want to make an open and save dialog in java an example of what i want is in the images belowopensavehow would i go about doing this,['java'] +81879,how to do integer model validation in aspnet mvc 2 i have a registration form and the user must enter the square footage of their house i would like this value to be only an integer is there a way to validate this value using attributes aspnet mvc,['c#'] +81900,google maps api v3 multiple markers on exact same spot bit stuck on this one i am retrieving a list of geo coords via json and popping them onto a google map all is working well except in the instance when i have two or more markers on the exact same spot the api only thisplays 1 marker the top one this is fair enough i suppose but would like to find a way to thisplay them all somehowi have searched google and found a few solutions but they mostly seem to be for v2 of the api or just not that great ideally i would like a solution where you click some sort of group marker and that then shows the markers clustered around the spot they are all inanybody had this problem or similar and would care to share a solution,['javascript'] +81901,how to prevent browser timeout in longrunning processes how would you prevent a browser from timing out while a long process is running in phpwe have a process which accepts a file upload and runs process on the file data sometimes this file can be very large with a lot of records and in these cases the user gets a timeout error i believe it is a browser timeout because the script is still running in the background and finishes successfullyi normally do not work in php in fact never before troubleshooting this website and was wondering if there was an easy way to prevent the browser from timing out while the process runs,['php'] +81903,concatenate one nsmutablearray to the end of another nsmutablearray a simple answer to this super simple question would be great here is the pseudcodensmutablearray africa lion tiger zebransmutablearray canada polar bear beaver loonnsmutable array animals africa canadawhat i want to end up withanimals lion tiger zebra polar bear beaver loonwhat is the proper syntax to achieve this in objectivec cocoathanks so much,['objective-c'] +81917,google test fixtures i am trying to understand how the google test fixtures worksay i have the following codeclass phrasetest public testingtest protected virtual void setup phraseclass myphrase1 new createphrase1234567890 phraseclass myphrase2 new createphrase1234567890 virtual void teardown delete myphrase1 delete myphrase2 test fphrasetest operatortest assert truemyphrase1 myphrase2when i compile why does it say myphrase1 and myphrase2 are undeclared in the test f,['c++'] +81924,why are assignment operators invalid in a foreach loop why are assignment operators invalid in a foreach loop i am using c but i would assume that the argument is the same for other languages that support foreach eg php for example if i do something like thisstring sarray new string5foreach string item in sarray item some assignmentrni get an error cannot assign to item because it is a foreach iteration variable,['c#'] +81926,how to programmatically access web page in java hi allthere is a web page from which i want to retrieve a certain string in order to do so i need to login click some buttons fill a text box click another button and then the string appearshow can i write a java program to do that automatically are there any useful libraries for that purposethanks,['java'] +81927,error deleting file permission denied with remove in c when i compile and run my c program that deletes a file called exampletxt belowinclude stdiohint main if remove exampletxt 0 perror error deleting file else puts file successfully deleted return 0it comes out like thiscd cusersmarkdesktop cusersmarkdesktopappexe error deleting file permission denied i lifted all restrictions on the file and there is full access to anyone that should include my programany solutionsedit when i type in del exampletxt on command prompt it worksweird,['c++'] +81943,check if thirdparty cookies are enabled i have an application that needs to check whether the client browser has thirdpartycookies enabled does anyone know how to do this in javascript,['javascript'] +81969,how do i make jsonnet the default json serializer if i have a web service asmx and i want it to use jsonnet to serialize all the objects that i return from that web service is there a way to do thatin other words i have a class like this jsonobjectmemberserializationoptout public partial class person public string firstname get set public string lastname get set jsonignore public string password get set and in my web service i have this webmethod public person getblahperson person p new person pfirstname bob plastname smith ppassword do not tell return p if using jquery i set the return type to json it serializes my object to json is it possible to make it use jsonnet through a setting in webconfig or something similar,['c#'] +81973,in aspnet mvc is it advisable for viewmodels to derive from domain models i am using aspnet mvc but this seems like a more generic mvc questionsay you have a domain model representing a person and you have a view for editing a person included in the person domain object is a state of residence property and in the view you want a dropdown that lists states is there any reason not to create a view model that derives from the domain model and simply includes properties for the ui spiciness the view requires if so why would not not want to do thistia,['c#'] +81976,entity framework code only error the model backing the context has changed since the database was created i created a code only poco for use against an existing database using entity framework 4 and the ctp4 when i run a query i get the error the model backing the xyzcontext context has changed since the database was created either manually deleteupdate the database or call databasesetinitializer with an idatabaseinitializer instance for example the recreatedatabaseifmodelchanges strategy will automatically delete and recreate the database and optionally seed it with new datai am unclear on why this is happening or what i can change i merely created the poco defined a simple dbcontext made a few tweaks and then tried to run a simple query since i am using code only i am unaware of any configuration settings that need to be made and i certainly do not want to recreate or delete the database since it is an existing databasethanks for any ideas,"['c#', '.net']" +81981,plsql jdbc how to get last row id whats plsql oracle equivalent of this sql server snippetbegin traninsert into mytablecontent values test assume there is an id column that is autoincrementselect identitycommit tranin c you can call mycommandexecutescalar to retrieve the id of the new row how can i insert a new row in oracle and have jdbc get a copy of the new ideditbalusc provided a very good starting point for some reason jdbc does not like named parameter binding this gives incorrectly set or registered parameters sqlexception why is this happening oracleconnection conn getappconnection string q begin insert into tb id values claim seqnextval returning id into newid end callablestatement cs oraclecallablestatement connpreparecallq csregisteroutparameternewid oracletypesnumber csexecute int newid csgetintnewid,['java'] +81984,doing a join over 2 tables in different databases using hibernate i have two tables in two separate oracle databases not schemas that i need to join in hibernate currently i have two hibernate sessions going out to the separate databases before anybody says look at hibernate shards i have spent a better part of a day looking at that subproject and have found that it is for horizontal partitioned data all the tables must be in all of the databases afaik there is no way for one to tell shards to look only in one database hibernate shards docs and is no longer being worked onthings that i have thought about to try to solve this problem doing a findall or some restricted variant of that on both of the tables and manually doing the join using some loops ok for very small tables prohibitive from small tables on uphave the sessions do some kind of interaction i have no idea if this is even feasible will have to look at the hibernate session api removing the database name from the url string of different hibernatexcfgxml and insert them into the separate hbmxml files like thisclass namefoo tablefoo table schemafoo schema catalogfoo dbdoes not seem to work from my initial tests and that seems like truck sized security hole use the repository pattern unsure if my javafu is strong enoughis there something that i am overlooking in one of the cases above or can it be another way that i have not listed above,['java'] +81996,bind address and mysql server i came across the bind address while trying to configure the mysql server the details of why i want to configure the bind address is in the link belowmultiple hostnames and multiple privilegesnow i wan to understand the purpose of the bind address in the sense is a binding address the address we assign to the machine that is hosting the mysql serveri have no clue would be really helpful if someone could explain me the purpose of it and will assigning 0 to the binding address create any security flawsloop holes,['mysql'] +82013,hibernate different object with the same identifier value was already associated with the session possible duplicatehibernate error orghibernatenonuniqueobjectexception a different object with the same identifier value was already associated with the session when i use the daoupdateuserbean sessionsaveorupdateethrow the exceptiondifferent object with the same identifier value was already associated with the sessionthe function is like next public e savee e session session null try session sessionfactoryopensession logdebugsessionsessionhashcode save e sessionsaveorupdatee here throws exception sessionflush catch exception e1 logerrcannot open hibernate session e1getmessage cause e1getcause e1printstacktrace finally if session null sessionclose session null return e the userbean is an instance of class userbeanpublic class userbean private listgroupbean groups new arraylistgroupbean private listrolebean roles new arraylistrolebean public class groupbeanprivate listrolebean roles new arraylistrolebean every groupbean has a list of roles which are not changedin database group and role is manytomany mapping for example we have a groupbean1 it is roles rolebean1 rolebean2groupbean2 which roles are rolebean1now i create a new userbean1 it is groups is groupbean1and if i want to add the rolebean1 to userbean1 it will throws the exception like the title descripti look the serverlog and find that when i user daosave the saveorupdate order isuserbean1userbeangroups groupbean1 groupbeanroles rolebean1 save relebean1 the first time done rolebean1 done all rolebeans of grouproles done groupbean1 done all groupbeans of userbeangroupsuserbeanroles rolebean1 save rolebean1 the second time and throws exception here done rolebean1 done all rolebeans of userbeanrolesthe cause of the exception is rolebean1 has been saved twice in a session and their identity is the samein the function savee e if i usesessionmergeereplacesessionsaveorupdateewill not throw exception but the rolebean1 is not assocaited to userbean1anyone can give some suggestions about this,['java'] +82027,how do you pass variables from c to javascript looking to pass variables from c to javascript to use some jquery code passing doubles ints strings arrays does anyone know how to do thisfor example if i have this code snip in cstring blah this is a blah stringi would like to pass this into javascript so that i could use a mouseover event in jquerymydivmouseoverfunction do something with my blah string,"['c#', 'javascript']" +82028,what is the python equivalent of rubys inspect i just want to quickly see the properties and values of an object in python how do i do that in the terminal on a mac very basic stuff never used pythonspecifically i want to see what messageattachments are in this google app engine mailhandler example images videos docs etc,['python'] +82036,open directory using c i am accepting the path through command line inputwhen i dodiropendirargs1it doesnt enter the loopie dirnullhow do i pass the command line input to dir pointervoid mainint cchar args dir dir struct dirent dent char buffer50 strcpybuffer args1 dir opendirbuffer this part ifdirnull whiledentreaddirdirnull printfdentd name closediraout roottest is used to run the programaout to execute the programroottest input by the user ie valid path,['c'] +82066,editable timetable using drupal i would like to manage a timetable using drupal 6 there are several pieces of equipment on which an administrator thistributes people who get to use the equipmentessentially i want a table of equipment versus day of the week the plan shows the occupation of all equipment for the whole week what makes it more complicated is that the editing of the timetable should be very easy and quick usually people have the equipment for multiple days so one should be able eg to drag an entry and fill out more days this way i would also like to have a selection of people visible that one could drag onto the timetable and fill it out that way i assume one can do that with javascript but i have no experience with that is it possible to create somethinglike that with the drupal forms api any pointersexamples for thedragging javascriptor is there some existing software ordrupal module that can do that,"['php', 'javascript']" +82103,razor view engine and jquery does anybody know how to force razor view engine to print exact line which is under foreach loop code follows section headscript typetextjavascript srcurlcontentcontentscriptsjquery141jsscriptscript typetextjavascript srcurlcontentcontentscriptsjqueryprogressbarminjsscriptscript typetextjavascript documentreadyfunction foreachvar player in model jquerypbplayeridprogressbar scripti tried using and jquery but in both case razor do not know what to do is there any way to force him to print exact this jquerypbplayeridprogressbar i want to have something like this documentreadyfunction pb1progressbar pb2progressbar pb3progressbarthank you in advance,['jquery'] +82122,altering a column to be nullable i want to alter a table column to be nullable i have used alter table merchant pending functions modify numberoflocations nullthis gives an error at modify what is the correct syntax,['sql'] +82131,should i use pt or px what is the difference between pt and px in css which one should i use and why,['css'] +82148,windbg free object type monitoring my programs virtual bytes usage while it is running showed that by doing some kind operations the virtual bytes usage goes up by about 1gb in about 5 minutesthe program deals with tcp sockets and high data transfer throughput between them 800mbpsloading a dump file of the program in windbg showed that the reason for the very high and fast memory usage is about 1gb of free objectsindeed when i call the garbage collector gen 0 1 2 from the console screen of the program after getting it to this state it frees up about 1gb of memory usagei am trying to understand what exactly are these free objects and why are not they garbage collected by the garbage collector automaticallyedit one suggestion was that i may be creating the objects in the large object heap and it becomes fragmanted but this is not the case as i have seen that all of the free objects sits in gen 2 heapother suggestion was that maybe gen 2 heap gets fragmented because of pinned objects but if this was the case gccollect wouldnt fix the problem but it actually does so i believe this is not the case as wellwhat i suspect from the thiscussion with paul is that the memory does gets freed but is from some reason returned to the os rarely or only when i manually call gccollect,"['c#', '.net']" +82159,is this the one in ten time to rewrite i am very much against rewriting an application if it can be avoided i understand the rule that 9 times out of 10 it is better to refactor but i am in a situation where it might be the one time in ten and i am looking to find that linethe current situation isi took over the maintenance of a vb6sql applicationthe total lines of code is 75100k codebehinds modules and classesthe original developer left so it is just me and there is no opportunity to expand the team at least for a few yearsthere was no architecture to the program just straight sql calls in plain text in the form codebehindsdoes not try to follow the dry or oaoo principlesdatabase had some primary keys but no foreign keysbefore this system was in place everything was managed in big spreadsheets so this system really is a huge improvement over what they had but does not do what they are envisioningi was able to write myself some tools to replace all literal instances of table names and column names with constants and lookups and i wrote a quick code gen script to generate those constants and lookups from the database so now i can safely make database changes and see everywhere that broke i have started normalizing the database around the edges but it is like 3 of the way therethere are no unit tests so every time i change the database i basically have to rewrite whatever logic sits on top of it and i use the two versions to compare functionality and make sure it is the same so far so goodi started by just trying to fix critical bugs to stop the bleeding and i can safely say that is mostly done so now i am stepping back for a moment to look at the big picturemanagement is supportive and reasonable in their expectationsthe longterm goal is to convert it to net anywayso i am weighing these optionscontinue normalizing the database and modifying the vb6 app as i go ends up being a piece by piece rewriteput the vb6 one into a maintenanceonly state no new features pick one functional module at a time and rewrite that part in net on top of a normalized database structuremy thought is that if i choose option 1 then at the end i just have a vb6 app that they still want to upgrade to net and i have looked into that and it is costly and time consuming and even with the tools youll still get something that is somewhat of a frankenstein if i go with option 2 i believe i can be done sooner and i will jump right to the target technologyin the small scale pieces that i have already rewritten during my normalization process the result has been an improved module over what was already there so there is value being added during the rewritethe existing app for all its flaws is a great talking point for thiscussion the people using it can tell me whats working for them and what is not so there is certainly a lot of value there that wayso does this qualify as one of those one in ten times or not,['.net'] +82162,viewswitcher and layout height in android i added a viewswitcher to a linearlayout which has two views of different height however it seems the viewswitcher is occupying space of the biggest of the views rather than arranging itself is this how it should bewhat to do in the other case i was trying to create an accordion where the title panel when clicked grows in size,['android'] +82165,how to test css selector performance how would i go about testing the performance benchmarks of different css selectors i have read articles like this but i do not know if it is applicable to my website because he used a test page with 20 classes and 60 dom elementsshould i even caredoes performance really get downgraded that much based upon the css strategy you takefo example i like doing this navbar backgroundgray navbar li thisplayinlinebackgroundf ul classnavbar limenu 1li limenu 2li limenu 3liul but i could do this navbar backgroundgray navbaritem thisplayinlinebackgroundf ul classnavbar li classnavbaritemmenu 1li li classnavbaritemmenu 2li li classnavbaritemmenu 3liulsome would say and might be right that the second option would be faster but if you multiply the second method across all pages i see the following thisadvantagesthe page size will increase because all the elements having classesnumber of css classes can get quite large which would require more css class parsingmy pages seem to be 8kb with 10 dom elementsso my real question is how do i create a test bed where i could test performance deltas based on strategy taken for realistic web page sizes specifically how do i know how long it takes for a page to be thisplayed javascript how exactlyhelp and just plain opinions are welcome,"['html', 'css']" +82186,are there dictionaries in javascript like python i need to make a dictionary in javascript like thisi dont remember the exact notation but it was something likestates dictionary ctalexharry aklizaalex txfred harry is there such a thing in javascript,"['javascript', 'python']" +82190,does pushviewcontroller retain the controller i am struggling to find out if pushviewcontroller retains the controller currently i have the following code which works colorcontroller colorcontroller colorcontroller alloc initwithnibnamenibcolor bundlenilself navigationcontroller pushviewcontrollercolorcontroller animatedyescolorcontroller releasebut am considering removing the release and adding an autorelease colorcontroller colorcontroller colorcontroller alloc initwithnibnamenibcolor bundlenil autoreleaseself navigationcontroller pushviewcontrollercolorcontroller animatedyesmuch appreciatedgary,"['iphone', 'objective-c']" +82209,understanding ccombstr assignment operators say i have the followingbstr mybstr sysallocstring lmybstr ccombstr myccombstr mybstrdoes myccombstr take ownership of mybstr and free it when it goes out of scope or does it make a copy of mybstr and produce a memory leak if i dont free mybstrif this produces a memory leak whats the most efficient way of handling this mybstr will be passed in to a function as a bstr and i want to store it as a ccombstrinternally,['c++'] +82214,how do i prevent maven 2 from searching remote repositories for specific local depedencies how do i prevent maven 2 from searching remote repositories for specific dependencies that are in the local repository only,['java'] +82217,custom action in c used via wix fails with error 1154 i am using wix 351930 in visual studio 2010 targeting the net framework 35 later weekly builds of wix seem to be very broken with respect to their custom action template at least for now 1930 is the most recent build that seems to make a buildable c ca with working referencesi have two custom action assemblies written in c one of them works fine the other fails with the following errorcustomactionamehere returned actual error code 1154 note this may not be 100 accurate if translation happened inside sandboxi have compared the csproj files and wixproj files and as best i can tell the differences are appropriate e g list of included cs files i have changed the nonworking wxs to call the working custom action instead of the nonworking custom action and it works as epxectedwhat else can i look at to get this workingedit just to be complete 1154 refers to an invalid dll net helpmsg translates it in english to one of the library files needed to run this application is damagedsecond edit ran peverify against the dll grabbed a copy out of windowsinstaller while the installer was running and it says everything is fine in the dll the dll only has the custom action method with a return success so there is not a lot for it to verify but it does confirm the dll is not corruptthird edit the code in the broken custom action followsusing microsoftdeploymentwindowsinstallernamespace frameworkinstallerdatabase public class customactions customaction public static actionresult runmigrationsession session return actionresultsuccess not much to it the relevant parts of the wxs are as followsinstallexecutesequence custom actiondotnetmigratorcustomactionpreviousup aftersetmigrationpropertiespreviousupcdatadatabase 3custominstallexecutesequencebinary iddotnetmigratorcustomactiondll sourcefilevarframeworkinstallerdatabasecustomactionstargetdirsoftwareanswersframeworkinstallerdatabasecustomactionsdll customaction iddotnetmigratorcustomactionpreviousup returncheck binarykeydotnetmigratorcustomactiondll dllentryrunmigration executedeferred,['c#'] +82233,best language to parse extremely large excel 2007 files my boss has a habit of performing queries on our databases that return tens of thousands of rows and saving them into excel files i being the intern constantly have to write scripts that work with the information from these files thus far i have tried vbscript and powershell for my scripting needs both of these can take several minutes to perform even the simplest of tasks which would mean that the script when finished would take most of an 8 hour daymy workaround right now is simply to write a powershell script that removes all of the commas and newline characters from an xlsx file saves the xlsx files to csv and then have a java program handle the data gathering and output and have my script clean up the csv files when finished this runs in a matter of seconds for my current project but i cannot help but wonder if there is a more elegant alternative for my next one any suggestions,['java'] +82234,using dates in jquery flot thisplay i am trying to use flot to plot a graph with dates i have followed the advice on this string here but it does not seem to work for me here is my modified javascript from that other questiondocumentreadyfunction var d1 1262818800100126273240010012626460100 var d2 1262818800231262732400231262646023 plotplaceholder datad1linesshow truelabelmountaindatad2linesshow truelabelvalleyyaxis labelcm xaxis modetime timeformat ms i get a graph but it does not convert the xaxis into dates and the values on the xaxis do not even line up with what i have got in the data variables i have even tried multiplying each datapoint by 10 to convert to javascript timestamps but that did not help either i have also tried the following timeformat variables in case that was the problemms hs ymdbut no luck any ideas,['jquery'] +82235,how can i tell if a page has jumped to the anchor in javascript i have some javascript that can appear on many different pages sometimes those pages have been accessed via a url containing an anchor reference comment100 for instance in those cases i want the javascript to delay executing until after the window has jumped right now i am just using a delay but that is pretty hackish and obviously does not work in all cases i cannot seem to find any sort of dom event that corresponds to the window jumpaside from the simple delay the only solution i have come up with is to have the js look for the anchor in the url and if it finds one watch for changes in scrolltop but that seems buggy and i am not 100 sure that my script will always get fired before the scrolling happens so then it would only run if the user manually scrolled the page anyhow i do not really like the solution and would prefer something more event driven any suggestionsedit to clarifyi am not trying to detect a hash change take the following examplepage indexphp contains a link to postphpcomment1user clicks the link to postphpcomment1postphpcomment1 loadsdocumentready firesnot long later the browser scrolls down to comment1i am trying to reliably detect when step 5 happens,"['javascript', 'jquery']" +82240,propertygrid alternatives i love propertygrid well at least the concept behind it use reflection and attributes to edit your objects without writing much ui codemy excitement died out pretty quickly though the default propertygrid shipping with winforms flatout sucks well it is fine for editing simple objects and such but that is as far as it goesit does not thisplay appropriate uitypeeditors for dynamic properties which have type objectas soon as your objects contain collections you might be able to edit them with so called collectioneditor however it would not fire propertyvaluechanged event so once you need to add undo functionality youre screwedand i still have not found an elegant way to add validation for collectioneditorit is also problematic to implement undo if you have multiple objects selected because in that case propertyvaluechanged event args changeditem is nulli soon found myself writing hacks to address those issues with less than agreeable resultswhat would you dois there an elegant solution to at least the first three issuesis there an alternative propertygrid preferably free without pinvokes,"['c#', '.net']" +82243,using helpers in rails 3 to output html i am trying my best to build a helper that outputs a ul consisting of all the members of a collection for each member of the collection i want to print out a li that has a title and a div of links to crud the member this is pretty similar to what rails outputs for scaffolding for the index viewhere is the helper i have gotdef thisplay allcollection sym collection collection symto scapitalizesingularizeconstantizeall name collection symto sdowncase html html ul classnamelist for member in collection do html content tagli id membertitlegsub downcasestrip do concat content tagh1 membertitle class nametitle concat link to edit namememberidedit concat concat link to view namememberid concat concat button to delete namememberid confirm are you sure this cannot be undone method delete end end html ul return htmlend and that output exactly what i want first of all if anybody thinks there is a better way to do this please feel free to correct me i suspect that i am doing this in a bass ackwards way but at the moment its the only way i know howi then attempted to wrap the links in a div as followsdef thisplay allcollection sym collection collection symto scapitalizesingularizeconstantizeall name collection symto sdowncase html html ul classnamelist for member in collection do html content tagli id membertitlegsub downcasestrip do concat content tagh1 membertitle class nametitle concat content tagdiv class linksbar do concat link to edit namememberidedit concat concat link to view namememberid concat concat button to delete namememberid confirm are you sure this cannot be undone method delete end end end html ul return htmlend however i now no longer get any of the markup inside the divlinksbar output to the view i am sure this must have something to do with block and bindings but i can for the life of me figure out what or how to go about fixing it can anybody offer any help,"['ruby-on-rails', 'ruby']" +82244,error on line 39 at column 26 namespace prefix xlink for href on script is not defined i am embedding a javascript file inside an svg file like thissvg xmlnsdc xmlnscc xmlnsrdf xmlnssvg xmlns xmlnssodipodi xmlnsinkscape version10 width95869 height59278998 idsvg2275 sodipodiversion032 inkscapeversion046 sodipodidocnamemap of usa with state namessvg sodipodidocbasectempwebdesign inkscapeoutput extensionorginkscapeoutputsvginkscape metadata idmetadata2625 rdfrdf ccwork rdfabout dcformatimagesvgxmldcformat dctype rdfresource ccwork rdfrdf metadata defs iddefs2623 inkscapeperspective sodipoditypeinkscapepersp3d inkscapevp x0 29639499 1 inkscapevp y0 10 0 inkscapevp z95869 29639499 1 inkscapepersp3dorigin479345 197596 1 idperspective364 defs script typetextecmascript xlinkhrefscriptjs and i am getting the above error anyone know what am idoing wrong,"['javascript', 'html', 'css']" +82263,how to tell chrome language of your web site as a hint to the translate bar i have a web app that is in queens engrish but the chrome translate bar pops up and tells me that its in estoniani have tried lang and xmllang but the google translation bar seems to ignore thesenote the web application is totally ajax and the content that causes the bar to pop up is dynamic content that can appear long after the page load so perhaps i have to add a header to my ajax responsesanyone ever had issues like this guido,['javascript'] +82281,quick beginner xslt reference i need to learn xslt for wordpress and symphony theming what are some beginner friendly resources that are relatively easy to follow along to,"['html', 'css']" +82311,php remove first zeros want to remove all 0 placed at the beginning of some variablesome optionsif var 02 we should strip first 0 var 2if var 0203410 we should remove first 0 var 203410if var 20 do nothing var 20what is the solution,['php'] +82315,converting systemdecimal to systemguid i have a big dictionary where the key is decimal but the gethashcode of systemdecimal is thisasterously bad to prove my guess i ran a for loop with 10 neigboring decimals and checked the thistribution 10 different decimal numbers used only 2 two different hashcodesdecimal is represented as 16 bytes just like guid but the gethashcode thistribution of guid is pretty good how can i convert a decimal to guid in c as cheap as possibleunsafe code is okedit the test was requested so here is the codedecimal d 960mdictionaryint int hashcount new dictionaryint intint length 10for int i 0 i length i int hashcode dgethashcode int n if hashcounttrygetvaluehashcode out n hashcounthashcode and 1 else hashcountaddhashcode 1 dconsolewritelinehashcountcountthis prints 7 i do not remember the starting decimal that gave me 2,"['c#', '.net']" +82316,difference between managed and unmanaged i hearread about it sometimes when talking about net for example managed code and unmanaged code but i have no idea what they are and what are their differences what are their difference by definition what are the consequences of using either of them does this thistinction exist in netwindows only,['.net'] +82317,serverwide functionality across several web applications i need to perform pre and postprocessing of all incomming requests to a web server the functionality is both urllevel access restriction and language translation but also other special cases that need to be handled globalytypically this can be achieved with servlet filters but when the number of web applications grow it becomes desirable not to bundle the filters with every application since all applications need to be rebuilt and redeployed when making a change to a filterinstead i would like to install the filters globally on the server and i have found two possible solutions of which i am not satisfied with any of themon tomcat it is possible to deploy serverwide filters in the lib directory and configure the server webxml to map them to incoming requests the problem i see is that any filter dependencies also need to be deployed globally in the lib directory from what i understand this can cause hard to solve dependency conflicts with installed applications deploying the filters in a simple web application that mainly acts as a proxy would at least bundle the filters with their corresponding dependencies this application can then be deployed on the server and take all incoming requests before forwarding them to the target application using the crosscontext config parameter however this requires fiddling with the urls such that all links point to the proxyneither of these solutions seem to be satisfactory they are both platform dependent since they rely on tomcat they also both seem to have possible problems and require special handling of dependencieswhat is the best practise when using server wide functionality,['java'] +82328,question on using monitortryenter and locking object consider the following function that implements nonblocking access to only the one threadpublic bool trycancelgroup if monitortryenter locked if locked false locked true try do something catch exception ex locked false finally monitorexit locked return locked else return false and here is how locked variable is definedbool locked falsenow when program reaches monitorexit locked it throws an systemthreadingsynchronizationlockexception saying that locked variable was not synchronized before it all was working before when locked variable was defined as objectobject locked new objectwhen i changed it to bool in order to use it as boolean flag i started getting this exception,"['c#', '.net']" +82348,mysql loop over tables and alter table add index i have 10 tables that start with the same prefix table prefix some id i can take the ids from another tablewhat is the fast way to loop over all the tables in mysql and do alter table table prefix some id add index fields field,['mysql'] +82353,vs 2010 fails debugging httpexception invalid file name for file monitoring in loadcontrol i have really been struggling for days on this matteri have migrated a aspnet 35 project in vs2010 to a aspnet 4 project everything worked fine for several weekssomehow i get a strange error since a few days to clarify what this project looks likethe applicationit is a usercontrol based application and the app areas are composed of nested usercontrol hierarchies that load their children controls in oninit in order to get the event system to worknote everything works great in vs2008 and net 35the errornow when i start debugging the webapplication in vs2010 sometimes a httpexception is thrown with the messageinvalid file name for file monitoringin loadcontrol and now it gets interesting the parameter for loadcontrol is a prefixed usercontrolpath eg controlshomepartialascx but in the exception it is shown as a directory somewhere in the controls directoryprobably vs uses such an approach to internally track changed files to reloadhas anyone encountered the same issue if so have there been any solutionsedit when deploying the webapplication the error vanishes it only occurs when debugging i have currently thisabled httpexceptions in the debugexceptions menu but i would be very glad to catch those again too,['asp.net'] +82354,getting enum value via reflection i have a simple enum public enum testenum testone 3 testtwo 4 var testing testenumtestoneand i want to retrieve its value 3 via reflection any ideas on how to do this,['c#'] +82365,java searching for data within a website i am new to java and having some problemsthe main idea is to connect to a website and collect information off it and store it in an arraywhat i want the program to do is to search the website find a key word and store what comes after the key wordon the front page of daniweb along the bottom of the website there is a section called tag cloud which is filled with tags short wordstag cloud i want to store what is written heremy idea is to first read in the html of the website and then search that file for the key word followed by the text using scanner and stringtokenizer then store as a arrayis there a better way easierwhere do you suggest i look for some examples here is what i have so far import javanetimport javaiopublic class urlreader public static void mainstring args throws exception url dweb new url urlconnection dw dwebopenconnection bufferedreader in new bufferedreadernew inputstreamreaderhcgetinputstream systemoutprintlnconnected to daniweb string inputline printstream out new printstreamnew fileoutputstreamoutfiletxt try while inputline inreadline null outprintlninputline systemoutprintlninputline inclose outclose systemoutprintlnprinted text to outfile catch filenotfoundexception e eprintstacktrace try scanner scan new scanneroutfiletxt string search txtsearchgettext while scanhasnextline line scannextline still working while sthasmoretokens word stnexttoken if word search else scanclose searchwinthispose catch ioexception iox any help at all would be very much appreciated,['java'] +82366,how do i suppress warnings in checkstyle i am using the checkstyle plugin for eclipseit is great at finding things i did not intend 99 of the time but the 1 of the time i actually did intend to knowingly violate a rule i would like to let checkstyle know it need not concern itself with flagging a warningexample the missing a javadoc comment rule most of the time i want javadoc comments on my methods however a method such aspublic boolean isvalid return validcan probably get by without oneis there anything like the suppresswarnings annotation which can be used to flag a specific checkstyle rule violation as acceptable some sort of specially formatted comment maybe i do not want to thisable the rule i just want to ignore a specific violationi realize in this case i could just write the javadoc comment but in other cases fixing the rule violation is not so simple,['java'] +82370,notification resume activity i know there are several questions of this type but i tried all of it and it still does not workok for my app i have got an activity in this activity there are 4 tabs and the fourth one contents a list and a record button when i am pushing record there is a gps listener which starts after getting a new gps value it pushes it into the listthis works so farif i click the home button it still works if i longpress it then it resumes that activity with the specific tab open and the list still hold the listitems and the gps listener is still activethis works also finenow i wanted to add a notification which shows the count of gps values of the list as number on every new gps signal it updates the notification icon with the new number this is no problem but the action to click on the notification totally screws up my applicationthe actual code looks like thispublic void callnotifystring text notif new notification intent contentintent new intentthis tabactivityclass contentintentputextrafid thisspecialvalue contentintentsetflagsintentflag activity clear top intentflag activity single top notificon rdrawableicon notifsetlatesteventinfothis getstringrstringapp name text pendingintentgetactivitythisgetbasecontext 0 contentintent pendingintentflag update current notifledargb colorred notifledonms 200 notifledoffms 200 notifflags notificationflag show lights notificationflag ongoing event notificationflag only alert once notifnumber notifynumber mnotificationmanagernotifynotifynumber notifpublic void updatenotifystring text notifynumber notifnumber int notifynumber 2 intent contentintent new intentthis tabactivityclass contentintentputextrafid thisspecialvalue contentintentsetflagsintentflag activity clear top intentflag activity single top notifsetlatesteventinfothis getstringrstringapp name text pendingintentgetactivitythisgetbasecontext 0 contentintent pendingintentflag update current mnotificationmanagercancelnotifynumber 2 mnotificationmanagernotifynotifynumber notifso the updatenotify is called on a new gps signal and the callnotify is the first one before it starts the gps listener and yeah the notifynumber2 was my intention because i work with that number furtherif i compile it like this and click on the notification it opens a new tabactivity on the first tab if i click back then i get a lot of errors database is still open nullpointers and stuff i think because it starts a new tabactivity and the other one is still open because i can see the gps listener is still workingso what i want is that i can do the followingi open my app go to the tabactivity open tab 4 click record if i click back then it should hide the app also if i just click the home button but there is a notificationif i click on that one it should just show the hidden activity again and thats it so what i am doing wrong therei thought the flags flag activity clear top and flag activity single top should solve the problem,['android'] +82371,how do i save user preferences for my iphone app the question title pretty much gives it away i would like my app to remember a few things it is some sort of calculator so it should save the last used values and some user selectable settingsbasically i would like to save a handful of floats and bools and load them again the next time the app loadswhats the best and easiest way to do thatthanks,"['ios', 'objective-c', 'iphone']" +82376,junit assertion methods should be phrased in the positive or the negative should i be writingasserttrueuser logged in userisloggedinorasserttrueuser is not logged in userisloggedinthe former provides better reading inside the source filesi assert that the following is true user logged inthe error message could be read both waysjavalangassertionerror user logged inthere is an error in asserting that the user is logged inthe error is that the user is logged injunit documentation does not provide a clear guide to which it should be except it isthe identifying message for the link assertionerrorand in both cases the text identifies the test being runwhats the common usage,['java'] +82393,what method in the string class returns only the first and characters i would like to write an extension method to the string class so that if the input string to is longer than the provided length n only the first n characters are to be thisplayedheres how it looks likepublic static string truncatelongstringthis string str int maxlength if strlength maxlength return str else return the first maxlength characters what string method can i use to get only the first n characters of str,"['c#', '.net']" +82405,increment letters like numbers i would like to write a function that takes in 3 characters and increments it and returns the newly incremented characters as a stringi know how to increase a single letter to the next one but how would i know when to increase the second letters and then stop and then increase the first letter again to have a sequential increaseso if a is passed return aab if aaz is passed return aba hard parti would appreciate help with the logic and what php functions will be useful to useeven better has some done this already or there is a class available to do thisthanks all for any help,['php'] +82412,how to catch that map panning and zoom are really finished i am trying to write an application that will dynamically load data to map while user pans or zooms it i need to track when the map is finished to change its view state stops panning or zooming and then load a new portion of data for creating markers but in fact google maps api does not have any events to handle this there are some methods like creating an empty overlay to control ontouch events and so on but map panning could last long after user finished his touch because gmaps use some kind of inertia to make the pan smootheri tried to subclass mapview but its draw method is final thus it cannot be overriddenany ideas how to make precise handling of pan and zoom finishing,['android'] +82427,can jsf standard validation prevent code injection in my project i do duplicate validation at the presentation layer as well as the persistence layer with the hope to increase security so my question is can standard jsf validation prevent code injectionshinputtext idname valuebeancustomername requiredtrue requiredmessagevalidation error value is required titlename fvalidatelength maximum40hinputtexthere i validate if the field is empty and validate field length i know validate field length will make it harder to do code injection but sometimes you need a long field length such as textarea and if this is vulnerable how will i fix it thank you so much in advance,['java'] +82428,use a persistent notification to allow the user to return to running android app i am developing an app with numerous activities i would like to create a persistent notification that more or less says appname return to appname that will be present whenever my background services are running creating and thisposing of the notification was no problemnow the user could be on any of several screensactivities leave the application then want to reenter the app via the notification the problem is the notification must have an intent which launches a predetermined activity i want the notification to reenter the app in whatever activity is at the top of the history stackmy first attempt at an ugly workaround was to make an activity let us call it returnfromnotify whose only job was to finish itself in it is oncreate the notification would open returnfromnotify in the scope of the applications history which would then immediately remove itself sending the user back to the previous history state in the application stack this seems to work unless the user has used back to completely back out of the app then when they hit the notification returnfromnotify loads then finishes sending them back out to the home screen as there are no activities in the history stack for the appi considered trying to detect if there was anything in the history stack before returnfromnotify and if not fire up my main activity i cannot seem to find a way to do this eitherany input or suggestions for a javaandroid novice fyi my primary history is with scriptbased languages,['android'] +82429,how do i immediately execute an anonymous function in php in javascript you can define anonymous functions that are executed immediatelyfunction do something can you do something like that in php,"['php', 'javascript']" +82481,css how to add dot between navigation title after i login wlinkedincom the navigation bar on top right thisplays the title as followswelcome x skip to content search add connections settings help sign outi would like to know how they add between different titles i have used firebug but i did not see where they add such a small between titlesthank you,['css'] +82487,whats the best way to do application settings in android i would like to store some application settings like the url of an api and some settings for testing for an android applicationi mostly work as a net developer so i am used to using the file appconfig for this purpose whats a good way to do it in android,['android'] +82498,is it possible to sanitize javascript code i want to allow user contributed javascript in areas of my websiteis this completely insane are there any javascript sanitizer scripts or good regex patterns out there to scan for alerts iframes remote script includes and other malicious javascript should this process be manually authorized by a human checking the javascript would it be more sensible to allow users to only use a framework like jquery rather than giving them access to actual javascript this way it might be easier to monitorthanks,['javascript'] +82499,basic authentication with jqueryajax request and jsonp i have some local htmljs files with which i would like to invoke some remote servers via https and eventually use basic authentication for the requesti am encountering two problems first is that if i do not specify jsonp for the datatype jqueryajax request returns the erroraccess to restricted uri denied code 1012are my requests considered crossdomain because my main work file is stored locally but retrieving data from a server elsewhere so fine i update the call so it now looks likeajax url myserverurl type get datatype jsonp considered a cross domain ajax request if not specified username myusername password mypassword success functionresult success handling error functionreq status errthrown error handling because i need to use basic authentication i am passing in the usernamepassword but if i monitor the request i do not see it being set and additionally the server sends an error response since it does not have the expected infoadditionally because i have jsonp set beforesend would not get invokedhow do i pass along the credentials using basic authentication for this request,"['javascript', 'jquery']" +82504,wwinmain unicode and mingw i am working on learning the windows api and am using mingw as my compiler with codeblocks as my ide i have run into an issue with using the wwinmain function i used the program located here link text it compiles fine on vsc 2008 express but when using mingw i get the undefined reference to winmain16 error i have figured out what the problem is i think by replacing the wwinmain with just winmain and the string pointer pwstr with lpstr it compiles perfectly my question is how can i fix this and if not is not using unicode that big of a dealthanks,['c++'] +82532,how to handle infinite loop caused by invalid input using scanner so i am getting stuck with this piece of codeimport javautilinputmismatchexceptionimport javautilscannerpublic class consolereader scanner reader public consolereader reader new scannersystemin readerusedelimitersystemgetpropertylineseparator public int readintstring msg int num 0 boolean loop true while loop try systemoutprintlnmsg num readernextint loop false catch inputmismatchexception e systemoutprintlninvalid value return num and here is my outputinsert a integer number invalid value insert a integer number invalid value,['java'] +82542,how to estimate zip file size in java before creating it i am having a requirement wherein i have to create a zip file from a list of available files the files are of different types like txtpdfxml etci am using java util classes to do itthe requirement here is to maintain a maximum file size of 5 mb i should select the files from list based on timestamp add the files to zip until the zip file size reaches 5 mb i should skip the remaining filesplease let me know if there is a way in java where in i can estimate the zip file size in advance without creating actual fileor is there any other approach to handle this,['java'] +82545,please explain the use of javascript closures in loops possible duplicatejavascript closure inside loops simple practical example i have read a number of explanations about closures and closures inside loops i have a hard time understanding the concept i have this code is there a way to reduce the code as much as possible so the concept of closure can be made clearer i am having a hard time understanding the part in which the i is inside two parenthesis thanksfunction addlinks for var i0 link i5 i link documentcreateelementa linkinnerhtml link i linkonclick function num return function alertnum i documentbodyappendchildlink windowonload addlinks,['javascript'] +82546,python and openmp c extensions i have a c extension in which i would like to use openmp when i import my module though i get an import errorimporterror home entropysplitso undefined symbol gomp parallel endi have compiled the module with fopenmp and lgomp is this because my python installation was not compiled with the fopenmp flag will i have to build python from source or is there some other possibility this is the only time i actually use openmp in my moduleunsigned int feature indexpragma omp parallel forfor feature index 0 feature index num features feature index i would like to stick with openmp if it is possible just because it is so easy and the parallelization in this case suits it welledit i bit the bullet and recompiled python with openmp support my module works perfectly now but this is not really a great solution i cannot really thistribute this if it requires a complete recompile of python so does anybody know some way around this would ctypes work maybesolved it was a simple linking issue i rebuilt python for that openmp was not being properly linked during the compilation of the module so it is possible to load a c python extension that uses openmp,['python'] +82547,stack growth direction so from my previous memmove question i would like to know how to find direction of stack growth void stackdirectionint i int j ifji coutstack is growing up nendl else coutstack is growing down nendl int main int i1 stackdirtectioni,['c++'] +82552,androidsharedpreference hi i need simple explanation about shared preference in android and preference data,['android'] +82556,whats the story behind the name of the sos son of strike debugger extension whats the significance of the name son of strike does it serve any meaning or does it just sound cool,['.net'] +82566,perl dbi fetchall hashref consider the following tablemysql select from vcountrystatus countryname countryiso code status symbol currencyname brazil br 55 live brl brazilian real france fr 33 offline eur euro philippines ph 63 live php philippino peso 3 rows in set 0 seci am trying to construct a hash based on this table for this i do the followingusrbinperluse dbiuse datadumpermy dbh dbiconnectdbimysqldatabasedb user password raiseerror 1 autocommit 0 fetchhashkeyname name lc die db open error dbierrstrmy sth dbhprepareselect from vcountrystatussthexecutemy hash sthfetchall hashrefcountryisoprint dumperhashhere is the output this generatesvar1 ph symbol php status live countryname philippines countryiso ph currencyname philippino peso code 63 br symbol brl status live countryname brazil countryiso br currencyname brazilian real code 55 fr symbol eur status offline countryname france countryiso fr currencyname euro code 33 the question is why is the key of the hash countryiso repeated in the values inside the hashwhat i would prefer is the following outputvar1 ph symbol php status live countryname philippines currencyname philippino peso code 63 br symbol brl status live countryname brazil currencyname brazilian real code 55 fr symbol eur status offline countryname france currencyname euro code 33 is it possible using fetchall hashref dbi method or do i have to go the traditional way looping through each row and constructing the hash on the fly,['mysql'] +82580,string tokenizer for cpp string i want to use string tokenizer for cpp string but all i could find was for charis there anything similar for cpp string,['c++'] +82588,c can a struct inherit from a class i am looking at the implementation of an api that i am usingi noticed that a struct is inheriting from a class and i paused to ponder on it first i did not see in the c manual i studied with that a struct could inherit from another structstruct a struct b public a i guess that in such a case struct b inherits from all the data in stuct a can we declare publicprivate members in a struct but i noticed this class a struct b public a from my online c manuala class is an expanded concept of a data structure instead of holding only data it can hold both data and functions is the above inheritance valid even if class a has some member functions what happen to the functions when a struct inherit them and what about the reverse a class inheriting from a struct practically speaking i have this struct user messages stdliststdstring messagesand i used to iterate over it like this foreach message in user messagesmessages if i want to add member functions to my struct can i change its declaration and promote it to a class add functions and still iterate over my user messagesmessages as i did before obviously i am still a newbie and i am still unclear how structs and classes interact with each other whats the practical difference between the two and what the inheritance rules are,['c++'] +82618,caching all users in aspnet i am working on a web app in aspnetc which needs to be scalable to handle the high user load will probably run in a web farm since it will cater to a high number of users around 1 million plus but number of online users would be around 30k50k i plan to use caching provider based and was wonderingis it a good idea to cache all users for performance i plan to cache all other generic data like settings etc but how efficient would it be to cache all users in memory if a user changes hisher profile i will reload only that particular user in cache having a collection of all the users any suggestions on this approachdo i need to worry about locking when using this above users cache only one editing the profile would be the user himself that would be one atomic operation though there will be multiple read oeprations in different threads so while fetching users from cache or updating a particualr user should i use lockthanksasif,['asp.net'] +82621,sequence points in c a sequence point in imperative programming defines any point in a computer programs execution at which it is guaranteed that all side effects of previous evaluations will have been performed and no side effects from subsequent evaluations have yet been performedwhat does this mean can somebody please explain it in simple words,['c'] +82642,android detect another application has started playing audio my music application constantly plays music in the background however i would like to be able to detect when another application starts playing audio such as the youtube app so i can pausemutestop the audio in my applicationthis will allow a user to continue browsing the web whilst listening to music but then if they wish to watch a video at any point they can do so without audio conflictone solution might be to listen for a broadcast which states when an application begins using the audiomanager does such an intent action existedit as in the answer provided below there appears to be a method of detecting the loss of audio focus in 22 with audiomanageronaudiofocuschangelistenergreat but is there a solution for the more common versions of android ideally 15,['android'] +82668,how to add valid key without specifying value to a stdmap i have a stdmap and i would like to add a valid key to iterate over it later but without giving any value it will be given later on in the course of the iterations this is how i do it for now stdvectorstdstring valid keysfill then stdmapstdstring float mapforsize t i 0 i valid keyssize i i do not want to do that because in fact i do not use a float type mapvalid keysi 0f using forstdmapstdstring floatiterator it mapbegin it mapend it itsecond 0 dummyhow can i do that please thanks aforehand,['c++'] +82683,using null in c possible duplicatedo you use null or 0 zero for pointers in c is it a good idea to use null in c or just the value 0is there a special circumstance using null in c code calling from c like sdl,['c++'] +82689,developing apps for both iphone and android we have customers asking for apps that can run on both iphone and android i realize this will mean two different development projects but wonder if anyone has any advicecreative tips on this subject eg ways to maximize shared resourcesnote realize making the app webbased would be most effective way but looking for advice on crossdevelopment on the native platforms,"['iphone', 'android']" +82693,jquery insert new row into table at a certain index i know how to append or prepend a new row into a table using jquerymy table tbodylastappendhtmlhow to i insert the row given in the html variable into a specific row index i so if i3 for instance the row will be inserted as the 4th row in the table,"['javascript', 'jquery']" +82709,why only 1 public class in java file in any java file why can we have only one public class whose name is same as the java file name,['java'] +82720,passing too many arguments to printf any c programmer whos been working for more than a week has encountered crashes that result from calling printf with more format specifiers than actual arguments egprintfgonna s and s s crash burnhowever are there any similar bad things that can happen when you pass too many arguments to printfprintfgonna s and s crash burn dudemy knowledge of x86x64 assembly leads me to believe that this is harmless though i am not convinced that there is not some edge condition i am missing and i have no idea about other architectures is this condition guaranteed to be harmless or is there a potentially crashinducing pitfall here too,['c'] +82737,mysql case in select statement with like operator is it possible to combine the case statement and the like operator in a mysql select statementfor example i am trying to query a database that stores data in a single column in either one of two formats this is awful and hurts my head but i cant change the data so it is what it is so sometimes the column numbers would have data like 6901x and sometimes it would have data like 91xwhat i would like to do is query the data like so select case digits when like 6901 then substrdigits4 when like 91 then substrdigits2 end as digitsfrom rawthis obviously does not work but im hoping its possible,['mysql'] +82738,how to programatically detect if my application is running in iis 70 integrated mode from within an aspnet page generally we should have control of our apools and be able to force the managed pipeline mode in my case i do not have control and would like to implement the code behind code a little differently based on the managed pipeline mode integrated vs classic i just do not know how to detect this is there a simple way to do it from within the code behind page,"['c#', 'asp.net']" +82752,is there any way to prevent ajax pages from being viewed alone in a browser for example when i want to update a part of my page with ajax i would normally make the appropriate call to getpostphp which would return the markup to be inserted into my page is there any way to prevent a user from accessing this page directly eg examplecomgetpostphp with the appropriate get or post arguments and getting only part of the page since this should be used with ajax as part of a whole not alonei do not think permissions can be set on the file since it is the client requesting the page but is there a way to do this by passing an extra argument that can serve as a check digit of sorts,['php'] +82763,python virtualenv gtk20 to add gtk20 to my virtualenv i did the following virtualenv nositepackages pythonusrbinpython26 myvirtualenv cd myvirtualenv source binactivate cd libpython26 ln s usrlibpymodulespython26gtk20 now in the python interpreter when i do import gtk it says no module named gtk when i start the interpreter with sudo it works any reason why i need to use sudo and is there a way to prevent itupdateforgot to mention that cairo and pygtk work but it is not the one i needupdate2here the directory to show that i am not crazy,['python'] +82771,css child vs descendent selector i read that using the child selector in css is faster than the descendant selector for example p em as opposed to p em it seems to me that the majority of code i see in the wild does not take advantage of thisi understand that certain circumstances would merit the use of one or the other but in general should i be striving to take advantage of the child selector whenever possible or should i follow what seems to be convention and rely mostly on the descendent selector,['css'] +82784,is doxygen the de facto standard documentation syntax specification we all have the good habit of documenting our code right nowadays incode documentation itself has a syntax it is almost like a programming language onto itself the questions are what how many documentation syntax specifications existis there a standard documentation syntax who is defining this standard is there an official committee or body like there is one for defining c standards or has doxygen become the defacto standardit is difficult not to have heard about doxygen it is mentioned in every open source software project i have taken part in yet looking at the official doxygen web site it is far from obvious that doxygen is defining any kind of specification the impression i get when i read the ways it can help me is that doxygen is simply a software to extract incode documentation and present it in beautiful html pages looking at the doxygen front page i could even think that doxygen could use any documentation syntax defined in 3rd party specifications and extract it and output it as html also it is interesting to note that the doxygen web site does not capitalize the word doxygen as if it were not the brand of their software but a common noun well is it what is doxygen reallya parsing enginean html rendering enginea library that can be used by 3rd party software to render their own docsa documentation syntax de facto specificationall of the abovei am particularly confused as to the relationship between doxygen and other code parsers like antlr boostspirit ragel for example what is it that doxygen can do that antlr cannot and that antlr can that doxygen cannot also looking at the drupal project they havetheir own api module which is an implementation of a subset of the doxygen documentation generator specificationtheir own grammar parser module to add to the list above alongside doxygen itself antlr et alltheir own api web site running the two aforementioned modules presenting the drupal incode doxygen documentation so to take a c analogy it seems that the word doxygen is overloaded and means different things in different contexts within the drupal project doxygen does not refer to a software but simply a standard specification for documentation syntax even though as i said above the front page of the doxygen web site itself does not claim to be such a thing so my parting question isis there any other documentation syntax specification,['c++'] +82787,wordpress hook directly after body tag one of the things that drives me crazy about wp devolopement is i am never able to find the right hook so i figured i would ask here what i am trying to do is add a message to the top of each page by having my plugin add a function whats the best hook to use i want to insert conent right after the body tagthanksedit i know it is 3 years later now but here is a trac ticket for anyone who is interested,['php'] +82801,database modeller for jpa with visual diagrams i am looking for a tool to help in designing and implementing database and entities for a java project probably we are using jpa or direct hibernate the features i look for aredesign database with visual modellercreate entities from the visual modelupdate entity changes to the visual modelimport existing database schema as visual model entity classesso the idea is to originally create a database model with visual tool then autoto generate entities from it and afterwards modify the code and expect the visual diagram to reflect the changes so it works for documentation purposes i want a full representation of table schema not just an er diagramthere have been other questions of course but they do not seem to be so specific to javajpa and do not have as strict requirements they are also often just about generating a diagram from code or database schema they do not require bidirectional support if that is the right termthe products i found so far arenetbeans 671 supports generating java classes from uml jpa needs specific templates sounds too tricky does not identify new elements from classesdbschema seems to offer some visualization of schemas could not get it started so cannot say much commercial but it also has a free versionomondo eclipseuml seems to have some sort of support but costs like hellschemaspy supports only creating documentation from an existing database schema also could not find a comprehensive graphtoad data modeller somewhat messy homepage however seems to support creating diagrams from existing db as well as creating db schema from a diagram does not have code generation facilitieseclipse wtps dali jpa tools no support for visual presentation however targeted at providing aid to jpa developmentas a conclusion dali seems most interesting because it is targeted for jpa development however it does not seem to have a visual diagram of any sort just outlines and stuffany suggestions,['java'] +82804,how to use xdebug with eclipse ide for php hi my php project is set up on a remote test machine i need to debug it using eclipse ide how shall i progress i came to know i should prefer xdebug rather than zend debugger,['php'] +82817,java enum best practice this might seem like a trivial question but i am a bit muddled in my thinking regarding enumsso i have a class let us say its called dvdplayer and i want to have an enum that represents whether it is on off or standby so i can put the enum in the class it does not make sense outside of the class my question is this should the enum be public so that other classes can query values or should i make it private and then have ison isoff and isstandby methods the latter sounds a bit daft but i am unsure as to whether it is a good idea to have the enum as public as well,['java'] +82819,why should i use implicitly typed local variables when i say public static imytype getgatewaymanager iunitycontainer container getcontainer imytype gatewaymanager containerresolveimytype return gatewaymanagerit comes with a warning saying use implicitly types local variableif i change it to public static imytype getgatewaymanager iunitycontainer container getcontainer var gatewaymanager containerresolveimytype return gatewaymanagerit is fine can anyone can tell me why the vs editor thinks it is best practice to use var here,['c#'] +82838,can i sort the nsdictionary on basis of key in objectivec can i sort the nsdictionary on basis of key,['objective-c'] +82863,how to check whether list contains only none in python lnonenoneis there a function that checks whether list l contains only none or not,['python'] +82877,preferred java way to ping an http url for availability i need a monitor class that regularly checks whether a given http url is available i can take care of the regularly part using the spring taskexecutor abstraction so that is not the topic here the question is what is the preferred way to ping a url in javahere is my current code as a starting pointtry final urlconnection connection new urlurlopenconnection connectionconnect loginfoservice url available yeah available true catch final malformedurlexception e throw new illegalstateexceptionbad url url e catch final ioexception e loginfoservice url unavailable oh no e available falseis this any good at all will it do what i wantdo i have to somehow close the connectioni suppose this is a get request is there a way to send head instead,['java'] +82891,iterable objects and array type hinting i have a lot of functions that either have type hinting for arrays or use is array to check the arrayness of a variable now i am starting to use objects that are iterable they implement iterator or iteratoraggregate will these be accepted as arrays if they pass through type hinting or undergo is array if i have to modify my code is there a generic sort of is iterable or must i do something likeif is arrayvar or var instance of iterable or var instanceof iteratoraggregate what other iterable interfaces are out there,['php'] +82905,is there a way to create an immutable readonly xdocument i have an api that returns xelements and i want the document behind those xelements to be immutable readonly i need it fornot to give devs an ability to change it accidentally improving performance creating a copy of an xdocument might be a performance heavy operation in some casesit does not seem to possible to inherit override the necessary behavior in xdocumentxelementxcontainer because all virtual methods there are marked as internalinternal virtual void xcontaineraddattributexattribute aso my question is is there a way make it happen or it is better to have a different api that will either return something like xpathnavigators or it is better to have own classes like ireadonlyxelement etc,['.net'] +82916,how to read number of lines in uitextview i am using uitextview in my view i have requirement to count number of line contained by textview am using following function to read n however this works only when return key is pressed from keyboard but in case line warapper when i type continuous characters i wont get new line char how do i read new char when line is changed without hitting return key anybody has nay idea how to please share it i am follwing this link link booltextviewuitextview textview shouldchangetextinrangensrangerange replacementtextnsstring text any new character added is passed in as the text parameter if text isequaltostringn be sure to test for equality using the isequaltostring message textview resignfirstresponder return no so that the final n character does not get added return no for any other character return yes so that the text gets added to the view return yes,"['iphone', 'objective-c']" +82940,how to understand the design and code flow of any product quickly i have switched to a new company and i am working on a product that has a huge code base without documentation i want to quickly get acquainted with the design and the code flow of the product so that i may become a productive member asapslowly and steadily one does gets to understand the code but what should be the best and smart way one should approach the code base so that he understands the code quickly and start deliveringnote i tried my hands on star uml and tried to reverse engineer the class diagrams so that i may have a rough idea of the product internal designs but failed miserablyedit the question is not about gaining knowledge about what the product does but how the internals are designedfixing bugs and debugging using breakpoints does provide one way of achieving this but i was looking if there is even a faster way we could achieve thisin keiths wordsthis may work for some codebases but in general i think its a bad idea you tend to be too focused on the details while at first you want to get the big picture what the classes are what the communication patterns are etc plus if you have a thistributed application clientserver ntier etc or code that takes a long time to run it may not be practical to run it through a debugger,['c++'] +82960,android and paypal api integration i am trying to integrate the paypal api to make my app donation based i have two questions i can see the button i click it but it does not do anything the activity for checkoutintent does not firewhat are your experiences with donation based android apps i want to make about 250 a month of this thing is that even possiblepublic class donate extends activity implements onclicklistener paypal ppobj paypalinitwithappidthisgetbasecontext app80w284485p519543t paypalenv sandbox override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutdonate linearlayout mainlayout linearlayoutfindviewbyidridlinearlayout01 if ppobj null ppobj paypalinitwithappidthisgetbasecontext app80w284485p519543t paypalenv sandbox checkoutbutton paypalbutton checkoutbutton ppobjgetpaymentbuttonpaypalbutton 294x45 this paypalpayment type hard goods paypalbuttonsetonclicklistenerthis mainlayoutaddviewpaypalbutton public void onclickview arg0 paypalpayment newpayment new paypalpayment newpaymentsetamountfloat 100 newpaymentsetcurrencyusd newpaymentsetrecipient intent checkoutintent new intentthis paypalactivityclass checkoutintentputextrapaypalactivityextra payment info newpayment thisstartactivityforresultcheckoutintent 1 override public void onbackpressed intent menuintent new intentdonatethis mtgtoolsclass thisstartactivitymenuintent,['android'] +82973,dependency injection and appsettings let us say i am defining a browser implementation class for my applicationclass internetexplorerbrowser ibrowser private readonly string executablepath cprogram filesieexe code that uses executablepaththis might at first glance to look like a good idea as the executablepath data is near the code that will use itthe problem comes when i try to run this same application on my other computer that has a foreignlanguage os executablepath will have a different valuei could solve this through an appsettings singleton class or one of its equivalents but then noone knows my class is actually dependent on this appsettings class which goes against di ideias it might pose a difficulty to unittesting tooi could solve both problems by having executablepath being passed in through the constructorclass internetexplorerbrowser ibrowser private readonly string executablepath public internetexplorerbrowserstring executablepath thisexecutablepath executablepath but this will raise problems in my composition root the startup method that will do all the needed classes wiring as then that method has to know both how to wire things up and has to know all these little settings dataclass compositionroot public void run classa classa new classa string iesetting1 casdapopokaposkdaposkaexe string iesetting2 ie setting abc string iesetting3 lolbmp classb classb new classbiesetting1 classc classc new classcb iesetting2 iesetting3 which will turn easily a big messi could turn this problem around by instead passing an interface of the forminterface iappsettings object getdatastring nameto all the classes that need some sort of settings then i could either implement this either as a regular class with all the settings embedded in it or a class that reads data off a xml file something along the lines if doing this should i have a general appsettings class instance for the whole system or have an appsettings class associated to each class that might need one that certainly seems like a bit of an overkill also have all the application setings in the same place makes it easy to look and see what might be all the changes i need to do when tryign to move the program to different platformswhat might be the best way to approach this common situationeditand what about using an iappsettings with all its settings hardcoded in itinterface iappsettings string ie executablepath get int ie version get this would allow for compiletime typesafety if i saw the interfaceconcrete classes grow too much i could create other smaller interfaces of the form imyclassxappsettings would it be a burden too heavy to bear in medbig sized projectsi have also reading about aop and its advantages dealing with crosscuttingconcerns i guess this is one could not it also offer solutions to this problem maybe tagging variables like thisclass internetexplorerbrowser ibrowser appsetting string executablepath appsetting int ieversion code that uses executablepaththen when compiling the project wed also have compile time safety having the compiler check that we actually implemented code that would weave in data this would of course tie our api to this particular aspect,['c#'] +82974,how can i make text appear on next line instead of overflowing i have a fixed width div on my page that contains text when i enter a long string of letters it overflows i do not want to hide overflow i want to thisplay the overflow on a new line see belowdiv idtextbox stylewidth400px height200pxdfsfdsdfsdfdfsdfdivis there anyway to thisable overflow and put the overflowing text on a new line twitter does something like this but i cannot figure it out with css it is possible they are using javascriptcan anybody help with this,['css'] +82988,number of floats between two floats say i have two python floats a and b is there an easy way to find out how many representable real numbers are between the two in ie754 representation or whatever representation the machine used is using,['python'] +83020,how to do forms authentication on purely html pages using aspnet i am using forms authentication in iis7 to passwordprotect a dev site but the authentication seems to get bypassed when the site contains only static html files loginaspx webconfigwhen i renamed the files to aspx i am prompted with the login formi am not doing anything fancy i have a very simple login script and it should just redirect to indexhtml afterwardany suggestions to summarize the entire site is using html for now and needs to be password protectedauthentication modeforms forms nameappnameauth path loginurlloginaspx defaulturlindexhtml protectionall timeout525600 credentials passwordformatclear user nameuser passwordpassword credentials formsauthenticationauthorization deny users authorization,"['asp.net', 'html']" +83021,is there a way to trap all errors in a ajaxweb service i would like to trap any unhandled exception thrown in an aspnet web service but nothing i have tried has worked so farfirst off the httpapplicationerror event does not fire on web services so that is outthe next approach was to implement a soap extension and add it to webconfig withsoapextensiontypes add typefoo priority1 group0 soapextensiontypeshowever this does not work if you call the web method over json which my web site does exclusivelymy next idea would be to write my own httphandler for asmx which would hopefully derive from systemwebscriptservicesscripthandlerfactory and do something smart i have not tried this yetis there an approach i am missing thanksmikeupdatei will summarize the possibly solutions here1 upgrade to wcf which makes this whole thing much much easier2 since you cannot subclass or override the resthandler class you would have to reimplement the whole thing as your own ihttphandler or use reflection to manually call into its methods since the source to resthandler is public and only about 500 lines long making your own version might not be a huge amount of work but youd then be responsible for maintaining it i am also unaware of any licensing restrictions involved with this code3 you can wrap your methods in trycatch blocks or perhaps use lambda expressions to make this code a bit cleaner it would still require you to modify each method in your web service,"['c#', 'asp.net', '.net']" +83022,wcf 4 rest getting ip of request hey how do you get the ip address of the person making a request in something like the following servicecontract aspnetcompatibilityrequirementsrequirementsmode aspnetcompatibilityrequirementsmoderequired servicebehaviorinstancecontextmode instancecontextmodepercall public partial class usersservice webinvokeuritemplate method put public user addnewuseruser newuser code goes here including getting an ip thanks,['c#'] +83023,trying to post with ruby mechanize i have captured the login http headers using firefox plugin livehttpheadersi have found the following url and variablespost loginemailmyemail40gmailcompasswordsomethingremember1loginsubmitloginand heres the code i am runningrequire rubygemsrequire mechanizebrowser mechanizenewbrowserpostemailmyemail40gmailcompasswordsomethingremember1loginsubmitloginurl do pageputs pagebodyendhowever this gives me nothing is something wrong with my post parameters,['ruby'] +83024,android sdk mediaplayercreate randomly returns null i am having an issue where occasionally the mediaplayercreate method will return null even though the audio file is definitely there in fact if i put the call to create into a while loop the media player will eventually be created successfully this only seems to happen on my phone htc hero running 21 and never in the emulator is this just an issue with the phone or is there a different way i should be playing these audio filesnote that i want to be loading them dynamically which is get i am making the call to getindentifer if there is a better way of playing these dynamically please let me knowpublic void playaudiostring audiofile instance variable of type mediaplayer player null while player null player mediaplayercreate context getresourcesgetidentifieraudiofile raw contextgetpackagename playerstartthanks,['android'] +83043,what does javalangthreadinterrupt do could you explain what javalangthreadinterrupt does when invoked,['java'] +83060,mysql select multiple maximum values i have a table called order which contains columns id user id price and item id item prices are not fixed and i would like to select each items most expensive order i want to select user id item id and price in the same query i tried the following query but it does not return the correct result setselect user id item id maxpricefrom ordergroup by item idsome of the rows returned by this query have the wrong user id however all rows in the result set show each items correct highest price,['mysql'] +83066,can we create a vc executable which will work natively on both 32 bit and 64 bit windows is there any way to build a vc project so that the dllexe created by it will work as a 32 bit application on a 32 bit windows os and as a 64 bit application on a 64 bit windows os not in wow64i know that is possible for c applications using the anycpu option,['c++'] +83071,compare 2 versions of a net assembly how to compare 2 versions of a compiled net assembly to see changes between the 2 versions i have a library not welldocumented and i need to know what has been changed between the old version and the new version,['.net'] +83101,open source swing based application that employs good practices i am trying to learn swing and i was thinking you guys may know a really good swing based open source application that i could study and inspire from i am looking for something that has a real world use not just some concepts explained like examples in most books and tutorialsthank you,['java'] +83102,getting a reference to the parent iframe say i have a reference to a document object which is contained inside an iframe how do i get a reference to the container iframe parentnode and ownerdocument both return nullplease note that no context information is available eg solutions like windowx will not work all that is available is a reference to the document objectthanks,"['javascript', 'css']" +83104,php get html source code with curl how can i get the html source code of without using file get contentsi need to know this because on some webhosts allow url fopen is thisabled so you cannot use file get contents is it possible to get the html files source with curl if curl support is enabled if so howthanks,"['php', 'html']" +83118,selector on background color of textview i am attempting to change the background color of an android textview widget when the user touches it i have created a selector for that purpose which is stored in rescolorselectorxml and roughly looks like thatxml version10 encodingutf8selector xmlnsandroid item androidstate pressedtrue androidcolorcolorsemitransparent white item androidcolorcolortransparent selectorthe clickable attribute of the textview is true in case that is of interestwhen i assign this selector to a textview as androidbackgroundcolorselector i am getting the following exception at runtimeerrorandroidruntime13130 caused by orgxmlpullv1xmlpullparserexception binary xml file line 6 tag requires a drawable attribute or child tag defining a drawablewhen i change the attribute to drawable it works but the result is looking completely wrong because the ids appear to be interpreted as image references instead of color references as the drawable suggestswhat confuses me is that i can set a color reference eg colorblack as the background attribute directly this is working as expected using selectors does not worki can also use the selector as the textcolor without problemswhats the correct way to apply a backgroundcolorselector to a textview in android,['android'] +83130,how to redirect a user after registration when using devise i am using rails 23 and devise to handle user registration authenticationi need to redirect a user to an external 3rd party website immediately after a user signs up for an account been looking in the code online but cannot see how to do thishow can i alter the devise flow to redirect the user,"['ruby-on-rails', 'ruby']" +83131,what are register globals in php can someone give some examples of what register globals areand is global user id considered a register global,['php'] +83140,is there a way to get the source code from an apk file the hard drive on my laptop just crashed and i lost all the source code for an app that i have been working on for the past two monthsall i have is the apk file that is stored in my email from when i sent it to a friend is there any way to extract my source code from this apk file,['android'] +83146,is a element always available in the dom even if absent in the html markup every browser i have observed creates a head element that is accessible in the dom even if there are no explicit headhead tags in the documents markuphowever google analytics uses the following code for dynamic script insertionfunction var ga documentcreateelementscript gatype textjavascript gaasync true gasrc https documentlocationprotocol httpsl httpw googleanalyticscomgajs documentgetelementsbytagnamehead0 documentgetelementsbytagnamebody0appendchildgathe following linedocumentgetelementsbytagnamehead0 documentgetelementsbytagnamebody0appendchildgaseems to make a special concession for cases where a head element is not presentis this just a case of extreme backwardscompatibility eg for netscape 4 or the like or is there a case to be made for not assuming that modern browsers ie internet explorer 6 and more recent will always have access to a head element in the dom,"['javascript', 'html']" +83153,iphone storage in tmp directory i have a question from this stackoverflow question about iphone storage like i already tried to answer we can cache data in tmp directory but a comment says that the data can be deleted when os whimp i do not understand exactly the problem that the comment says i want to ask if the process of os deleting tmp directory is manually or automatically in other words if the system auto detect that our tmp directory has to be deleted another question is that if we can control or be asked to do something before the deleting process that can help us to keep the tmp directoryanother question is that if we can not do anything then how often the os will do that under what circumstances,"['ios', 'objective-c', 'iphone']" +83155,prevent html browser from clipping text showing 12 a text line let us say my browser window is 105 pixels high and i show a text block where each line of text is 10 pixels high the browser will show me 10 and 12 lines in the window ie the bottom line will be clipped verticallyis there some way to prevent this behavior and see only 10 linesthe reason i want to do this is that i am using a html widget uiwebview to render a book that will be thisplayed with a pageflipping paradigm note it looks like page rules are supposed to help me accomplish this but they only seem to apply when printing to a printer,"['html', 'css']" +83171,weird behaviour with conditional operator in net this has me pretty stumped maybe i am too tired right now rectangle rectangle new rectangle0 0 imagewidth imageheight rectangle croparea inputarea null rectangle inputareavalue if inputarea null croparea rectangleinputarea is a nullable rectangle which in my particular case is nullthe first two statements yields a croparea initialized to 0 the second however yields the correct croparea based on the image width and height have i misunderstood anything with the conditional operator it seems it does not return rectangle when inputarea null is there any quirks when working with value typesedit alright i should have tried this first restarted vs it seems the debugger lied to me or something anyway works now thanks,"['c#', '.net']" +83190,what does the valid annotation indicate in spring in the following example the scriptfile parameter is marked with an valid annotationwhat does that dorequestmappingvalue scriptfile method requestmethodpost public string createvalid scriptfile scriptfile bindingresult result modelmap modelmap if scriptfile null throw new illegalargumentexceptiona scriptfile is required if resulthaserrors modelmapaddattributescriptfile scriptfile modelmapaddattributeshowcases showcasefindallshowcases return scriptfilecreate scriptfilepersist return redirectscriptfile scriptfilegetid,['java'] +83193,detecting javascript errors in chrome chrome does not appear to give any indication that a page has javascript errors unless you open up the javascript console to checkis there any way to have an indication that there were errors and then automatically open the javascript console can the javascript console be opened from javascript,['javascript'] +83204,need to add text to rectangle i am creating dynamic rectangle and adding into stackpanel i need to add text to each rectangle how can i do that,['c#'] +83213,g standards support i am a bit puzzled reading this gcc 45 online manual standards sectionthey explain thisthe original iso c standard was published as the iso standard isoiec 148821998 and amended by a technical corrigenda published in 2003 isoiec 148822003 these standards are referred to as c98 and c03 respectively gcc implements the majority of c98 export is a notable exception and most of the changes in c03but they do not tell if gcc support the bare 98 c or only the corrected c03 in the c language section the explanation is more clearerrors in the 19 iso c standard were corrected in three technical corrigenda published in 2001 2004 and 2007 gcc does not support the uncorrected version so my question is is it also the case for g no support of the uncorrected standard the only 4 options to select a g standard are then stdc98 stdgnu98stdc0x and stdgnu0x is that correct and last subquestion what is the ansi option then is it only used in c mode edit ansi a synonym for stdc89 for c or stdc98,['c++'] +83224,c how to use the function uname i should write a function to get some information about the system the most important information is the the architecture i found the function uname which can be used including sysutsnameh well though i googled and i read the documentation i could not find any example of the function and i do not understand how to use uname anyone can explain me how to use it it would be great if you can write an example too thanks in advance,['c'] +83238,whats the graceful way of handling out of memory situations in cc i am writing an caching app that consumes large amounts of memoryhopefully i will manage my memory well enough but i am just thinking about what to do if i do run out of memoryif a call to allocate even a simple object fails is it likely that even a syslog callwill also failedit ok perhaps i should clarify the question if malloc or new returns a null or 0l value then it essentially means the call failed and it cannot give you the memory for some reason so what would be the sensible thing to do in that caseedit2 i have just realised that a call to new can throw an exception this could be caught at a higher level so i can perhaps gracefully exit further up at that point it may even be possible to recover depending on how much memory is freed in the least i should by that point hopefully be able to log something so while i have seen code that checks the value of a pointer after new it is unnecessary while in c you should check the return value for malloc,"['c++', 'c']" +83246,how do i use filedescriptor with http urls i was hoping this was going to work for getting androids mediaplayer to stream from a url using authentication but now i am not so sure i have no problem getting it to stream from an open server no authentication but i do not see any way to tell mediaplayer to use basic authentication unless perhaps using the filedescriptor argument works so i tried this but got the following errorillegalargumentexception expected file scheme in uri my code looks something like thisfile f new filenew urltourifileinputstream fis new fileinputstreamfmediaplayersetdatasourcefisgetfdis it correct to say that a filedescriptor can only be used with local file urls and not normal http urls if so does anyone have any other ideas on how to stream from a server that requires authentication using androids mediaplayer,['android'] +83248,how to make python 3 print utf8 how to make python 3 31 to printsome text to stdout in utf8 or how to output raw bytestestpytesttext test a a34a12 this is utf8 testtext2 btest2 xc4x81xc4x80xc4x93xc4x92xc4x8dxc4x8cxc5xa1xc5xa0xc5xabxc5xaaxc5xbexc5xbd just bytes printsysgetdefaultencoding printsysstdoutencoding printtesttext printtesttextencodeutf8 printtesttextencodecp1252replace printtesttext2 output in cp1257 and i replaced chars to byte values xhexutf8 cp1257 test xe2xc2xe7c7xe8xc8xf0xd0xfbxdbxfexde btest xc4x81xc4x80xc4x93xc4x92xc4x8dxc4x8cxc5xa1xc5xa0xc5xabxc5xaaxc5xbexc5xbd btest x9ax8ax9ex8e btest2 xc4x81xc4x80xc4x93xc4x92xc4x8dxc4x8cxc5xa1xc5xa0xc5xabxc5xaaxc5xbexc5xbd print is just too smart dthere is no point using encoded text with print it always show only representation of bytes not real bytesand it is impossible to output bytes at all because print anyway and always encodes it in sysstdoutencoding for exampleprintchr255 throws an errortraceback most recent call last file testpy line 1 in printchr255 file hpython31libencodingscp1257py line 19 in encode return codecscharmap encodeinputselferrorsencoding table0 unicodeencodeerror charmap codec cannot encode character xff in position 0 character maps to by the way print testtext testtext2decodeutf8 returns falsealthough print output is same edithow python 3 gets sysstdoutencoding and how to change iti made printraw function witch works fine tnx zackactually it encodes output to utf8 so in real it is not rawdef printrawtext rawout open1 w encodingutf8 closefdfalse printtext filerawout rawoutflush rawoutclose printrawcool testtext output now it print in utf8cool test a a34a12printrawchr252 also nicely prints a14 in utf8 xc3xbc and without errors now i am looking for maybe better solution if there is any,['python'] +83249,can i have a multi class selector in jquery can i do something like the below where i can have multiple classes trigger an eventared ablue agreenclickfunctionevent,['jquery'] +83251,ideal method to truncate a string with ellipsis i am sure all of us have seen ellipsis on facebook statuses or elsewhere and clicked show more and there are only another 2 characters or so i would guess this is because of lazy programming because surely there is an ideal methodmine counts slim characters iil1 as half characters but this does not get around ellipsis looking silly when they hide barely any charactersis there an ideal method here is mine return a string with a maximum length of codelengthcode characters if there are more than codelengthcode characters then string ends with an ellipsis param text param length return public static string ellipsisfinal string text int length the letters iil1 are slim enough to only count as half a character length mathceiltextreplacealliil length 20d if textlength length return textsubstring0 length 3 return textlanguage does not really matter but tagged as java because that is what i am mostly interested in seeing,['java'] +83275,java check whether a string is not null and not empty in my web app i have a search field where i get some string and a combo box so i am sending two arguments to the remote functioni want to check that the user input is not null and not empty so then i can construct a valid querypublic arraylist findemployeesstring str int dep throws classnotfoundexception sqlexception systemoutprintlnlist in arraylist list new arraylist javasqlstatement stmt javasqlresultset rs classfornamecommysqljdbcdriver string url jdbcmysqllocalhost3306general javasqlconnection con drivermanagergetconnectionurl root 1234 systemoutprintlnurl url systemoutprintlnconnection con stmt concreatestatement stmt concreatestatementresultsettype scroll insensitive resultsetconcur read only string qry select from person string werstr where ifstr null str here i want to check the str is empty or not qry werstr name like str systemoutprintlnqry werstr and ifdep 0 qry werstr deptdep qry systemoutprintlnqry rs stmtexecutequeryqry while rsnext employee employee new employee string name rsgetstring2 employeesetnamename int id rsgetint1 employeesetidid int dept rsgetint4 employeesetdeptdept int age rsgetint3 employeesetageage listaddemployee systemoutprintlnlist out return listwhat is the best way to do that,"['java', 'mysql']" +83285,unused parameter warnings in c code whats the best way to suppress unused parameter warning in c codefor instancebool nullfuncconst struct timespec when const char who unsigned short format void data int len return truein c i was able to put a comment around the parameters but not in c of courseit gives me error parameter name omittedsome tips would be appreciated,['c'] +83287,view content of apk file is there a way to extract and view the content of an apk file,['android'] +83299,ajax file download using jquery php i want to use the ajax functionality to download whereby the user will click the download link which will using ajax and get access a php file which will process the sent get variables and access the correct file for downloadingi have a few php scripts to handle the processing of the get variables which work on their own but when accessed using ajax they stop workingthe ajaxphp code im using is belowfunction ajaxdowndownloadmsghtml img srcmediaimagesajaxloadergif width128 height15downloadmsgloadmediadownloadsdownmanagerphpfilefilequeryfilenameftypedownex1please look through my code and help me find what im doing wrongthanx,"['php', 'jquery']" +83312,how do i offer a beta feature to select users rails we want to start letting our users help us test our feature changes before a wider release our rails app already has roles but i do not know how to we should go about implementing a beta feature without moving the whole app over some issues i cannot think of solutions toa beta feature may require a database migration how can you handle this when it could cause problems with the existing appchanging templates and the csass will likely change it for existing features toochanging the underlying model code could break existing controllers interfaces that rely on itone solution a bad option is to code in the new feature and wrap it in logic that only showsuses it if the user has the beta role the problem with this is when you finally take it live you could have a lot of unwindingchanging to do this is both a waste of time and could introduce bugsanother solution is to run a separate beta branch of the app off a subdomain and route users with the beta role to it the problem with this is that the complexity of ssl certificates email links and other domain dependent issues make this a bit of a maintenance pain though not as bad as the first solutionhow can i offer this most efficiently so as to minimize the additional work to maintain and then switch the beta to the full version,['ruby-on-rails'] +83327,is it possible to delete an objects property in php if i have an stdobject say asure there is no problem to assign a new property aanew property xyzbut then i want to remove it so unset is of no help heresoanew property nullis kind of it but is there a more elegant way,['php'] +83337,how do i pass content from a template to a layout in express i have a basic express server serverjsvar express requireexpressapp expresscreateserverappconfigurefunction appsetviews pathjoin dirname views appsetview engine jade appsetview optionsappget function request response responserenderwelcome locals some locals with a basic jade layout viewslayoutjade 5htmllangen head title pagetitle body h1 pagetitle asideidsidebar sidebarcontent content bodyand a simple page viewswelcomejade how do i pass pagetitle and sidebarcontent out to the layout from herep welcome to my fine sitein rails this might be something like content for or a simple instance variable,['javascript'] +83348,how can i declare dynamic string array in java i am using string array declare as zoom znew string422 but this array stores value from 0 to 32 so i got null pointer exception after looping value 32 how to solve this problem in javahow can i declare a dynamic array in java,['java'] +83350,how to download jars from maven central without writing any pomxml i would like something like the followingi want just an utility that is able to download jars and their dependencies from the maven repository without imposing no constraints on how my project should be builti would like something like thisdownloadjar destlib commonsiocommonsiojar14it should be able to download also the dependenciesupdatei wouldnt know about a pomxml should be structuredthe only task i need to be accomplished is the download of the jars i would like have a tool that could accomplish this task that does not bother me with superflous informationthere is something like that,['java'] +83354,html arabic support i have a website in which i have to put some lines in arabic how to do itwhere to get the arabic text characters how to make the page support arabici have to put a line per page and there is a lotta lotta pages so cannot go around making images and putting them,['html'] +83366,python private module in a package i have a package mypack with modules mod a and mod b in it i intend the the package itself and mod a to be imported freelyimport mypackimport mypackmod ahowever i would like to keep mod b for the exclusive use of mypack that is because it exists merely to organize the latters internal code my first question is is it an accepted practice in python programming to have private modules like thisif yes my second question is what is the best way to convey this intention to the client do i prefix the name with an underscore ie mod b or would it be a good idea to declare a subpackage private and place all such modules there,['python'] +83381,why would our java app not thisplay windows on secondary monitor we have a javaswing client that is been around for quite a few years when i moved from xp to vista client only runs on windows i noticed that whenever a new window is created usually a jframe descendant on my secondary monitor the window initially shows as blank ie instead of showing the normal contents of the window it is just a solid block of gray if i then drag that window onto the primary monitor the second it crosses the monitor boundary it draws itself properly and i can drag it back to the secondary monitor if the window is created on the primary monitor it always comes into existence perfectly i never had this problem on xp only on vista i am unable to easily test it on windows 7 lacking a dual monitor windows 7 machineanybody have any ideas is this perhaps a known java bug i am also running the most recent java 16 sdk,['java'] +83391,remove resize handles and border from elements with contenteditable the problem i am having is with the contenteditable attribute in ie some things never changethe problem is that i am getting resize handles and a thick border around li elements when they are in focusany idea of how to remove them css or javascript tricks are very welcome,"['javascript', 'html', 'css']" +83404,antixss java libraries i am looking for a java library that can provide protection against xss attacks i am writing a server and would like to validate my users input does not contain malicious javascriptwhich library would you recommend,['java'] +83406,are there plans for immutableenumset in java 7 i want to have all the efficiencies of enumset and pass it around without worrying that somebody would modify it,['java'] +83418,a facebooklikenotification system in php how can i put in place a facebooklikenotification system a usera writes a message to the userb a listener on the database routes the message to the userb on the userb interface the message appears instantlyhow can i do that in phpthank you very muchregards,"['php', 'javascript']" +83433,how to get the metadata of jstree this is my codedemo1jstree themes theme default dots true icons true url staticthemesdefaultstylecss ui this makes the node with id node 4 selected onload initially select locationhashslice1split1 json data data data a node attr id 1 time1321 callbackfunctionalerts children data t node children child 1 child 2 attr id 2 data title long format demo attr href data s node attr id 3 children data b node data k node attr id 11 children data o node children p n data wwqq node attr id 4 children child 1 child 2 data h node attr id 5 metadata i am the metadata children data a node children data t node children child 1 child 2 data b node sortfunction a b return thisget texta thisget textb 1 1 contextmenu show at nodefalse items ccpfalse sort the item label label sort the function to execute upon a click action function obj var fnfunction a b return thisget texta thisget textb 1 1 thischangesortobjfn all below are optional thisabled false clicking the item would not do a thing class sort class is applied to the item li node separator before false insert a separator before the item separator after true insert a separator after the item false or string if does not contain used as classname icon false submenu name label name action function obj var fnfunction a b return thisget texta thisget textb 1 1 thischangesortobjfn time label time action function obj var fnfunction a b return thisget texta thisget textb 1 1 thischangesortobjfn icons label icons actionfunctionobjwindowaobj submenu apple label apple action function obj thisset themeapple classic label classic action function obj thisset themeclassic default label default action function obj thisset themedefault core initially open plugins themes json datacrrmuicontextmenusearchsort bindsearchjstree function e data alertfound datarsltnodeslength nodes matching datarsltstr i set the metadatametadata i am the metadataand want to get it when i right clickon the contextmenu icons label icons actionfunctionobjconsolelogthisdatai show thisdata follow this article the metadata property will be saved using the jquery data function on the li node metadata a string array object etcbut i cannot get it what can i do,['jquery'] +83453,creating a simple xml file using python what are my options if i want to create a simple xml file in python library wisethe xml i want looks likeroot doc field1 nameblahsome value1field1 field2 nameasdfasdsome vlaue2field2 docroot,['python'] +83461,is c still being widely used in game engines the title is a bit of a misnomer what i mean really is c with classeslet me explain recently i bought the book shaderx7 which came with a lite and old copy of the unigine engine for one of the articles about shadow mapping techniquesi was dabbling through the code when i realized that while the author was using c and inheritance and all the c goodness most if not all the method content was essentially cstyle code for exampleint shaderget paramconst char namechar srcstring dest const char s src int size intstrlenname whiles ifstrncmpsnamesize ifs src strchrnrs 1 strchr ts size src s s size destclear whiles strchr ts s whiles strchr tnrs null dest s ifdestisempty logerrorshaderget param cannot get s nname return 0 memmovesrcsstrlens 1 return 1 s return 0i am not saying this is bad it does the job and that is what matters but i am more used to c style constructs with stdstring vectors etc and i make big use of the boost libraries so this kind of style come as a bit of a surprise to meis it really betterfaster to use this kind of code than to go the generic oo way did i fall into the too much abstraction trap edit corrected method name to make it clear what it is doing,"['c++', 'c']" +83467,rmagick warning while running server i am using gem 137 rails 235 and ruby 187 20080811 patchlevel 72 while starting server i get below warnings loading development environment rails 235usersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb44 warning already initialized constant percentgeometryusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb45 warning already initialized constant aspectgeometryusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb46 warning already initialized constant lessgeometryusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb47 warning already initialized constant greatergeometryusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb48 warning already initialized constant areageometryusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb49 warning already initialized constant minimumgeometryusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb52 warning already initialized constant flagsusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb58 warning already initialized constant rflagsusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb92 warning already initialized constant wusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb93 warning already initialized constant husersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb94 warning already initialized constant xusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb95 warning already initialized constant yusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb96 warning already initialized constant reusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb151 warning already initialized constant align type namesusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb156 warning already initialized constant anchor type namesusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb162 warning already initialized constant decoration type namesusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb169 warning already initialized constant font weight namesusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb180 warning already initialized constant gravity namesusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb187 warning already initialized constant paint method namesusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb199 warning already initialized constant stretch type namesusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb205 warning already initialized constant style type namesusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb673 warning already initialized constant model versionusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb674 warning already initialized constant destinationusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb675 warning already initialized constant file formatusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb676 warning already initialized constant file format versionusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb677 warning already initialized constant service identifierusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb678 warning already initialized constant envelope numberusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb679 warning already initialized constant product idusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb680 warning already initialized constant envelope priorityusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb681 warning already initialized constant date sentusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb682 warning already initialized constant time sentusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb683 warning already initialized constant coded character setusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb684 warning already initialized constant unousersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb685 warning already initialized constant unique name of objectusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb686 warning already initialized constant arm identifierusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb687 warning already initialized constant arm versionusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb691 warning already initialized constant record versionusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb692 warning already initialized constant object type referenceusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb693 warning already initialized constant object nameusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb694 warning already initialized constant titleusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb695 warning already initialized constant edit statususersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb696 warning already initialized constant editorial updateusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb697 warning already initialized constant urgencyusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb698 warning already initialized constant subject referenceusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb699 warning already initialized constant categoryusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb700 warning already initialized constant supplemental categoryusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb701 warning already initialized constant fixture identifierusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb702 warning already initialized constant keywordsusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb703 warning already initialized constant content location codeusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb704 warning already initialized constant content location nameusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb705 warning already initialized constant release dateusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb706 warning already initialized constant release timeusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb707 warning already initialized constant expiration dateusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb708 warning already initialized constant expiration timeusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb709 warning already initialized constant special instructionsusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb710 warning already initialized constant action advisedusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb711 warning already initialized constant reference serviceusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb712 warning already initialized constant reference dateusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb713 warning already initialized constant reference numberusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb714 warning already initialized constant date createdusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb715 warning already initialized constant time createdusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb716 warning already initialized constant digital creation dateusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb717 warning already initialized constant digital creation timeusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb718 warning already initialized constant originating programusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb719 warning already initialized constant program versionusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb720 warning already initialized constant object cycleusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb721 warning already initialized constant by lineusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb722 warning already initialized constant authorusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb723 warning already initialized constant by line titleusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb724 warning already initialized constant author positionusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb725 warning already initialized constant cityusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb726 warning already initialized constant sub locationusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb727 warning already initialized constant provinceusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb728 warning already initialized constant stateusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb729 warning already initialized constant country primary location codeusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb730 warning already initialized constant country primary location nameusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb731 warning already initialized constant original transmission referenceusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb732 warning already initialized constant headlineusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb733 warning already initialized constant creditusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb734 warning already initialized constant sourceusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb735 warning already initialized constant copyright noticeusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb736 warning already initialized constant contactusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb737 warning already initialized constant abstractusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb738 warning already initialized constant captionusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb739 warning already initialized constant editorusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb740 warning already initialized constant caption writerusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb741 warning already initialized constant rasterized captionusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb742 warning already initialized constant image typeusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb743 warning already initialized constant image orientationusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb744 warning already initialized constant language identifierusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb745 warning already initialized constant audio typeusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb746 warning already initialized constant audio sampling rateusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb747 warning already initialized constant audio sampling resolutionusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb748 warning already initialized constant audio durationusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb749 warning already initialized constant audio outcueusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb750 warning already initialized constant objectdata preview file formatusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb751 warning already initialized constant objectdata preview file format versionusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb752 warning already initialized constant objectdata preview datausersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb756 warning already initialized constant size modeusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb757 warning already initialized constant max subfile sizeusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb758 warning already initialized constant objectdata size announcedusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb759 warning already initialized constant maximum objectdata sizeusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb763 warning already initialized constant subfileusersmervmgemsruby187p72mbmgemsrmagick2131librmagickrb767 warning already initialized constant confirmed objectdata size,['ruby-on-rails'] +83478,listview scroll to the end of the list after updating the list i would like to make sure that the list is scrolled all the way to the bottom after i have updated the listview by using listadapter so that it thisplays the last element entered in the list how can i do this i tried this but no lucklvsettranscriptmodelistviewtranscript mode always scrollthank you,['android'] +83500,left string function in c whats the best way to return the first word of a string in cbasically if the string is hello world i need to get hellothanks,['c#'] +83506,object of class stdclass could not be converted to string i am having a problem with php at the moment i am getting this error object of class stdclass could not be converted to string the error occurs when i run this portion of code in my site function myaccount datauser data thisauthget userdatathisurisegment3 var dumpdatauser data thisloadmodelusers model datauser info thisusers modelget user and roadmaps by idthisurisegment3 thistemplatebuildusersmy account datathe line in which the error is occuring is this one datauser data thisauthget userdatathisurisegment3and this line is calling this function function get userdata ci get instance ifthislogged in return false else query cidbget whereusers arrayuser id cisessionuserdatauser id return queryrow i do not really now what this problem is so any help would be great,['php'] +83516,cannot install apk on phone i have just knocked together my first app have released and signed it and transferred to my phone but cannot get it to install on my phone after going through the screen saying do you want to install this application and clicking install i just get a message saying application not installed with no further explanation i had checked the signing using jarsigner verifyi have uploaded the apk to and obtained the log using the logcollector app on my phone the relevant extract is reproduced belowlog collector version 110device model htc desirefirmware version 22kernel version 263215gf9c0527htckerneland182 1 preempt fri jul 23 172653 cst 2010build number frf910831 101821289 iactivitymanager 93 starting activity intent actandroidintentactionview datfilesdcardblanketapk typapplicationvndandroidpackagearchive cmpcomandroidpackageinstallerpackageinstalleractivity 0831 101821359 ipackageparser20453 ukcooketchupblanketsquare compat added androidpermissionwrite external storage androidpermissionread phone state0831 101821379 dskia 20453 decoderdecode returned false0831 101821669 iactivitymanager 93 thisplayed activity comandroidpackageinstallerpackageinstalleractivity 331 ms total 331 ms0831 101822059 dpowermanagerservice 93 new lightsensor value640 lcdvalue1920831 101822390 dsynchronizationservice20285 checking preferences0831 101822769 iactivitymanager 93 starting activity intent datfilesdcardblanketapk cmpcomandroidpackageinstallerinstallaprogress has extras 0831 101822849 dskia 20453 decoderdecode returned false0831 1018229 ddalvikvm20459 gc explicit freed 419 objects 23968 bytes in 74ms0831 101823089 dpackageparser 93 scanning package dataappvmdl73677tmp0831 101823099 ipackageparser 93 ukcooketchupblanketsquare compat added androidpermissionwrite external storage androidpermissionread phone state0831 101823129 iactivitymanager 93 thisplayed activity comandroidpackageinstallerinstallaprogress 320 ms total 320 ms0831 101823139 wpackageparser 93 exception reading reslayoutmainxml in dataappvmdl73677tmp0831 101823139 wpackageparser 93 javaioioexception0831 101823139 wpackageparser 93 at javautilzipinflaterinputstreamreadinflaterinputstreamjava2070831 101823139 wpackageparser 93 at javautilzipzipfilezipinflaterinputstreamreadzipfilejava4320831 101823139 wpackageparser 93 at javaiofilterinputstreamreadfilterinputstreamjava1300831 101823139 wpackageparser 93 at orgapacheharmonyluniutilinputstreamhelperreadfullyandcloseinputstreamhelperjava1740831 101823139 wpackageparser 93 at javautiljarjarfilegetmanifestjarfilejava3070831 101823139 wpackageparser 93 at javautiljarjarfilegetinputstreamjarfilejava3850831 101823139 wpackageparser 93 at androidcontentpmpackageparserloadcertificatespackageparserjava3380831 101823139 wpackageparser 93 at androidcontentpmpackageparsercollectcertificatespackageparserjava5090831 101823139 wpackageparser 93 at comandroidserverpackagemanagerserviceinstallpackagelipackagemanagerservicejava59610831 101823139 wpackageparser 93 at comandroidserverpackagemanagerserviceaccess2100packagemanagerservicejava1380831 101823139 wpackageparser 93 at comandroidserverpackagemanagerservice5runpackagemanagerservicejava48190831 101823139 wpackageparser 93 at androidoshandlerhandlecallbackhandlerjava5870831 101823139 wpackageparser 93 at androidoshandlerthispatchmessagehandlerjava920831 101823139 wpackageparser 93 at androidoslooperlooplooperjava1440831 101823139 wpackageparser 93 at androidoshandlerthreadrunhandlerthreadjava600831 101823139 wpackageparser 93 caused by javautilzipdataformatexception data error0831 101823139 wpackageparser 93 at javautilzipinflaterinflateimplnative method0831 101823139 wpackageparser 93 at javautilzipinflaterinflateinflaterjava2550831 101823139 wpackageparser 93 at javautilzipinflaterinputstreamreadinflaterinputstreamjava1880831 101823139 wpackageparser 93 14 more0831 101823149 epackageparser 93 package ukcooketchupblanketsquare has no certificates at entry reslayoutmainxml ignoring0831 101823269 ddalvikvm 93 gc explicit freed 5970 objects 337960 bytes in 107ms0831 101824729 iinstallaprogress20453 finished installing ukcooketchupblanketsquaremany thanks for your helpedit 02092010i have modified the mainxml file again by removing pretty much all the whitespace it still does not install but is not quite the same error it is claiming there is a zip file error although i notice that certificates do appear further down the list if this is not something i am obviously doing wrong would it be better if i raised on android developers mailing list0902 1732819 wpackageparser 93 exception reading dataappvmdl73692tmp0902 1732819 wpackageparser 93 javaioioexception0902 1732819 wpackageparser 93 at javautilzipinflaterinputstreamreadinflaterinputstreamjava2070902 1732819 wpackageparser 93 at javautilzipzipfilezipinflaterinputstreamreadzipfilejava4320902 1732819 wpackageparser 93 at javaiofilterinputstreamreadfilterinputstreamjava1300902 1732819 wpackageparser 93 at orgapacheharmonyluniutilinputstreamhelperreadfullyandcloseinputstreamhelperjava1740902 1732819 wpackageparser 93 at javautiljarjarfilereadmetaentriesjarfilejava3600902 1732819 wpackageparser 93 at javautiljarjarfileinitjarfilejava2370902 1732819 wpackageparser 93 at javautiljarjarfileinitjarfilejava2180902 1732819 wpackageparser 93 at androidcontentpmpackageparsercollectcertificatespackageparserjava4710902 1732819 wpackageparser 93 at comandroidserverpackagemanagerserviceinstallpackagelipackagemanagerservicejava59610902 1732819 wpackageparser 93 at comandroidserverpackagemanagerserviceaccess2100packagemanagerservicejava1380902 1732819 wpackageparser 93 at comandroidserverpackagemanagerservice5runpackagemanagerservicejava48190902 1732819 wpackageparser 93 at androidoshandlerhandlecallbackhandlerjava5870902 1732819 wpackageparser 93 at androidoshandlerthispatchmessagehandlerjava920902 1732819 wpackageparser 93 at androidoslooperlooplooperjava1440902 1732819 wpackageparser 93 at androidoshandlerthreadrunhandlerthreadjava600902 1732819 wpackageparser 93 caused by javautilzipdataformatexception data error0902 1732819 wpackageparser 93 at javautilzipinflaterinflateimplnative method0902 1732819 wpackageparser 93 at javautilzipinflaterinflateinflaterjava2550902 1732819 wpackageparser 93 at javautilzipinflaterinputstreamreadinflaterinputstreamjava1880902 1732819 wpackageparser 93 14 more,['android'] +83532,hibernate saving user model to postgres i am using postgres via hibernate annotations but it seems to be falling over dealing with a user object120916442 error schemaexport unsuccessful create table user id bigserial not null password varchar255 username varchar255 primary key id120916442 error schemaexport error syntax error at or near userif i run the sql manually i have to put quotes around the table name as user seems to be a postgres keyword but how can i convince hibernate to do this itselfthanks in advance,['java'] +83556,sending and receiving data over a network using tcpclient i need to develop a service that will connect to a tcp server main tasks are reading incoming messages and also sending commands to the server in ten minutes like a synchronize command for example i used the tcpclient object as shown belowtcpclient tcpclient new tcpclienttcpclientconnectx 9networkstream tcpclientgetstreamclientstreamreader new streamreadernetworkstreamclientstreamwriter new streamwriternetworkstreamwhiletrue clientstreamreaderreadalso when i need to write out something in any method i use clientstreamwriterwritexis this usage correct or is there a better way,['c#'] +83565,sources of nondeterminism my supposedly deterministic program produces one of a few slightly different outputs on different runs the input compiler and computer are unchanging i am not sure which output is right because it always looks reasonablebesides a stray call to rand how could this be possible,['c++'] +83568,how can i trigger ajax error callback on success callback i am looking for a way to trigger ajax error in success callback i have tried to explain my problem code belowajaxurl requesturldata postdatatype postsuccess functionresponse ifresponsesuccess do something else request workflow fails in this case i have to trigger this ajax requests error callback error function do something on error casedatatype json,['jquery'] +83583,how do i set a value in ckeditor with javascript i am wondering how i can set a value in ckeditor using javascripti have tried the following but neither of them workdocumentform nametextarea namevaluedatatextareaidvaldatahowever both these work without the editor applied is there a way i can do this with the editor,['javascript'] +83585,how to create the histogram of an array with masked values in numpy in numpy 141 what is the simplest or most efficient way of calculating the histogram of a masked array numpyhistogram and pyplothist do count the masked elements by defaultthe only simple solution i can think of right now involves creating a new array with the nonmasked valuehistogramm arrm arrmaskthis is not very efficient though as this unnecessarily creates a new array i would be happy to read about better ideas,['python'] +83597,why does a silverlight textbox use r for a newline instead of environmentnewline rn in silverlight if a textbox acceptsreturn all newlines are r even though environmentnewline is rn why is this wpf has rn as newline for textbox,"['c#', '.net']" +83603,html how to define a default value for input typetext without using attribute value i need to give a default value for input typetext field as followsinput typetext size32 value namefee there is one way to give this default value as i knowinput typetext size32 value10 namefee here is the question is it possible that i can set the default value without using attribute valueas i know if i set the enter the value 10 manually and then view the source through web browser the value is still empty so i think there may be a method that i can usethank you,['html'] +83604,get notified when something is added to nspasteboard in my application i want to get notified if something is added into the nspasteboard if i copy an text from any other program i want my application to know about itsomewhere i read it cannot be done that way i should create a timer and check the content of the nspasteboard myselfis this the way to do or are there any kind of notifications,['objective-c'] +83607,string manipulation vs regexps we are often told that regexps are slow and should be avoided whenever possiblehowever taking into account the overhead of doing some string manipulation oneself not talking about algorithm mistakes this is a different matter especially in php or perl maybe java what is the limit in which case can we consider string manipulation to be a better alternative what regexps are particularly cpu greedyfor instance for the following in c java php or perl what would you recommendthe regexps would probably be fastersabcdefg or a whileiindexabcx0 y substr based solutionsdng or a scanning algorithmbut what aboutan email validation regexps0wxyxy27ugwouldnt a handmade and specific algorithm be faster while longer to writeedit the point of the question is to determine what kind of regexp would better be rewritten specifically for a given problem via string manipulationedit2a common implementation is perl regexp for instance in perl that requires to know how they are implemented what kind of regexp is to be avoided because the implementation will make the process lengthy and ineffective it may not be a complex regexpedit july 2011 based on commentsi am not saying all regexps are slow some particular regexps patterns are known to be slow due to the particular processing their and due to their implementationin recent perl php implementations for instance what is known to be rather slow and should be avoidedthe answer is expected from people who did already their own research profiler and who are able to provide a kind of general guidelines about what is recommendedto be avoided,"['java', 'php']" +83623,reference spring properties file using path relative to config file i am moving properties from inside my spring config file to a separate properties file this is included in the config file withbean classorgspringframeworkbeansfactoryconfigpropertyplaceholderconfigurer property namelocation valuefilepropertiesconfig modeserviceproperties beanas it stands the location of the properties file is relative to the current working directory of the server processthis creates the requirement that the process must be started from a specific working directory and even worse allows for the admittedly remote possibility that it could pick up an entirely different properties file for example if it was started with the working directory set to an older version of the servicei would like to reference the properties file using a path that is relative to the directory containing the config filelooking at filesystemresource it seems createrelative might be what i need but i cannot figure out how to use it in the config filethankssteve,['java'] +83635,scoping in python for loops i am not asking about pythons scoping rules i understand generally how scoping works in python for loops my question is why the design decisions were made in this way for example no pun intendedfor foo in xrange10 bar 2printfoo barthe above will print 92 this strikes me as weird foo is really just controlling the loop and bar was defined inside the loop i can understand why it might be necessary for bar to be accessible outside the loop otherwise for loops would have very limited functionality what i do not understand is why it is necessary for the control variable to remain in scope after the loop exits in my experience it simply clutters the global namespace and makes it harder to track down errors that would be caught by interpreters in other languages,['python'] +83645,installing c windows service on windows 7 i have a batch file that i have been using to install my c windows services for awhile now never had a problem until windows 7 i have attempted to run the batch file with administrator privileges i have attempted to run the command prompt with admin privs navigate to the windows service exe and run installutil there still does not workafter reading some other suggestions i tried moving my files out of the bin folder and running them from another location but that also did not workthe batch file looks like thisecho offrem the following directory is for net 20set dotnetfx2systemrootmicrosoftnetframeworkv2050727set pathpathdotnetfx2echo installing ieppams win serviceecho installutil i ieppams winservice1exeecho echo doneand i have a install log file that i dump info to if i just double click the bat file i getrunning a transacted installationbeginning the install phase of the installation see the contents of the log file for the cusersjustindesktopservice testieppams winservice1exe assemblys progress the file is located at cusersjustindesktopservice testieppams winservice1instalogan exception occurred during the install phase systeminvalidoperationexception cannot open service control manager on computer this operation might require other privileges the inner exception systemcomponentmodelwin32exception was thrown with the following error message access is deniedthe rollback phase of the installation is beginning see the contents of the log file for the cusersjustindesktopservice testieppams winservice1exe assemblys progress the file is located at cusersjustindesktopservice testieppams winservice1instalogthe rollback phase completed successfullythe transacted install has completedwhen i run the bat file with admin privileges nothing is written to the log file and the service is still not installedany thoughts is there a new way to install services in windows 7,"['c#', '.net']" +83646,working on large javascript applications our file structures is pretty good organizing functionality in separate folders my question is how do others work on applications that involves upwards of 500 javascript files we have written a maven plugin to concatenate these files together also runs yui compressor however this involves 310seconds of compiling for every changeis this step necessary for organization of a large application i feel like a well structured html file pulling in all these resources would save me 45minutes every day,['javascript'] +83647,why are jquerys callback arguments inconsistent a common pattern within jquery is a method that takes a callback which is passed an element of an array and its index within that array however it seems completely random which argument comes first for example from the jquery docs at jqueryeach collection callbackindexinarray valueofelement each functionindex element jquerymap array callbackelementofarray indexinarray map callbackindex domelement jquerygrep array functionelementofarray indexinarray invert filter functionindex in three cases jqueryeach each map the index comes first in the other two jquerygrep jquerymap the element comes first i know the api is now set but it seems like a gross inconsistency to meis there a pattern i am missing or is this just random should this be fixed or should i just shut up and memorize them,['jquery'] +83652,lauching app with url via uiapplicationdelegates handleopenurl working under ios 4 but not under ios 32 i have implemented uiapplicationdelegatesapplicationdidfinishlaunchingwithoptionsandapplicationhandleopenurlaccording to specification ie applicationdidfinishlaunchingwithoptionsreturns yes andapplicationhandleopenurl opens the url the code works under ios 4 in both cases ie when the app is launched and when it becomes active from suspended state however the code does not work under ios 32,"['iphone', 'ios']" +83657,rails 235 i18n monthday name translation problem my configlocalesplyml file sampled from herepl date day names niedziela poniedziaaek wtorek aroda czwartek piatek sobota month names styczea luty marzec kwieciea maj czerwiec lipiec sierpiea wrzesiea paaodziernik listopad grudzieain scriptconsolei18nlocale pl pltimenowstrftimea b tuesday augustwhy or put it another way how can i get translated month names i will also note that the locale file is definitely read as it includes a bunch of other translations which all work,['ruby-on-rails'] +83658,where do i put weblogicapplicationxml in my maven 2 project where do i put weblogicapplicationxml in my maven 2 project so that maven places it in meta inf in the target ear artifact,['java'] +83659,file upload progress bar possible duplicateupload progress bar in php can anyone suggest a good and easy way to include the file upload progress bar while uploading a file i know it would be a mix of javascript php please suggest one,"['php', 'javascript', 'html', 'css']" +83660,utility to unzip an entire archive to a directory in java i would like to do something like this in my programfile zipfile file destdir imaginaryziputilityunzipalltozipfile destdiri cannot possibly be the first to do this from a program where do i find a utility method like above i tried to look at apache commonsio but nothing there so where should i look,['java'] +83670,aspnet mvc html helper methods for new html5 input types html5 appears to support a new range of input fields for things such asnumbersemail addressescolorsurlsnumeric range via a sliderdatessearch boxeshas anyone implemented htmlhelper extension methods for aspnet mvc that generates these yet it is possible to do this using an overload that accepts htmlattributes such ashtmltextboxformodel modelfoo new typenumber min0 max100 but that is not as nice or typesafe ashtmlnumericinputformodel modelfoo min0 max100,['.net'] +83695,android how to video record upload transcode download play i am researching the development of an android 22 appservice that will enable users to record short i do emphasize short 30seconds video on their phones and then upload that video http to a server that will then transcode the video to other formats that same user can download videos from other android users and play themnow i get a bit lost with everyones recommended approaches to all the issues in doing something like this because i have not seen any ask this in a cohesive context ideally i would like a non commercial solution to this as in no vendorservice being needed for the the video hostingtranscoding but feel free to include those as a recommendation i have marked this as a wiki as i know many like to use youtube and vimeo for the middle layer in all thisthe questions arewhat server technologies do you recommend for hosting and transcoding what technology do you recommend for streaming the video it would be nice to offer a high and low quality encoding depending on the users network connectionwhat video format and software do you recommend for converting the uploaded video on the server to be viewable later by other android ownersim assuming it is bad to do any transcoding on the phone prior to upload batteryproc issues but if i am wrong with that assumption what do you recommendsome things that may help youthe video will only need to render on an android device and in the future in a webkit html5 browserbandwidth isnt cheap even with numerous 30 second videos so a good mix of video quality and video file size is important streaming if needed to ensure quality vs downloadthis is for android 22 devices with a video camera of course and medium to high density screen of 800x400 minopen source solutions server to receive the uploads code to do the transcoding server to do the streaming are preferred but not requiredcdns are an option but i do not think that really figures in to the picture right now,['android'] +83696,can i overload an operator in objectivec is it possible to override operator use in objectivecfor examplemyclassinstance myclassinstancecalls a custom function to add the two,['objective-c'] +83704,using annotation to ensure that value returned by method is not thiscarded string in java is immutable the following snippet is broadly speaking wrongstring s hello worldstouppercase wrongsystemoutprintlns still hello worlddespite this being wrong the code compiles and runs perhaps to the confusion of many beginners who must either be told what the mistake is or to find out for themselves by consulting the documentationreading the documentation is an essential part of understanding an api but i am wondering if this can be supplemented by additional compiletime checks in particular i am wondering if perhaps javas annotation framework can be used to enforce that the value returned by certain methods are not ignored api designerslibrary authors would then use this annotation in their methods to document which return values should not be ignoredonce the api is supplemented with this annotation or perhaps another mechanism then whenever a user writes a code such as above it would not compile or do so with a stern warningso can this be done and how would you go about doing something like thisappendix the motivationit seems clear that in the general case java should allow return values of methods to be ignored the returned values of methods like listadd always true systemsetproperty previous value can probably be safely ignored most of the timeshowever there are also many methods whose return values should not be ignored doing so is almost always a programmer error or otherwise not a proper usage of the api these includes things likemethods on immutable types eg string biginteger etc that return the result of operations instead of mutating the instance it is invoked onmethods whose return value is a critical part of its behavior and should not be ignored but people sometimes do anyway eg inputstreamreadbyte returns the number of bytes read which should not be assumed to be the entire length of the arraycurrently we can write codes that ignores these return values and have them compile and run without warning static analysis checkersbug findersstyle enforcersetc can almost certainly flag these as possible code smells but it would seem to be appropriateideal if this can be enforced by the api itself perhaps through annotationsit is almost impossible for a class to ensure that it is always used properly but there are things it can do to help guide clients to proper usage see effective java 2nd edition item 58 use checked exceptions for recoverable conditions and runtime exceptions for programming errors and item 62 document all exceptions thrown by each method having an annotation that would enforce clients to not ignore return values of certain methods and having it enforced by the compiler at compiletime either in the form of errors or warnings would seem to be in line with this ideaappendix 2 snippetthe following is a preliminary attempt that succinctly illustrates what i want to achieveinterface unthiscardable attachable to methods to indicate that itsreturn value must not be thiscardedpublic class unthiscardabletest public static unthiscardable int f return 42 public static void mainstring args f what do i have to do so this generates compilation warningerror systemoutprintlnf this one would be fine the above code compiles and runs fine as seen on ideonecom how can i make it not so how can i assign the semantics i want to unthiscardable,['java'] +83705,c closure hack is there any problem with such closure implementation stolen from python hack void functionint value struct closure closureint v value value value private int value closure cupon further investigation it appears in member functions local variables can not be used as default values but object variables can,['c++'] +83706,android change sdk version in eclipse unable to resolve target androidx i developed an android aplication against 21 sdk since then i have reinstalled eclipseandroid sdk with the new install i want to upgrade the dependancy of the android application to 22 sdk because i dont want 21 installed on my machine is this possible i am getting the following error from eclipse20100831 181832 androidapplication unable to resolve target android7,['android'] +83707,draggables and resizables in svg i want to make an svg element path rect or circle be able to be draggable and give it resize handlesbut unlike html dom not all elements have an upper left hand corner xy coordinate and a width and height for a box surrounding the content this makes it inconvenient to make a generic resize or drag procedureis it a good idea to have each path or circle be drawn inside its own svg object to give me a box to play withhow is draggableresizable typically implemented in svg,['javascript'] +83715,replicate the functionality of javas patternquote in a javascript regexp in java you might try to make a regular expression that would match the url stackoverflowcom using patterncompilestackoverflowcom but this would be wrong because the has special meaning in regular expressions the easiest way to fix this is to write patterncompilepatternquotestackoverflowcom which comes out to patterncompileqstackoverflowcome which quotes the entire string i want to do the same thing in javascript but javascripts regular expressions do not assign any meaning to q and e and it does not look like there is a javascript equivalent so i am not sure how to go about it my first thought see my answer below is to just put a backslash before any character that has a special meaning in a javascript regex but this seems potentially errorprone and i suspect that someone might know of a better waythis is for a firefox extension so mozillaspecific solutions are okay,"['java', 'javascript']" +83720,cache key causes error negating the minimum value of a twos complement number is invalid this is one of the strangest errors i have ever seeni am doing a very simple call to return values from the httpruntime cache the call isreturn httpcontextcurrentcachecachekeyif it returns null that is fine i check if the returned value is null and act accordingly i have been using this call for a long timerecently for some reason when cachekey is set to this exact valuetopic gridselectall5null2010083120publisheddesc51a systemoverflowexception is thrown negating the minimum value of a twos complement number is invalidnothing about the call associated code or server has changed if the cachekey has slightly different characters it works perfectly fine for instance this cachekey returns null without throwing any exceptiontopic gridselectall5null20100831210publisheddesc51notice the only difference between those two strings is the time characters 2010083120 versus 20100831210why the hell would that make any difference and why now after all this timethe stack trace isoverflowexception negating the minimum value of a twos complement number is invalid systemmathabshelperint32 value 12753486 systemwebcachingcachemultipleupdatecachecachekey cachekey cacheentry newentry boolean replace cacheitemremovedreason removedreason object valueold 142 systemwebcachingcacheinternaldogetboolean ispublic string key cachegetoptions getoptions 122 myprojecthelperscachehelpergetdatastring cachedomain string cachekey in i have tried changing the cache call to use httpruntimecache instead ie httpruntimecachecachekey but that made no difference i know it is the same underlying cache provider but i thought maybe the different call would make a difference no dice,"['c#', 'asp.net']" +83754,ruby what is the easiest way to remove the first element from an array lets say i have an array 0 132 432 342 234what is the easiest way to get rid of the first element 0,"['ruby-on-rails', 'ruby']" +83759,download image from the site in netc i am trying to download images from the site the code which i am using is working fine while the image is available if the image it not available it is creating a problem how to validate availability of the imagecodemethod 1webrequest requestpic webrequestcreateimageurlwebresponse responsepic requestpicgetresponseimage webimage imagefromstreamresponsepicgetresponsestream errorwebimagesavedimagesbook filename jpgmethod 2webclient client new webclientstream stream clientopenreadimageurlbitmap new bitmapstream error parameter is not validstreamflushstreamcloseclientthisposeif bitmap null bitmapsavedimages filename jpgeditstream has the following statements length systemnetconnectstreamstrlength threw an exception of type systemnotsupportedexception long systemnotsupportedexception position systemnetconnectstreamstrposition threw an exception of type systemnotsupportedexception long systemnotsupportedexception readtimeout 30 intwritetimeout 30 int,"['c#', '.net']" +83767,start command windows and run commands inside i need to start the command window with some arguments and run more commands insidefor example launch a testcmd and run mkdiri can launch the testcmd with procestartinfo but i am not sure how to run further commands can i pass further arguments to the testcmd processhow do i go about thisunable to add comments to answer so writing hereandrea this is what i was looking for however the above code doesnt work for me i am launching a testcmd which is new command environment like razzle build environment and i need to run further commandspsifilename ctestcmdpsiarguments arg0 arg1 arg2psiredirectstandardinput truepsiredirectstandardoutput truepsicreatenowindow truepsiuseshellexecute falseprocess p new processpstartinfo psipstartpstandardinputwritelinedircresultstxtpstandardinputwritelinedircresults2txt,['c#'] +83785,format xml string what is the best way to format xml within a php classxml element attributesomethingelementxml element attributesomethingelementxml element attributesomethingelementxml eofelement attributesomethingelementeofi am pretty sure it is the last one,['php'] +83799,matching an empty input box using css how do i apply a style to an empty input box if the user types something in the input field the style should no longer be applied is this possible in css i tried thisinputvalue,['css'] +83800,c from a javaview i must have missed a few things before anything let me first clarify that the below thoughts are purely my personal opinions and due to my limited knowledge i have no intention whatsoever to say that c is not cool i have been programming c for like a year and i think it really has some cool features nevertheless i feel a bit empty and thisappointed as i did not really learn any mindchanging things from c from the standpoint of a person who happens to have previously learned java as the 1st language according to the many posts i have read people prefer c as it is faster to a programmer like me who have not programmed timecritical applications before i have yet to have a chance to appreciate this so far what i have learned seems to me are all about syntaxes this is how we write a class in java and heres how to write it in c this is how to do inheritance in java and that is how to do in c and so on i know multiple inheritance is cool but to me not a mindchanging thing i think whats cool is to be able to answer why java did notcould not support multiple inheritance which is supposed to be more general than single inheritance somehow to me all are just syntaxes and my mind has not seemed to grow after coding c so far i think my problem it to write c programs with a javamind what i really want is as many persons suggest to change my ways of thinking after learning a new language i have yet to get to that with my c i can also write a couple of small python programs however i feel afraid to learn more about it as to me again it would be just learning a new syntax a new way of doing things that are just different without knowing the reasons i plan to learn c to really get to know things i think it would be a quite involving language let me know what you think and please give me some advice ps btw there is one specific question in c i want to confirm in c writing in the following way is not efficient if i am correct private a computeandreturna instead write it as private void computeandreturnaa aas in the first way the returned values are copied when we assign b compute and introduce some inefficiencies in java i guess the 1st way is clear in meaning and okay in efficiency as it passes things by reference,"['java', 'c++']" +83801,java code to convert country codes alpha2 in to alpha 3 ind using java is there a quick way to convert an alpha2 country code in or gb to the alpha3 equivalent ind or gbr i can get the alpha2 codes withstring codes javautillocalegetisolanguagesthat is not a problem actually my application reads in the alpha2 code but i need to output the alpha3 equivalent is there a similar way like above to get the alpha3 codesany suggestions,['java'] +83802,average timedelta in list i want to calculate the avarage timedelta between dates in a listalthough the following works well i am wondering if there is a smarter waydelta lambda last next next lastseconds next lastdays 86400 total sumdeltaitemsi1 itemsi for i in range1 lenitemsaverage total lenitems 1,['python'] +83814,how do i set mysql as the default database in rails 3 i started using rails 2 last april but stopped this june because i thought learning it when rails 3 was released would be more practical since a lot of it was completely refactored and restructured i used to work with ubuntu 1004 with sqlite3 as the default db but now i am using windows 7 and mysql 5 i already installed the gem adapter for mysql but to use it i still need to tweak databaseyml thanks,"['mysql', 'ruby-on-rails', 'ruby']" +83819,testing ef 40 with poco and t4 templates how mock context i am trying to create fake context accodring to as i can see there is an interface which exposes methods which returns iobjectset but t4 templates generates methods which returns objectset and there is no generated interface and on that page author adds interface to created context and it gives him way to create mock etcmy main goal is to use t4 templates to generate poco classes and create mockfake context to test my custom repositories is there any way to make it works without writing or changing t4 template how can i create mocks above context for iobjectset ist trivial if it is returning objectsets instead of iobjectsetsthx in advance,['c#'] +83838,javascript what does the caret operator do i have some javascript codescript typetextjavascriptdocumentreadyfunction calcularclickfunction var altura2 ddl alturaattrvalue1002 var peso ddl pesoattrvalue var resultado mathroundparsefloatpeso altura2100100 if resultado 0 resultadohtmlresultado imcshow scriptwhat does the caret operator mean in javascript,['javascript'] +83840,log4net does not write the log file i created a simple scenario using log4net but it seems that my appenders do not work because the messages are not added to the logfilei added the following to the webconfig fileconfigsections section namelog4net typelog4netconfiglog4netconfigurationsectionhandler log4net requirepermissionfalse configsectionslog4net appender namelogfileappender typelog4netappenderfileappender file valuedmydatadesktoplogfiletxt appendtofile valuetrue encoding valueutf8 layout typelog4netlayoutsimplelayout appender root level valueinfo appenderref reflogfileappender rootlog4netwithin the global asax file i addedilog logger logmanagergetloggertypeofmvcapplicationand within the application start methodloggerinfostarting the applicationwhat did i do wrongthanks in advance johannes,"['c#', '.net', 'asp.net']" +83850,serial keys what to do i have been reading some posts here and articles around the web but i cannot picture a serial keys based system for my applicationi read this one but i cannot turn the code into java and i am not very familiar with the terms eitherwhat possible insight can you give me on this ideally my application will be for sale but i do not expect it to be much popular i do not mind much if it gets cracked if i have users that appreciate the product and buy it but i want to avoid it to be easily cracked please be as specific as you can i am somewhat new to javathanks in advance,['java'] +83852,how to query a table in sqlalchemy i know how to query on a model now suppose there is a question modelclass questionbase tablename questions idcolumn user idcolumn now i can doquestion sessionqueryquestionfilter byuser id123onebut now i have a table not a model questionsquestions tablequestions basemetadata columnid columnuser id how to query it as what i do with modelssessionqueryquestionsfilter byuser id123onethis will report an errortraceback most recent call lastfile console line 1 in modulefile epython27libsitepackagessqlalchemy063py27eggsqlalchemyormquerypy line 851 in filter by for key value in kwargsiteritemsfile epython27libsitepackagessqlalchemy063py27eggsqlalchemyormutilpy line 567 in entity descriptor desc entityclass managerkeyattributeerror nonetype object has no attribute class managerbutsessionqueryquestionsallis okis filter by only work for models how can i query on tables,['python'] +83854,c protected abstract virtual base pure virtual private destructor so i found this quote today can anyone explainif you think c is not overly complicated just what is a protected abstract virtual base pure virtual private destructor and when was the last time you needed one a tom cargill,['c++'] +83861,mysql join the most recent row only i have a table customer that stores a customer id email and reference there is an additional table customer data that stores a historical record of the changes made to the customer ie when there is a change made a new row is insertedin order to thisplay the customer information in a table the two tables need to be joined however only the most recent row from customer data should be joined to the customer tableit gets a little more complicated in that the query is paginated so has a limit and an offsethow can i do this with mysql i think i am wanting to put a thistinct in there somewherethe query at the minute is like thisselect concattitle forename surname as namefrom customer cinner join customer data d on ccustomer iddcustomer idwhere name like smith limit 10 20additionaly am i right in thinking i can use concat with like in this wayi appreciate that inner join might be the wrong type of join to use i actually have no clue what the difference is between the different joins i am going to look into that now,"['sql', 'mysql']" +83876,why should thispose be nonvirtual i am new to c so apologies if this is an obvious questionin the msdn thispose example the thispose method they define is nonvirtual why is that it seems odd to me i would expect that a child class of an ithisposable that had its own nonmanaged resources would just override thispose and call basethispose at the bottom of their own methodthanks,"['c#', '.net']" +83889,converting an int array to a string array so i have this list of ints it could be a vector int listinteger whatever my goal though is to sort the ints and end up with a string how the int array starts out as is up in the airex start with512113end with string 123511is there anyway to do this without a for loop i have a for loop now for collecting the ints i would rather skip doing another for loop,['java'] +83898,why call baseonstop when windows service is stopped i am creating a cnet windows service and am wondering if you always have to call baseonstop in the services onstop method and whyprotected override void onstop threadrunning false thisexitcode 0 baseonstop,['c#'] +83900,wix t4 no custom tool option i want to generate a fragment using t4 but after adding a tt file to the wix project there is no custom tool option for this file and there is no menu item run custom tool when right clicking on the tt file is there a hack for this i am using vs 2010 and latest wix 35,"['c#', '.net']" +83903,determining paused state of quartz trigger is there a way to determine if a specific trigger in quartz is in paused statei know of the getpausedtriggergroups method on scheduler but there does not seem to be a way to figure out the paused state of a particular trigger for a particular jobdetailany friendly suggestions,['java'] +83918,how to remove the borders in jinternalframe i was able to remove the title bar from the jinternalframe but i do not know how to remove the borders,['java'] +83928,php sql select where like search item with multiple words i have a select where like query for a seach form which is as followsphp bucketsearch sanitizeone postbucketsearch plainbucketsearch strip word htmlbucketsearch ifisset postsearch resultmysql query select from buckets where bucketname like bucketsearch order by bucketname else resultmysql query select from buckets order by bucketname my problem is that if someone searches for instance for apple and pear i do not get any results that contain any of the words i can only make it return results well 1 result with all the words in it can anyone help me make this search a bit more versitle thanks in advance,"['php', 'sql', 'mysql']" +83931,why are c interface methods not declared abstract or virtual c methods in interfaces are declared without using the virtual keyword and overridden in the derived class without using the override keywordis there a reason for this i assume that it is just a language convenience and obviously the clr knows how to handle this under the covers methods are not virtual by default but are there other technical reasonshere is the il that a derived class generatesclass example ithisposable public void thispose method public hidebysig newslot virtual final instance void thispose cil managed code size 2 0x2 maxstack 8 il 0 nop il 01 ret end of method examplethisposenotice that the method is declared virtual final in the il,['c#'] +83933,mysql how to get exact difference of hours between two dates i will illustrate what i would like to get in the following example20100901 030 20100901 0010using timediff we get 2 as a result this means it is not considering the 50 minutes leftin this case what i would like to get is 50 minutes 60 083 period therefore the result should be 283 and not 2,"['sql', 'mysql']" +83937,promote to custom widget in a namespace i have mycustomwidget in a namespace mynamespacenamespace mynamespace class mycustomwidget public qwidget how do i promote a qwidget to mycustomwidget in my ui form it does not seem to accept a custom namespace,['c++'] +83941,decompress gzip string in java i can find plenty of functions that let you decompress a gzip file but how do i decompress a gzip stringi am trying to parse a http response where the response body is compressed with gzip however the entire response is simply stored in a string so part of the string contains binary charsi am attempting to usebyte responsebodybytes responsebodygetbytesbytearrayinputstream bais new bytearrayinputstreamresponsebodybytes gzipinputstream gzis new gzipinputstreambaisbut that just throws an exception javaioioexception not in gzip format,['java'] +83954,c passing function as argument i have written a function in c that does a numerical differentiation it looks like thispublic double diffdouble x double h 01 return functionx h functionx hi would like to be able to pass in any function as inpublic double diffdouble x function f double h 01 return fx h fx hi think this is possible with delegates maybe but i am not sure how to use themany help would be greatly appreciatedthanks ash,['c#'] +83965,htmlactionlink with a specified html id i would like to give the like generated with an htmlactionlink an html id so i can change the css depending on where i am i have a masterpage with a set of links and i would like to thistinguish the active tab with jquery changing the css of that active idright now i am using htmlactionlinksome view index controllerit generatesa hrefcontrollersome viewai would like to generatea idsomething hrefcontrollersome viewais that possible i have tried htmlactionlinksome view index controller new idblahblabut that generatesa hrefcontrollerlength5some viewa,['css'] +83973,converting a 2d numpy array to a structured array i am trying to convert a twodimensional array into a structured array with named fields i want each row in the 2d array to be a new record in the structured array unfortunately nothing i have tried is working the way i expecti am starting with myarray numpyarrayhello253world362 print myarrayhello 25 3 world 36 2i want to convert to something that looks like this newarray numpyarrayhello253world362 dtypecol1s8col2f8col3i8 print newarrayhello 25 3l world 3601 2lwhat i have tried newarray myarrayastypecol1s8col2f8col3i8 print newarrayhello 00 0l 25 00 0l 3 00 0l world 00 0l 36 00 0l 2 00 0l newarray numpyarraymyarray dtypecol1s8col2f8col3i8 print newarrayhello 00 0l 25 00 0l 3 00 0l world 00 0l 36 00 0l 2 00 0lboth of these approaches attempt to convert each entry in myarray into a record with the given dtype so the extra zeros are inserted i cannot figure out how to get it to convert each row into a recordanother attempt newarray myarraycopy newarraydtype col1s8col2f8col3i8 print newarrayhello 17219343871178711e317 51l world 17543139673493688e317 50lthis time no actual conversion is performed the existing data in memory is just reinterpreted as the new data typethe array that i am starting with is being read in from a text file the data types are not known ahead of time so i cannot set the dtype at the time of creation i need a highperformance and elegant solution that will work well for general cases since i will be doing this type of conversion many many times for a large variety of applicationsthanks,['python'] +83983,get an elements id is there another way to get an elements idobjgetattributeid,"['javascript', 'html']" +83985,simple php long polling chat script too simple im working on a simple chat app probably 10 to 20 users per roomthe script that queries the database for new messages looks too simple for all the request it will be gettingbelow is the block of code that loops for new messages the rest of the script is just getting the variables construction of the query and the json response objectsleeptime 1 secondsdata timeout 0query database for datawhiledata and timeout 10 data getquerysql ifdata no new messages on the chat flush wait for new messages sleepsleeptime timeout 1 else break the block above will query the database for new messages every second for 10 seconds if after the 10 seconds there are no new messages it will notify the browser the browser waits 5 seconds and then sends another request to get new messageshowever if the script finds new messages the browser will request more new messages instantly as soon as it gets the response with the new messages from the serverthis process goes on and onso how can i optimize this process any furtheris this as good as it getsis working fine on my local server but im afraid that just a few users could overload a live servershared host with all the requests and the loopings here is live demo you can check with firebug,['php'] +83999,python matplotlib memory not being released when specifying figure size i am using matplotlib to generate many plots of the results of a numerical simulation the plots are used as frames in a video and so i am generating many of them by repeatedly calling a function similar to this onefrom pylab import def plot densityfilenameitpsi na figurefigsize86 imshowabspsi na2origin lower savefigfilename 04dpngi clfthe problem is that the memory usage of the python process grows by a couple of megabytes with every call to this function for example if i call it with this loopif name main x linspace6e66e6128endpointfalse y linspace6e66e6128endpointfalse xy meshgridxy k 10 omega 200 times linspace0100e3100endpointfalse for it in enumeratetimes psi na sinkxomegat plot densitywavefunctionitpsi na print ithen the ram usage grows with time to 600mb if however i comment out the line figurefigsize86 in the function definition then the ram usage stays steady at 52mb 86 is the default figure size and so identical images are produced in both cases i would like to make different sized plots from my numerical data without running out of ram how might i force python to free up this memoryi have tried gccollect each loop to force garbage collection and i have tried f gcf to get the current figure and then del f to delete it but to no availi am running cpython 265 on 64 bit ubuntu 1004,['python'] +84020,how to use sharedpreferences in android to store fetch and edit values i want to store a time value and need to retrieve and edit it how can i use sharedpreferences to do this,['android'] +84030,free build servers for net i have got the question are there any free build servers for net applications we are starting project as remotely working team and right now we are searching for such solution as far as it is an academic project we do not have funds to buy server and run ccnet on it are there any charge free solutions or at least cheap onesi am asking rather about the service on the internet not software solution,"['.net', 'asp.net']" +84031,difference between jqtouch and jquery mobile what is the difference between jqtouch jquery mobile framework are they related other than being both based on jquery do they have the same goal edit jqtouch is now jqt,['jquery'] +84051,download images and save locally on iphone phonegap app i have already managed to save a web page xhtml successfully but i would also like to save the images and mp4 videos that are contained in it for further visualization in offline modei have got access to the ios filesystem so i save the html by obtaining the code through an ajax request and later saving it to a filei do not really know how to do the same with video and images i have a server to which i can send queries from my app so it shows exclusively the content i need to download with the optimal headers in case its necessary i just do not know how to download it from the client side javascriptthanks in advance for any help,"['javascript', 'iphone']" +84055,xslt generating html tags how to use an xml node value as an srcattribute for the tags i am still searching but i have not found yet the way to perform something like thisxslstylesheet version10xmlnsxsl some other templates xsltemplate matchimage img srcsrc attribute to be read from the xml filejpg xsltemplate xslstylesheetin my xml image tags the text value is the filename that should be inserted in the string src attribute to be read from the xml filejpg when processed by this xslt filehave you any idea to perform this,['html'] +84066,cd burning within an xbap hii have an xbap that needs to be able to burn cds when running from inside visual studio everything works okay however when running from a browser the imapi dll reports that the environment is not supported as soon as it tries to access the drivei am assuming this is coming down to permissioning i have a signed certificate which i have installed and the xbap is set to run as a full trust application although i am guessing that it cannot be or i wouldnt be having this problemcurrently this is all running on my local machine however eventually i want this to be deployed to a web server all users will already have the certificate installed on their clientsdoes anyone have any ideas as to what i have missed done wrongupdatei have tried creating a new test certificate which i have installed in my certificate store and then signed the xbap against it but it makes no differencereally could do with some ideas if anyone has anyfurther updatei have created a console application which is able to burn cds shelling out to this console application allows me to burn the cd from my xbap but not from inside the xbap itselfhowever this is really not what i want ideally i want to have all this contained within the xbap failing that is there a way to include the console application in the xbaps one click deploymentthanks,['c#'] +84085,protected keyword c i want to know what is the meaning of protected in c why we use it and the benefit of the keywordfor instanceprotected int currentcolorindexplease elaborate,['c#'] +84088,textview wrap around view i am trying to make my horizontal layouts take advantage of the room availablein an info showing activity i have a fact box followed by a large box of text i would like the infobox to float right similar to the following pictureis this possible using the android textview api,['android'] +84103,python how exactly can you take a string split it reverse it and join it back together again how exactly can you take a string split it reverse it and join it back together again without the brackets commas etc using python,['python'] +84108,hibernate criteria api join table problem i cannot use sorting on join tables let me explaini have three tables users roles and user rolesmy jpa entities are user userrole userrolepk roleuser userrole userrolepk role id pk user id name role name in fact the output that i want isselect from user roles your join users you on uid uruserid order by unameso i try to use hibernate criteria apicriteriaimpl criteria criteriaimpl sessioncreatecriteriauserroleclasscriteriaaddorderorderascpkusernamelist userroles criterialistthe error iscould not resolve property pkusername of modelsuserrolehow can i use criteria api on join tables,['java'] +84111,is it possible to show unicode characters in a html input typesubmit value a customer has a designer mockup of a form button that shows a right facing triangle character after the main text but i cannot seem to get this showing the offending markup is input typesubmit valueadd to basket 9654 this should look like add to basket if it renders in your browseris this possible or am i doing something wronga jquery workaround is acceptable as a hack too the page is html5 compliant maybe thatll helpthanks in advanceryanupdate the answers below are correct there was an easier way though i just copied the triangle out of this question and straight into me html editor no encoding neededthanks all,"['jquery', 'html']" +84112,meaning of operator in c if it exists i read this interesting line here in an answer by jon skeetthe interesting line is this where he advocated using a delegateloginfoi did something 0 actiongeneratedescriptionquestion is what is this operator i wonder i tried googling it but since it is made of symbols google could not be of much help really did i embarrassingly miss something here,"['c#', '.net']" +84120,how to get the selected index of a drop down i have a normal dropdown which i want to get the currently selected index and put that in a variable jquery or javascript jquery perferedselect nameccardsoption value0select saved payment methodoptionoption value1846test x1234optionoption value1962test2 x3456optionselect,"['javascript', 'jquery']" +84133,how do you use a json string or json object with jqgrid my jqgrid is work when my json data is in a static file but if i copy the data to a var and then try to load the var into the jqgrids url it does not showcan you pass a string into jqgridegthis worksfunction getjson var jsonfile entitywithchildrenjson return jsonfilereturning a file works finejsonmapjqgrid url getjson datatype jsonthis does notfunction getjson var json page1total10 records10 entities fieldsentity1 field1 11 fields field2 22 fieldsentity2 field3 33 fieldschildentity1 cfield1 1 return json doesnt workjsonmapjqgrid url getjson datatype json datatype jsonstringthis doesnt work either,['jquery'] +84143,writing an rss reader in java i am trying to write a basic rss reader for a class project our book shows an example by walking the dom tree is that a decent approach for an rss reader would i just ignore certain tags that are of uninterest to me and not to be used by the rss reader thanks,['java'] +84145,coreplot piechart slice color i am using core plot in one of my iphone projects is it possible to change the color for a selected slice in a pie chart using cppiechartdatasource cppiechartdelegate,['iphone'] +84170,merging overlapping ranges in php arrays i have an array in the following formatarray 0 array1 5 1 array4 8 2 array19 24 3 array6 9 4 array11 17where each item is a xtoy range what i would like to merge the overlapping ranges in the array to get something more like thisarray 0 array1 9 15 48 and 69 are overlapping so they are merged 1 array11 17 2 array19 24what would be the best way to accomplish this,['php'] +84174,thistinct difference between collect and each using arrays whats the main difference between collect and each preference some somecollect do x puts xsomeeach do x puts xend,['ruby'] +84188,checking that a list is not empty in hamcrest i was wondering if anyone knew of a way to check if a list is empty using assertthat and matchersbest way i could see just use junitassertfalselistisemptybut i was hoping that there was some way to do this in hamcrest,['java'] +84196,list assets in a subdirectory using assetmanagerlist my application has an assets directory in which i have dumped a bunch of text files i need to load at runtimei have a directory full of assets of a particular type ie assetssubdir and i want to load all of the files in this directory one at a timei have code like thisassetmanager assetmgr getassetsstring assetsiwant assetmgrlistsubdirforstring asset assetsiwant doassetythingasseti have tried a zillion different versions of the parameter to assetmgrlist and am not getting anywhereif i use i get back a list containing the assets directory and a few random other items meta inf for example if i pass any other string like assets or assets or assets or assets or mysubdir or mysubdir or assetsmysubdir or then i get back an empty arraythe documentation is unfortunately fairly incoherentdoes anybody know what the correct formula for that list parameter is,"['java', 'android']" +84201,bug in formclosingeventargsclosereason the requirements i am up againstabout 12 people are using this application but we only want to allow 4 to close the application through traditional methods altf4 file exit close if any other method is used taskmanager windowsshutdown or one of the allowed users close the application we need to perform some clean up closing out some connection channelsthe code i have used to satisfy said requirementsprivate void formclosingobject sender formclosingeventargs e if a user is allowed to close the application an empty file filename will be in the root directory of the application ifeclosereason closereasonuserclosing fileexistsfilename ecancel true return cleanupthe problemif a user not allowed to close attempts to close the application through traditional methods then attempts to close using task manager the closereason enum does not seem to reset itself thus causing task manager to pop the prompt to force close preventing the application from cleaning upthe questionis this a bug or am i missing something something that will reset the closereason after the formclosing event has been cancelled,['c#'] +84216,jquery heightwidth and thisplaynone i always thought elements that had thisplaynone css style returned 0 for height and widthbut in this examplehtmldiv idtarget stylethisplaynoneadivcssalerttargetheightthey do not how come i have seen 0 come back plenty of times in the past,"['jquery', 'css']" +84219,how to make a php extension i know you can technically make php extension just by making a php file and using require oncebut would it optimize the performance if you wrote an extension in c or cif so how would you make a helloworld for that,"['php', 'c++', 'c']" +84228,mysql unicode literals i want to insert a record into mysql that has a nonascii unicode character but i am on a terminal that does not let me easily type nonascii characters how do i escape a unicode literal in mysqls sql syntax,['mysql'] +84232,html form submit button confirmation dialog this is a general form codeform namesearch form action methodpostinput typetext namesearch text input typesubmit namesearch bt valuegoformis there a way could have a confirmation dialog saying yesno or confirmcancel etcone way i figured of dong is is with css layer and javascript and php that have a php isset chechk on the button and when set thisplay a div thisplayed with two buttons and onclickfunc js function of those buttons have a php variableflag set and then i can ifflag to continue or skip some codewell that is going to work and plus point is that i can have a well themed dialog box but i just wanna make my life easier,"['php', 'javascript']" +84235,mysql how to use trim in select query my table have set of records around 50 in the table i have column called username but some of username leading and trailing have the white space so am not getting exact order result because of white space so tell me how to use the trim in select query thanks,"['sql', 'mysql']" +84241,net enumerate winforms font styles i have been searching around for a way to list the valid font styles for a given font using the net framework even if i have to pinvoke gdi32 or some other api since not all fonts fall into the systemdrawingfontstyle enum values bold italic regular strikeout underline a perfect example of a font that does not fit the bill is segoe ui which is a truetype microsoft font with font styles of regular semibold light bold italic and bolditalic another example is arial which has regular narrow italic bold bold italic narrow bold narrow bold italic and narrow italicin windows 7 probably vista as well but i do not have a machine to check when you open explorer and browse to systemrootfonts you will see a column called font style which lists out all of the available styles for each font which tells me that there is definitely a way to do this at the very least through api callsultimately i am looking to enumerate the fontfamily list and then list out every font style for each family below is sample code for listing out all of the font families if anyone could provide assistance for listing the font styles available for each family i would appreciate it if i am going about this the wrong way i am definitely open to suggestionsdrawingtextinstalledfontcollection ifc new drawingtextinstalledfontcollectionforeach fontfamily ff in ifcfamilies consolewritelinefftostring something like this would be nice but afaik nothing similar exists foreach fontstyle style in ffstyles consolewritelinestyletostring,"['c#', '.net']" +84243,rails best practices for restful controller create and update methods ok i am trying to understand the best practices for the create and update methods for both html and xml formats the default code for a controller that the rails generator generates is a little unclear to mefor the create method given a good save the generator says to redirect towhatever for html and render xml whatever status created location whatever for xml given a bad save the generator says to render action new for html and render xml whatevererrors status unprocessable entity for xmlhowever for the update method given a good update the generator says to redirect towhatever for html and head ok for xmland given a bad update the generator says to render action edit for html and render xml whatevererrors status unprocessable entity for xmli understand this and it makes sense to me and works just fine but i have two questionsfirst for a successful create and update html format why redirect towhatever instead of render action show i understand the differences between redirect and render just more curious about which way you guys tend to do it and why it seems the redirect would be an unnecessary extra trip for the browser to makesecond why head ok upon successful update via xml but render xml whatever status created location whatever upon successful create via xml this seems inconsistent to me seems like a successful update via xml should be the same as a successful create via xml seems like you would need the newupdated object returned so you could test it how do you guys do it and why,['ruby-on-rails'] +84251,nested for loops using list comprehension if i had two strings abc and def i could get all combinations of them using two for loopsfor j in s1 for k in s2 printj khowever i would like to be able to do this using list comprehension i have tried many ways but have never managed to get it does anyone know how to do this,['python'] +84255,difference between this and this in jquery what is the fundamental difference between using this vs thisviewcommentsclickfunctionev returns the desired value alertthisgetattributeid gives an error sayin function is not defined alertthisgetattributeid returns the desired value alertthisattridwhat i thought was this will contain all functions that this has and morebut that does not seem to be the caseso what exactly is this and hw do i knw what functions are avaliable when im using it i knw i can get them through firebug but i would like to know if there any some other way some doc may be,['jquery'] +84274,craigslist automated posting api i was looking through craigslist bulk posting section and it requires an rss feed to be sent to a server to automatically post an add the site is found at posting interfacei have looked up and down for a sample of a php class but cannot find out anyone know of any class that exists thanks,['php'] +84275,difference between include and require in php is there any difference between them is using them a matter of preference does using one over the other produce any advantages which is better for security,['php'] +84280,rails 3 ssl deprecation i am upgrading an application to rails 300 and am wondering if the standard method for adding ssl has changed i vaguely remember demos indicating the router could now handle ssl though i am not sure if it was just for demonstration purposes i currently use the ssl requirement gem however it givesdeprecation warning using request uri is deprecated use fullpath instead called from ensure proper protocol at libraryrubygems18gemsl requirement010libssl requirementrb53also it appears to break when handling the new datamethod attributes for example link to logout user path method delete works fine when accessing from an ssl section of the application but fails attempts to render show action when followed from a nonssl section all actions in the user controller require ssl although i understand that the destroy action does not transmit secure data,['ruby-on-rails'] +84307,how do you enable touch interaction in core plot has anyone tried to add touch interaction to coreplot i am trying to implement custom layer to be able to draw a line on the chart which will show specific value and will draw itself in specified location when user touches chart area but i am not having any luck,['iphone'] +84313,how to work on the xampp mongodb in windows can any one let me know how to start working on the mongodb in xamppwindows with examples of applications,['php'] +84314,filter higher order function in c does c standard library andor boost have anything similar to the filter function found in functional languagesthe closest function i could find was stdremove copy if but it seems to be doing the opposite of what i want does boostlambda have any function to get a negated version of my predicate similar to not in haskell i could negate my predicate and use it with stdremove copy if thenplease note that i am not asking how to write filter function in c i am just asking whether standard library andor boost already provide such a functionthanks in advance,['c++'] +84318,merging two or more visual studio project into a one project i am working on a solution that contains bunch of projects i am going to refactor the solution by merging some of the projects togetheris there any tool or visual studio extension that helps me refactor my large solution by merging one or more projects into on projectof course this can be done manually but i am hoping for a more automated solution,['.net'] +84321,how to load different resx files based on some parameter i have an aspnet35 c aspx page that is internationalized in 10 different languagesthe page is very complex in its structured with dozens of nested views driven by a state machine patternedit i am using the metaresourcekey syntax in every asp control which allows to use declarative syntax for implicit resource expressionsi have been asked to brand the page based on some query string parameter branding will mean not just loading different css files but also having different text blurbs in all languagesis there an easy way to swap resx files without having to get resources manually for each of the hundreds of literals and images that i have on this pagein other words let us say i have the following resx filesbrand1 mypageaspxenusresxbrand1 mypageaspxdederesxbrand1 mypageaspxfrfrresxbrand2 mypageaspxenusresxbrand2 mypageaspxdederesxbrand2 mypageaspxfrfrresxmypageaspx will be looking for resx files named mypagexresxis there a way to load instead either the brand1xresx files or the brand2xresx based on some valuethanks in advance,"['c#', '.net', 'asp.net']" +84322,formatting code within notepad is there a keyboard shortcut to format code within notepad i am mainly working with html css and python codefor exampletitle block title endblock title link relstylesheet hrefmediastylecss typetextcss mediascreen headtohead title block title endblock titlelink relstylesheet hrefmediastylecss typetextcss mediascreen headi remember visual studio doing it with crtlkd and netbeans having the feature too but cannot find it within notepad if it can even do it,['html'] +84345,is there any benefit to declare a constant in a local scope in c is there any benefit to declare a local variable as const if i know that i would not be chaning its valuethanks,['c#'] +84351,measure code coverage only on new code we are looking for a creative way to measure code coverage on new code separate from existing code we have a large legacy project and want to start getting 90 coverage on any new functionality we would like a way to easily view a report that filters out any older code to make sure the new functionality is meeting our goal obviously still looking a increasing overall coverage on the project but need a nonmanual way to give us feedback on the new code activity we have this working for static analysis since we can look at the dates on the source files since cobertura is analyzing the class files they have new dates and this technique does not work any ideas stack java 15junit coberturahudson,['java'] +84352,publishing multiple ports with one service using jaxws 20 and webservice i want to create a soap service with multiple port types exposed where each port type has a separate interface i am trying to do this using jaxws 20exampleinterface a objecta getstring nameinterface b objectb getstring nameservice port a get port b getthe problem i am having is that an webservice is defined using a single classinterface so the only way i am able to set this up is having two separate services each service implemented by a separate class with a webservice annotationi would like to expose both ports using the same service to make it clear that both of them are part of the same api is this possiblereally what i am after is having some kind of nested namespace support in the wsdl so i can have the same methods in different namespaces i will have getsetdelete methods for different kinds of data next to each other but i would rather not put them all in the same big interface with getagetb and so on since i would like to be able to add new data types later on without forcing all the clients to regenerate from the new set of wsdls any tips on achieving this are welcome even if it means using another way of generating the wsdl from java code,['java'] +84374,how to write stereo wav files in python the following code writes a simple sine at frequency 400hz to a mono wav file how should this code be changed in order to produce a stereo wav file the second channel should be in a different frequencyimport mathimport waveimport structfreq 4400data size 40fname wavetestwavfrate 110250 framerate as a floatamp 640 multiplier for amplitudesine list x for x in rangedata size sine list xappendmathsin2mathpifreqxfratewav file waveopenfname wnchannels 1sampwidth 2framerate intfratenframes data sizecomptype nonecompname not compressedwav filesetparamsnchannels sampwidth framerate nframes comptype compnamefor s in sine list x write the audio frames to file wav filewriteframesstructpackh intsamp2wav fileclose,['python'] +84391,how to cancel scheduled job with delayed job in rails i am scheduling a job to run in say 10 minutes how to properly cancel this particular job without using any kind of dirty extra fields in model and so on is there any call to remove particular job or jobs related to specific model instance etc,"['ruby-on-rails', 'ruby']" +84402,jquery form submit my goal iswhen for is submitted a validation on form is made okan ajax is called to see that username and password do match okif they do not match thisplay an error okif they match then really submit the form not okinfact the trouble is i cannot submit the form since there is a jquery submit event on itfunction form1submit var usernameusernamevalvar passwordpasswordvalif usernamelength2 return falseif passwordlength2 return falsepostcheckphp username username passwordpassword functiondata if datako alertbad password return false else to be done here return falsefunction init form1submitfunction return form1submit documentreadyfunction init,"['javascript', 'jquery']" +84414,detect and suppress errors loading javascript file i want to source a javascript file from facebook usalljs the organization i work for has a firewall that blocks access to facebook it just goes to an html page that says access denied blah blah blah i want to be able to put a javascript src tag script srchttp script and detect and suppress the warnings when the browser tries to evaluate the html as javascriptanyone know how,['javascript'] +84420,typedef inheritance from a pure abstract base edit found duplicate i have whittled down some problem code to the simplest working case to illustrate the following my typedef in a pure abstract base class is not being inherited by the derived class in the code below i would like to inherit the system t typedef into the concretetemplatemethodinclude iostream pure abstract templatemethodtemplate typename t t analyzeruclass templatemethod public typedef t system t virtual void fn const system t t const 0template typename tclass analyzer public void templatedalgorithm const templatemethod analyzer t a const printf analyzertemplatedalgorithmn afnthis run the templatemethod void fn const printf analyzerfnn concrete templatemethodtemplate typename tclass concretetemplatemethod public templatemethod analyzert public typedef analyzert system t virtual void fn const system t t const printf concretetemplatemethodfnn tfn perform analyzers fn int main analyzer double a concretetemplatemethoddouble dtm atemplatedalgorithmdtm return 0this code compiles and runs as expected in the concretetemplatemethod the following is required and when removed causes compiler errorstypedef analyzert system tnote that the system t type is already typedefed in the base class however why must i include another typedef when inheritingi realize that i can qualify the typename of system t in the derived concretetemplatemethod by using typename templatemethod analyzert system t but that is a bit verbose and i would like to avoid having to retypedef to the base everytime i inherit and need to use that same system t is there a way around this that i can define in the base templatemethod,['c++'] +84421,show content in title when textoverflow css3 introduces textoverflow so you can hide overflowing text and even add ellipsesif the text is overflowing and hidden i would like to show it as a tooltip when hoveredthe easiest way to do this is to add the text to the title attribute of the element however that will make the text show whether it is overflowing or not i only want to show the tooltip when overflowedso if i had thisspansome text herespanspansome more text herespanand it rendered like thissome text heresome morethe first one would have no tooltip since there is no need and the second would have a tooltip that showedsome more text hereis there any way to set this up,"['jquery', 'html', 'css']" +84441,force flush on a gzipoutputstream in java we are working on a program where we need to flush force compress and send data a gzipoutputstream the problem is that the flush method of the gzipoutputstream does not work as expected force compress and send data instead the stream waits for more data for efficient data compressionwhen you call finish the data is compressed and sent over the output stream but the gzipoutputstream not the underlying stream will be closed so we cant write more data till we create a new gzipoutputstream which costs time and performancehope anyone can help with thisbest regards,['java'] +84447,marshal by bleedreferencevalue i have heard about marshal by reference marshal by bleed and marshal by value what exactly are the differences between these 3 i know that these are used when transporting data across appdomainsserialization but not much more,['c#'] +84453,youyube api watch private videos i have a website that has a draft mode someone can login and see what the site looks like to approve it before the public can see it i have youtube videos on an account that i put on private because i do not want the world to see them however i do want the people who login to the draft mode to be able to watch the private embeds is there a way i can use the youtube api and do it so the people can only see the videos and not really be logged in as that person so they cannot modify the video settings and not be able to stay signed in after leaving my webpage,['php'] +84469,what is the difference between split and explode the php manual for split saysthis function has been deprecated as of php 530 relying on this feature is highly thiscourageduse explode insteadbut i cannot find a difference between split and explode join has not been deprecated so what gives,['php'] +84477,whats the meaning of in a function call now i usually call a function that requires no arguments with like thismyfunction there is empty parensexcept in jquery calls where i can get away withfoobindclick myfunction no parensfine but recently i saw this comment here on soconsider using settimeoutmonitor 100 instead of settimeoutmonitor 100 eval is evil yikes are we really evaling a string here i guess i do not really understand the significance and implications of calling a function what are the real rules about calling and referring to functions,['javascript'] +84488,how to encode a wav to a mp3 on a android device i have simplified my question and offered a bountywhat options are there for compressing raw pcm audio data to a mp3 on a android devicemy original posti am creating a synthesiser on my android phone and i have been generating pcm data to send to the speakers now i am wondering if i can encode this pcm data as a mp3 to save to the sdcard the mediarecorder object can encode audio coming from the microphone into various formats but does not allow the encoding from programmatically generated audio dataso my question is is there a standard android api for encoding audio if not what pure java or ndk based solutions are there and can you recommend any of themfailing this i will just have to save my generated audio as a wav file which i can easily do,"['java', 'android']" +84491,comparing int with size t if i have a int and a size t variablecan i compare them likeint i1size t y2ifiydo somethingor i have to typecast one of them,['c'] +84495,using python with statement with tryexcept block is this the right way to use the python with statement in combination with a tryexcept blocktry with openfile r as f line freadlineexcept ioerror whateverif it is then considering the old way of doing thingstry f openfile r line freadlineexcept ioerror whateverfinally fcloseis the primary benefit of the with statement here that we can get rid of three lines of code it does not seem that compelling to me for this use case though i understand that the with statement has other usesedit is the functionality of the above two blocks of code identicaledit2 the first few answers talk generally about the benefits of using with but those seem of marginal benefit here weve all been or should have been explicitly calling fclose for years i suppose one benefit is that sloppy coders will benefit from using with,['python'] +84508,uitextview with syntax highlighting possible duplicateuitextview w syntax highlighting i have found a question on this already but it did not have a complete answer to it is there a framework or library that can do syntax highlighting in a uitextview specifically syntax highlighting and detection for objectivec on the iphonesome of my ideas of how to do thisnsattributedstring now available in ios 32 and greater but how would i put a nsattributedstring into a uitextviewuiwebview overlay it when the user finished editing and color the text with css stylesheets but how would i do this in a uiwebview giving it the text and then coloring it,"['iphone', 'objective-c']" +84520,writing a d d2 binding for existing c libraries i would really like to get more into d but the lack of good library support is really hindering me therefore i would like to create some d bindings for existing c libraries i would like to use i have never done any binding but it does not look too difficult eitheri am planning to do this for d2 not specifically d1 but if it could be for both even better i am using the dmd2 compilerwhat conventions should be used i noticed version statements aliases and regular constants function definitionswhat would be the difference between binding to a static library and thus linked against or a dynamic library is there any difference in the bindingfor binding a static library the dmd compiler does not seem to accept a or o files only lib and obj does this mean the libraries must be compiled with the dmc compiler as opposed to the gcc compiler and then linked through the dmd compilerif someone had a very short example of how a binding would be accomplished i would be great full currently i can compile c code with dmc link the object files and run functions from the c code in d however most c libraries just need a header file inclusion and need to be linked against in c i am uncertain how to make bindings that work for thatthanks,['c'] +84535,operating system from scratch i have been asked to choose a project for my operating system course at my university i was bubbled with the idea of making an operating system from scratch in python i have a few limitations i have only 3 months i want to do it in python i can put in say 2030 hours every week into it i want to know how feasible is the idea like how far can i go in building the same i would be very happy if i can get a basic version running something with a handful of very basic apps running is it possible with the given limitationsis there a book that can help me like a guideline need not be for python i just need a guide to tell me how i should go about making the osif the idea is not feasible can anyone tell me how much do i need to scale down my idea any help is much appreciated,['python'] +84537,is there a portable c compiler for windows i want to carry one in my flash drive and run it thanks,['c'] +84538,how best do i get to use openmp on mac os x 105 and ubuntu 104 i am looking at an opensource library dds a doubledummy bridge solver which in its latest release 211 adds some very useful multitasking functionality requiring either a windows system or openmp indeed that latest version would not even compile at all on a nonwindows system without full openmp support ubuntu 104 has a package available for an older version 119 which includes the python interface to the library pydds i contributed to upstream long ago but i would really like to use and contribute a python interface to the new functionality but for that i need a c compiler and supporting libraries that will give me openmp functionalityplus i need them on both ubuntu 104 and my good old intel macs which still run mac os x 105 to avoid losing compatibility with my good old powerpc macs but i am not holding out for a way to get openmp support on those powerpc macs too though of course i would just love to the intelbased ones would sufficei fully plan to hack as much as needed and contribute patches upstream of course once i have them working as i have long done on all open source code i have hacked on including dds itself in the past on dds itself pydds and any ancillary functionality for them but exactly because of that i would just love to avoid having to do a lot more preliminary hacking to get openmp support for c in the first place on the platforms i need it onso is there ideally anything i could just aptget install for ubuntu 104 and a thisk image or darwinport or whatever for mac os x 105 at least on intel processors that i could use to get started i am of course ready to buildfromsources patch sources etc as needed but i would much rather not have to if i can avoid it,['c'] +84539,how can i check if the content of a folder was changed i need a procedure that checks if new foldersfiles were added to a given selected folderi need this procedure to run upon application start up so the processing time at this stage is importanti guess i can make a log of current state log of the previous state sort and compare themfirst i need to know if there is another way second if there is no other way what is the best way to find difference between two lists of files paths both structure and algorithmsold statecfirstfolderadoccfirstfolderbdoccfirstfoldersecondfolderadoccfirstfoldersecondfolderbdocnew statecfirstfolderadoccfirstfolderbdoc cfirstfoldersecondfolderadoc cfirstfoldersecondfolderbdoc cfirstfoldersecondfoldercdoci am looking for cfirstfoldersecondfoldercdoc,['c#'] +84541,net image libraries what are some good image libraries for c mainly for things such as painting in layers or maybe a resource that can describe similar tasks,['c#'] +84545,gem update system is thisabled on debian error when i try to update rubygems by running gem update system i get this errorerror while executing gem runtimeerrorgem update system is thisabled on debian rubygems can be updated using the official debian repositories by aptitude or aptgetany idea what might be wrong and how i can fix it,"['ruby-on-rails', 'ruby']" +84548,whats the best way to check if the view is visible on the window whats the best way to check if the view is visible on the window i have a customview which is part of my sdk and anybody can add customview to their layouts my customview is taking some actions when it is visible to the user periodically so if view becomes invisible to the user then it needs to stop the timer and when it becomes visible again it should restart its course but unfortunately there is no certain way of checking if my customview becomes visible or invisible to the user there are few things that i can check and listen to onvisibilitychange it is for views visibility change and is introduced in new api 8 version so has backward compatibility issueonwindowvisibilitychange but my customview can be part of a viewflippers views so it can pose issuesondetachedfromwindows this not as usefulonwindowfocuschanged again my customview can be part of viewflippers views so if anybody has faced this kind of issues please throw some light,['android'] +84567,php include best practices question i have been learning syntax for php and practicing it i come from a net background so masterpages always made things pretty easy for me when it came to headers and footers so far i have a mainheaderphp and mainfooterphp which have my head menu and my footer html i created a mainbodyphp and at the top i put php include mainheaderphp and for the footer i put php include mainfooterphp this worked perfectly and made me smile because my pages all came together nicely the mainheader has my html and body and my mainfooter has my closing tags for those is this good practice,['php'] +84587,how to use dependency injection in zend framework currently i am trying to learn the zend framework and therefore i bought the book zend framework in action in chapter 3 a basic model and controller is introduced along with unit tests for both of them the basic controller looks like thisclass indexcontroller extends zend controller action public function indexaction thisviewtitle welcome placesfinder new places thisviewplaces placesfinderfetchlatest places is the model class that fetches the latest places from the database what bugs me here how should i test the indexcontroller in isolation as the reference to the places class is hardcoded i cant inject any stubs or mocks in indexcontrollerwhat i would rather like to have is something like thisclass indexcontroller extends zend controller action private placesfinder here i can inject anything mock stub the real instance public function setplacesfinderplaces thisplacesfinder places public function indexaction thisviewtitle welcome thisviewplaces thisplacesfinderfetchlatest the first code sample i posted is most definately not unit test friendly as indexcontroller cannot be tested in isolation the second one is much better now i just need some way to inject the model instances into the controller objectsi know that the zend framework per se has no component for dependency injection but there are some good frameworks out there for php can any be used together with zend framework or is there some other way to do this in zend framework,['php'] +84597,using some beans in filter bean class in my filter bean class i added some beans dependency with autowired annotation but in the method dofilter all my dependency beans have null public class facebookoauth implements filterautowiredprivate businesslogger loggerautowiredprivate iusersessioninfo usersessioninfoautowiredprivate facebookoauthhelper oauthhelperpublic void initfilterconfig fc throws servletexception nothing to dopublic void dofilterservletrequest sr servletresponse sr1 filterchain fc throws ioexception servletexception httpservletrequest req httpservletrequestsr httpservletresponse res httpservletresponse sr1 string code srgetparametercode if stringutilisnotblankstrcode string authurl thisoauthhelpergetauthurlcodethisoauthhelper is equal at null and other dependancy beans to could you help me in fact i do not use mvc notion on server side spring for my side client i use flex technology and blazeds servlet ton communicate with my serverso that is the reason i use the filter bean notion so how can i handle my session bean notion in my filter bean skaffmani implemented your idea so i update my applicationxml with bean idfacebookoauthhandler classcomxxfacebookoauthhandler bean classorgspringframeworkwebservlethandlersimpleurlhandlermapping property namemappings props prop keyfbauthfacebookoauthhandlerprop props propertybeanand my facebookoauthhandler class public class facebookoauthhandler extends abstractcontrollerautowiredprivate businesslogger loggerautowiredprivate iusersessioninfo usersessioninfoautowiredprivate facebookoauthhelper oauthhelperoverrideprotected modelandview handlerequestinternalhttpservletrequest request httpservletresponse response throws exception todo return nullbut this method handlerequestinternal is never called when my url is,['java'] +84608,default keyword in php what does the keyword default in php do there is no documentation on but i get an error when using it as a function name aunexpected t default expecting t stringawhat does it dowhere can i find information about it,['php'] +84610,difference before and after trigger in oracle can somebody explain difference between before and after trigger in oracle 10g with an example,['sql'] +84616,how to clear the screen with x1b2j how do we implement clrscr googling it i found that x1b2j can be used to clear the screen but how do we use it,['c'] +84618,razor syntax php equivalent is there an equivalent to the new aspnet razor syntax in php,"['c#', 'php', 'asp.net']" +84620,how to improve the performance of this haskell program i am working through the problems in project euler as a way of learning haskell and i find that my programs are a lot slower than a comparable c version even when compiled what can i do to speed up my haskell programsfor example my bruteforce solution to problem 14 isimport dataintimport dataordimport datalistsearchto 10nextnumber int64 int64nextnumber n even and and div 2 otherwise 3 and 1sequencelength int64 intsequencelength 1 1sequencelength and 1 sequencelength next where next nextnumber nlongestsequence maximumby comparing sequencelength 1searchtomain putstrln show longestsequencewhich takes around 220 seconds while an equivalent bruteforce c version only takes 12 secondsinclude stdiohint mainint argc char argv int longest 0 int terms 0 int i unsigned long j for i 1 i 10 i j i int this terms 1 while j 1 this terms if this terms terms terms this terms longest i if j 2 0 j j 2 else j 3 j 1 printfdn longest return 0what am i doing wrong or am i naive to think that haskell could even approach cs speedi am compiling the c version with gcc o2 and the haskell version with ghc make o,['c'] +84626,java 6 unsupported suppresswarningsrawtypes warning i moved to a new machine which has the latest suns java compiler and noticed some warnings in the existing java 6 code the eclipse ide suggested that i annotate the assignment withsuppresswarningsrawtypesfor exampleclass foot suppresswarningsrawtypesfoo foo new foowhen i moved back to the machine with the older compiler jdk 160 20 i have noticed that this older compiler now warns about the suppression of rawtypes warnings claiming that this suppression is unsupported and proposing to replace it with suppresswarningsunchecked also there were some places which the newest compiler by default made me to put both unchecked and rawtypes compiling that code with the older compiler reproduces the same warninghow can i enforce backwardforward compatibility between the two so that neither compiler produces warnings,['java'] +84628,how to make a transparent uiwebview i have an app with a uitableview and a corresponding detail view for each row in the detail view i have to thisplay some text and a background image text is different for each row but the image remains the same the easiest way in my opinion is to put the text in an rtf file and thisplay it in a uiwebview then just put a uiimageview behind the uiwebview i have tried to set the uiwebviews opacity to zero in ib but it did not helpcan you help me,"['ios', 'iphone']" +84651,why are signatures declared in the base class ignored class base public virtual void methodaint x consolewriteline in base class class derived base public override void methodaint x consolewriteline in derived int public void methodaobject o consolewriteline in derived object class test static void main derived d new derived int k 20 dmethodak the output i got for this is in derived object what is the reason for this strange behaviour after some research i found out the reason is the signatures declared in the base class are ignored why are they ignored,['c#'] +84652,is there a way track the focus on tab with javascript we need to track the effective time on site of our usersmost users when they are done leave the tab open and move to another tabtime on site it is extremely inaccurateis there a javascript event to track the loss of focus of the current tab,['javascript'] +84658,c suggestions of control statement needed i am a student and i got a homework i need some minor help with here is my taskwrite an application that prompts the user to enter the size of a square and thisplay a square of asterisks with the sides equal with entered integer your application works for sideas size from 2 to 16 if the user enters a number less than 2 or greater then 16 your application should thisplay a square of size 2 or 16 respectively and an error messagethis is how far i have come start int x string input consolewriteenter a number between 216 input consolereadline x int32parseinput consolewritelinen if x 16 x 2 control statement code code code else consolewritelineyou must enter a number between 2 and 16 goto start i need help with what control statmentif for while dowhile case boolean to use inside the if controlmy ideas are like do i write a code that writes out the boxes for every type of number entered that is a lot of code there must be a code containing some variable that could do the task for me but then what control statement suits the task bestbut if i use a variable how am i supposed to write the spaces in the output because after all it has to be a square i would love some suggestions on what type of statements to use or maybe just a hint of course not the whole solution as i am a student,['c#'] +84664,is it a bad idea to escape html before inserting into a database instead of upon output i have been working on a system which does not allow html formatting the method i currently use is to escape html entities before they get inserted into the database i have been told that i should insert the raw text into the database and escape html entities on outputother similar questions here i have seen look like for cases where html can still be used for formatting so i am asking for a case where html wouldnt be used at all,['html'] +84675,background image for wrap content i created a custom background image and wanted to use it as the background for a layout that has height of wrap content however the total height of the contents of within that layout are much less than the height of the background imagewhen i set it as the background in xml via androidbackgrounddrawableimage i noticed that it thisplays the entire height of the image although the height of the actual contents are much shorteris there a way to stop this from happeningthanks,['android'] +84697,maximum limit of css classes that can be assigned to html element how many number of css classes can be assigned for an html element,"['html', 'css']" +84708,how do you write program for mac os x hi just wondering how do you start writing programs for mac os xwhat language does it use can i use objective c which ide do i use any licensing fee should i know aboutthanks,['objective-c'] +84721,convert from bigint to datetime value please help me with this one i want to convert a value from bigint to datetimefor example im reading history table of teamcity server on the field build start time server i have this value on one record 1283174502729how can i convert to datetime valuethanks,['sql'] +84724,ipad mpmovieplayercontroller thisable fullscreen is there a way to thisable the fullscreen button of the mpmovieplayercontroller,['ios'] +84728,firefox lineheight issue with input fields i have realized the problem before but i guess it did not matter as much then as it did nowwhat i thiscovered is that firefox has a default lineheight value of 12 for input fields which can not be changed at least in osx do not have windows so i cannot confirm it therei did some experimenting and testing and there is just no way to change the default lineheight value of firefox all the other browsers ok i just tried with chrome and safari obey my value perfectly fine but not firefoxhas anyone ever noticed this and if yes have you found a solution to overcome this,['css'] +84735,should every sql server foreign key have a matching index is it good practice to create an index for every foreign key in a sql server database,['sql'] +84736,how can i make an image fit inside a div element when the image is wider than the div i have an image tag inside a div element div id mydiv img alt myimage src some sourcedivthe image is bigger than the div so the image is not inside the div element first i have thought about using width x height y but as i am still designing the page i fear to have to worry all the time those 2 dimensions how can i keep the image inside the div element also respecting the dimensions of the div elementthanks for helping,['html'] +84738,bind a command to a button inside a listview with caliburnmicro i am trying to create something like a mdi tabbed interface so i have a navigation pane a listbox on the left and a contentpresenter on the righti have a shellviewmodel that has a bindablecollection on it called availablescreens and i managed successfully to bind to that list with a listviews datatemplatelistview xnameavailablescreens listviewitemtemplate datatemplate wrappanel bulletdecorator button xnamethisplayview textblock textbinding pathname updatesourcetriggerpropertychanged button wrappanel datatemplate listviewitemtemplatethe problem now is that although the name of the button is set correctly i cannot make the command fire for me on the mdiviewmodel class i have the following code for that buttonpublic bool canthisplayview return truepublic void thisplayview messageboxshowhelloall the caliburnmicro samples work with binding through conventions to the xname property but if i remove the textbinding it stops working so i suspect that this way of databinding does not work for submodels anyway the shells viewmodel is quite simple at the momentshellviewmodel availablescreens mdiviewmodel1 mdiviewmodel2 currentactivescreenany idea how i would do this with caliburnmicro rob eisenberg suggested to me on twitter i might want to start out with caliburnmicro before going into the full fledged caliburn framework,['c#'] +84760,which maven plugin do i use for aspectj i am trying to add aspectj to a maven project using java 60 browsing around i found 2 maven plugins none of which works the way i would expectthe first one did not work at first through netbeans because i could not get the code to compile 50 or later source it complained about annotations etc after trying from command line which worked and comparing the commands executed it seems that its mavens install goal that is not compatible with the plugin and java 5 code while the compile goal works fine although it may be possible to work around this it is annoying and brings me to the question is the aspectjmavenplugin still being developed should i still use itthe second one is apachess own which seems more active and more likely to work i can however not find any complete examples and i am unable to run it i keep getting an exception from maven javalangillegalstateexception the plugin descriptor for the plugin plugin mavenmavenaspectjplugin was not found please verify that the plugin jar homekristoferm2repositorymavenmavenaspectjplugin40mavenaspectjplugin40jar is intactthe jar file is there intact and it also does not matter which version of the plugin i use it always throws the same exception any ideas on what the problem might be in short which plugin and how should i use itthanks,['java'] +84764,how to read systemwebserver configuration section is there any nice way to read configuration section group of iis7 by using webconfigurationmanager o anythingi tried to read the authorization section but webconfigurationmanagergetsection returns an ignoredsection instance this is what my code looks likeauthsection webconfigurationmanagergetsectionsystemwebserversecurityauthorization httpcontextcurrentrequestpath,['asp.net'] +84772,difference between applicationcontextxml and springservletxml in spring framework are applicationcontextxml and springservletxml related anyhow in spring frameworkwill the properties files declared in applicationcontextxml be available to thispatcherservleton a related note why do i need a servletxml at all why is applicationcontextxml alone insufficient,['java'] +84785,what is the android uithread ui thread can someone explain to me what exactly the ui thread ison developerandroidcom it says about the runonuithread functionpublic final void runonuithread runnable actionsince api level 1 runs the specified action on the ui thread if the current thread is the ui thread then the action is executed immediately if the current thread is not the ui thread the action is posted to the event queue of the ui threaddoes the ui thread mean that this will be run everytime the activity is pushed the the background by some ui activity like incoming call or screen dimming etc if not what exactly does the ui thread include thank you,['android'] +84787,how to prevent group concat from creating a result when no input data is present given the following mysql queryselect showid group concat showclipsclipid order by position asc as playlistfrom show inner join showclips on showid showclipsshowid i want to retrieve a list of all shows from the database including the ids of contained clips this works fine as long as there are entries in the show table for this problem let us assume all tables are completely empty group concat will return null and thus forcing a row into the result which contains only null values my application will then think that one showresult exists but that result will be invalid this can of course be checked but i feel like this could and should be prevented in the query already,['mysql'] +84792,prototype how to know the prototypejs version using a js function in jquery you can use jquery and you can know your framework version is there an equal script for prototypethank you,"['javascript', 'jquery']" +84802,high resolution images in a uiwebview i have a webview that thisplays an image as shown in the code below the bundle also has a with dimensions of 128x128 for use on the iphone4 the never shows is there a way to thisplay eitheror depending on whether it is an iphone or an iphone4 img srcdgt64png width64 height64 alignleft stylepadding2px,['iphone'] +84836,alpha masking in c systemdrawing i am trying to draw an image with a source bitmap and an alpha mask bitmap using the systemdrawinggraphics objectat the moment i loop x and y and use getpixel and setpixel to write the source color and mask alpha to a third bitmap and then render thathowever this is very inefficient and i am wondering if there is an faster way to achieve thisthe effect i am after looks like thisthe grid pattern represents transparency you probably knew that,['c#'] +84849,is there a structure in python similar to c stl map is there a structure in python which supports similar operations to c stl map and complexity of operations correspond to c stl map,"['c++', 'python']" +84852,why are there no and a operators in python why are there no and operators in python,['python'] +84870,how to make a clone method using shared ptr and inheriting from enable shared from this i have seen that a useful way to write a clone method that returns a boostshared ptr is to doclass apublic shared ptra clone const returnshared ptracloneimpl protected virtual a cloneimpl const returnnew athis class b public apublic shared ptrb clone const returnshared ptrbcloneimpl protected virtual b cloneimpl const returnnew bthis this allows the use of covariance with the regular pointer while still wrapping it in the safety of a smart pointer my problem is my class b needs to inherit from boostenable shared from this because right after construction it needs to register itself with a separate class passing a shared pointer to itself i have a create method that wraps construction and registration to make sure these always occur together the above clone method implementation cannot handle this requirement however the registration cannot occur in cloneimpl since no shared ptr yet exists owning the object preventing a call to shared from this and if this logic is not in the virtual function then an shared ptr that points to b does not know about bs registration needs when cloned what is the best way to handle this problem,['c++'] +84872,selection based on percentage weighting i have a set of values and an associated percentage for eacha 70 chanceb 20 chancec 10 chancei want to select a value a b c based on the percentage chance givenhow do i approach thismy attempt so far looks like thisr randomrandomif r 7 return aelif r 9 return belse return ci am stuck coming up with an algorithm to handle this how should i approach this so it can handle larger sets of values without just chaining together ifelse flows any explanation or answers in pseudocode are fine a python or c implementation would be especially helpful,"['c#', 'python']" +84891,is cakephp preferable for a large scale web application i am a good php developer and wanted to develop a large scale web application in php i was thinking about using the cakephp frameworkis cakephp good for large scale web applicationsshould i start learning and using itis cakephp worth investing time and money or should i go with core php or some other frameworki heard that it is difficult finding support for it in case you are stuck with some issueis this correcti have heard a lot of good things about it as well i am looking forward to your guidance,['php'] +84900,communicating back to parent from a webkit notification i am using webkitnotifications and createhtmlnotification etc to successfully create a notification in chrome windowsnow i would really like to have the notification window communicate back or at least set the focus to the tabwindow that created the notification which is part of the spec i realize it is still in the early phases for this feature but i thought maybe someone knows a way i tried windowopenerfocusfrom the notification window but it did not workthis pagesaysbringing focus back to the window that called the notification as stated in the proposal by using windowopenerfocus doesnat currently worki was hoping it was either out of date or that someone might know a workaroundthanks for any information you can sharejim,['javascript'] +84941,how to access mysqlresult in activerecord exampleresult activerecordbaseconnectionexecuteselect abchow can i get the abc value from result tried resultfirst without success thanksps gemsactiverecord 239 mysql 281,"['mysql', 'ruby-on-rails']" +84960,why is count not an unsigned integer possible duplicateswhy does net use int instead of uint in certain classeswhy is arraylength an int and not an uint hii always wonder why count is not an unsigned integer instead of a signed onefor example take listviewselecteditemscount the number of elements cannot be less then 0 so why is it a signed intif i try to test if there are elements selected i would like to test if listviewselecteditemscount 0 but because it is a signed integer i have to test if listviewselecteditemscount 0 or is there any case when count could be 0,"['c#', '.net']" +84986,how exactly does a server socket work how exactly does a server socket work when i create a java server socket and accept connection at port 1234 does the server actually uses the port 1234 for all clients i have read that when you write a network server the socket actually opens another port once the connection is acceptedis this true if so why am i not seeing it in netstat i see a lot of connections like this tcp 0 0 fmy ip1234 f97371349539236 established tcp 0 0 fmy ip1234 f8920415310126117 established tcp 0 0 fmy ip1234 f195240167026193 established tcp 0 0 fmy ip1234 f801879811615012 established tcp 0 0 fmy ip1234 f2187824819030794 established so are they really all connected to my server at 1234 if so does not that mean you the server will be able to accept infinite number of connections,['java'] +84990,using spring 3 autowire in a standalone java application here is my codepublic class main public static void mainstring args main p new main pstartargs autowired private mybean mybean private void startstring args applicationcontext context new classpathxmlapplicationcontextmetainfconfigxml systemoutprintlnmy beans method mybeangetstr service public class mybean public string getstr return string beans xmlns xmlnsxsi xmlnscontext xsischemalocation contextannotationconfig contextcomponentscan basepackagemypackagebeanswhy does not this work i get nullpointerexception is it possible to use autowiring in a standalone application,['java'] +84992,how to handle sub projects dependencies in maven my project is made of 5 sub projects one is a war and the other 4 are jars basically the war project needs all 4 jar projects and their dependenciesi can strip down the dependencies to have something like warabcd every sub project add their share of external dependencies spring struts hibernate so that in the end the war gets everything needed to runthis looks pretty well organised and square but then i ask myself if this is very practical to make changesimagine i have to change one line of code in project d without changing anything to its maven dependencies i would have to rerelease project d obviously but then i have to rerelease projects c b a and the war just to reflect this change in their pom files this can be long and annoying especially if you have to quickly release a new version to fix something in productioni could make the war depend on all 4 projects so then i just have to change project d version number in the war pom file but then i have project a depending indirectly on project d 10 and the war specifying project d 11 i think that the war direct dependency would win in that case wouldnt it this would make the new war release quicker but it would also mess my sub projects dependencies as they would be outdatedwhat would be an acceptable way to handle this situation,['java'] +84994,why is not setvisibility working on android progressbar it would be nice if the progressbar could be made to go away until it is needed is there a problem using setvisibilityprogressbar in applymenuchoice the problem with using setvisibilityprogressbar in printstatustaskexecute is that it crashes the app during runtimepublic class controller extends activity private progressbar progressbar public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutcontroller progressbar progressbarfindviewbyidridprogressbar private boolean applymenuchoicemenuitem item switch itemgetitemid case ridmenustatus progressbarsetvisibilityviewvisible new printstatustaskexecute progressbarsetvisibilityviewgone,['android'] +85002,what is the difference between pass by reference and call by reference what is the difference between pass by reference and call by reference in java,['java'] +85014,fancybox close from within iframe and take parent page to the link i found applying the following function to a links onclose works to close fancybox from within an iframeparentfancyboxclosei want to take this further and have the link take the parent page to a new urli have tried the following but it does not worka onclicklocationhrefparentfancyboxclose close and go to pageausing a href does not work either as the onclose takes precedence,['jquery'] +85017,how do i chain asynchronous operations with the task parallel library in net 4 i am attempting to programmatically chain asynchronous operations in c4 such as writes to a given stream object i originally did this manually hooking callbacks from one operation to the next but i thought i would try the net 4 task parallel library to save myself the trouble of reinventing the concurrent wheelto start with i wrap my async calls in tasks like sopublic static task createwritetaskstream stream byte data return taskfactoryfromasyncstreambeginwrite streamendwrite data 0 datalength nullcontinuations have made chaining synchronous operations very easy if youll excuse the unfortunate method namepublic static task chainflushstream stream task precedingtask return precedingtaskcontinuewithx streamflushbut there is no version of the taskcontinuewith method that accepts an async operation in the same way as taskfactoryfromasyncso assuming that i persist with using the tpl what i am looking for the correct implementation of this methodpublic static task chainwritestream stream byte data task precedingtask,"['c#', '.net']" +85029,why are protected members allowed in final java classes why are protected members allowed in final classesshould not this be a compiletime erroredit as people have pointed out you can get same package access by using the default modifier instead it should behave in exactly the same manner because protected is just default subclasses and the final modifier explicitly denies subclassing so i think the answer is more than just to provide same package access,['java'] +85030,what is a aweak framework referencea what does it mean to have a weak reference to a framework in iphone sdk,"['iphone', 'objective-c']" +85031,wcf 35 and udp is it possible to make udp binding in wcf 35 or it is only possible in net 40 if it is possible in net 35 could somebody give me an example please thanks,['c#'] +85041,net phone number parsing library does anyone know of a generic phone number parsing library for net ideally i am looking for something similiar to the ruby phone library,['.net'] +85056,create my own programming language possible duplicatesreferences needed for implementing an interpreter in ccbooks on creating interpreted languageshow to create a language these dayslearning to write a compiler possible duplicatelearning to write a compiler ok so i am only 13 years old i know some c very good at php pro at css html okay at javascript so i was thinking of how was c created i mean how can computer understand what codes mean how can it read so is it possible i can create my own language and how,['c++'] +85071,iphone avfoundation camera orientation i have been tearing my hair out trying to get the avfoundation camera to capture a picture in the correct orientation ie the device orientation but i cannot get it to worki have looked at tutorials i have watched the wwdc presentation and i have downloaded the wwdc sample program but even that does not do itthe code from my app isavcaptureconnection videoconnection cameravc connectionwithmediatypeavmediatypevideo fromconnectionsimagecaptureoutput connectionsif videoconnection isvideoorientationsupported videoconnection setvideoorientationuiapplication sharedapplicationstatusbarorientationimagecaptureoutput capturestillimageasynchronouslyfromconnectionvideoconnection completionhandlercmsamplebufferref imagedatasamplebuffer nserror error if imagedatasamplebuffer null nslogd screenorientation cmsetattachmentimagedatasamplebuffer kcgimagepropertyorientation nsstring stringwithformatd screenorientation 0 nsdata imagedata avcapturestillimageoutput jpegstillimagensdatarepresentationimagedatasamplebuffer uiimage image uiimage alloc initwithdataimagedata self processimageimage processimage uses the same writeimage method as the wwdc codeand the code from the wwdc app isavcaptureconnection videoconnection avcamdemocapturemanager connectionwithmediatypeavmediatypevideo fromconnectionsself stillimageoutput connections if videoconnection isvideoorientationsupported videoconnection setvideoorientationavcapturevideoorientationportrait self stillimageoutput capturestillimageasynchronouslyfromconnectionvideoconnection completionhandlercmsamplebufferref imagedatasamplebuffer nserror error if imagedatasamplebuffer null nsdata imagedata avcapturestillimageoutput jpegstillimagensdatarepresentationimagedatasamplebuffer uiimage image uiimage alloc initwithdataimagedata alassetslibrary library alassetslibrary alloc init library writeimagetosavedphotosalbumimage cgimage orientationalassetorientationimage imageorientation completionblocknsurl asseturl nserror error if error id delegate self delegate if delegate respondstoselectorselectorcapturestillimagefailedwitherror delegate capturestillimagefailedwitherrorerror library release image release else if error id delegate self delegate if delegate respondstoselectorselectorcapturestillimagefailedwitherror delegate capturestillimagefailedwitherrorerror at the beginning of their code they set the avorientation to portrait which seems very odd but i am trying to get it to detect the devices current orientation and use thatas you can see i have put uiapplication sharedapplicationstatusbarorientation to try and get this but it still only save the photos in portraitcan anyone offer any help or advice on what i need to be doingthanksoliver,['iphone'] +85088,python remove substring only at the end of string i have a bunch of stringssome of them have reci want to remove that only if those are the last 4 charactersso another wordssomestringthis is some string reci want it to besomestringthis is some stringwhat is the python way to approach this,['python'] +85092,php auth user not set for some reason none of the code withinif isset serverphp auth user isset serverphp auth pw when the above is set the code that is here will execute of courseis being executed for me when i enter the correct username and password the prompt box for the authorization again pops up wouldnt both fields be set if they are correct and i press enter but for some reason that is not the case what can i be doing wrongthank you,['php'] +85103,setting up environment variable in ant script i am using ant for building my projects this project needs more memory then default jvm size so i have added following line of code in the buildxml file setting up this value as project need this much memory to compileproperty environmentenv property nameenvant opts valuexms1024m xmx2048m but above line of code does not seems to have any effect as i am still getting the heap size problem so i have decided to use a batch script for launching the build the line of code in the given batch file is belowset ant optsxms512m xmx778mant f agorabuildxmlthis batch script successfully launch and executes the ant script but this is not what i am looking for is there a way exists so that i can setup this argument in the ant script itselfwhat should i do thanksvsd,['java'] +85108,tearing in html5 canvas i am making a small game using the html5 canvas element it works great except that it has a scrolling background with obvious tearing happening in firefox and chromium browsers in ubuntu i am pretty sure it is buffered because there is not any of the flickering i would expect just tearing is there any way to work around this or time rendering to right after the last screen refresh,['javascript'] +85114,android how to intercept a form post in android webviewclient on api level 4 i have a webviewclient attached to my webview like sowebviewsetwebviewclientnew mywebviewclienthere is my implementation of mywebviewclientprivate class mywebviewclient extends webviewclient override public boolean shouldoverrideurlloadingwebview view string url webviewloadurlurl return true i give the webview a url to load via loadurl if i have a link a href in the page my shouldoverrideurlloading method is called and i can intercept the link clickhowever if i have a form whose method is post the shouldoverrideurlloading method is not calledi noticed a similar issue here which seems to suggest overriding posturl in my webview however this api is only available starting from api level 5what can i do if i am on api level 4 is there any other way to intercept form posts,['android'] +85128,using bookmark button in uisearchbar how can we use the bookmark button that appears in uisearchbar i didnt found any delegate methods for that any help will be greatly appreciatedthanks in advance,"['iphone', 'objective-c']" +85152,how to avoid multiple nested ifs i am currently trying to restructure my program to be more oo and to better implement known patterns etci have quite many nested ifstatements and want to get rid of them how can i go about this my first approach was to get it done with exceptions so egpublic static boolean mymethodstring param if param null throw new nullreferenceexceptionparam may not be null if paramequalsnone paramequals0 paramequalszero throw new argumentnullexceptionparam may not be zero do some stuff with param this is not executed if param is null as the program stops a soon as one of the above exceptions is thrownthe method is used in the main class of the application egstatic void main try boolean test myclassmymethodnull will throw an exception catch exception ex messageboxshowexmessage error i think this is quite nice as it prevents the nested statements and nearly all of the methods actions are nicely arranged on one levelas with ifstatements the method would look like thispublic boolean mymethodstring param if param null if paramequalsnone paramequals0 paramequalszero do some stuff with param else messageboxshowparam may not be zero error else messageboxshowparam may not be null error which i find very very ugly and hard to maintainnow the question is is this approach good i know that might be subjective but how do you overcome nested ifs 1 or 2 levels are not that bad but it gets worse after that,['c#'] +85153,regex to check if a number is even can we have a regex to detect if a number is even i was wondering if we can have a regex to do this instead of usual or bit operationsthanks for replies,['java'] +85160,build failure in unit test project with accessors of a project containing covariant types i added a covariant interface to our projectinterface iviewinterface ipresenterout tview where tview iview tview view get i created some classes implementing these interfacesclass testview iviewclass testpresenter ipresentertestview public testview view get return something private void dosomething and i can use this without problemsipresenteriview presenter new testpresenterso everything seems right so i assume my covariance usage is correct unfortunately our unit test projects contain private accessors from some types located in the same project like the covariant interface which causes a build failurecould not load type genericinheritancetestipresenter impl1 from assembly genericinheritancetest accessor version0 cultureneutral publickeytokennull because it declares a covariant or contravariant type parameter and is not an interface or delegatewhat exactly is the problem here is there a failure in my implementation resp how to fix this can not be that we have to avoid accessors as soon as we use covariant types is it possible to prevent creating accessors for certain types to solve this problem,['c#'] +85162,call activity when notification click event i want to call the activity when user pull down the notification and click on that notificationhow can i do that,['android'] +85172,in c when using list is it good to cache the count property or is the property fast enough in other words which of the following would be faster if anylistmyclass mylistforeach whatever whatever in someotherlonglist if i mylistcount orlistmyclass mylistint listcount mylistcountforeach whatever whatever in someotherlonglist if i listcount thanks,['c#'] +85184,sql server order by case i am trying to get the following query to thisplay the results in alphabetical order by city except for the fact that i want berlin to appear at the top of the listso the results would look something likeberlin algeriaaustraliafijigreecehope that makes sensei currently have the followingselect companyname cityfrom customersorder by case when city berlin end,['sql'] +85194,ndepend several net assemblies have the name myassembly but they are different i have just started using ndepend and am trying to analyse a solutionthis warning appears when i add the solutions assemblies and it will not load any assemblies with the warningcant load the assembly myassembly several net assemblies have the name myassembly but they are different list of the dlls in the project which contain this assemblywhat could be causing this i am using a common assemblyinfocs file as well as the standard one to set some common attributes but there are no conflicts between these attributes,['.net'] +85214,how to change android tab text on the fly this seems like it should be simple but i cannot figure out a way to do it i am needing a tab to have beginning text but then have that text change after the user selects an item from a list i know how to change tab backgrounds and colors viamtabhostgetchildatindexsetbackgroundcolorbut there is not an option to change the tabs indicator i have tried using an edittextprivate edittext tabnameoverridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutstatistics comm new communicator tabname new edittextthis tabnamesettextbeginningtext mtabhost gettabhost mtabhostaddtabmtabhost newtabspectab 1 stat setindicatoruser setcontentridmestatstab mtabhostaddtabmtabhost newtabspectab 2 stat setindicatortabnamegettext setcontentridthemstatstab mtabhostaddtabmtabhost newtabspectab 3 stat setindicatorarchive setcontentridarchivestatstab mtabhostsetontabchangedlistenerthis gettabwidgetgetchildat1setonclicklistenernew onthemtabclicked mtabhostsetcurrenttab0 ontabchangedtab 1 statoverrideprotected void onactivityresultint requestcode int resultcode intent intent superonactivityresultrequestcode resultcode intent tabnamesettextchangedtabtext bundle extras intentgetextras themstats extrasgetstringarraythemstats mtabhostsetcurrenttab1 ontabchangedtab 2 statthat did not work either along with a few other attempts any ideas thanks ahead of time,['android'] +85219,mvn tomcatrun how do i edit serverxml i want to run mvn tomcatrun from the command line but how can i edit the serverxml to set maxhttpheadersize65536 in the connectors or can i configure the connectors in the pomxmlcheersnik,['java'] +85221,nullable int type allowed in settingssettings i have a property that i would like to type as int in my settingssettings file when i use int i get a runtime failuresystemnullreferenceexception object reference not set to an instance of an objecti can use a string type as a workaround where a check for null works but i have to parse the string and handle errors when the parse does not workbeing able to set the value to null allows me to keep the property documented in the settings file while making it obvious that no value has been set when not set i use a programmed default valueint configurednumberoflimits settingsdefaultrequirednumberoflimitsif configurednumberoflimits null requirednumberoflimits default required number limits,['c#'] +85232,get file modified date in vbnet i have a number of files in a folder and i need to get the last modified date so i usedfdate iofilegetlastwritetimefnameit works fine with some files but on others i get a date of 1601 but when i check the files in windows explorer all the dates look normal recent so i am guessing there are multiple files dates stored in the file system and the ones net is seeing are not the ones windows is seeing how can i get exactly the date which appears as date modified in a file explorer windowi tried some visual basic 60 api stuff but that does not seem to work in net,['.net'] +85236,moving data across the appdomain with good performance a little backgroundi am working on an net application that is uses plugins heavily the application can request data from the plugins that is then sent back and thisplayed by the applicationfirst i implemented the plugin framework in mef but feel that it was a bit limited for my purposes i wanted to be able to isolate plugins and have some versioning and licensing support since plugins can be written by thirdparty then started looking at maf which seems support just those scenarios however i can see one thing that might be a problem before i invest too much time changing everything to maf it would be great knowing if someone has experience with this issue since i havent worked much with mafthe problemcurrently when data is sent back to the application you get the actual objects of the data along with an adapter that says which fields the object contains and you can use the adapter on the object to extract the fields you want the good thing about this is that you do not have to generate any new results objects but can simply query the results data when you want it from each objectnow with maf there is the appdomain issue i cannot freely send all the objects across the app domain and inheriting from marshalbyref for each object is not viable i could generate a result object with the string fields for each object but from a performance standpoint it doesnt seem such a good idea the interface might only show 10 of hundreds of objects so it seems smarter to do on demandthe solution i am thinking might work is generating a sequence of just object ids and let the interface fetch the fields from the plugin through the appdomain through a proxy so the application says for instance it wants fieldname x from items y in the plugin and those strings is sent across the appdomainthe questionso my questions are is this a good way to do it is there a better way i am obviously going to take a little performance hit moving across the appdomain still but since it is on demand and only for a small number of objects it should not be too bad right how do i go about setting up a proxy object like thatit is not the easiest question in the world to answer sorry i will really appreciate any insight the future of the plugin architecture depends on it,['.net'] +85242,how to monitor which processes access a particular file in unix i have a file and a lot of process and process threads are accessing iti want to monitor the file to get a listing of what all processes tried to access the file being able to record the timestamps also would be excellent for logging purposes though i can do without itis there any unix utility that does something similarin case no such utility exists how should i program this using a script shell perl or a program c c,"['c++', 'c']" +85254,the type attribute of script and style elements in html i heard from crockford what type attributes on link and script elements are superfluous when those elements are used to load external resources because the http response determines the contenttype of the resourcelink relstylesheet hreffoocscript srcfoojsscriptbut what about the case when nonhtml code is placed inline inside the style and script elementsstyle inline css rules stylescript inline javascript codescriptis setting the type attribute in those cases recommendedare there any issues when we choose to omit the type attribute,['html'] +85258,change window location jquery i am using ajax to load my website content and want to update the window location when ajax is successfulhow can i update the window location to newpage i need users to be able to go back and to refresh is this possible,"['javascript', 'jquery']" +85274,iqueryable oftype where t is a runtime type i need to be able to get something similar to the following to worktype type something decided at runtime with gettype or typeofobject entitylist contextresourcesoftypetypetolistis this possible i am able to use net 4 if anything new in that allows this,['c#'] +85281,compare two list objects for equality ignoring order yet another listcomparing questionlistmytype list1listmytype list2i need to check that they both have the same elements regardless of their position within the list each mytype object may appear multiple times on a list is there a builtin function that checks this what if i guarantee that each element appears only once in a listedit guys thanks for the answers but i forgot to add something the number of occurrences of each element should be the same on both lists,['c#'] +85303,getting screen reader to read new content added with javascript when a web page is loaded screen readers like the one that comes with os x or jaws on windows will read the content of the whole page but say your page is dynamic and as users performing an action new content gets added to the page for the sake of simplicity say you thisplay a message somewhere in a span how can you get the screen reader to read that new message,['javascript'] +85312,would net be able to function just as well without the use of type object i am asking this because it seems like using object seems to be an easy way out to solve certain problems like i do not have a specific type so use object etcalso the reason this made me curious is because a colleague of mine told me that if net was a true objectoriented platform then it wouldnt have to have a catch all type like objectso if net did not have the object type what would be the alternative ways to solve the occuring problems to make it function just the samealso just to note this is not to bash net as i use it daily in my work just want to know more about itedit another note i remembered is because the type object exists its effect ripples throughout the whole net like ienumerable exists but also ienumerablet and in many situations you have to implement both the generic and nongeneric version of things etc,"['c#', '.net']" +85330,is it better to use exceptions in a validation class or return status codes suppose i am creating a class to validate a number like social security in us just as an example of a countrybased id there are some rules to validate this number that comes from an input in a html form in a websitei thinking about creating a simple class in python and a public validate method this validate returns true or false simply this method will call other small private methods like for the first x numbers if there is a different rule each one returning true or false as wellsince this is really simple i am thinking of using boolean status codes only if it is valid or not do not need meaningful messages about what is wrong i have been reading some articles about using exceptions and i would like to know your opinion in my situation would using exceptions would be a good idea,['python'] +85356,whats the ruby way to iterate over an array from arrayn to arrayn 1 say i have an array of size 5 i want to take an index from 04 as input and iterate through the array starting at the supplied indexfor example if the index given was 3 i want to iterate like soarr3arr4arr0arr1arr2i can think of plenty of ways to do this but whats the ruby way to do it,['ruby'] +85370,two different dll with same namespace i have two dll file that they both have a same namespace but they have different functions and typeshow can i references both dlls in my project and use their functions and typesby the way these two dll have some functions and types with same name and different implementation and some unique functions and types,['c#'] +85378,what is a good practice way to write a python gtk application i am currently writing a pygtk application and i would like some advice as to the best way to structure my application basically the application will read a specific file specification and present it in a gui for editingcurrently i have a parserpy which handles all the low level file io and parsing of the file i am thisplaying the contents of the file in a treeview which means that i need to use a treestore as my data typethe problem i have ran into is that i have only thought of two solutions to this problem the first is that my parser could build a treestore and pass it to my ui class that requires my parser depending on pygtk and minimizes the potential reuse for the class the second would be storing a reference to my ui class in parser which would also potentially limit the reuse of my parser class as a standalone libraryto condense my question into a short one liner is there a way to accomplish my goals in a more pythonic or oofriendly wayif looking at my code would help anyone trying to answer my question other pythonic suggestions welcome this is my first python program and i may be stuck in a more c style of thinking i plan on refactoring a lot of it,['python'] +85382,best high level web framework php preferred i am starting to architect a quite complex web application the implementation is probably going to be done in php though if there are impressive reasons to choose a different environment i might be convincedi have looked at tools like symfony and cakephp the problem is that it feels like they are relatively low level for a modern web 20 application they handle the basic things like mvc and scaffolding but not the more advanced ui elements that i am looking for here are some of my requirementssingle page architecture with minor exceptions there should be no page refresh all actions are done via ajax the way it is done in gmail and to a lesser extent in facebookajax layout and widget handling not only the application does not refresh the page but the developer can specify the layout and load various widgets into different parts of the page this is somewhat like igoogle but should be better integratedsupport both on the client side and server side for ajax widgets it should be trivial to thisplay the result of a select statement in an ajax tablearray like this should also apply to other widgets includingtreesmenusformsspeaking of forms there should be easy integration with client side validation signupauthenticationauthorization including all the housekeeping things like forgot my password captchas etcthere is more but i think i have given enough details so that you get an idea for what i am looking for basically i would like to engineer a modern web 20 app and skip writing testing debugging things that most web applications need to do and yes i know i can take yui or jquery and slap it on top of one of the regular platforms but then i would have to write all the glue now if there are modules that do this that would be interesting so if you say take symfony modules xyz jquery and there is your answer i would be happy to hear thatfinally in terms of priority i am looking for something that is scalable reliable well engineered more than something that is easy to learn and deploy,"['php', 'jquery']" +85387,ios accessibility label vs hint what is the difference between the label and hint property if i am trying to make a control accessible moreover what do the traits do are all of these properties spoken by voiceover if i fill them in,"['iphone', 'ios']" +85402,using encryptyes in a sql server connection string provider ssl provider error 0 the certificates cn name does not match the passed value i am using encryptyes in a sql server connection string as i need the tcpip traffic to be encrypted but on opening the connection i get an errora connection was successfully established with the server but then an erroroccurred during the prelogin handshake provider ssl provider error 0 the certificates cn name does not match the passed valueany suggestions how to fix this i assume i need some sort of certificate relationship between my servers but have no idea where to starti need this for two connections one each to a sql 20 server and one to a 2005 server,"['c#', 'sql']" +85404,what does a typedef with parenthesis like typedef int fvoid mean is it a function prototype typedef int fc name voidhere fc name is any valid c symbolhow different is this from a function pointer typedef,['c'] +85411,how can i create my own methods which take a block as an argument and which i can call later how can i create my own methods which take a block as an argument and which i can call lateri have tried following thingsimport uikituikithtypedef void viewcreatorvoidinterface blocks2viewcontroller uiviewcontrollervoidcreatebuttonusingblocksviewcreator blockend voidviewdidload super viewdidload self createbuttonusingblocksnsstring name uibutton dummybutton uibutton allocinitwithframecgrectmake50 50 200 100 dummybuttonbackgroundcolor uicolor greencolor selfview addsubviewdummybutton voidcreatebuttonusingblocksviewcreator block do something nsloginside creatori have also tried to pass the block variable to my custom method but without any success why it is so and what is the right way to do thisupdatethis is file ish import uikituikithtypedef void viewcreatorvoidinterface blocks2viewcontroller uiviewcontroller voidcreatebuttonusingblocksviewcreatorblockendand this is the m fileimport blocks2viewcontrollerhimplementation blocks2viewcontroller implement viewdidload to do additional setup after loading the view typically from a nib voidviewdidload super viewdidload self createbuttonusingblocksnsstring name uibutton dummybutton uibutton allocinitwithframecgrectmake50 50 200 100 dummybuttonbackgroundcolor uicolor greencolor selfview addsubviewdummybutton dummybutton release voiddidreceivememorywarning releases the view if it does not have a superview super didreceivememorywarning release any cached data images etc that are not in use voidviewdidunload release any retained subviews of the main view eg selfmyoutlet nil voidcreatebuttonusingblocksviewcreatorblock viewcreator nsloginside creatorend,['objective-c'] +85415,what important difference exists between monitortryenterobject and monitortryenterobject ref bool it seems that these code snippets ought to behave identically1 monitortryenterobjectif monitortryenterlockobject try dosomething finally monitorexitlockobject 2 monitortryenterobject ref bool introduced in net 40bool lockacquiredtry monitortryenterlockobject ref lockacquired if lockacquired dosomething finally if lockacquired monitorexitlockobject i see from the msdn documentation on the overload taking a ref bool parameterif the lock was not taken because an exception was thrown the variable specified for the locktaken parameter is false after this method ends this allows the program to determine in all cases whether it is necessary to release the lockbut the documentation also states that the overload taking only the object parameter throws no exceptions other than argumentnullexception so it seems like if an exception were thrown in code snippet 1 above it could only be because lockobject is null in which case no lock was taken and tryenter wouldve returned false anyway so the monitorexit call would not be neededclearly they would not have introduced this overload for no reason so what scenario is the monitortryenterobject ref bool method intended to address,['.net'] +85416,thisable all page elements with modal feature using jquery i wish to thisable all page elements upon an action like the modal feature that is in the jquery uilike on an ajax action i wish to show a notification and at the same time to enable the modal feature and after the request need to reenable the page elements backis there any option available in core jquery for that or any plugins,"['javascript', 'jquery', 'html', 'css']" +85424,java regex meta character and ordinary dot in java regex how to find out the difference between dot the meta character and the normal dot as we using in any sentence how to handle this kind of situation for other meta characters too like d,['java'] +85443,170 mb hello world deploying apps with qt i am new to qt but no problem in the c i used qt creator and made a simple program with a button like a hello world then i built the project i was not able to run the executable file in windows itself outside the creator because it needed these dll fileslibgcc s dw21dllmingwm10dllqtguid4dllqtcored4dlli found these files and put them beside the exe now the program works but the folder has a size of 170 mb because of the big dll files is this a way of deploying qt applications i know theirs a way to make a standalone static app but that is not the problem i am ok with the dlls but the dependencies seem to be too big is there a different method of deploying projects with smaller file sizes thanks,['c++'] +85447,do you know a good android rendering engine what is a rendering engine is there any for android,['android'] +85455,using an html checkbox to put 1 or 0 into a mysql table i am using a simple html checkbox in a form to put a 1 for checked and a 0 for unchecked in a field called subcheck in a mysql tabledoes the checkbox default to 1 for checked and 0 for unchecked if not how can i give it those valuesthanks in advancejohnformdiv clasubcheckinput typecheckbox namesubcheckclick here to receive free money in the mailpdivin the file the form goes tosubcheck postsubcheckmysql queryinsert into submission values null uid title slug cleanurl thisplayurl null subcheckthe mysql tablesubmission submissionid int11 unsigned not null auto increment loginid int11 not null title varchar10 not null slug varchar10 not null url varchar10 not null thisplayurl varchar10 not null datesubmitted timestamp not null default current timestamp subcheck tinyint1 not null primary key submissionid,"['php', 'mysql', 'html']" +85456,fast multiplication of values in an array is there a fast way to multiply values of a float array in c to optimize this function where count is a multiple of 4void multiplyfloat values float factor int count forint i0 i count i value factor value a solution must work on mac os x and windows intel and nonintel think sse vectorization compiler gcc vs msvc,['c++'] +85462,page preinit not called im running an aspnet 40 project the aspx page has autoeventwireuptrue set in the headeralthough onpreinit is called page preinit is not can anyone suggest what is wrongprotected void page preinitobject sender eventargs e responsewritebarprotected override void onpreiniteventargs e responsewritefoo baseonpreinite,['c#'] +85490,can regular javascript be mixed with jquery for example can i take this script from mozilla tutorialhtml head script typeapplicationjavascript function draw var canvas documentgetelementbyidcanvas if canvasgetcontext var ctx canvasgetcontext2d ctxfillstyle rgb20 ctxfillrect 10 10 55 50 ctxfillstyle rgba0 0 200 05 ctxfillrect 30 30 55 50 script head body onloaddraw canvas idcanvas width150 height150canvas bodyhtmland mix this javascript with jquerys documentready instead of relying on onload,"['javascript', 'jquery']" +85497,is it possible to put assembly instructions into cuda code i want to use assembly code in cuda c codein order to reduce expensive executionsas we do using asm in c programmingis it possible,['c'] +85501,proper hibernate annotation for byte i have an application using hibernate 31 and jpa annotations it has a few objects with byte attributes 1k 200k in size it uses the jpa lob annotation and hibernate 31 can read these just fine on all major databases it seems to hide the jdbc blob vendor peculiarities as it should doentitypublic class configattribute lob public byte getvaluebuffer return m valuebuffer we had to upgrade to 35 when we thiscovered that hibernate 35 breaks and would not fix this annotation combination in postgresql with no workaround i have not found a clear fix so far but i did notice that if i just remove the lob it uses the postgresql type bytea which works but only on postgresannotation postgres oracle works onbyte lob oid blob oraclebyte bytea raw255 postgresqlbyte typepba oid blob oraclebyte typebt bytea blob postgresqlonce you use type lob seems to not be relevantnote oracle seems to have deprecated the raw type since 8ii am looking for a way to have a single annotated class with a blob property which is portable across major databaseswhat is the portable way to annotate a byte propertyis this fixed in some recent version of hibernateupdateafter reading this blog i have finally figured out what the original workaround in the jira issue was apparently you are supposed to drop lob and annotate the property astypetypeorghibernatetypeprimitivebytearrayblobtype byte getvaluebuffer however this does not work for me i still get oids instead of bytea it did however work for the author of the jira issue who seemed to want oidafter the answer from a garcia i then tried this combo which actually does work on postgresql but not on oracletypetypeorghibernatetypebinarytype byte getvaluebuffer what i really need to do is control which orghibernateannotationstype the combination lob byte gets mapped to on postgresqlhere is the snippet from 355final from materializedblobtype sql type blob according to steves blog postgresql wants you to use streams for bytea do not ask me why and postgresqls custom blob type for oids note also that using setbytes on jdbc is also for bytea from past experience so this explains why usestreams has no affect they both assume byteapublic void setpreparedstatement st object value int index byte internalvalue tointernalformat value if environmentusestreamsforbinary use streams true stsetbinarystream index new bytearrayinputstream internalvalue internalvaluelength else use streams false stsetbytes index internalvalue this results inerror column signature is of type oid but expression is of type byteaupdatethe next logical question is why not just change the table definitions manually to bytea and keep the lob byte this does work until you try to store a null byte which the postgresql driver thinks is an oid type expression and the column type is bytea this is because hibernate rightly calls jdbcsetnull instead of jdbcsetbytesnull which pg driver expects error column signature is of type bytea but expression is of type oidthe type system in hibernate is currently a work in progress according to 355 deprecation comment in fact so much of the 355 code is deprecated it is hard to know what to look at when subclassing the postgresqldialect afakt typesbloboid on postgresql should be mapped to some custom type which uses oid style jdbc access ie postgresqlblobtype object and not materializedblobtype i have never actually successfully used blobs with postgresql but i do know that bytea just simply works as one i would expecti am currently looking at the batchupdateexception its possible that the driver does not support batching great quote from 2004 to sum up my ramblings i would say they we should wait for the jdbc driver to do lobs properly before changing hibernatereferencessidb526a17d9cf60a80f13d40cf8082aafd,['java'] +85521,how to check if a specific uiviewcontrollers view is currently visible possible duplicatehow to tell if uiviewcontrollers view is visible i am developing an app that processes a constant stream of incoming data from the network and provides a number of different uiviews for the user to view that datawhen certain model data gets updated based on the incoming stream from the network i access the associated uiviewcontroller or uitableviewcontroller and do setneedsthisplay on it in the case of uiviewcontroller or reloaddata in the case of uitableviewcontrolleris there a way to check if a given uiview is currently being thisplayed beyond just being loaded so that i only do setneedsthisplay or reloaddata if the user is currently looking at that uiview it would seem that calling setneedsthisplay or reloaddata on a view that the user is not currently looking at is a waste of processing power and wouldnt be good for battery life when the user eventually switches over to a view that previously got updated doing setneedsthisplay or reloaddata on the viewwillappear would make more sensethanks,"['iphone', 'objective-c']" +85535,hyphenated company name in java packages say youre working on the core module of the foo project for barbaz incorporated your code fragment might look like thispackage combarbazfoocoreimport combarbazfooutilwhat would the convention be if your companys website was not barbazcom but instead barbazcom,['java'] +85537,c richtextbox selection problem i have a richtextbox control on an application and heres my problem when the application runs if i start selecting with the mouse some of the characters inside a word and continue selecting outside it the selection automatically includes the whole word in which i begun selection and any other words from which i want to select just a part ms wordish if i am not mistakenegthe text is just another foobarwhat i want to select is just another foobar the thing between the what is actually selected just another foobarthe problem is just with mouse selecting if i select text with the keyboard it works just fine also the auto word select property of the control is turned off any idea why is that,['c#'] +85547,is there a mysql function to decode html entities i was wondering if there is a mysql function to decode text with html entities i have seen some approaches using replace but it looks kinda hard to manage all the entities,['mysql'] +85552,how to programatically thismiss a uisearchbar i have a standard table view with a uisearchcontroller implemented via a nib i want to mimic what happens when the user clicks cancel in the search bar the normal behaviour is that the search bar goes away and the table returns to its original state basically i want to have the same happen when the user selects an item that appears in their search resultsi cannot find anywhere the process of what happens when the user clicks cancel,['iphone'] +85555,rails routes limiting the available formats for a resource i have a series of resources that i want only available if accessed via the js format rails route resources gives me the formats plus the standard html is there a way to specify that only the js format routes be created,['ruby-on-rails'] +85587,publishing a ws with jaxws endpoint i built a minimal web service and published it using javaxxmlwsendpointif i try to get the wsdl at httplocalhost1234addservicewsdl it works finetrying to recieve it at i do not receive anythingthis address is the same as localhostis there a posibiility to publish a webservice without providing the addresspackage testimport javaxjwswebmethodimport javaxjwswebserviceimport javaxxmlwsendpointwebservicepublic class addservice webmethodpublic int addint a int b return ab public static void mainstring args endpointpublishhttplocalhost1234addservice new addservice changing the code to endpointpublish new addservicegets me the wsdl on the ip address but not on localhostis not there a posibility to just define the port,['java'] +85592,c fileio copy vs systemcp file1x file2x would it be quickerefficient to write a file copy routine or should i just execute a system call to cpthe file system could differ nfs local reiser etc however it would always be on a centos linux system,['c++'] +85608,java libraries to manage css explosion and or reuse java qi like css for simple web pages but loathe it when it comes to real world sites because you get css explosion and lots of repeatingi am tempted to use sass and or compass but they are ruby programs which will most likely require some interesting maven jruby love to get working for java web app dev this also makes it difficult if you are using eclipse or any ide that supports synchronization with a running web appis there a better alternative for the hell that is css in the hell that is java,"['java', 'css']" +85614,how do i find if my a table is myisam or innodb possible duplicatehow can i check mysql engine type for a specific table assuming that users is a table following command does not reveal if users table is myisam or innodbdesc users how do i find what is the type of users table,['mysql'] +85620,adjusting navigationitemtitleviews frame i noticed that the titleviews position depends on the rightbarbutton title how can i set the frame of the titleview to be in the center insteadi have tried setting titleviewframe but to no availheres the codeuibutton titlelabel uibutton buttonwithtypeuibuttontypecustomtitlelabel settitleright eye forstateuicontrolstatenormaltitlelabel settitlecoloruicolor whitecolor forstateuicontrolstatenormaltitlelabel settitlecoloruicolor blackcolor forstateuicontrolstatehighlightedtitlelabelframe cgrectmake100 0 180 44titlelabeltitlelabelbackgroundcolor uicolor clearcolortitlelabeltitlelabelfont uifont boldsystemfontofsize200titlelabeltitlelabelshadowcolor uicolor colorwithwhite00 alpha03 titlelabeltitlelabeltextalignment uitextalignmentcenter this does not work eithertitlelabel addtargetself actionselectortitletap forcontroleventsuicontroleventtouchupinsideselfnavigationitemtitleview titlelabelselfnavigationitemtitleviewframe cgrectmake100 0 180 44 this does not work either,['iphone'] +85625,automatically download sales reports from itunes connect i had a nice and hacky perl script to automatically scrape and download sales report files from itunes connect as of today apple overhauled the sales report site it looks a lot nicer but it uses a lot of javascript and simple scraping is not going to work any moreso does anybody know of a way to scrape this new site effectivelysome previous questions point to various scripts and online services i presume they are all broken now as well if you know of one that is still functional please let me know,"['iphone', 'ios']" +85658,handling the window closing event with wpf mvvm light toolkit i would like to handle the closing event when a user clicks the upper right x button of my window in order to eventually thisplay a confirm message orand cancel the closingi know how to do this in the codebehind subscribe to the closing event of the window then use the canceleventargscancel propertybut i am using mvvm so i am not sure it is the good approachi think the good approach would be to bind the closing event to a command in my viewmodeli tried that iinteractiontriggers ieventtrigger eventnameclosing cmdeventtocommand commandbinding closecommand ieventtrigger iinteractiontriggerswith an associated relaycommand in my viewmodel but it does not work the commands code is not executed,['c#'] +85665,is there any good known file based keyvalue datastructure available in c is there any good file based keyvalue datastructure available in csimilar to stdmaptemplate based with a insertdeleteget of ologn,['c++'] +85687,what is the difference between static and extern in c possible duplicatestatic vs extern c what is the difference between static and extern in c,['c'] +85692,is possible to keep session even after the browser is closed could anyone tell how to maintain a session in php so that the session contains are preserved and are accessible even after the browser is restartedin general a session expires with the closing of a browser but i want the session not to be closed so that the session datas can be accessed the next time the browser is used,['php'] +85697,where are the local global static auto register extern const volatile variables are stored where are the local global static auto register extern const volatile variables stored,"['objective-c', 'c']" +85715,how to write centered multicolored text to a canvas i am writing to a canvas from a threadpublic void drawcanvas canvas paint p new paint psetantialiastrue psettextsize30 psetcolorcolorwhite psettextalignpaintaligncenter canvasdrawtextcentered xcentre ycentre pmy problem start when i have a multi colored spannablestringbuilder which i want to write to the canvas and i have no idea how to do this spannablestringbuilder has a drawtext method which i have been unable to use or is there some other method to write a string to a canvas where some of the letters have a different color,['android'] +85724,how many connections are available in the adonet connection pool is it possible from an aspnet application to check how many connections of the adonet connection pool are currently inuse and how many are available not currently inuse,['.net'] +85726,get textlabel text of selected cell using the iphone sdk i would like to know how to get the textlabel string value of the selected uitableviewcell,['iphone'] +85729,how to mix html with gwt widgets i try to generate a dynamically gwt ui as a result i would get a html fragment like thisollimylabelliliinput typetextliolthe label should be a gwt label and the input should be a gwt textboxhow can i achieve this with gwt i have tried to use the htmlpanel class but how can i inject thelitagsi cannot use uibinder since i would like to dynamically create such fragments as shown above,['java'] +85733,how to switch between hide and view password is there a clever way to let the user switch between hide and view password in an android edittexta number of pc based apps let the user do this,['android'] +85741,case sensitive accent folding in javascript you wrote this codeaccentstidy functions var rstolowercase r rreplacenew regexps g r rreplacenew regexpa a ga r rreplacenew regexpa gae r rreplacenew regexpa gc r rreplacenew regexpa a ge r rreplacenew regexpa gi r rreplacenew regexpa gn r rreplacenew regexpa2a3a aa go r rreplacenew regexpa goe r rreplacenew regexpa1aoaa14 gu r rreplacenew regexpa12a gy r rreplacenew regexpw g return r i would like if answer my question pleaseif i would like big char the for example a a a e etc then i must change the codethank you very much,['javascript'] +85745,c using a base class as the implementation of an interface in c is it possible to use another base class to provide the implementation of an interface ie abstract base class in a derived class class base virtual void myfunction class interface virtual void myfunction 0class derived public base public interface myfunction is implemented by basethe above should compile but does not actually work is there any way to achieve this effectin case anyone cares the reason for wanting this is that it make sense for my application to use a generic library from another projectnamespace to provide the implementation of an interface in my project i could just wrap everything but that seems like a lot of extra overheadthanks,['c++'] +85751,servlet filter url mapping how can a filter be mapped to the root of a url i am using tomcat 702 and deploying an application as rootwar the welcome page is sign inxhtml i would like to run a filter whenever the client sends a request for the root of the site ie the domain name only or when the the client requests sign inxhtml here is what i have so far filter filternamemy filterfiltername filterclasscommyappmyfilterfilterclass filter filtermapping filternamemy filterfiltername urlpatternsign inxhtmlurlpattern filtermappingrequests for sign inxhtml directly successfully invoke the filter but i am not sure how to get requests for the root to invoke the filter according to the servlet spec version 30urlpatternurlpatternmaps to the default servlet and an empty string maps to the root heres the relevant section from the specthe empty string is a special url pattern that exactly maps to theapplications context root ie requests of the form httphostport in this case the path info is aa and the servlet path and context path isempty string aahowever both of the following url patterns cause tomcat to throw an exceptionurlpatternurlpatternurlpatternurlpatterni would really appreciate it if someone could shed some light on this thank youandrew,['java'] +85753,how to port android application to ios platform i am developing an android application and i would really like to deploy it for the iphone as wellhowever i do not know objectivec and i think it would take an annoyingly long time to figure that and the apple framework outis there a recommended way to port an android application to ios would the best bet be to hire a freelancer,"['java', 'objective-c', 'android']" +85760,ssh example of privatepublic key authentication can anyone give me an example of privatepublic key authentication in sshjin sshj whats the command line equivalent ofssh i pathtomykeyprivate usernamehosti tried error handling omittedfinal sshclient ssh new sshclientsshloadknownhostshconnecthostsshauthpublickeyusername pathtomykeyprivatefinal session session sshstartsessionbut in the log statements i seedebug netschmizzsshjsshclient attempting to load key from pathtomykeyprivatewarn netschmizzsshjsshclient could not load keys due to netschmizzsshjcommonsshexception no provider available forunknown key file at netschmizzsshjsshclientloadkeyshclientjava482 sshj030jarnaexception in thread main 104955943 reader debugnetschmizzsshjtransportreader stoppingnetschmizzsshjuserauthuserauthexception exhausted available authentication methodsthankseverett,['java'] +85774,implement startforeground method in android i want to implement the startforeground method in the service class for prevent service self killcan anybody sent me code for implementing this method,['android'] +85785,using resttemplate how to send the request to a proxy first so i can use my junits with jmeter i have a web service running on my dev box implemented using springmvc 30 i have various junits that test against that service using resttemplate what i would like to do is have jmeter pick up those junits rest requests when i run them however to do that i need to have springs resttemplate send them to the proxy that i am running jmeter on so the question is how can i do thati have done something similar with cxf and their httpconduit and httpclient stuff but i really have no idea how to do this with springmvc,['java'] +85791,uiview frame when navigation bar and tab bar controller exist i am creating a uiview programatically in loadview the application has a uitabbarcontroller and uinavigationcontrollerhow do i create a view that automatically resizes when a tab bar and a navigation bar both existmy current approach to this problem is calculating the heights of the navigation and tab bar controllers and subtracting them from the mainscreens heightfloat navobjectsheight selftabbarcontrollertabbarframesizeheight selfnavigationcontrollernavigationbarframesizeheightcgrect mainframe cgrectmake0 0 screenframesizewidth screenframesizeheight navobjectsheightuiview contentwrapper uiview alloc initwithframemainframe,"['iphone', 'objective-c']" +85807,stopping gif animation programmatically i am developing a twitter application which references to the images directly from twitterhow can i prevent animated gifs from being playedusing windowstop at the end of the page does not work for me in firefoxis there a better javascript hack preferable this should work for all browsers,"['javascript', 'html']" +85808,make a ruby program a daemon i want to write a ruby program that will always be running in the background a daemon on my maccan someone point me in the right direction on how this would be done,['ruby'] +85814,how to pass a typed collection from clojure to java i know the basics of clojurejava interop calling java from clojure and vice versa however i was not able to return a typed collection from clojure to java i am trying to see something of that nature listtypedobject from the java code which is calling into clojurejava objectpublic class typedobject private othertype1 prop1 public othertype1 getprop1 return prop1 public void setprop1othertype1 prop1 prop1 prop1 clojure methoddefn createlistoftypedobjects creates and returns a list of typedobjects input do work here to create and return list of typedobjects typedobj1 typedobj2 typedobj3genclass name somenamespace methods createlistoftypedobjectsstring let us consider that i am writing an api using clojure which is to be thistributed as a jar file to be used from java my question was really how to what to pass in place of the questions marks above inside the genclass for aot so that a programmer writing a piece of code in java using my api can have the appropriate intellisense code completion ie createlistoftypedobjects returns listtypedobject from within eclipse for example,['java'] +85821,run netbeans maven project from commandline i have got a maven project that runs perfectly inside netbeans how can i execute the application from the commandline without netbeans,['java'] +85827,database table names plural or singular what is the most common naming convention for sql database tableswas it historically one way and now it is better to do another waywhat are the most common practices now,['sql'] +85831,how to get pydoc command working in windows pydoc does not work in windows at this post the last answer by dave webb says to create a pydocbat file with this code in itpython cpython27libpydocpy after i create pydocbat where should it be placed so the pydoc command works in the command promptps adding cpython27libpydocpy to the windows path in the system environment variables does not work even after logging out and back in it does not work,['python'] +85834,android bindservice orand startservice i want to create service using bindservice methodbut when i close one activity my service is destroyed and i do not want thati try to put service in foreground using startforegroundnotification id notification service oncreate but service still destroynow i try with call two methods for starting service at same time intent bindintent new intentthis servicecclass startservicebindintent bindservicebindintent onservice bind auto createby calling these two methods service not destroyed my app work fine with this methodcan someone explain to me whether this is a good way or if it is not can you please give me idea why startforegroundnotification id notification does not work what is the best way to use bindservice but at the same time i do not want the service to self destroy,['android'] +85837,why is the winforms click event slower than the mouseclick event i am adding buttons to form with loop and i noticed adding click event handlers slowing down application too much later i tried mouse click event instead click event and it is working instantlythis screenshot showing my test resultsource code results for 10 event handlerclick 2892msmouseclick 1ms i cannot figure out why click event very sloweditif i change build platform target to x64 or any cpu results changingclick 5 mouseclick 9look like x86 platform target causing this problem but still x64 results not good too compared to x86 mouseclick time 1msedit2i changed screenshot now it will show better resultedit3,"['c#', '.net']" +85839,how to get data out of jquery getjson callback i need to get the json object data out of the callback function so that i can process it later in page not within the callback as i am now it must be obvious to everyone else as i cannot see anything written about it can anyone tell me how to do ithere is my codescript typetextjavascript srcsite mediajsjstree libjqueryjsscript script typetextjavascript srcscriptscript typetextjavascript function initialize var mylatlng new googlemapslatlng25363882131044922 var myoptions zoom 4 center mylatlng maptypeid googlemapsmaptypeidroadmap map new googlemapsmapdocumentgetelementbyidmap canvas myoptions return map function add markermap lat long var marker imagesite mediaimagesmap markerpng var mylatlng new googlemapslatlnglatlong titletitle var marker new googlemapsmarker position mylatlng map map titletitle iconmarker image mappantomylatlng windowonloadinitialize settimeoutmapinitialize20 getjsonajaxget functiondata eachdata functionival latitude valfieldslatitude longitude valfieldslongitude add markermap latitude longitude scriptdiv idmap canvas stylewidth 500px height 300pxdiv,['jquery'] +85840,contact us functionality in rails 3 i want to make a contact us form in rails 3 with the following fieldsnameemailmessage titlemessage bodythe posted messages are intended to go to my email address so i do not neccessarily must store the messages in the database do i have to use actionmailer any gem or plugin for it,['ruby-on-rails'] +85859,remove first and last char from string i have thisdatalist onetwothreelist explode datalistechopreprint rlistechoprewhich outputs array 0 1 one 2 two 3 three 4 how do i strip the fist and last in the string before exploding,['php'] +85873,iphone video recording cameracapturemode 1 not available because mediatypes does contain publicmovie i try to record a videothe message i got is from the following code on the device uiimagepickercontroller imagepickercontroller uiimagepickercontroller alloc init imagepickercontrollersourcetype uiimagepickercontrollersourcetypecamera imagepickercontrollerallowsediting yes imagepickercontrollercameracapturemode uiimagepickercontrollercameracapturemodevideo imagepickercontrollerdelegate self self presentmodalviewcontrollerimagepickercontroller animatedyes imagepickercontroller releaseany ideas i think it should be really easy to take a video when i start the camera app of the phone i have the choice between video and picture should not it be available for my app also10x in advancedanail,['iphone'] +85874,asynctask error handling i am using asynctask to perform some background calculations but i am unable to find a correct way to handle exceptions currently i am using the following codeprivate class mytask extends asynctaskstring void string private int e 0 override protected string doinbackgroundstring params try url url new url catch malformedurlexception e e 1 other code here return null override protected void onpostexecutestring result if e 1 logisome tag an error occurred perform post processing here i believe that the variable e maye be writtenaccessed by both the main and worker thread as i know that onpostexecute will only be run after doinbackround has finished can i omit any synchronizationis this bad code is there an agreed or correct way to handle exceptions in an asynctask,['android'] +85886,compiler error when using integer as template parameter what is wrong with the following piece of codetemplatetypename xstruct a templateint n int foo const return n templatetypename xstruct b int barconst ax v return vfoo13 include iostreamusing stdcoutusing stdendlint main adouble a bdouble b cout bbara endl return 0inside the function bbar the compiler complainserror invalid operands of types aa and ainta to binary aoperatoraif a is not a template everything compiles fine,['c++'] +85891,dynamic rows of divs boxes using css i have a variable number of boxes and i would like to thisplay as many as i can without forcing the viewer to scroll horizontally there should also be a certain space in between them this means that the boxes will have to move to the next or previous row if the browser is resizedhow do i achieve this using divs and cssthanks in advance ps enjoy my fine art skills,"['css', 'html']" +85901,finding the median value of an array i was wondering if it was possible to find the median value of an array for example suppose i have an array of size nine would it possible to find the middle slot of this array,"['java', 'c++']" +85915,is there an iphone library to provide something similar to an ipad popover is there some library that provides a uiviewuiviewcontroller similar to the ipad popover on the iphone i am just talking about a temporary view that appears on top of the current view and does the nice transitions that a uipopoverview does on an ipad,['iphone'] +85921,how do i remove all tinymce instances at startup i am dynamically creating and destroying textareas for this purpose however when i create a textarea and then an instance of it in tinymcethen come back to the page again it does not work i have found that the solution is to simply remove any existing instance of that same name but i was wondering if it is possible to just do it at startupthanks in advance,"['javascript', 'jquery']" +85926,looking for a graph layout framework for ios for an ios application i am making i need to show groups of elements grouped together according to their type and different groups of types separated from each other in a nicely done layout i thought of using an undirected graph with the grouped nodes all pointing to each other in a sort of circular reference and then each group as another metagraph with their nodes point at each other in a circular reference as well hoping that together with a good graph layout framework this could be thisplayed nicelyunfortunately the only framework i keep hearing of is graphviz but that does not seem to have an available port for ios so my question is eitherother ideas for how to implement what i needa good implementation of graph layout for the iosan available port of graphviz for the iosupdate please note i am not looking for graph plotting frameworks which are the frameworks used to draw graphs and charts such as pie charts etc i am looking for a layout framework which determines the optimal location for arbitrary nodes in an abstract graph,"['iphone', 'ios']" +85929,install mogli gem on rails 3 i am trying to install the mogli gem on rails 3 and am running into problems with the configuration i have no prior experience with rails 2 for rails 2add configgem mogli to environmentrbfor rails 3 i added the following to the gemfilegem moglifor rails 2 routesmapresource oauth controlleroauthmaproot controlleroauthmapoauth callback oauthcreate controlleroauth actioncreatefor rails 3 i addedresources oauthroot to oauthindexand i do not know how to represent the mapoauth callback in rails 3thanks,['ruby-on-rails'] +85931,loading a resource to a mutable bitmap i am loading a bitmap from a resource like so bitmap mbackground bitmapfactorydecoderesourceresrdrawableimagewhat i want to do is make some changes to the bitmap before it gets drawn to the main canvas in my draw method as it would seem wasteful to repeat lots of drawing in my main loop when it is not going to change i am making the changes to the bitmap with the followingcanvas c new canvasmbackgroundcdrawargb etcso naturally i get an exceptionjavalangillegalstateexception immutable bitmap passed to canvas constructorso to avoid that i made a copy of the bitmap so that it is mutablebitmap mbackground bitmapfactorydecoderesourceresrdrawableimagecopybitmapconfigargb 8 truewhich avoid the problem however it sometimes causes outofmemoryexceptions do know any better ways of achieving what i want,['android'] +85945,mutual exclusion for and asynchronous threads i have got an asynchronous application meaning that at any given time there can be and events is there a known algorithm for doing mutual exclusion for and threads without hardcoding each thread to have an id,['javascript'] +85946,how do i pass an extra parameter to jquery autocomplete field i am using the jquery autocomplete in one of my formsthe basic form selects products from my database this works great but i would like to further develop so that only products shipped from a certain zipcode are returned i have got the backend script figured out i just need to work out the best way to pass the zipcode to this scriptthis is how my form looksformselect idzipcodeoption value2020optionoption value3030optionoption value4040optionselectinput typetext idproductinput typesubmitformand here is the jquery codeproductautocomplete sourceproduct auto completephppostcode zipcodeval minlength 2 select functionevent ui action this code works to an extent but only returns the first zipcode value regardless of which value is actually selected i guess whats happening is that the source url is primed on page load rather than when the select menu is changed is there a way around this or is there a better way overall to achieve the result i am after,['jquery'] +85952,bottom borders on wpf grid i have got a pretty simple question regarding the wpf grid controli would like to set a bottom border on each row in the grid but can only find how to put all 4 borders around each cell my code is quite simplegrid height174 horizontalalignmentleft margin2328900 namegrid2 verticalalignmenttop width730 gridrowdefinitions rowdefinition height45 rowdefinition height25 rowdefinition height25 rowdefinition height25 rowdefinition height25 rowdefinition height25 gridrowdefinitions gridcolumndefinitions columndefinition width255 columndefinition width95 columndefinition width95 columndefinition width95 columndefinition width95 columndefinition width95 gridcolumndefinitionsgridfor another grid i am using that needs all four borders i am using border gridcolumn0 gridrow0 borderbrush61738b borderthickness1 ps the contents of the grid are some labels textboxes etc if that matters at allappreciate any pointersm,['c#'] +85956,how to make google fonts work in ie i have been developing a site that uses the google fonts api it is great and supposedly has been tested in ie but when testing in ie 8 the fonts simply do not get styledi included the font as google instructs thuslink href relstylesheet typetextcss and added its name to the front of a font family in css thusbody fontfamily josefin sans std light times new roman times seriffontsize 16pxoverflowy scrolloverflowx hiddencolor 05121fworks like a charm in chrome firefox safari no dice in ie 8 anybody know why,['css'] +85959,converting to ascii in c using a microcontroller pic18f4580 i need to collect data and send it to an sd card for later analysis the data it collects will have values between 0 and 1023 or 0x0 and 0x3ffso what i need to do is convert 1023 into a base 10 string of literal ascii values 0x31 0x30 0x32 0x33 my problem is that the only way i can think of to split the digits apart requires a lot of divisionchar temp4temp0 1023 10temp1 1023 100 10temp2 1023 10 100temp3 1023 10 10using this method finding the ascii values of an and digit decimal number requires 2n1 divisions is there a method that would be fasterthe end goal of this is to wind up with a csv file on the sd card that can quickly be plugged into any laptop to see a graph of the data in excel,['c'] +85964,add allow url fopen to my phpini using htaccess i want to allow allow url fopen on my server i have asked my host and they said it can be done with a htaccess file can anyone tell me how to go about this,['php'] +85969,calculating thistance between two points using latitude longitude what am i doing wrong i am trying to solve this assignment and it is taking too much timeheres my try it is just a snippet of my codefinal double radius 637101double temp mathcosmathtoradianslata mathcosmathtoradianslatb mathcosmathtoradianslatb lata mathsinmathtoradianslata mathsinmathtoradianslatb return temp radius mathpi 180i am using this formulae to get the latitude and longitudex deg min sec 60 60thanks,['java'] +85970,how can i showhide component with jsf how can i showhide component with jsfi am currently trying so do the same with the help of javascript but not successfulli cannot use any third party librariesthanks abhi,"['java', 'javascript']" +85975,c const reference before vs after typespecifier what is the difference between the arguments inint foo1const fred arg andint foo2fred const arg i do not see this case covered in the parashift faq,['c++'] +85978,combobox autocomplete on substring in one of my winforms applications i have a window with a combobox for the user to select a customer fromthe customers in this list box are in this format customerid customername for example 004540 northwind tradersthe native winforms combobox has an autocomplete feature builtin and it works well the problem is that it only works by matching from the beginning of the string of each item of the comboboxs list and not from anywhere substringwhat i would like my users to be able to do is to either type of the customerid or customername as senior users are familiar with most customerids while new recruits would benefit from being able to type the customername in and get the autocomplete anywaythat means that i actually want to look for the best match from the list where the inputted text is a substring of the combobox itema solution often suggested for this kind of scenario is to create a hidden list box that only shows up when the user types but i am not happy with that as it feels like a quick hack and is not easily reusable and may look and behave inconsistently compared to the standard combobox controli have tried to implement this myself using the droppeddown property to make the list appear and use selectedindex to set the item but the content of the comboboxs textbox is reset when i do that while i only would like the best matching item to be highlighted from the combobox lists i need suggest and not append appendmode can not be really be used with substringmatching anywayi think that there must be a better wayif anyone knows of a custom 3rd party control doing this i am not against buying one eitherthanksps i am programming in c for winforms with net framework 35,"['c#', '.net']" +85982,android activity image background size i am a bit confused on creating an image which will be acting as a background for my activities so in short my aim is that my application should be able to fit the different screen sizes therefore what size in pixel should my three images be to be able to fill the screen of the device in ldpi mdpi and hdpithank you for any response,['android'] +85991,how to use javastringformat in scala i am trying to use a format method of a string but if i place 1 2 etc in the string javautilunknownformatconversionexception is thrown pointing to a confusing java source code pieceprivate void checktextstring s int idx if there are any in the given string we got a bad format specifier if idx sindexof 1 char c idx slength 2 scharatidx 1 throw new unknownformatconversionexceptionstringvalueofc from this i understand that char is forbidden if so then what should i use for argument placeholdersi use scala 28,['java'] +85995,java nosuchmethoderror i am getting nosuchmethoderror comfoosomeservicedosmthzam i understanding correctly that this z means that return type of dosmth method is boolean if true then that kind of method really does not exist because this method returns some collection but on the other hand if i call this method i am not assigning its return value to any variable i just call this method like thisservicedosmthany ideas why this error occurs all necessary jar files exist and all other methods from this class seems to exist,['java'] +86022,how can i sort an sqlite query ignoring articles the a etc i am using c to thisplay a list of movie titles that i am calling from an sqlite database currently i am using a custom listbox class that has a function to sort the text stripping the word the from the beginning of every item however it does not exactly seem to be the simplest way to do it since it calls from the sqlite database and then sorts i would prefer to cut it down to just one step hopefully sorting straight from the database in my select queryi have done some searching on this and have found some suggestions including creating an extra sortby column in the database while this is certainly a possibility i am wondering if there is any simpler options that do not require inserting almost identical duplicate information especially if the database becomes larger i am pretty new to sqlite but i have read something about creating a collate function that can be used to create custom ordering however i am not sure if this is appropriate use for it and cannot seem to find any help with implementing it in cwas hoping someone might be able to share some guidance if an extra sorting column is the best way to go then that is what i shall do,['c#'] +86025,check if i can write a file to a directory or not with python i need to check if i can write a file to a directory that user point to with pythonis there an way to check it in advance i may be using try catch for this purpose but i expect something better in the sense that i can check in advance,['python'] +86029,object oriented php cms or framework i am embarking on a very big exercise to build a cms in php it is actually my attempt to learn php in a fun and hardcore way coming from a java background java is all object oriented so oop is in my blood but i am finding that oop has not made it yet to php most php is still being written today the old way without the new concepts i am trying to find an example php cms that is written as object oriented i hear xoops is any others you know of or any oop libraries in general that you know of that could help me in a cms project,['php'] +86044,how does your rails app include javascript i am very curious how your rails apps include javascript for exampledo you package all your js code into a single file and serve it for all requestsdo you conditionally load certain js depending on controlleractionwhat tools or techniques do you use ie asset packager yui compressor sprockets bigpipe inspired implementationa bit of background i work on a massive rails app that is very js heavy currently all js is minified and served from a single file this makes things very convenient as all frameworks and widgets are available everywhere i am beginning to question this approach is it seems a bit crazy to make all users pay the price for some js that they may never see littering the code with script includes seems crappy and difficult as large portions of the site deliver content via ajaxanyone have any advice to sharethanks much,"['javascript', 'jquery', 'ruby-on-rails']" +86059,create a copy of a nsobject how do i take a nsobject that i have set all the attributes of and then copy that into another block of memory that an array can use so i can re use the original one,"['iphone', 'objective-c']" +86067,proscons of storing serialized hash vs keyvalue database object in activerecord if i have several objects that each have basically a profile what i am using to store random attributes what are the pros and cons ofstoring a serialized hash in a column for a record vsstoring a bunch of keyvalue objects that belong to the main objectcodesay you have sti records like theseclass building activerecordbase has one profile as profilableendclass officebuilding building endclass home building endclass restaurant building endeach has one profileoption 1 serialized hashclass serializedprofile activerecordbase serialize settingsendcreate table profiles force true do t tstring name tstring website tstring email tstring phone tstring type ttext settings tinteger profilable id tstring profilable type ttimestampendoption 2 keyvalue storeclass keyvalueprofile activerecordbase has many settingsendcreate table profiles force true do t tstring name tstring website tstring email tstring phone tstring type tinteger profilable id tstring profilable type ttimestampendcreate table settings force true do t tstring key ttext value tinteger profile id tstring profile type ttimestampendwhich would you chooseassume that 99 of the time i would not need to search by the custom settings just wondering what the tradeoffs are in terms of performance and the likelihood of future problems and the number of custom settings will likely be anywhere from 1050i would rather go with the second option with the settings table because it follows the activerecord objectoriented conventions but i am wondering if in this kind of situation that would come at too high a performance costnote i am wondering in terms of rdbms only this would be a perfect fit for mongodbrethiscouchdbetc but i want to know purely the pros and cons in terms of sql,"['sql', 'ruby-on-rails', 'ruby']" +86073,base b new base vs base b new base without defining my own constructor if i do not define my own constructor is there any difference between base b new base vs base b new base,['c++'] +86091,windowonload vs documentready what are the differences between javascripts windowonload and jquerys documentready method,"['javascript', 'jquery']" +86121,what is delete what do these two strange lines of code meanthread guardthread guard const deletethread guard operatorthread guard const delete,['c++'] +86142,word sense thisambiguation in nltk python i am new to nltk python and i am looking for some sample application which can do word sense thisambiguation i have got a lot of algorithms in search results but not a sample application i just want to pass a sentence and want to know the sense of each word by referring to wordnet library thanksi have found a similar module in perl is there such module present in nltk python,['python'] +86145,resolving relative paths when loading xslt files i need to do an xsl transformation using apache fop and i had code like thissetup fopfop fop fopfactorynewfopmimeconstantsmime pdf outsetup transformersource xsltsrc new streamsourcenew filexslpathtransformer transformer tfactorynewtransformerxsltsrcmake sure the xsl transformations result is piped through to fopresult res new saxresultfopgetdefaulthandlersetup inputsource src new streamsourcenew filexmlpathstart the transformation and rendering processtransformertransformsrc reswhere xslpath is the path where my xslt file is storedi have confirmed that it works when i have only one xslt file but in my project i have divided things into several xslt files and joined them with the xslimport tag with this configuration i get a nullpointerexception because it does not understand all the information stored in xslt because it is thistributed over different filesi wonder if there is any way to load all these files in the source xsltsrc variable so all the xsl information is availableupdatei have changed the code based on the answer given by mads hansen but it still does not work i have to include the xslt slt files in the classpath so i load the xslt file with classloader i have checked that the url has the correct path when executing urltoexternalform this is my new piece of codeclassloader cl thisgetclassgetclassloaderstring systemid resourcesxsltmyfilexsltinputstream in clgetresourceasstreamsystemidurl url clgetresourcesystemidsource source new streamsourceinsourcesetsystemidurltoexternalformtransformer tfactorynewtransformersourceit finds and loads myfilexslt but it still does not resolve the relative paths to the other xslt fileswhat am i doing wrong,['java'] +86155,how to find the remaining time of a settimeout possible duplicatejavascript find the time left in a settimeout i am trying to use settimeout as a way of pausing a series of events in jsheres an example of what i am doing and what i would like to do in comments any suggestions how i can populate var timeremaining with the total milliseconds remaining in var a,['javascript'] +86162,html5 onpopstate on page load i am using the new html5 onpopstate event using firefox 4 the windowonpopstate event is triggered on a page load whilst in webkit this does not seem to be the casewhich is the correct behaviour,['javascript'] +86176,force hibernate query to access database i have loaded an entity into my transaction and have changed a property of that entity the transaction is not yet commited now i would like to get the original value of the changed propertyi have tried with a hql query like select pproperty from person p where pid 1 with the id of the entity loaded in the transaction i have set querysethintorghibernatecachemode cachemodeignore before executing the query but no success hibernate returns the value as set in the current transaction not the one from the database is there any way around this,['java'] +86210,setting a max width for linearlayout how can i set the max width of my horizontal linearlayout so if the contents are short say some text the layout shrinks and if the contents are longer it will not expand more than some max width valuei prefer doing this at the xml level,['android'] +86221,get each line from textarea textarea put returns between paragraphsfor linebreak add 2 spaces at endindent code by 4 spacesquote by placing at start of linetextareatext value from this textareahow to1 get each line from this textarea text and work with them using foreach2 add br to the end of each line except the last one3 throw each line to an arrayimportant text inside textarea can be multilanguagehave tried to usetext str replacen br textbut it does not workthanks,['php'] +86222,curious why is the throws exception syntax required in java alone we all know it is neededbut why is it needed in java alone when other similar languages that have exception handling capablities do not require us to write throws exception is there anyone who knows what was happening when java language was designed and why they made it that way just curiousps this may not be a practical or really necessary question it might not help me in anyway with my ongoing projects but certain language features kindle my curiosity deditlooks like my question was very vague i think i worded the question wrongly we need to use the throws exception kind of syntax at some points during programming when dealing with java code but something like that is never needed in c or c or even vbnet and php so why java alone insists on this,['java'] +86224,how to strip out the imdb id from a string in php i have several thousand text strings where the imdb occures in fairly random positions but its always in the following format tt0234215 tt some numbers what would be the best way to strip it out in php,['php'] +86226,can i use aliases in an insert statement can we use aliases with insert into syntaxnone of the following workinsert into tableblabla as blainsert into bla tableblablainsert into tableblabla blai cannot seem to find any information about this is there a valid way to use aliases in an insert statementabout the possible reasonsthanks in advancemem,['mysql'] +86237,a prepared statement where in query and sorting a with mysql imagine we have a queryselect from somewhere where id in151825 order by nameand an array of ids to fetch ids array151825with prepared statements it is adviced to prepare one statement and call it multiple timesstmt mysqliprepareselect from somewhere where idforeach ids as id stmtbind paramsi id stmtexec but now i will have to sort the results manually do i have any nice alternatives,"['php', 'mysql']" +86254,combine multiple rows into one space separated string so i have 5 rows like thisuserid col1 a1 b2 c2 d3 ehow would i do query so it will look like thisuserid combined1 a b2 c d3 e,"['sql', 'mysql']" +86273,in python small floats tending to zero i have a bayesian classifier programmed in python the problem is that when i multiply the features probabilities i get very small float values like 25e320 or something like that and suddenly it turns into 00 the 00 is obviously of no use to me since i must find the best class based on which class returns the max value greater valuewhat would be the best way to deal with this i thought about finding the exponential portion of the number 320 and if it goes too low multiplying the value by 1e20 or some value like that but maybe there is a better way,['python'] +86286,c template static member instantiation include mapinclude iostreamtemplate typename tclass a static stdmapint int datapublic a stdcout datasize stdendl data3 4 template typename tstdmapint int atdatastdmapint int achardataachar aint main return 0what is wrong with this without explicit instantiation it breaks at data3 4 explicit instantiation solves the problem but the program breaks after stdcout datasize stdendl what means that the static class template memeber data was instantiated,['c++'] +86288,do explicit instantiations of c class templates instantiate dependent base classes i figured an explicit instantiation request would automatically instantiate all base class members also but i get a linker error unresolved external symbol public void baseintfooint when building this code using visual studio 2008 or 2010note that adding a call to foo inside bar forces the compiler to instantiate baseintbar and the build succeeds so it appears that the compiler has all the necessary information to instantiate fobviously explicitly instantiating baseint in sourcecpp allows the build to succeed but it seems silly to need to explicitly instantiate any dependent base classes whenever explicitly instantiating a derived classis this normal i could not find what the standard says regarding this issueheaderhtemplatetypename tclass base public void footemplatetypename tclass derived public baset public void barsourcecppinclude headerhtemplatetypename tvoid basetfoo templatetypename tvoid derivedtbar thisfoo adding this forces instantiation of footemplate class derivedintmaincppinclude headerhint main derivedint d dfoo linker error unresolved external symbol public void baseintfoointeditit looks like the standard says only members of a class get instantiated by an explicit class instantiation so the linker error is justified in my examplenote that a class is defined by classhead memberspecification and the memberspecification in a class definition declares the full set of members of the class no member can be added elsewhere so members are only between the curly braces and public base class members do not become members of the derived class they are merely accessible from the derived class or by objects of the derived classmy only remaining question is why the standard specifies that explicit instantiation of a class template only instantiates members and not members of base classes my guess is that this allows greater control of what gets explicitly instantiated where someone that is using explicit template class instantiations would most likely have the base class definitions in a different file than the derived class definitions and would explicitly instantiate each separately,['c++'] +86289,what is the difference between linq to xml descendants and elements i have came across both these keywords in the vs intellisense i tried to googling the difference between them and did not get a clear answer which one of these have the best performance with small to medium xml files thanks,"['c#', '.net']" +86303,how to get the active view in an ios application from the app delegate how can i get the currently active view the main view currently being viewed by the user from the app delegate for references sake,"['objective-c', 'ios']" +86309,best way to create a reversed list in python in python what is the best way to create a new list whose items are the same as those of some other list but in reverse order i do not want to modify the existing list in placehere is one solution that has occurred to menew list listreversedold listit is also possible to duplicate old list then reverse the duplicate in placenew list listold list or new list old listnew listreverseis there a better option that i have overlooked if not is there a compelling reason such as efficiency to use one of the above approaches over the other,['python'] +86313,c lnk2019 error unresolved external symbol template clas constructor and destructor referenced in function main update if i include queuecpp in my programcpp it works just fine this should not be necessary righthey all i am using visual studio 2010 and having trouble linking a quickanddirty queue implementation i started with an empty win32 console application and all files are present in the project for verbosity heres the complete code to duplicate my error i realize some of the code may in fact be wrong i have not had a chance to test it yet because i have not yet been able to link itqueuehppifndef error codedefine error codeenum error code success underflow overflowendif error codeifndef queuedefine queuetemplateclass tstruct queue node t data queue node next queue node next null queue nodet pdata data pdata next null queue nodet pdata queue node pnext data pdata next pnext templateclass tclass queuepublic queue error code serve error code appendt item t front queueprivate void rescursive destroyqueue nodet entry queue nodet front rearendif queuequeuecppinclude queuehpptemplate class tqueuetqueue thisfront thisrear nulltemplateclass terror code queuetserve iffront null return underflow queue node temp thisfront thisfront thisfrontnext delete temptemplateclass terror code queuetappendt item queue node temp new queue nodeitem iftemp return overflow ifthisrear null thisrearnext temp thisrear temp return successtemplateclass tt queuetfront ifthisfront null return underflow return thisfrontdatatemplateclass tqueuetqueue thisrescursive destroythisfronttemplateclass tvoid queuetrescursive destroyqueue nodet entry ifentry null thisrecursive destroyentrynext delete entry programcppinclude queuehppint main queueint steve return 0and the errorserror 1 error lnk2019 unresolved external symbol public thiscall queueintqueueintvoid 1queuehqaexz referenced in function main comittedproject2 2project2 2programobj project2 2error 2 error lnk2019 unresolved external symbol public thiscall queueintqueueintvoid 0queuehqaexz referenced in function main comittedproject2 2project2 2programobj project2 2,['c++'] +86331,show pdf in android in my oncreate i do this check check if we have a pdf viewer else bad things happenintent intent new intentintentaction viewintentsettypeapplicationpdflistresolveinfo intents getpackagemanagerqueryintentactivitiesintent packagemanagermatch default onlyif intents null intentssize 0 thisplay message then finishon my htc desire this does not return a match even though i have adobes pdf viewer an answer to this question mentions that adobe may not have any public intents so the above check will obviously return nothingcan anyone verify whether you should be able launch acrobat from an intent or is there some other method or pdf viewer to usethe actual use case is downloading copies of invoices and storing them on local storage using code such as url url new urldata inputstream myinput urlopenconnectiongetinputstream fileoutputstream fos openfileoutputfname contextmode world readable transfer bytes from the input file to the output file byte buffer new byte8192 int length while length myinputreadbuffer 0 foswritebuffer 0 length progressdialogsetprogressi foscloseand then to show read from thisk and call intentopenfileinputfname will throw filenotfoundexceptionfile dir getfilesdir where files are storedfile file new filedir fname new file with our nameintent intent new intentintentaction view urifromfilefileintentsettypeapplicationpdfstartactivityintent,['android'] +86334,convert integer list to int array is there a way to convert a list of integers to array of ints not integer something like list to int without looping through the list and manually converting the intger to int,['java'] +86342,in the c language what does return 0 mean i am dealing with some c code that includesreturn 0what does that mean it is pretty much impossible to google for,['c'] +86351,python complex event processing are there any python alternatives similar to esper java and net that deal with complex event processing cep,['python'] +86360,why java arrays use two different sort algorithms for different types arraysjavas sort method uses quicksort for arrays of primitives and merge sort for arrays of objects i believe that most of time quicksort is faster than merge sort and costs less memory my experiments support that although both algorithms are onlogn so why are different algorithms used for different types,['java'] +86377,using adb logcat with a real phone and not the emulator when i am using the android emulator i can do adb logcat to see output messages log systemoutprintln originated from my code it also shows the stack trace of exceptions which happen during executionbut when i am using a real phone adb logcat does not do show anything i also tried adb d logcat which also does not thisplay anythingis there any way to get it working with the real phone thanksupdatei just tried adb s logcat is the serial number of the device and also got no resultsi tried another adb command to see if anything was working adb s bugreport this printed a lot of stuff example memory info cpu info and some java specific things so it seams that some stuff is working,['android'] +86388,the best way to abstract a javascript library what would be the best way to abstract away any given javascript framework jquery mootools etc that sits on the bottom of the framework stack essentially i would like to have a situation where i could swap out the library do changes only to one layer of the framework not to every module for example and the whole thing could be up and running againso every module should call a framework functions which would then be routed to the library,['javascript'] +86399,is there an onload event for input elements is it possible to trigger a javascript script when an input element or any other html element is rendered this script should be triggered from within the html tag so that we should be able to pass this to the js function,['javascript'] +86411,something wrong with thisregarding a returned value from a function in php for instance somefilephpfunction dosomething do lots of code whatever return something mainfilephpinclude somefilephpdosomething ignored the return value we do not need it herewhat happens when a function in php returns a value but we do not care about it is something wrong with this behavior or should we always get the variable even if well never used it outside the function scope how does php manage it is resources by returning a value that would not be used outside of the function scope,['php'] +86414,mysql join three tables hi i have three tables named student table id name1 ali2 ahmed3 john4 kingcourse tableid name1 physic2 maths3 computer4 chemistrybridgesid cid1 11 21 31 42 12 23 33 44 14 2now to show student name with the course name which he had studied likeresultstudent courseahmed physicahmed mathsahmed computerahmed chemistryali physicali mathsjohn computerjohn chemistryking physicking mathsi build following queryselect sname as student cname as course from student s course c join bridge b on cid bcid order by snamebut it does not return the required resultand what would be for normalized form if i want to find who is manager over otheremployeeid name1 ali2 king3 mak4 sam5 jonmanagemid eid1 21 33 44 5and wants to get resultresultmanager staffali kingali makmak samsam jon,['mysql'] +86421,how do libraries in different programming languages handle date time timestamps durations leapseconds years dsts timezones is there a standard body or a specific normative way how timerelated things should be implemented in practice like icu for unicoderelated tasks or is this currently a besteffort depending on how much effort time and money language and library implementers want to spendis there a specific and complete implementation which could serve as a example for how timerelated things should be handledwhich existing library would you consider as a bad a decent or a good example,"['c#', 'python']" +86437,padding on div border i want to put padding on a css border pull it inside a div away from the edge is this possible using css css3 is fine webkithere is the designi did this by placing a div inside a div then give a border to the inner div i want to make the markup slim as posible so i want to use only one div if posiblethank you,['css'] +86441,php spl autoload register i am trying to take advantage of autoloading in php i have various classes in different directories and so i have bootstrapped the autoloading as followsfunction autoload servicesclass name file services class name php if file existsfile require oncefile function autoload vosclass name file vos class name php if file existsfile require oncefile function autoload printersclass name file printers class name php if file existsfile require oncefile spl autoload registerautoload servicesspl autoload registerautoload vosspl autoload registerautoload printersit all seems to work fine but i just wanted to double check that this is indeed considered acceptable practise,['php'] +86470,how does one write a delete cascade for postgres i am manually constructing a delete cascade statement for postgresi have a transaction and a slice table related as shown below table publicslice column type modifiers id text not null name text referenced by table transaction constraint transaction slice id fkey foreign key slice id references sliceid table publictransaction column type modifiers id text not null slice id text referenced by table classification item constraint classification item transaction id fkey foreign key transaction id references transactionidtable publicclassification item column type modifiers id text not null transaction id text foreignkey constraints classification item transaction id fkey foreign key transaction id references transactionidsay i want to delete all transactions and classification items referenced by the slice whose name is my slice what do i need to write delete from classification item where transaction id delete from transaction where slice id delete from slice where namemy slice,['sql'] +86476,set a timeout for reading stdin is there a way to timeout a reading from stdin in order for the program not to hang for too long read0 var numberofbytes,['c'] +86477,check if a row could be deleted in mysql is there a way i can check if a row potentially could be deleted that it for example is not currently connected through restricted foreign keys to anything else reason i am making an admin page with all the users in the system listed they can always be thisabled but they may also be deleted however they can only be deleted if they are not connected to anything critical and i would like to not having to check that manually if it can be done easily in the databasenote i do not want to actually delete any user i just want to thisplay to the admin that a user could be deleted,['mysql'] +86486,convert nsdate to nsstring with nsdateformatter with timezone without gmt time modifier i am initializing my nsdateformatter thuslynsdateformatter dateformatter nsdateformatter alloc init autoreleasedateformatter setlocalenslocale alloc initwithlocaleidentifieren us posix autoreleasedateformatter setdateformate d m y hhmmss zdateformatter settimezonenstimezone timezoneforsecondsfromgmt0nsdate date nsdate datensstring datestring dateformatter stringfromdatedatedatestring is nowthu 29 jul 2010 145842 gmt0i want to get rid of the 0i am guessing from zone fallback that i might have a localization issue i am working around this right now by removing the 0 manually but that is not idealediti tried a couple of new ways to create the nstimezone but they both produce the same datestringnstimezone timezonewithnamegmtnstimezone timezonewithnameutcnstimezone timezonewithabbreviationgmtnstimezone timezonewithabbreviationutc,['objective-c'] +86488,rails 3 how to get the row number from a model with an order by i am putting together a small app that has a leaderboard concept in it basically the model is just a player name and a current scorewhat i want to do is get the ranking of a specific player and given that new scores are coming in all the time it needs to be dynamic obviously i could just do a normal find with an order by clause and then i would have to loop through each record not very efficient when i could have 10s of rows any suggestions on what approach i should be takinghere is the migration for the tableclass createscores activerecordmigration def selfup create table scores do t tstring player name tinteger current score ttimestamps end end def selfdown drop table scores endendeditas an example so i have the followingscoreselectplayer name current scorelimit20 score player name keith hughes current score 9 score player name diane chapman current score 8 score player name helen dixon current score 4 score player name donald lynch current score 9 score player name shawn snyder current score 2 score player name nancy palmer current score 9 score player name janet arnold current score 1 score player name sharon torres current score 9 score player name keith ortiz current score 5 score player name judith day current score 3 score player name gregory watson current score 7 score player name jeremy welch current score 3 score player name sharon oliver current score 7 score player name donald lewis current score 7 score player name timothy frazier current score 7 score player name john richards current score 1 score player name carolyn white current score 4 score player name ronald smith current score 2 score player name emily freeman current score 9 score player name gregory wright current score 2how can i work out the ranking of donald lewis,['ruby-on-rails'] +86508,android calendar view for date picker i am writing my first app and i have a question about datepickermy app requires the user to input a date the most userfriendly way would be to popup a calendarlike widget that thisplays the current month like a calendar grid something like thisi want to use that in place of the datepicker interface which has month day and year fields each with an up and down button to incrementdecrementis this type of functionality built into any android widget or view or would i have to design my own custom component to do this i figured this would already exist seeing how much this type of ui is used so frequently in nonmobile apps and web pagesthanks,['android'] +86521,javascript invalid quantifier in regex the regex is constructed on the fly but i have output it to firebug138nthe error isinvalid quantifier ni am not sure where to startthe actual code isvar re topregexpvar regex new re1 len n gmupdateper bennor mccarthys instructions i changed the code to this var regex new re1 len n gmfirebug still tells me thisinvalid quantifier nbreak on this error var regex new re1 len n gm another updatelooks like i had to double slash it and this solved the problemfinal codevar regex new re1 len n gm,['javascript'] +86527,efficient erlang port driver i want to spawn erlang processes that will communicate with a c program through a port driveras spawning many of these processes can be inefficient can i spawn one erlang process that receives messages and queue these messages for processing with the c programas this c program starts to wait for incoming jobs will it blockwhats the best strategyarchitecturethanks,['c'] +86540,how do i make a div have the same width and height of its content let us say i have an img element inside a div how do i make the div have the same width and height of its content using css,"['html', 'css']" +86550,how to see if a reader is at eof my code needs to read in all of a file currently i am using the following codebufferedreader r new bufferedreadernew filereadermyfilewhile rready string s rreadline do something with srcloseif the file is currently empty though then s is null which is no good is there any reader that has an ateof method or equivalent,['java'] +86568,how to apply css to iframe content there are a few threads on this site thiscussing this topic but none of the offered solutions worked for mecan anyone please provide a solution that you tried and you know that it worksthanks in advance,['css'] +86583,is there any concept in c like reflector in net i like to get code from c dll i know we easily get from net dll by reflector is there any method available in c for thisthanks in advance,"['.net', 'c++']" +86590,zend framework json output in controller i am generating a special form by id passed from ajax form output is json form creates finely but my problem is to show this json in view howthank you,['php'] +86594,when to use parallelfor i have recently moved to cnet 4i love parallelfor but not sure when to use and when not toi know that when order is not important for me i will use itbut are there any tests regarding the overhead of working with parallels meaning if my loop runs only 10 times and performs very little logic should i avoid parallels are there any thumb rules,['.net'] +86606,covariant typeparameter in scala needs to be invariant in java interface i have got a trait that looks like this some further information can be found at this related question by myself although i do not think it is needed for this questiontrait extractorab def extractdab lots of other thingsto use this in an existing java framework i would like this extractor to either have a function that returns a comparatorb being javautilcomparator or even better extend comparatora now that poses a problem because comparators type parameter is ought to be invariant while a is contravariant and b is covariantso i get errors like thisscala import javautilcomparatorimport javautilcomparatorscala trait extractorab extends comparatoraconsole6 error contravariant type a occurs in invariant position in type abjavalangobject with javautilcomparatora of trait extractor trait extractorab extends comparatora scala trait extractora b def compcomparatorb console7 error covariant type b occurs in invariant position in type javautilcomparatorb of method comp def compcomparatorb do you see any way out of this or is this just one of those cases where using java generics in scala hurts,['java'] +86630,cannot add value to the java collection with wildcard generic type why this code does not compile parent is an interfacelist extends parent list parent p factoryget returns concrete implementationlistset0 p fails here setint extends parent cannot be applied to int parent,['java'] +86637,multiline label in aspnet i want to use a multiline label but as the control is browser dependent even on setting the height width and wrap properties of the label control i am unable to thisplay multiline text it does not support every browser in the same way,['asp.net'] +86645,is there a benefit to using a return statement that returns nothing i am refactoring a large javascript document that i picked up from an open source project a number of functions use inconsistent return statements heres a simple example of what i meanvar func functionparam if param return do stuff return truesometimes the functions return boolean sometimes strings or other things usually they are inconsistently paired with a simple return statement inside of a conditionalthe problem is that the code is complex it is a parser that uses a multitude of unique regex matches creates and destroys dom nodes on the fly etc preliminary testing shows that in the above example i could change the return statement to become return false but i am concerned that i may not realize that it had a negative impact ie some feature stopped working on the script until much laterso my questions is there a benefit to using a blank return statement could this have been intentionally coded this way or was it just lazy can i change them all to return false or return null or do i need to dig through every call and find out what they are doing with the results of those functions,['javascript'] +86664,capture member variable by value how would i catch a member variable by value when using c11 lambda expressionsusing the my member syntax does not seem to work and implicit capture uses the this pointer what is need is a way to explicitly specify capture type of member variables is that possiblemy workaround for now isvoid member function stdshared ptrmy member class my member copy my member this should not be necessary stdasync stdcout my member copy stdasync stdcout my member wrong my member could be potentially out of scope,['c++'] +86678,winforms double buffering i added this to my forms constructor codethissetstylecontrolstylesallpaintinginwmpaint controlstylesuserpaint controlstylesdoublebuffer truebut it still shows ugly artifacts when it loads the controls whenever they change the form and its components change need updating often what do i need to do differently,['c#'] +86700,can i get the size of a struct field wo creating an instance of the struct it is trivial to get the size of a structs field in c if you have an instance of the struct eg uncompiledtypedef struct foo int bar bool baz foo foo sstoreinsomethingsbar sizeofsbar easy as pienow i can still do something like this but with the interface i am implementing i get a bool that indicates what the state of a specific bit in a bitfield should be i would be creating the struct solely to get the size of the data member is there a way to indicate to the compiler that it should use the size of a structs field without creating an instance of the struct it would be the philosophical equivalent ofsetbitbool val storeinsomething bitfield position constant position of bit being set val true 1 false 0 sizeoffoobar this is of course illegal the method i have been told i must use reqs the size of the target fieldcreating the struct on the stack should be fast and cheap but i suspect i will get dinged for it in a code review so i am looking for a better way that does not introduce an addl maintenance burden such as defines for sizes,['c++'] +86702,is it possible to access rails guides for rails 23 it used to be that the ruby on rails guides for version 30 were at and the guides for version 23 were at now that version 3 has been released its guides have been moved to the main urlis there any way to access the guides for rails 23,['ruby-on-rails'] +86706,square of a number being defined using define i was just going through certain codes which are frequently asked in interviews i came up with certain doubts if anyone can help me regarding thisi am totally confused on this now includestdiohincludeconiohdefine squarex xxmain int ij i4square4 j64square4 printfn di printfn dj printfn dsquare4 getchoutput is 4 64 16i am wondering why did square4 return 1 when i divided it i mean how can i get the value 4 and 64 when i divide it but when used directly i get 16,['c'] +86718,how to deal with circular references if i have those two projectsmycompanyerpbillingmycompanyerpfinancialbilling askssends information to financial and viceversa both are too big so i do not want to put them in a single projectvisual studio does not allow circular references how would you deal with that,['.net'] +86719,best way to get a glow effect windows phone 7 i am messing around with the windows phone 7 sdk and i am trying to make the screen look like an old fashion digital thisplay right now i am trying to figure out how to make the text glow like one of those cool digital clocks this is the sort of thing i would assume you would look in to using shaders for but it seems that shaders are thisabled for use on the windows phone 7 os any ideas to be more specific i want the text to look as though it is a light source and have the color bleed out slightly from the actual font,['c#'] +86725,advice on creating a microframework in javascript i would like to know what are the steps required to create a framework on top of nodejsi believe this can be a good way to learn that is why i am doing thisi have been checking other microframeworks and bigger frameworks but i am not being able to understand where to start i would like your advice on this thank youedit mvc framework like sinatra merb rails,['javascript'] +86738,why would imageviewsetimageuri work in android 22 but not 21 i am thisplaying images and some text in a list view with an adapter the images are pulled from the web then cached locally and thisplayed the images are already small 60px square and i know their size so i am using the advice from here suggesting i use setimageuri instead of decoding the bitmap the class that does the work is a modified version of fedors imageloaderthe code attaches a stub drawable to the imageview until the desired image is downloaded from the web then loads the cached file from the sdcard in android 22 this works just fine it is fast and i do not get oom crashes on 21 though i get the following error0915 110452993 infosystemout240 resolveuri failed on bad bitmap uri filesdcardandroiddatacomexamplemyappcache4164137the imageloader class is as followslicensed to the apache software foundation asf under oneor more contributor license agreements see the notice filethistributed with this work for additional informationregarding copyright ownership the asf licenses this fileto you under the apache license version 20 thelicense you may not use this file except in compliancewith the license you may obtain a copy of the license atunless required by applicable law or agreed to in writingsoftware thistributed under the license is thistributed on anas is basis without warranties or conditions of anykind either express or implied see the license for thespecific language governing permissions and limitationsunder the license public class imageloader the simplest inmemory cache implementation this should be replaced with something like softreference or bitmapoptionsinpurgeablesince 16 private hashmapstring uri cachenew hashmapstring uri private file cachedir public imageloadercontext context make the background thead low priority this way it will not affect the ui performance photoloaderthreadsetprioritythreadnorm priority1 find the dir to save cached images if androidosenvironmentgetexternalstoragestateequalsandroidosenvironmentmedia mounted cachedirnew fileandroidosenvironmentgetexternalstoragedirectoryandroiddatacomdroidiconlauncherproiconscache else cachedircontextgetcachedir ifcachedirexists cachedirmkdirs final int stub idrdrawableloading public void thisplayimagestring url activity activity imageview imageview int scalesize ifcachecontainskeyurl imageviewsetimageuricachegeturl else queuephotourl activity imageview scalesize imageviewsetimageresourcestub id private void queuephotostring url activity activity imageview imageview int scalesize this imageview may be used for other images before so there may be some old tasks in the queue we need to thiscard them photosqueuecleanimageview phototoload pnew phototoloadurl imageview scalesize synchronizedphotosqueuephotostoload photosqueuephotostoloadpushp photosqueuephotostoloadnotifyall start thread if it is not started yet ifphotoloaderthreadgetstatethreadstatenew photoloaderthreadstart private uri geturistring url int scalesize ifurl i identify images by hashcode not a perfect solution good for the demo try string filenamestringvalueofurlhashcode file fnew filecachedir filename from sd cache iffexists uri b urifromfilef systemoutprintlnftostring return b from web try uri bitmapnull inputstream isnew urlurlopenstream outputstream os new fileoutputstreamf utilscopystreamis os osclose bitmap urifromfilef systemoutprintlnftostring return bitmap catch exception ex exprintstacktrace return null else return null task for the queue private class phototoload public string url public imageview imageview public int scalesize public phototoloadstring u imageview i int ss urlu imageviewi scalesizess photosqueue photosqueuenew photosqueue public void stopthread photoloaderthreadinterrupt stores list of photos to download class photosqueue private stackphototoload photostoloadnew stackphototoload removes all instances of this imageview public void cleanimageview image forint j0 jphotostoloadsize ifphotostoloadgetjimageviewimage photostoloadremovej else j class photosloader extends thread public void run try whiletrue thread waits until there are any images to load in the queue ifphotosqueuephotostoloadsize0 synchronizedphotosqueuephotostoload photosqueuephotostoloadwait ifphotosqueuephotostoloadsize0 phototoload phototoload synchronizedphotosqueuephotostoload phototoloadphotosqueuephotostoloadpop uri bmpgeturiphototoloadurl phototoloadscalesize cacheputphototoloadurl bmp ifstringphototoloadimageviewgettagequalsphototoloadurl urithisplayer bdnew urithisplayerbmp phototoloadimageview activity aactivityphototoloadimageviewgetcontext arunonuithreadbd ifthreadinterrupted break catch interruptedexception e allow thread to exit photosloader photoloaderthreadnew photosloader class urithisplayer implements runnable uri uri imageview imageview public urithisplayeruri u imageview iuriuimageviewi public void run file f new fileurigetpath iffexists imageviewsetimageuriuri else imageviewsetimageresourcestub id public void clearcache clear memory cache cacheclear clear sd cache file filescachedirlistfiles forfile ffiles fdelete here is one of the adapters that implements this imageloaderpublic class coloradapter extends arrayadaptercolor private activity activity private int resource private string response private context context public imageloader imageloader public coloradapteractivity a context context int resource listcolor items supercontext resource items thisresourceresource imageloadernew imageloadercontext activity a override public view getviewint position view convertview viewgroup parent color color getitemposition string minflater contextlayout inflater service layoutinflater inflater inflater layoutinflatergetcontextgetsystemserviceminflater viewholder holder ifconvertviewnull convertview inflaterinflaterlayoutlistcolors parent false holdernew viewholder holdertxtnametextviewconvertviewfindviewbyidridtxtname holdertxtusertextviewconvertviewfindviewbyidridtxtuser holderimgcolorimgimageviewconvertviewfindviewbyidridimgcolorimg convertviewsettagholder else holderviewholderconvertviewgettag holdertxtnamesettextcolorgetname holdertxtusersettextdockgetuser holderimgcolorimgsettagcolorgeticonurl imageloaderthisplayimagecolorgeticonurl activity holderimgcolorimg 84 return convertview class viewholder textview txtname textview txtuser imageview imgcolorimg,['android'] +86740,converting decimal to int in c why percentage returns 0 when rate 0085 for example int percentage intrate100,['c#'] +86746,how serious is this new aspnet security vulnerability and how can i workaround it i have just read on the net about a newly thiscovered security vulnerability in aspnet you can read the details herethe problem lies in the way that aspnet implements the aes encryption algorithm to protect the integrity of the cookies these applications generate to store information during user sessionsthis is a bit vague but here is a more frightening partthe first stage of the attack takes a few thousand requests but once it succeeds and the attacker gets the secret keys it is totally stealthythe cryptographic knowledge required is very basicall in all i am not familiar enough with the securitycryptograpy subject to know if this is really that seriousso should all aspnet developers fear this technique that can own any aspnet website in seconds or whathow does this issue affect the average aspnet developer does it affect us at allin real life what are the consequences of this vulnerability and finally is there some workaround that prevents this vulnerabilitythanks for your answersedit let me summarize the responses i gotso this is basically a padding oracle type of attack sri provided a great explanation about what does this type of attack mean here is a shocking video about the issueabout the seriousness of this vulnerability yes it is indeed serious it lets the attacker to get to know the machine key of an application thus he can do some very unwanted thingsin posession of the apps machine key the attacker can decrypt authentication cookieseven worse than that he can generate authentication cookies with the name of any user thus he can appear as anyone on the site the application is unable to differentiate between you or the hacker who generated an authentication cookie with your name for himselfit also lets him to decrypt and also generate session cookies although this is not as dangerous as the previous onenot so serious he can decrypt the encrypted viewstate of pages if you use viewstate to store confidental data you should not do this anywaysquite unexpected with the knowledge of the machine key the attacker can download any arbitrary file from your web application even those that normally cannot be downloaded including webconfig etchere is a bunch of good practices i got that do not solve the issue but help improve the general security of a web applicationyou can encrypt sensitive data with protected configurationuse http only cookiesprevent dos attacksnow let us focus on this issuescott guthrie published an entry about it on his blogscottgus faq blog post about the vulnerabilityscottgus update on the vulnerabilitymicrosoft has a security advisory about itunderstanding the vulnerabilityadditional information about the vulnerabilitythe solutionenable customerrors and make a single error page to which all errors are redirected yes even 404s scottgu said that differentiating between 404s and 500s are essential for this attack also into your application error or erroraspx put some code that makes a random delay generate a random number and use threadsleep to sleep for that long this will make it impossible for the attacker to decide what exactly happened on your serversome people recommended switching back to 3des in theory if you do not use aes you do not encounter the security weakness in the aes implementation as it turns out this is not recommended at allsome other thoughtsseems that not everyone thinks the workaround is good enoughthanks to everyone who answered my question i learned a lot about not only this issue but web security in general i marked mikaels answer as accepted but the other answers are also very useful,"['asp.net', '.net']" +86747,pass variable on import let us say you have some timeconsuming work to do when a moduleclass is first imported this functionality is dependent on a passed in variable it only needs to be done when the moduleclass is loaded all instances of the class can then use the resultfor instance i am using rpy2import rpy2robjects as robjectspath to r source i need to pass thisrobjectsrsourcepath to r source chdir true this takes timeclass someclass def init self acurve self curve acurve def processcurveself robjectsrsomerfuncrobjectsfloatvectorself curveam i stuck creating a module level function that i call to do the workimport someclasomeclasourcerstuffpath to r sourcex someclasomeclass1234etci gotta be missing something here thanks,['python'] +86749,how to reverse color map image to scalar values how do i invert a color mapped imagei have a 2d image which plots data on a colormap i would like to read the image in and reverse the color map that is look up a specific rgb value and turn it into a float for exampleusing this image imagesmri demopngi should be able to get a 440x360 matrix of floats knowing the colormap was cmjetfrom pylab import imreadimport matplotlibcm as cmaimreadmri demopngbcolormap2floatacmjet tricky part,['python'] +86752,port forwarding on windows 7 how do i redirect an incomming request on port x to localhosty on windows 7development server vs 2008 only allow access from localhost which isnt good enough i need to test my app from various computers,"['c#', 'asp.net']" +86767,ejb testing strategies i am working on a java ee 6 application when i started out i was writing tests for my ejb classes by manually instantiating the ejb then manually adding the members that normally get provided by dependency injection as the application gets more complicated i find that this approach just does not cut it so i would like to be able to start my own ejb container in the test framework so it can manage my beans whats the best way to approach this i have heard of javaxejbembeddableejbcontainer are there other optionsi am using glassfish 3 and building with maven if that makes any difference,['java'] +86789,setting up annotation driven transactions in spring in configuration class so in the latest version of spring we are able to use the configuration annotation to setup our configurations for spring now in javaconfig it is possible to use the annotationdriventx annotationdriventx reference link annotation to setup transactions in our config class but since javaconfig has been decommissioned i was wondering if anyone knew how to setup something similar without javaconfig and without needing to add anything to the applicationcontextxml here is what i basically have for my config classconfigurationimportresourceconfigapplicationcontextxmlpublic class config public bean datasource datasource get and return datasource public bean service1 getservice1 return service1impl and i would like to make service1 transactional if anyone has any ideas on how to do this or if this is just not possible please let me know thanks,['java'] +86791,get part of a string using jquery html codediv idblockid45divhow can i get number 45 of string using jquery,['jquery'] +86792,most efficient way to create thumbnails i have a huge volume of thumbnailing to do currently i am using imagemagick but it is proving too inefficient it is too slow uses too much cpumemory etci have started to evaluate graphicsmagick which i expected to get wow results from i did not get them can someone take a quick look at my benchmark script does simple speed and file size comparison only no cpu and memory checks yetheres a sample output i gotgm convert took 750039 seconds to execute 10 iterationsconvert took 831421 seconds to execute 10 iterationsaverage filesize of gm convert 144588 bytesaverage filesize of convert 81194 bytes graphicsmagick is not that much faster and the outputted file sizes are significantly higher than imagemagick,['php'] +86793,android open contextmenu on short click pass item clicked details lvsetonitemclicklistenernew onitemclicklistener override public void onitemclickadapterview parent view view int position long id textview text textview viewfindviewbyidridbtitle registerforcontextmenutext viewshowcontextmenu override public void oncreatecontextmenucontextmenu menu view v contextmenuinfo menuinfo superoncreatecontextmenumenu v menuinfo textview text textview vfindviewbyidridbtitle charsequence itemtitle textgettext menusetheadertitleitemtitle menuinflater inflater getmenuinflater inflaterinflatermenucontext menu menu helloi am trying to open a contextmenu on short item clicki have managed to do so only if i add registerforcontextmenugetlistview somewhere but this also triggers contextmenu on long click which i do not want to happentried viewshowcontextmenu but it does not do anything unless i add the registerforcontextmenugetlistview tried registering the clicked item first and then call the showcontextmenu but did not do anything as wellalso i want to get the clicked item image text so i can use them in the contextmenuappreciate the help,['android'] +86796,why does an insert query occasionally take so long to complete this is a pretty simple problem inserting data into the table normally works fine except for a few times where the insert query takes a few seconds i am not trying to bulk insert data so i setup a simulation for the insert process to find out why the insert query occasionally takes more than 2 seconds to run joshua suggested that the index file may be being adjusted i removed the id primary key field but the delay still happensi have a myisam table daniel test insert this table starts completely emptycreate table if not exists daniel test insert id int unsigned auto increment not null value str varchar255 not null default value int int unsigned default 0 not null primary key id i insert data into it and sometimes a insert query takes 2 seconds to run there are no reads on this table only writes in serial by a single threaded programi ran the exact same query 10 times to find why the query occasionall takes a long time so far it appears to be a random occurrencethis query for example took 4194 seconds a very long time for an insertquery insert into daniel test insert set value int12345 value strafjdaldjsf aljsdfl ajsdfljadfjalsdj fajd as f ran for 4194 secondsstatus duration cpu user cpu system context voluntary context involuntary page faults minorstarting 042 0 0 0 0 0 checking permissions 024 0 0 0 0 0 opening tables 024 010 0 0 0 0 system lock 022 0 0 0 0 0 table lock 020 0 0 0 0 0 init 029 0 0 1 0 0 update 4067331 12151152 5298194 204894 18806 477995 end 094 0 0 8 0 0 query end 033 0 0 1 0 0 freeing items 030 0 0 1 0 0 closing tables 0125736 0278958 0072989 4294 604 2301 logging slow query 099 0 0 1 0 0 logging slow query 0102 0 0 7 0 0 cleaning up 035 0 0 7 0 0this is an abbreviated version of the show profile command i threw out the columns that were all zeronow the update has an incredible number of context switches and minor page faults opened tables increases about 1 per 10 seconds on this database not running out of table cache spacestatsmysql 5089hardware 32 gigs of ram 8 cores 266ghz raid 10 scsi hardthisks scsi i have had the hard drives and raid controller queried no errors are being reportedcpus are about 50 idleiostat x 5 reports less than 10 utilization for hardthiskstop report load average about 10 for 1 minute normal for our db machineswap space has 156k used 32 gigs of rami am at a loss to find out what is causing this performance lag this does not happen on our lowload slaves only on our high load master this also happens with memory and innodb tables does anyone have any suggestions this is a production system so nothing exotic,"['sql', 'mysql']" +86799,how do i read the public key from a signed c exe i am signing a dot net exe using signcodeexe with an spcpvk combothe file needs to read its own public key at runtime in order to verify some data i have gone down a number of different avenuesi have tried x509certificate executingcert x509certificatecreatefromsignedfileexeexecutingcert is then null i am guessing signcode is not creating an x509 signed file though if there is a switch to change that i am happy to go that wayeditedturns out the above does work i had my null check backwards assembly asm assemblygetexecutingassemblystring exe asmlocationx509certificate executingcert x509certificatecreatefromsignedfileexe if executingcert null consolewritelineassembly is signed byte assemblykey executingcertgetpublickey,['c#'] +86801,data warehousing arbitrary fields in our application we support userwritten pluginsthose plugins generate data of various types int float str or datetime and those data are labeled with bunches of metadata user current directory etc as well as three freetext fields metricname var1 var2 now we have several years of this data and i am trying to design a schema which allows very fast access to those metrics in an analytical fashion charts and stuff this is easy as long as there are only a few metrics were interested in but we have a large number of different metrics at different granularities and wed like to store useradded data to allow for later analysis possibly after a schema changeexample data please keep in mind this is very simplified basedir user trialno project metricvalue metricname var1 var2 pathtome me 0 domino 20 errors core dumb pathtome me 0 domino 986 tempuratur body someotherpwd oneguy 223 farq 443 manmonths waste mythical someotherpwd oneguy 224 farq 0 albedo nose polarbear pathtome me 0 domino 702 tempuratur room pathtome2 me 2 domino 2020 errors misc filtered anyone can add a parser plugin to start measuring a airspeed metric and wed like our analisys tools to just work on that new metricupdateconsidering that many of the metricnames are wellknown beforehand i can satisfy my requirements if i can enable analysis on those metrics and simply store the other useradded metrics we can accept the fact that new metrics would not be available for heavyduty analysis without an edit to the schema what do you guys think of this solutioni have divided our metrics into three fact tables one for facts that do not need a metrictopic one for ones that do and one for all the other metrics including unexpected onesfor the bountyi will accept any critique which shows how to make this system more functional or brings it into closer alignment with industry bestpractices references to literature gives added weight,['mysql'] +86807,examples of practical javascript object oriented design patterns what object oriented design patterns do you use in your applications javascript and why feel free to post code even if there is no formal design pattern attached to it i have written plenty of javascript but i have not applied much object orientated patterns to what i am doing and i am sure i am missing a lot,"['javascript', 'jquery']" +86808,javascript oo syntax there seem to be many different ways of doing oo in javascripti likefunction classaclassaprototype somefuncfunctionabc otherfuncfunctionvar cnew classaand have never used features beyond what this provides despite being a proficient ooer i suspect this is old fashioned because every so often i see new spangled variants and it makes me wonder if i am choosing the best approach for instance you can do magic in the constructor method to create private variables and accessor methods something i believed until relatively recently to be impossible what about subclassing i wouldnt know how to achieve this but it must have some sort of common pattern by nowhow do you do it and why,['javascript'] +86809,java how to check current perm permgen size yesterday when i was running the weblogic application server 11g installer i encountered a outofmemory error so i googled for the answerjava xms256m xmx512m xxpermsize128m xxmaxpermsize256m jar wls1032 genericjareverything worked however when i think twice about the solution i might have made a mistake how could i know the current settings of those i certainly need to check their values before overriding them rightany thoughts related link people in another thread on so suggested trial and error approach which is not idealmany thanks in advance,['java'] +86817,how do you convert a pil image to a django file i am trying to convert an uploadedfile to a pil image object to thumbnail it and then convert the pil image object that my thumbnail function returns back into a file object how can i do this,['python'] +86821,android adt plugin does not show up in eclipse i am using windows 7 and installed the 64 bit version of eclipse 352 i then installed the android adt plugin but when i try to configure it in the windows preferences dialog the android plugin does not show up in the left pane instead i see ddms this prevents me from specifying the location of the android sdk unless there is another way to give me the appropriate templates and suchsomeone posted a fix to this that includes setting the permissions of eclipse but that did not work for me i tried installing the android plugin from both online installation thru the url install and the offline archive method,['android'] +86833,how can i make this code pythonic so i have this code for an object that object being a move you can make in a game of rock papers scissornow the object needs to be both an integer for matching a protocol and a string for convenience of writing and viewingclass move def init self setmove selfnumtoname 0rock 1paper2scissors selfnametonum dictreversedpairing for pairing in selfnumtonameitems if setmove in selfnumtonamekeys selfmmovesetmove else selfmmoveselfnametonumgetsetmove make it to a number def defeatsself return moveselfmmove13 def losestoself return moveselfmmove13 def tieswithself return self operator overloading def eq ab return ammovebmmove def gt ab return adefeatsb def lt ab return alosestob def ge ab return ab or ab def le ab return ab or ab def str self return selfnumtonamegetselfmmove def int self return selfmmovenow i am kinda new to python coming from a c and java backgrounda big thing in python is that there is only one correct way to do somethinganother thing is not worrying about typei am pretty explicitly worrying about type hereso i am not sure what the correct way to handle these objects isat the moment i have an object which an be one of any 3 types or more but i am not sure what that would domaybe instead i should be used the objects of different classes and make them singletonsalso my object are currently modifiable after creation which is a bad thing in my mindso is this code pythonic and how can i make it more eleganti figure this is a good example to use to help me work out what makes good python code sorry if it seems a bit open ended,['python'] +86844,practical example of polymorphism can anyone please give me a real life practical example of polymorphism my professor tells me the same old story i have heard always about the operator ab c and 22 4 so this is polymorphism i really cannot associate myself with such a definition since i have read and reread this in many bookswhat i need is a real world example with code something that i can truly associate with for example here is a small example just in case you want to extend it class personobject def init self name selfname name class studentperson def init self name age superstudent self init name selfage age,['python'] +86863,conversion from long to double in java is there any way to convert a long data type to double or doublefor example i need to convert 152451l to a double data type,['java'] +86878,rails 3 generators git option in rails 2x i could pass on a git option to scriptgenerate to add files to git automatically after creation however i have been unable to find such an option or configuration in rails 30has this been removed or am i missing something i tried researching this for a while but i am unable to find any referencethanksprateek,['ruby-on-rails'] +86893,nsdate for first day of the month this is quite a simple concept but as of yet i have been unable to find an elegant and calendar locale independent solution i need to find the first day of the month for an arbitrary nsdate for example given an arbitrary nsdate arbitrarydate another nsdate object will be returned let us call this firstdayofmonthdate which represents the first day of the month in arbitrarydate the time component does not matter as i just need the nsdate object for the first day of the month although for neatness it would be useful if the time was just zeroed outthanks in advance for any assistance,['iphone'] +86906,converting a mysql result object to associative array codeigniter i am trying to get a database query which is an object converted to an associative array so that i can use it in the calendar class in codeigniterthis is my modelphpclass get diary model extends model function getalldiariesyearmonth data thisdbqueryselect day and entry from diary where monthmonth and yearyear the entries for the relevant month and year foreachdataresult array as row return result as assoc array to use in calendar echo rowday echo rowentry return data and this is the error i getatal error cannot use object of type ci db mysql result as array in cwampwmmsystemlibrariescalendarphp on line 219any ideas,"['php', 'mysql']" +86922,is that possible to thisplay divs next to each other without floating i want to put several divs next to each other in one row all divs have the same heighthere is how this can be done using float leftcan this be done without using float,"['css', 'html']" +86930,using boostlock guard for simple shared data locking i am a newcomer to the boost library and am trying to implement a simple producer and consumer threads that operate on a shared queue my example implementation looks like thisinclude iostreaminclude dequeinclude boostthreadhppboostmutex mutexstddequestdstring queuevoid producer while true boostlock guardboostmutex lockmutex stdcout producer pushing string onto queue stdendl queuepush backstdstringtest void consumer while true boostlock guardboostmutex lockmutex if queueempty stdcout consumer popped string queuefront from queue stdendl queuepop front int main boostthread producer threadproducer boostthread consumer threadconsumer sleep5 producer threaddetach consumer threaddetach return 0this code runs as i expect but when main exits i getusrincludeboostthreadpthreadmutexhpp45 boostmutexmutex assertion pthread mutex destroym failedconsumer popped string test from queueabortedi am not sure if the output from consumer is relevant in that position but i have left it inam i doing something wrong in my usage of boost,['c++'] +86949,significance of sleep0 i used to see sleep0 in some part of my code where some infinitelong while loops are available i was informed that it would make the timeslice available for other waiting processes is this true is there any significance for sleep0,['c++'] +86960,create a delimitted string from a query in db2 i am trying to create a delimitted string from the results of a query in db2 on the iseries as400 i have done this in tsql but cannot find a way to do it herehere is my code in tsql i am looking for an equivelant in db2declare a varchar10select a coalescea description descriptionfrom apcheckbooksselect aif the descriptions in my table look like thisdesc 1 desc 2 desc 3then it will return thisdesc 1 desc 2 desc 3,['sql'] +86967,gwtuibinder how to find the main css file with i am trying to build a gwt website with uibinder it is cool it works but i have a problem with uistylemy project is mavenized i use the gwtmavenplugin archetypethe applicationhtml and applicationcss files are in srcmainresourcescomfoobarpublicthe page i am trying to style is in srcmainjavacomfoobarclient page1java and page1uixmli can use a css file if it is in the same package with uistyle srcpage1css but i would like to target the applicationcss so i could avoid having the same styles in each css file in each packagei tried different relative paths and the applicationcss is never foundis there someone out there who had the same problem and would care to help me thanks,['css'] +86979,array of indexes to array of ranges ranges in ruby are pretty cool i end up with arrays such as this generanges 23425 500510 16401653and subsequently have to remove bits of them for that igenepositions generangescollect range rangeentries flatten 500 501 502 503 504 505 506 507 508 509 510 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653they get manipulated so some numbers get excluded and others may be added i may end up with this505 506 507 600 601 602 603 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654how can i convert this back into a compact array of ranges it seems that the inverse function should exist i would expect it to return something like this505507 600603 16431654thanks,['ruby'] +86982,where does xcode take applications identifier from i think my head soon explodei have been working on my application for some time and finally git an iphone for testing on device now i am trying to run my app on iphone but cannot do it i have done all necessary steps but getting an error berorcode sign error a valid provisioning profile matching the applications identifier comyourcompanymyproject could not be foundmy provisionign profile is called xcommynamein infoplist i changed bundle identifier to commynamemyapplicationmy project name is myproject because i cannot change it but my target and executables called myapplicationi have checked all setting and cannot even find this yourcompany anywherebut still getting this errorwhere need i seekthank you,['iphone'] +86983,c what will i miss if i start with net 20 i got a book named pro c 2005 and the net 20 platform third edition by andrew troelseni am wondering whether i should buy the pro c 2010 and the net 4 platform fifth edition instead since the latest version of net is 40 if i learn c based on this old book do i miss some critical parts of the c language or i can start with this book and learn new net 40 features with other resourcesthank you,['c#'] +86989,how to create a completely custom dialoguepopup in android change overlay colour and dialogue window layout i would like to completely reskin the default dialogue component in android specifically i would like to do thischange the semitransparent overlay background from the default black to a semitransparent whitechange the dialogue window byremoving the default windowed frame borderand replacing it with a layoutdefined in xml it is just going to bea borderless graphic with floatingbuttons no actual framei have seen tutorials about creating a custom layout for within the dialogue box eg but i have not seen anything regarding changing the colour of the overlay andor completely customizing the dialogue window that pops up and turning it more into an overlay with no window,['android'] +86990,when is extern c necessary in c in windows as we know that we can use c functions directly in c when is extern c necessary then,"['c++', 'c']" +86996,retrieve specific hash tags value from url in raw javascript how would one go about checking that a specific hash tag exists in a url then grab the valueexample hashtag2value2i want to be able to grab the value of either hashtag1 or hashtag2,['javascript'] +87007,draw part of a circle for an iphone application i want to draw a circle that is only for an x percentage filledsomething like thisi have no problems calculating the radius the degrees or the radians that is no problem also drawing the circle is already done but how do i get the iphone sdk to draw the part that is filledi can draw a rectangle that size but not part of a circlei just want to draw that on a a normal contexthope someone can give me any pointers here,"['iphone', 'objective-c']" +87009,selecting first td in the first table with css 3 say for example i havediv idcontainer table tr tdtd tdtd tr tr tdtd tdtd tr table table tr tdtd tdtd tr tr tdtd tdtd tr tabledivand td width10px height10px what i want to do is apply a style to the first td of the first tablei would have expectedcontainer tablefirstchild tdfirstchild background redhowever it does not work please advise,['css'] +87019,can static local variables cut down on memory allocation time suppose i have a function in a single threaded program that looks like thisvoid fsome arguments char buffer32 some operations on bufferand f appears inside some loop that gets called often so i would like to make it as fast as possible it looks to me like the buffer needs to get allocated every time f is called but if i declare it to be static this wouldnt happen is that correct reasoning is that a free speed up and just because of that fact that it is an easy speed up does an optimizing compiler already do something like this for me,['c++'] +87034,javascript sort array and return an array of indicies that indicates the position of the sorted elements with respect to the original elements suppose i have a javascript array like so var test b c d ai want to sort the array obviously i can just do this to sort the arraytestsort now test is a b c dbut what i really want is an array of indices that indicates the position of the sorted elements with respect to the original elements i am not quite sure how to phrase this so maybe that is why i am having trouble figuring out how to do it if such a method was called sortindices then what i would want isvar indices testsortindicesat this point i want indices to be 3 0 1 2a was at position 3 b was at 0 c was at 1 and d was a 2 in the original array hence 3 0 1 2one solution would be to sort a copy of the array and then cycle through the sorted array and find the position of each element in the original array but that feels clunky is there an existing method that does what i want if not how would you go about writing a method that does this,['javascript'] +87043,how to create and initialize safearray of doubles in c to pass to c my c method needs to be invoked from coriginally my c method takes a parameter of type double but when calling from c it becomes a safearrayin c i need to take data from an array of doubles and populate a safearray i have not found any sample code to do thisany help is appreciated,"['c#', 'c++']" +87044,use ant for running program with command line arguments my program getting command line arguments how can i pass it when i use ant,['java'] +87064,how to suppress the division by zero error and set the result to null for the whole application how to suppress the division by zero error and set the result to null for the whole application by saying for the whole application i mean it is not for a single expression instead whenever a division by zero error occurs the result is set to null automatically and no error will be thrown,['php'] +87068,undefined method to json for nomethoderror in activesupport 3 did to json get removed or something,['ruby'] +87098,android split string i have a string called currentstring and is in the form of something like thisfruit they taste good i would like to split up the currentstring using the as the delimiterso that way the word fruit will be split into its own string and they taste good will be another stringand then i would simply like to use settext of 2 different textviews to thisplay that string what would be the best way to approach this,"['java', 'android']" +87112,python subprocess timeout is there any argument or options to setup a timeout for pythons subprocesspopen methodsomething like thissubprocesspopen timeout20,['python'] +87117,what is the best way to execute a function when user clicks on a link from my experience i know three different ways to execute a javascript function when a user clicks on a linkuse the onclick attribute on the linka href onclickmyfunctionreturn falseclick meause the href on the link a hrefjavascriptmyfunctionclick meado not touch the link do everything in jsa hrefclick meain the javascript we will stop the default event and call the functionwhich one is better what are the advantages and thisadvantagesedit deleted the javascript on onclick,['javascript'] +87120,javascript variable in function name possible i hope this question is not too simple but i have no idea how can i start a function with a var in the function namefor example my functionsfunction at 26function at 21function at 99start the functionvar test id 21 at test id does not worki hope somebody can help methanks in advancepeter,['javascript'] +87132,end java command line application properly i am just wondering do i need to call systemexit0 right before main method of a java command line application ends if so why what is the difference from letting it exit on its own if i would just always put there 0 what is not cleaned upthanks in advance,['java'] +87148,is it considered acceptable to not call thispose on a tpl task object i want to trigger a task to run on a background thread i do not want to wait on the tasks completionin net 35 i would have done thisthreadpoolqueueuserworkitemd dosomething in net 4 the tpl is the suggested way the common pattern i have seen recommended istaskfactorystartnew dosomething however the startnew method returns a task object which implements ithisposable this seems to be overlooked by people who recommend this pattern the msdn documentation on the taskthispose method saysalways call thispose before you release your last reference to the taskyou cannot call thispose on a task until it is completed so having the main thread wait and call thispose would defeat the point of doing on a background thread in the first place there also does not seem to be any completedfinished event that could be used for cleanupthe msdn page on the task class does not comment on this and the book pro c2010 recommends the same pattern and makes no comment on task thisposali know if i just leave it the finalizer will catch it in the end but is this going to come back and bite me when i am doing lots of fire forget tasks like this and the finalizer thread gets overwhelmedso my questions are is it acceptable to not call thispose on the task class in this case and if so why and are there risksconsequencesis there any documentation that thiscusses this or is there an appropriate way of thisposing of the task object that i have missedor is there another way of doing fire forget tasks with the tpl,"['c#', '.net']" +87164,getting pdb in emacs to use python process from current virtualenv i am debugging some python code in emacs using pdb and getting some import issues the dependencies are installed in one of my bespoked virtualenv environments pdb is stubbornly using usrbinpython and not the python process from my virtualenv i use virtualenvel to support switching of environments within emacs and via the postactivate hooks described in this works well when running mx pythonshell import sys print syspath this points to all of my virtualenv libraries indicating that the pythonshell is that of my virtualenvthis is contradicted however by m which python which gives usrbinpythondoes anyone know how i can tell mx pdb to adopt the python process from the currently active virtualenv,['python'] +87179,best primary key for storing urls which is the best primary key to store website address and page urlsto avoid the use of autoincremental id which is not really tied to the data i designed the schema with the use of a sha1 signature of the url as primary keythis approach is useful in many ways for example i do not need to read the last id from the database so i can prepare all table updates calculating the key and do the real update in a single transaction no constraint violationanyway i read two books which tell me i am wrong in high performance mysql it is said that the random key is not good for the db optimizer moreover in each joe celkos books he says the primary key should be some part of the datathe question is the natural keys for urls are urls themselves the fact is that if for a site it is short wsomethingcom there is not an imposed limit for am url see consider i have to store and work with some millions of themwhich is the best key then autoincremental ids urls hashes of urls,['mysql'] +87180,html attributes for editorfor in aspnet mvc why cannot i pass in html attributes to editorfor eg htmleditorformodel modelcontrolperiodtype new thisabled thisabled readonly readonly i do not want to use metadataupdate the solution was to call this from the view htmleditorfor model modelcontrolperiodenddate new modifiablemodelcontrolperiodenddatemodifiableand use viewdatamodifiable in my custom editortemplatesstringascx where i have some view logic that determines whether to add readonly andor thisabled attributes to the inputthe anonymous object passed into editorfor is a parameter called additionalviewdata and its properties are passed to the editor template in the viewdata collection,['html'] +87194,what is the difference between escapexml and escapehtml i would like to escape characters in jsp pages which is more suitable escapexml or escapehtml,['html'] +87200,how do i test if ios device has telephone capabilities i want to offer phone support in my app at the press of a button for iphone users and thisplay a phone number for ipadipod touch users rather than detecting what device the user has is there a better way to query the hardware to see if it has telephony capabilities this would continue to work should ipad 3g one day open up for voice callsi am aware of how to limit an app to devices through the uirequireddevicecapabilities key but i am not looking to restrict platform just detect capabilities,"['iphone', 'objective-c', 'ios']" +87203,how to execute a shell script from c in linux how can i execute a shell script from c in linux,['c'] +87204,sql server enterprise manager mass delete of tables and changing ownership of tables i have pretty much no experience with sql servers enterprise manager so i am not sure if this is even possible or hopefully laughably simpleduring an import into a database something has happened where each table has duplicated itself with two important differencesthe first is that the owner on both tables is different the second is that only the structure has copied across on one of the copiessods law indicated that of course the data was stored on the tables owned by the wrong person so my question is can i quickly delete all tables owned by one user and can i quickly change the ownership of all other tables to bring them in linethere are enough tables that automation is going to be my preferred option by a long wayany help would be greatly appreciated i am running sql server 20,['sql'] +87205,why does the default objecttostring return a hex representation of the hashcode i am curious why objecttostring returns thisreturn getclassgetname integertohexstringhashcodeas opposed to thisreturn getclassgetname hashcodewhat benefits does thisplaying the hash code as a hex rather than a decimal buy you,['java'] +87209,executing shell script with system returns 256 what does that mean i have written a shell script to softrestart haproxy reverse proxy executing the script from the shell works but i want a daemon to execute the script that doenst work system returns 256 i have no clue what that might meanbinsh save previous statemv homehaproxyhaproxycfg homehaproxyhaproxycfgoldmv varrunhaproxypid varrunhaproxypidoldcp tmphaproxycfgnew homehaproxyhaproxycfgkill ttou cat varrunhaproxypidoldif haproxy p varrunhaproxypid f homehaproxyhaproxycfg then kill usr1 cat varrunhaproxypidold rm f varrunhaproxypidold exit 1else kill ttin cat varrunhaproxypidold rm f varrunhaproxypid mv varrunhaproxypidold varrunhaproxypid mv homehaproxyhaproxycfg homehaproxyhaproxycfgerr mv homehaproxyhaproxycfgold homehaproxyhaproxycfg exit 0fihaproxy is executed with user haproxy my daemon has it is own user too both run with sudoany hints,['c'] +87210,how to declare a template class as a friend in c i wana know if we can make a partial specialized class as a friend classtemplate class a class b class abclass ctemplate class b class ab c b class d template class e friend class ab d e how to achieve the above,['c++'] +87229,use of googlecollections mapmaker i just came across this answer in so where it is mentioned that the googlecollections mapmaker is awesomei went through the documentation but could not really figure out where i can use itcan any one point out some scenarios where it would be appropriate to use a mapmaker,['java'] +87263,listing all images in a directory using php i have the code below that lists all the images in a folder the problem is that it finds some files a and a that i am not sure what they are so i am not sure how to prevent them from showing up i am on a windows xp machine any help would be great thankserrors warning renameimagesimages functionrename no error in cwampwtestinglistphotosaphp on line 14warning renameimagesimages functionrename no error in cwampwtestinglistphotosaphp on line 14codephpdefineimagepath imagesif is dirimagepath handle opendirimagepathelse echo no image directorydirectoryfiles arraywhile file readdirhandle false newfile str replace file renameimagepath file imagepath newfile directoryfiles newfileforeachdirectoryfiles as directoryfile ifstrlendirectoryfile 3 echo img src imagepath directoryfile alt directoryfile br closedirhandle,['php'] +87269,finding linewraps supposing i have some random block of text in a single line like solorem ipsum dolor sit amet consectetur adipiscing elitbut for whatever reason width settings on the containing element use of textzoom etc on the viewers screen it thisplays as two or more lineslorem ipsum dolor sit ametconsectetur adipiscing elitor lorem ipsum dolor sitamet consecteturadipiscing elitis there any way to find out via javascript where those linewraps happenptext and phtml return lorem ipsum dolor sit amet consectetur adipiscing elit regardless of how the text is thisplayed,"['javascript', 'jquery', 'html']" +87273,help with autorotating infinite jquery carousel can not get carousel to loop infinitely instead of rewind i am building an autorotating imagecarousel with jquery and i am trying to get the images to rotate infinitely rather than when it reaches the last image it rewinds back to the first image and starts again unfortunately i am rather new at the jquery game so i am having some trouble getting this to work i have tried piecing together code i have found in tutorials online and modifying it to fit my code but no luck i think i might have to clone the existing images to appear after they cycle through but i am not sure what direction to go in any assistance is greatly appreciated heres the code i am working with belowhtmldiv classmain view div stylewidth165px height98px margin0 padding0 border0 img srccontenttemplate imageswanalogoblackbg165x98png div div classwindow ul classimage reel lia hrefmlbphiladelphiaphilliestickets titlephilliesimg srccontenttemplate imagesbannerssidebannerimgscroll1jpg altphillies ali lia hrefnflphiladelphiaeaglestickets titleeaglesimg srccontenttemplate imagesbannerssidebannerimgscroll2jpg alteagles ali lia hrefnhlphiladelphiaflyerstickets titleflyersimg srccontenttemplate imagesbannerssidebannerimgscroll3jpg altflyers ali lia hrefnbaphiladelphia76erstickets title76ersimg srccontenttemplate imagesbannerssidebannerimgscroll4jpg alt76ers ali lia hrefncaabasketball titlencaa basketballimg srccontenttemplate imagesbannerssidebannerimgscroll8jpg altncaa basketball ali lia hrefconcertstickets titleconcertsimg srccontenttemplate imagesbannerssidebannerimgscroll5jpg altconcerts ali lia hreftheatretickets titletheatreimg srccontenttemplate imagesbannerssidebannerimgscroll6jpg alttheatre ali lia hrefothereventstickets titlefamily eventsimg srccontenttemplate imagesbannerssidebannerimgscroll7jpg altfamily events ali ul div div stylewidth170px height290px border0 padding0 margin 290px 0px 0px 0px img srccontenttemplate imagesblackfadeborder170x290png div div classbottextbox center div classbottext a hrefmlbphiladelphiaphilliestickets titlephilliesphilliespa a hrefnflphiladelphiaeaglestickets titleeaglespeaglespa a hrefnhlphiladelphiaflyerstickets titleflyerspflyerspa a hrefnbaphiladelphia76erstickets title76ersp76erspa a hrefncaabasketball titlencaa basketballpncaa basketballpa a hrefconcertstickets titleconcertspconcertpa a hreftheatretickets titletheatreptheatrepa a hrefothereventstickets titlefamily eventspfamily eventpa div center div div classpaging a href rel11a a href rel22a a href rel33a a href rel44a a href rel55a a href rel66a a href rel77a a href rel88a divdivjavascriptdocumentreadyfunction pagingshow paging afirstaddclassactive var imagewidth windowwidth var imagesum image reel imgsize var imagereelwidth imagewidth imagesum image reelcsswidth imagereelwidth rotate function var triggerid activeattrrel 1 get number of times to slide var image reelposition triggerid imagewidth determines the thistance the image reel needs to slide paging aremoveclassactive remove all active class activeaddclassactive add active class the active is declared in the rotateswitch function slider animation image reelanimate left image reelposition 750 bottextanimate left image reelposition 750 rotation and timing event rotateswitch function play setintervalfunction set timer this will repeat itself every x seconds active paging aactivenext move to the next paging if activelength 0 if paging reaches the end active paging afirst go back to first rotate trigger the paging and slider function 1500 timer speed in milliseconds 7 seconds rotateswitch run function on launch on hover image reel ahoverfunction clearintervalplay stop the rotation function rotateswitch resume rotation timer on click paging aclickfunction active this activate the clicked paging reset timer clearintervalplay stop the rotation rotate trigger rotation immediately rotateswitch resume rotation timer return false prevent browser jump to link anchor edit cssmain view float left overflowhidden position relative width170px height475px backgroundcolorblack border0 margin2px padding2px 0px 2px 0px textaligncenterwindow height290px width170px overflow hidden position relative backgroundcolorblack border0 padding0px margin0pximage reel position absolute top 0 left 0 marginleft40pximage reel img float leftbottextbox height87px width1360px overflowhidden positionrelative backgroundurlcontenttemplate imagesblacksidebottom170x87png norepeat margin0px padding0pxbottext positionrelative top0 left0 margin32px 0px 0px 0px padding0 textaligncenterbottext p width170px float leftpaging position absolute bottom 40px right 70px width 178px height47px zindex 100 textalign center lineheight 40px thisplay none paging a padding 5px textdecoration none color fpaging aactive fontweight bold background 920 border 1px solid 610 mozborderradius 3px khtmlborderradius 3px webkitborderradius 3pxpaging ahover fontweight boldactually you can see the flash banner on the right that i am trying to replace with a jquery oneonce again i really appreciate any help with this like i said i am kinda new at working with jquery and i have been stumbling over this all day thanks a million,"['javascript', 'jquery', 'html', 'css']" +87279,net is it possible to use aspnet without mvc using html 5 is it possible to use aspnet without mvc using html 5 a link would be great,['.net'] +87284,how to check browsers javascript is enabled or not my application depends on javascript i want to check the client browsers javascript is enabled or not and raise an alert message if its turned off,"['javascript', 'asp.net']" +87292,autointerval precision in ms chart i am currently using the charting within net using systemwindowsformsdatavisualizationchartingchart thus far it seems very powerful and works great however there is a huge problem in terms of how it is autocalculating intervals i use a lot of double values and in libraries like zedgraph it handles this perfectly it selects minmaxinterval just fine however in ms chart it may select 20634539832 as a minimum and intervals of a similar decimal precision obviously this looks quite uglyso i tried simply making the axis format 0 and it works great when it loads the chart except when you zoom in you need greater precision maybe at 4 decimal places instead of 2 it seems i am either stuck with 9 decimal places all the time or else a constant fixed number that may break when someone requires greater precision i would rather it pick up the precision based on the level of zoom currently applied libraries like zedgraph and dundas which i believe ms is even using tend to pick good values that change as you zoom in and outis there any way to have the intervals change precision as the zoom frame changes it is probably some simple property i have set wrong but it is hard to tell with the millions of properties this thing has especially when there is about 14 places that represent the concept of interval,['c#'] +87315,setting z order of view with bringchildtofront i am trying to set the z order of a ui element ie a view so that it will overlap another element but calling viewgroupbringchildtofront has a weird side effectit moves the element to be the last item in the parent the viewgroup is this a bug expected behavior or what more importantly how can i set the z order or a view without this unfortunate side effect,['android'] +87327,c or event delegates returning bool i have created a console for my game in xna and i have a delegate for when a command has been entered at the moment the delegate is returning a bool value i have declared an event inside the console class which returns false and then subscribed to this event from other classes the idea is if none of the classes that subscribe to this event return true then it is assumed that the user has entered an invalid command however if at least one of the subscribed classes returns true then the command is assumed to be validat the moment only one class is taken into account for returning true or false is there a way i can look at the return values of all the subscribing classes then or their resultthanks,"['c#', '.net']" +87331,there is no attribute allowtransparency i am looking for some alternate way to doiframe transparencytrue when i do the w3c validation i am getting the errorcolumn 31 there is no attribute allowtransparencyif use this cssiframetransfix opacity 0 filteralphaopacity0for the above snippet i am getting a blank iframe,"['html', 'css']" +87350,how does c generics affect collections with primitives as i understand it cnet generics support some degree of reification so if i have the following codelistint list new listintlistadd1will the value 1 be autoboxed or will the list object handle primitive ints efficiently,"['c#', '.net']" +87351,can button to generate tag instead of rather than input typesubmit i want to output buttonusing the button to method rails 300is this possible,['ruby-on-rails'] +87353,potential problem in swapping values of two variables without using a third variable i recently came along this method for swapping the values of two variables without using a third variableababbut when i tried the above code on different compilers i got different results some gave correct results some did notis anything terribly wrong with the code,"['c++', 'c']" +87367,add css class to a div in code behind i have a div and i am trying to add a css class to it in code but i receive the following error when i tryproperty or indexer systemwebuihtmlcontrolshtmlcontrolstyle cannot be assigned to it is read onlyi am using the following codeprotected void btnevent clickobject sender imageclickeventargs e btnventcstyle hom but a can anyone please help me,"['c#', 'css']" +87369,how can i thisable the submit button until text is entered in the input field i have an issue try to achieve this result pretty much what i need is to thisable the submit button until text is entered in the input field i have trying some functions but without results please if you can help me with this it would be really appreciatedhtml markupform action methodget idrecipenameinput typetext idname namename classrecipename valuehave a good name for it enter here onfocusif thisvalue have a good name for it enter here thisvalue onblurif thisvalue thisvalue have a good name for it enter here input typesubmit clasubmitname value formthanks in advance,"['javascript', 'jquery', 'html', 'css']" +87378,how can i get intellisense in phpeclipse on custom objects pulled out of array in foreach loop i have a collection of custom objects podcast in an arraywhen i use a foreach loop to iterate through this collection i do not have code completion on the variable that contains the object pulled out of the collection as i would in cvisualstudio for instanceis there a way to give php a type hint so that eclipse knows the type of the object being pulled out of the collection so it can show me the methods on that object in intellisensephppodcasts new podcastsecho podcastsgetlisthtmlclass podcasts private collection array function construct thiscollection new podcastthis is the first one thiscollection new podcastthis is the second one thiscollection new podcastthis is the third one public function getlisthtml r ifcountthiscollection 0 r ul foreachthiscollection as podcast r li podcastgettitle li r ul return r class podcast private title public function gettitle return thistitle public function settitlevalue thistitle value function constructtitle thistitle title addendumthanks fanis i updated my foreach template to include that line automaticallyifcountlines 0 foreachlines as line var var type,['php'] +87389,python why elif keyword i just started python programming and i am wondering about the elif keywordother programming languages i have used before use else if does anyone have an idea why the python developers added the additional elif keywordwhy notif a printaelse if b printbelse printc,['python'] +87390,nsstring in uiwebview i have an nsstring and a webview in my project objectivec for iphone i have called indexhtml in webview and inside it i inserted my script javascripthow can i pass the nsstring as a var in my script and viceversathis is an example but i do not understand it very well,"['javascript', 'iphone', 'objective-c']" +87398,rails 3 facebook plugingem does anyone know of a good rails 3 compatible gem or plugin that support the facebook api rather graph api but old rest is ok too mostly for getting profile picture info friends and posting on walli am looking for something that seems to be maintained well so i know i can count on it in the future as well,['ruby-on-rails'] +87399,php how to get previous sunday of a specific date in the past i am retrieving an entry from a database with a date associated with it i want to be able to get the previous sunday and the next saturday relative to that specific date to populate a jquery datepickeri know how to do it with the actual timedate with strtotimelast sundaybut i do not know how to do that for a date other than nowthanks,['php'] +87423,horizontal css gradients i want to have a gradient as the background of my webpage i have figured out how to make the gradient vertical but i want it to be horizontalbackgroundimage webkitgradientlinear 0 25 0 0 fromrgb176 196 2 torgb255 255 255backgroundimage mozlineargradientcenter bottom rgb153 255 51 25 rgb255 102 51 80,['css'] +87434,dynamically loading css i am trying to create a page theme function for my site i want to load the corresponding themes dynamically on the page using separate css filesi am using this code filerefsetattributerel stylesheet filerefsetattributetype textcss filerefsetattributehref linkcss documentgetelementsbytagnamehead0appendchildfilerefwhich works fine but it does not return any info if the css file has loaded or notis there a way to catch when the css is loaded maybe by using ajax,"['javascript', 'css']" +87438,trailing return type using decltype with a variadic template function i want to write a simple adder for giggles that adds up every argument and returns a sum with appropriate typecurrently i have got thisinclude iostreamusing namespace stdtemplate class tt sumconst t in return intemplate class t class pauto sumconst t t const p p decltypet sump return t sumpint main cout sum5 100 2 endlon gcc 451 this seems to work just fine for 2 arguments eg sum2 55 returns with 75 however with more arguments than this i get errors that sum is simply not defined yet if i declare sum like this howevertemplate class t class pt sumconst t t const p pthen it works for any number of arguments but sum2 55 would return integer 7 which is not what i would expectwith more than two arguments i assume that decltype would have to do some sort of recursion to be able to deduce the type of t sump is this legal c0x or does decltype only work with nonvariadic declarations if that is the case how would you write such a function,['c++'] +87507,is there some website that has examples of every method in the python standard library for example c have cpluspluscomreference which contain all of c standard library complete with definitions and more importantly examples so i was wondering if there is such a website for pythoni know that python is self documented like i could usehelpobjectobject doc dirobjecti know of docpythonorglibrarywikipythonorgbut it does not have examples of every method it would be nice if there was such a website because when i am learning a new python library i find myself just testing the methods to see if it does what i want and it makes my programming really slowbut this maybe because i have only have 2 years of programming under my belt so my question is is there such a website and is there a better way to learning a new library in python because when learning a new c library all i need to do is follow by example which makes learning a new c library really easy,"['c++', 'python']" +87525,problem with spring fileupload i have the following block of code which is handling my file upload of a photo that i am using in my spring mvc web application i am using spring mvc commonsmultipartfileresolver to handle file uploadsifmodelgetphoto null ifmodelgetphotoisempty multipartfile file modelgetphoto string filename filegetoriginalfilename string filepath basedirectory filename fileoutputstream fos new fileoutputstreamfilepath try foswritefilegetbytes agentprofilesetphotourifilename catch illegalstateexception e systemoutprintlne finally fosclose in my appservletxml file i have the following code to configure the multipartfile resolver bean bean idmultipartresolver classorgspringframeworkwebmultipartcommonscommonsmultipartresolver beani am experiencing some random problems when i am uploading photos 1if i go to upload a smaller photo around 3 kb or so it will upload successfully2if i go to upload a little larger photo it will create the file in the directory but with a size of 0 bytes and will give the following error message javalangillegalstateexception file has been moved cannot be read againorgspringframeworkwebmultipartcommonscommonsmultipartfilegetbytescommonsmultipartfilejava112comzadminmvccontrolleraddagentcontrollerprocessfinishaddagentcontrollerjava145orgspringframeworkwebservletmvcabstractwizardformcontrollervalidatepagesandfinishabstractwizardformcontrollerjava642orgspringframeworkwebservletmvcabstractwizardformcontrollerprocessformsubmissionabstractwizardformcontrollerjava492orgspringframeworkwebservletmvcabstractformcontrollerhandlerequestinternalabstractformcontrollerjava265orgspringframeworkwebservletmvcabstractcontrollerhandlerequestabstractcontrollerjava153orgspringframeworkwebservletmvcsimplecontrollerhandleradapterhandlesimplecontrollerhandleradapterjava48orgspringframeworkwebservletthispatcherservletdothispatchthispatcherservletjava874orgspringframeworkwebservletthispatcherservletdoservicethispatcherservletjava808orgspringframeworkwebservletframeworkservletprocessrequestframeworkservletjava476orgspringframeworkwebservletframeworkservletdopostframeworkservletjava441javaxservlethttphttpservletservicehttpservletjava637javaxservlethttphttpservletservicehttpservletjava717i have tried a couple different options configuring the multipart resolver such as switching it to handle a commonsmultipartfile object as oppose to a plain multipartfile object but nothing changedi have also tried to manuall configure the maximum upload size in the commonsmultipartfileresolver bean with the following property property namemaxuploadsize value10240 nothing changed as well i am not sure what the commonsmultipartresolver defaults to as far as size of the file that can be uploaded but that is not my questioni have been told that the problem i am experiencing is due to a problem in the multipart parserhandler that spring is using i had a recent post about this same problem and because new information was found wanted to repost with the new information the old post can be found at commonsmultipartfileresolver problemi feel that i have checked nearly every resource on the internet to find additional documentation but am unable to figure out the problemplease help me figure out what is going on with this and if there is a better simpler solution to maybe explorer those options but i would prefer to stay with my current method if i can find a solutioneditnote i have been experimenting with different size photos to upload and i believe that the limit that it is allowing me to upload is around 10kb anything larger then 10kb is causing it to break and give me the error above,['java'] +87527,android get date before 7 days one week how to get date before one week from now in android in this formatsimpledateformat dateformat new simpledateformatymmdd hhmmssex now 20100919 hhmmss before one week 20100912 hhmmssthanks,"['java', 'android']" +87534,relational database design question surrogatekey or naturalkey which one is the best practice and whya type table surrogateartificial keyforeign key is from usertype to typeidb type table natural keyforeign key is from usertype to typetypename,['sql'] +87577,how to avoid content typesxml in nets zippackage class i wish to know if there is any way to avoid to have a content typesxml file inside the zip file while using nets zippackage class,['.net'] +87580,how to bold csv data in excel i work on a pythondjango project i write csv code as followsresponse httpresponsemimetypetextcsv responsecontentthisposition attachment filenameduedatewisesearchcsv writer csvwriterresponse writerwriterowinfant namemother namemother address next vaccine dosedue datecomentsthis row is the header and i need to bold all header text i download csv as ms excel filehow can i do it please help,['python'] +87586,cannot find class in same package i am trying to compile boardjava which is in the same package and directory as hexagonjava but i get this errorboardjava12 cannot find symbolsymbol class hexagonlocation class oadams atrocheboard private hexagon tilesthe first few lines of boardjavapackage oadams atrocheimport javautillinkedlistimport javautilqueueimport javaioprintstreamimport p323hexpublic class board implements piecefieldsprivate int nprivate hexagon tilesthe first few lines of hexagonjavapackage oadams atrocheimport p323hexpublic class hexagon implements piecei just cannot see what i am doing wrong any ideasthanks,['java'] +87596,how to resize array in c possible duplicatecan you resize a c array after initialization i need to do the equivalent of the following c code in carrayresizeref a alength 1how to achieve this in c,['c++'] +87623,save many canvas element as image i have 3 layers of canvas 1 is matrix 2 3 is graphics how to preserve them in one imagediv styleposition relative canvas idmatix width100 height100 styleposition absolute left 0 top 0 zindex 0canvas canvas idlayer1 width100 height100 styleposition absolute left 0 top 0 zindex 0canvas canvas idlayer2 width100 height100 styleposition absolute left 0 top 0 zindex 1canvasdiv,['javascript'] +87624,get size of file on thisk var length new systemiofileinfopathlengththis gives the logical size of the file not the size on the thisk i wish to get the size of a file on the thisk in c preferably without interop as would be reported by windows explorerit should give the correct size including fora compressed filea sparse filea fragmented file,"['c#', '.net']" +87629,rails 3 returning a http 406 not acceptable i have the following controller code def create admin adminnewparamsadmin respond to do format if adminsave redirect toadmin notice admin was successfully created else render action new end end end def update admin adminfindparamsid respond to do format if adminupdate attributesparamsadmin redirect toadmin admins path notice admin was successfully updated else render action edit end end endand the following routes admin admins get adminadminsformat actionindex controlleradminadmins admin admins post adminadminsformat actioncreate controlleradminadmins new admin admin get adminadminsnewformat actionnew controlleradminadmins edit admin admin get adminadminsideditformat actionedit controlleradminadmins admin admin get adminadminsidformat actionshow controlleradminadmins admin admin put adminadminsidformat actionupdate controlleradminadmins admin admin delete adminadminsidformat actiondestroy controlleradminadminsnow aside from the slightly whacky naming the redirects always result in a 406 not acceptable what could be wrong,['ruby-on-rails'] +87632,why does not java 5 api take advantage of covariant return types since java 5 we are allowed to have covariant return types why does not the java api take advantage of thistake graphics2dcreate for instance why is not it overridden to return a graphics2d object it seems to me that it would be backward compatible in all situations,['java'] +87638,how to generate sequence of numberschars in javascript is there a way to generate sequence of characters or numbers in javascriptfor example i want to create array that contains eight 1s i can do it with for loop but wondering whether there is a jquery library or javascript function that can do it for me,"['javascript', 'jquery']" +87644,create file path from variables i am looking for some advice as to the best way to generate a file path using variables currently my code looks similar to the followingpath myrootdirectoryfor x in list of vars if ospathisdirpath x line a printx exists else osmkdirpath x line b printx createdfor lines a and b as shown above is there a better way to create a file path as this will become longer the deeper i delve into the directory treei envisage an existing builtin method to be used as followscreate pathpath in hereproducing a path of the form myrootdirectoryinhereif there is no built in function i will just write myself onethank you for any input,['python'] +87657,join string and nonestring using optional delimiter i am basically looking for the python equivalent to this vbvba string operationfullname lastname firstnamein vbvba and are both concatenation operators but they differ in how they handle a null valuesome string null nullsome string null some stringthis hidden feature allows for the first line of code i wrote to include a comma and space between the required lastname and the optional firstname values if firstname is null null is the vbvba equiv of pythons none fullname will be set to lastname with no trailing commais there a oneline idiomatic way to do this in pythontechnical notegnibblers and eumiros answers are not strictly the equivalent of vbvbas and using their approaches if firstname is an empty string rather than none there will be no trailing comma in almost all cases this would be preferable to vbvbas result which would be to add the trailing comma with a blank firstname,['python'] +87663,aes 256 encryption in net framework 20 does anyone know if c can be used in net framework 20 to use aes 256 encryption and decryption appreciate if the inbuilt framework supports this or if we have to use any external apis for the samethanks,"['c#', '.net']" +87671,c how to force a slpash screen to be shown in the primary thisplay in a dualmonitor system i am facing a problem when thisplaying a splash screen in a system with two monitors when i start the application in the primary thisplay and then the mouse pointer is moved to the second monitor before the splash screen is shown my splash screen follows the mouse pointer that means the splash screen is shown in the 2nd thisplay and after it finishes its work thissapears and the application is thisplayed in the primary monitor this looks pretty ugly and unprofessionali have tried to set the property formstartpositioncenterscreen in the forms properties and set it in run time in the constructor of my form but none of this has worked by the way i am using cany hints to achieve that the splash screen be thisplayed in the same monitor as my applicationany help will bee deeply appreciatedgreetingsvictor,['c#'] +87675,should i use properties or direct reference when accessing instance variables internally say i have a class like thisinterface myawesomeclass nsobjectprivate nsstring thing1 nsstring thing2property retain nsstring thing1property retain nsstring thing2endimplementation myawesomeclasynthesize thing1 thing1endwhen accessing thing1 and thing2 internally ie within the implementation of myawesomeclass is it better to use the property or just reference the instance variable directly assuming cases in which we do not do any work in a custom access or mutator ie we just set and get the variable preobjective c 20 we usually just access the ivars directly but whats the usual coding stylebest practice now and does this recommendation change if an instance variableproperty is private and not accessible outside of the class at all should you create a property for every ivar even if they are private or only for publicfacing data what if my app does not use keyvalue coding features since kvc only fires for property accessi am interested in looking beyond the lowlevel technical details for example given suboptimal code likeinterface myawesomeclass nsobject id myobjproprety id myobjendimplementation myawesomeclasynthesize myobjendi know that myobj anotherobject is functionally the same as selfmyobj anotherobjbut properties are not merely fancy syntax for instructing the compiler to write accessors and mutators for you of course they are also a way to better encapsulate data ie you can change the internal implementation of the class without rewriting classes that rely on those properties i am interested in answers that address the importance of this encapsulation issue when dealing with the clas own internal code furthermore properlywritten properties can fire kvc notifications but direct ivar access would not does this matter if my app is not utilizing kvc features now just in case it might in the future,['objective-c'] +87700,adding a column description does anyone know how to add a description to a sql server column by running a script i know you can add a description when you create the column using sql server management studiohow can i script this so when my sql scripts create the column a description for the column is also added,['sql'] +87701,declare function at end of file in python is it possible to call a function without first fully defining it when attempting this i get the error function name is not defined i am coming from a c background so this issue stumps me declaring the function before worksdef kerma return energy mass print kermahowever attempting to call the function without first defining it gives troubleprint kermadef kerma return energy massin c you can declare a function after the call once you place its header before itam i missing something here,['python'] +87709,retrieve or simulate full query from pdo prepared statement i stumbled upon this question from two years ago is there a way to get the raw sql string executed when calling pdostatementexecute on a prepared statement for debugging purposes this would be extremely usefulthe winning answer states that you can also get what you want if you set the pdo attribute pdoattr emulate prepares in this mode pdo interpolate parameters into the sql query and sends the whole query when you executebut it does not mention how to get the resulting query string i know it is a bad idea performance wise but that does not bother me in debug mode does anybody know how to do thisps if there is some way i could have reopened drawn attention to the original two year old topic instead of opening a new one please let me know,['php'] +87710,a basic question about while true level beginnerdef play gameword list hand deal handhand size random init while true cmd raw inputenter and to deal a new hand r to replay the last hand or e to end game if cmd n hand deal handhand size play handhandcopy word list print elif cmd r play handhandcopy word list print elif cmd e break else print invalid commandmy question while what is truei reckon saying while true is shorthand but for what while the variable hand is being assigned a value and what if the variable hand is not being assigned a value,['python'] +87729,how to convert html rtf in java the basic api of java that uses rtfeditorkit and htmleditorkit is not able of recognize tags like br and tableso i have searched on internet a better way of converting html to rtf and i have found two solutions that seem to workjodconverter and htmltortfconverter the first one needs oppenoffice installed to work and the second one uses dll so it canat be used on linuxdoes anyone know about other solutionthanks for any help,"['java', 'html']" +87742,how careful should i be with threadsafety when creating methodsactivities which interact with sqlite database i am creating an app which allows for many different activities to be started from a tabactivityup to 25 most of the activities require data from the sqlite database so when oncreate is run an asynctask creates an sqliteopenhelper objectwhich will open a readablewritable database runs a query data is retrieved and everything is then closed i was just testing messing around to see if i could break something so i added every activityto the tabactivitys tabhost i then started mashing each tab as quickly as possible i noticed that very quickly i began to see in the logcat caused by androiddatabasesqlitesqliteexception database is locked begin exclusive and the app proceeded to dietypically there will only be about 46 tabsi can just limit the user anyway for the tabhost i have not been able to break anything with a small amount of tabs to mash but i am still worried that maybe i am accessing the database in a poor wayhow can i prevent my sqlitedatabase objects to cause a lockif i create a contentprovider will that eliminate the possibility of database lockingdo you have any suggestions for changes i could make for accessing data from an sqlitedatabasei ended up taking the approach of using the application class and storing 1 sqliteopenhelper and trying my best to keep it synchronized this seems to be working great i put all my 25 activities in the tabhost and mashed away on them with no errorsi am calling sqlitedbapplicationgetapplicationsetdbhelpernew dbhelperthis constantsdb name null constantsdb version code methodshown below in every oncreate in my activitiesany further suggestions to this approach or to the changes i made using this application classimport androidappapplicationimport androiddatabasesqlitesqlitedatabasepublic class sqlitedbapplication extends application private dbhelper dbhelper private sqlitedatabase db public synchronized dbhelper getdbhelper db dbhelpergetdatabasereturns the already opened database object whiledbisdblockedbycurrentthread dbisdblockedbyotherthreads return dbhelper public synchronized void closedb ifnull dbhelper dbhelperclose ifnull db dbclose override protected void finalize throws throwable ifnull dbhelper dbhelperclose ifnull db dbclose superfinalize public synchronized void setdbhelperdbhelper dbhelper ifnull thisdbhelper thisdbhelper dbhelper thisdbhelpersetdbthisdbhelpergetwritabledatabasecreates and sets the database object via getwritabledatabase,['android'] +87746,how did sql become the dominant database language for most programming tasks youve got quite the selection of languages to choose from and good strong communities behind plenty of them but when you need to work with a database there is really only one viable choice these days sql sure there are different companies with different implementations and dialects but youre still looking things up withselect columnsfrom tablejoin other table on criteriawhere other criteriait was not always this way though as late as the early 90s there was no single obvious way to interact with a database but today there is and with the way computer languages tend to proliferate rather than converge i find that a bit odd what historical and technical factors led to sqls almost complete dominance of the database access domain,['sql'] +87748,spring integration test is slow with autowiring i am trying to speed up the integration tests in our environment all our classes are autowired in our applicationcontextxml file we have defined the followingcontextannotationconfigcontextcomponentscan basepackagecommycompanyframeworkcontextcomponentscan basepackagecommycompanyserviceadditional directoriesi have noticed that spring is scanning all directories indicated above and then iterates over each bean and caches the properties of each one i went over the debug messages from springas a result the following test takes about 14 seconds to runpublic class mytest extends basespringtest test def void mytest println test is there any way to lazy load the configuration i tried adding defaultlazyinittrue but that did not workideally only the beans required for the test are instantiatedthanks in advanceupdate i should have stated this before i do not want to have a context file for each test i also do not think one context file for just the tests would work this test context file would end up including everything,['java'] +87755,java servlet getparameter for a param that is a url i am building a site which submits a url to a servlet for analysis purposes on the client side i submit the url as a parameter that is encoded for examplesubmit goes to httplocalhostmyservleturlhttp3a2f2fwsitecomon the server side i have my servlet request the parameter like sostring url requestgetparameterurlwhat i receive is a decoded string so far so good this works as expected most of the timethe problem occurs when a url param contains parameters of its ownsubmit param22goes to httplocalhostmyservleturlhttp3a2f2fwsitecom3fparam13d126param23d2everything is fine on the client site but in my servlet when i get the parameter i receive only part of the url paramit dropped the second param from my input url param i am definitely encoding the url param before submitting it to the server what is going on,['java'] +87776,best way to get two nibbles out of a byte in javascript i am parsing a binary file in javascript that is storing two pieces of information per byte one per nibble the values are of course 016 and 016in all other parts of the file format each byte represents one piece of information so i have been using the following to successfully get the number values i needvar num strcharcodeat0 0xffbut i am stuck at trying to figure out how to get the 016 value of the first nibble and the same for the 2nd nibble from my single byte character strappreciate any help on this,['javascript'] +87785,port an iphone app to mac os x i have an app running on the iphone that i would like to convert into a runnable application on mac os x it uses a single uiviewcontroller which i have heard needs to be changed into an nsviewcontroller basically what i am wondering is what needs to be changed about an iphone application to make it work like a mac application instead for instance is there a mac uikit equivalent or how do i use the mac interface objects that show up in interface builder things like this is there anything that needs to be fundamentally different about the structure of the code for it to run,"['iphone', 'objective-c']" +87795,ruby on rails no route matches i am new to rails and am just implementing some basic applications just starting on my second app and have run into what is a basic problem but google is yielding me nothinggetting this errorno route matches controlleruser actionadmin loginhere is my routesrbblahapplicationroutesdraw do resources items cart userendhere is my applicationshtmlerb the idea is this is a header of course and i am trying to create a link to login right now it is just supposed to set the login session variable to 1doctype htmlhtmlhead titleblahtitle stylesheet link tag all javascript include tag defaults csrf meta tag headbodydiv idheaderholder div idtitleblahdiv div idmenu div class menuitemblogdiv div class menuitem link to products controller items action index div div class menuitemcontactdiv div classmenuitem link to cart controller cart action index div div classmenuitem link to unless current admin controller user action admin login div divdivdiv idcontent yield divbodyhtmland this is my user controllerrbclass usercontroller applicationcontroller def index end def admin login sessionlogin 1 sessioncart nil flashnotice admin user successfully logged in cart reset redirect to controller items endendwhat am i missing in my routesrb or otherwiseam sure it is something daft,['ruby-on-rails'] +87800,tracking changes in the active directory using c is there a way to raise events if someone changed something in active directory eg thisable user account,['c#'] +87801,connect sphinx autodocskipmember to my function i want to use sphinxs autodocskipmember event to select a portion of the members on a certain python class for documentationbut it is not clear from the sphinx docs and i cannot find any examples that illustrate where do i put the code to connect this i see sphinxconnect and i suspect it goes in my confpy but when i try variations on this code in confpy i cannot find the app object that i should connectdef maybe skip memberapp what name obj skip options print app what name obj skip options return false this is not even close to correctfrom sphinxapplication import sphinxsphinxconnectautodocskipmember maybe skip membera pointer to a simple example would be ideal,['python'] +87823,running multiple c task async hi normally i would do this with a background worker but i would like to do it with c task instead just to understand task betterthe thing is that i have a class with the following properties private int number1 public int number1 get return number1 set number1 value onpropertychangednumber1 private int number2 public int number2 get return number2 set number2 value onpropertychangednumber2 please note that i use the inotifypropertychangednumber1 taskintfactorystartnew generateresultresultnumber2 taskintfactorystartnew generateresult2resultthe generateresult and generateresult2 are just dumme methods who sleeps and then return a numberhow would i make this work async since right now generateresult2 is first called when generateresult is finished i need it to be able work async since i have no idea of when each task is going to finish or even if its going to finish,"['c#', '.net']" +87835,proper indenting for ordered lists in html i cannot get an ordered list to show proper indentingthe numbers are all aligned to the rightso the browser chrome shows a space before the single digit numbers and only aligns the double digit numbers correctly to the lefthow can i output a nice ordered list where the numbers are all aligned to the left and the list items all start below each other,"['html', 'css']" +87850,will the destructor of the base class called if an object throws an exception in the constructor will the destructor of the base class be called if an object throws an exception in the constructor,['c++'] +87854,solr multicore post data i am using solar application in multicore mode and i am unable to post dataxmlwhen i am trying to post a data by command linecmd windows to solr then i get an error missing solr core name in pathso please give me detailed answer,['java'] +87856,the guava library for java what are its most useful andor hidden features i have had a quick scan of the guava api and the new collection types it providesmultimap and bimap for example appear useful and i am thinking of including the library in the projects i work on however i also have a reticence to include libraries willynilly if they are of no great benefit and learning the features wastes valuable timehave you included the guava library in your project and has it proved useful in any unexpected way would you always use it in the future what has been its main benefittime saver what are its hidden features,['java'] +87881,java oneliner for list cleanup is there a construct in java that does something like thishere implemented in python item for item in oldlist if itemgetint 5today i am using something likeitemtype newlist new arraylistfor itemtype item oldlist if itemgetint 5 newlistadditem and to me the first way looks a bit smarter,"['java', 'python']" +87883,how do i parse a dtd file i want to parse a dtd file and use the info i get from that to create some classes i know that i can convert it to a xsd and then parse it but i was hoping to avoid that everything i find via google is to validate against a dtd so i guess my question is how do i parse a dtd file using c or are there any tools or libraries out there that i can use i should add that i am using visual studio 2005,['c#'] +87906,count from multiple tables in mysql how do i go about selecting counts from multiple tables in mysqlsuch asselect count as table1count from table1 where someconditionjoin select count as table2count from table2 where someconditioncross join subqueriesselect count as table3count from table3 where someconditioneditthe goal is to return this table1count table2count table3count 14 27 0,['mysql'] +87908,align swing components across panels we have a jpanel wich contains multiple jpanels wich contain jcomponents let us say jlabels and jtextboxesinside each of the internal jpanels we use jgoodies layout in order to ensure proper alignement of all labelsbut of course we would like to have all the labels aligned independently on which subpanel they are how could we do that without fixing the width of the column which contains the jlabelswe cannot loose the jpanels since we have to have borders around groups of components,['java'] +87930,rationale behind overflowexception thrown with negative array size after writing code that can be boiled down to the followingvar size1var arrnew bytesizei was surprised that it threw an overflowexception the docs for overflowexception statethe exception that is thrown when an arithmetic casting or conversion operation in a checked context results in an overflowi could not see how providing a negative size for and array length fits into the description given for this exception so delved a little deeper and found that this is indeed the specified behaviourthe computed values for the dimension lengths are validated as follows if one or more of the values are less than zero a systemoverflowexception is thrown and no further steps are executedi wonder why overflowexception was chosen it is pretty misleading if you ask me it cost me at least 5 minutes of investigation not counting my musings here can anyone shed any light on this to my thinking peculiar design decision,['c#'] +87933,coloring text in richtextbox c how can i color new line of text with some different colors and then add it to richtextboxi am using silverlight,['c#'] +87934,how to keep an iphone app running on background fully operational first of all i know there is only support for voip audio and location apps to run in background and that they will run just while the audio is been played or while using location services etcwhat i want to know is if there is a way to keep my app running on background fully operational does not matter the impact on batterys lifethat way the user of my app can select from settings to keep alive the app whenever he wants and just for the amount of time he wish eg if he is waiting for something that requires the app to be running after receiving the messages he can turn off the keep alive functionalityi do not know if this is possible but i had read some post that say so but unfortunately they did not say how to update in this tutorial i found that acrobits has two apps on the apple store that can force the application to stay alive and awake in the background so there is a way to do this,"['iphone', 'objective-c']" +87939,returning all characters before the first underscore using re in python i would like to return all of the characters in a string that precede the first appearance of an underscore in addition i would like the string that is being returned to be in all uppercase and without any nonalpanumeric charactersfor exampleagav08 binloop v6 agav08tlav1 binloopv2 tlav1i am pretty sure i know how to return a string in all uppercase using stringupper but i am sure there are several ways to remove the efficiently any help would be greatly appreciated i am still learning regular expressions slowly but surely each tip gets added to my notes for future useto further clarify my above examples are not the actual strings the actual string would look likeagav08 binloop v6with my desired output looking likeagav08and the next example would be the same stringtlav1 binloopv2desired outputtlav1again thanks all for the help,['python'] +87940,rails preserving get query string parameters in link to i have a typical search facility in my app which returns a list of results that can be paginated sorted viewed with a different records per page value etc each of these options is controlled by parameters in the query string a simplified examplesearchqtestpage2now say i need to thisplay a set of links that set records per page value to 10 20 30 each link must include the existing query parameters which can be a very long set plus a new per page parametersearchqtestpage2 per page10searchqtestpage2 per page20searchqtestpage2 per page30is there an easy way to do it with just link to helper or i need to parse and reproduce the query string from previous request somehow,['ruby-on-rails'] +87956,javascript add events crossbrowser function implementation use attacheventaddeventlistener vs inline events in order to add events we could use this simple 1st solutionfunction addeventhtml element event name event function ifhtml elementattachevent internet explorer html elementattacheventon event name function event functioncallhtml element else ifhtml elementaddeventlistener firefox company html elementaddeventlistenerevent name event function false do not need the call trick because in ff everything already works in the right way or this 2nd solution that adds inline eventsfunction addeventhtml element event name event function var old event html elementon event name iftypeof old event function html elementon event name function event functioncallhtml element else html elementon event name function old event event functioncallhtml element these are both crossbrowsers and can be used in this wayaddeventdocumentgetelementbyidsome div id click function alertthistagname shows div since i have the feeling attacheventaddeventlistener are used more around in events handling implementations i am wondering are there any thisadvantagesdrawbacks against using the 2nd solution that i might better be aware ofi can see two but i am interested in more if anythe 2nd solution screws up innerhtml of elements by adding events inlineusing 2nd solution i can easily remove all functions associated with a certain event type html elementon event name null but i can not use detacheventremoveeventlistener to remove exactly a specific functionany answers like use jquery or any other fw are pointless,['javascript'] +87979,is there an online tool to compile less i am trying to use less in my webpage but am having trouble compiling it it is built to work on ruby which i do not have permission to install on my pc is there an online tool for this compilationi know that lessphp exists but i cannot find the demo on their site any longerto summarise i am looking for a quick and dirty solution to compiling less to test my stylesheets locally ideally this would integrate with microsoft expression web 4 hooray for dreamspark but i would be perfectly happy with a copy paste compile copy paste web interfacedoes such an interface exist,['css'] +87980,purpose of cc prototypes i was reading wikipedia on cc prototype statements and i am confusedwikipedia say by including the function prototype you inform the compiler that the function fac takes one integer argument and you enable the compiler to catch these kinds of errorsand uses the below as an exampleinclude stdioh if this prototype is provided the compiler will catch the error in main if it is omitted then the error will go unnoticed int facint n prototype int mainvoid calling function printfdn fac error fac is missing an argument return 0 int facint n called function if n 0 return 1 else return and facn 1but the function definition of the called function already includes all the information that the prototype tells the compiler so why cannot the compiler deduce this information from the called functions definition since they contain identical statementsinformation letter for letterwhat am i missing seems like extra work for no obvious gainedit thanks guys i assumed the compilers were multipass i guess i am spoiled to current languages like python it makes sense since it is so old to need some kludges to do things accurately in a single pass it seems more obvious to me now apparently it requires fairly intimate knowledge of how the compiler links and compiles,"['c++', 'c']" +87981,find occurrences of characters in a java string i would like to count the occurrences of a character in a string suppose i have the string ab how would i count the amount of as in it,['java'] +87985,javascript retrieve key names from an object say i have thisvar x aa1z a2x bb1y b2wis there a way to iterate over x to get a and b i want the member name not its content i do not want to get a1z a2xthanks,['javascript'] +87992,when repr is called print object calls object str then when object repr is called i see that print object calls object repr when object str does not exist but i expect that is not the only way to call repr,['python'] +88002,adding readline functionality without recompiling python i recently upgraded to ubuntu 1004 lts and refreshed my python environment i installed python 27 from source unfortunately i did not notice that setupthist has the readline line commented out by default by default there is no readline support installed i am now using the python interpreter as a repl enough that the constant a and d are very obnoxious can i add readline support quickly or do i have to actually recompile python again it seems like the sort of thing where there should be a quick sane way to do it but i do not know such a way,['python'] +88003,does php have a set object i am new to php and i cannot figure out this basic question does php have some sort of set or list object something like an array but with the ability to dynamically add or remove any number of objects from it,['php'] +88013,sql profiler not showing insertsdeletesupdates when i run the profiler while running my application it only seems to show selects not inserts or anything that changes the database yet my database is being updated so those commands must be being executed what do i have to do to get it to show updates i am using entity framework btw if that might make a difference,['sql'] +88032,why is null an invalid linq projection i had the following statement which always returns nullvar addins allocationsselectmany set setlocationsanyq qismatchlevel count liststringsetaddins null i changed it slightly and now it works finevar addins allocationsselectmany set setlocationsanyq qismatchlevel count setaddins new liststring my primary question why cannot null serve as a return type from the ternary operator in this context of linqa secondary question is there a more clever way to formulate the above query particularly if it eliminates the new list,['c#'] +88033,binary search to compute square root java i need help writing a program that uses binary search to recursively compute a square root rounded down to the nearest integer of an input nonnegative integerthis is what i have so farimport javautilscannerpublic class sqrt public static void mainstring args scanner console new scannersystemin systemoutprintenter a valid integer int value consolenextint calculatesquarerootvalue public static int calculatesquarerootint value while value 0 double sqrt int mathsqrtvalue systemoutprintlnsqrt return 1 the fact that it has to use binary search to compute the square root is the part that is confusing me if anyone has any suggestions on how to do this it would be greatly appreciated thank you,['java'] +88036,using c for backend calculations in a web app i am running a php front end to an application that does a lot of work with data and uses cassandra as a data store however i know php will not give me the performance i need for some of the calculations as well as the management for the sheer amount of data that needs to be in memoryi would like to write the backed stuff in c and access it from the php application i am trying to figure out the best way to interface the twosome options i have looked atthrift a natural choice since i am already using it for cassandragoogles protocol buffersgsoapapache axisthe above are only things i looked at i am not limiting myselfthe data being transferred to the php application is very small so streaming is not required only results of calculations are transferredwhat do you guys think,['c++'] +88038,uitabbarcontroller get index of tapped i have got a tab bar application and i need to know when and what button a user taps on the tab bar as to thisplay the appropriate notifications and suchin short how would i go about detecting the index of a tapped uitabbaritem on a uitabbarthanks in advance,"['iphone', 'objective-c']" +88043,when do i need the windows sdk and what is net for i am a student and after taking some introductory programming courses in java c and just finishing up a book on c i would like to start developing applications for windowsi have done my best to page through google and find the answers i need but i seem to be at a losswhen would i need the windows sdk over just the regular apiand what is net and why would i need itwhat is so special about c and should i use that over ccthank you so much any help would be appreciated,"['c#', '.net', 'c++', 'c']" +88055,overriding a default option value in cmake from a parent cmakeliststxt i am trying to include several thirdparty libraries in my source tree with minimal changes to their build system for ease of upgrading they all use cmake as do i so in my own cmakeliststxt i can use add subdirectoryexternfoo for libfoobut the foo cmakeliststxt compiles a test harness builds documentation a shared library which i do not need and so on the libfoo authors had the foresight to control these via options optionfoo build shared build libfoo shared library on for example which means i can set them via the cmake command line but i would like to make that off by default and overridable via the command linei have tried doing setfoo build shared off before add subdirectoryexternfoo that has the effect of not trying to build the shared library during the second and subsequent build attempts but not during the first one which is the one i really need to speed upis this possible or do i need to maintain forked cmakeliststxt for these projects,['c++'] +88066,in java what do the return values of comparablecompareto mean what is the difference between return 0 return 1 and return 1 in compareto in java,['java'] +88094,namespaces in c vs imports in java and python in the java and python world you look at a source file and know where all the imports come from ie you know in which file the imported classes are defined for examplein javaimport javafoobarpublic class myclass private bar mybar new baryou immediately see that the barclass is imported from javafoo so bar is declared in javafoobarjava in pythonimport pythonbazfrom pythonfoo import barmy bar barmy other pythonbazotherhere it is clear that bar comes from the pythonfoo package and other is obviously from pythonbazin c correct me if i am wrongusing foousing bazusing anothernamespacepublic class myclass private bar mybar new bartwo questions1 how do i know where the barclass is declared does it come from the namespace foo or bar or anothernamespace edit without using visual studio2 in java the package names correspond to directory names or it is a very strong convention thus when you see which package a class comes from you know its directory in the file systemin c there does not seem to be such a convention for namespaces or am i missing something so how do i know which directory and file to look in without visual studio after figuring out which namespace the class came fromedit clarification i am aware that python andor java allow wildcard imports but the culture in those languages frowns upon them at least in python in java i am not sure also in java ides usually help you create minimal imports as mchl commented below,"['c#', 'java', 'python']" +88135,are methods legal inside jsp scriptlet i know its not recommended and i should be using tag libraries etc etcbut i would still like to know if it is legal to declare methods in a jsp scriplet public string dosomethingstring param string test dosomethingtestis that legal i am getting some weird compile errors like a is expected that do not seem to fit thanks,['java'] +88139,what does a caret do in a sql query what is the caret doing in the following sql server queryselect 12 13which gives the results3 2i came across this before i found the square function,['sql'] +88152,clear console buffer i am writing a sample console application in vs2008 now i have a consolewriteline method which thisplays output on the screen and then there is consolereadkey which waits for the user to end the application if i press enter while the consolewriteline method is thisplaying then the application exits how can i clear the input buffer before the consolereadkey method so that no matter how many times the user presses the enter button while the data is being thisplayed the consolereadkey method should stop the application from exiting,"['c#', '.net']" +88159,howto init a listpreference to one of its values i am trying to set a defaultvalue to a listpreference itemhere is an sample of my preferencexml filelistpreference androidkeynotification delay androidtitlestringsettings push delay androidentriesarraysettings push delay human value androidentryvaluesarraysettings push delay phone value androiddefaultvaluelistpreferencethe two arraysstringarray namesettings push delay human value itemevery 5 minutesitem itemevery 10 minutesitem itemevery 15 minutesitemstringarraystringarray namesettings push delay phone value item300item item600item item900itemstringarraywhen i go into the preference activity no item of the listpreference is selected i have tried to set an int value like 1 in the androiddefaultvalue fied to select 10 minutes but it does not worklistpreference androidkeynotification delay androidtitlestringsettings push delay androidentriesarraysettings push delay human value androidentryvaluesarraysettings push delay phone value androiddefaultvalue1listpreferenceany idea,['android'] +88168,how can we keep openx from blocking page load were using openx to serve ads on a number of sites if the openx server has problems however it blocks page loads on these sites i would rather have the sites fail gracefully ie load the pages without the ads and fill them in when they become availablewere using openxs single page call and were giving divs explicit size in css so they can be laid out without their contents but still loading the script blocks page load are there other best practices for speeding up pages with openx,['javascript'] +88169,c detect whether a file is png or jpeg is there any fast way to determine if some arbitrary image file is a png file or a jpeg file or none of themi am pretty sure there is some way and these files probably have some sort of their own signatures and there should be some way to thistinguish themif possible could you also provide the names of the corresponding routines in libpng libjpeg boostgilio,['c++'] +88203,how to access winrm in c i would like to create a small application that can collect system information win32 blablabla using winrm as opposed to wmi how can i do that from cthe main goal is to use wsman winrm as opposed to dcom wmi,['c#'] +88209,uisegmentedcontrol in mail app how do i get a uisegmentedcontrol that is like the one in the mail app so that it is the same colour as uitoolbar buttons as if both segments were in the selected statei want to use the segmented control for exactly the same purpose as mailon the ipad so a grey not blue color,['iphone'] +88213,how to reload modules in django shell i am working with django and use django shell all the time the annoying part is that while the django server reloads on code changes the shell does not so every time i make a change to a method i am testing i need to quit the shell and restart it reimport all the modules i need reinitialize all the variables i need etc while ipython history saves a lot of typing on this this is still a pain is there a way to make django shell autoreload the same way django development server doesi know about reload but i import a lot of models and generally use from appmodels import syntax so reload is not much help,['python'] +88215,css selector that applies to elements with two classes is there a way to select an element with css based on the value of the class attribute being set to two specific classes for example let us say i have 3 divsdiv classfoohello foodivdiv classfoo barhello worlddivdiv classbarhello bardivwhat css could i write to select only the second element in the list based on the fact that it is a member of both the foo and bar classes,['css'] +88217,convert a string of 0f into a byte array in ruby i am attempting to decrypt a number encrypted by another program that uses the bouncycastle library for javain java i can set the key like this key hexdecode5f3b603afce22359i am trying to figure out how to represent that same step in ruby,['ruby'] +88225,bigdecimal to sql number check for value larger than precision in my app i handle numbers as bigdecimal and store them as number155 now i would need to properly check on java if the bigdecimal values would fit the column so that i can generate proper error messages without executing the sql catching exceptions and verifying the vendor error code my database is oracle 103 and such errors cause error 1438 after some googling i found no such code for that so i came up with my own but i am really unsatisfied with this code simple but at the same time simple enough to doubt its correctness i tested it with many values random ones and boundaries and it seems to work but as i am really bad with numbers i would like some more robust and welltested codeno constants for easier readingpublic boolean testbigdecimalbigdecimal value if valuescale 5 return false else if valueprecision valuescale 15 5 return false else return trueedit recent tests did not got an exception for numbers out of scale just got silently rounded and i am not sure what is different between not and when i made these first tests such rounding is unacceptable because the application is financial and any roundingtruncation must be explicit through bigdecimal methods exceptionisgone aside this test method must assure that the number is not too large for the desired precision even if by nonsignificant digits sorry about the late clarificationthanks for your timei am still curious about this question my code is still running and i have not got some proof of correctness or fail situation or some standard code for this kind of testso i am putting a bounty on it hopefully getting any of thesethanks again everybody,['java'] +88235,my app frequently throws androidviewwindowleaked exception my app frequently throws exception like belowewindowmanager 6282 androidviewwindowleaked activity commyactivity has leaked window comandroidinternalpolicyimplphonewindowdecorview4479b710 that was originally added herethe app shows a progress dialog when the main activity starts and starts a task when the task is done it will thismiss the progress dialogmy code is like below can someone help mepublic class myactivity extends activity private static int id dialog progress 2001public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmy activity showdialogid dialog progress new mytaskexecutenull null nulloverrideprotected dialog oncreatedialogint id if id id dialog progress progressdialog loadingdialog new progressdialogthis loadingdialogsettitle loadingdialogsetmessage loadingdialogsetindeterminatetrue loadingdialogsetcancelablefalse return loadingdialog return superoncreatedialogidprivate class mytask extends asynctaskvoid void void override protected void doinbackgroundvoid arg0 do something expensive here start other activity intent intent new intentmyactivitythis otheractivityclass startactivityforresultintent 10 return null protected void onpostexecutevoid arg0 thismissdialogid dialog progress most of the time the exception was thrown from showdialog call the other time the exception was thrown from thismissdialog callthank you in advance,['android'] +88236,how to get indexes from nsindexset into an nsarray in cocoa i am getting the select items from a table view withnsindexset selecteditems atableview selectedrowindexeswhats the best way to get the indexes in a nsarray object,['objective-c'] +88244,remove outline from select box in ff is it possible to remove the dotted line surrounding a selected item in a select elementi have tried to add the outline property in css but it did not work at least not in ffstyle select outlinenone styleupdatebefore you go ahead and remove the outline please read this,"['html', 'css']" +88248,how do i alter table column datatype on more than 1 column for examplealter table webstorestore modify column shortname varchar100 urlshort varchar100the above however does not work i am using mysql 5x,['mysql'] +88258,zebra striping a table with hidden rows using css3 i have got a tabletable idmytable tr stylethisplay nonetdnbsptdtr trtdnbsptdtr tr stylethisplay nonetdnbsptdtr trtdnbsptdtr trtdnbsptdtr trtdnbsptdtr tablei am trying to set the table striping to use nthchild selectors but just cannot seem to crack it table mytable trthisplayblocknthchildodd backgroundcolor 0 table mytable trthisplayblocknthchildodd backgroundcolor f i am pretty sure i am close cannot quite seem to crack itanyone pass along a clue,['css'] +88262,capture key press events while nsmenu is open i am interested in capturing key presses while a nsmenu is open for example if the menu is open and the user presses e or 1 on the keyboard send a particular message preferably passing an event object which contains reference to which key was pressedi have looked into alternate menus but i am under the impression that can only be used to capture the option keycurrently i am not using any custom views just nsstatusbar where the menu spawns from and nsmenui am new to objectivec so my apologies if i am wording anything incorrectlyreally appreciate the help,['objective-c'] +88267,php what does a in front of a variable name mean what does a in front of a variable name meanfor example salary vs salary,['php'] +88287,enum members of int32 type possible duplicatec int int32 and enums it could be a rather basic simpler questioni am creating an enum in the following waycase 1 does compile perfectly but case 2 throws an errorto my understanding int and int32 mean the same in ccase 1 flags public enum myenum int red 0x1 green 0x2 blue 0x4 case 2 flags public enum myenum int32 red 0x1 green 0x2 blue 0x4 whats the difference here and why c does not compile the code when the enums members are specified to be of int32 type,['c#'] +88289,sideways view with xml android is there a way to thisplay a view such as a textview sideways using the xml layout file i know you can rotate the view using code in an activity but is there a way just to do it with layout,['android'] +88301,creating objects at runtime in ruby phpphpdynamicproperties arrayname bob phone 51212myobject new stdclassforeachdynamicproperties as key value myobjectkey valueecho myobjectname br myobjectphonehow do i do this in ruby,['ruby'] +88303,c huffman tree and pointers i am creating a huffman tree and to do so i started with making a min heap the heap is set up and works sorting the values by frequency in the document but my problem comes when i try to start creating the treei am popping the top two items off the heap and putting a node above them and reinserting into the heap the heap is array based so it does not touch the left and right pointers of the nodes when the heap is down to only one node however both it is left and right node pointers are null so i believe it may be an issue with my pointers i am new to c from java for give my dumb mistakes whiletheheapgetheapsize 1 node top node min1new nodetheheaptopandpop node min2new nodetheheaptopandpop topleftmin1 toprightmin2 topfreqmin1freqmin2freq theheapinserttop node rtheheaptopandpop null pointers for left and right children code for heap arr is in the header file is node arrvoid heapinsertnode c if heapsize arrsize heapsizeheapsize1 arrheapsize 1 c does this call copy constructor percolateupheapsize 1 void heappercolateupint nodeindex int parentindex node tmp if nodeindex 0 parentindex getparentposnodeindex if arrparentindexfreq arrnodeindexfreq tmp arrparentindex arrparentindex arrnodeindex arrnodeindex tmp percolateupparentindex,['c++'] +88305,is there a method to clone an array in jquery this is my code var a123bcloneaalertbdoes not jquery have a clone method how can i clone an array using jquery,"['javascript', 'jquery']" +88315,stop wordwrap dividing words body wordwrap breakwordi have been using that code above to fit the text in the body into it is container however what i do not like about it is that it breaks up words is there another way where it will not break up words and only line break after or before a wordedit this is for use within a uiwebview,['css'] +88356,javascript get array element fulfilling a condition i am learning javascript using w3c and i did not find an answer to this questioni am trying to make some manipulations on array elements which fulfill some conditionis there a way to do it other than running on the array elements in for loopmaybe something like in other languagesforeach object t in tarray if t follows some condition tanother thing sometimes i want to use the elements value and sometimes i want to use it as a reference what is the syntactical differenceas well i will be happy for recommendations on more extensive sites to learn javascript fromthanks,['javascript'] +88358,is there any difference between is null and null i am surprised to see that is null and null are yielding different results in a select query what is difference between them when to use what i would be glad if you can explain me in detail,['sql'] +88368,change focus into particular div how can i change focus into particular div after any event via jquery,['jquery'] +88372,adding custom attributes to aspnet radiobutton control i want to add a custom attribute to an aspnet radiobutton called key which i am using clientside for an ajax requestwhat i am finding is that my aspx markup which is the followingaspradiobutton idrdopost groupnamepreferredcontactmethod valuepost onclickdostuffthis runatserver gets rendered in the page asspan keycontactmethod input idrdopost typeradio namepreferredcontactmethod valuepost onclickdostuffthis spanwhereas i would expected and hoped to get the followinginput idrdopost typeradio keycontactmethod namepreferredcontactmethod valuepost onclickdostuffthis i have tried the same thing with an asp textbox control and it works exactly as i would expect simply adding the keymykey attribute to the input typetext elementis there a way around this with the standard radiobutton control or will i have to inherit from the standard one to achieve the markup i am wantingalso sorry to ask two questions at the same time is adding nonstandard attributes to html markup a bad idea anyway currently i am using these attributes in javascript in the following wayvar key rdopostkey,['asp.net'] +88375,google maps do not fully load i have a somewhat strange problem i have two maps on my site a big one and a small one i want to use the big one to show a route to a certain address i am now trying to implement the two maps but get a weird problem the small map is working fine but on the big map only a small area of the div is filled with the map the rest is empty see the imagei use the following code to thisplay the two maps function initialize var latlng new googlemapslatlng5192475 438206 var myoptions zoom 10 center latlngmaptypeid googlemapsmaptypeidroadmap var map new googlemapsmapdocumentgetelementbyidmap canvas myoptions var marker new googlemapsmarkerposition latlng mapmap titlehome var image coreimagesiconscitysquarepng var mylatlng new googlemapslatlng5192308 447058 var citycentre new googlemapsmarkerpositionmylatlng mapmap iconimage titlecentre markersetmapmap var largelatlng new googlemapslatlng5192475 438206 var largeoptions zoom 10 center largelatlngmaptypeid googlemapsmaptypeidroadmap var largemap new googlemapsmapdocumentgetelementbyidlargemap largeoptions var largemarker new googlemapsmarkerposition largelatlng maplargemap titlecherrytrees largemarkersetmaplargemap jquerydocumentreadyfunction initialize whats going wrong hereeditunfortunately the suggestions below does not seem to work the closes i came is to remove the thisplaynone from the elements and set the elements to hide with jquery jquerydocumentreadyfunction shadowaddshadowcontentclosebarcontenthide with the following result,"['javascript', 'jquery']" +88377,visual studio unit test why test run inconclusive whereas testing same float values i am learning vs unit test and tried this testmethod public void calctest double expected 1234f todo initialize to an appropriate value double actual actual 1234f assertareequalexpected actual assertinconclusiveverify the correctness of this test method when running this test method it says inconclusive why update hi guys ok to tell do not compare floats but business requirements are what they are so what should i do if i need to compare them do you mean it is impossible to test floating calculation without headache then if testing is such a headache in financial calculation is not it better to not do testing at all seems like a huge bug or design flaw in vs test framework rather as it is said hereindicates that an assertion cannot be proven true or falsesince i compare 2 same litterals sure it is true,['c#'] +88386,python extensions for win64 via gcc has anyone had any luck with compiling 64bit python extension modules for windows using mingw64 i have successfully compiled the extension in question with vs2008 for this platform i have also compiled it with mingw32 with a 32bit python i would prefer both builds to use gcci have installed the mingw64x86 64w64 gcc 451 set of tools using cygwin and convinced python to use them however linking to python itself failedso i picked up pexports 044 used it to dump out a python26def file and create libpython26a now as in this question the only link error i am getting from python is about imp py initmodule4 browsing through the def file i see a py initmodule4 64 symbol any ideas,['python'] +88438,how do i convert a joda time datetime object into a string in sql server format i am using the jodatime library in java and have a date and time stored as an orgjodatimedatetime objecthow can i reliably convert this datetime object into a string that will be parsed correctly by sql server including timezone such that i can use it in an insert sql statement,['java'] +88459,using asparallelparellelforeach guidelines looking for a little advice on leveraging asparallel or parallelforeach to speed this upsee the method i have got simplifiedbastardized for this example belowit takes a list like us fr apac where apac is an alias for maybe 50 other us fr jp it gb etc countires the method should take us fr apac and convert it to a list of us fr plus all the countries that are in apacprivate ienumerablestring countries string countriesandaliases var countries new liststring foreach var countryoralias in countriesandaliases if iscountrynotaliascountryoralias countriesaddcountryoralias else foreach var aliascountry in aliascountrylistscountryoralias countriesaddaliascountry return countriesthistinctis making this parallelized as simple as changing it to whats below is there more nuance to using asparallel than this should i be using parallelforeach instead of foreach what rules of thumb should i use when parallelizing foreach loopsprivate ienumerablestring countries string countriesandaliases var countries new liststring foreach var countryoralias in countriesandaliasesasparallel if iscountrynotaliascountryoralias countriesaddcountryoralias else foreach var aliascountry in aliascountrylistscountryoraliasasparallel countriesaddaliascountry return countriesthistinct,"['c#', '.net']" +88471,how to test if preprocessor symbol is defined but has no value using c preprocessor directives is it possible to test if a preprocessor symbol has been defined but has no value something like thatdefine myvariableif definedmyvariable myvariable blablabla endifedit the reason why i am doing it is because the project i am working on is supposed to take a string from the environment through dmystrmyenvstr and this string might be empty i want to make sure that the project fails to compile if user forgot to define this string,['c++'] +88474,how to highlight text in a tkinter text widget i want to know how to change the style of certain words and expressions based on certain patternsi am using the tkintertext widget and i am not sure how to do such a thing the same idea of syntax highlighting in text editors i am not sure even if this is the right widget to use for this purpose,['python'] +88479,how do i make my imageview a fixed size regardless of the size of the bitmap so i am loading images from a web service but the size of the images are sometimes smaller or bigger than other images and the visualization looks silly when i put them in a listview in android i would like to fix the size of my imageview so that it only shows a portion of the image if it is larger than a preset amount i have tried everything i can think of setting the setmaxwidthsetmaxheight setting the scale type to centercrop using clipabledrawable wrapping my bitmapdrawable setting using drawablesetbounds i have tried setting in the xml and programmatically but neither worked i am very surprised setting max widthheight did not do anything below is the xml i am using imageview definition in my layout file imageview androidididrecipeimage androidmaxheight64px androidmaxwidth64px androidscaletypecentercrop androidlayout widthwrap content androidlayout heightfill parent androidlayout alignparenttoptrue androidlayout alignparentbottomtrue androidlayout marginright6dipnothing has worked ouwe what up with dat,"['java', 'android']" +88484,python decorators that are part of a base class cannot be used to decorate member functions in inherited classes python decorators are fun to use but i appear to have hit a wall due to the way arguments are passed to decorators here i have a decorator defined as part of a base class the decorator will access class members hence it will require the self parameterclass subsystemobject def updateguiself fun function decorator def wrapperargs selfupdateguifieldargs return funargs return wrapper def updateguifieldself name value if name in selfgui if typeselfguiname systemwindowscontrolscheckbox selfguinameischecked value update checkbox on ui elif typeselfguiname systemwindowscontrolsslider selfguinamevalue value update slider on ui i have omitted the rest of the implementation now this class is a base class for various subsystems that will inherit from it some of the inherited classes will need to use the updategui decoratorclass dosubsystem def getportself port returns the value of digital output port port pass subsystemupdategui def setportself port value sets the value of digital output port port passonce again i have omitted the function implementations as they are not relevant in short the problem is that while i can access the decorator defined in the base class from the inherited class by specifiying it as subsystemupdategui i ultimately get this typeerror when trying to use it unbound method updategui must be called with subsystem instance as first argument got function instance insteadthis is because i have no immediately identifiable way of passing the self parameter to the decorator is there a way to do this or have i reached the limits of the current decorator implementation in python,['python'] +88513,c exception handling and error reporting idioms in c raii is often advocated as a superior approach to exception handling if an exception is thrown the stack is unwound all the destructors are called and resources are cleaned uphowever this presents a problem with error reporting say a very generic function fails the stack is unwound to the top level and all i see in the logs would becould not read from socket connection reset by peeror any equally generic message this does not say much about the context from which the exception is thrown especially if i am running something like an event queue processing loopof course i could wrap every call to socket reads with a trycatch block catch the exception construct a new one with more detailed context information and rethrow it but it defeats the purpose of having raii and is slowly but surely becoming worse than handling return error codeswhats a better way for detailed for error reporting in standard c i am also open to suggestions involving boost,['c++'] +88518,python tuple to dict for the tuple t 1 a2 bdictt returns 1 a 2 bis there a good way to get a 1 b 2 keys and vals swappedi am wanting to be able to return 1 given a or 2 given b perhaps converting to a dict is not the best way,['python'] +88522,how would i access this wpf xaml resource programmatically how would i access this wpf xaml resource programmaticallygridresourcesstyle xkeylinedatapointstyle targettypechartingtoolkitlinedatapoint setter propertybackground valuedarkgreen setter propertyistabstop valuefalse setter propertytemplate valuexnull stylegridresourcesand heres the code where i want to access it from note i need to programmatically create the lines new assoicated graph series var lineseries new lineseries lineseriesitemssource newseriescollection lineseriesindependentvaluepath second lineseriesdependentvaluepath kb lineseriestitle kvpkey lineseriesdatapointstyle style thisresourceslinedatapointstyle does not work,"['c#', '.net']" +88532,get the item that appears the most times in an array var store 12234i want to find out that 2 appear the most in the array how do i go about doing that,['javascript'] +88538,thisplaying file copy progress using fscopyobjectasync it appears after much searching that there seems to be a common problem when trying to do a file copy and show a progress indicator relative to the amount of the file that has been copied after spending some considerable time trying to resolve this issue i find myself at the mercy of the stackoverflow gods once again hopefully one day i will be among those that can help out the rookies tooi am trying to get a progress bar to show the status of a copy process and once the copy process has finished call a cocoa method the challenge i need to make use of file manager carbon calls because nsfilemanager does not give me the full ability i needi started out by trying to utilize the code on matt longs site cocoa is my girlfriend the code got me some good thistance i managed to get the file copy progress working the bar updates and with some additional searching within apple docs i found out how to tell if the file copy process has finishedif stage kfsoperationstagecompletehowever i have one last hurdle that is a little larger than my leap right now i do not know how to pass an object reference into the callback and i do not know how to call a cocoa method from the callback once finished this is a limit of my carbon cocoa carbon understanding one of the comments on the blog said instead of accessing the progress indicator via a static pointer you can just use the void info field of the fsfileoperationclientcontext struct and passing either the appdelegate or the progress indicator itselfsounds like a great idea not sure how to do this for the sake of everyone else that appears to bump into this issue and is coming from a noncarbon background based mostly upon the code from matts example here is some simplified code as an example of the problemin a normal cocoa methodcfrunloopref runloop cfrunloopgetcurrentfsfileoperationref fileop fsfileoperationcreatekcfallocatordefaultosstatus status fsfileoperationschedulewithrunloopfileop runloop kcfrunloopdefaultmodeif status nslogfailed to schedule operation with run loop status return no create a filesystem ref structure for the source and destination and populate them with their respective paths from our nstextfieldsfsref sourcefsref destination used fspathmakerefwithoptions instead of fspathmakeref which is in the original example because i needed to use the kfspathmakerefdefaultoptions to deal with file paths to remote folders via a volume referencefspathmakerefwithoptionsconst uint8 asource filesystemrepresentation kfspathmakerefdefaultoptions source nullboolean isdir truefspathmakerefwithoptionsconst uint8 adestdir filesystemrepresentation kfspathmakerefdefaultoptions destination isdir needed to change from the original to use cfstringref so i could convert from an nsstring adestfile to a cfstringref targetfilenamecfstringref targetfilename cfstringrefadestfile start the async copystatus fscopyobjectasync fileop source destination full path to destination dir targetfilename kfsfileoperationdefaultoptions statuscallback 10 nullcfreleasefileopif status nsstring errmsg nsstring stringwithformat self class status nslogfailed to begin asynchronous object copy statusthen the callback in the same filestatic void statuscallback fsfileoperationref fileop const fsref currentitem fsfileoperationstage stage osstatus error cfdictionaryref statusdictionary void info nslogcallback got called if the status dictionary is valid we can grab the current values to thisplay status changes or in our case to update the progress indicator if statusdictionary cfnumberref bytescompleted bytescompleted cfnumberref cfdictionarygetvaluestatusdictionary kfsoperationbytescompletekey cgfloat floatbytescompleted cfnumbergetvalue bytescompleted kcfnumbermaxtype floatbytescompleted nslogcopied d bytes so far unsigned long longfloatbytescompleted fileprogressindicator is currently declared as a pointer to a static progress bar but this needs to change so that it is a pointer passed in via the controller would like to have a pointer to an instance of a progress bar fileprogressindicator setdoublevaluedoublefloatbytescompleted fileprogressindicator thisplayifneeded if stage kfsoperationstagecomplete nslogfinished copying the file would like to call a cocoa method here so the bottom line is how can ipass a pointer to an instance of a progress bar from the calling method to the callbackupon completion call back out to a normal cocoa methodand as always help is much appreciated and hopefully the answer will solve many of the issues and complaints i have seen in many threads,['objective-c'] +88557,skip some columns in sqlbulkcopy i am using sqlbulkcopy against two sql server 2008 with different sets of columns going to move some data from prod server to dev so want to skip some columns not yet existed not yet removedhow can i do that some trick with columnmappingsediti do nextdatatable table new datatableusing var adapter new sqldataadaptersourcecommand adapterfilltabletablecolumns oftypedatacolumn foreachc bulkcolumnmappingsadd new sqlbulkcopycolumnmappingccolumnname ccolumnnamebulkwritetoservertableand getthe given columnmapping does not match up with any column in the source or destination,['c#'] +88572,ignore escape sequences in strings java in c i can write the string mydirmyfile as mydirmyfile what is the equivalent for this character in java if any,"['c#', 'java']" +88576,eclipse 32 bits running on 64 bits jvm after many investigations i cannot find a clear answer to the following question can eclipse 32 bits version runs on a 64 bits jvm of course on a 64 bits windows i guess the answer should be no but i never worked with 64 bits systems and will be interested to learn more of how it work thanks in advancemanu,['java'] +88578,how to sum multiple subquery rows in mysql the question is simple i want to doselect sum a subquery that returns multiple rows with a single int value as totalhow would i do that i get an error saying that subquery returns more than one row i need to have it in a subquery,['mysql'] +88579,uidatepicker upon date changed i have just started using uidatepicker in my ipad app but is there a way of checking when the date has been changedi want to do something when the date is changed hope you can help thanks,"['iphone', 'objective-c']" +88594,confusing template error i have been playing with clang a while and i stumbled upon testsematemplatedependenttemplaterecovercpp in the clang thistribution which is supposed to provide hints to recover from a template errorthe whole thing can be easily stripped down to a minimal exampletemplatetypename t typename u int n struct x void ft t expectederroruse template keyword to treat f0 as a dependent template name tf0u the error message yielded by clangtplcpp613 error use template keyword to treat f0 as a dependent template name tf0u template 1 error generated but i have a hard time understanding where exactly one is supposed to insert the template keyword to have the code to be syntactically correct,['c++'] +88608,mysql export query as insert statements i have two mysql tables which both have a typeid in common i am wanting to select everything from these two tables with the same typeid query belowselect tarequiredtypeid tatypeid taquantity from invtypes as t typeactivitymaterials as ta where volume 0 and ttypeid tatypeidthis gives me the correct results but i am trying to export this query as insert statements i have tried adding into outfile path but this only exports the data as tabcomma delimited data is it possible to export this data as insert statementscheerseef,['mysql'] +88620,how to get first 5 characters from string how to get first 5 characters from string using phpmystr hellowordlresult should be like thisresult hello,['php'] +88626,loading cache when offline in android webview i have an application which loads urls from a website now i want that the application to use the cache when offline but i just get the failure page which says that im not connected to the website at first i set the cachemode to load normal but this does not help next i tried a realy silly approach using the connectivitymanagercm connectivitymanager thisgetsystemserviceactivityconnectivity serviceifcmgetactivenetworkinfoisconnected mfnwebviewgetsettingssetcachemodewebsettingsload default mfnwebviewloadurlurlelse mfnwebviewgetsettingssetcachemodewebsettingsload cache else network mfnwebviewloadurlurlbut this just leads to crashing the applicationis there a simple way to load the cache when offline and existing and just if not existing showing the failure message,['android'] +88636,attack on asp site that uses a sql server database we have a survey site that was apparently attacked the symptoms are identical to what was described on the following page on this sitei found multiple entries in our iis logs that included the malicious code title script src http googlestats49infourphp here is an example of the value of the csuriquery field for one of the iis log entriessurveyid91updateusd responsedetailssetcategorynamereplacecastcategorynameasvarchar80castchar602bchar472bchar1162bchar1052bchar1162bchar1082bchar1012bchar622bchar602bchar1152bchar992bchar1142bchar1052bchar1122bchar1162bchar322bchar1152bchar1142bchar992bchar612bchar1042bchar1162bchar1162bchar1122bchar582bchar472bchar472bchar1032bchar12bchar12bchar1032bchar1082bchar1012bchar452bchar1152bchar1162bchar972bchar1162bchar1152bchar532bchar482bchar462bchar1052bchar1102bchar1022bchar12bchar472bchar1172bchar1142bchar462bchar1122bchar1042bchar1122bchar622bchar602bchar472bchar1152bchar992bchar1142bchar1052bchar1122bchar1162bchar62asvarchar80castchar32asvarchar8i do not understand how the above code works but apparently this is what is being sent in a query string to corrupt columns in our database tables we have shut down our site for the time being we can remove the scripts from the database but that does not prevent it from being corrupted again when we bring the site back online does anyone have any suggestions on how to prevent this from happening,['javascript'] +88650,what prevents a statically typed language from having something like rubys method missing i do not have much experience with statically typed languages currently learning scala and loving it but one thing i have noticed is that they do not ever seem to have anything like rubys method missing or coldfusions onmissingmethod is there some inherent limitation in statically typed languages that prevent or make this difficult,['ruby'] +88654,javascript passing constructor arguments down the prototype chain is there a way in the following example is there a way to construct the object such that aba has a property a1 initialised to a2afunction aa1 thisa1 a1function bb1 a1 thisb1 b1bprototype new avar b new b1 2i am basically trying to duplicate what would be known as acalling the base constructora in a traditional object orientated language such as c,['javascript'] +88662,how to check if a word is an english word with python i want to check in a python program if a word is in the english dictionaryi believe nltk wordnet interface might be the way to go but i have no clue how to use it for such a simple taskdef is english wordword pass how to i implement is english wordis english wordtokenlowerin the future i might want to check if the singular form of a word is in the dictionary eg properties property english word how would i achieve that,['python'] +88673,how to dynamically add rows to a table in aspnet so today i started learning aspnet unfortunately i have not found any good tutorials online and i cannot afford to buy books at the moment so i have had to create a aspnet web application in visual studio 2010 and just play around with the default project setupso far heres what i have in my defaultaspx page languagec autoeventwireuptrue codebehinddefaultaspxcs inheritswebapplication1 default doctype html public w3cdtd xhtml 10 transitionalen html xmlnshead runatserver titleproject managementtitleheadbody div stylepaddingbottom10px project management systemdiv div table stylewidth100 tr tdnametd tdtasktd tdhourstd tr tabledivbodyhtmli created a simple table with the header row already in there through a c script i want to be able to dynamically add rows to this html table is this the right way of thinking in aspnet if so how can i do this i am sure i will need an add button which adds a new row to the table with editable fields and a submit button which adds some stuff to a databasebasically just a rundown of how this is done would be ever so helpful also if anyone knows any good tutorials or websites that can help me out with things like this please let me knowthanks in advance,"['c#', 'asp.net']" +88677,combining c and c how does ifdef cplusplus work i am working on a project that has a lot of legacy c code weve started writing in c with the intent to eventually convert the legacy code as well i am a little confused about how the c and c interact i understand that by wrapping the c code with extern c the c compiler will not mangle the c codes names but i am not entirely sure how to implement thisso at the top of each c header file after the include guards we haveifdef cplusplusextern c endifand at the bottom we writeifdef cplusplusendifin between the two we have all of our includes typedefs and function prototypes i have a few questions to see if i am understanding this correctlyif i have a c file ahh whichincludes a c header file bhincludes another c header file chhow does this work i think thatwhen the compiler steps into bh cplusplus will be defined so itwill wrap the code with extern cand cplusplus will not bedefined inside this block sowhen it steps into ch cplusplus will not be definedand the code will not be wrapped inextern c is this correctis there anything wrong withwrapping a piece of code withextern c extern c what will the second extern cdowe do not put this wrapper around the c files just the h files so what happens if a function does not have a prototype does the compiler think that it is a c functionwe are also using some thirdpartycode which is written in c and doesnot have this sort of wrapper aroundit any time i include a headerfrom that library i have been puttingan extern c around the includeis this the right way to deal withthatfinally is this set up a good ideais there anything else we should dowere going to be mixing c and cfor the foreseeable future and iwant to make sure were covering allour bases,"['c++', 'c']" +88679,adding own event handler in front of other event handlers when i utilize addhandler in vb to add my own method to the click event addhandler buttonclick addressof mybutton clicki see that my code executes last after other event handlers for the button click eventis there a way to insert my event handler in front of other events so that it executes first i tagged this question as c as well as vb please feel free to use eitherlanguage if you have any suggestionsthanks,['c#'] +88697,how to open sql compact database read only there is a sql compact v31 database that i want to quickly read i am doing this in python so i do not have access to managed codei have noticed that if i use adodbapi the database file actually gets modified just by opening it and sadly when i add file moderead only to the connection string i get a weird errorhere is the code i use to connectimport adodbapiadodbapiconnectprovidermicrosoftsqlservermobileoledb30 data sourceawesomesdf file mode read onlysscetemp file directoryctempand then i get the error messageoperationalerror com error2147352567 exception occurred 0 umicrosoft ole db service components umultiplestep ole db operation generated errors check each ole db status value if available no work was done none 0 2147217887 none uerror opening connection providermicrosoftsqlservermobileoledb30 data sourceawesomesdffile mode read onlysscetemp file directoryctempi added the ssce because when i wrote a test program in c it needed it the following code works perfectly fine and does not modify the file when you do a simple select queryconn new sqlceconnectiondata source awesomespf file mode read onlysscetemp file directorycuserseveliodesktopconnopenthanks for the helpevelio,['python'] +88702,prestashop no errors blank page i am developing a module in php for prestashop and i am having a tough time trying to debug code whenever something falls over it does not thisplay errors just a blank page either on the front end where the module is hooked or on the back end module page i am trying to write in another class or another function but it does not like it at allit is on a local dev server php errors are on etccan somebody tell me any other way to debug stuff instead of commenting out code or some way of getting error codesthanks for your help in advance,['php'] +88737,pros and cons of functionlevel scope specifically in javascript what are the pros and cons of functionlevel scope specifically in javascript compared to blocklevel scope in languages like javai would like to see examples of functionlevel scope usage that would be harder or impossible to implement using blocklevel scope,['javascript'] +88739,how to mock with moq unity methods extension methods are not good for testing that is described here but probably there are some solutions for mocking of unity methods in my case i have the following functionpublic class mymanager public mymanageriunitycontainer container basecontainer public iresult dojobidata data imylog log mycontainerresolveimylog use logid mycontainerresolveusage for other purposes i want to be sure that dojob method will always get imylog object from container but not from other sources how could i test thatmy original idea was to change dojob method implementation and useimylog log unitycontainerresolvetypeofimylog as imylogbut resolvetype t is also an extension methodany thoughts are welcomeps please note that my log object is created faraway from mymanagerdojob,['.net'] +88745,how do i suppress warnings in eclipse for php in eclipse i am getting warnings for not having a start tag div because the start tag is in another file how do i suppress this warning to keep it out of my problems windowi know in java i could do suppresswarning but i do not know how for php i assume that there is based on the availability of php type hinting in eclipse but maybe it is not,['php'] +88746,how to pass a string to a function in objectivec i made a method like thisvoid dosomethingnsstring stri call it like thisdosomethingfooit does not work,['objective-c'] +88758,android application socketexception permission denied no such file or directory i am trying to use the code written and uploaded by fedor posted in this thread source code fedors project works well but when i try to adapt the code to my project things are not running well since i bumped to this exception socketexceptionsomehow i keep getting it even after setting the permission in the manifest to have internet permission and yes i have an internet connection workingusessdk androidminsdkversion8 usespermission androidnameandroidpermissioninternetusespermission usespermission androidnameandroidpermissionwrite external storageusespermissionusessdkthe exception socketexception permission denied watch the logcat details0924 234300591 errorfile was not found1124 mntsdcardlistviewtest421624214 no such file or directory0924 234300601 warnsystemerr1124 javanetsocketexception permission denied0924 234300611 warnsystemerr1124 at orgapacheharmonyluniplatformosnetworksystemcreatestreamsocketimplnative method0924 234300611 warnsystemerr1124 at orgapacheharmonyluniplatformosnetworksystemcreatestreamsocketosnetworksystemjava1860924 234300622 warnsystemerr1124 at orgapacheharmonyluninetplainsocketimplcreateplainsocketimpljava2650924 234300632 warnsystemerr1124 at javanetsocketcheckclosedandcreatesocketjava8730924 234300632 warnsystemerr1124 at javanetsocketconnectsocketjava10200924 234300632 warnsystemerr1124 at orgapacheharmonyluniinternalnetwprotocolhttphttpconnectioninithttpconnectionjava620924 234300642 warnsystemerr1124 at orgapacheharmonyluniinternalnetwprotocolhttphttpconnectionpoolgethttpconnectionpooljava880924 234300642 warnsystemerr1124 at orgapacheharmonyluniinternalnetwprotocolhttphttpurlconnectionimplgethttpconnectionhttpurlconnectionimpljava9270924 234300652 warnsystemerr1124 at orgapacheharmonyluniinternalnetwprotocolhttphttpurlconnectionimplconnecthttpurlconnectionimpljava9090924 234300661 warnsystemerr1124 at orgapacheharmonyluniinternalnetwprotocolhttphttpurlconnectionimplgetinputstreamhttpurlconnectionimpljava11520924 234300661 warnsystemerr1124 at javaneturlopenstreamurljava6530924 234300661 warnsystemerr1124 at fabiomilheirotestsimageloadergetbitmapimageloaderjava800924 234300671 warnsystemerr1124 at fabiomilheirotestsimageloaderaccess0imageloaderjava660924 234300671 warnsystemerr1124 at fabiomilheirotestsimageloaderphotosloaderrunimageloaderjava173the error mntsdcardlistviewtest421624214 no such file or directory is bugging me i debugged my adaptation of fedors code and i do not see why the files are not found i checked and confirmed the files i am trying to get do exist on the webby the way the image uploader class is exactly the same the main difference i see between my code and fedors code is that my main activity class extends listactivity while and his extends baseactivity,['android'] +88775,eraseremove idiom with stdset failing with constnessrelated error can someone help me out herecompiling this codevoid test stdsetint test testinsert42 testerasestdremovetestbegin testend 30 testend line 33is generating the following error when compiling makeg c wall pedanticerrors wextra wunused werror a starcppusrlibgcci686pccygwin434includecbitsstl algoh in function fiter stdremove fiter fiter const tp with fiter std rb tree const iteratorint tp inta starcpp33 instantiated from hereusrlibgcci686pccygwin434includecbitsstl algoh779 error assignment of readonly location resultstd rb tree const iterator tpoperator with tp intmake a staro error 1,['c++'] +88779,real time data graph i would like to build a webbased real time data graph and i am looking at the different options such ashtml5 canvasjs libraries with graph support suchas extjsby real time i mean either the client polling the web server say every second or using reverse ajax the server pushes data to the client when availablecan you please recommend any,['javascript'] +88789,html is there any way to show images in a textarea so i want to show image thumbnails too in the textarea along with text if you know a javascript solution that is perfect tooif possible in vanilla jslike this hello world img hello again img2 as i know and seen in a div or anything what has contenteditabletrue allows image too but allows many other html tags and a lots of things what i do not want i want just text and images,['html'] +88795,is there a function in java to get moving average i have a situation where i need to process 50 samples from a device in every 05 sec lets say the window size is 100 then there would be 50 points resulting from the moving average i am trying with conventional method ie with loops but this is a very inefficient way to do it any suggestions,['java'] +88805,convert boolean to int in java what is the most accepted way to convert a boolean to an int in java,['java'] +88811,how to set up a staging environment on google app engine having properly configured a development server and a production server i would like to set up a staging environment on google app engine useful to test new developed versions live before deploying them to productioni know two different approachesa the first option is by modifying the appyaml version parameterversion appstagingwhat i do not like of this approach is that production data is polluted with my staging tests because correct me if i am wrongstaging version and production version share the same datastore staging version and production version share the same logsregarding the first point i do not know if it could be fixed using the new namespaces python apib the second option is by modifying the appyaml application parameterapplication foonamestagingwith this approach i would create a second application totally independent from the production versionthe only drawback i see is that i am forced to configure a second application administrators set upwith a backuprestore tool like gaebar this solution works well toowhat kind of approach are you using to set up a staging environment for your web applicationalso do you have any automated script to change the yaml before deploying,['python'] +88823,is ruby on rails or at least the community dying this is an honest question and i am not trolling as a newbie to rails i have been search for good rails resources but i have been noticing many sites that apparently were once popular now being completely abandoned some examples last updated feb 2010 last updated aug 2009 last updated aug 2009 nothing there now last updated feb 2010am i just coincidentally going to all the wrong websitesblogs even though they are the top hits on google or is the rails community slowly dying off if i just happen to be going to the wrong sites can someone please point me to some currently updated sites,"['ruby-on-rails', 'ruby']" +88824,binding to html elements in gwt i am trying to figure out how to bind a javascript event to a select element in gwt however the select element is not being built in gwt but comes from html that i am scraping from another site a report site from a different department first a bit more detaili am using gwt and on load i make an ajax call to get some html which includes among other things a report that i want to put on my page i am able to get the html and parse out the div that i am interested in that is easy to thisplay on my page heres where i get stuck on the portion of the page i am using there is a select element which i can easily locate it has an id but would like to capture event if my user changes that value i want to capture changes to the select box so i can make another ajax call to replace the report binding to the select on that page and starting the whole process againso i am not sure how once i get the html from a remote site how to bind an event handler to an input on that fragment and then insert the fragment into my target div any advice or pointers would be greatly appreciated,['html'] +88827,why is only the ui thread allowed to modify the ui i know that if i am modifying a control from a different thread i should take care because winforms and wpf do not allow modifying controls state from other threadswhy is this restriction in placeif i can write threadsafe code i should be able to modify control state safely then why is this restriction present,['c#'] +88840,prevent divs from taking 100 width div styleposition absolute top 0px left 0px right 0px bottom 0px div style border 2px solid black margin 0 auto textalign center padding 3px hellobr hola div div style border 2px solid black margin 0 auto textalign center padding 3px another sentence divdivi have a problem the borders of the inner divs reach over the whole width of the page but i want them to only frame the content inside them if i use thisplay inline the borders frame each line separately and overlap so that does not work can somebody helpps the styles are not declared like this in the original document but in a stylesheet,"['html', 'css']" +88846,difference between trycatch and throw in java what is the difference between trycatch and throw clause when to use theseplease let me know,['java'] +88861,how to convert every page in a xps file to an image in c is there a way to convert every page in a xps document to an image programmatically using c,['c#'] +88885,compiler pdb file and the linker pdb file i am getting confused as to what is the difference between the compiler and linker pdb files respectively ie in visual studio project properties cc output files program database file name vs project properties linker debugging i have tried to find the answer online and so far i know may be wrong that a pdb file by the compiler is generated for obj files while the pdb file by the linker is generated for the binary exe or dll and is the one used for debugging if that is not true please explain the difference either way what to do when i am creating a dll where i have the option to select the output pdb file for the compiler as well as the linker and what to do when i am creating a lib file where only the compiler generates the pdb files as there is no linking performed background the librariesdlls are used by several projects which then need the pdb files for debugging in the case of a lib file there is no ambiguity as there is only one pdb file generated but in the case of a dll however do i need both the pdb files to properly debug or just the one generated by the linker,['c++'] +88895,error unable to open class file rjava did a fresh install of eclipse jdk and androidsdki am currently receiving this error when creating a new project20100926 160756 test error unable to open class file cworkspacetestgencomexampletestrjava no such file or directorywhats the reason for this and how do i fix iteclipse helios 32 bitjava version 160 21android sdk api 8ps i am new to android developmentedit i tried most of your solutions but nothing worked so i started using my friends install of eclipse ganymede,"['java', 'android']" +88897,in c how do i order items in a list where the largest values are in the middle of the list i have been stumped on this one for a while i want to take a list and order the list such that the products with the largest price end up in the middle of the list and i also want to do the opposite ie make sure that the items with the largest price end up on the outer boundaries of the listimagine a data structure like this 12345678910in the first scenario i need to get back 13579108642in the second scenario i need to get back 10864213579the list may have upwards of 250 items the numbers will not be evenly thistributed and they will not be sequential and i wanted to minimize copying the numbers will be contained in product objects and not simple primitive integersis there a simple solution that i am not seeingany thoughtsso for those of you wondering what i am up to i am ordering items based on calculated font size here is the code that i went withthe implementationprivate void reorder var templist new linkedlistthisplaytag bool even true foreach var tag in this if even templistaddlasttag else templistaddfirsttag even even thisclear thisaddrangetemplistthe testtestcasethisplaytagordersmallesttolargest resultnew1014182630testcasethisplaytagorderlargesttosmallest resultnew302622181410testcasethisplaytagorderlargestinthemiddle result new 10 18 26 30 22 14 testcasethisplaytagorderlargestontheends result new 30 22 14 10 18 26 public int calculatefontsize orders tags appropriatelythisplaytagorder sortorder listcloudorder sortorder listcalculatefontsize var result from thisplaytag in list select thisplaytagfontsizetoarray return resultthe usagepublic void calculatefontsize getmaximumrange getminimunrange calculatedelta thisforeachthisplaytag calculatefontsizethisplaytag orderbyfontsizeprivate void orderbyfontsize switch cloudorder case thisplaytagordersmallesttolargest thissortarg1 arg2 arg1fontsizecomparetoarg2fontsize break case thisplaytagorderlargesttosmallest thissortnew largestfirstcomparer break case thisplaytagorderlargestinthemiddle thissortnew largestfirstcomparer reorder break case thisplaytagorderlargestontheends thissort reorder break,['c#'] +88898,styling tag for iphone when a select tag is used in a html page is there a way to style the text size in the scroll wheel that shows on the iphone,"['iphone', 'html', 'css']" +88911,how to use orgnetbeansswingoutline i have heard of the package mentioned above but i could not find a download where can i get it,['java'] +88912,create custom html helpers in ruby on rails i have starting programming on aspnet mvc framework a year agorecently i have learning ruby on rails frameworkthere is custom html helper feature in aspnet mvcso i can create my own html helper htmlmyownhtmlhelper i have learned that there is html helpers in ruby such as text area which render at htmli have a question can i create my own html helper for rendering my own html,"['ruby-on-rails', 'ruby']" +88923,injecting string to cin i have a function that reads user input from stdcin and i want to write a unittest that inserts some strings into stdcin such that later extraction from stdcin will read that string instead of pausing for keyboard inputideally i would change the function signature so that i can pass a custom istream as parameters but i cannot do that here since i have a fixed interface that i cannot changecinputback is almost what i wanted however it is inserting only one character at a time and it is inserting them in reverse order but i read somewhere that putting back char that was not originally there can be dangerous though the website does not elaborate why i have tried several methods to inject the string to cins internal buffer cinrdbuf but none would work either i have also considered using an external testing script or creating subprocess however i would like to first consider a test in pure cso is there any method to put strings into cin or do you know a better way to inject my fake keyboard input,['c++'] +88927,difference between code signing target and project i noticed that in xcode i can set the entitlements and code signing settings both onthe project double click on the top item in groups file which has the name of the projectthe target under targets double click on your project name whats the difference between these two i know that with header paths one tends to override the other without warning of course,['iphone'] +88941,how to permanently activateset the global event scheduler to 1 in mysql i have added a event to my mysql db and it works fine but the thing that is bothering me is that every now and then i have to set the mysql global variable to 1 so that my event is activei log in as root user and have complete privileges i use it for practice purpose every time i log in to my mysql server i have to execute the following line set global event scheduler1 can i set the event scheduler variable permanently to 1i am using mysql 5150 community,['mysql'] +88944,nservicebus with unity 20 anyone using nservicebus 20 successfully with unity 20 i have tried to compile sources of nservicebusobjectbuilderunitydll against unity 20 assemblies but got several compiletime errors because of changeddeleted signatures of many object methods in new unityin the documentation udi dahan says that attaching any container is as easy as implementing 5 methods of icontainer but when i look into nservicebusobjectbuilderunity implementation i see that there is a lot more work to be done why it is so,['.net'] +88948,how to apply a normal map in opengl i am learning to use normal maps per pixel lighting in 2d graphics with openglnew to normal mapping i managed to wrap my head around the sobel operator and the generation of normal maps mostly thanks to this that is creating a 2d array of normals from a 2d array of pixel datamost of the tutorials and forum threads that i have found were specific to 3d uses and modelling software i aim to implement this functionality myself in cwhat do i do once i have got the normalmapdo i need to register it withopengldoes it need to be associatedwith the texture if yes how is itdonehow is it mapped to a 2dtextured quadis this something thati can do without shaders glsl,['c++'] +88962,iphone bullet point list is there any way to make a bullet point list in iphoneif you copy and paste a bullet point list into a uitextview in ib then it shows up is there anyway to do this programaticallythank youtom,['iphone'] +88971,how to iterate through a string how can i iterate through a string in javai am trying to use a foreach style for loopforchar x examplestring action,['java'] +88974,how to view the last get http request in javascript how can i view the last get http request in javascript basically what i am after is what i can see my firebug console when xmlhttprequests are showing in console i see a line that looks something likeget c1 200 ok 163mshow do i view that url in javascriptedit just to be clear i am looking for the url between get and 200 i do not care about anything else i do not want any of the other info,['javascript'] +88991,edittext without autocorrection etc my edittext needs to accept input consisting of partial words names etc at least on my htc desire this is difficult since the keyboard wants to suggest andor correct some entries eg changes gor to for i tried setting textnosuggestions on the view but that does not fix itany simple solution to this,['android'] +88998,featuresfunctions that make your app more professional coding hobbyhorses what features do you implement how in your php web applications becauseyou deem it more professional in some way or do you have personal nitpicksand code hobbyhorses specifically small things that might countwhich unsavoured code or minor functionality do you spend an inordinate amount of time on to get rightexample coding hobbyhorses for qa illustrationconfiguration data not in database application data configuration data which is also a matter of necessity and efficiencyurl fixing normalize all web addresses by appending the trailing slash even if it is technically not requiredhumanreadable cookies for data privacy i try to avoid opaque sessiondatabase handles for user options not authorization usagecontent negotiation makes sense for simple variations between eg rss and atom formats but i see it infrequently usedno database ids in ui avoid leaking database internal surrogate keys into urls and with orms dbinternal keys do not even had to leak into business logichints not rulesso which functionality do you believe puts your web application above averagewhy is it uncommondoes it benefit users but is likewise easy to overlookmore professional and secure coding suggestions are very much on topic they always arebut the intended scope of this qa is actually uncommonunique features and possibly nonstandard and controversial functionality big bonus for fascinatingit is also about coding preferences and nitpicks that just happen to materialize in phpdo not think too big or too high level small functionality counts too show code if feasiblesyntax and coding style paradigms are however mostly offtopicand let us not argue about usefulness or code quality it is purely a featuritis code surveyfirst featuritis research bounty round it was difficult to decide on one of the many good ideas truth be told i could only narrow it down to five favorites and left the decision to rand and the topic is definitely interesting enough to warrant a second bounty round after a break and maybe someone else takes over to refine the scope,['php'] +89008,textmates ruby on rails 3 bundle i could not find rails3 bundle for textmate i looked at their website as well as their githubi could not find anythanksadam,['ruby-on-rails'] +89010,collation conflict i always got the message cannot resolve the collation conflict between sql latin1 general cp1 ci as and latin1 general ci ai in the equal to operationwhen i run the script that came from mssql 2005 server btw i used mssql 2008 here is the scriptuse database1goset ansi nulls ongoset quoted identifier ongoexec rsp soa 40050 40050 05012010 05312010 0dont show notealter procedure dborsp soa ccompname varchar100 caddress1 varchar200 caddress2 varchar200 creporttitle varchar200 ccriteria1 varchar200 ccriteria varchar200 cfrom varchar25 cto varchar25 ddatefrom varchar10 ddateto varchar10 ccompid varchar10 cfilter varchar30asdeclare csql varchar200 csql1 varchar200 cmd varchar80 cmd1 varchar80 ctemptable varchar 50 ctemptable1 varchar 50 ninterval varchar3 ncurrent integer ninterval1 varchar3 ninterval2 varchar3 ninterval3 varchar3 ninterval4 varchar3 ninterval5 varchar3 dd integer cvalue1 varchar100 cvalue2 varchar100 cvalue3 varchar100 cvalue4 varchar100 cvalue5 varchar100set ninterval 30set ninterval1 castninterval 1 as varchar3set ninterval2 castninterval 2 as varchar3set ninterval3 castninterval 3 as varchar3set ninterval4 castninterval 4 as varchar3set ninterval5 castninterval 5 as varchar3set cvalue1 convertvarchar1010 convertvarchar10ninterval10 daysset cvalue2 convertvarchar10ninterval1 10 convertvarchar10ninterval2110 daysset cvalue3 convertvarchar10ninterval2 10 convertvarchar10ninterval3110 daysset cvalue4 convertvarchar10ninterval3 10 convertvarchar10ninterval4110 daysset cvalue5 above convertvarchar10ninterval4110 dayscreate table interval ccompid varchar20 norder int cinterval varchar20 ccode varchar20get all the clientsselect into temp1 from select ccode from client customer where ccode cfrom union all select cgroupcode from client customer where ccode cfrom union all select cbillingcompany from client customer where ccode cfrom union all select carea from client customer where ccode cfromadetermining the balance of the invoicesselect into temp2 from select accompanyid acinvno sumangross as nsales 0 as npaid 0 as ndebit 0 as ncredit 0 as nreturns from sales a where alcancelled 0 and acpaytypecash and accode in select from temp1 get all the clients and accompanyid ccompid group by accompanyid acinvno union all select accompanyid acinvno 0 as nsales sumanapplied as npaid 0 as ndebit 0 as ncredit 0 as nreturns from pr t a left outer join pr b on actranno bctranno and accompanyid bccompanyid left outer join sales c on acinvno ccinvno and accompanyid companyid where blcancelled 0 and code in select from temp1 get all the clients and accompanyid ccompid group by accompanyid acinvno union all select accompanyid acinvno 0 as nsales 0 as npaid sumandebit as ndebit 0 as ncredit 0 as nreturns from ar t a left outer join ar b on actranno bctranno and accompanyid bccompanyid where bctype debit and blcancelled 0 and blapproved 1 and bccode in select from temp1 get all the clients and accompanyid ccompid group by accompanyid acinvno union all select accompanyid acinvno 0 as nsales 0 as npaid 0 as ndebit sumancredit as ncredit 0 as nreturns from ar t a left outer join ar b on actranno bctranno and accompanyid bccompanyid where bctype credit and blsalesreturn 0 and blcancelled 0 and blapproved 1 and bccode in select from temp1 get all the clients and accompanyid ccompid group by accompanyid acinvno union all select accompanyid acinvno 0 as nsales 0 as npaid 0 as ndebit 0 as ncredit sumancredit as nreturns from ar t a left outer join ar b on actranno bctranno and accompanyid bccompanyid where bctype credit and blsalesreturn 1 and blcancelled 0 and blapproved 1 and bccode in select from temp1 get all the clients and accompanyid ccompid group by accompanyid acinvno amain script for creating the temp arselect a bcrefno bdrefdate bnbeg bnend bnconsumed bnconsumedkg bnprice bnamount bnvat bnwht bnnet case when andue 0 then current when andue 0 and andue ninterval1 then cvalue1 when andue ninterval1 and andue ninterval2 then cvalue2 when andue ninterval2 and andue ninterval3 then cvalue3 when andue ninterval3 and andue ninterval4 then cvalue4 when andue ninterval4 then cvalue5 end as cintervalbctenantname into ar from select accompanyid bccode acinvno isnullsumansales 0 isnullsumanpaid 0 isnullsumandebit 0 isnullsumancredit 0 isnullsumanreturns 0 as nbalance bddate bcsman bngross bcterm ccvalue castcastconvertvarchar20getdate101 as datetime bddate as integer castccvalue as integer as ndue dateadcastccvalue as integerbddate as dduedate from select from temp2 determining the balance of the invoices a left outer join sales b on acinvno bcinvno and accompanyid bccompanyid left outer join parameter user c on bcterm ccparamname and cctype terms where bccode in select from temp1 get all the clients and accompanyid ccompid group by accompanyid bccode acinvno bddate bcsman bngross bcterm ccvalue having isnullsumansales 0 isnullsumanpaid 0 isnullsumandebit 0 isnullsumancredit 0 isnullsumanreturns 0 0 a left outer join select accompanyid acinvno bcrefno date as drefdate case when actype meter then bnmeterin when actype weight then bnweightout else 0 end as nbeg case when actype meter then bnmeterout when actype weight then bnweightin else 0 end as nend bnconsumed case when actype meter then bnconsumedkg when actype weight then bnweightout bnweightin else 0 end as nconsumedkg bnprice bnamount 112 as namount bnamount bnamount 112 as nvat case when elewt1 then bnamount 112 enewt100 else 0 end as nwht bnamount as nnetfctenantname from sales a left outer join sales t b on acinvno bcinvno and accompanyid bccompanyid left outer join item c on bcitemno ccitemno and accompanyid companyid left outer join dr d on dcdrno bcrefno left outer join client customer e on accode eccode left outer join meter reading t f on bcmrno fctransno and bnmeterin fnmeterin where cctype cylinder and actype invoice and accode in select from temp1 get all the clients and accompanyid ccompid union all select accompanyid acinvno dcdrno as crefno date as drefdate 0 as nbeg 0 as nend bnconsumed 0 as nconsumedkg bnprice bnamount 0 as nvat 0 as nwht 0 as nnet as ctenantname from sales a left outer join sales t b on acinvno bcinvno and accompanyid bccompanyid left outer join item c on bcitemno ccitemno and accompanyid companyid left outer join dr d on acinvno dcinvno where cctype cylinder and actype invoice and dcdrno is null and accode in select from temp1 get all the clients and accompanyid ccompid b on acinvno bcinvno and accompanyid bccompanyidmain script for creating the temp intervalinsert into intervalselect thistinct ccompid 1 above 120 days ccode from arinsert into intervalselect thistinct ccompid 2 91 120 days ccode from arinsert into intervalselect thistinct ccompid 3 61 90 days ccode from arinsert into intervalselect thistinct ccompid 4 31 60 days ccode from arinsert into intervalselect thistinct ccompid 5 1 30 days ccode from arinsert into intervalselect thistinct ccompid 6 current ccode from arthisplaying the resultselect anorder acinterval accode ccname ccfirstname case when isnullccmiddleinitial then else ccmiddleinitial end cclastname as ccustomername case when isnullccbusinessname then ccname else ccbusinessname end as cbusinessname ccaddress cclastname ccjobtitle dccompanyname dcaddress1 dcaddress2 dcphone dcfax dcemail ccterm bcinvno bnbalance bddate bngross bcrefno bdrefdate bnbeg bnend bnconsumed bnconsumedkg bnprice bnamount bnvat bnwht bnnet isnullentotalpdc0 as ntotalpdc fntotalar fntotalpastdue cnlimit ddatefrom as dstartdate ddateto as denddategctenantname bctenantnamecase when cfilter show note then 1 else 0 end as lnotefrom interval aleft outer join ar b on acinterval bcinterval and accode bccodeleft outer join client customer c on accode codeleft outer join company d on accompid dccompanyidleft outer join select accode sumanamount as ntotalpdc from checks a where aldeposited0 and actranstype col and accode cfrom and accompanyid ccompid group by accodee on accodeeccodeleft outer join select accode sumanbalance as ntotalar sumcase when acinterval current then isnullanbalance0 else 0 end as ntotalpastdue from ar a group by accode select accodesumntotalar as ntotalarsumntotalpastdue as ntotalpastdue from select thistinct accode anbalance as ntotalar case when acinterval current then isnullanbalance0 else 0 end as ntotalpastdue from ar a a group by accodef on accodefccodeorder by anorder accode drop table temp1 drop table temp2 drop table interval drop table ar select from temp1 select from temp2 select from interval select from arthe sql server always pointing the error to this linethisplaying the resultselect anorder acinterval accode ccname ccfirstname case when isnullccmiddleinitial then else ccmiddleinitial end cclastname as ccustomername case when isnullccbusinessname then ccname else ccbusinessname end as cbusinessname ccaddress cclastname ccjobtitle dccompanyname dcaddress1 dcaddress2 dcphone dcfax dcemail ccterm bcinvno bnbalance bddate bngross bcrefno bdrefdate bnbeg bnend bnconsumed bnconsumedkg bnprice bnamount bnvat bnwht bnnet isnullentotalpdc0 as ntotalpdc fntotalar fntotalpastdue cnlimit ddatefrom as dstartdate ddateto as denddategctenantname bctenantnamecase when cfilter show note then 1 else 0 end as lnote,['sql'] +89011,how to understand this code of flask could anyone explain this linei14g localproxylambda request ctx stacktopg code from flaskfrom werkzeug import localstack localproxy context locals request ctx stack localstackcurrent app localproxylambda request ctx stacktopapprequest localproxylambda request ctx stacktoprequestsession localproxylambda request ctx stacktopsessiong localproxylambda request ctx stacktopg code of local is here,['python'] +89033,can you you show a grey hint in an html text box with css alone you see these text input boxes from time to time on the web a grey label is shown inside the box but once you type there the grey text thisappears this page even has one the title field behaves exactly like thatso questionsis there a standard term for this i am really struggling to find anything on googlecan it be done with just cssfailing that can it be done with localised javascript ie code just within the tag not in the html header,"['javascript', 'html', 'css']" +89039,is there thisplaymember and valuemember like properties for checkedlistbox control c winforms i have this datatable with the following structureid value1 item 12 item 23 item 3and i thisplay the values from the datatable into a checkedlistbox control by adding each row as an itembut how can i include the id is there thisplaymember and valuemember like properties for checkedlistbox control,['c#'] +89044,binary representation of a net decimal hey all quick question how does a net decimal type get represented in binary in memory we all know how floatingpoint numbers are stored and the thusly the reasons for the inaccuracy thereof but i cannot find any information about decimal except the followingapparently more accurate than floatingpoint numberstakes 128 bits of memory296 sign range28 sometimes 29 total significant digits in the numberis there any way i can figure this out the computer scientist in me demands the answer and after an hour of attempted research i cannot find it it seems like there is either a lot of wasted bits or i am just picturing this wrong in my head can anyone shed some light on this please thanks,['.net'] +89047,what does mean in ruby on rails compared to i have always used some code to insert ruby into html when using ruby on rails i have just noticed that other projects sometimes use some code,['ruby-on-rails'] +89051,why codeigniter shopping cart class does not allow any special character in the name i have a question just like in the title why codeigniter shopping cart class does not allow any special character in the name when i am adding some item with normal name containing only standard characters it works like charm however if i add something like say word word or something like that it would not add anything to the shopping cart can someone provide me with some hints on that one please,['php'] +89052,android code to convert base64 string to bitmap hi stackoverflow team i have a problem in converting base64 string to bitmap in android i am using the camera to fetch the image and i am convert the image to base64 string to post to the server i want to show that image in the imageview so how can i show the image in the imageview after fetching the image from the camera please help me to solve the problem,['android'] +89054,how to detect illegal utf8 byte sequences to replace them in java inputstream the file in question is not under my control most byte sequences are valid utf8 it is not iso88591 or an other encoding i want to do my best do extract as much information as possiblethe file contains a few illegal byte sequences those should be replaces with the replacement characterit is not an easy task it think it requires some knowledge about the utf8 state machineoracle has a wrapper which does what i needutf8validationfilter javadocis there something like that available commercially or as free softwarethanksstephansolutionfinal bufferedinputstream in new bufferedinputstreamistreamfinal charsetdecoder charsetdecoder standardcharsetsutf 8newdecodercharsetdecoderonmalformedinputcodingerroractionreplacecharsetdecoderonunmappablecharactercodingerroractionreplacefinal reader inputreader new inputstreamreaderin charsetdecoder,['java'] +89055,thisableenable element with checkbox and jquery i have a checkbox and if i tick it i want a textfield to become enabled thisabled as default and when i untick the the checkbox i want it to become thisabled againi saw here how i caan toggle a css class and here asked questionshow do i thisable2fenable a form element3f how i can switch between enabled and thisabled with two buttons but how do i toggle a textfields thisabledenabled status by tickuntick a checkboxthanks in advance,['jquery'] +89065,java timebased mapcache with expiring keys do any of you know of a java map or similar standard data store that automatically purges entries after a given timeout this means aging where the old expired entries aageouta automaticallypreferably in an open source library that is accessible via maveni know of ways to implement the functionality myself and have done it several times in the past so i am not asking for advice in that respect but for pointers to a good reference implementationweakreference based solutions like weakhashmap are not an option because my keys are likely to be noninterned strings and i want a configurable timeout that is not dependent on the garbage collectorehcache is also an option i wouldnt like to rely on because it needs external configuration files i am looking for a codeonly solution,['java'] +89066,is it possible to unpack a tuple in python without creating unwanted variables is there a way to write the following function so that my ide does not complain that column is an unused variable def get selected indexself path column self tree viewget cursor return path0in this case i do not care about the second item in the tuple and just want to thiscard the reference to it when it is unpacked,['python'] +89069,array string difference in java vs c i know about c and i am entering into java and confused about its approach towards arrays and strings it is totally different from arrays and strings in c please help me understand what is actually the difference between c and java for strings and arrays,"['java', 'c']" +89071,force to open save as popup open at text link click for pdf in html i have some big size pdf catalogs at my website and i need to link these as download when i googled i found such a thing noted below it should open save as popup at link click head meta namecontentthisposition contentinline filenamefilenamepdf but it does not work when i link to file as below it just links to file and trying to open the file a hreffilenamepdf titlefilie namefile nameaappreciate helps thanks a lotupdate according to answers belowas i see there is no 100 reliable crossbrowser solution for this probably the best way is using one of the web services listed below and giving download link,['html'] +89073,difference between class variables and class instance variables can anyone tell me about the difference between class variables and class instance variables,['ruby'] +89094,rails 3 how to thisplay error messages in embedded form i am new to rails trying to set up my first embedded form the form itself works but i cannot determine how to send validation error messages to the view i assumed fobjecterrors would provide access but while the method is said to exist fobjecterrorscount always returns 0 and fobjecterrorsany returns false apart from not showing the actual error messages the form is working as expected that is failing to insert invalid data and returning to the form which failed validation model controller view listed below any help much appreciated form embedded in boardsshowhtmlerb form forboard boardboardthreadsbuild do f div classfield flabel title br ftext field title div div classfield div classactions fsubmit div div end class boardthread activerecordbase belongs to user belongs to board validates user presence true validates board presence true validates title presence trueendclass boardthreadscontroller applicationcontroller def create board boardfindparamsboard id boardthread boardboardthreadsnewparamsboardthread boardthreaduser current user boardthreadsave redirect to board pathboard endend,['ruby-on-rails'] +89111,how to call windowalertmessage from c i have my own exception based on some condition and want to raise an alert when control comes in this catch block catch applicationexception ex want to call windowalert function here,"['c#', 'asp.net']" +89136,how to print characterset in objective c i am using gnustep shell for programming objectivec i am able to convert string to a character set but unable to print the converted character set in the console please tell me a way to print it thanks in advance,['objective-c'] +89151,xml parser error entity not defined i have searched stackoverflow on this problem and did find a few topics but i feel like there is not really a solid answer for me on thisi have a form that users submit and the fields value is stored in a xml file the xml is set to be encoded with utf8every now and then a user will copypaste text from somewhere and that is when i get the entity not defined errori realize xml only supports a select few entities and anything beyond that is not recognized hence the parser errorfrom what i gather there is a few options i have seeni can find and replace all nbsp and swap them out with 32 or an actual spacei can place the code in question within a cdata sectioni can include these entities within the xml filewhat i am doing with the xml file is that the user can enter content into a form it gets stored in a xml file and that content then gets thisplayed as xhtml on a web page parsed with simplexmlof the three options or any other options i am not aware of whats really the best way to deal with these entitiesthanksryanupdatei want to thank everyone for the great feedback i actually determined what caused my entity errors all the suggestions made me look into it more deeplysome textboxes where plain old textboxes but my textareas were enhanced with tinymce it turns out while taking a closer look that the php warnings always referenced data from the tinymce enhanced textareas later i noticed on a pc that all the characters were taken out because it could not read them but on a mac you could see little square boxes referencing the unicode number of that character the reason it showed up in squares on a mac in the first place is because i used utf8 encode to encode data that was not in utf to prevent other parsing errors which is somehow also related to tinymcethe solution to all this was quite simplei added this line entity encoding utf8 in my tinymceinit now all the characters show up the way they are supposed toi guess the only thing i do not understand is why the characters still show up when placed in textboxes because nothing converts them to utf but with tinymce it was a problem,['php'] +89156,css 100 width on browser resize hi all i am trying to build a layout using css and i am coming up against a strange problem well strange for me i have 3 divs a header a footer and a maincontent area header and footer must remain at a constant width of 100 while the maincontent area must be fixed centrally at 996px this is all fine however when i resize the browser window to a width lower than 996px and then scroll the content of the window right the 100 header and footer seem to be truncated and are no longer 100 i have knocked up a little barebones script to illustrate the issue styles inline to keep it compact i know i can add overflowhidden to each of the containers in order to turn off the scrollbars when to window is resized i have also written a small piece of jquery to force the divs back to the width if the width drops below a certain width however my question is around the css is there a better pure css fix for this issue or can anybody explain why this happensthankyou in advancedotschtml xmlnshead meta httpequivcontenttype contenttexthtml charsetutf8 titlediv width testtitleheadbody stylebordernone margin0 padding0 height100 width100 div idheadercontent stylewidth100 margin0 padding0 backgroundcolor0ff height50pxdiv div idmaincontent stylewidth996px margin0 padding0 backgroundcolorff00ff height250px marginauto div idinnercontent content of the page here div div div idfootercontent stylewidth100 margin0 padding0 backgroundcolor00f height70pxdivbody,['css'] +89166,net multiple namespaces for single class is it possible to have a single class reside within two namespaces and how can i do thisto clarify we have a class library let say root namespace is classlib1 which has grown over time more classes and i want to logically group classes into different namespaces however some of the older classes need to be grouped into these new namespaces eg classlib1section1 and doing so will break legacy code in other assemblys that use this class library so i want to be able to refer to a class using both namespaces until we can phase the old ones outi cannot find any information on this which suggests there is a reason that people would not want to do this,"['c#', '.net']" +89193,how do you implement a reusable named pipe listener that runs asynchronously i cannot find a good example of how to create a reusable named pipe listener that runs asynchronously i can make a reusable listenernamedpipeserverstream pipeserver new namedpipeserverstreammypipe pipedirectioninout while true pipeserverwaitforconnection streamreader reader new streamreaderpipeserver messageboxshowreaderreadline pipeserverthisconnect and i can make an asychronous listenernamedpipeserverstream pipeserver new namedpipeserverstreammypipe pipedirectioninout 1 pipetransmissionmodemessage pipeoptionsasynchronous pipeserverbeginwaitforconnectiona pipeserverendwaitforconnectiona streamreader reader new streamreaderpipeserver messageboxshowreaderreadline nullbut i cannot seem to get both going is there a good example for this i am also concerned about partially sent messages as i believe that is an issue with asynchronous communications like thisupdatei am a little closerpipeserver new namedpipeserverstreammypipe pipedirectioninout 1 pipetransmissionmodemessage pipeoptionsasynchronouspipeserverbeginwaitforconnectiona pipeserverendwaitforconnectiona streamreader reader new streamreaderpipeserver while running string text readerreadline if stringisnulloremptytext false messageboxshowtext messageboxshowdone nullthat will read successfully once and will continue looping with readline returning an empty empty string after the initial successful read so it is clearly not blocking and is attempting to read again the problem is if i send the same message a second time it does not get picked up and my pipe writer says it is receiving error 2316 though i cannot figure out what that means i think i just need to do something similar to this where the pipe gets cleaned up each time like the first code sample i listed but i have not gotten that to work yet,['.net'] +89194,how to implement an onvisible event in javascript is there any technique or set of techniques that can be used to implement what in effect would be an onvisible event in javascripti would like my javascript to detect when an element in a web page such as a paragraph of text or an image becomes visible in a browser window as a user scrolls down a page i would also like a corresponding event onnotvisible to fire when an element that was once visible in the browser window can no longer be seenif it cannot be easily implemented in javascript are there any browser specific events that can provide the same functionality,"['javascript', 'html']" +89203,any significant reasons not to use ajax i am planning on making my web app quite ajax heavy before i do i am wondering what people think of such sites are there any significant reasons not to do thisbtw no need to mention seo reasons also i think the benefits make up for the fact that people without javascript will have a limited experience though i am open to being convinced otherwise,['javascript'] +89207,are both csrf tokens and captcha needed can someone confirm this do i need to provide both a csrf token and a captcha in a submission form or do the two more or less serve the same function one can be used instead of the other,['php'] +89208,changing text of done button in keyboard i know there is a question about this subject already but i think it is possible to change the text of the done button of a keyboard because many of the apps i use are in french and the text of the done button is accader but i do not know how to do this,"['iphone', 'objective-c', 'ios']" +89233,get the id of current table row with jquery hi i have the following code in a form when the user clicks a button i want to get the current row in order to identify which of the buttons was clicked tr idtest1 td alignleft valignmiddle div alignrightcontactdiv td td colspan4 alignleft valignmiddle input typetext idcontact1 size20 number input typetext idnumber1 size20 td td input typebutton valuebutton 1 idcontact1 tdtrtr idtest2 td alignleft valignmiddle div alignrightcontactdiv td td colspan4 alignleft valignmiddle input typetext idcontact2 size20 number input typetext idnumber2 size20 td td input typebutton valuebutton 1 idcontact2 tdtrtr idtest3 td alignleft valignmiddle div alignrightcontactdiv td td colspan4 alignleft valignmiddle input typetext idcontact3 size20 number input typetext idnumber3 size20 td td input typebutton valuebutton 1 idcontact2 tdtri thought the following jquery would return the id name but it does not inputtypebutton clickfunction bid thisid button id trid trattrid table row id can anyone give me some advice please thanks,"['jquery', 'html']" +89247,what exception to throw i have a function which calculates the mean of a list passed as an argument i would like to know which of java exception should i throw when i try to compute the mean of a list of size 0public double mean mylinkedlist extends number list if listisempty throw new if i am not mistaken java has some defined exception for this case code goes herethanks,['java'] +89250,how to move all computed css styles from one element and apply them to a different element using javascript i have an external stylesheet that is applying some styles to a given element i want to be able to move those styles using javascript to a different element entirely without having prior knowledge of the styles that are being appliedthe csstd padding 5px div the htmltd div apply the td styles to this div instead of the td divtdthe javascriptdocumentreadyfunction trchildrentdeachfunction move the td styles to div how can i achieve thisupdate to be clear i have no control over the css i have no way of knowing what styles may be applied the problem that i am trying to solve is being able to take an element and copy its styles which may be unknown and apply them to a different element,['jquery'] +89301,why cannot this checkbox created dynamically with jquery be clicked jsfiddlei am using a jquery plugin that allows the user to draw boxes in an area i use jquery to put a checkbox along with a dropdown list in the box that appears when the user lets go of the mouse button this is towards the bottom of the javascript in the jsfiddle the problem is the checkbox is unclickable i do have some click checking code in the mousestart mousedrag and mousestop events to stop another box from being created when you click in an existing box but i do not think this is causing the problem because the dropdown list that is created can be clicked and furthermore if you remove the click checking code the checkbox remains unclickable what is causing the checkbox to be unclickable thanks for readingeditthanks to vinaycs answer i can now see that the click reaches the checkbox with this codeboxclickfunctione alertclicked thisattrchecked truebut the thisattrchecked true line does not make the checkbox checked can anyone tell me why i have updated the jsfiddleedit 2harmen noticed that the code assigns the same id to each checkbox in the actual code there is a counter appended to the id so each one is unique but i have taken that out because i think this is just a jquery issue i would change the jsfiddle but if you just create one box thus one checkbox the same problem occurs,"['javascript', 'jquery']" +89302,close open html tags in a string situation is a string that results in something like thispthis is some text and here is a strongbold text then the post stop herepbecause the function returns a teaser summary of the text it stops after certain words where in this case the tag strong is not closed but the whole string is wrapped in a paragraphis it possible to convert the above resultoutput to the followingpthis is some text and here is a strongbold text then the post stop herestrongpi do not know where to begin the problem is that i found a function on the web which does it regex but it puts the closing tag after the string therefore it would not validate because i want all openclose tags within the paragraph tags the function i found does this which is wrong alsopthis is some text and here is a strongbold text then the post stop herepstrongi want to know that the tag can be strong italic anything that is why i cannot append the function and close it manually in the function any pattern that can do it for me,['php'] +89309,c whole class in h file if i am creating a class with small functions that do not do much is it acceptable to just put them all into the header file so for a particular class it is only just the h with no cpp to go with it,['c++'] +89314,java set iterator safe for removal of elements i would like to iterate over a set and remove the elements from the set that match some condition the documentation of iterator says nothing about modifying the list while iterating over it is this possible if not what would be the best way to do it note that i only want to remove elements from the set that are provided by the iteratoredit quickly was shown that this is possible can i also do it with the following syntaxfornode and myset mysetremoven,['java'] +89315,why is there no call to the constructor this code does not behave how i expect it toincludeiostreamusing namespace stdclass class class coutdefault constructor called class coutdestrutor called int main class objecti expected the output default constructor called but i did not see anything as the output what is the problem,['c++'] +89316,100 abstract class vs interface is there a reason to use a 100 abstract class and not an interface can you give me a good example when to use both so i can grasp the concept a littleupdate100 abstract class abstract class with only abstract methodsi am curios if there are differences between php and java regarding this aspectupdate2even if i understand most of the reasons i am more interested in the conceptual more than technical reasons,"['java', 'php']" +89322,is it possible to monitor folder using java code is there anyone know how to monitor a folder using java or anyone could gave me a point that how could i start this heres my thought about it start a thread to scan the folder changeswhich could be createdeleteupdate files in this folder or something else happenlike last updated but in this case you have to control thread loop if this thread loop is not controlled wellthen it would be a waste of cpu and may cause a fatal problemoris there any framework or some demo code to do this hope we could find a better way to do this thank you very much,['java'] +89347,javascript regular expression fails every other time it is called i am using the following javascript to read strings out of a text file and process them with a regular expressionwhile textfileatendofstream currline textfilereadline match reexeccurrline do stuff with matchthe problem i have is that every other time reexec is called it fails and returns null so the first row is processed correctly but the second row results in null then the third row works and the fourth row results in nulli can use the following code to get the result i wantwhile textfileatendofstream currline textfilereadline match reexeccurrline if match null match reexeccurrlinebut that seems a bit of a nasty kludge can anyone tell my why this happens and what i can do to fix it properly,['javascript'] +89358,jquery elements fail to select parent it seems elements selected using containssub with sub containing or cannot get to their parentsthe following example should illustrate the problem i am having in both safari and camino gecko on machtml head script typetextjavascript srcscript head body pstrongbarstrongp pstrongltfoogtstrongp script typetextjavascriptalertbody strongcontainsbarlengthalertbody strongcontainsbarparentlengthalertbody strongcontainsfoolengthalertbody strongcontainsfooparentlength this failsalertbody stronglengthalertbody strongparentlength two p elementsalertbody strongparentparentlength one body script bodyhtmloutput is10221any ideas why the fourth one is 0 instead of 1 or how i can circumvent thisthis page mentions escaping names in selectors but that did not work either also i am not sure if it is applicable,['jquery'] +89374,how to get systemiostream from a string object i have string object i need to pass this data to another object of type xyz but this object of type xyz is taking only systemiostream so how to convert the string data into a stream so that object of xyz type can use this string data,['c#'] +89382,continuing download after the app goes to background in my app i download around 25mb data during the download process if the user press the center button and app goes background what should be done so that the download continues once the app comes to foreground,['iphone'] +89391,get value from aspnet mvc lambda expression i am trying to create my own html helper which takes in an expression similar to the builtin labelfor helper i have found examples to obtain the value of a property when the expression is similar to thismodel modelforenamehowever in some of my models i want to obtain properties in child elements egmodel modepersonforenamein these examples i cannot find anyway to easily obtain the value of forename can anybody advise on how i should be getting this valuethanks,"['c#', 'html']" +89414,limiting double to 3 decimal places this i what i am trying to achieveif a double has more than 3 decimal places i want to truncate any decimal places beyond the third do not roundeg 128789 12878if a double has less than 3 decimals leave unchangedeg 125 125 8924 8924i came across this commanddouble example 1234567double output mathroundexample 3but i do not want to round according to the command posted above 1234567 12346i want to truncate the value so that it becomes 12345,['c#'] +89425,android private content provider i am developing an application that involves some sensitive user information i retrieve this information via a private web api i am trying to determine the best way to get this data into my app right now i am exploring creating a content provider that can do so my hesitation is in making it secure i want this data to be usable only by my application ideally no other apps would even know it existsdo you have any pointers or advice on how to do this effectively and securelyany info on content providers whos data source is a remote oauthd apithanksedit i say content provider but if that is not the best way to do what i need by all means let me know what else to look into,['android'] +89435,webview and html5 i am piecing together a cheapo app that amongst other things frames some of our websites pretty simple with the webviewclient until i hit the videothe video is done as html5 elements and these work fine and dandy on chrome iphones and now that we fixed the encoding issues it works great on android in the native browsernow the rub webview does not like it at all i can click on the poster image and nothing happensgoogling i found which is close but seems to be based on a link as in a href instead of a video element ondownloadlistener does not appear to get invoked on video elementsi also see references to overriding onshowcustomview but that seems to not get called on video elements nor does shouldoverrideurlloading i would rather not get into pull xml from the server reformat it in the app by keeping the story layout on the server i can control the content a bit better without forcing people to keep updating an app so if i can convince webview to handle tags like the native browser that would be besti am clearly missing something obvious but i have no clue what,['android'] +89437,jquery via google cdn best practices i am loading jquery via googles cdn using the following codemy main question is what will happen if a user hits my site and has not yet got jquery precached will he download the google version and my own how does concurrency here workscript typetextjavascript srcscriptscript typetextjavascript iftypeof jquery undefined cdata documentwritescript srcincludesjquery142minjs typetextjavascriptscript scriptthanks,['jquery'] +89450,python how to exit main function possible duplicatesterminating a python scriptterminating a python program my question is how to exit out in python main function i have tried return but it gave the error syntaxerror return outside function can anyone help thanksif name main try if condition i want to exit here do something finally do something,['python'] +89465,permissions when using execute sp executesql i have a database where all access is controlled by stored procedures the dba would like to avoid giving users direct readwrite access to the underlying tables which i can understand hence all updating and selecting of data is done via stored procedures basically he has created one role that has execute permissions to all the stored procedures in the database and given users that rolethe problem is that one of the stored procedures dynamically builds a sql query and executes it via execute sp executesql without going into great detail the query is built dynamically because it changes significantly depending on many user input parameters the stored procedure in question is only a select sql statement however i am finding that just giving the stored procedure execute permission is not enough the underlying tables referenced within the stored procedure that make use of execute sp executesql need to have been given datareader access or else the stored procedure fails any thoughts on how to correct this i really wanted to restrict access to the tables to only stored procedures but i need to find a way to work around the stored procedures that make use of execute sp executesql thank you,['sql'] +89475,java generics incompatible type compiletime error for a cs class i am writing a linked list implementation of a linked list interface created by my professor the assignment requires us to use generics for the list what i have created i think is pretty standard public class mylinkedlistt implements adtlistinterface private class nodet nodet head nodet prev public nodeint max public void shift nodet newnode new nodetthismax newnodeprev headprev at compile time following error is generatedmylinkedlistjava1 incompatible types found mylinkedlisttnodet required mylinkedlisttnodetnewnodeprev headprevthis error has me very confused can anyone explain to me what the issue is,['java'] +89476,get android google analytics referrer tag were planning to use google analytics to track ad clickthrough referrals through the android market to our applicationaccording to the google documentation the referrer tag comes through via an intent and is automatically recorded by the google analytics librarythat is great but we need to extract that referral tag for our own internal analytics the documentation is shy on details about how to grab it out of the initial launch intent and instructions on how to simulate this before going livedoes anyone have experience with this,['android'] +89484,where does php save temporary files during uploading i am using xampp on windows by printing filesfiletmp name it seems that the temporary file was saved at cxampptmpphpabcdtmp but i cannot see it on the filesystem of the server however the file can be moved or copied via move uploaded file rename or copy so where does php actually save temporary files during uploading,['php'] +89491,how can i simultaneously query all blog options table in a wordpress multisite installation 30 in our wordpress 30 multisite installation we have a custom option for all of our blogs called something like platform admins can enter in a value for this platform when creating or editing a blog some blogs may have no platformwe need to be able to create a list of all platforms and their associated blogs the problem is we dynamically create and delete blogs through other site mechanisms so we have lots of blog options tables with numbers that are not necessarily contiguous ie wp 2 options wp 4 options wp 12 options etcmy question is this is there a way in wordpress to grab an option across all blogs conversely is there a query i could run that would do this manually i have tried something like this to no effectselect from select table name from information schematables where table name like wp options as twhere option nameplatformdoes it make sense what i am trying to do again i apologize for my lack of mysql knowledge but i have not been able to find any answers about how to do this i could also query all these table names first and then query each table separately but thats not really an option because we have many blogs and we may need to run this query for many page requests simultaneously and this would be adding hundreds of queries to each of these requestsany advice or help you guys could give would be greatly appreciated,"['mysql', 'sql']" +89498,shortcut for null if object is null or objectmember if object is not null i am trying to write a generic extension method that let us me do thisthisstartdate startdatexattributenullorpropertyofdatetime return datetimeparsestartdatexattributevaluenullorpropertyof would return null if it is used on a null object eg if startdatexattribute was null or return the result of a func if it is not nullwhat would this extension method look like,['c#'] +89504,custom behaviour to iphone addressbook ui controller is there any way to customize the abpeoplepickernavigationcontroller and let user select multiple contacts without going into details i can push contacts into an array as user selects them but there is no way to give visual feedback back to user that heshe selected the contacts he clicked or unselect them on second click i do not want to roll my own ab just for this simple featureas a workaround can i thisplay a custom modal view on top of iphone ab ui,"['iphone', 'objective-c']" +89512,adressbook crash only with some contacts my app crashes it is a problem that arises from the addressbook api it only happens with some contactshere is the logexception type exc breakpoint sigtrapexception codes 0x0102 0x316ebd38crashed thread 0thread 0 crashed0 corefoundation 0x01cfe cfretain 901 addressbook 0x04b2c abcmultivaluecopyvalueatindex 282 addressbook 0x01066a abmultivaluecopyvalueatindex 23 call monitor 0x03824 callappdelegate peoplepickernavigationcontrollershouldcontinueafterselectingpersonpropertyidentifier appdelegatem4084 addressbookui 0x032cfc abpeoplepickernavigationcontroller personviewcontrollershouldperformdefaultactionforpersonpropertyidentifierwithmembercell 1525 addressbookui 0x03b8ce abpersonviewcontrollerhelper persontableviewdatasourceselectedpropertyatindexinpropertygroupwithmembercellforediting 26 addressbookui 0x04a17c abpersontableviewdatasource valueatindexselectedforpropertygroupwithmembercellforediting 407 addressbookui 0x048c00 abpersontableviewdatasource tableviewdidselectrowatindexpath 3168 uikit 0x091f40 uitableview selectrowatindexpathanimatedscrollpositionnotifydelegate 6569 uikit 0x09db40 uitableview userselectrowatindexpath 12410 foundation 0x086c86 nsfiredelayedperform 36211 corefoundation 0x071a54 cfrunloop is calling out to a timer callback function 812 corefoundation 0x073ede cfrunloopdotimer 85413 corefoundation 0x07485e cfrunlooprun 108214 corefoundation 0x01d8e4 cfrunlooprunspecific 22415 corefoundation 0x01d7ec cfrunloopruninmode 5216 graphicsservices 0x036e8 gseventrunmodal 10817 graphicsservices 0x03794 gseventrun 5618 uikit 0x062a0 uiapplication run 39619 uikit 0x04e10 uiapplicationmain 66420 call monitor 0x028e8 main mainm1421 call monitor 0x028b8 start 32this is driving me crazy as it only happens with an isolated number of contactsany help would be greatly appreciatedhere is the code that was requested thank you very very much for your helpit is an extract from the method where i think the error happensthe weird thing is that it only happens with certain contacts and deleting the contact then creating a new one solves the problem boolpeoplepickernavigationcontrollerabpeoplepickernavigationcontroller peoplepicker shouldcontinueafterselectingpersonabrecordrefperson propertyabpropertyidproperty identifierabmultivalueidentifieridentifier nsstring firstname nsstring abrecordcopyvalueperson kabpersonfirstnameproperty nsstring lastname nsstring abrecordcopyvalueperson kabpersonlastnameproperty nsnumber record nsnumber numberwithintabrecordgetrecordidperson iflastnamenil namensstring stringwithformat firstnamelastname else namefirstname abmultivalueref phone abrecordcopyvalueperson property nsstring value nsstring abmultivaluecopyvalueatindexphone identifier nsstring label nsstring abmultivaluecopylabelatindexphone identifier nsmutablearray temparraynsmutablearray alloc initwitharraynsuserdefaults standarduserdefaults objectforkeymainarray nsdictionary stringdictionary nsdictionary dictionarywithobjectsandkeysname klabelkey value knumberkeylabel knumberlabelkeyrecord kreferencekey nil temparray addobjectstringdictionary nsarray mainarray nsarray arraywitharraytemparray nsuserdefaults standarduserdefaults setobjectmainarray forkeymainarray,"['iphone', 'ios']" +89540,how to find column name with column index in datagridviewc i want to find column name in datagridviewi have column index how i can find itdgvtransgridcurrentcellcolumnindex i want its column nameplz helpthanks,['c#'] +89541,how to detect encodings on signed integers in c the iso c standard allows three encoding methods for signed integers twos complement ones complement and signmagnitudewhats an efficient or good way to detect the encoding at runtime or some other time if there is a better solution i want to know this so i can optimise a bignum library for the different possibilitiesi plan on calculating this and storing it in a variable each time the program runs so it does not have to be blindingly fast i am assuming the encoding would not change during the program run,['c'] +89569,is there any simple pattern of slf4j usage in unit tests i am using junit4 and hibernate3 in my project hibernate depends on slf4j and thus my project includes this library as well now i would like to use slf4j in unit tests in order to log supplementary testing information could you please provide a short example of how my unit test should look like in order to log just one line of text preferably without code duplication in multiple tests,['java'] +89573,what c ides on linux have intellisense in par with or better than visual studio there are some linux based c projects in the pipe what ides should i go for that have some kind of intellisense in par with or better than the one of a bare visual studio that is without the visual assist steroidsnote that i did not use the words as good as or better i consider the visual studio c intellisense everything but good hence the in par with words and visual assist comment,['c++'] +89582,css relative positioning vs backgroundimage backgroundposition i am working on a thumbnail page for an image gallery thumbnail previews are done as an ul with floating li with a fixed square sizethe thumbnails images themselves however are not necessarily square or same size they have the properties of the large images they representto make it look nice i would like to thisplay the center of the thumbnail image in the square li cutting off an equal amount of overflow left and right see fig 1 oo oo o o o fig 1 fig 2i can do this by removing the img tag and defining css spriteli stylewidth x height x overflow hidden div stylebackground url norepeat center centerlithis works and looks nice but only when you have css enabled plus it is not very semantic since the image is not thisplayed by an img tagwhen i use an img tag in place of the inner div above things look more like in fig 2 how would i move the img via css to always be centered no matter how wide the thumbnail image actually is i assume some sort of relative positioning might do it but a naa ve position relative left 50 does not workps yes i know that i could make all the thumbnails square assume that this is not the answer i am looking for,['css'] +89598,using guice without a main method i am creating a library that will be included as a jar so it would not contain a main method i am wondering what is the best practice for bootstrapping guice in this case i have one top level singleton public class testmanager private testmanager public static testmanager getinstance construct and return singleton public void createsomeobjects where should i bootstrap guice i was thinking that in the constructor that i could call guicecreateinjectornew module but it wouldnt inject any of the objects created in createsomeobjects is there a common way to do this when you do not have a main methodcheers,['java'] +89599,regular expression for validating a username i am still kinda new to using regular expressions so heres my plight i have some rules for acceptable usernames and i am trying to make an expression for themhere they are115 charactersaz az 09 and spaces are acceptablemust begin with az or azcannot end in a spacecannot contain two spaces in a rowthis is as far as i have gotten with itazaz1azaz09ss014sit works for the most part but does not match a single character such as acan anyone help me out here i am using pcre in php if that makes any difference,['php'] +89600,what is the difference between tomcat jboss and glassfish i am starting to look into enterprise java and the book i am following mentions that it will use jboss netbeans ships with glassfish i have used tomcat in the pastwhat are the differences between these three programs,['java'] +89641,what is the most efficient way to create a forum lightbulb unread system alright another interesting problem over at route 50we wanted to implement a true forum lightbulb system where posts that are unread by a user after the users account is created show as unread until that status is cleared or until the user reads themwe figured the best and easiest way to do this would be to implement a table of unread messagesthe columns are user id board id thread id post id timestamp and hiddenthis is working very well and very quickly for seeing which boardsthreadsposts are unread and linking to them per user however it is incredibly slow for a user to post to the forum even though only a single sql query is being runinsert ignore into forums lightbulb select idxunix timestamp0 from usersi am sure this is the result of having 3065 user accounts how can i speed up this process i would prefer to keep the system as realtime as possibleimportant note please limit your answers to a shared hosting environment with no additional budget we are limited to php and mysql 5153log,"['php', 'mysql']" +89645,ioerror request data read error i seem to be getting an ioerror request data read error quite a lot when i am doing an ajax upload for example out of every 5 file uploads it errors out on atleast 3 other people seem to have had the same issue eg some other observationsit is definitely not my internet connection or a browser issue seems to be happening on all browsers chromeffoperai am running django 1 apache2214 ubuntu mod ssl2214 openssl098k mod wsgi28 python265on lucidit is also not the file size i can sometimes upload 1 mb files but fail on 180 kb filestracebacktraceback most recent call last file homeubuntuvirtualenvsanonymous applibpython26sitepackagesdjangocorehandlersbasepy line 98 in get response response middleware methodrequest e file homeubuntuvirtualenvsanonymous applibpython26sitepackagesdjangocorehandlersbasepy line 92 in get response response callbackrequest callback args callback kwargs file homeubuntuvirtualenvsanonymous applibpython26sitepackagesdjangocontribauthdecoratorspy line 78 in call return selfview funcrequest args kwargs file homeubuntuwebappsanonymous appappdo workviews init py line 391 in some form ajax upload f requestfilesgetfile upload file homeubuntuvirtualenvsanonymous applibpython26sitepackagesdjangocorehandlerswsgipy line 187 in get files self load post and files file homeubuntuvirtualenvsanonymous applibpython26sitepackagesdjangocorehandlerswsgipy line 137 in load post and files self post self files selfparse file uploadselfmeta selfenvironwsgiinput file homeubuntuvirtualenvsanonymous applibpython26sitepackagesdjangohttp init py line 124 in parse file upload return parserparse file homeubuntuvirtualenvsanonymous applibpython26sitepackagesdjangohttpmultipartparserpy line 133 in parse for item type meta data field stream in parserstream self boundary file homeubuntuvirtualenvsanonymous applibpython26sitepackagesdjangohttpmultipartparserpy line 606 in iter for sub stream in boundarystream file homeubuntuvirtualenvsanonymous applibpython26sitepackagesdjangohttpmultipartparserpy line 420 in next return lazystreamboundaryiterself stream self boundary file homeubuntuvirtualenvsanonymous applibpython26sitepackagesdjangohttpmultipartparserpy line 446 in init unused char self streamread1 file homeubuntuvirtualenvsanonymous applibpython26sitepackagesdjangohttpmultipartparserpy line 299 in read out joinparts file homeubuntuvirtualenvsanonymous applibpython26sitepackagesdjangohttpmultipartparserpy line 292 in parts chunk selfnext file homeubuntuvirtualenvsanonymous applibpython26sitepackagesdjangohttpmultipartparserpy line 314 in next output self producernext file homeubuntuvirtualenvsanonymous applibpython26sitepackagesdjangohttpmultipartparserpy line 375 in next data selffloreadselfchunk size file homeubuntuvirtualenvsanonymous applibpython26sitepackagesdjangohttpmultipartparserpy line 405 in read return self filereadnum bytesioerror request data read errorwsgirequestgetquerydict postcould not parsecookies utma 16827998916887712101285773436128577343612857734361 utmb 16827998920101285773436 utmc 168279989 utmz 168279989128577343611utmcsrdirectutmccndirectutmcmdnone beta true sessionid b1ecf92f2bba13e1885d07803e10aa03 timezone offset 330metacontent length 188575 content type multipartformdata boundary57602381214905740261171925981 document root htdocs gateway interface cgi11 https 1 http accept texthtmlapplicationxhtmlxmlapplicationxmlq09q08 http accept charset iso88591utf8q07q07 http accept encoding gzipdeflate http accept language enusenq05 http connection keepalive http cookie betatrue utma16827998916887712101285773436128577343612857734361 utmb16827998920101285773436 utmc168279989 utmz168279989128577343611utmcsrdirectutmccndirectutmcmdnone sessionidb1ecf92f2bba13e1885d07803e10aa03 timezone offset330 http host xcompute1amazonawscom http keep alive 115 http referer http user agent mozilla50 x11 u linux i686 enus rv19210 gecko20100915 ubuntu1004 lucid firefox3610 path usrlocalsbinusrlocalbinusrsbinusrbinsbinbinusrx11r6bin path info udomysomeesentersomedocumentsajaxuploadothersomedocument path translated homeubuntuwebappsanonymous appsettingsapacheqawsgipydomysomeesentersomedocumentsajaxuploadothersomedocument query string remote addr remote port 15561 request method post request uri domysomeesentersomedocumentsajaxuploadothersomedocument script filename homeubuntuwebappsanonymous appsettingsapacheqawsgipy script name u server addr 10196142182 server admin devanonymous appcom server name ec2184727996compute1amazonawscom server port 443 server protocol http11 server signature addressapache2214 ubuntu server at ec2184727996compute1amazonawscom port 443addressn server software apache2214 ubuntu ssl tls sni ec2184727996compute1amazonawscom mod wsgiapplication group qaanonymous appcom mod wsgicallable object application mod wsgilistener host mod wsgilistener port 443 mod wsgiprocess group mod wsgireload mechanism 0 mod wsgiscript reloading 1 mod wsgiversion 2 8 wsgierrors mod wsgilog object at 0xb9456860 wsgifile wrapper builtin method file wrapper of mod wsgiadapter object at 0xb936a968 wsgiinput mod wsgiinput object at 0xb9720e30 wsgimultiprocess true wsgimultithread false wsgirun once false wsgiurl scheme https wsgiversion 1 0,['python'] +89669,whats the best way to implement a fulltext search for an aspnet mvc application i have built an aspnet mvc application with mvc 20 and fluent nhibernate hided behind repositories for some reasons the application represents a quite complex domain with some different objects like users messages comments files and appointmentsnow i want to implement a fulltext search which is enabling the user to find easily all types of content by simply entering a search phrase when handling all that types of different objects in the application seperately i now have to put them together for the search that means the user makes no thistinction between the different types he just enters xyz and wants to get results in a list comments mixed up with messages etcoption 1 is to create a search service which fetches the search result from the different repositories and prepares the combined output sorting paging etc but that is really really expensive when the data behind grows and it will growso i am looking for an alternative solution currently i am working with sql server 2008 what i have found is lucenenet but i did not invest much time yetany suggestions,['asp.net'] +89673,compiling c on remote linux machine clock skew detected warning i am connected to my universitys small linux cluster via putty and winscp transferring files using the latter and compiling and running them with the former my work so far has been performed in the universitys labs but today i have been doing some work at home that generated an interesting warningi uploaded an entire folder of stuff and upon running the make command i get this as the last line of outputmake warning clock skew detected your build may be incompletethe resulting binary works correctly and there does not seem to be any other unexpected errors in the build processi seem to be able to trigger the error by building after uploading some new replacement files i edit everything locally then upload the new version so i am wondering if it is something just as simple as mismatched file modification times or something more concerningso should i be worried how do i fixprevent this,['c++'] +89684,are there any static analysis tools that can help detect shared ptr circular references are there any static analysis tools that can help detect shared ptr circular referenceseven if such a tool could not detect complicated cases it would still be useful for eliminating the simple cases,['c++'] +89693,unity autofactory with params i am trying to figure out the correct way to inject an autofactory which takes params or even if this is possible with unity for example i know i can do thispublic class testlog private funcilog logfactory public testlogfuncilog logfactory thislogfactory logfactory public ilog createlog return logfactory containerregistertypeilog logtestlog test containerresolvetestlogilog log testcreatelognow what i will like to be able to do ispublic class testlog private funcstring ilog logfactory public testlogfuncstring ilog logfactory thislogfactory logfactory public ilog createlogstring name return logfactoryname containerregistertypeilog logtestlog test containerresolvetestlogilog log testcreatelogtest nameunfortunately this does not work i can see how you can set up custom factories for creating instances in unity just cannot seem to fund any clear examples for this exampleobviously i could create my own factory but i am looking for an elegant way to do this in unity and with minimum code,['c#'] +89698,effective way to find any files encoding yes is a most frequent question and this matter is vague for me and since i do not now much about itbut i would like a very precise way to find a files encodingso precise as notepad isthanks,['c#'] +89700,is there a visualization tool that can inspect a java code base and report interpackage dependencies we have a java code base that has grown to be too big for a single monolithic jar more than 50 classes one of the tasks that we are investigating is how much effort would it be to break this single jar into smaller components with controlled dependencies between them however it is somewhat hard to look at a big bag of code and be sure that you are finding the best points of separation without some analysisare there good tools to inspect and visualize the interpackage dependencies given those we would have a set of suggested cut points where we could begin separating codeas an example in the days before netbeans and eclipse and at a different job we used togetherj and togetherenterprise those had the ability to do a static package analysis and draw the uml diagram that sort of behavior would be optimal but that feature alone is not sufficient to justify the cost,['java'] +89711,is this linq statment vulnerable to sql injection is this linq statment vulnerable to sql injectionvar result from b in contexttests where bid inputtextboxtext select bwhere context is an entity and tests is a tablei am trying to learn linq and i thought that the benefit of it was that it was not vulnerable to sql injection but some stuff i have see has said differently would i need to parametrize this linq statement to make it safer if so howalso would this be considered linq to sql or linq to entities,['asp.net'] +89720,how to get mysql command line client not to print blob fields in select exploring some tables which have blob fields how could i do a select with the command line client and have it surpress the printing or truncate to a standard field width the blob fields rather than scrolling a bunch of binary junk on the screen this is with mysql 51 client just want to do a select and not list all of the nonblob fields individually for development,['mysql'] +89726,rails 3 observer looking to learn how to implement an observer for multiple models i would like to add an auditor observer which does an action anytime after create for 3 models books characters authorsi recently heard of the observer capability but cannot find any documentation on the ability is it support in rails 3how do i create an auditor observer that does something after create for 3 modelsthanks,['ruby-on-rails'] +89742,rails console thisplay active record results in a table is there a way to thisplay active record results in table format in the scriptconsole environment,"['ruby-on-rails', 'ruby']" +89756,enoent while creating a unix socket in ruby i am trying to create a socket in ruby usingrequire socketw unixsocketnewsocketand i keep running intono such file or directory socket errnoenoentthis looks completely backwards to me because new is supposed to create that missing file what am i missing,['ruby'] +89764,how did 16bit c compilers work cs memory model with its use of pointer arithmetic and all seems to model flat address space 16bit computers used segmented memory access how did 16bit c compilers deal with this issue and simulate a flat address space from the perspective of the c programmer for example roughly what assembly language instructions would the following code compile to on an 8086long arr65536 assume 32 bit longslong ifori 0 i 65536 i arri i,['c'] +89817,threadstatic vs threadlocal performance speedups or alternatives i recently read this post about poor performance of fields marked threadstatic they are apparently 60x slower than normal field access does net 4s threadlocal t perform any betterare there any alternatives that offer high performance threadspecific storage,['.net'] +89818,google chrome extension consolelog from background page if i call consolelogsomething from the popup page or any script included off that it works finehowever as the background page is not directly run off the popup page it is not included in the consoleis there a way that i can get consolelogs in the background page to show up in the console for the popup pageis there any way to from the background page call a function in the popup page,['javascript'] +89822,boost shared ptr assignment why can i not do thisboostshared ptrqueulist nextvoid queulistsetnextptrqueulist next boostmutex mtx boostmutexscoped lock lockmtx scope of lock if next null is this needed on a shared ptr next next why can i not assign a raw ptr to a shared ptr how should i do it insteadedit calling this method when the next variable is assigned properly it still causes an error when the queulist object is destroyed for some reason i get a debug assertion the destructor of the object does nothing in particular it only crashes when i call this function queulist li queulist lis lisetnextptrliswhen main goes out of scope i get a debug assertion any ideas,['c++'] +89826,how do i use a recursive array iterator to process a multidimensional array i am trying to get something like this workingfunction posts formatter posts foreach posts as k v if is arrayv posts formatterv else switch strtolowerk make email addresses lowercase case strposk email false postsk strtolowerv break make postcodes uppercase case strposk postcode false postsk strtoupperv break capitalize certain things case strposk line1 false case strposk line2 false case strposk line3 false case strposk forename false case strposk surname false postsk capitalizev break it will correctly go through the array and format the values but i cannot get it to return them i have played around with removing the from the function declaration and adding a return at the end but it would not do anythingadditionally i am thinking perhaps using a recursivearrayiterator might be the way to go however despite the presence of a book right in front of me with a chapter on spl iterators its examples are useless towards being able to achieve what i am trying to how would i go about implementing oneeditarray user array title mr forename lowercase surname name businessname some dude telephone 07545464646 postcode wa1 6nj line1 blergh road line2 randomly capitalized words line3 email address array postcode ab1 1ba line1 test road line2 testville line3 testshire date 20100930,['php'] +89841,checking all array values at once is there a simple way to check if all values in array are equal to each otherin this case it would return falsearray0 yesarray1 yesarray2 noand in this case truearray0 yesarray1 yesarray2 yesso yeah is there a functionmethod to check all array values at oncethanks in advance,['php'] +89855,convention in java new outside of constructor method simple question a friend of mind wrote code similar to this one which is just to explain you my question it is not useful at allclass example private int tab new int10 public example forint i 0 i 10 i tabi intmathrandom100 forint i 0 i 10 i systemoutprintlntabi public static void mainstring arg example ex new example i told him he should put the new inside the constructorclass example private int tab public example tab new int10 when he ask me why i dint know what to answer i did not have a definite argument other than it is better this way the way i learn it you can initialize variables with basic types int double but for arrays you should do it in the constructorsois it really better are there some good reasons convention styledoes it change anything like lessmore memory usedi am not considering the case where the number of element can vary it will always be 10,['java'] +89867,objectdefineproperty in es5 i am seeing posts about a new objectcreate that makes enumeration configurable however it relies on a objectdefineproperty method i cannot find a cross browser implementation for this method are we stuck writing for the old objectcreate i cannot write things that would not work in ie67,['javascript'] +89885,httpservletrequest get json post data possible duplicateretrieving json object literal from httpservletrequest i am http posting to url httplaptop8080apolloservicesrpccmdexecutewithpost data jsondata data http request has contenttype of applicationjson charsetutf8how do i get the post data jsondata from httpservletrequestif i enumerate the request params i can only see one param which is cmd not the post data,['java'] +89901,altering dll search path for static linked dll i have searched for any hints how i can do this but all i found was how to redirect a sxs dll to the local application folderhere is what i want to accomplishthe c applicationexe is linked to a dll plugindll dependant project this dll is not placed inside the application directory but in a subfolder called plugins as the dll is statically linked the application would try to load it from the application folder is there any way how i can change the search path for this particular dll either through manifests or vs2008 linker configurations,['c++'] +89909,vim omnicompletion for c i was wondering if there is any tool like omnicppcomplete for c method signature shown in the abbreviation is what i am most interested in i have searched everywhere with not availupdate i will be editing mostly from a shell terminal so please refrain from suggesting gui alternatives to vim,['c#'] +89920,how to manually symbolicate ios crash to view crash logs trying to debug app the trouble is i cannot find this programsymbolicatecrashshsudo cp developerplatformsiphoneosplatformdeveloperlibraryxcodepluginsiphoneremotedevicexcodeplugincontentsresourcessymbolicatecrash usrlocalbinis it a separate download i am using xcode 323thanks,"['iphone', 'ios']" +89927,foreign key referencing a view in oracle i am attempting to reference a view with a foreign key but i am getting this errorerror ora02270 no matching unique or primary key for this columnlisthowever i have created a primary key on this view and verified it in the constraints tab in toad this is the table i am attempting to createcreate table question question id integer not null created user id integer not null constraint pk question primary key question id constraint fk user foreign key created user id references some viewview idsome view is a view based on another view which points to the employee table in another schema,['sql'] +89930,how do i fix invalid html characters in pages served with different encoding i have a number of websites that are rendering invalid characters the pages meta tags specify utf8 encoding however a number of pages contain characters that cannot be interpreted by utf8 probably because the files were saved with another encoding such as ansi the one in particular i am concerned about right now is a fancy apostrophe as in bobassorry if that does not show up correctly w3s validator indicates the entity is x92 but it would not validate the file because it does not map to unicode and of course if i open the file in notepad and change the encoding to utf8 the character is replaced by a 92 in a black boxheres my question whats the easiest way to fix this do i have to open all the pages and replace that character with a conventional apostrophe or is there a quick fix i could add say to iis that might override or fix the encoding issue or do i have to bruteforce findreplace i have hundreds of pages on these websites and i have no idea how many of them i would have to change so if anyone knows a way i could either circumvent this problem or fix it quickly i would appreciate it,['html'] +89932,how to convert a user defined type to primitive type let us say we have a class called complex which represents a complex numberi want to convert this object to a double objectthe other way around i can do by implementing a copy ctor in complexcomplexconst double dhowever i cannot implement i copy ctor in double which will receive a complexhow do i do this i know there is a way with operator overloading but i could not find howeventually i want the this line will compilecomplex cdoublecthanks,['c++'] +89942,aspnet get physical filepath from url is there a way to get the physical filepath from an aspnets urlscenerio i have an app that is on two severs but it will now be on lots more and each server puts it in a different physical file path right now i am doing this for server 1if requesturlgetleftparturipartialpathcontainscom applicationstorefilespath edatarootsitef1appsiteupload for server 2if requesturlgetleftparturipartialpathcontainsnet applicationstorefilespath ewebrootsite2f34abcghiappsiteupload but what i need to do is something like thisfor all serversapplicationstorefilespath getphysicalfilepath uploadhow can i do it,['asp.net'] +89946,is naming tables september 2010 acceptable and efficient for large data sets dependent on time i need to store about 73200 records per day consisting of 3 points of data id date and integersome members of my team suggest creating tables using months as the table name september 2010 while others are suggesting having one table with lots of data in itany suggestions on how to deal with this amount of data thanks thank you to all the feedback,"['php', 'mysql']" +89972,c static variables question i was recently interested in how does microsoft visual c compiler makes and optimizes static variables i have the following codevoid no static initialization static int value 3void static initializationint new value static int value new valueinclude cstdlibint main no static initialization static initialization1 static initializationrand return 0my main area of interest was of course the last case i was interested in the following does the compiler has to make explicit checks on every function call if the function is called the first time then static value is overwritten or not the first time then nothing happensi have the assembly listing and would be proud if someone could help me how this is implemented compiling with optimizationshere first statement got fully optimized and two calls of the second statement were inlined and they actually represent similiar chunks of code each of them does test something something and then makes a short jump if the test was not successful these jumps obviously point to the end of corresponding routinecould someone give a better explanation of what is happening here does the compiler actually have a flag which indicates if this is the first time the function was called or not where is it stored i guess all that test stuff is about it but i am not exactly surethank you,['c++'] +89974,c instance constructor vs static constructor what are the differences between the two i have only used one kind of constructor and i believe it is the static constructor only familiar with c and java,['c#'] +89994,jsonnet valuetype members not getting deserialized i have been toying around with jsonnet and i am liking it a lot however i have run into a problem when deserializing objects with valuetype members for example consider this codepublic struct vector public float x public float y public float z public override string tostring return stringformat012 x y z public class object public vector positionclass program static void mainstring args var obj new object objposition new vector x 1 y 2 z 3 var str jsonconvertserializeobjectobj consolewritelinestr positionx10y20z30 obj jsonconvertdeserializeobjectobjectstr consolewritelineobjposition 0 consolereadkeytrue the position is serialized correctly but it is not recovered during deserialization interestingly the following code works as expectedclass program static void mainstring args var vec new vector x 1 y 2 z 3 var str jsonconvertserializeobjectvec consolewritelinestr x10y20z30 vec jsonconvertdeserializeobjectvectorstr consolewritelinevec 123 consolereadkeytrue as you can see the vector is getting properly serializeddeserialized by itself is there an easy solution for the first scenario or do i have to create something along the lines of a custom converter,['c#'] +89998,mysql slow query join multiple wheres order by long time lurker first questioni am struggling to optimize this query which selects the lowest priced items that match the chosen filtersselect product info minproduct allsale price as sale price product allbuy linkfrom product infonatural join select from product all where product alldate 20100930 as product allwhere product infocategory 2 and product infogender w group by product allprod idorder by minproduct allsale price asc limit 13its explain id select type table type possible keys key key len ref rows extra 1 primary derived2 all null null null null 89801 using temporary using filesort 1 primary product info eq ref primarycategory prod id retail pricecategory ret primary 4 product allprod id 1 using where 2 derived product all ref date 2 date 2 3 144107 i have tried eliminating the subquery which intuitively seems better but in practice takes even longerselect product info minproduct allsale price as sale price product allbuy linkfrom product infonatural join product allwhere product alldate 20100930and product infocategory 2 and product infogender w group by product allprod idorder by minproduct allsale price asc limit 13and its explain id select type table type possible keys key key len ref rows extra 1 simple product info ref primarycategory prod id retail pricecategory ret category retail price 5 const 269 using where using temporary using filesort 1 simple product all ref primaryprod iddate 2 prod id 4 equipster dbproduct infoprod id 141 using where here are the tables create table product all prod id int 10 not null primary key ref id int 10 not null primary key date date not null buy link blob not null sale price float not null engine myisam create table product info prod id int 10 not null auto increment primary key prod name varchar 200 not nullbrand varchar 50 not nullretail price float not nullcategory int 3 not nullgender varchar 1 not nulltype varchar 10 not null engine myisam my questionswhich query structure seems optimalwhat indices would optimize this queryless importantly how does the indexing approach change when adding or removing where clauses or using a different order by such as sorting by off order by 1minproduct allsale priceproduct inforetail price desc edit both queries natural join acts on prod id one record in product info can have multiple instances in product all which is why they need to be grouped,['mysql'] +90001,failed to launch shortcut application is not installed on your phone i am trying to create a desktop shortcut to one of my activity in androidi use the code that work in every tuto example i have read final intent shortcutintent new intentintentaction main componentname name new componentnamegetpackagename myactivity shortcutintentsetcomponentname shortcutintentaddflagsintentflag activity new task shortcutintentaddflagsintentflag activity clear top final intent intent new intent intentputextraintentextra shortcut intent shortcutintent intentputextraintentextra shortcut name blabla intentputextraintentextra shortcut icon icon intentsetactioncomandroidlauncheractioninstall shortcut sendbroadcastintent finishand i added the main action to my activity activity androidlabelstringapp name androidnamemyactivity intentfilter action androidnameandroidintentactionmain intentfilter activitythe result is that the application does not want to launchin the logcat everything seem fine1001 011751591 infoactivitymanager2424 starting activity intent actandroidintentactionmain flg0x140 cmpmypackagenamemyactivity bnds125384235522 has extras and the home tell me that the application is not installedplease help me i am totally lost and spend a few hours trying to solve the issue and read all info i can getthank a lot,['android'] +90007,what is a process reaper thread in java i am getting hundreds of these process reaper threads that build up over time in my application anyone have any idea what these may be they seem to be in my use of runtimeexec however i am destroying my process in a finally statement but they still show upscreen shot process proc null string line try loggerinfotrying to execute command arraysaslistcommandtostringreplace proc runtimegetruntimeexeccommand catch ioexception e loggerinfoioexception while trying to execute command return false finally ifproc null procdestroy,['java'] +90022,why is this comparison always true i have the following code in my fileunsigned char pdata new unsigned charifpdata0 160 pdata0 255when i compile it i get a warning from the compiler gccwarning comparison is always true due to limited range of data typehow can this be is not the range of an unsigned char 0255 i am confused,['c++'] +90032,how to get a single nsstring character from an nsstring i want to get a character from somewhere inside an nsstring i want the result to be an nsstringthis is the code i use to get a single character at index its substringtoindexi substringtoindex1is there a better way to do it,['objective-c'] +90061,random natural movement jquery how can i recreate this type movement with jquery for images i am planning to use it as a web page background if it is not possible with jquery i will go with flash as3 but i prefer jquery,"['javascript', 'jquery']" +90073,last insert id mysql i have a mysql question that i think must be quite easy i need to return the last inserted id from table1 when i run the following mysql queryinsert into table1 titleuserid values test1 insert into table2 parentidotheriduserid values last insert id41select last insert idas you can understand the current code will just return the last insert id of table2 instead of table1 how can i get the id from table1 even if i insert into table2 between,['mysql'] +90088,google map comes partially grey area comes instead of images from google server sometimes google map comes partially with other area getting grayed out there is one catch if we start firebug images do come in that gray area dont know why this is happeninganybody ever experienced this and found solution please share,['javascript'] +90091,android classcastexception on activity startup i have a simple activity program in androidbasically the class just extends activitybut when i start it i get a classcastexception in the constructor of my classi dont even have a constructor defined so it must be in the constructor of the superclass which is activityunfortunately the debugger doesnt give any detailed information on what class it is trying to casthere is the stacktracethread 1 main suspended exception runtimeexception activitythreadpackageinfomakeapplicationboolean instrumentation line 649 activitythreadhandlebindapplicationactivitythreadappbinddata line 4232 activitythreadaccess30activitythread activitythreadappbinddata line 125 activitythreadhhandlemessagemessage line 2071 activitythreadhhandlerthispatchmessagemessage line 99 looperloop line 123 activitythreadmainstring line 4627 methodinvokenativeobject object class class class int boolean line not available native method methodinvokeobject object line 521 zygoteinitmethodandargscallerrun line 868 zygoteinitmainstring line 626 nativestartmainstring line not available native method and when i look into this runtimeexception i getdetailmessage unable to instantiate application comtestmyapp javalangclasscastexception comtestmyapp id830067694464 the only code ispackage comtestimport androidappactivitypublic class myapp extends activity,['android'] +90114,obsession with nonblocking scripts since i thiscovered the concept of nonblocking scripts i have become obsessed with loading all my external scripts this wayi have even hacked joomla templateswhich i know is a bad practice in order to load nonblocking scripts in the indexphp file example code belowfunction var script documentcreateelementscript head documentgetelementsbytagnamehead0 scripttype textjavascript scriptsrc of manyjs headappendchildscriptmy questions arewhen is it goodbad to load nonblocking scriptswhat should be the limit for using nonblocking scripts,['javascript'] +90116,switch statement with multiple constantexpression in c is it possible possible duplicatemultiple cases in switch is it possible to do a multiple constantexpression switch statement likeswitch i case runnotrun runfaster something like this dorun break case save dosave break default invalidcommandcommand break,['c#'] +90118,functionalimmutable data structures for the jvm does anyone know of a javajvm data structure library providing functional aka immutable or persistent in the functional sense equivalents of the familiar java data structuresby functional i mean that the objects themselves are immutable while modifications to those objects return new objects sharing the same internals as the parent object where appropriate for efficiency in both time and space a naa ve implementation could just copy the whole thing on every writemuch like javas concurrency libraries this does not seem like something i can or should implement myself so it would be nice to have a functional data structure library i can use in the jvm,['java'] +90131,fastest way to interface between live unsaved excel data and c objects i want to know what the fastest way is of reading and writing data to and from an open excel workbook to c objects the background is that i want to develop a c application that is used from excel and uses data held in excel the business logic will reside in the c application but the data will reside in an excel workbook the user will be using excel and will click a button or do something similar on the excel workbook to initiate the c application the c application will then read data off the excel workbook process the data and then write data back to the excel workbookthere may be numerous blocks of data that are required to be read off and written back to the excel workbook but they will normally be of a relatively small size say 10 rows and 20 columns occasionally a large list of data may need to be processed of the order of 50 rows and 40 columnsi know that this is relatively easy to do say using vsto but i want to know what the fastest but still robust and elegant solution is and get an idea of the speed i do not mind if the solution recommends using third party products or uses cthe obvious solution is using vsto or interop but i do not know what the performance is like versus vba which i am currently using to read in the data or if there are any other solutionsthis was posted on experts exchange saying that vsto was dramatically slower than vba but that was a couple of years ago and i do not know if the performance has improved 23635459htmlthanks,['c#'] +90135,unit testing action filters how to mock viewresult i did a search on so and looks like this question gets asked quite often i have been able to get the mocks working and i am also able to execute onactionexecuted without any issues heres my unit test the commented lines are the ones that fail and i am sure i am not mocking the right type arrange var viewresult new viewresult var filtercontextmock new mockactionexecutedcontext var routedata new routedata var httpcontextmock new mockhttpcontextbase routedatavaluesdata mock data var requestcontext new requestcontexthttpcontextmockobject routedata var controller new fakecontroller controllercontrollercontext new controllercontextrequestcontext controller filtercontextmocksetupf froutedatareturnsroutedata filtercontextmocksetupf fcontrollerreturnscontroller filtercontextmocksetupf fresultreturnsviewresult act var wrapfilterattribute new wrapfilterattribute wrapfilterattributeonactionexecutedfiltercontextmockobjecthere is my action filterpublic class wrapfilterattribute actionfilterattribute public override void onactionexecutedactionexecutedcontext filtercontext var view viewresultbasefiltercontextresult if view null baseviewmodel viewmodel baseviewmodelviewviewdatamodel new baseviewmodel viewmodelwrap new wrapperfactorygetwrap baseonactionexecutedfiltercontext the issue i am facing here is filtercontextresult always comes in as emptyresult i would like to push in a hydrated viewresult instead any ideas how i can accomplish thismany thanks,['asp.net'] +90137,javascript regular expression remove first and last slash i have these strings in javascriptbankingbonificiitaliabankingbonificiitaliaand i would like to remove the first and last slash if it is existsi tried but it does not workreading some post in stackoverflow i found that php has trim function and i could use his javascript translation 566 but i would prefer a simple regular expression,['javascript'] +90142,getting result of dynamic sql into a variable for sqlserver executing dynamic sql as follows in stored proceduredeclare sqlcommand nvarchar10declare city varchar75set city londonset sqlcommand select count from customers where city cityexecute sp executesql sqlcommand ncity nvarchar75 city cityhow do i use the count column value as return value in the sp,['sql'] +90150,write content to new window with jquery i have a web page with a div element in it when a user clicks print i want to print the contents of that div please note i only want to print the contents of the div not the entire page to attempt this i decided i would open a new window using javascript i was then going to write the contents of the div into the new window my question is is this possible with jquery if so how currently i am trying the followingfunction printclick var w windowopen var html divtoprintidhtml how do i write the html to the new window with jquery,['jquery'] +90153,phpunit fatal error handling i use phpunit for unit tests but when a fatal error is triggered the script dies and i have no correct phpunit outputi would like that the phpunit output stays correctly formated because it is read by a plugin for eclipse actually the fatal error stops phpunit and in eclipse the plugin cannot interpret anything because the phpunit script had an error instead of handling itthanks,['php'] +90157,c generic overloading of list how would this be done the stringbuilder class allows you in what i consider to be a very intuitive way to chain method calls to append appendformat and some others like sostringbuilder sb new stringbuildersbappendfirst string appendsecond stringthe list class add method on the other hand returns void so chaining calls does not work this in my opinion and the immortal words of jayne cobb just don make no kinda sensei admit that my understanding of generics is very basic but i would like to overload the add method and others so that they return the original object and allow chaining any and all assistance will be rewarded with further firefly quotes,['c#'] +90165,find element by style selector in jquery i am trying to find an element with a particular style and change its style to something elsehere is the html elementtable stylewidth 5px tr tdblablablatd trtablenow i am trying to find the table with width 5px and change it to 650px using jquerytablestylewidth5pxcsswidth 610pxbut this is not working can somebody spark an idea pleasenote for some reason i cannot change the html,['jquery'] +90169,are there any benefits to using a c method group if available when dealing with something like a liststring you can write the followinglistforeachx consolewritelinexor you can use a method group to do the same operationlistforeachconsolewritelinei prefer the second line of code because it looks cleaner to me but are there any benefits to this,['c#'] +90175,make tkinter widget take focus i have a script that uses tkinter to pop up a window with a message how do i make sure it takes focus so the user does not miss it and explicitly has to thismiss the window the code is root tkto read stuff w labelroot textto readwpackrootmainloop,['python'] +90181,rc4 128 bit encryption in c i need to perform a 128bit rc4 encryption i am using net and c is there a builtin function to do thisif not i found this function that can do itpublic void rc4ref byte bytes byte key byte s new byte256 byte k new byte256 byte temp int i j for i 0 i 256 i si bytei ki keyi keygetlength0 j 0 for i 0 i 256 i j j si ki 256 temp si si sj sj temp i j 0 for int x 0 x bytesgetlength0 x i i 1 256 j j si 256 temp si si sj sj temp int t si sj 256 bytesx st but i do not know if it is 128bit or not it looks 256 but i really do not know the difference,"['c#', '.net']" +90190,how do i set a conditional compile variable in cc you can define macros in code like thisdefine old way 1although i have never done it i assume that the same thing is available in c more to the point in cc it is possible to then do some conditional compilation logic by doing something like thisif old way 1 int i 0else int i 1endifok so this is all cool and all that and again i assume that such logic is possible within c what i would like to know is how do i define constants at the project level so that i can put in logic that will allow me to conditional compile one block of code if i define the constant one way or another block of code if i do not define it that way i am assuming that it is done somewhere in the projects properties but how and where do i define it,['c#'] +90205,linq to entities case sensitive comparison this is not a casesensitive comparison in linq to entitiesthingiesfirstt tname thingamabobhow can i achieve case sensitive comparison with linq to entities,"['c#', '.net']" +90219,bigdecimal setscale and round what is the difference between this two call is there any 1new bigdecimal353456roundnew mathcontext4 roundingmodehalf up 2new bigdecimal353456setscale4 roundingmodehalf up,['java'] +90243,best way to generate xml i am creating an web api and need a good way to very quickly generate some well formatted xml i cannot find any good way of doing this in pythonnote some libraries look promising but either lack documentation or only output to files,['python'] +90244,how to get the duration of a video in python i need to get the video duration in python the video formats that i need to get are mp4 flash video avi and mov i have a shared hosting solution so i have no ffmpeg support,['python'] +90248,function passing arguments in reverse here is my functionvoid abcchar def unsigned int w unsigned int x unsigned int y unsigned int z printfval 1 dn w printfval 2 dn x printfval 3 dn y printfval 4 dn zand here is where i call this functionunsigned int exp4 1 2 3 4 unsigned short count 0abcanyarray expcount expcount expcount expcountand here is the output that i expectval1 1val2 2val3 3val4 4but what i get is completely reverse of itval1 4val2 3val3 2val4 1i do not know why any help would be appreciated,['c++'] +90273,get contacts photo which are synced with facebook for android i am trying to show contact pictures in my application but i am getting pictures of those who were added manually only and not those which are synced with facebook how to work around this here is my code belowuri uri contenturiswithappendedidcontactscontractcontactscontent uri longparselongphotoidinputstream input contactscontractcontactsopencontactphotoinputstreamcontextgetcontentresolver urireturn bitmapfactorydecodestreaminput,['android'] +90274,how to produce beep sound using a escape character if i write the following program then there is no beep sound on running the codeinclude stdiohint main printfa return 0 can you tell me how to use a for producing beep sound using c program,['c'] +90285,how to get aspnet client id at external javascript file when i use embedded javascript functions i can get client id of elements with this codedocumentgetelementbyidbuttonxclientid but now i am using external javascript file for caching and faster renderingand this code does not work any more for getting client ids of elements it gives errorhow can i get client ids of elements at external javascript file usingaspnet 20 netframework 35 c iis 75,"['javascript', 'asp.net']" +90292,java array declaration possible duplicatedifference between int array and int array in java we can declare an array in these two stylesint aint bis there any difference,['java'] +90316,iphone sdk 4 avfoundation how to use capturestillimageasynchronouslyfromconnection correctly i am trying to use the new avfoundation framework for taking still pictures with the iphonewith a button press this methos is called i can hear the shutter sound but i cannot see the log output if i call this method several times the camera preview will freezeis there any tutorial out there how to use capturestillimageasynchronouslyfromconnectionself stillimageoutput capturestillimageasynchronouslyfromconnection self stillimageoutputconnections objectatindex0 completionhandlercmsamplebufferref imagedatasamplebuffer nserror error nsloginside voidinitcapture avcapturedeviceinput captureinput avcapturedeviceinput deviceinputwithdeviceavcapturedevice defaultdevicewithmediatypeavmediatypevideo errornil avcapturevideodataoutput captureoutput avcapturevideodataoutput alloc init captureoutputalwaysthiscardslatevideoframes yes thispatch queue t queue queue thispatch queue createcameraqueue null captureoutput setsamplebufferdelegateself queuequeue thispatch releasequeue nsstring key nsstringkcvpixelbufferpixelformattypekey nsnumber value nsnumber numberwithunsignedintkcvpixelformattype 32bgra nsdictionary videosettings nsdictionary dictionarywithobjectvalue forkeykey captureoutput setvideosettingsvideosettings selfcapturesession avcapturesession alloc init selfcapturesessionsessionpreset avcapturesessionpresetlow selfcapturesession addinputcaptureinput selfcapturesession addoutputcaptureoutput selfprevlayer avcapturevideopreviewlayer layerwithsession selfcapturesession selfprevlayer setorientationavcapturevideoorientationlandscapeleft selfprevlayerframe cgrectmake00 00 4800 3200 selfprevlayervideogravity avlayervideogravityresizeaspectfill selfviewlayer addsublayer selfprevlayer setup the default file outputs avcapturestillimageoutput stillimageoutput avcapturestillimageoutput alloc init autorelease nsdictionary outputsettings nsdictionary alloc initwithobjectsandkeys avvideocodecjpeg avvideocodeckey nil stillimageoutput setoutputsettingsoutputsettings outputsettings release self setstillimageoutput stillimageoutput if selfcapturesession canaddoutputstillimageoutput selfcapturesession addoutputstillimageoutput selfcapturesession commitconfiguration selfcapturesession startrunning,['iphone'] +90322,kill process started with systemdiagnosticprocestartfilename i am trying to create an app that will perform actions on specific times much like the windows task scheduler i am currently using procestart to launch the file or exe required by the taski am initiating a process by calling a file an mp3 and the process starts wmp since it is the default application so far so good now i want to kill that process i know that it is normal behavior for the procestartstring string to return nothing null in c in this caseso i am asking how can i close wmp when i called it through procestartstring stringeditplease note that i am not opening wmp directly with procestart and this is the line with which i run the processvb me procsaddprocestartme procinfoc this procsaddprocestartthis procinfo procinfo is a procestartinfo instance procinfofilename is croutemyfilemp3 that is why wmp opens in any case all of the start methods except for the instanceone which returns a boolean return nothing null in c because wmp is not the process that was directly created please note that wmp is run and the song does play,"['c#', '.net']" +90338,using main and delta indexes in sphinx im switching fulltext searching on my site to sphinx im going to be using sphinxse to perform the searchesi created 2 indexes as specified in the manual it seems to work and index different stuff in its own index but im somewhat confused about how i should handle the index updating merging and rebuilding the way i understand is i cron it to run indexer delta rotate every 5 mins or so which would add new submissions to the index then once a day i would merge the delta index into the main index by running indexer main delta rotate then once a month or so i will run indexer all to rebuild all indexes am i doing this right or am i missing something,['php'] +90342,handling gzipped content on android i am trying to parse a file from the web on android using the dom method the code in question istry url url new url to beatport inputsource is new inputsourceurlopenstream documentbuilderfactory dbf documentbuilderfactorynewinstance documentbuilder db dbfnewdocumentbuilder document document dbparseis documentgetdocumentelementnormalize catchexception e logvtag exception ebut i am getting the following exceptionvxmlparsetest1 846exception orgxmlsaxsaxparseexception name expected positionstart tag null2176 in javaioinputstreamreader43ea4538 the file is being handed to me gzipped i have checked the is object in the debugger and its length is 6733 bytes the same as the content length of the file in the response headers however if i save the file to my harddrive from the browser it is size is 59114 bytes furthermore if i upload it to my own server which does not gzip xmls when it serves them and set the url the code runs just finei am guessing that what happens is that android tries to parse the gzipped streamis there a way to first unzip the stream any other ideas,"['java', 'android']" +90343,atomicboolean vs synchronized block i was trying to cut thread contention in my code by replacing some synchronized blocks with atomicbooleanheres an example with synchronizedpublic void togglecondition synchronized thismutex if thistoggled return thistoggled true do other stuff and the alternative with atomicbooleanpublic void togglecondition if thisconditiongetandsettrue do other stuff taking advantage of atomicbooleans cas property should be way faster than relying on synchronization so i ran a little microbenchmarkfor 10 concurrent threads and 10 iterations atomicboolean comes in only slightly faster than synchronized blockaverage time per thread spent on togglecondition with atomicboolean 00338average time per thread spent on togglecondition with synchronized 00357i know microbenchmarks are worth what they are worth but should not the difference be higher,['java'] +90350,catching error corrupt jpeg data premature end of data segment when creating an uiimage with corruptincomplete jpeg data the console will print out error corrupt jpeg data premature end of data segmentthe incomplete image will be shown with grey filling up the incomplete part i do not want this to happeni desperately tried with a trycatch block but it does not catch the error is there any way to catch the error,['iphone'] +90356,is there any point using mysql limit 1 when querying on indexedunique field for example i am querying on a field i know will be unique and is indexed such as a primary key hence i know this query will only return 1 row even without the limit 1select from tablename where tablenameid123 limit 1or only update 1 rowupdate tablename set somefieldsomevalue where tablenameid123 limit 1would adding the limit 1 improve query execution time if the field is indexed,"['sql', 'mysql']" +90357,how to use code contracts when deriving from interfaces like idictionary one class i am writing implements idictionarystring object in my copyto implementation i would like to use code contracts stuff like contractrequiresargumentnullexceptionarray nullbut i get this warning with some namespaces removed for readabilitymethod luadictionarycopytokeyvaluepairstringobjectint32 implements interface method icollectionkeyvaluepairstringobjectcopytokeyvaluepairstringobjectint32 thus cannot add requiresi see that there are some related questions but they all seem to have to do with interfaces that are under the users control obviously idictionaryt u is not under my control so i cannot annotate it with contractclassfor or anything like thatso am i just unable to use code contracts here if so major bummer,['c#'] +90372,how the live objects are figured out in young generation collection i understand that time taken by ygc is proportional to number of live objects in eden i also understand that how the live objects are figured out in major collections all the objects in thread stacks and static objects and further objects reachable from those objects transitively but i dont understand how the live objects are figured out in young generation collection if it parses the thread stacks then it need to parse eden tenured space which is not the case i think so how does jvm find the live objects in eden and copies them in to survivor space,['java'] +90377,alloc and init what do they actually do can someone explain to me what init and alloc do in objc i am reading this objc book that gives an example of creating object but it does not really go into details of what it does what does alloc return what does init returnanimal k animal allock k init,['objective-c'] +90383,copy constructor of base and derived classes i have those two classesbase class class base public baseint 0 base basebase basederived may be problem here note i tried without this function int valueofbase protected int protecteddata private int basedata derived class class derived public base public derivedint derivedderived derived private int deriveddata and here my main int main base base1 derived derived base return 0 i read that if my derived class does not have copy ctor copy ctor of the base will be called but every time i receive conversion from base to nonscalar type derived requested who is wrong my compiler or my book or i have just misunderstood thanks in advance,['c++'] +90394,best way to perform several sequential uiview animations i have a series of 8 uiview animations that occur directly after my view is loaded right now i am accomplishing this by using the animationdidstopfinishedcontext delegate method and everything works as expected the problem is that i have a new method for each animation most of the code in each of these methods is repeated with only the animation duration and the actual positioning of elements changingi tried to create a single method which would be called and have the context hold the parameters needed to change the ui appropriately but it seems to be recursively calling itself well past the amount of times i call itvoidanimationdidstopnsstring animationid finishedboolfinished contextvoid context nsnumber number nsnumber context int animationstep number intvalue int nextanimationstep animationstep 1 nsnumber nextanimationstepnumber nsnumber numberwithintnextanimationstep nsloganimation step i animationstep cgrect firstframe cgrectmakeselffeedsscrollframesizewidth 2 00f selfsecondfeedviewviewframesizewidth selfsecondfeedviewviewframesizeheight cgrect thirdframe cgrectmakeselffeedsscrollframesizewidth 2 00f selfthirdfeedviewviewframesizewidth selfthirdfeedviewviewframesizeheight uiview beginanimationsnil contextnextanimationstepnumber uiview setanimationbeginsfromcurrentstateyes uiview setanimationcurveuiviewanimationcurvelinear uiview setanimationdelegateself if animationstep 8 uiview setanimationdidstopselectorselectoranimationdidstopfinishedcontext nslogbeginning animations switch animationstep case 0 uiview setanimationduration3 selffirstfeedviewviewcenter cgpointmakeselffirstfeedviewviewcenterx 30 selffirstfeedviewviewcentery break case 1 uiview setanimationduration3 selffirstfeedviewviewcenter cgpointmakeselffirstfeedviewviewcenterx 30 selffirstfeedviewviewcentery break case 2 uiview setanimationduration3 selfsecondfeedviewview setframefirstframe break case 3 uiview setanimationduration3 selfsecondfeedviewviewcenter cgpointmakeselfsecondfeedviewviewcenterx 30 selffirstfeedviewviewcentery break case 4 uiview setanimationduration3 selfsecondfeedviewviewcenter cgpointmakeselfsecondfeedviewviewcenterx 30 selffirstfeedviewviewcentery break case 5 nsloganimation step 6 uiview setanimationduration5 selffirstfeedviewviewcenter cgpointmakeselffirstfeedviewviewcenterx 230 selffirstfeedviewviewcentery selfsecondfeedviewviewcenter cgpointmakeselfsecondfeedviewviewcenterx 230 selffirstfeedviewviewcentery break case 6 uiview setanimationduration5 selfthirdfeedviewview setframethirdframe break case 7 uiview setanimationduration3 selfthirdfeedviewviewcenter cgpointmakeselfthirdfeedviewviewcenterx 30 selffirstfeedviewviewcentery break case 8 uiview setanimationduration3 selfthirdfeedviewviewcenter cgpointmakeselfthirdfeedviewviewcenterx 30 selfthirdfeedviewviewcentery break default break uiview commitanimations i know this is probably a naive implementation i am new to iphone development and am looking for some best practices to apply here am i going about this in the wrong way,['iphone'] +90401,semicolon in namespace necessary when working with namespace i need to finish it with a semicolon when i put a forward declaration of a class into a namespace for example many people does not include a semicolon but it seems to be optionaldoes semicolon add functionality or change the current functionality by adding or removingthanks,['c++'] +90404,complicated expression involving logical and void mainvoid int xyz xyz1 z x y zis this finei have lately started reading about sequence points stuffs but i cannot figure out whether the above sample of code is fine or not i know the operator introduces a sequence point so i am not very sure about the behavior of the expression z x y z someone please tell me the correct answer,"['c++', 'c']" +90417,in linq can i select multiple items say i have an array of strings like thisstring foos abc def ghii want a new collection that contains each string and its reverse so the result should be abc cba def fed ghi ihgi could just iterate through the array but this is pretty clumsystring reverse string str return new string strreverse toarray liststring results new liststring foreach string foo in foos resultsadd foo resultsadd reversestris there a way to do this in linq something likevar results from foo in foos select foo and also select reversefoo,"['c#', '.net']" +90424,using drupal and ruby has anyone integrated both i started a small web project and used drupal to build it so far so good you can quickly set up a nice cms oriented site add social features via modules and you have an extensive api to do the customizations in a nicely architected platformthe problem comes now the site is growing beyond what was originally planned for and i find myself in the situation of seriously starting write code for it while i gained a new respect for php thanks to the drupal project i want to do it in ruby i will feel more confortable it will be easier to maintain later and i can reuse it in other rubyrails apps over time i suppose i will rewrite the existing parts in drupal in rubybased on this the question is has anyone integrated both both a success or failure story it is quite a big decision and i just cannot find info about anyone who has done it on google,['ruby'] +90426,multi value dictionary anyone know of a good implementation of a multivaluedictionary basically i want something that allows multiple values per key i want to be able to do something likedictaddkey valand if the key does not already exist it will add it if it does it will just add another value to that key i am just going to iterate over it so i do not really care about the other retrieval methods,['c#'] +90428,java generic methods and numbers i want to make a generic method which makes the total sum of a list of numberswhat i was trying is thispublic static t extends number t sumlistlistt data t total 0 for t elem data total elem return totalbut the problem is that there is no operator in t and that total cannot be assigned to zerohow can i do thisthanks,['java'] +90463,jquery but what about all the children i feel like i have to use way too many children in some of my jquery functionsheres my htmldiv classgoalsmallcontainer div classgoalcontent div classgoalrow span classgoalactionsand heres my jquerygoalsmallcontainerhoverfunction thischildrengoalcontentchildrengoalrowchildrengoalactionscssvisibility visible function thischildrengoalcontentchildrengoalrowchildrengoalactionscssvisibility hiddenis there a better way tell me for the kids,"['jquery', 'html', 'css']" +90465,what is the difference between a click and mouseclick what is the difference between a click and mouseclick,['c#'] +90476,python intersection of multiple lists i am playing with python and am able to get the intersection of two listsresult setaintersectionbnow if d is a list containing a and b and a third element c is there an builtin function for finding the intersection of all the three lists inside d so for instanced 1234 234 34567then the result should be34,['python'] +90483,get item count of a list using linq i want to query a list and find out how many items match the selection criteria using linq and c net 35 how would i modify the query to return an int countvar specialbook from and in storethisplaytypelist where nthisplaytypespecial book select n,['c#'] +90511,c switchcase string starting with is there any way to make a case condition in a switch statement where you say if a string begins with somethingexswitch mystring caseabcstring begins with abc abcd or abc1 or abcz or abc or abc will fall in this condition do something break default breakupdateother strings can be different lengthabcabczyvdcs2qwertyask,['c#'] +90523,add item to a listbox using jquery how to add item to a listbox using jqueryfor example in the following listbox option value1optionoption value2item 2optionoption value3item 3optionoption value4item 4optionoption value0alloption,['jquery'] +90532,how to convert a negative number to positive how can i convert a negative number to positive in python and keep a positive one,['python'] +90551,python replacing an element in a list of lists 2 a previous question with the same title as mine has been posted with i think the same question but had other problems in the code i was not able to determine if that case was identical to mine or notanyway i want to replace an element within a list in a listcodemynestedlist 004 0 0 0 0 0 0 0 0mynestedlist11 5i now expect0 0 0 5 0 0 0 0but i get0 5 0 5 0 5 0 5whythis is replicated in the command linepython 312 r31279147 apr 15 2010 153548 gcc 443 on linux2,['python'] +90564,can i use html 5 for footer links which is not a primary navigation can i use html 5 nav for footer links which is not a primary navigation or should it be used once in a page,['css'] +90567,using html to do a skype call i tried to insert the following snippet in my script by clicking the link it should do a call to a skype account i have been looking for hours now but cannot figure out why it doesnt worka hrefcalltousernameimg src btn small greengif border0ais it accepted in any way or do i miss sth herei would be really thankful for an answer,['html'] +90580,iphone app crash on ios 40 all crash reports submitted for our application on ios 40 are giving the below informationapplication specific informationmy app name3532 was suspended with locked system filesprivatevarmobilelibraryaddressbookaddressbooksqlitedbany idea what this indicates and what could be the possible cause of crash our application is not interacting with addressbooksqlitedb at allthe complete crash logexception type 020exception codes 0xdead10cchighlighted thread 0application specific informationapp name3532 was suspended with locked system files privatevarmobilelibraryaddressbookaddressbooksqlitedbthread 00 libobjcadylib 0x3302e4ac object thispose1 corefoundation 0x31372cfe nsobjectnsobject dealloc2 quartzcore 0x33e45264 calayer dealloc3 quartzcore 0x33eb5e60 calayer dealloc4 quartzcore 0x33e3c752 calayerrelease5 quartzcore 0x33e3cd20 carelease root if unused calayer calayer void6 quartzcore 0x33e3ccbc x hash table remove if7 quartzcore 0x33e3cb26 catransactioncommit8 quartzcore 0x33e42406 catransactionobserver callback cfrunloopobserver unsigned long void9 corefoundation 0x313caa42 cfrunloop is calling out to an observer callback function 10 corefoundation 0x313cc46e cfrunloopdoobservers11 corefoundation 0x313cd774 cfrunlooprun12 corefoundation 0x313768e4 cfrunlooprunspecific13 corefoundation 0x313767ec cfrunloopruninmode14 graphicsservices 0x329f36e8 gseventrunmodal15 graphicsservices 0x329f3794 gseventrun16 uikit 0x316692a0 uiapplication run17 uikit 0x31667e10 uiapplicationmain18 app name 0x02a64 main 3619 app name 0x02a34 start 32thread 10 libsystembdylib 0x35228c4c kevent 241 libsystembdylib 0x352d1e44 thispatch mgr invoke2 libsystembdylib 0x352d1894 thispatch queue invoke3 libsystembdylib 0x352d1a34 thispatch worker thread24 libsystembdylib 0x35275d82 pthread wqthread5 libsystembdylib 0x3526efcc start wqthread 0thread 20 libsystembdylib 0x351fc6b4 semaphore wait signal trap 81 libsystembdylib 0x35229d92 semaphore wait signal2 libsystembdylib 0x351fe4a4 pthread mutex lock3 webcore 0x30138194 webtrythreadlockbool4 webcore 0x301380da webrunlooplock cfrunloopobserver unsigned long void5 corefoundation 0x313caa42 cfrunloop is calling out to an observer callback function 6 corefoundation 0x313cc46e cfrunloopdoobservers7 corefoundation 0x313cd780 cfrunlooprun8 corefoundation 0x313768e4 cfrunlooprunspecific9 corefoundation 0x313767ec cfrunloopruninmode10 webcore 0x30138056 runwebthreadvoid11 libsystembdylib 0x35275986 pthread start12 libsystembdylib 0x3526b0e4 thread start 0thread 30 libsystembdylib 0x351fc658 mach msg trap 201 libsystembdylib 0x351fe724 mach msg2 corefoundation 0x313cb2c8 cfrunloopservicemachport3 corefoundation 0x313cd582 cfrunlooprun4 corefoundation 0x313768e4 cfrunlooprunspecific5 corefoundation 0x313767ec cfrunloopruninmode6 foundation 0x3329571e nsurlconnectionnsurlconnectionreallyinternal resourceloadloop7 foundation 0x33265c96 nsthread main8 foundation 0x332ea9da nsthread main 9 libsystembdylib 0x35275986 pthread start10 libsystembdylib 0x3526b0e4 thread start 0thread 40 libsystembdylib 0x35220a20 selectdarwin extsn 201 corefoundation 0x313d0e70 cfsocketmanager2 libsystembdylib 0x35275986 pthread start3 libsystembdylib 0x3526b0e4 thread start 0thread 50 libsystembdylib 0x3527685c workq kernreturn 81 libsystembdylib 0x35275e98 pthread wqthread2 libsystembdylib 0x3526efcc start wqthread 0thread 60 libsystembdylib 0x3527685c workq kernreturn 81 libsystembdylib 0x35275e98 pthread wqthread2 libsystembdylib 0x3526efcc start wqthread 0thread 70 libsystembdylib 0x35205974 access 81 libsqlite3dylib 0x3282f5a6 unixaccess2 libsqlite3dylib 0x32826e5a sqlite3osaccess3 libsqlite3dylib 0x32835bf0 sqlite3btreebegintrans4 libsqlite3dylib 0x3284f038 sqlite3step5 libsqlite3dylib 0x3282639c sqlite3 step6 appsupport 0x31475634 cpsqlitestatementcopystringresult7 appsupport 0x3147626e cpsqliteconnectioncopyvalueforproperty8 appsupport 0x314773a2 cpsqlitedatabasecopyvalueforproperty9 appsupport 0x314773ba cpsqlitedatabasecopyuniqueidentifier10 addressbook 0x34dd7c3a abccreateaddressbookwithdatabasedirectoryandforceinprocessmigrationandresetsortkeys11 addressbook 0x34dd7eba abccreateaddressbookwithdatabasedirectoryandforceinprocessmigration12 addressbook 0x34dd7ec8 abccreateaddressbookwithdatabasedirectory13 addressbook 0x34de3e78 abaddressbookcreate14 textinput 0x34973fb8 kbmatchable strings from address book15 textinput 0x34978686 kbdynamicdictionaryimplbackground load address bookkbstaticdictionary const16 textinput 0x34979d36 kbbackgroundloadvoid17 libsystembdylib 0x35275986 pthread start18 libsystembdylib 0x3526b0e4 thread start 0unknown thread crashed with unknown flavor 5 state count 1binary images 0x10 0x41f cvcrdvr armv6 4ca92ed88199f56c60997ff21ed9963e varmobileapplications6ef0091efe4743b7851508688a530869cvcrdvrappcvcrdvr 0xeb0 0xecf dnsso armv7 240b8d3f07b4fcb234de598f8e67de1a usrlibinfodnsso 0xf0 0xf4f accessibilitysettingsloader armv7 9e7d0552cedc18ba0b26cd182c47df8d systemlibraryaccessibilitybundlesaccessibilitysettingsloaderbundleaccessibilitysettingsloader0x2fe0 0x2fe26f dyld armv7 193570c1391880df7da870149117e49e usrlibdyld0x301350 0x30686f webcore armv7 859bdd351085819fb4da07d12b41543f systemlibraryprivateframeworkswebcoreframeworkwebcore0x30ac50 0x30adaf libresolv9dylib armv7 1ed920d5a995cd94e71c41631d7c551e usrliblibresolv9dylib0x30adc0 0x30bc4f libglprogrammabilitydylib armv7 9bcf5fe3e7abc3425e581ff2896579 systemlibraryframeworksopenglesframeworklibglprogrammabilitydylib0x30ca50 0x30d4bf webkit armv7 a1d04572b3214188f60f2d1961ac1fe8 systemlibraryprivateframeworkswebkitframeworkwebkit0x30eb40 0x30f76f cfnetwork armv7 9fdd61632fd1b48d65daba561528946f systemlibraryframeworkscfnetworkframeworkcfnetwork0x312970 0x3129cf mobilekeybag armv7 d33678689445fcf1898314262fd1ebd3 systemlibraryprivateframeworksmobilekeybagframeworkmobilekeybag0x3129f0 0x312e7f libblasdylib armv7 3b4a2849c10d100a178a3c2d9f6af523 systemlibraryframeworksaccelerateframeworkframeworksveclibframeworklibblasdylib0x312ea0 0x31358f proofreader armv7 479bd40ac65cb7e6c30d79d649571f systemlibraryprivateframeworksproofreaderframeworkproofreader0x313590 0x3142bf corefoundation armv7 17c9c36ae8824496b507446869cd4d9d systemlibraryframeworkscorefoundationframeworkcorefoundation0x314720 0x314a0f appsupport armv7 2a64271b39599b2180d0dfd3141027ee systemlibraryprivateframeworksappsupportframeworkappsupport0x316630 0x3280df uikit armv7 6c767127e477e6ac7b7f083857ca8064 systemlibraryframeworksuikitframeworkuikit0x328240 0x32868f libsqlite3dylib armv7 36b9bc7d02e29c8d321dd0d7bf7e115e usrliblibsqlite3dylib0x3286b0 0x3286df iomobileframebuffer armv7 1fdf9182a63464743901526caf39240a systemlibraryprivateframeworksiomobileframebufferframeworkiomobileframebuffer0x329b60 0x329ccf rawcamera armv7 78168f60a21e67ce307c5ce30054dba6 systemlibrarycoreservicesrawcamerabundlerawcamera0x329dc0 0x329e2f liblockdowndylib armv7 df3c6cea5e6848109a6e033e1d883320 usrlibliblockdowndylib0x329e30 0x329ebf libgcc s1dylib armv7 b8fc1381e87a55740d9ac66195039a63 usrliblibgcc s1dylib0x329f0 0x329fbf graphicsservices armv7 7194df9e594ae0fd9d9c600ccf456a08 systemlibraryprivateframeworksgraphicsservicesframeworkgraphicsservices0x329fc0 0x32a46f libstdc6dylib armv7 baab09769f92decea73680bc15aa8618 usrliblibstdc6dylib0x32ad30 0x32ad5f libaccessibilitydylib armv7 06dd6032c40b1feb094d63eeb2002d6d usrliblibaccessibilitydylib0x32b170 0x32b59f coretelephony armv7 bc8796c8e011fea9923170d3c948a694 systemlibraryframeworkscoretelephonyframeworkcoretelephony0x32b980 0x32b9bf iosurface armv7 e67242f81fd1c0fa5e84b3fae5d310ae systemlibraryprivateframeworksiosurfaceframeworkiosurface0x32bb60 0x32bb6f veclib armv7 85f89752df7814c1b243c26f59388523 systemlibraryframeworksaccelerateframeworkframeworksveclibframeworkveclib0x32bd10 0x32bdbf externalaccessory armv7 56a0856978d36be40c42834de8ab966d systemlibraryframeworksexternalaccessoryframeworkexternalaccessory0x32de80 0x32f06f coregraphics armv7 4022bbf12f11dd1f6b75662c764e7f7c systemlibraryframeworkscoregraphicsframeworkcoregraphics0x32f20 0x32f2df datadetectorsui armv7 8f6e03c382591e1f30f06e97b4b31570 systemlibraryprivateframeworksdatadetectorsuiframeworkdatadetectorsui0x3302b0 0x330cbf libobjcadylib armv7 89553a61e05078fd178ac0ea2081ae40 usrliblibobjcadylib0x3325a0 0x379f foundation armv7 c985a61696030b4d1bdc8fe010f4e43b systemlibraryframeworksfoundationframeworkfoundation0x37c0 0x38ef voiceservices armv7 f5b5b032e4c0b79c42e0fde5a59a6eb3 systemlibraryprivateframeworksvoiceservicesframeworkvoiceservices0x3344f0 0x33489f iokit armv7 5e0169de165c2fd25a2ddac1f3e19d06 systemlibraryframeworksiokitframeworkversionsaiokit0x336410 0x33680f libglimagedylib armv7 b96f5e231a3e39677b5e3621d61d2f11 systemlibraryframeworksopenglesframeworklibglimagedylib0x336810 0x33683f mobileinstallation armv7 74e2bd725da63513053b4fa41d8cd89c systemlibraryprivateframeworksmobileinstallationframeworkmobileinstallation0x3368e0 0x3371bf imageio armv7 abf07fc0430aaf2a2823753c78061aac systemlibraryframeworksimageioframeworkimageio0x33850 0x33969f libicucoreadylib armv7 c4f4fd74dfa672fb4d84914585bbada5 usrliblibicucoreadylib0x33c6f0 0x33c87f libripadylib armv7 436e3b257ba088ca6f773961ce619892 systemlibraryframeworkscoregraphicsframeworkresourceslibripadylib0x33c880 0x33c8bf libgfxshareddylib armv7 12f82e44ff36b29f8d0661878be83554 systemlibraryframeworksopenglesframeworklibgfxshareddylib0x33c90 0x33c9cf datadetectorscore armv7 bc6bff5b67aae8b97a8cdd43ed7b0bb1 systemlibraryprivateframeworksdatadetectorscoreframeworkdatadetectorscore0x33e360 0x33edef quartzcore armv7 109b4f6a3d2ee5aa1bb5775ab5a489bc systemlibraryframeworksquartzcoreframeworkquartzcore0x33ee20 0x33f8bf libxml22dylib armv7 1d74fa3a5cec309857503a51cb2df667 usrliblibxml22dylib0x340350 0x342cf liblapackdylib armv7 fbc3f7ad1260a159d75be53218fa9e0c systemlibraryframeworksaccelerateframeworkframeworksveclibframeworkliblapackdylib0x343a80 0x343b1f corevideo armv7 58180e899ec56cd8bca00221dea2bc32 systemlibraryframeworkscorevideoframeworkcorevideo0x343ee0 0x3442cf libvdspdylib armv7 cc8d6be7a5021266e26ebd05e9579852 systemlibraryframeworksaccelerateframeworkframeworksveclibframeworklibvdspdylib0x3442d0 0x34435f libkxlddylib armv7 4ec35c4d1e1e73416aea84537829ce91 usrlibsystemlibkxlddylib0x344380 0x345f opengles armv7 e397de408a0a789f816bc1803ae58faf systemlibraryframeworksopenglesframeworkopengles0x344e80 0x34521f mobilecoreservices armv7 d38c937ae35487da263d2657536189 systemlibraryframeworksmobilecoreservicesframeworkmobilecoreservices0x3456c0 0x3459bf coretext armv7 76eb1b63d684c3d21dba9e81296d2f systemlibraryframeworkscoretextframeworkcoretext0x3459c0 0x345d2f security armv7 7cea1027f1a381b8d6c5ffae4dae0d22 systemlibraryframeworkssecurityframeworksecurity0x3473c0 0x347dbf javascriptcore armv7 894df23ebbc4df713d9519141a61dd19 systemlibraryprivateframeworksjavascriptcoreframeworkjavascriptcore0x347dc0 0x347ddf coresurface armv7 042e433142b7faa4c96b23e5faaf13 systemlibraryprivateframeworkscoresurfaceframeworkcoresurface0x348440 0x3484bf libbz210dylib armv7 5d079712f5a39708647292bccbd4c4e0 usrliblibbz210dylib0x3487c0 0x348aaf systemconfiguration armv7 2b44ac2fc47fc45c4006d08019688dbb systemlibraryframeworkssystemconfigurationframeworksystemconfiguration0x348ac0 0x348b7f libz1dylib armv7 19a78978d5908bedc6496470fe542936 usrliblibz1dylib0x348e90 0x34929f coreaudio armv7 1723726845b73efbeca75b33d75f335a systemlibraryframeworkscoreaudioframeworkcoreaudio0x3493e0 0x3496cf libcgfreetypeadylib armv7 475259824770c6ff1b63f30238b3ea81 systemlibraryframeworkscoregraphicsframeworkresourceslibcgfreetypeadylib0x3496d0 0x349a3f textinput armv7 949f29588014140b606042685de1dee6 systemlibraryprivateframeworkstextinputframeworktextinput0x349a40 0x349c3f bom armv7 c73b68b11b2801cefbfbdb6328a7fcfb systemlibraryprivateframeworksbomframeworkbom0x34dd50 0x34e07f addressbook armv7 3dde743216bbf016019b59f821dda6e3 systemlibraryframeworksaddressbookframeworkaddressbook0x34f430 0x34f4f springboardservices armv7 7624f0a9e197261f2df43edb86ba0256 systemlibraryprivateframeworksspringboardservicesframeworkspringboardservices0x34f50 0x34f5df libbsm0dylib armv7 27ad6b3a74ce1068586eabd6a553183f usrliblibbsm0dylib0x34f5e0 0x34f64f iap armv7 42a87fc47e059f5a73dcff27b9e0be systemlibraryprivateframeworksiapframeworkiap0x3502d0 0x35151f audiotoolbox armv7 802e4d5c449b69d9552809e5230baa84 systemlibraryframeworksaudiotoolboxframeworkaudiotoolbox0x351560 0x35156f accelerate armv7 f4c04cdfdb64d209828315cdd5b60bf9 systemlibraryframeworksaccelerateframeworkaccelerate0x351fb0 0x35308f libsystembdylib armv7 3fcf32f3ad8ef745480b5b36efc41953 usrliblibsystembdylibwe tried symbolicatecrash too but it does not point to anywherethanks and regardshetal,['iphone'] +90598,jquery load page then parse html i have used the line below in my app but now i need to parse the html loaded before i show it whats the best way to get certain html elementsdivloadpagehtmlthanksupdatednow i am using this but having trouble geting the title attribute of a div with the id divfunction get title gettesthtml functiondata var data data var title div dataattrtitle alerttitle the html in the var data looks like thisdiv iddiv titletitle examplep contentpp contentpdivthanks again,['jquery'] +90630,overlay a view over whole screen when using uitabbarcontroller i want to overlay a hudstyle transparent graphic over the entire screen in a uitabbarcontroller setup the button to do this is in the first tabs screen firstviewcontroller and the overlay should also cover the tabs is this possible,"['iphone', 'objective-c', 'ios']" +90641,how to remove all objects from an nsmutablearray i need to remove all objects from an nsmutablearray i cannot seem to do this by enumerating as the code crashescan anyone tell me the best way to do this with a code example if possible,"['iphone', 'objective-c']" +90643,alert user if session is going to expire option to renew session i have been looking all day for a php or javascript solution to do thisi would like to alert the user their session is about to time out popup ability to extend the session timehere is a visual if you need one on this pageeditjquery is the framework if that helps,"['php', 'javascript']" +90648,galleryadapterview child drawable state i am using a gallery view where the view corresponding to each item is nontrivial and consists of text as well as multiple buttonswhen i click to drag the gallery view somewhere not on one of the buttons the buttons drawable state changes to pressed and appears as if all of the buttons are currently being pressed additionally the same behavior happens for the selected state eg all of the text of the child textviews changes colori am trying to prevent this behavior and have found the androidduplicateparentstate xml attribute as well as the setduplicateparentstateenabled property this seems like it should accomplish what i am trying to do but it seems to have no effectany ideas,['android'] +90656,jquery ui resizable with scroll bars i am trying to have a resizable on a div but the resizer handle is always contained within the div can i have it where scrollbars end edit i have achieved it with jscrollpane but after using jscroll i am unable to resize horizontally,"['javascript', 'jquery']" +90662,how to make ratingbar to show five stars i am following the standard example of how to add a ratingbar to control the number of stars i tried to use androidnumstars5 the problem is that the number of stars does not seem to do anything at all in portraitlayout i get 6 stars and when i flip the phone i get about 10 stars i tried to set the number of stars in my activity mybarsetnumstars5 that loads the xml but there was no success with that option either so my question is how do i define my layout so that it will only show five stars set numstars does not seem to workthanks in advanceroland,['android'] +90670,stop a swing timer from inside the action listener i am trying to stop a timer inside the the actionlistener below is the code of what i am trying to do i am tring to stop the timer i created when a certain condition is met inside the actionperformed method timerstop does not work the compiler does not let me do that any help suggestion advice would be really helpful public class toggleannotationsaction extends identifiedmultiaction this status indicates if the toggle action has been completed defines the toggling direction of a codetoggleannotationactioncode instance public static enum direction forward backwardprivate direction mydir create an action with the direction presets given by the provided codeenumcode param dir an codeenumcode defined in this class which maps to the correct direction of toggling see behaviorsmultiactidentifiedmultiactionidentifiedmultiactionenum public toggleannotationsactiondirection dir superdir thismydir dir performs the toggling moving the audio position to the nextprevious annotation afterward sends an update to all codeupdatingactionscode since the waveform thisplay autonomously decides when to paint itself this action may not result in an instant visual change pprints warnings if an appropriate annotation could not be found despite the action being enabled param e the codeactioneventcode provided by the trigger public void actionperformedactionevent e reset status to 0 status 0 annotation ann findannotationmydir curaudiogetmasterframestomilliscuraudiogetaudioprogress ifann null systemerrprintlnit should not have been possible to call getclassgetname could not find matching annotation else final long approxframe curaudiogetmastermillistoframesanngettime final long curframe curaudiogetaudioprogress ifapproxframe 0 approxframe curaudiogetmasterdurationinframes 1 givemessageerrormessagethe annotation i am toggling to is not in rangenplease check annotation file for errors return timer timer new timer10 new actionlistener private long panframe curframe private long endframe approxframe public void actionperformedactionevent evt ifmydir directionforward if panframe endframe how do i stop my timer here return curaudiosetaudioprogresswithoutupdatingactionspanframe panframe 40 else ifmydir directionbackward if panframe endframe how do i stop my timer here return curaudiosetaudioprogresswithoutupdatingactionspanframe panframe 40 timerstart myframegetinstancerequestfocusinwindow a forward backward codetoggleannotationsactioncode should be enabled only when audio is open not playing and when there is an annotation following preceding the current position overridepublic void update ifcuraudioaudioopen ifcuraudiogetplayergetstatus precisionplayerstatusplaying setenabledfalse else double curtimemillis curaudiogetmasterframestomilliscuraudiogetaudioprogress iffindannotationmydir curtimemillis null setenabledtrue else setenabledfalse else setenabledfalse finds the nextprevious codeannotationcode relative to a certain audio position in milliseconds param dir the direction of movement param curtimemillis the present time in milliseconds return in principle the codeannotationcode afterbefore codecurtimemilliscode private annotation findannotationdirection dir double curtimemillis annotation anns annotationthisplaygetannotationsinorder ifmydir directionforward forint i 0 i annslength i ifannsigettime curtimemillis 1 return annsi else forint i annslength 1 i 0 i ifcurtimemillis annsigettime 1 return annsi return null thanks in advance krishnan,['java'] +90677,how to use jquery to prevent the space key from entering a space i thought it would be a simple thing to hijack the space key when in a form input so that it would function like a hyphen generally jquery makes stuff like this really simplethe code i tried is this streamurlkeydownfunction e if ekeycode 32 return 109 but this has no effect whatsoever i tried a more simple script streamurlkeydownfunction e if ekeycode 32 return 109 alertekeycode this script correctly alerts 32 on space press and 109 on hyphen press also i have no javascript errorswhy wouldnt if ekeycode 32 return 109 work when i replace that line with if ekeycode 32 alertspace i get the alert correctly so i know the if is returning true correctlywhat givesedit solutionthanks to nick for pointing out the copypaste issue i ended up with a little bit of a hybrid heres the code that i have gotten to work which is both smooth and handles copypaste streamurlkeydownfunction e if ekeycode 32 thisvalthisval append to input return false return false to prevent space from being added changefunction e thisvalfunction i v return vreplace g,"['javascript', 'jquery']" +90681,good learning method for objectivec i know this must be asked a millions times and cannot be easy to answer as there is o definitive method but any help would be appreciated thanksi have been playing around with all sorts of things in xcode and with objectivec however i cannot seem to find a good way of learning things in an efficient wayi have bought the book programming in objectivec 20 and its great but just lays down the basics it seemsi want to learn in the 2d game development direction then of course 3d after nailing that if thats the right thing to doi am 17 currently in year 13 last year of schoola levels and am almost definitely taking a gap year any good well known reputable courses online or offline real world this is my first programming language and i am absolutely serious about learning thisone last question is when learning things online i have in the past started building a feature and learning a certain aspect in programming only to find out after adding more its slows down the app or its to inefficient is the key to use a certain method in a certain situation being os many ways to do the same thing or use any of those methods and refine it in your app to make it run smoothly sorry its hard for me to know when i have little experience thus farsorry for rambling on i would appreciate any help thank you,"['iphone', 'objective-c']" +90683,calling haskell from c code i am currently writing an app in c and found that some of its functionality would be better written in haskell i have seen instructions on calling haskell from c code but is it possible to do the same with cedit to clarify what i am looking for is a way to compile haskell code into an external library that g can link with the object code from cupdate i have put up a working example below for anyone else interested also so i would not forget,['c++'] +90708,sql insert into multiple tables in one query assuming that i have two tables names and phonesand i want to insert data from some input to the tables in one query how can it be doneplease if it can be done explain the syntax,"['sql', 'mysql']" +90734,static method overloading with generics where i try to create two static overloading methods i got an compilation error can anyone explain thispublic class a public static void asetstring stringset public static void asetmapstringstring mapset,['java'] +90758,is there a generator version of stringsplit in python stringsplit returns a list instance is there a version that returns a generator instead are there any reasons against having a generator version,['python'] +90763,ajaxcontroltoolkit requires aspnet ajax 40 scripts can anyone have a solution for this issuemicrosoft jscript runtime error ajaxcontroltoolkit requires aspnet ajax 40 scripts ensure the correct version of the scripts are referenced if you are using an aspnet scriptmanager switch to the toolkitscriptmanager in ajaxcontroltoolkitdlli am using aspnet 35 vs 2008 the version i can see in the ajaxcontroltoolkitdll file 35404122,['asp.net'] +90766,how can i find all subclasses of a class given its name i need a working approach of getting all classes that are inherited from the base class in python,['python'] +90771,differences in jsonstringify result between browsers when i jsonstringify the following codevar exampleobject name a12iga kovaa kraj a12ua34emberki get different results between browsersie8 and google chrome returnnameu017diga kovau010dkraju017duu017eemberkwhile firefox and opera returnnamea12iga kovaakraja12ua34emberki am using the browsers native json implementation in all 4 browsers if i undefine the native json implementation and replace it with the one from jsonorg then all browsers returnnamea12iga kovaakraja12ua34emberkwhy is this happening which result is correct and is it possible to make that all browsers returnnameu017diga kovau010dkraju017duu017eemberk,['javascript'] +90778,invalidkeyexception illegal key size i have a test which runs great on my development macbook pro but fails to run in continuous integration teamcity serverthe error is followingjavasecurityinvalidkeyexception illegal key size at javaxcryptocipheradashoa13 at javaxcryptocipherinitdashoa13 at javaxcryptocipherinitdashoa13both development box and teamcity uses java 16 and i use bouncycastle library for the need of special aes encryptionthe code is followingprivate byte aesencryptedinfostring info throws unsupportedencodingexception illegalblocksizeexception badpaddingexception invalidkeyexception nosuchalgorithmexception nosuchpaddingexception invalidparameterspecexception invalidalgorithmparameterexception nosuchproviderexception securityaddprovidernew bouncycastleprovider secretkey secret new secretkeyspeccustomlongsecretkeysubstring0 32getbytes aes cipher cipher ciphergetinstanceaescbcpkcs7padding bc cipherinitcipherencrypt mode secret new ivparameterspecvector secret keygetbytes return cipherdofinalinfogetbytesutf8updatelooks like according to the selected answer i have to modify something on my teamcity installation and it will possibly affect some user installations so its not a good choice i have to switch to another crypto library to do that without limitations so probably bouncy castle will helpupdate 2i actually switched to use bouncycastle to avoid this limitation note this only works if you use own bc classes directly not the bc provider,['java'] +90803,how does linker know which symbols should be resolved at runtime how does linker know which symbols should be resolved at runtime particularly i am interested what information shared object files carry that instruct linker to resolve symbols at runtime how does the dynamic symbol resolution work at runtime ie what executable will do to find the symbol and in case multiple symbols with the same name were defined which would be found what happens if the file was linked only statically but then it is linked dynamically at runtime as part of a shared library which symbol will be used by the executable in other words is that possible to override symbols in an executable by linking those symbols into a shared librarythe platform in question is sun os,['c++'] +90811,scala object extends java class static field i am would like to know how could i inherent static field from java class in scalahere is a java example if i a class named classfromjava i could extend it add some static field and use the subclass to access the version fieldpublic class classfromjava public static int version 1public class classfromjavasub extends classfromjava public static string note a notepublic class test public static void main string args systemoutprintln classfromjavasubversion this works but if i want extends classfromjava in scala and add some constant value it seems not workobject classfromscala extends classfromjava val note a noteobject test def main args arraystring this line would not compile classfromscala has no value version println classfromscalaversion what should i do if i would like classfromscala also has the version variable,['java'] +90819,why was not yield added to c0x i have been using yield in many of my python programs and it really clears up the code in many cases i blogged about it and it is one of my sites popular pagesc also offers yield a it is implemented via statekeeping in the caller side done through an automatically generated class that keeps the state local variables of the function etci am currently reading about c0x and its additions and while reading about the implementation of lambdas in c0x i find out that it was done via automatically generated classes too equipped with operator storing the lambda code the natural question formed in my mind they did it for lambdas why did not they consider it for support of yield toosurely they can see the value of coroutines so i can only guess that they think macrobased implementations such as simon tathams as an adequate substitute they are not however for many reasons calleekept state nonreentrant macrobased that alone is reason enough etcedit yield does not depend on garbage collection threads or fibers you can read simons article to see that i am talking about the compiler doing a simple transformation such asint fibonacci int a 0 b 1 while true yield a int c a b a b b c intostruct generatedfibonacci int state int a b generatedfibonacci state 0 a 0 b 1 int operator switch state case 0 state 1 while true return a case 1 int c a b a b b c garbage collection no threads no fibers no simple transformation arguably yes,['c++'] +90831,how do i add authorizations to code sign an app from new keychain without any human interaction i am trying to automate the process of building iphone apps with a particular certificate so imagine if different users uploaded their cert into the system and it was immediately available to code sign against i want to do this without any interaction i also do not want to clutter up the system or logon keychain with different user certificates to this end i haveturned off the requirement in xcode to require code signing for a a builddeveloped a ruby script to build an application via the xcodebuild command line toolcreated a script to automatically create a new keychain for a user of my systemwritten a script to code sign a built iphone app everything works but i need to manually hit enter when the codesign program tries to exercise the sign permission my keychains are all unlocked oddly enough it works if i make the keychain the default keychain but that is not scalable ie i could only have one build process going at any given time when i manually click always allow for that process i get an entry in my keychain dump that looks like thisentry 1 authorizations 6 decrypt derive export clear export wrapped mac sign do notrequirepassword description privatekey applications 2 0 usrbincodesign okso i am thinking that i need to use the authorize command in security to preautorize codesign for those permissions the security man page is pretty poor i cannot seem to get it to work using commands like thissecurity v authorize uew sign usrbincodesign code sign vars pointing to app and a specific keychaindoes anyone have any ideas,['iphone'] +90852,load rtf or text file into uitextview iphone sdk hi i was wondering how should i load rtf or text file into uitextview i use several codes but didt work nsstring filepath nsbundle mainbundle pathforresourcefilename oftypetxtmytextviewtext filepaththank you,['iphone'] +90860,understanding zip function all thiscussion is about python 312 see python docs for the source of my questioni know what zip does i just do not understand why it can be implemented like thisdef zipiterables zipabcd xy ax by iterables mapiter iterables while iterables yield tuplemapnext iterableslet us say i call zipc1 c2 c3 if i understand correctly iterables is initially the tuple c1 c2 c3the line iterables mapiter iterables converts it to an iterator that would return iterc1 iterc2 iterc3 if iterated throughinside the loop mapnext iterables is an iterator that would return nextiterc1 nextiterc2 and nextiterc3 if iterated through the tuple call converts it to nextiterc1 nextiterc2 nextiterc3 exhausting its argument iterables on the very first call as far as i can tell i do not understand how the while loop manages to continue given that it checks iterables and if it does continue why the tuple call does not return empty tuple the iterator being exhaustedi am sure i am missing something very simple,['python'] +90871,is there a coalesce operator for properties of properties in c so there is the coalescing operator that allows handy handling of null objects ie mythisplaystring mystring nabut is there a nice fancy operator for handling a similar situation on properties of objects for instance lets say that the property you are interested in is a property of a property like mydataobjectmysubmodelmypropertyif myproperty is null you want coalesce to na you can use here but what if mydataobject is null or mydataobjectmysubmodel this also comes up with xml when trying to get optional attributes and elements of an element ie mystring myelementattributemyoptionalattributevalue na fails if the attribute is not thereis there a nice fancy way of handling this scenario,['c#'] +90873,ruby test each array element get one result i want a oneliner to return truefalse that tests each element in an array for whether it is an integer or not so if any element in the array is not an integer it should return false else true heres my try 214map x xis a integerreduce x result x and result true 2a4map x xis a integerreduce x result x and result falseany other ideas to thistill it down furtherthanks,['ruby'] +90878,java constants file i am developing an android application and i am very new on java and androidi want to create some constants to use in some activities where can i define these constantsthanks,"['java', 'android']" +90882,phpunit stacktestassertempty deprecated i am learning building php unit tests using phpunit there they have a manual and i encountered this example where they use assertempty but when i run this code in command line i get this error call to undefined method stacktestassertempty in varwtestsstacktestphp on line 20 so if this method is deprecated or something why they use it also is there another method for this of course i can try this thisassertequals0 countstack but anywaysthe same with assertnotempty,['php'] +90883,what is the purpose of double implying for exampleconst decimal dollars 2550mwhy do we have to add that mwhy not just doconst decimal dollars 2550since it already says decimal doesnt it imply that 2550 is a decimal,['c#'] +90884,plotting histograms whose bar heights sum to 1 in matplotlib i would like to plot a normalized histogram from a vector using matplotlib i tried the followingplthistmyarray normedtrueas well asplthistmyarray normed1but neither option produces a yaxis from 0 1 such that the bar heights of the histogram sum to 1 i would like to produce such a histogram how can i do itthanks,['python'] +90893,uidatepicker in popoverview in ipad i have an ipad specific application running ios 322 which thisplays a settings view in a ui popover this all renders great but now i am trying to get a date picker to render inside the view and not sure what the best approach is for thisplaying itright now it has a button which toggles visibility of the date picker within the modal but that seems very clumsy for managing thismissal compared to the normal approach of an action sheeti have not been able to find a best practice for this situation and was wondering if anyones run into this before and could offer some suggestions or guidancethanks,['ios'] +90918,how to limit the size of a table i have a sql server 2005 database i am logging data to a table i want to prevent the table data from getting too big how can i limit the size of the table to x number of rows and keep logging i want the oldest rows to drop off,['java'] +90922,count character occurrences in a string how can i count the number of in a string like bla bla blabla bla,['c++'] +90931,using a thistinct clause to filter data but still pull other fields that are not thistinct i am trying to write a query in postgresql that pulls a set of ordered data and filters it by a thistinct field i also need to pull several other fields from the same table row but they need to be left out of the thistinct evaluation example select thistinctuser id user id created at from creations order by created at limit 20i need the user id to be thistinct but do not care whether the created at date is unique or not because the created at date is being included in the evaluation i am getting duplicate user id in my result setalso the data must be ordered by the date so using thistinct on is not an option here it required that the thistinct on field be the first field in the order by clause and that does not deliver the results that i seekhow do i properly use the thistinct clause but limit its scope to only one field while still selecting other fields,"['sql', 'ruby-on-rails']" +90934,nlog performance what should the expected overhead be for loggingi have tried this example private class person private static logger logger logmanagergetcurrentclasslogger public string name get private set public personstring name name name loggerinfonew person created with name 0 name listperson people new listperson for int i 0 i maxtest i peopleaddnew personitostring with maxtest values of 10050010 50results in maxtestnologging logging100 25ms 186ms500 33ms 812ms10 33ms 1554ms50 33ms 7654msgranted one would probably never log this excessive amount but it this the performance hit one would expect i have also tried using the asyncwrapper in the config target nameasyncfile xsitypeasyncwrapper target namefile xsitypefile filenamebasedirlogtxt targetregards eric,['c#'] +90948,visual studio breakpoint macro to modify a value i am debugging an application c and i have found a point in the code where i want to change a value via the debugger so right now i have got a breakpoint set whereupon i dodebugger reaches breakpointi modify the variable i want to changei hit f5 to continue runninglather rinse repeatit is hitting this breakpoint a lot so i would like to automate this i would like to set the breakpoint to run a macro and continue executionhowever i have no experience writing visualstudio macros so i do not know the commands for modifying a variable of the executing program i have looked around but have not found anything helpful online so far,['c++'] +90951,track progress when using parallelforeach i am refactoring my program to use parallelforeach before when i was using a regular for loop i was updating a wpf progress bar using thispatcher thisplaying the completed by dividing the current array index by the array size with a parallel foreach loop this does not thisplay properly ie jumps eratically which is expectedhow can i update a wpf progress bar from a parallel for each loop so i can track the number of completed iterations,"['c#', '.net']" +90977,near and far pointers what is difference between our usual pointersones which we normally use near pointers and far pointers and is there a practical usage for near and far pointers in present day cc systems any practical scenario which necessiates use of these specific pointers and not other cc semantics will be very helpful,"['c++', 'c']" +90995,how to update column with null value i am using mysql and need to update a column with a null value i have tried this many different ways and the best i have gotten is an empty stringis there a special syntax to do this,['mysql'] +90996,visual studio how to debug a library with an external executable i am developing a class library the library is to be used by another program an exe with no source code the library file location is passed as a parameter to this exe for example by running progexe libdlli would like to debug the library using this exe using debug tools such as breakpoints etc how do i use visual c to do thisi found a possible way which is creating a oneline program which execute progexe libdll surely there is a better way,['.net'] +91003,how to stop visual studio from opening my winforms controls in the designer when i want to editview the code for a winforms controlform i created i need to rightclick in the solution and select view code the default action for opening the file is view designer this appears to be the case for any c file containing a class that inherits from a winforms control even if this is indirectly the daft thing is that vs does this if it cannot run the designer for instance when the control is not the first class in the file is there hint or attribute or workaround to stop vs from doing this,['c#'] +91011,shortcut to create properties in visual studio i have seen some people creating properties in c really fast but how they dod itwhat shortcuts are available in visual studio currently using visual studio 2010 to create propertiesi am using cfor examplepublic string mystring getset,['c#'] +91018,how to upload files to amazon s3 official sdk that are larger than 5 mb approx i am using the latest version of the official amazon s3 sdk 10141 to create a backup tool so far everything works correctly if the size of the file i am uploading is below 5 mb but when any of the files is above 5 mb the upload fails with the following exceptionsystemnetwebexception the request was aborted the request was canceled systemioioexception cannot close stream until all bytes are written at systemnetconnectstreamcloseinternalboolean internalcall boolean aborting end of inner exception stack trace at amazons3amazons3clientprocessrequesterrorstring actionname httpwebrequest request webexception we httpwebresponse errorresponse string requestaddr webheadercollection resphdrs type t at amazons3amazons3clientinvokets3request userrequest at amazons3amazons3clientputobjectputobjectrequest request at backuptoolkits3moduleuploadfilestring sourcefilename string destinationfilename in wcodeautobackuptoolbackuptoolkits3modulecsline 88 at backuptoolkits3moduleuploadfilesstring sourcedirectory in wcodeautobackuptoolbackuptoolkits3modulecsline 108note 5 mb is roughly the boundary of failure it can be slightly lower or anything higheri am assuming that the connection is timing out and the stream is being automatically closed before the file upload completes i have tried to find a way to set a long timeout but i cannot find the option in either amazons3 or amazons3config any ideas on how to increase the timeout like an application wide setting i can use or is it unrelated to a timeout issuecodevar s3client awsclientfactorycreateamazons3clientawsaccesskey awssecretkeyvar putobjectrequest new putobjectrequest bucketname bucket filepath sourcefilename key destinationfilename md5digest md5base64 generatemd5digest trueusing var upload s3clientputobjectputobjectrequest,['.net'] +91020,zend form setrequiredtrue or addvalidatornotempty is there any real difference between the behavior or output of these 2 they look to me like they do the same thingaddvalidatornotempty setrequiredtrue,['php'] +91028,gcc left shift overflow the following little program is very awkward using gcc version 421 apple inc build 5664 on a macinclude stdiohint main int x 1 32 int y 32 int z 1 y printfxd z dn x zthe result is x0 z 1any idea why the values of x and z are differentthanks a lot,['c'] +91030,convert dictionary to semicolon separated string in c simple one to start the day given a dictionarystring string as followsvar mydict new dictionarystring stringmydicta 1mydictb 2mydictc 3mydictd 4i wish to create a string a1b2c3d4an example implementationvar mystringbuilder new stringbuilderbool first trueforeach keyvaluepairstring string pair in mydict if first first false else mystringbuilderappend mystringbuilderappendformat01 pairkey pairvaluevar mydesiredoutput mystringbuildertostringnote the dictionary is likely to have less than 10 items which suggests that a stringbuilder is overkillwhat alternative implementations are more succinct efficient does the framework have any features that will help,['c#'] +91034,select per month i have got the following tablepurchasesid item user price timethe time field is a timestampi need a query that would return one row per month and that row would contain the sum of price for each item in that month,"['sql', 'mysql']" +91037,long lived java weakreferences i am currently trying to diagnose a slow memory leak in my application the facts i have so far are as followsi have a heap dump from a 4 day run of the applicationthis heap dump contains 800 weakreference objects which point to objects all of the same type which i will call foo for the purposes of this question retaining 40mb of memoryeclipse memory analysis tool shows that each of the foo objects referred to by these weakreferences is not referred to by any other objects my expectation is that this should make these foo objects weakly reachable and thus they should be collected at the next gceach of these foo objects has a timestamp which shows that they were allocated over the course of the 4 day run i also have logs during this time which confirm that garbage collection was happeninga huge number of foo objects are being created by my application and only a very small fraction of them are ending up in this state within the heap dump this suggests to me that the root cause is some sort of race conditionmy application uses jni to call through to a native library the jni code calls newglobalref 4 times during start of day initialisation to get references to java classes which it useswhat could possibly cause these foo classes to not be collected despite only being referenced by weakreferences according to eclipse memory analyser tooledit1mindasthe weakreference i am using is equivalent to the following example codepublic class fooweakref extends weakreferencefoo public long longa public long longb public string stringa public fooweakreffoo xiobject referencequeuefoo xiqueue superxiobject xiqueue foo does not have a finalizer and any finalizer would not be a consideration so long as the weakrefs have not been cleared an object is not finalizable when it is weakly reachable see this page for detailskasten the weakreferences are cleared before the object is finalizable my heap dump shows that this has not happenedjarnbjo i refer to the weakreference javadocsuppose that the garbage collector determines at a certain point in time that an object is weakly reachable at that time it will atomically clear all weak references to that object and all weak references to any other weaklyreachable objects from which that object is reachable through a chain of strong and soft referencesthis suggests to me that the gc should be detecting the fact that my foo objects are weakly reachable and at that time clearing the weak referencesedit 2j flemm i know that 40mb does not sound like much but i am worried that 40mb in 4 days means 40mb in 100 days all of the docs i have read suggest that objects which are weakly reachable should not hang around for several days i am therefore interested in any other explanations about how an object could be strongly referenced without the reference showing up in a heap dumpi am going to try allocating some large objects when some of these dangling foo objects are present and see whether the jvm collects them however this test will take a couple of days to setup and completeedit 3jarnbjo i understand that i have no guarantee about when the jdk will notice that an object is weakly reachable however i would expect that an application under heavy load for 4 days would provide enough opportunities for the gc to notice that my objects are weakly reachable after 4 days i am strongly suspicious that the remaining weakly references objects have been leaked somehowedit 4j flemm thats really interesting just to clarify are you saying that gc is happening on your app and is not clearing softweak refs can you give me any more details about what jvm gc config you are using my app is using a memory bar at 80 of the heap to trigger gc i was assuming that any gc of the old gen would clear weak refs are you suggesting that a gc only collects weak refs once the memory usage is above a higher threshold is this higher limit configurableedit 5j flemm your comment about clearing out weakrefs before softrefs is consistent with the javadoc which statessoftref suppose that the garbage collector determines at a certain point in time that an object is softly reachable at that time it may choose to clear atomically all soft references to that object and all soft references to any other softlyreachable objects from which that object is reachable through a chain of strong references at the same time or at some later time it will enqueue those newlycleared soft references that are registered with reference queuesweakref suppose that the garbage collector determines at a certain point in time that an object is weakly reachable at that time it will atomically clear all weak references to that object and all weak references to any other weaklyreachable objects from which that object is reachable through a chain of strong and soft references at the same time it will declare all of the formerly weaklyreachable objects to be finalizable at the same time or at some later time it will enqueue those newlycleared weak references that are registered with reference queuesfor clarity are you saying that the garbage collector runs when your app has more than 50 free memory and in this case it does not clear weakrefs why would the gc run at all when your app has 50 free memory i think your app is probably just generating a very low amount of garbage and when the collector runs it is clearing weakrefs but not softrefsedit 6j flemm the other possible explanation for your apps behaviour is that the young gen is being collected but that your weak and soft refs are all in the old gen and are only cleared when the old gen is being collected for my app i have stats showing that the old gen is being collected which should mean that weakrefs get clearededit 7i am starting a bounty on this question i am looking for any plausible explanations for how weakrefs could fail to be cleared while gc is happening if the answer is that this is impossible i would ideally like to be pointed at the appropriate bits of openjdk which show weakrefs being cleared as soon as an object is determined to be weakly reachable and that weak reachability is resolved every time gc runs,['java'] +91049,how can i check if an sql result contains a newline character i stored or think i stored some text from a textbox that is effectively lolncatsin sql management studio it comes up in the description has lol catshow can i check if the and is there or not,['sql'] +91051,how to locate a freedelete mismatch reported by valgrind in a multithreaded program here is the valgring report14546 thread 514546 invalid free delete delete14546 at 0x4905d free vg replace mallocc23514546 by 0x3bf7efaa8f free mem in lib64tlslibc234so14546 by 0x3bf7efa581 libc freeres in lib64tlslibc234so14546 by 0x4802676 vgw freeres vg preloadedc6214546 address 0x4dc4ee0 is not stackd mallocd or recently freedhow can i know which thread is it as the thread number varies from one execution to another will assigning names to my threads help here edit i do not think it will as this is mentioned in the drd section of the manuali am using valgrind311 on red hat enterprise linux as4,['c++'] +91076,ferror messages in rails 30 rails 30 deprecated ferror messages and now requires a plugin to work correctly i however want to learn how to thisplay error messages the new native way i am following the getting started guide which uses the deprecated method when implementing the comments form for exampleh2add a commenth2 form forpost postcommentsbuild do f ferror messages div classfield flabel commenter br ftext field commenter divdiv classfield flabel body br ftext area body divdiv classactions fsubmit div end here is the correct way to do it as generated by the scaffold form forpost do f if posterrorsany div iderror explanation h2 pluralizeposterrorscount error prohibited this post from being savedh2 ul posterrorsfull messageseach do msg li msg li end ul div end i understand that i use the post variable in the latter example but what variable do i reference in the former to get the error messages for comment creation,"['ruby-on-rails', 'ruby']" +91085,inject aspnet mvc controller property into service layer dependency i am using an approach similar to the one in this aspnet mvc tutorial where you pass a wrapper around a controllers modelstate collection into a validation class so that the controller can access error informationhere is a cooked up exampleinterface iproductvalidator void validateproduct itemclass productvalidator constructor public productvalidatormodelstatewrapper validationdictionary interface iproductservice void addproductpublic class productservice iproductservice constructor public productserviceiproductvalidator validator using the castle windsor container for iocdi how do i create the iproductservice typically i would havemvcapplicationioccontainerresolveiproductservicebut this is not able to inject the value of the controllers modelstate property into the constructor for productvalidator i could possibly wire this up using constructor parameters but that seems really ugly,['c#'] +91106,naming conventions for java methods that return booleanno question mark i like using question mark at the end of methodfunction names in other languages java does not let me do this as a work around how else can i name boolean returning methods in java using an is has shouldcan in the front of method sound ok for some cases is there a better way to name such methods for eg createfreshsnapshot,['java'] +91119,csv to excel conversion is there a way to convert csv file to excel file upon request through apachehtaccess,['php'] +91129,extending an existing layout in rails i have my main application layout but then i have an account section of my site which has exactly the same layout as the application layout markupwise except the account pages have an added sidebar in the content area of the layoutrather than blatantly copy the application layout and create a nearly redundant account layout i would like to extend the application layout adding the sidebar in the content areaso i have something like this in my application layouthtmlbodydiv idcontent yield divbodyhtmland i wanthtmlbodydiv idcontent div idsidebardiv yield divbodyhtmlis there a way to accomplish this without copying code,['ruby-on-rails'] +91130,vs2010 show derived types option missing in class view i am working with a visual c project in visual studio 2010 and browsing various types in the class view according to this documentation there is supposed to be a show derived types option in the class view settings menu similar to the show base types option however it seems to be missing i have not managed to find any bug reports or references to this issue so i am wondering if i am just missing something here,['c#'] +91131,how do i remove the warning from a easymockanyobjectlistclass call compiler cannot stop complaining with this call easymockanyobjectlistclass i tried to specify lists typeeasymockanyobjectlistmytypeclassbut it does not seems to be an option anyway it is stupid since java will erase the type during the compilationis there a clean way suppresswarning is not a clean way imo to remove this warningthank you,['java'] +91150,how to script firefox or any mozilla based browser i need to automate something like thisopen an urlwait until the page is fully loadedsave complete page as i can provide a namei saw line options but i cannot find an option to invoke the command save page as in mode web page complete so i can have all css js xml and related files needed to thisplay the pagei know some python that i could use it if i find a way to talk to firefox the webbrowser module is not help here since it does not allow to save a page i am opened to any kind of solutionplatform linux but i could use another if there is no other wayimportant i cannot just retrieve the html given by the web server since i need all css js images and files that are used to see to page as rendered by the browser for example an image may be not linked in the html but referenced by a js that is executed when the page is rendered the only way i think that i could retrieve this image is by executing the page as if i were the browser and then get all files from the resulting page and not the original page,['python'] +91153,need help with sql query to find things tagged with all specified tags let us say i have the following tablestagsid integername stringpostsid integerbody texttaggingsid integertag id integerpost id integerhow would i go about writing a query that select all posts that are tagged with all of the following tags name attribute of tags table cheese wine paris frace city scenic artsee also note similar but not a duplicate,"['sql', 'mysql', 'ruby-on-rails']" +91166,is it possible to add an array or object to sharedpreferences on android if not is there any workaround i have an array list of objects that have a name and an icon pointer i do not want to use a database,['android'] +91170,how can i make a horizontal listview in android possible duplicatehorizontal listview in android like many things in android you wouldnt think this would be such a hard problem but oh by golly would you be wrong and like many things in android the api does not even provide a reasonably extensible starting point i will be damned if i am going to roll my own listview when all i want is to take the thing and turn it on its side rantokay now that i am done fuming let us talk about the problem itself what i need is basically something exactly like the gallery but without the centerlocking feature i do not really need listviews listselector but it is a nicetohave mostly i could do what i want with a linearlayout inside a scrollview but i need the child views to come from a listadapter and i would really like to have a view recycler and i really do not want to write any layout codei peeked into the source code for some of these classesgallery it looks like i could use the gallery if i override most of the onxyz methods copy all their source code but refrain from calling scrollintoslots but i am sure that if i do that i will run into some member field that is inaccessible or some other unforeseen consequenceabsspinner since the mrecycler field is packageprivate i doubt i will be able to extend this classabslistview it looks like this class is only meant for vertical scrolling so no help thereadapterview i have never had to extend this class directly if you tell me it is easy to do and that it is easy to roll my own recyclebin i will be very skeptical but i will give it a shoti suppose i could possibly copy both absspinner and gallery to get what i want hopefully those classes are not using some packageprivate variable i cannot access do yall think that is a good practice does anyone have any tutorials or thirdparty solutions that might put me in the right directionupdatethe only solution i have found so far is to do it all myself since asking this question i have overridden adapterview and implemented my own horizontallistview from scratch the only way to truly override the gallerys centerlocking feature is to override the private scrollintoslots method which i believe would require generating a subclass at runtime if youre bold enough to do that it is arguably the best solution but i do not want to rely on undocumented methods that could changeswathi ep below suggested that i give the gallery an ontouchlistener and override the scroll functionality if you do not care about having fling support in your list or if it is okay for the views to snap to the center at the end of the fling animation then this will work for you however in the end it still proves impossible to remove the centerlocking feature without removing fling support and i ask you what kind of list does not flingso alas this did not work for me but if youre interested in this approach read oni also had to make some additions to swathis code to get what i wanted in gesturelistenerontouch in addition to delegating to the gesture detector i also had to return true for action up and action cancel events that successfully thisabled the centerlocking feature but it also thisabled flinging i was able to reenable fling by having my own gesturelistener delegate to the gallerys onfling method if you want to try it out go into your apidemos sample code and replace the gallery1java class with the following codeimport comexampleandroidapisrimport androidappactivityimport androidcontentcontextimport androidcontentrestypedarrayimport androidosbundleimport androidviewcontextmenuimport androidviewgesturedetectorimport androidviewmenuitemimport androidviewmotioneventimport androidviewviewimport androidviewviewgroupimport androidviewcontextmenucontextmenuinfoimport androidviewgesturedetectorsimpleongesturelistenerimport androidviewviewontouchlistenerimport androidwidgetadapterviewimport androidwidgetbaseadapterimport androidwidgetgalleryimport androidwidgetimageviewimport androidwidgettoastimport androidwidgetadapterviewadaptercontextmenuinfoimport androidwidgetadapterviewonitemclicklistenerpublic class gallery1 extends activity override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutgallery 1 reference the gallery view final gallery g gallery findviewbyidridgallery set the adapter to our custom adapter below gsetadapternew imageadapterthis set a item click listener and just toast the clicked position gsetonitemclicklistenernew onitemclicklistener public void onitemclickadapterview parent view v int position long id toastmaketextgallery1this position toastlength shortshow gesture detection final gesturedetector gesturedetector new gesturedetectornew mygesturedetectorg ontouchlistener gesturelistener new ontouchlistener override public boolean ontouchview v motionevent event boolean retval gesturedetectorontoucheventevent int action eventgetaction if action motioneventaction up action motioneventaction cancel retval true onup return retval public void onup here i am merely copying the gallerys onup method for int i ggetchildcount 1 i 0 i ggetchildatisetpressedfalse gsetpressedfalse gsetontouchlistenergesturelistener we also want to show context menu for longpressed items in the gallery registerforcontextmenug override public void oncreatecontextmenucontextmenu menu view v contextmenuinfo menuinfo menuaddrstringgallery 2 text override public boolean oncontextitemselectedmenuitem item adaptercontextmenuinfo info adaptercontextmenuinfo itemgetmenuinfo toastmaketextthis longpress infoposition toastlength shortshow return true public class imageadapter extends baseadapter int mgalleryitembackground public imageadaptercontext c mcontext c see resvaluesattrsxml for the declarestyleable that defines gallery1 typedarray a obtainstyledattributesrstyleablegallery1 mgalleryitembackground agetresourceid rstyleablegallery1 android galleryitembackground 0 arecycle public int getcount return mimageidslength public object getitemint position return position public long getitemidint position return position public view getviewint position view convertview viewgroup parent imageview i new imageviewmcontext isetimageresourcemimageidsposition isetscaletypeimageviewscaletypefit xy isetlayoutparamsnew gallerylayoutparams136 88 the preferred gallery item background isetbackgroundresourcemgalleryitembackground return i private context mcontext private integer mimageids rdrawablegallery photo 1 rdrawablegallery photo 2 rdrawablegallery photo 3 rdrawablegallery photo 4 rdrawablegallery photo 5 rdrawablegallery photo 6 rdrawablegallery photo 7 rdrawablegallery photo 8 public class mygesturedetector extends simpleongesturelistener private gallery gallery public mygesturedetectorgallery gallery thisgallery gallery override public boolean onflingmotionevent e1 motionevent e2 float velocityx float velocityy return galleryonflinge1 e2 velocityx velocityy,['android'] +91174,why does id id and id id in cpython why does cpython no clue about other python implementations have the following behaviortuple1 tuple2 dict1 dict2 list1 list2 makes sense tuples are immutableassertidtuple1 idtuple2 also makes sense dicts are mutableassertiddict1 iddict2 lists are mutable tooassertidlist1 idlist2assertid id why no assertion error on thisassertid id or thisassertid idi have a few ideas why it may but cannot find a concrete reason whyeditto further prove glenns and thomas point1 id43309099122 x 3 idx43309099124 id4334243440,['python'] +91175,best practices for editing sln proj suo files in net there are suo sln proj files for every solutionproject whilst i know what these files are is it wise to edit them by hand do they ever even need to be edited if so what is the best waythanks,['.net'] +91180,definitive algorithm for determining most accurate returned from iphone corelocation has anyone nailed this down yeti have read a lot of forum postings and i still cannot tell if this is a settled questiongiven that didupdatetolocation can return cached or inaccurate information how do you tell when you have an accurate fixwhen you set desired accuracy to kcllocationaccuracynearesttenmeters hundredmeters kilometer threekilometers it seems obvious that you can compare the horizontal accuracy of points returned against the desired accuracy to decide when to accept a pointbut the values of kcllocationaccuracybestfornavigation and kcllocationaccuracybest are 2 and 1 respectively so how do i know when i have the desired accuracyi currently check the age of the fix and reject any fix that is too old timewisei then check to see if the horizontal accuracy is negative and reject that if it isif i get a positive verticalaccuracy then i generally use that fix since the corresponding horizontal accuracy is also goodbut these checks were used when i has looking for accuracy in the 10100s of metersi do not know what if anything to check when i am running accuracybestfornavigation or accuracybest am i suppose to level the locationmanager running constantly and never expect to shut it off and do not filter any resultsanyone wiser than i with an answerthanks,['iphone'] +91183,padding between checkbox and label for the css gurus out there this markup outputs a checkbox with a label value1 to its right but value1 is too close to the checkboxdd idrrelement label for1 input typecheckbox value1 idrr1 namerr value 1 labelddso i am trying to create a paddingright effect to the right of the checkbox but it is not working the checkbox and label move together how can i target the checkbox only or its text only so i create a padding gapdd label input paddingright100px,['css'] +91188,handling html select options with event delegation to javascript on iphone safari we are developing a web application with gui customized to use on iphone a page on the app has 3 subsequent select dropdowns where selection of an option from 1st dropdown derives the options for 2nd dropdown and so forth the subsequent dropdown options are populated by javascript based on onchange event on previous dropdown the problem is that on iphone the options for a select appears with prev and next links to move to previous and next control when the next link is clicked then the control moves to next select and thisplays the options the javascript is triggered by onchange event for previous select and populates the options for next select but on dropdown for 2nd select thisplays the previous options before it is repopulated by the javascript is there a workaround or event that can sequence execution of javascript and then selection of next control is there any event that can be triggered when a select option is selected and before control leaves the select element is there a handle for next and previous links for select dropdown option thisplay,"['javascript', 'iphone', 'html']" +91195,clear button on uitextview how can add a clear button cross inside a circle for text view like in text field,"['ios', 'objective-c', 'iphone']" +91214,why keep code behind clean and do everything in xaml what is the benefit of keeping code behind cleanmany times i come across posts here about someone trying to do the equivalent in xaml instead of code behind their only reason being they want to keep their code behind clean correct me if i am wrong but is not the case that xaml is compiled too into baml then at runtime has to be parsed into code anywayxaml can potentially have more runtime bugs as they will not be picked up by the compiler at compile time from incorrect spellings these bugs are also harder to debugthere already is code behind like it or not initializecomponent has to be run and the gics file it is in contains a bunch of code though it may be hiddenis it purely psychological i suspect it is developers who come from a web background and like markup as opposed to codeedit i do not propose code behind instead of xaml use both i prefer to do my binding in xaml too i am just against making every effort to avoid writing code behind esp in a wpf app it should be a fusion of both to get the most out of it,"['c#', '.net']" +91219,what is wrong with this mysql query it is 1230am and i have been coding for 9 hours straight i really need to get this project done but mysql is messing with my deadline could you examine this snippet for me and see if you can find out what is wrongphpmysql queryq thisdbqueryselect from bans where ipipkeeps returning the following errormysql error oct 6th 2010 1131pm cdt you have an error in your sql syntax check the manual that corresponds to your mysql server version for the right syntax to use near from bans where ip2065390231 at line 1 1064i do not see anything wrong with the query i have even tried different methods of including the variable ip but with no availeditjust to add in here the ip column in my database is a varchar255edit 2here is the whole affected code keep in mind that this is all in a class if i am missing something let me knowline from another functionifthisisbanned serverremote addrtrue return json encodearrayerroryou are banned from this shoutbox affected functionfunction isbannedip q thisdbqueryselect from bans where ipip num thisdbaffected rows ifnum0 row thisdbfetch arrayq ifrowexpires time rowexpires 0 thisunbanuseripinternal return false return true return falseunbanuser functionfunction unbanuseriptbox q thisdbqueryselect from bans where ipip num thisdbaffected rows ifnum0 q thisdbquerydelete from bans where ipip return tbox json encodearraystatusremoved true else return tbox json encodearrayerrorunable to locate the user true,"['php', 'mysql']" +91222,c how to get first char of a string can the first char of a string be retrieved by doing the followingmystringtochararray0,['c#'] +91232,should i expose actions instead of events while working with wf 40 i noticed that the workflowapplication class exposes action properties aborted complete etc instead of eventsis there a specific reason when should i prefer action properties instead of eventsthank you,['c#'] +91236,channels for java java ee c aspnet and soa what are the freenode irc channels for java java ee c aspnet and soa,"['c#', 'java', 'asp.net']" +91238,search for a word in a string if i am looking for a particular word inside a string for example in the string how are you i am looking for are would a regular indexof work faster and better or a regex matchstring teststr how are youstring lookup aremethod1if teststrindexoflookup 1 systemoutprintlnfoundormethod 2if teststrmatchlookup systemoutprintlnfoundwhich of the two methods above is a better way of looking for a string inside another string or is there a much better alternativeivard,['java'] +91255,how to clear contents of a jtable i have a jtable and it is got a table model defined like thisjavaxswingtabletablemodel datamodel new javaxswingtabledefaulttablemodeldata columnstblcompoundssetmodeldatamodeldoes anyone know how i can clear its contents just so it returns to an empty table,['java'] +91259,how can i make rails 3 localize my date formats i am working on a rails 3 project where there is place for date input within a form the text field with the date uses a date picker so there is no concern about the date being entered in a wrong format however the date is being thisplayed in the db format eg 20100121note this is specifically in form fields eg ftext field publish date which should automatically use default format and should not need to be provided with a valuei have tried adding in a customized locale which has the following date configurationdate formats use the strftime parameters for formats when no format has been given it uses default you can provide other formats here if you like default dmy short b d long b d yand then setting my locale to this configi18ndefault locale enau however this does not seem to take and its becoming quite frustratingthe app will eventually support a number of locales so setting up an initializer to override the date formats at application startup is not really suitable and i know that this should work i am guessing i have missed something herethe locale file is configlocalesenauyml and in my applicationrb i am including configi18nload path dirrailsrootjoinconfig locales ymlto sconfigi18ndefault locale enauin my applicationrb file,['ruby-on-rails'] +91277,importing ant buildxml in eclipse i have an android project that uses ant to build is it possible to import this ant project in eclipse ideupdate there is an option to create project using ant buildxml in eclipse filenewprojectjavajava project from existing ant buildfile and if the buildxml file is selected it show error specified buildfile does not contain a javac taski guess javac is declared in this tasktaskdef namesetupclassnamecomandroidantsetuptaskclasspathrefandroidantlibs,"['java', 'android']" +91282,are there any multipartformdata parser in c no asp i am just trying to write a multipart parser but things getting complicated and want to ask if anyone knows of a ready parser in c just to make clear i am writing my own tiny http server and need to pars multipart formdata toothanks in advancegohlool,['c#'] +91287,closing files properly opened with urllib2urlopen i have following code in a python script try send the query request sf urllib2urlopensearch query search soup beautifulsoupbeautifulstonesoupsfread sfclose except exception err printcould not get programme information printstrerr returni am concerned because if i encounter an error on sfread then sfclsoe is not calledi tried putting sfclose in a finally block but if there is an exception on urlopen then there is no file to close and i encounter an exception in the finally blockso then i tried try with urllib2urlopensearch query as sf search soup beautifulsoupbeautifulstonesoupsfread except exception err printcould not get programme information printstrerr returnbut this raised a invalid syntax error on the with line how can i best handle this i feel stupidas commenters have pointed out i am using pys60 which is python 254,['python'] +91304,c copy a file to another location with a different name if certain conditions are met i want to copy a file from one directory to another without deleting the original file i also want to set the name of the new file to a particular value i am using c and was using fileinfo class while it does have copyto method it does not give me the option to set the file name and the moveto method while allowing me to rename the file deletes the file in the original locationwhat is the best way to go about this,['c#'] +91309,can a php object instance know its name if i have code like thisclass person age height more stuff about the person function about return can i get the persons name john new personpeter new personprint johnabout print johnprint peterabout print peteris it possible to print the persons name stored as the variable name from the methodas it is not standard procedure i am guessing it is a bad ideai have looked it up and i cannot find anything about it,['php'] +91352,why does iis7 take a long time it looks likes if i do not visit my low traffic site for a day it takes a long time for the first page to load i believe it is probably because iis7 shuts down the application when it receives no requests for a certain length of time how can i stop this from happening i have a dedicated server so i have all the access required to change things in iis,['asp.net'] +91369,javascript recursive anonymous function lets say i have a basic recursive functionfunction recurdata data data1 var nothing function recurdata nothinghow could i do this if i have an anonymous function such asfunctiondata data data1 var nothing function something here that calls the function nothingi would like a way to call the function that called this function i have seen scripts somewhere i cannot remember where that can tell you the name of a function called but i cannot recall any of that information right now,['javascript'] +91376,picking up zf2 is it worth it now i have been a web developer for the past 8 years although i would only consider the second half of that time as real experiencein the past year i have done a couple of zend framework based business applications and i have been able to get comfortable with itnow i have been offered a position for leading a startup on the technical side i am pretty excited as i am given freedom to make crucial decisions and am encourage to use new technologies to make our product cutting edgeso my question to you more experienced guys are is it worth picking up zf2 will the transition of learning the new ways be easy how much does the coding style change can one start with the current available version and rely that the future releases will be compatible are the benefits of zf2 vs 1 great enough to justify investing my time into adopting when faced with a job such as mine are there more important questions i should be askingthanks all advice greatly appreciated update zend framework 2 stable released,['php'] +91382,saving geotag info with photo on ios41 i am having major issues trying to save a photo to camera roll with geotag info on ios41 i am using following alassetslibrary api voidwriteimagedatatosavedphotosalbumnsdata imagedata metadatansdictionary metadata completionblockalassetslibrarywriteimagecompletionblockcompletionblocki have the gps coordinates that i wish to save with the photo as an input unfortunately there is no documentation or sample code that describes how to form the metadata nsdictionary that encapsulates the gps coordinates can somebody post a sample code that is known to work i have also tried using iphone exif library to save geo info in imagedata rather than using metadata but unfortunately iphone exif library is crashing any help is greatly appreciated,['iphone'] +91388,splash screen does not return focus to main form i everyone i currently have a problem with my focus when using a splash screen i am using vs2008 with net framework 20 also i have linked my project with the visualbasicdll since i use the applicationservices to manage my single instance app and splash screenhere is a code snippet simplified of what i tried debuggingnamespace myproject public class bootstrap summary main entry point of the application it creates a default configuration bean and then creates and show the mdi container summary stathread static void mainstring args creates a new app that manages the single instance background work applicationenablevisualstyles applicationsetcompatibletextrenderingdefaultfalse app myapp new app myapprunargs public class app windowsformsapplicationbase public app base make this a singleinstance application thisissingleinstance true thisenablevisualstyles true there are some other things available in the vb application model for instance the shutdown style thisshutdownstyle microsoftvisualbasicapplicationservicesshutdownmodeaftermainformcloses add startupnextinstance handler thisstartupnextinstance new startupnextinstanceeventhandlerthissiapp startupnextinstance protected override void oncreatesplashscreen thissplashscreen new mymainform thissplashscreenstartposition formstartpositioncenterscreen protected override void oncreatemainform do your initialization here systemthreadingthreadsleep50 test then create the main form the splash screen will automatically close thismainform new form1 summary this is called for additional instances the application model will call this function and terminate the additional instance when this returns summary param nameeventargsparam protected void siapp startupnextinstanceobject sender startupnextinstanceeventargs eventargs copy the arguments to a string array string args new stringeventargscommandlinecount eventargscommandlinecopytoargs 0 create an argument array for the invoke method object parameters new object2 parameters0 thismainform parameters1 args need to use invoke to bc this is being called from another thread thismainforminvokenew mymainformprocessparametersdelegate mymainformthismainformprocessparameters parameters now what happens is that when i start the application the splash screen shows as expected but when it is destroyed it does not return the focus to the main form form1 in the test the mainform simply flashes orange in the taskbar if i launch the application from the ide vs2008 focus works just fine i am using xp pro also the main form is not on top of every other windows if i comment out the oncreatesplashscreen method the application gets focus normallyto test normal execution i am using the vs command prompt to launch my application i am using the release version of my projectany ideasediti also handle the startupnextinstance event to send my commandline arguments to my main form for test purposes it was removed hereedit added a bit more code now you have the full extent of my bootstrap,['c#'] +91436,jquery hide title attribute but not remove it i have seen that most people will do it with this solution that on mouse over we will grab the value in the title attribute then remove its value while on mouse out well put it back onthisattrtitle orthisremoveattrtitle i want to know is it possible just hide the tooltip from appearing than removing the title attributethanks,['jquery'] +91450,sql select return default value if null database ms sql 2008select listingtitle listingmls picturespictureth picturespicture listingid from listing inner join pictures on listingid pictureslistingidwhere picturesid select minid from pictures where listingid listingidthe issue is i have several listings without a picture and because of this sql script they do not show up how can i get them to show upmaybe give the picturespicture column a value of defaultjpg if the value is null i am pretty lost on this so if someone could help that would be amazing sorry if i am asking the question poorly as well i dont understand how to ask really what i need it to do but ask for more details and i will post themeach listing can have as many pictures as the user wants i need this script to thisplay a listing even if it does not have a picturephase 2thank you all so far i am learning some new commands i never even knew existed the issue now is its returning a row for each picture a listing has but the default image is working greatselect listingtitle listingmls coalescepicturespictureth default thjpg as pictureth coalescepicturespicture defaultjpg as picture listingid from listing leftouter join pictures on listingid pictureslistingidhow can i get it so it only returns 1 row per listingid,['sql'] +91451,find position of i am trying to find the position of test3 in jquery can someone lead me down the right path pleasei need jquery to thisplay 5ul idnumeric clasortable boxier stylemarginright 1emlitest7lilitest2lilitest6lilitest5lilitest3lilitest8liulthank you,['jquery'] +91478,java implementation of a jvm some time ago i found the mjvm project sadly this project has been abandoned by it author i asked igor via emaili wonder if there is a continued open source project of a full implementation of a jvm in java like this oneby full i mean not only to emulate mobile devices,['java'] +91485,how can i change the name of a windows service i have a windows service application developed in c the same service needs to be run with different config files to run on these on the same machine i would need to change the name of the service i can create multiple copies of the solution but not sure how to change the names of the servicesthanks,['c#'] +91512,c const member function that returns a const pointer but what type of const is the returned pointer i apologize if this has been asked but how do i create a member function in c that returns a pointer in the following scenerios1 the returned pointer is constant but the junk inside can be modified2 the junk inside is constant but the returned pointer can be modified3 neither the junk nor the pointer can be modified is it like soint const func constconst int func constconst int const func constall of the tutorials i have read do not cover this thistinctionside noteif my method is declared const then the tutorials say that i am stating that i would not modify the parameters but this is not clear enough for me in the case when a parameter is a pointer do my parameters need to be likea void funcconst int const x constb void funcconst int x constc void funcconst int const x const,['c++'] +91514,how to configure an extradifferent migrations folder a colleague and i are working in different projects that share some models so we are sharing the models through a git submoduleadditionally wed like to be able to also share migrationsin this way my colleagues migrations would be in the folder dbmigrateother db of my projecthow can i configure rails migrations to also run the migrations in this extra folder,"['ruby-on-rails', 'ruby']" +91546,when is malloc necessary in c i think all mallocsizeofstructure can be replaced this waycharsizeofstructurethen when is malloc necessary,['c'] +91547,how to approach debugging a huge not so familiar code base seldom during working on large scale projects suddenly you are moved on to a project which is already in maintainance phaseyou end up with having a huge code cc code base on your hands with not much doccumentation about the designthe last person who could give you some knowledge transfer about the code has left the company already and to add to your horrors there is not enough time to get acquainted with the code and develop an understanding of the overall modulesin this scenario when you are expected to fix bugscore dumpsfunctionalityperformance problems etc on the modules what is the approach that you will take so the question is what are your usual steps for debugging a not so familiar cc code base when trying to fix a bugedit enviornment is linux but code is ported on windows too so suggestions for both will be helpful,"['c++', 'c']" +91549,what is the difference between athisa athisa and athisa what is the difference between these three formsthisthisthis,"['javascript', 'jquery']" +91566,problems with div vertical scrollbars on ipad when a user perform a search on my website i want to show the result in a small div with vertical scrollbars instead of that the user need to scroll the full page that works perfect in all browsers but i get problems on the ipad i can see that the search result does not fit into the div but no scroll bar is showing up on the ipad also when i try to scroll inside the div the full page is scrolled instead is there a solution to get this workinghtml and cssdiv clasearchresult here i show the search resultdivdivsearchresult height 540px overflow mozscrollbarsvertical overflowy scroll,"['css', 'html']" +91579,jquery regex replace from select text i have some text i fetch inside here but only want the currency how can i get rid of the other valuesi tried this but did not have any luckvar symbol divprice h5 divnumtextreplaced heres the example html the selector i am using works fine just not the replacediv classprice h5 classbiguns div classnum a1228 div lowest price per night h5 div,['jquery'] +91588,select cells randomly from numpy array without replacement i am writing some modelling routines in numpy that need to select cells randomly from a numpy array and do some processing on them all cells must be selected without replacement as in once a cell has been selected it cannot be selected again but all cells must be selected by the endi am transitioning from idl where i can find a nice way to do this but i assume that numpy has a nice way to do this too what would you suggestupdate as mentioned in my comment below i should have stated that i am trying to do this on 2d arrays and therefore get a set of 2d indices back sorry,['python'] +91601,is it possible to use httpbrowsercapabilities from a c console application i need to parse useragent strings from a console app and this seems like a simple way to do it but i obviously do not have an httprequest object and cannot seem to make a fake one with a useragent header i get platform not supported exception is there any way to do this or should i start exploring other alternatives to user agent parsing,['c#'] +91609,how to thisplay an image on a mkoverlayview update images who are projected on the mkmapview using a mkoverlayview use the mercator projection while the image that i use as input data uses a wgs84 projection is there a way to convert the input image to the right projection wgs84 mercator without tiling the image up and can it done on the fly normally you could convert a image to right projection using the program gdal2tilesthe input data however changes every fifteen minutes so the image has to be converted every fifteen minutes so the conversion has to be done on the fly i also want the tiling to be done by mapkit and not by myself using gdal2tiles or the gdal framework update endi am currently working on a project which thisplays a rainfall radar over some part of the world the radar image is provided by eumetsat they offer a kml file which can be loaded into google earth or google maps if i load the kml file in google maps it thisplays perfectly but if i draw the image using a mkoverlayview on a mkmapview the image is slightly offor example on the left side google maps and on the right side the same image is thisplayed at a mkmapviewthe surface that the image covers can be viewed on google maps the satellite that is used for the image is the meteosat 0 degree satellitethe surface that both images cover is of the same size this is the latlonbox from the kml file it specifies where the top bottom right and left sides of a bounding box for the ground overlay are aligned latlonbox idge met0d vpmpelatlonbox north574922north south574922south east574922east west574922west rotation0rotation latlonboxi create a new custom mkoverlay object called radaroverlay with these parametersradaroverlay alloc initwithimagedataselfcurrentradardata objectatindex0 valueforkeyimage withlowerleftcoordinatecllocationcoordinate2dmake574922 574922 withupperrightcoordinatecllocationcoordinate2dmake574922 574922the implementation of the custom mkoverlay object radaroverlay id initwithimagedatansdata imagedata withlowerleftcoordinatecllocationcoordinate2dlowerleftcoordinate withupperrightcoordinatecllocationcoordinate2dupperrightcoordinate selfradardata imagedata mkmappoint lowerleft mkmappointforcoordinatelowerleftcoordinate mkmappoint upperright mkmappointforcoordinateupperrightcoordinate maprect mkmaprectmakelowerleftx upperrighty upperrightx lowerleftx lowerlefty upperrighty return self cllocationcoordinate2dcoordinate return mkcoordinateformappointmkmappointmakemkmaprectgetmidxmaprect mkmaprectgetmidymaprect mkmaprectboundingmaprect return maprectthe implementation of the custom mkoverlayview radaroverlayview voiddrawmaprectmkmaprectmaprect zoomscalemkzoomscalezoomscale incontextcgcontextrefcontext radaroverlay radaroverlay radaroverlay selfoverlay uiimage image uiimage alloc initwithdataradaroverlayradardata cgimageref imagereference imagecgimage mkmaprect themaprect selfoverlay boundingmaprect cgrect therect self rectformaprectthemaprect cgrect cliprect self rectformaprectmaprect nsuserdefaults preferences nsuserdefaults standarduserdefaults cgcontextsetalphacontext preferences floatforkeyradartransparency cgcontextaddrectcontext cliprect cgcontextclipcontext cgcontextdrawimagecontext therect imagereference image release when i download the image i flip the image so it can be easily drawn in the mkoverlayviewsize t width cgimagegetwidthimagereference selfscalefactorsize t height cgimagegetheightimagereference selfscalefactor calculate colorspace for the specified imagecgcolorspaceref imagecolorspace cgimagegetcolorspaceimagereference allocate and clear memory for the data of the imageunsigned char imagedata unsigned char mallocheight width 4memsetimagedata 0 height width 4 define the rect for the imagecgrect imagerectifimageimageorientationuiimageorientationup imageimageorientationuiimageorientationdown imagerect cgrectmake0 0 width height else imagerect cgrectmake0 0 height width create the imagecontext by defining the colorspace and the address of the location to store the datacgcontextref imagecontext cgbitmapcontextcreateimagedata width height 8 width 4 imagecolorspace kcgimagealphapremultipliedlastcgcontextsavegstateimagecontext scale the image to the opposite orientation so it can be easylier drawn with cgcontectdrawimagecgcontexttranslatectmimagecontext 0 heightcgcontextscalectmimagecontext 10 10ifimageimageorientationuiimageorientationleft cgcontextrotatectmimagecontext m pi 2 cgcontexttranslatectmimagecontext 0 widthelse ifimageimageorientationuiimageorientationright cgcontextrotatectmimagecontext m pi 2 cgcontexttranslatectmimagecontext height 0 else ifimageimageorientationuiimageorientationdown cgcontexttranslatectmimagecontext width height cgcontextrotatectmimagecontext m pi draw the image in the contextcgcontextdrawimageimagecontext imagerect imagereferencecgcontextrestoregstateimagecontextafter i flipped the image i manipulate it and then store it in memory as a nsdata objectit looks like the image got stretched but it looks allright at the center of the image which is at the equator,"['iphone', 'objective-c']" +91611,django proxy model and foreignkey how to make entrycategory to be instance of categoryproxy see code for detailsclass categorymodelsmodel passclass entrymodelsmodel category modelsforeignkeycategoryclass entryproxyentry class meta proxy trueclass categoryproxycategory class meta proxy trueentry entryproxyobjectsgetpk1entrycategory i want categoryproxy instance herecast from category to categoryproxy is ok too but i am not very familiar with orm internals to properly copy internal stateeditreason i added method to categoryproxy and want to use himentryproxyobjectsgetpk1categorymethod at category proxyedit 2currently i implemented it like thisentryproxy metaget field by namecategory0relto categoryproxybut it looks terrible,['python'] +91614,create 2d context without canvas i am currently looking for a way to create a canvas 2d rendering context without actually having a canvas element on the page i could dynamically create a canvas element and hide it but then again i do not want to show the image directly to the user anytime so there is no point of actually having a canvas element in the page so i am basicly looking for something that is similar tovar image new image but only for canvas 2d rendering context pseudo codevar context new 2dcontext is there functionality like this i was not able to find anything like it callingvar context new canvasrenderingcontext2d which is the name of the rendering context interface by html5 spec just gives me awkward errors in firefoxuncaught exception exception cannot convert wrappednative to function nsresult 0x80570d ns error xpc cant convert wn to fun location js frame httplocalhost top level line 25 data no,['javascript'] +91651,if div has content show div ok heres what i have it works fine but it looks for a word rather than content i just want it to show when there is any content documentreadyfunction if box3containsproductlength thirdshow i dont think you need the html for this it looks for product how do i make it just look for content 0div idfirst classtab div classtabtxt adetailsa divdivdiv classtab idsecond div classtabtxt ainspirationa divdivdiv classtab idthird stylethisplaynone div classtabtxt anotesa divdivdiv classboxholder div styleoverflow hidden thisplayblock classbox idbox1 div stylepadding 10px lineheight16px panelproductdescription div div div styleoverflow hidden thisplaynone classbox idbox2 div stylepadding 10px lineheight16px panelproductwarranty div div div styleoverflow hidden thisplaynone classbox idbox3 div stylepadding 10px lineheight16px panelupc div divdivits an interspire shopping cart so the panelupc calls in something inserted through the admin panel in this case if there is nothing it shows as blank space in the code viewing source in browser,"['jquery', 'html']" +91660,android how do i resetclear application preferences during unit testing i want to start with a consistent test environment so i need to resetclear my preferences heres the setup for test i have so far it is not reporting any errors and my tests pass but the preferences are not being clearedi am testing the mainmenu activity but i temporarily switch to the optionscreen activity which extends androids preferenceactivity class i do see the test correctly open the optionscreen during the run public class mytest extends activityinstrumentationtestcase2mainmenu override protected void setup throws exception supersetup instrumentation instrumentation getinstrumentation instrumentationactivitymonitor monitor instrumentationaddmonitoroptionscreenclassgetname null false startnewactivity see next paragraph for what this does probably mostly irrelevant activity getactivity sharedpreferences settings preferencemanagergetdefaultsharedpreferencesactivity settingseditclear settingseditcommit i am pretty sure this is not necessary but not harmful eitherstartnewactivity code intent intent new intentintentaction main intentsetflagsintentflag activity new task intentsetclassnameinstrumentationgettargetcontext optionscreenclassgetname instrumentationstartactivitysyncintent activity currentactivity getinstrumentation waitformonitorwithtimeoutmonitor 5 asserttruecurrentactivity nullthanks,['android'] +91665,python strtotime equivalent i am using this to convert date time strings to a unix timestampstrinttimemktimetimestrptimedated b y hms zhowever often the date structure is not the same so i keep getting the following error messagetime data did not match format datatue 26 may 2009 195820 0500 fmtd b y hms zdoes anyone know of any simply function to convert a string representation of a datetime to a unix timestamp in python i really do not want to have to open a process to call a php script to echo the timestamp everytime time in a loop,['python'] +91674,linq what is the quickest way to find out deferred execution or not what is the quickest way to find out which net framework linq methods eg ienumerable linq methods are implemented using deferred execution vs which are not implemented using deferred execution while coding many times i wonder if this one will be executed right way the only way to find out is go to msdn documentation to make sure would there be any quicker way any directory any list somewhere on the web any cheat sheet any other trick up your sleeve that you can share if yes please do so this will help many linq noobs like me to make fewer mistakes the only other option is to check documentation until one have used them enough to remember which is hard for me i tend not to remember anything which is documented somewhere and can be looked up d,"['c#', '.net']" +91712,explicitly exclude an html element from the tab order is there anyway to exclude an element from the tab order of a html formso if i have the followinginput typetext nameusernameinput typetext namepasswordinput typebutton nameforgotpasswordinput typesubmit namelogini am aware that i can use tabindex as 1234 but i do not want to have to number all the fields my application is dynamically creating the fieldsthanks jason,['html'] +91725,does const help the optimizer c possible duplicateconstants and compiler optimization in c let the holy wars begini have heard a number of differing opinions on the usefulness of const in c of course it has uses in member function declarations etc but how useful is it as a modifier on variables or rather constants does it indeed help the optimizer if the rest of the code is left the same,['c++'] +91734,how to load local json files in javascript i am writing a web app well actually it will eventually be an os x dashboard widget but i decided to prototype it first as a simple web page that needs to load some initializing data from a local json file my code looks like thisfunction loaddatos var xobj new xmlhttprequest xobjoverridemimetypeapplicationjson xobjopenget datosjson true xobjonreadystatechange function if xobjreadystate 4 var jsontexto xobjresponsetext processthedatajsontexto xobjsendnullthe function get called from an onload event in the html files body tag now from what i see when debugging the function gets executed but the onreadytstatechange event handler never gets calledwhat should i do i thought it was a bit odd to use a xmlhttprequest to access a local file but the new tutorials i have seen that deal with this issue seem to say that it should work the 99 of docs i have seen talk about how to load json from a remote server not from a local filei am testing using firefox 3610 but i have also tried with safari 4,['javascript'] +91773,aspnet mvc ninject single instance per request for multiple constructors im trying to implement an unit of work pattern by passing an unit of work instance into my repositoriesrelevant code from globalasaxpublic class sitemodule ninjectmodule public override void load bindiunitofworktosqlunitofwork inrequestscope withconstructorargumentconnectionstring configurationmanagerconnectionstringsentitiesconnectionstring bindiproductrepositorytoproductrepository bindicategoryrepositorytocategoryrepository repository constructorspublic class productrepository iunitofwork unitofwork public productrepositoryiunitofwork unitofwork thisunitofwork unitofwork public class categoryrepository iunitofwork unitofwork public categoryrepositoryiunitofwork unitofwork thisunitofwork unitofwork what i want is that a maximum of 1 instance of sqlunitofwork is created per request and is passed into my repositories via their respective constructorsis the inrequestscope method on the iunitofwork binding enough if not how can i achieve this,['asp.net'] +91784,check if a user has scrolled to the bottom i am making a pagination system sort of like facebook where the content loads when the user scrolls to the bottom i imagine the best way to do that is to find when the user is at the bottom of the page and run an ajax query to load more poststhe only problem is i do not know how to check if the user has scrolled to the bottom of the page with jquery any ideasi need to find a way to check when the user has scrolled to the bottom of the page with jquery,"['javascript', 'jquery']" +91785,is it possible to make realtime network games in javascript is it possible to make realtime network games using javascript i have seen flash do it but i am interested in making a multiplayer browserbased game that does not depend on any plugins i have read that it is impossible to keep ajax connections open for streaming communication and it is not feasible to make several new ajax connections per second to keep the client in sync with the server,['javascript'] +91787,can i share variables between different functions in php i will try to explain with an examplelet us say i have two different functions and one of them has a defined variable in the second function i do not wanna write the same variable again can i simply use the variable from the first function in the second one without redefining it in the second functionsomething likefunction a var my variablefunction b echo varsorry if this questions is a bit silly but i am still a beginner,['php'] +91788,greedy nongreedy allgreedy matching in c regex how can i get all the matches in the following example only abcd is matchedmatchcollection greedymatches regexmatchesabcd ab only ab is matchedmatchcollection lazymatches regexmatchesabcd ab how can i get all matches ab abc abcdthankspeterps i want to have the all matches in a generic manner the example above is just an example,['c#'] +91797,how can i use ioss standard red number badges within my app i know that it is trivial to add a red number badge to an apps icon on the home screen whats the best way to get a badge that looks like this within my app there are some classes i have found online that can do this such as mknumberbadgeview but none that i have found look completely right facebook for example implements red badges within the app perfectly as far as i can see did they just build their own badges by trial and error any suggestions would be appreciatedthanksluke,"['iphone', 'objective-c']" +91809,installing mysqldb for python 26 on osx i am trying to install mysqldb for python 26 as per these instructions database accesshtmwhen i get to this step python setuppy build i get the errorusersmacbookpromysqlpython123 user sudo python setuppy buildsh mysql config command not foundtraceback most recent call last file setuppy line 15 in metadata options get config file my crawlermysqlpython123setup posixpy line 43 in get config libs mysql configlibs r file my crawlermysqlpython123setup posixpy line 24 in mysql config raise environmenterrors not found mysql configpathenvironmenterror mysql config not foundi have mysql installed and added to my bashwhat am i doing wrong,"['python', 'mysql']" +91834,shared ptr magic mr lidstram and me had an argument mr lidstrams claim is that a construct shared ptrbase pnew derived does not require base to have a virtual destructorarmen tsirunyan really will the shared ptr clean up correctly could you please in this case demonstrate how that effect could be implementeddaniel lidstram the shared ptr uses its own destructor to delete the concrete instance this is known as raii within the c community my advice is that you learn all you can about raii it will make your c coding so much easier when you use raii in all situationsarmen tsirunyan i know about raii and i also know that eventually the shared ptr destructor may delete the stored px when pn reaches 0 but if px had static type pointer to base and dynamic type pointer to derived then unless base has a virtual destructor this will result in undefined behavior correct me if i am wrongdaniel lidstram the shared ptr knows the static type is concrete it knows this since i passed it in its constructor seems a bit like magic but i can assure you it is by design and extremely niceso judge us how is it possible if it is to implement shared ptr without requiring polymorphic classes to have virtual destructorthanks in advance,['c++'] +91836,print call stack in c or c is there any way to dump the call stack in a running process in c or c every time a certain function is called what i have in mind is something like thisvoid foo print stack trace foos body returnwhere print stack trace works similarly to caller in perlor something like thisint main void will print out debug info every time foo is called register stack trace functionfoo etcwhere register stack trace function puts some sort of internal breakpoint that will cause a stack trace to be printed whenever foo is calleddoes anything like this exist in some standard c libraryi am working on linux using gccbackgroundi have a test run that behaves differently based on some commandline switches that should not affect this behavior my code has a pseudorandom number generator that i assume is being called differently based on these switches i want to be able to run the test with each set of switches and see if the random number generator is called differently for each one,"['c++', 'c']" +91838,how to change the font size on a matplotlib plot how does one change the font size for all elements ticks labels title on a matplotlib ploti know how to change the tick label sizes this is done withimport matplotlib matplotlibrcxtick labelsize20 matplotlibrcytick labelsize20 but how does one change the rest,['python'] +91840,systemnetwebexception the request was aborted the request was cancelled i have a wcf service that has been giving me this error under load conditions and i cannot seem to recreate the error otherwise weve been trying to find a way around it for about a week now with no such luckthe error i see has two parts to itsystemservicemodelcommunicationexception an error the request was aborted the request was cancelled occurred while transmitting data over the http channelandsystemnetwebexception the request was aborted the request was cancelledi have seen many people suggest to thisable working with keep alive by overloading a method in the referencecs file and setting keepalive false however our client side is using a service reference in addition to web reference and this option does not exist anymoreanother option i have seen was to add a custom binding to the service instead of the basichttpbinding we are using now but that would bother backwards support of the webservice to those who have been using a webreference since custombinding is not soap enabledhas anyone dealt with this error before is there a way to thisable keep alive in wcf without affecting the server side is there anything other that keep alive that is known to cause this error,['.net'] +91843,no such file to load bcrypt ext via devise i am using database authentication in devisecurrent gem on rails 3 and i get the following error when trying to log in with usernamepasswordno such file to load bcrypt ext this error occurred while loading the following files bcrypt bcrypt exti have previously successfully installed bcryptruby212 gemany ideas i also tried giving bundler the git repo address and fetching the master but it does not solve the issue,['ruby-on-rails'] +91852,how to alter double by its smallest increment is something broken or i fail to understand what is happening static string getrealbinarydouble val long tmp doubledoubletolongbitsval stringbuilder sb new stringbuilder for long and 64 n 0 tmp 1 if tmp 1 0 sbinsert0 0 else sbinsert0 1 sbinsert0 insert2 insert16 append return sbtostringpublic static void mainstring argv for int j 3 j 0 double d j for int i 3 i 0 d doublemin value systemoutprintlnd getrealbinaryd with output201 0 0201 0 0201 0 0100 10 0100 10 0100 10 049e3240 0 0110e3230 0 01015e3230 0 011,['java'] +91853,core data with json this question is a follow up on this question i am using the json library found at my core data object model has a manytomany relationship to itself and as such has a set for its sub object in json the set is represented through an array of object ids nothing really exoticwhen i am calling setvaluesforkeyswithdictionary on the managed object with the object structure i get from parsing the json string i receive this exception terminating app due to uncaught exception nsinvalidargumentexception reason nsarraym minusset unrecognized selector sent to instance 0x6c7b440if someone can explain why i am all ears i also receive some exception from undefined key but this is understandablejson contains extra fields and totally manageablenow my question isam i missing something here because in the other question the person who answered and op did not report any of this problem i could patch it and handle the faulty operation by overriding setvaluesforkeyswithdictionary and passing when the key is a relationship but this makes the code a lot less generic which i quite like,['objective-c'] +91861,android sqlite database shared between activities what is the best way for sharing one sqlite db between several activities tables from db are shown in listview and also deletinginserting records is to be performed i heard smth about services but did not found example for my problem now i have sqliteopenhelper class for opening db i close db in onpause and open it in onresume but i cannot insert data to db from subactivity smth goes wrong,['android'] +91873,in php how do i extract multiple email addresses from a block of text and put them into an array i have a block of text from which i want to extract the valid email addresses and put them into an array so far i have string file get contentsexampletxt load text file contents matches array create array pattern azaz09 azaz09 azaz09 azaz09 regex for pattern of email address preg matchpattern string matches find matching patternhowever i am getting an array with only one address therefore i am guessing i need to cycle through this process somehow how do i do that,['php'] +91889,performance issue for vectorsize in a loop hi when having a vectorint varforint i0 i varsizei is the size function called each time or only once from the answers i guess i better use iterators or just have variable before the loop,['c++'] +91904,create hardware for iphone to connect with external device arduino hi i need to create a simple connector i think i may need to create an arduino board that will take data from the application and then transmit them to an external devicethere is a slider in the application which the user can adjust when adjusting the slider the application will just send in values from the application to the connection that i need to make which will connect to the external devicestep 1 how do i program the ipad application so that it will transmit to the connecterthere must be some api to achieve thisstep 2 what do i need to use to create the connecter a circuit board which will read the simple string data coming in and then transmit say an integer back out to the external device so that my iphone can communicate with iti really need help with this one ive never done this before but i need to get this done,"['iphone', 'objective-c']" +91926,what is the easiest method for verticalhorizontal centering of a div in the window given a div with known dimensions say width 300px height 200px what is the easiest method to place it in the middle of the screen both vertically and horizontally example herei am interested in latest firefox no need for ie hackscss only please no javascript,"['css', 'html']" +91934,when creating html emails should we use html head body tags in my email views i usually just do something likedl dtnamedt ddvaluedlshould i be doing it like thishtml headhead body dl dtnamedt ddvaluedd dl bodyhtmlin other words like i was marking up a standalone documenti guess i can safely assume any web based email client will strip it outwhat is the right way,['html'] +91948,is there a rails way to check which attributes have been updated in an observer i have an activityobserver which is observing tasks and has an after update callbacki want to test if a particular attribute has been modified in the updateis there a rails way to compare the attributes of the subject with what they were before the update or to check if they have changed,['ruby-on-rails'] +91961,java ee for beginners i am back from vacations and in my company there are new students that just started with their study my exercise is to show them a little bit of java ee they already know java basicsso my questions is whats the best knowledge to learn as a beginner infomation should not be too dry,['java'] +91982,explicit implementation of an interface using an automatic property is there any way to implement an interface explicitly using an automatic property for instance consider this codenamespace autoproperties interface imyinterface bool myboolonlyget get class myclass imyinterface static void main public bool myboolonlyget get private set line 1 bool imyinterfacemyboolonlyget get private set line 2 this code compiles however if you replace line 1 with line 2 it does not compile it is not that i need to get line 2 working i am just curious,['c#'] +91988,how to trim whitespace between characters how to remove whitespaces between characters in ctrim can be used to remove the empty spaces at the beginning of the string as well as at the end for example c sharp trim results c sharpbut how to make the string into csharp we can remove the space using a for or a for each loop along with a temporary variable but is there any built in method in cnet framework 35 to do this like trim,['c#'] +91990,getting the musical data of an ipodtrack how can i get the content rawsample data of an ipodtrack i have seen apps like ringtone designer and imovie which can do it but i have no idea which api they use or what they do i could imagine that imovie uses private apis but ringtone designer is a thirdparty app so it must be possible with the public apifunctions,"['iphone', 'objective-c']" +92002,ie9 https security is compromised by my greasemonkey script iave got a greasemonkeyforie script in ie9 thatas importing jquery but on secure pages it doesnat workiam gettingsec71 https security is compromised by the code that fails isvar script documentcreateelementscriptscriptsetattributesrc how can i make this work the script doesnat cause a problem in firefox,"['javascript', 'jquery']" +92005,sql error stating invalid column name when i have verification if it exists why there is staging script which creates new column document definition id stages it with values of message type id 5 and then removes column message type idfirst time everything run ok but when i run script second time i am getting this errorinvalid column name message type idit makes no sense since i have verification if that column existsif existsselect from information schemacolumns where column name message type id and table name document queuebegin update document queue set document definition id message type id 5 error here but condition is not metwhy,['sql'] +92014,why can you not invoke extension methods directly can someone explain to me why in the following the 3rd invocation of dosomething is invalid error message is the name dosomething does not exist in the current context public class a public class b a public void whynotdirect var a new a adosomething ok thisdosomething ok dosomething why not public static class a ext public static void dosomethingthis a a consolewritelineok,['c#'] +92023,creating facebook event for specific page with fb graph api i need synchronize events from my cms to facebook specific page i am trying to create an event for my created page but still have no result i can simply create events related to user but not to page code uses facebook phpsdkpage id 31337page facebookapipage idevent data array name event datehms start time time 6060 end time time 60602 owner pagepost facebookapipage idevents post event dataafter executing this snippet event is created but as i have said before it belongs to user though owner in given data is page my app has manage pages create event and publish stream permissions what i am missingsolutionat old rest api documentation i have found that new graph api still needs parameter page id so variable event data should be like belowevent data array name event datehms start time time 6060 end time time 60602 page id pageid,['php'] +92025,css margins overlap problem please see my code i do not understand why the margins of these divs are overlappingdiv classalignright div clasocial a href classtwita a href classfba div social div classcontact get in touch span44 10012 12345span div contact div clasearch form methodpost action input typetext value names gtbfieldid28 form div search divthe css alignright float rightheader social margintop 50pxheader social a thisplay inlineblockheader social fb width 64px height 1px paddingtop 60px overflow hiddenheader social twit width 64px height 1px paddingtop 60px overflow hiddenheader contact margin 20px 70px 20px 0 fontsize 14px fontweight boldheader contact span color fheader search margin 10px 0 0,['css'] +92057,android checkboxpreference default value i have the following xml code for my checkboxpreferencecheckboxpreference androidkeypref boot startup androidtitleauto start androiddefaultvaluetrue but when i retrieve the preference in code the value is falsesharedpreferences preferencemanagergetdefaultsharedpreferencesthisboolean autostart sharedpreferencesgetbooleanpref boot startup truemy autostart variable returns falseis there a specific reason for this am i missing a step to set the default value to true,['android'] +92063,googles protocol buffers in c we are looking at using googles protocol buffers to handle serialization between a c application and a c application via networkingmy question is i have found a couple of different verisions for c both look pretty good however does anyone know what is different if anything between the twoprotobufnetjskeet dotnetprotobufs,"['c#', 'c++']" +92070,ruby class types and case statements what is the difference betweencase itemclasswhen myclass do something herewhen array do something different herewhen string do a third thingendand case itemclasswhen myclassclass do something herewhen arrayclass do something different herewhen stringclass do a third thingendfor some reason the first one of these works sometimes and the second does not and other times the second one works and the first one does not why which one is the proper way to do it,['ruby'] +92082,how should i store uiimages within my core data database i am developing an application which demands around 100 images or maybe more to be preinserted into the core data database along with other related informationnow i can easily add other data by just writing a few lines of code but for uiimages i am unsure how to do it without writing a lot of code i was wondering is there anyway to do this easily or if there is not whats the best way to achieve this with the least amount of effortalso is it okay to store images in a core data database or should we only only save the addresses of images on the local file system,"['iphone', 'objective-c', 'ios']" +92104,lnk2022 error when using clr i am having a problem linking a c project in vs2008 when using the clr compile option i am getting the following build errorsclass1obj error lnk2022 metadata operation failed 8013118d inconsistent layout information in duplicated types propsheetpagea 0x02046fclass1obj error lnk2022 metadata operation failed 8013118d inconsistent layout information in duplicated types propsheetpagew 0x020473class2obj error lnk2022 metadata operation failed 8013118d inconsistent layout information in duplicated types propsheetpagea 0x02046fclass2obj error lnk2022 metadata operation failed 8013118d inconsistent layout information in duplicated types propsheetpagew 0x020473class3obj error lnk2022 metadata operation failed 8013118d inconsistent layout information in duplicated types propsheetpagea 0x02046eclass3obj error lnk2022 metadata operation failed 8013118d inconsistent layout information in duplicated types propsheetpagew 0x020472class4obj error lnk2022 metadata operation failed 8013118d inconsistent layout information in duplicated types propsheetpagea 0x02046eclass4obj error lnk2022 metadata operation failed 8013118d inconsistent layout information in duplicated types propsheetpagew 0x020472class5obj error lnk2022 metadata operation failed 8013118d inconsistent layout information in duplicated types propsheetpagea 0x02046eclass5obj error lnk2022 metadata operation failed 8013118d inconsistent layout information in duplicated types propsheetpagew 0x020472class6obj error lnk2022 metadata operation failed 8013118d inconsistent layout information in duplicated types propsheetpagea 0x02046eclass6obj error lnk2022 metadata operation failed 8013118d inconsistent layout information in duplicated types propsheetpagew 0x020472link fatal error lnk1255 link failed because of metadata errorsi have no idea what propsheetpagea and propsheetpagew are referring to i checked online to see microsofts description of the error but am at a loss as to what it meansto resolve this problem add unique identifiers when you use managed extensions for c so that you avoid using anonymous structures as global variablesmicrosoft has confirmed that this is a bug in the microsoft products that are listed at the beginning of this article this bug was corrected in microsoft visual c net 2003any ideas would be greatly appreciatededitafter doing a ildasm on class1obj i extracted two messages typedef 1134 02046f typdefname propsheetpagea 02046f flags notpublic sequentiallayout class sealed ansiclass beforefieldinit 00100108 extends 010b typeref systemvaluetype layout packing0 size56 customattribute 1 0c0012a0 customattribute type 0a03 customattributename microsoftvisualcmiscellaneousbitsattribute instance void ctorint32 length 8 value 01 00 41 00 00 00 00 00 a ctor args 65 customattribute 2 0c0012a1 customattribute type 0a01 customattributename microsoftvisualcdebuginfoinpdbattribute instance void ctor length 4 value 01 00 00 00 ctor args customattribute 3 0c0012a2 customattribute type 0a04 customattributename systemruntimecompilerservicesnativecppclassattribute instance void ctor length 4 value 01 00 00 00 ctor args typedef 1138 020473 typdefname propsheetpagew 020473 flags notpublic sequentiallayout class sealed ansiclass beforefieldinit 00100108 extends 010b typeref systemvaluetype layout packing0 size56 customattribute 1 0c0012b0 customattribute type 0a04 customattributename systemruntimecompilerservicesnativecppclassattribute instance void ctor length 4 value 01 00 00 00 ctor args customattribute 2 0c0012b1 customattribute type 0a01 customattributename microsoftvisualcdebuginfoinpdbattribute instance void ctor length 4 value 01 00 00 00 ctor args customattribute 3 0c0012b2 customattribute type 0a03 customattributename microsoftvisualcmiscellaneousbitsattribute instance void ctorint32 length 8 value 01 00 41 00 00 00 00 00 a ctor args 65i am not sure what all this means but it looks as if the second entry is identical to the first with the exception of the attributes being defined backwards,['c++'] +92105,how to manage custom fonts in web application systemdrawing i have an application that writes text onto images using systemdrawing c i am using specific fonts to do this since i cannot rely on my shared hosting servers to have all the custom fonts i may need and since the list of fonts is likely to grow how can i manage the fonts used for my application could i include ttf files in my project and reference them somehow what about a sql database containing fonts,['c#'] +92113,client side includes vs server side includes we have an html page with multiple div blocks we want to separate these divs into multiple files and then combine them all together into a single file is it best to use server side includes jsp in our case or client side includes note that were using jquery not sure if jquery has a clever way to do the includes,"['javascript', 'jquery', 'html']" +92132,dto shape flat complexnested or a mixture of both i have an mvc2 ntier application dal domain service mvc web using a d approach domain driven design having a domain model with repositories my service layer uses a requestresponse pattern in which the request and response objects contain dtos data transfer objects to marshal data from one layer to the next and the mapping is done via help from automapper my question is this what shape should a dto typically take can it have nestedcomplex dtos as well or should it strictly be a flat projection or possibly a mixture of both also what are the main reasons for having a flat dto vs a more complexnested dtofor instance suppose i had a domain such as the followingpublic class employee public string firstname get set public string lastname get set public company company get set public class company public string name get set public string address get set public string city get set public string state get set there are three different ways i have thought of modeling the response objectoption 1 the dryest optionpublic class getemployeeresponse public class employeedto get set contains a companydto propertyfrom the research i have done it would be inappropriate for a dto to take a similar shape as the domain objects as demonstrated aboveoption 2 a flattened projection of the domain antidrypublic class getemployeeresponse public string firstname get set public string lastname get set public string companyname get set public string companyaddress get set public string companycity get set public string companystate get set this is more simple like a dto apparently should be but ultimately makes for more dtosoption 3 a mixture of bothpublic class getemployeeresponse public employeedto employee get set public companydto company get set this allows for the code to be a little bit more dry reusable and manageable and does not expose my domain structure to the end user the other main benefit is that other responses like getcompanyresponse could simply return companydto without having to make a copy of all those properties similar to option 2 what do you think which option of these if any have you taken andor have worked for you if these requestresponses later get exposed as wcf service methods does your answer change,['c#'] +92147,handling bugs raised by customers in tfs i am part of a team developing aspnet applications using scrum we currently use tfs for almost all aspects of our project management source control testing and bug trackinghowever there is a gap when it comes to customerraised bugs bugs found internally are easy to add to tfs allowing us to link changesets to actual bugs when bugs are found by customers though we find ourselves using an externallyfacing bug tracking system jira at the moment and manually entering the same bug in tfs this results in duplication of effort and often a loss of detail in one or both systemsi have been unable to find any integration tools between jira or other bug trackers and tfs or a way of allowing customers to create tfs bugs directlyhow do you handle this are there any products or plugins that help this process,['.net'] +92156,how to pass 2d array matrix in a function in c i need to do this to persist operations on the matrix as well does that mean that it needs to be passed by reference will this sufficevoid operate on matrixchar matrix20,['c'] +92162,strange javascript idiom what does xyztestfunctionxyz do john resig wrote a nifty class function swanky i am trying to figure out what is going on and have pretty much everything figured out except a single linefntest xyztestfunction xyz b superb a couple things immediately jump to mind first xyz is never initialized as a variable so why then does this work second why is it testing xyz against something that is not returning anything no return statement unless there is some nifty properties of javascript i am unaware of which is possible i fancy myself rather good at js and can interpret most the code i come across it does not however mean i am eve on the same mt everest sized mountain that john resig calls homefor those curious here is the full unedited code from john resigs site john resig simple javascript inheritancefunction var initializing false fntest xyztestfunctionxyz b superb the base class implementation does nothing thisclass function create a new class that inherits from this class classextend functionprop var super thisprototype instantiate a base class but only create the instance do not run the init constructor initializing true var prototype new this initializing false copy the properties over onto the new prototype for var name in prop check if were overwriting an existing function prototypename typeof propname function typeof supername function fntesttestpropname functionname fn return function var tmp this super add a new super method that is the same method but on the superclass this super supername the method only need to be bound temporarily so we remove it when were done executing var ret fnapplythis arguments this super tmp return ret name propname propname the dummy class constructor function class all construction is actually done in the init method if initializing thisinit thisinitapplythis arguments populate our constructed prototype object classprototype prototype enforce the constructor to be what we expect classconstructor class and make this class extendable classextend argumentscallee return class,['javascript'] +92167,rails belongs to many models i did find some questions on so about rails associations that are somewhat like my question but for the life of me i cannot seem to understand how to use belongs to multiple modelsheres the table structure i intend to haveuser idpost id user id foreign key a post belongs to a user aka who created this postcomment id user id foreign key a comment belongs to a user aka who made this comment post id foreign key a comment belongs to a post aka what post this comment is forand the associationsuser has many posts has many commentspost belongs to user has many commentscomment belongs to user belongs to postis this the correct approach,['ruby-on-rails'] +92193,applying a function all values in an array jobs is an array retrieved from a db query print rjobs showsarray id 131 title bla baseline lorem ipsum description ullilist 1lililist 2liul eventid 1008array id 132 title bla 2 baseline lorem ipsum lorem ipsum description ullilist 1lililist 2liul eventid 1009etc id like to run utf8 encode on all values of these arrays i am not sure if i should use array map array walk recursive the output should not alter the names of the array keys so that i do not need to change anything in my template soh1jtitleh1should still work albeit utf8 encodededit i am trying the following no luckfunction fix charskey value return utf8 encodevaluearray walk recursivejobs fix chars,['php'] +92195,directorycontentsatpath deprecated ios 4 i am using directorycontentsatpath which is deprecated in ios 4 what to use instead thisthanks,['iphone'] +92202,fork concept in c since c supports threading is there any way to implement fork concept in cthanks in advance,"['c#', '.net']" +92203,how to get an id without join in doctrine2 i have entity like this tablenametable entity class table columntypeinteger id generatedvaluestrategyidentity private id manytoonetargetentityentitiesusers joincolumnnameuserid referencedcolumnnameid private user columntypestring private textif i do qgetquerygetsingleresultgetusergetuseriddoctrine generate query likeselect from table t inner join users you on uid tuserid where id 100but if i dont need table users how to get an useridin pure sql i can justselect from table where id 100and get userid without join users table,['php'] +92219,get all table names of a particular database by sql query i am working on application which can deal with multiple database servers like mysql and ms sql serveri want to get tables names of a particular database using a general query which should suitable for all database types i have tried followingselect table name from information schematables where table typebase tablebut it is giving table names of all databases of a particular server but i want to get tables names of selected database only how can i restrict this query to get tables of a particular database,['sql'] +92224,android how can i stop an infinite animation applied on an imageview i have an imageview on which i have applied a rotate animation since i want the rotation to go on continuously i gave the repeatcount as infinite in my rotatexmlandroidrepeatcountinfinitein oncreate i load the animation and start itanimation myanim animationutilsloadanimationthis ranimrotateobjectimgstartanimationmyanim when a button is pressed the rotation must stop hence in my onclick i called clearanimationobjectimgstartanimationmyanim my simple question is whether stopping the animation is the right thing to do i assume clearanimation corresponds to loadanimation but there is no stopanimation that corresponds to startanimation,['android'] +92226,how to use a variable as object attribute in rails i have a paymentdetail model with attribute home address country so i can use payment detailhome address country where payment detail is object of that modeli want to use something like thiscountry attributeaddress type address country where address type is equal to home payment detailcountry attribute means attribute name is stored in a variable how can i do thisedit country attributeaddress type address countrycountry listcarmencountry namesevalcountry attribute country list,"['ruby-on-rails', 'ruby']" +92228,what happened to the a few years ago dean edwards brought us this workaround to the documentonload problem the ie version of the solution involved appending this snippet to the documentscript defer srcie onloadjsscriptdean was also pretty adamant on the fact that this was the closest solution to perfection he could find and thismissed any solution that involved the onreadystatechange attribute as being unreliable see comments subsequent refinements on his solution still involved some version of script defer and most js framework implemented it including jquerytoday i am perusing jquery 141s source and i cannot find it at which point was it dropped and why,"['javascript', 'jquery']" +92231,predefined array of http errors for php use i have an errorphp file attached to errorhandler that will take the error http status in as a get variable is there an array i can find that has a mapping of status codes to error names and descriptions or do i have to write one myself,['php'] +92247,hibernate arraylist cannot be cast to set i have a java ee application and i use hibernate the domain objects i changed the list arraylist to set hashset because it is better to use setsbut in my dao implementation i run into a problempublic setperson getallpersons sessionfactory sessionfactory hibernateutilgetsessionfactory session sess sessionfactorygetcurrentsession transaction tx sessbegintransaction suppresswarningsunchecked setitem items setitem sesscreatequeryfrom itemlist txcommit return itemshere i get an errorjavalangclasscastexception javautilarraylist cannot be cast to javautilsetwhat can i do to avoid this errorthank you in advance best regards,['java'] +92253,execute my groovy script with ant or maven i have the following1 java class1 bat file starts the groovy script1 groovy fileall in the same foldernow i want to use maven or ant to run the groovy file but i cannot get it to work is there someone who can show me how to write this pomxml or buildxml i do not want to use the bat file anymore,['java'] +92255,how does rtc checkesp implemented rtc checkesp is a call that verifies the correctness of the esp stack register it is called to ensure that the value of the esp was saved across a function callanyone knows how it is implemented,['c++'] +92261,how to select first 30 chars in a sql query select first 20 chars ofcolname from dbis this possible,['sql'] +92262,wpf save webbrowser html does anyone please know how to do this i thought that there would be an easy way to achieve this but cannot find anything about saving the contents of webbrowser html,"['c#', 'html']" +92293,gzip or not gzip i keep hearing that gzip your site is a good practice to speedup delivery my site has a very vast load in general shall i still look into gzip i also read about thisadvantages of using gzip such as time required to unzip contents for the browser to thisplay is it trueupdatethis question is based on the assumption that the site is fairly optimized alreadyactually i optimized it already most of the content on my site is db driven and originally it took some time to load it all so what i did i wrote a few scripts that run nightly generate content and store it as static html files that are included on the heaviest trafficked pages the load on the server is way below its capacity so thank you for that insight i will consider it more seriously now i was thinking of using some php class that does it dynamically do you have any recommendations,['php'] +92297,c void cast and operator comma in a define i found this while reading some source code define macrox ifvoid 0 x else some funci do not fully understand the reasons behind that operator comma and the void cast this has probably something to do with macro protection i know that void0 is used sometimes to protect cascading elses in macros such as in if then foo else void0any ideas of why operator comma is thereedit i am starting to think this has something to do with the owl 00,['c++'] +92307,android webview webpage should fit the device screen i have tried the following to fit the webpage based on the device screen sizemwebviewsetinitialscale30and then set the metadata viewportmeta nameviewport contentwidth320 initialscale10 maximumscale10 userscalableno meta nameviewport contentwidthdevicewidth initialscale10 maximumscale10 minimumscale10 userscalable0meta nameviewport contentwidthdevicewidth targetdensitydpimediumdpibut nothing works webpage is not fixed to the device screen sizecan anyone tell me how to get this,['android'] +92320,how to run unit tests mstest in parallel i am looking for ways to run test suites in parallel i am aware of testrunconfig setting this allows you to multiplex on the number of cpus i want to run 10 tests in parallel this makes sense because i am testing a web service so 90 of the time spent in a test is waiting for the service to respond any ideas on how to pull this off the tests are written for vs but i am open to running them outside of vs later edit the visual studio test team have added this in vs 2015 update 1 see mark sowuls answer bellow,['c#'] +92326,converting nsstring to nsdate and back again how would i convert an nsstring like 010210 meaning 1st february 2010 into an nsdate and how could i turn the nsdate back into a string,"['ios', 'objective-c']" +92327,how to thisplay base64 encoded image in html if it is located in a separated file i have base64 encoded image if i put it right into html it worksimg srcdataimagepngbase64but when i put all that base64 content into a separated file it does notimg srcimagebase64txti tried changing extension to png but it does not help any ideas,['html'] +92338,copyonwritearray or vector allthe edge vector class has over arraylist is that it is synchronized and hence ensures threadsafety however between copyonwritearray and vector what should be the preferred considering thread safety and performance in consideration,['java'] +92360,what is the difference between using a cross join and putting a comma between the two tables what is the difference between select from a bandselect from a cross join b they seem to return the same resultsis the second version preferred over the first is the first version completely syntactically wrong,['sql'] +92363,how is the best way to extract the entire content from a bufferedreader object in java i am trying to get an entire webpage through a urlconnectionwhats the most efficient way to do thisi am doing this alreadyurl url new urlurlconnection connectionconnection urlopenconnectioninputstream in connectiongetinputstream bufferedreader bf new bufferedreadernew inputstreamreaderinstringbuffer html new stringbufferstring line bfreadlinewhilelinenull htmlappendline line bfreadlinebfclosehtml has the entire html page,['java'] +92367,uiimage from a region of uiview i am trying to clip a region of an uiview into a uiimage for later reusei have worked out this code from some snippets cgrect frameiwant cgrectmake100 100 100 100 uigraphicsbeginimagecontextviewframesize viewlayer renderincontextuigraphicsgetcurrentcontext step a get an image for the full frame uiimage fullframe uigraphicsgetimagefromcurrentimagecontext uigraphicsendimagecontext step b clip the image cgimageref regionimage cgimagecreatewithimageinrect fullframe cgimage frameiwant uiimage finalimage uiimage imagewithcgimage regionimage cgimagerelease regionimageview is the uiview which i am clipping and finalimage is the uiimage i wantthe code works without problem however is kind of slow i believe that some performance could be gained by taking just the portion of the screen directly in step ai am looking for something like renderincontext withrect or uigraphicsgetimagefromcurrentimagecontextwithrect hehestill have not found anything yet please help me if you know of some alternative,"['iphone', 'ios']" +92379,thisable a link in ie9 prototype stop not working ie9 is still in beta but all the same here is a questionusing prototypejs 161 proper form for adding a click event to a link and override the default link behavior would bemylinkobserveclick functione dosomething estopwhile this works perfectly in every other browser that i tried ie9 is a unique case the default event behavior fires and my link takes me to the linked location it seems that stop is not doing its job in ie9the following code works perfectly in ie9mylinkonclick function dosomething return falseany idea what i could do to fix the prototype methodology for use in ie9,['javascript'] +92393,conversion from myitem to nonscalar type myitem requested i have this c codeinclude iostreamusing namespace stdstruct myitem int value myitem nextitemint main myitem item new myitem return 0and i get the errorerror conversion from myitem to nonscalar type myitem requestedcompiling with g what does that mean and whats going on here,['c++'] +92416,how to add icon in alert dialog before each item i am using an alertdialog see the below code now i want to put an image before each textfor example email icon then text email facebook icon then text facebook etcusing the following code how can i add an icon before each text valuefinal charsequence items email facebook twitter linkedin alertdialogbuilder builder new alertdialogbuildermorethisbuildersettitleshare applictionbuildersetitemsitems new dialoginterfaceonclicklistener override public void onclickdialoginterface dialog int item if item 0 else if item 1 else if item 2 else ifitem 3 alertdialog alert buildercreatealertshow,['android'] +92424,python time differences i have two time objectsexampletimestruct timetm year2010 tm mon9 tm mday24 tm hour19 tm min13 tm sec37 tm wday4 tm yday267 tm isdst1timestruct timetm year2010 tm mon9 tm mday25 tm hour13 tm min7 tm sec25 tm wday5 tm yday268 tm isdst1i want to have the difference of those two how could i do thati need minutes and seconds only as well as the duration of those two,['python'] +92438,how to embed a linux bash terminal inside ruby on rails web page how to embed a bash promptterminal inside ruby on rails web pagehow to execute a linux command from the web page and get the output of the ommand,"['ruby-on-rails', 'ruby']" +92453,are types and oo coupled trying to understand if types imply oo and vice versaquestions what exactly is a type can a class in ruby be called a type in javascript the native functionsobjects like arraystringfunction are they types is a c struct a type how is it that a language can be typed even when it does not support oo for eg haskell is it that types in such langs are data types without behaviormethods in objectsclasses in oopl what are the significant differences in types between langs that have types but no oo and langs that support ooif classesobjects are types does not oo imply types can you have a type system without the typical hierarchies seen in oo langs since clojure supports type hints can it be called typed in some sense it is not statically typeddo the words untyped and dynamically typed mean the same thing,"['javascript', 'ruby']" +92460,cooperative multitasking using tpl we are porting modeling application which uses ironpython scripts for custom actions in modeling process the existing application executes each python script in separate thread and uses cooperative model for this now we want to port it to tpl but first we want to measure context switching basically what we have right now tasks queueeach task from this queue executes one ironpython scriptinside ironpython script we call for c class method which is synchronization point and should transfer task ironpython execution to waiting statewhat we want to dowe want to make infinite loop which will iterate through tasks queuewhen we get one task we try to execute itin pythonscript we want to call c method and transfer this script to waiting state but not remove it from the queueon next iteration when we get another task we check is it in the waiting state if so we wake it up and try to executein each moment we should have only one active taskand finally we want to measure how many task we could execute per secondi do not really know is it something about cooperative multitaskingwe are thinking about custom taskscheduler is it good approach or does someone know better solutionthanksupdatedok so for example i have such codepublic class cooperativescheduler taskscheduler ithisposable private blockingcollectiontask tasks private thread thread private task currenttask public cooperativescheduler this tasks new blockingcollectiontask this thread new thread foreach task task in this tasksgetconsumingenumerable this currenttask task tryexecutetaskthis currenttask this threadname cooperative scheduler thread this threadstart public void sleepcurrenttask if this currenttask null what to do here protected override ienumerabletask getscheduledtasks return this taskstoarraytask protected override void queuetasktask task no long task this tasksaddtask protected override bool tryexecutetaskinlinetask task bool taskwaspreviouslyqueued throw new notimplementedexception public void thispose this taskscompleteadding this threadjoin custom task scheduler it has one thread for task execution and currenttask field for running task also it has sleepcurrenttask in this method i want to suspend current task execution but i do not know howclient code is simple cancellationtokensource tokensource new cancellationtokensource application app applicationcreate task task taskfactorystartnew appschedulersleepcurrenttask tokensourcetoken taskcreationoptionsnone appschedulermaybe someone has better ideas,"['c#', 'python']" +92501,like operator in expression tree i have a linq extension method to dynamically filter linq queries using string values for example querywherehelpercolumname 1 i could use many different filter operators like greaterthan or notequal etc but not like there is no expressionlike or expressionstartswith etc how can i implement like operator to my expression tree heres my codepublic static iqueryablet wherehelpertthis iqueryablet source string columnname object value string filtertype parameterexpression table expressionparametertypeoft expression column expressionpropertyorfieldtable columnname expression valueexpression expressionconvertexpressionconstantvalue columntype expression where null switch filtertype case where expressionlessthancolumn valueexpression break case where expressionlessthanorequalcolumn valueexpression break case where expressionequalcolumn valueexpression break case where expressiongreaterthancolumn valueexpression break case where expressiongreaterthanorequalcolumn valueexpression break case where expressionnotequalcolumn valueexpression break expression lambda expressionlambdawhere new parameterexpression table type exprargtypes sourceelementtype methodcallexpression methodcall expressioncalltypeofqueryable where exprargtypes sourceexpression lambda return iqueryabletsourceprovidercreatequerytmethodcall,['.net'] +92521,fit image in webview i am planning to thisplay images from sd card in a webview in order to take advantage of he built in zoom capabilities of webview however i am facing an issue with thisplaying images that are bigger than screen size eg 1800x1200 to fit the screen initially like in an imageview i want the image to be thisplayed in full at first and provide zoom control to the usersi have tried using wrap content for webviews width and height but that does not work any ideasfollowing is a code snippet i am using string path getrealpathfromurimurilistget0 this gets the file path webview webview findviewbyidridwebview01 websettings settings webviewgetsettings settingssetbuiltinzoomcontrolstrue settingssetsupportzoomtrue webviewloadurlfile path,['android'] +92529,sqlalchemy move mixin columns to end i have a sqlalchemy model where all most all tablesobjects have a notes field so to try follow the dry principle i moved the field to a mixin class class notesmixinobject notes sacolumnsastring40 nullablefalse defaultclass servicebase notesmixin tablename service service id sacolumnsainteger primary keytrue name sacolumnsastring255 nullablefalse indextrue uniquetrueclass datacenterbase notesmixin tablename datacenter datacenter id sacolumnsainteger primary keytrue name sacolumnsastring255 nullablefalse indextrue uniquetrueclass networkbase notesmixin statusmixin tablename network network id sacolumnsainteger primary keytrueetcnow the notes column is the first column in the modeldb i know it does not affect the functionality of my app but it irritates me a bit to see notes before id etc any way to move it to the end,['python'] +92538,like does not accept null value i have query that is build from users inputs passed via html form it looks like simple exampleselect from table where tablecolumn like parameterthis parameter may be optional so if user left corresponding input field empty i pass it worked fine until i encountered null values i understand that match symbols not null but i would like to consider null as empty string in this casewhat should i do change query how or pass another symbols when user left empty inputthanksps it is real problem from existing system and i know it is far from optimal solution but i have to deal with it,['sql'] +92542,can inapp purchases be gifted in the app store does anyone know if inapp purchase can be gifted for example if i want to give a family member free coins in a game is this possible,['iphone'] +92558,sql cte and order by affecting result set i have pasted a very simplified version of my sql query below the problem that i am running into is that the order by statement is affecting the select results of my cte i have not been able to understand why this is my original thinking was that within the cte i execute some select statement then the order by should work on those resultsunfortunately the behavior that i am seeing is that my inner select statement is being affected by the order by giving me items that are not in the top 10here is an example of dataindexed in reverse order by idid date9600 201010129599 201009089598 201008319597 201008319596 201008309595 201008119594 201008069593 201008059592 201008029573 201008108174 2010080538 20291220my basic querywith results asselect top 10 id datefrom dboitemsselect idfrom resultsquery returnsid date9600 201010129599 201009089598 201008319597 201008319596 201008309595 201008119594 201008069593 201008059592 20100802my query with the order bywith results asselect top 10 id datefrom dboitemsselect idfrom resultsorder by date descquery returnsid date38 202912209600 201010129599 201009089598 201008319597 201008319596 201008309595 201008119573 201008109594 201008068174 20100805can anyone explain why the first query will only return ids that are in the top 10 of the table and the second query returns the top 10 of the entire table after the sorting is applied,['sql'] +92563,using audiotrack in android to play a wav file i am working with android trying to make my audiotrack application play a windows wav file tadawav frankly it should not be this hard but i am hearing a lot of strange stuff the file is saved on my phones mini sd card and reading the contents does not seem to be a problem but when i play the file with parameters i am only pretty sure are right i get a few seconds of white noise before the sound seems to resolve itself into something that just may be righti have successfully recorded and played my own voice back on the phone i created a pcm file according to the directions in this examplewithout the backwards maskinganybody got some suggestions or awareness of an example on the web for playing a wav file on an androidthanksr,['android'] +92566,java how to get iterator from string i need a iteratorcharacter from a string object is there any available function in java that provides me this or do i have to code my own,['java'] +92590,remove whitespace from each array item rails i found this codeeach key a selfastrip if selfarespond to strip on this website but i assume that is for a hash i am trying to do the same with an arrayi have tried a few different things but cannot figure it outthank you for any help,"['ruby-on-rails', 'ruby']" +92595,best logger for cocoa can anyone recommend me a good logger for cocoa something that should be in par with log4ji have been developing this app in cocoa as the source code is growing i find my self craving for a logger i have googled a bit have found a few options but i am looking to hear from you guys your experiences with these loggersi look forward to hearing your comments,"['iphone', 'objective-c', 'ios']" +92603,javascriptjquery gotchas what are some of the common javascript andor jquery gotchas that you have seen or been tripped up byas an example it was pointed out to me this morning that you have to be careful with the radix when doing parseint because if your string starts with a 0 the radix will default to 8,"['javascript', 'jquery']" +92623,howto clean a mysql innodb storage engine is it possible to clean a mysql innodb storage engine so it is not storing data from deleted tablesor do i have to rebuild a fresh database every time,['mysql'] +92627,start nonelevated process from elevated process possible duplicatehow to run not elevated in vista nethow do you deelevate privileges for a child process my program running as an elevated process and starting new processes with procestartfor security reasons i would like to run those new processes as nonelevatedhow to do that,"['c#', '.net']" +92629,how to prevent macro redefinition after working some time in my project this warning begin to appear2gamecpp2cprogram filesmicrosoft sdkswindowsv60aincludewindefh126 warning c4005 apientry redefinicia3n de macro2 cusersferrandirectogameprojectsdevlibsglfwincludeglfwh72 vea la definicia3n anterior de apientry2cprogram filesmicrosoft sdkswindowsv60aincludewingdih23 warning c4005 wingdiapi redefinicia3n de macro2 cusersferrandirectogameprojectsdevlibsglfwincludeglfwh88 vea la definicia3n anterior de wingdiapii am sure that is a matter of the order of the include files to solve because none of this files are mine my question is if there is a generic way to prevent or to find which files must to be reordered to avoid this message,['c++'] +92686,class for jquery ui datepicker button i have the following code for the jquery ui datepickerfunction datedatepicker showon button buttontext choose date dateformat yymmdd it creates a button on the side of the text box so people can click the box and select a date is it possible to apply a class to the button that is created so i can apply a css style to it,['jquery'] +92687,linq select thistinct while ignoring the xml field i have a complex linq query using linq 2 ef that can return duplicate results and i am thus using the thistinct method to avoid duplicates heres the skeletonvar subquery1 one queryvar subquery2 another queryvar result subquery1thistinctunion subquery2thistinct toarrayeach of the sub queries join a common user table with another table and perform a where query the results are later combined in the union this worked fine until the table was modified to include an xml column which results in this exceptionthe xml data type cannot be selected as thistinct because it is not comparablein this case i do not care if the xml column is equivalent across the results actually i only need to be assured that the primary key userid is thistinct in the resultsis there a way to use thistinct but ignore the xml column or a simpler way to assure that i remove records from the result with the same userid in an efficient way ideally this would not retrieve duplicate records from the database and would not require postprocessing to remove the duplicatesupdatei have found out that if i serialize my queries to arrays ahead of time then there is no need for any kind of comparer since linq2objects does not have the xml thistinct selection issue for example i can do thisvar subquery1 one queryvar subquery2 another queryvar result subquery1thistincttoarrayunion subquery2thistincttoarray toarrayso what i am really looking for is a way to avoid serializing the intermediate queries and do a linq2entities call directly that will not fetch records with duplicate userids thanks for all the answers thus far,['c#'] +92701,java int to string integertostringi vs new integeritostring sometimes java puzzles mei have a huge amount of int initializations to makewhats the real differenceintegertostringinew integeritostring,['java'] +92710,simple way to update ienumerable objects using linq assume i have a business object like thisclass employee public string name public int id public string desgination public int grade listemployee lstemp new listemployee new employee nameadesginationseid1 new employee namebdesginationtlid2 new employee namecdesginationplid3 new employee nameddesginationseid4 new employee nameedesginationsseid5 and if i want to update the employee grade to 3 whose designation is se then i have to write something like thislstemplstempselectx xgrade xdesgination se 3 xgrade return x tolistbut here when using select it will generate new employee object everytime not updating the existing lstemp so i have to reassgin the updated list to lstemp it seems to me it affects the performance when updating large updates frequently is there a workaround for this,['c#'] +92724,android how to enablethisable wifi or internet connection programmatically using the connectivity manager class we can get access to either wifi or internet network connectivitymanager connec connectivitymanagergetsystemservicecontextconnectivity service are we connected to the netif connecgetnetworkinfo0getstate networkinfostateconnected connecgetnetworkinfo1getstate networkinfostateconnected where 0 and 1 respectively refers to mobile and wifi connectionif my android device is connected to both can we switch between any of the network or can we thisable any of the network like using a functionconnecgetnetworkinfo0setstatenetworkinfostatethisconnected,['android'] +92756,how are extension methods compiled how the c compiler implement extension methods,['c#'] +92762,oracle sql query that returns rows with only numeric values i have a field column in oracle called x that has values like a1b2c3 abc 1ab 123 156how do i write an sql query that returns me only the x that hold pure numerical values no letters from the example above would be a123a and a156aselect xfrom mytablewhere,['sql'] +92778,visual studionet added javabased web service reference using wsdl but cannot find it i am trying to add a javabased web service reference to my net project using a wsdl generated by it but every time i have added it i cannot find it from the code let alone invoke its one webmethod i can add it alright and it shows up in my project tree but i cannot see the methods and i cannot find or access the webservice from my code when i right click it and try to view it in the object browser it does not show up what gives this is the contents of the wsdl i left out the data types to keep it small xml version10 wsdldefinitions xmlnsxsd xmlnswsdl xmlnssoap xmlnstns 01 targetnamespace 01 wsdlmessage nameresponse wsdlpart namedefaultinput elementtnsresponse wsdlmessage wsdlmessage namerequest wsdlpart namedefaultoutput elementrequest wsdlmessage wsdlporttype namehandymanifestfargoonrampservicesoap wsdloperation namesavefco wsdlinput messagetnsrequest wsdloutput messagetnsresponse wsdloperation wsdlporttype wsdlbinding namehandymanifestfargoonrampservicesoap typetnshandymanifestfargoonrampservicesoap soapbinding transport wsdloperation namesavefco soapoperation soapaction styledocument wsdlinput soapbody useliteral wsdlinput wsdloutput soapbody useliteral wsdloutput wsdlfault namegenericsoapfault soapfault namegenericsoapfault useliteral wsdlfault wsdloperation wsdlbinding wsdlservice namehandymanifestfargoonrampservice wsdlport namehandymanifestfargoonrampservicesoap bindingtnshandymanifestfargoonrampservicesoap soapaddress location wsdlport wsdlservice wsdldefinitionsupdatetrying to run the wsdl through svcutilexe gives me some interesting error messages r1014 the children of the soapbody element in a envelope must be namespace qualified the use of unqualified element names may cause naming conflicts therefore qualified names must be used for the children of soapbody part defaultoutput of message request from service description with targetnamespace 01and error unable to import binding handymanifestfargoonrampservicesoap from namespace 01 unable to import operation savefco the element 01response is missingso this tells me that the message elements should have the same namespace specified in the sections below wsdlmessage nameresponse wsdlpart namedefaultinput elementtnsresponsewsdlmessagewsdlmessage namerequest wsdlpart namedefaultoutput elementrequestwsdlmessagebut how do i do that,"['java', '.net']" +92782,how to get fbapimefeed post to work i have tried to use fbapi to post something to my feed for hours now i cannot get it to work for me i gave the permissions to the app i can post to my feed with the php sdk but i have to use javascriptbutton onclickdopostpost to streambuttonscriptwindowdopost function fbapi mefeed post body trying the graph loginfobindmefeed post callback scriptcan someone give me the example of a simple html page that uses fbapi to post to a feed,['javascript'] +92789,assigning click event to div but not anchor within it a jquery questioni have a div that contains text and an anchor tagi want to assign a click event to the div tag and its content excluding the anchor tagso when i click on the div an alert window pops up but if i click the anchor thats within the div the alert should not occurthe div would be something like thisdiv idmydiv this is the content of the div img srcblahjpg a hrefsomewherehtmlclick herea some more contentdivany ideas i am using jquery to assign the click event to the div,['jquery'] +92796,amazon api itemsearch categories i am using php pear amazon package to retrieve products from the api i can search for books and dvds at the moment but i need all the categories the problem is i cant find all the categories like eg home gardeni am using below code to pull out booksresult amazonitemsearchbooks optionsi have tried replacing books with homegarden but doesnt work i need a full list of amazon cats anyone have any ideas where i can get these from i have trawled the amazon sitecheersj,['php'] +92827,how to iterate through google multimap i have to iterate through google multimap buti am using jdk 14 and cannot switch to higher version so i can not use generic featuresmy multimap can have multiple values for a keythere might be a situation when a value of multimap is multimap in itself,['java'] +92829,order of execution of jquery document ready suppose i have a js file which looks like this documentreadyfunction first task documentreadyfunction second task documentreadyfunction third task upon loading the file the tasks get executed in order i am not able to understand why i am guessing that the callback methods are fired when an on ready event occurs how is the execution order being retained are the consecutive call backs being queued up in some place note i know that this is a very naive way of coding i have written the snippet only to get my point across and do not write such code in my projects,['jquery'] +92833,how to store millions of double during a calculation my engine is executing 10 of simulations on x deals during each simulation for each deal a specific condition may be verified in this case i store the value which is a double into an array each deal will have its own list of values ie these values are indenpendant from one deal to another dealat the end of all the simulations for each deal i run an algorithm on his listdouble to get some outputs unfortunately this algorithm requires the complete list of these values and thus i am not able to modify my algorithm to calculate the outputs on the fly ie during the simulationsin normal conditions ie x is low and the condition is verified less than 10 of the time the calculation ends correctly even if this may be enhancedmy problem occurs when i have many deals for example x 30 and almost all of my simulations verify my specific condition let say 90 of simulations so just to store the values i need about 90 30 64bits of memory about 216mb one of my future requirements is to be able to run 50 of simulationsso i cannot continue with my current way of storing the values for the moment i used a simple structure of mapstring listdouble where the key is the id of the element and listdouble the list of valuesso my question is how can i enhance this specific part of my application in order to reduce the memory usage during the simulationsalso another important note is that for the final calculation my listdouble or whatever structure i will be using must be ordered so if the solution to my previous question also provide a structure that order the new inserted element such as a sortedmap it will be really greati am using java 16edit 1my engine is executing some financial calculations indeed and in my case all deals are related this means that i cannot run my calculations on the first deal get the output clean the listdouble and then move to the second deal and so onof course as a temporary solution we will increase the memory allocated to the engine but it is not the solution i am expecting edit 2regarding the algorithm itself i cannot give the exact algorithm here but here are some hintswe must work on a sorted listdouble i will then calculate an index which is calculated against a given parameter and the size of the list itself then i finally return the indexth value of this listpublic static double algodouble input listdouble sortedlist if somespecificcases return 0 calculate the index value using input and also size of the sortedlist double index specific case where i return the first item of my list if index 1 return sortedlistget0 specific case where i return the last item of my list if index sortedlistsize return sortedlistgetsortedlistsize 1 here i need the indexth value of my list double val sortedlistgetint index double finalvalue somebasiccalculationsval return finalvaluei hope it will help to have such information nowedit 3currently i will not consider any hardware modification too long and complicated here the solution of increasing the memory will be done but it is just a quick fixi was thinking of a solution that use a temporary file until a certain threshold for example 10 my listdouble stores new values in memory when the size of listdouble reaches this threshold i append this list in the temporary file one file per dealsomething like thatpublic void addnewvaluedouble v if listsize 10 appendlistinfile listclear listaddvat the end of the whole calculation for each deal i will reconstruct the complete listdouble from what i have in memory and also in the temporary file then i run my algorithm i clean the values for this deal and move to the second deal i can do that now as all the simulations are now finishedwhat do you think of such solution do you think it is acceptableof course i will lose some time to read and write my values in an external file but i think this can be acceptable no,['java'] +92860,signedxml checksignature returns false i have looked at other posts on here regarding this issue and none of them seem to address my situationi have been trying to verify a saml assertion for the last week and i have 2 clients that have sent me saml but i cannot verify itthe main process is we get a base64 encoded assertion and i decode it load it into an xmldocment with preservewhitespace truethe verify method is public static bool verifyx509certificate2 cert xmlelement xmlelement signedxml signedxml bool flag try keyinfo keyinfo new keyinfo var clause new keyinfox509datacert keyinfoaddclauseclause xmlelement signatureelement getsignatureelementxmlelement if signatureelement null string message the xml does not contain a signature throw new samlsignatureexceptionmessage signedxmlloadxmlsignatureelement if keyinfo null signedxmlkeyinfo keyinfo setsigningkeyfromkeyinfosignedxml flag signedxmlchecksignaturecertpublickeykey catch exception exception throw new samlsignatureexceptionfailed to verify the xml signature exception return flag private static void setsigningkeyfromkeyinfosignedxml signedxml ienumerator enumerator signedxmlkeyinfogetenumerator while enumeratormovenext if enumeratorcurrent is keyinfox509data var current keyinfox509data enumeratorcurrent if currentcertificatescount 0 var certificate x509certificate currentcertificates0 var certificate2 new x509certificate2certificate asymmetricalgorithm key certificate2publickeykey signedxmlsigningkey key return else if enumeratorcurrent is rsakeyvalue var value2 rsakeyvalue enumeratorcurrent signedxmlsigningkey value2key return if enumeratorcurrent is dsakeyvalue var value3 dsakeyvalue enumeratorcurrent signedxmlsigningkey value3key return throw new samlsignatureexceptionno signing key could be found in the key info i have the certificate from the client that i read in from webconfig its stored as base64 encoded string xmlelement is the signed element signedxml is a signedxml object that was created with new signedxmlxmlelementboth clients get false returned by checksignature but when i create my own signed saml with my certificate it will return truewhat am i missing here edit yes both of the clients are on java and i posted the setsigningkeyfromkeyinfo method,"['c#', '.net']" +92885,how to replace javascript of production website with local javascript on my production website i have compiled javascriptscript srcjsmycodeminjsscriptit would be very convient for debugging if i could make my browser replace that withscript srchttplocalhostjsmycode1jsscriptscript srchttplocalhostjsmycode2jsscripti know i could manipulate the dom using something like greasemonkey userscripts but i could not come up with a solution which would prevent the execution of mycodeminjsany ideas,['javascript'] +92891,javascript math parser library is there a good math parser in javascript i want to be able to parse something likelog31452pow2lnx2ythanks,['javascript'] +92899,array of imagebuttons assign rviewid from a variable hey there my app is going to be using an array of 64 imagebuttons 8x8 and they are all already declared in my xml layout with names like one1 two5 eight8 etc rather than declare these each individually in my java i thought it might be smart to declare them all in some for loops i haveimagebutton musicgrid new imagebutton 88then i have my nested for loops that basically create a string that will be in place of ridwhatever it is just that last line in my loops that is supposed to do the assigning what would the correct syntax for that be or is this not even possible to do and if so how better would i handle a 64 button grid thanksfor int i 0 i 8 i for int j 0 j 8 j string btnid rid switchi case 0 btnidconcatone break case 1 btnidconcattwo break case 2 btnidconcatthree break case 3 btnidconcatfour break case 4 btnidconcatfive break case 5 btnidconcatsix break case 6 btnidconcatseven break case 7 btnidconcateight break switchj case 0 btnidconcat1 break case 1 btnidconcat2 break case 2 btnidconcat3 break case 3 btnidconcat4 break case 4 btnidconcat5 break case 5 btnidconcat6 break case 6 btnidconcat7 break case 7 btnidconcat8 break musicgridij imagebutton findviewbyidbtnid,['android'] +92907,using slick upload with mvc 2 and jquery ajax i am trying to get slick upload working inside a jquery ui dialog i have got it uploading the file just fine and i have checked out the samples and they all end up with the entire page reloading i have managed to make it so it does not do it is final postback to deal with the files after it uploads by setting the autopostbackafteruploadfalseso it now puts the files on the server with the random guid name and it gets a response that looks like thisstate completereason notterminatedpercentcomplete 10percentcompletetext 10 contentlengthtext 826 kbtransferredlengthtext 826 kbremaininglengthtext 0 bytescurrentfilename desertjpgcurrentfileindex 1timeelapsedtext 1 secondtimeelapsedshorttext 01timeremainingtext timeremainingshorttext 0speedtext 596 kbsecso what i need to know is how do i ajaxly post what slick upload does automatically when you have the autopostbackafterupload set to trueheres my code htmlbeginformorganizationmembereditcontactsectionchangephoto organizationmember formmethodpost new with id uploadform enctype multipartformdata kwslickupload idslickupload1 runatserver autopostbackafteruploadfalse uploadformiduploadform showduringuploadelementscancelbutton hideduringuploadelementsuploadbutton maxfiles1 autouploadonpostbackfalse progressinterval200 downlevelselectortemplate input typefile downlevelselectortemplate uplevelselectortemplate input typebutton valueadd file uplevelselectortemplate filetemplate kwfilelistremovelink runatserverx removekwfilelistremovelink kwfilelistfilename runatserver kwfilelistvalidationmessage runatserver forecolorred filetemplate progresstemplate table width99 tr td uploading kwuploadprogresselement iduploadprogresselement1 runatserver elementfilecounttext kwuploadprogresselement iduploadprogresselement2 runatserver elementcontentlengthtextcalculatingkwuploadprogresselement td tr tr td currently uploading kwuploadprogresselement iduploadprogresselement3 runatserver elementcurrentfilename file kwuploadprogresselement iduploadprogresselement4 runatserver elementcurrentfileindexnbspkwuploadprogresselement of kwuploadprogresselement iduploadprogresselement5 runatserver elementfilecount td tr tr td speed kwuploadprogresselement iduploadprogresselement6 runatserver elementspeedtextcalculatingkwuploadprogresselement td tr tr td about kwuploadprogresselement iduploadprogresselement7 runatserver elementtimeremainingtextcalculatingkwuploadprogresselement remaining td tr tr td div styleborder 1px solid 008800 height 15em position relative kwuploadprogressbarelement iduploadprogressbarelement1 runatserver stylebackgroundcolor 00ee00 width 0 height 15em div styletextalign center position absolute top 15em width 100 kwuploadprogresselement iduploadprogresselement8 runatserver elementpercentcompletetextcalculatingkwuploadprogresselement div div td tr table progresstemplate kwslickupload p input typebutton valueupload iduploadbutton a hrefjavascriptkwgetslickupload1clientid cancel idcancelbutton stylethisplaynonecancela p htmlendformscript typetextjavascript var thething var urltopost theurlthathandlesthepostback function v2setupphotodialog thething kwgetslickupload1clientid thethingadd onuploadendedfunction status var data uploadformserialize ajax type post url urltopost data data success function v2regularnoticesuccess error function v2regularnoticefail uploadbuttonliveclick function thething kwgetslickupload1clientid thethingsubmit return false kwgetslickupload1clientid submit scriptas you can see i tried having the onuploadended take the status as a parameter but it does not fill it with any of the useful information that the status parameter for the action needs it currently serializes the form and sends that but it only populates 1 field kw uploadidthe controller action does not do anything yet it just tries to take a uploadstatus as a parameter but it is empty if i just serialize the form i am sure i am missing something obvious but i cannot figure it out i am finding the documentation kind of hard to follow and not to helpful in this casethanks,['jquery'] +92927,check if exec is thisabled is there any function in php that i can use to detect whether or not the exec function is available,['php'] +92932,lite weight and simple jquery auto suggestautocomplete all i need is a very simple auto complete that suggests words that have the letters the user is typing in them very simple nothing fancy either inline or from an external file i only need about 20 or so results to be suggested totali saw this one but it is 8kb which is pretty big for what i need it for does anyone know of a smaller light weight autocomplete script or does anyone know the jquery to provide a super simple autocompleand i am not using jquery ui that is a crappy bloated addon to jquery so i cannot use their autocomplete i am sure it is 10mb large anyways,['jquery'] +92935,2d framework c i am looking for a 2d framework with such things as layersparticlesscreen managersprite batchparallaxetc coded in c out there i am looking for somethings that does not necessarily have graphics because i want to add it on to airplay sdk or something i can easily rewire to do the graphics through airplayedit i found what i needed cocos2d was potted to c and airplay sdk cocos2dx thanks for the answers anyways,['c++'] +92941,htmlcss inputtextarea default text and colors two semirelated questions1 i have seen input and textarea boxes that contain some default text like enter search terms here and the moment you click on the box the text thisappears how is this implemented is this a javascript thing2 can the default text be in one color and whatever you type either overwriting or appending be in a different color,['css'] +92943,is the clr incompatible with java as a language i have wondered for a while about the feasibility of having java run on the clrafter seeing a previous question here i realize that there are quite a few differences between the sun java platform and the net runtime that would make crosscompiling impossible in all but the most trivial casesthat being said is not il a turingcomplete language could not you write a jvm in il of course the answer is yes but why even go that farmy question isis the clr as a platform incompatible with java as a language not a platformhow much of java would have to be contorted or broken in order to make it fitsurely this could be compiled for the clr netimport systempublic class helloworldexample public static void mainstring args consolewritelinehello world clarificationwhat i am getting at is that i want to know what language features of java are incompatible with their clr counterpartsfor example i think that generics are somehow incongruent i believe that it is as similar story with exceptions,['java'] +92950,parsing simple xml with nokogiri i have the following xmllinks item titletitle 1title urlurl item item titletitle 2title urlurl item item titletitle 3title urlurl itemlinksand i would like to convert it to a html listul lia hreftitle 1ali lia hreftitle 2ali lia hreftitle 3aliulcurrently i have thiscontrollerrequire nokogiridoc nokogirixmllinks docxpathlinksitemmap do i title ixpathtitle url ixpathurlendtemplateul linkseach do l lia href lurl ltitle ali end ul resulting htmlul lia hreftitle 1title 2title 3ali lia hreftitle 1title 2title 3ali lia hreftitle 1title 2title 3aliulwhat am i doing wrong is there a more optimal way of doing this,"['ruby-on-rails', 'ruby']" +92967,custom attributes in uibinder widgets i am using gwt and uibinder for my app and i am trying to do thisgtextbox uifieldsearchbox stylenamestylesearchbox placeholdersearch but the custom placeholder attribute would not work because there is not a setplaceholder method on textbox i need to this searchboxgetelementsetattributeplaceholder searchback in the java code any ideas on how to do this in uibinder itself i suppose i could change it over to a normal input element and try to grab a reference and its value but i would rather not go down that road,['java'] +92973,sieve of eratosthenes finding primes python just to clarify this is not a homework problem i wanted to find primes for a math application i am building came across sieve of eratosthenes approach i have written an implementation of it in python but it is terribly slow for say if i want to find all primes less than 2 million it takes 20 mins i stopped it at this point how can i speed this updef primes sievelimit limitn limit1 primes range2 limitn for i in primes factors rangei limitn i for f in factors1 if f in primes primesremovef return primesprint primes sieve20updatei ended up doing profiling on this code found that quite a lot of time was spent on removing an element from the list quite understandable considering it has to traverse the entire list worstcase to find the element then remove it and then readjust the list maybe some copy goes on anyway i chucked out list for dictionary my new implementation def primes sieve1limit limitn limit1 primes dict for i in range2 limitn primesi true for i in primes factors rangeilimitn i for f in factors1 primesf false return i for i in primes if primesitrueprint primes sieve120,['python'] +93025,how to get dates of a week i know week number i know the week number of the year a week is start from sunday then monday tuesdaysaturdaysince i know the week number whats the efficient way to get the dates of the specific week by using java code,['java'] +93049,how to do unit testing of functions writing files using python unittest i have a python function that writes an output file to thiski want to write a unit test for it using python unittest modulehow should i assert equality of files i would like to get an error if the file content differs from the expected one list of differences as in the output of unix diff commandis there any officialrecommended way of doing that,['python'] +93057,what is the point in a retain immediately followed by an autorelease i am looking at some open source code and trying to understand why the author has done something in a particular waythe class is a wrapper around nsarray to create a stack data structure with push pop etcone method is topobject which returns the topmost object on the stack and its implementation is idtop return stack lastobject retain autorelease stack is an instance of nsmutablearraywhats with the retain followed by an immediate autoreleasemy initial reaction was that this would prevent an analyser warning about a memory leak but i analysed without the retainautorelease and there was still no warninglooking at the lifecycle an object would be created pushed to the stack and released so the stack owns the object the underlying array will retain it upon addingso i do not understand the use of the retainautorelease here,['objective-c'] +93061,can int value be assigned to id type objective c i want to know if this assignment is correctid var 9will var be assigned the value 9 or do we have to wrap in some wrapper class like nsnumber,['objective-c'] +93068,buildbot parsing python unit test results i have a test suite that outputs test results in the python unit test format is there an existing buildbot moduleplugin that can parse this form exampledigitalreadwrite 02 okdigitalreadwrite 03 okdigitalreadwrite 04 okpwmoutput 02 pwm128 50 low 49 high okpwmoutput 03 pwm128 50 low 49 high okpwmoutput 04 pwm128 50 low 49 high okran 6 tests in 1652soki have written a custom parser but it is only got the basic cases is it worth the effort to make it comprehensive for all flavors of python unit test format,['python'] +93080,str replace in sql update heres a sample tablename picturejohn s linda b let us say there are several hundred more recordslet us also say we moved servers from servera to serverbwould it be possible to go into this table with one query to rename the content in the column picture for every record to read the correct server name,"['sql', 'mysql']" +93082,android avoid scaling of background in a start activity of our android application were using a linearlayout with an background image for whole space the image size is 320x480 the same as device resolution were using for testingthe problem is the image will be scaled und looks not so nicei tried to use imageview instead but i have got black borderssome ideas how to avoid scaling or how to get the proper size for background imagethank you in advancemur,['android'] +93092,maximum length of byte i am trying to create an array of bytes whose length is uint32maxvalue this array is essentially a smallish inmemory databasebyte countrycodes new byteuint32maxvalueon my machine however at runtime i get a systemoverflowexception with arithmetic operation resulted in an overflowwhats the deal do i need to use an unsafe block and malloc how would i do that in c,['c#'] +93098,textbox with new line we tried several ways to make a textbox to accept the enter newline etc but we are still facing the same problems most of the third party controls allow the user to format the text as he wants eg add color font table etc however for most stylish websites we do not want to allow the user to format the text that waybut we still want them to make enter so we thisable most functions colors bold table insert image etc but we still have another problem copy and paste it is not uncommon to see people that copy from ms word in the textbox and wham all the style of the site is awfulthat is why i turn on the possibility of making my own textbox multiline the asp net and just let the right to make press enter br what is the best way to proceedis there any tips that i have to watch outthank you,['asp.net'] +93108,create unqiue caseinsensitive constraint on two varchar fields in oracle 10g how do i add a unique caseinsensitive constraint on two varchar fields for example given the following records already in the tablestephen swensenjohn smiththe following inserts would be invalidstephen swensenjohn smithstephen swensenbut the following inserts would be validstephen smithjohn swensen,['sql'] +93121,how to determine where assemblyload searches for assemblies i have a vs addin that is using a binaryformatter to deserialize an object to resolve the type of this object it is calling assemblyloadobjecttypefullname but it is triggering an exception because assemblyload cannot find the assembly in any of the places it is searching on the given assembly is sibling to the addin assembly but it seems that assemblyload cannot find it therea possible solution would be to determine where assemblyload should look for assemblieswhat should i dops i am trying not to put this assembly on gac because i would need to update it everytime i recompile the assembly,"['c#', '.net']" +93124,php filestmp name i am trying to upload a doc file from a form and send it to email i am using filesfiletmp namethe problem is it is returning a randomly generated file name so when it reaches the inbox the filename is phpvwrgkndat filename is random each timehow can i preserve the filename and extensionnote i am using geekmail class,['php'] +93125,c how to return dictionary or hashset as readonly collections possible duplicateis there a readonly generic dictionary available in net hi everyonei realized that it was possible to return lists as read only collections var list new liststringreturn listasreadonlyi wanted to write a similar piece of code for data structures like dictionary or hashset but i didnat find a way to achieve such a goal is there a way to return a dictionary or a hashset as a readonly collectionthank you,['c#'] +93128,keyboard accessible web dropdown menus is there a way to build keyboard accessible dropdown menus on web sites our current web application has standard hover menus but this really slows down our data entry clerks who are accustomed to desktop apps where there is a keyboard accessible menu and no need to use a mouse we figured out how to show the menu with a keyboard shortcut but i am not sure how to select one of the entries such as by using the first letter of the menu entry like in most desktop apps edit a link to a site that does this or some other type of example would be really helpful,"['javascript', 'jquery', 'html', 'css']" +93131,windows 7 does not allow me edit files in common application data folder i want to store some files and edit them for my software in common application data under windows 7i do not know why windows 7 does not allow my software to change files unless i run them as administratorwhere can i store my files so it would not require admin permission,['c#'] +93134,find a specific tag with beautifulsoup i can traverse generic tags easily with bs but i do not know how to find specific tags for example how can i find all occurances of div stylewidth300px is this possible with bs,['python'] +93143,what to consider before subclassing list i was recently going over a coding problem i was having and someone looking at the code said that subclassing list was bad my problem was unrelated to that class he said that you should not do it and that it came with a bunch of bad side effects is this truei am asking if list is generally bad to subclass and if so what are the reasons alternately what should i consider before subclassing list in python,['python'] +93171,progressdialog does not want to update the message i just tried to implement a progressdialog and i have some issues to change the text during my long and complex calculationsfor string astringmystringarray logvtag astring mprogressdialogincrementprogressby1 mprogressdialogsetmessageastringi can clearly see the incrementprogressby working and my dialog updating but the message does not changeany idea on how to make that workthank a lot,['android'] +93172,does python urllib2 automatically uncompress gzip data fetched from webpage i am using dataurllib2urlopenurlreadi want to knowhow can i tell if the data at a url is gzippeddoes urllib2 automatically uncompress the data if it is gzipped will the data always be a string,['python'] +93179,problem saving shared preferences in android right now i am trying to save a variable when i close the app and get the variable back when i open the app back up i have no idea if i am doing this right my variable is called count and would like to save and restore it is this right if so why is not it working if not what do i need to change i am obviously using sharedpreferencesprotected void onpause superonpause sharedpreferences settings getsharedpreferencesprefs count 0 sharedpreferenceseditor editor settingsedit editorputintcount count editorcommitoverrideprotected void onresume superonresume sharedpreferences settings getsharedpreferencesprefs count 0 count settingsgetintcount count,['android'] +93182,is google guava harder to use than apache collections i am thinking of asking my team of mixed skill levels to use google guava prior to guava i would have used the apache collections or its generified versionguava as opposed to apache collections seems to be stronger in some ways but perhaps less easy to use for less experienced programmers heres one area where i think might exemplify thatthe code i have inherited contains a lot of looping over lists of what are essentially maps of heterogeneous values probing them for values doing null checks and then doing something trivialboolean foo final list maplike stuff final string target final string uppercasetarget targettouppercase0 for maplike m stuff final maplike and maplike mget hard coded string if and null final string s nget another hard code string if s null stouppercaseequals uppercasetarget return true return false my initial thought was to use apache collections transformersboolean foo final list maplike stuff final string target collection string sa collection string collectionutilscollect stuff transformerutilschainedtransformer new transformer apputilspropertytransformerhard coded string apputilspropertytransformeranother hard coded string apputilsuppercasetransformer return sacontains targettouppercase using guava i might go two waysboolean foo final list maplike stuff final string target collection string sa collections2transform stuff functionscompose apputilsuppercasefunction functionscompose apputilspropertyfunctionanother hard coded string apputilspropertyfunctionhard coded string return sacontains targettouppercase or iterablescontains sa targettouppercase which actually does not buy me muchcompared to apache collections functionscompose g f reverses the intuitive order functions are applied righttoleft rather than the obvious lefttoright of transformerutilschainedtransformera more subtle issue is that as guava returns a live view calling contains on the live view is likely to apply the composed function multiple times so what i really ought to do is return immutablesetcopy sa contains targettouppercase but i might have nulls in my transformed set so i cannot quite do that i can dump it into a javautilcollection of coursebut that is not going to be obvious to my less experienced team and will likely be missed in the heat of coding even after i explain it i would hoped that perhaps iterablescontains would do the right thing and know some instanceof magic to thistinguish a liveview proxy from a plain old collection but it does not that makes guava perhaps harder to useperhaps i write something like a static method in my utility class to handle this list always uses linear search so no value in copying or perhaps i should copy it into a setboolean contains final list list final object target return listcontains target set does not use linear search so copyboolean contains final set set final object target return immutablesetcopy set contains target whoops i might have nulls return setsnewhashset set contains target or perhaps only copy sets above a certain size set does not use linear search so copyboolean contains final set set final object target final set search setsize 16 setsnewhashset set set return searchcontains target i suppose i am asking why is not there an easier transform in guava and i suppose the answer is fine just always dump what it returns into a new collection or write your own transform that does that but if i need to do that might not other clients of the guava libraries perhaps there is a better way that is in guava that i do not know about,['java'] +93184,game need for speed most wanted cannot controlled by java class robot i wrote a bot for controlling racing game using java robot the bot works well for need for speed underground except for key down up left right keys work very well however my bot cannot control need for speed most wanted the bot works fine but the game does not accept the simulated key events i did some searching and found the game is directx based in directx the keyboardmouse events are special it seems that the game asks the keyboard directly not through windows and i try my program in cs and found it works pretty welli program in windows 7 using eclipse and java 16 so i want to ask why does not need for speed most wanted accept the simulated key events and how to solve this program thank you,['java'] +93197,within an ios app how do i detect that the user has pressed one of the arrow keys on their external keyboard i have a couple of ios applications which present inherently linearly organised information allowing the user to move forward and backward through the data with onscreen controls i would like to allow users with the keyboard dock or a paired bluetooth keyboard to use the arrow keys to move back and forth as well since the apps are fullscreen it is very important to the user experience that there is no risk of thisplaying an onscreen keyboard as a sideeffecti cannot find an api that will let me do this in apples documentation but i cannot be sure that i have used the right search termswhat apis are there which will allow me to achieve thisupdate i have raised this as an enhancement on apples bug reporting site,['ios'] +93199,behaviour of unsigned right shift applied to byte variable consider the following snip of java codebyte bbyte 0xf1byte cbyteb4byte dbyte b4outputc0xffexpected outputc0x0fhowas b in binary 1 01after unsigned right shift 0 1 hence 0x0f but why is it 0xff how,['java'] +93200,best way to completely destroy a session even if the browser is not closed is it enough to session start must start a session before destroying itif isset session unset session session unset session destroywhen the user selects log out from a menu but does not quit his browser i want to totally remove all existence of the session and session,['php'] +93202,whats the safe way to fill multidimensional array using stdfill heres what i am usingclass something char flags2680 astdfillaflags00 aflags002680 0update i should have made it clear earlier that i am using this inside a class,['c++'] +93218,linux how to kill programs that use port 1935 i have a red5 server java running on my linux serversometimes the server shuts down when i try to restart it i got an errorbinding error this port is alerady in useso i try to kill the server with killall 9 javaand try to restart the server same errori have to wait for a while about 23 minutes and restart it again that worksi just need to know why when i kill the process i still have to wait 23 minutes before port 1935 is free and i can run the server againis there a way to kill this process immediately and free the port,['java'] +93227,java classisinstance vs classisassignablefrom let clazz be some class and obj be some objectisclazzisassignablefromobjgetclassalways the same asclazzisinstanceobjif not what are the differences,['java'] +93230,how is set implemented i have seen people say that set objects in python have o1 membershipchecking how are they implemented internally to allow this what sort of data structure does it use what other implications does that implementation haveevery answer here was really enlightening but i can only accept one so i will go with the closest answer to my original question thanks all for the info,['python'] +93231,what are the client profile versions of net framework 35 and 4 in visual studio 2010 i do not know the differences between 35 and 35 client profile same for 4so whats up with that,['.net'] +93242,gracefully remove n delimiter after last string within stringbuilder have following java codethat creates stringbuilder with nie carriage return delimiterswhile scannerhasnextline sbappendscannernextlineappendnit is occurredthat after last stringline had n symbolhow to gracefully remove last n from resulting stringbuilder objectthanks,['java'] +93245,opinion on reuse of db context in linq i have a class that uses linq to access the database some methods call others for exampleclass usermanager public user getlist usingvar db new mycontext return dbuserswhereitem itemactive false public user adduserstring name usingvar db new mycontext dbusersinsertonsubmitnew user id guidnewid name name active false return getlist in the call to adduser i am required to return the new list i know as it stands it is not a great design but i have eliminated detail for simplicity however the call to getlist creates a second data contexti could pad this out with extra methods vizpublic getlist usingvar db new mycontext return getlistdbpublic getlistmycontext db then replace my call in adduser so as to keep the same data contexti seem to see this type of thing a lot in my code and i am concerned with the cost of creating and releasing all these data contexts does anyone have an opinion as to whether it is worthwhile putting in the extra work to eliminate the creation and deletion of these contexts,['c#'] +93249,what programming languages can one use to develop android applications possible duplicateswhich programming languages can i use on android dalvikwhich programming languages can be used to develop in android what programming languages can one use to develop android applicationsalso are there plans in the future to expand the amount of programming languages that android will supportupdate there are really good answers over here,['android'] +93255,howto uninstall rvm possible duplicatehow to remove rvm ruby version manager from my system how can i uninstall or reinstall rvm on ubuntu 910 i messed up my current installation,['ruby'] +93263,cost of using params in c does anyone have advice for using the params in c for method argument passing i am contemplating making overloads for the first 6 arguments and then a 7th using the params feature my reasoning is to avoid the extra array allocation the params feature require this is for some high performant utility methods any advice is it a waste of code to create all the overloads,['c#'] +93272,what would be a good open source lightweight c library with basic utility functionality to use in an embedded system i am thinking of something like glib but possibly a slim version with a minimal foot print it would need basic utilities such as linked lists vectors and hash tables it should also have a minimal runtime footprint,['c'] +93295,how to replace the first occurrence of a regular expression in python i want to replace just the first occurrence of a regular expression in a string is there a convenient way to do this,['python'] +93302,python how to invoke an function on an object dynamically by name in python say i have a string that contains the name of a class function that i know a particular object will have how can i invoke itthat isobj myclass this class has a method dostufunc dostuff how to call objdostuff using the func variable,['python'] +93305,omniauth openid getting certain fields from openid provider i am using the rails gem omniauth to login users when using an openid provider i would like to get certain field like email and nickname but i do not see any documentation on this any ideas thanks,['ruby-on-rails'] +93315,android thread problem why ui still blocks when i have used a worker thread package comcommonswareandroidthreadsimport androidappactivityimport androidosbundleimport androidoshandlerimport androidosmessageimport androidviewviewimport androidviewviewonclicklistenerimport androidwidgetprogressbarimport androidwidgettextviewimport androidwidgettoastpublic class handlerdemo extends activity thread mbackground progressbar bar handler handler new handler override public void handlemessagemessage msg barincrementprogressby5 boolean isrunning false override public void oncreatebundle icicle superoncreateicicle setcontentviewrlayoutmain bar progressbar findviewbyidridprogress public void onstart superonstart barsetprogress0 mbackground new threadnew runnable public void run try int a 0 for int i 0 i 20 isrunning i for int j 0 j 20 j for int k 0 k 10 k a handlersendmessagehandlerobtainmessage catch throwable t just end the background thread findviewbyidridloginbuttonsetonclicklistener new onclicklistener public void onclickview v mbackgroundrun isrunning true public void onstop superonstop isrunning false i am really confused about that,['android'] +93316,storing html code in the sql database problem i want to store an html code in an sql database it stores everything fine except when there are attributes defined such as border0i think single quotation mark is not an issue how do i avoid this from happeningthe error error you have an error in your sql syntax check the manual that corresponds to your mysql server version for the right syntax to use near 0,"['php', 'sql', 'mysql', 'html']" +93327,php how to find application root i am having problems with my include files i do not seem to be able to figure out how to construct my urls when i use require oncesomefilephp if i try to use an include file in more than one place where the directory structures are different i get an error that the include file cannot be foundin aspnet to get my application root path i can use directoryfileaspx the tild forward slash always knows that i am referencing from my website root and find the file no matter where the request comes from within my website it always refers back to the root and looks for the file from there question how can i get the root path of my site how can i do this so i can reuse my include files from anywhere within my site do i have to use absolute paths in my urlsthank you,['php'] +93328,do global variables mean faster code i read recently in an article on game programming written in 1996 that using global variables is faster than passing parameters was this ever true and if so is this still true today,"['c++', 'c']" +93333,fixed object id for system objects and small integers in ruby why do system objects like nil true or false have a fixed object id in ruby also i tried printing out the object ids of numbers they are the same and follow an odd number sequence pattern any explanation for thisniltruefalseeach o print oobject id 4 2 0 nil true false 050each i print iobject id 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95 97 99 101 050,['ruby'] +93371,writeread plist file iphone i have plist in my iphone app and i want to read and write an integer from my single to and form iti have this to read it scoredata score scoredata shareddata filepath statsplist nsmutabledictionary plistdict nsmutabledictionary alloc initwithcontentsoffilefilepath scorehighscore plistdict objectforkeyscorethen to write to itscoredata score scoredata shareddata nsmutabledictionary plistdict nsmutabledictionary alloc initwithcontentsoffilefilepath plistdict setvaluescorehighscore forkeyscore plistdict writetofilefilepath atomically yesi am getting an error in both partsinvalid conversion form objc object to intand invalid conversion form int to objc objecti appreciate any help thanks,"['iphone', 'objective-c']" +93372,swing modal dialog refuses to close sometimes this is supposed to show a modal dialog and then hide it again in practice this works about 75 of the time and the other 25 of the time the dialog stays visible this is on ubuntu 1010 running openjdk runtime environment icedtea6 19 6b20190ubuntu1 this always prints setvisibletrue about to happen setvisiblefalse about to happen setvisiblefalse has just happened even when the dialog stays visiblepackage modalproblemdemoimport javaawtframeimport javaxswingjdialogimport javaxswingswingutilitiespublic class main public static void mainstring args final dialogs d new dialogs new thread override public void run dshow dhide start static class dialogs final jdialog dialog public dialogs dialog new jdialogframe null hello world modal true dialogsetsize400 200 public void show swingutilitiesinvokelaternew runnable public void run dialogsetlocationrelativetonull systemoutprintlnsetvisibletrue about to happen dialogsetvisibletrue public void hide swingutilitiesinvokelaternew runnable public void run systemoutprintlnsetvisiblefalse about to happen dialogsetvisiblefalse systemoutprintlnsetvisiblefalse has just happened,['java'] +93375,best way to teach yourself ruby i have a decent amount of web development and programming experience with c c and several markup languages in order to expand my knowledge i have decided to learn ruby and i am wondering what you guys recommend as being the best way to teach it to yourself i took a quick browse through the books available at amazon but nothing immediately jumped out at methanks a lot in advance i really appreciate it,['ruby'] +93385,mongoid mongodb and querying embedded documents i have author and book modelsan author has many embedded bookscan i query the embedded books or do i have to fetch authors first to get books,['ruby-on-rails'] +93386,how to make heapq evaluate the heap off of a specific attribute i wish to hold a heap of objects not just numbers they will have an integer attribute in them that the heap can sort by the easiest way to use heaps in python is heapq but how do i tell it to sort by a specific attribute when using heapq,['python'] +93387,check if a object is defined best practice i have the following json response from a ajaxrequestvar json response freeofchargeproduct description product orderqty 5 productname xyz qty 6 details price 5 instock true focquantity 1 orderlineid 4788 totalorderlineprice 74136 totalorderprice 131492 totalqty 17the json dosent always return a freeofchargeproduct property so if i want to get the freeofchargeproduct price then i have to do the followingvar getfreeofchargeproductprice function var r jsonresponse if r rfreeofchargeproduct rfreeofchargeproductdetails return rfreeofchargeproductdetailsprice return nullno problems but it is very annoying to check every property in the object so i created a function that check if a property in a object is definedvar getvalue function str context var scope context window properties strsplit i fori 0 i propertieslength i if scopepropertiesi return null scope scopepropertiesi return scopevar price getvaluejsonresponsefreeofchargeproductdetailsprice price is null if no such object existsnow to my question is this a good or bad way to check if a property exists in an object any better suggestionsmethodsediti do not want to use the operator i am lazy and i am looking for a reusable method to check if a object or property of a object is defined thanks,['javascript'] +93395,why filechannel in java is not nonblocking i wanted to write a program which writes to multiple files simultaneously thought it will be possible with one thread by using nonblocking mode but filechannel does not support nonblocking mode does anybody know why,['java'] +93397,how to create toast from intentservice it gets stuck on the screen i am trying to have my intentservice show a toast messagebut when sending it from the onhandleintent message the toast shows but gets stuck and the screen and never leavedi am guessing its because the onhandleintent method does not happen on the main service thread but how can i move ithas anyone has this issue and solved it,['android'] +93404,alternative to matlab i am looking for some environment that fulfil all conditions below is free or have free students licenceenables to make dll that can be used in c in visual studio 2010has very good performance on matrix calculationshas good documentation or examplestutorialsit does not have to be compatible with matlab,['c#'] +93407,python circular imports once again aka whats wrong with this design let us consider python 3x scriptsmainpyfrom testteam import teamfrom testuser import userif name main you user t team usetteamt tsetleaderutestuserpyfrom testteam import teamclass user def setteamself t if issubclasst team class selfteam ttestteampyfrom testuser import userclass team def setleaderself u if issubclassu user class selfleader unow of course i have got circular import and splendid importerrorso not being pythonista i have three questions first of alli how can i make this thing work and knowing that someone will inevitably say circular imports always indicate a design problem the second question comesii why is this design badand the finally third onei what would be better alternativeto be precise type checking as above is only an example there is also a index layer based on class which permits ie find all users being members of one team user class has many subclasses so index is doubled for users in general and for each specific subclass or all teams having given user as a memberediti hope that more detailed example will clarify what i try to achieve files omitted for readibility but having one 300kb source file scares me somehow so please assume that every class is in different file entityclass entity id none defs data none def init self kwargs self id uuiduuid4 for example or randint or x1 self data updatekwargs def settattr self name value if name in self defs if issubclassvalue class self defsname self dataname value more stuff goes here specially indexing dependencies so we can do indexsome class name of property someobject to find all objects of some class or its children where given property someobject else raise exceptionsome misleading message else self dict name value def gettattr self name return self dataname users class userentity defs teamteamclass dpluseruser defs teamdplteamclass pythonuserdpluser passclass perluserdpluser passclass functionaluseruser defs teamfunctionalteamclass haskelluserfunctionaluser passclass erlanguserfunctionaluser pass teamsclass teamentity defs leaderuserclass dplteamteam defs leaderdpluserclass functionalteamteam defs leaderfunctionaluserand now some usaget1 functionalteamt2 dlpteamt3 teamu1 haskelluseru2 pythonusert1leader u1 okt2leader u2 okt1leader u2 not ok exceptiont3leader u2 ok now indexprintindexfunctionalteam leader u2 t2printindexteam leader u2 t2t3so it works great implementation details ommitted but there is nothing complicated besides of this unholy circular import thing,['python'] +93419,overlay an android layout on a surfaceview i am designing a simple android game using a surfaceview similar to the lunar lander sample provided by google i want to have various things such as highscores messages menus etc pop up on screen with the surface view still in the backgroundthe problem is that i want the pop ups to contain many design elements such as images textboxes etc is there a way that i can create a layout in xml to design the pop up i want and then thisplay that over the surfaceview as one object rather than having to construct each individual element one by one in code and paint them all to the canvasi want to animate the pop ups in from the side of the screen so it would be good if i design the layout in xml so that all the object know their relation to each other and then animate that layout as one objectit strikes me as something quite simple but i just cant seem to find how to achieve it,['android'] +93423,recommendations for an experienced programmer new to javascript i come from a cunix background with a lot of experience in shell scripting and some on perl elisp etc too but now i am getting into some work where i will need to be developing interactive webbased interfaces and i need to learn javascript my problem is that all the resources i have found online for learning javascript seem to be targeted at an audience whos never programmed and their authors do not seem much better as soon as i see validating user input to take the load off your server as one of the great uses for js i want to scream and i feel like i cannot trust anything else the author says can anyone recommend good resources for an experienced programmer wanting to learn js as a new language ideally i would like to get started online but dead tree recommendations would be welcome too especially if i can preview them online,['javascript'] +93431,how to load rgb565 buffer to imageview i have file image rgb565raw which contains image buffer in rgb565 format i want this image to be thisplayed in imageview is it possible without extra code of converting to rgb8i have tried tobitmapfactoryoptions opt new bitmapfactoryoptionsoptinpreferredconfig bitmapconfigrgb 565bitmap bitmap bitmapfactorydecodefileimage 001 rgb565rawbut bitmap is nullthen i also tried to load using bytearraybitmapfactoryoptions opt new bitmapfactoryoptionsoptinpreferredconfig bitmapconfigrgb 565bitmap bitmap bitmapfactorydecodefiledecodebytearraydata 0 datalength optplease guide me to correct direction my image dimension is 160x160,['android'] +93448,generating xml document in php escape characters i am generating an xml document from a php script and i need to escape the xml special charactersi know the list of characters that should be escaped but what is the correct way to do itshould the characters be escaped just with backslash or what is the proper wayis there any builtin php function that can handle this for me,['php'] +93449,optional spring bean references in my application i am using contextloaderlistener to load context files from many jars usingcontextparam paramnamecontextconfiglocationparamname paramvalueclasspathmetainfcontextbeansxmlparamvaluecontextparamthis means i can reference beans from other jars without doing importin the application there are multiple deployment options and in some deployments jars can be excluded to support that i would like some bean references to be optional for examplebean idmainappbean classcomsomeappmyapplication constructorarg index0 reflocalbean constructorarg index1 refoptionalbeanreference1 constructorarg index2 refoptionalbeanreference2 beanin the example above i would like to have optionalbeanreference1 equal null if the reference was not found mark it optional in some waycan this be done in spring or what method do you recommend for handling dynamic references,['java'] +93456,how can i uninstall ruby on ubuntu how can i uninstall ruby 192dev 20100702 i486linuxon ubuntu need to reinstall please help,"['ruby-on-rails', 'ruby']" +93483,how to migrate a csv file to sqlite3 or mysql python i am using python in order to save the data row by row but this is extremely slowthe csv contains 70million lines and with my script i can just store 1thousand a secondthis is what my script looks likereader csvreaderopentest resultscsv rfor row in reader testresulttyperow0 namerow1 resultrow2savei reckon that for testing i might have to consider mysql or postgresql any idea or tips this is the first time i deal with such massive volumes of data,"['python', 'mysql']" +93516,how to develop plugins for the native android browser i searched the web but no luck how can plugins for the native android browser be developed neither google nor the android sdk give information about this topic,['android'] +93517,turn off ie 8 compatibility mode for site my company uses ie8 as the default browser and by default compatibility mode is set for all intranet sites i am building an intranet site that works when compatibility mode is turned off i am using resetcss and several opensource javascript programs eg datatables what i would like to do is force compatibility mode off for my site is there any programmatic way to do it i have tried setting the meta values meta httpequivxuacompatible contentieie8 and meta httpequivxuacompatible contentieedge to no availwhats the most frustrating part is that chrome and firefox work great as is,"['javascript', 'css']" +93560,async google analytics javascript golf unfortunately this may not be a valid codegolf question as it is likely javascript only however since this is likely to be the only usefulintherealworld codegolf contest i am going to go ahead and post itthe google analytics asyncronous tracking snippet is used by many websitesthe script goes a little something like thisscript typetextjavascript var gaq gaq gaqpush setaccount uax gaqpush trackpageview function var ga documentcreateelementscript gatype textjavascript gaasync true gasrc https documentlocationprotocol httpsl httpw googleanalyticscomgajs var s documentgetelementsbytagnamescript0 sparentnodeinsertbeforega s scriptwinner will be determined by the shortest raw deflate there is a difference between http 11 deflate aka zlib and raw deflate compressed code by bytecount that will load and initialize async google analytics on a pagein the case of a tie winner will be determined by raw character count if it we still have a tie well decide by last edittime submittedsome rulesthe gaq check is not required and should be removedmust be protocol aware http vs httpsmust not pollute the global namespace except for the gaq varmust be copypastable to any xhtml document ie not dependent on the pages markupmust work in all agrade browsersthis does not have to pass jslint or any html validatorsmust set the async flagmust use this deflator for the byte count of the deflatecompressed outputtipunderstand the basics of the deflate algorithm and more importantly lz77 compressionudpate 216275since my original version has been beaten i will go ahead and post it herenote this has a bug where async gets set to false for all http requestsfunctiondtg gaq setaccountuax trackpageviewgdcreateelementtgsrcgasynclocationprotocol5sslwgoogleanalyticscomgajstdgetelementsbytagnamet0parentnodeinsertbeforegtdocumentscript,['javascript'] +93564,java strange behavior with sin and toradians i have been given the task of using java to produce a sin table however i seem to get some very weird results for some values of the input i am using the belowsystemoutprintln sin currentpoint mathsinmathtoradianscurrentpointwhere int currentpoint is a value in degrees eg 90these are results i find weird sin360 24492935982947064e16 sin180 12246467991473532e16 sin150 0494 sin120 08660254037844387expectingsin360 0sin180 0sin150 05sin120 0866025404am i missing something,['java'] +93599,minimize subqueries with in queries on appengine python is there any clever way to avoid making a costly query with an in clause in cases like the following onei am using google app engine to build a facebook application and at some point i obviously need to query the datastore to get all the entities that belong to any of the facebook friends of the given usersuppose i have a couple of entities modeled as suchclass thingdbmodel owner dbreferencepropertyreference classuser requiredtrue owner id dbstringpropertyrequiredtrue andclass userdbmodel id dbstringpropertyrequiredtrue at some point i query facebook to get the list of friends of a given user and i need to perform the following query get all thing instances that belong to friendsquery thingallqueryfilterowner id in friend idsif i did that appengine would perform a subquery for each id in friend ids probably exceeding the maximum number of subqueries any query can spawn 30is there any better way to do this ie minimizing the number of queriesi understand that there are no relations and joins using the datastore but in particular i would consider adding new fields to the user or thing class if it helps in making things easier,['python'] +93613,import cannot be resolved import comgoogleandroidmaps i was successfully using google maps in my application but then needed to change the android sdk version from 15 to 20 now the import for google maps cannot be resolved,"['java', 'android']" +93639,jquery flot pie slice color i cannot figure out how to get flotpie to change the pie slice color just the series color is this possible,['jquery'] +93640,textmate jserb toggle i am using a jserb template to render some jquery when editing an htmlerb file in textmate i frequently use the convenient key combo ctrl to create and then toggle the following tags this shortcut does not work by default when editing jserb files in the bundle editor i found a snippet called insert erbas or under ruby by adding sourcejs to the scope selector i was able to get insertion to work but when i pressed the key combo multiple times instead of toggling the tag i got a tag inside of a tag like this i have tried changing the scope of the command called toggle erb tags but i cannot seem to get toggling to work any suggestionsupdate november 19 2010this is no longer a problem in the new version of textmate that came out this week 1510 1623,['ruby-on-rails'] +93641,replacing selected text in the textarea what is the best way to do this in jquery this should be a fairly common use caseuser selects text in a textarea he clicks on a link the text in the link replaces the selected text in the textareaany code will be much appreciated i am having some issues with part 3,"['javascript', 'jquery']" +93645,show first line of a paragraph i have a div with a multiline paragraphis there any way maybe using jquery to only show the first line of the paragraph and hide the others,"['jquery', 'html', 'css']" +93653,get all css attributes with jquery heres how you get one css attribute using jquerysomeobjectcssattribute how do you get them all without specifying and preferably in the following format so it can be reapplied with jquery later cssobj overflowhidden height100 positionabsolute thankseditthe methods i am trying to get are declared in a style sheet they are not inline sorry for not specifying,"['jquery', 'css']" +93655,networkx python how to change edges weight by designated rule i have a weighted graphfnxpath graph10gnxgraphfor u v in fedges gadd edgeuvweight1get the nodes list0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9i want to change each edges weight by this rule remove one node such as node 5 clearly edge 4 5 and 5 6 will be delete and the weight of each edge will turn to these edges are nearby the deleted edge 4 5 and 5 634weight1167weight11these edges are nearby the edges above mentioned23weight1278weight12these edges are nearby the edges above mentioned12weight1389weight13 this edge is nearby 1201weight14how to write this algorithmps path graph is just an example i need a program suit any graph type furthermore the program need to be iterable it means i can remove one node from origin graph each timeregards,['python'] +93711,duplicate key exception from entity framework i am trying to catch the exception thrown when i insert a already existing user with the given username into my database as the title says then i am using ef the only exception that is thrown when i try to insert the user into to db is a updateexception how can i extract this exception to identify whether its a duplicate exception or something else,['c#'] +93718,can an svm learn incrementally i am using a multidimensional svm classifier svmnet a wrapper for libsvm to classify a set of featuresgiven an svm model is it possible to incorporate new training data without having to recalculate on all previous data i guess another way of putting it would be is an svm mutable,['c#'] +93728,converting utf8 general ci tables and fields to utf8 unicode ci i have made a mistake when designing my application database several years ago and collation settings of my tables and table fields are mixed some of them are utf8 general ci and some of them are utf8 unicode cithis causes problems when joining tables with different collations now i am planning to change collation settings and make them the same utf8 unicode ci i will be running these two sql queries on all my tablesalter table table1 default character set utf8 collate utf8 unicode cialter table table1 change action action varchar 250 character set utf8 collate utf8 unicode ci not nullmy question is does running these two sql queries break any field values especially the ones which contains accented characters or is it safe to run these two querieslooking forward to hear from you thanks for your answers,['mysql'] +93729,root cause of an invalid object name dboetc error i am doing some maintenance programming on a fairly large project which was started by someone whos now left the companyi have just backed up one of the companys databases and then reattached it to our test server that much appears to be working okayi then go through the programs usual login procedure and that part also appears to workhowever once i get to a point in the program where it needs to execute a stored procedure i get back an error telling me invalid object name informixdbocustomerrunning the same function on the original database works fine and returns the data i expect to sexplanations for similar errors i have found seem to refer to schemas but that is where things get a little odd the original database does not obviously have any schemas in its security folder it just has a users folder containing dbo and a roles folder containing the database roles folder with the usual db owner etc stuff and an empty folder named application rolesthe security folder on the backedupandrestored database is full of all kinds of crap three users in addition to dbo a schemas folder certificates folder two encryption key folders i cannot delete any of thesefrom my limited understanding of the sql login system the user i am logging in as is getting nondbopermissions from this collection of random crap and so is being denied access to the parts of the database owned by dbofor my own understanding what is the core of the problem that is throwing up these invalid object name errors and for practical matters what can i do to rectify this situation and actually have the program i am using work on the test database in the same way as it does on the live one,['sql'] +93734,how can get start and end time on fullcalendar how can i get start and end time of visible days in fullcalendari need it for use in another javascript instace is there some function like calendergetstarttime,"['javascript', 'jquery']" +93739,android prompt users input using a dialog i would like to prompt the user to give me input in my android application using a dialog this is what i have foundalertdialogbuilder alert new alertdialogbuilderthisalertsettitletitlealertsetmessagemessage set an edittext view to get user input final edittext input new edittextthisalertsetviewinputalertsetpositivebuttonok new dialoginterfaceonclicklistener public void onclickdialoginterface dialog int whichbutton string value inputgettext do something with value alertsetnegativebuttoncancel new dialoginterfaceonclicklistener public void onclickdialoginterface dialog int whichbutton canceled alertshowbut this gives me androidviewwindowmanagerbadtokenexception unable to add window token null is not for an applicationis there any problem on my code it seems like a null argument is passed on the dialog but i cannot find out what is the problem,['android'] +93754,how can i add a hyperlink to a jface dialog how can i make a hyperlink in a jface dialog that when clicked opens the link in the default web browser a full example would be useful i know there is a orgeclipsejfacetexthyperlink package but i cannot find a suitable example,['java'] +93770,is rebasing dlls or providing an appropriate default load address worth the trouble rebasing a dll means to fix up the dll such that it is preferred load adress is the load address that the loader is actually able to load the dll atthis can either be achieved by a tool such as rebaseexe or by specifying default load addresses for all your own dlls so that they fit in your executable processthe whole point of managing the dll base addresses this way is to speed up application loads or so i understandthe question is now is it worth the troublei have the book windows via cc by richternazarre and they strongly recommenda making sure that the load addresses all match up so that the loader does not have to rebase the loaded dllsthey fail to argue however if this speeds up application load times to any significant amountalso with aslr it seems dubious that this has any value at all since the load addresses will be randomized anywayare there any hard facts on the procons of thisa in my wvc5th ed it is in the sections titled rebasing modules and binding modules on pages 568ff in chapter 20 dll advanced techniques,"['c++', 'c']" +93775,achieving white opacity effect in htmlcss is there a way to achieve this effect in a crossbrowser compatible way without having to prepare separated imagesbasically the frame on which text lays has a white overlay of 50 opacity i would like a solution that does not involve creating any other image in addition to the background but i do not know if it is possible,"['html', 'css']" +93783,what is the maximum length of html textbox can anyone help me with the length of maximum characters that can be contain in a normal html text box,"['asp.net', 'html']" +93795,linq way to get piecewise difference between element and next element in list is there a linq way of knowing what the next element in the sequence is while iterating as a concrete example say i have a list of ints and i want to calculate the difference between each element and its successor so for example i would like to be able to writevar mylist new listint 138210 var differences mylistselect ml mlnext ml pseudocode obviouslywhere the result i want is a list 2568 obviously this is trivial in a for loop but can anyone think of a neat oneliner in linq to do this job,['c#'] +93802,how do i return a list as a variable in python and use in jinja2 i am a very young programmer and i am trying to do something in python but i am stuck i have a list of users in couchdb using python couchdb library flask framework who have a username which is the id and email i want to use the list of email addresses in a select box in a jinja2 templatemy first problem is how to access the email addresses if i dofor user in db doc dbuser emails docemail print optionsi getso i can get my list of emails but where my brutal inexperience is showing up is that i do not know how to then use them the list only exists in the for loop how do i return that list as a useable list of variables and how do i then make that list appear in my jinja2 template in an option dropdown i guess i need a function but i am a green programmerwould so appreciate help,['python'] +93806,is it possible to check who is connected to your wireless network so after hours of research i have found nothing about this questionis it possible to see who is connected to my wireless network using cexample i have 2 laptops laptop a and laptop ba is on running my program i made andconnected to my wireless networkb is starting up and connects to my wireless network a can now see that b is connected to the wireless network through the program i madeis this possible,"['c#', '.net']" +93848,how to make shadow on borderbottom i need to apply the border shadow on borderbottom by css3 i just want to apply css3 shadow on bottom is this possible,['css'] +93860,how can i get the argument spec on a decorated function i need to determine the argspec inspectgetargspec of a function within a decoratordef decorfunc wrapsfunc def decorargs kwargs return funcargs kwargs return decordecordef my funckey1 valuefalse passi need to be able to inspect the wrapped my func and return the keyvalue arguments and their defaults it seems that inspectgetargspec does not get the proper functionfwiw i need this for some runtime inspectionvalidation and later documentation generation,['python'] +93864,how to get duration from avplayer not avaudioplayer i would like to make a uisliderscrubber for my avplayer but since this is not an avaudioplayer it does not have a built in duration any suggestion on how to create the slider for fast forward rewind and progress of the playback i read the doc on avplayer it has a built in seektotime or seektotimetolerancebeforetoleranceafter i do not really understand it would this be the answer for my slider avplayer also has addperiodictimeobserverforintervalqueueusingblock is this for getting the duration of my track can someone give me an example on how to implement this code i am not a fan of apples documentation it seems very hard to understand,"['iphone', 'objective-c']" +93865,the parameter foo should not be assigned whats the harm compare this methodvoid dostuffstring val if val null val default value lots of complex processing on val to this methodvoid dostuffstring origval string val origval if val null val default value lots of complex processing on valfor the former method eclipse emits the warning the parameter val should not be assigned whyto my eye the former is cleaner for one thing it does not force me to come up with two good names for val coming up with one good one is hard enoughnote assume there is no field named val in the enclosing class,['java'] +93908,linking with a pragma with g in visual c one may link to a library in the code itself by doing pragma comment lib libnamelib is something similar possible in g,['c++'] +93912,security and mail function in php i am using mail to send simple mails for convenience i am using a header to set a from address i wonder i can put whichever address there and pretend to be anyone i tried just towards myself for curiosity and actually it works is this normal it is the correct way to use the mail function and is there any way to recognize the identity of the sender of these mailsediti sent a mail to my self using my gmail address as from in the header of mail i received the message with these headers areceived from smartydreamhostcom smartydreamhostcom 2081131758 by mxgooglecom with esmtp id w21si2197938ybh68201010191930 tue 19 oct 2010 1930 0700 pdtreceived from nationalsdreamhostcom nationalsdreamhostcom 691631656 by smartydreamhostcom postfix with esmtp id eb56d6e804a for tue 19 oct 2010 193329 0700 pdtreceived by nationalsdreamhostcom postfix from userid 3598506 id e4bb635c83f tue 19 oct 2010 193329 0700 pdtreturnpath receivedspf pass googlecom domain of designates 2081131758 as permitted sender clientip2081131758authenticationresults mxgooglecom spfpass googlecom domain of designates 2081131758 as permitted sender smtpmail what happened i cannot interpretate headers but look like google accepted the fake address,['php'] +93921,current est time in java with daylight saving i stumbled upon this piece of code to get current time in est with daylight saving it seems to work fine when checked on the internet by the time thisplayed in sites providing current time in est with daylight saving simpledateformat dateformat new simpledateformatymdd hhmms dateformatsettimezonetimezonegettimezoneest5edt systemoutprintlndateformatformatnew datei just want to confirm has anybody used something like this before or there is a better way to achieve the same i cannot use joda library due to constraintsthanks in advance,['java'] +93943,javascript how to join combine two arrays to concatenate into one array i am trying to combine 2 arrays in javascript into onevar lines new arrayabclines new arraydefthis is a quick example i want to be able to combine them so that when the second line is read the 4th element in the array would return dhow would i do this,['javascript'] +93947,produce a random number in a range using c how do i go about producing random numbers within a range,"['c#', '.net']" +93948,how to make sure a generated guid is unique globally let us say i want to set a guid to be my applications assembly guid as searched from internet we can use new guidnext to get a new unique valuei cannot figure out how my guid is warranted to be unique against others please explain if you know how to,['c#'] +93957,android how to change the application title hi i need to change the application title as when i move to new tabi tried to change the app name with varying string in stringxml but that is not actual dynamic change that i wantis there any alternative way of doing this,['android'] +93967,how close java input streams in the following codedatainputstream in new datainputstream new bufferedinputstreamnew fileinputstreamfileinclosedo i need to close the 2 other stream in addition to closing the top level stream,['java'] +93978,net open files which are embedded in a resource file how can i open files which are embedded in a resource file like a file on the hardthisk with an absolute path,"['c#', '.net']" +93982,how to insert embed a file object into excel sheet i need to insert embed a file object txt file in ms excel sheet using javathe requirement is not to put the contents of txt file into excel instead i need to put the whole file as an embedded object into exceli am using apache poi jar for thisi have seen all the examples present in poi37beta1 but was not able to find any example to insert embed a file object in excel sheeti have seen poifsfilesystem classes but was not able to find the appropriate class to use for this problemi am facing issue in embedding file object into excel please help me doing this using apache poi or any other jar,['java'] +94009,sorting a dictionary with date keys in python i have a dictionary the keys are dates datetime i need to sort the dictionary so that the values in the dictionary are sorted by date so that by iterating through the dictionary i am processing items in the desired chronological ie datetime orderhow may i sort such a dictionary by dateexamplemydict 20101 fld 1 1 fld 2 42 20102 fld 123 fld 2 2217 note i am using strings here instead of datetime to keep the example simple,['python'] +94014,how can i list all files in a directory sorted alphabetically using php i am using the following php code to list all files and folders under the current directoryphpdirname dir opendirdirnamephpwhilefalse file readdirdiriffile and file and file indexphpechoa hreffilefilea br the problem is list is not ordered alphabetically perhaps it is sorted by creation date i am not sure how can i make sure it is sorted alphabetically,['php'] +94018,service reference error failed to generate code for the service reference i have a windows service solution and am trying to add a service reference to a hermesopensource ebms message server web service in vs2010i can find the web service using it is url but when i try and populate the service reference i get the following errors in visual studioerror 8 custom tool error failed to generate code for the service reference testservice please check other error and warning messages for details cusersadmindocumentsvisual studio 2010projectsmyprojectmyprojectmessagehandlerservice referencestestservicereferencesvcmap 1 1 myprojectmessagehandlerwarning 6 custom tool warning cannot import wsdlbindingdetail there was an error importing a wsdlporttype that the wsdlbinding is dependent onxpath to wsdlporttype wsdldefinitionstargetnamespacewsdlporttypenameebmsstatusqueryxpath to error source wsdldefinitionstargetnamespacewsdlbindingnameebmssoaphttpstatusquery cusersadmindocumentsvisual studio 2010projectsmyprojectmyprojectmessagehandlerservice referencestestservicereferencesvcmap 1 1 myprojectmessagehandlerwarning 7 custom tool warning cannot import wsdlportdetail there was an error importing a wsdlbinding that the wsdlport is dependent onxpath to wsdlbinding wsdldefinitionstargetnamespacewsdlbindingnameebmssoaphttpstatusqueryxpath to error source wsdldefinitionstargetnamespacewsdlservicenameebmsmessagestatusquerywsdlportnameebmsstatusquery cusersadmindocumentsvisual studio 2010projectsmyprojectmyprojectmessagehandlerservice referencestestservicereferencesvcmap 1 1 myprojectmessagehandlerwarning 5 custom tool warning cannot import wsdlporttypedetail an exception was thrown while running a wsdl import extension systemservicemodeldescriptionxmlserializermessagecontractimportererror schema with target namespace could not be foundxpath to error source wsdldefinitionstargetnamespacewsdlporttypenameebmsstatusquery cusersadmindocumentsvisual studio 2010projectsmyprojectmyprojectmessagehandlerservice referencestestservicereferencesvcmap 1 1 myprojectmessagehandlersome investigation seemed to suggest it is due to svcutilexe not been able to build the proxys due to not having permissions to a directory possibly cwindowstemp i have tried assigning various access permissions but i am not really sure which user needs the permission or if it is just a red herringany ideas would be greatly appreciatedthanks,"['c#', '.net']" +94019,how to delete record from table i have a problem with deleting a record from sqlite3 databaseconn sqlite3connectdatabazadbc conncursordata3 strinputplease enter name mydata cexecutedelete from zoznam where name data3conncommitccloseall is good but delete does not workhave anybody some idea,['python'] +94025,casting boolean to boolean in java i have a code aspublic class booleantest public booleantest super public static void mainstring args booleantest bt new booleantest btdoprocess private boolean method return false private void doprocess boolean obj booleanmethod systemoutprintlnobjbooleanvalue the question is can line systemoutprintlnobjbooleanvalue throw nullpointerexception in any situation,['java'] +94026,is stringutilsisnumeric method specification logically correct apache is stringutilsisnumeric method specification sayschecks if the string contains only unicode digits a decimal point is not a unicode digit and returns falsenull will return false an empty string will return trueis this logically rightwhy do they see empty string as numeric,['java'] +94032,when does nsurlconnections initwithrequest return nil does anyone know in which situations initializing a nsurlconnection returns nil instead of the created connection the documentation says it is possible but fails to specify when this happensthe methodmessage in questionnsurlconnection alloc initwithrequestrequest delegateselfaccording to the nsurlconnection class referencereturn value the url connection for the url request returns nil if a connection cannot be initializedthe url loading system programming guide says the followingif nsurlconnection canat create a connection for the request initwithrequestdelegate returns nilwhile it is possible that this method returns nil i am unable to come up with a scenario which triggers this i have tried the following scenariosurlrequest with an empty url connectiondidfailwitherror delegate method is called with unsupported url as errorurlrequest with invalid url connectiondidfailwitherror delegate method is called with bad url as errorurlrequest with nonexistent url connectiondidfailwitherror delegate method is called with a server with the specified hostname could not be found as errorvalid request but no internet connectiondidfailwitherror delegate method is called with the internet connection appears to be offline as errornil request causes a crashthe initwithrequest method returned a valid nsurlconnection in each scenario besides the last one and called the connectiondidfailwitherror with an appropriate errorhas anybody been able to figure out which scenario does cause nil to be returned,"['iphone', 'ios']" +94033,are there any c facial recognition libraries that work are there any c facial recognition libraries that work i would like to locate people in my data base by having them stare in a camera this is not used for security or authentication just to help with a quick lookup so if it is good enough to narrow down a list of people that would be a win,['c#'] +94047,java set interface and collection interface differences i just looked up the set interface and found that it mostly or completely only redeclares functions which are already in the collection interface set itself extends collection so does not that mean that the set interface automatically has all the functions from collection so why are they redeclared thenfor example set redeclares this returns the number of elements in this set its cardinality if this set contains more than ttintegermax valuett elements returns ttintegermax valuett return the number of elements in this set its cardinality int size returns truett if this set contains no elements return truett if this set contains no elements boolean isemptyand the declaration in collection returns the number of elements in this collection if this collection contains more than ttintegermax valuett elements returns ttintegermax valuett return the number of elements in this collection int size returns truett if this collection contains no elements return truett if this collection contains no elements boolean isemptythis seems very redundant to me why not just define the set interface aspublic interface sete extends collectione i think there is no single difference between those interfaces rightof course i am not asking about the different semantics meaning of set i know that i am just asking about if it technically ie to the compiler has any difference ie speaking generallyinterface a a void foo interface b extends a void foo interface c extends a now is there any difference between a b or cwhile the contract ie what is said in the documentation can really be different for some functions as for add there is a valid reason to redeclare them to be able to put a new documentation ie to define the new contracthowever there are also functions like isempty which have exactly the same documentation contract why are they also redeclared,['java'] +94048,statistical analysis for php i am trying to write a reporting system for a project i am working on that analyzes peoples pre and post test scores and does some analysis on it i have searched to the best of my ability but cannot find a php class set of functions that seems to do the analysis i needcurrently i am dumping the dataset to a csv and one of my coworkers is running it through spss to perform a pairedsamples ttest that is the analysis i need run as we need the pvaluei know that there is this class in php however none of that seems to be documented to the point that i can understand iti do not mind having to write the analysis myself but if it already exists i would like to avoid reinventing the wheelthanks for any help,['php'] +94062,iframe and conflicting absolute positions i would like to have an iframe dynamically sized using the following cssmyiframe position absolute top 0 bottom 0 left 0 right 0however no browser seems to support thisin good browsers i could wrap the iframe in a div with the quoted css style and set the height width of the iframe to 100 but this does not work in ie7 short of using css expressions has anyone managed to solve thisupdatematthecat answered with a scenario that works if the iframe is located directly under the body and the bodyhtml tags have height 100 set in my original question i did not state where the iframe was and what styling applied to it is container hopefully the following addresses thishtml body div idcontaineriframe idmyiframeiframediv bodyhtmland let us assume the following container csscontainer position absolute top 10px bottom 10px left 10px right 10pxif you now place height 100 on the iframe it will not size correctly,['css'] +94063,wcf exception handling if an exception occurs in my wcf service what is the best way to communicate that error to the clientshould i log it on the service and rethrow a soap exceptionor should i log it and return a user friendly message,['c#'] +94078,how can i prefetch a memory region most easily background i have implemented a stochastic algorithm that requires random ordering for best convergence doing so obviously destroys memory locality however i have found that by prefetching the next iterations data the performance drop is minimizedi can prefetch n cache lines using mm prefetch in a simple mostly oscompilerportable fashion but whats the length of a cache line right now i am using a hardcoded value of 64 which seems to be the norm nowadays on x64 processors but i do not know how to detect this at runtime and a question about this last year found no simple solutioni have seen getlogicalprocessorinformation on windows but i am leery of using such a complex api for something so simple and that would not work on macs or linux anyhowperhaps there is some entirely other apiintrinsic that could prefetch a memory region identified in terms of bytes or words or whatever and allows me to prefetch without knowing the cache line lengthbasically is there a reasonable alternative to mm prefetch with define cache line len 64,['c++'] +94079,thisable background drawing in jframe in order to properly thisplay aero dwm effects i am having problems using the dwm functionality of windows vista7 on java windows i want to make the background of my frame use the aero style the windows api to do so is provide by the function dwmextendframeintoclientarea in the dwmapi library i have managed to call the procedure properly via jna and it does what it is supposed to do you can see that for example when resizing the frame before the next repaint you see the proper aero effects in the area not yet painted see the attached imagebut somewhere i cannot figure out where a background is painted over the aero effect and the effect is lostwhat i have already triedusing a custom contentpane with opacity set to falsesetting the opacity of the layeredpane and the rootpane to falseusing a frame instead of a jframeset the background color of the jframecontentpane to blackfully transparentuse setlayersopaque and a custom variant thereof see first answer for more detailsso far i could not succeed removing that background is it a limitation of awtswing how can i remove that background or use the aero effect properlyyour help is greatly appreciatedscreenshothere a screenshot of a frame without any contents having set the opacity of the rootpane layeredpane and contentpane to false i did it quickly while resizing you see that the effect is properly applied to the area java did not yet paint on as a new user i cannot post the image directlyodd behaviorupon further investigation i came across the following odd behavior if the window size is 150x150 or below the contents are thisplayed transparently this is very glitchy for normal window components if you paint directly on the frame by overriding the paint method everything is drawn semitransparent additionally the coordinate system seems to be a little off it appears as the zero point of the jframe is set to the actual zero point of the window thus swing tries to paint to areas where actually the window border is located which then of course is not visiblesee this screenshot aero bugpngexample codethis is the code i userequires jnajar and platformjar available from the jna homepageimport comsunjnafunctionimport comsunjnanativeimport comsunjnanativelibraryimport comsunjnastructureimport comsunjnaplatformwin32windefhwndimport comsunjnaplatformwin32winnthresultimport javaxswingjframeimport javaxswingjlabelimport javaxswinguimanagerpublic class aeroframe extends jframe public aeroframe setdefaultcloseoperationjframeexit on close jlabel label new jlabeltestlabel labelsetopaquefalse addlabel pack enableaeroeffect private void enableaeroeffect nativelibrary dwmapi nativelibrarygetinstancedwmapi hwnd aeroframehwnd new hwndnativegetwindowpointerthis margins margins new margins marginscxleftwidth 1 marginscxrightwidth 1 marginscybottomheight 1 marginscytopheight 1 dwmextendframeintoclientareahwnd hwnd margins pmarinset function extendframeintoclientarea dwmapigetfunctiondwmextendframeintoclientarea hresult result hresult extendframeintoclientareainvokehresultclass new object aeroframehwnd margins ifresultintvalue0 systemerrprintlncall to dwmextendframeintoclientarea failed public class margins extends structure implements structurebyreference public int cxleftwidth public int cxrightwidth public int cytopheight public int cybottomheight public static void mainstring args try uimanagersetlookandfeeluimanagergetsystemlookandfeelclassname jframesetdefaultlookandfeeldecoratedtrue catch exception e eprintstacktrace new aeroframesetvisibletrue,['java'] +94084,rails delayed job memory consumption problem were having huge problems with the delayed job plugin jobwhen we start tasks with ruby scriptdelayed job start the process never lets go of ram it acquiresso it starts with 10 25 gets to 80 and never lets go of the ram even if it has no jobs to processany ideas how we can get over thisthanksps rails envproduction scriptdelayed job start did not work for us to start the delayed job worker,['ruby-on-rails'] +94095,counter cache in single table inheritance i am wondering if the counter cache would work in single table inheritancefor these modelsclass user has many questionsendclass question belongs to user counter cache trueendclass simplequestion questionendclass complexquestion questionendso will the following counters workcreate tableusers do t tinteger questions count tinteger simple questions count tinteger complex questions countendall of them worknone of them workonly questions count workonly simple questions count and complex questions countwhich one i am guessing the 3rd but i want 4 more if it is not 4 how do i make 4 work update here is an exampleid user id question content type1 3 something simplequestion2 3 something simplequestion3 3 something complexquestionso now i wantuserquestions count 3usersimple questions count 2usercomplex questions count 1my question is whats the basic behavior of counter cache true and is it possible to apply on single table inheritance,['ruby-on-rails'] +94121,datagrid row content vertical alignment i have a regular datagrid from wpf 40 rtm where i put data from a database in order to make clean light style of datagrid i use a tallhigh rows and by default datagrid aligns row content in top vertical position but i want to set a center vertical alignmenti already tried to use this property verticalalignmentcenterin datagrid options but it does not help mehere is an example of xamlcode describing my datagrid without center vertical alignmentdatagrid xnamecontentdatagrid stylestaticresource contentdatagrid itemssourcebinding roweditendingcontentdatagrid roweditendingdatagridcolumns datagridtextcolumn headeruserid width100 isreadonlytrue bindingbinding pathuserid datagridtextcolumn headerusername width100 bindingbinding pathusername datagridtextcolumn headeruseraccesslevel width100 bindingbinding pathuseraccesslevel datagridtextcolumn headeruserpassword width bindingbinding pathuserpassword datagridcolumnsdatagridresult of executing this codeas you can see all rows content has top vertical alignwhat do i have to add in order to get center vertical alignment of each row contentthanks,['c#'] +94123,why does collectionsshuffle fail for my array why does my code not workpackage generatinginitialpopulationimport javautilarraysimport javautilcollectionspublic class testshuffle public static void mainstring args int arr new int10 for int i 0 i arrlength i arri i collectionsshufflearraysaslistarr for int i 0 i arrlength i systemoutprintarri the result is 0 1 2 3 4 5 6 7 8 9i was expecting a randomly shuffled sequence,['java'] +94127,refresh ui with a timer in wpf with backgroundworker we have an application in wpf that shows data via observablecollection after 5 minutes i want to refresh the datai thought i could use the systemtimerstimer object for its elapsed event and then call a backgroundworker to call the method that starts the job the method is on a viewmodel classbut it seems that there is a problem the threadsso i tried with the thispatcher but same thing againheres my simplified and not optimized code summary initializes a new instance of the see crefapplicationcontroller class summarypublic applicationcontroller createdefaulttabs timer timer new timer20 20 secs for testing purpose timerautoreset true timerenabled true timerelapsed new elapsedeventhandlerontimebeforerefreshelapsed timerstartprivate void ontimebeforerefreshelapsedobject sender elapsedeventargs e thispatchercurrentthispatcherinvokenew action refreshdata thispatchercurrentthispatcherinvokenew action updatelayout private void refreshdata foreach object tab in tabitems if tab is titledetailsview titledetailsviewmodel vm titledetailsviewtabdatacontext as titledetailsviewmodel vmrefresh private void updatelayout foreach object tab in tabitems if tab is titledetailsview titledetailsviewmodel vm titledetailsviewtabdatacontext as titledetailsviewmodel vmhandlegettitlebysymbolresponse any suggestions on how i should proceed,['c#'] +94148,what does typedef void something mean i am trying to understand what this means the code i am looking at hasin htypedef void mcbstatic mcb m processin cmcb modesm process nulland sometimes when i dom processi get segmentations fault it is probably because the memory was freed how can i debug when it gets freedi hope my questions are clear,['c++'] +94150,creating an arraylist of objects so now i have figured out how to make multiple of the same object correctly i need to know how to make an array of them changing depending on how many are needed because it is pretty much an object that stores 3 numbers how can i create an arraylist that is of different objects because i am going to have the numbers inside them different,"['java', 'android']" +94158,jquery widget create or init some jquery plugin extend widget use create method while others use init method can someone explain the differences between the twoalso any guidance on when it is better to extend widget or directly extend jqueryfn,['jquery'] +94160,javaxvalidationvalidationexception unable to find default provider i am currently working on spring mvc web app and trying to hook up validation using the valid annotation when i fire up the application i am getting the following exceptionjavaxvalidationvalidationexception unable to find a default provideri have hibernate validator 310ga on the classpath as well as javax validation 100ga hibernate core 331ga and hibernate annotations 340gais there an incompatiblity in those versions that i am not seeing or can anyone think of any reason why i am still getting this exception with hibernate validator on the class pathcheerscaps,['java'] +94164,find and replace in multiple files ok whats the best solution in php to search through a bunch of files contents for a certain string and replace it with something elseexactly like how notepad does it but obviously i dont need the interface to that,['php'] +94167,could not establish secure channel for ssltls for soap call our core server is calling out to a soap web service over https on a number of different servers to confirm that a transaction has completedthe code is dotnet 35 vb and works for the various callback services we have set up until we just moved a new one into production and it is refusing to communicate giving the following errorunhandled exception systemservicemodelsecuritysecuritynegotiationexceptioncould not establish secure channel for ssltls with authority wxyzzycom systemnetwebexception the request was aborted could not create ssltls secure channelat systemnethttpwebrequestgetresponseat systemservicemodelchannelshttpchannelfactoryhttprequestchannelhttpchannelrequestwaitforreplytimespan timeoutthe relevant piece of code would seem to bedim epaddr as new systemservicemodelendpointaddresyscallbackaddressdim bind as new systemservicemodelbasichttpbindingservicemodelbasichttpsecuritymodetransport svc new callbacksvcxyzzycallbacksoapclientbind epaddrfrom my personal laptop winxp i can run the code and it connects to the new server without issuesfrom the main server which calls all the callback services windows server enterprise service pack 1 the code always results in the aforementioned ssl errorafter googling the issue i tried adding the following line certainly not suitable for production but i wanted to testsystemnetservicepointmanagerservercertificatevalidationcallback functionse as object cert as systemsecuritycryptographyx509certificatesx509certificate chain as systemsecuritycryptographyx509certificatesx509chain sslerror as systemnetsecuritysslpolicyerrors truethe result was the same the ssl error still occurredother places suggest the root cert has not be installed correctly on the calling machine but both the new server and old callback servers use certs issued by go daddy so i do not think this is the case here,['.net'] +94170,calculating bytesize of java object i am working on calculaitng the size memory used of a java object hashmap it contains elements of different data types at runtime so noofelem sizeofelement is not that good an approach the code right now does it by series of if x do somethingelse if primitives lookup size and calculatehowever this process is a cpu hog and inefficient i am thinking of following 2 approaches insteadserialize the object to a buffer and get the size look into javalanginstrument to get the sizei am looking for anyones experience with these approaches for performance efficiency scaling etc or if you know any better waypsthis is a background utility that i am building so the size need no be super accurate though it should be about correct so i am willing to trade accuracy for performancei am not interested in the deepsize the size of objects that are refered by this object will not be computedi am looking for a performance comparisons and understanding how getobjectsize works internally so that i do not messup something else to improve the performancethanks,['java'] +94177,is there any reason for using classes in python if there is only one class in the program i have seen some people writing python code by creating one class and then an object to call all the methods is there any advantage of using classes if we do not make use of inheritance encapsulation etc such code seems to me less clean with all these self arguments which we could avoid is this practice an influence from other programming languages such as java or is there any good reason why python programs should be structured like thisexample codeclass app all the methods go herea app,['python'] +94180,probability in javascript help sorry i am new to js and cannot seem to figure this out how would i do probabilityi have absolutely no idea but i would like to do something out of 100 chance maybe 07 chance to execute function e and 30 chance to execute function d and so on they will add up to 100 exactly with a different function for each but i have not figured out exactly how to do this in any form what i found is mostly strange high school math tutorials powered by javascriptkit or something,['javascript'] +94206,download multiple files as zip in net i have a file list with check box for each files if the user checks many files and click download i have to zip all those files and download it like in mails attachments i have used the code mention in this post for single file download pls help how to download multiple files as zip,"['c#', '.net']" +94266,phpmyadmin alternative ajax excellike if i searched for phpmyadmin and excel i get answers like hot wo import excelfilesi searched for a phpmyadminalternative that works faster with ajax and i want to edit once fields directly like excel click and edit via ajax i dont like to click the row and say now edit then edit and click ok return and new loading to edit only one field i hope you have answers for me,"['php', 'mysql']" +94282,sorted dataview to datatable i have the following methodprivate datatable getsortedtabledatatable dt dtdefaultviewsort name desc i would need to return the datatable sortedmy issue is that i cannot change the return type of this method and i have to return a datatable but i would like return it sortedare there any magic hidden property of dtdefaultview to return the dt sortedthanks a lot in advancebest regards,"['c#', 'asp.net']" +94311,java generics template specialization possible overriding template types with specific types i am wondering what are the options to specialize generic types in java ie in a templated class to have specific overrides for certain typesin my case i was a generic class of type t to return null usually but return the empty string when t is the string type or 0 zero when its the integer type etcmerely providing a typespecific overload of a method produces a method is ambiguous erroregpublic class hacking public static void mainstring args barinteger barint new barinteger barstring barstring new barstring ok returns null systemoutprintlnbarintgetnew integer4 error the method getstring is ambiguous for the type barstring systemoutprintlnbarstringgetnew stringfoo public static class bart public t gett x return null public string getstring x return is the only option to subclass the generic class with a specific type see stringbar in the following example public static void mainstring args barinteger barint new barinteger stringbar barstring2 new stringbar ok returns null systemoutprintlnbarintget ok returns systemoutprintlnbarstring2get public static class bart public t get return null public static class stringbar extends barstring public string get return is this is the only way it is a bit of a pain to have to create a subclass for every type i want to specialize instead of an overload of get in the bar classi am guessing i could check the instanceof in the barget method eg t gett t if t instanceof string return if t instanceof integer return 0 else return null however i have been taught to avoid instanceof and use polymorphism when possible,['java'] +94340,how can i speed up mysql query with multiple joins here is my issue i am selecting and doing multiple joins to get the correct itemsit pulls in a fair amount of rows above 10 this query takes more than 5mins when the date range is set to 1 yeari do not know if it is possible but i am afraid that the user might extend the date range to like ten years and crash itanyone know how i can speed this up here is the queryselect thistinct t1first name t1last name t1email from table1 as t1 inner join table2 as t2 on t1cu id t2o cid inner join table3 as t3 on t2o ref t3i oref inner join table4 as t4 on t3i pid t4p id inner join table5 as t5 on t4p cat t5c id where t1subscribe 1 and t1cdate startdateand t1cdate enddateand t5store 2i am not the greatest with mysql so any help would be appreciatedthanks in advanceupdatehere is the explain you asked forid select type table type possible keys key key len ref rows extra1 simple t5 ref primaryc store typec idc store type 2 c store type 2 1 const 101 using temporary1 simple t4 ref primaryp cat p cat 5 alphacomt5c id 326 using where1 simple t3 ref i pidi oref i pid 4 alphacomt4p id 31 1 simple t2 eq ref o refo cid o ref 28 alphacomt3i oref 1 1 simple t1 eq ref primary primary 4 alphacomt2o cid 1 using wherealso i added an index to table5 rows and table4 rows because they do not really change however the other tables get around 50010 entries a month i heard you should add an index to a table that has that many new entriesis this true,"['sql', 'mysql']" +94343,uitableview footerview with button button does not work i am trying to create a custom view for my uitableview footerview that has a button in it i can see it there but when i touch it nothing happens can you see whats wrong here voidviewdidload super viewdidload ifselftableviewtablefooterview nil allocate the view if it does not exist yet uiview footerview uiview alloc init create the button uibutton addnewbtn uibutton buttonwithtypeuibuttontypecustom the button should be as big as a table view cell addnewbtn setframecgrectmake0 0 320 addmerchanttvc cellheight set title font size and font color addnewbtn settitleadd new forstateuicontrolstatenormal addnewbtntitlelabel setfontuifont boldsystemfontofsize20 addnewbtn settitlecoloruicolor blackcolor forstateuicontrolstatenormal addnewbtn addtargetself actionselectoraddnew forcontroleventsuicontroleventtouchupinside uiimageview cellgradient uiimageview alloc initwithimageuiimage imagenamedcellgradientpng cellgradientframe cgrectmake0 54 320 16 footerview addsubviewcellgradient add the button to the view footerview addsubviewaddnewbtn footerviewuserinteractionenabled yes selftableviewtablefooterview footerview selftableviewtablefooterviewuserinteractionenabled yes footerview release cellgradient release voidaddnewidsender this is never called nslogtouched,['iphone'] +94345,print a histogram based on word lengths c this is a kr exercise 113write a program to print a histogram of the length of words in its input it is easy to draw the histogram with bars horizontal a vertical orientation is more challengingthe section was about arrays and to be honest i am not sure i fully understood it everything up to this point was fairly easy to grasp this was notanyway i am trying to do a histogram with horizontal bars first once i got that down i will try vertical but right now i am not even sure where to begin with the easy version i slept on it woke up and still could not get iti drew an example of what the program would output001xx002x003x004x005x006x007x008009x010x10xand tried to break it the program down in sections this is what i came up withprint top borderprint category print x each time condition is true print newline repeatprint bottom borderbut the more i think about it the less i think that is how it would work because getchar goes through one character at a time and it wouldnt be able to go back up to put a x in the right category or i am just really confused as to how i would solve this problem heres as far as i have been able to get code wiseinclude stdiohdefine maxwordlength 10 print a histogram of the length of words in input horizontal bar versionint mainvoid int c while c getchar eof return 0could someone help enlighten me not necessarily with the code maybe just pseudo code or with some words from the wise as to what i need to do or think or something this has just been a really big stone in the road and i would like to get past it i will check back in 30 minutes,['c'] +94356,how to show marker in maps launched by geo uri intent i have a application where i want to show different locations one at the time picked by user input by launching google maps with their specific geocoordsi am currently using this with real lat and long values of courseintent intent new intentintentaction view uriparsegeolatlongz17startactivityintentit is quite exactly what i want except that it does not show any indicator or marker for the specified point it only centers at it is locationis there some way to get the marker or something else included without using a mapview,['android'] +94362,create new window using jquery i am working on a little project in javascriptjquery in order to thisplay results from a calculation done in javascript i would like to open a new window with some predefined content and modify this content in order to thisplay the results im using code like thisvar resultwindow windowopenresulthtmlvar doc body resultwindowdocumentdocappendpresultpthis is not working since the result document is not yet loaded when i append the content so it is overwritten with the contents of resulthtmli also triedresultwindowdocumentreadyfunction fill result document hereandresultwindowdocumentloadfunction fill result document herebut ready works only on the current document it is called immediately if the current document is already loaded and load does not get called at allperhaps someone can point me to the right direction thanks in advanceediti finally solved this by creating the new document by hand in javascript likew windowopennewwinowwidth800height600menubar1status0scrollbars1resizable1d wdocumentopentexthtmlreplacedwritelnhtmlhead link relstylesheet typetextcss hrefstylecshead bodybodyhtml use d to manipulate dom of new document and thisplay resultsif i were to do the same thing today two years of experience later i would use some javascript template library like handlebars to maintain a template and compile it to javscript,"['javascript', 'jquery']" +94367,password with a colon fails basic auth i am using basic auth if my password contains a colon i seem to get a failure to authenticate are colons not allowed in a password how i am authenticatingdefaulthttpclient client new defaulthttpclienthttprequestinterceptor preemptiveauth new httprequestinterceptor clientaddrequestinterceptorpreemptiveauth 0clientgetcredentialsprovidersetcredentials new authscopeexamplecom 443 new usernamepasswordcredentialsme passwordtestpasswords without a colon always work passwords with a colon always fail do i have to escape the password somehow before handing it to the usernamepasswordcredentials class constructor i know basicauth uses the usernamepassword separated by a colon then base64 encoded is that what the problem is herethanks update thanks all yes was a problem in the server i was communicating with,['java'] +94371,could you share a link to an url parsing implementation as far as i understand an url consists of the folowing fieldsprotocol http https ftp etcuser nameuser passwordhost address an ip address or a dns fqdnport which can be impliedpath to a document inside the server documents rootset of arguments and valuesdocument part asprotocoluserpasswordhostportpathdocumentarg1val1arg2val2parti need a code to get value or nullempty value if not set of any of these fields from any given url string am i to implement this myself or there is already a code for this so i do not need to invent a wheeli am particularly interested in scala or java code c php python or perl code can also be useful,['java'] +94375,how can i make short random unique keys like youtube video ids in php is there any way to create unique keys like those used in youtube video urls ex,['php'] +94383,python 27 themed common dialog tkinter interfaces via ttk python 27 32bit windows were experimenting with python 27s support for themed tkinter ttk for simple guis and have come away very impressed the one area where the new theme support seems to have come up short is how os specific common dialogs are wrappedcorrected in other words the messagebox and colorchooser common dialogs have ugly looking win 95 style blocky looking buttons vs the themed roundedgradient buttons that normally show up on these common dialogs under xp vista and windows 7 i am testing on all 3 platforms with identical unthemed resultsnote the filedialog common dialogs askopenfilename askopenfilenames asksaveasfilename askdirectory are all properly themedimport tkmessagebox as messageboxmessageboxshowinfoimport tkcolorchooser as colorchoosercolor colorchooseraskcolor parentroot titlecustomize colors any ideas on whats required to get tkinters messagebox and colorchooser common dialogs to be os theme compatible at least under windows xp or higher,['python'] +94385,is it possible to extend net framework namespace like one can extend net framework class it is possible to extend a class like string see is there a way to extend in a similar way systemweb for example by adding our own classes to this namespace,['c#'] +94387,how do i render a jquerytmpl template to a string the documentation for jquerytmpl uses appendto to insert the template into the dom during the rendering processtmpl mytemplate mydata appendto target i am attempting to convert an existing app from another templating engine and my code needs to render a template into a string first before it is added to the dom is this possible how would that be done,['jquery'] +94404,simple text to html conversion i have a very simple asptextbox with the multiline attribute enabled i then accept just text with no markup from the textbox is there a common method by which line breaks and returns can be converted to p and br tags i am not looking for anything earth shattering but at the same time i do not just want to do something likehtmlinsert0 phtmlreplaceenviromentnewline enviromentnewline pphtmlreplaceenviromentnewline brhtmlappendpthe above code does not work right as in generating correct html if there are more than 2 line breaks in a row having html like brpp is not good the br can be removed,"['c#', 'html']" +94429,static pages in rails so i am wondering what the best way to do static pages in rails is or rather rails 3 i have always been a little confused about this like should i create a controller or not,['ruby-on-rails'] +94432,android how to get the time from a timepicker when it is typed in i have got a dialogpreference which implements a simple timepickerontimechangedlistener see below setting the time by clicking the buttons works great but i do not know how to save the state of the timepicker when the user typed in the time directly into the textfield it could be sufficient to access to the current textfield value so i would be able to persist it in ondialogclosed but timepickergetcurrenthour would not do it please helppublic class timepreference extends dialogpreference implements timepickerontimechangedlistener overridepublic void ontimechangedtimepicker view int hours int minutes selectedhours hours selectedminutes minutesoverridepublic void ondialogclosedboolean positiveresult ifpositiveresult string timestring selectedhours selectedminutes ifispersistent persiststringtimestring,['android'] +94435,c inline member function in cpp file i know that inline member functions by definition should go into the header but what if it is not possible to put the implementation of the function into the header let us take this situationfile ahpragma onceinclude bhclass a b bfile bhpragma onceclass a forward declarationclass b inline a getadue to the circular include i have to put the implementation of geta intobcppinclude bhinclude ahinline a bgeta return awill the compiler inline geta if so which inline keyword is the significant one the one in the header or the one in the cpp file is there another way to put the definition of an inline member function into its cpp file,['c++'] +94451,ruby on rails 3 and how to make web service i tried to make this to work but i got uninitialized constant actionwebservice error when i use standard old actionwebservice but if i install datanoises actionwebservice gem i cannot settup project properly to use them in gemfile with gem bundlerthere is a alternative someone make this think to work,['ruby-on-rails'] +94455,django how to override unique together error message in a models meta class i define a unique together i have a modelform based on this model when i call is valid on this modelform an error will automatically raised if unique together validation fails that is all goodnow my problem is that i am not satisfied with the default unique together error message i want to override it how can i do that for a field related error i can easily do that by setting error messages on the field parameters but unique together is a non field error how can i override a non field error message,['python'] +94477,php function to replace a ithposition character is there a function in php that takes in a string a number i and a character x then replaces the character at position i with xif not can somebody help me in implementing it,['php'] +94480,c4503 warnings how do i solveget rid of them it is my first time trying out c stl i am trying to build a multidimensional associative array using map for exampletypedef struct da string read mode string data type void pvalue void pvarmemlocdaint main mapstring mapstring mapstring mapstring mapstring da data datalvl1stg1flr1dep1rom1 new da datalvl1stg1flr1dep1rom2 new da datalvl1stg1flr1dep1rom3 new da ieclvl1stg1flr1dep1rom1read mode file ieclvl1stg1flr1dep1rom2read mode poll ieclvl1stg1flr1dep1rom3read mode report return 0when compiling the code above in vs2005 i got 170 of c4503 warningsall of the warnings are about decorated name length exceeded name was truncatedthe program seems to run fine thoughanyone care to spare some time to explain to me what caused these warnings and how do i solve em thanks in advance warning 1 warning c4503 stdmap kty tymap decorated name length exceeded name was truncated cprogram filesmicrosoft visual studio 8vcatlmfcincludecstringth 2121warning 2 warning c4503 stdmap kty tymap decorated name length exceeded name was truncated cprogram filesmicrosoft visual studio 8vcatlmfcincludecstringth 2121warning 3 warning c4503 stdmap kty tyoperator decorated name length exceeded name was truncated cprogram filesmicrosoft visual studio 8vcatlmfcincludecstringth 2121warning 4 warning c4503 std tree traits tree decorated name length exceeded name was truncated cprogram filesmicrosoft visual studio 8vcatlmfcincludecstringth 2121warning 5 warning c4503 stdmap kty tyoperator decorated name length exceeded name was truncated cprogram filesmicrosoft visual studio 8vcatlmfcincludecstringth 2121warning 6 warning c4503 std tree traitsiteratoriterator decorated name length exceeded name was truncated cprogram filesmicrosoft visual studio 8vcatlmfcincludecstringth 2121warning 7 warning c4503 std tree traitsiteratoriterator decorated name length exceeded name was truncated cprogram filesmicrosoft visual studio 8vcatlmfcincludecstringth 2121,['c++'] +94491,how to execute jobs just after spring loads application context i want to run some jobs just after loading the spring context but i do not know how to do thisdo you have any idea how to do that,['java'] +94494,finding max element of a vector where a member is used to decide if its the maximum consider a class a having a member x and a stdvector a now its a common task to search for the maximal x among all elements inside the vector clearly i can only use stdmax element if there is an iterator on the xs but i must write one by my own or i just make a simple for loopmaxsofar stdnumeric limits double maxfor stdvector a const iterator cit asbegin cit asend cit if citx maxsofar maxsofar citxbut it is so tedious and i am so lazy is there a better option,['c++'] +94496,why can we delete arrays but not know the length in cc possible duplicatec programming how does free know how much to free how is is that it is possible for us to delete dynamically allocated arrays but we cannot find out how many elements they have cannot we just divide the size of the memory location by the size of each object,"['c++', 'c']" +94526,using real world units instead of types i have a project with many calculations involving a lot of real world units thistancetemperatureflow ratethis project involves complicated and numerous calculation formulasthat is why i supposed the use of custom types like temperature thistance can be good for code readability for exampletemperature x 553meter y 3orvar x new temperature553i tried to make a temperature class that uses a double internal valuepublic class temperature double value doublenan public temperature public temperaturedouble v value v public static implicit operator temperaturedouble v return new temperaturev but class are nullable this mean that something like temperature mytempis correct and will be null i dont want this i dont want to use structs because they are too limited they cannot use parameterless constructor nor instance field intializers like double value doublenan to define a default value i wand default underlying double value to be nanthey cannot inherits from classes they only can implement interfacesthem i wonder whether there is a way to tell ctemperature mytemp 23k c does not implement anything to make k unitbut i know c does not handle no custom unitstemperature mytemp new kelvin23 this might workso i imagine i could create two celsius and kelvin classes that inherits from temperature and then i started to wonder if the idea really worth it because it involves a lot of coding and testingthat is the thiscussion i would like to start would the use of real world units in my code instead of net types would be a good thing or not did anyone this already what are the pitfalls and the best practices or should i better keep stay away from this and use standard net types,['c#'] +94528,casting one c structure into another i have two identical but differently named c structurestypedef struct double x double y double z cmaccelerationtypedef struct double x double y double z vector3dnow i want to assign a cmacceleration variable to a vector3d variable copying the whole struct how can i do thisi tried the following but get these compiler errorsvector acceleration incompatible typevector vector3dacceleration conversion to nonscalar type requestedof course i can resort to set all members individuallyvectorx accelerationxvectory accelerationyvectorz accelerationzbut that seems rather inconvenientwhats the best solution,['c'] +94553,jpa criteria tutorial i have been trying to find a jpa criteria api tutorial but have not been much successful do you know about any for beginners i would like to start using it in an java5maven app to build complex search queries,['java'] +94571,can we create static array with a size that is an executetime constant we all know the basic rules for static arrayint size 20char myarraysizeis not legalandconst int size 20char myarraysizeis okbut what about thisint fconst int size char myarrsizevoid main f2 f1024msvc says it is an error gcc seems to compile and execute it fineobviously it is not portable but should it be acceptedwhich compiler does the right thing in that situationalso if it is permited by the compiler should it be permited by good programming standardspracticeeditedthe idea is that i would want stack allocation for the speed but i would not know at compile time the size of the arrayi know that there is some other solutions and that stack alloc would probably not be a significative optimization but i think it is an interesting usage,['c++'] +94584,how can i unzip a specific folder how can i unzip a specific folder with antspecifically i have downloaded apachetomcat6029zip which contains the folder apachetomcat6029 i want ant to unzip everything under apachetomcat6029 but not include apachetomcat6029 in the top of hierarchy i have tried a bunch of things but i cannot seem to get it to workheres my latest attemptunzip destreleasedirimagetomcat srctomcatzip patternset include nameapachetomcat6029 patternsetunzipany ideas,['java'] +94605,data structure for a random world so i was thinking about making a simple random world generator this generator would create a starting cell that would have between one and four random exits in the cardinal directions something like a maze after deciding those exits i would generate a new random cell at each of those exits and repeat whenever a player would get near a part of the world that had not yet been generated this concept would allow a infinite world of sorts all randomly generated however i am unsure of how to best represent this internally i am using c which does not really matter i could implement any sort of data structure necessary at first i thought of using a sort of directed graph in which each node would have directed edges to each cell surrounding it but this probably would not work well if a user finds a spot in the world backtracks and comes back to that spot from another direction the world might do some weird things such as generate two cells at one locationany ideas on what kind of data structure might be the most effective for such a situation or am i doing something really dumb with my random world generationany help would be greatly appreciatedthankschris,['c++'] +94613,error field has an incomplete type quaternionh15 error field ava has incomplete typehi i am stuck on an error that i cannot seem to solvebelow is my codeifndef quaternion hdefine quaternion hinclude vec3hclass vec3class quaternionpublic quaternionvec3 v quaterniondouble w vec3 v vec3 v this is where the error is double scalar quaternion operator quaternion s quaternion conjugateendifmy vech looks like thisifndef vec3 hdefine vec3 hinclude pointhinclude quaternionhinclude mathhclass quaternionclass vec3 friend ofstream operator ofstream output const vec3 p friend ifstream operator ifstream input vec3 p public vec3 vec3double x double y vec3double x double y double z double xyz operators vec3 operator vec3 a const vec3 operator double s const vec3 operator double s const vec3 operator quaternion q const used to do vector vec3 addition vec3 operator vec3 a const point operator point a const vec3 operator point a vec3 crossproductvec3 v1 itself cross v1 double dotproductvec3 v double length void normalizeendifthanks for the help again,['c++'] +94616,memory fences need help to understand i am reading memory barriers by paul e mckenneyeverything is explained in great details and when i see that everything is clear i encounter one sentence which stultifies everything and make me think that i understood nothing let me show the examplevoid foovoid a 1 1 b 1 2void barvoid while b 0 continue 3 asserta 1 4let us say this two functions are running on a different processorsnow what could possibly happen is store to a 1 could be seen after store to b 2 by the second processor because first processor queues store to a and proceed to store b instruction ok that is fine we add a write fence in the line between 1 and 2 but this code still can fail because second processor might queue the invalidate message so we add one more memory fence read fence this time in the line between 4 and 4void foovoid a 1 1 write memory barrier b 1 2void barvoid while b 0 continue 3 read memory barrier asserta 1 4this enforce second processor to process all queued messages invalidate a and read it again by sending read mesi message to first processor on 4 ok next the article saysmany cpu architectures therefore provide weaker memorybarrier instructions that do only one or the other of these two roughly speaking a aread memory barriera marks only the invalidate queue and a awrite memory barriera marks only the store buffer while a fullfledged memory barrier does bothgreat that is clear but after that i see thisthe effect of this is that a read memory barrier orders only loads on the cpu that executes it so that all loads preceding the read memory barrier will appear to have completed before any load following the read memory barrier similarly a write memory barrier orders only stores again on the cpu that executes it and again so that all stores preceding the write memory barrier will appear to have completed before any store following the write memory barriersoall loads preceding the read memory barrier will appear to have completed before any load following the read memory barrierthat mixes up everything what was explained before what does it mean which load in function bar have to complete before load of a 4 i understand the assert could fail without memory barrier in this function just because the processor may read an old value because it still did not manage to invalidate it is cache line where object a is locatedexplanation in details would be really helpful i am trying to understand it all the daythanks very much in advance,['c++'] +94622,mysql difference between in and exist mysql questionwhat is the difference between not in and not exist when doing subqueries in mysql,"['sql', 'mysql']" +94628,pdo error message here is a snippet of my codeqry insert into nonexistanttable id score select id 40 from anothernonexistanttable where description like search string and available yes on duplicate key update score score 40sth thispdoprepareqrysthexecutedataprint rthispdoerrorinfothis should give me an error because the tables do not even exist all i get however is thisarray 0 0 how can i get a better description of the error so i can debug the issue,['php'] +94634,which doctype declaration should we use i have read a number of books on doctype declaration and the three variations strict transitional and framesetbut i am still not able to fully understand their difference and indeed am not sure which variation i should use when creating my website in particular i do not understand the difference between strict and transitionalcould you please advise me,['html'] +94654,iphone uiwebview can auto complete be turned off on a input text field i have searched high low for an answer on this and i cannot seem to find an answer or anybody else having the same issue hope some one can assisti have a web page for signup which i am viewing in an iphone uiwebview a user is asking if we can stop capitalization on the first letter of the email address being entered i thought this did not matter but apparently it can for the localpart on some email systems apparently it is only the domain that is only case insensitiveit seems autocomplete is the culpriti have tried adding autocompleteoff to the input element in the html but ios is obviously ignoring itcan autocomplete be turned off on a html input text field within a uiwebview thanks,['iphone'] +94674,compile php with gd for iphone os 41 the goalhave a working version of php with the gd library working on an ipod touch 4th genthe statusphp is working on the ipod lighttpd php 528 sqlite3 without gdwhen trying to compile php on the ipod i get this error the proposed solutioncan anyone point me in the direction of how to compile php with gd and then package it up nicely as a deb file for everyone else to usethe best situation i believe is to compile the latest version of php with the gd library included and enabled second best would be to settle for compiling gd as a module and then installing that into the currently working php that is available from cydia however to compile gd you would have to do this with the same source that was used to create the php 5283 iphoneosarmdeb available from cydia i think it would be easier and safer for everyone in the future to just compile a fresh php with gd already enabled and then pack it up as a debhere is what i have from phpinfo of the currently installed version of phpsystemdarwin ipodtouch 1031 darwin kernel version 1031 wed aug 4 223551 pdt 2010 rootxnu1504553310release arm s5l8930x ipod41build datejan 25 2009 025542configure commandconfigure buildx86 64unknownlinuxgnu hostarmappledarwin9 enablestaticno enablesharedyes prefixusr localstatedirvarcachephp withiconvusrarmappledarwin9usr withcurlhomedataplteldestiphoneosarmcurlusr enablefastcgihere is the package information from cydias repopackage phpversion 5283architecture iphoneosarmmaintainer jay freeman saurik installedsize 14492depends curl libxml2filename debsphp 5283 iphoneosarmdebsize 4626280md5sum dbb30ea608945a5d45de02df74df71b0section developmentpriority optionaldescription overly popular html templating languagename php hypertext preprocessortag purposeconsole roledeveloperps i am not the only person working on this as during my searching i found several other posts with people who need this too once i have this completed i will host the file somewhere so that everyone can enjoy,"['php', 'iphone']" +94678,is my method of measuring running time flawed sorry it is a long one but i am just explaining my train of thought as i analyze this questions at the endi have an understanding of what goes into measuring running times of code it is run multiple times to get an average running time to account for differences per run and also to get times when the cache was utilized betterin an attempt to measure running times for someone i came up with this code after multiple revisionsin the end i ended up with this code which yielded the results i intended to capture without giving misleading numbers implementation cstatic void testtstring testname funct test int iterations 10 consolewritelinetestname consolewritelineiterations 0 iterations var results enumerablerepeat0 iterationsselecti new systemdiagnosticsstopwatchtolist var timer systemdiagnosticsstopwatchstartnew for int i 0 i resultscount i resultsistart test resultsistop timerstop consolewritelinetimems 0311028 310 resultsmint telapsedmilliseconds resultsaveraget telapsedmilliseconds resultsmaxt telapsedmilliseconds timerelapsedmilliseconds consolewritelineticks 0311028 310 resultsmint telapsedticks resultsaveraget telapsedticks resultsmaxt telapsedticks timerelapsedticks consolewritelineof all the code i have seen that measures running times they were usually in the form approach 1 pseudocodestart timerloop and times run testing code directly or via functionstop timerreport resultsthis was good in my mind since with the numbers i have the total running time and can easily work out the average running time and would have good cache localitybut one set of values that i thought were important to have were minimum and maximum iteration running time this could not be calculated using the above form so when i wrote my testing code i wrote them in this form approach 2 pseudocodeloop and times start timer run testing code directly or via function stop timer store resultsreport resultsthis is good because i could then find the minimum maximum as well as average times the numbers i was interested in until now i realized that this could potentially skew results since the cache could potentially be affected since the loop was not very tight giving me less than optimal resultsthe way i wrote the test code using linq added additional overheads which i knew about but ignored since i was just measuring the running code not the overheads here was my first version implementation astatic void testtstring testname funct test int iterations 10 consolewritelinetestname var results enumerablerepeat0 iterationsselecti var timer systemdiagnosticsstopwatchstartnew test timerstop return timer tolist consolewritelinetimems 0311028 resultsmint telapsedmilliseconds resultsaveraget telapsedmilliseconds resultsmaxt telapsedmilliseconds consolewritelineticks 0311028 resultsmint telapsedticks resultsaveraget telapsedticks resultsmaxt telapsedticks consolewritelinehere i thought this was fine since i am only measuring the times it took to run the test function the overheads associated with linq are not included in the running times to reduce the overhead of creating timer objects within the loop i made the modification implementation bstatic void testtstring testname funct test int iterations 10 consolewritelinetestname consolewritelineiterations 0 iterations var results enumerablerepeat0 iterationsselecti new systemdiagnosticsstopwatchtolist resultsforeacht tstart test tstop consolewritelinetimems 0311028 310 resultsmint telapsedmilliseconds resultsaveraget telapsedmilliseconds resultsmaxt telapsedmilliseconds resultssumt telapsedmilliseconds consolewritelineticks 0311028 310 resultsmint telapsedticks resultsaveraget telapsedticks resultsmaxt telapsedticks resultssumt telapsedticks consolewritelinethis improved overall times but caused a minor problem i added the total running time in the report by adding each iterations times but gave misleading numbers since the times were short and did not reflect the actual running time which was usually much longer i needed to measure the time of the entire loop now so i moved away from linq and ended up with the code i have now at the top this hybrid gets the the times i think are important with minimal overhead afaik starting and stopping the timer just queries the high resolution timer also any context switching occurring is unimportant to me as it is part of normal execution anywayat one point i forced the thread to yield within the loop to make sure that it is given the chance at some point at a convenient time if the test code is cpu bound and does not block at all i am not too concerned about the processes running which might change the cache for the worse since i would be running these tests alone anyway however i came to the conclusion that for this particular case it was unnecessary to have though i might incorporate it in the final final version if it proves beneficial in general perhaps as an alternate algorithm for certain codenow my questionsdid i make some right choices some wrong onesdid i make wrong assumptions about the goals in my thought processwould the minimum or maximum running times really be useful information to have or is it a lost causeif so which approach would be better in general the time running in a loop approach 1 or the time running just the code in question approach 2would my hybrid approach be ok to use in generalshould i yield for reasons explained in the last paragraph or is that more harm to the times than necessaryis there a more preferred way to do this that i did not mentionjust to be clear i am not looking for an allpurpose use anywhere accurate timer i just want to know of an algorithm that i should use when i want a quick to implement reasonably accurate timer to measure code when a library or other 3rd party tools is not availablei am inclined to write all my test code in this form should there be no objections final implementationstatic void testtstring testname funct test int iterations 10 print header var results enumerablerepeat0 iterationsselecti new systemdiagnosticsstopwatchtolist for int i 0 i 100 i warm up the cache test var timer systemdiagnosticsstopwatchstartnew time whole process for int i 0 i resultscount i resultsistart time individual process test resultsistop timerstop report resultsfor the bounty i would ideally like to have all the above questions answered i am hoping for a good explanation on whether my thoughts which influenced the code here well justified and possibly thoughts on how to improve it if suboptimal or if i was wrong with a point explain why it is wrong andor unnecessary and if applicable offer a better alternativeto summarize the important questions and my thoughts for the decisions madeis getting the running time of each individual iteration generally a good thing to havewith the times for each individual iteration i can calculate additional statistical information like the minimum and maximum running times as well as standard deviation so i can see if there are factors such as caching or other unknowns may be skewing the results this lead to my hybrid versionis having a small loop of runs before the actual timing starts good toofrom my response to sam saffrons thought on the loop this is to increase the likelihood that constantly accessed memory will be cached that way i am measuring the times only for when everything is cached rather than some of the cases where memory access is not cachedwould a forced threadyield within the loop help or hurt the timings of cpu bound test casesif the process was cpu bound the os scheduler would lower the priority of this task potentially increasing times due to lack of time on the cpu if it is not cpu bound i would omit the yieldingbased on the answers here i will be writing my test functions using the final implementation without the individual timings for the general case if i would like to have other statistical data i would reintroduce it back into the test function as well as apply the other things mentioned here,['c#'] +94693,making deep copy of uiimage my class contains an uiimage property which i want to enforce as a copy property by any external clients accessing it but when i try to do a copy in my custom setter i get the runtime error about uiimage not supporting copywithzone so whats a good way to ensure that the correct ownership policy is followed declared in the interface asproperty nonatomic readonly copy uiimage personimage class implementation voidsetpersonimageuiimage newimage if newimage personimage personimage release uiimage does not support copywithzone personimage newimage copy,"['iphone', 'objective-c']" +94701,setting font of textbox from code behind this maybe a stupid question but how do i set the font of a textbox from a string in the code behind exampletxteditorfontfamily consolas,['c#'] +94702,how to rename a table column in mysql how to rename a table column in table xyz the columns aremanufacurerid name status ai pk inti want to rename to manufactureridi tried using phpmyadmin panel which is not working it shows an errormysql said documentation1025 error on rename of shoppingsqlc98 26 to shoppingtblmanufacturer errno 150,['mysql'] +94704,get string between two other strings in objc i am trying to parse a string and get another string in the middleie hello world this is a stringi need to find the string between world and is this i have looked around but have not been able to figure it out yet mainly because i am new to objective c anyone have an idea of how to do this with regex or without,"['iphone', 'objective-c']" +94729,thisplaying the build timestamp in an application i would like to thisplay the timestamp of when the application was built in an about box this will allow me tracking different versions of the application how can i retrieve this information in java,['java'] +94740,how to build a conceptual search engine i would like to build an internal search engine i have a very large collection of thousands of xml files that is able to map queries to concepts for example if i search for big cats i would want highly ranked results to return documents with large cats as well but i may also be interested in having it return huge animals albeit at a much lower relevancy score i am currently reading through the natural language processing in python book and it seems wordnet has some word mappings that might prove useful though i am not sure how to integrate that into a search engine could i use lucene to do this howfrom further research it seems latent semantic analysis is relevant to what i am looking for but i am not sure how to implement it any advice on how to get this done,['python'] +94747,adding tracelistener to webconfig i want to use below code with a website which config sections i should add to webconfig to log the output into a file or windows eventlog using systemdiagnostics singleton in real codeclass logger in constructor traceautoflush false public void logmessage string formattedlog formatlogmessage tracetraceinformationformattedlog traceflush,['asp.net'] +94753,thisable java jit for a specific methodclass i am having an issue in my java application where the jit breaks the code if i thisable the jit everything works fine but runs 1020x sloweris there any way to thisable the jit for a specific method or classedit i am using ubuntu 1010 getting the same results both withopenjdk runtime environment icedtea6 19 6b20190ubuntu1openjdk 64bit server vm build 170b16 mixed modeandjavatm se runtime environment build 160 16b01java hotspottm 64bit server vm build 142b01 mixed mode,['java'] +94758,converting string series to float list in python i am quite new to programing so i hope this question is simple enoughi need to know how to convert a string input of numbers separated by spaces on a single line52 56 53and convert this to a float listlsit 525653how can this be done,['python'] +94760,android 22 how do i detect if i am installed on the sdcard or not i am writing an android app that stores a lot of media files they are not the type and are far too many to clutter up the users notification or other media directories but they also must be userupdatable so i cannot put them in the resources i can use getexternalfilesdir to get a path on the sdcard but i only want to do that if the app itself is installed on the sdcard if the app is installed internally i want to put the media in the internal memoryso how can i determine if my app is running in internal or external memory,['android'] +94763,fastest way to copy files in java what ist the fastest way to copy a big number of files in java so far i have used file streams and nio overall streams seem to be faster than nio what experiences did you make so far,['java'] +94781,java how to run thread separately from main programclass subj how to run thread from main class but separately from that claso a bit of details i have one program which must run a process that process a cmd one runs only when main program finished and unloaded from memory and only after unload main program that process starting his work what should i add to the program,['java'] +94807,detect windows version with javascript specifically i am trying to detect windows xp users as they are not compatible with my softwareis there a way to detect with at least 70 or higher accuracy,['javascript'] +94810,using html5 file uploads with ajax and jquery admittedly there are similar questions lying around on so but it seems none quite meet my requirements here is what i am looking to doupload an entire form of data one piece of which is a single filework with codeigniters file upload libraryup until here all is well the data gets in my database as i need it good good but i would also like to submit my form via an ajax postusing the native html5 file api not flash or an iframe solutionpreferably interfacing with the lowlevel ajax jquery methodi think i could imagine how to do this by autouploading the file when the fields value changes using pure javascript but i would rather do it all in one fell swoop on for submit in jquery i am thinking it is not possible to do via query strings as i need to pass the entire file object but i am a little lost on what to do at this point am i chasing a unicorn herethanks so much for any help you could give,"['javascript', 'jquery']" +94838,how to read a multisession dvd thisk size in windows trying to read the sizes of thisks that were created in multiple sessions using getthiskfreespaceex gives the size of the last session only how do i read correctly the number and sizes of all sessions in ccthanks,['c++'] +94846,looking for a sip stack for android i am looking for a sip stack to use on the android platform since it is for a client to be used for commercial purposes gpled stacks are not feasible what would you recommend so,['android'] +94852,why is creating servlets in eclipse breaking my webxml being somewhat lazy i was rather happy to find that i could create a new servlet source code by going new servlet instead of going new class and then editing the class into a servlethowever i have thiscovered that every time i create a new servlet in eclipse eclipse modifies my webxmlspecifically it modifies the top element towebapp xmlnsxsi xmlns xmlnsjavaee xmlnsjsp xmlnsweb 2 5xsd xsischemalocation 2 4xsd idwebapp id version24linebreaks minethis does not seem necessarily bad but then it modifies various subelements by putting javaee in front of their name to indicate that these elements belong in that namespacefor example it changesthisplaynameshowlifecyclesthisplaynametojavaeethisplaynameshowlifecyclesjavaeethisplaynameafter which eclipse then complains about all the elements it modified giving me notations likecvccomplextype24a invalid content was found starting with element javaeethisplayname one of http javasuncomxmlnsj2eedescription thisplayname j2eeicon thistributable contextparam http javasuncomxmlnsj2eefilter filtermapping j2eelistener servlet servletmapping http javasuncomxmlnsj2eesessionconfig mimemapping j2eewelcomefilelist errorpage jspconfig http javasuncomxmlnsj2eesecurityconstraint loginconfig j2eesecurityrole enventry ejbref http javasuncomxmlnsj2ejblocalref serviceref j2eeresourceref resourceenvref message destinationref messagedestination locale encodingmappinglist is expectedto make matters worse when i use find and replace to delete all to javaee which litters the file eclipse still complains about these even though they are no longer there i must copy and paste the entire remaining file on top of itself to make these complaints go awayi am sure eclipse is trying to be useful anticipating some desire or need for this namespace how can i do either one of two thingsmake it stop doing thistake advantage of whatever it is trying to do and make it work for me instead of against me,['java'] +94864,arabic text box i have developed a web site some fields are entered in english while others are entered in arabic languagenow i wanna simplify the input operation for the user and want arabic textbox as a dlli have one but it works only with ie not with firefox or google chrome thanks so muchhow to enforce the user to write in arabic i mean moving the cursor directly without alt shift keys every time when trying to change the language if there is any way property dll or what ever to do that,"['c#', '.net', 'asp.net']" +94871,what will a python programmer gain by learning ruby i am going to be learning ruby haskell and prolog at universitynow i am wondering what should get most of my attention i have half a year to do all three which means i need to decide on one language to get my extracurricular time the others i will learn just enough to do very good in the coursei am familiar enough with haskell and prolog to know that learning them will teach me a few very important concepts of computer science i am not so sure about rubygoing through a few tutorials and introductions i get the impression that ruby is a lot of shallow magic now i am asking the ruby people what will i have gained should i decide never to use it again after i have spent half a year learning it that python did not already teach methis question is not intended to make the case for ruby although i realise this is a potential topic of great argumentation i use python for all my cs work now i have done quite a bit of functional programming with it as well i am also already quite familiar with object oriented programming in java python and c and i will as i said do some logical programming with prologwhat then is left for ruby to teach meto further dilute the questioni am not interested in writing funprograms or cool web applicationsi am just interested in the computerscience bits implementing algorithms data structures and so on although having fun surely would not hurtideally concepts thiscussed need to be learnable in about 10 hoursi am not at all interested in rails any technology that hides complexity is in this case detrimental i cannot help this question being argumentative but an ideal answer to this question will mention a profoundly important concept of theoretical computer science that ruby helps the programmer use and understand in order to gain scientifically adjuvant knowledge to candidates i came up with are metaprogramming and multithreading i do not know if ruby is particularly great to learn either of them,['ruby'] +94886,what is correct way to have single signal handler function for multiple signals what is the best way in c on linux for setting up a program that can handle multiple posixsignals with the same functionfor example in my code i have a handler function that i want to generically call when ever a signal is caught to perform some actions exit handler function called by sigaction void exithandler int sig siginfo t siginfo void ignore printf got d signal from dn siginfosi signo siginfosi pid loopcounter0 returni have set up two signals to catch by having individual sigaction calls for each signal set exit handler function for sigusr1 sigint ctrlc struct sigaction actactsa flags sa siginfoactsa sigaction exithandlersigaction sigusr1 act 0 sigaction sigint act 0 is this the correct way to set up this type of handling is there any other way where i do not have to enumerate all the possible signal numbers,['c'] +94901,elegant way to assign object id in java i have a class for objects lats say appleseach apple object mush have a unique identifier id how do i ensure elegantly and efficiently that newly created has unique idthanks,['java'] +94919,comparing doubles i am writing a program that consists of a while loop that reads two doubles and prints them the program also prints what the larger number is and what the smaller number isthis is the code i have so farint main variable declarations double a double b while ab while a b do not equal cin a b cout a b n if ab if ab smaller value is a cout the smaller value is a endl the larger value is b endl else if ba else if ba cout the smaller value is b endl the larger value is a endl else if ba cout the two numbers you entered are equal n the next step is having the program write out the numbers are almost equal if the two numbers differ by less than 1010 how would i do this,['c++'] +94929,how do i upgrade from rails 235 to rails 238 i have got a rails 235 app that i want to upgrade to rails 3 in the rails 3 upgrade railscast they suggest upgrading to 238 before going to 3 i have tried googling but the information i find is all about upgrading to rails 3 i found this question which seems to suggest doing gem update rails and rake railsupdate but wouldnt these commands upgrade to rails 3 as it is the latest version how do i upgrade to rails 238 thanks for reading,['ruby-on-rails'] +94932,how to get stack trace of an exception in scala to print it in a program of mine i would like to catch all exceptions and explicitly print them to be able to proceed with finally while still seeing exceptionsso i have tried thistry catch case ex exception println n ex println n exgetstacktrace n finally but this using getstacktrace itself causes javalangoutofmemoryerror permgen space what am i doing wrong i am sure i have plenty of free jvm heap memory free before getting this as i have tried causing an exception in the very beginning of the program,['java'] +94933,generating variable names on fly in python is there a way i can generate variable names in python in a loop and assign values to them for example if i haveprices 5 12 45i wantprice1 5price2 12price3 45can i do this in a loop or something instead of manually assigning price1 prices0 price2 prices1 etcthank you editmany people suggested that i write a reason for requiring this first there have been times where i have thought this may be more convenient than using a listi do not remember exactly when but i think i have thought of using this when there are many levels of nesting for example if one has a list of lists of lists defining variables in the above way may help reduce the level of nesting second today i thought of this when trying to learn use of pytables i just came across pytables and i saw that when defining the structure of a table the column names and types are described in the following mannerclass tableformattablesisdescription firstcolumnname stringcol16 secondcolumnname stringcol16 thirdcolumnname stringcol16if i have 100 columns typing the name of each column explicitly seems a lot of work so i wondered whether there is a way to generate these column names on the fly,['python'] +94939,android hide soft keyboard ime below is a bit of code that i managed to get to work to hide the soft keyboard on android it works by the user clicking anywhere on the screen outside of a edittext inputs to hide the ime soft keyboard it registers a ontouchlistener to the scrollview ididsv background which when the screen is touched it hides the ime soft keyboard via the inputmethodmanager code i have set the scroll view as the parent layout in this case but it also works with any other layout view i hope this is useful to someone out there in android landxmlscrollview androidididsv background androidlayout widthfill parent androidlayout heightfill parent xmlnsandroid other views and edittextsscrollviewjavaprivate scrollview svbackgroundoverrideprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutnewentry svbackground scrollviewfindviewbyidridsv background svbackgroundsetontouchlistenernew ontouchlistener override public boolean ontouchview v motionevent event inputmethodmanager imm inputmethodmanagergetsystemservicecontextinput method service immhidesoftinputfromwindowsvbackgroundgetwindowtoken 0 return false,"['java', 'android']" +94942,how to use a c library in a c app thus far i have figured out out i needed to recompile the library as a dll instead of a lib enable clr and eha instead of ehsc now i have got a managed dll which i have added as a reference in my c projectnow how do i use iti am prepared to write some wrappers but i do not know where to begin or how to see what functions i have gained access to i have read a little bit about how the class names and functions might be mangled by the compiler do i need to go back and add declspec exports everywhere if so how or is there an option in vs2010 that says do not mangle itthe c library in question is still under active development so i am hoping i can modify the c library as little as possible and just recompile it periodically with a few switches and then expose the new functionality as i need it,"['c#', 'c++']" +94945,sandbox jvm to secure server from untrusted sources how can protecting my server from malicious activity when accepting and executing uploaded untrusted codethe users should be able to implement my interface and given data perform some calculations and return data no io operations are required and certainly no threadprocess manipulation or other tomfooleryusing the javapolicy file it is possible to deny everything by granting nothing cat testpolicy grant using this policy file operations not granted will cause a security exception cat printjavapublic class print public static void mainstring a throws exception systemoutprintlnsystemgetpropertyosname javac printjava java djavasecuritymanager djavasecuritypolicytestpolicy printexception in thread main javasecurityaccesscontrolexception access denied javautilpropertypermission osname read at javasecurityaccesscontrolcontextcheckpermissionaccesscontrolcontextjava323 at javasecurityaccesscontrollercheckpermissionaccesscontrollerjava546 at javalangsecuritymanagercheckpermissionsecuritymanagerjava532 at javalangsecuritymanagercheckpropertyaccesecuritymanagerjava1285 at javalangsystemgetpropertysystemjava650 at printmainprintjava3is this foolproof do i need to do more to secure my server environment from untrusted sources,['java'] +94954,thisable f5 in webbrowser possible duplicatesthisable browsers back buttonhow do i thisable the f5 refresh on the browser hii created an application in c that will download data from the internet and this is done one time only and put it in a webbrowser and this data should be static i want to know if there is a way to thisable the f5 key from doing a refreshi tried injecting javascript to thisable f5 but it will still refresh the webbrowser,"['c#', '.net']" +94955,jquery validation plugin how to change css on error i am following the demo over hereon submitting the form if the field is empty how are the input boxes and other fields getting that red border around them what is it i have to add in my plugin decleration to get thatupdateprofile formvalidate rules nickname required address required messages nickname required address nbsprequired i know how to get the border via css i need to know how is the validate plugin changing the cssregards,['jquery'] +94959,what does final do if you place it before a variable very basic question but what does final do if you place it before a variable such as belowfinal edittext mytextfield edittext findviewbyidridmytextfieldwhat does final do,['java'] +94975,implement faster graphics operation on wpf canvas i am trying to build a simple graphics application in wpf c the purpose is to draw 1010 rectangles of size 4 pixels eachi have modified the onrender method of the canvas to draw the rectangles drawings are performed for smaller number of rectangles say 5050 or 100100 rectangles of 4 pixel each but it is slowing down as i am increasing the no of rectangles following is my code protected override void onrenderdrawingcontext dc baseonrenderdc fillcellsdc if showgrids drawgriddc draw grid lines void fillcellsdrawingcontext dc int cellsize4 for int i 0 i maxrow i for int j 0 j maxcolumn j dcdrawrectanglegetrectbrushij getrectpenij new rectj cellsize i cellsize cellsize 1 cellsize 1 the above code takes more than a minute to draw 1010 rectanglesis there any method to make this process faster is there any other thing i can use in place of thisthanks,['c#'] +94982,colon in python list index i am new to python i see used in list indices especially when it is associated with function calls python 27 documentation suggests that listsappend translates to alena x why does one need to suffix lena with a coloni understand that is used to identify keys in dictionary,['python'] +94996,is the stripes framework dead anyone using it i am a big fan of the and using it heavily for my projects however the project seems to be dead it is not possible to register to the website anymore no license and i couldnt contact any of the administrators also the mailinglist is not availableis anyone aware of the status of the projectit would be a pity if it was dead as i think it is one of the most elegant frameworks for java web development,['java'] +95009,how many bytes does a string have is there some function which will tell me how many bytes does a string occupy in memoryi need to set a size of a socket buffer in order to transfer the whole string at once,['python'] +95023,gmail is ignoring thisplaynone i have a query that gmail is ignoring thisplaynone what to do in email html for hide arow or div,"['html', 'css']" +95031,print currency number format in php i have some price values to thisplay in my pagei am writing a function which takes the float price and returns the formatted currency val with currency code toofor example fnprice100101 should print 101,['php'] +95045,jpacriteria api like equal problem i am trying to use criteria api in my new projectpublic listemployee findempsstring name criteriabuilder cb emgetcriteriabuilder criteriaqueryemployee c cbcreatequeryemployeeclass rootemployee emp cfromemployeeclass cselectemp cthistinctemp listpredicate criteria new arraylistpredicate if name null parameterexpressionstring p cbparameterstringclass name criteriaaddcbequalempgetname p if criteriasize 0 throw new runtimeexceptionno criteria else if criteriasize 1 cwherecriteriaget0 else cwherecbandcriteriatoarraynew predicate0 typedqueryemployee q emcreatequeryc if name null qsetparametername name return qgetresultlistnow when i change this line criteriaaddcbequalempgetname pto criteriaaddcblikeempgetname pi get an error saying the method likeexpression expression in the type criteriabuilder is not applicable for the arguments path parameterexpressionwhats the problem,['java'] +95052,can a stored procedure work with two different databases how about two servers i am wondering if mysqls stored procedures can work with two different databases on the same machine how about if they are on different servers,"['sql', 'mysql']" +95072,vector graphics in android i am working on an application that thisplays someone elses database of images the images they have are all vector graphics and can be converted to any format however keeping them in a vector format is good because users will probably want to zoom in closelythe question is is there a builtin way to thisplay a vector graphic in android the format does not matter we can convert the current format were considering is pdf but given that there is no native pdf support i would have to do something pretty complex just to get it working for example integrating poppler into my app via the ndk the alternative is to just convert the vector graphics into a simpler format jpg gif but i would rather avoid that,['android'] +95079,when to use cast and oftype in linq i am aware of two methods of casting types to ienumerable from an arraylist in linq and wondering in which cases to use themegienumerablestring somecollection arraylistoftypestringorienumerablestring somecollection arraylistcaststringwhat is the difference between these two methods and where should i apply each case,"['c#', '.net']" +95101,android append at the end textview i have a view to that i need to add some textthe used view is textview androidlayout marginleft10dp androidlayout widthwrap content androidgravitycenter vertical androidlayout gravitycenter androidmaxlines3 androidlayout height70dp androidtextcolor0 androidtextsize12dp the problem i have is if this text contains more than 3 line it just shows three line but no indication that it cut some linei want to append at end of third line if it cut some data,['android'] +95105,c searching a text in word and getting the range of the result i can find a text in a word file viawordrange range wordappactivedocumentcontentwordfind find rangefindfindtext xfindclearformattingfindexecuteref missing ref missing ref missing ref missing ref missing ref missing ref missing ref missing ref missing ref missing ref missing ref missing ref missing ref missing ref missingthis tells me if the text is found but i need the range of the found textpiece,['c#'] +95152,convert string to datetime object i would like to convert this string into a datetime objectwed oct 20 163544 0 2010is there a simple way to do this or do i have to write a re to parse the elements convert oct to 10 and so fortheditstrptime is great however withdatetimestrptimedate str a b d hms z yi getvalueerror z is a bad directive in format a b d hms z yeven though z seems to be correctedit2the z tag appears to not be supported see i got around it by using a timedelta object to modify the time appropriately,['python'] +95154,what is going on with customusernamepasswordvalidatortype i have been creating a custom usernamepassword validator for a wcf service and ran across the configuration item customusernamepasswordvalidatortype i have been able to make my code work by following examples but i just do not understand what is going on unfortunately the msdn article does not provide much detailthis is the sample that microsoft providesservicecredentials usernameauthentication usernamepasswordvalidationmodecustom customusernamepasswordvalidatortypemicrosoftservicemodelsamplescalculatorservicecustomusernamevalidator service servicecredentialsi am trying to understand what the two parameters are to customusernamepasswordvalidatortype microsoftservicemodelsamplescalculatorservicecustomusernamevalidator and servicecan someone please help me understand what these parameters meanthanks,['c#'] +95156,text box with line wrapping in matplotlib is it possible to thisplay text in a box through matplotlib with automatic line breaks by using pyplottext i was only able to print multiline text that flows beyond the boundaries of the window which is annoying the size of the lines is not known in advancea any idea would be much appreciated,['python'] +95163,raphael position how can i get the position of an object in raphael i can get the size using getbbox but there appears to be no way to get the position,['javascript'] +95166,obsolete java optimization tips there are number of performance tips made obsolete by java compiler and especially profileguided optimization for example these platformprovided optimizations can drastically according to sources reduces the cost of virtual function calls vm is also capable of method inlining loop unrolling etcwhat are other performance optimization techniques you came around still being applied but are actually made obsolete by optimization mechanisms found in more modern jvms,['java'] +95168,javascript web workers how do i pass arguments found the answer some some of my problems html5 web workershow do i pass an argument to a web worker though using this basic examplecontents of workerjsfunction dosomething postmessage donesettimeout dosomething 30 js code var worker new workerworkerjs workeronmessage function event alerteventdata,['javascript'] +95203,thisplay unicode characters in textview android there are a number of posts all over the internet on this topic however none of them have been able to isolate and solve the problemi am trying to show some special utf8 encoded symbols stored in a sqlite database using a textview however all it shows is boxes i understand what this means is that right font is not installed but when i print those symbols using arial font on mac it worksi am trying to use an arial typeface on the device and the emulatorany advise,['android'] +95204,copy rows from one datatable to another datatable how can i copy specific rows from datatable to another datable in c there will be more than one row,['c#'] +95226,html5 multiple canvas on a single page if we use multiple canvas on a single html page does it hamper the performance of the application that is being developed and does the code get very bulky and require more time to load the page,['html'] +95252,how to type into input field with wickettester i am writing a unit test for a wicket webpage i want to fire up a page type into a field click a link and then make some assertionslooking at the api of wickettester and basewickettester i could not find any method that takes a path like forminput to locate an input field and lets you enter text in it set up wickettester create pagetesterstartpagepagetester type into input field how to do thistesterclicklinkformcontinuebutton assert somethingdid i miss something this seems like a pretty basic use case are you not supposed to use wickettester like this that would be surprising given the presence of methods like clicklink,['java'] +95265,how to detect xaccelredirect nginx xsendfile apache support in php about applicationi am working on an ecommerce application in php to keep urls secure product download links are kept behind php there is a file say downloadphp which accepts few parameter via get and verifies them against a database if all goes well it serves file using readfile function in phpabout problemnow problem comes when file to be passed to readfile is larger than memory limit set in phpinias this application will be used by many users on sharedhosting we cannot relay on altering phpini settingsin our effort to find workarounds i first thought we can go for fread calls in while loop but it seems that will impose problems as well as highlighted here sending large files reliably in phpso my best option is to detectcheck if server supports xaccelredirect in case of nginx xsendfile in case of apacheif server supports xaccelredirect xsendfile i can use them and in else block i can make system admin aware about memory limit enforced by phpiniideally i want to use server side support like xaccelredirect xsendfile wherever possible and if that does not work i would like to have a fallback code to read files without readfile i am not yet sure as how readfile and fread in while loop are different but seems while loop will create problem again as suggested in sending large files reliably in phphope to get some help suggestions codes guidancethanks for reading,['php'] +95298,prevent inserting overlapping date ranges using a sql trigger i have a table that simplified looks like thiscreate table test validfrom date not null validto date not null check validto validfromi would like to write a trigger that prevents inserting values that overlap an existing date range i have written a trigger that looks like thiscreate trigger trigger teston testfor insertasbegin if exists select from test t join inserted i on ivalidto tvalidfrom and ivalidfrom tvalidto begin raiserror noverlapping range 16 1 rollback transaction return endendbut it does not work since my newly inserted record is part of both tables test and inserted while inside a trigger so the new record in inserted table is always joined to itself in the test table trigger will always revert transationi cannot thistinguish new records from existing ones so if i would exclude same date ranges i would be able to insert multiple exactlysame ranges in the tablethe main question isis it possible to write a trigger that would work as expected without adding an additional identity column to my test table that i could use to exclude newly inserted records from my exists statement likecreate trigger trigger teston testfor insertasbegin if exists select from test t join inserted i on iid tid and exclude myself out ivalidto tvalidfrom and ivalidfrom tvalidto begin raiserror noverlapping range 16 1 rollback transaction return endendimportant if impossible without identity is the only answer i welcome you to present it along with a reasonable explanation why,['sql'] +95301,are visual studio express products really only for hobbyists students and novices i have used visual studio professional 2008 and have been testing the free c express 2010 version recently in general i am amazed at how good it is for free and how many of the full vs features it has i am thinking of using it for a commercial program and i know the license allows for that it is just the description of it being for nonprofessional developers like hobbyists students and novice developers concerns me a bitwhat i am interested in knowing is what is stopping it being professional that ishave you evaluated the express edition and found a specific useful feature lacking that stopped you from using it or did you initially use the express versions but upgraded to full vs because of a feature lacking if so what was that feature i have searched for similar questions and found lists of differences between the full vs and express versions but i am more interested in knowing peoples personal experiences with it it seems like many of the extra features in vs target developers working in large teams so i am mainly interested in hearing from either solo or small team developers where it seems like there is less compelling reasons to upgrade the limitations i have personally encountered areextensions not being supported though i can still use dottrace nunit and an obfuscator outside of the vs integration albeit it is a bit less convenient limited refactoring although the rename and extract method are still there and i think they are the most useful edit not having encapsulate field in express used to be annoying though though the introduction of automatic getters and setters has pretty much canceled that out i thinkmore limited debugging for multithreaded appsedit another is that you cannot easily switch between targeting any cpux86x64 in express like you can in vs it is possible but needs manually editing your project file to do so but the pluses seem to outweigh the minuses so far is there anything you found was a dealbreaker for you update to come back to this a couple of months later and after releasing a product built with the express version it is indeed possible to program professionally with the express versions the limitations within the program itself are pretty minor and can be worked around but i have increasingly come to realise it is really the extensions not supported one that is the only major drawback no resharper coderush or the like and no source control profiling database explorer or unit testing and the like within vs itself it is more of a productivity drag than a deal breaker but it is annoying to come across a cool looking vs extension only to see that not supported in express versions noticeif anyone else is in the same situation i would evaluate the extensions you use or might be planning to use first and see how important they are to you express is fine if you do not use any extensions or could live without them without a significant drop in productivity otherwise stick with the professional version,['c#'] +95303,how to implement memmove in standard c without an intermediate copy from the man page on my systemvoid memmovevoid dst const void src size t len description the memmove function copies len bytes from string src to string dstthe two strings may overlap the copy is always done in a nondestructive manner from the c99 standard6585 when two pointers are compared the result depends on the relative locations in the address space of the objects pointed to if two pointers to object or incomplete types both point to the same object or both point one past the last element of the same array object theycompare equal if the objects pointed to are members of the same aggregate object pointers to structure members declared later compare greater than pointers to members declared earlier in the structure and pointers to array elements with larger subscript values compare greater than pointers to elements of the same array with lower subscript values all pointers to members of the same union object compare equal if the expression p points to an element of an array object and the expression q points to the last element of the same array object the pointer expression q1 compares greater than p in all other cases the behavior is undefinedthe emphasis is minethe arguments dst and src can be converted to pointers to char so as to alleviate strict aliasing problems but is it possible to compare two pointers that may point inside different blocks so as to do the copy in the correct order in case they point inside the same blockthe obvious solution is if src dst but that is undefined if src and dst point to different blocks undefined means you should not even assume that the condition returns 0 or 1 this would have been called unspecified in the standards vocabularyan alternative is if uintptr tsrc uintptr tdst which is at least unspecified but i am not sure that the standard guarantees that when src dst is defined it is equivalent to uintptr tsrc uintptr tdst pointer comparison is defined from pointer arithmetic for instance when i read section 656 on addition it seems to me that pointer arithmetic could go in the direction opposite to uintptr t arithmetic that is that a compliant compiler might have when p is of type charuintptr tp1uintptr tp1this is only an example generally speaking very little seems to be guaranteed when converting pointers to integersthis is a purely academic question because memmove is provided together with the compiler in practice the compiler authors can simply promote undefined pointer comparison to unspecified behavior or use the relevant pragma to force their compiler to compile their memmove correctly for instance this implementation has this snippetif uintptr tdst uintptr tsrc as authormaintainer of libc take advantage of the fact that we know memcpy copies forwards return memcpydst src len i would still like to use this example as proof that the standard goes too far with undefined behaviors if it is true that memmove cannot be implemented efficiently in standard c for instance noone ticked when answering this so question,['c'] +95312,jquery draggable and clone var icon div stylewidth100pxheight100pxborderstylesolidicondraggable containment parent axis y drag functioneui iconclonetrueappendtobodyafter i have made a clone icon dragging stopped workingdoes anybody know how to fix thisthanks,['jquery'] +95322,adding values to a magento dropdown or multiselect product attribute while adding a new product i am wondering if anyone has found or written an extension that would allow a magento website administrator the ability to add values to their products attribute while adding the product for example if i sell books and want the book author to be in a drop down list so that it would be used in layered navigation it seems odd that i would have to add the author via the attributes section before adding the product from a workflow standpoint it really makes sense to have an add new value button next to the drop down on my add product screen anyone have any thoughts or insight,['php'] +95323,strange user agent with google chrome i was working with some javascript and found a strange user agent with my google chromei have google chrome 7051741 beta installed on my ubuntu laptopnow afaik my user agent should be something close to chrome7051741but it is showing memozilla50 x11 u linux i686 enus applewebkit5347 khtml like gecko chrome7051741 safari5347why is this happening i have thisabled all the installed extensions but it is still the same,['javascript'] +95325,ftps tlsl from ruby on rails app i have an ftp server which only accepts connections through running ftps explicit ftp over tls i need to be able to connect to this using a ruby on rails app does anybody know of a method to do this i have tried the netftp library but this does not appear to support ftps connections,"['ruby-on-rails', 'ruby']" +95335,delete all bulk insert first off let me say i am running on sql server 2005 so i do not have access to mergei have a table with 150k rows that i am updating daily from a text file as rows fall out of the text file i need to delete them from the database and if they change or are new i need to updateinsert accordinglyafter some testing i have found that performance wise it is exponentially faster to do a full delete and then bulk insert from the text file rather than read through the file line by line doing an updateinsert however i recently came across some posts thiscussing mimicking the merge functionality of sql server 2008 using a temp table and the output of the update statementi was interested in this because i am looking into how i can eliminate the time in my deletebulk insert method when the table has no rows i still think that this method will be the fastest so i am looking for the best way to solve the empty table problemthanks,['sql'] +95336,jpahibernate whats better for composite primary keys idclass or embeddedid implementations and why whats better for jpahibernate composite primary keys idclass or embeddedid implementations and whythis is an intentionally naive question i decided to use embeddedid for whatever reason and i feel like i made the wrong choice dereferencing the embeddedid that contains the column properties is redundant and quite errorprone when codingare there any more reasons for andor against the other is the a recommendation by the jpa spec,['java'] +95338,how to better organize classespackages in a framework so that the client of my application can easily extend them let us assume i am in charge of developing a scrabble game being that one of the principal requirements of the client is the ability to later try out different ways and modes of the game i already made a design that is flexible enough to support those kinds of changes the only question left is what to expose to the clientobjects access modifiers and how to organize it how to expose my objects in namespacespackageshow should i define things such that the client can both easily use my standard implementation a standard scrabble game and yet be able to make all the modifications that he wants i guess what i need is a kind of framework on which he can work oni organized my classesinterfaces in a nonstrict layered systemdata typescontains basic data types that might be used in the whole system this package and its members can be accessed by anyone in the system all its members are publicdomaincontains all the interfaces i have defined and that might be useful to be able to make clients new scrabbles implementations also contains value types like piece that are used in the game all its members are publicimplementationscontains all the needed classescode to implement my standard scrabble game in a implementationsstandardscrabble package if the client decides to implement other variants of the game he can create them in implementationsxyz for examplethese classes are all package protected and the only thing that is available to the outside of the package is a game fade uses both domain and data types packagesuicontains the ui class that i have implemented so that both the client and the users of the program can run the game my implementation can access all the other layersthere are several drawbacks to the way i am organizing things the most obvious being that if the client wants to create its own version of the game he will have to basically implement almost everything by himselfi share in the domain the interfaces but he can do almost nothing with them i feel i should maybe pass all the implementations classes to the domain and then only have a fade that builds up my standard scrabble in the implementations namespacehow would you approach this is there any recomended reading on how to build this kind of programs basically frameworksthanks,"['c#', 'java']" +95352,can an executable thiscover its own path linux possible duplicatehow to find the location of the executable in c i would like an executable to be able to thiscover its own path i have a feeling that the answer is you cannot do this but i would like this to be confirmedi do not think i can use getcwd because i might not be executing it from the same directory i do not think i can use argv0 because that is based on the string that is used to execute it are there any other optionsrationalethe real problem is that i would like to place an executable somewhere on a filesystem and place a default config file alongside it i want the executable to be able to read its config file at runtime but i do not want to hardcode this location into the executable nor do i want the user to have to set environment variables if there is a better solution to this situation i am all ears,['c'] +95358,thistributing jquery licence in commercial software iam building a commercial web application that uses jquery i think i need to use the mit licence for jquery because the application is commercial when i looked at the mit licence in wikipedia it says ait is a permissive license meaning that it permits reuse within proprietary software on the condition that the license is thistributed with that softwareamy question is how do you thistribute the licence in a web application does the user have to accept the licence the first time they use the web site or do i include the licence in an about page,['jquery'] +95363,python filewrite creating extra carriage return i am writing a series of sql statements to a file using python the template string looks likestore insert tinsert stores storenum values s i am writing to the file like sofor line in source line linerstrip fields linesplitt scriptwritestore insert tuplefields scriptwriteoslinesephowever in the resulting output i see rrn at the end of each line rather than rn as i would expect why,['python'] +95364,android launch activity from clickable text is there any way i can launch an activity from a portion of a string egi have this in my stringsxml filestring nameclickable stringthis is a uclickable stringustringi would like the text between the u tags to be underlined and launch an activity when clicked when inserted in to a textview,['android'] +95376,high profile monotouch apps a client do not want to consider monotouch for a new project monotouchinfo has a long list of apps but i have not found any on the caliber that can convince a client too choose a technology the client has seen the list and actually use the bland screenshots as an argument against monotouchwhere can i find examples of applications useful as motivation high profile apps created using monotouch the apps you call home about the apps that made it to the top 25 lists in their category,['iphone'] +95384,how to change the value of datetoday within a running ruby process i know this is a bad idea but i have lots of legacy code and i want to run through some historical batch jobs i dont want to change the systems date because other stuff runs on the same system is there any way that i can change the value that datetoday will return for the life of a given process only the idea here is to rewind and run some older batch scripts that were used to work off of datetodaythanksjoel,"['ruby-on-rails', 'ruby']" +95426,can i draw outside the bounds of an android canvas i am porting an app written in a graphics environment that allows drawing to happen outside the bounds of the clipping rectangle any way to do this in android,['android'] +95434,java apply callback to array values i am looking for a simple way to apply a callback method to each element in a string array for instance in php i can make all elements in an array like thisarray array mapstrtolower arrayis there a simple way to accomplish this in java,['java'] +95437,get current color im using glcolor4f10f 10f 10f alpha to set transparency to primitives i am drawinghowever i would like to be able to read the current opengl alpha value is that possibleegfloat current alpha glgetalpha glcolor4f10f 10f 10f alpha current alpha,['c++'] +95443,is there a library that can compile c or c i came here to ask this question because this site has been very useful to me in the past seems to have very knowledgeable users who are willing to thiscuss a question even if it is metaphysical at times and also because googling it did not workjava has a compiler and then it has a jdt library that can compile java on the fly for example used in jasperreports to turn a report template into java codemy question does anyone know of a libraryproject that would offer compiling as a set of library classes in cc for example a suite of classes to perform preprocessing parsing codeoptimization and of course binary rendering to executable images such as elf or win format basically something that would allow one to compile c or c scriptlets as part of an application,['c++'] +95450,nullable vs int is there any difference apparently nullableint and int are equivalent in value are there any reasons to choose one over the othernullableint a nullint b nulla b this is true,"['c#', '.net']" +95461,mysql how to call sql script file from other sql script file suppose i have wrote script table abcsql which creates table abc i have created many such scripts for each of required tables now i want to write a script that call all of these script files in a sequence so basically i want another script file createtablessql mysql provides option to execute a script file from mysql shell application but could find some command like exec cmyscriptsmytablesql please tell me if there is any command that can be written in sql script itself to call other one in latest mysql versions or alternative for samethanks,"['sql', 'mysql']" +95469,python correct way to initialize when superclasses accept different arguments if i have got three classes like thisclass baseclassobject def init self base arg base arg2none class mixinclassobject def init self mixin arg class childclassbaseclass mixinclass def init self base arg mixin arg base arg2none what is the correct way to initialize mixinclass and baseclassit does not look like i can use super because the mixinclass and the baseclass both accept different argumentsa and two calls mixinclass init and baseclass init will could cause the diamond inheritence problem super is designed to prevent,['python'] +95477,how to create a dynamic array of integers how to create a dynamic array of integers in c using the new keyword,['c++'] +95479,patching codesymbols into a dynamiclinked elf binary suppose i have an elf binary that is dynamic linked and i want to overrideredirect certain library calls i know i can do this with ld preload but i want a solution that is permanent in the binary independent of the environment and that works for setuidsetgid binaries none of which ld preload can achievewhat i would like to do is add code from additional object files possibly in new sections if necessary and add the symbols from these object files to the binarys symbol table so that the newly added version of the code gets used in place of the shared library code i believe this should be possible without actually performing any relocations in the existing code even though they are in the same file these should be able to be resolved at runtime in the usual plt way for what it is worth i only care about functions not dataplease do not give me answers along the line of you do not want to do this or that is not portable what i am working on is a way of interfacing binaries with slightlyabiincompatible alternate sharedlibrary implementations the platform in question is i386linux ie 32bit if it matters unless i am mistaken about whats possible i could write some tools to parse the elf files and perform my hacks but i suspect there is a fancy way to use the gnu linker and other tools to accomplish this without writing new code,['c'] +95480,c what are scenarios where using pointers is a good ideatm possible duplicatecommon uses for pointers i am still learning the basics of c but i already know enough to do useful little programs i understand the concept of pointers and the examples i see in tutorials make sense to me however on the practical level and being a former php developer i am not yet confident to actually use them in my programsin fact so far i have not felt the need to use any pointer i have my classes and functions and i seem to be doing perfectly fine without using any pointer let alone pointers to pointers and i cannot help feeling a bit proud of my little programsstill i am aware that i am missing on one of cs most important feature a double edged one pointers and memory management can create havoc seemingly random crashes hard to find bugs and security holes but at the same time properly used they must allow for clever and efficient programmingso do tell me what i am missing by not using pointerswhat are good scenarios where using pointers is a mustwhat do they allow you to do that you could not do otherwisein which way to they make your programs more efficient and what about pointers to pointers edit all the various answers are useful one problem at so is that we cannot accept more than one answer i often wish i could actually it is all the answers combined that help to understand better the whole picture thanks,['c++'] +95523,executing cmdexe commands from java i am trying to read a file from the user in which each line is a cmdexe command and run it it is okay to assume the commands are legal but when i give a command like echo hi i get runtime exception errorexception in thread main javaioioexception cannot run program echo createprocess error2 the system cannot find the file specifiedi am trying to run the commands like thisruntimegetruntimeexeccommandwhere command echo hi this does work for commands like regedit though so it seems the runtime i am getting is like the run window and not cmd is there a way to run these commands,['java'] +95532,where is the all android broadcast intent list i want to receive the android broadcast messages is there a list of all intents,['android'] +95535,android download large files i am trying to download a large zip file from a web server but i have a weird behaviour the description isi am executing the code in the device emulator api level 3 version 15 with an sd card of 512mb i start the device with wipe data userthe length of the size from conexiongetcontentlength is 7012725the server address is localhost 10022 but i have tried with an external server and the behaviour is the same i have double checked that i can download the file through a web browseri have these permisions in the manifest fileusespermission androidnameandroidpermissioninternetusespermissionusespermission androidnameandroidpermissionwrite external storageusespermissionthe errorit starts downloading the file i can see the text 10 20 30 40 50 and then it stops at 60after a while the emulator reboots itselfworkaroundsthis issue in stackoverflow is working in the device not in my caseabout this wifi lock issue what i have done is add this permission androidpermissionwake lock and then this piece of code but with exactly the same behaviourwifimanagerwifilock wifilockwifimanager manager wifimanager getsystemservicecontextwifi servicewifilock managercreatewifilockwifilockwifilockacquirewifilockreleasehere is the code that it is being executing in a separate threadprivate void downloaddata try logvtag downloading data url url new url urlconnection connection urlopenconnection connectionconnect int lenghtoffile connectiongetcontentlength logvtag lenghtoffile lenghtoffile inputstream is urlopenstream file testdirectory new fileenvironmentgetexternalstoragedirectorytestdirectory iftestdirectoryexists testdirectorymkdir fileoutputstream fos new fileoutputstreamtestdirectoryfileszip byte data new byte1024 int count 0 long total 0 int progress 0 while countisreaddata 1 total count int progress temp inttotal100lenghtoffile ifprogress temp10 0 progress progress temp progress progress temp logvtag total progress foswritedata 0 count isclose fosclose logvtag downloading finished catchexception e logvtag exception in downloaddata eprintstacktrace any cluethank you very muchupdate with more log descriptionhi chris i have tried to thiscover what was going on at first with this log in the eclipse environment here are a little bit more detail about what is happening time action note that i have changed the file to download for another one in orther to do more tests but the results are quite the same0 it starts downloadingviphoto 853 downloading dataviphoto 853 lenghtoffile 7732809viphoto 853 total 10viphoto 853 total 20viphoto 853 total 30viphoto 853 total 40viphoto 853 total 50 round 05 here it stops and the ddms thisconnects the device immediately0340 it finish the download not always and the device reboots on its owniprocess 595 sending signal pid 595 sig 3idalvikvm 595 threadid7 reacting to signal 3ddalvikvm 722 gc freed 2193 objects 135808 bytes in 176 secviphoto 853 total 60idalvikvm 595 wrote stack trace to dataanrtracestxtiactivitymanager 595 process comgoogleandroidappsmapsfriendservice pid 778 has diediactivitymanager 595 process comandroidmms pid 732 has diedviphoto 853 total 70viphoto 853 total 80viphoto 853 total 90viphoto 853 total 100viphoto 853 downloading finishedviphoto 853 thread finish loadingiprocess 595 sending signal pid 595 sig 9iactivitythread 757 removing dead content provider settingsiactivitythread 748 removing dead content provider settingsiactivitythread 722 removing dead content provider settingsiactivitythread 700 removing dead content provider settingsiservicemanager 549 service package died services dyingiservicemanager 549 service wifi diedeinstalld 557 eofeinstalld 557 failed to read sizeiinstalld 557 closing connectiondqemud 560 fdhandler event thisconnect on fd 11dqemud 560 fdhandler event thisconnect on fd 12evold 550 framework thisconnectedizygote 554 exit zygote because system server 595 has terminatediservicemanager 549 service simphonebook diediservicemanager 549 service isms diediservicemanager 549 service iphonesubinfo diediservicemanager 549 service phone dieddandroidruntime 949 dandroidruntime 949 androidruntime start and starting could anyone try my code and to download a zip file with size round 8mb does it works for you,['android'] +95537,when to use partitioner class can anyone suggest typical scenarios where partitioner class introduced in net 40 canshould be used,"['c#', '.net']" +95539,split a string by whitespace keeping quoted segments allowing escaped quotes i currently have this regular expression to split strings by all whitespace unless it is in a quoted segmentkeywords pop rock hard rockkeywords keywordsmatchwgconsolelogkeywords pop rock hard rockhowever i also want it to be possible to have quotes in keywords like thiskeywords pop rock hard rock dream popthis should return pop rock hard rock dream popwhats the easiest way to achieve this,['javascript'] +95568,htmlcss how to put text both right and left aligned in a paragraph what would be the best code to have two bits of text in a single paragraph one left aligned the other right aligned that also isthe least code as possiblethe easiest for clients to render ie using least resourcesi add this last one to be sure tabletrtdtdtd alignrighttdtrtable would get ruled out not only is this a beast of code compared to a couple of properly styled div span or ps it is also a beast if you know what a html render engine has to load and calculate to decide on the cell sizes before it even gets to painting text in themif youre not sure what i mean heres an example a page footer with left aligned the name of the user currently logged on and on the same line right aligned the current date and time andor website version,"['html', 'css']" +95571,how do i get an apk file from an android device how do i get the apk file from an android device or how do i transfer the apk file from device to system,['android'] +95579,split one pdf page into two i want to split one wide pdf page into two pdf pages my original page is wide as two a4 page size but height is normalfor a4 i trying to use itext but with no effects thanks for attention,['java'] +95580,autogenerate function comments in eclipse how to autogenerate xml based function header comments param etc in eclipse is there an equivalent of shortcut in visual studio,['java'] +95582,how to test if a datetime is between 2 days of week dayofweek in c given an arbitrary set of dayofweek end points like dayofweekfriday and dayofweeksunday how would one test if an arbitrary date falls between those two days inclusiveexample result true oct 23 2010 is a saturdayvar result inbetweendaysinclusivenew datetime2010 10 23 dayofweekfriday dayofweeksunday result true oct 22 2010 is a fridayresult inbetweendaysinclusivenew datetime2010 10 22 dayofweekfriday dayofweeksunday result true oct 24 2010 is a sundayresult inbetweendaysinclusivenew datetime2010 10 24 dayofweekfriday dayofweeksunday result false oct 25 2010 is a mondayresult inbetweendaysinclusivenew datetime2010 10 25 dayofweekfriday dayofweeksundaythanks,['c#'] +95590,silverlight constructor injection into view model design mode im trying to get to grips with writing testable viewmodels in silverlight 4 im currently using mvvm light im using autofac and the ioccontainer is doing its job fine however to inject into the constructor of viewmodels which are bound to views i have this constructor chaining public userviewmodel thisioccontainerresolveiuserserviceasync public userviewmodeliuserserviceasync userservice if thisisindesignmode return userservice userservice which does not feel clean but is the best option i have found so far this works and my app works as desired and is testable with control inverted however with my vm bound to my view like this usercontroldatacontext viewmodeluserviewmodel usercontroldatacontextin my xaml page attributes design mode in both vs2010 and blend doesnt work is there are nicer way to achieve what im trying in silverlight that still works with design mode losing design mode isnt a deal breaker but will be handy while learning xaml a cleaner none chained way would be nice though im thinking it maybe possible to use autofac ioc to resolve viewmodels to views as apposed to the xaml markup approach above and go down this routethanks,['c#'] +95604,cookie is not a function when i try to load my page that uses jquery when the following line is hitif cookiecompare null i get the error cookie is not a function has anybody seen this before,"['javascript', 'jquery']" +95620,find all a substrings occurrences and locations i am writing a program to parse some data saved as text files what i am trying to do is find the location of every needle in a haystack i already can read the file in and determine the number of occurrences but i am looking to find the index also,['c++'] +95632,advantages of an empty class in c what could be the possible advantagesuses of having an empty classps this question might sound trivial to some of you but it is just for learning purpose and has no practical significance fyi googling did not help,['c++'] +95638,add a uinavigationbar to a uitableviewcontroller without a uinavigationcontroller i have an existing uitableviewcontroller that was previously being used in a uinavigationcontrolleri need to convert it to be presented as a modal view however i still want to have a navigation bar at the top i know this sounds strange why not present it in the uinavigationcontroller if i want a uinavbar i want to present it without the uitabbarcontroller that is associated with my uinavigationcontrolleri tried opening the xib adding a new view moving the uitableview to be a subview and adding a navigationbar to that new view as well however this does not seem to make any impact and the whole tableview is still presented no nav bar is visible i think this is because the class is a subclass of uitableviewcontrollerdo i need to convert this to a uiviewclass is there a good approach to adding a navbar in code or via interface builder to an existing uitableviewcontrollerthanks for any advice on how to approach this,['iphone'] +95648,does the order of fields in a where clause affect performance in mysql i have two indexed fields in a table type and userid individual indexes not a composite types field values are very limited let us say it is only 0 or 1 so 50 of table records have the same type userid values on the other hand come from a much larger set so the amount of records with the same userid is smallwill any of these queries run faster than the otherselect from table where type1 and userid5select from table where userid5 and type1also if both fields were not indexed would it change the behavior,"['sql', 'mysql']" +95655,androidwebkit textoverflow ellipsis not working i am trying to get the following code to work on an androind 21 phone htc sense uih1 fontsize 14px fontweight bold color f whitespace nowrap textoverflow ellipsis overflow hidden however the textoverflow property does not seem to work has anybody else had this problem or found a way to work around it,"['android', 'css']" +95662,ignore tab character in uitextfield ipad app i have a tableview with textfields in each cell and i want to those textfieldsignore the character tab twhen the tab key is pressed the textfieldshouldchangecharactersinrange method it is not calleddoes anyone knows how to do this i know that there is no tab key in the ipadkeyboard but the blutooth and dock ones do and triggers a really weird behaviorthanks,['iphone'] +95674,datadriven testing in nunit in mstest you can do something liketestmethoddatasourcemicrosoftvisualstudiotesttoolsdatasourcecsv testdatacsv testdatacsv dataaccessmethodsequentialpublic void testsomething double column1 converttodoubletestcontextdatarowcolumn1 assertareequalwhat is the equivalent code in nunit 25,['c#'] +95676,why are there extra pixels around my android gridview i have a gridview in my android application that has a number of imageviews in it the space on my screen is limited and i want the images to take up as much of the available space as they can unfortunately the gridview always leaves 5 pixels of empty screen space around the outside edge of the imageviews the space between imageviews is set with horizontalvertical spacing and behaves correctly the empty space acts kind of like a margin around the imageviews but i cannot get rid of it does anyone know whats causing this border and how i can get rid of it or at least make it smaller thanksupdate i am creating the imageviews by inflating an xml file in the getview method of my adapter class heres the xml i am inflatingimageview xmlnsandroid androidbackgroundff00ff i defined the gridview in my layout xml file like thisgridview androidididmygrid androidlayout widthfill parent androidlayout heightwrap content androidlayout aboveidabutton androidlayout marginbottom8dp androidnumcolumns5 androidbackgroundff0heres a screen shot of the problem the red area in my gridview the purple areas are my imageviews the image being thisplayed is a simple blue rectangle with a transparent center the image is 45x45 pixels but is only 30x30 pixels in my app i will worry about that later the red border around the purple is what i am trying to eliminate,['android'] +95687,how do i create an unfocusable form in c i am looking to create a form in c that cannot accept focus ie when i click a button on the form focus is not stolen from the application that currently has the focussee the windows onscreen keyboard for an example of this note that when you click a button the focus is not taken from the application youre currently usinghow can i implement this behaviourupdateturns out it is as simple as overriding the createparams property and adding ws ex noactivate to the extended window style thanks for pointing me in the right directionunfortunately this has the undesirable sideeffect that it messes with form movement ie you can still drag and drop the form around the screen but the windows border is not thisplayed while dragging so it is difficult to precisely position itif anyone knows how to solve this it would be appreciated,"['c#', '.net']" +95727,differences in putting a module in helpers or in lib what are the reasons putting a module in helpers over the lib folder in a ror appare helpers more controller specific while the lib is more general in nature,['ruby-on-rails'] +95735,rails how do i call selfsave in my model and have it persist in the database i am trying to keep model logic within my model but i cannot get it to perform modifications on itself and have them persist in the databasein my controllerarticleperform some calulcationsin my modeldef perform some calculations selffoogsubregexp string selfsaveendif i drop debugger statements into my method and after my call to it in the controller articlefoo has the correct value however when i continue it does not persist in the database and webrick does not report any update statementswhats going wrong i do not know if i have ever had to do this before but surely it is possible right,['ruby-on-rails'] +95745,what does data source cannot be empty use memory to open an inmemory database mean i recently converted my sql server database into sqlite db but when i try to open my sqlite using open it throws me this errordata source cannot be empty use memory to open an inmemory databaseedit added connection stringconnectionstring data sourcedxdbversion3connection new sqliteconnectionconnectionstringconnectionopenwhy do i get this i converted the same sql server database to sql ce and mysql and i did not get these errors,['c#'] +95765,get the logged on user name in c how do i get the current logged on user name in windows 7 ie the user who is physically logged on to the console in which the program that i am launching is runningfor example if i am logged on as mainuser and run my console application that will thisplay the logged on user name as subuser then the program only returns subuser as the currently logged on useri used the following 2 techniques to get the user name both are not getting me the thing that i wantsystemenvironmentgetenvironmentvariableusernamesystemsecurityprincipalwindowsidentitygetcurrentusernote that however this vbscript code returns the logged on user name irrespective of the user account from which this script is runstrcomputer set objwmiservice getobjectwinmgmts impersonationlevelimpersonate strcomputer rootcimv2 set compsys arr objwmiserviceexecquery select from win32 computersystem for each sys in compsys arr wscriptecho username sysusernamenextany way it is possible in c,['c#'] +95780,is it possible to list all functions in a module i defined a py file in this formatfoopydef foo1 passdef foo2 passdef foo3 passi import it from another filemainpyfrom foo import orimport foois it possible list all functions name eg foo1 foo2 foo3thanks for your help i made a class for what i want pls comment if you have suggestionclass getfuncviastrobject def init self d import foo for y in getattrfoo x for x in dirfoo if callabley dy name y def getattr self val if not val in selfd raise notimplementederror else return dval,['python'] +95798,can i replace a spring bean definition at runtime consider the following scenario i have a spring application context with a bean whose properties should be configurable think datasource or mailsender the mutable application configuration is managed by a separate bean let us call it configurationan administrator can now change the configuration values like email address or database url and i would like to reinitialize the configured bean at runtimeassume that i cannot just simply modify the property of the configurable bean above eg created by factorybean or constructor injection but have to recreate the bean itselfany thoughts on how to achieve this i would be glad to receive advice on how to organize the whole configuration thing as well nothing is fixed editto clarify things a bit i am not asking how to update the configuration or how to inject static configuration values i will try an examplebeans utilmap idconfiguration initial configuration utilmap bean idconstructorinjectedbean classfoo constructorarg valueconfigurationfoobar bean bean idconfigurationservice classconfigurationservice property nameconfiguration refconfiguration beanbeansso there is a bean constructorinjectedbean that uses constructor injection imagine the construction of the bean is very expensive so using a prototype scope or a factory proxy is not an option think datasourcewhat i want to do is that every time the configuration is being updated via configurationservice the bean constructorinjectedbean is being recreated and reinjected into the application context and dependent beanswe can safely assume that constructorinjectedbean is using an interface so proxy magic is indeed an optioni hope to have made the question a little bit clearer,['java'] +95809,html code for text checkbox i34 is there an html code for the text checkbox i34edit so to be clear i need the html number for the symbol i34 not the form element checkbox,['html'] +95812,are h1h2h3h4 tags block or inline elements is it correct html to change the color of text inside a h1 h2 h3 or h4 element are they block levelfor exampleh1span stylecolorabab500span hello worldh1,['html'] +95815,whats the current status of javascript es5 what browsers engines already support es5 strict,['javascript'] +95819,css selector speed according to new article from csstricks there is a big difference between how you select your elements because they are selected from right to leftthe article can be found herei am about to create a page that have different documents on the same pagemy question is how should i go about the html for css efficiency or vise versadiv classdocumenttype1 h1some headingh1 psome paragraphpdivdiv classdocumenttype2 h1some headingh1 psome paragraphpdivthere can be multiple of the same document type i can therefore not use an iddocumenttype1 h1 documenttype1 p documenttype2 h1 documenttype2 p this will be inefficient since all p tags are found firsthow would you go about it if this should be done faster and you should be able to move the same article to a new document type,['css'] +95820,why am i unable to select a custom type for a setting from the same projectassembly as the settings file i am trying to set the type of an application setting property to a custom enum type i have defined in my assembly call this project ain the settings browser i click browse and am presented with the select a type dialog boxand the types defined in project a are not seem to be available to me yet types are available from other projects that a has referencedit seems almost beyond comprehension to me that one would not be able to use types defined in the base project so i assume i am doing something wrong i have tried building cleaning rebuilding restarting without any luck so what exactly am i missingedit screenshot here,['c#'] +95850,why the moqproxycastleproxyfactory type initializer exception when using net40nocastle so i copied the sample code from the moq home page pretty much verbatim and am getting a castle proxy exceptionheres my code as a console app for an easier sampleusing systemusing systemcollectionsgenericusing systemlinqusing systemtextusing moqnamespace moqtestconsole public interface ilovethisframework bool downloadexistsstring s class program static void mainstring args mockilovethisframework mock new mockilovethisframework wow no recordreplay weirdness mocksetupframework frameworkdownloadexists20returnstrue hand mockobject as a collaborator and exercise it like calling methods on it ilovethisframework lovable mockobject bool download lovabledownloadexists20 verify that the given method was indeed called with the expected value mockverifyframework frameworkdownloadexists20 everything compiles nicely but when it calls mockobject the following exception is thrownsystemtypeinitializationexception was unhandled messagethe type initializer for moqmock1 threw an exception sourcemoq typenamemoqmock1 stacktrace at moqmock1initializeinstanceb 0 in dcodemoqsrcsourcemockgenericcsline 138 at moqpexprotectorinvokeaction action in dcodemoqsrcsourcepexprotectorcsline 56 at moqmock1initializeinstance in dcodemoqsrcsourcemockgenericcsline 136 at moqmock1ongetobject in dcodemoqsrcsourcemockgenericcsline 153 at moqmockgetobject in dcodemoqsrcsourcemockcsline 152 at moqmockget object in dcodemoqsrcsourcemockcsline 147 at moqmock1get object in dcodemoqsrcsourcemockgenericcsline 131 at moqtestconsoleprogrammainstring args in cprojectstestmoqtestconsolemoqtestconsoleprogramcsline 25 at systemappdomain nexecuteassemblyruntimeassembly assembly string args at systemappdomainexecuteassemblystring assemblyfile evidence assemblysecurity string args at microsoftvisualstudiohostingprocesshostprocrunusersassembly at systemthreadingthreadhelperthreadstart contextobject state at systemthreadingexecutioncontextrunexecutioncontext executioncontext contextcallback callback object state boolean ignoresyncctx at systemthreadingexecutioncontextrunexecutioncontext executioncontext contextcallback callback object state at systemthreadingthreadhelperthreadstart innerexception systemtypeinitializationexception messagethe type initializer for moqproxycastleproxyfactory threw an exception sourcemoq typenamemoqproxycastleproxyfactory stacktrace at moqproxycastleproxyfactoryctor at moqmock1cctor in dcodemoqsrcsourcemockgenericcsline 54 innerexception systemiofilenotfoundexception messagecould not load file or assembly castlecore version2500 cultureneutral publickeytoken407dd0808d44fbdc or one of its dependencies the system cannot find the file specified sourcemoq filenamecastlecore version2500 cultureneutral publickeytoken407dd0808d44fbdc fusionlog prebind state information log user jsidev001jmacintyrelog thisplayname castlecore version2500 cultureneutral publickeytoken407dd0808d44fbdc fullyspecifiedlog appbase filecprojectstestmoqtestconsolemoqtestconsolebindebuglog initial privatepath nullcalling assembly moq version40108270 cultureneutral publickeytoken69f491c39445e920log this bind starts in default load contextlog no application configuration file foundlog using host configuration file log using machine configuration file from cwindowsmicrosoftnetframeworkv4030319configmachineconfiglog postpolicy reference castlecore version2500 cultureneutral publickeytoken407dd0808d44fbdclog attempting download of new url filecprojectstestmoqtestconsolemoqtestconsolebindebugcastlecoredlog attempting download of new url filecprojectstestmoqtestconsolemoqtestconsolebindebugcastlecorecastlecoredlog attempting download of new url filecprojectstestmoqtestconsolemoqtestconsolebindebugcastlecoreexelog attempting download of new url filecprojectstestmoqtestconsolemoqtestconsolebindebugcastlecorecastlecoreexe stacktrace at moqproxycastleproxyfactorycctor innerexception so it appears to be a castle proxy component that is missing but i am referencing the binary from the net40nocastle directorylatest version of moq moq4010827and i am new to moq so i may be doing something extremely dense,['c#'] +95856,how do i send an sms from a shell i would like to be able to send an actual sms message from a shell using just the command line and not relying on any apk to do so i am interested in sending this message between phones not from the emulator to the phone for example by running the commandservice call phone 2 s16 1234567890i can place a call from phone to phone using the command line the service list command shows an isms service which i cannot seem to provide the correct arguments for i would assume that one of the args should be a pdu string but have not had any luck so far,['android'] +95857,paperclip style depending on model has many polymorphic images i have set up my models to use a polymorphic image model this is working fine however i am wondering if it is possible to change the styles setting for each model found some examples using sti model image however this is not an option for me because i am using a has many relationarthas many images as imageableimagebelongs to imageable polymorphic truehas attached file file styles thumb 150x150 normal 492x600 change this setting depending on modelupdatei tried starting up a debugger inside the proc method only fields related to the attached file is populatedrunirbimage0060 ainstance image id nil created at nil updated at nil imageable id nil imageable type nil file file name img 9834jpg file content type imagejpeg file file size 151326 file updated at 20101030 084023this is the object from imagecontrollercreateimagecontrollercreateimage image id nil created at nil updated at nil imageable id 83 imageable type art file file name img 9834jpg file content type imagejpeg file file size 151326 file updated at 20101030 083249i am using paperclip 235 and rails 301 no matter what i do the ainstance object is the image with only the fields related to the attachment populated any ideasupdate2after reading a lot on the paperclip forum i do not believe it is possible to access the instance before it has been saved you can onlye see the paperclip stuff and that is iti got around this problem by presaving the image from the image controller with a before filter without the attachment before filter presave image only create private def presave image if imageidnil save if new record arts controller sets image image imagenewimageable type paramsimageimageable type imageable id paramsimageimageable id imagesavevalidate false imagefile paramsfile set to paramsimagefile if you edit an image end end,"['ruby-on-rails', 'ruby']" +95868,is using namespacelike bad possible duplicatewhy is using namespace std considered a bad practice in c every time i use using namespace std i always get that thats a terrible programming habitnow i am graduating this december with my bs in cs but i do not claim to know everything but no one has ever explained why this is so bad i understand what it does but i honestly do not see a huge deal with itanyone care to explain in my mind it just makes typing cout a whole lot more bearable than stdcouti can understand why you wouldnt want to put it in a header file but just in a normal implementation file i dont see why it would be a problem,['c++'] +95872,initializer properties accessors and copyretainreadonly i want to understand how to set the parameters of properties accessorsi took the following code from an example of kal calendar holidayhinterface holiday nsobject nsdate date nsstring name nsstring countryproperty nonatomic retain readonly nsdate dateproperty nonatomic retain readonly nsstring nameproperty nonatomic retain readonly nsstring country idinitwithnamensstring name countrynsstring country datensdate dateend holidaymimport holidayhimplementation holidaysynthesize date name country idinitwithnamensstring aname countrynsstring acountry datensdate adate if self super init name aname copy country acountry copy date adate retain return self voiddealloc date release name release country release super deallocend1 the properties are set to retain but since the setter cannot be used the retain makes no sense here2 in addition in the initwithname method the values are set with copy why not directly defining the properties with copy and using the accessor methodsproperty nonatomic copy nsstring name selfname aname3 do i need the readonly here i do not know why they are used here if i would use copy together with the setter the readonly prohibits me to set the value because there is no setter4 in the initwithname method sometimes copy and sometimes retain is used i would suggest to use always copy here because the value should not get modified later5 what i can remember is that it is ok to copyretain in the initwithname and release in the dealloc methodso how would you suggest to use retain copy and readonly in this example here,"['iphone', 'objective-c']" +95878,linq performance faq i am trying to get to grips with linq the thing that bothers me most is that even as i understand the syntax better i do not want to unwittingly sacrifice performance for expressiveness are they any good centralized repositories of information or books for effective linq failing that what is your own personal favourite highperformance linq technique i am primarily concerned with linq to objects but all suggestions on linq to sql and linq to xml also welcome of course thanks,"['c#', '.net']" +95879,new line in silverlights textblock i know that some will reply things such as linebreak this is not what i am looking for i want to know if i store textblocks string in a resource file can i do some thing about it to make the text in textblock to go to a new linetried lt linebreak gt wo spacetried rntried 1310none of the options worked anyone got ideas,['c#'] +95889,how can i use php to list all the dates in a year i am trying to use php to create a script that searches all the days between now and one years time and lists all the dates for fridays and saturdays i was trying to use phps date and mktime functions but cannot think of a way of doing this is it possiblethanksben,['php'] +95910,can i test status bar notifications using androids testing framework i have a class that sends a status bar notification in android i cannot find a way to test whether the notification was sent or not which makes it very hard to write any kind of useful unit testdoes anyone have a solution for this,"['java', 'android']" +95913,storage size of anamesa isnat known i get this error while compiling this c source fileinit source buildsrcnames listc7 error storage size of anamesa isnat knowninclude stdiohinclude listhint main struct list names namessize 3 struct listelmt michael struct listelmt john struct listelmt adams nameshead michael michaeldata 12 michaelnext john johndata 14 johnnext adams adamsdata 16 struct listelmt pointer listhead forint x 0 x 3 x printfiterationd data d x pointerdata pointernext pointernextnext and here is header of this linked listifndef list hdefine list hinclude stdioh define linked list elementstypedef struct listelmtvoid datastruct listelmt next listelmt define a structure for the listtypedef struct listint sizeint matchconst void key1 const void key2void destroyvoid datalistelmt headlistelmt tail listvoid list initlist list void destroyvoid datavoid list destroylist listint list ins nextlist list listelmt element const void dataint list rem nextlist list listelmt element void dataint list sizeconst list listlistelmt list headconst list listlistelmt list tailconst list listint list is headconst listelmt elementint list is tailconst listelmt elementvoid list dataconst listelmt elementlistelmt list nextconst listelmt elementendif,['c'] +95948,asserting order of synchronization in java in highly concurrent systems it can be difficult to be confident that your usage of locks is correct specifically deadlocks can result if locks are acquired in an order that was not expected while being acquired in the proper order in another threadthere are tools eg coverity which can do static analysis on a code base and look for unusual locking orders i would like to explore other options to meet my needsare there any lightweight tools for instrumenting java code which can detect cases where locks are being acquired in an order other than expected i am okay with explicitly calling out locking orders via comments annotationsfree andor opensource solutions preferred please also comment if there are noninstrumentation approaches to this problem for my purposes lightweight meansif it is instrumentation i can still run my program with the same ballpark performance 3050 degradation is acceptable i supposei do not have to spend half the day interacting with the tool just to get an okay out of it ideally i should only notice that i am using it when there is a problemif it is instrumentation it should be easy to thisable for production environmentsit should not clutter my code at every synchronize statement as previously mentioned i am okay with explicitly commentingannotating the objects or classes of objects which get locked with relative orderings,['java'] +95950,how to redirect without w using rails 3 rack i understand there are a lot of questions that answer this i am familiar with htaccess and nginxconf methods but i do not have access to such traditional configuration methods on heroku simone carletti gave this answer that leverages rails 2x metals but i am using rails 3 and this is not compatibleredirect nonw requests to w urls in rails please notei am not looking for a simple before filter in my applicationcontroller i would like to accomplish a rewrite similar to simones i believe this is job for the webserver or middleware like rack at the very least so i would like to leave this bit out of the actual app codegoalredirect to statuswfoocom foocom 301wfoocomwhatever foocomwhatever 301only hosts matching w should be redirect all other requests should be ignored,['ruby-on-rails'] +95974,itunes connect does not allow to enter multiline description i have just submitted my first app to the app store and i have problem with description field in itunes connect it does not allow me to enter multiline value i have tried everything copyingpasting from different editors entering manually etc if there is one line like hello world it saves successfullywhen i have got at least 2 lines of text lkehelloworld it just shows me the following error message and does not savedescription cannot contain control characters for example null new lines carriage returns escape and other invisible characters,['iphone'] +96005,setting a different taskbar icon to the icon thisplayed in the titlebar c i have both dark and light versions of my application icon the dark version works best on gray surfaces such as windows xp taskbar where the light version works best as an icon in the titlebaris there a way i can set the icon in the taskbar to a different icon than the one used in my form in c pinvoke is fine,['c#'] +96029,what is the difference between typecasting and typeconversion in c or java what is the difference between typecasting and typeconversion in c or java,"['java', 'c++']" +96038,how to convert utf8 to unicode i try to convert a utf8 string to a java unicode string string question requestgetparametersearchwordbyte bytes questiongetbytesquestion new stringbytes utf8the input are chinese characters and when i compare the hex code of each caracter it is the same chinses character so i am pretty sure that the charset is utf8 where do i go wrong,['java'] +96042,why is my eclipse launch configuration not being added to the run or debug configurations list just finally found a solution for this so thought i would post it here as a question and answer so i find it next time i google iti have a launch file which i can run by context menu run as but it is not being added to the list of debug or run configurations like it should why not,['java'] +96050,execute an installed python package as a script is there a way to enable a package to be executed as a script for example easy install pathtofooegg python m foo name worldhello worldi have tried creating a main py file inside my package but it is not being executed i am using python 26 the following error is raised foo is a package and cannot be directly executedthe structure of my package is as followsfoo setuppy foo init py main pyrunning python m foo main name world works as expected but i would prefer the former way of execution is this possible,['python'] +96064,commenting code c visual studio best practise i am looking for a rather arbitrary answer so this might more be a thiscussion i am wondering what the best practise for commenting my c code in visual studio is right now i am using the triple to generate the xml and use sand castle to build a chm or html file but my problem is that i use code comments for two reasonswhen other developers are using my code they can read the documentation both intellisence and the chm or html filebut i also use commenting as reminders to myself so i can remember my thoughts when i come back half a year later to some complex methodshow can both goals be accomplished without interfering with each other and in the same time be a quick task not taking a lot of coding time,['c#'] +96065,how do i properly load the jquery fullcalendar plugin in a hidden div i am using the jquery tools tabs to divide my page into tabs one of those tabs contain a jquery fullcalendar because i load javascript last in the page for speed and to avoid flash of unstyled content i hide the initially unseen tabs using thisplaynone when doing this the fullcalendar does not render properly it shows the proper buttons but until i press the todaybutton no calendar is shown if i allow it to render into a visible div it thisplays properlyi can work around this using the tabselect events to render the calendar or by moving the calendar and tab scripts to the head but i would rather if there was a more proper solution,['jquery'] +96066,bulk insert using stored procedure i have a query which is working finebulk insert zipcodes from e5digit commercialcsv with firstrow 2 fieldterminator rowterminator n but now i want to create a stored procedure for iti have written below code to make its stored procedurecreate proc dboinsertzipcodefilepath varchar500e5digit commercialcsvasbeginbulk insert zipcodes from filepath with firstrow 2 fieldterminator rowterminator n endbut its showing errormsg 102 level 15 state 1 procedure insertzipcode line 6 incorrect syntax near filepathmsg 319 level 15 state 1 procedure insertzipcode line 7 incorrect syntax near the keyword with if this statement is a common table expression an xmlnamespaces clause or a change tracking context clause the previous statement must be terminated with a semicolonplease tell me what i am doing wrong and what i can do to make it work in stored procedurethanks,['sql'] +96081,in wpf how to get binding of a specific item from the code the example of this would bea textbox is bound to some data there is a second text box which is not bind to anything so i want to bind text box 2 to the same data 1st textbox is boundin other words i want to know if the dependencyobject stores some reference to it is databindings if not what is the way to find out all databindings of a specific object,['c#'] +96104,c class with objectivec friend i have an application thats a mix of c and objectivecquite a lot of the c classes exist merely as facades to access the underlying objectivec object from the rest of the x applicationmy problem is one of design the objectivec class needs to call back into the c class via a set of methods i would prefer to mark as private no other c class not even derived classes needs to be messing around with thesebut i cannot mark them private as there does not seem to be a way to make objectivec class methods friends of a c classi considered cheating and using macros to mark the c methods as public when objc is defined but that changes the methods decoration and would result in link errorsanyone else encountered this myviewmminterface myview nsview public cmyview cppvoiddrawrectnsrectdirtyrect cgcontextref cgc cgcontextrefnsgraphicscontext currentcontextgraphicsport cppdrawcgc myviewhclass cmyview id view public this method should be private it exists only for the myview objc class void onpaintcgcontextref cdc,"['c++', 'objective-c']" +96110,assertequals does not work without second parameter casting folks why i am getting the the method assertequalsstring object object is ambiguous for the type dictionarytest error for this junit test test public void testeditcard integer a 10 integer b 12 integer c 2 assertequalstest ab c adding casting assertequalstest integerab c resolves the problem,['java'] +96114,how to call wine dll from python on linux i am writing a python script in linux and need to call some windows functions available in wine specifically allocateandinitializesid and lookupaccountsidw to determine who is logged in to a remote windows computer these functions are part of advapi32dll in wine edit using the answers i was able to call the function but lookupaccountsidw only works on the local computerhow can i access these functions or a wine dll in general i have tried cdloadlibrarywinedrive cwindowssystem32advapi32dllbut it results in an erroroserror winedrive cwindowssystem32advapi32dll invalid elf headeris there another ctypes function that would work or some wine interface i could use,['python'] +96117,deciphering the net clr20r3 exception parameters p1p10 i am trying to decipher the meaning on the p1p10 parameters associated with a clr20r3 that is written to the event log when my application experiences an exceptionthe best i have been able to find isp1 the hosting process eg w3wpexep2 the hosting process version eg 6037901830p3 eg 42435be1p4 the assembly from which the exception was raised eg mrtableswebservicep5 the assembly version eg 2120p6 eg 4682617fp7 eg 129p8 eg 50p9 the exception type raised eg systemargumentexceptionp10 eg nilgoogling for clr20r3 provides thousands of sample parameter values from which someone can try to derive a patternbut i am hoping for documentation on the parameter meanings as opposed to educated guessesedit while i can hope for canonical documentation really i would be happy to see the exception being thrown at what line complete with a stack trace,['.net'] +96121,most efficient way to make the first character of a string lower case what is the most efficient way to make the first character of a string lower casei can think of a number of ways to do thisusing charat with substringstring input someinputstringstring output charactertolowercaseinputcharat0 inputlength 1 inputsubstring1 or using a char array string input someinputstring char c inputtochararray c0 charactertolowercasec0 string output new stringci am sure there are many other great ways to achieve this what do you recommend,['java'] +96125,how to make an opengl rendering context with transparent background rendering contexts usually have a solid color on the background black or whatever see the image belowi am wondering if it is possible to setup a window with no decorations and with the transparent background while allowing me to render opengl stuff on itthis would give the illusion that the triangle is floating on the screen the transparent background should allow you to see the desktop or other applications that might be behind itcould you please exemplify with source codeplatform windows win32 only,['c'] +96132,css scrollbar width folks is it possible to increase the width of a scrollbar on a div element placed inside the bodyi am not talking about the default scrollbar on the browser itself this page runs in full screen mode and because the browser scrollbar never comes into picture the inner div element has its own scrollbar,"['html', 'css']" +96181,audio input on android emulator how can one get audio input on the android emulator i am using the 22 sdk and emulating on ubuntu 1010i have the hwaudioinput property set to yes on my emulator but i get the message recognizer not present when i run the voice recognition api demo app on the emulator on my phone of course it works finei am trying to use the speech input stuff from the sdk as mentioned here they do not mention a thing about getting it to work on the emulatori have seen postings all over the forums about this with little to no sure solutions or successes you know how it goes with forums that is why i am posting this question to stackoverflow hopefully we can get one clearcut answer,['android'] +96186,java code for wrapping text lines to a max line width before i reinvent the wheel poorly i would like to know if there is a some existing java code for wrapping text lines to a given maximum width ideally it wouldrespect existing linebreaksbreak up lines that exceed a maximum length on word boundariesbreak up words whose length exceeds the maximum line width by inserting hyphensedit there are no pixels here only javalangstring maximum width refers to the number of characters on a line,['java'] +96187,facebook graph api php sdk posting on page as page it is final try with php if it fails i will try with js so my goal is to post on fb page as page name through php this is what i want to getbut all i get is shown pic below also it is visible only to this profile not to friendsppl who likeetc this is my current codefunction post facebookdatanull redir null result require once root appsconfigurationmodelsconfigurationitemphp require once root componentsfacebookfacebookphp thisconfigurationitem new configurationitemthisgetcontext rowthisconfigurationitemfindbycatkeyitemkeysystemfacebook login apiidrowvalue correct apiid rowthisconfigurationitemfindbycatkeyitemkeysystemfacebook pass secretrowvalue correct secret key facebook new facebookarray appid apiid secret secret cookie true session facebookgetsession me null if session try uid facebookgetuser me facebookapime catch facebookapiexception e error loge messagedatafacebook text attachment array message datafacebook text name dataname link thisgetlinktolatestnews description try facebookapipage idfeed post attachment result facebook sent catch facebookapiexception e result facebook failed error loge else login url facebookgetloginurl headerlocation login url exit echo result exit return result what i am doing wrong i could not find anything in api documentationtop google results only for js thanks for help,['php'] +96202,googles voice search speech recognition service google has speech recognition services available for use from mobile phones android has it built in iphone users can use the google application weve found one article where someone tried to reverse engineer the service at google mobiles voice search on the iphonewe want to better understand what is happening over the network when we use androids recognizerintent does anyone have any experience using this service over the web or know of other articles that may explain its workings,['android'] +96203,unit testing with djangocelery i am trying to come up with a testing methodology for our djangocelery project i have read the notes in the documentation but it did not give me a good idea of what to actually do i am not worried about testing the tasks in the actual daemons just the functionality of my code mainly i am wonderinghow can we bypass taskdelay during the test i tried setting celery always eager true but it made no differencehow do we use the test settings that are recommended if that is the best way without actually changing our settingspycan we still use managepy test or do we have to use a custom runneroverall any hints or tips for testing with celery would be very helpful,['python'] +96207,script to save varbinary data to thisk i have some varbinary data stored in a table in ms sql server 2005 does anyone have sql code that takes a query as input lets say the query guarantees that a single column of varbinary is returned and outputs the bytes to thisk one file per row i am sure this has been asked a thousand times before but googling comes up with mostly net solutions i want an sql solution,['sql'] +96217,any way to boost jvm startup speed it is said that java is 10x faster than python in terms of performance that is what i see from benchmarks too but what really brings down java is the jvm startup timethis is a test i madetime xlsx2csvpy types of esi v2docembpackage9output skippedreal 0m0085suser 0m0072ssys 0m0013stime java jar client usrlocalbintikaapp07jar m types of esi v2docembpackage9real 0m2055suser 0m2433ssys 0m0078ssame file a 12 kb ms xlsx embedded file inside docx and python is 25x faster wthit takes 2055 sec for javai know it is all due to startup time but what i need is i need to call it via a script to parse some documents which i do not want to reinvent the wheel in pythonbut as to parse 10k files it is just not practicalanyway to speed it up i already tried client option and it only speed up by so little20 my another idea run it as a longrunning daemon communicate using udp or linuxicp sockets locally,['java'] +96221,can background image extend beyond divs borders can background image extend beyond divs borders does overflow visible apply to this,"['css', 'html']" +96225,maintaining directory structure when loading local files into uiwebview on iphone i am noticing a minor annoyance when working with local files in a uiwebview and hoping there is a simple workaround as a simplified example lets say in my xcode project i have a folder called webproject that contains an html file and a subfolder called images where the images reside the html file references the images as youd expect srcimagesmyimagejpg for example which works just dandy if this where are normal webpage when you load the html file in a uiwebview however this image would not show up because it seems that all of the files are just thrown into one big bundle folder so the image link is actually srcmyimagejpg is there anyway to enforce the directory structure of these files in the main bundle so that this sort of thing does not happen thanks,['iphone'] +96237,default value of guid in for a column in mysql i want a column to default to a guid so if i am doing an insert and i do not explicitly set the value i want it to default to a new guid valuehow can i do this,"['sql', 'mysql']" +96243,how to access css properties in javascript when applied via external css file i have a little problem when i set the css rule using some property say backgroundimage in an external css file and then try to access it using javascript in another external js file it does not work that is to say i do not get any value for documentgetelementbyidsomeidstylebackgroundimagebut when i set the css rule using style attribute in html file itself it worksso my query is cannot i access css property in js if css is set in external css file,"['javascript', 'html', 'css']" +96248,is chromes javascript console lazy about evaluating arrays i will start with the codevar s hiconsolelogss0 byeconsolelogssimple right in response to this firebug sayshibyewonderful but chromes javascript console 7051741 beta saysbyebyehave i done something wrong or is chromes javascript console being exceptionally lazy about evaluating my array,['javascript'] +96271,how to create android spinner without down triangle on the right side of the widget i have a screen where the user has many items to input so screen space is at a premium i want the look of the widget on the screen before the user presses it to be similar to an edittext or the left portion of the spinner widget without the normal down triangle on the right side of the spinner then when the user presses the widget heshe will get the normal spinner selection dialog is there some spinner style attribute i can change to accomplish thisi have not been able to see code like thisthanks,['android'] +96292,how to supress c warning cs0675 bitwiseor operator used on a signextended operand i cannot seem to get rid of this warning for the following line of codedwordwrdindex dgetwordenglish ulongithe warning applies to the code after the assignment operator the method getword returns a ulong i have tried the following to no availdwordwrdindex dgetwordenglish ulongidwordwrdindex dgetwordenglish ulongidwordwrdindex ulongdgetwordenglish ulongianyone have any ideas,"['c#', '.net']" +96293,android tablelayout width i have a two column tablelayout as the only child of a scroll view the first column contains textviews labels and the second column contains edittextspinnerdatewidget etc values even though i have have specified androidlayout widthfill parent for tablelayout tablerow all widgets in values columnthe screen looks perfect when the activity is created however when one types a really long value in the edittext the values column goes beyond the visible screen areahow do i tackle thisthanks,['android'] +96298,how to set named argument for stringformat i have c error when callingstringformatformatabbc 122the error is named argument specifications must appear after all fixed arguments have been specifiedhow can i fix thisediti prefer to use named parameters,['c#'] +96308,use jquery to control video tag so i want to use a jquery function to collect a url from a links rel and pass it to a elementcollecting the rel and sending it to the is no problem but whats required to trigger the elements load and play functions from jqueryheres what i have so farfunction acomponentlinkclickfunction eventpreventdefault var vidurl thisattrrel myvideo sourceattrsrc vidurl myvideoload myvideoplay atm it does not play i assume jquery does not natively have access to the play function but there must be a way around that,"['javascript', 'jquery', 'html']" +96309,change font of uinavigationcontroller title can i change the font of my uinavigationcontroller title,['iphone'] +96319,how database stores data internally in btreebtree my question is that how database stores data and how it performs query internallysuppose we have following fields in our tableidnameageweightmanagerand we query select from table1 where age50 and weight100i am just curious that how it perform query internally what will the node of btrebtree contains in this example,"['mysql', 'sql']" +96351,output each combination of an array of numbers with javascript i have several numbers in an arrayvar numarr 1 3 5 9i want to cycle through that array and multiply every unique 3 number combination as follows1 3 5 1 3 9 1 5 9 3 5 9 then return an array of all the calculationsvar ansarr 152745135anyone have an elegant solution thanks in advance,['javascript'] +96368,trouble getting pylint to find inherited methods in pylonssa models i have a pylons app that i am using sqlalchemy declarative models for in order to make the code a bit cleaner i add a query onto the sa base and inherit all my models from that so in my appmodelmeta i havebase declarative basemetadata basemetadatasession scoped sessionsessionmakerbasequery sessionquery propertyqueryi think inherit this into appmodelmymodel and declare it as a child of metabase this lets me write my queries as mymodelqueryfiltermymodelid 3allthe trouble is that pylint is not seeing query as a valid attribute of my models e102jobcounterreset count class jobcounter has no query memberobviously this error is all over the place since it occurs on any model doing any query i do not want to just skip the error because it might point out something down the road on nonorm classes but i must be missing something for pylint to accept thisany hints,['python'] +96407,multiple table sqlite db adapters in android i was reading the android sqlite notepad tutorial that referenced creating a db adapter class to create and access a db table when dealing with a multitable sqlite database is it best practice to create a different adapter class for each table or create a single db adapter class for the entire android applicationmy application uses multiple tables and i was hoping not to have to have a single massive adapter class the problem however is that i have a nested subclass of sqliteopenhelper per the notepad example within each adapter when the first table is accessed everything works fine when i then try to access the second tblefrom a different activity my app crashesat first i thought the crash was being caused by a versioning issue but both adapters now have the same database version and it is still crashingheres an example of one of the db adapters for the table the other adapters all follow the same format with varying implementationspublic class infodbadapter public static final string row id id public static final string name name private static final string tag infodbadapter private static final string database name myappdb private static final string database table usersinfo private static final int database version 1 private static final string database create create table usersinfo id integer primary key autoincrement name text private databasehelper mdbhelper private sqlitedatabase mdb private final context mctx private static class databasehelper extends sqliteopenhelper databasehelpercontext context supercontext database name null database version override public void oncreatesqlitedatabase db dbexecsqldatabase create override public void onupgradesqlitedatabase db int oldversion int newversion logwtag upgrading database from version oldversion to nonnls1nonnls2 newversion which will destroy all old data nonnls1 dbexecsqldrop table if exists usersinfo nonnls1 oncreatedb public infodbadaptercontext ctx thismctx ctx public infodbadapter open throws sqlexception thismdbhelper new databasehelperthismctx thismdb thismdbhelpergetwritabledatabase return this close return type void public void close thismdbhelperclose public long createuserstring name contentvalues initialvalues new contentvalues initialvaluesputname name return thismdbinsertdatabase table null initialvalues public boolean deleteuserlong rowid return thismdbdeletedatabase table row id rowid null 0 nonnls1 public cursor fetchallusers return thismdbquerydatabase table new string row id name null null null null null public cursor fetchuserlong rowid throws sqlexception cursor mcursor thismdbquerytrue database table new string row id name row id rowid null nonnls1 null null null null if mcursor null mcursormovetofirst return mcursor public boolean updateuserlong rowid string name contentvalues args new contentvalues argsputname name return thismdb updatedatabase table args row id rowid null 0 nonnls1 when the first adapter in this case usersinfo is accessed everything works as expected let us say i have another adapter for friend info that follows the same structure as above when it is accessed by a different activity it would seem to me that the nested subclass of sqliteopenhelper would attempt to create the database again obviously something is wrong because in that scenario my app crashesso is the standard practice within android to create a single mammoth db adapter instead of individual adapters per table,['android'] +96411,opencl for python i am looking for a good opencl wrapperlibrary for python with good documentation i tried to search some but could not find one good enough,['python'] +96421,what is the difference between the standard library and the standard template library i keep seeing reference to both the c standard library and the c standard template library stl what is the difference between them wikipedia mentions that they share some headers but that is about it,['c++'] +96430,has anyone found osgi to be useful in corporate applications has anyone deployed a corporate application in osgi and found it usefuli can see the benefits forced modularity good dependency definitions etc but these seem to be mainly build related improvementshas anyone found it useful to dynamically replace an existing module we tend to split our application by process and to be honest it is not that difficult to startup a new instance of the app with updated libraries would osgi be useful for thishow reliable is the replacing of a module it strikes me that if you have a very busy process with lots going on replacing a running module is fraught with danger,['java'] +96442,using clientserver certificates for two way authentication ssl socket on android i am working on an android app that requires both client and server certificate authentication i have an sslclient class that i created that works beautifully on regular desktop java se 6 i have moved it into my android project and i am getting the following error keystore jks implementation not foundi have looked online a bit and it looks like there is a possibility that java keystores are not supported on android awesome but i have a feeling there is more to it than that because none of the sample code i have found resembles what i am trying to do at all everything i found talks about using an http client rather than raw ssl sockets i need ssl sockets for this applicationbelow is the code in my sslclientjava file it reads the keystore and truststore creates an ssl socket connection to the server then runs a loop while waiting for input lines from the server then handles them as they come in by calling a method in a different class i am very interested to hear from anyone with any experience doing ssl sockets on the android platformimport javaiobufferedreaderimport javaioioexceptionimport javaioinputstreamimport javaioinputstreamreaderimport javaiooutputstreamwriterimport javaioprintwriterimport javasecurityaccesscontrolexceptionimport javasecuritykeymanagementexceptionimport javasecuritykeystoreimport javasecuritykeystoreexceptionimport javasecuritynosuchalgorithmexceptionimport javasecurityunrecoverablekeyexceptionimport javasecuritycertcertificateexceptionimport javaxnetsslkeymanagerfactoryimport javaxnetsslsslcontextimport javaxnetsslsslsocketimport javaxnetsslsslsocketfactoryimport javaxnetssltrustmanagerfactoryimport otherpackegeotherclassimport androidcontentcontextimport androidutillogpublic class sslclient static sslcontext ssl ctx public sslclientcontext context try setup truststore keystore truststore keystoregetinstancebks trustmanagerfactory trustmanagerfactory trustmanagerfactorygetinstancetrustmanagerfactorygetdefaultalgorithm inputstream truststorestream contextgetresourcesopenrawresourcerrawmysrvtruststore truststoreloadtruststorestream testtesttochararray trustmanagerfactoryinittruststore setup keystore keystore keystore keystoregetinstancebks keymanagerfactory keymanagerfactory keymanagerfactorygetinstancekeymanagerfactorygetdefaultalgorithm inputstream keystorestream contextgetresourcesopenrawresourcerrawclientkeystorekeystoreloadkeystorestream testtesttochararray keymanagerfactoryinitkeystore testtesttochararray logdssl key keystoresize logdssl trust truststoresize setup the ssl context to use the truststore and keystore ssl ctx sslcontextgetinstancetls ssl ctxinitkeymanagerfactorygetkeymanagers trustmanagerfactorygettrustmanagers null logdssl keymanagerfactory keymanagerfactorygetkeymanagerslength logdssl trustmanagerfactory trustmanagerfactorygettrustmanagerslength catch nosuchalgorithmexception nsae logdssl nsaegetmessage catch keystoreexception kse logdssl ksegetmessage catch ioexception ioe logdssl ioegetmessage catch certificateexception ce logdssl cegetmessage catch keymanagementexception kme logdssl kmegetmessage catchaccesscontrolexception ace logdssl acegetmessage catchunrecoverablekeyexception uke logdssl ukegetmessage try handler handler new handler handlerstart catch ioexception ioexception ioexceptionprintstacktrace class handler implements runnable class handler extends thread private sslsocket socket private bufferedreader input static public printwriter output private string serverurl 17461103206 private string serverport 60 handlersslsocket socket throws ioexception handler throws ioexception public void sendmessagameinfogestring message handleroutputprintlnmessage override public void run string line try sslsocketfactory socketfactory sslsocketfactory sslclientssl ctxgetsocketfactory socket sslsocket socketfactorycreatesocketserverurl integerparseintserverport thisinput new bufferedreadernew inputstreamreadersocketgetinputstream handleroutput new printwriternew outputstreamwritersocketgetoutputstream logdssl created the socket input and output do line inputreadline while line null line inputreadline parse the message and do something with it done in a different class otherclassparsemessagestringline while lineequalsexit catch ioexception ioe systemoutprintlnioe finally try inputclose outputclose socketclose catchioexception ioe finally updatemaking some good progress on this problem found out that jks is indeed not supported neither is directly choosing the sunx509 type i have updated my code above to reflect these changes i am still having an issue with it apparently not loading the keystore and truststore i will update as i figure out moreupdate2i was doing my keystore and truststore file loading in a desktop java way rather than the correct android way the files must be put in the resraw folder and loaded using getresources i am now getting a count of 1 and 1 for the keystore and truststore size which means they are loading i am still crashing on an exception but getting closer i will update when i get this workingupdate3looks like everything is working now with the exception of my keystore being set up incorrectly if i thisable client side authentication on the server it connects without issue when i leave it enabled i get a handling exception javaxnetsslsslhandshakeexception null cert chain error so it looks like i am not setting up the certificate chain correctly i have posted another question asking how to create a client keystore in the bks format with the proper certificate chain how to create a bks bouncycastle format java keystore that contains a client certificate chain,"['java', 'android']" +96471,running eclipse with command line arguments is there some way by which i can configure eclipse to run a program with certain command line arguments for debugging,['java'] +96507,how to turn on the wifi on android emulator device today i want to measure the wifi signal quality so i download the wifi analyzer app and i install it on the emulatorbut it showed that the wifi has not been turned on thus i turn it on but it still shows errors i tried several times but it is still not workingany ideas,['android'] +96520,why is wpfs drawingcontextdrawtext so expensive in wpf 40 my listbox using a virtualizingstackpanel contains 500 items each item is of a custom type class page frameworkelementprotected override void onrenderdrawingcontext dc drawing 10 single characters to different positions formattedtext is a static member which is only instantiated once and contains the string a or b for int i 0 i 10 i dcdrawtextformattedtext new point drawing 10 ellipses very fast and low ram usage for int i 0 i 10 i dcdrawellipsebrushesblack null new point1010now when moving the scrollbar of the listbox back and forth so that every items visual is created at least once the ram usage goes up to 500 mb after a while and then after a while goes back to ca 250 mb but stays on this level memory leak i thought the advantage of a virtualizingstackpanel is that visuals which are not neededvisible get thisposed anyway this extreme ram usage only appears when drawing text using drawtext drawing other objects like drawellipse does not consume so much memory is there a more efficient way to draw many text items than using drawingcontexts drawtext here is the complete sample just create a new wpf application project and replace the window1 code i know there are flowdocument and fixeddocument but they are no alternativexamlwindow xclasswpfapplication1window1xmlnsxmlnsxtitlewindow1 height900 width800grid backgroundblack listbox namelb scrollviewercancontentscrolltrue backgroundblack listboxitemspanel itemspaneltemplate virtualizingstackpanel orientationhorizontal itemspaneltemplate listboxitemspanel listboxgridwindowand the window1xamlcspublic partial class window1 window readonly observablecollectionframeworkelement collection new observablecollectionframeworkelement public window1 initializecomponent for int i 0 i 500 i collectionaddnew page width 500 height 800 lbitemssource collection public class page frameworkelement static formattedtext formattedtext new formattedtexta cultureinfogetcultureinfoenus flowdirectionlefttoright new typefacenew fontfamilyarialtostring 12brushesblack protected override void onrenderdrawingcontext dc dcdrawrectanglebrusheswhite null new rect0 0 width height double yoff 0 for int i 0 i 10 i draw 10 as dcdrawtextformattedtext new pointi 80 5 yoff if i 80 0 yoff 10,['c#'] +96528,how to create a method parameter object with resharper in a few seconds is it possible to select all the parameters of a method and ask resharper to create a class from those parameters as a method parameter object,['.net'] +96539,c warning mark assemblies with neutralresourceslanguageattribute i am getting the following warningca1824 mark assemblies with neutralresourceslanguageattributeaccording to msdn the cause of this isan assembly contains a resxbased resource but does not have the systemresourcesneutralresourceslanguageattribute applied to it could anyone please explain what it meansi do not want to define specific culture setting i want them to be customisable,['c#'] +96552,android intent filter i am trying to register my activity so that it can be used by the activity chooserpicker allowing a user to choose whether or not to select my applicationactivity to complete what they are trying to doi want to provide the option for the user to be able to select my application when they want to send an sms message and when they want to place an outgoing call to try to achieve this i added the following pieces of code within my activity tags in my manifestintentfilteraction androidnameandroidintentactionsendto category androidnameandroidintentcategorydefault data androidmimetypetextplain intentfilterintentfilteraction androidnameandroidintentactionnew outgoing call category androidnameandroidintentcategorydefault intentfilterhowever the activity chooser never appears and the native apps are used without providing a choice to the user can anyone see where i am going wrongediti have figured out i need to add data androidschemesms data androidschemesmsto for the sms message but what do i use for the outgoing calledit 2i have tried the following for the outgoing call intentfilter action androidnameandroidintentactionview action androidnameandroidintentactiondial category androidnameandroidintentcategorydefault category androidnameandroidintentcategorybrowsable data androidschemetel intentfilterbut again with no luck has this been blocked from 16 onedit 3this is what happens when i click text mobileso i want the same thing when i click call mobile,['android'] +96558,library to integrate googles oauthopenid hybrid in java web app i am building a java web app that needs access to a users google calendar data therefore i thought the oauthopenid hybrid is the best way to gowhats the best library to handle the job and reduce the amount of code on my endi tried openid4java spring security openid both do not support hybrid as well as dyuproject could not get it integratedps gae is not an optionany ideas,['java'] +96559,why cannot i use a javascript function before its definition inside a try block as thiscussed here function definitions can be used before they are defined but as soon as a section of code is wrapped in a try block this ceases to be the casethis thisplays hello worldhellofunction hello alerthello world but this thisplays referenceerror hello is not definedtry hello function hello alerthello world catch err alerterrso there is clearly something special about a try block with respect to function declarations is there any way to get around this behavior,['javascript'] +96566,mongodb and java driver ignore case in query this is the code i am using now how do i add the ignore case attributedbobject query new basicdbobjectprop valuethanks,['java'] +96568,canvas getimagedata does not work when running locally on windows security exception i am writing a local html5 app to process some scientific images i am on os x and i am specifically writing it in javascripthtml5 for portability so that i can demonstrate it to my supervisor on a windows machine this app will never be deployed on a serverthe problem is it works perfectly on safari on os x but on windows it throws up a security error both in firefox and chrome i think this is because it thinks the image is on a different domain but in reality it is in the same folder as the scriptis there any way i can get around thisthe error in question is the same as detailed hereedit i should clarify the answer on the question i linked running it on a local server is not feasible because i cannot go and install any software or servers on these machines the reason i am hoping for an alternative answer is because it does work on os x,['javascript'] +96591,how unique is uniqid this question is not really a problem looking for a solution it is more just a matter of simple curiosity the php uniqid function has a more entropy flag to make the output more unique this got me wondering just how likely is it for this function to produce the same result more than once when more entropy is true versus when it is not in other words how unique is uniqid when more entropy is enabled versus when it is thisabled are there any drawbacks to having more entropy enabled all the time,['php'] +96596,how do i stop gpslocation tracking when my activity finishes i have a very simple app for android that thisplays a google maps view and uses the gps to track the position essentially like so public void oncreatebundle savedinstancestate mlocationmanager locationmanager getsystemservicelocation service public void onresume superonresume mlocationmanagerrequestlocationupdatesmprovider 20 1 thispublic void onpause superonpause mlocationmanagerremoveupdatesthispublic void onlocationchangedlocation location mposition getgeopointforlocationlocation mmapcontrollersetcentermpositionand when i use the following command to exit the application eg through a menu the gps keeps on tracking it seems that the activity is still running case ridmenu exit finish how do i stop the gps tracking if it does not work by removing the location manager in onpause and calling finish as far as i have read tutorials or other questions this should be the solution,['android'] +96627,how to determine the size of permgen within a java application ie programmatically is there any way to measure the currently used size of permanent generation permgen within my java application i cannot use external profiling tools such as visualvm even better would be an estimation of the memory consumption of a java class in the permgen is it nearly proportional to the size of the bytecode file,['java'] +96633,tell gcc to specifically unroll a loop how can i tell gcc to unroll a particular loopi have used the cuda sdk where loops can be unrolled manually using pragma unroll is there a similar feature for gcc i googled a bit but could not find anything,['c'] +96646,how to change a widgets font style without knowing the widgets font familysize is there a way to change a tkinter widgets font style without knowing the widgets font family and font sizeuse case we create our ui using standard tkinter widgets label entry text etc while our application runs we may want to dynamically change the font style of these widgets to bold andor italics using the config method unfortunately there appears to be no way to specify a font spec without specifying the fonts family and sizethe following are examples of what wed like to do but neither of these examples workwidgetconfigfontboldorwidgetconfigfont none none bold,['python'] +96648,check if input is integer type in c the catch is that i cannot use atoi or any other function like that i am pretty sure were supposed to rely on mathematical operations int num scanfdnum if num is not integer printfenter integer return i have triednum22 numnum10ifscanfdnum1but none of these workedany ideas,['c'] +96650,how to change java version used by tomcat i have java 16 and tomcat 55 installed on my systembut tomcat 55 accesses java 15 and hence as the outcome i get the error bad version number in class file while executing java code with jsphow can i change the tomcat version to java 16updatei tried changing the jvm that the tomcat5wexe is pointing to the version 16 and now i am out of the bad version in class file error but now i get the following errorexceptionorgapachejasperjasperexceptionorgapachejasperservletjspservletwrapperhandlejspexceptionjspservletwrapperjava498orgapachejasperservletjspservletwrapperservicejspservletwrapperjava411orgapachejasperservletjspservletservicejspfilejspservletjava308orgapachejasperservletjspservletservicejspservletjava259javaxservlethttphttpservletservicehttpservletjava729root causejavalangnullpointerexceptionmyfirstsearchlinkcheckurlsearchlinkjava20orgapachejsptest jsp jspservicetest jspjava52orgapachejasperruntimehttpjspbaseservicehttpjspbasejava98javaxservlethttphttpservletservicehttpservletjava729orgapachejasperservletjspservletwrapperservicejspservletwrapperjava369orgapachejasperservletjspservletservicejspfilejspservletjava308orgapachejasperservletjspservletservicejspservletjava259javaxservlethttphttpservletservicehttpservletjava729what might be the root cause,['java'] +96654,how do i animaterotate a uiview 90 degress from its upper right corner i have been searching for hours trying to find a way to animaterotate a uiview 90 degrees from the upper right cornerthe effect should almost work like a swinging door from the top of the screenhope someone can help,['ios'] +96656,is there a way to programmatically convert vb6 formatting strings to net formatting strings does anyone know of a good reference for vb6 formatstringsdoes anyone know of a converter from vb6 formatting strings to net stringsi am working on porting a large vb6 code base to net it is a database centric piece of software and the database itself holds vb6 formatstrings which are later loaded and used to thisplay other data in the databasemy question like this article is how to port this however the answer chosen for that question is not adequate for my needs i am uncomfortable relying on libraries specifically designed for backwards compatibility with a language i have been specifically hired to port away,['c#'] +96662,how to access prototypes parent this from within methods function i have this classfunctionfunction menu thisclosetimer 0 thisdropdown 0menuprototypemenutimer function thisclosetimer settimeoutfunction thismenuclose thistimeoutmenuprototypemenuclose function ifthisdropdown thisdropdowncssvisibilityhiddeni want to call the function menuclose which is part of the menu class but i think this code actually trys to call menuclose from the closetimer objecthow do i reference menuclose from the menu object from within menutimer,['javascript'] +96680,using datediff to find duration in minutes i am trying to use datediff to find out the duration between columna and columnb select datediff minute stime etimefrom exceptions2where stime exceptions2starttimeand etime exceptions2endtimethis produces errors can anyone please help me with what i am doing wrong,['sql'] +96684,specifying multiple interfaces for a parameter i have an object that implements two interfaces the interfaces arepublic interface iobject string name get string class get ienumerableiobjectproperty properties get public interface itreenodet t parent get ienumerablet children get such thatpublic class objectnode iobject itreenodeiobject public string class get private set public string name get private set public ienumerableiobjectproperty properties get set public ienumerableiobject children get private set public iobject parent get private set now i have a function which needs one of its parameters to implement both of these interfaces how would i go about specifying that in c an example would bepublic typedobjectiobjectnodeiobject baseobject ienumerableitype types iobjectnodeiobject iobject parent construct hereor is the problem that my design is wrong and i should be implementing both those interfaces on one interface somehow,['c#'] +96688,python tkinter embed matplotlib in gui i am trying to embed a plot in my tkinter gui coded in python i believe the code below succeeds in simply putting a graph into a canvas but i do not have any control of the canvas location within the gui grid i want to be able to have a subsection of my gui be the plotnot the entirety of it how can i position this canvas widgetusrappspythonbinpythonimport matplotlib sysmatplotlibusetkaggfrom numpy import arange sin pifrom matplotlibbackendsbackend tkagg import figurecanvastkagg navigationtoolbar2tkaggfrom matplotlibfigure import figurefrom tkinter import master tkmastertitlehello worldf figurefigsize54 dpi100a fadd subplot1t arange00301s sin2pitaplottsdataplot figurecanvastkaggf mastermasterdataplotshowdataplotget tk widgetpacksidetop fillboth expand1mastermainloop,['python'] +96694,how can i prevent users from writing things inside of a combobox i would like my windows form combobox to only allow users to select from available options and not write things inis there a property somewhere i am missing thank you,['c#'] +96695,custom cursor outside of browser window i have a element on my website which is freely resizable this is done by 4 handles on the edges on hovering these handles and while resizing the element i want to show the respective resize arrowscurrently i implemented this behavior by setting the css cursor style of the bodyroot to these arrows the problem about it is the limit to the client area of the browser window it would be visually more consistent and less confusing if the arrow cursor would be visible everywhere while the mouse is hold downgoogle maps is doing the same thing with their hand cursor while moving the map so my question is how to achive this effect on my ownmy current relevant sourcefunction startobjectscalinge estoppropagation epreventdefault documentdocumentelementstylecursor thisstylecursor windowaddeventlistenermouseup stopobjectscaling falsefunction stopobjectscalinge estoppropagation documentdocumentelementstylecursor windowremoveeventlistenermouseup stopobjectscalingvar tg documentgetelementbyidtransformgadgetvar handle tgfirstchildnextsiblingforvar i0i4i handleaddeventlistenermousedown startobjectscaling false handle handlenextsibling,['javascript'] +96697,in a spring 30 get request whats the difference between a pathvariable and a requestparam in an example such as the following whats the difference between a pathvariable and a requestparamrequestmappingvalue portfolioportfolioidpath method requestmethodgetpublic final string portfoliohttpservletrequest request modelmap model pathvariable long portfolioidpath requestparam long portfolioidrequest,['java'] +96698,does there exist a method in c to get the relative path given two absolute path inputs does there exist a method in c to get the relative path given two absolute path inputsthat is i would have two inputs with the first folder as the base such asctemp1adamandctemp1jamiethen the output would be jamie,"['c#', '.net']" +96717,how to thisplay multiple google maps per page with api v3 i have the following script and i want to make both maps appear on the page but no matter what i try i can only get the first map initialize to thisplay the second one does not any suggestions also i cannot add it in the code but the first map is being thisplayed in div idmap canvasdivdiv idroutedivthanksscript typetextjavascript create a directions object and register a map and div to hold the resulting computed directionsvar mapvar directionspanelvar directionsfunction initialize map new gmapdocumentgetelementbyidmap canvas mapsetcenternew glatlng411255275736964801 15 directionspanel documentgetelementbyidroute directions new gdirectionsmap directionspanel directionsloadfrom armonk fire department armonk ny to php echo lastcallgoogleaddress mapaddcontrolnew gsmallmapcontrol mapaddcontrolnew gmaptypecontrolscript div idmap canvas2 stylewidth200px height200pxdivdiv idroute2divscript typetextjavascript create a directions object and register a map and div to hold the resulting computed directionsvar map2var directionspanel2var directions2function initialize2 map2 new gmapdocumentgetelementbyidmap canvas2 map2setcenternew glatlng411255275736964801 15 directionspanel2 documentgetelementbyidroute2 directions2 new gdirectionsmap2 directionspanel2 directions2loadfrom address1 to address2 map2addcontrolnew gsmallmapcontrol map2addcontrolnew gmaptypecontrolscript script typetextjavascriptfunction loadmaps initialize initialize2 script,['javascript'] +96723,adding lib to configautoload paths in rails 3 does not autoload my module i place a file name grb in side railsrootlib folderthe file content is like thismodule googleendthen i add configautoload paths wconfigrootlib railsrootappdelayed jobsto my railsrootconfigapplicationrbhowever when i try to invoke google from rails console an exception is thrown the exception goes away only if i execute require google why should not my file is autoloaded and should not i access the module without any extra require statement,['ruby-on-rails'] +96724,can i launch different activities on startup depending on user preferences i have a listactivity and a mapactivity i would like to launch either one of these activities on application startup that has been chosen by the user in a preferences windowso far the only way i see to launch an activity on application startup is to specify it in the application manifest file using activity androidnamemyactiivty androidlabelstringapp name intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activityi am thinking i might have to start an activity that does nothing but looks at the user preferences and then launches either the listactivity or mapactivity seems like a waste to have an activity do nothing but launch another activity in my research i have not found any solution to this problem any suggestions would be greatly appreciatedthanks regardsdave,['android'] +96732,application idle time in my application there are three activities a b c a i want to detect applications idle time so that after 15 mins it will pop up a message irrespective of activity what is the best method to implement this,['android'] +96733,what is getattr exactly and how do i use it i was reading about the getattr function the problem is that i still cannot grasp the idea of its usage the only thing i understand about getattr is that getattrli pop is the same as calling lipopi did not understand when the book mentioned how you use it to get a reference to a function without knowing its name until runtime maybe this is me being a noob in programming in general could anyone shed some light to the subject when and how do i use this exactly,['python'] +96738,finding first index of element that matches a condition using linq var item listwheret someconditioni would love to be able to find out the index of the element that was returned in fact in my case all i want is an index so that i can skip into the list by that muchis there a way to do this in an ienumerable i would hate to use a listt for this but that does have a findindex method,['c#'] +96742,dynamic height for div i have the following divdiv idproductsdivproducts height 102px width 84 padding5px marginbottom8px border 1px solid efefefnow inside the div i am dynamically generating 4 links but sometimes there could be more or less than 4 links how can i change the css to dynamically resize the div according to its contents,['css'] +96748,android application restarts on orientation change when i change orientation application restarts and i lost my current data i am using activity group which contain lots of activities when i change orientation application restarts from main activityis it possible to avoid this application restart on orientation changeanybody knows please let me know,['android'] +96752,can we use ruby on rails to develop a mobile app since rails uses mvc acrhitecture i was wondering that if we can use rails to develop a mobile app or any web app out of mvc the m and c would not change to develop the mobile app righti mean the models and controllers will remain the webserver only the view portion should be changed such that istead using htmlerb files i want java or android sdk or whatever to provide the ui for the mobile user can some enlighten me on this perspective also i have been hearing about jrbuy does it come into play for our mobile app development requirement,"['ruby-on-rails', 'ruby']" +96754,letting the code try different things until it succeeds neatly this is the second time i found myself writing this kind of code and decided that there must be a more readable way to accomplish thismy code tries to figure something out that is not exactly well defined or there are many ways to accomplish it i want my code to try out several ways to figure it out until it succeeds or it runs out of strategies but i have not found a way to make this neat and readablemy particular case i need to find a particular type of method from an interface it can be annotated for explicitness but it can also be the only suitable method around per its argumentsso my code currently reads like somethod candidatemethod getmethodbyannotationclazzif candidatemethod null candidatemethod getmethodbybeingonlymethodclazzif candidatemethod null candidatemethod getmethodbybeingonlysuitablemethodclazzif candidatemethod null throw new nosuitablemethodfoundexceptionclazzthere must be a better wayaedit the methods return a method if found null otherwise i could switch that to trycatch logic but that hardly makes it more readableedit2 unfortunately i can accept only one answer,['java'] +96756,sql listing all column names alphabetically i know thatselect from tablewill list all columns in the table but i am interested in listing the columns in alphabetical ordersay i have three columns name age and sexi want the columns organized in the formatage name sexis it possible to do this with sql,['sql'] +96778,getting value of select dropdown before change the thing i want to achieve is whenever the select dropdown is changed i want the value of the dropdown before change i am using 132 version of jquery and using on change event but the value i am getting over there is after changeselect nametestoption valuestackstackoptionoption valueoverflowoverflowoptionoption valuemymyoptionoption valuequestionquestionoptionselectlets say currently option my is selected now when i change it to stack in the onchange event ie when i changed it to stack i want it is previous value ie my expected in this casehow can this be achieved edit in my case i am having multiple select boxes in the same page and want same thing to be applied to all of them also all of my select are inserted after page load through ajax,"['javascript', 'jquery']" +96780,how to retrieve element value of xml using java i am new to xml i want to read the following xml on the basis of request name please help me on how to read the below xml in java xml version10 config request namevalidateemailrequest requestqueueemailrequestrequestqueue responsequeueemailresponseresponsequeue request request namecleanemail requestqueuecleanrequestrequestqueue responsequeuecleanresponseresponsequeue request config,['java'] +96785,template thisambiguator i am trying to find any information about template keyword used as thisambiguator but there is nothing about that probably i am searching wrong keywords but there is nothing like template or template in standard google shows only gcc problems from different forums but not really explanation what is it used forcode like that failed to compile without template keyword on line 11 on gcc but i am not quite sure that this conforms standardtemplatetypename bstruct s1 templatetypename t void test templatetypename tstruct s2 s2 s1ttemplate testint int main s2intso my question is why does template keyword used here what kind of ambiguity is there without that keyword and where can i read about that i would really appreciate link to standardthanks,['c++'] +96788,race condition in c signal handlers puzzle i need to know how to avoid a race condition when handling signals in c each time my program receives a signal i want it to alter a global linked list it is vitally important that i not miss a signal and equally important that the global linked list i am modifying not be changed while the handler is executingthe problem is if i receive a signal and start the handler but am then interrupted by another signal this as i understand it triggers a new execution of the signal handler which will operate on the same global dataset not permissiblei cannot use a lock because if the first handler call is interrupted it will naturally never free the lock for the interrupting handler to pick up so how do i do it any idea,['c'] +96802,cannot convert lambda expression to type string because it is not a delegate type the error is shown at select when i write next linq querydatatable dtbl int count from p in dtbl select precordidmaxplease help me out,"['c#', '.net']" +96810,how can i deserialize xml list using restsharp i have an xml like thisxml version10 encodingutf8 xml item accountid1accountid accounttypeid1accounttypeid accounttypename accountbankid1accountbankid accountbankname accountsaldo0accountsaldo item item accountid2accountid accounttypeid1accounttypeid accounttypename accountbankid2accountbankid accountbankname accountsaldo0accountsaldo item xml i want to deserialize this xml list to poco object which ispublic class account public string accountid get set public string accounttypeid get set public string accounttypename get set public string accountbankid get set public string accountbankname get set public string accountsaldo get set i found great product restsharp for working with rest client i want to use its deserializer and i tried 2 approaches1 i tried requestrootelement itemvar response executeaccountrequestand i only got first item element which is logical2 when i try something likerequestrootelement xmlvar response executelistaccountrequesti got nullwhere am i wrong with thisupdate the solution is in accepted answer comments,['c#'] +96835,what is the difference between borland gcc and mingw compilers i have been programming for a while at an intermediate level of course i have been executing the same code in these different compilers mostly gcc and mingw but i am unable to make out the difference between these compilers i mean by what way is the one better than the other or what makes them different are there some special needs where you might want to use gcc and for others maybe mingw,['c'] +96844,javascript communication between browser tabswindows whats the most reliable way to have javascript communicate between tabswindows of the same browser for example when tab 2 starts audio playback tab 1 somehow knows about this and can pause it is playeri am building a site with a music player so at the moment if you open two tabs to the site you could start music on boththis is obviously bad so i am trying to find a solution any ideasthanks,['javascript'] +96846,hyphen resources in rails 3 routes how is it possible to use hyphen in resources urlsfor example mymodel or mymodel1if i define route as resources mymodel i get syntax error because rails generates method def hash for mymodels urloptions nil,['ruby-on-rails'] +96861,why do we need strdup while i was working on an assignment i came to know that we should not use assignments such as char shello worldprograms using such syntaxes are prone towards crashingi tried and used int funchar temp do sum operation on temp print temp funhello worldeven the above worksthough the output is compiler and standard specificinstead we should try strdup or use const char i have tried reading other similar questions on the blog but could not get the concept that why the above code shouldnt workis memory allocated and what difference does const make,['c'] +96863,is there a point to minifying php i know you can minify php but i am wondering if there is any point php is an interpreted language so will run a little slower than a compiled language my question is would clients see a visible speed improvement in page loads and such if i were to minify my phpalso is there a way to compile php or something similar,['php'] +96876,hashmap in java 100 million entries i want to store 100 million terms and their frequencies in a text database into a hashmap string double it is giving me out of memory error i tried to increase the heapspace to xmx150m however it runs half an hour then again throw the same exception the file size from which i am trying to read the words and frequencies is 17gb any help would be much appreciatedthanks,['java'] +96893,how to import xml string in a php domdocument for exemple i create a domdocument like that phpimplementation new domimplementationdtd implementationcreatedocumenttype html qualifiedname w3cdtd xhtml 10 transitionalen publicid transitionaldtd systemid document implementationcreatedocument dtdelementhtml documentcreateelementhtmlelementhead documentcreateelementheadelementbody documentcreateelementbodyelementtitle documentcreateelementtitletexttitre documentcreatetextnodemy bweb pageattrlang documentcreateattributelangattrlangvalue endocumentappendchildelementhtmlelementhtmlappendchildelementheadelementhtmlappendchildattrlangelementheadappendchildelementtitleelementtitleappendchildtexttitreelementhtmlappendchildelementbodyso now if i have some xhtml string like that phpxhtml h1helloh1pworldphow can i import it in the body node of my domdocument for now the only solution i have found is something like that phpsimplexmlelement new simplexmlelementxhtmldomelement dom import simplexmlsimplexmlelementdomelement documentimportnodedomelement trueelementbodyappendchilddomelementthis solution seems very bad for me and create some problemes like when i try with a string like that phpxhtml phellonbspworldpok i can bypass this problem by converting xhtml entities in unicode entities but it is so uglyany help thanks by advance related question domdocumentvalidate problem solved,['php'] +96894,c finding the number of elements in an array in chow do you find the number of elements in an array of structs after sending it to a functionint mainvoid mystruct array struct1 struct2 struct3 struct4 struct5 struct6 printfdn sizeofarray printfdn sizeofarray0 farrayvoid fmystruct array printfdn sizeofarray printfdn sizeofarray0for some reason the printf in main shows different results than the printf in fmy need is to know how many elements are in the array,['c'] +96898,android webview performance in my app i am loading a list of external urls in webview and allow user to flip through them webviews are loaded on to a view flipper i find the performance is really bad in webview load url i have tried everything from using the frame layout to limiting the number of webviews to load still the performance is not satisfactoryhow do i optimize the performance of webview this should be a common usage am i missing something obviousmy webview settings are webviewsetinitialscalewebview scale webviewgetsettingssetjavascriptenabledtrue webviewgetsettingssetbuiltinzoomcontrolsfalse webviewsetwebviewclientnew mywebviewclient webviewsetontouchlistener new ontouchlistener,['android'] +96909,is there a good site for tracking your ranking on android market is there a good site for tracking what your apps ranking is per category on android market a long time ago androidstatscom seemed to work but its long history,['android'] +96936,declare multiple variables in javascript i want to declare multiple variables in a functionfunction foo var src arr new array var caption arr new array var fav arr new array var hidden arr new arrayis this the correct way to do thisvar src arr caption arr fav arr hidden arr new array,['javascript'] +96937,select first and last element with particular class using jquery i have a list of spans with particular class place and some of them have class activated is there a way to select the first item with class activated and the last span classplace onclickactivate1spanspan classplace onclickactivate2spanspan classplace activated onclickactivate3spanspan classplace activated onclickactivate4spanspan classplace activated onclickactivate5spanspan classplace activated onclickactivate6spanspan classplace onclickactivate7span,"['javascript', 'jquery', 'html']" +96943,control the mouse cursor using c i am trying to write a program using c that would allow me to remotely take control of the mouse on a windows machine this would allow me to issue commands to the mouse to move to a certain part of the screen and then click on that part of the screen i was wondering if there were any c classes that i would be useful in achieving this goal any help is appreciated thanks,['c#'] +96945,devisecucumber adding a step which confirm a user exists i am new to cucumber and i find following snippets to test the devise login feature however it seems one more step missing and i did not find any solutiongiven that a confirmed user exists do pending express the regexp above with the code you wish you hadendhere the following codefeaturesauthenticationsessionfeaturefeature session handling in order to use the site as a registered user i need to be able to login and logoutbackground given that a confirmed user existsscenario outline logging in given i am on the login page when i fill in user email with email and i fill in user password with password and i press sign in then i should action examples email password action test1234 see signed in successfully password see invalid email or password scenario logging out given i am logged in when i go to the sign out link then i should see signed out successfullyfeaturesstep definitionsauthentication stepsrb sessiongiven i am logged in do visit path tothe login page fill inuser email with useremail fill inuser password with userpassword click buttonsign in if definedspecrailsmatchers pageshould have contentsigned in successfully else assert pagehas contentsigned in successfully endendspecfactoriesuserrbfactorydefine minimal user class user do u uusername minimal uemail upassword test1234 upassword confirmation test1234endhere the link to the orginal codemany thanks for your help,['ruby-on-rails'] +96969,javascript closure vs global variable which is best practice which results in better performanceupdate jsperfcom reports that a is faster a using a closurevar obj init function var self this elementclickfunction selfclickevent clickevent function thismiscmethod miscmethod function b using the global variablevar obj init function removed selfthis closure elementclickthisclickevent simple method handler clickevent function objmiscmethod global variable used miscmethod function,['javascript'] +96979,multiple reactors main loops in one application through threading or alternative means i have got an idea for an app i would like to work on to learn a bit more about twisted and websockets i was thinking of integrating a previously written irc bot into a web application as far as i can see it i would need three reactors to make it workprimary reactor web server http this would be your average twistedweb application when you access it you can post an irc serverchannel to connection the web server would then talk to a different reactor in a different thread which issecondary reactor irc bot this would be an irc bot running via the twisted irc client protocol it would join a channel and whenever something was said it would take that data and push it to yet another reactor on yet another thread which istertiary reactor websocket server ws since websockets do not use the regular http protocol they need their own server or so it seems looking at examples such as this when the irc bot receives a message it tells the websocket server to push that message to connected clientsin my mind this makes sense it seems like it would be possible does anyone have any examples of multiple reactors running in separate threads or is this something i have imagined that cannot be done in the current incarnation of twistedare there any architecture changes that can or should be made to minimize the reactor count etcthanks for any help,['python'] +96985,is permgen included in xmx when i say xmx1024m does this include permgen ie xxmaxpermsize is taken from these 1024m or it is separatelooking at thisi thought that it takes from 1024m but until now i had believed they were separate,['java'] +96995,how should i fire javascript blur event after click event that causes the blur i have run into this problem a few times and i am not happy with the solutions i have used beforei have an input box with a blur event that validates the content of it and a button which will fill the input box on click the problem is clicking the button fires the input blur event and then the button click event so content inserted by the button is not what is validatedsee i know this is the correct behavior but i cannot think of a clean way to get around the problem,"['javascript', 'jquery']" +97001,what are some useful examples of malloc in c i am just reading about malloc in cthe wikipedia article provides an example however it justs allocate enough memory for an array of 10 ints in comparison with int array10 not very usefulwhen would you decided to use malloc over c handling the memory for you,['c'] +97008,ways to create a unique user fingerprint in php what is the best way to generate a fingerprint of user uniqueness in phpfor examplei could use a users ip addressas the fingerprint however therecould be multiple other users on the same ipi coulduse the users ip user agent asthe fingerprint however a single usercould simply swap from safari tofirefox and again be seen as being uniqueideally the fingerprint so label the machine rather than browser or ip but i cannot think of how this is achievableopen to ideassuggestions of how you uniquely identify your users and what advantagesthisadvantages your method has,['php'] +97009,force order of messages with hornetq i have setup a jms server with hornetq as a jms provider queuei have an application which acts as a producer and another one different computer as a consumeri understand that the jms specification does not guarantee the order of delivery but i am looking for a way to do just that receive the messages exactly in the order they have been sent even if it is provider specificany ideas,['java'] +97014,how to enable paging and sorting on aspnet 40 gridview programmatically i am using aspnet 40 with c visual web developer 2010 expressi have successfully managed to implement a simple gridview bound to a stored procedure data source using declarative aspnet code as shown hereaspgridview idgrdtrades runatserver datakeynamestradeid enablepersistedselectiontrue selectedrowstylebackcoloryellow allowpagingtrue allowsortingtrue pagesize 20 autogeneratecolumnsfalse datasourceidsdstrades columns aspcommandfield showselectbuttontrue buttontypelink selecttextselect aspboundfield datafieldtradeid headertexttradeid readonlytrue sortexpressiontradeid more columns columnsaspgridviewaspsqldatasource idsdstrades runatserver connectionstring connectionstringstradesdb providername connectionstringstradesprovidername selectcommandusp gettrades selectcommandtypestoredprocedure aspsqldatasourceit works great including paging and sorting i want to remove the sqldatasource and use codebehind i am trying to put database access code in one place so far i have this in my codebehindprotected void page loadobject sender eventargs e if thisispostback grdtradesselectedindex 0 dbutil db new dbutil grdtradesdatasource dbgettrades grdtradesdatakeynames new string tradeid grdtradesdatabind this is needed otherwise i get the gridview grdtrades fired event pageindexchanging which was not handledvoid grdtrades pageindexchangingobject sender gridviewpageeventargs e grdtradespageindex enewpageindex grdtradesdatabind my declarative code now looks likeaspgridview idgrdtrades runatserver enablepersistedselectiontrue selectedrowstylebackcoloryellow allowpagingtrue allowsortingtrue pagesize 20 autogeneratecolumnsfalse onpageindexchanginggrdtrades pageindexchanging columns aspcommandfield showselectbuttontrue buttontypelink selecttextselect aspboundfield datafieldtradeid headertexttradeid readonlytrue sortexpressiontradeid more columns columnsaspgridviewthe problem is when i click on a page number the page becomes blank i would also like to implement sorting but would like to get the paging working first please helpthanks,"['c#', 'asp.net']" +97052,iphone notifications max number of notifications i have an iphone app sending notifications and everything is working fine except sometimes let me explain i am using a pretty simple php script to send the notifications using the stream context create method but some users told me they do not receive some notifications apparently i may encounter some cases where i need to send up to 50 notifications within a minute and i think this might be the problem i am using one single stream to send all the notificationsdid any of you guys encountered such an issue do i need to split in several streams is there any info about the max number of notifications i may send in a streamthanks edit 1 speed is not the issue here i am able to push all my notifications to apple within a minute i may have some issues in the future if my number of users growns but it is ok atm the problem i see here is that apple may consider me a spammer or something and does not deliver all my 50 notifications do you guys have any idea how i can get sure about that,['iphone'] +97059,jquerys fadein slow is too fast i am using the jquery fadein fadeout with the slow option but it is still a little too fast for menow i have read that you can only choose between fast and slow but is there a way to make it slower,['jquery'] +97063,move constructor on derived object when you have a derived object with a move constructor and the base object also has move semantics what is the proper way to call the base object move constructor from the derived object move constructori tried the most obvious thing first derivedderived rval baserval however this seems to end up calling the base objects copy constructor then i tried explicitly using stdmove here like this derivedderived rval basestdmoverval this worked but i am confused why it is necessary i thought stdmove merely returns an rvalue reference but since in this example rval is already an rvalue reference the call to stdmove should be superfluous but if i do not use stdmove here it just calls the copy constructor so why is the call to stdmove necessary,['c++'] +97082,aspnet mvc issue with configuration of forms authentication section i have an aspnet mvc 3 beta application running on iis in my webconfig i defined following section responsible for forms authenticationauthentication modeforms forms loginurlaccountlogon namevnk protectionall timeout43200 cookielessusecookies authenticationthe defined login address is accountlogonwhen i try to get the login url usingformsauthenticationinitializestring loginurl formsauthenticationloginurl i receive vnksiteaccountloginwhy do i get a different address from the one defined in webconfigupdate the vnksite prefix is not a problem here the problem is that loginurl property of formsauthentication class does not reflect the value from webconfig it means that if i change the value of loginurl attribute in webconfig from accountlogon to eg foobar formsauthenticationloginurl still has value of vnksiteaccountlogin why,['asp.net'] +97092,c mfc how to draw alpha transparent rectangle in a c mfc application using the dc of cpaintdc dcthis how do i draw a rectangle lprect with an alpha transparency that i can adjustfollowing is an example c code which i need to convert into cprivate void picturebox1 paintobject sender painteventargs e graphics g egraphics color color colorfromargb75colorred sets color red with 75 alpha transparency rectangle rectangle new rectangle100100400400 gfillrectanglenew solidbrushcolor rectangle draws the rectangle with the color set,['c++'] +97093,like button in ios application does anybody know how to place facebook like button into ios application i have tried the method described in this blog post but i do not really like this method because its ugly login dialog and what is more important it makes user login twice for example user wants post a message to his wall if he is not logged in i call standard fblogindialog after that user posted a message he may want push like button and he have to login again it is really bad user experiencehow to be how can i give user like feature in my ios app,['ios'] +97100,get boolean from database using android and sqlite how can i obtain the value of a boolean field in an sqlite database on androidi usually use getstring getint etc to get the values of my fields but there does not seem to be a getboolean method,"['java', 'android']" +97131,using realloc in c stdrealloc is dangerous in c if the mallocd memory contains nonpod types it seems the only problem is that stdrealloc wont call the type destructors if it cannot grow the memory in situa trivial work around would be a try realloc function instead of mallocing new memory if it cannot be grown in situ it would simply return false in which case new memory could be allocated the objects copied or moved to the new memory and finally the old memory freedthis seems supremely useful stdvector could make great use of this possibly avoiding all copiesreallocationspreemptive flame retardant technically that is same bigo performance but if vector growth is a bottle neck in your application a x2 speed up is nice even if the bigo remains unchangedbut i cannot find any c api that works like a try reallocam i missing something is try realloc not as useful as i imagine is there some hidden bug that makes try realloc unusablebetter yet is there some less documented api that performs like try reallocnote i am obviously in libraryplatform specific code here i am not worried as try realloc is inherently an optimizationupdatefollowing steve jessops comments on whether vector would be more efficient using realloc i wrote up a proof of concept to test the reallocvector simulates a vectors growth pattern but has the option to realloc instead i ran the program up to a million elements in the vectorfor comparison a vector must allocate 19 times while growing to a million elementsthe results if the reallocvector is the only thing using the heap the results are awesome 34 allocation while growing to the size of million bytesif the reallocvector is used alongside a vector that grows at 66 the speed of the reallocvector the results are less promising allocating 810 times during growthfinally if the reallocvector is used alongside a vector that grows at the same rate the reallocvector allocates 1718 times barely saving one allocation over the standard vector behaviori do not doubt that a hacker could game allocation sizes to improve the savings but i agree with steve that the tremendous effort to write and maintain such an allocator is not work the gain,"['c++', 'c']" +97152,whats better many small tables or one big table i have got a database which will store profiles about individuals these individuals have about 50 possible fields some are common things like first name last name email phone numberothers are things like hobbies skills interestssome are height weight skin coloreach of these groups are used by the system at different times in terms of being able to negotiate through the database i would prefer to have 7 tables each of about 8 fields what is best practice to doedit the data is going to be used in a search engine for finding profile matches does this affect what i am doing,['mysql'] +97156,what is the way data is stored in npy i am saving numpy arrays using numpysave functioni want other developers to have capability to read data from those file using c languageso i need to knowhow numpy organizes binary data in fileok it is obvious when i am saving array of i4 but what about array of arrays that contains some structurescannot find any info in documentationupd lets say tha data is something like dt npdtypeouter3i4outer2inner10i4inner2f8upd2 what about saving dynamic data dtype objectimport numpy as npa 0b 00c abdtype npdtypename s2 objvalue objectdata npzeros3 dtypedata0objvalue adata1objvalue bdata2objvalue cdata0name adata1name bdata2name cnpsaverdinnpy datais it real to read that thing from c,['python'] +97169,influence mathrandom i am looking for a way to influence mathrandomi have this function to generate a number from min to maxvar rand functionmin max return mathfloormathrandom max min 1 minis there a way to make it more likely to get a low and high number than a number in the middlefor example rand0 10 would return more of 01910 than the rest,['javascript'] +97171,nsurlrequest would not fire while uiscrollview is scrolling i have a problem in that i am trying to background load a sound file while the user moves around a uiscrollview the problem is that i am using nsurlrequest so i can load in the background but even then it refuses to actually load until the uiscrollview has stopped scrolling is there anything i can do about thisthanks,"['objective-c', 'ios']" +97189,make the divider of an nssplitview undraggable and do not show the dragging cursor i have an nssplitview no uisplitviewcontroller with three subviews now for the last divider index 1 i want the divider to not show the dragging cursor two arrows pointing out of eachother i have this to stop the dragging but the cursor is still showing up cgfloatsplitviewnssplitview splitview constrainsplitpositioncgfloatproposedposition ofsubviewatnsintegerdividerindex if dividerindex 1 return splitview framesizewidth 161 note that i only want to hide the cursor for the divider at index 1 can anyone help me thanks no i do not want to use bwtoolkit,['objective-c'] +97191,splitting a list of dictionaries into several lists of dictionaries i have been whacking away at this for a while to no avail any help would be greatly appreciatedi haveevent 0 voltage 1 time 0event 0 voltage 2 time 1event 1 voltage 1 time 2event 1 voltage 2 time 3event 2 voltage 1 time 4event 2 voltage 2 time 5and i want to split that list of dictionaries up per event like this there can be arbitrarily many eventslist0 event 0 voltage 1 time 0event 0 voltage 2 time 1list1 event 1 voltage 1 time 2event 1 voltage 2 time 3list2 event 2 voltage 1 time 4event 2 voltage 2 time 5listn,['python'] +97230,get referrer after installing app from android market i am trying to register a broadcast receiver that catches comandroidvendinginstall referrer intents launched by android after an app is installed from the marketi am following the details here however i cannot use google analytics so i have created my own solution i have added the following to my manifest filereceiver androidnamecomtestreceiver androidexportedtrueintentfilter action androidnamecomandroidvendinginstall referrer intentfilterreceiverand created a basic broadcastreceiver classpublic class receiver extends broadcastreceiver override public void onreceivecontext context intent intent bundle extras intentgetextras string referrerstring extrasgetstringreferrer logwtest referrer is referrerstring however when the app is installed the receiver does not seem to catch the intent if the intent is even broadcast and i get no logging outputam i going wrong somewhere or is the market no longer launching these intents when an app is installed,['android'] +97264,indentation and new line command for xmlwriter in c i am writing some data to xml filebut when i open it all the values are in a single linehow can write it in readable formatie each node in new line and indentationfilestream fs new filestreammyfilexml filemodecreatexmlwriter w xmlwritercreatefswwritestartdocumentwwritestartelementmyfile wwriteelementstringid idtextwwriteelementstringdate datetimepicker1textwwriteelementstringversion vertextwwriteendelementwwriteenddocumentwflushfsclose,['c#'] +97271,good beginners tutorial to socketio i am very new to the world of webdevelopment and jumped into the bandwagon because i find the concept of html5 very interesting i am fairly confident on working with canvas and would now like to move over to websockets part of it i have come to understand socketio is by far the framework to work with when we want to work with web socketsany pointers on what tutorial and examples to refer to for a total dummy would be very appreciated,['javascript'] +97287,c create simple xml file how can i create a simple xml file and store it in my system,['c#'] +97303,f html parsing what other options currently exist for parsing html in f currently have some regular expressions but would prefer something like pythons beautiful soup or be able to using an api similar to jquery from fi have seen the fslex and fparsec but i am not sure if someone else has already built some html parsing library with these or i would have to write my own,['html'] +97319,running unique tasks with celery i use celery to update rss feeds in my news aggregation site i use one task for each feed and things seem to work nicelythere is a detail that i am not sure to handle well though all feeds are updated once every minute with a periodic task but what if a feed is still updating from the last periodic task when a new one is started for example if the feed is really slow or offline and the task is held in a retry loopcurrently i store tasks results and check their status like thisimport socketfrom datetime import timedeltafrom celerydecorators import task periodic taskfrom aggregatormodels import feed results periodic taskrun everytimedeltaminutes1def fetch articles for feed in feedobjectsall if feedpk in results if not resultsfeedpkready the task is not finished yet continue resultsfeedpk update feeddelayfeedtaskdef update feedfeed try feedfetch articles except socketerror exc update feedretryargsfeed excexcmaybe there is a more sophisticatedrobust way of achieving the same result using some celery mechanism that i missed,['python'] +97323,exclude when parent has class trying to exclude a set of elements from the matched set when it is parent object has a cetain classcurrent solution ispages li anotthisparenthasclassnoscriptbut this is not behaving as i would expect what am i doing wrong,['jquery'] +97324,button with no postback well i have a aspnet page where i have a button that im using to execute a javascript but after the javascript has run the page reloadspostback how can i avoid thatbutton onclickprintelementcontentprintbutton,"['javascript', 'asp.net', 'html']" +97326,why does stdstring not provide a conversion to const char this is more of a policy or a historical question why was it decided not to provide a const char conversion for stdstring were there a fear someone might do printfs s and believe it would automatically convert are there any open thiscussions on this issue,['c++'] +97331,table border color in css with border collapse i want to put a line above some field in a table to indicate that it is a sum of the above values however the table already has borders by defaulthere is an example i have a table with borders collapsed i set the borderbottom on one field and the bordertop on the field below it both of these specify the same border the css for the top one is used is there a way to use the bottom onehtml head style typetextcss table bordercollapse collapse tdfirst borderbottom solid red 1px tdsecond bordertop solid gold 1px style body table trtd classfirsthellotdtr trtd clasecondworldtdtr table bodyhtmlthis shows two cells with a red line between them is there way to get a gold line,['css'] +97336,itextsharp pdfpcellverticalalignment and pdfpcellhorizontalalignment im trying to figure out how to get my text inside a pdfpcell to show in the middle i have tried many different options likemycellverticalalignment elementalign middlemycellverticalalignment pdfpcellalign middlemycellverticalalignment rectanglealign middlenone of that works for me verticalalignment takes an int so i tried to make a loop to see if i could find the right number but everything just get left bottom align document mydocument new documentpagesizea4 pdfwriter mypdfwriter pdfwritergetinstancemydocument new filestreamstrpdffilepath filemodecreate mydocumentopen mydocumentnewpage pdfcontentbyte mypdfcontentbyte mypdfwriterdirectcontent pdfpcell mycell paragraph myparagraph pdfptable mytable new pdfptable4 mytablewidthpercentage 100 mytablesetwidthsnew int4 25 25 25 25 mytabledefaultcellborderwidth 1 mytabledefaultcellbordercolor basecolorred for int i 100 i 100 i myparagraph new paragraphstringformatalignment 0 i myparagraphfontsetfamilyverdana myparagraphfontsetcolor72 72 72 myparagraphfontsize 11 mycell new pdfpcell mycelladdelementmyparagraph mycellhorizontalalignment i mycellverticalalignment i mytableaddcellmycell mydocumentaddmytable mydocumentaddnew chunkstringempty mydocumentclose,['c#'] +97349,using a class name in jquerys closest i am attempting to do some calculations for a running total this is my code quantity inputlivechangefunction var valone parsefloatthisval var valtwo parsefloatpricetext var totaltotal valone valtwo cost of itemsclosestcost of itemstexttotaltotaltofixed2 calctotal quantity input is an input price is the price of the product cost of items is where i want to update the total cost for the item ie item1 a5 x 3 quantity a15 total for item1calctotal is a function that just updates a total cost for the order the problem is keeping all the math in one row of the table ie i am doing the calc in the code above and its not sticking to its row its updating all the fields with class cost of items etcthe problem with showing my html is that its dynamically added by jquery appends but here is the relevant jqueryitemsappendtr classtablerowtda classremoveitem hrefimg srcadminimagesdeletepngimgatd classom part no ompartno tdtd suppartno tdtd cat tdtd classdescription desc tdtd manuf tdtd list tdtd thisc tdtdp classadd editaddeditpinput typetext classquantity input namequantity input tdtd classprice each nett price priceeach tdtd classcost of itemstdtdp classadd editaddeditpinput typetext classproject ref input nameproject ref input p classproject refptdtreditworking solutionquantity inputlivechangefunction var valone parsefloatthisval var valtwo parsefloatthisclosesttrfindpricetext var totaltotal valone valtwo thisclosesttrfindcost of itemstexttotaltotaltofixed2 calctotal,['jquery'] +97352,how do i thisable a system device programatically i am looking for way to thisable a system device in cnet given either the pid vid or the device nameafter searching i found this project herebut i need something that will work on xp vista windows 7 both x86 and x64 operating systemsthe project i linked only works with xp and vista x86even when running the application with administrator privilegesdoes anyone know of a solutionlibrary that would work on all operating systemsthanks,"['c#', '.net']" +97357,why i got advice has not been applied warning why does the following code pointcut callstolist call list beforelist l callstolist targetl systemoutprintlncool generates the following warningadvice defined in orgeclipseajdtexampleslistadvice has not been applied xlintadvicedidnotmatchi am working with in eclipse i installed eclipse aspectj plugin and of course my project is an aspectj projectedit moreover i started from a working example provided by ajdt plugin pointcut callstobegintask callvoid iprogressmonitorbegintask before callstobegintask systemoutprintlncooli cannot see any difference except the fact that this example works without warning,['java'] +97361,sql delete based on condition in join it is possible to delete records based on a satisfied condition with a join queryfor instance i have a linking table joining 3 records the query i have at the moment deletes records from this table where one of the ids is not in an imploded php array i have come to realise that the query should only remove records from this table if the ids do not exist in the array and they belong to a certain other table based on the a link to another table,['sql'] +97402,oracle sql return true if exists question how do i check if a particular element exists in a table how can i return true or falsei have a table that has user iduser passworduser secretqverbally i want to do this if a particular user id exists in the user id column then return true otherwise return false,['sql'] +97468,passing a java class into a void parameter with jna i have a function in c which i am trying to call from java with jnaint mycfuncvoid s int lsaccording to the jna documentation the void requires a comsunjnapointer be passed to the function in java with jna i believe the above function will be wrapped as followspublic interface mywrapper extends library public int mycfuncpointer s intbyreference lsthe objects which need to linked to the pointer and passed in parameter s will be classes which implement jna structure such aspublic class myclass extends structure public int x public int y public int zunfortunately the parameter ls is an integer representing the length of the class in bytes java does not have a sizeof function so this adds an extra bit of complexitythe other major problem i am having is ensuring i am correctly passing the contents of the object to native memory and backmy code is similar to the followingimport comsunjnanativeimport comsunjnapointerimport comsunjnastructureimport comsunjnaptrintbyreferencepublic void foo mywrapper wrapper mywrapper nativeloadlibrarysomedllwithlegacycode mywrapperclass myclass myobj new myclass myobjx 1 myobjy 2 pointer mypointer myobjgetpointer int size nativegetnativesizemyclassclass intbyreference len new intbyreferencesize myobjwrite is this required to write the values in myobj into the native memory wrappermycfuncmypointer len myobjread does this read in the native memory and push the values into myobj mypointerclearsize is this required to clear the memory and release the pointer to the gci am getting an error that the data passed is of a larger size than is expected by the c functionthe above code roughly following the same sort of steps as provided out in this answer to a question dealing with a similar issue but in c i have tried and tested that it works in cmy question is similar to another on stackoverflow but that deals with a pointer to an intbyreference rather than a pointer to a class,['java'] +97475,rails 3 devise how to skip the current password when editing a registration i have implemented omniauth with my devise model so i can authenticate using other servicespassword is not necessary anymore for my model as users can authenticate using twitter facebookeverything is working fine but when an user try to edit its registration devise skip the process because the user did not inform the current password which doesnt exist in some cases nowi created a registration controller to overwrite the devises oneclass registrationscontroller deviseregistrationscontroller def update super endendbut i have not find any documentation about how to skip the password verification how could i do it in my update action,['ruby-on-rails'] +97477,avurlasset refuses to load video i am trying to load a video file into my ipad app as an avurlasset using the asynchronousloading stuff to wait for it to be ready problem is when i run it i get a completely generic failure error message that i have no idea what to do with the video works if i hand it to an mpmovieplayercontroller but avurlasset seems to refuse to have anything to do with itcodeasset avurlasset alloc initwithurlnsurl urlwithstringdocpath stringbyappendingpathcomponentvideomov optionsnilasset loadvaluesasynchronouslyforkeysnsarray arraywithobjecttracks completionhandler thispatch asyncthispatch get main queue self composeifready voidcomposeifready nserror error nil ifasset statusofvalueforkeytracks errorerror avkeyvaluestatusfailed nslogerror loading error description iferror nil nslogokay awesomethe outputerror loading error domainavfoundationerrordomain code11800 the operation couldnat be completed avfoundationerrordomain error 11800 userinfo0x1696f0 nsunderlyingerror0x169a40 the operation couldnat be completed osstatus error 1293611800 by the way is the error code for unknown error kind of a dead end any ideas is there something i should be setting up before i try to load the asset,['ios'] +97479,jquerysending password via ajax i have registration boxand i want users to register via ajaxis it safe to send password via jquery ajaxif notcan someone explain what to do to secure password dataany example,['jquery'] +97482,how can i lower the weak ref processing time during gc currently i am facing the problem that my application is showing long gc times sporadically but all these are only caused by weak reference processing so the thread stopped time is always close to the weak ref processing time all other gc cycles are 01 sec to 0200 secfrom the gclog reformatted10388186 gcyg occupancy 206547 k 306688 k10388186 rescan parallel 01095860 secs10388295 weak refs processing 20799570 secs 1 cmsremark 2973838k3853568k 3180386k4160256k 21899230 secs times user251 sys0 real218 secstotal time for which application threads were stopped 21906890 secondscurrently i have these settings in place tried simpler settings but no changexms4gxmx4gxxnewsize128mxxuseconcmarksweepgcxxcmsincrementalmodexxmaxgcpausemillis50xxcmsinitiatingoccupancyfraction50xxparallelgcthreads16xxthisableexplicitgcif i turn up newsize i end up with long normal gc cycles the machine has 8 cores and does not burn that much cpu for the application tried to get to run the old gen gc early and concurrentlyand yes i cannot get rid off the weak ref usage because this is part of a 3rd party library,['java'] +97488,load content of a div on another page you will see from this code that it loads the content url from the hash tag is there anyway to load only a single div element from that external pagefunction iflocationhash content inloadloadlocationhashsubstring1 nav aclickfunction content inloadloadthishashsubstring1 so something like after substringinload content1but that does not workthanks,"['jquery', 'html']" +97497,calculating extremely large powers of 2 i have made a program in java that calculates powers of two but it seems very inefficient for smaller powers 240 say it does it in less than a second however i am looking at calculating 243112609 which is one greater than the largest known prime number with over 12 million digits it will take a very long time to run heres my code so farimport javaiopublic class power private static byte x 2 private static int y 43112609 private static byte a x private static byte b 1 private static byte product private static int size 2 private static int prev 1 private static int count 0 private static int delay 0 public static void mainstring args throws ioexception file f new filenumbertxt fileoutputstream output new fileoutputstreamf for int z 0 z y z product new bytesize for int i 0 i alength i for int j 0 j blength j productij byte ai bj checkplacevaluei j b product for int i productlength 1 i productlength 2 i if producti 0 size if delay 500 delay 0 systemoutprint delay string str for int i productproductlength1 0 productlength 2 productlength 1 i 0 i systemoutprintproducti str producti outputwritestrgetbytes outputflush outputclose systemoutprintln public static void checkplacevalueint placevalue if productplacevalue 9 byte remainder byte productplacevalue 10 productplacevalue 10 remainder productplacevalue 1 remainder checkplacevalueplacevalue 1 this is not for a school project or anything just for the fun of it any help as to how to make this more efficient would be appreciated thankskyleps i failed to mention that the output should be in base10 not binary,['java'] +97504,c how to encrypt strings at compile time i want to hide some strings in my exe so people cannot simply just open the exe and look at all the strings there i do not care about the strength of the encrypting method so i will probably use xor etchow can i do this at compile time that way my strings would not be stored in the exe but the encrypted versions would then i would just use my decrypting function every time to thisplay those strings on screen,['c++'] +97508,how to maintain seo while using jquery to show hidden divs im working with jquery ui on many of my websites and i am concerned that any content that is in hidden divs that will be used for a dialog is not search engine friendly and i would like to find out ifis content in hidden divs searchedindexed by googlewhat is the best practice for using jquery ui dialogstabs or other hidden elements on a webpage to ensure the best results for seo,['jquery'] +97509,how to perform a insertupdate with core data i have got the basics of inserting records and deleting records with core data however i would appreciate help with one of the most common functions the insertupdatebasically i use nsmutablearray arraywithcontentsofurl to get an array that contains rows from a mysql table what i need to do is now sync up my coredata storein other words i need to add every row in the array to my coredata table but if it already exists i need to update the record with the latest values also if it exists in core data and not in the downloaded array i would need to delete iti probably could hack this together however i would like to see how its properly and efficiently done without memory leaks,"['ios', 'objective-c', 'iphone']" +97511,mysql how to sum a timediff on a group so i have got a set of results that looks something like thisselect user id starttime endtime timediffendtime starttime as timedifrom mytable user id starttime endtime timediff 1 20101105 080 20101105 090 010 1 20101105 090 20101105 10 010 2 20101105 0630 20101105 070 0030 2 20101105 070 20101105 090 020 2 20101105 090 20101105 10 010 now i need to group the results by user id and sum timediff if i add a group by clause it does not sum the timediff and i wouldnt expect it to how can i sum the timediffs for each user,"['sql', 'mysql']" +97532,why implement interface explicitly so what exactly is a good use case for implementing an interface explicitly is it only so that people using the class do not have to look at all those methodsproperties in intellisense,['c#'] +97537,what is the difference between pickle and shelve i am learning about object serialization for the first time i tried reading and googling for differences in the modules pickle and shelve but i am not sure i understand it when to use which one pickle can turn every python object into stream of bytes which can be persisted into a file then why do we need the module shelve is not pickle faster,['python'] +97538,really php argument 1 passed to my function must be an instance of string string given function phpwtfstring s echo snphpwtftype hinting is da bombcatchable fatal error argument 1 passed to phpwtf must be an instance of string string givenit is more than a little orwellian to see php recognize and reject the desired type in the same breath there are five lights damn itwhat is the equivalent of type hinting for strings in phpbonus consideration to the answer that explains exactly what is going on heresummarythe error message is confusing for one big reasonprimitive type names are not reserved in phpthe following are all valid class declarationsclass string class int class float class double my mistake was in thinking that the error message was referring solely to the string primitive type the word instance should have given me pause an example to illustrate furtherclass string n 1234s1 stringns2 new stringa arrayno yesprintfs1 primitive string s string instance sn ais strings1 ais as1 stringprintfs2 primitive string s string instance sn ais strings2 ais as2 stringoutputs1 primitive string yes string instance nos2 primitive string no string instance yesin php it is possible for a string to be a string except when it is actually a string as with any language that uses implicit type conversion context is everything,['php'] +97581,why do c textboxappendtext newlines thissapear when using and as line terminator i am using a multiline textbox and i am getting behavior i cannot fully explain i use textboxappendtextline n to append a new line to a textbox when using this 3 times i getline line linethisplayed in the textbox now i resize the textbox the text becomesline line line that is the newlines thissapear i know i should be using textboxappendtextline environmentnewlineso i know how to solve the problem i would like to know why when using n the newlines initially appear but thissapear when resizing,['c#'] +97586,convert systemdrawingcolor to systemwindowsmediacolor systemdrawingcolor drawredcolor systemdrawingcolorredsystemwindowsmediacolor mediacolor drawredcolortomediacolor,['.net'] +97587,image tag inside link to undefined method symbolize keys for authfacebookstring i think i am missing a little something here the it is a simple image inside a link the code link to image tag facebookpng authfacebook the error is undefined method symbolize keys for authfacebookstringwhatd i do wrong here,['ruby-on-rails'] +97603,c using ithisposable to clean up temp files i have a fileuploader class that can optionally be given a zip file which it extracts to a temporary location and returns the file pathsfrom what i understood implementing the ithisposable interface on the fileuploader class and using the thispose method to remove all temp files would make the class clean itself up as soon as its reference fell out of contextthis doesnt seem to be the case though can anyone explain how i might go about what im trying to achieveupdateto clarify my code is public actionresult importfile fileuploader uploader new fileuploadercontrollercontext file where file is the posted forms file element uploadersaveorextractfilestotemplocation foreach string file in uploaderfiles try do some stuff catch exception err let the user know return view im trying to get the fileuploader to delete all temp files after the importfile method has completed,['c#'] +97604,update requires a valid insertcommand when passed datarow collection with new rows i am trying to add a new row to my database here is my code ds1 is my dataset da1 is my data adapter drow ds1tableslocalitatinewrow drow1 aux1replace replace tolower drow2 aux2tolowerreplace drow3 aux1 drow4 ex drow5 ey ds1tableslocalitatirowsadrow da1updateds1 localitatiat the da1updateds1localitati the program stops and gives me the error update requires a valid insertcommand when passed datarow collection with new rowsthe connection to the database works i have retrieved info from the db any ideas,['c#'] +97635,embed ms access database in c winform app i have a c winform application that accesses data from an ms access database this means my applications requires at least 2 files the exe file and the accdb file is it possible to include the database in the exe file so my solution consists of a single file the same way you would include an image in the project resources if it is possible are they any major reasons why it should not be done and how would you access the data from code the project is a only a little one for personal use so if performance is hit it does not matter too muchthanks in advance,['c#'] +97670,get synchronizationcontext from a given thread i seem not to find how to get the synchronizationcontext of a given threadthread uithread uiconfigurationuithreadsynchronizationcontext context uithreadhuhwhy should i need thatbecause i need to post to the uithread from different spots all across the front end application so i defined a static property in a class called uiconfiguration i set this property in the programmain methoduiconfigurationuithread threadcurrentthreadin that very moment i can be sure i have the right thread however i cannot set a static property likeuiconfigurationsynchronizationcontext synchronizationcontextcurrentbecause the winforms implementation of that class has not yet been installed since each thread has it is own synchronizationcontext it must be possible to retrieve it from a given thread object or am i completely wrong,['c#'] +97674,understanding objects in python i am a little confused by the object model of python i have two classes one inherits from the otherclass node def init identifier selfidentifier identifierclass atomnode def init symbol selfsymbol symbolwhat i am trying to do is not to override the init method but to create an instance of atom that will have attributes symbol and identifierlike thisatomfe 1 will create an atom with symbol fe and identifier 1thus i want to be able to access atomidentifier and atomsymbol once an instance of atom is createdhow can i do that,['python'] +97676,how can i programatically generate a thumbnail of a pdf with the iphone sdk were thisplaying pdf content using uiwebviews at the moment ideally i would like to be able to thisplay thumbnails in the uitableview without loading many different uiwebviews concurrently they are slow enough loading one document never mind 10does anyone have any tips on how i go about doing thisi have thought about screen capturing a document loaded using uidocumentinteractioncontroller or uiwebview but this means they would all have to be thumbnailed before thisplaying the table,"['iphone', 'objective-c']" +97682,c how to make a simple udp server can i make udp server and client using udpclient classand i need to send an image from the server to all clientscan some show me a code sample i am new to this,['c#'] +97688,is it possible to use obsolete attribute on only a getter or a setter of a property is it possible to use obsolete attribute on only a getter or a setter of a propertyi would like to be able to do something like thispublic int id get return id obsoletegoing forward this property is readonlytrue set id valuebut obviously that will not build is there a work around that allows me to apply this attribute to just the setter,['c#'] +97707,converting a list to a list or any class that extends number i want to create a very generic utility method to take any collection and convert it into a collection of a user selectable class that extends from number long double float integer etci came up with this code that uses google collections to transform the collection and to return an immutable listimport javautillistimport comgooglecommonbasefunctionimport comgooglecommoncollectimmutablelistimport comgooglecommoncollectlists takes a code liststring and transforms it into a list of the specified code clazz param t param stringvalues the list of strings to be used to create the list of the specified type param clazz must be a subclass of number defines the type of the new list return public static t extends number listt tonumberlistliststring stringvalues final classt clazz listt ids liststransformstringvalues new functionstring t suppresswarningsunchecked override public t applystring from t retval null if clazzequalsintegerclass retval t integervalueoffrom else if clazzequalslongclass retval t longvalueoffrom else if clazzequalsfloatclass retval t floatvalueoffrom else if clazzequalsdoubleclass retval t doublevalueoffrom else throw new runtimeexceptionstringformattype s is not supported yet clazzgetname return retval return immutablelistcopyofids it can be used like this convert liststring to listlonglistlong ids miscutilstonumberlistproductids longclassis my code overkill or how would you simplify it and at the same time keep it generic enough,['java'] +97717,is mod operation more cpu intensive than multiplication why is mod operation more expensive than multiplication by a bit more than a factor of 2 please be more specific about how cpu performs division operation and returns the result for mod operationin the following example the threads each run for a second the test was performed on a sparc processor multiplicationvoid somethread int a 10234 while true opers a a a a opers 26 106 in a sec modvoid somethread int a 10234 while true opers a a 107 a opers 12 106 in a sec,['c++'] +97724,how to restrict t to value types using a constraint i want to restrict the possible types and can takeon using a constraint i wish to restrict and to be either a int or a decimalpublic static chart populateintot nlistt yaxis listn xaxis where and int decimal do stuff hereany help appreciated,['c#'] +97746,variable scope issue with if statements php alright i seem to have a misconception with variable scope with php forgive my lack of the subject as i come from a java c background thinking i could make variables accessible to functions or if statements simply by placing it outside it below is a snippet of what i am trying to accomplishforeach nm as rowim itm name im lnk lnk ctyrow ifmode addmenu m m id id will be coming from fresh insert of menu name else m postmnu addrow echo menu id m ifmode addcat m c id id will be coming from fresh insert of cat name else m postcat addrow used for testing purposes echo item name itm name br echo lnk lnk br echo m m br m is empty here because its a new declaration as oppose to accessing m value from if statement thisplay fields liitm name itemli sql array itm name lnk m add a new entry to the queue now what i am trying to do is make the m variable values accessible outside the if statements its in to the m variable used in the sql array statement in c i would simply declare a variable outside the foreach loop and be able to use it after doing some reading on the matter i found that using the global or globals keywords would only work if my global scope variable is assign the value before the foreach and declaring global m to obtain that value within the loop but with my current code m is of a local scope within the if statements and everyone thiscourages using them now is there a better method of making m accessible to the sql array statement,['php'] +97759,rails possible to convert a pdf to images i have a rails 3 app with paperclips3is it possible to allow a user to upload a pdf convert the pdf to images and then uploadthanks,['ruby-on-rails'] +97786,how to reimport module to python then code be changed after import i have a foopydef foo print testin ipython i usein 6 import fooin 7 foofootestthen i changed the foo todef foo print test changedin ipython the result for invoking is still testin 10 import fooin 11 foofootestthen i usein 15 del fooin 16 import fooin 17 foofootesti delete the foopyc in same folder foopy exists but still no luckmay i know how to reimport the updated code in runtime,['python'] +97790,how to make uiprogressview on the uitableviewcell change immediately i put a uiprogressview on a uitableviewcell like that uitableviewcell cell tableview dequeuereusablecellwithidentifierdownloadcellifcellnil cell uitableviewcell alloc initwithstyleuitableviewcellstylesubtitle reuseidentifierdownloadcell autorelease uiprogressview downpreview uiprogressview alloc initwithprogressviewstyleuiprogressviewstyledefault downpreviewtag 123 downpreviewframe cgrectmake40070 20010 cellcontentview addsubviewdownpreviewwhen download size have changed i do that uiprogressview downpreview uiprogressviewcell viewwithtag123downpreviewprogress downloadprebut the look of downpreview will not change immediately only after i touch cell or other cell so how to make uiprogressview on the uitableviewcell change immediately,['ios'] +97800,how to use all view and helper methods inside of rails console for rails 2x and 3x helpermethod name worked in some version of rails are there ways that work in both rails 2 235 and 301 to use all view and helper methods,['ruby-on-rails'] +97823,handling entities in a game as a small exercise i am trying to write a very small simple game engine that just handles entities moving basic ai etcas such i am trying to think about how a game handles the updates for all of the entities and i am getting a little bit confused probably because i am going about it in the wrong wayso i decided to post this question here to show you my current way of thinking about it and to see if anyone can suggest to me a better way of doing itcurrently i have a cengine class which take pointers to other classes that it needs for example a cwindow class centitymanager class etci have a game loop which in pseudo code would go like this within the cengine classwhileisrunning windowclear screen entitymanagerdraw windowflip screen cap fpsmy centitymanager class looked like thisenum player enemy allyclass centitymanager public void create entityint entitytype player enemy ally etc void delete entityint entityid private stdvectorcentity entityvector stdvectorcentity entityvectoriterand my centity class looked like thisclass centity public virtual void draw 0 void set idint nextentityid int get id int get type private static nextentityid int entityid int entitytypeafter that i would create classes for example for an enemy and give it a sprite sheet its own functions etcfor exampleclass cenemy public centity public void draw implement draw void do ai stuffclass cplayer public centity public void draw implement draw void handle inputall of this worked fine for just drawing sprites to the screenbut then i came to the problem of using functions which exist in one entity but not in anotherin the above pseudo code example do ai stuff and handle inputas you can see from my game loop there is a call to entitymanagerdrawthis just iterated through the entityvector and called the draw function for each entity which worked fine seeing as all entities have a draw functionbut then i thought what if it is a player entity that needs to handle inputhow does that worki have not tried but i assume that i cannot just loop through as i did with the draw function because entities like enemies would not have a handle input functioni could use an if statement to check the entitytype like soforentityvectoriter entityvectorbegin entityvectoriter entityvectorend entityvectoriter ifentityvectoriterget type player entityvectoriterhandle input but i do not know how people normally go about writing this stuff so i am not sure of the best way to do iti wrote a lot here and i did not ask any concrete questions so i will clarify what i am looking for hereis the way i have laid outdesigned my code ok and is it practicalis there a better more efficient way for me to update my entities and call functions that other entities may not haveis using an enum to keep track of an entities type a good way to identify entities,['c++'] +97827,php number decimal point visible only if needed i would like to know if exists some function to automatically format a number by it is decimal so if i havephp sql resultcol number 145575 number format sql resultcol number 2 will return 145575 sql resultcol number 145500 number format sql resultcol number 2 could i get 1455 instead of 145500so my answer is if does exist some way to remove the decimals if i have decimal data forma in my db only when it is roundor shoud i do something like thatphp sql resultcol number 145500 str replace00 stringnumber format sql resultcol number 2 will return 1455,['php'] +97841,how to calculate the internet checksum from a byte in java i am trying to figure out how to calculate the internet checksum in java and its causing me no end of pain i am horrible at bit manipulation i found a version in c calculate an internet aka ip aka rfc791 checksum in c however my attempt at converting it to java does not see to produce the correct results can anyone see what i am doing wrong i suspect a data type issuepublic long getvalue byte buf byte 0xed 0x2a 0x44 0x10 0x03 0x30 int length buflength int i 0 long sum 0 long data 0 while length 1 data 0 data bufi 8 bufi 1 0xff sum data if sum 0xf0 0 sum sum 0xf sum 1 i 2 length 2 if length 0 sum bufi 8 sum bufferi if sum 0xf0 0 sum sum 0xf sum 1 sum sum sum sum 0xf return sum,['java'] +97848,javascript string replace with regular expression and function as arguments i seem to be getting conflicting advice in the books i read on this functionalityi am wondering if someone could clarifyfor example nicholas zakas states the function argument has a signature of the formatfunctionmatch pos originaltext p139 pro javascript for web developers 2nd ed wroxhe goes on to say when the regular expression has one match the function gets passed three arguments as above when there are multiple capture groups each matched string is passed in as an argument with the last two positions being the position and originaltextthen we come to doug crockfords javascript the good parts p90he stipulates the syntax again as stringsearcvaluereplacevaluesearchvalue can be a regex great a matchif replacevalue is a function the first parameter is the matched text then second is capture group 1 the third is capture group 2 and so onthere is a noticeable difference here ie no position argumenti was also looking at an example in pro javascript design patterns apress p152 that started this whole cross referencing process off these guys ross harmesdustin diaz rather unhelpfully specify the replacevalue function with two arguments named a bbut it tends to reinforce the notion doug crockford describescan someone confirm whether the nicholas zakas description is indeed a valid option too,['javascript'] +97858,linq to salesforce sql provider so i have this new project my company uses the salesforcecom cloud to store information about daytoday operations my job is to write a new application that will among other things more seamlessly integrate the crud operations of this data with existing inhouse application functionalitythe heart of the salesforce wsdl api is a set of query web methods that take the query command as a string the syntax of the query is sqlish but not quite they call it soql i am not a fan of magic strings so i would like to use linq in the codebase and parse the iqueryable into the soql query i need in the wrapper for the service it is certainly possible l2e l2sql but i would like to know if there is a shortcut because if i say it will take more than a day or two to roll my own i will be encouraged to find another method most likely a method for each generaluse query which was the method used in older apps if i succeed in making a generalpurpose soql parser we can use it in several other upcoming apps and i will be a hero even if i make a simple one that only supports certain query structures it will go a long way by allowing me to proceed with the current project in a linqy way and i can expand on it in my free timehere are the options as i see itlook harder for an existing linq2soql provider my googlefu is failing me here or else there simply is not one the only net wrapper only mentions linq as a nicetohavebuild an expression tree parser it needs to support at least the select and where method calls and needs to either parse lambdas or manipulate their method bodies to get the operations and projections needed this seems to be a rather massive task but like i said it is certainly possiblewrap the service in linq2sql or a similar existing linq provider that will allow me to extract a closeenough query string polish it up and pass it to the service there must be dozens out there though none that just drop in afaikcall expressiontostring or expressiondebugview and manipulate that string to create the soql query it will be brittle it will be ugly behind the scenes and it will support only what i am explicitly looking for but it will provide a rudimentary translation that will allow me to move onwhat do you guys think is building a linq parser more than a twoday task for one guy would a bodgedup solution involving an existing linq provider possibly do it would it be terrible to chop up the expression string and construct my query that wayedit thanks to kirk for the grounding i took some more looks at what i would be required to do for even a basic soql parser and it is just beyond the scope of me getting working application code written on any feasible schedule for instance i have to build a select list from either the select method lambda or a default one from all known columns from my wsdl object a task i had not even thought of i was focusing more on the where parsing i am sure there are many other unknown unknowns that could turn this into a pretty big deal i found several links which shows the basics of writing a linq provider and though they all try to make it simple it is just not going to be feasible timewise right now i will structure my repository for now using named methods that encapsulate named queries a constant class of formattable query strings should reduce the amount of headscratching in maintenance not perfect but far more feasible if and when a linq2soql provider gets off the ground either inhouse or opensource we can refactorfor others looking for linq provider references here are those helpful links i foundbuilding a linq providerwalkthrough creating an iqueryable linq providerlinq building an iqueryable provider series in 17 parts this one though long and involved has a lot of real indepth explanations and is good for firsttimers,['c#'] +97862,when is filejoin useful from reading the documentation it is apparent that filejoin joins the given parameters with the characterwhen is using this as opposed to filenamesjoin beneficial,['ruby'] +97866,negative pow in python i have this problem import math mathpow10713 traceback most recent call last file stdin line 1 in module valueerror math domain errorany suggestion,['python'] +97867,jquery valueattr is not a function i have this snipped in my pagecategory sorting form saveclickfunction var elements category sorting elements div eachelements functionkey value consoleinfokey value consoleinfocat id valueattrcat id and when it is executed i get0 div classdragable cat id6 value styleopacity 1 valueattr is not a function consoleinfocat id valueattrcat idwhat am i doing wrong here i am trying to get the value of the divcat id elementthanks eric,"['javascript', 'jquery']" +97869,select random rows in sqlite in mysql you can select x random rows with the following statementselect from table order by rand limit xthis does not however work in sqlite is there an equivalent,['sql'] +97880,generate er diagram from postgressql database on osx snow leopard could you tell me if you know any programs that can generate erdiagrams from an existing postgressql database on osx snow leoparddid not find something useful in googlethanks,['sql'] +97890,alphabetindexer with custom adapter can someone show me an example of how to use alphabetindexer with a custom adapter that uses a getview i have it working with a standard adapter but have no clue how to implement it with a custom adapterthanks,['android'] +97897,clearing intent my android app is getting called by an intent that is passing information pendingintent in statusbarwhen i hit the home button and reopen my app by holding the home button it calls the intent again and the same extras are still there override public void onsaveinstancestatebundle savedinstancestate superonsaveinstancestatesavedinstancestate override public void onrestoreinstancestatebundle savedinstancestate superonrestoreinstancestatesavedinstancestate this is the code that does not run like its supposed to string imgurl bundle extras thisgetintentgetextras ifextras null imgurl extrasgetstringimgurl if imgurlequalstextview01gettexttostring imageviewsetimagedrawable getimagefromurl imgurl layout1setvisibility0 textview01settextimgurltextview to hold the url and my intentpublic void shownotificationstring ticker string title string message string imgurl string ns contextnotification service notificationmanager mnotificationmanager notificationmanager getsystemservicens int icon rdrawableicon icon from resources long when systemcurrenttimemillis notification time charsequence tickertext ticker tickertext make intent intent notificationintent new intentthis activityclass notificationintentputextraimgurl imgurl notificationintentsetflags pendingintentflag update current pendingintentflag one shot pendingintent contentintent pendingintentgetactivitythis 0 notificationintent pendingintentflag update current pendingintentflag one shot make notification notification notification new notificationicon tickertext when notificationsetlatesteventinfothis title message contentintent flags notificationflags notificationflag show lights notificationflag ongoing event notificationflag only alert once notificationflag auto cancel sounds notificationdefaults notificationdefault sound notify mnotificationmanagernotify1 notificationis there any way to clear the intent or check whether it has been used before,['android'] +97900,mysql order by help i am looking to do an order by in a certain order i know i can modify the entire database but i would then need to modify the entire code basewhat i am have is a column in a table games called statusso select from games order by status asc will retrieve results going from 0 then 1 then 2what i am looking for is to be able to order it by 1 then 0 then 2any ideas,"['sql', 'mysql']" +97902,enable and thisable all breakpoints in eclipse is there a way to enable and thisable all breakpoints in eclipsei dont want to remove them just thisable them enable them after some condition is metthanks in advance,['java'] +97909,jquery selector how to selector two element select named1 option valuedd1option option valuedd1optionselectselect named2 option valuedd2option option valuedd2optionselecti have two select how two use jquery select this two selectnamed1changefunctionxthis code only could select one elementany one could give a handthanks,['jquery'] +97924,when does error occurs in java i am a student and right now going through exceptions and errors in javai have a confusion about when error occurs please share with me some examples,['java'] +97937,sysargv1 meaning in script i am currently teaching myself python and was just wondering in reference to my example below in simplified terms what the sysargv1 represents is it simply asking for an inputusrbinpython31 import modules used here sys is a very standard oneimport sys gather our code in a main functiondef main print hello there sysargv1 command line args are in sysargv1 sysargv2 sysargv0 is the script name itself and can be ignored standard boilerplate to call the main function to begin the programif name main main,['python'] +97941,is it possible to create statefull web service in c i have now something like thispublic class service1 systemwebserviceswebservice webmethod public string method1 someobj so someclassgetsomeobj this executes very long time 50s and more return somethod1 this exetus in a moment webmethod public string method2 someobj so someclassgetsomeobj this executes very long time 50s and more return somethod2 this exetus in a moment is it possible to make statefull web service so that i can reuse someobj so and just call methods on the same object so the client which will use this service would first call web method which would create so object and return some idand then in subsequent calls the web service would reuse the same so object based on idedithere is my actual codewebmethodpublic listprocinfo getprocessliststring domain string machinename string username string password taskmanager tm new taskmanagerusername password domain machinename return tmgetrunningprocesseswebmethodpublic bool killprocestring domain string machinename string processname string username string password new taskmanagerusername password domain machinenamekillprocessprocessname,['c#'] +97942,nhibernate sqlserverce i have problem with this exceptionhibernatehibernateexception could not create the driver from hibernatedriversqlservercedriver systemreflectiontargetinvocationexception exception has been thrown by the target of an invocation nhibernatehibernateexception the idbcommand and idbconnection implementation in the ssembly systemdatasqlserverce could not be found ensure that the assembly systemdatasqlserverce is located in the application directory or in the global assembly cache if the assembly is in the gac use qualifyassembly element in the application configuration file to specify the full name of the assemblyi tried everything i googled a lotsystemdatasqlservercedll is in debug directory is local referenced is not i gac i have copy local set true in debug directory is all other needed sqldll i tried x86 compilation but nothigthis is my nhibernate configxml version10 encodingutf8 hibernateconfiguration xmlnsurnnhibernateconfiguration22 sessionfactory property nameproxyfactoryfactory classnhibernatebytecodespringproxyfactoryfactory nhibernatebytecodespringproperty property nameconnectionprovidernhibernateconnectiondriverconnectionproviderproperty property namedialectnhibernatedialectmssqlcedialectproperty property nameconnectiondriver classnhibernatedriversqlservercedriverproperty property nameshow sqltrueproperty mapping files sessionfactoryhibernateconfigurationnhibernate version 30 beta 1 sqlserverce version 35 sp1my ideanhibernate still look in gac becouse a had installed sqlserverce after uninstall the problem starts how can i say to nhibernate please look take this dll,['c#'] +97974,how to divide a list into and equal parts python possible duplicatehow do you split a list into evenly sized chunks in python given any list of words lst i should divide it into 10 equal partsx lenlst10how to give these parts variable namesin the output i need 10 variables part1 part2 part10 with x number of words in itany ideas,['python'] +97984,multiple asynchronous connections with urllib2 or other http library i have code like thisfor p in range110 result false while result is false ret urllib2requesthttpserverstrp try result processurllib2urlopenretread except urllib2httperror urllib2urlerror pass resultsappendresulti would like to make two or three request at the same time to accelerate this can i use urllib2 for this and how if not which other library should i use thanks,['python'] +97998,mysql too many indexes i am spending some time optimizing our current databasei am looking at indexes specificallythere are a few questionsis there such a thing as too many indexeswhat will indexes speed upwhat will indexes slow downwhen is it a good idea to add an indexwhen is it a bad idea to add an indexpros and cons of multiple indexes vs multicolumn indexes,"['sql', 'mysql']" +98013,no jcode gem when running rails server when i try to run rails server it is giving me an error saying that it cannot find jcode and i think jcode is a default ruby libdo you guys have any clue as to whats going onusersseanfchanrvmgemsruby192p0globalgemsgdata1libgdatarb21in require no such file to load jcode loaderror from usersseanfchanrvmgemsruby192p0globalgemsgdata1libgdatarb21in top required from usersseanfchanrvmgemsruby192p0globalgemscontacts124libcontactsgmailrb1in require from usersseanfchanrvmgemsruby192p0globalgemscontacts124libcontactsgmailrb1in top required from usersseanfchanrvmgemsruby192p0globalgemscontacts124libcontactsrb6in require from usersseanfchanrvmgemsruby192p0globalgemscontacts124libcontactsrb6in top required from usersseanfchanrvmgemsruby192p0globalgemsbundler103libbundlerruntimerb64in require from usersseanfchanrvmgemsruby192p0globalgemsbundler103libbundlerruntimerb64in block 2 levels in require from usersseanfchanrvmgemsruby192p0globalgemsbundler103libbundlerruntimerb62in each from usersseanfchanrvmgemsruby192p0globalgemsbundler103libbundlerruntimerb62in block in require from usersseanfchanrvmgemsruby192p0globalgemsbundler103libbundlerruntimerb51in each from usersseanfchanrvmgemsruby192p0globalgemsbundler103libbundlerruntimerb51in require from usersseanfchanrvmgemsruby192p0globalgemsbundler103libbundlerrb112in require from usersseanfchanrubypracticegettingcontanctsconfigapplicationrb7in top required from usersseanfchanrvmgemsruby192p0globalgemsrailties301librailscommandsrb28in require from usersseanfchanrvmgemsruby192p0globalgemsrailties301librailscommandsrb28in block in top required from usersseanfchanrvmgemsruby192p0globalgemsrailties301librailscommandsrb27in tap from usersseanfchanrvmgemsruby192p0globalgemsrailties301librailscommandsrb27in top required from scriptrails6in require from scriptrails6in mainsystem mac osx snow leopardruby rvm 192rails 301gem 137trying to use contacts gemthankssean chan,['ruby-on-rails'] +98018,danger of c substring method recently i have been reading up on some of the flaws with the java substring method specifically relating to memory and how java keeps a reference to the original string ironically i am also developing a server application that uses c nets implementation of substring many tens of times in a second that got me thinkingare there memory issues with the c net stringsubstringwhat is the performance like on stringsubstring is there a faster way to split a string based on startend position,"['c#', '.net']" +98025,why do i get undefined reference errors even when i include the right header files when i tried to compile this program it failedinclude stdiohinclude stdlibhinclude pthreadhinclude unistdhvoid writenumbersvoid threadarg int start stop start atoichar threadarg stop start 10 while start stop printfdn start sleep1 return 0int mainint argc char argv pthread t thread1 thread2 create the threads and start the printing pthread createthread1 null writenumbers void argv1 pthread createthread2 null writenumbers void argv2 pthread jointhread1 null pthread jointhread2 null return 0it gave me the following errorstmpccrw21s7o in function mainpthreadctext0x83 undefined reference to pthread createpthreadctext0xaa undefined reference to pthread createpthreadctext0xbd undefined reference to pthread joinpthreadctext0xd0 undefined reference to pthread joincollect2 ld returned 1 exit statuswhy does it give me these undefined reference errors even though i had included pthreadh which declares these functions,['c'] +98036,activitynotfoundexception i am getting an activitynotfoundexception in the following codemainjavaintent intent new intent intentsetactioncomtestapptest startactivityintent activitynotfoundexceptionmanifestxmlactivity androidnamemainactivity androidthemeandroidstylethemedialog intentfilter action androidnamecomtestapptest intentfilteractivity,['android'] +98040,oauth2 for javascript is there an oauth2 library for javascript or how can i create a javascript app to interact with an oauth2 provider,['javascript'] +98050,stack performance in programming languages just for fun i tried to compare the stack performance of a couple of programming languages calculating the fibonacci series using the naive recursive algorithm the code is mainly the same in all languages i will post a java versionpublic class fib public static int fibint n if n 2 return 1 return fibn1 fibn2 public static void mainstring args systemoutprintlnfibintegervalueofargs0 ok so the point is that using this algorithm with input 40 i got these timingsc 2796socaml 2372spython 106407sjava 1336scmono 2956sthey are taken in a ubuntu 1004 box using the versions of each language available in the official repositories on a dual core intel machinei know that functional languages like ocaml have the slowdown that comes from treating functions as first order citizens and have no problem to explain cpythons running time because of the fact that it is the only interpreted language in this test but i was impressed by the java running time which is half of the c for the same algorithm would you attribute this to the jit compilationhow would you explain these resultsedit thank you for the interesting replies i recognize that this is not a proper benchmark never said it was p and maybe i can make a better one and post it to you next time in the light of what weve thiscussed edit 2 i updated the runtime of the ocaml implementation using the optimizing compiler ocamlopt also i published the testbed at feel free to make additions to it if you want,"['java', 'python', 'c']" +98055,how can i create a websocket on google app engine for html5 this is the demo that a simple chat client you must open it on webkit browser like chrome and safari the demo use a web socket server based on nodejs websocketservernodejs but i think it cant deploy on google app engine so did you know how to make a websocket using python on google app engine and running the demo on it thanksthis is the code doctype htmlhtml langenheadmeta charsetutf8 meta nameviewport contentwidth620 titlehtml5 demo web sockettitlelink relstylesheet href typetextcss script srcscriptheadbodysection idwrapper header h1web socketh1 headerstylechat width 97 them fontweight bold thembefore content them color b fontsize 14px you fontstyle italic youbefore content you color b fontsize 14px fontweight bold log overflow auto maxheight 300px liststyle none padding 0 margin 0log li bordertop 1px solid c margin 0 padding 10px 0stylearticle form input typetext idchat placeholdertype and press enter to chat form p idstatusnot connectedp pusers connected span idconnected0spanp pto test open two windows with web socket support type a message above and press returnp pthe server side code is available here a hrefnodewebsocket servera note that it runs on a href titlenodejsnodejsap ul idlogularticlescriptfunction openconnection uses global conn object if connreadystate undefined connreadystate 1 conn new websocketwsnoderemysharpcom8001 connonopen function stateclassname success stateinnerhtml socket open connonmessage function event var message jsonparseeventdata if typeof message string loginnerhtml li classthem messagereplaceg function m return entitiesm li loginnerhtml else connectedinnerhtml message connonclose function event stateclassname fail stateinnerhtml socket closed var connected documentgetelementbyidconnected log documentgetelementbyidlog chat documentgetelementbyidchat form chatform conn state documentgetelementbyidstatus entities if windowwebsocket undefined stateinnerhtml sockets not supported stateclassname fail else stateonclick function if connreadystate 1 connclose settimeoutfunction openconnection 250 addeventform submit function event eventpreventdefault if were connected if connreadystate 1 connsendjsonstringifychatvalue loginnerhtml li classyou chatvaluereplaceg function m return entitiesm li loginnerhtml chatvalue openconnection script footera hrefhtml5 demosaa idbuilt hrefrem built thisaa hrefviewsourceview sourceafooter sectiona hrefimg styleposition absolute top 0 left 0 border 0 src left darkblue 121621png altfork me on github abodyhtml,"['javascript', 'python']" +98057,detect loops in computer player in a cardgame a while ago i created a small cardgame web app for fun the player plays against the computer and mostly it works fine sometimes though the computer player gets into a loop the point of the game is to lose all your cards and if you do not have a card to play you take the pile sometimes the computer plays xyz takes the pile plays xyz takes the pile etc i keep track of the moves i have made so at any point i have an array that looks something like c2d5h2s4c5h2s4c5h2s4c5in this case i can see that i have gotten into a loop of playing h2s4c5 then taking the pile and then repeatingso the generalized problem is whats the best way to detect repeating patterns in a list i could probably whip something up using a simple for loop trying to find the card i am about to play and if i find that in position x then i could check whether the pattern from x to and repeats at position xnx to x but this seems like the kind of problem that could have a nice algorithm for it how would you code this given the following function signaturefunction findloopspreviousmoves nextmove maxpatternlength return looplength loopcount or null if there are no loopsps this is not a homework assignment the game exists and is at if anyone is interested,['javascript'] +98066,java change ao to aeouu possible duplicatesremove diacritical marks a c1 a a a1 a a1 a1 a1 i e2 a e3 e from unicode charsis there a way to get rid of accents and convert a whole string to regular letters how can i do this thanks for the help,['java'] +98070,getting the root head of a digraph in networkx python i am trying to use networkx to do some graph representation in a project and i am not sure how to do a few things that should be simple i created a directed graph with a bunch of nodes and edges such that there is only one root element in this graph now what i would like to do is start at the root and then iterate through the children of each element and extract some information from them how do i get the root element of this digraphso it would be something like thisthis is not real code just pseudopython to convey the general intent of what i would like to do root mydigraphroot for child in rootchildren iteratethroughchildrenchilddef iteratethroughchildrenparent if parenthasnochildren return for child in parentchildren do something iteratethroughchildrenchildi did not see anything in the documentation that suggested an easy way to retrieve the root of a digraph am i supposed to infer this manually oi tried getting itermydigraph with the hope that it would iterate starting at the root but the order seems to be random help will be appreciated thanks,['python'] +98083,what is the use of filter and chain in servlet chaindofilterreqreswe used this in a servlet program i want to know what is the use of the method dofilter in a servletalso what is the use of filter and chain concept in java servlets,['java'] +98085,aspectj loadtime weaving for signed jars does anybody success in using aspectj loadtime weaving with signed jars i got an exception and have no idea how to fix it tested with aspectj 1681610exception in thread main javalangnoclassdeffounderror compackageclazzajcclosure1 at compackagetestmaintestjava55caused by javalangclassnotfoundexception compackageclazzajcclosure1 at javaneturlclassloader1rununknown source at javasecurityaccesscontrollerdoprivilegednative method at javaneturlclassloaderfindclassunknown source at javalangclassloaderloadclassunknown source at sunmisclauncherappclassloaderloadclassunknown source at javalangclassloaderloadclassunknown source at javalangclassloaderloadclassinternalunknown source 1 morefrankly speaking i event not sure if it is technically possible but i know that similar issue using dynamically generated java code from signed java classes was done for hibernate project ie using javassist instead of cglib details are here,['java'] +98104,microsoft technology how do you upgrade your knowledge keep up to date in the new released versions nowadays i am struggling with something i did not experience maybe 5 years ago and i was wondering if you have experienced the samethe problem i do not have a good way to update my knowledge as new microsoft products are releasedin the old days say 5 years ago when ms released a new product it was maybe 2 or 3 years after the latest one in that time they appearantly had the time to write msdn books and i bought one read it and i was up to date with most of the new things in the new releaseit did not cover everything 100 but i knew whats new and i could google for more infobut in these days with ms releasing more and more out of band and more frequently the msdn books are not released for every new technology and i am a little lost for a resource where i can find the info i used to find in the msdn booksfor example now i am building websites with aspnet mvc2 and mvc3 is on it is way lately there are all kind of posts about mvc3 like there were on mvc2 but the downside imo in all these blogposts is that i not only get the info very fragmented different posts different blogs different writing styles but also very different in detailsome posts go very detailed but some of them even the one which get twittered by the scott lack a certain amount of problem description and or technical depthi guess what i actualy miss is that the info about the new topics not searching for a whole msdn site just want to be updated on the new stuff is presented somewhere as a whole and if it is possible as a coherent story toowhat i have now is a collection of links to all kind of blogposts and videos etcand also with buying the msdn book you knew what you could expect and it did have some quality and i prefer buying a 60 book that has that quality over looking at 30 videos of 45 minutes of which half of them has a thisappointing quality which you can only thiscover by watching itso long story are there more programmers experiencing this issuemichelpsi am not complaining about ms releasing but i do have a problem with find good resources to keep up to date,"['c#', 'asp.net']" +98106,android not able to attach a file in email by default files saved to the internal storage are private to your application and other applications cannot access them nor can the useri am able to see the file datadatapackage namefiles in file explore in ddms but when i attached the above file uri using imageuri in email then i saw that attached file is of 0kbi have used the default email apis of androidcan anyone suggest me how to attach a file in email that is private to the applicationalthough i am successful able to save the file in sd card and attaching the file from sd card this is working finebut if sd card is not available and saving the file to the internal storage then how can i attach them in emailstring filename hello filetxtstring string hello worldfileoutputstream fos openfileoutputfilename contextmode privatefoswritestringgetbytesfosclosefile imagefile getfilestreampathfilename uri imageuri urifromfileimagefilefinal intent emailintent new intentandroidcontentintentaction sendemailintentsettypeemailintentputextraandroidcontentintentextra streamimageurithisstartactivityforresultintentcreatechooseremailintent send mailsub activity,['android'] +98109,not operator in c for int strange question but someone showed me thisi was wondering can you use the not operator for int in c its strange to meinclude iostreamusing namespace stdint main int a5 b4 c4 d d a b b c a c b cout d system pause return 0,['c++'] +98110,serialize an object to xml i have a c class that i have inherited i have successfully built the object but i need to serialize the object to xml is there an easy way to do itit looks like the class has been set up for serialization but i am not sure how to get the xml representation my class definition looks like thissystemcodedomcompilergeneratedcodeattributexsd 40303191systemserializableattributesystemdiagnosticsdebuggerstepthroughattributesystemcomponentmodeldesignercategoryattributecodesystemxmlserializationxmltypeattributeanonymoustype true namespace systemxmlserializationxmlrootattributenamespace isnullable falsepublic partial class myobject here is what i thought i could do but it does not workmyobject o new myobject set o propertiesstring xml otostringhow do i get the xml representation of this object,['c#'] +98111,how to implement a unique index on two columns in rails i have a table and i am trying to add a unique index on two columns those columns are also indexed so my question is if i just can remove the indexes who were just for one column or if i have to use all three indexesadd index subscriptions user idadd index subscriptions content idadd index subscriptions user id content id unique truethanks for your clarificationmarkus,['ruby-on-rails'] +98112,android align button to bottomright of screen using framelayout i am trying to put the zoom controls of the map on the bottom right corner of screen i could do it with relativelayout using both alignparentbottomtrue and alignparentrighttrue but with framelayout i did not find any such attributes how do i align it to the bottomright of screen,['android'] +98115,inplace editing of text in uitableviewcell i know this has to be a really simple question but i am having trouble finding it in a simple place where there are not so many other things going on that i can isolate the specific behaviori know i need to add a uitextfield as a subview to the uitableviewcell to make it editable what is the best way to do this i see an example in uicatalog but i am confused with all of the extra things it is doing with the dictionaryagain please excuse the ignorance of this question a pointer to sample code or a screencast would be much appreciatedthanks in advancealan,['iphone'] +98128,django adding css classes when rendering form fields in a template i am outputting fields of a form in a template like this formfirst name and i would like to add a class eg blueprints spanxclass to it so i would like to know if there is a nice readymade solution template filter for that which i could use in the fashion formfirst nameadd claspan4 i just want to know if djangos developers or anybody has thought of that yet without my knowledge before doing it on my own,['python'] +98135,explain c fundamentally has a corrupt type system in the book coders at work p355 guy steele says of ci think the decision to be backwardscompatible with c is a fatal flaw itas just a set of difficulties that canat be overcome c fundamentally has a corrupt type system itas good enough to help you avoid some difficulties but itas not airtight and you canat count on itwhat does he mean by describing the type system as corruptcan you demonstrate with a simple example in ceditthe quote sounds polemic but i am not trying to be i simply want to understand what he meansplease give examples in c not c i am interested in the fundamentally part too,"['c++', 'c']" +98137,what does cxf stands for in apache cxf what does cxf abbreviation meanwhat is c what is x what is f,['java'] +98141,17136119 144 is false possible duplicatephp math precision here is a sample code in phpecho 17136119php result 144javascript result 14403manual result 144var1 144converted 17136119variable 1 is less than convertedecho var1 convertedyesnoresult yesvariable 1 is equal to convertedecho var1 convertedyesnoresult noecho converted 144yesno noecho 14400 144yesno yescould you give me a straightforward explanationanswer and tell me that php is not buggy,['php'] +98147,gdb break on any class method i have a class with a regrettable number of methods i would like gdb to break whenever i enter the class so through any of the methods is there a way to do this without setting break points individually for each method,['c++'] +98178,executable jar would not find the properties files i use this code in my program to load a properties fileproperties properties new propertiesurl url new appgetclassgetresourceproperties filepropertiesloadurlopenstreamthe code runs fine in eclipse then i package the program into a jar named myprogramjar and run it i got a nullpointerexception at the second line the jar does not contain the properties file they both are in the same directory i am using maven to create the jar how can i fix this problemupdate i do not want to add the properties file to the jar since it will be created at deployment time,['java'] +98189,running mstest unittests using a msbuild script could you please guide me how to run mstest unit tests using an msbuild script,['.net'] +98198,windowonbeforeunload may fire multiple times just because you do not see use for a feature does not mean it is not usefulthe stack exchange network gmail grooveshark yahoo mail and hotmail use the onbeforeunload prompt to preventwarn users that they are leaving a page after they have begun editing something oh yah nearly every single desktop program that accepts saveable userinput data utilizes this promptuserbeforeleaving ux patterni have a function which behaves similarly to this onewindowonbeforeunload function only prompt if the flag has been set ifpromptbeforeleaving true return are you sure you want to leave this page when a user attempts navigates away from the page the browser presents them with the option to leave or stay on the page if the user selects the leave this page option and then they quickly click on a link again before the page unloads completely the dialog fires againare there any foolproof solutions to this problemnote the following not the solution var alreadyprompted falsewindowonbeforeunload function only prompt if the flag has been set ifpromptbeforeleaving true alreadyprompted false alreadyprompted true return are you sure you want to leave this page because the user might select the stay on the page option which would cause future onbeforeunloads to stop working,"['javascript', 'jquery']" +98211,c how to loop while mouse button is held down can you point me in the right direction i am trying to get a loop to trigger while the form button is depressed pseudocodewhile button1 is pressedvalue1 1and then of course stop looping when the button is released,['c#'] +98225,rails where does new something path variable get set up i created a scaffold for messages and new message path and edit message path for use in link tos are all set up but now i have created appviewsmessagessenthtmlerb and i want to do something along the lines of link to sent sent message path but i cannot figure out how to do that i get undefined local variable or method sent message path for actionviewbase0x103117c50,"['ruby-on-rails', 'ruby']" +98235,linq the query operator elementatordefault is not supported why the following code produces the errorthe query operator elementatordefault is not supporteddim im from view in dbviews where viewpass txtcodetext select new with id viewuniqueidtostring thistinctresponseredirecttestaspxx im0idis there any way of fixing it without using the firstordefault optionupdate and here is the stacktrace at systemdatalinqsqlclientqueryconvertervisitsequenceoperatorcallmethodcallexpression mc at systemdatalinqsqlclientqueryconvertervisitmethodcallmethodcallexpression mc at systemdatalinqsqlclientqueryconvertervisitinnerexpression node at systemdatalinqsqlclientqueryconverterconvertouterexpression node at systemdatalinqsqlclientsqlproviderbuildqueryexpression query sqlnodeannotations annotations at systemdatalinqsqlclientsqlprovidersystemdatalinqprovideriproviderexecuteexpression query at systemdatalinqdataquery1systemlinqiqueryproviderexecutesexpression expression at systemlinqqueryableelementatordefaulttsourceiqueryable1 source int32 index at loginbtnlogin clickobject sender eventargs e in dprojectsmemorialoginaspxvbline 14 at systemwebuiwebcontrolsbuttononclickeventargs e at systemwebuiwebcontrolsbuttonraisepostbackeventstring eventargument at systemwebuiwebcontrolsbuttonsystemwebuiipostbackeventhandlerraisepostbackeventstring eventargument at systemwebuipageraisepostbackeventipostbackeventhandler sourcecontrol string eventargument at systemwebuipageraisepostbackeventnamevaluecollection postdata at systemwebuipageprocessrequestmainboolean includestagesbeforeasyncpoint boolean includestagesafterasyncpoint,['asp.net'] +98241,favicon in subdirectory all subdomain i am used to just save the faviconico in the public html folder for adding the faviconthe problema i have now is that i want to thisplay the in all the files of a certain subdirectory examplecomexample onwards just putting it there doesnt seem to do the jobi know i could go document by document and addlink relshortcut icon hreffaviconico typeimagexicon but i hope there is a more practical way first i thought there might be a way trough css but that doesnt seem to be the casethis would have come in handy because every document already includeslink relstylesheet typetextcss hreftestcss so any ideas or workarounds to how to solve this,['html'] +98265,qt automated testing how would they have been able to do that is there a qt inspection library standard window spy tools work in some areas but other important areas such as list items in a list view are not inspectable through windows messagesi know there is the qttest framework but what i would like is something that can access an application as a whole so that i can have automated integration testing,['c++'] +98287,is it possible to solve this recently i encountered this puzzle int main int arr7 int bcda a4 printfdarr return 0the question is to replace with a integer so that output is 4 i am not sure but i do not think this is solvable in a standard way not invoking undefined behavior or depending on implementation if no then i am very interested in knowing how editthis task is taken from here i tried to solve with 10 but sadly it is not the answer the problem setter wantshowever i solved it using some pretested implementation dependent mumbojumbobut i really have no explanation for how it really works here is the answer spoileryou are welcome to explain it,"['c++', 'c']" +98295,how to make rounded border in ie8 with css i would like to know how to make rounded border in ie8 i am usingmozborderradius4pxwebkitborderradius4pxfor mozilla and safari,"['html', 'css']" +98303,reload css stylesheets without reloading the page i have been using safari as my development browser and i find it quite difficult to preview css changes in a heavy javascript environmentmy web application and development environment is as followsmac osx snow leapordsafaritextmatemootoolsmochauixhtml 11 transitionalcss3,['css'] +98326,where i can find inject jar i am following the mvc unit test instructions from this sitebut i cannot find the jar for the inject annotation does anybody know where the jar is,['java'] +98329,data structure to store huge amount of data in my applicationi have to load volumedata from set of images mrc images and keep the pixel data in memoryimages are grayscaled so one byte per pixelmy development environment is qt framework mingw for windows and gcc for linuxat the momenti use a simple data structure to store volumedata as unsigned char volumedataand do one huge allocation as followsvolumedatanew unsigned charimagexsize imageysize numofimagesfollowing are the important methods to access imagedata in a given planesuch asunsigned char getxyplanesliceint z valueunsigned char getyzplanesliceint x valueunsigned char getzxplanesliceint y valuewith my simple datastructure it was easy to implement above methodsbut we might need to adopt to volume size as 20x20x10 37gb in the futureand current datastructure will not be able to handle that huge datahow to avoid fragmentation noweven with 10x10x200 data application crash giving bad allocwhats the best way to change the datastructure for this shall i use something like linkedlist which each chunk is of size 100mbalsouser should be able to perfome some imageprocessing filters on volumedata and also should be able to reset to original pixel valuethat means i should keep two copies of volumedata with current implemetation its likeunsigned char volumedataoriginalunsigned char volumedatacurrentso with 20x20x10 datarange its going to utilize about 8gb 4gb for each volumebut in win32 the address space is 4gbhow to tackle this i should go with 64bit application edit here is a snapshot of my application basicallyi load the volumedata from set of imagesfrom mrc formatetc and thisplay them in different planeviewers xyyxyzimage shows xyplanevieweri need to keep above 3 dataaccess methods to show an image in a particular planeusing sliderbar user can change which image to show in the selected planethanks in advance,['c++'] +98340,any way to limit border length is there any way to limit the length of a border i have a div that has a bottom border but i want to add a border on the left of the div that only stretches half of the way up is there any way to do so without adding extra elements on the page,['css'] +98349,automapper running extremely slow on mapping 1400 records i am using automapper which i am very impressed with however i have a complex object with many nested collections i am using telerik openaccess and it returns the 1400 records fast but when i pass it to automapper and it slows to a ridiculous crawl here is my code for reference listdalevent query httpcontexteventswheree einactive true eevent locations nulltolist mappercreatemapdalevent eventdto mappercreatemapdalevent association eventassociationdto mappercreatemapdalevent executingunit eventexecutingunitdto mappercreatemapdalevent funding eventfundingdto mappercreatemapdalevent location eventlocationdto mappercreatemapdalevent objective eventobjectivedto mappercreatemapdalevent osr eventosrdto mappercreatemapdalevent paxbreakdown eventpaxbreakdowndto mappercreatemapdalevent regionalconsideration eventregionalconsiderationdto mappercreatemapdalevent reviewstatus eventreviewstatusdto mappercreatemapdalevent spcalendarclone eventspcalendarclonesdto mappercreatemapdalevent task eventtasksdto mappercreatemapdalevent tso eventtsosdto mapperassertconfigurationisvalid mapperallownulldestinationvalues true ilisteventdto result mappermaplistdalevent listeventdtoquery return resulthelp,"['c#', 'asp.net']" +98366,opening a xls spreadsheet programatically in c from a sharepoint site in read write mode i have written a procedure that will open a xls from a local thisc refresh the data in it and then save it again this works finethe problem occurs when i replace the filename to point to a sharepoint site it opens the file fine refreshes the file but when it trys to save the file it throws an exception with the message cannot save as that name document was opened as readonlyif i try and save the file with a different filename then it works finedoes anybody know what i am missing i think it must have somethoing to do with how i am opening the file is there another way that i can force the opening of the file in a readwrite manner private static void refreshexceldocumentstring filename var xls new microsoftofficeinteropexcelapplication xlsvisible true xlsthisplayalerts false var workbook xlsworkbooksopenfilename filename ignorereadonlyrecommended true readonly false try refresh the data from data connections workbookrefreshall wait for the refresh occurs wish there was a better way than this systemthreadingthreadsleep50 save the workbook back again workbooksaveasfilename filename this is when the exception is thrown close the workbook workbookclosesavechanges false catch exception ex exception message is cannot save as that name document was opened as readonly finally xlsapplicationquit xls null many thanks in advance for suggestionsjonathan,['c#'] +98371,detect start and stop editing uitextview how can i call some code upon entering a uitextview user taps to edit it and leaving the view user taps to leave itappreciate any help,"['iphone', 'objective-c']" +98378,how can i get a method name with the namespace class name i would like to get the fully qualified method name i can see how to get the method name on its own with the followingsystemreflectionmethodbasegetcurrentmethodnamebut this only returns the actual name i need everything likemyassemblyclassnamemethodname,['c#'] +98379,can you overload sum to add custom types i have a money struct that has currency and amount i would like to be able to sum an list by using linqpublic struct money public string currency get set public decimal amount get set public static money operator money m1 money m2 if m1currency m2currency throw new invalidoperationexception return new money amount m1amount m2amount currency m1currency given the above code if i have a list of items that have money value objects is it possible to get the sum function to work with a money value objectieitemssumm mmoneyvalue,['c#'] +98380,incell data bars in jqgrid possible or not i generally do not like using excel and microsoft products in general but excel 20072010 has some very nice conditional formatting features which sadly i have not seen in many other places so far one of these which i use extensively in business reports is data barsin my opinion these data bars are extremely helpful in understanding the meaning of data beyond the numbers while the difference between 200 and 20 users is just a hardtograsp digit to the human eye a bar which is 10 times longer is much more intuitivemy question is there any way to include incell conditional data bars for every value of a column in jqgrid mirroring the excel functionality this would be the only way i see to get rid of our excel sheets and implement the reports in an online reporting system data bars are simply inthispensable once you get used to them and they are the only reason we still use excel for reportsif as i assume there is no builtin functionality like this in jqgrid do you think it would be a lot of work to custombuild it do you have any ideas what the best way would be to approach this,['jquery'] +98390,copycut collapsed code and have it collapsed when pasted when i copy or cut collapsed code and paste it somewhere else the code gets expanded is there any way to make visual studio to retain the collapseexpand state when copycutpasted i am hoping that i can rearrange methods order quickly by cutting and pasting while all the implementaion details are nicely collapsedi am working on vs2008 c right now but any tip on vs2010 is also appreciated,['c#'] +98411,iis 7 url rewrite rules are not being applied i have a net 40 web application hosted on iis7 serverafter reading this about serving static content from another server so that cookies are not sent with every request for a static file i tried it out but without much successthis is the part written in the webconfig filesystemwebserver rewrite rules rule nameimages stopprocessingtrue match urlimages action typerewrite urlr1 appendquerystringtrue logrewrittenurltrue rule rules rewritesystemwebserverwith this rule defined every link to a file in the images folder should be rewriten into the staticserver url but this does not work at all now every image that is in the images folder returns a 404 not found any idea on what could be causing this behavior or a different solution on how to serve files from a specific folder from a different server without having to go trough tons of code and change all the links to link to the static server i did also try using the redirect action type instead of the rewrite action which actually worked but it defies the reason why i am trying to serve the files on a different server this way the request is sent to my dynamic content server with all the required cookies and is redirected to the staticserver which is actually worse than serving the images from the dynamic content server,['asp.net'] +98424,grant select permission on a view but not on underlying objects i often read that one purpose of a view is security to allow some users access to the underlying table and other users to a derived view only with that in mind i designed several views that supply restricted datasets to external usersall very fine but in practice this does not work after i grant select permission on a view the users cannot access it unless i grant select on all underlying objects too same story for stored procedures the net result is nonfunctional for i end up still granting access to sensitive data to the wrong users as well as annoying for it is easy to forget one object and the users come back to complain that the view does not workis there a way to grant select permissions on a view or stored procedure without having to expose the underlying objects too,['sql'] +98434,what is c 5 and where does it come from i know c 35 is used with vs2008 and net 35also c 4 is part of vs2010 and net 40 but what is c 5 what ide,"['c#', '.net']" +98437,do your javadocs get compiled into your class files when you compile your java files does it also embed your javadocs and comments into the class filefor example if you have large javadocs does it effect the overall size of your class file or does the compiler ignore everything beginning with and,['java'] +98442,html multiselect limit is it possible to set limit to multipleselectbelow is an example code where user can select more than 1 valueselect multiplemultiple namechooseoption value1value 1optionoption value2value 2optionoption value3value 3optionoption value4value 4optionoption value5value 5optionoption value6value 6optionselectbut how to limit user to select not more than 3 valueany idea,['html'] +98465,jaxb and collections containing generics we have the jaxbjava code below this worked fine until we changed listjqgridto rows to list extends jqgridto rows when we made that change we get this errorconstructor threw exception nested exception is comsun xmlbindv2runtimeillegalannotationsexception 1 counts of illegalannotationexceptions property rows appears in xmltypeproporder but no such property exists maybe you meant records this problem is related to the following location at commeuiservicejqgridjsonrootwhy do we get this error cannot you use generics as we did ie specifing extends xmlrootelementxmltypename proporder records page total rowspublic class jqgridjsonroot int total total pages for the query int page current page of the query int records total number of records for the query list extends jqgridto rows,['java'] +98472,do i need to explicitly close the streamreader in c when using it to load a file into a string variable examplevariable new streamreader file readtoendis that acceptable,['c#'] +98486,what rules does compiler have to follow when dealing with volatile memory locations i know when reading from a location of memory which is written to by several threads or processes the volatile keyword should be used for that location like some cases below but i want to know more about what restrictions does it really make for compiler and basically what rules does compiler have to follow when dealing with such case and is there any exceptional case where despite simultaneous access to a memory location the volatile keyword can be ignored by programmervolatile sometype ptr someaddressvoid somefuncvolatile const sometype input function body,['c++'] +98500,core data force custom mapping modelpolicy instead of lightweight migration i have got about 4 different versions of my data model now and every one except the last one has been just a minor change using automatic lightweight migration for this latest model i need to do a bit of additional work during the migration so i created a custom mapping model and a migration policy subclass with some actions in the createdestinations and createrelationships problem is my mapping modelcustom policy is not being called and it seems that core data is trying to perform lightweight migration instead is there something i need to do to keep lightweight migration around but use my mapping model when there is one available,['iphone'] +98501,euler program in java i just started with solving project eulers problems even though this one is very simple i want to take your opinion on the best solutionthe problem if we list all the natural numbers below 10 that are multiples of 3 or 5 we get 3 5 6 and 9 the sum of these multiples is 23find the sum of all the multiples of 3 or 5 below 10this is how i coded itpackage comproblemonetenpublic class naturalnumber public static void mainstring args int sum0 forint i0 i10 i ifi3 0 i5 0 sum i systemoutprintlnsum,['java'] +98512,order of default and nondefault arguments in python i understand that default arguments come at the end and that nondefault arguments cannot follow a default argument that is fine like for example def foox0 y return x ysyntaxerror nondefault argument follows default argumentthat is ok as expectedhowever what about the case when i want that the first argument should be a default one like for example as is apparent from the above code x has to be the first argument and it should have a default value of 0 is it possible to do this i am asking because even in the range function i am guessing it is something like thisdef rangestart0 end paso how is this done and if it is not possible how is this implemented by range note that i am insisting on the first argument to be default that is the entire point i am using range as an example because it fits my problem perfectly of course one could implement range as def rangeend start0 but that is not the point,['python'] +98524,garbage collection on a local variable i am a c programmer entering the world of java and i cannot get rid of the bad feeling of having to let the java garbage collector do my cleaninghow for example will this code behave in javapublic void myfunction myobject object new myobject objectdosomethingwill the local variable object be deleted when myfunction exitsdo i have to set object to null before exiting or will it be out of scope and be deleted by the gc or at worst will it leak like it would in c,['java'] +98534,jquery getjson with timeout when making a call out to the yahoo web service to return a data set is it possible to set a timeout and exit the routine once its elapsedjquerygetjson function data result set here,['jquery'] +98542,jquery removeattrthisabled not working on firefox i have some code that looks like the following coming back from an xhr responsejquerytextnothiddenremoveattrthisabledthis is a result of input fields being thisabled after form submit the xhr response returns this tidbit of jquery and reenables controls works great on every browser even partially on ff 361 osx what i mean by partially is that some text fields have the thisabled attribute removed others do not these text fields are verified not hidden,"['javascript', 'jquery']" +98547,move a range of elements between containers i have been looking at the c documentation for a function which would move a range of elements from one container to another using move semantics however i have not found such a function what am i missinghow would i do the following without copying and using explicit loops move 10 elements from beginning of source to end of destdestend movesourcebegin sourcebegin 10,['c++'] +98570,why is java platform independent in theory and platform dependent in practice i know that one of the big things about java is that it is platform independent in the sense that you can make a java application and have it run in windows linux mac and so forth as long as you do not use libraries specific to one os and as long as you have a jvm installed for the appropriate os to interpret things correctlyhowever why cannot a normal computer java program as in a simple hello world in java for windows or linux for example run just the same in a mobile phone when mobile phones also have their specific jvm installed to interpret things correctlywhy is it necessary to change the architecture of the program in some cases such as android development or use java me to make applications specific for some general mobile phonesi know that there are some functions that are related to certain functionalities of the os that might not apply in the mobile platforms for example such as some things related with console input methods and so forth but is this really the only reason that makes things not compatible if so why would not a simple application that just declares and initializes an integer variable be able to run across all nonmobile and mobile platforms that have a jvm availablei am aware of other questions that have been posted before such as this but that do not focus the exact point i am aiming for here,['java'] +98572,c wcf catch fault exceptions of base type i have been looking everywhere to find out how to catch a base fault contract type in c i would like to have all my fault contracts inherit from one class and have one catchfaultexception fex in the mvc controllerdatacontractsdatacontractpublic class baseclass1 datacontractpublic class class2 baseclass1 serviceservicecontractpublic interface iservice1 operationcontract faultcontracttypeofbaseclass1 faultcontracttypeofclass2 do i need this one void throwclass2public class service1 iservice1 public void throwclass2 throw new faultexceptionclass2new class2 class2 reason service consumerfaulttestserviceservice1client client nulltry client new faulttestserviceservice1client clientthrowampfaultsinvalidparameter 0catch faultexceptionnamespacebaseclass1 fex does not go in here as i would expect catch faultexception fex other possible option messagefault fault fexcreatemessagefault var fe1 faultgetdetailbaseclass1 this throws a serialization exception it needs class2please let me know if either of these catch statements can be fixed to do what i am looking for,['c#'] +98605,convert bitmap to sepia in android is there any way to convert a bitmap to sepiai know to convert to grayscale is to set the setsaturation in colormatrixbut what about sepia,['android'] +98611,sql insert with select and hardcoded values for illustration purposes let us say i have a database moviestitle director cost profitsnow i would like to insert a new row into the movies table based on a director found in another table and then hard coded valuesinsert into movies select name from directors where name lucasis how i understand select inserts work but what if i want to use the select as well as pass in hard coded values so something theoretically like thisinsert into movies valuesstar warsselect name from directors where namelucas 50 10is this possible,"['sql', 'mysql']" +98628,how to retrieve the dimensions of a view i have a view made up of tablelayout tablerows and textviews i want it to look like a grid i need to get the height and width of this grid the methods getheight and getwidth always return 0 this happens when i format the grid dynamically and also when i use an xml version how to retrieve the dimensions for a view here is my test program i used in debug to check the results import androidappactivityimport androidosbundleimport androidwidgettablelayoutimport androidwidgettextviewpublic class appwig extends activity override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmaindemo includes the grid called board int vh 0 int vw 0 test1 used the xml layout which is thisplayed on the screen tablelayout tl tablelayout findviewbyidridboard tl tablelayout findviewbyidridboard vh tlgetheight getheight returned 0 why vw tlgetwidth getwidth returned 0 why test2 used a simple dynamically generated view textview tv new textviewthis tvsetheight20 tvsetwidth20 vh tvgetheight getheight returned 0 why vw tvgetwidth getwidth returned 0 why eof method eof class,['android'] +98631,is there a way to step through a rails app in a debugger is there a way to step through a rails app in a debugger as it handles a request,['ruby-on-rails'] +98678,restrictions on the main function c03 3613 the function main shall not be used 32 within a program i wonder why this rule exists is anyone aware of any systemimplementation where it would be a problem if main were used ps 1 i know the definition of the term used 2 i know there are simple workarounds like calling a single mymain from main and using mymain instead 3 the question is about realworld implementations which would have a problem if the restriction werent there thanks,['c++'] +98686,java annotation processing how do i know if a round is the last one when extending abstractprocessor there is a possibility to override init but there is no opposite method which would be called after all rounds were processedthis is a problem when you have to append information collected during each round to same file you just cannot ever close the file because you never get to know when the last round was so the file is never closed and remains emptyusing a shutdown hook does not work either the hook is never calledany ideas,['java'] +98694,suspendthread wow64 suspending in kernel code update microsoft have yet to fix it in windows 81edit this turned out to be a bug in wow64 getthreadcontext may return stale contents when the thread is suspended in long mode ring3 user mode i have suggested to microsoft to use ring2 to perform the translation suspendthread would then only suspend thread in ring3 as it does now no changes necessary and a crashfaultexploit in ring2 would not affect the kernel it would only affect ring2 and ring3such changes would necessitate the change of a few winapi functions such as wow64getsetthreadcontext etc this would break apps relying on undocumented features but that is to be expected granted translation would be slower as it takes a few cpu cycles to transition from ring3 to ring2 depending on the cpu family but i would think that the role of the os is first and foremost to ensure correct operation translation already adds overhead to apps running under wow64 so that is to be expected tooi do hope that microsoft would fix this issue otherwise debuggers mono apps boehm gc apps that rely on getthreadcontext under wow64 would not work for starters i have seen debuggers show stale stack traceedit2 bad news from my conversation with alexey from msft here it looks as though it may not get fixed at all in fear that the fix would break apps that rely on undocumented featuresoriginal questionsome people seem to be confused about the following i initially thought it was due to suspendthread suspending a thread while in kernelmode code it was not the following was merely my initial suspicion which turned out to have nothing to do with the actual root cause which was the stale contents returned by getthreadcontextfrom msdnsuspending a thread causes the thread to stop executing usermode application codewhat i have found however is that my 32bit app in windows 7 running under wow64 thread a calling suspendthread on thread b can pause it while it is running 64bit code which i would expect is not usermode code eip shows the suspended thread stopped at wow64cpux86switchto64bitmode0759c31b0 ea27369c753300 jmp 0033759c3627with its esp having changed i know this because while the esp is pointing to the same page as that threads stack it is got a much higher address than the current stack pointer if i put a breakpoint at the instruction which the above returns to and then get the thread to resume i found that the esp changes back to the value before the x86switchto64bitmode call which is the correct stack pointer i also found that when single stepping into the same function i can never get that higher address esp value at any point of the single step in fact when single stepping esp value never changes before and after the x86switchto64bitmode callalso i did make sure suspendthread succeed by checking against dword1all of these leads me to believe that the thread is suspended in kernelmode codewhat could be causing the os to suspend a thread while it is running nonusermode code how do i prevent that this is basically preventing me from getting the actual current stack pointer of thread b note that when the app runs outside of wow64 on native x86 os no such problem exists,['c++'] +98695,problem with positional parameters in jpa native query i am trying to dostring sql select email from users where type like b and username like 1list results emcreatenativequerysqlsetparameter1 usernamegetresultlistbut i get illegalargumentexception that tells me that the parameter is out of bounds what am i doing wrong,"['java', 'sql']" +98701,how can i refresh the gallery after i inserted an image in android i have added an inserted in gallery using android api as followingimagesmediainsertimagectxgetcontentresolver scardtestjpg hello descriptionactually the image that i passed its full path scardtestjpg is already successfully inserted in the db but when you open the gallery you cannot see it unless you switch offon the device or mountunmount the external memoryit there any way to refresh the gallery on demandthanksbassel kh,['android'] +98708,expandablelistview hide indicator for groups with no children in an expandablelistview is there a way to hide the group indicator for groups with no children,['android'] +98711,python qt windows forms or swing for a crossplatform application i would like to develop a smallmediumsize crossplatform application including guimy background mostly web applications with mvc architectures both python pylons sqlalchemy and java know the language well but do not like it that much i also know some c so far i have no gui programming experience neither windows forms swing nor qti plan to use sqlite for data storage it seems to be a nice crossplatform solution and has some powerful features eg full text search which sql server compact lacksi have done some research and these are my favorite options1 qt python pyqt or pyside and sqlalchemyprospython the languageopen source is strong in the python world lots of libraries and userssqlalchemy a fantastic way to interact with a db and incredibly well documentedconscompilation thistribution and deployment more difficultno qt experienceqt designer not as nice as the visual studio winforms designer2 netmono windows forms c fluent nhibernate systemdatasqliteprosc i like it especially compared to java and would like to get more experience in itthe winforms gui designer in visual studio seems really slickintellisenseclickonce deploymentwindows forms look and feel good on windowsconsfluent nhibernate far less documented than sqlalchemy also annoying fluent docs refer to nhibernate docs which refer to hibernate aargh but plain nhibernate xml does not look very comfortablewindows forms will not look behave native on linuxmac os correctfewer open source libraries in the net world fewer oss users less documentation in generalno winforms and nhibernate experience3 jvm java jython swing sqlalchemyi am emotionally biased against this one but listed for completeness sakeprosjvmswing work well as crossplatform basisjythonsqlalchemylots of open source librariesconsswing seems ugly and difficult to layoutlacks a good gui designerguessing that i would not be able to avoid java for ui stuffnot sure how stable the jythonjava integration isoptions that i have ruled out just to avoid thiscussion on these wxwidgetswxpython now that qt is lgpled gtkpygtkthe look and feel of the final application is very important to me the above technology stacks are very different pyqt net winforms jvm swing and require some time to get proficient sowhich alternative would you recommend and why,"['c#', 'java', 'python']" +98731,the way to compare string in an efficient way in c is it efficient to compare a string with another string or string literal like thisstring astring bif a testor if a bmy coworker asked me to use memcmpany comments about thisthanks,['c++'] +98742,qslider value changed signal i am using a qslider v46 for input as well as to provide feedback to the user for the feedback i will be calling the setvalue method i am trying to find a signal that will fire only if the user modified the value the valuechanged signal fires when the user changed the value as well as when i call setvalue slidermoved only fires when the user drags the slider not when using the keyboard i checked the api docs and cannot seem to find anything am i missing something this seems something that would be common if there is no other signal how would you recommend that i simulate this functionality should i set a flag before calling setvalue thisconnect and reconnect the signal every time i call setvalue,['c++'] +98745,linq to entityframework datetime in my application i am using entity framework my tablearticleperiodstartdatei need records that match datetimenow startdate and startdate period datetimenowi tried this code but its now working contextarticle wherep pstartdate datetimenow wherep pstartdateadayspperiod datetimenowwhen i run my code the following exception occurlinq to entities does not recognize the method systemdatetime adaysdouble method and this method cannot be translated into a store expression,['c#'] +98749,how to marshal an object via jaxb without any information about it i have an object value which is of some type either xmlrootelementannotated or not i want to marshal it into xmlstring value1 testassertequalsfootestfoo toxmlfoo value1 xmlrootelementclass bar public string bar testassertequalsfoobartestbarfoo toxmlfoo new barcan i do it with jaxb existing facilities or i should create some custom analyzer,['java'] +98759,how to keep google chrome extension popup open if i open my extension popup then i open another window or tab following the popup does not stay open if i return to itis there a way to force it so the popup stays open,['javascript'] +98762,can i wrap each line of multiline text in a span i have been trying to figure out how to do this if it is even possible and have drawn a blanki have some text that will wrap onto multiple lines i want to detect each individual line and wrap it in a span finally i want to assign a class to each span from a looping arrayfor examplediv idquote i have some text that wraps onto three lines in this containerdivi want to get my jquery to parse those lines detect where it wraps and turn it into thisdiv idquote span classredbgi have some text thatspan span classorangebgwraps onto three linesspan span classyellowbgin this containerspandivthe reason that i want to do this dynamically is that i am doing it within responsive templates so sometimes the same text will only wrap onto two lines or maybe four in an iphoneis this doable i have found this which calculates the number of lines used in a block of text but that does not really extend to do what i needif any jquery ninjas can help i would be very grateful,['jquery'] +98764,optimal way to join three tables in sqlite a simplified database of internet bookmarks i thought it would make sense to organize the tables logically like sobookmarks id title url basically external data suid title user userspecific data favorites ratings etc suid isfavorite 0 or 1 history last used use count etc suid lastused tdatetime suid is unique id integer primary keyfrom bookmarks flagged as favorite i need to select and most recently used to populate a menu at runtime as a convenienceselect bookmarkssuid title from bookmarks inner join user using suid inner join history using suid where isfavorite 1 order by lastused desc limit 15the statement works and seems sufficiently readable but is it optimal the bookmarks table is intended to hold 2050k records on average ie not your standard browser bookmark manager the app will execute 3 or 4 similar statements at startup to populate controls all fields used in the example are indexedi am teaching myself sql and came up with the above code but maybe i am overlooking a syntax or an idiom that could improve it,['sql'] +98767,ef4 mvvm expose entities in viewmodel i have played around with some different implementations of modelviewviewmodel and consistently come across a situation where i am not sure of the correct way to proceed i know one of the goals of mvvm is to decouple the view from the application logic so that the logic can be tested without the presence of a view putting the logic in a viewmodel which has no dependencies on the view solves this problem great even better if the model can be decoupled from the viewmodel in such a way that it can be mockedso my question is should the viewmodel decouple the model from the view in other words is it ok to expose entityframework entities to the view through the viewmodel for example say there is a combobox in the view where the user can choose a state for an address in the addressviewmodel should state be exposed as a real entitytype property or should it be exposed as a stateviewmodel if it should be a stateviewmodeltyped property i do not understand how the underlying model should be managed within the addressviewmodelstate setter because what is being set in the property is a stateviewmodel and not a state entity it seems to me that this could go either way but seems more consistent to never expose the model directly to the view thoughts,['.net'] +98770,using c to dynamically generate css files i have a site that gets deployed to over a dozen clients the main website has a base template and each client has a client folder that overrides the colours the problem is that there are a lot of css files so making a change that forces us to update every client takes a long time the automated build process takes care of replacing the updated filesi would like to change the css files to be usercontrols instead and those usercontrols could then inherit from another usercontrol where client specific values are storedso instead of having a formscss file and then a clientformscss file i would have a formsascx file that inherits from a usercontrol that contains the coloursex control languagec classnameforms register tagprefixcss tagnameclient srccssclientstylingascx css document body colorclientbodycolorthen the masterpage would inherit from the usercontrol instead this would make the maintenance of the client sites much easierso is this solution efficient and recommended or is there a better way to accomplish the same end result if this is possible would it also be possible to have the formsascx control output the markup as css or make the extension css and still have the ascx properties,"['c#', 'asp.net', 'css']" +98772,why use anonymous function possible duplicatehow do you use anonymous functions in php why should i use an anonymous function i mean whats the real deal using iti just do not really get this i mean you use function to make the code more clean or to use it more than once but anonymous functions just do not do neither the first nor the secondi googled them and i could not find anyone asking the same problem,['php'] +98777,how to limit the scope of a logical call context i have placed some data on the call context callcontextsetdatakeydata where data is of a type that implements ilogicalthreadaffinative the reason that it implements ilogicalthreadaffinative is that it must be shared across multiple threads in the current application however the application also makes remote calls to another service and this is where the problem comes in my ilogicalthreadaffinative implementation is not serializeable and should not be even if i were to mark it serializable the remote application does not have access to the assembly in which the type is declared so it would not be able to deserialize itso how do i share call context data within my application appdomain but not with every external application it happens to need to talk to,['.net'] +98785,how do browsers determine which exact colors to use for border inset or outset if i specify border 1px outset blue as the style for an element the browser renders two different border colors one for the top and left borders and another for the bottom and right borders li border 10px outset 0ff color f backgroundcolor 0ff width 30 p margin 1em 2em textalign center liphipligiven a single color specified for the border how does the browser determine which colors to render the border in alternately given a graphical comp a psd for example that shows an outset border with two different colors how can i choose a single border color to specify to get the closest results to the comp,['css'] +98800,is it bad practice to use hrefjavascriptfunc than onclickfunc for anchors possible duplicateshref for javascript links or javascriptvoid0why is it bad practice to use links with the javascript protocol as question says which approach is better a hrefjavascriptfunc blahaor a href onclickfunc blaha,"['javascript', 'html']" +98806,activity oncreate called when phone goes to sleep when i press the sleep button on my droid my activitys oncreate is getting called why is that happening why would the os want to call oncreate when the device is going to sleep is there any way to stop it or at least know it is because the phone was put to sleep,['android'] +98810,lazy logger message string evaluation i am using standard python logging module in my python applicationimport loggingloggingbasicconfiglevellogginginfologger logginggetloggerlogwhile true loggerdebugstupid log message joinstri for i in range20 do somethingthe issue is that although debug level is not enable that stupid log message is evaluated on each loop iteration which harms performance badlyis there any solution for thisin c we have log4cxx package that provides macros like thislog4cxx debuglogger messasage that effectively evaluates to if log4cxxdebugenabledlogger log4cxxlogloggerlog4cxxlog4cxx debug messagebut since there are no macros in python afaik if there a efficient way to do logging,['python'] +98811,c struct how to assign a null value i have a listlistint somestructfor some reason it is not allowing me to assign null values to it what do i do if i want to have no struct associated,['c#'] +98812,what is jquerys ajax default timeout value does anyone know what the default jquery ajax timeout value is,['jquery'] +98816,forcing file download in php inside joomla framework i have some php code that runs a query on a database saves the results to a csv file and then allows the user to download the file the problem is the csv file contains page html around the actual csv contenti have read all the related questions here already including this one unfortunately my code exists within joomla so even if i try to redirect to a page that contains nothing but headers joomla automatically surrounds it with its own navigation code this only happens at the time of download if i look at the csv file that is saved on the server it does not contain the htmlcan anyone help me out with a way to force a download of the actual csv file as it is on the server rather than as the browser is editing it to be i have tried using the header location like thisheaderlocation filenamebut it opens the file in the browser rather than forcing the save dialogheres my current codeset dynamic filenamefilename customerscsvopen file to write csvfp fopenfilename wget all dataquery select cfirstnameclastnamecemail as customer email aemail as address emailcphone as customer phone aphone as address phone acompanyaaddress1aaddress2acityastateazip clast signin from dbprecustomers c left join dbprecustomers addresses a on cid acustomer id order by clast signin descvotes mysql queryquery or die file file br line line pqueryp mysql errorcounter 1while row mysql fetch arrayvotes1 put header row if counter 1 headerrow array foreach row as key val headerrow key fputcsvfp headerrow put data row fputcsvfp row counterclose filefclosefpredirect to fileheadercontenttype applicationoctetstreamheadercontentthisposition attachment filenamefilenameheadercontenttransferencoding binaryreadfilefilename exiteditsfull url looks like this eimcarttaskcustomerswith the actual download link looking like this eimcarttaskcustomerssubtaskexportmore editsheres a shot of the page that the code is on the generated file still is pulling in the html for the submenu the code for the selected link export as csv is nowindexphpoptioncom eimcarttaskcustomerssubtaskexportformatrawnow here is a screenshot of the generated saved fileit shrank during the upload here but the text highlighted in yellow is the html code for the subnav list customers add new customer export as csv heres what my complete code looks like now if i could just get rid of that last bit of html it would be perfect fp fopenphpoutput w query select cfirstnameclastnamecemail as customer email aemail as address emailcphone as customer phone aphone as address phone acompany aaddress1 aaddress2acityastateazipclast signin from dbprecustomers c left join dbprecustomers addresses a on cid acustomer id order by clast signin desc votes mysql queryquery or die file file br line line pqueryp mysql error counter 1 redirect to file headercontenttype applicationoctetstream headercontentthisposition attachment filenamecustomerscsv headercontenttransferencoding binary while row mysql fetch arrayvotes1 put header row if counter 1 headerrow array foreach row as key val headerrow key fputcsvfp headerrow put data row fputcsvfp row counter close file fclosefpupdate for bjornheres the code i think that worked for me use the raw param in the link that calls the actionindexphpoptioncom eimcarttaskcustomerssubtaskexportformatrawbecause this was procedural our link was in a file called customersphp which looks like thisswitch rsubtask case add case edit if the form is submitted then go to validation includesubnavphp if rcustformsubmitted true includevalidatephp else includeshowformphp break case delete includesubnavphp includeprocessphp break case resetpass includesubnavphp includeresetpassword break case export includeexport csvphp break default includesubnavphp includelistphp breakso when a user clicked on the link above the export csvphp file is automatically included that file contains all the actual codeheadercontenttype applicationoctetstreamheadercontentthisposition attachment filenamecustomerscsvheadercontenttransferencoding binaryfp fopenphpoutput wget all dataquery select cfirstnameclastnamecemail as customer email aemail as address emailcphone as customer phone aphone as address phone acompanyaaddress1aaddress2acityastateazip clast signin from dbprecustomers c left join dbprecustomers addresses a on cid acustomer id order by clast signin descvotes mysql queryquery or die file file br line line pqueryp mysql errorcounter 1while row mysql fetch arrayvotes1 put header row if counter 1 headerrow array foreach row as key val headerrow key fputcsvfp headerrow put data row fputcsvfp row counterclose filefclosefp,['php'] +98817,php unserialize error at offset works on some servers not others i have code that works on a handful of servers but not others which is coming up with serialised data i call a page like thishttpdomainindexphpsalesdrilldownsparamsa12s13selectiontypes8facilitys8datetypes5dailys10dateoptions9drilldowns6metrics13bookingamounts9companyfks211s10facilityfks0s7classfks0s15customdatestarts4nulls7newdates1020101101s10metricnames10bookings20s16currentdateranges1011012010s23currentmetricnavigations8deldeltegetexcel0this is the code i am usingprotected function getrequestvariables ifisset requestparams var dump requestparams echo lengthstrlen requestparams vars unserialize requestparams var dumpvars else vars request unset saved drilldown options thiscisessionsvar setpostvars null this is a var dump outputstring447 a12s13selectiontypes8facilitys8datetypes5dailys10dateoptions9drilldowns6metrics13bookingamounts9companyfks211s10facilityfks0s7classfks0s15customdatestarts4nulls7newdates1020101101s10metricnames10bookings s16currentdateranges1011012010s23currentmetricnavigations8deldeltewhen that gets processed i get the following errora php error was encountered severity notice message unserialize functionunserialize error at offset 6 of 447 bytes filename pluginsdrilldownsphp line number 93i am trying this on 5213 works on some linux some os x not others have checked phpini charset i think i cannot figure it out for the life of me i have tried things as simple as string18 a1s3sam length18and it still errors any clue as to why,['php'] +98837,can someone please explain class self to me i am jumping into rails programming for the first time and while looking at the code for some libraries i have downloaded i occasionally notice the code class self def func stuff endendi have tried searching the web for an explanation but the gets stripped from most useful search engines so it ends up just searching for class self which is not very useful any insight would be appreciated,"['ruby-on-rails', 'ruby']" +98843,how to call an indexer on a c class from powershell i am having trouble figuring out how to get powershell to call an indexer on my class the class looks something like this vastly simplifiedpublic interface iintcounters int thisstring countername get set public class myclass iintcounters public iintcounters counters get return this int iintcountersthisstring countername get return something if i new up this class i cannot just use the bracket operator on it i get an unable to index error i also tried using get item which is what reflector shows me the indexer ultimately becomes in the assembly but that gets me a does not contain a method named get item errorupdate this appears specific to my use of explicit interfaces so my new question is is there a way to get powershell to see the indexer without switching away from explicit interfaces i really do not want to modify this assembly if possible,['c#'] +98844,how get iframe body after load i need obtain the iframe body after iframe load,['jquery'] +98848,iphone app crashes only in release mode on 3g i have an app i am writing that crashes when i call addsubview on a uiscrollview with exc bad access it only does this on iphone 3g in release mode and only on the device i works fine in all these other configurationsiphone 3g debug modeiphone 3gs debug and release modeiphone 4 debug and release modesimulator allfurthermore there is no rational reason why this should be happening my object is not released by any of my code,['iphone'] +98862,how to detect a script load of a file url fails in firefox i want to detect if a script tag that was dynamically created and added to the dom fails to load the onerror event works except with file urls in firefoxunfortunately none of the techniques described here except timeouts which are unacceptable in my case seem to work in firefox if the src of the script tag is a file url or relative url and the page was loaded via a file urltest casevar script documentcreateelementscriptscriptsetattributetype textjavascriptscriptsetattributesrc doesnotexistjsscriptonerror function alertloading failed documentgetelementsbytagnamehead0appendchildscriptload this in an html page with a file url the onerror event would not execute in firefox load from a webserver or on safari or chrome and it willthis seems like a bug to me is there any known way around it,['javascript'] +98863,error when defining inner classes in a test class in junit i am having some problems when defining inner classes in a test class inherited from testcase for junit 3 scenario is like followingfoojavapublic class foo public void method footestjavapublic class footest extends testcase public class bar extends foo public void method public void testmethod now if i run this from eclipse the tests run ok but if i try to run from an ant task it fails junit junitframeworkassertionfailederror class foobar has no public constructor testcasestring name or testcase bar is not a test class it is just a subclass of foo overriding some method that i do not need to do the real stuff when testingi am quite lost at the moment and i do not know how to approach this problem is the only way to create the subclasses as standalone,['java'] +98874,removing underline from specific anchor tag why does following anchor tag has text underlineda class pagerlink href testapagerlink backgroundcolor e4f5f8 border1px solid c0deed textdecorationnone,['css'] +98882,error installing rails on ubuntu 1004 i am trying to install rails on ubuntu 1004 so far i have executed these commandsaptget install buildessential libapache2modpassenger apache2 rubygems ruby18dev libopensslrubygem install fastthreadgem install railsfastthread installed easily however trying to install rails results inerror error installing rails bundler requires rubygems version 136so i tried gem v which returned 135how do i upgrade rubygems aptget would not install above 135 and gem update system results inerror while executing gem runtimeerror gem update system is thisabled on debian rubygems can be updated using the official debian repositories by aptitude or aptgetso right now i simply cannot install rails because i need a newer version of rubygems and ubuntu would not let me upgrade my current version of rubygemsas a side note i tried installed rails via aptget install rails which seemed to work but i do not see rails as a gem when i type gem list whats the deal with thatanother note the result of gem list is local gems abstract 100actionmailer 301 300actionpack 301 300activemodel 301 300activerecord 301 300activeresource 301 300activesupport 301 300arel 201 101builder 212erubis 266fastthread 107i18n 042mail 229mimetypes 116mysql 281polyglot 031rack 121rackmount 0613racktest 056railties 301 300rake 087rubygemsupdate 137thor 0144treetop 148tzinfo 0323i assume installing rails via aptget installed those gems prior to installing rails through aptget i only had mysql and fastthread,['ruby-on-rails'] +98884,transition from black and white to color i have an icon that is in black and white and i want the icon to transition to the color icon as a crossfade during the hover event how can i do this in jquery stumpedthanks,['jquery'] +98889,efficient circular buffer i want to create an efficient circular buffer in python with the goal of taking averages of the integer values in the bufferis this an efficient way to use a list to collect valuesdef add to buffer self num selfmylistpop 0 selfmylistappend num what would be more efficient and why,['python'] +98895,closing an activity on oncreate i am opening an activity using thisstartactivitynew intentparentthis childclassand on the child i have this code on the oncreate function the if contains more than just true of coursepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate if true alertdialogbuilder builder new alertdialogbuilderthis buildersetpositivebuttonok null buildersettitleerror buildersetmessageconnection error please try later show finishactivity0 return why is the activity not closing i get the alert box but then i have to tap the back button to go back,['android'] +98898,preventing a webpage from dragging on an ipad in the code i am currently working on a webpage that will be viewed on an ipad it uses the jqueryui libraries to thisplay a slider bar however when a user tries to drag the sliderbars instead the entire page drags does anyone know if there is any sort of override that can be specified in the jquery or html to prevent the browser from dragging the page on an ipad upon touch drag event,"['javascript', 'jquery']" +98904,rails radio buttons for collection sets i have the following which outputs a select box flabel request type id br requesttypes requesttypeall fcollection select request type id requesttypes id title prompt true what is the rails method to instead output radio buttons,['ruby-on-rails'] +98907,why cannot i read fstreams binary data with operator if i do something like the followingifstream filefileopensomefile iosbinaryunsigned int datafile datamy stream will always flag the fail bit and the data will remain unitialized however if i read a char or unsigned char instead the stream is fine perror is telling me result too large the only thing i saw on google was a suggestion saying that operator should not be used for binary data prefer read but i find the operator cleaner and easier to use and it does not require casting everything can someone explain the issue,['c++'] +98908,how to keep track of row index when jtable has been sorted by the user i have a jtable which has 1st row blank now when i sort the table based on a column by clicking on that column then the blank row goes at the bottom if i insert something in the blank row and do the sorting then the row is placed accordingly how do i keep track of its row index even when it is sorted i need to access that row but if user does the sorting then i loose the row index as it is no more the 1st row,['java'] +98916,difference between a roworiented and columnoriented databases in dealing information retrieval recently i started working on hbase one of the columnoriented databases while going through the source code one question keeps popping in my head thought of asking thismy question is how exactly a roworiented database deals with information retrieval say a select query and how different is that when comes to columnoriented databaseand how different these databases store data in the underlying flat files at the end of day every database uses filesplease do correct me in case i went wrong in any part of this questionregardskrishna,['java'] +98938,mask an edittext with phone number format nan like in phonenumberutils i want to make user inputted phone number in an edittext to dynamically change format every time the user inputs a number that is when user inputs up to 4 digits like 7144 the edittext shows 7144i would like the edittext to be dynamically updated to format whenever the user inputs a digit how can this be done also i am handling more than one edittexts,['android'] +98951,how do i use for each to output to cout is there a more straightforward way to do thisfor eachv numbersbegin v numbersend bind1stoperator coutwithout an explicit for loop if possibleedithow to do this for stdcin with a stdvector if possible how to read n elements only,['c++'] +98952,whats the fastest way to compare two arrays for equality i have two arrays of objects which are likely to have the same values but in a different order eg cat dog mouse pangolin dog pangolin cat mouse i wish to treat these two arrays as equal whats the fastest way to test this,['c#'] +98957,increment field value on replace i have done this successfully with an update statement before but not a replacei am saving favourite items in a mysql table when a user has checked outtable favs isuser intitem intcount int default 0the sql i am trying is replace into favs useritemcount values 13 count 1although it does not throw any errors it does not seem to increment the value eitheris this possible thank you,['mysql'] +98958,how to use comparison and if not in python in one piece of my program i doubt if i use the comparison correctly i want to make sure that u0 you u0step before do something if not u0 u and u u0step u0 u0 step change the condition until it is satisfiedelse do something condition is satisfied,['python'] +98992,html 5 footer tag be always at bottom i am developing a site in html 5 i wrap all my footer content in footer tag like code below doctype htmlhtmlheadheadbodyheaderh1talking dogsh1bphumans are not the only talkerspbheaderarticlepever encountered a talking dog i haveppit all happened one day as i was walking down the streetparticlefootera 2009 woofer dog corporationfooterbodyhtmlhowever above code is not the actual site code as i can not share can someone please suggest me the best way to do this in html 5 so that it work on all major browsers like ie678 firefox safari crome opera,['html'] +99000,how do i choose between semaphore and semaphoreslim their public interfaces appear similar the documentation states that the semaphoreslim is a lightweight alternative and does not use windows kernel semaphores this resource states that the semaphoreslim is much faster in what situations does the semaphoreslim make more sense over the semaphore and vice versa,['c#'] +99025,adl with typedefs from another namespace i have something like thisinclude iostreamnamespace n typedef stdpairint double mypair stdostream operator stdostream o mypair const mypair int main nmypair pr stdcout prthis naturally does not work because adl would not find operator because namespace n is not associated with mypair unfortunately afaik one may not add to namespace std so if i chose to define operator in std that would be kinda illegal so what to do in such situations i do not want to explicitly qualify operator nor do i wish to write using namespace n so questions arehow to refactor the codewhy wouldnt adl associate namespaces of typedefs serious reasons it would be nice eg in this case thanks,['c++'] +99031,best way to share portions of a maven pomxml across unrelated projects our company has defined a number of best practices with regard to maven poms for example specifying utf8 for resource processing which folders to do filtering on handling unit tests vs integration tests and compiler settingsright now these best practices are documented on our company wiki but when the list of best practices changes these changes are rarely reflected in the project poms until there is a problem human nature being what it is and allis there some way we can provideenforce these settings and properties via maven it is almost like giving every project a parent pomxml but i do not want and cannot have all these projects reference the same parent pomwe need an approach that will work on developers machines as well as our hudson ci server,['java'] +99048,localizing html submit button label in wicket how do i put a localized message on the face of a submit button i am using wicket and normally to use a localized message i would use something like wicketmessage keymessagekeyi have an html button defined as input typesubmit valuelogini want to localizeinternationalize the value loginany ideas,['html'] +99055,jquery validator dynamic parameters is there a way to pass dynamic parameters into a custom jquery validate method specifically i was looking for a way to compare 2 controls and would like to pass one to the others validate method for comparisonhere is what i currently have add method validatoraddmethodlowerint functionvalue element params alertinside method if isnanparseintparams return true else return parseintvalue parseintparams validatorformatplease enter a number smaller than 0 set validation form1validate rules lowint required true integer true lowerint 8 i would like to pass a dynamic value here if i run it as above it works as it should if i change the 8 passed in to lowerint to highintval it seems to set the value for the lowerint function only once and never update it i realize that i can get the value inside of the method by calling highintval but i would like to pass the value instead if at all possible,['jquery'] +99060,how to test 500html in rails development env i want to test the 500 error pages in my rails app using the development environmenti already tried this in configenvironmentsdevelopmentrb configaction controllerconsider all requests local falsebut this does not seem to have any effect,['ruby-on-rails'] +99063,can we have multiline comments in a java properties file in a java properties file we can do single line comments with is there any way by which we can do multiline comments,['java'] +99069,warning ignoring platform ds store not a folder this warning pops up when i bring up the avd manager in eclipse 35 on a mac with osx 1064 any ideas of what is causing this,['android'] +99074,when to use getset methods in java i want to know when to use get and set methodsgetnamesetname in my class and when simple classvariablename instead classvariablegetnamehere is example of class using set and get methodspublic class classexampe string name string course public string getname return name public void setname string studentname name studentname public string getcourse return course public void setcourse string studentcourse course studentcourse thanks,['java'] +99092,raphael canvasbackground onclick event i have been working with raphael to create drag and drop shapes on a canvas i do this using the drag function supplied in the raphael framework along with my event functions i have no issues doing thisi also have a function that creates a new shape ondblclick the problem is i can only attach the event to a shapes or other elements i createadding events to a shape works like so r raphaelcanvas 100 100 rrect100 100 25 50attrfill fillcolordblclickmydblclickusing the same principle on the canvas does not work r raphaelcanvas 100 100 rdblclickmydblclickdoes anybody know a way to attach click events to the canvas ie i can click anywhere in the div excluding shapes and the event will be triggeredthanks,"['javascript', 'jquery']" +99099,multiple index variables in php foreach loop is it possible to have a foreach loop in php with multiple index variables akin to the following which does not use correct syntaxforeach courses as course sections as sectionif not is there a good way to achieve the same result,['php'] +99107,why cant i make the background of a png transparent after rotating it with php i tried literally all day yesterday trying to figure this out i rotate an image via imagerotate i get a black background where the image is not covering anymore i have tried everything i cant think of to make that background transparenthere is my current code function rotatedegrees image thisimage imagealphablendingimage false color imagecolorallocatealphaimage 0 0 0 127 rotate imagerotateimage degrees color imagecolortransparentrotate color imagesavealphaimage true thisimage rotate i am really starting to get ticked off can someone show me some working code pleasecould it be something wrong with my wamp server and dreamweaver because i even tried this image alpha and it still puts out either a black or white background,['php'] +99113,how can i get checkstyle to skip equals and hashcode methods generated by eclipse our project contains several classes that we have equals and hashcode methods generated by eclipse right click source generate hashcode and equals exampleoverridepublic boolean equalsobject obj if this obj return true if obj null return false if getclass objgetclass return false final myto other myto obj if num othernum return false if name null if othername null return false else if nameequalsothername return false if table null if othertable null return false else if tableequalsothertable return false return truethese methods that work well for our application but unfortunately do not pass our cyclomatic complexity checks with checkstyle since these methods are autogenerated we are not concerned with their complexity we could suppress the entire class from checkstyle but we would prefer to be able to exclude just these two methodsdoes anyone know how to create a custom rule in checkstyle that will allow us to exclude generated equals and hashcode methods in any way without excluding the entire class,['java'] +99119,aspnet forms authentication when using iphone uiwebview i am writing a aspnet mvc 2 application that uses forms authentication and currently i am having a problem with our iphone application in regards to the authenticationlogin over the web we have developed a simple iphone app that uses the the uiwebview control at this stage all the app does is navigate to our aspnet website simple right the problem is that the user cannot get past the login page the repro steps areopen iphone appthe app navigates to the home pagethe user is not authenticated so they are redirected to the login screenpagethe user enters the correct user name and password clicks submiton the server side the user is authenticated and a cookie is generated and sent to the client using formsauthenticationgetauthcookiethe server sends are redirect to send the user to the correct home pagebut the user is then redirected back to the login screeni have done some extensive debugging on this and what i do know is the cookie is being sent to the client and the client is storing the cookie verified this in the iphone debugger and also by using javsascript to thisplay cookie data on the page the cookie is being sent back to the server verified this in the visual studio debugger it is the correct cookie it is the same one that was set the property useridentityisauthenticated returns false for some reason even though the auth cookie is contained in the request object i have verified that the iphone app is setup to accept cookies and they are on the clienthere is the funny thing it works fine if you open the safari browser on the iphone and go to our site directly it has the same behaviour on the ipad too in that it does not get past the login screen this repros on the emulators and on devicesthis same web site has been tested with ie 78 safari for windows blackberry iemobile 65 phone 7 and it works find the only circumstance that it does not work on is the uiwebview in the iphone app,['asp.net'] +99128,embedding resources in executable using gcc i am looking for a way to easily embed any external binary data in a cc application compiled by gcca good example of what i would like to do is handling shader code i can just keep it in source files like const char shader source here but that is extremely impracticali would like the compiler to do it for me upon compilation linking stage read file foobar and link its content to my program so that i would be able to access the contents as binary data from the codecould be useful for small applications which i would like to thistribute as a single exe filedoes gcc support something like this,"['c++', 'c']" +99151,using devise invitable for adding users to a group in ruby on rails i have a groups resource within my app that users can join a group has and belongs to many users and vice versa the devise invitable plugin allows an existing user on my app to email an invitation to another poetntial user to register on the site but i want some extra functionality i want a user to be able to invite someone to a particular group so that as soon as they accept that invitation in the email they can see a link to join that grouphas anyone used devise invitable to do something like this whats the best way to go about adding this extra functionality it seems i would need to include some sort of of group token identifying the group in the invite email then pass it back in the url that the user clicks to accept the inviteshould i be overriding the invitations controller methods or is there another plugin that serves the purpose better,['ruby-on-rails'] +99158,check if user is root in c how can i verify if the user is root,['c'] +99162,is it a problem when an iad may be obscured i added the adbannerview to a view and when i load the app i get the following messageadbannerview warning a banner view 0x7a023c0 has an ad but may be obscured this message is only printed once per banner viewas far as i can see the entire banner is visible on the screen is this really a problem or is it only a warning that i can ignore,['iphone'] +99197,bootstrapping a web server in scala the following is possible using python aptget install python easy install flask cat hellopyfrom flask import flaskapp flask name approutedef hello return hello worldif name main apprun python hellopy4 commands and 7 lines of code to get a web server running is very impressive indeedwhats the scala equivalent,['python'] +99198,trying to get simplest possible example of performselector withobject working heres my method signature for targetmethodvoidtargetmethod idargthis worksmyobject targetmethodcalled the regular waythis does notmyobject performselectorselectortargetmethod withobjectcalled using selectorit results in the following errorselectortest targetmethod unrecognized selector sent to instance 0x4e075d0what am i doing wrong,['objective-c'] +99212,how can i improve this phpmysql news feed let me start right off the bat by saying that i know this is not the best solution i know it is kludgy and a hack of a feature but that is why i am herethis questionwork builds off some thiscussion on quora with andrew bosworth creator of facebooks news feedi am building a news feed of sorts it is built solely in php and mysqlthe mysqlthe relational model for the feed is composed of two tables one table functions as an activity log in fact it is named activity log the other table is newsfeed these tables are nearly identicalthe schema for the log is activity loguid int11 activity enum activity id int11 title text date timestampand the schema for the feed is newsfeeduid int11 poster uid int11 activity enum activity id int11 title text date timestampany time a user does something relevant to the news feed for example asking a question it will get logged to the activity log immediatelygenerating the news feedsthen every x minutes 5 minutes at the moment will change to 1530 minutes later i run a cron job that executes the script below this script loops through all of the users in the database finds all the activities for all of that users friends and then writes those activities to the news feedat the moment the sql that culls the activity called in activityloggetusersactivity has a limit 100 imposed for performance reasons not that i know what i am talking aboutphpuser new useractivitylog new activitylogfriend new friendnewsfeed new newsfeed get all the usersusersarray usergetallusersforeachusersarray as userarray uid userarrayuid get the users friends friendsjson friendgetfriendsuid friendsarray json decodefriendsjson true get the activity of each friend foreachfriendsarray as friendarray array activityloggetusersactivityfriendarrayfid2 only write if the user has activity ifemptyarray add each piece of activity to the news feed foreacharray as news newsfeedaddnewsuid friendarrayfid2 newsactivity newsactivity id newstitle newstime thisplaying the news feedsin the client code when fetching the users news feed i do something likefeedarray newsfeedgetusersfeedwithlimitandoffsetuid 25 0foreachfeedarray as feeditem use a switch to determine the activity type here and thisplay based on type eg user name asked a question where a question feeditemtitleimproving the news feednow forgive my limited understanding of the best practices for developing a news feed but i understand the approach i am using to be a limited version of whats called fanout on write limited in the sense that i am running a cron job as an intermediate step instead of writing to the users news feeds directly but this is very different from a pull model in the sense that the users news feed is not compiled on load but rather on a regular basisthis is a large question that probably deserves a large amount of back and forth but i think it can serve as a touchstone for many important conversations that new developers like myself need to have i am just trying to figure out what i am doing wrong how i can improve or how i should maybe even start from scratch and try a different approachone other thing that bugs me about this model is that it works based on recency rather than relevancy if anyone can suggest how this can be improved to work relevancy in i would be all ears i am using directed edges api for generating recommendations but it seems that for something like a news feed recommenders would not work since nothings been favorited previously,"['php', 'mysql']" +99213,what php ides support the facebook xhp extension the facebook xhp extension introduces what are basically xml literals well xhtml literals to the php language allowing syntax like the followingfoo divhellodivfoo div hello divfoo helloecho divfoodiv outputs divhellodivfoo helloecho divsubstrfoo 0 2div outputs divhedivthe biggest problem is that i cannot find an ide that supports this syntax without flagging it as a syntax errori am told that facebook generally uses vim or emacs for development but i am hoping for a more fullblown ide that supports this syntax at present netbeans 69 70 m2 and zend studio 8 all flag this syntax as an error even though it executes fine on php with the xhp extension enabledsuggestions for an editor or plugin to an editor that allows this to work without syntax errorsinfo about xhp,['php'] +99216,how do i play an mp3 in the resraw folder of my android app i have a small 200kb mp3 in the resraw folder of my android app i am trying to run it in an emulator from eclipse it is recognized as a resource in the r file but when i try to preparestart my activity crashes was there something else i needed to change perhaps in the manifest mediaplayer mplayer mediaplayercreatefakecallscreenthis rrawmysoundfiletry mplayerpreparemplayerstart catch ioexception e handle this later,['android'] +99218,dom exception when assigning html entities to innerhtml on this page running the following code in javascript console will throw an exceptionvar div documentcreateelementdiv divinnerhtml raquochrome 8055228 mac error invalid state err dom exception 11 firebug in firefox 3612 mac ns error dom syntax err an invalid or illegal string was specified safari 502 mac error no modification allowed err dom exception 7opera works finebut it works fine in all other pages i tried my questions are whats special about the page and why does chrome and firefox throw an exceptionwriting the character directly without using entity works finevar div documentcreateelementdiv divinnerhtml ausing other entities also works egvar div documentcreateelementdiv divinnerhtml lt,"['javascript', 'html']" +99224,how to find the calling convention of a third party dll could any one explain me how to get to know the calling convention of a dll without getting and processing method names lets say our application is loading a third party dll and in order to handle it is there any effective ways to get to know the calling convention of a dll stdcall cdecl fastcall,['c++'] +99246,python vs php speed i want to solve a problem from project euler btw problem 25 and i found a solution in pythonfibonacci 1old1 0old2 1limit 10i 1while lenstrfibonacci limit fibonacci old1 old2 old1 old2 old2 fibonacci i i 1printiit took 15 seconds to calculatei implemented the same in php this is the codefibonacci 1old1 0old2 1limit 10i 1while strlenstringfibonacci limit fibonacci old1 old2 old1 old2 old2 fibonacci i i 1printiand it took more than 30 minutes and still calculatingi know that python is considered faster than php but still it should not be so big a difference how to improve my php code to get the results faster if there is a way to do it editi edit this post based on comments below so first my solution was not going to workone solution can be instead of old while to put this onewhile strlennumber formatfibonacci 0 limit but again is a big speed issueso the final solution is using bcmathfibonacci 1old1 0old2 1limit 10i 1while strlenfibonacci limit fibonacci bcaddold1 old2 old1 old2 old2 fibonacci i i 1echo fibonacci br printiso you can get the results at the same speed as python in php,"['php', 'python']" +99249,using zlib under windows mingw i cannot seem to get zlib to do anything on mingw under windowsi downloaded zlib betamingwzlibzlib1231mingw32 and put the header and lib files in the right placesimple code likeinclude stdlibhinclude stdiohinclude zlibhint mainint argc char argv long a char buffer1024 a 1024 compressbufferatesting7 return 0compiledgcc testc lzlib wall o testexecompiles finehowever the exe crashes at the compress functionany ideas,['c'] +99254,unused using statements i may already know the answer to this question but i thought it was worth asking anyway if i have a load of using statements within my code file that are not being used does that have any sort of detrimental performance impact how does the compiler deal with them at compilerun timethanks,['c#'] +99257,design patterns used in zend framework i am preparing talk about general architecture of zend framework and wanted to summarize design patterns used in it i believe it will be beneficial both for those knowing zf and learning dps and for those knowing dps and learning zf in a former case one would be able to see realworld application of patterns and get a better comprehension of framework in the secondeven brief answers in a form zend contoller front singleton are good enough if a little elaboration is provided for some notsoobvious cases it will be even betteri am primary interested in gof patterns as they seem to be the starting point of any dpadventureupd not directly related but for those who know java there is extremely complete answer for gofs dp examples found in java core,['php'] +99270,qtreeview with drag and drop support in pyqt in pyqt 4 i would like to create a qtreeview with possibility to reorganize its structure with drag and drop manipulationi have implemented my own modelqabstractitemmodel for qtreeview so my qtreeview properly thisplays the datanow i would like to add drag and drop support for trees nodes to be able to move a node inside the tree from one parent to another one dragcopy and so on but i cannot find any complete tutorial how to achieve this i have found few tutorials and hints for qtreewidget but not for qtreeview with custom modelcan someone point me where to lookthank you,['python'] +99286,how to save graphics object as image in c i have panel and various controls on it i would like to save an image of this panel into a file how can i do this ineed to do something like screenshot but i need just image of certain panel in my application and i want to do this on a button click in my appbest regards primoz editi also draw on this panel using this code graphics g charttemperaturecreategraphics gdrawlinep prevpoint elocation prevpoint elocationbut then i do not get this into image why and how to fix this edit 2namespace grafi public partial class form1 form bool isdrawing false point prevpoint public form1 initializecomponent private void charttemperature mousedownobject sender mouseeventargs e isdrawing true prevpoint elocation private void charttemperature mousemoveobject sender mouseeventargs e pen p new pencolorred 2 if isdrawing graphics g charttemperaturecreategraphics gdrawlinep prevpoint elocation prevpoint elocation numofmouseevents 0 pthispose private void charttemperature mouseupobject sender mouseeventargs e isdrawing false this is my drawing code to draw a custom line onto a chart can you please help me to do it proper way,['c#'] +99299,substring error is not a function i do not understand why i get an error message using the substring method to declare a variablei want to use the first part of the url in a comparisonsite this is the part that is going wrongvar currentlocation documentlocationmuzloc currentlocationsubstring045prodloc currentlocationsubstring048 techloc currentlocationsubstring047 the errorcurrentlocationsubstring is not a functionbut this part of the code is finevar url thisattrhrefsubstring2 mainall of the codejqueryfunction var siteurl http toplocationhosttostring wordpress declareren van url van de website url declareren van een url welke dan ook currentlocation muzloc prodloc techloc alinks ahref siteurl declareren van alle menulinks het teken betekent begint met otherlinks ahref siteurl wpcontent sitelinks alinksnototherlinks maindiv content hash windowlocationhash muziekurl pf productieurl pf techniekurl pf if hash hash wordpress hashsubstring1 substring methode haalt karakters van je string af in dit geval de vanwege de offset1 url hash maindivloadurl function pageload var alinks ahref siteurl otherlinks ahref siteurl wpcontent sitelinks alinksnototherlinks sitelinkseachfunction thisattrhref thispathnamesubstring10 clickfunction var url thisattrhrefsubstring2 main maindivloadurl function var currentlocation documentlocation muzloc currentlocationsubstring045 prodloc currentlocationsubstring048 techloc currentlocationsubstring047 if muzloc muziekurl bodyanimate backgroundcolor 151c07 500 nieuwsanimate borderbottomcolor 99cc33 500 stripe transaddheaderanimate backgroundcolor 99cc33 500 tabtekst 3stopanimate backgroundcolor b8860b 500 tab 3addagoldstopanimate color b8860b 500 tabtekst 4stopanimate backgroundcolor 765aad 500 tab 4addapurplestopanimate color 765aad 500 else if prodloc productieurl bodyanimate backgroundcolor 251b02 500 nieuwsanimate borderbottomcolor ffcc33 500 stripe transaddheaderanimate backgroundcolor ffcc33 500 tabtekst 2stopanimate backgroundcolor 6b8e23 500 tab 2addagreenstopanimate color 6b8e23 500 tabtekst 4stopanimate backgroundcolor 765aad 500 tab 4addapurplestopanimate color 765aad 500 else if techloc techniekurl bodyanimate backgroundcolor 181223 500 nieuwsanimate borderbottomcolor b39be4 500 stripe transaddheaderanimate backgroundcolor b39be4 500 tabtekst 2stopanimate backgroundcolor 6b8e23 500 tab 2addagreenstopanimate color 6b8e23 500 tabtekst 3stopanimate backgroundcolor b8860b 500 tab 3addagoldstopanimate color b8860b 500 else bodyanimate backgroundcolor 202020 500 nieuwsanimate borderbottomcolor f 500 stripe transaddheaderanimate backgroundcolor f 500 tabtekst 2stopanimate backgroundcolor 6b8e23 500 tab 2addagreenstopanimate color 6b8e23 500 tabtekst 3stopanimate backgroundcolor b8860b 500 tab 3addagoldstopanimate color b8860b 500 tabtekst 4stopanimate backgroundcolor 765aad 500 tab 4addapurplestopanimate color 765aad 500 pageload pageload end document ready function,"['javascript', 'jquery']" +99307,how to isolate different javascript libraries on the same page suppose we need to embed a widget in third party page this widget might use jquery for instance so widget carries a jquery library with itselfsuppose third party page also uses jquery but a different versionhow to prevent clash between them when embedding widgets jquerynoconflict is not an option because it is required to call this method for the first jquery library which is loaded in the page and this means that third party website should call it the idea is that third party site should not amend or do anything aside putting tag with a src to the widget in order to use italso this is not the problem with jquery in particular google closure library even compiled might be taken as an examplewhat solutions are exist to isolate different javascript libraries aside from obvious iframemaybe loading javascript as string and then eval by using functioncode to eval not the evalcode to eval it in anonymous function might do the trick,['javascript'] +99308,geographic midpoint between two coordinates i have been using the moveabletype website to aid me in some geocoordinate calcuations and it is been very useful however i have a bug in my calculation of the midpoint between two coordinates my result is close to the expected but not close enoughposa 4764570362 12214073746posb 4764316917 12214032175expected result taken from the movable type calculator 47a38a240a3n 122a08a226a3w 4764 122140556 my result 496054801645915 122140529595759here is my codeprivate geocoordinate midpointgeocoordinate posa geocoordinate posb geocoordinate midpoint new geocoordinate double dlon degreestoradiansposblongitude posalongitude double bx mathcosdegreestoradiansposblatitude mathcosdlon double by mathcosdegreestoradiansposblatitude mathsindlon midpointlatitude radianstodegreesmathatan2mathsindegreestoradiansposalatitude mathsindegreestoradiansposblatitude mathsqrtmathcosdegreestoradiansposalatitude bx mathcosdegreestoradiansposalatitude bx by by midpointlongitude posalongitude radianstodegreesmathatan2by mathcosdegreestoradiansposalatitude bx return midpointi have got a couple of private methods to do the conversion between degrees and radians and back egprivate double degreetoradiandouble angle return mathpi angle 1800i cannot work out why my results are off by a couple of degrees on the lat value any ideasthanks,['c#'] +99315,use jquery to auto select text inside a span tag when clicked i have a div which contains a series of span tags each containing a string of text i would like to attach a jquery click event to all of the spans so that when the text inside any span is clicked the entire line of text dom innertext object will be auto selected to facilitate the dragdrop or copypaste of the text stringfor example my content isdiv idmyspans spannbspthis is my textnbspspan spannbspthis is my textnbspspandivif the cursor is clicked on any text inside a span i want to select the text within that span so that it can be dragdropped without the span tags just the innertext of the span as a copydoes jquery have an easy means to do thisedit a more detailed explanation of what i am trying to accomplishwithout aid of script in order to copy a block of text the user has to manually drag select a selection rectangle across the text block the text then becomes selected signaling that a click drag event will pick up all of the selected text so i am trying to create script that allows a single click on the text to automatically select the text for the user so they do not have to manually do it themselves,['jquery'] +99316,what is dynamic sql i just asked an sql related question and the first answer was this is a situation where dynamic sql is the way to go as i had never heard of dynamic sql before i immediately searched this site and the web for what it was wikipedia has no article with this title the first google results all point to user forums where people ask more or less related questions however i did not find a clear definition of what a dynamic sql is is it something vendor specific i work with mysql and i did not find a reference in the mysql handbook only questions mostly unanswered in the mysql user forumson the other hand i found many references to stored procedures i have a slightly better grasp of what stored procedures are although i have never used any how are the two concepts related are they the same thing or does one uses the other basically what is needed is a simple introduction to dynamic sql for someone who is new to the conceptps if you feel like it you may have a go at answering my previous question that prompted this one sql how can we make a table1 join table2 on a table given in a field in table1,"['mysql', 'sql']" +99348,python csv error line contains null byte i am working with some csv files with the following codereader csvreaderopenfilepath rutry for row in reader print row read successfully rowexcept csverror e sysexitfile s line d s filename readerline num eand one file is throwing this error file mycsv line 1 line contains null bytewhat can i do google seems to suggest that it may be an excel file that is been saved as a csv improperly is there any way i can get round this problem in python update following johnmachins comment below i tried adding these lines to my script print repropenfilepath rbread200 dump 1st 200 bytes of filedata openfilepath rbreadprint datafindx00print datacountx00and this is the output i got xd0xcfx11xe0xa1xb1x1axe1x00x00x00x00x00x00x00x00 snip813834so the file does indeed contain nul bytes,['python'] +99408,jquery fireing public method of one plugin after changes from second plugin hey there need some advice again i am working on a project with a filterable portfolio based on this plugin link wgethificomblogajqueryplugintocreateaninteractivefilterableportfoliolikeoursthe portfolio items are shown in a horizontal slider which is adding scroll areas hot spots on the left and right side of the browser windowhere comes my problemthe width of the slider is calculated in the plugin smoothdivscroller wsmoothdivscrollcom but when i change the content of the slider via the filter navigation the total width of the slider changes but the smoothdivscroller plugin is not noticing iti set up a simplified example in jsfiddle for you and you can experience the whole problem herekuemmelschnurdeprojekte when all projects are shown alle and you scroll to the right and then switch to the category lehrprojekte you would not see any projects because they are on the far left side and the total width of the container is not recalculatedin order to fix this i have three ideas where i need some serious help1 the smoothdivscroll plug in offers a public method to recalculate the width of the container like makemescrollablesmoothdivscrollrecalculatescrollableareawhich i need to fire every time after portfoliolist a is clicked and i need to combine this with the method where the slider automatically switches to the first element of the current content makemescrollablesmoothdivscrollmovetoelement first2 my second idea cause i do not know if or how 1 works is to check if the url changes and then fire the recalculation the filter uses a hash to address the content so i thought i could read out the url and every time the part directly after the hash changes i could fire the method3 i could bind the filterable plugin to the smoothdivscroll plugin with something like beware of completely wrong code portfoliolistfilterable portfoliofilter aclickfunction makemescrollablesmoothdivscrollmovetoelement firstrecalculatescrollableareaso what do you think again the jsfiddle link jsfiddlenettobiasmayqudtfthankstobips i would have setup the links properly but i need 1 more reputation point to post more then 1 link,['jquery'] +99415,convert an entire string into an integer in javascript i recently ran into a piece of code very much like this onevar nhours parseinttxthoursif isnannhours do somethingelse do something else with the valuethe developer who wrote this code was under the impression that nhours would either be an integer that exactly matched txthours or nan there are several things wrong with this assumptionfirst the developer left of the radix argument which means input of 09 would result in a value of 0 instead of 9 this issue can be resolved by adding the radix in like sovar nhours parseinttxthours10if isnannhours do somethingelse do something else with the valuenext input of 15 will result in a value of 1 instead of nan which is not what the developer expected since 15 is not an integer likewise a value of 1a will result in a value of 1 instead of nanall of these issues are somewhat understandable since this is one of the most common examples of how to convert a string to an integer and most places do not thiscuss these casesat any rate it got me thinking that i am not aware of any built in way to get an integer like this there is numbertxthours or txthours which comes closer but accepts noninteger numbers and will treat null and as 0 instead of nanto help the developer out i provided the following functionfunction converttointegertext var number mathfloortext return text number text number nanthis seems to cover all the above issues does anyone know of anything wrong with this technique or maybe a simpler way to get the same results,['javascript'] +99434,javascript ie detection why not use simple conditional comments in order to detect ie most javascript libaries do all sort of tricksjquery seem to add a temporary object into your pagess dom to detect some featuresyui2 does regex on the user agent in its yahooenvua function file yahoojsafter reading this answer it came in my mind that it is true in order to detect simply ie in javascript we could simply add to our pagesif iescript typetextjavascriptwindowisie truescriptendifscript typetextjavascript srcallyourotherscriptsherejsscriptnow the windowisie variable is set for all our javascript code by simply doingifwindowisie beside the fact that this might result in being a pain because it has to be added in all pages are there any issuesconsiderations i might be unaware offyi i know it is better to use object detection rather than browser detection but there are cases where you still have to use browser detection,['javascript'] +99439,why zipinputstream cannot read the output of zipoutputstream i am stuck with this junit testpublic void test throws exception bytearrayoutputstream out new bytearrayoutputstream zipoutputstream zipout new zipoutputstream out zipoutputnextentry new zipentry file zipoutwrite new byte 0x01 0x02 0x03 zipoutcloseentry zipoutclose zipinputstream zipin new zipinputstream new bytearrayinputstream outtobytearray zipentry entry zipingetnextentry assertnotnull entry assertequals file entrygetname assertequals 3 entrygetsize i am writing a file with the name file and a content of three bytes to a zipoutputstream then i try to read the created data with a zipinputstream but the last assert fails because entrygetsize is 1 and not 3 as expectedwhat am i doing wrong here what do i have to change to restore the content of file i think i first have to know the length to be able to read the data from the stream,['java'] +99443,casting as decimal and rounding so it appears that if youcastfield1 as decimal field1this will automatically add rounding the original is defined asfield1 typefloat length8 prec53 i need to cast it to decimal because i need my entity framework layer to generate this field as decimal instead of doubleis there a way to cast it as decimal so that it preserves original precision and does not round i would like to avoid having to declare the precision in the cast because 1 there are 100s of fields involved with varying precision and 1 if the underlying table changes in the future it could cause unforeseen bugs to emerge and 3 makes the management more difficult,['sql'] +99467,regex how to find the maximum integer value of a pattern imagine i have the following stringi will have some 1 some 42 and maybe some 5 as wellbasically i am interested in knowing the maximum integer value that follow the pattern integer i am not even sure it is possible to do with a regex what regex could i use so that in the above example the answer would be 42ps one easy solution is evidently to simply look for any integer patterns and use the script c code to iterate through all the matches and find the highest value my question is is it possible to do it straight away within the regexbackground understanding what follows is probably not necessary to answer the question but i thought some of you might want to knowbasically i am using c and boostformat formats are patterned with placeholders like this 1 2 etc boostformat throws an exception if the number of supplied variables do not correspond to the maximum integer value in the format itself the formats i am going to use are supplied by trusted users web site administrators still to do things properly i need to validate the patten thus i need to find the maximum integer in the pattern to make sure no exception will be thrown at run time if you are using boostformat with usersupplied formats how did you deal with this issue btw there is no boostformat tag although there are other boostfoo tagssolution billy oneal provided the right answer and beh tou cheh in the comments to the selected answer was kind enough to paste the actual codeinclude iostreaminclude stringinclude dequeinclude strtkhppint main stdstring s i will have some 1 some 42 and maybe some 5 as well stddequeint int list strtksplit regexd s strtkrange to type back inserterint list strtkmatch modematch 1 if int listempty stdcout max strtkmax of contint list stdendl return 0,['c++'] +99480,setting another month as default in jquery ui datepicker before thisplay in my situation i have to set the month to last month as defaultthe default month for the datepicker is current month but i want it to be last month or other month as default showing how can i make it such as 201009 as the defaultthank you very much,['jquery'] +99492,iterate over values in flags enum if i have a variable holding a flags enum can i somehow iterate over the bit values in that specific variable or do i have to use enumgetvalues to iterate over the entire enum and check which ones are set,['c#'] +99499,select function in socket programming can anyone tell me the use and application of select function in socket programming in c,['c'] +99501,what is wrong with making a unit test a friend of the class it is testing in c i have often made a unit test class a friend of the class i am testing i do this because i sometimes feel the need to write a unit test for a private method or maybe i want access to some private member so i can more easly setup the state of the object so i can test it to me this helps perserve encapsulation and abstraction because i am not modifying the public or protected interface of the classif i buy a third party library i wouldnt want it is public interface to be polluted with a bunch of public methods i do not need to know about simply because the vendor wanted to unit testnor do i want have to worry about a bunch of protected members that i do not need to know about if i am inheriting from a class that is why i say it preserves abstraction and encapsulationat my new job they frown against using friend classes even for unit tests they say because the class should not know anything about the tests and that you do not want tight coupling of the class and its test can someone please explain these reasons to me more so that i may understand better i just do not see why using a friend for unit tests is bad,['c++'] +99502,generic foreach iteration of namednodemap in java looking at the namednodemap interface how do you iterate it with generics it seems to use node rather than string but i am not so sure how to use node objectsnamednodemap namednodemap docgetattributesmapstring string stringmap mapstring string namednodemapfor mapentrystring string entry stringmapentryset keyvalue stuff hereyes i can see how to iterate without using generics and with a regular for loop but i would like to use the above idiom for maps of course the problem would appear to be that despite the name namednodemap does not actually implement the map interface guess you just gotta bite the bullet here and do something likeprivate void iteratenamednodemap attributeslist for int j 0 j attributeslistgetlength j systemoutprintlnattribute attributeslistitemjgetnodename attributeslistitemjgetnodevalue there is nothing nicer,['java'] +99512,unbalanced stack i have written a vc dll the declaration for one of the methods in the dll is as followsextern c declspecdllexportvoid startitint number capture cvcapturefromcamnumberi use this dll in a c code using pinvoke i make the declaration asdllimporttrackingdll entrypoint startit public extern static void startitint numberand i call the function in the code asstartit0now when this line is encountered the compiler is throwing me this errora call to pinvoke function usingtrackingusingtrackingform1startit has unbalanced the stack this is likely because the managed pinvoke signature does not match the unmanaged target signature check that the calling convention and parameters of the pinvoke signature match the target unmanaged signaturei cannot understand why is it throwing this error as the signature in both managed and unmanaged code are the same moreover in my another machine the same code is running perfectly in visual studio so this makes me think that the error thrown is mis leading please helpthanks,['c#'] +99522,recommended method to locate the current script i am writing a script that needs to add dom elements to the page at the place where the script is located widgetlike approachwhat is the best way to do thishere are the techniques i am consideringinclude an element with an idlocator right above the script issuesi do not like the extra markupif i reuse the widget in the page several elements will have the same locator id i was thinking about adding a line in the script to remove the id once used but stilladd an id to the script issueseven though it seems to work the id attribute is not valid for the script elementsame issue as above several elements will have the same id if i reuse the script in the pageuse getelementsbytagnamescript and pick the last element this has worked for me so far it just seems a little heavy and i am not sure if it is reliable thinking about deferred scriptsdocumentwrite not elegant but seems to do the jobedit based on the reply from idealmachine i am thinking about one more optioninclude in the script tag an attribute for example goaltabify use getelementsbytagnamescript to get all the scripts loop through the scripts and check the goaltabify attribute to find my script remove the goal attribute in case there is another widget in the pageedit another idea also inspired by the replies so faruse getelementsbytagnamescript to get all the scripts loop through the scripts and check innerhtml to find my scriptat the end of the script remove the script tag in case there is another widget in the page,['javascript'] +99536,whats meant by parameter int initial capacity in an arraylist whats meant by parameter int initialcapacity in an arraylist i thought it is the number of elements but it did not work when i did thispublic class myclass private arraylistinteger arr public myclassint and elements arr new arraylistintegern elements,['java'] +99538,interview question search in sorted array x for index i such that xi i i was asked the following question in my interview yesterdayconsider a java or c array say x which is sorted and no two elements in it are same how best can you find an index say i such that element at that index is also i that is xi ias clarification she also gave me an example array x 3 1 0 3 5 7 index 0 1 2 3 4 5 answer is 3 as x3 3the best i could think was a linear search after the interview i though a lot on this problem but could not find any better solution my argument is the element with the required property can be anywhere in the array so it could also be at the very end of the array so we need to check every elementi just wanted to confirm from the community here that i am right please tell me i am right thanks,"['java', 'c++']" +99544,what is the difference between ivars and properties in objectivec what is the semantic difference between these 3 ways of using ivars and properties in objectivec1class myotherobject interface myobject property nonatomic retain myotherobject otherobj2import myotherobjecthinterface myobject myotherobject otherobj property nonatomic retain myotherobject otherobj3 import myotherobjecth interface myobject myotherobject otherobj,['objective-c'] +99547,file get contents returns empty string i am hesitated to ask this question because it looks weirdbut anywayjust in case someone had encountered the same problem alreadyfilesystem functions fopem file file get contents behave very strange for http wrapperit seemingly works no errors raised fopen returns resource it returns no data for all certainly working urls eg file returns empty array file get contents returns empty string fread returns falsefor all intentionally wrong urls eg it behaves exactly the same save for little supposedly domain lookup timeout after which i get no error while should but empty stringurl fopen wrapper is turned oncurl both command line and php versions works fine all other utilities and applications works fine local files opened finethis error seems inapplicable because in my case it does not work for every url or hostphpfpm 5211linux version 2635648fc14i686,['php'] +99548,where and how handle springhibernate exceptions im using springhibernate for a desktop applicationi am trying to build it with a layered implementation so i havegui layer call service layer call dao layera small example to better exaplain my situation in gui layerprivate void actionperformedactionevent evt adduserprivate void adduser check gui validation for user inputs ifinputisvalid string usernamenametextgettext string passpasstextgettext now call service layer userservicecreateuserusername pass now here i want to show a message to user like operation successful or operation failed or more sofisticated message like user with same name already exists service layertransactionalpublic void createuserstring name string pass user usernew username pass userdaosaveuser another service layer example transactionalpublic boolean createuserstring name string pass user usernew username pass try userdaosaveuser catchexception ex logex return false return true in this case gui layer can know if save is succesful but it cannot know why the save is failed some username db service shutdown etcthe problem is who throw exception and who handle iti think dao have to throw first exception and service layer rethrow it and finally gui layer handle exception so i can show message to user is this goodthere is a way to build some exceptionhandler using springwhat is the best practice to manage exceptions using springhibernatethanks,['java'] +99549,how to set background color of a button in java gui below is the code which creates 9 buttons in gridlayout form on a specific pannel3 what i want is to make the background of each button black with grey text over it can anyone help please forint i1i9i p3addnew jbuttoni,['java'] +99552,how to build project from maven pom file i have a maven pom file for an open source project this pom file has all the info like what other jars it depends on etc i installed maven created a dir samprj and copied the pom file into that dir cd into that dir and ran mvn command without any arguments but i got bunch of errors i am absolutely new to maven so i think i am missing something i tried also from eclipse import project exisitng maven project but that also does not work except eclipse creates a project that has just that file pomxml i expect something that first it will download the jar for the project and then download all dependent jars and config files but nothing thereso given a pom file how do i build the project from it,['java'] +99564,bind multiple keys to keypress event i am currently using this javascript kepypress code to fire events upon keypressdocumentkeydownfunctione switchekeycode case 39 epreventdefault alertarrow key break case 37 epreventdefault alertarrow key but what i am wondering is if i can instead of binding one key bind a combination of two keys could i possibly do something likedocumentkeydownfunctione switchekeycode case 39 37 epreventdefault alertarrow key break,"['javascript', 'jquery']" +99565,ruby on rails validate a cost what is the best way to validate a costprice input by a user validation rules belowexamples of formats allowed 23 2 123 025 5 63 maximum of two digits after decimal pointminimum value of 001maximum value of 9,['ruby-on-rails'] +99575,devise login form in another controller i am trying to have the devise log in form be on my home pagewhen i just copy the form over of course i get errors because the resource variables and etc are not set in the actioni found this solution on the internet however his solution is to set the needed variables in a module called contenthelperwhere do i put this code i tried putting it in the initializers but i still get the error about resource variable not existing,['ruby-on-rails'] +99577,problem using pow in c why does the following bit of code work in cint res pow2 3printfdn reswhile this other does notint a 2int b 3int res powa bprintfdn reseven if i try double a 2double b 3double res powa bprintffn resi get anundefined reference to powwhat am i doing wrong,['c'] +99590,java threads waiting to lock object that is not visibly locked normally when i ask for a thread dump the symptoms of a poorly performing system are easily explained ie normally i would be able to see that a number of threads are clearly waiting on a monitor which has been acquired but not released by anotherin this case i have a lot of threads waiting for a monitor 0x965ad100 but none appears to have that monitor in the first place the threads in question can be identified with this signaturewaiting to lock 0x965ad100 a ukgovdtiogfoxconagenti have tried googling this and all i seem to find are posts that thiscuss monitors that are locked nothing about waiting for a monitor that is not lockedthread dump in full dumptxti hope someone here can explain what i am seeing or at least point me in the right direction thanks in advance for any responses,['java'] +99595,rails 3 routing error when using acts as taggable on v203 i am using acts as taggable on v203 in rails 3 to add tags to posts i add a tag cloud as described here but i am encountered an erroractioncontrollerroutingerror in postsindex no route matches actiontag idpolitics controllerposts my code is belowposthelpermodule postshelper include tagshelperendmodel postclass post activerecordbase acts as taggable on tagsendpostcontrollerclass postcontroller applicationcontroller def tag cloud tags posttag counts ontags endendview tag cloudtags wcss1 css2 css3 css4 do tag css class link to tagname action tag id tagname class css class end routesrbblogapplicationroutesdraw do root to postsindex resources posts do member do post notify friend end collection do get search end resources comments end resources users resource session match login sessionsnew as login match logout sessionsdestroy as logoutendwhat am i doing wrong thanks for your answers,['ruby-on-rails'] +99598,do any databases allow multiple indexes on the same table to be created simultaneously i am pretty sure this cannot be done in oracle but i would love to be proved wrongsay i have a huge table in with lots of columns and i want to create indexes on a dozen or so columns using oracle i would fire off several sequential create index statements and go off and boil the kettleeach create index needs to scan through every row in the table to form the indexie 10 indexes 10 full scansyoud think an obvious optimisation would be to scan the table once and index the 10 columns at the same time wouldnt you create indexes on mytable ix mytable cola cola ix mytable colb colb ix mytable colc colcso obvious that there must be a great reason why it is not thereany ideasi could fire off each create index simultaneously in separate sessions and hope the database buffer cache saved the day but seems like a long shotediti did not get a definitive answer so i asked the same question on oraclelgeneral consensus was that it is not available but would perhaps be a useful feature most useful response was from david aldridge who suggested that if the create index statements were all kicked off at the same time then oracle would do the right thing,['sql'] +99601,how to control orientation of video assembled with avmutablecomposition i am assembling a bunch of video clips filmed on the iphone in portrait mode to assemble them i am taking straightforward approach as follows avurlasset to get hold of the different videos then shoving these into an avmutablecompositiontrack and then putting this into an avmutablecomposition which i am exporting to file with avassetexportsessionmy problem is that when i come to thisplay the video in a uiwebview it is appearing in landscape mode however if i view any of the component views they appear in portrait view does anyone know how to sort out the orientation i tried messing around with the avmutablecomposition naturalsize changing the width and height around but that just made my people look short and fat whilst on their sidethanks in advance for any thoughts suggestionstudor,['iphone'] +99610,is there a way to use gcc to convert c to mips i completed a c to mips conversion for a class and i want to check it against the assembly i have heard that there is a way of configuring gcc so that it can convert c code to the mips architecture rather than the x86 architecture my computer users an intel i5 processor and prints the outputrunning the terminal in ubuntu which comes with gcc what command do i use to configure gcc to convert to mips is there anything i need to install as welleditlet me clarify please read thisi am not looking for which compiler to use or people saying well you could crosscompile but instead you should use this other thing that has no instructions on how to set up if youre going to post that at least refer me to instructions gcc came with ubuntu i do not have experience on how to install compilers and it is not easy finding online tutorials for anything other than gcc then there is the case of crosscompiling i need to know about as well thank you,['c'] +99616,how do i apply url normalization rules in php is there a preexisting function or class for url normalization in phpspecifically following the semantic preserving normalization rules laid out in this wikipedia article on url normalization or whatever standard i should be following converting the scheme and host to lower casecapitalizing letters in escape sequencesadding trailing to directories not filesremoving the default portremoving dotsegmentsright now i am thinking that i will just use parse url and apply the rules individually but i would prefer to avoid reinventing the wheel,['php'] +99625,how to use a php switch statement to check if a string contains a word but can also contain others i am using a php switch to include certain files based on the incoming keywords passed in a parameter of the pages urlthe url for example could be pagephpkwcitroen20berlingo20keywordsinside the page i would like to use something like this switch getkw case berlingo include berlingophp break case c4 include c4php break what i want to do in the first case is include the berlingophp file if the keyword parameter contains berlingo but it does not have to be exactly that keyword alonefor example i want to include the berlingophp file if the keyword is berlingo but also if it is citroen berlingohow can i evaluate if a given string contains a value using a php case select switch statementthanks,['php'] +99655,is extend faster than in python we can concatenate lists in two wayslstextendanother lstlst another lsti thought extend would be faster than using because it reuses the list instead of creating a new one using the other twobut when i test it out with timeit it turns out that is faster timeitlextendx l range10 x range10016929602623 timeitl x l range10 x range10015030503273 timeitlextendx l range500 x range10805264949799 timeitl x l range500 x range10750471830368is there something wrong with the code i put in timeit,['python'] +99661,android memory leaks points are not clear friends i have read complete article related to avoiding memory leaks in androidright now1 i am using private nested class not staticif i make that nested class static will it be usefull2 article saysif youre about to use inner classes or anonymous classes think carefully do not use anonymous classes until youre very sure and can prove that they are not causing a memory leakcan any one give me example of that which one is good approach and which one bad for memory leaksany help would be appreciated,['android'] +99684,which is faster in ruby a hash lookup or a function with a case statement we have a few places in a timecritical script where we convert old ids into strings at the moment we use case statements inside a function like sodef get name id case id when 1 one thing when 3 other thing else default thing endendi am considering replacing this with a hash lookup like sonames 1 one thing 3 other thingnamesdefault default thingit feels like it ought to be faster to use namesid than get nameid but is it,['ruby'] +99691,how to reduce default c memory consumption i have a server application written in c after startup it uses about 480 kb of memory on x86 linux ubuntu 804 gcc 424 i think 480 kb is an excessive amount of memory the server is not even doing anything yet no clients have been connected to the server see also my comment below in which i explain why i think 480 kb is a lot of memorythe only things the server does during initialization is spawning one or two threads setting up a few sockets and other simple things that are not very memoryintensivenote that i am talking about real memory usage not vm size i measured it by starting 100 instances of my server on an idle laptop and measuring the system memory usage with free before and after starting the server instances i have already taken filesystem cache and things like that into accountafter some testing it would appear that something in the c runtime is causing my server to use this much memory even if the server itself does not do anything for example if i insertgetchar return 0right afterint mainint argc char argv then the memory usage is still 410 kb per instancemy application depends only on curl and boost i have a fair amount of experience with c programming and i know c libraries do not tend to increase memory consumption until i use themother things that i have founda simple hello world c app consumes about 50 kb of memorya simple hello world c app linked to curl but otherwise not using curl consumes about 50 kb of memory as wella simple hello world c app no boost consumes about 100 kb of memorya simple hello world c app that includes some boost headers but does not actually use boost consumes about 100 kb of memory no boost symbols when inspecting the executable with nmmy conclusion is therefore as followsgcc throws away unused boost symbolsif my app uses boost then something in the c runtime probably the dynamic linker causes it to use a lot of memory but what how do i find out what these things are and what can i do about themi remember some kde thiscussions several years ago about c dynamic linker issues the linux c dynamic linker back then caused slow startup time in kde c apps and large memory consumption as far as i know those issues have since been fixed in c runtimes but could something similar be the cause of the excessive memory consumption i am seeinganswers from gccdynamic linking experts are greatly appreciatedfor those who are curious the server in question is phusion passengers logging agent,['c++'] +99698,running a method with parameters in a thread in c i am currently working on a project in c i have a method called updateprogress which has two int parameters count and totalrows if i have call the method by saying updateprogresscount totalrows this works fine but i want to run this method within a new thread how can i go about doing this i have looked online and everything looks overly complicated for what i am wanting to do thanks for your help with this,['c#'] +99702,best way to detect country location of visitor possible duplicatelocation detecting tecniques for ip addresses for our website it is important to know from exactly which country our visitor is coming fromi guess the best answer for my question would be the simple geo location feature of current browser systems which just ask the user if the website is allowed to see his geographic location but i do not want want to bother visitor with questions i would love to automatically detects the visitors location country should be enoughwhats the best way to do this what ip database would be the best is the browser header trustable enough to detect his country enus enen encawhats the best solution,"['php', 'javascript']" +99716,how to deal with windows readdirectorychangesw and its mixed longshort filename output i am developing a piece of c code that uses readdirectorychangesw to monitor changes under a directory in windows i have read the related msdn entries for readdirectorychangesw and the file notify information structure as well as several other pieces of documentation at this point i have managed to monitor multiple directories with no apparent problems in the monitoring itself the problem is that the filenames put in the file notify information structure by this function are not canonical according to msdn they can be in either long or short form i have found several posts which suggest caching both short and long pathnames to handle this case unfortunately according to my own testing on a windows 7 system this is not sufficient to eliminate the issue because there are not just two alternatives for each filename the problem is that in a pathname each component can be in either long or short form the following pathnames could all refer to the same filecprogra1myprog1mydata1txtcprogra1myprog1mydatafiletxtcprogra1myprogrammydata1txtcprogra1myprogrammydatafiletxtcprogram filesmyprog1mydata1txtand as far as i can tell from my testing using cmdexe they are all perfectly acceptable essentially the number of valid pathnames for each file rises exponentialy with the number of components in its pathnameunfortunately readdirectorychangesw seems to fill in its output buffer with the filenames as provided to the system call that causes each operation for example if you use cmdexe commands to create rename delete etc files the file notify information will contain the filenames as specified at the command linenow in most cases i could use getlongpathname and friends to get a unique path for my use unfortunately that cannot be done when deleting files by the time i get the notification the file is already gone and the getpathname functions will not workat the moment i am thinking about using more extensive caching to determine which alternative pathnames are used by applications for each file which would handle any case except for the one where someone decides to delete a file out of the blue using an unseen mixed pathname and i am thinking about creative data mining from the parent directory modification events and falling back to checking the actual directory for that caseany suggestions for an easier way to do this ps1 while change journals would deal with this effectively i hope i do not believe i can use them due to their ties to ntfs and the lack of administrator priviledges for my application i would rather not go there unless i am absolutely forced tops2 please keep in mind that i code mainly on unix so be gentle,['c'] +99733,the equivalent of configure in windows what is the equivalent of configure in windowssometimes i download a cc library and when i use the make it it says use configure but obviously configure can only be used on a linux machine and the libraries do not usually have instructions for compiling on windows although they do support windows they do not provide instructionsfor example the library wxsvg says it works on windows but when i download it i do not see any instructions for compiling on windows and i only linux files for configuring it,['c++'] +99736,how to enablethisable toolbar items how do you make a gtktoolbutton thisabled so that it is greyed out like thishow do you make it enabled again,['python'] +99752,execute remote python script via ssh i want to execute a python script on several 15 remote machine using ssh after invoking the scriptcommand i need to thisconnect ssh session and keep the processes running in background for as long as they are required to i have used paramiko and pyssh in past so have no problems using them again only thing i need to know is how to thisconnect a ssh session in python since normally local script would wait for each remote machine to complete processing before moving on,['python'] +99770,stream volume in soundpool vs volume in audiomanager i am so confusedsoundpoolplayint soundid float leftvolume float rightvolume int priority int loop float ratevolume here is from 00 to 10tutorials i have seen recommend to calculate stream volume asaudiomanager mgr audiomanager getcontextgetsystemservicecontextaudio serviceint streamvolume mgrgetstreamvolumeaudiomanagerstream musicstreamvolume streamvolume audiomanagergetstreammaxvolumeaudiomanagerstream musicmsoundpoolplaymsoundpoolmapgetindex streamvolume streamvolume 1 0 1fwhich makes sense i would assume that this volume would override global media volume set by user in phone and i can change volume for my app independently by changing stream volume in soundpoolbut in reality it works like multiplier if i set 05 for volume in soundpool the actual volume will be always half of the global one very easy to reproduceset global media volume inphone settings to maxset volume in activity using soundpoolplay to 05 play soundset volume in soundpoolplay to 1 play sound it will be two times loudercan somebody explain why it works like that is volume passed to soundpoolplay method really a multiplier to the global volume,['android'] +99774,transforming empty element into null when unmarshalling with jaxb a class is defined with the following jaxb annotationclass course xmlelement name booklistbook requiredbooks new arraylistbookwhen unmarshalling an xml document that contains thiscourse bookcoursei end up with a book added to the list with all of its attributes set to null i do not control the xml input how can i prevent this empty book from being added i tried intercepting in set or add methods but turns out jaxb bypasses setters when dealing with collections any suggestions,['java'] +99794,choosing the right ios xml parser so there are a million different xml parsers for the iphone i have a medium sized xml file that contains alot of duplicate tags at different points in the hierarchy i was thinking about tbxml but i was concerned about its lack of xpath support for instance lets say my xml file looked like thisblog author foo1 author comments comment text cdata html code that must be extracted text authorfoo2author comment comment text cdata here is another post text authorfoo1author comment commentsblogbasically my requirements are that i need to be able to extract that cdata and know whether it is the blog author a comment author,['iphone'] +99797,silverlight and arraylist does visual studio 2010s silverlight support arraylist if yes then how to use it if not then whyhow to use arraylist in silverlight,"['c#', 'asp.net']" +99826,how do i enable jquery intellisense in eclipse andor aptana possible duplicateaptana plugin for eclipse and jquery code assist i have got eclipse running with the aptana addon and would like to have jquery intellisensecodecomplete eg i would like css etc to pop up in the following examplei tried to set this in aptana preferences but it does not seem to have support for jquery no checkboxhow can i get jquery code complete in eclipse andor aptana,['jquery'] +99834,select query with date condition i would like to retrieve the records in certain dates after dmmy or after dmmy and before dmmy how can i do it select datefrom tablewhere date 1092008andselect datefrom tablewhere date 1092008and date 1092010it does not work,['sql'] +99838,how to clear memorycache i have created a cache using the memorycache class i add some items to it but when i need to reload the cache i want to clear it first what is the quickest way to do this should i loop through all the items and remove them one at a time or is there a better way,['c#'] +99845,sap web service from net via wcf i am trying to consume a sap web service from net via wcf i have generated the proxy and i have configured the appconfig file here is my test codewebservicesapztest rfcclient mywcfservice new webservicesapztest rfcclientmyendpointmywcfserviceclientcredentialsusernameusername usernamemywcfserviceclientcredentialsusernamepassword passwordwebservicesapztestrfc parameter new webservicesapztestrfcparametertestinput this is a simple testwebservicesapztestrfcresponse response mywcfserviceztestrfcparameterconsolewritelinereponsetestoutputconsolereadline the ztestrfc sap method is a very simple function that accepts an input string and outputs result the input stringwhen i call ztestrfc method i got a null value in variable response but soap messages seem to be finesoap requestmessagelogtracerecordhttprequest xmlnsmethodpostmethodquerystringquerystringwebheadersvsdebuggercausalitydatauidpoxjmi5ncdatnipmwfar52katqhavnnwjeempmexoyrvn7oxwcjzltnnikldpg5migacqaavsdebuggercausalitydatawebheadershttprequestsenvelope xmlnsheaderaction smustunderstand1 xmlnsurnsapcomdocumentsapsoapfunctionsmcstyleztest rfcztestrfcrequestactionsheadersbody xmlnsxsi xmlnsxsdztestrfc xmlnsurnsapcomdocumentsapsoapfunctionsmcstyletestinput xmlnsthis is a simple testtestinputztestrfcsbodysenvelopemessagelogtracerecordsoap responsemessagelogtracerecordhttpresponse xmlnsstatuscodeokstatuscodestatusdescriptionokstatusdescriptionwebheaderscontentlength359contentlengthcontenttypetextxml charsetutf8contenttypesetcookiemysapsso2ajexmdabaaxqmdewmda1msagicacaamwndadaahemtegicagiaqaddiwmtaxmtewmtiwoquabaggaafycqabu2f8a9jcb8wyjkozihvcnaqccoihlmihiagebmqswcqyfkw4dahofadalbgkqhkig9w0bbwexgciwgb8caqewezaomqwwcgydvqqdewnqmtecaqawcqyfkw4dahofakbdmbggcsqgsib3dqejazelbgkqhkig9w0bbwewhayjkozihvcnaqkfmq8xdtewmtexmdeymdk0ofowiwyjkozihvcnaqkemryefjc2fnflvbnu1zaodwtlpapes8sapmakgbyqgsm44bamemdauahubs844bob2f8ngeguepmglakbveggucfqfls6hii21bwt1mejmqvabd32fjfvmw3d3d path domaindomain setcookieserversap netweaver application server abap 700serverwebheadershttpresponsesoapenvenvelope xmlnssoapenc xmlnssoapenvsheader xmlnsheadersoapenvbodyrfcztestrfcresult xmlnsrfcurnsapcomdocumentsapsoapfunctionsmcstyletestoutput xmlnsresulttestoutputrfcztestrfcresultsoapenvbodysoapenvenvelopemessagelogtracerecordi do not know what could be happening any ideasthanks in advance,['.net'] +99876,set the nonserializedattribute to an auto property this cannot be done in c any way to do itlaugh in case my little pun was not understood what i mean is how can i mark a property in c as nonserialized of course when the property contains logic it is natural to be unable to do it but autoproperties are serializable and as such i would expect to have some way to allow me to prevent their serialization,['c#'] +99887,navigate to specific page in scrollview with paging programatically how do i navigate to a specific page programmatically basically i have an app with a scrollview populated with a bunch of subviews tableviews in this case when clicking on a subview it zooms in and the user can edit and navigate the table however when i zoom back out i reload the entire view in case there were any changed made by the user of course reloading the view sends the user back to page 0 i have tried setting the pagecontrolcurrentpage property but all that does is change the dot of the pagecontrol does that mean that something is wrong or do i need to do something else as wellall that is controlling the page scrolling is this method voidscrollviewdidscrolluiscrollview sender cgfloat pagewidth selfscrollviewframesizewidthint page floorselfscrollviewcontentoffsetx pagewidth 2 pagewidth 1selfpagecontrolcurrentpage pagensstring listname selfwishlists objectatindexselfpagecontrolcurrentpageselflabellistnametext listname,['iphone'] +99898,java tryfinally return design question in java a try finally is executed somewhat unintuitively to me as illustrated in another question in java does return trump finally if you have a return statement in the try block it will be ignored if a finally block is defined for example the functionboolean test try return true finally return false will always return false my question why is this is there a particular philosophy behind this design decision made by java i appreciate any insight thank youedit i am particularly interested as to why java thinks it is ok to violate the semantics that i define if i return in a try block the method should return right then and there but the jvm decides to ignore my instruction and return from a subroutine that actually has not yet been reached,['java'] +99899,is it safe to push back dynamically allocated object to vector whenever i need to add dynamically allocated object into a vector i have been doing that the following wayclass foo vectorfoo vvpush backnew foo do stuff with foo in v delete all foo in vit just worked and many others seem to do the same thingtoday i learned vectorpush back can throw an exception that means the code above is not exception safe so i came up with a solutionclass foo vectorfoo vauto ptrfoo pnew foovpush backpgetprelease do stuff with foo in v delete all foo in vbut the problem is that the new way is verbose tedious and i see nobodys doing it at least not around meshould i go with the new wayor can i just stick with the old wayor is there a better way of doing it,['c++'] +99902,how to get parent element by specified tag name using jquery i want to get an elements parent which has an specified tag namesample codetable tr td input typebutton idmyid td trtablenow i want something like thismyidspecificparenttable returns nearest parent of myid element which table is it is tagname,['jquery'] +99904,get element with jquery and selenium ide 108 i am trying to get element with jquery and selenium ide 108tdstorevaluetdtdresultfindimgfilteraltquotnameofphotoquoteq0tdtdtdand in log i geterror element resultfindimgfilteraltnameofphotoeq0 not found when i put this command in firebug i get this element why it does not work editalternatively for example you can give me code how to get id of first object whith java tag at main page of stackoverflowtaga reltag titleshow questions tagged java classposttag hrefquestionstaggedjavajavand the example result from div idquestionsummary4303985 classquestionsummary narrowisquestionsummary4303985,['jquery'] +99915,how to highlight imageview when focused or clicked a good example of this is either on the twitter launch screen the screen with the large icons that is seen when the application is first launch or even just look at the application tray when you focus an application iconbasically i need to highlight an imageview where the highlight contours to the image within the imageview and looks like it is a border to that image i would also like to customize the highlight to have it be a certain color and for it to fade outthanksgroomsy,['android'] +99919,order of memory thisposal and gc in c what actually happens in c when1 a method gets invoked2 the method allocates memory eg memorystream mm new memorystream3 an exception occurs in the method which is caught by the invoking classesdoes the resource mm gets freed by the garbage collector is this a security risk eg dosps i know it is best practice to explicitely free any allocated resource that would mean to use the usingstatement or trycatchfinallyblock,['c#'] +99923,why cast after an instanceof in the example below from my coursepack we want to give to the square instance c1 the reference of some other object p1 but only if those 2 are of compatible typesif p1 instanceof square c1 square p1what i do not understand here is that we first check that p1 is indeed a square and then we still cast it if it is a square why casti suspect the answer lies in the thistinction between apparent and actual types but i am confused nonethelessedithow would the compiler deal withif p1 instanceof square c1 p1edit2is the issue that instanceof checks for the actual type rather than the apparent type and then that the cast changes the apparent typethanksjdelage,['java'] +99929,compass lucene hits i use lucene and compass on it and i have a problem try compasshits hits compassqueryhits for compasshit compasshit hits if resultssize maxresults loginfothis number of results exceeded d for query s maxresults query break else resultsaddt compasshitgetdata when the data is geting by compasshitgetdata and it is a 100 hit it reexecute the search is there any possibility to change it to 200 or moreeditfrom wiki apache orgiterating over all hits is slow for two reasons firstly the search method that returns a hits object reexecutes the search internally when you need more than 100 hits and my question is there opportunity to change this value 100 to 200 but important is that i use compass nor a raw lucene,['java'] +99933,live tile updates how do you create a live tile for windows phone 7 i was wondering because i would basically like to have text that updates on the live tile once per 15 minutes that a user could just glance at would this timing be possible,['c#'] +99950,nesting phpfunctions to what purpose why would php allow nesting functions phpfunction foo function bar return bar return fooprint fooprint bar is valid php but why would nesting be needed everand even if so why can i call bar from anywhere and not eg only withing foo or trough foobar or suchi ran into this today because i forgot a closing bracket somewhere and had one too many further down the code was valid and no errors thrown but it all started acting really weird functions not being declared callbacks going berserk and so on is this a feature and if so to what purpose or some idiosyncrasyanswer commentor points out that this is a duplicate of what are php nested functions for,['php'] +99956,how do i use a relative path in a python module when the cwd has changed i have a python module which uses some resources in a subdirectory of the module directory after searching around on stack overflow and finding related answers i managed to direct the module to the resources by using something like import osospathjoinospathdirname file fontsmyfontfthis works fine when i call the module from elsewhere but it breaks when i call the module after changing the current working directory the problem is that the contents of file are a relative path which does not take into account the fact that i changed the directory mymodule file mymodule init pyc oschdir mymodule file mymodule init pychow can i encode the absolute path in file or barring that how can i access my resources in the module no matter what the current working directory is thanks,['python'] +99957,accessing variables in the debugging session with ipython and pdb on i am new to ipython and i am trying to use ipython to debug my code i did1 pdbautomatic pdb calling has been turned onand thenin 2 run mycodepyand in the code i have 10 so it raises an exception and will automatically goes into the debug sessionzerodivisionerror float divisionipdb variablearray 0704313 1347006 281474391so i can access variables but when i do the followingipdb b variable the specified object variable is not a function or was not found along syspathbut this worksipdb b selfx,['python'] +99975,asynctask and looperprepare error i have the following codeclass overlaytask extends asynctaskvoid void void override public void onpreexecute if sites null mymapviewgetoverlaysremovesites mymapviewinvalidate sites null override public void doinbackgroundvoid unused grabshipswithlocation return null override public void onpostexecutevoid unused mymapviewgetoverlaysaddsites mymapviewinvalidate isloading false that seems to work fine on a few test devices but i am seeing a lot of errors appearing on the dev console i cannot seem to work out why and where to put this looperprepare is it neededjavalangexceptionininitializererrorat comtestappnamefindermain1gotlocationfindermainjava286at comtestappnamemylocationgetlastlocationrunmylocationjava89at javautiltimertimerimplruntimerjava289caused by javalangruntimeexception cannot create handler inside thread that has not called looperprepareat androidoshandlerinithandlerjava121at androidosasynctaskinternalhandlerinitasynctaskjava421at androidosasynctaskinternalhandlerinitasynctaskjava421at androidosasynctaskclinitasynctaskjava152as requested mylocationjava class getlastlocation extends timertask override public void run lmremoveupdateslocationlistenergps lmremoveupdateslocationlistenernetwork location net locnull gps locnull ifgps enabled gps loclmgetlastknownlocationlocationmanagernetwork provider ifnetwork enabled net loclmgetlastknownlocationlocationmanagergps provider if there are both values use the latest one ifgps locnull net locnull ifgps locgettimenet locgettime locationresultgotlocationgps loc else locationresultgotlocationnet loc return ifgps locnull locationresultgotlocationgps loc line 89 return ifnet locnull locationresultgotlocationnet loc return locationresultgotlocationnull,['android'] +99985,how to create multiple android apps from one code base i have an android code base which uses apis with settings to get different data for several apps all apps use the same code base but with one or two design tweaks so how do i reuse the main code base without having to copy the whole android project each timeiphone uses multiple targets in the same project which works well if android cant do this do i need to compile binaries of the code base in one project and then import into each new app project if so how i am using eclipse and am an intermediate java developerany help much appreciateddoug,['android'] +99996,rethis and memcache or just rethis i am using memcached for some caching in my rails 3 app through the simple railscache interface and now i would like to do some background job processing with rethis and resquei think they are different enough to warrant using both on heroku though there are separate fees to use both memcached and rethis does it make sense to use both or should i migrate to just using rethisi like using memcached for caching because least recently used keys automatically get pushed out of the cache and i do not need the cache data to persist rethis is mostly new to me but i understand that it is persistent by default and that keys do not expire out of the cache automaticallyedit just wanted to be more clear with my question i know it is feasible to use only rethis instead of both i guess i just want to know if there are any specific thisadvantages in doing so considering both implementation and infrastructure are there any reasons why i should not just use rethis ie is memcached faster for simple caching i have not found anything definitive either way,['ruby-on-rails'] +100017,is there any way to send audio file to the speechtotext recognition i want the android speech recognition system analysing audio file and not the default incoming voice from microphoneis there any way to do that thank you,['android'] +100050,crossplatform means of getting users home directory in ruby java has the convienient systemgetpropertyuserhome to get the users home directory in a platformindependent way whats the equivalent in ruby i do not have a windows box to play around with and i feel like relying on tildes in filenames is not the cleanest way are there alternatives,['ruby'] +100053,jquery textarea focus when i click a button i want the textarea in this li element to focusli classcommentblock idcommentbox79 stylethisplay listitem div div classgrid userimageblocks div classimgsmall img width35 height35 altimage srcbackasura1filesimagessmall1288170363aca595cabb50jpg div div div classgrid usercontentblocks alpha omega form acceptcharsetutf8 actionbackasura1accountsavecomment methodpost div stylethisplay none input typehidden valuepost name method div input typehidden idstatusmessagereplypid value79 namedatastatusmessagereplypid input typehidden idstatusmessagereplyitemid value1 namedatastatusmessagereplyitem id input typehidden idstatusmessagereplycommentersitemid value1 namedatastatusmessagereplycommenters item id textarea idstatusmessagereplymessage namedatastatusmessagereplymessage write your comment textarea input typesubmit name valuecomment classcomment idcomment79 form div div classcleardiv divlithis is my jquery codeuserstatusbuttonsclickfunction var id thisattrid commentboxidslidetogglefast commentboxid statusmessagemessagefocus return false,['jquery'] +100054,drawing a grid using css i am looking for a way to draw a grid ie inside of a div using css and js if necessary it feels like it should be relatively straight forward but i have not been able to figure it out any advice would be greatly appreciatedthank you in advancelenny,['css'] +100070,determine if a view is inside of a popover view we have common views that we use in our application in many locations inside of uinavigationcontrollers occasionally the uinavigationcontrollers are inside of popover views now the views we put into the nav controllers modify their navigation controllers toolbar buttons and in some cases use custom buttons that weve created we need to be able to figure out from the uiviewcontroller itself if the view is inside of a popoverview so we can thisplay the correctly colored buttonswe can easily get the navigation controller reference from the uiviewcontroller using uiviewcontrollernavigationcontroller but there does not seem to be anything for finding a uipopovercontrollerdoes anyone have any good ideas for how to do thisthanks,['objective-c'] +100080,what exactly is one definition rule in c what exactly does one definition rule in c say the only trustworthy occurence i can find is in the c programming language 3rd ed p 923 is there any official definition of the rule except that,['c++'] +100091,is there any difference between 1u and 1 in c while 1u i nsize i any particular reason to use 1u instead of 1,['c'] +100094,operator overloading why is overloaded operator mandated to be a member function 1353 but not a compound assignment operator eg operator 1352 am i overlooking something here,['c++'] +100116,is there a quick way to create a set currently i am creating a new set like this stdseta s sinserta1 sinserta2 sinserta3 sinserta10is there a way to create s in one line,['c++'] +100117,ndimensional array i want to create an ndimensional array of doubles at compiletime the number of dimensions and is not knowni ended up defining the array as a dictionary with the key being an array of ints corresponding to the different axes so in a 3dimensional array i would supply 5 2 3 to get the double at 5 2 3 in the arrayhowever i also need to populate the dictionary with doubles from 0 0 0 to m1 m2 mn where m1 to mn is the length of each axismy initial idea was to create nested forloops but as i still do not know how many i would need 1 for each dimension i cannot do this at compiletimei hope i have formulated the question in an understandable manner but feel free to ask me to elaborate parts,['c#'] +100145,can java stringindexof handle a regular expression as a parameter i want to capture the index of a particular regular expression in a java string that string may be enclosed with single quote or double quotes sometimes no quotes how can i capture that index using javaegcapture string class word,['java'] +100171,templates for setters and getters i am not familiar with templates but i wonder if it is possible to use them for setter and getter methods for example in this situationdouble exmlclassgetavoid const return a void exmlclasetaconst double a a adouble exmlclassgetbvoid const return b as you can see methods are almost the same except they refer to another private variables a b c is there a more elegant way to write those functions or it is common practice to do like above in such situations and if its common to use templates i would appreciate example how you would use them in code aboveanother question i would ask is how should getters and setters be properly declared is it good coding styledouble getavoid constvoid setaconst double adouble getbvoid constvoid setbconst double bdouble getcvoid constvoid setcconst double ci mean should getters be always const and setters take as argument reference to an object rather than copy it which would be probably a little bit slower,['c++'] +100184,get list of photo galleries on android i am looking fora list of the existing photo gallery names hopefully their top thumbnail as wellthe contents of the gallery i can then load thumbnails and full size as neededhow would i go about getting a list of the galleries do not know if that is the proper term in android for the groupings of images visible in the gallery app and their contents i need access to the gallery in it is structure without using the existing gallery thisplay i am creating a totally new one not an over layer to the photo requestor etci assume mediastoreimages is where i need to be but i do not see anything that will give me the groupings,['android'] +100189,dynamic routes with rails 3 i have a task to develop a rails application following the model for routingi need to have pagecontroller and page model page urls must be like contacts shipping some pagealso i need have catalogcontroller and category model categories urls must be like laptops smartphonesandroidand it will be productscontroller and product model urls of products must be line laptopstoshiba sattelite l605 smartphonesandroidhtc magici understand that this problem can be solved by using urls likepageshippingcatalogsmartphonesandroidbut the customer does not want to see the insertion of page or catalog in the urlplease tell me the direction for solving this problemsorry for my bad english,"['ruby-on-rails', 'ruby']" +100192,what does this mean in jquery what does this means and when it is used,"['javascript', 'jquery']" +100234,not in condition in sql can anyone tell me the exact syntax for not in condition in sql on two columnsthis is my query written in vbastrnewsql select thistincttblrevrellog detailpartnumber tblrevrellog detailchangelevel tblrevrellog detailid from tblrevrellog detail left join tbleventlog on tblrevrellog detailpartnumber tbleventlogpartnumberstrnewsql strnewsql where tbleventlogpartnumber not inselect tbleventlogpartnumber from tbleventlog where tbleventlogeventtypeselected pn removed from wrapper and tbleventlogtrackingnumber temptrackingnumber and tbleventlogtrackingnumber tblrevrellog detailrevreltrackingnumberi want to change this sub query like it should apply on the combination of two columns as followsstrnewsql select tblrevrellog detailpartnumber tblrevrellog detailchangelevel tblrevrellog detailid from tblrevrellog detail left join tbleventlog on tblrevrellog detailpartnumber tbleventlogpartnumberstrnewsql strnewsql where tbleventlogpartnumber tbleventlogpartnumberchglvl not inselect tbleventlogpartnumbertbleventlogpartnumberchglvl from tbleventlog where tbleventlogeventtypeselected pn removed from wrapper and tbleventlogtrackingnumber temptrackingnumber and tbleventlogtrackingnumber tblrevrellog detailrevreltrackingnumberbut this is not working,['sql'] +100238,invalid uri the hostname could not be parsed i am try to construct uri but i am unable to handle bad urisis there any way we can handle bad urisif reviewseitemitemindexurltostringcontainshttp ouri new urireviewseitemitemindexurltostringelse ouri new urihttp reviewseitemitemindexurltostringelse part gets error out for bad uris thank you,['c#'] +100249,directoryexistsctempfoo returns true when directory does not exist ok i got bit by something that seems a tad weird i realize it was my mistake to not format the pathname correctly but i would expect the following test to return false especially since the folder did not existdirectoryexistsctempfoobut in fact it returns true even though the directory does not existthe code should be directoryexistsctempfoocan someone explain to me why i get a false positive from the first version i would expect it to return false or throw an exception perhaps but not return true,"['c#', '.net']" +100257,php whats the difference between initializing an array with new vs without it i have always created arrays by just populating themfoo carbut i have seen a lot of foo arrayfoo carandfoo new arraywhats the difference between not initializing using array and using new arraythanks,['php'] +100279,microsoft sql server any way to tell when a record was created our customer wants to order by the record creation date to me this seems like a system variable some sort of meta data for the record itselfis there a way to tell when a record was created without actually creating a datetime field with a default of getdate and hope that no one modifies it,['sql'] +100294,python how do i make temporary files in my test suite i am using python 26 and nosei am writing tests for my python app i want one test to open a new file close it and then delete it naturally i prefer that this will happen inside a temporary directory because i do not want to trash the users filesystem and it needs to be crossoshow do i do it,['python'] +100295,scaling text to fit on iphone i am having a bit of trouble working out the best way to render text in my applicationmy main view consists of a text view and the design of the application dictates a few thingsthe font size of the text should be dynamic the text frame should be centred vertically in the viewhyphenation should be automatic and only when needed avoided if possibleat the moment i am using a uilabel and the following code to try and guess the best font size to use for the amount of texttxt this is just some sample textmylabelfont self getfontforstringtxtmylabeladjustsfontsizetofitwidth yesmylabelnumberoflines 0mylabel settexttxtand uifont getfontforstringnsstring txt cgfloat textlength txtlength cgfloat maxfontsize 71 cgfloat minfontsize 27 cgfloat newfontsize 0 nsarray chunks txt componentsseparatedbystring nssortdescriptor sortdescriptor nssortdescriptor alloc initwithkeylength ascendingno autorelease nsarray sortedchunks chunks sortedarrayusingdescriptorsnsarray arraywithobjectsortdescriptor cgsize labelsize thethinglabelboundssize cgsize projectedsize sortedchunks objectatindex0 sizewithfontuifont boldsystemfontofsizemaxfontsize if projectedsizewidth labelsizewidth cgfloat percentagedifference projectedsizewidth labelsizewidthlabelsizewidth100 if percentagedifference 50 newfontsize minfontsizepercentagedifference100 10 if newfontsize minfontsize newfontsize minfontsize else newfontsize percentagedifferencemaxfontsize100 10 ifnewfontsize maxfontsize2 newfontsize maxfontsize absnewfontsize else if textlength 11 textlength 255 newfontsize maxfontsize maxfontsize minfontsize textlength 11 100 else if textlength 11 newfontsize maxfontsize else if textlength 255 newfontsize minfontsize return uifont boldsystemfontofsizenewfontsizethis works to an extent but often falls over when the text is a bit on the long side these two example show it rendering the following stringsshort amount of texta substantially longer amount of text which i still want to render nicelyas you can see in the second example with far longer text there are a number of issuesthe initial widowthe dropped ythe missing nicelyso with all this in mind what are my options i am open to moving to using coretext if this is the right solution but have no idea where to start it is also possible i have made a mistake which i just cannot see in my font size guessing codeany input you could offer would gratefully recievedmany thanks,['iphone'] +100302,sqlite export with column names is there any sqlite command or thirdparty tool that allows database dumps to include column names in the insert into statementsinstead ofinsert into mytable values a bi would like to seeinsert into mytable column1 column2 values a bthe dump command in sqlite only offers the first version,['sql'] +100313,visual studio 2010 debugging if var null not triggering solved problem with constructormatthew flaschen and michael burr pointed out the problem of the overloaded constructor of nodeint calling node which does not work becausethanks guysi have built a program i am debugging it and have run into a weird problem a if statement is not getting triggered when it should be this is a school project where we must build an avl tree with at least one optimizing feature i am sure and have tested that the rdown and ldown work as the balancing factors the tree is not perfectly balanced rather it is based on the hight of the branches ie balance should only return 101 otherwise it is unbalanced i hope this is enough information to solve this weird problem i have never ran into anything like this before with microsoft visual studio 2010node structstruct node int data the data in the node int rdown the number of ellements below the node on the right side int ldown the number of ellements below the node on the left side node parrent the nodes parrent node lchild the nodes left child node rchild the nodes right child node rdown 0 ldown 0 data 0 parrent null lchild null rchild null node int dat rdown 0 ldown 0 parrent null lchild null rchild null data dat bool end if lchild null rchild null return true check if this node is the end of the line where it does not return false have any children bool goodtoadd if lchild null rchild null return true make sture the current node has at least one spot to add return false a new node to either lchild or rchild must be null int balance return ldown rdown get a balance number for the nodesearch function that is causing the problemsnode avl treesearchconst node num node tmpnode avl treeroot tmpnode is a place holder for the search for int i 1 true i increment int i to check for excess searching pervents endless loop if tmpnode null causing problems the search has reached a dead end the data is not contained null return null if tmpnodedata numdata if the data of num is the same as tmpnode the data is contained node return tmpnode since the node has not been found yet move down the tree if tmpnodedata numdata tmpnodelchild null if the data is smaller than the tmpnode move to the lchild tmpnode tmpnodelchild else if tmpnoderchild null since the node has been proven to not be to the data to be searched for tmpnode tmpnoderchild and it is not smaller move to the right if i rootldown 1 i rootrdown 1 the while loop has searched suffecent time and has not ended string tmp the search incountered a critical error aborting to prevent an endless loop the string error throw tmp is thrown should not happen indicates a broken tree a screen shot of the first encounter with the for loopa screen shot of the second encounter with the for loopif you would note in the autos tab at the bottom that all the data and the node itselfs address is null yet in the next screen shot it continuesthe program continues whati pushed f10 the go to next command button and it jumps right over the statement why,['c++'] +100315,does d have something akin to c0xs move semantics a problem of value types with external resources like stdvectort or stdstring is that copying them tends to be quite expensive and copies are created implicitly in various contexts so this tends to be a performance concern c0xs answer to this problem is move semantics which is conceptionally based on the idea of resource pilfering and technically powered by rvalue referencesdoes d have anything similar to move semantics or rvalue references,['c++'] +100323,why firstchild select all children i want to select only the very first links from dropdown menu the ones with one text but firstchild selects them alinksorry for the mess in the html part but i am customizing wordpress theme and it produces so many classes and idsthe most important thing is at the end of css file,['css'] +100355,how to find gcd lcm on a set of numbers what would be the easiest way to calculate greatest common divisor and least common multiple on a set of numbers what math functions can be used to find this information,['java'] +100372,mkmapview crashing with exc bad access i have the following line of code which activates the breakpointmapview addannotationsgrabinstanceitemarraythis crashing randomly grabinstanceitemarray is fully populated always and is never changing at the time due to this bit of code only being called once the array is full this particular time this was confirmed as 323 items in the arraynszombieenabled does not find anything at all eitherthe backtrace is below and line 1154 is the line above0 0x0126a372 in insert 1 0x0126a312 in splitnode 2 0x0126a3b7 in insert 3 0x011db253 in mkannotationcontainerview addannotation 4 0x011dfc2e in mkannotationcontainerview addannotations 5 0x011b0b30 in mkmapview addannotations 6 0x09257 in bigviewcontroller plotitems self0x614de90 cmd0x16464f at userszdocumentsiphone projectsbigprojectclassesbigviewcontrollerm11547 0x005336c1 in nsnote callback 8 0x01c18f99 in cfxnotificationpost old 9 0x01b9833a in cfxnotificationpostnotification 10 0x00529266 in nsnotificationcenter postnotificationnameobjectuserinfo 11 0x024071 in itemgrabber parserdidenddocument self0x617b540 cmd0x689aa3 parser0xf6b4ab0 at userszdocumentsiphone projectsbigprojectclassesitemgrabberm267,['iphone'] +100384,how to initialize memberstruct in initializer list of c class i have the following class definitions in cstruct foo int x char array24 short yclass bar bar int x foo fooand would like to initialize the foo struct with all its members to zero in the initializer of the bar class can this be done this waybarbar foo x8 or what exactly does the foox do in the initializer listor is the struct even initialized automatically to zero from the compiler,['c++'] +100399,generate c class from xml can i generate a c class from an xml file,"['c#', '.net']" +100409,how can i implement rubys arrayinclude in javascript i have an array temparray kathmandupokharadharan to make sure that pokhara is in temparry i have to use loop and check every element of temparrayis there a way to implement rubys arrayinclude so that i do not need to use a loop,"['javascript', 'ruby']" +100410,what do we need unary function and binary function for i read the tutorials about the binary and unary functions i understood the structure of them but i could not imagine in which case i need these functions can you give an example for usage of them function function,['c++'] +100411,php call to undefined function mb strlen on custom compiled php with mbstring enabled i have this custom compiled php v533 with the following extensions enabled via configureconfigure prefixusrlocalphp533 withconfigfilepathusrlocalapache2conf withapxs2usrlocalapache2binapxs withbz2 withcurlusrlib withcurlwrappers withfreetypedirusrlocal withgdusrlocal withgettext withgmp withiconvusrlocal withimapusrlocalimap2007e withimapssl withjpegdirusrlocallib withkerberos withlibxmldirusrlib withmcryptusrlocal withmhash withmysqlusrlibmysql withmysqlsockvarlibmysqlmysqlsock withmysqliusrlibmysqlmysql config withopensslusr withpcredirusrlocallib withpear withpngdirusrlocallib withreadline withsqlite withxmlrpc withxslusrlocal withzlibdirusrlocallib withzlibusrlocal withoutpgsql enablebcmath enablecalendar enableexif enableembeddedmysqlishared enableftp enablegdjisconv enablegdnativettf enablembstringall enablembregex enableshared enablesockets enablesoap enablesqliteutf8 enablezendmultibyte enablezip thisablepdo thisablephar phpinfo clearly states that mbstring is enabledfunny thing is when i try to run some php scripts sugarcrm updates it reports the following errorphp fatal error call to undefined function mb strlen in crmincludepclzippclziplibphp on line 4165can anyone throw some light into why this is happening and how to fix thisthanksme,['php'] +100430,is there priority queue data structure implementation in rubys standard library does rubys standard library have a priority queue implementation,['ruby'] +100450,inheriting and overriding functions of a stdstring since stdstring is actually a typedef of a templated class how can i override it i want to make a utf8 stdstring that will return the correct length among other things,['c++'] +100471,iterating over a vector in reverse direction i need to iterate over a vector from the end to the beginnig the correct way isforstdvectorsometreverse iterator rit vrbegin rit vrend rit do somethingwhen dosomething involves knowing the actual index then some calculations need to be done with rit to obtain it like index vsize 1 rit vrbeginif the index is needed anyway then i strongly believe it is better to iterate using that indexforint i vsize 1 i 0 i do something with vi and i this gives a warning that i is signed and vsize is unsignedchanging toforunsigned i vsize 1 i 0 i is just functionally wrong because this is essentially an endless loop what is an aesthetically good way to do what i want to do which is warningfreedoes not involve castsis not overly verbosei hope i am not looking for something that does not exist,['c++'] +100476,java sending http parameters via post method easily i am successfully using this code to send http requests with some parameters via get methodfunction void sendrequeststring request ie request param2bparam3c url url new urlrequest httpurlconnection connection httpurlconnection urlopenconnection connectionsetdooutputtrue connectionsetinstancefollowredirectsfalse connectionsetrequestmethodget connectionsetrequestpropertycontenttype textplain connectionsetrequestpropertycharset utf8 connectionconnectnow i may need to send the parameters ie param1 param2 param3 via post method because they are very longi was thinking to add an extra parameter to that method ie string httpmethodhow can i change the code above as little as possible to be able to send paramters either via get or posti was hoping that changingconnectionsetrequestmethodgettoconnectionsetrequestmethodpostwould have done the trick but the parameters are still sent via get methodhas httpurlconnection got any method that would helpis there any helpful java constructany help would be very much appreciated,['java'] +100477,django apache mod wsgi having to restart apache after changes i configured my development server this wayubuntu apache mod wsgi python 26i work on the server from another computer connected to itmost of the times the changes do not affect the application unless i restart apachein some cases the changes take effect without restarting the webserver but after let us say 3 or 4 page loads the application might behave like it used to behave previous to the changesuntil now i just reloaded everytime apache as i have the development server here with me but hell after a while got so annoying how can i avoid thisi cannot work with the development server as i need an environment that is as close as possible as the production onethanks,['python'] +100486,what do i need to install to get microsoftteamfoundationworkitemtrackingclientdll do i simply need to install the vs2010 sdk is there such a thing as the tfs2010 sdk and if so would that be the thing i need to install and if so where can i get it on microsofts extend visual studio web site i saw a link to example code for the tfs 2010 sdk but i could not find the tfs 2010 sdk itselfthe reason i am asking i am building a codebase that is not mine which depends on microsoftteamfoundationworkitemtrackingclientdll,['.net'] +100490,control flow graph generator for c code i need a tool that takes c code and generate the control flow graph of the codeif there is something like this in visual studio do please point it out to methanks,['c#'] +100499,c questions about function pointers i have written the following codeinclude stdafxhinclude iostreamusing namespace stddouble funca return 10int gdouble pf cout pf endl return 0int g2double pf cout pf endl return 0int tmainint argc tchar argv gfunca case i gfunca case ii g2funca case i g2funca case iv return 0i have run the above code on vs2008 and each function call returns 100here is the questionq1 is there any problem in the codeq2 it seems that c does not make difference between pf and pf is that correctthank you,['c++'] +100518,spring transactional and hibernate lazy loading i am using spring hibernate all my hibernatedao use directly sessionfactoryi have application layer service layer dao layer and all collections is lazly loadedso the problem is that sometime in the application layerthat contains guiswing i load an entity using a service layer methodthat contains transactional annotation and i want to use a lazly property of this object but obviusly the session is already closedwhat is the best way to resolve this troubleediti try to use a methodinterceptor my idea is to write an aroundadvice for all my entities and use annotation so for example custom annotation say that session is required for this methodtargetelementtypemethodretentionretentionpolicyruntimepublic interface sessionrequired an aroundadvice to intercept method callspublic class sessioninterceptor implements methodinterceptor public object invokemethodinvocation mi throws throwable bool sessionrequiredmigetmethodisannotationpresentsessionrequiredclass begin and commit session only if sessionrequired ifsessionrequired begin transaction here object retmiproceed ifsessionrequired commit transaction here return ret an example of entityentitypublic class customer implements serializable id long id onetomany listorder orders this is a lazy collection sessionrequired public listorder getorders return orders and finally in application layerpublic void foo load customer by id getcustomer is annotated with transactional this is a lazy load customer customercustomerservicegetcustomer1 get orders my interceptor open and close the session for me i hope listorder orderscustomergetorders finally use the ordersdo you think can this workthe problem is how to register this interceptor for all my entities without do it in xml filethere is a way to do it with annotation,['java'] +100529,what exception is thrown when key is not found in python dictionary if i havemap stackoverflow try mapexpertsexchangeexcept what is the exception type that is thrown here print is not free could not find it on the web,['python'] +100531,how do i restart a phusion passenger standalone have to do passenger stop then startor i can still do this by touching tmprestarttxt,['ruby-on-rails'] +100533,android how do i prevent the soft keyboard from pushing my view up i have a vertical sliding drawer at the bottom of my app when the soft keyboard opens it pushes the tab for the drawer up so it sits atop the keyboard i actually want it to remain at the bottom of the screen becoming hidden when the keyboard is shown anyone else run into this issue know how to fix it,['android'] +100538,magento how can i migrate configuration changes from development to production environment we are actively developing modules and when we push the changes to our production site there are usually several configuration changes we need to make would be nice to automate thisthoughts,['php'] +100550,xmlhttprequest origin null is not allowed accesscontrolalloworigin for file to file serverless i am trying to create a website that can be downloaded and run locally by launching its index fileall the files are local no resources are used onlinewhen i try to use the ajaxslt plugin for jquery to process an xml file with an xsl template in sub directories i receive the following errorsxmlhttprequest cannot load filecpathtoxsl20websitedatahomexml origin null is not allowed by accesscontrolalloworiginxmlhttprequest cannot load filecpathtoxsl20websiteassetsxslmainxsl origin null is not allowed by accesscontrolalloworiginthe index file making the request is filecpathtoxsl20websiteindexhtml while the javascript files used are stored in filecpathtoxsl20websiteassetsjshow can i do to fix this issue,['jquery'] +100555,how to detect user inactivity in android user start myapp and logs inselects session timeout to be 5 minsdoes some operations on the appall in foregroundnow user bring myapp to background and starts some other app count down timer starts and logs out user after 5 minsor user turns the screen off count down timer starts and logs out user after 5 minsmy questioni want this same behavior even when the app is in the foreground but user does not interact with the app for a longtime say 67 mins assume the screen is on all the time i want to detect kind of user inactivity no interaction with app even though the app is in the foreground and kick start my count down timerthanks in advance,['android'] +100562,call derived class method from base class reference class materialpublic void foo cout class material class unusual material public materialpublic void foo cout class unusual material int main material strange unusual material strangefoo outputs class material return 0i would like for this to result in the class unusual material being thisplayed to the console is there a way i can achieve this in my program i have a class material from which other more specific materials are derived the method materialfoo represents a method in material that is adequate for most materials but occationally another foo needs to be defined for a material with unusual properties all objects in my program contain a material field in the event that they are assigned an unusual material i would like the derived unusual foo to be calledthis is probably either pretty easy or impossible but i cannot figure it out either waythanks,['c++'] +100567,using generic types in a static context public static btnodee treecopybtnodee source ifsource null return null else btnode left btnodetreecopysourceleft btnode right btnodetreecopysourceright return new btnodesourcedata left right my questions is why cannot i use the generic type e in a static context i tried search for several answers could not find any that make snese,['java'] +100569,removing dollar signs from prices i am building a string of amounts but need to remove the dollar signs i have this jquery code buildlistproductpriceid productitemcell pricelistit is returningpricelist150019502950i need to remove the dollar signs but cannot seem to figure it out tried using trim but i think that removes only white spacesorry for the newbie question thanks in advance for any helpheres the full codefunction buildlistitems name var values itemseachfunction valuespushthisvalue thistextreturn name valuesjoinvar result buildlistproductcodeid productitemcell skulistbuildlistproductquantityid productitemcell input quantitylistbuildlistproductpriceid productitemcell pricelistvar string resultjoinhere is the raw code before the javascript runsspan classproductpriceiddiv classproductitemcell1500divdiv classproductitemcell1950divdiv classproductitemcell2950divspan,['javascript'] +100572,add a delay to progress dialog i want to make a dummy progress dialog appear for 2 or 3 seconds it would not actually do anything other than say detecting i have the code progressdialog dialog progressdialogshowthis detecting true dialogshow dialogthismissbut what do i put in between the show and the thismissal to have the dialog appear for a few seconds thanks,['android'] +100576,play framework best practice to use urls in separate javascript files i am currently reorganizing a play project where there is a lot of jscode in the html template files this code should be moved to externaljs files for better readability and faster page loading times howeverwhen i just create a js file in the public folder all thecontrollermethod link replacements are no longer working i wasthinking about calling some initialization function from the htmltemplates which just supplies the required urls likeinitialize applicationdothis applicationdothishowever this is becoming very cumbersome and errorprone with any urlthat is added another thing is that the i18n also no longer works sowhat is the best practice for scenarios like these where you have yourjs code in a separate file but still want to use url generation andi18n in your js,['javascript'] +100586,validate an ip address with mask i have ip addresses and a mask such as 10132 i would like to check if 101 is inside that range is there a library or utility that would do this or do i need to write something myself,['java'] +100593,getting data from cells in slickgrid what method do i use for slickgrid to get the cell contents for examplegrid new slickgridmygrid data columns optionsgridonaddnewrow functionitemcoldef gridremoverowdatalength datapushitem gridupdaterowcount gridrendergridoncurrentcellchanged functionargs get cell contentthanks in advance,"['javascript', 'jquery']" +100594,safely parsing a json string with unquoted keys json2js is strict requiring all object keys be doublequoted however in javascript syntax foobar is equivalent to foobar i have a textarea that accepts json input from the user and would like to ease the restriction on double quoting the keys i have looked at how json2js validates a json string in four stages before it evals it i was able to add a 5th stage to allow unquoted keys and would like to know if there are any security implications to this logicvar data namehello age23 make sure the incoming data is actual json logic borrowed from if stestdatareplacebfnrtu09afaf4g replacenrtruefalsenullddeedg replacesg edited allow keyarray by replacing with safe char everything up to this point is json2js this is the 5th stage where it accepts unquoted keys replacewsg edited allow any alphanumeric key consolelog new functionreturn data else throw invalid json data,['javascript'] +100596,allow users to create forms within android surveydata collection app i am trying to develop an android app that could be used by advocacy groups or campaigners such that they would be able to create their own forms surveys for which they can go out canvassing and collect opinion data from people who do not have internet connections and thus cannot take surveyspolls online could also be used at events or anything else that requires data collection in the fieldthe benefit is allowing data collection on the spot without having to transfer data from paper to the office computer by handi have been looking over this tutorial by frank abelson and have also been pouring through the open data kit but the odk is a little more intense than i am prepared for and the abelson tutorial does not thiscuss much how users could create their own formsi suppose users could just create their own xml files for custom forms in the office and store them on the server but i was wondering if there was a way for them to do this on the android appjust a hint about possible architecture or simple resources would be helpful i am having a hard time picturing the solution at the moment,['android'] +100602,looping on c iterators starting with second or nth item i am looking for a readable elegant way to do the following in c here shown in pythonfor datum in data1 do workthe iterators on the data in question may not support random access iterators so i cannot just usefor miter databegin 1 miter dataend miterthe best i have come up with is the followingiterableiterator miter databeginfor miter miter allmjdsend mjditer do workit is not too lengthy but it is hardly expository at first glance it actually looks like a mistakeanother solution is to have an nth element helper function i guess any cooler ideas,['c++'] +100610,how do i use xml namespaces with findfindall in lxml i am trying to parse content in an openoffice ods spreadsheet the ods format is essentially just a zipfile with a number of documents the content of the spreadsheet is stored in contentxml import zipfilefrom lxml import etreezf zipfilezipfilespreadsheetodsroot etreeparsezfopencontentxmlthe content of the spreadsheet is in a celltable rootfindurnoasisnamestcopendocumentxmlnstable10tablewe can also go straight for the rowsrows rootfindallurnoasisnamestcopendocumentxmlnstable10tablerowthe individual elements know about the namespaces tablensmaptableurnoasisnamestcopendocumentxmlnstable10how do i use the namespaces directly in findfindall the obvious solution does not work trying to get the rows from the table rootfindalltabletabletraceback most recent call last file stdin line 1 in module file lxmletreepyx line 1792 in lxmletree elementtreefindall srclxmllxmletreec41770 file lxmletreepyx line 1297 in lxmletree elementfindall srclxmllxmletreec37027 file usrlibpython26thistpackageslxml elementpathpy line 225 in findall return listiterfindelem path file usrlibpython26thistpackageslxml elementpathpy line 200 in iterfind selector build path iteratorpath file usrlibpython26thistpackageslxml elementpathpy line 184 in build path iterator selectorappendopstoken0 next tokenkeyerror,['python'] +100620,examplesillustration of waitfree and lockfree algorithms i have read that waitfree causes all threads to finish independently and lockfree ensures the program as a whole completes i could not quite get it can anyone give an example java illustrating thisedit does lockfree mean a program without deadlock,['java'] +100626,php caseinsensitive parameters how do i accept passed get or post values case insensitivelylike samplephporderbyasc will still be the same as samplephporderbyasc or samplephporderbyascis there a means of achieving the above efficiently,['php'] +100654,get the current language in device how can we get the current language selected in the android device,['android'] +100720,problem casting stl complex to fftw complex the fftw manual says that its fftw complex type is bit compatible to stdcomplexdouble class in stl but that does not work for meinclude complexinclude fftw3hint main stdcomplexdouble x10 fftw complex fx fx reinterpret castfftw complexxthis gives me an errorerror invalid cast from type astdcomplexdoublea to type adouble 2awhat am i doing wrong,['c++'] +100725,firebug how to see attached events of an object i have attached some events to some divs using addeventlistener but where can i see the events in firebug,['javascript'] +100729,could not create the driver from nhibernatedriversqlite20driver heres the code that raises the exception public configuration getconfiguration var persister sqliteconfiguration standard usingfiletestdb showsql var configuration fluently configure databasepersister mappingsmap mapfluentmappingsaddfromassemblyofwordmap buildconfiguration new schemaexportconfigurationexecutetrue true false return configuration the full exception text failure nhibernatehibernateexception could not create the driver from nhibernatedriversqlite20driver nhibernate version21240 cultureneutral publickeytokenaa95f207798dfdb4 systemreflectiontargetinvocationexception exception has been thrown by the target of an invocation nhibernatehibernateexception the idbcommand and idbconnection implementation in the assembly systemdatasqlite could not be found ensure that the assembly systemdatasqlite is located in the application directory or in the global assembly cache if the assembly is in the gac use element in the application configuration file to specify the full name of the assemblyversion of nhibernate is 21240version of systemdatasqlite is 10660target framework is 35 x86local copy for systemdatasqlite is onwhat may be wrong,['c#'] +100743,good uses of the finalize method this is mostly out of curiosityi was wandering if anyone has encountered any good usage for objectfinalize except for debuggingloggingprofiling purposes if you have not encountered any what would you say a good usage would be,['java'] +100747,record and play audio simultaneously any one help to me to record and play audio simultaneously in iphone,"['iphone', 'objective-c']" +100811,how to cout the correct number of decimal places of a double value i need help on keeping the precision of a double if i assign a literal to a double the actual value was truncatedint main double x 740200133400 stdcout x nfor the above code snippet the output was 7402is there a way to prevent this type of truncation or is there a way to calculate exactly how many floating points for a double for example number of decimalx would give 11 since the input is unknown at runtime so i cannot use setprecisioni think i should change my question tohow to convert a double to a string without truncating the floating points ie include iostreaminclude stringinclude sstreamtemplatetypename tstdstring type to string t data stdostringstream o o data return ostrint main double x 740200 stdcout type to string x nthe expected output should be 740200 but the actual result was 7402 so how can i work around this problem any idea,['c++'] +100815,convert html to nsattributedstring in ios i am using a instance of uiwebview to process some text and color it correctly it gives the result as html but rather than thisplaying it in the uiwebview i want to thisplay it using core text with a nsattributedstring i am able to create and draw the nsattributedstring but i am unsure how i can convert and map the html into the attributed stringi understand that under mac os x nsattributedstring has a initwithhtml method but this was a mac only addition and is not available for iosi also know that there is a similar question to this but it had no answers i though i would try again and see whether anyone has created a way to do this and if so if they could share it,"['iphone', 'objective-c']" +100827,prebuffering for avqueueplayer does anyone know if avqueueplayer starts buffering the next avplayeritem when the current item is about to finish playingi know there is nothing in the docs to suggest this i am asking mostly if anyone has observed this kind of behavior or not,"['iphone', 'objective-c']" +100846,how to do a like caseinsensitive and accent insensitive in oracle 10gr2 and jpa in a j2ee project using jpa how can i force a like query to be case insensitive and accent insensitivei know about changing session variables nls comp and nls sort but i am wondering if there is another trick to do this in the query itself without changing session variables,['java'] +100855,how to restore sql server database through c code i try to restore the database like thissql restore database mydatabase to thiskdmydataback cmd new sqlcommandsql conn cmdexecutenonquery cmdthisposebut i always get errormsg 3102 level 16 state 1 line 7 restore cannot process database mydatabase because it is in use by this session it is recommended that the master database be used when performing this operation msg 3013 level 16 state 1 line 7 restore database is terminating abnormally,['c#'] +100861,aspnet button click w javascript are you sure prior to post back i have a aspbutton that will fire a delete and want to have a client side javascript are you sure popup prevent any accidentswhats the javascript to handle this,"['javascript', 'asp.net']" +100881,warning mysql connect 2002 no such file or directory trying to connect via unixtmpmysqlsock in i am trying to connect to my mysql db with the terminal on my apple with phpyesterday it worked fine and now i suddenly get this error see title i have no clue how to solve it i have spend all my free time trying today the script works when i use my browser to run it i have xampp installed but terminal refuses to connect to the dbher eis the file that i include to connect script works when i do not include this but then it does not connect to the dbphp mysql connectlocalhost root or diemysql error mysql select dbfnb1c data or diemysql errorthat should be right since with my browser i can connect when i run the script the command i use is php scriptnamephp,"['php', 'mysql']" +100893,begun learning opengl need help figuring out this problem so i have begun learning opengl reading from the book opengl super bible 5 ed it is explains things really well and i have been able to create my first gl program myself just something simple a rotating 3d pyramid now for some reason one of the faces are not rendering i checked the vertecies plotted it on paper first and it seemed to be right found out if i changed the shader to draw a line loop it would render however it would not render a triangle can anyone explain whyvoid setuprc glclearcolor00f 00f 00f 10f shadermanagerinitializestockshaders m3dvector3f vverts1 05f00f05f00f05f00f05f00f05f m3dvector3f vverts2 05f00f05f00f05f00f05f00f05f m3dvector3f vverts3 05f00f05f00f05f00f05f00f05f m3dvector3f vverts4 05f00f05f00f05f00f05f00f05f trianglebatch1begingl line loop 3 trianglebatch1copyvertexdata3fvverts1 trianglebatch1end trianglebatch2begingl triangles 3 trianglebatch2copyvertexdata3fvverts2 trianglebatch2end trianglebatch3begingl triangles 3 trianglebatch3copyvertexdata3fvverts3 trianglebatch3end trianglebatch4begingl triangles 3 trianglebatch4copyvertexdata3fvverts4 trianglebatch4end glenablegl cull facefloat rot 1void renderscene glcleargl color buffer bit gl depth buffer bit gl stencil buffer bit glfloat vred 10f 00f 00f 05f glfloat vblue 00f 10f 00f 05f glfloat vgreen 00f 00f 10f 05f glfloat vwhite 10f 10f 10f 05f m3dmatrix44f transformmatrix if rot 360 rot 0 else rot rot 1 m3drotationmatrix44transformmatrixm3ddegtoradrot00f10f00f shadermanagerusestockshaderglt shader flat transformmatrix vred trianglebatch1draw shadermanagerusestockshaderglt shader flat transformmatrix vblue trianglebatch2draw shadermanagerusestockshaderglt shader flat transformmatrix vgreen trianglebatch3draw shadermanagerusestockshaderglt shader flat transformmatrix vwhite trianglebatch4draw glutswapbuffers glutpostrethisplay sleep10,['c++'] +100913,what is the difference betwen boostmulti array views and subarrays after looking the documentation i cannot figure this one outi can write code such astypedef boostmulti arrayboostint32 t 3 data t 3d typedef data tarray view3type data 3d view t 2d typedef data 3d view treference data 2d subarray ttypedef data tarray view2type data 2d view tthen i can access a 2d slice using via the types data 2d subarray t or data 2d view twhat is the difference between them what can i do with one that i cannot do with the other is it there any performance difference thanks a lot for clarifying this to mebest regardsrodrigob,['c++'] +100931,how to change currenttime for unit testing date functions in php how do i change the current time ie the output of time in php for unittesting datemanipulationclass,['php'] +100943,how to put my javascript in the footer i just want to ask on how to print script javascript at the footer using simple plugin i am using wordpress 30 any ideas,['javascript'] +100948,validate vs validates associated there is a validate specifier that can be directly used on the association see 41212 at this rails guide and also a validates associated see 32 at that rails guidewhere do both differ,['ruby-on-rails'] +100966,sorting a json object in javascript i have been looking for a while to sort a json object like thisresults layerid 5 layername pharmaceutical entities attributes objectid 35 facilitytype pharmacy facilitysubtype 24 hr pharmacy commercialname e sadd maarab pharmacy geometrytype esrigeometrypoint layerid 5 layername pharmaceutical entities attributes objectid 1 facilitytype pharmacy facilitysubtype 24 hr pharmacy commercialname e gayathy hospital pharmacy geometrytype esrigeometrypoint layerid 5 layername pharmaceutical entities attributes objectid 255 facilitytype pharmacy facilitysubtype 24 hr pharmacy commercialname e al dewan pharmacy geometrytype esrigeometrypoint alphabetically by value of commercialname e to getresults layerid 5 layername pharmaceutical entities attributes objectid 255 facilitytype pharmacy facilitysubtype 24 hr pharmacy commercialname e al dewan pharmacy geometrytype esrigeometrypoint layerid 5 layername pharmaceutical entities attributes objectid 1 facilitytype pharmacy facilitysubtype 24 hr pharmacy commercialname e gayathy hospital pharmacy geometrytype esrigeometrypoint layerid 5 layername pharmaceutical entities attributes objectid 35 facilitytype pharmacy facilitysubtype 24 hr pharmacy commercialname e sadd maarab pharmacy geometrytype esrigeometrypoint i cannot find any code that will do this can anyone give me some help,['javascript'] +100974,how to use jquery to select the nth option i have the following htmlselect onchangethisformsubmit namename option value95101e0117201044055pm95101e0117201044055pmoption option valuegrrexamplegrrexampleoption option valueadminadminoption option value123w123woptionselectmay i know how i can use jquery to option with value adminthanks,"['javascript', 'jquery', 'html']" +100978,method that accept and number of parameters in c i am developing an windows application oftentimes i need to clear the textboxes whenever the user save the record or click on clear buttoncurrently i am using this code txtboxnametextstringempty for each textboxso can it be possible to write a method that accept the and number of parameterlike reading the all the textboxes in an array and using foreach we can clear themthe main requirement is to write a method which accept the and number of parameterie the parameter size will be unknownif any body having idea about how to do this then please help methanks in advance,['c#'] +100990,c not catching unhandled exceptions from unmanaged c dll i have got an unmanaged c dll which is being called from a c app i am trying to get the c app to catch all exceptions so that in the event of the dll failing due to an unmanaged exception then the user will get a halfdecent error message the c app is a web service implementing it is own http handlerthe problem i have is that not all types are being caught so if i create the following and execute the c app then the dll throws an error and the entire application terminates any ideasthis is being created in vs2005 and using net framework v2c testhifndef inc test hdefine inc test hextern c declspecdllexport void processbadcallendifc testcppinclude iostreaminclude vectorusing namespace stdvoid processbadcall vectorint myvalues int a myvalues1 cout a endlc programcsclass program dllimporttestdll entrypointprocessbadcall static extern void processbadcall static void mainstring args try processbadcall catch sehexception ex consolewritelineseh exception 0 exmessage catch exception ex consolewritelineexception 0 exmessage the dll is being compiled under the release configuration with the following compiler flagso2 gl d win32 d ndebug d crt secure no warnings d unicode d unicode d windll fd eha md forelease fdreleasevc80pdb w4 wx nologo c wp64 zi tp errorreportprompt,"['c#', 'c++']" +101001,the ultimate cleansecure function i have a lot of user inputs from get and post at the moment i always write mysql real escape string getvari would like to know whether you could make a function that secures escapes and cleans the get post arrays right away so you would not have to deal with it each time you are working with user inputs and suchi was thinking of an function eg cleanmeinput and inside it it should do mysql real escape string htmlspecialchars strip tags stripslashes i think that would be all to make it clean secure and then return the inputso is this possible making a function that works for all get and post so you would do only this get cleanme get post cleanme postso in your code later when you work with eg getblabla or posthaha they are secured stripped and so ontried myself a littlefunction cleanmeinput input mysql real escape stringinput input htmlspecialcharsinput ent ignore utf8 input strip tagsinput input stripslashesinput return input,['php'] +101018,idea for resolving implicit includes in c c i have just came up with an idea to solve a problem and wanted to share it sorry if too banalso a big c project i am reviewing contains many includes which relies on symbols from other includes but which do not include the required includes any slight change in buildprocedure results in missing symbol failuresso in order to check all includes for selfcontainment at once i search for all h create on the fly a cppfile which only contains include statement with this h file and try to compile it at the end i obtain a list of good and bad include filescool is not it or is there an easier solution to do it,"['c++', 'c']" +101021,can you do greater than comparison on a date in a rails 3 search i have this search in rails 3notewhereuser id current userid notetype pnote type date pdateorderdate asc created at ascbut i need the date pdate condition to be equivilent to date pdate how can i do this thanks for reading,['ruby-on-rails'] +101034,jquery save json data object in cookie how do i save json data in a cookiemy json data looks like thisarticlesholderdata15 nametestname nr4price400articlesholderdata25 namename2 nr1 price100articlesholderdata37 namename3 nr14 price60and i want to do something likevar datastore cookiebasketdata articlesholderdataand to retrieve the data i want to load it into articlesholder likeeachcookiebasketdata functionie articlesholderdatai edoes anyone know if i am on the right track or should this be done in some other way simply put how do i put and pull json data from a cookie,['jquery'] +101060,c ping a website keepalive service is there a way in c to be able to ping a url every 15 minutes and get a response back from the serveri want to try to see if net can be used to build a simple tool to have aspnet websites invoke a rebuild so that the first user does not incur the load penalty when the application is startedor if anyone has an alternative method of accomplishing the same goalthoughts tips ideas,"['c#', 'asp.net']" +101063,large draggable item into small droppable container it works but it is a little problematic when there are multiple small droppable areas near each other 15x15px and i want to drop a 150x150px draggable item in a correct container it is very difficult to get it rightis there a way to make the draggable item drop at a current cursor positioni could then use cursorat to specify the cursor to be outside the draggable item and it would be easy to aim it to correct droppable area,['jquery'] +101069,ampersand character inside a value of jquery ajax request data option i am performing asynchronous http ajax requests via jquery with the basic ajax the code looks like the followingtextareablurfunction var thisid thisattrid var thisvalue thisval ajax type post url somephp data id thisid value thisvalue success function alert saved successfully everything is working properly as usual until user types inside textarea ampersand character than when i debug php function which saves the value it always have a value until this characteri believe there has to be a solution to skip ampersand somehow any ideas,['jquery'] +101075,oncreateview being called too often in custom preference i have created a custom preference which has the following constructorpublic coordinatespreferencecontext context attributeset attrs supercontext attrs setlayoutresourcerlayoutcoordinates preferenceand i have overriden oncreateview so it writes to the log like thisoverrideprotected view oncreateviewviewgroup parent logdtest creating preference view return superoncreateviewparentand my log is full of creating preference view messages this creates a laggy feel to scrolling and i believe convert view is supposed to solve this i had a look at the preference source code and if convert view is null then oncreateview is calledfor testing purposes i added this methodoverridepublic view getviewview convertview viewgroup parent if convertview null return supergetviewconvertview parent return supergetviewconvertview parentand set a break point i have found that almost always my convert view is null and therefore it must create a new view why is this and how can i improve this to avoid a laggy preference screenedit changed the way the oncreate is called now its all android i just use setlayoutresource but this does not solve the problemedit2 i have used debugstartmethodtracing and have found as i suspected that 55 of the time spend when i am just scrolling up and down is spend on the inflation of the preference from the method oncreateview which is called from getview when convertview is nullthanks jason,['android'] +101084,can i do an atomic merge in oracle i have a couple instances of a j2ee app running in a single weblogic clusterat some point these apps do a merge to insert or update a record into the backend oracle database the merge checks to see if a row with a specified primary key is there or not if it is there update if not insertnow suppose two app instances want to insert or update a row with primary key 100 suppose the row does not exist during the check stage of merge they both see that the rows not there so both of them attempt to insert then i get a unique key constraint violationmy question is this is there an atomic merge in oracle i am looking for something that has a similar effect to insert for update in plsql except that i can only execute sql from my appsedit i was unclear i am using the merge statement while this error still occurs the thing is only the modifying part is atomic not the whole merge,['java'] +101087,type safer bitflags in c while revising some old c code i ran across several bitflags defined as enumsenum fooflags fooflag1 1 0 fooflag2 1 1 fooflag3 1 2 etcthis is not uncommon but it bothered me that as soon as you start to combine flags you lose the type informationint flags fooflag1 fooflag2 weve lost the information that this is a set of flags relating to foosome searching on so showed that i am not the only one bothered by thisone alternative is to declare flags as defines or const integrals so bitwise operations wouldnt transform the type probably the problem with this is it allows our bit set to commingle with unrelated flags via ints or other enumsi am familiar with stdbitset and boostdynamic bitset but neither are designed to address my issue what i am looking for is something like cs flagsattributemy question is what other solutions are there for a more type safe set of bitflagsi will post my own solution below,['c++'] +101089,how to save a graphic created by coreplot to a jpg file i am using coreplot to draw different graphs in my application then i would like to save this graph to a jpg file and publish to some social networking site eg twitteri did some documentation reading and understood that the following methods could be useful for mecgbitmapcontextcreateimage creating a cgimage as a copy from a bitmap graphics context ie the view where my graph is situated or the whole screen have i understood rightcgimagecreatewithimageinrect i can clip out some part of the image if neededuiimage imagewithcgimage converting cgimage to an uiimage objectuiimagejpegrepresentation converting my uiimage object to a jpg nsdata object which then i can share to my social networkthe first question is have i understood right the sequence of operations i have to carry out to accomplish my task i would have tried it out myself but i have got a problem which leads to the second question from where do i get the graphics context info to pass into cgbitmapcontextcreateimage if i am using coreplot sorry if it is a dumb question but i am not really at home with graphics contextsthanks a lot for any help in advance and if i get with all this somewhere i promise to post my code sample herewell thanks to brad it was really easy but as i promissed i have to post the linescpxygraph graphcpxygraph allocinitwithframecgrectmake0 0 100 100 setting up the graph uiimage newimagegraph imageoflayernsdata newpnguiimagepngrepresentationnewimage or you can use jpg or pdf for test purposes i write the file to the documents directory but you can do whatever you want with your new png filensstring filepathnsstring stringwithformatgraphpng nssearchpathfordirectoriesindomainsnsdocumentdirectory nsuserdomainmask yes lastobjectifnewpng writetofilefilepath atomicallyyes nslogcreated new file successfully,['iphone'] +101121,fast way to read interleaved data i have got a file containing several channels of data the file is sampled at a base rate and each channel is sampled at that base rate divided by some number it seems to always be a power of 2 though i do not think that is importantso if i have channels a b and c sampled at divders of 1 2 and 4 my stream will look likea0 b0 c0 a1 a2 b1 a3 a4 b2 c1 a5 for added fun the channels can independently be floats or ints though i know for each one and the data stream does not necessarily end on a power of 2 the example stream would be valid without further extension the values are sometimes big and sometimes littleendian though i know what i am dealing with upfronti have got code that properly unpacks these and fills numpy arrays with the correct values but it is slow it looks something like hope i am not glossing over too much just giving an idea of the algorithmfor sample num in rangetotal samples channels to sample ch for ch in all channels if chsamples forsample num format str build format string from channels to sample data structunpack my fileread read and unpack the data iterate over data tuple and put values in channels to sample for val ch in zipdata channels to sample chdatasample num chdivider valand it is slow a few seconds to read a 20mb file on my laptop profiler tells me i am spending a bunch of time in channelsamples for which makes sense there is a bit of conditional logic theremy brain feels like there is a way to do this in one fell swoop instead of nesting loops maybe using indexing tricks to read the bytes i want into each array the idea of building one massive insane format string also seems like a questionable road to go downupdatethanks to those who responded for what it is worth the numpy indexing trick reduced the time required to read my test data from about 10 second to about 02 seconds for a speedup of 50x,['python'] +101135,efficient c pool allocator i am currently attempting to write a 2d scene graph in c and i need to decide on a way of storing the child nodes i am expecting very many reads and few writes so a linked list is out of the question due to poor spatial locality of reference and using realloc every time to add a child node would probably fragment the free list into oblivion a pool allocator seems to be the best solution but i cannot seem to find any implementations to use does anyone know of an allocator that would efficiently handle randomish allocations and deallocations of a few hundred small structs or perhaps a better allocation scheme,['c'] +101138,pil thumbnail is rotating my image i am attempting to take large huge images from a digital camera and convert them into something that i can thisplay on the web this seems straightforward and probably should be however when i attempt to use pil to create thumbnail versions if my source image is taller than it is wide the resulting image is rotated 90 degrees such that the top of the source image is on the left of the resulting image if the source image is wider than it is tall the resulting image is the correct original orientation could it have to do with the 2tuple i send in as the size i am using thumbnail because it appears it was meant to preserve the aspect ratio or am i just being completely blind and doing something dumb the size tuple is 1010 because i want the longest side to be shrunk to 10 pixels while keeping ar preservedcode seems simpleimg imageopenfilenameimgthumbnail1010 imageantialiasimgsaveoutput fname jpegthanks in advance for any help,['python'] +101155,error please use the md switch for afxdll builds i encountered an error in visual studio please use the md switch for afxdll buildsso if i undefine the afxdll will my program go wrong,['c++'] +101159,producing latex output in java is there a java library for producing latex output from java,['java'] +101172,string from edittext to float i have an edittext for which will be using for a float number so i am trying to read the text from the edittext and put it into a float variable but i seem to have a text to float problem this is the line i havefloat number edittext findviewbyid ridedit float gettexti have tried using floatparsefloatstring and just general casting but nothing seem to do it what can i do here also is there a way to check for a valid float number before writing it to a variable,"['java', 'android']" +101177,datagridviewcombobox how to allow any value i am having some trouble with visualstudio 2010 c winformsi have created a datagridview with an unbound column that is of type datagridviewcomboboxcolumn the column works fine except unlike a normal combobox i cannot seem to type in just any value i am forced to pick a value from the listis there a property i need to set or another type i can use that will allow me to enter any value in the cell in addition to providing a list to pick a value fromthanks,['c#'] +101180,c algorithm to calculate least common multiple for multiple numbers is there a c algorithm to calculate the least common multiple for multiple numbers like lcm3612 or lcm57912,['c++'] +101183,creating a 2d matrix in python i create a 6x5 2d array initially with just none in each cell i then read a file and replace the nones with data as i read them i create the empty array first because the data is in an undefined order in the file i am reading my first attempt i did thisx none56which resulted in some weird errors that i now understand is because the operator on lists may create references instead of copiesis there an easy one liner to create this empty array i could just do some for loops and build it up but that seems needlessly verbose for python,['python'] +101188,replacing rn newline characters after running json encode so when i run json encode it grabs the rn from mysql aswell i have tried rewriting strings in the database to no avail i have tried changing the encoding in mysql from the default latin1 swethish ci to ascii bin and utf8 bin i have done tons of str replace and chr10 chr13 stuff i do not know what else to say or do so i am gonna just leave this herejson json encodenewifisset getpretty echo str replace jsonreadableparsejson else json str replace jsonecho parsejsonthe jsonreadable function is from here and the parse function is from here the str replaces that are already in there are because i am getting weird formatted html tags like h1 finally new is an array which is crafted above full code upon requesthelp me stackoverflow youre my only hope,"['php', 'mysql']" +101192,sql server 2008 how do i thisconnect everyone from my db i need to rename the database but i cannot since other processes is using it i do not care about the process and i need to kill it how do i remove all connections from the db,['sql'] +101198,what is the proper way to detect if code is running on the main thread in objectivec ios my code needs to guarantee a certain operation run on the main thread but calls may come from background threadsto detect situations in the background i was using the following voidselectortoruninmainthreadidarguments push to main thread if nsrunloop currentrunloop nsrunloop mainrunloop self performselectoronmainthreadselectorselectortoruninmainthread withobjectarguments waituntildoneno return function content this works on ios 4 and ios 32 but not on ios 313 and earlier in these earlier versions the function will keep getting called in an endless loopchanging the comparison toif nsrunloop currentrunloop isequaltonsrunloop mainrunloophas no effect they still never compare to the same valuei found a solution that appears to be working but i would like to see what other people suggest first,"['iphone', 'objective-c', 'ios']" +101242,an implementation problem of f seq i am digging into f source code recently in seqfs binding we use a type defintion to apply a local dynamic optimization we automatically rightassociate binding ie push the continuations to the right that is bindg bindg g1 cont1 cont2 bindg g1 cont1 o cont2 this makes constructs such as the following linear rather than quadratic let rec rwalk and if and 0 then yield rwalk n1 yield and after seeing the above code i tested two codelet rec rwalk and seq if and 0 then yield n yield rwalk n1 andlet rec rwalk and seq if and 0 then yield rwalk n1 yield and i found the first one is very fast while the second is very slow if and 10 it costs 3 seconds on my machine to generate this sequence thus quadratic time the quadratic time is reasonable as egseq yield 1 2 n1 yield and translates to seqappend 1 2 n1 nthis append operation should take linear time i guess while in the first code the append operation is like this seq yield n yield n1 n2 1 which costs constant timethe the comments in code say that it is linear maybe this linear is not linear time maybe this linear relates to using customized implementation for sequence rather than moandf computation expression as mentioned in f specification however the specification does not mention the reason for doing so could anyone clarify the fuzziness here thanks a lotps because this is a language design and optimization problem i also attached haskell tag to see if people there have insights,['.net'] +101255,jqgrid reload grid it is an addition for previous my question about adding columns into jqgridbased table here my new jscodevar col names first second third fourth fifthvar col model nameinvid indexinvid width100 nameinvdate indexinvdate width90 nameamount indexamount width80 alignright nametax indextax width80 alignright nametotal indextotal width80 alignright function creategrid var handle listjqgrid urldataxml datatype xml mtype get colnames col names colmodel col model now i call creategrid after document is loaded everything works fine now i want to add a new column with empty data and reload jqgrid add columnclickfunction listtriggerdestroygrid also tried unloadgrid col namespushnew col modelpushname test index test width 100 creategrid and recreate grid but nothing happens whyupd add columnclickfunction col namespushnew col modelpushname test index test width 100 listtriggerreloadgrid the same situationupd2i tried theseajaxgridoptions cache falseloadoncefalsedid not change the situation,['javascript'] +101271,where are the gems when ruby compiled manually in mac os x 1068 i manually built ruby 192 on snow leopard now i canat find my old gem files iam guessing they are in a different path now or something so i have three questionswhat is the old gem path where gem install sinatra puts the sinatra gemwhat is the new gem path which is set when i build ruby manuallyhow do i change it so ruby finds my gems again,['ruby'] +101284,android get response from a https url greetingsi am developing an android app and need to open a url with post parameters over https and get the responsethere is the added complication that i have a selfsigned certificate i also need to accept cookiesanyone have any ideas about where to get startedmany thanks in advance,['android'] +101291,does anyone have the monokai theme for pycharm i really miss the monokai theme and really cannot stand the white backgrounddoes anyone have a pycharm schema for monokai by chance,['python'] +101301,idataerrorinfo vs ivalidatableobject currently my business objects implement idataerrorinfo since i intend to use these libraries in aspnet mvc 3 i figure i should implement ivalidatableobject as well or maybe instead of does wpf work with ivalidatableobjecthow do dataannotations fit into the picture,['.net'] +101304,android can i use one sqliteopenhelper class for multiple database files my app uses two databases separate files to handle these databases i have created two helper classes which extend sqliteopenhelper one for each databasei am now going to add a third database and wonder whether i need to create yet another helper class and if i used a 4th and a 5th database would i need even more helper classes or can i use the same helper class for multiple databasesthe problem that i see with trying to use just one helper class is that i cannot see how to pass the name of the individual database files to the helper at present the name of the database is hardcoded as a static field of each of the helper classes but if i had only one helper class i would need to be able to pass the different names in to the constructor when creating the separate helper objects the problem is that the sqliteopenhelper constructor seems to be called by android with just one parameter the context,['android'] +101307,which is faster x1 or x10 i do not want to optimize anything i swear i just want to ask this question out of curiosityi know that on most hardware there is an assembly command of bitshift eg shl shr which is a single command but does it matter nanosecondwise or cputactwise how many bits you shift in other words is either of the following faster on any cpux 1andx 10and please do not hate me for this question,"['c++', 'c']" +101308,c event based memory leaks i have an application which has some memory leaks due to events not being detached before an object reference is set to null the applicaiton is quite big and its difficult to find the memory leaks by looking at the code i want to use sosdll to find the names of the methods that are the source of leaks but i am getting stuck i set up a test project to demonstrate the problemhere i have 2 classes one with an event and on the listens to that event as belownamespace memoryleak class program static void mainstring args testmemoryleak testmemoryleak new testmemoryleak while consolereadkeykeyequalsq class testmemoryleak public event eventhandler anevent internal testmemoryleak aneventlistener leak new aneventlistener thisanevent s e leakonleak aneventthis eventargsempty class aneventlistener public void onleak consolewritelineleak event i break into the code and in the intermediate window typeload sosdllthen i use dumpheap to get the objects on the heap of the type aneventlistenerdumpheap type memoryleakaneventlistenerand i get the followingpdb symbol for mscorwksdll not loaded address mt size01e19254 0040348c 12 total 1 objectsstatistics mt count totalsize class name0040348c 1 12 memoryleakaneventlistenertotal 1 objectsi use gcroot to work out why the object is not being garbage collectedgcroot 01e19254and get the followinggcroot 01e19254note roots found on stacks may be false positives run help gcroot formore infoerror during command warning extension is using a callback which visual studio does not implementscan thread 5208 osthread 1458esp2ef3ccroot01e19230memoryleaktestmemoryleak01e19260systemeventhandler01e19248memoryleaktestmemoryleakc thisplayclass101e19254memoryleakaneventlistenerscan thread 7376 osthread 1cd0i can now see the event handler that is the source of the leak i use do to look atthe fields of the event handler and getdo 01e19260name systemeventhandlermethodtable 65129dc0eeclass 64ec39d0size 320x20 bytes cwindowsassemblygac 32mscorlib20 b77a5c561934e089mscorlibdllfields mt field offset type vt attr value name65130770 40ff 4 systemobject 0 instance 01e19248 target6512ffc8 40100 8 ectionmethodbase 0 instance 0 methodbase6513341c 40101 c systemintptr 1 instance 0040c060 methodptr6513341c 40102 10 systemintptr 1 instance 0 methodptraux65130770 4010c 14 systemobject 0 instance 0 invocationlist6513341c 4010d 18 systemintptr 1 instance 0 invocationcountso now i can see the pointer to the method that is not being detached0040c060 methodptrbut how do i get the name of that method,['c#'] +101312,how to detect ipad user tap on keyboard hide button in my app i have some complex logic surrounding the hiding and showing of the keyboard i am interested in detecting when the user who has an ipad specifically taps on the ipad keyboard hide buttoni am not interested in detecting when the keyboard is supposed to hide only when the user actually physically taps on this button any suggestionsthank you,['ios'] +101331,how to clear focus and remove keyboard on android i have a edittext controlif i tap it the softkeyboard will popup however when i press enterokreturn then the edittext control it still has focus and the keyboard uphow do i close the softkeyboard and remove focus from it,['android'] +101335,scala enumerations with singleton objects as enumeration elements and a possibility to iterate over them i already looked at the scala question about emulating javas enum and case classes vs enumeration but it seems too much effort for too less benefitbasically i would like to have a values method returning all singleton objects of dayofweek without repeating myself a few timesthis is how my code should look likeobject dayofweek extends myenum object monday extends dayofweek1 object tuesday extends dayofweek2 object wednesday extends dayofweek3 object thursday extends dayofweek4 object friday extends dayofweek5 object saturday extends dayofweek6 object sunday extends dayofweek7class dayofweekordinal intthe method values should return something like if it had been written like this val values arraymonday tuesday wednesday thursday friday saturday sundayeverything should happen in the myenum trait so i only need to extend it to get the functionalitytrait myenum val values thisgetclassgetfieldmodule etc etcany suggestion how this could be done exactlythe idea is that values accesses the class and finds all singleton objects of the class they are extendingedit it looks like all suggestions do not take in account that the user can create objects too which should of course be comparable to the defined onesi will try to give another example maybe it is more clearobject monthday extends myenum some important holidays object newyear extends monthday 1 1 object unityday extends monthday11 9 object saintnicholas extends monthday12 6 object christmas extends monthday12 24class monthdaymonth int day intof course the user can create other monthdaysval mybirthday new monthdaymonth dayifmonthdayvaluescontainsmybirthday well i probably have to workelse great it is a holidayi want to have a trait myenum which i can mix into the object holding my enumeration objects with methods to return a list of them def values listmonthday or iterate over them def next monthday or def previous monthdaypps i created a new question for the second part of this question as requested by ken bloom,['java'] +101338,android immediate auto complete greetingsthe android auto complete only starts after two letters how can i make it so the list appears when the field is just selectedthanks,['android'] +101340,simple and fast c compression libraryclass is there some simple easy to use c library or just a class for compressionit should be something easy to use and fast compression ration can be worse,['c++'] +101352,recommended approach for presenting formatted text in android i am developing an application that will provide instructions to making a product the text will have bullets andor numbered steps as well regular text paragraphs i may have headings for various sections the text will be placed into a scrollable texviewi was originally planning on loading the text from a resource text file and then applying formatting via xml however i just learned about webview and the ability to load local html files i could easily format the text in html and load it into a webview for the various activitiesmy question is is there a performance issue with using webview vs textview are there other ways to easily format text for a textviewthanks,"['html', 'android']" +101357,example of how to use fastcgi finish request can someone show a simple example on how to use fastcgi finish request functioni googled but only found some general mention of it some people say they use it successfully but i could not find a single example with codefor example i have a php object to send a response to a browser i generate html then returning it via getresult then echo the resultlike this obj new controllerecho ogetresultlet us say i want to take advantage of this optimization technique to send result to browser and then finish up some potentially long process like connecting to some api like maybe facebook apihow would i go about doing this i understand that basically i can call fastcgi finish request and then continue executing php script i just need to see example code i am not smart enough to figure it out by myself,['php'] +101360,overlay nsscroller over content is there any way to overlay the nsscroller over the content of the scroll view like in ios i have already tried several approachesa setting the frame of the scroll view content view nsclipview to extend into the bounds of the scrollerb adding an nsscroller object as a subview of the scroll view positioned where i wantc creating an entirely custom scroller view and placing it as a subview this worked but that would mean that i need to rewrite all the functionality of nsscrollersparrow seems to successfully do this and it seems to do it through a regular nsscroller subclass seeing as it responds to the scroll settings set in system preferences appearance it is not really drawing the scroller that is the issue its just making it overlay the contentany advice is appreciated,['objective-c'] +101372,how to create a usercontrol that you can drop other controls in it in winforms how can i create a usercontrol that when i put on my form i can then add other controls inside by dragging them from the toolbox the same way as with all containers controls panels group boxes etc i have tried to add controls by dropping them in my control but then when i move my control the controls i added stay right where they are which wouldnt happen if instead of my control i would use a panel the other controls would move with the panel,"['c#', '.net']" +101373,getting tkinter check box state how do i get the state of a tkinter check box by state i mean get whether or not it has a check mark in it or not,['python'] +101378,what are the purpose of api specific typedefs such as glsizei glint glvoid what are the purpose of api specific typedefs such as glsizei glint glvoidi see this everywhere in c and c code basic types are often typdefed with the libraries prefixsuffix whats the reasoning behind this is this good practice should my programs be doing something similar themselvesat first glance it seems to make the code a little bit less readable you have to take an instant to translate glint into int in your head and that is an easy example something like uint makes more since to me at least this is shortening unsigned int into four leters,"['c++', 'c']" +101379,cryptographic failure while signing assembly in visual studio i do not know where i went wrong when i build it searches for the default path for the dll to sign in eventhough i specified the pathi have created and stored my snk file in the same location as the dllassembly info file for errorcollectionusing systemreflectionusing systemruntimecompilerservicesusing systemruntimeinteropservices general information about an assembly is controlled through the following set of attributes change these attribute values to modify the information associated with an assemblyassembly assemblytitleerrorcollectionassembly assemblydescriptionassembly assemblyconfigurationassembly assemblycompanyassembly assemblyproducterrorcollectionassembly assemblycopyrightcopyright a 2010assembly assemblytrademarkassembly assemblyculture setting comvisible to false makes the types in this assembly not visible to com components if you need to access a type in this assembly from com set the comvisible attribute to true on that typeassembly comvisiblefalse the following guid is for the id of the typelib if this project is exposed to comassembly guid2c17131b0ae34146a797308f5958e819 version information for an assembly consists of the following four values major version minor version build number revision you can specify all the values or you can default the build and revision numbers by using the as shown below assembly assemblyversion10assembly assemblyversion10assembly assemblyfileversion10assembly systemreflectionassemblykeyfiledservicesbinerrorcollectionsnki get the following errorcryptographic failure while signing assembly dserviceserrorcollectionobjdebugerrorcollectiondll error reading key file dservicesbinerrorcollectionsnk the system cannot find the file specified errorcollection,['c#'] +101380,how to pass array through hidden field here my codeorderj0euclidean geomethiyil kodpagugalorderj1q16jhidden fieldinput typehidden namehdntotal valuephp echo gtot input typehidden namehdnorder valuephp echo order input typesubmit valueplace orderhdntotal value is coming in next page but hdnorder is not print posthdnorder print only array on screen,['php'] +101381,how can i make a css table fit the screen width currently the table is too wide and causes the browser to add a horizontal scroll bar,"['html', 'css']" +101387,reloading custom uitableviewcell after reordering cells i have uitableview which uses custom uitableviewcells the cells can have one of three types of background images set in each cells backgroundviewimage property top middle or bottom the top and bottom images are for the first and last cells and have rounded corners much like a grouped uitableviews cells all other middle cells within the uitableview have a rectangular middle background imagemy problem is that when reordering the cells in the uitableviews edit mode the cells do not refresh with a different background image depending on their new location for example if i move the first cell into the middle of the table it still retains its original top background image with rounded corners and the new cell which appears at the top of the table view still has its original middle background image which all looks a bit oddi can get around this by doing a reloaddata on the table view but this has the problem of not giving a nice graceful animation of the changes i noticed that when reordering a standard grouped uitableview as soon as a cell is moved dragged the background image on the relevant cells change even before the moved cell has been dropped into its new location which looks very nice i would like to achieve the same thingto this end i have implemented tableviewtargetindexpathformovefromrowatindexpathtoproposedindexpath which is called every time a row is dragged around in the table view within this i have tried various methods of setting the backgroundviewimage including just directly setting the image and then also explicitly telling it to redraw the cell andor image using setneedslayout and setneedsthisplay but nothing seems to make the cell redraw i have nslogged the results of these changes and they appear to be committing to the cell as the correct values appear in the nslog but the cell just does not seem to be updating on screenif anyone could point out what i am doing wrong or suggest a better way of achieving a working outcome i would be very much appreciative thanksedit the following code was pulled from the bounty and formatted so it can be more easily digesteduiimage rowbackgrounduiimage selectionbackgroundnsinteger sectionrows tableview numberofrowsinsectionindexpath sectionnsinteger row indexpath rowif row 0 row sectionrows 1 rowbackground uiimage imagenamedfield title bkgpng selectionbackground uiimage imagenamedfield title bkgpngelse if row 0 rowbackground uiimage imagenamedtable row top bkgpng selectionbackground uiimage imagenamedtable row top bkgpngelse if row sectionrows 1 rowbackground uiimage imagenamedtable bottom row bkgpng selectionbackground uiimage imagenamedtable bottom row bkgpngelse rowbackground uiimage imagenamedtable row bkgpng selectionbackground uiimage imagenamedtable row bkgpnguiimageview rowbackgroundimageview uiimageview alloc initwithimagerowbackgrounduiimageview rowbackgroundselectionimageview uiimageview alloc initwithimageselectionbackgroundif row sectionrows 1 uiimageview sep uiimageview alloc initwithimageuiimage imagenamedcell separatorpng sep setframecgrectmake20 56 280 1 rowbackgroundimageview addsubviewsepcell setbackgroundviewrowbackgroundimageviewrowbackgroundimageview release,['iphone'] +101393,why does the visual studio conversion wizard 2010 create a massive sdf database file i have opened a 2009 c sln in 2010 and run the visual studio 2010 conversion wizard it seems to have done the conversion fine but there is a 60 mb sdf file created with the same name as my sln file apart from extension there was no sdf file before i am pretty sure when i have used the wizard on c projects this file has not been createdit looks like it is created to help the conversion wizard but i do not see why it is left when the wizard has finished the tables in the database areassoc spansassoc textbase class parentscode item kindscode itemsconfig filesconfigsfile mapfile signaturesfilesparsersprojectspropertiesrefssymbolsi assume i can just delete this file,['c++'] +101425,how to make a uitableviewcell with a uitextview inside that dynamically adjust its height on the basis of the uitextview i would like to have a tablew view with a behaviour similar to the iphone contacts app by apple a uitableviewcell with a uitextview inside so that when i write in the uitextview the uitextview increases its height and so accordingly the uitableviewcell dynamically adjusts its height i searched over the whole web finding only partial solutions and lack of sample codeplease help me i am desperatetony,['iphone'] +101442,serializing an array in jquery how to prepare this array for ajax submit here images return val1val2 but after i use paramimages i get back undefinedundefinedundefinedundefined rem imagesclickfunction var images new array images set image inputcheckedeachfunctioni imagesi thisval alertparamimages return falsegenerally the idea is to check the images to delete on page then on button click loop trough all images checked and serialize array for submit over ajax to php script,['jquery'] +101451,detecting physical menu key press in android i am trying to detect when the physical menu button on my android phone has been pressed i though the code below would work but it does not where am i going wrong pleasethe error returned is illegal modifier for parameter onkeydown only final is permittedpublic boolean onkeydownint keycode keyevent event if keycode keyeventkeycode menu do stuff else return superonkeydownkeycode event,['android'] +101457,python sort function breaks in the presence of nan sorted2 floatnan 1 returns 2 nan 1at least on activestate python 31 implementationi understand nan is a weird object so i wouldnt be surprised if it shows up in random places in the sort result but it also messes up the sort for the nonnan numbers in the container which is really unexpectedi asked a related question about max and based on that i understand why sort works like this but should this be considered a bugdocumentation just says return a new sorted list without specifying any detailsedit i now agree that this is not in violation of the ie standard however it is a bug from any common sense viewpoint i think even microsoft which is not known to admit their mistakes often has recognized this one as a bug and fixed it in the latest version anyway i ended up following khachiks answersortedlist key lambda x floatinf if mathisnanx else xi suspect it results in a performance hit compared to the language doing that by default but at least it works barring any bugs that i introduced,['python'] +101458,generating all permutations of a given string what is an elegant way to find all the permutations of a string eg ba would be ba and ab but what about abcdefgh is there any example java implementation,['java'] +101470,minmax zoom level in openlayers i am using openlayers to thisplay a map in a web page i am using tiles from cloudmade but the same issues occur with the mapnik tiles from openstreetmapi am trying to restrict the map so that the user cannot zoom all the way out to world view i want them to stay at roughly a city level zoom at minimumi have tried using the minzoomlevel maxzoomlevel numzoomlevels properties only the maxzoomlevel and numzoomlevels properties seem to work whereas the minzoomlevel property seems to be completely ignoredis there another way to accomplish this,['javascript'] +101471,can someone explain rubys use of pipe characters in a block can someone explain to me rubys use of pipe characters in a block i understand that it contains a variable name that will be assigned the data as it iterates but what is this called can there be more than one variable inside the pipes anything else i should know about it any good links to more information on itfor example25times i puts i,['ruby'] +101474,shortcut key for jbutton without using alt key in swt you can give any button a shortcut key simply by adding in front of the letter in the button label for example if my button label is play i can activate the button by hitting letter p on the keyboardin swing you can add a shortcut key using the mnemonic property however you need to hit altp to activate the button this is really most appropriate for menu shortcuts i want to activate the button with a letter press and no alt modifieri have seen this post on how to do it but it seems absurdly complicated is there an easier way to do thisupdate after camickr suggestion i ended up using this code i could not find any clear and simple example online so hopefully this will help people out play is a jbutton but can be any component in the windowplaygetinputmapplaywhen in focused windowputkeystrokegetkeystrokekeyeventvk p 0 playplaygetactionmapputplay new abstractaction public void actionperformedactionevent e playactionperformede some function,['java'] +101484,what is the point of the c99 standard c99 adds several useful features to the language yet i find it difficult to recommend any practice which depends upon c99 the reason for this is because there are few any actual implementations of the c99 language sure there is limited support in a few compilers but nobody wants spend the time to write c code only to have it be unportablethis is frustrating given that the standard was written and finalized over 10 years ago now plus i hear thiscussions of a c1x from time to time and i wonder why someone would be taking steps to revise the language given that the current version of the language is not yet implementedso my question is as joe blow c programmer today what is useful wrt the c99 standard to me if any,['c'] +101489,simple php random array i have a simple array like thisinput arrayline1 line2 line3and want to echo one of the values randomly i have done this before but cannot remember how i did it and all the examples of array rand seem more complex that what i needcan any help thanks,['php'] +101495,how to establish a secidentityref in an iphone keychain without a p12 how do you create a secidentityref in an iphone keychain if1 you already have the private key in the keychain and2 you have just received the certificate from a casecpkcs12import does not help in this case unless there is an api to create a p12 from a private key and a certificatesecidentitycreatewithcertificate would be the answer on the mac but it does not exist on the iphoneis it possible using secitemadd many thanks andrew,['iphone'] +101516,what is aggregatecatalog what is aggregatecatalog what does it mean when you construct a new aggregatecatalog what does it mean when you add assemblies to the catalog eg catalogcatalogsaddnew assemblycatalogsomeassembly other than assemblies what can you add to the catalog any general knowledge related to this would be helpful too i am a total noob,"['c#', '.net']" +101543,mysql select rows with more than one occurrence heres my query it selects a list of ids from two tables across two databases the query works fineselect enid fpblogidfrom frenchblog pics fp frenchblog news fn englishblog news en where fpblogid fnid and entitle fr fntitle and fptitle i only want to thisplay rows where a enid occurs more than onceso for instance if this was the current query resultenid fpblogid 10 12 12 8 17 9 12 8i only want to query to show this instead enid fpblogid occurrences 12 8 2,['mysql'] +101549,how to search for an element in a vector i have a code like thisstdvectorstringiterator pp findvbeginvendasdasda cout p endlif asdasda is not a part of the vector p points to some garbage and cout gives a seg fault what should be the if statement that would make the cout execute onlyif asdasda was foundand also the position of asdasda in v like if we had earlier declared v3 as asdasdathen how can i know from the find that v3 is asdasda,['c++'] +101551,how to get full host name port number in application start of globalaspx i tried uri uri httpcontextcurrentrequesturlstring host urischeme urischemedelimiter urihost uriportand it worked well on my local machine but when being published to iis7 there is an exception sayingsystemwebhttpexception request is not available in this contextanyone know how to achieve this,"['c#', 'asp.net']" +101558,android how can i compile my codes online i just want to know is there any way to compile and run my android application codes online without installing the sdk on the computer thanksabhinav,['android'] +101560,create form auto complete in google app engine i want to build a auto complete feature for a tags field like in so on app engine any idea how i should go about the proceserver side algo what logic should be there for autocompleteapp engine implementation what should be the datastore schema for this,['python'] +101563,how to export sql query to txt using command line i want to export select from table results to a text file from the command line in linux how should i do thisthanksjean,['mysql'] +101567,spring application context load order on my webxml i have a springmvc servlet declaration which has a corresponding springmvcservletxmlservlet servletnamespringmvcservletname servletclassorgspringframeworkwebservletthispatcherservletservletclaservletservletmapping servletnamespringmvcservletname urlpatternmyappurlpatternservletmappingi also have my usual applicationcontextxml file which one gets loaded first the springmvcservletxml or the applicationcontextxmlthe reason i am asking this is whenever i place the mvcannotationdriven element in the applicationcontextxml i get a severe context error but when i put that element in the springmvcservletxml my web app runs fine any ideas whyon another webapp i have the mvcannotationdriven inside the applicationcontextxml and it runs fineaddendum i do notice that the presence of aopconfig poses conflict against mvcannotationdriven,['java'] +101573,substitute for forking in windows i have been following beej networking guide and in the server section there is portion of code where it has called a function forkif fork this is the child process closesockfd child does not need the listener if sendnew fd hello world 13 0 1 perrorsend closenew fd exit0i am on a windows machine and cant get that part working what can i do to solve thismy code is as follows server define win32 winnt 0x501include iostreaminclude windowshinclude winsock2hinclude ws2tcpiphinclude stdiohinclude systypeshusing namespace stdconst int winsockversion 2define backlog 10define port 30int mainvoid wsadata wsadata if wsastartupmakewordwinsockversion0wsadata 0 coutwsastartup initialized endl int status int sockfd new fd const char yes 1 struct addrinfo hints resloop find struct sockaddr storage their addr socklen t addr size memsethints0sizeof hints hintsai family af inet hintsai socktype sock stream hintsai flags ai passive if status getaddrinfonullporthintsres 0 coutcall to get addrinfo successful endl for loop find res loop findnull loop find loop findai next if sockfd socketloop findai familyloop findai socktypeloop findai protocol 1 coutcould not create socket endl continue else coutsocket created endl clearing in use ports if setsockoptsockfdsol socketso reuseaddryessizeofint 1 coutcouldnt clear blocked port endl perrorsetsockopt exit1 if bindsockfdloop findai addrloop findai addrlen 1 closesocketsockfd perrorserver bind continue break if listensockfdbacklog 1 coutlistening for incoming connections accept loop whiletrue socklen t addr size sizeof their addr new fd acceptsockfdsockaddrtheir addraddr size if new fd 1 perroraccept continue struct sockaddr new addr int len sizeof new addr getpeernamenew fdnew addrlen coutconnected to new addrsa data endl iffork this is a child process closesocketsockfd if sendnew fdhello world130 1 perrorsend closesocketnew fd exit0 closesocketnew fd clear stuff if wsacleanup 0 coutwsacleanup unsuccessful endl else coutwsacleanup successful endl return 0,['c++'] +101577,iphone localization infoplist if i declare japanese french german simplified chinese thai in the localization field of my apps myappinfoplist file will the itunes store detect this and correctly advertise these together with the localization native development region of english as the languages in which my app is availableif not what should i do to make sure these localizations are advertisedshould i replace the localization entry with commaseparated string of iso 6391 codes en fr de ja th zhhansthanking you in advance,['iphone'] +101588,how thread safe is thrift re i seem to have requests thisrupting one another editapparently what i was hoping to do is outside of the scope of thrift if i make sure there is never more than one client on the port everything is aok of course this kind of defeats the purpose as i would like to have several reusable connections open to the server to improve response times and lower overheadif anyone has a suggestion of an alternate way to achieve this it would be appreciatedor if my conclusion is wrongbackgroundi have a multicomponent application that is mostly connected up by thriftmostly javaphp connectionsso far it all has appeared to be fine but having introduced a javajava connection where the client end is a servlet that can launch hundreds of requests a secondthe method being accessed has the following interfacebool pvcheck1i32 toolid throws1dpnotoolexception nteto make sure it was not something weird on the service end i replaced the implementation with a trivial one override public boolean pvcheckint toolid throws texception boolean ret apigetviewsanddectoolid return true the errorspossible causesso long as there is not many connections it goes by fine but as soon as connections come close together connections start getting stuck in the readerif i pull one of them up in the debugger the stack looks like this daemon thread http8080197 suspended bufferedinputstreamreadbyte int int line 308 tsockettiostreamtransportreadbyte int int line 126 tsocketransportreadallbyte int int line 84 tbinaryprotocolreadallbyte int int line 314 tbinaryprotocolreadi32 line 262 tbinaryprotocolreadmessagebegin line 192 dumbopaymentclientrecv pvcheck line 120 dumbopaymentclientpvcheckint line 105 receiverperformtaskhttpservletrequest httpservletresponse line 157 receiverdogethttpservletrequest httpservletresponse line 109 receiverhttpservletservicehttpservletrequest httpservletresponse line 617 receiverhttpservletserviceservletrequest servletresponse line 717 applicationfilterchaininternaldofilterservletrequest servletresponse line 290 applicationfilterchaindofilterservletrequest servletresponse line 206 standardwrappervalveinvokerequest response line 233 standardcontextvalveinvokerequest response line 191 standardhostvalveinvokerequest response line 127 errorreportvalveinvokerequest response line 102 standardenginevalveinvokerequest response line 109 coyoteadapterservicerequest response line 298 http11aprprocessorprocesslong line 859 http11aprprotocolhttp11connectionhandlerprocesslong line 579 aprendpointworkerrun line 15 threadrun line 619 this seems to be triggered by data getting corrupted as i get the following exceptions101122 183855 warn loggerreceiver pvcheck had an exceptionorgapachethrifttapplicationexception pvcheck failed unknown result at thriftgenerateddumbopaymentclientrecv pvcheckdumbopaymentjava135 at thriftgenerateddumbopaymentclientpvcheckdumbopaymentjava105 at receiverperformtaskreceiverjava157 at receiverdogetreceiverjava109 at javaxservlethttphttpservletservicehttpservletjava617 at javaxservlethttphttpservletservicehttpservletjava717 at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava290 at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava206 at orgapachecatalinacorestandardwrappervalveinvokestandardwrappervalvejava233 at orgapachecatalinacorestandardcontextvalveinvokestandardcontextvalvejava191 at orgapachecatalinacorestandardhostvalveinvokestandardhostvalvejava127 at orgapachecatalinavalveserrorreportvalveinvokeerrorreportvalvejava102 at orgapachecatalinacorestandardenginevalveinvokestandardenginevalvejava109 at orgapachecatalinaconnectorcoyoteadapterservicecoyoteadapterjava298 at orgapachecoyotehttp11http11aprprocessorprocesshttp11aprprocessorjava859 at orgapachecoyotehttp11http11aprprotocolhttp11connectionhandlerprocesshttp11aprprotocoljava579 at orgapachetomcatutilnetaprendpointworkerrunaprendpointjava15 at javalangthreadrunthreadjava619and101122 175946 error ninja arreceiver aa14a receiver aservletserviceaa34a34aajavalangoutofmemoryerror java heap space at orgapachethriftprotocoltbinaryprotocolreadstringbodytbinaryprotocoljava296 at orgapachethriftprotocoltbinaryprotocolreadstringtbinaryprotocoljava290 at orgapachethriftprotocoltbinaryprotocolreadmessagebegintbinaryprotocoljava198 at thriftgenerateddumbopaymentclientrecv pvcheckdumbopaymentjava120 at thriftgenerateddumbopaymentclientpvcheckdumbopaymentjava105 at receiverperformtaskreceiverjava157 at receiverdogetreceiverjava109 at javaxservlethttphttpservletservicehttpservletjava690 at javaxservlethttphttpservletservicehttpservletjava803 at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava269 at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava188 at orgapachecatalinacorestandardwrappervalveinvokestandardwrappervalvejava210 at orgapachecatalinacorestandardcontextvalveinvokestandardcontextvalvejava172 at orgapachecatalinacorestandardhostvalveinvokestandardhostvalvejava127 at orgapachecatalinavalveserrorreportvalveinvokeerrorreportvalvejava117 at orgapachecatalinacorestandardenginevalveinvokestandardenginevalvejava108 at orgapachecatalinaconnectorcoyoteadapterservicecoyoteadapterjava151 at orgapachecoyotehttp11http11processorprocesshttp11processorjava870 at orgapachecoyotehttp11http11baseprotocolhttp11connectionhandlerprocessconnectionhttp11baseprotocoljava665 at orgapachetomcatutilnetpooltcpendpointprocesocketpooltcpendpointjava528 at orgapachetomcatutilnetleaderfollowerworkerthreadrunitleaderfollowerworkerthreadjava81 at orgapachetomcatutilthreadsthreadpoolcontrolrunnablerunthreadpooljava685 at javalangthreadrunthreadjava636perhaps i am way off the mark but i am pretty sure these are related to the client continuing to attempt to read when there is nothing being sentsome implementation detailsboth the server and client are using the java binary protocoli wrote a simple client pool class which lets me reuse clients these are the main functionspublic synchronized client getclient ifclientqueueisempty return newclient else return clientqueuegetlast private synchronized client newclient int lefttotry serverarrlength client cli null whilelefttotry 0 cli null loginfocreating new connection to serveraroundrobinpos port ttransport transport new tsocketserveraroundrobinpos port tprotocol protocol new tbinaryprotocoltransport cli new clientprotocol try transportopen catch ttransportexception e cli null logwarnfailed connection to serveraroundrobinpos port roundrobinpos ifroundrobinpos serverarrlength roundrobinpos 0 lefttotry return clipublic void returnclientclient cli clientqueueaddfirstclithe client applicationsnamely tomcat servlets access it in the following way client dpayclient null ifdpay null dpayclient dpaygetclient null try dpayclientpvcheckrequestparametersgetid catch dpnotoolexception e return catch texception e logwarnpvcheck had an exception e finally ifdpayclient null dpayreturnclientdpayclient the actual thrift connection is upped in the following mannerprivate boolean initthriftint port configuration conf tprotocolfactory protocolfactory new tbinaryprotocolfactory dpaymenthandler handler new dpaymenthandlerconf dumbopaymentprocessor processor new dumbopaymentprocessorhandler inetaddress listenaddress try listenaddress inetaddressgetlocalhost catch unknownhostexception e logerrorfailed in thrift init e return false tservertransport servertransport try servertransport new tserversocket new inetsocketaddresslistenaddress port catch ttransportexception e logerrorfailed in thrift init e return false ttransportfactory transportfactory new ttransportfactory tserver server new tthreadpoolserverprocessor servertransport transportfactory protocolfactory loginfostarting dumbo payment thrift server on listenaddress integertostringport serverserve return truefinallybeen stuck on this for a while now it may well be i am missing something obvious i would really appreciate any help with thisif any additional information is needed please let me know there is a whole mouthful there so i wanted to try to keep stuff to the most hopefully relevant,['java'] +101628,ant java zipfileset excluding a directory i have an ant target for creating zip like this zip destfilethistmyzipzip zipfileset dirdocsmanual prefixdocsuserguide zipthis basically creates archive myzipzip with all the files and directories under docsmanual prefixed with docsuserguide in the archivebut i don want to include all the directories under docsmanual to be copied into the archivei have a directory called old under docsmanual which i want to excludehow to achieve this,['java'] +101631,where can i download source for mysql connectorj googling did not help,['mysql'] +101641,adding multiple fonts to uiappfonts overrides each other i am trying to add some custom fonts to an iphone app through uiappfonts in infoplist i can reach both fontnames by code ie myfontbold and myfontmedium my problem is that the last font in uiappfonts array overrides the other one making both myfontbold and myfontmedium render out myfontbold if this is the last entry in the plist array by dragging myfontbold as the first entry makes both fontnames render myfontmedium the property list excerptuiappfonts item 0 myfontmedium item 1 myfontboldi am calling the font withuifont applicationfontbold uifont fontwithnamemyfontbold sizeuifont buttonfontsizeuifont applicationfont uifont fontwithnamemyfontmedium sizeuifont buttonfontsizeanyone tried adding multiple fonts to one fontfamily,['iphone'] +101644,how to call python functions dynamically i have this codefields nameemaildef clean name passdef clean email passhow can i call clean name and clean email dynamicallyfor examplefor field in fields clean fieldi used the curly brackets because it is how i used to do it in php but obviously does not workhow to do this with python,['python'] +101665,how to create a simple map using javascriptjquery how can you create the javascriptjquery equivalent of this java codemap map new hashmap does not not have to be a hash map any keyvalue map is finemapputmykey1 myobj1mapputmykey2 myobj2 repeat and timesfunction object getk return mapgetk,"['javascript', 'jquery']" +101677,can the precision of sql server 2008 time be reduced to only hours and minutes with sql server 2008 the time data type has an optional precision argument default is 7 with this you can control how many fractional decimal places are stored and thisplayed declare time time3set time getdateprint timethe above would print this 104725347the documentation says the smallest precision is time0 this would store and print 104725is it possible to reduce the precision even more to eliminatezero out seconds 1047 i know this can be done manually by adding a constraint datepartseconds time 0 performing math on data entry to zero out the seconds and manually format when printing but i am looking for a simplier way to just define a field in a table as hours and minutes in much the same way that the date type allows you to define a field as just the date no time component,['sql'] +101679,c or vbnet iterate all public enums we have a common component in our source which contains all the enums approx 300 for a very large applicationis there any way using either c or vbnet to iterate through all of them in order to perform an action on each onethe question how to iterate all apublic stringa properties in a net class is almost relevant but the enums i am dealing with are a mix of types,['c#'] +101686,php importance of a number in a set of numbers i have a set of numbers eginput array1 4 7 4 9 4 8 6 2 8 7 7 4 5 3i am trying to work out the importance of each number based on the following ruleas the sequence gets longer the numbers get less significant and each time a number is mentioned then it will improve the relevance how much depends on its position in the sequencei am expecting something likearray 4 90 1 75 7 60 so 4 is the most inportant followed by 1 and then 7 etc note that the output is completely fabricated but gives in indication that 4 should be the most important i believe i want some kind of linear solution,['php'] +101690,what are legal characters for an html element id what characters can i use in an identifier for an html element for examplespan idsection5 or rather should i stick to certain characters to make sure the id works across all major browsersjavascript engine,"['javascript', 'html', 'css']" +101698,how to set phps auto prepend file directive per directory background i have got some code that checks to see if a user has a valid session before processing the php page that i would like to set as the auto prepend file however i need to exclude the page where the user attempts to login from requiring a valid session i would like to be able to set the auto prepend file value on an per directory basis environment php 526m apache 2 running php as a cgi not as mod php on windows if that matters and on a machine that i have complete control over not a hosted environmentusing a htaccess file is out bc i am not using mod php i have not been able to alter the in phpini to set the auto prepend file the server throws an internal error and ini set does not work bc it has already loaded the session checking file before i can change the value of auto prepend file i do not see a way to set auto prepend file on a per directory basis if you are not using mod phphtaccess am i missing something,['php'] +101704,in a makefile is a directory name a phony target or real target according to what i have read about makefiles a phony target is any target that does not correspond to an actual filename my intuition says that a directory as a target would be treated the same as a file why is this important i have a directory as a target in my makefile when i have it as a prerequisite to my primary executable that executable always gets made whether or not everything is up to date if i take it out as a prerequisite my makefile is smart enough to know when things need to be built but i have the problem of not knowing if the directory needs to be created according to what i have read about make any phony targets are not good as prerequisites because make does not know if they are up to date so they will always rebuild the associated target here is an excerpt from my makefile exec with path obj dir dpend objs echo echo this dir machine echo linking shared library echo ar rc exec with path insertobjs ar rc exec with path objs echo make dirs for object code and linksobj dir if d obj dir then mkdir obj dir fiso in this case is obj dir a directory name a phony target or not,['c++'] +101707,how to find rows which are duplicates by a key but not duplicates in all columns i am working with a table which is an extract of a set of other tables all of the rows of the extract table should be unique according to keys d1 d2 and d3 they are not it appears that an earlier developer attempted to solve this problem by using a select thistinct across all columns being queried from this table this will work but only if every row which is a duplicate on d1 d2 d3 is also a duplicate across the nonkey columns ignoring the identity column that was added to the extract tablein other words given rows as followsd1 d2 d3 c4 c5 c6 a b c x1 x2 x3a b c x1 x2 x3thenselect thistinct d1 d2 d3 c4 c5 c6from bad tablewill work as there is no difference between the rows which are duplicated on d1d2d3 but if the table containedd1 d2 d3 c4 c5 c6 a b c x1 x2 x3a b c x1 x2 x4then select thistinct would return two rows for the key abc furthermore we would have to decide which of x3 or x4 was the correct valuei know how to find the duplicates on d1d2d3 i even know how to find the duplicates across all the columns other than the identity columnwith duplicatesd1d2d3 as select d1 d2 d3 from source group by d1 d2 d3 having count1select sd1 sd2 sd3 sc4 sc5 sc6from source sinner join duplicates d on sd1 dd1 and sd2 dd2 and sd3 dd3order by sd1 sd2 sd3 sc4 sc5 sc6the question is how do i find the subset of the above resultset which are duplicates on d1d2d3 but not duplicates on d1d2d3c4c5c6,['sql'] +101709,uiactionsheet buttons color how can i change the color of uiactionsheet buttons color,['iphone'] +101715,if sentence contains string if a sentence contains hello world no quotes then i need to return true and do something possible sentences could be like thisvar sentence this is my hello world and i like widgetsvar sentence hello world the beginning of allvar sentence welcome to hello worldif sentencecontainshello world alertyes else alertnoi know the contains does not work so i am looking for something does work regex is the enemy here,"['javascript', 'jquery']" +101731,rails fields for render partial with multiple locals producing undefined variable alli am experiencing a problem with a standard fields for setup in my form partial i havediv classcomment list ffields for comments do cf render partial commentscomment fields locals f cf tester true end link to add fields add a comment f comments divin the comment fields partial i have the usual fields and then my test variable testerto s when i remove the tester variable everything works well as soon as i add the test variable i get this erroractionviewtemplateerror undefined local variable or method tester for class0xa1f36640xa1f1bd4has anyone else ran into this problem when using a fields for with multiple localsto elaborate a bit more my comment fields partial looks like thisdiv classcomment dynamic field span classcomment content ftext field content class comment content span testerto s link to remove fields remove f divit is only called from the form partial,['ruby-on-rails'] +101735,load javascript async then check dom loaded before executing callback problemload js files asynchronously then check to see if the dom is loaded before the callback from loading the files is executed edit we do not use jquery we use prototypeedit added more comments to the code example hey guysi am trying to load all of my js files asynchronously so as to keep them from blocking the rest of the page but when the scripts load and the callback is called i need to know if the dom has been loaded or not so i know how to structure the callback see belowload asynchronouslyfunction var e documentcreateelementscript etype textjavascript easync true esrc srcstr a little magic to make the callback happen ifnavigatoruseragentindexofopera etext initpage else ifnavigatoruseragentindexofmsie eonreadystatechange initpage else einnerhtml initpage attach the file to the document documentgetelementsbytagnamehead0appendchildeinitpagehelper function requires dom be loadedinitpage function ifdomloaded if dom is already loaded just call the function initpagehelper else if dom is not loaded attach the function to be run when it does load documentobservedomloaded initpagehelper the callback gets called properly due to some magic behind the scenes that you can learn about from this google talk featurerelatedwhats the easiest crossbrowser method for asking if the dom has loaded alreadyeditheres the full solution i went withi included prototype and the asynchronous script loader using the normal method life is just so much easier with prototype so i am willing to block for that script script typetextjavascript srcprototypeprototypejsscriptscript typetextjavascript srcasyncloaderjsscriptand actually in my code i minified the two files above and put them together into one file to minimize transfer time and http requests then i define what i want to run when the dom loads and then call the function to load the other scripts script typetextjavascript initpage function scriptscript typetextjavascript loadscriptasyncscriptaculousscriptaculousjs initpage loadscriptasyncscriptaculouseffectsjs initpage loadscriptasyncscriptaculouscontrolsjs initpage loadscriptasyncmypagejs initpagescriptlikewise the requests above are actually compressed into one httprequest using a minifier they are left separate here for readability there is a snippet at the bottom of this post showing what the code looks like with the minifier the code for asyncloaderjs is the following allows you to load js files asynchronously with a callback that can be called immediately after the script loads or after the script loads and after the dom is loaded prototypejs must be loaded first for best results create a regular script tag that calls a minified combined file that contains prototypejs and this file then all subsequent scripts should be loaded using this function var onload queue var dom loaded falsefunction loadscriptasyncsrc callback run immediately var script documentcreateelementscript scripttype textjavascript scriptasync true scriptsrc src ifundefined typeof callback scriptonload function if dom loaded run immediately callback else onload queuepushcallback clean up for ie and opera scriptonload null scriptonreadystatechange null scriptonreadystatechange function if scriptreadystate complete if dom loaded run immediately callback else onload queuepushcallback clean up for ie and opera scriptonload null scriptonreadystatechange null else ifscriptreadystate loaded evalscript if dom loaded run immediately callback else onload queuepushcallback clean up for ie and opera scriptonload null scriptonreadystatechange null var head documentgetelementsbytagnamehead0 headappendchildscriptdocumentobservedomloaded function dom loaded true var len onload queuelength for var i 0 i len i onload queuei onload queue nulli added the option to run a script immediately if you have scripts that do not rely on the page dom being fully loaded the minified requests actually look likescript typetextjavascript srcminbjavascriptlibfprototypeprototypejsasyncloaderjsscriptscript typetextjavascript initpage functionescriptscript typetextjavascript srcstr minfimplode js files loadscriptasyncsrcstr initpage scriptthey are using the plugin from thanks for the helpk,['javascript'] +101743,what is microsoftcontracts and where is it coming from i have a custom sharepoint job that is erroring out when it tries to run when i look at the error i seecould not load file or assembly microsoftcontracts version10 cultureneutral publickeytoken736440c9b414ea16 or one of its dependencies the system cannot find the file specifiedi have searched my solution and there is no reference to this anywhere where could this be coming from,['.net'] +101746,enable browsers to remember form values when using jquery see i have got a form in my web app and if the user submits it and presses the browser back button the form values are remembered eg any values the user enteredonce i add jquery 142 to the page eg reference it as a script then this behaviour changes from what i have read this happens because jquery hooks the onunload event and this is a signal to browsers that the script is not bfcacheaware so it turns off bfcacheupdate i looked into this a bit further and this problem was fixed in jquery 14 it seems it looks like the problem was caused by the autocomplete plugin i was using i will post a resolution if i find one,['jquery'] +101756,programmatically format xml in indented form just like visual studios autoformat i have not found a way using nets xmlwriter and associated xmlwritersettings to format an xml string in indented form exactly the way that visual studio does it with its autoformat command ctrle ctrld or depending on keyboard mapping ctrlk ctrldi would like to do this because i habitually autoformat all my files in vs both code and config files i have an installer app that updates config files and i would like to see actual diffs instead of the entire document changedi have not explored all the different formatting options for autoformat but i like each xml attribute to be on a separate line with the first on the same line as the opening tag and subsequent ones lined up with the first like thisasset assetid12345 bucketdefault ownernobody file pathlocalhostshareassetamov metadata metadataid23456 keyasset type valuevideoasseti have tried formatting with xmlwritersettings properties newlinehandling newlinehandlingnone and newlineonattributes true but that puts the first attribute below the opening tag and all attributes have the same indentation regardless of the of characters in the element name like thisasset assetid12345 bucketdefault ownernobody file pathlocalhostshareassetamov metadata metadataid23456 keyasset type valuevideo assetnotice that the standard xmlwriter also ends attributeonly elements with extra space before the slash which i thislike but not sure if that is the xml standard i would think that visual studio uses the same api options readily available to developers but i have yet to find those magical settings anyway heres my format methodpublic static string formatxml string xmlstring bool indented using textreader textreader new stringreader xmlstring using xmlreader xmlreader new xmltextreader textreader using textwriter textwriter new stringwriter var settings new xmlwritersettings if indented settingsindent true settingsindentchars settingsnewlineonattributes true settingsnewlinehandling newlinehandlingnone using var xmlwriter xmlwritercreate textwriter settings while xmlreaderread xmlwriterwritenode xmlreader false return textwritertostring,['.net'] +101778,removing a calayer at index 0 i have added a gradient layertheviewlayer insertsublayergradient atindex0and later on in another method i want to remove this layer i figured i should get the array of sublayers then get the sublayer at index 0 and call removefromsuperlayer on it is this the correct way or if not can you do itcheers,['iphone'] +101794,uniquely identifying reference types in the debugger i come from a c background so apologies if this is a nonc way of thinking but i just need to know in c if i have two pointers and i want to know if they point to the same thing i can look in the memorywatch window and see their value to see if they are pointing to the same memory spacein c i have not been able to find something along those lines one reference type with exactly the same values could in fact be the exact same object or it could be something wildly differentis there a way for me to see this kind of information in c perhaps some kind of equivalent to the operator for the watch window or some such,['c#'] +101796,how to set div value how do i set the valuetext of a divdiv idnumberofdivbtnclickfunction event getjsonhttphostmyserviceimplsvcgetcountmethod id 1 function data alertdata numberofval data,['jquery'] +101806,nsoutlineview remove thisclosure triangle and indent i am using nsoutlineview for a project and cannot seem to figure out two thingshow to remove the thisclosure triangle for tree nodes apps like itunes seem to be able to do thisis there some sort of nsoutlineview delegate method that is used for this or does it require a subclasshow to thisable indenting for items i have tried using setindentationperlevel and setting it to 0 as well as changing the column indent to 0 in interface builder but it does not seem to have any effect,['objective-c'] +101816,passing javascript variable to html textbox i need help on html formi got a javascript variable and i am trying to pass the variable to a html form texbox i want to thisplay the variable on the textbox dynamically but i do not know how to pass the variable to the html form and call the variablevar testinput typetext namelg value size25 maxlength50 thisabledthisabledbrbrhow do i pass test to html form and change its valuethanks,"['javascript', 'html']" +101817,i need help adding an array to a vector in c i am following along with the opengl super bible 5th edition and they define a vectorvector as in math as typedef float m3dvector3f3i am trying to add an instance of this to an stdvectorthe re sizable array in c however i keep getting an error saying array initialization needs curly bracesfull errorthe way i defined the stdvector and the way i am adding to it isstdvectorm3dvector3f verticesfloat vertex3sscanf slinec str s f f f vertex0 vertex1 vertex2m3dvector3f v vertex0 vertex1 vertex3verticespush backvi have gathered that the problem is with the verticespush backv call because i do not get an error when i comment that out could someone explain to me and help me figure out why it would not let me add this vector to my vector,['c++'] +101824,change background color of uimodaltransitionstylefliphorizontal i would like to change the color behind the flip from white to a different color or picture is that possible,"['iphone', 'ios']" +101832,what does a constructor return my question is what does a constructor return this question is not quite different from what is the return type of a constructori have read somewhere that a constructor returns a complete object implicitly ie implicit return type is the name of the class but it shall not be specified explicitlystruct emptyint main empty creates a temporary and implicitly a constructor is calledso as per my interpretation the implicit return type should be the name of the class in this case empty is my wild interpretation correct,['c++'] +101834,deleting the current session with racksessioncookie i feel like i am missing something obvious here and i am hoping that as soon as i post this someone will shame me with the google search link i was missing enable sessionsget logout do what goes here to kill the sessionend,['ruby'] +101859,uniform thistribution with random i know if i use the random generator from java generating numbers with nextint the numbers will be uniformly thistributed but what happens if i use 2 instances of random generating numbers with the both random classes the numbers will be uniformly thistributed or not,['java'] +101870,django is it a good idea to generate js dynamically when i write my js files for a django project of course i do some ajax calls and for the moment the urls for those calls are hardcoded which is very uglyi was thinking of having the js files served by django instead of apache so i could take advantage of the template tags url is there a reason why i should not do this or is there a right way to do this i can give a least one it will consume a lot of time resending js files that have not changed what would be great is to have an application that generates files when restarting django server and serves them statically after,['javascript'] +101872,how do i change the color of radio buttons i mean a radio button itself consists of a round shape and a dot at the center when the button is selected what i want to change is the color of both can this be done using css,['css'] +101875,sql how to properly check if a record exists reading some sql tuning documentation i found thisselect count counts the number of rows often is improperly used to verify the existence of a recordis select count really that bad whats the proper way to verify the existence of a record,['sql'] +101876,injection in my quartz job i would like to know how can i use injection in my job using guiceas i cannot use inject on the default constructor may i use it directly on the attribute as follow i always got a nullpointerexception with persondao i know that a dao has nothing to do here but it is just for testingpublic class simplequartzjob implements job inject persondao person private static logger logger loggergetloggersimplequartzjobclassgetname public simplequartzjob override public void executejobexecutioncontext context throws jobexecutionexception if loggerisdebugenabled loggerdebugin simplequartzjob executing its job at new date by contextgettriggergetname logic in my module i have the following declarationbindpersondaoclasstohibernatepersondaoimplclassactually i use the persondao here because i know it works within another class with injection but the injection is done on the constructor level therecan someone give me an advicethx very much have a nice dayhere is more info about quartz configwebxml servlet servletnamequartzinitializerservletname thisplaynamequartz initializer servletthisplayname servletclassorgquartzeeservletquartzinitializerservletservletclass loadonstartup1loadonstartup initparam paramnameconfigfileparamname paramvaluequartzpropertiesparamvalue initparam initparam paramnameshutdownonunloadparamname paramvaluetrueparamvalue initparam initparam paramnamestartscheduleronloadparamname paramvaluetrueparamvalue initparam servletquartzpropertiesorgquartzpluginjobinitializerclassorgquartzpluginsxmlxmlschedulingdataprocessorpluginorgquartzpluginjobinitializerfilenamesquartzconfigxmlorgquartzpluginjobinitializerfailonfilenotfound trueorgquartzthreadpoolclass orgquartzsimplsimplethreadpoolorgquartzthreadpoolthreadcount 5orgquartzthreadpoolthreadpriority 5quartzconfigxml xml version10 encodingutf8jobschedulingdata xmlns xmlnsxsi xsischemalocation scheduling data 1 8xsd version18 schedule job namemailjobname groupmyjob groupgroup descriptionthe job descriptiondescription jobclasvcdataserverquartzsimplequartzjobjobclass job trigger cron namemytriggername groupmytrigger groupgroup jobnamemailjobjobname jobgroupmyjob groupjobgroup cronexpression10 cronexpression cron trigger schedulejobschedulingdata,['java'] +101891,opencv could not find encoder for the specified extension here is my code i am using to convert iplimage to jpgiplimage fiplimageheaderfiplimageheader cvcreateimageheadercvsize160 120 8 3fiplimageheaderimagedata char memblockvectorint push backcv imwrite jpeg qualityppush back10vectorunsigned char bufcvimencodejpeg fiplimageheader buf pcvreleaseimageheaderfiplimageheaderbut i am getting this erroropencv error unspecified error could not find encoder for the specified extension in imencode file buildbuilddopencv210srchighguiloadsavecpp line 409terminate called after throwing an instance of cvexception what buildbuilddopencv210srchighguiloadsavecpp409 error 2 could not find encoder for the specified extension in function imencodewhy is that i have opencv 21 installed and this works so obviously jpg encoder must be therecvsaveimagehomerichardimjpg fiplimageheader,['c++'] +101898,valgrind reports memory possibly lost when using glib data types i am developing a library using a number of glib datastructures ghashtable gslist etc i have been checking my code frequently for memory leaks using valgrind most of the issues valgrind points out are quite easy to fix however there is a few that i cannot figure out all of these are reported as possibly lostat the top of the valgrind stacktrace i always find the same 4 libraries297 1512 bytes in 3 blocks are possibly lost in loss record 24 of 25297 at 0x4004b11 memalign vg replace mallocc532297 by 0x4004b6b posix memalign vg replace mallocc660297 by 0x5e9ac4 in liblibglib20so012003297 by 0x5ea4fe g slice alloc in liblibglib20so012003further down in the call stack there is always a call to a glib function such as g key file new g slist prepend g strsplit g key file load from file g file get contents my questions are has anyone come across this and found a way around it or is this something i can thisregard is it due to glib using memory pools as suggested here i am using valgrind350 glib2123 gcc gcc 412 20080704 red hat 41248 centos release 55 final,['c'] +101915,animate textlabel in uitableviewcell using willtransitiontostate i am trying to animate the textlabel in a uitableviewcell when i press the edit buttoni am trying to make it fade out and fade infading in works but when i press edit the textlabel thisappears and when i press on done i fades in just perfectlycan anyone tell me why it is not workingthanks in advance voidwilltransitiontostateuitableviewcellstatemaskstate super willtransitiontostatestate if state uitableviewcellstateeditingmask state uitableviewcellstateshowingdeleteconfirmationmask uiview beginanimationsnil contextnull uiview setanimationduration03 labelalpha 00 uiview commitanimations voiddidtransitiontostateuitableviewcellstatemaskstate super didtransitiontostatestate if state uitableviewcellstateeditingmask state uitableviewcellstateshowingdeleteconfirmationmask uiview beginanimationsnil contextnull uiview setanimationduration05 labelalpha 10 uiview commitanimations,['iphone'] +101921,low fps when accesing iphone video output image buffer i am trying to do some image processing on iphone i am using to capture the camera framesmy problem is that when i am trying to access the captured buffer the camera fps drops from 30 to about 20 does anybody knows how i can fix iti use the lowest capture quality i could find avcapturesessionpresetlow 192x144 in kcvpixelformattype 32bgra format if anybody knows a lower quality i could use i am willing to try itwhen i do the same image access on other platforms like symbian it works okhere is my codepragma mark pragma mark avcapturesession delegate voidcaptureoutputavcaptureoutput captureoutput didoutputsamplebuffercmsamplebufferrefsamplebuffer fromconnectionavcaptureconnection connection we create an autorelease pool because as we are not in the main queue our code is not executed in the main thread so we have to create an autorelease pool for the thread we are in nsautoreleasepool pool nsautoreleasepool alloc init cvimagebufferref imagebuffer cmsamplebuffergetimagebuffersamplebuffer lock the image buffer if cvpixelbufferlockbaseaddressimagebuffer 0 kcvreturnsuccess calculate fps and thisplay it using main thread self performselectoronmainthreadselectorupdatefps withobject id nil waituntildoneno uint8 base uint8 cvpixelbuffergetbaseaddressimagebuffer image buffer start address size t width cvpixelbuffergetwidthimagebuffer size t height cvpixelbuffergetheightimagebuffer int size heightwidth uint8 prgbtmp m prgbimage here is the problem m prgbimage is rgb image i want to process in the for loop i convert the image from bgra to rgb as a resault the fps drops to 20 for int i0isizei prgbtmp0 base2 prgbtmp1 base1 prgbtmp2 base0 base base4 prgbtmp prgbtmp3 thisplay received action self performselectoronmainthreadselectorthisplayaction withobject id nil waituntildoneno self thisplayactioneyeplayoutput saveframe imagebuffer unlock the image buffer cvpixelbufferunlockbaseaddressimagebuffer0 pool drain as a followon to the answers i need to process the image in realtime it is being thisplayedi noticed that when i use avcapturesessionpresethigh the most simple thing i do like for int i0isizei x base0causes the framerate to drop to 45 fps i guess its because an image in that size is not cachedbasically i need 96x48 image is there a simple way to downscale the camera output image a way that uses hardware acceleration so i could work with the small one,['iphone'] +101931,design class aggregation stack allocation vs dynamic memory allocation please have a look at the two simplified examples of designing a class aggregation belowsolution 1header need include forward declaration is not enoughinclude doorhclass cgaragepublic cgarageconst stdstring valprivate cdoor m doorsourceinclude garagehcgaragecgarageconst stdstring val m doorvalsolution 2headerinclude smart ptrhpp forward declarationclass cdoorclass cgaragepublic cgarageconst stdstring valprivate scoped ptrcdoor m doorsourceinclude garagehinclude doorhcgaragecgarageconst stdstring val m doornew cdoorvalquestions concerning the creation of the cdoor memberwhat advantagesthisadvantages do you see in the design of the examples dynamic allocation of cdoor vs automatic allocationthis is what i came up withsolution 1 no issues with memory handling or lifetime no need for expensive memory allocation at runtime need additional include in header compilation speed slower closer coupling to cdoor many includes in header files are considered badsolution 2 loose coupling with cdoor in header only forward declaration needed memory needs to be handled by programmer which design do you usually prefer for what reason,['c++'] +101940,limit the amount of number shown after a decimal place in javascript hay i have some floats like these434552768367and i want to thisplay them like this434276367i do not want to round the number up or down just limit the amount of numbers shown after the decimal place to 2,['javascript'] +101961,query to get xml output for hierarchical data using for xml path in sql server i have a table with columns nodeid nodename parentnodeid and i want to ouput entire table data in the form of xml like the following using sql query i think for xml path mode in sql server can be used to achieve this i use sql server 2008 using recursion but not sure how thanks in advancexml version10 encodingutf8 nodes node id1 namenode1 node id11 namenode11 node id1 namenode1 node id112 namenode112 node node node id2 namenode2 node id21 namenode21 node id211 namenode211 node id212 namenode212 node nodenodes,['sql'] +101997,mysql how to load data with fixedrow format into user variables i am trying to load a file where are all the lines use the same rules assume header is a single lineheader1header2but unluckily when i try to use the load data infile statement i get this error error code 1409cannot load value from file with fixed size rows to variablethis is the code i wroteuse testdrop table if exists example hcreate table example h id char20 sp char3 iva char11 primary key nlp char6 dlp date duvi date delp char30 filler char39 vtlp char3 fill char49load data infile btilsptxt into table testexample h fields terminated by lines terminated by n id sp iva nlp var date one var date two delp filler vtlp fill set dlp str to datevar date one ymd duvi str to datevar date two ymdi had this idea reading the bottom of this page comment by ramam pullella and i found the same explained on some websites but i cannot understand why i am getting this errorif i do not use the var date one and var date two variables and so the str to date function the date is not rendered as mysql needs the date in the file is something like 20100701 then that field would contain all zeros or a different date than what i am expecting if i change dlp and duvi to be represented by char8 then it works but i would not use the sql date comparisons and similar toolscan you help me please thank you very muchedit it seems the problem is given by the line terminated by since this kind of line is a fixed row undelimited maybe it cannot be assigned to variable for an unknown reason but it is this way it worksthe documentation saysuser variables cannot be used when loading data with fixedrow format because user variables do not have a thisplay widthany suggestionreediti have read the comment by ryan neve at bottom of that page he gives a trick to read fixedrow into variablesload data local infile file name into table tablevar1set datestr to datesubstrvar1310mdytimesubstrvar1148windvelocitysubstrvar1265winddirectionsubstrvar13windcompasubstrvar1383windnorthsubstrvar1436windeastsubstrvar1516windsamplessubstrvar1614do you think it is a good way to do it,"['sql', 'mysql']" +102003,collectionssort with multiple fields i have a list of report objects with three fields all string typereportkeystudentnumberschooli have a sort code goes likecollectionssortreportlist new comparatorreport overridepublic int comparefinal report record1 final report record2 return record1getreportkey record1getstudentnumber record1getschool comparetorecord2getreportkey record2getstudentnumber record2getschool for some reason i do not have the sorted order one advised to put spaces in between fields but whydo you see anything wrong with the code,['java'] +102010,browser support of drag and drop file uploads i cannot seem to find it online anywhere just demos or links to the spec or the google gears implementation that is all great but i was curious what the actual browser support of it is across the main browsers and os firefox chrome safari opera and does ie have an alternative what about ie9,['javascript'] +102028,loop through all controls on aspnet webpage i need to loop through all the controls in my aspnet webpage and do something to the control in one instance i am making a giant string out of the page and emailing it to myself and in another case i am saving everything to a cookiethe problem is masterpages and items with collections of controls inside them i want to be able to pass in a page to the method then have that method be generic enough to loop through all controls in the innermost content page and work with them i have tried doing this with recursion but my recursion is incomplete i want to pass a page object into a method and have that method loop through all controls in the innermost content page how can i achieve this private static string controltostringcontrol control stringbuilder result new stringbuilder string controlid stringempty type type null foreach control c in controlcontrols try controlid cidtostring if c is ieditabletextcontrol resultappendcontrolid ieditabletextcontrolctext resultappendbr else if c is icheckboxcontrol resultappendcontrolid icheckboxcontrolcchecked resultappendbr else if c is listcontrol resultappendcontrolid listcontrolcselectedvalue resultappendbr else if chascontrols resultappendcontroltostringc resultappendbr catch exception e return resulttostringwithout trycatchobject reference not set to an instance of an objecton line controlid,"['c#', 'asp.net']" +102037,ifelse in pythons list comprehension how can i do the following in pythonrow unicodexstrip for x in row if x is not none else essentiallyreplace all the nones with empty strings and thencarry out a function,['python'] +102038,hibernate illegal attempt to associate a collection with two open sessions i am using persistence in a project for school and i have a problem when i am try to deleting and updating object all others queries worksthe exception is illegal attempt to associate a collection with two open sessionsi close every session i have openedhibernateutils codepublic class hibernate protected static final sessionfactory sessionfactory private session session static try create the sessionfactory from hibernatecfgxml sessionfactory new configurationconfigurebuildsessionfactory session catch throwable ex make sure you log the exception as it might be swallowed systemerrprintlninitial sessionfactory creation failed ex throw new exceptionininitializererrorex public void createobject obj thissession sessionfactoryopensession sessiongettransactionbegin sessionsaveobj sessiongettransactioncommit sessionclose public void refreshobject obj thissession sessionfactoryopensession sessiongettransactionbegin sessionrefreshobj sessiongettransactioncommit sessionclose public void updateobject obj thissession sessionfactoryopensession sessiongettransactionbegin sessionsaveorupdateobj sessiongettransactioncommit sessionclose public void deleteobject obj thissession sessionfactoryopensession sessiongettransactionbegin sessiondeleteobj sessionflush sessiongettransactioncommit sessionclose protected string protectstringstring toprotect return toprotectreplace daoperson public class daoperson extends hibernate public void removeperson p if p instanceof student student s studentp setpersistenceclassclass set sgetclasses iteratorpersistenceclassclass it setiterator while ithasnext persistenceclassclass r itnext rgetstudentsremoves pgetbirthcountry pgetcountry thisdeletep else thisdeletepfor information my mapping file of students is class namepersistenceclassperson tablet person id nameid columnperson id generator classnative id property namefirstname columnperson first name notnulltrue property namelastname columnperson last name notnulltrue property nametype columnperson type notnulltrue property namebirthdate columnperson birth date property namebirthcity columnperson birth city property namephonenumber columnperson phone number property namemobilenumber columnperson mobile number property namemail columnperson mail property nameaddress columnperson address address property namezipcode columnperson address zipcode property namecity columnperson address city property nameimage columnperson image typeimage manytoone namecountry columnperson address country classpersistenceclasscountry manytoone namebirthcountry columnperson birth country classpersistenceclasscountry manytoone namecivility columnperson civility classpersistenceclasscivility manytoone namesex columnperson sex classpersistenceclasex joinedsubclass namepersistenceclastudent tablet student key columnperson id set nameclasses tablet class student inversetrue key columnperson id manytomany classpersistenceclassclass columnclass id set joinedsubclass joinedsubclass namepersistenceclassteacher tablet teacher key columnperson id joinedsubclass classand the main mapping file hibernateconfigurationsessionfactory database connection settings property nameconnectiondriver classorggjtmysqldriverpropertyproperty nameconnectionurljdbcmysqllocalhostprojetpropertyproperty nameconnectionusernamerootpropertyproperty nameconnectionpasswordproperty jdbc connection pool use the builtin property nameconnectionpool size10property sql dialect property namedialectorghibernatedialectmysqlinnodbdialectproperty drop and recreate the database schema on startup also try with aupdatea to keep the previous values property namehbm2ddlautoupdateproperty echo all executed sql to stdout property nameshow sqltruepropertymapping resourcepersistenceconfigurationspersonhbmxmlmapping resourcepersistenceconfigurationscountryhbmxmlmapping resourcepersistenceconfigurationscivilityhbmxmlmapping resourcepersistenceconfigurationssexhbmxmlmapping resourcepersistenceconfigurationsformationhbmxmlmapping resourcepersistenceconfigurationsyearhbmxmlmapping resourcepersistenceconfigurationsclasshbmxmlmapping resourcepersistenceconfigurationssubjecthbmxmlmapping resourcepersistenceconfigurationsroomhbmxmlmapping resourcepersistenceconfigurationslessonhbmxmlsessionfactoryhibernateconfigurationi try a lot of configuration but i have everytime the same exception if somebody have an idea i want it thanks sorry for my bad english,['java'] +102047,how do i turn an array to a string in php for an array like the one below what would be the best way to get the array values and store them as a commaseparated stringarray 0 33160 1 33280 2 33180 3 33163 4 33181 5 33164 6 33162 7 33179 8 33154 9 33008 10 33009 11 33161 12 33261 13 33269 14 33169 15 33022 16 33141 17 33168 18 33020 19 33023 20 33019 21 33153 22 33238 23 33138 24 33167 25 33082,['php'] +102048,what does exporting private keys mean makecert pe by specifying a ape switch using makecert utility we make a private key exportablea what is it meant by private key being exportable that we can copy the created pvk file containing private key to another system and use it there b if so then i assume pvk is only created if private key is to be exported thus how do we useobtain private key when we do not want to export it and thus do not specify ape switch when creating a certificatethank you,['.net'] +102070,is it viable to handle mysql backups with git today i had this really neat idea for backing up my database put the dump file in a git repository then commit on each dump so that i have both the most recent copy but can easily roll back to any previous backup i can also easily pull a copy of the repository on a regular basis to keep a copy on my own computer as a backup of the backups it definitely sounds cleverhowever i am aware that clever solutions sometimes have fundamental flaws what sort of issues might i hit storing mysqldump diffs in git is it worth it what do most people do in order to have multiple database backups on the server and keep redundant copies elsewhere,['mysql'] +102076,accent insensitive regex my codejqueryfnextend highlight functionsearch var regex new regexp searchreplacei0 ig return thishtmlthishtmlreplaceregex functiona b c return acharat0 a strong classhighlight c strong i want to highlight letters with accentsiebodyhighlightcaoshould highlight aao or aao or cao or exprecaotion or caotionhow can i do that,['jquery'] +102085,what does one question mark following a variable declaration mean whilst playing around in an open source project my attempt to tostring a datetime object was thwarted by the compiler when i jumped to the definition i saw thispublic datetime timestampmight someone please enlighten me on what this is called and why it might be useful,"['c#', '.net']" +102091,how do i get the type of constructor parameter via reflection i am using type hinting on my constructor parameter list like sopublic function constructfoorepository repositoryis there a way to use the php reflection api to get the hinted type in other words i want a reflection function that i can call to somehow get back the string foorepository i have tried getting the constructor via reflection and then getting the parameters if the constructor but i do not see anything that will give me the string of the hinted type,['php'] +102095,how do i get ruby to parse time as if it were in a different time zone i am parsing something like this112310 232957which has no time zone associated with it but i know it is in the utc time zone while i am not how can i get ruby to parse this as if it were in the utc timezone,['ruby'] +102096,assign custom identifier to an id property i am migrating a legacy system over to use hibernate 3 it currently generates its own identifiers to keep with what the system currently does before i try and move it over to something a little better how would i go about specifying using annotations my own class that will return the custom generated identifiers when an insert occurssomething likeidcustomidgeneratorfooclass obviously this is not a real annotationpublic string getid where the foo class has one method that generates the identifiercurrently i am just calling the setidstring id method manually but was hoping for a better way to deal with this situation,['java'] +102099,should i use windows management service or remote agent service to publish to a remote server i have a remote web server that i have full administrator access over and i want to deploy a websitewhen i use visual studios publish tool among other things which seem a bit less convenient ftp etc i have the option of using either windows management service or remote agent service all the documentation says is thisto publish remotely through remote agent service use httpremotecomputername this option is typically used to deploy a web application inside a network in an intranet scenario you must have appropriate permissions to perform the deployment on the destination serverto publish to a hosting site using windows management service use the value that is specified by the hosting provider you can typically use just a server name hostedremoteserver or a complete url that includes a server name a port number and the web deploy handler name httpshostedremoteserver8172msdeployaxd the hosting provider can tell you the name of the server and the port number if applicablethis is not enough information for me to decide though yeah i am not publishing over a network but i do have full access over the machine i am deploying to at the same time msdeploy is the big fancy thing that scott hanselman describes in his talk and that i have been convinced as being the awesome way to deployso which should i do are there any obscure security considerations or anything,['asp.net'] +102133,silverlight media player position problem i am facing a strange issue my application plays movies from specific positions so even a position mentioned in milliseconds matters for me i am assigning a position to a media element but it is showing the wrong frame i do not know why media player is not playing from the position that i am givinghere is some sample code timespan otimespan timespanfrommilliseconds16800200 this shows 044020 mediaplayerposition otimespan but after assigning value is 04401990here is a screenshot before and after assigningcan anybody tell me what i am doing wrong here,"['c#', 'asp.net']" +102134,find mapped value of map is there a way in c to search for the mapped value instead of the key of a map and then return the key usually i do somemapfindsomekeysecond to get the value but here i want to do the opposite and obtain the key the values and keys are all unique,['c++'] +102155,why is the aspnetvisual studio web development server so slow xkcdi know that compiling nowadays is much faster than it was before yet for me it seems that compiling and especially runningdebugging aspnet projects with the visual studio web development server is incredibly slowsince the beginning of last summer i have been working heavily on aspnet mvc projects of course the best way to debug them is by using the web server that comes with visual studio when doing that i get horrendously slow loading times chrome dev tools typically report that loading one of my pages had a 3 minute wait time followed by a short loading timei have seen these two questions but they do not help while i do most of my debugging work in chrome the same happens in iehas anyone else had this problem before if so any tipsalso i doubt that the problem lies with the speed of my machine this computer is really fast running windows 7 and visual studio 2010 so i do not see why aspnet debugging should be so slowupdate in his answer below jon skeet suggested attempting to identify whether the problem is being caused by the environment or by the code itself i created a brand new mvc project and ran it the first test appeared to be much faster however after testing it a few more times it is safe to say that the first test was an anomaly usually it takes as long as my big project 2 3 minutes thus this is a problem with the environment thanks in advance for any helpupdate 2 it is been a while since i updated this question here are some details i have gathered since my last updatethis delay is occuring on both of my development machines both running windows 7 and visual studio 2010this delay is happening for all my mvc2 and mvc3 projects but i have not experimented with plain aspnet yetplainvanilla mvc projects experience the same delay as mvc projects with big codebasesthisabling intellitrace did not helpthisabling ipv6 did not helpi have not found a solution for this problem so i have been stuck with huge wait times does anyone know how to solve this,"['c#', 'asp.net']" +102163,difference between aspnet web app and aspnet mvc 3 empty web app i want to build my own web framework and i want to build it in c i figure the easiest way to get started is to use aspnet to handle all the server communication stuff the rest i want to build my self i know next to nothing about aspnet but know c the mvc pattern and other web frameworks quite wellin visual studio 2010 i seeaspnet web applicationaspnet mvc 2 empty web applicationaspnet mvc 3 empty web applicationi figure one of these should be good as a base i just want some entry point into some c code i started with php so it is a little bit weird for me to not be able to just load up a file in my browser anyway which should i use whats the difference between a plain aspnet web app and an empty mvc 3 app if it is empty it should not be using any of the mvc framework should it i just want to make sure i use the latest and greatest asp for handling the server stuff before i embark down this road,['asp.net'] +102168,grand central thispatch gcd with coredata i am using grand central thispatch gcd in my application to do some heavy lifting the application is using coredata for data storage purposes heres my scenario along with relevant questionthispatch queue t main queue thispatch get main queuethispatch queue t request queue thispatch queue createcomapprequest nullthispatch asyncrequest queue mynsmanagedobject mobject selffetchedresultscontroller objectatindexpathnsindexpath indexpathforrow0 insection0 a heavy lifting a a update mobject a self savemanagedobjectcontext as a result of self savemanagedobjectcontext fetchresultscontroller delegate methods are called automatically consequently the ui updation logic kicksnow my question is do i need to use main queue for savemanagedobjectcontext should i perform all operations on my nsmanagedobject in main queue some of the operations that update the nsmanagedobject might take 23 seconds please advise,['iphone'] +102177,devise logging out automatically after password change in devise if i change users password and after it gets updated in the db the site immediately logs out the user i do not want this behavior how do i do that please help,['ruby-on-rails'] +102181,how to print the string a pointer points to while debugging using gdb how do i inspect a string a pointer is pointing to when stepping through a program using gdb i can see the a pointer is pointing to 0x82c6e10 i know it is a string how do i print it using printfsn 0x82c6e10 gives bad format string missing the fact that gdb does not complain of unknown command tells me that the solution is some variation of what i am doing am i right i tried escaping the quotes but that did not help,['c'] +102184,convert view into bitmap possible duplicateconverting a view to bitmap without thisplaying it in android i am trying to convert the view into bitmap from following reference linklink textnow the problem is how can i get the bitmap that is being converted from view only in the example author has used relativelayoutthispatchdrawc but this line is giving me compile time error iethe method thispatchdrawcanvas from the type viewgroup is not visiblehere is my code and i have written the following code inside oncreate function canvas cnull create layout relativelayout relativeview relativelayoutlayoutparams lp new relativelayoutlayoutparams relativelayoutlayoutparamsmatch parent relativelayoutlayoutparamsmatch parent relativeview new relativelayoutthis relativeviewsetlayoutparamslp background of layout bitmap viewbgrnd bitmapfactorydecoderesourcegetresourcesrdrawablebgblack relativeviewsetbackgrounddrawablenew bitmapdrawableviewbgrnd associated with canvas bitmap returnedbitmap bitmapcreatebitmap320480bitmapconfigargb 8 c new canvasreturnedbitmap paint paint new paint create imageview that holds image imageview newimage new imageviewthis bitmap srcbitmap bitmapfactorydecoderesourcegetresourcesrdrawablebgpink newimagesetimagebitmapsrcbitmap textview newtext new textviewthis newtextsettextthis is the text that its going to appear cdrawbitmapviewbgrnd 0 0 paint relativeviewlayout100 0 256 256 relativeviewaddviewnewimage relativeviewaddviewnewtext here i am getting compile time error so for timing i have replaced this line with relativeviewdrawc relativeviewthispatchdrawchere the returnedbitmap should contain the image of imageview and textview but this bitmap contains only bacground bitmap of relativeview ie bgblack,['android'] +102190,how to sleep a c boost thread seems impossible to sleep a thread using boostthreadmethod sleep requires a system time but how can i build itlooking inside libraries does not really help muchbasically i have a threadinside the function that i pass to this thread as entry point i would like to call something like boostthis threadsleepor something how to do thisthank you,['c++'] +102194,wifi to wifi connectivity using android i want to transfer messages from the android device to desktop application my question is that can i connect the android wifi device with the desktop wifi device without any use of internet connection i want to use it just like the bluetooth is this possible or not if it is possible then how can i implement itthanks and regardsamit thaper,['android'] +102205,i need a workaround for a safarichrome bug that is becoming a thorn in my side so i have this neat little javascript function that i am using to print text to the browser window in a cool commandprompty style it takes a string and prints it one character at a time to the window at a set interval here it is i have cut out all the unnecessary parts so that this will work as a standalone exampledoctype html public w3cdtd xhtml 10 transitionalen html xmlnshead titletitle script typetextjavascript srcscript script typetextjavascript var letterindex 0 var intervalid 0 function writeonelettermystring var char mystringletterindex thisplayappendchar letterindex if letterindex mystringlength letterindex 0 clearintervalintervalid function carethtmlu2588 this will help you visualize where the script is at in it is sequence and make it painfully obvious when the freezing issue occurs the following string sample is so long because it is important that you be able to duplicate this error to understand my question var mystring quisque vestibulum consequat orci in euismod tortor dapibus eu duis nec urna nec erat sagittis pretium vel ac diam nulla mi lorem tempor ut cursus in mattis non libero curabitur eget venenatis justo lorem ipsum dolor sit amet consectetur adipiscing elit maecenas blandit ante in ligula tincidunt quis vehicula massa scelerisque pellentesque nec posuere massa sed eget nunc a erat dictum faucibus in vitae tempor lorem class aptent taciti sociosqu ad litora torquent per conubia nostra per inceptos himenaeos lorem ipsum dolor sit amet consectetur adipiscing elit aenean vel imperdiet tellus suspenthisse ultricies sem a libero sagittis feugiat ut convallis magna eu mauris molestie dapibus nulla feugiat urna non ante facilisis non ultrices nisi viverra aliquam vitae magna libero cum sociis natoque penatibus et magnis this parturient montes nascetur ridiculus mus curabitur at odio sit amet nisi dapibus scelerisque in fringilla lorem at sapien rutrum scelerisque intervalid setintervalfunction writeonelettermystring 15 scriptheadbody span idthisplay spanspan idcaretspanbodyhtmlgo here to try out the sample code aboveif you are in ie or ff the code will run exactly as expected writing out every character in the string until it finishes however if you run this code in chrome or safari you get an interesting bug sometimes when the line hits the side of its container and the words wrap and drop to the next line it freezes the typing stops being rendered to the browser but it is still happening in the dom because if the page gets modified or the browser resized then the remaining text appears all at oncea couple things i have noticed about this are that it only seems to happen when it drops down a line with a leading space also if you resize the browser window while the script is still running or after the script has finished it will suddenly burst back into action and you will see the rest of the text any resizing maximizing etc will start the letters showing up again only to freeze again later of courseit is extremely frustrating since it never shows the rest of the string unless the page is modified by more javascript afterward or the browser is resized it completely defeats the entire purpose of writing the script in the first place when this happensany ideas i am completely stumped and google turns up nothingeditif you cannot reproduce the error it is probably because your screen is a different resolution than my own and you are getting lucky try to resize either the browser window the jsfiddle thisplay container or both and then run the script again it should not take much before you see it freeze try to aim so that one of the lines will word wrap on a space this seems to be where it happens mostlyi have done this in chrome and safari on 3 different computers one on a completely different network altogether if you still cannot see the error then run it in chrome and firefox side by side if chrome seems to finish earlier than ff then that is the freezing glitch in action if you resize the browser or modify the page in any way then suddenly all the remaining text will appear at once,"['javascript', 'jquery', 'html']" +102213,c to assembly call convention 32bit vs 64bit i have been following the excellent book programming ground up wanting to learn assembly although not in the book at this point i wanted to call my assembly function from c on a 32 bit machine this works as is when working from the bookwhat i do here is storing the first argument in ebx and the second in ecxtype power functionglobl powerpower pushq ebp movl esp ebp subl 4 esp movl 8ebp ebx movl 12ebp ecxi compile this and the rest of the function into an object file create a mainc where i prototype the function and call it something like thisint powerint b int xint a power2 1however when i compile this on a 64 bit machine i get some very unexpected results i modified the obvious like the fact that esp and epb needs to be replaced with rsp and rpb but digging with gdb reveals that the arguments are nowhere to be found on the stackchecking out what happens by using the s option to gcc i can see that instead of pushing the variables on the stack gcc stores the arguments in registers movl 1 esi movl 2 edi call poweron the 32 bit machine it does what i expect and push the arguments on the stack movl 1 4esp movl 2 esp call powernow what is going on here why does gcc pass the arguments in registers on 64 bit and on the stack on 32 bit this is very confusing and i cannot find any mention on this anywhere is there anyone who can enlighten me on this situation,['c'] +102245,get model associated with corresponding view in htmlhelper my view inherits modelsmymodel page languagec masterpagefilesomethingmaster inheritsmodelsmymodel i need a property modelsomething to be available in a htmlhelper method when i call it from this view htmlcustomhelper is there any way to access this maybe via viewcontext or viewdatadictionaryi do not want to explicitly pass modelsessionkey for each helper i call is there any approach that i missed or is this impossiblethanks,"['c#', 'asp.net']" +102256,how does pdo know last inserted id in mysql edit this question title originally was how does doctrine know last inserted id in mysql and was related to doctrine orm mapper after some digging i found out that this question is not related to doctrine but to pdo mysql mysql c api and finally to mysql clientserver communication i have decided to change the title so maybe someone will find answer to hishers questionfor those who are not using doctrine i was curious why bellowmysql queryinsert into category name valuescatecho mysql insert idor similarpdoexecinsert into category name valuescatecho pdolastinsertidwill lead to only one position without separate select last insert id in log1701 query insert into category name values catoriginal questioni have 2 tablescategoryidnameproductid name categoryidi created new category object and product object i assigned category object to product object i did not set any idsproduct new productproductname asdfcategory new categorycategoryname catproductcategory categoryafter that i flushed the connection and check mysql logs1684 query start transaction1684 query insert into category name values cat1684 query insert into product name categoryid values asdf 3121684 query commithow did doctrine know that the newly created category id is 312 there is nothing else in logs,"['php', 'mysql']" +102262,upgrade eclipse java compiler i started using ant that ships with eclipse it annoys me that i get hundreds of warnings in the lines ofjavac warning javaiobufferedinputstreamclassjavaiobufferedinputstreamclass major version 51 is newer than 50 the highest major version supported by this compiler javac it is recommended that the compiler be upgradedhow do i upgrade compiler,['java'] +102264,refresh parent window when the popup window is closed is there any way i can refresh the parent window when a popup window is closed without adding any javascript code to the popup windowi have a page parentphp on which users can click open popup to open a popup window this popup window shows some flash content and its not possible for me to add something like windowonunload function windowopenerlocationreload to the popup window page markupis there any other method to achieve thisthanks,"['javascript', 'jquery']" +102273,cannot identify reason for column ambiguously defined error here is the sql select allocoa id from qdodqtran owner allocation alloc inner join select hoa id hdiv ord no hprocess queue id hfrom ba no hfrom ba suf hfrom interest type cd hfrom interest type cd hfrom div ord grp htransfer percent h2original net amount h2new net amount from qdodqtran fund transfer hist h inner join select thistinct h0oa id h0original net amount h1new net amount from qdodqtran fund transfer hist h0 inner join select h4oa id sum h4new net amount as new net amount from qdodqtran fund transfer hist h4 group by h4oa id h1 on h0oa id h1oa id where h0original net amount h1new net amount and h0oa id 10 h2 on hoa id h2oa id h3 on allocoa id h3oa idevery column has it is table defined the main inner join the one after the alloc table runs fine when ran by itself any ideas why this is not working this is being executed against an oracle 10204 database i have also tried it against an 11201 database thinking if it was an oracle bug it would be resolved in 112 but it failed there as well,['sql'] +102283,custom container view controller i want to create my own container view controller ie something like uinavigationcontroller or uitabbarcontroller docs say i should not do that but why not navigation and tabbar containers are good examples that such thing is possible and works really well also i understand that iphone has small screen and people should not mess it up by navigation buttons etc but on an ipad there is a lot of space and splitting it to many view controllers would give us great opportunitiesi have a feeling apple did not add such api yet but they will few days ago they have added docs about ipadspecific controllers yeah container ones and they have modified texts to something lessforbiddinganyway what problems may i have if i try to use two or more view controllers on one screen i know only one of them will get events like orientation change or low memory warning so i have to pass these events to contained vcs i am afraid about compatibility with future versions of ios cause if they will add new events then contained vcs would not execute default actions inherited from uiviewcontroller anything else do you think my app may be rejected by apple maybe there is other way to have some view elements persistent on each screen without copying a lot of same code to every vcthanks in advance,"['iphone', 'ios']" +102284,target iphone application by model eg 3g vs 3gs much like the required device capabilities on the infoplist file is it possible to configure an application such that it will only be available on some device modelsi know how to target it by device family iphoneipod vs ipad but in this case i am looking to target by model i also know how to programmatically determine the model but what i want is for itunes to prevent some device models from being able to download an app which is why doing it via infoplist seems like it would be the best wayfor instance if i wanted an app to be available on iphone 3gs or iphoneipod 4 and upper but not on iphone 3g is there any way to do it,"['iphone', 'ios']" +102292,android which event fires when on screen keyboard appears i would like to hook to an event that fires when androids on screen keyboard appears for example when user taps edittext to bring up the keyboard anyone know which event or listener to usetimo,['android'] +102298,what is ecmascript in visual studio when i am setting my script type to javascript this comes up as an option in intellisensea quick google search came up with lame results leading me to believe this is not terribly popular to usewhat is it does anyone use it script typetextecmascriptwhy,['javascript'] +102301,align text with java graphics 2d can anyone tell me how to alight text right in java 2dheres the code it draws a column of text that is naturally aligned leftfont yfont new fontarial fontbold 13interval 0g2dsetfontyfontfor string l binlabels g2ddrawstringl 0 135 interval interval interval 15driving me crazythanks yallslothishtype,['java'] +102303,rails 3 setting the timezone to the current users timezone i put this in application controllerbefore filter set timezone def set timezone timezone current usertime zone end but i always get the errorundefined method time zone for user0xa46e358and i just do not know whyi hope someone can help,['ruby-on-rails'] +102322,webbrowser control in a new thread i have a list uris that i want clicked to achieve this im trying to create a new webbrowser control per uri i create a new thread per uri the problem i am having is the thread end before the document is fully loaded so i never get to make use of the documentcomplete event how can i overcome thisvar item new parameterizedthreadstartclicitclick var thread new threaditem name clickthread threadstarturiitempublic static void clickobject o var url uriitemo consolewritelineclicking urllink var clicker new webbrowser scripterrorssuppressed true clickerdocumentcompleted browsecomplete if stringisnulloremptyurllink return if urllinkequalsaboutblank return if urllinkstartswithhttp urllinkstartswithhttps urllink http urllink clickernavigateurllink,['c#'] +102330,how can i retrieve the udid on ios i was wondering if it was possible to find out the udid of the users iphone can someone shed some light,['ios'] +102348,compile time vs run time dependency java what is the difference between compile time and run time dependencies in javait is related to class path but how do they differ,['java'] +102354,c is push backnew object a memory leak is the following c code a memory leaklistpush backnew stringhias i understand it push back from any std collectioncontainer always makes a copy so if the new string is copied nothing can ever delete the newd string right since there is no reference to it after the push backam i correct or wrong herethanksjbuedit i think i am wrong since new will return a pointerwell always have the pointer to be able to delete the new string,['c++'] +102360,simple ajax with play i have been sifting through many jquery ajax tutorials and attempting to incorporate it with my play app but i am not quite understanding a few things is it possible someone could explain how to do the following through ajax calls 1 suppose i want to retrieve a list of contacts from a controller each contact has name phone email does the controller need to build the proper response for the template what does the controller look like what does the javascript look like to retrieve it2 for addingupdating a new contact through an ajax call what does the javascript look likehere is code for an example of the explanation above not using ajaxcontrollerpublic static void list list contacts contactfetchall rendercontactspublic static void addstring name string phone string email contact contact new contact contactname name contactphone phone contactemail email contactsavepublic static void updatelong id string name string phone string email contact contact contactfindbyidid contactname name contactphone phone contactemail email contactsavetemplate lists all contactslist contacts ascontact contactname contactphone contactemaillisttemplate add contactform contactsadd idforminput typetext namename input typetext namephone input typetext nameemail input typesubmit valueadd form,['jquery'] +102368,app crashes with 42 iphone simulator set startwithshell off i am writing application which perfectly works on 4041 iphone simulator but not 42i am getting such warningdetected an attempt to call a symbol in system libraries that is not present on the iphonefcntlunix2003 called from function get socket nonblocking in image testappif you are encountering this problem running a simulator binary within gdb make sure you set startwithshell off firsthow to set set startwithshell off on xcode i am tried to add this line to gdbinit but without luckwith 4041 sdk iphone simulator prints warnings about attempt to call symbol that is not present on the iphone in debug window but app do not crashes using using 42 app crashes how to prevent 42 crashes thanks,"['iphone', 'objective-c']" +102372,how can i use python to get the system hostname i am writing a chat program for a local network i would like be able to identify computers and get the userset computer name with python,['python'] +102384,reading a value from applicationini i have a value that is defined in applicationini conditionstime 50how can i read it in an zend action the zend way,['php'] +102389,how can i convert json to xml in ruby is there any way to convert json to xml in ruby,['ruby'] +102393,best practice to find source of php script termination i have a php script that grabs a chunk of data from a database processes it and then looks to see if there is more data this processes runs indefinitely and i run several of these at a time on a single serverit looks something likephp whileshouldstillrun do stuff logthatweexitedloopthe problem is after some time something causes the process to stop running and i have not been able to debug it and determine the causehere is what i am using to get information so farerror log logging all errors but no errors are shown in the error log register shutdown function registered a custom shutdown function this does get called so i know the process is not being killed by the server it is being allowed to finish or at least i assume that is the case with this being calleddebug backtrace logged a debug backtrace in my custom shutdown function this shows only one call and it is my custom shutdown functionlog if reaches the end of script outside of the loop i have a function that logs that the script exited the loop and therefore would be reaching the end of the source file normally when the script dies randomly it is not logging this so whatever kills it kills it while it is in the middle of processingwhat other debugging methods would you suggest for finding the culpritnote i should add that this is not an issue with max execution time which is thisabled for these scripts the time before being killed is inconsistent it could run for 10 seconds or 12 hours before it diesupdatesolution thank you all for your suggestions by logging the output i thiscovered that when a mysql query failed the script was set to die doh updated it to log the mysql errors and then terminate got it working now like a charm,['php'] +102394,generate sql for sqlite database from entity framework model is it possible to generate a sqlite database from the model with entity framework i created a sqlite connection and created a model but when i click generate database from model i get the following which looks like ms sql and makes errors if executed with sqlite just the beginning of the file entity designer ddl script for sql server 2005 2008 and azure date created 11252010 002641 generated from edmx file gfoobarmodel1edmx set quoted identifier offgouse foobarsqlitegoif schema idndbo is null executencreate schema dbogomy connection string looks like the following so i definitely chose the right database typemetadataresmodel1csdlresmodel1ssdlresmodel1mslprovidersystemdatasqliteprovider connection stringdata sourcegfoobarbazshould not it work this wayeditsince nobody seem to know an answer i will make it easier is it possible to generate sql code with ef for any database other than the microsoft sql server,['.net'] +102419,why does m2eclipse complain about missing artifact when mvn command line does not i have just set up a brand new installation of eclipse helios and have configured m2eclipse to use an external v 221 installation of maven the system compiles fine on the command line but from within m2eclipse several of my project modules have an errormissing artifact javaxjmsjmsjar11testi can get past the error by excluding the jms artifact from the atomikos dependencies but my main question is how can the two provide different resultseven more odd is that i have another installation of eclipse helios and everything works fine,['java'] +102431,warning in extern declaration i declared a variable i in temp2h extern i which contains just one above lineand made another filetemp3c includestdiohincludetemp2hint main extern ii6printfthe i is diwhen i compiled above as cc i temp3c i got following errors tmpccjcwzyyo in function maintemp3ctext0x6 undefined reference to itemp3ctext0x10 undefined reference to icollect2 ld returned 1 exit statusi had declared extern in temp3c above as k r page 33 says as i mentioned in above posti tried another way for temp3c with same header file temp2h includestdiohincludetemp2hint main i6printfthe i is diand compiled it cc i temp3c and got following errortmpcczzygslo in function maintemp3ctext0x6 undefined reference to itemp3ctext0x10 undefined reference to icollect2 ld returned 1 exit statusi also tried includestdiohincludetemp2hint main extern i6printfthe i is di compiled this one cc i temp3cgot same error as in post 1 temp3c in function amainatemp3c5 error aia has both aexterna and initializerso i have tried at least 3 different ways to use extern but non of them worked,['c'] +102436,memorystreamclose or memorystreamthispose which one do i callis it necessary to call bothwill the other throw an exception if i have already called one of them,"['c#', '.net']" +102437,get class in static method and inheritance php we have a codeclass parentclass public static function getname return get claself class childclass extends parentclass echo parentclassgetname parentclassecho childclassgetname parentclassif i use get classthis there is the same result also for selfthis staticthis etcany way to get child class name without adding methods to child class for this,['php'] +102457,defining a constant string containing non printable character in c i want to define a constant string containing non printable characters in c for eg let say i have a stringchar str1 0x01 0x05 0x0a 0x15now i want to define it like thischar str2 what should i write in place of do define an string equivalent to str1,['c'] +102460,how to convert hex string to hex number possible duplicatehow do i convert hex string into signed integer example3a convert to 0x3athanks a lot,['c#'] +102464,mysql in condition limit hey i have to use in condition in my mysql statement with a large set of idsexampleselect from users where id in 123410is there a limit if items the in statement can have,['mysql'] +102496,does private mean different things in c and c i was wondering why c does not allow private virtual functions and ran across the aptly named why are private virtual methods illegal in cin the accepted answer eric lippert who probably knows what he is talking about said if you desire to restrict the ability to override the method in nonnested derived classes then you can do so by restricting the ability of nonnested classes to derive from the base classin c private virtual makes sense because it means i want classes derived from me to override the functionality of this function but they should not be able to call it directly in other words private controls who can call a function and has no effect on who can override it i realize that since only derived classes can override in the first place and since c prohibits private virtual functions this question may be meaningless are there other scenarios in which the protection level of a function can effect who can override it protected internal perhaps,"['c#', 'c++']" +102497,pygame translucent sprites with per pixel alpha is it possible to thisplay pygame surfaces with controllable alpha i would like to take a surface with its own per pixel alpha and thisplay it with variable level of translucency without affecting the surface data and keep the transparency intact ie the objects on the surface would keep their shapes but their contents becoming more or less translucentin other words i want to combine perpixel alpha from the source image with persurface alpha calculated at the runtime,['python'] +102502,regex to conditionally replace twitter hashtags with hyperlinks i am writing a small php script to grab the latest half dozen twitter status updates from a user feed and format them for thisplay on a webpage as part of this i need a regex replace to rewrite hashtags as hyperlinks to searchtwittercom initially i tried to usephpstrtweet preg replacesw 1a href2a strtweettaken from in the course of testing i thiscovered that test is converted into a link on the twitter website however 123 is not after a bit of checking on the internet and playing around with various tags i came to the conclusion that a hashtag must contain alphabetic characters or an underscore in it somewhere to constitute a link tags with only numeric characters are ignored presumably to stop things like good presentation bob slide 3 was my favourite from being linked this makes the above code incorrect as it will happily convert 123 into a linki have not done much regex in a while so in my rustyness i came up with the following php solutionphptest this is a test tweet to see if 123 and 4 are not encoded but test l33t and 8oo8s are get all hashtags out into an arrayif preg match allsw test arrhashtags 0 foreach arrhashtags2 as strhashtag check each tag to see if there are letters or an underscore in there somewhere if preg matchdaz i strhashtag test str replacestrhashtag a hrefsubstrstrhashtag 1strhashtaga test echo testit works but it seems fairly longwinded for what it does my question is is there a single preg replace similar to the one i got from gistgithub that will conditionally rewrite hashtags into hyperlinks only if they do not contain just numbers,['php'] +102519,boostshared ptr and dynamic cast i have a problem using a shared ptr of a base class i cannot seem to be able to call the derived clas methods when dereferencing it i believe code will be more verbose than meclass base public boostenable shared from thisbase public typedef boostshared ptrbabelnet pointerclass derived public base public static pointer create return pointernew derived void anymethod basepointer foo derivedcreate i cannot call any method of derived with foo how can i manage to do this is dynamic cast a valid answer fooderivedmethod compilation fail,['c++'] +102533,resources for c programmer to learn js i am proficient in c i dont know java script and want to learn js what should be the wayprocess for me i know basic html css,"['javascript', 'c++']" +102550,css is it correct that text content of a div overflows into the padding i expected that the padding inside a div would remain clear of any text but given the following htmlcss the contenttext spills out into the paddingdiv classfoohelloworlddivfoo float left overflow hidden background red paddingright 10px width 50px border 1px solid greenthe text overflows it is 50px size and into the 10px padding is that by design if so it seems pretty dumb padding is not padding if it is got stuff in it or am i just doing something wrong regards css newbie,['css'] +102555,difference between list and linkedlist we use list whenever we need a list i notice now that there is a linkedlisti was wondering what was the difference between these 2 and when you should use one over the other,['c#'] +102559,encapsulating action and func i am trying to make a design for some sort of iexecutable interface i will not get into details but the point is that i have several actions that need to be executed from a base class they may take different parameters no big deal and they maymay not return a valueso far this is my designpublic abstract class actionbase snip public abstract class actionwithresultbaset actionbase public abstract t executepublic abstract class actionwithoutresultbase actionbase public abstract void executeso far each of my concrete actions need to be a child from either actionwithresultbase or actionwithoutresult base but i really do not like that if i could move the definition of execute to actionbase considering that the concrete class may or may not return a value i will have achieved my goalsomeone told me this could be done with using func and action for which i totally agree but i cannot find a way to have that into one single class so that the caller would know if the action is going to return a value or notbrief i want to do something like action1execute returns somethingvar a new action1var result aexecute action2execute returns nothingvar b new action2bexecute,['c#'] +102567,does use of final keyword in java improve the performance in java we see lots of places where the final keyword can be used but its use is uncommon for examplestring str abcsystemoutprintlnstrin the above case str can be final but this is commonly left off when a method is never going to be overridden we can use final keyword similarly in case of a class which is not going to be inheriteddoes the use of final keyword in any or all of these cases really improve performance if so then how please explain if the proper use of final really matters for performance what habits should a java programmer develop to make best use of the keyword,['java'] +102577,keep uitableview static when inserting rows at the top i have a tableview that i am inserting rows into at the topwhilst i am doing this i want the current view to stay completely still so the rows only appear if you scroll back upi have tried saving the current position of the underlying uiscrollview and resetting the position after the rows have been inserted but this results in a judder up and down although it does end up back in the same placeis there a good way of achieving this update i am using beginupdate then insertrowsatindexpath endupdates there is no reloaddata callscrolltorowatindexpath jumps to the top of the current cell saved before adding rowsthe other approach i tried which ends up in exactly the right pace but with a judder issave tableview currentoffset underlying scrollview methodadd rows beginupdatesinsertendupdates reloaddata to force a recalulation of the scrollview size recalculate the correct new offset from the bottom of the scrollviewsetcontentoffset underlying scrollview methodtrouble is the reloaddata causes the scrollviewtableview to start scrolling briefly then the setcontentoffset returns it to the correct placeis there a way of getting a tableview to work out it is new size without starting thisplay wrapping the whole thing in a beginanimation commitanimation does not help much eitherupdate 2 this can clearly be done see the offical twitter app for one when you pull down for updates,['iphone'] +102584,url for a file in public in my rails v238 app i have a static resource file which i have put at publicmyfilekml no need for any special routesrb setting rightit serves up just fine at httplocalhost30myfilekmlwhen i deploy to passenger it appears at httpmyservermyappnamemyfilekmlall is well so fari have a view an erb file which spews out javascript which needs to reference this file the output needs to be myfilekml on localhost and myappnamemyfilekml in production or maybe the full urls as above or maybe a relative url involving a bit of awkward with restful urlsshould i be able to do something like url for myfilekml or root urlmyfilekmli know there is an insanely easy answer to this question but honestly i have had no luck finding it quite a few people talking about root url but what is that a variable i can reference in a view it is undefined,['ruby-on-rails'] +102594,onpostexecute not being called in asynctask handler runtime exception i have an asynctask that fetches some data and then updates the ui with this new data it has been working fine for months but i recently added a feature that thisplays a notification when there is new data now when my app is launched through the notification sometimes i get this exception and onpostexecute is not calledthis is what happens when the app is launched1 expand the ui and find views2 cancel the alarm through alarmmanager that checks for new data and reset the alarm this is so that if the user thisables the alarm it is cancelled before the next time heshe reboots3 start the asynctask if the app was launched from the notification pass in a little bit of the data and then cancel the notificationi am stuck on what could be causing this exception it seems that the exception is from the asynctask code so i am not sure how i can fix itthankshere is the exceptionimy app 501 doinbackground exitingwmessagequeue 501 handler442ba140 sending message to a handler on a dead threadwmessagequeue 501 javalangruntimeexception handler442ba140 sending message to a handler on a dead threadwmessagequeue 501 at androidosmessagequeueenqueuemessagemessagequeuejava179wmessagequeue 501 at androidoshandlersendmessageattimehandlerjava457wmessagequeue 501 at androidoshandlersendmessagedelayedhandlerjava430wmessagequeue 501 at androidoshandlersendmessagehandlerjava367wmessagequeue 501 at androidosmessagesendtotargetmessagejava348wmessagequeue 501 at androidosasynctask3doneasynctaskjava214wmessagequeue 501 at javautilconcurrentfuturetasksyncinnersetfuturetaskjava252wmessagequeue 501 at javautilconcurrentfuturetasksetfuturetaskjava112wmessagequeue 501 at javautilconcurrentfuturetasksyncinnerrunfuturetaskjava310wmessagequeue 501 at javautilconcurrentfuturetaskrunfuturetaskjava137wmessagequeue 501 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava1068wmessagequeue 501 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava561wmessagequeue 501 at javalangthreadrunthreadjava1096edit here is my oncreate method in my main activity the one opened by the notification there are some onclicklisteners that i omitted to save space i do not think they should have any effect since the buttons they are attached to are not being pressedoverridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate call the parent setcontentviewrlayoutmain create the ui from the xml file find the ui elements controls slidingdrawer findviewbyidriddrawer contains the buttons comic imageview findviewbyidridcomic thisplays the comic subtitle textview findviewbyidridsubtitletxt textbox for the subtitle prevbtn button findviewbyidridprevbtn the previous button nextbtn button findviewbyidridnextbtn the next button randombtn button findviewbyidridrandombtn the random button fetchbtn button findviewbyidridcomicfetchbtn the go to specific id button mostrecentbtn button findviewbyidridmostrecentbtn the button to go to the most recent comic comicnumberedttxt edittext findviewbyidridcomicnumberedttxt the text box to zooming image view setup zoomcontrol new dynamiczoomcontrol zoomlistener new longpresszoomlistenerthis zoomlistenersetzoomcontrolzoomcontrol zoomcomic imagezoomview findviewbyidridzoomcomic zoomcomicsetzoomstatezoomcontrolgetzoomstate zoomcomicsetimagebitmapfactorydecoderesourcegetresources rdrawabledefaultlogo zoomcomicsetontouchlistenerzoomlistener zoomcontrolsetaspectquotientzoomcomicgetaspectquotient resetzoomstate enter the new id imm inputmethodmanager getsystemservicecontextinput method service used to hide the soft keyboard logilog tag beginning loading of first comic int notificationcomicnumber getintentgetintextracomic 1 logilog tag comic number from intent notificationcomicnumber if notificationcomicnumber 1 fetch new myfetcherthis zoomcomic subtitle controls comicnumberedttxt imm zoomcontrol fetchexecutemyfetcherlast thisplayed comic else fetch new myfetcherthis zoomcomic subtitle controls comicnumberedttxt imm zoomcontrol fetchexecutenotificationcomicnumber notificationmanager getsystemservicecontextnotification servicecancelall logilog tag ending loading of new comic logilog tag first run checks beginning get sharedpreferences prefs getsharedpreferencesprefs contextmode private check if this is the first run of the app for this version if prefsgetbooleanfirstrun major version number true prefseditputbooleanfirstrun major version number falsecommit firstrunversiondialog check if this is the first run of the app if prefsgetbooleanfirstrun true prefseditputbooleanfirstrun falsecommit firstrundialog logilog tag first run checks done onclicklistener s for the buttons omitted to save spaceedit 2 i have been digging through android source code tracking down where the exception is coming from this is lines 456 and 457 of sendmessageattime in handlermsgtarget thissent queueenqueuemessagemsg uptimemillisand this is enqueuemessage from messagequeue final boolean enqueuemessagemessage msg long when if msgwhen 0 throw new androidruntimeexceptionmsg this message is already in use if msgtarget null mquitallowed throw new runtimeexceptionmain thread not allowed to quit synchronized this if mquiting runtimeexception e new runtimeexception msgtarget sending message to a handler on a dead thread logwmessagequeue egetmessage e return false else if msgtarget null mquiting true msgwhen when logdmessagequeue enqueing msg message p mmessages if p null when 0 when pwhen msgnext p mmessages msg thisnotify else message prev null while p null pwhen when prev p p pnext msgnext prevnext prevnext msg thisnotify return true i am a little confused about what mquiting is but it looks like the previous time enqueuemessage was called msgtarget was null,['android'] +102626,facebook mutual friends and fql 4950 record limit i am trying to select all mutual friends connections with phpfql using my uid 540 friends which means 120 connections of which 6500 are unique so this code should return all the connections but facebook apparently has a 4950 row limit on fql queries select mutual unique friends unique connections facebookapi clientfql query select uid1 uid2 from friend where uid1 in select uid2 from friend where uid1uid and uid2 in select uid2 from friend where uid1uid i know the numbers above because the original code i wrote loops through my friend list and sends a getmutualfriend query for each of them foreach friends as key mutual friends facebookapi clientfriends getmutualfriendskey foreach mutual friends as f uid array pushall connections arraykeyf uid of course it takes almost 3 minutes to run that script while the fql query returns in 5 seconds after an hour of searching for this answer i have come to the conclusion the only way to get around this is to use a mixture of the two methods well that and post here any ideas on a better way to write this script and beat the 4950 row limitheres an fql multiquery that should do the same as above it is also limited to 4950queries user friendsselect uid2 from friend where uid1 uidmutual friendsselect uid1 uid2 from friend where uid1 in select uid2 from user friends and uid2 in select uid2 from user friendsmq test facebookapi clientfql multiquerytrimqueriesprint rmq test,['php'] +102631,in linux how can i tell if i am linking to a static or dynamic library i have a static and a dynamic library with the same name libclsocketa and libclsocketso when i specify what library i want to link to i simply enter lclsocket as the library my program complies and runs perfectly fine but what library am i using the static library or the dynamic library i want to give my friend my program and i am not sure if i need to include the libraries in the release c codelite pclinuxos 2010,['c++'] +102641,codeigniter when to use redirect and when to use thisloadview i am fairly new to codeigniter and i am wondering on some codeigniter best practices when should i use redirect versus usingthisloadviewit seems that when i use redirect then thissessionset flashdata works like it should but when i use thisloadviewthe message is thisplayed after an additional request,['php'] +102645,php header redirect with post variables i am working with php and i am making an action page which a form posts to the page checks for errors then if everything is fine it redirects them to the page where the data has been posted if not i need to to redirect them back to the page they were at with an error and the post variables here is the gist of how it worksthe html would look like thisform nameexample actionactionphp methodpost input typetext nameone input typetext nametwo input typetext namethree input typesubmit valuesubmitformactionphp would look like thisiferror check postone true headerlocation formphp here is where i need the data to post back to the form page else function to insert data into database headerlocation postedphpin the case of an error i need it to post back to the first pagei cannot use get because the input will be too largei do not want to use session if possibleis this possible,"['php', 'html']" +102646,whats the purpose of using before a functions argument i saw some function declarations like thisfunction boovar what does the character do,['php'] +102648,is there a pretty print stack dump let us face it debug backtrace output is not very pretty did anyone code a wrapperand whats your favourite pretty var dump which is usable in commercial projects so no gpl although lgpl is oksee also a more prettyinformative var dump alternative in php,['php'] +102663,how do i describe an enumeration column in a rails 3 migration how do i describe an enumeration column in a rails 3 migration,['ruby'] +102686,how do i cleanup a thread after its run method finishes what should be done with a thread after its run method finishes executing is there any cleanup needed for a thread in java,['java'] +102689,how to configure resharper 51s test runner to accept network shares i have a project that lies on a network share the test runner tries to run the tests but fails with an error messageunit test runner failed to load assemblyjetbrainsresahrpertaskrunnerframeworktaskexception could not load file or assembl filemysharevisual studio 2010projectsmyporjecttestmyprojectbinreleasetestmyprojectdll or one of its dependenciesthe tests run with mstest i have enabled the option loadfromremotesources in devenvexeconfig on visual studio 2010 pro and the testproject is deployablethe problem is the location from which the test runner tries to read the assembly filewhen i start the project from c it workswhat can i do,['c#'] +102692,how to declare static variables in objectivec can someone tell how we can declare a static variable as part of a objective c class i wanted this to track the number of instances i am creating with this class,['objective-c'] +102696,objectivec whats the difference between null nil and as the title says whats the difference between null nil and for example if i want to check a string in a dictionary is emptywhich condition should i use if dictionary objectforkeyastring nilorif dictionary objectforkeyastring isequaltostringorif dictionary objectforkeyastring nullwhich one is right,['objective-c'] +102705,uipickerview image with label in component i have uipickerview with two columns and in one column i want to thisplay image and label next to it it works thisplay and image and label just label is under image how to put image on the left and label on the right side i tried to changle label align to right but it doesnt work uiview pickerviewuipickerview pickerview viewforrownsintegerrow forcomponentnsintegercomponent reusingviewuiview view ifcomponent kstatecomponent uiimage img uiimage imagenamedrts1png uiimageview temp uiimageview alloc initwithimageimg tempframe cgrectmake0 0 29 29 uilabel channellabel uilabel alloc initwithframecgrectmake0 0 60 60 channellabeltext sdfsdfdsf channellabeltextalignment uitextalignmentleft channellabelbackgroundcolor uicolor clearcoloruiview tmpview uiview alloc initwithframecgrectmake0 0 110 60 tmpview insertsubviewtemp atindex0 tmpview insertsubviewchannellabel atindex1 return tmpview,"['iphone', 'objective-c']" +102710,datagridview keydown event not working in c datagridview keydown event is not working when i am editing text inside a cell i am assigning shortcut alts to save the data it works when cell is not in edit mode but if it is in edit mode below code is not workingprivate void datagridview1 keydownobject sender keyeventargs e if ekeydata keysalt keyss save data,"['c#', '.net']" +102715,java converting html with images in css to pdf i am looking for a free java library to convert html to pdf html page is formatted with css and those styles contains images gif at the moment i am using flying saucer but this library cant convert css with images properlythanks in advancemarek,"['java', 'html']" +102718,error httpservletrequest refers to the missing type string hii am implementing a project in struts in which i am getting an error in jsp pagei have already configured tomcat6 jre and jdk6 in eclipce idecode isrequestgetcontextpatherror isthe method getcontextpath from the type httpservletrequest refers to the missing type stringhow can i resolve this error,['java'] +102719,find gaps in a sequence of strings i have got a sequence of strings 01 02 03 upto 2 million they are not contiguous meaning there are gaps say after 03 the next string might be 06 i need to find out all these gaps in the above case 04 05this is what i have done so far gaps listtotal lencurr idsfor i in rangetotal tmp id s strizfill7 if tmp id in curr ids continue else gapsappendtmp idreturn gapsbut as you would have guessed this is slow since i am using list if i use a dict to prepopulate curr ids it will be faster but whats the complexity to populating a hashtable whats the fastest way to do this,['python'] +102723,windows azure or amazon ec2 for aspnet mvc development if you want to build enterprise aspnet mvc applications that use mssql databases is it better to use windows azure or amazon ec2i did not find any satisfying answersso what are the advantages and thisadvantages of the two cloud plattforms price performance simplicity of integration,"['.net', 'asp.net']" +102729,java version statistics where can i see statistics about the most used java versionsi want to develop applications that will run on most systems,['java'] +102751,aspnet mvc cookies not saving why does not this cookie save in the session start method of my globalasax new anon uservar authcookie new httpcookieuserid stringformat01 regiseraccountresponseusername regiseraccountresponsekey expires datetimemaxvalue domain domaincom secure true httponly truecreate the new users cookie there is no need to call registernewusersession as this is done in the same callhttpcontextcurrentresponsesetcookieauthcookie,['c#'] +102754,why should i learn a php framework i dont mean that petulantly but is there anything wrong with hand coding all of your php i see alot on this sitemany others that to go for php jobs etc that its essential to learn a framework like zend cakephp or similar,['php'] +102756,css firefox how to deactivate the dotted border firefox click indicator this click indicator is a thisgusting piece for my recent web projects i hate this how can i say to my firefox browser that he should not mark the clicked object,['css'] +102774,how to check if an image contains a face and it is reasonably visible i am not sure if this is solveable but i though i will ask anywayin my company we deal with massive enrollment camps where small teams of 5 to 10 people go to a village and enroll people the enrollment involves entering some data capturing fingerprints and taking a mugshot of the enduser using a webcam understandably enrollment is done by external vendors to whom we have outsourced the activitysince the no of records are overwhelmingly large trying to verify records manually is making the entire process slow so we have automated as many things as possible except for one thing which is to check if the photo captured using the webcam is of good qualityi know good quality is a vague term which cannot be translated to a software based solution however while trying to define good quality to myself i found this qualitynow finally coming to my question what parts of these image quality checks can be automatednote the photographs will be printed on a smartcard in stampsize they would barely be 100x125 pixels at 300 dpicheersraghu,['c#'] +102778,preferredidiomatic way to insert into a map i have identified four different ways of inserting into a stdmapstdmapint int functionfunction0 42functioninsertstdmapint intvalue type0 42functioninsertstdpairint int0 42functioninsertstdmake pair0 42which of those is the preferredidiomatic way and is there another way i have not thought of,['c++'] +102794,iis 75 web service and http 405 error i have a web service which i host on my machine i use windows 7 and iis 75 problem when the client tries to consume the web service heshe gets a http 405 errorin the log file of iis i can see that this is refused because post verb is not allowed question how can i allow post verb for those requestsdo i have to add mapping of the wsdl file and if i do how do i have to configure this mapping i have checked and in existing mappings i have nothing for wsdl extensionis there maybe another thing to setup on iis to allow those requestsweb service is built using wcf,['c#'] +102811,c objects when should i use pointer or reference i can use an object as pointer to it or its reference i understand that the difference is that pointers have to be deleted manually and references remain until they are out of scopewhen should i use each of them what is the practical differenceneither of these questions answered my doubtspointer vs reference c difference between reference objects and pointers,['c++'] +102822,html whats the correct form of br how is correct to write the br tag in htmlbr or bror anything else,['html'] +102823,does highchartsjs have a debug mode diagnosing syntax errors in highcharts is really difficult in part because it seems to suppress errors is there a debug mode where it does not do that,['javascript'] +102826,hibernate use of postgresql sequence does not affect sequence table i have configured hibernate to use postgresql sequence via annotations to generate values for primary key id column as followsid sequencegeneratornamepk sequencesequencenameentity id seqgeneratedvaluestrategygenerationtypesequencegeneratorpk sequencecolumnnameid uniquetrue nullablefalsepublic int getid return thisidwhat i see with this configuration is that hibernate is already assigning id values 30 on persisting whereas the query on used sequence shows the followingdatabase select last value from entity id seqlast value 691 rowquestionsis there anything wrong or notshould hibernate sync with the sequence tableif not where does it store the last generated idthank you,['java'] +102838,make msdeploy visual studio not delete app data folder but delete everything else i am using visual studios publish button to deploy my website and want a different app data folder on the server there is a checkbox for leave extra files on destination do not delete which prevents my app data folder from getting deleted but then it will eventually accumulate a lot of vestigial files as the website changesis there any way to make it exclude just app data when it deletes everything,['asp.net'] +102853,reinserting a record into an extjs store the codeextonready function extquicktipsinit extnamespacetimetracker timetrackerdatastore new extdatajsonstore root timecardentries url phpscriptstimecardentryscriptphp storeid timesheet autoload true autosave true writer new extdatajsonwriter encode true fields name id type integer name user id type integer name ticket id type integer name description type string name start time type date dateformat ymd his name stop time type date dateformat ymd his name client id type integer name is billable type integer timetrackertimeentrygrid new extgrideditorgridpanel renderto extgetbody store timetrackerdatastore autofit true height 500 title timesheet entries tbar xtype button text add record iconcls silkadd handler function var timecardentry timetrackertimeentrygridgetstorerecordtype var tce new timecardentry description new timesheet entry start time new dateformatmdy his is billable 0 timetrackertimeentrygridstopediting var newrow timetrackerdatastoregetcount timetrackerdatastoreinsertnewrow tce timetrackertimeentrygridstarteditingnewrow 0 view new extgridgridview autofill true colmodel new extgridcolumnmodel defaults sortable true editable true columns id ticket number header ticket dataindex ticket number editor new extformtextfieldallowblank true renderer functionvalue return value na value id description header description dataindex description editor new extformtextfieldallowblank false id start time header start dataindex start time renderer extutilformatdaterenderermdy hi a editor new extformdatefieldallowblank false id stop time header stop dataindex stop time renderer extutilformatdaterenderermdy hi a editor new extformdatefieldallowblank false id client header client dataindex client id renderer functionvalue return value na value id billable header billable dataindex is billable renderer functionvalue return value no yes id actions header null xtype actioncolumn items icon assetsimagessilk iconspage copypng iconcls action icon handler functiongrid rowindex columnindex the problem starts here gridstopediting var newrow timetrackerdatastoregetcount recordclone gridstoregetatrowindex recordclonedatastart time new dateformatymd his gridstoreinsertnewrow recordclone gridstarteditingnewrow 0 icon assetsimagessilk iconspage deletepng handler functiongrid rowindex columnindex alertcalled the goalwhen the user clicks the copy button that store record is stored into memory its start time is set to the current date and time and it is reinserted into the store as a new recordthe current resulti receive the following js error uncaught typeerror cannot read property data of undefinedmy questionsfor starters i am not even sure if i am grabbing the currently selected rows data record properly second i have no idea what the error message i am getting meansany help is as always highly appreciatedthanksupdate 1after some tweaking heres what i came up with this modified code for the copy button handler id actions header null xtype actioncolumn items icon assetsimagessilk iconspage copypng iconcls action icon handler functiongrid rowindex columnindex gridstopediting var newrow timetrackerdatastoregetcount var currentrecord gridstoregetatrowindex var timecardentry gridstorerecordtype tce new timecardentrycurrentrecorddata tcedatastart time new dateformatymd his gridstoreinsertnewrow tce icon assetsimagessilk iconspage deletepng handler functiongrid rowindex columnindex alertcalled heres what i am doingstop editing the gridget the number of records currently in the storegrab the currently selected record and store it in memorygrab the record type from the storemake a new instance of the store record type and pass in the data object from the selected record the data object is equivalent to the object literal if you were making a new record by hand see my original add button code for detailsalter the start time value of the new object that was created to todays date and timeinsert record into gridhappy timeplease critique this code and let me know if there is a better way to do it thanksupdate 2 handler functiongrid rowindex columnindex gridstopediting var recordclone gridstoregetatrowindexcopy extdatarecordidrecordclone ifrecordclone gridstoreaddrecordclone i updated the code to use the copy and add methods and it does work however when i call the add method i get a e is undefined error but when i refresh the page the record is inserted despite the error message ideas,['javascript'] +102857,thisable orientation change rotation animation i need to thisable the animation that plays when the orientation changes is this possible if not is it possible to speed it upjust to clarify i do not want to stop the orientation change just the animation i want an instant orientation change,"['iphone', 'objective-c', 'ios']" +102861,php detect page refresh i have a page actionphp on which i run an sql query through the code so that whenever the page is viewed the query runs like its like counting page viewsphpmysqli queryupdate the problem is when the page is refreshed the query is run page refresh is counted as a page view which i want to avoid question how to avoid it what i am looking for is a simple solution so that i can check if page was refresh some condition do,['php'] +102866,jpa persist object in a manytoone relationship i have a companyemployee onetomany relation in my database defined asentitypublic class employee id generatedvaluestrategygenerationtypeidentity private long id manytoone joincolumnnamecompanyid company company entitypublic class company id generatedvaluestrategygenerationtypeidentityprivate long idnow i am adding a newly created employee to a detached company the code i use is something like company company em1findcompanyclass 5lem1closeentitytransaction et em2gettransactionetbeginemployee employee new employemployeecompany companyem2persistemployetclosewill this work okis hibernate going to merge the company into the 2nd entitymanager or just use its id and persist the employee objectmight hibernate somehow duplicate my company object or throw an exception saying that a company with the same id already exists in the db,['java'] +102891,how to include a string variablechar within system command linux char s hello assume it is dynamically allocated correctly i want to use s in the below statement when s would be treated as a string with the value hello systemgrep s searchtexttxt resulttxt how do i do this,['c'] +102895,is update deletemarked as insert this is sql server question but i would appreciate the answers form other dbms contexts properly identified the answer by seth lynch to my question in msdn forum is a halfwritten values reading prevented with nolock hint tells when data is updated it is not over written the original row is marked as deleted and a new row is inserted is it correct statement can you give references supporting this in docshow can it be verified related thiscussions in sql is update always faster than deleteinsert update not long time ago i believed that dirty reads permitted in read uncommitted transaction isolation level or what is the same in sql server through withnolock hint permitted reading from other transactions uncommitted or committed if not yet changed values but not partlychanged partly updated partly deleted or partly inserted resume putting it short that phrase is generally and for most cases incorrect while it states categorically about rather uncommon cases in sql server,['sql'] +102897,sorting 50 0 0 numbers suppose that we need to sort 50 0 0 numbers suppose that the numbers is stored in a file what is the most efficient algorithm for solving this problem parallel algorithm for sortinghow to do it maybe useful link i cannot use standard algorithm therefore i ask you about methods and algorithms ok i read about parallel mergesort but it is not clear for me solution the first version code is located here,['java'] +102903,executable path to mac app in a py2appmac application bundle is there a way to spawn another instance of same app from within the app by passing different command line argumentsor given a mac app bundle how can i run it from command line and pass some arguments tooedit1forking is a limited option which may not work with 3rd party executables bundle with appi need to run this on mac and windowsedit2 question is how to run a a bundled python script using subprocess moduledetailsi am using py2app to generate a app bundle for my appilcation my application has two parts mainapp which is the uibackgroundapp a background process which does the real job both mainapp and backgroundapp have been implemented as python script and actually they are the same python script with different commandline eg python myapypython myapy backgroundproceso when i run python myapy it automatically starts background process based on program path but as i have now bundled my app as py2app i am not sure what executable i should be calling and passing backgroundprocess optionwhat i have tried open myappapp this opens the app but i cannot pass the arguments to it as they will be arguments for open command and will not be passed to my app myappappcontentsmacosmyapp backgroundprocess opens the app but not the backgroun process as it seems arguments are not being passed to appalso it throws error traceback most recent call last file usersagyeyprojectsmyapprelease426py2exethistmyappappcontentsresourcesrunpy line 4 in module from renderprocess import renderengineapp file renderprocessrenderengineapyc line 6 in module file wx init pyc line 45 in module file wx corepyc line 4 in module file wx core pyc line 18 in module file wx core pyc line 11 in loadimporterror dlopenusersagyeyprojectsmyapprelease426py2exethistmyappappcontentsresourceslibpython25libdynloadwx core so 2 library not loaded executable pathframeworkslibwx macud280dylib referenced from usersagyeyprojectsmyapprelease426py2exethistmyappappcontentsresourceslibpython25libdynloadwx core so reason incompatible library version core so requires version 700 or later but libwx macud280dylib provides version 260conclusion it looks like it may not be possiblelaunch an app on os x with command lineopen does not except arguments,['python'] +102908,how to choose my primary key i found this reading material on choosing a primary keyis there a guide blog post on how to choose the primary key for a given table should i use a autoincrementedgenerated key or should i base the primary key on the data being modeled assuming it has a truly unique fieldshould the primary key always be long for performances sake or can i take an external unique id as primary key even if it is a string,"['sql', 'mysql']" +102924,insert javascript at top of including file in jinja 2 in jinja2 i would like the following to work as it looks like it should by runningfrom jinja2 import environment filesystemloaderenv environmentloaderfilesystemloadertemplate envget templatexhtmlprint templaterenderessentially the objective is to coalesce all the javascript into the head tags by using a a call js some js endcall macroxhtmlhtmlhead script typetextjavascript block head js endblock script headbody include yhtml bodyhtml yhtml macro js extend head js block head js super try caller catch e mylogerrorename emessage endblock endmacro some div idabctextdiv call js jquery parlance function abccsscolor red endcall expected resultwhen i run xhtml through jinja2 i would expect the result to behtmlhead script typetextjavascript try abccsscolor red catch e usflogerrorename emessage script headbody some div idabctextdiv bodyhtmlactual resultthe actual results are not encouraging i get a couple types of potentially illuminating errors egtypeerror macro js takes no keyword argument calleror when i try adding another basis macro such as macro js2 block head js something endblock endmacro i get the following exceptionjinja2exceptionstemplateassertionerror block head js defined twicei feel as though i am running into a design issue regarding the precedence of the block tags over the macro tags ie macros do not seem to encapsulate block tags in the way i expecti suppose my questions are quite simplecan jinja2 do what i am attempting if so howif not is there another python based templating engine that does support this sort of pattern eg mako genshi etc which would work without issue in google app enginethank you for reading i appreciate your inputbrian edit i am trying to write an extension to resolve this problem i am halfway there using the following codefrom jinja2 import nodes environment filesystemloaderfrom jinja2ext import extensionclass javascriptbuilderextensionextension tags setjs js content def init self environment superjavascriptbuilderextension self init environment environmentextend javascript builder content def parseself parser parse tokens tag parserstreamnext return getattrself s strtagparser tag def js contentself parser tag return the output content list selfenvironmentjavascript builder content node nodesoutputlinenotaglineno nodenodes for o in content list print nappending node s stro nodenodesextendo0nodes print returning node s n node return node def jsself parser tag body parserparse statementsnameendjs drop needletrue print adding s strbody selfenvironmentjavascript builder contentappendbody return nodesconst slurped javascript env environment loader filesystemloader extensions javascriptbuilderextension this makes it simple to add javascript to the end of a template eghtmlheadheadbody js some javascript 3 5 endjs js more 2 endjs script typetextjavascript js content scriptbodyhtmlrunning envget templatexhtmlrender will result in some illuminating comments and the expected output ofhtmlhead script typetextjavascript script headbody slurped javascript slurped javascript script typetextjavascript some javascript 8 more 2scriptbodyhtmlof course this is not the same as having the script in the head as hoped but at least it is conveniently coalesced into one placehowever the solution is not complete because when you have a include yhtml in there where yhtml includes a js statement the js content gets called before the includes js statement ie xhtml is fully parsed before yhtml startsi also need to but have not yet inserted constant nodes that would have the static javascript trycatch which i indicated i wanted to have in there this is not an issuei am pleased to be making progress and i am grateful for inputi have opened the related question jinja2 compile extension after includeseditsolutionclass javascriptbuilderextensionextension tags setjs def init self environment superjavascriptbuilderextension self init environment environmentextendjbc def parseself parser parse tokens tag parserstreamnext body parserparse statementsnameendjs drop needletrue return nodescallblock selfcall method jbc none none body set linenotaglineno def jbcself callernone selfenvironmentjbc ntry s catch e caller return slurped after completed the environment will contain a variable jbc that has all the javascript i can insert this via for example stringtemplate,['python'] +102934,how do i confirm all elements in a hash are defined what is the best way to check if all the objects in the ruby hash are defined not nil the statement should return false if at least one element in the hash is nil,['ruby'] +102935,custom animation in android i have written a custom view now i want to do a little custom animation when the user touches itwhen i say custom i mean i basically want to render each frame myself and not use a predefined animation like described herewhat is the proper way of implementing this,['android'] +102937,how to know date is today i am trying this but is not working whyhtmlbody script typetextjavascript var todaynew date today is nov 28 2010 todaysethours0 todaysetminutes0 todaysetseconds0 documentwritetoday var today2 new datenovember 28 2010 documentwritetoday2 if today today2 documentwrite if today today2 today today2 documentwrite if today today2 documentwrite if today today2 documentwrite if today today2 documentwrite if today today2 documentwrite scriptbodyhtmland i always get thissun nov 28 2010 0 gmt0900 jst sun nov 28 2010 0 gmt0900 jst are not both dates to be the same hence i should get printed but is not happening thank you for your help in advance,['javascript'] +102942,how do i convert an integer to a float in javascript i have got an integer eg 12 and i want to convert it to a floating point number with a specified number of decimal placesdraftfunction inttofloatnum decimal code goes here inttofloat12 1 returns 120inttofloat12 2 returns 1200 and so ona,['javascript'] +102949,how to add custom parameters to an url query string with python i need to add custom parameters to an url query string using pythonexamplethis is the url that the browser is fetching getscrcgiq1ln0then some python commands are executed and as a result i need to set following url in the browserscrcgiq1ln0somestring1is there some standard approach,['python'] +103002,how to save 2 strings on an android app i am a relatively new programmer and i have not really worked with xml before other than writing layouts for android applicationsi want to be able to have a user save an int value figured it would be easier to save the int as a string however so that way it is usable whenever they use my app for example i have a start time and end time i want them to be able to save instead of inserting everytime they open the appi was thinking the easiest way to go about this would be to save the file to an xml file but after looking at android tutorials the only coding i could understand about xml files was how to load the resource files from the files but nothing on how to save or edit these stringsi do not have access to a database for this project so it needs to be able to be saved directly on the phonewhats the easiest way to save 2 strings for an android app,"['java', 'android']" +103008,trouble with template parameters used in macros i am trying to compile the following piece of code i get an error on the line which specializes stdvector it seems the one parameter being passedin is somehow being assumed to be two parameters is it perhaps something to do with anglebracketsis there a special waymechanism where by such parameters can be correctly passed to the macroinclude vectortemplatetypename astruct aclass define specialize aclassxtemplate struct aclassx x a specialize aclassint okspecialize aclastdvectorintstdallocatorint errorint main return 0the error that i get is as follows1 line 55 error macro specialize aclass passed 2 arguments but takes just 12 line 15 error expected constructor destructor or type conversion before int3 compilation terminated due to wfatalerrorslink,['c++'] +103017,deploying netfwtypelib to manage the windows firewall my windows service needs to createremove certain rules from the windows firewall for this i interface with netfwtypelib in windowssystem32hnetcfgdll via com it works great on my 64bit windows 7 machine but testing on another 64bit windows 7 machine throws the following errorservice cannot be started systemiofilenotfoundexceptioncould not load file or assembly interopnetfwtypelib version10 cultureneutral publickeytokennull or one of its dependencies the system cannot find the file specifiedi have a feeling that if i embed and install the assembly with my application i would have problems with different versions of windows and between 32bit and 64bithow do i solve this missing assembly deployment issueedit this seems to be a vs2010 issue for any target framework except 40 does anyone have a fix for this,['c#'] +103023,ignore parent padding i am trying to get my horizontal rule to ignore the parent paddingheres a simple example of what i haveparent padding10pxwidth100pxhr width100pxyou will find that the horizontal rule extends out of the parent by 10px i am trying to get it to ignore the padding that everything else in the parent div needsi am aware that i could make a separate div for everything else this is not the solution i am looking forthanks,"['html', 'css']" +103034,is it possible to read the value of a annotation in java this is my codecolumncolumnnamefirstnameprivate string firstname columncolumnnamelastname private string lastname public string getfirstname return firstname public void setfirstnamestring firstname thisfirstname firstname public string getlastname return lastname public void setlastnamestring lastname thislastname lastname is it possible to read the value of my annotation columncolumnnamexyz123 in another class,['java'] +103045,scrape facebook in python i am interested in getting the number of friends each of my friends on facebook has apparently the official facebook api does not allow getting the friends of friends so i need to get around this somehwhat sensible limitation somehow i tried the followingimport sysimport urllib urllib2 cookielibusername password mypasswordcj cookielibcookiejaropener urllib2build openerurllib2httpcookieprocessorcjlogin data urlliburlencodeemail username pass passwordrequest urllib2requestrequestadd headeruseragentmozilla50 x11 u linux x86 64 enus rv19212 gecko20101027 fedora36121fc14 firefox3612openeropenrequest login dataresp openeropenprint respreadbut i only end up with a captcha page any idea how fb is detecting that the request is not from a normal browser i could add an extra step and solve the captcha but that would add unnecessary complexity to the program so i would rather avoid it when i use a web browser with the same useragent string i do not get a captchaalternatively does anyone have any saner ideas on how to accomplish my goal ie get a list of friends of friends,['python'] +103062,android thisable bounce effect in custom gallery i have a custom gallery with fullscreen items and i have overridden the onfling method of gallery in this overridden function i check if the user had flinged to the left or right and act accordingly withonkeydownkeyeventkeycode dpad right event oronkeydownkeyeventkeycode dpad left eventthis works great but there is some sort of bounce animation when i scroll the new image comes in and moves just too far then moves back to the final position because the images i use are far too big the bounce animation looks horrible and therefor i want to thisable itany suggestionsthanks a loterik,['android'] +103105,entity framework problem associating entities with nullable field i am using entity framework and i am trying to associate an entity that was created from a database table with an entity that was created from a database view because entity framework is not able to infer the relationships between a database table and a view automatically i am using the entity designer to construct an association between the entities however if the foreign key is a nullalbe type i get the following errorerror 113 multiplicity is not valid in role company in relationship usersview because all the properties in the dependent role are nullable multiplicity of the principal role must be 01in my scenario i have a companyid foreign key in my usersview that is nullable ie users may not have a company creating an association with a nullable foreign key was never a problem with linq 2 sql does anyone know how i can get around this problem in entity frameworkthanks in advance,"['c#', '.net']" +103115,listview ignoring wrap content i have a problem with the listview in androidwhen i set androidlayout heightwrap content listview stays just one or two rows long and i cannot find a way to make him wrappedframelayout xmlnsandroid androidorientationvertical androidlayout widthfill parent androidlayout heightfill parent scrollview androidlayout widthfill parent androidlayout heightfill parent linearlayout androidlayout widthfill parent androidlayout heightfill parent androidorientationvertical androidgravitycenter textview androidididquestion androidlayout widthfill parent androidlayout heightwrap content listview androidididlistview01 androidlayout widthfill parent androidlayout heightwrap content linearlayout scrollviewframelayoutis there any way to accomplish this thanks in advance,['android'] +103116,rails 3 rake task cannot find model in production my simple rake task stored in libtasksitems spiderrake runs just fine in development all it does is call spider on the item modelnamespace items do desc spider the web for data hoorah task spider environment do itemspider endendi have the environment task as a dependency so everything works just fine however when i add rails envproduction i hit errors both on my local server and the production server rake itemsspider rails envproduction tracein homematchuwebsitesmyrailsapp invoke itemsspider first time invoke environment first time execute environment execute itemsspiderrake aborteduninitialized constant objectitemhomematchurvmgemsruby192preview3rails3gemsrake087librakerb2503in const missinghomematchurvmgemsruby192preview3rails3gemsrspeccore200beta22librspeccorebackward compatibilityrb20in const missinghomematchurvmgemsruby192preview3rails3gemsrspecexpectations200beta22librspecexpectationsbackward compatibilityrb6in const missinghomematchuwebsitesopenneoimpressitemslibtasksitems spiderrake4in block 2 levels in top requiredhomematchurvmgemsruby192preview3rails3gemsrake087librakerb636in calltrace of how rake gets to my taskthis just seems odd to me apparently the models have not been loaded correctly i am on rails 303 though development on this app started back when rails 3 was in beta how can i go about debugging this issue thanks,['ruby-on-rails'] +103121,mysql difference between two timestamps in seconds is it possible to calculate difference between two timestamps in mysql and get output result in seconds like 20101129 131655 20101129 131355 should give 180 secondsthank you,"['sql', 'mysql']" +103122,html5 empty elements by empty i mean the followinglink relstylesheet hrefresetcss typetextcss been using xhtml transitional for several years now and to validate properly the trailing is required for elements that do not contain other elements is this required for a valid html5 document,['html'] +103124,php removing excess whitespace i am trying to remove excess whitespace from a string like thishello worldtohello worldanyone has any idea how to do that in php,['php'] +103129,are not fields in classes similar to global variables i started learning a functional programming languagesml and programmed in this language a little bit and then i went started checking java and i had this feeling that class fields seem like global variables and they complicate programming for example i must read methods to see which one readwrite them etcfrom what i have heard using global variables in programming languages like c is a bad idea but what about java class fields are not they something like global variables for all your class methods is it a bad idea to use fields or maybe i have understand something wrong or i program in the wrong way java,['java'] +103144,how do i check if the request is made via ajax in codeigniter how do i check if the request is an ajax i am using codeigniter i have a link that when it clicked it will open the popup dialog window this is done through ajax it requests to a controller name login windowcodeigniterhere is the controller namefunction login window request via ajax thisloadviewlogin windowjqueryhere is the jquery codei am using a jquery plugin faceboxareldialogfaceboxa hrefhttplocalhostcodeigniterlogin window reldialogloginai want to check if it is an ajax request and if not i will redirect them to homepage so there is no way they can access the page that is intended only for ajax requests,['php'] +103157,how to show messagebox on aspnet if i need to show a messagebox on my aspnet webform how to do iti try messageboxshowddbut it is not working,"['c#', 'asp.net']" +103168,export data to csv in rails i need export data as csv in rails appl i found this plugin do you know about some better solution,['ruby-on-rails'] +103172,loading user controls dynamically how to load a user control dynamically in a pagei have a page that contains radiobuttons each click on a radio button loads a user control ascx in the pagewhat i am doing is loading all controls at the same time but set their visibility to false when a user clicks a radiobutton i set the visibility of the specific user control to trueas a result i am loading all the user controls on each postbackis there any other possible way of doing this,"['c#', 'asp.net']" +103186,how to perform division in timespan i have a value in timespan let us say tsp1 2 hour 5 minutes i have another timespan variable which contains a value like tsp2 0 hours 2 minutesplease tell me how i can divide tsp1 by tsp2 so that i can get the exact number of times tsp2 divides into tsp1 and what the remainder isi am using visual studio 2008thanks,['c#'] +103195,doxygen syntax in python can somebody please help me to figure out how to comment python code correctly to get parsed by doxygen somehow it ignores the tags the output html shows the tagsbrief creates a new hello objectthis hello object is beeing used to param name the name of the userboth variants i tried do not workclass hello brief short description longer description def init self name brief creates a new hello object this hello object is beeing used to param name the name of the user selfname nameclass hello brief short description longer description def init self name brief creates a new hello object this hello object is beeing used to param name the name of the user selfname name,['python'] +103204,how can i make links in fromhtml clickable android this seems like a trivial problem but is has me kind of stumped i want to load an html string using htmlfromhtml and have any links in the string to be clickable and open in the browserbasic exampletextviewsettexthtmlfromhtmla hrefthis is a linkawith this snippet the text is formatted as if it were a link blue underlined but it is not clickable i tried linkify but it only seems to work with links that are not htmlbasedany suggestions,"['html', 'android']" +103212,customizing uilocalnotifications alert i have to change the alertview of a uilocalnotification how can i achieve this,['ios'] +103218,how to store and retrieve array list value in bundle in android can any body tell how to store and retrieve array list value in bundle in android give example thanks,['android'] +103251,when calling windows api functions from c which source for signatures to trust net framework source code or pinvoke for example this is from net framework source file unsafenativemethodscsdllimportexterndlluser32 exactspellingtrue charsetcharsetauto public static extern bool getwindowrecthandleref hwnd in out ref nativemethodsrect rectand this is from pinvokenetdllimportuser32dllreturn marshalasunmanagedtypeboolpublic static extern bool getwindowrecthandleref hwnd out rect lprectwhich is the correctbest signature for this function only one of them has return marshalasunmanagedtypebool or in out ref etci have noticed that in net framework source files manymost signatures have exactspellingtrue charsetcharsetauto but on pinvoke they do not is this required,['c#'] +103271,how does python keep track of modules installed with eggs if i have a module foo in libsitepackages i can just import foo and it will work however when i install stuff from eggs i get something like blah401py27win32egg as a folder with the module contents inside yet i still only need do import foo not anything more complicated how does python keep track of eggs it is not just dirname matching as if i drop that folder into a python installation without going through thistutils it does not find the moduleto be clearer i just installed zope the folder name is zopeinterface330py27win32egg this workspython 271 r27186832 nov 27 2010 183046 msc v1500 32 bit intel on win32type help copyright credits or license for more information import zopeinterfacei create a blah401py27win32egg folder with an empty module haha in it and init py this does not workpython 271 r27186832 nov 27 2010 183046 msc v1500 32 bit intel on win32type help copyright credits or license for more information import blahhahatraceback most recent call last file stdin line 1 in moduleimporterror no module named blahhahathis does thoughpython 271 r27186832 nov 27 2010 183046 msc v1500 32 bit intel on win32type help copyright credits or license for more information from pkg resources import require requireblah10blah 401 cpython27libsitepackagesblah401py27win32egg import hahaso how do i make it work without a require,['python'] +103273,is there any way to thisable some dom element from capturing mouse events i have an element which is on top of an initial element this element is not a child of the initial element i am capturing mouseover event of the initial element and when the mouse cursor is over the top element i am loosing itis there any way to thisable the top element from getting mouse eventsi have a solution where the mouseover of the top element triggers mouseovere of the initial element but this solution might not work in my situationthank youas for an example i have slightly modified an example for the jquery doc here region is the initial element and region2 is the obstructive element region3 is a child of the region so it does not prevent its mouseoverdoctype htmlhtmlhead style region width220px height170px margin10px marginright50px backgroundyellow border2px groove floatright region2 backgroundcolor white floatright position relative right 150px top 50px width 100px height 100px border 1px solid region3 width30px height 30px backgroundcolor brown p margin0 marginleft10px colorred width220px height120px paddingtop70px floatleft fontsize14px span thisplayblock style script srcscriptheadbody p try scrolling too spanmove the mouse over the divspan spannbspspan p div idregiondiv idregion3divdiv div idregion2divscript regionmousemovefunctione var pagecoords epagex epagey var clientcoords eclientx eclienty spanfirsttext epagex epagey pagecoords spanlasttext eclientx eclienty clientcoords scriptbodyhtml,['jquery'] +103281,android receiving long sms multipart i have an application which has to listen for specific sms so far easy but when i receive the message it is multipart is there a proper way to receive the sms as one messagenow my activity starts two times for each part of the sms should i concatenate the sms by hand,['android'] +103299,mysql is it possible to make this query any faster i have a table test containing millions of entries each row contains a floating point feature and a count how often this feature is present in item id the primary key for this table is the combination of id and feature ie every item may have multiple features there are usually a couple of hundred to a couple of thousand feature entries per item idcreate table test id int not null feature double not null count int not nullthe task is to find the 500 most similar items to a given reference item similarity is measured in number of identical feature values in both items the query i have come up with is quoted below but despite properly using indices its execution plan still contains using temporary and using filesort giving unacceptable performance for my use caseselect t1id t2id sum least t1count t2count as priority from test as t1inner join test as t2 on t2feature t1featurewhere t1id some user supplied id value group by t1id t2id order by priority desclimit 500any ideas on how to improve on this the schema can be modified and indices added as needed,"['sql', 'mysql']" +103305,using server variables in a href with runatserver when i use an anchor tag on an aspx page as belowa hrefpagespageaspxid servervariablename test ait will get the variable value correctly assigned to id but it would not route the page correctly as the will not be evaluated without the runatserver attribute on the a tag but once i add the runat server attribute it does not evaluate the servervariable name anymore does anyone know how this works or what i should do to take care of both,"['c#', 'asp.net']" +103307,confused by relation between dom and html apis could someone try to explain to me how are dom and html related is one subset of another is one a more abstract concept than the another is html an extension of dom or do they describe rather unrelated concepts related only in that you can transform from html into dom how would you draw these 2 in one picture if you had tofor example what is the purpose of these difference specs both first and last links contain information about htmlelementi found a possible answer to this question here which is the goals of the htmlspecific dom api areto specialize and add functionality that relates specifically to html documents and elementsto provide convenience mechanisms where appropriate for common and frequent operations on html documentsdoes this mean that the 3rd link in the list above extends the dom core which is described in the 1st linkor if you implement dom core that allows you to manipulate simple documents but if you implement html that gives you like a superdom that allows you to manipulate more complicated objects finally say you want to implement your own browser that is able to open only html5 websites render as well as support javascript is it enough to read the specification found in the 3rd link or do you first need to implement everything provided in dom and then implement html5 specific thingsas you can see i am quite confused so it is hard to formulate proper questions updatei guess i am wondering about dom api vs html api vs dom html api vs html dom api,['html'] +103328,how to get automatic table creation working in spring hibernate jpa i cannot get automatic table creation working in spring when using hibernate jpahere are my config filesxml version10 encodingutf8persistence xmlns xmlnsxsi xsischemalocation 1 0xsd version10 persistenceunit namenaverotest providerorghibernateejbhibernatepersistenceprovider classxclass properties property namehibernatearchiveautodetection valueclass hbm property namehibernateshow sql valuetrue property namehibernateconnectiondriver class valueorghsqldbjdbcdriver property namehibernateconnectionurl valuejdbchsqldbfiletmpnaverotestdb property namehibernateconnectionusername valuesa property namehibernateconnectionpassword value property namehibernatehbm2ddlauto valuecreate property namehibernatedialect valueorghibernatedialecthsqldialect properties persistenceunitpersistencecontextxml xml version10 encodingutf8 beans xmlnstx xmlns xmlnsxsi xsischemalocation for auto creation of tables bean iddatasource classorgspringframeworkjdbcdatasourcedrivermanagerdatasource property namedriverclassname valueorghsqldbjdbcdriver property nameurl valuejdbchsqldbfiletmpnaverotestdb property nameusername valuesa property namepassword value bean bean identitymanagerfactory classorgspringframeworkormjpalocalcontainerentitymanagerfactorybean property namedatasource refdatasource property nameloadtimeweaver bean classorgspringframeworkinstrumentclassloadinginstrumentationloadtimeweaver property property namejpavendoradapter bean idjpaadapter classorgspringframeworkormjpavendorhibernatejpavendoradapter property namegenerateddl valuetrue property namedatabaseplatform valueorghibernatedialecthsqldialect property nameshowsql valuetrue bean property bean bean idpicturebean classdenaveroserverblpicturebean property nameentitymanagerfactoryref localentitymanagerfactory property bean beansany ideas what may be wrongthanks for any help,['java'] +103339,gembundler load error cannot activatealready activated i ran bundle update to update my gems now i get this when i try to start up the local development server anyone know how to fix hostnamemyapp username rails susersusernamervmrubiesruby192p0libruby191rubygemsrb238in activate cannot activate i18n 041 runtime for mail2210 actionmailer303 rails303 already activated i18n050 for activemodel303 actionpack303 rails303 gemloaderror from usersusernamervmrubiesruby192p0libruby191rubygemsrb254in block in activate from usersusernamervmrubiesruby192p0libruby191rubygemsrb253in each from usersusernamervmrubiesruby192p0libruby191rubygemsrb253in activate from usersusernamervmrubiesruby192p0libruby191rubygemsrb254in block in activate from usersusernamervmrubiesruby192p0libruby191rubygemsrb253in each from usersusernamervmrubiesruby192p0libruby191rubygemsrb253in activate from usersusernamervmrubiesruby192p0libruby191rubygemsrb254in block in activate from usersusernamervmrubiesruby192p0libruby191rubygemsrb253in each from usersusernamervmrubiesruby192p0libruby191rubygemsrb253in activate from usersusernamervmrubiesruby192p0libruby191rubygemsrb1065in gem from usersusernamervmgemsruby192p0rails3binrails18in main,['ruby-on-rails'] +103351,how can i estimate the thisk size of a string with javascript i need to try to estimate the thisk size of a text string which could be raw text or a base64 encoded string for an imageaudioetc in javascript i am not sure how to estimate this the only thing when googling i can find is length so i thought maybe someone on stackoverflow might knowthe reason i need to know is i have a localstorage script that needs or would love to have the ability to check when a user is nearing his 5mb or 10mb in ie quota and prompt them to increase the max size for the domain so if a user hits lets say 45mbs of data it would prompt with youre nearing your browsers 5mb data cap please increase your max data by instructions on increasing it for the browser,['javascript'] +103352,function arithmetic library for python i am searching for a library that will let me manipulate functions with the standard operators etclets suppose you have a function fx x 2 and gx x 2 i would like to be able to write f g and get a new functor that is essentialy x 2 x 2 or fg and get x 2 2i know this is not too hard to implement youll just have to make a functor class and overload it is call function but i am hoping there is a 3rd party library for iti am not trying to use this for anything heavyweight just for learning thanks for the help,['python'] +103358,difference between timezones americalos angeles and uspacific and pst8pdt i need to convert a bunch of dates in a mysql database from pacific time americalos angeles to utc i found a great so answer on how to do thisduring my tests and preparation i am finding that i am getting the same time conversions when using any of the following time zone namesamericalos angelesuspacificpst8pdtso my questions are the followingare these all just aliases to the same thing or are there actual differences between them at some point in timeif i want to provide a list of timezones to users on a website would it be better to give them selections from the america group of names or the us group of names,['mysql'] +103361,error saving in the keychain with iphone sdk i use the apple wraper for the keychain and try to save a item on it running in simulator ios 41i have not experience with the keychain beforei get this errorcould not add the keychain item error 25299in keychainitemwrapperm line 304 no previous item found add the new oneresult secitemaddcfdictionaryrefself dictionarytosecitemformatkeychainitemdata nullnsassert result noerr could not add the keychain item this is how i do the save void savekeynsstring key valuensstring value keychainitemwrapper keyitem keychainitemwrapper alloc initwithidentifierkey accessgroupnil keyitem setobjectvalue forkeyidksecvaluedata keyitem releaseand this are the values that the api try to savecfbasichash 0x7231f60 0x320d380type mutable dict count 5entries 2 cfstring 0x2e6eb98 0x320d380contents labl cfstring 0x2fb018 0x320d380contents 3 cfstring 0x2e6efb8 0x320d380contents v data cfstring 0x727de60 0x320d380contents dit84 cfstring 0x2e6ebc8 0x320d380contents acct cfstring 0x2fb018 0x320d380contents 5 cfstring 0x2e6eb58 0x320d380contents desc cfstring 0x2fb018 0x320d380contents 6 cfstring 0x2e6ebe8 0x320d380contents gena cfstring 0x2ffd08 0x320d380contents usercode,['iphone'] +103368,c unit tests mocking objects i am currently looking at some unit test librarys in c and have some questionsthere seem to be no mocking facility in boosttest but i can hardly think of doing unit tests without creating mock objectsfunctions how would you do that in boosttest are you doing it manually how i mean there are several ways i can think of none of these seem nice or are you simply doing without mock objectsgoogletest and googlemock looks like nice libraries with mockingsupport however it requires every object that shall be mocked to be virtual i do not really like this it is not that i am worrying about the performance i could define a macro to get it out of production code anyway but i find this very intrusive i wonder if there is another solution which does not require that much change to the existing code love clojure there,['c++'] +103369,guice with parents what do i do with guice when i need to call a parent constructor that is also injectable eg i have an abstract parent class that has a constructor that is injected with an object shared by all derived children and each child also has an injectable constructorcalling super wont work because java wants me to pass in the object as a paremeter rather than have guice injectthanksedit i am wondering if maybe i need to use method injection instead,['java'] +103371,ios 42 looking for a way to manipulate the iphone 4 cameras focus thistance i am working in an ar project and we want to manipulate the focusing thistance of the iphone4 camera is this even possible so far weve found just toggling and auto focusing as options listed here classreferencereferencehtml23apple refoccinstmavcapturedeviceisadjustingfocusthanks in advance for any tips,['iphone'] +103382,how can i make certain parts of my html not selectable how can i make certain parts of my html not selectablei have some absolutely positioned divs that keep getting selected if a user tries to select the content of my pageis there a way to make it so certain elements such as those divs are not selectableedit the main issue is when someone copies these absolute divs and then pastes them into the rich text editor on my site the rich text editor breaks on ie,"['javascript', 'html', 'css']" +103384,how to align input forms in html i am new to html and i am trying to learn how to use formsthe biggest issue i am having so far is aligning the forms here is an example of my current html fileform first nameinput typetext namefirstbr last nameinput typetext namelastbr emailinput typetext nameemailbr formthe problem with this is the field box after email is drastically different in terms of spacing compared to first and last name what is the proper way to make it so that they lineup essentiallyi am trying to practice good form and syntaxa lot of people might do this with css i am not sure i have only learned the very basics of html so far,['html'] +103389,problem with nsrange i am having a problem with nsrange here is my codensrange range nshttpcookie requestheaderfieldswithcookiesnshttpcookiestorage sharedhttpcookiestorage cookiesforurlnsurl urlwithstringcookie objectforkeycookie rangeofstringxnslogf rangelengthif rangelength 1 nslogdo something else nslogauthingconsole output 0do somethingand then the second time i run through the code0authingwhat the hell is going on nsnotfound i think it was does not work and i am not the only person finding this problem so using it is not a solutionthanks for any helpcheersedit i tried using nslogd rangelength but it gives incorrect output the first time it runs through the second time it runs through it is correct i have tried using nsnotfound thinking that the strange output is due to it being nsnotfound but it did not trigger,['iphone'] +103396,usage of nsexception in iphone apps one of my friends asked me not to use nsexception in iphone apps the reason he gave was performance bottleneck but i am not convinced of itcan someone confirm me that we should restrain from using nsexception in iphone app if you have best practices for using nsexception please provide that tooupdatethis link requests us to use exception handling at the app level have someone ever done it please give the advantages of it and any other performance hitches it could create,"['iphone', 'ios']" +103410,division to percentage in ruby on rails if prescribed wod count userworkoutsrx workoutscount returns 4 and user workout count userworkoutscount returns 26how come number to percentageprescribed wod count user workout count returns 0 and not 15,"['ruby-on-rails', 'ruby']" +103423,how to set progressbar at the center screen in frame layout i am using following code but my progress bar is not thisplaying in the center of frame layout i want to avoid padding to my progressbarcan any one please explain it is perfectly working if i am using linear layoutxml version10 encodingutf8framelayout xmlnsandroid androidorientationvertical androidlayout widthwrap content androidlayout heightwrap content androidgravitycenter verticalcenter horizontal progressbar androidididprogress bar androidlayout widthwrap content androidlayout heightwrap content imageview androidididgallery img androidlayout widthwrap content androidlayout heightwrap content framelayout,['android'] +103433,list of all american holidays as nsdates i am seeking a way to get all american holidays as an array of nsdates is there a way to implement that,['ios'] +103434,single sign on in aspnet cookie name machinekey and what more i have two aspnet apps hosted on one server their configs have the same machinekey values and the authentication sections look as followsauthentication modeforms forms loginurl logindefaultaspx namemysingleauth authenticationauthentication modeforms forms loginurlmysinglelogon0 timeout2880 namemysingleauth authenticationthe single sign on authentication in both applications using one cookie still does not work what am i missingedit the two apps are on our intranet one under httpsip84 and the other under httpsip86 where ip is an ip,['asp.net'] +103455,getting devices local timezone 20100614 0221490400 or 20100614 0221490400is there a way to convert this string to the date according to the local machine time zone with format 20100614 0221 am,"['java', 'android']" +103460,phpunit fatal error i have just started creating unit tests for my code again i have had phpunit working in the past but today it is not playing ball before i created any new tests i decided to run some old ones to see if they were still valid but i get a fatal error from phpunit itself i run phpunit from the cli in ubuntu phpunit testcasefilephp deprecated comments starting with are deprecated in etcphp5cliconfdimapini on line 1 in unknown on line 0php warning xdebug must be loaded as a zend extension in unknown on line 0warning directive register long arrays is deprecated in php 53 and greater in unknown on line 0warning directive magic quotes gpc is deprecated in php 53 and greater in unknown on line 0fatal error class phpunit framework mockobject matcher invokedrecorder not found in usrsharephpphpunitframeworkmockobjectmatcherinvokedatleastoncephp on line 60call stack 02 651688 1 main usrbinphpunit0 031 1173168 2 requireusrsharephpphpunittextuicommandphp usrbinphpunit48 046 1485456 3 require onceusrsharephpphpunittextuitestrunnerphp usrsharephpphpunittextuicommandphp47 047 1503344 4 require onceusrsharephpphpunitframeworkphp usrsharephpphpunittextuitestrunnerphp47 00168 3848688 5 requireusrsharephpphpunitframeworktestcasephp usrsharephpphpunitframeworkphp68 00178 4091880 6 require onceusrsharephpphpunitframeworkmockobjectmatcherinvokedatleastoncephp usrsharephpphpunitframeworktestcasephp49i checked to make sure that the files exist that the file paths etc are correct but i do not really know how to go about fixing it can anyone help,['php'] +103487,how to convert an html webpage to a picture how to convert an html webpage to a picture like google previewis there a java library permitting thisis there a commandline argument to call browsers to make them convert a web page into a picture png for instance,['java'] +103492,why was function overloading added to c i have a c background i was just wondering why was function overloading added to c c does not have function overloading but c does what was the need for it what went across the mind of the language designer at that time,"['c++', 'c']" +103493,tesseract or any other ocr lib i am looking for an explanation api doc examples of how to use and train tesseract in c nothing useful on the google tesseract page and yet to find something over the webanyone useful sources experiences would be more than welcome as i have no idea how to begin with itps i am open for suggestions on otherlibrariesonly free libraries,['c++'] +103506,that assembly does not allow partially trusted callers initializecomponent scenario i am in the process of refactoring one of our applications to use nhibernate and came across this issue a couple weeks back the issue was originally with nhibernate and castle and to solve this they were both recompiled with the assembly allowpartiallytrustedcallers however after making some changes to the ui and codebase this error has reappeared again also worth noting is that i control the loading my user controls programmatically from form mainproblem whenever the user controls are generated i receive the error below if i comment out the loading then the program will run when i debug it ends at the initializecomponent function which is autogenerated note that i cannot step into that function systemsecuritysecurityexception was unhandled messagethat assembly does not allow partially trusted callers sourcea grantedset permissionstate refusedset urlfilecdocuments and settingsiddesktopanhib2bindebugaexe stacktrace at ausercontrolcyberinitializecomponent at ausercontrolcyberctor in cdocuments and settingsiddesktopanhib2usercontrol cybercsline 34 at aformmainformmainloadobject sender eventargs e in cdocuments and settingsiddesktopanhib2form maincsline 30 at systemwindowsformsformonloadeventargs e at systemwindowsformsformoncreatecontrol at systemwindowsformscontrolcreatecontrolboolean fignorevisible at systemwindowsformscontrolcreatecontrol at systemwindowsformscontrolwmshowwindowmessage m at systemwindowsformscontrolwndprocmessage m at systemwindowsformsscrollablecontrolwndprocmessage m at systemwindowsformscontainercontrolwndprocmessage m at systemwindowsformsformwmshowwindowmessage m at systemwindowsformsformwndprocmessage m at systemwindowsformscontrolcontrolnativewindowonmessagemessage m at systemwindowsformscontrolcontrolnativewindowwndprocmessage m at systemwindowsformsnativewindowdebuggablecallbackintptr hwnd int32 msg intptr wparam intptr lparam at systemwindowsformssafenativemethodsshowwindowhandleref hwnd int32 ncmdshow at systemwindowsformscontrolsetvisiblecoreboolean value at systemwindowsformsformsetvisiblecoreboolean value at systemwindowsformscontrolset visibleboolean value at systemwindowsformsapplicationthreadcontextrunmessageloopinnerint32 reason applicationcontext context at systemwindowsformsapplicationthreadcontextrunmessageloopint32 reason applicationcontext context at systemwindowsformsapplicationrunform mainform at aprogrammain in cdocuments and settingsiddesktopanhib2programcsline 32 at systemappdomain nexecuteassemblyassembly assembly string args at systemappdomainnexecuteassemblyassembly assembly string args at systemruntimehostingmanifestrunnerrunboolean checkaptmodel at systemruntimehostingmanifestrunnerexecuteasassembly at systemruntimehostingapplicationactivatorcreateinstanceactivationcontext activationcontext string activationcustomdata at systemruntimehostingapplicationactivatorcreateinstanceactivationcontext activationcontext at systemactivatorcreateinstanceactivationcontext activationcontext at microsoftvisualstudiohostingprocesshostprocrunusersassemblydebuginzone at systemthreadingthreadhelperthreadstart contextobject state at systemthreadingexecutioncontextruntrycodeobject userdata at systemruntimecompilerservicesruntimehelpersexecutecodewithguaranteedcleanuptrycode code cleanupcode backoutcode object userdata at systemthreadingexecutioncontextruninternalexecutioncontext executioncontext contextcallback callback object state at systemthreadingexecutioncontextrunexecutioncontext executioncontext contextcallback callback object state at systemthreadingthreadhelperthreadstart innerexception anyone have any ideas on the subject i have already added assembly allowpartiallytrustedcallers to the assembly is there any way to find out which reference is causing this error or any way to step through initializecomponentnote i have every permission included and the project is set to partial trustanyways any help is greatly appreciated,['c#'] +103512,managementobject class not showing up in systemmanagement namespace i am trying to write some wmi in my windows form and the managementobject is givin me the the type or namespace name managementobject could not be found errorhere is my uncomplete codeusing systemusing systemcollectionsgenericusing systemlinqusing systemtextusing systemiousing systemthreadingusing systemsecuritypolicyusing systemmanagementusing systemmanagementinstrumentationnamespace consoleapplication2 class program static void mainstring args managementobject thisk new managementobjectwin32 logicalthiskdeviceidc,"['c#', '.net']" +103513,setting corner radius on uiimageview not working i am at a bit of a loss i have used the layer property of uiview to round the corners of multiple elements in my app however this one uiimageview is simply not complying not sure what i am missingthe uiimageview called previewimage is contained in a table view cell i have tried setting the cornerradius property multiple location in the cell itself and in the controller that creates the cell to no availstatic nsstring cellidentifier mytableviewcellmytableviewcell cell mytableviewcell tableview dequeuereusablecellwithidentifiercellidentifierif cell nil nsarray toplevelobjects nsbundle mainbundle loadnibnamedcellidentifier ownerself optionsnil cell toplevelobjects objectatindex0 cellpreviewimagelayercornerradius 20 made it 20 to make sure it is obviousis there something about the way cells are loaded that i am missing,"['iphone', 'ios']" +103521,gwt webappcreator creating a maven project the source attachment does not contain the source for the file urlclasspathclass i have created a maven2based gwt application imported it into eclipse and when i debug as a gwt web application the eclipse debug session suspends with a filenotfoundexception it thisplays a window saying the source attachment does not contain the source for the file urlclasspathclassi have completely wiped out the eclipse workspace and metadata subdirectory createdimported a blank project and the same thing happens if i do run as gwt web application it works ok with a couple of warnings what do i need to tweak to get this working in debug modesteps to reproduce the problem1 create applicationwebappcreator noant maven xnoeclipse out myapp comexamplemyapp2 import and change settingsthe application is imported into the eclipse workspace in the settings the use google web toolkit checkbox is tickedthis project has a war directory is checked the war directory is set to srcmainwebapp the launch and deploy from this directory is unchecked3 debug asnow the debug toolbar button is pressed choose gwt web application and select targetw as the war directory you should see the same problem the call stack in the debug pane contains the followingmyapphtml web application comgooglegwtdevdevmode at localhost51620 thread main suspended exception filenotfoundexception urlclasspathjarloadergetjarfileurl line 644 urlclasspathjarloaderaccess600urlclasspathjarloader url line 540 urlclasspathjarloader1run line 607 accesscontrollerdoprivilegedprivilegedexceptionaction line not available native method urlclasspathjarloaderensureopen line 599 urlclasspathjarloaderurl urlstreamhandler hashmap line 583 urlclasspathjarloader3run line 810 accesscontrollerdoprivilegedprivilegedexceptionaction line not available native method urlclasspathjarloadergetresourcestring boolean set line 806 urlclasspathjarloadergetresourcestring boolean line 765 urlclasspathgetresourcestring boolean line 169 urlclassloader1run line 194 accesscontrollerdoprivilegedprivilegedexceptionaction accesscontrolcontext line not available native method launcherappclassloaderurlclassloaderfindclastring line 190 launcherappclassloaderclassloaderloadclastring boolean line 307 launcherappclassloaderloadclastring boolean line 301 launcherappclassloaderclassloaderloadclastring line 248 cprogram filesjavajdk160 21binjavawexe 28 nov 2010 152832versions and pluginsgwt 21eclipse helios 36maven 221jrejdk jdk 16021google plugin for eclipse 36 version 140v201010280102maven integration for eclipse m2eclipse version 0102201006231649 this has been configured to point to maven 221 environment and not to use the embedded maven3 instance,['java'] +103540,alter table in magento setup script without using sql jonathon day saysupdates should not be in the form of sql commands i have not come across any ddl or dml statments that cannot be executed via magentos config structuresin the question how can i migrate configuration changes from development to production environmenti would like to know how best to addmodifyremove a column or index tofrom a table in this manner but without relying on sql is it even possiblefurthermore what other actions can only be done in sql,"['php', 'sql']" +103555,mysql russian characters thisplay incorectly i have to make an russian version of a website but i cannot find out how to insert russian characters into databasei tryed almost every possible coding but it only shows 20,['mysql'] +103562,int vs intptr when you have a handle first a background questionin general what is the difference between int and intptr my guess is that it is an actual object rather than a value like an int or byte is assuming that is trueso they are not the same yet i see handles represented as both intptr controlhandleint or uint a pinvoke can be setup to return an int and it works just finedllimportcoredlldll setlasterror truepublic static extern int getforegroundwindowprivate string getactivewindow const int nchars 256 int handle 0 stringbuilder buff new stringbuildernchars handle coredllgetforegroundwindow if coredllgetwindowtexthandle buff nchars 0 return bufftostring return so int vs intptr does it matter for handles can you use either,['c#'] +103563,android list view clickable problem i have this customized list each row contains an image and two lines of text one below the other i want to open a new activity when any list item is clicked but i am not able to do so even after implementing the setonitemclicklistener please correct me if i am wrong the below is the code for the list ps this is an normal activity and not list activityl1setadapternew efficientadapterthiseventtitlearrayeventdatearrayeventimagelinkarray l1 getlistview l1setclickabletrue l1setonitemclicklistenernew onitemclicklistener override public void onitemclickadapterview arg0 view arg1 int position long arg3 intent intent new intentmainactivitythis thisplayactivityclass bundle b new bundle bputstringevent eventtitlearrayposition intentputextrasbundle startactivityintent toastmaketextgetapplicationcontext opening detailed view foreventtitlearrayposition toastlength shortshow,['android'] +103566,java subversion libraries i have been researching java apis for subversion svn it seems there are 3 availablejavahl part of the svn project provides a relatively lowlevel apisvnclientadapter part of the subclipse project provides a relatively highlevel apisvnkit unlike the other 2 this provides a 100 java implementation of the svn protocol ie no native libaries must be installed it provides a highlevel api a lowlevel api an implementation of javahl and a commandline client that uses svnkit for it is implementationi have no practical experience with any of these apis but assuming the above is true svnkit looks like a clear winner i know from experience that appearances can be deceiving so am looking for feedback from someone who has actually used one or more of these libraries is svnkit the runaway winner as suggested above or is there a better choicei guess the answer will depend on what i will be doing with the api and perhaps surprisingly the answer is mostly writing eg adding updating and deleting files creating projects and repositories branching etcthanksdon,['java'] +103568,stringreplaceall without regex i would like to replace all instances of a substring in a string but stringreplaceall only accepts a pattern the string that i have came from a previous match is it possible to add escapes to the pattern that i have or is there a version of replaceall in another class which accepts a literal string instead of a pattern,['java'] +103576,create a devise user from ruby console any idea on how to create and save a new user object with devise from the ruby consolewhen i tried to save it i am getting always false i guess i am missing something but i am unable to find any related info,"['ruby-on-rails', 'ruby']" +103587,rspec bundle is broken in textmate and rvm i have had a difficult time since i started using rvm i have done all the rvmtextmate set up and have the latest bundles but i still cannot run rspec test from textmatei have the latest bundle from githubcomrspecrspectmbundlegitand it is installed in libraryapplication supporttextmatebundles rspectmbundlervm default is using the system ruby 186rspec gem versionsgem list local grep specblue light special 020rspec 220rspeccore 221 201rspecexpectations 220 201rspecmocks 220 201rspecrails 201 132textmatetm rubyusersjspoonerrvmbinrvmautorubythe error rspeccore loaderrorusersjspoonerlibraryapplication supporttextmatebundlesrspectmbundlesupportlibrspecmaterb29in require no such file to load rspeccore loaderror from usersjspoonerlibraryapplication supporttextmatebundlesrspectmbundlesupportlibrspecmaterb29 from tmptextmatecommand8073rb2inrequire from tmptextmatecommand8073rb2,['ruby'] +103597,rails how to sortreorder an orderedhash i have an orderedhash generated from the answer here that looks like thisorderedhash 253445710153850so i need to sort the hash by the second value in descending order i tried thisvarsort ab b1 a1nomethoderror undefined method sort for activesupportorderedhash0x127a50848how can i reorder this orderedhash,['ruby-on-rails'] +103601,directly accessing nested dictionary values in objectivec is there a way to directly access an innerarray of an an outer array in objectivec for example a call to an external data source returns the following objectbio this is the profilebio datafirst name johnlast name doelocation name any town any statemetadata pictures picture i want to be able to access for example the locationname or the metadatapicturespicture data dot notation however does not seem to work for example gfblocation result objectforkeylocationname gfbpicture result objectforkeymetadatapicturespicturethe only way i have been able to access this data is by first setting the contents of the inner arrays to objects thoughts,"['iphone', 'objective-c']" +103604,do i need to release the com object on every foreach iteration heres the potential problemi create a com object and then use a foreach to iterate through each element in a collection it returns do i need to release each individual element i iterate through in the collection see code below if so i cannot think of a way to effectively to release it from within a finally statement just in case there is an error as the item is being operated uponany suggestionsprivate static void dostuff comobjectclass manager null try manager new comobjectclass foreach comobject item in managergetcollectionofitems logdebugitemname releasecomobjectitem do i need this line it is not in a finally block possible memory leak catch exception finally releasecomobjectmanager private static void releasecomobjectobject instance if instance null try systemruntimeinteropservicesmarshalreleasecomobjectinstance catch log potential memory leak logdebugpotential memory leak unable to release com object finally instance null,['c#'] +103617,is stringelementat o1 under remarks it saysif the type of source implements ilist that implementation is used to obtain the element at the specified index otherwise this method obtains the specified elementstring does not implement ilistt does that mean this will be an on operation if i declare something likeienumerablechar mystring stringy,['c#'] +103630,soapfault exception could not connect to host sometimes fail to call the web servicethis problem happens all the timewhat could be the problemerror soapfault exception http could not connect to host in 0 internal function soapclient dorequestxml version http 1 0,['php'] +103634,svg icons not showing up in qt4 release build in windows i have a qt4 application with svg icons compiled with mingw in windows linked to qt shared librarieswhen application is run svg icons show up in debug and release builds in linux however in windows svg icons show up only in debug build but not in release buildall svg icons are listed in projectqrc and projectpro has resources projectqrc application uses qtsvg4dll version 470qt 470 qt creator 201 mingwg 440solution update in application directory create imageformats directory and put qsvg4dll there instead of application directory itself or create a qtconf file with appropriate path more information in deploying plugins,['c++'] +103655,live wallpaper preview thumbnail size whats the width and height of the live wallpaper preview thumbnail in pixels it is definitely larger than 72x72 that i know,['android'] +103668,does typefacecreatefromasset cache simple question does typefacecreatefromasset cache or should i just keep a reference around in memory to keep handy the reason why i ask is because i use it quite a lot all to maintain a single font across many activities views so i am wondering if typeface will do a simple bit of caching so i do not have to maintain the reference myself,['android'] +103669,email multiple recipients without revealing other recipients i am using javamail to send emails to a list of recipients but do not want them to be able to see who else received the email i also do not want to send it using bcc since then the user does not even see themselves in the to list i thought this code would do it but it shows all the recipients in the to list other than creating a loop and sending the emails one at a time is there another way to do thisnote recipients is a string array containing the email addressesjavaxmailinternetinternetaddress addressto new javaxmailinternetinternetaddressrecipientslengthfor int i 0 i recipientslength i addresstoi new javaxmailinternetinternetaddressrecipientsimsgsetrecipientsjavaxmailmessagerecipienttypeto addressto,['java'] +103670,is there an html safe truncate method in rails i have a string of html in rails i would like to truncate the string after a certain number of characters not including the html markup also if the split happens to fall in the middle of an opening and closing tag i would like to close the open tags for examplehtml 123a href456a7890truncate markuphtml length 5 123a href45a,"['html', 'ruby-on-rails', 'ruby']" +103677,fedex checksum algorithm for tracking numbers how do i validate potential fedex tracking numbers without hitting a web service i have heard fedex employs a modified version of the luhn algorithm,['java'] +103700,regarding javascript new date and dateparse this is my code var exampledate23122010 231200 var datenew dateexampledatereturns invalid date var date1dateparseexampledatereturns nani want to convert above string into date so i have written a code as you have seen above this code is running fine in ie and opera but date variable is returning me an invalid date and date1 is returning nan in mozilla firefox what should i doit is urgent help methank you,['javascript'] +103702,c easiest way to populate a listbox from a list if i have a list of strings egliststring mylist new liststringmylistaddhellomylistaddworldis there an easy way to populate a listbox using the contents of mylist,['c#'] +103717,closed source library includes boost thistribution i am using a closed source library by activ financial that includes with their api a boost thistribution both some boost header files and boost library filesi also use boost in my existing codebase and i need to use activ from my existing codesome pointsi can encapsulate my use of activ so that the entire activ part amounts to a single class i wrote that does not expose any of activs headersthis single header file does not use any boost anythingin this way i can ensure that the activ parts of my code use activs boost hpp files and my code uses my boosts hpp filesmy worry comes in linking how can i ensure that my activ dependent code links to activs boost and my other code links to my boosti am using g now will also be doing this in vs2008 i got it working in vs2008 before but i have no idea how everything linked i want to try to make sure it is done correctlyis there a way to do it without further encapsulating the activ part in a dynamic library editfor one my final product is always an executable file for two i statically link to boost myself the activ library includes both static and dynamic versions of boost object libraries and i plan to statically link it i never pass boost objects between code that uses different boost versionsthe question is how do i link one cpp or o file to objects in one library file and then make sure other o files link to the identical objects in another library file is this possible,['c++'] +103718,error deleted row information cannot be accessed through the row to whom this may concern i have searched a considerable amount of time to work a way out of this error deleted row information cannot be accessed through the rowi understand that once a row has been deleted from a datatable that it cannot be accessed in a typical fashion and this is why i am getting this error the big issue is that i am not sure what to do to get my desired result which i will outline belowbasically when a row in dg1 is deleted the row beneath it takes the place of the deleted row obviously and thus inherits the deleted rows index the purpose of this method is to replace and reset the rows index via grabbing it from the corresponding value in the dataset that took the deleted rows place and as such the index valueright now i am just using a label lbltext to try and get a response from the process but it crashes when the last nested if statement trys to compare valueshere is the codevoid dg1 clickobject sender eventargs e rowindex dg1currentrowindex gets the current rows string value converttostringdg1rowsrowindexcells0value if dstables0rowsrowindexrowstatetostring deleted for int i 0 i dg1rowscount i if converttostringdstables0rowsi0tostring value where the error is occurring lbltesttext aha when working will place index of compared dataset value into rowstate which is thisplaying the current index of the row i am focussed on in dg1 thanks ahead of time for the help i really did search and if it is easy to figure out through a simple google search then allow myself to repeatably hate on me because i did trygc,['c#'] +103746,recursion and passing by reference i have a tree of categories of the following structure6 array id 6 name computers productcount 0 children array 91 array id 91 name notebook productcount 5 children array 86 array id 86 name desktop productcount 0 children array beside a subcategory each category may contain products like a folder may contain subfolders and just filesi am trying to write a recursive function which i want to take this array as reference and strip both leaf categories with productcount 0 and all parent categories that contain such empty nodes in other words after processing i want to have only those categories that hold products on any sublevelsi have wrote some code now debugging it and it does not strip empty nodes may be i am not using references properly please help me fix it if possible function prunetree node if nodechildren nodeproductcount unsetnode if emptynodechildren foreach nodechildren as key child prunetreenodechildrenkey return,['php'] +103747,scaling svg raphaeljs like an swf i started using raphaeljs a few days ago and i am really enjoying it the only thing i have not been able to figure out is how to get the paper or svgvml tag to fill the browser window like an swf see this examplenote the way the above example resizes with the browser windowi was able to get the paper to resize with the browser window but no luck getting all the vector graphics to adjust their size any feedback would be greatly appreciatedediti tried a bunch of different routes with this viewbox worked great but its svg only i just figured out how to do it using raphael sets and a little code on the windowonresize event i will post my findings later tonight or tomorrow i would still really like to see other solutions to the question if there are any,['javascript'] +103748,basic syntax question for shared ptr i am new to the shared ptr i have a few questions regarding the syntax of c0x shared ptr as belowfirst questionshared ptrclassaptrnew classa worksshared ptrclassaptrptr how could i create a new object to assign it to shared pointersecond questionshared ptrclassaptr2 could be tested for null from the if statement belowshared ptrclassa ptr3new classaptr3 how could i assign null again to ptr3 so that the if statement below becomes trueifptr3 cout ptr equals null,['c++'] +103751,is it possible to detect gdi leaks from the visual studio debugger leaking gdi objects can be seen from the task manager or from process explorer well you do not see the leaks but you can see if object uasage count continually goes upthere are also tools that allow to view gdi objects by type such as gdiviewa deleaker dpus or the gdidebug sourecodea note that i consider gdiview a great tool to get the job done of identifying and confirming the existance gdi leaks but it does not really help you to find the leaking code in large applications i will also note here that the tool works very nicely and seems well behaved although its homepage is a littlebit weird there is also a windbg plugin called leaktrap that uses mss detours libraryi also know and have used aqtimes resource profiler that allows to detect gdi and other resource leaks in an application including stack traces for the leaking callsnow my actual question however is is it possible to detect leaking gdi objects from within the vc debugger so that one does not need a separate tool and gdi leaks can be caught during normal debugging and not have to be checked separately,['c++'] +103775,why is this illegal in strict mode yeah yeah i know strict mode am not around yet but really i am planning for the futureso why is this thisattridreplacecontrol legendfadein not allowed in es5 strict modeor am i misinterpreting jslintproblem at line 516 character 18 strict violationcould it be a little more verbose i wondereditto avoid confusion heres more of the original codefunction thisplaylegend thisattridreplacecontrol legendfadein,['javascript'] +103793,how to view the identity of person who signed the apk on android device i need to view who signed the application i have installed onto my device is this generally possible to do on the device or on pc,['android'] +103812,removing control characters from a string in python i currently have the following codedef removecontrolcharactersline i 0 for c in line if c chr32 line linei 1 linei1 i 1 return linethis is just does not work if there are more than one character to be deleted,['python'] +103828,does webkit have a clipping bug given a region where the lineheight and any margins are n and the region has a height that is a multiple of n and the scrolltop is increased by multiples of n i find that i get the result i expect in firefox opera and netfront but in chrome windows safari mac and the latest webkit nightly mac there is some leakage and i see partial linesin my actual project which i cannot share the effect is quite pronounced but even in a reduced test case the bottom of the previous line can be seen peaking out at the top of the boxis it possible to avoid this effect is this a bug in the webkit rendering engine that should be reportedthe reduced test case can be seen below and as a live example on my website click on the document a few times to scroll it and not the dots at the top of the box which are the bottom of the letters of the previous linedoctype html html langen head meta charsetutf8 titlescrolltop issuetitle style body backgroundcolor white color black wrapper width 300px fontsize 19px fontfamily sansserif lineheight 21px height 210px a multiple of line height overflow hidden wrapper margin 0 padding 0 wrapper p marginbottom 21px same as line height style script windowaddeventlistenerclick function documentgetelementbyidwrapperscrolltop 210 script head body h1scrolltop issueh1 div idwrapper div idcontent pto sherlock holmes she is always ithei woman i have seldom heardhim mention her under any other name in his eyes she eclipsesand predominates the whole of her sex it was not that he feltany emotion akin to love for irene adler all emotions and thatone particularly were abhorrent to his cold precise butadmirably balanced mind he was i take it the most perfectreasoning and observing machine that the world has seen but as alover he would have placed himself in a false position he neverspoke of the softer passions save with a gibe and a sneer theywere admirable things for the observer8212excellent for drawing theveil from men8217s motives and actions but for the trained reasonerto admit such intrusions into his own delicate and finelyadjusted temperament was to introduce a thistracting factor whichmight throw a doubt upon all his mental results grit in asensitive instrument or a crack in one of his own highpowerlenses would not be more thisturbing than a strong emotion in anature such as his and yet there was but one woman to him andthat woman was the late irene adler of dubious and questionablememoryp i had seen little of holmes lately my marriage had drifted usaway from each other my own complete happiness and thehomecentred interests which rise up around the man who firstfinds himself master of his own establishment were sufficient toabsorb all my attention while holmes who loathed every form ofsociety with his whole bohemian soul remained in our lodgings inbacker street buried among his old books and alternating fromweek to week between cocaine and ambition the drowsiness of thedrug and the fierce energy of his own keen nature he was stillas ever deeply attracted by the study of crime and occupied hisimmense faculties and extraordinary powers of observation infollowing out those clues and clearing up those mysteries whichhad been abandoned as hopeless by the official police from timeto time i heard some vague account of his doings of his summonsto odessa in the case of the trepoff murder of his clearing upof the singular tragedy of the atkinson brothers at trincomaleeand finally of the mission which he had accomplished sodelicately and successfully for the reigning family of hollandbeyond these signs of his activity however which i merelyshared with all the readers of the daily press i knew little ofmy former friend and companionp one night8212it was on the twentieth of march 18212i wasreturning from a journey to a patient for i had now returned tocivil practice when my way led me through backer street as ipassed the wellremembered door which must always be associatedin my mind with my wooing and with the dark incidents of thestudy in scarlet i was seized with a keen desire to see holmesagain and to know how he was employing his extraordinary powershis rooms were brilliantly lit and even as i looked up i sawhis tall spare figure pass twice in a dark silhouette againstthe blind he was pacing the room swiftly eagerly with his headsunk upon his chest and his hands clasped behind him to me whoknew his every mood and habit his attitude and manner told theirown story he was at work again he had risen out of hisdrugcreated dreams and was hot upon the scent of some newproblem i rang the bell and was shown up to the chamber whichhad formerly been in part my own div div body html,"['javascript', 'html', 'css']" +103834,how to force a piece of text to be direction ltr inside a direction rtl paragraph so phone numbers are always ltr left to rightworking on a multilingual website i need to insert a phone number with a prefix and numbers separated by inside a text paragraph that has direction rtl for relevant languages of courseso i have something like thisltr test directionltrrtl test directionrtlphone directionltrp idtextplease call to span idphone44123321span for some helppof course this is not working because direction only works for block elements and span is an inline element i need the phone number to be inside the paragraph so i cannot change span to thisplayinlinei am being clearhow to make it work,"['html', 'css']" +103836,exclude click event based on condition i am trying to set conditions on a jquery event i have an input element and a div i want to detect a click anywhere on the page and to execute that method but only if the click is not on the input or div,['jquery'] +103852,how do i wait for an asynchronously thispatched block to finish i am testing some code that does asynchronous processing using grand central thispatch the testing code looks like thisobject runsomelongoperationanddo stassertathe tests have to wait for the operation to finish my current solution looks like this block bool finished noobject runsomelongoperationanddo stasserta finished yeswhile finishedwhich looks a bit crude do you know a better way i could expose the queue and then block by calling thispatch syncobject runsomelongoperationanddo stassertathispatch syncobjectqueue abut thatas maybe exposing too much on the object,['objective-c'] +103856,why do we not just use minified js i see this word alot minified and i never seem to pick a script ie from jquery plugins that is minified but i suppose i should if i am right minified means to remove all unecessary stuff from source code without changing its functionality so why dont we just have minified source and why bother with the full blown version why give people the optionyolo,"['javascript', 'jquery']" +103889,why is t instantiated as int can anyone please explain why this compiles and why does t end up with type intinclude utilityvoid fint r rtemplate typename fun typename tvoid gfun fun t t funstdforwardtt int main int i 0 gf ii see this on gcc 450 20100604 and gdb 72602,['c++'] +103901,string format for numbers or currency i need to give comma for every thousends so i used dataformatstring0 it is working fine but when value is 0 it is showing 00 i just want to show only 0how can we do that,"['c#', 'asp.net']" +103908,how can i strip all punctuation from a string in javascript using regex if i have a string with any type of nonalphanumeric character in it this is an example of a string with punctuationhow would i get a nopunctuation version of it in javascriptthis is an example of a string with punctuation,['javascript'] +103927,if you have multiple spaces inside a string in java how do you condense them into a single space between words if a string has multiple spaces between wordsthe cat sat on the mathow do you make it a single spacethe cat sat on the mati tried this but it did not workmytext mytexttrimreplace,['java'] +103928,cross platform php to c net encryptiondecryption with rijndael i am currently having a bit of problem with decrypting a message encrypted by php mcryptthe php code is as followingphp iv size mcrypt get iv sizemcrypt rijndael 256 mcrypt mode cbc iv 45287112549354892144548565456541 key anjueolkdiwpoida text this is my encrypted message crypttext mcrypt encryptmcrypt rijndael 256 key text mcrypt mode cbc iv crypttext urlencodecrypttext crypttext64base64 encodecrypttext printcrypttext64 nbrthe the encrypted message is then sent to a aspnet platform c however i am having problem retaining the order of decryption base64 decode to urldecode the code i had in aspnet is as the following iv and key is the same as in phppublic string decodestring str byte decbuff convertfrombase64stringstr return systemtextencodingutf8getstringdecbuffstatic public string decryptrj256string cypher string keystring string ivstring string sret rijndaelmanaged rj new rijndaelmanaged utf8encoding encoding new utf8encoding try byte message convertfrombase64stringcypher byte message encodinggetbytescypher byte key encodinggetbyteskeystring byte iv encodinggetbytesivstring rjpadding paddingmodezeros rjmode ciphermodecbc rjkeysize 256 rjblocksize 256 rjkey key rjiv iv memorystream ms new memorystreammessage using cryptostream cs new cryptostreamms rjcreatedecryptorkey iv cryptostreammoderead using streamreader sr new streamreadercs sret srreadtoend finally rjclear return sretstring temp decryptrj256serverurldecodedecodecypher keystring ivstringthe problem i am having is that after i recieved the encrypted message from php i converted it into byte and then converted back to utf8 encoded string so i can urldecode it then i feed the result into the function where i converted the string back to byte and ran it through the decryption process however i cannot get the desired resultany ideasthanks in advance,"['c#', 'php']" +103940,android asynctask progressdialog will not open in activitygroup i am trying to have a a progress dialog open when polling my server the class is an activitygroup because it is nested within a tab bar to keep the view within the frame the activitygroup is needed here is the declaration of my activitygroup class public class checkinactivity extends activitygroup public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutcheckin new locationcontrolexecutethisnow my asynctask class is within the same checkinactivityclass as suchprivate class locationcontrol extends asynctaskcontext void void private final progressdialog dialog new progressdialogcheckinactivitythis protected void onpreexecute thisdialogsetmessagedetermining your location thisdialogshow when i run the given app it throughs an error relating to windowmanagerbadtokenexception stating the it cannot start the window with an unknown token i tried making a sample app that is just a regular activitynot activitygroup and it worked just fine does anyone know how to modify this to make it work or a work around that will allow the progress bar to be nested within the tab bar any help is greatly appreciated,['android'] +103950,creating one static library for ios and simulator for thistribution if you create a static library for ios do you have to thistribute the header files with it or is there another way to get it to workcurrently i have a single my liba file for both device and simulator but when i drag it into another test app to use it it says it cannot find the header and that all the places i am using it in the code are undeclared so i figure i am either doing something wrong or i have to also send the appropriate header files with itbackground to my processi have seen two guides for creating a static library for both device and simulator one on this site build fat static library device simulator using xcode and sdk 4and one here i used the second site to just try it out i am also a bit curious if i did it correctly i just went into the releaseiphoneossimulator folders and found the a in the ios one and the o in the simulator one,"['objective-c', 'ios']" +103961,simulating duck typing in java the problem i would like to be able to generically access in java any propertyfield on a java ojbect similarly to how a dynamic language think groovy javascript would i would not know at the time i am writing this plumbing code what type of object it is or what the propertyfield name will be but i will know the propertyfield name when i go to use itmy current solution so far i have written a simple wrapper class that uses javabeansintrospector to grab the properties of a beanpojo and expose them as a mapstring object it is crude but works for simple casesmy question is what other methodologies are there for approaching this problem besides reflection converting to a mapbefore i go too much further down this path i would like to know if anyone knows how i could cannibalize something out of rhino or perhaps javaxscript which has a well thought out implementation of this concept or perhaps an entirely different approach that i have not considerededit yes i am familiar with reflection which i believe is what introspector is using under the hood anyway i was just curious if there was any other well thought out solutionsedit 2 it appears that the most popular answers involve 1 reflection either directly or via helper classes andor 2 mapping to interfaces which implement the desired class members i am really intrigued by the comment which talks about leveraging groovy since groovy has true ducktyping and it is a jvm language is there a way to make a simple helper in groovy and call it from java this would be really cool and probably more flexible and perform betteranswer i marked mikes answer as the best since it is a complete concept which comes the closest i probably would not go that route for this particular case but it is certainly a useful approach anyone looking through this should be sure to read the conversations on here as there is a lot of useful info in there as wellthanks,['java'] +103962,using regexp in assertequals does not work i am having problems with using regexp in my assertequals statement this is the statementassertassertequalsregexptst095 drivergettitlebut i get this errororgjunitcomparisonfailure expectedregexptst095 but wastst23570 this is the new summaryit looks like the regexp is just a string that is being compared what am i missing,['java'] +103971,naming convention for a c dictionary how do we name a dictionary variablesay in my method i have dictionarystring liststring dictionary where the keys of the dictionary are country names and the values are lists of provincestate names how should i rename dictionaryi know we can create a country class for this example but please do not mention this alternative because i am thinking of good naming convention herethanks,['c#'] +103982,is that possible to build static qt library with webkit enabled and how i tried to build static qt library with the following commandconfigure prefixusrlocalqt static accessibility multimedia audiobackend svg webkit javascriptjit script scripttools declarative dbus debugbut i got a message saidwarning using static linking will thisable the webkit moduleis that possible to build static qt library with all modules enabled and howthanks,['c++'] +103989,what do f and d mean at the end of numeric literals i have seen some of this symbols but i cannot find anything strange with itdouble d 5dfloat f 30fwhat does the d and f behind 5 exactly means,['java'] +104002,integer cube root i am looking for fast code for 64bit unsigned cube roots i am using c and compiling with gcc but i imagine most of the work required will be language and compileragnostic i will denote by ulong a 64bit unisgned integergiven an input and i require the integral return value r to be such thatr r r and and r 1 r 1 r 1that is i want the cube root of n rounded down basic code likereturn ulongpown 103is incorrect because of rounding toward the end of the range unsophisticated code likeulongcuberootulong n ulong ret pown 05 103 if n 101ull return ret if n 18446724184312856125ull return 2642245ull if ret ret ret n ret while ret ret ret n ret return ret while ret 1 ret 1 ret 1 n ret return retgives the correct result but is slower than it needs to bethis code is for a math library and it will be called many times from various functions speed is important but you cannot count on a warm cache so suggestions like a 2642245entry binary search are right outfor comparison here is code that correctly calculates the integer square rootulong squarerootulong a ulong x ulongsqrtdoublea if x 0xf xx a x return x,['c'] +104008,where is the makefile generated by the eclipse cdt i have built a hello world c project with eclipsehelios cdt it compiled fine but i would like to take a look at the makefile cdt generated i cannot find it in project folderdebugrelease folders or in the src folders where can i find this makefile,['c++'] +104024,android result from asynctask not being returned to main activity i am trying to use an asynctaskextended class to handle connecting to a url parsing json thisplaying an indeterminate progressdialog during parsing and returning the results as keyvalue pairs in a hashmap to the main activity the results of the hashmap will then be read by the main activity and put into form fields however even though i am populating the hashmap in my asynctask evidenced by println statements calling a method in the main activity that returns the hashmap yields an empty result i cannot figure out if this is something i am doing wrong or if i am misunderstanding the capabilities of asynctaski am debating converting my class that extends asynctask to an activity essentially the user should not be able to do anything else during this data searchparsing and should wait until the progressdialog goes away before they can interact with the application again or by hitting the back button also my application needs to be able to handle certain cases in my asynctask where exceptions are caught cannot connect to url bad json product id to search by cannot be found and custom error dialogs are tailored for those exceptions i could easily do this if this class were an activity as i could send back different result codes when calling finish depending on if an exception is caughtagain i am not sure if asynctask is the best solution here since the user will not be doing anything else while the information is being gathered and parsed please advise me if a new activity would make sense or if i am just mangling my implementation of a background threadmainactivityjavaminitiateproductlookupbuttonsetonclicklistenernew viewonclicklistener public void onclickview v productlookup pl new productlookupid mainactivitythis plexecute the below variable is always empty hashmapstring string productinfo plgetproductinfo applyproductinfotoformfieldsproductinfo productlookupjavapublic class productlookup extends asynctaskobject void hashmapstring string private string mproductid private context mcontext hashmapstring string mproductinfo progressdialog mdialog public productlookupstring id context applicationcontext mproductid id mcontext applicationcontext mproductinfo new hashmapstring string override protected void onpreexecute mdialog new progressdialogmcontext mdialogsetmessageloading product info please wait mdialogsetindeterminatetrue mdialogsetcancelablefalse mdialogshow override protected void onpostexecutehashmapstring string result superonpostexecuteresult mdialogthismiss mproductinfo result override protected hashmapstring string doinbackgroundobject params try connect to url parse json and add keyvalue pairs to mproductinfo catch malformedurlexception e eprintstacktrace catch ioexception e eprintstacktrace catch jsonexception e eprintstacktrace finally try close inputoutput reader variables catch ioexception e eprintstacktrace return mproductinfo public hashmapstring string getproductinfo return thismproductinfo,['android'] +104029,asihttprequest 61 errors i am using the asihttprequest in many projects but recently with each new project when i am trying to add the asihttprequest classes i get the following error before using classes just when i am trying to import thembuild finjan of project finjan with configuration debugld builddebugiphonesimulatorfinjanappfinjan normal i386cd usersappledesktopapplicationfinjansetenv macosx deployment target 105setenv path developerplatformsiphonesimulatorplatformdeveloperusrbindeveloperusrbinusrbinbinusrsbinsbindeveloperplatformsiphonesimulatorplatformdeveloperusrbingcc42 arch i386 isysroot developerplatformsiphonesimulatorplatformdevelopersdksiphonesimulator313sdk lusersappledesktopapplicationfinjanbuilddebugiphonesimulator fusersappledesktopapplicationfinjanbuilddebugiphonesimulator filelist usersappledesktopapplicationfinjanbuildfinjanbuilddebugiphonesimulatorfinjanbuildobjectsnormali386finjanlinkfilelist mmacosxversionmin105 framework foundation framework uikit framework coregraphics framework audiotoolbox framework avfoundation o usersappledesktopapplicationfinjanbuilddebugiphonesimulatorfinjanappfinjanundefined symbols cfhttpauthenticationisvalid referenced from asihttprequest attempttoapplyproxycredentialsandresume in asihttprequesto asihttprequest attempttoapplycredentialsandresume in asihttprequesto cfhttpmessageapplycredentialdictionary referenced from asihttprequest applyauthorizationheader in asihttprequesto asihttprequest applyauthorizationheader in asihttprequesto asihttprequest applyproxycredentials in asihttprequesto asihttprequest applycredentials in asihttprequesto cfhttpmessageisheadercomplete referenced from asihttprequest readresponseheaders in asihttprequesto kcfstreampropertyhttpsproxyport referenced from kcfstreampropertyhttpsproxyportnon lazy ptr in asihttprequesto maybe you meant kcfstreampropertyhttpsproxyportnon lazy ptr inflate referenced from asihttprequest uncompresszippeddata in asihttprequesto asihttprequest uncompresszippeddatafromsourcetodestination in asihttprequesto kcfstreamsslcertificates referenced from kcfstreamsslcertificatesnon lazy ptr in asihttprequesto maybe you meant kcfstreamsslcertificatesnon lazy ptr cfnetworkcopyproxiesforautoconfigurationscript referenced from asihttprequest proxiesforurlfrompac in asihttprequesto kcfproxytypekey referenced from kcfproxytypekeynon lazy ptr in asihttprequesto maybe you meant kcfproxytypekeynon lazy ptr cfreadstreamcreateforstreamedhttprequest referenced from asihttprequest startrequest in asihttprequesto asihttprequest startrequest in asihttprequesto kcfproxyportnumberkey referenced from kcfproxyportnumberkeynon lazy ptr in asihttprequesto maybe you meant kcfproxyportnumberkeynon lazy ptr kuttagclassmimetype referenced from kuttagclassmimetypenon lazy ptr in asihttprequesto maybe you meant kuttagclassmimetypenon lazy ptr inflateend referenced from asihttprequest uncompresszippeddata in asihttprequesto asihttprequest uncompresszippeddatafromsourcetodestination in asihttprequesto asihttprequest uncompresszippeddatafromsourcetodestination in asihttprequesto asihttprequest uncompresszippeddatafromsourcetodestination in asihttprequesto asihttprequest uncompresszippeddatafromsourcetodestination in asihttprequesto inflateinit2 referenced from asihttprequest uncompresszippeddata in asihttprequesto asihttprequest uncompresszippeddatafromsourcetodestination in asihttprequesto kcfproxyautoconfigurationurlkey referenced from kcfproxyautoconfigurationurlkeynon lazy ptr in asihttprequesto maybe you meant kcfproxyautoconfigurationurlkeynon lazy ptr cfhttpauthenticationrequiresusernameandpassword referenced from asihttprequest attempttoapplyproxycredentialsandresume in asihttprequesto asihttprequest attempttoapplycredentialsandresume in asihttprequesto kcfhttpauthenticationusername referenced from kcfhttpauthenticationusernamenon lazy ptr in asihttprequesto maybe you meant kcfhttpauthenticationusernamenon lazy ptr kcfstreampropertyhttpproxy referenced from kcfstreampropertyhttpproxynon lazy ptr in asihttprequesto maybe you meant kcfstreampropertyhttpproxyportnon lazy ptr kcfstreampropertyhttpproxyhostnon lazy ptr kcfstreampropertyhttpproxynon lazy ptr kcfstreampropertyhttpresponseheader referenced from kcfstreampropertyhttpresponseheadernon lazy ptr in asihttprequesto maybe you meant kcfstreampropertyhttpresponseheadernon lazy ptr cfhttpmessagegetresponsestatuscode referenced from asihttprequest readresponseheaders in asihttprequesto kcfproxytypehttp referenced from kcfproxytypehttpnon lazy ptr in asihttprequesto maybe you meant kcfproxytypehttpnon lazy ptr kcfhttpauthenticationschemebasic referenced from kcfhttpauthenticationschemebasicnon lazy ptr in asiauthenticationdialogo kcfhttpauthenticationschemebasicnon lazy ptr in asihttprequesto maybe you meant kcfhttpauthenticationschemebasicnon lazy ptr scnetworkreachabilityschedulewithrunloop referenced from reachability startnotifier in reachabilityo scnetworkreachabilitygetflags referenced from reachability currentreachabilitystatus in reachabilityo reachability isreachable in reachabilityo reachability isconnectionrequired in reachabilityo reachability isconnectionondemand in reachabilityo reachability isinterventionrequired in reachabilityo reachability isreachableviawwan in reachabilityo reachability isreachableviawifi in reachabilityo reachability reachabilityflags in reachabilityo deflateinit2 referenced from asihttprequest compressdata in asihttprequesto asihttprequest compressdatafromsourcetodestination in asihttprequesto cfnetworkcopyproxiesforurl referenced from asihttprequest startrequest in asihttprequesto asihttprequest proxiesforurlfrompac in asihttprequesto cfhttpmessagesetheaderfieldvalue referenced from asihttprequest main in asihttprequesto asihttprequest checkrequeststatus in asihttprequesto kcfproxytypesocks referenced from kcfproxytypesocksnon lazy ptr in asihttprequesto maybe you meant kcfproxytypesocksnon lazy ptr kcfstreampropertyhttpattemptpersistentconnection referenced from kcfstreampropertyhttpattemptpersistentconnectionnon lazy ptr in asihttprequesto maybe you meant kcfstreampropertyhttpattemptpersistentconnectionnon lazy ptr cfhttpmessagecopyversion referenced from asihttprequest readresponseheaders in asihttprequesto cfhttpauthenticationcopyrealm referenced from asihttprequest attempttoapplyproxycredentialsandresume in asihttprequesto asihttprequest attempttoapplycredentialsandresume in asihttprequesto cfhttpmessagecopyallheaderfields referenced from asihttprequest readresponseheaders in asihttprequesto cfhttpmessagecreaterequest referenced from asihttprequest main in asihttprequesto kcfproxyhostnamekey referenced from kcfproxyhostnamekeynon lazy ptr in asihttprequesto maybe you meant kcfproxyhostnamekeynon lazy ptr kcfstreampropertyhttpproxyhost referenced from kcfstreampropertyhttpproxyhostnon lazy ptr in asihttprequesto maybe you meant kcfstreampropertyhttpproxyhostnon lazy ptr cfhttpmessagecopyresponsestatusline referenced from asihttprequest readresponseheaders in asihttprequesto kcfstreampropertyhttprequestbyteswrittencount referenced from kcfstreampropertyhttprequestbyteswrittencountnon lazy ptr in asihttprequesto maybe you meant kcfstreampropertyhttprequestbyteswrittencountnon lazy ptr deflate referenced from asihttprequest compressdata in asihttprequesto asihttprequest compressdatafromsourcetodestination in asihttprequesto scnetworkreachabilitycreatewithaddress referenced from reachability reachabilitywithaddress in reachabilityo kcferrordomaincfnetwork referenced from kcferrordomaincfnetworknon lazy ptr in asihttprequesto maybe you meant kcferrordomaincfnetworknon lazy ptr kcfstreamsslvalidatescertificatechain referenced from kcfstreamsslvalidatescertificatechainnon lazy ptr in asihttprequesto maybe you meant kcfstreamsslvalidatescertificatechainnon lazy ptr cfhttpauthenticationcreatefromresponse referenced from asihttprequest attempttoapplyproxycredentialsandresume in asihttprequesto asihttprequest attempttoapplycredentialsandresume in asihttprequesto deflateend referenced from asihttprequest compressdata in asihttprequesto asihttprequest compressdatafromsourcetodestination in asihttprequesto asihttprequest compressdatafromsourcetodestination in asihttprequesto asihttprequest compressdatafromsourcetodestination in asihttprequesto uttypecopypreferredtagwithclass referenced from asihttprequest mimetypeforfileatpath in asihttprequesto kcfstreampropertyhttpsproxyhost referenced from kcfstreampropertyhttpsproxyhostnon lazy ptr in asihttprequesto maybe you meant kcfstreampropertyhttpsproxyhostnon lazy ptr kcfhttpauthenticationschementlm referenced from kcfhttpauthenticationschementlmnon lazy ptr in asiauthenticationdialogo kcfhttpauthenticationschementlmnon lazy ptr in asihttprequesto maybe you meant kcfhttpauthenticationschementlmnon lazy ptr cfhttpauthenticationcopymethod referenced from asihttprequest attempttoapplyproxycredentialsandresume in asihttprequesto asihttprequest attempttoapplycredentialsandresume in asihttprequesto kcfhttpauthenticationaccountdomain referenced from kcfhttpauthenticationaccountdomainnon lazy ptr in asihttprequesto maybe you meant kcfhttpauthenticationaccountdomainnon lazy ptr uttypecreatepreferredidentifierfortag referenced from asihttprequest mimetypeforfileatpath in asihttprequesto cfnetworkcopysystemproxysettings referenced from asihttprequest startrequest in asihttprequesto scnetworkreachabilityunschedulefromrunloop referenced from reachability stopnotifier in reachabilityo kcfstreampropertyhttpproxyport referenced from kcfstreampropertyhttpproxyportnon lazy ptr in asihttprequesto maybe you meant kcfstreampropertyhttpproxyportnon lazy ptr cfhttpauthenticationrequiresaccountdomain referenced from asihttprequest findproxycredentials in asihttprequesto asihttprequest findcredentials in asihttprequesto asihttprequest attempttoapplyproxycredentialsandresume in asihttprequesto asihttprequest attempttoapplycredentialsandresume in asihttprequesto scnetworkreachabilitycreatewithname referenced from reachability reachabilitywithhostname in reachabilityo scnetworkreachabilitysetcallback referenced from reachability startnotifier in reachabilityo kcfhttpauthenticationpassword referenced from kcfhttpauthenticationpasswordnon lazy ptr in asihttprequesto maybe you meant kcfhttpauthenticationpasswordnon lazy ptr kcfhttpversion1 0 referenced from kcfhttpversion1 0non lazy ptr in asihttprequesto maybe you meant kcfhttpversion1 0non lazy ptr kcfhttpversion1 1 referenced from kcfhttpversion1 1non lazy ptr in asihttprequesto maybe you meant kcfhttpversion1 1non lazy ptr kcfstreampropertysslsettings referenced from kcfstreampropertysslsettingsnon lazy ptr in asihttprequesto maybe you meant kcfstreampropertysslsettingsnon lazy ptr kcfstreamerrordomainhttp referenced from kcfstreamerrordomainhttpnon lazy ptr in asihttprequesto maybe you meant kcfstreamerrordomainhttpnon lazy ptr cfreadstreamcreateforhttprequest referenced from asihttprequest startrequest in asihttprequesto kuttagclassfilenameextension referenced from kuttagclassfilenameextensionnon lazy ptr in asihttprequesto maybe you meant kuttagclassfilenameextensionnon lazy ptrld symbols not foundcollect2 ld returned 1 exit statuswhat is causing this,"['iphone', 'objective-c']" +104051,remove css class in code behind i have this controlasplabel idlblname runatserver textmy name cssclassrequired regular i want to remove the required class from code behind how can i do that,"['c#', 'asp.net', 'css']" +104070,escape sequence f form feed what exactly is it f is said to be the form feed t is a tab a is a beep n is a newline what exactly is a form feed f the following programinclude iostreamint main stdcout hellofgoodbye stdendl prints hello then a female sign an upside down holy hand grenade and then goodbye all on one line,['c++'] +104074,load event for iframe not fired in ie why is the load event not fired in ie for iframesplease take a look at this examplework perfectly as expected in ff and chrome but ie fails,['jquery'] +104078,databinding on custom control with itemplate this is a sample code of my custom server control designertypeofcontainercontroldesignertoolboxdata0blocarrondi runatservercontenuprincipalcontenuprincipal0blocarrondipublic class blocarrondi webcontrol private itemplate contenuprincipal protected panel panelcontenuprincipal new panel public blocarrondi basehtmltextwritertagdiv persistencemodepersistencemodeinnerproperty templateinstancetemplateinstancesingle public itemplate contenuprincipal get return contenuprincipal set contenuprincipal value protected override void oniniteventargs e baseoninite panelcontenuprincipalid panelprincipal thiscontrolsadd panelcontenuprincipal if contenuprincipal null contenuprincipalinstantiatein panelcontenuprincipal and here the implementation controlsblocarrondi runatserver contenuprincipal asplabel idlabelinfo runatserver contenuprincipalcontrolsblocarrondimy label labelinfo is accessible on the code behind great but if i use my custom control in a repeater or a listview i cannot use the containerdataitem property inside the contenuprincipal template asprepeater idrepeaterinfos runatserver itemtemplate controlsblocarrondi runatserver contenuprincipal asplabel runatserver text containerdataitem as msginfothisplaymessage contenuprincipal controlsblocarrondi itemtemplateasprepeaterthe error message systemwebuicontrol does not contain a definition for dataitem and no extension method dataitem accepting a first argument of type systemwebuicontrol could be found are you missing a using directive or an assembly referencehow can i use the containerdataitem property inside the contenuprincipal template of my control,['asp.net'] +104079,how to check that type is inherited from some interface c i have followingassembly asm assemblygetassemblythisgettypeforeach type type in asmgettypes myattribute attr attributegetcustomattributetype typeofmyattribute as myattribute ifattr null type is inherited from iinterface how can i check that type is inherited from myinterface does is keywork will work in this waythank you,['c#'] +104084,servlet context injection fail while using jersey test framework i am beginning with jersey and trying to get freemarker working with it using tdd i want to make a viewprocessor for my templates but fail to inject the servlet context in the classhere is the class code providerpublic class myprocessor implements viewprocessortemplate context public servletcontext mycontext freemarkerconfigurationsettemplateloader new webapptemplateloadermycontext mycontextgetinitparameterfreemarkertemplatepath and here is the test code public class myprocessortest extends jerseytest public static myprocessor mp public myprocessortest throws exception supernew webappdescriptorbuildercomdomainbuild test public void firsttest mp new myprocessor string path new stringtestftl template template mpresolvepath assertnotnulltemplate i use maven with dependencies as follow dependency groupidcomsunjerseyjerseytestframeworkgroupid artifactidjerseytestframeworkgrizzlyartifactid version15snapshotversion scopetestscopedependencymy code runs fine when i deploy to my local jetty server but if i want to test the code in my ide it failed to inject the servlet context context mycontext is null when i run the test i think i am missing something but i am a complete beginner with servlet world,['java'] +104088,hibernate cannot simultaneously fetch multiple bags hibernate throws this exception during sessionfactory creationorghibernateloadermultiplebagfetchexception cannot simultaneously fetch multiple bagsthis is my test caseparentjavaentitypublic parent id generatedvaluestrategygenerationtypeidentity private long id onetomanymappedbyparent fetchfetchtypeeager indexcolumnnameindex col if i had this the problem solve but i retrieve more children than i have one child is null private listchild childrenchildjavaentitypublic child id generatedvaluestrategygenerationtypeidentity private long id manytoone private parent parenthow about this problem what can i doeditok the problem i have is that another parent entity is inside my parent my real behavior is thisparentjavaentitypublic parent id generatedvaluestrategygenerationtypeidentity private long id manytoone private antoherparent anotherparent onetomanymappedbyparent fetchfetchtypeeager private listchild childrenanotherparentjavaentitypublic antoherparent id generatedvaluestrategygenerationtypeidentity private long id onetomanymappedbyparent fetchfetchtypeeager private listanotherchild anotherchildrenhibernate does not like two collections with fetchtypeeager but this seems to be a bug i am not doing unusual thingsremoving fetchtypeeager from parent or anotherparent solves the problem but i need it so real solution is to use lazycollectionlazycollectionoptionfalse instead of fetchtype thanks to bozho for the solution,['java'] +104101,in html5 canvas can i make the y axis go up rather than down i am drawing a graph in canvas and struggling with the fact that the yaxis is backward the origin is in the topleft corner and increasing values go down rather than up00 x0 0y canvas instead does this of this 0y v 00 x0 i know that i can move the origin to the bottomleft corner using translatecontexttranslate0 canvasheightand i know that i can invert the yaxis using scalecontextscale1 1that seems to work except that it causes text to appear upsidedown is there a way to make canvass coordinates work the way i expect,['javascript'] +104106,accessing hibernate session from ejb using entitymanager is it possible to obtain the hibernate session object from the entitymanager i want to access some hibernate specific apii already tried something likeorghibernatesession hsession entitymanagerimpl emgetdelegate getsessionbut as soon as i invoke a method in the ejb i get a system exception occurred during an invocation on ejb with a nullpointerexception i use glassfish 301,['java'] +104112,cannot install pg gem on windows i have got 2 ruby versions 187 and 192 and postgresql 83 i cant install pg gem on any of them getting this errorcdevelopmentruby187binrubyexe extconfrbchecking for pg config yesnot recordedchecking for libpqfeh nocannot find the libpqfeh header extconfrb failed could not create makefile due to some reason probably lack ofnecessary libraries andor headers check the mkmflog file for moredetails you may need configuration optionsprovided configuration options withoptdir withoutoptdir withoptinclude withoutoptincludeoptdirinclude withoptlib withoutoptliboptdirlib withmakeprog withoutmakeprog srcdir curdir rubycdevelopmentruby187binruby withpg withoutpg withpgconfig withoutpgconfig withpgdir withoutpgdir withpginclude withoutpgincludepgdirinclude withpglib withoutpglibpgdirlibi know it is a common problem but i have not found any working solution yet oh i have added cprogram files x86postgresql83bin to my path,"['ruby-on-rails', 'ruby']" +104119,android how to add a custom button state for instance the default button has the following dependencies between its states and background imagesxml version10 encodingutf8selector xmlnsandroid item androidstate window focusedfalse androidstate enabledtrue androiddrawabledrawablebtn default normal item androidstate window focusedfalse androidstate enabledfalse androiddrawabledrawablebtn default normal thisable item androidstate pressedtrue androiddrawabledrawablebtn default pressed item androidstate focusedtrue androidstate enabledtrue androiddrawabledrawablebtn default selected item androidstate enabledtrue androiddrawabledrawablebtn default normal item androidstate focusedtrue androiddrawabledrawablebtn default normal thisable focused item androiddrawabledrawablebtn default normal thisable selectorhow can i define my own custom state smth like androidstate custom so then i could use it to dynamically change my button visual appearance,['android'] +104128,git workflow for a small team of developers and designers i am getting lost with git branching model and the workflow that i want to create for my team developers designerssuppose that the project is based on a mvc pattern so we have a structure similar to models controllers views developers works on the m c parts with some basicgenerated views rails django or cakephp app for exampleand designers works on the v parthow can i manage that developers works on mc and keep some basic crappy views and in the same time designers make sexy views based on controllers actions coded and added by developers progressively i tried to make it works with 3 branches master productionready dev ui but no idea how a designer working on ui branch can keep the code elsewhere than views updated an a working appthanks folks for help,['ruby-on-rails'] +104133,how do i close an android alertdialog i am developing a quiz and i need the user to answer all the questions before proceeding when the user has not answered all the questions i thisplay a simple alertdialog informing him or her the problem is whatever i do i cannot get the alertdialog to close why is not dialogcancel workingthis is the code alertdialogbuilder ad new alertdialogbuilderthis adsettitleunanswered questions adsetmessageyou have not answered all the questions adsetpositivebuttonok new dialoginterfaceonclicklistener public void onclickdialoginterface dialog int id dialogcancel adshow,['android'] +104146,is l m undefined behaviour i have started studying about c0x i came across the follow expression somewhereint l 1 m2l mi have no idea whether the second expression has well defined behavior or not so i am asking it hereis not it ub i am just eager to know,['c++'] +104152,waiaria javascript capability testing in the spirit of progressive enhancement i would like to do some aria capabilities testing to implement additional enhancements if they are supported by the browser i am not looking to detect screen readersai am looking to ensure that screen reader users will get the optimal experience given the tools that they are using for example if the arialive attribute is not supported then it may not be a good idea to implement endless scrollingi am aware that there is an additional concern that browsers may support these attributes but the screen reader may not since screen readers run transparently over browsers i am okay with that edge case being ignoredi have never heard of anyone doing anything like this is it as easy as testing for additional dom properties endowed by browsers do one of mark pilgrims other capability testing techniques work herethanks,['javascript'] +104171,counter in foreach loop in c working of foreachas i know foreach is a loop which iterates through a collection or array one by one starting from 0 index till the last item of the collectionso if i have and items in an arrayforeach var item in arr then in 1st iteration itemarr0then in 2nd itemarr1in last nth itemarrn1conclusion from working it seems that at each iteration it knows that which value to be taken from array or it knows the index of the item to be taken from arraynow my question how can i get index of an item without using a new variableforeach string item in mylist if item myitem get index of item break,['c#'] +104173,is there a standard net way to test if a sqlconnection string works possible duplicatehow to check if connection string is valid currently i am doing it like thisinternal bool checkconnection using sqlconnection testconn new sqlconnectionthisconnectionstring try testconnopen catch sqlexception return false return trueis there a better way to do this,['c#'] +104189,google map event bounds changed triggered multiple times when dragging i have a google map with markers i want my markers to be refreshed when the map is movedzoomedgoogle recommend to use the event bounds changed for that but when i move the map the event is triggered for each pixel that i move the map i want the map to be refreshed only when the user stopped moving the map ie when he released the mouse button after dragginghow can i do that thanks,['javascript'] +104190,minifying and combining files in net i am looking at implementing some performance optimization around my javascriptcss in particular looking to achieve the minification and combining of such i am developing in netc web applicationsi have a couple of options and looking for feedback on eachfirst one is this clever tool i came across chirpy which via visual studio combines minifies etc this is a visual studio add in but as i am in a team environment this tool isnt idealmy next option is to use an msbuild task to minify the files and also combine them maybe read from an xml file what needs to be combined while this works for minifying fine the concern i have is that i will have to maintain what must be combined which could be a headache3rd option is to use msbuild task just for the minifying and at runtime using some helper classes combine the files on a per page basis this would combine the files give it a name and add a version to itany other options i could consider my concern with the last option is that it may have performance issues as i would have to open the file from the local drive read its contents and then combine the files this is alot of processing at run time i was looking at something like squishit this minifies the files at run time but i would look at doing this at compile timeso any feedback on my approaches would be great if the 3rd option would not cause performance issues i am leading towards it,"['c#', 'javascript', 'css']" +104201,how can i write a generic anonymous method specifically i want to write thispublic funcilistt t selectelement list listfirstbut i get a syntax error at t cannot i have a generic anonymous method,['c#'] +104257,javascript onclick alert not working in chrome select namehistory idhistory option valuehistory 1 onclickalerth1history 1option option valuehistory 2 onclickalerth2history 2option option valueclearhistory onclickthisformsubmit clear historyoptionselectcould someone help me with this scripti am expecting that whenever the user clicks history 1 it will alert h1the script works in firefox and ie but not in chrome,['javascript'] +104281,why does a cc compiler need know the size of an array at compile time i know c standards preceding c99 as well as c says that the size of an array on stack must be known at compile time but why is that the array on stack is allocated at runtime so why does the size matter in compile time hope someone explain to me what a compiler will do with size at compile time thanks the example of such an array isvoid func here array is a local variable on stack its space is allocated at runtime why does the compiler need know its size at compiletime int array10,"['c++', 'c']" +104282,how to set isolation level on sqlcommandsqlconnection initialized with no transaction the following method is supposed to peroform a dirty read on an open connection there are no transactions where do i set isolationlevelpublic string dodirtyreadstring storedprocname sqlconnection connection using sqlcommand command new sqlcommandstoredprocname connection commandcommandtype commandtypestoredprocedure how to set isolationlevel to read uncommitted here commandexecutenonquery,['sql'] +104283,how to prevent multiple instances of an activity when it is launched with different intents i have come across a bug in my application when it is launched using the open button on the android market it seems that launching it from the market uses a different intent then launching it from the phones applications menu this is leading to multiple copies of the same activity being launched which are conflicting with each otherfor example if my app consists of the activities abc then the above issue can lead to a stack abcai tried using androidlaunchmodesingletask on all the activities to fix this problem but it has the unwanted sideeffect of clearing the activity stack to root whenever i hit home example abc home a when what i need is abc home abcis there a good way to prevent launching multiple activities of the same type without reseting to the root activity when using home,['android'] +104284,jquery select all rows containing certain text within a td in the row i have a table for which i am attempting to select all rows which have a td containing the text test and then hide the td with class msvbicon on all the matched rowsi intitally had the code below but this only hide the class on the last matched row tdcontainstestlastparentchildrenmsvbiconcssvisibilityhiddenso i tried this but its not working trhastdcontainstesteachfunction thischildrenmsvbiconcssvisibilityhidden simplified html look like thistabletbodytrtd classmsvbicontdtdtdtdtdtdtdtdtdtdtesttdtrtbodytable,['jquery'] +104293,read an image pixel by pixel in ruby i am trying to open an image file and store a list of pixels by color in a variablearray so i can output them one by oneimage type could be bmp jpg gif or png any of them is fine and only one needs to be supportedcolor output rgb or hexi have looked at a couple libraries rmagick quick magick mini magick etc and they all seem like overkill heroku also has some sort of difficulties with imagemagick and my tests do not run my application is in sinatraany suggestions,['ruby'] +104297,why is systemdrawingcolorgreen 0 1280 i thought it should be 02550 anyone know why,"['c#', '.net']" +104301,grouping into interval of 5 minutes within a time range i have some difficulties with mysql commands that i want to do select atimestamp name countbname from time a id b where auser buser and aid bid and bname john and atimestamp between 201016 1030 and 201016 110 group by atimestampthis is my current output statementtimestamp name countbname 201016 1032 john 2201016 103512 john 7201016 103634 john 1201016 103745 john 2201016 104826 john 8201016 105500 john 9201016 105808 john 2how do i group them into 5 minutes interval resultsi want my output to be liketimestamp name countbname 201016 1030 john 2201016 103500 john 10201016 1040 john 0201016 104500 john 8201016 1050 john 0201016 105500 john 11,"['mysql', 'sql']" +104328,jquery click remember old value while i click on select element i need to remember old value of the selected element this code works in ffchrome and opera instead of ie remember the old value choose select option and replace old value remembered with a selected optioncode documentreadyfunction viewtableorders tr td selectclickfunction oldcurrentpath thisval oldid thisattrtitle oldcurrentdate viewtableorders trvagon oldid td inputinput ver1val dataajax event on change path viewtableorders tr td selectchangefunction do something old value,"['javascript', 'jquery']" +104329,why does stl set have count when all elements are supposed to be unique i can understand that multiset has count for counting the number of occurrences of a value because elements can be repeated in multisetbut whats the point of having count in set when all the values are already unique,['c++'] +104331,does insertion to stl map invalidate other existing iterator i used stdmap in stl can i use iterator after some other element inserted to the map is it still valid,['c++'] +104334,videoview black flash before and after playing i have a videoview which i want to use to play a movieclip i use it like this to play it and it worksvideoview vv new videoviewthisvvsetvideouriuriparseandroidresourcecortex2hcbjrawintrosetcontentviewvstarthowever i see a black flash just before and after the movie clip the flash in itself is not a big problem but the blackness of it is the background is white so if the flash is white or if it thissapears it will be okay,"['java', 'android']" +104341,this is ugly and there has to be a better way to write it in jquery thisparentparentparentparentfindnamereply to idthats just stupid looking but its the best way i can think of writing it i tried parentsuntilli but that didnt work at all and i also tried parentsli and closestli isnt there something in jquery with the equivalent ofthisfirstparentthatmatchesthislifindnamereply to idif not i think ill try submitting it to the jquery corehere is my html long so i put it on pastebin working on getting jsfiddle in there,"['javascript', 'jquery']" +104346,how do i keep a label centered in winforms in winforms i am using a label to thisplay different messages like success failure etci would like to center that label in the center form i want a solution that will keep it centered whether there is just one word or a whole sentence in the label,"['c#', '.net']" +104347,when is static variable loaded in java runtime or compile time when is static variable loaded runtime or compile time can someone please explain iti would really appreciate the helpthank you,['java'] +104348,variable length array overhead in c looking at this question why does a cc compiler need know the size of an array at compile time it came to me that compiler implementers should have had some times to get their feet wet now it is part of c99 standard that is 10 years ago and provide efficient implementationshowever it still seems from the answers to be considered costlythis somehow surprises meof course i understand that a static offset is much better than a dynamic one in terms of performance and unlike one suggestion i would not actually have the compiler perform a heap allocation of the array since this would probably cost even more this has not been measured but i am still surprised at the supposed costif there is no vla in a function then there would not be any cost as far i can seeif there is one single vla then one can either put it before or after all the variables and therefore get a static offset for most of the stack frame or so it seems to me but i am not wellversed in stack managementthe question arise of multiple vlas of course and i was wondering if having a dedicated vla stack would work this means than a vla would be represented by a count and a pointer of known sizes therefore and the actual memory taken in an secondary stack only used for this purpose and thus really a stack toorephrasinghow vlas are implemented in gcc vc is the cost really that impressive end rephrasingit seems to me it can only be better than using say a vector even with present implementations since you do not incur the cost of a dynamic allocation at the cost of not being resizableeditthere is a partial response here however comparing vlas to traditional arrays seem unfair if we knew the size beforehand then we would not need a vla in the same question andreyt gave some pointers regarding the implementation but it is not as precise as i would like,['c++'] +104371,notation i cannot understand in quake source code c i was taking a look at the quake 1 gpl code and i came across various similar header files the purpose or use of which i do not seem to understand they look like tables of some sorts and are structured like this1 01 11 21 31 41 5without anything before or after them i understand they define something but i have never come across this kind of notation in cyou can read one of the header files i am referring to heremy question is what are thosethings the asm is actually giving me less problems than that stuff,['c'] +104398,how best to handle styles for nested h1s in html5 i am currently working on some html5 themes for a few of my websites and i keep running into problems with the way h1s can be used multiple times i cannot seem to predict in what elements the headings will show up but i do want to try and size them automatically based on their position in the domi was thinking about using something likeh1 fontsize 3em h2body header h1 fontsize 25em h3body header h2body header h1 fontsize 2em but obviously that is far from waterproof having an extra element around an h1 that does not really mean it is deeper in the page structure will tend to pick way too small sizes for example an unordered list with blocks that each have their own title will have something like section ul li header h1title of a blockh1 header content li ulsectionwhich makes the h1 appear much deeper than it actually is what are good ways to handle this,['css'] +104401,how do i keep common code shared between projects in c i am kinda new to c and i am trying to figure out a good solution for keeping common code somewhere that is used by several projectsfirst i tried keeping it in a cs file and add it to the projects that needs the code but this copies the file meaning if i do any changes to the common code it will not be reflected in the various projects using this codethen i tried creating a class library instead and reference the dll within the projects using the code first of all i cannot get this to work even though i am following the tutorials even when i reference the dll i still cannot use it somehow but even if this worked it still needs an extra dll to be bundled with my app for some common code and that is not what i wantis there any way to keep common code that is referenced without needing to ship a dll w,['c#'] +104407,application launcher text application name in two lines currently i am developing an application whose name is long so i would like to thisplay name in two line same as quick calendar and search people in an attached home screen widgetplease show me a way to implement this is it possible to do so,['android'] +104411,copy stdstack into an stdvector is the following code guaranteed by the standard to workassuming st is not emptyinclude vectorinclude stackint main extern stdstackint stdvectorint st int end sttop 1 int begin end stsize stdvectorint stack contentsbegin end,['c++'] +104415,why does net socketthisconnect take two minutes i am using nets socket class and i am using the following codesocketshutdownsocketshutdownbothsocketthisconnecttruethis then blocks for exactly two minutes i have specified true because i am going to reuse the socket immediately and reestablish the connection whether i have the shutdown call in there or not it blocks for two minutes the only thing i can do is pass false to thisconnect but i want to reuse the socketany ideasupdatei have read the codes i have set the dontlinger option it does not helpupdate 2i have added a network trace as per requesttrace 1 using the dontlinger optionsystemnetsockets verbose 0 4668 socket5009246socketinternetwork2systemnetsockets verbose 0 4668 exiting socket5009246socket systemnetsockets verbose 0 4668 socket5009246connecten2063562120systemnetsockets information 0 4668 socket5009246 created connection from abcden to wxyzmsystemnetsockets verbose 0 4668 exiting socket5009246connect systemnetsockets verbose 0 4668 socket5009246thisconnectsystemnetsockets verbose 0 4668 exiting socket5009246thisconnect trace 2 using the shutdownsocketshutdownbothsystemnetsockets verbose 0 0300 socket5009246socketinternetwork2systemnetsockets verbose 0 0300 exiting socket5009246socket systemnetsockets verbose 0 0300 socket5009246connectde2063562120systemnetsockets information 0 0300 socket5009246 created connection from abcde to wxyznsystemnetsockets verbose 0 0300 exiting socket5009246connect systemnetsockets verbose 0 0300 socket5009246shutdownboth2systemnetsockets verbose 0 0300 exiting socket5009246shutdown systemnetsockets verbose 0 0300 socket5009246thisconnectsystemnetsockets verbose 0 0300 exiting socket5009246thisconnect,['.net'] +104417,how to change the amount of building threads in xcode i am building a couple of c files in xcode that take a lot of memory to compile 1 gb file because i do this on my dual core laptop xcode uses 2 threads for building the two threads will eventually be building the files that take a lot of memory simultaneously so the system suffers memory starvation and the compilation grinds to a near halta sufficient solution for me would be to force xcode to use only one build thread does anybody know a way to change how many build threads xcode usesfor those who are interested the c files contain a sizable boostspiritqi parser,['c++'] +104427,how to add a method to enumeration in scala in java you couldpublic enum enum one public string method return 1 two public string method return 2 three public string method return 3 public abstract string methodhow do you do this in scala,['java'] +104428,submit pdf form fields to a http post request i have made a pdf form in adobe acrobat now i want to make a button that submits the form to a http post request i have searched for about 4 hours but i have not found an example to do thishere i read that it is possible to send the pdf form fields with a http submission but there is also no example giveni am looking for a javascript example that i can link to the submit button,['javascript'] +104434,jquery validate textarea maxlength bug i am using jqueryvalidate v 160 to validate my formsone of my database fields is limited to 10 chars i added a validation to the corresponding textarea like thisin the header of my page i addformvalidatevalidateinside my page i declareform methodpost classvalidate actionsave textarea namedescription minlength15 maxlength10 iddescription classrequiredtextarea input typesubmit valuesave formthe issue i am encountering is that jquery seems to count the number of chars involved in a new line differently as my databasewhen i type exactly 10 chars without new lines all goes well and the validation works if i type 10 chars with some new lines jquery allows the post to happen but my database refuses the insertupdate because the data is too bigany hints would be appreciated,['jquery'] +104438,is it best practice to always use accessor methods even when accessing local state consider the following classpublic class person private integer age standard accessorspublic integer getage return agepublic void setageinteger age thisage agepublic string getageastextstring if thisage 20 return twenty return unknowni just have 1 integer and 2 accessors if i want to create a utility method that returns the objects state as a string is it best practice to refer to the class variable as thisage or should i be using getageis there a best practice or is it down to developer thiscression,['java'] +104440,is i undefined behavior is i undefined behavior is it possible that the side effect of prefix increment happens after retrieving the incremented object for postfix increment to operate on that would seem strange to memy gut feeling says this is undefined in c03 and welldefined in c11 am i right,['c++'] +104460,use of typename keyword with template function parameters in c the typename keyword is needed so the compiler can thisambiguate between nested types and nested values in templates however there are certain situations where no ambiguity is possible such as when a derived class inherits from a nested class typetemplate class tclass derived public ttype here the typename keyword is not required and is in fact not even allowed this makes sense because the context removes the ambiguity here ttype must refer to a type since you obviously cannot inherit from a valuei would think the same thing would hold true for function template parameterstemplate class tvoid fooconst ttype vin this case the context makes it clear that ttype must refer to a type since a function parameter cannot be a value yet the compiler does not accept this it wants const typename ttype this seems inconsistent why does the language allow the implicit assumption of a nested type in the context of inheritance but not in the context of function parameters in both cases there can be no ambiguity so why the need for typename in one but not the other,['c++'] +104463,how can i find out why my thread is being stopped in aspnet our logs are reporting threadabortexceptions that are stopping our quartznet jobs at seemingly random intervals from what i understand this wouldnt normally be caused by something the thread itself is doing eg reading a file from an ftp server or executing a linq to entities query but rather because some outside process is telling the thread to stop furthermore the way the logs are being created leads me to believe that the entire web application is being restarted when we get these errors so i am guessing that the restart process is whats causing the thread to be aborted in the first placeso my question is how can i figure out why the serverapplication is being restarted are there logs somewhere that would give me details on each restart are there common causes for something like this that i should investigatethanks in advance for your helpediti just had a thiscussion with some coworkers and it sounds like iis automatically puts the application to sleep after a certain period of inactivity which might be part of the problem with some research i have found an idle timeout setting for worker threads in iis i think that when the application has not processed any requests for a certain amount of time it issues a shutdown command for some reason quartz does not shut down immediately but instead it waits for the next job to get fired and then the system detects that jobs thread and kills it while it is trying to runso i guess we need to come up with some way to gracefully finish any running jobs when the system wants to shut down and make quartz actually shut down when it is told to if it is not running any jobs does anybody have any experience wit this sort of issue,['asp.net'] +104466,how to get and cancel a pendingintent i have an alarmmanager which i am using to send notifications to the user at specific times since there are multiple alarms i have multiple pending intents that i am creating and giving a unique id however there are certain situations in which i will need to get all the pending intents and then cancel them so i can reset the alarms i have tried doing his and i still cant seem to get it right so i have a couple questionsis this how you would correctly get and cancel a pendingintentintent intent new intentcon appointmentnotificationrecieverclasspendingintent sender pendingintentgetbroadcastcon id intent pendingintentflag cancel currentalarmmanager am alarmmanager congetsystemservicecontextalarm serviceamcancelsenderdoes the intent need to exactly match that of the original pending intentextras and alldoes the pendingintent flag need to match that of the original pending intent,['android'] +104486,how do i create the first line in a new google spreadsheet using the api this is how i create the spreadsheetdocsservice client new docsservice ideaclientusessl clientsetoauthcredentials oauthparameters new oauthhmacsha1signer documentlistentry newentry new comgooglegdatadatadocsspreadsheetentry newentrysettitle new plaintextconstruct gideadbdocumentlistentry insertedentry clientinsert new url requestor id useremail newentrynow i want to write the first line in itbut unfortunately all api calls seam to base on the fact that there already is a first line for you insert namevaluepairs where the name is the headline i want to create guidehtmlcreatingtablerecordsany ideas how i can create the first line the one which defines the field names,['java'] +104491,c covariant return types utilizing generics is the code below the only way to implement covariant return typespublic abstract class baseapplicationt public t employee get set public class application baseapplicationexistingemployee public class newapplication baseapplicationnewemployee i want to be able to construct an application or a newapplication and have it return the appropriate employee type from the employee propertyvar app new applicationvar employee appemployee this should be of type existingemployeei believe this code works fine but it gets really nasty when i have several properties that require the same behaviorare there any other ways to implement this behavior generics or otherwise,['c#'] +104492,java library to find the mime type from file content i am searching for a java library which tells you the mime type by looking at the file contentbyte array i found this project using jmimemagic and it no longer supports newer file types eg ms word docx format as it is inactive now from 2006,['java'] +104495,the database file is locked with systemdatasqlite i am suddenly getting the following errors from sqlite after adding a new transactionthe database file is locked database is lockedhas anyone seen this i added an update transaction following some successful selectsinserts i cannot find anything different about this one,['c#'] +104502,how to group latitudelongitude points that are close to each other i have a database of user submitted latitudelongitude points and am trying to group close points together close is relative but for now it seems to 500 feetat first it seemed i could just group by rows that have the same latitudelongitude for the first 3 decimal places roughly a 300x300 box understanding that it changes as you move away from the equator however that method seems to be quite lacking closeness cannot be significantly different than the thistance each decimal place represents it does not take into account that two locations may have different digits in the 3rd or any decimal place but still be within the thistance that place represents 331239 and 331240i have also mulled over the situation where point a and point c are both close to point b but not each other should they be grouped together if so what happens when point d is close to point c and no other points should it be grouped as well certainly i have to determine the desired behavior but how would either be implementedcan anyone point me in the right direction as to how this can be done and what different methodsapproaches can be usedi feel a bit like i am missing something obviouscurrently the data is an a mysql database use by a php application however i am open to other storage methods if they are a key part in accomplishing this here,['sql'] +104520,how to calculate the square root of a float in c how can i calculate the square root of a float in c similar to coresqrt in xna,['c#'] +104528,do overridden methods inherit decorators in python just like the title says do overridden methods inherit decoratorsclass a memoized def funself arg return noneclass ba def funself arg computations return somethingso does bfun maintain the decorator,['python'] +104534,how to put arbitrary widgets into a gtkmenu how can any gtkwidget eg a progress bar be put into a gtkmenu as one of the menu items,['python'] +104544,programming from scratch what i would like to know is to start programming from scratch without any operating system and anything like itas i know windows and mac and almost anything even the dos is written in c c pascal etc so i think i should know one of these languages but for this i would need a program where i can write the code and also to compile it but without an operating system and programs how can be this done how could they do itbut this is not enough far how was c written in what so when i mean scratch i mean building everything from the basics maybe from 0101 right now i think this is the exact start point but how can i do it what should i have and where should i startthanks for every answer,"['c++', 'c']" +104558,how do i check an array for duplicates i have got an array a i would like to check if it contains duplicate values how would i do so,['ruby'] +104570,how to render an aspnet webform page from globalasax for one reason or another i am messing around with a minimalistic aspnet just for fun i have thisabled a lot of things and am attempting to reimplement things one thing i cannot quite figure out is how to render an aspnet pageaspx this is my progress so far globalasax protected virtual void application beginrequest object sender eventargs e htmltextwriter writernew htmltextwriterresponseoutput ifrequesturlabsolutepathsubstring0mathminrequesturlabsolutepathlength8static return let it just serve the static files else ifrequesturlabsolutepathtest1 test1 onew test1 oprocessrequestcontext orendercontrolwriter writerflush writerclose responseflush responsewritewritertostring else responsecontenttypetextplain responsewritehi world completerequest the static bit works as does the hi world i cannot get the test1 route to work though it reaches that point but all that is thisplayed is a black page i have a test1aspx page with this designer content page languagec inheritsnamespacetest1 doctype html public w3cdtd xhtml 10 stricten htmlhead titletest1titleheadbody form idform1 just testing if two forms works and such form form idform2 input typetext idtest1 formbodyhtmland it has almost no code behindjust an empty function which does not matter what am i doing wrong here,"['c#', 'asp.net']" +104571,whats the most efficient way of converting a 10 mb json response into an nsdictionary our app must thisplay a big chunk of data with minimal remote http requests so we have added an endpoint to our backend that provides all the necessary data as a single json response this results in 15mb compressed or roughly 8 mbs of uncompressed jsonformatted textnot much of a problem it downloads in 10 30 seconds and were using asihttprequest to write the whole response to thisknow comes the fun part after reading the uncompressed file into a memory mapped string we use stigs jsonframework to convert it into an nsdictionary this has worked very well for the rest of our app and the typical 2 kb json response for the rest of our api endpoints however deserializing these 8 mbs of data takes from a couple of seconds simulator to minutes 3g and 2nd gen ipod touchi am researching the best approach to read in all this datai would love to use binary plists served straight from the backend but we are using java and i have not found a proper library that fits our requirements and with such a tight deadline writing our own might not be the best ideaif it helps in any way the json string we are parsing is mostly an array of x items like so items key1 value1 key2 value2 key1 value1 key2 value2 key1 value1 key2 value2 key1 value1 key2 value2 key1 value1 key2 value2 key1 value1 key2 value2 what is the most efficient method to read in this 8 mb json formatted string into a nsdictionary in memory,"['iphone', 'objective-c']" +104575,iis 70 visual studio 2010 related configuration data for the page is invalid i have just switched to using iis7 in my visual studio 2010 project i have run vs 2010 as an administrator to do sowhen i navigate to the url for my page on the iis server i get this messagethe requested page cannot be accessed because the related configuration data for the page is invalidin the detailed error information it has thismodule iis web corenotification beginrequest handler not yet determined error code 0x80070021 config error this configuration section cannot be used at this path this happens when the section is locked at a parent level locking is either by default overridemodedefaultdeny or set explicitly by a location tag with overridemodedeny or the legacy allowoverridefalse config file cuserschris paynterdocumentsvisual studio 2010projectstypetesttypetestwebconfig then in the config source it shows line 48 in red47 validation validateintegratedmodeconfigurationfalse48 modules runallmanagedmodulesforallrequeststrue49 systemwebserveri am very new to aspnet and it would be much appreciated if anyone can guide me in the right direction to resolving thischeers,['asp.net'] +104593,warning x has different visibility default in y and hidden in z i am trying to make an iphone app that uses opencv plus another c libraryit seems to compile and link fine it actually worksis just i want to get rid of this ugly warningld warning stdvectorint stdallocatorint m insert aux gnu cxx normal iteratorint stdvectorint stdallocatorint int consthas different visibility default in usersnacho4ddocumentsprojectsiosiaropencv deviceliblibcxcoreacxdatastructso and hidden in usersnacho4ddocumentsprojectsiosiarbuildiarbuilddebugiphoneosiarbuildobjectsnormalarmv6combinationowhat does it mean how can i solve itjust in case this is the header of combination class from the library i mentionedcombinationhtypedef stdvectorint combitypedef stdvector combi allcombiclass combinationpublic void initconst int n const int m allcombiiterator begin allcombiiterator end allcombiconst iterator begin const allcombiconst iterator end constprivate void nestint nest int column int n1 int n2 int k allcombi resultprivate allcombi m datathanks in advanceignacio,"['iphone', 'c++']" +104600,cgpoint relative to view consider a screen point cgpoint and a view uiview which is somewhere inside the view hierarchy it can be a subview of other views how can you convert the point to a point relative to the views coordinates,"['iphone', 'ios']" +104609,android service please explain an android service how does it differ from an activity does it depend on an application state such as running in the foregroundbackground,['android'] +104615,how to make rounded textview in android i am developing an android applicationin my applicationi want to thisplay paragraph string in textviewso i want to rounded textview look like given bellow textview shout be center position of the screen same like given bellowhow is possiblethanks friends,['android'] +104617,why floating point value such as 314 are considered as double by default in msvc why do i need to put 314f instead of 314 to thisable all those warnings is there a coherent reason reason for this,['c++'] +104630,how can i use strip tags in regular ruby code nonrails i need to turn html into plain text there is a nice function that does that in actionviews sanitizehelper but i have trouble understanding how i can reference it and use it in a simple testrb filei would like to be able to call strip tagsblolb lol,"['html', 'ruby']" +104631,how to determine if an annotation is inside of mkpolygonview ios i am trying to calculate if a specific annotationlike the blue circle of the user location or a mkpinannotation is inside an mkpolygon layer on the mapviewany advice to achieve this,['ios'] +104647,what is the purpose of constraining a type to an interface what is the purpose of allowing the followingclass at where t ifoo private t t at t thist t etc how is this meaningfully different from just declaring a to require an ifoo wherever it needs oneclass a private ifoo foo aifoo foo thisfoo foo etc the only difference that i can see is that in the first case i am guaranteed both that at will always be instantiated with a t that implements ifoo and that all of the objects in a will be of the same base type but for the life of me i cannot figure out why i would need such a constraint,['c#'] +104659,rotate cgimage taken from video frame this is apples code from technical qa qa1702 for getting a uiimage from a video buffer unfortunately the image returned is rotated 90 degrees how do i edit this so that the image returned is correctly oriented uiimage imagefromsamplebuffercmsamplebufferref samplebuffer cvimagebufferref imagebuffer cmsamplebuffergetimagebuffersamplebuffer cvpixelbufferlockbaseaddressimagebuffer 0 void baseaddress cvpixelbuffergetbaseaddressimagebuffer size t bytesperrow cvpixelbuffergetbytesperrowimagebuffer size t width cvpixelbuffergetwidthimagebuffer size t height cvpixelbuffergetheightimagebuffer cgcolorspaceref colorspace cgcolorspacecreatedevicergb cgcontextref context cgbitmapcontextcreatebaseaddress width height 8 bytesperrow colorspace kcgbitmapbyteorder32little kcgimagealphapremultipliedfirst cgimageref quartzimage cgbitmapcontextcreateimagecontext cvpixelbufferunlockbaseaddressimagebuffer0 cgcontextreleasecontext cgcolorspacereleasecolorspace uiimage image uiimage imagewithcgimagequartzimage cgimagereleasequartzimage return image,['iphone'] +104664,some questions about structuring domaindrivendesign namespaces i have some general questions about framework design i am building an api for an iphone application in cnet framework 35 sql 2008 using linq i have followed the domaindrivendesign pattern in a book andhave the following folder structurecore dataaccessimpldomainimplcore is my core api library my dlls dataaccess contains the data access interfacesdataaccessimpl contains the repositories linq to the dbdomain contains most of my data types and properties impl contains my services ie accountservicecs emailservicecsnow as an exercise i have added a windows service to this projectand am attempting to call functionality from the dlls in this service my question is what layer should i be exposing to other applicationsand what should stay hidden should the service classes from the impl folder be what programmers see or the repositories from dataaccessimplor should i just lay it all out for the programmers to see as it looksnow this seems sort of confusing when i started reading about d i was assuming that the repositories would behidden and accessed by the service classes but i am finding i need to call functionality from both in my client have i designed this wrong my other question has do do with namespace naming when the windows servicecalls functionality from my core library i have to do my includes as suchusing companyproductproductcorecoredataaccessimpl using companyproductproductcorecoredomain using companyproductproductcorecoreimplthis seems wordy looking at microsofts dlls they seem to keep with a twotierconvention systemlinq systemtext etc having companyproductproductcorecoreimpl seems messy and does not really tell the programmer what this namespace does but itis what was suggested by the example i read is there a best practice here your suggestions and any examples are seriously appreciated thanks,['c#'] +104667,difference between function and function function fun1function fun1what is the difference between these,['php'] +104692,command line tool for finding basic javascript syntax errors are there any commandline linux tools that can catch basic syntax errors and compile time errors in my javascript files even if said javascript files are written for use in a web browseri typically code my javascript at the same time i am coding my server side code in say ruby or perl it would save me significant time if i could partially test my client side javascript the same way i test my server side ruby and perl on the command line typically from within emacs i am not expecting to catch run time javascript errors on the server just basic things like a mistyped variable name or an extra bracket somewhere or a runaway string things that could be found before actually attempting to execute the codewhat i do now to testdebug javascript is the usual cycle of visit web app in browser check firebug or other console back to emacs to fix errors repeat doing that is certainly unavoidable for more complex types of errors eg involving user and network interaction but a garden variety syntax error could be caught and dealt with more quickly on the command line without loading up the browseri have looked a bit into some server side platforms like nodejs but they all seemed geared toward writing and executing server side code so all of the client side specific bits in my code would presumably make it barf i also found an emacs mode for javascript repl but it does not seemed designed to do just basic compile checks it basically loads the whole page via an external graphical browser and lets you monkey with it which is precisely what i am trying to avoid,['javascript'] +104702,how can i access my trackpad in c i am pretty bored this weekendi have decided to build a morse code application where i can use my trackpad to tap morse code in and have my app sound it outi told you i was bored dis there some defacto way to access a trackpad in c i mean using pressure graphs thanks,['c#'] +104707,ruby efficient way to get multiple hash keys for a given value whats the most efficient way to get all the hash keys from a given valuemy hash a b cbbi want to give the hash bb as an input value and get all they keys bc back as an arrayreturns only one keymy hashindexbb returns only bthis works but seems inefficientmy hashselectkv v bb mapi i0 returns b and ci have read all the docs i feel like there is something obvious i am missingthanksupdatei ended up switching the keys and values for the hash creation and going with an array for the values this is a more efficient solution see below for best ways to do value look ups if you have tonew structure my hash abc,['ruby'] +104708,is there an online temporary code bin for c js bin jsfiddle clones is there a website that offers simple temporary code bins for c syntax highlighting is a plus i have found nice ones for javascript jsfiddle,['c#'] +104712,cocoa drag and drop any file type i am trying to create a drag and drop region that accepts any file type and will upload it to a server using asihttprequest i looked at the following example that apple providesbut it only covers dealing with the dragging and dropping of images how can i set up my drag and drop operations to deal with any file typethanks,['objective-c'] +104728,consuming google channel api in c the official documentation does not mention the support but i am wondering if it is possible to hook up a client program instead of javascript to use the channel api i am currently using the basic polling technique from a windows app having the channel api would improve responsiveness and reduce load quite a biti suppose as a ugly hack i could render a hidden webbrowser object in the background and have javascript running in that then feed off of that is there a better solution,['c#'] +104730,table is marked as crashed and should be repaired i am getting this error in wordpress phpmyadmin145 table db namewp posts is marked as crashed and should be repaired when i login to phpmyadmin it says wp posts is in usemy website is currently down because of thisi googled this problem but i do not see the repair button on phpmyadmin please let me know how to fix this i am not sure where to issue php command please advise my proficiency with php is very basic,['mysql'] +104740,getting first weekday in a month with strtotime i am trying to figure out the first wednesday of a given month using strtotime but the first wednesday argument fails whenever the first wednesday happens to fall on the 1stfor a more general illustration of this problem see the following code and resultmon strtotimedecember 2010 first mondaytue strtotimedecember 2010 first tuesdaywed strtotimedecember 2010 first wednesdaythu strtotimedecember 2010 first thursdayfri strtotimedecember 2010 first fridaysat strtotimedecember 2010 first saturdaysun strtotimedecember 2010 first sundayecho strftimemdy mon brecho strftimemdy tue brecho strftimemdy wed brecho strftimemdy thu brecho strftimemdy fri brecho strftimemdy sat brecho strftimemdy sun brresults in120610120710120810120210120310120410120510notice something should not one day of the week coincide with the 1st of the month but it never does and instead the second instance of the day on the 8th is always returnedanyone have an explanation for this,['php'] +104741,c abstract factory using templates i am trying to create an abstract factory template for multiple abstract factories in c and came up with thisdefine crtdbg map allocinclude crtdbghinclude mapinclude stdiohclass basepublic virtual base virtual bool get 0class deriveda public basepublic bool get return true class derivedb public basepublic bool get return false template class tclass creatorpublic virtual creator virtual t create 0template class tclass derivedcreator public creatortpublic t create return new t template class t class keyclass factorypublic void registerkey id creatort fn functionmapid fn t createkey id return functionmapidcreate factory stdmapkey creatortiterator i functionmapbegin while i functionmapend delete isecond i private stdmapkey creatort functionmapint mainint argc char argv crtsetdbgflag crtsetdbgflag crtdbg report flag crtdbg leak check df register factorybase char temp tempregisterda creatorbasenew derivedcreatorderiveda tempregisterdb creatorbasenew derivedcreatorderivedb pointer to base interface base pbase 0 create and call pbase tempcreateda printfderiveda un pbaseget delete pbase create and call pbase tempcreatedb printfderivedb un pbaseget delete pbase return 0it compiles and runs fine with no memory leaks win32 crtdbg but i do not know if this is really the correct way to do an abstract factory template tempregisterda creatorbasenew derivedcreatorderivedai am also wondering about the line above i am confused why i have to cast i do not understand templates very well but i would assume that it should work fine considering that both the template class and the actual class are derived that code actually works fine as shown above and even deletes fine with no memory leaks i just do not feel entirely comfortable with iti have not been able to find any real examples of template classes except for this from mangos wow emulator but i do not think i can use that method in my project because i plan on using dlls at some point in my project and it uses crtp which is against my requirement for runtime polymorphism,['c++'] +104750,developing chat api like that of stackoverflow how to begin developing chat api like the one stackoverflow uses if it is open source where can i find it if not can anyone guide me how to build a similar chat api,['php'] +104760,file get contents when url does not exist i am using file get contents to access a url file get contentsif the url is not real it return this error message how can i get it to error gracefully so that i know that the page does not exist and act accordingly without thisplaying this error messagefile get contents functionfilegetcontents failed to open stream http request failed http10 404 not found in myphppagephp on line 3for example in zend you can say if requestissuccessfulclient new zend http clientclientseturirequest clientrequestif requestissuccessful do stuff with the result,['php'] +104764,what are the implications of calling numpys c api functions from multiple threads this is risky business and i understand the global interpreter lock to be a formidable foe of parallelism however if i am using numpys c api specifically the pyarray data macro on a numpy array are there potential consequences to invoking it from multiple concurrent threadsnote that i will still own the gil and not be releasing it with numpys threading support also even if numpy makes no guarantees about thread safety but pyarray data is threadsafe in practice that is good enough for mei am running python 266 with numpy 130 on linux,['python'] +104767,why does a stream thispose when its writer is thisposed consider the following codeusing var ms new memorystream usingvar writer binarywriterms writerwritesomething writerflush assertthatmslength 0 throws objectthisposedexceptionon the one hand a thisposable object should thispose of it is resources i get that but on the other hand the object did not create and does not own this resource it was provided calling code should take responsibility for it no i cannot think of any other situations like this but is it a consistent pattern in the framework for any class receiving thisposable objects to thispose of them on its own thispose,['c#'] +104784,which abbreviations should we use for python variable names in generally i am using the standard naming stated in pep8 for variables likedelete projectsconnect serverhowever sometimes i cannot find any good name and the name just extend to a long oneproject name to be deleted i could use pr nm del but this makes the code unreadable i am really suffering finding good variable names for functions whenever i begin to write a new function i just spent time to find a good variable name is there any standard for choosing certain abbreviations for well known variable names like deleteprojectconfiguration etc how do you choose short but good and readable variable names this question might be not depend directly to python but as different programming languages uses different variable names formatting i thought i limit this question to python only,['python'] +104786,is there any need to learn javascript dom methods for web development now we have jquery et al with the availability of jquery is there any need to learn direct dom manipulation with javascript in order to be a professional web developersite builderetcthis probably could be asked with prototype mootools etc too but i am not familiar with them apart from their names,"['javascript', 'jquery']" +104787,convert wstring to string encoded in utf8 i need to convert between wstring and string i figured out that using codecvt facet should do the trick but it does not seem to work for utf8 localemy idea is that when i read utf8 encoded file to chars one utf8 character is read into two normal characters which is how utf8 works i would like to create this utf8 string from wstring representation for library i use in my codedoes anybody know how to do iti already tried this locale mylocalecs czutf8 mbstate t mystate wstring mywstring la34a12aa const codecvtwchar tcharmbstate t myfacet use facetcodecvtwchar tcharmbstate t mylocale codecvtwchar tcharmbstate tresult myresult size t length mywstringlength char pstr new char length1 const wchar t pwc char pc translate characters myresult myfacetout mystate mywstringc str mywstringc strlength1 pwc pstr pstrlength1 pc if myresult codecvtwchar tcharmbstate tok cout translation successful pstr endl else cout failed endl return 0which returns failed for cs czutf8 locale and works correctly for cs cziso88592 locale,['c++'] +104796,android animate rotate i did some digging in android code and saw the use of in the indeterminate progress bar after trying to create my own drawable with this taganimatedrotate xmlnsandroid androiddrawabledrawablespinner pia androidpivotx50 androidpivoty50 androidframescount12 androidframeduration100 i get an errorno resource identifier found for attribute frameduration in package android which means that frameduration is a private attribute is there a way to use this animaterotate featuremy task is to replace the systems default indeterminate progress bar i would like to do it with as little code as possible just change few attributes if possibleusing the progressbar view settingandroidindeterminateonlytrueandroidindeterminatebehaviorcycleandroidindeterminateduration3500androidindeterminatedrawabledrawablepia sivuvatorand point drawablepia sivuvator to that object wouldve make my task as elegant as they come but i am stuck on those private attributeshelp,['android'] +104814,is it possible to abort a task like aborting a thread threadabort method we could abort a thread like thisthread thread new threadsomemethodthreadabortbut can i abort a task in net 40 in the same way not by cancellation mechanism i want to kill the task immediately,['c#'] +104820,activitynotfoundexception when different packages targetclass in preferencescreen the applications default package is exampleappand the target activitys package is exampleappabccalling startactivity for exampleappabctheactivity in java code just works but specifying it on preferencexml does not workpreferencescreen androidkeykey androidtitlestringtitle intent androidactionandroidintentactionmain androidtargetpackageexampleappabc androidtargetclasstheactivitypreferencescreeni tried androidtargetclassexampleappabctheactivity but it does not work toois it impossible to start an activity of nondefault package in preference,['android'] +104823,need to convert text field to varchar temporarily so that i can pass to a stored procedure i am using a sql 20 databasei am working with a database in which i cannot change the types on the tables or the stored procedures one of the stored procedures i need to call expects a parameter of text i can get to the text field but i am unable to figure out who to store that in a variable or any other way to pass it into the stored procedureif i try and create a text variable sql would not let me if i convert it to varchar i only get the first character from the text field any tricks to get around this much appreciated thank you,['sql'] +104834,how do i create a new object in javascript based on a typestring how do i create a new object in javascript based on a variable typestring containing the name of the objectnow i have with more tools coming the list will get longerfunction gettoolname switchname case selecttool return new selecttool break case linetool return new linetool break case blurtool return new blurtool break case pointertool default return new pointertool break and defined my tools likepointertoolprototype new toolpointertoolprototypeconstructor pointertoolfunction pointertool thisname pointertoolpointertoolprototypeclick functionx y infoyou clicked at x yi would like to get ride of the growing switch statement it seems wrong,['javascript'] +104836,spawn processes but only 5 at a time i am working off a queue with filenames each file has to be processed by a external binary this works fine but it only processes one file at a time is it possible two spawn a number of processes parallelqueuestring queue new queuestringqueueenqueue1mp3queueenqueue2mp3queueenqueue3mp3queueenqueue10mp3while queuecount 0 string file queuedequeue process p new process pstartinfofilename binaryexe pstartinfoarguments file pstartinfouseshellexecute false pstartinfocreatenowindow true pstartinforedirectstandardoutput true pstart pwaitforexitupdate i like the solution from alex le spawn processes but only 5 at a time but is it possible to wait for the child processes to exit as suggested by ben voigtedit 1 i need to check for pexitcode 0 to make some database updates,['c#'] +104840,ruby operator method calls vs normal method calls i am wondering why calls to operator methods do not require a dot or rather why cannot normal methods be called without a dotexampleclass foo def object puts this will work end def plusobject puts this would not endend f foonewf anything this will workf plus anything nomethoderror undefined method plus for mainobject,['ruby'] +104850,how can i make routes from a rails 3 engine available to the host application i have a rails 3 application with several engines containing additional functionality each engine is a separate service that customers can purchase access toi am however having a problem with routes from the engines that are not readily available to the controllers and viewscontrollerclass classroomscontroller applicationcontroller respond to html def index respond withclassrooms companyclassroomsall end def new respond withclassroom companyclassroomsbuild end endappviewsclassroomsnewhtmlhaml form for classroom do f fsubmitconfigroutesrb in enginemyenginenameengineroutesdraw do resources classroomsendconfigroutesrb in appseabedapplicationroutesdraw do mount myenginenameengine engine endlibmy engine namerb in enginemodule myenginename class engine railsengine endendattempting to go to classroomsnew results in nomethoderror in classroomsnewshowing appviewsclassrooms formhtmlhaml where line 1 raised undefined method hash for classrooms path for module0x0104cff0f8and attempting to call classrooms path from any other view results in the same errori can however call myenginenameengineroutesurl helpersclassrooms path and get it working i am thinking i might have defined the routes wrong but cannot find another way that workstried running the app with both passenger standalone and apache module and webrick rails server using latest rails from git 7c920631ec3b314cfaa3a60d265de40cba3e8135,['ruby-on-rails'] +104884,how to deploy web apps in the agile way what is the best set of practices and tools that could support me in the continuous deployment of an web applicationwe should be able to deploy effortless several times a day it is a ruby on rails 3 app we use git and github,['ruby-on-rails'] +104895,refresh uiview for drawrect is there a way to refresh a uiview which will subsequently call drawrectediti am doing view setneedsthisplay however it does not appear to be working or at least my nslog in drawrect is not thisplayingedit2please see comments of selected answer for the gory details number one tip make sure it is property linked,['iphone'] +104903,creating a two dimensional array in objectivec whats the easiest way to declare a two dimensional array in objectivec i am reading an matrix of numbers from a text file from a website and want to take the data and place it into a 3x3 matrixonce i read the url into a string i create an nsarray and use the componentsseparatedbystring method to strip of the carriage return line feed and create each individual row i then get the count of the number of lines in the new array to get the individual values at each row this will give mw an array with a string of characters not a row of three individual values i just need to be able to take these values and create a two dimensional array,['objective-c'] +104972,printing on roll paper i am using c with winforms i am trying to print bills on a paper roll the width of the paper is 3in but the length of the paper is dynamic its a roll paper the length depends on how many items are there in the list eg in a purchase if there are 100 items sold then it will be quite long roll while for a single item purchased it would be of small lengthwhen i print the report after the end job printer eject the last page more than i need it eject paper as long as a4 size i want to print the required lines then stop printing i use a roll of paper not a4 or a3 and an epson lq300 ii printerto be more specific printing is always done to pagesized units if i set the page to be 3in x 8in then i always end up with a printout that is a multiple of 8in long if i have a 9in bill to print i end up with a 16in printout wasting 7in of paper how can i print with the last page being only as long as it needs to behere is the codeprivate void printdoc printpageobject sender printpageeventargs e font printfont new fontcourier new 12 int y 15 egraphicsdrawstringa line printfont brushesblack 0 y y y 20 egraphicsdrawstring line printfont brushesblack 0 y y y 25 egraphicsdrawstring line printfont brushesblack 0 y y y 35 egraphicsdrawstring line printfont brushesblack 0 y y y 45,"['c#', '.net']" +104978,ccli performance compared to native c good morningi am writting a spell checker which for the case is performancecritical that being and since i am planning to connect to a db and making the gui using c i wrote an editthistance calculation routine in c and compiled to a dll which i use in c using dllimport the problem is that i think though i am possibly wrong that marshalling words one by one from string to char is causing a lot of overhead that being i thought about using ccli so that i can work with the string type in net directly my question is then how does ccli performance compares to native c code for heavy mathematical calculations and array accessthank you very much,['c#'] +104981,generate only tests from existing model controllers i have a rails3 app that is based on someone elses work for some reason they decided not to supply the tests with the app which i am finding frustratingwhat i want to be able to do is scaffold the tests for all the existing controllers and models so i can get a head start on creating the tests myself in testunit i do not want to recreate the models or controllers just create the testsi am new to rails and have hunted about for the rake command that might do this but all with no luck so far any advice direction most appreciated,['ruby-on-rails'] +104992,listunsubscribe in email header howto i am trying to add a listunsubscribe header to my email that is being sent so far i had not any luck trying to do sowhat i have got so farvar mailmessage new mailmessage subject newslettersubject body newsletterhtml isbodyhtml true sender new mailaddresenderaddress mailmessagetoaddsubscriberemail mailmessagereplytolistaddsenderaddress mailmessageheadersaddlistunsubscribe unsubscribeurlthe unsubscribeurl is something like wexamplecomunlistid8822772727when i sent the email everything works fine except for the listunsubscribe option which is not shown in any mail clientany assistance would be welcome updatethis is the whole code i use for sending the email var mailmessage new mailmessage subject newslettersubject body newsletterhtml isbodyhtml true sender new mailaddresenderaddress mailmessagetoaddsubscriberemail mailmessagereplytolistaddsenderaddress mailmessageheadersaddlistunsubscribe stringformat0 mailmessageheadersencoding encodingdefault var smtpclient new smtpclient smtpclientsendmailmessageupdate 2after a little research i got the header into the mailmessage when i sent an email i can see the following headers listunsubscribe mimeversion 10from to replyto date 8 feb 2011 095022 0100subject test met plaatjecontenttype texthtml charsetusasciicontenttransferencoding quotedprintable but when i open the email in any client i cannot see the unsubscribe button in the client am i doing something else wrong,"['c#', 'asp.net']" +104996,how to use profile guided optimizations in g also can anyone point me to a good tutorial on the subject i cannot find any,['c++'] +104999,c treemindmap gui i am trying to research some gui technology for c where i can thisplay a tree view opposed to the standard one providedessentially i want to have the gui draw a tree of data as if you were going to draw a binary tree on a piece of paper or something then making each of the nodes clickableif this isnt available does anyone know of something where i could have a mindmap type gui which shows links between elements and those are clickablei can guess people will say make one yourself in which case i give up already thats too advanced for me and as i am on a work placement i dont think i would be granted the time to make it as there are more pressing issues to get working first like actually making the programme workthank you,['c#'] +105015,how to check if a string contains a specific word in php considera how are youif a contains are echo truesuppose i have the code above what is the correct way to write the statement if a contains are,['php'] +105072,is it possible to register an iphone app name i was wondering if it is possible to register an iphone app name before the app goes on the app storeexamplea developer comes up with a really clever name for a iphone gamehe wants to register the name before he programs the game so that no one else comes up with the same name,['iphone'] +105077,responseredirect and thread was being aborted error i had this error thread was being aborted this afternoon in my error logthe code that caused this error isresponseredirectloginaspx trueif i change the bool value to false the error log becomes empty and this error stops coming again but the program stops workingif i keep it as such i am getting this error like nuisancei want to know the alternative for using responseredirect passing true as the value for the endresponse parameter,['asp.net'] +105090,c difference between first and find so i know that find is only a listt method whereas first is an extension for any ienumerablet i also know that first will return the first element if no parameter is passed whereas find will throw an exception lastly i know that first will throw an exception if the element is not found whereas find will return the types default valuei hope that clears up confusion about what i am actually asking this is a computer science question and deals with these methods at the computational level i have come to understand that ienumerablet extensions do not always operate as one would expect under the hood so heres the q and i mean from a close to the metal standpoint what is the difference between find and firstheres some code to provide basic assumptions to operate under for this questionvar l new listint 1 2 3 4 5 var x lfirsti i 3var y lfindi i 3is there any actual computational difference between how first and find thiscover their values in the code abovenote let us ignore things like asparallel and asqueryable for now,['c#'] +105096,do i need to check for sql injection even on validated inputs this is about a classifieds websitei use php and mysql to insert records into a dbi have a html form and users must fill in this form to proceedbelow is the form inputs and the validation made on each input javascriptname only letters allowedtel only numbers allowedemail special emailregexp matchheadline no special characters allowed all else is fine by special characters i mean etc max length 35 charstext same as headline just no limit on lengthprice only numbers allowedi do mysql real escape string on the headline and text but nothing elsemy question is simply is this enoughi have no other security measures whatsoeverupdatevar alphaexp azazas var numexp dd0d 020var num only 09var emailexp wazaz09azaz0924var textexp swaw3gmivar headlineexp sdazaza,"['php', 'javascript', 'mysql', 'html']" +105099,is there an equivalent of the lock statement for readerwriterlockslim i like the shortcut in c of lockmylock do stuff is there an equivalent for readwrite locks specifically readerwriterlockslim right now i use the following custom method which i think works but is kind of annoying because i have to pass in my action as an anonymous function and i would prefer to use a standard locking mechanism if possible void bool dowithwritelockreaderwriterlockslim rwlock int timeout action fn bool holdinglock false try if rwlocktryenterwritelocktimeout holdinglock true fn finally if holdinglock rwlockexitwritelock return holdinglock,"['c#', '.net']" +105103,can we use ojdbc14jar with oracel11g and jdk15 i believe there are different flavors of this questions already asked but i wanted to confirm this again as we are very close to our release and wanted to validate with the communitywe have been using oracle10g and java 15 for quite some time now with ojdbc14jar i know that ojbc14jar is catered towards java 14 but thankfully we never saw any issue while using this with 15 version another reason for not moving to ojbc5 was the fact that we did not see ojdbc5jar in the installed oracle 10g at allwe have upgraded our db to be 11g now and i did not see ojdbc14jar does this mean we have to move to ojdbc5jarwe are willing to make the change but can the people who made the switch confirm if they saw any issue when they changed the jdbc driver to ojdbc5jar from ojdbc14jarrelated to it it would be good if someone can elaborate little more about dms flavors of this jar and how it is to be used,['java'] +105106,how to restrict a program to a single instance i have a console application in c and i want to restrict my application to run only one instance at a time how do i achieve this in c,['c#'] +105109,php gmails messages contain invalid html and random jargon i am creating an emailbased cms with php and i am required to use gmail as the email service the script is insanely simple for now and the only problem i am having is dealing with gmails email syntaxi was expecting something a bit more manageable like this when getting an emailuasfasfasfu u stylefontstyle italicasdfafu ustylefontstyle italic fontweight boldasfsafu asfasf a hrefhttpasfasfafsasfasfabr lorem ipsum dolor sit amet consectetur adipiscing elit praesent sodales mauris quis nisl pellentesque eleifend sed convallis turpis quis turpis malesuada feugiat fusce sed metus non orci convallis congue integer egestas vulputate ipsum sed fringilla velit elementum scelerisque pellentesque convallis metus sit amet enim faucibus adipiscingbut i am getting this instead duck and coveruasfasfasf uu style3dfontstyle italic asdfaf a0uu style3dfontstyle italic fontweight bold asfsaf uasfasf a href3dhttpasfasfafsasfasfadivbrdivdivmeta httpequiv3dcontenttype content3dtexthtml charset3dutf8span class3dapplestylespan style3dfontfamily arial helvetica sans fontsize 11px p style3dtextalign justify fontsize 11px lineheight 14px margintop 0px marginright 0px marginbottom 14px marginleft 0px paddingtop 0px paddingright 0px paddingbottom 0px paddingleft 0px lorem ipsum dolor sit amet consectetur adipiscing elit praesent sodales mauris quis nisl pellentesque eleifend sed convallis turpis quis turpis malesuada feugiat fusce sed metus non orci convallis congue integer egestas vulputate ipsum sed fringilla velit elementum scelerisque pellentesque convallis metus sit amet enim faucibus adipiscingpspani tried tidy but it cannot deal with gmails links and line breaks the breaks are just at the end which completely mess up tidy and the links are sometimes at random i think like this a href3dhttpasfasfafsasfasfa with those n right in the middlehow would i train tidy to deal with this sort of blasphemous html and output something i can pipe directly into a div inside of a websitethanks,['php'] +105112,scrollheight property in firefox i am working on a function to detect whether text inside of a div element would overflow in this regard i have a function working in both chrome and ie that compares the elements scrollheight to the clientheight attributeshowever in firefox both attributes as well as offsetheight always report the same number which happens to be the height of the div elementi do get accurate results from the scrollheight property if i add overflowauto to the div style but thisplaying the scrollbar is not an acceptable solution for the project i am working onany suggestions,"['javascript', 'html']" +105120,objectivec releasing a property declared in a category i have a category on an existing class that adds a property and a few methods to the classinterface aclass acategory nsstring apropertyproperty nonatomic retain nsstring apropertyendin the implementation file i want to release this property when the object is deallocated however if i declare dealloc in this class it will override the dealloc from the original class from what i understand what then is the proper way to release this aproperty when the object is deallocatedimplementation aclass acategorysynthesize aproperty voiddealloc aproperty release this will skip the original dealloc method from what i understand super deallocend,['objective-c'] +105135,is there a performance hit of replacing local variables with arguments in javascript is there any performance hit for writing a function such that local var statements are replaced with arguments examplefunction howmanymatcharr pattern ignored i l total l arrlength total 0 for i 0 i l i if patterntestarri total return totalsome advantagessmaller minified size no var statementsless programmer time spent trying to use as few vars as possibleall local vars defined in one placeand thisadvantagesarguments can be altered in unexpected ways see belowless clear in body that vars are localconfusing to see arguments that do not do anythingif someone unknowingly removes them your code writes to globalsstill it might be an easy way for a minifier to automatically squeeze out more bitsupdate a big thisadvantage not mentioned so far if a function is called with and parameters the first and items in arguments will be binded to the first and identifiers in the argument list see the last bullet in 1018 consider thisfunction procestuffignoredi j k use ijk to loop do stuff with the arguments pseudoarrayin the above example if you called procestuffstuff1 stuff2 setting i and j would overwrite arguments0 and arguments1 respectively,['javascript'] +105140,what is attr accessor in ruby i am having a hard time understanding attr accessor in ruby can someone explain this to me i have done tons of google searches i just cannot understand it fully,['ruby'] +105187,php curl https i found this function that does an awesome job imho tip how get web page using curl get a web file html xhtml xml image etc from a url return an array containing the http server response header fields and content function get web page url options array curlopt returntransfer true return web page curlopt header false do not return headers curlopt followlocation true follow redirects curlopt encoding handle all encodings curlopt useragent spider who am i curlopt autoreferer true set referer on redirect curlopt connecttimeout 120 timeout on connect curlopt timeout 120 timeout on response curlopt maxredirs 10 stop after 10 redirects ch curl init url curl setopt array ch options content curl exec ch err curl errno ch errmsg curl error ch header curl getinfo ch curl close ch headererrno err headererrmsg errmsg headercontent content return headerthe only problem i have is that it does not work for https anny ideas what i need to do to make this work for https thanks,['php'] +105208,how to print in ios 42 i want to integrate the print functionality in my appthe document i want to print will be in doc or txt formati am not very experienced in iphone development yet so finding it difficult to implement it by following the apple documentationif someone could help me by posting some sample code will be a great help,['iphone'] +105209,download a file and redirector alternative users fill out a form with a valid form they click to download a file i would like to be able to redirect them to another page eg page2html and initiate a download i cannot initiate download on page2html because most browsers will flag security warnings if a download link is not directly clicked onhow is something like this accomplished using javascript or jquery obviously the following does not work but it is meant for illustrative purposesdocumentgetelementbyidfonclick function windowlocation downloadexe windowlocation page2html,"['javascript', 'jquery']" +105210,in c which is faster 2 i 1 or i 1 1 i realize that the answer is probably hardware specific but i am curious if there was a more general intuition that i am missingi asked this question given the answer now i am wondering if i should alter my approach in general to use i 11 instead of 2i 1,['c++'] +105221,is there an offline geocoding framework library or database for ios is there an offline geocoding framework library or database for ios a place to get the data fromi need to be able to geocode street addresses in cities worldwide or at least in the united states into latitude and longitude for sunrise and sunset calculationsthe information must be in a format that will work on iphone os either a database file or written in cobjectivec,['iphone'] +105224,linq to sql any with multiple conditions i am trying to use any in an if statement like soifthisdbusersanyx xuserid userid do stuffis there a way i can put multiple conditions inside of the any for example something likeifthisdbusersanyx xuserid userid and xusername username do stuffor is there a better way to go about this,['c#'] +105228,ipad flipclock with core animation i am trying to make the flipclock animation i find this tutorial very interestingbut i still cannot make it work if someone did it and could share is experience or even the code source that will be really nicethanksps if you have other tutorial link please share them,"['iphone', 'objective-c']" +105230,android maps array index out of bound exception i have a task to show 458 markers to show in android maps and to avoid performance related issues i update the data on map using an asynctask instance here is a short scenario of what i do i fetch the latitudelongitude of 458 locations around uki run the loop and as per android blog tutorial i add them in itemizedoverlay classafter every 50th iteration i call publishprogress method to place 50 markers in mapafter the 50th iteration the flow goes into onprogressupdate via publishprogress and here is my code of onprogressupdate method mapoverlays mapviewgetoverlays this line was called in asyc tasks constructor hello overlay is an instance of itemizedoverlaymapoverlaysaddhellooverlaymapviewgetcontroller also called in constructorcontrollersetzoom12controlleranimatetocenterpointcontrollersetcentercenterpointthis code throws arrayindexoutofboundexception and the logcat does not show any of the class from my module here is the logcat dump if it elaborates my problem1207 113448644 errorandroidruntime508 javalangarrayindexoutofboundsexception1207 113448644 errorandroidruntime508 at comgoogleandroidmapsitemizedoverlaygetindextodrawitemizedoverlayjava21207 113448644 errorandroidruntime508 at comgoogleandroidmapsitemizedoverlaydrawitemizedoverlayjava2401207 113448644 errorandroidruntime508 at comgoogleandroidmapsoverlaydrawoverlayjava1791207 113448644 errorandroidruntime508 at comgoogleandroidmapsoverlaybundledrawoverlaybundlejava421207 113448644 errorandroidruntime508 at comgoogleandroidmapsmapviewondrawmapviewjava4761207 113448644 errorandroidruntime508 at androidviewviewdrawviewjava65351207 113448644 errorandroidruntime508 at androidviewviewgroupdrawchildviewgroupjava15311207 113448644 errorandroidruntime508 at androidviewviewgroupthispatchdrawviewgroupjava12581207 113448644 errorandroidruntime508 at androidviewviewgroupdrawchildviewgroupjava15291207 113448644 errorandroidruntime508 at androidviewviewgroupthispatchdrawviewgroupjava12581207 113448644 errorandroidruntime508 at androidviewviewdrawviewjava65381207 113448644 errorandroidruntime508 at androidwidgetframelayoutdrawframelayoutjava3521207 113448644 errorandroidruntime508 at androidviewviewgroupdrawchildviewgroupjava15311207 113448644 errorandroidruntime508 at androidviewviewgroupthispatchdrawviewgroupjava12581207 113448644 errorandroidruntime508 at androidviewviewgroupdrawchildviewgroupjava15291207 113448644 errorandroidruntime508 at androidviewviewgroupthispatchdrawviewgroupjava12581207 113448644 errorandroidruntime508 at androidviewviewdrawviewjava65381207 113448644 errorandroidruntime508 at androidwidgetframelayoutdrawframelayoutjava3521207 113448644 errorandroidruntime508 at comandroidinternalpolicyimplphonewindowdecorviewdrawphonewindowjava18301207 113448644 errorandroidruntime508 at androidviewviewrootdrawviewrootjava13491207 113448644 errorandroidruntime508 at androidviewviewrootperformtraversalsviewrootjava141207 113448644 errorandroidruntime508 at androidviewviewroothandlemessageviewrootjava16331207 113448644 errorandroidruntime508 at androidoshandlerthispatchmessagehandlerjava991207 113448644 errorandroidruntime508 at androidoslooperlooplooperjava1231207 113448644 errorandroidruntime508 at androidappactivitythreadmainactivitythreadjava43631207 113448644 errorandroidruntime508 at javalangreflectmethodinvokenativenative method1207 113448644 errorandroidruntime508 at javalangreflectmethodinvokemethodjava5211207 113448644 errorandroidruntime508 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava8601207 113448644 errorandroidruntime508 at comandroidinternaloszygoteinitmainzygoteinitjava6181207 113448644 errorandroidruntime508 at dalviksystemnativestartmainnative methodps i have tested the application with relatively smaller 10 and relatively larger 150 iterations instead of 50 but the application throws same error,['android'] +105247,center content in div with css how to center content in div horizontally and vertically i will be happy if someone give me small sample code with css,['css'] +105251,how to check if a record exists using jpa i want to know whether a given record is present in a database or not so far i have achieved this by writing a jpa query and the running it by getsingleresult method this would throw a noresultexception if the record with the given parameter does not exist of course it is not a must for the record to exist so it is the normal behaviour sometimes that is why i asked to myself is it neccessary to throw an exception which i have to handle by a catch block as far as i know the cost of exception handling is quite big so i am not very satisfied with this solution also i do not even need the object i only need to know it is existence in the dbis there a better way to check whether an object exist or not eg using getresultlist and checking it is size maybe,['java'] +105265,how to insert into stdmap is there a std iterator i could use to insert elements into stdmap using a std algorithm for example stdcopy i need a container to link one object to a string and i thought about using stdmap is there a better container forgot to say items needs to be sorted,['c++'] +105271,recommended way to format numbers in a locale aware way lets assume we have one millionin english it should be formatted as 10 in german it should be 10thanks,"['java', 'android']" +105302,empty mutable array how do i empty my mutable array thanksmason soizaweb design derby,"['iphone', 'objective-c']" +105312,gtk filechooser to open both files and folders how do i get my filechooser to be able to select both files and folders when the open button on the filechooser dialog is hit i want to squeeze the ability to open files and filders in just one filechooser i am using gtk and python,['python'] +105314,exception while parsing wsdl description resource path location typewsi a problem occured while running the wsi wsdl conformance checkorgeclipsewstwsiinternalanalyzerwsianalyzerexception null nested exception is javalangnullpointerexceptionthe wsdlanalyzer was unable to validate the given wsdl filechangedelementswsdl wstestwebcontentwsdl line 1 wsdl problemupdatenetbeans gives this errorcvcelt1 cannot find the declaration of element wsdldefinitions 7the part of wsdlxml version10 encodingutf8 standalonenowsdldefinitions xmlnssoap xmlnstns xmlnswsdl xmlnsxsd namex targetnamespace,['java'] +105315,add google analytics to github wiki pages i have a couple of github projects that i want to be able to track the traffic to i have done this in the past by adding google analytics tracking code to each wiki page however the github wiki upgrade in september broke this and i do not seem to be able to add javascript code to my wiki pages anymorea couple of random other points1 i am aware that github probably blocked js on the wiki for security reasons2 i know github provides its own very basic traffic graph but i would like all the power of gais there any way for me to restore google analytics tracking to my github wiki if not is there an alternative,['javascript'] +105351,what does this s regex mean in javascript what does s mean in regexwhile cur null if cur nodetype 3 s testcur nodevalue element removechild cur else if cur nodetype 1 cleanwhitespace cur,['javascript'] +105399,where to get full source code for rtjar i am searching the source code for rtjar for oracle jrejdk 6 update 22the srczip which is included with the delivery does not contain all sources for examples the sun eg sunreflectreflection packages are missingwhere can i get a complete srczip,['java'] +105400,is it possible to convert a winform to a webform in net i did not think it was possible but i was just talking to a coworker who said she had done it before is she pulling my chain,"['.net', 'asp.net']" +105406,can gnuplot take different arguments at run time maybe with python i have 500 files to plot and i want to do this automatically i have the gnuplot scriptthat does the plotting with the file name hard coded i would like to have a loop that calls gnuplot every iteration with a different file name but it does not seem that gnuplot support command line arguments is there an easy way i also installed the gnuplotpython package in case i can do it via a python scripthowever i could not find the api so it is a bit difficult to figure outthank you,['python'] +105408,mock httpcontextcurrent in test init method i am trying to add unit testing to an aspnet mvc application i have built in my unit tests i use the following codetestmethodpublic void indexaction should return view var controller new membershipcontroller controllersetfakecontrollercontexttestuser with the following helpers to mock the controller contextpublic static class fakecontrollercontext public static httpcontextbase fakehttpcontextstring username var context new mockhttpcontextbase contextsetupgetctx ctxrequestisauthenticatedreturnsstringisnulloremptyusername if stringisnulloremptyusername contextsetupgetctx ctxuseridentityreturnsfakeidentitycreateidentityusername return contextobject public static void setfakecontrollercontextthis controller controller string username null var httpcontext fakehttpcontextusername var context new controllercontextnew requestcontexthttpcontext new routedata controller controllercontrollercontext context this test class inherits from a base class which has the followingtestinitializepublic void init inside this method it calls a library which i have no control over which tries to run the following codehttpcontextcurrentuseridentityisauthenticatednow you can probably see the problem i have set the fake httpcontext against the controller but not in this base init method unit testing mocking is very new to me so i want to make sure i get this right what is the correct way for me to mock out the httpcontext so that it is shared across my controller and any libraries which are called in my init method,['c#'] +105421,any idea how to update python pip on a windows box pip install upgrade pip does not work because the windows fs is brain damaged and would not let you delete an open filei have tried setting my environment to the virtualenv that i want to update and then running from a different pip but that fails withjm epythonjmcpython26scriptspip install upgrade pipdownloadingunpacking pip running setuppy egg info for package pip warning no previouslyincluded files matching txt found under directory docs build no previouslyincluded directories found matching docs build sourcesinstalling collected packages pip found existing installation pip 071 uninstalling pip successfully uninstalled pip running setuppy install for pip warning no previouslyincluded files matching txt found under directory docs build no previouslyincluded directories found matching docs build sources installing pipscriptpy script to cpython26scripts installing pipexe script to cpython26scripts installing pipexemanifest script to cpython26scripts installing pip26scriptpy script to cpython26scripts installing pip26exe script to cpython26scripts installing pip26exemanifest script to cpython26scriptsexceptiontraceback most recent call last file cpython26libsitepackagespip071py26eggpipbasecommandpy line 120 in main file cpython26libsitepackagespip071py26eggpipcommandsinstallpy line 165 in run file cpython26libsitepackagespip071py26eggpipreqpy line 1251 in install file cpython26libsitepackagespip071py26eggpipreqpy line 466 in commit uninstall file cpython26libsitepackagespip071py26eggpipreqpy line 1549 in commit file cpython26libshutilpy line 216 in rmtree rmtreefullname ignore errors onerror file cpython26libshutilpy line 216 in rmtree rmtreefullname ignore errors onerror file cpython26libshutilpy line 221 in rmtree onerrorosremove fullname sysexc info file cpython26libshutilpy line 219 in rmtree osremovefullnamewindowserror error 5 access is denied cusersmarkappdatalocaltemppipgvsoveuninstallpython26scriptspipexestoring complete log in cusersmarkappdataroamingpippiplogjm epythonjmdir cusersmarkappdatalocaltemppipgvsoveuninstallpython26scripts volume in drive c has no label volume serial number is 74e4fe9f directory of cusersmarkappdatalocaltemppipgvsoveuninstallpython26scripts12072010 1132 am dir 12072010 1132 am dir 05142010 0554 pm 7168 pipexe 1 files 7168 bytes 2 dirs 22824603648 bytes freejm epythonjmdel cusersmarkappdatalocaltemppipgvsoveuninstallpython26scriptspipexei am hoping someone else has figured out a way around this its no problem on linux,['python'] +105445,how to run a php script asynchronously i am creating a php script that will be run via the command line as part of this script there are times where i might need to spawnfork a different script that could take a long time to complete i do not want to block the original script from completing if i were doing this with javascript i could run ajax requests in the background that is essentially what i am trying to do here i do not need to know when the forks complete just that they start and complete themselveshow can i run these php scripts asynchronouslyforeach lotsofitems as item if itemneedsextrahelp start some asynchronous process here and pass it item,['php'] +105446,tool for detecting javascripts events do you know a tool or plugin for mozilla or iexplorer that shows javascripts fired events while an user is navigating and interacting with a web pagethanks,['javascript'] +105450,html purifying in php i am writing php class which have to remove all potentially dangerous elements or bogus html tag such as bad links from html source usually i would use html purifier library or similar librarybut selfwritten code is required in this project there are two conditionsit can not have more than 3kb codeit should execute really fasti wrote something that could do the job but i do not know if it is safe enough to usemy question isis there any way to test it properlyor maybe someone has quick small and tested library like this,"['php', 'javascript', 'html']" +105458,what are the wontfix bugs on gnulinux and how to work around them both linux and the gnu userspace glibc seem to have a number of wontfix bugs ie bugs which the responsible parties have declared their unwillingness to fix despite clearly violating the requirements of iso c andor posix but i am unaware of any resource for programmers which lists such bugs and suggestions for working around themhere are a few that come to mindthe linux udp select bug select and related interfaces flag a udp socket file descriptor ready for reading as soon as a packet has been received without confirming the checksum on subsequent recvreadetc if the checksum was invalid the call will block working around this requires always setting udp sockets to nonblocking mode and dealing with the ewouldblock condition if i remember correctly maradns was the first notable project affected by this bug and the first to complain unsuccessfully to have it fixed note as pointed out by martin v lawis apparently this bug has since been fixed workarounds are probably only necessary if you need to support really outdated versions of linuxthe printf family in the gnu c library wrongly treats arguments to s as multibyte character strings instead of byte strings when a field precision as in 3s is specified potentially causing truncated output i know of no workaround except replacing the whole printf subsystem or simply not using the printf family of functions with nonmultibytecharacter byte strings but this can be problematic if you want to process legacycodepage strings using snprintf while in a utf8 localewrong errno result codes for certain syscalls cannot remember which ones right off usually these are easy enough to check for if you just read the gnulinux man pages and compare them to the standard i cannot find the references for this and perhaps i am mistaken the closest i can find is the issue of enotsup and eopnotsup having the same value see pdtr 24715what are some more bugs and workarounds we can add to this list my goals in asking this question areto build a more complete list of such bugs so that both new and experienced programmers can quickly become aware of potential issues that could arise when running an intendedtobeportable program on gnulinuxto leverage the so collective brain to think up clever and unobtrusive standard workarounds for as many such bugs as possible instead of everyone having to invent their own workarounds after getting stung and possibly doing so in suboptimal ugly or hackish ways or worse yet in ways that break support for moreconformant systems,['c'] +105459,get mavenproject from just the pomxml pom parser is it possible to get an instance of orgapachemavenprojectmavenproject or some other object form of the pom from just the pomxml filethanks in advance,['java'] +105469,how do i get nokogiri to add the right xml encoding i have created a xml doc with nokogiri nokogirixmldocumentthe header of my file is xml version10 but i would expect to have xml version10 encodingutf8 is there any options i could use so the encoding appears,['ruby'] +105507,why should i use foreach instead of for int i0 i it seems like the cool way of looping in c and java is to use foreach instead of c style for loops is there a reason why i should prefer this style over the c style i am particularly interested in these two cases but please address as many cases as you need to explain your pointsi wish to perform an operation on each item in a listi am searching for an item in a list and wish to exit when that item is found,"['c#', 'java', '.net']" +105516,do not change link color when a link is clicked i have a link in an html pagea hreffoofooathe color of the link text is originally blue when the link is clicked the color of the link text changes to red first and then changes back to blue i want to the color of the link text not to change when user clicks on it how can i make it happeni tried aactive color nonein css but got no luckand i do not want to use this in cssaactive color blue because the original color of the link text can be some other than bluethanksedit the page is thisplayed on iphone browser and i want to make aactive to keep the original link text color,"['html', 'css']" +105520,how to change a ruby on rails application name i have a ruby on rails application that was created usingrails new old name d mysqlnow i want to change the application name to be new namejust changing the application folder name will not be enough because the database name for example also has to be changed from old name development to new name development i wonder if there are other places in the automatically generated files that needs changingis there any built in command for changing the application name,['ruby-on-rails'] +105545,which python async library would be best suited for my code asyncore twisted i have a program i am working on that will be reading from two network sources simultaneously i wanted to try out an asynchronous approach rather than use threading this has lead me to wonder which library to usei have come up with some simple example code that kind of demonstrates what my program will be doingimport snifferdef first for station in sniffersniff wifi logstationmacdef second for station in sniffersniff ethernet logstationmacfirstsecondthe two sniffer methods look somewhat like thisdef sniff wifiself while true yield mac addressthe while true loop obviously makes them blockingi want to use asyncore for this as it is part of the standard library no 3rd party dependencies are a bonus however that does not mean i would not use it if you recommend i docan i achieve what i am trying to do with asyncore if so could you show me how to convert my example code to asyncore code do you know of any good asyncore tutorials,['python'] +105561,how to thisable an android button i have created a layout that contains two buttons next and previous in between the buttons i am generating some dynamic views so when i first launch the application i want to thisable the previous button since there wont be any previous views i also want to thisable the next button when there are not more views to thisplay is there anyway to thisable the buttons,['android'] +105605,javascriptdom how to remove all events of a dom object just question is there any way to completely remove all events of an object eg a divedit i am adding per divaddeventlistenerclickeventreturnerfalse an eventfunction eventreturner return function dosomething edit2 i found a way which is working but not possible to use for my casevar returnedfunctionfunction addit var div documentgetelementbyiddiv returnedfunction eventreturner divaddeventlistenerclickreturnedfunctionfalse you have to take here a var and not the direct call to eventreturner because the function address must be the same and it would change if the function was called againfunction removeit var div documentgetelementbyiddiv divremoveeventlistenerclickreturnedfunctionfalse,['javascript'] +105615,retrieving array of ids in mongoid how do you retrieve an array of ids in mongoidarrid1id2userwhereidarryou can do this easily if you are retrieving another attributeuserwherenicknameinkkllbut i am wondering how to do this in mongoid this should be a very simple and common operation,['ruby'] +105622,creating new instance from class with constructor parameter i have situation where my java class needs to create a ton of certain kind of objects i would like to give the name of the class of the objects that are created as a parameter in addition i need to give the created class a parameter in its constructor i have something likeclass compressor class ccos public compressorclass ccos thisccos ccos public int getcompressedsizebyte array outputstream os new bytearrayoutputstream the following does not work because ccos would need os as its constructors parameter outputstream cos outputstream ccosnewinstance do you have any ideas how i could remedy thiseditthis is part of a research project where we need to evaluate the performance of multiple different compressors with multiple different inputs class ccos is a compressed outputstream either from javas standard library apache compress commons or lzmajavacurrently i have the following which appears to work fine other ideas are welcomeoutputstream os new bytearrayoutputstreamoutputstream compressedout outputstream ccosgetconstructoroutputstreamclassnewinstanceosfinal inputstream sourcein new bytearrayinputstreamarray,['java'] +105630,decimalformatformatdouble in different threads i have to print many formatted decimal values in many threads in parallel to format the decimal values i use a javatextdecimalformat configured by a patterni am aware of the warning from the java doc of decimalformat decimal formats are generally not synchronized it is recommended to create separate format instances for each thread if multiple threads access a format concurrently it must be synchronized externallybut i donat know if this warning applies to my scenarioi configure the javatextdecimalformat once when the application starts and store the formatter in a final field after that i only use the formatdouble methodthe reason why i want to do this is i donat want to lose performance by creating a new decimalformat instance every time i need to print a formatted numberi looked at the decimalformatformatdouble code and it looks to be thread safe but i am not surecould you please confirm that the usage of decimalformatformatdouble is eventually thread safe when not changing the configuration of the formatter or explain why it is not,['java'] +105644,prevent anchor behaviour when i want to prevent default behaviour of anchor tag im using a hrefjavascriptvoid0linkawhich is the most effective solution,['javascript'] +105648,transparent background on winforms i wanted to make my windows form transparent so removed the borders controls and everything leaving only the forms box then i tried to the backcolor and transparencykey to transparent but it didnt work out as backcolor would not accept transparent color after searching around i found this at msdnsetstylecontrolstylesuserpaint truesetstylecontrolstylesoptimizeddoublebuffer truesetstylecontrolstylessupportstransparentbackcolor truethisbackcolor colortransparentthistransparencykey backcolorunhappyly it did not work either i still get the grey or any other selected color backgroundall i wanted to do is to have the windows form transparent so i could use a background image that would act as if it was my windows formi searched around here and saw many topics in regards opacity which is not what i am looking for and also saw some in regards this method i was trying but have not found an answer yethope anyone can light my pathupdateimage removed as problem is solved,['c#'] +105654,guava iterablesfrequencyiterable predicate is there really no method that determines the number of elements that satisfy a predicate in an iterablewas i right to do thisreturn listsnewarraylistiterablesfilteriterable predicatesizeif so what is the reason that there is no methoditerablefrequencyiterablet predicatetcheers,['java'] +105658,jquery if my css visibilityhidden how can i appear my elements in my css i have set some elements visibiliyhidden how can i show themi have done it before with opacity but i have some bug in ievar i 0myselectioneachfunctioni thisdelayi 100 myselectionlengthanimate opacity 1 queuetrue duration10 easingquarteasein how can i do if i want controll visibility with jquery instead of opacitythank you,['jquery'] +105659,contact api storing contact as an invisible contact how to make it visible i am trying to add a contact in android using getcontentresolverfirst i created an arraylistarraylistcontentprovideroperation ops new arraylistcontentprovideroperationthen populated the array list byint rawcontactinsertindex opssizeopsaddcontentprovideroperationnewinsertrawcontactscontent uri withvaluecontactscontractrawcontactsaccount nameaccountname buildopsaddcontentprovideroperationnewinsertcontactscontractdatacontent uri withvaluebackreferencecontactscontractdataraw contact idrawcontactinsertindex withvaluecontactscontractdatamimetypecontactscontractcommondatakindsstructurednamecontent item type withvaluecontactscontractcommondatakindsstructurednamethisplay name name buildand finally in a try blockgetcontentresolverapplybatchcontactscontractauthority opswhen i excecute this i am not getting any error or exception but the contact does not appear in the android contacts when i retrieve the invisible contacts i could find this contact can any one figure out what is going wrong,['android'] +105671,should i write equals methods in jpa entities i want to check if entity is in a collection member onetomany or manytomany of another entityif entity2getentities1containsentity1,['java'] +105672,unit testing in xcode 4 i have managed to set up unit tests for my library in xcode 4 i have performed builds with tests that i know will pass and fail ie stasserttrueyes and stasserttrueno just to make sure it is working i am using the default apple sentest libraries following this documenthowever when my tests are running i am getting this error in the build log an internal error occurred when handling command output ideactivitylogsectionrecorder endmarker unrecognized selector sent to instance 0x20310b580to be clear it is not affecting the running of the tests at all just the output into the build window all the tests run each time so i can tell a pass fail by looking to see if the build succeeds or failshowever when my tests fail i cannot find out which one fails because the output seems to stop when it gets to that errordoes anyone have experience with unit testing xcode 4 this error,"['iphone', 'ios']" +105678,getting the index of a particular item in array i want to retrieve the index of an array but i know only a part of the actual value in the array for example i am storing author name in the array dynamically say author xyz i want to find the index of array item containing something like author as i do not know the value part how to do this,['c#'] +105700,jaxrs implementation of linkelement expansion while reading documentation of google data api and atlassian rest api i found interesting functionality link or title element expansion i would like to implement this functionality in my java project of web service server for our is but i cannot find any proper solution or advices for implementation my project is quite big with many services so i need some robust and most automated solution i was thinking about how to implement it like an extension for resteasy and jaxb but it seems to be very complicateddo you know some opensource projects which implements this functionality or any advices which could help me,['java'] +105706,print array without brackets and commas i have previously written a hangman game for my java class in school i am now currently porting it to android and have met a few problems the original java program wrote all outputs to the console now i have to somehow beutify the output so that it fits the layout that i have designedhow do i print an array without the brackets and commas the array contains slashes and gets replaced one by one when the correct letter is guessedi am using the usual tostring function of the arraylist class and my output is formatted like a n d r o i d i want it to simply print out the array as a single stringthis problems seems so simple although i have not been able to find a solution to it not by using the search function eitheri fill the array using this bit of codeforint i 0isecretwordlengthi hiddenarrayaddsecretwordsubstringii1 publicarrayadd and i print it like thisfinal textview currentwordview textview findviewbyidridcurrentword currentwordviewsettextpublicarraytostringany help would be appreciated,"['java', 'android']" +105707,how can i find the amount of seconds passed from the midnight with java i need a function that gives me how many seconds passed from the midnight i am currently using systemcurrenttimemillis but it gives me the unix like timestampit would be a bonus for me if i could get the milliseconds too,['java'] +105712,html5 canvas on android phones redraw and highlight issues i am having a redraw issue when you are scrolling the canvas will not redraw until you release your touch the problem with that is i depend on ontouchmove to move my character around so until the touch is release the canvas will not redrawanother problem is when ever the canvas is touched it is focus or activated it develops a focus ring around it i tried setting both the focus and active pseudos borders and outlines to nothing also i saw drawfocusring for the context of the canvas however that did not seem to resolve the issuecurrently i tested on android stock browser 22 mytouch 3g,"['javascript', 'android']" +105722,exporting data from sqlite 3 i need a simple way to export data from an sqlite database of multiple tables then import them into another databasehere is my scenario i have 5 tables a b c d eeach table has a primary key as the first column called id i want a unix command that will dump only the data in the row from the primary key in a format that can be imported into another database i know i can do a sqlite3 db dump grep insertbut that gives me all data in the table i am not a database expert and i am trying to do this with all unix commands in which i can write a shell script rather than writing c code to do it because that is what people are telling me that is the easiest way i just refuse to write c code to accomplish a task that possible can be done in 45 statements from the command lineany suggestions,['sql'] +105729,rails 23x equivalent of rails3 optional route parameters in rails 3 i can do something like thismatch pagesection to some controllerpageand both page and pagesome section will map to some controllerpageis there an equivalent of this in rails 23x i cannot seem to find iti am currently using two separate route methods like somappage page action pagemappage section pagesection action page,['ruby-on-rails'] +105734,how can i manage building library projects that produce both a static lib and a dll i have got a large visual studio solution with 50 projects there are configurations for staticdebug staticrelease debug and release some libraries are needed in both dll and static lib form to get them we rebuild the solution with a different configuration the configuration manager window is used to setup which projects need to build in which flavours static lib dynamic dll or boththis can by quite tricky to manage and it is a bit annoying to have to build the solution multiple times and select the configurations in the right order static versions need building before nonstatic versionsi am wondering instead of this current scheme might it be simpler to manage if for the projects i needed to produce both a static lib and dynamc dll i created two projects egcorelibcoredlli could either make both of these projects reference all the same files and build them twice or i am wondering would it be possible to build corelib and then get coredll to link it to generate the dlli guess my question is do you have any advice on how to structure your projects in this kind of situationthanks,['c++'] +105750,determine if a string is absolute url or relative url in java given a string how do i determine if it is absolute url or relative url in java i tried the following codeprivate boolean isabsoluteurlstring urlstring boolean result false try url url new urlurlstring string protocol urlgetprotocol if protocol null protocoltrimlength 0 result true catch malformedurlexception e return false return result the problem is that all relative urls are throwing the malformedurlexception as there is no protocol defined example wgooglecom and questionsask,['java'] +105755,web service that returns any http status code you specify for api testing purposes a few months ago i remember reading about a useful little web service somebody put together for api testing purposes basically you just did a call like this egand the server would respond with a 405 method not allowedit was basically just a handy little utility you could use during development if you just wanted to interact with a live url that behaved the way you specifiedmy googlefu is weak today and i cannot for the life of me remember what it was called i am sure i could whip something like this up myself in about as long as its taken me to type this question but if anybody remembers what i am talking about perhaps you can sharemany thanksedit posted something i whipped up real quick but i would still be interested in the answer if someone knows what i am referring to,['python'] +105769,what does the html acronym span stands for i guess that div might actually stand for division since it creates a division in the document by separating content before and after it am i rightbut span is a little bit more obscure on its meaning i made some googling on this and found some interesting options super passive analyzer node space node simple plain access nodedoes anyone know the right acronym for span,['html'] +105774,linking error libxml2dylib at xcode 325 sdk 42 i am trying to connect to twitter using oauth library the library needs libxml2dylib to be added when adding this to sdk 41 or less the project build successfully but when i use that with xcode 325 and sdk 42 i got errors about missing headersi just add the libxml2dylib to frameworks then from target configuration i add sdkrootusrincludelibxml2 to the header search pathi got error libxmlxmlreaderh no such file or directorythe twitter oauth library i am trying to add is twitteroauth heres a tutorial where you can see that the src project it has works correctly on sdk 41 and not even compile at sdk42 what i miss,['iphone'] +105777,how can i get a resource content from a static context i want to read strings from an xml file before i do much of anything else like settext on widgets so how can i do that without an activity object to call getresources on,"['java', 'android']" +105785,php convert datetime to seconds i have a datetime value in mysql 20101208 161212that i would like to get the seconds to that date using phpso basically a php equivalent of mysql time to sectimediff20101208 161212now,"['php', 'mysql']" +105799,why does post not honor charset but an ajax request does tomcat 6 i have a tomcat based application that needs to submit a form capable of handling utf8 characters when submitted via ajax the data is returned correctly from getparameter in utf8 when submitting via form post the data is returned from getparameter in iso88591 i used fiddler and have determined the only difference in the requests is that charsetutf8 is appended to the end of the contenttype header in the ajax call as expected since i send the content type explicitly contenttype from ajaxapplicationxwformurlencoded charsetutf8contenttype from formapplicationxwformurlencodedi have the following settingsajax post outputs chars correctlyajax type post url blah async false contenttype applicationxwformurlencoded charsetutf8 data data success functiondata form post outputs chars in iso form idleadform enctypeapplicationxwformurlencoded charsetutf8 methodpost acceptcharsetutf8 actionapathxml declarationxml version10 encodingutf8doctypedoctype html public w3cdtd xhtml 10 transitionalen meta tagmeta httpequivcontenttype contenttexthtml charsetutf8jvm parametersdfileencodingutf8i have also tried using requestsetcharacterencodingutf8 but it seems as if tomcat simply ignores it i am not using the requestdumper valve from what i have read post data encoding is mostly dependent on the page encoding where the form is as far as i can tell my page is correctly encoded in utf8the sample jsp from this page works correctly it simply uses setcharacterencodingutf8 and echos the data you post so to summarize the post request does not send the charset as being utf8 despite the page being in utf8 the form parameters specifying utf8 the xml declaration or anything else i have spent the better part of three days on this and am running out of ideas can anyone help me,['java'] +105800,thumbnail of a pdf page java how can i generate a thumbnail image of pages in a pdf document using java,['java'] +105802,converting base64 image to multipartformdata and sending with jquery i have a base64 encoded jpg in javascript which i would like to post to a server which is expecting multipartformdataspecifically to the pivotal tracker api which has an example curl call like so curl h xtrackertoken token x post f filedatapathtofile idstoriesstory idattachmentsi have basic xml only calls to their api working fine using ajax like soajax url type post contenttype applicationxml datatype xml beforesend functionxhr xhrsetrequestheaderxtrackertoken key data storystory typefeaturestory typenamefire torpedoesnamestory success function alertput completed but i am stumped on how to take my base64 encoded jpg and send it as if i had uploaded a file in a formany ideas,"['javascript', 'jquery']" +105849,does my aspnet application stop executing if i overwrite the dlls assume that my aspnet application is making 4 separate database calls if after the 2nd call i overwrite the dlls in bin folder does it stop the application from continuing its processing hence resulting in the 3rd and 4th database calls being failedany advice would be greatly appreciated mosh,['asp.net'] +105865,finding value in unordered map i am using boost unordered map i have a key value pair for each entry how could i determine whether a particular value exist in the map i do not want to create another unordered map which stored the value as key and key as value thanks,['c++'] +105892,difference between onload and ready can you list the difference between onload and documentreadyfunction functions in the using jquery,"['javascript', 'jquery']" +105899,using antlr 33 i am trying to get started with antlr and c but i am finding it extraordinarily difficult due to the lack of documentationtutorials i have found a couple halfhearted tutorials for older versions but it seems there have been some major changes to the api sincecan anyone give me a simple example of how to create a grammar and use it in a short programi have finally managed to get my grammar file compiling into a lexer and parser and i can get those compiled and running in visual studio after having to recompile the antlr source because the c binaries seem to be out of date too not to mention the source does not compile without some fixes but i still have no idea what to do with my parserlexer classes supposedly it can produce an ast given some inputand then i should be able to do something fancy with that,['c#'] +105900,why does not ansi c have namespaces having namespaces seems like nobrainer for most languages but as far as i can tell ansi c does not support it why not any plans to include it in a future standard,['c'] +105912,how do you initialize a map which takes a struct as value i am using a map as an associative array of ids value where the value is a struct defining the objectinclude mapstruct category int id stdstring namestdmapint category categoriesint main categories1 1 first category categories2 2 second categorythe above code compiles with g but with the following warning warning extended initializer lists only available with stdc0x or stdgnu0xi have read various questionsanswers here about struct initialization but i am still a bit confused i have a series of related questionsi could add the compiler option stdc0x and be done with the warning but still be none the wiser about the underlying problem wouldnt things break if i add a method to the category structwhat would the best way be to initialize this pod struct category in a more c03 compliant waybasically i am not yet sure of the consequences of doing things one way rather than another way this kind of associative array where the key is the id of an object is easy with php and i am still learning about the proper way to do it in c is there anything i should pay attention to in the context of the code aboveeditthe following questions are related but i did not understand the answers when i first read themc initialize anonymous structc initializing a struct with an array as a memberinitializing structs in c,['c++'] +105932,best practice for brand logo on websites i have to make a microsite and i want to know the best method of using a logo in the html template ignore the fact this is invalid code its just arbitrary waffle if i use alt for exampleoption 1a href img srclogogif aoption 2h1 a href img srclogogif ah1option 3h1 a href ah1h1background urllogogifh1 aheight px width pxoption 4is using h1 h2 or h3 better for seo as i understand that repetitive h1s are a bad idea and the company brand is not the main subject for every page on it is websitewhat i normally use is option 3 like thish2 spancompany namespan a href ah2h2height px width px background urllogogifh2 athisplay block height px width pxh2 a spanthisplay none,"['html', 'css']" +105933,jquery wrap without refresh i need to wrap an iframe in a div wihtout the iframe reloading the content is there a way to suppress the refresh or another way to wrap the content,['jquery'] +105940,how do i schedule a task with celery that runs on 1st of every month how do i schedule a task with celery that runs on 1st of every month,['python'] +105954,when testing an iphone application is it enough to just use the leaks instrument i am about to finish my first iphone application and i am am wondering if there are a set of steps that are used to check the app for memory leaks performance etcis checking with the leaks instrument enoughare there any series of tests that need to be run is there any tutorialdocument that you guys can point me to,"['iphone', 'ios']" +105963,how to split string preserving whole words i need to split long sentence into parts preserving whole words each part should have given maximum number of characters including space dots etcfor exampleint partlenght 35string sentence silver badges are awarded for longer term goals silver badges are uncommonoutput1 part silver badges are awarded for2 part longer term goals silver badges are3 part uncommon,['c#'] +105966,uiprerenderedicon glossy problem i have a problem when i want to undo the glossy stile of the app icon the apple documentation refdocuidtp409252sw1 says that there is a uikit key for that i tried to find this key uiprerenderedicon in the infoplist file of my application but i could not find it anywherei use xcode 321 and ios 30 i guess that this key can only be used in an higher sdk am i rightthank you in advanced for your responsenikolay,['iphone'] +105976,converting sql float to sql int lost data i am having some problems with converting some data stored in a float datatype to data stored in an int datatype the below example illustrates my problemdeclare data table id int weight floatinsert into data values10015662select castweight 10 as int from dataselect 0015662 10select cast0015662 10 as intthe desired results would be id 1 value 15662however when coming from the data table i do not seem to get this i instead get id 1 value 15661does anyone have any idea why this is i am guessing it is some sort of float nuance but i never thought it would have a problem with something like the above any ideas thanks in advance for your help,['sql'] +105978,how to close a jquery fancybox from button click i am using fancy box to create a popup and load another page on it using an iframe here is my code script typetextjavascriptdocumentreadyfunction calendar dayclickfunction day num thisfindday numhtml day data promptenter stuff thisfindcontenthtml if day data null ajax url windowlocation type post data day day num data day data success functionmsg locationreload documentreadyfunction aiframefancybox1fancybox width 800 height 650 overlayopacity 04 overlaycolor 0 hideoncontentclick false autoscale false transitionin elastic transitionout elastic type iframe scriptit loads the page successfully and does the stuff but instead of closing the popup form it loads the popup source form inside the popup itself i want to close the popup form when the work is done and return to the main menu page from which the popup was generated how do i achieve this on a button click of the popup formregards rangana,['jquery'] +105989,how to set the min and max height or width of a frame the size of tkinter windows can be controlled via the following methodsminsizemaxsizeresizableare there equivalent ways to control the size of tkinter or ttk framesbryan i changed your frame1pack code to the followingframe1packfillboth expandtrueframe1bind configure maxsize and i added this event handler attempt to prevent frame from growing past a certain sizedef maxsize eventnone print frame1winfo width if frame1winfo width 200 print frame1 wider than 200 pixels frame1pack propagate0 frame1config width200 return breakthe above event handler detects that a frames width is too big but is unable to prevent the increase in size from happening is this a limitation of tkinter or have i misunderstood your explanation,['python'] +105992,threading cultureinfo net tpl plinq it is not possible to set an entire net application to another culture other than the user profileculture in net the appropriate way to control cultureinfo seems to be using the dedicated methods on objects such as datetime however when dealing with massive amounts of legacy code not all code under your control this is not possible to achieve therefor one can for example create a subclasswrapper to thread och threadpool and set the required cultureinfo before the delegate is executed or the delegate itself could be required to contain a set of the culture hard to validate and prone to misstakeslooking at tpl more specifically plinq however i find it hard if not impossible to change culture settings in a centralized wayany suggestions that deals withoverriding threadapplicationcultureinfo in legacy codethanks,['.net'] +106004,c style casting and readability in c yes i know you should not use c style casts in c but in some cases i really think it is a lot more readable if you do compare these two for exampled doublei 2354 d doublejd static castdoublei 2354 d static castdoublejwhich one is more readablenow on to my main question obviously i prefer the upper one but there is one way to make it even more readable in my opiniond doublei 2354 d doublejmy question here is will this be less efficient will the compiler create more doubles in this case than if they were casted with the other methods or is it clever enough not to is this more or less bad than typical cstyle casts,"['c++', 'c']" +106021,how to remove extra space between two words using c how to remove extra space between two words using c considerhello worldi want this to be manipulated as hello world,['c#'] +106033,how to insert html to php domnode is there any way i can insert an html template to existing domnode without content being encodedi have tried to do that with domcreateelementdiv h1hello worldh1domcreatetextnodeh1hello worldh1the output is pretty much the same with only difference that first code would wrap it in a divi have tried to loadhtml from string but i have no idea how can i append it is body content to another domdocumentin javascript this process seems to be quite simple and obvious,"['php', 'html']" +106037,get a slice of a javascript associative array i have an associative array object in javascript that i need only part of with a regular array i would just use slice to get the part i need but obviously this would not work on an associative array is there any built in javascript functions that i could use to return only part of this object if not what would be considered best practices for doing so thanks,['javascript'] +106043,php how can i get file creation date i am reading a folder with lots of fileshow can i get the creation date of a file i do not see any direct function to get itthere are filemtime and filectimeand if the file has not been modified what will happen,['php'] +106046,constructor injection alternatives castle windsor i like constructor injection for dependency injection it forces a clear declaration of concerns from a type and helps with testabilityi like constructor injection in most places logging as an example where i do not like it if i have a base class from which many other classes inherit and i want all of those classes to use an instance of my ilogger or whatever and i do not want a static factory loggerinstancei do not want to have to declare a constructor on every subclass that takes an iloggerso i could have my base class declare the logger as a property and have it injected that waypublic class mybaseclass public ilogger logger get set but that does not assure me that logger actually gets injected and is not nulli do not like having ilogger with a public setsowhat other options do i have i am using castle windsori have contemplated making an interface public interface iinitializablet void initializet instance public class mybaseclass iinitializableilogger could have other iinitializables too protected ilogger logger get private set public void initializeilogger instance logger instance then having a facility on my container that automatically calls all implementations of iinitializablet upon type constructionbut i am wondering what other peoples thoughts are before i go that route,['.net'] +106053,how to create a multidimensional arraylist in java i am fairly new to arraylists anyway but i need them for this project i am doing so if you guys could help me i would be more than gratefulbasically i need to create a multidemensional arraylist to hold string values i know how to do this with a standard array like so public static string array but this is no good because i do not know the size of my array all i know is how many demensions it will haveso if you guys know how to make a dynamically resizable array with 2 demensions please could you tell methanks in advanceandyeditupdatemaybe it would be easier to resize or define a standard array using a varible but i do not knowit is probably easier to use my original idea of an arraylist though all i need is a complete example code to create a 2d arraylist and add so example values to both dimensions without knowing the index,['java'] +106055,mysql what is a page i cannot for the life of me remember what a page is in the context of a mysql database when i see something like 8kbpage does that mean 8kb per row or,['mysql'] +106057,javascript app in android i am new to android programming and looking for some general knowledge i am considering writing logic of my application in javascript so that the same code could be executed in a webapp and in a desktop application would it be possible to also have it working on android i know thatsl4a is marked as alphaquality and user would need to install it to make such an app work still it provides access to android api sl4a scripts also cannot go to android market as far as i knowa simple webapp does not have access to most android apiwould it be possible to write a simple java app that would embed an html widget with javascript code and provide some wrapper to access necessary apii am not looking for a fully portable thingi intend to adapt ui to each environment manually i just would like to have the internal logic common to all ports,"['javascript', 'android']" +106065,regex to minimize css i have a strait forward aggregatorminimizercacher i have written in nodejs it works quite well now i am however wondering if there is any way to improve my minimizing regex calls some comments are not striped from the css entirely and i notice a few other hiccups here and therealso considering my abilities with regex i might be able to do the same in half the calls any suggestions will be greatly appreciatedthanksfunction minimizedata content var content content content contentreplace nrtg content contentreplace s2g content contentreplace ssg content contentreplace sg content contentreplace snrsnrg content contentreplace snrsnrg content contentreplace sg content contentreplace sg content contentreplace sg return content,"['javascript', 'css']" +106072,ignore one table with mysqldump i have this big database 100 tables and 30 million rows that is being a pain in the ass to import back from a full backupproblem is that one table contains most of the data about 27 million rows and is entirely static so i was wondering if it was possible to specify 1 table to ignore when creating a backup with mysqldump instead of listing every table but the one i want to ignore,['mysql'] +106081,declaring strings public static readonly versus public const versus public static const in each project we have there is a file used to store the various sql statements used in that project there are a handful of variations on how the class is declared and how the strings are declaredexample class declartionsinternal sealed class classnameinternal static class classnamepublic sealed class classnamepublic static class classnameinternal class classnameexample string declarationsinternal const string stringnameinternal static string stringnamepublic static readonly string stringnamepublic static string stringnamepublic const string stringnamei do not understand what the performance implications are between the different declarations is there a best practice for this situationscenario,['c#'] +106082,android long click on a button perform actions i want to use the same button to perform 2 different methodsone method when user single clicks it and a second method different when the user long clicks iti use this for the single short click which works greatbutton downselected button findviewbyidriddownselected downselectedsetonclicklistenernew onclicklistener public void onclickview v method i have tried to add a longclicklistener but it did not workappreciate any ideas on how to solve thisthanks,['android'] +106105,searching within xcode i have had some problems with searching in xcode what is the best way to find and locate a method or class within a certain project,['iphone'] +106107,ajax requestsresponses how to make them lightning fast i came across a site that does something very similar to google suggest when you type in 2 characters in the search box eg ca if you are searching for canon products it makes 4 ajax requests each request seems to get done in less than 125ms i have casually observed google suggest taking 500ms or longerin either case both sites are fast what are the general conceptsstrategies that should be followed in order to get superfast requestsresponses thanksedit 1 by the way i plan to implement an autocomplete feature for an ecommerce site search where it 1 provides search suggestion based on what is being typed and 2 a list of potential products matches based on what has been typed so far i am trying for something similar to sli systems search see for example,['javascript'] +106125,rails url for and namespaced models in rails is it possible to namespace models in modules and still get correct behavior from url forfor instance here url for works as expected appmodelsuserrbclass user activerecordbaseend configroutesrbresources users appviewsusersindexhtmlhaml url foruser users1whereas after putting the user model into a module url for complains about an undefined method m user path appmodelsmuserrbmodule m class user activerecordbase endend configroutesrbresources users appviewsusersindexhtmlhaml url foruser undefined method m users pathis it possible to have url for ignore the module in muser and return user path for url foruser instead of m user pathupdateso after almost 5 years heres the solution thanks to esad this has been tested in rails 42 appmodelsmuserrbmodule m class user activerecordbase endend appmodelsmrbmodule m def selfuse relative model naming true end def selftable name prefix m endend configroutesrbresources users appviewsusersindexhtmlhaml url foruser users1note when generating model view and controller with binrails g scaffold muser the views and the controller will be namespaced too you need to move appviewsmusers to appviewsusers and appcontrollersmusers controllerrb to appcontrollersusers controllerrb you also need to remove references to the module m everywhere except in the model muserfinally the goal here was to namespace models but not views and controllers with esads solution the module m containing user is explicitly told to not appear in routes thus effectifely the m is stripped of and only user remainsthe user model can now reside in appviewsmodelsmuserrb the users controller lives in appviewscontrollersusers controllerrb and the views can be found in appviewsusers,['ruby-on-rails'] +106131,processing files larger than 2 gb in c with stl i am doing binary file processing and in my algorithm i would like to know the actual type of pos type and off type for example when computing the size of the file or seeking to a given position tellg and seekgwhen computing the size of the file i just static cast the pos type to an int64 t and it seems to work finehow about seekg is it safe to pass an int64 t to itis there a way to make pos type and off type to be an int64 t perhaps using traitsi would like to eliminate the hideous cast and find a way that is in accordance with the c standardupdate see alsois it safe to assign pos type to uint64 t when dealing with large files 2gbiostream and large file support,['c++'] +106134,i have started using this javascript pattern is there anything wrong with it i have started using this pattern in javascript i am not sure if i read about it specifically or if i just conjured it up one daythe format isvar name function var init function init something aclickshow var show function show something initand here is a real world examplevar contactform function var init function if bodyhasclasscontact return var form contact content form formvalidate rules fullname required true email required true email true messages email email please make sure this email is valid initis there anything wrong with this,['javascript'] +106138,storing usergenerated text in database securely rubyrails i am trying to figure out a way to store usergenerated text securely in a database so that only the user is the one who can access hisher stored text i could have rails encrypt and decrypt the users text entries using the users password as the key but if the user ever forgot their password there would be no way to ever decrypt their previous contenttext since the rails app uses bcrypt to store only a hash of the passworddoes anyone know how that could be done it looks like dropbox does something like it all files stored on dropbox servers are encrypted aes256 and are inaccessible without your account password yet they allow you to reset your password and i am assuming they do not store your plain text password anywherewhat am i missing any suggestions would be greatly appreciated thanks,"['ruby-on-rails', 'ruby']" +106154,how do i move a group of controllers into a folder i have generated a group of scaffolds with edited code inside but now i want to move these groups of controllers into a folder let us say its name is admin how do i do iti put admin in the controller already moved them into a folder already but still there is an error,['ruby-on-rails'] +106171,how can i throw an exception for the whole class instead of doing it method by method i am writing a program in java and nearly every method in one of my classes is written likepublic void dostuff throws awtexceptionis there a way for me to get rid of the extra step of typing throws awtexception for each method and somehow do it for the entire class,['java'] +106172,check if a database cell is empty first i am accessing an ms access 2007 database through c and i keep getting an exception whenever i try to read an empty cellspecifically i am trying to read a datetime cell that may or may not be emptyi am using ole db and have filled a dataset none of these conditions workdataset dataset getdatasetdatarow row datasettables0rows0datetime time new datetimetime datetimerow5 exception thrownhow to check if the cell is empty before trying to assign it none of these work ifrow5 null ifrow5 dbnull ifrow5 string edit i should have mentioned when i debug it says that row5 equals systemdbnull but i get an error when i try ifrow5 dbnull the error says dbnull is a type which is not valid in the given context,['c#'] +106173,missing numbers interview question redux the common interview problem of determining the missing value in a range from 1 to and has been done a thousand times over variations include 2 missing values up to k missing valuesexample problem range 110 1 2 4 5 7 8 9 10 36here is an example of the various solutionseasy interview question got harder given numbers 1100 find the missing numbersmy question is that seeing as the simple case of one missing value is of on complexity and that the complexity of the larger cases converge at roughly something larger than onlogncould not it just be easier to answer the question by saying sort mergesort the range and iterate over it observing the missing elements this solution should take no more than onlogn and is capable of solving the problem for ranges other than 1ton such as 10to10 or 100 to 100 etc is there any reason to believe that the given solutions in the above so link will be better than the sorting based solution for larger number of missing valuesnote it seems a lot of the common solutions to this problem assume an only number theoretic approach if one is being asked such a question in an se interview wouldnt it be prudent to use a more computer sciencealgorithmic approach assuming the approach is on par with the number theoretic solutions complexitymore related linksalgorithm how to tell if an array is a permutation in on,['c++'] +106178,why use jpa instead of directly writing sql query on java file ie directly to jdbc i have been reading up on several articles what is jpa java persistent api and which vendor supporting it datanucleus jboss hibernate etci do not have experience with orm object relational mappingwhat i have done so far is to write my own database classes using dto and dao so far i am happy about what i have but would like to know why people use jpa over java file which contains sql to me i feel like writing dao class would be ok something like belowpublic class daousers public void insertnewuserdto dtouser string query insert into usersusername address valuesdtouserusername dtouseraddress executorrunquery i have learned jpa uses jpql java persistent query language and it operates against entity objectrather than directly with db tables my understanding correct me if im wrong is that entity object here is same as my dto object kind of like beanbut anyhow what really benefit jpa gives over writing pure sql in my fileseems like using annotations required by jpa and make sql not readable feels not really attractive to meplease let me know if you need more clarification i am new to this topic and would like to hear some opinion,['java'] +106179,how do i set a namespace prefix to an xattribute in net alli want to create a soap envelope xml document egsoapenvelope soapencodingstyle xmlnssoapsoapenvelopei am using systemxmllinq to do this but i cannot figure out how to add the soap prefix to the encodingstyle attributeso far i have thisxnamespace ns xnamespacegetxattribute prefix new xattributexnamespacexmlns soap nsxattribute encoding new xattributeencodingstyle xelement envelope new xelementns envelope prefix encodingwhich gives mesoapenvelope encodingstyle xmlnssoapsoapenvelopeyou use xattribute to add a prefix to an element can i use xattribute to add a prefix to an xattributethanks p,"['c#', '.net']" +106203,handler or listeners what is better handler or listeners what is better use for notification of event what is faster more efficient etc,['android'] +106226,debugging automatic properties is there any way to set breakpoint on settergetter in autoimplemented property int counter get set other than changing it to standard property i am doing it in this way but to do that i have to change and recompile whole project,['c#'] +106245,beginner cuda simple var increment not working i am working on a project with cuda to get the hang of it i have the following codeinclude iostreamusing namespace std global void incint foo fooint main int count 0 cuda count cudamallocvoidcuda count sizeofint cudamemcpycuda count count sizeofint cudamemcpyhosttodevice cout count count n inc 100 25 count cudamemcpycount cuda count sizeofint cudamemcpydevicetohost cudafreecuda count cout count count n return 0output iscount 0count 0whats the problemthanks in advance,['c++'] +106255,how to make a java generic method static the following is a snippet on how to make a java generic class to append a single item to an array how can i make appendtoarray a static method adding static to the method signature results in compile errorspublic class arrayutilse public e appendtoarraye array e item e result enew objectarraylength1 resultarraylength item return result,['java'] +106272,videoview crop to square using an imageview i can set a square height and width say 100dip x 100dip then using androidscaletypecentercrop gives me an image which is cropped to square regardless of aspect ratiocan we do this with a videoviewi have tried just setting a square height and width but it just resizes to fill the square as best as it can while maintaining the aspect ratio which i guess is completely expectedit does not seem to have any scale or crop properties methods unlike imageview but this in the videoview documentation makes me think i am missing somethingvideoview provides various thisplay options such as scaling and tintingany ideas would be much appreciated,['android'] +106275,php elegance keys unsetting i need to remove from an array some keys array arraya a b b c cunsetarrayaunsetarraybhow can i do this more elegance maybe there is a function like this array keys unseta bi do not need array values or foreach i only want to know is it possiblethank you in advance sorry for my english and childlike question,['php'] +106283,transliteration with iconv in ruby when i am trying to transliterate a cyrillic utf8 string withiconviconvascignoretranslit utf8 stringto ssee questions1726404transliterationinrubyi am getting everything but those symbols that have to be transliteratedfor example rn34o r and gavry gvrywhats wrongruby 187 rails 235 wseven,['ruby'] +106288,how can i serialize this json using jackson annotations i have the following json fields foo foovalue bar barvalue i wrote a pojo as follows public class mypojo jsonpropertyfields private listfield fields static class field jsonpropertyfoo private string foo jsonpropertybar private string bar getters and setters for those 2this fails obviously because my json field fields is a hashmap and not a listmy question is is there any magic annotation that can make jackson recognize the map keys as pojo property names and assign the map values to the pojo property values ps i really do not want to have my fields object as aprivate mapstring string fieldsbecause in my realworld json i have complex objects in the map values not just stringsthanks philippe,['java'] +106293,phpmyadmin enable drop database statement i was alerted by my hosting provider that i exceed my 10 table limit i have a lot of databases and would like to delete more at once unfortunaltley they do not have a multiselect feature so i decided to use a query in phpmyadminwhen i try something like drop database some name i get drop database statements are thisablesdoes anyone know if it is possible to enable them or a different way to delete multiple databases,['mysql'] +106305,could not load file or assembly dll or one of its dependencies i have this dll that i created a long time ago and use to connect to the db of a specific software that i develop for i have had no issues for well over 4 years and countless applications with this dlltrying to deploy my latest creation i get the following error systemiofilenotfoundexception could not load file or assembly dll or one of its dependencies the specified module could not be foundso for every dll i ever wrote i always made a simple forms application to test that dll just by itself running that simple app yielded the same error the dll does not load or use anything else than system systemdata systemxml so as far as depencies of it go i do not see anything wrongby the way everything works on a dev station the problem is limited to deployment stations net and the necessary rethistributables since i do everything in c are deployed and workingrunning fuslogvwexe showed everything as working finerunning dependsexe said warning at least one module has an unresolved import due to a missing export function in a delayload dependent modulei already tried rewriting the whole thing which yielded the same resultsclues anyoneeditshere is the total error messagesee the end of this message for details on invoking justintime jit debugging instead of this dialog box exception text systemiofilenotfoundexception could not load file or assembly connectiontodll or one of its dependencies the specified module could not be foundfile name connectiontojobboss32dll at testconnectionform1button1 clickobject sender eventargs e at systemwindowsformscontrolonclickeventargs e at systemwindowsformsbuttononclickeventargs e at systemwindowsformsbuttononmouseupmouseeventargs mevent at systemwindowsformscontrolwmmouseupmessage m mousebuttons button int32 clicks at systemwindowsformscontrolwndprocmessage m at systemwindowsformsbuttonbasewndprocmessage m at systemwindowsformsbuttonwndprocmessage m at systemwindowsformscontrolcontrolnativewindowonmessagemessage m at systemwindowsformscontrolcontrolnativewindowwndprocmessage m at systemwindowsformsnativewindowcallbackintptr hwnd int32 msg intptr wparam intptr lparam loaded assemblies mscorlib assembly version 40 win32 version 40303191 rtmrel0303190100 codebase filecwindowsmicrosoftnetframeworkv4030319mscorlibdlltestconnection assembly version 10399618980 win32 version codebase filecprogram20files20x86conntestconnectionexesystemwindowsforms assembly version 40 win32 version 40303191 built by rtmrel codebase filecwindowsmicrosoftnetassemblygac msilsystemwindowsformsv40 40 b77a5c561934e089systemwindowsformsdllsystemdrawing assembly version 40 win32 version 40303191 built by rtmrel codebase filecwindowsmicrosoftnetassemblygac msilsystemdrawingv40 40 b03f5f7f11d50a3asystemdrawingdllsystem assembly version 40 win32 version 40303191 built by rtmrel codebase filecwindowsmicrosoftnetassemblygac msilsystemv40 40 b77a5c561934e089systemdllthere is no errors in the event viewer,['.net'] +106314,php datetimecreatefromformat does not parse iso 8601 date time code speaks a million wordsphp echo strtotime20101207t230z1291762800echo datec 129176280020101208t0100php var dumpdatetimecreatefromformatc 20101207t230zboolfalsephp var dumpdatetimecreatefromformatdatetimeiso8601 20101207t230zboolfalseany idea whats going on btw yes new datetime20101207t230z works fine but i prefer to know what input i am getting,['php'] +106316,install ios app into xcode simulator were ios and other mobile platform developers and our sales folks routinely need to provide demos of our apps for clients what were trying to do is automate a process so sales people can go to a selfserve website and feed the app into their simulatorusing xcodebuild we can kick off the build process and then present it as a secure download link via our intranet but all that lets them do is install it to their ios device this is ok except not everyone on the road has an ios device or some have old ipod touches and that is super slow so i was thinking that there is gotta be a way to get it installed in their simulatori see that others have hacked it in there by zipping up a simulator directory and placing it on anotherset target to simulator release deploy stop iphone simulator zip your app from libraryapplication supportiphone simulatoruserapplications send it to someone else and let that person know to unzip it in that folder than start iphone simulator and youre donei guess we can do this but it does not seem deterministic or at least a lot harder to script i would prefer to work with the app but if the only way to do it is with this hacky copy and paste operation thatll be what we have to doany thoughts,['ios'] +106332,how can i make capybara use routing helpers i am using rails 3 steak capybara i have restful resources is it possible to use routing helpers available to views and controllers,['ruby-on-rails'] +106337,using abs method in java my compiler does not know the method i have a simple question but i cannot find a solution for it i want to use the abs method but it does not work i am always getting the error cannot find symbol method absinti have already tried to use the method by including import javamath above the code but that doenst work too,['java'] +106344,thoughts on how to implement i am porting some very old ccode into c and i have run across a linked list implemented within an array the element is a simple structurestruct element void m ptrdata short m nextentry short m preventryas an array there is quick access to the data if you know the index the linked list aspect lets the elements be moved around and deleted from the list elements can be moved in the list based on frequency of use up for mru and down for lru i like to find a better way to implement this than using another array i would like to use stl but i am not certain which container is best to use any one have any thoughts,['c++'] +106367,c generating a pseudo number between 1020 i am making a textbased c rpg and i am trying to figure out how to work out the amount of damage that the enemy hits you for my idea is something like thisdamage done randomintbetween10and20enemylevelthis way it does not always hit for a set amount each time and allows there to be critical strikes for example if the hit is above 15 i would class that as a critical strikei am new to c so i am not quite sure how i can do this any help would be greatly appreciated,['c++'] +106369,change buffer size on mediaplayer is there any way to change default buffer size on streaming mediaplayer,['android'] +106381,javascript get array of dates between 2 dates var range getdatesnew date new dateadays7i would like range to be an array of date objects one for each day between the two datesthe trick is that it should handle month and year boundaries as wellthanks,['javascript'] +106389,why cannot i use new string in the debugger the following code compiles successfullystring foo new stringnew char b a r the following code fails to be evaluated if pasted into the watch window or the immediate windownew stringnew char b a r the error message isnew stringnew char b a r threw an exception of type systemargumentexception base systemsystemexception only newstring function evaluation can create a new string message only newstring function evaluation can create a new string paramname nullwhy does this happen,['c#'] +106429,loading custom classes in codeigniter just starting to use codeigniter and i would like to import some of my old classes for use in a new project however i do not want to modify them too much to fit into the ci way of doing things and i would like to be able to continue to use netbeans autocomplete functionality which does not work too well with ciso what is the best way to load custom classes class files into codeigniter without having to use the librarymodel loading mechanismsi apologise if this is something i should be able to find quickly but i cannot seem to find what i am after everything i see is just telling me how to go through ci,['php'] +106437,equivalents to msvcs countof in other compilers are there any builtin equivalents to countof provided by other compilers in particular gcc and clang are there any nonmacro forms,['c'] +106442,memcpy vs memmove i am trying to understand the difference between memcpy and memmove and i have read the text that memcpy does not take care of the overlapping source and destination whereas memmove doeshowever when i execute these two functions on overlapping memory blocks they both give the same result for instance take the following msdn example on the memmove help pageis there a better example to understand the drawbacks of memcpy and how memmove solves it crt memcpyc illustrate overlapping copy memmove always handles it correctly memcpy may handle it correctlyinclude memoryhinclude stringhinclude stdiohchar str17 aabbccint main void printf the string sn str1 memcpy str1 2 str1 4 printf new string sn str1 strcpy s str1 sizeofstr1 aabbcc reset string printf the string sn str1 memmove str1 2 str1 4 printf new string sn str1 outputthe string aabbccnew string abbthe string aabbccnew string abb,['c'] +106443,global array in php i have to function in two different filesone of them should add a new item to an array each time is called and the array should be accessible what i did for it is function1 global array array hibut it just create one item in array even if i call this function 4 times,['php'] +106445,how to center a div vertically i have a div that i want to center horizontally and verticallyfor the horizontal issue everything is great but i have a problem with the vertical alignmenti tried thisparent thisplay tablechild thisplay tablerow verticalalign middlebut this does not work,"['html', 'css']" +106466,sorting multiple fields in mysql i have a table with 2 fields date and importance now i want to sort both these fields in descending order so that the rows are ordered by importance for each date for example if sorted correct rows should return like thisdec 3 2010 10dec 3 2010 10dec 3 2010 8dec 3 2010 7dec 3 2010 3dec 3 2010 1dec 2 2010 10dec 2 2010 9dec 2 2010 3dec 1 2010 8dec 1 2010 5dec 1 2010 5dec 1 2010 4is there an efficient way of accomplishing this with only one query statement,['mysql'] +106474,implementing efficient audit trail of record changes in google app engine design patterns i have a quite common design problem i need to implement a history log audit trail for records in google app engine the history log has to be structured ie i cannot join all changes into some freeform text and store in string field i have considered the following options for the history model and after noticing performance issues in option 1 i have chosen to implement option 3 but have stil some doubts if this solution is efficient and scalable for instance is there a risk that performance will degrade significantly with increased number of dynamic properties in option 3 do you have some deeper knowledge on the proscons for each option or could suggest other audit trail design patterns applicable for google app engine db characteristicsuse classic sql masterdetail relationprossimple to understand for database developers with sql backgroundclean direct definition for history record and its propertiessearch performance easy searching through history can use indicestroubleshooting easy access by administration tools ahadminconsonetomany relations are often not recommended to be implemented this way in gae dbread performance excessive number of record read operations to show long audit trail eg in details pane of a big records liststore history in a blob field pickled python structuresprossimple to implement and flexibleread performance very efficientconsquery performance cannot search using indicestroubleshooting cannot inspect data by admin db viewer ahadmin unclean not so easy to understandaccept for sql developers they consider this uglystore history in expandos dynamic properties eg for each field fieldname create history fieldname n fields where n0n is a number of history recordprossimple simple to implement and understandtroubleshooting can read all the history properties through admin interfaceread performance one read operation to get the recordconssearch performance cannot simply search through history records they have different namenot too clean number of properties may be confusing at first lookstore history in some set of list fields in the main record eg for each fieldname create a fieldname history list fieldprosclean direct definition of history propertiessimple easy to understand for sql developersread performance one read operation to get the recordconssearch performance can search using indices only for records which whenever had some value and cannot search for records having combination of values at some particular time troubleshooting inspecting lists is difficult in admin db viewer,['python'] +106481,c negate an expression i am seeking for a way to negate an expression used to filter iqueryable sequencesso i have got something likeexpressionfunct bool expression x truenow i wish to create the expression which would result in yielding x false so i basically want to negate the expressionthe working method i have found myself works like thisvar negatedexpression expressionlambdafunct bool expressionnotexpressionbody expressionparameters0but i am almost sure there is a better way could you help me something like notexpression probably,['c#'] +106491,return errors from php run via ajax is there a way to get php to return an ajax error code if the php script fails somewherei was following a tutorial and typed this in to my phpreturnerror truereturnmsg could not connect to dband all was well until i realised it was json data is there a way to return errors using standard post and returned html data as in trigger jquerys ajax error event,['php'] +106494,how to list dependencies of a jar is there a tool that can list third party packages that contain third party classes referenced in the jar let say that it would recognize what is home package from jar file definition and it would print out a list of fully qualified names of third party classes up to 3rd level that were referenced within the jarorgapachecommons orgapachemavenjavaxservletjsporgeclipsepersistenceorgapachejackrabbitthe purpose is that i need to find maven dependencies for that jar file and deploy it as a maven artifact,['java'] +106498,inherit xibfile in interface builder i have a viewcontrollerxib made in ib that has a uitableviewi want to build another xibfile eg searchviewcontrollerxib thas inherit from viewcontrollerxib the new searchviewcontrollerxib should inherit the uitableview and additionally it should have a uisearchbar and a uibuttonit is possible to make this scenario with the interface builder,"['iphone', 'objective-c']" +106500,legality of using operator delete on a pointer obtained from placement new i am dang certain that this code ought to be illegal as it clearly would not work but it seems to be allowed by the c0x fcdclass x void raw mallocsizeof xx p new raw x according to the standard the rhs is a placementnew expressionoperator deletep definitely wrong per litbs answerdelete p legal i hope notmaybe one of you language lawyers can explain how the standard forbids thisthere is also an array formclass x void raw mallocsizeof xx p new raw x1 according to the standard the rhs is a placementnew expressionoperator deletep definitely wrong per litbs answerdelete p legal i hope notthis is the closest question i was able to findedit i am just not buying the argument that the standards language restricting arguments to function void operator deletevoid apply in any meaningful way to the operand of delete in a deleteexpression at best the connection between the two is extremely tenuous and a number of expressions are allowed as operands to delete which are not valid to pass to void operator deletevoid for examplestruct a virtual a struct b1 virtual a struct b2 virtual a struct b3 virtual a struct d virtual b1 virtual b2 virtual b3 struct e virtual b3 virtual d int main void b3 p new e void raw mallocsizeof d b3 p2 new raw d operator deletep definitely ub delete p definitely legal operator deletep2 definitely ub delete p2 return 0i hope this shows that whether a pointer may be passed to void operator deletevoid has no bearing on whether that same pointer may be used as the operand of delete,['c++'] +106508,how does the kdtree nearest neighbor search work i am looking at the wikipedia page for kd trees as an example i implemented in python the algorithm for building a kd tree listed the algorithm for doing knn search with a kd tree however switches languages and is not totally clear the english explanation starts making sense but parts of it such as the area where they unwind recursion to check other leaf nodes do not really make any sense to mehow does this work and how can one do a knn search with a kd tree in python this is not meant to be a send me the code type question and i do not expect that just a brief explanation please,['python'] +106509,inconsistent behaviour with nsdateformatter on two different devices i am having a bit of a problem with nsdateformatter failing on one users device returning nil when parsing a string and working perfectly when i run it locally either in the simulator or on my devicei am trying to rule out what could be causing a difference in this behaviour my first thought was the locale but i have tried setting it explicitly to ensure the same locale is always used but it makes no difference here is the codensdateformatter dateformatter nsdateformatter alloc initdateformatter setdateformatymmddthhmmssznslocale locale nslocale alloc initwithlocaleidentifieren gbdateformatter setlocalelocalelocale releasensdate thedate dateformatter datefromstringdatestringnslogparsing date as datestring thedateon the failing device i getparsing date 20101128t2030490 as nullbut locally i getparsing date 20101128t2030490 as 20101128 203049 0this is driving me crazy am i missing something else i am running 42 locally simulator and on my device an iphone 4 the failing device is a 3gs running 421any ideas would be much appreciated,"['iphone', 'objective-c']" +106511,how compatible is the java implementation of android exactly is there any definition that states which standard class libraries are supported on androidlet us assume we build a jar library and compile it using javasethis library will maybe used by a javase server application andor on a jsp serverare there any means to know beforehand if androids dex will be able to compile this library into dalvik bytecodeother means than trialerror i mean,"['java', 'android']" +106538,uiimagewritetosavedphotosalbum causes exc bad access i develop a cgimage and it works fine when the program thisplays it on the screen using thisoutput viewlayer performselectoronmainthreadselectorsetcontents withobject id image waituntildoneyesnow doing this crashes the applicationuiimagewritetosavedphotosalbumuiimage imagewithcgimage imagenilnilnili do not understand it at all heres the stack during the crash0 0x33b5db6e in memmove line 651 0x341ddee2 in cgaccesessiongetbytes2 0x31ab4488 in alphaprovidergetbytes3 0x341ddf52 in cgaccesessiongetbytes4 0x31abbc80 in writeone5 0x31abbdae in cgimagepluginwritejpeg6 0x31ab2ddc in cgimagedestinationfinalize7 0x3037eda2 in imagedatafromimagewithformatandproperties8 0x3037effc in imagedatafromimageref9 0x3038ea3c in plassetssaver saveimageimagedatapropertiescompletionblock block invoke 110 0x33c32680 in thispatch call block and release11 0x33c32ba0 in thispatch worker thread212 0x33bd7250 in pthread wqthreadhere is the method with the problemvoidcaptureoutput avcaptureoutput captureoutput didoutputsamplebuffer cmsamplebufferref samplebuffer fromconnection avcaptureconnection conenction nsautoreleasepool pool nsautoreleasepool alloc init get a cmsamplebuffers core video image buffer for the media data cvimagebufferref imagebuffer cmsamplebuffergetimagebuffersamplebuffer lock the base address of the pixel buffer cvpixelbufferlockbaseaddressimagebuffer 0 get the number of bytes per row for the pixel buffer uint8 image data cvpixelbuffergetbaseaddressimagebuffer get the number of bytes per row for the pixel buffer size t bytesperrow cvpixelbuffergetbytesperrowimagebuffer get the pixel buffer width and height size t width cvpixelbuffergetwidthimagebuffer size t height cvpixelbuffergetheightimagebuffer removed part here which modifies the cvpixelbuffer pixels with a particular algorithm bottom view setneedsthisplay bottom view performselectoronmainthreadselectorsetbackgroundcolor withobject uicolor colorwithred0 greenav2550 blue0 alpha1 waituntildone yes create a devicedependent rgb color space cgcolorspaceref colorspace cgcolorspacecreatedevicergb create a quartz image from the pixel data cgdataproviderdirectcallbacks providercallbacks 0 getbytepointer releasebytepointer getbytesatposition 0 cgdataproviderref d provider cgdataprovidercreatedirectimage datapixels4providercallbacks cgimageref image cgimagecreate widthheight832bytesperrowcolorspacekcgbitmapbyteorder32little kcgimagealphapremultipliedfirstd providernulltruekcgrenderingintentdefault draw image if needs photo uiimagewritetosavedphotosalbumuiimage imagewithcgimage imagenilnilnil needs photo no if recording writer input appendsamplebuffersamplebuffer output viewlayer performselectoronmainthreadselectorsetcontents withobject id image waituntildoneyes unlock the pixel buffer cvpixelbufferunlockbaseaddressimagebuffer0 free up the context and color space cgcolorspacereleasecolorspace cgimagereleaseimage cgdataproviderreleased provider pool drain thank you for any help with this problem,['iphone'] +106552,replacing last x amount of numbers i have a php variable that looks a bit like thisid 01922312i need to replace the last two or three numbers with another character how should i go about doing thisthanks a lot in advanceedit sorry for the confusion basically i have the variable above and after i am done processing it i want it to look something like thisnew 01922xsorry againedit2 doh typo with the quotes sorry,['php'] +106554,how to style an unordered list with jquery ui so that the elements begin with a ui icon instead of the default list symbol i would like to use an icon from the jquery ui icon set to style an unordered listdiv ul lijohn doeli lijack snowli limary moeli uldivby default this list appears with dots in front of each elementjohn doejack snowmary moeinstead i would like to replace the dot with an icon such as uiiconpersonhow to accomplish this,"['jquery', 'html', 'css']" +106565,oncreateoptionsmenumenu menu only gets called once during the lifecycle of an activity i noticed that overridepublic boolean oncreateoptionsmenumenu menu only gets called once i need this to get called every time the menu is thisplayed because i addremove items from the menu depending on the application stateis this possible,['android'] +106573,calculate 100 meter thistance when the latitude and longitude is a known point i want to know if it is possible to calculate a 100 meter thistance around a given point with a known latitude and longitude i have some coordinates in a mysql database and want to know if a specific coordinate lies in 100 meter range from a given point i am using the android platform i know only one coordinate longitude and latitude where i am standing current location and i want to set the thistance range say 100 meters i have more coordinates saved in the database and want to calculate if the other points saved in the database are in 100 meter range from my current location or not i do not know if i can use gis database in my application,"['android', 'mysql']" +106581,use php to create edit and delete crontab jobs is it possible to use php to create edit and delete crontab jobsi know how to list the current crontab jobs of the apache useroutput shell execcrontab lecho outputbut how to add a cron job with php crontab e would just open a text editor and you will have to manually edit the entries before saving the fileand how to delete a cron job with php again you have to manually do this by crontab ewith a job string like thisjob 0 2 usrbinphp5 homeuser1workphphow do i add it to the crontab jobs list with php,['php'] +106586,making http head request with urllib2 from python 2 i am trying to do a head request of a page using python 2i am tryingimport misc urllib2opender urllib2build openermisc urllib2myhttpredirecthandler misc urllib2headrequestwith misc urllib2py containingclass headrequesturllib2request def get methodself return headclass myhttpredirecthandlerurllib2httpredirecthandler def init self selfredirects def http error 301self req fp code msg headers result urllib2httpredirecthandlerhttp error 301 self req fp code msg headers resultredirect code code return result http error 302 http error 303 http error 307 http error 301but i am gettingtypeerror init takes at least 2 arguments 1 givenif i just doopender urllib2build openermisc urllib2myhttpredirecthandlerthen it works fine,['python'] +106591,why does not php catch a class not found error in the following example if the class does not exist i want to catch the error and create a null class insteadbut in spite of my trycatch statements php simply tells me class smartformasdfasdf not foundhow can i get php to catch the class not found errorphpclass smartformlogin extends smartform public function render echo pthis is the login formp class smartformcodewrapper extends smartform public function render echo pthis is the code wrapper formp class smartformnull extends smartform public function render echo pthe form htmlentitiesthisidcode does not existp class smartform protected idcode public function constructidcode thisidcode idcode public static function createsmartformidcode classname smartform smartformidcode try return new classnamesmartformidcode catch exception ex return new smartformnullsmartformidcode formlogin smartformcreateloginformloginrenderformlogin smartformcreatecodewrapperformloginrenderformlogin smartformcreateasdfasdfformloginrendersolutionthanks mchl this is how i solved it thenpublic static function createsmartformidcode classname smartform smartformidcode ifclass existsclassname return new classnamesmartformidcode else return new smartformnullsmartformidcode,['php'] +106593,how to get 0padded binary representation of an integer in java for example for 1 2 128 256 the output can be 16 digits010101010i triedstringformat16s integertobinarystring1it puts spaces for leftpadding 1how to put 0s for padding i could not find it in formatter is there another way to do itthanks in advanceps this post describes how to format integers with left 0padding but it is not for the binary representation,['java'] +106599,importing external jar files i have written a java code which imports an external jar file how can i compile and run it on the commandline thanks in advance,['java'] +106622,how to implement a contentobserver for call logs i would like to know if there is a way to know if the content provider of callings has changed i mean if i make a call or i answer a call it returns a flag that a new log has been added to the call log or the place where android store informations about callingsbecause when i make a call android stores the number the contact name if exists the hour of the calling the duration all in the content provider so is there a way to capture this flag that says the content provider of callings is bigger i mean that a new data has been inserted on the content provider calogcallsso i still have a lot of doubts related to this issue i do not know where to register the content observer my intention is when something changes in the calog content provider the insert method of the code will be used i mean the code would not do anything unless new data has been added to the calog content provider if some data has been added to the calog content provider then the code will query the new data and then will insert i wanna do this because without a content observer the application was inserting data in the database that was already inserted every time i run the application got itso here is my code if someone could tell me where to put registercontentobserver and everything else that is neededpublic class ratedcalls extends listactivity private sqlitedatabase db private calldatahelper dh null stringbuilder sb new stringbuilder openhelper openhelper new openhelperratedcallsthis public void oncreatebundle savedinstancestate superoncreatesavedinstancestate cursor cursor getcontentresolverquery androidprovidercalogcallscontent uri null null null androidprovidercalogcallsdate desc dh new calldatahelperthis db openhelpergetwritabledatabase startmanagingcursorcursor int numbercolumnid cursorgetcolumnindexandroidprovidercalogcallsnumber int durationid cursorgetcolumnindexandroidprovidercalogcallsduration int contactnameid cursorgetcolumnindexandroidprovidercalogcallscached name int dateid cursorgetcolumnindexandroidprovidercalogcallsdate int numtypeid cursorgetcolumnindexandroidprovidercalogcallscached number type date dt new date int hours dtgethours int minutes dtgetminutes int seconds dtgetseconds string currtime hours minutes seconds arrayliststring calist new arrayliststring if cursormovetofirst do string contactnumber cursorgetstringnumbercolumnid string contactname cursorgetstringcontactnameid string duration cursorgetstringdurationid string calldate dateformatgetdateinstanceformatdateid string numtype cursorgetstringnumtypeid contentvalues values new contentvalues valuesputcontact id 1 valuesputcontact name contactname valuesputnumber type numtype valuesputcontact number contactnumber valuesputduration duration valuesputdate calldate valuesputcurrent time currtime valuesputcont 1 thisdbinsertcalldatahelpertable name null values toastmaketextgetbasecontext inserted toastlength long calistaddcontact number contactnumber ncontact name contactname nduration duration ndate calldate while cursormovetonext setlistadapternew arrayadapterstringthis rlayoutlistitem calist listview lv getlistview lvsettextfilterenabledtrue lvsetonitemclicklistenernew androidwidgetadapterviewonitemclicklistener override public void onitemclickadapterview parent view view int position long id toastmaketextgetapplicationcontext textview viewgettext toastlength shortshow,['android'] +106625,how to get uiview frame origin and size while animation i have uiview animationuiview beginanimationsnil contextnulluiview setanimationduration25 myviewframe cgrectmake218 216 myviewframesizewidth 05 myviewframesizeheight 05uiview commitanimationsand nstimer with callback method the question is it possible to get current myviewframe size and origin inside timer callback methodor may be there is another way to trace it,['iphone'] +106626,is there any way to do if ie inside of a css file i know you can put conditional statements to load different css files if you are in internet explorer but can you do this inside of a css file i have a situation where i want the right margin to be 20 if it is internet explorer but 10 if it is any other browser,['css'] +106628,whats the most semantically correct way to do subheadings edit the correct term seems to be byline not subheading i will leave the post otherwise unmodified convert in your head whats the most semantically correct way to do subheadings example belowaboutwe sell apples yaylorem ipsumsince the contents of the subheading are not of much importance when compared to actual informative headings i thought that they should not be seen as separate headings by screen readers and search enginesso the options that i thought of are as followsh2abouth2h3we sell apples yayh3 this is what i would like to avoidh2abouth2span clasubheadingwe sell apples yayspan works is it the best way do not knowh2aboutspan clasubheadingwe sell apples yayspanh2 part of the heading i do not really know if it is a good or bad thingany advice on this oneplease correct me if i got the term subheading wrongi probably did,['html'] +106649,css sticky footer footer without a fixed height i have implemented the sticky footer many times from the only problem is that the footer has a fixed height is there a pure css solution to allow the footer to grow based on the content inside a js solution wouldnt be bad but css would be bestthanks in advance for the help,['css'] +106667,stop suppressing javascript errors i am using firebug to view javascript errors but i am also using jquery for some reason i never see javascript errors when using jquery and this is one of the biggest problems with working with jquery in the first placethere is no particular code to show just imagine alertareareg where areareg is undefined or any sort of javascript error and firebug would not tell me about it the javascript will simply fail without warning or notification of any sort this is always the case in any project where i have used jquery and it is the only reason i do not like jquery because it is notoriously difficult to debug when something goes wrongfor some reason i have even had trouble finding this question raised online let alone answered but i figured i would give it a try hereis there any way to make jquery stop suppressing error messagesam i the only one in the world who has always had this problem with jqueryediti use both firefox with firebug and chrome and i only use the nonminified version of jquery still i have never in my entire life seen a jquery error message of any kind neither useful nor useless nor in fact normal javascript errors when using jquery,"['javascript', 'jquery']" +106672,c systemobject vs generics i am having a hard time understanding when to use object boxingunboxing vs when to use genericsfor examplepublic class stack int position object data new object10 public void push object o dataposition o public object pop return dataposition vspublic class stackt int position t data new t100 public void pusht obj dataposition obj public t pop return dataposition which one should i use and under what conditions it seems like with the systemobject way i can have objects of all sorts of types currently living within my stack so wouldnt this be always preferable thanks,['c#'] +106716,is wif a good option for securing wcf 40 restful service with iphone i have a project which needs to expose wcf restful service to iphoneipad clientthe wcf worked now i need to secure it with username and passwordfor some reason i am a little reluctant to go with custombasicauth oauth is also not ideal in wcf world for now you have to create wrapper to do work around it please do correct me if i am wrongnow i am looking at the windows identification foundation to be honest that looks like a smart way but lacking of documentationthere are 2 things have to put into considerationimplementation have to be iphonefriendlynot just used in networldimplementation need to be easily deployed to cloud azurei would like to know which option will you choose and what is the reason of choosing itany links or reference will be greatly appreciated,['iphone'] +106724,how to terminate a thread blocking on socket io operation instantly in the context of java i create a new thread to read network input when open a gui window and when i close the window i want to release the socket resource and terminate the thread immediately now i am using setsotimeout method but i do not want to wait the timeout exception could anybody give some suggestion thanks,['java'] +106730,how to refresh a textview while looping in android i have thispublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain textview debugview textviewfindviewbyidriddebugview forint i0i100i try threadsleep100 catch interruptedexception e todo autogenerated catch block eprintstacktrace debugviewsettextintegertostringi i would expect it to update the text view each time through the loop so i would get1 2 3 99instead the app does nothing for 10 seconds and then outputs 99i am guessing that i need the textview to refresh during the loop i am new to android development can somebody please tell me if this is the best way to accomplish thismy eventually goal is to be able to process audio samples to build a guitar tuner i am trying to simply verify visually that the app is responding to external audio and i want to update a textview to demonstrate that please advise if there is a better way to do this,['android'] +106749,what do pty and tty mean i noticed there are many mentions of pty and tty in some opensource projects could someone can tell me what do they mean and what is the difference between them thanks,['c'] +106757,mongodb and postgresql thoughts i have got an app fully working with postgresql after reading about mongodb i was interested to see how the app would work with it after a few weeks i migrated the whole system to mongodbi like a few things with mongodb however i found certain queries i was doing in postgresql i could not do efficiently in mongodb especially when i had to join several tables to calculate some logic for example thismoreover i am using ruby on rails 3 and an odm called mongoid mongoid is still in beta release documentation was good but again at times i found the odm to be very limiting compared to what active record offered with traditional sql database systemseven to this date i feel more comfortable working with postgresql than mongodb only because i can join tables and do anything with the data i have made two types of backups one with postgresql and the other with mongodb some say some apps are more suitable with one or the other type of db should i continue with mongodb and eventually hope for its ror odm mongoid to fully mature or should i consider using postgresql a few more questions1 which one would be more suitable for developing a social networking site similar to facebook2 which one would be more suitable for 4page standard layout type of website home products about contact,['sql'] +106771,is there a biginteger class in php is there a biginteger class in php if so how do i access it or use it,['php'] +106778,getting the most common color of an image i would like to get the most common color from an image i use java and i want to have the most predominant color are there any cbir java library to make thisthanks,['java'] +106781,create a new folder using java program on windows and linux machines how can i create a folder using java code on both windows and linux machines,['java'] +106786,how to hide warning in jaxws client which maybe caused by jaxws library i am using netbeans to generate web service client in my application and my program using jaxws library to set timeout in calling web service problem arise because it generate a lot of this warning message whenever i start this program dec 13 2010 43521 pm comsunxmlwspolicyeffectivealternativeselector selectalternatives warning wsp0075 policy assertion atalwayscapability was evaluated as unknown dec 13 2010 43521 pm comsunxmlwspolicyeffectivealternativeselector selectalternatives warning wsp0075 policy assertion atassertion was evaluated as unknown dec 13 2010 43521 pm comsunxmlwspolicyeffectivealternativeselector selectalternatives warning wsp0019 suboptimal policy alternative selected on the client side with fitness unknown i found the same problem with mine in here but it also have no answer until now is there any way to hide this warning i try to search using google and cannot find any match answer for this problem,['java'] +106787,iphone how to get local currency symbol ie unstead of au heres a code of how i get currency symbol nownslocale lcl nslocale alloc initwithlocaleidentifierau au autoreleasensnumberformatter fmtr nsnumberformatter alloc init autoreleasefmtr setnumberstylensnumberformattercurrencystylefmtr setlocalelclnslog lcl thisplaynameforkeynslocalecurrencysymbol valueaud nslog fmtr currencysymbol both nslogs return au as i understood from apple development documentation there are at least two currency symbols for each currency these symbols could be the same though local that is used within a country for australia for example and international au for australia so the question is how to get local currency symbol any ideasthanks in advance,"['iphone', 'objective-c']" +106815,how do i monitor all incoming http requests i need to monitor my application from incoming http post and get requests originating from outside and sometimes inside the machine is this possiblebeen using fiddler but this only does outgoing not incoming from outside the machine or have i configured it incorrectlythis is for my web app that is meant to be receiving a post from an external server,['asp.net'] +106816,creating custom overlay on the map i am trying to replicate this feature of maps in androidyou can see that on the map there is a circle depicting the range that the user has selectedin my application i will also want a dragger to reside on the perimeter of the circle which can be dragged to redefine radiusif someone could tell me how to draw custom drawable overlays and 2d graphics over map i can do other things on my ownthanksthe full application can be reached at this link,['android'] +106820,android pausing and resuming handler callbacks i have a handler that i am using as followshandlerpostdelayedplay 10when my application onpause is called before this is done i need to pause it and tell it not to perform the postdelayed until i resumeis this possible or is there an alternative waymy problem is that when onpause is called i pause the audio soundmanager but if this handlerpostdelayed is called after that the audio will not be paused and will continue to play with my application in the backgroundoverridepublic void onpause soundmanagerautopausebut then the postdelayed after 10ms starts the audio playing again,['android'] +106821,cnet mdi bugs when programicaly hiding and showing again a maximized child form and when maximized child forms icon cannot be changed sorry for such long title basically i am having two problems with cnet mdi you can download vs2010 solution which reproduces bugs here1 when programicaly hiding and showing again a maximized child form it is not maximized properly again and becomes neither maximized or in normal statechildform new formchildformtext child formchildformmdiparent thisprivate void showbutton clickobject sender eventargs e childformvisible trueprivate void hidebutton clickobject sender eventargs e childformvisible falsewhen child form is maximized then programicaly hidden and shown again it becomes something like this please notice the menu bar child forms control box appears but child form is not maximizedat this stage child form cannot be moved around however i found a workaround for that simply by showing and hiding a dummy child form which forces the actual child form to become properly maximized but this makes mdi area to flicker tried invalidate refresh update methods but they do not help maybe there are other workarounds to overcome this bug and not to make mdi area flicker with dummy child formprivate void workaround1button clickobject sender eventargs e dummyformvisible true dummyformvisible false2 when child form is maximized the icon of the child form is thisplayed on menu bar however if you have to change the icon while the child form is maximized the icon on the menu bar is not being refreshed see the image above i found a workaround for that too which basically hides and shows menu bar icon gets refreshed but it makes everything below menu bar to flicker tried invalidate refresh update methods but they do not help is there any other way to make menu bar to refresh the child forms iconprivate void workaround2button clickobject sender eventargs e menustripvisible false menustripvisible truealso i noticed that when parent form is in normal window state mode not maximized and you change the width or height of the form by 1 pixel child form becomes maximized as it should be and child forms icon on menu bar gets refreshed properly and you do not need other workaround i described above if i change the size of the form programicaly form flickers by 1 pixel and i cannot do that when parent form is maximized is there any way how i could invoke the repaintrefresh functionality which is called when you resize a form and which makes child form become maximized properly and the icon on the menu bar refreshed thankspovilas,"['c#', '.net']" +106830,change max connect errors in mysql i need to change max connect errors on mysql but i have no ssh control into the server can you change it just using a mysql queryif not can anyone advise how i would change this on amazons rds service it does not seem to be in their parameter optionsthank you,['mysql'] +106833,how to parse from sql time string to javasqltime i have a database with a time field when i get the fields with a php i receive the time field as a string by jsonthe string i recive is like this 080ok all works fine here but i need to have that string in javasqltime formatthere is a easy way to do itcodestring hour1retrievehourfromphpsqlconnectiontime ahour1how to transform hour1 into timethanks,"['java', 'sql']" +106856,parse ruby object in javascript rails in my view i have one object and want to work with this onject from javascripti try to var js obj jqueryparsejsonraw rails objto json it works but if i have symbols new string symbols in this object all failshave somebody know good approach to do it,"['javascript', 'ruby-on-rails']" +106865,how does google app engine user service work internally i am just curious about how google app engines user service works the way i understand it the user logged in state is stored in the cookie to get the cookie one has to have a http servlet request object for java servlet at least but the user service api does not require any http servlet request as input so how does it get the cookie to check the whether the user is logged in or nottim,['java'] +106870,private keyword vs no private keyword what is the use of the private keyword if everything by default is privatepublic class a object someobject private object someotherobjectwouldnt both of the above be private if they are both private then why the need for the keyword itself,"['c#', '.net']" +106872,how can i thisable jobs in the quartz jdbcjobstore what is the best way to thisable a job in the jdbcjobstore without deleting it is job or trigger records and without wiping the cron expression,['java'] +106875,how can i extract the file name and extension from a path in c i have a list of files stored in a log in this syntaxcfotofoto2003shadowgifdetcmomjpgi want to extract the name and the extension from this files can you give a example of a simple way to do this,['c++'] +106876,adding scroll to gwt suggestbox does anyone know how to1 add a scroll to the popup created by the suggestbox2 how to customize the looks css of the suggestbox efficientlyi want to make above changes without touching the actual implementation as much as possiblealso this solution should support ie7ie8 ff chromethanks,['css'] +106885,size of session in codeigniter how do i increase the size of the session framework codeigniterthe standard size is 04 kb,['php'] +106906,how to implement undo functionality in my application i want to provide the user with a small undo functionality there are not many actions than can be undone by the user particularly the actions areadd notes to an objectcolor an objecttag a objcet with a stringnow i thought about how to implement this i first thought of a action class that is the abstract base class for the 3 different actions that can be taken by the user every time the user takes on of these actions a new appropriate instance of a subclass of this abstract action class is created and inserted into a list that contains all actionswhenever the user wants to undo something the list is thisplayed to the user and he can choose which action he want to undonow i was thinking what has to be stored in such an action objectthe state of the object before the actionthe actual action that was taken eg the string that was added to a objects notesi am not sure if this is enough i also thought about something like a chronological ordering but this should be necessary since the list can be maintained chronologically correctare there any other things i should consider,"['c#', '.net']" +106941,why does my sql query fail i am using this to retrieve information from a database the query always brings errorsthis is my queryselect from users order by rand limit 10it always brings up errors on either the order by rand or the limit 10any reason why this is happening also is there any solutions to this,['mysql'] +106946,prototype registry is undefined i have registry is undefined row 57with prototype 17pagenav aeachfunctionelement elementobserveclick dosomethishrefpagenav is a ul list with li and a tags,['javascript'] +106952,naming convention for passing data through extras in android when passing extras such as intentputextramyname myname whats the convention for the name of the extraie if passing data between two activities both would putextract data under the id myname but should i just hardcode myname everywhere or keep the value in the rvaluesstring,['android'] +106959,face recognition and aging faces in c hello i am looking for some good library opensource that allows me to do face recognition and to easily aging facestake a look for example at i need some library cross platform not just for windows and i would integrate that code into some iphone applicationsany suggestionsmany thanks,['c++'] +106964,narrowing conversions in c0x is it just me or does this sound like a breaking change c0x is going to make the following code and similar code illformed because it requires a socalled narrowing conversion of a double to a int int a 10 i am wondering whether this kind of initialization is used much in real world code how many code will be broken by this change is it much effort to fix this in your code if your code is affected at allfor reference see 8546 of n3225a narrowing conversion is an implicit conversionfrom a floatingpoint type to an integer type orfrom long double to double or float or from double to float except where the source is a constant expression and the actual value after conversion is within the range of values that can be represented even if it cannot be represented exactly orfrom an integer type or unscoped enumeration type to a ioatingpoint type except where the source is a constant expression and the actual value after conversion will fit into the target type and will produce the original value when converted back to the original type orfrom an integer type or unscoped enumeration type to an integer type that cannot represent all the values of the original type except where the source is a constant expression and the actual value after conversion will fit into the target type and will produce the original value when converted back to the original type,['c++'] +106965,why is the string version of getline a nonmember function the getline function has a character version that is a member function as well as a global version that takes strings why are not they both member functions the current way makes it seems as though there is not a string version,['c++'] +106966,create and parse multipart http requests in python i am trying to write some python code which can create multipart mime http requests in the client and then appropriately interpret then on the server i have i think partially succeeded on the client end with thisfrom emailmimemultipart import mimemultipart mimebaseimport httplibh1 httplibhttpconnectionlocalhost8080msg mimemultipartfp openmyfilezip rbbase mimebaseapplication octetstreambaseset payloadfpreadmsgattachbaseh1requestpost httplocalhost8080server msgas stringthe only problem with this is that the email library also includes the contenttype and mimeversion headers and i am not sure how they are going to be related to the http headers included by httplibcontenttype multipartmixed boundary2050792481mimeversion 102050792481contenttype applicationoctetstreammimeversion 10this may be the reason that when this request is received by my webpy application i just get an error message the webpy post handlerclass multipartserver def postself collection print webinputthrows this errortraceback most recent call last file usrlocallibpython26thistpackageswebpy034py26eggwebapplicationpy line 242 in process return selfhandle file usrlocallibpython26thistpackageswebpy034py26eggwebapplicationpy line 233 in handle return self delegatefn selffvars args file usrlocallibpython26thistpackageswebpy034py26eggwebapplicationpy line 415 in delegate return handle classcls file usrlocallibpython26thistpackageswebpy034py26eggwebapplicationpy line 390 in handle class return tocallargs file homericharddevelopmentserverwebservicepy line 31 in post print webinput file usrlocallibpython26thistpackageswebpy034py26eggwebwebapipy line 279 in input return storifyout requireds defaults file usrlocallibpython26thistpackageswebpy034py26eggwebutilspy line 150 in storify value getvaluevalue file usrlocallibpython26thistpackageswebpy034py26eggwebutilspy line 139 in getvalue return unicodifyx file usrlocallibpython26thistpackageswebpy034py26eggwebutilspy line 130 in unicodify if unicode and isinstances str return safeunicodes file usrlocallibpython26thistpackageswebpy034py26eggwebutilspy line 326 in safeunicode return objdecodeencoding file usrlibpython26encodingsutf 8py line 16 in decode return codecsutf 8 decodeinput errors trueunicodedecodeerror utf8 codec cannot decode bytes in position 137138 invalid datamy line of code is represented by the error line about half way down file homericharddevelopmentserverwebservicepy line 31 in post print webinputit is coming along but i am not sure where to go from here is this a problem with my client code or a limitation of webpy perhaps it just cannot support multipart requests any hints or suggestions of alternative code libraries would be gratefully receivededitthe error above was caused by the data not being automatically base64 encoded adding encodersencode base64basegets rid of this error and now the problem is clear http request is not being interpreted correctly in the server presumably because the email library is including what should be the http headers in the body insteadstorage contenttype multipartmixed u boundary u1342637378n mimeversion 10nn1342637378n contenttype applicationoctetstreamn mimeversion 10n contenttransferencoding base64n n0fincs pbk1ja etcso something is not right therethanksrichard,['python'] +106981,why do different versions of silverlight assemblies have the same version number why do different versions of silverlight assemblies have the same version numberlocation silverlightv30systemcoredll name systemcore version2050 cultureneutral publickeytoken7cec85d7bea7798e location silverlightv40systemcoredll name systemcore version2050 cultureneutral publickeytoken7cec85d7bea7798e location silverlightv40profilewindowsphonesystemcoredll name systemcore version2050 cultureneutral publickeytoken7cec85d7bea7798e while standard net has different version numberslocation frameworkv4030319systemdll name system version40 cultureneutral publickeytokenb77a5c561934e089 location frameworkv2050727systemdll name system version20 cultureneutral publickeytokenb77a5c561934e089,['.net'] +106986,how to profile application startup with visualvm as far as i can tell you can only profile a running application using visualvmdoes anyone know of a way to profile the launch and startup of a java application using visualvmi am convinced there must be a way otherwise it would be a major oversighthoping i have just misread the documentationthanks p,['java'] +106997,parse float with two decimal places i have the following code i would like to have it such that if price result equals an integer let us say 10 then i would like to add two decimal places so 10 would be 10or if it equals 106 would be 1060 not sure how to do thisprice result parsefloattest varsplit1slice01,['javascript'] +107018,is this common practice to avoid key not found in a dictionary i was wondering whether the following style is a common practice to avoid key not found in a dictionary default is 0value my dic100 if 100 in my dic else 0,['python'] +107049,choose list variable given probability of each variable i have been trying to code a program that uses the softmax activation function in the middleright now i have a list of probabilities like thisp0100250605the sum of all the variables in p is always 1i wanted a way to pick the index of the list given the probability attached to itor in other words a function that returned0 10 of the time1 25 of the time2 60 of the time3 5 of the timei have absolutely no idea where to start on this any help would be appreciated,['python'] +107059,how to check if not available methods are used if deployment target base sdk i would like to know how you check that your code do not call not available methods when the deployment target is inferior to base sdk it is possible to run the application on a device with the sdk equal to deployment target but i search a way more automatic any idea regardsquentin,"['iphone', 'objective-c', 'ios']" +107062,sleep in jquery greetings alli want to make jquery sleepwait for a second between two functions div1hidesleep or wait or for a sec div2showhow to do so,"['javascript', 'jquery']" +107063,what exactly is the zookeeper quorum setting in hbasesitexml what exactly is the zookeeper quorum setting in hbasesitexml,['java'] +107067,what are the advantages and thisadvantages of using phonegap and titanium i am planning to create a cross platform application which works in android iphone and blackberry i thought of using phonegap or titanium my questions are as these whether in cross platform if it is possible toachieve all the native behavior ofall phone models something like in android menu and iphone gesturesapart from crossplatformadvantage what are otheradvantage do it havewhat are the thisadvantages isthere any limitation when it comes to comparing tonative appwhether i can use same codewithout any modification in all the devices or i have tochange the code with respective todevice identified dynamically,['android'] +107076,how to start a python file while window starts i have a python file and i am running the file if windows is shutdown and booted up again how i can run that file every time windows starts,['python'] +107096,using collection size in for loop comparision is there a compiler optimization for the size methods of collections in java consider the following code forint i0ilistsizei some operationthere is a call to the size methods for every i would not it be better to find out the size and reuse it method calls have overheadsfinal int len listsizeforint i0ileni some operationhowever when i timed both these code pieces there was no significant time difference even for i as high as 10 am i missing something hereupdate1 i understand that the size is not computed again unless the collection changes but there has to be some overhead associated with a method call is it the case that the compiler always inlines these see eskos answer update 2 my curiosity has been fueled further from the answers given i see that good jit compilers will often inline this function call but they will still have to determine whether the collection was modified or not i am not accepting an answer in the hope that someone will give me pointers regarding how this is handled by compilers,['java'] +107114,how do i protect phone number from bots i want a phone number which thisplay on public page will be protected example converts phone number characters to html entities and bots cannot grab the number in plain text let me know the trick,"['php', 'jquery']" +107123,is jqgrid free download jqgrid js file from is it freewhat is this i see price and licensesomeone clarify please,"['javascript', 'jquery']" +107132,generating hierarchyid i would like to insert the hierarchyid like this ceo root1 purchase manager2 sales manager11 purchase executive21 sales executivethis is what the hierarchy i would like to use is it right one if so how can i do this can any one give me some code snippet,['sql'] +107160,how a change the content size of a webview in android i have a webview control in a scrollview when i load a long html document into it it resizes to accommodate it this is correct however when i use the same control again afterwards and put less spaceconsuming html into it the content size does not shrink this is a problem because the user is able to still scroll a short document into white space any ideas on how to resolve this,"['java', 'android']" +107214,this pointer in c not c i am trying to create a stack in c for fun and came up with the idea of using struct to represent the stack then i add function pointers to the struct for push and pop operations so far all is good it seems but for the implementation of the push and pop functions i need to refer to this somehow how can that can it be donethis is my structstruct stack int data int current size int max size int pushint int popand as an example heres pushint pushint val ifcurrent size max size 1 return 0 datacurrent size val current size return 1as you can imagine the compiler has no idea what current size is as it would expect something like stackcurrent size is this possible to overcome somehow,['c'] +107216,android check if service is running via bindservice what would be the best way to check if an android service is running i am aware of the activitymanager api but it seems like the use of the api is not advised for the scenarios similar to mine source i am also aware of the possibility of using globalpersistent variables to maintain the state of a servicei have tried to use bindservice with flags set to 0 but i got the same problems as the person on the source link the only exception was i was trying the bindservice with a local servicethe following callgetapplicationcontextbindservicenew intentgetapplicationcontext myserviceclass mserviceconnection 0always returns true but does not get connected is this the expected behaviour it seems to me bindservice should return false if the service is not already running it is not i have checked that or if the bind auto create flag is not set again it is not,['android'] +107247,python building an lru cache i have around 60 entries in mongodb in the following format featurecategorycountwhere feature could be any word category is positive or negative and count tells how many times a feature occurred in a document for that category i want to cache the top 10 tuples let us say so as not to query database each time how does one build an lru cache in python or are there any known solutions to this,['python'] +107252,select direct child of this in jquery i know that i can use img this to select all img elements in this in my current case i am trying to manipulate only direct child images of this is there a selector for that,['jquery'] +107268,how do i add a column to an rdlcs dataset and have it appear for use in the report i have an rdlc that has a separatelydefined dataset the time has come that i have the need to add a column to one of the tables which i can do without issue however when i open the rdlc to use the new column it does not appear in the report data panethis issue was reported to microsoft here but it was closed as by design the workaround offered with the issue does not seem to work for vs2010 refresh the dataset or the table neither does anythinghas anyone seen this problem and if so how did you get around it,['.net'] +107304,how to plot graphs in gnuplot in real time in c i am trying to plot a graph in real time using gnuplot and cdoes anyone know of any good libraries that does thisthanks,['c++'] +107305,read a line of text from an input stream in java keeping the linetermination characters i have this code in javainputstreamreader isr new inputstreamreadergetinputstreambufferedreader ir new bufferedreaderisrstring linewhile line irreadline null do stuff with lineif the input stream contains the following hellonheyryorngoodday then line variable would be following on each iterationhelloheyyogooddayi want to read one line at a time but i want to keep the linetermination charactershellonheyryorngooddayhow can i do this is there a readymade classes i can useupdate heres what i am trying to do and why i need to keep the endofline character and why the eol character may be differenti am reading a post request they consists of pure text messages where the lines always end with rn by the standard specification however post request may contain binary data which may contain bytes that look like termination characters to java reader objects in my example an image is being uploaded the image data is sent on a single line however however the images binary data contains bytes that the reader would interpret as n r or sometimes rn if those two bytes happens to be next to each otheri have to read the post request one line at a time because that is how it works i suppose i could read everything and then parse the whole thing but that is not efficient especially if a large file say 1024 mib file is being uploaded,['java'] +107318,multitenant cqrs architecture my team is beginning implementation of a greenfield application with a requirement for multitenancy i have been doing a large amount of research on patterns for simple scalability especially on thistributed cloudbased infrastructure and cqrs seems to be the buzzword du jour going so far as being called crack for architecture addicts which i find quite funny benefits and pitfalls aside it is quite hard to find anyone besides greg young that has used this idea extensively or at all in production apps and can provide realworld guidance for itso here are my questions1 does a cqrs architecture accommodate your typical multitenant application or is it better suited for larger scale internal enterprise applications2 if you recommend that it is used in this situation can you provide some fromthetrenches guidance on approaches especially on things to get right early on and what aspects should be evolved organically3 if anyone has tried and found it too difficult or not realized the benefits or has strong arguments against it and recommend sticking to crud and tiered design i would like to know about those experiences as wellfor reference the application will be written in net and the front end will initially be web based aspnet mvc potentially being extended to mobile and thick clients concurrency transactional activity and data volume are all expected to remain relatively low throughout the lifespan of the application compared to high volume financial apps and the like for infrastructure we plan on using azure,['.net'] +107329,returning strings from dll functions for some reason returning a string from a dll function crashes my program on runtime with the error unhandled exception at 0x775dfbae in cranberry library testerexe microsoft c exception stdout of range at memory location 0x001ef604i have verified it is not a problem with the function itself by compiling the dll code as an exe and doing a few simple tests in the main functionfunctions with other return types int double etc work perfectlywhy does this happenis there a way to work around this behaviorsource code for dll libraryhinclude stringstdstring getgreeting librarycppinclude libraryhstdstring getgreeting return hello worldsource code for tester testercppinclude iostreaminclude libraryhint main stdcout getgreetingedit i am using vs2010conclusiona workaround is to make sure the library and source are compiled using the same compiler with the same options etc,['c++'] +107369,is it possible to thisable spellcheck in a textarea via javascript is it possible to thisable spellcheck in a textarea via javascripti have been looking at the html5 spellcheck attribute and i can get it to work on its own however i would like to be able to change this attribute via javascriptafter reading the documentation provided at the above link i put together the following lines of code snippets from a larger file i know they would not work on their owndocumentqueryselectoreditorspellcheck falseanddocumentqueryselectoreditorspellcheck truebut it does not seem to work have i made a mistake or misunderstood the documentation unhelpfully the javascript console in google chrome is not returning an error or is there any other way to go about doing this,['javascript'] +107372,c aspnet how to access cache when no httpcontextcurrent is available is null during application end in globalaspx httpcontextcurrent is null i still want to be able to access cache it is in memory so want to see if i can reference it somehow to save bits to thiskquestion is there a way to reference cache in memory somehow when httpcontextcurrent is nullperhaps i could create a global static variable that would store pointer to cache that i could update on http requests pseudo static pointer x httprequestcurrent and retrieve a reference to cache through that pointer in application end is there a better way to access cache in memory when there is no http request is made,"['c#', 'asp.net']" +107375,why does java permit escaped unicode characters in the source code i recently learned that unicode is permitted within java source code not only as unicode characters eg double i mathpi but also as escaped sequences eg double u03c0 mathpi the first variant makes sense to me it allows programmers to name variables and methods in an international language of their choice however i do not see any practical application of the second approachhere are a few pieces of code to illustrate usage tested with java se 6 and netbeans 691this code will print out 3141592653589793public static void mainstring args double i mathpi systemoutprintlnu03c0explanation i and u03c0 are the same unicode characterthis code will not print out anythingpublic static void mainstring args double i mathpi u002a systemoutprintlni a comment explanation the code above actually encodespublic static void mainstring args double i mathpi systemoutprintlni a comment which comments out the print satementjust from my examples i notice a number of potential problems with this language featurefirst a bad programmer could use it to secretly comment out bits of code or create multiple ways of identifying the same variable perhaps there are other horrible things that can be done that i have not thought ofsecond there seems to be a lack of support among ides neither netbeans nor eclipse provided the correct code highlighting for the examples in fact netbeans even marked a syntax error though compilation was not a problemfinally this feature is poorly documented and not commonly accepted why would a programmer use something in his code that other programmers will not be able to recognize and understand in fact i could not even find something about this on the hidden java features questionmy question is thiswhy does java allow escaped unicode sequences to be used within syntaxwhat are some pros of this feature that have allowed it to stay a part java despite its many cons,['java'] +107383,intersection of two strings in java need a java function to find intersection of two strings ie characters common to the stringsexample string s1 new stringsychellestring s2 new stringsydney,['java'] +107387,spring and hibernate suddenly set the transaction to readonly we have an application running on jboss 423 using spring 252 and hibernate 326ga this is running on linux jee01 2616600545smp using its own user writing to a oracle 10g database on another machinewere using a standard view service dao layering where each dao is annotated with repositorythis is all running 247 without many problems but every several days and sometimes a couple of times in one day the whole system goes into a bad state where nothing can be written to the database anymore these stacktraces appear in the logsorgspringframeworkdaoinvaliddataaccessapiusageexception write operations are not allowed in readonly mode flushmodenevermanual turn your session into flushmodecommitauto or remove readonly marker from transaction definitionwe scanned the complete system and there is one place in the system where the flushmode is temporarely set to manual after which a finally block set its back to its original value this is because we do not want to flush the state to the database before this query runs so we cannot change this very easily the normal flushmode is set to auto and on several places we temporarily set it to commit and switching it back to the default againonly a server restart restores the system back to working orderthe question is why does the system set all transactions to readonlymanual flush mode i googled this but could not find a solutionthis is our spring and hibernate configuration only relevants part showing bean idsessionfactory classorgspringframeworkormhibernate3annotationannotationsessionfactorybean property namedatasource ref beandatasourcename property property nameconfiglocation valueclasspathhibernatecfgxmlvalue property bean bean idhibernateinterceptor classorgspringframeworkormhibernate3hibernateinterceptor property namesessionfactory refsessionfactory bean txannotationdriven transactionmanagertxmanager txadvice idtxadvice transactionmanagertxmanager the transactional semantics txattributes all methods starting with get are readonly txmethod nameapprove readonlyfalse propagationrequired rollbackforjavalangexception txmethod nameupdate readonlyfalse propagationrequired rollbackforjavalangexception txmethod namesave readonlyfalse propagationrequired rollbackforjavalangexception txmethod namedelete readonlyfalse propagationrequired rollbackforjavalangexception other methods use the default transaction settings see below txmethod name readonlytrue propagationrequired txattributes txadvice aopconfig aoppointcut idservicemethods expressionexecution commyapplicationservice aopadvisor advicereftxadvice pointcutrefservicemethods aopconfig bean idtxmanager classorgspringframeworkormhibernate3hibernatetransactionmanager property namesessionfactory refsessionfactory bean end of spring config hibernate configuation hibernateconfiguration sessionfactory name property namedialectorghibernatedialectoracle10gdialectproperty property nameshow sqlfalseproperty property nameuse outer joinfalseproperty property namehibernatecacheuse query cachetrueproperty property namehibernatecacheuse second level cachetrueproperty property namecacheprovider classorghibernatecacheehcacheproviderproperty property namehibernateconnectionsetbigstringtryclobtrueproperty property namehibernatejdbcbatch size0property sessionfactory mapping hibernateconfigurationthis is the stacktraceorgspringframeworkdaoinvaliddataaccessapiusageexception write operations are not allowed in readonly mode flushmodenevermanual turn your session into flushmodecommitauto or remove readonly marker from transaction definitionat orgspringframeworkormhibernate3hibernatetemplatecheckwriteoperationallowedhibernatetemplatejava1137at orgspringframeworkormhibernate3hibernatetemplate16doinhibernatehibernatetemplatejava701at orgspringframeworkormhibernate3hibernatetemplateexecutehibernatetemplatejava374at orgspringframeworkormhibernate3hibernatetemplatesaveorupdatehibernatetemplatejava699at nlcompanymyappdaoimplgenericdaoimplsavegenericdaoimpljava94at nlcompanymyappdaoimplcalldaoimplsavecalldaoimpljava266at nlcompanymyappdaoimplcalldaoimplsavecalldaoimpljava47at nlcompanymyappserviceimplcallserviceimplsavecallcallserviceimpljava98at sunreflectnativemethodaccessorimplinvoke0native methodat sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava39at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava25at javalangreflectmethodinvokemethodjava592at orgspringframeworkaopsupportaoputilsinvokejoinpointusingreflectionaoputilsjava310at orgspringframeworkaopframeworkreflectivemethodinvocationinvokejoinpointreflectivemethodinvocationjava182at orgspringframeworkaopframeworkreflectivemethodinvocationproceedreflectivemethodinvocationjava149at orgspringframeworktransactioninterceptortransactioninterceptorinvoketransactioninterceptorjava106at orgspringframeworkaopframeworkreflectivemethodinvocationproceedreflectivemethodinvocationjava171at orgspringframeworkaopinterceptorexposeinvocationinterceptorinvokeexposeinvocationinterceptorjava90at orgspringframeworkaopframeworkreflectivemethodinvocationproceedreflectivemethodinvocationjava171at orgspringframeworkaopframeworkjdkdynamicaopproxyinvokejdkdynamicaopproxyjava204at proxy142savecallunknown sourceat nlcompanymyappviewbeancallcalldetailbeandosavecalldetailbeanjava319at nlcompanymyappviewbeaneditmodeawarebeansaveeditmodeawarebeanjava151at sunreflectgeneratedmethodaccessor472invokeunknown sourceat sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava25at javalangreflectmethodinvokemethodjava592at orgapacheelparserastvalueinvokeastvaluejava131at orgapacheelmethodexpressionimplinvokemethodexpressionimpljava276at comsunfaceletseltagmethodexpressioninvoketagmethodexpressionjava68at orgapachemyfacestrinidadcomponentmethodexpressionmethodbindinginvokemethodexpressionmethodbindingjava46at comsunfacesapplicationactionlistenerimplprocessactionactionlistenerimpljava102at orgapachemyfacestrinidadcomponentuixcommandbroadcastuixcommandjava190at javaxfacescomponentuiviewrootbroadcasteventsuiviewrootjava458at javaxfacescomponentuiviewrootprocessapplicationuiviewrootjava763at comsunfaceslifecycleinvokeapplicationphaseexecuteinvokeapplicationphasejava82at comsunfaceslifecyclephasedophasephasejava100at comsunfaceslifecyclelifecycleimplexecutelifecycleimpljava118at javaxfaceswebappfacesservletservicefacesservletjava265at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava290at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava206at nlcompanymyappviewauditauditfilterdofilterauditfilterjava88at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava235at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava206at orgapachemyfacestrinidadinternalwebapptrinidadfilterimpl invokedofiltertrinidadfilterimpljava238at orgapachemyfacestrinidadinternalwebapptrinidadfilterimpl dofilterimpltrinidadfilterimpljava195at orgapachemyfacestrinidadinternalwebapptrinidadfilterimpldofiltertrinidadfilterimpljava138at orgapachemyfacestrinidadwebapptrinidadfilterdofiltertrinidadfilterjava92at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava235at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava206at orgacegisecurityutilfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava265at orgacegisecurityinterceptwebfiltersecurityinterceptorinvokefiltersecurityinterceptorjava107at orgacegisecurityinterceptwebfiltersecurityinterceptordofilterfiltersecurityinterceptorjava72at orgacegisecurityutilfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava275at orgacegisecurityuiexceptiontranslationfilterdofilterexceptiontranslationfilterjava124at orgacegisecurityutilfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava275at orgacegisecurityprovidersanonymousanonymousprocessingfilterdofilteranonymousprocessingfilterjava125at orgacegisecurityutilfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava275at orgacegisecuritywrappersecuritycontextholderawarerequestfilterdofiltersecuritycontextholderawarerequestfilterjava81at orgacegisecurityutilfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava275at orgacegisecurityuiabstractprocessingfilterdofilterabstractprocessingfilterjava271at orgacegisecurityutilfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava275at orgacegisecurityuilogoutlogoutfilterdofilterlogoutfilterjava110at orgacegisecurityutilfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava275at orgacegisecuritycontexthttpsessioncontextintegrationfilterdofilterhttpsessioncontextintegrationfilterjava249at orgacegisecurityutilfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava275at orgacegisecurityutilfilterchainproxydofilterfilterchainproxyjava149at orgacegisecurityutilfiltertobeanproxydofilterfiltertobeanproxyjava98at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava235at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava206at orgjbosswebtomcatfiltersreplyheaderfilterdofilterreplyheaderfilterjava96at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava235at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava206at orgapachecatalinacorestandardwrappervalveinvokestandardwrappervalvejava230at orgapachecatalinacorestandardcontextvalveinvokestandardcontextvalvejava175at orgjbosswebtomcatsecuritysecurityassociationvalveinvokesecurityassociationvalvejava182at orgapachecatalinaauthenticatorauthenticatorbaseinvokeauthenticatorbasejava432at orgjbosswebtomcatsecurityjacontextvalveinvokejacontextvalvejava84at orgapachecatalinacorestandardhostvalveinvokestandardhostvalvejava127at orgapachecatalinavalveserrorreportvalveinvokeerrorreportvalvejava102at orgjbosswebtomcatservicejcacachedconnectionvalveinvokecachedconnectionvalvejava157at orgapachecatalinacorestandardenginevalveinvokestandardenginevalvejava109at orgapachecatalinaconnectorcoyoteadapterservicecoyoteadapterjava262at orgapachecoyoteajpajpprocessorprocessajpprocessorjava437at orgapachecoyoteajpajpprotocolajpconnectionhandlerprocessajpprotocoljava366at orgapachetomcatutilnetjioendpointworkerrunjioendpointjava446at javalangthreadrunthreadjava595this all works fine,['java'] +107400,what does means in rails i found here the following syntaxh personfirst name what does the h means,['ruby-on-rails'] +107405,unsigned int in java i am trying to implement an existing network protocol which makes heavy use of unsigned datatypes which are not supported by java what i currently do is for each datatype chose the next bigger one so that the unsigned number may fit into the positive region and then use byte shifting to get the desired effect since this is pretty error prone and for an unsigned long onward i have to use biginteger which is a lot heavier than expanded types i was wondering if there is not a better way to achieve this,['java'] +107420,failure install failed already exists when i tried to update my application when i tried to update my applcation with new version that has same signature as previous one shows above errorwhat i am missing,['android'] +107423,usefullness of delete this in member function possible duplicatesis it ok to use delete this to delete the current objectshould objects delete themselves in c i just came across this question on programmersstackexchange and saw the question about doing a delete this inside a member functionfrom what i understand it is generally a nono however there are some circumstances where this could be useful when would something like that be useful and what are the technical reasons for not doing it,['c++'] +107456,using foreach loop to iterate through two lists i have two listslistobject a new listobjectlistobject b new listobjectnow i want to iterate through the elements of both list i could do that by writing a foreach loop for each list but is it also possible to do something like thatforeachobject o in a b odosomethingit would also be nice if something like that would be possibleforeach object o in a b odosomething,"['c#', '.net']" +107461,moving connections and instances between two computers ia ve got a mysqlserver that ia m administrate remotely with mysql workbenchnow ia ve got a new computer and i cant find any solution to move my connections and instancesprofiles to my new computer this cana t be an unsolved question huh not the first time this would happen for someone elsecorrection ita s not the serverinstances that i want to move i need to exportmovebackup my many clientprofilesinstancesconnections in mysql workbench,['mysql'] +107467,asynchronous io in c using windows api which method to use and why does my code execute synchronous i have a c application which generates a lot of output and for which speed is critical the program is basically a loop over a large 812gb binary input file which must be read sequentially in each iteration the read bytes are processed and output is generated and written to multiple files but never to multiple files at the same time so if you are at the point where output is generated and there are 4 output files you write to either file 0 or 1 or 2 or 3 at the end of the iteration i now write the output using fwrite thereby waiting for the write operation to finish the total number of output operations is large up to 4 million per file and output size of files ranges from 100mb to 35gb the program runs on a basic multicore processori want to write output in a separate thread and i know this can be done withasyncronous iocreating threadsio completion portsi have 2 type of questions namely conceptual and code specific conceptual questionwhat would be the best approach note that the application should be portable to linux however i do not see how that would be very important for my choice for 13 since i would write a wrapper around anything kernelapi specific for me the most important criteria is speed i have read that option 1 is not that likely to increase the performance of the program and that the kernel in any case creates new threads for the io operation so then why not use option 2 immediately with the advantage that it seems easier to program also since i did not succeed with option 1 see code issues belownote that i read but i dont see a motivation on what to use based on the nature of the application so i hope somebody could provide me with some advice what would be best in my situation also from the book windows system programming by johnson m hart i know that the recommendation is using threads mainly because of the simplicity however will it also be fastestcode questionthis question involves the attempts i made so far to make asynchronous io work i understand that its a big piece of code so that its not that easy to look into in any case i would really appreciate any attemptto decrease execution time i try to write the output by means of a new thread using winapi via createfile with file flagged overlap with an overlapped structure i have created a sample program in which i try to get this to work however i encountered 2 problemsthe file is only opened in overlapped mode when i delete an already existing file i have tried using createfile in different modes create always create new open existing but this does not helponly the first writefile is executed asynchronously the remainder of writefile commands is synchronous for this problem i already consulted it seems that the problem i have is related to the fact that any write operation to a file that extends its length will be synchronous i have already tried to solve this by increasing file sizevalid data size commented region in code however i still do not get it to work i am aware of the fact that it could be the case that to get most out of asynchronous io i should createfile with file flag no buffering however i cannot get this to work as wellplease note that the program creates a file of about 120mb in the path of execution also note that print statements not ok are not desireable i would like to see can do work in background appear on my screen what goes wrong hereinclude windowshinclude mathhinclude stdiohinclude stdlibhinclude timehdefine async remove this definition to run synchronously ie using fwriteifdef async struct overlapped poverlapped handle peventh handle pfileelse file pfileendifdefine dim x 100define dim y 150define printerrormsgs printffile s line d s file line msgs fflushstdout return 0 define printfmsgs printfmsgs fflushstdout define start timer time t time1time2 clock t clock1 timetime1 printfstart time sctimetime1 fflushstdoutdefine end timer timetime2 clock1 clock printfend time sctimetime2 printfelapsed processor time 2fnfloatclock1clocks per sec fflushstdoutdouble aio datdim y 0double do computedouble adouble b int arr lenint main start timer const char pname test1bin dword dwbytestowrite bool berrorflag false int j0 int i0 int foverlapped0 ifdef async create open the file pfilecreatefilepname generic write open for writing 0 share write access null default security create always create newoverwrite existing file flag overlapped file flag no buffering overlapped file null no attr template check whether file opening was ok ifpfileinvalid handle value printfxngetlasterror printerrorfile not opened properlyn make the overlapped structure poverlapped calloc1sizeofstruct overlapped poverlappedoffset 0 poverlappedoffsethigh 0 put event handle in overlapped structure ifpoverlappedhevent createeventnulltruefalsenull printfxngetlasterror printerrorerror in createeventn else pfile fopenpnamewb endif create some output forj0jdim yj aio datj do computei j dim x determine how many bytes should be written dwbytestowrite dwordsizeofaio dat fori0idim xi do this dim x times ifdef async ifi0 setfilepointerpfiledwbytestowritenullfile current ifsetendoffilepfile printfinpfile printerrorerror in set end of filen setfilepointerpfiledwbytestowritenullfile current write the bytes ifberrorflag writefilepfileaio datdwbytestowritenullpoverlapped check whether io pending or some other error ifgetlasterrorerror io pending printflasterror xngetlasterror printerrorerror while writing filen else foverlapped1 else if you get here output got immediately written bad foverlapped0 iffoverlapped do background this msgs is what i want to see forj0jdim yj aio datj do computei j dim x forj0jdim yj aio datj do computei j dim x printfcan do work in backgroundn else not overlapped this message is bad printfnot okn wait to continue ifwaitforsingleobjectpoverlappedheventinfinitewait object 0 printerrorwaiting did not succeedn reset event structure ifreseteventpoverlappedhevent printfxngetlasterror printerrorerror in reseteventn poverlappedoffsetdwbytestowrite else fwriteaio datsizeofdoubledim ypfile forj0jdim yj aio datj do computei j dim x forj0jdim yj aio datj do computei j dim x endif ifdef async closehandlepfile freepoverlapped else fclosepfile endif end timer return 1 double do computedouble adouble b int arr len int i double res 0 double xa mallocarr len sizeofdouble double xb mallocarr len sizeofdouble if xa xb abort for i 0 i arr len i xai sina xbi cosb res res xaixai freexa freexb return resuseful links ccref clscommoncppref asynchioc aio read write eghtmi know this is a big question and i would like to thank everybody in advance who takes the trouble reading it and perhaps even respond,['c'] +107469,loading multiple versions of the same assembly i am working with a thirdparty assembly and unfortunately i now need to load their latest and a previous version into my project so at runtime i can decide which one to load i only ever need one not bothwith this in mind i am also dependent upon the types provided by the components so i cannot load from reflection and query every time for the methodeventsinterfaces that i want to use i have seen some mention of handling this via appdomains but am not sure how to proceedwould the process be to code against one version of the component and then at runtime using the appdomain swap in the correct dll i want to be consumed so i would only be handling this at startup,['c#'] +107471,androidjava javadoc missing after updating android sdk after i recently installed the new android sdk stuff i no longer can view the javadoc while editing my projects code i get this message note this element has no attached source and the javadoc could not be found in the attached javadoci am getting this message for all methods variables classes etci have installed the documentation and everything available to me via the android update manager i have also tried to do a clean install of the android sdk and eclipse and no luck getting the javadoc workingi have also tried manually setting the javadoc via project properties javadoc location filecprogram filesandroidandroidsdkwindowsdocsreference with no luckwhat suggestions do you have that could fix this problem,['android'] +107475,java socket performance bottleneck where i recently started the development of an application making intensive usage of networking a first attempt was made using rmi and for a couple of reasons we switched over to pure sockets however when testing sockets over a network or even on localhost we dropped to a rate of 25 requestssecond while using rmi it was two orders of magnitude higherwith a little more testing we obtained following for localhostsending always the same object 31628 requestssecsending always a new object 25 requestsseconly object creation rate 34 millions per second so that is not the bottleneckhere is the client code the server side just replies an ackpublic static void mainstring args throws ioexception classnotfoundexception socket kksocket null objectoutputstream out null objectinputstream in null kksocket new socketbarium 4 out new objectoutputstreamkksocketgetoutputstream in new objectinputstreamkksocketgetinputstream long throughput long millis tcprequest hello null throughput 0 millis systemcurrenttimemillis while systemcurrenttimemillis millis 10 hello new tcprequest helloservice hello hellopayload mathrandom throughput systemoutprintln systemoutprintln objects created throughput requestssec systemoutprintln throughput 0 millis systemcurrenttimemillis while systemcurrenttimemillis millis 10 outwriteobjecthello object res inreadobject throughput systemoutprintln systemoutprintln same object throughput throughput requestssec systemoutprintln throughput 0 millis systemcurrenttimemillis while systemcurrenttimemillis millis 10 hello new tcprequest outwriteobjecthello object res inreadobject throughput systemoutprintln systemoutprintln new objetcs throughput throughput requestssec systemoutprintln outclose inclose kksocketclosethe tcprequest class is just a dummy class without anything specialso if creating object is fast if sending it over the network is fast why on earth is sending a new object over the network so slowand if you keep a same object and modify its content before sending it you will also have high transfer rate but fall in the nasty pitfallwhen working with object serialization it is important to keep in mind that the objectoutputstream maintains a hashtable mapping the objects written into the stream to a handle when an object is written to the stream for the first time its contents will be copied to the stream subsequent writes however result in a handle to the object being written to the streamwhich happened to us and caused some hours of debugging before figuring it out so basically how do you achieve high throughput with sockets i mean with rmi being a wrapper around it we were already two orders of magnitude highersolvedby replacingout new objectoutputstreamkksocketgetoutputstreamwithout new objectoutputstreamnew bufferedoutputstreamkksocketgetoutputstreamthe performances are normal again nearly the same high throughput as with the same object case,['java'] +107490,sql timeout expired for 2 second query the problem is i have a stored procedure that runs consistently in sql server management server with a time of 2 seconds but when calling that same stored procedure from code it times outwhen it runs correctly from ssms it should return about 30 rowsi have tried a few different ways to call the procedure from code but every time the same result this just recently started happening yesterday it was working finethe preferred method for calling the procedure for us is using linq2sql which gives the following error messagetimeout expired the timeout period elapsed prior to completion of the operation or the server is not responding description an unhandled exception occurred during the execution of the current web request please review the stack trace for more information about the error and where it originated in the code exception details systemdatasqlclientsqlexception timeout expired the timeout period elapsed prior to completion of the operation or the server is not respondingsource errorline 16 public imultipleresults gettournamentratingnoncomplaintdataglobalsystemdatalinqmappingparameterattributedbtype datetime systemnullablesystemdatetime startdate globalsystemdatalinqmappingparameterattributedbtype datetime systemnullablesystemdatetime enddate globalsystemdatalinqmappingparameterattributedbtype int systemnullableint officialsportid globalsystemdatalinqmappingparameterattributedbtype char1 systemnullablechar gender globalsystemdatalinqmappingparameterattributedbtype int systemnullableint levelline 17 line 18 iexecuteresult result thisexecutemethodcallthis methodinfomethodinfogetcurrentmethod startdate enddate officialsportid gender levelline 19 return imultipleresultsresultreturnvalueline 20 does anyone know what the differences are between running it in ssms and through code what can be done to troubleshoot this issue,"['asp.net', 'sql']" +107506,c get the item type for a generic list what would be the best way of getting the type of items a generic list contains it is easy enough to grab the first item in the collection and call gettype but i cannot always be sure there will be an item in the collectionhope that makes sensethankssonny,['c#'] +107507,google audit question the following external css files were included after an external javascript file in the document head to ensure css files are downloaded in parallel always include external css before external javascript 1 inline script block was found in the head between an external css file and another resource to allow parallel downloading move the inline script before the external css file or after the next resourcemy html ishead link relstylesheet hrefgstylecss script typetextjavascript srcgmainjsscript script typetextjavascript languagejavascript your chart objects var mychart function to hold all chart creation function initcharts mychart new ganttchartchart1 mychartgaddbardynamic 2232010 342010 mychartgloaddatagoing to the shop4320101932010watching tv9320102332010watching tv1320102332010watching tv18320102832010end input132010932010 mychartgdraw mychartgchangebarcolour1 dd2200 mychartgchangebarcolour2 9900ee mychartgchangebarcolour3 00dd00 mychartgchangebarcolour4 ffbb00 mychartgchangebarcolour5 00aa99 scriptheadbody onloadinitcharts div idchart1 classgcontainer div div iddbdivbodyis it getting confused between the body inline script,"['javascript', 'html']" +107546,why are object variables declared with a star this may seem like trivial questionbut why is that we have to use the asterisk symbol when declaring object variableslike we do car mazda car alloc initwhats the importance of the asterisk i mean the compiler already knows it is an object i am sure the compiler can be trained not to complain about it but then again by omitting it i get an error message statically allocating instance of objectivec class nsobject what purpose would that serve,['objective-c'] +107569,ide for cssless files dreamweaver i am using lesscss the frameworkcompiler for css my ide dreamweaver does not recognize less as css so no niceties such as error checking or code completion there is there anything i can do about that,['css'] +107588,please recommend me some railsruby open source code that needs documentationtests written i have been using ruby on rails for the last 4 months or so and i have been really enjoying the whole concept of open source i know it is not exclusive to rubyrails but coming from windows programming this is my first real exposure to iti want to give back what i can but i do not feel like i can contribute any worthwhile open source projects or gems of my own so i figured a good place to start is by documenting or writing tests for some existing projectscould you guys please point me to a few possible options i would prefer projects that are pretty active but at the same time not too complex since i am not very good with ruby right nowthis might be a subjective question but at this point i have no idea where to even start so even subjective answers would be much appreciated,"['ruby-on-rails', 'ruby']" +107589,rails where params is defined i use params in my controller like thisclass productscontroller applicationcontroller def create product productnewparamsaircon endendis params an attribute of applicationcontroller i guess not because it does not have the prefix so what actually params is can i use it in any custom method in productscontroller,['ruby-on-rails'] +107613,how to show the text on a imagebutton i have a imagebutton and i want show a text and a image on it but when i try imagebutton androidtextok androidididbuttonok androidsrcdrawablebuttonokandroidlayout widthmatch parent androidlayout heightwrap contenti get on emulator the button have image but without the text how can i show the text please help me,['android'] +107633,difference between style positionabsolute and style positionrelative can any one tell me the difference between style positionabsolute and style positionrelative and how they differ in case i add it to divspaninput elementsi am using absolute right now but i want to explore relative as well how will this change the positioning,['css'] +107635,nlp programming tools using php since big web applications came into existence searching for data and doing it lightning fast and accurate has been one of the most important problems in web applications for a while i have worked using lucenenet which is a c port of the lucene project i also work using php using zend frameworks lucene api which brings me to my question most times for providing good indexing we need to perform some nlp tools like tokenizing lemmatizing and many more the question isdo you know of any good nlp programming frameworktoolset using phpps i am very aware of the zend api for lucene but indexing data properly is not just storing and relying in lucene you need to perform some extra tasks like those above,['php'] +107658,unable to unbind the window beforeunload event in jquery i have a page where the user can drag and drop objects and save them as an imagewhen a user navigates away from the page the event beforeunload is fired now this happens every time what i want to do is unbind the event if the user has saved his work so that the message may not pop up againto do this i have used theunbind method in jquery but it does not seem to work below is the code for binding and unbinding the eventsvar notsaved function return you have not yet saved your workdo you want to continue doing so may cause loss of your work windowbindbeforeunload notsavedafter save method has been calledwindowunbindbeforeunload notsavedwhat am i doing wrong herealso the save method is actually an ajax call,['jquery'] +107668,mongodb and c case insensitive search i am using mongodb and the c driver for mongodbi recently thiscovered that all queries in mongodb are casesensitive how can i make a caseinsensitive searchi found one way to do this querymatches firstname bsonregularexpressioncreatenew regexsearchkeyregexoptionsignorecase,"['c#', '.net']" +107677,how do i temporarily redirect stderr in ruby i would like to temporarily redirect stderr in a ruby script for the duration of a block ensuring that i reset it to its original value at the end of the blocki had trouble finding how to do this in the ruby docs,['ruby'] +107685,set maxlength in html textarea how can i set the maxlength in a textarea and why maxlength is not working properly in textarea,['html'] +107708,uninitialized constant when included test helper module i am getting an uninitialized constant error when trying to include a helper module into a testi have the following files in my rails test directory functional admin school controller testrbfunctional controller helperrbthe classmodules bodies are as followsmodule controllerhelper def check sort order items column direction endendclass adminschoolscontrollertest actioncontrollertestcase include controllerhelper test should sort by columns do check sort orderassignsschools schoolsname asc check sort orderassignsschools schoolsname desc endendwhen i run this the test output isrvmgemsruby192p0gemsrspeccore230librspeccorebackward compatibilityrb20in const missing uninitialized constant controllerhelper nameerrori have tried playing with the namespaces but cannot get the module mixed in at all any ideas why i am getting this error or is this even the correct way to extract common test functions i am very new to rails so any advice would be appreciated cheers,"['ruby-on-rails', 'ruby']" +107715,java generics why someobjectgetclass does not return class extends t i would expect that from the aspect of compile time as well as from the aspect of runtime it wouldnt be a problem for getclass to provide a correctlytyped return valuebut i must be wrongpublic class getclassgenerics2 static class myclass public static void mainstring args myclass myinstance new myclass here it works class extends myclass type myinstancegetclass mymethodmyinstance public static t extends myclass void mymethodt instance class extends t type instancegetclass javalangruntimeexception uncompilable source code incompatible types required javalangclass extends t found javalangclasscapture1 of extends getclassgenerics2myclass edit it does not work with classt and class super t either,['java'] +107721,error a signinresponse message may only redirect within the current web application mvc 20 application i have a situation where we have a mvc 2 applicationi tried this with a basic mvc 2 app without any extra stuff still same problem and am using adfs 2 for authenticating my userssonow i get into my application and i get the belowid3206 a signinresponse message may only redirect within the current web application app is not allowed description an unhandled exception occurred during the execution of the current web request please review the stack trace for more information about the error and where it originated in the code exception details microsoftidentitymodelprotocolsfederationexception id3206 a signinresponse message may only redirect within the current web application app is not allowedi have read most blogs on this and posted to one federatedauthentication wsfederation passiveredirectenabledtrue issuerhttpsauthdomainadfsls realmhttpsdevelopment domainapp requirehttpstrue cookiehandler requiressltrue federatedauthenticationaudienceuris add valuehttpsdevelopment domainapp audienceurisi have the trailing slash on the realm and audienceuris i have added what he suggested to application beginrequest a i then copied code to development domain as thatas where the certs are it just gets stuck in an infinite loop theni also have checked my relying party on the geneva server the identifiers and endpointspost are both httpsdevelopment domainapp again with the trailing slashi think itas a problem with the fact itas a mvc application i have created numerous claims aware website and got my claims etc on the defaultaspx page my thinking is that the routing that is involved with the mvc app is somehow posting it back wrongany help really apprecaited as im looking at this for quiet a while now to no availj,['c#'] +107726,how to monkeypatch code that gets autoloaded in rails i am monkeypatching a rails engine with something likesomeclassclass eval do endthe first time i hit the web site on development mode at least it works but the second time it is like my patch never existed i presume it is rails autoreloading the engine which is installed in vendor and not reloading my code this is rails 23any ideas how to do it so that my code also gets reloaded,['ruby-on-rails'] +107731,mastermind scoring algorithm in c using linq i am looking for an elegant way to compute the score of a guess in the mastermind game in c preferably using linqin mastermind the codemaker generates a secret code of 4 digits using the digits 1 through 6 a digit may be used more than once as an example the secret code isint secret 1 2 3 1 the codebreaker tries to break the secret code by presenting a guess in this example the guess isint guess 1 1 2 2 both code and guess are now stored in an array but other collection types are okay toothe codemaker then scores this guess by announcing the number of blacks and whites a black is awarded for each digit from the guess which is correct in both value and position a white is awarded for each correct digit placed in the wrong position in this example the score is 1 black for the 1 in position 1 and 2 whites for the 1 and 2 in positions 2 and 3back to the question i am looking for an elegant way to compute the score of a guess in c preferably using linq so far i have come up with a statement that computes the number of blacksint blacks new int 0 1 2 3 counti guessi secretii was going to proceed along the lines that the number of whites is the total number of matches 3 minus the number of blacks so i triedint whites guessintersectsecretcount blacksbut alas ienumerableintersect produces 1 2 instead of 1 1 2 because it looks at thistinct digits only so it computes whites 1 instead of 2i cannot come up with another way of computing whites except from using c style nested loops can you preferably using linq i like the way an algorithm can be expressed in code using linq execution speed is not really an issue,['c#'] +107740,android and facebook how to get picture of logged in user i use the official facebook sdk in my android application after the user logs in i can get the uid and the name of the facebook user like sofacebook mfacebook new facebookapp id user logs in string jsonuser mfacebookrequestmepicture throws errorstring jsonuser mfacebookrequestmejsonobject obj utilparsejsonjsonuserstring facebookid objoptstringidstring name objoptstringnamei also know that the i can access the profile picture with those linksfacebookidpicture facebookidpicturetypelargei would love to use this code to geht the profile picturepublic static drawable getpictureforfacebookidstring facebookid drawable picture null inputstream inputstream null try inputstream new url facebookid pictureopenstream catch exception e eprintstacktrace return null picture drawablecreatefromstreaminputstream facebookpictures return picturebut it just wont work i always get the following errorssl handshake failure failure in ssl library usually a protocol errorand i cant solve this issue it seems to be rather complicatedlook here or here so what other options are there to get the picture of a facebook user that successfully logged into my application,['android'] +107747,how to install trusted ca certificate on android device i have created my own ca certificate and now i want to install it on my android froyo device htc desire z so that the device trusts my certificate android stores ca certificates in its java keystore in systemetcsecuritycacertsbks i copied the file to my computer added my certificate using portecle 15 and pushed it back to the device now android does not seem to reload the file automatically i have read in several blog posts that i need to restart the device doing so results in the file being overwritten with the original one againmy next try was to install the certificate from sd card by copying it and using the according option from the settings menu the device tells me that the certificate has been installed but apparently it does not trust the certificate moreover when i try to copy the keystore to my computer i still find the original stock cacertsbksso what is the right way to install my own root ca certificate on an android 22 device as a trusted certificate is there a way to do it programmatically,['android'] +107750,reloadrowsatindexpathswithrowanimation crashes my app i got a strange problem with my uitableview i use reloadrowsatindexpathswithrowanimation to reload some specific rows but the app crashes with an seemingly unrelated exception nsinternalinconsistencyexception attempt to delete more rows than exist in sectionmy code looks like followsselftableview reloadrowsatindexpathsnsarray arraywithobjectnsindexpath indexpathforrow0 insection0 withrowanimationuitableviewrowanimationfadewhen i replace that reloadrowsatindexpathswithrowanimation message with a simple reloaddata it works perfectly any ideas,['iphone'] +107757,how to change serial port speed on the fly with boostasio or how to find out if the hardware buffer is empty i am having a peculiar problem with boostasio and a boostasioserial port device the code is finally working pretty well with asynchronous reads and stuff but i cannot figure out how to change the speed of the serial port on the fly what i am trying to do right now is just telling the device connected in my serial port to change the serial port speed to say 38400 baud then i am setting my computers serial port to the same speed viaport set optionboostasioserial port basebaud raterate but whats really happening is that if i do the set option part the device never receives the command to change the speed if i do not do the set option part the device changes speed correctly from what i gather whats happening is that the blocking synchronous write puts stuff in the hardware buffer on my computer and returns then does the set option which thiscards the buffer before it has had time to send data to the device so i need to think of some way to check if the hardware buffer is empty and the device really has received the command to change the speed before reconfiguring my computers serial port i also cannot find any info on if i have to do close and open on the port for the speed change to take affect i am also wondering if close thiscards the stuff in the buffer or not i am using a usbserial port adapter and my platform is ubuntu 1010 if it makes any difference,['c++'] +107780,how do you stop console from popping up automatically in eclipse i have a web application running in eclipse with tomcat and it has a few errors that make the console popup every few seconds how do i stop it from automatically popping uptaking focus,['java'] +107790,why does systemiopathcombine have 4 overloads in net 4 systemiopath has the following overloads for the combine methodpublic static string combineparams string pathspublic static string combinestring path1 string path2public static string combinestring path1 string path2 string path3public static string combinestring path1 string path2 string path3 string path4the first one was added in net 4 to support any number of path arguments the second one was already there in earlier versions so i suppose it is kept for backwards compatibilitybut i am curious what the use of the other overloads is are not these use cases already covered by the first method signature with paramsedit i now believe that the answer is because not all languages have params support and passing an array without params support is inconvenient however the stackoverflow hive mind seems to thisagree strongly therefore as a compromise i am not accepting any answer,"['c#', '.net']" +107799,how to run python nose tests with a different version of python we have centos with the ancient python 24 interpreterbut we would like to write out tests with a newer 2526 syntaxassuming we have a second python interpreter installed eg python26 is there any wayto run the nosetests shell command and tell it to use a specific python interpreter instead of the default one,['python'] +107822,ruby objects and json serialization without rails i am trying to understand the json serialization landscape in ruby i am new to rubyis there any good json serialization options if you are not working with railsthat seems to be where this answer goes to railshow to convert a ruby object to jsonthe json gem seems to make it look like you have to write your own to json methodi have not been able to get to json to work with arrays and hashes documentation says it works with theseis there a reason the json gem does not just reflect over the object and use a default serialization strategy is not this how to yaml works guessing here,['ruby'] +107869,netscperror scp did not finish successfully i have a script which will do the file transfer from one server to another but it gives an errornetscperror scp did not finish successfully can any body help me here is my codenetscpstart scom username password password doscp scpupload source destination end,['ruby-on-rails'] +107901,iphone max socket buffer size im trying to figure out what is the most optimized socket buffer size on ios when i query kipc maxsockbuf with sysctl it returns a 4mb buffer size which seems to me pretty high from my experience socket recv performance seems better when using the default continuous buffer size of the system unix guy speaking here however i cannot run a sysctl a on ios to get that info and its also not available through the c interface for sysctl or does it have a different namedoes anyone else have tested what is the most performant recv socket buffer size on ios,"['iphone', 'ios']" +107909,does varargs offer a kind of poor mans polymorphism no doubt every other student of c has noticed this it is new to meif i declareint xlate void and then define xlate in several different ways maybe all definitions but one are ifdefed outint xlate char arg1 int xlate int arg1 char arg2 int arg3 int xlate char arg1 int arg2 and omit any mention of va list never mentioning it in everydefinition of xlate and then call xlate abiding by one of itsseveral definitions it seems that every compiled version of xlate works just the way i want at least under gcc and msvcis this relaxed undemanding generous compiler behavior guaranteed under c99thanks pete,['c'] +107913,ipad thismiss keyboard without knowing which textfield opened it is there a way to do a general resignfirstresponder to hide the keyboard regardless of what textfieldviewetc calls itreason is i have a lot of textfields on my view and do not want to have to resignfirstresponder for all textfields to hide the keyboard just want a general self resignfirstresponderany ideasthanks in advance,"['objective-c', 'iphone']" +107917,play simple beep with python without external library using only the modules that come with a standard python 26 installation would it be possible to play a simple beeping noise,['python'] +107929,how to launch a android service when the app launches i am still fresh to android and id think the below config works for launching my service when the app launches service androidnameplaylistupdaterservice intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter servicebut this is not the case what did i miss,['android'] +107948,android textview change text color on click i have a textfield that behaves like a local link clicking on it fetches an image from database and shows it it does not ping to server all the timehere is the xml code for the text viewtextview androidlayout marginleft2dp androidlinksclickabletrue androidlayout marginright2dp androidlayout widthwrap content androidtextstringbeatles androidclickabletrue androidididbeatles androidtextcolorcolorblack androidtextsize12dp androidlayout heightwrap content androidtextcolorhighlightcoloryellow androidtextcolorlinkcoloryellow androidautolinkalltextviewthe question is i want to see the color of text view should be changed in yellow instead of the same black color just like the button behavior but instead of changing the background color i want to change a text color,['android'] +107950,python beautifulsoup equivalent to lxml make links absolute so lxml has a very hand feature make links absolutedoc lxmlhtmlfromstringsome html pagedocmake links absoluteurl for some html pageand all the links in doc are absolute now is there an easy equivalent in beautifulsoup or do i simply need to pass it through urlparse and normalize itsoup beautifulsoupsome html pagefor tag in soupfindalla hreftrue url data urlparsetaghref if url data0 full url url for some html page test url,['python'] +107957,properties file changes are not reflecting unless restarting glassfish server i am using jsf20 and glassfish v3i have a validatormessageproperties file under webinfclasses folder of my projectwhen i make any changes to messages in this file through my project its changes are not reflectedi access this messages through floadbundle varmsg basenamevalidationmessagesare there any configurations to be made in glassfish or my project sideps the same functionality works under jetty 700pre3please comment if question is not clear,['java'] +107960,c name mangling decoder for g is there any c namemangling decoder for g,['c++'] +107963,configure nginx in passenger 302 stand alone in older passengers 300 it was possible to configure the standalone nginx passenger passenger start in the passengerdir there was a complete nginx installation 300x86 64ruby192macosx106nginxin 302 there only is a sbindir the config directory is missing where can i find the config files,['ruby-on-rails'] +107976,firebug problem cannot use consolelog i have a problem with the current version of firebugfirefox 3613firebug 160 and 161b1 tried bothmy javascript cannot use consolelog or any console at all to output debug messages i am not sure when it stopped working but for now i get an console is not defined when i try to access it or a message popup when i run this codeif console undefined alert1i had the latest firephp extension developercompanion installed but removed it to see if that was causing the problem did not change anything thoughany ideas is this happening to someone else tooupdatelooks like my problem was actually caused by something else i use jquery and have all my code wrapped in function to make it run after the page has been renderedwhat i did not consider is that then the code runs in another scope console is not available in that scopeto use the console i have to call windowconsolelogbla,['jquery'] +107988,jqgrid incorrect select drop down option values in edit box i am using form edit there are two select boxes in the form one select box is the country another select box is the state the state select box depends on the country selected and will be populated dynamically for examplecountryus option value1 uk option value2state for usalabama option value1 california option value2 florida option value3 hawaii option value4state for uklondon option value5 oxford option value6as you can see above the id of state for uk starts with 5 when i edit a record which contained country id2 uk and state id6 oxford the edit form will shows correctly country is uk and state is oxford but if you drop down the state select box the option text is correct it shows london oxford but the option value will starts from 0 what should be correct is that the option value should starts from 5if you select and change the country drop down box to us then change back again to uk the option value will be populated correct starts from 5my question is how can we populate the select box for the state with the correct option value based on the country in edit box when the edit form loads,"['javascript', 'jquery']" +108011,how to save consolewriteline output to text file i have a program which outputs various results onto a command line consolehow to save the outputs to a text file via stream reader or other methodssystemcollectionsgenericienumerablestring lines filereadalinesctestntfs8txtforeach string r in linesskip1 string token rsplit string datetime token0split string timetext datetime4 string actions token2 consolewritelinethe time for this array is timetext consolewritelinetoken7 consolewritelineactions macactionsactions x 1 consolewritelineif x 2 consolewritelinethe selected time does not exist within the log filessystemiostreamreader reader string sres readerreadtoendstreamwriter swsw filecreatetextctemptestbodyfileswwritelinesresswcloseconsolewritelinefile createdreaderclose,['c#'] +108019,why cannot we use double pointer to represent two dimensional arrays why cannot we use double pointer to represent two dimensional arraysarr25 hellohaiptr arrhere why does not the double pointer ptr work in this expample,['c'] +108025,how can i select a range of indexes from an array in python i would do thisvar testtest1test2test3test var13then variable test would be test1test2test3how can i do this in php,['php'] +108031,how can i strip commas and periods from a string i have string containing something like thisfavourite bands coldplay guns roses etchow can i remove commas and periods using preg replace,['php'] +108032,jquery ui sortable table handle i am having some difficults with sortable option handlewhen i usetable trsortablethisableselectionthere is no problemif i add the handle option then the sortable stops workingtable trsortable handle tdeq0thisableselectionthe linkscan anyone help me please,['jquery'] +108041,what is the meaning of auto value in a css property what is the meaning of auto value of a css property what happens when value of a css property is set to auto,['css'] +108063,how is null true a string since true is not a string type how is null true a string string s true cannot implicitly convert type bool to string bool b null true cannot implicitly convert type string to boolwhat is the reason behind this,"['c#', '.net']" +108084,why code snippet in vb is more featured than in c as i read for vbinside the snippet element add the references element and all of the required child elements that add a reference to the project when the snippet is insertedfor cvisual c code snippets to do not support the references section so a reference to systemwindowsformsdll must be added to the project manuallywhat fundamental reason prevents c to support references like vb update i saw this posted but it is not even as fullfeatured as code snippet references as code snippet references will allow you to add multiple references at once not just one by onec is supposedly more professional than vbnet one would expect c to be more featured not more limited or does professional means you have to do it the hard way as said manually pwhen will the c team catch up with vbnet team,['c#'] +108097,android best practice returning values from a dialog what is the correct way to return the values to the calling activity from a complex custom dialog say text fields date or time picker a bunch of radio buttons etc plus a save and cancel buttonsome of the techniques i have seen on the web includepublic data members in the dialogderived class which can be read by the activitypublic get accessors launching the dialog with an intent as opposed to show plus handlers in the dialog class which take input from the various controls and bundle them up to be passed back to the activity so when listener hits save the bundle is passed back using returnintentlisteners in the activity which process input from the controls that are in the dialog eg so the timepicker or datepickers listeners are really in the activity in this scheme practically all the work is done in the activityone listener in the activity for the save button and then the activity directly interrogates the controls in the dialog the activity thismisses the dialogplus more that i have already forgotten is there a particular technique that is considered the canonically correct or best practice method,['android'] +108115,how to catch the ending resize window i need catch the event endresize in wpf,['c#'] +108146,c question padding bits in unsigned integers and bitwise operations c89 i have a lot of code that performs bitwise operations on unsigned integers i wrote my code with the assumption that those operations were on integers of fixed width without any padding bits for example an array of 32 bit unsigned integers of which all 32 bits available for each integer i am looking to make my code more portable and i am focused on making sure i am c89 compliant in this case one of the issues that i have come across is possible padded integers take this extreme example taken from the gmp manual however on cray vector systems it may be noted that short and int are always stored in 8 bytes and with sizeof indicating that but use only 32 or 46 bits the nails feature can account for this by passing for instance 8sizeofintint bit i have also read about this type of padding in other places i actually read of a post on so last night forgive me i do not have the link and i am going to cite something similar from memory where if you have say a double with 60 usable bits the other 4 could be used for padding and those padding bits could serve some internal purpose so they cannot be modifiedso let us say for example my code is compiled on a platform where an unsigned int type is sized at 4 bytes each byte being 8 bits however the most significant 2 bits are padding bits would uint max in that case be 0x3f 1073741823 include stdiohinclude stdlibh padding bits represented by underscores int main int argc char argv unsigned int a 0x2a 101010101010101010101010101010 unsigned int b 0x15 010101010101010101010101010101 unsigned int c a b 1 unsigned int d c 5 10 unsigned int e d 5 01 printf a xnb xnc xnd xne xn a b c d e return 0is it safe to xor two integers with padding bitswouldnt i xor whatever the padding bits arei cannot find this behavior covered in c89furthermore is the c var guaranteed to be 0x3f or if for example the two padding bits were both on in a or b would c be 0xf same question with d and e am i manipulating the padding bits by shiftingi would expect to see this below assuming 32 bits with the 2 most significant bits used for padding but i want to know if something like this is guaranteed a 2ab 15c 3fd 3fe0e 01falso are padding bits always the most significant bits or could they be the least significant bits thanks guys edit 12192010 5pm est christoph has answered my question thanksi had also asked above whether padding bits are always the most significant bits this is cited in the rationale for the c99 standard and the answer is no i am playing it safe and assuming the same for c89 here is specifically what the c99 rationale says for a6262 representation of integer types padding bits are useraccessible in an unsigned integer type for example suppose a machine uses a pair of 16bit shorts each with its own sign bit to make up a 32bit int and the sign bit of the lower short is ignored when used in this 32bit int then as a 32bit signed int there is a padding bit in the middle of the 32 bits that is ignored in determining the value of the 32bit signed int but if this 32bit item is treated as a 32bit unsigned int then that padding bit is visible to the useras program the c committee was told that there is a machine that works this way and that is one reason that padding bits were added to c99 footnotes 44 and 45 mention that parity bits might be padding bits the committee does not know of any machines with useraccessible parity bits within an integer therefore the committee is not aware of any machines that treat parity bits as padding bits edit 12282010 3pm est i found an interesting thiscussion on complangc from a few months agobitwise operator effects on padding bits velocityreviews readerbitwise operator effects on padding bits google groups alternate linkone point made by dietmar which i found interesting let us note that padding bits are not necessary for the existence of trap representations combinations of value bits which do not represent a value of the object type would also do,['c'] +108212,longrunning asynchronous thread in wcf there is a wcf service with a longrunning asynchronous threadthis longrunning operation can run more then 1 daywe are hosting wcf service on iis 6the thread is running ok but in 20 minutes we are receiving error messagethread has been abortedthe thread is dead as a resultour wcf service configurationservicebehaviorinstancecontextmode instancecontextmodesingleservicebehaviorconcurrencymode concurrencymodesinglecan you suggest the source of this problemthank you for you answers,['c#'] +108215,python and or operators return value i was watching a 2007 video on advanced python or understanding python and at 1827 the speaker claims as some may know in python and and or return one of the two values whereas not returns always a boolean when has this been the caseas far as i can tell and and or return booleans too,['python'] +108239,getting started with nexus s nfcrfid getting started with nexus s nfcrfid can anyone provide any guidancei am interested in creating some home brew demos using the nexus s nfcrfid hardwarei think i need to find the appropriate tags and how to encode urls into tags that the nexus s can read by it is tags appnot sure about iso 143 tags or mifare etcdoes nexus s support all of libnfcif i root the device can i get access to write functionalitythanks,['android'] +108245,how to properly define colors in resource dictionaries the following does not work runtime tells me it cannot convert fae to a colorresourcedictionary xmlns xmlnsx color xkeyitemheaderback faecolorresourcedictionary,['.net'] +108247,finding if path2d selfintersects i need to find if path2d intersects itself for now i do it by simply extracting an array of lines from path and finding if any of these intersect but it has on2 complexity and so it is very slow is there a faster way to do it,['java'] +108252,right justifying numbers in an input field using this example how would i right justify numbers in the input fieldshtmlbodyform nameinput actionhtml form actionasp methodgettaxes input typenumber nametaxes value br shipping input typenumber nameshipping value alignright br input typesubmit valuesubmit form pclick the submit button the formdata will be sent to a page called html form actionasppbodyhtml,['html'] +108268,sane way to define default variable values from within a jinja template i would like to set default values for variables used in my jinja template inside of the template itself looking at the jinja2 documentation i do not see any way to do this have i missed something i see the default filter but i want to set the value template wide instead of a usebyuse basisi spent an hour or so trying to teach myself enough about the jinja2 extension writing process to write an extension tag setdefault which could look like this setdefault animal wumpas the desired effect would be equivalent to the set tag if the assignedto name was undefined but to have no effect if the assignedto name was defined i have thusfar failed to get this to workmy work around is to circumvent jinja entirely and make a compound file the area before a special marker is a yaml mapping of default values and the area after a marker is the jinja template an proof of concept implementation of this that seems to work fine isskel text animal wumpasthe car carried my animal to the vetclass errorexception pass skel rx recompile rpdefaults tnptemplate remultilineredotall env jinja2environmenttrim blockstruedef renderskel context m skel rxmatchskel text if not m raise errorskel split failed defaults yamlloadmgroupdefaults or template envfrom stringmgrouptemplate or templateglobalsupdatedefaults return templaterendercontextprint renderskel textprint renderskel text animalcatso is there a way to do the equivalent in stock jinja2 or how might one write an extension to accomplish the desired effect,['python'] +108295,why does not consolewriteline consolewrite work in visual studio express i just open a console application and i typeconsolewritelinetestbut the output window does not show this i go to the output window with ctrlwobut nothing shows up when i run my program am i nuts or is this not supported in the visual studio 2010 express,['c#'] +108305,why create an ienumerable i do not understand why i would create an ienumerable or why it is important i am looking at the example for ienumerablebut i can basically do the same thing if i just went listperson people new listpersonso whats ienumerable good for can you give me a situation where i would need to create a class that implements ienumerable,['c#'] +108317,programmically controlling a bluetooth phone i want to write a program in c that will allow me to place phone calls through my phone and receive phone calls through my pc speakers and microphone via bluetooth i have never done bluetooth programming and i am hoping someone can point me to an open source or free net library for bluetooth programming specifically to do the functions i requested i am using a broadcom bt2250 bluetooth dongle any help would be appreciated,['c#'] +108321,why am i getting this cannot modify frozen hash error i have a person model an item model a person has many items and an item belongs to a personin this code i need to delete the existing items for a person and create new ones from a parameter which is an array of hashes then i need to update one of the items fields based on one of its other fieldsperson personfindparamsidpersonperson itemseach do q qdestroyendperson items from param activesupportjsondecodeparamsperson itemsperson items from parameach do pi personperson itemscreatepi if piis ahashendpersonperson itemseach do x if xitem type type1 xitem amount 5 elsif xitem type type2 xitem amount 10 end xsaveendon the xitem amount 5 xitem amount 10 lines i get this errorruntimeerror in personscontrollersubmit itemscannot modify frozen hash how can i fix this thanks for reading,"['ruby-on-rails', 'ruby']" +108334,python converting monday tuesday wednesday to monday to wednesday i am getting a sequence of day of the week python code of what i want to dodef week days to stringweek days week days to stringsunday monday tuesday sunday to tuesday week days to stringmonday wednesday monday and wednesday week days to stringsunday wednesday thursday sunday wednesday thursday if lenweek days 2 return s and s weekdays elif week days consecutiveweek days return s to s week days0 week days1 return joinweek daysi just need the week days consecutive function the hard part hehany ideas how i could make this happenclarificationmy wording and examples caused some confusion i do not only want to limit this function to the work week i want to consider all days of the week s m t w t f my apologies for not being clear about that last night edited the body of the question to make it cleareredit throwing some wrenches into itwraparound sequence week days to stringsunday monday tuesday saturdaysaturday to tuesdayand per user470379 and optional week days to stringmonday wednesday thursday fridaymonday wednesday to friday,['python'] +108343,group multiple apps under the same icon in application launcher i want to group multiple apps under the same icon in the application launcherfor example 5 apps each thisplaying 1 different image but those 5 apps should appear as separate apps on the android market therefore they need to have different package namebut different package name means that on the android device they will appear as 5 separate apps in the application launcher which i am trying to avoidthe closest solution that i found is to listen for package added broadcast event and every time another app from those 5 are installed on the device all the already installed apps would call setapplicationenabledsetting from packagemanager to hide their icons and let the app that was just installed to handle thingsbut the icons are hidden only after rebooting the deviceis there a way to force the application launcher to refresh at runtimeor is there any other way to solve my goali am running out of optionsthanksmiha,['android'] +108360,how to show full object in chrome console var functorfunction testfunctorprop1consolelogfunctorthis only show the function part of the functor cannot show the properties of the functor in console,['javascript'] +108379,using tornado with pika for asynchronous queue monitoring i have an amqp server rabbitmq that i would like to both publish and read from in a tornado web server to do this i figured i would use an asynchronous amqp python library in particular pika a variation of it that supposedly supports tornadoi have written code that appears to successfully read from the queue except that at the end of the request i get an exception the browser returns finee 101219 010735 web868 uncaught exception get 127001 httprequestprotocolhttp hostlocalhost50 methodget uri versionhttp11 remote ip127001 remote ip127001 body headershost localhost50 acceptlanguage enusenq05 acceptencoding gzipdeflate keepalive 115 accept texthtmlapplicationxhtmlxmlapplicationxmlq09q08 useragent mozilla50 x11 u linux x86 64 enus rv19213 gecko20101206 ubuntu1010 maverick firefox3613 acceptcharset iso88591utf8q07q07 connection keepalive cachecontrol maxage0 ifnonematch 58f554b64ed24495235171596351069588d0260e traceback most recent call last file homedavedevellibpython26sitepackagestornadowebpy line 810 in stack context yield file homedavedevellibpython26sitepackagestornadostack contextpy line 77 in stackcontext yield file usrlibpython26contextlibpy line 113 in nested yield vars file homedavelibpython26sitepackagestornadostack contextpy line 126 in wrapped callbackargs kwargs file homedavedevelsrcpikapikatornado adapterpy line 42 in handle events self handle read file homedavedevelsrcpikapikatornado adapterpy line 66 in handle read selfon data availablechunk file homedavedevelsrcpikapikaconnectionpy line 521 in on data available selfchannelsframechannel numberframe handlerframe keyerror 1i am not entirely sure i am using this library correctly so i might be doing something blatantly wrong the basic flow of my code isrequest comes increate connection to rabbitmq using tornadoconnection specify a callbackin connection callback create a channel declarebind my queue and call basic consume specify a callbackin consume callback close the channel and call tornados finish functionsee exceptionmy questions are a fewis this flow even correct i am not sure what the purpose of the connection callback is except that it does not work if i do not use itshould i be creating one amqp connection per web request rabbitmqs documentation suggests that no i should not but rather i should stick to creating just channels but where would i create the connection and how do i attempt reconnects should it go down brieflyif i am creating one amqp connection per web request where should i be closing it calling amqpclose in my callback seems to screw things up even morei will try to have some sample code up a little later but the steps i described above lay out the consuming side of things fairly completely i am having issues with the publishing side as well but the consuming of queues is more pressing,['python'] +108383,php show a number to 2 decimal places whats the correct way to round a php string to 2 decimal placesnumber 520 it is a string from a dbformatted number round to 2dpnumberecho formatted numberoutput is 520how function round to 2dp definition should be,['php'] +108418,javaxsd parsing i doubt if there is something like this but i thought to ask thoughdoes anyone know if there is a library in java that reads an xsd file and creates the defined elements eg in a string format to use in the codeeg read in the following schema xml version10 encodingutf8 xsschema elementformdefaultqualified xmlnsxs xselement nameaddress xscomplextype xssequence xselement namestreet typexsstring xselement nametown typexsstring xselement namecountry typexsstring minoccurs0 xselement xssequence xscomplextype xselement xsschemaand have a string in the following format address streetstreet towntown countrycountryaddressautomatic tools do something similar ie parse a wsdl and from the types section create for example jaxb classes that can be instances of the elements defined in schemais there any library to do this updatefor example in eclipse when creating an xml descriptor for a web application it presents a tree table with all the required elements for the users to fill in according to schema how do they do it i imagine they parse the xsds included in the jarsany input is very welcomethank you,['java'] +108421,how to filter a dictionary in python d foo x bar y zoo none foobar nonei want to filter all the items whose value is none and update the foo and bar items with a particular value i triedfor i in xitems if ii none xpopi0 else xupdatei0updated but it is not working,['python'] +108429,what is the time complexity of stdsort in the c standard library what is the complexity of stdsort in the c standard library which sort is applied is there any rule of applying any particular sorting algorithm there,['c++'] +108438,python is not operator i notice there is a comparison operator is not should i literally translate it into instead of not,['python'] +108453,python message box without huge library dependancy is there a messagebox class where i can just thisplay a simple message box without a huge gui library or any library upon program success or failure my script only does 1 thing also i only need it to run on windows,['python'] +108456,wcf fastest interprocess communication a have a webaccessible via basichttpbinding wcf service which i also want to access from other net services on the same machine with as higher performance as possible i understand that the netnamedpipebinding is ideal for this but wonder what the best configuration would be given that i am only even going to be communicating with other net processes for example i need not necessarily use an encoding such as soap as this is perhaps too bulky and i do not need the compatibility with any other clients other than a net client i also do not think i need any securitywhat would be the best binding configuration for this purpose or any other configurations for that matter,['c#'] +108460,multithreading when would i use a join i see online that it says i use mythreadjoin when i want to block my thread until another thread finishes one of the things i do not get about this is what if i have multiple threadsbut generally i just do not get when i would use join or a condition that it is useful for can anyone please explain this to me like i am a fourth grader very simple explanation to understand will get my answer vote,['c#'] +108462,images showing in simulator but not on the iphone device so when i run the application from the device the pictures show up and everything works great however when i move to the device i run in about 10 out of 38 pictures that do not show up i am pulling the names for the images from an sqlite database and i already checked and the names are correct case and everything i checked the bundle and the images are correctly in theredoes memory play into effect in this i am not really sure what else could cause this to happenthankssolutionthe files somehow were not saved properly and were unable to be opened by say photoshop or paint even so with the files not being able to be open they werent showing up thanks for the help everyone,['iphone'] +108464,jqgrid rowobject inconsistencies the first page of results with a jqgrid rowobject returns expected data but then returns incomplete data for subsequent pages of results whyfirst page of resultsrowobject3 will equal 2subsequent pages of results rowobject3 will equal undefined and returning to the first page of results will also now equal undefinedmore details and some codewith jqgrid if you want to implement a custom formatter you use a parameter called rowobject that contains the row data so for instance one row of rowobject could be something like18 133 betelguese 3 photojpg 0 so my custom formatter uses some of this data to prepare a link as followsvar newval a hrefproj rowobject3 images imgval imgval aand this gives me a url likea hrefproj3imagesphotojpgphotojpgaso far so good my problem is that when i go to the next page of results in the jqgrid i lose some of this data and geta hrefprojundefinedimagesphotojpgphotojpgaif i load the page with all of the results thisplayed everything works fine however if i use paging only the first page of results will have the correct value for rowobject3 while every other result on subsequent pages will not have that rowobject valueso why is rowobject containing the correct data on what is initially loaded into the grid and seeming to lose that data when the next page of grid results appearsone thing i am seeing in firebug that i do not understand when the page initially loads i getconsolelogrowobject 18 133 betelguese 3 photojpg 0 on the next page of results where things stop working as i expect i seeconsolelogrowobjectobject photo id18 site id133 more why the change the first result is json so why am i now getting this object,"['javascript', 'jquery']" +108467,which cc header file defines a byte data type i am porting a header with this declaration struct tmaterialinfo char strname255 the texture name char strfile 255 the texture byte color 3 the color of the object the header has the following includesinclude windowshinclude stdiohinclude stdlibhinclude mathhinclude fstreaminclude vectorinclude glglh header file for the opengl32 libraryincludeglgluh header file for the glu32 libraryinclude glglauxhwhere does that byte come from,"['c++', 'c']" +108476,robust way to deploy a rack application sinatra i am looking for a robust way to deploy a rack application in this case a sinatra app requests will take a little time 02505 sec waiting on proxied http requests and there may be a decent amount of trafficshould i go with a traditional mongrel cluster setup use haproxy as a load balancer nginx rackupwhat solutions have you used and what are the advantages,['ruby'] +108480,what sorts of javascriptjquery methods do you routinely code into your sites i am coding a core javascript object for my site building in the common methods i use and wrapping a few jquery methods as wellit is built like thisvar core baseurl lang enus loggedin false msg functionstr for var i 1 len argumentslength i len i str strreplace i 1 return str include functionurl success cache ajax url url datatype script success success cache cache false etcmsg is a method to mimic c stringformat include lets me asynchronously pull in scripts there are others formatdate converts datetime string to users local time getbrowser gets browser types based on feature detection open opens a link in a new window etcthis core object lets me perform a wide array of tasks by just calling coremethod moving nearly all of my javascript code into a js file which can be cached just out of curiousity what sorts of common functions do you build into your sites,['jquery'] +108488,nodejs json parsing error i am attempting to make a facebook application with nodejs however i am having trouble in checking signed requests every time i make a request the program throws a syntaxerror unexpected token illegal as suchundefined1721599476 syntaxerror unexpected token illegalthe culprit function is belowfunction parse signed requestsigned request secret encoded data signed requestsplit2 decode the data sig encoded data0 json base64urldecodeencoded data1 data jsonparsejson error occurs here check algorithm not relevant to error if dataalgorithm dataalgorithmtouppercase hmacsha256 consoleerrorunknown algorithm expected hmacsha256 return null check sig not relevant to error expected sig cryptocreatehmacsha256secretupdateencoded data1digestbase64replacegreplaceg replace if sig expected sig consoleerrorbad signed json signature return null return datajust for testing a valid signed request would be wgvkmukb utg0l8gspvf6smzacp46977pttcrx0pueeyjhbgdvcml0ag0ioijitufdlvniqti1niisimv4cglyzxmiojeyoti4mjeymdasimlzc3vlzf9hdci6mti5mjgxndgymcwib2f1dghfdg9rzw4ioiixnti1ndk2odq3nzczmdj8mi5zv2nxv2k2t0k0u0h4y2jwtwjraddbx18umzywmc4xmjkyodixmjawltcymtu5otq3nnxqadrmb2t6s1iyamozqwlxvldqnxp2ctbmefeilcj1c2vyijp7imxvy2fszsi6imvux0dciiwiy291bnryesi6imf1in0sinvzzxjfawqioii3mje1otk0nzyifqwhy am i getting this error when it is valid json and simply using a static string of json will work fine and are there any tips to fix thisthanks,['javascript'] +108520,name vs id attribute in html are there any advantages to using div idhere instead of div namehere are they both referenced to as here,['html'] +108521,how to handle nullreferenceexception in a foreach foreach string s in myfieldgetchilds if s null handle null else handle normal value when i run my program i get a nullreferenceexception because getchilds may return null how can i make my program to continue anyway and handle the exception i cannot handle it outside of the foreach cannot explain why because it will take too much time and i am sure you guys are busy p any ideasi already tryed that wayforeach string s in myfieldgetchilds new arraylist1 if s null handle null else handle normal value but it does not work program just jump at the end of the foreach but i want it to enter the foreach instead,['c#'] +108538,how do i write a tab in python let us say i have a file how do i write hello tab alex,['python'] +108549,nullable for generic method in c how can i write a generic method that can take a nullable object to use as an extension method i want to add an xelement to a parent element but only if the value to be used is not nullegpublic static xelement addoptionalelementhis xelement parentelement string childname t childvaluecode to check if value is nulladd element to parent here if not nullif i make this addoptionalelementt then i get compiler errorsif i make this addoptionalelementnullablet then i get compiler errorsis there a way i can acheive thisi know i can make my call to the methodparentaddoptionalelementmytypebut is this the only way,['c#'] +108568,how to get an html file using python i am not very familiar with python i am trying to extract the artist names for a start from the following page geeartarthtml how do i retrieve the page my two main concerns are what functions to use and how to filter out useless links from the page,"['python', 'html']" +108570,how to create crisp background image for 1x1 android widget i am creating an a 1x1 widget and no matter what i try i just cannot get the background image looking nice and crisp i have read just about any resource i can find yet i still cannot wini am designing for the htc desirenexus 1 and would love someone to tell me when creating the background in photoshop what dpiheightwidth to use currently using 7210080 i will worry about other devices resolutions once i can get it looking nice on my test device firstalso if there is anything special i need to be putting in the layoutmainxml and widget providerxml files i simply cannot find any examples for 1x1 gadgets so have the followingmainxmllinearlayout xmlnsandroidandroidididwidgetandroidlayout widthfill parentandroidorientationverticalandroidbackgrounddrawablebackground androidlayout gravitycenter androidlayout heightwrap contentwidget providerxmlappwidgetprovider xmlnsandroidandroidminwidth72dipandroidminheight72dipandroidupdateperiodmillis60androidinitiallayoutlayoutmainany help would be greatly appreciated,['android'] +108594,changing the font and font size in a textarea field using the following code samplehtmlbodyscript language javascriptmaxl240var bname navigatorappnamefunction talimittaobj if taobjvaluelengthmaxl return false return truefunction tacounttaobjcnt objcntcreateobjectcnt objvaltaobjvalue if objvallengthmaxl objvalobjvalsubstring0maxl if objcnt ifbname netscape objcnttextcontentmaxlobjvallength elseobjcntinnertextmaxlobjvallength return truefunction createobjectobjid if documentgetelementbyid return documentgetelementbyidobjid else if documentlayers return evaldocument objid else if documentall return evaldocumentall objid else return evaldocument objidscriptfont facearial font size2maximum number of characters for this text box is 240fontbrtextarea onkeypressreturn talimitthis onkeyupreturn tacountthismycounter namemessage rows6 wrapphysical cols42textareabrfont facearial font size2you have bspan idmycounter240spanb characters remaining for your messagefontbodyhtmlhow do i change the font and font size in the textarea,"['javascript', 'html', 'css']" +108619,undefined reference to forkpty so i am developing my project in eclipse in ubuntu 1004 i have the following lines of codeinclude ptyhpid t pidint masterpid forkptymaster null null nullbut when i try to build it within eclipse i get the errorundefined reference to forkptyany idea how to solve this problem,['c++'] +108620,how to log an int on android logdgetclassgetname bla bla blato loghow can i show an int value what is the equivalent of cs d and so on,['android'] +108622,enable shared from this and inheritance i have got a type which inherits from enable shared from thistype and another type that inherits from this type now i cannot use the shared from this method because it returns the base type and in a specific derived class method i need the derived type is it valid to just construct a shared ptr from this directlyeditin a related question how can i move from an rvalue of type shared ptrbase to a type of shared ptrderived i used dynamic cast to verify that it really was the correct type but now i cannot seem to accomplish the actual move,['c++'] +108633,why android is built on a vm dalvik i am curious to know what made google choose to develop androids framework on java vmin the process of writing code for android for nearly 6 months now i observed that running code on a vm in a resource limited platform is really slow there is a lot of overhead involved i know that java is portable etc etc is it not possible at all to use native languages and get both performance and features offered by a vm for performance oriented applications one still ends up writing native code and wrap it with jniso why did google choose this particular stack arm based core understandable arm is the best for mobile deviceslinux open sourcejava vm my questionedit i know java jvm runs on par with c applications on my server but not on androidwith respect to android its not the case as a matter of my experience a c code wrapped with jni runs far faster than java code note i have even checked with exact same code from a static block in java i will agree with your answer on any other platform,['android'] +108641,select element with specific data by using jquery is it possible to set some data by using the jquery data method and then later query it something like find all elements with data foo true,"['javascript', 'jquery']" +108661,how to check for of lines using jquery example a div with width of 30px with the words this is text let us say that since the width is narrow it renders on the page like thisthisistext3 lines is there a way in jquery to tell how many lines it takes to render to the page for example something like containerlinecountbusiness purpose if my content exceeds a certain number of lines i want to manipulate it so that a scroll bar does not appear but i also have a fixed height so i do not want to mess with overflow css propthanks,['jquery'] +108664,increasing the depth of cprofiler in python to report more functions i am trying to profile a function that calls other functions i call the profiler as followsfrom mymodule import foodef start fooimport cprofile as profileprofilerunstart output filep pstatsstatsoutput fileprint name print psort statsnameprint all stats pprint statsprint cumulative top 10 psort statscumulativeprint stats10i find that the profiler says all the time was spend in function foo of mymodule instead of brekaing it down into the subfunctions foo calls which is what i want to see how can i make the profiler report the performance of these functionsthanks,['python'] +108667,java generics arraylist initialization it is known that arraylist init should be like thisarraylista a new arraylistaarraylistinteger a new arraylistnumber compiletime errorso why does java allow these 1 arraylist extends object a1 new arraylistobject2 arraylist a2 new arraylistintegerthen if they are correct why does not allow these 1 a1add32 a2add3the compiler message is the method addint capture1of extends object in the type arraylist is not applicable for the arguments intmore general 1 a1addnull e 2 a2add ei read about this but it is good to hear from you thanksthe other amusing point is arraylistarraylist a new arraylistarraylist correct arraylist a new arraylist wrong i know it is reason but i have some question in my mind that mentioned above,['java'] +108680,c difference between throw new badconversionx and throw badconversionx class badconversion public stdruntime error public badconversionstdstring const s stdruntime errors inline stdstring stringifydouble x stdostringstream o if o x throw badconversionstringifydouble throw new badconversionstringifydouble return ostr q1 when we throw an exception in the function what is the difference between throw new classname and throw classnameq2 which one is betterthank you,['c++'] +108686,webbrowser control prevent rightclick in my application i have a form that contains a browser control in which i thisplay an ssrs report i would like to prevent the user from rightclicking in the browser control and being shown the popup menu ideally i would like the rightclick to do nothing is there a way i can accomplish this,['c#'] +108704,grouping switch statement cases together i may be over looking something but is there a simple way in c to group cases together instead of writing them out individually i remember in basic i could just doselect case answercase 1 2 3 4example in c for those that need itinclude iostreamhinclude stdiohint main int answer cout how many cars do you have cin answer switch answer case 1 case 2 case 3 case 4 cout you need more cars break case 5 case 6 case 7 case 8 cout now you need a house break default cout what are you a peaceloving hippie freak cout npress enter to continue endl getchar return 0,['c++'] +108709,detect the location of appdatalocallow i am trying to locate the path for the appdatalocallow folderi have found an example which usesstring folder cusers environmentusername appdatalocallowwhich for one is tied to c and to users which seems a bit fragilei tried to useenvironmentgetfolderpathenvironmentspecialfolderlocalapplicationdatabut this gives me appdatalocal and i need locallow due to the security constraints the application is running under it returned blank for my service user as well at least when attaching to the processany other suggestions,"['c#', '.net']" +108716,asynctask onpostexecute never gets called i am not sure what i am doing wrong but onpostexecute never gets calledcreated a base class called baseactivityjavafrom my original activity i extended this classplaced posttoopenfeint class inside baseactivitycalled it from the ui thread from the main activity my doing new posttoopenfeintexecutethe onpreexecute doinbackground gets triggered but for some reason the onpostexecute never gets calledthank you in advancedave private class posttoopenfeint extends asynctaskvoid void void nonjavadoc see androidosasynctaskdoinbackgroundparams override protected void doinbackgroundvoid params does all the work here return null nonjavadoc see androidosasynctaskonpostexecutejavalangobject override protected void onpostexecutevoid result todo autogenerated method stub superonpostexecuteresult toastmaketextmainscreenthis done syncing toastlength longshow nonjavadoc see androidosasynctaskonpreexecute override protected void onpreexecute todo autogenerated method stub superonpreexecute toastmaketextmainscreenthis about to sync all your scores toastlength longshow looking into it more this is what i was able to observe for example if i place this call new posttoopenfeintexecuteright after oncreate of the activity then everything works fine if i place this call say inside a button listenersettingsbuttonsetonclicklistenernew viewonclicklistener public void onclickview v new posttoopenfeintexecutethe onpostexecute never gets called not sure what i am doing wrong the restriction i read was to call this from ui thread and i am calling it from ui thread,['android'] +108723,combine user with prefix error with setuppy install i was trying to install python packages a system i recently gained access to i was trying to take advantage of pythons relatively new per user sitepackages directory and the new option user the option is currently undocumented however it exists for python 26 you can see the help by running python setuppy install helpwhen i tried runningpython setuppy install useron any package i downloaded i always got the following errorerror cannot combine user with with prefixexec prefixhome or install platbasethe error was extremely perplexing because as you can see i was not providing the prefix execprefix installbase or installplatbase flags as command line options i wasted a lot of time trying to figure out what the problem was i document my answer below in hopes to spare some other poor soul a few hours of yak shaving,['python'] +108752,how do stateless servers work i try to understand this normally each time user login system server side will create a session while user client side there is cookie when people talk about stateless serverside stateful client side what do they mean server side no need use session keep track user only use cookies on client side to check user mean if i change server user will not notice it and still can resume using the service how to configure springsecurity to to do this,['java'] +108754,how to implement a memory heap was not exactly sure how to phrase the title but the question isi have heard of programmers allocating a large section of contiguous memory at the start of a program and then dealing it out as necessary this is in contrast to simply going to the os every time memory is neededi have heard that this would be faster because it would avoid the cost of asking the os for contiguous blocks of memory constantlyi believe the jvm does just this maintaining its own section of memory and then allocating objects from thatmy question is how would one actually implement thisthanksdragonwrenn,"['c++', 'c']" +108778,is flying saucer project closed someone know what happened with flying saucer project site down and i cannot get access to manuals updi have solved problem it is seems thay have problems with dnsi did put 20416104198 xhtmlrendererdevjavanetto my hosts file and it is happened all works fine,['java'] +108779,python threads all executing on a single core i have a python program that spawns many threads runs 4 at a time and each performs an expensive operation pseudocodefor object in list t threadtargetprocess argsobject if fewer than 4 threads are currently running tstart otherwise add t to queuebut when the program is run activity monitor in os x shows that 1 of the 4 logical cores is at 100 and the others are at nearly 0 obviously i cannot force the os to do anything but i have never had to pay attention to performance in multithreaded code like this before so i was wondering if i am just missing or misunderstanding somethingthanks,['python'] +108784,uialertview add 3 buttons i created uialertview and add two buttons now i need to add one more button in alert viewhow to edit my code to add one more buttonuialertview alert uialertview alloc initwithtitlerefresh messageare you want to refresh data delegateself cancelbuttontitlecancel otherbuttontitlesok nilalert showalert releaseif anyone knows the solution please help methanks,"['iphone', 'objective-c', 'ios']" +108796,how to find the 404 error cause when i am using a webview based application and the server fails in iphone sdk i am implementing a webview based application in that i need to find out a way when the 404 error occurred anyones help will be much appreciatedthanks to allmonish,['objective-c'] +108798,jquery create a form and add elements to it programmatically hi i need to create a form and add elements to it programaticallyform formformformappendinput typebutton valuebuttonthis does not seem to work right,['jquery'] +108816,will an inner transaction scope roll back if the outer transaction scope dosent complete i have two transaction scopes one within another i would love to know if the inner transaction scope will be rolled back after it has been committed and the outer one does not complete,['c#'] +108832,cannot programmatically hide uibutton created with ib my ios uibutton is correctly linked from ib to an iboutlet in my view controller as i can change its title from my code ieselfmybutton settitlenew title forstateuicontrolstatenormal workshowever selfmybutton sethiddenyes does not workorselfmybuttonhidden yes does not workwhats going on how can i make mybutton thisappearupdate some additional infoheres the code related in to my uibuttonin my h fileiboutlet uibutton mybuttonibactionpushedmybuttonidsenderproperty nonatomicretain uibutton mybuttonin my m filesynthesize mybutton voidpushedmybuttonidsender selfmybuttonhidden yes voiddealloc selfmybutton release,"['iphone', 'objective-c', 'ios']" +108854,how to convert cmsamplebufferuiimage into ffmpegs avpicture i am trying to encode iphones camera frames into a h264 video using ffmpegs libav libraries i found in thisapples article how to convert cmsamplebuffer to uiimage but how can i convert it to ffmpegs avpicturethanks,['iphone'] +108855,objectvalid returns false but objecterrorsfull messages is empty i am confuse about objects that i cannot save simplified model is class subscription activerecordbase belongs to user class name user foreign key user idhas many transactions class name subscriptiontransaction validates presence of first name message ne peut aatre videvalidates presence of last name message ne peut aatre videvalidates presence of card number message ne peut aatre videvalidates presence of card verification message ne peut aatre videvalidates presence of card type message ne peut aatre videvalidates presence of card expires on message ne peut aatre videattr accessor card number card verificationvalidate on create validate card def validate card unless credit cardvalid credit carderrorsfull messageseach do message errorsadd to base message end endenddef credit card credit card activemerchantbillingcreditcardnew type card type number card number verification value card verification month card expires onmonth year card expires onyear first name first name last name last name endend and in my subscription controller if subscriptionsave do somethingelse debugger means breakpoint where i try subscriptionerrorsfull messages do something elseend i tried to use rubydebug for this adding a breakpoint where i do some testssubscriptionvalid false subscriptionerrorsfull messages subscriptionsave activerecordrecordinvalid validation failedwhich explains that activerecord does not allow the save method unfortunately i cannot know why the object is invalidif you have any idea thank you,"['ruby-on-rails', 'ruby']" +108873,is there a java equivalent for pythons map function i would like to easily transform a collection list of objects of class a to a collection of objects of class b just as pythons map function does it is there any wellknown implementation of this some kind of library i have already searched for it in apache is commonslang but with no luck,"['java', 'python']" +108885,how to save tagskeywords in database i want to create a simple tags system using php and mysql so that users can add few tags via form my question is that should i save the tags as an array in single database column eg tag1 tag2 tag3 or i should have separate columns in database table where i should save each tag in each column i hope my question is clearthanks,['mysql'] +108889,where to store application constants in zend i have a few constants that i will need to define for my application for example site key which would contain a random key for salt passwordsi am not sure where i should define those though i thought of placing them in publicindexphp but that seems a bit messy is there a specific place where they should go according to zend or somethingthanksediti am trying to do it this wayin my applicationini i have thissiteglobalsitekey testand in my bootstrapphp fileprotected function initglobalsconfig thisgetoptionsdefinesite key configsiteglobalsitekeystill this is not working when i try to echo site key in my controller like thisecho site keyit does not show anything any ideas,['php'] +108919,order multidimensional array recursively at each level in php i have an array of this formarray first level array dir 3 array subdir 1 array file 2mp4 stdclass object name file 2mp4 file 1mp4 stdclass object name file 1mp4 dir 1 array subdir 2 array file 6mp4 stdclass object name file 6mp4 file 9mp4 stdclass object name file 9mp4 file 7mp4 stdclass object name file 7mp4 subdir 1 array file 8 stdclass object name file 8mp4 i need to order it like thisarray first level array dir 1 array subdir 1 array file 8 stdclass object name file 8mp4 subdir 2 array file 6mp4 stdclass object name file 6mp4 file 7mp4 stdclass object name file 7mp4 file 9mp4 stdclass object name file 9mp4 dir 3 array subdir 1 array file 1mp4 stdclass object name file 1mp4 file 2mp4 stdclass object name file 2mp4 i browsed through other similar questions and i have been trying to solve it with usort but i could not get my head around it sany idea,['php'] +108922,jquery each click function not working edit this works but not sure why buttoneachfunction thisbind click function alertthisval i am not sure why this is not working right now i am just trying to output an alert with the button value but it is not working on my page i do not get any console errors in firebug and cannot see anything that would prevent it from working my html looks like thistable idaddressbooktablethead tr thnameth thactionth trtheadtbody tr td7892870td tdbutton idbutton20 classcustomaction valuexy89 nameinfoclickbuttontd tr tr td9382098td tdbutton idbutton21 classcustomaction valuexy544 nameinfoclickbuttontd tr tr td3493900td tdbutton idbutton22 classcustomaction valuexy231 nameinfoclickbuttontd trtbodytableand the code looks like this buttoneachfunction thisclickfunction alertthisval but clicking on it does nothing at all am i using it incorrectly,['jquery'] +108923,when would you use the this keyword in php when would you use the this keyword in php from what i understand this refers to the object created without knowing the objects namealso the keyword this can only be used within a methodan example would be great to show when you can use this,['php'] +108948,how to get iphonestyle overscrolling in android 23 gingerbread in the stock gingerbread release overscrolling is indicated with an orange flash however the release notes and some of the api docs seem to indicate that there is support for iphonestyle overshoot overscroll behavior for example seehere however it is not clear how to make these work simply setting drawables with these methods does not change the behavior does anybody know of a way to do this,['android'] +108961,continuous build infrastructure recommendations for primarily c greenhills integrity i need your recommendations for continuous build products for a large 12mloc software development project characteristicsclearcase revision controlapprox 80 c 15 java 5 script or lowlevel compiles for green hills integrity os but also some windows and jvm chunksmostly an embedded system also includes some ui pieces and some development support simulation tools config tools etceach notional version of the deliverable includes deployment images for a number of boards ui machines etc 10 separate images 5 thistinct operating systemsneed to maintaintrack many simultaneous versions which notably are built for a variety of different board support packagesbuild cycle time is a major issue on the project need support for whatever features help address this mostly need to manage a large farm of build machines i guess operates in a secure environment this is a govt program edited to add this is a classified program outsourcing the build infrastructure is a nonstarterinterested in any best practices or peripheral guidance you might offer the build automation issues is one of several overlapping best practices that appear to be missing on the program but try to keep your answers focused on build infrastructure piece and observations directly relatedcost is not the driving concern scalability and ease of retrofitting onto an existing infrastructure are keyedited to address dans comment,['c++'] +108966,how to get the row number from a datatable i am looping through every row in a datatableforeach datarow row in dtrows i would like to get the index of the current row within the dt datatable for exampleint index dtrowscurrent row numberhow do i do this,['c#'] +108975,draw semi transparent overlay image all over the windows form having some controls draw semi transparent overlay image all over the windows form having some controls such that all its child controls should be visible but you cannot click them it should just like we see some things through some semi transparent black mirrori have tried using transparent control that is subclassing panel control and drawing image over that control however all the controls are fully visible,['c#'] +108986,route alias in rails i have a model stories in rails 3i want to make an alias books for stories so i can have routes books192 instead of stories192 and also that all my generated links eg link to point to books routes instead of stories routeshow can i do thatthanks,['ruby-on-rails'] +109003,forwarding emails with a php script we have a croned php script that checks an inbox every ten minutes the purpose of this script is to handle stop to quit functionality for our sms notification service we provide if the script finds any emails with the word stop at the beginning of the email we remove the user from our notification databaseto cover our bases wed like any emails that do not meet the above criteria to be forwarded on to another email address which is an alias that several people receive and check hourly however were running into problems forwarding the emails from this php scriptknowing how the mail function of php works it is quite obvious we need to reinsert the headers before mailing however mime multipart emails always get sent as a garble of text including the barriers and any base64 encoded attachmentsdoes anyone know of a simple way to take an email message and forward it on properly using a php scriptwere using the native imap functions built in to php 5 we also have access to the pear mail module however we have been unable to find any examples or people doing similar tasks by searching google,['php'] +109005,is it safe to install sql server 2008 r2 and mysql sidebyside on windows server 2003 enterprise edition are there any drawbacks to such a configuration,"['sql', 'mysql']" +109006,populate tables with test data whilst maintaining relational integrity i have a mysql database with innodb tables many of which have foreign keysi was going to write a script to populate the tables with test data 1020k rows or more but i thought i ought to ask if there is something already out there that can generate test data based on the field types but ensure relational integrity at the same timei have seen and have downloaded the script at generatedatacom but as far as i can see it is clever but it would not read the tables within your db and generate data based on what it finds you have to do it all manually,['mysql'] +109007,why proces exited method not being called i have following code but why the processexited method is never called it is the same if i do not use windows shell startinfouseshellexecute falseprocestartinfo startinfo new procestartinfostartinfocreatenowindow truestartinfouseshellexecute truestartinfowindowstyle processwindowstylehiddenstartinfofilename pathstartinfoarguments rawdatafilenamestartinfoworkingdirectory utilgetparentdirectorypath 1try process correctionprocess procestartstartinfo correctionprocessexited new eventhandlerprocessexited correctionprocesswaitforexit status trueinternal void processexitedobject sender systemeventargs e print out here,"['c#', '.net']" +109010,encryption with aes256 and the initialization vector i have a question relating to the use of an initialization vector in aes encryption i am referencing the following articles posts to build encryption into my program 1 java 256bit aes encryption2 i was originally following ericksons solution from the first link but from what i can tell pbkdf2withhmacsha1 is not supported on my implementation so i turned to the second link to get an idea for my own iterative sha256 hash creation my question comes in how the iv is created one implementation 1 uses methods from the cypher class to derive the iv where are the other 2 uses the second 16 bytes of the hash as the iv quite simply why the difference and which is better from a security standpoint i am kinda confused to the derivation and use of ivs as well i understand what they are used for just not the subtler differences so any clarification is also very welcomei noticed that the second link uses aes128 rather than aes256 which would suggest to me that i would have to go up to sha512 is i wanted to use this method this seems like it would be an unfortunate requirement as the users password would have to be 16 characters longer to ensure a remotely secure hash and this app is destined for a cell phonesource is available on request though it is still incompletethank you in advance,"['java', 'android']" +109044,mediawiki rollback bot mass undo troll actions i want to rollback every page a certain ip address has edited and delete any pages they have madehow can i do this with either a bot or a plugin or even default functionality to do this i have found the bot documentation here but have not been able to find any source codes with getting user contributions and rolling backthanks for your help this should preferably be in php,['php'] +109055,for improving my programming skills i want to follow learn a new language a year what we can learn in 2011 i want to learn a new programming language in 2011 i am a java progmrammer with not more than a year experience i want to learn something which is really new and exciting but not related to mobiles iphone android ipad symbian,['java'] +109063,understanding the concept of javascript callbacks with nodejs especially in loops i am just starting with nodejs i have done a little ajax stuff but nothing too complicated so callbacks are still kind of over my head i looked at async but all i need is to run a few functions sequentiallyi basically have something that pulls some json from an api creates a new one and then does something with that obviously i cannot just run it because it runs everything at once and has an empty json mostly the processes have to run sequentially but if while pulling json from the api it can pull other json while it is waiting then that is fine i just got confused when putting the callback in a loop what do i do with the index i think i have seen some places that use callbacks inside the loop as kind of a recursive function and do not use for loops at allsimple examples would help a lot,['javascript'] +109072,how do i use the enum value from a class in another part of code coming from a c background from a night course at a local college i have sort of started my way in c having a lot pain getting used to the syntax i am also still very green when it comes to coding techniquesfrom my winmain function i want to be able to access a variable which is using an enum i declared in another classinside corehclass core public enum game mode init menus gameplay game mode gamemode core core otherfunctionsinside maincppcore coreint winapi winmain startup code here coregamemode coregame modeinit etcbasically i want to set that gamemode to the enum value of init or something like that from my winmain function i want to also be able to read it from other areasi get the errorexpected primaryexpression before tokenif i try to use coregamemode coregame modeinit then i get the same errori am not fussed about best practices as i am just trying to get the basic understanding of passing around variables in c between files i will be making sure variables are protected and neatly tucked away later on once i am use to the flexibility of the syntaxif i remember correctly c allowed me to use enums from other classes and all i had to do was something like coreenumnameenumvaluei hope what i am wanting to do is clear as i have no idea what a lot of the correct terminology is,['c++'] +109082,what is the use of static constructors please explain to me the use of static constructor why and when would we create a static constructor and is it possible to overload one,['c#'] +109084,set left margin for a paragraph in html i want to start a paragraph after putting 5 spaces and all the lines beneath the first line should come in a straight line imean all the lines in the paragraph should have 5 spaces before it startsi am getting this paragraph from databsei want a html tag that will define left margin for a complete paragraph,['html'] +109086,what does mean i am a relative newbie to objectivec only studied arron hillegrass book and am confused by the following snippit of code i have found in one of apples code examples in particular what does the meanid initwithnumbersnsarray numbers self super init if self nil self numbers numbers copy return selfin the header file numbers is declared as nsnumber number the underscore has some significance from what i recall reading somewhere but that too eludes me at the momentthanksrobin,['objective-c'] +109092,must jdbc resultsets and statements be closed separately although the connection is closed afterwards it is said to be a good habit to close all jdbc resources after usage but if i have the following code is it necessary to close the resultset and the statementconnection conn nullpreparedstatement stmt nullresultset rs nulltry conn retrieve connection stmt connpreparestatement some sql rs stmtexecutequery catchexception e error handling finally try if rs null rsclose catch exception e try if stmt null stmtclose catch exception e try if conn null connclose catch exception e the question is if the closing of the connection does the job or if it leaves some resources in use,['java'] +109119,mysql command line would not open i just installed the latest version of mysql until now i had it on windows xp but i wanted to install this on another computer with windows 7even after configuring everything correctly the mysql client would not show up in the start folder so i went to the bin folder of mysql and tried opening mysqlexe but it would immediately close downi then tried opening mysqlexe in cmd this is what i getcprogram filesmysqlmysql server 55binmysqlerror 1045 280 access denied for user odbclocalhost using password noany ideas how i can get this to work,['mysql'] +109124,what is a table prefix what is a table prefix and what are their advantages and thisadvantages this is in relation to mysql,['mysql'] +109126,swing to swt conversion which thisadvantages we are considering to port our swing applications to swtjface to get a more native look and feel more ui rendering speed and less bugsis there anybody who already has done such a port and wants to share some information especially thisadvantages we should expect thanks in advanceps maybe this rather should be a wiki because it makes no sense to accept one as the ultimate answer,['java'] +109132,solr sunspot determine indexing language at runtime dynamically choose analyzers i would like to use solr sunspot to index a bilingual fren site the issue model post can be written both in french or in english i can determine at runtime what is the language but i also need solr to index the model accordingly eg for french models i would need a french stemmer filter clasolrsnowballporterfilterfactory languagefrenchwhat are my options can i change solr analyzers at runtime can i make a set of analyzers for each language,['ruby-on-rails'] +109158,stackoverflow userpic generation identicons i an creating a website in c aspnet and want to use a feature similar to stackoverflow every time a new user registers on the stackoverflowcom he is assigned a default user picture until he has a gravatar now every picture is different from the previous one so it is sure it is generated i want to know how can this be done in cnote i do not think it is a meta question so please do not move it there,"['c#', '.net', 'asp.net']" +109161,java for software developers i am a net developer and have been for a while now i work for an organization that was just recently acquired by a larger company whose primary development language is java there are a few net developers but the ratio of net to java has decreased substantially now that the teams have mergedthat being said i have decided it would be best for me to start java development however most of the books i have seen so far for learning java all take a very basic approach what is a class oop principles etc etc i am comfortable with this part of development and do not need a primer unless there are differences so profound that someone recommends the fundamentals from a java perspective anyway i am looking for a book recommendation for java development from a software developers perspective that thiscusses todays techniques for example mvc architecture application best practices i am a web developer this includes web services is it worthwhile to work with jsps or consider ruby instead etc etc a huge bonus would be learning through doing something like murachs where i can step through a project from start to finish and is light enough on fundamentals that i do not get bored i am hoping to walk away with enough basic knowledge to volunteer for some internal projects and grow from therei am sorry if my question is needlessly broad but i am struggling to find a starting point aside from my eclipse installation i am doing this on ubuntu deliberately avoiding windowsthanks for any direction or insight you can offeredit after thiscussing with a coworker and reading berts great suggestion all of them have been excellent thank you all very much it turns out the main focus is on ee and glassfish they use netbeans for development since it is tightly bound to glassfishthis does not mean much to me except that i think the parallel drawn is iisweb apps to win32 apps but perhaps it will help clarify some of the more openended questions in my op,['java'] +109166,static member function and threadsafety in c when you have local variables in a static member function does it mean those local variables are also implicitly static or are they really localexamplestatic void myclasomefuncint someintint myint someint is myint really a local variable or does it change due to the static qualifier at function levelalso different threads from a thread pool running this function does myint need to be protected by a lock assuming that all values passed to it are different and have no relation to each otheredit thanx for the answers now what if i passed in a boostshared ptrt knowing that this object would not be concurrently being used by another thread not sure if one can really guarantee that or can you i guess a raw ptr passed in would need some protection if it were being used all over,['c++'] +109171,android which versions of android should i support i have been working on this project for my company and my boss said we want to target as many devices as possible so make it work for 16 which seriously tied my hands at some timeswhat i am wandering now is is it worth supporting 16 in generalwith the release of 23 and the fact that most recent phones have been updated to 2x what place is left for 16 devices,['android'] +109176,android onactivityresult is always 0 this has been killing me for two days now i have a main activity a which calls a second activity b activity b simply presents the user with a listview when i press an item on the list view i want a couple of strings to be passed back to the main activity a and activiy b will finishthe problem is i always get a resultcode of 0 and the data bundle is null i really do not understand why this is happeninghere is my codestart activity b for resulttestsetonclicklistenernew viewonclicklistener override public void onclickview v intent i new intentrecipeactivitythis browseloadrecipesclass startactivityforresulti recipe chooser this starts the second activity fine activity b populates a listview and when i click an item i am trying to send some data back to the calling activity aany text at the moment so i used the following in activity b lvsetonitemclicklistenernew onitemclicklistener override public void onitemclickadapterview a view v int position long id bundle bundle new bundle bundleputstringtext please work pleaasee intent mintent new intent mintentputextrasbundle setresultresult ok mintent finish in the calling activity i have the following listening for the return as followsprotected void onactivityresultint requestcode int resultcode intent data switchrequestcode todo case recipe chooser toastmaketextgetapplicationcontext in recipe return toastlength shortshow toastmaketextgetapplicationcontext resultcode is stringvalueofresultcode toastlength shortshow if resultcode result ok bundle b getintentgetextras toastmaketextgetapplicationcontext returned bgetstringtext toastlength longshow if resultcode result canceled break i can see that the request code is correctly returned but the resultcode is always a 0 and the data is always a nulli have ran through the debug and the setresult is doing its job and the bundle does indeed have the data i am passing but it is lost at some point along the wayis there something in the manifest i am missing or something it is killed my progress on this project so farany help would truly be appreciatedthanksdean,['android'] +109196,net visual studio 2008 svn reading revision number at compile time does any one know if there is a way to access a solutionprojects revision number from svn and incorporate this in application code at compile timethanks,['c#'] +109206,php difference between and and possible duplicatephp and or keywords dear alli would like to get clear in mind about conditional operators in php please clarify me what is the difference between and and in phpthanks in advance,['php'] +109215,facebook api session still exists after user logout i am using facebook phpsdk in my iframe facebook app to get user login statusright after i sign out using facebook account log out link the session is not destroyed yet i must wait a few minutes before old session expires then my app will again get the correct login statusi expect the facebook to kill itself and the session when user signs out how do i manually kill the sessionhere is my codeinitparams array appid confapp id secret confsecret api key cookie truefb new facebookinitparamsfbgetsession will return a session object eventhough user signed outsolvedcalling fbapime will destroy the session if user has previously logged outi have changed my code as followingif session try fbuid fbgetuser me fbapime catchfacebookapiexception eif the api call is unsuccessful session will be set to null very weird behavior i do not explain everything that is going on here but it solved my problem of having residual session object not being updated via getsession method,['php'] +109218,synthesizing a property without instance variables i thought i understood property and synthesize but i did some experimenting and i cannot figure out why the below what i thought was broken code worksas you can see there is no instance variable that corresponds to the name property does objectivec somehow create an instance variable if it does not find an instance variable with the same name and typeheaderimport foundationfoundationhinterface addresscard nsobject property copy nonatomic nsstring namevoid printendimplementationimport addresscardhimplementation addresscardsynthesize namevoid print nslogname selfnamevoid dealloc name release super deallocendtestint main int argc const char argv nsautoreleasepool pool nsautoreleasepool alloc init addresscard ac addresscard alloc init acname brandon ac print ac release pool drain return 0,['objective-c'] +109244,useful stock sql datasets does anyone know of any resources that provide good useful stock datasets for example i have downloaded a sql script that includes all of the us states cities and zipcodes this saved me a lot of time in a recent application where i wanted to be able to do lookups by geography are any of you aware of other useful datasets that are freely available for downloadfor exampleblacklisted ip addressesnames of collegesuniversitiesnames of corporationsstock symbolsanyone have any recommendationseditas an example here is the location where i found a mysql script containing all of the us zip codes and their corresponding latitudelongitude has anyone else found similarly useful datasets in sql that can be easily imported and usededit 2to clarify what type of datasets i am talking about i am referring to datasets that can be immediately useful for applications can be applied across a variety of scenarios and typically represent information that is easy to find for small cases but harder to compile for larger data sets the zip code database is a great example to me it is not hard to get the latlong for a single given zip code but it is a bit more time consuming to get the values for all valid zip codes in the us this data is also not useful to a single industry or business sector but can be applied across a range of applications,['sql'] +109255,can java render translucent text using subpixel aa i have found that while rendering opaque text in java latest version 6u23 uses subpixel aa just fine rendering translucent text does notsubpixel aa the same text for which only the color has been changed from 0xf to 0xbf as you can see the translucent text is clearly standard aa and rather than a clean translucent rendering it has that awful 90s spidery appearanceis this due to a technical limitation for subpixel aa in general or a bug in java or just because java does not even try for translucent text or have i missed somethinggraphics initializationdbgraphicsgraphics2ddbimagegetgraphicsifdctrootpropertiesgetbooleanantialiastrue try map hntsmapdctrootawtcomponentgettoolkitgetdesktoppropertyawtfontdesktophints set aa on overall note general aa must be off for subpixel aa to be honored text widgets must do this themselves dbgraphicssetrenderinghintrenderinghintskey antialiasingrenderinghintsvalue antialias on ifhntsnull set font rendering hints from desktop dbgraphicsaddrenderinghintshnts else try set text aa to fontspecified gasp aa java 6 dbgraphicssetrenderinghintrenderinghintskey text antialiasingrenderinghintsclassgetfieldvalue text antialias gaspgetnull catchthrowable thr3 set text aa to default dbgraphicssetrenderinghintrenderinghintskey text antialiasingrenderinghintsvalue text antialias on catchthrowable thr dctrootlogprintlnantialiasing not supported on this jvm thr dctrootsetpropertyantialiasfalse turn off aa for subsequent painting else try dbgraphicssetrenderinghintrenderinghintskey antialiasingrenderinghintsvalue antialias off dbgraphicssetrenderinghintrenderinghintskey text antialiasingrenderinghintsvalue text antialias off catchthrowable thr ignore exception text renderingobject oaathisablegeneralaagcgcdrawstringtlxxtyxametgetheightrestoregeneralaagcoaastatic private volatile boolean hasrenderinghintstrue static init main static methods thisable the general antialiasing rendering hint returning whether the old value was renderinghintsvalue antialias on p this method is needed for text rendering due to a bug in awt as of java 6 20 when general aa is on text is not rendered using subpixel aa so general aa has to be turned off before rendering text and turned back on when done this method abstracts that work and deals with the possibility that the jvm does not support rendering hints such as is the case with jme jvms static public object thisablegeneralaagraphics2d gc object oldnull ifhasrenderinghints try oldgcgetrenderinghintrenderinghintskey antialiasing gcsetrenderinghintrenderinghintskey antialiasingrenderinghintsvalue antialias off catchnoclassdeffounderror thr hasrenderinghintsfalse catchnosuchfielderror thr hasrenderinghintsfalse catchnosuchmethoderror thr hasrenderinghintsfalse return old thisable the general antialiasing rendering hint returning whether the old value was renderinghintsvalue antialias on p this method is needed for text rendering due to a bug in awt as of java 6 20 when general aa is on text is not rendered using subpixel aa so general aa has to be turned off before rendering text and turned back on when done this method abstracts that work and deals with the possibility that the jvm does not support rendering hints such as is the case with jme jvms static public void restoregeneralaagraphics2d gc object val object oldnull ifhasrenderinghints valnull try gcsetrenderinghintrenderinghintskey antialiasingval catchnoclassdeffounderror thr hasrenderinghintsfalse catchnosuchfielderror thr hasrenderinghintsfalse catchnosuchmethoderror thr hasrenderinghintsfalse,['java'] +109283,is postgres better than mysql when one needs to add a column to a table with millions of rows were having problems with mysql when i search around i see many people having the same problem i have joined up with a product where the database has some tables with as many as 150 million rows one example of our problem is that one of these tables has over 30 columns and about half of them are no longer used when trying to remove columns or renaming columns mysql wants to copy the entire table and rename with this amount of data it would take many hours to do this and the site would be offline pretty much the whole time this is just the first of several large migrations to improve the schema these are not intended as a regular thing just a lot of cleanup i inheritedi tried searching to see if people have the same problem with postgres and i find almost nothing in comparison talking about this issue is this because postgres is a lot better at it or just that less people are using postgres,['mysql'] +109317,how do i know if a mysql table is using myisam or innodb engine in mysql there is no way to specify a storage engine for a certain database only for single tables however you can specify a storage engine to be used during one session withset storage engineinnodbso you do not have to specify it for each tablehow do i confirm if indeed all the tables are using innodb,['mysql'] +109340,how can a windows service start a process when a timer event is raised i have created a windows service with timer and in firing event of timerelapsed i am creating a process systemdiagnosticsprocestartexe path at interval of 5 seconds but this process does not get created on the firing of an eventis there any other way of doing thisthanks in advanceprivate void timer elapsedobject sender systemtimerselapsedeventargs e process pr new process prstartinfofilename cprogram filesmessengermsmsgsexe prstartinfowindowstyle processwindowstylenormal prstartinfocreatenowindow false prstart,"['c#', '.net']" +109361,create a grid in wpf as template programmatically i want to create a basic user control with a style programmaticallyin this style i want to add a grid no problem but i cannot add column definitions to this gridmy example code iscontroltemplate templ new controltemplateframeworkelementfactory mainpanel new frameworkelementfactorytypeofdockpanelmainpanelsetvaluedockpanellastchildfillproperty trueframeworkelementfactory headerpanel new frameworkelementfactorytypeofstackpanelheaderpanelsetvaluestackpanelorientationproperty orientationhorizontalheaderpanelsetvaluedockpaneldockproperty docktopmainpanelappendchildheaderpanelframeworkelementfactory headerimg new frameworkelementfactorytypeofimageheaderimgsetvalueimagemarginproperty new thickness5headerimgsetvalueimageheightproperty 32dheaderimgsetbindingimagesourceproperty new bindingelementimage relativesource new relativesourcerelativesourcemodetemplatedparent headerpanelappendchildheaderimgframeworkelementfactory headertitle new frameworkelementfactorytypeoftextblockheadertitlesetvaluetextblockfontsizeproperty 16dheadertitlesetvaluetextblockverticalalignmentproperty verticalalignmentcenterheadertitlesetbindingtextblocktextproperty new bindingtitle relativesource new relativesourcerelativesourcemodetemplatedparent headerpanelappendchildheadertitleframeworkelementfactory maingrid new frameworkelementfactorytypeofgridframeworkelementfactory c1 new frameworkelementfactorytypeofcolumndefinitionc1setvaluecolumndefinitionwidthproperty new gridlength1 gridunittypestarframeworkelementfactory c2 new frameworkelementfactorytypeofcolumndefinitionc2setvaluecolumndefinitionwidthproperty new gridlength1 gridunittypeautoframeworkelementfactory c3 new frameworkelementfactorytypeofcolumndefinitionc3setvaluecolumndefinitionwidthproperty new gridlength3 gridunittypestarframeworkelementfactory coldefinitions new frameworkelementfactorytypeofcolumndefinitioncollectioncoldefinitionsappendchildc1coldefinitionsappendchildc2coldefinitionsappendchildc3maingridappendchildcoldefinitionsmainpanelappendchildmaingridframeworkelementfactory content new frameworkelementfactorytypeofcontentpresentercontentsetbindingcontentpresentercontentproperty new binding relativesource new relativesourcerelativesourcemodetemplatedparent path new propertypathcontent maingridappendchildcontenttemplvisualtree mainpanelstyle mainstyle new stylemainstylesettersaddnew setterusercontroltemplateproperty templthisstyle mainstylebut the creation of frameworkelementfactory with type columndefinitioncollection will throw an exception columndefinitioncollection type must derive from frameworkelement frameworkcontentelement or visual3dwho can help me,['c#'] +109363,how to remove protocol from uri how can i remove the protocol from uri ie remove http,"['c#', 'asp.net']" +109370,how to execute custom javascript in webbrowser control i want to apply some styling commands to specific website inside webbrowser control the best way to do it is to invoke javascript i want that style to be editable with javascript it is easy i know i can do it with webbrowser1navigatejavascript alerthi void0 but maximum url length that webbrowser accepts is 502 how to execute longer scripts or maybe there is a way to append my css to web document ps i cannot edit documents text property since it will break scripts in this website and i need working copy but just slyled a bit,"['c#', 'javascript', '.net']" +109386,how to create the magic xcdatamodeld folder package recently i managed by accident do not ask to delete my core data datamodel files and classes and i was completely and utterly unable to create the files again to be exactly the same as they would be in a freshly started project where those files are being prepared automatically by xcodein a new project the files would look like thiswhile all i was able to create wasdid i mention that the app did not work anymore this way it crashed saying the model must not be nil the problem was solved by starting a new project with the same name and dragging the files over to the old one not the most elegant solution i supposei figured however that there are things about core data that i still do not quite understand obviouslyplease enlighten me whats the magic behind the xcdatamodeld folder why would fooxcdatamodel feature that green checkedicon does the datamodel need to be compiled or processed in some waythanks alot guys,"['iphone', 'objective-c']" +109428,load a page of data at a time i have got a data grid with pages with more than 10k rows so its very slow when it first loads whats the best way of solving this problem i have read that jdbc paging is the usual solution for such problem but some people are saying to use sql rownum is an easier solution so i wanted to ask firstif you think paging is the best solution could you please give me a couple of pointers on how to go on about itlink to implimentation etc,['java'] +109447,javascript document write overwriting page i am very new with javascripti am trying to create a tag using documentwrite with wordpress to add a style that hides images before they are preloaded i have had to resort to writing a javascript style to hide the images before they are loaded via css i do not want to actually write it into the css file incase the user has javascript thisabled and then the images would never showi am trying to get this code to workjqueryfunction documentwritestyle typetextcss preload img thisplay none style bodywrappreloadthisbut it is just overwriting the whole page and making it go blank how can i stop this i want to add the tag to the without removing the page tried using return no lucksorry i am a novice thanks in advance,['javascript'] +109488,how do i use hasclass to detect if a class is not the class i want how do i use hasclass so it works as doesnothaveclass in other words rather than looking to see if it is a specified class looking to see if it is not a specified class can i use an exclamation point or something like that,"['javascript', 'jquery']" +109500,how can i detect arrow keys in java i know how to implement a key listener that is not the problempublic void keytypedkeyevent event if eventgetkeychar key left ctdirection left if eventgetkeychar 40 ctdirection down if eventgetkeychar 39 ctdirection right if eventgetkeychar 38 ctdirection up what do i put where the left key 40 39 38 when i created a keylistener and type in the keys i believe i got 37 40 i do not know what to put there to listen for just the arrow keys,['java'] +109512,generic list of generic interfaces not allowed any alternative approaches i am trying to find the right way to use a generic list of generic interfaces as a variablehere is an example it is probably not the best but hopefully you will get the pointpublic interface iprimitivet t value get and then in another class i want to be able to declare a variable that holds a list of objects that implement iprimitivet for arbitrary t i know this line will not compile because i do not define t listiprimitivet primitives new listiprimitivestprimitivesaddnew star assuming star implements iprimitivexprimitivesaddnew sun assuming sun implements iprimitiveynote that the t in iprimitivet could be different for each entry in the listany ideas on how i could setup such a relationship alternative approaches,['c#'] +109517,check if user has email set up on their idevice how do you check programmatically if a user has set up an email account in mailapp it seems to be causing a crash cheers,['iphone'] +109532,sorting a vector of double precision reals and obtain their order in c would like to sort a lengthy 220 vector of reals obviously sort does the trick having used r before i was used to the nice order function which yields the permutation that leads to the sorted vector probably someone has done this in c maybe it is just my weak googlefu that prevents me from finding it and yeah obivously my c newbness could stop me from spotting something straightforwardexamplex 24 55 22 1then the permutationperm 3 2 0 1maps the original x to the sorted x in ascending orderi can probably implement some bubble sort which does not only sort x but performs the same transpositions on the vector 012 and outputs both but i believe someone must have thought about it and especially have done it efficientlythank you very much philipp,['c++'] +109540,when deserializing json from within a c program should i ever need to use anything other than javascriptserializer net provides the javascriptserializer class in thesystemwebscriptserialization namespace provided in systemwebextensionsdllit was originally intended to support ajax web server apps but the class can be used by any application client server hybrid anything that serializes and deserializes net classes to json i have a desktop app that captures screenshots and uploads to facebook and uses this class to deserialize the response would i ever want to look elsewhere for json deserialization from within net if so why and where would i look if not then why does jsonnet exist is it strictly for historical purposes ie because it was created by the community before the javascriptserializer,"['c#', '.net']" +109559,turn off chromesafari spell checking by htmlcss is there a way for a web developer to turn off chromesafariwebkit is spellchecking on particular input or textarea elements i mean either by special tag attribute or a proprietary css instructionthere is a css instruction for turning off outlining of inputs so i thought that might also exist i know how a user can do itor as a user can i thisable it for some particular domain,"['html', 'css']" +109566,unwanted outline or border around button when clicked i have a styled button on my website but when i click it it creates an unwanted border or outline i do not know which i would like you to show me how i can remove that border below is all the code that pertains to the button i would appreciate any help you give thanksthe cssbuttonborderhiddenmarginbottom6pxbackgroundcolortransparentfontweightboldtexttransformuppercasetextdecorationunderlinecursorpointeroutlinenonewebkitborderradius 10pxmozborderradius 10pxborderradius 10pxbuttonhoverbackgroundcoloradff2ftextdecorationnonethe htmlbuttonthis is my buttonbutton,"['html', 'css']" +109594,convert any title to url slug and back from url slug to title i want to convert any title eg of a blog entry to a user friendly url i used rawurlencode to do that but it gives me a lot of strange strings like sthe algorithm should consider german chars like a a etc i want to make a url from title and be able to get the title by decoding the urli tried some of this code that is provided in some other questions but it seems to be one wayeg harzude hoerzude harzude any ideas,['php'] +109605,how to get resource strings from aspnet markup hi i have an assembly called like xcommondll there is some resources files for multilanguage app let us say it languageresx languageenusresxetci have a web application which contains this above dll as referenceso how can i use this resources file in my web applications markup sidetext resourcesclass resourcekey is not valid because of class name is in another assembly,"['c#', 'asp.net']" +109639,how to make two android devices to communicate through tcp we want to establish tcpip connection between two android devicesfor now we thought that it would be simpler if we make the connection device to device so there is no server that is between the two phonesmost of the time if not always one has no real ip address nat and so on is this a problem for creating a tcp socketi did not manage to find any exact information for this any advice and opinion will be highly appreciatedthanks,['android'] +109649,3 equals or case equality operator in ruby integer 5 returns true similarly string karthik returns truehowever 5 integer returns false and karthik stringwhy is the operator not commutative,['ruby'] +109674,how do i correctly install ambethiarecaptcha with rails 3 i have done the following stepsadded to gemfilegem recaptchaadded to configinitializersrecaptcharbrecaptchaconfigure do config configpublic key mykeyhere configprivate key mykeyhereendadded to view raw recaptcha tagsran bundle installthen restarted server the resultundefined local variable or method recaptcha tags for class0x1053ba00x1053b69c8,['ruby-on-rails'] +109676,google map v3 off center in hidden div i have a google map inside a div that i need to be hidden by default div idnewpost stylethisplaynonewhen the map is unhidden a part of it is not rendering i am guessing i have to reload the map onsubmit anybody know how to do thisthanksheres my code script typetextjavascriptjquerydocumentreadyfunction jquerynewcatchhideliveclick functionevent jquerynewposttoggleshow this is the map oad function on the body tagbody onloadload onunloadgunloadhere is the div that is toggled and the div that contains the mapdiv idnewpost stylethisplaynone div idmap stylewidth 500px height 300pxdiv,['javascript'] +109678,does number of columns affect mysql speed i have a table i only need to run one type of query to find a given unique in column 1 then get say the first 3 columns outnow how much would it affect speed if i added an extra few columns to the table for basically data storage i know i should use a saparate table but lets assume i am constrained to having just 1 table so the only way is to add on some columns at the end so if i add on some columns say 10 at the end 30 varchar each will this slow down any query given in the first sentence if so by how much of a factor do you think compared to without the extra reduntant yet present columns,['mysql'] +109682,wrapping around a python list as a slice operation consider the following simple python code l range3 l0 1 2we can take slices of this array as follows l131 2is there any way to wrap around the above array by shifting to the left1 2 0by simply using slice operations,['python'] +109689,android bluetooth bluejacking possible reading from the current android bluetooth apis require devices to be paired before an rfcomm connection can be established pairing is automatically performed when you initiate an encrypted connection with the bluetooth apishowever to my knowledge the bluetooth protocol allows vcf vcard files to be sent without having paired two devices this is what makes bluejacking possible on older phones like sony ericsson k7 series nokia 63 series etcin the interests of writing an android bluejacking application i would like to be able to send vcard files from android without having to first pair with the device does anyone know if this is possible,['android'] +109690,any differences between asinstanceofx and tox for value types i used intellijs ability to convert java code to scala code which generally works quite wellit seems that intellij replaced all casts with calls to asinstanceofis there any valid usage of asinstanceofint asinstanceoflong etc for value types which cannot be replaced by toint tolong,['java'] +109707,get the year from specified date php i have a date in this format 20680615 i want to get the year from the date using php functions could someone please suggest how this could be done,['php'] +109712,android anr keythispatchingtimedout error while continuous tapping on screen i am getting application not responding anr dialog while continuous tapping on the screenthere is no view on the screen where i am tapping frequency of this issue is less but still i am not able to remove it completelyhere i am attaching the log what i caught during this errorerroractivitymanager1322 anr in comtestmjandui comtestmjanduitermsandcondactivityerroractivitymanager1322 reason keythispatchingtimedouterroractivitymanager1322 parent comtestmjanduisplashactivityerroractivitymanager1322 load 659 637 521erroractivitymanager1322 cpu usage from 11430ms to 2196ms agoerroractivitymanager1322 rtalmjandui 9 7 user 1 kernel faults 649 minorerroractivitymanager1322 system server 4 2 user 2 kernel faults 10 minorerroractivitymanager1322 logcat 3 1 user 1 kernel faults 675 minor 1 majorerroractivitymanager1322 synaptics wq 1 0 user 1 kernelerroractivitymanager1322 ami304d 1 0 user 0 kernelerroractivitymanager1322 processlghome 1 0 user 0 kernel faults 47 minorerroractivitymanager1322 sync supers 0 0 user 0 kernelerroractivitymanager1322 droiddunserver 0 0 user 0 kernel faults 6 minorerroractivitymanager1322 events0 0 0 user 0 kernelerroractivitymanager1322 oidinputmethod 0 0 user 0 kernel faults 2 minorerroractivitymanager1322 mandroidphone 0 0 user 0 kernel faults 2 minorerroractivitymanager1322 ndroidsettings 0 0 user 0 kernelerroractivitymanager1322 sh 0 0 user 0 kernel faults 110 minorerroractivitymanager1322 flush1790 0 0 user 0 kernelerroractivitymanager1322 total 19 13 user 6 kernelwarnwindowmanager1322 continuing to wait for key to be thispatchedwarnwindowmanager1322 no window to thispatch pointer action 1can anyone please help me to solve this issuethanks in advance,['android'] +109714,how to document all exceptions a function might throw if you have a public function which may throw an exception which uses other private or public helper functions which can also throw exceptions i think you should document what exceptions the public function can throw and this includes exceptions thrown by the helper functionssomething like this using doxygen throw exception throw exceptionthrownbyhelper throw exceptionthrownbyhelpershelper void thefunction helperwhichmaythrowexceptionand helperwhichmaythrowexception also calls other functions which may throw exceptionsto do this you canrecursively follow all functions thefunction calls and look for exceptions thown by that function this is a lot of work and you might forget to document an exception somewhere when you add an exception to a helpercatch all exceptions thrown by helpers in thefunction and convert them so you are sure only the exceptions you specify are thrown but then why use exceptionsdo not worry about exceptions thrown by helper functions but then you can not unittest all exceptions because you do not know which exceptions can be thrown by the public functionhave some tool which semiautomatically lists all exceptions thrown by helpers etc i looked in the documentation of doxygen but did not find a way to do thisi would like to use option 4 but i have not found a good solution yet maybe it is doable with doxygen or maybe i just want to document to muchedit maybe its not really clear but i am looking for an easy way to document all exceptions preferably using doxygen a function might throw without manually checking all helper functions an easy way includes do not document all exceptions or catch and transform all exceptions in thefunction,['c++'] +109733,rspec and initialize method how can i specify initialize behaviour with rspec for example here generatorrbclass generator attr accessor seed def initializeseed nil seed seed pick seed end def pick seed timenowto i endendgenerator specrbrequire generatordescribe generator it calls pick seed method unless seed specified do endendi would like to set expectation that pick seed method called from initialize method,['ruby'] +109750,tracing rails 3 sql queries is there any gem which works on rails 3 that can show which part of my code generated which sql query on rails 23 there was plugin called query trace but it does not seem to work on rails 3 it generates following error alias method undefined method log info for class activerecordconnectionadaptersabstractadapter nameerror,['sql'] +109753,why is my listview not showing anything i have a very basic listview in android and had set a very basic adapter my problem is that the list view does not show anything regardless of the adapter and the notifydatasetchanged here is my codexmlxml version10 encodingutf8relativelayout xmlnsandroid androidlayout widthwrap content androidlayout heightwrap content textview androidtextstringapp name androidlayout widthwrap content androidlayout heightwrap content textview listview androidididselectview androidlayout heightwrap content androidlayout widthwrap content listviewrelativelayoutthe activity codeimport androidappactivityimport androidosbundleimport androidwidgetlistviewimport comandroidcoursephonemapperrimport comandroidcoursephonemappermodelselectviewadapterpublic class selectactivity extends activity private listview mlistview private selectviewadapter madapter override public void oncreatebundle savedstate superoncreatesavedstate setcontentviewrlayoutselect activity initializelistview private void initializelistview mlistview listview findviewbyidridselectview madapter new selectviewadapterthis mlistviewsetadaptermadapter madapternotifydatasetchanged override public void onresume superonresume and the adapter codeimport androidcontentcontextimport androidgraphicscolorimport androidviewviewimport androidviewviewgroupimport androidwidgetbaseadapterimport androidwidgettextviewpublic class selectviewadapter extends baseadapter private context mcontext private textview mmocktextview public selectviewadaptercontext cnt mcontext cnt mmocktextview new textviewmcontext mmocktextviewsettexttest text mmocktextviewsetbackgroundcolorcolorcyan override public int getcount return 3 override public object getitemint position return mmocktextview override public long getitemidint position return 3 override public view getviewint position view convertview viewgroup parent return mmocktextview the problem is that nothing is shown on the screen a black screen and the first text view from the xml is all i get i cannot see the mocktextview and its text apparently i am doing something quite wrong but i cant figure out what,['android'] +109755,undo a newline n printed to command line printferror dn 1printfnstatus d 50prints error 1status 50in this set up is there any chance to insert error 2n between error 1n and nstatus 50 i understand that r and b can be used to change printed text in the same line eg if there is a single n between error 1 and status 50 but can i change text in a previous linethanks,"['c++', 'c']" +109757,jquerys function jquery syntax possible duplicatejquery what does function jquery mean i stumbled up on the following code included in one file but i just cannot understand what it really means function function dosomething1somedata function dosomething1somedata jqueryquestion 1what does this syntax mean in the contex of jqueryquestion 2how can we call these functions let say from other files such as the html index file and other javascript files thanks,"['javascript', 'jquery']" +109784,how to assign pointer address manually in c programming language how to assign pointer address manually in c programming languagefor example memory address is 0x28ff44,['c'] +109801,c how to make it harder for hackercracker to get around or bypass the licensing check first of all i understand that almost all applications can be cracked especially written in c my question here is to make it a little bit harder to cracksuppose that the user has saved the license file under the applicationstartuppath where all users can readand then every time when the application starts it will check if it can find and verify the license fileif the application can find and verify we let the user to continue with full functionalitiesif not we prompt a messagebox showing unlicensed continue to use with trial version functionalities limitedmy question is if i am a hackercracker i would try to get around or bypass the licensing check instead of cracking the license file because if we use rsa signature it is very difficult to crack a license fileso where should we put the license checkps and also is it safe if i put a global variable islicensed true false to limit the functionalities is it easy for a hacker to change islicensed true,['c#'] +109810,windowsformstimer or systemthreadingtimer i have an application that runs many threads each thread should have a timer that checks for something in that threads scope my question is which timer i should use and what is the difference between both,"['c#', '.net']" +109821,abstracted lcd density how do you calculate the abstracted lcd density for an avd,['android'] +109822,android clickable layout i have got a linear layout that i have set true to be clikable focus but the problem is there is no focus thisplayed when clicked how can i get the focus to be thisplayedheres my codelinearlayout androidididlinear tv layout androidorientationhorizontal androidlayout widthfill parent androidlayout heightfill parent androidlayout weight1 androidclickabletrue androidfocusabletrue androidpaddingbottom7px,['android'] +109826,android listview text color i am trying to set the listview textcolor to black since i am using a white backgroundhere is my mailactivitypublic class mailactivity extends listactivity string listitems compose inbox drafts sent override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmails setlistadapternew arrayadapterthis androidrlayoutsimple list item 1 listitems and my xmlxml version10 encodingutf8linearlayout xmlnsandroid androidorientationvertical androidlayout widthfill parent androidlayout heightfill parent androidbackgroundf listview androididandroididlist androidlayout widthfill parent androidlayout heightwrap content textview androididandroididempty androidlayout widthwrap content androidlayout heightwrap content androidtextempty set androidtextcolor0 linearlayouti am getting the background as white but am not sure where to set the foreground to black i have tried in the xml and looks like it is not helping,['android'] +109850,how to 100 height table only scroll tbody is it possible to scroll the content of a 100 height table and not the header using css and only showing the scroll bar to the side of the tbody content and not the header row thanks,"['html', 'css']" +109858,get legend as a separate picture in matplotlib i am developing a web application and want to thisplay a figure and its legend in different locations on the page which means i need to save the legend as a separate png file is this possible in matplotlib in a more or less straightforward way,['python'] +109866,csize of a 2d vector how do i find the size of a 2 dimensional vector so far i have the following code which does not compileinclude iostreaminclude vectorusing namespace stdint main vector vector int v2d for int x 0 x 3 x for int y 0 y 5 y v2dpush backvector int v2dxpush backy coutv2d0sizeendl coutv2d00sizeendl return 0,['c++'] +109871,how to create a va list on gcc i am trying to convert some code so that it compiles on gcc too right now it compiles only on msvcthe code i am stuck at is in a pseudoformatting function that accepts as input a format string and zero or more arguments const char format it will then process some of the placeholders consuming some of the arguments and pass the rest to vsprintf along with a new va list dynamically generatedthis is the actual code for generating the new va listchar new args char mallocsumchar n new argsforint i 0 i nargs i int j orderi int len getlentypesj memcpyn args cumuloffsetsj len and lenvsprintfbuffer sformatc str new argsin my defense i did not and would never write this code in fact i think it is one of the most hackiest things i have seen in my whole lifehowever this function is very complex very old and very important it is also has not been modified in years well except now so while i would like to rewrite it from scratch i cannot justify the time it would take plus the bugs it would introduceso i need a way to do this same thing on gcc but there a va list is not a char so i am gettingerror iso c forbids casting to an array type va list tag 1,"['c++', 'c']" +109874,recommended development web server for ruby on rails 3 what web server would you recommend for ruby on rails 3 web development on linux how about windows,['ruby-on-rails'] +109877,calling closure assigned to object property directly i would like to be able to call a closure that i assign to an objects property directly without reassigning the closure to a variable and then calling it is this possiblethe code below does not work and causes fatal error call to undefined method stdclasscallbackobj new stdclassobjcallback function print helloworldobjcallback,['php'] +109884,django asynchronous processing i have a bunch of django requests which executes some mathematical computations written in c and executed via a cython module which may take an indeterminate amount on the order of 1 second of time to execute also the requests do not need to access the database and are all independent of each other and djangoright now everything is synchronous using gunicorn with sync worker types but i would like to make this asynchronous and nonblocking in short i would like to do somethingreceive the ajax requestallocate task to an available worker without blocking the main django web application worker executes task in some unknown amount of timedjango returns the result of the computation a list of strings as json whenever the task completesi am very new to asynchronous django and so my question is what is the best stack for doing this is this sort of process something a task queue is well suited for would anyone recommend tornado celery rabbitmq or perhaps something elsethanks in advance,['python'] +109891,generic class for performing massparallel queries feedback i do not understand why but there appears to be no mechanism in the client library for performing many queries in parallel for windows azure table storage i have created a template class that can be used to save considerable time and youre welcome to use it however you wish i would appreciate however if you could pick it apart and provide feedback on how to improve this classpublic class asyncdataqueryt where t new public asyncdataquerybool preserve order m preserve order preserve order thisqueries new listcloudtablequeryt10 public void addqueryiqueryablet query var data query dataservicequerytquery var uri data queryrequesturi required thisqueriesaddnew cloudtablequerytdata query summary blocking but still optimized summary public listt execute thisbeginasync return thisendasync public void beginasync if m preserve order true thisitems new listtqueriescount for var i 0 i queriescount i thisitemsaddnew t else thisitems new listtqueriescount 2 m wait new manualreseteventfalse for var i 0 i queriescount i var query queriesi querybeginexecutesegmentedcallback i public listt endasync m waitwaitone m waitthispose return thisitems private listt items get set private listcloudtablequeryt queries get set private bool m preserve order private manualresetevent m wait private int m completed 0 private object m lock new object private void callbackiasyncresult ar int i intarasyncstate cloudtablequeryt query queriesi var response queryendexecutesegmentedar if m preserve order true preserve ordering only supports one result per query lock m lock thisitemsi responseresultssingle else add any number of items lock m lock thisitemsaddrangeresponseresults if responsehasmoreresults true more data to pull querybeginexecutesegmentedresponsecontinuationtoken callback i return m completed interlockedincrementref m completed if m completed queriescount m waitset,['c#'] +109894,deserialize json object into dynamic object using jsonnet is it possible to return a dynamic object from a json deserialization using jsonnet i would like to do something like thisdynamic jsonresponse jsonconvertdeserializejsonconsolewritelinejsonresponsemessage,"['c#', '.net']" +109904,collection was modified enumeration operation may not execute why i am enumerating over a collection that implements ilist and during the enumeration i am modifying the collection i get the error collection was modified enumeration operation may not executei want to know why this error occurs when modifying a item in the collection during iteration i have already converted my foreach loop to a for loop but i want to know the details on why this error occurs,"['c#', '.net']" +109916,keyboard in html textinput thisappear when webview call loadurl again i use webview for my androind app i got a problem and request a solution for helpthere is a textfield in the html page when it gets focus and then i call mwebviewsetfocusableintouchmodetruein java code so that the android softkeyboard will popup to let me key inthe problem is i need using multithread for some processes in java and call mwebviewloadurlstrjscall as callback to execute javascript function but the keyboard gets hiddenthe way i try is to force the keyboard to show again but how can the keyboard always show when loadurl is calleddose anyone meet the same issue and solve it alreadysincerelyjr,['android'] +109921,why does r does not exist error come in android packagesappsmyfoldersrccomandroidmyfoldermyfilejava196 package r does not exist addpreferencesfromresourcerxmlmyfile packagesappsmyfoldersrccomandroidmyfoldermyfilejava344 package r does not exist menuadd0 menu save 0 rstringmenu save packagesappsmyfoldersrccomandroidmyfoldermyfilejava346 package r does not exist menuadd0 menu cancel 0 rstringmenu cancel packagesappsmyfoldersrccomandroidmyfoldermyfilejava454 package r does not exist errormsg mresgetstringrstringerror empty packagesappsmyfoldersrccomandroidmyfoldermyfilejava458 package r does not exist errormsg mresgetstringrstringerror empty,['android'] +109947,call a c function in aspnet when clicking on a html link i am new to aspnet so pardon the newbie question i have some inputs and some textareas in my myeditpageaspx page and i wish to upload them to a database but to do so i need to link a a href to a function in my myeditpageaspxcs how can i do so thanks,['asp.net'] +109952,how to compile a library on net framework net compact framework i am developing a technical library class that can be used on both types of frameworks compact or notwhat is the best way to develop such library using by default the net features for xp embedded and do restrictions when using windows ce using cfnet thanks,['c#'] +109962,how to restrict date range of a jquery datepicker by giving two dates i am having two dates that is stored in db and am selecting it using ajax and what i need is to show the datepicker values between the dates i selected from dbhere is my code for itbut it is not working properlyfunction setdatepickersettingsisfisc var fsdate fedate ajax type post url assethandlersajaxgetdataashxfisc1 success functiondata alertdata var res datasplitdata will be 442010 120542011 120 var sdate res0splitgetseparatorres0 alertseparator getseparatorres1 starts sdate var edate res1splitgetseparatorres1 alertend edate alertsub sdate0 fsdate new datesdate2substring0 4 sdate0 sdate1 alertstarts fsdatesubstring0 4 fedate new dateedate2substring0 4 edate0 edate1 alertend fedatetostring var dtsettings changemonth true changeyear true showon both buttonimage clienturl imagescalendarpng buttonimageonly true showstatus true showothermonths false dateformat ddmmyy mindatefsdate assigning startdate maxdatefedate assigning enddate return dtsettingspls provide some solution i need the datetime picker which requires values between that range thanks in advance,['jquery'] +109965,equivalent to push or pop for arrays i am trying to add remove and reference items from an array i create in my main java file but i am having trouble figuring out the correct syntax in actionscript they have push and pop for adding and removing items in an array is there an equivalent in android,"['java', 'android']" +109982,php add seconds to a date i have adate which containstue jan 4 075959 2011i want to add to this date the followingduration674165 in secondsonce the seconds are added i need the result back into date formati do not know what i am doing but i am getting odd resultsnote both variables are dynamic now they are equal to the values given but next query they will have different values,['php'] +109987,html5 video element nonseekable when using django development server i have got a django app serving a webpage with an html5 element there is a wierd feature turning the video element to be nonseekable videoseekable returns a timeranges object with length0 whereas it should be length1 this means i cannot edit the video javascript cannot do anything either the thing is when i upload the problematic webpage statically no django just plain htmljscss to my website for testing it works fine length1however if i try to serve the same static page on my django dev server still gives the same problemi am using djangos static serving for devdebug purposes do you have any idea what is causing this or how can i fix it thanks,"['javascript', 'python']" +109995,what is the best practice store images in android in sd card or in sql lite db i want to store sample images what is the best efficient way weather to store on sd card or in db,['android'] +110003,what is a single step exception what is a single step exception in the context of a stack trace and a break pointcheersj,['asp.net'] +110013,how do i check to see if a resource exists in android is there a built in way to check to see if a resource exists or am i left doing something like the followingboolean resultint test mcontextgetresourcesgetidentifiermy resource name drawable mcontextgetpackagenameresult test 0,"['java', 'android']" +110016,phpfpm for windows the phpfpms homepage states that it is part of php since php 533 now i was wondering when i download the newest php binaries from phpnet there is no phpfpm in it how do i get it is it even available for windows,['php'] +110020,how do you synchronously load a script from another directory via an ajax call i often need to load other javascript files via ajax so at the beginning i used the standard function jquery provides for script loadinggetscriptscript namejscallback functionbut this did not work out since getscript is asynchronous the jquery api for ajax says async is set to true by default topic is thiscussed in the comments of the api for getscript so i wrote this function as provided by someone in the comments of the api page linked aboveloadfunctionscriptcallback jqueryajax asyncfalse typeget urlscript datanull successcallback datatypescript this seemed to work well so i went on but i recently noticed that this only works for scripts in the same directory eg calling myobjloadtestjs works well but calling myobjloadtesttestjs does not work at allit feels like i am missing something obvious but i did not manage to find the problem any idea,"['javascript', 'jquery']" +110037,how to tag that a class is threadsafe or not in msdn documentation we see consolethread safetythis type is thread safetextwriterthread safetyany public static shared in visual basic members of this type are thread safe any instance members are not guaranteed to be thread safei have developed a similar static class to the console one so how can i tag it to thread safe i am extracting xml documentation and i would know how i can this part like in the msdn dochope i am clear enoughthanks for help,['c#'] +110053,if a marker interface does not have any methods how does it work i am aware of what marker interface is and when we need to use it one question is still not clear to me if a marker interface does not have any method or body how does it work at runtime,['java'] +110059,creating new sql server table with c i have this code to create new sql table when i execute this its shows me this error which is on screenshot in my db there ise not such table it shows this error any name of table can anyone help mepublic void createstring tname string constring try using sqlcommand cmd new sqlcommandcreate table dbo tname id int identity11 not null datetime date not null barcode nvarcharmax not null artnumber nvarcharmax not null productname nvarchar50 not null quantity int not null selfprice decimal18 2 not null price decimal18 2 not null thisccount int null comment nvarcharmax null constraint tname primary key clustered id asc with pad index off statistics norecompute off ignore dup key off allow row locks on allow page locks on on primary on primary new sqlconnectionconstring cmdconnectionopen cmdexecutenonquery cmdconnectionclose catch exception throw,['c#'] +110061,how can i do a jquery swear word bad word filter i know there are many arguments as to why this is a bad idea but in my implementation i am planning on enablingthisabling bad words in the account settings in other words bad words will be visible by default but switched off hidden if askedthe plan will be to send a json string to the client and let the client filter out the bad wordsjson stringswear1 swear2original phrasethis phrase includes swear1final outputthis phrase includes this is what i have tried so far documentready function bodyhtmlreplaceasdf f now on a side note i am using aspnet mvc and i could do this on the server side but i was thinking that this would be better if offloaded to the client i am open to suggestions on this,['jquery'] +110062,is is possible to include views in a gem that the user can render as a partial say i am making gem awesome o and it will make apps awesome how could i package up some view partials so that the user can optionally use them in hisher app for eg render partial some path to awesome olist of awesome is that possible,"['ruby-on-rails', 'ruby']" +110064,definitions of sqrt sin cos pow etc in cmath are there any definitions of functions like sqrt sin cos tan log exp these from mathhcmath available i just wanted to know how do they work,"['c++', 'c']" +110065,how to close a python thread from within for every client connecting to my server i spawn a new thread like this create a new clientc clientselfserveraccept globqueueglobqueueindex globqueueindex serverqueue start itcstart and thread itselfthreadsappendcnow i know i can close all the threads using this code loop through all the threads and close join them for c in selfthreads cjoinbut how can i close the thread from within that thread,['python'] +110069,eclipse with j2ee plugins will not build class files to output directory i have had this issue with several versions of eclipse in some scenarios eclipse will not output bytecode class files to the output directory i will do a build and a clean i am working with tomcat server i stop the server and still eclipse will not do a buildmy output directory projectwebcontentwebinfclassessometimes after doing so many builds andor restarting my machine i am able to build again to that directory does any know what the problem isalso what is the best way to create a bug report for this problemversion info galileoeclipse java ee ide for web developersbuild id 201002181602also mvn m2eclipse plugin installed,['java'] +110091,objective c last object when using fast enumeration what is the best way to know when i have reached the last object in an array when using fast enumeration is there a better way than incrementing an int and then comparing that to the length of the array,"['iphone', 'objective-c']" +110093,converting html to pdf in php i know that there is a lot of posts about this problembut can someone help me to setup this script to work on my localhosti just spent all week on this problemi have download imagemagicghostscriptactiveperleverythingbut still cannot make simple example to work,"['php', 'html']" +110100,how to lock user account on 5 unsuccessful attempts i have a website developed using aspnetc i would like to lock an user account on 5 consecutive login failures within a time period of 30 minutes i do not want to do this on database side and i know this is cannot be done by session variables i also do not want to use cookies for this as a user can easily thisable cookiesis there a perfect way to do this with above limitations,"['c#', 'asp.net']" +110102,what are the big improvements between guava and apache equivalent libraries we currently use apache collections string utils etc i need to decide if we should switch from the apache foundations implementationthe important criteria is ease of developers use performancememory usage is not yet an important issue for us speed of development is the key criteria at this pointi would appreciate opinions about how the developers life became significantly easier with guava,['java'] +110105,interview question remove duplicates from an unsorted linked list i am reading cracking the coding interview fourth edition 150 programming interview questions and solutions and i am trying to solve the following question21 write code to remove duplicates from an unsorted linked list follow up how would you solve this problem if a temporary buffer is not allowedi am solving it in c so i made my own node classpublic class nodet where t class public nodet next get set public t value get set public nodet value next null value value my solution is to iterate through the list then for each node to iterated through the remainder of the list and remove any duplicates note that i have not actually compiled or tested this as instructed by the bookpublic void removeduplicatesnodet head iterate through the list nodet iter head whileiter null iterate to the remaining nodes in the list nodet current iter whilecurrent null currentnext null ifitervalue currentnextvalue currentnext currentnextnext current currentnext iter iternext here is the solution from the book the author wrote it in javawithout a buffer we can iterate with two pointers acurrenta does a normal iteration while arunnera iterates through all prior nodes to check for dups runner will only see one dup per node because if there were multiple duplicates they would have been removed alreadypublic static void deletedups2linkedlistnode head if head null return linkedlistnode previous head linkedlistnode current previousnext while current null linkedlistnode runner head while runner current check for earlier dups if runnerdata currentdata linkedlistnode tmp currentnext remove current previousnext tmp current tmp update current to next node break all other dups have already been removed runner runnernext if runner current current not updated update now previous current current currentnext so my solution always looks for duplicates for the current node to the end while their solution looks for duplicates from the head to the current node i feel like both solutions would suffer performance issues depending on how many duplicates there are in the list and how they are thistributed density and position but in general is my answer nearly as good as the one in the book or is it significantly worse,"['c#', 'java']" +110123,multithreading for loop while maintaining order i started messing around with multithreading for a cpu intensive batch process i am running essentially i am trying to condense multiple single page tiffs into single pdf documents this works fine with a foreach loop or standard iteration but can be very slow for several 100 page documents i tried the following based on a some examples i found to use multithreading and it has significant performance improvements however it obliterates the page order instead of 1234 it will be 134265 on what thread completes first my question is how would i utilize this technique while maintaining the page order and if i can will it negate the performance benefit of the multithreading thank you in advancepdfdocument doc new pdfdocumentstring mail textbox1textstring split mailsplitnew string environmentnewline stringsplitoptionsnoneint counter splitcount source must be array or ilistvar source enumerablerange0 10toarray partition the entire source arrayvar rangepartitioner partitionercreate0 counterdouble results new doublecounter loop over the partitions in parallelparallelforeachrangepartitioner range loopstate loop over each range element without a delegate invocation for int i rangeitem1 i rangeitem2 i f prime splitireplace pdfpage page docaddpage xgraphics gfx xgraphicsfrompdfpagepage ximage image ximagefromfilef prime double x 0 gfxdrawimageimage x 0,['c#'] +110132,form input field names containing square brackets like fieldindex i have seen a lot of php code that handles form input in which the input field names contain square brackets i understand that this somehow results in php arrays when a php script examines the post variableexample htmlform action methodpost input namefruit1 valueapple input namefruit2 valuebanana formexample url1applefruit2bananaexample phpassert postfruit array1apple 2bananamy questions about this what is the mechanism behind it at what point do these names that contain brackets get converted into arrays is this a feature of the http protocol of web servers of the php languagecontinuing the previous question is this a commonly used hack or a normal programming toolwhat are all the rules for using brackets in input field namescan multidimensional arrays be created this way,['php'] +110140,is it possible to specialize a template using a member enum struct bar enum special 4 templateclass t int k struct foo templateclass t struct foottspecial usagefoobar aafails to compile using gcc 412it complains about the usage of tspecial for partial specilization of foo if special was a class the solution would be to a typename in front of it is there something equivalent to it for enums or integers,['c++'] +110149,reference for good android ui design patterns i would like to get some links for getting started with design patternsmy requirement is at initial stage how to go about developing a particular pattern say customized listview which can be shared across applications eg applications will call something like drawcustomizedlistviewparams and my code will draw the listview according to the parameters supplied this is particularly useful when across the applications i have to draw customized viewsmy intention isi should not repeat the same code everywhere for doing similar taskany references for the above requirement,['android'] +110157,minifying css js and html together minifying js and css is quite common the benefits of minifying js are much greater that those seen with css because with css you cannot rename elements and same goes for html but what if all 3 were minified together so that the benefits of using shorter names can be brought to css and html that is instead of minifying without any regard to the relationships between the 3 these could be preserved and made simpler i imagine that the implementation could be quite difficult but if it were possible do you think it would provide a significant advantage over traditional minification,"['javascript', 'html', 'css']" +110158,automatically growing lists in python is there a way to make an automatically growing list in python what i mean is to make a list that would grow when an index that does not yet exist is referenced basically the behaviour of ruby arraysthanks in advance,['python'] +110162,how can i find out which javascript causes an ajax request i am having a problem with a java jsf application in a certain case a user action causes an ajax http request that updates the ui correctly but then immediately a second request is triggered causing a second incorrect updatehow can i find out preferably using firebug where exactly that second request is triggered there is a lot of minified framework js code so i do not know where to place breakpoints setting the form onsubmit handler to consoletrace did not help i suppose because these are independant ajax requests,['javascript'] +110163,how bindvalue with in pdo query connectprepareselect usersfirstname userslastname usersid from users inner join users friends on usersidusers friendsuidwhere biduser and type type and accepted 1 and usersfirstname like querystring or userslastname like querystring limit 10querybindvaluequerystring querystringquerybindvaluetype typequerybindvalueuser userqueryexecutethis is what i haveim having error when i try to bindvalue and then use it in the prepared statement querystring fatal error uncaught exception pdoexception with message sqlstatehy093 invalid parameter number number of bound variables does not match number of tokenshow can i solve this,['php'] +110182,longer execution through java shell than console i have a script in python which do some computations when i run this script in console it takes about 7 minutes to complete but when i run it thought java shell it takes three times longer i use following code to execute the script in javathisp runtimegetruntimeexecscriptpy batch envpthisinput new bufferedreadernew inputstreamreaderpgetinputstreamthisoutput new bufferedwriternew outputstreamwriterpgetoutputstreamthiserror new bufferedreadernew inputstreamreaderpgeterrorstreamdo you have any suggestion why the python script runs three time longer in java than in a consoleupdate 29122010the computation goes as followjava sends data to the pythonpython reads the datapython generates a decision tree this is a long operationpython sends a confirmation that the tree is readyjava receives the confirmationlater there is a series of communications between java and python but it takes only several secondupdate 29122010thank you for all your comments and suggestions it took one working day to find out that my assumption was wrong the code i used had a bug and in fact different computation were performed in console and in shell when i fixed it the computation time was the same summary the computation time of a script run in console and in java shell is almost the same the additional time for initialize java vm and io communication is insignificant,"['java', 'python']" +110184,file get contents returns 403 forbidden i am trying to make a sitescraper i made it on my local machine and it works very fine there when i execute the same on my server it shows a 403 forbidden errori am using the php simple html dom parser the error i get on the server is thiswarning file get contents functionfilegetcontents failed to open stream http request failed http11 403 forbidden in homescrapingsimple html domphp on line 40the line of code triggering it isurlidhtmlfile get htmlurli have checked the phpini on the server and allow url fopen is on possible solution can be using curl but i need to know where i am going wrong,['php'] +110224,using folderbrowserdialog in wpf application i have a wpf application that i need to have users access directories in i have searched to the end of the world on how to integrate windows forms into wpf and have found all kinds of information on how to integrate form controls into my xaml however integrating a folderbrowserdialogi am veteran programmer but very new to net 2nd day in fact and i believe i can not find good information on immplementing this simply because i can not determine what the nametype is for a folderbrowserdialogplease help thanksdavidoh and i am using c and visual studio 2008,"['c#', '.net']" +110228,declaration of variable causes segmentation fault i do not understand the reason for a segmentation fault error in my programthe code is available hereat line 29 i declare a pclimage variable defined with typedef like an array of structthe definition of pclimage type is the following from srclibmykinecth filetypedef struct int valid float x float y float z unsigned char blue unsigned char green unsigned char red point3dtypedef point3d pclimage480640the program works well but when i declare a second pclimage i get a segmentation fault as soon as i launch the programfor example if at line 30 of the first file i add pclimage bgpcl the program immediately crashescan anyone help me,['c'] +110229,c json custom serialization is there a waylibrary that will allow me to customize json serialization similar to gson custom serializershere is what i am trying to getthis object keyvaluepairage10 myagewill normally get serialized likemyage key age value 10 whilst i want it to serialize like age 10 instead any ideas,['c#'] +110232,c static member variable and its initialization for static member variables in c class the initialization is done outside the class i wonder why any logical reasoningconstraint for this or is it purely legacy implementation which the standard does not want to correct i think having initialization in the class is more intuitive and less confusingit also gives the sense of both static and globalness of the variable for example if you see the static const member,['c++'] +110245,visual studio jumpto shortcut what it the visual studio shortcut to switch to recently edited line of code useful after accidentally pressing page down for example i saw my mother using it but could not spot what the combination was also could not find on internet,"['c#', '.net']" +110267,replacing php ext with html through htaccess greetingsi am trying to replace php extensions with html so far i got rewriterule html 1php it works nicely when url like sitepagehtml is entered and pagehtml does not physically exist but pagephp doeshowever what i would like to have is when sitepagephp is entered the viewer sees only sitepagehtml in the browser locationis that doable or do i have to set up explicit redirects for each page thanks in advanceps dev environment i am using is xampp on os x if it makes any difference,['php'] +110295,patterned text using php gd library im trying to create something that looks like this using php gd libraryi have figured out how to create simple text using gd library but im stuck on how to put a patterned text in itanybody have any idea on how to do this,['php'] +110302,aspnet web application mvc deployment automation and subversion we are trying to automate the build process to our staging servers but have run into a snag albeit fairly minor we are using the publish functionality built into vs2010 committing to subversion and then a 3rd party app beanstalk automatically pulls the updated files and ftps them to the staging serverthe problem weve run into is that we only appear to have the following choiceslesser of 2 evils if we choose to use replace matching files with local copies this works great with one exception this option does not delete any files that were deleted from the project this will lead to junk andor security issues for unkempt files from the days of oldif we choose to use delete all existing files prior to publish this deletes the entire folder structure including the svn hidden folders that subversion uses for update tracking etc this seems like the best solution from an accuracy standpoint but it really destroys the local svn environment which is the middleman for this automationmy question is there an easy work around for this or a totally different deployment option were overlooking we do not want to publish directly to the server from vs as we want to track whowhatwhen a deployment takes place the only thing i have come across is to delete the file contents manually prior to publishing while leaving the folder structure intact then deploying with replace matching files with local copies unfortunately this brings on a whole new meaning of the word automationany ideas on how best to accomplish this,['asp.net'] +110324,count size lengthtoo many choices in ruby i cannot seem to find a definitive answer on this and i want to make sure i understand this to the nth level a a hello b world acount 2 asize 2 alength 2 a 10 20 acount 2 asize 2 alength 2so which to use if i want to know if a has more than one element then it does not seem to matter but i want to make sure i understand the real difference this applies to arrays too i get the same resultsalso i realize that countsizelength have different meanings with activerecord i am mostly interested in pure ruby 192 right now but if anyone wants to chime in on the difference ar makes that would be appreciated as wellthanks,['ruby'] +110336,how do i bypass protect from forgery in rails 3 for a facebook canvas app i have a rails 3 facebook canvas app when it loads up it gives me an invalid authenticity token error and thisplays the signed request parameter that facebook sends to my app is there a way to bypass the protect from forgery for the signed request from facebookthankstim,['ruby-on-rails'] +110337,bind jquery ui autocomplete using live i have searched everywhere but i cannot seem to find any helpi have some textboxes that are created dynamically via js so i need to bind all of their classes to an autocomplete as a result i need to use the new live optionas an example to bind all items with a class of foo now and future createdfooliveclick function alertclickedit takes and behaves the same as bind however i want to bind an autocompletethis does not workfooliveautocomplete functionevent ui source urlphp surpressed other argumentshow can i use live to bind autocompleteupdatefigured it out with framerfunction searchlivekeyupautocomplete function thisautocomplete source urlphp,['jquery'] +110372,how to support multiple android version in your code take accessing contacts in androidandroidjar for versions 16 has peoplecontent uri for invoking contacts related info whereas in later versions we need to have api support for rawcontactscontent urisame thing is true for accessing calendar for instance as its uri is changed in android 22is there a best practice to manage all different changes without adding additional application or build separately for each version of changes,"['java', 'android']" +110382,is there any real world reason to use throw ex in c throw ex is almost always wrong as it resets the stack tracei just wonder is there any real world use for this the only reason i can think of is to hide internals of your closed library but that is a really weak reason apart from that i have never encountered in the real worldedit i do mean throw ex as in throwing the exact same exception that was caught but with an empty stacktrace as in doing it exactly wrong i know that throw ex has to exist as a language construct to allow throwing a different exception throw new differentexceptionex as innerexception ex and was just wondering if there is ever a situration where a throw ex is not wrong,"['c#', '.net']" +110405,how to efficiently convert byte array to string i have a byte array of 151 bytes which is typically a record the record needs to inserted in to a oracle database in 151 byte of array range from 0 to 1 is a record id 2 to 3 is an reference id 4 to 9 is a date value the following data in an byte array is a date value i want to convert it to string byte b 484849484852 when converted to string it becomes 10042 new stringb current approachis there any way to efficiently to convert byte array of some range arrayscopyofrangeb05 to string,['java'] +110412,how to check device natural default orientation on android ie get landscape for eg motorola charm or flipout i have an activity showing preview from camera so it need to be set as landscape only at the bottom regardless of device rotation i want to show a text view i am using orientationeventlistener which gives devices orientation from its natural position i can implement a solution which works well on portrait default devices but to make it work also on landscape default devices i need to be aware of running on such a device thus the question is how to check it,['android'] +110413,retrieve json with stackoverflow api i want to retrieve information from my stack overflow profile as json using the api so i use this link httpapistackoverflowcom10users401025but when i make the request i get a file containing the json data how do i deal with that file using ajaxhere is my code html head script var req getreputation function getreputation req new xmlhttprequest reqopenget reqonreadystatechange processuser reqsend function processuser var res jsonparsereqresponsetext alerttest script headthe alert is never fired and reqresponsetext seems to be empty any ideas,['javascript'] +110420,what does in mysql mean what does in mysql mean and do,['mysql'] +110426,fastest way to swap elements in python list is there any any faster way to swap two list elements in python thanla lb lb laor would i have to resort to cython or weave or the like,['python'] +110433,how to determine which compiler has been used to compile an executable from a compiled file can i see which compiler has been used to generate the file,"['c++', 'c']" +110471,how can i partially sort a python list i wrote a compiler cache for msvc much like ccache for gcc one of the things i have to do is to remove the oldest object files in my cache directory to trim the cache to a userdefined sizeright now i basically have a list of tuples each of which is the last access time and the file size first tuple element is the access time second tuple element is file sizeitems 1 42341 3 22 0 3234 2 42342 4 123 now i would like to do a partial sort on this list so that the first and elements are sorted where and is the number of elements so that the sum of their sizes exceeds 450 the result should be basically this partially sorted list only first two elements are sorted because the sum of their second field is larger than 450items 0 3234 1 42341 3 22 2 42342 4 123 i do not really care about the order of the unsorted entries i just need the and oldest items in the list whose cumulative size exceeds a certain value,['python'] +110479,creating a jquery like object my end goal is being able to do something like thismyvarparameterfunctiontoperformsilly enough even after reading up on how variables are declared looking at the jquery code i still cannot get my head around itthis is what i have tried so far but it failsvar myclass functioncontext thisprint function consolelogprintingthismove function consolelogcontextvar test new myclasstestprint worksconsolelogmoving testazertymove type property error,['javascript'] +110483,how can i suspend and resume layout in wpf how can i suspend and resume layout in wpfi heard that this is not necessary but this is extremely necessaryi process a lot of change positions and if they are rendered one by one it creates a delay effecthere are some codecompositiontargetrendering new eventhandlerdrawvoid drawobject sender eventargs e clean screen for int i maincanvaschildrencount 1 i 1 i if maincanvaschildreni is playerusercontrol maincanvaschildreni is image maincanvaschildrenremovemaincanvaschildreni draw floor around floorservicefloorentity floorsaround floorserviceselectfloorsaroundplayerid for image image new image imagesource new bitmapimagenew uri floorsaroundiimagesource urikindrelative maincanvaschildrenaddimage draw players around its similar as draw floors around,['.net'] +110485,using gson in android to parse a complex json object i am relatively new to java programming and need to parse a complex json object across the wire i have been reading documentation on gson the past day and have not had much luck being able to fully parse this type of structure events name exp date 10102010 tags tag 1 tag2 tag3 more events contacts name john smith date 10102010 tags tag 1 tag2 tag3 more contactsi have been able to get it to work similarly to this question but cannot figure out how to get that additional array level to work,['android'] +110496,how to check if alarmmanager already has an alarm set when my app starts i want it to check if a particular alarm registered via alarmmanager is already set and running results from google seem to indicate that there is no way to do this is this still correct i need to do this check in order to advise the user before any action is taken to create a new alarm,['android'] +110512,convert dictionary to list i know that its possible to convert a list of keyvaluepair into a dictionary but is there a quick way besides looping through manually to perform the vice versa operation this would be the manual wayforeach keyvaluepairdoubledouble p in dict listaddnew keyvaluepairdoubledoublepkeypvaluenot really that bad but i was just curious,['c#'] +110514,finding a list of all the android apps on the market is there a way of getting access to the details of each one programatically,['android'] +110517,audio stream buffering i need to play live audio stream actually it is radio the problem is that i also need to manage 20 minute buffer for stream as far as i understand it is not easy to implement with adnroid first i checked mediaplayer but it does not provide any methods for buffer managment in fact you even cannot set buffer size directlysecondly i tried to manage buffer using local files progressively download the stream to a temporary files and switch them but when you want to switch to following file change datasource in mediaplayer audio is not played continuously you can hear short interruptionsthe last idea is to use stream proxy usually it is used for playing streams in adnroid versions below 8 in stream proxy you create serversocket read from audio stream and write to player so actually i can manage buffering there i can cache stream and write to mediaplayer whatever i want but it does not work with android 8 i got exception connection reset by peer javanetsocketexception connection reset by peer mediaplayer 8 does not want to read data from socketthus i have two questions1 what other way to implement stream buffering2 how to adapt streamproxy for android 8 any ideas are appreciatedthanks,['android'] +110532,uitableview reloadrowsatindexpaths performing animation when it should not i am using a uitableview in my ios app and have been seeing a strange issue recentlysuppose my table is structured as followssection 1 headerrow section 2 headersection 3 headerrowrow note that section 2 has no rowsi am performing updates to the rows in my table via selftv beginupdates selftv reloadrowsatindexpathsip withrowanimationuitableviewrowanimationnone selftv endupdatesi do not want any animations taking place i just want the row to update the issue is that this strategy works for every row and section in the my table except section 3 row 1 the first row of the last section when i update this row which is indeed using the correct indexpaths rather than get no animation the row does this little jump like it is sliding in a new row to replace the old one or something the row slides up ever so slightly then back down as if i was inserting a row i am guessing it has something to do with the header calculations but i do return correct values for heightforheaderinsection has anyone seen this behavior,['ios'] +110543,rails 3 generate unique codes coupons whats the best way to generate unique codes to use as coupon codesthanks,"['ruby-on-rails', 'ruby']" +110557,how scalable is codeigniter v other php frameworks how scalable is codeigniter v other php frameworks i am new to codeigniter and love to know how scalable it is when compared to other php frameworks,['php'] +110558,where does business logic go in rails i am an aspnet mvc developer just starting with my first big project on rails however im confused as where to put your business logic on aspnet i create a library which contains servicesdomain driven design which handle business logic i have heard that rails uses a concept of fat model skinny controller but i have some projects in aspnet which adding all the logic to the controller would create a big mess is there any other way,['ruby-on-rails'] +110559,adjustpan not preventing keyboard from covering edittext i am trying to create a pretty basic chat screen with a listview thisplaying the text and an edittext at the bottom and a send button to the right of the edittext everything is functional but when i click the edittext the virtual keyboard covers it the screen pans up a little but not enough to become visible above the keyboard i have got the adjustpan tag in my manifest and have also tried the adjustresize tag to no avail i am guessing it has something to do with the way my layout is set up but i honestly have no clue please helpcurrent layoutlinearlayout xmlnsandroidandroidorientationverticalandroidlayout widthfill parentandroidlayout heightfill parentlistview androidididandroidlist androidlayout height0dip androidlayout widthfill parent androidlayout weight1 androidstackfrombottomtruelistviewlinearlayout androidorientationhorizontal androidlayout widthfill parent androidlayout heightwrap content edittext androidididsendmessagebox androidfocusabletrue androidlayout widthfill parent androidlayout heightwrap content androidlayout weight1 androidscrollbarsvertical androidmaxlines4 androidtext androidinputtypetextshortmessagetextautocorrecttextcapsentencestextmultiline androidmaxlength10 androidhinttype your message androidimeoptionsactionsend button androidididsendmessagebutton androidlayout widthwrap content androidlayout heightwrap content androidlayout gravitybottom androidtextsendlinearlayout,['android'] +110571,secret copy to clipboard javascript function in chrome and firefox updatelooks like browsers are starting to support copy natively in jsin the console windows of both chrome and firefox on mac i can executecopyparty in your clipboardand the text gets copied to my clipboard i have searched so and google and cannot seem to find anything on this are these specific to each browserwhere can i find more information onthese javascript functionsbrowser versionsjavascript returned from chrome console when executing copyfunction object if injectedscript typeobject node var nodeid injectedscripthostpushnodepathtofrontendobject false false injectedscripthostcopynodenodeid else injectedscripthostcopytextobject what does this code meanhere are 2 screenshots of executing copy function in chrome console with all chrome extensions thisabled,['javascript'] +110574,combining link to with render partial i would like to combine 2 commands into 1 if its possible render partial sharedlogo link to dashboard root url i would like to call the logo in the shared directory and have it be a link at the same timehow would i write this,"['html', 'ruby-on-rails']" +110583,what are common design patterns in cocoa touch in java community design pattern is very common term in object c and cocoa touch world there are also some design patterns such as mvc targetaction delegate kvo etc the purpose question here is to hear more professional experience from guru after all some patterns are common used in ios development just like some are very common in j2ee world so question maybe how many common patterns in ios development field let me put some heremvc delegate targetaction communication between v and c kvc kvo notification comm between m and c singleton,"['objective-c', 'ios']" +110586,which is the best ide to use for java for beginner i have just started learniing java there are many ides available and i am confused which should i usecan anyone recommend which ide should i use which is helpful in long run and easy to use,['java'] +110590,speechrecognizer causes anr i need help with android speech api edit i should have mentioned this already but i am running this code in a service the entire app is turned onoff by a widget button and has no activityupdate i tried attaching the sdk sources to the project so i could get a more precise idea of where the failure was occurring but from the looks of it only public apis are included which seems to make them a lot less useful can anyone suggest at least a debugging approach for solving this issue i am kind of stucki am trying to use androids speech recognition package to record user speech and translate it to text unfortunately when i attempt initiate listening i get an anr error that does not point to anything specificas the speechrecognizer api indicates a runtimeexception is thrown if you attempt to call it from the main thread this would make me wonder if the processing was just too demanding but i know that other applications use the android api for this purpose and it is typically pretty snappyjavalangruntimeexception speechrecognizer should be used only from the applications main threadhere is a trimmed sample of the code i am trying to call from my service is this the proper approachthanks for taking the time to help this has been a hurdle i have not been able to get over yetintent intent new intentrecognizerintentaction recognize speechintentputextrarecognizerintentextra language model recognizerintentlanguage model free formintentputextrarecognizerintentextra calling package comdomainappspeechrecognizer recognizer speechrecognizer createspeechrecognizerthisgetapplicationcontextrecognitionlistener listener new recognitionlistener override public void onresultsbundle results arrayliststring voiceresults results getstringarraylistrecognizerintentextra results if voiceresults null logegetstringrstringlog label no voice results else logdgetstringrstringlog label printing matches for string match voiceresults logdgetstringrstringlog label match override public void onreadyforspeechbundle params logdgetstringrstringlog label ready for speech override public void onerrorint error logdgetstringrstringlog label error listening for speech error override public void onbeginningofspeech logdgetstringrstringlog label speech starting recognizersetrecognitionlistenerlistenerrecognizerstartlisteningintent,['android'] +110591,how to convert full c project to vbnet how to convert full c project to vbnet,['c#'] +110594,how does java know how to iterate an array string strs new string 1 2 6 for string s strs systemoutprintlnsthis is a question about java internals in the above code sample how does the foreach loop figure out how long the array is are arrays actually objects internally or is it using stuff like sizeof that is inaccessible to front end programmers i have a feeling i am just missing something stupid but i figure it could also be cool,['java'] +110602,how can i get the google cache age of any url or web page in my project i need the google cache age to be added as important information i tried to search sources for the google cache age that is the number of days since google last reindexed the page listedwhere can i get the google cache age,['html'] +110619,what are generics in c what are generics in c illustrated with a simple example what are some related articles or websites for this topic,['c#'] +110640,how could i know if an object is derived from a specific generic class suppose that i have an object then how could i know if the object is derived from a specific generic class for examplepublic class genericclasst public bool isderivefromobject o return ogettypeissubclassoftypeofgenericclass will throw exception hereplease notice that the code above will throw an exception the type of the generic class cannot be retrieved directly because there is no type for a generic class without a type parameter provided,"['c#', '.net']" +110654,mysql group concat duplicates i make my join from a farmtoanimal table like this there is a similar farmtotool tableid farmid animal 1 1 cat 2 1 dogwhen i join my tables in a view i get a result that looks like thisfarmid animal tool 1 cat shovel 1 dog shovel 1 cat bucket 1 dog bucketnow i do group by farmid and group concatanimal and group concattool i getfarmid animals tools 1 catdogcatdog shovelshovelbucketbucketbut what i really want is a result that looks like this how can i do itfarmid animals tools 1 catdog shovelbucket,"['sql', 'mysql']" +110657,widgets configured with androidconfigure will receive onupdate even if configuration is unfinished this is how i configure my apps widgetappwidgetprovider xmlnsandroid androidminwidth240dp androidminheight193dp androidupdateperiodmillis8640 androidinitiallayoutlayoutxyz appwidget androidconfigurecomxyzactivityconfiguration therefore the system will bring up the configuration activity once the widget has been put on the homescreen by the user unfortunately without the configuration applied this widget should not be put on the screen i added some debugging output this happens when the user is selecting the widget for his homescreen note this is when the configuration activity is in front not the widgetiactivitymanager 101 start proc comxyz for broadcast comxyzwidgetxyzxyzwidgetprovider pid14371 uid10050 gids3003 1015dxyzwidgetprovider14371 onreceive androidappwidgetactionappwidget enableddxyzwidgetprovider14371 onenableddxyzwidgetprovider14371 onreceive androidappwidgetactionappwidget updateso that means even the widget is not configured both events enabled update will be fired enabled makes sense to me but update clearly not especially when the configuration activity finished successfully no additional update event is being senti also read that by setting the result of the configuration activity to activityresult canceled one is able to cancel the configuration process but as this clearly runs asynchronous i do not know how to make the configuration process blocking anyone encountered this beforemy final note i had a look in the android gallery widget which somehow manages this properly so a nonconfigured gallery widget will not be added but i suspect some htc magic there as the logs are not very helpful,['android'] +110669,share sessions between tomcat instances without using sticky sessions i am going to have 3 tomcat servers and a load balancer that thispatches the requests without using sticky sessionsi want to share sessions data between the servers and i am thinking in persisting them in db i would like to use memcached as a layer in front of my db to serve the requests faster and to do not put my db under heavy loadi am thinking in providing my customized tomcat manager that uses memcached before gettingpersisting session data to db as at the moment i do not see a transparent way of doing it it means that i will have to manage it again in the case i switch to another app serveris this a good solution or do you see a better approach,['java'] +110673,why truncate when we open a file in w mode in python i am going through zed shaws python book i am currently working on the opening and reading files chapters i am wondering why we need to do a truncate when we are already opening the file in a w modeprint opening the filetarget openfilename wprint truncating the file goodbyetargettruncate,['python'] +110701,testing file uploading and downloading speed using ftp i am working in a desktop application using java in my application i have to perform a speed test which will show the file uploading and downloading speedfor uploading test i am uploading a small test file to a ftp server and based on time taken i am calculating the file upload speed similarly i am downloading a test file form server and calculating download speedbut result i am getting does not match with actual ftp file uploading and downloading speedit seems that the establishing connection to ftp server is increasing the time hence the resultant speed i am calculating is lesshere is the file uploading code i am using public int gettransferratefile filename int trrate 0 try outputstream fout null inputstream bin null connectftpuserftppassftpserver ftpsetfiletypeftpsclientbinary file type ftpenterlocalpassivemode fout ftpstorefilestreamtestuploadfile bin new fileinputstreamfilename byte b new byte8192 int bytesread 0 long starttime systemcurrenttimemillis long endtime 0 while bytesread binreadb 1 foutwriteb 0 bytesread bytesuploadedset bytesread endtime systemcurrenttimemillis trrate int float bytesuploadedset endtime starttime catch ioexception ex loggergetloggerftpfilestorageserviceclassgetnameloglevelsevere null ex return trratecould you suggest any link or some way to get nearest uploading and downloading speedi thanks to all your valuable suggestion,['java'] +110712,what are the differences between g version 4008 and 432 whats the difference between g 4008 and g 432 these two are the most common c compilers that i have seen used in various programming competitionsi tried to google it but found nothing,['c++'] +110719,firebug is it possible to save output to file i have a test engineer to reproduce bugs for me the bug is random so i want him to save the log to the file when it occurs is it possible,['javascript'] +110761,strlen was not declared in this scope c i need to install a simulator in my ubuntu it is written in c and when i try to run make i get this error strlen was not declared in this scope any solution to overcome this error,['c++'] +110764,reg free com with vb6 on windows 7 i have some net code i use from vb6 code i have always developed this on an xp machine by creating a vb6exemanifest file that listed the dependent net assemblies for example say my 2 net assemblies are someassemblyadll and someassemblybdll here is what vb6exemanifest looks like i use version1100 below because that is the version i set on the net assemblyversion in assemblyinfocsxml version10 encodingutf8 standaloneyesassembly xmlnsurnschemasmicrosoftcomasmv1 manifestversion10 assemblyidentity type win32 name client version 1100 dependency dependentassembly assemblyidentity typewin32 namesomeassemblya version1100 dependentassembly dependency dependency dependentassembly assemblyidentity typewin32 namesomeassemblyb version1100 dependentassembly dependencyassemblythen along with the dlls in the same directory i have the assemblies and their own manifest files here is an example someassemblyadllmanifestxml version10 encodingutf8 standaloneyesassembly xmlnsurnschemasmicrosoftcomasmv1 manifestversion10 assemblyidentity typewin32 namesomeassemblya version1100 clrclass clsidf1234567123412341234123456789012 progidsomeassemblyaclass1 threadingmodelboth namesomeassemblyaclass1 clrclass file name someassemblyadll assemblyi also run tlbexp on referenced dlls to create tlb files and this is what i reference in my vb6 project filei want to move to a windows 7 64 bit machine using the same methods when i hit the vb6 code that instantiates the net object on the win7 machine i get activex component cannot create objecton xp it succeeds if i purposely misspell the dependent assembly in vb6exemanifest on xp i get this application has failed to start because teh application configuration is incorrect reinstalling the application may fix this problemon win7 vb6 just loads it is like it ignores the manifest on win7 so i cannot load my net object using reg free methods on win7 if i regasm the dll everything worksany ideas on how to make vb6 work with reg free com on win7 64 bit,"['c#', '.net']" +110768,how to use adb p i am trying to connect from my android device to the host using usb and pthere seems to be an option adb p that can be used but i cannot find an explanationon how to use it there is an old thiscussion here but they ended patching adb i cannot believe this has not being fixed by nowthis is the explanation of the adb command and that is all the documentation i have been able to findnetworking adb p parameters run p over usb note you should not automatically start a p connection refers to the tty for p stream eg devdevomap csmi tty1 parameters eg defaultroute debug dump local notty usepeerdnsi am not clear on what the tty argument looking at the sources it seems to be a service such as shell hostversion etc or it could be as the doc says devdev but i do not know which to usealso the command seems to fork a p in the host but i do not know how it runs on the android device,['android'] +110773,google maps polyline how do i remove it so i checked previous questions regarding this which all relate to v2 which is of no helpso i create two markers save them in an array as markersto and markersfromand then add them with thisfunction route forvar key in markers flightplancoordinatespushmarkerskeyposition flightpath new googlemapspolyline path flightplancoordinates strokecolor ff0 strokeopacity 10 strokeweight 2 flightpathsetmapmapbrilliantbut next time i use it with new markers in the array it just adds a polyline there without removing the previous onei seem to have tried everything removing from the first array the flightpath setmapnull and so forthwhats the correct way to remove the previous line before drawing a new oneedit solvedsolutionfunction route var flightplancoordinates forvar key in markers flightplancoordinatespushmarkerskeyposition ifflightpath flightpathsetpathflightplancoordinates else flightpath new googlemapspolyline path flightplancoordinates strokecolor ff0 strokeopacity 10 strokeweight 2 flightpathsetmapmap reason flightplancoordinates needs to be initialized within the scope this resets the array every time it is used cleaning it out properly also thanks for the input below to make the code a bit nicer,['javascript'] +110785,specify private sshkey to use when executing shell command with or without ruby a rather unusual situation perhaps but i want to specify a private sshkey to use when executing a shell git command from the local computerbasically like this git clone theusertheprojectgit key homechristofferssh keystheuseror even better in rubywith keyhomechristofferssh keystheuser do shgit clone theusertheprojectgitendi have seen examples of connecting to a remote server with netssh that uses a specified private key but this is a local command is it possible,['ruby'] +110789,how to dynamically update the choices in a selectioncell using gwt i am trying to have a table that thisplays data that the user inputs as well as edit the data i have figured out how to do this with text ie they can edit the name of something in the table but i cannot get it to work with selection cells it works correctly if the items in the selection cell are predefined but i cannot dynamically update the items in the cell to include new things after i have created the cell to explain more i have a type column the user enters items into the table with a given type but that can also add new types later when they click on the item in the type column i want the dropdown box to contain all the new types that they have entered but i do not know how to accomplish this here is the code i have so far that does not update like i want it to recordgettypelist will contain additional entries after the user enters new types selectioncell edittypecombobox new selectioncellrecordgettypelist columnassignment string typecolumn new columnassignment stringedittypecombobox override public string getvalueassignment object return objectgettype typecolumnsetfieldupdaternew fieldupdaterassignment string override public void updateint index assignment object string value int row index string newtype value recordeditassigntyperow newtype updateclassgradelabel loginfoset type to value celltableredraw celltableaddcolumntypecolumn typeeditthanks to peter knego foe helping me figure this out here is the modified dynamicselectioncell class if anyone if interested copyright 2010 google inc licensed under the apache license version 20 the license you may not use this file except in compliance with the license you may obtain a copy of the license at unless required by applicable law or agreed to in writing software thistributed under the license is thistributed on an as is basis without warranties or conditions of any kind either express or implied see the license for the specific language governing permissions and limitations under the license package comgooglegwtcellclientimport comgooglegwtcoreclientgwtimport comgooglegwtdomclientelementimport comgooglegwtdomclientnativeeventimport comgooglegwtdomclientselectelementimport comgooglegwtsafehtmlclientsafehtmltemplatesimport comgooglegwtsafehtmlsharedsafehtmlimport comgooglegwtsafehtmlsharedsafehtmlbuilderimport javautilarraylistimport javautilhashmapimport javautillist a link cell used to render a dropdown list public class dynamicselectioncell extends abstractinputcellstring string interface template extends safehtmltemplates templateoption value00option safehtml deselectedstring option templateoption value0 selectedselected0option safehtml selectedstring option private static template template private hashmapstring integer indexforoption new hashmapstring integer private final liststring options construct a new link selectioncell with the specified options param options the options in the cell public dynamicselectionceliststring options superchange if template null template gwtcreatetemplateclass thisoptions new arrayliststringoptions int index 0 for string option options indexforoptionputoption index public void addoptionstring newop string option new stringnewop optionsaddoption refreshindexes public void removeoptionstring op string option new stringop optionsremoveindexforoptiongetoption refreshindexes private void refreshindexes int index 0 for string option options indexforoptionputoption index override public void onbrowsereventcontext context element parent string value nativeevent event valueupdaterstring valueupdater superonbrowsereventcontext parent value event valueupdater string type eventgettype if changeequalstype object key contextgetkey selectelement select parentgetfirstchildcast string newvalue optionsgetselectgetselectedindex setviewdatakey newvalue finisheditingparent newvalue key valueupdater if valueupdater null valueupdaterupdatenewvalue override public void rendercontext context string value safehtmlbuilder sb get the view data object key contextgetkey string viewdata getviewdatakey if viewdata null viewdataequalsvalue clearviewdatakey viewdata null int selectedindex getselectedindexviewdata null value viewdata sbappendhtmlconstantselect tabindex1 int index 0 for string option options if index selectedindex sbappendtemplateselectedoption else sbappendtemplatedeselectedoption sbappendhtmlconstantselect private int getselectedindexstring value integer index indexforoptiongetvalue if index null return 1 return indexintvalue,['java'] +110795,css h1 only as wide as the text i have an h1 style for my sitecentercol h1 color 006bb6 fontweight normal fontsize 18px padding3px 3px 3px 6px borderleft3px solid c6c1b8 backgroundf2efe9 thisplayblockthe background color spans the entire width of the centercol 500pxhow do i make this h1 only span the width of the text of the h1,['css'] +110808,java catching specific exceptions say i have the followingtrysomethingcatchexception genericcatch allcatchspecificexception secatch specific exception onlywhat would happen when it comes across specificexception does it catch it as a generic exception first and then catch the specificexception or does it only catch specificexception while ignoring generic exceptionsi do not want both generic and specificexception being caught,['java'] +110809,what does statically typed and freeform mean for c in the c tag wiki it is mentioned thatc is a statically typed freeform multiparadigm compiled generalpurpose programming languagecan someone please explain the terms statically typed and freeformthanks,['c++'] +110822,abstract test case using python unittest is it possible to create an abstract testcase that will have some test methods but this testcase would not be called and those methods will only be used in subclasses i think i am going to have one abstract testcase in my test suite and it will be subclassed for a few different implementation of a single interface this is why all test methods are the some only one internal method changes how can i do it in elegant way,['python'] +110825,php type hinting not getting along with interfaces and abstract classes i think it will be much easier to see the problem in a code example than writing the question in the first place here is my php codephpinterface aninterface public function method class aclass implements aninterface public function method echo method abstract class anabstractclass abstract public function method aninterface object class concreteclass extends anabstractclass public function method aclass object objectmethod object1 new concreteclassobject2 new aclassobject1method object2 the above code causes the following errorfatal error declaration of concreteclassmethod must be compatible with that of anabstractclassmethodthe problem is that php does not seem to be recognizing the signatures of anabstractclassmethod and concreteclassmethod as compatible am i doing something wrong thanks,['php'] +110842,how often are sales stats updated on itunes connect my app was accepted by apple today and i am trying to figure out how many times it has been downloaded does anybody know how often the sales stats are updated on itunes connect is it once per day if so at what time is it updated,['ios'] +110868,python glob multiple filetypes is there a better way to use globglob in python to get a list of multiple file types such as txt mdown and markdown right now i have something like thisprojectfiles1 globglob ospathjoinprojectdir txt projectfiles2 globglob ospathjoinprojectdir mdown projectfiles3 globglob ospathjoinprojectdir markdown,['python'] +110894,how to play video in java swing how to play a video in java swing is there any swing components for this,['java'] +110915,c pointer scope what happens when you have the following codevoid makeithappen char text hello worlddoes text go out of scope and get deleted automatically or does it stay in the memoryand what about the following exampleclass someclass public someclass someclasomeclasomeclass someclasomeclass stdcout destroyed stdendlint main someclass someclass new someclass return 0 what happend to someclassdoes the same thing occur herethanks,['c++'] +110919,w in ruby regular expression matches chinese characters i use the code belowputs matched if a a12 wit puts matched and surprised me since a a12 is two chinese characters it does not any of 09 az az and but why it outputs matchedcould somebody give me some clues thank you in advance and expect someone can answer me before 2011 happy new year,['ruby'] +110962,illegalargumentexception the bind value at index 1 is null does anybody know what this means1231 205545861 errorandroidruntime12478 caused by javalangillegalargumentexception the bind value at index 1 is null1231 205545861 errorandroidruntime12478 at androiddatabasesqlitesqliteprogrambindstringsqliteprogramjava2341231 205545861 errorandroidruntime12478 at androiddatabasesqlitesqlitequerybindstringsqlitequeryjava1821231 205545861 errorandroidruntime12478 at androiddatabasesqlitesqlitedirectcursordriverquerysqlitedirectcursordriverjava481231 205545861 errorandroidruntime12478 at androiddatabasesqlitesqlitedatabaserawquerywithfactorysqlitedatabasejava13451231 205545861 errorandroidruntime12478 at androiddatabasesqlitesqlitequerybuilderquerysqlitequerybuilderjava3301231 205545861 errorandroidruntime12478 at androiddatabasesqlitesqlitequerybuilderquerysqlitequerybuilderjava2801231 205545861 errorandroidruntime12478 at netlpcollectionistaprovidersproductcontentproviderqueryproductcontentproviderjava3501231 205545861 errorandroidruntime12478 at androidcontentcontentprovidertransportquerycontentproviderjava1631231 205545861 errorandroidruntime12478 at androidcontentcontentresolverquerycontentresolverjava2451231 205545861 errorandroidruntime12478 at netlpcollectionistaprovidersfacadecontentproviderqueryfacadecontentproviderjava5631231 205545861 errorandroidruntime12478 at androidcontentcontentprovidertransportquerycontentproviderjava1631231 205545861 errorandroidruntime12478 at androidcontentcontentresolverquerycontentresolverjava2451231 205545861 errorandroidruntime12478 at netlpcollectionistautilscanaddtaskexistsproductscanaddtaskjava1641231 205545861 errorandroidruntime12478 at netlpcollectionistautilscanaddtaskinitscanaddtaskjava711231 205545861 errorandroidruntime12478 at netlpcollectionistautilitemscanaddtaskinititemscanaddtaskjava341231 205545861 errorandroidruntime12478 at netlpcollectionistauiactivitiescollectionscdcdcollectionviewwindowmusiccditemscanaddtaskinitcdcollectionviewwindowjava1471231 205545861 errorandroidruntime12478 at netlpcollectionistauiactivitiescollectionscdcdcollectionviewwindowrestorelocalstatecdcollectionviewwindowjava10441231 205545861 errorandroidruntime12478 at netlpcollectionistauiactivitiescollectionscdcdcollectionviewwindowonrestoreinstancestatecdcollectionviewwindowjava9661231 205545861 errorandroidruntime12478 at androidappactivityperformrestoreinstancestateactivityjava8151231 205545861 errorandroidruntime12478 at androidappinstrumentationcallactivityonrestoreinstancestateinstrumentationjava10961231 205545861 errorandroidruntime12478 at androidappactivitythreadperformlaunchactivityactivitythreadjava2641,['android'] +110986,can we have an anonymous struct as template argument the title is pretty selfexplanatory but heres a simplified exampleinclude cstdiotemplate typename tstruct mytemplate t member void printmembersize printfin sizeoft int main mytemplatestruct int a int b t compiler does not like this tprintmembersize return 0the compiler complains when i try to use an anonymous struct as a template argument whats the best way to achieve something like this without having to have a separate named struct definition,['c++'] +111013,java for loop not working i hope this is not a stupid question but i have looked up every example i can find and it still seems like i have this code right and it still is not working i enter one number and it moves on to the next line of code instead of looping i am using this to fill an array with user input numbers i appreciate any help thanksfori0 i9 i systemoutprintln please enter a number numi keyboardnextdouble sum numi product numi,['java'] +111015,installed jvm is 64 bit or 32 bit how can i identity whether the installed version of java is 64 bit or 32 bit,['java'] +111030,redirecting a page to another page for 5 seconds then redirecting again i am trying to redirect a page to another page and that was working successfully however i am trying to redirect the first page to another page with adverts this page will then redirect to another page after five secondsi am trying to do that by doing thisphpincludeadsphpphp sleep2url geturlheaderlocation urlexithowever it is showing the advert in adsphp perfectly but it is not redirecting after five seconds i am receiving this error in my web browser warning cannot modify header information headers already sent by output started at homenucleusipublic htmladvertsadsphp1in homenucleusipublic htmladvertsindexphp on line 7a typical link i would be redirecting to would be this,['php'] +111035,settimeout with zero delay used often in web pages why possible duplicatewhy is settimeoutfn 0 sometimes useful i noticed a trend in web pages that they use settimeoutfunction 0 more often instead of just making the calli wonder why could not find something about it except for the reason that it is used as trick to avoid a stack overflow but this is not always the case for the places it is being used,['javascript'] +111037,how do i thisplay add model in tabular format in the django admin i am just starting out with django writing my first app a chore chart manager for my family in the tutorial it shows you how to add related objects in a tabular form i do not care about the related objects i just want to add the regular object in a tabular form this is what i have in my adminpyfrom choresmodels import chorefrom djangocontrib import adminclass choreadminadminmodeladmin fieldsets none fields description frequency person adminsiteregisterchore choreadminand i want when i click add chore that rather than seeingdescription frequency person i want it to showdescription frequency person is this trivial to do or would it take a lot of custom effort and if it is easy how do i do itthanks,['python'] +111042,textarea character limit by javascript php i use 2 methods to check that the user is not entering too many characters in a textarea1 passive phptextarea posttextareaif strlentextarea300verifybad2 activewhyle typing javascriptfunction ismaxlengthobj var mlengthobjgetattribute parseintobjgetattributemaxlength if objgetattribute objvaluelengthmlength objvalueobjvaluesubstring0mlengthand the textarea itself is as follows htmltextarea nametextarea idtextarea cols40 rows5 styleborder 1px solid 480091 width460px wrapsoft maxlength300 onpastereturn ismaxlengththis onkeyupreturn ismaxlengththistextareaboth methods work except the php strlen function seems to count returns line breaks differently than my javascript functiondoes anyone know how to resolve this so that they both count the same characters regardless of line breaks spaces etcthanks a lot,"['php', 'javascript']" +111069,model change events in nested collections not firing as expected i am trying to use backbonejs in my first real application and i need some help debugging why certain model change events are not firing as i would expectif i create a collection from a json array from the server then fetch it at set intervals i do not get notified if an individual model in the collection has changed the backbone documentation suggests that such notifications should be generated all i seem to get is a refresh notification on each fetch which is not useful otoh if i create a model from a json object from the server then fetch the model at set intervals i do get a change notification when an attribute changes any ideasdetailsmy web service at employeesusernametasks returns a json array of task objects with each task object nesting a json array of subtask objects for example id45002 nameopen dining room subtasks id1statusyellownameclean all tables id2statusrednameclean main floor id3statusrednamestock condiments id4statusyellownamecheck replenish trays id47003 nameopen registers subtasks id1statusyellownameturn on all terminals id2statusyellownamebalance out cash trays id3statusyellownamecheck in promo codes id4statusyellownamecheck register promo placards another web service allows me to change the status of a specific subtask in a specific task and looks like this tasks45002subtasks1statusred aside i intend to change this to a http postbased service but the current implementation is easier for debuggingi have the following classes in my js appsubtask model and subtask collectionvar subtask backbonemodelextendvar subtaskcollection backbonecollectionextend model subtasktask model with a nested instance of a subtask collectionvar task backbonemodelextend initialize function each task has a reference to a collection of subtasks thissubtasks new subtaskcollectionthisgetsubtasks status of each task is based on the status of its subtasks thisupdate status var taskcollection backbonecollectionextend model task task view to renders the item and listen for change events to the modelvar taskview backboneviewextend tagname li template tasktemplatetemplate initialize function bindallthis on change render thismodelbindchange thison change on change functione alerttask model changed when the app launches i instantiate a taskcollection using the data from the first web service listed above bind a listener for change events to the taskcollection and set up a recurring settimeout to fetch the taskcollection instance tasks new taskcollectiontasksurl employees username taskstasksfetch success function apprenderviews tasksbindchange function alertcollection changed apprenderviews poll every 5 seconds to keep the models uptodatesetintervalfunction tasksfetch 50everything renders as expected the first time but at this point i would expect either or both a collection change event or a model change event to get fired if i change a subtasks status using my second web service but this does not happen funnily i did get change events to fire if i added one additional level of nesting with the web service returning a single model for exampleemployeepkaushik tasksid45002subtasksid1but this seems klugey and i am afraid i have not architected my app right i will include more code if it helps but this question is already rather verbosethoughts,['javascript'] +111076,what does it mean to inflate a view from an xml file i am new to android development and keep coming across references to inflating views from a layout xml file i googled and searched the development guide but still was not able to pick up a sense for what it means if someone could provide a very simple example it would be much appreciated,['android'] +111079,problem applying jquery ui theme to buttons i am trying to apply a theme to my buttons input typebutton input typesubmit and button but i have not been able to get it to work at least not in all of them just in one the add button according to this page the only markup i need to apply a theme to a button is simply this buttonbutton labelbutton but it just does not worki added a working demo on jsfiddlei really hope you can help me out with this,['html'] +111090,creating ruby applications for windows i want to develop a windows application honestly i care little about crossplatforms for now but still would be goodi want to use ruby since it has quite a simple syntax and is so well simple and easy to learnmy application is like a game level creator where you can design your own level and then run it with another application which is a game level player by reading the project file created by the creator app you get the ideanow i got a new pc and is completely clean absolutely no trace of my old ruby experiments and failsfirst of all i will need to choose a gui platform for my ruby application can you recommend me one i have heard of shoes and tk but want to know what you think,['ruby'] +111104,css3 columns and images my example here shows an image in the center of css3 generated columns i need the text in the column to the right of the image to wrap around the image so that it does not appear in front of the image this to my understanding is not doable in current css does someone have a nonobtrusive way of achieving what i am looking fori would love to achieve this look here without the title and misc stuff located in the top left of course the idea would be to allow the adding of images anywhere in the markup and have it look correctlyi dont care about browser support at this time so any solution is greatthanks in advanceerik,['javascript'] +111132,how to find all duplicate from a list i have a liststring which has some words duplicated i need to find all words which are duplicatesany trick to get them all,['c#'] +111142,python equivalent of filter getting two output lists ie partition of a list let us say i have a list and a filtering function using something like filterlambda x x 10 141274212 42i can get the elements matching the criterion is there a function i could use that would output two lists one of elements matching one of the remaining elements i could call the filter function twice but that is kinda ugly edit the order of elements should be conserved and i may have identical elements multiple times,['python'] +111168,is there any trick to put rounded corners on a google map possible duplicatetransparent rounded corners on google map i have tried using the usual style sheet properties for specific browsers but none seem to work is there a trick to making this happen i know i have seen it in the wild but cannot recall where,"['html', 'css']" +111179,ios application background downloading hey i need to know how i can have my ios application start a download in the background of the application like have the download run in the appdelegate file so changing viewcontrollers will not interrupt or cancel the download i also need to be able to get the progress of the download 0 10 to set a uiprogressview object to which also means i need a voidprogressdidchangetointprogress function,['iphone'] +111202,how to optimize conways game of life for cuda i have written this cuda kernel for conways game of life global void gameoflifefloat returnbuffer int width int height unsigned int x blockidxxblockdimx threadidxx unsigned int y blockidxyblockdimy threadidxy float p tex2dinputtex x y float neighbors 0 neighbors tex2dinputtex x1 y neighbors tex2dinputtex x1 y neighbors tex2dinputtex x y1 neighbors tex2dinputtex x y1 neighbors tex2dinputtex x1 y1 neighbors tex2dinputtex x1 y1 neighbors tex2dinputtex x1 y1 neighbors tex2dinputtex x1 y1 syncthreads float final 0 ifneighbors 2 final 0 else ifneighbors 3 final 0 else ifp 0 final 1 else ifneighbors 3 final 1 syncthreads returnbufferx ywidth final i am looking for errorsoptimizationsparallel programming is quite new to me and i am not sure if i get how to do it rightthe rest is a memcpy from an input array to the 2d texture inputtex bound to a cuda array output is memcpyed from global memory to host and then dealt withas you can see a thread deals with a single pixel i am unsure if that is the fastest way as some sources suggest doing a row or more per thread if i understand correctly nvidia themselves say that the more threads the better i would love advice on this from someone with practical experience,['c'] +111217,how to override php configuration when running in cgi mode there are some tutorials out there telling me how to override php configuration when it is running in cgi mode but i am still confused because lots of them assume that the server is running on linux while i need to do that also on windowsmy hosting is indeed using linux but my local development computer is using windows xp with xampp 173 so i need to do that in my local computer first then i want to change the configuration on hosting serverthe php in my hosting server is already run as cgi while in my local computer still run as apache moduleat this point the processes that i understand arechange php to work in cgi mode i did this by commenting these two line in httpdxamppconf loadfile cxamphpphp5tsdll loadmodule php5 module modulesphp5apache2 2dllmy php is now running as cgi i checked this with phpinfo it tells me that the server api is now cgifastcgi now i want to override php configurationcreate cgibin directory in documentroot my documentroot is in dw i am using apache with virtual host so it is now dwcgibinchange the default cgibin directory settings from cxamppcgibin to dwcgibinscriptalias cgibin dwcgibindirectory dwcgibin options multiviews indexes symlinksifownermatch includes execcgi allowoverride all allow from alldirectorycopy phpini file to dwcgibin and modify upload max filesize setting from 128m to 10mcreate phpcgi file in dwcgibin and put these code inside the filebinshusrlocalcpanelcgisysphp5 c homeuserpublic htmlcgibinthat is it i am stuck at this point all of tutorials tell me to create phpcgi file and put shell code inside the filehow to do the 6th step on windows i know the next step is to create handler in htaccess file to load that phpcgiand also because i will also need to change php configuration on my hosting server linux is the 6th step above right some tutorial tells to insert these lines instead of abovebinshexport phprcsiteini1exec cgibinphp5cgii am sorry if my question is not clear i am a new member and this is my first question in this sitethank you,['php'] +111221,multiple elements with similar css i have multiple html elements they use very similar css styles only difference is border style one element has all but left border another all but right etcso far i used to create several different styles which have only one line of code different that seriously bloated my css file is there any better solution to my problem is there any kind of inheritance that i could use,['css'] +111222,how to select one row with lowest numeric value of one column what would be the query to select one row with lowest numeric value of one column,['mysql'] +111227,error while running zipalign i got this error when trying to export a signed apk in eclipseerror while running zipalignunable to open as zip archivei have run the helpcheck for updates to make sure the latest update is installed and sdk tools also up to date,['android'] +111236,ipod mini controls thisabled when certain audio session parameters are set i am working on a music visualizer for the iphoneipad under ios 3 you could double tap the home button and get ipod controls with the latest version 4142 these controls are now grayed out when the home button is pressed i found a similar complaint at although there was not a solution i have the base sound category set to kaudiosessioncategory playandrecord with kaudiosessionproperty overridecategorymixwithothers set to true just to add more fun to the problem i am using openal for some sound effectsi have tried setting the category back to ambient when the application goes into the background but either it happens too late or it is not sufficient,['iphone'] +111237,how to open maps app from my code to show directions hi i have to show directions between two coordinates i would like to open maps app passing the start and end coordinates from my code i do not want to open it in the google maps which opens in browsersafari i tried that method that was working perfectnsstring urlstr nsstring stringwithformat daddrff s lat s long d lat d longuiapplication sharedapplication openurl nsurl urlwithstringurlstrbut i want to open iphone maps app how can i do this is this possible any help will be appreciated,['iphone'] +111302,schema validation xml i have an xsd file and an xml file how can i check if the xml is in the right schema like the xsd filei know there is an validate function in the xmldocument class but it needs an event handlerand all i need is true or falseps i am working invisual studio 2010,['c#'] +111303,recording streaming audio from a online radio i am working on a application where i am playing a live radio from a url i want to record the radio and save it to local file system can someone help me for thatthankspankaj,['iphone'] +111308,java blockingqueue latency high on linux i am using blockingqueues trying both arrayblockingqueue and linkedblockingqueue to pass objects between different threads in an application iam currently working on performance and latency is relatively important in this application so i was curious how much time it takes to pass objects between two threads using a blockingqueue in order to measure this i wrote a simple program with two threads one consumer and one producer where i let the producer pass a timestamp taken using systemnanotime to the consumer see code belowi recall reading somewhere on some forum that it took about 10 microseconds for someone else who tried this donat know on what os and hardware that was on so i was not too surprised when it took 30 microseconds for me on my windows 7 box intel e7500 core 2 duo cpu 293ghz whilst running a lot of other applications in the background however i was quite surprised when i did the same test on our much faster linux server two intel x5677 346ghz quadcore cpus running debian 5 with kernel 26262amd64 i expected the latency to be lower than on my windows box but on the contrary it was much higher 75 a 100 microseconds both tests were done with sunas hotspot jvm version 16023 has anyone else done any similar tests with similar results on linux or does anyone know why it is so much slower on linux with better hardware could it be that thread switching simply is this much slower on linux compared to windows if thatas the case itas seems like windows is actually much better suited for some kind of applications any help in helping me understanding the relatively high figures are much appreciatededitafter a comment from davec i also did a test where i restricted the jvm on the linux machine to a single core ie all threads running on the same core this changed the results dramatically the latency went down to below 20 microseconds ie better than the results on the windows machine i also did some tests where i restricted the producer thread to one core and the consumer thread to another trying both to have them on the same socket and on different sockets but this did not seem to help the latency was still 75 microseconds btw this test application is pretty much all i am running on the machine while performering testdoes anyone know if these results make sense should it really be that much slower if the producer and the consumer are running on different cores any input is really appreciatededited again 6 januaryi experimented with different changes to the code and running environmenti upgraded the linux kernel to 26362 from 26262 after the kernel upgrade the measured time changed to 60 microseconds with very small variations from 75100 before the upgrade setting cpu affinity for the producer and consumer threads had no effect except when restricting them to the same core when running on the same core the latency measured was 13 microsecondsin the original code i had the producer go to sleep for 1 second between every iteration in order to give the consumer enough time to calculate the elapsed time and print it to the console if i remove the call to threadsleep and instead let both the producer and consumer call barrierawait in every iteration the consumer calls it after having printed the elapsed time to the console the measured latency is reduced from 60 microseconds to below 10 microseconds if running the threads on the same core the latency gets below 1 microsecond can anyone explain why this reduced the latency so significantly my first guess was that the change had the effect that the producer called queueput before the consumer called queuetake so the consumer never had to block but after playing around with a modified version of arrayblockingqueue i found this guess to be false a the consumer did in fact block if you have some other guess please let me know btw if i let the producer call both threadsleep and barrierawait the latency remains at 60 microsecondsi also tried another approach a instead of calling queuetake i called queuepoll with a timeout of 100 micros this reduced the average latency to below 10 microseconds but is of course much more cpu intensive but probably less cpu intensive that busy waitingedited again 10 january problem solvedninjalj suggested that the latency of 60 microseconds was due to the cpu having to wake up from deeper sleep states and he was completely right after thisabling cstates in bios the latency was reduced to 10 microseconds this explains why i got so much better latency under point 2 above when i sent objects more frequently the cpu was kept busy enough not to go to the deeper sleep states many thanks to everyone who has taken time to read my question and shared your thoughts hereimport javautilconcurrentarrayblockingqueueimport javautilconcurrentcyclicbarrierpublic class queuetest arrayblockingqueuelong queue new arrayblockingqueuelong10 thread consumerthread cyclicbarrier barrier new cyclicbarrier2 static final int runs 50 volatile int sleep 10 public void start consumerthread new threadnew runnable override public void run try barrierawait forint i 0 i runs i consume catch exception e eprintstacktrace consumerthreadstart try barrierawait catch exception e eprintstacktrace forint i 0 i runs i try ifsleep 0 threadsleepsleep produce catch exception e eprintstacktrace public void produce try queueputsystemnanotime catch interruptedexception e public void consume try long t queuetake long now systemnanotime long time now t 10 divide by 10 to get result in microseconds ifsleep 0 systemoutprintlntime time catch exception e eprintstacktrace public static void mainstring args queuetest test new queuetest systemoutprintlnstarting run first once ignoring results testsleep 0 teststart run again printing the results systemoutprintlnstarting again testsleep 10 teststart,['java'] +111315,redirect in spring mvc why cannot i get this to work in my controllerrequestmappingmethod requestmethodpostpublic string onsubmit model model modelattributeform form form bindingresult result httpservletrequest request throws ioexception writeexception biffexception if resulthaserrors return redirectindexhtml i getjavaxservletservletexception could not resolve view with name redirectindexhtml in servlet with name thispatcher orgspringframeworkwebservletthispatcherservletrenderthispatcherservletjava1042 orgspringframeworkwebservletthispatcherservletdothispatchthispatcherservletjava798 orgspringframeworkwebservletthispatcherservletdoservicethispatcherservletjava716 orgspringframeworkwebservletframeworkservletprocessrequestframeworkservletjava644 orgspringframeworkwebservletframeworkservletdopostframeworkservletjava560 javaxservlethttphttpservletservicehttpservletjava637 javaxservlethttphttpservletservicehttpservletjava717 orgnetbeansmoduleswebmonitorservermonitorfilterdofiltermonitorfilterjava390 i have got this to work before why not now,['java'] +111330,how to send email through iis7 i am trying to set up a smtp server on my windows 7 machine in iis7 i have set it to deliver email to localhost port 25 no authentication but when i try to connect programmatically from my c program i get an errorfailure sending mail inner exception no connection could be made because the target machine actively refused it 12700125public static void sendemailmailmessage m var smtp new smtpclient host localhost port 25 usedefaultcredentials true smtpsendmwhy what other secret switch do i have to flip,['c#'] +111344,do invariant assertions fit into c programming in the book coders at work the author asks how do you use invariants in your code please explain what this question meansi saw class invariants on wiki but the example is in java and i am not skilled enough in java to relate this example to c net 40 introduces invariance covariance and contravariance and is well explained here invariance is so broad the authors usage of the word seems unit test related for those that read the book what does the author mean are we talking about making an assumption and simply testing the validity after the unit test,"['c#', 'java', '.net']" +111349,interface casting vs class casting i have been led to believe that casting can in certain circumstances become a measurable hindrance on performance this may be moreso the case when we start dealing with incoherent webs of nasty exception throwingcatchinggiven that i wish to create more correct heuristics when it comes to programming i have been prompted to ask this question to the net gurus out there is interface casting faster than class castingto give a code example let us say this existspublic interface ientity iparent daddymommy get public interface iparent ientity public class parent entity iparent public class entity ientity public iparent daddymommy get protected set public iparent adameve interfaces get ientity e this while edaddymommy null e edaddymommy as ientity return e as iparent public parent adameve classes get entity e this while edaddymommy null e edaddymommy as entity return e as parent so is adameve interfaces faster than adameve classes if so by how much and if you know the answer why,"['c#', '.net']" +111350,how to create a uitableviewcell with a uiswitch and get the data i have a simple problem i created a custom uitableviewcell that includes a uiswitch in interface builderquestion 1 easier better way to do it question 2 when used in an uitableviewcontroller what would be the best way to get the data at some point i either need to go through the table and check every cell about the status or send some feedback when the status of the switches changes directly thanks for the help,['iphone'] +111352,jquery detecting when a user clicks out of an input type text field i want to detecting when a user clicks out of an input type text field not inheres what i have but both events are firing on click inside focusinput idtitle valhello titlefocusoutfunction consoleloginsideblurfunction consolelogoutside,['jquery'] +111356,jquery eventpreventdefault not working in firefox jsfiddle included this is a kind of similar duplicate to some others here but i think i am using eventpreventdefault correctly in this caseheres a jsfiddle you can see the code with basically click the submit buttonin chrome nothing happens correct responsein firefox page reloads oh noesso why is the page reloading in firefox and not chrome i have been firebugging it and no errors come up in either,"['javascript', 'jquery']" +111358,mysql sum elements of a column i have a table with 3 columns abc i want to select some rows from the table and then the mysql to return a single row having the values added on each column a b c1 2 2 22 4 4 43 6 6 6mysql should return in this case if i select all the three rows a b c1 12 12 12,['mysql'] +111362,how do i compile my appconfig into my exe in a vs2010 c console app i am creating a console app in visual studio 2010 with c i want this app to be stand alone in that all you need is the exe and you can run it from anywhere i also want to use appconfig to store connection strings and so on my problem is that i cannot seem to figure out how to include that appconfig data into the compiled exe i do see it creates appnameexeconfig but i do not want people to have to worry about grabbing two separate files when they get the app none of the googling i have done has come up with anything is this even possible,"['c#', '.net']" +111383,determining date equality in javascript i need to find out if two dates the user selects are the same in javascript the dates are passed to this function in a string xthat is all the granularity i needhere is my code var valid true var d1 new datedateinval var d2 new datedateoutval alertd1nd2 ifd1 d2 alertyour check out date must be after your check in date valid false else ifd1 d2 alertyou cannot check out on the same day you check in valid false the javascript alert after converting the dates to objects looks like thistue jan 25 2011 0 gmt0800 pacific standard timetue jan 25 2011 0 gmt0800 pacific standard timethe test to determine if date 1 is greater than date 2 works but using the or operators do not change valid to false,['javascript'] +111391,project euler 1find the sum of all the multiples of 3 or 5 below 10 i am trying to solve math problems with ruby from the project euler here is the first one i triedif we list all the natural numbers below 10 that are multiples of 3 or 5 we get 3 5 6 and 9 the sum of these multiples is 23find the sum of all the multiples of 3 or 5 below 10please help me to improve my codetotal 0010each do i total i if i3 0 i5 0endputs total,['ruby'] +111394,error using jquery ui selectmenu plugin in ie the jquery ui selectmenu plugin demoed here i am having a couple of problems with this plugin i will focus on just one that only happens in iei have htmllabel forsearchstatelabelselect stylewidth 160px namesearchstate idsearchstate optionctoption optionmaoption optionnhoptionselectand jqueryselectsearchstateselectmenuin firefox this works however in ie i get error on load invalid argument jquery 142 line 4618 however the new styled selectmenu appears along with the original one this is by design but the original html select menu should be hidden but when i click an option i get several of these errorsthis optionlist is null or not an object uiselectmenujs line 400any ideas why this does not work in ielines 399401 of uiselectmenujs selectedoptionli function return this optionliseqthis selectedindexlines 46154622 of jquery141jsname namereplacerdashalpha fcamelcaseif set style name valuereturn style name,"['javascript', 'jquery', 'html']" +111439,using curl to submitretrieve a forms results i need help in trying to use curl to post data to a page and retrieve the results after the form has been submittedi created a simple formform nametest methodpost actionformphp input typetext namename size40 input typetext namecomment size40 input typesubmit valuesubmit formin addition i have php code to handle this form in the same page all it does is echo back the form valuesthe curl that i have been using is this h curl init curl setopth curlopt url pathtoformphp curl setopth curlopt post true curl setopth curlopt postfields array name yes comment no curl setopth curlopt header false curl setopth curlopt returntransfer 1 result curl exech echo resultwhen i launch the page with the curl code in it i get the formphp page contents but it does not not showthe variables that php should have echod when the form is submittedwould appreciate any help with thisthanks,['php'] +111447,virtual joystick in java have you heard of a virtual joystick for windows that has java wrappingsi have trying ppjoy and it works great but then i will need to use jni to get it working from java and that does not seem easy for the time beingthanks,['java'] +111457,exception handling pattern it is a common pattern i see where the error codes associated with an exception are stored as static final ints when the exception is created to be thrown it is constructed with one of these codes along with an error message this results in the method that is going to catch it having to look at the code and then decide on a course of action the alternative seems to be declare a class for every exception error case although related exceptions would derieve from a common base class is there a middle ground what is the recommended method,['java'] +111459,how to remove an id attribute from a div using jquery i want to remove the id attribute from this imageimg width270 classthumb idthumb height270 srcimg1 1jpg i tried doing thisimgthumbremoveattridnonebut it is not removing the ideditimgthumbattrsrc responseimgthumbattrid nonthumbthis deosnt load the picture or in this case the src but when i remove the id attribute it works fine,"['javascript', 'jquery', 'html']" +111461,why is eclipse php not recognizing namespace declarations when i type namespace orm in eclipse it underlines orm in red and says that it is expecting a parenthesis is there a way to make eclipse recognize namespaces,['php'] +111463,what regular expression would i use to find the word oy what is regular expression would i use to find the word oy i need it to work in a userscript also i have to make sure it does not remove words that contain oy like olive oyl,['javascript'] +111473,how can i extract a url from a sentence that is in a nsstring what i am trying to accomplish is as follows i have a nsstring with a sentence that has a url within the sentience i am needing to be able to grab the url that is presented within any sentence that is within a nsstring so for examplelet us say i had this nsstringnsstring somestring this is a sample of a sentence with a url within iti need to be able to extract from within that nsstring this nsstring is not static and will be changing structure and the url will not necessarily be in the same spot of the sentence i have tried to look into the three20 code but it makes no sense to me how else can this be done thanks for help,['iphone'] +111474,trycatch using right syntax which oneusing var myobject new myclass try something here catchexception ex handle exception ortry using var myobject new myclass something here catchexception ex handle exception,['c#'] +111487,fancybox passing variable back to parent when fancybox window is closed hi i was wondering if it is possible to pass back a variable from fancybox child to parent once child is closedany info is muchly appreciatedregardsphil edit function cleanup var bla fancyboxframecontentsfindinputnamepd id alertblavaltree product aclasscopyfancybox width 770 height 95 autoscale false transitionin none transitionout none type iframe oncleanup cleanup,['jquery'] +111572,spring unit and integration tests i am looking for best practices for setting up unit and integration tests using springi usually use 3 kind of testsreal unit tests no dependenciestests run either as unit test inmemory db local calls mockobjects or as integration testpersistent db remote callstests run only as integration testscurrently i only have tests of the second category which is the tricky parti setup a base test class likecontextconfigurationlocations my spring testxml public abstract class abstractmytestcase extends abstractjunit4springcontexttestsand unit tests likepublic class footest extends abstractmytestcasewith autowired attributeswhats the best way to run the test in a different integration test environment subclass the test and override the contextconfigurationcontextconfigurationlocations my spring integration testxml public class foointegrationtest extends footestwould this work i cannot currently easily test it here the problem with this approach is that contextconfigurationlocations my spring integration testxml is duplicated a lotany suggestionsregardsflorian,['java'] +111585,deleting all files from a folder using php for example i had a folder called temp and i wanted to delete or flush all files from this folder using php could i do this,['php'] +111590,mongodb automatically generated ids are zeroes i am using mongodb and official c driver 09i am just checking how embedding simple documents worksthere are 2 easy classespublic class user public objectid id get set public string name get set public ienumerableaddress addresses getset public class address public objectid id get set public string street get set public string house get set i create a new uservar user new user name sam addresses new address new address house bighouse street bigstreet collectioninsertusertobsondocumentthe user is successfully saved so is his addressafter typingdbusersfindin mongodb shell i got the following result id objectid4e572f2a3a6c471d3868b81d name sam addresses id objectid0 street bigstreet house bighouse why is address object id 0doing queries with the address works thoughcollectionfindonequeryeqaddressesstreet streetnameit returns the user sam,['c#'] +111600,is there a unique computer identifier that can be used reliably even in a virtual machine i am writing a small client program to be run on a terminal server i am looking for a way to make sure that it will only run on specified server and in case it is removed from the server it will stop functioning i understand that there are no methods to make it 100 secure none the less i want to make it difficult for most power users to be able to do it i was looking at different unique identifiers like processor id windows product id computer guid and other uis because the terminal server is a virtual machine i cannot locate anything that is completely unique to this machineany ideas on what i should look into to make this mostly secure i do not have time or the need to make it as secure as possible because it will defeat the purpose of the application itself i do not want to user mac address even though it is unique to each machine it can be spoofed by following instructions found on internetas far as microsoft product id because our system team clones vm servers and we use corporate volume key i found already two servers that i have access to that have same product id number i have no idea how many others out there that have same product idalternatively instead of trying to identify the machine i might be better off by identifying the user and create group based permission handled through ad for access to this software,"['c#', '.net']" +111609,casting a generic class without specific type i have the following generic classpublic class homet where t class public string getclasstype get return ttostring now i am getting an object x which i know for sure is homepublic void dosomethingobject x ifx is check if home i want to invoke getclasstype method of x but i do not know his generic type x as home what should i use here can i even make a cast without specifying the generic type of the class,"['c#', '.net']" +111632,save result of stored procedure in a table variable possible duplicatehow to select into temp table from stored procedure i have a nested stored procedure callin one of the stored procedures i want to save the result into a table variable likt this insert into mytable exec sp mystoredprocedurehowever because the proc is nested the following error occurs an insert exec statement cannot be nestedthe procedure must be called from another procedure changing this is not an optioni wanted to try to use an output parameter but it still has to be set with a insert into statementwhat are other options to save the data that is retrieved from the call of a stored procedure into a variable,['sql'] +111639,source code dependency manager for c there are already some questions about dependency managers here but it seems to me that they are mostly about build systems while i am looking for something targeted purely at making dependency tracking and resolution simpler and i am not necessarily interested in learning a new build systemso typically we have a project and some common code with another project this common code is organized as a library so when i want to get the latest code version for a project i should also go get all the libraries from the source control to do this i need a list of dependencies then to build the project i can reuse this list tooi have looked at maven and ivy but i am not sure if they would be appropriate for c as they look quite heavily javatargeted even though there might be plugins for c i have not found people recommending themi see it as a gui tool producing some standardized dependency list which can then be parsed by different scripts etc it would be nice if it could integrate with source control tag get a tagged version with dependencies etc but that is optionalwould you have any suggestions maybe i am just missing something and usually it is done some other way with no need for such a tool thanks,['c++'] +111643,capture javaxnetdebug to file i need to save the javaxnetdebugall output that is created to a file i am using log4j and i tried creating a logging proxy as in the code example below however it is not picking up the info i am not sure where the javaxnetdebug is being printed to i tried capturing systemout and systemerr this way but neither worked thanks for your helppublic class stdouterrlog private static final logger logger loggergetloggerstdouterrlogclass public static void tiesystemoutanderrtolog systemsetoutcreateloggingproxysystemout systemseterrcreateloggingproxysystemerr public static printstream createloggingproxyfinal printstream realprintstream return new printstreamrealprintstream public void printfinal string string realprintstreamprintstring loggerinfostring,['java'] +111652,where exactly is the difference between ioc and di possible duplicateinversion of control dependency injection i always read iocinversin of control and didependency injection in the same context what is exactly the difference between ioc and di how does ioc differ from di,['c#'] +111657,where can i find jpa ormxml usage samples i am trying to see some usage samples of jpa ormxml if some one direct me to a link,['java'] +111658,insert on duplicate key do nothing i have a table with a unique key for two columnscreate table xpouser permanent gift id int unsigned not null auto increment fb user id int unsigned not null gift id int unsigned not null purchase timestamp timestamp null default now primary key id unique index user gift unique fb user id asc gift id asc i want to insert a row into that table but if the key exists to do nothing i do not want an error to be generated because the keys existi know that there is the following syntaxinsert on duplicate key update but is there something likeinsert on duplicate key do nothing,"['mysql', 'sql']" +111662,cannot detect a ctrl key shortcut on keydown events whenever there is a readonly textbox with focus i thought i solved this problem by myself but it came back to haunt my application so here it goes i have the following keydown event handler registered in a form with a couple of thisabled and readonly textboxes and they are only simple shortcuts for the buttonsprivate void accountviewform keydownobject sender keyeventargs e esuppresskeypress true ehandled true if controlmodifierkeys keyscontrol ekeycode keyse isineditmode btneditmode clicksender e if controlmodifierkeys keyscontrol ekeycode keyss isineditmode btneditmode clicksender e if ekeycode keysescape btncancel clicksender e if controlmodifierkeys keyscontrol ekeycode keysw close the form has keypreview set to true but whenever a readonly textbox has focus and i press ctrl e i cannot get controlmodifierkeys keyscontrol and ekeycode keyse to be both true at the same time what is really strange is that ctrl w works anyone has any idea what the hell is going on,"['c#', '.net']" +111665,workflow ie directed graph browser based editors i want to provide a wysiwyg tool preferably javascript based for workflow diagramming ie directed graphs i need commercial software friendly licensing which can include paying a fee to oem if there is a necessary server side piece i would need it in java or coldfusion because i am integrating with an existing product my workflow graphs can have more than one start vertex but only one end vertex and edges are directed beyond wysiwyg editing i am looking for a tool that can assist with the following ability to export the drawing so it can bepersisted parsed by a programming language i am assuming xml but other formats are just fine edited again preserving layout informationassociate arbitrary data with edges and vertices including ability to define viewedit panes nice to have detection if any vertices are unable to reach the end automatically layout vertices and edges if no plotting information is provided i have looked at mxgraph which seems promising but am hoping an answerer here can provide some additional direction before i jump down the rabbit hole,"['java', 'javascript']" +111673,longest common subsequence i have written the below code for lcs it works for many cases but breaks for the one below i do not understand where my code is breaking please help the code is in cnamespace longestcommonsubsequencebfclass program static void mainstring args string b accgtgagttattcgttctagaa string a cactaaggtacctggttc find lcs in ab starting from index 0 of each int longestcommonsubsequence lcsa b 0 0 consolewritelinelongestcommonsubsequence consoleread find the longest common subsequnce starting from index1 in a and index2 in b pass a as shorter string public static int lcsstring a string b int index1 int index2 int max 0 if index1 alength you have reached beyond a and thus no subsequence return 0 if index2 blength you may reach end of 2nd string lcs from that end is 0 return 0 for int i index1 i alength i int exist bindexofaiindex2 if exist 1 found true int temp 1 lcsa b i 1 exist 1 if max temp max temp return max,['c#'] +111675,how to check if the url contains a given string how could i do something like thisscript typetextjavascriptdocumentreadyfunction ifwindowlocationcontainsfranky this does not work any suggestions alertyour url contains the name franky script,"['javascript', 'jquery']" +111686,platformindependent way of detecting if git is installed this is how i detect git in rubywhich git 2devnull and successhowever this is not crossplatform it fails on nonunix systems or those without the which command although i am not sure what those arei need a way to detect git that satisfies these conditionsworks reliably crossplatform even on windowsdoes not output anything to stdout or stderrsmall amount of codeupdate the solution is to avoid using which altogether and to redirect output to nul on windowsrequire rbconfigvoid rbconfigconfighost os msdosmswindjgppmingw nul devnullsystem git version void 21the system command returns true on success and false on failure saving us the trip to success which is needed when using backticks,['ruby'] +111690,putting rails over top of an existing database i have an application written in phpmysql symfony to be specific that i would potentially like to rewrite in rails i know how to create scaffolding for tables that do not exist yet but how do i get rails to read my existing table structure and create scaffolding based on thatupdate it turns out i can run the following command to get rails to generate models for merails generate scaffold bank nomigrationbut it does not give me forms i would prefer something that gives me forms,"['mysql', 'ruby-on-rails']" +111695,android timer how can someone get a simple example of updating textfield every second or soi want to make a flying ball and need to calculate the ball coordinates every second that is why i need some sort of timeri do not get anything from here,['android'] +111701,checking something isempty in javascript how can i check if a variable is empty in javascript sorry for the stupid question but i am a newbie in javascriptifresponsephoto is empty do somethingelse do something elseresponsephoto was from json and it could be empty sometimes empty data cells i want to check if it is empty,"['javascript', 'jquery']" +111703,how to insert zeros between bits in a bitmap i have some performanceheavy code that performs bit manipulations it can be reduced to the following welldefined problemgiven a 13bit bitmap construct a 26bit bitmap that contains the original bits spaced at even positionsto illustrate0abcdefghijklm input 32 bits0a0b0c0d0e0f0g0h0i0j0k0l0m output 32 bitsi currently have it implemented in the following way in cif input 1 12 output 1 24if input 1 11 output 1 22if input 1 10 output 1 20my compiler ms visual studio turned this into the followingtest eax10hjne 0064f5ecor edx10h repeated 13 times with minor differences in constantsi wonder whether i can make it any faster i would like to have my code written in c but switching to assembly language is possiblecan i use some mmxsse instructions to process all bits at oncemaybe i can use multiplication multiply by 0x1 or some other magical constantwould it be better to use conditionset instruction setcc instead of conditionaljump instruction if yes how can i make the compiler produce such code for meany other idea how to make it fasterany idea how to do the inverse bitmap transformation i have to implement it too bit it is less critical,['c'] +111718,zindex and iframe issue dropdown menu hey having a rather puzzling issue with my dropdown menus and iframesi have applied a zindex of 10 to the dropdown menus however the iframe containing the youtube video still appears above the menu see for yourself below check the shortcodes menu id765i cannot figure out why this is can anyone help me out here is the css if it helpsjquerydropdown position absolutebottom 0right 10pxjquerydropdown ul margin 0padding 0liststyle nonejquerydropdown ul li margin 0padding 15px 10px 15px 10pxposition relativefloat leftjquerydropdown ul li a thisplay blocktextdecoration nonefontweight boldfontsize 13pxcolor 707070outline nonejquerydropdown ul li ul position absoluteleft 10pxtop 46pxthisplay nonebackground f4f4f4border 1px solid e1e1e1bordertop nonezindex 10padding 5px 0mozboxshadow 1px 2px 3px a4a4a4webkitboxshadow 1px 2px 3px a4a4a4boxshadow 1px 2px 3px a4a4a4jquerydropdown ul li ul li margin 0padding 0float noneposition relativezindex 10jquerydropdown ul li ul li a width 180pxpadding 10pxzindex 10jquerydropdown ul li ul li ahover background e0e0e0,['jquery'] +111746,mysqldump from powershell and windows encoding i am doing an export from command line on msdos with mysqldump mysqldump u root p defaultcharactersetutf8 w b dbname cmysql backupsqlmy databasetables are encoded with utf8 and i specify the same encoding when i did the dump but when i open the file with notepad or scite i see an encoding of utf16 ucs2 if i do not convert the file with iconv to utf8 before running the import i got an errorit seems that msdos cmdexe is redirecting by default with utf16 can i change this a side note i use powershell to call mysqldumpupdate it seems that it occurs only when calling mysqldump from powershell i change the command line with the one i use in my ps script,['mysql'] +111749,generics overload resolution and delegates sorry cannot find a better title possible duplicatewhy is funct ambiguous with funcienumerablet i noticed a very weird overload resolution issue with genericsconsider the following methodsstatic void footsourcetsource element functsource int selector intdumpstatic void footsourcetsource element functsource double selector doubledumpstatic t identitytt value return valuec 4 tested in linqpadif i try to call foo with a lambda expression as the selector everything works finefoo42 x x prints intbut if i replace x x with identity the compiler cannot decide between the 2 foo overloadsfoo42 identity the call is ambiguous between the following methods or properties userqueryfoointint systemfuncintint and userqueryfoointint systemfuncintdoublehow can the second overload be a valid candidate type inference correctly determines that tsource is int so the t parameter for the identity method has to be int as well so the return type has to be int too identity could be a funcintint or a funcdoubledouble but not a funcintdoubleand it gets worse even if i specify all type parameters explicitly i still get the same errorfooint42 identityint the call is ambiguoushow can there be any ambiguity here as far as i can tell there is no way the overload that takes a funcintdouble can be a candidate i guess the explanation must be somewhere in the specifications but i cannot find the relevant bit or it might be a bug in the compiler but i guess it is unlikelynote that it does work if i explicitly create the delegatefoo42 new funcint intidentity prints intso could someone explain whats going on here also why does it work with a lambda but not with a method group,['c#'] +111753,getting error 400 404 httputilityurlencode not encoding full string why do the following urls give me the iis errors belowa a2 this works but is not the result from httputilityurlencodeb 2623funkypageerror for ahttp error 40411 not foundthe request filtering module is configured to deny a request that contains a double escape sequenceerror for bhttp error 40 bad requestaspnet detected invalid characters in the urlthe last part of the url after show is the result after the text is being sent through httputilityurlencode so according to microsoft it is url encoded correctlyif i user httputilityurlpathencode rather than httputilityurlencode i get the a2 results but b ends up looking likefunky20pagewhich is still wrong does microsoft know how to url encode at all is there a function someone has written up to do it the correct wayediti have written my own encoderstatic public string urlencodestring encode if encode null return null string encoded foreach char c in encode int val intc if val 48 val 57 val 65 val 90 val 97 val 122 encoded c else encoded valtostringx return encodedthe function works with a2 above just fine the result for b isbut even though that looks like a nice valid url iis still gives me ahttp error 40 bad requestaspnet detected invalid characters in the url,['c#'] +111754,python close file descriptor question i think this question is more of a coding style rather than technical issuesaid i have a line of codebuf opentesttxtrreadlineswill the file descriptor automatically close or will it stay in the memoryif the file descriptor is not closed what is the prefer way to close it,['python'] +111758,have global function definition in header file and avoid duplicated symbol linkage error i have the following code in a header only filepragma onceclass error code public unsigned int64 hi unsigned int64 lo stdostream operator stdostream o const error code e return o ehi elo i get linkage error when there are 2 cpp in the project include this header fileerror lnk2005 class error code cdecl operatorclass error code const class vitroxerror code const uyaaverror code0abv100z already defined in xobji know i can resolve this problem if i move the definition of operator to a cpp file or to a dll file however i just would like to have them in a single header file is there any technique to achieve so or must i separate the definition to another file,['c++'] +111760,pdo prepared statements nulls i have a delete query that i am running but just realized that this does not work when user id is null which happens in certain casesid 1user id nulldelete sqlprepare delete from game player where id and user id if deleteexecutearray id user idis there any work around other than having different queries for when the value is null since apparently the only way to have the where work properly is with user id is null instead of user id null,"['php', 'sql']" +111762,uislider and uiscrollview i have a uislider as part of a view that is loaded into a uiscrollview with paging enabled i have noticed an unexpected behavior if the user tries to use the slider quickly ie press and move it activates the scroll view causing the page to switch however if your press and hold for a second the slider activates and you can then adjust the slider value this behavior is undesirablewhat is the best way to make the uislider responsive when loaded into a uiscrollview i have thought about adding a blocker view that just eats up touch events that is placed under the slider but not sure if this is the best way to go about it,['iphone'] +111772,how to detect circular gesture via gesture recognizer i am trying to implement a volumecontrollike round button currently i can detect swipes by the gesture recognizer how can i detect a circular gesture clockwise and anticlockwise on the button thanks,['iphone'] +111775,getting app icon in android i am having some trouble retrieving icons for installed android app the following code returns icons for all apps however some apps are returned with small icons perhaps from drawable ldpi folder while some with large icons listpackageinfo package getpackagemanagergetinstalledpackages0forpackageinfo p package iappicon papplicationinfoloadicongetpackagemanager how can i get icons which are all of the same size just like in manage application section of android,['android'] +111779,css border for checkbox i am applying a style for a checkbox from jqueryreg checkboxcssborderthin solid redthe border works fine in ie but not in mozilla how can i make it browser compatible,"['jquery', 'css']" +111815,how can i get mime type of an inputstream of a file that is being uploaded simple question how can i get mime type or content type of an inputstream without saving file for a file that a user is uploading to my servlet,['java'] +111833,rationale for koenig lookup whats the rationale of koenig lookupcannot avoid thinking of it like something that makes your code a lot harder to read and more instablecould not they define koenig lookup so that it only work for specific cases ie nonmember operators or when explicitly required,['c++'] +111835,soft deletes navigation properties in ef4 ctp5 poco basically i want to use soft deletes but have the navgiation properties not show the soft deleted records are there any ways to intercept the navigation property queries on poco objects in entity frameworkvery simple example public class product public int id get set public string name get set public int categoryid get set public virtual category category get set public bool isdeleted get set public class category public int id get set public string name get set public virtual icollectionproduct products get seti can easily insert the criteria into my repository so that it does not return any products where isdeletedtruehowever i cannot see how to accomplish this for other objects that have soft deleted entites in their navigation propertiesie if i access mycategoryproducts where mycategory is a category it should not show any products where isdeletedtruei could potentially workaround this using an additional property of categorypublic icollectionproduct currentproducts get return thisproductswhereppisdeleted but that is not the elegant solution i am looking for is there a way to attach criteria to the navigation property or any better solutions for how to handle this,['c#'] +111874,php check who had read sent email i am sending email to some users and wants to know who had read it means if some one had read that email then a log file will maintain which contain the email address of that user with datetimeipfor this i send a javascript function with the email html template which just alert the email address of the user when ever a user opens that email likeforn0 nsizeofcheckbox n mail new phpmailer mailishtmltrue mailsubject subject function script languagejavascriptfunction statsemailidalertemailidscript bodyopen body onloadstatscheckboxn msg body body tabletrtdhello everyonetdtrtablebody mailbody functionbodyopenmsg body mailwordwrap 50 mailfromname muhammad sajid mailismail mailfrom mailaddaddresscheckboxn sent mailsend the html template works fine and shows an alert popup on page load but it does not works if i use to send this html templateand i only want to solve this issue using php5xx javascript no other software or third party toolany help,['php'] +111890,use of for in a c application i have been looking through some sample source code for an application i use and i came across this linefor the rest of the applications codeit looks like this is to create an infinite loop but i am not familiar with and it is very hard to google unfortunately,['c#'] +111892,twisted server for multiple clients i want to write a server that can accept multiple clients in python twisted i am already quite familiar with socket programming with the standard python socket module but here comes the troublei think twisted is really hard to get into and i have read some tutorials about it but a thing that i cannot really find is a simple socket server that accepts multiple connections can anyone help if i missed some valuable information online please let me know because i am pulling my hair out any help is much appreciatedandesay,['python'] +111898,changing the keypress in an input box or contenteditabletrue div how can i modify a keypress for the letter a to return a keybress for the letter b ie every time you type the letter a in the div the output is actually the letter bi am not that concerned with a solution that works in iejust one that works in safari chrome ffin chrome i can see that a keypress event has the properties charcode keycode and which all of which get assigned the keypress event number if i fire an event on a keypress i can modify these values but i cannot figure out what to return so that the actual key that gets typed is different for examplewindowkeypressfunctione window is a jquery object echarcode 102 ewhich 102 ekeycode 102 consoleloge return ei can also see that along with charcode which and keycode there is also an originalevent property which in turn also has these properties however i have not been able to modify those i tried with things like eoriginaleventcharcode 102,"['javascript', 'jquery']" +111899,how to get value after decimal point from a double value in c i would like to get the decimal value from a double valuefor example23456 04561123 023could anyone let me know how to do this in cthanksmahesh,['.net'] +111901,will the cache line aligned memory allocation pay off i just know basic ideas on aligned memory allocation but i did not cared much about align issue because i am not an assembly programmer also did not have experience with mmxsimd and i think this is the one of the the premature optimizationsthese days people saying more and more about cache hit cache coherent optimization for size etc some source code even allocate memory explicitly aligned on cpu cache linesfrankly i do not know how much is the cache line size of my i7 cpu i know there will be no harm with large size align but will it really pay off without simd let us say there 10 items of 100 bytes data in a program and access to these data is the most intensive work of the programif we change the data structure and make all the 100 bytes size data aligned by 16 byte is it possible to gain noticeable performance gain 10 5,"['c++', 'c']" +111916,throwing an exception of the proper type in my code i have often situations like thispublic void mymethodstring data anotherclass objectofanotherclass getobjectdata if objectofanotherclass null throw new whatexceptiontype1objectofanotherclass is null if objectofanotherclasomeproperty 0 throw new whatexceptiontype2someproperty must not be negativeimagine that getobject makes use of some external libraries which are not under my control and that this library returns null if no object for data exists and considers a negative someproperty as a valid state and therefore does not throw an exception further imagine that mymethod cannot work without objectofanotherclass and does not make sense with a negative somepropertywhat are the proper exceptions for whatexceptiontype12 to throw in this situationbasically i had four options in mind1 invalidoperationexception because mymethod does not make sense under the conditions described above on the other hand the guidelines and intellisense in vs too say that an invalidoperationexception should be thrown if the object the method belongs to is in an invalid state now the object itself is not in an invalid state instead the input parameter data and some other operations based on this parameter lead to a situation where mymethod cannot operate anymore2 argumentexception because there are values for data the method can work with and other values the method cannot but i cannot check this by inspecting data alone i have to call other operations before i decide3 exception because i do not know which other exception type to use and because all other predefined exceptions feel too specialized and not fitting to my situation4 mycustomexception my own exception type derived from exception this seems always an option but i am worried that i have to define lots of special exception classes for many different error conditions when i start to follow this patternare there other and better options what are the arguments in favor or against those optionsthank you for feedback in advance,"['c#', '.net']" +111933,why is php treating carriage return linefeed combo as a single byte i have a php script that truncates a string at 41 bytes i call strlen on the string to check its size however if the string has a rn combo this combo is treated as one byte so in my case instead of 42 bytes php thinks it is 41 bytesalso substr truncates it to 42 instead of 41 bytes if strlenvalue 41 value substrvalue 0 41another weird condition i have a large set of data i am passing through this function thousands of strings if i use a simpler test data set then the code works correctly treating rn as 2 bytesany ideasthanks,['php'] +111943,div overflow scrolltobottom is it possible if i have a div with overflowauto so that it is a scrollable div and i load it with information that makes a significant scroll area is there a way that when i load the information the div shows the bottom results or essentially scrolls to the bottomi have seen jquery solutions but this is for use in an hta so i cannot use jquery is there a purely javascript way to accomplish this,"['javascript', 'html']" +111947,drawing app on ipad using opengl i am creating a drawing app text for the ipad using opengl i have already had a look at apples example glpaint and my app is now based on that code my app should be just for drawing text not for painting pictureswell my app works i can write some text but the writing is not really good it does not make fun to write the drawing path is not smooth it is angularly because i am drawing a line from one point to another and the path has everywhere the same width my idea is when youre writing fast the line is thinner than when youre writing slow it should be the same experience like writing with a real pen how can i make the path look much smoother how can i vary the width of the line depending on the speed of writing here you can see what i mean,['iphone'] +111950,retrieve the user profile image from twitter i am using the twitter4j api in java to retrieve the profile image for a twitter user whose logged in the command is something like twittergetprofileimagetwittergetscreenname imagesizewhat is the image size how can i thisplay the profileimage object in a label for example,['java'] +111953,rails 3 link to to destroy not working i am trying to create a destroy link to my users controller i am also using devisehere is my code view link to delete user child confirm are you sure you want to delete childfull name method delete class useradditional style fontsize12pxfontweightnormal controllerdef destroy if user userfindparamsid userdestroy respond to do format formathtml redirect to account index path formatxml head ok end endendroutesdevise for users resources users except newthe link translates to localhost30users10when clicked this opens the users show instead of deleting themany ideas,['ruby-on-rails'] +111970,fontface works in ie8 but not ie9 as described above i have issues with fontface not thisplaying in ie9 although it thisplays fine in every other browser including ie8 and under additionally when viewing locally on my computer ie9 does thisplay the font just not when fully livethe site isbigwavedesigncoukgccgccthe code used is fontface fontfamily leaguegothicregular src urlleague gothic 0webfonteot src localleague gothic regular urlleague gothic 0webfontwoff formatwoff urlleague gothic 0webfontf formattruetype urlleague gothic 0webfontsvgwebfonta36nfpye formatsvgfontweight normalfontstyle normalanyone any ideas why this might be occurringcheersediti have found the following site that thisplays the same font ok in ie9 anyine any ideas how he did that,['css'] +111992,why dec 31 2010 returns 1 as week of year for instancecalendar c calendargetinstancedateformat sdf new simpledateformatddmmycsettime sdfparse31122010outprintln cget calendarweek of year prints 1same happens with joda time,['java'] +112013,what tools and extensions are critical for magento development were building a nice little community of magento experts here i am curious what magento extensions and other software tools ides editors etc everyone is using to help with their development projectsboth free and commercial tools are more than welcome,['php'] +112021,generate walking directions with maps app ios as of now i successfully generate directions with maps app from my app with the following code nsstring formattedgroceryaddress nsstring stringwithformatenhanceduiactionsheet actionsheetgroceryaddress stringbyreplacingoccurrencesofstring withstringnsstring routestring nsstring stringwithformatdaddrlocaldatahelperuserlocationcoordinatelatitudelocaldatahelperuserlocationcoordinatelongitudeformattedgroceryaddressuiapplication sharedapplication openurlnsurl urlwithstringroutestringit opens the maps app with the appropriate driving directions the thing is i would like to open maps with the walking directions by default maybe i can pass another parameter in my request to do thatanybody knows how thanks,['ios'] +112022,resolve icontainer what is the suggested method of getting the autofac container from inside a class in the application does autofac provide for resolving an icontainer property on a class or do i need to store the container globally once i have build it,['c#'] +112036,why hibernate changed hibernateexception to unchecked runtimeexception i know that in some version hibernate exceptions were changed to be unchecked what is the reason is this a philosophy issue or practical one,['java'] +112084,nsdate substract one month i want two nsinteger year month to go one month back eg now is 201101 how can i get 201012 adding is one thing but i want to substract hope someone could help me a bit out herensdate date nsdate datensdatecomponents datecomponents calendar componentsunitflags fromdatedatensinteger year datecomponents yearnsinteger month datecomponents monthcalendar releasensstring pdf name nsstring stringwithformatfile d 02dpdf year monthgreets endoedit my solution nscalendar calendar nscalendar alloc initwithcalendaridentifiernsgregoriancalendar nscalendarunit unitflags nsyearcalendarunit nsmonthcalendarunit nsdaycalendarunit nshourcalendarunit nsminutecalendarunit nssecondcalendarunit nsdate date nsdate date nsdatecomponents datecomponents calendar componentsunitflags fromdatedate nsinteger year datecomponents year nsinteger month datecomponents month bool substractonemonth yes if substractonemonth if month1 year month 12 else month calendar release nsstring pdf name nsstring stringwithformatfile d 02dpdf year month,"['iphone', 'objective-c']" +112085,django get html output into a variable instead of using render to response which will send the html output back to browser i would like to take the results generate html using templates output the html into a variable in my viewspy how can i do thisupdate solved the way to do this from djangotemplateloader import render to stringrendered render to stringmy templatehtml foo bar thanks to ned for pointing to the correct docs,['python'] +112101,uiwebview loadhtmlstring shows blank screen i have a strange problem with uiwebviews loadhtmlstring where it would only thisplay a blank view when i called loadhtmlstring with my content html string it does not matter what the content of the htmlstring is it simply does nothingthe strange thing is that it used to work a few weeks ago when i tested it on the simulator and device my code is belownsmutablestring shtmlbuf nsmutablestring stringwithstringbody stylebackgroundcolor 0 color f fontfamily helvetica fontsize 10pt width 300px wordwrap breakwordif m ocallarray count 0 m oputarray count 0 shtmlbuf appendstringswarrtitle if m ocallarray count 0 nsstring formattedcall nsstring stringwithformat br scalltitleself arraytostringm ocallarray shtmlbuf appendformat formattedcall if m oputarray count 0 nsstring formattedput nsstring stringwithformat br sputstitleself arraytostringm oputarray shtmlbuf appendformat formattedput if m obullarray count 0 m obeararray count 0 shtmlbuf appendstringscbbctitle if m obullarray count 0 nsstring formattedbull nsstring stringwithformat br sbulltitleself arraytostringm obullarray shtmlbuf appendformat formattedbull if m obeararray count 0 nsstring formattedbear nsstring stringwithformat br sbeartitleself arraytostringm obeararray shtmlbuf appendformat formattedbear if m ootherarray count 0 nsstring formattedother nsstring stringwithformat br sothertitleself arraytostringm ootherarray shtmlbuf appendformat formattedotherm odatapresentview loadhtmlstringshtmlbuf baseurlnilnote the html can render on a regular web browser before this problem so the html is not a problemedit added initialization codecreate wcbbc panelwcbbcpanel warrantsandcbbc alloc initwithframecgrectmake320 0 320 230m omaincontentscrollview addsubviewwcbbcpaneluiview initialization code idinitwithframecgrectframe self super initwithframeframe if self initialization code cgrect oframe frame cgpoint opositioncoords cgpointmake0 0 oframeorigin opositioncoords m odatapresentview uiwebview alloc initwithframeoframe m odatapresentview loadhtmlstringhtmlbody stylebackgroundcolor 0 color f fontfamily helvetica fontsize 10pt width 300px wordwrap breakwordbodyhtml baseurlnil m odatapresentviewdelegate self self addsubviewm odatapresentview return self,['iphone'] +112107,python 256bit hash function with number output i need a hash function with a 256bit output as long intfirst i thought i could use sha256 from the hashlib but it has an string output and i need a number to calculate with converting the 32 byte string to a long would work also but i did not find anythingin struct there is a unpack function but this only works for 8 byte long types and not for longer longs,['python'] +112135,what is the cls variable used in python classes why is cls used instead of selfany help appreciated,['python'] +112140,ios deployment target missing i am updating an older iphone application and the usual base sdk missing pops up when i open the project settings and try to set the ios deployment target it is not in the list this is the first time i have encountered thisi am able to set the base sdk to latest sdk but many of the options are missing from the settingswhat should i do to update this project so it has all the settings,['iphone'] +112146,how to call external url in jquery i am trying to put comments on facebook wall using jquerybut my ajax call not alowing external url can anyone explain how can we use external url with jquery below is my code var fburl 481759124404commentsaccess tokenmy tokenajax url fburl data messagecommentdata type post success function resp alertresp error functione alerterror e its giving xmlhtprequest error,['jquery'] +112149,how to encode url in javascript and decode it in c i have a url with querystrings through which some data are passed i want to retrieve the data in the server side what is the solution for this problem,"['c#', 'javascript']" +112154,why does calling ienumerablecount create an additional assembly dependency assume this chain of dll referencestestsdll automationdll whitecoredllwith the following line of code in testsdll where everything buildsresultmissingpaths now when i change this to resultmissingpathscounti get the following build error for testsdll whiteuiitem is not defined in an assembly that is not referenced you must add a reference to whitecoredll and i do not want to do that because it breaks my layeringhere is the type definition for result which is in automationdllpublic class hasresult public hasresultienumerablestring missingpaths missingpaths missingpaths public ienumerablestring missingpaths get set public bool allexist get return missingpathsany down the call chain the input param to this ctor is created via the treenode class is in whitecoredllassetpathswhereassetpath findtreenodeusingcachetreehandle assetpathwhy does this dependency leak when calling count on ienumerable i then suspected that lazy evaluation was causing this for some reason so i slotted in an toarray in the above line but did not workupdate 2011 01 07 curiouser and curiouserit would not build until i add a whitecore reference so i add a reference and build it in order to find the elusive dependency source open it up in reflector and the only references listed are automation mscorlib systemcore and nunit so the compiler threw away the white reference as it was not needed ildasm also confirms that there is no white assemblyref entryany ideas on how to get to the bottom of this thing primarily for now i wanna know why reasons what are the chances that this is an vs2010msbuild bugupdate 2011 01 07 2as per shimmys suggestion tried calling the method explcitly as an extension methodenumerablecountresultmissingpathsand it stops cribbing not sure whyhowever i moved some code around after that and now i am getting the same issue at a different location using ienumerable this time reading and filtering lines out of a file on thisk totally unrelated to white seems like it is a symptomfixvar lines filereadlinesafilepathtoarrayonce again if i remove the toarray it compiles again it seems that any method that causes the enumerable to be evaluated toarray count tolist etc causes this let me try and get a working tinyapp to demo this issueupdate 2011 01 07 3phew more information it turns out the problem is just in one source file this file is linqphobic any call to an enumerable extension method has to be explicitly called outthe refactorings that i did caused a new method to be moved into this source file which had some linq still no clue as to why this class thislikes linqusing systemusing systemcollectionsgenericusing systemiousing systemlinqusing gsourautomationconstantsusing gsourautomationframeworkusing nunitframeworknamespace gsacceptancetests public abstract class configurethingbase ourtestfixture private static ienumerablestring getexpectedthingsforstring param even this would not compile although it compiles fine in an adjoining source file in the same assembly ienumerablestring s new string0 consolewritelinescount this is the line that is now causing a build failure var expectedinfo filereadlinessomecsvfilepath whereline linestartswithrem stringcomparisoninvariantcultureignorecase selectline linereplaceplaceholder param toarray unrolling the linq above removes the build error var expectedinfo enumerabletoarray enumerableselect enumerablewhere filereadlinessomecsvfilepath line linestartswithrem stringcomparisoninvariantcultureignorecase line linereplaceplaceholder paramupdate 2011 01 11 4narrowed it down to what seems the perp but no motive resumed the quest post the weekend and using the evergreen process of elimination was able to zone in on the offending bitthe problem is the following using directive in the source file in testsdllusing gsourautomationframeworknext i went after the most probable suspect within this namespace and i had whiteextensions under the spotlightnamespace gsourautomationframework public static class whiteextensions public static t pollandgethis window parentwindow string automationid where t uiitem public static window waitforwindowwithtitlethis application application string windowtitle public static bool hastreenodethis tree treehandle string assetpath public static hastreenodesresult hastreenodesthis tree treehandle ienumerablestring assetpaths this led to 3 fixes both of which workturn the extension methods into normal static methodsmove this class into a subnamespace gsourautomationframeworkwhitemake this an internal class as it is meant for internal consumption once again the guideline of choosing the most restrictive access modifier bites mealthough my specific instance is fixed can this update help someone explain the reason for this if not shimmy gets the tick for pointing towards the right direction,"['c#', '.net']" +112160,how to use visible and invisible for a button in android i want to make a button invisible when i click another button then the invisible button will become visible and then perform onclick actions on the visible buttonwhat onclick actions i can use on the visible button i used this method shown below donebutton button findviewbyidriddone donebuttonsetonclicklistenerthis donebuttonsetvisibilityviewinvisible override public void onclickview v todo autogenerated method stub ifvequalsremove donebuttonsetvisibilityviewvisible ifvequalsdonebutton intent inew intentonethissecondclass startactivityi finish donebuttonsetvisibilityviewinvisible in the above method the invisible and visible propertyes are working but onclick action is not working so please tell me an answer for the above problem or tell me if there is any other method for visible and invisible on button and onclick action on that buttonand i also used this method donesetclickabletrue donesetonclicklistenernew onclicklistener public void onclickview v intent inew intentonethissecondclass startactivityi finish,['android'] +112163,retrieve an object from hashset in c possible duplicatewhy cant i retrieve an item from a hashset without enumeration i need to add a lot of objects to a setand i should retrieve them very fast the only way that i know is using hash but the hashset class in c does not contain any get method the dictionary class is not useful because finding an object is very timeconsuming in a dictionary,['c#'] +112171,not class selector in jquery is there a simple selector expression to not select elements with a specific classdiv classfirstfoo div classfirstmoo div classfirstkoo div classfirstbar secondfoo i just want to get the first three divs and trieddivclassfirstclassfirstbarbut this receives all as the last div contains more than firstbar is there a way to use a placeholder in such an expression something like thatdivclassfirstclassfirstbar does not seem to workany other selectors that may help,"['javascript', 'jquery']" +112197,jquery add iframe with content i have such problemi need to open iframe in fancybox i need iframe because of i need to browse through links in opened document and stay in fancyboxbut i want to put content into iframe from variable not through src attribute i have already got content by ajax i need to do some checks on content before put it to iframe so there are no way to do it instead of ajax query so i do not need one more queryfancybox do not allow to use content attribute with typeiframe so i decided to create iframe dynamically insert my content into it and show iframe by fancybox as a regular blockit is likejqueryiframe idsomeidappendtobodycontentsfindbodyappendcontentand thanjqueryiframe idsomeidfancyboxbut the first part do not work i can see the iframe that was added to page but without any content i have full html page in variable content but when i try to append just some text it do not work as wellwhat i have done wrongmaybe there are another way to do what i needthanks for your advise,['jquery'] +112215,random element of list from linq sql in cnet 35 i get by linq all my users from my usertablenow i will return a random user from this list how to do,"['c#', '.net']" +112219,how to start a new list continuing the numbering from the previous list i am trying to do something that used to be really easy before the start attribute on ol tags was deprecated i would just like to have a pair of ordered lists in my page but start the numbering of the second list where the first one finished something like1 do stuff2 do stuffheres a paragraph3 do stuffi have seen that the counterreset and counterincrement css properties should be able to achieve this but i cannot get it working heres my code so farhtmlhead style typetextcss ol li counterincrement mycounter olstart counterreset mycounter olcontinue counterreset mycounter 2 styleheadbody ol clastart liyou cannot touch thisli liyou cannot touch thisli ol pstop hammer timep ol classcontinue liyou cannot touch thisli olbodyhtmlto be honest even if that worked it wouldnt be ideal i do not want to have to specify the number reached by the first list in my olcontinue selectorwhat am i doing wrong whats the minimal htmlcss combination required to achieve the desired effectthanks in advance the solution i finally adoptedheres the html and css code i finally used thanks to felix for getting me there must also mention that lee offers an interesting jquery alternative toohtmlhead style typetextcss olsplit liststyletype none olsplit libefore counterincrement mycounter content countermycounter 00a0a0 olsplit li textindent 13em olstart counterreset mycounter styleheadbody ol clasplit start liyou cannot touch thisli liyou cannot touch thisli ol pstop hammer timep ol clasplit liyou cannot touch thisli olbodyhtmlcaveat it turns out that this solution does not work in ie8s compatibility view and probably other versionsbrowsers too if that does not bother you great,"['html', 'css']" +112228,is using using better possible duplicatewhat is the c using block and why should i use it my question is using usingado something with a better than declaring a and using it that way ie more secure faster see examples for clarificationexample 1without usingstreamwriter swstring linesw new streamwriterdnewconxmlswwritelinexml version10 encodingutf8 standalonenoswwritelineconfigfor int i 0 i 36 i line line xmlnodesi line valsi line xmlnodesi swwritelineline swwritelineconfigswcloseswthispose example 2with usingstring line using sw new streamwriterdnewconxml swwritelinexml version10 encodingutf8 standaloneno swwritelineconfig for int i 0 i 36 i line line xmlnodesi line valsi line xmlnodesi swwritelineline swwritelineconfig,['c#'] +112231,how to handle c exceptions when calling functions from lua i have a working c function that i am able to call from lua to demonstrate my problem here is an exampleint pushhellolua state l string strhello lua pushlstringl strdata strlength return 1note i know i do not have to use string variable there but it is there to demonstrate the problemhere are my two problemswhen i call this function from lua string constructor may throw an exception is that a problem will lua handle it and unwind the lua stack properly i do not think so how can i solve that do i need to add trycatch around all such code and convert the exception to lua error is not there a better solutionanother problem that i have probably solved by compiling lua as c is when lua pushlstring calls lua error string destructor would not be called if longjmp was used is the problem solved by compiling as c and throwing exceptions instead of using longjmpto clarify possible solution i can see to problem 1 would be thisint pushhellolua state l string str try strassignhello catchexception e lual errorl ewhat lua pushlstringl strdata strlength return 1but that is very ugly and error prone as trycatch would need to be added to many places it could be done as a macro and put around every command that can throw but that would not be much nicer,['c++'] +112233,how can i customize the system menu of a windows form i want to add the age old about menu item to my application i want to add it to the system menu of the application the one which pops up when we click the application icon in the topleft corner so how can i do it in net,"['c#', '.net']" +112237,custom typeconverter with variable standardvalues i have a datagridview with info about competitors i thisplay each copmetitors properties in propertygrid i want some of those properties eg degree city institute to be dropboxes with values taken from database for this purpose i can create a custom typeconvertor like this oneclass degreetypeconverter stringconverter static string valuelist bachelor master student public override bool getstandardvaluessupported itypedescriptorcontext context return true public override bool getstandardvaluesexclusive itypedescriptorcontext context return true public override standardvaluescollection getstandardvalues itypedescriptorcontext context return new standardvaluescollection valuelist typeconvertertypeofdegreetypeconverter public string degree get return degree set degree value but i want to get that valuelist from database and i have 14 such properties so some universal converter would be much better than 14 converters with the only difference valuelist is it possible to create a typeconverter with variable valuelist for example passed into typeconverter as parameter in constructor or maybe there is another way to have in propertygrid a dropbox with variable value listhope it was clear enoughthnx in advance,"['c#', '.net']" +112245,json allowget error this error comes up in our mvc app randomly sometimes doing the same exact thing it would not sometimes it will does anyone know if this has to do with anything that could be a simple fix or if this is something common that a lot of you have seensysteminvalidoperationexception this request has been blocked because sensitive information could be thisclosed to third party web sites when this is used in a get request to allow get requests set jsonrequestbehavior to allowget at systemwebmvcjsonresultexecuteresultcontrollercontext context at systemwebmvccontrolleractioninvokerinvokeactionresultcontrollercontext controllercontext actionresult actionresult at systemwebmvccontrolleractioninvokerc thisplayclass14b 11 at systemwebmvccontrolleractioninvokerinvokeactionresultfilteriresultfilter filter resultexecutingcontext precontext func1 continuation at systemwebmvccontrolleractioninvokerc thisplayclass14c thisplayclass16b 13 at systemwebmvccontrolleractioninvokerinvokeactionresultfilteriresultfilter filter resultexecutingcontext precontext func1 continuation at systemwebmvccontrolleractioninvokerc thisplayclass14c thisplayclass16b 13 at systemwebmvccontrolleractioninvokerinvokeactionresultfilteriresultfilter filter resultexecutingcontext precontext func1 continuation at systemwebmvccontrolleractioninvokerc thisplayclass14c thisplayclass16b 13 at systemwebmvccontrolleractioninvokerinvokeactionresultwithfilterscontrollercontext controllercontext ilist1 filters actionresult actionresult at systemwebmvccontrolleractioninvokerinvokeactioncontrollercontext controllercontext string actionname at systemwebmvccontrollerexecutecore at systemwebmvccontrollerbaseexecuterequestcontext requestcontext at systemwebmvccontrollerbasesystemwebmvcicontrollerexecuterequestcontext requestcontext at systemwebmvcmvchandlerc thisplayclass8b 4 at systemwebmvcasyncasyncresultwrapperc thisplayclass1b 0 at systemwebmvcasyncasyncresultwrapperc thisplayclass81b 7iasyncresult at systemwebmvcasyncasyncresultwrapperwrappedasyncresult1end at systemwebmvcmvchandlerendprocessrequestiasyncresult asyncresult at systemwebmvcmvchandlersystemwebihttpasynchandlerendprocessrequestiasyncresult result at systemwebhttpapplicationcallhandlerexecutionstepsystemwebhttpapplicationiexecutionstepexecute at systemwebhttpapplicationexecutestepiexecutionstep step boolean completedsynchronously,['jquery'] +112247,c compare the data in two object models i have a dialog when spawned it gets populated with the data in an object model at this point the data is copied and stored in a backup object model when the user has finished making their changes and click ok to thismiss the dialog i need a quick way of comparing the backup object model with the live one if anything is changed i can create the user a new undo statei do not want to have to go and write comparison function for every single class in the object model if possibleif i serialised both object models and they were identical but stored in different memory locations would they be equal does some simple way exist to compare two serialised object models,['c#'] +112250,scan site for images and alt attributes wed like to run a scan on our site that returns a report with the followingeach image tag found and a visual representation of that image on the reportthe alt attribute for that image also identify if an alt attribute is not foundis there a simple tool that does this were attempting to check for alt attributes and make sure the alt attributes accurately describe to the image they represent that is why the visual representation in the report is important,['html'] +112252,parsing html with the html agility pack and linq i have the following htmltbody tr td classname test1 td td classdata data td td classdata2 data 2 td tr tr td classname test2 td td classdata data2 td td classdata2 data 2 td trtbodythe information i have is the name so test1 test2 what i want to know is how can i get the data that is in data and data2 based on the name i have currently i am usingvar data from tr in docdocumentnodedescendantstr from td in trchildnodeswherex xattributesclassvalue name where tdinnertext test1 select trbut i get object reference not set to an instance of an object when i try to look in data,['c#'] +112261,css rotate property in ie i want to rotate the div to a certain degree in ff it functions but in ie i am facing a problemfor example in the following style i can set rotation1 to 4 filter progiddximagetransformmicrosoftbasicimagerotation1this means that the div will be rotated to 90 or 180 or 270 or 360 degree but if i need to rotate the div only 20 degrees then it does not work anymorehow may i solve this problem in ie,['css'] +112289,poco vs entity framework generated classes what are the advantages of using one over the other i know poco classes are more optimal but are they worth the overkill and should we always be using pocos or is there a time when you should prefer entity framework classes,['.net'] +112290,out of memory error in ant i am trying to run ant task however i get the following errorjavadoc javadoc error javalangoutofmemoryerror please increase memoryjavadoc for example on the sun classic or hotspot vms add the option jxmxjavadoc such as jxmx32mjavadoc 1 errorjavadoc 103 warningsi have tried googling to find out how i can set this value but i cannot find iti have tried javadoc maxmemory256mi have triedexport ant optsxmx256mbut i still get the same exception i have tried to increase the value to 1024m witouth any successupdatei solved it it had nothing to do with little memory it was an endeless loop in my javadoc generation,['java'] +112293,php instanceof equivalent for a stringrepresented classname it is best to explain by an examplei look for a function thefunctionilookfor that will make the code workmyclassname somenameparentorinterfacename someparentif thefunctionilookfor myclassname echo is parrentedit i try to avoid instantiating the class just to perform this check i would like to be able to pass 2 string parameters to the checking function,['php'] +112300,any good zend framework minify implementations are there any good implementations of minify integration with zend framework i am looking for examples i would love to have a plugin that overrides thisheadlink and spits out the correct minified urlcontenteditit seems most examples i find are not fully optimized in one form or fashion i am looking for a solution that meets the following requirementsreduces multiple links and script tags to one request one for link and one for scriptsthe closest i have seen is a request path that passes a commadelimited string to min like soscript srcminffile1jsfile2jsfile3js typetextjavascriptscriptwhy not something that combines all scripts into one file on thisk on the fly and then caches it so that you are not doing the minification on every requestscript srcjsappjssomerandomstringhere typetextjavascriptscriptthe combining aspect should maintain order in reference to prepend append etcwhile i do not care so much about sending correct expires headers because i force gzipping etags and expires headers on the serverside having that optional would be beneficial to other users lastly having a build script that generates the minified assets is not necessary bad as long as it is easy to do and does not require a code change after every build,['php'] +112304,what does mean in java possible duplicatejava array argument declaration syntax i have seen to be used in between of object type and object name in java i get the idea that it represents collection of the object note the following examplespublic setmembersmember membersmap map my question is what really means i have never seen this in any documentation where they explained it,['java'] +112306,what is resolveassemblyreferencecache i am trying to figure out what this file is or rather these files are fori have found a number of webpages that mention it but the answer to the question is always something like this file is not your problem without describing what the file is i do not seen an obvious page on msdn eitherthe files themselves are pretty big and not textonly though they have a lot of text i am guessing it is something used during compilation only though the modification date is older than any of my object files is this related to pdb files or debugging at all,"['c#', '.net']" +112312,append results from two queries and output as a single table i have two queries that i have to run i cannon join them but their resultant tables have the same structrure for example i have select from products where producttypemagazineselect from products where producttype booki have to combine the result of these two queries and then output it as one single result i have to do this inside a stored procedure ps these are just examples i provided i have a complex table structure the main thing is i cannot join them,['sql'] +112325,how to convert string hhmm to joda duration i have a field in a form to state the time duration of an eventsay the event is to last 15 mins so the field will have the following value 0015if it is to last 1 hour 0100 etchow can i create a jodatime duration object with the string hhmmlooking at jodatime home page it mentions that it is possible to create a duration object from specified object using convertermanager and durationconverter respectivelymy question is how can i implement the above interfaces so that i can create a duration object by passing the a 430 parameterthanks in advancelucas,['java'] +112336,partial order sorting say we have some items and each defines some partial sorting rules like thisi am a and i want to be before bi am c and i want to be after a but before dso we have items abcd with these rulesabca cdnothing else so b and d have no preferences in ordering and are considered equalas you see transitive relation rules are not working here however if ab it still means that ba so there can be multiple possible results of sortinga b c da c d ba c b da b c dhow can i implement a sorting algorithm that handles such a situationthe reason therere multiple loadable modules and some of them depend on others in a way each module can declare simple rules relative to other modulesload me before module aload me after module bload me before module a but after module bnow i need to implement this ordering somehow answer code by paddy mccarthy mit r1try from functools import reduceexcept passdata des system lib setstd synopsys std cell lib des system lib dw02 dw01 ramlib iesplit dw01 setie dw01 dware gtechsplit dw02 setie dw02 dwaresplit dw03 setstd synopsys dware dw03 dw02 dw01 ie gtechsplit dw04 setdw04 ie dw01 dware gtechsplit dw05 setdw05 ie dwaresplit dw06 setdw06 ie dwaresplit dw07 setie dwaresplit dware setie dwaresplit gtech setie gtechsplit ramlib setstd iesplit std cell lib setie std cell libsplit synopsys set def toposort2data for k v in dataitems vthiscardk ignore self dependencies extra items in deps reducesetunion datavalues setdatakeys dataupdateitemset for item in extra items in deps while true ordered setitem for itemdep in dataitems if not dep if not ordered break yield joinsortedordered data item dep ordered for itemdep in dataitems if item not in ordered assert not data a cyclic dependency exists amongst r dataprint njoin toposort2data end of,['python'] +112347,access property value as string literal in php okay im relearning php for a small home project and run into a problem so heres a quick one for all you php expertsi have build an abstract class which should access properties of yql yahoo returned json objects decoded to php objects lets say i want to access the property id then i do like this rightprintphpobjectid okaybut i want to be able to access the property in a more abstract manner ie something like thispropertyname idprintphpobjectpropertyname printphpobjectid but none of the above is working i am sure for obvious reasons but me not beeing php expert i am having a hard time figurring out this call please help me here,['php'] +112356,whats the difference between using stringequalsstr1str2 and str1 str2 possible duplicatec difference between and equals in my daily code routine i use them a lot but really do not know how exactly they are different from each otherifstringequalsstr1 str2andifstr1 str2,['c#'] +112383,using serial port rs232 in android i want to send signals via serial port using the javacomm api classes on an android device and here is how i imagine it1 the android device would be archos 32 which has android 22 and usb host mode2 include rxtx lib package with my android app and include rxtx native code using android ndk3 a short cable which is usbserialcould you explain to me where i might face problems,"['java', 'android']" +112393,getting aspnet to store viewstate in the session rather than bulking up the html i am trying to get aspnet to store viewstate in the session rather than bulking up the htmlnow i have read that aspnet comes with the sessionpagestatepersister which can be used instead of the default hiddenfieldpagestatepersister to do this i was wondering how i go about dropping it inthis is what i have got so fari think i need to create a pageadapter that returns a sessionpagestatepersister from its getstatepersister method and somehow get the page to use this pageadapter but pagepageadapter only has a getter so i am not sure how you set itsee the remarks heading here thanks,"['c#', 'asp.net']" +112399,operator overloading member function vs nonmember function i read that an overloaded operator declared as member function is asymmetric because it can have only one parameter and the other parameter passed automatically is the this pointer so no standard exists to compare them on the other hand overloaded operator declared as a friend is symmetric because we pass two arguments of the same type and hence they can be comparedmy question is that when i can still compare a pointers lvalue to a reference why are friends preferred using an asymmetric version gives the same results as symmetricwhy do stl algorithms use only symmetric versions,['c++'] +112403,what is the use of method overloading in java when it is achieved by changing the sequence of parameters in the argument list i was reading a java training manual and it said that method overloading in java can be achieved by having a different argument list it also said that the argument list could differ in i number of parametersii datatype of parametersi sequence of parametersmy concern is about i what is the use of trying to overload a method just by changing the sequence of parameters i am unable to think of any benefits by this way,['java'] +112409,oneliner if statements how to convert this ifelsestatement total noob here so be gentle i have looked everywhere and cannot seem to find the answer to this how do i condense the followingif expression return trueelse return falsei cannot get it to work since it is returning something vs setting something i have already seen things like thissomevar expression value1 value2like i said please be gentle,['c#'] +112410,what is the best way to test a rails app i am new to testing in rails i have decided to learn test driven development and hence i am researching on how to go about it in railsi started out with testunit and soon came to know that better tools and testing frameworks available things i have heard of areshouldamocharspeccucumberfactory girlnow i am very confused as to how to go ahead what is the best combination of these tools i need to learn also where can i find resources to learn thesei am building the app in rails 30,['ruby-on-rails'] +112417,how to record filtered video for iphone it is easy to record video by two ways uiimagepicker or alassetlibrarybut if i want to process each frame with image effect filterthen save result as videohow to do that i can use avcapturevideodataoutput to process each frame and save filtered frame to still image but can not save them to videomy question is how to save them to videoif using avcapturemoviefileoutputit is easy to record camera to video but can not put filter for each frame thanks for any clues or comments,['ios'] +112435,c value type versus make pair which is faster for map insert typedef mapkeytype valtype kvmapkvmap kvmapkvmapinsert kvmapvalue type key val kvmapinsert make pair key val which of the above options to insert to a stl map is always faster whynote i am well aware that insert is faster than using for adding not updating keyvalue pairs to a map please assume that my query is about adding not updating hence i have restricted it to insert,['c++'] +112442,is there support for sparse matrices in python is there support for sparse matrices in pythonpossibly in numpy or in scipy,['python'] +112450,injecting mock service for spring unit tests i am testing a class that uses use autowired to inject a servicepublic class ruleidvalidator implements constraintvalidatorvalidruleid string autowired private rulestore rulestore some other methodsbut how can i mock rulestore during testing i cannot figure out how to inject my mock rulestore into spring and into the autowiring systemthanks,['java'] +112453,select options not showing in ie i have a dynamically generated select with some options and it shows the options fine in normal browsers but its empty options in ie heres the generated htmlselect name0 idcustom 0 styleborderbottom c0cedb 1px solid borderleft c0cedb 1px solid backgroundcolor ededed width 280px fontsize 087em bordertop c0cedb 1px solid borderright c0cedb 1px solid option id10 value0 name001x2gb ecc ddri 2gb ecc ddrioption option id1001 value10 name012x2gb ecc ddri 4gb ecc ddri 10 aoptionselecti cannot really show you the javascript since there is so much of it and i would be able to make it simple just for a demo maybe you had some of you wouldve had a similar experience and could figure this one out thanksi have added some javascriptcustom orderappendtr idcustom category rowtdpaddingheaderselect idcustom category namecategory stylebackgroundcoloredededborder1px solid c0cedbwidth280pxfontsize087emselectplusspantdtrfor var i0icomponentscategoryvaluelengthi custom categoryappendoption idcomponentscategoryvalueiid valuecomponentscategoryvalueipriceoption removalscategoryi dependenciescategoryi selectinputcategorygetdiffcategorygetdiff function adds the values to the options with html function the weird thing is if i alert the html of the option just after the getdiff function it shows the value filled out and it i put the getdiff function in the for loop where the options are generated it fills the values and shows them in ie just not the last onei am calling getdiff outside the loop for optimization and since i can add the values later after all the options are generated well at least i thought i could since it works on firefox and chrome,"['javascript', 'jquery']" +112455,mvc does the faviconico also look for a controller i get an errorthe controller for path faviconico was not found or does not implement icontrollerthen i thought how does the framework know for which files it has to instantiate a controller because the same thing is true for script css and other filesnever thought of that but now the favicon is complaining i was wonderingbut back to the error why does that occur,['asp.net'] +112457,where to put defaultservlethandler in spring mvc configuration in my webxml the default servlet mapping ie is mapped to spring thispatcher in my spring thispatcher configuration i have defaultannotationhandlermapping controllerclassnamehandlermapping and annotationmethodhandleradapter which allows me to map url to controllers either by its class name or its requestmapping annotation however there are some static resources under the web root which i also want spring thispatcher to serve using default servlet according to spring documentation this can be done using mvcdefaultservlethandler tagin the configuration below there are 4 candidate locations that i marked which are possible to insert this tag inserting the tag in different location causes the thispatcher to behave differently as following case 1 if i insert it at location 1 the thispatcher will no longer be able to handle mapping by the requestmapping and controller class name but it will be serving the static content normallycas 2 3 it will be able to handle mapping by the requestmapping and controller class name as well as serving the static content if other mapping cannot be done successfullycase 4 it will not be able to serve the static contents removal note this was a bug when implementing a controller which has a method mapped to but does not have explicit request mapping on the controller class nametherefore case 2 and 3 are desirable according to spring documentation this tag configures a handler which precedence order is given to lowest so why the position matters and which is the best position to put this tagxml version10 encodingutf8beans xmlns xmlnsxsi xmlnsmvc xmlnscontext xsischemalocation contextannotationconfig contextcomponentscan basepackagewebappcontroller location 1 enable annotationbased controllers using controller annotations bean idannotationurlmapping classorgspringframeworkwebservletmvcannotationdefaultannotationhandlermapping location 2 bean idcontrollerclassnamehandlermapping classorgspringframeworkwebservletmvcsupportcontrollerclassnamehandlermapping location 3 bean idannotationmethodhandleradapter classorgspringframeworkwebservletmvcannotationannotationmethodhandleradapter location 4 mvcdefaultservlethandler all views are jsps loaded from webinfjsp bean idviewresolver classorgspringframeworkwebservletviewinternalresourceviewresolver property nameviewclass valueorgspringframeworkwebservletviewjstlview property nameprefix valuewebinfjsp property namesuffix valuejsp beanbeans,['java'] +112462,sending a response from php to an androidjava mobile app i currently have a piece of code in my android application that picks up the devices imei and sends that imei as a parameter to a php script that is hosted on the internet the php script then takes the imei parameter and checks a file to see if the imei exists in the file if it does i want to be able to let my android application know that the imei exists so essentially i just want to be able to return true to my applicationis this possible using phphere is my code so farandroidjavatest http get for php public void executehttpget throws exception bufferedreader in null try httpclient client new defaulthttpclient httpget request new httpget requestseturinew uri imei scriptphpimei telmanagergetdeviceid httpresponse response clientexecuterequest in new bufferedreader new inputstreamreaderresponsegetentitygetcontent stringbuffer sb new stringbuffer string line string nl systemgetpropertylineseparator while line inreadline null sbappendline nl inclose string page sbtostring systemoutprintlnpage finally if in null try inclose catch ioexception e eprintstacktrace the above sends the imei as a parameter to the php script which picks it up successfully and runs a check against the file successfully however i ned to then be able to send a positive response back from the php script if the imei matches one in the filehere is the phpphp to return plain text headercontenttype plaintext imei getimei filefopenimeitxtr or exitunable to open file whilefeoffile if imeichopfgetsfile echo true fclosefileso instead of echo true i want to be able to let my application know that the imei was found is this possible and if so what should i be using to achieve it,"['java', 'php', 'android']" +112470,using jquery to trigger html onclick event input typetext idtest value nametest value valuexyz input idtest default nametest default typecheckbox onclickwiththisformelementstest value thisabled thischecked if thischecked value else ifvalue value value the inline onclick is generated by a cms which i have no control ofi want to execute test defaultclick with jquery but that does not work because it is not bound to the jquery event manageri have been trying variations oftest defaultclickfunction e etargetattronclickapplycheckbox e return false clickbut with no avail please helpthanksthere are dozens of different functions that may be in inline in the onclick it is not really an option to duplicate them and run them in parallelthe answers work in a small demo but not in the live environment please look at i need the checkbox to be triggered programaticallybizarrely only metadata field text 10190 default0click triggers the event correctly can anyone explain this,"['javascript', 'jquery']" +112483,finding local maximaminima with numpy in a 1d numpy array can you suggest a module function from numpyscipy that can find local maximaminima in a 1d numpy array obviously the simplest approach ever is to have a look at the nearest neighbours but i would like to have an accepted solution that is part of the numpy thistro,['python'] +112492,filesystemwatcher surpassing file system permissions while experimenting with filesystemwatcher i have found out that it somehow surpasses my user accounts permissions to files and folders and will raise change events with information about what has changed in files and folders that you do not even have access toi have two questions about that1 why does this happen 2 is this a problem in the ad configuration how do i fix it 3 is there any way to gather these files or even create a filesysteminfo of them to get more info about the files not only the changes made on them as far as i have tried only the filesystemwatcher immune to the restrictions i cannot run any other thing over it heres a list of what i have triedfileexistsdirectoryexistsfileinfo instance on found filesdirectoryinfo instance on found filesfilecopyfiledeleteupdate tried helges solution with somethin similar to what he is sugested not through windows api but through the command promptrobocopy b myserverfolder csomefolderbest command name everyou can check through robocopy that b stands for backup mode which is what helges suggested that would be the cause to this security surpassingi will try anything i want to find out what exactly causes filesystemwatcher to be able to watch folders i do not have permission to open knowing why i want to learn both how to block filesystemwatcher and how to gather found filesi would make a survey if i was with my personal account please can someone help me i will write a blog post about the solution among other things that might help anyone with the same doubt in the future,['c#'] +112496,cycle enumeration of a directed graph with multi edges how can i find all cyles in a directed graph with multi edgesgraph example 1cycles 126123412345612653434556graph example 2 multiedge 45cycles 1231415notes i do not want to detect a cycle boolean result i want to list all cyclesany strongly connected component algorithm is not sufficient for my problem it would find only one component in both examplesi am using the quickgraph implementation in c but i would be happy to see an algorithm in any language,['c#'] +112499,what is the scala equivalent to a java builder pattern in the work that i do on a day to day in java i use builders quite a lot for fluent interfaces eg new pizzabuildersizelargeontopofbasecheesywithingredienthambuildwith a quickanddirty java approach each method call mutates the builder instance and returns this immutably it involves more typing cloning the builder first before modifying it the build method eventually does the heavy lifting over the builder statewhats a nice way of achieving the same in scalaif i wanted to ensure that ontopofbasebase was called only once and then subsequently only withingredientingredient and buildpizza could be called ala a directed builder how would i go about approaching this,['java'] +112501,object reference set to null in finally block public void testfinallysystemoutprintlnsetonetostringprotected stringbuilder setonestringbuilder buildernew stringbuildertrybuilderappendcoolreturn builderappendreturnfinallybuildernull why output is coolreturn not null regardsmahendra athneria,['java'] +112504,how can you create alt shortcuts in a windows forms application i would like to create keyboard shortcuts for some controls in my windows forms applicationexamplenotice the underlined f e v p b i have a label and a textbox control i would like to associate that alt keyboard shortcut to the label and the textbox so if someone presses alt b focus is given to the associated textbox is there a way to create this association,['c#'] +112513,iphone sdk textfieldshouldreturn not being called were trying to figure out how to get the keyboard to hide but were having problems getting the textfieldshouldreturn to fire we are not sure why this is what has been donehinterface multisalesviewcontroller uiviewcontroller uitextfielddelegatectxtcardnumberdelegate self booltextfieldshouldreturnuitextfield textfield textfield setuserinteractionenabledyes textfield resignfirstresponder return yesalso the textfield has it is delegate set to files owner in interface builder one odd thing is that the viewcontrollers voidtextfielddidendeditinguitextfield textfield is working can anyone comment as to how to get the hiding of the keyboard working,['iphone'] +112521,javascript intellisense in vs2010 extremely slow and memory hungry i am having 2 problems with the intellisense in vs2010 our project is very large it consists of a couple hundred js files comprising a couple hundred thousand lines of code after using vs2010 for as little as 510 minutes the memory usage can easily climb to over 1gb which causes a significant slow down and every time i ctrltab between files updating javascript intellisense appears in the status bar all of our js files have tags so intellisense knows where to find related code each js can easily reference 2030 other js filesso i am assuming every time you ctrltab or open a new js file the intellisense gets rebuilt and to me it looks like it rebuilds intellisense every time you ctrltab regardless of whether you made any changes or now and it never appears to release any memory the memory usage never goes downi have tried every solution i have found online even some that seemed stupid because i am getting desperate i even installed vs2010 sp1 beta today hoping microsoft had fixed it noclosing tabs does not help either the memory usage remains highmy current solution is to restart vs2010 every 3060 minutes and try keep a minimum number of files openany ideas,['javascript'] +112523,avoid removal of current lucenenet index during rebuild i am new to lucenenet but i am using an open source tool built for sitecore cms that uses lucenenet to index lots of content from the cms i confirmed yesterday that when i rebuild my indexes the current index files wipe clean so anything that relies on the index gets no data for about 3060 seconds the amount of time for a full index rebuild is there a best practice or way to make lucenenet not overwrite the current index files until the new index is completely rebuilt i am basically thinking i would like it to write to new temp index files and when the rebuild is done have those files overwrite the current indexexample of what i am talking aboutbuild fresh index 30 secondsindex has about 500 documentsuse code to access data in index and thisplay on websiterebuild index 30 secondsany code that now reads the index for data returns nothing because the index files are being overwritten results in website not showing any datarebuild complete data now available again data back on websitethanks in advance,['c#'] +112527,cachesetmaxage not working under iis works fine under vs dev srv i am trying to add a maxage header to my response it works fine on my visual studio development server but as soon as i move the app to iis tried both iis express locally and iis on the server the header thisappearsmy coderesponsecachesetcacheabilityhttpcacheabilitypublicresponsecachesetmaxagenew timespan1 0 0 0vs dev server response all works just finehttp11 200 okserver aspnet development server10date fri 07 jan 2011 145504 gmtxaspnetversion 2050727cachecontrol public maxage86400iis7 responsehttp11 200 okserver microsoftiis75date fri 07 jan 2011 150054 gmtxaspnetversion 2050727cachecontrol publicps it is an ashxhandler if it matters,"['c#', 'asp.net']" +112529,nhibernate unable to convert mysql datetime value to systemdatetime i am getting the unable to convert mysql datetime value to systemdatetime error because from what i can tell i have a record with 0 0 now while the data should never be that it should be null there are cases when this might happen and i do not want my entire application to crash because of it i am using nhibernate and i tried adding change my connection string to allow zero datetime so the connection string configuration looks likeproperty nameconnectionconnection string serverlocalhostdatabaseuser systemuser idrootpasswordroot allow zero datetimetruepropertyhowever i still receive that error how can i allow nhibernate to allow zero values for timestampdatetimedatatime,"['c#', 'asp.net', 'mysql']" +112530,how can i run a php script in the background after a form is submitted problemi have a form that when submitted will run basic code to process the information submitted and insert it into a database for thisplay on a notification website in addition i have a list of people who have signed up to receive these notifications via email and sms message this list is trivial as the moment only pushing about 150 however it is enough to cause it takes upwards of a minute to cycle through the entire table of subscribers and send out 150 emails the emails are being sent individually as requested by the system administrators of our email server because of mass email policies during this time the individual who posted the alert will sit on the last page of the form for almost a minute without any positive reinforcement that their notification is being posted this leads to other potential problems all that have possible solutions that i feel are less than idealfirst the poster might think the server is lagging and click the submit button again causing the script to start over or run twice i could solve this by using javascript to thisable the button and replace the text to say something like processing however this is less than ideal because the user will still be stuck on the page for the length of the script execution also if javascript is thisabled this problem still existssecond the poster might close the tab or the browser prematurely after submitting the form the script will keeping running on the server until it tries to write back to the browser however if the user then browses to any page within our domain while the script is still running the browser hangs loading the page until the script has ended this only happens when a tab or window of the browser is closed and not the entire browser application still this is less than idealpossible solutioni have decided i want to break out the email part of the script into a separate file i can call after the notification has been posted i originally thought of putting this on the confirmation page after the notification has been successfully posted however the user will not know this script is running and any anomalies will not be apparent to them this script cannot failbut what if i can run this script as a background process so my question is this how can i execute a php script to trigger as a background service and run completely independent of what the user has done at the form leveledit this cannot be croned it must run the instant the form is submitted these are highpriority notifications in addition the system administrators running our servers thisallow crons from running any more frequently than 5 minutes,['php'] +112544,axis vs jaxws for web service client i am deciding on the implementation of web service client in java i have generated axis client in eclipse and jasws client with wsimport both solutions work and now i have to choose one to go forward what should i think about before picking one over the other,['java'] +112546,java hardware acceleration i have been spending some time looking into the hardware acceleration features of java and i am still a bit confused as none of the sites that i found online directly and clearly answered some of the questions i have so here are the questions i have for hardware acceleration in java1 in eclipse version 360 with the most recent java update for mac os x 16u10 i think is hardware acceleration enabled by default i read somewhere that somecanvasgetgraphicsconfigurationgetbuffercapabilitiesispageflippingis supposed to give an indication of whether or not hardware acceleration is enabled and my program reports back true when that is run on my main canvas instance for drawing to if my hardware acceleration is not enabled now or by default what would i have to do to enable it2 i have seen a couple articles here and there about the difference between a bufferedimage and volatileimage mainly saying that volatileimage is the hardware accelerated image and is stored in vram for fast copyfrom operations however i have also found some instances where bufferedimage is said to be hardware accelerated as well is bufferedimage hardware accelerated as well in my environment what would be the advantage of using a volatileimage if both types are hardware accelerated my main assumption for the advantage of having a volatileimage in the case of both having acceleration is that volatileimage is able to detect when its vram has been dumped but if bufferedimage also support acceleration now would it not have the same kind of detection built into it as well just hidden from the user in case that the memory is dumped3 is there any advantage to usingsomegraphicsconfigurationgetcompatibleimagegetcompatiblevolatileimageas opposed toimageioreadin a tutorial i have been reading for some general concepts about setting up the rendering window properly tutorial it uses the getcompatibleimage method which i believe returns a bufferedimage to get their hardware accelerated images for fast drawing which ties into question 2 about if it is hardware accelerated4 this is less hardware acceleration but it is something i have been curious about do i need to order which graphics get drawn i know that when using opengl via cc it is best to make sure that the same graphic is drawn in all the locations it needs to be drawn at once to reduce the number of times the current texture needs to be switch from what i have read it seems as if java will take care of this for me and make sure things are drawn in the most optimal fashion but again nothing has ever said anything like this clearly5 what awtswing classes support hardware acceleration and which ones should be used i am currently using a class that extends jframe to create a window and adding a canvas to it from which i create a bufferstrategy is this good practice or is there some other type of way i should be implementing thisthank you very much for your time and i hope i provided clear questions and enough information for you to answer my several questions,['java'] +112547,difference between fprintf printf and sprintf can anyone explain in simple english about the differences between printf fprintf and sprintf with exampleswhat stream is it ini am really confused between the three of these while reading about file handling in c,['c'] +112548,why is this javascript getting called twice i have a button where i have hooked the onclick to a call to retrieve the users location and then use the location to make another call to retrieve a list of nearby locations for some reason the geolocation success method is being called twice on the second click of the buttonso i load the page click the button allow permission to use my location and it will make one ajax request to get the nearby locations this works finei click the button again allow permission to use my location again it will make one ajax request to get the locations wait 2 seconds and then make another request using the same coordinates without me allowing permission so the success method has to be getting called twice but i am not sure whyfindlocationclickfunction myscriptfindnearbylocationsthisplaydata thisplayerrorthis click function is not being called twice and i have commented out all the code in thisplaydata and thisplayerrorfindnearbylocations function onsuccess onfailure if navigatorgeolocation browsersupportflag true navigatorgeolocationgetcurrentpositionfunction position alertthis is getting called twice except on the initial call myscriptfindstorespositioncoordslatitude positioncoordslongitude onsuccess onfailure function onfailuretrue anyone see where i have gone wrongedit i do not think the markup is the problem i am only using basic webpages for testing there is no styling or other elements at the momentform idform1 runatserver div mycontrolssearch idsearch runatserver divformand the user control along with all the necessary javascript includesscript typetextjavascript documentreadyfunction findlocationclickfunction myscriptfindnearbylocationsthisplaydata thisplayerror scriptinput typebutton idfindlocation valuefind location div idresultsdiv,"['javascript', 'jquery']" +112566,any glpolygonmode alternative on iphone opengl es i am new to opengl and i found out that opengl es does not support apis such as glpolygonmode gl back gl fillany ideas how to implement it,['iphone'] +112571,how to detect iphone sdk if a video file was recorded in portrait orientation or landscape i am using alassetsgroup enumerateassetsatindexes to list the assets in the photos camera app for a given video asset i want to determine whether it was shot in portrait or landscape mode in the following code asset is an alasset and i have tested to see if it is a video asset asset valueforpropertyalassetpropertytype is alassettypevideo thenint orientation asset valueforpropertyalassetpropertyorientation intvaluein this case orientation is always 0 which is alassetorientationup maybe this is to be expected all videos are up right but a portrait video is represented in mpeg4 as a landscape video turned 90 degrees ie all videos are actually landscape try the mediainfo app on the mac if you do not believe me where within the file andor how do i access the information that tells me it was actually recorded while holding the phone in portrait orientationi have also tried this given the url of the assetavurlasset avasset avurlasset alloc initwithurlurl optionsnilcgsize size avasset naturalsizenslogsizewidth f sizeheight f sizewidth sizeheightcgaffinetransform txf avasset preferredtransformnslogtxfa f txfb f txfc f txfd f txftx f txfty f txfa txfb txfc txfd txftx txftywhich always yields a width height so for iphone 4 width1280 height720 and the transform a and d values are 10 the others are 00 regardless of the capture orientationi have looked at the meta data using mediainfo app on the mac i have done a hexdump and so far have not found any difference between a landscape and portrait video but quicktime knows and thisplays portrait videos vertically and the phone knows by rotating a portrait video if you are holding the phone in landscape orientation on playback and correctly thisplaying it if holding it in portraitbtw i cannot use ffmpeg cannot live with the license restrictions is there an iphone sdk native way to do this,['iphone'] +112578,sql server silently truncates varchars in stored procedures according to this forum thiscussion sql server i am using 2005 but i gather this also applies to 20 and 2008 silently truncates any varchars you specify as stored procedure parameters to the length of the varchar even if inserting that string directly using an insert would actually cause an error eg if i create this tablecreate table testtable teststringfield nvarchar5 not nullthen when i execute the followinginsert into testtableteststringfield valuesnstring which is too longi get an errorstring or binary data would be truncatedthe statement has been terminatedgreat data integrity preserved and the caller knows about it now let us define a stored procedure to insert thatcreate procedure sptesttableinsert teststringfield nvarchar5as insert into testtableteststringfield valuesteststringfieldgoand execute itexec sptesttableinsert teststringfield nstring which is too longno errors 1 row affected a row is inserted into the table with teststringfield as strin sql server silently truncated the stored procedures varchar parameternow this behaviour might be convenient at times but i gather there is no way to turn it off this is extremely annoying as i want the thing to error if i pass too long a string to the stored procedure there seem to be 2 ways to deal with thisfirst declare the stored procs teststringfield parameter as size 6 and check whether its length is over 5 this seems like a bit of a hack and involves irritating amounts of boilerplate codesecond just declare all stored procedure varchar parameters to be varcharmax and then let the insert statement within the stored procedure failthe latter seems to work fine so my question is is it a good idea to use varcharmax always for strings in sql server stored procedures if i actually want the stored proc to fail when too long a string is passed could it even be best practice the silent truncation that cannot be thisabled seems stupid to me,['sql'] +112584,pairs from single list often enough i have found the need to process a list by pairs i was wondering which would be the pythonic and efficient way to do it and found this on googlepairs zipt2 t12i thought that was pythonic enough but after a recent thiscussion involving idioms versus efficiency i decided to do some testsimport timefrom itertools import islice izipdef pairs 1t return zipt2 t12 def pairs 2t return izipt2 t12 def pairs 3t return izipislicetnonenone2 islicet1none2a range10b xrangelenadef pairs 4t ignore value of t t b return izipislicetnonenone2 islicet1none2for f in pairs 1 pairs 2 pairs 3 pairs 4 time the pairing s timetime for i in range10 p fa t1 timetime s time using the pairs s timetime for i in range10 p fa for a b in p pass t2 timetime s print t1 t2 t2t1these were the results on my computer148668909073 263187503815 1145185947420105381965637 135109519958 1245713233950257992746 146182489395 1459244966510251388549805 170076990128 169825601578if i am interpreting them correctly that should mean that the implementation of lists list indexing and list slicing in python is very efficient it is a result both comforting and unexpectedis there another better way of traversing a list in pairsnote that if the list has an odd number of elements then the last one will not be in any of the pairs which would be the right way to ensure that all elements are includedi added these two suggestions from the answers to the testsdef pairwiset it itert return izipit itdef chunkwiset size2 it itert return izipitsizethese are the results 0159502029419 125745987892 12558648586302492218018 123795199394 123572707176results so farmost pythonic and very efficientpairs izipt2 t12most efficient and very pythonicpairs izipitert2it took me a moment to grok that the first answer uses two iterators while the second uses a single oneto deal with sequences with an odd number of elements the suggestion has been to augment the original sequence adding one element none that gets paired with the previous last element something that can be achieved with itertoolsizip longestfinallynote that in python 3x zip behaves as itertoolsizip and itertoolsizip is gone,['python'] +112601,android how to check if a view inside of scrollview is visible i have a scrollview which holds a series of views i would like to be able to determine if a view is currently visible if any part of it is currently thisplayed by the scrollview i would expect the below code to do this surprisingly it does notrect bounds new rectviewgetdrawingrectboundsrect scrollbounds new rectscrollgetscrollx scrollgetscrolly scrollgetscrollx scrollgetwidth scrollgetscrolly scrollgetheightifrectintersectsscrollbounds bounds is visible,['android'] +112604,convert an int to ascii character i have int i 6and i want char c 6by conversion any simple way to suggesteditalso i need to generate a random number and convert to a char then add a txt and access it in an ifstream,"['c++', 'c']" +112615,edit rails model from command line i am pretty new to ruby on rails and i was wondering if there was a way to edit the database schema for a model for example i have the subscriber model in my application the way i created it was by using rails generate scaffold subscriber emailstringbut now i want a name in the subscriber model as well is there any easy way to do this i have put a lot of code in my current controllers and views so i do not necessarily want to destroy the scaffold but i would like to edit the model thanks in advancehwrdps i am using ruby on rails 3,['ruby-on-rails'] +112623,is there a way to keep firefox from putting cached emails and passwords on my registration form i have a site with registration modify account forms when a user navigates to one of these pages firefox is filling in certain areas of the form it is filling ininput typetext namenemail2 value input typepassword namenpassword value not sure why these names are original for this form it can be the first time a user ever visits this form and it will fill in their username and password not even in the correct boxes from their cached passwordsnote the names of the actual login boxes are emailaddr and password also the label is different for these boxes that it is filling in not sure what i should do it looks horrible when a user comes to edit their account information and half optional fields for changing their emailpassword are filled out with their current informationany help is appreciated,['html'] +112636,how to change a textviews style at runtime i have an android app on which when the user taps a textview i would like to apply a defined stylei thought to find a textviewsetstyle but it does not exists i tried textviewsettextappearancebut it does not work,"['java', 'android']" +112654,aspnet mvc alternative for bindexclude id is there an alternative for bindexclude id related question could i write a model binder,['c#'] +112661,changing output path in web project in vs2010 i have several aspnet web projects and their output folder are set to cbuildsprojectnamebin instead of the default bin folder this makes f5 debugging not working because the aspnet development server expects the bin folder under the project folder i then changed to use local iis web server httplocalhostwebproject1 and manually updated the vdir physical path to my custom output path however the vs2010 will not load the csproj because it detects the url is already mapped to a different folder location i know i probably should not change the output folder but wondering if there is an easy way to workaround this the goal is to make f5 debugging work with custom build output foldersupdate due to aristos answerthanks aristos unfortunately that would not solve the problem all my projects already use the project reference so all the reference dlls are correctly copied to the output folder the reason why f5 debugging does not work is because the output folder is not the normal bin sub folder but in some other path say cbuildsoutfoobinit seems that in order to use f5 to debug the web project in vs2010 it has to use the default output path bin if you change that then f5 will not work and even worse your project may not even load,"['c#', 'asp.net']" +112667,why does osx document atoiatof as not being threadsafe i understand that strtol and strtof are preferred to atoiatof since the former detect errors and also strtol is much more flexible than atoi when it comes to nonbase10but i am still curious about something man atoi or atof on os x though not on linux mentions that atoiatof are not threadsafe i frankly have a hard time imagining a possible implementation of atoi or atof that would not be threadsafe does anybody know why the man page says this are these functions actually unsafe on os x or any other platform and if they are why on earth wouldnt the library just define atoi in terms of strtol and therefore be safe,['c'] +112672,renaming table in rails i want to rename a table any tablei tried this line of codeactiverecordconnectionadaptersschemastatementsrename tableold name new nameheres the weird thing i know i got it working the first time but now i get this error undefined method rename table for activerecordconnectionadaptersschemastatementsmodulewas there something i need to set or am i going blind herethanks,['ruby-on-rails'] +112684,is there some lispy language that seamlessly integrates with python is there a language based on sexpressions with powerful macros that allows as seamless integration with python as clojure with jvmi want to try using such syntax and features while having access to all usual python libraries including pyqt,['python'] +112687,how can i reload a script in irb i am writing a ruby script for use in the rails environment but i chose to run it from irb because reloading the rails console can be a pain now the wait time is much shorter from irb but i am bothered that i have to restart irb and require the script everytime i make a change is there a simpler way of reloading a script from irb i found a method in this thread but that only applies to gem files apparently my require statement looks like this require fileexpand path file libqueryedit having tried load rather than require i still could not get it to work i cannot get a stop on these errorsruby192p0 load fileexpand path file libqueryrbloaderror no such file to load usersnewuserdropboxsitesrailshacknycirblibqueryrb,['ruby'] +112722,is there a better way to switch between html and json output in pyramid testformat no longer seems to workconfigadd routetest testext viewmsviewstestviewspyfrom pyramidresponse import responsefrom pyramidrenderers import renderimport jsondef testrequest extension requestmatchdictext variables name blah asd sdf if extension html output rendermypackagetemplatesblahpt variables requestrequest if extension json output jsondumpsvariables return responseoutputis there an easier way to do this with pylons it was a simpledef testself formathtml cvariables a 1 b 2 if format json return jsondumpscvariables return rendertemplatesblahhtmli suspect i am approaching this the wrong way,['python'] +112766,cannot create devise account using rake dbseed for rails 30 i am trying to preload all devise accounts in advance using rake dbseed data for all other models seems to be inserted in the database but for some reason no rows are created for person model which uses devise registration from web interface works fine but i want to avoid creating accounts manually thats the reason i am using rake dbseed i copied encrypted passwordpassword salt from an account created via web interface please let me know how to get around this many thankspeople personcreate email encrypted password 2a10syacaohjqtvetctpymroufbhgmylfj4flrk3nhyerwfeokkp2nvw password salt 2a10syacaohjqtvetctpymrou first name n last name y in routesrb i have devise for people,['ruby-on-rails'] +112779,declaring iboutlet inside or outside interface sorry if am i being too picky on this one but i am learning ios programming now and i have seem some people who declare the iboutlet like thisiboutlet attached to propertyimport uikituikithimport customcellhinterface customtableviewcontroller uitableviewcontroller customcell customcellproperty nonatomic retain iboutlet customcell customcellendand some declaring like thisiboutlet attached to the declaration inside the interfaceimport uikituikithimport customcellhinterface customtableviewcontroller uitableviewcontroller iboutlet customcell customcellproperty nonatomic retain customcell customcellendwhich one is the proper way to declare it are any differences between themif someone know to explain why do they put it on different places it would be awesome to learnthanks a lot,"['objective-c', 'ios']" +112790,what is the best way to get date and time in clojure i need to log some events on a clojure clientserver scenario but it seems to me that clojure does not provide a datetime function can any one confirm this or i am missing something here if i am correct then i need to use java interop right,['java'] +112805,android listview child view setenabled and setclickable do nothing i am doing some asynctask work after user clicks an item in my listview i would like to thisable the item so it cannot be clicked twice i have simplified the click listener to contain only this method but it still does not do anything for me the view looks the same and it lets itself be happily clicked again much to my annoyancepublic void onitemclickadapterview parent view clickedview int position long id item episode parentgetitematpositionposition clickedviewsetclickablefalse clickedviewsetenabledfalse clickedviewinvalidatemy view for each row is a custom linearlayout with two textviews,['android'] +112810,ruby on rails how to set up find options in order to not use cache in ruby on rails you can find records from the database with this syntaxmodel namefind by field nameexamples userfind by email userfind by id1 time ago if i am not wrong i read somewhere that you can explicitly thisable caching for find operations but i can not remember howcan someone help me remember,['ruby-on-rails'] +112812,rails any fancy ways to handle 404s i have a rails app i built for an old site i converted from another cms in a nonrails language hehe most of the old pages are mapped to the new pages using routesrb but there are still a few 404si am a rails newb so i am asking if there are any advanced ways to handle 404s for example if i was programming in my old language i would do thisget the url script name that was being accessed and parse it do a lookup in the database for any keywords ids etc found in the new urlif found redirect to the page or if multiple records are found show them all on a results page and let user choose with rails i would probably want to do status moved permanently i am guessingif not found show a 404are there any gemsplugins or tutorials you know of that would handle such a thing if it is even possible or can you explain on a high level how that can be done i do not need a full code sample just a push in the right directionps it is a simple rails 3 app that uses a single content model,['ruby-on-rails'] +112817,how to check java bit version on linux possible duplicateinstalled jvm is 64 bit or 32 bit how do i check which bit version of java is installed on my linux machine when i typejava versioni getjava version 160 16javatm se runtime environment build 160 16b01java hotspottm server vm build 142b01 mixed modeis that 32bit or 64bit,['java'] +112823,sqlite3 operationalerror unable to open database file question why can i not open the databaseinfo i am working on a project whose purpose is not important but uses a sqlite3 database i made a test program that runs and passes to it the location to make a databasetmpcercoulddband the unit test program can make the db no problem i then go actually use the program passing the same location to it and it says operationalerror unable to open database filei have tried doing it with an empty data base with the database the unit test left behind and with no database at all in all three cases i get this error the most frustrating part has to be the fact that the unit test can do it just fine but the actual program cannot any clues as to what on earth is going on,['python'] +112829,skip before filter ignores conditionals i am trying to use skip before filter only if the app is in production mode i do not want my development instances public and i want the app to automatically detect what type of instance it is on and thisplay a login screen when it is not in production mode so my application controller has the following linebefore filter authenticate user except sign in redirects to loginand the controller for thisplaying pages has this lineskip before filter authenticate user only show if in productionpublic pages are public but only when in productionand in production is simply def in production envrails envproduction endi realize that there may be other avenues here but i am curious as to why skip before filter seems to ignore the conditional and always just skip the before filter is there something i am missing,['ruby-on-rails'] +112838,efficient python daemon i was curious how you can run a python script in the background repeating a task every 60 seconds i know you can put something in the background using is that effeictive for this casei was thinking of doing a loop having it wait 60s and loading it again but something feels off about that,['python'] +112844,php associative arrays how to treat integer as string i have a simple associative arraya arrayab cdi want to check if the key 1 exists in the array egisseta1this string is being treated as an integer so thatecho a1 prints dhow do i get it to treat it as a stringi do not want to use array key exists or in array because my benchmarking shows isset will be a lot faster,['php'] +112848,android stringxml reading html tags problem in android projects stringsxml file i have following html textxml version10 encodingutf8resourcesstring namemyheadstrbubold underline ubstringresourceswhen i read this into getstringrstringmyheadstr it gives only text bold underline it forgets the html tags and how to read complete string with html tags from stringxml,['android'] +112854,define vs enum in an embedded environment how do they compile this question has been done to death and i would agree that enums are the way to go however i am curious as to how enums compile in the final code defines are just string replacements but do enums add anything to the compiled binary or are they both equivalent at that stage when writing firmware and memory is very limited is there any advantage no matter how small to using definesthanksedit as requested by the comment below by embedded i mean a digital camerathanks for the answers i am all for enums,['c'] +112866,apply question for javascript i study the following code to logconsolelogapply console arguments what is the purpose of apply here why not just consolelogmessage argumentsthanks,['javascript'] +112870,why net dictionaries resize to prime numbers according to this question a net dictionary resizes its allocated space to prime numbers that are at least twice the current size why is it important to use prime numbers and not just twice the current size i tried to use my googlefu powers to find an answer but to no avail,['.net'] +112895,php exit or die in ajax requests whats the best practice here using die or exit whats the difference between the twoif getdo thing echo bla bla exit or die or something elseendif,['php'] +112930,how to make the eclipse code template like this in some eclipse project i can see the every code filejava has a code template like thispublic class aclass constants fields constructors getter setter methods forfrom superclassinterfaces methods inner and anonymous classes i want to generate these comments automatically when create a new java class so how do i doi try to set the code templates in eclipse preferences but did not success,['java'] +112940,mp3 playing using avaudioplayer not working on device i am testing my app on my 3gs iphone with ios 42i am using the following code which plays a sound in my ibaction it works perfectly in the simulator both ipad and iphone i hear the sound nsstring pathtomusicfile1 nsbundle mainbundle pathforresourcealarm oftypemp3nserror erroralarmsound avaudioplayer allocinitwithcontentsofurlnsurl fileurlwithpathpathtomusicfile1 errorerror nslogsong1 loadedif alarmsound nil nslogerror playing sound else alarmsoundnumberofloops 20 alarmsoundvolume 10 alarmsound playi have everything declared properly headers and frameworks etc as i can hear the sound in the simulator i have also checked that my phone is not in silent mode i hear other sounds from the generic iphone gui example from a datepickeri have also cleaned all targets and deleted the app to reinstall any ideas whats wrong,['iphone'] +112948,cython inline function with numpy array as parameter consider code like thisimport numpy as npcimport numpy as npcdef inline incnpndarraynpint32 t arr int i arri 1def test1npndarraynpint32 t arr cdef int i for i in xrangelenarr incarr idef test2npndarraynpint32 t arr cdef int i for i in xrangelenarr arri 1i used ipython to measure speed of test1 and test2in 7 timeit test1arr100 loops best of 3 613 ms per loopin 8 timeit test2arr10 loops best of 3 979 us per loopis there a way to optimize test1 why does not cython inline this function as told updateactually what i need is multidimension code like this cython infer typestrue cython boundscheckfalse cython wraparoundfalseimport numpy as npcimport numpy as npcdef inline incnpndarraynpint32 t ndim2 arr int i int j arri j 1def test1npndarraynpint32 t ndim2 arr cdef int ij for i in xrangearrshape0 for j in xrangearrshape1 incarr i jdef test2npndarraynpint32 t ndim2 arr cdef int ij for i in xrangearrshape0 for j in xrangearrshape1 arrij 1 timing for itin 7 timeit test1arr1 loops best of 3 647 ms per loopin 8 timeit test2arr100 loops best of 3 207 ms per loopexplicit inlining gives 300x speedup and my real function is quite big so inlining it makes code maintainability much worseupdate2 cython infer typestrue cython boundscheckfalse cython wraparoundfalseimport numpy as npcimport numpy as npcdef inline incnpndarraynpfloat32 t ndim2 arr int i int j arri j 1def test1npndarraynpfloat32 t ndim2 arr cdef int ij for i in xrangearrshape0 for j in xrangearrshape1 incarr i jdef test2npndarraynpfloat32 t ndim2 arr cdef int ij for i in xrangearrshape0 for j in xrangearrshape1 arrij 1 cdef class fastpassingfloat2darrayobject cdef float data cdef int stride0 stride1 def init self npndarraynpfloat32 t ndim2 arr selfdata floatarrdata selfstride0 arrstrides0arrdtypeitemsize selfstride1 arrstrides1arrdtypeitemsize def getitem self tuple tp cdef int i j cdef float pr r i j tp pr selfdata selfstride0i selfstride1j r pr0 return r def setitem self tuple tp float value cdef int i j cdef float pr r i j tp pr selfdata selfstride0i selfstride1j pr0 value cdef inline inc2fastpassingfloat2darray arr int i int j arri j 1def test3npndarraynpfloat32 t ndim2 arr cdef int ij cdef fastpassingfloat2darray tmparr fastpassingfloat2darrayarr for i in xrangearrshape0 for j in xrangearrshape1 inc2tmparr ijtimings in 4 timeit test1arr1 loops best of 3 623 ms per loopin 5 timeit test2arr100 loops best of 3 229 ms per loopin 6 timeit test3arr1 loops best of 3 201 ms per loop,['python'] +112951,remove a listener from a view in android is there any way to remove a listener from a view in android i have a checkbox that i attached a checkchangedlistener to the problem is that calling setchecked on it causes my listener to fireif i cannot just remove a listener is there a way to prevent the listener from firing when i call setchecked manually versus it being checked from a touch event,['android'] +112953,rails polymorphic has many through i am pulling some data from an external api and would like to cache the results locally i have a class searchterm which i would like to be associated with a few different activerecord types through the table searchable items i am pretty sure i have the tables set up correctly but something in my associations must be wrongclass foo activerecordbase has many search terms as searchable through searchable itemsendclass bar activerecordbase has many search terms as searchable through searchable itemsendclass searchterm activerecordbase has many searchables through searchable itemsendclass searchableitem activerecordbase belongs to search term belongs to searchable polymorphic trueendi would expect to be able to do something like searchtermfind by termsearchtermsearchables and it would return an array of foo and bar objects however i get the error could not find the association searchable items in model searchtermthanks in advance for any insight you can provide to me,['ruby-on-rails'] +112954,how to find method name from within that method in java i was wondering if there is a way to know the method name being executed at run timefor instance inside a private void dosomething string s method i would like to know that i am executing the dosomething string s method,['java'] +112988,can i use an instantiated object as an array key for exampleproduct new productcatifissetsalesproduct salesproductelse salesproduct 1,['php'] +112989,how to use existing windows functionality to extract text from the ui i have done a bit of looking around and found various bits and pieces relating to this but nothing concretei need to find a method of extracting ui elements other than that of the spy tool i am able to locate screen items and their underlying text captions based on hwnd however 3rd party apps such as firefox offer further problems as they only have one large window for the thisplay if anyone has any ideas on how to natively get screen coordinates to do an ocr or control recognition of ui elements within say a web page i would love to hear from you,['c#'] +112999,refreshing the thisplay from a widget i am trying to set the screen brightness from a widget we know this is easily possible since tons of widgets do this already but howin a service i call from the widget i do this to set the brightnesettingssystemputintthisgetcontentresolver settingssystemscreen brightness 200that works great except it does not refresh the screen to apply the new settings turning the screen off and on does refresh the thisplay settings so we know that the code worksi also read on several sites that something like this will refresh the screen but we cannot use this since we are in a widget the widget activity and the service cannot use getwindowwindowmanagerlayoutparams lp getwindowgetattributeslpscreenbrightness 100 10fgetwindowsetattributeslphow else are all these widgets like beautiful widgets power control extended controls etc doing thisupdateanother poster recommended kicking off an empty activity and executing the windowmanager refresh that works but it brings up an ugly black screen for a second since the other widgets do not do this there has to be a way to keep the ugly blank black screen from showing,['android'] +113015,android alarm is cancelled after closing the application i have a problem with alarmmanager i set the code for scheduling a repeating alarm and after i run the application the alarm runs fine even if i click on home button and the application is paused the alarm still runs on its intervalthe problem is if i open the task manager and force close the application then the alarm stops from runningis this a normal behavior is there any way to avoid this and keep the alarm running after closing the applicationthe code is below the method is called by the applicationcontext class oncreate private void schedulealarm if alarmscheduled true return we only need to schedule once int alarminterval defprefgetapplicationcontextgetintalarminterval 30 final intent intent new intentgetapplicationcontext collectoralarmreceiverclass final pendingintent pending pendingintentgetbroadcastgetapplicationcontext 0 intent 0 alarmmanager alarmmgr alarmmanager getapplicationcontextgetsystemservicecontextalarm service alarmmgrcancelpending cancel others alarmmgrsetrepeatingalarmmanagerrtc wakeup systemcurrenttimemillis10 alarminterval10 pending deflogtagschedulealarm alarm scheduled interval alarminterval seconds alarmscheduled true receiver codepublic void onreceivecontext context intent intent logitag collectoralarmreceiver invoked starting collectorservice in background contextstartservicenew intentcontext collectorserviceclass intent collectorservice new intentcontextcollectorserviceclass collectorserviceputextraaction collectorserviceaction background request messages contextsendbroadcastcollectorservicethanks,['android'] +113022,is documentready necessary i saw this question in stackoverflow but do not feel that it was answered at allis documentready necessaryi link all my javascripts at the bottom of the page so in theory they are all running after the document is ready anyways,['jquery'] +113029,mysql select enum values i need to select the enum values of a column from searching i have found two waysselect column type from information schemacolumns where table name mytable and column name mycolumnand the othershow columns from mytable where field typealthough the first query will give me this infoenumvalue1value2value3the 2nd query gives me the same and with additional columns as well i would prefer to just get those values without the enum and commas is it possible or do i need to parse the values out not that it is hard just checking if there is an easier wayassuming there is no easier way which of the two queries above is better to use i noticed that the 2nd query does not show the query time when i ran it i almost thought it did not require any time at all but if i turn on the profiler i can see that it does take time but it seem a bit faster so would the 2nd query be more efficient,['mysql'] +113051,function returns value without return statement why does following code has a correct output int ggt has no return statement but the code does work anyway there are no global variables setinclude stdiohinclude stdlibhint ggtint intvoid main int x1 x2 printfbitte geben sie zwei zahlen ein n scanfd x1 scanfd x2 printfggt ist dn ggtx1 x2 systempauseint ggtint x1 int x2 whilex1 x2 ifx1 x2 return x1 x1 x2 else return x2 x2 x1,['c'] +113056,when to use stringbuilder in java it is supposed to be generally preferable to use a stringbuilder for string concatenation in java is this always the casewhat i mean is this is the overhead of creating a stringbuilder object calling the append method and finally tostring already smaller then concatenating existing strings with the operator for two strings or is it only advisable for more than two stringsif there is such a threshold what does it depend on perhaps the string length but in which wayand finally would you trade the readability and conciseness of the concatenation for the performance of the stringbuilder in smaller cases like two three or four stringseditexplicit use of stringbuilder for regular concatenations is being mentioned as obsolete at obsolete java optimization tips as well as at java urban myths,['java'] +113072,get nearest places on google maps using mysql spatial data i have a database with a list of stores with latitudes and longitudes of each so based on the current lat lng location that i input i would like to get a list of items from those within some radius like 1 km 5km etcwhat should be the algorithm i need the php code for algorithm itself,['php'] +113092,how to set android camera orientation properly i want to set the camera orientation according to the device orientation in android but nothing seems to be working i tried to rotate the surface as well as the camera parameters but the camera preview in portrait mode always comes upside down i would need to rotate it by 90 degree clockwise for it to be correct here is the code i am using right now which works in landscape mode only surfaceholdercallback surfacecallback new surfaceholdercallback override public void surfacedestroyedsurfaceholder holder camerastoppreview camerarelease camera null override public void surfacecreatedsurfaceholder holder initcamera private size getoptimalpreviewsizelistsize sizes int w int h final double aspect tolerance 02 double targetratio double w h if sizes null return null size optimalsize null double mindiff doublemax value int targetheight h try to find an size match aspect ratio and size for size size sizes logdtag checking size sizewidth w sizeheight h double ratio double sizewidth sizeheight if mathabsratio targetratio aspect tolerance continue if mathabssizeheight targetheight mindiff optimalsize size mindiff mathabssizeheight targetheight cannot find the one match the aspect ratio ignore the requirement if optimalsize null mindiff doublemax value for size size sizes if mathabssizeheight targetheight mindiff optimalsize size mindiff mathabssizeheight targetheight return optimalsize override public void surfacechangedsurfaceholder holder int format int width int height cameraparameters parameters cameragetparameters listsize sizes parametersgetsupportedpreviewsizes size optimalsize getoptimalpreviewsizesizes width height logdtag surface size is width w height h logdtag optimal size is optimalsizewidth w optimalsizeheight h parameterssetpreviewsizeoptimalsizewidth optimalsizeheight parameterssetpreviewsizewidth height camerasetparametersparameters camerastartpreview,['android'] +113104,monitoring historypushstate from a chrome extension i am developing a chrome extension to tweak facebook however catching browsing actions within html5enabled sites such as facebook requires an override of windowhistorypushstate as explained in this so questionunfortunately it seems that chromes isolated worlds prevent this sort of override is there any other method of catching history changes other than polling documentlocationhref,['javascript'] +113105,checking whether an object conforms to two separate protocols in objectivec in objectivec when you declare an instance variable you can check if it conforms to a protocol on assignment at compile time like soid myprotocol variableis it possible to check whether an object assigned to the variable conforms to two separate protocols at compile time as inid myprotocol myotherprotocol variablei know i can do runtime checking using conformstoprotocol and respondstoselector et al which i do before actually using the object for added safety and i could write my own setter method that does the check but i would like to know at compile time,['objective-c'] +113121,populating a datagridview with text and progressbars i am creating a multithreaded application in which each thread will appear as a row in my datagridview i want a progressbar in each row indicating the corresponding thread progressthe question is is this possible and if so how,['c#'] +113125,collect every pair of elements from a list into tuples in python possible duplicatepairs from single list i have a list of small integers say1 2 3 4 5 6i wish to collect the sequential pairs and return a new list containing tuples created from those pairs ie1 2 3 4 5 6i know there must be a really simple way to do this but cannot quite work it outthanks,['python'] +113141,c settings file why do i have to use settingsdefault i am just wondering why it is settingsdefaultmysetting instead of just settingsmysetting,['c#'] +113144,php login framework to include googlefacebookopenid etc in my website i have built a login system which is quite simple i started implementing the facebook login option and it got a bit messyi am looking for some sort of frameworkcode sample db structure sample of a code that bundles the whole thing loginsregistrations via googlefacebookopenid and as many others you know ofstackoverflow has a very similar mechanism of what i am looking foranyone knows of such a system,"['php', 'mysql']" +113157,is it possible to thisable the iphones automatic hyperlinks we send out a notification email whenever we have phishing emails reported to us in these emails we include a copypaste of the text inside the original phishing email as a sample of what is reported to us our code strips all hyperlinks out of the email via php but still includes in plain text the link when users receive this email in their client thunderbird outlook hordeimp etc the hyperlink is removedhowever the iphone likes to take web addresses in plain text and automatically turn them into hyperlinks is there any possible way to stop this action from happening via a html tag or by using php to replace certain parts of the hyperlink,"['php', 'html', 'ios']" +113159,static cast vs dynamic cast suppose i am given a c library full of inheritance i am given a base in a function when i know that it is actually pointing to a derived object and derived inherits base but i do not know what kind of inheritance it is publicprotectedprivate i also do not know if there is any virtual function in the hierarchygiven this situation without looking into the source codedocumentation of base and derived which cast should i use or should i consult the codedocumentation first to ensure about polymorphismbackgroundi am writing changeevent function of qmainwindow in qt 47 the changeevent function takes qevent which i can cast to other type by knowing qeventtype i was wondering if i should use static cast or dynamic castthanks,['c++'] +113163,why this hibernate mysql connection is readonly i have an application using spring with hibernate on a mysql database for some reason as of the last few days anytime i try to persist any objects to my database i am getting the following error javasqlsqlexception connection is readonly queries leading to data modification are not allowedi cannot for the life of me figure out why this is happening my application was working fine a few days ago i am configuring a sessionfactory object in my applicationcontextxml file like this bean idsessionfactory lassorgspringframeworkormhibernate3annotationannotationsessionfactorybean property nameconfiglocation valueclasspathhibernatecfgxml property namepackagestoscan list valuecomdomaindomainobjectsvalue list property beanmy hibernatecfgxml file looks like thisxml version10 encodingutf8doctype hibernateconfiguration public hibernatehibernate configuration dtd 30en hibernateconfiguration sessionfactory database connection settings property nameconnectiondriver classcommysqljdbcdriverproperty property nameconnectionurljdbcmysqlurl to db3306db nameproperty property nameconnectionusernamedb userproperty property nameconnectionpassworddb passwordproperty jdbc connection pool use the builtin property nameconnectionpool size10property sql dialect property namedialectorghibernatedialectmysql5dialectproperty enable hibernates automatic session context management property namecurrent session context classthreadproperty thisable the secondlevel cache property namecacheprovider classorghibernatecachenocacheproviderproperty echo all executed sql to stdout property nameshow sqltrueproperty drop and recreate the database schema on startup property namehbm2ddlautoupdateproperty sessionfactoryhibernateconfigurationi am using a the mysqlj conenction version 51 hibernate version 32 spring mvc 305,['mysql'] +113164,keep unversioned files when deploying with capistrano everytime i run cap deploy in the remote server i lost some unversioned files because capistrano creates a new directory and checkouts the head revision in it but there are some files that are not versioned like users avatars paperclip and uploaded images which do not get copied to the new current releasehow can i workaround thisthanks,['ruby-on-rails'] +113167,what design decisions would favour scalas actors instead of jms what are the differences using scala actors instead of jms for example from a performance and scalability perspective what does the scala actor model add compared to jms in which cases does it make more sense to use actors rather than jms ie what problems does actors address that jms cannot cover,['java'] +113175,entity framework datetime and utc is it possible to have entity framework i am using the code first approach with ctp5 currently store all datetime values as utc in the databaseor is there maybe a way to specify it in the mapping for example in this one for the last login columnmodelbuilderentityuserpropertyx xidhascolumnnameidmodelbuilderentityuserpropertyx xisadminhascolumnnameadminmodelbuilderentityuserpropertyx xisenabledhascolumnnameenabledmodelbuilderentityuserpropertyx xpasswordhashhascolumnnamepassword hashmodelbuilderentityuserpropertyx xlastloginhascolumnnamelast login,['c#'] +113191,floatleft in objectivec i am trying to make a bunch of buttons behave somewhat like floatleft in cso whenever the view changes size on orientation change for example the buttons should adjust so they fit within their container viewin landscape mode this uiscrollview should scroll horizontally in portrait mode it should scroll verticallyi am trying to make an scrollview similar to the featured tab in the ipad youtube app landscape has 4 columns portrait 3 columns subscriptions tab portrait the same view has 2 columns,['objective-c'] +113202,how to reference the cuserspublic directory programmatically in c is it safe to programmatically reference the public folder throughdirectory systemenvironmentgetenvironmentvariablepublicmycompanyname etcor is there a better wayagain what if someone deletes the environment variable for public and is this safe to use for different language ossthis follows how to install to the public directory in windows 7 from the vs 2010 deployment setup project,"['c#', '.net']" +113227,jquery sortable grid functionality without identical dimensions i am looking to create a sortable via drag and drop grid similar to what jquerys sortable grid does however sortable requires that you use only divs with identical dimensions for my purposes each block is allowed to be different widths and heightsthe functionality i am looking for is the snaptogrid capabilities while shoving the other elements out of the way draggable does everything except for preventing them from overlapping and shoving the other elements out of the wayoh it does not have to be jquery either i am open to using other methods if it is easier,"['javascript', 'jquery']" +113236,client side only cookies i need something like a cookie but i specifically do not want it going back to the server i call it a client side session cookie but any reasonable mechanism would be greatbasically i want to store some data encrypted on the server and have the user type a password into the browser the browser decrypts the data with the password or creates and encrypts the data with the password and the server stores only encrypted data to keep the data secure on the server the server should not store and should never receive the password ideally there should be a cookie session expiration to clean upof course i need it be available on multiple pages as the user walks through the web sitethe best i can come up with is some sort of iframe mechanism to store the data in javascript variables but that is ugly does anyone have any ideas how to implement something like thisfwiw the platform is aspnet but i do not suppose that matters it needs to support a broad range of browsers including mobilein response to one answer below let me clarify my question is not how to achieve the crypto that is not a problem the question is where to store the password so that it is persistent from page to page but not beyond a session and in such a way that the server does not see it,"['javascript', 'html']" +113258,how do large sites accomplish rowlevel permissions so i am making a small site using cakephp and my acl is set up so that every time a piece of content is created an acl rule is created to link the owner of the piece of content to the actual content this allows each owner to editdelete their own content this method just seems so inefficient because there is an equivalent amount of acl rules as content in the database i was curious how do big sites with millions of pieces of content solve this problem,"['php', 'mysql']" +113262,remove url parameters with javascript or jquery i am trying to use the youtube data api to generate a video playlist however the video urls require a format of youtubecomwatchv3szod3xkl0y but what the api generates is youtubecomwatchv3szod3xkl0yfeatureyoutube gdata so what i need to do is be able to select everything after and including the ampersand and remove it from the url any way to do this with javascript and some sort of regular expression,"['javascript', 'jquery']" +113276,iphone could not support development i recently reinstalled osx it has been a pain rounding up all of my certificates etc but i finally am back however when trying to install an app on either of two iphones 3gs i have they both saysoftware version 421 8c148 xcode cannot find the software image to install this version could not support developmentwhat is going on both iphones list themselves as up to date in itunes and ios developers center only lists 42 as the available sdkedit i do have a paid membership and i have recently had test apps installed on both of these devicesupdate i removed all 3 the 2 included of my devices from the provisioning portal and deleted them from the organizer closed xcode detached device restarted plugged in device no luck,"['iphone', 'ios']" +113291,struct file in linux driver i am currently learning how to write linux device drivers and i have trouble understanding struct file i am using the book linux device drivers 3rd edition to help me outthis is what i understood a struct file represents an open file thus when open is called in the device driver module the kernel will create a struct file that includes everything related to the device driver b if you want to pass around this instance of the device driver then one has to pass a pointer to the particular struct file that was created by the kernel after open c fileprivate data will always return a pointer to the deviceanother question related to this is the field f pos the book says that the driver can read this value if it wants to know the current position in the file this is what i understand from it d if struct foo dev and if the total amount of memory used by this driver to store data is x then f pos points to the current position in that block of memory reserved by the driver how much of what i understood is right and please correct me where i am wrongthanksmir,['c'] +113309,can java reuse nonthisposed system gui resources i am trying to understand more about the thispose function of awtswings window class and what it does imagine the following series of eventsan instance a of a window derivative x is garbagecollected after going out of scope thispose is not called prior to garbage collectiona new instance of x b is created and shown does b use the nonthisposed resources left behind after a was gcdfurthermore for a window derivative z if there are many instances of z is the jre able to reuse window resources between them,['java'] +113321,java how to i change the color of a specific line or row of string in a text area the one way i could change the color is by setforground however when there are multiple lines of code it makes everything green or black is there another method or any way of solving this problem thanksint key evtgetkeycode if key keyeventvk enter string tb1enterdvalue tb1gettexttostring iftb1enterdvalueequalsyes textarea1setforegroundcolorgreen else textarea1setforegroundcolorlightgray thistextarea1appendtb1enterdvaluenewline thistb1settext,['java'] +113327,using jedit as an ide what are the steps necessary to configure jedit to be an ide i basically want to compile and debug java programs there are so many java plugins i am not sure which ones are best,['java'] +113333,android httpclient perfomance i developing android app which uses a lot of http requests to web service at first i was creating a new httpclient instance before every requestto increase performance i try to do requests in many threads so i created single httpclient instance shared by all threads using threadsafeconnectionmanagerschemeregistry registry new schemeregistryregistryregisternew schemehttp plainsocketfactorygetsocketfactory 80basichttpparams params new basichttpparamsconnmanagerparamssetmaxtotalconnectionsparams 100httpprotocolparamssetversionparams httpversionhttp 1 1httpprotocolparamssetuseexpectcontinueparams truethreadsafeclientconnmanager connmanager new threadsafeclientconnmanagerparams registryhttpclient client new defaulthttpclientconnmanager paramsbut performance decreased to my surprise i have measured time to be spended to exequte requests in such waylong starttime systemcurrenttimemillishttpresponse response clientexecutepostrequestlong reqtime systemcurrenttimemillis starttimelogisynctimer request time reqtimehere this is a log which i get with simple defaulthttpclient without parameters new instance per request01 1051136 infosynctimer18400 request time107601 1054686 infosynctimer18400 request time105101 1057996 infosynctimer18400 request time105401 1059166 infosynctimer18400 request time107001 100346 infosynctimer18400 request time117201 102656 infosynctimer18400 request time1043and what i get with threadsafeclientconnmanager and single httpclient instance01 110606926 infosynctimer18267 request time700101 110610412 infosynctimer18267 request time338501 1106202 infosynctimer18267 request time980101 110623622 infosynctimer18267 request time205801 110629906 infosynctimer18267 request time626801 110634746 infosynctimer18267 request time352501 110650302 infosynctimer18267 request time151what happens and how can i fight thisupdateuse keepalive advantage is what i want but when i create new httpclient instance for every request connection can not be reused despite of this such version runs faster reasons of it is unclear for me,['android'] +113341,how to capture the screen using devgraphicsfb0 android how to capture the android device screen content using devgraphicsfb0 and how to make it an image file using the collected data from frame bufferi know for this it requires the device to be rooted and i am ok with thatthanks in advance,['android'] +113351,what is the difference between synchronizedcollection and the other concurrent collections how does synchronizedcollectiont and the concurrent collections in the systemcollectionsconcurrent namespace differ from each other apart from concurrent collections being a namespace and synchronizedcollectiont being a clasynchronizedcollectiont and all of the classes in concurrent collections provide threadsafe collections how do i decide when to use one over the other and why,['c#'] +113355,difference between utf8 and utf16 difference between utf8 and utf16why do we need thesemessagedigest md messagedigestgetinstancesha256string text this is some textmdupdatetextgetbytesutf8 change this to utf16 if neededbyte digest mddigest,['java'] +113378,free heap size does not increase in maven when i run mavenjettyplugin i run next commandmvn dmaven optsxmx1024m xms512m djettyport8080 jettyrunbut when i try to output free heap size withlong heapfreesize runtimegetruntimefreememoryit always outputs something about about 30 i suppose it is size in bytes so about 30 megabytes why then free heap memory did not increase,['java'] +113387,unable to cast com object microsoft outlook c i have written this code to view the unread items in my outlook mail box and here is the code microsoftofficeinteropoutlookapplication app microsoftofficeinteropoutlookitems items microsoftofficeinteropoutlooknamespace ns microsoftofficeinteropoutlookmapifolder inbox microsoftofficeinteropoutlookapplication application new microsoftofficeinteropoutlookapplication app application ns applicationsession inbox nsgetdefaultfoldermicrosoftofficeinteropoutlookoldefaultfoldersolfolderinbox items inboxitems foreach microsoftofficeinteropoutlookmailitem mail in items if mailunread true messageboxshowmailsubjecttostring but on the foreach loop i am getting this errorunable to cast com object of type system comobject to interface type microsoftofficeinteropoutlookmailitem this operation failed because the queryinterface call on the com component for the interface with iid 0630340c046 failed due to the following error no such interface supported exception from hresult 0x804002 e nointerfacecan you please assist me how to resolve this error,['c#'] +113389,how to extend already defined lists and maps in spring application context imagine a staged application context with different phases we start with an early phase to define the necessary infrastructure the xml application contexts are loaded sequentially the reason to split up these files is an extensionplugin mechanismstage 01defaultconfigurationxmlwe prepare and declare the map with id examplemapping to enhance them later with databeans xmlns xmlnsxsi xmlnsutil xsischemalocation utilmap idexamplemapping beansstage 02customconfigurationxml optionalwe configure the examplemapping and add an entrybeans xmlns xmlnsxsi xmlnsutil xsischemalocation utilmap idexamplemapping entry keythekey valuethevalue utilmapbeansstage 03makeuseofconfigurationxml mandatoryuses the defined map examplemapping whether it is configured customly or it is still the empty declared mapbeans xmlns xmlnsxsi xsischemalocation bean idexampleservice classcomstackoverflowexampleexampleservice property namemapping refexamplemapping beanbeansthe problem here is that it is not possible to add entries to the examplemapping map after the first stage spring throws an exception that the map with id examplemapping already exists if we leave out the first stage the map is undeclared and the third stage cannot resolve examplemapping which also produces an exceptionhow can i solve this issue i read collection merging spring docs but this did not helped is it possible to add values later to mapslists before using themthank you,['java'] +113390,how to transfer a c structure to java by use of jni from c i am creating a dll which is loaded in javai call some c functions from java and also call java functions from c whith uncomplex data types this is working finei struggle with the transfer of a c structure to javahere is a small example descriping what i want to doit is not complete and maybe not correct because my problem is that i am not sure how to do itmy goal is to pass a structure from the type structtype from c to java in order to use the values in the java programin ctypedef struct unsigned char value1 unsigned char value2 structtypevoid pastructtojavastructtype mystruct class cls jmethodid mid globalenv globalobj are globlal values which are already set cls globalenvgetobjectclassglobalenv globalobj mid globalenvgetmethodidglobalenv cls receivestructfromc lpackagestructtypev globalenvcallvoidmethodglobalenv globalobj mid mystructin java public class structtype public int value1 int because there is no uint8 type public int value2public structtype mmystructpublic structtype getmystruct return mmystructpublic void setmystructstructtype mystruct mmystruct mystructpublic void receivestructfromcstructtype mystruct setmystructmystructthanks in advance for your helpsteffen,"['java', 'c']" +113418,how to access servlet session in cxf interceptor i have an in cxf interceptor i want to access the the servlet session in its handlemessage method my interceptor extends abstractphaseinterceptori want to access the session to store some info about the user as my web service client maintains sessionsi can already access the session in my web services,['java'] +113423,what can i do to make my c application take advantage of multiple processor cores i have been doing some tests about the way a net c application uses resources like cpu or memory i wrote some loops that calculate values for a large amount of numbers and i am satisfied with the weight of the algorithmi have a quad core 24 ghz processor but i have noticed that in task manager my application is only using 25 of my cpu why is not it using 100 does that mean that a net c application compiled in vs 2008 only supports single core cpu or is there a way that i can force it to use all cpus,"['c#', '.net']" +113432,css3 and pie not working in ie 8 im trying to demo css3pie and it wont work in ie at allhtml doctype html public w3cdtd html 401 transitionalenhtml head meta httpequivcontenttype contenttexthtml charsetwindows1250 link hreftestcss typetextcss relstylesheet titletesttitle head body div idtitlediv div idsub titlediv div idmain area div iddate areadiv div bodyhtmlcssbody margin 0 autotitle margin 0 auto width 100 height 40px backgroundcolor whitesub title margin 0 auto width 100 height 25px backgroundcolor greendate area width 310px height 250px border 1px solid 4a4949 padding 60px 0 textalign center webkitborderradius 1px mozborderradius 1px borderradius 1px webkitboxshadow 707070 2px 2px 4px mozboxshadow 707070 2px 2px 4px boxshadow 707070 2px 2px 4px background ebebeb background webkitgradientlinear 0 0 0 bottom fromedebeb toc9c7c8 background mozlineargradientedebeb c9c7c8 background lineargradientedebeb c9c7c8 piebackground lineargradientedebeb c9c7c8 behavior urlpiehtc the result is just a block with a border no gradientshadow etcany helpsolution would be much appreciated,['html'] +113433,google maps saving dragable directions you can create markers in my web application and create a route with google directions with those markers but i want the user to be able to change the route aswell and i have found dragable directions in the google maps api v3 is there a way to save the changed directions in the database so you can create the exact route again with that information,['javascript'] +113443,jquery sortable without jquery ui i am in need of sortable drag drop functionality and i am using jquery i cannot really use jquery ui because for this project it would be an overhead i would need to add many kb of js and css only to use small part of functionalityis there any plugin that you could recommend or maybe a simple implementation path that i can followthe solution must be as lightweight as possible preferably based on jquerysizzle or pure javascript,['jquery'] +113450,error androidcontentresresourcesnotfoundexception file from xml type layout resource id 0x1020a hey i am trying to create a design for a list that looks like and mostly behaves like the call log like shown herefor this i downloaded the source code and i am studying it for know what class and xml file implement it and i found this two xml files recent calls list itemxmlxml version10 encodingutf8relativelayout xmlnsandroidandroidlayout widthmatch parent androidlayout heightandroidattrlistpreferreditemheightandroidpaddingleft7dip compsyhclodontpresswithparentimageview androidididcall icon androidlayout widthwrap content androidlayout heightmatch parent androidpaddingleft14dip androidpaddingright14dip androidlayout alignparentrighttrue androidgravitycenter vertical androidsrcandroiddrawablesym action call androidbackgrounddrawablecall background include layoutlayoutrecent calls list item layout and the other is recent calls list item layoutxmlxml version10 encodingutf8merge xmlnsandroidview androidididdivider androidlayout width1px androidlayout heightmatch parent androidlayout margintop5dip androidlayout marginbottom5dip androidlayout toleftofidcall icon androidlayout marginleft11dip androidbackgrounddrawabledivider vertical darkimageview androidididcall type icon androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparenttoptrue androidlayout alignparentlefttrue androidlayout marginleft4diptextview androidididdate androidlayout widthwrap content androidlayout heightwrap content androidlayout toleftofiddivider androidlayout alignparentbottomtrue androidlayout marginbottom8dip androidlayout marginleft10dip androidtextappearanceandroidattrtextappearancesmall androidsinglelinetruetextview androidididlabel androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentlefttrue androidlayout alignparentbottomtrue androidlayout marginleft36dip androidlayout marginright5dip androidlayout alignbaselineiddate androidsinglelinetrue androidellipsizemarquee androidtextappearanceandroidattrtextappearancesmall androidtextstyleboldtextview androidididnumber androidlayout widthwrap content androidlayout heightwrap content androidlayout torightofidlabel androidlayout toleftofiddate androidlayout alignbaselineidlabel androidlayout alignwithparentifmissingtrue androidsinglelinetrue androidellipsizemarquee androidtextappearanceandroidattrtextappearancesmalltextview androidididline1 androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentlefttrue androidlayout alignparenttoptrue androidlayout toleftofiddivider androidlayout aboveiddate androidlayout alignwithparentifmissingtrue androidlayout marginleft36dip androidlayout marginbottom10dip androidtextappearanceandroidattrtextappearancelarge androidsinglelinetrue androidellipsizemarquee androidgravitycenter verticaland my activity is thispublic class ratedcalls extends listactivity private static final string log tag recentcallslistprivate tablelayout tableprivate calldatahelper cdhprivate tablerow rowprivate tablerow row2public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutrecent calls list item logilog tag calling from oncreate cdh new calldatahelperthis table new tablelayoutgetapplicationcontext row new tablerowgetapplicationcontext startservicenew intentthis ratedcallsserviceclass logilog tag service called filistpublic void onresume superonresume filistpublic void filist liststring ratedcalls new arrayliststring ratedcalls thiscdhselecttopcalls setlistadapternew arrayadapterstringratedcallsthis androidridlist ratedcalls listview lv getlistview lvsettextfilterenabledtrue lvsetonitemclicklistenernew onitemclicklistener public void onitemclickadapterview parent view view int position long id toastmaketextgetapplicationcontext textview viewgettext toastlength longshow and then i tried to run it on the android emulator and then it the logcat returned an error like thiscaused by javalangruntimeexception your content must have a listview whose id attribute is androidridlistso inside the recent calls list itemxml i declared thislistview androididandroididlist androidlayout widthwrap content androidlayout heightwrap content androidlayout x1px androidlayout y1pxlistviewand now with this declared i tried to run in the emulator but the logcat returns another errorandroidcontentresresourcesnotfoundexception file from xml type layout resource id 0x1020aso my question is why is this happening and if you have another solution for implement a view like this i am tryingthanks,['android'] +113466,why are winforms applications stathread by default when you create an empty winforms application with visual studio the template has the stathread attribute in the main application class i have been reading some docs about it but i am not sure if i understood it at allreally i have some questions about itwhy is this attribute addedwhat does it meanwhat happens if you remove this attribute,"['c#', '.net']" +113470,jquery opacity cross browser is the the jqueryselectorcssopacity50 cross browserthe only reason i ask is because the line below that wed normally use on cssmozopacity50 filteralphaopacity50 opacity50,['jquery'] +113476,matplotlib simultaneous plotting in multiple threads i am trying to do some plotting in parallel to finish large batch jobs quicker to this end i start a thread for each plot i plan on makingi had hoped that each thread would finish its plotting and close itself as i understand it python closes threads when they get through all the statements in run below is some code that shows this behaviorif the line that creates a figure is commented out it runs as expected another plausibly helpful tidbit is that it also runs as expected when you only spawn one threadimport matplotlibpyplot as pltimport timeimport queueimport threadingdef taphistplots for item in str1 it behaves as expected if the line above is used instead of the one below for item in str1str2 otheritem 1 taphistqueueputitem otheritem maketaphiststartclass maketaphistthreadingthread def runself item otheritem taphistqueueget fig figurequeueget figurequeueputfig1 print itemstrfign timesleep13 pltfigurefig comment out this line and it behaves as expected pltclosefigtaphistqueue queuequeue0figurequeue queuequeue0def main start timetime code in here runs only when this module is run directly figurequeueput1 taphistplots while threadingactivecount1 timesleep1 print waiting on d threadsn threadingactivecount1 print ds elapsed timetimestartif name main mainany help is duly appreciated,['python'] +113495,how do i get the text from uitextfield into an nsstring i have tried various methods which all give me warnings such as username nsstring stringwithformat yournamefield stringvalue which just gives me a warning ofuitextfield may not respond to stringvaluehow do i do this,"['iphone', 'objective-c']" +113501,do i have to add i upgraded devexpress components but in my application i have to change every register assemblydev version line in every pageis there any way to do this without putting same lines to every pagecannot i do this in webconfig page register assemblydevexpresswebaspxgridviewv101 version10160 cultureneutral publickeytokenb88d1754d700e49a namespacedevexpresswebaspxgridview tagprefixdx,['asp.net'] +113510,if curlopt ssl verifypeer is false is the data transfer no longer secure i have recently run into a problem posting data to a server whose ssl certificate was updated i did some research and i found that when curlopt ssl verifypeer is set to false post date goes through successfully can somebody explain the relationship between curlopt ssl verifypeer and verifyhost also if i set verifypeer to false am i no longer transmitting the data over a secure connectionthanks a ton for any help anyone can give,['php'] +113515,with gcc can i thisable wframelargerthan on a perfunction basis using gcc is it possible to specify a set of functions that are exempt from wframelargerthan for example main,"['c++', 'c']" +113542,c equivalent for java executorservicenewsinglethreadexecutor or how to serialize mulithreaded access to a resource i have a couple of situations in my code where various threads can create work items that for various reasons should not be done in parallel i would like to make sure the work gets done in a fifo manner regardless of what thread it comes in from in java i would put the work items on a singlethreaded executorservice is there an equivalent in c i have cobbled something together with a queue and a bunch of lock blocks but it would be nice to be able to use something offtheshelf and testedupdate does anybody have experience with systemthreadingtasks does it have a solution for this sort of thing i am writing a monotouch app so who knows if i could even find a backported version of it that i could get to work but it would at least be something to think about for the futureupdate 2 for c developers unfamiliar with the java libraries i am talking about basically i want something that lets various threads hand off work items such that all those work items will be run on a single thread which is not any of the calling threads,"['c#', '.net']" +113552,how to get the previous url using php suppose my sites url is given as hyperlink on some page on the internet that page could be anything on internet blog orkut yahoo even stackoverflow etc and someone clicks on itand visited my site so can we know using php the previous url from which the visitor came to my page,['php'] +113555,c public variable as writeable inside the class but readonly outside the class i have a net c class where i need to make a variable public i need to initialize this variable within a method not within the constructor however i do not want the variable to be modifieable by other classes is this possible,['c#'] +113569,listcontains based on a property of a list item i have a list mylist of myobjects is it possible to check if mylist contains a particular myobject based on a property of myobject in vbnet in c youd something similar to this rightmylistexistsmyobject myobjectproperty1 3,['.net'] +113579,php json encode is encoding the same data twice i am getting some data from a database and am encoding it to jsonjson ifresult dbcqueryquery num resultnum rows fori 0 i num i row resultfetch array json json encoderow ifi num1 json but instead of getting the json string in the formatnamejoe age22 etcetci am getting every value duplicated because it is giving me the element name as being both the index of an associative and nonassociative array so i am getting0joe namejoe 122 age22 3etc etcetcwhile i can still use the json it is still twice the size that i want it to be and so not efficient is there anyway i can get the json encode method to just give me the associative array inices as the json tags wrong words to describe these things no doubtmany thanks,['php'] +113600,how do i implement autocomplete without using a dropdownlist how can i implement autocomplete without a dropdownlist i would like for the autocomplete to fill in the remaining letters in the textbox in an alternate grey as shown in this picturenb i am not looking for the normal jquery ui autocomplete plugin,"['javascript', 'jquery']" +113603,appcelerator vs monotouch which one is best for a net developer i am a net developer with 10 years experience developing web mobile apps i am looking to branch into iphone and possibly android development i am looking at two productsappcelerator titanium andmonotouch i like monotouch because of it is standing in the mono development communitity and it is c in saying that appcelerator looks very straight forward using html and javascript and targets android too which is overtaking the iphone the apps i am looking to develop are line of business applications with data entry syncing with back office etc can anyone give their opinion on the pros cons of using these tools or any experiences i am very interested in any thoughts thanks in advanceciaran,"['iphone', 'android']" +113608,does printfx1 invoke undefined behavior according to the c standard 6522 paragraph 6if the expression that denotes the called function has a type that does not include a prototype the integer promotions are performed on each argument and arguments that have type float are promoted to double these are called the default argument promotions if the number of arguments does not equal the number of parameters the behavior is undeined if the function is deined with a type that includes a prototype and either the prototype ends with an ellipsis or the types of the arguments after promotion are not compatible with the types of the parameters the behavior is undeined if the function is deined with a type that does not include a prototype and the types of the arguments after promotion are not compatible with those of the parameters after promotion the behavior is undeined except for the following casesone promoted type is a signed integer type the other promoted type is the corresponding unsigned integer type and the value is representable in both typesboth types are pointers to qualiied or unqualiied versions of a character type or voidthus in general there is nothing wrong with passing an int to a variadic function that expects an unsigned int or vice versa as long as the value passed fits in both types however the specification for printf reads 71961 paragraph 9if a conversion specification is invalid the behavior is undeined if any argument is not the correct type for the corresponding conversion speciication the behavior is undeinedno exception is made for signedunsigned mismatchdoes this mean that printfx 1 invokes undefined behavior,['c'] +113619,how do i add a check constraint in a rails migration i need to add a new integer column to an existing table in my rails app the column can only have values 1 2 3 so i would like to add a check constraint to the tablecolumn how do i specify this constraint within a rails migration,"['mysql', 'ruby-on-rails', 'ruby']" +113628,find all occurrences of a substring in python python has stringfind and stringrfind to get the index of a substring in stringi wonder maybe there is something like stringfind all which can return all founded indexes not only first from beginning or first from endfor examplestring test test test testprint stringfindtest 0print stringrfindtest 15that is the goalprint stringfind alltest 051015,['python'] +113632,is the c compiler unable to infer method type parameters by expected return type this seems odd to me but i remember a thread where eric lippert commented on the inability by design or at least convention i think of c to overload methods based on return type so perhaps it is in some convoluted way related to thatis there any reason this does not workpublic static t testt where t new return new t elsewheresomeobject myobj testbut this does var myobj testsomeobjectfrom a certain perspective they are both fine in that youre not repeating yourself in a very small way but is this just a different pass of the compiler,['c#'] +113650,mysql escape string whole post array i was wondering is it possible to just my sql escape string the whole post and get array so you dont miss any variablesnot sure how to test it or i wouldve myself thanks,"['php', 'mysql', 'sql']" +113655,structuremap and injecting ienumerable i am new to structuremap and have some existing code that i am working with that uses structuremap 254there is a class that is constructed using structuremap that has a constructor that takes ienumerableicar as a parameterthe registry has the following codescanx xthecallingassembly xwithdefaultconventions xaddalltypesoficar forrequestedtypeienumerableicarthedefaultisconstructedby x objectfactorygetallinstancesicari am writing a unit test and have obtained a nested container off the objectfactory and have injected an instance using the inject method one of the instances of icar should receive the injected type in its constructor however it was not working and i tracked that down to the objectfactorygetallinstances call which does not use my nested containerhow can i get this to worki also read about structuremap autowiring arrays and ienumerable instances but i could not get it to workis there a better way to rewrite the above registry code so that an instance of ienumerableicar will be created and use the injected type from my nested container,['.net'] +113661,help simplifying a makefile for multiple executables i have common code eg hellocpp that is used by multiple executables i am using a single makefile to build it allexeapp1out app2outsrchellocppobjsrccpposrc mainapp1cpp app2cppobj mainsrc maincppoall exe app1out app1o obj g obj o app2out app2o obj g obj o cppo g c o clean rm f exe obj obj maini am not very happy about having a separate target for each executable the targets are essentially the same is there any way to do this with one target for all executables i was hoping that something like this would workexeapp1out app2outsrchellocppobjsrccpposrc mainapp1cpp app2cppobj mainsrc maincppoall exeoout obj g obj o cppo g c o clean rm f exe obj obj mainbut i get a linking errormishamishadesktopcppstack make f makefile2g c app1cpp o app1og app1o helloo o app1outg helloo no such file or directorymake app1out error 1rm app1ofor some reason it tries to build app1out without building its dependency helloo can anyone explain why this does not work and suggest something that doesheres the rest of the dummy code just in caseapp1cppinclude helloh intmainvoid print helloapp2cppinclude helloh intmainvoid for int i 0 i 4 i print hello return 0hellocppinclude helloh include stdioh voidprint hello printfhello worldnhellohifndef hello hdefine hello hvoidprint helloendif,['c++'] +113666,most efficient way to thisplay a 1x1 gif tracking pixel web beacon i am building a basic analytics service based in theory off of how google analytics works but instead of requesting an actual image i am routing the image request to a script that accepts the data and then outputs an image since browsers will be requesting this image on every load every millisecond countsi am looking for the most efficient way for a file to output a gif file from a php script so far i have established 3 main methods is there a more efficient way for me output a 1x1 gif file from within a php script if not which of these is the most efficient and scalable three identified methodsphp image building librariesim imagecreatetruecolor1 1imagefilledrectangleim 0 0 0 0 0xfb6b6fheadercontenttype imagegifimagegifimimagedestroyimfile get contents the image off of the server and output itim file get contentsrawgif headercontenttype imagegif echo im base64 decode the imageheadercontenttype imagegifecho base64 decoder0lgoddhaqabaiapxqbacwaqabacakqbadsmy gut was that base64 would be fastest but i have no idea how resource intensive that function is and that file get contents would likely scale less well since it adds another filesystem actionfor reference the gif i am using is here editso the reason i am serving this image is that my analytics library builds a query string and attaches it to this image request rather than parse logs i am routing the request to a php script which processes the data and responds with an imageso that the end users browser does not hang or throw an error my question is how do i best serve that image within the confines of a script,"['php', 'javascript']" +113669,capture http requests with javascript is it possible with javascript to listen for and capture outgoing http requests for example ajax calls sort of like firebug etc,['javascript'] +113672,how would i design a clientside queue system overviewi am working on a project and i have come across a bit of a problem in that things are not happening in the order i want them to happen so i have been thinking about designing some kind of queue that i can use to organize function calls and other miscellaneous javascriptjquery instructions used during startup ie while the page is loading what i am looking for does not necessarily need to be a queue data structure but some system that will ensure that things execute in the order i specify and only when the previous task has been completed can the new task begini have briefly looked at the jquery queue and the ajaxqueue but i really have no idea how they work yet so i am not sure if that is the approach i want to take but i will keep reading more about these toolsspecificscurrently i have set things up so that some work happens inside documentreadyfunction and other work happens inside windowloadfunction for examplehead script typetextjavascript i want this to happen 1st loadjavascript do some basic configuration for the stuff that needs to happen later i want this to happen 2nd documentreadyfunction do some work that depends on the previous work do have been completed var script documentcreateelementscript do some more work i want this to happen 3rd windowloadfunction do some work that depends on the previous work do have been completed initializesymbols initializeblock other work etc scripthead and this is really tedious and ugly not to mention bad design so instead of dealing with that mess i want to design a pretty versatile system so that i can for example enqueue loadjavascript then var script documentcreateelementscript then initializesymbols then initializeblock etc and then the queue would execute the function calls and instructions such that after one instruction is finished executing the other can start until the queue is empty instead of me calling dequeue repeatedlythe reasoning behind this is that some work needs to happen like configuration and initialization before other work can begin because of the dependency on the configuration and initialization steps to have completed if this does not sound like a good solution please let me know some basic worki have written some code for a basic queue which can be found here but i am looking to expand its functionality so that i can store various types of objects such as individual javascriptjquery instructions and function calls essentially pieces of code that i want to executeupdatewith the current queue that i have implemented it looks like i can store functions and execute them later for example a js file fnloadjavascript function getscriptjssymbolssymboljs getscriptjsstructuresstructurejs another js filefunction init symbols and structures indexhtmlvar thequeue new queuethequeueenqueueloadjavascriptthequeueenqueueinitvar ljs thequeuedequeuevar init thequeuedequeueljsiniti also think i have figured out how to store individual instructions such as equationhtml or perhaps even ifelse statements or loops by wrapping them as suchthequeueenqueuefunction equationhtml other instructions etc but this approach would require me to wait until the queue is done with its work before i can continue doing my work this seems like an incorrect design is there a more clever approach to this also how can i know that a certain function has completed executing so that the queue can know to move on is there some kind of return value that i can wait for or a callback function that i can specify to each task in the queuewrapupsince i am doing everything clientside and i cannot have the queue do its own thing independently according to an answer below is there a more clever solution than me just waiting for the queue to finish its worksince this is more of a design question than a specific code question i am looking for suggestions on an approach to solving my problem advice on how i should design this system but i definitely welcome and would love to see code to back up the suggestions i also welcome any criticism regarding the queuejs file i have linked to above andor my description of my problem and the approach i am planning to take to resolve itthanks hristo,"['javascript', 'jquery']" +113673,how to implement tcp server and tcp client in java to transfer files i have implement the simple tcp server and tcp client classes which can send the message from client to server and the message will be converted to upper case on the server side but how can i achieve transfer files from server to client and upload files from client to server the following codes are what i have gottcpclientjavaimport javaioimport javanetclass tcpclient public static void mainstring args throws exception string sentence string modifiedsentence bufferedreader infromuser new bufferedreadernew inputstreamreadersystemin socket clientsocket new socket127001 6789 dataoutputstream outtoserver new dataoutputstreamclientsocketgetoutputstream bufferedreader infromserver new bufferedreadernew inputstreamreaderclientsocketgetinputstream sentence infromuserreadline outtoserverwritebytessentence n modifiedsentence infromserverreadline systemoutprintlnfrom server modifiedsentence clientsocketclose tcpserverjavaimport javaioimport javanetclass tcpserver public static void mainstring args throws exception int firsttime 1 while true string clientsentence string capitalizedsentence serversocket welcomesocket new serversocket3248 socket connectionsocket welcomesocketaccept bufferedreader infromclient new bufferedreadernew inputstreamreaderconnectionsocketgetinputstream dataoutputstream outtoclient new dataoutputstreamconnectionsocketgetoutputstream clientsentence infromclientreadline systemoutprintlnclientsentence if clientsentenceequalsset outtoclientwritebytesconnection is systemoutprintlnrunning here welcomesocketclose outtoclientwritebytescapitalizedsentence capitalizedsentence clientsentencetouppercase n ifclientsentenceequalsquit outtoclientwritebytescapitalizedsentenceenter the message or command systemoutprintlnpassed outtoclientwritebytesenter the message or command welcomesocketclose systemoutprintlnconnection terminated so the tcpserverjava will be executed first and then execute the tcpclientjava and i try to use the if clause in the tcpserverjava to test what is users inputnow i really want to implement how to transfer files from both sidedownload and uploadthanks,['java'] +113676,how to install pymssql on windows with python 27 it seems that there are no such binaries yetthere is an issue on googlecodebut i cannot figure out what to do with those files provided,['python'] +113678,center div horizontally on this page i would like to horizontally center the main container div relative to the page normally i would achieve this by adding a css rulecontainer margin 0 auto however the layout of this page which i did not write uses absolute positioning for container and most of its child elements so this property has no effectis there any way i can achieve this horizontal centering without rewriting the layout to use static positioning i have no problem with using javascriptjquery if that is the only way to achieving my objective,"['jquery', 'css']" +113694,stringempty in strings 2 days ago there was a question related to stringlastindexofstringempty returning the last index of stringdo c strings end with empty stringso i thought that a string can always contain stringempty between characters liketesting t stringempty e stringempty sting stringemptyafter this i wanted to test if stringindexofstringempty was returning 0 because since stringempty can be between any char in a string that would be what i expect it to return and i was not wrongstring teststring testingint index teststringlastindexofstringempty index is 6index teststringindexofstringempty index is 0it actually returned 0 i started to think that if i could split a string with stringempty i would get at least 2 string and those would be stringempty and rest of the string since stringindexofstringempty returned 0 and stringlastindexofstringempty returned length of the string here is what i codedstring emptystring stringemptychar emptystringchararr emptystringtochararraystring mydummystring abcdefgstring result mydummystringsplitemptystringchararrthe problem here is i cannot obviously convert stringempty to char and result in an empty string i would really love to see the result of this operation and the reason behind this so my questions areis there any way to split a string with stringemptyif it is not possible but in an absolute world which it would be possible would it return an array full of chars like 0 t 1 e 2 s and so on or would it just return the complete string which would make more sense and why,['c#'] +113738,automatic popping up keyboard on start activity i got a relative simple question i have an activity with a lot of edittexts in them when i open the activity it automatically focusses to the first edittext and thisplays the virtual keyboardhow can i prevent this,['android'] +113739,filtering data using entitydatasource and where hi i have an entitydatasourcei need programmatically send a variable selectedvalue to be used in a where filter for the entitydatasource can you post a simple core to show me how to do it thanks for your timeto create whereparameters on entitydatasource i use this code parameter parameter new parameterselectedvalue typecodeint32 uxtreeview1selectedvalue parameterdefaultvalue 0 uxentitydatasourcenodeswhereparametersaddparameterhere the code for the control aspentitydatasource iduxentitydatasourcenodes runatserver connectionstringnametesthierarchyentities defaultcontainernametesthierarchyentities enableflatteningfalse enableupdatetrue entitysetnamecmscategories whereitcategoryid selectedvalue entitytypefilter select aspentitydatasource,"['c#', 'asp.net']" +113752,converting an int to stdstring what is the shortest way preferably inlineable to convert an int to a string answers using stl and boost will be welcomed,['c++'] +113768,cannot debug tests using resharper cannot launch debugger i am not able to debug my tests using resharperdebug option in my project i have seen this issue raised by lots of people but hast come across a solid suggestion which solves my issuethe strange thing is that if i create a sample project and write a simple unit test i am able to debug it without any issueshowever when i try to do this in my current project it simply throws a dialog box saying cannot launch debuggeri have checked this with my peers and they doest face this issue also i do not have any issues while running the testit is an xp machine and following is the version of resharperjetbrains resharper 51 c edition build 5117534 on 20101015t155130licensed to x plugins none visual studio 90210228 copyright a 2003a2011 jetbrains sro all rights reserved thanksm,['c#'] +113789,whats wrong with const what are the known shortfalls of const in c and c0x,['c++'] +113798,android thisable default vibration of onlongclick is there a way to thisable the vibration for the onlongclick eventi want no vibration or if enabled a custom vibrationeditthank you that did it,['android'] +113802,how do i write a long integer as binary in python in python long integers have unlimited precision i would like to write a 16 byte 128 bit integer to a file struct from the standard library supports only up to 8 byte integers array has the same limitation is there a way to do this without masking and shifting each integersome clarification here i am writing to a file that is going to be read in from nonpython programs so pickle is out all 128 bits are used,['python'] +113811,extremely fast way to clone the values of a jagged array into a second array i am currently working on an application that is responsible for calculating random permutations of a jagged array currently the bulk of the time in the application is spent copying the array in each iteration 1 million iterations total on my current system the entire process takes 50 seconds to complete 39 of those seconds spent cloning the arraymy array cloning routine is the following public static int copyarraythis int source int destination new intsourcelength for each row for int y 0 y sourcelength y initialize array destinationy new intsourceylength for each column for int x 0 x destinationylength x destinationyx sourceyx return destination is there any way safe or unsafe to achieve the same effect as above much faster,['c#'] +113823,create formatted string from arraylist consider following code arraylistinteger alist new arraylistinteger alistadd2134 alistadd3423 alistadd4234 alistadd343 string tmpstring forint avalue alist tmpstring avalue tmpstring string tmpstringsubsequence0 tmpstringlength1 systemoutprintlntmpstringmy result here is 213434234234343 as expectedi do replace the last comma with the ending to get expected result is there a better way of doing this in general,['java'] +113828,mvc active directory membership i am trying to make use of the active directory membership rather than sql but there is very limited documentation available online i have managed to connect my application to the domain controller without any problems but when you use contextuseridentityname it comes up with domainuser i want to basically drill down and get information such as full name email address etci just need a useful link and the searching i have done does not appear to have got me anywheremany thanks,['c#'] +113831,why use stringformat why would anyone use stringformat in c and vb net as opposed to the concatenation operators in vb and in cwhat is the main difference why are everyone so interested in using stringformat i am very curious,['c#'] +113838,how do i use the mingw gdb debugger to debug a c program in windows i have looked for documentation on this and found nothing i have mingw installed and it works great i just do not know how to use the debuggergiven some simple code say in a file called mycodecppint main int temp 0 for int i 0 i 5 i temp i return 0how would i debug this what are the commands that i use to debug code with mingw and gdb in windows can i step through the code via the command line like in visual studio if so what commands do i use to do thatare there any tutorials for using gdb out there i could not find any but if anyone could direct me to one that would be great too i am tired of writing tons of stdcout statements to debug complex code,['c++'] +113843,multithreading with net httplistener i have a listenerlistener new httplistenerlistenerprefixesaddhttp8077listenerstartlistenerthread new threadhandlerequestslistenerthreadstartand i am handling requestsprivate void handlerequests while listenerislistening var context listenerbegingetcontextnew asynccallbacklistenercallback listener contextasyncwaithandlewaitone private void listenercallbackiasyncresult ar var listener arasyncstate as httplistener var context listenerendgetcontextar do some stuffi would like to write void stop in such a way thatit will block until all currently handled requests will end ie will wait for all threads to do some stuffwhile it will wait for already started requests it will not allow any more requests ie return at the beginning of listenercallbackafter that it will call listenerstop listenerislistening became falsehow could it be writeedit what do you think about this solution is it safepublic void stop lock this isstopping true reseteventwaitone initially set to true listenerstopprivate void listenercallbackiasyncresult ar lock this if isstopping return reseteventreset numberofrequests var listener arasyncstate as httplistener var context listenerendgetcontextar do some stuff lock this if numberofrequests 0 reseteventset,"['c#', '.net']" +113846,web scraping how to identify main content on a webpage given a news article webpage from any major news source such as times or bloomberg i want to identify the main article content on that page and throw out the other misc elements such as ads menus sidebars user comments whats a generic way of doing this that will work on most major news sites what are some good tools or libraries for data mining preferably python based,['python'] +113868,what is best way to change one value in xml files in java i have an xml file and i know the node name i need to change the value for the nodename is ipaddressi can use jdom get document get node and change the value and write it or i can write an xslt filethe code changing value goes from java so my question is which option is better the size of the xml file can be differentanother xsltrelated question is it possible to write an xslt file such that i will not be listing all nodes that are in xml but will just specify like if node ipaddress then take the new value and how would i apply the xslt transformation from javathank you,['java'] +113876,change css fontfamily for separate options in select tag i do not know if this is possible and if not if someone can throw out optional ideas but i am attempting to thisplay a drop down of different fonts specifically fonts from googles font directory in a select tag in the drop down i am trying to show a preview by styling each option with the font it representsoption nametangerine stylefontfamilytangerine verdanatangerineoptionthis does not seem to be working though any clues why or how to fix it,"['html', 'css']" +113896,private inheritance using directive overloads i am using private inheritance in a project in the implemented in terms ofsense the base class defines operator and this is the functionality i want to use thus i haveclass a private b using boperator however how can i control which version of the operator i get in fact i need more than one both the const and nonconst versions can this be accomplished,['c++'] +113900,what does only catch exceptions you can handle really mean i am tasked with writing an exception handling strategy and guidelines document for a netc project i am working on i am having a tough go at it there is plenty of information available for howwhen to throw catch wrap exceptions but i am looking for describing what sorts of things should go on inside the catch block short of wrapping and throwing the exceptiontry dosomethingnotnicecatch exceptionicanhandle ex looking for examples of what people are doing in catch blocks other than throw or wrapping the exception and throwingthanks in advance,['c#'] +113903,can css automatically add text if you check the form at this link youll see that required fields have a classrequired in the css and a in the markup can the which shows in the markup be added entirely with css for divs that have this class,['css'] +113904,jquery toggle div with radio buttons simple html jquerylabelinput idrdb1 typeradio nametoggler value1 moneylabellabelinput idrdb2 typeradio nametoggler value2 interestlabeldiv idblk1 stylethisplaynone divdiv idblk2 stylethisplaynone divfunction nametogglereachfunctioni thischangefunction blk1 blk2hide divid blk thisval dividshowslow the desired toggle effect does not work though clicking one radio box fails to hide the otherany ideas,['jquery'] +113918,is ajax a separate language from javascript or is it a javascript framework basically is ajax similar to javascript in syntax and semantics,['javascript'] +113919,do whilefalse pattern possible duplicatewhy are there sometimes meaningless dowhile and ifelse statements in cc macros why is the do whilefalse necessary in the macros belowdefine logmessage do lockmutualexclusion lock logmutex a lot of code while falsei dont think it serves any functional purpose am i overlooking something,['c++'] +113925,using php dateinterval to create recurring events so i have spent quite a bit of time researching how best to add recurring events to my calendar applicationi would like to use the php dateinterval function and have formulated the code below to try and work out how to create a recurring event based on the original events start date finish date and the enddate of recurrenceuser defined event start and finish dateseventstart new datetime 20110131 090 eventfinish new datetime 20110132 170 user defined event recurring end dateendrecurring new datetime 20110531 235959 define for recurring period functionbegin eventstartend endrecurringdefine our intervalinterval dateintervalcreatefromdatestringnext fridayperiod new dateperiodbegin interval end dateperiodexclude start dateloop through and create new dates for recurring eventsforeach period as dt recurringstartdate dtformat l ymd hisn recurringenddate not sure how to process the end date in this start date foreach loopthis should hopefully create a list of new event start dates but i also need to define new end dates for my recurring events how do i do this do i need to process this in the event start date foreach loopmy other question is how i could combine multiple dateintervals to take care of repeat every monday wednesday and friday currently only single dateintervals are working like next fridaythanks for your helptim,['php'] +113926,converting a sentence string to a string array of words in java i need my java program to take a string likethis is a sample sentenceand turn it into a string array likethisisasamplesentenceno periods or punctuation preferably by the way the string input is always one sentenceis there an easy way to do this that i am not seeing or do we really have to search for spaces a lot and create new strings from the areas between the spaces which are words,['java'] +113941,automate pydev interpreter setup i have a scenario where i want to be able automate the setting up of various python interpreters for use in pydev these interpreters have special environment variables forced builtins and libraries defined is there a way through perhaps an ini file or through the pydev jython api to programmatically define python interpreters for pydev,['python'] +113942,getting the type of an array of t without specifying t typegettypet i am trying to create a type that refers to an array of a generic type without specifying the generic type that is i would like to do the equivalent of typegettypeti already know how to do this with a nonarray type egtypegettypesystemcollectionsgenericienumerable1 ortypeofienumerableheres some sample code that reproduces the problemusing systemusing systemcollectionsgenericpublic class program public static void somefunctienumerablet collection public static void somearrayfunctt collection static void mainstring args actiontype printtype t consolewritelinet null ttostring null actionstring printfirstparametertype methodname printtype typeofprogramgetmethodmethodnamegetparameters0parametertype printfirstparametertypesomefunc printfirstparametertypesomearrayfunc var ienumerablet typegettypesystemcollectionsgenericienumerable1 printtypeienumerablet var ienumerabletfromtypeof typeofienumerable printtypeienumerabletfromtypeof var arrayoft typegettypet printtypearrayoft prints null not even sure where to start for typeoft the output issystemcollectionsgenericienumerable1ttsystemcollectionsgenericienumerable1tsystemcollectionsgenericienumerable1tnulli would like to correct that last nullthis will be used to get an overload of a function via reflections by specifying the method signaturevar somemethod sometypegetmethodmethodname new typeofarrayoft call somemethodmakegenericmethod some time lateri have already gotten my code mostly working by filtering the result of getmethods so this is more of an exercise in knowledge and understanding,['c#'] +113946,php dom remove element leave contents i am trying to remove certain links depending on their id tag but leave the content of the link for example i want to turn some text goes a href idremovehereatosome text goes herei have tried using the belowdom new domdocumentdomloadhtmlmb convert encodinghtml htmlentities utf8xp new domxpathdomforeachxpqueryacontainsidremove as oldnode revised strip tagsoldnoderevised mb substrdomsavexmlxpquerybodyitem0 6 7 utf8echo revisedroughly taken from here but it just spits back the same content of htmlany ideas on how i would achieve this,"['php', 'html']" +113949,cs pure virtual function implementation and header files i am having some trouble implementing pure virtual functions inherited from some abstract class when the classes in question are divided into h and cpp files the compiler g tells me that the derived class cannot be instantiated because of the existence of pure functions interfacehnamespace ns class interface public virtual void method0 interfacecppnamespace ns interfacemethod not implemented here derivedh namespace ns class derived public interface note see below derivedcpp namespace ns void derivedinterfacemethod dosomething maincpp using namespace nsint main interface instance new derived compiler errordoes this mean that i have to declare the method twice in the interfaces h and in the derivedh too is there no other way around,['c++'] +113954,lock screen orientation android possible duplicatehow to thisable orientation change in android i am writing an android application that uses tabs with different contents activitiesin one of these activities i would like to lock the screen orientation to landscapemodebut in the other activities i want the normal orientation according to sensorwhat i am doing now is that i am calling setrequestedorientationactivityinfoscreen orientation landscapewhen i switch to the landscape mode activity and setrequestedorientationactivityinfoscreen orientation sensorwhen i switch back to the other activities however this does not seem to workthe whole application locks up what is the normal approach to this problem,['android'] +113959,is there a way for xcode to warn about new api calls on more than one occasion i have seen crashing bugs appear on ios 3x due to use of a new call that was introduced in 4x without proper checkingis there a way for xcode to warn about classes methods and procedures that are only available a later version than the deployment targetthat way i could easily list through all the code and make sure it is properly conditionalized,"['iphone', 'ios']" +113962,keyboard short cut for accessing previous statements in python idle using a mac is there a keyboard short cut for accessing previous statements in python idle i am using a mac thanks,['python'] +113972,how can i use sql ce 4 databases for functional tests due to the potential differences between linqtoentities ef4 and linqtoobjects i need to use an actual database to make sure my query classes retrieve data from ef correctly sql ce 4 seems to be the perfect tool for this however i have run into a few hiccups these tests are using mstestthe problem i have is if the database does not get recreated due to model changes data keeps getting added to the database after each test with nothing getting rid of the data this can potentially cause conflicts in tests with more data being returned by queries than intendedmy first idea was to initialize a transactionscope in the testinitialize method and thispose the transaction in testcleanup unfortunately sql ce4 does not support transactionsmy next idea was to delete the database in testcleanup via a filedelete call unfortunately this seems to not work after the first test is run as the first tests testcleanup seems to delete the database but every test after the first does not seem to recreate the database and thus it gives an error that the database file is not foundi attempted to change testinitialize and testcleanup tags to classinitialize and classcleanup for my testing class but that errored with a nullreferenceexception due to the test running prior to classinitialize or so it appears classinitialize is in the base class so maybe that is causing iti have run out of ways to effectively use sql ce4 for testing does anyone have any better ideasedit i ended up figuring out a solution in my ef unit test base class i initiate a new instance of my data context and then call contextdatabasedelete and contextdatabasecreate the unit tests run a tad slower but now i can unit test effectively using a real databasefinal edit after some emails back and forth with microsoft it turns out that transactionscopes are now allowed in sqlce with the latest release of sqlce however if you are using ef4 there are some limitations in that you must explicitly open the database connection prior to starting the transaction the following code shows a sample on how to successfully use sql ce for unitfunctional testing testmethod public void my sqlcescenario using var context new mysqlcemodelcontext a derived from dbcontext objectcontext objctx iobjectcontextadaptercontextobjectcontext objctxconnectionopen a open your connection explicitly using transactionscope tx new transactionscope var product new product name vegemite contextproductsaddproduct contextsavechanges objctxconnectionclose a close it when done,['c#'] +114087,jquery event that tracks click in browser autocomplete i have a keyup event on an input this event works fine for auto complete when you select a value and press enter but it does not work when you click at an auto complete valueis there an event that i can use in such casei already tried the change one but it does not workthankseditmaybe i was not clear but i am referring to the autocomplete feature that browsers have i am not trying to build my ownexample i have the following eventproductkeyupsearchbyproductwhen user clicks at this input the old values that he already typed shows up it is the browser that does this if he clicks on one of the values the function searchbyproduct is not calledwhich event do i have to register to track this click and that the input content has changed,['jquery'] +114093,problems setting a new node value in java dom xml parsing i have the following codedocumentbuilder dbuilder dbfactory newdocumentbuilderstringreader reader new stringreadersinputsource inputsource new inputsourcereaderdocument doc dbuilderparseinputsourceand then i would like to create a new element in that node right under the root node with this codenode node doc createelementnew nodenodesetnodevaluenew node valuedoc getdocumentelementappendchildnodethe problem is that the node gets created and appended but the value is not set i do not know if i just cannot see the value when i look at my xml if its hidden in some way but i do not think that is the case because i have tried to get the node value after the create node call and it returns nulli am new to xml and dom and i do not know where the value of the new node is stored is it like an attributenew node valuenew node value or does it put value herenew node new node value new nodeany help would be greatly appreciatedthanks josh,['java'] +114095,how do i find where jdk is installed on my windows machine i need to know where jdk is located on my machine on running java version in cmd it shows the version as 16xxto find the location of this sdk on my machine i tried using echo java home but it is only showing java home as there is no java path var set in my environment variables,['java'] +114100,whats the best way to manage concurrency in a database access application a while ago i wrote an application used by multiple users to handle trades creationi have not done development for some time now and i cannot remember how i managed the concurrency between the users thus i am seeking some advice in terms of designthe original application had the following characteristicsone heavy client per user a single database access to the database for each user to insertupdatedelete trades a grid in the application reflecting the trades table that grid being updated each time someone changes a deal i am using wpf heres what i am wonderingam i correct in thinking that i should not care about the connection to the database for each application considering that there is a singleton in each i would expect one connection per client with no issue how can i go about preventing the concurrency of the accesses i guess i should lock when modifying the data however do not remember how to how do i set up the grid to automatically update whenever my database is updated by another user for examplethank you in advance for your help,['c#'] +114101,can i expandcollapse content of jquery ui accordion by click another elements too by default there are headers of contents to control expandcollapsebut in my situationi could expandcollapse the contents by another elements too for examplethe basic structure of jquery ui accodion codescript function accordion accordion scriptdiv classdemodiv idaccordion h3a hrefsection 1ah3 div p mauris mauris ante blandit et ultrices a suscipit eget quam integer ut neque vivamus nisi metus molestie vel gravida in condimentum sit amet nunc nam a nibh donec suscipit eros nam mi proin viverra leo ut odio curabitur malesuada vestibulum a velit eu ante scelerisque vulputate p divdivand now i have another elementsjust like ul idanother elements can expandcollapse too lia href expandcollapse contents of section1 of idaccordion tooaliulthank you very much,['jquery'] +114121,jlayeredpane versus container layering jlayeredpane allows one to stack multiple components on top of one another using jlayeredpaneaddcomponent integer components in higher layers thisplay on top of components in lower layerscontaineraddcomponent int provides a similar mechanism whereby components with lower indexes thisplay on top of components with higher indexesplease note that the first mechanism uses integer and the second mechanism uses int also one renders high values on top of low ones and the other does the opposite do not mix the two my question is whats the point of using jlayeredpane when container already provides the same mechanism does one layer components better than the anotherupdate there is also containersetcomponentzordercomponent int to consider,['java'] +114124,how many bytes of memory does a javautildate object use i need to store a large amount of dates potentially large enough that the amount of heap space used is a concern so please no lectures on premature optimization and i am wondering if it makes sense to use some sort of primitive representation instead of javautildate or some other existing date class i know i could do some profiling to try it out but does anyone know offhand exactly how many bytes of memory a single date object uses,['java'] +114132,sql to find the first occurance of sets of data in a table say if i have a tablecreate table t tabledtm timestamp not null code int not nulland i insert some rowsinsert into t tabledtm code values 20110113 10 5insert into t tabledtm code values 20110113 1010 5insert into t tabledtm code values 20110113 1020 5insert into t tabledtm code values 20110113 1030 5insert into t tabledtm code values 20110113 1040 0insert into t tabledtm code values 20110113 1050 1insert into t tabledtm code values 20110113 110 1insert into t tabledtm code values 20110113 10 1insert into t tabledtm code values 20110113 1120 0insert into t tabledtm code values 20110113 1130 5insert into t tabledtm code values 20110113 1140 5insert into t tabledtm code values 20110113 1150 3insert into t tabledtm code values 20110113 120 3insert into t tabledtm code values 20110113 1210 3so i end up with a table similar to20110113 10 520110113 1010 520110113 1020 520110113 1030 520110113 1040 020110113 1050 120110113 110 120110113 10 120110113 1120 020110113 1130 520110113 1140 520110113 1150 320110113 120 320110113 1210 3how can i select the first date of each set of identical numbers so i end up with this20110113 10 520110113 1040 020110113 1050 120110113 1120 020110113 1130 520110113 1150 3i have been messing about with sub queries and the like for most of the day and for some reason i cannot seem to crack it i am sure there is a simple way somewherei would probably want to exclude the 0s from the results but that is not important for nowthanks,['sql'] +114133,heavy use of phps some php code i look at is littered with php and tags depending on whether it is outputting html or not is there any performance benefit to this rather than using echo to write the html it makes the code extremely hard to read when the codes constantly switching between code and html via the php tagnote that i am not just talking about the occasional switchover the code i am currently looking at the mantisbt sourcecode is giving me a headache with the amount of times it is switching very very hard to read i am wondering if there is a reason for them doing it like this,['php'] +114138,how come the net framework 35 offline installer is 200 mbs larger than the net 4 offline installer i have codesupport an application built on net framework that has always run on net 2 this year we are upgrading the application to use net 35 or 4 in preparing for this change we noticed that that offline installer required for our customer base for net 35 is 200 mbs bigger than the net 4 offline installer here are my questionswhy is the dotnet 35 installer so much bigger than the 4 offline installercan we target net 35 but thistribute net 4 in other words is net 4 backwards compatible assuming that net 4 was the only installed net could application still target earlier frameworksif our application is compiled for x86 cpu rather than any cpu do you still have to thistribute the x64x86 client profile or can we just thistribute the x86 client profile in other words can we thistribute the x86 client profile even though it will be installed on x64 machines if our app is compiled for x86 target cpu any risks or gotchas for doing thisthe issue is that if we upgrade our app to target net 4 there are a lot of application servers that we also have to upgrade which effects a number of other applications any thoughtsseth,['.net'] +114153,how to execute mysql script with variables using phppdo i am unable to execut long script the pdo throws an exceptionsqlstatehy0 general errorif i submit script which does not contain variables it runs wo problemthe same script runs on phpmyadmin interfacehere is my code snippet try dsn mysqlhost db server dbname db default db new pdodsn db user db pass dbsetattributepdoattr errmode pdoerrmode exception q dbqueryquery if q echo dberrorinfo else rows qfetchallpdofetch assoc catch pdoexception e var dumpe here is some test which does not execute by pdoset ra lmc809select ra lmchow i should execut with pdo the multi line scriptsthanks arman,"['php', 'mysql', 'sql']" +114163,blowfish salt length for the crypt function according to the crypt documentation the salt needs to be 22 base 64 digits from the alphabet 09azazthis is the code example they givecryptrasmuslerdorf 2a07usesomesillystringforsaltthe first confusing part is that salt has 25 characters not 22 question 1 does that mean the salt is supposed to be longer than 22 charactersthen i tested the function myself and noticed something if i use a 20 character salt i get this using 20 char salt 01cryptrasmuslerdorf 2a0701 2a07016th1f3o1sypwaeufdz7ieidkqokgkh2so when i used a 20 character salt the entire salt is in the output which is convenient because i do not have to store the salt in a separate place then i want to use random salts i would be able to read the salt back out of the generated hashhowever if i use a 22 character salt as the documentation says or a longer one the salt is cut off at the end using 22 char salt 0122cryptrasmuslerdorf 2a070122 2a07012urtfyykwmppmwdrmcualulrbkhvglui 22nd character of the salt is gone using 25 char salt 012cryptrasmuslerdorf 2a07012 2a07012urtfyykwmppmwdrmcualulrbkhvglui same hash was generated as before 21 chars of the salt are in the hashquestion 2 so what exactly is the proper length of a salt 20 22 longerquestion 3 also is it a good idea to read the salt out of the hash when it is time to check passwords instead of storing the salt in a separate field and reading it from there which seems redundant since the salt seems to be included in the hash,['php'] +114177,detecting constness of nested type normally if i need to detect whether a type is const i just use boostis const however i ran into trouble when trying to detect the constness of a nested type consider the following traits template which is specialized for const typestemplate class tstruct traits typedef t referencetemplate class tstruct traitsconst t typedef t const referencethe problem is that boostis const does not seem to detect that traitsconst treference is a const typefor examplestdcout stdboolalphastdcout boostis consttraitsintreferencevalue stdcout boostis consttraitsconst intreferencevalue stdendlthis outputs false falsewhy does not it output false true,['c++'] +114180,why does joda time change the pm in my input string to am my input string is a pm time logstart sunday january 09 2011 630 pmi am using joda times pattern syntax as follows to parse the datetime datetimeformatter parser1 datetimeformatforpatterne m dd y hmmss aa datetime starttime parser1parsedatetimestartso why is my output string am logparser1printstarttime sunday january 09 2011 630 am,['java'] +114186,starting tasks in foreach loop uses value of last item i am making a first attempt at playing with the new tasks but something is happening that i do not understand first the code which is pretty straightforward i pass in a list of paths to some image files and attempt to add a task to process each of thempublic boolean addpicturesiliststring paths boolean result pathscount 0 listtask tasks new listtaskpathscount foreach string path in paths var task taskfactorystartnew boolean taskresult processpicturepath return taskresult taskcontinuewitht result tresult tasksaddtask taskwaitalltaskstoarray return resulti have found that if i just let this run with say a list of 3 paths in a unit test all three tasks use the last path in the provided list if i step through and slow down the processing of the loop each path from the loop is usedcan somebody please explain what is happening and why possible workaroundsthankswts,['c#'] +114191,light weight c sax xml parser i know of at least three light weight c xml parsers rapidxml tinyxml and pugixml however all three use a dom based interface ie they build their own inmemory representation of the xml document and then provide an interface to traverse and manipulate it for most situations that i have to deal with i much prefer the sax interface where the parser just spits out a stream of events like startoftag and the application code is responsible for doing whatever it wants based on those eventscan anyone recommend a light weight c xml library with a sax interfaceedit i should also note the microsoft xmllite library which does use a sax interface well actually a pull interface which is possibly even better unfortunately it is ruled out for me at the moment since as far as i know it is closed source and windows only please correct me if i am wrong on this,['c++'] +114193,fixing paths in python is there an easy way in python to resolve path operators like for instance is there a function call that will convert testpath to path,['python'] +114210,how to get selected option jquery autocomplete i know there is a select event but is not workingthis is my codeasignacion movimiento ordencompraautocomplete asignacionesobtenerordenescompra extraparams serial function return asignacion movimiento materialval delay 200 select function event ui alertthisvalue uiitemvalue obtenerdatosadicionales return true i also tried addingresult function event data formatted alertdata obtenerdatosadicionales return true but nothing happenshow can i get the value of the selected item by the userthx,['jquery'] +114215,use web garden to simulate web farm session issues i just stumbled across the concept of a web garden in an iis app pool that is when more than one process serves the same webpage from what i understand this means aspnet inproc sessions have the same problems as a web farmmy question is assuming your production environment is a web farm but your developmenttest environment is not would it be helpful to set up a web garden in devtest i am thinking this would help catch any multiproceserver issues early on or at least confirm that everything works as expected,['asp.net'] +114223,why is the result of 13 0 i was writing this codepublic static void mainstring args double g 1 3 systemoutprintf2f gthe result is 0 why is this and how do i solve this problem,['java'] +114224,curvingwarping views with coreanimation or opengl for carousel effect right now i am populating a uiscrollview with a series of views the views need to be warped to make the uiscrollview appear like a carousel in other words when the user scrolls it needs to be like a circle i have never done anything quite like this before but i am assuming coreanimation is out of the question and opengl needs to be used if this is possible with coreanimation or quartz then i really just need a sample on how to warp the views and i can figure the rest out myself but i am not familiar with opengl,['iphone'] +114226,regular expression for 10 digit number without any special characters what is the regular expression for a 10 digit numeric number no special characters and no decimal,"['c#', '.net']" +114238,generate visual studio xml documentation from javascript files were currently using sandcastle to generate our api documentation which is working great however wed like to use visual studio style comments with our javascript files and have an xml documentation file generated that can be processed by sandcastle is this possible i am currently trying out ajax doc but having trouble getting it working getting sysservices is undefined js error from microsofts ajax lib googling and binging lead me nowhere looking to see if there are alternatives to ajax doc i can use to generate the documentationany constructive input is greatly appreciated,['javascript'] +114250,equivalent to produce field glow in other browsers i was long using this to add a glow to focused fields i accessed my page from firefox for the first time and realized it does not work on it and most likely not on explorer eitherborder 1px solid e68d29outlinecolor webkitfocusringcoloroutlineoffset 2pxoutlinestyle autooutlinewidth 5pxi had copy pasted it from another page so i am not quite sure how it works what is the equivalent for firefox or explorer i mean how do i make a similar glow in other browsers thanks,['css'] +114263,sql query to find all tables in a database that have a column with a specific name what query can i run on a database that will tell me which tables in that database have a column named rcptnmbr,['sql'] +114269,memory allocation in c i am confused about the memory allocation in c in terms of the memory areas such as const data area stack heap freestore heap and globalstatic area i would like to understand the memory allocation pattern in the following snippet can anyone help me to understand thisif there any thing more apart from the variable types mentioned in the example to help understand the concept better please alter the exampleclass foobar int n stored in stack public int pubvar stored in stack void fooint param param stored in stack int pp new int int is allocated on heap and param static int nstat stored in static area of memory int nloc stored in stack string str mystring stored in stack ifcondition static int nsif stored in static area of memory int loopvar stored in stack int mainint foobar bar bar stored in stack or a part of it foobar pbar pbar is stored in stack pbar new foobar the object is created in heap what part of the object is stored on heapeditwhat confuses me is if pbar new foobar stores the object on the heap how come int nloc and int pubvar that are components of the object stored on stack sounds contradictory to me should not the lifetime of pubvar and pbar be the same,['c++'] +114279,what does if file 0 mean in ruby if file 0 unshift filejoinfiledirname file i found this code in ruby whats the meaning,['ruby'] +114283,is there a way to use uiviewanimationoptiontransitioncurlup without it animating the entire screen i have a view controller that has the following hierarchyuiviewcontrollerview presentview uiview stagedview uiview uitoolbari am using the transitionfromviewtoviewdurationoptionscompletion method to animate a page curl up to swap between the presentview and the stagedview the present and staged view only cover most of the screen and there is a uitoolbar at the bottom when i use the uiviewanimationoptiontransitioncurlup transition it is animating the whole root view toolbar included not just the two views involveduiview transitionfromviewselfpresentview toviewselfstagedview duration05f optionsuiviewanimationoptiontransitioncurlup completion bool finished if finished cleanup code is there a way to only animate the two subviews leaving the toolbar alone if so how,['iphone'] +114290,how to do proper database testing tdd on rails 3 using mongodb and mongoid how would go about writing proper unit testing and integration testing for that matter using mongodb through mongoid on rails i am asking because to the opposite of using let us say sqlite3 even when running tests everything i do does persists so for the moment i am writing the creation test and then i manually delete everything i do but it is getting annoying and even complicated to do for integration testingsample of what i dobeforeeach do user usercreateattrendaftereach do mongodb is not a transactional db so added objects create during tests cannot be rollbacked checking for the existance of a similar object with exact name and email regex make it case insensitive cleanup userwherename example user email i cleanupdestroy unless cleanupnilendany idea how to make mongodb not persistent during testing i cannot even run the console in sandbox mode because to use mongoid i had to deactivate active record,['ruby-on-rails'] +114302,mysql order by in mongodb findone in my mongo collection i have several records with timestamps i want to use findone and return the oldest record with a where parameterif it is not possible to use findone it is alright i just need to return the oldest record with a where parameterhow can this be done in mongodb,['php'] +114310,html element array namesomething or namesomething i saw something on this site handling array of html form elements in javascript and phpit said about put the array in name property and how the get the input collections valueeg nameeducationbut as i know html input element is arrayready by name on clientside getelementsbyname or serverside post in php or requestform in aspnet for example nameeducation so what is the different with or with not the,"['php', 'html']" +114318,why should i care about rvms gemset feature when i use bundler i just do not get it i thought bundler was developed to resolve version conflicts between gems so that i just have to require bundlersetup and everything is fine knowing that bundler will load the correct versions of all my gems and their dependencies now rvm is great for managing multiple rubies i know but why should i care about the gemset feature do i miss something here can it make my development even easier maybe some of you can give me some hints on the perfect rvm bundler workflow for both development and productioni also do not know when rvm starts switching to another ruby i know that i can have an rvmrc file in my project but do i have to cd to this directory so that the switch happensfurthermore i usually use passenger for development since thanks to the passengerprefpane integration in mac os is great can i still do that with rvm or is there a better way to do it does passenger recognize rvmrc files and switch to the correct gemset,['ruby'] +114328,how to sftp with php i have came across many php scripts for web ftp clients i need to implement a sftp client as a web application in phpdoes php support fot sftp i could not find samplescan anyone help me with this,['php'] +114330,checking for dbnull throws a strongtypingexception i am using a dataset to pull data from a db one of the fields in a row is null i know this however the following vbnet code throws a strongtypingexception in the autogenerated get somefield method in the dataset designerif not isdbnullarowsomefield thendo somethingend ifaccording to documentation and this question it should be fineedit if arowsomefield is dbnullvalue then also returns the same error argh,['.net'] +114333,webrat autofilling form fields i am learning how to write tests with cucumberwebrat one of my test scenarios is set to test form validation leaving fields empty strangely enough fields that i do not fillin with fill in are set to the fields name attribute this only happens when i run cucumber when using a browser this does not happenthe step i am using is straight forwardwhen i submit the form do not filling in the name field here fill in description with this is a description click button saveendafter running the scenario that uses the step above i can see that the text field name is set to name instead of being empty this is also the case if i fill in that field with an empty space or nilfill in name with the form i am testing on is simple enoughform actionitemcreate methodpost div label foritemnamenamelabel input typetext namename iditemname div div label foritemdescriptiondescriptionlabel textarea namedescription iditemdescriptiontextarea div input typesubmit valuesave formany idea why this is happening,['ruby'] +114339,how to center jquery ui buttons adding this to css does not workuidialogbuttonpane textalign center the buttons are still on the right sidewhat should i do,['jquery'] +114357,jquery keypress backspace would not fire i wonder what i am doing wrongskeypressfunctione switch ekeycode case 8 backspace consolelogbackspace case 9 tab case 13 enter case 37 left case 38 up case 39 right case 40 down break default dosearch i want my dosearch function also to be fired when i hit the backspace key at the moment absolutely nothing happens when i press backspace in chrome and safariany ideas,['jquery'] +114359,int to hex string i need to convert and int to hex stringwhen converting 1400 578 using tostringx or tostringx2 but i need it like 0578 can anyone provide me the iformatter to ensure that the string has 4 chars long,['c#'] +114361,javascript object literal length undefined i am working on this animation function but i have a problem i cannot seem to perform what should be an easy task i can not get the length of an object if you check out that jsfiddle you can see that i am running alertpropertieslength and it is returning undefined can anyone see why this might be,['javascript'] +114365,python exception message capturing import ftplibimport urllib2import osimport logginglogger logginggetloggerftpuploaderhdlr loggingfilehandlerftploglogformatter loggingformatterasctimes levelnames messageshdlrsetformatterformatterloggeraddhandlerhdlrloggersetlevellogginginfoftpaddr some ftp addressdef upload to ftpcon filepath try f openfilepathrb file to send constorbinarystor filepath f send the file fclose close file and ftp loggerinfofile successfully uploaded to ftpaddr except e loggererrorfailed to upload to ftp strethis does not seem to work i get syntax error what is the proper way of doing this for logging all kind of exceptions to a file,['python'] +114367,how to profile memory usage i am aware of valgrind but it just detects memory management issues what i am searching is a tool that gives me an overview which parts of my program do consume how much memory a graphical representation with eg a tree map as kcachegrind does for callgrind would be cooli am working on a linux machine so windows tools will not help me very much,['c++'] +114389,query sql server database from native ios application i am working on an inhouse ios app that will need readonly access to a sql server with multiple databases i know the stock answer here is write some web services but i would like a solution that is selfcontained is there any way to directly connect to a sql server database from an ios application i am thinking something like a basic odbc connectioni have seen a lot of users asking this question but very few answers other than write a web service is that really the only way,['ios'] +114391,thistance between items in a listview i have a listview in my layout listview androidididlist infoitems androidlayout widthfill parent androidlayout heightwrap contentevery list item layout looks likelinearlayout xmlnsandroid androidlayout widthfill parent androidlayout heightwrap content androidorientationvertical androidbackgrounddrawableselector custombutton androidpadding10dp androidlayout gravitycenter textview androidididtext history station name androidlayout widthwrap content androidlayout heightwrap content androidgravitycenter verticalleft androidtextcolorcolorrnv blue 540c textview androidididtext history line id androidlayout widthwrap content androidlayout heightwrap content androidgravitycenter verticalleft androidtextcolorcolorrnv blue 540c linearlayouti want to have a thistance between all item for that iv played with androidmargin property but without successdoes anybody know how to change the thistance between item in a listviewthank youmur,['android'] +114392,list with items returns empty i have created a simple list function but if i loop through the list it is empty it should not be list function public class process hook public static liststring pro hook new liststring new string list all pocesses protected static string list all pocesses stringbuilder list new stringbuilder foreach process i in processgetprocesses try foreach processmodule pm in imodules pro hookaddpmfilenametostring catch return listtostring call private void button1 clickobject sender eventargs e foreach string list in process hookpro hook consolewriteline list,"['c#', '.net']" +114411,installing windows service with scexe or installutilexe there is difference but which scexe and installutil both installuninstall windows services but they do not seem to work the same waywhat is the differencefor instance installutil fails some file or dependency not found error while sc create happily installs the service too add to the strangeness the service does not show up if i run net start in the console but it does show up in the services guivariants of this happen when i try to uninstalli have written the service myself and earlier versions work dotnet35,['.net'] +114414,find types in all assemblies i need to look for specific types in all assemblies in a web site or windows app is there an easy way to do this like how the controller factory for aspnet mvc looks across all assemblies for controllersthanks,"['c#', '.net', 'asp.net']" +114415,can anyone explain me 1nf 2nf 3nf bcnf rules with a proper example this is a common interview question i faced one interview where the interviewer gave me one table and asked me tell him which normal form the table is in if it is in nf then normalize it to the next nfi am always get confused between these normal forms of database can anyone explain to me these normal forms with a proper example of how each nf is modeled into table so it will help in my next interview,['sql'] +114424,is it possible to roll back create table and alter table statements in major sql databases i am working on a program that issues ddl i would like to know whether create table and similar ddl can be rolled back inpostgres mysql sqlite et aldescribe how each database handles transactions with ddl,['sql'] +114431,browser based ide textarea with code completion available recently i thiscovered it is possible to have syntaxhighlighting in a textarea using javascriptare there open source libraries which also support auto completioni would like to make a simple online editor for htmlcss templatespreferably the completion is can be extended so i can add custom rules,['javascript'] +114436,use of global keyword in python what i understand from reading the documentation is that python has a separate namespace for functions and if i want to use a global variable in that function i need to use globali am using python 27 and i tried this little test sub 0 0 0 0 def getjoin return joinsub getjoin0it seems things are working fine even without global i was able to access global variable without any problemam i missing anything also following is from python documentationnames listed in a global statement must not be defined as formal parameters or in a for loop control target class definition function definition or import statementwhile formal parameters and class definition make sense to me i am not able to understand the restriction on for loop control target and function definition,['python'] +114445,do bluegene systems support ltdl or any other kind of dlopen support so i have some code that uses dlopen for loading libraries and i want it to work on a bluegene system but i do not have a bluegene to test things on and i have never directly worked with one does bluegene support ltdlh or does it use something else if so what does it use,['c++'] +114472,autowire not working in junit test i am sure i am missing something simple bar gets autowired in the junit test but why does not bar inside foo get autowired runwithspringjunit4classrunnerclasscontextconfigurationbeansxmlpublic class bartest autowired object bar test public void testbar throws exception this works assertequalsexpected barsomemethod this does not work because the bar object inside foo is not autowired foo foo new foo assertequalsexpected foosomemethodthatusesbar,['java'] +114497,wireless iphone app thistribution problem with itmsservices protocol i have followed all the directions from apple and some other blog posts i have archived the app made plist and ipa files put them on a server and linked to them i can install the provisioning profile just fine but when i click on the link to install the app in safari on the iphone nothing happens no error message nothing this is what the link looks likea hrefitmsservicesactiondownloadmanifesturlinstall the appaany idea why this is not working it seems the itmsservices protocol is just dead mime types are fine i can point to the plist file in the address bar and it thisplays as text,['ios'] +114514,iphone coredata application directory i am using this xcode template for core data on the delegate i have this method nsurl applicationdocumentsdirectory return nsfilemanager defaultmanager urlsfordirectorynsdocumentdirectory indomainsnsuserdomainmask lastobjectbut this requires ios4i am trying to make the app compatible with 30so i have converted this method to nsurl applicationdocumentsdirectory nsarray paths nssearchpathfordirectoriesindomainsnsdocumentdirectory nsuserdomainmask yes nsstring documentsdirectory paths objectatindex0 return nsurl urlwithstringdocumentsdirectorybut when coredata tries to use the store url on nsurl storeurl self applicationdocumentsdirectory urlbyappendingpathcomponentmyfilesqlite if persistentstorecoordinator addpersistentstorewithtypenssqlitestoretype configurationnil urlstoreurl optionsnil errorerror it crashes on the if line with the messagecoredata sql stores only support file urls got varmobileapplicationsbb312a7e6ae14ba2ad876b96d8855cc6documentsmyfilesqlitebut storeurl is a nsurl any clues thanks,['iphone'] +114516,escaping values in rails similar to mysql real escape string i know about prepared statements but if i am using raw sql does activerecord have a way to manually escape valuessomething like this would be niceselfescapeomalley omalley,['ruby-on-rails'] +114518,whats the best approach for modifying pdf interactive form fields on ios i have been doing some head banging on this one and solicit your advicei am building an app that as part of it is features is to present pdf forms meaning thisplay them allow fields to be changed and save the modified pdf file back out uiwebviews do not support pdf interactive formsusing the cgpdf apis and benefit from other questions posted here and elsewhere i can certainly present the pdf without the form fieldswidgets scan and find the fields in the document figure out where on the screen to draw something and make them interactivewhat i cannot seem to figure out is how to change the cgpdfdictionary objects and write them back out to a file one could use the cgpdf apis to create a new pdf document from whole cloth but how do you use it to modify an existing fileshould i be looking elsewhere such as 3rd party pdf libs like podofo or libharu i would love to hear from anyone who has successfully modified a pdf and written it back out as to your approach,['ios'] +114529,test driven development unit testing let me first explain what i am aiming for with this questionwhat kind of dev i am i am the guy who thinks about the problem writes the code and then tests it by myself i am developing webapps mainly but there are also projects which are ui based too rcpswing apps i run my app and click here test this you probably know this stylewell i am a guy who tries to improve himself with every lineproject and i want my codeapps to be tested pragmatically i write in code i want test in codeso i started for some of my classesfunctions to use unit tests junit 4 this works for backend stuff where no ui is involved tbh i find it hard to write the most of tests if were building a webapp there are probably interactions with the session or something i guess you get the point what i am looking for are some resources probably with examples any good book advice would be welcome too do not get me wrong i do not want only stuff for logic testing i am interested in ways to test my ui maybe this is an important part too i developing in java 85 of the time and phppython the restregards,['java'] +114540,nginx auth basic and php i want to protect a folder of my website with a password using auth basic this folder contains phpscripts which should be executed if they are requestedi tried the followinglocation admin auth basic adminsection auth basic user file myfolderhtpasswd location adminphp auth basic adminsection auth basic user file myfolderhtpasswd fastcgi pass 12700190 fastcgi index indexphp fastcgi param script filename document rootfastcgi script name include fastcgi params i will be asked for usernamepassword when requesting the phpscripts in that adminfolder but the phpscripts will always be downloaded instead of executed via fastcgiwhat am i doing wrongedit on my local machine everything works fine with this configuration o0edit btw php is working outside the adminfolder with the same fastcgioptionsedit omg the sites config was stored at etcnginxsitesavailablemysite and etcnginxsitesenabled contained a symlink to the mysitefile since some time changing the mysitefile had no effect eg changing all locations to deny all had no effect the files were sent without a problemso i removed the symlink and restarted the server then i created the symlink again restarted the server and everything works as expected can someone explain the odd behaviourgest regardsbiggie,['php'] +114545,template function as a template argument i have just got confused how to implement something in a generic way in c it is a bit convoluted so let me explain step by stepconsider such codevoid aint do somethingvoid bint something elsevoid function1 a123 a456void function2 b123 b456void test function1 function2it is easily noticable that function1 and function2 do the same with the only different part being the internal functiontherefore i want to make function generic to avoid code redundancy i can do it using function pointers or templates let me choose the latter for now my thinking is that it is better since the compiler will surely be able to inline the functions am i correct can compilers still inline the calls if they are made via function pointers this is a sidequestionok back to the original point a solution with templatesvoid aint do somethingvoid bint something elsetemplatevoid paramint void function param123 param456void test functiona functionball ok but i am running into a problem can i still do that if a and b are generics themselvestemplatetypename tvoid at t do somethingtemplatetypename tvoid bt t something elsetemplate param void function paramsometypesomeobj paramanothertypesomeotherobjvoid test functiona functionbi know that a template parameter can be one ofa type a template typea value of a typenone of those seems to cover my situation my main question is hence how do i solve that ie define function in the last example yes function pointers seem to be a workaround in this exact case provided they can also be inlined but i am looking for a general solution for this class of problems,['c++'] +114548,is it possible to port an ios app to windows using gnustep for learning purposes i am an objectivec newbie who still does not have a mac but still i want to practice the language i heard that in the nonmac world gnustep offers a good alternative to cocoa and can be used as a lerning tool for new objectivec developers my question is since gnustep ports a lot of the cocoa classes what are the chances of me porting an ios game its development framework i am talking about canabalt for ios which is based on the ios version of the flixel framework i would like to know whether there is even the slightest chance of being able to port run this game on windows using gnustep remember that this is entirely for educational purposes so please do not look for any practical value in it besides me getting better with objc i guess that it should be technically possible in general what are the chances of porting any ios app to win using gnustep,"['iphone', 'objective-c', 'ios']" +114552,free font and color chooser for wpf i am looking for some good font chooser and color chooser components for wpf i was trying to find some standard solutions like winforms components but there seems to be none i wonder whyit does not have to be perfect someshing from code project would be enought but i would prefer good looking intuitivetouse componentsthank you,"['c#', '.net']" +114567,java ee 6 and alternatives i am a java se developer but i have rich webbackground php perlcgi and so on and now i am starting new project it will have web interface spaghetti business logic relational database as storage and connections to other services i do it from the scratchmy colleagues told me to use spring spring security and strutsi look briefly at java ee 6 spec and found that it covers almost all aspects of enterprise application i asked my colleagues why do they need spring and struts but looks like they use technologies simply because they are familiar with them and not familiar with classic java ee 6 stackso my question is what is bad about java ee 6why do i need spring if there are jndi lookups it will take a day or two to create fake initialcontext for unittests and that is all i stand with out of external tools like springwhy do i need springsecurity if there is a security built in servlets speci can map any request to any servlet using webxml no strutsxml is needed i can use servletfilters instead of struts interceptors there is rmi so i do not need springremote and so onwhy should i bother my self with all that fancy stuff if there is java ee 6i really want to find situation when java ee 6 is not enoughdo you have anythanks,['java'] +114577,spawn a new thread to open a new window and close it from a different thread right now i have c code to spawn a new window in a different thread this works but as soon as the new spawned window opens it closes and the thread ends how would i make it so the new spawned window can be closed from the first threadhere is a tree of how the spawning currently worksmain threaduses a function in the main thread to start another function in a separate thread to open w window causing the window to use that threadbasically i just want the two windows to each have their own thread and be able to control the spawned secondary window from the first window thread,['c#'] +114580,django template convert a python list into a javascript object i am working on a django python website i have a page where i want to thisplay a table of search results the list of results is passed in to the template as normali also want to make this list of objects accessible to the javascript codemy first solution was just create another view that returned json format but each page load required calling the query twice so then i tried only downloading the data using the json view and printing the table using javascriptbut this is also not desirable as now the presentation layer is mixed into the javascript codeis there a way to create a javascript object from the python list as the page is rendered,"['javascript', 'python']" +114592,whats the syntactically proper way to declare a c struct i have seen c structs declared several different ways before why is that and what if anything does each do differentfor examplestruct foo short a int b float ctypedef struct short d int e float f bartypedef struct baz short a int b float c bazint main int argc char const argv struct foo a bar b baz c return 0,['c'] +114595,enumerating combinations in a thistributed manner i have a problem where i must analyse 500c5 combinations 255244687600 of something thistributing it over a 10node cluster where each cluster processes roughly 106 combinations per second means the job will be complete in about seven hoursthe problem i have is thistributing the 255244687600 combinations over the 10 nodes i would like to present each node with 25524468760 however the algorithms i am using can only produce the combinations sequentially i would like to be able to pass the set of elements and a range of combination indicies for example 0107 10720 107 etc and have the nodes themselves figure out the combinationsthe algorithms i am using at the moment are from the followingstack overflow question efficiently computing vector combinationsi have considered using a master node that enumerates each of the combinations and sends work to each of the nodes however the overhead incurred in iterating the combinations from a single node and communicating back and forth work is enormous and it will subsequently lead to the master node becoming the bottleneckis there any good combination iterating algorithms geared up for efficientoptimal thistributed enumeration,['c++'] +114597,how do i access the supersuper class in java miniexample inside in the example below how can i access from c the method method of the class aclass a public void method class b extends a public void method class c extends b public void method void test method cmethod supermethod bmethod csupermethod bmethod bsupermethod error what i want to know the error i am getting is no enclosing instance of the type b is accessible in scopeanswer no this is not possible java does not allow it similar question,['java'] +114598,what is the difference between solr vs websolr i am researching on full text search engine and i installed sunspot which makes use of apache solr library we host on heroku and they offer a websolr addon which confused me can i use sunspot without websolr on herokualso can anyone let me know where to find the websolr api key when i add the heroku websolr addon,['ruby-on-rails'] +114601,curved lines using only html andor css i need to add curved lines connecting nodes of a diagram in html i want to create them using only html andor css i am ok with css3 even if not all browsers support the feature i need particularly do not care so much about ie8 and below here are solutions i could use with reasons against themcanvas or svg do not like it because i have to then deal with browser differences and not sure of performance when i have hundreds maybe thousands of these objects floating between my nice nodesimage i would need a ridiculous number of images to deal with all the possible curved lines and an image does not scale nicely at all when zooming in and outdiv with a css borderradius and another div that covers the portion of the lines we do not want not worried about ie8 and below not supporting this but this is an ugly hack where i cannot have the resulting curved lines over anything like a background or other lines overlapping can iwhat options am i missing is it possible to have a div with a borderradius that is visible for only 1 corner and work on all browsers except ie8 and below,['css'] +114603,mvc how much code should be in a view i am a webdeveloper and i was a coder for a long time but i have never used a pure mvc architecture now i started own project and decided to make htmlcss by myself and hire a coder we chose the popular phpmvcframeworkfirst steps are done some pages are coded and after looking to the result i have got the question how much code is there should be in templates viewfor example here is a template filephp thisloadviewheader php thisloadviewbanner div iditemsphpfori0 icountmain i echo div classitem div classnamemaininamediv ifmainiicq else echo div classphonemainiphonediv echo divdivphp thisloadviewfooter do you think there is too much code in this template or it is normal,['php'] +114620,hiding options of a select with jquery okay let us start with an examplekeep in mind this is only an exampleselect id selection1 option value 1 id 1number 1option option value 2 id 2number 2option option value 3 id 3number 3optionselectnow from here we have a dropdown with 3 optionswhat i want to do now is to hide an option adding style thisplaynone will not helpthe option would not appear in the dropdownlist but using the arrow keys you can still select itessentially it does exactly what the code says it is not thisplayed and it stops therea jquery function of 1hide will not workplus i do not only want to hide the option i want to completely remove itany possibility on doing sodo i have to use parentsiblingchild elements if so i am still not sure howany help on this would be greatly appreciated thanks another question it is relatedok so i found out that there is a remove available in jquery works wellbut what if i want to bring it backifcondition thisremove i can loops this should not be complicatedbut the thing of which i am trying to do is thismaximum capacity of class input field hereselect room dropdown herewhat i would like for it to do is to update is dropdown using a function such as change or keyupi could create the dropdown only after something is typed at a change or a keyup execute the dropdown accordinglybut what i am doing is thisroomarray mysql queryselect from select case when type classroom then 1 when type computer laboratory then 2 when type lecture hall then 3 when type auditorium then 4 end as classtypevalue from rooms t order by classtypevalue maxppl roomid echo select id roomwhile rooms mysql fetch arrayroomarray option valuephp echo roomsroomid idphp echo roomsroomid php echo roomstype echo nbsp echo roomsroomid echo nbsp echo roomsmaxppl echo option php echo selectyes i know it is very messyi plan to change it later onbut the issue now is this can i toggle the removal of the options according to what has been typedis it possible to do so with a dropdown made from a loop because i sure as hell cannot keep executing sql queries or is that even an option because if it is possible i still think it is a bad one,['jquery'] +114647,compare columns where one is similar to part of another i am trying to write a select statement where i can see if one column is like part of anothertblnames id fullname firstname1 mr john doe ceo john2 mr jake doe exec jake3 mrs betty smith chair jillthe query should return3 mrsbetty smith chair jillhowever mine just returns every row in the tableselect id fullname firstnamefrom tblnameswhere firstname not like fullnameany ideas,['sql'] +114656,this in function inside prototype function i basically have an object extended with a function through its prototype inside that function another function exists however when using this in this nested function it does not seem to refer to the object but the functionfor examplevar sampleobject function thisfoo 123sampleobjectprototypegetfoo function var nested function return thisfoo return nestedvar test new sampleobjectwindowalerttestgetfoo undefinedthe thisfoo does not refer to the 123 value but is undefined as this refers to the nested function in which no foo exists how can i access the 123 value from the nested functionthanks,['javascript'] +114686,toggle input thisabled attribute using jquery here is my codeproduct1 checkboxclickfunction this closesttr find the parent row findinputtypetext find text elements in that row attrthisabledfalsetoggleclassthisabled enable them end go back to the row siblings get its siblings findinputtypetext find text elements in those rows attrthisabledtrueremoveclassthisabled thisable themhow do i toggle attrthisabledfalsei cannot seem to find it on google,['jquery'] +114692,run a customized version of a rails application heres our basic requirementswe have a base rails application which is being actively maintainedwe want to offer a customized version of this app given thatservers must reside in our customers premise and run on a different domainthere is a specific logging instrumentation for their own monitoring in the datacenterto do that i can see several options to achieve that goalgit branchrailsenginerailsapplicationthe most obvious answer would be git branch for full flexibilityhowever i am not sure if it is a good idea because the code base is largely shared and the mainline has a lot more activities catching up with rebase merge could be just extra hasslewe want to decouple the original and the customized versions as far as possible in other words we want to have as less often conflicts as possible between the original and the customizedrailsengine or railsapplication seemed like a close idea i am not familiar with rails engines but i do not understand how to have ourappapplication and ourcustomizedappapplication in one place and switch between them globally and dynamicallyprobably it would be nice to havecustom initializers controllers and views in a separate directory to override or patch the originalability to specify which app the original or the customized to boot by an environment variable like rails appseparate config files like so configdatabaseyml to be configcustomer1databaseymlability to use the same deployrb for capistrano probably with configserversyml and configcustomer1serversyml to define roles and ipsis there practices conventions for our requirements any adviceour apps run on ruby 192 rails 303updatewe started it as a git branch we created a rake task to generate a file at configbranch that includes text like master or customized and applicationrb reads it upon bootstrap configs like databaseyml or serversyml now live in configmainline or configcustomized and applicationrb handles them accordinglyconfigpathsconfigdatabase configbranchdatabaseymlnot perfect but good enough for now i will update when we find a better way to do this,['ruby-on-rails'] +114725,how to extract a floating number from a string in python i have a number of strings similar to current level 134 db and i would like to extract just the floating point number i say floating and not decimal as it is sometimes whole can regex do this or is there a better way,['python'] +114736,android xml what is the purpose of the star in the id string in some sources i see such declarationsitem androidididmenu thisplay groups androidiconandroiddrawableic menu allfriends androidtitlestringmenu thisplaygroup notice the androidit seems to give access to internal resources but would like to know for surealso curious if it is safe to build application with such declarations using android 22 sdk and run it on 15,['android'] +114740,set time zone offset in ruby the default time zone offset in ruby is apparently 0800 i want to set mine to 0500 how do i do this,['ruby'] +114763,using methodinfogetcurrentmethod in anonymous methods public static void mainstring args action a consolewritelinemethodinfogetcurrentmethodname athis code will return an obscure string like so mainb 0is there a way of ignoring the anonymous methods and get a more readable method name,"['c#', '.net']" +114788,keeping all libraries in the arduino sketch directory i know that you are supposed to place any external libraries under the libraries folder of the arduino install directory but i have a project that uses several libraries that i have created for the project and mainly to keep all that code self contained and out of the main pde file however i have tried to place the libraries in the same directory as the main pde file so that i can more easily keep everything synced up in subversion i work on this on multiple computers and i do not want to have to keep going back and syncing up the libraries separately also just for the sake of being able to easily zip of the sketch folder and know that it contains everything it needsi have tried adding the header files to the sketch as a new tab but that does not seem to work at all do not even care if they should up in the arduino idei have also tried adding the libraries to the sketch directory in subdirectories what i would greatly prefer and then linking to them asinclude mylibmylibhandinclude mylibmylibhbut both of these result in file not found errorsis this possible and if so how do i include them in the main file for building preferably in their own subdirectories,"['c++', 'c']" +114796,mysql equivalent of decode function in oracle i am trying to find an equivalent of decode function in mysql it works like thisselect name decodeage 13thirteen14fourteen15fifteen16sixteen 17seventeen18eighteen19nineteen adult as agebracketfrom personthe decode function will compare value of column age with 13 14 15 and return appropriate string value thirteen fourteen and if it matches with nothing then default value of adult will be returnedany ideas which function in mysql can do this job thanksclarification i agree using case is one way of achieving desired result but i am rather looking for a function because of performance and other reasons,"['sql', 'mysql']" +114816,c why the assignment operator should return a const ref in order to avoid abc i am reading a book about c and more precisely about the operator overloadingthe example is the followingconst array arrayoperatorconst array right check selfassignment if not self assignment do the copyingreturn this enables xyzthe explanation provided by the book about returning const ref instead of ref is to avoid assignments such as xyz i do not understand why we should avoid this i understand that xy is evaluated first in this example and since it returns a const reference the z part cannot be executed but why,['c++'] +114823,how to return a variable from a javascript function into html body i am still new to javascript and i am trying to get a function to return a variable using html javascript basically the function should just return whichever radio button that the user clicks on although at the moment i do not see anything being returned at allthe function is here script typetextjavascriptfunction getselecteditem var chosen len documentf1r1length for i 0 i len i if documentf1r1ichecked chosen documentf1r1ivalue return chosenscriptand then in the html section i have these radio buttons and my attempt to get the variable chosen output to the screen form name f1input type radio name r1 value on onclickgetselecteditemon input type radio name r1 value off onclick getselecteditemoform script type textjavascriptdocumentwritechosenscriptat the moment nothing seems to be getting returned from the function although if i output the variable chosen inside the function then it is working correctlythanks in advance,"['javascript', 'html']" +114832,rails browser detection methods hey everyone i was wondering what methods are standard within the industry to do browser detection in rails is there a gem library or sample code somewhere that can help determine the browser and apply a class or id to the body element of the xhtml thanks i am just wondering what everyone uses and whether there is accepted method of doing thisi know that we can get the useragent and parse that string but i am not sure if that is that is an acceptable way to do browser detectionalso i am not trying to debate feature detection here i have read multiple answers for that on stackoverflow all i am asking for is what you guys have done updateso thanks to faunzy on github i have sort of understand a bit about checking the user agent in rails but still not sure if this is the best way to go about it in rails 3 but here is what i have gotten so fardef users browseruser agent requestenvhttp user agentdowncase users browser begin if user agentindexmsie user agentindexopera user agentindexwebtv ieuser agentuser agentindexmsie5chr elsif user agentindexgecko gecko elsif user agentindexopera opera elsif user agentindexkonqueror konqueror elsif user agentindexipod ipod elsif user agentindexipad ipad elsif user agentindexiphone iphone elsif user agentindexchrome chrome elsif user agentindexapplewebkit safari elsif user agentindexgooglebot googlebot elsif user agentindexmsnbot msnbot elsif user agentindexyahoo slurp yahoobot everything thinks it is mozilla so this goes last elsif user agentindexmozilla gecko else unknown end end return users browserend,"['ruby-on-rails', 'ruby']" +114834,jquery last focused element i have a basic login form which uses ajax to login users if the details are incorrect text is thisplayed showing login has failed when this is shown the last textbox the user entered text in loses focus is it possible to set focus to the last textbox which the user was on before pressing submitpressing enterloginclickfunction e epreventdefault ajax type post datatype text url loginphp data username usernameval password passwordval cache false success functionreply if replyindexofsuccess 0 locationreload else loginresulthtmllogin failed set focus here any suggestions thanks,['jquery'] +114853,class library cannot find membershipuser i have added a class library project to my applicationin one of my classes i need to use the membershipuser class but the project cannot find it i have added references to systemweb systemwebsecurity and systemsecurityprincipali am not sure what the problem is has anyone run into this,"['c#', 'asp.net']" +114869,javabeans and introspection messed up on boolean and indexed properties a former colleague of mine started a thiscussion half an hour ago about javabeans and why they did not quite work the way he wants in jsf the particular case is about boolean properties 1 for a boolean property named isurl eclipse generates thisprivate boolean isurlpublic boolean isurl public boolean seturlboolean url but this does not work in jsf he made it work by adding public boolean getisurl the implementation might be buggy so let us make sure whos right by using the introspection apibeaninfo info introspectorgetbeaninfoclasstestclassfor propertydescriptor pd infogetpropertydescriptors systemoutprintlnpdgetname pdgetreadmethod pdgetwritemethodfor the above code this prints both methods ie eclipse is right jsf is wrong but that sounded suspicious to me since the specification does not mention anything about the double isbut while looking through the spec i saw something i have never used the so called indexed properties you can have private string bar and then public string getbarint idx so2 i tried that with the introspector and it did not find a read method for bar the result from the above code was bar null null so i came to think now the introspector does not follow the spec perhaps it did not follow it in the previous case and ultimately jsf is right in fact indexed properties can make so that there are two read methods for a given property and that is not possible with the propertydescriptor class of the introspection apiwhat does this lead us to we have a possibly broken api that does not conform to the spec which leads to other implementations of the spec jsf uses a custom one obviously which leads to further misunderstandings and confusionsa sidenote for something that bothered me in the javabeans spec they call the naming conventions for the methods design patterns this sounds wrong to meso now onto the questionsis the javabeans spec clearis the introspection api correctis a new javabeans specification needed at least to clarify the behaviour of booleans that is subjective to an extentupdate it appears the jsf usage is beanisurl rathern than beanurl which makes perfects sense not to work with isurl accessorps jdk 160 20 jsf 12 myfaces,['java'] +114878,rails how to make a conditional radio button checked given a radio button like so radio button tag permissionrole id 2 how can i make the radio buttons checked status condition to only be checked if permissionrole idnil or if permissionrole id 2i tried radio button tag permissionrole id 2 permissionrole idnil checked true checked false thanks,['ruby-on-rails'] +114884,efficient way of iterating over true bits in stdbitset is there a way of iterating over a possibly huge stdbitset that is linear in the number of bits that are set to true i want to prevent having to check every single position in the bitset the iteration should successively return the indices of each bit that is set to true,['c++'] +114891,python string formatting reference one argument multiple times if i have a string like0 1 1 foo barand i wantfoo bar barwhat do the replacement tokens have to be i know that my example above is incorrect i am just trying to express my goal,['python'] +114893,table header to stay fixed at the top when user scrolls it out of view with jquery i am trying to design an html table where the header will stay at the top of the page when and only when the user scrolls it out of view for example the table may be 500 pixels down from the page how do i make it so that if the user scrolls the header out of view browser detects its no longer in the windows view somehow it will stay put at the top anyone can give me a javascript solution to thistable thead tr thcol1th thcol2th thcol3th tr thead tbody tr tdinfotd tdinfotd tdinfotd tr tr tdinfotd tdinfotd tdinfotd tr tr tdinfotd tdinfotd tdinfotd tr tbodytableso in the above example i want the thead to scroll with the page if it goes out of viewimportant i am not looking for a solution where the tbody will have a scrollbar overflowauto,"['jquery', 'html']" +114894,is it possible for parent window to notice if child window has been closed i have parent window opener and child popup parent opens popup child let us say in parent page i have js function helloin order for child to call parents hello when the child window is closed and also pass an argument i can dowindowclosewindowopenerhellosomeargumentthis will close the window and also call parents hellobut what if i do not want to have the code windowopenerhello in child page i mean i want the code to be in parent page onlyone thing i can think of issomewhat parent knows when the child is closed event listenr not sure in js but in such case how to receive the argument ie some data back from the child,['javascript'] +114898,itertools product speed up i use itertoolsproduct to generate all possible variations of 4 elements of length 13 the 4 and 13 can be arbitrary but as it is i get 413 results which is a lot i need the result as a numpy array and currently do the following c itproduct11npcomplex01 npcomplex01 repeatlength sendbuf nparraylistcwith some simple profiling code shoved in between it looks like the first line is pretty much instantaneous whereas the conversion to a list and then numpy array takes about 3 hours is there a way to make this quicker it is probably something really obvious that i am overlookingthanks,['python'] +114904,jquery eq vs get i am new to jquery and i am wondering what the difference is between jquerys get and eq functions i may misunderstand what the get function does but i thought it odd that i could not call a function on the returned on the returned element in the same linedoes not workie h2get0fadeinslowworksh2eq0fadeinslow,['jquery'] +114906,setonitemclicklistener on custom listview i have a custom listview this listview contains 1 image and 6 textviews to retrieve the value i have created a setonitemclicklistener whenever i click on the listview how could i actually retrieve all the data from the 6 textviews,['android'] +114915,remote service vs local service dear alli am a newbiew to android i had read a lot of articles about android service but i am not clearly understanding what defferent between local service and remote service except for local service run in the same process as the lunching activity remote services run in their own process the busy coders guide to android development mark l murphy please shows me what different between local service and remote servicewhats the advantagethisadvantage of using local service whats the advantagethisadvantage of using remote servicethanks best regardsdai son,['android'] +114931,financial python library i am looking for a python library that provides simple set of financial calculations such as macd emas and other indicators i have been looking around for it but either all projects that were trying to do it are dead or nonexistent is there a library like that in the existencethanks,['python'] +114942,net application auto restart when configuration changes i have to completely restart application when any part of it is configuration changes iis does it is best to watch for configuration in aspnet apps but how do i to restart such applications as console or servicesis it ok to monitor configuration file changes with filesystemwatcher and start new instance of application closing current onesomething like var file new fileinfoappdomaincurrentdomainsetupinformationconfigurationfile var watcher new filesystemwatchfiledirectoryfullname filter notifyfilter notifyfilterlastwrite watcherchanged procestart current process shutdown watcherenableraisingevents true,['.net'] +114958,generating sha256 in iphoneobjective c how to create a sha256 of a string in iphoneobjective csha256 in objectivec for iphonei have read thisbut i am not able to understand thisi want to create output similar to php funcation as followshash hash hmacsha256 implode hash parameters api keywhere hash parameters is the array of argumentscan you write this as a method which will take the input stringand what will be the output of method nsdata or nsstringi have to create a request with thisso in the request objecttherequest sethttpbodyrequestbodywhat should be the type of requestbody,['iphone'] +114982,write reliably to same file from different processes i did create a small c tracing solution which works very well within one process all is well but when i open the output file from diferent processes the data gets not correctly written i did open the file with file share write to be able to write to the file when it is already open then i did create a named mutex to ensure proper synchronisation between processes but it appears that this is not enough according to the msdn this does work within one process but not between different processes next i tried to call flushfilebuffers after every write while the mutex was still held but data was still thistorted like thisthe format is time process idthread id method enterleaveseverity namespacemethod and then the message text 102942994 74482236 dll2testfndll2 l1 duration 0094s102943040 74482236 dll2dllmain l1102943134 74482236 info dll2dllmain l1 process detach102943181 74482236 dll2dllmain l1 duration 0141s dll2dllmain l1 102942681 74482236 info dll1dllmain l1 process attach102942728 74482236 dll1dllmain l1 102942744 221655102942775 74482236 dll1testfndll1 102102942822 74482236 info dll1testfndll1 102942837 22165576102942853 74482236 dll1testfndll1 l1102942884 22165576102943306 74482236 dll1dllmain l1102943353 74482236 info dll1dllmain l1 process detach102943400 74482236 dll1dllmain l1 duration 0094si have looked at file flag no buffering but it has severe limitations and it seems not easy to use does anybody know the right way to write synchronized to the same file without thistoriting the outputyours alois kraus,"['c++', 'c']" +114987,javascript how to detect if a word is highlighted i am writing a firefox addon that is triggered whenever a word is highlighted however i need a script that detects when a word is highlighted and i am stuck an example would be nytimescom when youre reading an article and you highlight a word the reference icon pops up however the nytimescom script is super complex i am 16 and not much of a programmer so that is definitely way out of my league,['javascript'] +114996,how to tell jaxb that order of elements does not matter is it possible to tell jaxb to ignore the order of elements so that the generate xsd will contain allelements instead of sequenceelements,['java'] +115014,is there any way to thisable compiler optimisation for a specific line of code is there any way to thisable compiler optimisation for a specific line of code in visual studio,['c++'] +115016,how to select a node of treeview programatically in c used treeviewselectednode to select a child node how to invoke treeviewafterselect event when a node is selected programaticallythistreeview1selectednode thistreeview1nodes0nodes0nodes0nodes0 if thistreeview1nodes0nodes0nodes0nodes0isselected messageboxshownode is selected,['c#'] +115023,php get and set magic methods unless i am completely mistaken the get and set methods are supposed to allow overloading of the get and setfor example the following statements should invoke the get methodecho foobarvar foobarand the following should use the set methodfoobar testthis was not working in my code and is reproducible with this simple exampleclass foo public bar public function getname echo getname return thisname public function setname value echo setname to value thisname value foo new fooecho foobarfoobar testecho foobarthis only results intestputting some die calls in there shows that it is not hitting it at allfor now i just said screw it and am manually using get where it is needed for now but that is not very dynamic and requires knowledge that the overloaded code is in fact not being called unless specifically called i would like to know if this is either not supposed to function the way i have understood that it should or why this is not workingthis is running on php 533,['php'] +115034,what is the cause for the failure jarsigner attempt to rename file to fileorg failed when signing jars with ant i am getting the error signjar jarsigner attempt to rename cworkspaceline editorlibiconjar to cworkspaceline editorlibiconjarorig failedwhen attempting to self sign a set of jars with ant inside eclipse the ant build has worked fine in this project and similar code in other projects i made some small changes to code and tried to rebuild and keep getting this errorhere is the related ant targettarget namesign dependsjar descriptionsigns jars genkey keystoremykeystore1 aliassomething storepasomethingpass dnamecnclassification ounapa ogpc cus signjar keystoremykeystore1 aliassomething storepasomethingpass fileset filewebdirjarname fileset dirlibdir include namejar fileset signjar targeti deleted the project and pulled it down again from our repository so it has the same default project settings as other projects that this part does not fail i looked at the jar in question and it was not readonly i changed the name and the next alphabetical jar file also failed there is no program running that is accessing the jars in this folder any suggestions as to cause,['java'] +115046,what does documentform mean in javascript in javascript what is the meaning of the identifiers documentcookie documentforms and the value field i have trouble understanding the use of the below syntax examplevar xdocumentformsmyformemailvaluebest wishesi 12i,['javascript'] +115053,how to grant modify phone state permission for apps ran on gingerbread i write an application that attempts to modify phone call state it works well on android 22 or less but throw an exception on android 23 because of the lack of permission on androidpermissionmodify phone state permission i declared this permission on androidmanifestxml any idea below is the exception log0115 091423210 errorandroidruntime404 fatal exception main0115 091423210 errorandroidruntime404 javalangruntimeexception unable to start receiver testphonereceiver javalangsecurityexception neither user 10031 nor current process has androidpermissionmodify phone state0115 091423210 errorandroidruntime404 at androidappactivitythreadhandlereceiveractivitythreadjava17800115 091423210 errorandroidruntime404 at androidappactivitythreadaccess2400activitythreadjava1170115 091423210 errorandroidruntime404 at androidappactivitythreadhhandlemessageactivitythreadjava9780115 091423210 errorandroidruntime404 at androidoshandlerthispatchmessagehandlerjava990115 091423210 errorandroidruntime404 at androidoslooperlooplooperjava1230115 091423210 errorandroidruntime404 at androidappactivitythreadmainactivitythreadjava36470115 091423210 errorandroidruntime404 at javalangreflectmethodinvokenativenative method0115 091423210 errorandroidruntime404 at javalangreflectmethodinvokemethodjava5070115 091423210 errorandroidruntime404 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava8390115 091423210 errorandroidruntime404 at comandroidinternaloszygoteinitmainzygoteinitjava5970115 091423210 errorandroidruntime404 at dalviksystemnativestartmainnative method,['android'] +115054,placing a custom view based uibarbuttonitem in the navigation bar without default horizontal padding how do i remove the horizontal padding to the left and right of custom left and right uinavigationbar items there seems to be 10 points of padding that ios sets by defaulti am customizing left and right navigation bar buttons i have given up on trying to set my own backbuttonitem so i am just using the leftbarbuttonitemin either case left or right pressing these custom buttons indicates that apple seems to preserve some padding to the left of the leftbarbuttonitem and to the right of the rightbarbuttonitem regardless of how wide i make the custom background and image properties of the uibutton i place inside the leftright bar button item as its custom viewsince uibarbuttonitems have no frame i can access i cannot position them within their superview like i can normal uiviewsany suggestions on how to remove this default padding see screen shot attached to see the bit i am trying to reduce to a zero width in the screen shot the plus icon appears shifted to the right because i gave it an inset but the highlighted background image also presumably using that inset is getting clipped on its right sidesee image at for reference heres how i am creating my custom uibarbuttonitem in this case it is the right button uibarbuttonitem customaddbuttonitemwithtargetidtarget actionselaction uibutton custombuttonview uibutton buttonwithtypeuibuttontypecustom custombuttonviewframe cgrectmake00f 00f 450f 440f custombuttonview setbackgroundimage uiimage imagenamedbgnavbarbuttonoutsiderightnormalpng forstateuicontrolstatenormal custombuttonview setbackgroundimage uiimage imagenamedbgnavbarbuttonoutsiderighthighlightedpng forstateuicontrolstatehighlighted custombuttonview setimage uiimage imagenamedbgnavbarbuttonaddnormalpng forstateuicontrolstatenormal custombuttonview setimage uiimage imagenamedbgnavbarbuttonaddhighlightedpng forstateuicontrolstatehighlighted custombuttonview addtargettarget actionaction forcontroleventsuicontroleventtouchupinside uibarbuttonitem custombuttonitem uibarbuttonitem alloc initwithcustomviewcustombuttonview autorelease custombuttonview setimageedgeinsetsuiedgeinsetsmake00f 100f 00f 00f custombuttonitemimageinsets uiedgeinsetsmake00f 100f 00f 00f return custombuttonitem,"['iphone', 'ios']" +115066,storing datetime utc vs storing datetimeoffset i usually have an interceptor that right before readingwriting fromto the database does datetime conversion from utc to localtime and from localtime to utc so i can use datetimenow derivations and comparisions throughout the system without worrying about timezonesregarding serialization and moving data between computers there is no need to bother as the datetime is always utcshould i continue storing my dates sql 2008 datetime in utc format or should i instead store it using datetimeoffset sql 2008 datetimeoffsetutc dates in the database datetime type have been working and known for so long why change it what are the advantagesi have already looked into articles like this one but i am not 100 convinced though any thoughts,['sql'] +115073,why is a c reference considered safer than a pointer when the c compiler generates very similar assembler code for a reference and pointer why is using references preferred and considered safer compared to pointersi did see difference between pointer variable and reference variable in c which thiscusses the differences between themedit1i was looking at the assembler code generated by g for this small programint mainint argc char argv int a int ra a int pa a,['c++'] +115077,how to order by with union is it possible to order when the data is come from many select and union it togethersuch asselect idnameagefrom studentwhere age 15unionselect idnameagefrom studentwhere name like ahow can i order this query by namesome said you can query look like thisselect idnameagefrom studentwhere age 15 or name like aorder by namebut in this case i just ignore that solutionthank you in advance,['sql'] +115080,using rx to block and possibly timeout on an asynchronous operation i am trying to rewrite some code using reactive extensions for net but i need some guidance on how to achieve my goali have a class that encapsulates some asynchronous behavior in a low level library think something that either reads or writes the network when the class is started it will try to connect to the environment and when succesful it will signal this back by calling from a worker threadi want to turn this asynchronous behavior into a synchronous call and i have created a greatly simplified example below on how that can be achievedmanualresetevent readyevent new manualreseteventfalsepublic void starttimespan timeout simulate a background process threadpoolqueueuserworkitem asyncstarttimespanfromseconds1 wait for startup to complete if thisreadyeventwaitonetimeout throw new timeoutexceptionvoid asyncstarttimespan delay threadsleepdelay simulate startup delay thisreadyeventsetrunning asyncstart on a worker thread is just a way to simulate the asynchronous behavior of the library and is not part of my real code where the low level library supplies the thread and calls my code on a callbacknotice that the start method will throw a timeoutexception if start has not completed within the timeout intervali want to rewrite this code to use rx here is my first attemptsubjectunit readysubject new subjectunitpublic void starttimespan timeout threadpoolqueueuserworkitem asyncstarttimespanfromseconds1 point a see below thisreadysubjecttimeouttimeoutfirstvoid asyncstarttimespan delay threadsleepdelay thisreadysubjectonnextnew unitthis is a decent attempt but unfortunately it contains a race condition if the startup completes fast eg if delay is 0 and if there is an additonal delay at point a then onnext will be called on readysubject before first has executed in essence the iobservable i am applying timeout and first never sees that startup has completed and a timeoutexception will be thrown insteadit seems that observabledefer has been created to handle problems like this here is slightly more complex attempt to use rxsubjectunit readysubject new subjectunitvoid starttimespan timeout var ready observabledefer threadpoolqueueuserworkitem asyncstarttimespanfromseconds1 point b see below return thisreadysubjectasobservable readytimeouttimeoutfirstvoid asyncstarttimespan delay threadsleepdelay thisreadysubjectonnextnew unitnow the asynchronous operation is not started immediately but only when the iobservable is being used unfortunately there is still a race condition but this time at point b if the asynchronous operation started calls onnext before the defer lambda returns it is still lost and a timeoutexception will be thrown by timeouti know i can use operators like replay to buffer events but my initial example without rx does not use any kind of buffering is there a way for me to use rx to solve my problem without race conditions in essence starting the asynchronous operation only after the iobservable has been connected to in this case timeout and firstbased on paul bettss answer here is working solutionvoid starttimespan timeout var readysubject new asyncsubjectunit threadpoolqueueuserworkitem asyncstartreadysubject timespanfromseconds1 point c see below readysubjecttimeouttimeoutfirstvoid asyncstartisubjectunit readysubject timespan delay threadsleepdelay readysubjectonnextnew unit readysubjectoncompletedthe interesting part is when there is a delay at point c that is longer than the time it takes for asyncstart to complete asyncsubject retains the last notification sent and timeout and first will still perform as expected,"['c#', '.net']" +115083,what mutationtesting frameworks exist for cc mutation testing has been out there for a while now and it seems there are at least one or two commercial mutation testing frameworks for cc have you used them what are your experiences are there any open source alternatives,['c++'] +115090,do subclasses inherit private fields this is an interview questiondoes subclasses inherit private fieldsi answered no because we cannot access them using the normal oop way but the interviewer thinks that they are inherited because we can access such fields indirectly or using reflection and they still exist in the objectafter i came back i found the following quote in the javadocprivate members in a superclassa subclass does not inherit the private members of its parent classdo you know any arguments for the interviewers opinion,['java'] +115101,accessing the users request in a post save signal i have done the below post save signal in my project from djangodbmodelssignals import post savefrom djangocontribauthmodels import user core signals core signals will operate based on postdef after save handler attr audit objsender kwargs print userget profile if hasattrkwargsinstance audit obj if kwargscreated kwargsinstanceaudit objcreateoperationinsert operation byuseridsave else kwargsinstanceaudit objcreateoperationupdatesave connect the handler with the post save signal django 12post saveconnectafter save handler attr audit obj thispatch uidcoremodelsauditnewthe operation by column i want to get the user id and store it any idea how can do that,['python'] +115102,simplest way to achieve automatic notification of property change i know that there are solutions out there for implementing inotifypropertychanged but none of them are as simple as reference this library createadd this attribute done i am thinking aspectoriented programming here does anyone know of a really simple way to do this bonus points if the solution is free here are some relevant links none of which provide a simple enough answeraspect examples inotifypropertychanged via aspectslinfuinotifypropertychanged auto wiring or how to get rid of redundant codeinotifypropertychanged with unity interception aop,['.net'] +115105,webclientdownloadstring returns string with peculiar characters i have an issue with some content that we are downloading from the web for a screen scraping tool that i am buildingin the code below the string returned from the web client download string method returns some odd characters for the source download for a few not all web sitesi have recently added http headers as below previously the same code was called without the headers to the same effect i have not tried variations on the acceptcharset header i do not know much about text encoding other than the basicsthe characters or character sequences that i refer to area aa andathese characters are not seen when you use view source in a web browser what could be causing this and how can i rectify the problemstring urldata stringemptywebclient wc new webclient add headers to impersonate a web browser some web sites will not respond correctly without these headerswcheadersadduseragent mozilla50 windows u windows nt 61 engb rv19212 gecko20101026 firefox3612wcheadersaddaccept wcheadersaddacceptlanguage engbenq05wcheadersaddacceptcharset iso88591utf8q07q07urldata wcdownloadstringuri,"['c#', 'asp.net', '.net']" +115109,testing interactive python programs i would like to know which testing tools for python support the testing of interactive programs for example i have an application launched by python dummy programpy hi whats your name josephi would like to instrument joseph so i can emulate that interactive behaviour,['python'] +115119,can you register multiple modeladmins for a model alternatives say i have the django model classclass foomodelsmodel bar modelscharfield baz modelscharfieldand the modeladminsclass foo admin 1adminmodeladmin list thisplay idbarclass foo admin 2adminmodeladmin list thisplay idbazis there any way to register both modeladmins so that they show up under the django admin interfacei triedadminsiteregisterfoofoo admin 1adminsiteregisterfoofoo admin 2but i get the errorthe model foo is already registeredany suggestionsif not are there alternative ways to dynamically control the fields shown in the modeladmin change list view,['python'] +115123,convert to absolute value in objectivec how do i convert a negative number to an absolute value in objectivecie10 becomes10,['objective-c'] +115125,c how to get last time in foreach statement possible duplicateforeach loop determine which is the last iteration of the loop foreach datarowview row in orderedtabledefaultview iflasttime dosomethingorderedtable is a datatabledoes anyone know how to find out whether we are on the last foreach iteration please keep in mind that i do have duplicates in orderedtable,"['c#', '.net']" +115131,suggestions for dealing with ies terrible javascript dom accessing engine i am working on a site that has a page that can potentially become very long it can have in theory 10 rows of data in it then these rows could each have subrowsi am currently using a list sublist structure to represent the data because it is difficult to visualize subsets in tables the subset data is in a table though the problem is this in ie my hovering over the row styles tooltips and other javascripts are taking upwards of 5 seconds to fire the page hangs like crazy and is pretty much unuseable in ff chrome and safari it works just fine i do not need a whole bunch of stats saying ie is slow i know it is what i need is some suggestions theories ideas on how to combat the slownesome of the ideas i have had so farsome kind of paging mechanism but that gets tricky bc 1 it is a list not a table and 2 it is got sub sub lists and sub tables for those sub lists so wed need to somehow page based on the top level i think because we do not want to split the data up at all i guess that might be feasiblesome kind of mechanism that holds the content in a javascript array or object or soomething and does not add it to the dom until it is been scrolled to and takes it away when you scroll past it in theory this would be cool but i think it would be horrible to impliment something else entirelythanks in advance for any ideas i am probably going to try and put a bounty on this as soon as i am able to help inspire you editoh my i think i may have found part of the problem using dyna trace thanks pointy for reminding me about this tool i had forgotten about out the click event of one of my buttons seems to be firing an insane amount like 20 times and count something is clicking it automatically or something crazy like that weird thing is i do not have any javascripts that trigger that button click edit this does not seem to be an issue anymoreeditalso i do not think it is the complexity of my markup that is affecting the responsiveness of my scriptsi know if i could use just id selectors it would be best but i have optimized my selectors and qtips as much as possible with help from so in the past i have a button that is just on the page not nested in anything that the click handler takes 4 or 5 seconds to register it is not that the click action takes a long time it is just slow to notice that it is been clickededit i had 5 spans that were each nested in a span unnecessarily i unnested those and it seems to have cut the slowness in about 12 these 5 spans were repeated in every rowedit heres some of the relevant scriptsthe main button handlerfilterscheduledshiftsclickfunction var categoryid categoryidval var activityid activityidval var shiftstatusfilters getshiftstatusfilterids var dayofweekfilters getdayofweekfilters var startdatefilter getstartdatefilter var enddatefilter getstartendfilter var datatopost categoryid categoryid activityid activityid statuses shiftstatusfilters daysofweek dayofweekfilters startdate startdatefilter enddate enddatefilter var url urltofilterval listholderhtmlwebloading ajax url url data datatopost type post success function data documentgetelementbyidscheduledactivityshiftlistholderinnerhtml data error function v2errornoticev2textsharedgenericajaxerrormessage the getfilter functions are very simple functions that run in a few milliseconds nothing interesting or noteworthy happening in therethis bit attaches some of the behaviour that is very slowin other pages they react nice and quick on this page 23 seconds spaninfocarddiespaninfocardlivemouseover function var this this if thisdatatooltipattached var title if thisattrinfocardtitle title thisattrinfocardtitle else title thishtml thisqtip content text loading title title ajax url thisattrurltoget data data position at right middle my left top adjust screen flip hide fixed true when mouseout show solo true delay 500 ready true style classes uitooltiplight infocardtip widget true tip corner true width 15 height 15 thisdatatooltipattached true there are 2 different versions of this for 2 different classes one gets a single shift one gets the user s for a bunch of shifts as with other things once the function itself runs quick the ajax is fast the v2reloadscheduledactivitysection runs in about 50 ms nothing interesting in there divgetshiftuserarrowdieclickdivgetshiftuserarrowliveclick function var listisvisible thisattrlistisvisible var holder thisattrlistholder var activityholder toplevel0formatthisattractivityshiftid if listisvisible 1 v2reloadscheduledactivitysectionthis 1 else holderemptytogglehide thisremoveclassgetshiftuserarrowopen thisattrlistisvisible listisvisible 1 heres a bit of the html this is the for a day the main list has one of these for every day of the year or whatever range they pick there could be any number of sub lis in that list but it tends to be between 110 li classentityrow stylefontweightnormal div classtoplevelrow sectiondate1212011 120 am div clascheduledayheader onlyfloatleftinie7 stylewidth100marginbottom0pxfontweightnormal div classbuttons onlyfloatleftinie7 stylepaddingtop0px paddingbottom0pxmargintop0pxmarginbottom0px div classgetdayuserarrow onlyfloatleftinie7 listisvisible1 sectiondate1212011 120 am urlthisisnottherealurldiv divspan classcategorizednameholder onlyfloatleftinie7 stylethisplayinlineblock width380pxpaddingbottom2pxfriday january 21 2011span span classtimeholderspanstartspan span classtimeholderspanendspan span clastatusiconsstatusspan span claskinnycolumn glossaryme tooltipa numbermnspan span claskinnycolumn glossaryme tooltipa numbermxspan span claskinnycolumn glossaryme tooltipa numberbuspan span class skinnycolumn glossaryme tooltipa numberavspan span claskinnycolumn glossaryme tooltipassignedasspan span claskinnycolumn glossaryme tooltipa numbercospan div div clashiftlistholder sectiondate1212011 120 am ul clascheduledactivitiesfordaylist entitylist fancylist sublist li classentityrow activityshiftid4645 idlistitemfor4645 div classblueonhover scheduleshiftheader stylewidth100 div classbuttons onlyfloatleftinie7 stylepaddingtop0px paddingbottom0pxmargintop0pxmarginbottom0px div classgetshiftuserarrow onlyfloatleftinie7 listisvisible1 activityshiftid4645 urlsomeurl4645 sectiondate1212011 120 amdiv divspan classcategorizednameholder onlyfloatleftinie7 stylethisplayinlineblock width350pxpaddingbottom2pxspan classassignlink activityshiftid4645sometextspanspan span classtimeholderspan900 amspan span classtimeholderspan1230 pmspan div clastatusicons onlyfloatleftinie7 div classtipme legendme classtopicktheicon tooltipmin scheduled legendgroupid5 span classnothisplay3span div div classtipme legendme otherclasstopicktheicon tooltipunlocked legendgroupid5 span classnothisplay2span div div classtipme legendme anotherclasstopicktheicon tooltipdo not auto assign legendgroupid5 span classnothisplay1span div div classtipme legendme classtopicktheiconagain tooltipdo not autolock legendgroupid5 span classnothisplay1span div divspan classonlyfloatleftinie7span claskinnycolumn tipme contenttooltip tooltipa number1span span claskinnycolumn tipme contenttooltip tooltipa numberspan span claskinnycolumn tipme contenttooltip tooltipa number0span span claskinnycolumn tipme contenttooltip tooltipa number0span span claskinnycolumn tipme contenttooltip tooltipassigned2span span claskinnycolumn tipme contenttooltip tooltip a number0spanspan div div classuserlisthoder iduserlistholder4645 activityshiftid4645div li li classentityrow activityshiftid4129 idlistitemfor4129 div classblueonhover scheduleshiftheader stylewidth100 div classbuttons onlyfloatleftinie7 stylepaddingtop0px paddingbottom0pxmargintop0pxmarginbottom0px div classgetshiftuserarrow onlyfloatleftinie7 listisvisible1 activityshiftid4129 urlsomeurl4129 sectiondate1212011 120 amdiv divspan classcategorizednameholder onlyfloatleftinie7 stylethisplayinlineblock width350pxpaddingbottom2pxspan classassignlink activityshiftid4129blah bla blahspanspan span classtimeholderspan900 amspan span classtimeholderspan500 pmspan div clastatusicons onlyfloatleftinie7 div classtipme legendme classtopicktheicon tooltipmin scheduled legendgroupid5 span classnothisplay3span div div classtipme legendme otherclasstopicktheicon tooltipunlocked legendgroupid5 span classnothisplay2span div div classtipme legendme anotherclasstopicktheicon tooltipdo not auto assign legendgroupid5 span classnothisplay1span div div classtipme legendme otherclassforicon tooltipon availabilities legendgroupid5 span classnothisplay2span div divspan classonlyfloatleftinie7span claskinnycolumn tipme contenttooltip tooltipa number1span span claskinnycolumn tipme contenttooltip tooltipa number5span span claskinnycolumn tipme contenttooltip tooltipa number0span span claskinnycolumn tipme contenttooltip tooltipa number0span span claskinnycolumn tipme contenttooltip tooltipassigned5span span claskinnycolumn tipme contenttooltip tooltip a number0spanspan div div classuserlisthoder iduserlistholder4129 activityshiftid4129div li li classentityrow activityshiftid3534 idlistitemfor3534 div classblueonhover scheduleshiftheader stylewidth100 div classbuttons onlyfloatleftinie7 stylepaddingtop0px paddingbottom0pxmargintop0pxmarginbottom0px div classgetshiftuserarrow onlyfloatleftinie7 listisvisible1 activityshiftid3534 urlsomeurl3534 sectiondate1212011 120 amdiv divspan classcategorizednameholder onlyfloatleftinie7 stylethisplayinlineblock width350pxpaddingbottom2pxspan classassignlink activityshiftid3534even morespanspan span classtimeholderspan100 pmspan span classtimeholderspan430 pmspan div clastatusicons onlyfloatleftinie7 div classtipme legendme schedulingfullya numbericon tooltipmin a number legendgroupid5 span classnothisplay4span div div classtipme legendme lockedicon tooltiplocked legendgroupid5 span classnothisplay1span div div classtipme legendme classtopicktheiconagain tooltipauto assign legendgroupid5 span classnothisplay2span div div classtipme legendme otherclassforicon tooltipon assignments legendgroupid5 span classnothisplay3span div divspan classonlyfloatleftinie7span claskinnycolumn tipme contenttooltip tooltipa number1span span claskinnycolumn tipme contenttooltip tooltipa number5span span claskinnycolumn tipme contenttooltip tooltipa number0span span claskinnycolumn tipme contenttooltip tooltipa number0span span claskinnycolumn tipme contenttooltip tooltipassigned7span span claskinnycolumn tipme contenttooltip tooltip a number3spanspan div div classuserlisthoder iduserlistholder3534 activityshiftid3534div li ul div divli aanything with tipme or glossaryme brings up a qtip tooltip like this tipmelivemouseover function var this this thisremoveattrtitle thisremoveattralt if thisdatatooltipattached thisqtip show ready true solo true delay 500 style classes uitooltiplight infocardtip widget true content thisattrtooltip position at bottomright my topleft adjust screen flip x 0 y 0 hide fixed true inactive 10 thisdatatooltipattached true thistriggermouseover something tells me it might be all my tooltip handlers that are causing the problem let me know if you guys want anything else,"['javascript', 'jquery']" +115151,how to get stringformat to complain at compile time the compiler has access to the format string and the required types and parameters so i assume there would be some way to indicate missing parameters for the varargs even if only for a subset of cases is there someway for eclipse or another ide to indicate that the varargs passed might cause a problem at runtime,['java'] +115166,how to handle multiple video streams in red5 i am writing a red5 application that provides 1on1 video chat to a flash client over rtmpunfortunately most tutorials i was able to find were sketchy at best and the documentation of red5 itself tends to be vague when it comes to api concepts and intended usagein short i am a bit stuck and looking for hints on red5 applicationadapter implementation gnarly details are as followsfirst of all the connections come in two flavors visitors and consultants a visitor should be able to indicate which consultant it wishes to communicate with a consultant simply gets connected to the requesting visitor as long as the consultant is not busy servicing anotherobviously every rtmp connection has twoway traffic both sending and receiving video from the standpoint of the server connections bring in a bunch of video streams that get their receiving endpoints assigned by request since several video conversations can be in progress simultaneously the main task of the application is to handle the mapping of visitor streams to consultants and provide a list indicating each consultants state busyavailable via amfso all in all i have a pretty good idea what i am aiming for but how to achieve it with red5 is still a bit of a mysteryhopefully someone can enlighten me in any or all of the followingwhat is the easiest way to establish the connection type visitorconsultantwhich api classes should be used to implement a persistent globally accessible list of active connections for reporting the state of each consultanthow to switch receving endpoints dynamically when the goal is to connect a specific visitor to the selected consultant,['java'] +115172,datetimetryparse issue with dates of yddmm format i have the following date in string format 20112901 1200 am now i am trying to convert that to datetime format with the following codedatetimetryparsedatetime out dt but i am alwayws getting dt as 1101 120 am can you please tell me why and how can i convert that string to dateedit i just saw everybody mentioned to use format argument i will mention now that i cannot use the format parameter as i have some setting to select the custom dateformat what user wants and based on that user is able to get the date in textbox in that format automatically via jquery datepicker,"['c#', 'asp.net']" +115182,new number vs number what is the difference between new number and number i get that new number creates a number object and number is just a function but when should i call which and whyon a related note mozilla saysdo not use a boolean object to convert a nonboolean value to a boolean value instead use boolean as a function to perform this taskx booleanexpression preferredx new booleanexpression do not usewhy is that i thought the results were the same,['javascript'] +115193,list of references in google app engine for python in google app engine there is such a thing as a listproperty that allows you to hold a list array of items you may also specify the type of the item being held for instance string integer or whatever google app engine also allows you to have a referenceproperty a referenceproperty contains a reference to another google app engine model entity if you access a referenceproperty it will automatically retrieve the actual entity that the reference points to this is convenient as it beats getting the key and then getting the entity for said keyhowever i do not see any such thing as a listreferenceproperty or referencelistproperty i would like to hold a list of references to other entities that would automatically be resolved when i attempt to access elements within the list the closest i can get it seems is to hold a list of dbkey objects i can use these keys to then manually retrieve their associated entities from the serveris there any good solution to this basically i would like the ability to have a collection of autodereferencing references to other entities i can almost get there by having a collection of keys to other entities but i would like it to know that these are key items and that it could dereference them as a service to methank you,['python'] +115204,using ssl sockets and nonssl sockets simultaneously in boostasio i am in the process of converting a library to boostasio which has worked very well so far but i have hit something of a stumbling block with regards to a design decisionboostasio provides support for ssl but a boostasiosslstreamboostasioiptcpsocket type must be used for the socket my library has the option of connecting to ssl servers or connecting normally so i have made a class with two sockets like thisclass client public boostenable shared from thisclientpublic clientboostasioio service io service boostasiosslcontext context socket io service securesocket io service context private boostasioiptcpsocket socket boostasiosslstreamboostasioiptcpsocket securesocket and within there are a bunch of handlers that reference socket for example i have socket is open in several places which would need to become securesocket lowest layeris open for the other socketcan anyone suggest the best way to go about this i would rather not create a separate class just for this purpose because that would mean duplicating a lot of codeedit i rephrased my original question because i misunderstood the purpose of an openssl function,['c++'] +115215,using python and mechanize to submit form data and authenticate i want to submit login to the website redditcom navigate to a particular area of the page and submit a comment i do not see whats wrong with this code but it is not working in that no change is reflected on the reddit siteimport mechanizeimport cookielibdef mainbrowserbr mechanizebrowser cookie jarcj cookieliblwpcookiejarbrset cookiejarcj browser optionsbrset handle equivtruebrset handle gziptruebrset handle redirecttruebrset handle referertruebrset handle robotsfalse follows refresh 0 but not hangs on refresh 0brset handle refreshmechanize httphttprefreshprocessor max time1opens the site to be navigatedr bropenhtml rread select the second index one formbrselect formnr1 user credentialsbrformuser dummyusernamebrformpasswd dummypassword loginbrsubmitopen up comment pager bropenhtml rreadtext box is the 8th form on the page which i believe is the text areabrselect formnr7change text value to a testing stringbrformtext this is an automated testsubmit the information brsubmitwhats wrong with this,['python'] +115226,wcf and interfaces on data contracts while creating the wcf proxy using svcutil is it possible to include the interfaces as well from which the data contracts inherit egpublic class sometype isometype public string name get set public interface isometype public string name get set when i create the proxy using this the sometype type is created at the client but the interface is not created and there is no inheritance either i tried marking the interface as datacontract but that attribute isnt allowedis it possible to do what i am trying to do,"['c#', '.net']" +115228,need help explain an obfuscated c code this code snippet drove me crazy anyone could help me explain thisinclude stdiohchar xxtihrcxcxtihrxrcxtihxhrcxtixihrcxtxtihrcxtihrcxint mainint lforl7lputchar010lif main 88putchar 073putchar3310xf2a8bthankschan nguyen,['c'] +115232,check memory leaks in windows possible duplicateis there a good valgrind substitute for windows i have used valgrind in linux can anyone tell me some similar tools for checking memory leak in windows,['c++'] +115237,error putpkt write failed hi everyone i am thispalying remote images in tableview cellwhile i scrolled through the imagesdelete one of them and reloaded them my application exited showing this warning message ignoring packet error continuing gdb stack trace at putpkt write failed0 gdbarmappledarwin 0x0019026b remote backtrace self 54recent remote packets prior to putpkt write failedthe code for tableview cell images is uitableviewcell tableviewuitableview tableview cellforrowatindexpathnsindexpath indexpath static nsstring celltypecell uitableviewcell cell tableview dequeuereusablecellwithidentifiercelltype if cell nil cell uitableviewcell alloc initwithstyleuitableviewcellstyledefault reuseidentifiercell autorelease cellaccessorytype uitableviewcellaccessorythisclosureindicator cellbackgroundcoloruicolor clearcolor celltextlabeltextresultarray objectatindexindexpathrow valueforkeyservice uiimage indicatorimage uiimage imagenamedindicatorpng cellaccessoryview uiimageview alloc initwithimageindicatorimage autorelease nsthread threadnsthread allocinitwithtargetself selectorselector objectnil thread setstacksize44 thread start cellbackgroundviewuiimageview allocinitwithimageuiimage imagenamedcellpngautorelease uiimageview alloc initwithimageuiimage imagenamedbackpng autorelease cellselectionstyleuitableviewcellselectionstylenone uiimageview imageview uiimageview alloc initwithframecgrectmake19 15 75 68 imageviewcontentmode uiviewcontentmodescaletofill frameimagepath nsstring stringwithformatproductinfoarray objectatindexindexpathrowvalueforkeyimage imageview setimagewithurlnsurl urlwithstringframeimagepathplaceholderimageuiimage imagenamedno imagepng cellcontentview addsubviewimageview imageview release imageview nil return celland the method i call to reload the data in table after deleting is voidviewwillappearboolanimated spinner uiactivityindicatorview alloc initwithactivityindicatorstyleuiactivityindicatorviewstylegray spinnercenter selfviewcenter selfview addsubviewspinner spinner startanimating snapitparsing sharedinstanceassignsenderself snapitparsing sharedinstancestartparsingforshowproductsappdeluseridstring,['iphone'] +115249,best way to handle email parsingdecoding in php currently i am using the pear librarys mimedecodephp for parsing incoming emails it seems to have a lot of issues and fails to decode a lot of messages so i would like to replace it with something betteri am looking for something that is able to properly separate parts of the message such as to from body etc ideally it would be able to handle all common encoding methods such as base64 uuencode quoted printable etcin situations where both plain text and html versions of the same message are contained in a single email i would ideally like it to know the difference between them so i could choose which part i wished to thisplayi am not worried about attachments at this point in time but it would be nice for it to have knowledge of them in case i want to implement that in the futurei saw php has a group of functions that start with the word imap that appear they may do what i would like but i am unsure without trying them outcurrently i am doing onthefly decoding of the messages in php which is why i am looking for a php replacement solutiondoes anyone have an experience with this that could point me in the right direction i would hate to start using something that would end up not doing what i need in the long run,['php'] +115258,change the priority level in log4j hi normally in log4j priority levels are as follows debug info warn error fatalcan we change this priority levelsmy requirement is i need to log only details which have priority level info and fatal logs with priority level debug warn and error should not log if i can change the priority levels as debug warn error info fatalit is possible or is there any other way to do that pls help,['java'] +115262,enum from string int etc using extension method we can create methods to convert an enum to other datatype like string int by creating extension methods toint tostring etc for the enumi wonder how to implement the other way around eg fromintint fromstringstring etc as far as i know i cannot create myenumfromint static extension method so what are the possible approaches for this,"['c#', '.net']" +115268,sql in clause 10 item limit it is possible to put more than 10 items in the sql in clause we have been getting issues with our oracle database not being able to handle it if yes how do we put more than 10 items in the sql in clause if not what else can i do,['sql'] +115273,qt compiler warning overriding commands for target ignoring old commands for target when i am compiling my qt project for windows i receive these 2 warningsmakefiledebug109 warning overriding commands for target debugmoc mainwindowcppmakefiledebug106 warning ignoring old commands for target debugmoc mainwindowcppi assume they indicate some problem with my project config what is the problem and how do i fix it,['c++'] +115277,html5s file api example with jquery i would like to use html5s file api in combination with the external drag and drop functionality drag an external file onto a designated spot and capture its contents and jquery i found a working nonjquery example html5 demo file api var drop documentgetelementbyiddrop dropondragover function thisclassname focus return false dropondragend function thisclassname return false dropondropfunctione thisclassname epreventdefault var file edatatransferfiles0 var reader new filereader readeronload function evt consolelogevttargetresult readerreadastextfile this works fine now i would like to make this more a jqueryish and i tried dropbindondragoverfunction thisaddclassfocus return falsebindondragendfunction thisremoveclassfocus return false bindondropfunctione thisremoveclassfocus epreventdefault var file edatatransferfiles0 var reader new filereader readeronload function evt consolelogevttargetresult readerreadastextfile but that does not work none of the binded events seems to get triggered i also tried to loose the on part for the eventnames but that also does not workhopefully somebody here can shine a lightregardsjeroen,['jquery'] +115302,prevent background image from stretching the view whenever i assign background to a view that is laid out with wrap content if the background image is larger than a view the view is stretched so that it can hold the entire background why is it so and how to prevent it it occurs even if the image is 9patch and has stretchable areas marked why is not the image shrunk to the size of the view,['android'] +115305,difference in net protocol buffer libraries at the moment there are two proto buf libraries for net with jon skeet as the owner with marc gravell as the ownerwhat is the difference between the two are both coded to the same spec as the google spec are there any differencesthe reason i ask is that currently we have proto buf interop between services that use the java and potentially c libraries and want to make sure we avoid any problems or edge cases,['.net'] +115344,is there any way to save an xmldocument without indentation and line returns possible duplicatehow to remove whitespace from an xmldocument all my searches have brought up people asking the opposite but i have a file which grows by nearly 50 if it is saved with line returns and indentationis there any way round thisedit i am not talking about opening a file but saving one this code reproduces the bug for mevar path ctestxmlsystemiofilewritealltextpath rootrntlinelinerntlinelinernrootsystemxmlxmldocument doc new systemxmlxmldocumentdocpreservewhitespace falsedocloadpathdocpreservewhitespace false just in casedocsavepatha breakpoint in the middle shows that docinnerxml is effectively rootlinelinelinelineroot as expected but the contents of testxml at the end isroot line line line lineroot,"['c#', '.net']" +115346,making the iphone vibrate how can the iphone be set to vibrate oncefor example when a player loses a life or the game is over the iphone should vibrate,['ios'] +115370,is there a tool to analyse if a c and wpf project can be ported to silverlight i have a wpf and c application and i want to know if it can be ported to silverlight is there a tool to analyse the dependencies and tell me what i cannot use and what i can thanks,['c#'] +115377,javascript adding zeros to the beginning of a string max length 4 chars var number 1310should be left alonevar number 120should be changed to 0120var number 10should be changed to 0010var number 7should be changed to 07,['javascript'] +115389,looking for a dropin replacement for a javautilmap problemfollowing up on this question it seems that a file or thiskbased map implementation may be the right solution to the problems i mentioned there short versionright now i have a map implemented as a concurrenthashmapentries are added to it continually at a fairly fixed rate details on this latereventually no matter what this means the jvm runs out of heap spaceat work it was strongly suggested that i solve this problem using sqlite but after asking that previous question i do not think that a database is the right tool for this job so let me know if this sounds crazy i think a better solution would be a map stored on thiskbad idea implement this myself better idea use someone elses library which onerequirementsmusthavesfreepersistent the data needs to stick around between jvm restartssome sort of searchability yes i need the ability to retrieve this darn data as well as put it away basic result set filtering is a plusplatformindependent needs to be productiondeployable on windows or linux machinespurgeable thisk space is finite just like heap space i need to get rid of entries that are n days old it is not a big deal if i have to do this manuallynicetohaveseasy to use it would be great if i could get this working by the end of the weekbetter still the end of the day it would be really really great if i could add one jar to my classpath change new concurrenthashmapfoo bar to new somethiskstoredmapfoo barand be donedecent scalability and performance worst case new entries are added on average 3 times per second every second all day long every day however inserts would not always happen that smoothly it might be no inserts for an hour then insert 10 objects at oncepossible solutionsehcache i have never used it before it was a suggested solution to my previous questionberkeley db again i have never used it and i really do not know anything about ithadoop and which subproject have not used it based on these docs its crossplatformreadiness is ambiguous to me i do not need thistributed operation in the foreseeable futurea sqlite jdbc driver after allehcache and berkeley db both look reasonable right now any particular recommendations in either direction,['java'] +115392,android set spinner default value to null i am trying to get a spinner to load up with no selected value once the user selects a value it then takes them to another page this is proving to be a problem because at present the page just loads straight away before the user gets a choice to choosemy spinner class is setup the same way as googles so basically is it possible have a spinner that loads with nothing selected because at present it loads the first item in my string arraythanks everyone,['android'] +115396,deprecation of the static keyword no more in c it is possible to use the static keyword within a translation unit to affect the visibility of a symbol either variable or function declarationin n3092 this was deprecatedannex d2 deprstatic the use of the static keyword is deprecated when declaring objects in namespace scope see 336in n3225 this has been removedthe only article i could find is somewhat informalit does underline though that for compatibility with c and the ability to compile cprograms as c the deprecation is annoying however compiling a c program directly as c can be a frustrating experience already so i am unsure if it warrants considerationdoes anyone know why it was changed,['c++'] +115409,visual studio equivalent of java systemout what do i use in visual studio c to perform the equivalent of javas systemoutprintln stuff does the output from the command show in the output window in the idei have a button on a webpage that calls a service which returns a string i want to see whats in the string and have tried all the variations below and nothing ever shows up in the output it also does not stop on the breakpoint so i can check if there are any results var service new otesttylerapiapiwebservicesoapclientresults serviceodysseymsgexecutionmessage messagetypefindcasebycasenumber sourceapimessage referencenumber1 nodeid1 userid1 casenumbert4cv0043212010casenumbermessage nmodysseymetrosystemdiagnosticsdebugwriteresults,['c#'] +115420,delete row from php array how can i remove an element from an arrayfor exampledata arrayfirst second thirdarray deletedata2data would now read arrayfirst seconddoes such a builtin function existthanks,['php'] +115424,how to make rails external database calls so i would like to be able to add an external database to my configdatabaseyml then model one table from itis this possible i have not been able to figure out howconnection to multiple databases in different modelsconnections are usually created through activerecordbaseestablish connection and retrieved by activerecordbaseconnection all classes inheriting from activerecordbase will use this connection but you can also set a claspecific connection for example if course is an activerecordbase but resides in a different database you can just say courseestablish connection and course and all of its subclasses will use this connection insteadthis feature is implemented by keeping a connection pool in activerecordbase that is a hash indexed by the class if a connection is requested the retrieve connection method will go up the classhierarchy until a connection is found in the connection pool,['ruby-on-rails'] +115430,whats the xpath syntax to get tag names i am using nokogiri to parse a large xml file say i have got the following structuremenagerie penguinpablopenguin penguinmortimerpenguin bullferdinandbull aardvarkjames cornelius mathison humphrey zophar handlebrush iaardvarkmenageriei can count the nonpenguins like thisxmlxpathmenagerienotpenguinlength 2but how do i get a list of the tags like this the exact format is not important i just want to visually scan the nonpenguinsbullaardvarkupdatethis gave me the list i wanted thanks oded and tmn and delnanxmlxpathmenageriesnotpenguineach do node puts nodenameend,['ruby'] +115442,debugging jquery ajax function js codeajax type post url httplocalhostmyservicedirserviceasmxfoo contenttype applicationjson charsetutf8 data jsondata success function msg alertgood error function xhr status switch status case 404 alertfile not found break case 500 alertserver error break case 0 alertrequest aborted break default alertunknown error status i get unknown error error how do i get to the bottom of this i would like to know what the error actually is thanks,['jquery'] +115448,make nivo slider fadein on load hey i want to load the nivo slider in this orderbefore the slides appear a loadinggif is shownonce the slides are ready to appear they fadeinthe nivo sliders call function looks like thiswindowloadfunction start window load slidernivoslider effectrandom specify sets like foldfadeslicedown slices12 animspeed500 slide transition speed pausetime30 startslide0 set starting slide 0 index directionnavfalse next prev directionnavhidetrue only show on hover controlnavfalse 123 controlnavthumbsfalse use thumbnails for control nav controlnavthumbsfromrelfalse use image rel for thumbs controlnavthumbssearch jpg replace this with controlnavthumbsreplace thumbjpg this in thumb image src keyboardnavtrue use left right arrows pauseonhovertrue stop animation while hovering manualadvancefalse force manual transitions captionopacity08 universal caption opacity beforechange function afterchange function slideshowend function triggers after all slides have been shown lastslide function triggers when last slide is shown afterload function triggers when slider has loadedthe loadinggif is shown with this css statement that is located within the nivoslidercss fileslider background e urlimagesnivoloadergif norepeat 50 50 position relative width 960px height 328pxslider img position absolute top 0px left 0px thisplay nonei thought the way to do this was to use the builtin afterload parameter like this afterloadfunction thisfadein but that did not work outso i would really appreciate any ideasthank youupdatethe html is very simple as most nivo sliders layoutsdiv idslider classbox imagevideo top box cinema img srcassetsimagescinemaslide1jpg img srcassetsimagescinemaslide2jpg img srcassetsimagescinemaslide3jpg img srcassetsimagescinemaslide4jpg divwhen i use the afterload parameter nothing happens the loadinggif appears but then the images show up harshly without the fadein i would like so basically everything works but i would just like these images to fade in once the show is ready to start then they should simply slide with their random transitions as they do now,"['jquery', 'css']" +115464,get innerhtml from external page with javascript i am trying to get innerhtml of a div that is located on external page it is possible to do this using this kind javascript code script typetextjavascript documentreadyfunction var html documentgetelementbyidglr1srcmy pagehtmlinnerhtml alerthtml script,"['javascript', 'jquery', 'html']" +115488,validate a dropdownlist in aspnet mvc in controllerviewbagcategories categoryrepositorygetallcategoriestolistin view htmldropdownlistcat new selectlistviewbagcategoriesid categorynamehow can i make it so that by default it says select categoryand validate to check something is selected client and on the modelthanks,['c#'] +115490,future proof dals we are in the beginning of a really long development project with several sub projects basically each subproject will take several months to develop the code itself will be split up into several c projects but the physical database will be shared by all projectsthe problem is maintainability if we add a column to a table or split a table into two smaller tables well have to go back and modify our c dal to support these changes this is not acceptable as well constantly be adapting the db conform to the needs of the company as a whole and not just the needs of a single program constantly changing old code would be a neverending task our db people suggested a different view we do all our crud through stored procedures and use linq across several tables to perform our select statements then if we restructure the db several years from now we can simply supply the same stored procs and views and not have to modify our older codethe question we have is what orm should be used for something like this ef seems a bit overkill maybe it is not would something like subsonic with it is t4 templating allow for a simpiler and perhaps faster dalor perhaps someone has an idea on how to make this entire process less painful wed rather not add another layer to our application but neither do we want to go back and modify code everytime we make a db change edit 1so when i said i do not really want to add more layers this is mostly because we already have several layers we have silverlight views viewmodels bll objects via csla then we have the dal and finally the sql tables themseleves,['c#'] +115491,html5 application manifest not clearing cache on manifest change i have a rails app that i am trying to get using html5 application caching using rackoffline the applicationmanifest file is set up and is being downloaded and checked by my html pagethe manifest looks as followscache manifest 2d9bf2b03a07dc960fd8fe69659ceeffd4d28ccf8619669a506c3682bf223878404html422html500htmlloginhtmlstylesheetsscaffoldcssjavascriptsjqueryminjsjavascriptsjqueryjsjavascriptsapplicationjsjavascriptsrmbzjsjavascriptsrailsjsimagesrailspngnetworkthe page i am accessing is localhost30mobile and it has cached wonderfully viewable when i take down the rails server however the applicationmanifest file that it references has changed in fact it changes with each request by manipulating the commented hexadecimal id but chrome is not updating the page the console log in chrome gives the followingdocument was loaded from application cache with manifest httplocalhost30applicationmanifestapplication cache checking eventapplication cache downloading eventapplication cache progress event 0 of 12 httplocalhost30loginhtmlapplication cache progress event 1 of 12 httplocalhost30404htmlapplication cache progress event 2 of 12 httplocalhost30422htmlapplication cache progress event 3 of 12 httplocalhost30javascriptsrailsjsapplication cache progress event 4 of 12 httplocalhost30javascriptsrmbzjsapplication cache progress event 5 of 12 httplocalhost30imagesrailspngapplication cache progress event 6 of 12 httplocalhost30500htmlapplication cache progress event 7 of 12 httplocalhost30javascriptsjqueryjsapplication cache progress event 8 of 12 httplocalhost30stylesheetsscaffoldcssapplication cache progress event 9 of 12 httplocalhost30javascriptsjqueryminjsapplication cache progress event 10 of 12 httplocalhost30mobileapplication cache progress event 11 of 12 httplocalhost30javascriptsapplicationjsapplication cache error event manifest changed during update scheduling retryi do not quite understand why it is failing it seems to be doing everything it should until the last line i get a similar log if i navigate in my browser to localhost30applicationmanifest it seems that the manifest is cached itself so could that be why it complains that the manifest has changed any ideasthanks,['ruby-on-rails'] +115495,propagate constness to data pointed by member variables it is often quite confusing to c newcomers that const member functions are allowed to call nonconst methods on objects referenced by the class either by pointer or reference for example the following is perfectly correctclass someclass class someclassimpl someclassimpl impl pimpl idiom public void const method conststruct someclasomeclassimpl void non const method modify data void someclassconst method const impl non const method ok because impl is const not impl however it would sometimes be rather handy if the constness would propagate to pointed objects i voluntarily used the pimpl idiom because it is one of the case where i think constness propagation would be very usefulwhen using pointers this can easily be achieved by using some kind of smart pointer with operators overloaded on constnesstemplate typename t class const propagating ptr public const propagating ptr t ptr ptr ptr t operator return ptr t const operator const return ptr t operator return ptr t const operator const return ptr assignment operator get method reset method private t ptr now i just need to modify someclassimpl to be a const propagating ptrsomeclassimpl to obtain the wanted behaviorso i have a few questions about thisare there some issues with constness propagation that i have overlookedif not are there any libraries that provide classes to obtain constness propagationwouldnt it be useful that the common smart pointers unique ptr shared ptr etc provide some mean to obtain this behavior for example through a template parameter,['c++'] +115499,android and getting a view with id cast as a string in the java code of an android project if you want the reference for a view resource you can do something likeview addbutton findviewbyidridbutton 0in the above ridbutton 0 is not a string is it possible to dynamically refer to a resource by a string such as ridbutton 0i would like to refer to a button by ridbutton i where i is replaced by some valid index,"['java', 'android']" +115500,i want to animate in fact fade within drawrect is there a way to make drawrect animate from the previous scene to the next oneamazingly you can animate inside drawrect try it you can fade translate or animate any other propertyhowever it starts from fresh from blank so for example if you put a fadein animation block in drawrect the previous scene with thisappear and the new scene will fade up from whitei want the screen to fade from the previous image drawn in the previous cycle of drawrect to the new image i have just drawn err am drawingis there a way to do that perhaps trickily by manipulating whats going on with drawrectthis would seem to be a very common use case blending from one scene to the nextdoes anyone know the secretof course obviously this can be done in the core animation milieu or in many other ways but having drawrect fade from one drawrect to the next is an obvious idea cheersastounding update thanks to the genius of wrightcsthanks only to wrightcs we now know that drawrect handles animations perfectly simply paste this code at the end of any drawrect and try itselfalpha 00uiview beginanimationsnil contextnulluiview setanimationduration2selfalpha 10uiview commitanimationsit treats the entire drawrect no matter how complex as one enormous block and it wraps it in that animation yes it even includes painted in offscreen areas bitmap rendering or anything else everything gets animated who knewthe problem at hand how to make it start the animation from the previous scene rather than start from blank,"['iphone', 'ios']" +115512,badge icon resourceview is there a built in badge icon like the info icon so that i can show status updates on other views in my app it is easy enough to duplicate manually but i would like to use a built in resource if it is available,['iphone'] +115516,working with decimals in ruby on rails 3 i am trying to calculate the average net price of a product i have in my product model total sold and total net revenue doing straight division in the method seems to always result in 0 i resorted to using bigdecimal as i figured that was the problem but with my latest iteration of the code below i am still getting zero when the answer comes out to a decimaldef avg price bigdecimaltotal soldto s bigdecimaltotal net revenueto s 100end net revenue is in cents which is why i divide by 100 can someone point out what i am doing wrong or should do,"['ruby-on-rails', 'ruby']" +115543,if else embedding inside html what is the correct way of embedding if else and elseif conditions inside html,"['php', 'html']" +115546,is it possible to create a category of the block object in objectivec i would like to add functions by creating a category for objectivec blocks block int ablockint int int and if and 1 return n return ablock and 1 ablock and 2 instead of just allowing the normal ablock copy ablock retain ablock release ablock autorelease i could do thing likeablock maptoanarraypossible categoryinterface unknownblockclass map nsarray maptonsarray array end,['objective-c'] +115580,mocking httprequest and httpresponse for mvc application i am currently writing some unit tests to check the functionality and correct workings of the asp mvc application that we have writtenin this mvc application i am using a special actionfilterattribute that allows for authentication when making requests to the mvc applicationthe code for this actionfilterattribute is thisusing systemusing systemsecurityauthenticationusing systemtextusing systemwebmvcusing tenforceexecutionframeworkusing tenforceexecutionapi2implementationnamespace tenforceexecutionwebfilters summary this class defines a custom authentication attribute that can be applied on controllers this results in authentication occurring on all actions that are beeing defined in the controller who implements this filter summary attributeusageattributetargetsclass attributetargetsmethod inherited true allowmultiple true public class authenticationfilter actionfilterattribute region iauthorizationfilter members summary this function gets called by the mvc framework prior to performing any actions on the controller the function will check if a call is authorized by the caller the function will extract the username and password from the http headers send by the caller and will validate these against the database to see if there is a valid account for the user if the user can be found in the database operations will resume otherwise the action is canceled summary param namefiltercontextthe context for the filterparam public override void onactionexecutingactionexecutingcontext filtercontext call the base operations first baseonactionexecutingfiltercontext surround the entire authentication process with a trycatch to prevent errors from breaking the code try extract the custom authorization header from the http headers string customauthheader encodingutf8getstringconvertfrombase64stringfiltercontextrequestcontexthttpcontextrequestheaderstenforceauth split the header in the subcomponents string components customauthheadersplit check if both components are present if componentslength 2 this header consists of 2 parts the username and password seperate by a vertical pipe string username components0 stringempty string password components1 stringempty string databaseid authenticatorconstructdatabaseidfiltercontexthttpcontextrequestrawurl validate the user against the database if authenticatorauthenticateusername password databaseid the request is valid so add the custom header to inform the request was authorized allowrequestfiltercontext return throw new invalidcredentialexceptionthe provided username password combination is invalid username username if we reach this point the authorization request is no longer valid throw new invalidcredentialexceptioninsufficient parameters supplied for a valid authentication catch exception ex log the exception that has occurred loggerloggettype ex cancel the request as we could not properly process it cancelrequestfiltercontext endregion region private methods summary cancels the athorization and adds the custom tenforce header to the response to inform the caller that his call has been denied summary param nameauthcontextthe authorizationcontxt that needs to be canceledparam private static void cancelrequestactionexecutingcontext authcontext authcontextresult new httpunauthorizedresult if authcontextrequestcontexthttpcontextrequestservervariablesserver softwarecontainsmicrosoftiis7 authcontexthttpcontextresponseaddheadertenforcerauth denied else authcontexthttpcontextresponseheadersaddtenforcerauth denied summary allows the authorization and adds the custom tenforce header to the response to inform the claler that his call has been allowed summary param nameauthcontextthe authorizationcontext that needs to be allowedparam private static void allowrequestactionexecutingcontext authcontext authcontextresult null if authcontextrequestcontexthttpcontextrequestservervariablesserver softwarecontainsmicrosoftiis7 authcontexthttpcontextresponseaddheadertenforcerauth ok else authcontexthttpcontextresponseheadersaddtenforcerauth ok endregion the problem i am currently facing is that i cannot seem to properly mock the section with the response headers i have written a unittest that mocks a httprequest and httpresponse object and calls the attribute function with the request i can follow the successful login path branch in the code for an iis7 simulation as this relies on properties but when i try to follow the iis6 branch in a login i am getting null pointer exceptionsi use the following code to construct the moq objects summary this function is called before running each test and configures the various properties of the test class so that each test will run with the same settings initialy the function will configure the mock framework object so that they simulate a proper web request on the actionfilter of a controller summary setup protected void testsetup construct the mock object required for the test httprequest new mockhttprequestbase httpresponse new mockhttpresponsebase httpcontext new mockhttpcontextbase actioncontext new mockactionexecutingcontext filter new webfiltersauthenticationfilter configure the properties to modify the headers request and response objects starting from the httpcontext base object also create the custom header collection and set the test uri actioncontextsetupgetc chttpcontextreturnshttpcontextobject httpcontextsetupgetr rrequestreturnshttprequestobject httpcontextsetupgetr rresponsereturnshttpresponseobject httpresponsesetupgetx xheadersreturnsnew systemnetwebheadercollection httprequestsetupgetr rrawurlreturns the actuall test looks like this summary parathis test will call the actionfilter and perform a standard authorization request against the database using the credentials of the system administrator account the test relies on the moq framework to mock several of the key components in the mvc framework such as the httprequest httpresponse and httpcontext objectspara parathe test expects the authentication to succeed and relies on the iis6 implementationpara summary test maxduration public void successfullauthenticationoniis6 configure the authentication header of the request so that a valid authentication can take place we want valid login credentials when the filter requests the header httprequestsetupgetr rheadersreturnsnew systemnetwebheadercollection tenforceauth correctauthtoken httprequestsetupgetr rservervariablesreturns new systemcollectionsspecializednamevaluecollection server software microsoftiis60 httpresponsesetupgetr rheadersreturnsnew systemcollectionsspecializednamevaluecollection httpresponsesetupr raddheadertenforcerauth ok call the action on the filter and check the response filteronactionexecutingactioncontextobject check the actionresult to null and that the response header contains the correct value assertistrueactioncontextobjectresult null assertistrueactioncontextobjecthttpcontextresponseheaderstenforcerauthequalsok the last assert is failing because the header is not beeing set i have used the debugger to step through the code and the filter does actually set the header so i think that the moq object is not properly configured to handle the request could someone please shed some light on how i can get my httpresponse to accept the headersadd request,['c#'] +115582,what is the purpose of python 27s download package windows x86 msi program database upgrading from python 2526 to python 27 on winxp i have found new download package forms for python at so i am wondering what is the purpose of python 27s download package windows x86 msi program database searching on web did not bring me clarifications on thisactually it contains lots for pdb library files which on my pc are associated to palm pdb files this should be false as palm os is dead,['python'] +115590,find a database with a particular table or find a table in every database of sql server i have a sql server with hundreds of databases and each database having hundreds of tablesnow i would like to find where in these databases is a table that i am looking fori could find if a table existed in individual database using use mydatabase select from systables where name mytable gobut using this means i have to manually change the database for hundreds of times i would like to find the database name onlyis there a way out,['sql'] +115602,map a property to a collection item i have been sifting through automapper documentation to try and find a recommended solution to this but have not been able to find itlet us say i have a class like the followingpublic class foo public string note get set this class gets populated from the client and gets mapped to the following domain object classpublic class bar public ilistnote notes get set where note ispublic class note public string text get set other properties excluded for brevityi would like to map the note string property on foo firstly to the text property on a new instance of note and then add that note to the notes collection on bar i am using a valueresolver to perform the first part of this operation mapping the string to a new instance of note but am not sure about how to go about the second part mapping that item to a item in a collectionwhats the cleanest way of doing this,['c#'] +115619,genericfactory as singleton i read the article abstract factory template style by jim hyslop and herb sutter this factory is implemented as a singleton they provided an easy way to register classes automatically with the registerinfactory helper class now i have read several times that singletons should be avoided some even consider them as antipatterns and that there are just a few cases where they are usefullis this one of them or is there an alternative approach which provides such an easy way to autoregister classes,['c++'] +115649,get specific edge with boostgraph i am using boostgraph and i have two vertex descriptors what is the quickest way to get the edge between them without iterating over all the edges,['c++'] +115681,login failed for user iis apoolclassic net apool i just added my website to iis after much troubleshooting i was able to make it run with the classic net app poolbut on the page which requires connecting with the database i am getting the error login failed for the user iis apoolclass net apoolplease suggest a workaround,['asp.net'] +115691,what is the best strategy to handle unhandled exceptions error 500 responses in aspnet mvc actions for ajax requests i am confused as to how to handle this situation usually when an unhandled aspnet exception occurs the server sends back an html message of some sort either the default aspnet error handler or a custom error handler in either case though html is being sent back and usually it is a good idea to make the page user friendlyhowever i am having an issue where the unhandled exceptions are occurring in aspnet mvc controller actions that are expected to return json for ajax calls when the javascript reads the returned page which is html instead of intended json it crashes due to not being able to convert the response into json right now i am using extjs i want json to be returned upon an exception so that the user can be notified that an error has occurredthe only solution i can think of is to do the following in every action that returns jsontry catch exception ex return jsonnew success false msg exmessage i do not like that method because it requires me catch all exceptions which is bad for obvious reasons and it requires me to pepper every jsonresult action with that same exception handling code which makes it hard to change later is there a better method to return a more appropriate error result only on action methods that return json but still keep regular error pages user friendly for nonajax web requests,['c#'] +115692,create mysql date range cannot seem to find the answer i am looking fori want to create a range of dates from 20101101 to 20150101 in a table201011012010110220101103etccolumn datatype is datethanks,['mysql'] +115696,javascript when to use prototypes i would like to understand when it is appropriate to use prototype methods in js should they always be used or are there cases where using them is not preferred andor incurs a performance penalty in searching around this site on common methods for namespacing in js it seems that most use a nonprototype based implementation simply using an object or a function object to encapsulate a namespace coming from a classbased language its hard not to try and draw parallels and think that prototypes are like classes and the namespace implementations i mentioned are like static methods any clarification would be great,['javascript'] +115697,java standard for clientserver communication what is the official java api for clientserver or p2p communication java rmi some other networking apiis this official networking api the standard for both se and eei am sure the answer is very contextspecific so let us take a look at a few instancesyou have 2 swing clients installed on 2 machines and connected to the same network or the internet and you want either of them to send the other a primitive such as the integer 4 or some pojo like a widget objectsame as 1 above but between a swing client and a fullycompliant java ee backend implementing managed beans app servers the whole nine yardsi do not have a specific application in mind i am just wondering what are the norms for clientclient and clientserver communication in the world of java,['java'] +115706,visual studio adding data connections given key not present in the dictionary i have read through a couple of previous similar questions and none seem to provide a fix so i ask again i am using visual studio and am trying to connect to a db in server explorer regardless of what database i try to connect to it gives a given key not present in the dictionary error i have tried with sql ce and sql express 2008 databases and each give the same issue i can connect quite easily with sql management studio express so i believe the databases are the same thanks in advance,['sql'] +115709,c mvc image upload resizing server side i have got an webapplication where users can upload images the current problem i am running into is that the images being uploaded are being saved to the database in the original format this causes a lot of performance issues when the images are used on a webpage i used dottrace to profile the application and i see significant problems when images are processed from the databasethe idea i have is to resize the image when it is uploaded to the server take the following example which i want the application to do when the user uploads a new imageuser uploads an imagethe image is being resized to an size of 7500 x 7500 in pixels in 72 dpithe image is being saved into the databaseoriginal file gets thisposedthe only stored image is the one mentioned above and the webapplication contains technology to resize this on the flyi have already read several topics here on so and most of them point me into the direction of imagemagick this tool is already familiar at my company and being used in php projects but are there any good and stable released c wrappers for this tool i already found the tools below but they are either in bata release alpha release or currently not updatedimagemagicknetimagemagick appi also found this topic on so in this topic the following code example is suppliedprivate static image createreducedimageimage imgorig size newsize var newbm new bitmapnewsizewidth newsizeheight using var newgrapics graphicsfromimagenewbm newgrapicscompositingquality compositingqualityhighspeed newgrapicssmoothingmode smoothingmodehighspeed newgrapicsinterpolationmode interpolationmodehighqualitybicubic newgrapicsdrawimageimgorig new rectangle0 0 newsizewidth newsizeheight return newbmin short the questions i haveare there any advantages in relation to performance using the example aboveis there a good and reliable c wrapper for imagemagick i can use to do thisany other good tips relating to the performance are welcome,"['c#', 'asp.net']" +115711,how to load the profile of a newlyloggedin user before the redirect i started an aspnet mvc 2 project and i am building off of the code that was generated automaticallythe problem that i am experiencing is that after a user is logged in it appears that the profile of the newlyloggedin user is not loaded into the httpcontext so i get a providerexception with the message this property cannot be set for anonymous users when attempting to set a property value in the current users profilefor the postonly logon action visual web developer 2010 express basically generated httppost public actionresult logonlogonmodel model string returnurl if modelstateisvalid if membershipservicevalidateusermodelusername modelpassword formsservicesigninmodelusername modelrememberme where formsservice is a property of the controller of type formsauthenticationservice also generatedpublic class formsauthenticationservice iformsauthenticationservice public void signinstring username bool createpersistentcookie if stringisnulloremptyusername throw new argumentexceptionvalue cannot be null or empty username formsauthenticationsetauthcookieusername createpersistentcookie public void signout formsauthenticationsignout after the formsservicesigninmodelusername modelrememberme line i was assuming that information for the newlyloggedin account would be immediately available to the controller but this does not appear to be the case if for example i add profilesetpropertyvaluemyprofileproperty test below the call to formsservicesignin then i get the providerexception this property cannot be set for anonymous usershow do i load the newlyloggedin users profile into the httpcontext so that i can set a property value in his or her profile before the next request,['c#'] +115717,why would you want to put an index on a view microsoft sql server allows you to add an index to a view but why would you want to do this my understanding is that a view is really just a subquery ie if i say select from myview i am really saying select from myviews queryit seems like the indexes on the underlying tables would be the ones that matter the most so why would you want a separate index on the view,['sql'] +115730,what does where t class new mean can you please explain to me what where t class new means in the following line of code void addtt item where t class new,['c#'] +115751,retry task framework i have a number of situations where i need to retry a task ntimes if it fails sometimes with some form of backoffbeforeretry logic generally if an exception is thrown the task should be retried up to the maxretry counti can easily write something to do this fairly generically but not wanting to reinvent the wheel i was wondering if anyone can recommend any frameworks for this the only thing i have been able to find is ant retry but i do not want to use ant tasks directly in my applicationthanks,['java'] +115762,interpolation double quoted string of associative arrays in php when interpolating phps stringindexed array elements 533 win32the following behavior may be expected or notha arraykey1 hello to meprint hakey1 correct usual wayprint hakey1 warning works use of undefined constantprint he said hakey1 correct usual wayprint he said hakey1 warning works use of undefined constantprint he said hakey1 error unexpected t encapsed and whitespaceprint he said ha key1 error unexpected t encapsed and whitespaceprint he said hakey1 correct how comesinerestingly the last line seems to be correct php code any explanationscan this feature be trustededit the point of the posting now set in bold face in order to reduce misunderstandings,['php'] +115772,update the console window with java how can i make java update the current console window instead of going onto a new line or appending new content onto old as an example if i wanted to demonstrate progress i would output progress n where and would be the given percentage obviously what i would want to do is simply update and with the current percentage any help would be appreciated,['java'] +115774,is it possible to perform a like statement in a ssis expression i am using a derived column task to change column data using a case when statement however i need to be able to saysql code would becase when column01 like i then 0 else 1 endin ssis expression language that would becolumn01 i 0 1 that is for equals i not like iis it possible to use a like operator,['sql'] +115777,any easy way to plot a 3d scatter in python that i can rotate around currently i am using matplotlib to plot a 3d scatter and while it gets the job done i cannot seem to find a way to rotate it to see my data betterheres an exampleimport pylab as pimport mpl toolkitsmplot3daxes3d as p3data is an ndarray with the necessary data and colors is an ndarray withb g and r to paint each point according to its classfigpfigureax p3axes3dfigaxscatterdata0 data2 data3 ccolorsaxset xlabelxaxset ylabelyaxset zlabelzfigadd axesaxpshowi would like a solution that lets me do it during execution time but as long as i can rotate it and it is shortquick i am fine with itheres a comparison of the plots produced after applying a pca to the iris dataset1 mayavi2 matplotlib mayavi makes it easier to visualize the data but matplotlib looks more professional matplotlib is also lighter,['python'] +115792,how can i match a russian word using preg replace in php how do i go about matching a russian word in a string also in russian in phpso for example something like thispattern n34234preg replacepattern replacement string in russiani tried utf8 encode and htmlentities with utf8 flag for pattern but it did not work should i also encode string in russianupdate suggestion for u flag did not work so i am putting the actual code i need this for it is from a glossary plugin for wordpress my site is properly setup to use russian language and it does work but not in this instance so heres the codeglossary title glossary itempost titleglossary search bglossary titlesbiuglossary replace ltatimestampgt0ltatimestampgtcontent temp preg replaceglossary search glossary replace content 1when i do a quick echo into html comment this is the kind of string i get for the patternbn34234sbiuand well that still does not seem to work i thought maybe it was the s that was screwing me over this level of regex is a bit beyond me but i assume it is there for possible plurals but removing it did not helpupdate 2 okay so i decided to do a complete blank slate test plain php file with some content strings in english and russian and target words to replace here is the codecontent en nulla volutpat pretium nunc ac feugiat neque lobortis vitae in eu sapien sit amet eros tincidunt viverra b stylecolorpurpleproinb congue hendrerit felis et consequat neque ultrices lobortis b stylecolorpurpleproinb luctus bibendum libero et molestie sed tristique lacus a urna semper eget feugiat lacus varius donec vel sodales diam b stylecolorpurpleproinb fringilla laoreet purus a facilisis nisi porttitor vel nullam ac justo ac elit laoreet ullamcorper vel a magna suspenthisse in arcu sapienfind en proinreplace with en em stylecolorredreplacementemglossary search bfind ensbiucontent en replaced preg replaceglossary search replace with en content encontent ru lorem ipsum n34n 34n3414n nn34 n34n 34nn 2n 34 1412 nn12 nn1234 341212 n3412 no nn1234 n 12 no2 n34342 2 nn o34n34n34 12 34n n n34nn341 n on nn b stylecolorpurple2nb nonn nn b stylecolorpurple2nb nonn nn b stylecolorpurple2nb nonn 12343 n343n1414n nonn341212341 2no n on34nn html n34n lorem ipsum 2 on2 nonn 34 n1434n12 nfind ru 2nreplace with ru em stylecolorred12343 emglossary search bfind rusbiucontent ru replaced preg replaceglossary search replace with ru content ruand here is a screenshot of the output as you can see the english text had the target word replaced while the russian has not and the code is identical and i am using the u flag the file is also utf8 encoded any suggestions and again i tried removing the s still nothing,['php'] +115794,why is html legend tag text color different in ie vs other browsers perhaps i am missing something very obvious but why does the following html produce text in the legend that shows up blue in internet explorer but black in other browsershtml head head body fieldset fontitalictrue legend stylefontsize 24px fontweight bolderthis is a testlegend fieldset bodyhtmli would like the color to be common among each browser so i am explicitly setting the color to black but i am curious why there is a difference here,['html'] +115797,string comparison operator vs equals possible duplicatec are stringequals and operator really same for string comparison which approach is better and safestring s1sarfarazstring s2nawazbool result1 s1s2 approach 1bool result2 s1equalss2 approach 2or both are same under the hood,['c#'] +115806,explain ci get instance looking through code igniters source codein its helper functions i keep seeingci get instancecan anyone please explain to me how this worksi get that it is returning a reference to the ci super object but where does get instance come from,['php'] +115807,jquery dialog dialog fields added multiple times to the dom i am using the jquery ui to thisplay tabs in one of the tabs i have a dialog box if i navigate to that tab open the dialog close it navigate off the tab then back again and open the dialog i end up with multiple and duplicate html elements in the dom in other wordsi have got my main page setup with tabsdiv idgrouptabs stylewidth600px height600px thisplaynone ul lia hreftab1aspxspaninfospanali lia hreftab2aspxspanassociationsspanali uldivtab 2 contains a dialog boxdiv iddgevent input idsomeiddivdgeventdialogi have found that if i open the dialog navigate away to another tab and back again the next time i open up the dialog i will end up with duplicate elements both named someid in my dom this causes problems because when i try to grab the value from someid ie someidval i end up getting the value from the first instance of the dialogis there a fix to make sure that the fields are removed when the dialog is closed or better yet that they are removed properly when navigating to another tabeditin the end i believe the problem is related to the use of tabs and dialog together any field i have on the form that is outside the dialog gets removed from the dom when i navigate off the tab however anything that was in the dialog remains in the dom after i navigate away thus when i navigate back i end up with duplicates,['jquery'] +115808,reflection on a static overloaded method using an out parameter i am having some issues with invoking an overloaded static method with an out parameter via reflection and would appreciate some pointersi am looking to dynamically create a type like systemint32 or systemdecimal and then invoke the static tryparsestring out x method on itthe below code has two issuestgetmethodtryparse new type typeofstring t fails to return the methodinfo i expectmiinvokenull new object valuetostring concreteinstance appears to succeed but does not set the out param concreteinstance to the parsed valueinterwoven into this function you can see some temporary code demonstrating what should happen if the type parameter was set to systemdecimalpublic static object castobject value string type type t typegettypetype if t null object concreteinstance activatorcreateinstancet decimal tempinstance 0 listmethodinfo l new listmethodinfotgetmethodsbindingflagsstatic bindingflagspublic methodinfo mi mi tgetmethodtryparse new type typeofstring t this fails to get the method returns null mi lfirstordefaultx xname tryparse xgetparameterslength 2 ugly hack required because the previous line failed if mi null try bool retval decimaltryparsevaluetostring out tempinstance consolewritelineretvaltostring retval is true tempinstance is correctly set object z miinvokenull new object valuetostring concreteinstance consolewritelineztostring z is true but concreteinstance is not set catch exception ex debugwritelineexmessage return concreteinstance return valuewhat do i need to do to ensure that my tgetmethod call returns the correct methodinfo what do i need to do to have concreteinstance correctly set in my miinvoke calli know there are a bunch of questions on this topic but most of them involve static generic methods or static methods that are not overloaded this question is similar but not a duplicate,['c#'] +115809,unable to launch app for broadcast intent i wrote a small clock widget like all clocks it has to be updated every minute so i set up an alarm to do this it worked fine it was just a little too small so i fiddled with an xml attribute and tried again it forceclosed i changed the attribute back to the original and tried again it again forceclosedthe logcat followsfrom package install to the os killing it0119 133852292 debugpackagemanager57 new package installed in dataappcomclock2apk0119 133852571 infoactivitymanager57 force stopping package comclock uid100430119 133852571 infoprocess57 sending signal pid 593 sig 90119 133852612 infoactivitymanager57 force stopping package comclock uid100430119 133853022 debugphotoappwidgetprovider282 getphoto query count00119 133853022 debugphotoappwidgetprovider282 sending out viewsnull for id00119 133853131 infoactivitymanager57 start proc comclock for broadcast comclockclock pid613 uid10043 gids10150119 133853713 debugclock widget613 updated0119 133854011 infoactivitymanager57 force stopping package comclock uid100430119 133854021 infoprocess57 sending signal pid 613 sig 90119 133854301 debugdalvikvm121 gc explicit freed 13673 objects 524360 bytes in 177ms0119 133854542 debugdalvikvm125 gc explicit freed 4956 objects 200960 bytes in 440ms0119 133854801 warnrecognitionmanagerservice57 no available voice recognition services found0119 133855032 debugdalvikvm57 gc explicit freed 4960 objects 290104 bytes in 201ms0119 133855042 infoinstalld35 unlink datadalvikcachedataclassesdex0119 133855131 debugandroidruntime605 shutting down vm0119 133855151 debugdalvikvm605 debugger has detached object registry had 1 entries0119 133855212 infoandroidruntime605 note attach of thread binder thread 3 failed0119 1338571 debugphotoappwidgetprovider282 getphoto query count00119 1338571 debugphotoappwidgetprovider282 sending out viewsnull for id00119 133855762 infoactivitymanager57 start proc comclock for broadcast comclockclock pid622 uid10043 gids10150119 133856332 warnasset622 asset path dataappcomclock1apk is neither a directory nor file type10119 133856373 debugandroidruntime622 shutting down vm0119 133856373 warndalvikvm622 threadid1 thread exiting with uncaught exception group0x4001d80119 133856722 debugphotoappwidgetprovider282 getphoto query count00119 133856732 debugphotoappwidgetprovider282 sending out viewsnull for id00119 133856841 errorandroidruntime622 fatal exception main0119 133856841 errorandroidruntime622 javalangruntimeexception unable to instantiate receiver comclockclock javalangclassnotfoundexception comclockclock in loader dalviksystempathclassloaderdataappcomclock1apk0119 133856841 errorandroidruntime622 at androidappactivitythreadhandlereceiveractivitythreadjava27890119 133856841 errorandroidruntime622 at androidappactivitythreadaccess3200activitythreadjava1250119 133856841 errorandroidruntime622 at androidappactivitythreadhhandlemessageactivitythreadjava20830119 133856841 errorandroidruntime622 at androidoshandlerthispatchmessagehandlerjava990119 133856841 errorandroidruntime622 at androidoslooperlooplooperjava1230119 133856841 errorandroidruntime622 at androidappactivitythreadmainactivitythreadjava46270119 133856841 errorandroidruntime622 at javalangreflectmethodinvokenativenative method0119 133856841 errorandroidruntime622 at javalangreflectmethodinvokemethodjava5210119 133856841 errorandroidruntime622 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava8680119 133856841 errorandroidruntime622 at comandroidinternaloszygoteinitmainzygoteinitjava6260119 133856841 errorandroidruntime622 at dalviksystemnativestartmainnative method0119 133856841 errorandroidruntime622 caused by javalangclassnotfoundexception comclockclock in loader dalviksystempathclassloaderdataappcomclock1apk0119 133856841 errorandroidruntime622 at dalviksystempathclassloaderfindclasspathclassloaderjava2430119 133856841 errorandroidruntime622 at javalangclassloaderloadclassclassloaderjava5730119 133856841 errorandroidruntime622 at javalangclassloaderloadclassclassloaderjava5320119 133856841 errorandroidruntime622 at androidappactivitythreadhandlereceiveractivitythreadjava27800119 133856841 errorandroidruntime622 10 more0119 133856901 warnasset57 asset path dataappcomclock1apk is neither a directory nor file type10119 133856913 warnpackagemanager57 failure retrieving resources forcomclock0119 133857932 debugphotoappwidgetprovider282 getphoto query count00119 133858003 debugphotoappwidgetprovider282 sending out viewsnull for id00119 133905101 infoprocess622 sending signal pid 622 sig 90119 133905151 infoactivitymanager57 process comclock pid 622 has died0119 133905182 warninputmanagerservice57 window already focused ignoring focus gain of comandroidinternalviewiinputmethodclientstubproxy43ecc6980119 133905892 debugphotoappwidgetprovider282 getphoto query count00119 133905892 debugphotoappwidgetprovider282 sending out viewsnull for id00119 133906011 infoactivitymanager57 start proc comclock for broadcast comclockclock pid630 uid10043 gids10150119 133906413 warnasset630 asset path dataappcomclock1apk is neither a directory nor file type10119 133906472 debugandroidruntime630 shutting down vm0119 133906482 warndalvikvm630 threadid1 thread exiting with uncaught exception group0x4001d80119 133906901 errorandroidruntime630 fatal exception main0119 133906901 errorandroidruntime630 javalangruntimeexception unable to instantiate receiver comclockclock javalangclassnotfoundexception comclockclock in loader dalviksystempathclassloaderdataappcomclock1apk0119 133906901 errorandroidruntime630 at androidappactivitythreadhandlereceiveractivitythreadjava27890119 133906901 errorandroidruntime630 at androidappactivitythreadaccess3200activitythreadjava1250119 133906901 errorandroidruntime630 at androidappactivitythreadhhandlemessageactivitythreadjava20830119 133906901 errorandroidruntime630 at androidoshandlerthispatchmessagehandlerjava990119 133906901 errorandroidruntime630 at androidoslooperlooplooperjava1230119 133906901 errorandroidruntime630 at androidappactivitythreadmainactivitythreadjava46270119 133906901 errorandroidruntime630 at javalangreflectmethodinvokenativenative method0119 133906901 errorandroidruntime630 at javalangreflectmethodinvokemethodjava5210119 133906901 errorandroidruntime630 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava8680119 133906901 errorandroidruntime630 at comandroidinternaloszygoteinitmainzygoteinitjava6260119 133906901 errorandroidruntime630 at dalviksystemnativestartmainnative method0119 133906901 errorandroidruntime630 caused by javalangclassnotfoundexception comclockclock in loader dalviksystempathclassloaderdataappcomclock1apk0119 133906901 errorandroidruntime630 at dalviksystempathclassloaderfindclasspathclassloaderjava2430119 133906901 errorandroidruntime630 at javalangclassloaderloadclassclassloaderjava5730119 133906901 errorandroidruntime630 at javalangclassloaderloadclassclassloaderjava5320119 133906901 errorandroidruntime630 at androidappactivitythreadhandlereceiveractivitythreadjava27800119 133906901 errorandroidruntime630 10 more0119 133906901 debugphotoappwidgetprovider282 getphoto query count00119 133906922 debugphotoappwidgetprovider282 sending out viewsnull for id00119 133907051 warnactivitymanager57 process comclock has crashed too many times killing0119 133907062 infoprocess57 sending signal pid 630 sig 90119 133907151 warnactivitymanager57 unable to launch app comclock10043 for broadcast intent actandroidappwidgetactionappwidget update cmpcomclockclock has extras process is bad0119 133907151 warnactivitymanager57 finishreceiver called but none activei have never seen this error before and have no idea whats causing it or how to fix it can someone interpret this for me please,['android'] +115810,relative path to a file using c i have a commandline program that takes a configuration file as a parameter that is cmyprogramexe c cconfigfilesmyconfigfiletxt i want to be able to make it so that i do not have to type the absolute path to the configuration file so instead of the above i can just enter cmyprogramexe c myconfigfiletxti am not familiar enough with how c deals with paths to understand if or how this can be done any insight is appreciated,"['c#', '.net']" +115822,list do i pass objects or references well i have looked into generics and have following questionlistsomeclass listnew listsomeclasomeclass myinstancesomeclasslistaddmyinstancei am not sure what will be added to list reference or object of reference type pointing to actual value of myinstanceedit or i will add value that is reference data type which points to actual objectthanks,['c#'] +115836,android import ressources from library project is it possible to use ressources like strings that are defined in library projects in the applicationprojects if so howbecause i cant seem to resolve the strings i would like to resolve like thisstring title sampleint id ressourcesgetidentifiertitle string compackagegives me this exceptionwarnresourcetype278 no package identifier when getting value for resource number 0x0warnsystemerr278 androidcontentresresourcesnotfoundexception string resource id 0x0the string sample i am looking for is definitely in this package provided in the stringsxml of the library project i can even see it in the rjava,['android'] +115837,how can i embed an entire github gist dynamically on a page i have some text that includes urls to github gists i would like to look for those urls and put the gist inline in the content clientside some things i have trieda direct lookup to githubs oembed apifor this means i do a jsonp lookup to ampurlhttps3a2f2fgistgithubcom2f733951extract the html property of the object and add adding that to my page the problem here is that githubs oembed api only returns the first three lines of the gistusing the jqueryembedly plugincallingjqueryasomethingembedlyallowscripts trueworks but embedly strips formatting from the gist wrapping it in a pre tag does not help because there are no linebreaksusing githubs js version of the gist uses documentwrite so i do not have any control over where in the page when i require it dynamically if i could write it into the html source it would show up in the right place but this is all being done clientside,"['javascript', 'jquery']" +115849,slide a div offscreen using jquery this is a bit of a challenge heres what i am looking for3 divs on screendiv 1 resides in the middle of the page centereddiv 2 resides just off the screen on the far leftdiv 3 resides just off the screen on the far rightonclick div 1 slides to the position div 2 was to the left div 2 slides off the screen entirely div 3 slides to where div 3 was middle centered a new div arrives on the righti have tried using jquery animation and addclass jquery does not like sliding a div offscreen any thoughtsfor an example of what i am describing visit grouponcom i thought it was a cool idea and have given myself the challenge of recreating it so far no diced,"['javascript', 'jquery', 'html', 'css']" +115854,classloader leak are they worth solving classloader leaks usually result in javalangoutofmemoryerror permgen in the instance of working on application servers you may see this as a result of many redeploys of a common application the explanation and possible resolutions to this problem can be seen on these two links among others leaks the dreaded javanow for the most part they are easy to get around simply increase the xxmaxpermsize and when the inevitable happens restart the jvm completely the problem with trying to solve this is that in large applications many classes can cause the classloader to leak and thus the classes to stay within the permgen two questions arise from thisis it reasonable to say that an issue like this is better to just increase the max perm size and restart where necessary or should finding a resolution be a higher priority are there easier ways to resolve a classloader leak,['java'] +115862,implementing debounce in java for some code i am writing i could use a nice general implementation of debounce in javapublic interface callback public void callobject argclass debouncer implements callback public debouncercallback c int interval public void callobject arg should forward calls with the same arguments to the callback c but batch multiple calls inside interval to a single one when call is called multiple times in interval milliseconds with the same argument the callback function should be called exactly oncea visualizationdebouncercall x x x xcallbackcall x x x interval is 2does something like this exist already in some java standard libraryhow would you implement that,['java'] +115867,make alternating css table row style work in internet explorer i use this css code to thisplay a database output in rows where the colors repeat in every 2nd rowtbody trnthchild2n td tbody treven td background none repeat scroll 0 0 e5ecf9 if i open it in my ie it wont work any advicei am using ie 8,"['html', 'css']" +115875,attaching jquery event handlers so that they are triggered first is there a way to attach a jquery event handler such that the handler is triggered before any previouslyattached event handlers i came across this article but the code did not work because event handlers are nolonger stored in an array which is what his code expected i attempted to create a jquery extension to do what i wanted but this is not working the events still fire in the order they were boundfnextend bindfirst functiontype handler var basetype type var dotidx typeindexof if dotidx 0 basetype typesubstr0 dotidx thiseachfunction var oldevts var data datathis var events dataevents data events var handlers eventsbasetype for var h in handlers if handlershasownpropertyh oldevtsh handlersh delete handlersh also tried an unbind here to no avail var self this selfbindtype handler for var h in oldevts if oldevtshasownpropertyh selfbindbasetype oldevtsh is there a natural way to reorder event handling if there is not do you know of technique i could apply i am using jquery 141 though i will upgrade if i must,['jquery'] +115877,a switch java problem case expressions must be constant expressions i having a problem in my switchcase statement the error says case expressions must be constant expressions i understand the error and i can resolve it using if but can someone tells me why the case expression must be constant in a switchcase a code example of my error public boolean onoptionsitemselectedmenuitem item int iddirectory menuitem findviewbyidridcreatedirectorygetitemid int idsuppression menuitem findviewbyidridrecycletrashgetitemid int idseetrash menuitem findviewbyidridseetrashgetitemid switch itemgetitemid case iddirectory createdirectorycurrentdirectory break case idsuppression recycletrash break case idseetrash seetrash break return superonoptionsitemselecteditemthx for your explanation,"['java', 'android']" +115885,where are rake tasks defined on a freshly created rails project generated by rails somename one can run some default rake tasks likerake testrake dbmigrateetcquestion is where does these tasks get described the default rakefile does not have all these tasksfurthermore i checked out some project that uses rspec and i am able to run rake spec to run all the tests where does the spec target defined,"['ruby-on-rails', 'ruby']" +115886,datagridview validation changing cell value i would like to manipulate a cell in my datagridview when it is validating so that if the user enters a value that is not valid for the database but is easily converted to valid data the program will change the value to an appropriate onei am able to validate my value properly but when i try to change it to something valid i get a dataerror here is my code private void unit list 2 groupsdatagridview cellvalidatingobject sender datagridviewcellvalidatingeventargs e consolewritelinevalidating datagridviewcolumn col thisunit list 2 groupsdatagridviewcolumnsecolumnindex datagridviewcell cell thisunit list 2 groupsdatagridviewrowserowindexcellsecolumnindex if col thisbatchdatagridviewtextboxcolumn thisunit list 2 groupsdatagridviewiscurrentcellineditmode consolewriteline batch column datarow rows label entrydatasetviewjobbatchlistselectstringformatjob0 and thisplay1 combobox1selectedvalue eformattedvalue if rowslength 1 consolewriteline auto completed item from list 0 rows0batch ecancel true cellvalue rows0batch thisunit list 2 groupsdatagridviewendedit else consolewriteline no autocomplete int i 0 if inttryparseeformattedvaluetostring out i consolewriteline not an integer either ecancel true the line that reads cellvalue rows0batch is not doing what i expect it to do,['c#'] +115890,passing object as parameter to constructor function and copy its properties to the new object i have a javascript constructor like thisfunction boxobj thisobj objwhich i want to pass an object as a parameter like thisvar box new boxprop1 a prop2 b prop3 cand gives me something like thisboxobjprop1boxobjprop2boxobjprop3but i would like the properties to be directly on the object like thisboxprop1boxprop2boxprop3i know i could do something like thisfunction boxobj thisprop1 objprop1 thisprop2 objprop2 thisprop3 objprop3but that is not good because then my constructor would have to know before the names of the properties of the object parameter what i would like is to be able to pass different objects as parameters and assign their properties directly as properties of the new custom object created by the constructor so i get boxpropx and not boxobjpropx hope i am making myself clear maybe i am measing something very obvious but i am a newbie so please need your helpthanks in advance,"['javascript', 'jquery']" +115892,unicode in usernames and passwords after reviewing this i realised i still have a few questions left regarding the topicare there any characters that should be left out for legitimate security purposes this includes all characters such as brackets commas apostrophes and parentheses while on this subject i admittedly do not understand why admins seem to enjoy enforcing the you can only use the alphabet numbers and spaces rule does anything else have the potential to be a security flaw or break something i am not aware of even in ascii as far as i have seen during my coding days there is absolutely no reason that any character should be barred from being in a username,"['php', 'mysql']" +115893,how can i force php to use the libiconv version of iconv instead of the centosinstalled glibc version the code i am working on runs perfectly on windows xp and on mac os x when testing it on centos and on fedora and ubuntu it is not working properly searching the nets led me to the conclusion that it is the glibc version of the iconv that is causing the problem so now i need the libiconv version of iconv for zend lucene to work properlyi already downloaded libiconv and configured it with prefixusrlocal make then make install without any errors it seems that it was successfully installed because executing usrlocalbiniconv version says the version is the libiconv although a simple iconv version still gives the glibc versionthen i recompiled php from source using withiconvusrlocal but still the phpinfo is showing the iconv being used is the glibc version i have also already tried several other compiles using withiconvdir or using usrlocalbinphpof course i restarted the web server after recompiling phpi have the following line in my etchttpdconfhttpdconfloadmodule usrlibhttpdmoduleslibphp5soand libphp5so is actually in usrlibhttpdmodulesphpinfo shows php 533 i also yum removed the preinstalled php 51 just to make sure but the iconv is still using the glibc versionldd usrlibhttpdmoduleslibphp5so giveslinuxgateso1 0x003b10usrlocallibpreloadable libiconvso 0x00110libcryptso1 liblibcryptso1 0x001ed0librtso1 liblibrtso1 0x0021f0libmysqlclientso15 usrlibmysqllibmysqlclientso15 0x003b20libldap23so0 usrliblibldap23so0 0x0026e0liblber23so0 usrlibliblber23so0 0x00370libiconvso2 usrlocalliblibiconvso2 0x005160libfreetypeso6 usrliblibfreetypeso6 0x002a80libpng12so0 usrliblibpng12so0 0x002280libzso1 usrliblibzso1 0x003280libcurlso3 usrliblibcurlso3 0x00f230libmso6 liblibmso6 0x0033b0libdlso2 liblibdlso2 0x003640libnslso1 liblibnslso1 0x0037e0libxml2so2 usrliblibxml2so2 0x00f5f0libsslso6 liblibsslso6 0x0862c0libcryptoso6 liblibcryptoso6 0x041450libgssapi krb5so2 usrliblibgssapi krb5so2 0x08e2d0libkrb5so3 usrliblibkrb5so3 0x0611a0libk5cryptoso3 usrliblibk5cryptoso3 0x005f40libcom errso2 liblibcom errso2 0x0024e0libidnso11 usrliblibidnso11 0x071f50libcso6 liblibcso6 0x08aa60libpthreadso0 liblibpthreadso0 0x003970libldlinuxso2 0x002510libresolvso2 liblibresolvso2 0x0748a0libsasl2so2 usrliblibsasl2so2 0x07ddf0libkrb5supportso0 usrliblibkrb5supportso0 0x062b70libkeyutilsso1 liblibkeyutilsso1 0x003690libselinuxso1 liblibselinuxso1 0x0913b0libsepolso1 liblibsepolso1 0x07eb40this is a crosspost from nullpointerph,['php'] +115906,how to detect ie6 and show alert i am trying to show an alert when a user using ie6 uses my site i am thinking something like this will workif ie 6script languagejavascriptalert the year 2004 just called they want their browser backscriptendifi would test this but i do not have a windows box i can use atm is this the correct way to do it,"['javascript', 'html']" +115912,what is consolelog and how do i use it possible duplicatewhat is consolelog i see this line in a lot of jquery scripts out there i assume it is used for debugwhere can i see this log,['javascript'] +115917,jquery match only part of id from div i ran into an unusual situation yesterday nighti need to match only part of id let me clear you all with an examplei have few divs likediv idsales info 1 divdiv idsales info 2 divdiv idsales info 3 divand jquery goes likejquerydivdont know what to write herebindclick function i need to match only sales info ignoring 1 2 or anything can anyone suggest me how to achieve thisthanks,['jquery'] +115919,fill django form field data with db data i am trying prefill a form field with data from a db object how do you set up the formview and model to fill a field with this datathe goal is to let the user only select data that is queried from the object ex an event has bands playing the user selects their favorite band from those at the eventi tried looking through the docs for formdata but cannot seem to find what i am looking forthanks,['python'] +115937,i am not sure if i have the correct indexes or if i can improve the speed of my query in mysql my query has a join and it looks like it is using two indexes which makes it more complicated i am not sure if i can improve on this but i thought i would askthe query produces a list of records with similar keywords the record being queriedheres my queryselect match keywordspadid countmatch keywordsword as matching wordsfrom keywords current program keywords inner join keywords match keywords on match keywordsword current program keywordswordwhere match keywordsword is not null and current program keywordspadid 25695group by match keywordspadidorder by matching words desclimit 0 11 the explainword is varchar40,"['mysql', 'sql']" +115943,unexpected behaviour for threadpoolqueueuserworkitem please check the code sample below public class sample public int counter get set public string id public void runcount for int i 0 i counter i threadsleep10 consolewritelinethisid itostring class test static void main sample arrsample new sample4 for int i 0 i arrsamplelength i arrsamplei new sample arrsampleiid sample itostring arrsampleicounter 10 foreach sample s in arrsample threadpoolqueueuserworkitemcallback sruncount consolereadkey the expected output for this sample should be something like sample0 0 sample1 0 sample2 0 sample3 0 sample0 1 sample1 1 sample2 1 sample3 1 however when you run this code it would show something like this insteadsample3 0 sample3 0 sample3 0 sample3 1 sample3 1 sample3 0 sample3 2 sample3 2sample3 1 sample3 1 i can understand that the order in which the threads are executing might differ and hence the count isnt increasing in round robin fashion however i fail to understand why all the ids are being thisplayed as sample3 while the execution is clearly happening independent of each other arent different objects being used with different threads,"['c#', '.net']" +115945,how to get selected months last date in cnet i am using a drop down list for selecting the month in aspx page i have to get last date of the selected month in aspxcs page some months have 30 days and some have 31 dayshow can i do this,"['c#', 'asp.net']" +115947,facebook connect graph status objects have comments capped at 25 does anyone know why no matter how many comments a given graph status update object has it will cap the comments at 25 i have a feeling it only returns a sample of the actual comments on the object how do i force it to get them all without using the fql apis,['ios'] +115952,c check if file is text based how can i test whether a file that i am opening in c using filestream is a text type file i would like my program to open any file that is text based for example txt html etcbut not open such things as doc or pdf or exe etc,['c#'] +115958,day name from nsdate i would like to show the name of day in my iphone application and i do not found the solutionthanks for help,"['iphone', 'objective-c']" +115963,can the exposure time be manually adjusted for an ios cameras i want to adjust the exposure of the iphoneipod touch camera with intimate detail i would prefer to take a series of photos with decreasing exposure times to obtain a sequence of images for hdr reconstruction is this possibleif not whats the next best thing it seems you can set a point of interest in the image for the autoexposure perhaps i could search for a darklight region of the image and then use this exposurepointofinterest to adjust the exposure but this seems like a very indirect solution that is also errorprone if anybody has tried an alternative such an answer is also desirable,"['iphone', 'ios']" +115976,progressdialog thismissal in android i want to open a progressdialog when i click on the list item that opens the data of the clicked item form the web service the progressdialog needs to be appeared till the webcontent of the clicked item gets openedi know the code of using the progress dialog but i do not know how to thismiss it particularlyi have heard that handler is to be used for thismissing the progress dialog but i did not found any worth example for using the handler ultimately can anybody please tell me how can i use the handler to thismiss the progress dialogthanksdavid,['android'] +115978,urlcontent like method in jquery or javascript possible duplicateurl helper in java script urlcontent aspnet mvc helper method returns equivalent absolute url i am searching for a method in jquery or javascript that works like thisbecause i want to separat javascript code into a file js and you know that file does not supports urlcontent inside javscript codeurl method of jquery not works like urlcontentupdated 22 jan 2011hi guys iave a workaroundin the cshtml file i created a agetpatha function that returns absolute path including domain name and can be accessible inside any js fileinclude following code in any aspnet mvc view cshtml or aspx or vbhtmlscript typetextjavascript var fullpath httpcontextcurrentrequesturlschemehttpcontextcurrentrequesturlauthority function getpathurl return fullpath url scriptscript srcurlcontentjavascriptfilejs typetextjavascriptscriptand the code inside any javascript filefunction alertgetpathcontentsitecssthe result is or localhost1234contentsitecss visual cassini serveryou just need to replace urlcontent with getpath in any js file,['jquery'] +115983,find and replace within a text file i have a text file which is about 40 lines long i need to import this text file into a program which only accepts text files which are delimited with spaces or tabs but this text file is delimited with semicolons there is no option in the program i am exporting the text file from arcmap to change the delimination and doing find and replace in the text file itself will literally take 2 daysi have searched for a script to do this but they all seem to replace the whole line of the word file with a space instead of individually replacing each semicolon leaving me with an empty text filehere is a sample of my text fileoid pointidgrid codepoint xpoint y1560200900250122514975012560200900750122514975012235602009012501225149750122457020090175012251497501225570200902250122514975012265702009027501225149750122757020090325012251497501228570200903750122514975012295702009042501225149750122105702009047501225149750122i need it to look something like this1 560 200900250122 514975012 560 200900750122 5149750122,['python'] +116002,validates acceptance always failing i cannot see what i am missing but something is obviously not rightin modelvalidates terms acceptance true on updatetrying a few options a factoryblog agreement blogagreement id 54 terms false created at 20110120 113303 updated at 20110120 113303 accept code fa27698206bb15a6fba41857f12841c363c0e291 user id 874 aterms false aterms true true asave false aterms 1 1 asave false aterms 1 1 asave false aerrorsfull messages terms must be accepted,['ruby-on-rails'] +116025,can i restyle google maps infowindows to look less crappy the chunky speech bubble things look pretty crap in my opinion i would like something much tidier and more minimalare there any native ways to change the info box style without manually replacing the elements with js each time an infowindow is shown clumsyi am using google maps api v3,['html'] +116067,windows phone 7 native code support 2 questionscan someone tell me if unmanaged c code willbe supported in future versions of phone 7 os for all developerswhat are ms reasons for notsupporting unmanaged c code,['c++'] +116077,ios avfoundation show a time thisplay over a video and export i want to show a thisplay overlay over a video and export that video including this thisplay i had a look into the avfoundation framework avcompositions avassets etc but i still do not have an idea to achieve this there is a class called avsynchronizedlayer which lets you animate things synchrounous to the video but i do not want to animate i jsut want to overlay the time thisplay into every single frame of the video any adviceregards,['ios'] +116104,how to get pid of process i have just started within java program i have started a process with following code processbuilder pb new processbuildercmd c path try process p pbstart catch ioexception ex now i need to know the proces pid that i have just started,['java'] +116106,is monos vbnet support ready for a production site previously i have only used microsoftcentric solutions but for an upcoming aspnet project i am considering using mono and hosting it on a linux amazon ec2 instance based on the responses to my previous question this sounds doable however i am most comfortable with vbnet and i am wondering how well mono supports it does anyone have firsthand experience writing aspnet applications for mono using vbnet if so i would like to know how it went what kind of compatibility issues you ran into and if you consider monos vbnet support ready for use on a production sitei know monos cnet support is very good so that is my fallback plan but i would really prefer to use vbnet,"['.net', 'asp.net']" +116114,can i treat a specific warning as an error the following is a simplified version of a pattern i sometimes see in my students codebool foobarint a int b if a b return truethe real code is more complicated of course visual studio reports a warning c4715 not all control paths return a value and i would like to treat all warnings c4715 as errors is that possible,['c++'] +116118,build and project management tool for ios build and dependencies i have a java apache maven and android background and i am dabbling a bit with ios now i am wondering if there is some sort of standard tool chain that helps with things likemanaging scm details svn git mercurial branching taggingrelease management version numbering managing dev vs prod configurationworking with dependencies eg centralized for multiple project and developers remote accesside independent buildci build testing libraries unit testing integration testing ui testing mockingstatic analysisproject health reportingother ides and a whole bunch of other things that the maven ecosystem provides like public library repositories and so on from my initial research there does not seem much around but i might just be looking in the wrong placeswhat are the must have tools and libraries for ios development also i have the impression that xcode rules it all and if a feature is not there you end up out of luck eg git or hg support and add other tools thats fine but you will always have to use xcode right,"['iphone', 'objective-c', 'ios']" +116128,dump all values in vars in freemarker i am attempting to dump all the variables available to my freemarker templates i am attempting to use something likelist varskeys as propprop varsgetproplisti read in the documentation that vars does not support the keys functionality however i am using the above to show what i am trying to dothis is my first day with freemarker so any advice would be great,['java'] +116130,amazon s3 image downloading instead of thisplaying in browser this is driving me mad i am uploading images to s3 using the php sdk whenever i browse to the image url the browser downloads the image opposed to thisplaying iti think its something to do with content type prepare to upload the file to s3 bucket s3create objectbucket file name array contenttype binaryoctetstream acl amazons3acl public can you helpthanks,['php'] +116144,best javascript solution for clientside form validation and interaction our web forms are really complex whats a great solution for extensible form validation preferably one that works with jquerybackgroundour site has a bit of ajax but the real focus is on user experience through about 20 multipage forms or wizards these forms are complicatedpresentation some fields are floats or ints validation means stripping nondecimal characters but we also want to make sure that if a user enters 5 into a price field the field is updated to 500side effects some fields have side effects when updated eg updating the price or quantity of an item needs to update a subtotal fieldwidgetdriven elements some fields are hidden and have values populated by widgets eg a map widget lets you point to a location and a hidden field is updated with latitudelongitude coordinates but the location must be within a certain regiongroups some fields are groups like addresscitystatezip and should only be validated when all of the fields have bee populatedserverside validation validation of some fields requires backend checking via ajax requestsmultiple forms per page sometimes a user needs to fill out one form before a dialog opens with another form a framework has to be more versatile than binding to onsubmit a we sometimes post multiple forms in order from the same page using ajax eg we let users sign up and create a widget in one swoop but due to legacy systems that flow requires two post requests customizable error thisplay sometimes errors appear above fields sometimes the field style changes and our new designs call for tooltiplike popups ala qtip for some errorssnappiness user experience is key and tactile feedback is important any solutionsubmit buttons clicking the submit button needs to validate everything and then show a response a but since some of the validation happens asynchronouslywere currently using the jquery validation library but our forms appear to be outgrowing its capability i have been looking at things like angular knockout and backbonejs but i am worried that they are too heavyweight or that they would require us to rewrite our frontend this should be a community wiki,"['javascript', 'jquery', 'html']" +116153,how do i use taglib to readwrite coverart in different audio formats i would like to use taglib to readwrite coverart especially for mp3 and ogg files but i could not find any examples could someone point me to some examples where should i look to find more information about this,['c++'] +116154,applescript to copy folders into xcode i am having some trouble copying folders into xcode projects with applescript without applescript i drag the folder into xcodei have used a similar applescript handler as the one shown below to copy libraries into xcode using wrapperlibrary for the file type below i am using wrapperfolder to try to copy a folder into xcode and it is not working on addfolderfname fpath tell application xcode tell project unityiphone set my targets to targets set s target to item 1 of my targets set compile phase to compile sources phase of s target set link phase to get link binary with libraries phase of s target tell root group set a to make new file reference with properties full pathfpath fname namefname file typewrapperfolder add a to link phase end tell end tell end tell end addfolderdoes anyone have any ideas on what i am missing or how to write an applescript to copy a folder into xcode,['iphone'] +116156,java thread per connection model vs nio is the nonblocking java nio still slower than your standard thread per connection asynchronous socketin addition if you were to use threads per connection would you just create new threads or would you use a very large thread pooli am writing an mmorpg server in java that should be able to scale 10 clients easily given powerful enough hardware although the maximum amount of clients is 240 which i believe is impossible to reach for the thread per connection model because of a 150 thread limit in javafrom a three year old article i have heard that blocking io with a thread per connection model was still 25 faster than nio namely this document but can the same still be achieved on this day java has changed a lot since then and i have heard that the results were questionable when comparing real life scenarios because the vm used was not sun javaalso because it is an mmorpg server with many concurrent users interacting with each other will the use of synchronization and thread safety practices decrease performance to the point where a single threaded nio selector serving 10 clients will be faster all the work does not necessary have to be processed on the thread with the selector it can be processed on worker threads like how minanetty worksthanks,['java'] +116158,proving the primality of strong probable primes using the probabilistic version of the millerrabin test i have generated a list of mediumlarge 200300 digit probable primes but probable am not good enough i need to know these numbers are prime is there a library preferably wrapped or wrappable in python that implements one of the more efficient primality proving algorithmsalternatively does anyone know where i can find a clear detailed and complete description of ecpp or a similarly fast algorithm that does not assume a great deal of prior knowledgeupdate i have found a java implementation of another test aprtcle that conclusively proves primality it verified a 291digit prime candidate in under 10 minutes on an atom processor still hoping for something faster but this seems like a promising start,['python'] +116164,how to zoom in smoothly on a marker in google maps i would like to be able to zoom in smoothly on a marker in google maps if one just sets the zoom on double click the map is suddenly on that zoom level without any smooth transition zooming in only one level further than the current level google maps shows a nice smooth transition so it must be possible to zoom in smoothly for more than one level but how,['javascript'] +116175,max size of an ios application what is the maximum size of an ios application any constraints,['ios'] +116192,devise gem in rails generate user root path trying to redirect users to their associated home page after successful login wout niling out stored location forresource or scopewhich is giving me some endless redirect loops pretty sure i have set it up wrong regardless i am looking for a better approach devises docs state after signing in a user confirming the account or updating the password devise will look for a scoped root path to redirect example for a user resource it will use user root path if it exists otherwise default root path will be used this means that you need to set the root inside your routes root to homei am sorta a newbiehow does one go about generating this home root path for each user rdocs also mention object after sign in path forresource or scopethe default url to be used after signing in this is used by all devise controllers and you can overwrite it in your applicationcontroller to provide a custom hook for a custom resource by default it first tries to find a resource root path otherwise it uses the root path for a user scope you can define the default url in the following way mapuser root users controller users creates user root path mapnamespace user do user userroot controller users creates user root path endbut these just gives me undefined local variable or methodmap for actionthispatchroutingmappera errors,['ruby-on-rails'] +116193,can i execute custom actions after successful sign in with devise i have an app that has basic devise authentication after sign in i would like to look up the user account user belongs to account account has many users and store that in the session so that it is available like the current userwhat is the rails way of storing session in formation like thisis there a hook i can use with devise to execute code after successful signin,['ruby'] +116200,convert arrayofhashes to a hashofhashes indexed by an attribute of the hashes i have got an array of hashes representing objects as a response to an api call i need to pull data from some of the hashes and one particular key serves as an id for the hash object i would like to convert the array into a hash with the keys as the ids and the values as the original hash with that idheres what i am talking aboutapi response id 1 foo bar id 2 foo another bar ideal response 1 id 1 foo bar 2 id 2 foo another bar there are two ways i could think of doing thismap the data to the ideal response belowuse api responsefind x xid i for each record i need to accessa method i am unaware of possibly involving a way of using map to build a hash nativelymy method of mapping keys datamap x xid mapped hashkeyszipdataflatteni cannot help but feel like there is a more performant tidier way of doing this option 2 is very performant when there are a very minimal number of records that need to be accessed mapping excels here but it starts to break down when there are a lot of records in the response thankfully i do not expect there to be more than 50100 records so mapping is sufficientis there a smarter tidier or more performant way of doing this in ruby,['ruby'] +116213,help understanding jquerys jqueryfninit why is init in fn i was looking over the jquery to better understand how it works the constructor basically just calls new jqueryfniniti was wondering what is the point of having the init inside jquerys prototype wouldnt defining init as part of the jquery object itself serve the same purposebasically i would like to know why jquerys init function is located at jqueryfninit and not jqueryinitare there people doing thisjqueryaeq0hideinitdivslidetoggle,"['javascript', 'jquery']" +116238,merging a detached or new entity with an existing entity in hibernatejpa best practice question when the business layer creates a new entity which logically represents an instance of an existing entity that should be updated say they share the same business key is this method of merging bad practicepublic user adduser user user existinguser getuserdaofindbybusinesskeyusergetbusinesskey false usersetidexistingusergetid user getuserdaomergeuser return useri ask because setting the id explicitly on the detached entity feels pretty strange to me but even though the equals and hashcode method of the user entity are appropriately implemented setting the id here is the only way to ensure the merge takes placeis there a better practiceare there specific drawbacks to this method that would bite me later onthanks for taking a look,['java'] +116271,where is the class outline view in netbeans for php in eclipse i have a class outline view which shows me the members of my classi installed netbeans 691 but cannot find a window which shows me a list of the methods etc in the class i am working on where can i find this,['php'] +116315,php make a string upper case but not the html entities in it how can i make the content in a string to upper case but not the html entities in it is it possiblestr fundaenspmentalismecho strtoupperstri want to produce thisfunda mentalismbut i get this with strtoupperfundaenspmentalism,"['php', 'html']" +116329,why is gettype returning datetime type for nullable possible duplicatenullable type is not a nullable type in the following codedatetime dt datetimenowmessageboxshowdtgettypetostringthe message box shows systemdatetime instead of nullabledatetime the following also returns false because the gettype is wrongif dtgettypeisassignablefromtypeofdatetime btw using datetime or nullabledatetime does not make a differencein the watch window you have the type column that is thisplaying the correct type systemdatetimein my code i have reference to dt as an object so i need to get to the underlying type correctly how can i do this,"['c#', '.net']" +116331,how do i use admob on the android os using admob how can i give an advertisement in an android application,['android'] +116334,finding number of cores in java how can i find the number of cores available to my application from within java code,['java'] +116340,how can i add a unit test project to an existing mvc3 application from empty template i created an mvc3 application from the empty template so i couldna t add a visual studio unit test project to the solutioni made some changes added some controllers and now i want to try tdd so i need to add a framework for testingbut i cana t see how i can do thati want some way where i can create my test project right in the solution explorer for example websitetest with some basic folders and filesi saw here some questions about how to add unit tests but those were with xunitnet or nunit and i want the original vs test frameworki am using visual studio 2010 professionali am also interested to know what others think about the 3rdparty unit test frameworks are they betterwhat about for beginners,['c#'] +116342,how can i make phps fgetcsv to recognize the classic mac cr new line character i use this code to get the number of columns from a csv file thisdummy file handler fopenthisconfigfilerif dataset fgetcsvthisdummy file handler thisnumber of columns countdatasetit works fine unless the file is exported with excel for mac 2011 since the new line character is then classic mac cr which fgetcsv does not recognizeif i manually change the newline from classic mac cr to unix lr then it works but i need this to be automatedhow can i make fgetcsv recognize the classic mac cr new line character,['php'] +116348,maven3 mavenantrunplugin failed to create task or type if i am trying to use if ant tasks within maven buildi found many articles that suggest using antnodeps dependency eventually all this tricks did not work on maven3 ant 181 mavenantrunplugin 16an ant buildexception has occured problem failed to create task or type ifcan anything helpheres real code rather it is not necessary but just in case profiles profile idsmtpconfigurationprofileid activation activebydefaulttrueactivebydefault activation build plugins plugin groupidorgapachemavenpluginsgroupid artifactidmavenantrunpluginartifactid version16version executions execution phasevalidatephase goals goalrungoal goals configuration tasks if isset propertysmtpfile then delete fileprojectbuildoutputdirectorysmtpproperties copy filesmtpfile tofileprojectbuildoutputdirectorysmtpproperties then elseif isset propertysmtpprofile then delete fileprojectbuildoutputdirectorysmtpproperties copy filesrcmainresourcessmtpprofilesmtpproperties tofileprojectbuildoutputdirectorysmtpproperties then else delete fileprojectbuildoutputdirectorysmtpproperties copy filesrcmainresourcesproductionsmtpproperties tofileprojectbuildoutputdirectorysmtpproperties else elseif if tasks configuration execution executions dependencies dependency groupidorgapacheantgroupid artifactidantnodepsartifactid version181version dependency dependencies plugin plugins build profileprofiles,['java'] +116350,using fastcgi applications from within a c app i am developing a small webserver in c as part of a larger project the nature of the project prevents me from using something like apache nginx which would be my first choicethe webserver needs php to process some of the requests it recievesat the moment i am running php as a cgi using systemdiagnosticsprocess and piping data to and from this works but is pretty slow presumably from the overhead from php start starting from scratch is the main issue so i want to try using fastcgi insteadi have looked at the fastcgi spec and made a start at implementing a basic subset but have not have much luckmost of of the examples i have seen have been libraries for developing fastcgi modules not for invoking them so i have had very little to use as referencehas any one got any experience of doing this under net or could recommend any useful resources for this kind of project,"['c#', 'php']" +116352,php how can this variable inside one class be object of another one here is an exampleclass test public function testmethod print rthis gives me test1 object class test1 public function test1method testtestmethod test1 new test1test1test1methodi find this strange can anyone please explain to me why it happens,['php'] +116366,solution for cannot update project reference validating web site delay folks i have a an old aspnet website that i have to modify occasionallywhen i go to build or run the site i get cannot update project reference source project not availablevalidating web siteit then steps through each folder and page in the project validates it the site is quite sizable and can take 5 minutes on my beefy windows7 pcanyone any ideas how i can track down the project reference and get rid of this the validation is breaking my heart small change run wait 5 minutes test small change run wait 5 minutes gagaspnet is not my bag so forgive me if this is a school boy error,['asp.net'] +116368,is this a reasonable way to subclass a javascript array i realize that strictly speaking this is not subclassing the array type but will this work in the way one might expect or am i still going to run into some issues with length and the like are there any drawbacks that i would not have if normal subclassing were an option function vector var vector vectorsum function sum 00 fori 0 i thislength i sum thisi return sum return vector v vector vpush1 vpush2 consolelogvsum,['javascript'] +116387,scale background image to wrap content of layout i have a layout that contains some text fields and has a background image that is thisplayed at the top of my activity i would like the background image to scale to wrap the content do not care about aspect ratio however the image is larger than content so the layout instead wraps the background image heres my original coderelativelayout androidlayout widthfill parent androidididheaderlist androidlayout gravitytop androidlayout heightwrap content androidbackgrounddrawableheader textview androidlayout heightwrap content androidlayout widthwrap content androidididnametext androidtextjhn doe androidtextcolorf androidtextsize30sp androidlayout alignparentlefttrue androidlayout alignparenttoptrue androidpaddingleft4dp androidpaddingtop4dp textview androidlayout heightwrap content androidlayout widthwrap content androidtextcolorf androidlayout alignparentlefttrue androidididhourstext androidtext170 hours androidtextsize23sp androidlayout belowidnametext androidpaddingleft4dp relativelayoutafter searching through some other questions i found these twohow to wrap content views rather than background drawablescale a drawable or background imagebased on this i created a framelayout w an imageview showing the background unfortunately i still cannot get it to work i want the height of the background image to shrinkexpand w the size of the text views but with the framelayout the imageview fits to the size of it is parent and i cannot find a way to make the parent fit to the size the text view layout heres my updated codeframelayout androidlayout widthfill parent androidlayout heightwrap content imageview androidsrcdrawableheader androidlayout widthfill parent androidscaletypefitxy androidlayout heightfill parent relativelayout androidlayout widthfill parent androidididheaderlist androidlayout gravitytop androidlayout heightwrap content textview androidlayout heightwrap content androidlayout widthwrap content androidididnametext androidtextjohn doe androidtextcolorf androidtextsize30sp androidlayout alignparentlefttrue androidlayout alignparenttoptrue androidpaddingleft4dp androidpaddingtop4dp textview androidlayout heightwrap content androidlayout widthwrap content androidtextcolorf androidlayout alignparentlefttrue androidididhourstext androidtext170 hours androidtextsize23sp androidlayout belowidnametext androidpaddingleft4dp relativelayoutframelayoutdoes anybody have any suggestions for how best to make an image scale to the size of the contents of some layout i am not concerned with the aspect ratio of the image as it would not matter i just want it to fill the backgroundthanks,['android'] +116396,partial template specialization based on signedness of integer type giventemplatetypename tinline bool f t and return and 0 and 100 when used with an unsigned type generates a warningunsigned nf and warning comparison and 0 is always trueis there any clever way not to do the comparison n 0 when t is an unsigned type i tried adding a partial template specializationtemplatetypename tinline bool f unsigned t and return and 100 but gcc 421 does not like that i did not think that kind of partial template specialization would be legal anyway,['c++'] +116401,tuning gc for java audio application i have noticed that when playing audio in java marksweepcompact stage in gc is too long and results in short periods of silence which is unacceptable so i need to use a low pause gc i have tried parallel and cms they seem to work better because i suppose the pause is shorter and they do not do full collection as often as the default oneso far i have tested my program with the following options for parallelgcxxuseparallelgc xxmaxgcpausemillis70and for concurrentmarksweepxxuseconcmarksweepgcxxcmsincrementalmodexxcmsincrementalpacingi also tried g1gc but it is still experimental in java 6 options for both modesxms15mxmx40mxxunlockexperimentalvmoptionsxxcmsclassunloadingenabledxxtieredcompilationxxaggressiveoptsxxuseadaptivesizepolicydsunjava2dnoddrawfalsedswingaatexttruexxmaxpermsize25mxxmaxheapfreeratio10xxminheapfreeratio10which gc is better in this situation can any of these settings be optimized for best cpu performance and minimal memory usage as welledit to recognize the pause i record time to write audio data to the output line usually it is between 92 to 120 ms i am writing 16384 bytes 92ms ad when full gc is run it is 200 ms65424 full gc system psyounggen 872k0k2432k psoldgen 12475k12905k16960k 13348k12905k19392k pspermgen 15051k15051k272k 02145081 secs times user020 sys0 real021 secs was writing 16384 bytes time to write 263 msedit2 allocation pattern for my app is the following it loads bunch of objects at startup then it starts playing and i guess most of the objects after that are allocated by the gui because staringpausing the audio does not change the gc graph much this is what visualgc shows with parallel gcthe graph starts at startup and i start playback labeled are1 sound delay and full gc i think it increased old size101646 full gc psyounggen 64k0k6848k psoldgen 15792k12773k19328k 15856k12773k26176k pspermgen 15042k14898k23808k 02411479 secs times user019 sys0 real024 secs2 i open the app window and pause playback nothing really changes a bit later it increases eden size3 i open the windows and start playback againso i need to increase allocated old gen size how do i do that i am running with xxnewratio10 and xxnewsize10mthank you,['java'] +116408,language syntax diffsheet between java and c is there a language syntax diff cheatsheet that someone could point me that would thisplay the differences between something written in java and the same thing written in ci realize it is not going to be a onetoone feature set but from what i have seen the languages seem pretty closefor instance it would thisplay things like,"['c#', 'java']" +116412,how to automatically authenticate windows integrate without login popup i wrote an aspnet application with defaultaspx when i hit this page it is asking me windows login popup window my application should me windows authentication required but it should integrated windows authentication if i enter login password i am able to see my page how can i automatically integrate this windows authenticationi added below code in webconfig still does not workauthentication modewindows identity impersonatefalse authorization deny users authorization,"['c#', 'asp.net']" +116418,comparison interface methods vs virtual methods vs abstract methods what are the advantages and thisadvantages of each of theseinterface methodsvirtual methodsabstract methodswhen one should choose what what are the points one should keep in mind when making this decision,['c#'] +116421,getting the highest value of a column in mongodb i have been for some help on getting the highest value on a column for a mongo document i can sort it and get the topbottom but i am pretty sure there is a better way to do it i tried the following and different combinations transactionsfindid xmaxsellprice 0but it keeps throwing errors whats a good way to do it besides sorting and getting the topbottomthank you,['ruby'] +116437,alternative y combinator definition i have spent some time wrapping my head around the y combinator lately and i have found that it is usually defined more or less as follows this is in c but the language of choice is not importantpublic delegate tresult selfapplicabletresultselfapplicabletresult rpublic static tresult utresultselfapplicabletresult r return rrpublic static functarg1 treturn ytarg1 treturnfuncfunctarg1 treturn functarg1 treturn f return ufunctarg1 treturnr arg1 furarg1while that is perfectly functional pun intended it would seem that my definition is much simplerpublic static functarg1 treturn ytarg1 treturnfuncfunctarg1 treturn functarg1 treturn f return fn yfnis there any reason why the latter definition is not as common i have yet to find it on the net would it perhaps have something to do with defining y in terms of itself,['c#'] +116438,get iis bindings at runtime i wonder how to get the iis binding settings of the current site host name port ip address at runtime using aspnetdoes net provide any way to get these informationedit i need a way to get the http and https ports configured to redirect to the right port when switching from http to https and back from https to http if other ports then 80443 are used is there a way to do this without extended privilegesregards,['asp.net'] +116443,django template cannot loop defaultdict import collectionsdata firstname john lastname smith firstname samantha lastname smith firstname shawn lastname spencer new data collectionsdefaultdictlistfor d in data new datadlastnameappenddfirstnameprint new dataheres the outputdefaultdicttype list smith john samantha spencer shawnand heres the template for lastname firstname in dataitems h1 lastname h1 p firstnamejoin p endfor but the loop in my template does not work nothing shows up it does not even give me an error how can i fix this it is supposed to show the lastname along with the firstname something like this h1 smith h1p john samantha ph1 spencer h1p shawn p,['python'] +116446,where does iis 75 log errors where does iis 75 log errorsevent viewerlog filei get a very non specific internal 500 error i would like to find out morei am running php and i did what this last comment on this post said but still not logging to the cwindowstemp,['php'] +116457,can i use a lambda function or stdfunction object in place of a function pointer i have got a library that i need to use that defines the followingtypedef void callbackfunctionconst int iand has a function to register your callback that looks likevoid registercallbackcallbackfunction pcallbackbecause i would like to capture the state of several variables to be used in the callback i cannot simply use a plain function what i would prefer to use is a lambda function but the following does not compileauto fcallback const int i cout i endlregistercallbackfcallbackinstead i get the errorerror c2664 registercallback cannot convert parameter 1 from anonymousnamespacelambda0 to callbackfunction cdecl no userdefinedconversion operator available that can perform this conversion or the operator cannot be calledi have been reading up on this topic a lot and trying a few different probably idiotic approaches but i cannot seem to get this to work casting the function allows the code to compile but not surprisingly it crashes it may be that i have overlooked the solution either here on stackoverflow or elsewhere so a link will suffice though since i am a bit new to some of these techniques please make sure that the correspondence is clear enough for a newbie for instance if this conversation contains my answer i do not understand please simplify or explain the correspondence fyi i am using visual c 2010please let me know if there is anything i can do to clarify my question thanks in advance for the help,['c++'] +116459,sql query where all records in a join match a condition i have what seems to be a simple problem but can not figure out the proper solution via sql i am using postgresql specificallytake the followingselect from users inner join tags on tagsuser id usersid where tagsname in word1 word2this does not do what i need i want to find users whose tags are only included in the list if the user has a tag that is not in the list the user should not be includeduser1 tags word1 word2 word3user2 tags word1user3 tags word1 word2 given word1 and word2 i want to prepare a query that returns user2 and user3 user1 is excluded because it has a tag that is not in the listhopefully i made this clear thanks for your help,['sql'] +116461,how to get the location of the dll currently executing i have a config file that i need to load as part of the execution of a dll i am writingthe problem i am having is that the place i put the dll and config file is not the current location when the app is runningfor example i put the dll and xml file heredprogram filesmicrosoft team foundation server 2010application tierweb servicesbinpluginsbut if i try to reference the xml file in my dll like thisxdocument doc xdocumentloadaggregatoritemsxmlthen aggregatoritemsxml translates tocwindowssystem32inetsrvaggregatoritemsxmlso i need to find a way i hope of knowing where the dll that is currently executing is located basically i am looking for thisxdocument doc xdocumentloadcooldllclasscurrentdirectoryaggregatoritemsxml,"['c#', '.net']" +116473,pass this to a function hey guysi am trying to builda media playlist that can advance the credits play the video and change the title on thumbhover end of video and on nextprev click so i need to write some functions that can then be called together so like this function showbox thisparentscontainerfindboxshow function hidebox thisparentscontainerfindboxhide ahover function showbox function hidebox the problem is that this does not carry through to the functions from the hover how do i do thisthanks for the help,['jquery'] +116475,difference between list view and datagrid in wpf hey i have to retrieve some questions from the database and thisplay them on the user screen dynamicallyi also need to add some controls in the columns of grid viewbasically a question and input box for an answerplease suggest which one should i use list view or data grid,['.net'] +116480,c static vs instance methods i am risking it this might be a newb question but here goes i am tempted to add a method to a class that could possible have thousands and thousands of instances in memory at a given time now the other option is creating a static class with a static method and just create the static method there instead of an instance method in the class something like sothispublic static class petowner public static void renamepetpet pet string newname petname newname instead of thispublic class pet public string name get set public void renamestring newname thisname newname i am just wondering if the static class alternative would take considerably less memorythanks,['c#'] +116491,suppress wrapper object when serializing java object into json using jackson i have a web service that returns a list as json it uses jackson to map a list of java pojos into json the problem is that the json representation has a wrapper object around the array and i just want the array ie i am getting thisoptiondtolist when what i really want is this i am serializing the java list directly i am not wrapping the list with a wrapper object and serializing a wrapper object it is jackson that seems to be adding the javascript wrapper objecti assume there is some annotation i can use on the pojo to suppress the wrapper object but i am not seeing itconstraints on solutioni would like to fix this on the service side rather than peeling off the wrapper on the client the client is a jquery ui widget the autocomplete widget not that it matters that expects a simple array and i do not want to modify the widget itselfwhat i have triedi tried replacing the list of java pojos with an array of java pojos and the result is the samei tried jsontypeinfouse idnone thinking that that might suppress the wrapper but it did not,['java'] +116500,relative urls in ajax requests why does javascript treat relative urls differently than standard html think of the following url or just browse to it open a firebug console or another javascript console and enter the followingvar x new xmlhttprequestxopenget foo truexsendbarunder my system the request is sent to the rome in the url is simply ignored the same request with a trailing slash in the url appends the foo to the full urlthis seems to make it pretty hard to encode the correct urls in javascript are there any javascript libraries that help to overcome this problemi asked a similiar question before but more jquery specific where this also happens i hope i get a better answer with this somewhat more library independent question,['javascript'] +116502,how to open modaldialog on pageload how can i open a modal dialog on pageload in the constructor of the webpage and without the ajaxrequesttarget with wicket,['java'] +116509,ant classpath and junitjar i have the an buildxml that allows me to run junit tests here is the relevant partpath idjunit 4libraryclasspath pathelement locationeclipsepluginsorgjunit4 450v20090824junitjar pathelement locationeclipsepluginsorghamcrestcore 110v200905010710jarpathpath idmyprojectclasspath pathelement locationbin path refidjunit 4libraryclasspathpathtarget namerun unit tests dependsbuild mkdir dirjunitoutputdir junit printsummaryyes haltonfailureno classpath refidmyprojectclasspath formatter typexml batchtest todirjunitoutputdir fileset dirsrc include nametestjava fileset batchtest junittargetif i replace the linepathelement locationeclipsepluginsorgjunit4 450v20090824junitjarwith pathelement locationeclipsehomepluginsorgjunit4 450v20090824junitjarthe change breaks the classpath i get the following errorthe classpath for junit must include junitjar if not in ants own classpathas far as i understand the location attribute should hold the same value in both cases so what can be the reasonas a side question this build file will not work on an environment with different junit version the path will break is it possible to add a general path to junitjar,['java'] +116512,how to know density of device hias we can get the resolution in android but how can we know the density of the devicescreenthnakx,['android'] +116522,whats the best way to write a commandline app in java okay i know there are probably a dozen ways to solve this but i am looking for either a skeleton app or some sort of tutorial that will explain the best way to write a framework for creating javabased commandline tools if my program requires a lot of switchesoptionsetc whats the best way to handle all of them how do you decide which stuff should be placed into an optionssettings file and which stuff gets put on the command line any sort of sample code would be great that way i can put my time more towards the central focus of my app rather than the commandline plumbing,['java'] +116533,why does css padding increase size of element i am trying to give my div and textarea some padding when i do this it increses the size of the element instead of shrinking the content area inside of it is there any way to achieve what i am trying to dothanks for your help,"['html', 'css']" +116543,xpath axis get all following nodes until i have the following example of html lots of html h2foo barh2ploremppipsumppetcph2bar bazh2pdum dum dumpoopfiddlesp lots more html i am looking to extract all paragraphs following the foo bar header until i reach the bar baz header the text for the bar baz header is unknown so unfortunately i cannot use the answer provided by bougyman now i can of course using something like h2textfoo barfollowingp but that of course will grab all paragraphs following this header so i have the option to traverse the nodeset and push paragraphs into an array until the text matches that of the next following header but let us be honest that is never as cool as being able to do it in xpathis there a way to do this that i am missing,['ruby'] +116549,move constructor seemingly not executed this is my first experiment with c0x rvalue references and something strange seems to be going onin the code sample below the factory function makewindow returns a window object by value the caller uses it to initialize a window object if i understood correctly this should invoke the move constructor in order to detect this i throw an exception there on top of that i thisabled the copy constructorinclude iostream fake winapitypedef void hwndhwnd createwindow return void1 void destroywindowhwnd end winapi c winapi wrapper libraryclass windowpublic windowhwnd inhandle mhandleinhandle stdcout window constructor handle inhandle stdendl windowwindow rhs mhandlerhsmhandle stdcout window move constructor handle mhandle stdendl rhsmhandle 0 throw 1 this is my breakpoint window stdcout window destructor handle mhandle stdendl if mhandle destroywindowmhandle private windowconst window window operatorconst window hwnd mhandle factory functionwindow makewindow return windowcreatewindowint main window windowmakewindow stdcout everything is ok stdendl return 0however the code runs fine without this exception being thrown this is the console outputwindow constructor handle 0x1window destructor handle 0x1everything is okif i comment out the move constructor then compilation fails with the following errorsmysterymovecpp in function window makewindowmysterymovecpp395 error windowwindowconst window is privatemysterymovecpp4933 error within this contextmysterymovecpp in function int mainmysterymovecpp395 error windowwindowconst window is privatemysterymovecpp5735 error within this contextmake all error 1it does not seem to make sense can anyone explain what is going onupdatethanks to philipp i learned that move constructors can also be omitted this is described in a12834 and footnote 124 of the n3126 draft standardit is there also mentioned that rvo is only allowed for nonvolatile objects this means i can get around it writing the factory function like this factory functionwindow makewindow volatile window windowcreatewindow return const castwindowwindowand indeed it workswindow constructor handle 0x1window move constructor handle 0x1terminate called after throwing an instance of intabort trap,['c++'] +116555,how to read integers elegantly using c stream i have a file full of lines in this format1 2 3i want to only load numbers using c streams whats the most elegant way to do it i only thought about cinget and checikng each char if it is number or not,['c++'] +116564,rand implementation i would like to go through how rand and srand functions are implemented and would like to tweak the code to modify it to my requirements where can i find the source code of rand and srand,['c'] +116565,how to publish web site using psake is there a way to publish aspnet web application using psake just like visual studio do,['asp.net'] +116571,are there any tools out there to refactor the codingstyle of a java code base normally when doing some work on an existing project i would just go with whatever style is already established in the code base but our team has to maintain multiple small to medium sized projects which all differ slightly in coding style it would be more efficient and less confusing if we could cleanup these differences so i am looking for a tool that allows me to refactor the existing style lots of features are already provided by standard code formatting tools like changing the indentation style what i am missing is a tool that allows me to strip the prefixes of field and parameter names in some projects all members are prefixed with m all parameters are prefixed with p and static members are prefixed with s the tool should be able to handle cases like void setvaluestring pvalue mvalue pvaluewhich should become void setvaluestring value thisvalue valuethe tool should generate a warning in a case like this void setvaluestring pvalue int value 42i know every major ide provides the refactor rename feature what i am looking for though is a tool which processes a whole code base without me needing to go over each parameterfield individually edita lot of the answers mention tools to reformat source code or check the code base against a set of style rules i am aware that those tools exist what i am specifically looking for is an advanced tool that allows me to remove scope specific variable name prefixes,['java'] +116587,issues playing a video with monotouch i am having a few issues playing a video in monotouch from what i can find there are two different approaches to take both result in the audio being played but no video i am betting i am missing something simple so any help would be greatattempt one taken from mt documentationmovieplayer new mpmovieplayercontrollernew nsurltestmp4 movieplayerplayattempt twomovieplayer new mpmovieplayerviewcontrollernew nsurltestmp4 thispresentmovieplayerviewcontrollermovieplayerthanks,['iphone'] +116588,android install apk programmatically is it possible to install an apk programmatically in the background or does the user have to accept the installation my scenario is that i want my employees to all have the same set of applications installedof course they can install applications by them self but i want them all to have at least some applications installedi am not talking about installing applications from the market,['android'] +116592,android and xmpp currently available solutions i would like to pose a question as to which xmpp library would be the best choice nowadays for android developmenti have been using the patched smacklibrary from here as issuggested in many other questionshere in so however that is a patched version ofthe smack api from two years ago andalthough it generally works well i amexploring any other more recentoptionsi have been looking at the officialsmack api and after a littleresearch it seems it might work justfine nowadays although i have nottried it yet in a real applicationthere is also another solution i cameacross beems asmack librarybeem is a fairly new xmpp client forandroid and from what i understandthey are using their own patchedversion of asmackfinally there is asmack but thattoo has not been updated for quitesome time as the site suggestsdo you have any other suggestions or can you explain why i should choose one of the above over the rest,['android'] +116622,anonymous inner classes in c i am in the process of writing a c wicket implementation in order to deepen my understanding of c and wicket one of the issues were running into is that wicket makes heavy use of anonymous inner classes and c has no anonymous inner classesso for example in wicket you define a link like thislink link new linkid override void onclick setresponsepage since link is an abstract class it forces the implementor to implement an onclick methodhowever in c since there are no anonymous inner classes there is no way to do this as an alternative you could use events like thisvar link new linkidlinkclick sender eventargs setresponsepageof course there are a couple of drawbacks with this first of all there can be multiple click handlers which might not be cool it also does not force the implementor to add a click handleranother option might be to just have a closure property like thisvar link new linkidlinkclick setresponsepagethis solves the problem of having many handlers but still does not force the implementor to add the handlerso my question is how do you emulate something like this in idiomatic c,"['c#', 'java']" +116650,js functions arguments default values in some languages you can set default values for functions argumentsfunction fooarg1 50 arg2 default how do you do it in javascript,['javascript'] +116656,how do i create a pip requirements file for a tarball on my local filesystem tell me if what i am trying to do does not make sensei want to create a virtual environment that among other things includes mysqldb 123 this library is thistributed as a gzipped tarball tgz file i want to install everythingaincluding tarballs on my local filesystemafrom a requirements file in requirementsappstxt this is based on a setup i saw in pippy install e ve enablesitepackages requirement requirementsappstxti could not find any documentation on the pip requirements file format for local files what does the requirements file appstxt need to contain if the directory requirements contains the file mysqlpython123tgz,['python'] +116667,catching commandline errors using x whenever you want to execute something on the command line you can use the following syntaxxcommand to runhowever i want to catch an error or at least get the response so i can parse it correctly i tried settingresult xcommand to runand using a trycatchbegin xcommand to runrescue did not workendto no avail how can i capture the results instead of having them printed out,['ruby'] +116674,how to set up pdftk or itext to work with rails 3 on heroku i am trying to find a way to inject fdf file content into a fillable pdf file provided by customer and not supposed to be redrawn using prawn or pdfkit and i think i have to use either itextwith jruby or pdftk both of these libs work with no problem on my ubuntu local machine but i am wondering how i would get either them to work on heroku has anyone tried to get itextjruby or pdftk to work on heroku thanks for your help,['ruby-on-rails'] +116680,how to run sql scripts from a pl sql procedure i have a procedure like create or replace procedure test is begin dbms outputput linethis is a testendi want to run some sql scripts stored in the current directoryi could run them from sqlplus with scriptnamesql but how can i do it from inside the procedure for excreate or replace procedure test is begin dbms outputput linethis is a test scriptnamesqlendthis does not seem to work is there a specific to run sql scripts from plsql procedures,['sql'] +116691,explain this snippet which finds the maximum of two integers without using ifelse or any other comparison operator find the maximum of two numbers you should not use ifelse or any other comparison operator i found this question on online bulletin board so i thought i should ask in stackoverflowexampleinput 5 10output 10i found this solution can someone help me understand these lines of codeint getmaxint a int b int c a b int k c 31 0x1 int max a k c return max,['c'] +116724,tomcat jdbc connection pool vs c3p0 connection pool i recently came across this connection pool implementationi find it quite interestingdid anyone try this out i think it looks great except the fact that it does not support automatic retry and statement cache like c3p0does anyone one know how it compares to c3p0 till now i used c3p0 but i find it is connection handling in a multithread environment problematic it opens way too much connections compared to number of application threadsthanks,['java'] +116733,use of rvalue reference members i was wondering what use an rvalue reference member hasclass a is this one useful foo fdoes it have any benefits or drawbacks compared to an lvalue reference member what is a prime usecase of it,['c++'] +116740,how to find the child class name from base class at runtime inside base class how to find the current child class name,['c#'] +116747,icon overlay issue with python i found some examples and topics on this forum about the way to implement an icon overlay handler with python 27 the win32com package but it does not work for me and i do not understand why i create the dll and i have no error when i register it i have also tried directly with the script but it is the same it is like the class is never calledhere is the codeimport win32traceutilfrom win32comshell import shell shellconimport pythoncomimport winerrorimport osreg path rsoftwaremicrosoftwindowscurrentversionexplorershelliconoverlayidentifiersreg key gdiconoverlaytestclass gdclass reg clsid 512ae200f07541e697dd48eca4311f2e reg progid gdtestserver reg desc gd desc public methods getoverlayinfogetpriorityismemberof com interfaces shelliid ishelliconoverlayidentifier pythoncomiid ithispatch def init self pass def getoverlayinfoself return ospathabspathrciconstestico 0 shellconisioi iconfile def getpriorityself return 0 def ismemberofself fname attributes printismemberof fname ospathbasenamefname if ospathbasenamefname hellotext return winerrors ok return winerrore faildef dllregisterserver print registering s reg key import winreg key winregcreatekey winreghkey local machine reg path subkey winregcreatekeykey gdclass reg progid winregsetvalueexsubkey none 0 winregreg sz gdclass reg clsid print registration complete s gdclass reg desc def dllunregisterserver print unregistering s reg key import winreg try key winregdeletekey winreghkey local machine rss reg path gdclass reg progid except windowserror details import errno if detailserrno errnoenoent raise print unregistration complete s gdclass reg desc if name main from win32comserver import register registerusecommandlinegdclass finalize register dllregisterserver finalize unregister dllunregisterserverhi and thanks for your answeri have tested with a log file and also win32traceutil the registrationunregitration messages are logged the registry entries are also created under1hkey local machinesoftwaremicrosoftwindowscurrentversionexplorershelliconoverlayidentifiersgdtestserver 2 hkey local machinesoftwaremicrosoftwindowscurrentversionshell extensionsapproved3 directly under class rooti have also added some logs inside the methods getoverlayinfo getpriority and ismemberof but i cannot see a trace when i browse through the explorermy configuration ispython 27pywin32214win32py27exewindows xp sp 2you can download all the code here,['python'] +116761,mysql how to insert values in a table which has a foreign key i have these two tables just for exampletab teacher id teacher primary key autoincrement name teacher a varchartab student id student primary key autoincrement name student a varchar id teacher fk foreign key reference to a teacher tab teacheri want to know how to insert in these two casescase 1 insert a new student with an preexistin teacher so i have to get the foreign key with a teacher namecase 2 insert a new student with a new teacher the teacher i am creating in the same time i am creating the student,['mysql'] +116764,android moving background image while navigating through views after searching for days to find a solution for my current problem i am addressing to you what i want to have is a background image which behaves like the stock homescreen or the weather app here youtubecomwatchvi2oh4gl5wbet0m54si just need a not animated background image like the road in that video which scrolls a bit while swiping to another viewin my app i would like to swipe through some listviews with a scrolling backgroundwhat i have testedviewflipper i used big image and cut it vertically into 5 pieces then i set those cutted images in each layout thisplaying the listviews as background horizontalscrollview in the horizontalscrollview i added a linearlayout and set the big image as background then i used gesturedectector to add snapping when swiping through the listviewsboth worked but that requires a really big image and i am not sure if it scales correctly to different screen sizes also it does not behave like the original homescreen where the background moves just a little bit while the foreground changes to the next viewi read the post here i checked the recommended launcherjava which led me to the workspacejava ablobfsrccomandroidlauncher2workspacejavaas far as i understand it uses the wallpapermanager by setting offsets mwallpapermanagersetwallpaperoffsetsgetwindowtoken mathmax0f mathminmscrollxfloatscrollrange 1f 0api says setwallpaperoffsetsibinder windowtoken float xoffset float yoffset set the position of the current wallpaper within any larger space when that wallpaper is visible behind the given windowbut as far as i understand this just changes the background image of the phone itselfwhat can i do do you know an open source application or sample code which does the sameprobably i have to draw canvas myself never did before please give me some advice,['android'] +116765,relationship between the rails cookie object the cookie http header and documentcookie when i access documentcookie in javascript it spits out sayuser credentials5beea8874f2db9feb873828basically what appears to be some encoded information finewhen i look at the headers i do see that exact same string being set to user credentials but there is also another value being set for myapplication sessionbah7ciiqx unlike with user credentials this one includes capital letters and letters after fsowhat is myapplication session is this related to the session object in railswhy does not myapplication session show up with javascript documentcookie,"['javascript', 'ruby-on-rails']" +116769,sql give me 3 hits for each type only i have some kind of impossible request i have a table where one of the columns is named type i would like to select 3 records for each type in that column is that possiblenote also that i am using mysql and sphinxupdatetable structureid title type1 a string12 c string23 e string24 d string25 f string26 b string26 b string2what i want my mysql to return is up to 3 records for each type ordered by titleid title type1 a string16 b string22 c string24 d string2,"['sql', 'mysql']" +116778,pass by reference and value with pointers i do not understand why passing a pointer to a function does not change the data being passed in if the function proto looked like this void func int p and func allocated memory to p why cannot it be used outside of the function i thought that pointers were addresses,['c++'] +116799,why does imageviewsetimagematrix not work i want to rotate an image using imageviewsetimagematrixmatrix but it simply does not have any effecti call matrixpostrotate45 20 20 before passing it to the function above but no effect the image is not rotated whymatrixpostrotate45 20 20imageviewsetimagematrixmatrix,['android'] +116802,should setting an image src to data url be available immediately consider the following fragile javascript codevar img new imageimgsrc dataimagepngbase64 assume valid data danger attempting to use image immediately after setting srcconsolelog imgwidth imgheight somecanvascontextdrawimage img 0 0 danger setting onload after setting srcimgonload function consolelogi ran the questionsshould the image width and height be correct immediatelyshould the canvas draw work immediatelyshould the onload callback set after the src was changed be invokedexperimental testsi created a simple test page with similar code in safari my first tests both by opening the html page locally file url and loading it from my server showed everything working the height and width is correct the canvas draw works and the onload also firesin firefox v36 os x loading the page after launching the browser shows that the heightwidth is not correct immediately after setting drawimage fails the onload handler does fire however loading the page again however shows the widthheight being correct immediately after setting and drawimage working it would appear that firefox caches the contents of the data url as an image and has it available immediately when used in the same sessionin chrome v8 os x i see the same results as in firefox the image is not available immediately but takes some time to asynchronously load from the data urlin addition to experimental proof of what browsers the above does or does not work i would really love links to specs on how this is supposed to behave so far my googlefu has not been up to the taskplaying it safefor those who do not understand why the above might be dangerous know that you should use images like this to be safe first createfind the imagevar img new image then set the onload handlerimgonload function use the forsureloaded img here then set the srcimgsrc,"['javascript', 'html']" +116811,android sample microphone without recording to get live amplitudelevel i was trying to get the amplitude level of a microphone on android like somediarecorder recorder new mediarecorderrecordersetaudiosourcemediarecorderaudiosourcemictimer timer new timertimerscheduleatfixedratenew recordertaskrecorder 0 10private class recordertask extends timertask private mediarecorder recorder public recordertaskmediarecorder recorder thisrecorder recorder public void run logvmicinfoservice amplitude recordergetmaxamplitude unfortunately this only returns 0 all the timeit appears that for this to work i have to actually start recording is that correctif so do i need to record for 500ms get amplitude stop recording and repeatfinally do i have to record to a file i do not need to save this audio file cannot i just get the current amplitude or highest amplitude since last call of the current live microphone input without recordingany help is appreciated thanks,"['java', 'android']" +116812,hamming thistance on binary strings in sql i have a table in my db where i store sha256 hashes in a binary32 column i am looking for a way to compute the hamming thistance of the entries in the column to a supplied value ie something likeselect from table order by hammingthistancehash unhexinsert supplied sha256 hash here asc limit 10in case youre wondering the hamming thistance of strings a and b is defined as bit countab where is the bitwise xor operator and bit count returns the number of 1s in the binary stringnow i know that both the operator and bit count function only work on integers and so i would say that probably the only way to do it would be to break up the binary strings in substrings cast each binary substring to integer compute the hamming thistance substringwise and then add them the problem with this is that it sounds terribly complicated not efficient and definitely not elegant my question therefore is could you suggest any better way please note that i am on shared hosting and therefore i cannot modify the db server or load librariesedit1 obviously loading the whole table in php and doing the computations there would be possible but i would rather avoid it because this table will probably grow quite largeedit2 the db server is mysql 51edit3 my answer below contains the code that i just described aboveedit4 i just found out that using 4 bigints to store the hash instead of a binary32 yields massive speed improvements more than 100 times faster see the comments to my answer below,"['sql', 'mysql']" +116821,how to assign a c struct inline typedef struct int hour int min int sec counter tand in the code i would like to initialize instances of this struct without explicitly initializing each member variable that is i would like to do something likecounter t countercounter 103047 does not workfor 103047rather thancounterhour 10countermin 30countersec 47do not recall syntax for this and did not immediately find a way to do this from googlingthanks,"['c++', 'c']" +116829,multiple slickgrid in jquery tabs i am creating multiple slickgrids and puts them in a jquery tabthe first slickgrid on the first jquery tab works fine but when i switch to the next tabthe data columns on the slickgrid does not show up until you resize the header and the columns are not aligned to the header is there any way i can fix thisheres my code exerpul classtabs lia hreftab 1fadf monoali lia hreftab 2badf monoali lia hreftab 3badf coloraliuldiv classtab container div idtab 1 classtab content div idslickgrid 1div div div idtab 2 classtab content div idslickgrid 2div div div idtab 3 classtab content div idslickgrid 3div divdiv,['jquery'] +116833,how to thisplay utf8 characters in phpmyadmin i have my database properly set to utf8 and am dealing with a database containing japanese characters if i do select from the mysql command line i properly see the japanese characters when pulling data out of the database and thisplaying it on a webpage i see it properlyhowever when viewing the table data in phpmyadmin i just see garbage text iea a a12a aahow can i get phpmyadmin to thisplay the characters in japanesethe character encoding on the html page is set to utf8editi have tried an export of my database and opened up the sql file in geany the characters are still garbled even though the encoding is set to utf8 however doing a mysqldump of the database also shows garbled charactersthe character set is set correctly for the database and all tables latin is not found anywhere in the filecreate database japanese default character set utf8 collate utf8 general cii have added the lines to mycnf and restarted mysql but there is no change i am using zend framework to insert data into the databasei am going to open a bounty for this question as i really want to figure this out,['mysql'] +116834,how to implement ssl in zend mvc i have implemented secure pages before by using a specific secure folder eg https folder vs http folder on the server i have started using zend framework and would like parts of the application eg login to use https i have searched on google and even here but could not find anything that explains how to handle this can i have https for specific controllersactions thanks,['php'] +116854,which language that runs on jvm is best suited for creating a dsl we have a requirement to create complex fixed length and variable length strings these strings might represent a customer profile an order etc which jvm based programming language do you guys suggestidea is for a end user to create the strings using this dsl so i am looking for validation code completion etc,['java'] +116866,how to send key event to an edit text for example send a backspace key to the edit text control to remove a character or send a char code like 112 to append a character in the edittext control programmaticallyactually i need a method likevoid onkeyreceivedint keycode here i would like to append the keycode to edittext i know how to add a visible character but what about some special keys like arrow key backspace key,"['java', 'android']" +116872,how to create a button in uiview programmaticaly in iphone i am new to iphone development in my application i want to add next and previous buttons in uiview programmaticaly in iphone i want help with you for this problemcan any one please give me information about itthank you in advance,['iphone'] +116878,browse for folder dialog i need to know how to get the browse for folder dialog in java i am aware of swt but i need to do in swing is there any solution to thisas we start on eclipse it will ask for choose workspace we can see the browse for folder dialog at that timethanks in advance,['java'] +116887,is static method faster than nonstatic editoh i forgotclass test1 public static function test fori0 i10 i j i class test2 public function test for i0 i10 i j i for this algorithmtime start microtimetest1 new test2fori0 i100i test1testtime end microtimetime1 time end time starttime start microtimefori0 i100i test1testtime end microtime time2 time end time starttime time1 time2echo difference timei have resultsdifference 07561 and these days i am trying to make my methods static as possible but is it really true atleast for php,['php'] +116902,secure c coding practices i am looking for a comprehensive record of secure coding practices in csince i have not found such a list existing here already we might as well make this into a community wiki for further referencei am looking for solutions to security issues like stack and heap based buffer overflows and underflows integer overflows and underflows format string attacks null pointer dereferencing heapmemory inspection attacks etcnb besides coding practices secure libraries that defend against these kind of attacks are worth mentioning toole as suggested by msalters in comments this question has been split into two separate questions one for c and one for calso see secure c coding practices,['c++'] +116910,how to set background color in jquery how to set background color of td in jqueryeg thiscssbackgroundcolorredthanks,"['jquery', 'css']" +116920,jpanel keylistener i am trying to add a key listener that holds a jtabbedpaneit should switch the tabs when ctrl tab is receivedbut the keypressed event is never sent i tried adding it to the panel and to the tabbed object but with no success here is my code switchtabslistener ctrltablistener new switchtabslistenergenerictabbedpanel jmainframeaddkeylistenerctrltablistener generictabbedpaneladdkeylistenerctrltablistener,['java'] +116925,how to make an array of arrays in java this may seem like a noob question but this is a serious question hypothetically i have 5 string array objectsstring array1 new stringstring array2 new stringstring array3 new stringstring array4 new stringstring array5 new stringand i want another array object to contain those 5 string array objects how do i do it can i put it in another array,['java'] +116931,android upload photos greetingsi am having trouble uploading a photo from my android phone here is the code i am using to prompt the user to select a photopublic class uploader public void upload logieohhi intent photopickerintent new intentintentaction get content photopickerintentsettypeimage startactivityforresultphotopickerintent 1 protected void onactivityresultint requestcode int resultcode intent data if resultcode result ok bundle extras datagetextras bitmap b bitmap extrasgetdata what do do now with this bitmap how do i upload it so i have the bitmap b however i do not know what to do nexti have the following code for sending post requestslistnamevaluepair params new arraylistnamevaluepair2 paramsaddnew basicnamevaluepairsomevala stringvalueoflat paramsaddnew basicnamevaluepairsomevalb stringvalueoflng new httpconnectionhandlerpostparamshow can i hook up a bitmap image to this i have searched google for ages and cannot find a good way of doing iti hope someone can helpmany thanks in advanceok i have tried chirag shahs suggestion here is my codeprotected void onactivityresultint requestcode int resultcode intent data if resultcode result ok uri imageuridatagetdata listnamevaluepair params new arraylistnamevaluepair1 paramsaddnew basicnamevaluepairimage imageurigetpath postparams where the post function as recommended ispublic void poststring url listnamevaluepair namevaluepairs httpclient httpclient new defaulthttpclient httpcontext localcontext new basichttpcontext httppost httppost new httpposturl try multipartentity entity new multipartentityhttpmultipartmodebrowser compatible forint index0 index namevaluepairssize index ifnamevaluepairsgetindexgetnameequalsignorecaseimage if the key equals to image we use filebody to transfer the data entityaddpartnamevaluepairsgetindexgetname new filebodynew file namevaluepairsgetindexgetvalue else normal string data entityaddpartnamevaluepairsgetindexgetname new stringbodynamevaluepairsgetindexgetvalue httppostsetentityentity httpresponse response httpclientexecutehttppost localcontext logieohresponsetostring catch ioexception e eprintstacktrace however myurlcomajaxuploadphotophp is getting nothing i have created a php log to log any activity on uploadphotophp and nothing is showing up it is worth noting that if i just type myurlcomajaxuploadphotophp straight into a web browser it logs fineany more suggestionsmany thanks,['android'] +116936,jquery how to get all stylescss defined within internalexternal document with html of an element i know that dividhtml will give me innerhtml i also need its styles which might be defined by the means of classes either inline style attribute or all the stylesclasses within a separate style tagis it possibleupdatewhat if html is like div idtestdivcfwcvbdiv and a css class for testdiv is defined in external stylesheetupdate 2sorry for not clarifying this earlierif this is my htmldiv iddivid span clasomeclasome innertextspandivand styles are defined in separate style sheet or in head stylesdivid clear both padding 3px border 2px dotted c fontsize 107 lineheight 130 width 660pxsomeclass color bluethen when i try to get inner html of dividhtml or call any other custom function i need something like belowstyledivid clear both padding 3px border 2px dotted c fontsize 107 lineheight 130 width 660pxsomeclass color bluestylediv iddivid span clasomeclasome innertextspandivupdate 3 for answer by kirilloidi ran below code in command window of chrome debugger tools for this page itself and this is what i see typeerror cannot read property rules of undefinedfunction getelementchildrenandstylesselector var html selectorget0outerhtml selector selectorsplitmapfunctionsubselector return subselector subselector join elts selector var rulesused main part walking through all declared style rules and checking whether it is applied to some element sheets documentstylesheets forvar c 0 c sheetslength c var rules sheetsirules sheetsicssrules forvar r 0 r ruleslength r var selectortext rulesrselectortext var matchedelts selectortext for var i 0 i eltslength i if matchedeltsindexeltsi 1 rulesusedpushcssrule break var style rulesusedmapfunctioncssrule if browsermsie var csstext cssrulestylecsstexttolowercase else var csstext cssrulecsstext some beautifying of css return csstextreplacesg 1n replaceas set indent for css here joinn return stylen style nstylenn htmlgetelementchildrenandstylesposttextfirst,"['javascript', 'jquery', 'css']" +116937,set the default value in dropdownlist using jquery i have many options in my dropdownlist likeoption value1it is meoptioni need to select the option who have value it is me inside the tag not by attribute like 1how can i do this using jquery,"['javascript', 'jquery', 'html', 'css']" +116964,just got my app rejected because it ask the user to register on startup any help i have just received an email from apple saying that the app i submitted to the app store a week ago has been rejected the text of the email is reprinted belowthank you for submitting idealwine app to the app store a weve completed the review of your app however we cannot post this version to the app store because it requires customers to register with personal information without providing accountbased features applications cannot require user registration prior to allowing access to app features and content such user registration must be optional and tied to accountbased functionality as required by the app store review guidelines a a a a a 172a a apps that require users to share personal information such as email address and date of birth in order to function will be rejected a additionallya we need additional information about your app and in app purchase a please take some time to review the following questions and provide as detailed information as you canplease provide more information on the length of the subscription provided by idealwine appwhere is the in app purchase locatedif you have any questions about this information or would like to thiscuss it further please feel free to reply to this email a to appeal this review please submit a request to the app review board at we look forward to reviewing your revised appthe first reason is clear enought but i still wonder if just adding an alternative for the user to signin using an existing loginpassword will solve the issue so there will be login or register alternativefor the second reason i do not understand why they have rejected the inapp purchasehas anyone had this issue before,['iphone'] +116966,background image cut off beyond viewport url for the unruly site after we put it live we thiscovered that if the viewport is too small for the content so as to require scrolling the background image bodytag repeatx would not extend beyond the initial view but i cannot for the life of me figure out why and how to fix it a note to bear in mind is that i did not code the site by myself since i am not that javascriptsavvy and the designers wanted some swooshy effects my senior colleague could surely find a remedy but he is unfortunately away and i would like to wrap this upthe state of the html and css is the same as when i found out about the issue but i have tried suggestions i have seen on similar questions mainly revolving around minwidth i do not really understand the difference between and my problemfull view iimgurcom6adpnjpgproblem iimgurcomx6jvpjpg,"['html', 'css']" +116996,finding bottlenecks in javascript i am attempting to find a bottleneck in my javascript basically i am developing a chrome extension written in javascript which is taking 45 seconds to perform a task there is a lot of code involved in the task and using print statements chrome built in dev tools just isnt working the dev tools do not seem to even see my javascript running i am wondering if anyone has any advice tools they think could be of benefit,['javascript'] +117003,oracle sql query to format number by comma guys i want to print the following data with comma separated values using oracle sql696585242087to 696585242087and same for the decimal,['sql'] +117007,install tkinter for python i am trying to import tkinter however i get an error stating that tkinter has not been installedimporterror no module named tkinter please install the pythontk packagei could probably install it using synaptic manager can i however i would have to install it on every machine i program on would it be possible to add the tkinter library into my workspace and reference it from there,['python'] +117011,call method when home button pressed on android so i have this method in one of my android activitiesoverridepublic boolean onkeydownint keycode keyevent event ifkeycode keyeventkeycode back logdtest back button pressed else ifkeycode keyeventkeycode home logdtest home button pressed return superonkeydownkeycode eventbut even though the keycode home is valid the log method never fires this works for the back button though does anyone know why this is and how to get this to workthanks,['android'] +117017,spring tomcat and static resources and mvcresources i started doing a web app from scratch before i have always been working on apps that were already running for a long time so i did not have to deal with the full setup phase i am using spring 3 and tomcat 6 and i am using eclipse 36i have a big problem with serving images or other things different from controller responses in fact i cannot find a way to have my images in my jsps my configuration works with servletmapping servletnamespringthispatcherservletname urlpatternurlpattern servletmapping in webxml and bean nameaccise classitjsoftwarejaccisewebcontrollersmaincontrollerbeanfor the servlet context plus other of course i have read many messages here and other forums talking about thismvcresources mappingresources locationresources but if i insert that in my servletcontextxml i will be able to serve images yet the controller accise would not be reachable am i misusing or i misunderstood the resources tag whats the correct wayupdate solution found the problem was that my servletconfigxml missed one declarationnow it isusing annotations on the controllerxml version10 encodingutf8beans xmlns xmlnsxsi xmlnsmvc xmlnscontext xmlnsaop xmlnstx xsischemalocation contextcomponentscan basepackageitjsoftwarejaccisewebcontrollerscontextcomponentscan mvcannotationdriven bean classorgspringframeworkwebservlethandlerbeannameurlhandlermapping mvcresources mappingresources locationresources,['java'] +117053,why does posix specify wctomb as nonthreadsafe but not mbtowc in xsh 291 wctomb is listed as one of the functions which is not required to be threadsafe however the opposite conversion function mbtowc does not appear in the list on an implementation with encodings that use shift states neither has a threadsafe api and it makes no sense that one is required to be threadsafe and the other is not while neither can be threadsafe without forbidding stateful encodingslikewise for wcstombs which is in the list and mbstowcs which is not since both of these functions operate on entire strings which begin and end in the initial shift state they are not stateful their apis are threadsafe and again it makes no sense that one direction is specified to be threadsafe but not the othercan anyone shed some light on this,['c'] +117101,java calculate days in year is there a method in any native java class to calculate how many days werewill be in a specific year as in was it a leap year 366 days or a normal year 365 daysor do i need to write it myselfi am calculating the number of days between two dates for example how many days left until my birthday i want to take into account the february 29 of leap year i have it all done except that 29th,['java'] +117102,does django have a way to open a http long poll connection leave the connection open until an event occurs,['python'] +117133,boostspiritqi and outofsequence variables i am writing a lexigraphical analyser it takes an english string and converts it into a set of latitudelongitude coordinates it is a bit like google earthanyway i have written my symbol tables and grammar and it is happily parsing formatted data struct latlongdegrees stdstring dirlat double deglat stdstring dirlong double deglong for example north 2359 east 3082here is my grammar basic latitude double longitude double where latitude and longitude are symbol tables that map from shorthand compass directions to strings eg e to east so on to my questioni want to add the following rule to my grammar where the latitude and longitude symbols are in the opposite positionsreversed longitude double latitude double this parses but the deglat and deglong values are not reversed along with string values they are simply parsed directly into the struct without regard for the string labelshow do i build a struct or boostfusion vector when the data to be parsed is not sequential,['c++'] +117134,how to monitor the cpu usage of a php script how can i do thathow do share hosts limit the cpu time for a script,['php'] +117154,programatically setting max java heap size is there a way to set the max java heap size programatically instead of as a vm argumentsomething likesystemgetpropertiesputheap variable 10m,['java'] +117166,how to center a twoline text in a textview on android i want to let it looks like this two lines here is the current layout not working at allrelativelayout androidlayout widthwrap content androidlayout heightwrap content androidgravitycenter vertical textview androidlayout widthwrap content androidlayout heightwrap content androidtexttwonlines androidlayout gravitycenter vertical androidlayout centerinparenttruerelativelayoutany ideathanks,['android'] +117175,what is the size of empty class in cjava what is the size of an empty class in c and javawhy is it not zerosizeof returns 1 in the case of c,"['java', 'c++']" +117179,what does a backslash do in php 53 what does a do in phpi was reading the following code which has it all over the place the link will bring you to one of the lines which contains it,['php'] +117188,no newline after div is there a way to not have a newline inserted before a div without using float left on the previous element maybe some tag on the div that will just put it to the right,['html'] +117189,how do i require https for this django view rlogindjangocontribauthviewslogintemplate nameloginhtml authentication formcustomauthenticationformhow do i add https required to this i usually have a decorator for itbut in this case i cannot apply itdef secure requiredview func decorator makes sure url is accessed over https def wrapped view funcrequest args kwargs if not requestis secure if getattrsettings https support true request url requestbuild absolute urirequestget full path secure url request urlreplacehttp https return httpresponseredirectsecure url return view funcrequest args kwargs return wrapped view func,['python'] +117201,interface abstract class coding standard i spotted a proposed c codingstandard which stated try to offer an interface with all abstract classes does someone know the rationale for this,"['c#', '.net']" +117211,delete newline return carriage in file output i have a wordlist that contains returns to separate each new letter is there a way to programatically delete each of these returns using file io in python edit i know how to manipulate strings to delete returns i want to physically edit the file so that those returns are deletedi am looking for something like thiswfile openwordlisttxt r for line in wfile if lenline 0 note the following is not real this is what i am aiming to achieve wfiledeleteline,['python'] +117213,how do i start a program with arguments when debugging i want to debug a program in visual studio 2008 the problem is that it exits if it does not get arguments this is from the main methodif args null argslength 2 args0touppertrim rm consolewritelinerm must be executed by the rsm consolewritelinepress any key to exit program consoleread environmentexit1i do not want to comment it out and and then back in when compiling how can i start the program with arguments when debugging it is set as the startup project,['c#'] +117219,route handlers inside a class i have a sinatra app setup where most of the logic is performed inside of various classes and the postget routes instantiate those classes and call their methodsi am thinking about whether putting the postget route handlers inside of the classes themselves would be a better structure in any case i would like to know if it is possible so for instanceclass example def say hello hello end get hello do message say hello endendwithout modification to the above sinatra will say there is no method say hello on the sinatraapplication object,['ruby'] +117224,convert nsstring to nsinteger i want to convert string data to nsinteger,['iphone'] +117231,how can i make my cursor survive an orientation change i am trying to make my app rotation friendly but i am having some problems saving the cursorthe cursor holds about 13k rows of data thisplayed in a listview and thus would take quite a while if i would do a requery every time the configuration changes in my onretainnonconfigurationinstance i am returning my cursor and then retrieving it through getlastnonconfigurationinstancehowever my retrieved cursor seems to be closed already and thus my adapter cannot render the list anymore from what i understand the cursor was closed since ondestroy automatically closes all cursorsi save the cursor like thisoverridepublic object onretainnonconfigurationinstance return mycursorand retrieve it like thismycursor cursorgetlastnonconfigurationinstanceif mycursor null do some stuff here access db etc else we are returning from configuration change feed the cursor to the adapteri am pasting the stack trace if someone wants to look at it 0125 165745637 errorandroidruntime12976 androiddatabasestaledataexception access closed cursor 0125 165745637 errorandroidruntime12976 at androiddatabaseabstractwindowedcursorcheckpositionabstractwindowedcursorjava217 0125 165745637 errorandroidruntime12976 at androiddatabaseabstractwindowedcursorgetstringabstractwindowedcursorjava41 0125 165745637 errorandroidruntime12976 at comtestsamplehelperdictionaryadapterbindviewdictionaryadapterjava35more listviewrelated errors herei stepped through the code and i found out that as far as onretainnonconfigurationinstance the cursor is still open but after getting it through getlastnonconfigurationinstance it is already closedhow can i make my cursor survive the orientation change thank you for the helpeditbased on romains answer i commented out all my startmanagingcursors i should have connected the dots and thought about it anyway my app now survives one rotation but flipping it back to the original orientation still crashes it continuing my debugging and will let you know what i find outedit2i think i may have found what is causing the new errors i have implemented a filterqueryprovider which returns a new cursor what i did was assign the results of that filter to my original cursor seems to work so far,['android'] +117246,cross browser rgba transparent background while keeping content text images nontransparent i want to get rgba backgrounds working with all browsers i did some searching and found out that generally there are three types of browsers out there1 browsers that support rgba2 internet explorer that supports rgba via bizarre msfilter thing3 browsers that do not support rgba but i could use base64 png images with data uri scheme even when browser does not support uri scheme according to this it still could be donei have no problems with rgba supporting browsers and i can get it working with ie but problem is that i have no idea how to generate client side base64 png images for uri scheme i really do not want to pregenerate png files because my rgba values are not constant i could go with dynamic png generation with php gd library but i would really like to do all this on client side so i would like to know is there any good way out there for generating semitransparent png images with javascript after this i could just base64 encode them and use them with uri schemethank youediti want to have semitransparent div background while having content fully visible,"['javascript', 'css']" +117249,arraysaslist doubt people say that aslist method convert the array into list and its not copying so every change in alist will reflect into a so add new values in alist is illegal since array have fixed sizebut aslist method returns arraylistt how the compiler differentiates line 3 from 5 line 3 gives me exception unsupportedoperationexception string a abcd1 liststring alist arraysaslista2 alistadde3 liststring b new arrayliststring4 badda5,['java'] +117252,how do you change text to bold in android how do you change textfont settings in an android textview for example how do you make the text bold,['android'] +117265,how to resolve warning application does not specify an api level requirement helloi am writing an android application but as i do run this application the following application generates and application does not appear on the windowsplease help i will appreciate if i get right solution,['android'] +117276,repackage apk file to contain custom assets what build tool to use update this is an old post and references below to broken aapt versions will be out of datebased on previous feedback i am storing custom text fields in the assets directory of my appi will write the app using default user details in an asset file and the client would like to rebuild the app for each user including that users details in the asset filei am aware this is method has some serious shortcomings but the client is still keen to do it in this way see embed login details in apk file different for each user or other optionsthis question relates to troubles i am having with rebuilding the apk file once i have unzipped it and updated the custom asset file i am quite convinced i am missing something small however the documentation and posts i have found on these methods are not helpful enough for a newcomeraapt android sdk tool unfortunately the android docs on using aapt on the android docs link 2 below are very limited the console command help shows a bit more info when trying to use it to just add a file to the testapk it ends up deleting the original and creating a new file testapkzip containing only the file i tried to add i have not been able to find the correct command line combination to take an unzipped apk and repackage it that would be my first prizeapkbuilder android sdk tool firstly this tool is deprecated which is a negative point for it i also cannot get it to work with what i have in that unzipped folder i think i am missing a preapkbuilder step because apkbuilder asks for a resource zip archive and i have a resource folderant build tool other similar posts say to build with ant rather than using the android tools i am having trouble getting ant to work one particular link to getting ant to work with android link 3 below looks promising but looks like it is for a different android sdk my buildxml that is generated by android looks different to his unfortunately i know little about ant and am having trouble becoming expert enough to solve my current issuefurther to nickts solution below running the ant script gives me the errortaskdef class comandroidantsetuptask cannot be found using the classloader antclassloaderi have found some references online to this error have confirmed that localproperties has an sdkdir setting that is pointing to my android sdk install folder sdkdirapplicationsandroidsdkmac 86 there might be some other option that i have not listed thiscovered which i would be interested in hearing about i realize that delving into the gears that are normally covered up by my ide can lead to diffuculties but i know that a lot of the so users can do many of these things and i hope i get the interest of some of them thanks for any helpeclipse 36 on mac snow leopard 106 64 bitps i am not able to post more than 1 hyperlink yet so i have included these addresses to show more info to my question1 stackoverflowcomquestions4783160embedlogindetailsinapkfiledifferentforeachuserorotheroptions2 developerandroidcomguidedevelopingtoolsaapthtml3 wthisgruntledratscomp27,['android'] +117283,difference between stringbuffer and stringbuilder class i could get more on the internet and from sun java but needed to get the clear difference with the help of an examplestringbuffer or stringbuilderwhats the difference and when to prefer considering the response time,['java'] +117319,box and unbox what does it means possible duplicateswhy do we need boxing and unboxing in cwhat is boxing and unboxing and what are the trade offs in c what doe sit means box and unboxhere an extract from msdn where i founded the textbut this convenience comes at a cost any reference or value type that is added to an arraylist is implicitly upcast to object if the items are value types they must be boxed when they are added to the list and unboxed when they are retrieved both the casting and the boxing and unboxing operations decrease performance the effect of boxing and unboxing can be very significant in scenarios where you must iterate over large collectionsthanks,"['c#', '.net']" +117329,how to stop and continue a pthread i am coding in c actually in ooc which is then compiled to chow do i instruct a thread to wait at a particular checkpoint until some other thread tells it to continue i am actually using a tight loop in the thread and polling a variable i am changing from the main thread but i think that is not well performing right besides that when i do a tight loop in a thread should i include a sleep in the loop to avoid consuming much cpu power just looping,['c'] +117331,how to manually commit a managed transaction i was given an api in the form of a jar to do some external accounting operations from my javaseamhibernate aplicationinternally the api is an plain hibernate application using two independent data sources besides the one used from seam itselfthe issue is that one of the api operations raises the following exception when doing an internal commitjavasqlsqlexception you cannot commit during a managed transaction at orgjbossresourceadapterjdbcbasewrappermanagedconnectionjdbccommitbasewrappermanagedconnectionjava543 at orgjbossresourceadapterjdbcwrappedconnectioncommitwrappedconnectionjava334 at orghibernatetransactionjdbctransactioncommitandresetautocommitjdbctransactionjava139 at orghibernatetransactionjdbctransactioncommitjdbctransactionjava115 at comotherapiaccountingimplmoneymovementapiaccountingimpljava261 at commyappintegrationexternalapiintegratorstoreacountingdataexternalapiintegratorjava125 at commyappsessionemployeeaccountingpersistdataemployeeaccountingjava123 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokeunknown source at sunreflectdelegatingmethodaccessorimplinvokeunknown source at the source code of the moneymovement method looks like the standard hibernate session transaction idiomsession sess factoryopensessiontransaction txtry tx sessbegintransaction do some work txcommitcatch exception e if txnull txrollback throw efinally sessclosei am using seam managed transactions with jta i am also forced to use the custom api and i am not allowed to alter the source codewhat are my alternatives how can i isolate the seam managed transactions from the api hibernate session it is possible to configure a connection from a specific data source to not be a managed trx,['java'] +117332,pass variable to subprocess call in python i am trying to pass my variables from raw input to my subprocess command i am new to python any help would he appreciated usrbinpythonimport subprocessprint nwhat user nameusername strraw inputusername print nwhat is the user iduserid intraw inputenter user id print nwhat is the users primary groupprimarygroup intraw inputenter group print nwhat is the users secondary groupsecondarygroup intraw inputenter group subprocesscalluseradd m g primarygroup g secondarygroup u userid usernameprintnthe user has been added,['python'] +117359,sequence points conditionals and optimizations i had an argument today with one of my collegues regarding the fact that a compiler could change the semantics of a program when agressive optimizations are enabledmy collegue states that when optimizations are enabled a compiler might change the order of some instructions so thatfunction fooint a int b if a 5 if b 6 do something might be changed tofunction fooint a int b if b 6 if a 5 do something of course in this case it does not change the program general behavior and is not really importantfrom my understanding i believe that the two if condition belong to two different sequence points and that the compiler cannot change their order even if changing it would keep the same general behaviorso dear so users what is the truth regarding this,"['c++', 'c']" +117371,window cc crypto api examples and tips i am asking this question because i have spent the best part of a day trawling through msdn docs and other opaque sources for simple straightforward guidelines on how to get started with the windows cc crypto apiwhat i would like to see is some example code typical include paths linking guidelines etc anything useful really i know this is an imprecise question but i reckon imprecise answers are better none at alli will get the ball rolling with my own meager findings,"['c++', 'c']" +117411,is it possible to use regular expression for jettys servletmapping i have this one mappingservletmappingservletnameserviceservletnameurlpatternserviceurlpatternservletmappingbut i also want servicemasterto map to master servlet servletmappingservletnamemasterservletnameurlpatternservicemasterurlpatternservletmappingi believe there is a conflict here since calling service will trigger service servlet right away is there a way for me to use some kind of exclusion in servletmapping or may be regexp to do what i want to do,['java'] +117426,embedded c data storage module design i am in the process of designing a embedded c data storage module it will be included by filesmodules who want access to this shared systemwide data multiple tasks aggregate dozens of inputs gpio can i2cspissp data etc and stores those values off using the api then other tasks can access the data safely through the api the system is an embedded app with an rtos so mutexes are used to protect the data these ideas will be used regardless of the implementationi have designed something like this in the past and i am trying to improve upon it i am currently halfway through a new implementation and i am running into a few hiccups and would really benefit from a fresh perspectivequick rundown of the requirements of this moduleideally there would be one interface that can access the variables one get one seti would like to return different variable types floats ints etc this means macros are probably neededi am not pressed for code space but it is always a concernquick getssets are absolutely paramount which means storing in strings ala xmljson is outno new variables need to be added during runtime everything is statically defined at bootthe question is how would you go about designing something like this enumerations structures accessors macros etc i am not looking for code here just thiscussing general overall design ideas if there is a solution on the internet that addresses these sorts of things perhaps even just a link is sufficient,['c'] +117427,haml in rails 3 produces only doctype html hey guys i am running into a problemif use something like this xmlhtml head title myspace body h1 i am the international space station p sign my guestbooki get only this as sourcedoctype htmlhtml head titlemyspacetitle head body h1i am the international space stationh1 psign my guestbookp bodyhtmlthanks for any help,"['html', 'ruby-on-rails', 'ruby']" +117435,why is listtclear on according to the msdn documentation on the listtclear methodthis method is an on operation where and is countwhy on i ask because i would assume that clearing a listt could be accomplished simply by allocating a new t array internally no other class could have a reference to this array so i fail to see the harm in this approachnow maybe this is a stupid question is allocating a t array itself on for some reason i would not have thought so but maybe it is is my lack of a cs degree showing right now if so i suppose that would explain it since according to the same documentation quoted above the capacity of the list remains unchanged which means an array of equal size would need to be constructedthen again this does not seem like it could be the correct explanation as then the documentation should have said where and is capacityanot counti just suspect that this method rather than allocating a new array zeroes out all elements of the current one and i am curious to know why this would behans passant pointed out in a comment to lukehs answer that the docs are correct clear only zeroes out the elements that have been set in the listt it does not need to rezero all the elements past those,['.net'] +117441,software usage analytics in c i have a project i am working on currently and would like to implement some sort of software tracking in the code ideally stuff like how often its launched how long it runs for feature tracking etc i already use exceptioneer for unhandled exceptions but would like something similar for usage trackingthis data should all be anonymous and ideally run as a service by someone else and i would like to give the users the option to turn it off if they so wish to so is this something i should implement myself or are there third parties out there that do this sort of things i know it might be a sticky area but i have seen stats about iphone app usage they do it so why cant we if the user agrees of courseupdate based on the comments i should have been more clear this is a winforms net 4 application though i am thinking of updating it later with wcf i would only be tracking my own application though i would also want to know minor information about environment windows os version sp maybe proc and ram,['c#'] +117444,understanding baseadapters and how to use them i am trying to set up a an image gridview layout and this involves deriving a new class from the baseadapter class i have been using the tutorial on the website developerandroidcom but i still do not quite understand what it means could someone please explain to me what exactly is a baseadapter i do not understand the definition provided by the android developers websitethanks,['android'] +117447,set timeout dialog in android i want to set timeout for dialog progress dialog in android to make the dialog thisappears after a period of time if there is no response for some action,['android'] +117453,understanding method added for class methods i would like to do some magic in the moment instance and class methods are added to some class therefore i tried the followingmodule magic def selfincludedbase baseextend classmethods end module classmethods def method addedname puts class method name added end def some class method puts some class method end end endclass foo include magic def selfmethod addedname puts instance method name added end endthis approach works well for instance methods fails for class methods how can i solve that any suggestions,['ruby'] +117454,when to use sql subqueries versus a standard join i am working on rewriting some poorly written sql queries and they are overutilizing subqueries i am looking for bestpractices regarding the use of subqueriesany help would be appreciated,['sql'] +117455,dangerous to store a well hashed password and the method used to hash it in plain sight i am developing a clientside application in c that will communicate with a server php page for credentials and for some critical services i am wondering if it is dangerous to store a well hashed password on the clients machine by well hashed i mean with a random seed using a wellknown secure hashing function for the purposes of this thiscussion assume the source is freely available as all binaries can be reverse engineeredmy thought was that i would store the username and hashed password on the users computer and that this username and hash would be sent in plain text over an unencrypted http connection to the server for validation this of course will not prevent a hacker from using someone elses username and password hash as their own without knowing the source password with some code tweakswould a malevolent individual be able to do anything with a hashed password and code used to produce the hash other than log in as an other user if they obtained this informationwhat do other clientside applications do to prevent one user from logging in as an other user if the hacker does not have access to the source password for example steamis there an easy cheap both cost and time more secure way to handle thisexample of how a hacker would spoof someone elses login credentials using my current logiclegit user signs in for the first time credentials get storedhacker gains access to the file system locates username and hashed passwordhacker modifies source code or uses code injection to send the acquired username and hashed password instead of what the program would normally dothe product i am producing is not going to be the next ebay facebook or stackexchange and is low budget i do not need something top notch and do not care for thefts as i am planing to use a pay what you want model i am mainly posting this for curiositys sake,"['c#', 'php']" +117458,what if any source code of a rails project should be obscured even for an open source project this was a hard one to search for if i have an open source rails web application project whose source code is publicly hosted like on github what information should be obscured or swapped if that application is to be run in production at a public website my assumption is that things like configinitilizerssecret tokenrb any authentication salting stuff and the database login information should not be the same in production as in development what other precautions should be taken to ensure that the production site is not vulnerable to people fiddling with the sessions or anything else i am not considering,['ruby-on-rails'] +117459,my static c function is playing games with me totaly weird so i have written a small and from what i initially thought easy method in cthis static method is meant to be used as a simple password suggestion generator and the code looks like thispublic static string createrandompasswordint outputlength string source var output stringempty for var i 0 i outputlength i var randomobj new random output sourcesubstringrandomobjnextsourcelength 1 return outputi call this function like thisvar randompassword stringhelpercreaterandompassword5 abcdefghijklmnopqrstuvwxyz1234567890now this method almost always return random strings like a b 8 etc where i thought it should return strings like a8jk2a 82mok7 etchowever and here is the wierd part if i place a breakpoint and step through this iteration line by line i get the correct type of password in return in 100 of the other cases when im not debugging it gives me crap like a 6 etchow is this possible any suggestion is greatly appreciated btw my system visual studio 2010 c 40 aspnet mvc 3 rtm project w aspnet development server have not tested this code in any other environments,['c#'] +117470,confirm jquery sortable receive event i have two separate ul listslista and listbboth of them are sortable thanks to the jquery ui pluginusers of the project i am working on wants to confirm the action when items are moved from one list to the other but not when moving within the same list when an action is triggered the page will launch an ajax request to the server to update the positions of the listswhats troubling me is the order of the events my experience so far is that the update event is triggered before the receive event so before the confirm dialog is shown a request has already been initiatedunfortunately i forget which of the lists that trigger the request but in my case it really does not matter if an item is dragged onto another list nothing should be sent to the server until the user has confirmed the actioni have used jquery quite a bit but i think i could use some help on this onejavascriptsortablesortable start function event ui uihelperaddclasortabledragclone stop function event ui uihelperremoveclasortabledragclone update function event ui if uisenderlength 0 alertitem was moved within the same list make request else do nothing receive function event ui if confirmshow move or copy dialog from 0 to 1 do request else uisendersortablecancel no request tolerance pointer connectwith sortable placeholder sortabledraggableplaceholder forceplaceholdersize true appendto body helper clone zindex 6thisableselectionmarkupdiv idlista ul clasortable liitem 1li liitem 2li liitem 3li uldivdiv idlistb ul clasortable liitem 1li liitem 2li liitem 3li uldivupdatescenario iuser drags a1 to a3 result is no confirm dialog so a request is sent to the server so that the new sort order is persistedscenario iiuser drags a1 to b3 or b3 to a1 result is a confirm dialog and then only if the dialog is accepted a request is sent to the server this is where i have settled with two requests as i described in one of my comments,['jquery'] +117503,ios apptoapp trasnmission of data using new document support api problembuilding enterprise applications of a suite nature and need to be able to pass data from one application to another example app1 is a barcode reader that produces and inventory list app2 needs a fresh copy of the same inventory list information that app1 just produced in order to accomplish its goal of producing purchase orders the two apps and databases are two large to squeeze together in single app plus the suite will continue to grow with more and more appsunderstandingi fully understand that each application is in it is own sandbox however in reading through the documents regarding the new uidocumentinteractioncontroller api it appears that an application can dip outside of the sandbox just a little to readin view or openin a document that was not apart of the bundle or created within the applicationdata flowi am trying to keep it simple i have been using the docinteraction sample application downloaded from apple and another applicationcalled app1 to try and work with a simple text file in app1 i create a simple txt file and save it to the documents folder but this is still inside the apps sandbox in the docinteraction modified sample i have been trying to figure a way to view openin or better yet readin the created txt file if i can pass a simple txt file between the two i can include a csv structure to update the databases on each side when ever the applications are openedi have tried to utilize the launch options keys with no luckin short i just cannot seem to get my head aroundwhere app1s data needs to gohow to find the data in the other app say app2how do you open the file that exist inside another applications sandboxend resulti have tried to stay away from the the document interaction docs outline previewing a document or presenting optionsregistering your support of file typesopening files from other appsthisplaying and printing quick look previewsit is the opening files from other apps that i am most interested with it directs me to utilize the applicationdidfinishlaunchingwithoptions method by passing in dictionary values for the keys this is where i get lost how do i set the keys so that it knows where and what to look for and i am still not clear the proper director that app1 should be saving information to in order for the keys to point to the correct placeopening email file attachments and opening pdfs in ibooks cannot be the only places where you can utilize this api or else apple wouldnt have went through all the work they are already allow to talk from apptoappnote i am not trying to get app1 to directly transmit data into app2s files i do not think that would be allowed by apple at all i am trying to get app1 to zip up its data save it in proper location so when user decides to use app2 the data can then be available to app2 by readingin the dataif someone has a sample application tutorial or even a solid idea how to get this working i would really appreciate the help thanksps somebody with 1500 or higher reputation please create a uidocumentinteraction tag for stackoverflow,['iphone'] +117517,how to get a dimension slice from a multidimensional array i am trying to figure out how to get a single dimension from a multidimensional array for the sake of argument let us say it is 2d i have a multidimensional arraydouble d new double 1 2 3 4 5 5 4 3 2 1 if it was a jagged array i would simply call d0 and that would give me an array of 1 2 3 4 5 is there a way i can achieve the same with a 2d array,"['c#', '.net']" +117525,how do i format date in jquery datetimepicker i use jquery datetimepicker which was extended from jquery datepicker to pick not only date but time tooi want to set datetime format this way ddmmy hhmmtimepickerdatetimepicker dateformat ddmmy separator mindate new datebut this does not work i get datetime in following formatthu jan 27 2011 020517 gmt0100is there any javascript function to format this datetime if not how do i do that using the plugin check out my code fiddle,"['javascript', 'jquery']" +117532,datagrid mvvm scroll into view greetingsi have managed to scroll to the selected item using but this only scrolls untill it gets to the selected itemi want the selected item to show at the top of the datagrid currently it shows at the bottom of the datagridis there any way to accomplish this,['c#'] +117540,can you delete a field from a document in solr index i have a big index and during the indexation process there was an error so to avoid reindexing which takes several days i want to simply delete specific field and reindex is there any suggestion,['java'] +117544,iphone inapp purchase screen shot when posting an inapp purchase with apple they ask for a screenshot to be included before going to reviewwhat kind of screenshots do they wantmy inapp purchase unlocks some of the lite version i am not sure what apple wants to see here,['iphone'] +117555,mapping elements in 2d upper triangle and lower triangle to linear structure i have a matrix m which is of nxn dimensions where mij mji i would like to represent this structure as a na2n2 linear array k to save space my problem is coming up with the formula that will map a mminijminij into a range 0n22below is a mapping of a 3x3 matrix with indexes for k linear array the x means those cells do not exist and instead their transpose is to be used0123x456xx78x9here is a 7x7 matrix with indexes for the k linear array 0 1 2 3 4 5 6 0 00 01 02 03 04 05 06 1 07 08 09 10 11 12 2 13 14 15 16 17 3 18 19 20 21 4 22 23 24 5 25 26 6 27at the moment i have the followingint main const unsigned int and 10 int mnn int m m00 assertmij m n minij maxij int k assertmij k return 0,['c++'] +117596,python create an html formatted report i have a python 26 app running on linux that creates a csv file from the app i need to create an html report as a single html file that presents the data from the csv probably as a table and also highlights fields where the values meet certain criteria charting type functionality would be a nice to havewhats the best way to do thisno gpl stuff please,"['python', 'html']" +117601,cassandra low perfomance i have to choose cassandra or mongodbor another nosql database i accept suggestions for a project with a lot of inserts1mdayso i create a small test to measure the write perfomance heres the code to insert in cassandraimport timeimport osimport randomimport stringimport pycassadef get random stringstring length return joinrandomchoicestringletters for i in xrangestring lengthdef connect connect to a test database connection pycassaconnecttest keyspace localhost9160 db pycassacolumnfamilyconnectionfoo return dbdef random insertdb insert a record into the database the record has the following format id timestamp 4 random strings 3 random integers record recordid strtimetime recordstr1 get random string64 recordstr2 get random string64 recordstr3 get random string64 recordstr4 get random string64 recordnum1 strrandomrandint0 100 recordnum2 strrandomrandint0 10 recordnum3 strrandomrandint0 10 dbinsertstrtimetime recordif name main db connect start time timetime for i in range10 random insertdb end time timetime print insert time lf end time start timeand the code to insert in mongo it is the same changing the connection functiondef connect connect to a test database connection pymongoconnectionlocalhost 27017 db connectiontest insert return dbfoo2the results are 1046 seconds to insert in cassandra and 437 to finish in mongo it is supposed that cassandra it is much faster than mongo inserting data so what i am doing wrong,['python'] +117609,c getting file names without extensions when getting file names in a certain folderdirectoryinfo di new directoryinfocurrentdirnamefileinfo smfiles digetfilestxt foreach fileinfo fi in smfiles builderappendfiname builderappend by finame we get a file name with its extension file1txt file2txt file3txthow better to get file names without file extensions file1 file2 file3,['c#'] +117623,group by week how to get empty weeks i have the following code which groups some events ymmdd hhmmss in weeks which are thisplayed as for example y2010 week 50select date formatdate yx weekv as regweek count as number it works good but i would like to return all weeks even if the ones in which no event is placedif no event is registered in the third week at the moment i getweek 1 10week 2 1week 4 2i would like to getweek 1 10week 2 1week 3 0week 4 2,"['sql', 'mysql']" +117627,what techniques can i use to be more productive with ruby on rails just curious as i have been digging deeper in rails i have found there are often routine things that i originally learned to do in a verbose way and as i begin to understand the framework and the ruby language better i find much nicer andor shorter andor faster ways to do the same thingsso i thought it would be great to hear tips from the rest of you what things have you learned that have really boosted your productivity using ruby in general or the rails framework specifically if you could teach a new rails developer like me one timesaving habit or tool or coding convention you wish youd learned sooner what would it be,"['ruby-on-rails', 'ruby']" +117634,how do i detect ie8 using jquery possible duplicatehow do i detect ie 8 with jquery hi alli was on here looking for a jquery snippet to detect ie8 this is what i found see below ifjquerybrowserversionsubstring0 2 8 step1cssmarginleft8px i found this but it doesnt seem to be workingcan someone advise me where i might be going wrongor have other suggestionsthanks,['jquery'] +117643,javascript function vs function i have often see expressions such asfunction var x 1 how do i interpret it syntactically this alone is a anonymous function definitionfunction what the after that and why put it in the enclosing thanks,['javascript'] +117649,using phpunit how do you test only two or more groups in phpunit is help it thisplays the following group only runs tests from the specified groups excludegroup exclude tests from the specified groupseasy enough for one group this worksphpunit group fastnow i cannot quite figure out how to do this with more than one group the following is not working for mephpunit group fast unit it believes you want to test unitphpphpunit group fast unit it believes you want to test unitphpphpunit group fast unit it looks for a single group fast unitphpunit groups fast unit there is no option groupsphpunit group fast group unit only one is honoredany thoughts on the correct syntax would be welcome thank you,['php'] +117655,preventing sql injection using only php the think is that i have a complete working website with many calls to the mysql server and doing some research on this site i saw that making my querys in this formquery sprintfselect from users where users and passwords mysql real escape stringuser mysql real escape stringpasswordi can solve the security issue but as i said i have many calls to the mysql server and the best way in my case to solve the problem is going directly to the vars im passing to the query but whitout using a mysql function because im out of the query let me explain it i have thismysql queryselect from post where id getediti cant do modifications to this query because i have a lot of this in all my code insted i preefer to check for injections on the var getedithow can i using pure php check for sql injections on the variables of the querys like geteditfreehack getedit,"['php', 'mysql']" +117660,const variables in header file and static initialization fiasco after reading a lot of the questions regarding initialization of static variables i am still not sure how this applies to const variables at namespace leveli have kind of the following code in a header file configh generated by the build scriptstatic const stdstring path1 xyzabcstatic const stdstring path2 etcaccording to what i have read the static keyword is not necessary even deprecated heremy question is the code above prone to the static initialization fiascoif i have the following in a header file myclasshclass myclasspublic myclassconst stdstring str m strstr stdstring get const return m str private stdstring m strconst myclass myclass1testwill this pose any problems with static initializationif i understood right due to const variables having internal linkage there should be no problem in both casesedit due to dribeas answermaybe i should mention that i am interested in use cases likein maincppinclude confighinclude myclasshstdstring anotherstringpath1 myclass1getint main another question regarding this use case will the compiler optimize away path2 in this case,['c++'] +117682,adding assembly reference within webconfig i have some general questions about webconfig and how it works regarding assembly reference i have been playing around with the new razor view engine and had some trouble getting it up and runningmy problem started with a general the type or namespace name x does not exist in the namespace x are you missing an assembly referencenow i figured this was just a simple add reference to the project and i would be on my way but even after i added a reference to the missing assembly my project kept breakingi found the solution and i had to add an assembly reference within the webconfig once i did this everything worked finefirst i want to understand why it took adding a reference to webconfig to fix this problem why was not a project reference just good enoughsecond when it comes to adding references in webconfig i would like to understand the syntax when i see markup like this add assemblysystemwebwebpages it seems very clear to me that i am adding an assembly named systemwebwebpages but the full syntax in my webconfig is add assemblysystemwebwebpages version10 cultureneutral publickeytoken31bf3856ad364e35 version seems self explanatory but what is culture and publickeytoken used for are they required what happens if i do not know either of them can i just put anything in,['asp.net'] +117730,creating and returning a big object from a function imagine such situation that i have a function like thisobject f object obj return objwhere sizeofobject is a big valueand then i make a call of this functionobject object f do i understand correctly that first object will be created on a stack in the function and then will be copied to object variableif so is it reasonably to create an object in the function on a heap and to return a pointer to it instead of a copy but i mean that the object must be created in the f function not passed by a pointer or a reference to this function and initializedediti do not mean that f is a very simple function it can have a really complex routine of object initialization depending on some context will the compiler still optimize it as well,"['c++', 'c']" +117737,is there a wchar t version for asprintf i need a c function which returns the final length of a formatted string so i can properly allocate the target string rather than calculate the length myself there is snprintf which does just this upon inability to write the entire string but unfortunately there is no wide char alternative for itswprintf returns 1 in case of error not the needed length why not the same behaviour the title mentioned asprintf seems to be of no help also as it provides a nonwide version only vscwprintf can be used on windows but i need a crossplatform standard version or at least a linux version and i will ifdef the codeany ideas thanks,['c'] +117740,devise omniauth and iphoneandroid app i have set up user auth for my rails app with devise and omniauthnow i am wondering where i should start to use the same auth for an android and iphone app i want to createshould i use a mobile version of my authfacebook or should i directly send a request from the app this is a quite general question but i have found nowhere to look atedit i have just added token auth to the app to use with the restful api i am just missing the omniauthfacebooktoken part,"['iphone', 'android', 'ruby-on-rails']" +117741,how to allow copying message on messagebox how can i allow selecting and copying of text from messagebox in wpf,"['c#', '.net']" +117780,java set focus on jbutton when pressing enter how can i make it so that when i press enter in a jtextfield it activates a specific jbutton what i mean is something along the lines of a web page form where you can press enter to activate the button in the form thanks,['java'] +117792,reuse sql with view or function i have a sql query that i will be reusing in multiple stored procedures the query works against multiple tables and returns an integer value based on 2 variables passed to itrather than repeating the query in different stored procedures i want to share it and have 2 optionscreate a view to which i can join to based on the variables and get the integer value from itcreate a function again with criteria passed to it and return integer variablei am leaning towards option 1 but would like opinions on which is better and common practice which would be better performance wise etc joining to a view or calling functionedit the rdbms is sql server,['sql'] +117804,why getspeed always return 0 on android i need to get the speed and heading from the gps however the only number i have from locationgetspeed is 0 or sometimes not available my code string provider initlocmanager if provider null return false locationlistener loclistener new locationlistener public void onlocationchangedlocation location updatewithnewlocationlocation interval startid logigetstringrstringlogging tag speed locationgetspeed public void onproviderthisabledstring provider updatewithnewlocationnull interval startid public void onproviderenabledstring provider public void onstatuschangedstring provider int status bundle extras locmanagerrequestlocationupdatesprovider interval default gps min thistance loclistener private string initlocmanager string context contextlocation service locmanager locationmanager getsystemservicecontext criteria criteria new criteria criteriasetaccuracycriteriaaccuracy fine criteriasetaltituderequiredfalse criteriasetbearingrequiredtrue criteriasetspeedrequiredtrue criteriasetcostallowedtrue criteriasetpowerrequirementcriteriapower low string provider locmanagergetbestprovidercriteria true if provider null providerequals thisplaygpsnotenabledwarningthis return null return provideri tried to play the criteria with but no success does anyone have an idea what is the problem,['android'] +117815,does php time return a gmtutc timestamp i just want to check if time returns a utcgmt timestamp or do i need to use date default timezone set,['php'] +117820,java can member variable and local method variable have the same name specifically i am trying to do this how would i accomplish itclass test private int var1 public testint var1 var1 var1 set the member variable to what was passed in i am sure there is a very obvious answer it is just escaping me right now,['java'] +117830,how to store printstacktrace into a string how can i get the eprintstacktrace and store it into a string variablei want to use the string generated by eprintstacktrace later in my programi am still new to java so i am not too familiar with stringwriter that i thinkwill be the solution or if you have any other ideas please let me know thanks,['java'] +117856,how to remove accents in mysql i have just compiled a database of 1 million place names i am going to use it in an autocomplete widget to look up cities a lot of these places have accents i want to be able to find records when a user types the name without an accent in order to do this i have got a 2nd column with an unaccented copy of the name many of these records are still blank so i want to write a query to fill them in is this possible in straight mysql if so how,['mysql'] +117860,sqlite or mysql how to decide any good rules of thumb on how to decide which of the two to useand if you take over an sqlite db and the system is expected to get much larger how to decide whether to stick with it or move to mysql,['mysql'] +117871,alphabetize results of dirglob in my controller i havefiles dirglobpublicdownloadsin my view i have fileseach do f p fsplitrails rootpublicdownloadsp end how can i put the results in alphabetical order,['ruby-on-rails'] +117875,how to override a function in another javascript file i have a javascript file mybasefilejs which has the function mybasefunction i want to override this function in another javascript file when the function is called in a button click i want the original mybasefunction to be executed along with some other code how can i do this,['javascript'] +117878,suppress androidmanifestxml minsdkversion related warning as recomended here supporthtml for compatibility reasons my androidmanifestxml contains thisusessdk androidminsdkversion3 androidtargetsdkversion4this generates warning in eclipseattribute minsdkversion 3 is lower than the project target api level 4are there any means to suppress this warning or get rid of it any other way it is really annoying,['android'] +117887,subprocesscheck output does not seem to exist python 265 i have been reading the python documentation about the subprocess module see here and it talks about a subprocesscheck output command which seems to be exactly what i needhowever when i try and use it i get an error that it does not exist and when i run dirsubprocess it is not listedi am running python 265 and the code i have used is belowimport subprocesubprocesscheck outputls l devnulldoes anyone have any idea why this is happening,['python'] +117890,how can i use an integer value as key to set value in nsmutabledictionary how can i use an integer value as key to set a float value in nsmutabledictionary,"['iphone', 'objective-c']" +117895,jquery ui autocomplete with item and id i have the following script which works with a 1 dimensional array is it possible to get this to work with a 2 dimensional array then whichever item is selected by clicking on a second button on the page should thisplay the id of whichever item is selectedthis is the script with the 1 dimensional arrayvar local source c java php coldfusion javascript asp rubytxtallowsearchautocomplete source local sourcethis is the script for the button to check the id which is incompletebuttonclickfunction alerttxtallowsearchsomeone get id of selected item,"['javascript', 'jquery']" +117917,how to render a view using ajax in spring mvc i am using spring mvc and i need to make an asynchronous call to the server and refresh only a piece of the pagewhat i actually have is a controller that returns a string i call the controller using jquery post functionthe problem with my solution is that i am not able to render a jsp like i do when i use modelandview as return type is there any way to return a view already renderedthanks in advanceneuquino,['jquery'] +117921,getting data from mysql into json using php i have the following quite simple test php that extracts the data and puts it into json formatted texti get the following errorfatal error allowed memory size of 33554432 bytes exhausted tried to allocate 1979603 bytes in varwtestphp on line 33where line 33 is the json encode lineis there a way to make this more efficient the phpini is already set to 32m as max size up from the 8m standard php requireadmindb loginphp dbmysql connecthost username password or diecould not connect mysql select dbdb name db or die result mysql queryselect from listinfo or diecould not query json array ifmysql num rowsresult rowmysql fetch assocresult whilerowmysql fetch rowresult cast results to specific data types test datarow jsontestdatatest data mysql closedb echo json encodejson,"['php', 'mysql']" +117925,webapp 2 5xsd showing errors when validating webxml in eclipse i have no idea what i could have done to cause this because my time spent programming is stretched out and i have already forgotten what i might have done but now when i load eclipse it saysthe errors below were detected when validating the file webapp 2 5xsd via the file webxml in most cases these errors can be detected by validating webapp 2 5xsd directly however it is possible that errors will only occur when webapp 2 5xsd is validated in the context of webxml s4seltcharacter nonwhitespace characters are not allowed in schema elements other than xsappinfo and xsdocumentation saw jdk 6 xmlrelated apisthe entity name must immediately follow the in the entity referencemy first few lines of webxml looks like so xml version10 encodingutf8webapp xmlnsxsi xmlns xmlnsweb 2 5xsd xsischemalocation 2 5xsd idwebapp id version25i have read that it could be an error with the server where the file is being retrieved from or with caching i have thisabled and cleared the cache and as far as i can tell the server is the same everyone else is using unless they switched to an oraclecom url and i have not found it yet any thoughts would be greatly appreciated,['java'] +117949,rspec unknown attribute question i am working through the excellent railstutorialorg site have have a basic question about rspecwhen i run the below test on a new user model i get an unknown attribute username message and a failed test beforeeach do attr lname e user fname e test email username testuser end it should create a new instance given valid attributes do usercreateattr enderror syntax isfailures 1 user should create a new instance given valid attributes failureerror usercreateattr unknown attribute username specmodelsuser specrb11in block 2 levels in top requiredthe field is in the users table string it is in the model as attr accessible and in the console i can create a user with exactly the same syntax in the test this username field was added via a migration after creating the initial table is there some other file i need to update herethanks,['ruby-on-rails'] +117956,how can i add a javaagent to a jvm without stopping the jvm i wish to profile a java application without stopping the application can i add a javaagent somehow while the application is running,['java'] +117959,android listview with onitemclicklistener and gesturedetector i have a the following listactivitypublic class showdayactivity extends listactivity implements onitemclicklistener private gesturedetector gesturedetector private viewontouchlistener gesturelistener override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutday registerforcontextmenugetlistview gesturedetector new gesturedetectornew mygesturedetector gesturelistener new viewontouchlistener override public boolean ontouchview v motionevent event return gesturedetectorontoucheventevent getlistviewsetonitemclicklistenerthis getlistviewsetontouchlistenergesturelistener suppresswarningsstaticaccess override public boolean onoptionsitemselectedmenuitem item return superonoptionsitemselecteditem override public boolean oncontextitemselectedmenuitem item return superoncontextitemselecteditem override public void onitemclickadapterview parent view v int pos long id editeventpos class mygesturedetector extends simpleongesturelistener private static final int swipe min thistance 120 private static final int swipe max off path 250 private static final int swipe threshold velocity 200 override public boolean onflingmotionevent e1 motionevent e2 float velocityx float velocityy if mathabse1gety e2gety swipe max off path return false right to left swipe if e1getx e2getx swipe min thistance mathabsvelocityx swipe threshold velocity logdicscalendar fling left return true else if e2getx e1getx swipe min thistance mathabsvelocityx swipe threshold velocity logdicscalendar fling right return true return false the contextlistener longclick on the listitems works perfectly today i added the gesturelistener and detector which works too butthe gesturedetector detects a fling all right but after it is done with its logic the context menu opens which is obviously not what i want any ideas what i am doing wrong or what i might do about it,['android'] +117962,android fragments and animation how should you implement the sort of sliding that for example the honeycomb gmail client usescan transactionmanager handle this automatically by adding and removing the fragments it is kind of difficult to test this due to the emulator being a slideshow,['android'] +117966,charting massive amounts of data we are currently using zedgraph to draw a line chart of some data the input data comes from a file of arbitrary size therefore we do not know what the maximum number of datapoints in advance however by opening the file and reading the header we can find out how many data points are in the filethe file format is essentially time double value double however the entries are not uniform in the time axis there may not be any points between say t 0 sec and t 10 sec but there might be 100k entires between t 10 sec and t 11 sec and so onas an example our test dataset file is 26 gb and it has 324m points wed like to show the entire graph to the user and let her navigate through the chart however loading up 324m points to zedgraph not only is impossible were on a 32bit machine but also not useful since there is no point of having so many points on the screenusing the filteredpointlist feature of zedgraph also appears to be out of question since that requires loading the entire data first and then performing filtering on that dataso unless were missing anything it appears that our only solution is to somehow decimate the data however as we keep working on it were running into a lot of problems1 how do we decimate data that is not arriving uniformly in time2 since the entire data cannot be loaded into memory any algorithm needs to work on the thisk and so needs to be designed carefully3 how do we handle zooming in and out especially when the data is not uniform on the xaxisif data was uniform upon initial load of the graph we could seek by predefined amount of entries in the file and choose every and other samples and feed it to zedgraph however since the data is not uniform we have to be more intelligent in choosing the samples to thisplay and we cannot come up with any intelligent algorithm that would not have to read the entire filei apologize since the question does not have razorsharp specificity but i hope i could explain the nature and scope of our problemwere on windows 32bit net 40,"['c#', '.net']" +117970,livequery performance i have recently thiscovered that livequery plugin for jquery may be quite wasteful as it does not use event delegation but binds all bindable events and rechecks the whole dom on each changeif anyone has more information or suggestions on best practices using livequery and live i would be very grateful,['jquery'] +117994,is is possible to export functions from a c dll like in vs c in vs cc you could use extern c declspecdllexport function declaration how do i accomplish this in a c dll is there c code equivalent to the above codeedit more infoi am trying to create an add in for notepad and i want to use c but the common way i have seen so far is to use legacy c code with the above call to export a few of the functions that notepad expects to import and call there is an example app using c but this still requires a loader dll which i assume from the commentsanswers below is the only way for c,"['c#', 'c++']" +117999,allow google chrome to use xmlhttprequest to load a url from a local file when trying to do a http request using xmlhttprequest from a local file it basically fails due to accesscontrolalloworigin violationhowever i am using the local web page myself so i was wondering if there is any way to make google chrome allow these requests which are from a local file to a url on the interneteg get fails when executing in a local file but i have scripted the page myself and i am using it myself so it would be extremely useful if i could suppress it and load the urlso how can i allow google chrome to load urls using xmlhttprequest from local files,"['javascript', 'jquery']" +118000,how to troubleshoot systemwebhttpexception 0x804005 file does not exist apologies if this has already been answered on this site i searched but did not find this exact scenarioi am adding log4net to a wcf service i added a handler in the application error event and it is catching a file not found error on every requesti have seen this with web sites and usually the error can be traced down to not having a favicon file in the root directory or to a missing image referenced in a css stylesheethowever this is a wcf service there is no css stylesheet and adding a favicon to the root did not solve the problemdoes anyone else have a good way to troubleshoot this some cluesi have not deployed this yet to the real iis server i am running it locallythe error does not happen when i am running in debug inside visual studio only when i access the service from a web browser ie or chromei added the url and file path to the error message and this is what they areurl httplocalhost3994 filepath error systemwebhttpexception 0x804005 file does not existedit the above values are what show up in the logged exceptionprotected void application errorobject sender eventargs e var objerr servergetlasterrorgetbaseexception if objerr is systemwebhttpexception var filepath contextrequestfilepath var url httpapplication sendercontextrequesturl logerrorurl url filepath filepath objerr else logerrorapplication error objerrany help would be greatly appreciated,['asp.net'] +118003,texttospeechoninitlisteneroninitint being called continuously i am getting reports that on some not all htc desire hd frf91 22 and htc evo 4g pc361003296515 22 the texttospeechoninitlisteneroninitint is being called repeatedly over 1500 times in the space of a few seconds on the same object this behaviour does not occur for any of my other users or with other desire hd users afaictthe code istexttospeech tts new texttospeechcontext new texttospeechoninitlistener private int mcallcount 0 trying to investigate potential infinite loops override public void oninitint status if mcallcount 100 1 report this mcallcount anyone any ideasedit i have also tried calling the shutdown method the first time multiple listener calls are detected but this does not seem to help,['android'] +118020,get process name from pid or handle assuming i already have the handle to a window i can get the pid with getwindowthreadprocessid is there a way i can get the process name without having to get all the processes and try to match my pid,['c#'] +118031,how do i do an xpath regex search in my cucumber capybara step definition rails 3 i have a scenario that validates that the image i just uploaded exists on the next pagethis below works great except that i have a variable folder structure based on the listing id how can i use regex here to match image to only the filename instead of the entire urlthen i should see the image do image pageshould have xpathimgsrcpublicimagesimageend,['ruby-on-rails'] +118035,number of spaces in html please tell me how to put more than one space in html for one spacewe write nbspso for 5 spaces we have to write nbsp five timesis there any alternative way or any tag,['html'] +118038,how to run a maven project from eclipse i am trying to run a simple java project i had created a project using the maven project type i have one main class called testmain when i tried to run the project using right click run there was no menu to run the application as run as java application i am wondering where that option has gonecan anyone please help me to run the java application,['java'] +118048,a robust smpp library for net i am developing an online sms messenger and looking for a scalable and robust smpp library for net i saw easysmpp but have some doubts with it and roamingsmpp there are also one but i cannot recall it is name for me the most important is it is scalability stability and fault tolerance i may have 500k users and several hundreds sms per second the communication will be 2 way receive should be able to reply to sms msg received from my messengerso i am interested if anyone can recommend the library which suits my needs it does not matter for me if it is free or commercialthanks,"['c#', '.net']" +118049,is relying on shortcircuiting safe in net assume myobj is null is it safe to write this ifmyobj null myobjsomestring nulli know some languages would not execute the second expression because the evaluates to false before the second part is executed,"['c#', '.net']" +118056,modules vs layers in java package structure i used to put everything in packages like thiscomcompanyappmodule1comcompanyappmodule2but it has made packagebased aop pointcuts difficult and resulted in huge packages that need an ide to make sense ofso now i realize i need a deeper package structure but i am constantly torn give modules preference like thiscomcompanyappmodule1domaincomcompanyappmodule1logiccomcompanyappmodule1persistencecomcompanyappmodule2domaincomcompanyappmodule2logiccomcompanyappmodule2persistenceor give layers preference like thiscomcompanyappdomainmodule1comcompanyappdomainmodule2comcompanyapplogicmodule1comcompanyapplogicmodule2comcompanyapersistencemodule1comcompanyapersistencemodule2pros and cons of each,['java'] +118065,better datetime or use defaultdatetime for null i am designing a cnhibernate website that features a private messaging system i would like admins to check if and when a message has been read by a user and together highlight those messages that have not been read yet by users to achieve both i found two optionsoption 1class message datetime readwhere readnull means not read yetoption 2class message datetime readwhere readdefaultdatetime january 1st 1 ad 0 means not read yetat university i have been taught to use the null value to handle all special cases and also using the nullable type seems a good choice since it looks easier to query for unread messages by checking whether they are null or notbut using nullable types at least involves boxing and unboxing in code with performance decreasing on the other hand querying for unread messages means comparing the value but it can be indexedmy question iswhat is your suggested approach for this what would best practices suggest in this case,['c#'] +118071,how to make simplejson serializable class i have a class defined like thisclass a def init self selfitem1 none def repr self return strself dict when i do import simplejson mya a simplejsondumpsmyatypeerror item1 none is not json serializablei cannot find the reason why do i need to add any particular method to a for simplejson to serialize my class object,['python'] +118073,why does a rake task in a loop execute only once i have rails application that connects to multiple databases i wrote custom rake task that looks like thistask migrate accounts schema environment do t users userfind all conditions state 2 order id asc userseach do user if userstate 2 activerecordbaseestablish connection adapter postgresql host userdatabase host port userdatabase port username usersubdomain password userdatabase password database userdatabase name raketaskdbmigrateinvoke end endendthe problem is that task executes dbmigrate only for users0 user first user in collection and there is no errors just stoppes silentlyheres output from rake trace invoke appmigrate accounts schema first time invoke environment first time execute environment execute appmigrate accounts schema invoke dbmigrate first time invoke environment execute dbmigrate invoke dbschemadump first time invoke environment execute dbschemadump invoke dbmigrate i have no idea why the rest of users do not get migrated,['ruby'] +118086,javascript intellisense in razor view engine child pages i am after a way of getting my referenced js files in my master cshtml files to come through to the child cshtml filesi have something like this in the master file so the js files always get referenced and indeed i get js intellisense in the master fileif false script typetextjavascript srcscriptsjqueryjsscripthowever when i reference the mastercshtml file in a child page like this layout viewssharedmastercshtmli get no javascript intellisense i really do not want to have to put the script tags at the top of each child page there are a lot of script tags and a lot of child pages,['javascript'] +118104,chrome but not firefox autofill is overlapping label text despite jquery i have made a login form which contains the labels for username and password with the below jquery used to hide the labels once the user focuses on the fielddocumentreadyfunction formlogin input bindfocuslabelfx function thisprevhide bindblurlabelfx function thisprevthisvalue show hide triggerblurlabelfxand the htmlform methodpost idloginform actionaccountslogin div classinputwrapper label forid usernameusernamelabel input idid username size30 typetext nameusername divformthe problem is that chromes autocomplete appears to be loading the username and password before this scrip can catch it giving me strangely overlapping text until i manually focus on it this is not a problem with firefox pic any suggestions on how to fix this so that autofilled data causes the labels to hide,"['javascript', 'jquery', 'html']" +118115,dead code detection in ruby does anyone know of a production worthy package commercial or oss that can detect which lines of code have been executed or notwere looking around for some tools that can help us detect dead code in a production environment running ruby on rails 187daniel,"['ruby-on-rails', 'ruby']" +118119,sql server select into variable i have the following code in one of my sql 2008 stored procs which executes perfectly fine create procedure dboitem additem customerid uniqueidentifier description nvarchar100 type int username nvarchar100 as begin declare toprelateditemid uniqueidentifier set toprelateditemid select top1 relateditemid from relateditems where customerid customerid declare tempitem table itemid uniqueidentifier customerid uniqueidentifier description nvarchar100 type int username nvarchar100 timestamp datetime insert into item output inserted into tempitem select newid customerid description type username getdate select itemid customerid toprelateditemid description type username timestamp from tempitemendgoso the question for you guys is is there a possibility to do something along the lines ofdeclare tempcustomer table customerid uniqueidentifier firstname nvarchar100 lastname nvarchar100 email nvarchar100select customerid firstname lastname email into tempcustomer from customerwhere customerid customeridso that i could reuse this data from memory in other following statements sql server throws a fit with the above statement however i do not want to have to create separate variables and initialize each one of them via a separate select statement against the same table ughany suggestions on how to achieve something along the lines without multiple queries against the same table,['sql'] +118126,is there a module for python that does facial recognition is there a module for python that does facial recognition it should take in an image and compare it to a different image,['python'] +118132,printing a picture from a console application i am trying to find how to print a picture as in on paper in c i am trying to keep it very simple so no use of winforms and just using console outputi looked for an answer myself but could not make sense of any of the results,"['c#', '.net']" +118168,cmpxchg16b correct this does not exactly seem to be right although i am unsure whyadvice would be great as the documentation for cmpxchg16b is pretty minimal i do not own any intel manualstemplateinline bool casvolatile typesuint128 t src typesuint128 t cmp typesuint128 t with description the cmpxchg16b instruction compares the 128bit value in the rdxrax and rcxrbx registers with a 128bit memory location if the values are equal the zero flag zf is set and the rcxrbx value is copied to the memory location otherwise the zf flag is cleared and the memory value is copied to rdxrax uint64 t cmpp uint64 tcmp uint64 t withp uint64 twith unsigned char result 0 asm volatile lock cmpxchg16b 1nt setz b0nt qresult output msrc input what to compare against rax uint64 t cmpp1 lower bits rdx uint64 t cmpp0 upper bits what to replace it with if it was equal rbx uint64 t withp1 lower bits rcx uint64 t withp0 upper bits memory cc rax rdx rbxrcx clobbered items return resultwhen running with an example i am getting 0 when it should be 1 any ideas,['c++'] +118179,how do you make chrome pinned tabs flash certain google sites such as gmail google voice and i think google reader show a little flash when they update in the background when the window does not have focus this is definitely done through a javascript api i have seen at least one other website imoim do it as wellhow do you make this happen in javascriptif you are not entirely sure what i am talking about here is a short clip,['javascript'] +118208,railsdevise setting a devise cookie to persist across different subdomains i use devise for authentication and want the following to workuser logs in at the user makes a payment at the user returns to to continue using the systemi am following this tutorial but am at the part where i need to make devise do what authlogic does here help,['ruby-on-rails'] +118226,exception at start of request clientauth ssl i have an application embedding jetty i would like to use client cert authentication in ssl and when i enable that i am getting the following exception at start of request but the request is getting served properly after that this exception comes only when accessed from ie or chrome it does not come when accessed from firefox we have our custom sslconnector extending sslsocketconnector i am trying to debug it but wanted to know if there is any specific placecode where i can start checking javaxnetsslsslhandshakeexception remote host closed connection during handshake at comsunnetsslinternalsslsslsocketimplreadrecordsslsocketimpljava808 at comsunnetsslinternalsslsslsocketimplperforminitialhandshakesslsocketimpljava12 at comsunnetsslinternalsslsslsocketimplstarthandshakesslsocketimpljava1139 at comsunnetsslinternalsslsslsocketimplstarthandshakesslsocketimpljava1123 at orgmortbayjettysecuritysslsocketconnectorsslconnectionrunsslsocketconnectorjava631 at orgmortbaythreadboundedthreadpoolpoolthreadrunboundedthreadpooljava451 caused by javaioeofexception ssl peer shut down incorrectly at comsunnetsslinternalsslinputrecordreadinputrecordjava3 at comsunnetsslinternalsslsslsocketimplreadrecordsslsocketimpljava789 updatei enabled ssl debug option and was getting this exception on a read immediately after the serverhellodone message this is the message where server sends its cert along with request for client certificate i believe i am not sure whats happening in first read any help is deeply appreciated clienthello tlsv1 created session1 tls rsa with aes 128 cbc sha serverhello tlsv1 certificate chain certificaterequestcert types rsa dsscert authorities serverhellodonewrite tlsv1 handshake length 703received eofexception errorhandling exception javaxnetsslsslhandshakeexception remote host closed connection during handshakeupdateupdated jdk to latest 23 and tried with the two properties enabledthisabled still geting the same behaviormore infotlsv1 and sslv3 are enabled in all browsers the communication is happening properly without clientauth enabled with client auth always we get exception on first handshake and the next is getting properly done and proceeding without exceptions using jetty version 6114 at server side,['java'] +118229,c interview questions i have just seen two interview questions for which i was unable to find any satisfying answersthe questions arehow many levels deep can include files be nested when should a type cast not be usedcan anyone explain the answers to methanks in advance,['c'] +118251,how to make an immutable object in python although i have never needed this it just struck me that making an immutable object in python could be slightly tricky you cannot just override setattr because then you cannot even set attributes in the init subclassing a tuple is a trick that worksclass immutabletuple def new cls a b return tuple new cls a b property def aself return self0 property def bself return self1 def str self return immutable 0 1formatselfa selfb def setattr self ignored raise notimplementederror def delattr self ignored raise notimplementederrorbut then you have access to the a and b variables through self0 and self1 which is annoyingis this possible in pure python if not how would i do it with a c extensionanswers that work only in python 3 are acceptableupdate so subclassing tuple is the way to do it in pure python which works well except for the additional possibility of accessing the data by 0 1 etc so to complete this question all that is missing is howto do it properly in c which i suspect would be quite simple by just not implementing any geititem or setattribute etc but instead of doing it myself i offer a bounty for that because i am lazy,['python'] +118264,mysql concurrency how does it work and do i need to handle it in my application i am currently running a mysql database all of my tables are using the table engine innodbeveryone who logs into my application can view records and i am worried that at some point two users might update or insert a record at the same time does mysql handle this type of concurrency issue gracefully or is this something that i am going to have to program into my code if i do have to program it into my code how do you go about handling a concurrency case like this,['mysql'] +118269,nondeprecated equivalent of i want to achieve the same aswindowopenlalalaphp lalala but i want to send a http post request instead of a http get request thus i am using the followingformattraction lalalaphp attrtarget lalala w3schoolsorg says this is deprecated attrmethod post appendhiddenparamparam1 param1 appendhiddenparamparam2 param2 submitremove hiddenparam is a function i created that returns an input tag the type attribute set to hidden the id attribute set to the first parameter and the value attribute set to the second parameterhowever the target attribute is deprecated is there any way to achieve what i am trying to do by nondeprecated means,['html'] +118282,simd why is the sse rgb to yuv color conversion about the same speed as the c implementation i have just tried to optimize an rgb to yuv420 converter using a lookup table yielded a speed increase as did using fixed point arithmetic however i was expecting the real gains using sse instructions my first go at it resulted in slower code and after chaining all the operations it is approximately the same speed as the original code is there something wrong in my implementation or are sse instructions just not suited to the task at handa section of the original code followsdefine rrgb24yuvci2 00 0299define rrgb24yuvci2 01 0587define rrgb24yuvci2 02 0114define rrgb24yuvci2 10 0147define rrgb24yuvci2 11 0289define rrgb24yuvci2 12 0436define rrgb24yuvci2 20 0615define rrgb24yuvci2 21 0515define rrgb24yuvci2 22 0100void realrgb24toyuv420converterconvertvoid prgb void py void pu void pv yuvtype py yuvtype py yuvtype pu yuvtype pu yuvtype pv yuvtype pv unsigned char src unsigned char prgb y have range 0255 you v have range 128127 double uv double rgb step in 2x2 pel blocks 4 pels per block int xblks width 1 int yblks height 1 forint yb 0 yb yblks yb forint xb 0 xb xblks xb int chroff ybxblks xb int lumoff yb width xb 1 unsigned char t src lumoff3 top left pel b doublet g doublet r doublet pylumoff yuvtyperrgb24yuvci2 rangecheck 0to255int05 rrgb24yuvci2 00r rrgb24yuvci2 01g rrgb24yuvci2 02b you rrgb24yuvci2 10r rrgb24yuvci2 11g rrgb24yuvci2 12b v rrgb24yuvci2 20r rrgb24yuvci2 21g rrgb24yuvci2 22b top right pel b doublet g doublet r doublet pylumoff1 yuvtyperrgb24yuvci2 rangecheck 0to255int05 rrgb24yuvci2 00r rrgb24yuvci2 01g rrgb24yuvci2 02b you rrgb24yuvci2 10r rrgb24yuvci2 11g rrgb24yuvci2 12b v rrgb24yuvci2 20r rrgb24yuvci2 21g rrgb24yuvci2 22b lumoff width t t width3 6 bottom left pel b doublet g doublet r doublet pylumoff yuvtyperrgb24yuvci2 rangecheck 0to255int05 rrgb24yuvci2 00r rrgb24yuvci2 01g rrgb24yuvci2 02b you rrgb24yuvci2 10r rrgb24yuvci2 11g rrgb24yuvci2 12b v rrgb24yuvci2 20r rrgb24yuvci2 21g rrgb24yuvci2 22b bottom right pel b doublet g doublet r doublet pylumoff1 yuvtyperrgb24yuvci2 rangecheck 0to255int05 rrgb24yuvci2 00r rrgb24yuvci2 01g rrgb24yuvci2 02b you rrgb24yuvci2 10r rrgb24yuvci2 11g rrgb24yuvci2 12b v rrgb24yuvci2 20r rrgb24yuvci2 21g rrgb24yuvci2 22b average the 4 chr values int iu intu int iv intv ifiu 0 rounding iu 2 else iu 2 ifiv 0 rounding iv 2 else iv 2 puchroff yuvtype chroff rrgb24yuvci2 rangecheck n128to127iu4 pvchroff yuvtype chroff rrgb24yuvci2 rangecheck n128to127iv4 end for xb ybend convertand here is the version using sseconst float frrgb24yuvci2 00 0299const float frrgb24yuvci2 01 0587const float frrgb24yuvci2 02 0114const float frrgb24yuvci2 10 0147const float frrgb24yuvci2 11 0289const float frrgb24yuvci2 12 0436const float frrgb24yuvci2 20 0615const float frrgb24yuvci2 21 0515const float frrgb24yuvci2 22 0100void realrgb24toyuv420converterconvertvoid prgb void py void pu void pv m128 xmm y mm loadu psfcoeff 0 m128 xmm you mm loadu psfcoeff 1 m128 xmm v mm loadu psfcoeff 2 yuvtype py yuvtype py yuvtype pu yuvtype pu yuvtype pv yuvtype pv unsigned char src unsigned char prgb y have range 0255 you v have range 128127 float bgr14 bgr13 00 float bgr24 bgr23 00 float bgr34 bgr33 00 float bgr44 bgr43 00 step in 2x2 pel blocks 4 pels per block int xblks width 1 int yblks height 1 forint yb 0 yb yblks yb forint xb 0 xb xblks xb int chroff ybxblks xb int lumoff yb width xb 1 unsigned char t src lumoff3 bgr12 floatt bgr11 floatt bgr10 floatt bgr22 floatt bgr21 floatt bgr20 floatt t t width3 6 bgr32 floatt bgr31 floatt bgr30 floatt bgr42 floatt bgr41 floatt bgr40 floatt m128 xmm1 mm loadu psbgr1 m128 xmm2 mm loadu psbgr2 m128 xmm3 mm loadu psbgr3 m128 xmm4 mm loadu psbgr4 y m128 xmm res y mm mul psxmm1 xmm y pylumoff yuvtyperrgb24yuvci2 rangecheck 0to255xmm res ym128 f320 xmm res ym128 f321 xmm res ym128 f322 y xmm res y mm mul psxmm2 xmm y pylumoff 1 yuvtyperrgb24yuvci2 rangecheck 0to255xmm res ym128 f320 xmm res ym128 f321 xmm res ym128 f322 lumoff width y xmm res y mm mul psxmm3 xmm y pylumoff yuvtyperrgb24yuvci2 rangecheck 0to255xmm res ym128 f320 xmm res ym128 f321 xmm res ym128 f322 y xmm res y mm mul psxmm4 xmm y pylumoff1 yuvtyperrgb24yuvci2 rangecheck 0to255xmm res ym128 f320 xmm res ym128 f321 xmm res ym128 f322 u m128 xmm res mm add ps mm add ps mm mul psxmm1 xmm u mm mul psxmm2 xmm u mm add ps mm mul psxmm3 xmm u mm mul psxmm4 xmm u float fu xmm resm128 f320 xmm resm128 f321 xmm resm128 f322 v xmm res mm add ps mm add ps mm mul psxmm1 xmm v mm mul psxmm2 xmm v mm add ps mm mul psxmm3 xmm v mm mul psxmm4 xmm v float fv xmm resm128 f320 xmm resm128 f321 xmm resm128 f322 average the 4 chr values int iu intfu int iv intfv ifiu 0 rounding iu 2 else iu 2 ifiv 0 rounding iv 2 else iv 2 puchroff yuvtype chroff rrgb24yuvci2 rangecheck n128to127iu 2 pvchroff yuvtype chroff rrgb24yuvci2 rangecheck n128to127iv 2 end for xb ybthis is one of my first attempts at sse2 so perhaps i am missing something fyi i am working on the windows platform using visual studio 2008,['c++'] +118291,troubles of adding a new id auto increment after table exist i have a table with 380 records but without any auto increment column like idnow i have to add an id column and i am wondering could there be troubles,['mysql'] +118313,efficiently solving a letternumber problem in python if a 15 and 152 is represented as a2 while 215 is represented as 2a then a number x has to be found such that8x 8x8i tried this naive python code i 0 whilei10 ifint8stri8intstri8 break i i1 print ibut it is taking a huge amount of time to produce a correct resulthow to optimize the code,['python'] +118325,codeigniter database how to update multiple tables with a single update query i saw this on the codeigniter forum considering the below codeupdate ainner join b using idset afirstnamepekka alastnamekuronenbcompanynamesuomi oybcompanyaddressmannerheimtie 123 helsinki suomiwhere aid1 this is how you would apparently do it in codeigniterthisdbsetafirstname pekkathisdbsetalastname kuronenthisdbsetbcompanyname suomi oythisdbsetbcompanyaddress mannerheimtie 123 helsinki suomithisdbwhereaid 1thisdbjointable2 as b aid bidthisdbupdatetable as athis does not work in reality i have had a look a the sql which this produces and the results do not even mention the join does anyone have any idea how to do an update with a join using codeigniters active record database class,['mysql'] +118326,java unchecked call to comparetot as a member of the raw type javalangcomparable i am trying to implement a sorted list as a simple exercise in java to make it generic i have an addcomparable obj so i can use it with any class that implements the comparable interfacebut when i use objcompareto anywhere in the code i get unchecked call to comparetot as a member of the raw type javalangcomparable from the compiler with xlintunchecked option the code works just fine but i cannot figure out how to get rid of that annoying messageany hints,['java'] +118329,volatile datetime as datetime cannot be declared as volatile is this right private datetime time public datetime time get threadmemorybarrier return time set time value threadmemorybarrier that property could be accessed from different threads so i want to ensure they get always the latest version without use contention lockediti have a collection of hardtocreate items each one has a datetime property named creationtime indicating when this item was created it is initialized to datetimeutcnowevery time a item is accessed that property is updated to datetimeutcnowthere is a thread that executes in timely fashion in a threaded timer that checks if datetimeutcnow 1 hour itemcreationtime if true it deletes the itemi want to ensure that when the deletion thread comes into the collection all the items have their latest last access datetime on it so i can avoid create the item again just because a cache held the value for a couple of milliseconds dthanks in advance,"['c#', '.net']" +118331,monotouch global exception handling i am having a nasty bug show up in the wild and i cannot put my finger on it is there a way to have a global trycatch block or a way to handle any exception that is unhanded in monotouch can i just wrap uiapplicationmainargs in a try catchafter the exception is caught id like to show a uialertview to thisplay the resultsany help,"['c#', 'ios']" +118333,virtualenv python and subversion i am trying to use the python subversion swig libraries in a virtualenv nositepackages environment how can i make this work,['python'] +118334,check if page added to iphone homescreen is it possible to check using javascript or css if a page has been added to the iphone homescreen in webapp mode like getting the height of the screen which wouldnt have the nav bar so would be 460px,"['javascript', 'iphone']" +118341,monkey giving an odd error on android emulator i am letting monkey run on my app via android emulator using the following instructionmonkey p packagename v 50i am getting the following errors0128 1145392 errormediaplayerservice34 error 20128 1145392 errormediaplayer58 unable to to create media player0128 114558783 errormediaplayerservice34 error 20128 114558783 errormediaplayer58 unable to to create media player0128 114613742 errormediaplayerservice34 error 20128 114613752 errormediaplayer58 unable to to create media playerthis happens over and over again every few seconds and is the only error that occurs this is odd because my app does not touch any media player functionality at all it is a simple notetodo app any insight into what monkey is touching that is causing the error and what i could do to prevent itor can this be safely ignoredthanksediti think i found the source of my issue apparently monkey managed to put my keyboard into some sort of asian language and whenever the bottom left key two asian characters is pressed in the soft keyboard image below i receive the mediaplayer error does anyone know what this key does,['android'] +118345,hudson and mavenreleaseplugin i am using hudson with the mavenreleasepluginas you may know the mavenreleaseplugin builds project in 2 steps releaseprepare then releaseperformhow should i configure hudson to execute releaserollback in case releaseperform failed,['java'] +118349,matplotlib not thisplaying figures this must be a really basic question i am trying to use matplotlib heres the basic example from the documentationimport numpy as npimport matplotlibpyplot as pltx nparange0501y npsinxpltplotxyi have tried this in ipython bpython and the default interpreter ubuntu 1010 64 bit and all i get are messages likematplotliblinesline2d object at 0x3f14a90what am i doing wrong,['python'] +118355,nlog write null to optional database column i am using nlog for logging in an aspnet application and making use of the database target with microsoft sql serveri have some logging parameters that are optional and not always specified i would like these to be written as null when they are not provided however nlog seems to always write them as empty stringsis there a way to configure it to write null as the defaultref,"['c#', '.net', 'asp.net']" +118358,default css filename for html we have indexhtml the file thats automatically loaded by the webserver if no filenames are specified is there an equivalent for css either from the webserver point of view or just by convention surely it is not indexcss rightthanksupdatei guess i phrased my question a little poorly i already knew that css files would not be loaded automatically i was just wondering if there was a strong convention for default css files although there exists no strong convention there are common names as listed by the people who answered some of which aredefaultcssmaincsswebcstylecsitecssor you can name the css file with the same filename as the html file that uses it,['css'] +118359,function inside function simple example two methods one called from anotherdef method aarg some data method bargdef method barg return some datain python we can declare def inside another def so if method b is required for and called only from method a should i declare method b inside method a like this def method aarg def method barg return some data some data method bor should i avoid doing this,['python'] +118374,how can i exclude data for certain tables but keep structure with mysqldump i am doing a regular dump of a database that uses the database for logging i need to create a mysqldump command that dumps everything from the database but excludes the row information for the log tables i see the nodata parameter but that does not seem to support selecting only certain tables,['mysql'] +118383,how can i specialize a typedef and its implicit type differently i have something like thistypedef int anothertypetemplate typename t func t value and i want to specialize these two cases separatelytemplate bool funcint int value template bool funcanothertype anothertype value i do not really need to specialize for int what i really need is to execute a different function for anothertype and i cannot change the definition of anothertype or the base functionoverloading does not help either because of sfinae,['c++'] +118389,updatesourcetriggerpropertychanged equivalent for a windows phone 7 textbox is there a way to get a textbox in windows phone 7 to update the binding as the user types each letter rather than after losing focus like the following wpf textbox would dotextbox textbinding pathtextproperty updatesourcetriggerpropertychanged,['c#'] +118394,does calling last on an ilist iterate the entire list does the last extension method take into account if it is called on an ilist i am just wondering if there is a significant performance difference between theseilistint numbers new int 1 2 3 4 5 6 7 8 9 int lastnumber1 numberslastint lastnumber2 numbersnumberscount1intuition tells me that the first alternative is on but the second is o1 is last smart enough to try casting it to an ilist,['c#'] +118395,creating a javascript local applicationran in browser i would like to write an application that would use both javascript and html as for the user interface the app wouldnt really need an internet connection but will need access to the users local filesmy first thought was that this would be impossible in a browser due to the security restrictions on the access to local filesmy second thought was to try to use webkit directly from c and use python instead of javascript but that seems rather complicated and i feel like overkilling by using qtmy third thought was to use a signed java applet to make all local accesses but then i am not too sure of this eitherany suggestions on what i should do,"['javascript', 'html']" +118406,have i reached the limits of the size of objects javascript in my browser can handle i am embedding a large array in script tags in my html like this nothing surprisingscript var largearray lots of stuff in here scriptin this particular example the array has 210 elements that is well below the theoretical maximum of 231 by 4 orders of magnitude heres the fun part if i save js source for the array to a file that file is 44 megabytes 46573399 bytes to be exactif you want to see for yourself you can download it from github all the data in there is canned so much of it is repeated this will not be the case in productionnow i am really not concerned about serving that much data my server gzips its responses so it really does not take all that long to get the data over the wire however there is a really nasty tendency for the page once loaded to crash the browser i am not testing at all in ie this is an internal tool my primary targets are chrome 8 and firefox 36in firefox i can see a reasonably useful error in the consoleerror script stack space quota is exhaustedin chrome i simply get the sadtab pagecut to the chase alreadyis this really too much data for our modern highperformance browsers to handleis there anything i can do to gracefully handle this much dataincidentally i was able to get this to work read not crash the tab onandoff in chrome i really thought that chrome at least was made of tougher stuff but apparently i was wrongedit 1crayon i was not looking to justify why i would like to dump this much data into the browser at once short version either i solve this one admittedly notthateasy problem or i have to solve a whole slew of other problems i am opting for the simpler approach for nowvarious right now i am not especially looking for ways to actually reduce the number of elements in the array i know i could implement ajax paging or whathaveyou but that introduces its own set of problems for me in other regardsphrogz each element looks something like thisdatetimenew date129617640 terminalidterminal9 general buildversion1005a v110119 beta ssm extid26680 md cdma netloader no bcast validfalse md cdma netloader no bcast pngattempt0will but i have a computer with a 4core processor 6 gigabytes of ram over half a terabyte of thisk space and i am not even asking for the browser to do this quickly i am just asking for it to work at all a1edit 2mission accomplishedwith the spoton suggestions from juan as well as guffa i was able to get this to work it would appear that the problem was just in parsing the source code not actually working with it in memoryto summarize the comment quagmire on juans answer i had to split up my big array into a series of smaller ones and then arrayconcat them but that was not enough i also had to put them into separate var statements like thisvar arr0 var arr1 var arr2 var bigarray arr0concatarr1 arr2 to everyone who contributed to solving this thank you the first round is on meother than the obvious sending less data to the browser,['javascript'] +118410,what are the various python cmss and their statuses i am usually a php developer that has lots of experience with drupal cms framework and i realize drupal is very mature but i do not know much about the python scene i have heard the following cmss be mentionedplonedjango frameworkwhat other cmss are there and what do you think are some of the pros and cons how mature are they is it even worth starting to use python for general web development,['python'] +118427,how do i execute an authenticated ajax request without resetting the tomcats session timeout i have got an existing grails web application that is in production and has a 30 minute session timeout we are running tomcat tcserver when a user is authenticated and on certain pages i want to make some periodic polling ajax requests to the server that do not extend this 30 minute session timeout so that our session timeout is not thwartedthe question is similar to this unanswered aspnet question but none of the answers there will do and this in the javatomcat realm how do i execute an authenticated ajax request without resetting the tomcats session timeoutis there some sort of filter or urlmatching mechanism that i can use to exclude requests from extending the session timeout,['java'] +118431,how to use mysql decimal i cannot quite get a grasp of mysqls decimal i need the row to be able to contain a number anywhere from 01 to 9 how would i structure it to work like so,['mysql'] +118445,how to get the selected item from listview in my android app i have created a listview component called mylist and filled it with objects of my own custom typeclass myclass private string thisplayname private string thevalue here constructor getters setters and tostring are implementedi used the arrayadapter to bound the arraylist theobjects with mylistarrayadaptermyclass adapter new arrayadaptermyclassthis rlayoutlay item theobjectsmylistsetadapteradapterthis works fine the list is populated and etc but when i am trying to access the selected item i receive a null object i have done this using mylistsetonitemclicklistenernew onitemclicklistener public void onitemclickadapterview adapter view v int position long id myclass selitem myclass mylistgetselecteditem string value selitemgetthevalue getter methodwhat seems to be the problem thank you,['android'] +118449,usb communication with androidarduino i am working on this android application that needs to communicate over usb i have an archos 101 tablet specifications here 101itspecshtmlcountryuslangen it has a full usb host port i can put a flash usb drive in the usb port and copy files to and from the flash drive onto internal storage i have this arduino fio board with an xbee attached to it i have an xbee explorer dongle with another xbee that i plan to hook into the archos 101 tablet into the usb portas of right now i can put the xbee explorer dongle into my computer and sendreceive data to and from the arduino fio no problems is there a way for android to talk over usb i know there has to be drivers somewhere in the tablet allowing usb communication but i cannot find a way to access them or use them i can see android recognizing the xbee explorer dongle i downloaded a terminal emulator and i can type dmesg and see that it sees the dongle hooked up but i cannot do anything with iti seem to need a ftdi driver for android i would greatly appreciate any help in getting my tablet to communicate with the xbee explorer dongle,['android'] +118453,android mediaplayer how to use surfaceview or mediaplayer to play video in correct size i am playing local video file using mediaplayer and surfaceview surfaceview is the only control in activity while my video files are qvga or other problem is that video is getting stretched how can i play video in its original size eg qvga with remaining area blackfrom iterationwhen i am forcefully sets layout heightwidth of surfaceview in xml video thisplayed finesurface holdersetfixedsizewh has no effect neither mpsetthisplayplease guide in thisupdatexml fliexml version10 encodingutf8framelayout xmlnsandroid androidididhome container androidlayout widthfill parent androidlayout heightfill parentsurfaceview androidididsurface androidlayout widthfill parent androidlayout heightwrap content androidpaddingtop10dip framelayoutmediaplayer usage is as per following linkthanks in advance,['android'] +118456,php saving object in session i am trying to save an object in session but the followingphpuser dbload username pass session user user on subsequent page loadsuser session user retrieve the user from sessionunfortunately this does not workthe script tried to execute a method or access a property of an incomplete object please ensure that the class definition user of the object you are trying to operate on was loaded before unserialize gets called or provide a autoload function to load the class definitionunless you use serializephpuser dbload username pass session user serialize user on subsequent page loadsuser unserialize session user retrieve the user from sessioni am assuming a serialize is required because session info is saved out to thisk but should not php be smart enough to serialize stuff on its ownand with the use of serialize unserialize is this going to work now reliably or do i need a serialize method in my php class,['php'] +118482,how to change html object element data attribute value in javascript how do you change html object element data attribute value in javascripthere is what i am trying object typetexthtml idhtmlframe styleborder none standbyloading width100object var element documentgetelementbyidhtmlframe elementsetattributedata,"['javascript', 'html']" +118494,does python have a built in function for string natural sort using python 3x i have a list of strings for which i would like to perform a natural alphabetical sort natural sort the order by which files in windows are sortedfor instance the following list is naturally sorted what i wantelm0 elm1 elm2 elm9 elm10 elm11 elm12 elm13and heres the sorted version of the above list what i haveelm11 elm12 elm2 elm0 elm1 elm10 elm13 elm9i am looking for a sort function which behaves like the first one,['python'] +118496,how to use base64 included in android since api 8 22 in a android project api 3 android 15 i need to use base64 on my app import androidutilbase64 but base64 was included in android with 22 api lvl 8 then when i make the import i get this error base64 cannot be resolved and does not give me the possibility to import it because i am making my project with api lvl 3 for some reasons my app have to be compatible with old versions of android 15 16 etcit is possible to use base64 without migrating to api lvl8,['android'] +118503,c reflection why getfields list fields that i have not created how to exclude them this code returns fields that i created but also some system fields i am in wpf app i did not create myselffieldinfo fieldinfosfieldinfos thisgettypegetfieldsbindingflagsnonpublic bindingflagsinstancehow to exclude the system fields and keep only my own update these fields are not fields i inherited from my own class either,"['c#', '.net']" +118507,how to convert a base64 string into a bitmap image to show it in a imageview i have a base64 string that represents a bitmap imagei need to transform that string into a bitmap image again to use it on a imageview in my android apphow to do itthis is the code that i use to transform the image into the base64 string proceso de transformar la imagen bitmap en un stringandroidsrcclogopngresources r thisgetresourcesbitmap bm bitmapfactorydecoderesourcer rdrawablelogobytearrayoutputstream baos new bytearrayoutputstream bmcompressbitmapcompressformatpng 100 baos bm is the bitmap object byte b baostobytearraystring encodedimage base64encodeb base64defaultencodedimage base64encodebytesb,['android'] +118511,java generics get class i got a list programmed like this public class mylistt is there any way to use the t variable to get the name of class so i can from within mylist know if t is string socket etcedit nevermind found the answer here,['java'] +118522,how can i edit a jar file possible duplicatemodifying a file inside a jar so i have a jar file with one class file on it i just need to change some words in the filewhat program should i usei want this to work for my phone,['java'] +118538,select from mysql table between datetime x min ago and datetime x min ago i think i summed nicely it up in the title i want to select online users from a specific time to another specific time my table look like thiscreate table online id bigint20 not null auto increment username varchar 16 not null ip varchar39 not null default time datetime not null default 0 0 primary key idi want a query that return the usernames that have been online the last 15 minutes and a query for the users that have been online the last 60 minutes but not the last 15 minutes so the querys do not return the same values this i do not know how to do,"['sql', 'mysql']" +118543,java hashmap duplicate elements i want to add duplicate elements on hashmapsoputname1 1putname1 3putname1 3putname2 1putname2 3how i can do that,['java'] +118552,reverse object in jqueryeach htmlinput idsdata typehidden value16511211650300164920016481321647110164610016451201644801643161164210116411001640183 jsvar data parsejsonsdatavaleachdata functionid sc alertidout 1640 1641 1642 1651how to make it in reverse order ex 1651 1650,"['javascript', 'jquery']" +118555,regex to strip all directorynames from path leave filename i want to remove all directorynames from a pathpayloadbrownieappinfoplistshould becomeinfoplistwhat regex should i use or can i use replace from string in javathanks,['java'] +118561,python pyqt popup window so i have been creating my gui with qt for my python application i have now come to a situation where after a button has been pushed the appropriate deferred gets executed we perform some tasks then i need to open up a separate window that contains one or two things but i cannot seem to figure out how to create this new separate window could anyone give me an example of how to create one,['python'] +118579,array initialization with default constructor public class sample static int count 0 public int abc public sample abc samplecount i want to create an array of above class and want each element in the array to be initialized by invoking the default constructor so that each element can have different abcso i did thissample samples new sample100but this does not do what i think it should do it seems this way the default constructor is not getting called how to invoke default constructor when creating an arrayi also would like to know what does the above statement do,['c#'] +118593,how can i hook a youtube video flash player to slow down playback the only good software i know which can decelerate and accelerate the playback of a youtube video in any browser without first downloading it because that would be cumbersome is enounce myspeedunfortunately this software is not free and my trial version ran out i was playing around with its registry settings and noticed a few keysprogramstohook iexploreexefirefoxexeplugincontainerexechromeexesafariexeoperaexemaxthonexefeeddemonexerealplayexeflvplayerexeflv playerexeflockexeadobe media playerexeuseflashadapter 1llmodules ole32dllnspr4dllchromeexerealplayexeobjb3201dlloleaut32dllrpflashplayerdllmodulestointercept flash10flash9npswf32dllgcswf32dllfldbg10flashplayer311kocxadobe media playerexebased on the names and values of these registry keys i am guessing the myspeed software hooks some functions in the listed modules but modules are or are not the same as dlls and does so for each process listed in programstohook this is what i do not understand what is the concept of the myspeed software obviously it is hooking something but i am not too familiar with the intricacies of windows hooks so i came to ask you experts i am thinking if i can understand how this hook process works i can make my own version of the software using easyhook which is a fantastic net library to perform usermode and kernelmode hooksi thought that windows usermode hooking goes something like this you choose one function in one dll and you intercept that function aka hook in one process you want if you want to hook the dll in multiple processes you just have to repeat the procedure for each processand then kernelmode hooking is just choosing one function in one dll and intercepting that function in every process that calls it hence kernelmode but surely there are tons of ways to hook i am not too sure on whats the difference between these two hooks and dll injection eitherso the point is i would like to know how myspeed works what is their hooking concept if i can know this then i can make such a software in netthanks in advance,['c#'] +118600,i want to build a chat room using rails should i use juggernaut 2 or cramp originally i planned to use juggernaut however it is not compatible with rails 3 and new juggernaut 2 seems to be completely independent from rails which is not what i want then i found cramp it looks quite neat but is still under development so i am just wondering which framework should i use or is there a better one thanks,['ruby-on-rails'] +118604,how to align a pointer in c is there a way to align a pointer in c suppose i am writing data to an array stack so the pointer goes downward and i want the next data i write to be 4aligned so the data is written at a memory location which is a multiple of 4 how would i do thati have uint8 t ary1024 ary ary1024 ary now suppose that ary points at location 0x05 i want it to point to 0x04now i could just do ary ary 4but c does not allow modulo on pointers is there any solution that is architecture independent,['c'] +118608,how do i use python to easily expand variables to strings whats a nice idiom to do thisinstead ofprint s is a s s that s name adjective noun verbi want to be able to do something to the effect ofprint name is a adjective noun that verb,['python'] +118624,how to get the end event of catransitionanimation my codes show belowcatransition transition catransition animationtransitionduration duration i hope to get the end event of catransitionanimationis it psossiblethanksinterdev,['iphone'] +118634,what is the use of bytebuffer in java what are example applications for a bytebuffer in java please list any example scenarios where this is used thank you,['java'] +118647,android app development without eclipseadt i would like to learn android app development but i do not want to use any ide especially eclipse and its adt plug in it is just that i am more comfortable with command line executing commands myself and seeing whats going on beneath i am looking for a good referencetutorialebookwalk through on the flow is there any such resources available,['android'] +118652,autowidth of comboboxs content is anybody know of a way to make the comboboxs contents width to autosizei do not mean to combobox itself just the opened content,"['c#', '.net']" +118660,when to thispatch release i am fairly new to gcd and was trying to find an answer to this assuming i have the following codethispatch queue t queue thispatch queue createqueue nullthispatch asyncqueue do some stuffwhere in the code should i release the queue inside or outside the block,"['iphone', 'objective-c']" +118666,run function when page is loaded i want to run a function when the page is loaded but i do not want to use it in the body tagi have a script that runs if i initialise it in the body like thisfunction codeaddress codebody onloadcodeaddressbut i want to run it without the body onloadcodeaddress and i have tryed a lot of things eg thiswindowonload codeaddressbut it is not workingso how do i run it when the page is loaded,['javascript'] +118680,net how do i invoke a delegate on a specific thread isynchronizeinvoke thispatcher asyncoperation synchronizationcontext etc note first of all that this question is not tagged winforms or wpf or anything else guispecific this is intentional as you will see shortlysecond sorry if this question is somewhat long i try to pull together various bits of information floating around here and there so as to also provide valuable information my question however is right under what i would like to knowi am on a mission to finally understand the various ways offered by net to invoke a delegate on a specific threadwhat i would like to knowi am looking for the most general way possible that is not winforms or wpfspecific to invoke delegates on specific threadsor phrased differently i would be interested if and how the various ways to do this such as via wpfs thispatcher make use of each other that is if there is one common mechanism for crossthread delegate invocation that is used by all the otherswhat i know alreadythere is many classes related to this topic among themsynchronizationcontext in systemthreadingif i had to guess that would be the most basic one although i do not understand what exactly it does nor how it is usedasyncoperation asyncoperationmanager in systemcomponentmodelthese seem to be wrappers around synchronizationcontext no clue how to use themwindowsformssynchronizationcontext in systemwindowsformsa subclass of synchronizationcontextisynchronizeinvoke in systemcomponentmodelused by windows forms the control class implements this if i would have to guess i would say this implementation makes use of windowsformssynchronizationcontextthispatcher thispatchersynchronizationcontext in systemwindowsthreadingseems like the latter is another subclass of synchronizationcontext and the former delegates to itsome threads have their own message loop along with a message queuethe msdn page about messages and message queues has some introductory background information on how message loops work at the system level ie message queues as the windows apii can see how one would implement crossthread invocation for threads with a message queue using the windows api you would put a message into a specific threads message queue via postthreadmessage that contains an instruction to call some delegate the message loop which runs on that thread will eventually get to that message and the delegate will be calledfrom what i have read on msdn a thread does not automatically have its own message queue a message queue will become available eg when a thread has created a window without a message queue it does not make sense for a thread to have a message loopso is crossthread delegate invocation possible at all when the target thread has no message loop let us say in a net console application judging from the answers to this question i suppose it is indeed impossible with console apps,['.net'] +118681,any java libraries or frameworks providing doubleentry accounting and ledger functionality i would like to be able to do crud operations on the following typesbank accountstransactionsclientsinvoices suppliersand particularly i would like to be able to calculate uk vati am looking for something more accounting orientated than erp orientated like for example openbravoreporting is not really an issue as i am using birt reports elsewhere in the system and would be using that for outputting reportssomething similar to gnucash with a java api would be perfect there is a jgnucash lib but it seems to lack the functionality for the mysql backend that i requiream usingedit ok i see that this question has been asked a number of times before without a complete solution so i will update the post with my current research status and see if it encourages anyone experts to chime injgnucashthere is a java reimplementation of the gnucash file format hereit has limited mysql functionality compared to the original xml file format and has been fully released as open source though it would take quite a bit of work to get into into useopenbravois probably the best bet at the moment as it provides accounts transactions invoices billing and has a lot of pluginsmartin fowler has a lot of information on the actual design of accounting oo models herethere are a number of other erp or double ledger based offerings in java such as jfire jmoney compiere which i will endeavour to evaluate,['java'] +118699,why is a a in c void main ifa a printfyes equal else printfno not equalwhy is the output no not equal,['c'] +118711,initialization of java class vs interface i am stuck at the below concept of initialization of java class and interface i read the following sentence in the below mentioned book an interface is initialized only because a nonconstant field declared by the interface is used never because a subinterface or class that implements the interface needs to be initialized but that is not the case when we initialise any java class thus initialization of a class requires prior initialization of all its superclasses but not its superinterfaces initialization of an interface does not require initialization of its superinterfacesmy question is why is this so any help would be greatly appreciated thanksps book inside the java virtual machine by bill venners chapter 7 lifetime of a class,['java'] +118714,python the mechanism behind list comprehension when using list comprehension or the in keyword in a for loop context iefor o in x do something withoorlo for o in xhow does the mechanism behind in works which functionsmethods within x does it call if x can comply to more than one method whats the precedence how to write an efficient x so that list comprehension will be quick,['python'] +118725,no route matches controller show scaffold generated code i started a rails app using scaffold the app relates people to institutions when i go to httplocalhost30peoplei get the following errorno route matches controllerpeople actionshow idperson pid 302 name and so onif i remove all the link to cells in the scaffoldgenerated table the page loads just fine this error happens for all the indexhtmlerb files in my appheres my peopleindexhtmlerbh1listing peopleh1table tr thth thth thth thth tr peopleeach do person tr td personname td td link to show person td td link to edit edit person pathperson td td link to destroy person confirm are you sure method delete td tr end tablebr link to new person new person path and the beginning of my controllerspeoplerb class peoplecontroller applicationcontroller get people get peoplexml def index people personallorder year grad name respond to do format formathtml indexhtmlerb formatxml render xml people end end get people1 get people1xml def show person personfindparamsid respond to do format formathtml showhtmlerb formatxml render xml person end endand the results of rake routespeople get peopleformat controllerpeople actionindexpost peopleformat controllerpeople actioncreatenew person get peoplenewformat controllerpeople actionnewedit person get peopleideditformat controllerpeople actioneditperson get peopleidformat controllerpeople actionshowput peopleidformat controllerpeople actionupdatedelete peopleidformat controllerpeople actiondestroyhome index get homeindexformat controllerhome actionindexroot format controllerhome actionindexand the migration for peopleclass createpeople activerecordmigration def selfup create table people id false primary key pid do t tinteger pid null false tstring name tstring degree tinteger phd area tstring thesis title tinteger year grad tinteger instid phd tinteger year hired tinteger instid hired tinteger schoolid hired tinteger deptid hired tstring email tstring notes tinteger hire rankid tinteger tenure track tinteger prev instid tinteger prev rankid end end def selfdown drop table people endendand here is my routesrb file minus the commented lines that scaffolding automatically generatesihiringapplicationroutesdraw do resources ranks departments institutions schools people get homeindex root to homeindexenddoes it have something to do with setting a different primary key for the table i am not sure if it is a model or routes problem or something i have not thought of i did restart my rails server after scaffolding,['ruby-on-rails'] +118730,differences between iqueryable list ienumerator i am wondering what the different is between iqueryable list ienumerator and when i should using each onefor instance when using linq to sql i would do something like thispublic listuser getusers return dbuserwhere some query here tolistnow i am wondering if i should be using iqueryable instead but i am unsure of the advantages of using it over the list,['c#'] +118739,how to call methods of a service from activity i simply want to call methods of a local service from my activity how can i do that,['android'] +118740,gem available in irb but not rails console i am trying to use the redcloth gem in my rails project when i used irb i can load the gemrequire rubygemsrequire redclothand it works fine but when i try the same thing in the rails console i get an error message stating that the gem cannot be founddoes anyone have any idea what might cause this,"['ruby-on-rails', 'ruby']" +118746,why is there insertorthrow but no updateorthrow or deleteorthrow i am creating android app that uses sqlite database looking at the sqlitedatabase class i found that there is a method called insertorthrow which is similar to insert but with one important difference if insert fails it will throw exception and app will die if not catched i am using insertorthrow in the initial stage of the development because it draws my attention to sql errors in a very noticeable way ie app diesi am just curious why is there no updateorthrow deleteorthrow etc i have tried to google for info but did not found anything,['android'] +118754,error lnk2019 unresolved external symbol main referenced in function tmaincrtstartup i do not know whats wrong with it i cannot find where the error is commenting out the implementation does not resolve the error eitherheader fileifndef main savitch sequence hdefine main savitch sequence hinclude cstdlib provides size tnamespace main savitch 3 class sequence public typedefs and member constants typedef double value type typedef stdsize t size type static const size type capacity 30 constructor sequence modification member functions void start void advance void insertconst value type entry void attachconst value type entry void remove current constant member functions size type size const bool is item const value type current const private value type datacapacity size type used size type current index endifsourceinclude sequence1hinclude asserthnamespace main savitch 3 default constructer sequence is empty sequencesequence used current index 0 start the iteration void sequencestart current index 0 iterate void sequenceadvance current index number of items in the sequence sequencesize type sequencesize const return used checks if there is a current item bool sequenceis item const return current index used used 0 returns the current value sequencevalue type sequencecurrent const assertis item no current item return datacurrent index adds an item before the current index void sequenceinsertconst value type entry assertentry 0 pointer is invalid assertcurrent index sequencecapacity no room to add an item move items up starting with the last item and working down to the current item arrays start at 0 so the 1 adjusts it for size type i used 1 i current index i datai 1 datai datacurrent index entry adds an item after the current index void sequenceattachconst value type entry assertentry 0 pointer is invalid assertcurrent index sequencecapacity no room to add an item move items up starting with the last item and working down to the current item arrays start at 0 so the 1 adjusts it for size type i used 1 i current index i datai 1 datai if current index 0 dataused entry else datacurrent index 1 entry removes the current item void sequenceremove current for size type i current index i used i datai datai 1,['c++'] +118774,lock aqcuired and further attempts to lock do not block are c locks reentrant i have written a test of what i think should be a valid case for a deadlock it appears that once the lock has been acquired by an instance of the a class that instance does not need to reacquire the lock anymore even if i explicitly try to call another method that should lock again here is the classinternal class tester private readonly object sync new object public tester public void testlock lock sync for int i 0 i 10 i deadlocki private void deadlockint i lock sync tracewritelinei no deadlock output0 no deadlock 1 no deadlock 2 no deadlock 3 no deadlock 4 no deadlock 5 no deadlock 6 no deadlock 7 no deadlock 8 no deadlock 9 no deadlocki would have thought that this would cause a deadlock can anybody shed some light on this,"['c#', '.net']" +118777,how can i effectively debug c code that is wrapped with jni in eclipse android dev i have got a segfault but i have absolutely no idea how to locate ittips,"['java', 'android', 'c']" +118788,c11 lambda in decltype for the following codeauto fint count decltypeint m return 0 return int m return 0 g 45 gives the errorstest1cpp132 error expected primaryexpression before inttest1cpp132 error expected before intwhat is the problem what is the correct way to return a lambda from a function,['c++'] +118804,c inheritance inaccessible base i seem to be unable to use a base class as a function parameter have i messed up my inheritance i have the following in my mainint some ftnfoo f some code bar bsome ftnband the class bar inheriting from foo in such a wayclass bar foopublic bar snipprivate snipshould this not work i do not seem to be able to make that call in my main function,['c++'] +118805,a newbie question in qt mainwindowmainwindowqwidget parent qmainwindowparent uinew uimainwindow uisetupuithis in this section of code after what does qmainwindowparentuinew uimainwindow mean,['c++'] +118814,uiimageview not showing image i have the following codeinterface neighborprofileviewcontroller uiviewcontroller uiimageview profpic uitextview text uibutton buzz nsstring uid nsmutabledata responsedata nsdictionary resultsproperty nonatomic retain iboutlet uiimageview profpicproperty nonatomic retain iboutlet uitextview textproperty nonatomic retain iboutlet uibutton buzzproperty nonatomic retain nsstring uidendheres what i have in the viewdidload on the m fileimplementation neighborprofileviewcontrollersynthesize uidsynthesize profpicsynthesize buzzsynthesize text implement viewdidload to do additional setup after loading the view typically from a nib voidviewdidload super viewdidload nsurl url some url to the picture nsdata data nsdata datawithcontentsofurlurl uiimage img uiimage alloc initwithdatadata autorelease selfprofpic uiimageview alloc initwithimage imgi think i wired up the uiimageview via ib correctly i have an outlet from the uiimageview to the profpic in the files owner what am i doing wrong,"['iphone', 'objective-c']" +118824,is it possible to define constants in css i use a few colors throughout my css stylesheet for example testdiv background 123456is it possible to define that color by name so i can reference it in the css sheet like this testdiv background colorname,['css'] +118828,php uploading a picture while creating a new record this is more of a conceptual question and not about the underlying programming technique when i am in the process of creating a new record say an add record screen the record id is not available to me yet the same screen has an option of uploading a picture too using swfupload which means the picture gets uploaded immediately since the record id is not available yet there is no way to associate this particular picture with a record in the db till i have hit the save button now suppose after uploading the picture i navigate away from the add record screen leaving an orphaned picture file on the server i can come back to the add record screen and keep doing this on and on and eat up a sizable chunk of the server space with unlinked unused imageshow would you tackle this issue what flow of logic should be enforced hereone option which i am experimenting with right now is to store the uploaded images in a tmp folder and moving them out and placing them in another proper folder once the record has been created with a link the the picture in it is final resting place and then run nightly cron jobs to clear off the leftovers from the tmp folderany other brighter and elegant approaches to thisthanksme,['php'] +118836,how to start with memcached currently i am working on a project in which i need to use memcached i have researched through a lot of web links but i do not understand how to get started with memcached i have already worked with mongodb but would like help with configuration of memcachedi am using windows 7 operating system and have used the following links so far aspnetaspx,"['c#', '.net']" +118841,datetimezone error unknown or bad timezone i am trying to run this scriptphpd new datetimenow new datetimezoneasiakolkatatime dformathiecho timebut i got this errorfatal error uncaught exception exception with message datetimezone construct a hreffunctiondatetimezoneconstructfunctiondatetimezoneconstructa unknown or bad timezone asiakolkatathough it works well for asiadacca for example what could be the problem and how to fix it,['php'] +118842,getting mouse position with javascript within canvas i am studying jquery and html5 canvas all i want to do is a simple html5 drawing example when the mouse move i draw red squares under my mousemy code is simple but i have a problem getting the mouse cursor position within the canvasright now i am using xeventoffsetx to get the mouse position this works very well in chrome however when it comes to firefox it does not work i changed the code to xeventlayerx but it seems that layerx is the position of my mouse relative to the web page not the position of the canvas because i always see an offseti have two questions first what is the right thing to do to get the correct mouse position under firefox second how can i write a code that works for ie firefox chrome safari and operahere is my code doctype html htmlheadscript typetextjavascript srcjqueryjsscriptscript typetextjavascript documentready functionvar flip documentgetelementbyidflip var context flipgetcontext2d contextfillstyle rgb255255255 contextfillrect0 0 500 500 aclickfunctioneventalertthanks for visiting flipmousemovefunctionevent var x y x eventlayerx y eventlayery alertmouse poseventlayerx var flip documentgetelementbyidflip var context flipgetcontext2d contextfillstyle rgb25500 contextfillrectx y 5 5 script head body bgcolor0 a hrefjqueryacanvas idflip width500 height500 this text is thisplayed if your browser does not support html5 canvascanvas bodyhtml,['javascript'] +118849,android how to approach fall detection algorithm i want to be able to feature a fairly simple fall detection algorithm in my application at the moment in onsensorchanged i am getting the absolute value of the current xxz values and subtracting sensormanagergravity earth 98 ms from this the resulting value has to be bigger than a threshold value 10 times in a row to set a flag saying a fall has been detected by the accelerometer the threshold value is about 8ms also i am comparing the orientation of the phone as soon as the threshold has been passed and the orienation of it when the threshold is no longer being passed this sets another flag saying the orientation sensor has detected a fall when both flags are set an event occurs to check is user ok etc etc my problem is with the threshold when the phone is held straight up the absolute value of accelerometer is about 98 ms but when i hold it still at an angle it can be over 15ms this is causing other events to trigger the fall detection and if i increase the threshold to avoid that it would not detect fallscan anyone give me some advice here with what possible values i should use or how to even improve my method many thanks,['android'] +118856,calling another method from the main method in java i have class foo public static void mainstring args do public void dobut then when i call do from main by running the command java foo on the command line java complains that you cannot call a method from a static functionso my question is how do you call methods from the main method and if it is not possible what are some alternative strategies to call methods after the program is run from the command line using the java command,['java'] +118877,creating minidump for access violation exception using setunhandledexceptionfilter i am using the following code to create a minidump file whenever there is a structured exception generated from my codevoid createminidump exception pointers pep open the file typedef bool pdumpfn handle hprocess dword processid handle hfile minidump type dumptype pminidump exception information exceptionparam pminidump user stream information userstreamparam pminidump callback information callbackparam handle hfile createfile tctempminidumpdmp generic read generic write 0 null create always file attribute normal null hmodule h loadlibraryldbghelpdll pdumpfn pfn pdumpfngetprocaddressh minidumpwritedump if hfile null hfile invalid handle value create the minidump minidump exception information mdei mdeithreadid getcurrentthreadid mdeiexceptionpointers pep mdeiclientpointers true minidump type mdt minidumpnormal bool rv pfn getcurrentprocess getcurrentprocessid hfile mdt pep 0 mdei 0 0 0 close the file closehandle hfile long winapi myunhandledexceptionfilter struct exception pointers exceptioninfo createminidumpexceptioninfo return exception execute handler and i am doing setunhandledexceptionfiltermyunhandledexceptionfilter from the main entry point of my app i am not setting it for each thread though after this to test this code i did the following to generate an access violation int p 0 p 0 the dump file did get generated then i used windbg and opened the dump file and used ecxr command to get the exception record however no information is coming there ie i am not getting the call stack also if i use analyze v command then it is able to show the line where the crash occured does anybody know what i am missing and how to solve thisbtw i am using vc7 compiler with eha asynchronuos exception model flag,['c++'] +118879,start an application from notification bar in android i have an application i want to show my app icon to the notification bar when my application is running and i also want when user will click on my app icon present in the notification barmy app will be open how to do this please help,['android'] +118889,c delegates and method signatures from msdnany method that matches the delegates signature which consists of the return type and parameters can be assigned to the delegateso how is this possiblepublic delegate void alarmeventhandlerobject sender eventargs epublic event alarmeventhandler alarmprotected virtual void onalarmeventargs e alarmeventhandler handler alarm if handler null invokes the delegates handlerthis e delegate alarmeventhander and event alarmeventhandler have different signatures yet handler can be assigned to alarmperhaps i am misunderstanding delegates somewhat and i would be very grateful if someone could explain where i am going wrong,['c#'] +118893,inheriting behaviours for set and frozenset seem to differ can someone explain the following behaviourclass derivedset1frozenset def new clsargs return frozenset new clsargs class derivedset2set def new clsargs return set new clsargs aderivedset1item1item2 works bderivedset2item1item2 does not worktraceback most recent call last file inheritingbehaviourspy line 12 in module bderivedset2item1item2 does not worktypeerror derivedset2 expected at most 1 arguments got 2this is surprising to me that you can alter the constructor of a frozen set whereas it is not possible for the constructor of a mutable set,['python'] +118912,winforms c outlook style calendar i have been tasked at recreating an ms access calendar in a winforms c application what i had created for the users they hate basically i was doing a datadump into a datagridview where they could search by month day or employee to get the calendar events they have asked for a redesign to make this look like a outlook style calendar frontend with a sql server backend design let me say that there is zero budget for this project so purchasing components is not an option for us has anyone had to create an outlook style calendar that allows for multiple events on a given day etc do you have any examples of how to proceed or any suggestions,['c#'] +118928,do multiple inline js scripts slow down loading time of a page i am trying to optimize the loading time of a site that has a lot of js spaghetti code some of it actually looks like thisscriptvar xfooscriptscriptvar ybarscriptinstead of the saneprogrammer codescript var xfoo var ybarscriptso i was wondering whether this kind of thing actually does harm aside from the aesthetics would combining the scripts into a single script tag bring any loading time benefit,['javascript'] +118929,firefox 4 no longer supports scrollable tbody workarounds well as mentioned in the firefox 4 changelog there will be no longer support for scrollable tbodysthere are a bunch of workarounds javascript or 2 seperate tables but none of them solves all problems javascript is obviously slower with 600 rows you can forget to try to scroll a table and 2 tables are gonna be problematic with cellwidthdo you know if there is some cool way to do this we are using jsf facelets and now have to redo the tags starting with a good idea would be awesome,"['javascript', 'jquery', 'css']" +118931,are c enums slower to use than integers it is really a simple problem i am programming a go program should i represent the board with a qvectorint or a qvectorplayer whereenum player empty 0 black 1 white 2i guess that of course using player instead of integers will be slower but i wonder how much more because i believe that using enum is better codingi have done a few tests regarding assigning and comparing players as opposed to intqvectorint vecvecresize10int size vecsizeforint i 0 isize i veci 0forint i 0 isize i bool b veci 1qvectorplayer vec2vec2resize10int size vec2sizeforint i 0 isize i vec2i emptyforint i 0 isize i bool b vec2i blackbasically it is only 10 slower is there anything else i should know before continuingthanksedit the 10 difference is not a figment of my imagination it seems to be specific to qt and qvector when i use stdvector the speed is the same,['c++'] +118932,how to retrieve edittexts xml id i have a form with many edittexts and when i press a certain button i need to retrieve all these controls and put them into a hashmap so the key is the name key1 int the following codeedittext androidididkey1 stylestylekeys and the value whatever text the user entersmy question is how can i retrieve the name of the edittext for the hashmaps keys getid returns a numberthanks,['android'] +118949,objectivec staticclass method definition what is the difference between static and i am wondering if someone can explain the difference between the functions below they are both static but require different signature syntaxes i am wondering how these are handled at runtime and why you would use one over the other int returnintnsstring mystring1 withstring2nsstring mystring2 if mystring1 isequaltostringmystring2 return 1 else return 0vsstatic int returnintnsstring mystring1 nsstring mystring2 if mystring1 isequaltostringmystring2 return 1 else return 0thanks,"['iphone', 'objective-c']" +118956,what does orghibernateduplicatemappingexception error mean i am trying to force jpahibernate to generate and use only lowercase tablenames i have implemented a namingstrategy like thispublic class mynamingstrategy extends defaultnamingstrategy override public string classtotablenamestring classname return superclasstotablenameclassnametolowercase i have applied it by setting this property in persistencexmlproperty namehibernateejbnaming strategy valueentitiesstrategymynamingstrategywhen i do this i get this stacktracesevere exception while invoking class orgglassfishpersistencejpajpadeployer prepare methodorghibernateduplicatemappingexception same physical table name planning references several logical table names planning orderproductman planning at orghibernatecfgconfigurationmappingsimpladdtablebindingconfigurationjava2629 at orghibernatecfgannotationstablebinderbuildandfilltabletablebinderjava254 at orghibernatecfgannotationstablebinderbindtablebinderjava177what does the same physical table name planning references several logical table names planning orderproductman planning meanentities from the error simplified as much as i could let me know if you need the restentitypublic class planning implements serializable id generatedvaluestrategy generationtypeauto private integer id private integer qty manytoone private orderproductman orderproduct entitytablepublic class orderproductman implements serializable id generatedvaluestrategy generationtypeidentity basicoptional false private integer opid basicoptional false private int qty manytooneoptional false private productman produse manytooneoptional false private orderman orders transient private int totalscheduled transient private int totalproduced,['java'] +118958,surfaceviewgetholder not returning surfaceholder i am trying to code an app that uses the camera i am getting a nullpointerexception when trying to get the surfaceholder that i eventually pass to the surfacecreated that starts up the camera is there any situation when the getholder returns nullthankspackage comtecmarkimport javaioioexceptionimport androidappactivityimport androidgraphicspixelformatimport androidhardwarecameraimport androidosbundleimport androidutillogimport androidviewsurfaceholderimport androidviewsurfaceviewimport androidviewwindowimport androidviewwindowmanagerpublic class cameraview extends activity implements surfaceholdercallback surfaceview msurfaceview surfaceholder msurfaceholder camera mcamera boolean mpreviewrunning called when the activity is first created override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate getwindowsetformatpixelformattranslucent requestwindowfeaturewindowfeature no title getwindowsetflagswindowmanagerlayoutparamsflag fullscreen windowmanagerlayoutparamsflag fullscreen setcontentviewrlayoutcamera surface msurfaceview surfaceview findviewbyidridsurface camera logisurfaceholder about to get surface holder try msurfaceholder msurfaceviewgetholder catchexception e eprintstacktrace logisurfaceholder msurfaceholdertostring msurfaceholderaddcallbackthis msurfaceholdersettypesurfaceholdersurface type push buffers setcontentviewrlayoutcamera surface surfacecreatedmsurfaceholder override public void surfacechangedsurfaceholder holder int format int w int h if mpreviewrunning mcamerastoppreview cameraparameters p mcameragetparameters psetpreviewsizew h mcamerasetparametersp try mcamerasetpreviewthisplayholder catch exception e eprintstacktrace mcamerastartpreview mpreviewrunning true override public void surfacecreatedsurfaceholder holder try logicamera about to open camera mcamera cameraopen logicamera camera opened mcameragetparameters mcamerasetpreviewthisplayholder mcamerastartpreview catch ioexception e eprintstacktrace logicamera ok override public void surfacedestroyedsurfaceholder holder mcamerastoppreview mpreviewrunning false mcamerarelease end of activity0131 1529173 warnsystemerr9144 javalangnullpointerexception0131 1529178 warnsystemerr9144 at comtecmarkcameraviewoncreatecameraviewjava420131 1529178 warnsystemerr9144 at androidappinstrumentationcallactivityoncreateinstrumentationjava10470131 1529178 warnsystemerr9144 at androidappactivitythreadperformlaunchactivityactivitythreadjava24590131 152917783 warnsystemerr9144 at androidappactivitythreadhandlelaunchactivityactivitythreadjava25120131 152917783 warnsystemerr9144 at androidappactivitythreadaccess2200activitythreadjava1190131 152917783 warnsystemerr9144 at androidappactivitythreadhhandlemessageactivitythreadjava18630131 152917783 warnsystemerr9144 at androidoshandlerthispatchmessagehandlerjava990131 152917783 warnsystemerr9144 at androidoslooperlooplooperjava1230131 152917783 warnsystemerr9144 at androidappactivitythreadmainactivitythreadjava43630131 152917783 warnsystemerr9144 at javalangreflectmethodinvokenativenative method0131 152917788 warnsystemerr9144 at javalangreflectmethodinvokemethodjava5210131 152917788 warnsystemerr9144 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava8600131 152917788 warnsystemerr9144 at comandroidinternaloszygoteinitmainzygoteinitjava6180131 152917788 warnsystemerr9144 at dalviksystemnativestartmainnative method0131 152917793 debugandroidruntime9144 shutting down vm0131 152917793 warndalvikvm9144 threadid3 thread exiting with uncaught exception group0x4001b1800131 152917793 errorandroidruntime9144 uncaught handler thread main exiting due to uncaught exception0131 152917803 errorandroidruntime9144 javalangruntimeexception unable to start activity componentinfocomtecmarkcomtecmarkcameraview javalangnullpointerexception0131 152917803 errorandroidruntime9144 at androidappactivitythreadperformlaunchactivityactivitythreadjava24960131 152917803 errorandroidruntime9144 at androidappactivitythreadhandlelaunchactivityactivitythreadjava25120131 152917803 errorandroidruntime9144 at androidappactivitythreadaccess2200activitythreadjava1190131 152917803 errorandroidruntime9144 at androidappactivitythreadhhandlemessageactivitythreadjava18630131 152917803 errorandroidruntime9144 at androidoshandlerthispatchmessagehandlerjava990131 152917803 errorandroidruntime9144 at androidoslooperlooplooperjava1230131 152917803 errorandroidruntime9144 at androidappactivitythreadmainactivitythreadjava43630131 152917803 errorandroidruntime9144 at javalangreflectmethodinvokenativenative method0131 152917803 errorandroidruntime9144 at javalangreflectmethodinvokemethodjava5210131 152917803 errorandroidruntime9144 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava8600131 152917803 errorandroidruntime9144 at comandroidinternaloszygoteinitmainzygoteinitjava6180131 152917803 errorandroidruntime9144 at dalviksystemnativestartmainnative method0131 152917803 errorandroidruntime9144 caused by javalangnullpointerexception0131 152917803 errorandroidruntime9144 at comtecmarkcameraviewoncreatecameraviewjava470131 152917803 errorandroidruntime9144 at androidappinstrumentationcallactivityoncreateinstrumentationjava10470131 152917803 errorandroidruntime9144 at androidappactivitythreadperformlaunchactivityactivitythreadjava24590131 152917803 errorandroidruntime9144 11 more,['android'] +118968,how to implement retry and times in case of exception in c i am developing a wpf 40 application in which we get the data from a remote web service the web service exposes around 120 methods to its clients if a web service call from my wpf application fails i need to retry it and times which is configurable via appconfig how to implement this are there any design patterns that address this problem,"['c#', '.net']" +118987,import existing c source code into visual studio i am trying to import an existing c applications source into visual studio to take advantage of some specific ms tools however after searching online and playing with visual studio i cannot seem to find an easy way to import existing c source code into visual studio and keep it structurally intact the import capacity i did find flattens out the directories and puts them all into one project am i missing somethingthis is all unmanaged c and contains specific builds for winunix,['c++'] +118999,java converting an image to an input stream without creating a file for an applet i am working on i need to convert a bufferedimage file to an input stream so that i can upload the image to my mysql server originally i was using this code classfornamecommysqljdbcdrivernewinstance connection connection drivermanagergetconnectionconnectionurl user pass psmnt connectionpreparestatement insert into save imageuser image values psmntsetstring1 username imageiowriteimage png new filecimagepng file imagefile new filecimagepngfileinputstream fis new fileinputstreamimagefilepsmntsetbinarystream2 inputstreamfis fislengthint s psmntexecuteupdateifs 0 systemoutprintlndonewhile catching the relevant exceptions the code hangs on the part where the applet attempts to save the image to the computer the code worked perfectly in eclipse or whenever i ran the applet from the localhost so i am assuming the problem is in the privileges that the applet has in saving files to the users computeri was just was wondering if there was a way to turn the image file into an inputstream without having to save a file to the users computer i tried usingimageiocreateimageinputstreamimagebut then i could not convert the imageinputstream back to an inputstream any suggestionsthanks,['java'] +119000,c htmlencode iso88591 entity names vs numbers according to the following table for the iso88591 standard there seems to be an entity name and an entity number associated with each reserved html characterso for example for the character a entity name eacuteentity number 233similarly for the character entity name gt entity number 62for a given string the httputilityhtmlencode returns an html encoded string but i cannot figure out how it works here is what i mean consolewritelinehtmlencodeaoutputs 233gtit seems to be using the entity number for the a character but the entity name for the characterso does the htmlencode method really work with the iso88591 standard if it does is there a reason why it sometimes uses the entity name and other times the entity number more importantly can i force it to give me the entity name reliablyedit thanks for the answers guys i cannot decode the string before i perform the search though without getting into too many details the text is stored in a sharepoint list and the search is done by sharepoint itself using a caml query so basically i cannoti am trying to think of a way to convert the entity numbers into names is there a function in net that does that or any other idea,"['c#', '.net']" +119002,jquery how does one thisable everything inside a div but still keep everything visible the goal is to thisable all the links when one is clicked and then thisable all the links until the server sends an unthisable command using a similar method that would be used to thisableso since all the links are in one containing div i figure i could just temporarily thisable that how would i go about doing that,"['javascript', 'jquery']" +119005,stream android screencast to pc i am going to make a presentation of an android application and since it will have a large audience assisting i will probably need to stream the android screencast to a pc do you know any tool free or paid able to do it thank you,['android'] +119023,how do i force one field in rubys csv output to be wrapped with doublequotes i am generating some csv output using rubys builtin csv everything works fine but the customer wants the name field in the output to have wrapping doublequotes so the output looks like the input file for instance the input looks something like this1firstname lastnamemorefields2firstname lastname jrmorefieldscsvs output which is correct looks like1firstname lastnamemorefields2firstname lastname jrmorefieldsi know csv is doing the right thing by not doublequoting the third field just because it has embedded blanks and wrapping the field with doublequotes when it has the embedded comma what i would like to do to help the customer feel warm and fuzzy is tell csv to always doublequote the third fieldi tried wrapping the field in doublequotes in my to a method which creates a firstname lastname field being passed to csv but csv laughed at my punyhuman attempt and output firstname lastname that is the correct thing to do because it is escaping the doublequotes so that did not workthen i tried setting csvs force quotes true in the open method which output doublequotes wrapping all fields as expected but the customer did not like that which i expected also so that did not work eitheri have looked through the table and row docs and nothing appeared to give me access to the generate a string field method or a way to set a for field and always use quoting flagi am about to dive into the source to see if there is some supersecret tweaks or if there is a way to monkeypatch csv and bend it to do my will but wondered if anyone had some special knowledge or had run into this beforeand yes i know i could roll my own csv output but i prefer to not reinvent welltested wheels and i am also aware of fastercsv that is now part of ruby 192 which i am using so explicitly using fastercsv buys me nothing special also i am not using rails and have no intention of rewriting it in rails so unless you have a cute way of implementing it using a small subset of rails do not bother i will downvote any recommendations to use any of those ways just because you did not bother to read this far,['ruby'] +119024,how does pthread work i am experienced at multithreaded programming in java and c and am starting to learn how to do it in c on linux i grew up in the programming sense on linux so i understand it is memory philophy process handling etc at a high levelmy question is not how to do threading i would like to know how pthread actually does it does it fork a process and handle your interprocess communication for you somehow or does it just manage the address space i want nittygritty details googling has only produced how to do it questions not how it works,['c'] +119035,how to tell if a drop down has options to select how to tell if a drop down has options to select,"['javascript', 'jquery']" +119059,access sqlite database on android device i am trying to access the sqlite database file on the device i mean i have launched the app on the device via adb and now i wanto to download this file as i did before on emulator via ddms but when i select the device on ddms and open the folder data it is empty is it the right way to do or there is another way to download this db filethanks,['android'] +119064,how to work with serverquery string how to work with serverquery string and paginationwhen my table is sorted by this linka href serverphp selfsort namenamesortasc titlelangsorteer ascamy url becomes relationphpsort nameadressortascthe i use an pagination linkecho a href serverphp self serverquery stringpageiia and the url becomes relationphpsort nameadressortascpage2so far so good but when browsing to other pages it can be as long asrelationphpsort nameadressortascpage2page3page14page23page27the age keeps appearing because of the serverquery string how can i clean up my url with only keeping the last page and sort nameadressortascor do you suggest an other solution of ordering and pagination,['php'] +119065,show runtime for each rspec example currently i am running more than 1k examples and it is taking a long time to complete more than 20 minutesi would like to identify which examples are the ones taking more time to complete is there any way to run rspec and return the time each example takes to completeindividually i am using rspec 130 and rspecrails 123,['ruby-on-rails'] +119066,noclassdeffounderror in mapactivity i have this error in my map appdo you know what is wrongi have checked and the package is right in my java files and also i have put the useslibraries of google maps into my application tag in the manifestxmlplease helpim trying hours to solve it,['android'] +119103,how to list imported modules how to enumerate all imported moduleseg i would like to get os sys for from this codeimport osimport sys,['python'] +119142,reading large txt efficiently in c i have to read a large text file 10 gb in c this is a csv file with variable length lines when i try to read line by line using ifstream it works but takes long time i guess this is becuase each time i read a line it goes to thisk and reads which makes it very slowis there a way to read in bufferes for example read 250 mb at one shot using read method of ifstream and then get lines from this buffer i see lot of issues with solution like buffer can have incomplete lines etc is there a solution for this in c which handles all these cases etc are there any open source libraries that can do this for example boost etc note i would want to avoid c stye file pointers etc,['c++'] +119145,bundler throws uninitialized constant gemsilentui nameerror error after upgrading to rubygems 150 i ran gem update system to update to rubygems 150 and after every time i run any bundle commands i getrvmgemsruby187p249gemsbundler109libbundleruirb56 uninitialized constant gemsilentui nameerrorhas anyone else had this issue,['ruby'] +119149,objc how to convert nsdata to an array of ints i have a nsdata item that is holding a bunch of ints how do i go about getting them out and into an nsarraythe memory structure in the nsdata is 32bit int in littleendian order one right after the othersorry for the basic question but still learning the objc way of doing things,['objective-c'] +119151,should i be using object literals or constructor functions i am getting confused over which way i should be creating an object in javascript it seems there are at least two ways one is to use object literal notation while the other uses construction functions is there an advantage of one over the other,['javascript'] +119153,facebook user deauthorizes the app when user accepts the facebook application from my website i am storing the user details and facebook detailsaccess token in database when he removes my application from facebook i want to remove the detail from database how to do this i can give deauthorize callback url if some one removes application it will redirect to this page but wt should be the code here to delete the data from db i means when it redirect will it post the access token details so that i can charge fro access token and delete that row,['php'] +119160,textview show partial text i have a textview in which i must load a message the textview has maximum 2 lines androidlines2 the message may contain an n characterhow should i load the message in that textview so that words would be wrapped and if in those 2 lines message does not fit at the end of last visible word i must add three dots how can i detect the length of text that fits in that textview my code for textview is textview aididtv message agravitytop alayout widthwrap content alayout heightwrap content alayout alignparenttoptrue alayout torightofidiv icon alayout marginleft2dp alayout margintop4dp apaddingright7dp apaddingbottom5dp atextsize12sp atypefacesans aellipsizemarquee alines2 amaxlines2 atextcolorandroidcolorblack but in application text appears on two lines even if there is a line containing the signature the message is like message text nsignature but the message can be on 123 lines depending of message length,['android'] +119184,javascript execution order with settimeout say that i have the following codefunction testa settimeouttestb 10 dolongfunction testb dosomethingfunction dolong takes a few seconds to do somethingi execute testa i have read that javascript is singlethreaded what happens after 10 milliseconds when the timeout for testb is reachedsome possibilities i can think oftestb is queued up to execute after dolong and anything else it called have finisheddolong is immediately terminated and testb is starteddolong is given a little while longer to execute before being stopped either automatically or after prompting the user and testb is starteddolong is paused testb is started after testb has finished dolong resumeswhat is the correct answer is it implementation dependant or part of the standardthis question is similar but not the same as far as i can tellany links that you can recommend for better understanding javascript execution would be appreciatedthanksyes i know that not all browsers follow standards,['javascript'] +119190,make a link have 100 width i have a box that is x px wide and in it i have a list ul with link elements lia alihow can i with css make the link clickable outside the text and in 100 width of the box making each line in the box clickable d,['css'] +119200,share combobox datasource may i ask why does both comboboxes trigger each other such that both have same valuescannot i share a single list and have 2 comboboxes with different selected textprivate void form1 loadobject sender eventargs e bindingliststring list new bindingliststring listadda listaddb listaddc listad bindcbo1 list bindcbo2 list private void bindcombobox combobox bindingliststring list commented lines are in actual code but appears unimportant in this question comboboxdropdownstyle comboboxstyledropdown comboboxautocompletesource autocompletesourcelistitems comboboxautocompletemode autocompletemodesuggest comboboxdatasource list comboboxfocus comboboxtext stringempty comboboxselectedtext stringempty updateok now i found out the issue is that the datasource is managed by some bindingcontext and currencymanager to automatically synchronise the list but i feel someone must know how to thisable this behaviouri do not wish to use 2 different lists because i want to be able to modify this single list at runtime and have the changes be reflected on all comboboxes any method to achieve this would be greatly appreciated,['c#'] +119220,default text in input field i do not know if this has a special name for it but is there a nice easy way to set default text in an input field which thisappears on focus and reappears on blur if the textbox is empty,"['javascript', 'jquery']" +119237,using installutil to install a windows service with startup parameters i am using installutil to install my service and i just cannot figure out how to specify the startup parameters for ithere is my installer subclassruninstallertruepublic class serverhostinstaller installer private serviceinstaller m serviceinstaller private serviceprocessinstaller m serviceprocessinstaller private static string s usage usageninstallutil i usernameuser name passworduser password ncstubserverhostexe public serverhostinstaller m serviceinstaller new serviceinstaller m serviceinstallerservicename programservicename m serviceinstallerthisplayname programservicename m serviceinstallerstarttype servicestartmodeautomatic m serviceprocessinstaller new serviceprocessinstaller m serviceprocessinstalleraccount serviceaccountuser installersaddm serviceinstaller installersaddm serviceprocessinstaller public override void installidictionary statesaver baseinstallstatesaver string username thiscontextparametersusername if username null consolewritelines usage throw new installexceptionmissing parameter username string userpass thiscontextparameterspassword if userpass null consolewritelines usage throw new installexceptionmissing parameter password m serviceprocessinstallerusername username m serviceprocessinstallerpassword userpass can anyone indicate how do i specify the service startup parameters,"['c#', '.net']" +119251,explicit casting from super class to subclass public class animal public void eat public class dog extends animal public void eat public void mainstring args animal animal new animal dog dog dog animal the assignment dog dog dog animal does not generate a compilation error but at runtime it generates a classcastexception why cannot the compiler detect this error,['java'] +119267,how to configure wcf services to work through https without http binding i have configured my wcf services to work with ssl but it works only if the http binding exists in the iis web site when the http binding not exists and exists only https binding i get the following errorthe httpgetenabled property of servicemetadatabehavior is set to true and the httpgeturl property is a relative address but there is no http base address either supply an http base address or set httpgeturl to an absolute addresshow can i resolve this issuethanks,['.net'] +119271,just uploaded android app how long before app shows in android market search i have just uploaded a new app to the android market however when i try to download it to my phone through the android market it does not appearplease can someone with knowledge of this let me know how i can get my app to appear in the search results,['android'] +119276,how do i copy binary data to a stringstream i have a stdvectorint and i want serialize it for this purpose i am trying to use a stdstringstream vectorint v vresize10 for int i0i10i vii stringstream ss stringstreamin stringstreamout stringstreambinaryhowever when i copy the vector to the stringstream this copy it as characterostream iteratorint itsscopyvbeginvenditthe value that inserted to buffer strbuf is 123456789i sucssesed to write a workaround solution for int i1i10i sswritecharpisizeofinti want to do it something like first way by using std function like copy thanks herzl,['c++'] +119285,when opening a jquery ui dialog page scrolls up you can see it here make your browser window smaller scroll down and click on a button near a textboxis there a way to make it not scroll up,['jquery'] +119303,use jquery to select a dropdown option i was wondering if it is possible to get jquery to select an option say the 4th item in a dropdown boxselect optionoption optionoption optionoption optionoption optionoptionselecti want the user to click a link then have the select box change it is value as if the user has selected it by clicking on the option,"['javascript', 'jquery', 'html']" +119331,jps cannot connect to a remote jstatd i am trying query a remote jvm with jps using jstatd in order to eventually monitor it using visualvmi got jstatd running with the following security policygrant codebase filejavahomelibtoolsjar permission javasecurityallpermissionjstatd is running on a 64bit linux box with a 160 10 version hotspot vm the jstatd command isjstatd jdjavasecuritypolicyjstatdtoolspolicy jdjavarmiserverlogcallstruei am trying to run jps from a windows 7 machine due to firewall restrictions i am tunneling the rmi data through an ssh tunnel to my windows machine such that the jps command line is jpsexe m l rmilocalhostwhen i run jps i see the connection attempt in the jstatd log which looks like thisfeb 1 2011 115034 am sunrmiserverunicastserverref logcallfiner rmi tcp connection3127001 127001 sunrmiregistryregistryimpl0 0 javarmiremote lookupja valangstringbut on the jps side i get the following errorerror communicating with remote host connection refused to host 1921681137 nested exception is javanetconnectexception connection refused connectbased on the connection attempt listed in the jstatd log i think jps is actually reaching the host but for some reason is getting blocked is there some security policy i have set or some other setting somewhere i can change so that i can get jps to pull stats from the remote jstatd,['java'] +119340,quartznet recur every x weeks i need to implement the following scenario using quartznetrecur every and weeks onsunday andor monday tuesday wednesday thursday friday saturdayso for example i might select monday and thursday and recur every 2 weeks is this possiblei figure it out that the way to go might be using cron expressions but i have not had luck so far with the recur every x weeksthanks,['c#'] +119355,programmatically add url patterns in django is there a way to programmatically add url patterns to django without having to restart the server or is there a way force django to reprocesscache url patterns the urlconf,['python'] +119373,sql find next row in a where clause given an id i have a table called products in a mysql database products looks some what like thisid name din strength active deleted1 apa test 00246374 25 1 04 apa bob 00246375 50 1 05 apa tire 002468 50 1 07 apa rot 00521414 100 1 09 apa apa 01142124 100 1 06 apa code 00121212 150 1 08 apa serv 0145 600 1 0obviously i have left out several columns not important to my question when i query this table i will be sorting by one of several different columns the user interface allows individual users to change the sorting column and order and i may have a search clause in which case i will do a like clause on name and dinwhat i want to know is given the sorting info and search info and the id of a specific product say i searched for 004 which returned 3 results and i am viewing one of them how could i get the next and previous productsi need to do this because if a user clicks to editview one of the products after searching and sorting results they want to be able to cycle through results without going to the previous pageis there a good and efficient way to do this in sql or am i best off using php any ideas are also welcomecurrently using this sql query which is experiencing issues if i sort by the strength column as there are duplicate valuesselect tfrom wp products tinner join wp products curr on currid 38 and tstrength currstrength and tid currid or tstrength currstrengthwhere tactive 1 and tdeleted 0 and tname like or tdin like order by tstrength asc tid asclimit 1my php code using wordpress designed to get the next item sql select tfrom wpdbprefix apsi products tinner join wpdbprefix apsi products curr on currid itemid and t wpdbescape queryorderby curr wpdbescape queryorderby and tid currid or t wpdbescape queryorderby curr wpdbescape queryorderby where tactive 1 and tdeleted 0 and tname like querywhere or tdin like querywhere order by t wpdbescape queryorderby queryorder tid asclimit 1,"['php', 'sql', 'mysql']" +119380,c null coalescing operator returning null recently my coworker showed me a block of code that was not working correctlypublic class someclass private ilistcategory categories public void setcategories categories getcategories new listcategory dosomethingelse public ilistcategory getcategories return retrievecategoriesselectsomethingtolist i am aware that the operator is superfluous since the linq tolist will always return a list but that is how the code was set upthe problem was that categories was null in the debugger setting a breakpoint on categories getcategories new listcategory then stepping over to dosomethingelse categories would still be nulldirectly setting categories to getcategories worked fine splitting the in to a full if statement worked fine the null coalescing operator did notit is an aspnet application so a different thread could possibly be interfering but it was on his machine with only him connected in a browser cateogories is not static or anythingwhat i am wondering is how could this possibly happeneditjust to add to the bizarreness categories is never set anywhere besides that function apart from initializing the classthe exact code is like sopublic class categorylistcontrol private icategoryrepository repo private ilistcategory categories public override string render args repo servicelocatorgeticategoryrepository category category repofindbyurlurl categories repogetchildrencategory new listcategory render some other rendering stuff public class categoryrepository icategoryrepository private static ilistcategory categories public ilistcategory getchildrencategory parent return categorieswherec cparent parenttolistcategory even it getchildren magically returned null categorylistcontrol categories still should never ever be null getchildren should also never ever return null because of ienumerabletolistedit 2trying out smartcavemans code i found out thiscategory category repofindbyurlurl categories repogetchildrencategory new listcategory skins skin when the debugger is here categories is nullrendererrenderoutput skinscontent writecontent when the debugger is here categories is fineas well when testing if categories null throw new exception categories was null on the if statement then stepping over the exception was not thrownso it seems like this is a debugger bug,"['c#', '.net']" +119381,what is the proper way to overload operators in abstract base classes suppose i have an abstract base class that just defines a container on which addition can be performedclass base public virtual base virtual base operatorconst base rhs 0then i want subclasses of base to provide the actual operationclass derived public base public base operatorconst base rhs would not compile actual implementation here is my problem operator is supposed to return a new base object but base being abstract it would not compile i tried to get around that by using a factory to return a reference to a base object but then in the body of the operator i find myself doing casts because the addition only makes sense on derived objects in any case it feels like i am biting my own tail is there a proper solution to thisupdate based on the answers so far it seems i am using the wrong pattern i want to separate the interface from the implementation so that library code only has to know the interface and client code provides the implementation i tried to do that by providing the interface as an abstract base class and the implementation as subclasses update2 my question was actually 2 questions a concrete one about overloading operators in abstract classes and another about my intent how do i allow the client to customize the implementation the former has been answered do not for the latter it seems that the interface class pattern i use is actually a good one to solve that problem according to griffiths and radford it is just that i should not mess with overloaded operators,['c++'] +119383,dump stacktrace for each thread running is there a way in net vbnet or c when an exception happens to dump the stacktrace of each thread basically i would like to reproduce what happens in visual studios debugthreads window to see what each thread was doing when the exception happened,"['c#', '.net']" +119388,i am looking for gevent for python 27 for windows however gevent depends upon greenlet and the msi version i found fails to install and the egg for 26 refuses to install the msi version fails as follows cwindowssystem32easy install greenletinstall dir cpython27libsitepackagessearching for greenletreading reading reading best match greenlet 031downloading processing greenlet031targzrunning greenlet031setuppy q bthist egg thistdir cusersianappdatalocaltempeasy install1epg28greenlet031eggthisttmpmqhu3ncpython27libthistutilsthistpy267 userwarning unknown thistribution option repository warningswarnmsggreenletcgreenletc fatal error c1074 idb is illegal extension for pdb fileerror setup script exited with error command cprogram files x86microsoft visual studio 100vcbinclexe failed with exit status 2cwindowssystem32i guess this means that i have a wrong version of vs is there anything else i can use i want to get pyqt4 so the gui would not lock up if the database cannot be reached or takes ages to reply,['python'] +119396,protecting a system deployed in a hostile environment at my company we are developing a large system comprised of several serversthe system is comprised from about 5 logical components data is stored in xmls ms sql and sqlite it is a net systemmostly the components communicate using wcf and some custom udpclients access the system mostly through the custom udp or webaspnet silverlight protecting the communication is easy some ssl and some security on the wcf and were donethe main problem we are facing is that the system needs to be deployed on a clients site a client that we dont necessarily trust we need to defend the data on the servers and the software itself from reverse engineering both are crucially important to usalso we need a kill switch i would like something that destroys the data and the software upon command or if unable to call home for a certain period of timethe direction that i was thinking of is using tpm or something alike some hardware encryption solution in combination with another service that we could keep internally to encrypt all the software and data on the servers so that the keys will come from our server safely in our site and maybe memory curtaining from the tpmhow do you suggest solving such a problemupdate 0402i am looking for practical suggestions or advise on products that could help me so i am starting a bountylook guys were basically putting our machine in the clients site for business and practicality reasons we own that machine and the client receives everything he is paying for within hours and he can do with the data whatever he wants but i the algorithms running on that machine and some of the data stored there is our trade secrets that we want to protectideally i would want the machine not to work at all not even boot if i dont say it is ok and without my ok for everything on the machine to remain encrypted memory curtaining also looks like a nice way to protect the machine while executing also ideally i would want the hds and the storage on all the machines to explode as soon as someone gets near them with a screwdriver but i think that would be taking it too far update 1002ok after doing some research i think we are going to try something in the same direction as the ps3 encryption system except were going to bring in the keys for decrypting the software and the data from our servers doing so we can decide on our machines whether we trust the server requesting the keys we can get a kill switch just by reseating the machine this is probably be based on tpm or something similar maybe intels txti am also really interested in memory curtaining as an important security featurebtw we cant solve this by moving the valuable parts of our system to our site both because of business requirements and because its not technologically feasible we would need a huge bandwidth,['.net'] +119410,twitter authentication through androids accountmanager classes i am working on a twitter based app and am trying to incorporate androids builtin account support for twitter the following code works to popup the confirmation dialog for my app to access twitter but i am unsure of what to pass in as the authenticationtype any help would be appreciated i have googled all over the place and cannot seem to find the correct answer it goes in place of oauth belowaccountmanager am accountmanagergetthisaccount accts amgetaccountsbytypetwitter account typeifacctslength 0 account acct accts0 amgetauthtokenacct oauthwhat goes here null this new accountmanagercallbackbundle override public void runaccountmanagerfuturebundle arg0 try bundle b arg0getresult logetrenddroid this authtoken bgetstringaccountmanagerkey authtoken catch exception e logetrenddroid exceptionauthtoken null,['android'] +119413,how do i import a third party module in python i have found a third party module which i would like to use how do i technically import that moduleparticularly i want to use a module called context manager obviously i cannot just import garlicsimgeneral misccontext managerbecause it would not find garlicsim so what should i write to import the thingedit i am using both python 3x and python 2x and i would like to get answers relevant to both versions,['python'] +119428,passing command line argument to python program using idle i have downloaded a python file xpy that is supposed to run on the command line bytyping python xpy filename1 filename2and that should take these two files as argumentsi was wondering if there is a way i can use idle to pass in these arguments is there a way other than setting sysargv thanks,['python'] +119429,requirejs how to define modules that contain a single class i have a number of javascript classes each implemented in its own javascript file for development those files are loaded individually and for production they are concatenated but in both cases i have to manually define a loading order making sure that b comes after a if b uses a i am planning to use requirejs as an implementation of commonjs modulesasynchronousdefinition to solve this problem for me automaticallyis there a better way to do this than to define modules that each export one class if not how to you name what the module exports a module employee exporting a class employee as in the example below does not feel dry enough to medefineemployee exports functionexports exportsemployee functionfirst last thisfirst first thislast last definemain employee function employee var john new employemployeejohn smith,['javascript'] +119432,why does python assignment not return a value why is python assignment a statement rather than an expression if it was an expression which returns the value of the right hand side in the assignment it would have allowed for much less verbose code in some cases are there any issues i cannot seefor example lst is some sequence x is come classx xlstappendxcould have been rewritten aslstappendx xwell to be precise the above would not work because x would be treated as a keyword argument but another pair of parens or another symbol for keyword arguments would have resolved that,['python'] +119436,a linux daemon and the stdinstdout i am working on a linux daemon and having some issues with the stdinstdout normally because of the nature of a daemon you do not have any stdin or stdout however i do have a function in my daemon that is called when the daemon runs for the first time to specify different parameters that are required for the daemon to run successfully when this function is called the terminal becomes so sluggish that i have to launch a seperate shell and kill the daemon with top to get a responsive prompt back now i suspect that this has something to do with the forking process closing the stdinstdout but i am not quite sure how i could work around this if you guys could shed some light on the situation that would be most appreciated thankseditint mainargc char argv setup signal handling check command line arguments pid t pid sidpid forkif pid 0 exitexit failureifpid 0exitexit succesid setsidifsid 0 exitexit failureumask027 set syslogging do some logic to determine wether we are running the daemon for the first time and if we are call the one time function which uses fgets to recieve some input while1 do required work do some clean up procedures and exit return 0you guys mention using a config file this is is exactly what i do to store the parameters recieved via input however i still initially need to get these from the user via the stdin the logic for determining whether we are running for the first time is based off of the existence of the config file,['c'] +119452,ios corelocation altitude prior to ios 40 corelocation was reporting altitude correctly now it always reports as 0 ftvoidlocationmanagercllocationmanager manager didupdatetolocationcllocationnewlocation fromlocationcllocation oldlocation nsstring tlatitude nsstring stringwithformat35f newlocationcoordinatelatitude nsstring tlongitude nsstring stringwithformat35f newlocationcoordinatelongitude the following returns 0 nsstring taltitude nsstring stringwithformati newlocationaltitude theres more code but it is not relevant and this worked prior to ios 40 manager stopupdatinglocationnot working on device nor simulator does anyone else experience this issue,"['iphone', 'ios']" +119455,index 0 beyond bounds for empty array error i do not understand on how to debug this error message20110201 204556151 neme3206207 terminating app due to uncaught exception nsrangeexception reason nsmutablearray objectatindex index 0 beyond bounds for empty array call stack at first throw 0 corefoundation 0x027deb99 exceptionpreprocess 185 1 libobjcadylib 0x0292e40e objc exception throw 47 2 corefoundation 0x027d4695 nsarraym objectatindex 261 3 neighborme 0x0f617 neighbormapviewcontroller regionfromlocations 65 4 neighborme 0x01047b neighbormapviewcontroller locationmanagerdidupdatetolocationfromlocation 94 5 corelocation 0x02393870 cllocationmanager onclienteventlocation 793 6 corelocation 0x0239218b onclientevent 49 7 corelocation 0x023a8a83 z22clclientinvokecallbackp10 clclient13clclienteventpk14 cfdictionary 47 8 corelocation 0x023a9b2c z27clclienthandledaemondatafixp10 clclientpk23cldaemoncommtoclientfixpk14 cfdictionary 290 9 corelocation 0x023acb30 z24clclienthandledaemondatap12 cfmachportpvls1 1125 10 corefoundation 0x02720982 cfmachportperform 338 11 corefoundation 0x027bf4 cfrunloop is calling out to a source1 perform function 52 12 corefoundation 0x02720807 cfrunloopdosource1 215 13 corefoundation 0x0271da93 cfrunlooprun 979 14 corefoundation 0x0271d350 cfrunlooprunspecific 208 15 corefoundation 0x0271d271 cfrunloopruninmode 97 16 graphicsservices 0x030bd00c gseventrunmodal 217 17 graphicsservices 0x030bd0d1 gseventrun 115 18 uikit 0x002eeaf2 uiapplicationmain 1160 19 neighborme 0x02818 main 102 20 neighborme 0x027a9 start 53 21 0x01 0x0 1terminate called after throwing an instance of nsexceptionthere is nsmutablearray in this code so how is this possible,"['iphone', 'objective-c']" +119457,creating a digital audio workstation i am trying to write my own daw mostly just to learn about the mathematics of how signals are processed to get effects but also for fun a rather large undertaking but i have the time at the moment i would like for it to work something like propellerheads record as in the rack especiallyi am running on a mac so i am thinking of using audio units for the different parts then core audio for the scaffolding parts so the whole thing would be written in c or objchowever i have not used either audio units or coreaudio before and the internet has not been any help for learningdoes anyone know where i could learn about theseor would java the only other language i would feel comfortable using be better or is there something i have completely missed while trying to find the easy way to do thisthanksjon,"['java', 'c']" +119458,force eclipse to automatically import a class with multiple options if a class is used in a java project in eclipse and it is not imported already and there is only one class with that name eclipse will automatically import itif there are two or more classes with the same simple name eclipse will ask the user to select the desired one i would like to avoid having to select one and instead prefer having a default class importedfor example i commonly use list and arraylist and each time i use them in a new class i have to select javautilarraylist and javautillist from the suggestions of eclipse because there is another class with the name list javaawtlistis there some way to set javautillist and javautilarraylist as a default import if list and arraylist is usedfor now i created an eclipse template that triggers on the word list are there any other ideas or improvementsimportjavautillistjavautilarraylistlist list new arraylist,['java'] +119462,css3pie in mvc where to place the piehtc file i have been trying to use the css3pie in my mvc project to render rounded corner panel but have no luck so fari follow the sample with normal html page and it works perfectly but not in my mvc projecti think it is something to do with the path of the piehtc file that is being confused in mvci place the piehtc file in project folder root and in my css file i usebehavior urlpiehtci think the mvc router needs to be modified to accept htc file extensionsorry im new with mvc has anyone tried piehtc and have it working in mvc project please helpthanks,['css'] +119479,how can i be sure that the compiler does not optimize away my performance test i have a class that does some timeconsuming calculations i am trying to performance test itint numvalues 10random random new randomstartmeasuringtimedouble resultfor int i 0 i numvalues i result calculatorinstancedosometimeconsumingcalculationsonrandomnextdoublestopmeasuringtimei am using random values so the compiler would not optimize the calculations for being a million times the same but what about the results does the compiler see it is not used any more and leaves out the call but then can it see any side effects the method call could havei do not want to put the results somewhere into a file array or to systemout because i think this will slow down the test with work that i do not want to measure or produce an outofmemoryerrorthanks in advanceedit changed the title a bit,['java'] +119482,experience with using h5py to do analytical work on big data in python i do a lot of statistical work and use python as my main language some of the data sets i work with though can take 20gb of memory which makes operating on them using inmemory functions in numpy scipy and pyimsl nearly impossible the statistical analysis language sas has a big advantage here in that it can operate on data from hard thisk as opposed to strictly inmemory processing but i want to avoid having to write a lot of code in sas for a variety of reasons and am therefore trying to determine what options i have with python besides buying more hardware and memoryi should clarify that approaches like mapreduce will not help in much of my work because i need to operate on complete sets of data eg computing quantiles or fitting a logistic regression model recently i started playing with h5py and think it is the best option i have found for allowing python to act like sas and operate on data from thisk via hdf5 files while still being able to leverage numpyscipymatplotlib etc i would like to hear if anyone has experience using python and h5py in a similar setting and what they have found has anyone been able to use python in big data settings heretofore dominated by sas edit buying more hardwarememory certainly can help but from an it perspective it is hard for me to sell python to an organization that needs to analyze huge data sets when python or r or matlab etc need to hold data in memory sas continues to have a strong selling point here because while thiskbased analytics may be slower you can confidently deal with huge data sets so i am hoping that stackoverflowers can help me figure out how to reduce the perceived risk around using python as a mainstay bigdata analytics language,['python'] +119490,how to record an audio file in mp3 format i am using the following settings for recording audio file in mp3 format using avaudiorecordernsdictionary recordsettings nsdictionary alloc initwithobjectsandkeys nsnumber numberwithfloat 4410avsampleratekey nsnumber numberwithint kaudioformatmpeglayer3avformatidkey nsnumber numberwithint 1 avnumberofchannelskey nsnumber numberwithint avaudioqualitymaxavencoderaudioqualitykeynilbut not able to record with thesei searched a lot for this but was not able to get some relevant postsome posts say that it is not possibleif its not possible then why soplease answer,"['iphone', 'objective-c']" +119494,is quirks mode legit i was on vacation without access to my good friend internet explorer and i threw together a pretty complete web app when i got home i was surprised and encouraged to see that my site was working in ie until i threw in any sort of valid doctype i know it is not best practice to throw browsers into quirks mode or it wouldnt be called quirks mode but i guess my question is what are the practical ramifications of having a quirks mode site is it necessary or even worth it to painstakingly slave away to correct the issues of which i am yet unaware or can i leave it as is functioning cross browser thanks,"['html', 'css']" +119498,javascript trycatchelsefinally like python java ruby etc how can javascript duplicate the fourpart trycatchelsefinally execution model that other languages supporta clear brief summary is from the python 25 whats new in javascript terms x this example is a syntax errortry protectedblock catche handlerblock else elseblock finally finalblockthe code in protectedblock is executed if the code throws an exception handlerblock is executed if no exception is thrown elseblock is executedno matter what happened previously finalblock is executed once the code block is complete and any thrown exceptions handled even if thereas an error in handlerblock or elseblock and a new exception is raised the code in finalblock is still runnote that cutting elseblock and pasting at the end of protectedblock is wrong if an error happens in elseblock it must not be handled by handlerblock,['javascript'] +119500,full postback triggered by linkbutton inside gridview inside updatepanel i have a gridview inside of a updatepanel in a template field is a button i use for marking items functionally this works fine but the button always triggers a full page postback instead of a partial postback how do i get the button to trigger a partial postbackaspscriptmanager idcontentscriptmanager runatserver aspupdatepanel idcontentupdatepanel runatserver childrenastriggerstrue contenttemplate aspgridview idordergrid runatserver allowpagingfalse allowsortingfalse autogeneratecolumnsfalse columns asptemplatefield headertext itemtemplate asplinkbutton idmarkascompletebutton runatserver textmarkascomplete commandnamemarkascomplete commandargument evalid itemtemplate asptemplatefield aspboundfield datafieldname headertextname aspboundfield datafieldloaddate headertextload date aspboundfield datafieldemployeecutoffdate headertextcut off date aspboundfield datafieldiscomplete headertextis completed columns aspgridview contenttemplateaspupdatepanel,"['c#', 'asp.net']" +119503,should i use in my php code if i use in my code will it affect performance,['php'] +119505,uniqid in javascriptjquery whats the equivalent of this function in javascriptbasically i need to generate a random id that looks like a4245f54345 and starts with a alphabetic character so i can use it as a css id,"['javascript', 'jquery']" +119513,find speed of vehicle from images i am doing a project to find the speed of a vehicle from images we are taking these images from within the vehicle we will be marking some object from the 1st image as a reference using the properties of the same object in the next image we must calculate the speed of the moving vehicle can anyone help me here i am using python opencv i have succeeded till finding the marked pixel in the 2nd image using optical flow method can anyone help me with the rest,['python'] +119520,java resultsetclose preparedstatementclose what for in my webapplication i make extensive use of a database i have an abstract servlet from which all the servlets that need a database connection inherit that abstract servlet creates a database connection calls the abstract method which must be overriden by the inheriting servlets to do their logic and then closes the connection i do not use connection pooling because my application will have a very limited number of users and operations my question is whats the worst that can happen if i do not ever close the resultsets preparedstatements and statements that my inheriting servlets create if the connections that create them are always closed,['java'] +119566,thisplay an image in c i want to thisplay images with c with picturebox i have created an class that contians a picturebox and a timer but when create object from that nothing thisplaywhat should i doam i using timer1 correctlyhere is my code public form1 initializecomponent private void button1 clickobject sender eventargs e c1 c new c1 ccreate move1 class c1 picturebox p new picturebox timer timer1 new timer public void create moveint i pimagelocation 1png plocation new point50 50 i 1 50 timer1start timer1interval 15 timer1tick new eventhandlertimer tick private int k 0 void timer tickobject sender eventargs e some code this part work outside the class c1 properly,['c#'] +119573,javascript decompress inflate unzip ungzip strings i am looking for javascript implementation of string inflating algorithmsi want to compress on the server side java and decompress on the client side javascripti have foundunzip strings in javascriptthat one is marked as answered with an answer for different problem other answers are also for something else unzipping files in zip formatjavascript inflate implementation possibly ff 36 onlythis is closest to what i need however i would like to have some alternativessuggestionsthanks ondraupdate i have quite a specific use case please do not answer do not do that in javascripti am writing an offline reporting tool once generated it is put to a static store and deflating may save megabytes for a single report i am constrained by other apps so i cannot store it as a zip file,['javascript'] +119587,are there oauth 2 server side php or java implementations if there is more then one implementation which one is bettermostly maintained specifically for oauth 20 draft 12,"['java', 'php']" +119593,how to get value of checked item from checkedlistbox i have used a checkedlistbox over my winform in c i have bounded this control as shown below chlcompaniesdatasource dscompaniestables0chlcompaniesthisplaymember companynamechlcompaniesvaluemember idi can get the indices of checked items but how can i get checked item text and value rather how can i enumerate through checkeditems accessing text and valuethanks for sharing your time,['c#'] +119599,resteasy multipartdataform file upload on gae i am trying to use resteasy 201ga to upload a form with a file in it into gae application using the method advised at how do i do a multipartform file upload with jaxrsindexhtmlform actionrestupload methodpost enctypemultipartformdata input typetext namename input typefile namefile input typesubmit formrestjavapathpublic class rest post pathrestupload consumesmultipartformdata public string postcontentmultipartform uploadform form systemoutprintlnformgetdatalength systemoutprintlnformgetname return done uploadformjavapublic class uploadform private string name private byte data formparamname public void setpathstring name thisname name public string getname return name formparamfile public void setcontentdatabyte data thisdata data public byte getdata return data but i am getting the following error message probably due to the resteasy providers implmenetation that uses temporary files to handle the input streamhttp error 500problem accessing filesserviceupload reason javaiofileoutputstream is a restricted class please see the google app engine developers guide for more detailscaused byjavalangnoclassdeffounderror javaiofileoutputstream is a restricted class please see the google app engine developers guide for more details at comgoogleappenginetoolsdevelopmentagentruntimeruntimerejectruntimejava51 at orgapachejamesmime4jstoragetempfilestorageprovidertempfilestorageoutputstreaminittempfilestorageproviderjava117 at orgapachejamesmime4jstoragetempfilestorageprovidercreatestorageoutputstreamtempfilestorageproviderjava107 at orgapachejamesmime4jstoragethresholdstorageproviderthresholdstorageoutputstreamwrite0thresholdstorageproviderjava113 at orgapachejamesmime4jstoragestorageoutputstreamwritestorageoutputstreamjava119 at orgapachejamesmime4jcodeccodecutilcopycodecutiljava43 at orgapachejamesmime4jstorageabstractstorageproviderstoreabstractstorageproviderjava57 at orgapachejamesmime4jmessagebodyfactorytextbodybodyfactoryjava167 at orgapachejamesmime4jmessagemessagebuilderbodymessagebuilderjava148 at orgapachejamesmime4jparsermimestreamparserparsemimestreamparserjava101 at orgapachejamesmime4jmessagemessageinitmessagejava141 at orgapachejamesmime4jmessagemessageinitmessagejava100 at orgjbossresteasypluginsprovidersmultipartmultipartinputimplparsemultipartinputimpljava76 at orgjbossresteasypluginsprovidersmultipartmultipartformannotationreaderreadfrommultipartformannotationreaderjava55 at orgjbossresteasycoreinterceptionmessagebodyreadercontextimplproceedmessagebodyreadercontextimpljava105 at orgjbossresteasypluginsinterceptorsencodinggzipdecodinginterceptorreadgzipdecodinginterceptorjava46 at orgjbossresteasycoreinterceptionmessagebodyreadercontextimplproceedmessagebodyreadercontextimpljava108 at orgjbossresteasycoremessagebodyreaderutilitydoreadreaderutilityjava1 at orgjbossresteasycoremessagebodyreaderutilitydoreadreaderutilityjava93 at orgjbossresteasycoremessagebodyparameterinjectorinjectmessagebodyparameterinjectorjava146 at orgjbossresteasycoremethodinjectorimplinjectargumentsmethodinjectorimpljava114 at orgjbossresteasycoremethodinjectorimplinvokemethodinjectorimpljava137 at orgjbossresteasycoreresourcemethodinvokeontargetresourcemethodjava252 at orgjbossresteasycoreresourcemethodinvokeresourcemethodjava217 at orgjbossresteasycoreresourcemethodinvokeresourcemethodjava206 at orgjbossresteasycoresynchronousthispatchergetresponsesynchronousthispatcherjava514 at orgjbossresteasycoresynchronousthispatcherinvokesynchronousthispatcherjava491 at orgjbossresteasycoresynchronousthispatcherinvokesynchronousthispatcherjava120 at orgjbossresteasypluginsserverservletservletcontainerthispatcherserviceservletcontainerthispatcherjava200 at orgjbossresteasypluginsserverservlethttpservletthispatcherservicehttpservletthispatcherjava48 at orgjbossresteasypluginsserverservlethttpservletthispatcherservicehttpservletthispatcherjava43 at javaxservlethttphttpservletservicehttpservletjava717 has anyone encountered this issue with gae and resteasy has anyone solved it i could not find any mentioning for this issue anywherethanks,['java'] +119604,why is there no implicit this in javascript in javascript this must always be stated explicitly when accessing its properties for examplefunction frobberx thisx x return thisfrobberprototypefrob function wrong return x x right return thisx thisxi am aware i can use withthis which is deprecated and generally frowned upon but why are not properties of this in scope automatically i am thinking there must be a reason for this design decision,['javascript'] +119608,mysql query order by multiple items is is possible to order by multiple rows i want my users to be sorted by last activity but at the same time i want the users with pictures to appear before the ones withoutsomething like thisselect some colsfrom prefix userswhere some conditionsorder by last activity pic set desc,['mysql'] +119621,generics and javabeansintrospector given the following code skeleton is it possible to determine that the property foo is in fact of type stringpublic class testintrospection public static class superbeant private t foo public t getfoo return foo public void setfoot foo thisfoo foo public static class subbean extends superbeanstring public static void mainstring args throws introspectionexception beaninfo beaninfo introspectorgetbeaninfosubbeanclass propertydescriptor propertydescriptors beaninfogetpropertydescriptors for propertydescriptor prop propertydescriptors if fooequalspropgetname systemoutprintfs of sn propgetname propgetpropertytype method readmethod propgetreadmethod type returntype propgetreadmethodgetgenericreturntype if returntype instanceof typevariable typevariable t typevariable returntype genericdeclaration d tgetgenericdeclaration systemoutprintlntypevariable tgetname tgetbounds0 the actual output isfoo of class javalangobject typevariable t class javalangobjectedit i should have mentionend that i know about type erasure and that the method is in fact returning an object on the bytecode level nevertheless the metadata about generic types is available in the class file and can be queried by reflection as in the sample code here is another snippet that shows that subbean in fact has a type parameter of type string type superclass subbeanclassgetgenericsuperclass parameterizedtype pt parameterizedtype superclass systemoutprintlnptgetactualtypearguments0outputclass javalangstringthe question then remains how do i relate this actual type argument to the type variable if i know that there is only one type parameter this is simple but i would like this code to work also for beans having multiple generic type parameters,['java'] +119649,how do i map different values for a parameter in the same requestmapping in spring mvc suppose i haverequestmappingparams actionnuovoprodotto public modelandview nuovoprodotto requestparamvalue page required false defaultvalue 1 int page requestparamvalue action string action modelattribute prodotto prod httpsession session throws exception is it possible to map this request to like two or three values of action parameteri tried many ways like requestmappingparams actionnuovoprodotto actionsalvaprodotto orrequestmappingparams actionnuovoprodottosalvaprodotto but they do not work if i cannot what are the solutions besided writing an handler for every single parameter value combination,['java'] +119650,copy file from truecrypt volume to clipboard i use this code to copy files to clipboardidataobject data new dataobjectdatasetdatadataformatsfiledrop new string xtestdocmemorystream memo new memorystream4byte bytes new byte byte5 0 0 0 memowritebytes 0 byteslengthdatasetdatapreferred dropeffect memoclipboardsetdataobjectdataunfortunately this does not work if the thisk is a truecrypt mounted volume what is the way to do this on a truecrypt volume,['c#'] +119651,what is the dict dict attribute of a python class class aobject pass a dict dictproxy object at 0x173ef30 a dict dict traceback most recent call last file string line 1 in fragmentattributeerror dictproxy object has no attribute dict a dict copy dict attribute dict of a objects a dict dict attribute dict of a objects what is this objectif i do asomething 10 this goes into a dict what is this attribute dict of a objects found in a dict dict and when does it contain something,['python'] +119652,selecting inner html in a jquery selector i have the following html div idctl00 m g f660033c e200 4bff b244 b574efe5b9b5 ul stylemarginleft 0px li idli5a hreft paula li li idli4a hrefpeopler jessea li li idli1a hrefanimalsel guapoa li li idli2a hrefanimalssashaa li li idli3a hrefpeopleg jenicea li uldivi want to select only li elements that contain in the inner text i can check for this in jquery using the following code if thishtmlindexof 1 return however i would like to do this in the jquery selector to avoid unnecessary parsing i can use something like this to match on the id fieldul li aid but i was not able to find a way to match on the html within the a element in the jquery selector is it possible to do this thanks in advance,"['jquery', 'html']" +119663,boosttest tests on a static library i am using boosttest for unit testingbecause of several reasons i would like to write the unit test cases on different static librariesthe problem is that when i do this the automatic registrar does not workfor instance if i have something like foo testscppdefine boost test module fooinclude boosttestunit testhppboost auto test case bar boost check false used to generate libfootestsa maincppdefine boost test dyn linkdefine boost test maininclude boosttestunit testhpp used to generate mainothen if i link maino with libfootestsa and execute the final binary it saystest setup error test tree is emptyeverything works just fine if i create the binary from the source codes directly but i want to be able to write unit tests inside static libraries using automatic registrationcan i achieve thisis there some macro i need to define some symbol that i need to export from libfootestsathanks,['c++'] +119683,like operator or using wildcards in linq to entities i am using linq 2 entitiesfollowing is the problemstring str testdoc containsstr converts this into like testdocexpected conversion like testdocif it was linq 2 sql i could have used sqlmethodslike as somebody answered it in my previous question but now as i am using l2e not l2s i need other solution,['c#'] +119698,when setting up a wcf client and server how synchronized does the config files must be most of the wcf examples out there show you how to configure wcf client and server now what happens if you differ the configuration slightly between them i mean who has the final wordlet us take this client configuration for exampleconfigurationsystemservicemodel bindings wshttpbinding binding namewshttpbinding isampleservice closetimeout0100 opentimeout0100 receivetimeout0100 sendtimeout0100 bypassproxyonlocalfalse transactionflowfalse hostnamecomparisonmodestrongwildcard maxbufferpoolsize524288 maxreceivedmessagesize65536 messageencodingtext textencodingutf8 usedefaultwebproxytrue allowcookiesfalse readerquotas maxdepth32 maxstringcontentlength8192 maxarraylength16384 maxbytesperread4096 maxnametablecharcount16384 reliablesession orderedtrue inactivitytimeout0010 enabledfalse security modemessage transport clientcredentialtypenone proxycredentialtypenone realm message clientcredentialtypewindows negotiateservicecredentialtrue algorithmsuitedefault establishsecuritycontexttrue security binding wshttpbinding bindings client endpoint addresshttplocalhost8080sampleservice bindingwshttpbinding bindingconfigurationwshttpbinding isampleservice contractisampleservice namewshttpbinding isampleservice endpoint clientsystemservicemodelusually the server side will have the exact same binding configured on its exposed serverbut what happens now if on the server side is defined with opentimeout 030 what will be the timeout who wins i do the same question for all other parametersthe whole thing seems a big mess how can you tell for each element of the configuration binding client service behavior etc and all their details which parameters is required and in which side client or serverit seems you could define the entire binding with all timeout parameters on the server side and on the client side simply put the minimum required configuration so all parameters from the server are accepted but now what are the minimum required parameters on the client considering the server has a more in depth configurationwhat are the best practice when configuring client and server using wcf regarding parameters for each element of the configuration bindings services clientendpoint and behaviorwhen conflicting parameters are defined between client and server how wcf handles it,['.net'] +119740,how to convert html entities like to their character equivalents i am creating a file that is to be saved on a local users computer not rendered in a web browseri am currently using html entity decode but this is not converting characters like 8211 which is the ndash and was wondering what other function i should be usingfor example when the file is imported into the software instead of the ndash or just a it shows up as 8211 i know i could use str replace but if it is happening with this character it could happen with many others since the data is dynamic,['php'] +119742,sum of all values in a python dict i am new to python let us say i have a dictionary in which the keys map to integers liked key11key214key347is there a syntactically minimalistic way to return the sum of the values in die 62 in this casethanks,['python'] +119769,why clicking on checkbox does not add the attribute checkedchecked when i click a checkbox why does checked attribute is not getting added you can see the code here,"['javascript', 'jquery', 'html']" +119789,how to set datetimezone for code igniter to work with php53 when datetimezone in phpini is commented out it gives mea php error was encounteredseverity warningmessage main it is not safe to rely on the systems timezone settings you are required to use the datetimezone setting or the date default timezone set function in case you used any of those methods and you are still getting this warning you most likely misspelled the timezone identifier we selected americalos angeles for 80no dst insteadfilename controllershelloworldphpline number 2when i havedatetimezone americalos angelesit gives me thisserver error the website encountered an error while retrieving httplocalhostciindexphphelloworld it may be down for maintenance or configured incorrectly here are some suggestions reload this web page later http error 500 internal server error an unexpected condition was encountered while the server was attempting to fulfill the requesti am using php53 code igniter 200 and apache22 anyone has this problem tooupdate 1i tried loading a testphp without code igniter where the first 3 lines of testphp isdate default timezone setamericalos angelesecho datel j of f y his aand it works fine different timezones also works fine tooso i suspect the problem is from code igniteranyone using code igniter here,['php'] +119800,why is my string not being printed i have some code that in its smallest complete form that exhibits the problem being a good citizen when it comes to asking questions basically boils down to the followinginclude stringinclude iostreamint main void int x 11 stdstring s value was x stdcout s stdendl return 0and i am expecting it to output value was 11instead instead of that i am getting justwhy is that why can i not output my string is the string blank is cout somehow broken have i gone mad,['c++'] +119802,how to handle http authentication using httpurlconnection i am writing a java client that posts to a http server that requires authenticationi have to support at least the following three authentication methods basic digest or negotiate additionally the post may be very large over 2mb so i need to use streaming as is documented for httpurlconnectionwhen output streaming is enabled authentication and redirection cannot be handled automatically a httpretryexception will be thrown when reading the response if authentication or redirection are requiredso i need to handle authentication myself i searched and searched again for a way to employ the already coded classes but found no wayi could just pluck the needed sources from here as they are gplv2 with classpath exception is this the right waythanks,['java'] +119834,create comma separated strings c i have an object which holds many values some of them not all values from the object need to be put in a csv string my approach was thisstring csvstring onumber oid owhatever somehow i think there is a better more elegant way,['c#'] +119843,css pagebreak not working in all browsers i am having trouble getting this working in most browsers except for ie it even works correctly in ie6 and operafirefox separates the divs correctly but only prints the first pagechrome and safari only applies the page break to the last divhow can i get this working across all browsers correctlythe htmldiv idleftnav ul links etc uldivdiv idmainbody div idcontainer div classpagebreak content div div classpagebreak content div div classpagebreak content div divdivthe divs with the ids leftnav and mainbody are are set to floatleft so they thisplay nicelyi only want to print the pagebreak classes hiding the leftnav and the rest of the mainbody with cssthe css media print leftnav thisplaynone mainbody bordernone marginnone paddingnone answerafter reading the w3schools pagebreakafter article i realised that i had not removed the float from the mainbody div after setting floatnone on the mainbody div the pages now thisplay correctly dthanks for your replies,['css'] +119853,hung jvm consuming 100 cpu we have a java server running on sun jre 6u20 on linux 32bit centos we use the server hotspot with cms collector with the following options i have only provided the relevant ones xmx896m xss128k xxnewsize384m xxmaxpermsize96m xxuseparnewgc xxuseconcmarksweepgcsometimes after running for a while the jvm seems to slip into a hung state whereby even though we do not make any requests to the application the cpu continues to spin at 100 we have 8 logical cpus so it looks like only one cpu does the spinningin this state the jvm does not respond to sighup signals kill 3 and we cannot connect to it normally with jstack we can connect with jstack f but the output is dodgy we can see lots of nullpointerexceptions from jstack apparently because it was not able to walk some stacks so the jstack f output seems to be uselesswe have run a stack dump from gdb though and we were able to match the thread id that spins the cpu we found that using top with a perthread view h option with a thread stack that appears in the gdb result and this is how it looks likethread 443 thread 0x7e5b90 lwp 263100 0x0115ebd3 in compactiblefreelistspaceblock sizeheapword const const from usrjavajdk160 20jrelibi386serverlibjvmso1 0x01160ff9 in compactiblefreelistspaceprepare for compactioncompactpoint from usrjavajdk160 20jrelibi386serverlibjvmso2 0x0123456c in generationprepare for compactioncompactpoint from usrjavajdk160 20jrelibi386serverlibjvmso3 0x01229b2c in gencollectedheapprepare for compaction from usrjavajdk160 20jrelibi386serverlibjvmso4 0x0122a7fc in genmarksweepinvoke at safepointint referenceprocessor bool from usrjavajdk160 20jrelibi386serverlibjvmso5 0x01186024 in cmscollectordo compaction workbool from usrjavajdk160 20jrelibi386serverlibjvmso6 0x011859ee in cmscollectoracquire control and collectbool bool from usrjavajdk160 20jrelibi386serverlibjvmso7 0x01185705 in concurrentmarksweepgenerationcollectbool bool unsigned int bool from usrjavajdk160 20jrelibi386serverlibjvmso8 0x01227f53 in gencollectedheapdo collectionbool bool unsigned int bool int from usrjavajdk160 20jrelibi386serverlibjvmso9 0x0115c7b5 in gencollectorpolicysatisfy failed allocationunsigned int bool from usrjavajdk160 20jrelibi386serverlibjvmso10 0x0122859c in gencollectedheapsatisfy failed allocationunsigned int bool from usrjavajdk160 20jrelibi386serverlibjvmso11 0x0158a8ce in vm gencollectforallocationdoit from usrjavajdk160 20jrelibi386serverlibjvmso12 0x015987e6 in vm operationevaluate from usrjavajdk160 20jrelibi386serverlibjvmso13 0x01597c93 in vmthreadevaluate operationvm operation from usrjavajdk160 20jrelibi386serverlibjvmso14 0x01597f0f in vmthreadloop from usrjavajdk160 20jrelibi386serverlibjvmso15 0x015979f0 in vmthreadrun from usrjavajdk160 20jrelibi386serverlibjvmso16 0x0145c24e in java startthread from usrjavajdk160 20jrelibi386serverlibjvmso17 0x00ccd46b in start thread from liblibpthreadso018 0x00bc2dbe in clone from liblibcso6it seems that a jvm thread is spinning while doing some cms related workwe have checked the memory usage on the box there seems to be enough memory available and the system is not swappinghas anyone come across such a situation does it look like a jvm bugupdatei have obtained some more information about this problem it happened again on a server that has been running for more than 7 dayswhen the jvm entered the hung state it stayed like that for 2 hours until the server was manually restarted we have obtained a core dump of the process and the gc log we tried to get a heap dump as well but jmap failed we tried to use jmap f but then only a 4mb file was written before the program aborted with an exception something about the a memory location not being accessibleso far i think the most interesting information comes from the gc log it seems that the gc logging stopped as well possibly at the time when the vm thread went into the long loop657501199 full gc system 657501199 cms 400352k313412k524288k 24024120 secs 660634k313412k878208k cms perm 29455k29320k68568k 24026470 secs times user239 sys001 real240 secs 657513941 gc 657513941 parnew 314624k139k353920k 00228180 secs 628036k327412k878208k 00230510 secs times user008 sys0 real002 secs 657523772 gc 657523772 parnew 328623k17110k353920k 00244910 secs 642036k330523k878208k 00247140 secs times user008 sys0 real002 secs 657535473 gc 657535473 parnew 331734k20282k353920k 00259480 secs 645147k3695k878208k 00261670 secs times user011 sys0 real002 secs 688346765 gc 1 cmsinitialmark 485248k524288k 515694k878208k 00343730 secs times user003 sys0 real004 secs 688346800 cmsconcurrentmarkstart688347964 cmsconcurrentmark 10831164 secs times user252 sys009 real116 secs 688347964 cmsconcurrentprecleanstart688347969 cmsconcurrentpreclean 0405 secs times user0 sys001 real001 secs 688347969 cmsconcurrentabortableprecleanstart cms abort preclean due to time 688352986 cmsconcurrentabortablepreclean 23515017 secs times user383 sys038 real501 secs 688352987 gcyg occupancy 297806 k 353920 k688352987 rescan parallel 01815250 secs688353169 weak refs processing 00312660 secs 1 cmsremark 485248k524288k 783055k878208k 02131580 secs times user113 sys0 real022 secs 688353201 cmsconcurrentsweepstart688353903 cmsconcurrentsweep 06600702 secs times user091 sys007 real070 secs 688353903 cmsconcurrentresetstart688353912 cmsconcurrentreset 0808 secs times user001 sys0 real001 secs 688354243 gc 688354243 parnew 344928k30151k353920k 00305020 secs 681955k368044k878208k 003080 secs times user015 sys0 real003 secs688943029 gc 688943029 parnew 336531k17143k353920k 00237360 secs 813250k494327k878208k 00241260 secs times user010 sys0 real003 secs 688950620 gc 688950620 parnew 331767k22442k353920k 00344110 secs 808951k496k878208k 00347690 secs times user011 sys0 real004 secs 688956596 gc 688956596 parnew 337064k37809k353920k 00488170 secs 814618k515896k878208k 00491550 secs times user018 sys004 real005 secs 688961470 gc 688961471 parnew promotion failed 352433k332183k353920k 01862520 secs688961657 cmsi suspect this problem has something to do with the last line in the log i have added some in order to skip some lines that were not interestingthe fact that the server stayed in the hung state for 2 hours probably trying to gc and compact the old generation seems quite strange to me also the gc log stops suddenly with that message and nothing else gets printed any more probably because the vm thread gets into some sort of infinite loop or something that takes 2 hours,['java'] +119863,mvc3 valums ajax file upload i am trying to use valums ajax uploader i have the following on my pagevar button fileupload0var uploader new qqfileuploader element button allowedextensions jpg jpeg png gif sizelimit 2147483647 max size action adminhomeupload multiple falseit does post to my controller but qqfile is always null i tried thesepublic actionresult uploadhttppostedfile qqfileandhttppostedfilebase file requestfilesfilewithout any lucki found an example for ruby on rails but not sure how to implement it in mvcin firebug i see thishttplocalhost61143adminhomeuploadqqfile2glonglonglongnamecopygif,['asp.net'] +119865,how to find the current translate position in canvas how do i get the current translate position from a canvas i am trying to draw stuff where my coordinates are a mix of relative to each other and absolute to canvaslets say i want to docanvastranslatex1 y1canvasdrawsomething0 0 will show up at x1 y1 all good now i want to draw a point at x2y2canvastranslatex2 y2canvasdrawsomething0 0 will show up at x1x2 y1y2 i could docanvasdrawsomethingx1 y1 but i do not always know those coordsthis works but is dirtyprivate static point getcurrenttranslatecanvas canvas float pos new float 2 canvasgetmatrixmappointspos return new pointintpos0 intpos1point p getcurrenttranslatecanvascanvasdrawsomethingpx pythe canvas has a getmatrix method it has a settranslate but no gettranslate i do not want to use canvassave and canvasrestore because the way i am drawing things it is a little tricky and probably messy is there a cleaner way to get these current coordinates,['android'] +119866,mixed locales in rails i18n rails somehow mixes my locales an i have absolutely no clue why most of my translated strings work as expected but for some it mixes the localesinterestingly this only happens on one of our systems specifically running passenger with apachewhen using webrick thin or passenger standalone on my development system everything is alrightthis is what i have in my applicationrbconfigi18ndefault locale dethis is in application controllerrbbefore filter set localedef set locale i18nlocale current client current clientlocale i18ndefault localeendi experience the problems on pages where current client is nil and the else part gets executedso i am basically using the de locale when showing a validation error on a form i experience mixed up translations like thisist zu kurz nicht weniger als 6 zeichen und translation missing enactiverecorderrorscustompassword formatas you can see the error message from the first failing validation is translated as expected for the second error message tries to access the english translation which does not exist i suspect a problem with lazy loading of translated strings even before the before filter gets executedany clues why this might happenfor the record this is rails 3editi just thiscovered that this depends on the environment used when using the development environment everything is fine when using the production environment or a productionlike environment i experience the behavior described aboveedit 2i found out even more it specifically depends on configcache classes when set to true i see the mixed translations when set to false as in the typical development environment i18n works as expectededit 3maybe this is related to the following bug edit 4this is related to the bug mentioned above the problem is due to eagerly loaded model classes which use i18n strings but eager class loading happens before i18n initialization hence the translations are not found there even is another bug about thisunfortunately the rails guys did not manage to include the fix in the recent 304 release as far as i can tell hence i am trying to figure out a workaround like this in my application configuration configbefore eager load do i18nload path dirrailsrootjoinconfig locales deymlto s i18nrailtiereloaderpathsconcat i18nload path i18nrailtiereloaderexecute if updated i18nreload endunlucky this does not work any clues,['ruby-on-rails'] +119867,how read imageview margin programmatically i have an imageview which is written in a layout file and looks like thislinearlayout androidlayout widthfill parent androidlayout heightfill parent androidorientationvertical imageview androidididnews image androidlayout heightfill parent androidlayout widthfill parent androidlayout marginleft18dip androidlayout marginright18dip androidbackgrounda linearlayouthow can i read the androidlayout marginleft attribute in my activityi tried this following code but layoutparams of my imageview does not have any margin members like for example linearlayoutlayoutparams hasimageview imageview imageviewfindviewbyidridnews imagelayoutparams lp imageviewgetlayoutparamsint marginleft lpmarginleft do not do this it will not work cause there is no member called marginleftany suggestions how to get the margin from a imageviewthank you,['android'] +119876,how to pass different objects as a parameter to asyctask i am using following code to create an asynctaskpublic class savefiletoexternalstorage extends asynctaskfile void boolean protected boolean doinbackgroundfile file dalcategories c new dalcategories boolean result csaveobjectcustomlistobjectfile0 return result protected void onprogressupdate setprogresspercentprogress0 protected void onpostexecuteboolean result showdialogdownloaded result bytes now i want to pass it two parameters customlistobject and file objects with void progress and boolean return typei do not know how to pass that customlistobject to my asynctask along with the file object,['android'] +119883,what does volatile mean in java we use volatile in one of our projects to maintain the same copy of variable accessed by different threads my question is whether it is alright to use volatile with static the compiler does not give any errors but i do not understand the reason of using both,['java'] +119885,force portrait orientation mode i am trying to force the portrait mode for my application because my application is absolutely not designed for the landscape modeafter reading some forums i added these lines in my manifest fileapplication androiddebuggabletrue androidicondrawableicon androidlabelstringapp name androidscreenorientationportraitbut it does not work on my device htc desire it switches from portrait lo landscape ignoring the lines from the manifest fileafter more forums reading i tried to add this in my manifest fileapplication androiddebuggabletrue androidicondrawableicon androidlabelstringapp name androidconfigchangesorientation androidscreenorientationportraitand this function in my activity classpublic void onconfigurationchangedconfiguration newconfig superonconfigurationchangednewconfig setrequestedorientationactivityinfoscreen orientation portraitbut again no luck,['android'] +119908,get value from key using linq i have dictionary from string key i want to get value of corresponding key using linq,['c#'] +119913,what is the shortest way to compare if two ienumerable have the same items in c possible duplicatetest whether two ienumerablet have the same values with the same frequencies i wroteupdated correctionstatic bool havesameitemstthis ienumerablet self ienumerablet other return otherexceptthisany thisexceptotherany is not there a shorter wayi know there is sequenceequal but the order does not matter for me,['c#'] +119929,using simple xml to read rss feed i am using php and simplexml to read the following rss feedi can get most of the information i want like sorss simplexml load fileecho h1 rsschanneltitle h1foreach rsschannelitem as item echo h2a href itemlink itemtitle ah2 echo p itempubdate p echo p itemdescription p but how would i output the thumbnail image that is in the following tagmediathumbnail width66 height49 url 51078953 226alanpotburyjpg,['php'] +119938,struggling with vertex and index buffers in direct3d i have tried for many months to learn how idirect3dvertexbuffer9 and idirect3dindexbuffer9 work i have read multiple books ebooks and forums and i still cannot get the hang of how they work can somebody help me understand how they work and how they link togetherps i have tried searching through the related questions but nothing interested methanks,['c++'] +119992,downloadingcaching google maps for offline use i would like to be able to implement this in an android app and i thought it was possible with the newest google maps api release but i have not seen much thiscussion on the topic ideally youd be able to downloadcache maps for a certain region for later offline use is it only possible to do this via the google maps 5 application and not the api without violating the tos i know openstreetmap and others allow this but i believe google maps still offers superior mapping and the most widespread usagethanks in advance,['android'] +120035,summing up digits hi i have been trying out this problemsuppose pn is sum of digits of 2n for example as 215 32768 and the sum of its digits is 3 2 7 6 8 26so p1526 catulate sum of the pn for n1 to 10here is my python code which is giving 67783431 as answer but the judge does not seems to be agree on thisdef pn and int1n s 0 while and 0 s n10 and 10 return ssum 0for i in range1101 sum pielse printsumcould anybody tell me whats wrong in my approach i would be appreciate if somebody points me to a mathematical solution for the same,['python'] +120059,calculating europeanoptionimpliedvolatility in quantlibpython i have r code that uses rquantlib library in order to run it from python i am using rpy2 i know python has its own bindings for quantlib quantlibpython i would like to switch from r to python completelyplease let me know how i can run the following using quantlibpythonimport rpy2robjects as robjectsrobjectsrlibraryrquantlibx robjectsrxeuropeanoptionimpliedvolatilitytypecall value10 underlying100strike100 dividendyield001 riskfreerate003maturity05 volatility04print xsample run python volpy loading required package rcppimplied volatility for europeanoptionimpliedvolatility is 0381,['python'] +120070,how can i prompt the user to turn on location services after user has denied their use i have an application with an explicit user interaction that makes use of the users current location if the user denies access to location services i would still like subsequent uses to prompt the user to go to settings and reenable location services for my appthe behavior i want is that of the builtin maps appreset location warnings in settings general reset reset location warningsstart maps apptap current location button in lower left cornermaps prompts with maps would like to use your current location do not allow allowchoose do not allow optiontap current location button in lower left corner againmaps prompts with turn on location services to allow maps to determine your location settings cancelin my own app the same basic flow results in my cllocationmanagerdelegate locationmanagerdidfailwitherror method being called with a kclerrordenied error at the final step and the user is not given the option to open the settings app to correct iti could thisplay my own alert in response to the error but it would not have the ability to launch the settings app like the alert that the os can provide as used by the builtin maps appis there something in the cllocationmanager class i am missing that would be able to give me this behavior,['ios'] +120073,what browsers support overflowy from what i understand overflowy is a css3 selector but at it does not have that selector shown show i do not know what browsers support itfirst are overflowy and overflowx actually css3 selectorssecond what browsers support them,"['html', 'css']" +120079,show value within bar on flot bar chart i would like to show the value within the bar on the flot bar chart something like this 20 10 data 1 10 2 20is there a way to do this,"['javascript', 'jquery']" +120090,sorting a vector of structs i have a vectordata info where data is defined asstruct data string word int numberi need to sort info by the length of the word strings is there a quick and simple way to do it,['c++'] +120113,resolveurl without an aspnet page i am looking for a way to resolve a relative url the way you would with a page or control instance msdn docs such aspageresolveurlcommonerroraspxbut when i only have an httpcontext available to me such as when i am in a httphandler will i need to use a custom function such as the one seen hereor is there a way to get at the underlying function used by the page,"['c#', '.net', 'asp.net']" +120135,what does for mean in cc what does the following meanfor unfortunately i cannot google that and get meaningful results,"['c++', 'c']" +120142,wpf application will not start due to a systemiofileformatexception i have written a wpf application in net 40 i have installed and successfully run the application on the following operating systemswindows xp sp2vistawindow 7 32 bitwindows 7 64 bitafter installing the application on a machine with windows xp sp3 the application failed to start i checked the event viewers application logs and found the following errorapplication applicationnameexeframework version v4030319description the process was terminated due to an unhandled exceptionexception info systemiofileformatexceptionstack at systemwindowsmediaimagingbitmapframedecodeensurethumbnail at systemwindowsmediaimagingbitmapframedecodeget thumbnail at msinternalappmodeliconhelpergetbestmatchsystemcollectionsobjectmodelreadonlycollection1systemwindowsmediaimagingbitmapframe systemwindowssize at msinternalappmodeliconhelpercreateiconhandlefromimagesourcesystemwindowsmediaimagesource systemwindowssize at msinternalappmodeliconhelpergeticonhandlesfromimagesourcesystemwindowsmediaimagesource iconhandle byref iconhandle byref at systemwindowswindowupdateicon at systemwindowswindowsetupinitialstatedouble double double double at systemwindowswindowcreatesourcewindowboolean at systemwindowswindowcreatesourcewindowduringshow at systemwindowswindowsafecreatewindowduringshow at systemwindowswindowshowhelpersystemobject at systemwindowswindowshow at applicationnameapploadmainwindow at applicationnameapponstartupsystemwindowsstartupeventargs at systemwindowsapplicationctorb 1systemobject at systemwindowsthreadingexceptionwrapperinternalrealcallsystemdelegate systemobject int32 at msinternalthreadingexceptionfilterhelpertrycatchwhensystemobject systemdelegate systemobject int32 systemdelegate at systemwindowsthreadingthispatcheroperationinvokeimpl at systemwindowsthreadingthispatcheroperationinvokeinsecuritycontextsystemobject at systemthreadingexecutioncontextruntrycodesystemobject at systemruntimecompilerservicesruntimehelpersexecutecodewithguaranteedcleanuptrycode cleanupcode systemobject at systemthreadingexecutioncontextruninternalsystemthreadingexecutioncontext systemthreadingcontextcallback systemobject at systemthreadingexecutioncontextrunsystemthreadingexecutioncontext systemthreadingcontextcallback systemobject boolean at systemthreadingexecutioncontextrunsystemthreadingexecutioncontext systemthreadingcontextcallback systemobject at systemwindowsthreadingthispatcheroperationinvoke at systemwindowsthreadingthispatcherprocessqueue at systemwindowsthreadingthispatcherwndprochookintptr int32 intptr intptr boolean byref at mswin32hwndwrapperwndprocintptr int32 intptr intptr boolean byref at mswin32hwndsubclassthispatchercallbackoperationsystemobject at systemwindowsthreadingexceptionwrapperinternalrealcallsystemdelegate systemobject int32 at msinternalthreadingexceptionfilterhelpertrycatchwhensystemobject systemdelegate systemobject int32 systemdelegate at systemwindowsthreadingthispatcherinvokeimplsystemwindowsthreadingthispatcherpriority systemtimespan systemdelegate systemobject int32 at mswin32hwndsubclasubclasswndprocintptr int32 intptr intptr at mswin32unsafenativemethodsthispatchmessagesystemwindowsinteropmsg byref at systemwindowsthreadingthispatcherpushframeimplsystemwindowsthreadingthispatcherframe at systemwindowsthreadingthispatcherpushframesystemwindowsthreadingthispatcherframe at systemwindowsthreadingthispatcherrun at systemwindowsapplicationrunthispatchersystemobject at systemwindowsapplicationruninternalsystemwindowswindow at systemwindowsapplicationrunsystemwindowswindow at applicationnameappmainso i am guessing that it has something to do one of the images i have in one of my windows but not sure what has anyone seen this exception before and have a solutionnote in case this is relevant my installer loads wic and the full net framework 40 onto the target machine where necessary,['.net'] +120156,force an entire mysql database to be in memory for the purposes of running a large number of tests that interact with the database i want to do two thingsi would like to copy the schema of a database without copying its data i can do this with a script that grabs the create table statements from each table in the databaseupon creating this database i would like to force it to be 100 in memoryi am stuck on how to do part 2 is there an easier way to do this other than specifying each tables engine somehow that seems like a poor way of doing it,['mysql'] +120167,why phpexcel does not allow to write more than 50 rows can any one please tell me why phpexcel does not allow more than 50 rowsi am using an opensource phpexcel for report generation on my projects and i could not write more than 50 rows of data from mysqldb my result set fetch 7230 records when the query is executed how do i fix it,['php'] +120172,how to modify capistrano deploy to automatically run migrations in rails 30 right now i have to run cap deploy and cap deploymigrations if there are migrations to be runhow i modify the cap deploy task to run migrations,['ruby-on-rails'] +120173,specify taskbar icon for a messagebox how do i specify which icon a messagebox should use in the taskbar there are no messageboxshow overloads which let me select a taskbar icon only an icon to use in the actual form,['.net'] +120194,dnsgethostentry error conditions and resolution methods i have a very specific problem concerning dnsgethostentrya service uses dnsgethostentry to retrieve all ip adresses of a host using the name of of the host this has always worked fine at a specific customer dnsgethostentry throws the no such host is known error when querying specific hosts the problem only occurs when trying to resolve hosts that are on a different domain than the machine the service is installed on the service has worked for quite some time but recently is stopped working throwing the no such host is known error sadly no stack trace is available nslookup works though no problems there the service in question is written in vbnet targetting the net framwork 20the comments in the msdn entry for net 30 vvs85aspx indictate that there may be a problem with the reverse dns entries for the hosts but i was not able to reproduce the problem on a test network even with all reverse lookup zones deleted there are more comments for other net versions all having similiar problems edit even deliberatly addind a wrong ptr record does not make the problem occur on my test machineedit2 the only thing that made the error come up was thisconnecting the network adapter and thereby making the dns server unavailable even though the forward resolving still worked due to cachingso my questions are under which conditions does gethostentry throw this specific error which resolution methods does it use if i am not mistaken it uses the unmanaged winsock function getnameinfo vvs85aspx name resolution can be by the domain name system dns a local hosts file or by other naming mechanismsany ideas why this suddenly fails for machines on the other domain but not for machines on the same domainthanks and best regardscun83,['.net'] +120197,should i load entire jquery ui jscss or only the parts that i need on a certain page i know what many of you will say this is a stupid question or maybe this is not the right forum or depend on the application etci am just wondering if i have a custom theme that i might change in future is it a good idea to separate the jquery ui i mean the js classes and css in smaller chunks files like droppableetc and include only the one that i need on certain page or keep them together and load the entire ui on every page both have positives and negatives i am just not sure which is betterwhat is your opinion any different approach possible,['jquery'] +120201,jqgrid headers on two or more rows i have the following problemi need to put on two or more rows header content of a jqgridi saw the example provided by zac on jqgrid double headers under alternatives but by changing only the css i get no change on the gridis it possible to have a more complete example in order to reproduce the behaviorthanksangelo,['jquery'] +120204,how to import to use objc msgsend i would like to import runtimes header to use objc msgsend but i am gettingerror nsobjcruntimeh no such file or directoryshould i add something to the header search path,"['objective-c', 'ios']" +120209,library for mesh generation in net is there any librarydll available in net or available as third party librarywhich provide following functionalitywe just add as input points cloud or points in 3d space with x y and z coordinateand it thisplay 3d object in viewport3d means automatically generate mesh from point cloud and give us the output as 3d object in viewport3dnote consider object would be convex objectthanks,"['c#', '.net']" +120217,select single row with linq to sql i start deal with linq to sql and i try solve this primitive problemi have very simple table with two columnsnick key uniquepasswordi would like delete row with some nick valuei use this method public void deletespirituserstring nick var user from you in dcspirit users where unick nick select u using var scope new transactionscope dcspirit usersdeleteonsubmituserfirst try dcsubmitchanges catch exception exception throw exception scopecomplete problem is that i must use userfirst if i want one single row i would like select with linq only one row know ienumerable because nick is unique,['c#'] +120221,copy datatable from one dataset to another i am trying to add to a new dataset x a datatable that is inside of a different dataset yif i add it directly i get the following errordatatable already belongs to another datasetdo i have to clone the datatable and import all the rows to it and then add the new datatable to the new dataset is there a bettereasy way to do it,['c#'] +120252,net xmlserializer on overriden properties i have a base class with an abstract propertypublic abstract int id getsetnow i have a subclass which is xmlserialized so it hasxmlelementsomethingpublic override int id get set i cannot move the xmlelement attribute to baseclass since every subclass will have a different xml elementnamenow when i deserialize this class i get the following errormember subclassid hides inherited member baseclassid but has different custom attributeswhat can i do,"['c#', '.net']" +120264,generating xml using sax and java anyone know of a good tutorial or have a good example for writing xml using the sax framework or something similar and java searching has yielded very little in terms of useful results i am trying to export from an android app and am looking to avoid as much memory overhead as possible,['java'] +120293,jstree types plugin does not thisplay custom icons i have a simple html layout that looks like thisdiv idfoo ul li idid1a hrefsome category 1a ullia hrefsome textaliul ullia hrefsome textaliul li li idid2a hrefsome category 2a ullia hrefsome textaliul ullia hrefsome textaliul li uldivthe jstree definition looks like thisfoojstreecore animation 0themes theme classic dots false icons truesort function a b return thisget texta thisget textb 1 1 types valid children folder types folder valid children file icon image pathtoimagesfolderpng max depth 1 file valid children none icon image pathtoimagesfilepng plugins html data themes contextmenu search sort types however i am still getting the generic theme icons for the filescategory should have a folder and the subcategories should have a file am i missing somethinghere is the answer for each type folder file etc you put in the list item rel where something is folder and whatnot then in your jstree configuration you have these settings for the types plugintypes valid children folder types folder valid children file max depth 1 file valid children none icon image safariextensionbaseuri imagesfilepng we define what to do with each rel type here this way jstree will pick up the rel type in the list item and figure out what to do with it from these definitions,['javascript'] +120316,rails 3 building an oauth2 provider i am developing an api in ruby on rails 3 and i would like to secure it with oauth2in other words i need to create an oauth provider is there a working gem for rails 3 out there or perhaps a tutorial on the issueupdatei know rails are rest based so i find it very strange that there are no tutorials on how to create a public api and secure it does anyone know of any good tutorials preferable with oauththankful for all help,['ruby-on-rails'] +120329,can gcc output c code after preprocessing i am using an open source library which seems to have lots of preprocessing directives to support many languages other than c so that i can study what the library is doing i would like to see the c code that i am compiling after preprocessing more like what i would writecan gcc or any other tool commonly available in linux read this library but output c code that has the preprocessing converted to whatever and is also readable by a human,['c'] +120339,is there any kind of referencecomparer in net there are several places in bcl where one can make use of iequalitycomparer like enumerablecontains or dictionary constructor i can provide my comparer if i am not happy with the default one sometimes i want to know whether the collection contains that very object that i have reference to not the one that is considered equal in any other meaningthe question is whether there exists standard equality comparer in the bcl that relies only on referenceequals method the one that i wrote myself is thisclass referencecomparert iequalitycomparert where t class private static referencecomparert m instance public static referencecomparert instance get return m instance m instance new referencecomparert public bool equalst x t y return referenceequalsx y public int gethashcodet obj return runtimehelpersgethashcodeobj i did not test it thoroughly nor considered lots of scenarios but it seems to make enumerablecontains and dictionary pretty happy,"['c#', '.net']" +120341,correct way to do html5 checkbox i cannot seem to find an example anywhere whats the correct way of doing a html5 checkbox,['html'] +120348,how to throw jsf2 404 error let us say that i have an application which manages users you can add new user delete them edit detail etc each user has na id and has detail page on url like thisuserdetailjsfid123now what should happen if user with id 123 does not exists i think that natural reaction would be 404 standard error exactly the same as is outputed when you make some typo in url like userdtailjsf so the question is is there such methodor maybe is this reaction 404 appropriatethanks,['java'] +120350,jpeg files uploaded to a php script arrive corrupt but not all the time i have a php script to which i upload jpeg images through an html form you can see the code here but i will attempt to present the relevant parts in this post the form is declared like soform actionadm addphotophp methodpost enctypemultipartformdata namemyformthe max file size form field is set to 5mbinput typehidden namemax file size value5242880the images i want to upload are about 3mb in sizeonce it is uploaded i turn the image file into a gd jpegfilename filesfiletmp namemyimage imagecreatefromjpegfilenamesometimes the upload works fine and sometimes imagecreatefromjpeg emits warnings about the jpeg being corrupt for example line breaks added for readabilitywarning imagecreatefromjpeg functionimagecreatefromjpeg gdjpeg libjpeg recoverable error corrupt jpeg data 47 extraneous bytes before marker 0xd9 in pathadm addphotophp on line 97warning imagecreatefromjpeg functionimagecreatefromjpeg tmpphpwlss9x is not a valid jpeg file in pathadm addphotophp on line 97the thing is this does not happen reliably that is if i try the same image several times in a row sometimes it will upload successfully and sometimes there will be errors and within the attempts that result in errors the specifics of the error message will vary too with the particular photo that produced the above messages the number of extraneous bytes is sometimes 47 sometimes 20 occasionally 68what might be causing the files to arrive corrupt on some attempts but not othersps i know that there is an ini setting that tells gd to try hard to work with corrupt jpegs but that is not the point i want to know why the result of the upload is inconsistentpps here are the values of some possiblyrelevant php ini settingsmemory limit 128mpost max size 8mfile uploads onmax file uploads 20upload max filesize 128mupload tmp dir no valueupdate i added code to echo out the size and md5 checksum of the file once it was uploaded the size is always the correct filesize the size of my local copy of the file the md5 however varies between attempts when the md5 is correct matches the md5 of my local copy there is no error message when there is an error message the md5 is always different from expected also this is just a perceived difference but errors seemed to be occurring more frequently last night than this morning only a minority of transfers this morning resulted in an errorhere are some bad uploads curiously there were a couple of uploads that gave an md5 checksum different to that expected but did not produce errors correct md5 f7b9587f39c7332e62a08adf34cefbd0 38 extraneous bytes 2a28c46079071d9d2e2fd49865b35d59 ce1c69f798953b201dcc35f85f3b29b4 b013a0428a71adff674a46e92372d46b 71 extraneous bytes a271928f3559b6deaa19804704b5bcb3 92 extraneous bytes cab2a10ad8535addaca3b19bcb607a30 premature end of data segment 4514d39db1d94ab691d6da26c0832cdb no error 83b2e3624ddcfdeb3efc10be81631916 07d0a97b21d423fdeb4c6f88d76f8cd3update in response to andre and pekka here are links to two versions of the same picture this one is the original copy of the image as stored on my machine i uploaded it the way i usually upload files to my webhosting ie i used an ftp client this one is the same image uploaded using my script but with a line added to move it to that location using move uploaded file the error message on that upload was corrupt jpeg data 30 extraneous bytes you will notice that the bottom part of the image appears incorrect i apologise for the large size of the images but i can only use examples of the type of images that are giving me problemsi should make it clear that this is a different image to the one that i used for the above md5 checksums i did not think to use the same imageupdate using the two images i linked above i found the differences between the two files there are two sequences of 32 bytes that are different in one image from the other the files are otherwise identicalnb the first character is numbered as character 1 not character 0nb 2116624 and 2493456 are both 16 modulo 32 the difference between them is 368 1024character 2116624 through line 2116655 32 characters original image 3c bc 20 19 eb 93 cd 34 db 93 68 7c 8d 5e 37 d4 d3 84 91 70 7e 7c 82 3e e9 e8 3d eb 2e ff 00 ce bad image 89 c9 54 a6 e5 3d f4 fc 8e 7f 68 d5 47 14 41 f6 55 11 7d a6 55 24 a8 e0 f7 a8 a4 43 06 18 c2 c1character 2493456 through character 2493487 32 characters original image 3d a4 61 37 19 75 63 2e 51 62 ca 07 e0 9e 49 35 5d 65 8d 22 01 7f 5e b4 a7 19 3a 7a ef 72 1c e3 bad image 4f 99 26 39 6a db d9 cd 3e 5b ec 63 46 3c b4 ef 2d b6 30 35 0f 12 a1 b6 9a 11 68 1a 69 07 0c 49,['php'] +120390,cannot import or create new project from samples or downloads on androideclipse basically i need help importing downloaded source or creating a project from sample source programs i am looking for step by step instructions for both if anyone can point me there or post the stepsi am very new to androideclipse i have the environments installed and have successfully written a very minor app that works on the emulator and my real droid x i cannot however get any of the android samples into a project without errors i have tried importing creating from existing source and etcetera and it is all a mess with errors everywherei have however successfully created a new empty project then brought the components into the project one at a time typing or pasting in code for every file i would hover over and import android and other components as needed the wiktionarysimple for example ran with only a couple of changes and several warnings that i left alone i had to add formattedfalse in the statements belowstring nametemplate user agent formattedfalsess linux androidstringstring nametemplate wotd title formattedfalsewiktionaryword of the days sstringbut there has to be an easier way to import i have done the intuitive and i have followed instructions that i have found but to no avail can anyone give me a complete list as to how to import or create a project from existing source or from source i have downloaded from the web,['android'] +120393,should i write my app with sencha touch or native with the recent updates to sencha touch it is looking more and more like a native app for iphone and even ipad there are still many differences and the documentation is a little lacking at the moment my question is given that i am already fully capable of creating native app in objective c should i switch to sencha touch and phonegap or start integrating those tools what are the pros and conseditthanks for the insightful points one of my partners wrote up their opinion over the weekend with some ideas that have not been mentioned here web vs native how should you write your app,"['objective-c', 'ios']" +120398,how to get the position of a draggable object i am trying to get the x and y of the draggable object using jquerythe scenario is i am dragging and dropping an object onto another object and want to get the position of the dragdrop objectedit now i can get the position of the object but i need morehere is what i have triedscript function draggabledraggable drag function var offset thisoffset var xpos offsetleft var ypos offsettop thistextx xpos y ypos droppabledroppable drop functionevent ui this addclassuistatehighlight findp htmldropped scriptnow i can get the position of the draggable object but i need it to be resizable and in addition to getting xy of the draggable i also need the size of it any help would be greatthanks,['jquery'] +120403,what is an effective method of traversing a 2d array vertically to programatically find an empty set first off this is not homework i am trying to create a wordsearch game from scratch and have hit a barrier i need some guidance oni am using a 2d array of chars to for the grid of a wordsearch i am quite comfortable with placing words in these arrays horizontally but i am really stuck for ideas on how to do this verticallythis is what i have so far you should just be able to copypaste it and run itimport javautilarraylistimport javautillistpublic class wordgame private static liststring words new arrayliststring private static int longestwordlength 0 private static int padsize 4 private static char grid null public static void mainstring args initialisewords workoutlongestword setupgrid printit private static void printit for int i 0 i gridlength i for int j 0 j gridlength j systemoutprintgridij systemoutprintn private static void setupgrid grid new charlongestwordlength padsizelongestwordlength padsize for int i 0 i gridlength i string w i wordssize wordsgeti for int j 0 j gridlength j gridij j wlength wcharatj private static void workoutlongestword for string word words if wordlength longestwordlength longestwordlength wordlength private static void initialisewords wordsaddmonkey wordsaddcow wordsaddelephant wordsaddkangaroo which prints out something like monkeycowelephantkangarooi need to randomly pad them out on the leftright hand side but i can do that myselfquestion what is an effective way of attempting to place words vertically into a 2d array like the above my initial thought was to count downwards for the required word length breaking if anything other than a is found and to keep doing this until i can find a space for the word however this does not get pretty once i take into account word overlappingany pointers,['java'] +120413,is it possible to delete all the session variables except a few is it possible to delete all the session variables except a fewi am building a website using php mysql,"['php', 'jquery']" +120419,django change default value for an extended model class i posted a similar question a while earlier but this one is different i have a model structure of related classes likeclass questionmodelsmodel ques type modelssmallintegerfielddefaulttype1 choices choice typesclass mathquestionquestion need to change default value of ques type here ex ques type modelssmallintegerfielddefaulttype2 choices choice typesi want to change the default value of ques type in the derived class how should i accomplish this,['python'] +120420,how does the blue brain project and neuron software work this question is related to 873448from wikipediathe blue brain project is an attempt to create a synthetic brain by reverseengineering the mammalian brain down to the molecular level using a blue gene supercomputer running michael hiness neuron software the simulation does not consist simply of an artificial neural network but involves a biologically realistic model of neuronsif we build it correctly it should speak and have an intelligence and behave very much as a human doesmy question is how the software works internally if it involves a biologically realistic model of neurons how is that different from a neural network and why cannot neural networks simulate a biological brain well while this project would be able to and how is neuron software used in the simulation lastly i apologize if this question does not belong here maybe the biostar stackexchance would be a better place to ask,['c'] +120426,find all list permutations of a string in python i have a string of letters that i would like to split into all possible combinations the order of letters must be remain fixed so thats monkeybecomescombinations m onkey mo nkey m o nkey etcany ideas,['python'] +120429,how can i use a dynamic settingsblah instead of appsettingsblah i get how to use dynamic in c 40 however i am not sure how to take something and make it dynamicable my technical termfor example instead of configurationmanagerappsettingsblah how can i make a wrapper of sorts that will let me just use it like a dynamic settingsblah,['c#'] +120436,python converting gif frames to png i am very new to python trying to use it to split the frames of a gif into png images using this gif from pil import imageim imageopenfighterfrontgiftransparency iminfotransparency imsavetest1png transparencytransparencyimseekimtell1transparency iminfotransparency imsavetest2png transparencytransparency first frame comes out perfect second frame test2png comes out black but in the right shape ie is this specific to the image i am working with or am i doing something wrongthanks,['python'] +120446,concatenate a varchar and int i need to concatenate a varchar and int in tsql,['sql'] +120449,what are the differences between linearlayout relativelayout and absolutelayout i am confused about the difference between linearlayout relativelayout and absolutelayout could someone please tell me the exact differences between them,['android'] +120451,change the uitextview text direction my language is not supported by ios by default so unicode is not an option so i am using a embedded true type font on a uitextviewit works for the most part but my issue is like arabic and hebrew my language is written from right to left so i need to change the direction of the text not text alignment i did some searches they all talk about nslocale and stuff but can it be changed in code if i can change it to something like arabichebrew it would work i guess but it should be done in code because i dont want change the language of the phoneso what really are my options for text input any help would be appreciatedthanks,"['ios', 'iphone']" +120499,how do i generate a url outside of a controller in aspnet mvc how do i generate a url pointing to a controller action from a helper method outside of the controller,['c#'] +120508,java generate create table code from an existing table is there a way to generate the create table code from an existing table in a derby database or a simple way to gather the necessary table information,"['java', 'sql']" +120513,jquery droppable and scrollable divs i have a little problem with jquery uis droppable component but i am not quite sure whether i have that problem because of my code or because of a bug in the componenti have a div with a fixed width and height the overflowx for that div is set to hidden overflowy is set to autowithin that div i have some more divs so many of them that the outer div starts scrolling each of the inner divs is a droppable accepting a draggable which is outside the wrapper divif i drag drop the draggable item somewhere within the wrapper everything works fine the problem is that the drop event gets even triggered if i drop the element shortly below the wrapper divi am not really good at explaining the problem therefore here is some code which reproduces the problemsimply drag and drop the drag me container below the div with the scrollbar unexpectedly you will see the alert droppednow something interesting if you scroll down to item test28 and now you drag and drop the draggable below the wrapper the drop event would not be triggered it looks like the hidden elements are still accessible when you drop something on themso is this a bug or do i need to write my code differently to make it work or both,['jquery'] +120521,overflow in bit fields can i trust that the c compiler does modulo 2n each time i access a bit fieldor is there any compileroptimisation where a code like the one below would not print out overflowstruct uint8 t foo2 ggfoo 3gfooifgfoo 0 printfoverflownthanks in advance florian,['c'] +120524,html5 geolocation implementation i have a list of areas and lattitudelongitude which i am asking the user to select their location when they hit my site i would like to have their location prefilled using html5s geolocation if possible but i am not exactly sure the best way to do that there seems to be a lack of tutorials on the web at least from what i can find has anyone done this do you know of a good tutorialresourceupdateif i have coordinates of bunch of cities how can i use javascript to determine the closest location,['jquery'] +120548,gpsgis calculations algorithm to predict future position based on movementmph looking for resources or algorithm to calculate the following in a navigation appif my current gps position is 00 and i am heading 32 degrees at 15 miles per hour how can i calculate what my position will be in 10 secondsie gpscoordinate predictedcoord gpscoordinatefromlatlong0 0addbymovement32 15 timespanfromseconds10edit current code based on answer belowpublic gpscoordinate addmovementmilesperhourdouble heading double speedmph timespan duration double x speedmph systemmathsinheading pi 180 durationtotalseconds 3600 double y speedmph systemmathcosheading pi 180 durationtotalseconds 3600 double newlat thislatitude 180 pi y earthradius double newlong thislongitude 180 pi systemmathsinthislatitude pi 180 x earthradius return gpscoordinatefromlatlongnewlat newlong,['c#'] +120556,aspnet mvc 3 redirect to another action i want to redirect the index action of the home controller to another controllers action and nothing else my code is thus public void index all we want to do is redirect to the class selection page redirecttoactionselectclasses registration right now this just loads a 0 kb blank page and does nothing i have a feeling it has something to do with that void return type but i do not know what else to change it to whats the issue here,['c#'] +120580,comparingclustering trajectories gps data of xy points and mining the data i have got 2 questions on analyzing a gps dataset1 extracting trajectories i have a huge database of recorded gps coordinates of the form latitude longitude datetime according to datetime values of consecutive records i am trying to extract all trajectoriespaths followed by the person for instance say from time m the xy pairs are continuously changing up until time n after n the change in xy pairs decrease at which point i conclude that the path taken from time m to n can be called a trajectory is that a decent approach to follow when extracting trajectories are there any wellknown approachesmethodsalgorithms you can suggest are there any data structures or formats you would like to suggest me to maintain those points in an efficient manner perhaps for each trajectory figuring out the velocity and acceleration would be useful2 mining the trajectories once i have all the trajectories followedpaths taken how can i comparecluster them i would like to know if the start or end points are similar then how do the intermediate paths compare how do i compare the 2 pathsroutes and conclude if they are similar or not furthermore how do i cluster similar paths togetheri would highly appreciate it if you can point me to a research or something similar on this matterthe development will be in python but all kinds of library suggestions are welcomethanks in advance,['python'] +120584,how do i find the largest value in a column in postgres sql for examplename weightjon 100 jane 120 joe 130how do i only return the name of the person with the largest weight,['sql'] +120588,trying to find the second largest value in a column postgres sql i am trying to find the second largest value in a column and only the second largest valueselect aname maxaword as wordfrom apple awhere aword select maxaword from apple agroup by anamefor some reason what i have now returns the second largest value and all the lower values also but fortunately avoids the largest valueis there a way to fix this,['sql'] +120593,porting autodesk animator pro to be cross platform a previous relevant question from me is here reverse engineering old paint programsi have set up my base of operations here wiki coming soonokay so now i have a 30 line legacy msdos codebase it is sort of a be careful what you wish for situation i am not an experienced c programmer i am not entirely inexperienced either but for all intents and purposes i am a noob to the language and in particular the intricacies of its libraries i am especially ignorant of the vagaries of the differences between c programs written specifically for msdos and programs that are cross platform however i have been studying this code base for over a year now and this is what i know about animator procompilers and tools used watcom c compilertcmake make program from turbo c386asm a specialised assembler for the phar lap dos extenderand of course the phar lap dos extender itself a selection of obscure dos utilitiesmuch of the compilation seems to be driven by batch files though i have obtained copies of all these tools i have not yet succeeded at compiling it though i have compiled its older brother autodesk animator originalit is got a plugin system that replicates dll before dlls were available based on rex the plugin system handlesvideo drivers with a plethora of included vesa driversinput drivers including wacom tablets and keyboardsdrawing toolsinks like photoshops filters or blending modesscripting addons essentially compiled scriptsfile formatsit is got its own script interpreter named poco based on the c language the scripting language has enough power to do virtually all the things the plugin system can do just slowergiven this information this is my development plan please criticise this the source code is available in the link above so you can easily if you are so inclined assess the situation yourselfcompile with its original toolsswitch to using djgpp and make the necessary changes to get it to compile with that plus the original assemblerinclude the allegrocc game library and switch over as much functionality to that library as possible perhaps by simply writing new video and input drivers that use the allegro api i am thinking allegro rather than sdl because there is a dos version of allegro and fascinatingly one of its core functions is the ability to play animator pros native format flichopefully after 3 i will have eliminated most or all of the assembler in the project i say hopefully because it is in an obscure dialect that does not assemble in any modern free assembler without significant modification i have tried them all whatever is left gets converted to assemble in nasm or to c code if i can define the assemblers actual functionswitch the dos extender from phar lap to hx dos which promises to replicate as much of the win32 api as possible then make all the necessary code changes for that to workswitch to the win32 version of allegrocc assuming that the win32 version can run on top of hxdos make any further necessary changesmodify the plugin system to use some kind of standard cross platform plugin library what this would be i have no idea maybe you can offer some suggestions i talked to the developer who originally wrote the plugin system and he said some of the things it does are not possible on modern oss because of segmentation restrictions i am not sure what this means but i am guessing it means all the plugins will need to be rewritten almost from scratchmagically i got all the above done and we can try and make it run in windows osx and linux whilst dealing with other cross platform niggles like long file names and things i have not thought ofanyone got a problem with any of this is allegro a good choice if not why what would you do about this plugin system what would you do different is this whole thing foolish and should i just rewrite it from scratch using the original as inpiration it would apparently take the original developer about a month to do that one thing i have not covered above is the textfont system not sure what to do about that but animator pro has its own custom font format but also is able to use postscript type 1 fonts and some other formats,['c'] +120610,shuffle 2 php arrays in the same way i have this for examplearrayone0 0arrayone1 1arrayone2 2arrayone3 3arraytwo0 00arraytwo1 11arraytwo2 22arraytwo3 33how can i shuffle them both to get something likearrayone0 2arrayone1 1arrayone2 3arrayone3 0arraytwo0 22arraytwo1 11arraytwo2 33arraytwo3 00or any other random order but having the same random factor in bothfor example i want that arrayone0 and arraytwo0 get shuffled to get arrayonex and arraytwox x being a random key but the same on both arrays,['php'] +120612,percent encoding javascript is there a javascript function that takes a string and converts it into another string that is percentencoded that way something like this guy turns into this20guythanks,"['javascript', 'jquery']" +120620,where can i find a free easy to implement spellcheck component for net this may be a tall order but i would like to find a spellchecker component that is easy to implement i only need to spellcheck one textbox i have looked around and cannot seem to find anything that does not cost a fortune or is not overly complicated to implement i did find a wrapper for nhunspell but could not get it to actually thisplay the spellcheck box for whatever reasoncomponentones spellcheck control is absolutely excellent but of course costs an absolute fortune since you cannot buy just that component you have to buy the whole suite all the other ones i have found seem to be the same wayi liked the componentone version the best because all you had to do way reference it initialize and when you called it you simply told it which control to check it was lovelysuggestions,"['c#', '.net']" +120627,move list element to the end in stl i have already the list pointer of cdrawobjectstdlistcdrawobject elementshow i can move some element to the end of listi see stl algorithms reference but i do not find this operations how i can do it,['c++'] +120628,what packages does 1 java and 2 groovy automatically import having programmed in groovy quite a bit i know classes in certain packages are automatically imported whats the scoop for 1 java and 2 groovyis there a definitive list of ones you do not need to specify an import for for each of these languages,['java'] +120632,rails 3 activerecord the best way to mass update a single field for all the records that meet a condition in rails 3 using activerecord is there a singlequery way to set the hidden field to true for all records that meet a condition say for example condition phonenum some phone number if a single query cannot do it what is the optimal approach,['ruby-on-rails'] +120673,design time error visualstate occurs in at least two namespaces i am getting the following errorambiguous type reference a type named visualstate occurs in at least two namespaces systemwindows and systemwindows consider adjusting the assembly xmlnsdefinition attributesi am not referencing any of these assembly name spaces directly i am doing the followingresourcedictionaryxmlnsxmlnsx the application compiles fine just throwing these errors at design time this happens to a few other classes that are a part of the vsm library,"['c#', '.net']" +120689,how to check if location services is on or not how can i check if the user has turned off location services so that i can prompt himher to turn it on in order to use my appthank you,['iphone'] +120695,how to set the android property layout alignparentbottom to a button dynamically i have a dynamic layout and i have a button how can i set the property layout alignparentbottom to that button so that it would appear in the bottom of my relative layoutor do you know another way,['android'] +120698,how to zip a whole folder using php i have found here at stackoveflow some codes on how to zip a specific file but how about a specific folderfolder indexhtml picturejpg importanttxtinside in my folder there are files after zipping the my folder i also want to delete the whole content of the folder except importanttxtfound this here at stacki need your help thanks,['php'] +120700,javascript file load order and dependency management just wondering about thisi have several separate javascript files that all contain code based on the module pattern a few of the modules have some of the others as dependencies if i know that none of the code would be called on the html until the page is loaded does the order in which the files load still importantis the fact that the module code sits inside an immediate function enough to trigger the requirement that the other modules be loaded alreadyi am prepared to look into the requirejs library if need be but just wanted to know if what i am going is ok first,['javascript'] +120713,whats the proper way to handle timeouts for active record with a connection pool i have tracked down a strange error undefined method run callbacks for nilnilclass and been able to reproduce it with this sample codebasically the problem is active record is getting a timeout the default is 5s but throwing an undefined method exception which seems wrong to me but anyway whats the right way to handle this in my real code i have a bunch of threads that are busy doing real work but occasionally i hit this error so imagine the puts is the real code i want the existing threads to keep working away when this happensthreads 10times do n threads threadnew activerecordbaseconnection poolwith connection do conn puts n conn res connexecuteselect sleep6 async true end end block and wait for all threads to finishthreadseach t puts joined tjoin rescue exception e puts endif i run this code as is i get the exception if i reduce the sleep to 4s i do not heres the output with the 6s sleepjoined0 activerecordconnectionadaptersmysql2adapter0xb73c63801 activerecordconnectionadaptersmysql2adapter0xb73c55482 activerecordconnectionadaptersmysql2adapter0xb73c4fe43 activerecordconnectionadaptersmysql2adapter0xb73c4a804 activerecordconnectionadaptersmysql2adapter0xb73c451cjoinedjoinedjoinedjoinedjoinedundefined method run callbacks for nilnilclassusrlibrubygems18gemsactiverecord2libactive recordconnection adaptersabstractconnection poolrb212in checkinsqltstrb31in joinsqltstrb31sqltstrb31in eachsqltstrb31,"['mysql', 'ruby-on-rails']" +120737,how to delete an item in a list if it exists i am getting new tag from a form text field with selfresponsegetnew tag and selected tags from checkbox fields with selfresponseget allselected tagsi combine them like thistag string new tagnew tag list f1striplisttag stringsplit selected tagsf1striplist is a function that strips white spaces inside the strings in the listbut in the case that tag list is empty no new tags are entered but there are some selected tags new tag list contains an empty string for example from logginginfonew tagselected tagsuhello ucool uglamnew tag listu uhello ucool uglamhow do i get rid of the empty stringif there is an empty string in the list s u uhello ucool uglam i sindex del si suhello ucool uglambut if there is no empty string s uhello ucool uglam if sindex i sindex del si else print new tag list has no empty stringbut this givestraceback most recent call last file pyshell30 line 1 in module if new tag listindex valueerror listindexx x not in listwhy does this happen and how do i work around it,['python'] +120741,set todays date as default date in jquery ui datepicker i just want todays date to be the default value in the input that is using jquery uis datepickerinput idmydate typetext i tried the below code but it did not workvar currentdate new date mydatedatepickersetdatecurrentdate,['jquery'] +120746,how to move files in qt is there a crossplatform function in qt that is equivalent to the movefile function in windows and the mv command in linux,['c++'] +120757,create new variables from array keys in php suppose i have an array like thisfoo arrayfirst 1st second 2nd third 3rdhow can i pick the keys out of the array and make them their own variablesfor example the array foo would becomefirst 1stsecond 2ndthird 3rdi ask this because i am creating an mvc framework to help with my oop and i would like the user to pass a variable to the view loading function which will allow the user to use variables in the template without having to know what the array was calledfor examplearray arraytitle my blog thisloadviewviewphp arrayviewphpecho titleoutputmy blog,['php'] +120766,ioscoreaudio a strange cadebugprintfh no such file or directory error there are bunch of helper filess in ipublicutility folder of several audio related apple sample codes such as auriotouchi can build these samples fine but whenever i create a new project for testing and include the files from ipublicutility folder i getcadebugprintfh no such file or directory error in cadebugmacrosh filei made the settings of my test project to coincide with apple samples but this error isnot going away any suggestionsdk ios 42 imac osx 1066thanks allsy,['ios'] +120771,extract 2nd level domain from domain python i have a list of domains egsitecouksitecomsitemeuksitejpncomsiteorguksiteitalso the domain names can contain 3rd and 4th level domains egtestexamplesiteorguktest2sitecomi need to try and extract the 2nd level domain in all these cases being siteany ideas,"['javascript', 'jquery', 'python', 'html']" +120773,two inner joins mysql how would i preform two inner joins in one queryie three tablesinvoiceaddressclientinvoice has a column which references an id in clients it also has a column which references an address i need to get both the clients name from the matched table and the address from the matched table how would i inner join both tablesi will add a few detailsinvoice has rows addressreferences address id clientreferences client id id and notesclient has rows first name last nameaddress has rows street name and cityi need to pull up,"['sql', 'mysql']" +120781,where does easy install install things i want to install sphinx and the website says to useeasy install u sphinxwhat will happen when i install this command will i get the source alsowhere will it install,['python'] +120801,core motion in the background will core motion framework work while the app is in the background,"['iphone', 'ios']" +120809,c global object i wanna create a global object in cpp program how do i do thatis this rightin global objhinclude classhclass objin maincppextern class obj,['c++'] +120828,how can i set my cygwin path to find javac i have a windows 7 system on which i have installed the latest java compiler i also have the latest cygwin i want to use the java compiler from cygwins shell i edited the path variable in cygwin as followsexport pathpathcygdrivecprogram filesjavajdk160 23bini can see the javac binary in the above directory however when i try to compile my java file i getjavac command not foundam i doing something wrong in setting the path variable like this do i have to do something else i am new to java and not very familiar with cygwin,['java'] +120846,why is mvc design pattern used extensively for website development i am developing my knowledge of oop design patterns and as my main focus is website development and web app development i have tried to find examples of design patterns in these fields but seem to come across web frameworks mainly any other examples would be appreciated it seems to me that the majority all of php based frameworks appear to use the mvc design pattern as this is the most widely used would it be right to assume that it is the best design pattern for this type of development or is it a reflection of a shallower learning curve as opposed to other design patternsi have also noticed that the codeigniter framework uses both a singleton pattern and an mvc pattern is this kind of hybrid design pattern common and is it effective or is was it used in codeigniter for a specific reason,['php'] +120854,html5 placeholder css padding i have seen this post already and tried everything i could to change the padding for my placeholder but alas it seems it just does not want to cooperateanyway here is the code for the css edit this is the generated css from sasearch margintop 1px thisplay inline float left marginleft 10px marginright 10px width 220pxsearch form position relativesearch input padding 0 10px 0 29px color 5 border none background urlimagesbg searchbarpng1296191141 norepeat width 180px height 29px overflow hiddensearch inputhover color 00ccff backgroundposition 0px 32pxand heres the simple htmldiv idsearch form input typetext value placeholdersearch nameq autocompleteoff class form div idjquerylivesearch stylethisplay block position absolute top 15px width 219px ul idsearchresults classdropdown ul divdivpretty simple the placeholder is off for some reason but when you try to type in the input field the text is the aligned it seems that you can only change the colorfor webkit of the placeholder but if i try to edit the padding of the containing input it wrecks the design of the input pulls out hairhere are screenies of the placeholder and the input field with text inputeditfor now i have resorted to this jquery pluginit works right out of the box and it fixes my chromes problem i would still like to uncover what the problem is if it has something to do with my chrome or somethingi am pretty sure it is not the styles since john catterfeld reproduced it with no problems so i am hoping someone out there could still point me to the right direction as to why this is happening to memy clients chrome as well so this is probably native to chromeosx if john is using windows,['css'] +120855,how to read one stream into another fileinputstream in new fileinputstreammyfilebytearrayoutputstream out new bytearrayoutputstreamquestion how can i read everything from in into out in a way which is not a handcrafted loop with my own byte buffer,['java'] +120858,how to serialize an object of androidgraphicspath i am trying to store objects of androidgraphicspath in internal device memory does anyone know how to serialize a androidgraphicspath object and also is there any other way of storing a path object thanks,['android'] +120885,cross platform and language plugin system i am looking for a good cross platform and cross language plugin system in ci am currently using qt as a frameworki need the plugins to be cross platform and to be able to be created in different scripting languages python ruby etc and java anyone here knows a good system for thatthxbl00dshooter,['c++'] +120887,androidhow to add support the javascript alert box in webviewclient hi i implement the many things using the webviewclient like onunhandledkeyeventshouldoverrideurlloading and moreif want to add the support for alertbox then need to switch to webchromeclient then i can not do other thingsany one know how mix the both future i have check the code for javasript alert box at thank you,['android'] +120892,loaders in android honeycomb i am trying to figure out how to use loaders in android 30 but cannot seem to get it to work the docs only describe using cursorloader but i am using asynctaskloaderfrom the docs it seems that you should only need to implement asynctaskloaderloadinbackground but it never gets called after getloadermanagerinitloader and then creating the loader in the callbacki can see debug messages saying created new loader loaderinfo4040a828 0 articledataloader4036b350 so it seems like it is created successfullyis it possible that loaders are currently broken in the sdk or is there some method you need to call after creating the loader they have not done that in the cursorloader exampleedit seems like calling forceload on the loader returned from initloader starts the loading at least but this means you cannot handle rotations correctly,['android'] +120898,when to use static member function possible duplicateswhere would you use a friend function vs a static functionc static member functions when is it appropriate to use a static member function in c please give me a real world example,['c++'] +120918,how to make a mac osx cocoa application fullscreen i have been trying to make my mac application enter fullscreen now for a while but cannot get it to work according to the apple developer center i should use enterfullscreenmodewithoptions which gives me method enterfullscreenmode not foundeverywhere i google there seems to be people having issues with making their app fullscreen so what is the way to make it workeditof course enterfullscreenmode is for the nsview and i used it on a nswindow it is not the view i want to have fullscreen but the window i cannot find any function for the nswindow though,['objective-c'] +120932,determining if a given python module is a builtin module i am doing some parsing and introspection of various modules but i do not want to parse builtin modules now there is no special type for builtin modules like there is a typesbuiltinfunctiontype so how do i do this import cornedbeef cornedbeefmodule cornedbeef from meatishcornedbeefpyc cornedbeef file meatishcornedbeefpyc del cornedbeef file cornedbeefmodule cornedbeef builtinaccording to python a module is apparently builtin if it does not have a file attribute does this mean that hasattrsomemodule file is the way to check if a module is built in surely it is not exactly common to del somemodule file but is there a more solid way to determine if a module is builtin,['python'] +120940,ruby 192 and rails 3 cannot open rails console gkaykckmain myapplication rails consoleusrlocallibruby191irbcompletionrb9in require no such file to load readline loaderror from usrlocallibruby191irbcompletionrb9in top required from usrlocallibrubygems191gemsrailties303librailscommandsconsolerb3in require from usrlocallibrubygems191gemsrailties303librailscommandsconsolerb3in top required from usrlocallibrubygems191gemsrailties303librailscommandsrb20in require from usrlocallibrubygems191gemsrailties303librailscommandsrb20in top required from scriptrails6in require from scriptrails6in maini have installed rails 3 on ruby 192p136 which is ok i guess but i cannot start rails console and it gives me the error i copied the apps worked great with ruby 187 and i never saw an error like thisany ideas what it could be,"['ruby-on-rails', 'ruby']" +120957,android spinner onitemselected setonitemselectedlistener not triggering this is driving me nuts since it is something i have done before but cannot figure out why it is not working nowi have got a menu button implemented in the usual way via a menuxml file and the onoptionsitemselected method with a switch in it that creates and thisplays a spinneri have added the setonitemselectedlistener but it never seems to trigger the spinner appears i pick an option or back out neither onitemselected or onnothingselected are calledhere is all the code between the case and return true of the menubuttonhandling switch statement topthis is a variable referring to the context of the activity works fine for all other toasts in the appstring widgetmodes mode 1 mode2arrayadapterstring widgetmodeadapter new arrayadapterstring this androidrlayoutsimple spinner item widgetmodeswidgetmodeadaptersetdropdownviewresourceandroidrlayoutsimple spinner dropdown itemspinner widgetmodespinner new spinnerthiswidgetmodespinnersetadapterwidgetmodeadapterwidgetmodespinnersetpromptchoose widget modewidgetmodespinnersetonitemselectedlistenernew onitemselectedlistener override public void onitemselectedadapterview parentview view selecteditemview int position long id toastmaketexttopthis derp toastlength longshow override public void onnothingselectedadapterview parentview toastmaketexttopthis herf toastlength longshow widgetmodespinnerperformclickany ideas i vaguely suspect that the fact i am creating the spinner programmatically is the problem,['android'] +120960,difference between regex az and azaz i am using a regex to program an input validator for a text box where i only want alphabetical characters i was wondering if az and azaz were equivalent or if there were differences performance wisei keep reading azaz on my searches and no mention of azi am using javas stringmatchesregex,['java'] +120962,how to make a call via pc by adb command on android i would like to make call via adb command on androids command linehow should i use adb command in order to make a call via pcplease provide source code,['android'] +120963,which framework to use codeigniter symfony or cakephp i would like to use one of the framework listed in the title but i am afraid to choose the wrong one since i do not know much about the framework i know php well but every time i create a site i spent too much time creating my own little framework matter of fact i was afraid of using a framework because of fear of being stuck with inflexible and slow framework that could not handle high traffic website which framework addresses my fear the most,['php'] +120965,c getters setters declaration possible duplicateswhy use getters and settersc 30 autoproperties useful or not is there a difference between defining properties the following way private with getter setterprivate string fnamepublic string name get return thisfname set thisfname value define as a propertypublic string name get setas far as i can tell it only looks like a stylistic preference am i missing something,['c#'] +120967,how to calculate the destination contentoffset of a uiscrollview in motion i am using a uiscrollview as the basis of a component that makes use of core animation when the user swipes the view i would like to position elements according to the destination resting position of the scroll view for this i need to calculate the destination contentoffset of the uiscrollview in the scrollviewwillbegindecelerating method or similarthe reason i need this is that i will be using the destination contentoffset to animate views nested within the scrollviews contentview to their final position i could of course set up an observer on the contentoffset or similar but this would result in chaotic animation as the nested views would then update their positions multiple times during deceleration i would like this to happen just the onceis there a simple way to do this,['iphone'] +120978,uitextfielddelegate vs uitextfield control events if i want to handle changes to a uitextfield such as the user typing in it it seems like this can be done either by assigning a delegate to that text field and then having the delegate implement shouldchangecharactersinrange or by adding a target to the textfield and handling the uicontroleventeditingchanged eventaside from the fact that with the delegate method you can return no and therefor stop the user from making the edit is there any difference between these 2 thingssame question for handling the beginning of editing or the ending of editing it could be done either with the appropriate delegate methods or with the appropriate events what is the textfield delegate actually for if the control events can do the necessary work,['ios'] +120996,c why is casting from void pointer to function pointer undefined possible duplicatewhy are function pointers and data pointers incompatible in cc in the man page for dlsym the following snippet has been provided double cosinedouble handle dlopenlibmso rtld lazy writing cosine double double dlsymhandle cos would seem more natural but the c99 standard leaves casting from void to a function pointer undefined the assignment used below is the posix12003 technical corrigendum 1 workaround see the rationale for the posix specification of dlsym void cosine dlsymhandle cosi looked up the relevant spec page but still cannot grasp the reason behind not allowing conversions from void pointers to function pointers are not void pointers supposed to be big enough to accomodate all types of pointers if so why leave this casting undefined,['c'] +121003,reload rails 3 initializer in development mode i am building a rails 3 app where users can select one of a number of templates and build a little website i am trying to initialize all of the available templates when the application starts that is essentially a file that let us me define them all then calls templateaddtemplate for each one of them which in turn stores them in templates and i can access them via templatefindnamethe problem is that in development mode the initializer i have making the calls to templateadd are getting loaded on the first request then wiped out on reload i have read about configto prepare but it is not working for me likely because i am requiring the templates like this template config at apptemplatestemplate nametemplate namerbpath fileexpand pathrailsroot apptemplatesdirfilejoinpath each do template name filebasenametemplate require filejoinpath name namerbendwhat can i do to either reload these files after reload or keep them from getting trashed at all also if you have a recommendation for a better way to handle this i am all ears i am still getting my footing with rails especially in regards to configuration stuffi am temporarily avoiding this problem by loading the data in the class save me from this ugly nonmodular nastiness,"['ruby-on-rails', 'ruby']" +121010,redirect cin to a string i want to have cin read input from a stringis there a way to have it do thissomething like thisconst char s 123 abcinreadfroms i want something like thisint icinicouti 123,['c++'] +121019,losing hover when animating with jquery without moving mouse i have this row of thumbnails that i am animating with jqueryeach of these thumbnails has a hover and active classthey work fine but when i animate the list the new thumbnail under the mousecursor does not apply the hover i have to move the mouse a little bit after each clickit is kinda difficult to exaplain i have made a fiddle here when you start clicking after thumb 3 without moving the mouse you see what i meanit works fine in firefox not safari chrome ie etcis there something i can do about thisfor reference here is my codestyle typetextcss container position relative overflow hidden width 140px height 460px float left marginright 100px background silver ul position absolute top 10 liststyle none margin 10px padding 0 li marginbottom 10px width 120px height 80px background gray list2 li a thisplay block width 120px height 80px outline none list2 li ahover background teal list2 li aactive background navy styledocumentreadyfunction var idx 2 0 list2 li a clickfunction list2 li aremoveclassactive thisaddclassactive var id list2 li aactivedataindex 2 idy mathmax0 id 90 thisparentparentanimate top idy px return false eachfunction thisdataindex idx 2 idx 2 div classcontainer ul idlist2 lia classactive hrefali lia hrefalilia hrefalilia hrefalilia hrefali lia hrefalilia hrefalilia hrefalilia hrefali lia hrefalilia hrefalilia hrefalilia hrefali lia hrefalilia hrefalilia hrefalilia hrefali lia hrefalilia hrefalilia hrefalilia hrefali lia hrefalilia hrefalilia hrefalilia hrefali uldiv,"['javascript', 'jquery']" +121023,a binding cannot be set on the source property of type binding a binding cannot be set on the source property of type binding a binding can only be set on a dependencyproperty of a dependencyobject treeview height400 width400 treeviewitem itemssourcebinding sourcebinding pathdata xpath converterstaticresource stringtoxmldataproviderconverterconverterparameterroot headerheader treeviewwhat is wrong with itemssourcebinding sourcebinding pathdatadata rootparm11parm1parm22parm2parm33parm3rooti try to use this code samplethe differ is that i want to bind the itemssource to data in datacontextthere is nothing wrong with the converteredittreeviewitem itemssourcebinding pathdata headerparameters fills treeview with one element the string so datacontext is correcteditthis code works better is there a generic way to read xml in threeview i do not know the structure of xml in all examples i have seen you have to declare sub nodes typestreeviewitem datacontextbinding pathdata converterstaticresource stringtoxmldataproviderconverter itemssourcebinding headerparameters,['c#'] +121024,selecting a json object with a colon in the key i am using a third party tool that posts a json response it works great but one of the keys i need to use has a colon in it and i have no idea how to select this object in javascriptfor example photo reg id 50 thumb id 51 original id 53 how do i select photooriginalid i get syntax errors when i leave the colon in and undefined when i try dropping the colon,['javascript'] +121035,mass assignment authorizer and nested attributes i am using dynamic attr accessible as per this articleit works fine but i have not found an elegant way to make it work with nested attributes heres some simplified codeclass company activerecordbase has many employees accepts nested attributes for employeesendclass employee activerecordbase belongs to company attr protected salary attr accessor accessible def mass assignment authorizer if accessible all activemodelmassassignmentsecurityblacklistnew else super accessible end end endlet us say i have an admin interface with a restful form for a company on this form i have fields for employees attributes including blank fields to create new employees i cannot find a way to call employeeaccessible in this context browsing through the activerecord source code it seems that this might be impossible in the remotest part of a very deep call stack nested associations just result in employeenew being called with the attributesi would thought about creating a special attribute that could be passed in through mass assignment if the attributes value were the right code the employee instance would set accessible to all but i do not think there is a way to guarantee that this attribute gets set before the protected attributesis there any way to make dynamic protected attributes work with nested attributes,['ruby-on-rails'] +121039,java keystore and password settings i have the following question on java keystores and keytool i assume that a keystore may have more than 1 certificates as i have tried via keytool i can create a keystore and to access this keystore i have to set a password also to access each certificate entry i have to set a password is it mandatory to have the same password for the keystore and the entries if not and i think that it is reasonable to assume so why is the following code char pwd new charsecretkeystore ks keystoregetinstancekeystoregetdefaulttypeksloadnew fileinputstreammypersonalkeystore pwdkmfinitks pwdfails here with exceptiongives me the following exceptionexception in thread main javasecurityunrecoverablekeyexception cannot recover key at sunsecurityproviderkeyprotectorrecoverunknown source at sunsecurityproviderjavakeystoreenginegetkeyunknown source at sunsecurityproviderjavakeystorejksenginegetkeyunknown source at javasecuritykeystoregetkeyunknown sourcesecret is the password to access the keystore mypersonalkeystore which i created via keytool there are 2 entries in it for certificates 1 dsa and 1 rsa each has a different password with keystore and each other now the code is correct because if i use a keystore with a single certificate entry having the same password as the keystore there is no exception and the program runs fineso what is the problem here i should not have different passwords i should not have many certificates or what,['java'] +121042,divide ints and round up in objectivec i have 2 ints how do i divide one by the other and then round up afterwards,['objective-c'] +121051,omniauth google openid webrickhttpstatusrequesturitoolarge i am using omniauth to allow users to log in with their google openid accounts when i try to log in in development mode with webrick i get a webrickhttpstatusrequesturitoolarge error when i deploy it to my rails host it works fineis there a different web server i should use instead of webrick,['ruby-on-rails'] +121063,return html or build html using javascript i am returning data about contacts to build a listthe basic html looks likerepeat20div classcontact a rel123firstname lastnamea div classinfo repeat5 div div classinfolabelagediv div classinfopiece56div div endrepeat divdivendrepeatthe repeat20 is not actual codethat block of code is repeated 20 timesmy question iswhat is more benificialcreate the markup server side return the actual htmlreturn json data with the information and build the list client sidefor the purpose of this thiscussion let us assume some constantsserver load is not an issue we are using a high performance serverthe returned data is for thisplay purposes only not to be manipulatedwe are not factoring in users without javascript enabledwe are not factoring in any browsers internet explorer 7,"['php', 'jquery', 'html']" +121086,location for session files in apachephp what is the default location of session files on an installation of apachephp on ubuntu 1010,['php'] +121087,how to pass variables to slot methods in qt i am making a little chat messenger program which needs a list of chat channels the user has joined to represent this list graphically i have made a list of qpushbuttons which all represent a different channel these buttons are made with the following method and that is where my problem kicks invoid messengeraddtoactivepanelsstdstring channel activepanelscontents thisfindchildqwidget qstringactivepanelscontents pushbutton new qpushbuttonactivepanelscontents pushbuttonsetobjectnamepushbutton pushbuttonsetgeometryqrect0 0 60 60 pushbuttonsettext pushbuttonsettooltipqstringchannelc str pushbuttonsetcheckabletrue pushbuttonsetcheckedfalse connectpushbutton signalclicked this slotswitchtabchannelactivepanelcontents is a qwidget that holds the listthe point is that each button should call the switchtabstring tabname method when clicked including the specific channels name as variable this implementation does not work though and i have not been able to find out how to properly do this,['c++'] +121102,app offlinehtm throwing http 500 errors on production box i have created an app offlinehtm file for an aspnet mvc2 application running on iis7 win2008 64bit and ensured that it is over 512 bytes it is 2kb right now on my dev box running visual studio 2010 it works like a charm but when i put it on the production box all i get is the generic http 500 error saying the page cannot be thisplayed because an internal server error has occurredwhats especially strange is that i do not get anything logged in the application event log nor does elmah pick anything up i have thisabled custom errors put formsauthentication location exceptions for the file ensured i am not referencing any other files images etc but nothing fixes iti have read every post on so and googled for hours and cannot figure this out any ideas what might be wrong i am pulling my hair out here,['asp.net'] +121103,rails production static files routing error when i run my app locally in testdev my views come up nicely and everything is happy when i try to navigate to those same erb files running on my remote serverlocal production server i get errors like the followingactioncontrollerroutingerror no route matches stylesheetsscaffoldcssi have seen similar questions here on so but none have been able to solve my problem the closest thing i have found to an answer is the first answer here rails 404 error for stylesheet or javascript filesas i understand it the best thing to do would be to configure my webserver to serve static files how do i do this locallyon herokuupdateas per raidfives suggestion i changed configserve static assets from false to true and this fixed my issue however i see that it says in productionrb that apache or nginx should already be serving static assets is it any less goodprofessional to serve static assets in this way and if so how would i achieve the desired results if i am using herokuupdate 2apparently heroku does this automatically i had an extra comma that was causing the mischief i was able to look in the extended heroku logs using the following tip to track down the trouble thanks so,['ruby-on-rails'] +121104,how can i work with gzip files which contain extra data i am writing a script which will work with data coming from instrumentation as gzip streams in about 90 of cases the gzip module works perfectly but some of the streams cause it to produce ioerror not a gzipped file if the gzip header is removed and the deflate stream fed directly to zlib i instead get error 3 while decompressing data incorrect header check after about half a day of banging my head against the wall i thiscovered that the streams which are having problems contain a seeminglyrandom number of extra bytes which are not part of the gzip data appended to the endit strikes me as odd that python cannot work with these files for two reasonsboth gzip and 7zip are able to open these padded files without issue gzip produces the message decompression ok trailing garbage ignored 7zip succeeds silentlyboth the gzip and python docs seem to indicate that this should work emphasis minegzips formattxtit must be possible to detect the end of the compressed data with any compression method regardless of the actual size of the compressed data in particular the decompressor must be able to detect and skip extra data appended to a valid compressed file on a recordoriented file system or when the compressed data can only be read from a device in multiples of a certain block sizepythons gzipgzipfilecalling a gzipfile objectas close method does not close fileobj since you might wish to append more material after the compressed data this also allows you to pass a stringio object opened for writing as fileobj and retrieve the resulting memory buffer using the stringio objectas getvalue methodpythons zlibdecompressunused dataa string which contains any bytes past the end of the compressed data that is this remains until the last byte that contains compression data is available if the whole string turned out to contain compressed data this is the empty stringthe only way to determine where a string of compressed data ends is by actually decompressing it this means that when compressed data is contained part of a larger file you can only find the end of it by reading data and feeding it followed by some nonempty string into a decompression objectas decompress method until the unused data attribute is no longer the empty stringhere are the four approaches i have tried these examples are python 31 but i have tested 25 and 27 and had the same problem approach 1 gzipopenwith gzipopenfilename as datafile data datafileread approach 2 gzipgzipfilewith openfilename rb as gzipfile with gzipgzipfilefileobjgzipfile as datafile data datafileread approach 3 zlibdecompresswith openfilename rb as gzipfile data zlibdecompressgzipfileread10 approach 4 zlibdecompressobjwith openfilename rb as gzipfile decompressor zlibdecompressobj data decompressordecompressgzipfileread10am i doing something wrongupdateokay while the problem with gzip seems to be a bug in the module my zlib problems are selfinflicted while digging into gzippy i realized what i was doing wrong a by default zlibdecompress et al expect zlibwrapped streams not bare deflate streams by passing in a negative value for wbits you can tell zlib to skip the zlib header and decrompress the raw stream both of these work approach 5 zlibdecompress with negative wbitswith openfilename rb as gzipfile data zlibdecompressgzipfileread10 zlibmax wbits approach 6 zlibdecompressobj with negative wbitswith openfilename rb as gzipfile decompressor zlibdecompressobjzlibmax wbits data decompressordecompressgzipfileread10,['python'] +121109,running multiple instances of rails server i am new to rails so please forgive me if this is obviousi am doing a lot of experimenting creating to applications testing features etc it got my first scaffolded app running great but i wanted to create a second app to test a different feature i backed up a folder level on my computer ran rails new taskmaster a test todo list app i ran the scaffolding for the task model fired up the server via rails server and attempted to load httplocalhost30 but i got a routing error saying it could not find the members route but members was from my first rails app i thought by firing off rails server in the taskmaster directory it would startup the server for that applicationhow do i tell the rails server which application to serve upupdatei just thiscovered that if iroll back to the fresh install of the first rails app before i created the member scaffoldfire up the rails server via rails server in the applications root directorycheck httplocalhost30it still attempts to go for the members route the one that no longer exists because i rolled back via giti am guessing this means something in my usrlocal area relating to my ruby and rails initial installs is mainatining this info my apps are setup in my documents folder in my home dir i thought that rails apps were essentially self contained apps inside the directory you just needed a working ruby install to get them going does the rails server sit inside each app directory or is the some overarching rails server that accommodates all apps,['ruby-on-rails'] +121111,css fontface with the arabic fonts i am trying to use an arabic external fontfontface fontfamily my src urlge ss tv boldotf formattruetypepcustomfont fontfamily my verdana tahomait is appearing like thisbut it should appear like,['css'] +121112,how do i write an extension method for a generic type with constraints on type parameters i am working with a task specific net plattform which is precompiled and not opensourcefor some tasks i need to extend this class but not by inheriting from it i simply want to add a methodat first i want to show you a dummycode existing classpublic class matrixt where t new public t values i want to extend this class in the following waypublic static class matrixextension public static t getcalcresulthis matrixt mat t result 0 return result i have got this syntax from many google links so no idea whether it is correct the compiler tells me no error but in the end it does not work in the end i want to call this function in the following waymatrixint m new matrixintint anumber mgetcalcresultso anyone got an idea thank you for your helpregards nem,"['c#', '.net']" +121117,android start in symbol keyboard mode but do not restrict to numbersonly input i want to specify that android should start the soft keyboard for a given edittext in the numericsymbols mode i know this can be done by setting the input type of the edittext to be numeric using edittextsetinputtype except that i do not want to restrict the input type for the edittext to numeric input only is there another way to tell android what keyboard it should open for a given edittext i want essentially a math class of numeric input accepting arbitrary mathematical expressions including 09,"['java', 'android']" +121129,why is not css visibility working i added a spoiler class in css to use for well spoilers text is normally invisible but appears when the mouse hovers over it to reveal the spoiler to whoever wants to read itspoiler visibilityhiddenspoilerhover visibilityvisibleshould be simple but for some reason this does not work the text remains invisible even when i point the mouse on it any idea what could be causing this,['css'] +121136,is there anyway to cache functionmethod in c i got bored with writing same to code again and again to cache the objects in data access layer is there anyway to cache c function results without much changes to functionsis there any framework supports this functionality at the moment can i archive the same by writing custom c function attributes if so drop me some points to start implementation,"['c#', '.net']" +121140,can the thread per request model be faster than nonblocking io i remember 2 or 3 years ago reading a couple articles where people claimed that modern threading libraries were getting so good that threadperrequest servers would not only be easier to write than nonblocking servers but that they would be faster too i believe this was even demonstrated in java with a jvm that mapped java threads to pthreads ie the java nio overhead was more than the contextswitching overheadbut now i see all the cutting edge servers use asynchronous libraries java nio epoll even nodejs does this mean that async won,['java'] +121164,ruby 19 no such file to load win32open3 i am running ruby 192 on windows and am trying to port code that worked in ruby 18 the code uses open4popen4 which previously worked fine with 192 i have done the followinginstalled popen4 via gem install popen4required popen4 via require popen4attempted to use popen4 like open4popen4cmd io inio outio er when i do i get the errorno such file to load win32open3if i try and install win32open3 gem install win32open3 i get the errorwin32open3 requires ruby version 190does anyone know how i get around this problem,['ruby'] +121191,cufon loaded asynchronously does not render in ie i am creating a site which uses cufon and is particularly heavy in terms of pageweight due to a large amount of javascript therefore i am trying to load in the script asynchronously with headjs like soheadjs function headjsjslibscufonyuijs function headjsjssharedstag bold 700fontjs function cufonreplaceh1 fontfamily stag bold so jquery is downloaded first the subsequent cufon lib file and cufon font are downloaded in sequence and then cufon is finally called to replace the h1 obviously this is a trimmed down example with fewer replacements but this still does not work when just attempting to replace the h1the problem is that only in internet explorer 678 the text is not replaced but i can see that cufon has definitely been called i can ascertain this because the tag has the class cufonactive cufonready added to it when i inspect the markup using the ie developer toolbar the cufoncufoncanvas tags are there inside the selected elements but are for want of a better word invisiblein ie9 the script behaves as intended similar to chrome and firefox i have tried adjusting the cufon drawing engine and have updated to the latest 109i version for good measure if i move the cufon calling statements to the document ready event instead of loading asynchronously it works but i am trying to optimize page load and my site will be using a number of cufon fonts as well as many other js plugins i have also tried using both labsjs and headjs to load the appropriate files asynchronously,['javascript'] +121221,output raw image from imagick image in php i am using imagick lib to do some modifications to original image then i would like to output it directly to browser without saving is there a way to do thati tried to use imagickwriteimagestdout empty output and phpstdout with error unable to write to fileany ideas,['php'] +121236,how to create a dbf file from scratch in c i am trying to write a dbf file from scratch in my program i want to create it add some columns and then add data to the columns x amount of times my program will not need to read it in again but other programs willi have looked around for a solution to this but all seem to assume an existing dbf file whereas i want to make a new onethe purpose of this is to make the dbf part of an esri shapefiledoes anyone know how to do this,"['c#', '.net']" +121252,how do i enlarge an eer diagram in mysql workbench i am working on a moderately complex schema in mysql workbench and the single page of the eer diagram is now full up does anyone know how to enlarge it to two or more pages,['mysql'] +121267,can i reuse httpwebrequest without thisconnecting from the server i am trying to debug a specific issue with my aspnet application the client runs the following codevoid uploadfile string serverurl string filepath httpwebrequest request httpwebrequesthttpwebrequest create serverurl credentialcache cache new credentialcache cacheadd new uri serverurl basic new networkcredential user pass requestcredentials cache requestmethod post requestcontenttype applicationoctetstream requesttimeout 60 requestkeepalive true using binaryreader reader new binaryreader fileopenread filepath requestcontentlength readerbasestreamlength using stream stream requestgetrequeststream byte buffer new byte1024 while true int bytesread readerread buffer 0 bufferlength if bytesread 0 break streamwrite buffer 0 bytesread httpwebresponse result httpwebresponserequestgetresponse handle result not relevant and write throws an exception with unable to write data to the transport connection an established connection was aborted by the software in your host machine text i used systemnet tracing and found that something goes wrong when i send the request with contentlength setspecifically if i omit everything that is inside using statement in the code above the server promptly replies with wauthenticate and then the client reposts the request with wauthenticate and everything goes fine except the file in not uploaded and the request fails much lateri would like to do the following send an request without data wait for wauthenticate then repeat it with wauthenticate and data so i tried to modify the code above first set all the parameters then call getresponse then do sending but when i try to set contentlength property an exception is thrown with this property cannot be set after writing has started textso httpwebrequest seems to be nonreusablehow do i reuse it for resending the request without closing the connection,"['c#', '.net', 'asp.net']" +121287,orghibernatehibernateexception hibernatecfgxml not found i am trying to use hibernate with spring 3 mvc but at the moment i get this exception thrown i think i need to define my hibernatecfgxml somewhere but not sure wherei basically followed this example here and in particularly saw this line of code there that suppose to magically find my hibernatecfg file using thisreturn new configurationconfigurebuildsessionfactoryi am guessing that is not correct i currently have my hibernatecfg file inside srccomjrhibernatebelow is my cfg filexml version10 encodingutf8doctype hibernateconfiguration publichibernatehibernate configuration dtd 30enhibernateconfiguration sessionfactory database connection settings property nameconnectiondriver classcommysqljdbcdriverproperty property nameconnectionurljdbcmysqllocalhost3306racingleagueproperty property nameconnectionusernameusernameproperty property nameconnectionpasswordpasswordproperty property namehibernateformat sqltrueproperty jdbc connection pool use the builtin property nameconnectionpool size1property sql dialect property namehibernatedialectorghibernatedialectmysqldialectproperty enable hibernates automatic session context management property namecurrent session context classthreadproperty thisable the secondlevel cache property namecacheprovider classorghibernatecachenocacheproviderproperty echo all executed sql to stdout property namehibernateshow sqltrueproperty drop and recreate the database schema on startup property namehibernatehbm2ddlautoupdateproperty property namehbm2ddlautoupdateproperty mapping resourcecomjrmodelhibernatemappingsuserhbmxml sessionfactoryhibernateconfigurationmy hibernate utils classpackage comjrutilsimport orghibernatesessionfactoryimport orghibernatecfgconfigurationpublic class hibernateutils private static final sessionfactory sessionfactory buildsessionfactory public static sessionfactory buildsessionfactory try create the sessionfactory from hibernatecfgxml return new configurationconfigurebuildsessionfactory catch throwable ex make sure you log the exception as it might be swallowed systemerrprintlninitial sessionfactory creation failed ex throw new exceptionininitializererrorex which gets called bu this abstract classpackage comjrdbimport orghibernatesessionfactoryimport orghibernateclassicsessionimport comjrutilshibernateutilspublic abstract class dbwrappert private static sessionfactory sessionfactory null private static session session public dbwrapper setsessionfactory private void setsessionfactory sessionfactory hibernateutilsbuildsessionfactory session sessionfactorygetcurrentsession public boolean addnewitemt dbitem try sessiongettransactionbegin sessionsavedbitem sessiongettransactioncommit catch exception e systemerrprintlnerror exception when adding new item to table e finally sessionclose sessionfactoryclose return false public abstract boolean removeitemstring uid public abstract boolean modifyitemstring uid t itemand here is the controller that originally does some hibernate stuffprivate logger logger loggergetloggerusercontrollerclass private userdb userdbrequestmappingvalue userregistersuccess method requestmethodpostpublic string submitregisterformvalid user user bindingresult result validate the data recieved from user loggerinfovalidate the data recieved from user if resulthaserrors loggerinfoform has resultgeterrorcount errors return accountcreateform else if everthings ok add user details to database loggerinfoif everthings ok add user details to database userdb new userdb userdbaddnewitemuser thisplay success and auto log the user to the system return accountmain cheers in advance i also have all my table hibvernate xml mappings in the same location as my hibernatecfgxml file,['java'] +121291,fast string suffix checking in c net 40 what is the fastest method of checking string suffixes in ci need to check each string in a large list anywhere from 50 to 10 items for a particular term the term is guaranteed never to be embedded within the string in other words if the string contains the term it will be at the end of the string the string is also guaranteed to be longer than the suffix cultural information is not importantthese are how different methods performed against 10 strings half of them have the suffix 1 substring comparison 1360ms 2 stringcontains 2233ms 3 compareinfoissuffix 2460ms 4 stringendswith 2908ms 5 stringlastindexof 3068msthese are average times edit forgot to mention that the strings also get put into separate lists but this is not important it does add to the running time thoughon my system substring comparison extracting the end of the string using the stringsubstring method and comparing it to the suffix term is consistently the fastest when tested against 10 strings the problem with using substring comparison though is that garbage collection can slow it down considerably more than the other methods because stringsubstring creates new strings the effect is not as bad in net 40 as it was in 35 and below but it is still noticeable in my tests stringsubstring performed consistently slower on sets of 120130 strings this will obviously differ between systems and implementationseditbenchmark codeeditflyingstreudels code runs fast but jon skeets recommendation of using endswith in conjunction with stringcomparisonordinal appears to be the best option,['c#'] +121330,calculating sunrise and sunset with java i search a way to calculate sunrise and set for a given timezone aka location i would like something similar to zend datethe idea is to have an application where you can select a location and based on that you get the actual time and also sunrise set timecheers and thankslony,['java'] +121335,using the result of an expression eg function call in a stored procedure parameter list i am trying to write a stored procedure to assist with development of our database but i am having some trouble using it for exampledeclare pid intset pid 1exec writelog component source could not find given id castpid as varcharthis yields the error on sql server 2005msg 102 level 15 state 1 line 4 incorrect syntax near can someone explain to me why my syntax is incorrect and the right way to solve this problem,['sql'] +121343,using strides for an efficient moving average filter i recently learned about strides in the answer to this post and was wondering how i could use them to compute a moving average filter more efficiently than what i proposed in this post using convolution filtersthis is what i have so far it takes a view of the original array then rolls it by the necessary amount and sums the kernel values to compute the average i am aware that the edges are not handled correctly but i can take care of that afterward is there a better and faster way the objective is to filter large floating point arrays up to 50x50 x 16 layers in size a task that scipyndimagefiltersconvolve is fairly slow atnote that i am looking for 8neighbour connectivity that is a 3x3 filter takes the average of 9 pixels 8 around the focal pixel and assigns that value to the pixel in the new imageimport numpy scipyfiltsize 3a numpyarange100reshape1010b numpylibstride tricksas strideda shapeasizefiltsize stridesaitemsize aitemsizefor i in range0 filtsize1 if i 0 b numpyrollb powfiltsize21i 0filtered numpysumb 1 powfiltsize2reshapeashape0ashape1scipymiscimsaveaveragejpg filterededit clarification on how i see this workingcurrent codeuse stride tricks to generate an array like 012123234 which corresponds to the top row of the filter kernelroll along the vertical axis to get the middle row of the kernel 10121213131415 and add it to the array i got in 1repeat to get the bottom row of the kernel 202121232324 at this point i take the sum of each row and divide it by the number of elements in the filter giving me the average for each pixel shifted by 1 row and 1 col and with some oddities around edges but i can take care of that laterwhat i was hoping for is a better use of stride tricks to get the 9 values or the sum of the kernel elements directly for the entire array or that someone can convince me of another more efficient method,['python'] +121347,how do i replace multiple items in a string starting string i like dogs cats and birdsfinal output neededi like a hrefdogsa a hrefcatsa and a hrefbirdsaso basically changing items with brackets to links,['javascript'] +121354,how to check if list element contains an item with a particular property value public class pricepublicmodel public pricepublicmodel public int pricegroupid get set public double size get set public double size2 get set public int printtype get set public double price get set listpricepublicmodel pricepubliclist new listpricepublicmodelhow to check if element of pricepubliclist contains certain value to be more precise i want to check if there exists pricepublicmodelsize 200 also if this element exists how to know which one it isedit if dictionary is more suitable for this then i could use dictionary but i would need to know how,['c#'] +121359,a base class pointer can point to a derived class object why is the viceversa not true a base class pointer can point to a derived class object why is the viceversa not true without castinglogically a base class would not have enough information of the derived class but a derived class should have the information of the base class as welli am missing some basics here,['c++'] +121386,how do i check an http request response status code from ios i am sending an http request from ios ipadiphone to my python google app engine server using the nsurlconnection and nsurlrequest classes how do i read the responses status ie the value set by app engine using responseset status200 messagesuccess for instance i am not able to find where i can read these status codes once i receive the nsurlconnections connectiondidfinishloading delegate call on the client end,"['iphone', 'objective-c']" +121393,accessing a variable defined in a parent function is there a way to access foo from within innerfunction outer foo function inner print foo innerouter,['php'] +121407,peculiar reverse cascading in css i have got a situation where my css is applying styles that do not apply to the object being styled here is exact code from my sitecss filerules aside width 270px right 0px top 0px float leftrules aside h3 borderbottomwidth 2px borderbottomstyle solid borderbottomcolor 2a2a2a paddingbottom 6px paddingtop 11px marginbottom 0px color f0e29a fontsize 14px letterspacing 05px texttransform uppercase now here is some html that utilizes itarticle classcontent rules section section aside some content asidearticleand here is the css markup that chromes inspector shows for the aside elementrules aside borderbottomwidth 2pxborderbottomstyle solidborderbottomcolor 2a2a2apaddingbottom 6pxpaddingtop 11pxmarginbottom 0pxcolor f0e29afontsize 14pxletterspacing 05pxtexttransform uppercasewidth 270pxright 0pxtop 0pxfloat leftthis does not make any sense only an h3 element should be styled from the rules aside h3 selector yet it is cascading down into the root aside element i have other instances of this happening as well this is happening in google chrome latest versionincluding screenshots for proofthirtydot editjsfiddlenet2hnlx running this exact same code from an html file on my machine yields the problem results but running it from jsfiddle yields the expected results a staceythe code from the jsfiddledoctype html html xmlns head titlejsfiddle exampletitle style typetextcss article section aside header nav thisplay block container margin 0px auto width 960px position relative section float left width 685px left 0px backgroundcolor c section h2 padding 10px section h3 fontsize 32px color ffcc00 fontweight bold padding 10px borderbottomwidth 2px borderbottomstyle solid borderbottomcolor 2a2a2a marginbottom 18px marginleft 10px marginright 10px rules aside width 270px right 0px top 0px float left backgroundcolor 0 aside h3 borderbottomwidth 2px borderbottomstyle solid borderbottomcolor 2a2a2a paddingbottom 6px paddingtop 11px marginbottom 0px color f0e29a fontsize 14px letterspacing 05px texttransform uppercase backgroundcolor f style head body div idcontainer article section psection textp section aside paside textp aside article div body html,"['html', 'css']" +121417,how to encode periods for urls in javascript the so post below is comprehensive but all three methods described fail to encode for periodspost how to encode a url in javascriptfor instance if i run the three methods ie escape encodeuri encodeuricomponent none of them encode periodsso foodstore comes out as foodstore which breaks the url it breaks the url because the rails app cannot recognize the url as valid and thisplays the 404 error page perhaps it is a configuration mistake in the rails routes filewhats the best way to encode periods with javascript for urls,"['javascript', 'html', 'ruby-on-rails']" +121434,how to use cdecl callback with pinvoke i have a c library that has cdecl callbacks how can i use these from ceverything seems to say that they must be stdcall callbacksto be cleardelegate int deldllimportmylibdllcallingconventioncallingconventioncdeclpublic static extern int funcwithcallbackdel foowhere del must be called cdeclwise,['c#'] +121443,cannot perform runtime binding on a null reference exception i am trying to find the dimensions of an excel table using c by finding the first null cell within the first column which consists of dates and the header rowheres the code i am using right nowpublic static void findingtablebounds string datecol arraylist datecolumn new arraylist arraylist numberofcolumns new arraylist for int column 1 column currentrow column datecol excelrangeworksheetcellscurrentrow 1value2tostring if datecol datecolumnadatecol currentrow totalrow consolewritelinetotal row 0 totalrow else consolewritelinetotal row 0 totalrow currentrow 2 note there is a closing bracket for this method i did not include it because there is another for loop that does the exact same thing as the above code but only for how many columns there arethe error occurs at datecol excelrangeworksheetcellscurrentrow 1value2tostring i am pretty sure it happens because i am trying to assign a null value the cell to datecol a string when string is a nonnullable type unfortunately i am not sure how to solve the problem,['c#'] +121451,is there a java implementation of the html5 input email validation i would like to use the new input typeemail element i would like to have java code that implements the same validation on the server that happens in the browserthe html5 spec defines email addresses in abnf as1 atext ldhstr ldhstr whereldhstr letdighyp letdighyp ldhstrletdighyp letdig letdig letter digitletter any one of the 52 alphabetic characters a through z in upper case and a through z in lower casedigit any one of the ten digits 0 through 9andatext alpha digit printable usascii characters not including specials used for atoms these are not the same rules as in rfc 5322how can i test that an address complies with these rules in javathanks,['java'] +121462,pymysql fetchall results as dictionary is there any way to get the results from a fetchall as a dictionary using pymysql,"['python', 'mysql']" +121483,fql and graph api in ios have anyone used fql of graph api in iosi am trying to get users posts from different groups i have read fql documentation but i need to see an example to help me proceedplease help,['ios'] +121486,iphone click view behind transparent uiscrollview i have a uiscrollview that is set to have a clear background part of the scrollview does have content but part does not so it shows other views behind it i would like to be able to click through the uiscrollview and to the mkmapview behind but only for the transparent portion of the uiscrollviewi have found some code which i am having a real hard time understanding how to get working voidtouchesbegannsset touches witheventuievent event if self yourmethodthatdeterminesinterestingtouchestouches witheventevent selfnextresponder touchesbegantouches witheventevent could someone help me wrap my mind around how to forward a touch event to a view that is behind another view can i call voidtouchesbegannsset touches witheventuievent event from a uiviewcontroller,"['iphone', 'ios']" +121489,help understanding c optimization i was playing with c and wanted to speed up a program i made changes and was able to do so however i need help understanding why the change made it faster i have attempted to reduce the code to something easier to understand in a question score1 and report1 is the slower way score2 and report2 is the faster way the first method first stores a string and an int in a struct in parallel next in a serial loop it loops through an array of those structs and writes their data to a buffer the second method first writes the data to a string buffer in parallel next in a serial loop it writes the string data to a buffer here are some sample run timesrun 1 total average time 0492087 secrun 2 total average time 0273619 secwhen i was working with an earlier nonparallel version of this the times were almost the same why the difference with the parallel versioneven if i reduce the loop in report1 to write a single line of output to the buffer it is still slower total time about 42 sechere is the simplified codeusing systemusing systemcollectionsgenericusing systemlinqusing systemtextusing systemdiagnosticsusing systemthreadingtasksusing systemionamespace optimizationquestion class program struct validword public string word public int score validword valid stringbuilder output int total public void score1string words valid new validwordwordslength for int i 0 i wordslength i stringbuilder builder new stringbuilder foreach char c in wordsi if c u builderappendc if wordsilength 3 validi new validword word buildertostring score wordsilength public void report1stringbuilder outputbuffer int total 0 foreach validword wordinfo in valid if wordinfoscore 0 outputbufferappendlinestringformat0 1 wordinfowordtostring wordinfoscore total wordinfoscore outputbufferappendlinestringformattotal 0 total public void score2string words output new stringbuilder total 0 for int i 0 i wordslength i stringbuilder builder new stringbuilder foreach char c in wordsi if c u builderappendc if wordsilength 3 outputappendlinestringformat0 1 buildertostring wordsilength total wordsilength public void report2stringbuilder outputbuffer outputbufferappendoutputtostring outputbufferappendlinestringformattotal 0 total static void mainstring args program program new program100 for int i 0 i programlength i programi new program string words filereadalineswordstxt stopwatch stopwatch new stopwatch const int timing repetitions 20 double averagetime1 00 stringbuilder output new stringbuilder for int i 0 i timing repetitions i stopwatchreset stopwatchstart outputclear parallelforeachprogramprogram p pscore1words for int k 0 k programlength k programkreport1output stopwatchstop averagetime1 stopwatchelapsedtotalseconds gccollect averagetime1 doubletiming repetitions consolewritelinestringformatrun 1 total average time 0 sec averagetime1 double averagetime2 00 for int i 0 i timing repetitions i stopwatchreset stopwatchstart outputclear parallelforeachprogramprogram p pscore2words for int k 0 k programlength k programkreport2output stopwatchstop averagetime2 stopwatchelapsedtotalseconds gccollect averagetime2 doubletiming repetitions consolewritelinestringformatrun 2 total average time 0 sec averagetime2 consolereadline,"['c#', '.net']" +121502,differences between detach hide and remove jquery what is the functional difference between these three jquery methodsdetachhideremove,"['javascript', 'jquery']" +121505,add a click handler to a horizontalpanel in gwt how do i add click handlers to horizontalpanelit worked with the use of adomhandler in newer gwt versions but i had to downgrade to gwt 204 where this is not supported i used to do it like thishorizontalpanelgetwidget1adomhandlersomeclickhandlerclickeventgettypeorhorizontalpaneladomhandlersomeclickhandler clickeventgettype,['java'] +121507,what is the difference between index out of range exception and index outside the bounds of array exception is there any difference between index was out of range exception and index was outside the bounds of the array exception,"['c#', '.net']" +121536,when escaping a string with html entities can i safely skip encoding chars above unicode 127 if i use utf8 when outputting a string in html one must escape special characters as html entities etc for understandable reasonsi have examined two java implementations of thisorgapachecommonslangstringescapeutilsescapehtmlstringnethtmlparserjerichocharacterreferenceencodecharsequenceboth escape all characters above unicode code point 127 0x7f which is effectively all nonenglish charactersthis behavior is fine but the strings it produces are nonhumanreadable when the characters are nonenglish for example in hebrew or arabic i have seen that when chars above unicode 127 are not escaped like this they still render correctly in browsers i believe this is because the html page is utf8 encoded and thus these characters are understandable to the browsermy question can i safely thisable escaping unicode characters above code point 127 when escaping html entities provided my web page is utf8 encoded,"['java', 'html']" +121548,how to xml serialize child class with its base class i am able to serialize a single typeclass but is there a way that i can serialize it base class toofor exampleclass bahere i am able to serialize class b but how can i serialize class a,"['c#', '.net']" +121554,c detect folder junctions in a path i want to make a quick check if in a complete path a junction point is used i already have a function to test a folder like isjunction but maybe there is an other solution to not call isjunction on every subfolderso i am looking for a function like hasjunctionsinpathstring path without testing each folder of the pathis there something which can do thiseditor betteris it possible to resolve all junctions in a path to get the real location of a file or folder this would be even better solve my problem and i still can compare the result with the original path to implement a bool hasjunctionsinpathstring path function,['c#'] +121556,how to put objective c code into word office with syntax highlighting i am writing documentation about an app and want to explain the code i want to copy parts of the objective c code from xcode to microsoft wordi do not know how to put the code with syntax highlighting and maybe line numbers too into worddoes anybody know a usable solution for this little problem,['objective-c'] +121557,case insensitive stringfind is there exist a case insensitive find method for stdstring,['c++'] +121562,str replace in twig i want to do a simple str replace in my twig template i am new to twig and probably i need to add new filter or sth like that or to use existing how can i do this where can i find list of filters available,['php'] +121565,using zend auth to secure all controllers how would i globally secure all my controllers except for my login controller to ensure my application is secure at all points no hidden backdoor to ajax calls etc i thought that i might put it in my bootstrap file but this does not feel right i am trying to avoid adding any code to each controllersuggestions,['php'] +121572,thisabling android home button for industry application i am writing an industry application which will be used by traffic wardens to register offences through my program using formsthe app is using a webview so it is just a container for an external webpage we do not want our users to exit the application so we have to thisable all buttons i succeeded in thisabling them except for the home buttoni read some threads about this topic but i do not have any solutions yet the idea is that i am able to make the app the default home app so if the user presses the home button it launches my app and does not exit how can i accomplish that if we must we are able to tamper with android itself when we install the app but if there is some solution through configuration it would be appreciated,['android'] +121575,placing c project references in a subfolder i have a solution with multiple projects that all output dlls except for the main application of course copy local is set to true for all of the references and everything is fine and dandy with dlls in the same directory as the exemy problem is that this is ugly i would like to put all the dlls in a subfolder actually two subfolders down to be precise how can i do this in visual studio 2008i have found a few questions that seem similar but i could not find the simple answer that i know has to existedit to be clearer i want to know how to make the assembly loader look for references somewhere besides the operating directory users will be interacting with some of the other files in the directory and the less clutter there is for them the betteredit 2 i also want to avoid using the gac the application needs to be self contained,['c#'] +121587,how to subtract datetime in javascript i have a field at a grid containing datetime and i need to know the difference between that and current datetime what could be the best way of doing so,['javascript'] +121610,what is powershell good for i am competent c programmer and a newbie to powershell i wonder what it is good for is it more of a programmers tool or admins please share your experience when it would be easier to write a script using net assemblies than a c tool what real production tasks do you use it forupd maybe the question should be what it is good for compared to c not batch,['.net'] +121617,routing in symfony2 how to setup default routing in symfony2in symfony1 it looked something like thishomepage url param module default action index default symfony url symfonyaction param module default default index url module param action index default url moduleaction,['php'] +121665,load jquery into a chrome extension i am attempting to load jquery into my chrome extension and make it equal to an object but i am wondering how would i go about this basically i would like something likejquery loadlibrariesjquery142minjshow would i do thisedit i am injecting into content script,['jquery'] +121666,visually thisable a checkbox but allow it to still submit its value i have a checkbox which is updated from other selections but it is important to show the checked status to the user however i also want it to be read only in functionality and represented as such in the thisplayit works fine bythisabling the checkbox gives the greyed out box to assist the user visuallyhowever this means upon submittingthe value is not savedconversely if i set the checkboxto readonly it thisables thecheckbox but still appears like anormal checkboxi kinda want a bit from each a checkbox that submits it is value but looks like a thisabled checkbox and still thisplays its check status does anyone have any ideas,"['jquery', 'html', 'css']" +121672,android theme not being set i have a theme that refuses to be applied to activities none of the styles are applied if i do not supply the layout widthlayout height attributes for button it also gets a runtime error showing that the button class is not being appliedresvaluesthemesxmlxml version10 encodingutf8resources style nametheme parentandroidstylethemeblack item nameandroidwindownotitletrueitem item nameandroidbuttonstylestylebuttonitem item nameandroidwindowbackgroundcolorpage background lightitem item nameandroidtextappearancestyletextappearanceitem styleresourcesresvaluesstylesxmlxml version10 encodingutf8resources style nametextappearance parentandroidstyletextappearance item nameandroidtextsize12spitem item nameandroidtextcolorcolordarkblueitem style style namebutton parentandroidstylewidgetbutton item nameandroidlayout widthfill parentitem item nameandroidlayout heightwrap contentitem item nameandroidtextcolor3c2f4fitem item nameandroidtextsize20dipitem styleresourcesand the relevant manifest settingapplication androidicondrawableicon androidlabelstringapp name androidthemestylethemewhats the obvious mistake i am missing,['android'] +121699,is there somewhere an index of py3konly libraries i am curious if there are important libraries that support only python 3 since it appears that many libraries that do support it also happen to support python 2,['python'] +121703,magic number in boosthash combine the boosthash combine template function takes a reference to a hash called seed and an object v according to the docs it combines seed with the hash of v byseed hash valuev 0x9e3779b9 seed 6 seed 2i can see that this is deterministic i see why a xor is usedi bet the addition helps in mapping similar values widely apart so probing hash tables would not break down but can someone explain what the magic constant is,['c++'] +121708,what does the following error mean program received signal aexc bad accessaswitching to process 388killerror while killing target killing anyway warning error on line 2179 of sourcecachegdbgdb1472srcgdbmacosxmacosxnatinferiorc in function macosx kill inferior safe oskern failure 0x5xquitthe debugger has exited with status 0gdb,['iphone'] +121712,do not allow cell to be moved to another section how can i thisable that the user can move cells to other sections i do not want to show an alert each time thanks d,['iphone'] +121718,overriding visited overrides link hover active please consider these stylesalink color blue avisited color red ahover color green aactive color black speciallink color pink and now this markupa hrefnormal linkaa href idspecialspecial linkai expect the special link to be pink while keeping the other colors however pink replaces the other colorswhy is this happening how could i fix it thank you,['css'] +121736,simple interprocess communication i am looking for a simple way to pass messages from one process perl script shortlived to another python script longrunning both processes local to the same machinei have done some research but what i have found was either over my head or seemed unnecessarily complex leaving me a bit lost and confusedi imagine a minimal example roughly like the following listenerpyclass listener def init self port selfport port def on messageself msg print s s timestamp msgrecipient listener1234 senderplsub send message my msg port send messagehello world 1234any pointers on how to solve andor where to read up on this would be greatly appreciated,['python'] +121754,a substitute for expandoobject in net 35 with least overhead how can i imitate the functionality of the expandoobject in a net 35 application with the least overhead my best lead so far is to use the lin fu framework but i am thinking there may be something betterto give a better idea of what i am going for here my objective is to dynamically create the type from the parameters of a methodinfo so basically i want to turn this public class serviceobject public void executestring transformmeintoaproperty into public class serviceobjectexecutesignature public string transformmeintoaproperty get set at runtime i have to be able to access the parameters using reflection because i am using linq expressions,['c#'] +121770,actionmailer 3 without rails i am writing a small ruby program that will pull records from a database and send an html email daily i am attempting to use actionmailer 303 for this but i am running in to issues all the searching i have done so far on using actionmailer outside of rails applies to versions prior to version 3 could someone point me in the right direction of where to find resources on how to do this heres where i am so far on my mailer file libbug mailerrbrequire action maileractionmailerbasedelivery method fileclass bugmailer actionmailerbase def daily email mail to from subject testing mail endendbugmailerdaily emaildeliveri am definitely stuck on where to put my views every attempt i have made to tell actionmailer where my templates are has failedi guess i should also ask if there is a different way to go about accomplishing this program basically i am doing everything from scratch at this point obviously what makes rails awesome is it is convention so is trying to use parts of rails on their own a waste of time is there a way to get the railslike environment without creating a fullblown rails app,['ruby'] +121776,jscrollpane resizing with variablesized content my resizable jscrollpanes content has a minimum width if the jscrollpane is smaller than this width horizontal scroll bars should appear if it is greater than this width the viewport content should expand to fill up the entire viewportseems like a simple concept and i have got something that is working but it feels like a hackimport javaxswingimport javaawtimport javaawteventcomponentadapterimport javaawteventcomponenteventpublic class ssbtest public static void mainstring args swingutilitiesinvokelaternew runnable public void run final component view new myview final jscrollpane jscrollpane new jscrollpaneview jscrollpaneaddcomponentlistenernew componentadapter override public void componentresizedfinal componentevent e final dimension minimumsize viewgetminimumsize final int width mathmaxminimumsizewidth jscrollpanegetviewportgetwidth viewsetpreferredsizenew dimensionwidth minimumsizeheight showindialogjscrollpane private static void showindialogfinal jscrollpane jscrollpane final jdialog dialog new joptionpanejscrollpanecreatedialogjscrollpane resize test dialogsetresizabletrue dialogsetmodaltrue dialogsetvisibletrue systemexit0 private static final class myview extends jpanel override protected void paintcomponentfinal graphics g superpaintcomponentg gsetcolorcolorred gdrawstringdimensions are getsize 10 20 gdrawrect0 0 getminimumsizewidth1 getminimumsizeheight1 gsetcolorcolorblue gdrawrect0 0 getpreferredsizewidth1 getpreferredsizeheight1 override public dimension getminimumsize return new dimension200 200 override public dimension getpreferredsize return supergetpreferredsize resizing the dialog triggers the componentlistener which explicitly sets the preferred size of the viewport view triggering component validation however resizing causes jittery scroll bars is there a cleaner way to do thisedit thanks to camickr for the scrollablepanel link i have modified my jpanel class to implement scrollable and dynamically change the return value for getscrollabletracksviewportwidthwhen the viewport is big i return true for getscrollabletracksviewportwidth telling the jscrollpane to fill the view with my component when the viewport is small i return false so the scrollbars appearimport javaxswingimport javaawtpublic class ssbtest public static void mainstring args swingutilitiesinvokelaternew runnable public void run final component view new myview final jscrollpane jscrollpane new jscrollpaneview showindialogjscrollpane private static void showindialogfinal jscrollpane jscrollpane final jdialog dialog new joptionpanejscrollpanecreatedialogjscrollpane resize test dialogsetresizabletrue dialogsetmodaltrue dialogsetvisibletrue systemexit0 private static final class myview extends jpanel implements scrollable override protected void paintcomponentfinal graphics g superpaintcomponentg gsetcolorcolorred gdrawstringmyview getwidth x getheight 10 20 gdrawrect0 0 getminimumsizewidth1 getminimumsizeheight1 gsetcolorcolorblue gdrawrect0 0 getpreferredsizewidth1 getpreferredsizeheight1 gdrawstringpreferredminimum size 10 getpreferredsizeheight2 gsetcolorcolorgreen gdrawline0 0 getwidth getheight override public dimension getminimumsize return new dimension200 200 override public dimension getpreferredsize return getminimumsize public dimension getpreferredscrollableviewportsize return getpreferredsize public int getscrollableunitincrementfinal rectangle visiblerect final int orientation final int direction return 10 public int getscrollableblockincrementfinal rectangle visiblerect final int orientation final int direction return visiblerectwidth public boolean getscrollabletracksviewportwidth final container viewport getparent return viewportgetwidth getminimumsizewidth public boolean getscrollabletracksviewportheight return true,['java'] +121786,optimized way to get get item methodinfo right now i have targettypegetmethodget item bindingflagsinstanceis there anything better,['c#'] +121790,help me understand pack openssl random pseudo bytes and mt rand for salting passwords i am building an application that will have a user base and i am at the point of securing the login i am fairly new to programming and php but my efforts thus far have pointed to using crypt and a blowfish hashed saltbefore i go further let me specify that i am not interested in phpass at this timewithin the crypt documentation a user recently posted thisphp salt substrstr replace base64 encodepackn4 mt rand mt rand mt rand mt rand 0 22 it is intended for use on systems where mt getrandmax 2147483647the salt created will be 128 bits in length padded to 132 bits and then expressed in 22 base64 characters crypt blowfish only uses 128 bits for the salt even though there are 132 bits in 22 base64 characters if you examine the crypt blowfish input and output you can see that it ignores the last four bits on input and sets them to zero on outputnote that the highorder bits of the four 32bit dwords returned by mt rand will always be zero since mt getrandmax 231 so only 124 of the 128 bits will be pseudorandom i found that acceptable for my applicationi tested my server and indeed mt getrandmax returns 2147483647 i tried poking around the documentation to understand what the above code really doesthe pack code n4 is for a 32bit string big endian byte order repeated 4 times which i assume is why there is 4 mt rand argumentswhat i do not understand is why he replaces with and the purpose of 22 base64 characters not that i fully understand what base64 isit was recommended that i look into openssl random pseudo bytes for my random salt generation as the previous method i was looking at was limiting itself to just 1234567890abcdefghijklmnopqrstuvwxyzsupposedly there was a bug pre 534 causing openssl random pseudo bytes to run painfully slow occassionally causing timeout errors i am not sure if i should try to use openssl random pseudo bytes with crypt or something like the above method using mt rand and packi am trying to understand more how all these elements work and what they are doing conceptuallyrather than just using one without understanding it to achieve my goal i am trying to learn pcan someone help me understand the different elements at work here or at least direct me to a knowledge base where i can read about it i think the most eluding component is understanding the different formatsterminology base64 ascii hexdec bit byte etc but also in the end how to achieve a fairly secure salt for use with my passwords,['php'] +121806,test ios app on device without apple developer program or jailbreak how can i test an ios application on my ipod touch without registering for the apple developer program or jailbreaking my ipodneither is a viable option at the momenti would like to test on the device itself instead of the onscreen emulator to see how it performs on an actual ipod,['ios'] +121812,creating private class method how come this approach of creating a private class method worksclass person def selfget name persons name end class self private def persons name sam end endendputs hey personget nameputs hey personpersons name raises private method persons name called for personclass nomethoderrorbut this does notclass person def selfget name persons name end private def selfpersons name sam endendputs hey personget nameputs hey personpersons name,['ruby'] +121813,using htmleditorfor to generate a textarea with a specific number of rows and columns i know you can use the datatype attribute with the editorfor html helper to specify that a particular property of a model entity should be thisplayed as a multiline input field what if i want to specify the number of rows and columns the text area must havein the model datatypedatatypemultilinetextpublic string htmltext get set in the view htmleditorforx xhtmltextwanted result textarea idhtmltext rows10 cols40valuetextareais there a way to generate this kind of code without using the htmltextarea helper,['asp.net'] +121818,convert latlongs to xy coordinates i have the latlong value of an small area in melbourne 37803134145132377 and also a flat image of thatthat i exported from openstreet map osmarender image image width 1018 and height916i would like to be able to convert using c the latlong to an xy coordinate where the point would reflect the locationi used various formulas that i found in web like one given below but nothing helpsvar y 1 lat 90 map height 180var x lon 180 map width 360it would be of great help if any one give me clear explanation of how to do this any code would be much appreciated,['c++'] +121853,center message in android dialog box i want the message text within my dialog box to be center aligned,"['java', 'android']" +121854,how to redirect qdebug qwarning qcritical etc output i am using a lot of qdebug statements for debug output is there any crossplatform way i can redirect that debug output to a file without resorting to shell scripts i am guessing that open and dup2 will do the job in linux but will it work compiled with mingw in windowsand maybe there is a qt way to do it,['c++'] +121883,why this php curl function cannot work function get dataurl ch curl init timeout 5 curl setoptchcurlopt urlurl curl setoptchcurlopt returntransfer1 curl setoptchcurlopt connecttimeouttimeout data curl execch curl closech return datai find this function from the internet when i test it in a php file using this code returned content get data but it cannot workand get a 301 moved permanently the document has moved here error why,['php'] +121892,editing microsoft word documents programmatically i want to know if this could be donei am building a data dictionary for our software system school project and i am thinking of an automated way to do this basically i do not use much of microsoft word 2007 i only use it in documenting schools stuff etc i want to know if its possible to createedit a word document programmatically from a templatethe idea is i will create a page on word that contains an empty form that will be repeated on every page for every data that i will input to my program it will update the corresponding field in the form and skips to the next formthe purpose of this is to eliminate copypaste methods my habit and to speed things up when doing the documentation,"['c#', '.net']" +121894,hibernate how to use concat and group concat how can i use concat and group concat in hql queries,"['java', 'mysql']" +121898,using ads in phonegap iphone app does anyone have any insight experiencelinks they can point me to for adding ads to an app i am building on the phonegap platform i have been searching and not a lot of information out there thought i would ask thanks in advance,['iphone'] +121902,what does ipa file stands for whenever i download any application from itunes the file extension is ipa i already know that this is a zip file which contains some plist info it is meant for iphoneipodi am wondering what is the full name of this ipa,['iphone'] +121903,how to create a simple local sql database insert values into it using c how to create a simple local sql database insert values into it using c can any one provide me a sample code or project link i googled a bit i am not getting how to doif you can advice it would be great,"['c#', '.net', 'sql']" +121942,how to comment or like a photo in facebook through fbconnect or graph api in iphone sdk i am developing a iphone application in which i want to comment or like a photo on facebook for facebook integration i am using fbconnect and graph api i am getting friends photos on my wall in my application now i want to like or comment on them through my iphone application please suggest me how can i obtain thatthanks in advance,['ios'] +121952,how do you merge in git on windows i tried to use git however for me the biggest problem with it is that there is no tool for mergeing at least the msysgit does not give me anything how can i merge in git are there any great tools for it or do i have to use winmerge or application like thati use java and eclipse,['java'] +121954,finding stack trace in eclipse with android not used to using eclipse for java mainly used jedit but with the android dev along comes eclipse i have switched to the debug window and pressed the debug button which starts my app it crashes however i cannot find the stack trace i can see in the debug pane that it has crashed with a exception however i cannot see any more information not sure if you can get it but i am a little used to visual studio with line numbers and a bit more information saying what went wrong as i said all i am getting is thread 1 mainsuspended exception runtimeexceptionin the debug window can anyone shed some light as to where i can find more information,"['java', 'android']" +121957,conditional statements difference is there any difference between below two statementsif null objandif obj nulleditif both treated same which will be preferablethanks,"['c#', 'asp.net']" +121962,loading utf8 encoded text into mysql table i have a large csv file that i am going to load it into a mysql table however these data are encoded into utf8 format because they include some nonenglish charactersi have already set the character set of the corresponding column in the table to utf8 but when i load my file the nonenglish characters turn into weird characterswhen i do a select on my table rows do i need to encode my data before i load the into the table if yes how can i do this i am using python to load the data and using load data local infile command thanks,['mysql'] +121965,how to check if uidocumentinteractioncontroller will fail to open document due to missing external application on ipad i am using uidocumentinteractioncontroller for showing popover menu open in so that user can open a document in other applicationmethod presentopeninmenufrombarbuttonitemanimated returns no in case there is no application able to open given document menu will not show but it is too late for me to wait until getting so far i would like to thisable the button initiating that opening if it is not possible instead of raising expectations of an user and then say sorry it is not possible to open it is it possible to query system to see if there is at least one application registered for particular document type i have checked canpreviewitem in qlpreviewcontroller but it seems it does not support the same document types which uidocumentinteractioncontroller can handle,"['iphone', 'objective-c']" +121974,java executorservice awaittermination of all recursively created tasks i use an executorservice to execute a task this task can recursively create other tasks which are submitted to the same executorservice and those child tasks can do that tooi now have the problem that i want to wait until all the tasks are done that is all tasks are finished and they did not submit new ones before i continuei cannot call executorserviceshutdown in the main thread because this prevents new tasks from being accepted by the executorservice and calling executorserviceawaittermination seems to do nothing if shutdown has not been calledso i am kinda stuck here it cannot be that hard for the executorservice to see that all workers are idle can it the only inelegant solution i could come up with is to directly use a threadpoolexecutor and query its getpoolsize every once in a while is there really no better way do do that,['java'] +121984,get a swing component by name i have in a jframe some components that i wantto refer into another jframe and i wantto get them by name and notdo public getset methods for eachis there a way from swing to get a component reference by its name like doceg formcontrolstextthanks,['java'] +121993,should i comment my log calls when creating my final package i have an application that uses a lot of logd or loge calls for debugging now i want to create my final package for release the android export feature from eclipse mentions to remove the debuggable flag in the manifest which i have done should i also comment all the log calls to improve the performance of my application or these calls will do nothing in the non debuggable final version package,['android'] +122016,java networking connection refused connect i have been trying to get a simple networking test program to run with no resultsserverimport javaioimport javanetpublic class servertest public static void mainstring args final int port number 44827 whiletrue try listen on port serversocket serversock new serversocketport number systemoutprintlnlistening get connection socket clientsock serversockaccept systemoutprintlnconnected client get input bufferedreader br new bufferedreadernew inputstreamreaderclientsockgetinputstream systemoutprintlnbrreadline brclose serversockclose clientsockclose catchexception e eprintstacktrace clientimport javaioimport javanetpublic class clienttest public static void mainstring args throws ioexception final int port number 44827 final string hostname x attempt to connect try socket sock new sockethostname port number printwriter out new printwritersockgetoutputstream true output outprintlntest outflush outclose sockclose catchexception e eprintstacktrace the program works just fine when i use 127001 or my internal ip for the hostname but whenever i switch to my external ip address it throws a javanetconnectexception connection refused connect errori purposely picked such an uncommon port to see if that was the problem with no lucki can connect with no problems using telnet but when i try to access the port with canyouseemeorg it tells me the connection timed outi even tried to thisable all firewalls and antivirus including the windows default ones and the router firewall with all ports forwarded and dmz enabled and it still says that the connection timed out i use comcast as my isp and i doubt that they block such a random portwhen i use a packet tracer it shows tcp traffic with my computer sending syn and receiving rstack so it looks like a standard blocked port and no other suspicious packet traffic was going on i have no idea what is going on at this point i have pretty much tried every trick i know if anyone know why the port might be blocked or at least some way to make the program work it would be very helpful,['java'] +122017,how to pass a javascript variable into a erb code in a js view i have this javascript view in my rails 3 projectappviewsexpensesnew dailyjserbvar i parseintdailyattrdatanum 1dailyappendagrego fila i br dailyappend escape javascriptrenderpartial new expense locals i i dailyattrdatanum ii want to pass my i javascript variable to a ruby partial through locals how i can accomplish this,"['javascript', 'ruby-on-rails']" +122027,php extension vs library and can it be converted some php wamplamp packages come with php extensions packaged within like php amf php db php gd2 and i just have to activate the extension or install the extension if it does not come by default my question in general is how are these extensions different from libraries and in specific i want to know can an extension be turned into a library that is loaded in the project itself the goal is to call the library without special installations like php extensions need sometimes when youre on shared hosting you do not have enough privileges to install a new extension,['php'] +122078,attribute name not allowed on element div at this point doctype htmlhtml head titlejgrowltitle meta httpequivcontenttype contenttexthtmlcharsetutf8 script typetextjavascript srcscript script typetextjavascript srcscript script typetextjavascript srcdataawojgrowljsscript script typetextjavascript srcdatashortcutjsscript link relstylesheet typetextcss hrefdataawojgrowlcss script typetextjavascript documentreadyfunction divnamemessageawomsginput message sticky true shortcutaddmfunction divnamemessageawomsginput message sticky true shortcutaddhfunction alertur doin it wrong script head body div namemessage classjgrowl bottomright errorgrowldiv body htmlhello i am getting a w3c error that i cannot understandline 31 column 61 attribute name not allowed on element div at this pointthat is this rowdiv namemessage classjgrowl bottomright errorgrowldiv,"['javascript', 'html']" +122089,suspend databinding of controls i have a series of controls that are databound to values that change every second or so from time to time i need to pause the controls so that they do not update their databindings in either direction i then later need to unpause the controls so that they can update the datasource with their values and receive future updates from the source as normal how do i accomplish thissample bindingtextbox textbinding updatesourcetriggerlostfocus modetwoway pathmydata,"['c#', '.net']" +122099,get mouse position in scrollable div yet another question that has been pecking away at me the last few days as you may have seen from my other questions i am creating some mind map software so extremely simplified i have a two divs one that is a square on the page and another inside that div which is about 10 times as large and draggable this is so that objects can be placed on the screen and then moved slightly to the side whilst another object is added etc i do this by creating the outer div scrollablethe problems that i am having though are to do with the mouse position in java script if i get the mouse position anywhere in the div it wont be correct as i offset the inner div by half its size to the top and left so effectively the user is looking at the middle of the canvas and can go any way they like i have tried tens of different mouse coordinate functions but none of these seem to work an example that is supposed to be cross browser that i found somewhere on the web isfunction getmousee var posx var posy if e var e windowevent if epagex epagey posx epagex posy epagey else if eclientx eclienty posx eclientx documentbodyscroleft documentgetelementbyidcanvasscroleft posy eclienty documentbodyscrolltop documentgetelementbyidcanvasscrolltop getmousebut even this does not work i am almost certain that the error is because i have the inner div being draggable hopefully i have made some sense trying to explain but if i have not here is a very simple jsfiddle in an attempt to demonstrate the situation that i have although no mouse clicking is done here purely to demonstrate my div structure in the product i am making the user will double click on the canvas and a new object will appear and hence why the mouse coordinates need to be correcti hope someone out there can help me thanks in advanceedit failed to mention that for part of my application i use jquery so a solution either with or without jquery would be fine thanks again,"['javascript', 'jquery']" +122113,how to determine if a type implements an interface with c reflection does reflection in c offer a way to determine if some given systemtype type models some interfacepublic interface imyinterface public class mytype imyinterface should yield truetypeofmytype models interfaceimyinterface,['c#'] +122116,which notnull java annotation should i use i am looking to make my code more readable as well as use tooling like ide code inspection andor static code analysis findbugs and sonar to avoid nullpointerexceptions many of the tools seem incompatible with each others notnullnonnullnonnull annotation and listing all of them in my code would be terrible to read any suggestions of which one is the best here is the list of equivalent annotations i have foundjavaxvalidationconstraintsnotnullcreated for runtime validation not static analysisdocumentationeduumdcsfindbugsannotationsnonnullused by findbugs static analysis and therefore sonardocumentationjavaxannotationnonnullthis might work with findbugs too but jsr305 is inactivesourceorgjetbrainsannotationsnotnullused by intellij idea ide for static analysisdocumentationlomboknonnullused to control code generation in project lombokplaceholder annotation since there is no standardsource documentationandroidsupportannotationnonnullmarker annotation available in android provided by supportannotations packagedocumentationorgeclipsejdtannotationnonnullused by eclipse for static code analysisdocumentation,['java'] +122131,appropriate use of static method conceptually is it appropriate to use a static method c when the method will only take inputs and reformat the input as the output for examplepublic static string formatstringstring inputstring return some formatting inputstring some other formattingif i were to have a few of these types of methods would a static utility class be a good idea,['c#'] +122133,what causes ios linking errors i have been getting some strange linking errors in xcode i understand more or less what linking errors are just not why they are showing up in my situationi have an app that started as iphone only when i adjusted it to be universal i got some odd linking errors i then simply created a new universal project and imported the files it built and executed without error now working with the ipad interface i have added some animations and am inheriting quartzcorequartzcoreh but when i build i get linking errors shown below what causes this sort of problem how can i fix it and how can i avoid it in the future objc class camediatimingfunction referenced fromobjcclassreftocamediatimingfunction in mainviewcontroller ipado objc class cabasicanimation referenced fromobjcclassreftocabasicanimation in mainviewcontroller ipado kcamediatimingfunctioneasein referenced from kcamediatimingfunctioneaseinnon lazy ptr in mainviewcontroller ipadomaybe you meant kcamediatimingfunctioneaseinnon lazy ptr objc class cakeyframeanimation referenced fromobjcclassreftocakeyframeanimation in mainviewcontroller ipado objc class caanimationgroup referenced fromobjcclassreftocaanimationgroup in mainviewcontroller ipado catransform3didentity referenced from catransform3didentitynon lazy ptr in mainviewcontroller ipadomaybe you meant catransform3didentitynon lazy ptrld symbols not foundcollect2 ld returned 1 exit status,['ios'] +122139,target blank vs target new whats the difference between a target new and a target blank and which should i use if i just want to open a link in a new tabwindow,['html'] +122143,sql server how can i select everything from a table with a prefix i have the following code in a very long stored procedure where p equals the products tableselectpetc1etc2which would give me productid and so oni would like to select it with a prefix such asselectp as p etc1etc2which would give me p productid and so onis this possible to do,['sql'] +122153,reading inputstream as utf8 i am trying to read from a textplain file over the internet linebyline the code i have right now isurl url new urlbufferedreader in new bufferedreadernew inputstreamreaderurlopenstreamlinkedliststring lines new linkedliststring readlinewhile readline inreadline null linesaddreadlinefor string line lines outprintln linethe file testtxt contains ahalla3 which i am using in order to test the encodingwhen i review the outputstream out i see it as aahaallaa i do not believe this is a problem with the outputstream since i can do outprintlna without problemsany ideas for reading form the inputstream as utf8 thanks,['java'] +122172,drop sql login even while logged in when dropping a sql server 2008 login as part of integration test execution i sometimes get the following errorsystemdatasqlclientsqlexception could not drop login sometestuser as the user is currently logged ini do not care if it is logged in i still want to drop it whats the easiest way to do this,['sql'] +122187,razor support of generic extension methods with regards to the razor view engine say i want to render htmltextboxforsomemodeli iname it does not seem that the inline syntax works as inhtmltextboxforsomemodeli inamethis does not seem to work because it interprets the generic as an html tag i could use a codeblock approach but then whats the best approach to output the content the html string returned from this method do i responsewrite it or is there a syntax for it or whats the approachthanks,['asp.net'] +122197,can use pushstate does anyone know of a library that determines if pushstate can be usedi was using thisifwindowhistorypushstate windowhistorypushstatenull documenttitle pathelse locationpathname pathbut i just found out that there is a bug in safari 502 that causes it not to work even though the above test passes i am thinking there might be other gotchas and someone has probably already found them and wrapped em up but i have not found anything yeteditcrescent freshfrom what i have seen it seems like pushstate pushes onto the history stack and changes the url but does not update locationpathname in my code i am using setinterval to check if the path has updatedvar cachedpathname locationpathnameifwindowhistorypushstate cachedpathname locationpathname setintervalfunction ifcachedpathname locationpathname cachedpathname locationpathname do stuff 100in safari 502 the locationpathname does not change when pushstate changes the url this works in other browsers and versions of safari,['javascript'] +122205,rails 2 modelfind1 gives activerecord error when id 1 does not exist i am using rails 235 and in that if i give modelfind1 and if 1 is not in the database it returns activerecord error should it just be returning nil as in the case of modelfind by column,['ruby-on-rails'] +122217,what is the difference between abstraction and encapsulation possible duplicatedifference between abstraction and encapsulation what exactly is the difference between encapsulation and abstraction in java any brief examples would also be appreciated,['java'] +122221,androidhow to upload mp3 file to http server i want to upload mp3 fileonly from device to my server i want to browse path of media data and select any mp3 file and upload it how can i do thisany ideathanks,['android'] +122231,objection to exceptions one of my friends raised this problem to me i was stuck because i am not an adept at using exceptions keep in mind that we both work in an working environment where we use c but do error handling in c tradition his problem was something like thisfunction a calls b which in turn calls c an exception is thrown from c and the catch block for that exception is in a what happens to resources acquired in b before the call to c how do we clean those up my answer was use raii but even when i said it i knew it was not gonna work we have huge code bases that have been written in the c mode nowhere in code have i seen auto pointers and such resources are not necessarily wrapped up in classes even when they are the destructors are left for the compiler in most cases in short everything is done manuallythe real problem is what to do to make the transition from c error handling to exceptions with the weight of a huge code base the problem my friend asked is just one of the possible questions that can be raised when you have your feet grounded in c error handling and want to know how the migration from there to exceptions can occur,['c++'] +122239,how to get the size of a string in python for example i get a stringstr please answer my questioni want to write it to a filebut i need to know the size of the string before writing the string to the file what function can i use to calculate the size of the string,['python'] +122241,selecting a row in qtreeview programatically i have a qtreeview with qfilesystemmodel as modelthe qtreeview has selectionbehavior set to selectrowsin my code i read a dataset to select and then select them via idx treeviewmodelindexsearch selectionselectidx qitemselectionmodelselectthis selects a cell not the row have added a stupid workaround but would rather fix this the correct wayfor int col0 col treeviewmodelcolumncount col idx treeviewmodelindexsearch col selectionselectidx qitemselectionmodelselect or is that the only way to do it,['c++'] +122244,transfer data from one activity to another activity using intents i would like to be able to transfer data from one activity to another activity how can this be done,['android'] +122250,is flags attribute neccessary i found with or without flags attributes i can do bit operation if i defined the following enumenum testtype none 0x0 type1 0x1 type2 0x2i am wondering why we need flags attribute,"['c#', '.net']" +122257,how to round time to the nearest quarter hour in javascript for examplegiven time 0822 rounded to 0815given time 0823 rounded to 0830should be pretty simple but all i was able to produce is lengthy not very good code to solve the issue my minds just gone blankregards,['javascript'] +122267,how to select the relative complement of a table b in a table a a b in an sqlquery i have got two tablessubjectsid categoriessubjectid i want to select all subjects from table 1 without the entries in 2 categoriesany tips appreciated best regards,"['sql', 'mysql']" +122272,how to get complex enum value string representation let us say i have this enumflagspublic enum sometype val1 0 val2 1 val3 2 val4 4 val5 8 val6 16 all val1 val2 val3 val4 val5 val6and some variablessometype easytype sometypeval1 sometypeval2sometype complextype sometypeallif i want to loop through values of the first enum i can simply doforeachstring s in easytypetostringsplit however when i try to apply the same approach to the complextype i get value all which is of course valid because it is also one of possible values of the enum but is there a neat way to actually see of what values is the sometypeall created of i know i could make a manual loop through all the values like thatifcomplextypehasflagmanualtypeval1,['c#'] +122277,infinte recursion while extending the admins app change form template i have the following template in templateadminchange formhtml extends adminchange formhtml block extrahead include dojangobasehtml block dojango content endblock endblock however for some reason it throws a templatesyntaxerror templatesyntaxerror at admincmspostaddcaught runtimeerror while rendering maximum recursion depth exceeded while calling a python objectcan anyone tell me what am i doing wrong,['python'] +122305,set timeout for socket when i create a socketsocket socket new socketipaddress portit throws an exception which is ok because the ip address is not available the test variables where string ipaddress 19216803 and int port 300the problem is how do i set it to timeout for that socketwhen i create the socket how do i reduce the time before i get a unknownhostexception and get the socket to timeout,['java'] +122327,difference between listall and listtrueforall is there a practical difference between all and trueforall when operating on a list i know that all is part of ienumerable so why add trueforall,['c#'] +122353,database storage of longitudelatitude values in sql server decimal2 in the table definition i sawlatitude varchar50longitude nvarchar50immediately obviously i queried the thinking behind this being positively sure these values are in fact numerical by nature long story short i postulated that these will be numerical decimal in fact and we would thiscard the thinkinginstrings philosophynow for the horns of my dilemma i just went ahead and typedlatitude decimal2 4but hold on a second 4 am not right right right so i thought i would up the threshold before realising in a split second might i add that 6 or 8 might not not cut it either so first things firstam i right in insisting we even go about it this way and if soto what precision ought these values be stored to ensure we can persist the entire value which is to be inserted for example is there anything predefined by specificationi do not just want to use something like latitude decimal2 16 simply for it to be just as flawed as decimal2 2 in principle and a similar question arises for longitude specifically but i am assuming the answer to one will suffice for the other ie decimal3 answerwe are using mssql server 2005it seems i am educating myself with sql server by manual experience and therefore rendering parts of this question irrelevant i can only use decimalx maxx not decimalx y anyway will leave the question as is for input,['sql'] +122354,how to parse html to modify all words this seems to be a recurring question but here goesi have html which is wellformatted it comes from a controlled source so this can be taken to be a given i need to iterate through the contents of the body of the html look for all the words in the document perform some editing on those words and save the resultsfor example i have file samplehtml and i want to run it through my application and product outputhtml which is exactly the same as the original plus my edits i found the following using htmlagilitypack but all the examples i have found look at the attributes of the specified tags is there an easy modification that will look at the contents and perform my editshtmldocument hd new htmldocumenthdload etesthtmvar noaltelements hddocumentnodeselectnodesimgnotaltif noaltelements null foreach htmlnode hn in noaltelements hnattributesappendalt no alt image hdsaveetesthtmthe above looks for image tags with no alt tags i want to look for all tags in the body of the file and do something with the contents which may involve creating new tags in the processa very simple sample of what i might do is take the following inputhtml headtitlesome titletitlehead body h1this is my pageh1 pthis is a paragraph of textp bodyhtmland produce the output which takes every word and alternates between making it uppercase and making it italicshtml headtitlesome titletitlehead body h1this emisem my empageemh1 pthis emisem a emparagraphem of emtextemp bodyhtmlideas suggestions,"['c#', 'html']" +122356,sending arguments via event handler so i am not actually sending arguments but setting a class variable to a certain value then using it again in another method is this the best practice way to do things if not i would be interested in learning the correct way thanks canshould the arguments be sent some other wayprivate string printthispublic void printitstring input printthis input setting printthis here static private printdocument pd new printdocument pdprintpage new printpageeventhandlerprintdocument printsomething pdprintprivate void printdocument printsomethingobject sender printpageeventargs e egraphicsdrawstringprintthis new fontcourier new 12 brushesblack 0 0 using printthis in the above line,['c#'] +122377,difference between ienumerable and ienumerable what is the difference between ienumerable and ienumerablet i have seen many framework classes implementing both these interfaces therefore i would like to know what advantages one get by implementing bothplease have a look how they have been definedpublic interface ienumerable thispid4 ienumerator getenumeratorpublic interface ienumerablet ienumerable ienumeratort getenumeratoras we see ienumerablet derives from ienumerable that means whatever ienumerable has ienumerablet inherits then why do we implement both instead of just ienumerablet is implementing ienumerablet not enoughlikewise there are other similar pairsilist and ilistt icollection and icollectionti would like to know about these as well,['c#'] +122378,escaping characters in a xml file with python i need to escape special characters in an ugly xml file 50 lines or so long heres an example of xml i have to deal withroot element namename surnamename mailmail elementroothere the problem is the character in the name how would you escape special characters like this with a python library i did not find the way to do it with beautifulsoup,['python'] +122401,adding subdirectory to viewshared folder in aspnet mvc and calling the view i am currently developing a site using aspnet mvc3 with razor inside the viewshared folder i want to add a subfolder called partials where i can place all of my partial views for the sake of organizing the site betteri can do this without a problem as long as i always reference the partials folder when calling the views using razorhtmlpartialpartialsviewnamemy question is if there is a way to add the partials folder to the list that net goes through when searching for a view this way i can call my view without having to reference the partials folder like sohtmlpartialviewnamethanks for the help,['asp.net'] +122406,signal 11 sigsegv crash android today i faced an error due to which my android application is getting by signal 11this error usually occurs due to unauthorized memory area access by android internal storage some of the possible scenarios are web access network communication server image downloading and such mine was the case of browser load urli need to launch the browser after a qr code scanapplication was keep on scanning and launching the browser fluently but the issue occurs after 1520 attempts of same stepsi researched a lot and found that its the memory error which occurs in android native libraries usually when an unknown memory area is tried to access by the android internal storage systemfinally i revealed that when i saw my application memory usage in the android application setting section i found that the cache has been reached to 10 mb,['android'] +122407,a question about writing a backgroundautomaticsilent downloaderinstaller for an app in c backgroundi have a main application that needs to be able to go to the web and download dll files associated with it ones that we write located on our server it really needs to be able to download these dll files to the application folder in cprogram files in the past i have used systemnetwebclient to download whatever files i wanted from the webthe issuei have had a lot of trouble downloading data in the past and saving to files on a users hard drive i get many reports of users saying that this does not work and it is generally because of user rights issues in the program in the cases where it was an issue with program user rights every user could go to the exact file location on the web download it and then save it to the right place manuallyi want this to work like all the other programs i have seen downloadinstall in this fassion ie firefox pluign updates flash player java adobe reader etc all of these work without a hitchthe questionis there some code i need to use to give my downloader program special rights to the program files folder can i even do this is there a better class or library that i should use is there a different approach to downloading files i should take such as using threads or something else to download dataany help here is appreciated i want to try to stay away from thirdparty appslibraries if at all possible other than microsoft of course due to licensing issues but still send any suggestions my wayagain other programs seem to have the rights issues and download capability figured out i want this same capability,['c#'] +122409,run an async function in another thread i am evaluating the async ctphow can i begin execution of an async function on another thread pools threadstatic async task test do something await somethingstatic void main string args is there more elegant way to write the line below var t taskexrun testwait doing much more in this same thread twait waiting for much more then just this single task this is just an example,"['c#', '.net']" +122412,right align text in html input field i have an html tag with a short maxlength but a long value attribute i would like the thisplayed text to show the end right side of the text rather than the start left sideinput maxlength10 valuea really really really long entry goes in herecurrently showsa really rinstead i would like it to showes in herecheersian,"['html', 'css']" +122419,set environment variable env for use in rails experimenting with mongoid on a rails server and confused about howwhere to set the environment variables configmongoidyml default template provides defaults defaults host localhost set these environment variables on your prod serverproduction host envmongoid host port envmongoid port username envmongoid username password envmongoid password database envmongoid database my question is are these set in rails somewhere or are they at the system level and if so wherehow to set so that no user account needs to be logged in for them to be valid,['ruby-on-rails'] +122423,extract thisplay name and description attribute from within a html helper i am building a custom htmllabelfor helper that looks like this public static mvchtmlstring labelfortmodel tvaluethis htmlhelpertmodel self expressionfunctmodel tvalue expression boolean showtooltip var metadata modelmetadatafromlambdaexpressionexpression selfviewdata to be able to get the proper name for the property i am using the following code metadatathisplaynameand on the property of the modelview class i got thisplaynametitelthe problem is that i also need a description there is an attribute called thisplay and that has name and description but i do not see how to extract this with the metadata variable in the above code,['c#'] +122428,reading nonuniform data from file into array with numpy suppose i have a text file that looks like this33 3 46 12 23 10 23 11 23 12 23 13 23 14 23 15 23 16 24 10 24 11 24 12 24 13 24 14 24 15 24 16 25 14 25 15 25 16 26 16 27 16 28 16 29 16 33 17 33 18 33 19 34 17 34 18 34 19 35 17 35 18 35 19 36 19 41 32 41 33 42 32 42 33i would like to read each line into a separate array of integers as in pseudo codefor line in textfile currentarray firstline do stuff with currentarraywhere in the first iteration currentarray would bearray33 3and in the second iteration currentarray would bearray46 12until the last iteration when currentarray would bearray41 32 41 33 42 32 42 33basically i would like to have the functionality of the numpy function loadtxtcurrentarray loadtxtscienceverticestxt usecols except instead of usecols being able to specify the row egcurrentarray loadtxtscienceverticestxt userowsline,['python'] +122438,why doesnat wcf support serviceside timeouts weave recently thiscovered that wcf does not support timing out operations on the service side note service side not client side while the client thisconnects after the specified time our testing has shown that for netnamedpipebinding nettcpbinding and basichttpbinding no timeout that we specify will cause the service operation to stop once it has been invoked below are the specific binding configurations that we triedbindings netnamedpipebinding binding nametestservicebindingconfigurationnamedpipe receivetimeout05 sendtimeout05 closetimeout05 opentimeout05 netnamedpipebinding nettcpbinding binding nametestservicebindingconfigurationtcp receivetimeout05 sendtimeout05 closetimeout05 opentimeout05 nettcpbinding basichttpbinding binding nametestservicebindingconfigurationbasichttp receivetimeout05 sendtimeout05 closetimeout05 opentimeout05 basichttpbindingbindingsour test service implementation looks like thispublic class testserviceimpl itestservice public testresult testittestargs args var stopwatch new stopwatch stopwatchstart this is a contrived example but it shows that wcf never stops this thread while true consolewriteline0 i am running forever stopwatchelapsed return new testresult result args were argsargs using netnamedpipebinding and nettcpbinding our client app would timeout after 5 seconds but the service would continue running indefinitelythat brings to my questions a is this a bug is there a specific reason why wcf would not want to time out services if they run for longer than expectedfrom my perspective some of the potential negative issues with this include the default limit of service instances is 10 therefore if you have bad code in your service that runs forever and it is hit 10 times your service will completely shut down no new connections are acceptedthere isnat any visibility into the fact that services are running forever short of custom logging or possibly using performance countersany resources that are being used by the service call may be held indefinitely sql row page and table locks for example if there are no other mechanisms to timeout the operation,['.net'] +122443,objectivec class conformstoprotocol bug i have come across some strange behavior in my iphone objectivec appi am using some code to test an objectif class conformstoprotocolsomevar somefunctionthatreturnsaclass protocolmyprotocol nsexception raiseinvalid argument formatthe variables returned by somefunctionthatreturnsaclass must conform to the myprotocol protocol in this caseoddly when i have a class that looks like thisinterface baseclass nsobjectmyprotocolendinterface subclass baseclassendand when i call this fragment class conformstoprotocolsubclass class protocolmyprotocol it returns noalso this code failsclass conformstoprotocolnsstring class protocolnsobject also returns nowhile this code returns yesnsstring conformstoprotocolprotocolnsobjectis there anything i am missing in the docs or is this a bug of some sort i am on ios 42 if that matters any,"['iphone', 'objective-c']" +122452,no setbordercolor method found on uiview layer i have the following code in two different classes both subclasses of uiview in one place it works fine the border is drawn in the other place i get warnings about methods not being found and of course the border does not get drawn how is this possibleuiview test uiview alloc initwithframecgrectmake0 0 100100testbackgroundcolor uicolor redcolortestlayer setbordercolor uicolor bluecolor cgcolor no setbordercolor method found testlayer setborderwidth 10 no setborderwidth method found self addsubviewtest,"['objective-c', 'ios']" +122453,want to implement a vpn for just one application i looking for add support to a vpn for my softwarei known pptp and openvpn the two makes a systemwide binding installing a tap driver so all applications route their traffic to thenhow could i implement a vpn support for just my application therea s any library example hint or way to do it my software is actually made in c mfc using the standard casyncsocket,['c++'] +122460,int to unsigned int conversion i am just amazed to know that i cannot convert signed to unsigned int by castingint i 62unsigned int j unsigned intii thought i already knew this since i started to use casts but i cannot do it,['c++'] +122481,what is the relationship between awt swt swing safjsr296 jface the netbeans platform and the eclipse rcp i am looking for something that puts this alphabet soup into perspective it would be nice if it were light on the politics of the differences and tries to illuminate the similarities if there are any,['java'] +122488,net end vs formclose vs applicationexit cleaner way to close ones app sometimes when i use formclose when debugging my program although the form is closed the application is still running i noticed this behaviour when using the msgbox functioni have no thread nor timer running so what is the best way to close a net app i am using vbnetthanks,['.net'] +122508,log4j fileappender issue in tomcat server i am working on a webapplication and i have a requirment to generate log files at run time for my impex processhere is the use casei am validating an xml file and validation error is being handled by custom error handlerthis error hanlde will be passed to the underlying validator jaxb 2x validatorso i have to create the log file when the instance of this error hanlder is being createdwe are using log4j as logging apihere is the code to create log file at run timexmlerrorhandlerobject errorhandlernew xmlerrorhandlerobjectlogfilelocation logfilenameerrorhandlergetlogfilename validatorseterrorhandlererrorhandler validatorvalidatesourcei am creating the log file inside xmlerrorhandler constructor since this is the only point i have control here is the code for the log file creationfileappender appender try appender new fileappenderlayout sbtostring false logaddappenderappender logsetadditivityfalse logsetlevellevelwarn catch ioexception e eprintstacktrace everything is working fine and file is being created correctly as well being written by the logger to the respective placebut if i restart my server real problem starts and logger start appending the log content not only to its current log file but also for all file being created for this process while server is running here is the detailslets suppose i have 3 log abc files already at the location with 3 lines in each log file and c was the latest file created in the process so when i restart my serverby resrarting i mean i stopped tomcat from the console it some how appending data in to previos all log files in this fashinc has still 3 linesb has now 6 linesa has now 9 linesit seems that the appender i hace created is still open or have refrence not sure what exactly going onany help in this regard will be helpfull,['java'] +122529,c thread sync autoresetevent i have been using an autoresetevent to do syncronisation between threads some threadsaf call autoreseteventwaitone while waiting for another threadx to finish its workwhilst the threadx owning the autoresetevent does its work and then calls sethowever only one of the waiting threadsaf is unblocked how can i get them all to unblock when threadx finishes it is worki guess i am using the wrong syncronisation primitive what should i be using and how code samples would be idealdavid,"['c#', '.net']" +122531,static method in java can be accessed using object instance in java static methods are created to access it without any object instance it makes some sense to me but recently i came across one strange thing that static method in java can also be accessed through its object instance this looks pretty wierd to me does anyone of you know why this feature is provided by java whats the significance of allowing static methods getting accessed with as well as without instance,['java'] +122541,c library with c interface i need to write a library in c usable by client to do some operations in a remote server the only thing in the specific i have not done yet it is the c library need a c interface let me explain betterfrom client using this lib i need to do call something likeint operationvoid addrif int0 errorand sobut the library it is a class in cso my answer is need i a global variable holding the instance of class in the librarythe are some better option to develop this c interface of c classthx in advice for answer,"['c++', 'c']" +122557,monitor vs lock when is it appropriate to use either the monitor class or the lock keyword for thread safety in ceditit seems from the answers so far that lock is short hand for a series of calls to the monitor class what exactly is the lock call shorthand for or more explicitlyclass lockvsmonitor private readonly object lockobject new object public void dothreadsafesomethingwithlockaction action lock lockobject actioninvoke public void dothreadsafesomethingwithmonitoraction action what goes here updatethank you all for your help i have posted a another question as a follow up to some of the information you all provided since you seem to be well versed in this area i have posted the link what is wrong with this solution to locking and managing locked exceptions,"['c#', '.net']" +122587,java call main method of a class using reflection i need to call the main method of a java class from another main method using reflectionusage of reflection is a must so as to remove compile time dependency of the main class being calledstraightforward approach is not yielding as it recognizes only public and nonstatic methodsuggestions,['java'] +122592,enum class emulation or solid alternative for msvc 100 i am looking for a hacky kind of solution to the following problemgcc 44 accepts the following c0x codeenum class my enum value1 value2which allows the use like thismy enum e my enumvalue1with all the bells and whistles this brings i would like to make this code compatible with msvc 2010 to the effect that the usage syntax does not change i already pondered on this before here and the accepted answer works but the need for the two different names fo the enum and the enum values is killing the compatibility of the two approaches this makes it of course unusable to replace the c0x code as is i wondered if some undef and define trickery could work around this allowing me to use enum classlike syntax perhaps without the strict type safety etc but at least the same syntax thanks,['c++'] +122594,why does not a java constant divided by zero produce compile time error possible duplicateis 10 a legal java expression why does this code compileclass compiles public final static int a 70 public final static int b 103 public static void mainstring args if i take a look in the compiled class file i can see that b has been evaluated to 30 and that a still is 70as far as i understand the jsl an expression where you divide by zero is not a constantref jls 1528my above statement is due to this linea compiletime constant expression is an expression denoting a value of primitive typehence dividing by zero is not evaluated to a primitive valuewhat i really dont understand is why the compiler allows this anyway just to be clear my code above crashes runtime with a javalangexceptionininitializererroras it seems to me the compiler threats any final static variable as a constant and evaluates it compile time that means that the compiler already has tried to evaluate a but since it was a division by zero it just let it go through no compile time error but this seems very very bizarre the compiler knows it is a divide by zero and that it will crash runtime but nevertheless it does not flag a compile error can anyone explain to me why,['java'] +122597,literal notation for dictionary in c i currently have a websocket between javascript and a server programmed in c in javascript i can pass data easily using an associative arrayvar data test val test2 val2to represent this data object on the server side i use a dictionarystring string but this is more typingexpensive than in javascriptdictionarystring string data new dictionarystringstringdataaddtest valdataaddtest2 val2is there some kind of literal notation for associative arrays dictionarys in c,['c#'] +122599,what can you do with lisp macros that you cannot do with firstclass functions i think i understand lisp macros and their role in the compilation phasebut in python you can pass a function into another functiondef ffilename g try fh openfilename rb gfh finally closefh so we get lazy evaluation here what can i do with macros and not with functions as first class objects,['python'] +122602,implementing a splash screen in ios i am quite a newbie in cocoa objectivec and ios developmenti would like to implement a view that is just a splash screen and only last for a short time before routing to the main view do you have any idea on how i should implement that any tutorials or code samples i have some with multiple views but none with a timer to redirect to another one after a few seconds like i want to do,"['objective-c', 'ios']" +122603,is it ok to use multiple nsundomanagers with one coredata managedobjectcontext edit really nobody has any suggestions or thoughts on this have i asked the question wrongly somehowmy iphone app has a single managedobjectcontext with a moderately complicated data model i am now adding undo functionality and am not clear on how best to handle nested viewcontrollers as each layer might modify the data model apples docs point out consider an application that thisplays a list of books and allows you to navigate to a detail view that in turn allows you to edit individual properties of the book such as its title author and copyright date you might create a new book from the list screen navigate between two other screens to edit its properties then navigate back to the original list it might seem peculiar if an undo operation in the list view undid a change to the authoras name that was made two screens away rather than deleting the entire bookso whats the best way to implement this currently i am thinking to have each viewcontroller keep its own undomanager which would be active whenever it is on the screen so my understanding is that this would require the following steps for each vcadd a property myundomanager add an undomanager method returning mymanagedobjectcontextundomanagerin viewdidappear mymanagedobjectcontextundomanager myundomanager create first if nilin viewwillthisappear mymanagedobjectcontextundomanager nilon memory warning selfundomanager removeallactions on dealloc selfmyundomanager nilfor each model change selfundomanager setactionnamenslocalizedstringaxacoredata will handle the actual undoredo postingsin addition i have to remain firstresponderin viewdidappear self becomefirstresponderadd canbecomefirstresponder method returning yesin viewwillthisappear self resignfirstresponderreenable firstresponder upon subviews resign eg textfieldsso far that seems like it works even across loadunload cycles and is nicely selfcontained but i have several questionsfirst is this the best practice for implementing undo across multiple vcswill i get in trouble with my child vcs not doing their undos prior to my doing my earlier onesif so does that list capture everything i need to dowill managedobjectcontext get confused with multiple undomanagers being activedo i need to call processpendingactions before swapping undomanagers,['iphone'] +122607,android sort array how can i sort this array by date or namestring datetable new string212datetable00 20110101datetable01 name1datetable10 20110103datetable11 name2datetable200 20110216datetable201 name3,"['java', 'android']" +122613,fancybox width not applying using the following js the width is not being adjusted it does not get adjusted when i use 750 or 750pxacitypromptfancybox width 750i have posted on the fancybox forums about this and have not gotten a response,['javascript'] +122624,convert a list to a string in c how do i convert a list to a string in cwhen i execute tostring on a list object i getsystemcollectionsgenericlist1systemstring,"['c#', '.net']" +122625,what is the fastest way of deleting files in a directory except specific file extension i have seen questions like what is the best way to empty a directorybut i need to knowwhat is the fastest way of deleting all the files found within the directory except any zip files foundsmells like linq here or whatby saying fastest way i mean the fastest execution time,"['c#', '.net']" +122627,scrapy how to manage cookiessessions i am a bit confused as to how cookies work with scrapy and how you manage those cookiesthis is basically a simplified version of what i am trying to dothe way the website workswhen you visit the website you get a session cookiewhen you make a search the website remembers what you searched for so when you do something like going to the next page of results it knows the search it is dealing withmy scriptmy spider has a start url of searchpage urlthe searchpage is requested by parse and the search form response gets passed to search generatorsearch generator then yields lots of search requests using formrequest and the search form responseeach of those formrequests and subsequent child requests need to have it is own session so needs to have it is own individual cookiejar and it is own session cookiei have seen the section of the docs that talks about a meta option that stops cookies from being merged what does that actually mean does it mean the spider that makes the request will have its own cookiejar for the rest of its lifeif the cookies are then on a per spider level then how does it work when multiple spiders are spawned is it possible to make only the first request generator spawn new spiders and make sure that from then on only that spider deals with future requestsi assume i have to thisable multiple concurrent requests otherwise one spider would be making multiple searches under the same session cookie and future requests will only relate to the most recent search madei am confused any clarification would be greatly receivededitanother options i have just thought of is managing the session cookie completely manually and passing it from one request to the otheri suppose that would mean thisabling cookies and then grabbing the session cookie from the search response and passing it along to each subsequent requestis this what you should do in this situation,['python'] +122642,find the max of 3 numbers in java with different data types say i have the following three constantsfinal static int my int1 25final static int my int2 10final static double my double1 155i want to take the three of them and use mathmax to find the max of the three but if i pass in more then two values then it gives me an error for instance this gives me an errordouble maxofnums mathmaxmy int1 my int2 my double2please let me know what i am doing wrong,['java'] +122646,how do i float a div to the center i want to be able to center a div in the middle of a page but cannot get it to work i tried float center in css but it does not seem to work,"['html', 'css']" +122647,jackson builder pattern i would like jackson to deserialize a class with the following constructorpublic clinicstring name address addressdeserializing the first argument is easy the problem is that address is defined aspublic class address private addressmaplocationtype string components public static class builder public builder setcitystring value public builder setcountrystring value public address create and is constructed like this new addressbuildersetcityfoosetcountrybarcreateis there a way to get keyvalue pairs from jackson in order to construct the address myself alternatively is there a way to get jackson to use the builder class itself,['java'] +122649,how to set the margin or padding as percentage of height of parent container i had been racking my brains over creating a vertical alignment in css using the followingbase backgroundcolorgreen width200px height200px overflowauto positionrelativevertalign paddingtop50 height50and used the following div structurediv classbase div classvertalign content here divdivwhile this seemed to work for this case i was surprised that when i increased or decreased the width of my base div the vertical alignment would snap i was expecting that when i set the paddingtop property it would take the padding as a percentage of the height of the parent container which is base in our case but the above value of 50 percent is calculated as a percentage of the width is there a way to set the padding andor margin as a percentage of the height without resorting to using javascript thanks in advance,"['html', 'css']" +122650,is c0x officialy released do major compilers support it i am not sure if release is the right word as it is not software but a standardwhat i mean is is the c0x standard finished is it still under developmentdo major compilers support it partially completely,['c++'] +122658,trouble yielding inside a blocklambda i have the following ruby code func1 generates a sequence of items derived from x func2 does something with the items generated by func1def testx func1 func2 func1callx do y func2cally endendfunc1 lambda do x for i in 1 5 yield x i endendfunc2 lambda do y puts yendtest2 func1 func2 should print 2 4 6 8 and 10this does not work of coursetestrb11 no block given localjumperror from testrb10in each from testrb10 from testrb4in call from testrb4in test from testrb20,['ruby'] +122666,why use percentage value for divs width in css i am reading articles about css i found out that many of writers suggest to use value for divs width or heighti am using pixels all the timewhy should i use value for divs width or height instead of pixelswhat are the advantages,['css'] +122670,jquery templates vs partial views in aspnet mvc i am taking a look at jquery templates it looks really interesting easy syntax easy to use very cleanhowever i cannot really see why it is better to use jquery templates instead of simply fetching partial views via ajax it simply seems like the partial views would be much easier to maintain and helps to avoid duplication of codei want to use jquery templates but when would it be better than partial views,['jquery'] +122671,invalid type argument of c structs i am trying to access items in an array of structs and print the structs fields as followsprintlistalbum a int numofstructs int i int j fori 0 i numofstructs i printfnumberdn i1 printfs aifield2 printfs aifield2 printfd aifield3 forj 0 j ainumofstrings j printfs aistringsj printfn but i get loads of errors as suchinvalid type argument of what am i doing wrong with this pointer,['c'] +122672,should generated documentation go into source control i have been recently finally getting around to documenting one of my open source projects the project is a class library for net i am using doxygen for generating html documentation from the source code now my question is should i store the html files doxygen produces in my source control,['.net'] +122675,jquery dollar sign as function argument i understand javascript closures and i have seen this done in native jsfunction all js code herebut what does adding the jquery spice dofunction all js code herejquery,['jquery'] +122680,php apc potential cache slam averted for key i am receiving this error while trying to use apc store i googled it and saw that this was apc timebomb bug and saw some fixes which suggested adding apcslam defense off to phpinii need to know whether this has happened because of a programming error and if yes how to fix itthis is the code segmentif data apc fetchfoo an array data else couple of lines apc storecircles an array this is where i get the errorthis script will be called frequently in my deployed systemi hope i have provided enough infothanks in advance,['php'] +122691,java pdf renderer what is the best library to render pdf files in javai want a library which ispure java or any platform independent librarysupports new pdf documentsbe free,['java'] +122706,windowtop window false condition in ie8 for some reason using thewindowtop windowcondition in ie8 always evaluates to false in other browsers it works finewhat is the reason for this and is there any other way for this condition to work crossbrowserthanksjoel,"['javascript', 'jquery']" +122721,when do i use a dot arrow or double colon to refer to members of a class in c coming from other cderived languages like java or c to c it is at first very confusing that c has three ways to refer to members of a class ab ab and ab when do i use which one of these operators note this is meant to be an entry to stack overflows c faq if you want to critique the idea of providing an faq in this form then the posting on meta that started all this would be the place to do that answers to that question are monitored in the c chatroom where the faq idea started out in the first place so your answer is very likely to get read by those who came up with the idea,['c++'] +122737,garbage collector tuning in ruby 19 i know about gcenablethisable but is there any way of controlling the ruby 19 garbage collector in more detail when profiling my code using perftoolsrb i notice that the gc stands for up to 30 of the total samples and i would like to see if it is possible to tune the gc to decrease this number are there any environment variables or other means by which you can set the number of heap slots the malloc limit etc like you can with ree,['ruby'] +122743,proper javascript inheritance i am wondering whether it is possible to inherit constructor in javascript in the following example i would like the moveable to assign x and y arguments to thisx and thisy respectivelly as i defined in sprite also what would be the best way but still short and readable to define the prototype without creating the instation of ancestor it would be best to assign it in the class itself not in the outside scope as i it is nowfunction spritex y thisx x x 0 thisy y y 0 thisgetpos function return x thisx y thisy function moveablex y moveableprototype new sprite,['javascript'] +122747,how to return a view for httpnotfound in aspnet mvc 3 is there a way to return the same view every time a httpnotfoundresult is returned from a controller how do you specify this view i am guessing configuring a 404 page in the webconfig might work but i wanted to know if there was a better way to handle this resultedit follow upi ended up using the solution found in the second answer to this question with some slight tweaks for aspnet mvc 3 to handle my 404s how can i properly handle 404s in aspnet mvc,['asp.net'] +122757,why is the derived clas destructor invoked on a const reference to the base class in gmans answer here the destructor of the restore base class is not virtual so i keep wondering how exactly that works normally youd expect the destructor of restorer base to be executed only after the object goes out of scope but it seems that the derived restorer holder destructor is really called anyone care to enlighten me,['c++'] +122788,virtualenv nositepackages is not working for me virtualenv nositepackages v1cd v1scriptsactivatebatpython c import django no problem herewhy does it see the django package it should give me an import error right,['python'] +122790,error running gem install on windows 7 64 bit i just installed ruby 192p136 using the installer from rubyinstallerorg and now i am trying to install rails when i do gem install rails i get the following errorcusersclaytonusagem install railserror while executing gem errnoeinval invalid argument phere are the ruby and gem versions i am runningcusersclaytonusaruby vruby 192p136 20101225 i386mingw32cusersclaytonusagem v137update found the solution here how to stop the gem utility from accessing my home directoryadded the following to the start of my bingemenvhome druby192,"['ruby-on-rails', 'ruby']" +122799,how to serialize to json in qt how can i json serialize a qvariant or other type of data in qt i do not want to use an external third party library like qjson,['c++'] +122802,using switch statement to handle button clicks i am trying to wrap my head around views listeners etc i have an activity with 2 buttons buttonplay and buttonstop my problem is i cannot wrap my head around the views and listeners completely enough to generate a working switch statementfor example i would like to create a single listener and somehow use it to determine which button is clicked then somehow use the id of the button clicked in my switch statement but everything i find online seems to use separate listeners for every button and then somehow use the view as the argument to the switch statementi realize the code below is not correct but am looking for what changes i would need to accomplish the abovei want to control the mediaplayer depending on which button is clicked i have button b1 button findviewbyidridbuttonplay b1setonclicklistenernew viewonclicklistener public void onclickview v perform action on click switchvgetid case ridbuttonplay play voicefile mediaplayercreategetbasecontext rrawvoicefilestart break case ridbuttonstop stop mediaplayer mediaplayercreategetbasecontext rrawvoicefilestop break ultimately i would like the most straighforward way to switch on whatever button is clicked i believe a big part of my confusion stems from the way onclicklisteners and views are used in this context,['android'] +122810,python correctness ie lint analyzing for notepad does anyone know of anything like pylint or pychecker for notepad or perhaps how to use pylint in notepad,['python'] +122815,java indexof method for multiple matches in string i had a question about the indexof method i want to find multiple cases of x in a stringsuppose my string is x is x is x is x i want to find x in all of its index positionsbut how do you do this for multiple cases is this even possible with indexofi did int temp strindexofxit find the first x i tried to do a for loop where i is initialized to length of string and this did not work since i kept finding the first x over and overfor int y temp1 y 0y int temp strindexofx systemoutprintlntempbut this does not work am i supposed to use regex because i do not really know how to use regex methodany help would be appreciated thanks,['java'] +122821,rails detect if users very first visit i am trying to make the user fill out a questionnaire if it is their first time visiting the site my controllers are set up like thisclass maincontroller basecontrollerendclass basecontroller applicationcontroller before filter first time visitingendclass applicationcontroller actioncontrollerbase def first time visiting if sessionfirst timenil sessionfirst time 1 redirect to questionnaire path unless current user end endendwhen i close the browser and reopen it though i always get redirected to the questionnaire,['ruby-on-rails'] +122828,missing button placed after listview hi i have a layout with 3 button at the top in a row and then a listview followed by a button below the listviewthis is my layoutxml filelinearlayout xmlnsandroidandroidorientationverticalandroidlayout widthfill parentandroidlayout heightfill parentrelativelayout xmlnsandroid androidlayout widthfill parent androidlayout heightwrap content button androidididbtn top10 androidlayout widthwrap content androidlayout heightwrap content androidtexttop 10 button androidididbtn top100 androidlayout widthwrap content androidlayout heightwrap content androidtexttop 100 androidlayout torightofidbtn top10 button androidididbtn showall androidlayout widthwrap content androidlayout heightwrap content androidtextshow all androidlayout torightofidbtn top100 listview androidididlv device androidlayout widthfill parent androidlayout heightwrap content androidlayout belowidbtn top10 androidlayout aboveidlv device button androidididbtn clearresult androidlayout widthfill parent androidlayout heightwrap content androidtextclear results androidlayout belowidlv device relativelayoutthis will give a result like this if i add some values to the listview then its ok the button below will be showbut if the listview becomes larger than the screen size then the button below that will not be visible even after scrolling to the bottom of the listviewhow to solve this issue i do not want button to be fixed at the bottom of the screen i want the button to be show at the end of the listview only,['android'] +122831,habtm uniqueness constraint i have two models with a habtm relationship user and roleuser has and belongs to many rolesrole belongs to useri want to add a uniqueness constraint in the join users roles table that says the user id and role id must be unique in rails would look likevalidates uniqueness of user scope roleof course in rails we do not usually have a model to represent the join relationship in a habtm associationso my question is where is the best place to add the constraint,['ruby-on-rails'] +122832,passing systemdatalinqtable into generic function i am trying to make a generic function that takes in a systemdatalinqtabletgeneric function public int gettmydatacontext db systemdatalinqtablet table string propertyvalue where t imatchable t prop tablefirstordefaulttp pnametolower propertyvaluetolower if prop null return propid interface so that i can access id propertypublic interface imatchable int id get set my errorthe type t must be a reference type in order to use it as parameter tentity in the generic type or method systemdatalinqtablei am not sure what i am doing wrong,['c#'] +122845,android samsung camera app would not return intentgetdata i am developing an app where an image taken from the native camera app is to be shown to the userthe code i did is intent intent intent new intentandroidmediaactionimage capturestartactivityforresultintent take picture result onactivityresultint requestcode int resultcode intent returnintent ifrequestcode take picture picture from camera if resultcode activityresult ok ifreturnintent null try get the file path where the image is stored this runs fine on all devices except samsung ones uri selectedimage returnintentgetdata ifselectedimage null ifreturnintentgetextras null returnintentgetextrasgetappconstantsdata null but i get the image bitmap here means the image is stored in thisk bitmap bmp bitmap returnintentgetextrasgetappconstantsdata catch exception e the problem here is the above code works fine on all devices i tried htcs ses but it somehow fails in the samsung ones the uri selectedimage returnintentgetdata never returns anything as my entire app is built over this logic of file path storing i am not able to proceed is there any solution people,['android'] +122881,irony tutorial on evaluating ast nodes i have defined a simple grammar in irony and generated a nice compact astnow i am trying to figure out how to evaluate it problem is i cannot find any tutorials on how to do thisi have defined just 2 ast nodesclass taglistnode astnode public override void initparsingcontext context parsetreenode treenode baseinitcontext treenode asstring taglist foreach var node in treenodechildnodes addchildnull node public override void evaluatenodeironyinterpreterevaluationcontext context astmode mode foreach var node in childnodes nodeevaluatenodecontext astmoderead class tagblocknode astnode public astnode content public override void initparsingcontext contextparsetreenode treenode baseinitcontext treenode asstring treenodechildnodes0findtokenandgettext content addchildnull treenodechildnodes1 public override void evaluatenodeevaluationcontext context astmode mode contextwritestringformat0 asstring contentevaluatenodecontext astmoderead contextwritestringformat0 asstring this will generate the following output htmlheadtitletitleheadbodyh1h1pbodyhtml314159265358979whereas the output i want ishtml head titlepage titletitle head body h1headerh1 pparagraph 1p p314159265358979p bodyhtml i do not think i am supposed to be using contextwrite the samples show pushing stuff onto contextdata and popping them off but i am not quite sure how that worksi am guessing pi gets tacked on at the end because it is automatically pushed onto contextdata and then one element is popped off at the end i am not really suresome pointers or a link to a tutorial would be nicealso how am i supposed to handle the different node types each tag can have 4 different types of content another tag a string literal a variable or a number should i be writing things like ifnode is stringliteral in the evaluatenode method or whati have found this one but they just loop over the ast and do not take advantage of evaluatenodeand then this one which replaces a single value in the data stackbut does not really explain how this gets outputted or anythingto be clear i specifically want to know how to override the evaluatenode methods in ironyastastnode to do what i wantokay i have traced that tidbit at the end to this line if evaluationcontexthaslastresult evaluationcontextwriteevaluationcontextlastresult environmentnewlinewhich is included in the default evaluation routineperhaps it works well for a calculator app but not so much in mine trying to figure out how to bypass the script interpreter now but then i do not know how to set the globals,['c#'] +122885,passing values to the layout in zend framework i am facing a problem in zendframework related to layout here i have to pass some values to the layout that will be used to thisplay the topranking users of the sitesince i am new to zendframework i am not able to find any way to do soif you have any code idea or link please provide methanks in advance,['php'] +122898,how can i wipe data from my hsqldb after every test i had some junit tests already written in my project which used to populate data in the setup method now i have added maven to my project and i want to execute all test cases form maven ie using mvn test the problem now is that my data base is not cleared after every test class has run i need to clear the hsqldb after test cases of each class have run,['java'] +122915,how to get file extension from save file dialog i would like to be able to save image according to extension that is entered in the save file dialog i have found out that simply entering eg jpg does not cause the save method to use this format of courseparsing the extension and then using eg switch and setting correct format sounds a bit ackward to me or there is no better way,['c#'] +122939,how can i increase username length of phpmyadminmysql user account how can i increase username length of phpmyadminmysql user accountedit sorry for my mistake its phpmyadminmysql user account not any mysql tableanswer according to this article i should not do this,['mysql'] +122946,how do i sort a nsmutablearray by nsstring length i have a nsmutablearray containing nsstrings of various lengths how would i go about sorting the array by the string length,"['iphone', 'objective-c', 'ios']" +122949,wpf something standard and similar to the splitcontainer is there something standard and similar to the windows forms splitcontainer in wpf i am a bit lost with grids because controls seem not to be inside the cells but over them si did some googling but i do not know exactly what to write in the search field,['c#'] +122950,python numpy boolean array negation in where statement withimport numpy as nparray get arrayi need to do the following thingfor i in rangelenarray if randomuniform0 1 prob arrayi not arrayiwith array being a numpyarrayi wish i could do something similar toarray npwherenprandomrandlenarray prob not array arraybut i obtain the following result referring to not arraythe truth value of an array with more than one element is ambiguous use aany or aallwhy can i take the value of array but not its negationcurrently i solved witharray npwherenprandomrandlenarray prob array 1 arraybut it looks really clumsy to methank you for your helpps i do not care if the statement modifies array or not i just need the result of the operationjust another question i want to do this change for 2 reasons readability and efficiency is there a real performance improvement with it thank you again,['python'] +122962,running several system commands in parallel i write a simple script that executes a system command on a sequence of filesto speed things up i would like to run them in parallel but not all at once i need to control maximum number of simultaneously running commandswhat whould be the easiest way to approach this,['python'] +122973,continue and break with an extended scope is there a possibility for a continue or break to have a bigger scope than the currently running loopin the following example i desire to to continue on the outer forloop when expr is true although it is called in the inner forloop so that neither some inner code nor some outer code is executedforint outercounter0outercounter20outercounter forint innercounter0innercounter20innercounter ifexpr continue outer here i wish to continue on the outer loop some inner code some outer codein the above,"['c#', '.net']" +122976,is this a circular dependency is this code a example of circular dependencypackage exprimport sheetsheetpublic class adressexpr implements expr private address address private sheet sheet public double valuesheet sheet return sheetvalueaddress public interface expr public double valuesheet sheetpublic class adress omissionspackage sheet import expraddress import exprexprpublic class sheet implements supersheet private map address expr map public double valueaddress address return mapgetaddressvaluethis public interface supersheet public double valueaddress addressi know the example is bad programming but does not the interface prohibit the circular dependency due to the value method,['java'] +122977,what does md5 do with my password string i set my password 13579 and the authentication mode forms convert it to md5 like mexg8klnq0twpfvaqytula but after couples of minutes i tried again and create another one by the same password 13579 but it converts to different one like um4gh8ho8cvoe0slg6oykawhat is the structure of md5 is it related to my username and time i want to create the same password for my users so i could not create the same password if it is depend on time,['.net'] +122996,bulk rename files in a folder php i have 10 images in a folder which has sku word in all the images for exampleswv1716bnskuzoom1jpgwv1716blskuzoom3jpgwhat i need to do is read all the filenames and rename it to the followingwv1716bnzoom1jpgwv1716blzoom3jpgso remove sku from filename is it possible in php to do bulk renaming,['php'] +123012,scriptmanagerregisterstartupscript code not working why i have used code like this in the past to successfully pop up an alert message on my aspnet webpage now it is not working i cannot figure out whyscriptmanagerregisterstartupscriptthis typeofpage uniqueid alertthis pops up trueany ideas,"['javascript', 'asp.net']" +123026,how can i transform xy coordinates and heightwidth on a scaled image to an original sized image related questioni am trying to do the same thing as in the linked question but with c i am showing a scaled image and am allowing a user to select an area to crop however i cannot just take the x1y1 x2y2 coordinates from the scaled image selection and crop that from the original i have tried doing some basic math like in the other question but that is obviously not the right approach either it is definitely closer editoriginal image dimensions w 1024 h 768scaled image dimensions w 550 h 412i start with an image say 1024x768 i want it to fit as large as possible in a 550x550 box i am using the following method to get the scaled image size while maintaining aspect ratio then i do a basic resize to those new dimensionsas for a selection area it can be anything 00 to 100100private static rectangle maintainaspectratioimage imgphoto rectangle thumbrect int sourcewidth imgphotowidth int sourceheight imgphotoheight int sourcex 0 int sourcey 0 int destx 0 int desty 0 float npercent 0 float npercentw 0 float npercenth 0 npercentw floatthumbrectwidth floatsourcewidth npercenth floatthumbrectheight floatsourceheight if we have to pad the height pad both the top and the bottom with the difference between the scaled height and the desired height if npercenth npercentw npercent npercenth destx intthumbrectwidth sourcewidth npercent 2 else npercent npercentw desty intthumbrectheight sourceheight npercent 2 int destwidth intsourcewidth npercent int destheight intsourceheight npercent rectangle retrect new rectanglethumbrectx thumbrecty destwidth destheight return retrect,['c#'] +123031,standard vector and boost array which is faster how the performance of boostarray compares to that of stdvector and which factors have significant influence on it,['c++'] +123041,java dependency injection xml or annotations annotations becoming popular spring3 supports them cdi depends on them heavily i can not use cdi with out of annotations rightmy question is whyi heard several issuesit helps get rid of xml but what is bad about xml dependencies are declarative by nature and xml is very good for declarations and very bad for imperative programmingwith good ide like idea it is very easy to edit and validate xml is not itin many cases there is only one implementation for each interface that is not truealmost all interfaces in my system has mock implementation for tests any other issuesand now my pluses for xmlyou can inject anything anywhere not only code that has annotationswhat should i do if i have several implementations of one interface use qualifiers but it forces my class to know what kind of injection it needsit is not good for designxml based di makes my code clear each class has no idea about injection so i can configure it and unittest it in any waywhat do you think,['java'] +123051,stringisnullorempty or isempty i just noticed on string they have a lot of extension methods that i guess i never noticed on stringssome are likeisempty seems to be equivalent to stringisnullorempty asint seems to be equivalent to converttoint32string does it throw exception as welli am just wonder do they use the same code under the hook and these are just away to reduce typing or is more going onsome do seem to be missing though like stringisnullorwhitespaceeditsorry when i said stringisnullorwhitespace is missing i ment that there was no extension method i do have that method is i write what i do aboveit also seems that these are not standard in the framework so i am trying to figure out where they came fromi am not sure if resharper added these or if some other reference i have i do not think i ever imported any extension pluginwhen i click definition over isemptyi get thisregion assembly systemwebwebpagesdll v4030319 cprogram files x86microsoft aspnetaspnet web pagesv10assembliessystemwebwebpagesdllendregionusing systemusing systemruntimecompilerservicesnamespace systemwebwebpages summary provides utility methods for converting string values to other data types public static class stringextensions summary converts a string to a strongly typed value of the specified data type parameters value the value to convert type parameters tvalue the data type to convert to returns the converted value public static tvalue astvaluethis string value summary converts a string to the specified data type and specifies a default value parameters value the value to convert defaultvalue the value to return if value is null type parameters tvalue the data type to convert to returns the converted value public static tvalue astvaluethis string value tvalue defaultvalue summary converts a string to a boolean truefalse value parameters value the value to convert returns the converted value public static bool asboolthis string value summary converts a string to a boolean truefalse value and specifies a default value parameters value the value to convert defaultvalue the value to return if value is null or an invalid value the default is false returns the converted value public static bool asboolthis string value bool defaultvalue summary converts a string to a systemdatetime value parameters value the value to convert returns the converted value public static datetime asdatetimethis string value summary converts a string to a systemdatetime value and specifies a default value parameters value the value to convert defaultvalue the value to return if value is null or an invalid value the default is the minimum time value on the system returns the converted value public static datetime asdatetimethis string value datetime defaultvalue summary converts a string to a systemdecimal number parameters value the value to convert returns the converted value public static decimal asdecimalthis string value summary converts a string to a systemdecimal number and specifies a default value parameters value the value to convert defaultvalue the value to return if value is null or invalid returns the converted value public static decimal asdecimalthis string value decimal defaultvalue summary converts a string to a systemsingle number parameters value the value to convert returns the converted value public static float asfloatthis string value summary converts a string to a systemsingle number and specifies a default value parameters value the value to convert defaultvalue the value to return if value is null returns the converted value public static float asfloatthis string value float defaultvalue summary converts a string to an integer parameters value the value to convert returns the converted value public static int asintthis string value summary converts a string to an integer and specifies a default value parameters value the value to convert defaultvalue the value to return if value is null or is an invalid value returns the converted value public static int asintthis string value int defaultvalue summary checks whether a string can be converted to the specified data type parameters value the value to test type parameters tvalue the data type to convert to returns true if value can be converted to the specified type otherwise false public static bool istvaluethis string value summary checks whether a string can be converted to the boolean truefalse type parameters value the string value to test returns true if value can be converted to the specified type otherwise false public static bool isboolthis string value summary checks whether a string can be converted to the systemdatetime type parameters value the string value to test returns true if value can be converted to the specified type otherwise false public static bool isdatetimethis string value summary checks whether a string can be converted to the systemdecimal type parameters value the string value to test returns true if value can be converted to the specified type otherwise false public static bool isdecimalthis string value summary checks whether a string value is null or empty parameters value the string value to test returns true if value is null or is a zerolength string otherwise false public static bool isemptythis string value summary checks whether a string can be converted to the systemsingle type parameters value the string value to test returns true if value can be converted to the specified type otherwise false public static bool isfloatthis string value summary checks whether a string can be converted to an integer parameters value the string value to test returns true if value can be converted to the specified type otherwise false public static bool isintthis string value,"['c#', '.net']" +123064,override compile error implementing an interface eclipse jdk160 23 linux i am getting compile errors in eclipse when using the override annotation for a class that is implementing an interfacecompiler compliance level is set to java 60i am using the latest version of the 60 jdkerror the method methodname of type classname must override a superclass methodsame code works fine on mac with comparable configurationpublic interface channelif public boolean cansendnarrowcast public boolean cansendbroadcast public class facebookchannel implements channelif override public boolean cansendnarrowcast return true override public boolean cansendbroadcast return true,['java'] +123085,changing default starting position of anchor i have a url with an anchor that is working as it shouldsitecomitemidcomment233when opened the anchor will be positioned at exactly the top of the pagehow do i change the starting point let us say i want it to be 50px down from the top the reason i am needing this is because i have fixed layers at the top of the page so the comment is appearing overlapped behind the fixed header div just in case because of crossbrowser compliance i prefer a solution that does not involve changing the container of the comment to fixed and positioning top minus the height of the header,"['javascript', 'jquery', 'html', 'css']" +123087,deprecate class inheritance only i would like to deprecate only the extension of a given class not all the methods and fields contained within a class using the deprecated annotationthat is a warning will occur if you extend a given class but references to methods or fields will not trigger a warning there are already several classes that extend this class and i want to have the deprecation warnings target these clients i cannot break them yet but they can be recompiled abi compatibility not neededis it possible in java 16 jdt compiler,['java'] +123092,load large image from server on android i am trying to thisplay a jpg file from a server into an imageview when i try to load a smaller image 300x400 there are no problems but when i try to load a full size picture 2336x3504 the image will not load the file size of the image is only 2mb i do not get any errors in logcat and there are no exceptions thrown it simply would not load the image i also tried using thisbitmapfactoryoptions optionsnew bitmapfactoryoptionsoptionsinsamplesize 8bitmap preview bitmapbitmapfactorydecodestreamisnulloptionsthis does not do anything to help load the large files but it does resize the smaller image like it is suppose to i did add the large picture to my resources and tested it as if it was embedded in the app and it worked fine just would not work on the server i have been working all day on this and cannot seem to figure out how to load these large pictures can anyone help me out with this thanks for any info here is the link where i found the above code and have been playing with the other examples but still not getting it to work edithere is the code i am using to load the imagepublic static bitmap getbitmapfromurlstring src bitmap bmimg url myfileurl null try myfileurl new urlsrc httpurlconnection conn httpurlconnectionmyfileurlopenconnection connsetdoinputtrue connconnect inputstream is conngetinputstream bitmapfactoryoptions optionsnew bitmapfactoryoptions optionsinsamplesize 16 bmimg bitmapfactorydecodestreamis null options return bmimg catch exception e todo autogenerated catch block logderror etostring return null here is the logcat screenshot could not figure out how to copy the text appropriately in eclipse i cleared the log right before i hit the button to load the image so all you see is what happens when i hit that button i erased the company and app names where you see com assume its commycompanymyapp,['android'] +123097,facebook fql like operator possible duplicatesdoes facebook fql contain the sql like operatorfacebook query using fql is it possible to use the familiar sql like operator within facebooks query languagei have tried running the query in the fql test console but it does not work i am wondering if i am missing something or if it is simply not possibleselect link id from link where url like frljtjnc8so and owner 421235go here to test,['sql'] +123106,choice of algorithm for indexof method in java i was just looking at the implementation of the java string clas indexof method and it seems the author of the code uses the brute force algorithm to find the substring in a given string that is the approach runs in omn where m and and are the length of the source and target strings respectivelywhy did not the author use a more efficient algorithm like rabinkarp which has a runtime complexity of om n if a good hash function is provided i might be missing out on the complete knowledge behind the reason for this implementation and hence wanted to understand,['java'] +123144,storing day and month without year i am having trouble with figuring out the best way to store some data in my database i have got to store ddmm dates in a database but i am not sure of the best way to store this so that it can be easily sorted and searchedbasically a user will be able to save important dates in the format ddmm which they will be reminded of closer to the daythe date data type does not seem completely appropriate as it includes year but i cannot think of another way of storing this data it would be possible to include a specific year to the end of all occasions but this almost does not seem right,['mysql'] +123151,how to deduce array size from an enum template argument how should i change the code below so that arrayindex array is enough and the size is automatically deduced from the enumeven if the enum changes it is guaranteed that it contains size referring to the correct sizetemplate typename enum int nclass array public int operatorenum index return arrayindex private int arraynenum index x y size int main arrayindex size array arrayx 1 return 0update as for arraytype means youre creating an array of type objects jerry and the name of class template is a bit misleading nawaz actually i am creating customsqlquerymodeltablecolumns the above is just a simplified code nothing more jerry and nawaz are rigth this simplified code is unfortunate,['c++'] +123159,how to use variables already defined in configparser i am using configparser in pythonconfigini isgeneralname my namebase dir homemyhomeexpexe dir base dirbinhere i want exp dir becomes homemyhomeexpbin not base dirbinit means base dir would be substituted to homemyhomeexp automatically,['python'] +123164,python random access file is there a python file type for accessing random lines without traversing the whole file i need to search within a large file reading the whole thing into memory wouldnt be possibleany types or methods would be appreciated,['python'] +123166,how do i set the httponly flag of a cookie with javascript i am trying to create a cookie with the httponly flag enabledwhile there seems to be a plethora of resources about how to do it in java and net i need to do it in javascripthere is my currently failing functioncreatecookie functionnamevaluedays if days var date new date datesettimedategettimedays24606010 var expires expiresdatetogmtstringelse var expires documentcookie namevalueexpires domainmydomaincom path httponlythanks,['javascript'] +123175,checking to see if user did not input anything in cin how do you check to see if the user did not input anything at a cin command and simply pressed enter,['c++'] +123187,is bundle id suffix the same as the bundle identifier in infoplist what is bundle id suffix tutorials said to use bundle id from infoplist i can notice bundle identifier in infoplist its value is comyourcompanyproduct namerfc1034identifiershould i type comyourcompanyproduct namerfc1034identifier as bundle id suffix,['iphone'] +123201,why is jython much slower than cpython despite the jvms advances no flame wars please i am admittedly no fan of java but i consider the jvm to be a fairly decent and welloptimized virtual machine it is jitenabled and very close to the common denominator of the prevalent cpu architectures i would assume that the cpython runtime would be farther from the metal than a corresponding jvmbased runtimeif my assumptions are correct could someone explain to me why jython suffers such a major loss in performance compared to cpython my initial assumption was that the jvm was simply designed for static languages and it was difficult to port a dynamic one to it however clojure seems to be an counterexample to that line of argumenton the other hand ironpython seems to be doing fine i believe the the lead developer on both projects wereare the same so the argument that code design and implementation in one is significantly better than the other does not seem likelyi cannot figure out what the precise reason is any help will be appreciated,['python'] +123202,whats the use of c4711 function selected for inline expansion visual c warning according to msdn visual c can emit c4711 warning function x selected for inline expansion if the compiler decides to inline a function that was not marked inlinei do not see how this warning can be useful suppose i compile my code and see this warning now what why would i care,['c++'] +123211,receive image data as json and injecting it into the dom i am packaging an image into json and sending it to the client on the client side i wish to thisplay this data as a image i am not sending the image url via json i am trying to send the whole image data itselfjson image data that i receive in the client looks like thispng aaia34aa wcalaqahaa ana2aamaj3axa14ana jaana eayaarida12pa caayya a34a12baa a1a ada,"['javascript', 'jquery']" +123213,defaults for to json in rails with include let us say i have a model post which belongs to a user to convert to json i do something like thisreplyto jsoninclude user only email id only title idhowever i want to set some defaults for this so i do not have to specify only everytime i am trying to override as json to accomplish this when i add as json in user model it is called when i do userto json but when user is included in replyto json my overriden as json for user is ignoredhow do i make this work thanks,['ruby-on-rails'] +123233,what the new mean in the following in the interface i saw the following public interface itest itestbase new string item get set i want to know the meaning of new here,"['c#', '.net']" +123247,c check printer status in my application windows seven vs2010 i have to decrement a credit counter after successfully printing an imageanyway before starting the entire process i would like to know about printer status in order to alert the user on paper out paper jam and so onnow looking around i found several example that use windows wmi but never works using this snippet for example the printer status is always ready also if i remove the paper open the cover turn off the printerthe printer status is always good also now that i am testing from office the printer that is comfortably turned off at homehave i to detonate the device by dynamite in order to have a printer error statusthis is the code i have usedmanagementobjectcollection mgmtcollectionmanagementobjectsearcher mgmtsearcherperform the search for printers and return the listing as a collectionmgmtsearcher new managementobjectsearcherselect from win32 printermgmtcollection mgmtsearchergetforeach managementobject objwmi in mgmtcollection string name objwminametostringtolower if nameequalsprinternametolower int state int32parseobjwmiextendedprinterstatustostring if state 1 other state 2 unknown state 7 offline state 9 error state 11 not available throw new applicationexceptionhope you are finally offline state int32parseobjwmidetectederrorstatetostring if state 2 no error throw new applicationexceptionhope you are finally offline where printername is received as parameterthank you in advice,['c#'] +123249,help with hashtables which contents string arrays in c i have a code like this hashtable ht new hashtablehtlsn new string5mathphischemgeombiohtweek new string7montuewedthufrisatsunhtgrp new string510a10b10c10d10enow i want to get values from this ht like below string s htlsn0but it gives error so how can i solve this problem,['c#'] +123250,appconfig connection string relative path i need to set in the appconfig the sqlite connection string i want to set the path relative to the debugrelease folders the database file will be copied to those foldersadd nameemailssqlite connectionstringdata sourcecuserstestdocumentsvisual studio 2008projectstestconsoleemailsdataemaildatabasesqlite providernamesystemdatasqliteand i want to have something like add nameemailssqlite connectionstringdata sourcedataemaildatabasesqlite providernamesystemdatasqliteis that possible,['.net'] +123269,which eclipse files to exclude from subversion repo we as a development team were always happy with subversion and eclipse we checked in everything and everything was fine until we had a new hire whos using anything but eclipse rad his rad checkins are currently polluting the svn repo withholding our eclipse checkouts to finish buildingone solution may be to force eclipse in the new hirers throat another more subtle and probably more suitable approach is to make our project ide agnosticinstead of removing the files by trial and error i hope to learn a quick and reliable solution i already learned that i shouldremove files and add them to the svnglobal ignore i am wondering is therea way to make this project wideinstead of having everybody fixingtheir own svn config something to add to your root svn directoryi am alsolooking for a list or even script toremove the eclipse files anddirectories from the svn repoproject settings classpathexternaltoolbuilders springbeans without running the risk ofcompletely ruining the workspace i amalso intested in finding the quickestway of restoring the workspace aswere using maven for softwareproject management i can do mvneclipseeclipse in the root ofworkspace but how do i find what theproper wst settings are and what is the quickest way or restoring your path settings in eclipse i thought that many people would have been faced with the same use case and consequently had the same questions but i have not found anything on google yet hopefully somebody here can point me in the right direction,['java'] +123284,strange iphone crash log can anybody tell me the reason for this crashspecially i am concerned about this application specific informationimixtapes1185 has active assertions beyond permitted time sbprocessassertion 0x66bc490 identifier uikitbackgroundcompletiontask process imixtapes1185 permittedbackgroundduration 60 reason finishtask owner pid1185 preventsuspend preventidlesleep sbprocessassertion 0x66ade50 identifier uikitbackgroundcompletiontask process imixtapes1185 permittedbackgroundduration 60 reason finishtask owner pid1185 preventsuspend preventidlesleep elapsed total cpu time seconds 106580 user 62160 system 420 3 cpu elapsed application cpu time seconds 1700 0 cpuhere is the crash logincident identifier c5dfdde42ae0461a937ac422353102cecrashreporter key 3a88f20a9e18f468445bddc212b7aa673c6dc89bhardware model ipod41process imixtapes 1185path varmobileapplications104bd0f8bc3343a9ab9ffc609750c4b6imixtapesappimixtapesidentifier imixtapesversion code type arm nativeparent process launchd 1datetime 20110215 141929967 0530os version iphone os 421 8c148report version 104exception type 020exception codes 0x8badf00dhighlighted thread 6application specific informationimixtapes1185 has active assertions beyond permitted time sbprocessassertion 0x66bc490 identifier uikitbackgroundcompletiontask process imixtapes1185 permittedbackgroundduration 60 reason finishtask owner pid1185 preventsuspend preventidlesleep sbprocessassertion 0x66ade50 identifier uikitbackgroundcompletiontask process imixtapes1185 permittedbackgroundduration 60 reason finishtask owner pid1185 preventsuspend preventidlesleep elapsed total cpu time seconds 106580 user 62160 system 420 3 cpu elapsed application cpu time seconds 1700 0 cputhread 00 libsystembdylib 0x31093268 mach msg trap 201 libsystembdylib 0x31095354 mach msg 442 corefoundation 0x30416648 cfrunloopservicemachport 883 corefoundation 0x30415ed2 cfrunlooprun 3504 corefoundation 0x30415c80 cfrunlooprunspecific 2245 corefoundation 0x30415b88 cfrunloopruninmode 526 graphicsservices 0x31eec4a4 gseventrunmodal 1087 graphicsservices 0x31eec550 gseventrun 568 uikit 0x313cf322 uiapplication run 4069 uikit 0x313cce8c uiapplicationmain 66410 imixtapes 0x02968 0x10 650411 imixtapes 0x0291c 0x10 6428thread 10 libsystembdylib 0x310bf974 kevent 241 libsystembdylib 0x31169704 thispatch mgr invoke 882 libsystembdylib 0x31169174 thispatch queue invoke 963 libsystembdylib 0x31168b98 thispatch worker thread2 1204 libsystembdylib 0x3110d24a pthread wqthread 2585 libsystembdylib 0x31105970 start wqthread 0thread 20 libsystembdylib 0x31093268 mach msg trap 201 libsystembdylib 0x31095354 mach msg 442 corefoundation 0x30416648 cfrunloopservicemachport 883 corefoundation 0x30415ed2 cfrunlooprun 3504 corefoundation 0x30415c80 cfrunlooprunspecific 2245 corefoundation 0x30415b88 cfrunloopruninmode 526 webcore 0x35b32124 runwebthreadvoid 3327 libsystembdylib 0x3110c886 pthread start 2428 libsystembdylib 0x31101a88 thread start 0thread 30 libsystembdylib 0x31093268 mach msg trap 201 libsystembdylib 0x31095354 mach msg 442 corefoundation 0x30416648 cfrunloopservicemachport 883 corefoundation 0x30415ed2 cfrunlooprun 3504 corefoundation 0x30415c80 cfrunlooprunspecific 2245 corefoundation 0x30415b88 cfrunloopruninmode 526 foundation 0x302fb5f6 nsurlconnectionnsurlconnectionreallyinternal resourceloadloop 2067 foundation 0x302d9192 nsthread main 388 foundation 0x302d2242 nsthread main 9669 libsystembdylib 0x3110c886 pthread start 24210 libsystembdylib 0x31101a88 thread start 0thread 40 libsystembdylib 0x3110b9f0 semwait signal 241 libsystembdylib 0x310c07ec pthread cond wait 7482 libsystembdylib 0x310c03d2 pthread cond wait 263 coremedia 0x3290cb14 waitoncondition 44 coremedia 0x3290ca5a figsemaphorewaitrelative 665 mediatoolbox 0x32a8bc9c fpa asyncmoviecontrolthread 486 coremedia 0x32928f76 figthreadmain 1667 libsystembdylib 0x3110c886 pthread start 2428 libsystembdylib 0x31101a88 thread start 0thread 50 libsystembdylib 0x310b768c selectdarwin extsn 201 corefoundation 0x3044d662 cfsocketmanager 5822 libsystembdylib 0x3110c886 pthread start 2423 libsystembdylib 0x31101a88 thread start 0thread 60 libsystembdylib 0x3110b9f0 semwait signal 241 libsystembdylib 0x310c07ec pthread cond wait 7482 libsystembdylib 0x310c03d2 pthread cond wait 263 imixtapes 0x0945b0 0x10 6035684 imixtapes 0x0953ec 0x10 6072125 imixtapes 0x08f3a6 0x10 58256 audiotoolbox 0x3281e376 audiofilestreamwrappercallpacketsprocunsigned long unsigned long void const audiostreampacketdescription bool 1227 audiotoolbox 0x3283adfa mp3audiostreamgeneratepacketsaudiofilestreamcontinuation 268 audiotoolbox 0x3281e5e4 audiofilestreamwrapperparsebytesunsigned long void const unsigned long 1809 audiotoolbox 0x3281de6c audiofilestreamparsebytes 13210 imixtapes 0x093fe6 0x10 60208611 imixtapes 0x08f466 0x10 58275812 corefoundation 0x3044ef6a signaleventsync 7013 corefoundation 0x3044f842 cfstream solo signaleventsync 5814 corefoundation 0x3044c7ee cfstreamsignalevent 32615 corefoundation 0x3044c6a0 cfreadstreamsignalevent 416 cfnetwork 0x32fe2a66 httpreadstreamstreameventunsigned long 9417 cfnetwork 0x32fe2adc httpreadstream streamcb cfreadstream unsigned long void 2418 corefoundation 0x3044ef6a signaleventsync 7019 corefoundation 0x3044eefe cfstream shared signaleventsync 19820 corefoundation 0x3047d6 cfrunloop is calling out to a source0 perform function 621 corefoundation 0x304165b0 cfrunloopdosources0 37622 corefoundation 0x30415e54 cfrunlooprun 22423 corefoundation 0x30415c80 cfrunlooprunspecific 22424 corefoundation 0x30415b88 cfrunloopruninmode 5225 foundation 0x302d28e4 nsrunloopnsrunloop runmodebeforedate 19626 imixtapes 0x090ed8 0x10 58952827 foundation 0x302d9192 nsthread main 3828 foundation 0x302d2242 nsthread main 96629 libsystembdylib 0x3110c886 pthread start 24230 libsystembdylib 0x31101a88 thread start 0thread 70 libsystembdylib 0x31093268 mach msg trap 201 libsystembdylib 0x31095354 mach msg 442 corefoundation 0x30416648 cfrunloopservicemachport 883 corefoundation 0x30415ed2 cfrunlooprun 3504 corefoundation 0x30415c80 cfrunlooprunspecific 2245 corefoundation 0x30415b88 cfrunloopruninmode 526 audiotoolbox 0x327a84ba genericrunloopthreadrunloop 307 audiotoolbox 0x327bb306 trunloopaqcliententryvoid 908 audiotoolbox 0x327a81d2 capthreadentrycapthread 1389 libsystembdylib 0x3110c886 pthread start 24210 libsystembdylib 0x31101a88 thread start 0unknown thread crashed with unknown flavor 5 state count 1,['iphone'] +123286,javascript jquery animate to auto height hi i want to animate a div from 200px to auto height i cant seem to make it work though anyone know howheres the codedivfirstclickfunction firstanimate height auto 10,"['javascript', 'jquery']" +123309,how can i set uipickerview at other than the default index i have an integer having value of 5 and i want to start my uipickerview with this index now what should i donormally uipickerview is on default 0 index row but i want it on index which is user defined as can be 5 6 or any other digit,['ios'] +123335,how to do an inline ifotherwise aka ternary operator in velocity in pure java i could do thisvalue a b a bwhereas in velocity the long form would beifa b setvalue aelse setvalue bendis there a short form in velocity i want to be able to do an ifotherwise inline,['java'] +123360,xmlhttprequest status 0 responsetext is empty cannot get data with xmlhttprequest status 0 and responsetext is emptyxmlhttpnew xmlhttprequestxmlhttpopenget catalogxml truexmlhttponreadystatechangefunction ifxmlhttpreadystate4 alertstatus xmlhttpstatusxmlhttpsendit alerts status 0the same situation with the localhost request cd catalogxml is saved as a local filexmlhttpopengethttplocalhostcd catalogxml truebut with the localhost ip requestxmlhttpopenget catalogxml trueand with the local file requestxmlhttpopengetcd catalogxml trueeverything is ok status 200what can cause the problem status0 with the online requestps live http headers shows that everything is ok in all 4 cases http11 200 ok contentlength 4742ps2 apache local web server on vmware host os win7 guest os ubuntu network adapter a nat browser a firefox,['javascript'] +123375,userscripts greasemonkey calling a websites javascript functions i am creating a userscript extension for firefox chrome and i am trying to use some of the code in the websites javascript egfunction myfunction return groovesharkplaynextsongthe problem is when i test this code grooveshark is a null referencei know there are other people who have done itsee bettergroovesharkbut i do not know why my simple extension cannot call groovesharks javascript functionsdo i need to append my script to the document in order for this to workdocumentdocumentbodyappendchildscriptdoes not greasemonkey inject my extensions javascript already can someone clarify this for me pleasethanks,['javascript'] +123403,how do i scroll to an element using javascript i am trying to move the page to a div elementi have tried the next code to no availdocumentgetelementbyiddivfirststylevisibility visibledocumentgetelementbyiddivfirststylethisplay block,"['javascript', 'html']" +123410,where to start with javaspaces i need to start with javaspaces and i found this article but i found jini library and downloaded it but coulnt find javaspaces library is it moved to jini or what,['java'] +123417,objectivec property that is readonly publicly but has a private setter i would like to use the property syntax to declare a synthesized property that is publicly readonly but has a setter that can be called privately from within the clasince it is objectivec this basically means that the setfoo method would be synthesized but calling it outside of the class itself would result in a warning unrecognized selector to trigger the warning i have to declare the property readonly is there any way to force a synthesized setter that is only available within the class,['objective-c'] +123454,carrierwave upload with nested forms not sure whats going on here but i think my nested form partials are causing a problem for carrierwavewhen i update a field with an uploaded file nothing happens no error but nothing stored eitheri have a household model with a has many relationship with an individuals model the individuals model has a picture uploaderclass individual activerecordbase belongs to household mount uploader picture pictureuploaderendin my views i have form for household html multipart true do fand then call a partial for the individuals ffields for individuals do builder render individual fields f builder fsubmitthe partial just has the following flabel firstname first ftext field firstname size 10 flabel lastname last ftext field lastname size 15 ffile field picturethe uploaded picture appears in the paramsstarted post households849 for 127001 at 20110215 154516 0500 processing by householdscontrollerupdate as html parameters 612008 active 66 individuals attributes0firstnamehannah pictureactionthispatchhttpuploadedfile0xb9fbd24 original filename3jpg content typeimagejpeg headerscontentthisposition formdata namehouseholdindividuals attributes1picture filename3jpgrncontenttype imagejpegrn tempfilefiletmprackmultipart201102156498ba4bp destroyfalse id4077 commitupdate household id849and is stored in the tmp directory under the upload path it is just never saved to the database nor moved into place in the filesystemany ideas,['ruby-on-rails'] +123458,where can i find a java servlet filter that applies regex to the output i am hoping someone has already written thisa servlet filter that can be configured with regular expression searchreplace patterns and applies them to the html outputdoes such a thing exist,['java'] +123470,aspnet mvc3 razor how to conditionally quit or end or return or break a partial view with razor how do you conditionally quit or end or return or break a partial viewif model null return,['asp.net'] +123480,best practices to test protected methods with phpunit on abstract classes with phpunit and php 53 it is possible to test protected methods the following page at stackoverflow outlined the best practice on itbest practices to test protected methods with phpunitprotected static function callprotectedmethodname classname params class new reflectionclassclassname method classgetmethodname methodsetaccessibletrue obj new classnameparams return methodinvokeargsobj paramsto test public methods on abstract classes is easy with phpunit to test protected methods on normal classes is easy with approach above to test protected methods on abstract classes must be possible somehow i know phpunit derives abstract classes and implements abstract methods in a concrete class and fires the tests against that concrete class but i do not know how to integrate that into the approach above to have a callprotectedmethodonabstractclasseshow are you doing such testsps the question is not about the truth of testing protected methods see white gray and blackboxtesting the need of testing protected methods depends on your test strategy,['php'] +123503,create mysql column with keymul i want to make a column with key mul what should i add to the following statement to make it do thatalter table skills required add column skill id int 11 not nullthanks for the help,['mysql'] +123523,how does gmails periodic mail fetching work when i am using gmail some new mails that i just received appear on the inbox even if i did not refresh the page i believe that would done in ajaxis there any good demo that works very similar to it periodically checking and getting json data i am not sure if it is json data to fetch new datathanks,"['php', 'javascript']" +123547,how to query seed used by randomrandom is there any way to find out what seed python used to seed its random number generatori know i can specify my own seed but i am quite happy with python managing it but i do want to know what seed it used so that if i like the results i am getting in a particular run i could reproduce that run later if i had the seed that was used then i couldif the answer is i cannot then whats the best way to generate a seed myself i want them to always be different from run to runi just want to know what was usedupdate yes i mean randomrandom mistake title updated,['python'] +123550,which php orm works best with zend framework well seeing as i am thissatisfied with zend db table after being spoiled by linq i am looking to get started learning an orm with php general consensus seems to be that doctrine and propel are the only good ones for serious use and whatever my opinion i would like to use something at least moderately popular so that people in the future can look at this app i am working on without having an head explosion pi am currently leaning towards propel because it is documentation seems to be a bit more complete and it supports the nested set model also called modified preorder tree transversal model right out of the box however i like doctrines use of namespaces and other php 53 features and it seems to be a bit more popularfrom those who have used either orm with zend framework which meshes better with the existing framework if either what kind of issues should i watch out for using either framework with zend,['php'] +123582,linq order by group by and order by each group i have an object that looks something like this public class studentpublic string name getset public int gradegetseti would like to create the following query group grades by student name order each student group by grades and order groups by max grade in each groupso it will look like this a 100a 80b 80b 50b 40c 70c 30i created the following query studentsgradesgroupbystudent studentnameorderbystudentgradesgroup studentgradesgroupmaxstudent studentgradebut that returns ienumerable igrouping and i have no way to sort the list inside unless i do that in another foreach query and add the results to a different list using addrangeis there a prettier way to do that,['c#'] +123586,ruby compare 2 arrays for matches and count the number of match instances i have 2 arraysarray1 abcdearray2 defghi want to compare the two arrays to find matches de and count the number of matches found 2 if array2includearray1 yes but how to count instances else no matches found end thanks in advance,"['ruby-on-rails', 'ruby']" +123592,fallback for jquery ui from google cdn html5 boilerplate uses the following trick for fallback to locally stored jquery if grabbing it from google cdn failsscriptwindowjquery documentwriteunescape3cscript srcjslibsjquery142js3e3cscript3escripthow would you implement this trick to perform the same trick for jquery ui,['jquery'] +123614,in mysql can i defer referential integrity checks until commit as in this question i have been reading poeaa and wondering if it is possible to defer referential integrity checks until commit in mysqli have run into this problem when wanting to insert a bunch of products and related products in the same commit even within a transaction i get constraint errors when i try to insert into the related products join tableif it helps i am using php pdo for database connectionsi would appreciate any help you could offer,['mysql'] +123625,using iframes in aspnet i have an aspnet website with a masterpage can i use the iframe so my aspx pages will load inside the iframes meaning it wont load the masterpagekinda like my iframe will be the contentplaceholder or maybe the contentplaceholder will be inside itany ideas,"['c#', 'asp.net']" +123635,rails how to search based on a boolean field mysql error i am running the following queryprojects companyprojectswhereactive trueordercreated at ascand i am getting the erroractiverecordstatementinvalid mysqlparseerror you have an error in your sqlthe error points to the 1i have tried many variations on my query but i cannot figure out the problem how can i solve this,['ruby-on-rails'] +123649,get the value of thisplayname attribute public class class1 thisplaynamesomething to name public virtual string name get set how to get the value of thisplayname attribute in c,['c#'] +123654,mysql integer 0 vs null when using integer columns is it better to have 0 or null to indicate no value for example if a table had a parent id field and a particular entry had no parent would you use 0 or null i have in the past always used 0 this is because i come from a java world where prior to 15 integers always had to have a value i am asking mainly in relation to performance i am not too worried about which is the more correct option,"['mysql', 'sql']" +123665,sqlce upsert update or insert how to prepare a row using common method following is the pseudocodesqlceresultset myresultset cmdexecuteresultsetoptionsetcbool found myresultsetseekif found do an update myresultsetread make current at this point we have a cursor positioned at a row to be edited myresultsetsetstring1 value for col 1 myresultsetsetstring2 value for col 2 etc myresultsetsetstring100 value for col 100 i want to replace above with commonmethodtofillrowdatasomerow finally update myresultsetupdate else do an insert sqlceupdatablerecord myrec myresultsetcreaterecord set primarykey myrecsetint320 pkvalue at this point we have a cursor positioned at a row to be edited myrecsetstring1 value for col 1 myrecsetstring2 value for col 2 etc myrecsetstring100 value for col 100 i want to replace above with commonmethodtofillrowdatasomerow finally insert myresultsetinsertmyrecfrom the above if i have 100 columns to prepare it has to be repeated twice what i want is some commonmethodtofillrowdata but what type of parameter do i use for such a methodcommonmethodtofillrowdatasqlceresultset or sqlceupdatablerecord parmrow parmrowsetint32col1 value1 parmrowsetstringcol2 value2 etc parmrowsetstring100 value for col 100directly quoting from msdn doco on sqlceupdatablerecord class represents a row of updatable values from the data source a sqlceresultset object contains one or more updatablerecordsif that is the case why cannot i have direct access to a single updatablerecord inside sqlceresultset once i position the cursor via a seek if that were possible that would enable me to usecommonmethodtofillrowdatasqlceupdatablerecord parmrow end of story,"['c#', '.net']" +123678,making rails tests aware of rack middleware outside railss internal chain context an application uses a piece of rack middleware that must be setup in configru rather than railss internal middleware chain this is for reasons not relevant to this questionquestion how do i make my tests functional and integration aware of this middlewarei will ellaborate with an example let us create a pristine rails 3 app using rackrewrite for illustration purposes configinitializersexamplerbrailsapplicationmiddlewareinsert 0 rackrewrite do r301 so end testintegrationthe testrbrequire test helperclass thetest actionthispatchintegrationtest test redirect from so to do get so assert redirected to endendif you run the above test all is good and with the browser you can confirm that visiting the path so will redirect you to stackoverflow indeedcool let us now set this up outside rails then remove the file configinitializersexamplerb described above and change configru to the following configrurequire fileexpand pathconfigenvironment file map so do run rackrewrite do r301 endendmap do run deletemeapplicationendnow the test will stop working the functionality does work as evidenced if you visit so with your browser it is only that the tests are not aware of that rack setup,['ruby-on-rails'] +123705,is net adoublea arithmetic independent of platformarchitecture if i run a complex calculation involving systemdouble on net under windows x86 and x64 and then on mono linux unix whatever am i absolutely guaranteed to get exactly the same result in all cases or does the specification allow for some leeway in the calculation,"['c#', '.net']" +123710,mysql select join where and where i have two tables in my databaseproductsid int primary keyname varcharproducttagsproduct id inttag id inti would like to select products having all given tags i triedselect from productsjoin producttags on productsid producttagsproduct idwhere producttagstag id in 1 2 3group by productsidbut it gives me products having any of given tags instead of having all given tags writing where tag id 1 and tag id 2 is pointless because no rows will be returned,['mysql'] +123715,error starting jettyservice solr update i installed the 32bit jdk and the service starts fine now no idea why though the machine it was failing on was 64bitupdate2 so installing the 32bit jdk will allow the service to install but solr will not run there is a stackoverflowexception and nullpointer excpetions in the logsi am trying to run jetty as a service on windows 7 64bit i have it running on a very similar machine just fine but on the second i am getting errors i have not been able to resolvethe service installs fine however when you try to start it you get the message in the console the jetty6service service was launched but failed to startthis is the related contents in the jettyservicelogstatus wrapper 20110216 125007 starting the jetty6service servicestatus wrapper 20110216 125007 wrapper started as servicedebug wrapper 20110216 125007 using tick timerdebug wrapperp 20110216 125007 server listening on port 320status wrapper 20110216 125007 launching a jvmdebug wrapper 20110216 125007 command java djettyhome djettylogslogs dsolrsolrhomecsolr xms5m xmx64m djavalibrarypathlibwin32 classpath libwin32jettywin32servicejava6126jarlibwin32wrapperjarlibjetty613jarlibjettyutil613jarlibservletapi25613jarstartjar dwrapperkeyc5cihijso0gmmcte dwrapperport320 dwrapperjvmportmin310 dwrapperjvmportmax319 dwrapperdebugtrue dwrapperpid4708 dwrapperversion323 dwrappernative librarywrapper dwrapperservicetrue dwrappercputimeout10 dwrapperjvmid1 orgmortbayjettywin32servicejettyservicewrapperlistener etcjettyxmlfatal wrapper 20110216 125007 unable to execute java command the system cannot find the file specified 0x2fatal wrapper 20110216 125007 java djettyhome djettylogslogs dsolrsolrhomecsolr xms5m xmx64m djavalibrarypathlibwin32 classpath libwin32jettywin32servicejava6126jarlibwin32wrapperjarlibjetty613jarlibjettyutil613jarlibservletapi25613jarstartjar dwrapperkeyc5cihijso0gmmcte dwrapperport320 dwrapperjvmportmin310 dwrapperjvmportmax319 dwrapperdebugtrue dwrapperpid4708 dwrapperversion323 dwrappernative librarywrapper dwrapperservicetrue dwrappercputimeout10 dwrapperjvmid1 orgmortbayjettywin32servicejettyservicewrapperlistener etcjettyxmlfatal wrapper 20110216 125007 critical error wait for jvm process failederror wrapper 20110216 125009 the jetty6service service was launched but failed to startthe one difference that i know of between the two machines is that the one that is not working had tomcat installed at one point which it no longer doesi have tried the followinguninstalled all copies of the java jdk and jrereinstalled the latest java jdk jdk160 24 which installs the associated jretried setting java home to cprogram filesjavajdk160 24googled all error messagesi can run java version in the console without errorin case someone is looking for more information on running jetty as a service check out,['java'] +123734,cache static clas data in silverlight i have static class that holds some infopublic static class sampledatacache private static dictionarystringsampledata cachedict new dictionarystringobject public static getstring key ifcachedictcontainskey cachedictaddkeynew sampledata return cachedictkey and when i refresh page i want sampledatacache to keep its datacan i achieve this in simple way,['c#'] +123761,python decorator for simple recursion in standard library or elsewhere i am looking for a python decorator that can make a function recursive i find myself writing a lot of functions like thisdef xyzdata if not isinstancedata typethatdenotessingularity return mapxyz data return singular xyzdatai figure there must be a decorator out there somewhere in the standard library that can slim down the notation a tadrecursivetypethatdenotessingularitydef xyzdata return singular xyzdatai have been searching but i cannot seem to get anywhere perhaps i am missing some essential terminologythanks for pointing me in the right direction,['python'] +123766,c memberfunction chaining return types and derived classes given this contrived examplestruct point 2d point 2d x int and x n return this point 2d y int and y n return this int x y struct point 3d point 2d point 3d z int and z n return this int z int main point 3d p px0y0z0 error point 2d has no member named z return 0the idea is to use memberfunction chaining to be able to call more than one memberfunction in a row there are many examples of this the above is the shortest one i could think of for the purpose of asking this question my actual problem is similar and is described belowthe problem is that if a derived class adds its own chaining memberfunctions but you call a base clas member function first you get a baseclass reference that of course would not work for calling a derived clas memberfunctionare there any clever ways to solve this problem and still maintain the ability to do memberfunction chainingthe actual problemmy actual problem is that my base class is an exception and my derived class is a class derived from the base exception for those classes also i want to use memberfunction chainingclass base exception public stdexception base exception set something int some param return this class derived exception public base exception int main try if thisaster throw derived exception required arg1 required arg2 set something optional param catch derived exception const e terminate called after throwing an instance of base exception the problem is that set something returns base exception but the catch expects a derived exception of course a human can tell that the actual type of the exception is a derived exception but the compiler apparently cannot tellthat is the problem i am really trying to solve ie how to have a base exception class be able to set optional parameters on the exception object yet return an instance of the derived type the point 2d example i gave above is i believe a smaller and simpler version of the same problem for people to understand and that a solution to the smaller problem will also solve my actual problemnote that i did consider making base exception a template and pass in the derived type liketemplateclass derivedclass base exception derived set something int some param return this i believe that in fact does solve the problem but it is not a perfect solution because if another class more derived exception derives from derived exception then were back to the same problem,['c++'] +123775,unzipping files in a faster way than using the javautilzip in android i need unzip a zip file of 25mb1087 files html css and db in android i have used javautilzip it works fine but i need improve the performance the unzip process last 110 minutes i need reduce this timei have followed some recomendations for improve the performance for example use bufferedinputstream fileoutputstream and bufferedoutputstreamread the zip in blocks byte data new byte2048while counter bismediafilereaddata 0 2048 1 bosmediafilewritedata 0 counteris there any way to improve my code i was searching third party zip programs to use programatically for example i tried the 7zipjbinding but it looks like android does not support this because i referenced the sevenzipjbindingjar and sevenzipjbindingallplatformsjar but i get an error native libraries detected in sevenzipjbindingallplatforms at 7zip homepage there are versions for mac windows linux but i did not see anything about androidcould you please recommend any other library to unzip files in androidthis is my all code public static void processzipfilestring strbinarypathstring strextractpath string strdestinationdbpath throws exception zipfile zipinfile null try if strextractpath null zipinfile new zipfilestrbinarypath for enumeration extends zipentry entries zipinfileentries entrieshasmoreelements zipentry zipmediaentry entriesnextelement if zipmediaentryisdirectory file mediadir new filestringformatss strextractpath zipmediaentrygetname mediadirmkdirs else bufferedinputstream bismediafile null fileoutputstream fosmediafile null bufferedoutputstream bosmediafile null try string strfilename stringformatss strextractpath zipmediaentrygetname file uncompressdir new filestrfilenamegetparentfile uncompressdirmkdirs if is a database file extract to other path androidmovinginteractivecomdatabases ifstrfilenamecontainsdb strfilename stringformatss strdestinationdbpath extractdbnamezipmediaentrygetname bismediafile new bufferedinputstreamzipinfilegetinputstreamzipmediaentry fosmediafile new fileoutputstreamstrfilename bosmediafile new bufferedoutputstreamfosmediafile int counter byte data new byte2048 while counter bismediafilereaddata 0 2048 1 bosmediafilewritedata 0 counter catch exception ex throw ex finally if bosmediafile null bosmediafileflush bosmediafileclose if bismediafile null bismediafileclose catch exception ex throw ex finally if zipinfile null zipinfileclose file flziptodelete new filestrbinarypath ifflziptodeleteexists flziptodeletedelete,['android'] +123780,how to escape literal percent sign when no backslash escapes option is enabled my company runs mysql in no backslash escapes mode how can i escape a literal or in a like query in this mode the standard way is but that does not work in this modeexample a column has the following values 5 off 50 off the following query works in standard mode but not in no backslash escapes modeselect from mytablewhere mycol like 5 off,['mysql'] +123784,resolveurlresolveclienturl equivalents for aspnet razor so i have started using the urlcontentsiteblah syntax as standard for css jscript and image urls solves a lot of issues indeed and it is at least consistent beween webforms and razor pages not all of my devs will be doing razor and yet they will still be working on this platform i have producedhowever for something that i am doing at the moment i could really do with a way to take a relative url written in a razor page and at run time resolve it to the correct server side file before turning it back into an absolute url for the client urlcontent does not do anything with relative urlsso basically i want either an equivalent of resolveurl or resolveclienturl at the razor leveli would like this to enable terser and more tolerant to renaming resource paths in some of my mvc views which can be a few folders further down from the root and whose content folder would be more easily expressed as a relative path so i could have folderfolderviewssharedlayoutcshtmlandfolderfoldercontentsitecss i have inferred the use of a layout page also to mirror the kind of issues that are addressed by resolveurl and the rebasing that webforms doesusing urlcontent as it is i would need to specify the full path urlcontentfolderfoldercontentsitecss but what i would like is urlcontentsitecssand have that work of course regardless of how many paths there are in the current requests routeof course i can get this to work in webforms if i ditch the urlcontent call and just rely on url rebasingis there any equivalent in razor,['asp.net'] +123785,testng beforemethod method not called when it resides in superclass and a specific group is run i am trying to use a group to run a subset of tests relevant to what i am working on called current the problem is that if i use a superclass to do some setup in a beforemethod the method runs when i run all tests but does not when i run with just the group current specifiedso when i run all tests the emptytest fails because the beforemethod is called when just running group current the method is not called note if i add testgroups current to the subclass then it does run however it runs all subclasses not labelled with current as well which defeats the purpose of the current groupif there is a better way to accomplish this behavior i am open to all solutionsthanksransomsuperclasspublic class testngsuperclass beforemethod public void failingtoshowthatitisnotrun assertfail subclasstestgroups currentpublic class testngcurrentgroup extends testngsuperclass public void emptytest testng configurationtest namecurrent groups run include namecurrent run groups packages package nameuiowawftest packagestesttest namealltests packages package nameuiowawftest packagestest,['java'] +123792,copy a file creating directories as necessary in ruby let us say i have a file at sourcetxt and i want to copy it to abctxt a and ab may or may not existis there a way to copy the file and have it create the necessary parent directories if necessaryideally this would be one command in particular i would like to avoid parsing the filedirectory parts of destination path and then manually calling fileutilsmkdir p and fileutilscppure ruby is preferred though a railsdependent solution is acceptable,['ruby'] +123806,architectural concerns fluent nhibernate the repository pattern and aspnet mvc i have just started a new project and have naturally opted to use a lot of new techi am using fluent nhibernate aspnet mvc 3 and am trying to apply the repository patterni have decided to seperate my business logic into a seperate project and define services which wrap my repositories so that i can return pocos instead of the nhibernate proxies and maintain more seperation between my front end and da logic this will also give me the power to easily provide the same logic as an api later a requirementi have chosen to use a generic irepositoryt interface where t is one of my nhibernate mapped entities which all implement ientity my interface only a marker reallythe problem is this goes against the aggregate root pattern and i am starting to feel the pain of the anemic domain modelif i change an object that is hanging of anotherroot changedchild changedin my service i have to do the followingpublic void addnewchildchilddto child rootid var childentity mappermapchilddtochildentitychild var rootentity rootrepositoryfindbyidrootid rootentitychildrenaddchildentity childrepositorysaveorupdatechild rootrepositorysaveorupdaterootif i do not save the child first i get an exception from nhibernate i feel like my generic repository i currently require 5 of them in one service is not the right way to go public serviceirepositorythingentity thingrepo irepositoryrootentity rootrepo irepositorychildentity childrepo irepositorycategoryentity catrepo irepositoryproductentity productrepoi feel like instead of making my code more flexible it is making it more brittle if i add a new table i need to go and change the constructor in all my tests i am using di for the implementation so that is not too bad but it seems a bit smellydoes anyone have any advice on how to restructure this sort of architectureshould i be making my repositories more specific is the service abstraction layer a step too faredit there is some great related questions which are helpingrepository pattern best practicerepository pattern helparchitectural conundrum,['c#'] +123821,how do i inflate an android options menu and set an item to enabledfalse my xml menu definition sets the item ridmenu refreshs enabled state to false when the app runs the menu item is greyed and thisabled why is this code in the app not enabling the itempublic boolean oncreateoptionsmenumenu menu menuinflater inflater getmenuinflater inflaterinflatermenumain menu menuitem refresh menugetitemridmenu refresh refreshsetenabledtrue return truewhat am i missing,['android'] +123831,matrix multiplication using cuda i am struck up with matrix multiplication on cuda the resultant product matrix is always zero i have read some sample codes like matrix multiplication in cuda for resolving my problem but all in vainapart from erratic result of 0 the maximum size of width code below is not even 512 i was not able to debug where the problem lies may be we can thiscuss it on stackoverflow i am referring programming massively parallel processorsincludecudahincludestdiohint mainvoid void matrixmultiplicationfloat float float int const int width 5 float mwidthwidth nwidthwidth pwidthwidth forint i 0 i widthwidth i mi 5 ni 5 pi 0 matrixmultiplicationm n p width forint i 0 i widthwidth i printfd n pi int quit scanfdquit return 0matrix multiplication kernel thread specification global void matrixmulkernelfloat md float nd float pd int width 2d thread id int tx threadidxx int ty threadidxy pvalue stores the pd element that is computed by the thread float pvalue 0 forint k 0 k width k float mdelement mdtywidth k float ndelement ndkwidth tx pvalue mdelementndelement pdtywidth tx pvaluevoid matrixmultiplicationfloat m float n float p int width int size widthwidthsizeoffloat float md nd pd transfer m and and to device memory cudamallocvoidmd size cudamemcpymdmsizecudamemcpyhosttodevice cudamallocvoidnd size cudamemcpyndnsizecudamemcpyhosttodevice allocate p on the device cudamallocvoidpdsize setup the execution configuration dim3 dimblockwidthwidth dim3 dimgrid11 launch the device computation threads matrixmulkerneldimgriddimblockmdndpdwidth transfer p from device to host cudamemcpyppdsizecudamemcpydevicetohost free device matrices cudafreemd cudafreend cudafreepd,['c'] +123839,when does java thread cache refresh happens thread 1 is executing this loop whilerunning do task printlndonethread 2 sets running false in case running is a volatile variable thread1 comes out of the loop and prints done my question is if running is not volatile when does thread1 reads running variable from the main memory note well i know the happens before relationship about synchronization and volatile variable but the thread 1 does stops even if running is not volatile or synchronized so my question is when does thread 1 decides to read from the main memory given that no synchronization or and no volatile,['java'] +123845,net venn diagram library is there an open source or paid net library that will create diagrams with two important features create venn diagramssave the diagrams as images,"['c#', '.net']" +123846,net clr when compiling cil to platformspecific instructions what about new cpu architectures etc when the net clr compiles cil to platformspecific instructions what does it do if it is compiling on a new cpu architecture ie one it is not familiar with is ms keeping ahead of the curve and releasing new optimized instruction compiling functionality in net by cooperating with architecture vendors intel amd etc,['.net'] +123847,is there an ecmascript validator is there an ecmascript validator like there is for html and css ideally i need some automated way to check against version 30 of this standard,['javascript'] +123848,random memory accesses are expensive during optimizing my connect four game engine i reached a point where further improvements only can be minimal because much of the cputime is used by the instruction tableentry te mtableidx i in the following code sampletableentry gettableentryunsigned int64 lock int idx lock 0xf bucketsize for int i 0 i bucketsize i tableentry te mtableidx i bottleneck about 35 of cpu usage if teheight notset lock telock return te return tableentrythe hash table mtable is defined as stdvectortableentry and has about 42 mil entrys about 64 mb i have tried to replace the vectorby allocating the table with new without speed improvementi suspect that accessing the memory randomly because of the zobrist hashing function could be expensive but really that much do you have suggestions to improve the functionthank youedit bucketsize has a value of 4 it is used as collision strategy the size of one tableentry is 16 bytes the struct looks like followingstruct tableentry old new unsigned int64 lock 8 8 enum valid ubound lbound flag 4 4 short score 4 2 char move 4 1 char height 4 1 24 16 bytes tableentry lock0ll flagvalid score0 move0 height127 summary the function originally needed 39 seconds after making the changes jdehaan suggested the function now needs 33 seconds the program stops after 100 seconds it is better but i think konrad rudolph is right and the main reason why it is that slow are the cache misses,['c++'] +123853,how to retrieve grandchild objects from a parent using linq i have several parent child grandchild relationships in my db schema usually i have the parent and i want some information about the grandchildren for example i have a user who has a collection of social networks which have collections of friends i find myself writing this code over and over again var friends new listfriend foreach var socialnetwork in userusersocialnetworks foreach var friend in socialnetworkfriends friendsaddfriend is there a more elegant way to do this with linqwhat i would really like to be able to do is userfriends but i would have to put a foreign key to user in the friend table and that does not smell right here is what that would look likeuser idsocialnetwork id userid friend id socialnetworkid userid thoughts,['.net'] +123860,how to thisable default sound effects for all my application or activity in my application i am using sound pool for the button click audio effectthe problem is that if in the devices settings audible selection is ticked then my buttons will produce two sounds the system one and my one at the same timeit seems that if in each button properties i set sound effects enabled to false the system sound is not heard any more but i have many buttons across a dozen of activities plus i am adding a matrix of buttons in code so it is rather inconvenient to set sound effects enabled to false manually for each one of them not sure how i do this in codeis there a more global way to stop audible selection in my application or at least for the one activity,['android'] +123861,how to get an individual css style in pyquery you can set a css style using several methods p pyquerypcssfontsize16pxpcssfontsize 16pxpcss fontsize16pxgreat but how to get an individual css stylepcssfontsize jquerylike method does not workppcssfontsize pythonic method does not workppcssfont size beardedos suggestionppattrstyle too much informationfontsize 16px fontweight boldthis seems strange inconvenient and unpyquery and unpython like one of the first two ought to return the style text surely is there a way to get a single css style alone without resorting to tools like split,"['python', 'css']" +123862,javascript advantage by placing functions inside variables i have seen recent code examples placing functions inside variables and then calling the functions like normalas invar myfunctionname function code heremyfunctionnamei am sure there are a lot of advantages with more advanced scenarios but i am just curious,['javascript'] +123869,ipad compatible html wysiwyg editor are there any ipad compatible wysiwyg html editorsedit what i am looking for is something that would work on a web app not a native ipad app,"['javascript', 'html']" +123870,sending signals to a running jvm i am using a custom signal handler to catch term abrt and int signals in a custom java daemon i have this handler in the code so that i can send term signals to it and gracefully shutdown the program via the kill command the signal handler works right now but when i compile the code i am receiving the following warning many times overwarning sunmiscsignalhandler is sun proprietary api and may be removed in a future releasewhile using these classesimport sunmiscsignalhandlerimport sunmiscsignalis there a better way to send signals to a running jvm to initiate a shutdown of the main thread i do not like having my code tied to this api when it could be removed in the futurethis code works on solaris and hpux today using 150 22 jvm any help or suggestions would be much appreciated i used this document from ibm to develop the signal handler,['java'] +123878,moving from mysql to postgresql best features i was missing i used to develop everything with mysql this week an opportunity to work with postgresql appeared why not i was always told that postgresql had a much bigger feature seti read some wikis but most of the info are really outdated what are the best features i was missing like partial indexes etcalso i will miss something from mysql,"['sql', 'mysql']" +123885,thisable pinch zoom in webview i am building an app that thisplays some content in a webview i am styling this content to fit the screen and no zooming is needed is there a way do turn off the zooming features of a webview,['android'] +123891,uiview hidden propertyis there more to it coming from actionscript i would set sprites to visiblefalse in order to keep them from being calculated in things like layout and to ensure they would not respond to events in ios development i am continuing with thisif a uiview is not needed i may both animate its alpha to zero and then set hiddentrue i wanted to know if i was wasting my time or if there is a benefit to this in my current project i am doing so with uiimageviews which are not responding to events anyway is setting hidden to true good practice or or just additional overhead,"['iphone', 'ios']" +123910,routing nested resources in rails 3 i have a pretty common case for nested routes i feel like that looks something like this in some sort of pseudonotationusernamephotos show photos for userfind by usernamephotos show photos for userallin a nutshell i have users they have photos i want to be able to show their photos on their page i also want to be able to show all photos regardless of the user i would like to keep my routes restful and using the builtin resource methods feels like the right way to do itoption 1 for doing this is to have photoscontrollerindex use a conditional to check which params are given and get the list of photos and set the view different for a users photos than for all photos it is even easy to route itresources photos only indexscope username do resources photosendboom it would seem like rails was setup for this after the routes though things get more complicated that conditional back in the photoscontrollerindex action is just getting more and more bloated and is doing an awful lot of delgation as the application grows and so do the number of ways i want to show photos it is only going to get worseoption 2 might be to have a userphotoscontroller to handle user photos and a photoscontroller to handle showing all photosresources photos only indexnamespace user path username do resources photosendthat generates the following routes photos get photosformat actionindex controllerphotos user photos get usernamephotosformat actionindex controlleruserphotos post usernamephotosformat actioncreate controlleruserphotos new user photo get usernamephotosnewformat actionnew controlleruserphotos edit user photo get usernamephotosideditformat actionedit controlleruserphotos user photo get usernamephotosidformat actionshow controlleruserphotos put usernamephotosidformat actionupdate controlleruserphotos delete usernamephotosidformat actiondestroy controlleruserphotosthis works pretty well i think but everything is under a user module and i feel like that might end up causing problems when i integrate it with other thingsquestionsdoes anybody have experience with something like thiscan anybody share a better way of handling thisany additional pros and cons to consider with either of these optionsupdate i have gone ahead implementing option 2 because it feels cleaner allowing rails logic to work rather than overriding it so far things are going well but i also needed to rename my namespace to users and add an as user to keep it from clashing with my user model i have also overridden the to param method on the user model to return the username path helpers still work this way tooi would still appreciate feedback on this method am i doing things the expected way or am i misusing this functionality,"['ruby-on-rails', 'ruby']" +123920,call r programming language from net i am working on an application that requires a great deal of stastical processing and output as images in a net desktop application the problems including generating the output images seem like a natural fit for r is there a wrapper api sdk or port that will allow me to call r from net,['.net'] +123932,sqlite3 gem fails to install i am trying to install the sqlite3ruby gem or the sqlite3 gem on os x 106 i am using ruby192 and i currently get the following sqlite3 version374 sudo gem install sqlite3building native extensions this could take a whileerror error installing sqlite3ruby error failed to build gem native extensionusersfolkenrvmrubiesruby192headbinruby extconfrbchecking for sqlite3h extconfrb failed could not create makefile due to some reason probably lack ofnecessary libraries andor headers check the mkmflog file for moredetails you may need configuration optionsprovided configuration options withoptdir withoutoptdir withoptinclude withoutoptincludeoptdirinclude withoptlib withoutoptliboptdirlib withmakeprog withoutmakeprog srcdir curdir rubyusersfolkenrvmrubiesruby192headbinruby withsqlite3dir withoutsqlite3dir withsqlite3include withoutsqlite3includesqlite3dirinclude withsqlite3lib withoutsqlite3libsqlite3dirlibusersfolkenrvmrubiesruby192headlibruby191mkmfrb368in try do the complier failed to generate an executable file runtimeerroryou have to install development tools first from usersfolkenrvmrubiesruby192headlibruby191mkmfrb452in try cpp from usersfolkenrvmrubiesruby192headlibruby191mkmfrb853in block in find header from usersfolkenrvmrubiesruby192headlibruby191mkmfrb693in block in checking for from usersfolkenrvmrubiesruby192headlibruby191mkmfrb280in block 2 levels in postpone from usersfolkenrvmrubiesruby192headlibruby191mkmfrb254in open from usersfolkenrvmrubiesruby192headlibruby191mkmfrb280in block in postpone from usersfolkenrvmrubiesruby192headlibruby191mkmfrb254in open from usersfolkenrvmrubiesruby192headlibruby191mkmfrb276in postpone from usersfolkenrvmrubiesruby192headlibruby191mkmfrb692in checking for from usersfolkenrvmrubiesruby192headlibruby191mkmfrb852in find header from extconfrb28in maingem files will remain installed in usersfolkenrvmgemsruby192headgemssqlite3133 for inspectionthe following is the results of which whereis and the sqlite3h is located in optlocalinclude which sqlite3optlocalbinsqlite3 whereis sqlite3usrbinsqlite3i have tried passing in the following as wellsudo gem install sqlite3 withsqlite3include optlocalinclude withsqlite3lib optlocallibsudo gem install sqlite3 withsqlite3dir optlocalbinwhich results in the followingerror error installing sqlite3ruby error failed to build gem native extensionusersfolkenrvmrubiesruby192headbinruby extconfrb withsqlite3dir usrbinsqlite3 extconfrb failed could not create makefile due to some reason probably lack ofnecessary libraries andor headers check the mkmflog file for moredetails you may need configuration optionsprovided configuration options withoptdir withoutoptdir withoptinclude withoutoptincludeoptdirinclude withoptlib withoutoptliboptdirlib withmakeprog withoutmakeprog srcdir curdir rubyusersfolkenrvmrubiesruby192headbinruby withsqlite3dirusersfolkenrvmrubiesruby192headlibruby191mkmfrb1336in dir config undefined method split for truetrueclass nomethoderror from extconfrb9in mainalso under usersfolkenrvmgemsruby192headgems sqliteruby223 sqlite3133under rvm i have ruby187 and the sqlite3 gem loads fine on that but after much googling i have not found a solution that works for me any help is greatly appreciated even if it involves manual installation hackery to get working,"['ruby-on-rails', 'ruby']" +123934,how do you set up a flask application with sqlalchemy for testing it seems common practice in flask to start like thisfrom flask import flaskfrom flaskextsqlalchemy import sqlalchemyapp flask name sqlalchemy database uri somethingappconfigfrom object name db sqlalchemyappand then import and use app and db everywhere but when you create db like this it grabs configuration from the app and it seems that this configuration cannot ever be overridden once it happens there are some pages on flasks website about making application factories but it is not clear how i would be able to still use app and db everywhere if i did thathow do i write a script to test my flask application with a different database how should i structure my application to make this possible do i have to use modules,['python'] +123941,how to thisplay updated time as system time on a label using c i want to thisplay current time on a label using c but time will continuously change as system time changes how can i do this,"['c#', '.net']" +123946,difference between id and id in android what is the diffirence between the id and idin id the plus symbol instructs to create a new resource name and add in to the rjava file but what about id from the documentation of id when referencing an android resource id you do not need the plus symbol but must add the android package namespace like soandroididandroididlistbut in the image below eclipse does not suggest any kind of androididare id and androidid the same,['android'] +123947,why input gives an error when i just press enter i have the following python codeprint this is a simple gameinputpress enter to continue print choose an optionbut when i press enter button i get the following errortraceback most recent call last file e4pythontemppy line 2 in module inputpress enter to continue file string line 0 syntaxerror unexpected eof while parsingps i am using python idle version 26 on windows 7,['python'] +123964,suffix of f on float value i am wondering what the difference is between these two variables in cfloat price 300andfloat price 300fthe trailing f,['c'] +123967,detect if cursor is hidden on mac os x is there a programmatic nonprivateapi way to detect whether the mouse cursor is hidden on mac os x as occurs for example when typing into a text fieldnscursor has hide and unhide but no ishidden i am wondering if there is some other api which might do what i want cbased apis are fine,['objective-c'] +123991,constants in python at the root of the module or in a namespace inside the module i am building a python module with about a hundred constantsi would like to avoid naming issues when people import my module so i was wondering what would be the best way to do itmy constant 1my second constant 2my2 constant amy2 second constant borclass my constant 1 second constant 2 class my2 constant a second constant b or maybe another of your suggestionscoming from java i surely prefer the second way but some might find it overkill,['python'] +124018,cobertura in eclipse i just installed ecobertura plugin but it looks like not a very userfriendly tool from within eclipse is there any good plugin for cobertura in eclipse or article to describe how to use ecoberturai am used to seeing code complexity and coverge etc in a very nice wayi need to use cobertura because the build system in the backend uses it so it makes sens to use it in the ide as wellregards,['java'] +124025,how do i convert a string to double using only mathh i am trying to convert a string to a double but since i am working on a windows native application as in linking only to ntdlldll i do not have most of the standard library available i can use basic fp support in mathh but that is basically ithow do i convert a string to the double closest to the rational number expressed in that string,"['c++', 'c']" +124029,how to set mimebodypart contenttype to texthtml the program below shows an unexpected return value for html multipart mime type why does this program print textplain and not texthtmlpublic class main public static void mainstring args throws javaxmailmessagingexception javaioioexception javaxmailinternetmimebodypart mime body part new javaxmailinternetmimebodypart mime body partsetcontenth1fooh1 texthtml systemoutprintlnmime body partgetcontenttype i have tried numerous alternative ways including setting a bytearraydatasource wrapped in a datahandler but to no avail the same thing happens when i try this with a mimemessage instead of a mimebodypartto compile and run on linuxjavac classpath activationjarmailjar mainjavajava classpath activationjarmailjar main,['java'] +124032,get current location address for android app i do not need to thisplay a map however i need to use the gps3g network to locate my current positions address not long and lat this will then be added to a automated sms response to inform a person that i currently cant reply the include the string address of my current locationi have the sms stuff working just need to figure out a method of accessing the gps and pulling an address i have seen sample code for latlong perhaps i need to convert latlong into an address within the google maps api i am unsure howto go about itany advicecode snippetssimilar tutorials welcome thanks,['android'] +124059,convert char to int in c and c how do i convert a char to an int in c and c,"['c++', 'c']" +124089,php whats the benefit of unsetting variables possible duplicateswhats better at freeing memory with php unset or var nullphp when to use unset hello guysmy question today is if there is a real benefit of unsetting variables in phpclass test public function m1a b c a b unseta b return c is it true that unsetting variables does not actually decrease the memory consumption during runtimethanks in advance,['php'] +124097,debug vs trace in c as i understand statements like debugwriteline will not stay in the code in the release build on the other hand tracewriteline will stay in the code in the release buildwhat is controling this behaviour does the c compiler ignores everything from the systemdiagnosticsdebug class when the debug is definedi am just trying to understand the internals of c and just curious,['c#'] +124108,must every ivar be a property i see it recommended all over the place when coding for ios that properties should be used for accessing instance variables because of the benefits this lends to memory management among other thingsthis advice does not sit terribly well with me i find that using properties instead of plain old ivars just takes too much code and i do not really see the benefits if youre comfortable with memory management is it really that important whats your approach to managing instance variables,"['objective-c', 'ios']" +124117,what is the difference between a class and a type in scala and java scalawhere can differences between a class and a type be observed in scala and why is this thistinction importantis it only a consideration from the language design pointofview or has it practical impact when programming scalaor is it fundamental to securing the boundaries of the type system nothing null come to my mindjavahow many of the considerationsdifferencesproblems mentioned above can also be recognized in javasee what is the difference between type and class as a languageagnostic introduction,['java'] +124133,php sentence boundaries detection i would like to divide a text into sentences in php i am currently using a regex which brings 95 accuracy and would like to improve by using a better approach i have seen nlp tools that do that in perl java and c but did not see anything that fits php do you know of such a tool,['php'] +124150,why are struts action classes not thread safe i can read in many websites that struts action classes are not thread safe i am not able to understand why this is so also i read a book which says struts action classes are cached and reused for performance optimization at the cost of having to implement the action classes in a threadsafe mannerhow is caching action classes and being thread safe related,['java'] +124156,stop link from sending referrer to destination i have a page where i do not want the outbound links to send a referrer so the destination site does not know where they came fromi am guessing this is not possible but i just want to make sure there werent any hidden javascript magic that could do it and that would work with some if not most browsersmaybe some clever http status code redirecting kungfusomething like this would be perfecta hrefexamplecom send referrerfalselinka,['javascript'] +124163,mysql query same table to gather todate and yeartodate information i have been struggling with this problem for hours even though i am sure there is an easy answer i am attempting to gather monthly information and yeartodate information from the same table i am also joining a second table to gather the group name expense table field type null key default extra id int5 no pri null auto increment account char14 no null batch int5 no null date date no null description varchar50 no null debit decimal102 no null credit decimal102 no null account data id varchar14 no null account data table field type null key default extra id int5 no pri null auto increment account code varchar14 no null group name varchar30 no null i can easily come up with either monthly or yeartodate information but no matter what i do i am not able to have both below is the closest i can come up with but it takes forever to execute and the results are not whats expectedselect account datagroup name summdebit summcredit as month sumydebit sumycredit as yearfrom account datainner join expense m on maccount data id account dataidand monthmdate in 7891012left join expense y on yaccount data id account dataidand monthydate in 7group by account datagroup namethis is what i am looking to accomplish group name month year payroll 10 50 payroll tax 10 50 benefits 500 10 any help is greatly appreciated i am new here and i hope i have followed all rules and have provided any of you with enough information to help but if not let me know and i will provide more philwinkle your solution properly modifiedselect adgroup nameifmonthedate in 7891012 sumedebit sumecredit ifmonthedate 7 sumedebit sumecredit from account data adleft join expense 2011 e on eaccount data id adidwhere eaccount data id 7group by adgroup name,"['sql', 'mysql']" +124164,how to dynamically remove a stylesheet from the current page is there a way to dynamically remove the current stylesheet from the pagefor example if a page containslink relstylesheet typetextcss hrefhttp is there a way to later thisable it with javascript extra points for using jquery,"['javascript', 'jquery', 'css']" +124189,retrieving a random item from arraylist i am learning java and i am having a problem with arraylist and randomgeneratori have an object called catalogue which has an array list of objects created from another class called itemi need a method in catalogue which returns all the information on one of the itemobjects in the listthe item needs to be selected at randomi have used the random generator util but i cannot get it working i cannot work out what i have done wrongimport javautilarraylistimport javautilrandompublic class catalogue private random randomgenerator private arraylistitem catalogue public catalogue catalogue new arraylistitem public item anyitem int index randomgeneratornextintcataloguesize return cataloguegetindex systemoutprintlnmanagers choice this week anyitem our recommendation to you when i try to compile i get an error pointing at the systemoutprintln line saying cannot find symbol variable anyitemany help greatly appreciated thanks,['java'] +124192,comparing chars in java it is been a while since i have done any java so my syntax is not the greatest at the momenti want to check a char variable is one of 21 specific chars what is the shortest way i can do thisfor exampleifsymbol abcdoes not seem to be working do i need to write it likeifsymbol a symbol b etc,['java'] +124195,how to retrieve the clients machine name from within a wcf operation contract i am currently looking at the operationcontectcurrent properties is there a nested property the will always return the machine name of the client i am currently using nettcp binding but would like to support additional bindings in the futureusing net 35 sp1,['c#'] +124206,animating a pulsing uilabel i am trying to animate the color the the text on a uilabel to pulse from black to white to black and repeat voidtimerflashnstimer timer self navtitle settextcoloruicolor whitecolor colorwithalphacomponent00uiview animatewithduration1 delay0 optionsuiviewanimationoptionallowuserinteraction animationsself navtitle settextcoloruicolor whitecolor colorwithalphacomponent10 completionnilself setfadetimernstimer scheduledtimerwithtimeinterval1 targetself selectorselectortimerflash userinfonil repeatsyesfirstly i am not sure of my method my plan as you can see above was to set up a animation block and call it using a repeating nstimer until canceledmy second problem as you can see above is that i am animating from black alpha 0 to white alpha 1 but i do not know how to animate back to black again so the animation loops seamlesslyessentially what i want is the text color to pulse on a uilabel until the user presses a button to continueedit 001i was getting into trouble because you cannot animate uilabel setcolor you can however animated uilabel setalpha so i am going to give that a goedit 002 voidtimerflashnstimer timer self navtitle setalpha05 uiview animatewithduration2 delay0 optionsuiviewanimationoptionallowuserinteraction animationsself navtitle setalpha09 completionnilthis works btw i do want it to stop which is why i hooked it up to a nstimer so i can cancel that the only thing is that this animates from midgray to nearwhite and then pops back does anyone know how i would animate back from nearwhite to midgray so i get a nice smooth cycleedit 003 solutionthe code suggested by dave delong see below does indeed work when modified to use the calayer opacity style attributeuilabel navtitlepropertynonatomic retain uilabel navtitle add animationcabasicanimation anim cabasicanimation animationwithkeypathopacityanim settimingfunctioncamediatimingfunction functionwithnamekcamediatimingfunctioneaseineaseoutanim setfromvaluensnumber numberwithfloat05anim settovaluensnumber numberwithfloat10anim setautoreversesyesanim setduration05self navtitle layer addanimationanim forkeyflash remove animationself navtitle layer removeanimationforkeyflash,"['iphone', 'objective-c']" +124212,submit without the use of a submit button mechanize so i started out with mechanize and apparently the first thing i try it on is a monkeyrhinolevel high javascript navigated sitenow the thing i am stuck on is submitting the formnormally i would do a submit using the mechanize builtin submit functionimport mechanizebrowser mechanizebrowserbrowserselect formname foobrowserformbar bazbrowsersubmitthis way it would use the submit button that is available in the html formhowever the site i am stuck on had to be one that does not use html submit buttons no they are trying to be javascript gurus and do a submit via javascriptthe usual submit does not seem to work with thisso is there a way to get around thisany help is appreciated many thankseditthe javascript function i am stuck onfunction foobar baz var qux documentformsqux quxbarvalue barsplitjoinquxbazvalue bazquxsubmitwhat i did in python and what does not workdef foobrowser bar baz qux browserselect formqux browserformbar joinbarsplit browserformbaz baz browsersubmit,['python'] +124225,lazy evaluation with ostream c operators i am looking for a portable way to implement lazy evaluation in c for logging classlet us say that i have a simple logging function likevoid syslogint priority const char format then in syslog function we can doif priority current priority returnso we never actually call the formatting function sprintfon the other hand if we use logging stream likelog log notice test 123all the formating is always executed which may take a lot of timeis there any possibility to actually use all the goodies of ostream like custom operator for classes type safety elegant syntax in a way that the formating is executed after the logging level is checked,['c++'] +124241,failsafe thisposal in an async world in the synchronous world c makes the management of all things thisposable really rather easyusingithisposable somethisposableblabla do our biddingdo not worry too much about ithowever when we go async we no longer have the convenience of the using block one of the best strategies i have encountered is the ccr iterator which allows us to use async code as if it were synchronous this means we can keep our using block in the iterator handler and not get too bogged down in the complex decision of when to thispose and catching all the cases where thisposal is requiredhowever in many cases invoking ccr can seem like overkill and to be honest although i am quite comfortable with ccr to the uninitiated it can look like doubledutchso my question is what other strategies exist for the management of ones ithisposables when the thisposable objects must persist beyond the immediate scope,['c#'] +124249,how to retrieve certificates from a pfx file with c i have been googling around for half a day looking for a way to read a pfx file and import the certificates into the certstore so far i am able to read the pfx file with x509certifcate and able to import one certificate within the pfx file so far so good but there are three certificates in the pfx file and when loading the pfx with x509certificate i am not able to see the other two certificatesthe certificate was exported with personal information exchange pkcs 12 pfxinclude all certificates in the certification path if possibleenable strong protection requires ie 50 nt 40 sp4 or abovethose are the options selected when exporting the certificates i know there are three certificates because i manually go into the certstore mmc and import it into a personal folder myself,['c#'] +124253,how can you dynamically create variables via a while loop i want to create variables dynamically via to a while loop in python anyone have any creative means of doing this,['python'] +124261,how to detect page scroll to a certain point in jquery imagine this is my pagephellopbr br br br br br br br br br br br p classmyparamy paragraphphow can i alert a message when the user has scrolled down to the paragraph with the class mypara and not before then,['jquery'] +124264,mocking out methods on any instance of a python class i want to mock out methods on any instance of some class in the production code in order to facilitate testing is there any library in python which could facilitate thisbasically i want to do the following but in python the following code is ruby using the mocha library def test stubbing an instance method on all instances of a class productany instancestubsnamereturnsstubbed name assert equal stubbed name someclassthatusesproductget new product name endthe important thing to note from above is that i need to mock it out on the class level since i am actually need to mock out methods on an instance created by the thing i am testinguse casei have a class querymaker which calls a method on an instance of remoteapi i want to mock out the remoteapiget data from remote server method to return some constant how do i do this inside a test without having to put a special case within the remoteapi code to check for what environment it is running inexample of what i wanted in action apyclass aobject def fooself return as foo bpyfrom a import aclass bobject def barself x a return xfoo testpyfrom a import afrom b import bdef new fooself return new fooafoo new fooy bif ybar new foo print success,['python'] +124281,crossthread operation not valid possible duplicatecrossthread operation not valid control accessed from a thread other than the thread it was created on okay i know why this is giving me this errorcrossthread operation not valid control form1 accessed from a thread other than the thread it was created onbut how can i make this workablesystemthreadingthread t new systemthreadingthread do really hard work and then listview1itemsaddlots of items lots more ui worktstarti do not care when or how the thread finishes so i do not really care about anything fancy or over complicated atm unless it will make things much easier when working with the ui in a new thread,"['c#', '.net']" +124285,how does a database cursor work with most drivers for most relational databases the default and preferred way to access results is to use a cursor or iteratorwhat i am guessing is that the database does something likeruns the queryprepares the result stores it in ramreturns the cursor for the result to the clientwhenever the database driver gets a call to fetch the next result it passes that cursor to the database which gives the next resulthowever i am not sure if that is really correct one thing that stumps me is that if the database client and database server are on different nodes and communicating via the network is not this slow does it really use such a lazy approach it makes sense not to return all the data but is there some middle path it takes,['sql'] +124297,how to use the final projectexeconfig file when creating a setup project i have created a console application blahexe with specific appconfigs for dev and prod these are named dev appconfig and prod appconfig i have hooked up an afterbuild target in my csproj file which copies the correct config file to the bin directory as blahexeconfig i have also created a setup project for this console app but i have run into a slight issue it seems that the setup project uses the actual appconfig from the project directory as opposed to the final blahexeconfig located in bin directorybin debug blahexeconfig i want the setup project to use this fileappconfig setup project uses this file at the momentdev appconfigprod appconfighow can i force the setup project to use the final config file generated in the bin folder and not the actual appconfig fileadditional informationmy current solution involves adding another afterbuild command which overwrites the actual appconfig file i do not like approach since it forces me to have an additional file that i do not need also having this file has caused me some grief already since i made changes to the appconfig file which got overwritten when building the question is about how to get the setup project use the final config file in the bin folder and not how to manage the config or ways to create a config file adapted from deploy an appconfig based on build configuration,['c#'] +124304,mysql make an existing field unique i have an already existing table with a field that should be unique but is not i only know this because an entry was made into the table that had the same value as another already existing entry and this caused problems how do i make this field only accept unique values,['mysql'] +124305,how to save jquery selector for later use i have the following codeitem code deletehideitem code deletingshowitem codeslideup400 function thisremove top messagehtmlitem has been deletedi want to save the selector i am using in a variable and use it to perform operation instead of searching the dom everytimeso i save the selector like this var saved item codebut how do i change the rest of the code i am not very familiar with jquery hence wondering how this can be done will this worksaved deletehidesaved deletinghidesavedslideup400 function thisremove top messagehtmlitem has been deleted,['jquery'] +124321,what is recommended way to perform async tasks in wpf are there any standard tools or recommended approaches for async tasks executionupd i understand how to use threads i only need to know the recommended wpf way to block ui while performing async call and how to update progress info,"['c#', '.net']" +124327,android test class fails to compile in eclipse with bound mismatch error i am writing testcases for an android app extending activityinstrumentationtestcase2 the test class looks like thispublic class solutionentryactivitytest extends activityinstrumentationtestcase2solutionentryactivity public solutionentryactivitytest supersolutionentryactivityclass in eclipse this code fails to compile with the error bound mismatch the type solutionentryactivity is not a valid substitute for the bounded parameter t extends activity of the type activityinstrumentationtestcase2tbut solutionentryactivity really is an androidappactivity the type hierarchy is like thisactivity ormlitebaseactivityh abstract kabowieactivity practiceactivity abstract solutionentryactivityi found two eclipse bugs from 2004 and 2005 which seem to deal with a similar problem but these should be long fixedi am using eclipse helios with android 22 and sun java 16any idea whats going on,"['java', 'android']" +124332,html soft hypen without dash i have a little layout problem on a clients website we show contact information of people in a little box the width of that box is constrained as it happens there are people with very long names this is in germany after all and the email address is a concatenation of the given name and family name the result with certain names the email address overflows the constraints given by the about boxinserting a shy before the results in the correct line break but looks like thisjohndoeexamplecomis it possible to suppress that dash i do not want to use br because for 90 of the names the available width is more than enough,['html'] +124334,constructor called on an already created object if i call a constructor on an already constructed object or struct will it allocate new space or just use the existing space so is the first object allocation more resource intensive like thisstruct f int abcd fint a int b a a b b void aint a int b a a b b first constructor callf f f5 6second constructor call on an already constructed objectf f7 8third constructor call on an already constructed objectf7 8is the constructor call more res intesive than the call to a function which does the same fa9 0is the constructor call more resource intesive than the call to a function which does the same void adoes the destructor gets called when i call a constructor on an already created object,['c++'] +124339,different levels of css and the priority over each other i was reading a decent article here on this topic tutorialcsstypesphpit came out highest ranked by google for the search term css style sheets prioritieshowever i think the site misinforms you and is incomplete can someone confirm my suspicions1 user defined style is second lowest priority in order to override other styles with it you need to use important to move it to highest2 it fails to mention the relative priorities of link versus import and import within linka more precise ordering would be 1 wins over 2 etc user defined browser prefs important not google chromeinline style sheet style attribute on html node internal style sheet style in headexternal style sheet importexternal style sheet linkexternal style sheet import inside linkuser defined browser prefs not google chromebrowser default shipped with browsermichael bowers pro css html design patterns is a good source for this too but it fails to mention inlineis there anything else missingps i was inferring important was missing from 28 so user defined appears twice once with important the second time without it so user defined is in essence second lowest the important can naturally be applied at any level,['css'] +124378,problem with 9 patch image as background i have a list view structure with relative layout that usesalternating background images for oddeven elements i am trying to setthe background drawable dynamically by calculating the position itworked fine with the normal bitmap but when i tried to use theninepatch image it breaks the ui all the elements get thistorted whatam i doing wrong could it be how the ninepatch image is created or isthere a different way to use a ninepatch image compared to a normalbitmapmy list view xml goes like thisxml version10 encodingutf8relativelayout xmlnsandroid androidlayout widthfill parent androidlayout heightwrap content androidididid01 androidbackgrounddrawablemy 9patch bg image imageview relativelayout imageview textview textview relativelayoutrelativelayoutmay be the solution here might work for my problem it is exact though i have to try it,['android'] +124383,converting from signed char to unsigned char and back again i am working with jni and have an array of type jbyte where jbyte is represented as an signed char ie ranging from 128 to 127 the jbytes represent image pixels for image processing we usually want pixel components to range from 0 to 255 i therefore want to convert the jbyte value to the range 0 to 255 ie the same range as unsigned char do some calculations on the value and then store the result as a jbyte againhow can i do these conversion safely i managed to get this code to work where a pixel value is incremented by 30 but clamped to the value 255 but i do not understand if it is safe or portable define clamp255v v 255 255 v 0 0 v jbyte pixel pixel clamp 255unsigned charpixel 30i am interested to know how to do this in both c and c,"['c++', 'c']" +124403,how to cutcroptrim a video in respect with time or percentage and save output in different file is there any tutorial or a c library which which help me to accomplish the followingchose a file to editask user to select cutcroptrim method by time or by percentagecutcroptrim the video by time or percentage as chosen say i wishto reduce a 5 minute video to 4 minute video or reduce the video by80save the video as requested in required pathnow steps 1 and 4 i have implemented but could not find a good c library to accomplish 3 and 4i looked up the ffmpeg library but could not find a good c wrapper to accomplish the requirementsany help will be be deeply appreciatedthank you,"['c#', '.net']" +124410,clone google map instance i have a map on a page which thisplays several places with markers and infowindowsnow i would like to put a fullscreen button and load the map into a jqueryui dialog but i have got some problemsis there a way to copy the google map instance i have created in one div into the other divor any other workaround like changing the div associated with the map sciencefiction,['jquery'] +124412,viability of c logging library for asynchronous capturing of high throughput data i am working with a real time system written in c we are looking to use either boost or pantheios for logging the system has some standard logging requirements which i am confident can be met by either framework but in addition we want to be capable of logging all input captured by this system this input will be captured by multiple threads including some threads that have realtime constraints and can not afford significant delays from inefficient logging this should result in a high throughput of data to be loggedi primarily want to know whether either framework can be trusted to manage such high throughput logging from multiple threads without delaying my time critical threads in addition we may need to do some data scrubbing which would require adding some sort of hook which is capable of identifying the capture inputs which have secure data run our data scrubbing hook and maintain a buffer containing mappings of values that were already scrubbedi believe both logging platforms can do this but it is not clear to me with a quick glance at their api can anyone who has used either of these logging tools give me some feedback on how efficient they are in this context how easy it would be to implement what i described or their preference between the two logging frameworks really any information would usefulthanks,['c++'] +124413,indicate to an ajax process that the delayed job has completed i have a rails 3 app that uses delayed job to fetch some data with a class method when the user hits the pagehow can i indicate to the ajax process that the class method has run so that i can stop pollingeditto clarify i want to know when the delayed job has run not when the ajax process has succeeded then i want to pass the delayed job completed status to the running ajax process,['ruby-on-rails'] +124451,how to run maven integration tests against a test environment database i am using maven and the mavenfailsafeplugin to start up jetty during the integrationtest lifecycle phase i then execute a number of itjava junit tests against my running webapp this is working as expected however i would like to connect to a test database for my integration tests i am storing its url in basedirsrctestresourcesjdbcproperties when the jetty plugin runs jettyrun it uses basedirsrcmainresourcesjdbcpropertes instead i tried reconfiguring the jetty plugin via the classesdirectory property to use projectbuildtestoutputdirectorybut the testclasses directory is missing my actual compiled project classes as well as the resources stored inbasedirsrcmainresources note surefire adds the test resources to the classpath followed by the main resources such that anything found in both will use the test version because it is found first in the classpathany ideas on how to get this set up correctlythankseditwell it seems there are configuration properties on the jettyplugin to deal with thistestclassesdirectory the directory containing generated test classesusetestclasspath if true the and the dependencies of test will be put first on the runtime classpathunfortunately they do not work here is the relevant portion of my pomxml testresources testresource filteringtruefiltering directorysrctestresourcesdirectory testresource testresources plugins plugin groupidorgmortbayjettygroupid artifactidmavenjettypluginartifactid version6126version configuration contextpathcontextpath stopport8005stopport stopkeystopstopkey configuration executions execution idstartjettyid phasepreintegrationtestphase goals goalrungoal goals configuration daemontruedaemon usetestclasspathtrueusetestclasspath testclassesdirectoryprojectbuildtestoutputdirectorytestclassesdirectory configuration execution execution idstopjettyid phasepostintegrationtestphase goals goalstopgoal goals execution executions plugin plugin artifactidmavenfailsafepluginartifactid version26version executions execution goals goalintegrationtestgoal goalverifygoal goals execution executions configuration usefilefalseusefile configuration plugin,['java'] +124453,how can i correctly format currency using jquery i do not need a mask but i need something that will format currencyin all browsers and not allow for any letters or special chars to be typed thanks for the helpexamplevalid 50 1053not valid w4500 343r6,['jquery'] +124494,how to remove unconverted data from a python datetime object i have a database of mostly correct datetimes but a few are broke like so sat dec 22 123408 pst 20102015without the invalid year this was working for meend date souptr4contents1rendercontentsend date timestrptimeend datea b d hms z yend date datetimefromtimestamptimemktimeend datebut once i hit an object with a invalid year i get valueerror unconverted data remains 2 which is great but im not sure how best to strip the bad characters out of the year they range from 2 to 6 unconverted charactersany pointers i would just slice end date but im hoping there is a datetimesafe strategy,['python'] +124503,read debugging information at runtime from an application i have some questions regarding debugging symbols and what can be done with them besides well debugging i am mostly interested in answers regarding gcc but i would also be happy to know how it looks like under other compilers including msvcfirst of allwhat are the common formatstypes of debugging symbols how do they relate to compilers and platforms is it always the same format on gcc and mingw among platformscan i check in runtime whether the build has them and what format are they inand some more practical questions how can icheck the current file and line numberobtain the qualified function name being executedobtain a full current stack tracelet me emphasize that i am talking about runtime checks all of those can be read and prettyprinted by gdb but i do not know how much info comes from the debugging symbols themselves and how much from the source code which gdb also has access tomaybe there is a library which is able to parse the debugging symbols and yield such informationare the debugging symbols standarthised well enough that i can expect some degree of portability for such solutions,"['c++', 'c']" +124517,how come this code does not deadlock should not the log method blocknamespace sandbox class program static void mainstring args var log new logger lock log logloghello world public class logger public void logstring message lock this consolewritelinemessage,"['c#', '.net']" +124518,android edittext with progress bar i am building a browser and i have an address bar as edittext on top of the webview what i would like to do is to present the loading of the page graphically in the background of the edittext much like in the iphones browser is this possiblethanksupdateso far i have tried the clipdrawable approach what i did was to take the stock drawable androidrdrawableeditbox background and create 2 versions a white background and a blue one to show the progress then i would create a layerdrawable like so bardrawable addressbargetbackground drawable progress getresourcesgetdrawablerdrawableeditbox progress cbardrawable new clipdrawableprogress gravityleft clipdrawablehorizontal cbardrawablesetlevel0 layerlist new layerdrawablenew drawable bardrawable cbardrawable addressbarsetbackgrounddrawablelayerlistand then i would call setlevel as the loading progresses the problem now is that there are weird issues such as the white drawable is too big or it moves to the topwhat do you think,['android'] +124521,how to build a regular expression c to identify a string of eight 1s 0s i am trying to build a regex to determine if a string contains a byte of binary digits ex 10010011i believe that 0101010101010101 would work but i am sure theres a more efficient way of doing it and being new to regular expressions i am not sure what that is,['c#'] +124523,where to put compiletimeconstant arrays say i have an array storing the first 10 primes like thisconst int primes 2 3 5 7 11 13 17 19 23 29this is all very fine and simple as long as i have 1 cpp file however if i have multiple cpp files i do not really know where to put this arrayan obvious solution would be this primeshextern const int primes10 primescppextern const int primes 2 3 5 7 11 13 17 19 23 29however the problem with this is that the primes array is no longer a compile time constant say xcpp wants to do some heavy calculations involving primesk with k a compile time constant it would have to do an actual memory lookup i do not like thatso where do i put this array so thatit is only once in the binary not once per cpp filearraysome constant is also a compiletime constantedithow about thisinline int primeint i static const int primes 2 3 5 7 11 13 17 19 23 29 return primesips even the obvious solution above took me quite some time to write apparently const variables have internal linking by default so i had to add extern to the primescpp file to make it work,['c++'] +124530,a grid layout of icontext buttons i am attempting to create a 3 x 3 grid of items each item consists of an imageview on top of a textview unfortunately i am having issues getting everything to play nicelyhere is my attempt to get 2 such items side by side the text views do not even show and the icons are squished together instead of evenly spacedtablelayout xmlnsandroidandroidlayout widthfill parentandroidlayout heightfill parentandroidstretchcolumns1 androidgravitycenter androidpaddingleft40px androidpaddingright40px tablerow linearlayout androidorientationvertical androidlayout widthfill parentandroidlayout heightfill parent imageview androidididusertoolsimage androidsrcdrawableftnicon androidlayout widthwrap content androidlayout heightwrap content textview androidtextuser accounts androidgravityright androidpadding3dip androidtextcolorf linearlayout linearlayout androidorientationvertical androidlayout widthfill parentandroidlayout heightfill parent imageview androidididqueueimage androidsrcdrawableftnicon androidlayout widthwrap content androidlayout heightwrap content textview androidtextqueue management androidgravityright androidpadding3dip androidtextcolorf linearlayouttablerowtablerow textview androidtexttest 3 androidpadding3dip androidtextcolorf textview androidtexttest 4 androidgravityright androidpadding3dip androidtextcolorf tablerowtablelayoutmy goal in the end is to have a grid of clickable items where the item is an image and text for a main menu can anyone guide me on what layouts i should use to achieve this,['android'] +124531,where do i put the jquery script tag in all the documentation i see the jquery script tag beneath title in the head but then when i go into some other sites the initializr template is the first off the top of my head they drop it into the bottom of the body you know right before bodywhich of these two is right,"['javascript', 'jquery']" +124534,app pool identity versus impersonation identity i found only one thread relating to this but it did not answer the question i am curious to a link or explanation of the difference between setting an impersonation user via in the webconfig versus setting the application pool identity in iis they seem to be independent and am confused on the detailed differences thanks,"['c#', 'asp.net']" +124544,jquery send string as post parameters i want to send a string as an ajax post parameterthe following codeajax type post url data foobarcalibrinolibri success functionmsg alertwowmsg is not working why,['jquery'] +124559,iphone smooth animation for uitableviewcell height change including content update possible duplicatecan you animate a height change on a uitableviewcell when selected i have a table view into which where you click on a swich into a cell many cells of the table view may change their height it is a little bit complicated to compute which cells will change their size so i would like not to call twice the same codei have a heightforrowatindexpath method this is the complicated oneis there a way to animate the cell grow or reduce feature without impacting the one that does not change i have tried uiview animations reloaddata for sections with animation but i did not find anything smoothi have tried to catch each cell that will have to change and call a reloaddata with animation on each cell it is near to work but the cells are updating one after the other and as i said before i do not want to do that because i must call twice the heightforrowatindexpath methodwhat i would like is something that can animated each cell that has a changing height with somthing like a grow or reduce movement and not a fade onedo you know a way to do that one more thing the content of the cell is changing a little bit when size change some text added back color changing and things like that,['iphone'] +124561,c how to know if a given path represents a root drive how can i know if a given directory is a root driveaside from checking if its path equals to a b c etc,['c#'] +124580,dynamically creating jquery mobile pages using jquery templates i am building a workout catalog using jquery mobile for the ui and jquery templates to deal with the html i have been able to append html to an already created page and get jquery mobile to change the markup thanks to the page functionhowever i want to be able to create new jq mobile pages i can inject code into divs with datarolepage call page on it and it is all fine but appending a fully made page to the body does not workeditthis question and my answer refers to jquery mobile alpha 3,['jquery'] +124585,aspnet membership change password not working i have this code for changing a users password when they click the password reset button with extra code to log to elmah so i can try to figure out what is going wrongthis is in aspnet mvc 2 using the standard aspnet membership provider with a simple view like thisnew password confirm password reset cancelthe route to this view is accountresetguid where guid is the users id in the aspnet membership databasethe key portion of the code is where it calls userchangepassword you can see that it logs a message when successful the problem is that for some users the success message is logged but they can not log in with the new password for other users it logs the success message and they can log inif userchangepasswordpwd confirmpassword errorsignalfromcurrentcontextraise new exceptionresetpassword changed successfully return jsonnew msg you have reset your password successfully jsonrequestbehaviorallowget the full code listing ishttppostpublic jsonresult resetpasswordstring id string newpassword string confirmpassword errorsignalfromcurrentcontextraisenew exceptionresetpassword started for id viewdatapasswordlength membershipminrequiredpasswordlength if stringisnullorwhitespacenewpassword errorsignalfromcurrentcontextraise new exceptionresetpassword new password was blank modelstateaddmodelerror form please enter a new password return jsonnew errors modelstateerrors jsonrequestbehaviorallowget if newpasswordlength membershipminrequiredpasswordlength errorsignalfromcurrentcontextraise new exceptionresetpassword new password was less than minimum length modelstateaddmodelerror form stringformatthe password must be at least 0 characters long membershipminrequiredpasswordlength return jsonnew errors modelstateerrors jsonrequestbehaviorallowget if stringisnullorwhitespaceconfirmpassword errorsignalfromcurrentcontextraise new exceptionresetpassword confirm password was blank modelstateaddmodelerror form please enter the same new password in the confirm password textbox return jsonnew errors modelstateerrors jsonrequestbehaviorallowget if confirmpasswordlength membershipminrequiredpasswordlength errorsignalfromcurrentcontextraise new exceptionresetpassword confirm password was less than minimum length modelstateaddmodelerror form stringformatthe password must be at least 0 characters long membershipminrequiredpasswordlength return jsonnew errors modelstateerrors jsonrequestbehaviorallowget if confirmpassword newpassword errorsignalfromcurrentcontextraise new exceptionresetpassword new password did not match the confirm password modelstateaddmodelerror form please enter the same password again return jsonnew errors modelstateerrors jsonrequestbehaviorallowget bool ismatch validationhelperisguidid if stringisnullorwhitespaceid ismatch errorsignalfromcurrentcontextraise new exceptionresetpassword id was not a guid modelstateaddmodelerror form an invalid id value was passed in through the url else id exists and is kosher see if this user is already approved get the id sent in the querystring guid userid new guidid try get information about the user membershipuser user membershipgetuseruserid if user null could not find the user errorsignalfromcurrentcontextraise new exceptionresetpassword could not find user by id id modelstateaddmodelerror form the user account can not be found in the system else errorsignalfromcurrentcontextraise new exceptionresetpassword user is userusername string pwd userresetpassword if userchangepasswordpwd confirmpassword errorsignalfromcurrentcontextraise new exceptionresetpassword changed successfully return jsonnew msg you have reset your password successfully jsonrequestbehaviorallowget errorsignalfromcurrentcontextraise new exceptionresetpassword failed to change the password for an unknown reason catch exception ex errorsignalfromcurrentcontextraise new exceptionresetpassword ex return jsonnew error exmessage exinnerexceptionmessage jsonrequestbehaviorallowget return jsonnew errors modelstateerrors jsonrequestbehaviorallowgetedit adding a bounty to try to get this solved this is one of the most annoying problems on my issue list and i have no idea how to proceed,"['c#', '.net']" +124590,retrieving a filename for an alasset how can the filename be extracted from an alassetis there a way to get this via the url or some other way,['iphone'] +124617,how to get the list of all engines in rails 3 app according to rails engines extending functionality in rails 2x one could dorailsinitializernewrailsconfigurationplugin loaderenginesthis code is not working in rails 3actioncontrollerroutingerror undefined method new for railsinitializermodule configapplicationrb12in require or loadwhat do i need to do in rails 3 to get such list of enginesthis is needed for extending controllers of a rails engine in the main app,['ruby-on-rails'] +124619,thisable predictive text in edittext i think this is a pretty simply question but how do i thisable the predictive text for an edittext in android do i set a property in the edittexts xml or a property in the edittexts object or both thanks,['android'] +124621,i cannot install sqlite3 gem possible duplicatesqlite3ruby install error on ubuntu hey guysi use aptget to install sqlite3 in my vps which is running ubuntu 10i can run sqlite3 with no problem but when i try to use gem install sqlite3 i got this errorrootmakserver gem install sqlite3building native extensions this could take a whileerror error installing sqlite3 error failed to build gem native extension usrlocalbinruby extconfrbchecking for sqlite3h nosqlite3h is missing try port install sqlite3 universalor yum install sqlite3devel and check your shared library search path thelocation where your sqlite3 shared library is located extconfrb failed could not create makefile due to some reason probably lack ofnecessary libraries andor headers check the mkmflog file for moredetails you may need configuration optionsprovided configuration options withoptdir withoutoptdir withoptinclude withoutoptincludeoptdirinclude withoptlib withoutoptliboptdirlib withmakeprog withoutmakeprog srcdir curdir rubyusrlocalbinruby withsqlite3dir withoutsqlite3dir withsqlite3include withoutsqlite3includesqlite3dirinclude withsqlite3lib withoutsqlite3libsqlite3dirlibgem files will remain installed in usrlocallibrubygems191gemssqlite3133 for inspectionresults logged to usrlocallibrubygems191gemssqlite3133extsqlite3gem makeoutany advice,['ruby'] +124624,exclusive css for iphoneandroid i am making a mobilefriendly stylesheet for a page of mine is there a simple way to make it show that stylesheet to iphoneandroid users or do i have to pull the useragents and figure it out that way and how do i do thatalso any tools to make this sort of web dev easier,"['iphone', 'android', 'html', 'css']" +124625,how do i use beaker caching in pyramid i have the following in my ini filecacheregions default term second short term long termcachetype memorycachesecondexpire 1cacheshort termexpire 60cachedefault termexpire 300cachelong termexpire 3600and this in my init pyfrom pyramid beaker import set cache regions from settingsset cache regions from settingssettingshowever i am not sure how to perform the actual caching in my viewshandlers is there a decorator available i figured there would be something in the response api but only cache control is available which instructs the user to cache the data not cache it serversideany ideas,['python'] +124626,how do i get a date without time in java continuing from this thiscussion java program to get the current date without timestampwhat is the most efficient way to get a date object without the time is there any other way than these twomethod 1simpledateformat sdf new simpledateformatymmdd date datewithouttime sdfparsesdfformatnew datemethod 2calendar cal calendargetinstancecalsetcalendarhour of day 0calsetcalendarminute 0calsetcalendarsecond 0calsetcalendarmillisecond 0datewithouttime calgettimeupdate1 i knew about joda i am just trying to avoid additional library for such a simple i think task but based on the answers so far joda seems extremely popular so i might consider it2 by efficient i mean i want to avoid temporary object string creation as used by method 1 meanwhile method 2 seems like a hack instead of a solution,['java'] +124629,fast way of getting the dominant color of an image i have a question about how to get the dominant color of an image a photo i thought of this algorithm loop through all pixels and get their color either red green yellow orange blue magenta cyan white grey or black with some margin of course and it is darkness light dark or normal and afterwards check which colors occurred the most i think this is slow and not very precise is there a better wayif it matters it is a uiimage taken from an iphone or ipod touch camera which is at most 5 mpx the reason it has to be fast is that simply showing a progress indicator does not make very much sense as this is for an app for people with bad sight or no sight at all because it is for a mobile device it may not take very much memory at most 50 mb,['ios'] +124630,nsstring how to go from algebra to algebra does anyone knows hoe to get a nsstring like algebra to algebra without the accent and capitalize only the first letterthanksrl,['iphone'] +124631,set innerhtml of an iframe in javascript how can i set the innerhtml of an iframe i mean how to set not getwindowifrm namedocumentinnerhtml h1hih1 does not work and the same for other solutionsiframe and parent document are on the same domaini would need to set html of the whole document iframe not its bodyi would need to avoid jquery solution,['javascript'] +124642,eclipse plugin for recording time spent on given projectfilemethod often i found myself working on 2 or more projects in one and the same monthweek sometimes i am forced to switch between the projects during the day and it becomes a nightmare to record correctly hours spend on each projectis there a plugin for eclipse that will record time spent on given projectfilemethod i imagine that it will contain some timer that counts time spent on each item which stops when detects inactivityi know that such measurement will not be very precise but i do not need such a precision i need something like a log124501 opened project proj1124503 opened file somefilejava124807 opened file someotherfilejava125022 focus switched to somefilejava132021 closed project proj1132025 opened project proj2 and so onsuch log will allow me to calculate how many time did i spent this day on proj1 how many on proj 2 etc,['java'] +124659,ios unable to set text of uilabel ok let me explain the situation i have two view controller let us call them first ans secondfirstviewcontroller inherit from uitableviewcontrollersecondviewcontroller inherit from uiviewcontrollerthe interface for the secondviewcontroller is made with interface builder and contains simply a label and an uiprogressview both label and uiprogressview outlet are connected with the right files owner secondviewcontroller a little bit of code in firstviewcontroller the following method is triggered by a notification void addtransfernsnotification notification nslognotification received nsdictionary transferinfo notification userinfo i think the problem is here atransfer dbtransfer alloc initwithnibnamedbtransfer bundlenil atransfersrcpath transferinfo objectforkeysrcpath atransferdstpath transferinfo objectforkeydstpath atransfer starttransfer transfer addobjectatransfer selftableview reloaddatathose are the tableview datasource methods nsintegernumberofsectionsintableviewuitableview tableview return the number of sections return 1 nsintegertableviewuitableview tableview numberofrowsinsectionnsintegersection nslogd numberofrowsinsectiontransfer count return transfer count uitableviewcell tableviewuitableview tableview cellforrowatindexpathnsindexpath indexpath static nsstring cellidentifier celluitableviewcell celltableview dequeuereusablecellwithidentifiercellidentifierif cell nil cell uitableviewcell alloc initwithstyleuitableviewcellstyledefault reuseidentifiercellidentifier autoreleasecellcontentview addsubviewtransfer objectatindexindexpathrow viewreturn cellthis is the code of secondviewcontrollerhinterface dbtransfer uiviewcontroller dbrestclientdelegate iboutlet uilabel filenamelabeliboutlet uiprogressview transferprogressnsstring srcpathnsstring dstpathdbrestclient restclientproperty nonatomicretain iboutlet uilabel filenamelabelproperty nonatomicretain iboutlet uiprogressview transferprogressproperty nonatomicretain nsstring srcpathproperty nonatomicretain nsstring dstpath void starttransferendthis is a method inside secondviewcontrollerm void starttransfernslognsrcpathdstpathif filenamelabel nslognullselffilenamelabel settextsrcpath lastpathcomponentselffilenamelabeltexttestnslogfilenamelabeltextrestclient dbrestclient alloc initwithsessiondbsession sharedsessionrestclientdelegateselfrestclient loadfilesrcpath intopathdstpathas you can see inside the starttransfer i check if filenamelabel is null and it is and i do not understand why maybe the null value is related to the allocation of the ivar atransfer btw it is impossible to set the text of the label,['ios'] +124690,jquery ui autocomplete add a css class to specific items i am using jquery uis autocomplete widget and i am fetching the items to thisplay through a callback as described in the referencei have a usecase where i need to present some of the items that i retrieve from the server slightly differently than others so that the user understands there is a difference between these items in my case some of the items are personal and some are global i would like to let the personal items stand out by adding a css class to them so that they have a slightly different backgroundis this possible i have seen in the reference documentation that an addon exists that allows me to put arbitrary html in the items but i feel that is suboptimal when all i really need to do is add a class in some casesi think i would end up with something like thismyelementautocomplete define callback to format results source functionreq add pass request to server var baseurl getitemsphp getjsonbaseurl req functiondata create array for response objects var suggestions process response eachdata functioni val var entry new object if valpersonal true add some css class somehow entryid valid suggestionspushentry pass array to callback addsuggestions,['jquery'] +124691,are delegates more lightweight than classes i tried thisassembling a c created executable but i could not come to a conclusion what i would like to know is that if for the clr cs delegates are really special entities or just a compiler sugari ask this because i am implementing a language that compiles to c and it would be much more interesting for me to compile anonymous functions as classes than as delegates but i do not want to use a design that later i will regret as they might be heavier on memory i think of javas permgen to base my questioning on even though i know there is no such thing for the clrthank youeditto be a little more clear i would like to know if there is and what are the differences betweenvoid main funcint int int add delegateint a int b return a band for exampleclass anonfuncion 1219023 fun3 public override int invokeint a int b return a b editi think that there might be a great difference betweenclass program static int addint a int b return a b static void main funcint int int add programadd andclass function 432892 fun3 public override int invokeint a int b return programadda b i read somewhere though that the syntax funcint int int add programadd is only a sugar for funcint int int add delegateint a int b return programadd but i really do not know if that is really truei could also see that the c compiler already caches all those instances so they are constructed only once i could do the same with my compiler though,['c#'] +124718,how to use jquery instead of prototype in a rails 3 application i would like to use jquery instead of prototype in my rails 3 applicationwhat is the official rails 3 way to do this,['jquery'] +124719,large file upload though html form more than 2 gb is there anyway to upload a file more than 2 gb using simple html form upload previously i have been uploading large files through silverlight using chunking dividing a large file into segments and then uploading segments one by one then reassemble segments at servernow we have a requirement that we just have to use simple html though gwt form uploads please guide me if there is any way to achieve large file upload this wayif it is impossible to do it using simple html can anyone guide me about how i can divide upload a file in segments using flex,['html'] +124728,get a single file from a remote mercurial repository is there a way to programmatically download a single file from a remote mercurial repository in java i have asked a very similar question regarding git now i am hoping i can do something similar with mercurial as welli prefer a solution which uses as little bandwidth as possible preferably only downloading that single file i do not need to browse the repository i already have the files pathi am not concerned with the history of the file i only want its latest versiona solution that only prints the file to the output is great as well of course it does not really have to save the file to thisk i can do that myselfi prefer a solution which does not depend on other applications eg an installation of a mercurial client on the machine a java library which contains a mercurial client implementation itself would be optimal however i will happily invoke hg if there is no other wayfrom what i understand about how mercurial works allowing working only against local repositories this could prove to be problematic but as i was able to do this with the similar git scm i am hoping there is a solution for mercurial as well,['java'] +124730,cxna multiplication faster than division i saw a tweet recently that confused me this was posted by an xna coder in the context of writing an xna gamemicrooptimization tip of the day when possible use multiplication instead of division in high frequency areas it is a few cycles fasteri was quite surprised because i always thought compilers where pretty smart for example using bitshifting and recently read a post by shawn hargreaves saying much the same thing i wondered how much truth there was in this since there are lots of calculations in my gamei inquired hoping for a sample however the original poster was unable to give one he did however say thisnot necessarily when it is something like center width 2 and i have already determined yes it is worth it so i am curiouscan anyone give an example of some code where you can change a division to a multiplication and get a performance gain where the c compiler was not able to do the same thing itself,['c#'] +124731,audio stream with avplayer there is a lot of streaming apps out there for ios they all use a player which i assume is the avplayer yet it seems impossible to find a decent documentation with sample code that works i am pretty sure it is nothing but a few line of codes but i just cannot figure out whats wrong i have an exc bad access error when trying to call the play method but the url is good and there is an instance of the player voidviewdidload super viewdidload load the array with the sample filensstring urladdress create a url objecturlstream nsurl urlwithstringurladdress selfplayer avplayer playerwithurlurlstream urladdress releasethe urlstream is a property with retain attribute then i have an ibaction that fires when the button is clicked and that tries to play it and that is where it crashes ibactionplaybuttonpressed player play can my problem be because i am trying to play mp3 or what the real url adress i am using works fine when i use a webview to load itif anyone could point me to a good sample not the avfoundation ou avplayer docs from apple nor the avtouchcontroller project it would be realy appreciated thanks,"['iphone', 'ios']" +124745,do anonymous classes always maintain a reference to their enclosing instance i am working with some code where one object foo is creating anotherobject bar and passing it a callable after this foo will returnbar and then i want foo to become unreachable ie available forgarbage collectionmy initial thought was to just create the callable anonymously egclass foo public bar createbar final int arg1 final int arg2 final int arg3 return new callablebaz override public baz call return new bazarg1 arg2 arg3 it occurred to me that this might not actually work as desired howeveras an inner class typically keeps a reference to its enclosing objecti do not want a reference to the enclosing class here because i want the enclosing object to becollected while the callable is still reachableon the other handdetecting that the enclosing instance is never actually referred toshould be pretty trivial so perhaps the java compiler is smart enoughto not include a reference in that caseso will an instance of an anonymous inner class hold on to areference to its enclosing instance even if it never actually uses theenclosing instance reference,['java'] +124752,can i avoid the native fullscreen video player with html5 on iphone or android i have built a web app that uses the html5 tag and javascript code that renders other content synchronized with the running video it works great in desktop browsers firefox chrome and safari on an iphone or a droidx the native video player pops up and takes over the screen thus obscuring the other dynamic content that i want to thisplay simultaneously with the videois there any way around this if necessary i will figure out how to write native apps for both those platforms but it would save me a ton of effort if i could just stick with html5javascript,"['iphone', 'android']" +124759,comparing objects in objc how does one compare objects in objectivecis it as simple as i want to check an array for an object and if it doesnt exist add it to the array otherwise remove it from the array,['objective-c'] +124760,taskfactorystartnew with uncaught exceptions kills w3wp i just transitioned some of my websites code from using queueuserworkitem to taskfactorystartnewi have some bad code that threw an exception and it ultimately shut down w3wp running iis 75 on windows server 2008 r2 x64 taskfactorystartnew methodthatthrowsexception application w3wpexe framework version v4030319 description the process was terminated due to an unhandled exception exception info systemaggregateexception stack at systemthreadingtaskstaskexceptionholderfinalizeexception systemaggregateexceptionmessage a tasks exceptions were not observed either by waiting on the task or accessing its exception property as a result the unobserved exception was rethrown by the finalizer threadstacktrace at systemthreadingtaskstaskexceptionholderfinalizeinnerexception systemdatasqlclientsqlexceptioni would have assumed an exception would have generated an event log and not have killed w3wp is this a wrong assumption,['c#'] +124789,inserting new attribute to a document using mongodb python i am new with mongodb coming from couchdb and i am having issues with adding new attributes to my documents in mongdb using the mondb python driverfor example i have the following document id123456textthis is niceand i want to insert a new attribute for example id123456textthis is nicecreated timedatetimedatetimenowhow do i go about adding the created time attribute to my documentthanks,['python'] +124799,algorithm for selecting all edges and vertices connected to one vertex i am using boost graph to try and make sense of some dependency graphs i have generated in graphviz dot formatunfortunately i do not know very much about graph theory so i have a hard time framing what i want to know in terms of graph theory lingofrom a directed dependency graph with 150 vertices i would like to zoom in on one specific vertex v and build a subgraph containing v all its incoming edges and their incoming edges all its outgoing edges and their outgoing edges sort of like a longest path through vthese dependency graphs are pretty tangled so i would like to remove clutter to make it clearer what might affect the vertex in questionfor example given g va b c d v v e f if i were to run the algorithm on c i think i want g va b c d fnot sure if b f should be included as well i think of it as all vertices before c should have their inedges included and all vertices after c should have their outedges included but it seems to me that that would lose some informationit feels like there should be an algorithm that does this or something more sensible not sure if i am trying to do something stupid cf bf above but i am not sure where to start looking thanks,['c++'] +124807,how to create spring bean with collection data decoupled from parent bean spring has ability to initialisate values of core java collection typesi have a complex collection type mapstring setstring map and it inital value defined in spring configbean iddao classrumypkgdaodaoimpl property namedatasource refdatasource property namemap map entry keytable set valuecommentvalue valueindexvalue set entry entry keyview set valuecommentvalue set entry map propertybeani want rewrite my config in next manner split it on 2 beans for more readability bean iddao classrumypkgdaodaoimpl property namedatasource refdatasource property namemap refidmymap beanbean idmymap entry keytable set valuecommentvalue valueindexvalue set entry entry keyview set valuecommentvalue set entrybeancan i achieve that with no creating additional classes,['java'] +124825,php function to evaluate string like 21 as arithmetic 211 i was just wondering if php has a function what would take in the string like 21 and produce the arithmetic result of it or will i have to do this manually with explode to get the values left and right of the arithmetic operatorthank you for your answers,['php'] +124841,is there a general string substitution function similar to sl4fj with sl4fj if i want to construct a string message there is a nice approach which makes use of substitutions for instance it might be something likeloggerinfoaction occured on object objectagetaction objectbif there are more than a few substitutions required then it is something likeloggerinfoaction occured on object with outcome new objectobjectagetaction objectb outcomemy question is is there a generic way for me to create a string and not just a slf4j log message something likestring str somemethodaction occured on object objectagetaction objectborstring str somemethodaction occured on object with outcome new objectobjectagetaction objectb outcomeif it is in the standard java library what would that somemethod bethanks,['java'] +124843,how can i check if a background image is loaded i want to set a background image on the body tag then run some code like thisbodycssbackgroundimageloadfunction alertbackground image done loading this does not workhow can i make sure the background image is fully loaded,"['javascript', 'jquery']" +124862,how to convert datetime string into minutes since unix epoch i need to convert datetime in a text file into number of minutes elapsed since unix epoch ie january 1st 1970eg 20060101 0714380 into 18934874i am using java to parse the filethanks,['java'] +124870,date and time formatting depending on locale i am new to both java and android development so this might be a stupid question but i have been searching for days now and cannot find a solutioni try to output a javautildate depending on the users localesearching on stackoverflow lead me to thisjavautildate date new datestring datestring dateformatgetdateformatgetapplicationcontextformatdatethis outputs20022011on my french localized phone almost finehow can i also output the hours minutes and seconds parts of the date using the users locale i have been looking in the android documentation but could not find anythingmany thanks,"['java', 'android']" +124894,two strings for key of a dictionary i have two string that i d like to use them as the dictionary key but i m kinda lazy to create another object calculate the hashcode of the strings etcso instead of that can i get the hashcodes of two string add them and use the result as the key of dictionaryit s possible to cause collisions rightany ideas,['c#'] +124905,find activerecord object by maximum field value of a child object how can i find the object associated with the results of an activerecord calculation rather than a valuefor example i have parent which has many children i would like to find the child with the maximum valuei understand that i can do parentchildrenmaximumvalue but this returns the maximum value is there a method similar to maximum and minimum that returns the entire object instead of the value so that i can use different fields from the maximum object,['ruby-on-rails'] +124907,unix pipes between child processes i am trying to write a program that will spawn an arbitrary number of child processes and pipe between them similar to a command line pipeline in my case i am trying to do ls l more and output that to stdout then have the parent continue executing more commandsi have the following code as a minimal exampleint main int argc const char argv int fd2 pipefd chdirdirectorywithlotsoffiles create one child process for more int pid fork if pid 0 closefd1 int ret dup2fd00 if ret 0 perrordup2 char argv10 argv0 more argv1 null execvpmore argv create another child process for ls int pid2 fork if pid2 0 int ret dup2fd11 if ret 0 perrordup2 char argv10 argv0 ls argv1 l argv2 null execvpls argv wait for the more process to finish int status waitpidpid status 0 printfdonen return 0now when i execute the program enclosed in a main function of course what i end up with is more which is expected i will hit d to page down mores output and u to go up and it seems to work fine but when i reach the bottom instead of exiting like more does it just leaves a blank line ctrlc works to exit it but it exits the entire program meaning the done line never gets printed a movie is available here that illustrates what happens note that at the very end i press ctrlc to get back to bashany thoughts on this i am just trying to figure out how to change it to where instead of going to a blank line after more reaches the bottom more quits and returns to the parent process so it can continue executing,['c'] +124916,how can you get the app id for my iphone application before i submit it to apple i am using appirater for my iphone application and it requires me to put in the appirater app id which is described as the apple generated software id how do i get this id while my app is still under development,['iphone'] +124917,format of devinputevent what is the format of the character devices located in devinputevent in other words how can i decode the character stream a python example would be greatly appreciatedi have been googling like crazy to no avail please help,['python'] +124930,turbo clike editor do you know if there is some borlands turbo c clone textonly ide or something similar for unix boxesi want to have a c ide editorcompilerdebugger in text mode available through my console terminal,['c++'] +124933,jquery returning parsererror for ajax request been getting a parsererror from jquery for an ajax request i have tried changing the post to a get returning the data in a few different ways creating classes etc but i cant seem to figure out what the problem ismy project is in mvc3 and i am using jquery 15i have a dropdown and on the onchange event i fire off a call to get some data based on what was selecteddropdown this loads the views from the list in the viewbag and firing the event works fine var viewhtmls new dictionarystring object viewhtmlsadatabind value viewid viewhtmlsaddonchange javascriptpagemodelloadviewcontentnameshtmldropdownlistview listselectlistitemviewbagviews viewhtmlsjavascriptthisloadviewcontentnames function ajax url adminajaxgetviewcontentnames type post datatype json data viewid viewval success function data alertdata error function data debugger alerterror the above code successfully calls the mvc method and returnsviewcontentid1nametopcontentnotecontent on the top viewcontentid2namebottomcontentnotecontent on the bottombut jquery fires the error event for the ajax method saying parsererror,"['javascript', 'c#', 'jquery', 'asp.net']" +124942,make arraylisttoarray return more specific types so normally arraylisttoarray would return a type of objectbut supposed it is an arraylist of object custom how do i make toarray to return a type of custom rather than object,['java'] +124945,how does one animate the android sync status icon i simply want to start and stop the sync icon that is in the status bar i thought it would be a simple call using notificationmanager but i cannot find the documentation or sample qa on the web or so,['android'] +124948,this is the htaccess code in wordpress can someone explain how it works this is the htaccess code for permalinks in wordpress i do not understand how this works can someone explainifmodule mod rewritecrewriteengine onrewritebase rewriterule indexphp lrewritecond request filename frewritecond request filename drewriterule indexphp lifmodulei googled and found out that f and d part means to give real directories and files higher prioritybut then what are indexphp l and rewriterule indexphp l how does wordpress process categories tags pages and etc with just thisdoes it happen internally if so i am interested in learning how to do it in phpthanks,['php'] +124950,changing the child elements css when the parent is hovered with jquery first of all i am assuming this is too complex for css3 but if there is a solution in there somewhere i would love to go with that insteadthe html is pretty straightforwarddiv classparent div classchild text block 1 divdivdiv classparent div classchild text block 2 divdivthe child div is set to thisplaynone by default but then changes to thisplayblock when the mouse is hovered over the parent div the problem is that this markup appears in several places on my site and i only want the child to be thisplayed if the mouse is over it is parent and not if the mouse is over any of the other parents they all have the same class name and no idsi have tried using this and children to no avail any help would be greatly appreciated thanksparenthoverfunction thischildrenchildcssthisplayblock function thischildrenchildcssthisplaynone,"['jquery', 'css']" +125031,jquery functions what is the use of writing a jquery function like sofunction myfunction what i mean is why wrap the function in,['jquery'] +125034,how do i show enum values in a combobox how do i show enum values in a combobox the code below result in the combobox having all thisplayed names being casehandlercstate i wanted it to have the actual names of the enum valuesmy enum is defined as followspublic enum casestate active 1 finished problemi have a class that is defined as thispublic class cstate public string name public int id public cstateint idstring name name name id id and the code for populating my comboboxarraylist al new arraylistforeach string cs in enumgetnamestypeofcasestate cstate aenum new cstateintenumparsetypeofcasestatecscs aladdaenumcbstatethisplaymember namecbstatevaluemember idcbstatedatasource al,['c#'] +125063,java threads and main thread whats the best way to make main thread to wait until all threads are finishedforint i0ini thread tnew thread tstartwait for all threads to finish,['java'] +125090,expression trees and nullable types i have been playing around with expression trees i have the following simple method that performs a query by dynamically creating an expression tree itemtype is a nullable int in the database and also in the ef entity class for some reason though the query throws the error of unhandled exception systeminvalidoperationexception the binary operator equal is not defined for the types systemnullable1systemint32 and systemint32i do not think i am asking ef to convert anything i have got my parameter defined as int which is what i thought it should benote i have looked at thisworking with nullable types in expression treesbut this guy is trying to pass in his nullable int value typed as object which ef i guess has problems with i am actually declaring this as the right type ab initio public void getresultcollectiont myentities db new myentities var result dbcreatequerytstringformat0 typeoftname s int itemtypevalue 1 var param expressionparametertypeoft var lambda expressionlambdafunct bool expressionequal expressionpropertyparam itemtype expressionconstantitemtypevalue param var list resultwherelambdatolist editi have also tried itemtypevaluevalue same error,['c#'] +125095,pygtk how do i make an image automatically scale to fit it is parent widget i have a pygtk app that needs to load an image of unknown size however i am having the problem that if the image is either very big or very small the window layout becomes thistorted and hard to use i need some way of making the image automatically scale to fit its parent widget unfortunately after doing some research it seems there is no code built in or otherwise that does what i am looking forhow could i go about writing something to do this i would have thought that somebody would have written some code for this already is there something that i missed,['python'] +125103,multithreaded code makes rhino mocks cause a deadlock were currently facing some issues during unit testing our class is multithreading some function calls on mocked objects using rhino mocks heres a example reduced to the minimumpublic class bar private readonly listifoo foolist public barlistifoo foolist foolist foolist public void start var alltasks new listtask foreach var foo in foolist alltasksaddtaskfactorystartnew foodosomething taskwaitallalltaskstoarray the interface ifoo is defined aspublic interface ifoo void dosomething event eventhandler myeventto reproduce the deadlock our unittest does the following1 create some ifoo mocks2 raise myevent when dosomething gets calledtestmethod public void foo raisebar var foolist generatefoolist50 var target new barfoolist targetstart private listifoo generatefoolistint max var mocks new mockrepository var foolist new listifoo for int i 0 i max i foolistaddgeneratefoomocks mocksreplayall return foolist private ifoo generatefoomockrepository mocks var foo mocksstrictmockifoo foomyevent null var eventraiser lastcallonfooignoreargumentsgeteventraiser foodosomething lastcallonfoowhencalledi eventraiserraisefoo eventargsempty return foo the more foos are generated the more often the deadlock occurs if the test would not block run it several times and it willstopping the debugging testrun shows that all tasks are still in taskstatusrunning and the current worker thread is breaking at in a sleep wait or join rhinomocksdllrhinomocksimplrhinointerceptorinterceptcastlecoreinterceptoriinvocation invocation 0x3d bytesthe weird thing which confuses us most is the fact that the signature of the intercept method is defined as synchronized but several threads are located here i have read several postings about rhino mocks and multithreaded but havnt found warnings expected setting up the records or limitations methodimplmethodimploptionssynchronized public void interceptiinvocation invocationare we doing something completely wrong on setting up our mockobjects or using them in a multithreaded environment any help or hint is welcome,['c#'] +125133,css borders thistance from object edge quick question i was writing out some code and was curious if there is a way to add a border on a div that is 5px within the object as in not on the actual edge of the div i checked out wc3 and did not see any specs but i may have missed itin my case i would be using a dashed border 5px inside the div to create an effect like the div had been sewn to the rest of the site i can do it fairly easily with backgroundimage but why add kb when a line or two of css could do iti would assume it would be something like borderposition or borderthistancethanks in advance,['css'] +125137,bizzarre issue trying to make rpy2 219 work with r 2121 using python 26 under windows xp rpy cannot find the rdll i have been having a real issue trying to make rpy2 play nice with my r install i first tried installing the rpy2 msi package and this did not appear to work when i ran the recommended tests it was giving me an error saying that it could not find the rdll because the new r installs post 211 install the dlls into an i386 folder where rpy2 cannot find them because its looking in the bin folder instead of the bini386 folderthen i tried to build the install from scratch myself using the command line tools thistutils included with python this did not work because setuppy claimed to be unable to find the r home location but i did work out that editing an environment variable path might show the rpy2 setup where to find the r installation i then made a couple of edits to the environment adding the r home variable pointing to the bini386 directory and made a new entry under the path variable pointing to the same spotunfortunately when it found the r path i got this issue insteadrunning buildrunning build pyrunning build exttraceback most recent call last file setuppy line 372 in module ospathjoindoc source rpy2 logopng file cpython26libthistutilscorepy line 152 in setup thistrun commands file cpython26libthistutilsthistpy line 975 in run commands selfrun commandcmd file cpython26libthistutilsthistpy line 995 in run command cmd objrun file cpython26libthistutilscommandbuildpy line 134 in run selfrun commandcmd name file cpython26libthistutilscmdpy line 3 in run command selfthistributionrun commandcommand file cpython26libthistutilsthistpy line 994 in run command cmd objensure finalized file cpython26libthistutilscmdpy line 117 in ensure finalized selffinalize options file setuppy line 1 in finalize options config get rconfigr home about file setuppy line 264 in get rconfig rc rconfigfrom stringrconfig file setuppy line 252 in from string nin stringn stringvalueerror invalid substring in stringso i went back to trying to use the premade install thinking that maybe the new edits to the environment might work but got this issue here traceback most recent call last file string line 245 in run nodebug file cdocuments and settingsuserdesktoprpy2219rpytestspy line 3 in module import rpy2robjectstests file cpython26libsitepackagesrpy2robjects init py line 12 in module import rpy2rinterface as rinterface file cpython26libsitepackagesrpy2rinterface init py line 56 in module raise runtimeerrorunable to locate rdll within s r home runtimeerror unable to locate rdll within cprogram filesrr2121bini386this is really weird because as anyone can check on their own install r installs rdll into cprogram filesrr2121bini386 and i have checked and verified that its in there and i have pointed rpy2 to this directory in the windows default path i know for a fact that rpy2 is looking in the right place but cannot understand why its not seeing rdllso why cannot rpy2 find it and does anyone know a way to get rpy2 working with r 212 perhaps i should try the newer rpy2 220 version its still in development though and 19 is supposed to be able to handle r 212 according to this website so i do not know what to dothanks to anyone who can help outedit i have also tried these instructions over here but they return the same cannot find dll error unless you change the environment variable r home to point straight at the cprogram filesrr 212 directory instead of into the i386 subdirectory if it points at the right place you get these errors back this looks a bit more promising but its still pretty badfail testnewwithoutinit rpy2rinterfaceteststest sexpvectorsexpvectortestcasetraceback most recent call last file cpython26libsitepackagesrpy2rinterfaceteststest sexpvectorpy line 43 in testnewwithoutinit selfasserttruefalse worked when tested but calling endembeddedr causes troubleassertionerrorfail testcallerrorwhenendedr rpy2rinterfaceteststest embeddedrembeddedrtestcasetraceback most recent call last file cpython26libsitepackagesrpy2rinterfaceteststest embeddedrpy line 122 in testcallerrorwhenendedr selfasserttruefalse worked when tested but calling endembeddedr causes troubleassertionerrorfail testreadconsolewitherror rpy2rinterfaceteststest embeddedrembeddedrtestcasetraceback most recent call last file cpython26libsitepackagesrpy2rinterfaceteststest embeddedrpy line 117 in testreadconsolewitherror selfasserttrueerrorstringstartswithtracebackassertionerrorfail testsetreadconsole rpy2rinterfaceteststest embeddedrembeddedrtestcasetraceback most recent call last file cpython26libsitepackagesrpy2rinterfaceteststest embeddedrpy line 97 in testsetreadconsole selfassertequalsyesstrip res0assertionerror yes fail testsetwriteconsole rpy2rinterfaceteststest embeddedrembeddedrtestcasetraceback most recent call last file cpython26libsitepackagesrpy2rinterfaceteststest embeddedrpy line 36 in testsetwriteconsole selfassertequals1 3n strjoin bufassertionerror 1 3n fail testwriteconsolewitherror rpy2rinterfaceteststest embeddedrembeddedrtestcasetraceback most recent call last file cpython26libsitepackagesrpy2rinterfaceteststest embeddedrpy line 55 in testwriteconsolewitherror selfasserttrueerrorstringstartswithtracebackassertionerrorfail testvectorunicodecharacter rpy2robjectsteststestnumpyconversionsnumpyconversionstestcasetraceback most recent call last file cpython26libsitepackagesrpy2robjectsteststestnumpyconversionspy line 54 in testvectorunicodecharacter selfasserttruefalse arrays of unicode characters causing segfaultassertionerrorran 172 tests in 0407sfailed failures7exit code true,['python'] +125146,remove hover css behavior from element i have css that changes formatting when you hover over an element htmldiv classtest blah divcsstesthover border 1px solid red in some cases i do not want to apply css on hover one way would be to just remove css class from the div using jquery but that would break other things since i also using that class to format its child elements so that led me to question is there a way to remove hover css styling from an element,"['html', 'css']" +125164,net why is there no fixed point numeric data type in c it seems like there would be a ton of uses for a fixed point data type why is there not one in netnote i understand we can create our own classesstructs to suit our fixed point purposes and needs that is not my question i want to know why ms decided not to include a fixed point numeric data type,"['c#', '.net']" +125176,execute a main class from a jar i have a jar which contain two main class class a and class b in the manifest i have mentioned class a now i have to execute classb from the same jar what should be the command i dont prefer to make two separate jarsthanks,['java'] +125198,populating a listview using an arraylist my android app needs to populate the listview using the data from an arraylist i have trouble doing this can someone please help me with the code,"['java', 'android']" +125202,using bindingsource to bind to nested properties or making entities bindable binding to a nested property is easy enoughcheckbox1databindingsaddnew bindingchecked bindingsource myproperty normal bindingcheckbox2databindingsaddnew bindingchecked bindingsource mypropertyinnerproperty nested propertyhowever when mypropertyinnerproperty is changed no events are raised the bindingsource is never notified of the changei have read that the solution is to make sure that when the innerproperty object raises the propertychanged event the myproperty class that contains innerproperty captures the event and also raises a propertychanged event of its ownhowever entity framework does not do this for me and i would rather not go through every instance of every class and wireup a custom method to every navigation property just to make the my classes bindable is there a decent workaround to make entities bindable,"['c#', '.net']" +125203,java convert integer to string given a numberint number 1234which would be the best way to convert this to a stringstring stringnumber 1234i have tried searching googling for an answer but no many seemed trustworthy,['java'] +125214,uitableview animate row reordering upon sort i have a table that users can sort in two different ways when users change between these two sorting modes i want the resort to be animated and while uitableviews methods provide animation help for inserting deleting and reloading rows i do not see anything that lets me animate row movementam i missing somethingassuming i am not does anyone have any sample code on how to do thisthanks,['ios'] +125258,c marshalling double from c dll i have a c dll with an exported functionextern c declspecdllexport double fftdouble datareal double dataimag the function calculates the fft of the two double arrays real and imaginary an returns a single double array with the real an imaginary components interleaved re im re im i am not sure how to call this function in cwhat i am doing isdllimportfftdllstatic extern double fftdouble datareal double dataimagand when i test it like thisdouble foo fftnew double 1 2 3 4 new double 0 0 0 0 i get a marshaldirectiveexception exceptioncannot marshal return value invalid managedunmanaged type combinationi am assuming this is because c double is not quite the same as c double but i am not sure how to fix it any ideasediti have changed the signatures so that i now pass some extra informationextern c declspecdllexport void fftdouble datareal double dataimag int length double outputwe always know the length of output will be 2x lengthanddllimportfftdllstatic extern void fftdouble datareal double dataimag int length out double outputtested like thisdouble foo new double8fftnew double 1 2 3 4 new double 0 0 0 0 4 out foonow i am getting an accessviolationexception rather than a marshaldirectiveexception,"['c#', 'c++']" +125262,missing animation when calling seteditinganimated to delete cells from table view when deleting cells it calls my seteditinganimated method which i have overridden because i need to adjust the height of my cells when editing but because of this when i press the edit button the slide in animation of the red circles with the minus signs do not occur instead they just appear into the cell how can i fix thisthis is my seteditinganimated code at the moment voidseteditingboolediting animatedboolanimatedselftableview seteditingediting animatedyesselftableview reloaddatasuper seteditingediting animatedanimatedany help will be appreciated thanks,['iphone'] +125265,ruby and money in a rails app how to store money values in the db i want to make sure i do not have rounding issues when it comes to storing prices for products in a rails appwhat mysql datatype should i use and what does it map to in railsi want decimal with 10 places for precision,"['ruby-on-rails', 'ruby']" +125271,what is subclassing i am new to java and i am trying to create an xml document and clone a specific node minus the textnodeof this document over and over again someone answered me and said i should subclass the node and override the cloning so my question is what is subclassing,['java'] +125283,activerecord count to count rows returned by group by in rails i looked around and could not find any answers to this all answers involved counts that did not use a group bybackgroundi have a paginator that will take options for an activerecordfind it adds a limit and offset option and performs the query what i also need to do is count the total number of records less the limit but sometimes the query contains a group option and activerecordcount tries to return all rows returned by the group by along with each of their counts i am doing this in rails 235what i want is for activerecordcount to return the number of rows returned by the group byhere is some sample code that demonstrates one instance of this used for finding all tags and ordering them by the number of posts with that tagoptions select tags count as post count joins inner join posts tags join table for posts and tags group tagsid order post count desc count tagcountoptionsoptions optionsmerge offset page 1 per page limit per page items tagfindoptionswith the select option the tagcount generates the following sqlselect counttags count as post count as count tags all count all as post count tagsid as tags id from tags inner join posts tags group by tagsid order by count descas you can see it merely wrapped a count around the tags count and mysql complains about the count within a countwithout the select option it generates this sqlselect count as count all tagsid as tags id from tags inner join posts tags group by tagsid order by countwhich returns the whole group by result set and not the number of rowsis there a way around this or will i have to hack up the paginator to account for queries with group bys and how would i go about doing that,['ruby-on-rails'] +125290,accessing arrays by indexarray in c and c so there is this little trick question that some interviewers like to ask for whatever reasonint arr 1 2 32arr 5 does this line compileassertarr2 5 does this assertion failfrom what i can understand ab gets converted to a b and since addition is commutative it does not really matter their order so 2a is really 2 a and that works fineis this guaranteed to work by c andor cs specs,"['c++', 'c']" +125316,is there a way to embed c code into a lua script i have a program which forces lua as a choice for programming plugins i would like to take some existing c code and use it in this program is this possiblei should add that i know one can easily embed lua code into c but i have not found the reverse anywhere thanks guys,['c#'] +125326,chrome safari errornot allowed to load local resource filedcstylecss when i access my aspx page in chrome or safari it shows this error in consolenot allowed to load local resource filedcstylecsseverything works fine in ie and ffi use an external css which is linked in aspx page vialink relstylesheet mediaall hreffiledcstylecss typetextcss i have tried all the combination of slasheswhether i am giving file path in wrong manner or its any security exception in these browsersi am logged in as administratorwhat am i doing wrong,['css'] +125336,using c foreach tuple how can i work with tuples in a foreach loopthe following code does not workforeach tuplexy in sqllineparamslinessqllineparamslines is array of tuples int string,['c#'] +125352,use of void in function parameter possible duplicatec void arguments just started with c and i cannot find answer to thisis there any difference betweenint foo int foovoid which should i prefer and whynote that this question also goes for int main should it be int main or int mainvoid when i do not want any command line arguments,['c'] +125354,installing pil to use with django on mac os x i am really annoyed by installation of pil python imaging library on mac os x 106 does anyone have it installed and could post the recipe here i have tried a lot of them posted here on this site and a lot from google but always anding with missing some part and cannot work normally with pilthanks in advanceignas,['python'] +125380,how to know device is power off i want to do something when the mobile device is closing but i do not know what is the method could you tell me how to detect if mobile device is shutting down i know the method about mobile restart androidintentactionboot completed but i cannot find similar power off,['android'] +125389,what is float in java i wrote this code float b 36and i get thiserrorunresolved compilation problem type mismatch cannot convert from double to floatwhy whats the definition of float,['java'] +125391,whats the fastest way to concatenate two strings in java whats the fastest way to concatenate two strings in javaie string ccypair ccy1 ccy2i am using cypair as a key in a hashmap and it is called in a very tight loop to retrieve valueswhen i profile then this is the bottleneckjavalangstringbuilderappendstringbuilderjava119 javalangstringbuilderstringbuilderjava93,['java'] +125409,html5 video black screen on ipad i am building a website that has videos embedded within them this website needs to cater for ipad users as well but i am having trouble with the ol video tag at the moment i have a video that plays fine in browsers but not on an ipad unfortunatelyi am just getting a black screen with the ipad and no error message to speak ofhere is my code for the videovideo idmovie width790 height250 controls source srcanimintroipadmp4 typevideomp4 codecsavc142e01e mp4a402 source srcanimintrowebm typevideowebm codecsvp8 vorbis source srcanimintrotheoraogv typevideoogg codecstheora vorbisvideoscript var v documentgetelementbyidmovie vonclick function if vpaused vplay else vpause scriptthe videos were all created following tutorials about html5 video they were all encoded using preferred ipad settings on miro video converterjust incase this matters i am not sure it will i am testing the video on an ipad simulatorno matter what i do i just cannot get the video to play,['javascript'] +125416,thisplay an image in span without converting it to a block level element i am a little confused over here i have a txtbox and to the right of the txtbox i want to insert a help icon i have inserted that into a span the problem is that i dont want to make this span a block because it goes down then is there any other way to thisplay this image without turning this into a block level elementthe code goes hereinput namefirm typetext idfirm size20 span idhelpicospanthe csshelpico backgroundurlimagesquestionpng left top width16px height16px,"['css', 'html']" +125432,determine if python script is being executed locally or as cgi let us say i have a basic python script testpyusrbinpythonprint contenttype texthtmlnnprint htmlhello worldhtmlhow would one determine if the script is being executed locally eg python testpyor being called via a web browser eg visitingthis does not seem to be addressed in the documentation for the cgi module i thought there might be a difference in the result of cgifieldstorage but there does not seem to be onethe only way i can think to do it is as followsusrbinpythonimport osprint contenttype texthtmlnnprint htmlhello worldhtmlif request method in osenviron print this is a webpageelse print this is not a webpageis this the best andor most ideal method whywhy not,['python'] +125457,nlog cpu performance issue i have problem with this method in nlog library nlogtargetswrappersasynctargetwrapperprocesspendingeventsobject stateit consume too much cpu time i have long running windows service using nlog and after two days my service consume over 80 cpu time one core is almost on 80 second 30 it is not 100 cpu time but it is changing and after cca 2 hours its back to normal so i have run profiler and this metod maybe cause it nlogtargetswrappersasynctargetwrapperprocesspendingeventsobject statei have 10 file targets all are setted as async it is a fact that i have lot of logging in my app but only on level trace if i switched to info level it not helpedcan you help me should i decrease logging in my app,"['c#', '.net']" +125462,twisted startingstopping factoryprotocol less noisy log messages is there a way to tell to twistd to not log all factory and protocol start and stopi use many type of protocols and performs a lot of connections and my log file grows a lotso i am looking for a simple way to thisable those messagesregards,['python'] +125472,how to correctly marshal vbscript arrays to and from a com component written in c i am building a com object in c net 40 to be used in an classic asp site now i would like to know whats the proper way to marshal vbscript arrays single and multidimensional back and forth between the component and the asp site a code sample would be highly appreciated,['.net'] +125482,ios uitextview nsundomanager i am trying to integrate the undoredo features in a uitextview i am building a latex editor with no luck and to be honest i am really confused about this argument i do not understand the steps involved in those two operations i mean i need two methods one to remove the last inserted textone to restore the text removed one doubt is where i get the last inserted text in other words where i have to register for the undo in textviewdidchange i can get the whole textin textviewshouldchangetextinrange i can get the last char insertedi know that what i wrote was not the best explanation ever but i hope someone here has faced the same problem in the past and can give me an hint basically to resume i have to add the undoredo features to a textview possibly having two buttons linked with those actionsthanks in advance,['ios'] +125499,how to change the view angle and label value of a chart net c short descriptioni am using charts for a specific application where i need to change the view angle of the rendered 3d pie chart and value of automatic labels from pie label names to corresponding pie valuesthis how the chart looksinitializationthis is how i initialize it dictionarystring decimal secondpersonswithvalues historymodelgetsecondpersonwithvalues decimal yvalues new decimalsecondpersonswithvaluesvaluescount values string xvalues new stringsecondpersonswithvalueskeyscount labels secondpersonswithvalueskeyscopytoxvalues 0 secondpersonswithvaluesvaluescopytoyvalues 0 incomeexpensechartseriesdefaultcharttype systemwindowsformsdatavisualizationchartingseriescharttypepie incomeexpensechartseriesdefaultpointsdatabindxyxvalues yvalues incomeexpensechartchartareasdefaultarea3dstyleenable3d true incomeexpensechartseriesdefaultcustomproperties pielabelstyleoutside incomeexpensechartlegendsdefaultenabled true incomeexpensechartchartareasdefaultarea3dstylelightstyle systemwindowsformsdatavisualizationchartinglightstylerealistic incomeexpensechartseriesdefaultpiedrawingstyle softedgebasically i am querying data from database using the historymodelgetsecondpersonwithvalues to get pairs as dictionarystring decimal where key is the person and value is ammountproblem 1what i need is to be able to change the marked labels from person names to the ammounts or add another label of ammounts with the same colors see imageproblem 2another problem is that i need to change the view angle of 3d pie chart maybe it is very simple and i just do not know the needed property or maybe i need to override some paint event either ways any kind of ways would be appriciatedthanks in advance george,['c#'] +125501,mybatis columns mapping i am using mybatis 303 and have problem some columns in database have names with underscores and these columns should be mapped to the entity properties that are of course in camelcaseclass user private string first name public interface userdao selectselect from users listuser findallusersunfortunately i cannot see any way to solve that declaretively like it is done in jpa columnname first namei could make aliases in selectclause for such columns sush as first name as firstname and etc but that also looks lameany ideas thanks,['java'] +125502,how do i know when a catiledlayer has rendered all visible tiles i am working on an application where i render pdf content in a catiledlayer i want to trigger one method after the rendering of the tiled layer is complete is there any delegate method that will be called immediately after the rendering of all visible tiles is completed is there any other way of knowing when this is finished,['iphone'] +125509,using different references in visual studio 2010 for different build platforms how do i set up a vs2010 project so that it uses different references based on the chosen platformin practice i would like to link a 32bit library when i choose x86 as platform but the 64bit version of it when i choose x64any idea on how to get this swap done for a c vs2010 project,['c#'] +125511,how to combine two jar files is it possible to combine two jar files such that in an applet tag i can simply do something likearchivejarjarjarjar1jar archivejarjarjarjar2jar instead ofarchivejar1jar archivejar2jari need to only have one jar file so putting two jar files in a folder will not help me,['java'] +125518,test to see if entity framework is connected to something when you create a new entitycollection object the connection does not attempt to open the database until you try and do something with that collection i need to determine whether or not an entity collection has a valid connection or not and i cannot find an efficient method of doing itcurrently i have got this in my codevar db new myentitycollectiontry var checkworking from c in dbcustomers select ccatch connecttobackupwhich is not only horrible code but very slow since it waits an age to determine whether or not the connection is active before throwing an exceptioni know i can control how long it waits before giving up by using connectiontimeout but that is just another ugly hack that makes a bad situation worsesurely there is a better way of doing this,['.net'] +125521,cancelling file download with httpclient and asynctask in my app i need to download files from url locations i want to thisplay progress of the download in a dialogbox or optionally in the notification area i have come across several good resources on this subject something like unfortunately all the examples do not provide a clear indication on how to properly cancel a download per the users request so my question is actually quite simplegiven an asynctask which downloads the file in the background with httpclient and thisplays a dialogbox with download progress and a cancel button how do i can cancel the download and stop the background task when the button is pressedi know killing threads is generally not a good idea so i will probably need to work with a cancelvariable in my background thread how do i communicate a stop signal from the button to the asynctaskregardsivo,['android'] +125557,how to gray out a html element i would like to gray out a html table to make it appear that it does not apply instead of hidding it any ideas on how this can be done hopefully with css,"['html', 'css']" +125558,how to create a stock quote fetching app in python i am quite new to programming in python i want to make an application which will fetch stock prices from google finance one example is csco cisco sytems i would then use that data to warn the user when the stock reaches a certain value it also needs to refresh every 30 secondsthe problem is i dont have a clue how to fetch the dataanyone have any ideas,['python'] +125584,help with add i am trying to understand how add worksclass mynum def init selfnum selfnumnum def add selfother return mynumselfnumothernum def str self return strselfnumif i put them in a listdmynumi for i in range10this workstmynum0for and in d ttnprint tbut this does notprint sumdtypeerror unsupported operand types for int and instancewhat am i doing wrong how can i get the sum to workupdatemy problem is how to use the sum on a list of objects that support the add need to keep it as generic as possible,['python'] +125592,get and set screen resolution how can i collect and change screen resolution using visual c,['c#'] +125620,removing region i had to take over a c project the guy who developed the software in the first place was deeply in love with region because he wrapped everything with regions it makes me almost crazy and i was looking for a tool or addon to remove all region from the project is there something around,"['c#', '.net']" +125623,what is the dojo equivalent to jquery live what is the dojo equivalent to jquery live the only solution i found was to dojothisconnect the event handlers and reconnect them once a dynamic piece of markup was added to the page,"['javascript', 'jquery']" +125659,how can i reserve an iphone app name in apples developer portal i want to reserve an app name that i intend to build out over the next 90 days how do i do this in apples web developer portal,['iphone'] +125668,android startservice synchronous i cannot find this anywhere in the documentationis a call to contextstartservice synchronous or asynchronous,['android'] +125673,how to create an inmemory database with sql ce 40 questionhow do i create an inmemory database with sql ce 40contexti would like to do some unit testing or automated integration testing with a real database however one that is inmemory thatll make the tests run fast plus the database will vanish in thin air once the test are finished runningaccording to scott guthries blog post vs 2010 sp1 and sql ce the new sql ce 40 is capable of doing just that providing an inmemory databasehowever i could not find any tutorials or code examples on the web showing how it is done i only found this connection string example in this blog post but that also hits the harddrive,['c#'] +125697,jquery titlecase is there a built in way with jquery to title case a string so given something like bob smith it turns into bob smith,"['javascript', 'jquery']" +125698,how to pass parameters of a function when using timeittimer this is the outline of a simple program some predefined constantsa 1b 2 function that does something criticaldef foonum1 num2 do something main program do something to a and bfor i in range20 do something to a and b and update a and b during each iterationimport timeitt timeittimerstmtfoonum1num2 print ttimeit5i just keep getting global name foo is not definedcan anyone help me on this thanks,['python'] +125713,java garbage collection java automatically calls garbage collector then why we need manual calls for garbage collection when should use systemgc,['java'] +125721,how to rotate the background image in the container i want to rotate the image which is placed in the button of scrollbar in chrome now i have a css with this contentwebkitscrollbarbuttonverticaldecrement backgroundimageurlimagesarrowuppng webkittransformrotate120deg moztransformrotate120deg backgroundrepeatnorepeat backgroundpositioncenter backgroundcolorecef bordercolor9i wish to rotate the image without rotating its content,['css'] +125749,working with multiple versions of visual studio i am trying to find a way of being able to use multiple versions of visual studio on the same set of projects the majority of our team uses 2008 but i am trying out 2010 all projects are cas i understand it visual studio 2010 insists on upgrading all projects so it is not possible to leave all the solutionproject files as 2008 versions i really do not want to branch the entire source tree so i would like to find a way for multiple versions of the project files coexisting currently i have duplicated all sln and csproj files so i have 2008 versionssolutionnameslnprojectacsprojprojectbcsproj 2010 versionssolutionnamevs2010slnprojectavs2010csprojprojectbvs2010csprojthe trouble is despite the 2010 versioned files all having the same assembly names as their 2008 counterparts visual studio 2010 believes the projects are all projectnamevs2010 renaming the project in vs fails with a message saying a file of the same name already existsi do not think putting the 2010 version in a subfolder would be a solution as it would screw up any relative paths in the filessois there any way to convince vs that the project name should not be suffixed with vs2010 ie not the same name as the file oram i approaching this the wrong way is there a better way of working with multiple versions of vs on the same projectsupdatemy initial claim was wrong that visual studio was failing to find the project references because it was using the file name the specific problem i was having was that in my build files the project references were of the formprojectreference includepathtoprojectnamevs2010csproj project483544502462449d8b32efeca39f6cd7project nameprojectnamenameprojectreferencethe project files that i copied apparently have a different id or whatever it is in the project element simply removing the element from the build file has solved that particular issueprojectreference includepathtoprojectnamevs2010csproj nameprojectnamenameprojectreferencehaving said that the whole process of duplicating the project and solution files has actually been more effort than it is worth so i am not recommending this approach,['c#'] +125751,how to retreive form values from httppost dictionary or i have an mvc controller that has this action methodhttppostpublic actionresult submitaction get post params here return something the form is a nontrivial form with a simple textboxquestion how i access the parameter values i am not posting from a view the post is coming externally i am assuming there is a collection of keyvalue pairs i have access to i tried requestparamsgetsimpletextbox but it returns error sorry an error occurred while processing your request,['asp.net'] +125752,flags to enable thorough and verbose g warnings often in c under gcc i will start with the following set of warning flags painfully assembled from multiple sourceswall wextra wformatnonliteral wcastalign wpointerarith wbadfunctioncast wmissingprototypes wstrictprototypes wmissingdeclarations winline wundef wnestedexterns wcastqual wshadow wwritestrings wnounusedparameter wfloatequal pedantic ansii will build at least my debug versions with this set of warnings and fix everything i possibly can usually everything and then only remove flags if they are either not relevant or not fixable almost never the case sometimes i will also add werror if i have to step away while compilingi am just picking up c yes i am 15 years behind the times and i would like to start off on the right footmy question is does someone have a precompiled similar set of complete warning flags for c under g i know many of them will be the same,['c++'] +125755,how to combine delegates in c i want to implement a method which takes two action a1 and action a2 delegates and returns new delegate which combines them the signature of he method is the followingpublic static actiontuplet1t2 combinewitht1t2this actiont1 a1 actiont2 a2so instead of saying a1t1 a2t2i want to be able to writea1combinewitha2tuplecreatet1t2what is the possible implementation of this method can be,"['c#', '.net']" +125761,python m unittest thiscover does not thiscover tests pythons unittest thiscover does not find my testsi have been using nose to thiscover my unit tests and it is working fine from the top level of my project if i run nosetests i getran 31 tests in 0390snow that python 27 unittest has thiscovery i have tried usingpython m unittest thiscoverbut i getran 0 tests in 0smy directory structure ismyproj reporter init py reportpy other app modules tests init py testreportpy other test modulesdo you have any ideas why unittests thiscovery algorithm cannot find the testsi am using python 271 and nose 100 on windows 7,['python'] +125763,how do i create a radial cluster like the following codeexample in python i have found several examples on how to create these exact hierarchies at least i believe they are like the following here stackoverflowcomquestions2982929 which work great and almost perform what i am looking for editheres a simplified version of pauls code which now should be easier for someone to help get this into a radial cluster instead of this current cluster shapeimport scipyimport pylabimport scipyclusterhierarchy as schdef fix vertsax orient1 for coll in axcollections for pth in collget paths vert pthvertices vert13orient scipyaveragevert13orient generate random features and thistance matrixx scipyrand40d scipyzeros4040for i in range40 for j in range40 dij absxi xjfig pylabfigurefigsize88 compute and plot the dendrogramax2 figadd axes030710602y schlinkaged methodsinglez2 schdendrogramyax2set xticksax2set yticksfix vertsax20figsavefigtestpngbut instead of a treelike structure i need a radial cluster like the following diagrams,['python'] +125773,how can i change the image of an imageview i have just started learning android and i do not know how can i change the image of an imageview ie it has some image which was set in the layout but i want to change that image through coding how should i do it here is the xml filelinearlayout xmlnsandroid androidlayout widthfill parent androidlayout heightfill parent androidbackgroundcc8181 imageview androidididimage androidlayout width50dip androidlayout heightfill parent androidsrcdrawableicon androidlayout marginleft3dip androidscaletypecenterthanks for replying,['android'] +125784,paging uiscrollview with different page widths i would like to have a horizontal scrolling uiscrollview with paging enabled the pages in this scrollview have different widths so the scrolling thistance differs from page to pagethe goal is to make a picker for different points in time eg now yesterday evening last week last month stopps herehere now has a smaller width than yesterday evening when paging through this values the scrollview should stop at the center of the according valueis that possible,['iphone'] +125799,setting loses caret position on element on pressing tab key i have pre with contenteditabletrue on my webpage and i am trying to make it append t when i press tab i found some other plugins for that but they were working only on textareaso the problem is that when i append text to the pre through jquery it loses the caret position i was sure it was losing focus but it is not so prefocus will do nothing i tried to blur it first but this is not practical cause the caret will return on different position depending on the browser some help please pmy code is here,['jquery'] +125809,android bitmapdrawabledrawcanvas does not seem to work i am trying to tile a 20x20 background onto my custom view but for some reason i am unable too bitmapdrawable background background new bitmapdrawablebitmapfactorydecoderesourcegetresources rdrawableback backgroundsettilemodexyshadertilemoderepeat shadertilemoderepeat backgrounddrawcanvasdoes anyone have an idea why it is not working,['android'] +125826,getting error orgspringframeworkbeansfactorynosuchbeandefinitionexception no bean named springsecurityfilterchain is defined i am running ntlm using spring security i am getting the following errororgspringframeworkbeansfactorynosuchbeandefinitionexception no bean named springsecurityfilterchain is definedhow can i resolve this errori have the following defined in webxmlfilter filternamespringsecurityfilterchainfiltername filterclassorgspringframeworkwebfilterdelegatingfilterproxyfilterclassfilterfiltermapping filternamespringsecurityfilterchainfiltername urlpatternurlpatternfiltermappingupdate 1i resolved that error now i am gettingorgspringframeworkbeansfactorynosuchbeandefinitionexception no bean named filtersecurityinterceptor is definedand i have the following bean idspringsecurityfilterchain classorgacegisecurityutilfilterchainproxy property namefilterinvocationdefinitionsource value convert url to lowercase before comparison pattern type apache ant httpsessioncontextintegrationfilter exceptiontranslationfilter ntlmfilter filtersecurityinterceptor value property beani changed my applicationcontextxml as follows because like sean patrick floyd mentioned some elements were old and dead and buried however i have other errors now which needs to be fixed thanksxml version10 encodingutf8beans xmlns xmlnsxsi xmlnssecurity xsischemalocation authenticationmanager alias authenticationmanagerauthenticationmanager securityauthenticationprovider securityuserservice securityuser nametestuser passwordpassword authoritiesrole user role admin securityuser nameadministrator passwordpassword authoritiesrole userrole admin securityuserservice securityauthenticationprovider bean iduserdetailsauthenticationprovider classcomicesofticefacessecurityuserdetailsauthenticationprovider securitycustomauthenticationprovider bean bean idntlmentrypoint classorgspringframeworksecurityuintlmntlmprocessingfilterentrypoint property nameauthenticationfailureurl valueaccessdeniedjspx bean bean idntlmfilter classorgspringframeworksecurityuintlmntlmprocessingfilter securitycustomfilter positionntlm filter property namestripdomain valuetrue property namedefaultdomain valuedomain property namenetbioswins valuedomain property nameauthenticationmanager ref authenticationmanager bean bean idexceptiontranslationfilter classorgspringframeworksecurityuiexceptiontranslationfilter property nameauthenticationentrypoint refntlmentrypoint bean securityhttp accessdecisionmanagerrefaccessdecisionmanager entrypointrefntlmentrypoint securityintercepturl patternaccessdeniedjspx filtersnone securityintercepturl pattern accessrole user securityhttp bean idaccessdecisionmanager classorgspringframeworksecurityvoteunanimousbased property nameallowifallabstaindecisions valuefalse property namedecisionvoters list bean idrolevoter classorgspringframeworksecurityvoterolevoter list property beanbeans,['java'] +125840,itextsharp measure chunk width height i am trying to do some precise alignment with itextsharp but i keep falling short as i cannot figure out a way to get a width height value for a chunk or paragraph if i create a paragraph that is a certain font and size and text then its dimensions should be known righti know that the default leftrightcenter alignments will do the trick for me mostly but i have scenarios where knowing the dimensions will be most useful any ideas,['c#'] +125841,most basic working vbo example i want to know the simplest method for using vbos in opengl i have tried running a few examples that work but are clouded with all other information thats making it really confusing me at the moment this is what i havegluint vboid 0const int trisize m trissize23m tris is an index array for verts and normalsglfloat vertices new glfloattrisizeglfloat normals new glfloattrisizeint j0for int i0 im trissize i2 normalsj m normalsm trisi13 verticesj m verticesm trisi3 normalsj m normalsm trisi131 verticesj m verticesm trisi31 normalsj m normalsm trisi132 verticesj m verticesm trisi32 im pretty sure this loop is right as its what i used before to thisplay mesh correctly without vbos using glvertex3fglgenbuffersarb1 vboidglbindbufferarbgl array buffer arb vboidglbufferdataarbgl array buffer arb sizeofverticessizeofnormals 0 gl static draw arbglbuffersubdataarbgl array buffer arb 0 sizeofvertices verticesglbuffersubdataarbgl array buffer arb sizeofvertices sizeofnormals normalsglvertexpointersizeofvertices gl float 3 0glnormalpointergl float 3 voidsizeofverticesin a render method i havegldrawarraysgl triangles 0 thisgettrinum 0 is the vboidalso i have a method that runs onceglenableclientstategl vertex arrayglenableclientstategl normal arraywhen i try to run my code i get exc bad accessany advice on what im doing wrong or a very simple implementation of a vbo would be very helpful,['c++'] +125847,how to detect if mouse click is legit or automated how to know if a mouse click is simulated or not when mouse click send by a program or real mouse device i am programming a system detection for a game to avoid bots autoclicksetc that only accept legit mouse clicks,['c++'] +125863,phpbb3 autologin i have integrated a phpbb3 forum to my already existing websitei have been able to make my registration process add the user to the phpbb db as wellnow i am facing a problem where i am trying to get the user to autologin to the forum when he logs in to my websitehave anyone here done that i cannot find anything relevant on google as all posts seem to talk about phpbb external webpages and how you can use phpbb sessions on other webpages however what i am trying to do is to initiate a login only when the member logs in to my website and following the tutorials i found on google will let my users log in to my site when they log in to my forum which is the other way aroundthanks,['php'] +125889,array of function pointers without a typedef arrays of function pointers can be created like sotypedef voidfunctionpointerfunctionpointer functionpointers stuff here what is the syntax for creating a function pointer array without using the typedef,['c++'] +125895,mongoose web server helloworld program i came across an embedded web server named mongoose and and i read the wiki it was great and i searched for some sample hello world program but i could not find it i found some example but that was written in c for windows and can any one provide an example c program to run this webserver,['c++'] +125899,how to convert an enum type variable to a string how to make printf to show the values of variables which are of an enum type for instancetypedef enum linux apple windows os type os type myos linuxand what i need is smth like printenumos type my os is s myoswhich must show a string linux not an integeri suppose first i have to create a valueindexed array of strings but i do not know what is the most beautiful way to do it is it possible at all,"['c++', 'c']" +125900,mysql subquery with userdefined variables i am trying to accomplish a query that requires a calculated column using a subquery that passes the date reference via a variable i am not sure if i am not doing it right but essentially the query never finishes and spins for minutes on end this is my queryselect groupdatedate formatorder dateym countthistinct customer email as num cust select countthistinct cevcustomer email as num prev from pj cust email view cev inner join pj cust email view as prev purch on prev purchorder date groupdate and cevcustomer emailprev purchcustomer email where cevorder date groupdate as prev cust countfrom pj cust email viewgroup by groupdatesubquery has an inner join accomplishes the selfjoin that only gives me the count of people that have purchased prior to the date in groupdate the explain is below id select type table type possible keys key key len ref rows extra 1 primary pj cust email view all null null null null 140147 using temporary using filesort 2 uncacheable subquery cev all idx email null null null 140147 using where 2 uncacheable subquery prev purch ref idx email idx email 768 cart acevcustomer email 1 using where and the structure of the table pj cust email view is as such pj cust email view create table pj cust email view order date varchar10 character set utf8 default null customer email varchar255 character set utf8 default null key idx email customer email key idx orderdate order date engineinnodb default charsetlatin1again as i said earlier i am not really sure that this is the best way to accomplish this any criticism direction is appreciatedupdatei have made a little progress and i am now doing the above procedurally by iterating through all known months instead of months in the database and setting the vars ahead of time i do not like this still this is what i have got nowsets the user defined varsset startdate201008 enddate201009gets total thistinct emails in the given rangeselect countthistinct customer email as num custfrom pj cust email viewwhere order date between startdate and enddategets the total count of customers who had purchased prior to the given rangeselect countthistinct cevcustomer email as num prev from pj cust email view cev inner join pj cust email view as prev purch on prev purchorder date startdate and cevcustomer emailprev purchcustomer email where cevorder date between startdate and enddatewhere startdate is set to the start of the month and enddate signifies the end of that months rangei really feel like this still can be done in one full query,['mysql'] +125909,looking for a simple audio playback library for c i am working on a simple audio player which is going quite well using qt and everything but i am in need of a solid but simple audio library i do not need anything fancy such as 3d sound and what do i know what else these things got nowadays i am just looking for something simple and efficienta list of features i am looking foraudio playback from filesogg mp3 and flac should be supported at the very leastshould be able to pause playbacki am planning to use it in csee nothing huge or anything but at the same time i am having a hard time finding something suitable the platform i am targeting is windows 7anyone out there that knows something that i might be looking for,['c++'] +125910,chromeonly crossdomain scripting errs in facebook iframe app upon fblogin in google chrome i am on 9059798 my facebook iframe app using graph apijavascript sdk tends to always throw the following two javascript errors see below based on crossdomain scripting but only on one page of the app it goes into an endless retry loop on the second message after leaving it overnight it reported a half million retries by this morning the fb call being used is for loginfbloginfunctionresponse if responsesession user successfully logged in else user cancelled login in firefox and ie9 i do not get these errors it is specific to chrome maybe webkit whats odd is i have a second page in the app that uses fblogin and it works in chrome in addition to the other browsers i read somewhere that safari has more stringent requirements on cross domain scripting it and chrome share the same code base domains protocols and ports must match error message i believe is actually satisfied because i have another page that works with the fblogin call the only other difference i see between these two messages is the postmessage query argument has a different value for each bolded in the messages however there is only one iframe that constitutes a facebook app so i wonder why two different values might be used one after the other i do not mean to lead answers to focus on this item but i did want to point it out suggestions are welcome as to what i might try to resolve this errors chrome javascript console messagesmessage 1 unsafe javascript attempt to access frame with url key168297653202478app id168297653202478thisplaypopupfbconnect0localeen usmethodpermissionsrequestnexthttp3a2f2fstaticakfbcdnnet2fconnect2fxd proxyphp23cb3df3d15633dc26origin3dhttp253a252f252fsubdomainexamplecom252ff22a8befa26relation3dopener26transport3d postmessage 26frame3d f1baf6f4 26result3d2522xxresulttokenxx2522permspublish stream2coffline accessreturn session1sdkjoeysession version3 from frame with url request871mifgh o05ponx20387xhd2ylarklu6quv8vkxy4eyjhbgdvcml0ag0ioijitufdlvniqti1niisimlzc3vlzf9hdci6mti5odqymdewmswidxnlcii6eyjjb3vudhj5ijoiy2eilcjsb2nhbguioijlbl9vuyisimfnzsi6eyjtaw4iojixfx19 domains protocols and ports must matchmessage 2 unsafe javascript attempt to access frame with url key168297653202478app id168297653202478thisplaypopupfbconnect0localeen usmethodpermissionsrequestnexthttp3a2f2fstaticakfbcdnnet2fconnect2fxd proxyphp23cb3df304d46e0826origin3dhttp253a252f252fsubdomainexamplecom252ff23ce820326relation3dopener26transport3d postmessage 26frame3d fcd3637bc 26result3d2522xxresulttokenxx2522permspublish stream2coffline accessreturn session1sdkjoeysession version3 from frame with url request871mifgh o05ponx20387xhd2ylarklu6quv8vkxy4eyjhbgdvcml0ag0ioijitufdlvniqti1niisimlzc3vlzf9hdci6mti5odqymdewmswidxnlcii6eyjjb3vudhj5ijoiy2eilcjsb2nhbguioijlbl9vuyisimfnzsi6eyjtaw4iojixfx19 domains protocols and ports must match,['javascript'] +125914,immutable chrome sqlite return objects i am using a sqlite db as a storage system for a webapp i been using the objects that are returned from queries directly in application for examplefunction get book by ididsuccesscallbackerrorcallback function successcallbacktransaction results ifresultsrowslength0 successcallbacknull else bookresultsrowsitem0 successcallbackbook dbtransaction function transaction transactionexecutesqlselect idtitlecontentlast read from books where idid successcallback errorcallback this returns me an object with the given id all columns are provided as properties nice the problem i just figured out is that all the properties of the result set object are immutable so for example if i want to change the property title it takes no effect which in my opinion makes no sense exampleget book by id1handleerrorfunction handlebook this does not work booktitle is still what it was booktitlebooktitlemore texti of course can convert all my db objects into mutable objects but i rather would not do that is that an expected behavior can i request mutable objectsi am using google chrome 90 on mac os x,['javascript'] +125927,jackson objectmapper constructor throws nosuchmethod i am using jackson sample code to deserialize a pojoobjectmapper m new objectmapperthis line throws a nosuchmethoderrorexception in thread main javalangnosuchmethoderror orgcodehausjacksontypejavatypeinitljavalangclassv at orgcodehausjacksonmaptypetypebaseinittypebasejava15 at orgcodehausjacksonmaptypesimpletypeinitsimpletypejava45 at orgcodehausjacksonmaptypesimpletypeinitsimpletypejava40 at orgcodehausjacksonmaptypetypebindingsclinittypebindingsjava18 at orgcodehausjacksonmaptypetypefactory fromtypetypefactoryjava525 at orgcodehausjacksonmaptypetypefactorytypetypefactoryjava61 at orgcodehausjacksonmapobjectmapperclinitobjectmapperjava179 at commeutilctrlbillingjobstatusfromjsonbillingjobstatusjava37i do not get it,['java'] +125953,in c how do i keep certain method calls out of the codebase entirely i am trying to get rid of all datetimenow method calls and replace them with my own getnow method which may sometimes return a fixed date for testing purposes how can i enforce that no one adds a datetimenow call in the future can i use ndepend or stylecop to check this on my continuous integration server thanks,['c#'] +125956,typedef type checking how do i get g to make type checks on typedefs is it possible ietypedef int t1typedef int t2t1 x 5 ok with met2 y x any way to get an error or a warning herei cannot use c0x features i do not know whether they can do thisedit what i want is something like thistypedef int ballidtypedef int batidbatid x 10mapbatid bat mminsertmake pairx bigbat okballid y 15minsertmake pairy smallbat give me a warning at least plzis this too much to ask,['c++'] +125959,jquery remove string from string i am trying to remove a string from a string in jqueryhere is the stringusername1 username2 and username3 like this posti would like to remove username1 from this listi tried adding the list to an array using split but i got an error i am assuming the error is because not every word has a comma after iti always want to remove the fist item from the list username1 is just an example username the first item will always be the username of the currently logged in user if they have liked this posti have tried var like list jquerytrimjquerypost like listparts1html updated list jquerypost like listparts1htmlreplacedoddsey65 jquerypost like listparts1htmlupdated listbut that did not update the list it does however update the list when using text instead of html but i have links inside the list which i need to preserveany help is appreciated thanks,"['javascript', 'jquery']" +125960,c public when debugging private otherwise is there a nice way to make it so that functions are public when i am testing with nunit but private otherwisenot having to generate a lot of extraneous code would also be niceeditit seems the solutions fall under 3 typesdo not do what i am attempting to douse compiler directivestry a clever solution like usinginternalsvisibletomight there be a way to do this programmatically ie just create a new temporary app that makes all protectedprivateinternalfunctions public plug that into nunit run the tests there and then go back to using the private functions for the release version,['c#'] +125962,javascript get and set variables in windowlocationhash does anyone have a good solution for getting and setting variables in windowlocationhashtake a url that looks like thisdomaincomq1s2what i would like is an unstressful way javascript or jquery to check the values of q and s when the page loads and change them following events on the pagei have found some code for getting hash variables but nothing sensible for setting them am i missing something really obvious or do i need to roll my own solution and release itthanks,"['javascript', 'jquery']" +125986,core data any way to fetch multiple entities i am just getting started with core data and as a learning exercise i am building an app where i need to thisplay different types of objects in a single table viewas an example say i have an entity for cheese and an unrelated entity for pirate on the main screen of my app the user should be able to create either a cheese or a pirate instance to add to the table viewso using the core data editor i have created entities for cheese and pirate however an nsfetchrequest seems to only allow you to retrieve one type of entity at a time withnsfetchrequest fetchrequest nsfetchrequest alloc initnsentitydescription entity nsentitydescription entityfornamecheese inmanagedobjectcontext contextfetchrequest setentityentityis there any way to perform a fetch that retrieves all cheese and pirate objectsthanks,"['iphone', 'ios']" +125997,writing to 0xb80 yields output on screen without any print statements such as printf include stdiohinclude coniohvoid main char far v char far0xb80 clrscr v w v 2 v e getchoutput is wei do not get how the output is getting printed without any printf or other print statements,['c'] +125998,how to split string using delimiter char using tsql i have this long string in one of the columns of the table i want to get only specific informationmy table structurecol1 123col2 acol3 clent id 4356hyclient name b b bobclient phone 66742626client fax 60151info inf877 mac3055400800my select statement isselect col1 col2 col3 from table01but in col3 i just need client names value which is b b bob in col3 column delimiter is pipe char eg client id 4356hy key value delimiter is equal to sign with one white space leading and trailingplease help,['sql'] +126003,ip address validation i am refactoring my code and wanted to use the ipaddresstryparse method to validate if a string is a valid ipv4 address instead of using regular expressionspublic static bool isipv4string value ipaddress address if ipaddresstryparsevalue out address if addressaddressfamily addressfamilyinternetwork return true return falsemy unit test is now failing because these input values return true and get parsed to the following ipaddress objectsvalue 0 address 0value 255255255 address 2552550255value 65536 address 0100does this make sense i can see that 0 is technically a valid ipv4 address even if it makes no sense for the user to enter that what about the other two why are they converted in the way they are and should i treat them as valid even if it might not be transparent for the user who maybe just forgot to enter the periods 65536 instead of 65536any help is most appreciated,"['c#', '.net']" +126007,whats the best easyefficient solution for aspnet developers to develop a mobile version of their existing website i hope the question is selfdescribingi am currently developing an aspnet website which uses a ms sqlserver database in the data layerand i was thinking what are my options to get a mobile version most importantly supports blackberry and iphone and hopefully every mobile device and when used on blackberry i want to be able to let it run at the bbs backgroundi was thinking about aspnet mobile controls but the projects page seems like a deadnotupdated framework and not sure exactly if supports only windows mobiles or whateditthank you for your questions but they all covered my problem from only one respective i mean how this is going to let me use the blackberry appliction options like letting my website run at the device background or sending notifications to my users,['c#'] +126053,implementing argmax in python how should argmax be implemented in python it should be as efficient as possible so it should work with iterablesthree ways it could be implementedgiven an iterable of pairs return the key corresponding to the greatest valuegiven an iterable of values return the index of the greatest valuegiven an iterable of keys and a function f return the key with largest fkey,['python'] +126058,locate bluetooth inbox our app needs to grab certain files from the bluetooth inbox after they are pushed from an external hardware device is there a way to programmatically find the bluetooth folder location on the galaxy it is mntsdcardbluetooth and on the desire it seems to be mntsdcarddownloadsbluetooththanks,['android'] +126060,use pointer to struct or not when using typedef in c in order to define a new datatype in c for example a type for linked list one can use one of the following definitionsstruct list node int x struct list node next1typedef struct list node list12typedef struct list node list2from what i have seen the common practice is the first definitionthe question is if the second definition is also an acceptable practicein which cases if any should one prefer the second over the firstprovided that the variables that we use are pointers to struct list node is it possible to do the same operations with both typeswhat are the advantages of the first,['c'] +126070,jaxb xmlelementwrapper nested nodes i want to generate xml that look like this mainnode node1node1 node2node2 mainnode mainnode2mainnode2 and this is how i generate the mainnode1 mainnode2 and node1 in my code xmlelementwrappername mainnode xmlelementname node1 public liststring getvalue return value xmlelementname mainnode2 public string getvalue2 return value2 how i could add node2 to the mainnode1,['java'] +126077,sql join format nested inner joins i have the following sql statement in a legacy system i am refactoring it is an abbreviated view for the purposes of this question just returning count for the time beingselect countfrom table1 inner join table2 inner join table3 on table2key table3key and table2key2 table3key2 on table1differentkey table3differentkeyit is generating a very large number of records and killing the system but could someone please explain the syntax and can this be expressed in any other waytable1 contains 419 rowstable2 contains 3374 rowstable3 contains 28182 rowseditsuggested reformatselect countfrom table1 inner join table3 on table1differentkey table3differentkey inner join table2 on table2key table3key and table2key2 table3key2,['sql'] +126083,how to check an android device is hdpi screen or mdpi screen i want to check this to fetch different images by internet how to do that,['android'] +126090,read utf8 character in specify position from a nsstring nsstring str 1ao3a5 nslogcstr characteratindex0 nslogcstr characteratindex1 nsstring characteratindex works well on ascii chars but how could i get the utf8 character at the index of 2 updated it seems unichar16bits cannot represent all the utf8 encoding strings8bites to 32bites so are there any method to get the char from nsstring,"['iphone', 'objective-c']" +126106,programatically change layout height classcastexception i am trying to animate a webview to drop down and reveal its contents i have written a handler to increase the height by 1 each time however i am running into a classcastexception the code i am using iswebviewlayoutparams params new webviewlayoutparamswvgetlayoutparamsparamsheight heightwvsetlayoutparamsparamsheightthissleep20on the line wvsetlayoutparamsparams i get ajavalangclasscastexception androidwidgetabsolutelayoutlayoutparamshow do i fix this,['android'] +126114,multiple uibarbuttonitems in uinavigationbar how to create multiple bar button in navigation bar,"['iphone', 'objective-c']" +126119,in ruby on rails what does authenticate with http basic do restful authentication uses authenticate with http basic but a search on the net can find many pages with no description on the official it can also be found except again there is no description no comment no specwhat does it do it seems to be able to use a login name and password from an http request and then they can be compared to the login name and encrypted password in the users table but is that the case why are not there even a 1line description,['ruby-on-rails'] +126133,how to thisable alertviews button in iphone i have alert view having 2 buttons ok and cancel and a textfieldnow i want to thisable ok button until user enter some text in textfieldhow can i do thisthanks in advance,['iphone'] +126139,error 2035 mqrc not authorized while connecting to mq i am getting this error while connecting to ibm mq i know that this is because of privileges but is there any way just to check the connection with ibm mqplease suggest,['asp.net'] +126157,implementation of blockingqueue what are the differences between synchronousqueue and linkedblockingqueue i see these implementation of blockingqueue and cannot understand the differences between them my conclusion so fari would not ever need synchronousqueuelinkedblockingqueue ensures fifo blockingqueue must be created with parameter true to make it fifosynchronousqueue breaks most collections method contains size etcso when do i ever need synchronousqueue is the performance of this implementation better than linkedblockingqueueto make it more complicated why does executorsnewcachedthreadpool use synchronousqueue when the others executorsnewsinglethreadexecutor and executorsnewfixedthreadpool use linkedblockingqueueeditthe first question is solved but i still do not understand why does executorsnewcachedthreadpool use synchronousqueue when the others executorsnewsinglethreadexecutor and executorsnewfixedthreadpool use linkedblockingqueue what i get is with synchronousqueue the producer will be blocked if there is no free thread but since the number of threads is practically unlimited new threads will be created if needed this will never happen so why should it uses synchronousqueue,['java'] +126165,wpf button click in c code i have an array of button which is dynamically generated at run time i have the function for button click in my code but i cannot find a way to set the buttons click name in code so what is the code equivalent for xamlbutton xnamebtn1 clickbtn1 clickor what should i place for in the following codebutton btn new buttonbtnname btn1btn btn1 click,['c#'] +126166,doxygen seamless documentation for project with c and vhdl i am setting up a documentation about some sort of library which consists of a cc part and a vhdl part plus some instructive doxygenonly pages they have to be put into one selfcontained group everything works so far nice and fluffybut what if i want to optimize the output in the vhdlsubdirectory by using optimize output vhdl yes and optimize the output of the csubdirectory by using optimize output c yes at the same timeas far as i understand using doxygentags is not optimal in my case since it introduces new doxyfileconffiles in each subdirectory with independent runs of doxygen in each subdirectory so doing this i cannot put both parts cvhdl in different subgroups of the same group anymore and links between the two parts are not possible also the whole module should be selfcontained to be includable into bigger documentations without the special buildstructure involved in this solutionwhat would you do,['c++'] +126178,how to mark a property as non serializable for json as the title says i want to mark a property as non serializable by the javascriptserializer how can achive that thanks in advance,['c#'] +126180,jquery not working in ie9 rc i have just upgraded to ie9 rc which i must add isnt too bad an attempt by microsoft so far they still have time to mess it up please dont comment below on how wonderfulrubbish you think it is i dont want a browser war in order to test websites now i understand its only a release candidate and is still being developed but for some reason none of jquery on my site is not being rendered properly i say not rendering properly i really mean not working fullstop the only way to get it to work is to use ie9 browser mode and ie8 standardsusing ie9 broswer mode and ie9 standards stops the jquery workingi understand im probably going to have to wait until they either ugrade ie or the jquery api but does anyone know why this is or possibly have a fix cheers guysupdateok so then guys you can either go back to jquery v14 or use this release candidate of jquery v15,"['jquery', 'html']" +126181,c application keeps freezing on remote i am developing a c application net 35 win forms which is run on a server and is accessed by users using remote desktop the application keeps freezing on seemingly random occasions on the remote machine ie all gui components turn to white task manager reports the application to be not responding but not when run locally i am not entirely sure about that but failed to reproduce the freeze on my machine has anyone experienced such behavior in his apps that are accessed remotely what debugging strategy would you suggest do i need to consider something special when developing win forms applications that are accessed by remote desktopedit some notes about the application and the freeze the application does not recover from the freeze also the freeze does not happen or did not happen yet during user interaction but in between log ins to the remote machine the application monitors a cfd solver so it is doing things even when no one is using it updatewe did infact implement detailed logging writing every function call to a file with a timestamp unfortunately the results were not very conclusive ie the last function call logged always returned correctly also there were some background timers still running even though the application appeared frozne gui completely white etc after some trouble we managed to have a look at a crashdump in windbg on the system thread we found a call to onuserpreferencechanged and further up to invokewaitone we cannot say for sure yet but it seems to be the issue decribed in these articles as a quick fix i installed a dummy handler to the event mentioned i will report how this works outupdate 2as it turns out a log in to a remote machine fires several onuserpreferencechanged events so it was indeed the suspected issue the fix turned out to be not so easy though i would have expected that an illegalcrossreferenceexception is thrown everytime a background thread tries to modify a control that was created on the system thread this does not seem to be the case i named my system thread and before each access to a control i asserted that the current thread name is the system threads name in various places this assertion failed eg in a callback from a timer but no exception was thrown after using proper delegation at these places the freezes stopped the application runs nonstop for some weeks now and my users are happy again,['c#'] +126182,how ios handle url scheme duplication if 2 other app register same url scheme how ios handle this,['ios'] +126207,how to generate a program dependence graph pdg from bytecode in java i want to generate a program dependence graph pdg from java bytecode for further programmatic analysis since this is old the paper is from 87 and presumably wellknown technology i thought that appropriate tools would be readily availablehowever i was not able to find themin fact an extensive search turned up only a few resultsthe bandera project which was abandoned in 2006the indus project which seems not to have received any effort since 2007 except for it being made open source in 2009the moose jee project which seems to be pretty new as there is basically no documentation whatsoeverand the soot framework which provides some classes see javadoc but seems to lack an implementation for the generation in fact soot is the basis for bandera and indusso my question is the following is there any alive and maintained implementation out there does anybody have experience in either one of the aforementioned projects what would you recommendthank you already for your input it is highly appreciated,['java'] +126212,how to create a tree view with checkboxes in python i have been using tkinter and tix to write a small program i am at a point where i need a tree view with checkboxes checkbuttons so i can select items from the tree view is there an easy way to do this i have been looking at ttktreeview and it looks easy to get the tree view but is there a way to insert a checkbutton to the view a simple code snippet would be really appreciated i am not limited to ttk anything will do as long as i have an example or good docs i can make it work,['python'] +126221,what is void and to what variablesobjects it can point to specifically can it point to intfloat etcwhat about objects like nsstring and the likeany examples will be greatly appreciated,"['c++', 'c', 'ios']" +126245,delphi dll in c var array as parameter i need use a delphi dll in my c codei have some success when using other methods with common parameters but in this case the solution still hiddenthe dll documentation presents this declarationfunction get matrix var matrix array 1200 of char boolean stdcalli tried to usedllimportdlldllpublic static extern bool get matrixref char matrixnot successful some help,['c#'] +126247,programmatically changing webkittransformation values in animation rules i have this stylesheet webkitkeyframes run 0 webkittransform translate3d0px0px0px 100 webkittransform translate3d0px1620px0px not i would like to modify the value of 1620px depending on some parameters like this webkitkeyframes run 0 webkittransform translate3d0px0px0px 100 webkittransform translate3d0px heighti 0px i would prefer to be able to use javascript and jquery though a pure css solution would be okthis is for an iphone game that runs in it is mobilesafari browser,"['javascript', 'css']" +126250,jquery listen for events in an iframe i am making a very simple rich text editor using jquery i do not want to use a thirdparty onei need to listen for events within an iframe same domain etc starting with typing apparently i will need to use bind a lotthis is what i have got at the moment which works fine in ie8 amazingly enough but not chromescriptfunction textcontentsbindkeyup keydown keypress functione var code ekeycode ewhich alertcode return false scriptbody iframe idtext nametext srcedithtmliframebodyon the key press event above i will also want to get the current value of edithtml and update a textarea with that valueany help would be much appreciated many thanksedit to explain further edithtml is an editable file using documentbodycontenteditable trueedit 2edithtml script languagejavascript function initializeiframe documentbodycontenteditable true scripthtmlbody onloadinitializeiframebodyhtml,['jquery'] +126253,android set spinner start point this is probably a simple straight forward thing to do for somei have this codesqlitedatabase db dbsgetreadabledatabase string sql select from table final cursor cursor dbrawquerysql null array spinner10 select while cursormovetonext array spinner1i cursorgetstring1 cursorgetstring2 i final arrayadapterstring adapter new arrayadapterstringthis androidrlayoutsimple spinner item array spinner1 s1setadapteradapteri populate the array and everything runs fine however i want to start the position of the spinner not at the first itemselect i want it to start where the item in the cursor here for example i hope i made senseto put it into context in table column 1 is age range from and column 2 is age range to so in the spinner i get 05 610 1120 etcand what i want to do is start the spinner selected at 1120 if the users dob makes him that age i know setselection would select a certain value but i need to work out the correct one for the users ageso i basically want to know how to work that out and populate select the spinner correctly thanks,['android'] +126262,clickonce update cancelled by user and it never asks for an update again i have a windows forms application and it is deployed through clickonce during launch of the application it checks for an update and prompts the user for the same if the user choose not to install the update for that session it does not ask anymore is this by design or am i missing any settinghow do i make it prompt the user for an update next time he launches the application,['c#'] +126269,string concatenation using preprocessor is it possible to concatenate strings during preprocessingi found this exampledefine h hello define w worlddefine hw h wprintfhw prints hello worldhowever it does not work for me prints out hello when i use gcc stdc99upd this example looks like working now however is it a normal feature of c preprocessor,"['c++', 'c']" +126278,hibernate nosuchfielderror instance but only with struts 1 i am new to java and hibernate being a rails and c developer anyway i have a test program that works fine with hibernate but my actual web app struts 1 crashes withsevere servletservice for servlet default threw exceptionjavalangnosuchfielderror instancei am usinghibernate 361 with annotationsstruts 1 with apache tilesc3p0 connection poolhere is the program that actually works it is a part of the main project just a simple java testpublic class testuser public static void mainstring args sessionfactory factory hibernateutilgetsessionfactory session session factorygetcurrentsession sessionbegintransaction string querystring from user where username quake query query sessioncreatequeryquerystring user quake userqueryuniqueresult sessiongettransactioncommit systemoutprintln quakegetemail systemoutprintln active quakeisactive userrepository userrepo new userrepository systemoutprintln user quake userrepofindallget0getemail works just fine outputs a little sample datanow when i try to do the same thing in struts i get the exception this is what does not workpublic class listusers extends orgapachestrutsactionaction forward namesuccess path private static final string success success this is the action called from the struts framework param mapping the actionmapping used to select this instance param form the optional actionform bean for this request param request the http request we are processing param response the http response we are processing throws javalangexception return overridepublic actionforward executeactionmapping mapping actionform form httpservletrequest request httpservletresponse response throws exception liststring listmsg new arrayliststring listmsgaddmessage a listmsgaddmessage b listmsgaddmessage c listmsgaddmessage d requestsetattributelistmsg listmsg userrepository userrepo new userrepository crashes here see hibernateutil string email userrepofirstgetemail return mappingfindforwardsuccess this is my hibernateutil classpublic class hibernateutil private static final sessionfactory sessionfactory buildsessionfactory private static sessionfactory buildsessionfactory try create the sessionfactory from hibernatecfgxml configuration config new configuration this line crashes in struts add annotated classes configaddannotatedclassuserclass configconfigure return configbuildsessionfactory catch throwable ex make sure you log the exception as it might be swallowed systemerrprintlninitial sessionfactory creation failed wtfqnil ex throw new exceptionininitializererrorex public static sessionfactory getsessionfactory return sessionfactory the configuration config new configuration line in the hibernateutil is the line that crashes in struts but not the test app here is the complete exception dumpfeb 24 2011 95158 am orgapachecatalinacorestandardwrappervalve invokesevere servletservice for servlet default threw exceptionjavalangnosuchfielderror instanceat orghibernatetypebasictyperegistryinitbasictyperegistryjava94at orghibernatetypetyperesolverinittyperesolverjava59at orghibernatecfgconfigurationinitconfigurationjava249at orghibernatecfgconfigurationinitconfigurationjava300at comkencogroupkkmsstrutsutilitieshibernateutilbuildsessionfactoryhibernateutiljava22at comkencogroupkkmsstrutsutilitieshibernateutilclinithibernateutiljava17at comkencogroupdaorepositoriesuserrepositoryfirstuserrepositoryjava33at comkencogroupkkmsstrutsactionslistusersexecutelistusersjava52at orgapachestrutsactionrequestprocessorprocessactionperformrequestprocessorjava425at orgapachestrutsactionrequestprocessorprocessrequestprocessorjava228at orgapachestrutsactionactionservletprocessactionservletjava1913at orgapachestrutsactionactionservletdogetactionservletjava449at javaxservlethttphttpservletservicehttpservletjava617at javaxservlethttphttpservletservicehttpservletjava717at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava290at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava206at orgtuckeywebfiltersurlrewriterulechainhandlerewriterulechainjava176at orgtuckeywebfiltersurlrewriterulechaindorulesrulechainjava145at orgtuckeywebfiltersurlrewriteurlrewriterprocessrequesturlrewriterjava92at orgtuckeywebfiltersurlrewriteurlrewritefilterdofilterurlrewritefilterjava381at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava235at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava206at orgnetbeansmoduleswebmonitorservermonitorfilterdofiltermonitorfilterjava393at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava235at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava206at orgapachecatalinacoreapplicationthispatcherinvokeapplicationthispatcherjava646at orgapachecatalinacoreapplicationthispatcherprocessrequestapplicationthispatcherjava436at orgapachecatalinacoreapplicationthispatcherdoforwardapplicationthispatcherjava374at orgapachecatalinacoreapplicationthispatcherforwardapplicationthispatcherjava302at orgtuckeywebfiltersurlrewritenormalrewrittenurldorewritenormalrewrittenurljava213at orgtuckeywebfiltersurlrewriterulechainhandlerewriterulechainjava171at orgtuckeywebfiltersurlrewriterulechaindorulesrulechainjava145at orgtuckeywebfiltersurlrewriteurlrewriterprocessrequesturlrewriterjava92at orgtuckeywebfiltersurlrewriteurlrewritefilterdofilterurlrewritefilterjava381at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava235at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava206at orgnetbeansmoduleswebmonitorservermonitorfilterdofiltermonitorfilterjava393at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava235at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava206at orgapachecatalinacorestandardwrappervalveinvokestandardwrappervalvejava233at orgapachecatalinacorestandardcontextvalveinvokestandardcontextvalvejava191at orgapachecatalinacorestandardhostvalveinvokestandardhostvalvejava127at orgapachecatalinavalveserrorreportvalveinvokeerrorreportvalvejava102at orgapachecatalinacorestandardenginevalveinvokestandardenginevalvejava109at orgapachecatalinaconnectorcoyoteadapterservicecoyoteadapterjava298at orgapachecoyotehttp11http11aprprocessorprocesshttp11aprprocessorjava859at orgapachecoyotehttp11http11aprprotocolhttp11connectionhandlerprocesshttp11aprprotocoljava579at orgapachetomcatutilnetaprendpointworkerrunaprendpointjava15at javalangthreadrunthreadjava662what am i doing wrongthanks,['java'] +126315,javascript open brace in the same line i remember there is a conventionrecommendation to put opening brace in the same line because the way javascript add semicolon or something okfunction blahprobably not okfunction blah but i do not find a relevant source to confirmdeny this is this true or just a myth,['javascript'] +126321,how do i programmatically remove an existing rule that was defined in xml i have a linear layout that is contained inside a relative layout it is set in the xml file to be to the right of another linear layout this works finein some cases i want to change the relative position of the layout during the oncreate of the activity so i need to modify the to the right of param to relate to another layouti tryed this relativelayoutlayoutparams layoutparams layoutparams relativelayoutlayoutparams linearlayouttomove getlayoutparams layoutparamsaddrulerelativelayoutright of ridnew ref linearlayoutbut it does not work oany clues,['android'] +126328,ffmpeg how to write video to a file what i want is 1 get video packet from stream source 2 decode it 3 and write that decoded data as video fileavi mpeg etci can able to get video packets from a file as avpacket and also can decode and save as an imageraw ffmpeg tutorials show how to do itbut i can not do not know write that video data to a fileother which can be played by media playerssuch as vlcbest wishesps real code samples will be great if possiblenow i make test with av interleaved write but i got strange error non monotone timestamps i have no control over pts values of media source some extra infoin ffmpeg i have to read media packets from media source it may be real fileavimov or even rtsp serverthen write those media packets to a real file physical avi mov etc filei need reader and writer i can read the media source file even encode packets according to given format but i can not write to filewhich any player can playand some pseudocodefile myfilemytestfileaviwhile source hasvideopackets packet sourcegetnextvideopacket frame decodedframe decodepacket videopacket encodedpacket encode decodedframe myfilewritefileencodedpacket or just write the original file without encode decode file myfilemytestfileavi while source hasvideopackets packet sourcegetnextvideopacket myfilewritefilepacket then i can able to open mytestavi file with a player,['c'] +126336,improving performance of django foreignkey fields in admin by default djangos admin renders foreignkey fields in admin as a select field listing every record in the foreign table as an option in one adminaccessible model i am referencing the user model as a foreignkey and since i have thousands of users django is populating the select with thousands of options this is causing the admin page to load incredibly slowly and the select is not very useful since it can take a while to scroll through thousands of options to find the one you wantwhats the best way to change the rendering of this field in order to improve page load and usability i would like the select field to be replaced with some sort of button to launch a search form popup or a text field that searches keywords via ajax to find the id for the specific user they want to associate does admin have anything like this builtin or would i have to write this from scratch,['python'] +126367,ef code first globally set varchar mapping over nvarchar i have what should be an easy question but i have been unable to find the answer myselfi am using ef4 ctp5 code first model with hand generated pocos it is processing string comparisons in generated sql as where nvalue objectpropertyi am aware that i can override this functionality using columntypename varcharpublic string property getsetwhich fixes the issue for that single occurrence and correctly generates the sql aswhere value objectpropertyhowever i am dealing with a very large domain model and going through each string field and setting typename varchar is going to be very very tedious i would like to specify that ef should see string as varchar across the board as that is the standard in this database and nvarchar is the exception casereasoning for wanting to correct this is query execution efficiency comparison between varchar and nvarchar is very inefficient in sql server 2k5 where varchar to varchar comparisons execute almost immediately,['c#'] +126369,programmatically moveanimate a uitableview row from one position to another i have a uitableview and i want to programmatically move one row from position n1 to position n2 and i would like it to animate from the old location to the new i have looked through the uitableview documentation and i am only seeing inserts reloads and deletes do you know of a way i can do this programmaticallya couple of notesi know that i can animate the deletion from location n1 and animate the insertion to location n2 at the same time that is my fallback but i would like the user to understand that it is truly moving from n1 to n2i am not talking about allowing the user to drag it from one place to another i understand how to do that i am looking for a way to initiate and animate the move programmatically,"['iphone', 'ios']" +126386,linuxpython encoding a unicode string for print i have a fairly large python 26 application with lots of print statements sprinkled about i am using unicode strings throughout and it usually works great however if i redirect the output of the application like myapy outputtxt then i occasionally get errors such as thisunicodeencodeerror ascii codec cannot encode character uxa1 in position 0 ordinal not in range128i guess the same issue comes up if someone has set their locale to ascii now i understand perfectly well the reason for this error there are characters in my unicode strings that are not possible to encode in ascii fair enough but i would like my python program to make a best effort to try to print something understandable maybe skipping the suspicious characters or replacing them with their unicode ids this problem must be common what is the best practice for handling this problem i would prefer a solution that allows me to keep using plain old print but i can modify all occurrences if necessaryps i have now solved this problem the solution was neither of the answers given i used the method given at as given by chrisj in one of the comments that is i replace sysstdout with a wrapper that calls unicode encode with the correct arguments works very well,['python'] +126408,can i serve html files using razor as if they were cshtml files without changing the extension of all my pages i manage a large aspnet site which has previously been converted from static html site to aspnet for several reasons mainly seo we decided not to rename all the files to aspx back when we originally converted the site this was very easy to do by simply adding the buildprovider and httphandler to the webconfigbuildproviders add extensionhtml typesystemwebcompilationpagebuildproviderbuildprovidershttphandlers add pathhtml verb typesystemwebuipagehandlerfactoryhttphandlersnow i am upgrading the site to use aspnet webpages with razor cshtml files i can rename all the files if necessary and use url rewriting to make the urls stay the same however it would be much easier if i could just configure the webconfig to tell it to parse html files as if they were cshtmli have searched around quite a bit and could not find anything equivalent to the pagehandlerfactory for razor pages it appears as though it is just an internal mechanism in the net 40 isapi handlerthe site is currently running on windows 2003 server and iis 6 we will be upgrading to 2008iis 75 in the near future but i would prefer not to wait for thatis there any way to get the html files to be parsed by razor as if they were cshtml files,['asp.net'] +126410,listen ignores the backlog argument i have the following problemi have sockfd socketaf inet sock stream 0after i set up and bind the socket let us say with sockfdsin port htons6 i immediately dolistensockfd 3sleep50 for test purposesi am sleeping for 50 seconds to test the backlog argument which seems to be ignored because i can establish a connection more than 3 times on port 6 what i mean is that i get a synack for each nth syn n3 sent from the client and placed in the listen queue instead of being dropped what could be wrong i have read the man pages of listen2 and tcp7 and foundthe behavior of the backlog argument on tcp sockets changed with linux 22 now it specifies the queue length for completely established sockets waiting to be accepted instead of the number of incomplete connection requests the maximum length of the queue for incomplete sockets can be set using procsysnetipv4tcp max syn backlog when syncookies are enabled there is no logical maximum length and this setting is ignored see tcp7 for more information but even with sysctl w sysnetipv4tcp max syn backlog2 and sysctl w netipv4tcp syncookies0 i still get the same results i must be missing something or completely missunderstand listens backlog purpose,['c'] +126414,why do we need to go for jquery newbie to jquery why do we need to go for jquery or what difference it makes on bringing jquery instead of ajax javascript whether jquery is the replacement of ajax and javascript,['jquery'] +126450,is it the rails way to use singular or plural controller names should i use article or articles,['ruby-on-rails'] +126454,hibernate criteria order by i have a table called gift which has a onetomany relationship to a table called clickthrough which indicates how many times that particular gift has been clicked i need to query for all of the gift objects ordered by clickthrough count i do not need the clickthrough count returned as i do not need anything done with it i just want to use it for purposes of orderingi need the query to return a list of gift objects directly just ordered by clickthrough count how do i do this using the criteria api i can find a lot of documentation out there on similar information to this but nothing quite like what i need,['java'] +126463,setting the source and target of the java compiler with maven does not work i have set my pom file to ask maven to compile my source code to be version 15 compatible using the source and target config params here is my pomproject xmlns xmlnsxsi xsischemalocation modelversion400modelversion groupidcomgroupid artifactiduserartifactid version001snapshotversion nametestname build plugins plugin groupidorgapachemavenpluginsgroupid artifactidmavencompilerpluginartifactid configuration source15source target15target configuration plugin plugins buildprojectand i have a simple main class like thispackage comuserpublic class test public static void mainstring argv systemoutprintlnisempty stringisempty was introduced since java 16 however compiling my code with mvn compile works while i would have expected it to fail because i have set maven to compile my code to java 15 and stringisempty was introduced in java 16 could anyone please suggest what i might have done wrong what is the correct way to force maven to use a particular java version when compilingfor information i am using apache maven 221 and javac 160 19thanks,['java'] +126484,net systemdiagnosticsstopwatch issue returns values too low on my computer the stopwatch is returning values way too low for example 200 ms when i specified threadsleep10 the program is supposed to wait 1 second i also tested with manualreseteventwaitone10 and got the same results both framework 20 and 30 gives this strange behavior i am running windows xp sp3 with net framework 35 sp1here is the result of my tests code below10 ms for datetimenowticks0201 ms for stopwatchelapsedticks0142 ms for stopwatchelapsedmilliseconds0139 ms for stopwatchelapsedticks after reset0264 ms for stopwatchelapsedticks setting threadaffinity0151 ms for stopwatchelapsedticks setting processoraffinity and more0371 ms for stopwatchelapsedticks with syncronized objectdone programcs fileclass program static void mainstring args stopwatchtestgo consolewritelinedone consolereadline stopwatchtestcs classinternal static class stopwatchtest public const int sleeptime 10 public static void go region test 0 with datetimenowticks long starttick datetimenowticks threadsleepsleeptime long stoptick datetimenowticks long elapseddt stoptick starttick 100 thisplayintelapseddt 10 10 datetimenowticks endregion test 0 with datetimenowticks stopwatch watch stopwatchstartnew long frequency stopwatchfrequency double nanosecpertick 10 10 10 frequency region test 1 with stopwatchelapsedticks starttick watchelapsedticks threadsleepsleeptime stoptick watchelapsedticks double elapsedsw stoptick starttick nanosecpertick thisplayintelapsedsw 10 10 stopwatchelapsedticks endregion test 1 with stopwatchelapsedticks region test 2 with stopwatchelapsedmilliseconds starttick watchelapsedmilliseconds threadsleepsleeptime stoptick watchelapsedmilliseconds thisplayintstoptick starttick stopwatchelapsedmilliseconds endregion test 2 with stopwatchelapsedmilliseconds region test 3 with stopwatchelapsedticks after reset watchstop watchreset watchstart starttick watchelapsedticks threadsleepsleeptime stoptick watchelapsedticks elapsedsw stoptick starttick nanosecpertick thisplayintelapsedsw 10 10 stopwatchelapsedticks after reset endregion test 3 with stopwatchelapsedticks after reset region test 4 with stopwatchelapsedticks and threadaffinity threadbeginthreadaffinity starttick watchelapsedticks threadsleepsleeptime stoptick watchelapsedticks elapsedsw stoptick starttick nanosecpertick thisplayintelapsedsw 10 10 stopwatchelapsedticks setting threadaffinity threadendthreadaffinity endregion test 4 with stopwatchelapsedticks and threadaffinity region test 5 with stopwatchelapsedticks and processoraffinity and more const int affinity 0x01 process proc processgetcurrentprocess procprocessoraffinity new intptraffinity procpriorityclass processpriorityclasshigh processthreadcollection ptc procthreads foreach processthread pt in ptc ptidealprocessor 0 ptprocessoraffinity new intptraffinity threadcurrentthreadpriority threadpriorityhighest starttick watchelapsedticks threadsleepsleeptime stoptick watchelapsedticks elapsedsw stoptick starttick nanosecpertick thisplayintelapsedsw 10 10 stopwatchelapsedticks setting processoraffinity and more endregion test 5 with processoraffinity and more region test 6 with syncronized object elapsedsw new synctimergo thisplayintelapsedsw 10 10 stopwatchelapsedticks with syncronized object endregion test 6 with syncronized object private static void thisplayint milliseconds string testname consolewriteline0 ms for 1 milliseconds testname synchronizationinternal class synctimer contextboundobject methodimplmethodimploptionssynchronized public double go stopwatchstartnew long frequency stopwatchfrequency double nanosecpertick 10 10 10 frequency long starttick stopwatchgettimestamp threadsleepstopwatchtestsleeptime long stoptick stopwatchgettimestamp return stoptick starttick nanosecpertick,"['c#', '.net']" +126487,using settimeout to improve responsiveness when looking to improve a pages performance one technique i have not heard mentioned before is using settimeout to prevent javascript from holding up the rendering of a pagefor example imagine we have a particularly timeconsuming piece of jquery inline with the htmlinputclickfunction do stuffif this code is inline we are holding up the perceived completion of the page while the piece of jquery is busy attaching a click handler to every input on the pagewould it be wise to spawn a new thread insteadsettimeoutfunction inputclickfunction do stuff 100the only downside i can see is that there is now a greater chance the user clicks on an element before the click handler is attached however this risk may be acceptable and we have a degree of this risk anyway even without settimeoutam i right or am i wrong,['javascript'] +126501,find the words start from a special character java i want to find the words that start with a sign in a string in java there can be spaces between the sign and the word as wellthe string hi how are you shall give the output as howyoui have tried this with regex but still could not find a suitable pattern please help me on thisthanks,['java'] +126517,android setting zoom level in google maps to include all marker points i am trying to set zoom level for maps in android such that it includes all the points in my list i am using following code int minlatitude integermax valueint maxlatitude integermin valueint minlongitude integermax valueint maxlongitude integermin value find the boundaries of the item set item contains a list of geopointsfor geopoint item items int lat itemgetlatitudee6 int lon itemgetlongitudee6 maxlatitude mathmaxlat maxlatitude minlatitude mathminlat minlatitude maxlongitude mathmaxlon maxlongitude minlongitude mathminlon minlongitudeobjmapcontrollerzoomtospan mathabsmaxlatitude minlatitude mathabsmaxlongitude minlongitudethis works sometimes however sometimes some points are not shown and i need to then zoom out to view those points is there any way to solve this problem,['android'] +126539,what use is a dependencyproperty whose ownertype is not a dependencyobject i have just started playing with dependencyproperties in wpf and i was wanting to check a couple of thoughts while i get to grips with themgiven the following and ignoring naming convention for nowclass mytestclass public static readonly dependencyproperty dp1 dependencypropertyregistermyprop typeofstring typeofmytestclass public static readonly dependencyproperty dp2 dependencypropertyregistermyprop2 typeofstring typeofmytestclass new propertymetadatahelloi find that dp2 throws a typeinitializationexception with the message mytestclass type must derive from dependencyobject which i expected but dp1 is accepted quite happilynow i understand why dp2 raises an exception as i am trying to register property metadata on a type that is not a dependencyobject and this is fine i have looked under the covers and can see the code path that both dp1 and dp2 follow so i understand from a code perspective why dp1 does not raise the exception but conceptually i would have expected both dp1 and dp2 to raise the same exceptionmy question is what use is there in creating a dependencyproperty like dp1 whose ownertype is not a dependencyobject as i cannot see how it can be used without the getvaluesetvalue methods on a dependencyobject,['c#'] +126541,create an array in javascript of custom objects hi i need some help with javascript function pricingdataidmethodfreqserviceprice thisidid thispaymentmethod idmethod thispaymentfrequency idfreq thisservice idservice thispriceprice i need to create an array in this wayvar tempnew pricingdatanew pricingdata12345new pricingdata12345but this does not work i am going to pass the data in through the server so i would prefer syntax similar to this,['javascript'] +126551,what is could not open shared capabilities memory gscapabilities no such file or directory when i do an xcodebuild headless commandline build i get could not open shared capabilities memory gscapabilities but the build product is finecompilexib resourcesmaininterfacebuilderxib cd usersxcodeprojectsx setenv ibc minimum compatibility version 312 setenv path developerplatformsiphoneosplatformdeveloperusrbindeveloperusrbinusersxcodeprojectsiphonebuildscriptusersxcodeprojectsiphonebuildscriptusrbinbinusrsbinsbin developerusrbinibtool errors warnings notices outputformat humanreadabletext compile usersxcodeprojectsxbuildreleaseiphoneosxappxnib usersxcodeprojectsxresourcesmaininterfacebuilderxib sdk developerplatformsiphoneosplatformdevelopersdksiphoneos42sdkcould not open shared capabilities memory gscapabilities no such file or directoryhow can i fix these warnings,['iphone'] +126561,c 35 optional and defaultvalue for parameters i am using c net 35 to build an application i have been working with optional parameter attributes in net 40 with no problems i did notice that with 35 there is the option workaround to add the following attributes to your method like so public static void methodnamestring name optionaldefaultvaluenullstring placeholder even though i have added the attributes to the method if i try and call it like so methodnametestthe compiler will complain that it is looking for two parameters instead of one is it actually possible to do this using c net 35 am i doing something wrong,"['c#', '.net']" +126562,list of default modules that come along with python 2x installation i have a project in my mind for which i am planning to use python for implementationbefore i start i am looking for a comprehensive list of all modules which come with a standard python2x python27 installation so that i can figure out what all can be done without installing a single dependency and later add dependencies accordingly according to the needsis there any online list available or any other way to find this list,['python'] +126606,java xml canonicalization whats the easiest way to make a canonical form of a xml file in java do you have some done code for that i have found several links on the net like this this and this but i cannot make it to work thanksivanedit i used the canonicalizer that was proposed down there but i get strange results to be more precize this method does not delete white spaces between elements this is what i getmetric xmlns xmlnsxsi nametotal memory consumption metric typedouble unitmbit xsischemalocation wslaxsd sourceserviceprovidersource measurementdirective resulttypedouble xsitypestatusrequest requesturi unused requesturi measurementdirective metric,['java'] +126607,enabling done button after inserting one char in a textfield textfielddidendediting or textfieldshouldbeginediting or i would like to enable the done button on the navbar in a modal view when the user writes at least a char in a uitextfield i triedtextfielddidendediting enables the button when the previous uitextfield resigns first responder so with the zero chars in the current uitextfieldtextfieldshouldbeginediting is called when the textfield becomes the first responderis there another way to do thiseditthe solution could be booltextfielduitextfield textfield shouldchangecharactersinrangensrangerange replacementstringnsstring stringbut neither selfnavigationitemrightbarbuttonitem setenabledyesordonebutton setenabledyes donebutton is an iboutlet tied to my done uibarbuttonitem in ibwork,"['iphone', 'ios']" +126610,avcapturevideopreviewlayer avcapturevideopreviewlayer avlayer avcapturevideopreviewlayer layerwithsessionsessionavlayerframe selfviewframeselfviewlayer addsublayeravlayeri use avcapturevideopreviewlayer to thisplay video on the viewbut the videos view did not fill up the full iphone4s screentwo grey bar at the rightleft sidei want the video fills up full screenhow can i deal with it thank you very much,['iphone'] +126616,how can i default a parameter to guidempty in c i wish to saypublic void problemguid optional guidemptybut the compiler complains that guidempty is not a compile time constantas i donat wish to change the api i canat use nullableguid,['c#'] +126629,generate poco objects from xml file i have an xml file which roughly describes a database schema i am inheritingi want to generate poco objects for this file to give me a head start with the business objects in my c applicationis this possible and how,['c#'] +126632,aspnet mvc global variables how do you declare global variables in aspnet mvc,"['c#', '.net', 'asp.net']" +126652,oracle sql order by in subquery problems i am trying to run a subquery in oracle sql and it will not let me order the subquery columns ordering the subquery is important as oracle seems to choose at will which of the returned columns to return to the main queryselect psid pscreated date pstlast updated pstfrom state pstto state select last updated from mwcrmprocess state transition subpst where subpstlast updated pstlast updated and subpstprocess state psid and rownum 1 as next response from mwcrmprocess state ps mwcrmprocess state transition pst where pscreated date sysdate 124 and psidpstprocess state order by psid ascreally should beselect psid pscreated date pstlast updated pstfrom state pstto state select last updated from mwcrmprocess state transition subpst where subpstlast updated pstlast updated and subpstprocess state psid and rownum 1 order by subpstlast updated asc as next response from mwcrmprocess state ps mwcrmprocess state transition pst where pscreated date sysdate 124 and psidpstprocess state order by psid asc,['sql'] +126678,entity framework casting error the following works perfectlyiqueryableproperty propertyquery propertydaosearchwithadditionalparameters elided iqueryablelong propertyidquery propertyqueryselectp ppropertyidvar relevantfmvs propertydaodbfmvhistorieswheref propertyidquerycontainsfpropertyidtolistbut the following blows upiqueryableproperty propertyquery propertydaosearchwithadditionalparameters elided var relevantfmvs propertydaodbfmvhistorieswheref propertyqueryselectp ppropertyidcontainsfpropertyidtolistnote that instead of creating propertyidquery separately i just substituted the query itself where the variable had beenexception isunable to cast the type systemlinqiqueryable1 to type systemlinqiqueryable1 linq to entities only supports casting entity data model primitive typescan someone shed some light on what ef 4 is doing under the covers to make only the first query work even though they are ostensibly equivalenti know iqueryablet and expression trees do a lot of stuff under the covers but how is it that saving an intermediate step into a local variable would affect the outcome editby request heres the full method that is being called and the methods that that method calls public iqueryableproperty basicsearchfromconstraintspropertyinvoiceconstraints constraints return executesearchfromconstraintsdynamicconstraintspropertyinst constraintscompanynumber constraintstaxsubtype constraintsphaseid constraintsstate constraintscounty constraintscity constraintsjurisdiction private iqueryablet executesearchfromconstraintstt property int companynumber byte subtype byte phaseid string state string county string city string jurisdiction where t property iqueryablet result basedbpropertiesoftypet if subtype 0 result resultwherep ptaxsubtypeid subtype if companynumber 0 result resultwherep pcompanynum companynumber if stringisnulloremptystate result resultwherep pstate state if stringisnulloremptycounty result resultwherep pcounty county if stringisnulloremptycity result resultwherep pcity city if stringisnulloremptyjurisdiction result resultwherep pjurisdiction jurisdiction if phaseid 0 result resultwherep pphaseid phaseid return result public virtual iqueryableproperty searchwithadditionalparametersdatalayerdaopropertyinvoiceconstraints constraints string propertynumber string altdesc string countyacctnumber string city string jurisdiction string secondarystateid string legaldesc string status int taxyear null iqueryableproperty result basicsearchfromconstraintsconstraints if stringisnulloremptystatus result resultwherep pstatus status if stringisnulloremptypropertynumber result resultwherep ppropertynumcontainspropertynumber if stringisnulloremptyaltdesc result resultwherep paltdescriptioncontainsaltdesc if stringisnulloremptycountyacctnumber result resultwherep pcountyaccountnumcontainscountyacctnumber if stringisnulloremptycity result resultwherep pcitycontainscity if stringisnulloremptyjurisdiction result resultwherep pjurisdictioncontainsjurisdiction if taxyearhasvalue result resultwherep pfmvhistoriesanyf ftaxyear taxyear if constraintsfmvphaseid 0 result resultwherep pfmvhistoriesanyf fphaseid constraintsfmvphaseid if stringisnulloremptysecondarystateid if constraintspropertyinst is welldetail result resultoftypewelldetailwherew wsecondarystateid secondarystateid else throw new applicationexceptioninvalid use secondary state id can only be set when searching for well property types if stringisnulloremptylegaldesc if constraintspropertyinst is realestatedetail result resultoftyperealestatedetailwherer rlegaldescrcontainslegaldesc else if constraintspropertyinst is realestateservicingdetail result resultoftyperealestateservicingdetailwherer rlegaldescrcontainslegaldesc else throw new applicationexceptioninvalid use legal description can only be set when searching for either real estate or real estate servicing property types return result editi really wanted akashs answer to be correct but if it was i would expect the middle query here to blow up but in fact all three work just finei am beginning to suspect that the inheritance structure i have on type property from the original example might have something to do with this dummybookmodelentities db new dummybookmodelentities iqueryableint bookids dbbookswhereb bid 4selectb bid iqueryablebook booksfromidquery dbbookswhereb bid 4 try var l1 dbbookswhereb bookidscontainsbidtolist consolewritelineid query with id local var worked count 0 l1count catch exception e consolewritelineid query failed consolewritelineetostring consolewriteline try var l1 dbbookswhereb booksfromidqueryselectb inner b inneridcontainsbidtolist consolewritelineid query with whole book local var worked count 0 l1count catch exception e consolewritelineid query with whole book local var failed consolewritelineetostring consolewriteline try var l1 dbbookswhereb booksfromidquerycontainsbtolist consolewritelinewhole book sub query without select worked count 0 l1count catch exception e consolewritelinewhole book sub query without select consolewritelineetostring consolewriteline editi added in some inheritance and now the bottom two queries fail it looks like any time you have an oftype in the query ef simply does not want to parse through entire queries within queries you have to break out your substeps into local variablesi will award akash the bounty tonight unless someone has something else to add dummybookmodelentities db new dummybookmodelentities iqueryableint bookids dbbooksoftypescifibookwhereb bid 4selectb bid iqueryablebook booksfromidquery dbbooksoftypescifibookwhereb bid 4 try var l1 dbbookswhereb bookidscontainsbidtolist consolewritelineid query with id local var worked count 0 l1count catch exception e consolewritelineid query failed consolewritelineemessage consolewriteline try var l1 dbbookswhereb booksfromidqueryselectb inner b inneridcontainsbidtolist consolewritelineid query with whole book local var worked count 0 l1count catch exception e consolewritelineid query with whole book local var failed consolewritelineemessage consolewriteline try var l1 dbbookswhereb booksfromidquerycontainsbtolist consolewritelinewhole book sub query without select worked count 0 l1count catch exception e consolewritelinewhole book sub query without select consolewritelineemessage consolewriteline consolewriteline,['c#'] +126679,write plugin for android app i will try to develop an app which is enabled for plugins like in windowsnetworld dllsi will have small rectanglelinearlayouts in my app where the user is able to manage them with visible onoff later on i or someone else will give the user a new plugin which the apps is thisplaying nowis it possible if yes howare there good sites out there you could direct meregardsfly,['android'] +126682,ast traversal in visitor or in the nodes update accepted ira baxters answer since it pointed me into the right direction i first figured out what i actually needed by starting the implementation of the compiling stage and it became obvious pretty soon that traversal within the nodes made thie an impossible approach not all nodes should be visited and some of them in reverse order for example first the rhs of an assignment so the compiler can check if the type matches with the rhsoperator putting traversal in the visitor makes this all very easyi am playing around with asts and the likes before deciding a major refactory of the handling of a minilanguage used in an applicaitoni have built a lexerparser and can get the ast just fine there is also a visitor and as concrete implementation i made an asttooriginal which just recreates the original source file eventually there is goin to be some sort of compiler that also implements the vsisitor and creates the actual c code at runtime so i want to make sure everything is right from the startwhile everything works fine now there is some similarduplicate code since the traversal order is implemented in the visitor itselfwhen looking up more information it seems that some implementations prefer keeping the traversal order in the visited objects themselves instead in order not to repeat this in each concrete visitoreven the gof only talks briefly about this in the same way so i wanted to give this approach a try as well but got stuck pretty soon let me explainsample source line and corresponding ast nodesift100x1sety20truex2conditional binaryop leftvariable namet operator rightinteger value100 iftrue assignment leftvariable namex operator rightinteger value1 method methodname namesety arguments integer value20 boolean valuetrue iffalse assignment leftvariable namex operator rightinteger value1some codeclass binaryop void accept visitor v vvisit this expr left op op expr right class variable void accept visitor v vvisit this name nameclass visitor provide basic traversal terminal visitors are abstract void visit variable 0 void visit binaryop p pleftaccept this popaccept this prightaccept this void visit conditional p pcondaccept this visitlist piftrue visitlist just iterates over the array calling accept on each element visitlist piffalse implementing asttooriginal is pretty straightforward all abstract visitor methods just print out the name or value member of the terminalfor the nonterminals it depends printing an assignment works ok with the default visitor traversal for a conditional extra code is neededclass asttooriginal void visit conditional p str if pcondaccept this str visitlistwithpostop is like visitlist but calls op for each except the last iteration visitlistwithpostop piftrue appendtext str visitlistwithpostop piffalse appendtext str str so as one can see both the visit methods for a conditional in visitor and asttooriginal are indeed very similarhowever trying to solve this by putting traversal into the nodes made things not just worse but rather a complete messi tried an approach with previsit and postvisit methods which solved some problems but just introduced more and more code into the nodesit also started to look like i would have to keep track of a number of states inside the visitor to be able to know when to add closing brackets etcclass binaryop void accept conditional v vvisit this opaccept v visitlist iftrue v visitlist iffalse v class vistor now all methods are pure virtualclass asttooriginal void visit conditional p str if now what after returning here binaryop will visit the op automatically so i cannot insert the if i make a postvisit binaryop and call it it binaryopaccept i get the chance to insert the but now i have to keep a state my postvisit method needs to know it is currently being called as part of a conditional things are even worse for the iftrueiffalse statement arrays each element needs a appended but not the last one how am i ever going to do that in a clean way question is this approach just not suited for my case or am i overlooking something essential is there a common design to cope with these problems what if i also need traversal in a different direction,['c++'] +126707,linq order by number then letters i have a list of strings and these strings contain numbers and wordswhat i wanted to do is order it by the numbers numeric order followed by the words alphabetical ordermy list does not contain a mix of the two here is an example1 5 500 lt rt 400 linq 1 5 400 500 lt rthere is a example of what i have it works but i was wondering if there is a better way of writing it int results 0 grabs all voltages var voltage activerecordlinqasqueryableequipment orderbyx xvoltage selectx xvoltage thistinct tolist order by numeric var numbervoltage voltage where x inttryparsex out results orderby x converttoint32x then by alpha var lettervoltage voltage wherex stringisnulloremptyx wherex inttryparsex out results orderbyx x return numbervoltageunionlettervoltagethanks for the help,['c#'] +126714,uigraphicsgetimagefromcurrentimagecontext memory leak pdf previews i am trying to create previews images of pages in a pdfbut i have some problems with the release of memoryi wrote a simple test algorithm that cycles on the problemthe app crashes near the 40th iterationnsarray paths nssearchpathfordirectoriesindomainsnsdocumentdirectory nsuserdomainmask yesnsstring documentsdirectory paths objectatindex0nsstring pdfpath documentsdirectory stringbyappendingpathcomponentmypdfpdfcfurlref url cfurlcreatewithfilesystempath null cfstringrefpdfpath kcfurlposixpathstyle no cgpdfdocumentref mypdf cgpdfdocumentcreatewithurl url cfrelease urlcgpdfpageref page cgpdfdocumentgetpage mypdf 1 int i0whilei 10 uigraphicsbeginimagecontextcgsizemake7681024 cgcontextref context uigraphicsgetcurrentcontext cgcontextsetrgbfillcolorcontext 10101010 cgcontextfillrectcontextcgrectmake0 0 768 1024 cgcontextsavegstatecontext cgcontexttranslatectmcontext 00 1024 cgcontextscalectmcontext 10 10 cgcontextdrawpdfpagecontext page cgcontextrestoregstatecontext the problem is here without this line the application does not crash uiimageview backgroundimageview1 uiimageview alloc initwithimageuigraphicsgetimagefromcurrentimagecontext uigraphicsendimagecontext backgroundimageview1 release nslogloop d icgpdfdocumentreleasemypdfthe abovementioned line seems to generate a memory leakhowever instruments does not show memory problemscan i escape from this kind of mistakesomeone can explain me in which wayare there other ways to show previews of a pdfupdatei think the problem is not the release of uiimage created by the method uigraphicsgetimagefromcurrentimagecontext but the release of uiimageview created with this autorelease imagei have divided the line of code in three stepsuiimage myimage uigraphicsgetimagefromcurrentimagecontextuiimageview myimageview uiimageview alloc initmyimageview setimage myimage memory leakthe first and second lines does not create memory leaks so i think that the method uigraphicsgetimagefromcurrentimagecontext is not the problemi also tried as follows but the problem persistsuiimageview myimageview uiimageview alloc initwithimagemyimagei think there is a memory leak in the release of a uiimageview that contains a uiimage with the autorelease propertyi tried to write my object uiimageview inheriting a uiview as explained in this threadthis solution works but is not very elegant it is a workaround i would prefer to use the object uiimageview solving the memory problem,"['objective-c', 'ios']" +126720,jqgrid access cell data while it is being edited i am currently using aftersavecell to handle manually updating some cells in a grid i have this working fine if the user uses enter to save the currently editing cell unfortunately if they click or tab out of the cell they are editing directly into another cell i can no longer grab the cell value of the newly edited cell as getcell will only return the html for the input control in summary is there any way to access the value of the cell even while it is being editedjquerydocumentreadyfunction var mydata id1 invdate20071001nametest notenote amount20tax10total210 id2 invdate20071002nametest2 notenote2 amount30tax20total320 id3 invdate20070901nametest3 notenote3 amount40tax30total430 id4 invdate20071004nametest notenote4 amount20tax10total210 id5 invdate20071005nametest5 notenote5 amount30tax20total320 id6 invdate20070906nametest notenote6 amount40tax30total430 id7 invdate20071004nametest7 notenote7 amount20tax10total210 id8 invdate20071003nametest8 notenote8 amount30tax20total320 id9 invdate20070901nametest notenote9 amount40tax30total430 id10invdate20070908nametest10notenote10amount50tax30total530 id11invdate20070908nametest11notenote11amount50tax30total530 id12invdatenametotal noteamounttaxtotal var grid list gridjqgrid cellsubmit remote cellurl examplegridsave datatype local data mydata mtype post colnames inv no date client amount tax total notes colmodel name id index id width 65 sorttype int hidden true name invdate index invdate width 120 align center formatter date formatoptions newformat dmy sortable false name name index name editable true width 90 sortable false name amount index amount editable true width 70 formatter number align right sortable false name tax index tax editable true width 60 formatter number align right sortable false name total index total editable true width 60 formatter number align right sortable false name note index note width 100 sortable false rownum 10 pager pager viewrecords true sortorder desc caption aftersavecell issue height 100 celledit true gridcomplete function calculatetotal aftersavecell function rowid name val irow icol calculatetotal function calculatetotal var totalamount 0 var totaltax 0 var grid jquerylist var ids gridjqgridgetdataids for var i 0 i idslength i var id idsi if gridjqgridgetcell id name total gridjqgridsetrowdata id amount totalamount tax totaltax total totalamount totaltax else totalamount numbergridjqgridgetcell id amount totaltax numbergridjqgridgetcell id tax thanks in advance,"['javascript', 'jquery']" +126730,run a compiled iphone simulator app build app without xcode so have a complete build of my app compatible for the ios simulator on snow leopard now i do not want to install xcode on my other mac to run this the question is there a way to only install the ios simulator i could install the app on my ios simulator on my primary mac and then just copy the iphone simulator folder from the library folder and paste it on my secondary macor is there any other app,['iphone'] +126744,adding a spacing between images in a uiscrollview how does one add a gapspace between multiple images that are added to the uiscrollviewone example would be photos app which has black spacing between images when paging,['iphone'] +126748,why does gdb evaluate sqrt3 to 0 the square root of 3 as estimated by wolfram alpha17320508075688772935274463415058723669428052538103806280558when i do sqrt3 in c it evaluates to 0 whyedit4 heres how you can reproduce this issue in gdb create testc as followsinclude stdioh include mathhint main printfsqrt3 fn sqrt3 return 0compilegcc o0 g wall pedantic ansi lm o test testcrun debuggergdb testenter this at consolegdb break testc6breakpoint 1 at 0x400578 file testc line 6gdb rstarting program homepdedeckerdesktoptest breakpoint 1 main at testc66 printfsqrt3 fn sqrt3gdb print sqrt31 0gdb ssqrt3 1732051my gdb version is gnu gdb gdb suse 71312,['c'] +126763,dynamic loading of dll i have a program which needs to use a large number of pluginseach plugin must support a very basic interface this interface is defined in a dll ibasecomponent for simplicity of question sakeeach plugin will be in a specific directory appdirectorypluginplugintypeeach plugin can have any name for the plugins dll appdirectorypluginplugintypepluginnamedllso i need to check through each plugin subdirectory find each plugin that has a class which supports the ibasecomponent interface instantiate the class and call some functions on the plug inok all fine and dandy none of this is particularly hard the problem though is that i seem to be running into some weird issuesevery plugin needs to have the basedll file in the individual plugin folders instead of just in the program that will be loading the plugin and also it seems that i get many errors and warnings around dynamically loading a dll which have dlls that also need to be loadedi am using pluginmodule systemreflectionassemblyreflectiononlyloadfrompathtoassemblyin order to grab the plugin dll and usingtypes moduleassemblygettypesin order to grab the types contained within the dll i am iterating over the types and checking if the individual type is of the ibasecomponent interface signifying this is a valid to load class withif typegetinterfaceframeworknamespaceibasecomponent null it is of the ibasecomponent interfacelater in order to actually create an instance of the class from the dll i usepluginmodule systemreflectionassemblyloadfrompathtoassemblyand then usetypes componentgettypesin order to get the types within the module then select and load the class which supports the interface same as abovethe problem seems to be on when i usetypes componentgettypeswhen actually trying to load the class instead of simply looking at it hence my different usage of loadfrom and reflectiononlyloadthe exception i receive on the gettypes call on a second plug in but never the first isunable to load one or more of the requested types retrieve the loaderexceptions property for more informationwith the loaderexceptions property asthe specified module could not be found exception from hresult 0x8007007enulli am unsure why this occurs the dll is in the plugin folder and the dll containing the ibasecomponent interface is also in every one of the plugin directories am i going about this the wrong wayalso is it required for me to keep a copy of the dll containing ibasecomponent within each plugin subdirectory as well as the one used by the program itself or am i doing something incorrectly that would allow me to remove this requirementi am aware of mef which is what i wanted to use but unfortunately because i am required to support this on net 20 i am unable to use mef,"['c#', '.net']" +126769,android default xml editor is not opening anymore unsupported content type error i have been using eclipse for developing apps in android for quite some time i updated the android sdk platform to 30 api 11 recently now i am unable to open the androidmanifestxml or any other xml files in the layout folder by double clickingwhen i double click any xml file like mainxml stringsxml i get the unsupported content type error is there any way to solve this problemps if i open the xml files with open with text editor it is opening but i am unable to see the layout for mainxml and respective gui for stringsxml and androidmanifestxml,['android'] +126786,access all stored cookies i want to access my chrome stored cookies from the javascript console is this possible,['javascript'] +126799,where cookie is managed in phonegap app with jquery my native iphone app developed with phonegap with jquery so its browser based can log in to web server and once logged in users can access their resources the server sets session id in cookie once user is authenticatedi do not have any trouble with this scheme but i am wondering where the cookie is stored because when i do alertdocumentcookie it returns empty stringis it possible that ajax function in jquery manages the cookie internally and send it along for every request to the same domain,['jquery'] +126800,is accept threadsafe i am currently writing a simple webserver in c for a course i am doing one requirement is for us to implement a thread pool to handle connections using pthreadsi know how i would go about doing this roughlycalling accept in a main thread and passing the file descriptor to a fre thread however my friend suggested an alternate method than the one i had in mind creating all my threads up front and getting them all to loop forever on a call to accept the idea being that accept will block all the idle threads and when a connection comes in only giving the file descriptor to one then when a given thread is done with a connection it loops back around and blocks on a call to accept again using the call to accept as a semaphore essentially this would simplify the implementation quite a bit he figures as you wouldnt need to keep track of which threads are busy and which are ready for a connection it would also be lower latency in theory as the thread can immediately start executingmy question is is this safe i am planning to implement it and try it out but i am not ready yet and i am quite curious to know the answer i have searched on google and here on stackoverflow but could not find anyone doing it this way is accept thread safe i assume there will be more overhead with this approach as you are running all your threads all the time are the two approaches simply a simple memorylatency tradeoffedit i am unsure if this should be community wiki apologies if it should be i cannot find the button p,['c'] +126804,how can i make my qtip decide on his own to left or right tip atribute atooltipeachfunctionthisqtip content url includesqtipphpthisattrrel thisattrdiv textloading show delay 400 hide fixed true delay 200 position corner target bottomleft tooltip right style name light width 700 wich i love wen the tooltip item is on the right panel of my website but if not cannot see it completehow can i make it tooltipright when it is somewhere else i mean how can i know,"['jquery', 'css']" +126810,chromesafari not calling unload in some cases have been stuck with this issue for a few days now and really need and would appreciate some help my requirement is that i want to make a server side callback to clear off some objects when the user navigates away from our page without clicking logout for business reasons our aspnet session timeout has to be set to a very high value further i do not want to popup a alertdialog to force the user to return to the page and click logoffthe solution i have arrived at thus far is to make a ajax callback by embedding this javascript in the pagewindowonunload pageleave function pageleave alerttest pagemethodschecklogoutabcxyzonsucceedonfail here is the problem though for ie and firefox the unload fires the alert is seen and i see the callback on my c side in all the cases i desire a user closes browser b user types in a new url in the address bar c user clicks on a link causing page to reloadfor chrome and safari cases a and b work fine however when the user clicks on a link which causes my aspx page to reload my c side code is not invoked the javasacript alert is fired thoughi am trying to see how i can get chromesafari to behave like iefirefox is this even a possibilitythanks in advance for the helprajesh,"['javascript', 'asp.net']" +126829,should i use a cms if i can develop it myself i am learning drupal to save some production time for my websites but it looks like it is the other way around maybe it is because i am a beginner but i am seeing that i spend a lot of time trying to make drupal adjust to what i want and it is not saving me time at all maybe it comes with some ready to use stuff but the time required to set it up theme it etc it is actually bigger than the time i would need to code it and put it theream i just a cms noob or are these things overrated,['php'] +126835,android arrayadapteradd method not working the arrayadapteradd method is not working for me i am using eclipse helios 36 with adt plugin target source is a froyo 22 emulator and 22 htc evo 4g here is my java class import androidappactivity import androidosbundle import androidwidgetarrayadapter public class main extends activity override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain string entries list item a list item b arrayadapterstring arradaptnew arrayadapterstringthis rlayoutlist item entries arradaptsetnotifyonchangetrue arradaptaddlist item c and here is my layout for the list item list itemxmlxml version10 encodingutf8textview xmlnsandroid androidlayout widthfill parent androidlayout heightfill parent androidpadding10dp androidtextsize12sptextviewit is giving me and error in the logcat that says caused by javalangunsupportedoperationexception at javautilabstractlistaddabstractlistjava411 at javautilabstractlistaddabstractlistjava432 at androidwidgetarrayadapteraddarrayadapterjava178,['android'] +126862,android activity naming i am running into more and more naming clashes between android activities and other classes i was wondering if you could tell me how you avoid these sadly my particular naming problems are not covered in the related questions on sofirst examplei have an activity that thisplays a level of the game however the data required for that level background artwork entities etc is stored in a separate class naturally i would call the latter class level however i would call the activity level as well because it thisplays levelssecond examplei have an activity that plays back a cut scene it basically thisplays several images in a row the information which image is shown for how long is stored in a separate class as in the previous case i would naturally call both classes cutscenehow would you solve these naming issues name the activities levelactivity and cutsceneactivity name the representation classes levelmodel and cutscenemodel something else,['android'] +126863,rupee symbol in mail i am using php mailer to send mails to my clients i need to insert the rupee symbol in the body of the mailshow can i do this,"['php', 'html']" +126869,trycatch oneliner available just as you can convert the followingvar tiffoo bar t a else t bintot foo bar a b i was wondering if there is a shorthand oneline way to convert thisvar ttry t somefunc catche t somethingelseis there a method of doing this in a shorthand way preferably an oneliner i could of course just remove the newlines but i rather mean something like the thing for ifthanks,['javascript'] +126871,how do i align columns in thead and tbody when tbody css thisplay attribute is block i have a table with thead tbody and tfootthe css value for thisplay is block enables adding a scrollbar to the body and scroll the rows while the thead and tfoot stay in placethe td tags widths are not fixed as the tables width changes according to the width of the tdi would like to align the theads th tags with the tbodys td tagshow can this be donecss or jqueryeditthe target browser is google chrome and adding a slight twist the table is rtlthe csstbody thisplay block overflow autothead tfoot thisplay blockthe html table captionmy tablecaption thead trthcol1ththcol2thtr thead tbody trtdcell11tdtdcell12tdtr trtdcell21tdtdcell22tdtr trtdcell31tdtdcell32tdtr trtdcell41tdtdcell42tdtr trtdcell51tdtdcell52tdtr trtdcell61 is widetdtdcell62tdtr tbody tfoot trth6 rowsthththtr tfoot tableyou can try it using this jsfiddlethanks and be happy,"['jquery', 'html', 'css']" +126897,finding the source of format errors when using python logging when i have lots of different modules using the standard python logging module the following stack trace does little to help me find out where exactly i had a badly formed log statementtraceback most recent call last file usrlibpython26logging init py line 768 in emit msg selfformatrecord file usrlibpython26logging init py line 648 in format return fmtformatrecord file usrlibpython26logging init py line 436 in format recordmessage recordgetmessage file usrlibpython26logging init py line 306 in getmessage msg msg selfargstypeerror not all arguments converted during string formattingi am only starting to use pythons logging module so maybe i am overlooking something obvious i am not sure if the stacktrace is useless because i am using greenlets or if this is normal for the logging module but any help would be appreciated i would be willing to modify the source anything to make the logging library actually give a clue as to where the problem lies,['python'] +126907,how to count identical string elements in a ruby array i have the following array jason jason teresa judah michelle judah judah allisonhow do i produce a count for each identical element wherejason 2 judah 3 allison 1 teresa 1 michelle 1or produce a hash wherewhere hash jason 2 judah 3 allison 1 teresa 1 michelle 1,['ruby'] +126926,how to edit csproj file when i am compiling my csproj file using net framework 40 msbuildexe file i am getting an error lable01 not found in the current context of website01csprojactually i need to add every aspnet page with its code behind files reference i done it its working fine but the above error is pendinghope it mean that i need to add form name lable01 in that csproj file but i do not know the syxtax anybody please do provide me with the syntax to add form name in csproj file,"['c#', '.net', 'asp.net']" +126957,rails how to use a helper inside a controller while i realize your are supposed to use a helper inside a view i need a helper in my controller as i am building a json object to returnit goes a little like this def x comments arraynew c commentseach do comment comments id commentid content html formatcommentcontent end render json commentsendhow can i access my html format helperthanks,['ruby-on-rails'] +126977,how can i set a bounding area for my dragable object in javascript i am making a drag and drop javascript engine i learned how to set a bounding box as the parent element however now i wish to set the bounding box to any parent of any parent or as the entire page boundlessright now my javascript engine looks like javascript documentvar dragobjdocumentaddeventlistenermousedown down falsefunction downevent ifeventtargetclassnamesearchdrag dragobj makeobjeventtarget dragobjelementstylezindex100 documentaddeventlistenermousemove freemovement false function freemovementevent if typeofdragobjelementmouseup undefined documentaddeventlistenermouseup drop false prevents redundantly adding the same event handler repeatedly dragobjelementstyleleft mathmax0 mathmineventclientx dragobjposx dragobjboundx px dragobjelementstyletop mathmax0 mathmineventclienty dragobjposy dragobjboundy pxfunction drop dragobjelementstylezindex1 documentremoveeventlistenermousemove freemovement false documentremoveeventlistenermouseup drop false alertdebug dropfunction makeboundlessobje var obj new object objelement e objboundx eparentnodeoffsetwidth eoffsetwidth objboundy eparentnodeoffsetheight eoffsetheight objposx eventclientx eoffsetleft objposy eventclienty eoffsettop return objfunction makeobje obj new object objelement e objboundx eparentnodeoffsetwidth eoffsetwidth objboundy eparentnodeoffsetheight eoffsetheight objposx eventclientx eoffsetleft objposy eventclienty eoffsettop var curleft curtop 0 if eoffsetparent do curleft eoffsetleft curtop eoffsettop alerteid einnerhtml ifeclassnamesearchbound objboundx curleft objelementoffsetleft objboundy curtop objelementoffsettop return obj while e eoffsetparent return objfunction findposobj donated by lwburk on stackoverflow var curleft curtop 0 if objoffsetparent do curleft objoffsetleft curtop objoffsettop while obj objoffsetparent return x curleft y curtop my css is as followscharset utf8 css document padding 0px margin 0pxdrag position absolute webkituserselect none mozuserselect none userselect nonebound position relativesquare width 100px height 100px background red cursormovecenter width 500px height 300px margin auto margintop 50px backgroundcolorc textalign center borderradius 25px mozborderradius 25pxbox backgroundcolor ff3 height 278px borderradius 0 0 25px 25px mozborderradius 0 0 25px 25px opacity 05and my html is pretty cleandiv idcenter h1hello world hr h1 div idbox classbound p classdrag square one p p classdrag square two p divdivi have attempted to make the proper functions multiple times i will give one that i have made which does not work and i will list whyif it does not have bounds i set the default bounds as the parent element because i do not know how to set bounds as the entire pageif one of the parent elements is a bound then i am not setting the bound coordinates correctly again i do not know howoh and i set the bounds while i create the drag objectjavascript creation functionfunction makeobje var obj new object objelement e objboundx eparentnodeoffsetwidth eoffsetwidth objboundy eparentnodeoffsetheight eoffsetheight objposx eventclientx eoffsetleft objposy eventclienty eoffsettop var curleft curtop 0 if eoffsetparent do curleft eoffsetleft curtop eoffsettop alerteid einnerhtml ifeclassnamesearchbound objboundx curleft objelementoffsetleft objboundy curtop objelementoffsettop return obj while e eoffsetparent return objwhat is the correct math for setting the bounding box and why can i get rid of the position relative in the bound class can i make drag class not position absolute i know all of these things will probably greatly affect how the bounding function is written if i had to choose between having the drag class or the bound class not need a certain type of position i would choose that the bound class be set to any kind of positioningthank you all for reading and helping it means a lot to me i am a full time boarding high school student with very little free time editi should note that i am on my tenth day of learning javascript or fifteenthhour depending on how you look at it and i would like to learn the language before i start using libraries like jquery this engine is an academic exercise i have made for myself for the sake of knowledge and learning the language,"['javascript', 'html', 'css']" +126989,using jqueryui sortable list with forms i am using jqueryui to create a sortable list and the ui part works great in that i can sort the items as desired on the web page i cannot figure out though how the order of the sorted list is included in the post i am a total noob with javascript so please forgive me if this is really simplehere are the relevant portions of my htmlscript typetextjavascript googleloadjquery 1 googleloadjqueryui 1 function onload sortable sortable axis y containment ballot scroll false sortable thisableselection googlesetonloadcallbackonloadscriptform methodpost actionvoteinput typehidden namekey value electionkey input typehidden nameuuid value uuid div idballot classcenterol idsortable classrankings li classrankingjamieli li classrankingjoanieli li classrankingmorleyli li classrankingfrankli li classrankinglarrylioldivformhow can the order of jamie joanie morley frank and larry be encoded in the post,['javascript'] +126991,line breaks not thisplaying in view i have persondescription with the following stored in the databasejnklfdsfdsffdsffsdfdsfs fds fd sf sdf ds how do i thisplay this with the linebreaks in the view it is currently thisplaying all on one line and i do not understand why,['ruby-on-rails'] +127016,should we use php5memcache or php5memcached when connect with memcached server in php there are 2 modules that can be used when programming with memcachedmemcache and memcachedin the document it said that php5memcached using libmemcached to connect memcached and there are more function available in php5memcached modulewhich one should i choose,['php'] +127043,add html content to document associated with jtextpane i have a question regarding some simple console i am making i know that it is possible to add html content to jtextpane with function settext with previously set setcontenttypetexthtml but for the needs of my application i need to work directly with javaxswingtextdocument which i get with getdocument functionfor example for removing the lines and appending the new ones yes it is kind of console i am making and i have already seen several examples in previous stackoverflow questions but none of them serves my needs so what i want is insert the html to the document and have it correctly rendered on my jtextpane the problem is when i add html content with insertstring methodwhich belongs to the document jtextpane is not rendering it and in output i see all the html tags is there any way to get this working correctlythat is how i insert the texttext panel new jtextpanetext panelsetcontenttypetexthtmldocument document text panelgetdocumentdocumentinsertstringdocumentgetlength line nulltext panelsetcaretpositiondocumentgetlengththanks in adavanceserhiy,"['java', 'html']" +127044,jaxb how to make jaxb not to unmarshal empty string to 0 i have a dto class with a field such as xmlattributenotnullprivate integer number nulli am trying to unmarshal xml such as number i need the nuber field to stay null so that a validation exception would be thrown instead jaxb unmarshals it as 0 how can i make it to behave correctly,['java'] +127055,which mysql datatype to use for an ip address possible duplicatehow to store an ip in mysql i want to get the ip address from serverremote addr and some other server variables which datatype is the right one for thisis it varcharn,"['php', 'mysql']" +127091,c create instance of the derived class in the base class i have the following set uppublic abstract class a public void f want to make an instance of b or c here a borc new public abstract void f2public class b a public override void f2 public class c a public override void f2 is this possible if so howedit borc needs to be the type of the particular derived class f is called from,['c#'] +127095,basic types to expose on a c api i am targeting windows but i do not see any reason why some api code i am writing cannot use basic c types what i want to do is expose methods that return strings and ints in the c world i would just use string and have a unicode string but in vc i have got the option of using stdstring stdwstring or mfcatl cstringsshould i just use stdwstring exclusively to support unicode or can i use stdstring which would be compiled to unicode based on my build settings i am leaning toward the latter i would prefer to provide getitemascstring methods on my objects for other string typesalso should i be using size t instead of integerthe api is going to be used by me and perhaps a future developer working on the c gui it is a way to separate concerns my preferencesintuitiveness for other developersforward compatibility with vccompatibility with other c compilersperformance this is a lesser concern for me but need the startup time for rest of my appany guides would be appreciated,['c++'] +127099,how to get all defined css selectors for a given dom element how to get all defined css selectors for a given dom element using jquerywith defined i mean all css selectors which are used in any of the stylesheets applied to the documentin a way this is similar to the feature implemented by firebug where in it shows all the applied css selectors for a selected dom elementany help is appreciated,"['javascript', 'jquery']" +127109,stack around the variable was corrupted void gameboardenterships char location1 int ships 0 int count 1 whileships num ships cout enter a location for ship count cin location cout endl gridlocation0location1 ship ships count im writing a battleship game i have the board layouts working and the computers randomly generated ships now i am working on this method to prompt the user to enter coordinates for the ships when i run the program it allows me to enter 5 ships when i enter the 6th ship it gives me this errorstack around the variable location was corruptedive looked for answers online and have not found anything exclusiveany help would be appreciated,['c++'] +127121,how to use razor syntax in aspnet web application not mvc how does one create a cshtml page in an aspnet web application the option to choose razor is obvious when using mvc it appears when adding a view but i cannot seem to figure out how to accomplish this in a plain aspnet web application is it even possible,['asp.net'] +127138,undefined method user path i am trying to construct a users model manually without using resources users in the routesrb file my routesrb file looks like thismatch usersid to usersshowmatch all users to usersindexthis is my index method in the users controllerdef index title all users users userpaginatepage paramspageendthis is my index viewh1all usersh1 will paginate ul classusers userseach do user li link to useremail user li end ul will paginate i get this error message when i hit localhost30all usersundefined method user pathi do not see where this is coming from can anyone helpeditok i have thiscovered that changing user to user in the view makes it work link to useremail user but i really do not understand the error message or the real difference between user and user plus clicking on the link created does not redirect to the users page it stays on localhost30all users,['ruby-on-rails'] +127157,iframe back button i searched a lot to get rid of this problem on the internet but could not find a specific solution despite the problem being thiscussed in details previouslythe query is simple my javascript dynamically adds an iframe to the web page which thisplays a feedback form the problem is that after answering now when the user clicks the backbutton of the browser the iframe instead of the browser window is affected ie the questionnaire is thisplayed again i want the browser back button to behave normallythis behavior is really annoying and i am having real trouble fixing thisi am using firefox looking forward to the replies please inform me if i should give more detailsthanks,['javascript'] +127161,how to rename a resource in visual studio okay i have never done win32 programming before and i have a question that seems fairly stupidhow do i rename idr menu1 to for example idr main menu i tried everything could not find a way,['c++'] +127178,is it possiblesafesane to pass around a function pointer to a static function letas say i only want to expose a function from one of my files by passing out a function pointer to that function is it safe to declare that function as static are compilers allowed to do any judo that would invalidate my function pointer or make it meaningless outside the context of that file since the function is declared as specific to that filenot my code but a silly example of what i meanvoid static cool functionvoidvoid extern cool function ptrvoid actually iam not sure of where the extern goes in a function pointer declaration damn you confusing functionpointer syntaxgiven that code or the syntactically correct approximation thereof would it be illegal to access cool function ptr from another file,['c'] +127234,assign pass to a function in python i have a piece of code that defines a function that takes a function as an argument like sodef stuffn f fnnow i want to provide some default value of f that does nothing so i figured i would use pass like sodef stuffn f none iff is none f pass fnbut this does not compile how should i be doing this,['python'] +127240,how can i access localisable strings for standard ios system terms eg favorites more i do not know if my approach to this is fundamentally wrong but i am struggling to get my head around a seemingly trivial localisation issuei want to thisplay the title of a system uitabbaritem more favorites featured etc in a navigation bar but where do i get the string from the strings file of the mainwindownib does not contain the string i did not expect it to and reading the title of the tabbaritem returns nil which is what stumped mei have been told there is no way to achieve it and i will just have to add my own localised string for the terms in question but i simply do not want to believe that that is maybe easy enough in some languages but looking up say more in already presents me with more than one possible word in some languages i am not happy about simply sending these words for translation either because it still depends on the translator knowing exactly which term apple uses so am i missing something simple here what do other people doobviously setting the system language on my test device and simply looking to see what titles the tab items have is another obvious possibility but i really have a problem with half backed workarounds like that thatll work for most languages but i am really gonna have fun when it comes to russian or japanesei am convinced there must be a more reliable way to do this surely there must be a strings file somewhere in the sdk that has these strings definedthanks in advancerich,['ios'] +127243,how to design and create a gridview using uiscrollview or uitableview i think gridview is a very common view in many situation as a beginner in ios i just wonder why ios did not provide a gridview claso heres my question how to design and create a gridview using uiscrollview or uitableviewor is there some other solution to create a gridviewthanks for your answers,"['objective-c', 'ios']" +127249,how to set a switch statement in while loop in java i want to do a switch in while loop where at the break of every switch statement the while loop stops and ask for an input like f r c q the statement below works but the statement does not break please helppublic static void mainstring args throws ioexception start both with 1 point int goodtotal 50 int montotal 50 input switch statement while goodtotal 0 montotal 0 systemoutprinttype a letter systemoutprintlnn systemoutprintf go out and fight systemoutprintlnn systemoutprintr rest systemoutprintlnn systemoutprintc check stats systemoutprintlnn systemoutprintq quit int input systeminread systemoutprintlnyou typed char input switch input case f systemoutprintlncontinue the game break case r systemoutprintlnplayers should rest break case c systemoutprintlnchecking the status of the game systemoutprintgoodman has goodtotal points and monster has montotal points systemoutprintlnn break case q systemoutprintlngame over systemexitinput break default systemoutprintlninvalid selection break set value of minimum and maximum damage int mindmg 2 int maxdmg 15 get random number int damage mindmg doublevalueofmathrandom maxdmg mindmgintvalue int damage2 mindmg doublevalueofmathrandom maxdmg mindmgintvalue remove value of damage from started value to get total value remaining goodtotal goodtotal damage montotal montotal damage2 print message if still in the game if goodtotal 0 systemoutprintlngoodman has goodtotal points left not bad man if goodman survives round 2 print a message of encouragement if goodtotal 0 count 1 count 2 systemoutprintthis is encouraging goodman has lasted past roundhh count print new message if goodman passes round 3 else if goodtotal 0 count 3 systemoutprintgoodman is as strong as samson he has lasted round count and still looks strong systemoutprint 10 hit points has been added to your total if montotal 0 systemoutprintlnwait monster has a total of montotal points and is still in the game exit if have less than 0 point and print game over congratulate the winner if goodtotal 0 systemoutprintlngoodman you are out of the game systemoutprintlnthe monster will take over the village this is sad systemoutprintlngame over else if montotal 0 systemoutprintlngoodman has been victorious systemoutprintlnthe monster is dead the people live systemoutprintlngame over systemoutprintlnthis is the end of round count systemoutprintlnn count count 1,['java'] +127264,how can i rightalign the contents of a extjs tbar i have a tbar inside a grid panel like thisthis is the code that produces itvar grid new extgridgridpanel region center style margin 10px store new extdatastore data mydata reader myreader title testing tbar filters width 100 xtype combo mode local value en triggeraction all forceselection true editable false fieldlabel produkt name language hiddenname language thisplayfield name valuefield value store new extdatajsonstore fields name value data name german value de name english value en name french value fr what do i need to change so that the dropbox is rightaligned instead of leftalignedaddendumthanks dogbane that works perfectly heres how i right aligned both text and dropdowntbar xtype tbfill filters width 100 xtype combo mode local,['javascript'] +127268,any java ide which can quickly establish a local project based on a remote jnlp file for instant debugging given a remote jnlp which works all jars are available etc but you need to run a debug session on the codeis there any facility that easily allows you to create a local project in any reasonably modern ide which consists of a local copy of the resources stated in the jnlp and can run said code in debug mode assume that a decompiler is available so it is just a matter of getting the debug session runningare there any ides eclipse netbeans intellij jdeveloper etc etc even a commercial offering which can do this just given the jnlp url,['java'] +127270,switch expression cannot be float double or boolean why does not the switch expression allow long float double or boolean values in java why is only int and those that are automatoically promoted to int allowed,['java'] +127272,javascript locationhref to open in new windowtab i have a javascript file from a third party developer it has a has link which replaces the current page with the target i want to have this page opened in a new tabthis is what i have so farif command lightbox locationhref hourindexphptypeindividualcan anyone help me out,['javascript'] +127274,get the current time in c i want to get the current time of my system for that i am using the following code in ctime t nowstruct tm mytime localtimenow if strftimebuffer sizeof buffer x mytime printftime1 sn bufferthe problem is that this code is giving some random time also the random time is different everytime i want the current time of my system,['c'] +127282,print a webpage to pdf document using php i can see there are a few options for doing this my question is does any one know of a way that i can simply pass a php web page into a pdf creator and it outputs exactly the same as if it was viewed via a browser taking into consideration css images and php functions etcthanks,['php'] +127288,javascript jquery radio button click i have 2 radio buttons and jquery runninginput typeradio namelom value1 checked firstinput typeradio namelom value2 secondnow with a button i can set onclick to run a function what is the way to make radio buttons run a function when i click on one of them,"['javascript', 'jquery']" +127289,spring roo field enum i am new to spring mvc and spring roowhat is field enumhow can i enumerate all allowed valuesis it implemented using lookup table or check constraint,['java'] +127300,how to get list of mongodb databases and collections list from a ruby on rails app i am using rails 3 and mongoid gem but i need to fill a combobox with the list of mongodb databases in mongodb shell we can list databases with show dbs command also there is getdbnamelist and dbgetcollectionnames commands in mongodb drivers but i could not figure out how to use these commands from a ruby on rails appalso i wonder if i can get databases and collections list with using mongoid gem because i am sure that i had read that mongoid supports using more than one database but i think it was model dependentso what do you think is there any solution or i have to use mongorubydriver gem not mongoid,['ruby-on-rails'] +127319,standard method for mysqls if function i have found mysqls if function to be very useful in giving me an efficient way to do conditional aggregate functions like thisselect sumifsomethinga something weight 0 as a sumsomething weight as all fromit is my understanding that this function is a feature of mysql and is not generally available in databases that use sqlis there a more standard method to achieve this functionality on the database side of things,"['mysql', 'sql']" +127336,swing with guice i am already using guice for the data model of my app and so far i am quite happy with it however the gui part is about to become a big ball of mud i find it hard to use guice here because swing components and models are tightly coupled and often force a certain initialization order my application consists basically of a header with a lot of filters a central and quite complex jtree component and a lot of actions eg from a jpopup menus dialogs wizards etc the main problem is that i have a lot of coupling between the components and actions eg complicated validations tree updates could you give me some advice how to structure that gui with guicei am aware of libs like guts but the documentation is really thin i would rather avoid to add another dependency to my project and to learn another api eg i do not know the swing application framework,['java'] +127337,how can i remove the badge number if i click on close button in push notification i am working with push notifications when i get a notification it comes with 2 button view and close if i click on view it opens the app and when i click the close button it does nothing but a badge number appears on the app icon then when i open my app again that badge number should thisappear but it does not how can i remove that badge number if user clicks on app icon thanx,"['iphone', 'objective-c']" +127351,orgeclipseswtswtexception widget is thisposed from table refresh the app is an eclipse 36 based rcp so jface version 352 running on windows 7i have a custom view class that contains a tableviewer and calls refresh on it sometimes but not very often it results in the stack trace below it is called from within the ui thread i suspected the problem was with other code that changes the backing list to the table but that any code that does this is also run in either a syncexec or asyncexec method so i do not understand how it could be a synchronisation issue between the changing of table items and the refresh of the viewerany ideas what i can do to prevent this happeningentry orgeclipsejface 4 2 20101020 092206140 message problems occurred when invoking code from plugin orgeclipsejface stack 0 orgeclipseswtswtexception widget is thisposed at orgeclipseswtswterrorswtjava3884 at orgeclipseswtswterrorswtjava3799 at orgeclipseswtswterrorswtjava3770 at orgeclipseswtwidgetswidgeterrorwidgetjava463 at orgeclipseswtwidgetswidgetcheckwidgetwidgetjava336 at orgeclipseswtwidgetswidgetgetdatawidgetjava521 at orgeclipsejfaceviewersabstracttableviewersetselectiontowidgetabstracttableviewerjava921 at orgeclipsejfaceviewersstructuredviewersetselectiontowidgetstructuredviewerjava1711 at orgeclipsejfaceviewersstructuredviewerpreservingselectionstructuredviewerjava1399 at orgeclipsejfaceviewersstructuredviewerpreservingselectionstructuredviewerjava1353 at orgeclipsejfaceviewersstructuredviewerrefreshstructuredviewerjava1455 at orgeclipsejfaceviewerscolumnviewerrefreshcolumnviewerjava537 at orgeclipsejfaceviewersstructuredviewerrefreshstructuredviewerjava1414 at orgeclipseswtwidgetssynchronizersyncexecsynchronizerjava179,['java'] +127359,where would i find detailed info about implementing closures like in javascript or scheme i am quite familiar with compiler theory in general and with the runtime environments of traditional procedural and objectoriented languages such as c pascal and java i am looking to gain a detailed understanding of how the runtime structure of a language like javascript is implemented specifically as related to closures how is the storage managed when are the closures allocated how it decides when to free the closure storage short of digging through the source code for v8 or rhino can you point me at papers or books or tutorials that can provide such a descriptionthanks,['javascript'] +127366,one javascript file per page or combine when using jquery and document ready function ok so i know it always depends on the situation but i have thus far combined my jquery filesplugins into a single compressed filenow i am wondering what i should do with my page specific jsjquery code should i have a single file with one documentready function and my entires sites js code inside of it or split it up into seperate js files per page with a document ready call in eachthese files will inclide things such as click handlers and other jquery code specific to certain pageswhats the best practice here to optimize load times and maintainabilty,"['javascript', 'jquery']" +127386,rails actionmailer how to send an attachment that you create in rails3 w actionmailer i want to send a txt file attachment the challenge is this txt file does not exist but rather i want to create the txt file given a large block of text that i havepossible ideas thanks,['ruby-on-rails'] +127390,add a column if it does not exist to all tables i am using sql server 20052008 i need to add a column to a table if it does not yet exist this will apply to all tables in a given database i hoped i was close but i am having issues with this solutionhow can this be doneheres what i haveexec sp msforeachtable declare tblname varchar255 set tblname parsename1 if not exists select column name from information schemacolumns where table name tblname and column name createdon begin alter table tblname add createdon datetime not null default getdate endbut i get errorserror 102 incorrect syntax near tblname incorrect syntax near createdon incorrect syntax near tblname incorrect syntax near createdon and so on for each table,['sql'] +127396,manage dns server by c code i need some sample code to createdelete zone and a record in microsoft dns server by c,['c#'] +127398,use xpath to find xml nodes with a specific child element i am new to the world of xpath i am wanting to take an xml approach to powering my simple portfolio website instead of a database which in this case would be superfluous as the only database element would be the projects themselvesi have authored an xml file with the following structurexml version10 encodingutf8 projects project titleamerchanthisetitle slugamerchanthiseslug projecttypeecommerceprojecttype launchdate20070801launchdate project now i can parse this xml file fine with php for a listing overview but how do i go about filtering projects with xpath for example how do i obtain all project nodes that has a child projecttype node with the value ecommercenormally i would run a sql query likeselect from projects where category ecommercewhat would the xpath equivalent be is my xml file in the right structure to accomodate this filteringany pointers would be great thanks in advance,['php'] +127405,load a static file in a spring controller i am pretty new to spring so apologies if i do not see the obvious answer here i set up small demo project with a spring mvc controller and deployed it to app engine in my controller i would like to read the content of a static file into a string whats the best way of doing thati googled a bit but i am probably searching for the wrong thing i tried the below but it does not workcontrollerrequestmappingmycontrollerpublic class mycontroller requestmappingvalue test method requestmethodget public responsebody string mytest filereader filereader null bufferedreader bufferedreader null string content try filereader new filereaderfilewebinfcontentsomecontenttxt bufferedreader new bufferedreaderfilereader content bufferedreaderreadline bufferedreaderclose catch exception ignored ignore return content any push into the right direction will be highly appreciated,['java'] +127409,c vs c in embedded linux i am developing an application for embedded linux arm it will execute 500 timessec therefore speed is important i would prefer to use c but i am afraid it will be slower than c even if i avoid fancy features like virtual functionsis there a reason to use c or it is just as fine to write in c,"['c++', 'c']" +127418,how can i access directorylocal variables in my major mode hooks i have defined a dirlocalsel file with the following contentpythonmode crvirtualenvname saasin my emacs i have the following function to retrieve this value and provide a virtualenv pathdefun crvirtualenv cond crvirtualenvname format ss virtualenvbase crvirtualenvname getenv emacs virtual env getenv emacs virtual env t emacsdpythonfinally in my pythonmodehook list i have this hook functionaddhook pythonmodehook crpythonmodeshellsetupdefun crpythonmodeshellsetup message virtualenvname is s crvirtualenvname let pythonbase crvirtualenv cond and fboundp ipythonshellhook fileexecutablep concat pythonbase binipython setq pythonpythoncommand concat pythonbase binipython setq pypythoncommand concat pythonbase binipython setq pypythoncommandargs colors nocolor t setq pythonpythoncommand concat pythonbase binpython setq pypythoncommand concat pythonbase binpython setq pypythoncommandargs nilwhen i open a new python file the message logged by crpythonmodeshellsetup indicates that crvirtualenvname is nil however when i ch v the name i get saas insteadobviously there is a load order issue here is there a way to have my mode hook statements respond to directorylocal variables,['python'] +127425,converting c razor to vb i am following the aspnet mvc tutorial and having started in vbnet i am having trouble converting the following razor codei have gotul for each g as mvcapplication1genre in model li gname li nextulbut getting attribute sepcifier is not a complete statementon both the li tags i understand i need to use line continuation but cannot figure out where i would be greatful if you can point out the problem,['asp.net'] +127434,getting a canvascontexts last points coordinates i want to create an arrowto function with canvasrenderingcontext2dprototype to do that i need to get the coordinates of the last point eg var ctx somecanvasgetcontext2dctxmoveto1040the coordinates of the last point are now 1040ctxlineto5050and now it is 5050how can i retrieve them,['javascript'] +127436,how to center text inside a li element inside an unordered list this list is working great for me but the text within the li elements is not centeringthe lis must auto resize to their contentnavmenu fontfamily verdana arial helvetica sansserif height 30px backgroundimage urlimgmenu bgpng backgroundrepeat repeatx borderbottom dotted thin 6 bordertop dotted thin 6 textalign center width 800pxnavmenu ul liststyle none padding 0 margin auto 0navmenu li float left borderright dotted thin 6 liststyle none padding 05em 2em 05em 075emnavmenu li a lineheight 15em color 3 textdecoration none fontsize 12px fontweight bold thisplay blockdiv idnavmenu ul li classcurrent page itema href titlehomehomea li classcurrent page itema href titlehomehomea li classcurrent page itema href titlehomehomea li classcurrent page itema href titlehomezxczczxczhomea uldiv,['css'] +127448,paypal api for ios allowed is apple ok with the use of paypal api in an ios app for selling goods and servicesany experience i have been reading the inapp purchase and it applies only to digital content,['iphone'] +127468,how can i update value of input text via ajax i want to have an input text box that i can update its value with ajax call get current revision and then another button update code base to make another ajax call the value in the text boxi do not know how to combine all this togetherform actionupgagephp revision input typetext namerevision value br input typesubmit valueupdate code base input typesubmit valueget current revision formi would like to use only javascript not jquery,['javascript'] +127469,how can i configure the maven shade plugin to include test code in my jar i use the shade maven plugin to build my project so that all of its dependencies are included in one jar this makes it easier to run it on hadoop shade seems to exclude my test code by default which is understandable since i would like to run integration tests against my cluster i am hoping to setup another profile to build a separate jar for this purpose is there any way to configure this plugin to also include test code,['java'] +127478,backbonejs vs javascriptmvc vs knockoutjs i want to use a javascript framework for a complex web application i have been looking at backbonejs knockoutjs and javascriptmvc being pretty new to client side javascript heavy web apps i am not sure which one to pick each one has a pretty different approach to separate the concerns modelviewcontroller vs modelviewviewmodel vs modelviewcollection what do you guys think what are the deciding factors which one would be the easiest to pick up what has your experience been like,['javascript'] +127486,jqueryuispinner change i am trying to use the latest version of the jqueryuispinnerjs the spinners are showingup and updating the textboxes but i am having trouble figuring out how to capture the change event it triggers when you manually change the value in the textbox but not when you use the spinner arrowsjquery inputnameopeningspinner min 0 max 100 doorsize6w7hfspinnerchangefunction alertthisspinnervalue htmlinput typetext value0 classfront iddoorsize6w7hf nameopening00,['jquery'] +127519,replace string in a text file in nodejs i am using nodejs i want to read a file with some placeholder strings and replace them dynamically before i serve the file this is not an html file so a templating engine will not workhow can i do this,['javascript'] +127524,javascript setinterval this is an example from a tutorial about setinterval but it doesnt explain it sufficiently for my newbie brain i would appreciate if you could answer these questionsi does the 10 millesecond timer mean that moveelement function will be triggered every second in other words after it has run it will wait 1 second and then run it againii is the purpose of moveelement to move the redbox 10 pixels to the left each time it runs is that why px is used in the functioni after moveelement runs for the first time does the new value for x x10 replace the value of 0 in var x0 ie does it get stored outside of the function in the variable x at the top of the programvar x 0setintervalmoveelement10function moveelement x10 var left x px documentgetelementbyidredboxstyleleftleft,['javascript'] +127531,python mock a module without importing it or needing it to exist i am using starting to use a python mock library for my testing i want to mock a module that is imported within the namespace of the module under test without actually importing it or requiring that it exist first ie throwing an importerrorsuppose the following code existsfoopy import helpers def foo func return helpershelper functhe goal is to test foo func when helperspy does not exist anywhere and if it does exist act as if it does not first try using the super cool patch decoratorfrom mock import patch sentinelimport foopatchfoohelpersdef foo testmock mockhelper funcreturn value sentinelfoobar assert foofoo func sentinelfoobarthis works if the helpers module can be imported if it does not exist i get an importerror next attempt with patch sans decoratorfrom mock import patch sentinel mockimport foohelpers mock patchfoohelpershelpers mockstartdef foo test helpers mockhelper func mockhelper func helpers mockhelper funcreturn value sentinelfoobar assert foofoo func sentinelfoobaragain this does not work if helpers is missing and if it exists the assertion fails not really sure why that happens third attempt current solutionimport syshelpers mock mocknamehelpers mock spechelper funchelpers mock name helperssysmoduleshelpers helpers mockimport foodef foo test helpers mockhelper funcreturn value sentinelfoobar assert foofoo func sentinelfoobarthis test passes regardless of whether or not helperspy existsis this the best way to accomplish this goal does the mocking library i am using provide an alternative to this what other ways can i do this,['python'] +127588,capybara assert attributes of an element i am using rspec2 and capybara for acceptance testingi would like to assert that link is thisabled or not in capybara how can i do this,['ruby-on-rails'] +127590,enterprise library pros and cons i am developing a complex business application wherein there will be a data access layer as of now we have two options either to create our own custom data access layer or to use a microsoft inbuilt library i am looking for some basic reasons to go with either option any reply will be highly appreciated,"['c#', 'asp.net']" +127614,what can cause hs err pid file not to be created on crash i need to investigate crashes of a java client application it is s swing application running in java web start environement on java se 6 update 23 on windows unfortunately for some crash cases the hs err pid file was not created it was not on the desktop so i have searched for it on pc and did not find itthere was an old hs err pid file on the desktop for the same application so it is reasonable to assume the new one should have been created there too there is no exception in the log in the end as it usually happens when jvm crashes on java exception so it looks like a crash that should result on creation of hs err pid filedo i need to configure something to make it work can the configuration of dr watson affect the creation of hs err pid filethankswe configured dr watson and analyzed the core dump file which was created after the app crashed again the error i saw was access violation from the stack trace i was able to see that the crash is caused by exception in a native code of a third party we use this was enough to delegate the issue to them bottom line1 some java crashes are not handled as expected by jvm so that hs err pid file is not created2 configuring os to create a core dump can help in those cases as the crash that is not handled by jvm will be handled by the os youll get less information in this case still it can be helpful,['java'] +127624,is there any javascript function in some library for turning simple wiki mark up given as multi line string into html what i generally need is simple opensource library with function that will turn given wiki mark up string into html if you can write such function please post it here it shall be tolerant to html objects inserts like youtube videos mathml and tex inside that string much alike mathstackexchangeso is there any such function in some javascript libraryhere is a little sample example to try onheader 1header 2 header 1 header 2 header 6header1 header1 iframe src width400 height225 frameborder0iframepa hrefdrawing inspirationa from a hrefwesley louisa on a hrefvimeoapiframe titleyoutube video player width640 height390 src frameborder0 allowfullscreeniframe abacus answer bubbles 1 bunk 2 bupkis belittler 3 burper cunning,"['javascript', 'html']" +127632,how do i create a hashcode in net c for a string that is safe to store in a database to quote from guidelines and rules for gethashcode by eric lippertrule consumers of gethashcode cannot rely upon it being stable over time or across appdomainssuppose you have a customer object that has a bunch of fields like name address and so on if you make two such objects with exactly the same data in two different processes they do not have to return the same hash code if you make such an object on tuesday in one process shut it down and run the program again on wednesday the hash codes can be differentthis has bitten people in the past the documentation for systemstringgethashcode notes specifically that two identical strings can have different hash codes in different versions of the clr and in fact they do do not store string hashes in databases and expect them to be the same forever because they would not beso what is the correct way to create a hashcode of a string that i can store in a database please tell me i am not the first person to have left this bug in software i have written,"['c#', '.net']" +127638,changing a c delegates calling convention to cdecl i have had this problem with c when i was using dotnet11the problem is this i have an unmanaged dll which has a function which takes a function pointer among other arguments when i declare the dllimport in c code i pass a delegate but the delegates in c have stdcall calling convention whereas the unmanaged function expects a cdecl function pointer thus my naive approach resulted in crashes then i found the following some guy wrote an excellent library that enables changing calling convention of the delegate by as i understood msilhacking things went well untili migrated to vs2008 and the new version of net under this version the abovementioned library does not work i am not really a c or net expert and to tell the truth i barely understand what his library does although it is opensource so i do not even want to try to adapt it to new net however i am hoping that newer version of c has some better solution available for my problem so so experts please help me with my pain in the buttocks,"['c#', 'c++']" +127639,good dry approach to rendering and ajax updating of page imagine a review site where users enter ratings and optionally short commentson each review page youve got many comments these are thisplayed in a table at the end of the page btw not looking for datagrid type controls far too simple for thati want to let users enter new reviews and update the page without a page refreshall simple stuff so far this is not the questionwhat is a good approach to generating for the page some thoughts generate the reviews html server side append new reviews using javascript client side downside is that youve got table html generation code in two placesupside more content on page as far as search engines concernedserver side only output reviews as jsonxmlwhatever and render html dynamically on page load using javasriptdownside template in javascript hard for designers to customize lack of content on pageis there an approach that combines the two methods ie a templating framework that will render existing data server side but also sends the template fragment client side so it can be reused there for additionseditswith 2 to get the data on initial page load would you a include jsonxml on initial page and run client side render on page loadb get it via a separate ajax call on page load simpler extra request and delayi am focused on jquerydjango but this question applies to other frameworks and ajax librariesthis is a bit of a subjective quesiton hope it does not step over the line thoughts,['jquery'] +127646,why does jaxb 2 ris xjc simple mode change collection names jaxb simple binding mode modifies collection names to their pluralversion eg additionaldata becomes additionaldatas is there any solution to change this behavior i need to have a java field name and methods name equal to xsd field name my bindings filexml version10 encodingutf8bindings xmlns xmlnsxsi xmlnsxjc xsischemalocation 2 0xsdversion21 globalbindings serializable uid1 xjcsimple globalbindingsbindings,['java'] +127650,portably safe to pass nullzero to dynamic cast out of habit for checking null pointers i have sometimes writtenmyclass c somebaseptr dynamic castmyclasomebaseptr 0if c in effect checking for a null pointer before passing to dynamic cast and also checking the returni then read in the msdn documentation a null pointer value is converted to the null pointer value of the destination type by dynamic castit appears then that i could remove the construct safely is this c portablesuch that the new code would bemyclass c dynamic castmyclasomebaseptrif c of course presuming that somebaseptr is either null or valid ie not wild pointing to garbage,['c++'] +127668,layout how to dynamically add views and break line based on empty space i would like to have a layout for views in android that manages itself to use its empty space dynamically and either puts the next view added right to the last view if it still fits or breaks line and adds the view on the new line on the leftexamplenamelongnameho superlongnamenextlongname bobsuemartinrichardjoe marvinhomerannmarie any clues thanks for your help,['android'] +127677,is there something like foreignkey in google app engines webapp i am using google app engine with their webapp framework is there something like djangos foreigkey in webapp ie i have a model and i want it to have a propertyfield that points at another model possible,['python'] +127701,sql count number of columns in all tables excluding views i am creating a query that returns the number of columns in each table but i want to exclude viewsthe following works but returns view resultsselect count table namefrom information schemacolumnsgroup by table nameany suggestionsnote mssql 2005,['sql'] +127706,python get datetime for 3 years ago today this must be a duplicate and documented but i cannot find the answer via googlein python how do i get a datetime object for 3 years ago todaythanksupdate fwiw i do not care hugely about accuracy ie it is feb 29th today i do not care whether i am given feb 28th or march 1st in my answer concision is more important than configurability in this case,['python'] +127708,how to read a value of an hard coded address in c i am looking to read the value that is located in address 302h the purpose is to read an input from hardware a part of a 104pc stack when i run the following code a get this error unhandled exception at 0x004134b9 in setoutputexe 0xc05 access violation reading location 0x0302include stdlibh define portbase 0x302int tmainint argc char argv int value int volatile port int portbase printfport dn port value port printfport value dn valueediti am running this under widows xp only documentation i can find on the board is beloweditfrom your answers below i can see that i need to write a driver for the board can someone point me to a resource on how to do so,['c++'] +127711,how to use scriptlet inside javascript can someone test this example and share the resultswhen i dovar myvar requestgetcontextpath alertmyvari get requestgetcontextpath removing the enclosing single quotes from requestgetcontextpath gives syntax errorhow can i use the scrptlet or expresion inside a js functionedit this link has an explanation that helped me,['javascript'] +127713,refactoring making a game engine more modular and how my game engine consists of a range of loosely coupled modules which can be loaded and unloaded some examples are the base module handling window management and responding to os events entity manager lua manager physics managerright now these modules are organized as namespaces and their state is defined through local variables in the respective source files each of the namespaces has an open close and update functionnow i do not really like the solution with namespaces anymoreit is not flexible enougheven if it might not be needed in reality having the plain ability of creating multiple instances of a module seems properit seems like i am not making use of oop here a module base class with a virtual update member function would sound more reasonableit is harder to ensure that when the module is closed and reopened all of the variables will be reset too a class with constructors and destructors would be easieryou cannot properly have the modules managed without explicitly calling open close and updateso my idea would have been to use classes for each of the modules derived from a module base class the module class instances would be handled by the modulemanager class which updates thembut the solution with oop brings up the problem of how the modules should communicate right now the base module told the console module to print something via consoleprinthow can i work around this problem without having to use something like g modulemanagergetconsolemoduleprinthow could this module manager work in detailand my final questiondo you have any further tips for me on the topic of writing a modular game engine in c with oopare there any design patterns that could help me in this situation or maybe even concrete reading material,['c++'] +127725,mysql join many to many single row i have 3 tables that i want to combine see below for detailsproductproductid name priceprod catproductid categoryidcategorycategoryid namejoinedproductproductid categorycategoryid productname productprice categorynameeach one though since a product can belong to more than one categorywhat i want to do is get each product with the categories that relate to them in a single query how would i got about this,"['mysql', 'sql']" +127727,concerning raii how to prevent errors caused by accidentally creating a temporary a while age a colleague told me he spent lot of time debugging a race condition the culprit turned out to be something like thisvoid foo scopedlockthismutex oops should have been a named object edit added the this to fix compilation issue in order to prevent situation from happening again he created the following macro after the definition of the scopedlock classdefine scopedlock error you should create a named objectthis patch works finedoes anyone know any other interesting techniques to prevent this problem,['c++'] +127729,integrating facebook authentication with existing aspnet membership coding platform aspnet 40 webforms with c we have a website with the existing login details managed by aspnet membership providernow client wants to add facebook connect to it so on registration i am giving a register using facebook buttonhow shall i proceed with integrating a successful authentication from facebook to my membership provider what i am planning is to create a username with unique identifier as a new user in aspnet membership and link that to another table that contains other openid userscos in future we plan to extend to google twitter live and all is that the best method,['asp.net'] +127762,rails 238 ruby 186 getting a visual call treegraph of what methods call what i have a mediumcomplex rails app the main controller the one that does what the app is there to do has a single action method it is not a standard restful app this is acting as an intermediary and there are external constraints on how it can be calledhowever it does have lots of methods and a number of filters and an evergrowing test suite the structure has changed considerably over time and i no longer have confidence that some of the mocha expectations that were set up for the tests written earlier are still appropriatethere are multiple people working on the app so i am constructing a cookbook for writing functional tests use these expectations and assertions when you want to ttest withwithout those side effects and so ona call treegraph would be extremely useful in composing such a document aside from the filters such could even be statically derived from the sources by something that knew about rails knoweverythingabouteverything model so maybe static is not such a good idea i have tried using rubyprof with my functional tests to get a call tree but all i get are trees relating to the test methods and parts of the kernel and rails and none of the controller methods at least not that i have found the profiling creates lots of little files instead of one big onethe failure to find the controller methods might be related to how the action method is invoked via send rather than some more normal mechanismblah blah blah just fyi on what i have tried so faris there a good tool to build a whocallswhat flow chartcall tree for a rails 238 appthanks,"['ruby-on-rails', 'ruby']" +127766,difference between restrictionslike and ilike in hibernate criteria api hibernates criteria api has restrictionsilike function which has the following contracta caseinsensitive like similar to postgres ilike operatorthat is cool but the same class also has like function having much more vague contractapply a like constraint to the named propertyexamplecriteria cr sessioncreatecriteriaemployeeclass to get records having fistname starting with zaracraddrestrictionslikefirstname zara case sensitive form of the above restrictioncraddrestrictionsilikefirstname zara,"['java', 'sql']" +127770,has boost library a gui i want to work on boost library and i was wondering an answer of question what gui of boost library is there any gui program for boost library and how can i integrate both of gui and boost to eachothersorry my english thanks your help,['c++'] +127776,loadingcreating an image into sharpdx in a net program i am trying to use sharpdx to create a simple mazelike 2d program using directxto that end i want to create bitmaps that i can render onscreen for the walls hallways outside of the maze etchowever i cannot seem to figure out how to either load an existing image file into the bitmap class in the sharpdx library or how to create a new such bitmap class from scratchsince all the classes are said to be mapped directly to directx types i guess this just means i need to learn more directx but i was hoping there was a simple example somewhere that could show me what i need to doif i have to construct a new bitmap from scratch and draw to it i can do that it is not difficult getting the pixels i need right however i cannot even seem to figure out that partdoes anyone have any experience with the sharpdx library and can give me some pointers,['.net'] +127778,issue creating a parameterized thread i am having problems trying to create a thread with a parameterizedthreadstart heres the code i have nowpublic class myclass public static void fooint x parameterizedthreadstart p new parameterizedthreadstartbar no overload for bar matches delegate parameterizedthreadstart thread mythread new threadp mythreadstartx private static void barint x do work i am not really sure what i am doing wrong since the examples i found online appear to be doing the same thing,['c#'] +127784,what does selfincludedbase do in ruby on rails restful authentication i thought we would dohelper method current user logged in authorizedto make these controller methods available for use as helper methods in views but in restful authentications libauthenticated systemrb i see inclusion hook to make current user and logged in available as actionview helper methodsdef selfincludedbase basesend helper method current user logged in authorized if baserespond to helper methodendwhy is it done this way instead of that single line also i do not see included being called anywhere,['ruby-on-rails'] +127800,google maps save polygon and points in mysql using php right now i have an application that allows users to draw a polygon on google maps i need to save this polygon using php and mysql but i am unsure of best practicesshould i enable spatial extensions and save the geometry should i save each vertical latlng pair in an array another approach i am unaware ofi am wondering what the best practices are using mysql spatial extensions seem daunting it returns things in wkt and then i have to parse that text to make it do something else it seems convoluted,"['php', 'mysql']" +127805,android sharedpreferences backup not working i have been doing my homework on how to backup sharedpreferences in my android application especially using reflection to maintain backwards compatibility at least i have been trying unfortunately none of my code actually ends up creating a backup this includes forcing adb bmgr commands on the emulator as explained here so i am wondering if the community could perhaps help me out and in the process come up with some better documentationheres my code to keep this as generic as possible for others i will simply call my application andy with a package name of comexampleandyandroid manifest excerptapplication androidbackupagentcomexampleandybackuphelper androidrestoreanyversiontrue metadata androidnamecomgoogleandroidbackupapi key androidvaluegiven key goes here backuphelperjavanote datadatacomexampleandyshared prefscomexampleandy preferencesxmlpackage comexampleandyimport androidappbackupbackupagenthelperimport androidappbackupsharedpreferencesbackuphelperpublic class blinkybackup extends backupagenthelper static final string prefs file andy preferences static final string backup key andypreferencesbackup public void oncreate sharedpreferencesbackuphelper backuphelper new sharedpreferencesbackuphelperthis prefs file addhelperbackup key backuphelper backupagentwrapperpackage comexampleandyimport androidappbackupbackupmanagerimport androidcontentcontextpublic class backupagentwrapper private backupmanager wrappedinstance static try classfornameandroidappbackupbackupmanager catch exception e throw new runtimeexceptione public static void checkavailable public void datachanged wrappedinstancedatachanged public backupagentwrappercontext ctx wrappedinstance new backupmanagerctx and finally the commands to initiate a backup during runtime in my application this code is run from a class available to my application not the main activity which is passed this as a context upon creation and then stored in the private variable mcontextprivate void backupdata boolean backupagentavailable false try backupagentwrappercheckavailable backupagentavailable true catch throwable t really nothing to do ifbackupagentavailable backupagentwrapper backupwrapper new backupagentwrappermcontext backupwrapperdatachanged to summarize neither the above function nor the commands below actually backup any data adb shell bmgr enable true adb shell bmgr backup comexampleandy adb shell bmgr run,['android'] +127808,centrally secure all tomcat webapps using basic authentication i have a tomcat 6 server containing three webapps a custom one as root jenkins and nexusi would like to secure all three centrally serverxml using basic authenticationhow can i achieve this without modifying or configuring the webapps themselves,['java'] +127823,sharing settings across methods in namespaced jquery plugin i am writing a plugin and following the jquery documentations recommended practice when it comes to namespacing and multiple methods my init takes care of merging default and custom settings using extend however i can not figure out how to make those options available outside of the init method say that call and initialize my plugin using amyplugindebugfalse how can i reference the debug property later when i call amypluginsomemethod a rough example is function var methods init functioncustomsettings var options debug true return thiseachfunction if customsettings extendoptions customsettings somemethod function ifoptionsdebug how can i access options here do something jquery fnmyplugin function method if methodsmethod return methodsmethodapplythis arrayprototypeslicecallarguments 1 else if typeof method object method return methodsinitapplythis arguments else errormethod method does not exist on jquerytbwaga,['jquery'] +127841,what happens when a computer program runs i know the general theory but i cannot fit in the detailsi know that a program resides in the secondary memory of a computer once the program begins execution it is entirely copied to the ram then the processor retrive a few instructions it depends on the size of the bus at a time puts them in registers and executes themi also know that a computer program uses two kinds of memory stack and heap which are also part of the primary memory of the computer the stack is used for nondynamic memory and the heap for dynamic memory for example everything related to the new operator in cwhat i cannot understand is how those two things connect at what point is the stack used for the execution of the instructions instructions go from the ram to the stack to the registers,['c++'] +127846,prepareforreuse can someone please show me how to use prepareforreuse i have been searching for hours and read dev docsin my custom cell which extends uitableviewcell i have the prepareforreuse method and its getting called but what do i do with it having rendering issues do i do thisdeadline for each labelimplementation posttablecustomcellcontrollersynthesize authornamesynthesize deadlinesynthesize thistancesynthesize interestedcountsynthesize descriptionsynthesize avatarsynthesize viewforbackgroundsynthesize fetchedresultscontroller managedobjectcontext idinitwithstyleuitableviewcellstylestyle reuseidentifiernsstring reuseidentifier if self super initwithstylestyle reuseidentifierreuseidentifier initialization code return self voidsetselectedboolselected animatedboolanimated super setselectedselected animatedanimated configure the view for the selected state void prepareforreuse nslogprep for reuse self clearfields void clearfields nslogclearfields was called jason voiddealloc super deallocend,"['iphone', 'objective-c']" +127851,check if one collection of values contains another suppose i have two collections as followscollection1a1a1m1m2collection2m2m3m1a1a1a2all the values are string values i want to know if all the elements in collection1 are contained in collection2 but i have no guarantee on the order and a set may have multiple entries with the same value in this case collection2 does contain collection1 because collection2 has two a1s m1 and m2 theres the obvious way sorting both collections and popping off values as i find matches but i was wondering if there is a faster more efficient way to do this again with the initial collections i have no guarantee on the order or how many times a given value will appearedit changed set to collection just to clear up that these are not sets as they can contain duplicate values,['c#'] +127853,cannot connect to camera service when using action image capture i am using the following code to tell the system i want to take a picture intent intent new intent androidprovidermediastoreaction image capture null intentputextraandroidprovidermediastoreextra output uri fromfilenew filefilepath startactivityforresultintent take photo activityit works like a champ the first time subsequent tries yield the following exceptionecameraholder 8300 javalangruntimeexception fail to connect to camera service ecameraholder 8300 at androidhardwarecameranative setupnative method ecameraholder 8300 at androidhardwarecameracamerajava110 ecameraholder 8300 at androidhardwarecameraopencamerajava90 ecameraholder 8300 at comandroidcameracameraholderopencameraholderjava100 ecameraholder 8300 at comandroidcameracameraensurecameradevicecamerajava1626 ecameraholder 8300 at comandroidcameracamerastartpreviewcamerajava1686 ecameraholder 8300 at comandroidcameracameraaccess5800camerajava94 ecameraholder 8300 at comandroidcameracamera5runcamerajava949 ecameraholder 8300 at javalangthreadrunthreadjava1096i imagine i have to somehow release the camera object but since i am not directly acquiring it i have no idea how to do this can someone help me out,['android'] +127854,google maps api v3 set zoom level to show a given radius i created a map where a user inputs a zipcode and a radius miles and i want the map to center on the point created from the zipcode and only thisplay roughly the area that would be within that radius i am creating a circle with the radius and trying to get the map to fit to that circle right now it centers correctly but the area being shown is way more than the radius givenmecenter map functionlatlng r latlng is the point of the zipcode var circ new googlemapscircle circsetradiusr 16090 circsetcenterlatlng mapsetcenterlatlng mapfitboundscircgetbounds updates markers googlemapseventtriggermapdragendedit drew the circle that i am using ideally the map would be zoomed in to the area within the radius,['javascript'] +127855,should put and delete be used in forms assuming my web application has full support of put and delete on the server side should i make use of them basically my question is how many browsers support thisform methodputorform methoddeleteis there any benefits to using these two http methods other than being restcompliant assuming the replacement for these two methods is the commonly used post,['html'] +127903,good java property files editor i work on an opensource java project and we have a lot of resource property files that contains localizable message resources those files are translated by volunteers to 20 languages and i am a developer who primarily edits codein java resource files for different locales are grouped together by a naming convention for example if the default normally english resource is fooproperties japanese resource is in foo japroperties french one is foo frproperties etc for the sake of this question let us call this group a resource groupnow every so often i need to refactor those resource files in addition i need the tool to support the basics of the property files all in all my list of requirements are something likerenaming property key name and i want a tool to rename all the keys in all the files in the same group without me individually going through themmove a property from one resource group to another and i want a tool to do so for each resource file in the groupin java resource files are in the iso88591 encoding and not in the platform default encodingi do not want to see ux when editingbrowsing property files but i do expect the tool to preserve themi do not want the tool to rearrange the order of properties in the resource file nor mess with the comments i expect the tool to preserve themi want the tool to handle other syntax details of resource files such as multiline textunfortunately i am not finding any good tool that fits these criteria i am primarily an intellij idea user but it does not do 2 and 3 eclipse builtin property file editor is even worse and afaict it does not do 1 2 4 in fact it lacks the view that cuts across resource files in the same group netbeans is similarly primitive the same goes for netbeans although it does 4does anyone know of a good tool that fits the bill,['java'] +127904,fatal error maximum execution time of 30 seconds exceeded i am downloading a json file from an online source and and when it runs through the loop i am getting this errorfatal error maximum execution time of 30 seconds exceeded in cwampwtempfetchphp on line 24,['php'] +127910,how to cout the stdbasic string i am trying to cout a basic stringtchar but cout is throwing error can i know how to do that,['c++'] +127911,what is the complete process from entering a url to the browsers address bar to get the rendered page in browser i am thinking about this question for a long time it is a big question since it almost covers all corners related to web developingin my understanding the process should be likeenter the url to the address bara request will be sent to the dns server based on your network configurationdns will route you to the real ip of the domain namea requestwith complete http header will be sent to the serverwith 3s ip to identifys 80 portsuppose we do not specify another portserver will search the listening ports and forward the request to the app which is listening to 80 portlet us say nginx here or to another serverthen 3s server will be like a load balancernginx will try to match the url to its configuration and serve as an static page directly or invoke the corresponding script intepretereg phppython or other app to get the dynamic contentwith db query or other logicsa html will be sent back to browser with a complete http response headerbrowser will parse the dom of html using its parserexternal resourcesjscssimagesflashvideos will be requested in sequenceor not for js it will be executed by js enginefor css it will be rendered by css engine and htmls thisplay will be adjusted based on the cssalso in sequence or notif there is an iframe in the dom then a separate same process will be executed from step 112the above is my understanding but i do not know whether it is correct or not how much precise did i miss somethingif it is corrector almost correct i hopemake the steps description more precise in your words or write your steps if there is a big changemake a deep explanation for each step which you are most familiar with one answer per step others can make supplement in each answers commentand i hope this thread can help all web developers to have a better understanding about what we do everydayand i will update this question based on the answersthanks,['html'] +127916,update multiple elements at once linq is it possible to set property on each element from list using linqfor examplevar users from you in contextusers where uname george select uforeach user us in users usmyprop falseis it possible to make it cleaner,['c#'] +127917,tips for improving opengl es fill rate on android in my live wallpaper i am drawing 3 textured quads that covers the whole screen on nexus one i get 40fps i am looking for ways to improving performancethe quads are blended on top of each other textures are loaded from rgb 8 bitmaps textures are 1024x1024i have gotglthisablegl ditherglhintgl perspective correction hint gl fastestglthisablegl10gl lightingglthisablegl depth testglenablegl texture 2dglenablegl blendglblendfuncgl one gl one minus src alphathings i have tried all resulting in the same 40fpsreduce texture size to 512x512 and 256x256use draw texture extensionthisable blendingchange texture filtering from gl linear to gl nearestuse vbos desperate try since there are just 3 quadsrun the drawing code in standalone activity in case being a live wallpaper somehow affects performanceif i draw 2 layers instead of 3 fps rises to 45 or sothen drawing just 1 layer sees fps rise to 55 i guess i am getting limited by fill rate since turning off and on the potentially costly features result in the same fps and the only thing that seems to improve fps is just drawing lessi am mulling over the idea of texture compression but supporting the different compression formats does not seem like fun etc1 has no alpha channel which i need and i am not sure if pvrtc and atitc can even be used from java and opengl es 10 or 11i would be glad to hear ideas on what else to tryi can give pointer to the current version of wallpaper and screenshots if that is of use,['android'] +127928,how do i get a list of gems that are installed that have native extensions i am on windows and have updated from ruby 18x to 19x and am now getting error popups that complain rubymssomethingrt18xdll is missingi would like to find out which gems have native extensions so i can uninstall them and force a rebuild of the native extensions locally during installation again to make the error go away,['ruby'] +127941,c write number digits one by one and in extension in a new line i am new in c and i cannot do a simple exercise for schooli want to do something like this please insert a number 12345 five four three two onebasically the user inputs a number and them the program writes in a new line the number from the last significant number to the mostthis is to do with the switch function and only basic programming skills i have thisinclude stdiohinclude stdlibhint main int num printfplease insert a number scanfd num switchnum case 1printfonenbreak case 2printftwonbreak case 3printfthreenbreak case 4printffournbreak case 5printffivenbreak case 6printfsixnbreak case 7printfsevennbreak case 8printfeightnbreak case 9printfninenbreak case 0printfzeronbreak i i use a number between 0 and 9 it works ok but a number bigger then that it does not do nothingthe first problem i cant solve is to in a number get the digit positioni believe that in my code the break is not doing nothingsorry if i cannot explain me better but english is not my native languageregardsfavolas in progress solution does not work if number 10 gives 0ainclude stdiohinclude stdlibhint main int num printfplease insert a number scanfd num int idigit for i 0 num100i digit num 10 switchnum case 1printfonenbreak case 2printftwonbreak case 3printfthreenbreak case 4printffournbreak case 5printffivenbreak case 6printfsixnbreak case 7printfsevennbreak case 8printfeightnbreak case 9printfninenbreak case 0printfzeronbreak num num 10,['c'] +127956,major javascript data structures i have a job interview coming up and one of the core technologies of the company is javascript i was told that the next interview will focus on js data structures a term that never came up in any of my education i have spend a while on google trying to find out more about them and the best thing i could come across was this wikipedia pageas you can tell the list of items is quite long and way too much to study before my interview since the wiki article is generic and not js specific i know that some most of whats on there does not apply to js can i get some help on what are the main data structures and what i should focus my time on i was unable to find an answer to that on googlei know arrays are one of the major ones that i will need to know what are the other major data structures i should be prepared to talk aboutthanks for any help,['javascript'] +127957,set a web page background color before the background image loads i have a web application and the background image is a dark color it is also over 100kb in size i do not really appreciate the background image being that big but that is not anything i can do anything about or the subject of this question in addition it is a jpeg the web design has come from the customer and i have to leave it as it is despite my protestsas the background image is mainly comprised of dark colors nearly black the text is whitethe trouble is the first time the user goes to the web page the background is white default browser background and the text is also white so you cannot read any of the text only after the background image has loaded can you read the text the page loads a css file this loads another css file and in this is specified the background image so on a highlatency connection such as umts mobile internet connection this can take a few secondsis there any way to say the background of this page should have a particular background image as now but in addition should have the color black ie black will be thisplayed until the background image has loaded or if it does not load in that way the user would be able to read the text immediately i am sure i have seen this done or was that table cell backgrounds but alas cannot remember how and googling also has not helpedthe current css isbody background transparent urlbgjpg top left norepeati have added black to the background property but this did not help,"['html', 'css']" +127958,why does ospathgetsize return a negative number for a 10gb file i am using the function ospathgetsize which gives the size of the file in bytesas my one file size is 10gb it give me size in negativebytesso can anyone give me any idea why this happenthis is my codeimport osospathsize ospathgetsizehomeuserdesktoptest1nrgprint ospathsize,['python'] +127973,static method get is this bad practice had a thiscussion with a colleague about wether this is bad practice or not now i can not find immediate examples of this online we have a lot of database object mappers and call it is functions like soexample the setid method gets the row from the database and sets it to predefined propertysclass person public static function getid object new person objectsetidid return object using it like this we can use simple constructions like this where we got the id from forexample a postperson persongetidinstead ofperson new personpersonsetididnow my instinct tells me this is bad practice but i can not explain it maybe someone here can explain why this is or is not bad practicehere are some other examples how we use it we mainly use it for getters just the names not the code almost all of them just run a query which can return 1 object and then use the id of the result to use the setid methodclass catalogarticle public static function getid public static function getbyarticlenumberarticlenumber articlenumber is unique in the database public static function getrandom runs a query returning a random row,['php'] +127994,issues stringifying a multidimensional array with jsonjs i have problems with stringify but i think my javascript array must be wrong heres my codevar questions new arrayvalidhoverfunction for i0i questionslengthi questionsinew array questionsinumeronumeroeqihtml questionsiquestioniteminputeqival questionsivariablevarnameeqival var stringjsonjsonstringifyquestions alert stringjsonthe stringjson var returns what am i doing wrong,"['javascript', 'jquery']" +127999,splitting a string into integers using istringstream in c i am trying to use istringstream to split a simple string into a series of integersinclude stringinclude iostreaminclude sstreaminclude vectorusing namespace stdint main string s 1 2 3 istringstream is while iss int n iss n cout and endl and i get 1 2 3 3why is the last element always coming out twice how to fix it,['c++'] +128004,error creating the web proxy specified in the systemnetdefaultproxy configuration section i receive the error from a third party application exethe application is only a exe no config file or otherserror creating the web proxy specified in the systemnetdefaultproxy configuration sectionhow can i handle that,"['c#', '.net']" +128007,springhibernate persist does not result in insert i am trying to implement a simple daoi have a daorepositoryiuserdaotransactionalreadonly truepublic class userdao implements iuserdao private entitymanager entitymanager persistencecontext public void setentitymanagerentitymanager entitymanager thisentitymanager entitymanager override public user getbyidint id return entitymanagerfinduserclass id override public boolean saveuser user entitymanagerpersistuser entitymanagerflush return true override public boolean updateuser user entitymanagermergeuser entitymanagerflush return true override public boolean deleteuser user user entitymanagergetreferenceuserclass usergetid if user null return false entitymanagerremoveuser entitymanagerflush return true and an entityentitytablename userspublic class user private int id private date creationdate id generatedvaluestrategy generationtypeidentity public int getid return id public user public userdate creationdate thiscreationdate creationdate public void setidint id thisid id public date getcreationdate return creationdate public void setcreationdatedate creationdate thiscreationdate creationdate heres appcontextxml bean identitymanagerfactory classorgspringframeworkormjpalocalcontainerentitymanagerfactorybean pdatasourcerefdatasource pjpavendoradapterrefjpaadapter ppersistenceunitnametest property nameloadtimeweaver bean classorgspringframeworkinstrumentclassloadinginstrumentationloadtimeweaver propertybeanbean idtransactionmanager classorgspringframeworkormjpajpatransactionmanager pentitymanagerfactoryrefentitymanagerfactorybean idjpaadapter classorgspringframeworkormjpavendorhibernatejpavendoradapter pdatabasemysql pshowsqltruebean classorgspringframeworkormjpasupportpersistenceannotationbeanpostprocessortxannotationdrivenunless i call flush after persist or merge the insert in not executedwhy is thatif i remove transactional then i get error on no transaction is in progress on flush but if remove flush nothing inserted to the db,['java'] +128009,settimeout and setting parameters i have some jquery code that looks like thismainnav2 limouseleavefunction var somenum mathrandom thisattrid somenum var t settimeouthidemenusomenum 200 liclickedmouseenterfunction cleartimeoutt function hidemenuid idremoveclassclickedit is purpose is to hide a mega menu on mouse leave but also takes into account accidental mouse leaves by using a 300 millisecond settimeout if the user brings the mouse pointer back into the li within 300 milliseconds the menu is not hidden because cleartimoutt is called the problem is when the user does intent to mouseout the function in the settimout is not being called according to this page timingasp my syntax is correct but i can only get the hidemenu function called from the settimeout if i write it like thisvar t settimeouthidemenu 300why is not it working as written where i can pass a variable into the function as a parameter,['jquery'] +128030,unquote string in c please forgive my laziness i could figure this out by reading up i know but i thought i would give one of you c geniuses the chance to win some repi have a data file in ini file like format that needs to be read by both some c code and some c code the c code expects string values to be surrounded in quotes the c equivalent code is using some underlying class or something i have no control over but basically it includes the quotes as part of the output string ie data file contents ofmy valhello worldgives mehello worldin my c string when i really need it to containhello worldhow do i conditionally on having first and last character being a remove the quotes and get the string contents that i wantthankyou very much,['c#'] +128034,iphone understanding iphone rotation i am banging my head on the wall trying to understand this see the next picturesuppose i have an iphone resting on a table at this time the rotation readings thru core motion are 0 for yaw roll and pitch picture athen i roll it 90 degrees now it is sitting on the table with its left side home button on the right now it reads 0 picture bnow i yaw it 180 degrees it is now sitting with its right side on the table home button on the left it now reads 180 picture cthe problem comes if i roll it now suppose i roll it 45 degrees i should be reading 180450 but instead i am reading 18045180 picture dwhy is that why is it giving me a value for pitch if i never changed that how can be pitch influenced by a rotation in other angles thanks,['iphone'] +128046,unable to use intellij with a generated sources folder related questionhow to configure intellij idea andor maven to automatically add directories with java source code generated using jaxb2mavenplugini have a custom plugin that generates sources under targetgeneratedsources note no toolname here so i get sources like targetgeneratedsourcescommycompanyetcthis format cannot be changed at all so will i be able to configure intellij into adding it as a source folder as of now i can see that intellij has added targetgeneratedsourcescom as the source folderplease note that i do not have the option of configuring the plugin update 1 i do not agree with the fact that i must put my generated sources under a tool name folder it may be a good convention but if i have only one generator there is no need for me to put it there again in my pomxml i have a resources section which clearly indicates that targetgeneratedsources should be treated as a source folder this works perfectly fine in eclipse so i have no idea why intellij would not respect my settings tldr when i put targetgeneratedsources in the resource section of pomxml why is intellij overzealous to add targetgeneratedsourcescom to the classpath,['java'] +128053,run individual parameterized testcase with nunitconsole i can run an individual testcase which takes a single string value with no problems from the command linefor example runnamespaceclassmethodmy input stringhowever the same procedure does not seem to work for me with numerical inputsfor example runnamespaceclassmethod123the output lists the correct input as a test to run but does not actually run any testseditlooking into this further it appears that the problem is with tests which take more than one argument using the following test filenamespace gettestsproj testfixture class nunitconsoletest testcase123 test descriptiona simple test with parameterized numeric inputs public void testnumericint a int b int c assertareequalc a b testcasemy string test descriptiona simple test with parameterized string input public void testsinglestringstring a assertareequalmy string a testcasestring1 string2 test descriptiona simple test with parameterized numeric inputs public void testtwostringsstring a string b assertareequalstring1 a the call nunitconsoleexe rungettestsprojnunitconsoletest gettestsprojgettestsprojbindebuggettestsprojdll properly runs all 3 testcasesthe call nunitconsoleexe rungettestsprojnunitconsoletesttestnumeric gettestsprojgettestsprojbindebuggettestsprojdll properly runs 1 testcasethe call nunitconsoleexe rungettestsprojnunitconsoletesttestsinglestringmy string gettestsprojgettestsprojbindebuggettestsprojdll properly runs 1 testcasehowever the call nunitconsoleexe rungettestsprojnunitconsoletesttestnumeric123 gettestsprojgettestsprojbindebuggettestsprojdll runs 0 testcasesand similarly the call nunitconsoleexe rungettestsprojnunitconsoletesttesttwostringsstring1string2 gettestsprojgettestsprojbindebuggettestsprojdll runs 0 testcasesalthough nunit seems to recognize the input run properlyselected tests gettestsprojnunitconsoletesttestnumeric123tests run 0 errors 0 failures 0 inconclusive 0 time 0 seconds not run 0 invalid 0 ignored 0 skipped 0andselected tests gettestsprojnunitconsoletesttesttwostringsstring1 string2tests run 0 errors 0 failures 0 inconclusive 0 time 00156256 seconds not run 0 invalid 0 ignored 0 skipped 0this is all using nunit 25910348i am interested in whether this is user error or unsupported functionality it would be very useful for what i am trying to do,['c#'] +128057,jquery animate background position i cannot seem to get this workingproduct family options ddanimate height 300px width 900px backgroundposition 20px 0px the height and width animate but not the background,['jquery'] +128073,which method is better css classes or ids let us consider these 2 ways of writing the same codemethod 1div idheader div iduser a idusernameusernamea a iduserimageuserimagea divdivmethod 2div idheader div classuser a classnameusernamea a classimageuserimagea divdivcss of method 1username color white userimage height 50px width 50px css of method 2header divuser aname color white header divuser aimage height 50px width 50px it seems to me that method 2 is cleaner since you will never end up with ids like userimageinnerbox now technically speaking which is the best method and why,"['html', 'css']" +128077,fork and threads in ruby i am running a program on a machine with a two processors when i do a fork is the child created as a native thread or it is like a green threadcoroutine is the child running concurrently with the parent or it is just parallel,['ruby'] +128105,how do i thisplay protected amazon s3 images on my secure site using php i am trying to move images for my site from my host to amazon s3 cloud hosting these images are of client work sites and cannot be publicly available i would like them to be thisplayed on my site preferably by using the php sdk available from amazonso far i have been able to script for the conversion so that i look up records in my database grab the file path name it appropriately and send it to amazon upload to s3s3create objectbucket folderfile name new array fileupload file temp acl amazons3acl private access denied grantee only own acl amazons3acl public image thisplayed acl amazons3acl open image thisplayed grantee everyone has open permission acl amazons3acl auth read image not thisplayed grantee auth users has open permissions acl amazons3acl owner read image not thisplayed grantee only ryan acl amazons3acl owner full control image not thisplayed grantee only ryan storage amazons3storage reduced before i copy everything over i have created a simple form to do test upload and thisplay of the image if i upload an image using acl private i can either grab the public url and i will not have access or i can grab the public url with a temporary key and can thisplay the imagephpthisplay the image linktemp link s3get object urlbucket folderfile name new 1 minutea hrefphp echo temp link php echo temp link abr img srcphp echo temp link altfinding image br using this method how will my caching work i am guessing every time i refresh the page or modify one of my records i will be pulling that image again increasing my get requestsi have also considered using bucket policies to only allow image retrieval from certain referrers do i understand correctly that amazon is supposed to only fetch requests from pages or domains i specifyi referenced188183 to set that up but then am confused as to which security i need on my objects it seemed like if i made them private they still would not thisplay unless i used the temp link like mentioned previously if i made them public i could navigate to them directly regardless of referreram i way off what i am trying to do here is this not really supported by s3 or am i missing something simple i have gone through the sdk documentation and lots of searching and feel like this should be a little more clearly documented so hopefully any input here can help others in this situation i have read others who name the file with a unique id creating security through obscurity but that would not cut it in my situation and probably not best practice for anyone trying to be secure,['php'] +128106,wpf documentviewer get itextpointer by glyphrun and vice versa just wondering whether anybody has tried to hack into wpf documentviewer in order to make it more useful i have spent almost a week already trying to create more powerful api for this control based on it is methods which i extract using reflection everybody knows how to get selected text from document viewer via reflection but my task is more complicated selected text has end and start properties which return itextpointers also i have a collection of glyphruns extracted using this code and now finally i want to find out which glyphrun contains selection start so i want to know how to convert itextpointers into glyphruns and vice versa i understand that they do not have 11 relationship this control with closed api and last week spent in reflector does not let me sleep well i hope maybe somebody tried to do it before or seen code samples and will be able to guide me through these jungles,['c#'] +128175,javascript cursor change and change back again i have this page that does some funky database stuff that takes a couple seconds to process and in the meantime i would like to set a wait cursor so the user does not flip out and keep clicking the button i have looked at the documentbodystylecursor waitthing the problem with this is that it only works when the mouse is over the body of the page ie still shows normal pointer if it is over a button how can i set it so that no matter where the mouse is on the page it shows a wait icona second part to this question is once it is done it is thing how do i set it back if i set it back to default this seems to override any hover cursor changes i had set in my css so it no longer becomes a hand when over a specified object etcedit the first answer works nicely except in ie it does not refresh the cursor so you notice the change of cursor type until you actually move the cursor any fixes,['javascript'] +128179,is html a contextfree language reading some related questions made me think about the theoretical nature of htmli am not talking about xhtmllike code here i am talking about stuff like this crazy piece of markup which is perfectly valid htmldoctype html public w3cdtd html 401enhtmlheadtitlep ltrspan idpspanpso given the enormous complexity that sgml injects here is html a contextfree language is it a formal language anyway with a grammarwhat about html5i am new to the concept of formal languages so please bear with me and yes i have read the wikipedia article,['html'] +128196,how to set pdf width in mobile safari i am trying to thisplay a pdf file embed in a webpage i am using the object tag the pdf can be thisplayed in iphone or ipad however i want to make the pdf thisplay fill the full width of the webpage i am unable to find out any document about setting the pdf width for mobile safari please helpobject idobjectpdf typeapplicationpdf datapdfpdf width100 height10px styleborder2px solid red textaligncenterparam nameview valuefith valuetypedata,['html'] +128201,validates associated not checking existence of associations can anyone figure out whats going on here i was able to get my code to work the way i want it to but i cannot figure out why validates associated is not working as i expect heres a snippet of my codeclass flag activerecordbase belongs to user belongs to post allow only one flag per post per user validates uniqueness of user id scope post id validates user id post id presence true validates associated user post attr accessible user id post idendwith this code i cannot save a flag with user id nil i can save a flag with user id 12345 ie some user id not in the database this is what the validates associated api specification saysvalidates associatedattr namesvalidates whether the associated object or objects are all valid themselves works with any kind of association note this validation will not fail if the association hasnat been assigned if you want to ensure that the association is both present and guaranteed to be valid you also need to use validates presence ofi was able to get the desired behavior by using this instead validates user post presence truemy understanding of the api specification is that validates associated checks the associated table to see if a row exists with an id matching the foreign key of flag provided the foreign key is nonnil can anyone offer any insight on this am i misunderstanding how validates associated is supposed to work,['ruby-on-rails'] +128204,android bouncy castle ioexception i am using suns keytool to create a bouncy castle keystore and import a certificate into it the keytool does produce a keystore in the bouncy castle format i then attempt to import the bouncy castle keystore into an android program i am able to get an instance of the bks keystore but calling load on the keystore throws javaioioexception wrong version of key storethis is the code keystore keystore keystoregetinstancebksinputstream is new fileinputstreammntsdcardarcgismystorebkskeystoreloadis abcdeftochararrayi tried various versions of the bouncy castle jar downloaded from releaseshtmlwhat am i doing wrongthanksranjit,['android'] +128252,android gallery view scrolling problem when onclicklistener for items given i have used gallery in my appin that i have two images in each gallery item like this each rabbit and mouse image is combined as a single gallery itemso i give onclicklistener for both images but if i give like that i cannot scroll by touching those images if i remove onclicklistener for that individual images i am able to scrollhow to archive both scroll and onclick for each images,['android'] +128261,exporting rsa key object to xml in java i am successfully running rsa encryptiondecryption in java this is how i generated the key objectoutputstream oos new objectoutputstreamnew fileoutputstreampath keypairgenerator kpg keypairgeneratorgetinstancersa kpginitialize1024 keypair keypair kpggeneratekeypair ooswriteobjectkeypairbut now i need to integrate my system with net code is it possible to export this keypair object into xml in the following formatas that net code can only accept keys in xml formatrsakeyvalue modulusmodulus exponentexponent pp qq dpdp dqdq inverseqinverseq ddrsakeyvalue,['java'] +128264,how to use a package constant in sql select statement how can i use a package variable in a simple select query statement in oraclesomething likeselect from mytable where typeid mypackagemy typeis it possible at all or only when using plsql use select within beginend,['sql'] +128290,add events to google calendaryahoo calendar outlook and ical the users of my javascript based site often need to create an event where they post an event name event description start time and the end time of the event along with the date now they would like to add those event details to the their google calendar or yahoo calendar or ical or outlook is their any standard library for that i am trying to figure it out for the past 3 days though i am aware of google apis but i am not aware of ical and outlook or even yahoo too i am looking for something very similar this in the right hand side you can see this add this to your site part i would like to do the same thingplease help me to get in hands on,['javascript'] +128301,floating multiplication performing slower depending of operands in c i am performing a stencil computation on a matrix i previously read from a file i use two different kinds of matrices nonzero type and zero type both types share the value of the boundaries 10 usually whilst the rest of the elements are 0 for zero type and 1 for nonzero typethe code stores the matrix of the file in two allocated matrices of the same size then it performs an operation in every element of one matrix using its own value and values of neighbours add x 4 and mul x 1 and stores the result in the second matrix once the computation is finished the pointers for matrices are swapped and the same operation is perform for a finite amount of times here you have the core codedefine getij rmaticols jdefine putij wmaticols jfor cur time0 cur timetimesteps cur time for i1 irows1 i for j1 jcols1 j putij 02fgeti1j getij1 getij getij1 geti1j change pointers for next iteration auxp wmat wmat rmat rmat auxpthe case i am exposing uses a fixed amount of 500 timesteps outer iterations and a matrix size of 8192 rows and 8192 columns but the problem persists while changing number of timesteps or matrix size note that i only measure time of this concrete part of algorithm so reading matrix from file nor anything else affects the time measurewhat it happens is that i get different times depending on which type of matrix i use obtaining a much worse performance when using zero type every other matrix performs same as nonzero type as i have already tried to generate a matrix full of random valuesi am certain it is the multiplication operation as if i remove it and leave only the adds they perform the same note that with zero matrix type most of the type the result of the sum will be 0 so the operation will be 020this behaviour is certainly weird for me as i thought that floating point operations were independent of values of operands which does not look like the case here i have also tried to capture and show sigfpe exceptions in case that was the problem but i obtained no resultsin case it helps i am using an intel nehalem processor and gcc 443,['c'] +128307,ascii value of character in ruby how do i obtain the ascii value of a character in ruby 19i searched the internet far and wide but without success i tried x and x0 but all they return is x,['ruby'] +128319,assertareequal failing in unit test i have the following unit teststring mtrlcode 0assessment target new assessmentmtrlcodeliststring edgecasesymbolcodes new liststring more than 3edgecasesymbolcodesaddflaedgecasesymbolcodesaddharedgecasesymbolcodesaddcoredgecasesymbolcodesaddenvonedgecasesymbolcodesaddenvredgecasesymbolcodesaddexptargethazardsymbols edgecasesymbolcodesliststring edgecasesymbolcodesexpected new liststring should be 3edgecasesymbolcodesexpectedaddflaedgecasesymbolcodesexpectedaddharedgecasesymbolcodesexpectedaddcorsystemwindowsformsmessageboxshowedgecasesymbolcodesexpected0 edgecasesymbolcodesexpected1 edgecasesymbolcodesexpected2 n targethazardsymbols0 targethazardsymbols1 targethazardsymbols2assertareequalliststringedgecasesymbolcodesexpected targethazardsymbols coshh 2008custom classesassessmentsethazardsymbols edge case did not return the expected valuewhich is testing an edge case a time when the liststring has more than 3 elements with the desired output being the return of only the first 3currently the test is failing and i have had to resort to using the messagebox to see inside of the test due to the breakpoints not being hitfrom what i can see the elements are the same however i realise there might be something else different with the liststring object but i cannot see this as the breakpoints are never been hiti cannot find the modules window in visual studio 2005what would your next steps be,"['c#', '.net', 'asp.net']" +128329,under what circumstances are rmul called in python say i have a list l under what circumstance is l rmul self other called,['python'] +128334,capture mouse movement and export to image code app to get more in depth information about the usage of winform or webapplications i want to capture mousemovement and click information it would be perfect if this could be rendered to an imagethe result would be something like thisthe question is how does one start with creating an app like thishow do i receive mousemovements and clicks when its a process from another applicationhow convert mousemovements to an imageanyone know if there is a opensource of freecheap app which can do thisiographica is able to do this but it is in java and it is free but not open source,['c#'] +128355,how to let an html image overlap another div classmainrunner img srcapp themesdefaultimagesagif img srcapp themesdefaultimagesbgif divi want bgif to overlap agif rather than go on a new line how can i achieve this,"['html', 'css']" +128358,why enumset is implmented as abstract class and enummap is implemented as concrete class i was wondering is there any reason why enumset is implemented as abstract class and enummap is implemented as concrete class,['java'] +128369,how to get uibutton target action and control events i am using uiimageviews with uibuttons a whole bunch so i created a custom class to permanently marry these two an make things a little simpler it all works well until i decided to implement idinitwithobjectauiimageviewbutton imageviewbuttonclearly i need to copy all relevant properties from the imageviewbutton object being passed the uiimageview is not problematic at all something like this deals with itimageview uiimageview alloc initwithframeimageviewbuttonimageviewframe copy all relevant data from the sources imageviewimagebuttonimageview setbackgroundcolorimageviewbuttonimageviewbackgroundcolor imagebuttonimageview setimageimageviewbuttonimageviewimage most of the button stuff is also readily availablebutton uibutton buttonwithtypeimageviewbuttonbuttonbuttontype copy all relevant data from the sources buttonbuttonframe imageviewbuttonimageviewframe button settitleimageviewbuttonbuttontitlelabeltext forstateuicontrolstatenormal buttontag imageviewbuttonbuttontag i am having a little trouble figuring out how to get all the data for the addtargetactionforcontrolevents methodlooking at the docs i can see that i might be able to use uicontrols allcontrolevents and alltargets methods i will dig into that right now and see how much trouble i can get into the one i am not sure about is the action can anyone give me a shove in the right directionthanksmartin,['iphone'] +128375,boolean expression as column value in transact sql in most rdbmses this workselect 5 3and evaluates to true it does not work in ms transact sql and the only workaround i have found is to writeselect case when 5 3 then 1 else 0 endwhich kind of sucks because it is much more verbose is there a better way to write the above kind of checks,['sql'] +128388,design strongly typed object from xml i have a couple of xml files that i need to work with and i have always used the xelement objects and pulled the data via the attribute name or the xelements valuei know there has to be a better way of using xml in c what is the best way to either auto generate or manually generate a strong typed object from the xml filethe xml is in the form of group id titlesome titletitle descriptionsome descriptiondescription rule idid severitymedium weight100 version1001version titleanother titletitle descriptionvery long descriptiondescription fixtext fixreff31r1 fixdescription of fixfixtext fix idf31r1 fix check systemc7883r4 chk checkcontentref namem hrefuri checkcontentcontentcheckcontent check rulegroupif i could parse an xml file into a listgroup that would be the bestthe only way i can think to do it is manually create the group rule and check objects and manually assign the data if there is a better more automated way to do this please let me know,['c#'] +128398,jquery select all elements without thisabled and no readonly with jquery i need to select all input elements with a conditionnot thisabled thisabled and not readonlyand then i am gonna change css style to query resultupdate i need iterate over result in order,['jquery'] +128439,calling the writeablebitmapwritepixels method i am trying to call the writeablebitmapwritepixels method but i cannot seem to understand the parametersthe msdn article is very dull or shuold i say null and i could not understand how to use the methodediti tried to modify a code from this article pixelformat pf pixelformatsrgba128float writeablebitmap wb new writeablebitmapwidth 5 height 5 100 100 pf new bitmappalettenew listcolor colorfromargb255 255 0 0 byte colordata 0 0 0 0 wbwritepixelsnew int32rect0 0 1 1 colordata 4 0 backgroundsource wbin the line before the last line the debugger claims that the buffer colordata size is not sufficient edit2i tried again void refreshgraphics pixelformat pf pixelformatspbgra32 writeablebitmap wb new writeablebitmapwidth 5 height 5 100 100 pf new bitmappalettenew listcolor colorfromargb255 255 0 0 byte colordata new byte10 byte t 0 for int i 0 i 10 i colordatai t wbwritepixelsnew int32rect0 0 10 10 colordata 10 0 backgroundsource wb now a value is is not in the expected rangethe stacktrace does not tell which oneedit 3problem solveddo not know how or why but the code works and i afraid to change it,['c#'] +128440,how to refactor variable type in eclipse i want to refactor code like thisint x4int yxsystemoutprintlnyhow can i do this automatically in eclipse so xs type promotion to long would cause dependent variables to change their types alsolong x4long yxsystemoutprintlny,['java'] +128460,how do i create a view in mysql how do i create a view in mysql,['mysql'] +128473,python property change listener pattern anyone know of any easy way to track changes to a dictionary object in python i am at a high level doing crud so i have a couple methods that handle changing a dictionary if the dictionary changes i want to call a function to basically do an observernotify class myclassobject def updateself item changed false ifselfmy dicthas keyitemid selfmy dictitemid item changed true ifchanged selfnotifywhat i am trying to avoid is all of the trackingsetting the boolean code was hoping there was an easier way to track changes this is a simple case but there could have been more complicated logic that would result in me having to set the changed flag,['python'] +128507,variable variables in javascript i know it is possible in php to have variable variables for examplex variablex hello worldecho variable thisplays hello worldis this possible in javascript how would it be done,['javascript'] +128527,using selenium to imitate dragging a file onto an upload element i have a web page that opens a div when you click a button this div allows you to drag a file from your desktop onto its area the file then gets uploaded to the server i am working with the ruby implementation of seleniumby using the javascript debugger in firefox i can see that an event called drop is being passed to some javascript code handlefiledropevent i presume that if i were to create a mock event and fire it somehow that i could trigger this codeif found an interesting article that seemed to point me in a promising direction but i am still short of figuring it all out i am able to pass javascript to the page using seleniums get eval method calling methods using thisbrowserbot is getting me the elements i needsohow do i build the file object thatneeds to be part of the mock dropevent how do i fire the drop eventsuch that it gets picked up as if ihad dropped a file in the div,"['javascript', 'ruby']" +128532,reusing an instance of nsurlconnection i am using an instance of nsurlconnection on the iphone to request data from a server managed by a delegate as usual the requests are quite frequent maybe once every 2 minutes say and have a common and fixed url rather than seeing the good instance of nsurlconnection being released after each download and then a new one being createdis there any worth in retaining the first connection and reusing it i would hope so one good authentication should be worth a thousandif so how do i reuse it the standout method in the docs is start but this seems to crash the app when called on an already used and nonnil instance of nsurlconnection the docs do say start causes the receiver to begin loading data if it has not alreadyin case it is of help with regard to the above questions i am was proposingif connection nil connection nsurlconnection connectionwithrequestrequest delegateself else connection start,['iphone'] +128533,retrieving matched context of mysql fulltext search in php and security i am doing a fulltext search on my mysql table pages i am thisplaying a list of pages that match the keyword in their title plain text varchar 255 or content html text when the match is found in the content field i would like to thisplay the snippet in which the match was found i have no idea how to go about this can you put me in the right directionquery select matchtitle content againstkeyword as score from page where matchtitle content againstkeyword order by score desc result mysql queryquery or die mysql errorifmysql num rowsresult 0 output pyour keyword matches the following pagesp whilerow mysql fetch assocresult title htmlentitiesrowtitle content htmlentitiesstrip tagsrowcontent content limit textcontent 250 cuts it down to 250 characters plus output h2titleh2 iftrimcontent output pcontentp i would like to place a snippet here with the matched context else output pkeyword not foundp also i have a question regarding security right now i am checking keyword in three waysnot blankmore than 2 charactersnot dangerous see belowi use a regular expression to match the following to see if the user input is dangerousscriptltscriptgtscriptdocumentalertbcxmailertorecipienttruncatedrop tablethis might be a little bit ridiculous and easy to work around but it is at least a minimal form of protection against xss exploits what is the recommended way to secure filter a keyword intended for search is phpids overkill,['mysql'] +128544,how to access parent object from lambda functions i have a recursive lambda function in one of my objects and it needs to access the objects mysqli connection this attemptrecfunc functionid name usethis produced an unreasonable fatal errorfatal error cannot use this as lexical variable in cuserscodemonkey1991desktopworkspacemeliorobjectsdatabasemanagerphp on line 88could anyone give me a few pointersedit just to clarify context i am trying to create this lambda function inside another function,['php'] +128566,submit form from a link this is what i am trying to do without success form namesomething actionhtphp methodpost a href onclickdocumenturlsubmithelloworldsubmitaformwhen i click on the link i want to post the value helloworld to htphp how can i do this,"['javascript', 'html']" +128570,how to serialize and deserialize objects using jaxb i have an issue i want to convert an object into another object using jaxb as in i have a class comhomestudent and another class comschoolstudent both have same arguments in fact both are same copy paste but different package i want to perform the conversion between then using jaxbhow to do that please help me,['java'] +128577,how do i create a linebreak in terminal i am using python in terminal on mac osx latest when i press enter it processes the code i have entered and i am unable to figure out how to add an additional line of code eg for a basic loop,['python'] +128625,how do i implement choose existing photo in my app like in default iphone phonebook i want to develop an app which has functionality same as iphone phonebook capturing image and choosing iamge what should i to use for doing suchi have made an uiimageview and a button for uiactionsheet now i want to perform take photo and choose existing photo options in my apphelp me out i do appreciate thanks in advance,"['iphone', 'objective-c']" +128628,best way to log a python exception i am printing my exceptions to a log file currently withtry coode in hereexcept exception e loggingerrorecould i be printing more information about the exception and the code that generated it than just the exception string things like line numbers or stack traces would be great,['python'] +128656,why use when you are sure types are equal it seems that the strict equality operator is preferred whenever possible i put my code in jslint and got the following feedbackcodefunction log consolelogargumentslength 1 arguments0 argumentsfeedback from jslintproblem at line 2 character 34 expected and instead saw i am curious to know what advantages has over here basically length returns a number and 1 is a number as well you can be 100 sure so is just a redundant extra token also checking for the type whilst you know the types will always be the same has no performance advantage eitherso whats actually the reason behind using here,['javascript'] +128667,chromeextension append functions to right click menu how would i append functions to the right click menu in the browser eg something appended to the right click menu which does function dosomething which is located in my extension,['javascript'] +128669,does a subclass inherit constructors from it super class in a subclass we can initialize data members using the subclas constructor which internally calls the superclas constructor super if a subclass cannot inherit constructors from its superclass then how can the super call initialize the superclass,['java'] +128672,value lookup table in c by strings if i have a set of small string values and i want to fetch a numeric value to represent them whats the best way to do this via a lookup tableif i were only needing to do a straight look up i know the optimal solution would just be a series of if statementsif strcmpstr foo 0 tmp fooelse if strcmpstr bar 0 tmp barbut i ask this because these small string values represent an attribute in a small project i am writing in c and the attributes can be readonly or readwrite no writeonly for now maybe neverso what i currently do just to make sure things work is have a lookup function comprised of an ifthen clause like above to look up which values are readonly and a second functions that looks up which values are readwrite but this is large and ugly to mei am thinking have three functions instead one function is the lookup function and it returns an int value that is the numeric form of the string but this lookup function can also take a flag that determines whether it fetches a readonly value or a readwrite value if a write operation is done on a value that is really readonly the function will return einval or something equivalentthe other two functions now still the read and write just call this lookup function passing in a string of the value and the flag that determines whether they are for reading or writingthing is i do not know how this is modeled in c if it can be modeled and searching google is tiresome with all the content farms ripping this place off and giving me cc answers insteadso this is how i think it will lookint lookup funcconst char name const char flag int tmpval 0 code to do the lookup if tmpval 0 return einval else return tmpvalint get readonly bitconst char name return lookup funcname roint get readwrite bitconst char name return lookup funcname rwthoughts the idea is to reduce code size by not repeating the ifthen branches for these two functions which differ slightly in overall design and simply let some kind of a lookup function figure out what function this value serves,['c'] +128677,java supertuning a few questions before i ask my question can i please ask not to get a lecture about optimising for no reasonconsider the following questions purely academici have been thinking about the efficiency of accesses between root ie often used and often accessing each other classes in java but this applies to most oo languagescompilers the fastest way i am guessing that you could access something in java would be a static final reference theoretically since that reference is available during loading a good jit compiler would remove the need to do any reference lookup to access the variable and point any accesses to that variable straight to a constant address perhaps for security reasons it does not work that way anyway but bear with mesay i have decided that there are some order of operations problems or some arguments to pass at startup that means i cannot have a static final reference even if i were to go to the trouble of having each class construct the other as is recommended to get java classes to have static final references to each other another reason i might not want to do this would be oh say just for example that i was providing platform specific implementations of some of these classes now i am left with two obvious choices i can have my classes know about each other with a static reference on some system hub class which is set after constructing all classes during which i mandate that they cannot access each other yet thus doing away with order of operations problems at least during construction on the other hand the classes could have instance final references to each other were i now to decide that sorting out the order of operations was important or could be made the responsibility of the person passing the args or more to the point providing platform specific implementations of these classes we want to have referencing each othera static variable means you do not have to look up the location of the variable wrt to the class it belongs to saving you one operation a final variable means you do not have to look up the value at all but it does have to belong to your class so you save one operation ok i know i am really handwaving nowthen something else occurred to me i could have static final stub classes kind of like a wacky interface where each call was relegated to an impl which can just extend the stub the performance hit then would be the double function call required to run the functions and possibly i guess you cannot declare your methods final anymore i hypothesised that perhaps those could be inlined if they were appropriately declared then gave up as i realised i would then have to think about whether or not the references to the impls could be made static or final orso which of the three would turn out fastest any other thoughts on lowering frequentaccess overheads or even other ways of hinting performance to the jit compilerupdate after running several hours of test of various things and reading i have found that most things you would normally look at when tuning eg c go out the window completely with the jit compiler i have seen it run 30 seconds of calculations once twice and on the third and subsequent runs decide hey you are not reading the result of that calculation so i am not running itfwiw you can test data structures and i was able to develop an arraylist implementation that was more performant for my needs using a microbenchmark the access patterns must have been random enough to keep the compiler guessing but it still worked out how to better implement a genericified growing array with my simpler and more tuned codeas far as the test here was concerned i simply could not get a benchmark result my simple test of calling a function and reading a variable from a final vs nonfinal object reference revealed more about the jit than the jvms access patterns unbelievably calling the same function on the same object at different places in the method changes the time taken by a factor of fouras the guy in the ibm article says the only way to test an optimisation is insituthanks to everyone who pointed me along the way,['java'] +128714,help with queryover and whereexists i have a problem i have persons and cats each person has some cats there is a foreign key in cats that points to the primary key in persons each cat has an age i want to select the persons that have old cats i want all the cats of these persons and not only the old catsi need to do it with the queryover syntaxin tsql it would be something likeselect p cfrom persons pleft join cats c on pid cowneridwhere exists select 1 from cats c2 where pid c2ownerid and c2age 5i know i have to use the subqueries and i could to easily with the old nhibernate syntax the criteriadetachedcriteria but i cannot do it in queryover syntaxi do not want an in condition my primary key is a complex key so i cannot do it with the invar persons sessionqueryoverpersonwithsubquerywhereexists,['c#'] +128718,basedonstaticresource xtype textbox in code behind for style how can you set the following in code behindstyle targettypextype textbox basedonstaticresource xtype textboxi am using a theme merged in appxaml it works great for all controls but when i define a style for something eg textbox the theme style does not get picked up unless i use basedon like above instead it gets the default textbox style now i am creating a datagridtextcolumn in code behind and i cannot get the basedon part to work for the editingelementstylestyle editingstyle new styletypeoftextboxeditingstylebasedon any suggestions also is there any way to get the theme style instead of the default style applied without using basedonthanks,['c#'] +128727,how to embed c code in javascript on cshtml mvc3 razor page how would i do the equivalent of this embedded in javascript on an mvc2 aspx pageif modelsomefunctionenabled true and also a whole function code block on a razor view page cshtml in mvc3something like foreachvar d in modelemployees which works fine when embedded in the html part of the view pagethanks,['javascript'] +128732,spell checker for net c does somebody know a good multilanguage spell checker for c neti mean i have googled it and i found some alternatives but does someone have a good success story with onei need to add a spell checker to my application i would like a library that integrates with systemwindowsformstexbox for examplealso my application is portable to linux mac using mono so it should be 100 managed codeedit i am looking for something that underlines with a red line a wrong word in the textbox and also proposes corrections in a contextmenu,"['c#', '.net']" +128734,parsing c to ocaml i would like to get the abstract syntax tree ast from a c code into an ocaml value so that i can further process the parsed code with a plain ocaml programi had in mind to use gcc get the ast in gimple with a hook and convert the gimple code to ocamlbut i wonder if there is another way or if someone did something similar already i have not found much actually on thati do not want to resort to using cil it is an ocaml parser for c code but it does not contain all optimizations that gcc has i especially need a deeper alias analysis than the one implemented in cilcan llvm be a good idea to look at already done maybeany better idea,['c'] +128739,how tell which jdk contains which versions of jaxws there is a fix in one of the more recent versions of jaxb 221 i am trying to determine if that is included in a recent update to java 6 is there a way to tell which which versions of a jvmjrejdk contain which versions of jaxwsjaxblooking at sunoracles site i can view the release notes for the latest versions of java se 6 but i cannot tell which versions of the xml libs are included i guess i could download the latest jdk and run xjc version but there should be a better way esp if it was added in a previous release i do not want to keep downloading jres to tell which was the first with the version of jaxb i am interested in,['java'] +128746,using boostaccumulators how can i reset a rolling window size does it keep extra history i am looking at the boostaccumulator framework specifically a couple of the rolling window calculationsinclude boostaccumulatorsaccumulatorshppinclude boostaccumulatorsstatisticsstatshppinclude boostaccumulatorsstatisticsrolling meanhppaccumulator setint statstagrolling mean acctagrolling windowwindow size 3as you see here i have set the window size to be three such that it is maintaining the mean average of the last three samples onlycan i amend that size at runtime perhaps based on a user settingif so and i increase the window size does the accumulator have extra internal state if it had already seen more than my new window size or would i have to wait for the extra values,['c++'] +128762,regular expression for valid subdomain in ruby i am attempting to validate a string of user input that will be used as a subdomain the rules are as followsbetween 1 and 63 characters in length i take 63 from the number of characters google chrome appears to allow in a subdomain not sure if it is actually a server directive if you have better advice on valid max length i am interested in hearing itmay contain azaz09 hyphen underscoremay not begin or end with a hyphen or underscoreedit from input below i have added the following4 should not contain consecutive hyphens or underscoresexamplesa valid0 valid not valid not valida not valida not valida not valid a not validaa valida valida valid0a validaa not valida 0 not validaa not valida not validmy issue is i am not sure how to specify with a regex that the string is allowed to be only one character while also specifying that it may not begin or end with a hyphen or underscorethanks,"['ruby-on-rails', 'ruby']" +128779,new self vs new static i am converting a php 53 library to work on php 52 the main thing standing in my way is the use of late static binding like return new staticoptions if i convert this to return new selfoptions will i get the same resultswhat is the difference between new self and new static,['php'] +128782,add new contact record to dynamics crm via rest call i know nothing about how dynamics works nor do i know anything about its data model nor do i understand its lingo so i apologize in advance if i am using the wrong termsi am building a website and when someone fills out a form on that site a new record needs to be created in dynamics crm i believe the latest version which is 2011this website is built in php so much of the sample code provided by ms does not apply ideally what i am looking for is some instructions or a link to a tutorial that looks like thismake a post request to this url pass it these parameterspassword application passwordfirstname contact first namelastname contact last nameaddress1 first line of street addressetc etcit will return the following info as a json stringerror code 0 for success otherwise error numbererror message description of error if anyi know that perhaps there is not a straightforward contact concept in the crm but rather some combination of opportunity and person and organization and i know that perhaps you do not just send it a password but rather some authentication token or cookie data and i know that it might require a soap call instead of a rest call although it seems the latest version supports rest which i would prefer because it is simpler and i know that it probably does not return json strings what i posted above is just an example of the format that my ideal answer would look like not trying to be demanding just that i know things can get lost in translation between the ms and php worlds sometimes so hopefully that helps explain what a useful answer to my feeble brain looks likeor perhaps i am totally offbase and doing this kind of thing is not possible without tons of customization on the dynamics sidebtw i am not currently concerned with 2way synchronization so i just need to tell the crm there is a new contact ideally it would automatically flag records it thinks are duplicates but that is not requiredthanks for any guidance or assistance you can provide,['php'] +128785,plinq asparallel with lower priority is it possible to run some of my plinq asparallel queries with a lower priority than othersor some with a higher priority than othersis this possible with plinq or will i have to avoid plinq and do all the stuff on my owneditupdatewould it be possible to callthreadsleep0inside the parallel executed method when i want to archive a lower priorityor is that a very bad practicehack,"['c#', '.net']" +128788,broadcasting a python function on to numpy arrays let us say we have a particularly simple function likeimport scipy as spdef funcx y return x ythis function evidently works for several builtin python datatypes of x and y like string list int float array etc since we are particularly interested in arrays we consider two arraysx sparray2 1 0 1 2y sparray2 1 0 1 2xx x spnewaxisyy yspnewaxis funcxx yythis returnsarray4 3 2 1 0 3 2 1 0 1 2 1 0 1 2 1 0 1 2 3 0 1 2 3 4just as we would expectnow what if one wants to throw in arrays as the inputs for the following functiondef func2x y if x y return x y else return x ydoing funcxx yy would raise an errorthe first obvious method that one would come up with is the spvectorize function in scipynumpy this method nevertheless has been proved to be not very efficient can anyone think of a more robust way of broadcasting any function in general on to numpy arraysif rewriting the code in an arrayfriendly fashion is the only way it would help if you could mention it here too,['python'] +128833,mathematica netlink in an aspnet application i am using the mathematica netlink platform to create a web service to format and calculate math problems however i am unable to get it workingi create it using this code logipdebugstarting the kernel linkif stringisnullorempty mathlinkarguments internelkernel mathlinkfactorycreatekernellinkelse internelkernel mathlinkfactorycreatekernellink mathlinkarguments logipdebugkernel link started internelkernelwaitandthiscardanswerthe value of mathlinkarguments is linkmode launch linkname cprogram fileswolfram researchmathematica70mathexethis piece of code is called from the application start method of the globalasaxcs filewhen it gets to the waitandthiscardanswer call it gives the server errorerror code 11 connected mathlink program has closed the link but there might still be data underway note the samplecode given with the netlink package both a console app and a winforms app worksediti copied the console app sample code given with mathematica into an aspnet page and it gave me the same error the first load and then on subsequent loads it gave meerror code 1 mathlink connection was lostedit2i forgot to mention that when i have procmon and task manager open while running my app i can tell that mathexe starts but it immediately exits which makes those error code make complete sensebut does not explain why that happened,"['c#', '.net', 'asp.net']" +128849,what does the operator mean looking through this c bigint library and found the bigintcpp file at the top there is a a comment at the top about compatibilitythis class was written for the g compiler and uses some of the g extensions like long double and the operatorwhat does that operator do i cannot find a reference to it anywhere else,['c++'] +128864,custom html attribute requires a custom helper i am trying to create a form with some custom data attributes on the inputsinput typetext datafamilydinosaursthis seemed like a nice clean way to have easy frontend access haha with jquery datafamilydinosaursdosomethingthe problem is i cannot get rails 303 to render the attribute ftext field question idpoll question classbiginput stylewidth98 attributesdatasubmit clear1 i have tried many permutations to no avail and cannot find an example of how to do this do i need to modify the text field helper to support any custom attributes,['ruby-on-rails'] +128885,naming conventions for universal applications i am writing a universal ios application ipad and iphone and find myself with massively long names for classes that cannot be shared between the two appsfamilyviewcontroller iphonehmfamilyviewcontrollera ipadhmdetailviewcontrollerb iphonehmdetailviewcontrollerb ipadhmand likewise the classes inside of these guys have the complete name device included mainly so that interface builder can easily use themi considered something like acontrollerah and bcontrollerah where aiphone and bipad but not excited about that option eitherwhat is the standing convention for classes like this in an ios universal application or am i hopefully missing something that obviates this necessity,"['objective-c', 'ios']" +128886,split string after x characters how to split string after 5 characters into an arrayexamplestring123456789expected outputoutput0 contain 12345output1 contain 6789,['php'] +128899,how to iterate through the builtin types in c i want to iterate through the builtin types bool char sbyte byte short ushort etc in chow to do thatforeachvar x in getbuiltintypesdo something on x,['c#'] +128912,how to pass jquery variables to php variable how do you pass a variable from jquery to php without a page refresh when i click on a checkbox i would like to pass a variable from jquery to php i am also using formdialogmy php codephpecho input nameopendialog typecheckbox classopendialog onclickcountchecked valuetaskid tdmy javascript codefunction countchecked var and inputcheckedlength var allvals inputcheckboxcheckedeachfunction allvalspushthisval seltextallvals select1valallvals alertallvals php taskidjrowtasktaskid echo arowtasktaskid checkboxclickcountchecked my jquery code mydialogdialog bgiframe true autoopen false modal true width 700 height500 resizable false open functionclosedialog 1documentbindclick overlayclickclose focus functionclosedialog 0 close functiondocumentunbindclick buttons submit function var bvalid true allfieldsremoveclass uistateerror bvalid bvalid checklength name username 3 16 bvalid bvalid checkregexp name az09az i username may consist of az 09 underscores begin with a letter if bvalid processdetails return false cancel function this dialog close inputnameopendialogattrchecked false opendialogclickfunction mydialogdialogopen closedialog 0,"['php', 'jquery']" +128922,soundpool sample not ready i have a wav file that i would like to use across my game currently i am loading the sound in oncreate of each activity in the game soundcount soundpoolloadthisrrawcount 1the sound will be played once the activity starts soundpoolplaysoundcount 09f 09f 1 1 1fproblem is at times i will hit the error sample x not readyis it possible to load the wav file once upon starting the game and keep it in memory and use it later across the game or is it possible to wait for 12 seconds for the sound to load finish,['android'] +128929,entity framework and business objects i have never used the entity framework before and i would like to try some personal projects implementing it to get my feet wet i see that entities can be exposed to the presentation layerbut i do not want certain fields exposed fields like modified dates and created dates and various other database fields how could i implement business objects and just expose the properties i need but still keep the objects serializable also what advantages does this have over linqtosql,['c#'] +128932,nhibernate returning complex object from sql function i have got an application witch uses nhibernate as an orm i have one persistent classpublic class match ientity public virtual int id get set public virtual string word get set public virtual int wordintervalbeginning get set public virtual int wordintervalending get set and i have an sql function on the server sidecreate function ftmatchtest returns table asreturn select mt1 mt2 case when mt1word mt2word then 1 else 0 end as sc from dbotmatchestest mt1 dbotmatchestest mt2i want to be able to call this function and map the result from it into the following classpublic class fresult public match match1 get set public match match2 get set public int sc get set is it possible to do it with nhibernate 30 is it possible to do it with fluentnhibernatethanks in advanceupdatedi map match class into tmatchestest tablestructure of tmatchestest table iscreate table dbotmatchestest id int identity11 not null word varchar50 not null wordintervalbeginning int not null wordintervalending int not null constraint pk tmatchestest primary key clustered id ascwith pad index off statistics norecompute off ignore dup key off allow row locks on allow page locks on on primary on primaryupdated2the solution i found on my own1 create named query like thisxml version10 encodingutf8 hibernatemapping xmlnsurnnhibernatemapping22 namespace consoleapplication8domainentities assemblyconsoleapplication8 resultset namefresultresset return aliasmatch1 classmatch return aliasmatch2 classmatch returnscalar columnsc typeint resultset sqlquery namegetfresult resultsetreffresultresset select match1 match2 case when match1word match2word then 1 else 0 end sc from dbotmatchestest match1 dbotmatchestest match2 sqlqueryhibernatemappingand execute the query like thissessiongetnamedquerygetfresult setresulttransformernew aliastobeanresulttransformertypeoffresult listfresultthis is the shortest and simples way i found so far to perform the task,['c#'] +128939,openxml spreadsheat saveas i have an excel 2007 spreadsheet that i edit with the openxml sdk 2i remove some rows etci would like to know how to save that spreadsheetdocument to another filename,['c#'] +128955,why is 1 2 in c false i got frustated with my other question so i wrote up this examplein c the below is true see demoint mainprintfd 1 2return 0output1in c it is false why is this falsealso i dont understand why i needed to create the bool operator in this example but not the one in my other question but no matter why is the below false it makes no sense to mebtw the logic making the below false is described hereusing systemusing systemcollectionsgenericusing systemlinqusing systemtextnamespace consoleapplication1 class program static void mainstring args myint a1 b2 bool resa b consolewritelineresult is 0 res class myint public int val public static bool operator truemyint t return tval 0 public static bool operator falsemyint t return tval 0 public static myint operator myint l myint r return lval rval public static myint operator myint l myint r return lval rval public static implicit operator myintint v return new myint val v public static implicit operator boolmyint t return tval 0,['c#'] +128960,how to convert a string to an array in php how to convert a string in array in php ie strthis is stringshould be like this arr0this arr1is arr2string the str splitstr 3 split the string in 3 character word but i want to convert the string after whitespace in an array,['php'] +128989,can an included php file know where it was included from for examplethis is indexphprequire onceheaderphpcan headerphp know it was included by indexphpediti found a solutionfunction backtrace filename includesname backtrace arraydebug backtrace if strposbacktrace array1filenamefalse return false else return true headerphpif backtrace filename includesindexphp echo indexphp,['php'] +128999,automating cucumber test scenarios for mysql i have built an important mysql database with a lot of view triggers functions and proceduresit is very hard to test and to not forget anything so i have written cucumber scenarios for all of the features of my db insert select etc request on functions an procedures etc and viewsthis help us a lot when we test the behavior of all this and even before writing view and other code it is very helpful to determinate want we really want to domy problem is after writing cucumber features we all test by hand in a mysql shelli am new in bddtdd and agile methods but i have done some search to know how to make some automation but found nothing very interesting for my caseis there somebody who can provide some interesting way to create automation for thisi do not know ruby but by example is it possible to use rspec directly with mysql with some examplesor in another language or any solution you can think ofthanks in advanceeditif found some interesting things with rspec and mysqlmysql support for cucumber nagiosmysql stepsrbmy problem is i do not have any knoledge with ruby rspec etci am working on it with the excellent pick axe book and rspec book from pragprogbut i will be very grateful for a little example of of rspec steps given the code belowthe mysql proceduredelimiter create procedure prc liste motif in texte text in motif varchar255 out nb motif int9 out positions textbegin declare er syntaxe condition for sqlstate 450 declare souschaine text declare positionactuelle int9 default 1 declare i int9 default 1 if lengthmotif lengthtexte then signal er syntaxe set message text bad request le motif est plus long que le texte mysql errno 400 end if set positions set nb motif 0 repeat set souschaine substring indextexte motif i set positionactuelle lengthsouschaine 1 if positionactuelle lengthtexte 1 then if lengthpositions 0 then set positions concatpositions end if set positions concatpositions positionactuelle set nb motif nb motif 1 end if set i i 1 until lengthsouschaine lengthtexte end repeatendthe cucumber featurefeature procedure prc liste motif in order to precess a string according to a given unit i want to know the number of units present in the chain and their positions knowing that the index starts at 1 background the database mydatabase in our sgbdr server given i have a mysql server on 1921680200 and i use the username root and i use the password xfe356 and i use the database mydatabase scenario outline using the procedure with good values in parameters given i have a procedure prc liste motif and i have entered texte for the first parameter and i have entered motif for the second parameter and i have entered nb motif for the third parameter and i have entered positions for the fourth parameter when i call prc liste motif then i should have out nb motif instead of nb motif then i should have out positions instead of positions exemples texte motif nb motif positions out nb motif out positions le beau chien e 3 2512 allo ll 1 2 allo w 0 an exemple of passed test by hand in mysql mysql h 1921680200 u root p xfe356welcome to the mysql monitor commands end with or gyour mysql connection id is 1server version 559 mysql community server gplcopyright c 20 2010 oracle andor its affiliates all rights reservedoracle is a registered trademark of oracle corporation andor itsaffiliates other names may be trademarks of their respectiveownerstype help or h for help type c to clear the current input statementmysql use mydatabasedatabase changedmysql set texte le beau chienquery ok 0 rows affected 0 secmysql set motif equery ok 0 rows affected 0 secmysql set nb motif nullquery ok 0 rows affected 0 secmysql set positions nullquery ok 0 rows affected 0 secmysql set out nb motif 3query ok 0 rows affected 0 secmysql set out positions 2512query ok 0 rows affected 0 secmysql call prc liste motiftexte motif nb motif positionsquery ok 0 rows affected 0 secmysql select nb motif out nb motif and positions out positions nb motif out nb motif and positions out positions 1 1 row in set 0 secthanks in advance for your help,['mysql'] +129009,geocodergetfromlocation throws ioexception on android emulator using android emulator 22 api 8i keep getting ioexception 0305 194211073 debugsntpclient58 request time failed javanetsocketexception address family not supported by protocol0305 194215505 warnsystemerr1823 javaioioexception service not availablethats my codeprivate locationmanager manager nulocationlistener locationlistener nulldouble latitude 0double longtitude 0listaddress mylist nullpublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain httptranslateget try manager locationmanager this getsystemservicecontextlocation service initlocationlistener managerrequestlocationupdatesmanagergps provider 0 0 locationlistener catch exception e todo autogenerated catch block eprintstacktrace private void initlocationlistener locationlistener new locationlistener override public void onlocationchangedandroidlocationlocation location if location null latitude locationgetlatitude longtitude locationgetlongitude try geocoder geocoder new geocoderweathercastdemothis localegetdefault listaddress addresses geocodergetfromlocationlocationgetlatitude locationgetlongitude 1 mylist geocodergetfromlocation locationgetlatitude locationgetlongitude 10 stringbuilder sb new stringbuilder if mylistsize 0 address address mylistget0 for int i 0 i address getmaxaddresslineindex i sbappendaddressgetaddresslineiappend n sbappendaddressgetlocalityappendn sbappendaddressgetpostalcodeappendn sbappendaddressgetcountryname catch ioexception e eprintstacktrace override public void onproviderthisabledstring arg0 todo autogenerated method stub override public void onproviderenabledstring provider todo autogenerated method stub override public void onstatuschangedstring provider int status bundle extras anyone has any ideai have managed to do it with emulator 21 api 7 but then the reverse geocoding always give an empty result anyone could confirm my codethanksthanksray,['android'] +129017,using apache httpclient for https i have enabled https in tomcat and have a selfsigned certificate for server auth i have created an http client using apache httpclient i have set a trust manager loading the server certificate the http client can connect with server no problem to see what is going on i enabled debugging systemsetpropertyjavaxnetdebug ssli saw the following which i can not understand at all adding as trusted cert subject cnme oumyhouse ohome lx stx cbb issuer cnme oumyhouse ohome lx stx cbb algorithm rsa serial number 0x4d72356b valid from sat mar 05 150651 eet 2011 until fri jun 03 160651 eest 2011 my certificate is thisplayed and is added to truststore as i see then trigger seeding of securerandomdone seeding securerandomhere is the part from debugging traces i do not get truststore is cprogram filesjavajre6libsecuritycacertstruststore type is jkstruststore provider is init truststoreadding as trusted cert subject cnswisign platinum ca g2 oswisign ag cch issuer cnswisign platinum ca g2 oswisign ag cch algorithm rsa serial number 0x4eb200670c035d4f valid from wed oct 25 113600 eest 2006 until sat oct 25 113600 eest 2036adding as trusted cert subject emailaddress cn ouvalicert class 1 policy validation authority ovalicert inc lvalicert validation network issuer emailaddress cn ouvalicert class 1 policy validation authority ovalicert inc lvalicert validation network algorithm rsa serial number 0x1 valid from sat jun 26 012348 eest 19 until wed jun 26 012348 eest 2019it seems that it also uses the default java trust store my question is why does this happen in my code i specify explicitly a specific truststore to use via truststoremanagers i was expecting only this to be used it seems that both my truststore and javas default is being used is this how it is supposed to work updatei tried the following systemoutprintlntmf notmfgettrustmanagerslengthsystemoutprintlnclass is tmfgettrustmanagers0getclassgetname i thought that i should see 2 trust managers since 2 keystores mine and javas default appear to be usedbut the result was only 1 trust manager tmf no1class is comsunnetsslinternalsslx509trustmanagerimpl update2 as you see in the code bellow i specify my keystoremy expectation is that only this should be used not this and cacert as well httpclient client new defaulthttpclient sslcontext sslcontext sslcontextgetinstancetls trustmanagerfactory tmf trustmanagerfactorygetinstancetrustmanagerfactorygetdefaultalgorithm keystore ks keystoregetinstancejks file trustfile new fileclienttruststorejks ksloadnew fileinputstreamtrustfile null tmfinitks sslcontextinitnull tmfgettrustmanagersnull sslsocketfactory sf new sslsocketfactorysslcontext sfsethostnameverifiersslsocketfactoryallow all hostname verifier scheme scheme new schemehttps sf 443 clientgetconnectionmanagergetschemeregistryregisterscheme httpget new httpgethttpslocalhost8443myapp httpresponse httpresponse clientexecutehttpgetdoes not make sense to me,['java'] +129020,programmatically choose item in select drop down i have a drop downselect option value11option option value22optionselecthow would i select item 2 programmatically,['html'] +129023,how to convert a java swing application to work on android so i built a program in java using swing for the interface and i did not realize how difficult it would be to convert it to be used as an android application is there any way for me to easily convert or rebuilt the program to be sold in the android market place if not can anyone point me toward any resources to help build a android,"['java', 'android']" +129024,horizontally scrolling list of images i am trying to create a horizontally scrolling list i am going to replace this with a fancy version when javascript is enabled but i want the markup and css to look and work fine without javascript on reasonably modern browsers any suggestions that uses javascript in any way is offmy current markupcss works but heres what i do not like about itthe current markup specify a very wide ul ie 10px and a container that scrolls on this is there a way to avoid this and instead have the width expands based on its content ie the blue background should not be therethere are two extraneous divs those with id extra1 extra2 that is just for styling purpose is there a way to eliminate this extra divif there is not enough image to fill the page width the scrollbar should collapse but currently it does not because i have a very wide ul which cannot collapsethe a tag are separated by the horizontal list i preferably want to keep them together is there a way to have them close together and cleanly separate them in cssaside do you know of any tutorials that thiscussed this sort of thing i have seen several tutorials that demonstrated having the whole page to scroll and i took some ideas from those but i cannot find any that demonstrated scrolling ulol elementextra info that might helpthe width of the page is static ie it is not fluidelastic layoutthe images in the page is dynamically generated from php and the number of images can changethe width of the thumbnails are welldefinedstripped down live example,"['html', 'css']" +129043,why does datetime to unix time use a double instead of an integer i am needing to convert a datetime to a unix timestamp so i googled it looking for some example codein just about all the results i see they use double as the return for such a function even when explicitly using floor to convert it to an integer unix timestamps are always integers so what problem is there with using either long or int instead of double static double converttounixtimestampdatetime date datetime origin new datetime1970 1 1 0 0 0 0 timespan diff date origin return mathfloordifftotalseconds,"['c#', '.net']" +129070,in c is there a way to go to a specific line in a text file if i open a text file using fstream is there a simple way to jump to a specific line such as line 8,['c++'] +129092,codeigniter from post data not going through im trying to make a file upload in codeigniter how ever when i add enctypemultipart formdata no post data will go through at all not even the other fields however when i dont add it i can get the other post data but of course no file upload whats going wrong here here is my view and controllerviewh2add a new albumh2form enctypemultipartformdata methodpost actionphp echo base urlindexphpphotonewalbum table stylemarginleft5px tr td album nametd tdinput typetext namename td tr tr td photo zip filetd tdinput typefile nameuserfile size20 td tr tr tdtd tdinput typesubmit valueupload photo file td tr tableformcontroller only containsvar dump postresult isarray0,['php'] +129095,need to speed up automapperit takes 32 seconds to do 113 objects hi i have some major problems with auto mapper and it being slow i am not sure how to speed it upi am using nhibernatefluent nhibernate and aspnet mvc 30serializable public class test public virtual int id get private set public virtual string name get set public virtual string description get set public virtual datetimedate get set public virtual ilistreminder reminders get set public virtual ilistreminder2 reminders2 get set public virtual test2 test2 get set public test reminders new listreminders reminders2 new listreminders2 so as you can see i got some properties some other classes as in my database i have references between themi then do thisvar a get all items returns a collection of test2var listmyviewmodel collection new listmyviewmodel foreach test2 t in a myviewmodel vm mappermaptest2 myviewmodelt vmsetdateformattdatetimedate datefiltersalltostring collectionaddvm view model public class myviewmodel public int id get private set public string name get set public string description get set public datetime datetimedate get set public string formatedduedate get set public string test2prefix get set public string test2backgroundcolor get set public string selecteddatefilter get set public bool descstate get set public bool alertstate get set summary constructor summary public myviewmodel default values selecteddatefilter all descstate false alertstate false summary sets the date formatter string used summary param namedateformatparam public void setdateformatdatetime duedate string datefilter simple if statement to format date mapping mappercreatemaptest2myviewmodelformemberdest destdescstate opt optresolveusingdescstateresolver formemberdest destalertstate opt optresolveusingalertstateresolver resolverspublic class alertstateresolver valueresolvertask bool protected override bool resolvecoretask source if sourcereminderscount 0 sourcereminders2count 0 return true else return false public class descstateresolver valueresolvertaskbool protected override bool resolvecoretask source if stringisnulloremptysourcedescription return false else return true ignore the weird names and any typos my real object works just fine and makes senseso i used the stop watch and did thisstopwatch a new stopwatch foreach test2 t in a astart myviewmodel vm mappermaptest2 myviewmodelt astop vmsetdateformattdatetimedate datefiltersalltostring collectionaddvm var b aelapsed comes back with 32 secondsi need to optimized this very badly,['c#'] +129112,android compatibility package does not include activitygetfragmentmanager i started trying to add fragments to my android app which is based on 21 using the android compatibility package that just came out on march 3rd i included the library into my project and started moving the code from my activitybased class to a fragmentbased one but i noticed that the fragment examples from google seem to rely on the fact that the activity class in 30 honeycomb has the new method getfragmentmanager it seems to be an integral hook into the fragment systemi have tried to look inside the compatibility package library for some included activity implementation that has getfragmentmanager but i cannot find it does anyone know where i can find getfragmentmanager so i can include fragments for honeycomb compatibility or if not do you know how i can include fragments without using a fragmentmanager,['android'] +129116,getting an array result from json decode how do i get an array as a result from json decodei had an array like thisarray array mod status yes mod newsnum 5and i saved this in database like json encodemod statusyesmod newsnum5now i want to get array again from database but when i usedecode json decodedbresulti getstdclass object mod status yes mod newsnum 5instead of an array how can i get an array instead of an object,['php'] +129121,filter other than this how to filter the current item from the list of items egdivclick function thisvalthis is clicked get the items that are not clicked div returns a list of items and one of them is clicked how to get the list of item that are not clickednote i am not looking the solution that adds attribute to the clicked item or unlicked item and filters it,['jquery'] +129160,apache server ignores htaccess i am trying to get a website working on my test environment but somehow it is not working i can load the normal index page but when i want to access pagetest it throws an error saying the page does not exists my log saysfile does not exist homepage urlwpagewhich is in fact true but it should got to my page controller instead and load the test methodmy htaccess looks like turn on url rewritingrewriteengine on installation directoryrewritebase protect hidden files from being viewedfiles order denyallow deny from allfiles protect application and system files from being viewedrewriterule applicationmodulessystemb 0 l allow any files or directories that exist to be thisplayed directlyrewritecond request filename frewritecond request filename d rewrite all other urls to indexphpurlrewriterule indexphp0 ptmy vhost configuration looks likevirtualhost 80 servername page url include etcapache2vhostsdvhcoinclude documentroot homepage urlw logging customlog varlogapache2access log common errorlog varlogapache2error log this should be changed to whatever you set documentroot to directory homepage urlw possible values for the options directive are none all or any combination of indexes includes followsymlinks symlinksifownermatch execcgi multiviews note that multiviews must be named explicitly options all does not give it to you the options directive is both complicated and important please see for more information options indexes followsymlinks allowoverride controls what directives may be placed in htaccess files it can be all none or any combination of the keywords options fileinfo authconfig limit allowoverride all controls who can get stuff from this server order allowdeny allow from all directory ifmodule alias module redirect allows you to tell clients about documents that used to exist in your servers namespace but do not anymore the client will make a new request for the document at its new location example redirect permanent foo alias maps web paths into filesystem paths and is used to access content that does not live under the documentroot example alias webpath fullfilesystempath if you include a trailing on webpath then the server will require it to be present in the url you will also likely need to provide a directory section to allow access to the filesystem path scriptalias this controls which directories contain server scripts scriptaliases are essentially the same as aliases except that documents in the target directory are treated as applications and run by the server when requested rather than as documents sent to the client the same rules about trailing apply to scriptalias directives as to alias scriptalias cgibin varwlocalhostcgibin ifmodule varwlocalhostcgibin should be changed to whatever your scriptaliased cgi directory exists if you have that configured directory homepage urlw allowoverride none options none order allowdeny allow from all directoryvirtualhosti am using gentooany help would be appreciated,['php'] +129161,when to use byte array when byte buffer what is the difference between a byte array byte buffer also in what situations should one be preferred over the othermy usecase is for a web application being developed in java,['java'] +129168,not using parentheses in constructor call with new c possible duplicatedo the parentheses after the type name make a difference with new so i had in my mainclass pc new classit was working asclass pc new classi realized just today that i had omitted the parentheses so i was hit by the opposite of the most vexing parse in a waymy question are these two forms equivalent,['c++'] +129190,php array unique for arrays inside array i need like array unique for arrays inside arraythe case should be equal but output not equalphparrarrayarraya1arraya2arr2array uniquearrifarr2arr echo equalelse echo not equalhow should be code fix to get output equalthanksyosef,['php'] +129192,facebook sso example not working an error ocurred please try again later i am trying to integrate facebook into my app and so have followed the tutorial at facebook android but i cannot get the first example single signon to work when my app loads up i get the facebook dialog but it just says an error occurred please try again later with a facebookstyle ok button at the bottom and there is nothing in logcati followed the steps in the tutorial but i am guessing there is something wrong with the app id or the hashkey generated by keytool here are the steps i followedclone fb gitcreate fbsdk projectcreate own fb project and link the fbsdk as a libraryi then did the keytool cmd with openssl and input the password android as suggested by others on stackoverflowi went to developersfacebookcom and created a new appin edit settingsmobile and devices i put my hash in the box providedin edit settingsmobile and devices i chose native app as application typeback in the app i copy and pasted the sso example codei changed the your app id in the facebook constructor to the app id shown on the developersfacebokkcom page for my new appi ran the app on my phonei do not know why there is nothing in logcat but when i install it the console always without fail says theactivitymanager warning activity not started its current task has been brought to the frontand i cannot find any logcat reference to my app or the error i was getting from the facebook sdk which was facebookproxyauth4828 failed to read calling packages signaturei have been at this for a few hours now and any help would be greatly appreciated i cannot believe the facebook sdk and help is so sketchy for android facebook should be ashamed of themselvesthanksinfinitifizz,['android'] +129205,add one year to datetime with php datausertime 20110307 003345 how can we add 1 year to this date something like newdata datausertime 1 year or newdata 20120307 003345thanksadam ramadhan,['php'] +129209,making changes to the devise user controller in rails i have started using devise for my rails app however i need to make some changes to the controller logic that devise has my problem is that i assign users roles and i want to put in paramsuserrole ids in the update action so if all the roles are unchecked then it actually workswhats the best way to do this,['ruby-on-rails'] +129219,how to backup sql server to sql file in back up i only get a back file but i would like to create sql file,['sql'] +129220,codeigniter timezone menu and date default timezone set i make use of codeigniters timezone menu which gives a drop down box of time timezones and i am wondering how are we supposed to make use of these timezones with phps date default timezone setan example of codeigniters timezone is up1 however you cannot use that with phps date default timezone set as the string it takes in should be something like europeberlinthe question is is there a way to convert a codeigniter timezone string to a php one that can be accepted by the date default timezone set,['php'] +129226,sorting a python list by two criteria i have the following list created from a sorted csvlist1 sortedcsv1 keyoperatoritemgetter1i would actually like to sort the list by two criteria first by the value in field 1 and then by the value in field 2 how do i do this,['python'] +129258,how to define c preprocessor variable in makefile i have a c preprocessor written like this ifdef cpp variable xy endifplease anyone tell me how to define this in makefilethanks,['c++'] +129270,could python be compiled to run on the v8 engine presumably javascript is compiled to some kind of bytecode to run on the v8 engine is python a similar enough language that we can imagine python being compiled to the same bytecode and run on the v8any projects trying to do this,['python'] +129285,why pear math biginteger48 0 case math biginteger mode default i used pearmathbigintegerphpphp 525 cli ubuntubuta new math biginteger48echo a tostring 0whyis it a bugit is specific of math biginteger mode default 3528 function int2bytesxpackn 48 0we needif48stringxthisvaluearray48return,['php'] +129298,how do you pinpoint a word or a selection in the entire document i am trying to highlight a part of the text on my website this highlighted text will be saved for the specific user in a database and when the document is opened again it will show the previously highlighted text i assumed i would be using javascript to highlight the text but i cannot seem to find a way to pinpoint where the word is that i am highlightingfunction getseltext var txt if windowgetselection txt windowgetselection else if documentgetselection txt documentgetselection else if documentselection txt documentselectioncreaterangetext else return return txti am using that to get the selection but i cannot figure out where the selection is in the text the biggest annoyance is when i have duplicates within the line or text so if i were to use search then i would find the first instance and not the one i was looking forso the question is how do you pinpoint a word or a selection in the entire document,"['javascript', 'html']" +129311,why can c not automatically provide threadsafe access to events where ccli can from the msdn documentation for eventhandler delegatein contrast to the c and visual basic examples the visual c example code does not require you to create a threadsafe temporary variable visual c version automatically provides threadsafe access enabling you to raise the event directlywhy can c not automatically provide threadsafe access to events where ccli can,"['c#', '.net']" +129316,give border title in div can i do like this in htmli want to add border title general information in this image on my div is it possible how to do itnotethe image is not html pages image its a java apps image,"['html', 'css']" +129320,how to set the content type on the servlet i am using a simple servlet which sends back document contents from the database as a byte array i would like to set a content type so that it has an appropriate extension while it is being retrieved via a doget calli do have the type of the document stored as a metadata in the database eg png gif png xls docx what should i set as the content type so that it retains the file extensionthe file gets downloaded with a name of doc how do i set the filename on the servlet for the data being downloaded,['java'] +129361,reschedule timer in android how can i reschedule a timer i have tried to cancel the timertimertask and and schedule it again using a method but its showing an exception errorexception errorjavalangillegalstateexception timertask is scheduled alreadycode i have used it private timer timer new timeralerttimertruepublic void rescheduletimerint duration timercancel timerscheduletimertask 10l duration 10l,['android'] +129362,how to create a mobile oriented multiplatform shared library in java i have a java application that runs on blackberry jde 45 i want to port this application to android and be able to maintain the 2 applications simultaneously i may also want to port this application to other java platforms j2me i understand that a good part of the code will have to be specific to each platform ui and other stuff but i also feel that a lot of the code could should be shared domain related classeswhat is the best way to achieve this and what are the pitfalls to avoidi have been able so far to create a jar with all my shared classes that i have been able to integrate into my blackberry application using preverify and rapc butthe jar is a j2se library how can i make sure that it will run or even compile on blackberry android or j2mei am also using a json library targeting j2me this library seems to make use of some kind of preprocessing directives cldc see how can i use or convert this library using the right preprocessing definitions,"['java', 'android']" +129371,how do i perform binary search on a text file to search a keyword in python the text file contains two columns index number5 spaces and characters30 spacesit is arranged in lexicographic order i want to perform binary search to search for the keyword,['python'] +129380,android annotation to run on ui thread is it possible to annotate method to run code in uithreadrunonuithreadnew runnable public void run my codelooks too complex to use it often,['android'] +129411,getting a headlessexception no x11 thisplay variable was set exception in thread main javaawtheadlessexception no x11 thisplay variable was set but this program performed an operation which requires it at javaawtgraphicsenvironmentcheckheadlessgraphicsenvironmentjava159 at javaawtwindowwindowjava432 at javaawtframeframejava403 at javaxswingjframejframejava202 at drawguidrawguijava15 at shapecreatorshapecreatorjava31 at shapecreatormainshapecreatorjava138what does this error message mean and how can i solve it,['java'] +129415,content of div is longer then div itself when width is set to 100 i have div of fixed width containing only input text box and width of that input is set to 100 i expect it to fill the div but instead it is slightly longerdemonstration codehtmldiv classcontainer input classcontent idtext1 typetext divcsscontainer width 300px height 30px border thin solid redcontent width 100result firefoxthis happens also in ie 8 chrome safari the overflow width seems to vary in different browsershow do i make the content to exactly fill the width of the div,"['html', 'css']" +129418,problem with passing booleans to update attributes i have got the following modelclass guestcatering activerecordbase validation validates name presence true validates order number presence true validates orderable presence trueendbut when i will try to update an existing guestcatering with the following codeguest cateringupdate attributesorderable falsethe guest catering variable is a valid guestcatering objectthe guest catering object has errors after the update like thatorderable cannot be blanknilbut when i pass a orderable true everything is fine and no errorswhats wrong here why cannot i set orderable to false,"['ruby-on-rails', 'ruby']" +129466,change default python coding style in python i am following camelcase naming style i checked my code with pylint and it gives error for not following lower case with underscores style also i use netbeans ide for coding this ide gives warning for not following lower case with underscores style how to tell pylint and netbeans that i am following camelcase naming style not lower case with underscoresthanks,['python'] +129473,iframe behaviour of onload vs addeventlistenerload i have been playing around with adding hidden iframe elements to a page and i want to manipulate the dom of the these once loaded i have noticed that i cannot start manipulating the dom immediately after adding the iframe to a page since it has not loaded yet this cannot be done with the domcontentloaded event since that fires against the document which does not exist in the iframe until it is added to the page so we have to use the load eventhere is some test codevar iframe documentcreateelementiframeiframeonload function consolelogloaded documentgetelementsbytagnamebody0appendchildiframethis works as expected however when i change it to addeventlistener it does not even get added to the domvar iframe documentcreateelementiframeiframeaddeventlistenerload function consolelogloaded documentgetelementsbytagnamebody0appendchildiframei have not tested attachevent in ieanyone shed any light on this,"['javascript', 'html']" +129477,is it a good practice to avoid using session state in aspnet mvc if yes why and how it is not explicitly written somewhere but i felt so after reading few blogs on aspnet mvc just got curious and thought of asking it hereupdate i am not asking about memorystorageram concerns on server for them there is a solution to store session out of process i know that i am curious that are there any scenarios where we had to use session in webforms but we can avoid it now in mvc taking benefit of the nice structured way offered by mvc,['asp.net'] +129478,asking questions in rake tasks i have a rake task that is called from another rake taskin this rake task i need to ask the user for some text input and then depending on the answer either continue or stop everything from continuing including the calling rake taskhow can i do this,['ruby'] +129483,does this javascript code follow the midpoint thisplacement algorithm i am trying to use the midpoint thisplacement algorithm using javascript and canvas as recommended on gamedevstackexchangecomthe code below generates points where the array index is the x position and its value is the y positionvar createterrain functionchops range chops chops 2 range parseintrange 100 if chops 8 return var cycle parseintwidth chops for var i 0 i width i cycle var y height 2 getrandomnumberrange range terraini y chops 2 range 05 createterrainchops rangegetrandomnumbers arguments are min and max width and height are respective of the canvasthis produces something likeit seems pretty choppy but that may just be how it ishave i got this algorithm right if not what is wrong and can you point me in the right direction,['javascript'] +129490,wordpress path url in js script file i added custom script wp enqueue scriptfunctions get bloginfotemplate url jsfunctionsjs search null falseit works great except in the functionsjs i haveresetstylebackground urlimagessearchfield clearpng norepeat top leftthis used to work before until i changed to pretty permalinks and htaccessthe folder hierarchy is likethemenamejs themenameimages the images and js folder are in themename folderi tried images image images normally it should go back 1 level wherever the js file is locatedi do not want to use full pathis there another way that wordpress can recognize in the javascript file to have the correct pathcurrently i am just confused what i am doing wrong,['javascript'] +129513,rails rest routing dots in the resource item id i have following in my routesrbresources users except new create do get friends as friends on member to usersfriendsendand following in my userrbdef to param selfloginendand when for example user with dots in login for example anything comes from facebook rails gives routing error no route found i suppose that is because it recognises anything after dot as a format or because of route constraints how can i come over this error,['ruby-on-rails'] +129540,handling to onchange event of autocompletetextfield in wicket i am writing an autocomplete component for a webapp using java and wicketis there a way to handle the onchange event to run some code when the user selects one of the options of the autocomplete list i tried doing this in the autocompletetextfield setoutputmarkupidtrue addnew ajaxeventbehavioronchange override protected void oneventajaxrequesttarget target systemoutprintlngetinput but the getinput method returns null is there a way to react to the onchange event and to be able to read what the user has enteredthanks for you time and knowledge,['java'] +129542,jquery datatables sort icons put on row below the actual text i have scoured through all my css files and there are a lot of them in addition to looking atremoving the sdom settings for my jquery datatables plug in but for some reason the sort icon up and down arrows next to my text is place below the text as if an html was somehow input has anybody ever had this happen before,['jquery'] +129544,cs inline how strong a hint is it for gcc and clangllvm in c the keyword inline serves two purposes first it allows a definition to appear in multiple translation units second it is a hint to the compiler that a function should be inlined in the compiled codemy question in code generated by gcc and clangllvm does the keyword inline have any bearing on whether a function is inlined if yes in what situations or is the hint completely ignored note this is a not a language question it is a compilerspecific question,['c++'] +129548,writer or outputstream i am designing a library where a class should have an ability to be able to convert itself internals into text which class shall i use outputstream or writer and what is the key difference between them in my casepublic interface memento void saveoutputstream stream void savewriter writerwhich one,['java'] +129553,jquery datatables filter column with comparison operators i have been using the datatables jquery plugin with the filter plug in and it is awesome however i was wondering if it is possible to filter table columns by row using a comparison operator eg or before a value in the filter input at the bottom of the tablethere is way to filter by range using input fields that accept a max and min value however i would like to forgo adding two additional input fields and somehow parse the input of this columnthe row i want to filter is populated with only integers age valuessome examples of desire behaviourinput results 20 less than than 20 20 greater than 2020 80 between 20 and 80 20 not 20anyone have experience modifying the behavior of the filter plugin to achieve this behavior thanksediti would like to be able to directly type in the comparison operator into these input boxes if an operator is detected it will filter based on the operator if no filter operator is detected i would like it to filter normallythe html for the filter input looks like thistfoot tr th class uistatedefault input typetext clasearch init valueage namesearch age th th class uistatedefault input typetext clasearch init valuepd status namesearch age of onset th trtfootthanks,"['javascript', 'jquery']" +129557,stl iterators prefix increment faster possible duplicatespreincrement faster than postincrement in c true if yes why is itis there a performance difference between i and i in c i got told that when using the stl and it is iterators i should always use iter instead of iteri quote because it can only be faster never sloweris this true,['c++'] +129564,extern enum in c i have an enum i have declared in some h filetypedef enum none one two three myenumin a seperate cpp i cannot do this extern enum myenum worksextern myenum two makes sence two is not an instance of myenumhow would one do so without including the whole header where the enum is declared,['c++'] +129580,curl post format for curlopt postfields when i use curl via post and set curlopt postfield do i have to urlencode or any special formatfor example if i want to post 2 fields first and lastfirstjohnlastsmithwhat is the exact codeformat that should be used with curlchcurl initcurl setoptch curlopt url urlcurl setoptch curlopt returntransfer 1curl setoptch curlopt post 1curl setoptch curlopt postfields datareplycurl execchcurl closech,['php'] +129588,grand central thispatch gcd vs performselector need a better explanation i have used both gcd and performselectoronmainthreadwaituntildone in my apps and tend to think of them as interchangeablethat is performselectoronmainthreadwaituntildone is an objc wrapper to the gcd c syntax i have been thinking of these two commands as equivalentthispatch syncthispatch get main queue self doityes self performselectoronmainthreadselectordoit withobjectyes waituntildoneyesam i incorrect that is is there a difference of the performselector commands versus the gcd ones i have read a lot of documentation on them but have yet to see a definitive answer,"['iphone', 'objective-c', 'ios']" +129602,can i have h2 autocreate a schema in an inmemory database i have already seen the h2 database in memory init schema via springhibernate question it is not applicable herei would like to know if there is a setting in h2 that will allow me to autocreate a schema upon connecting to it if it helps i am only interested in the inmemory caseh2 supports various semicolonseparated modifiers at the end of the url but i did not find one for automatically creating a schema is there such a feature,"['java', 'sql']" +129606,turn off a warning in sqlalchemy i am using sqlalchemy with reflection a couple of partial indices in my db make it dump warnings like thissawarning predicate of partial index i some index ignored during reflectioninto my logs and keep cluttering it does not hinder my application behavior i would like to keep these warnings while developing but not at production level does anyone know how to turn this off,['python'] +129608,is it possible to have pipe between two child processes created by same parent linux posix i have multiple child forked by the same parent and i try to construct pipe connection between all these child processes like a linked list structure child 1 sends data to child2 child 2 to child 3 child and to child 1 is there any proper way to do it in addition if i create and communicate between processes how i force the parent to wait all the process to finish their job since wait or waitpid waits for first finished process but i need to wait them all it is the another question that arisesthanks,['c'] +129609,compare two vectors c i was wondering is there any function to compare 2 string vectors to return the number of differentor the same elements or i have to iterate over both of them and test item by itemthanks,['c++'] +129617,if an activity is killed does the asynctask live on i think i know the answer to this but does an asynctask continue to live on once its calling activity has been finished protected void onpreexecute toastmaketextgetapplicationcontext your data is processing toastlength long finish edit so far two different answers,['android'] +129625,can i override the javascript function object to log all function calls can i override the behavior of the function object so that i can inject behavior prior t every function call and then carry on as normal specifically though the general idea is intriguing in itself can i log to the console every function call without having to insert consolelog statements everywhere and then the normal behavior goes oni do recognize that this will likely have significant performance problems i have no intention of having this run typically even in my development environment but if it works it seems an elegant solution to get a 10 meter view on the running code and i suspect that the answer will show me something deeper about javascript,['javascript'] +129641,use pastefromword filtering on all pasted content in ckeditor 3 ckeditor is a great editor and the pastefromword plugin is very good i would like to have the filtering provided by the plugin applied to all pasted text for example when pasting from word all fonts and sizes are stripped this does not happen when pasting from an emailthat said i came up with the following solution and posting it here to get some feedback i am wondering if i made it too complicated or if there is an easier way i kind of just copied the code from pastefromwordpluginjsvia my custom configjsckeditorconfigpastefromwordcleanupfile pastefromwordjsckeditoron instanceready function ev paste event to apply paste from word filtering on all text the pastefromword plugin will only process text that has telltale signs it is from word use this hook to treat all pasted text as if it is coming from word this method is a slightly modified version of code found in pluginspastefromwordpluginjs eveditoron paste function evt var data evtdata editor evteditor content pastefromwordhappened is a custom property set in custom pastefromwordjs so that filtering does not happen twice for content actually coming from word it is a dirty hack i know if editorpastefromwordhappened reset property and exit paste event editorpastefromwordhappened 0 return var loadrules function callback var isloaded ckeditorcleanword if isloaded callback else ckeditorscriptloaderload ckeditorconfigpastefromwordcleanupfile callback null false true return isloaded content datahtml no need to filter text if html tags are not presence so perform a regex to test for html tags if content testcontent var islazyload loadrules function if islazyload editorfirepaste data else data html ckeditorcleanword content editor reset property or if user tries to paste again it would not work editorpastefromwordhappened 0 islazyload evtcancel,['javascript'] +129642,concurrently retrieve select or create insert new row in generic sql without conflicts i have a system which has a complex primary key for interfacing with external systems and a fast small opaque primary key for internal use for example the external key might be a compound value something like given name varchar family name varchar zip code char and the internal key would be an integer customer idwhen i receive an incoming request with the external key i need to look up the internal key and heres the tricky part allocate a new internal key if i do not already have one for the given external idobviously if i have only one client talking to the database at a time this is fine select customer id from customers where given name foo and then insert into customers values if i do not find a value but if there are potentially many requests coming in from external systems concurrently and many may arrive for a previously unheardof customer all at once there is a race condition where multiple clients may try to insert the new rowif i were modifying an existing row that would be easy simply select for update first to acquire the appropriate rowlevel lock before doing an update but in this case i do not have a row that i can lock because the row does not exist yeti have come up with several solutions so far but each of them has some pretty significant issuescatch the error on insert retry the entire transaction from the top this is a problem if the transaction involves a dozen customers especially if the incoming data is potentially talking about the same customers in a different order each time it is possible to get stuck in mutually recursive deadlock loops where the conflict occurs on a different customer each time you can mitigate this with an exponential wait time between retry attempts but this is a slow and expensive way to deal with conflicts also this complicates the application code quite a bit as everything needs to be restartableuse savepoints start a savepoint before the select catch the error on insert and then roll back to the savepoint and select again savepoints are not completely portable and their semantics and capabilities differ slightly and subtly between databases the biggest difference i have noticed is that sometimes they seem to nest and sometimes they do not so it would be nice if i could avoid them this is only a vague impression though is it inaccurate are savepoints standardized or at least practically consistent also savepoints make it difficult to do things in parallel on the same transaction because you might not be able to tell exactly how much work youll be rolling back although i realize i might just need to live with thatacquire some global lock like a tablelevel lock using a lock statement oracle mysql postgres this obviously slows down these operations and results in a lot of lock contention so i would prefer to avoid itacquire a more finegrained but databasespecific lock i am only familiar with postgress way of doing this which is very definitely not supported in other databases the functions even start with pg so again it is a portability issue also postgress way of doing this would require me to convert the key into a pair of integers somehow which it may not neatly fit into is there a nicer way to acquire locks for hypothetical objectsit seems to me that this has got to be a common concurrency problem with databases but i have not managed to find a lot of resources on it possibly just because i do not know the canonical phrasing is it possible to do this with some simple extra bit of syntax in any of the tagged databases,"['mysql', 'sql']" +129648,pass array into vararg in ruby the ruby exec function takes a vararg for its second parameter to provide arguments to the program being executed however i would like to pass an array of arguments for various reasons i could work around this by just giving exec a completed string but that involves the shell and escaping possible parameters additionally as far as i can tell collapsing the arguments into one string will pass them as one argument to my program i want their thistinctness to be preserved is it possible to pass an array to a varargs argument in a ruby function note that in this case i cannot modify exec to accept any wrapping or shifts,['ruby'] +129667,specflow reusable step definitions is there a way to have specflow reuse step definitionsin other tools i have used a givenwhenthen base class that contains methods such aswhenanorderiscreated this inits a protected order member to be used by inheriting classesjust cant seem to get this working with specflow doesnt seem to like inheritanceis there a way to share steps across featuresmany thanks,['c#'] +129675,what exactly does using the application context mean i am new to this and i am sorry if this is a really dumb question i am just trying to clarify things my book says i can retrieve application context for process by using the getapplicationcontext method i just really do not know where to type this or what to do with any of it i can go to the hierarchy but what do i do with all the script there also where would i write activity callbacks in the mainxml an exercise wants me to add a logging tag to my project but i am not sure how to do this the exact text sayswithin the oncreate callback method add an informational logging message using the logi method and another exercise says toimplement some of the activity callback methods in addition to oncreate such as onstart add a log message to each callback method and then run the application normally as these seem like basic questions can someone please help me i am using the android sdk and eclipse i have made the hello world application but i have no idea what to do with context or retrieving resources please help,['android'] +129700,how to get last inserted id i have this codestring insertsql insert into aspnet gameprofilesuseridgameid valuesuserid gameidusing sqlconnection myconnection new sqlconnectionmyconnectionstring myconnectionopen sqlcommand mycommand new sqlcommandinsertsql myconnection mycommandparametersaddwithvalueuserid newuserid mycommandparametersaddwithvaluegameid newgameid mycommandexecutenonquery myconnectionclosewhen i insert into this table i have an auto increment int primary key column called gamesprofileid how can i get the last inserted one after this so i can use that id to insert into another table,"['c#', 'sql']" +129716,systembadimageformatexception could not load file or assembly cwindowsmicrosoftnetframework64v4030319installutilexe c produkcijadebugdynamichtmltoolexemicrosoft r net framework installation utility version 40303191copyright c microsoft corporation all rights reservedexception occurred while initializing the installationsystembadimageformatexception could not load file or assembly filec produkcijadebugdynamichtmltoolexe or one of its dependencies an attempt was made to load a program with an incorrect formatcwindowsmicrosoftnetframework64v4030319service is x86 compiled even both computers are x64 and it works on my computer here in server where is win 2008 i get this errori try solutions from google but none workslike write here i have x86 project,['c#'] +129742,android and thisplaying multilined text in a textview in a tablerow i am thisplaying a tablelayout with rows as followsxml version10 encodingutf8tablerow xmlnsandroid androidlayout widthmatch parent androidlayout heightwrap content relativelayout androidlayout widthmatch parent androidlayout heightwrap content textview androidlayout widthmatch parent androidlayout heightwrap content androidididone androidlayout marginleft10dip androidtextcolorb0171f textview androidlayout widthmatch parent androidlayout heightwrap content androidlayout belowidone androidididtwo androidlayout marginleft10dip androidellipsizenone androidsinglelinefalse androidscrollhorizontallyfalse androidmaxlines10 androidtextcolorandroidcolorblack relativelayouttablerowi am hitting this with everything i can find here and can think of to permit the text to wrap on many lines but to no avail the text is always forced to a single line running off the screen it might matter that i am working inside a tablerow here and so far as i can tell this has not been treated on this siteso how do i force my second textview to wrap to many lines,['android'] +129744,iphoneipad google maps iframe embed i have a google map embedded in an iframe just something likeiframe width425 height350 frameborder0 scrollingno marginheight0 marginwidth0 srcampll5115178610415039ampspn23511951723633ampthampz5ampoutputembediframein browsers this is just fine but the iphoneipad tries to load an app which seems just to work fine dont have one myself but the page loads and the user gets a popup message asking if he wants to run the app is there a way to just thisplay the map in the iframe,['iphone'] +129758,python last iteration in for loop is there any simple way to find the last iteration of the for loop in python i just want to convert a list to csv,['python'] +129780,what does set localelc ctype c actually do when my php script is run with utf8 encoding using nonascii characters some php functions like strtolower do not work i could use mb strtolower but this script can be run on all sorts of different platforms and configurations and the multibyte string extension might not be available i could check whether the function exists before use but i have string functions littered throughout my code and would rather not replace every instancesomeone suggested using set localelc ctype c which he says causes the string functions to work correctly this sounds fine but i do not want to introduce that change without understanding exactly what it is doing i have used set locale to change the formatting of numbers before but i have not used the lc ctype flag before and i do not really understand what it does what does the value c mean thanks,['php'] +129790,how can i find out why a gem bundle has locked a gem at a specific version i am trying to specify a version of the thrift gem in my gem filegem thrift 060when i trying to run bundle install i get this erroryou have requested thrift 060the bundle currently has thrift locked at 050try running bundle update thrifthow can i find out what is causing it to be locked at the earlier version would it be in the requirements of another gem i have listed in the gem fileor is it just being caused by the fact that the installed version is 050 and specifying a version in the gem file would not update an installed gem,['ruby'] +129796,htmlcss how to force div contents to stay in one line i have a long text inside a div with defined widthhtmldivstack overflow is the best divcssdiv border 1px solid black width 70pxhow could i force the string to stay in one line ie to be cut in the middle of overflow i tried to use overflow hidden but it did not help,"['html', 'css']" +129827,how to refresh a page with jquery by passing a parameter to url i am refreshing my page using jquerylocationreloadthis is working great but i want to refresh the same page by passing a parameter to url how can i do this by using jqueryexif my url is wmywebcom i want to refresh this by passing a parameter like this wmywebcomsinglethank you,['jquery'] +129829,how do i detect a mobile browser in a net mvc3 application i am developing a net mvc3 application is there a good way to detect if the user is using a mobile browser in the view using razor i am wanting to differ the thisplay logic if it is a mobile browserthanks,['.net'] +129836,possible to find out whether a user is logged into facebook over javascript api this question is not a duplicate of this onei do not want to know whether the user has authorized my application but if the user is logged into facebook completely independed from my applicationthe reason is that i want to pring user comments in my html code so that search engines can index themwhen a user is logged into facebook i want to replace the html code with the facebook comments snippet if not an alternative old school comment form should be thisplayedi would pull the comments regularely from the graph api to have them in my database and comments that are done using the classic form should be posted over the api not necessarily as the user could be an admin account to have all the data synchronizedi looked at the javascript sdk docs also found the function getloginstatus but the documentations are bad and not conclusive i know that there are also often features available at facebook codes that are not documented or implemented in higher level apismy questions arecan i somehow find out if a user is logged into facebookcan i somehow have a callback or notification of posted comments so i can trigger synchronization to my database or do i have to crawl the graph api on a regular basis,['javascript'] +129840,how to attach android source to eclipse i have previously had success attaching the android source to eclipse by following finn johnsens instructions herehowever this approach seems to have stopped workingsamueljosephscomputer4androidsources samueljoseph git checkout originfroyoreleaseprevious head position was 1de4a2c am 62619392 merge fix leak when keylock is recreatedhead is now at adba66b this class no longer existsthere was a more recent blog here which had some preorganized source for eclair but nothing since there are also some stackoverflow posts from 2008 older than both the above eg attaching java source to android projects in eclipsewhat is the current guidance for accomplishing this,['android'] +129853,how to take the first and items from a generator or list in python with linq i wouldvar top5 arraytake5how to do this with python,['python'] +129858,hibernate spring jps isolation custom isolation not supported i have been trying thistransactionalisolationisolationserializable rollbackforexceptionclass propagationpropagationrequires newon my service methods but spring complains sayingstandard jpa does not support custom isolation levels use a special jpadialecthow can i resolve this,['java'] +129880,reactive latest value to be received by iobservable i know that the following is a blocking call and will return the first value in the observable sequencevar result myobservablefirstdepending on what type of subject i use this has different implicationssubject first will block until the onnext is next called which means eventually this will be the latest valuebehaviorsubject first will block until at least one value has been pushed through onnext and because behaviorsubject tracks the last value this will be the latest valuereplaysubject first will block until at least one value has been pushed through onnext but in the case that many items have been pushed through onnext it will be the first on in its buffer which is not the last one now i am trying to find a consistent way of getting the last value regardless of which underlying observable is usedany ideas,"['c#', '.net']" +129924,how to send an int through udp in java i am trying to write a bit of code which sends a single int over udp the code i have so farsenderint num 2datagramsocket socket new datagramsocketbytearrayoutputstream bout new bytearrayoutputstreamprintstream pout new printstream bout poutprintnumbyte barray bouttobytearraydatagrampacket packet new datagrampacket barray barraylength inetaddress remote addr inetaddressgetbynamelocalhost packetsetaddress remote addr packetsetport1989socketsend packet receiver datagramsocket socket new datagramsocket1989 datagrampacket packet new datagrampacketnew byte256 256 socketreceivepacket bytearrayinputstream bin new bytearrayinputstreampacketgetdata for int i0 i packetgetlength i int data binread ifdata 1 break else systemoutprintint datathe problem is the receiver is printing 50 to screen which is obviously not right i think that the problem may be that i am somehow sending it as a string or something and its not reading it right any help,['java'] +129927,float from c to c i am not truly a cs guy so if any of you geniuses on here can point me in the right direction i will be eternally gratefuli have a ccode command line function that used to write its results to file i converted it to return it is data via a float array to a c program like such to avoid constant file iofloat mgribint argc char argvthis worked perfectly i now need to get this into a c program and heres where things go haywire the first thing i did to avoid the char was to make the arguments a series of bool that worked fine if i allow it to still dump to file the problem is juggling the cstyle float array in c within the ccode it was allocated with mallocso heres everything i have tried with no successi know the size of the arraymake a free function to export to call from c to release the memory when i am done with it after a few loops the c crashes with no warningrelease the malloc from c with marshalfreecotaskmem same resultmove the float to an argument and remove the ccode malloc void mgrib float data aallocate it with marshalalloccotaskmem free it with marshalfreecotaskmem buse marshalcopy to allocate free it with marshalfreecotaskmem maybe this is wrongi have dabbled in just about everything i could find in the internet please let me know if more info is necessary i am hoping this just a simple concept that i am missing,"['c#', 'c']" +129929,app freeze on coredata save i have an iphone app that freezes sometimes when saving coredata and then does not relaunch i did have a second thread that uses the database but i think i have followed the pattern to make a separate context for that thread here is the crash report from the relaunch any ideasi have tried changing it to only run with one thread and here is the latest freeze point after entering the background0 0x30851b98 in fsync1 0x3094e694 in sqlite3 purgeeligiblepagercachememory2 0x3094e6b8 in sqlite3 purgeeligiblepagercachememory3 0x30945372 in sqlite3 compileoption get4 0x30957f06 in sqlite3 extended errcode5 0x3095dc20 in sqlite3 extended errcode6 0x3095dd8e in sqlite3 extended errcode7 0x309646f8 in sqlite3 clear bindings8 0x3098845a in sqlite3 open169 0x3094495a in sqlite3 step10 0x31a1dc20 in execute11 0x31acc6e8 in nssqliteconnection committransaction12 0x31aca646 in nssqliteconnection endprimarykeygeneration13 0x31abeab4 in nssqlcore prepareforsave14 0x31a4acd0 in nssqlcore savechanges15 0x31a1591e in nssqlcore executerequestwithcontexterror16 0x31a1538a in nspersistentstorecoordinator executerequestwithcontexterror17 0x31a48544 in nsmanagedobjectcontext save18 0x080aa in kpersistence savemanagedobjects at kpersistencem24219 0x04320 in kinkastappdelegate applicationdidenterbackground at kinkastappdelegatem126here is my implementation of savemanagedobjectsboolsavemanagedobjectsnserror error persistentstorecoordinator lock bool success yes if managedobjectcontext nil if managedobjectcontext haschanges managedobjectcontext saveerror vlogunresolved error error error userinfo success no persistentstorecoordinator unlock return success,"['iphone', 'ios']" +129937,getting hibernate and sql server to play nice with varchar and nvarchar i am currently in the process of enabling utf8 characters in some tables of a large database these tables are already of mssql type nvarchar additionally i have several fields using varchar as well there is a well known issue with hibernates interactions with the jdbc driver see eg mapping to varchar and nvarchar in hibernate in short hibernatejdbc generates sql that passes all strings as unicode regardless of the underlying sql type when a nonunicode varchar field in the database is compared to a unicode input string the indicies for that column do not match the encoding so a full table scan is performed in the jdbc driver both jtds and ms versions there is a parameter to pass unicode strings as ascii but this is an all or nothing proposition that thisallows international characters from being input into the the database most posts i have seen on this issue have come up with one of two solutions 1 change everything in the database to nvarchar or 2 set the sendstringparametersasunicodefalse my question then is this is there any known solution for having varchar and nvarchar play nicely together it is a huge issue for my environment to change everything to nvarchar because of downstream dependencies and other external issues,['java'] +129953,persistent ssh session to cisco router i have search on this site and multiple other locations but i have been unable to resolve my problem of connecting and maintaining ssh session after one command below is my current codeoptlocalbinpythonimport os import pexpectimport paramikoimport hashlibimport stringiowhile true cisco cmd raw inputenter cisco router cmd ssh paramikosshclient sshset missing host key policyparamikoautoaddpolicy sshconnect192168221235 usernamenuts passwordcisco timeout 30 stdin stdout stderr sshexec commandcisco cmd print stdoutread sshclose if cisco cmd exit breaki can run multiple commands but for every commands a new ssh session is createdthe above program does not work when i need to configuration mode because ssh session is not reusedany assistance in resolving this matter is greatly appreciated,['python'] +129959,boost python linking i am adding boostpython for my game i write wrappers for my classes to use them in scripts the problem is linking that library to my app i am using cmake build systemnow i have a simple app with 1 file and makefile for itpython usrincludepython27boost inc usrincludeboost lib usrlibtarget maintargetso targeto g shared wlexportdynamic targeto lboost lib lboost python lusrlibpython27config lpython27 o targetsotargeto targetcpp g ipython iboost inc c fpic targetcppand this works it builds a so file for me which i can import from pythonnow the question how to get this for cmakei wrote in main cmakelisttxtfind packageboost components filesystem system date time python requiredmessageinclude dirs of boost boost include dirs messagelibs of boost boost libraries include directories boost include dirs target link librariesthemisto boost libraries message calls showinclude dirs of boost usrincludelibs of boost usrliblibboost filesystemmtausrliblibboost systemmtausrliblibboost date timemtausrliblibboost pythonmtaok so i have added simple cppfile for my project with include of boostpythonhpp i get an error at compilingusrincludeboostpythondetailwrap pythonhpp5023 fatal error pyconfigh no such file or directoryso it does not take all need include directoriesand second questionhow to organize 2step building of scriptcpp files in makefile i showed there are targeto and targetso how to process that 2 commands in cmakeas i understand the best way is to create subproject and do something therethanks,"['c++', 'python']" +129971,javascript get calling object possible duplicatejavascript how do you find the caller function hi guysis there a way to get the value of this from the function which has called the current functionlook at thisfunction tracemyself consolelogthisfunction a tracemyself consolelogthisvar a new awhen this code is executed the console thisplays first the window object and then the a object how can i make the code thisplay the a object twice with only changing line 2 i know that i could apply the function inside a with this but that is not what i wantis this possiblethanks for your help,['javascript'] +129998,viewing java documentation with eclipse on mac os x i am trying to accomplish a very basic task and somehow cannot seem to find how i would like to have my eclipse environment set in a way that i can get help and documentation on any standard classmethod in the jdk like i used to do a few years ago with eclipse on windows where having the cursor on a class name eg printwriter and clicking ctrlf2 would open up the java documentation for the printwriter classheres my environmentrunning os x version 1066just downloaded and installed the java developer package for mac os x 106 update 4 from connectapplecomi have eclipse galileo installedunder libraryjavajavavirtualmachines i have a file named 160 24b07334jdk which seems to be the new jdk i just installed however it is a single file not expanded into directories and files rightclicking it and selecting show package content shows me that deep inside it contains the files docsjar and srcjar however not sure what i should be doing with the 160 24b07334jdk file should i leave it as is or perhaps expand it to a full directory structureunder eclipse preferences javainstalled jres i have jvm 160 macos x default selected however the path points to systemlibrary and not to libraryanyway in eclipse putting the mouse over a class name i get a brown dialog with a short explanation of the class however i do not know how to open up the full java documentation of the class also could not find anywhere in eclipse a place to indicate where to take the java documentation from nor which hotkey would bring the java documentation upi apologize for the many details i am just assuming they may be necessary to get a good answerthanksa,['java'] +130003,entitlementsplist error when trying to build non adhoc versions i searched all around for an answer but no lucki successfully built an adhoc version of this app but now when i try to build for debug release or regular thistribution i get the build errorcodesign error the entitlements file usersdropboxmyappentitlementsplist is missingthe thing is a the entitlementsplist file is sitting right there in the resources folder b that is not even the correct path to the xcode project folder c i removed the key from the project settings build code signing entitlements so why is it even looking for the entitlementsplistwhat is going on how can i get xcode to stop trying to find the entitlements file i know it isnt even needed for the anything other than adhoc builds,"['iphone', 'objective-c', 'ios']" +130030,detect if a model has changed before calling save in django i have a database model that is being updated based on changes in remote data via an html scraperi want to maintain a field called changed a timestamp denoting when the last time that models values changed from what they were previously note that this is different from auto now as these fields are updated every time a models save method is calledhere is my questionin a models save method is there a straightforward way to detect if a model instances current values are different from the values in the database or are there any alternative methods to easily maintain a changed timestamp,['python'] +130037,what causes memory fragmentation in net i am using red gates ants memory profiler to debug a memory leak it keeps warning me thatmemory fragmentation may be causing net to reserver too much free memoryormemory fragmentation is affecting the size of the largest object that can be allocatedbecause i have ocd this problem must be resolved what are some standard coding practices that help avoid memory fragmentationcan you defragment it through some net methods would it even help,"['c#', '.net']" +130060,jquery event detection delete input box text with mouse drag text to input box i am able to detect the cut copy paste events with the following code searchinputbindcut copy paste function e settimeouthandlemouseevents 10is it possible to detect the following eventsdelete input box text with mousedrag text to input boxdrag text away from input boxundo action from mouse context menu or form edit menui tried binding on mousedown and mouseup but not workingsearchinputbindcut copy paste mousedown mouseup function e settimeouthandlemouseevents 10,['jquery'] +130061,how can i add items to a spinner in android how can i add items to a spinner,['android'] +130063,c conditional attribute on interface member i am trying to get rid of the if trace directives in my code by using the conditional attribute instead but cannot apply this approach easily to interfaces i have a way round this but it is pretty ugly and i am looking for a better solutioneg i have an interface with a conditionally compiled methodinterface ifooif trace void doitendifi cannot use the conditional attribute in an interface would not compileinterface ifoo conditionaltrace void doiti could have the interface method just call a conditional private method in the concrete classinterface ifoo void traceonlydoitclass foo ifoo public void traceonlydoit doit conditionaltrace void doit consolewritelinedid it this would leave my client code with redundant calls to the nop traceonlydoit method in a nontrace build i can get round that with a conditional extension method on the interface but it is getting a bit uglyinterface ifoo void traceonlydoitclass foo ifoo public void traceonlydoit consolewritelinedid it static class fooextensions conditionaltrace public static void doitthis ifoo foo footraceonlydoit is there a better way to do this,['c#'] +130065,how to animate the pie charts developed using coreplot library in the iphone application roambi the pie chart shown can be animated to rotate with the user as if rotating a thisc we can hold and do lot of stuff with thatsomeone mentioned that the roambi app was developed using coreplot librarywhat library use roambi app iphone to draw charthow can i manipulate a pie chart developed using core plot,['iphone'] +130072,running java gui application through linux terminal i am on ubuntu trying to run a java gui application through the terminal i am getting a headlessexception when i try to run it below is the stack traceexception in thread awteventqueue0 javaawtheadlessexception at javaawtgraphicsenvironmentcheckheadlessgraphicsenvironmentjava173 at javaawtwindowinitwindowjava437 at javaawtframeinitframejava419 at javaawtframeinitframejava384 at javaxswingjframeinitjframejava174 at guiimageviewerinitimageviewerjava34 at thisplayrunnerthisplayrunner1runthisplayrunnerjava15 at javaawteventinvocationeventthispatchinvocationeventjava226 at javaawteventqueuethispatcheventimpleventqueuejava647 at javaawteventqueueaccess0eventqueuejava96 at javaawteventqueue1runeventqueuejava608 at javaawteventqueue1runeventqueuejava606 at javasecurityaccesscontrollerdoprivilegednative method at javasecurityaccesscontrolcontext1dointersectionprivilegeaccesscontrolcontextjava105 at javaawteventqueuethispatcheventeventqueuejava617 at javaawteventthispatchthreadpumponeeventforfilterseventthispatchthreadjava275 at javaawteventthispatchthreadpumpeventsforfiltereventthispatchthreadjava200 at javaawteventthispatchthreadpumpeventsforhierarchyeventthispatchthreadjava190 at javaawteventthispatchthreadpumpeventseventthispatchthreadjava185 at javaawteventthispatchthreadpumpeventseventthispatchthreadjava177 at javaawteventthispatchthreadruneventthispatchthreadjava138i tried export thisplay00 before running the app but that had no effect how do you run a gui application through bash,['java'] +130078,how to access js array defined in another js file how i can access an javascript array which is defined in another javascript file,['javascript'] +130103,is there a valid alternative to antlr written in c antlr is a great piece of software but in my opinion is a little bit uncomfortable for a c programmer the c porting is out of date the parser antlr313jar required java etci am looking for a more c native language tool in order to parse a simple jsonlike grammar any suggestion,['c#'] +130105,jquery slideup to show the element and not hide jquerys slideup effect hides the element by sliding it up while slidedown shows the element i want to show my div using slideup can anyone guide me thanks,"['javascript', 'jquery']" +130108,android 9patch graphic does not scale in image view i havelinearlayout androidididlinearlayout01 androidlayout widthwrap content androidlayout heightwrap content androidorientationhorizontal imageview androidlayout heightwrap content androidlayout widthwrap content androidididimageview01 androidsrcdrawablephone80imageview imageview androidididimageview02 androidlayout heightwrap content androidsrcdrawableunderline androidlayout widthfill parent androidlayout gravityfill verticalfill horizontalimageviewlinearlayoutthe first image is a fixed size image which should not scale at all the image right of it should scale horizontally to the maximum space the source points to a valid 9png file unfortunatly it always only shows up in its original size what property to i have to set is imageview the right object at allthanksa,['android'] +130109,stanford pos tagger in java usage mar 9 2011 12206 pm edustanfordnlpprocessptblexer nextwarning untokenizable i12 ufd decimal 65533mar 9 2011 12206 pm edustanfordnlpprocessptblexer nextwarning untokenizable i12 ufd decimal 65533mar 9 2011 12206 pm edustanfordnlpprocessptblexer nextwarning untokenizable i12 ufd decimal 65533mar 9 2011 12206 pm edustanfordnlpprocessptblexer nextwarning untokenizable i12 ufd decimal 65533mar 9 2011 12206 pm edustanfordnlpprocessptblexer nextwarning untokenizable i12 ufd decimal 65533mar 9 2011 12206 pm edustanfordnlpprocessptblexer nextwarning untokenizable i12 ufd decimal 65533mar 9 2011 12206 pm edustanfordnlpprocessptblexer nextwarning untokenizable i12 ufd decimal 65533these are the errors that i am getting when i want to assign pos tags to sentences i read sentences from a file initially for few sentences i am not getting this error ie untokenizable but after reading some sentences this error arises i use v20 ie 2009 of pos tagger and model is left3words,['java'] +130111,default value for a text column i have a column in my table having data type as texthow can i give it a default null value so that when there is not entry in the column it does not consume memoryi was reading a similar question on a forum where they said column should be allowed for null values i did that but it does not work,['mysql'] +130126,call javascript function from jquery i have a javascript function from a google maps tutorialscript typetextjavascript function initialize scriptand in the tutorial it gets called by body onload but as i have jquery code anyway i thought i would just call it from thereso i just trieddocumentreadyfunction initializebut then no jquery works at all how do i call this function the correct way,"['javascript', 'jquery']" +130137,page vs window in wpf what is the difference between a page and a window in wpf when you are adding a new file in the solution explorer,['c#'] +130143,jquery post do i have to encode the url parameter i am making an ajax call with posturl cb the url i am passing in could potentially have weird characters like spaces and so ondo i have to use postencodeuricomponenturl cburl is something like fooweirdchara,['jquery'] +130167,python appending a dictionary to a list i see a pointer like behavior i tried the following in the python interpreter a b 1one aappendb a1 one b1 one a1 onehere after appending the dictionary b to the list a i am changing the value corresponding to the key 1 in dictionary a somehow this change gets reflected in the list too when i append a dictionary to a list am i not just appending the value of dictionary it looks as if i have appended a pointer to the dictionary to the list and hence the changes to the dictionary are getting reflected in the list tooi do not want the change to get reflected in the list how do i do itthank you for your time,['python'] +130168,using a delegate to pass data back up the navigation stack i have been battling with passing data between two view controllers for a couple of days now and getting very confused i am new to objectivec and finding some parts tricky to get my head roundi have a navigation controller firstview is a form and on this form i have a button which loads secondview which contains a tableview for the user to select some options i then want to pass the selection back to the firstview controller and thisplay the data etci have read alot about this stackoverflow iphonedevsdk cs 193p resources and the options i have seen are 1 ivar in app delegate dirty and not recommended2 create a singleton3 create a data model class4 use protocols and delegates recommended by applei want to do things right and want to use option 4 delegates in my programproblem is i do not understand delegates and how to setup and implement them could anyone provide a basic example on how to setup and pass an nsarray using the delegate and 2 view controllersthanks in advancematt,"['objective-c', 'ios']" +130172,encryption with blowfish in java following code works fine for me to encrypt a string with the blowfish encryption create a key generator based upon the blowfish cipher keygenerator keygenerator keygeneratorgetinstanceblowfish create a key secretkey secretkey keygeneratorgeneratekey create a cipher based upon blowfish cipher cipher ciphergetinstanceblowfish initialise cipher to with secret key cipherinitcipherencrypt mode secretkey get the text to encrypt string inputtext mytexttoencrypt encrypt message byte encrypted cipherdofinalinputtextgetbytesif i want to define my own secret key how do i do that,['java'] +130173,when is memory allocated by net process released back to windows the setupnet allocates memory for each generationas heap 0 1 2 loh in segments to get a continuous block of memory on startup and when it attempts to satisfy an allocation request after a collection this memory allocated for each heap will likely level off as the application awarms upa except potentially for generation 2 and large object heap during a garbage collection each heap 0 1 2 is swept and compacted except for the large object heap loh which is just swept i understand the asweepa part of a collection to mean that the gc identifies which objects are no longer rooted and are available for collection or finalization and that acompacta means that the addresses that are still alive in a heap are reorganized so that the available remaining heap has more continuous memory available to it as the budget for each segment within the heap is exceeded net will allocate another segment in order to fulfill allocations if it canthe questionmy question comes down to what happens to that memory in each heap that is not be used by the application committed any longer but is still reserved by net when is it released back to the os i believe this to be the scenario where a process might appear to be consuming a lot of memory virtual size is quite large but private bytes small but when inspecting its heaps are mostly free space as another caveat the total size of the heaps may also be quite small and not account for the memory being consumed by the process there is no blocked finalizer and all looks healthy for a process it may have been running for weeks before it triggered a monitor alert egtrying for further clarification of the question if you read tess net memory management a restaurant analogy if the tables are heap segments does the restaurant ever lose tables eg free heap segments editremoved confusing reference to working set and chickensadded reference to tess restaurant analogy,['.net'] +130188,what does the keyword transient mean in java i saw somewheretransient private trackdao trackdao,['java'] +130189,make fbapi calls synchronous i am creating fquery api on top of fb javascript sdk and till now everything worked fine but i got stuck in fbapi calls nowactually i am trying to load facebook user object ie me using fbapi functionfunction somefunc var r fqueryloadselector selector me return rfqueryload function selector fqueryfnresponse return fbapi selector function response we get response here is it possible to return the response or can we make it sync call i have tried many ways to work around but could not get success please provide suggestions,['javascript'] +130197,how to convert string to jsonobject in java i have string variable called jsonstringphonetypen95catwpnow i want to convert it into json object i searched more on google but did not get any expected answers,['java'] +130207,advanced c source code reformatting with visual studio we would like to be able to reformat c blocksfunctions of code directly from the visual studio ide so that developers easily can assure that the new code they insert adheres to our formatting guidelinesi have found the artistic style tool which pretty much covers the features wed need however it only can work on whole files from the cli so it is not very helpful for what wed want to use it whole file reformatting is certainly never what we want avisual studio 2005 has limited autoformat features but afaics these are mostly about correct indenting which is a bit lackingso my question is if there are any tools that can do advanced reformatting on a selection from the vs ide or maybe if there is a vs ide plugin making use of astyleedit the question linked to recommends a tool profactors stylemanager are there any other tools like thisnote a reformatting whole files or whole project trees is only useful for personal projects or for initial code checkins imho for a large team project blanket reformatting will mess up the change history of files or lines within files making it a lot harder to track whos changed what,['c++'] +130227,enabling vlasvariable length arrays in ms visual c how can i enable the use of vlas variable length arrays as defined in c99 in ms visual c or that is not possible at allyes i know that the c standard is based on c89 and that vlas are not available in c89 standard and thus are not available in c but msvc is supposed to to be a c compiler also a behavior that can be switched on using the tc compiler parameter compile as c code tc but doing so does not seem to enable vlas and the compiling process fails with the same errors when building as ccompile as c code tp maybe msvc c compiler is c89 compliant only or i am missing somethingsome special construct or pragmadefinecode sampleinclude stdlibhint mainint argc char argv char pcargc5 do something useful with pc return exit successcompile errorserror c2057 expected constant expressionerror c2466 cannot allocate an array of constant size 0error c2133 pc unknown size,['c'] +130229,wfs web feature service for aspnet mvcc basic versionis there a lightweight cnet library that can be used in an aspnet mvc app to service wfs requestsdetailed version we are developing a c aspnet mvc app that sits on top of a sql server 2008 database with some basic geospatial data i need to be able to thisplay a map with our simple pointline features db entities over a map background in the browser the plan is to use openlayers to render the map the background map is being provided by a thirdparty using wms so i know i can connect to and thisplay that okthe problem i have is that the data we wish to show over the map need to be filtered by the user it is currently shown in tabular form it appears that i really need to expose a wfs service to allow the user to filter data for thisplay on the mapis there a lightweight and ideally free c component that can do this i have had a brief play with sharpmap which is largely suitable for our needs but while i can use it to render a map and our data i have not been able to figure out how to apply filters which will vary request to request to the rendered data alternatively does anyone have any other suggestionsi am trying to avoid use of fullscale geoservers eg geoserver mapserver etc if possible as our requirements are quite basic and we have various infrastructure constraintsthanks in advance,['c#'] +130233,in javascript is there equivalent to apply that does not change the value of this seems easy enough i want to call a function with array of arguments sure i can say funcapplythis some arguments but that will change the value of this inside func any idea how to do this without changing it,['javascript'] +130238,why does pickle getstate accept as a return value the very instance it required getstate to pickle in the first place i was going to ask how to pickle a class that inherits from dict and defines slots then i realized the utterly mindwrenching solution in class b below actually worksimport pickleclass adict slots porridge def init self porridge selfporridge porridgeclass ba slots porridge def getstate self returning the very item being pickled in self return self selfporridge def setstate self state print setstate s types s state typestate0 typestate1 selfupdatestate0 selfporridge state1here is some output saved pickledumpsa10typeerror a class that defines slots without defining getstate cannot be pickled b bdelicious bbutter yes please loaded pickleloadspickledumpsb setstate butter yes please delicious typeclass main b type str bbutter yes please bporridgedeliciousso basically pickle cannot pickle a class that defines slots without also defining getstate which is a problem if the class inherits from dict because how do you return the content of the instance without returning self which is the very instance pickle is already trying to pickle and cannot do so without calling getstate notice how setstate is actually receiving an instance b as part of the statewell it works but can someone explain why is it a feature or a bug,['python'] +130247,mysql how to insert a record for each result in a sql query say i have a selectselect thistinct id customer id domain from config where type foowhich returns some recordshow can i do an insert for reach row in the result set likeinsert into config id customer id domain values id customer id wexamplecomwhere id and customer id are the fields of the row in the result setedit i did not want to just duplicate it but insert a new value in the field domain instead nevertheless a facepalmsituation as it is plain easy thanks,"['mysql', 'sql']" +130257,wpf scrollviewer in grid i have a gridgridrowdefinitions rowdefinition height100 rowdefinition heightgridrowdefinitionsthe second row is with scrollviewer scrollviewer verticalscrollbarvisibilityauto minheight400 gridrow1 itemscontrol itemssourcebinding selectedusercontrols scrollvieweri want the second row to be with scroll if neededbut the scroll is never visible event if the items controls are bigger than the screenhow can i get the scroll to appear when needed,['c#'] +130260,how to highlight listview item on touch i have a simple listview and i want each of it items to be highlighted on users touch i thought this should happen by default but it is not can you advicelistview xml listview androidididlist view androidlayout widthfill parent androidlayout heightfill parent androidpadding10dp androiddivider206600 androiddividerheight2dp androidsmoothscrollbartrue androidbackgroundf listviewand code of my adapterprivate class myadapter extends arrayadaptertask private layoutinflater minflater public myadaptercontext context int resource listtask list supercontext resource list minflater layoutinflaterfromcontext override public view getviewint position view convertview viewgroup parent view v convertview if v null v minflaterinflaterlayoutlist item null task task tasklistgetposition setup views from your layout using data in object here return v,['android'] +130262,hidingshowing uitableviewcell accessory thisclosure indicator i am trying to load a datastring from core data and if that value in that row equals to the accessory thisclosure indicator will hide and selectionstylenone i tried this but not successful if entityvalue cellselectionstyle uitableviewcellselectionstylenone cellaccessorytype uitableviewcellaccessorythisclosureindicator or nsstring this entityvalueif this cellaccessorytype uitableviewcellaccessorythisclosureindicator cellselectionstyle uitableviewcellselectionstylenoneboth not workingbut is this possible though thanks,['iphone'] +130263,why does the xdocument give me a utf16 declaration i am creating a xdocument like thisxdocument doc new xdocumentnew xdeclaration10 utf8 yeswhen i save the document like this docsavectijdfile2xml i get thisxml version10 encodingutf8 standaloneyeswhich is okbut i want to return the content as xml and i found the following code var wr new stringwriter docsavewr string s wrgetstringbuildertostringthis code works but then the string s starts with thisxml version10 encodingutf16 standaloneyesso it changed from utf8 to utf16 and that is not what i want because now i cannot read it in internet exploreris there a way to prevent this behaviour,['c#'] +130264,at what point does mysql innodb fine tuning become a requirement i had a look at this and these answer a lot of my questions regarding innodb vs myisam there is no doubt in my mind that innodb is the way i should go however i am working on my own and for development i have created a lamp ubuntu 1010 x64 vm server at present the server has 2 gb memory and a single sata 20gb drive i can increase both of these amounts without too much trouble to about 335 gb memory and a 200gb drivethe reasons i hesitate to switch over to innodb isa the above articles mention that innodb will vastly increase the size of the tables and he recommends much larger amounts of ram and drive space while in a production environment i do not mind this increase in a development environment i fear i can not accommodateb i do not really see any point in fine tuning the innodb engine on my vm this is likely something i will not even be allowed to do in my production environment the articles make it sound like innodb is doomed to fail without fine tuningmy question is this at what point is innodb viable how much ram would i need to run innodb on my server with just my data for testing this server is not open to anyone but me and also is it safe for me to assume that a production environment that will not allow me to fine tune the db has likely already fine tuned it themselvesalso am i overthinkingoverworrying about things,['mysql'] +130265,selfwindowrootviewcontroller vs window addsubview i have noticed a lot of examples for iphone apps in the application delegate voidapplicationdidfinishlaunchinguiapplication applicationhavewindow addsubview somecontrollerview 1as opposed to selfwindowrootviewcontroller selfsomecontroller 2is there any practical reason to use one over the other is one technically correct do controllers have an equivalent command to number 2 like selfsomecontrollerrootcontroller selfsomeothercontroller pseudocode,"['iphone', 'objective-c']" +130277,starting an action view activity to open the browser how do i return to my app in my app i need to open the banks page to make the user able to payreading the android documentation i see that i should use an action view and not a webview to accomplish this uri uri uriparse intent intent new intentintentaction view uri startactivityintentmy question is after the user is done with the payment how can i get back to the appi mean i would like to do something likestartactivityforresultintent result codeto open the banks site and then get back to the app when the user is done using theprotected void onactivityresultint requestcode int resultcode intent data callback to handle the result of the paymentand am i following the right way or is there any other way to accomplish this,['android'] +130280,spring ws and uddi i have a bunch of web services implemented in springws 159 we use maven to do our builds our services run on oc4j that have a uddi providerwhat we want to do is to start using uddi internally to register our web services to allow other groups in the business to find and use themthe problem is that i have not been able to find how to actually put this all together how do i get the services to register them selves when they are deployed to the app serverspring does not seem to have any support or annotations there does not appear to be a maven plugini have got all the pieces but how do i put these together into an automated solution,['java'] +130302,c programmatically reading emails from the exchange server when you search on web you will find very easy answers for how to read emails programmatically al the websites are explaining most of the same like this page depends from exchange server version servicecredentials new networkcredentialmdr password z serviceautothiscoverurl object o servicefinditemswellknownfoldernameinbox new itemview10 finditemsresultsitem findresults servicefinditemswellknownfoldernameinbox new itemview10 foreach item item in findresultsitems consolewritelineitemsubject it fails when it executes the autothiscoverurl line the error says the autothiscover service could not be located so i googled further and found this site from microsoft wexaqubcwubme93h2jji0mv2gtqcrl0g43z9m here you can test your mail server when i pass the parameters i get the error belowbut i still do not understand what the problem is do i need to add a record to dns can someone helpattempting to test potential autothiscover url testing of this potential autothiscover url failed test steps attempting to resolve the host name autothiscoverncbbe in dns the host name resolved successfully additional details ip addresses returned 213246192205testing tcp port 443 on host autothiscoverncbbe to ensure it is listening and open the specified port is either blocked not listening or not producing the expected response tell me more about this issue and how to resolve it additional details a network error occurred while communicating with the remote hostexception detailsmessage no connection could be made because the target machine actively refused it 213246192205443type systemnetsocketssocketexceptionstack traceat systemnetsocketstcpclientconnectstring hostname int32 portat microsoftexchangetoolsexrcateststcpporttestperformtestreallyattempting to contact the autothiscover service using the http redirect method the attempt to contact autothiscover using the http redirect method failed test steps attempting to resolve the host name autothiscoverzbe in dns the host name resolved successfully additional details ip addresses returned 213246192205testing tcp port 80 on host autothiscoverzbe to ensure it is listening and open the port was opened successfullyexrca is checking the host autothiscoverzbe for an http redirect to the autothiscover service exrca failed to get an http redirect response for autothiscover additional details a web exception occurred because an http 404 notfound response was received from iis7attempting to contact the autothiscover service using the dns srv redirect method exrca failed to contact the autothiscover service using the dns srv redirect method test steps attempting to locate srv record autothiscover tcpncbbe in dns the autothiscover srv record was not found in dns tell me more about this issue and how to resolve it,['c#'] +130304,storing a block in a collection is it possible to directly store a block in a collection such as nsarray,['objective-c'] +130308,mockito to test void methods i have following code i want to testpublic class messageservice private messagedao dao public void acceptfromofficemessage message messagesetstatus0 daomakepersistentmessage messagesetstatus1 daomakepersistentmessage public void setdao messagedao md thisdao md public class message private int status public int getstatus return status public void setstatus int s thisstatus s public boolean equals object o return status message ostatus public int hashcode return status i need to verify that method acceptfromoffice really sets status to 0 than persist message then chage its status to 1 and then persist it againwith mockito i have tried to do followingtest public void testacceptfromoffice throws exception messagedao messagedao mockmessagedaoclass messageservice messageservice new messageservice messageservicesetdaomessagedao final message message spynew message messageserviceacceptfromofficemessage verifymessagedaomakepersistentargthatnew basematchermessage public boolean matches object item return message itemgetstatus 0 public void describeto description description verifymessagedaomakepersistentargthatnew basematchermessage public boolean matches object item return message itemgetstatus 1 public void describeto description description i actually expect here that verification will verify calling twice of makepersistent method with a different message objects state but it fails saying that arguments are differentany clues,['java'] +130317,play alert sound same as default message ringtone is it possible to play some default sounds such as when an incoming smspush is receivedif ios sdk does not bundle these sound files where can i download the same sounds,['iphone'] +130320,why does not this motionevent simulation work in one of the views in an exercise app am trying to perform text selection programmaticallyi am able to programmatically enter text selection mode which is visually indicated by cursorcontrollers aka handles on the topleft corner of the viewif i manually drag the right cursorcontroller then click it again in the emulator it works as expected perfectly showing a brief message text copied to clipboardbut when i try to programmatically drag that right cursorcontroller nothing happensthe way i try to do this is by simulating a motionevent in the view i call event motioneventobtaindowntime eventtime motioneventaction down x y 0 mainactivityontouchthis eventin the mainactivity i of course implement ontouchlisteneroverridepublic boolean ontouchview v motionevent event called before buttons ontouchevent logvmainactivityontouch describeeventv event switch eventgetaction case motioneventaction down case motioneventaction up if vhasfocus vrequestfocus break return false if i understand correctly by mere returning false from ontouch android keeps looking for another ui object to consume the motionevent object eventually reaching my viewwhy does not this happeni must be missing something very fundamental,['android'] +130357,how do i escape some html in javascript given the text bthis is some textbi want to write it to my page so that it shows up like thisbthis is some textband not like thisthis is some textusing escapebthis is some textb gives me this lovely gem in firefox3cb3ethis20is20some20text3cb3enot exaclty what i am after any ideas,['javascript'] +130368,can i avoid putting key store password on commandline with jsse we are using maven 2 and have a maven repository manager secured with ssl client authentication in order for maven to access the repository the following system properties must be passed to javajavaxnetssltruststoretrustjksjavaxnetssltruststorepasswordtrustpassjavaxnetsslkeystorekeystorep12javaxnetsslkeystoretypepkcs12javaxnetsslkeystorepasswordkeystorepasee this miniguide for more detailsin order to set these system properties in maven i have to use the maven opts environment variable or pass them directly on the commandline either way when maven actually executes all of these properties become visible to other users on the system via ps including my key store passwordis there a way to set these properties so that the password does not get exposed on the commandline,['java'] +130371,specify image filling color when rotating in python with pil and setting expand argument to true i am trying to rotate an image in python using pil and having the expand argument to true it seems that when the background of my image is black the resulting image saved as a bmp will be a lot smaller than if i have a white background for my image and then i replace the black due to expand with white in either case my original image is always of two colors and right now i need the file size to be small since i am putting these images on an embedded device any ideas if i can force rotate to fill in another color when expanding or if there is another way to rotate my picture in order to make it small,['python'] +130382,test for value in javascript array in sql server i could say where x in12how would you rewrite the following in javascriptif x1 x2,['javascript'] +130393,how to unit test email sending i would like to test my email sending functionality using net c framework or any compatible library any suggestion how to do it,"['c#', '.net']" +130405,resharper refactoring to remove magic strings is there such a thing either as a part of the product or a plugin i cannot see to find iti want to go frompublic datatable fetch return executedatatable connectionstring pr detectaffectedorderlinestoprivate const string sp detect affected order linespr detectaffectedorderlinespublic datatable fetch return executedatatable connectionstring sp detect affected order lines,['c#'] +130417,php how to set current working directory to be same as directory executing the script i am in the process of transferring my website from one server to another i have some php scripts that use the is readable function which uses the current working directory on the old server when i call getcwd it outputs the folder in which the script is being executed on the new server it outputs the root directory i would like to know how i can configure php to use the current folder instead of i do not want to have to change any php code that already works on the old server i can configure the new server but do not know what settings to change i am using apache2 if that helpsedit it seems as though my working directory is not root like i thought when i create a testfilephp and echo getcwd it shows the directory the php file is in but in my problem file in the same directory getcwd shows up as,['php'] +130420,how to set an imageviews image from a string i have a list of entries and some bitmap files in the resdrawablemdpi directory i am trying to load the image corresponding to the string value selected from the list by generating a path string and using bitmap factory the problem is i do not think my path is right because the bitmap is always null even for the default imagestring name entriesgetposition string img resdrawablelogo nametolowercase png create the file name iconsetscaletypeimageviewscaletypecenter crop check to see if the file exists file file new fileimg if fileexists bm bitmapfactorydecodefileimg else use the default icon bm bitmapfactorydecodefilelogo defaultpng set the image and text iconsetimagebitmapbmdoes the res directory even get copied onto the device what is the correct path i should be using or should i be going about this differentlythanks,['android'] +130457,fcntlflock how to implement a timeout i am using python 27i want to create a wrapper function around fcntlflock that will timeout after a set intervalwrapper functiontimeouti have tried calling on another thread and using threadjointimeout but it seems that fcntlflock continues blockingdef getlockself timeout returns true if lock is aquired false if lock is already in use self lock file openproc lock w def getlockortimeout print processlock acquiring lock fcntlflockself lock filefileno fcntllock ex print processlock lock acquired thread threadingthreadtargetgetlockortimeout threadstart threadjointimeout if threadisalive print getlock timed out return false else return truei have looked into solutions for terminating threads the most popular solution seems to be subclassing threadingthread and adding a feature to raise an exception in the thread however i came across a link that says this method will not work with native calls which i am pretty sure fcntlflock is calling a native function suggestionscontext i am using a filelock to create a single instance application but i do not want a second instance of the application to sit around and hang until the first instance terminates,['python'] +130483,integer size in c depends on what size of the integer depends on whatwhether it is compiler dependent or machin dependent,['c'] +130508,mysql datatype int11 whereas unsigned int10 in mysql if we create a field datatype of int and does not specify any lengthvalues then it automatically became int11 and if we set the attribute unsigned or unsigned zerofill then it turns into int10where does this length1 goes,['mysql'] +130522,how to know if javascript stringreplace did anything the replace function returns the new string with the replaces but if there werent any words to replace then the original string is returned is there a way to know whether it actually replaced anything apart from comparing the result with the original string,['javascript'] +130527,are exceptions still undesirable in realtime environment a couple of years ago i was taught that in realtime applications such as embedded systems or nonlinuxkerneldevelopment cexceptions are undesirable maybe that lesson was from before gcc295 but i also know that exception handling has become betterso are cexceptions in the context of realtime applications in practicetotally unwantedeven to be switched off via via compilerswitchor very carefully usableor handled so well now that one can use them almost freely with a couple of things in minddoes c11 change anything wrt thisupdate does exception handling really require rtti to be enabled as one answerer suggested are there dynamic casts involved or similar,['c++'] +130529,nativeaudio sample in ndk build problem i have a problem when build nativeaudio sample in ndkthe main reason is slesopenslesh no such file or directoryi have googled but i dont find any thing helpfulplease help methanks in advance,['android'] +130537,iphone xmpp app run background i created a chat application using xmpp frameworkwhen i quit the appenter background mode i want to receive the chat messageand also need to thisplay the icon badgehow can i do this,"['iphone', 'objective-c', 'ios']" +130579,php crypt returning wrong answer i think i am losing my marbles here i have got a problem on my web site where randomly it stops accepting logins i have now been able to trace it to crypt behaving very strangelyin my database i have got the crypted version of the users password so let us say og12345678when the user logs in they enter their password i read the salt out of the db and then crypt what they entered and compare usually this works very wellso i am doing cryptenteredpassword saltfromdb in this case the salt would be og of course normally for a given users password crypt works finewhen things go wrong and when they do it is a permanent change until i restart apache i found that crypt starts returning a different answer for the same input with the same saltit is consistent however ie once the system has gone wrong crypt returns the wrong answer but it is always returning the same wrong answer repeated refreshes of the page show the same output the same salt is also in evidence in the newly incorrect crypt result also so it is not that the salt has gone missing somewhereif i then restart apache and rerun the script without any changes at all the results from crypt are then back to how they should bei appreciate it is not the latest php 528 but would value any views on this including whether it is a known bug fixed in a later version upgrading php is not a happy task with lots of sites some of which still use unfortunate quirks that all need to be retested with each upgrade if it is a known fixed bug then obviously i will get it all upgraded asap beyond that it will probably be easier to outsource the crypt externally since i only use it in one common place for my siteany input appreciatedmatt peddlesden update 11 mar 2011correction to comment previously given about operating system operating system is windows server 2008 sp1 64 bit apologies i should have double checked rather than assuming i could remember machine is a dell 2950 8gb ram xeon processorsi am starting to think along the lines krtek is suggesting when the system has gone wonky if i generate new crypt ie a very simple example where i set a variable to a string crypt it and then compare with the crypt all works great when i restart the server again it is all back to the previous calculations again so i am definitely leaning towards something that is changing the algorithm used to calculate the crypt result any thoughts on what might cause this to happen i printed out the values of the crypt std des etc and they do not change between restarts anyone got any clues on what might cause this to happenwhatever it was seemed to happen twice in one day yesterday most oddthanks for the answers thus far update 16 mar 2011just wanted to provide another updatethis is still happening still no further understanding of whyin case anyone comes across this in the future i think my solution going forwards is going to be to do some nasty hack to push all the crypt executions out to an external c application and stop having to rely on php to do them something is going wrong somewhere and at this point the only solution i can see is to remove it from the equation entirelyof course if it still happens that will be interesting to know too thanks all,['php'] +130632,objective c implement method which takes array of arguments heedoes anybody know how to implement an method in objective c that will take an array of arguments as parameter such asnsarray arraywithobjectsabnilthe method declaration for this method is idarraywithobjectsidfirstobji cannot seem to make such method on my own i did the following void dosometingidstring manytimesnsintegernumberoftimessomeclass dosometingabnil manytimes2it will give the warningtoo many arguments to function dosometingmanytimesthanks already,['objective-c'] +130648,defining new xcode template tags on a perproject basis it is well known that you can define the values for tags that are used in new file templates as described at so a typical template looks like this mainm aprojectnamea created by afullusernamea on adatea copyright c ayeara aorganizationnamea all rights reserved now i know how to define new templates and have done so however i want my new template to use my own new tag in it like this aattributionlinea and i want that tag to be definable on a per xcode project basis is this possible i have searched around and can only find the usual stuff about running something on the command line that defines a wellknown tag for all projects,['iphone'] +130673,rspec stub a templates helper method call from a controller spec using render views from rails 3 rspec 2 i am attempting to leverage the render views feature of controller specs the issue i have come across is that weve just installed the kaminari pager gem and i want to stub out the paginate sites call from my view so i do not have to manually stub out all the internal methods that kaminari defines on the collection for use with paginate helper if this was in a view spec i could stub out the helper method by calling viewstubpaginate but i cannot find any way to get a handle on the view object from a controller spec eg controllerviewstubpaginate is there any way to do this or are our options to either thisable render views for this method or to stub a bunch of internal kaminari methods that are not relevant to us since they should be covered by kaminaris tests and might change in future versionsdescribe sitescontroller do render views def mock sitestubs mock site mock modelsite stubsas null object end describe get index do it assigns all sites as sites do sitestub chainenabledorderedpage mock site want to do something here like controllerviewstubpaginate get index assignssitesshould eqmock site end endend,['ruby-on-rails'] +130676,specifying fetch strategy select join etc in nhibernate queryover query i am trying to create a query using queryover which will fetch a collection using the select or subselect mode the entity in question is track i want to load a collection called trackprices and i am doing this in the queryq qfetchitem itemtrackpriceseagerhowever this creates a left join which results in a problem for pagination i would like it to perform a seperate select or subselect any idea if it can be done as far as i know using the criteria api one would doqdetachedcriteriasetfetchmodetrackprices fetchmodeselectbut i want to avoid magic strings in the code thus i would prefer doing it using the queryover api,['c#'] +130684,whats wrong with registrygetvalue i trying to get a registry valuevar value registrygetvaluehkey local machinesoftwaremicrosoftcryptography machineguid 0in windows xp all ok but in windows 7 returns 0 in hkey local machinesoftwaremicrosoftcryptography using regedit i see machineguid but if i run var keys registrylocalmachineopensubkeysoftwareopensubkeymicrosoftopensubkeycryptography registrykeypermissioncheckreadsubtreegetvaluenameskeyslength is 0what do i do wrong with other values all ok in both of os,"['c#', '.net']" +130693,the content type texthtml charsetutf8 of the response message does not match the content type of the binding textxml charsetutf8 i created wcf service and testing wcf client using stand alone application i was able to view this service using internet explorer also able to view in visual studio service references here is the error messagethe content type texthtml charsetutf8 of the response message does not match the content type of the binding textxml charsetutf8could you please advice what could be wrongthank you,['c#'] +130700,stop safari mobile from giving input buttons rounded corners i guess the subject says it all i have a web application when viewed on an iphone ipod or ipad input submit buttons have rounded corners is there a way to stop this,['ios'] +130703,scroll bars showing on printed page in ie9 i am having an issue with ie9 showing horizontal scroll bars on a printed page even though the contents of the page fit entirely i have tried several things to remove them in my print css has anyone else had this issue and found a way around it,['css'] +130712,is ext js a superset of jquery so jquery handles dom manipulation event handling and special effects ext js also does that plus has a lot of builtin ui componentsheres the question is there anything substantial that jquery has that ext js does notheres the context i have been wondering what reason people would have of using both ext js and jquery some guessesthey feel more comfortable with jquery but need the extra capabilities of ext jsthey have a site already in production with jquery need to add ext js and do not want to rewrite whats already therethere is something that jquery has that ext js does not,['jquery'] +130724,does c support function composition in the latest version of c can i do something like thisi feel like linq is the closest but that is chaining not function composition right,"['c#', '.net']" +130765,c stdlist erasing removing elements while iterating possible duplicatecan you remove elements from a stdlist while iterating through it i have a loop in a function that iterates over an stdlist from begin to endin each cycle i perform some checks and maybe do a few manipulations on the current list entry and in some cases i want to remove it from the listnow as expected my iterator gets invalidatedis there any way to work around this to remove elements from a list while iterating over it,['c++'] +130780,gui alternative to when you have a lot of options a select might be good for choosing between 315 simple items but how do you deal with 15100the simplest option would be to just have a plain select with a lot of options but it is not very user friendly there is a lot of scrolling and it might be hard to find the option you are looking for the benefit is that you can maybe with scrolling see all the options you havea more advanced option would be to have a text field with autocomplete a user types in a letter or two and search results come back which you choose from it makes it easier to find the option you are looking for if you know what you are looking for the drawback is that the user cannot see all the optionsan even more advanced option would be to build a search list and choose widget which defaults to show x items but allows you to search an advantage of this approach is that i can allow search on multiple attributes and not just the name of the item which is to be selectedwhat solutions have you deployed inthese situationsis there a jquery plugin i should know about,"['javascript', 'jquery', 'html', 'css']" +130781,how is the stack initialized when a process requests for memory and an operating system is giving some new pages to the process the kernel should initialize the pages with zeros for instance in order to avoid showing potentially confident data that another process used the same when a process is starting and receives some memory for example the stack segment when i execute the following code in linux the result is that the majority of allocated memory is indeed 0 but something about 34 kb at the bottom of the stack the last elements of the array the highest addresses contains random numbersinclude cstdlibinclude iostreamusing namespace stdint main int a intallocasizeofint20 forint i 0 i 20 i cout ai endl return 0why is not it set to zero too could it be because it is being reused by the process if yes could it be the initialization code that had used those 34 kb of memory earlier,"['c++', 'c']" +130787,how to see the real sql query in python cursorexecute i use the following code in python with pyodbc for a msaccess basecursorexecuteselect a from tbl where b and c x yit is ok but for maintenance purposes i need to know the complete and exact sql string send to the databaseis it possible and how,"['python', 'sql']" +130812,how to thisplay the time in users timezone i am using rails 305 and i have created at and updated at stored in utc now i want to thisplay the created at time in users timezone i believe it is possible to pick users timezone from the browser and then convert time to users timezonei am sure rails will have a gemplugin to take care of something like this is there something,['ruby-on-rails'] +130814,how to save app on back button press how can i store the state of my app when back button is pressedwhen back button is pressed only onpause is called but not onsaveinstancestate where we can store our data in outstate bundleone answer may be sharedpreference but my problem is it will store only int and not intarray as bundles doesis there any way to explicitly call onsaveinstancestate,['android'] +130827,efficiency comparison of recursion and non recursive function in java as i understand recursive functions are generally less efficient than equivalent nonrecursive functions because of the overhead of function calls however i have recently encountered a text book saying this is not necessary true with java and cit does not say why but i assume this might be because the java compiler optimizes recursive functions in some waydoes anyone know the details of why this is so,"['c#', 'java']" +130834,query time result in mysql w php is there a way that i can get the time of a mysql query specifically with php the actual time it took to complete the query that issomething such as results 1 10 for brown 011 seconds i tried to look for an example to no avail here is an example of my code prepare sql statement stmt dbhprepareselect ijl description source user id timestamp from submissions where match ijl description against bind parameters stmtbindparam1 search pdoparam str execute prepared statement stmtexecutefor my current full text search using a myisam table engine any help would be incredible thank you,"['php', 'mysql']" +130839,java memory allocation alignment i know this is a weird question to ask in javabut is there a way to let java dynamic memory allocation be aligned with some alignment constraintsfor example is it possible to dynamically allocate objects that are aligned with the page sizethe reason i want to do this is because i am going to access the java object from native code through jni interface and the native code library requires the object to be alignedthanks,['java'] +130849,rails habtm callbacks is there a way to add callbacks for when an item is added to a habtm relationshipfor example i have the following two models user and role userrbclass user has and belongs to many roles end rolerbclass role has and belongs to many users endi want to add a callback to the method user role but i cannot seem to find an activerecord callback because there is no model for the join table because its a true habtm i am aware that i could write a method like add to rolerole and define everything in there but i would prefer to use a callback is this possible,['ruby-on-rails'] +130856,android fragment backstack issue i have the following code in my activity public void categoryclickedint categoryid string categoryname itemlist newfragment itemlistnewinstancecategoryid fragmenttransaction ft getfragmentmanagerbegintransaction ftreplaceriditemcontainer newfragment ftsettransitionfragmenttransactiontransit fragment open ftaddtobackstacknull ftcommit it works as expected i am able to go back after clicking a few times to the previous states however if i only go one deep i get the following exception0310 221719895 errorandroidruntime23075 javalangillegalstateexception content view not yet created0310 221719895 errorandroidruntime23075 at androidapplistfragmentensurelistlistfragmentjava3770310 221719895 errorandroidruntime23075 at androidapplistfragmentgetlistviewlistfragmentjava2770310 221719895 errorandroidruntime23075 at comxfragmentitemlistonactivitycreateditemlistjava670310 221719895 errorandroidruntime23075 at androidappfragmentmanagerimplmovetostatefragmentmanagerjava7490310 221719895 errorandroidruntime23075 at androidappfragmentmanagerimplmovetostatefragmentmanagerjava9210310 221719895 errorandroidruntime23075 at androidappbackstackrecordpopfrombackstackbackstackrecordjava6390310 221719895 errorandroidruntime23075 at androidappfragmentmanagerimplpopbackstackstatefragmentmanagerjava12540310 221719895 errorandroidruntime23075 at androidappfragmentmanagerimplpopbackstackimmediatefragmentmanagerjava4020310 221719895 errorandroidruntime23075 at androidappactivityonbackpressedactivityjava20570310 221719895 errorandroidruntime23075 at androidappactivityonkeydownactivityjava19530310 221719895 errorandroidruntime23075 at androidviewkeyeventthispatchkeyeventjava23350310 221719895 errorandroidruntime23075 at androidappactivitythispatchkeyeventactivityjava22360310 221719895 errorandroidruntime23075 at comandroidinternalpolicyimplphonewindowdecorviewthispatchkeyeventphonewindowjava16480310 221719895 errorandroidruntime23075 at androidviewviewrootdeliverkeyeventpostimeviewrootjava26820310 221719895 errorandroidruntime23075 at androidviewviewroothandlefinishedeventviewrootjava26550310 221719895 errorandroidruntime23075 at androidviewviewroothandlemessageviewrootjava19520310 221719895 errorandroidruntime23075 at androidoshandlerthispatchmessagehandlerjava990310 221719895 errorandroidruntime23075 at androidoslooperlooplooperjava1260310 221719895 errorandroidruntime23075 at androidappactivitythreadmainactivitythreadjava39970310 221719895 errorandroidruntime23075 at javalangreflectmethodinvokenativenative method0310 221719895 errorandroidruntime23075 at javalangreflectmethodinvokemethodjava4910310 221719895 errorandroidruntime23075 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava8410310 221719895 errorandroidruntime23075 at comandroidinternaloszygoteinitmainzygoteinitjava5990310 221719895 errorandroidruntime23075 at dalviksystemnativestartmainnative methodso basically if i only call the replace once it errors out on my when i hit the back button also with listfragment do i have to set the background to white i did not touch it and i can see the old listview showing throughthanks,['android'] +130868,finding local maxima over a dynamic range working in c i need to find all local peaks in a list of doubles and return them as another list doubles this seems simple enough if i have a set number of values i am comparing in any given window of values but i need to be able to actually pass this window size into the function itself that may be confusing but basically i need something like thispublic listdouble findpeakslistdouble values double rangeofpeakswhere if rangeofpeaks was 5 the current value would be compared to 2 values on each side of it to determine if it was a peak or not if rangeofpeaks was 11 the current value would be compared to 5 values on each side i would think this was a pretty basic algorithm however i have been unsuccessful in finding any good methods for detecting a peak like this has anyone ever done this before any help at all would be appreciated thanks in advance,['c#'] +130873,integrate existing aspnet mvc application with orchard cms i have orchard cms and i want to integrate my mvc site with it can anybody tell me how to do this,"['.net', 'asp.net']" +130874,ctl complex text language support in android i am trying to develop android ime for asia language require complicated rendering such as changing glyph forms reordering character order etc in pc the use of gtk pango graphite is sufficient in android how can i solve rendering of unicode for complex text languagethanks in advance,['android'] +130882,multiple packages in contextcomponentscan spring config how can i add multiple packages in springservletxml file in contextcomponentscan elementi have triedcontextcomponentscan basepackagezyzservice basepackagexyzcontroller andcontextcomponentscan basepackagexyzservice xyzcontroller andcontextcomponentscan basepackagexyzservice contextcomponentscan basepackagexyzcontroller but got errororgspringframeworkbeansfactorynosuchbeandefinitionexception no matching bean of type xyzdaodaoservicelogindao found for dependency,['java'] +130885,online php syntax checker validator could someone refer me to an online php validator it would be of much help thanks in advance,['php'] +130895,multiple file upload using cocoahttpserver or with any http server on iphone i used cocoahttpserver for transferring content to iphone in my application but it just provides single file upload but i saw applications which provide multiple uploads such as dropbox mydocs during googling i found that they are using kinda swf to perform multiple uploads so can anyone guide me to do multiple uploads for iphone using any existing http server or to modify cocoahttpserver for the same i am very new to server side programming and i have to implement multiple file uploading scheme for iphone where iphone would be acting as a http serverthanks in advance,"['iphone', 'objective-c']" +130921,what does the mean in tolower i have seen code like thisstdstring str whateverstdtransformstrbegin strend strbegin tolowerand i have a question what does mean before tolowerand stdtolower not works but tolower works ok,['c++'] +130929,why the unit test frameworks in fortran rely on ruby instead of fortran itself summarization fruit can be used only with fortran compilers although its functionality can be enhanced by using ruby check the answer below from its author andrew chenit seems that the available unit test frameworks xunit for fortran includefunitfruitflibsobjexxftk commercialin their webpages funit fruit and flibs mention they rely on ruby to function i have no idea about objexxftk it seems to me that xunit frameworks in java c and delphi and so forth only rely on the corresponding language itself then why do the fortran frameworks choose to rely on ruby instead of fortran itself,['ruby'] +130932,what happens if more than one user control registers documentready function i have a couple of user controls in an aspx page and each user control may need to register a startup block as an documentready function event handlerdo they override each previous functions of they are chained in order of registration,"['javascript', 'jquery', 'asp.net']" +130934,twitter api allow accept request to follow authenticated user i have a protected twitter account due to the age restricted content being thisplayed is there a way to use the twitter api to accept or reject the requests to follow this account i know that i can view these requests usingbut which request will accept a request i was looking at therequest but this seams to follow a user rather than accept the request for them to follow me,['php'] +130938,default text for empty repeater control using vs 2008 i have a repeater controlasprepeater runatserver idstoresrep datasourceidstoresqldatasource onitemdataboundstoresrep itemdatabound itemtemplate table stylepadding0px tr td stylewidth200pxasplabel idinfolbl runatserver choose stores for uploadasplabelnbspnbspnbspnbsp td td stylewidth110px asplabel idstorelbl runatserver text bindname asplabelnbspnbsp td tdaspcheckbox runatserver idstorecheck td tr table itemtemplateasprepeateraspsqldatasource idstoresqldatasource runatserver connectionstring connectionstringssomeconnectionstring selectcommandselect storeid name from store order by nameaspsqldatasourcenow i would like to thisplay a default text like no stores found if data source returns no items from database until now i have mostly used gridview where i did not have problems because of the emptydatatext attribute,['asp.net'] +130944,cython converting pointers to arrays into python objects alright i am so close to finishing this i can taste it over the past few week or so i have been attempting to create a python extension to interface with a library written in c via cython with a little help from the guys here and a couple of friends i have managed to get what feels like 98 of the way there only thing remaining is this i cannot for the life of me figure out how to turn a pointer to an array of unsigned shorts into a python object preferably a lista little background i am trying to interface with a part of the library that sets a callback function which i have successfully done with thisglobal callbackfuncctypedef unsigned short const ushort const uint16 tctypedef void function1const ushort data unsigned width unsigned heightcdef extern from libhpp void setcallbackfunction1cdef void csetcallbackfunction1 function setcallbackfunctioncdef void callcallbackconst ushort data unsigned width unsigned height global callbackfunc callbackfuncdatawidthheightcsetcallbackcallcallbackdef pysetcallbackcallbackfunc global callbackfunc callbackfunc callbackfuncthe problem occurs within the function callcallback where i get the error cannot convert const ushort to python object my first attempt around this was to create a new python list and loop through to get each element of the array into a python list like thisdatalist for i in rangewidthheight datalist dataiwhich sadly nets me with the compiled cython code trying to define a type as a const const unsigned short which is obviously a problemthen i tried thisdatalist for i in data datalist iwhich gives me c array iteration requires known end index note that i know very little cc so most of this does not make much sense to meso anyways is there any effective way of translating a pointer like that into a python object preferably faster than looping through the array since it is usually about 57344 items and this is quite time sensitiveedita little more clarification as i mentioned i am working with callbacks and the c function within the library that calls this sends a pointer to an array of const uint 16s which is why i defined const ushort that way because otherwise the types do not unify i cannot modify the library in any wayedit2looks like i got it what i ended up having to do was explicitly cast the array as an array of unsigned shorts rather than an array of const unsigned shorts to i could index them with a non constant to achieve this i created another c function like this someone else wrote it for me i barely know cunsigned short convert shortconst unsigned short test return const castunsigned short test and that allowed me to create the getindex function within my class and return the correct values based on the function so yeah python seems to be reading the arrays correctly and whatnot so this case seems closed thanks a lot,['python'] +130964,how to hide uitabbarcontroller i have a problem with uitabbarcontroller in my application i want to hide it but without using hidesbottombarwhenpushed because i want to hide it not when i pushed it for example i want to hide it when i press a hide button in my application i read many articles in google but i cant find out how i can do this,"['iphone', 'ios']" +130978,is there an api in jqgrid to add advanced filters to post data i see how in this code you can preset postdata filters by have this in your javascriptpostdata filtersgroupopandrules fieldinvdateopgtdata20070906 fieldinvdateopltdata20071004 fieldnameopbwdatatestis there any api that allows you to build this up something likejqgridgridaddpostdatafiltersandjqgridgridaddfilteritemfield cn valuejqgridgridaddfilteritemfield1 eq value2to help generate to top postdata filter code i tried this but it does not seem to workjqgridsetgridparam editurl projectupdateme ondblclickrow function rowid editprojectrowid windowlocationhrefprojectdetailrowid var grid gridvar f groupop and rules frulespush field name op cn data volat gridpsearch fruleslength 0extendgridppostdata filters jsonstringifyf updatei have this working now thanks to oleg but ifor some reason the find button somethng comes up with blank even thought i do have an advanced filter set i have added a picture,['jquery'] +130995,javascript currying i am trying to create curry function that can be applied to any function and return another with 1 of the arguments appliedproperties that i want to haveif function has only one argument curry function should return valuefa curryfx fxif function has many arguments currey should retrun curried functionga1a2an currygx g2a2an g2a2angxa2anlength propery of curried function should work as neededglength and currygxlength n1there is some implementations of curry in prototype framework and thiscussion in one blog but this implementation is not good because it does not work well on functions with only one argument 1 and also returning function length attribute is 0 3for first property there is an easy implementation function curryfx if flength 1 return fx but i do not know how to work with 3rd rule ie function can be constucted as inner function since there will be a nested lexical environment and will be able to use ffunction curryfx return function but in this case i will no longer will able to explicitly set parameters on the other hand function can be constructed with new function statement smth like that function curryfx var args for var i1 iflength i argspushai var sa argsjoin return new functionsareturn fxsa but in this situation f and x will unbound because anonymous function will be created inglobal lexical environmentso the questionsis there a way to explicitly set parameters count when creating function with function keywordis there a way to set environment of function created with new function statementus there a way to solve my problem in any other way,['javascript'] +131044,union in c are they feasible can a union in c have a member function how do union with data members and member functions exist if an object is createdif i suppose yes then are they feasible any where if yes then where,['c++'] +131053,input string was not in a correct format 2 double temptemp doubleconverttodouble12345678hey lads and ladies i cannot for the life of me figure out why the above line is not working the above line gives me a runtime error that saysan unhandled exception of type systemformatexception occurred in mscorlibdlladditional information input string was not in a correct format,"['c#', '.net']" +131055,correct way to do a css wrapper i have heard a lot of my friends talk about using wrappers in css to center the main part of a website is this the best way to accomplish this what is best practice are there other ways,"['html', 'css']" +131070,how to compare enum and int values enum myenum invalid0 value11 value12void main myenum e1 myenumvalue1 int i1 2 is there any difference how to compare enumeration values with integers if e1myenumi1 1st if inte1i1 2ndin each of mentioned cases we have convertion of enum to int or int to enumis there any difference in these conversions performance any other or they are exactly the samethanksps in current example i compare to magic number but in real application i am getting data from integer field from db,"['c#', '.net']" +131073,i cannot click on an aspbutton if it is hidden using jquery i have found stackoverflow answers and other resources saying that you can click on a hidden aspbutton with jquery byhiddenbuttonclientidclickorhiddenbuttonclientidtriggerclickhowever neither of these are working for me unless the button is visibletruehere is the buttonaspbutton idloadcustomercontacts runatserver onclickloadcustomercontacts click visiblefalse,['asp.net'] +131084,is it possible to read cpu cache hitmiss rate in android is it possible to read cpu cache hitmiss rate in android,['android'] +131091,jquery 151 breaks all ajax calls when i upgrade to jquery 151 or 15 all of the ajax calls in my site produce a parserror in the error option function there is also a script error uncaught syntaxerror unexpected token jquery151minjs16the site has been running wo errors using 144 here is code from one of the ajax callsajax url customergroupget type post contenttype applicationjson charsetutf8 datatype json success function grp if grp null clear group grp loadgrp else showerror customer group whoops error getting customer group information please contact and include your username and datetime of the error error function xse showerror customer group whoops error getting customer group information please contact and include your username and datetime of the error after much research i can not figure out why the error is occurring any insights appreciatededitedwith the full version of jquery i get the followinguncaught syntaxerror unexpected token ddextendglobalevaljquery151js16dajaxsetupconverterstext scriptjquery151js16bjjquery151js16wjquery151js16dsupportajaxdajaxtransportsendcjquery151js16and yes i am using jqueryvalidate,['jquery'] +131109,are there any restrictions on postgres column alias names are there any restrictions in terms of length ability to include nonascii characters etc on the name of a postgres column alias and have there been any changes to such restrictions from version 81 to the present,['sql'] +131110,use jquery to generate an arbitrarily deep list in javascript i have an array of objects that represents an arbitrarily deep listdata title depth title depth title depth title depth where depth is how deep in the list the element isi want to convert this data into htmlfor example title one depth 1 title two depth 1 title three depth 2 title four depth 3 title five depth 1 becomesul liponepli li ptwop ul li pthreep ul lipfourpli ul li ul li lipfivepliulwhat is the simplest way to do this using jquerythanks,"['javascript', 'jquery']" +131125,why does viewwillappear not get called when an app comes back from the background i am writing an app and i need to change the view if the user is looking at the app while talking on the phonei have implemented the following method voidviewwillappearboolanimated super viewwillappearanimated nslogviewwillappear svframe cgrectmake00 00 3200 selfviewboundssizeheightbut it is not being called when the app returns to the foregroundi know that i can implementnsnotificationcenter defaultcenter addobserverself selectorselectorstatusbarframechanged nameuiapplicationdidchangestatusbarframenotification objectnilbut i do not want to do this i would much rather put all my layout information in the viewwillappear method and let that handle all possible scenariosi have even tried to call viewwillappear from applicationwillenterforeground but i cannot seem to pinpoint which is the current view controller at that pointdoes anybody know the proper way to deal with this i am sure i am missing an obvious solution,"['iphone', 'objective-c']" +131130,java coding standards what coding standards in java should a programmer definitely follow for a more readable code,['java'] +131137,using wmi to identify which device caused a win32 devicechangeevent i have been writing some code that detects add and removal of usb devices and i have used the following wmi code to register for device change notificationswatcher new managementeventwatcherquerywatchereventarrived new eventarrivedeventhandlerdevicechangeeventreceivedwatcherstartthis is the handler codevoid devicechangeeventreceivedobject sender eventarrivedeventargs e foreach propertydata pd in eneweventproperties logdebugt pdname pdvalue t pdvaluegettype this is great and all it works for any usb device i plug in or remove from the system the problem that i am having is how do i identify the the device specifically that caused the events elsewhere in my program i am keeping a list of currently connected devices that i am most interested in so if a deviceremoved event comes through i can check that list against wmi using select from win32 pnpentity or some other similar query but this is a very inaccurate and cumbersome way of identifying the device that was removed the added problem is i have no way of accurately telling what device was added unless i cache the entire list of win32 pnpentity ahead of time and do really crazy comparisonsvalidationsam i missing something obvious here how do i associate the device change events to a specific deviceupdate i still have not come up with an ideal solution to this problem but what i am doing is maintaining a list of currently connected devices that i am interested in in memory and every time an event is handled see above i query the win32 pnpentity to see if the devices i have stored in my connected device list are still connected this is a suboptimal solution because it just seems weird that i cannot get any specific device identification information from the event that indicates device change event seems very strange that this info is unavailable sigh,['c#'] +131141,how to choose correct image resolution for android i have been battling with this for a couple of days i am trying to write a small custom rating bar with some custom images when i check the image i have on my htc desire the image looks horribly aliased i have tried using different resolutions and different sizes and still cannot figure out what resolutionhow to create a good qualityi have read the guidelines on the android site but to no avail i think the problem i am having is thisplaying lower resolution images on a higher dpi thisplay so the system upscales the image but i am not sure how to fix that higher resolution images larger images any advice would be greatalex,['android'] +131156,get total for limit in mysql using same query i am making a pagination method what i did wasfirst query will count all results and the second query will do the normal select with limitis there technically any way to do this what i have done but with only one querywhat i have nowselect count from tableselect from table limit 010,['mysql'] +131159,scale now or later i am looking to start developing a relatively simple web application that will pull data from various sources and normalizing it a user can also enter the data directly into the site i anticipate hitting scale if successful is it worth putting in the time now to use scalable or thistributed technologies or just start with a lamp stack framework or not any thoughts suggestions or comments would helpthisregard my vague description of the idea i would love to share once i get further along,['ruby-on-rails'] +131178,warning implode functionimplode invalid arguments passed i am getting the error belowwarning implode functionimplode invalid arguments passed in wpcontentthemesmythemefunctionsphp on line 1335atfunction my get tags sitemap if function existswp tag cloud get optioncb2 noposttags return unlinktags get optioncb2 unlinktags echo div classtagsh2tagsh2 ifunlinktags tags get tags foreach tags as tag ret tagname error occurs here echo implode ret else wp tag cloudseparator smallest11largest11 echo divany ideas how to intercept the error the site has exactly one tag,['php'] +131191,check if a string variable is in a set of strings which one is betterx abc x def x ghiwabc def ghiinclude xx abcdefghi,['ruby'] +131208,how to change choose file into browse input typefile i want to change the default input type file value choose file into browsehow to do thatthanks,['html'] +131252,date comparison to find which is bigger in c i want to know how to find which is bigger date using a c programkindly help me out plzthanks,['c'] +131253,how can i convert bitarray to single int how can i convert bitarray to single int the fastest way pls,"['c#', 'asp.net']" +131259,using an image as a submit button if i want to make my own clickable buttons i can do thisa hrefjavascript classbuttonsign upawhere css rules for abutton causes the link to be shown as a button if i apply the same trick to input typesubmit i get the button image but it is shown on top of the default submit button and the cursor does not change to a hand like it does on a tagshow can i fix this behavior,"['html', 'css']" +131286,recommendations for c database access hi i have programmed a fair bit of c but never with a database i would like to use sql server with c with some framework microsoft seems to have shipped a number of frameworks through the lifetime of c this makes it difficult for me to searchchoosewhich one should i choose i am developing a simple 3tier webapp i have watched a few entity framework net 40 videos but i get the feeling that things are too automatic i need to do some sql now and then and if i should go for the ef40 is this really the best reference any recommendations,['c#'] +131323,xpath fails if an element has a a xmlns attribute possible duplicatexpath finds nothing but im trying to use xml to parse a collada file the problem is i cannot seem to use xpath to access elements if the root tag has a xmlns attribute for example this works string testxml version10 encodingutf8collada version141 library materials material idmaterial namematerial instance effect urlmaterialeffect material material idmaterial2 namematerial instance effect urlmaterialeffect2 material library materialscolladatestlol new simplexmlelementstringprint rlollibrary materialsxpathmaterialidmaterial2but this does not string testxml version10 encodingutf8collada xmlns version141 library materials material idmaterial namematerial instance effect urlmaterialeffect material material idmaterial2 namematerial instance effect urlmaterialeffect2 material library materialscolladatestlol new simplexmlelementstringprint rlollibrary materialsxpathmaterialidmaterial2how does the xmlns suddenly make the xml tree unusable i thought it just defined the namespace so you could tell it apart from other identical tags in other namespaces what am i missing,['php'] +131334,use of a functor on for each why does the for each call on functor does not update sumtotal at the endstruct sum sumtotal0 int total void operatorint element totalelement int main sum s int arr 0 1 2 3 4 5 stdfor eacharr arr6 s cout stotal endl prints total 0,['c++'] +131338,why are my threaded mysqldb queries in python slower than the same nonthreaded queries i am building a threaded class to run mysql queries using python and mysqldb i do not understand why running these queries threaded is slower than running them nonthreaded heres my code to show what i am doing first heres the nonthreaded functiondef testquerydoquery list db mysqldbconnectlocalhost user pass db name cursor dbcursor q list query list for each in q list cursorexecuteeach results cursorfetchall dbcloseheres my threaded classclass querythreadthreadingthread def init self queue threadingthread init self selfqueue queue selfdb mysqldbconnectlocalhost user pass db name selfcursor selfdbcursor def runself cur query selfqueueget selfcursorexecutecur query results selfcursorfetchall selfdbclose selfqueuetask doneand heres the handlerdef queryhandlerquery list queue queuequeue for query in query list queueputquery total queries lenquery list for query in rangetotal queries t querythreadqueue tsetdaemontrue tstart queuejoini am not sure why this threaded code is running slower whats interesting is that if i use the same code only do something simple like addition of numbers the threaded code is significantly fasteri understand that i must be missing something completely obvious however any support would be much appreciated,"['python', 'mysql']" +131340,mass downcase a field for all records in rails when i first implemented a user model i allowed the user to type upper or lowercase email for their login info the problem is that its a mobile app and sometimes autocaps happen so the user would not get authenticated i have changed the create method to downcase the email first however this causes people with existing accounts to not be consistent so how can i add a migration to mass update the email field in the users table to downcase it,"['ruby-on-rails', 'ruby']" +131347,mocking functions using python mock i am trying to mock a function that returns some external content using the python mock module i am having some trouble mocking functions that are imported into a modulefor example in utilpy i have def get content return stuffi want to mock utilget content so that it returns something elsei am trying thisutilget contentmockreturn valuemocked stuffif get content gets invoked inside another module it never actually seems to return the mocked object am i missing something in terms of how to use mocknote that if i invoke the following things work correctly utilget contentmockreturn valuemocked stuff utilget contentmocked stuffhowever if get content is called from inside another module it invokes the original function instead of the mocked version from mymodule import myobj utilget contentmockreturn valuemocked stuff mmyobj mfuncstuffcontents of mymodulepyfrom util import get contentclass myobj def func get contentso i guess my question is how do i get invoke the mocked version of a function from inside a module that i callit appears that the from module import function may be to blame here in that it does not point to the mocked function,['python'] +131363,how to build libevent version 2010 with visual studio 2008 does anyone have clear instructions on building libevent2010 with visual studio 2008,"['c++', 'c']" +131373,is jvm stopped while executing jmap does my java application continue running while jmap is taking its memory dumpthanks,['java'] +131378,is there a way to only install the mysql client linux are there are any linux mysql command line tools that do not require the entire mysql db installation package to be installed what i am trying to do is from server 1 app server execute mysql commands that will get executed on server 2 db server i do not want to run the db on the local server or to install the full blown mysql db,['mysql'] +131384,mysql entity framework 40 stored procedure field mapping has anyone here used mysql with the entity framework 40 and stored procedures when i add a sp it does not show any of my fields that i need to input i also see no way to manually add them when i click function import mapping it simply says select an entity or association on the entity designer model browser to edit it is mapping any help is appreciated i am using the net connector 636,"['.net', 'mysql']" +131401,is digest authentication possible with jquery i am trying to send a request that requires http digest authentication is digest possible in jquery if so is this close to the correct way to do it it is not currently workingscript typetextjavascript ajax url url type get datatype json success function alerthello error function alerterror beforesend setheader function setheaderxhr xhrsetrequestheaderauthorization digest usernamepassword xhrsetrequestheaderaccept applicationjson script,['jquery'] +131409,why is stdmap implemented as a redblack tree why is stdmap implemented as a redblack treethere are several balanced binary search trees bsts out there what were design tradeoffs in choosing a redblack tree,['c++'] +131428,c making my project support unicode my c project currently is about 16k lines of code big and i admit having completely not thought about unicode support in the first placeall i have done was a custom typedef for stdstring as string and jump into codingi have never really worked with unicode myself in programs i wrotehow hard is it to switch my project to unicode now is it even a good ideacan i just switch to stdwchar without any major problems,['c++'] +131430,in python what operator to override for if object i find it very handy to check if an object is empty with the following constructlif l do stufor a standard python list the if will be executed only if the list is not emptymy question is how can i implement the same idea for my own objects,['python'] +131448,java advanced imaging where to get latest binary build i am searching for the latest official binary builds of java advanced imaging at least the platform independent javaonly build the official project web page is on but it only links to the source binary builds are not mentioned or am i too blind to see them,['java'] +131497,how to crosscompile for mips i have a dvb receiver settop box similar like dreambox and it has mips cpuit has embedded linux and i can connect to it with telnetquestion is how to compile simple hello world application in c where to get toolchain sdk,['c'] +131519,what load factor should be used when you know maximum possible no of elements in hashset what load factor should i use when i really know the maximum possible no of elements in a hashset i had heard that the default load factor of 075 is recommended as it offers good performance tradeoffs between speed space is this correct however a larger size hashset would also takes more time in creation and more spacei am using hashset just inorder to remove duplicate integers from a list of integers,['java'] +131524,is objectdb production ready in this benchmark objectdb is far the fastest dbbut i cannot see any other benchmark results from objectdbis anyone using objectdb is it production ready what are the experiences,['java'] +131532,ec2 fresh php install mail not working i am getting familiar with amazons ec2 i installed a lamp setup but when i try to send emails through the mail function that i have in my pages it does not work i checked and sendmail is running and is on the phpinfo pagei have tried changing the phpini sendmail from and it does nothing smtp port is open on the firewall im freakin lost,['php'] +131540,fast or bulk upsert in pymongo how can i do a bulk upsert in pymongo i want to update a bunch of entries and doing them one at a time is very slowthe answer to an almost identical question is here bulk updateupsert in mongodbthe accepted answer does not actually answer the question it simply gives a link to the mongo cli for doing importexportsi would also be open to someone explaining why doing a bulk upsert is no possible no a best practice but please explain what the preferred solution to this sort of problem isthanks,['python'] +131541,noclassdeffounderror when using powermock i am running a junit test case using the powermock test runneri am using the following command line to execute itjava cp junit49b2jareasymock30jarpowermockeasymock148fulljar orgjunitrunnerjunitcore sampletestwhen doing so i am receiving this errorinitializationerrorsampletestjavalangnoclassdeffounderror orgjunitinternalrunnerstestclassrunnerhow can i fix it,['java'] +131551,convert integer value to matching java enum i have an enum like thispublic enum pcaplinktype dlt null0 dlt en10mb1 dlt en3mb2 dlt ax253 snip 200 more enums not always consecutive dlt unknown1 private final int value pcaplinktypeint value thisvalue value now i get an int from external input and want the matching input throwing an exception if a value does not exist is ok but preferably i would have it be dlt unknown in that caseint val inreadintpcaplinktype type convert val to a pcaplinktype,['java'] +131564,css pseudoclasses with inline styles is it possible to have pseudoclasses using inline stylesexamplea href stylehovertextdecorationnonegoogleai know the above html would not work but is there something similar that willps i know i should use an external style sheet and i do i was just curious if this could be done using inline styles,"['html', 'css']" +131573,check opacity by jquery how do i check if the opacity of an element is 0 and then do something in jquery,"['javascript', 'jquery', 'html', 'css']" +131574,fragment duplication on fragment transaction ok whenever i try to replace a fragment in my application it only adds the fragment inside of the container the other fragment is and leaves the current fragment i have tried calling replace and referencing the view the contains the fragment and by referencing the fragment itself neither of these work i can add a fragment to a view with the fragment transaction manager but even if i try to remove it after its been added it does not work any help would be appreciated here are my filespublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain setup the actionabar use setdrawablebackground to set a background image for the actionbar final actionbar actionbar getactionbar actionbarsetthisplayshowtitleenabledfalse actionbarsetthisplayuselogoenabledtrue actionbarsetnavigationmodeactionbarnavigation mode tabs actionbaraddtabactionbarnewtabsettextrstringhome tab textsettablistenerthistrue actionbaraddtabactionbarnewtabsettextrstringinsert tab textsettablistenerthis fragment fragment new insert button frag fragmenttransaction transaction getfragmentmanagerbegintransaction transactionreplaceridbutton fragment fragment transactionaddtobackstacknull transactioncommithere is the layoutlinearlayout xmlnsandroid androidorientationvertical androidlayout widthfill parent androidlayout heightfill parent linearlayout androidorientationvertical androidididbutton fragment container androidlayout widthfill parent androidlayout heightwrap content fragment androidnamecombvsilveredittabhome button frag androidididbutton fragment androidlayout widthfill parent androidlayout heightwrap content linearlayout linearlayout androidorientationhorizontal androidlayout widthfill parent androidlayout heightfill parent fragment androidnamecombvsilveredittabquick insert frag androidididquick insert frag androidlayout width350dip androidlayout heightfill parent fragment androidnamecombvsilveredittabeditor frag androididideditor frag androidlayout widthfill parent androidlayout heightfill parent linearlayoutlinearlayoutand here is the fragment codepublic class insert button frag extends fragment override public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate superoncreatesavedinstancestate return inflaterinflaterlayoutinsert buttonscontainer false like i have said i have tried referencing the fragments parent view to replace it and the fragment itself by id and still it only adds the new fragment inside the containing view the original fragment is in,['android'] +131627,self referencing many to many relationships in fluent nhibernate automapping automapping to 1n and not nn the title pretty much explains it all i have a member object that references friends who are also type memberpublic class member entity public member friends new listmember public virtual ilistmember friends get set the schema generation tool makes it a 1n relationship while it should be a nn relationship ie a column is added to the member table called member id and no connecting table is createdis there any way to make a self referencing many to many relationships in fluent nhibernatei tried using an override that i got as an answer beforepublic class memberoverride iautomappingoverridemember public void overrideautomappingmember mapping mappinghasmanytomanym mfriends tablememberfriendslinktable but i get the error messagenhibernatemappingexception repeated column in mapping for collection projbomemberfriends column member idthanksedit i found the answer it is to putmappinghasmanytomanym mfriendsparentkeycolumnmember idchildkeycolumnfriend id tablememberfriendslinktableinversecascadesaveupdate,"['c#', '.net']" +131629,iphone ad hoc build using xcode 4 i just switched to xcode 4 and need to make an ad hoc build so my customer can test my app yet every tutorial i find is based on xcode 3 and i cannot seem to find my way with xcode 4 on similar settings and actions i need to do is there a tutorial or anything out there that can help me on this i googled it but with very poor results,['ios'] +131636,restart logging to a new file python i am using the following code to initialize logging in my applicationlogger logginggetloggerloggersetlevelloggingdebug log to a filedirectory reserveddypelogfilesnow datetimenowstrftimeymd hmsfilename ospathjoindirectory dype slog nowfile handler loggingfilehandlerfilenamefile handlersetlevelloggingdebugformatter loggingformatterasctimes filenames linenod funcnames messagesfile handlersetformatterformatterloggeraddhandlerfile handler log to the consoleconsole handler loggingstreamhandlerlevel logginginfoconsole handlersetlevellevelloggeraddhandlerconsole handlerloggingdebuglogging initializedhow can i close the current logging file and restart logging to a new filenote i do not want to use rotatingfilehandler because i want full control over all the filenames,['python'] +131643,notices for sequence after running migration in rails on postgresql application when i run my migration in rails application on postgresql i got following notices notice create table will create implicit sequence notification settings id seq for serial column notification settingsidnotice create table primary key will create implicit index notification settings pkey for table notification settingsmy migration file contains 088 create notification settingsrbclass createnotificationsettings activerecordmigration def selfup create table notification settings do t tinteger user id tinteger notification id tboolean notification on tboolean outbound end end def selfdown drop table notification settings endendi would like to know what this notices meanshow to avoid this noticeswhat will be the impact of such notices on the application if not avoidedregardssalil,"['ruby-on-rails', 'ruby']" +131669,how to determine whether appconfig file exists is there a way to find out whether an appconfig file exists without using fileexistsi triedif configurationmanagerconnectionstringselementinformationispresent but ispresent is false even if appconfig with a connection string existseditdid i misinterpret the ispresent property,['c#'] +131695,hiro vs other ioc containers in this article 11 apr 2009 the author claims hiro isthe worlds fastest ioc container a statically precompiled ioc container that performs as fast as an application without an ioc containeris it still the fastest ioc container today is it ready for production are there any other containers can do ioc at compile time what are its major advantages and thisadvantages over other ioc containersthanks,['.net'] +131698,how to add a button to a preferencescreen android i am quite new to android development and just came across preferencesi found preferencescreens and wanted to create a login functionality with it the only problem i have it that i do not know hot i could add a login button to the preferencescreenheres how my preference view looks likepreferencescreen xmlnsandroid preferencescreen androidtitlestringlogin androidkeylogin edittextpreference androidpersistenttrue androidtitlestringusername androidkeyusernameedittextpreference edittextpreference androidtitlestringpassword androidpersistenttrue androidpasswordtrue androidkeypasswordedittextpreference preferencescreenpreferencescreenthe button should be right under the two exittextpreferencesis there a simple solution for this problem the one solution i found was not working because i use sub preference screensupdatei figured out that i can add buttons this waypreferencescreen androidtitlestringlogin androidkeylogin edittextpreference androidpersistenttrue androidtitlestringusername androidkeyusernameedittextpreference edittextpreference androidtitlestringpassword androidpersistenttrue androidpasswordtrue androidkeypasswordedittextpreference preference androidlayoutlayoutloginbuttons androidkeyloginbuttonspreferencepreferencescreenand the layout file layoutbuttonsxml looks that wayxml version10 encodingutf8linearlayout xmlnsandroid androidlayout heightwrap content androidlayout widthfill parent androidweightsum10 androidbaselinealignedfalse androidorientationhorizontal button androidtextlogin androidlayout widthfill parent androidlayout weight5 androidlayout heightwrap content androidididloginbutton androidlayout gravityleftbutton button androidtextpassword androidlayout widthfill parent androidlayout weight5 androidlayout heightwrap content androidididforgottenpasswordbuttonbuttonlinearlayoutso now the buttons appear but i cannot access them in codei tried it with findviewbyid but this is returning null any ideas how i could access these buttons,['android'] +131699,difference between date class in package javautil package javasql in java both the javautil and the javasql package contain a date class so what is the difference between themif one date class is present in java then what is the need of another date class,['java'] +131712,mvvm light relaycommand parameters i am having an issue with passing a parameter to a relaycommand using the galasoft mvvm light framework i know that mvvm lights implementation of relaycommand does not use lambda parameters so i did some research and found a way that people worked around it by doing something like thispublic relaycommand projmenuitem edit get if projmenuitem edit null this should work projmenuitem edit new relaycommandprojeditnode return projmenuitem edit private void projeditnodeobject newtext var str newtext as string organlocationviewmodel sel projectorganlocationviewgetextendedtreeviewgettopnode consolewritelineselorganthisplayname selorganthisplayname strhowever i keep getting an error on the line projmenuitem edit new relaycommandprojeditnode that says argument 1 cannot convert from method group to systemactionwhat am i missing,['c#'] +131728,updating hibernate version manually i have two classes say foo and bar mapped as onetoone bidirectional using hibernate 361 final with jpa 20 like entitypublic class foo id private long id onetoonecascade cascadetypeall mappedby foo private bar bar onetoonecascade cascadetypeall mappedby foo private qux qux version private int version getters and setters omittedentitypublic class bar id private long id onetoone joincolumnname foo id nullable false private foo foo getters and setters omittedentitypublic class qux id private long id onetoone joincolumnname foo id nullable false private foo foo getters and setters omittednote that bar and qux does not have version columnif we update bar then hibernate will not increment the version of foo and same for qux but our business logic needs if someone updates bar in the foo and other thread is trying to update the qux of the same foo but does not have updated bar and vice versa then such updates should failsince hibernate does not update the version property of foo if we update the bar we decided to update the version of foo manually i know it is pretty weird and not recommended if we update the bar and quxit works perfectly fine but i am worry about some corner cases in concurrency which may fail this or will have unintended behavioris it safe to do this kind of tweak with version for this purpose or is there any other better alternative to this i have already tried optimisticpessimistic force increament,['java'] +131742,jquery stoppropagation vs stopimmediatepropagation can anyone point me the differences bw jquery eventstoppropagation and eventstopimmediatepropagation methodspossibly with example,['jquery'] +131745,how to add font color to a net console app is there a way to color the font of certain lines in a console app in netthanks,"['c#', '.net']" +131762,sdkbuildable open source web browsers for android i am trying to build a comprehensive list of known nonaosp open source web browsers for the android from which fellow programmers and i can learnbyexampleby nonaosp i mean that it can be built outside of the full firmware build the stock android browser is probably the best exemplary browser but unfortunately it cannot be built outside of the full firmware buildthe ability to build such apps in a regular android sdk development environment is important for those who learn best by experimenting with code modifications google search for open source browsers for android yields thisappointing results so perhaps we can come up with a more focused result links to actual source code repository would be superso far i managed to find the followingfennec aka mobile firefox source code heremementobrowser sourcecode here,['android'] +131766,mysql cluster ndb vs mysql replication innodb for rails 3 apps proscons we are doing an overview of our current systems trying to figure out if we can improve performance reliabilitycurrently we run a bunch of internal rails apps and our rails based website some are rails 3 already some are being converted to rails 3 they all connect to the following mysql setupmysql01 master server mysql02 slave daily db backups to a drive that is backed up on a daily weekly monthly semiannual basisall writes happen on mysql01 and most short reads go to it as well some more resource consuming reads like monthlyweekly reports that take 310 minutes to run and dump data into csv or backups go to mysql02 server we get about 35k visits per day to our site and have about 2030 internal users that use various apps daily for inventory order processing etc so these servers are not particularly under heavy loads other then those reports that run of the slave anywaysall servers run in a virtualized xen pool on debian lenny vms so we are doing a review of the systems and somebody threw a suggestion of switching to mysql cluster ndb setup i know of it in theory but have never actually run it so does anyone who had experience with it know of any pro cons vs our current setup and of any particular caveats when it involves ruby rails applications,"['mysql', 'ruby-on-rails']" +131791,how to automatically generate comments in visual studio 2010 and c from eclipse i am used that when i start typing a comment for a class or method the parameters return types and exceptions are autogenerated but in visualstudio 2010 i cannot find something like this any hints how to achieve that,['c#'] +131796,amazon aws tutorials i was wondering if there is any tutorials for amazon aws providing a stepbystep guide through setting up and hosting a simple application eg a simple holiday image list applicationi understand most of the components however i cant seem to link them logically togetheri have an amazon free tier account and i have signed up for the following services amazon ec2 amazon s3 amazon simpledb amazon sns sqs amazon elastic beanstalk for eclipseim confused about how to deploy an elastic beanstalk application written in java and eclipse through an ec2 instance etcthanks greatly in advanceu,"['java', 'android']" +131808,primary interop assemblies for microsoft office applications i am trying to install interop assemblies for microsoft office on my web serversfor the use of reading word documents from my sitecan i install just the assembliesor the only way is installing an office suite the exception could not load file or assembly microsoftofficeinteropword version140 cultureneutral publickeytoken71e9bce1e9429c or one of its dependencies the system cannot find the file specifiedlist of interop assemblies,"['c#', '.net']" +131814,is it possible to define a c macro in a makefile is it possible to put the equivalent of define var in a c program into a makefile so that one can control which part of the program should be compiled,['c'] +131818,is there a way to invert an activerecordrelation query let us say we have the followingirb postwherehidden trueto sql select posts from posts where postshidden 1could we somehow get an inverted sql query out of itwhat i am looking for should probably look like thisirb postwherehidden trueinvertto sql select posts from posts where not postshidden 1,"['sql', 'ruby-on-rails']" +131820,avoid creating a clustered index based on an incrementing key i got this hint from mssqlcitycom however i cannot understand its explanationavoid creating a clustered index based on an incrementing keyfor example if a table has surrogate integer primary key declared as identity and the clustered index was created on this column then every time data is inserted into this table the rows will be added to the end of the table when many rows will be added a hot spot can occur a hot spot occurs when many queries try to read or write data in the same area at the same time a hot spot results in io bottleneck note by default sql server creates clustered index for the primary key constraint so in this case you should explicitly specify nonclustered keyword to indicate that a nonclustered index is created for the primary key constraintbefore i read that i thought if i pick a column that is random in nature it is not correct because this will cause unnecessary page relocation when adding a new row so i think using a sorted column is preferrableafter reading this hint i think it is trying to say we do not really want to use a straightly sorted column to be our clustered index either because there is going to be an io bottleneck for those writeintensive applicationi do not really understand the cause of the io bottleneck that they are talking about are they saying too many operations sharing the same page is going to slow down the thisk operations how does this happen can somebody explain to me,['sql'] +131831,does the spring bean container command eliminate duplicate containers does the import command of the spring bean container eliminate duplicate containers for example if bean container file a imports b and c and each these in turn import d does spring eliminate or ignore the duplicate d container,['java'] +131860,should i open and close db for each query i am using old school adonet with c so there is a lot of this kind of code is it better to make one function per query and open and close db each time or run multiple queries with the same connection obect below is just one query for example purpose only using sqlconnection connection new sqlconnectionconfigurationmanagerconnectionstringsdbconnectmainconnectionstring add user to database so they cannot vote multiple times string sql insert into pollrespondents pollid memberid values pollid memberid sqlcommand sqlcmd new sqlcommandsql connection sqlcmdparametersaddpollid sqldbtypeint sqlcmdparameterspollidvalue pollid sqlcmdparametersaddmemberid sqldbtypeint sqlcmdparametersmemberidvalue sessionmemberid try connectionopen int32 rowsaffected intsqlcmdexecutenonquery catch exception ex consolewritelineexmessage,['c#'] +131900,sift hog and surf c opencv i have a simple question which i want to know what kind of libraries are available and can give good results for implementing sift hoghistogram oriented gradient and surf in c or opencvhence 1 give me the link for the code if you can which i will be so appreciated2 if you know one of them or any kind of information to lead me to what i want i will be so appreciated as well thanks,['c++'] +131924,iphone thismiss keyboard when touching outside of uitextfield i am wondering how to make the keyboard thisappear when the user touches outside of the uitextfield,"['ios', 'iphone']" +131925,how can i use systemwebuidatavisualizationchartingchart to make a chart does anyone have a good link for instructions on how to make a basic chart with microsofts builtin chart controli would like to make a stacked bar chart if i could but failing that a regular bar chart would suffice all the data for the chart is the result of a single sql call one result set 1 label column and 3 data columns if that makes any differencemy googlefu is failing me thanks in advance,['c#'] +131929,error handling with ajax in rails 3 i am creating a simple demo app that allows a user to enter their email address to register their interest in receiving beta access the app then sends them a confirmation email that lets them know weve received their request if youve ever signed up to be notified of a beta launch then you get the ideai am curious about how to handle errors in rails 3 while using ajax before implementing my respond to block i had a form that rendered a shared errors partialheres the form if flashnotice p flashnotice p end psign up to be notified when the beta launchesp form for user remote true do form render sharederrors target user formlabel email your email address formtext field email formsubmit notify me end and heres the aforementioned errors partial if targeterrorsany ul targeterrorsfull messageseach do message li message li end ul end very standard stuff the controller action looks like thisdef createuser usernewparamsuserrespond to do format if usersave formathtml redirect to back flashnotice thanks for your interest well let you know when the app is in beta formatjs else formathtml render action new formatjs endendendeverything works perfectly before implementing ajax if the form passes validation then they see the success flash message and if not then they see a list of errors so now that i have a createjserb file how should i handle the errors without repeating myself or is that impossible i obviously want to keep this as dry as possible,['ruby-on-rails'] +131935,how to set bullet colors in ulli html lists via css without using any images or span tags imagine a simple unsorted list with some li items now i have defined the bullets to be square shaped via liststylesquare however if i set the color of the li items with color f00 then everything becomes redwhile i only want to set the color of the square bullets is there an elegant wat to define only the color of the bullets in css without using any sprite images nor span tagshtmlulliitem 1liliitem 2liliitem 3liulcssli liststylesquare,['css'] +131936,move an array element from one array position to another i am having a hard time figuring out how to move an array element for example given the followingvar arr a b c d ehow can i write a function to move d before bor a after cafter the move the indices of the rest of the elements should be updated this means in the first example after the move arr0 would a arr1 d arr2 b arr3 c arr4 ethis seems like it should be pretty simple but i cannot wrap my head around it,['javascript'] +131941,should ithisposablethispose be made safe to call multiple times should implementations of ithisposable make thispose safe to call multiple times or the opposite what approach to most net framework classes takespecifically is it safe to call systemdatalinqdatacontextthispose multiple timesthe reason i ask is because i am wondering if this extra protection is necessarypublic override void thisposebool thisposing extra protection if thisobj null thisobjthispose thisobj null versus simply thisobjthispose basethisposethisposingwhen thisposing ithisposable members of a class or whether i should just call thisobjthispose without concern for whether it has been previously called,"['c#', '.net']" +131945,php http referrer i have a page which accepts posts from a remote site i would like to detect the domain that these posts are coming from i realize that it can be spoofed but it is better than nothingi have tried accessing the http referer variable but it just returns nullthe page accepts posts from sources like paypal instant payment notifications and other payment gatewayshow can i get the referring call,['php'] +131978,measuring thistance with iphone camera how to implement a way to measure thistances in real time video camera on the iphone like this app that uses a card to compare the size of the card with the actual thistanceare there any other ways to measure thistances or how to go about doing this using the card method what framework should i use,['iphone'] +131981,how to send a post request using django i dont want to use html file but only with django i have to make post requestjust like urllib2 sends a get request,['python'] +131983,python socketaccept nonblocking is there a way i can use pythons socketaccept in a nonblocking way that simply runs it and lets me just check if it got any new connections i really do not want to use threadingthanks,['python'] +131988,clear text in edittext when entered i am trying to set and onclicklistener so that when i click within the edittext element it will clear its current contents is there something wrong here when i compile this code i get a force quit and activitymanager cannot thispatch ddm chunk 4d505251 no handler defined errorpublic class project extends activity implements onclicklistener called when the activity is first created edittext edittext edittextfindviewbyidridedittext1 override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate edittextsetonclicklistenerthis setcontentviewrlayoutmain override public void onclickview v todo autogenerated method stub edittextsettext,['android'] +132002,py2exe lxml woes i have a wxpython application that depends on lxml and works well when running it through the python interpreter however when creating an exe with py2exe i got this error importerror no module named elementpathi then used python setuppy py2exe p lxml and i did not get the above error butanother one sayingimporterror no module named gzipcould anyone let me know what the problem is and how i can fix it also should i put anydll files like libxml2 libxslt etc in my thist folder i searched the computerand did not find these files so maybe they are not neededthanksedit i just tried with python setuppy py2exe p i gzip and the exe was created but the exe generated does not run i double click it and it does not do anythingheres the setuppy script i am usingfrom py2exebuild exe import py2exefrom thistutilscore import setupsetup windowsscript guipy edit2 i tried using cx freeze as an alternative but got the sameimporterror no module named elementpatherror did not know how to proceed after that,['python'] +132017,jlabel mouse events for drag and drop i want to enable the drag and drop feature over a jlabel by overriding mouse events over it but when i define the drag and drop in mousepressed event the mousereleased does not take effect on that jlabel am i doing something wrong thumbnailsi loopsettext1 thumbnailsi loopsettransferhandlernew transferhandlertext thumbnailsi loopaddmouselistener new mouseadapter public void mousereleasedmouseevent me systemoutprintlnhere mouse released public void mousepressedmouseevent me systemoutprintlnhere mouse pressed jcomponent comp jcomponent megetsource transferhandler handler compgettransferhandler handlerexportasdragcomp me transferhandlercopy thumbnails is array of jlabelwhen running the program the drag and drop works but the statement here mouse released does not get printed however when i remove the code responsible for dnd from the mousepressed method here mouse released is printedwhat is the wrong in this code,['java'] +132018,android pick images from gallery i want to create a picture chooser from gallery i use code intent new intentintentaction pick androidprovidermediastoreimagesmediaexternal content uri startactivityforresultintent tfrequestcodesgallerymy problem is that in this activity and video files are thisplayed is there a way to filter thisplayed files so that no video files will be thisplayed in this activity,['android'] +132019,in java can we divide a class into multiple files any possibility to divide a class into multiple physical files using java,['java'] +132035,ninject with unity3d unity3d uses gameobjects you add components to these gameobjects where a component is a script in c or js that inherits a base class unity itself is written in native code components cannot have a constructor and instead use reflection to find if you have certain named methods onstart update etcinstead of making my eyes bleed with lack of constructors and other really annoying things i figured i could do the followingpublic class somegamebehaviour public somegamebehaviourigameobject gameobject monobehaviour is the base classpublic class componentwrapper monobehaviour igameobject then i could grab gameobjecttransform or what have you from somegamebehaviour while decoupling it from the unity enforced retardarythe problemi could not use the default injection behaviour because componentsmonobehaviours do not and cannot have constructors it throws errors at you if you try so i rolled my own providerpublic class unityprovider iprovider public object createicontext context var go new gameobjectcontextrequesttargetname typeofcomponentwrapper var c gogetcomponentcomponentwrapper return c public type type get private set i can see in the unity editor that the gameobject gets created and componentwrapper gets attached however ninject throws a null ref error at me which i cannot figure out it seems to be doing further stuff to either igameobject or the target that is upsetting the processnullreferenceexception object reference not set to an instance of an objectninjectinfrastructurelanguageextensionsformemberinfogetparentdefinition systemreflectionmethodinfo method bindingflags flagsninjectinfrastructurelanguageextensionsformemberinfogetparentdefinition systemreflectionpropertyinfo propertyninjectinfrastructurelanguageextensionsformemberinfoisdefined systemreflectionpropertyinfo element systemtype attributetype boolean inheritninjectinfrastructurelanguageextensionsformemberinfohasattribute systemreflectionmemberinfo member systemtype typeninjectselectionheuristicsstandardinjectionheuristicshouldinject systemreflectionmemberinfo memberninjectselectionselectorc thisplayclass3selectpropertiesforinjectionb 2 iinjectionheuristic hsystemlinqenumerableanyiinjectionheuristic ienumerable1 source systemfunc2 predicateninjectselectionselectorselectpropertiesforinjectionb 1 systemreflectionpropertyinfo psystemlinqenumerablecreatewhereiteratorc iterator1d1systemreflectionpropertyinfomovenext systemcollectionsgenericlist1systemreflectionpropertyinfoaddenumerable ienumerable1 enumerablesystemcollectionsgenericlist1systemreflectionpropertyinfoaddrange ienumerable1 collectionninjectselectionselectorselectpropertiesforinjection systemtype typeninjectplanningstrategiespropertyreflectionstrategyexecute iplan planninjectplanningplannerc thisplayclass2getplanb 0 iplanningstrategy sninjectinfrastructurelanguageextensionsforienumerableoftmapiplanningstrategy ienumerable1 series systemaction1 actionninjectplanningplannergetplan systemtype typeninjectactivationcontextresolve ninjectkernelbaseresolveb 4 icontext contextsystemlinqenumerablecreateselectiteratorc iterator102ninjectactivationicontextsystemobjectmovenext systemlinqenumerablesingleobject ienumerable1 source systemfunc2 predicate fallback fallbacksystemlinqenumerablesingleordefaultobject ienumerable1 sourceninjectplanningtargetstarget1tgetvalue systemtype service icontext parentninjectplanningtargetstarget1tresolvewithin icontext parentninjectactivationprovidersstandardprovidergetvalue icontext context itarget targetninjectactivationprovidersstandardproviderc thisplayclass2createb 1 itarget targetsystemlinqenumerablecreateselectiteratorc iterator102ninjectplanningtargetsitargetsystemobjectmovenext systemcollectionsgenericlist1systemobjectaddenumerable ienumerable1 enumerablesystemcollectionsgenericlist1systemobjectctor ienumerable1 collectionsystemlinqenumerabletoarrayobject ienumerable1 sourceninjectactivationprovidersstandardprovidercreate icontext contextninjectactivationcontextresolve ninjectkernelbaseresolveb 4 icontext contextsystemlinqenumerablecreateselectiteratorc iterator102ninjectactivationicontextsystemobjectmovenext systemlinqenumerablecreatecastiteratorc iterator01somegamebehaviourmovenext systemlinqenumerablesinglesomegamebehaviour ienumerable1 source systemfunc2 predicate fallback fallbacksystemlinqenumerablesinglesomegamebehaviour ienumerable1 sourceninjectresolutionextensionsgetsomegamebehaviour iresolutionroot root ninjectparametersiparameter parametersobjectfactorygetinstancesomegamebehaviour at assetsscriptscoreobjectfactorycs31gridstart at assetsscriptsworldgridcs27,['c#'] +132047,custom observablecollection or bindinglist with support for periodic notifications summaryi have a large an rapidly changing dataset which i wish to bind to a ui datagrid with grouping the changes are on two levelsitems are frequently added or removed from the collection 500 a second each wayeach item has a 4 properties which will change up to 5 times in its lifetimethe characteristics of the data are as followsthere are 50 items in the collectionan item may within a second be added then have 5 property changes and then be removed an item may also remain in some interim state for a while and should be thisplayed to the userthe key requirement which i am having problems withthe user should be able to sort the dataset by any property on the objectwhat i would like to doupdate the ui only every n secondsraise only the relevant notifypropertychangedeventsif item 1 has a property state which moves from a b c d in the interval i needwant only one state change event to be raised adi appreciate a user does not need to have the ui updated thousands of times a second if an item is added has its state changed and is removed all within the window of and seconds between ui updates it should never hit the datagrid datagridthe datagrid is the component which i am using to thisplay the data i am currently using the xceed datagrid as it provides dynamic grouping trivially i am not emotionally invested in it the stock datagrid would be fine if i could provide some dynamic grouping options which includes the properties which change frequentlythe bottleneck in my system is currently in the time taken to resort when an items properties changethis takes 98 of cpu in the yourkit profilera different way to phrase the questiongiven two bindinglist observablecollection instances which were initially identical but the first list has since had a series of additional updates which you can listen for generate the minimal set of changes to turn one list into the otherexternal readingwhat i need is an equivalent of this arraymonitor by george tryfonas but generalized to support adding and removing of items they will never be movednb i would really appreciate someone editing the title of the question if they can think of a better summaryedit my solutionthe xceed grid binds the cells directly to the items in the grid whereas the sorting grouping functionality is driven by the listchangedevents raised on the bindinglist this is slightly counter intuitive and ruled out the montioredbindinglist below as the rows would update before the groupsinstead i wrap the items themselves catching the property changed events and storing them in a hashset as daniel suggested this works well for me i periodically iterate over the items and ask them to notify of any changesmonitoredbindinglistcshere is my attempt at a binding list which can be polled for update notifications there are likely some bugs with it as it was not useful to me in the endit creates a queue of addremove events and keeps track of changes via a list the changelist has the same order as the underlying list so that after weve notified of the addremove operations you can raise the changes against the right index summary a binding list which allows change events to be polled rather than pushed summaryserializablepublic class monitoredbindinglistt bindinglistt private readonly object publishinglock new object private readonly queuelistchangedeventargs addremovequeue private readonly linkedlisthashsetpropertydescriptor changelist private readonly dictionaryint linkedlistnodehashsetpropertydescriptor changelistdict public monitoredbindinglist thisaddremovequeue new queuelistchangedeventargs thischangelist new linkedlisthashsetpropertydescriptor thischangelistdict new dictionaryint linkedlistnodehashsetpropertydescriptor protected override void onlistchangedlistchangedeventargs e lock publishinglock switch elistchangedtype case listchangedtypeitemadded if enewindex count 1 throw new applicationexceptionitems may only be added to the end of the list queue this event for notification addremovequeueenqueuee add an empty change node for the new entry changelistdictenewindex changelistaddlastnew hashsetpropertydescriptor break case listchangedtypeitemdeleted addremovequeueenqueuee remove all changes for this item changelistremovechangelistdictenewindex for int i enewindex i count i changelistdicti changelistdicti 1 if count 0 changelistdictremovecount break case listchangedtypeitemchanged changelistdictenewindexvalueaddepropertydescriptor break default baseonlistchangede break public void publishchanges lock publishinglock publish internal void publish whileaddremovequeuecount 0 baseonlistchangedaddremovequeuedequeue the order of the entries in the changelist matches that of the items in this int i 0 foreach var changesforitem in changelist foreach var pd in changesforitem var lc new listchangedeventargslistchangedtypeitemchanged i pd baseonlistchangedlc i,['c#'] +132063,powershell script runs from the shell but not from my application i am trying to create a windows application that will be able to run a variety of powershell scriptsi have a script which works as it should when run from the powershell prompt and my windows application seems to execute it like it should but it is unable to find the methods on my ouwhen i execute the script from the windows application i get these messages outerror the following exception occurred while retrieving member create there is no such object on the server error the following exception occurred while retrieving member delete there is no such object on the serverpowershell scriptfunction newaduser param string username throw parameter username systemstring is required string password throw parameter password systemstring is required string organizationalunit users string thisplayname string firstname string lastname string initialsstring mobilephone string description switch cannotchangepassword switch passwordneverexpires switch thisabledtry currentdomain systemdirectoryservicesactivedirectorydomaingetcurrentdomain dn currentdomaingetdirectoryentrythistinguishedname ou adsi ldapcnorganizationalunitdn useraccount oucreateuser cnusername useraccountsetinfo useraccountuseraccountcontrol useraccountuseraccountcontrolitem0 bxor 0x02 enable the account useraccountsetinfo useraccountsamaccountname username useraccountsetinfo useraccountuserprincipalname 01 f username currentdomainname if thisplayname useraccountthisplayname thisplayname if description useraccountdescription description if firstname useraccountgivenname firstname if lastname useraccountsn lastname if initials useraccountinitials initials if mobilephone useraccountmobile mobilephone useraccountsetinfo useraccountsetpasswordpassword password if passwordneverexpires useraccountuseraccountcontrol useraccountuseraccountcontrolitem0 bxor 0x10 if cannotchangepassword everyone systemsecurityprincipalsecurityidentifiers110 everyonedeny newobject systemdirectoryservicesactivedirectoryaccessrule everyoneextendedrightdeny systemguidab721a531e2f11d0981900aa0040529b self systemsecurityprincipalsecurityidentifiers1510 selfdeny newobject systemdirectoryservicesactivedirectoryaccessrule selfextendedrightdeny systemguidab721a531e2f11d0981900aa0040529b useraccountget objectsecurityaddaccessruleselfdeny useraccountget objectsecurityaddaccessruleeveryonedeny useraccountcommitchanges useraccountsetinfo if thisabled useraccountuseraccountcontrol useraccountuseraccountcontrolitem0 bxor 0x02 useraccountsetinfo catch writeerror oudeleteuser cnusername return falsereturn truethe c code i have is thispowershell ps powershellcreate psaddscriptgetscriptnewaduserps1 psinvoke psaddcommandnewaduseraddparameters new listcommandparameter new commandparameterusername username new commandparameterpassword password new commandparameterfirstname firstname new commandparameterlastname lastname new commandparameterthisplayname realname new commandparameterinitials initials new commandparametermobilephone mobilephone new commandparameterorganizationalunit users new commandparameterpasswordneverexpires var results psinvoke foreach var obj in results consolewritelineobjtostring if psstreamserrorcount 0 foreach var err in psstreamserror consolewritelineerror 0 errtostring,['c#'] +132101,how to apply style classes to td classes what i am trying to find out is the proper syntax to apply some style to each individual td in my table belowsection idshows html5 section tag for the shows section h2 classgigshowsh2ul classgig start the table table tr setup the header row thwhenth thwhereth thstartth thfinishth tr php some php to fetch all the gig entries from the shows table shows query select from shows order by date asc shows mysql queryshows query a loop to place all the values in the appropriate table cells while show mysql fetch arrayshows begin the loop start the row tr format the date value from the database and print it td classwhenphp date datel f j y strtotimeshowdate echo date td td classvenuephp echo showvenue td format the the start and end times and print them td clastartphp time dategi strtotimeshowtime echo time td td classfinishphp until dategi strtotimeshowuntil echo until td finish this row tr some space before the next row div classcleardiv php close the loop finish the table tableulsectionthe styling that i have at the moment isshows tablegig fontsize 25px shows tdfinish marginleft 50pxi did have a class for the table itself but not sure if it is necessarythe fontsize works but what i cannot figure out is how to apply the style to the td th tr elements etc i have tried several things but cannot seem to get it to workany help much appreciatedthanks,"['html', 'css']" +132137,soap error server was unable to process request object reference not set to an instance of an object when i send a soap request to my service in the iis locally everything works finewhen i send a soap request to the same service that running on iis on another host everything works finebut when another programmer sends a soap request to my service he generally gets the right response except one method in the service that returnssoapbodysoapfault faultcodesoapserverfaultcode faultstringserver was unable to process request gt object reference not set to an instance of an objectfaultstring detail soapfaulti need to understand why he is receiving this errorhis soap request is exactly the same as soap request yet mine works and his does not,['c#'] +132142,when linking to an external js file is not this a security risk meaning if i have a website and i link to a external js file say for jquery or some widget service they can pretty easy just pull by authentication cookie and then login as me correctwhat if i am under ssl,"['javascript', 'jquery']" +132148,getting velocity error at statup vm global libraryvm i am using velocity with springbut in eclipse console i get this error my code works fine but i want to know how to fix itresourcemanager unable to find resource vm global libraryvm in any resource loader,['java'] +132155,handling innodb deadlock i have been getting a deadlock found when trying to get lock try restarting transaction error on my innodb tables here is the queryupdate views set visit cnt visit cnt 1 where visit day datenow and article id 4838this query also triggers this via on update triggerupdate articles set views views 1 where id newarticleidhere is how i tried to fixed itattempts left 5do mysql query query if we found a deadlock we will try this query 4 more times if mysql errno 1213 1213 deadlock error deadlocked true attempts left else deadlocked false whiledeadlocked attempts left 0my question is this the only way to handle a deadlock i mean this is quite ugly and deadlocks happen time to time anyway is there any recommended way to fix deadlocks,"['php', 'mysql']" +132156,draggable pushpin windows phone 7 bing maps control just wondering if there are any decent resources on how to program a draggable pushpin for a map in a windows phone 7 application i have had a good look and can only find information about how to do it for a browser applicationideally i want the user to be able to click on a pushpin and drag it to a location on the map however at the minute the only way i can think of doing this is for the user to drag the map and the pushpin remains at the centre of the map,['c#'] +132177,setting custom target and action in interface builder i have a custom control that is reused frequently it is meant to respond to a long press i would like to be able to set the target and selector in interface builder is there any method for having something likeproperty nonatomicassign iboutlet sel longpreselectoralternatively is there a way to add custom uicontrolevents that can be set it interface builderthanks,['iphone'] +132180,functional appendextend the methods append and extend in python are not functional by nature they modify the callee and return noneis there an alternative way to do what these methods do and get a new list as a returned valueconsider this exampledef myfunfirst args for elem in firstextendargs print elemobviously this would not workis there a way to construct a new list in place instead of being forced to write the followingdef myfunfirst args all args listfirst all argsextendargs for elem in all args print elemthanks,['python'] +132192,matching eg a unicode letter with java regexps there are many questions and answers here on stackoverflow that assume a letter can be matched in a regexp by azaz however with unicode there are many more characters that most people would regard as a letter all the greek letters cyrllic and many more unicode defines many blocks each of which may have lettersthe java definition defines posix classes for things like alpha characters but that is specified to only work with usascii the predefined character classes define words to consist of azaz 09 which also excludes many lettersso how do you properly match against unicode strings is there some other library that gets this right,['java'] +132197,can someone explain what the c func does i am reading the pro mvc 2 book and there is an example of creating an extension method for the htmlhelper classhere the code examplepublic static mvchtmlstring pagelinksthis htmlhelper html paginginfo paginginfo funcintstring pageurl magic hereand here is an example usagetestpublic void can generate links to other pages arrange were going to extend the html helper class it does not matter if the variable we use is null htmlhelper html null paginginfo paginginfo paginginfo currentpage 2 totalitems 28 itemsperpage 10 funcint string pageurl i page i act heres how it should format the links mvchtmlstring result htmlpagelinkspaginginfo pageurl assert resulttostringshouldequala hrefpage11aa hrefpage22aa hrefpage33a edit removed part that confused the point of this questionthe question is why is the example using func when should i use it what is functhanks,['c#'] +132212,get model class from symbol i am implementing a method that will be used in many places of a projectdef do associationendassociation is a symbol like articles tags users etcwhen the association is articles i need to work with the article modelwhen the association is users i need to work with the user modeletci know that i can write a helper method that returns model class depending on the provided symbol but is there a ready to use method for that,['ruby-on-rails'] +132218,java equivalent of invariant culture i am converting the following c code to java is there a java equivalent to the net concept of invariant culturestring upper mystringtoupperinvariantsince the invariant culture is really just the us culture i could just do something like this in java but i am wondering if there is a better waystring upper mystringtouppercaselocaleus,"['c#', 'java']" +132219,python how to convert a list of dictionaries values into intfloat from string i have a list of dictionaries as followslist a1 b2 c3 d4 e5 f6 how do i convert the values of each dictionary inside the list to intfloatso it becomeslist a1 b2 c3 d4 e5 f6 thanks,['python'] +132227,djangopiston how can i get app label model name before i was just using the buildin django serializers and it added a model field pk 1 model zoocathow can i get the same model field using djangopistoni tried fields id model but that did not work,['python'] +132234,how do browsers execute javascript i am trying to figure out if web browsers use an interpreter to execute javascript or some sort of compiler it is well known that scripting languages are interpreted not compiled however there is the jscriptcompiler that can compile javascript into msil this leaves me to wonder if ie ff chrome etc are using some sort of compiler or if it is an interpretercan anyone cite the specific method in which browsers run javascript,['javascript'] +132238,regex to check string contains only hex characters i have never done regex before and i have seen they are very useful for working with strings i saw a few tutorials for example but i still cannot understand how to make a simple java regex check for hexadecimal characters in a stringthe user will input in the text box something like 0123456789abcdef and i would like to know that the input was correct otherwise if something like xtyspg456789abcdef when return falseis it possible to do that with a regex or did i misunderstand how they work,['java'] +132250,save the tab state during orientation change i have 2 tabs for example tab1 tab2 which is thisplayed on the screen let the tabs be thisplayed on the portrait orientationtab1 thisplays activity1 tab2 thisplays activity2currently the selected tab state is tab2 now i change the orientation for portrait to landscape on changing the orientation to landscape mode instead of thisplaying tab2 currently tab1 is thisplayed basically i want to save the tab state when there is orientation changein order to perform the objective of saving the tab state i am writing the following codeprotected void onpause superonpause savecurrenttabstategetselectedtabprivate void savecurrenttabstateint value preferencemanagergetdefaultsharedpreferencesthiseditputint tabstate valuecommitoverrideprotected void onresume superonresume setcurrenttabpreferencemanagergetdefaultsharedpreferencesthis getinttabstate 0i wanted to know is my approach correct or not whether the above code is a proper way of saving the tab state on changing the orientation,['android'] +132253,ios app with hardware integration i want to develop an ios app that uses an external hardware plugin kind of like square however i was unable to find any references in apples documentation can someone point me to the right direction,"['iphone', 'ios']" +132258,how do i create these nested dom elements with jquery given these javascript variablesvar div id my divvar h1 class my headervar a class my a classvar a string teststringand this page elementdiv idcontainerdivi want to build this html structure with jquerydiv idcontainer div idmy div h1 classmy header a hreftest classmy a classteststringa h1 divdivwhat is the best and most readable way to chain the commands here,"['jquery', 'html']" +132279,how to know if a specific user has rated a android app in my android app i need implement a functionality that allow ask the user if he wish rate this app if the response is yes i am going to redirect to androidmarket app when the user already rated the app the app should not ask him for rate again so i need any way to know if the user already has rated the appi am using the androidmarketapi but i did not find any method that return who ratedmy appthe appsrequest returns the global rating for example 5the commentsrequest returns only comments but if there are some users that rate the app without comments the commentsresponse returns emptyi need something like this app myappuser rate 3 could you please give some ideas,['android'] +132284,mercurial cgi hgwebcgi fails i have mercurial 181 python 266 installed on win 2k8 r2 running on a vm i have tried installing from msi source and using tortisehg commandline hg works fine but i get the same error when running the hgwebcgitraceback most recent call last file hgwebcgi line 17 in application hgwebconfig file mercurialhgweb init pyc line 26 in hgweb file mercurialhgwebhgwebdir modpyc line 61 in init file mercurialhgwebhgwebdir modpyc line 70 in refresh file mercurialuipyc line 35 in init file mercurialdemandimportpyc line 75 in getattribute file mercurialdemandimportpyc line 47 in load file mercurialutilpyc line 576 in file mercurialdemandimportpyc line 85 in demandimport file mercurialwindowspyc line 21 in file mercurialdemandimportpyc line 75 in getattribute file mercurialdemandimportpyc line 47 in load file mercurialosutilpyc line 12 in file mercurialosutilpyc line 10 in loadimporterror dll load failed the specified module could not be foundthe other answers i have found on so and elsewhere pointed me to try installing from source dropping the pure osutil into the install or installing an older version i have tried them all this is especially frustrating because i have other similar nonvm machines running fine but have been unable to find the thisconnectideas,['python'] +132293,structuring sphinx documentation i have started documenting a python project using sphinx it is the first time i use it i am used to tools which work with a javadoclike syntax and i have some doubtssince i want the documentation to appear near the code i make use of the automodule autoclass and automethod directives so the structure of my documentation is as follows indexrst contains the toc and automodule my main packageand then the toplevel init py contains directives like automodule some subpackagefor each subpackage and so on finally each module contains directives autoclass some class membersfor each class in the modulethis mostly works but what i get is a single page documentation which is a little odd to work withhow should i organize my documentation in order to obtain a tree of hyperlinked files that is the main package should contain its own documentation and links to each of its subpackages and so on until each module has its own page,['python'] +132302,want to find records with no associated records in rails 3 consider a simple associationclass person has many friendsendclass friend belongs to personendwhat is the cleanest way to get all persons that have no friends in arel andor meta whereand then what about a has many through versionclass person has many contacts has many friends through contacts uniq trueendclass friend has many contacts has many people through contacts uniq trueendclass contact belongs to friend belongs to personendi really do not want to use counter cache and i from what i have read it does not work with has many throughi do not want to pull all the personfriends records and loop through them in ruby i want to have a queryscope that i can use with the meta search gemi do not mind the performance cost of the queriesand the farther away from actual sql the better,['ruby-on-rails'] +132312,accessing dates in php beyond 2038 i am of of the understanding that due to the nature that php represents dates using milliseconds you cannot represent dates past 2038 i have a problem where i want to calculate dates far in the future thousands of years awayobviously i cannot use the php date function to represent this date because of the limit however i have something on my side all i want to do is store the year month and day i do not care for the hour minute seconds and milliseconds am i correct in thinking that without including this additional information i should be able to calculate a lot further into the future because i am willing to thiscard a lot of information is this any library that currently does this if not does any have any advice on how to approach this problem,['php'] +132313,what is the point of stl character traits i notice that in my copy of the sgi stl reference there is a page about character traits but i cannot see how these are used do they replace the stringh functions they do not seem to be used by stdstring eg the length method on stdstring does not make use of the character traits length method why do character traits exist and are they ever used in practice,['c++'] +132318,which is better enumerableempty or new0 these are the sameienumerablestring ii enumerableemptystringi new string0so which to usei think the first communicates intent more clearly but it is bigger and a bit noisier not to mention ugly in the debugger the second is also more efficient in memory and cpu if i am reading reflector righti am leaning towards the new type0 but wanted to know what you all think,['c#'] +132323,aspnet mvc why does my app keep restarting i have an aspnet mvc website that gets about 6500 hits a day on a shared hosting platform at server intellect i keep seeing app restarts in the logs and i cannot figure out whyi have read scott gus article here and implemented the technique and heres what shows up in my logapplication shutdown shutdownmessagehostingenvironment initiated shutdown hostingenvironment caused shutdown shutdownstackatsystemenvironmentgetstacktraceexception e boolean needfileinfo at systemenvironmentget stacktrace at systemwebhostinghostingenvironmentinitiateshutdowninternal at systemwebhostinghostingenvironmentinitiateshutdown at systemwebhostingpipelineruntimestopprocessingit seems to occur about every five minutesare there any other ways to debug thisupdate here are the application pool settings mentioned by softioncpulimit 0limit action no actionlimit interval 5 minutesprocess model idle timeout 20 minutesping maximum response time 90 secondsstartup time limit 90 secondsrapidfail protectionenabled truefailure interval 5 minutesrecyclingprivate memory limit 100 mbregular time interval 1740 minutes 29 hoursrequest limit 0specific times nonevirtual memory limit 0,['asp.net'] +132344,various possible uses of the content property in css2css3 i am trying to find some uptodate info about various possible uses for content property in css but only find stuff in the ancients dungeons of the web dating from 2004 orso so i thought i have to ask this in 2011 againpbefore content urldingdongpngpbefore content some text i am very new to both the before selector as well as the content property and heard of it accidentally on this question which was answered very creatively by a lovely ladyhow to define the color of bullets in ulli lists via css without using any image bullets or any span tagonly to find out that some problems might occur concerning the actual encoding of the contentlibefore content a how to encode this special character as a bullit in an email stationeryand so my concrete question is besides url and text are ther other possibilitiesthanks very much for your suggestions and ideas,['css'] +132368,wsdl to java or java to wsdl i have recently picked up a project which has a rather nasty build process hand coded xsd schemas are read by jaxb to generate a java model of classes and factories which is used in hand coded java web service classes annotated which are then deployed to a server which is used as a source to read the complete wsdls from in order to generate a second java based model which includes the service and factory classes for the complete wsdl which is used in client programsthis sounds aweful and i do not think i need it to be so complicated so at some stage i would like to chuck all this away and eitherhand craft the wsdls generate a full model and add service codeor write the service and model classes and generate wsdls as necessary on the server at run timeeither way i want to end up with one source base for the model which both the server and clients can use and have one source of truth for what the model should be where as at the moment i feel like i have severalat the moment i am leaning towards the second option but which would you choose and which technologies would you use,['java'] +132413,how to detect quickly if a string is zlib compressed whats the quickest way in python to determine if a string was compressed by zlib i am using this currentlydef iscompresseddata result true try s zlibdecompressdata except result false return resulti am sure there is a more elegant way,['python'] +132414,rails belongs to and has many using nonstandard ids i have got two models item and product as followsirbmain0070 item itemid integer identification number string production date date created at datetime updated at datetime going in booleanirbmain0080 product productid integer sku string barcode identification string created at datetime updated at datetimethink of this as an item is of a particular producti have managed to refer all the items of a particular product productfind1items viaclass product activerecordbase has many items foreign key identification number primary key barcode identificationendbut i cannot seem to refer the product of a particular itemthis is what i have got nowclass item activerecordbase set primary key identification number belongs to product foreign key barcode identificationendand as far as my understanding re databases are concerned that should work except that it does not maybe i am missing out on something here i am fairly new to rails around a month or less,['ruby-on-rails'] +132420,how to avoid multiple login for the same user i wanted to stop multiple login of the same user so i created a table which keeps track of users who have logged in when they log in the data will be entered in the table when they click on logout data and session will be removedthe problem is when they close the browser window without logging out they would not be able to login ever again is there a better way to handle this,"['c#', 'asp.net']" +132434,modifying nstextstorage attributes causes scroll view to jump around i have implemented basic syntax highlighting by properly setting the nstextstorage delegate of my nstextview and changing the text attributes in textstoragedidprocesseditingthe basic process is as follows voidtextstoragedidprocesseditingnsnotification notification nstextstorage storage notification object storage beginediting nsstring text storage string nsrange textrange nsmakerange0 text length storage removeattributensforegroundcolorattributename rangetextrange some regex matching here storage addattributensforegroundcolorattributename valuecosyntax colorforpatterngrouppatterngroupname rangecapturedrangesgroup storage endeditingwhenever removeattributerange or addattributevaluerange is invoked when a space character is entered the nstextviews surrounding nsscrollview location begins to jump around scroll knob goes to some random position near the whats causing this,['objective-c'] +132464,how does joomla model view controller mvc work i am new to joomla i want to know how the joomla controller passes data to the model model to controller and controller to view although this might be a silly question i really tried to find the answer i hope i can get some help from the stackoverflow family,['php'] +132467,store objects in android i would like to know what would be the best option to store a custom java object that i have in my application i have read about serialization but it seems to be quite slowwhat is the best option,['android'] +132474,mysql column name standards conventions i am looking for document suggestions with column name standards or conventions for mysql can anybody suggest any,['mysql'] +132498,garbage collection with nodejs i was curious about how the nodejs pattern of nested functions works with the garbage collector of v8heres a simple examplereadfileblah functionstr var val getvaluefromstrstr function restofprogramval2 valif restofprogram is long running doesnt that mean that str will never get garbage collected my understanding is that with node you end up with nested functions a lot does this get garbage collected if restofprogram was declared outside so str could not be in scope is this a recommended practiceedit i didnt intend to make the problem complicated that was just carelessness so i have modified it,['javascript'] +132528,php best way to cache mysql results i am currently building a php framework original i know and im working on some optimisation features for it one dilema i have come accross is what is the best way to cache mysql results i know some people will say first optimise your mysql etc but lets say for arguments sake my query takes 1 minute to run and is as optimised as possiblewhat would be the best way to cache the results in php so i dont have to rerun the query every page loadmy first thought was to maybe loop through the results add them to an array serialize them and then store in a file now as creating the cache only occurs once i can afford the overhead of the serialize function if the array contains say 1 million results how ever loading the cached file and then unserializing the array on every pageload could have performance impactwould it then be a better idea to while caching instead of serializing the results and the writing to file write to the file in a way that thisplays the results in a php readable array so when it loads there is no unserialize overheadare there any other read faster ways to cache a slow query for frequent use,"['php', 'mysql']" +132532,how to make the visual studio debugger stop when a handled exception occurs in c i am trying to understand why and where an exception is thrown in my c code the problem is that all my code is in trycatch blocks so debugger does not stop when it happens is there a way to explicitly tell it to stop,['c#'] +132533,ruby vs lua as scripting language for c i am currently building a game server not an engine and i want it to be extendable like a plugin systemthe solution i found is to use a scripting language so far so good i am not sure if i should use ruby or lua lua is easier to embed but ruby has a larger library and better syntax in my opinion the problem is there is no easy way i found to use ruby as scripting language with c whereas it is very easy with luatoughs about this suggestions for using ruby as scripting language i tried swig but it is not nearly as neat as using luathanks,"['c++', 'ruby']" +132539,is there a way to select the bit rate while using avplayer for http live audio streaming i am using avplayer to stream audio content delivered in two quality formats the problem is that when passing from a lower format to a higher one done automatically by the framework when wifi is available there is a delay while playingis there a way to manually select a desired quality in order to prevent that delay,"['iphone', 'objective-c']" +132547,image aspect ratio using reportlab in python i want to insert an image inside a frame i found two ways to do thisdrawimageself image x y widthnone heightnone masknone preserveaspectratiofalse anchorcimagefilename widthnone heightnonemy question is how can i add an image in a frame while preserving its aspect ratiofrom reportlablibunits import cmfrom reportlabpdfgencanvas import canvasfrom reportlabplatypus import frame imagec canvasmydocpdfframe frame1cm 1cm 19cm 10cm showboundary1if i have a rectangular image i will get a square image aspect ration will change to 8x8 cm the advantage here is that i use coordinates relativeto the framestory storyappendimagemyimagepng width8cm height8cmframeaddfromliststory caspect ration is preserved but i cannot use the frames coordinates anymorecdrawimagemyimagepng 1cm 1cm width8cm preserveaspectratiotruecsave,['python'] +132559,how to convert string to ip address and vice versa how can i convert a string ipaddress struct in addr and vice versaand how do i turn in unsigned long ipaddressthanks,['c++'] +132571,thisplay link in rails form error message on our signup form we validates uniqueness of emailwhen the a user is attempting to use our sign up form and they specify an existing email address i would like them to see an error message like thisthis email address is already in use if youre having trouble logging in you can reset your passwordobviously i would like to use the named route for the link but my user model does not have access to it how can i accomplish thisside note we will be offering translations for our app soon and all of these error messages will end up in yaml files can i somehow inject my new password url in a message in my yaml locale files eg configlocalesenyml,['ruby-on-rails'] +132587,hash function determination how can we find the most efficient hash functionleast possible chances of collision for the set of stringssuppose we are given with some strings and the length of the strings is also not definedajayvijayrakhiwe know the count of no of strings available so we can design a hash table of sizecount available what could be the perfect hash function that we could design for such problemmultiplying each character ascii value by 31prime no in increment fashion leads to the a hash value greater than the value of max int and then modulus would not work properly so please give some efficient hash function build up solutioni have few set of strings lets say count 10 i need to implement a hash function such that all those 10 strings fit in uniquely in the hash table any perfect hash function o1 available for this kind of problem hash table size will be 10 for this case only c programmingplease explain the logic at website this looks very complicated but perfect to me what is the algorithm used here reading the code straight away is very difficultthanks,['c'] +132592,is the configuration service for net applications and wcf services sample productionready i recently stumbled across the configuration service fornet applications and wcf services it is part of the stocktrader 40 sample put out by microsoft i am wondered if anyone has either used or adapted this service for a production enterprise application is it enterpriseready how would it compare to a commercial solution such as soaware,['.net'] +132598,metaprogramming write in one language x crosscompile in multiple languages like c php java c in all projects i have done through the years i never came across a requirement like this though it seems so easy on paper write a plugin for many wellknown cmssobviously each pluginsystem or extension system is different and this requires specific bridging code through an adapter pattern but the core should be written once i do not expect wordpress users to use a phpjava bridge and i do not expect dotnetnuke users to use a netnative bridge though that is easier conceivedthe way i see it the core should be compilable in three main domains that cover most cms systemsnative intermediate language could be c or c target can be used as php extensionmsilcil for net based languagesjava byte code for java based systemsc and java translate pretty well to and from each other but c and c is much harder ultimately it would be nice to possibly add other targets so as not to force a wordpress or wikimedia user to install an extension prior to using a plugini am sure this has come up with other too whats a common way of tackling such problems should i define a dsl first and use dms or similar to transform other options,"['c#', 'java', 'php']" +132599,dictionarylike efficient storing of scipynumpy arrays backgroundthe issue i am working with is as followswithin the context of an experiment i am designing for my research i produce a large number of large length 4m arrays which are somewhat sparse and thereby could be stored as scipysparselil matrix instances or simply as scipyarray instances the space gainloss is not the issue hereeach of these arrays must be paired with a string namely a word for the data to make sense as they are semantic vectors representing the meaning of that string i need to preserve this pairingthe vectors for each word in a list are built onebyone and stored to thisk before moving on to the next wordthey must be stored to thisk in a manner which could be then retrieved with dictionarylike syntax for example if all the words are stored in a dblike file i need to be able to open this file and do things like vector worddbwordcurrent approachwhat i am currently doingusing shelve to open a shelf named worddbeach time the vector currently using lil matrix from scipysparse for a word is built storing the vector in the shelf worddbword vectorwhen i need to use the vectors during the evaluation i will do the reverse open the shelf and then recall vectors by doing vector worddbword for each word as they are needed so that not all the vectors need be held in ram which would be impossiblethe above solution fits my needs in terms of solving the problem as specified the issue is simply that when i wish to use this method to build and store vectors for a large amount of words i simply run out of thisk spacethis is as far as i can tell because shelve pickles the data being stored which is not an efficient way of storing large arrays thus rendering this storage problem intractable with shelve for the number of words i need to deal withproblemthe question is thus is there a way of serialising my set of arrays which willsave the arrays themselves in compressed binary format akin to the npy files generated by scipysavemeet my requirement that the data be readable from thisk as a dictionary maintaining the association between words and arraysgentlemen and ladies thanks in advance for any help or suggestions you may be able to offer,['python'] +132601,javascript get values from multiple select option box this one is driving me nuts itas got to be something simple and stupid that i am overlooking i have a multiple select box in a form i am just trying to get the values that are selected in my loop if i use alert then i have no problem as soon as try to concatenate the values i get the error aselbranchselected is null or not an object form nameinventorylist methodpost actioninventorylistasp select nameselbranch classbnotes size5 multiplemultiple option valueallalloption option value001 renton001 rentonoption option value002 spokane002 spokaneoption option value003 missoula003 missoulaoption option value004 chehalis004 chehalisoption option value005 portland005 portlandoption option value006 anchorage006 anchorageoption option value018 pdc018 pdcoption select input typebutton nameviewreport valueview classbnotes onclickgetinventory form script languagejavascript function getinventory var invform documentformsinventorylist var selbranchval var x 0 for x0xinvformselbranchlengthx if invformselbranchxselected alertinvformselbranchxvalue selbranchval selbranchval invformselbranchxvalue alertselbranchval script,['javascript'] +132607,can i host facebooks alljs locally i have been noticing that sometimes my facebook app runs slow and when checked it was because the alljs file was not loaded from the facebook server so i copied the file ontp my server and tested it everything seems to work fine and actually it runs faster my question is do you know if there are bugs or errors in doing this,['javascript'] +132622,how to partition a linq to objects query this is a resourceallocation problem my goal is to run a query to fetch the toppriority shift for any timeslotthe dataset is very large for this example letas say there are 100 shifts each for 10 companies though the real dataset is even larger they are all loaded into memory and i need to run a single linq to objects query against them var topshifts from s in shifts where from s2 in shifts where s2companyid scompanyid stimeslot s2timeslot orderby s2priority select s2firstequalss select stolistthe problem is that without optimization linq to objects will compare each and every object in both sets doing a crossjoin of all 10 x 100 against 10 x 100 which amounts to 10 billion 10 comparisons what i want is to compare only objects within each company as if company were indexed in a sql table this should result in 10 sets of 100 x 100 objects for a total of 10 million 10 comparisons the later would scale linearly rather than exponentially as the number of companies growstechnologies like i4o would allow me to do something like this but unfortunately i donat have the luxury of using a custom collection in the environment in which iam executing this query also i only expect to run this query once on any given dataset so the value of a persistent index is limited iam expecting to use an extension method which would group the data by company then run the expression on each groupfull sample codepublic struct shift public static long iterations private int companyid public int companyid get iterations return companyid set companyid value public int id public int timeslot public int priorityclass program static void mainstring args const int companies 10 const int shifts 100 consolewritelinestringformat0 companies x 1 shifts companies shifts var timer stopwatchstartnew consolewritelinepopulating data var shifts new listshift for int companyid 0 companyid companies companyid for int shiftid 0 shiftid shifts shiftid shiftsaddnew shift companyid companyid id shiftid timeslot shiftid 3 priority shiftid 5 consolewritelinestringformatcompleted in 0nms timerelapsedmilliseconds timerrestart consolewritelinecomputing top shifts var topshifts from s in shifts where from s2 in shifts where s2companyid scompanyid stimeslot s2timeslot orderby s2priority select s2firstequalss select stolist consolewritelinestringformatcompleted in 0nms timerelapsedmilliseconds timerrestart consolewritelinenshifts foreach var shift in shiftstake20 consolewritelinestringformatc 0 id 1 t 2 p3 shiftcompanyid shiftid shifttimeslot shiftpriority consolewritelinentop shifts foreach var shift in topshiftstake10 consolewritelinestringformatc 0 id 1 t 2 p3 shiftcompanyid shiftid shifttimeslot shiftpriority consolewritelinestringformatntotal comparisons 0n shiftiterations2 consolewritelineany key to continue consolereadkey sample output10 companies x 100 shifts populating data completed in 10ms computing top shifts completed in 52072100ms shifts c 0 id 0 t 0 p0 c 0 id 1 t 0 p1 c 0 id 2 t 0 p2 c 0 id 3 t 1 p3 c 0 id 4 t 1 p4 c 0 id 5 t 1 p0 c 0 id 6 t 2 p1 c 0 id 7 t 2 p2 c 0 id 8 t 2 p3 c 0 id 9 t 3 p4 c 0 id 10 t 3 p0 c 0 id 11 t 3 p1 c 0 id 12 t 4 p2 c 0 id 13 t 4 p3 c 0 id 14 t 4 p4 c 0 id 15 t 5 p0 c 0 id 16 t 5 p1 c 0 id 17 t 5 p2 c 0 id 18 t 6 p3 c 0 id 19 t 6 p4 top shifts c 0 id 0 t 0 p0 c 0 id 5 t 1 p0 c 0 id 6 t 2 p1 c 0 id 10 t 3 p0 c 0 id 12 t 4 p2 c 0 id 15 t 5 p0 c 0 id 20 t 6 p0 c 0 id 21 t 7 p1 c 0 id 25 t 8 p0 c 0 id 27 t 9 p2 total comparisons 101500 any key to continuequestionshow can i partition the query while still executing as a single linq query in order to get the comparisons down from 10 billion to 10 millionis there a more efficient way of solving the problem instead of a subquery,"['c#', '.net']" +132626,write image metadata to jpgpng file in ios is there any way to write a uiimage to a jpgpng file and then append metadata to it i know you can usewriteimagedatatosavedphotosalbummetadatacompletionblockto do this in the saved photos but how do you do the same thing directly to a file i cannot seem to find any way to do this i know that uiimagepngrepresentation and uiimagejpgrepresentation will give you nsdata that you can use to write the file but there is no way to appendreplace the metadata in the fileany ideas,"['iphone', 'ios']" +132635,html5 how to use the builtin next and previous controls on ios 42 android 23 both on gingerbread 23 and ios 42 the html5 audio tag generates an interface with next and previous buttonshow do i hook into those controlsit does not appear to be one of the html5 media events according to w3schoolshtml5 specsafari developer library controlling media with javascriptwhat javascript events do they emit or do they send http icecast messagesno http headers are sent on the button clickfor an example with screenshots see on androidif you have gingerbread or better youll see the controls in the webapp by defaulton ios iphone ipod ipadbegin playing the music sample on your ipodipadiphonethen click the button to background the appdouble click and swipe from left to right in the lower menu to access the player controlsnote playpause control does work more or less as expected setting the appropriate contentrange http header helps,"['iphone', 'android']" +132637,why does not xcode 4 create any products regardless of build configuration building my ipad app does not actually output a app file it does run in the ipad simulator and on a device but when i hit build or build and run the binary appears under products in red and is not created in the build folder as designated in build settingsany ideas,['ios'] +132645,nodejs garbage collector i have learnt from this thread garbage collection with nodejs that nodejs uses a generational gci routinely use cyclic object references both of which i deleteensure go out of scope eventually and would like to know if nodejs handles them well so for eg if it was done using ref counting there would be a problem so i would like to know how good node is at thissome usage scenariosfor every http request i create a settimeout with a lambda which potentially has references to scope objects the scope object also has a reference to the timeout object etcfor every user session i have a pointer still doing c programming reference to the http request objects which also have references to the session object etc the request objects are deleted often but the session object is notedit i ask because of this link that i found online,['javascript'] +132693,extended tuple unpacking in python 2 is it possible to simulate extended tuple unpacking in python 2specifically i have a for loopfor a b c in mylistwhich works fine when mylist is a list of tuples of size three i want the same for loop to work if i pass in a list of size fouri think i will end up using named tuples but i was wondering if there is an easy way to writefor a b c d in mylistso that d eats up any extra members,['python'] +132700,android proguard error with orgxmlpullv1xmlpullparser when my application is build with proguard it fails with following messagei use a default proguardcfg generated by android sdk with some libraryjarswhat can i do for it20110317 092704 myproject proguard returned with error code 1 see console20110317 092704 myproject note there were 4247 duplicate class definitions20110317 092704 myproject warning library class androidcontentresxmlresourceparser extends or implements program class orgxmlpullv1xmlpullparser20110317 092704 myproject warning library class androidcontentintent depends on program class orgxmlpullv1xmlpullparser20110317 092704 myproject warning library class androidgraphicsdrawableanimationdrawable depends on program class orgxmlpullv1xmlpullparser20110317 092704 myproject warning library class androidgraphicsdrawablebitmapdrawable depends on program class orgxmlpullv1xmlpullparser20110317 092704 myproject warning library class androidgraphicsdrawabledrawable depends on program class orgxmlpullv1xmlpullparser20110317 092704 myproject warning library class androidgraphicsdrawabledrawable depends on program class orgxmlpullv1xmlpullparser20110317 092704 myproject warning library class androidgraphicsdrawabledrawable depends on program class orgxmlpullv1xmlpullparser20110317 092704 myproject warning library class androidviewlayoutinflater depends on program class orgxmlpullv1xmlpullparser20110317 092704 myproject warning library class androidviewlayoutinflater depends on program class orgxmlpullv1xmlpullparser20110317 092704 myproject you should check if you need to specify additional program jars20110317 092704 myproject warning there were 9 instances of library classes depending on program classes20110317 092704 myproject you must avoid such dependencies since the program classes will20110317 092704 myproject be processed while the library classes will remain unchanged20110317 092704 myproject javaioioexception please correct the above warnings first20110317 092704 myproject at proguardinitializerexecuteinitializerjava32120110317 092704 myproject at proguardproguardinitializeproguardjava21120110317 092704 myproject at proguardproguardexecuteproguardjava8620110317 092704 myproject at proguardproguardmainproguardjava492apparently orgxmlpullv1xmlpullparser is not a program classi have updated proguard to newest version46 but have same warnings,['android'] +132706,mvc which method should be overridden to cache action result i am preparing to microsoft certificate exam 70515 reading microsoft book for this exam practicing tests one tests asksyou are creating a custom mvc action filter to cache action results which virtual method should you overridecorrect answer according to test program that is thistributed with a book is onresultexecutingand explanation for the answerwhen you create a custom action filter by inheriting from the actionfilterattribute class you can override four virtual methods that run in the following order onactionexecuting onactionexecuted onresultexecuting and onresultexecuted for output caching you want to capture the final rendered results therefore you should override the last method to run onresultexecutinghere is inconsistency if we need to override the last mentioned method then it should be onresultexecuted but in answer it is told onresultexecutingso the question iswhat is a correct method to be overriddenwhich option should i choose on exam to get answer considered as correct question is valid for case when correct answer is actually different from suggested by systemthanksps i not sure if current question belongs to so but at least it is pretty close,['c#'] +132715,replacing text inside of curley braces javascript i am trying to use javascript to dynamically replace content inside of curly braces here is an example of my codevar mystring this is names adjective type in javascript yes a typevar replacearray name adjective typevar replacewith john simple stringforvar i 0 i replacearraylength 1 i mystringreplacereplacearrayigi replacewithialertmystringthe above code should output this is johns simple string in javascript yes a stringhere is what happenswe are given a string with values in braces that need replaceda loop uses replacearray to find all of the values in curly braces that will need replacedthese values along with the curly braces will be replaced with the corresponding values in the replacewith arrayhowever i am not having any luck especially since one value may be replaced in multiple locations and that i am dealing a dynamic value inside of the regular expression can anyone help me fix this using a similar setup as above,['javascript'] +132718,do not know how to build task dbpopulate 1 namespace db do 2 desc fill database with sample videos 3 task populate environment do 4 require faker 5 raketaskdbresetinvoke 6 100times do n 7 headline fakerloremsentence3 8 video fakerloremwords5 9 videocreateheadline headline 10 video video 11 end 12 end 13 endi currently have this rake task in libtaskssample datarbwhen running rake dbpopulate i get the error do not know how to build task dbpopulate how do i get around thisnotesi am a newbie in railsruby i am using rails 3,['ruby-on-rails'] +132730,bookmarklet to open a new window forwards current window to object window i am using a small bookmarklet which opens a webpage in a new window it works properly on chrome however when i use the same in firefox it opens a new window with new web page but the page on which this bookmarklet was clicked is forwarded to some page with text object window how do i solve this issuemy codea hrefjavascriptopentargetnameheight500width500bookmarkletaplease let me know how to solve this issuethanks,['javascript'] +132750,create a summary row for data across multiple tables i am trying to write a sql query to generate a summary row for the actions performed by a given user in a given period i have the following relevant table structureusers idteamaudit periods can be processing shipping break etc user idperiod type can be processing shipping etc not currently normalizedstarted atfinished at can be null for the current period hence the logic around times belowaudit tasks audit period idaudit task type idcreated atscoreaudit task typesname scan place in pallet etcscore seems redundant but we need to maintain the score that the audit task received at the time it was performed as the audit task type score can change laterfor each user for a given period i would like to create something like the following row of datausersid usersemail time spent processing time spent shipping number of scans number of palletswhich would be calculated by figuring out for each userwhat audit periods fall at least partially in the desired window uses started at and finished athow long did a user spend in each type of audit period should involve group by audit periodsperiod type i would imaginewhat audit tasks fall within the desired window uses created at not in the code below yethow many of each type of audit task did a user accomplish during the window joins out to audit task type and likely involves a group by on audit task typesnamehow many points were earned during the time period sums the scores of all the audit tasks in the windowi have exhausted all of the sql tricks i know not many and came up with something like the followingselect uid as user id uemail as email uteam as team apperiod type as period type attname time to sec timediffleast20110317 0 ifnullapfinished at utc timestamp greatest20110316 0 apstarted at as period duration sumatscore as period score from audit periods as ap inner join users as you on apuser id uid left join audit tasks as at on ataudit period id apid left join audit task types as att on ataudit task type id attid where apstarted at 20110316 0 or apfinished at 20110317 0 and apfinished at 20110317 0 and apfinished at 20110317 0 or apstarted at 20110316 0 and apstarted at 20110316 0 and uteam in foo bar group by uid apid atidbut this seems to be functionally equivalent to just selecting all of the audit tasks in the end i have tried some subqueries as well but to little avail more directly this generates something like skipping less important columnsuser id period type period duration name score1 processing 1800s scan 2001 shipping 10s place in pallet 1001 shipping 10s place in pallet 1001 break 500s null nullwhen i wantuser id processing shipping break scan place in pallet score1 1800s 10s 500s 1 2 400i can easily fetch all of the audit tasks for a given user and roll them up in code but i might be fetching hundreds of thousands of audit tasks over a given period so it needs to be done in sqljust to be clear i am looking for a query to generate one row per user containing summary data collected across the other 3 tables so for each user i want to know how much time he spent in each type of audit period 3600 seconds processing 3200 seconds shipping etc as well as how many of each audit task he performed 5 scans 10 items placed in pallet etci think i have the elements of a solution i am just having trouble piecing them together i know exactly how i would accomplish this in rubyjavaetc but i do not think i understand sql well enough to know which tool i am missing do i need a temp table a union some other construct entirelyany help is greatly appreciated and i can clarify if the above is complete nonsense,"['mysql', 'sql']" +132773,unserialize through query at database level itself i have a column value in database as a2i0s2usi1s219i want to unserialize it by mysql query raher than using php function unserialize after fetching datai want to unserailize by mysql query bcoz i cannot join the other table with the serilaized value rather than executing another query after unserializing it with php,['mysql'] +132786,python how to know function return type and argument types while i am aware of the ducktyping concept of python i sometimes struggle with the type of arguments of functions or the type of the return value of the functionnow if i wrote the function myself i do know the types but what if somebody wants to use and call my functions how is heshe expected to know the types i usually put type information in the functions docstring like the id argument should be an integer and the function will return a string integer tuplebut is looking up the information in the docstring and putting it there as a coder really the way it is supposed to be done edit while the majority of answers seem to direct towards yes document i feel this is not always very easy for complex types for example how to describe concisely in a docstring that a function returns a list of tuples with each tuple of the form node id node name uptime minutes and that the elements are respectively a string string and integerthe docstring pep documentation does not give any guidelines on thati guess the counterargument will be that in that case classes should be used but i find python very flexible because it allows passing around these things using lists and tuples ie without classes,['python'] +132810,how can i get a files permission mask how can i get a files permission mask like 644 or 755 on nix using pythonis there any function or class for doing thatcould you guys help me out thank you very much,['python'] +132817,delete remote files i have files that i want to delete connection can be from file sharing http and ftpexample of files to deletemytestdeletefilenamebinftpmytestdeletefilenamebinhttpmytestdeletefilenamebinheres what i diduri target new uriftpmytestdeletefilenamebinfileinfo fi new fileinfotargetabsoluteurifideletethe error i get isthe given paths format is not supportedis there a single code that can delete in all these file typesi have created a simple code for this taskbased on thread responsethis is the inputuri target new uriftptabletijamfileserveruploadbinuri target new urihttptabletijamfileserveruploadbinuri target new uritabletijamfileserveruploadbinthis is the codebool deletefileonserveruri serveruri if serverurischeme uriurischemeftp ftpwebrequest request ftpwebrequestwebrequestcreateserveruri requestmethod webrequestmethodsftpdeletefile ftpwebresponse response ftpwebresponserequestgetresponse lblstatuscontent responsestatusdescription responseclose return true else if serverurischeme uriurischemefile systemiofiledeleteserverurilocalpath return true else if serverurischeme uriurischemehttp serverurischeme uriurischemehttps httpwebrequest request httpwebrequestwebrequestcreateserveruri requestmethod webrequestmethodshttpdeletefile httpwebresponse response httpwebresponserequestgetresponse lblstatuscontent responsestatusdescription responseclose return true else lblstatuscontent unknown uri scheme return false ftp and file deleted successfully webrequestmethodshttp does not contain deletefile so my question is how do i delete file from this urihttptabletijamfileserveruploadbin,['c#'] +132821,redefinition allowed in c but not in c why does this code work in c but not in cint i 5int i but if i write int i 5 again i get error in c alsoint main using i,"['c++', 'c']" +132828,using androidtextappearance on textviewedittext fails but style works this is a sample textview in xml which will properly apply the style textcontactcontactname to the textviewtextview androidididname androidlayout widthwrap content androidlayout heightwrap content androidlayout torightofidphoto androidlayout aligntopidphoto androidpaddingleft10dp androidtextfirst last stylestyletextcontactcontactname now i have some other things to set on this element which are not text related as such i tried to move the textcontactcontactname and apply it via androidtextappearancetextview androidididname androidlayout widthwrap content androidlayout heightwrap content androidlayout torightofidphoto androidlayout aligntopidphoto androidpaddingleft10dp androidtextfirst last androidtextappearancestyletextcontactcontactname unluckily the text formatting is not being appliedthis is how the style stored in resvaluesstylestextxml looks likestyle nametextcontactcontactname item nameandroidtextsize24spitem item nameandroidtextcolor3item item nameandroidshadowcolorfitem item nameandroidshadowdx0item item nameandroidshadowdy1item item nameandroidshadowradius1itemstyleam i using the textappearance tag wrongi tested on android 22 htc desire,['android'] +132848,how to build an ios like settings module i am really new to iphone development currentlly i am setting up an option module for my application the user should be able to edit some preferencesmy first approach was to have some text fields but i really like how ios handles editing preferences there is some kind of label clicking on that label opens another view with a field for editing i hope you understand what i mean how does ios achieve this is that table viewi mean this kind of design,['iphone'] +132849,filereadlines without locking it i can open a filestream withnew filestreamlogfilename filemodeopen fileaccessread filesharereadwritewithout locking the filei can do the same with filereadlinesstring path,['c#'] +132857,mysql performance join on vs where possible duplicatesmysql inner join vs whereexplicit vs implicit sql joins is there any difference performance wise when we run join queries using join on and where clause regardless of the number of tables or the number of entries in the tables not sure whether this topic has already been thiscussed over even if so i wish to know whether with the latest versions of mysql51 and above things have changed an explain statement clearly shows a lot of difference in the number of rows taken for consideration the syntax i am using is using join onselect field namesfrom table1join table2 on join conditionand join table3 on join condition and join table4 on join condition using whereselect field names from table names list separated by comma where join condition and join condition and join condition so not sure whether usage of join on or where clause would make a difference please assist,['mysql'] +132867,how to create a single instance application in c or c what would be your suggestion in order to create a single instance application so that only one process is allowed to run at a time file lock mutex or what,"['c++', 'c']" +132870,live video streaming application on android i am trying to build a live video streaming application that streams live video from androidusing the mediarecorder class i am able to capture the video data in the form of 3gp with h263 codecshowever when i run my application and stream media i get a 23 second delay at the server sidewhy am i getting this delay are there any internal buffers that i need to flush are there other ways of streaming video apart from using mediarecorder class,['android'] +132877,when should one use intval and when int what is the better option option 1intvalue int numericvalue option 2intvalue intvalnumericvalueis there any difference between these two lines and which should be used in which situation,['php'] +132883,is it possible to dynamically create an array of constant size in c first of all i want to reassure you all that i am asking this question out of curiosity i mean do not tell me that if i need this then my design has problems because i do not need this in real code hope i convinced you now to the questionfor most types t we can writet p new tnow what if t is an array typeint p3 new pointer to array of 3 new i tried thistypedef int arr3arr p new arrbut this does not workis there any valid syntax for this or it is impossible in c if it is impossible then why thanksedit i am guessing i was not clear enough i want to be able to use it in this situationvoid fint3int p3 new fp,['c++'] +132917,changing default download location does anybody have an idea about changing the default download location in android or do you guys know how can i write an android application which asks the user download location sd card or usb memory,['android'] +132922,how do i get tcsetpgrp to work in c i am trying to give a child process via fork foreground access to the terminalafter i fork i run the following code in the child procesetpgid0 0andsetpgidchild childin the parent processthis gives the child its own process group the call to setpgid works correctlynow i want to give the child access to the terminali added the following to the child after the setpgid callif tcsetpgrpstdin fileno getpid perrortcsetpgrp failedafter that there is an execv command to spawn usrbinnanohowever instead of having nano come up nothing happens and the terminal looks as if it is expecting user inputfurther no code seems to execute after the tcsetpgrp calli read somewhere that i need to send a sigcont signal to the child process to get it to work if the process is stopped how can i do that does the parent have to send the signalhow do i go about sending the sigcont signal if that is the solutionraisesigcontalso i am not sure if this helps but the code works fine and spawns nano if i run my program withexec programinstead ofprogramany ideas thanks so much,['c'] +132948,rails 3 get random record so i have found several examples for finding a random record in rails 2 the preferred method seems to bethingfind first offset randthingcountbeing something of a newbie i am not sure how this could be constructed using the new find syntax in rails 3so whats the rails 3 way to find a random record,"['ruby-on-rails', 'ruby']" +132953,why is paramiko raising eoferror when the sftp object is stored in a dictionary i am having trouble with an application i am writing that downloads and uploads files to and from other boxes via ssh the issue i am experiencing is that i can get download files just fine but when i try to put upload them onto another server i get an eoferror exception when i looked at write all in paramikosftppy it seemed like the error was caused when it could not write any data to the stream i have no network programming experience so if someone knows what it is trying to do and could communicate that to me i would appreciate iti wrote a simplified version of the function that handles my connections as ssh runcommand shows how the upload is failing in my application while simpletest shows how sftp put does work but i cannot see any difference between runcommand and simpletest other than how my sftp objects are being stored one is stored in a dictionary and the other by itself it seems like if the dictionary was the problem that downloading files wouldnt work but that is not the casedoes anyone know what could cause this behavior or could recommend another way to manage my connections if this way is causing problemsi am using python 27 with paramiko 176 i have tested this code on both linux and windows and got the same resultsedit code included nowimport osimport paramikoclass managessh manages ssh connections def init self selfhosts testbox testbox test test selfsshconnections selfsftpconnections selflocalfile ctestfile selfremotefile tmptempfile selffetchedfile ctempdl def sshself manages ssh connections for host in selfhostskeys try selfsshconnectionshost print ssh connection is already open for s host except keyerror e if no ssh connection for the host exists then open one open ssh connection ssh paramikosshclient sshset missing host key policyparamikoautoaddpolicy sshconnectselfhostshost0 22 selfhostshost1 selfhostshost2 selfsshconnectionshost ssh print ssh connection to s opened host try selfsftpconnectionshost print sftp connection is already open for s host except keyerror e open sftp connection ssh paramikosshclient sshset missing host key policyparamikoautoaddpolicy sshconnectselfhostshost0 22 selfhostshost1 selfhostshost2 selfsftpconnectionshost sshopen sftp print sftp connection to s opened host def runcommandself run commands and return output for host in selfhosts command if d tmp then echo n 1 else echo n 0 fi stdin stdout stderr selfsshconnectionshostexec commandcommand print s executed on s command host print returned s stdoutread selfsftpconnectionsgetselfremotefile selffetchedfile print downloaded s from s selfremotefile host selfsftpconnectionshostputselflocalfile selfremotefile print uploaded s to s selflocalfile host selfsftpconnectionshostclose selfsshconnectionshostclose def simpletestself host testbox ssh paramikosshclient sshset missing host key policyparamikoautoaddpolicy sshconnecthost 22 test test sftp sshopen sftp print sftp connection to s opened host sftpgetselfremotefile selffetchedfile print downloaded s from s selflocalfile host sftpputselflocalfile selfremotefile print uploaded s to s selflocalfile host sftpcloseif name main test managessh print running test that works testsimpletest print running test that fails testssh testruncommandoutputrunning test that workssftp connection to testbox openeddownloaded ctestfile from testboxuploaded ctestfile to testboxrunning test that failsh connection to testbox openedsftp connection to testbox openedif d tmp then echo n 1 else echo n 0 fi executed on testboxreturned 1downloaded tmptempfile from testboxtraceback most recent call last file paramikotestpy line 71 in module testruncommand file paramikotestpy line 47 in runcommand selfsftpconnectionshostputselflocalfile selfremotefile file cpython27libsitepackagesparamikosftp clientpy line 561 in put fr selffileremotepath wb file cpython27libsitepackagesparamikosftp clientpy line 245 in open t msg self requestcmd open filename imode attrblock file cpython27libsitepackagesparamikosftp clientpy line 627 in request num self async requesttypenone t arg file cpython27libsitepackagesparamikosftp clientpy line 649 in async request self send packett strmsg file cpython27libsitepackagesparamikosftppy line 172 in send packet self write allout file cpython27libsitepackagesparamikosftppy line 138 in write all raise eoferroreoferror,['python'] +132956,reset auto increment counter in postgres i would like to force the auto increment field of a table to some value i tried with thisalter table product auto increment 1453and alter sequence product restart with 1453error relation your sequence name does not existi am new to postgres i have a table product with id and name field,['sql'] +132961,python string memory usage on freebsd i am observing a strange memory usage pattern with python strings onfreebsd considerthe following session idea is to create a list which holds somestrings so that cumulative characters in the list is 100mbl for i in xrange10 lappendstri 10lenstrithis uses around 100mb of memory as expected and del l will clear thatl for i in xrange20 lappendstri 50lenstrithis is using 165mb of memory i really do not understand where theadditional memory usage is coming from size of both lists are samepython 264 on freebsd 72 on linuxwindows both uses around100mb memory onlyupdate i am measuring memory using ps aux that can be executed using ossytem after above code snippets also these were executed separatelyupdate2 looks like freebsd mallocs memory in multiples of 2 so allocating 5kb actually allocates 8kb i am not sure though,['python'] +132970,confused by the content of exceptionstacktrace suppose i have the following situation9 class program10 11 public static void wrappermethodaction func12 13 try14 15 throw new exceptioncase 116 funcinvoke17 18 catch exception ex19 20 consolewritelineexstacktrace21 22 23 24 static void mainstring args25 26 wrappermethod throw new exceptioncase 2 27 28 i run it and have the following outputat testexceptionsprogrammainb 0 in cusersadministratordocumentsvisual studio 2010projectstestexceptionstestexceptionsprogramcsline 26 at testexceptionsprogramwrappermethodaction func in cusersadministratordocumentsvisual studio 2010projectstestexceptionstestexceptionsprogramcsline 16if i uncomment throw new exceptioncase 1the output isat testexceptionsprogramwrappermethodaction func in cusersadministratordocumentsvisual studio 2010projectstestexceptionstestexceptionsprogramcsline 15so my question is why in the first case i can see the full path including the main function while i cannot see the same stuff in the second casehow can i thisplay the more complete information if the production code is similar to the second case scenario,['c#'] +132975,how do i replace all instances of a string with another string i found this on another stack question void replaceallstdstring str const stdstring from const stdstring to size t start pos 0 whilestart pos strfindfrom start pos stdstringnpos size t end pos start pos fromlength strreplacestart pos end pos to start pos tolength in case to contains from like replacing x with yx and my method string convert fann array to binarystring fann array string result fann array cout result n replaceallresult 1 0 cout result n replaceallresult 1 1 return resultwhich for this inputcout convert fann array to binary1 1 1 1 1 1 now the output should be 110011here is the output of the method 1 1 1 1 1 1 original1 1 0 1 replacing 1s with 0s11 1 result as it was returned from convert fann array to binaryi have been looking at the replaceall code and i am really not sure why it is replacing consecutive 1s with one 0 and then not returning any 0s and some 1s in the final result,['c++'] +132989,where is the resources folder for my project in xcode 4 when i create a new project in xcode 4 it does not create the resources folder like xcode 3 used to do is there a setting in xcode 4 to make this work,"['iphone', 'ios']" +132992,adb server not responding i am a android newbie i guess i might be doing something stupid here i have started the virtual device and i see that adbd daemon is running from the terminal emulator when i search for adb devices i get the following errorcprogram filesandroidandroidsdktoolsadb devices daemon not running starting it now on port 5037 adb server did not ack failed to start daemon error cannot connect to daemonno other process is using port 5037 what am i doing wrong here are the packages i have installed 1 android sdk tools revision 102 android sdk platformtools revision 33 sdk platform android 233 api 10 revision 1,['android'] +132994,mediaplayer stutters at start of mp3 playback i have been having a problem playing an mp3 file stored in a raw resource when the file first starts playing it generates perhaps a quarter of a second of sound and then restarts i know that this is basically a duplicate of the problem described here but the solution offered there has not worked for me i have tried several things and have made some progress on the problem but it is not totally fixedheres how i am setting up to play a filemplayerresettry assetfiledescriptor afd getresourcesopenrawresourcefdmaudioid if afd null toastmaketextmowner could not load sound toastlength longshow return mplayersetdatasourceafdgetfiledescriptor afdgetstartoffset afdgetlength afdclose mplayerprepare catch exception e logdlog tag could not load sound e toastmaketextmowner could not load sound toastlength long showif i exit the activity which calls mplayerrelease and come back to it creating a new mediaplayer the stutter is usually but not always goneprovided i load the same sound file i tried a couple of things that made no differenceload the sound file as an asset instead of as a resourcecreate the mediaplayer using mediaplayercreategetcontext maudioid and skip the calls to setdatasource and preparethen i noticed that logcat always shows this line at about the time that playback startsdebugaudiosink37 buffercount 4 is too small and increased to 12it got me wondering if the stuttering is due to the apparent rebuffering this led me to try something elseafter calling prepare call mplayerstart and immediately call mplayerpauseto my pleasant surprise this had a big effect a great deal of the stutter is gone plus no sound that i can hear is actually played at that point in the processhowever it still stutters from time to time when i call mplayerstart for real plus this seems like a huge kludge is there any way to kill this problem completely and cleanlyedit more info not sure if related if i call pause during playback seek to an earlier position and call start again i hear a short bit 14 sec of additional sound from where it was paused before it starts playing at the new position this seems to point to more buffering problemsalso the stuttering and paused buffer problems show up on emulators from 16 through 30,['android'] +133011,how to align text fields in div i am trying to align text fields in a div and make them float left so that they look like a table i want a layout like belowlabel1 textfield label2 textfield label3 textfieldlabel4 textfield label5 textfield label6 textfieldi tried to do this but it just would not come out correct,"['html', 'css']" +133020,xcode 4 if self super init issue i have recently eg just now upgraded to xcode 4 and i like it overall however there is one thing that annoys mewhen i write code like this if self super init it gives me an issue using the result of an assignment as a condition without parentheses how can i suppress this warning as it underlines all the text in red making me think that there is a critical error as i am a somewhat seasoned objectivec coder i really do not want to change my practices and add extra parentheses around my init statements,['objective-c'] +133041,finding columns that are not null in postgresql i had an assignment for each table to count nullable columns easy select table name count from information schemacolumns where is nullableno group by table namenow i have to modify this to count columns that have property not null will the following code do this or will it just check weather column name is not nullcreate temp table a as select thistinct column name table name as name from information schemacolumnswhere column name is not nullgroup by table name column nameselect name count from agroup by nameif no any advices,['sql'] +133042,scrollable i would like to have a table with a scrollbar to the righti want to accomplish this without any pluginsjquery just with cssthe table header is supposed to stay fixedwhat do i need to do to get this working,"['html', 'css']" +133047,onclicklistener cannot be resolved to a type eclipse hello im new to programming im trying to construct my first simple application im looking to play a short soundclip on the push of an imagebuttonwhile typing out my code i get an error with the statement buttonsetonclicklistenernew onclicklistener the on click listener is underlined and when i go to the error eclipse tells me that onclicklistener cannot be resolved to a typehere is my codeimport androidappactivityimport androidosbundleimport androidviewviewimport androidviewviewonclicklistenerimport androidwidgetbuttonimport androidwidgetimagebuttonpublic class main extends activity called when the activity is first created overridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmainfinal imagebutton button imagebutton findviewbyidridimagebutton1buttonsetonclicklistenernew onclicklistener public void onclickview v perform action on clicks i read a suggestion that said to addimport androidviewviewaswell asimport androidviewviewonclicklistenerthese import statements are also highlightedcould these errors be caused by how eclipse is set up on my computerany help would be greatly appreciated,"['java', 'android']" +133054,does the nsnotification retain the object my question is in regards the object that gets added to a postnotificationnameobject userinfo method does the nsnotification retain the object in a similar fashion to nsmutabledictionary or array meaning i can release the object after posting the notificationbelow is a code snippet to help describe my question is it valid to release the object a link to apple documentation could be really helpfulnsmutabledictionary teamdictcopy selfteamdict mutablecopyteamdictcopy setobjectnsnumber numberwithintselfscrollviewindex forkeyimageindexifselfstatusbuttontitle isequaltostringcompleted nsnotificationcenter defaultcenter postnotificationnameuncomplete objectteamdictcopy userinfonilteamdictcopy release,"['iphone', 'ios']" +133055,jquery ajax json datatype conversion hopefully that title is not too cryptic whats happening is i have a jquery ajax script that i am trying to use to access an api on a remote server which returns a json response however the api returns the json as mime type texthtml in the response header instead of applicationjson it would seem obvious that i simply need to change the returned content type from text to json to make the ajax call interpret the data correctlyunfortunately this is not the case i have tried this in a multitude of different ways all of which fail the closest i have gotten to getting this api call to work is when the debugger tells me resource interpreted as script but transferred with mime type texthtml and the ajax call errors out with my debug message that dumps the jqxhr object in json format which tells me readystate4status200statustextparsererrorhere is an example of my code although i have changed the code many various ways in my attempts at getting it to work but this version seems to be the closest to correctajax type get url httpusernameapiv1projectsjson contenttype applicationjson datatype jsonp converters jsonp jqueryparsejson success functiondata alertdata error functionjqxhr textstatus errorthrown consolelogjsonstringifyjqxhr consolelogtextstatus errorthrown if anyone can figure out what i need to do differently to make this work i will be extremely gratefulit may also be worth noting that if you copypaste the api url into a browser address bar and hit go it gives the proper json response with the proper response header applicationjson,['jquery'] +133058,getting exact error type in from dbvalidationexception i have the situation where i am initializing my model in databaseinitializer for ef 41 and get this annoying error validation failed for one or more entities see entityvalidationerrors property for more details so i go to this entityvalidationerrors and there is a field systemdataentityvalidationdbentityvalidationresult which gives me no information at all about what field it was unable to initialize is there a way to get more info about this errorto clear things outi know how to fix the string length problem what i am asking is how do i get the exact field name that is breaking the model,['.net'] +133060,start and stop profiling from javascript in chrome i would love to be able to start and stop the cpu profiler in the chrome developer window by making a javascript call something likechromecpuprofilerstart do expensive operation chromecpuprofilerstopright now the best i can do isclick start profiling do expensive operation click stop profiling is there even a shortcut key for this,['javascript'] +133067,jquery if page loaded is there any trick how to start a function in javascript which starts when the page is completely loaded,"['javascript', 'jquery']" +133083,entity framework code first how can i create a onetomany and a onetoone relationship between two tables here is my modelpublic class customer public int id get set public int mailingaddressid get set public virtual address mailingaddress get set public virtual icollectionaddress addresses get set public class address public int id get set public int customerid get set public virtual customer customer get set a customer can have any number of addresses however only one of those addresses can be a mailing addressi can get the one to one relationship and the one to many working just fine if i only use one but when i try and introduce both i get multiple customerid keys customerid1 customerid2 customerid3 on the addresses table i am really tearing my hair out over this onein order to map the one to one relationship i am using the method described here,['c#'] +133085,what is the difference between const iterator and iterator what is difference between these two regarding implementation inside stlwhat is the difference regarding performancei guess when it is read only we prefer const iterator rightthank you,['c++'] +133087,intentservice would not show toast this intentservice i created will show toasts in onstartcommand and in ondestroy but not in onhandleintent am i missing something about the limitations of an intentservicepublic class myservice extends intentservice private static final string tag myservicepublic myservice supermyserviceoverrideprotected void onhandleintentintent intent cycleoverridepublic int onstartcommandintent intent int flags int startid toastmaketextthis service starting toastlength shortshow this happens return superonstartcommandintentflagsstartidoverridepublic void oncreate superoncreateoverridepublic void ondestroy toastmaketextthis service stopping toastlength shortshow this happens superondestroyprivate void cycle toastmaketextthis cycle done toastlength shortshow this does not happen logdtagcycle completed this happens,['android'] +133091,sql to list all the tables that reference a particular column in a table i am using postgresql and i am trying to list all the tables that have a particular column from a table as a foreignkeyreference can this be done i am sure this information is stored somewhere in information schema but i have no idea how to start querying it thanks,['sql'] +133106,avassetimagegenerator provides images rotated when obtaining a uiimage of a video via avassetimagegenerator i am getting back images rotated well technically they are not when the video is shot in portrait orientation how can i tell what orientation the video was shot and then rotate the image properlyavurlasset asset avurlasset alloc initwithurlurl optionsnilavassetimagegenerator generate avassetimagegenerator alloc initwithassetassetnserror err nullcmtime time cmtimemake0 60cgimageref imgref generate copycgimageattimetime actualtimenull errorerrgenerate releaseuiimage currentimg uiimage alloc initwithcgimageimgref,"['iphone', 'objective-c', 'ios']" +133121,how to inject a map in java springs how to inject a map in java spring frameworkif possible please provide some sample codeis the following legalproperty nametestmap map entry key valuetestvalue key value list valuestringvalue valuestringvalue list value entry map property,['java'] +133134,css better to change cursor on hover or on stateless say you or i have coded an html elementa idhydrogen hrefhaand some hover csshydrogenhover backgroundredand now we want to put a fancy hand cursor when hovering there is two options for thisapply to stateless element hydrogen cursorpointeror apply to hover statehydrogenhover colorred cursorpointermy question is there any reasons why one way is decisively better than the other or is it tomato tomato,['css'] +133148,how to implement the action bar in api levels less than 11 i recently read about the action bar implementation in android in the dev sitebut i found that it requires a minimum api level of 11can someone tell me whether it is possible to implement action bar in api levels less than 11 such as 8 or 9if yes how can i do this,['android'] +133160,how can i get the product of all elements in a one dimensional numpy array i have a one dimensional numpy arraya numpyarray233i would like to have the product of all elements 18 in this casethe only way i could find to do this would beb reducelambda xy xy awhich looks pretty but is not very fast i need to do this a lotis there a numpy method that does this if not what is the most efficient way of doing this my real world arrays have 39 float elements,['python'] +133167,how can i create animated gif in java i would like to create a gif image from the set of bufferedimages how can i do this is there such library in pure java imagemagick is not an option i have found gif4j library but it is not royalityfree,['java'] +133169,how do i use a complex criteria inside a doctrine 2 entitys repository lets say i have a table that holds information about festivalseach festival has a start and end datei want to select all the festivals that are live that happen on a given datemeaning i want to select all the festivals that their start date is before or on a given date and that their end date is after or on a the same given dateso i went on to the repository class of the festival entity and created a method to do just thatbut the criteria argument findby expects is an array which all the examples only treat as a simple criteria eg arrayname billy will select all the rows that have the value billy in their name column which uses only the comparison operatorhow can i use other operators such as in not in like and etc thanks,"['php', 'sql']" +133174,how do i get php to log a stacktrace upon fatal error i have configured php to log errors and on my development machine they show up in the apache error logs asthu mar 17 182207 2011 error client 1 php parse error syntax error unexpected in userstroelsknprojectstestbootstrapincphp on line 27thu mar 17 182207 2011 error client 1 php stack tracethu mar 17 182207 2011 error client 1 php 1 main userstroelsknprojectstestpublicindexphp0however on the production machines ubuntu there is no stacktrace following the error and there is a referrer attached to the message eg it would look likethu mar 17 182207 2011 error client 1 php parse error syntax error unexpected in userstroelsknprojectstestbootstrapincphp on line 27 referer httplocalhosthow can i control this formatting i would very much like to have the stacktrace available in the logs,['php'] +133175,array unique without sorting i am building an autoloader that extends the include path it takes an array appends the exploded include path removes all references to the current directory adds a single current directory at the start of the array and finally join the whole thing back together to form a new include path the code is listed belowphpstatic public function extendincludepath array paths build a list of the current and new paths pathlist array merge explode path separator paths explode path separator get include path remove any references to the current directory from the path list while key array search pathlist unset pathlist key put a current directory reference to the front of the path array unshift pathlist generate the new path list newpath implode path separator pathlist if oldpath set include path newpath selfoldpaths oldpath return oldpathi wanted to also use array unique on the array before imploding it so that php does not keep looking in the same place multiple times if someone is careless and specifies the same path more than once however i also need to maintain the sort order of the array because include looks in the directories in the order they are defined in the include path i want to look in the current directory first then my list of search directories and finally the original include path so that for example an old version of a common library in the default include path does not get included in favour of a newer version in my search list for these reasons i cannot use array unique because it sorts the arrays contents is there a way of getting array unique to preserve the order of the elements in my array,['php'] +133180,php namespaces and require i need to include several files in a main indexphp filei am working with namespacescan i use includerequire and make the files use the same namespace as indexphp without specifying the namespaces and use statements in each included file,['php'] +133187,use of dialogs vs activities in android development where a popup interaction with a user is requiredone can use in most situations either a dialog or a activityexcluding extreme cases where the choice is easy i would like to knowyour ideas on which is preferedfor ex one might say that on screen orientation a dialog is lost and the userwill have to do the same interaction to get it while an activity stays in placeof course it is created again but still stays in its place in the visibility stacki would like all possible issues for both cases performance sideeffectsuser interaction issues etc,['android'] +133192,best way to separate two base64 strings i am using standard input and output to pass 2 base64 strings from one application to another what would be the best way separating them so i could get them as a two separate strings in other application i was thinking using a simple comma to separate them and then just use string s outputsplitwhere output is the data i read in from standard outputexample with the commamigfma0gcsqgsib3dqebaquaa4gnadcbiqkbgqcv5e5y0wrad5frljeusa71gipl3mhjiucw1xhj jdwxn87lihpe32uvitfmvp8flqfhi5h0pditdczufg8lxuiuoxxellwexa8hs7jc4zzr5ps3r fov3m6h8k5xgkwwlhvnqx47sagyy43jdbfx7fsyufehwwa2yksmzs3widaqab hnjpfqyeyjovbeegkwwntzr0jtpia1hlk1c8lbfcvcjfl33ssq3gbzi0zxn0n2wxbykjzj2kqbs lvrmfbqjrgvq4znf4f8zxjl9rvverk5x243c3szh05phzxiuyxje6gkitdmsxcwovvzsaghzu 3qqknbhin0fvyynpg0kfm0wytuw71ku1eq45ibcczgwqlrjx1gkzc9wh7xv36i6spyrxzucil 4qgnkt6x4qg7gfk3msam6h6jtfdzkehjjq6jzeapdqn5lxemy0jlgc4cadmcvyjdrcg02pg2woo gjt77xvxd1igibqypflwxi0biurwmaelojmzdryjjly69auxgpnqvsf4awc6jo8m1pzzhb yqva8kyirwbyijobosgok18upfwej5he3e8lwseciiopgxyxtnkseesgdopeem3huknyips lsthzekzejftr8lib9hlqdikyu2mqjtik5ciexoyy2go0ndl84rczmzalfflffocl9xsgyeer m1mxmydtmiqfdphezixhoylcikuhwr00dhxkvrq4q9lyceygfdiewlrm5seepcklwttgycv9hm h5vylhgikf5w6xcqcjle6vp4wwxmkhqyqradfw5mywskx7jbdtmv2mly7n6gqrqaopk8ruabvf mwwp1sgyhaxgrwuxth1tw498wi5jtqr3oub3uj5aqydhwzqtwm58wfvqxdv2bfzmgh7d9ac95 dq8qxkrv7otwvq5kklgpjy8imegiyxomqhklnz3qvbaijde2zivpty6xgmwgc4jebarra6v cbsovrezmxllnw,['c#'] +133215,uiwebview cancel opening a link when touch up is outside of the link i have a uiwebview with links in the text which open safari if pressedif a user touches a link it darkensbut if he wants to cancel pressing the link by moving his finger away first it stays dark and releasing the finger anywhere opens the linkis there some way to enable the user to cancel his click by moving away his finger along the lines of the behavior of a touch up inside button,['ios'] +133226,how to mock protected virtual members in fakeiteasy moq allows mocking protected virtual members see here is it possible to do the same in fakeiteasy,['c#'] +133235,webbrowserdrawtobitmap generating blank images for few sites consistently i have been using webbrowserdrawtobitmap in my aspnet page running in separate sta thread to capture web pages as an image but i found that i am getting blank images for few sites consistently i am aware that the method is not officially supported but it would be nice if someone can provide me any reason or a work around for these blank images issue,"['c#', 'asp.net']" +133245,how to allow sorting of a gridview i have a gridview and enabled sorting when running the application i click on the first column to sort and i get this error the gridview gvoutlookmeldingen fired event sorting which was not handledthis is the gridview aspgridview idgvoutlookmeldingen runatserver allowsortingtrue autogeneratecolumnsfalse autogenerateselectbuttontrue onselectedindexchangedgridview selectedindexchanged columns asptemplatefield headertextmelder itemstylehorizontalaligncenter sortexpressionmelder headerstyle bordercolor1a3491 width130pxheaderstyle itemstyle height20px horizontalaligncenteritemstyle itemtemplate stringevalmelder itemtemplate asptemplatefield aspboundfield datafieldonderwerp headertextonderwerp asptemplatefield headertextomschrijving itemtemplate div styleoverflowauto width 500px height 200px asplabel idlblomschrijving runatserver text bindomschrijvingasplabel div itemtemplate asptemplatefield aspboundfield datafieldmeldingsdatum headertextmeldingsdatum aspboundfield datafieldoutlookid headertextoutlookid columnsaspgridviewany help is appreciated,"['c#', 'asp.net']" +133249,meaning of javalangclasscastexception someclass incompatible with someclass i was experiencing occasional exceptions in xpages applicationjavalangclasscastexception someclass incompatible with someclassboth mentioned classes are the same it is class used as session bean i was not able to google anything covering my problem usual explanation for this was change in design elements not my casethe xpage application become unusable pages using session bean someclass since that moment until restart of http task or resave of facesconfigxmlin some cases this is related to other exceptioncomibmjscriptinterpretexception script interpreter error linex coly java method methodsignature containg someclasson java class someotherclass not foundwhat is behind this behavior,['java'] +133254,how to get an error description when playback fails on mpmovieplayercontroller i want to show an uialert if the videoplay fails so i registered the mpmovieplayerplaybackdidfinishnotification for my movie playernsnotificationcenter defaultcenter addobserverself selectorselectormymoviefinishedcallback namempmovieplayerplaybackdidfinishnotification objectselfmovieplayerin my mymoviefinishedcallback i check if in the user info dictionary is a object named error on my real device i do not get this error on no network error 404 error for file on the iphone simulator i receive the errorhow can i properly check the reasoning when i receive the mpmovieplayerplaybackdidfinishnotification,"['ios', 'objective-c']" +133255,how to use native activity can it be combined with traditional activity i have two libraries so which i load in java codehowever there are a few specific operations which require javaactivitycso files calls can i use native activity to implement part of those functionalities is native activity something which is additional to traditional activity or do i have to choose which type of activity i will useeditthere is a set of events which can be handled in native code by native activityandroidndksourcesandroidnative app glueandroid native app gluehenum command from main thread the ainputqueue has changed upon processing this command android appinputqueue will be updated to the new queue or null app cmd input changed command from main thread a new anativewindow is ready for use upon receiving this command android appwindow will contain the new window surface app cmd init window command from main thread the existing anativewindow needs to be terminated upon receiving this command android appwindow still contains the existing window after calling android app exec cmd it will be set to null app cmd term window command from main thread the current anativewindow has been resized please redraw with its new size app cmd window resized command from main thread the system needs that the current anativewindow be redrawn you should redraw the window before handing this to android app exec cmd in order to avoid transient drawing glitches app cmd window redraw needed command from main thread the content area of the window has changed such as from the soft input window being shown or hidden you can find the new content rect in android appcontentrect app cmd content rect changed command from main thread the apps activity window has gained input focus app cmd gained focus command from main thread the apps activity window has lost input focus app cmd lost focus command from main thread the current device configuration has changed app cmd config changed command from main thread the system is running low on memory try to reduce your memory use app cmd low memory command from main thread the apps activity has been started app cmd start command from main thread the apps activity has been resumed app cmd resume command from main thread the app should generate a new saved state for itself to restore from later if needed if you have saved state allocate it with malloc and place it in android appsavedstate with the size in android appsavedstatesize the will be freed for you later app cmd save state command from main thread the apps activity has been paused app cmd pause command from main thread the apps activity has been stopped app cmd stop command from main thread the apps activity is being destroyed and waiting for the app thread to clean up and exit before proceeding app cmd destroysince i know that part of my code which should be called after specific event is written in c i think it will be better to handle this in c via native activity however i have also code which have to be called after handle events in javaquestion is can i have native version native interface of my activity which will help me with some events and traditional java interface to this same activity in this same time,['android'] +133276,how to download multiple files in one shot in ie i want to download multiple files on click of a button in jspi am using the following code in the js to call one servlet twicevar iframe documentcreateelementiframeiframewidth iframeheight iframeframeborder 0iframescrolling noiframesrc xyzjspprodidp10245documentgetelementbyidiframe holderappendchildiframevar iframe2 documentcreateelementiframeiframe2width iframe2height iframe2frameborder 0iframe2scrolling noiframe2src xyzjspprodidp10243documentgetelementbyidiframe holderappendchildiframe2in xyzjsp i am calling the servlet which downloads the file from a path and send it on the browserissue is that it is working safarifirefox but not in iewe cannot download multiple files with ie,['javascript'] +133292,nested select linq query trying to work out a linq query and was wondering if you guys could help i have a list of objects foo and each foo object has a list of bar bar has an active date and a numeric value for examplefoo bar 010205 10 bar 040610 30023foo bar 300102 23494and i want to write a linq query that will return me a thistinct list of dates and the summed total for that dateit may be that its friday but i am drawing a blankthanks in advance,['c#'] +133304,comandroidmlibsyncexception too many open files when i attempt to run my application in eclipse on my device i have started getting alot of comandroidmlibsyncexception too many open files exceptionserrors in the console why is this and what does it mean what can i do to stop this,['android'] +133323,android imageview size not scaling with source image i have a few imageviews inside a linearlayout i need to scale down the imageviews so that they maintain their aspect ratios whilst fitting inside the linearlayout vertically horizontally i just need them to be adjacent to each otheri have made a simplified test bed for this which nests weighted layouts so that i have a wide but not very tall linearlayout for the imageviews xml version10 encodingutf8linearlayout xmlnsandroid androidorientationvertical androidlayout widthfill parent androidlayout heightfill parent linearlayout androidididlinearlayout1 androidlayout widthfill parent androidlayout heightfill parent androidlayout weight5 linearlayout androidididlinearlayout3 androidlayout heightfill parent androidlayout widthfill parent androidlayout weight1 imageview androidididimageview1 androidlayout heightwrap content androidlayout widthwrap content androidsrcdrawabletest image androidscaletypefitstartimageview imageview androidididimageview2 androidlayout heightwrap content androidlayout widthwrap content androidsrcdrawabletest image androidscaletypefitstartimageview linearlayout linearlayout androidididlinearlayout4 androidlayout heightfill parent androidlayout widthfill parent androidlayout weight1linearlayout linearlayout linearlayout androidididlinearlayout2 androidlayout widthfill parent androidlayout heightfill parent androidlayout weight1linearlayoutlinearlayoutin the eclipse layout editor the images are clipped vertically and not scaled at all but that is just one of those idiosyncrasies that we learn to lovewhen run on hardware the images are scaled to the correct height whilst preserving their aspect ratio my problem is that they are not next to each other the height of each imageview correctly matches the height of the linearlayout the width of each imageview is the width of the unscaled image the actual scaled down images appearing at the left side of their imageviews because of this i am getting a large gap between the imagesideally i would like to manage this through xml though if this is not possible i understand that using a custom view may be the best solutioni tried creating an iconview extends imageview class which overrides onmeasure so that i could create image views of the necessary size by scaling the width depending on the height but the parentwidth and parentheight being passed into the function were the dimensions of the screen and not of the linearlayout containeroverrideprotected void onmeasureint widthmeasurespec int heightmeasurespec int parentwidth measurespecgetsizewidthmeasurespec int parentheight measurespecgetsizeheightmeasurespec calculations followed by calls to setmeasureddimension setlayoutparams superonmeasurewidthmeasurespec heightmeasurespecso my questions are 1 can i amend the xml in some way to make it do what i need2 how do i make my custom class get the height of the linearlayout so that i can calculate the necessary width for the custom imagesthanks if youve managed to read this far even more thanks if you can point me in the direction of a solution,['android'] +133330,fulltext substring searching in ios i need my iphone ipad app to be able to quickly search through about 10 records about a paragraph worth of text each for any substring contained within the record so if the record contains the word flame querying for lame should match i am currently using sqlite but like term searches are too slow for this many records enabling fulltext search does not seem like it will fully meet my needs since sqlite only supports prefix wildcards eg flam not lamei have experimented with using a giant blob of text 350k and doing nsstring rangeofstring which i think uses a boyermoore algorithm this is faster than like term searches but still not the kind of speed i am hoping for any suggestions for approaches or libraries that would achieve this kind of scalable substring search and which would work on an iphone,"['iphone', 'ios']" +133347,simulating nested functions in c in c the following code works consider i always use gccint foo int foo var code int bar int bar var code return bar var return barfoo varhow can achieve the same functionality of nested functions in c on gcc compiler do not mind if this seems like a beginner question i am new to this site,"['c++', 'c']" +133362,android proguard javascript interface problem my project after obfuscation with proguard fail with javascriptinterface here is the link with some suggestions for proguard configuration but it dosnt work in my case threadthreadf889e846fbf7ec3fpli1so the calls from javascript loose binding to the associated java methodsmy proguard configuration regarding that keep public class comtrans codeandroidjavascriptcallback keep public class implements comtrans codeandroidjavascriptcallback keepclassmembers class implements comtrans codeandroidjavascriptcallback methods keepclassmembers class implements javascriptcallback void on keep public class comtrans code public protected keepclasseswithmembernames class commyactivityjavascriptinterfacekeepclasseswithmembernames class commyactivityjavascriptinterface public protected if anyone knows how to configure proguard to have it filter out related methods and classes that will help me a lot,"['javascript', 'android']" +133372,set animation google maps marker well im trying to set the bounce animation to a specific marker but whenever i call the markersetanimationgooglemapsanimationbounce method console says cannot read property bounce of undefined this means that marker is not defined right but if i use markersettitlebouncing the title does change am i doing something wrong here is the code script typetextjavascript function addmarkerlatlngimgtitlebounce var mylatlng new googlemapslatlnglat lng var marker new googlemapsmarker position mylatlng map map icon img title title zindex 1 ifbouncesetmarkersetanimationgooglemapsanimationbounce markersettitlebouncing scriptphp script fori0icountlosdatosi utcnew datetimelosdatosifechautc utcmodifyhorarioverano hours echo utcformatymd his iflosdatosicamioncamion scriptaddmarkerlosdatosilatitudlosdatosilongitudlosdatosiimglosdatosinombreset else scriptaddmarkerlosdatosilatitudlosdatosilongitudlosdatosiimglosdatosinombre echo script,['javascript'] +133381,keyword not supported provider error cnet 35 with a sql server 20 backend i have a connection string in my appconfig file that looks like thisadd namemfg connectionstring connectionstringprovidersqloledbdata sourcemfgpersist security infotruepasswordkb1234user idkbinitial catalogmfg providernamesystemdataoledb this connection string was built with the data source configuration wizard creating a dataset with this and dragging the datasource element to create a datagridview populates and successfully allows all crud operationshowever i am not looking to make changes to this through a databound form i am looking to do this behind the scenes in code since this is an older version of sql server i am assuming i must use oledbconnection and other oledb objects to get the job done when i try to execute the followingoledbconnection visualconnection new oledbconnectionconfigurationmanagerconnectionstringsmfg connectionstringconnectionstringi get an exception keyword not supported provideryet if i take out provider i am told that i must supply one not sure why this works through the dataset on the form yet i cannot create my own connection object any thoughtsedit it should be noted that when i originally created the connection to this database it told me that the database i was trying to connect to did not support sqlconnection and that i must choose another my choice being oledb at that time it is odd to me that this connection works behind the scenes as sqlconnection without provider in the connection string but the dataset then breaks,['c#'] +133384,how to center two divs floating next to one another i have written the following html trying to center two divs next to each otherdiv idwrapper styletextaligncenter div stylefloatleft lorem ipsumbr dolor sit amet div div stylefloatleft lorem ipsumbr dolor sit amet divdivhowever the code i have written results in the two divs floating all the way to the left what this does do correctly is float the two divs side by sidewhat do i need to change to center the two divs side by side,"['html', 'css']" +133387,unsafe class in android do the android dalvik standard libraries have any class similar to the undocumented class sunmiscunsafe in java se which allows direct access to memory,"['java', 'android']" +133391,python regex matching a parenthesis within parenthesis i have been trying to match the following stringstring templates indexhtml home basehtml basebut unfortunately my knowledge of regular expressions is very limited as you can see there are two parentheses that need to be matched along with the content inside the second onei tried using rematchw string but it did not work any help would be greatly appreciated,['python'] +133402,contenttype not changing with curlopt httpheaders i am trying to post some json to a web service with curl using the following codech curl initcurl setoptch curlopt returntransfer truecurl setoptch curlopt post truecurl setoptch curlopt header truecurl setoptch curlopt verbose truecurl setoptch curlopt url akapikeycurl setoptch curlopt httpheadersarraycontenttype applicationjsondata array ignorerobots false language english crawldelay 0 depth 3 root arrayurl curl setoptch curlopt postfields http build querydataresultcurl execchvar dumpresulti get the following in returnstring282 http11 200 ok server apachecoyote11 accesscontrolalloworigin contenttype textplain contentlength 120 date fri 18 mar 2011 190323 gmt codeerrorindexdefinitioninvalidmessageinvalid content provided for define errorpremature end of file i found this blog post that seems to be related it does seem to be sending textplain even though i have specified the contenttype in curlopt httpheaders as applicationjson but adding http build query has not helpedthanks in advance for any help,['php'] +133403,regex failing when pattern involves dollar sign i am running into a bit of an issue when it comes to matching subpatterns that involve the dollar sign for example consider the following chunk of textregular price 2050 final price 1520regular price 1899 final price 225regular price 1122 final price 3344regular price 5566 final price 7788i was attempting to match the regularfinal price sets with the following regex but it simply was not working no matches at allpreg match allregular price dd2final price dd2u data matchesi escaped the dollar sign so what gives,['php'] +133404,seamless deployment in aspnet iis kills worker process before new worker process is ready i am trying to deploy a net web application to iis 75 without any hassle for the users i have made sure that thisable overlapped recycle is false but i still run into the same problem every timeevery time i upload new binaries for the site iis kills the worker process before it has started a new one so every time i upload new binaries users get this error messageserver error in application could not load file or assembly myapplicationweb or one of its dependencies the process cannot access the file because it is being used by another process exception from hresult 0x80070020i have no idea how to do this seamless as it is now i just upload the binary but while the upload occurs or local copy it will give the above quoted behaviour i also tried using a web garden but with same resultwhat i am not looking forhow to solve it with external load balancers it is a functional solution but it is perfomance wise a bad solution for few servers and it would not work at all if there is only one serverhow to create a hackaround with a refresh in a custom error page as it has some obvious problems but more importantly wont work at all with web servicesajaxi really think this should be doable given updatein article above they sayhowever because the shutdown timeout value of a shutdown or startup is configurable the worker process can be terminated while it is still serving requests if it does not finish servicing existing requests within the time limiti have no idea where to find this value nor what it is default if its less then a few second it might explain my resultsps i am posting it on so rather than on sfwebmasters etc because i think this kind of knowledge will probably be minimal amongst people who are not active in development i hope this is all right,['asp.net'] +133409,moving if statement condition to a local variable makes c compiler unhappy could you please explain me the reason of the following situationtoday i wrote the code only variables names are changedprivate void foo int firstinteger secondinteger const string firststringvalue 1 secondstringvalue 2 if stringisnullorwhitespacefirststringvalue inttryparsefirststringvalue out firstinteger stringisnullorwhitespacesecondstringvalue inttryparsesecondstringvalue out secondinteger using firstinteger and secondinteger here firstinteger secondinteger everything was fine until i decided to move the if condition to a variableprivate void foo int firstinteger secondinteger const string firststringvalue 1 secondstringvalue 2 bool firstintegerandsecondintegerarespecified stringisnullorwhitespacefirststringvalue inttryparsefirststringvalue out firstinteger stringisnullorwhitespacesecondstringvalue inttryparsesecondstringvalue out secondinteger if firstintegerandsecondintegerarespecified use firstinteger and secondinteger here firstinteger secondinteger now the compiler underlines firstinteger and secondinteger variables with error local variable might not be initialized before accessingbut why the only thing i made is refactored the code a bit and as i see it the logic is the same,['c#'] +133410,enabling django admin filters on manytomany fields i have a simple django model resemblingclass addressmodelsmodel blahclass memberdatamodelsmodel user modelsforeignkeyuser addresses modelsmanytomanyfieldaddressi want to expose the address model in admin to allow a user to filter address records by their associated user egclass addressadminadminmodeladmin model address list filter the modeladminlist filter property allows this but i am not sure what field name to use to support my manytomany relationship if the address model has a direct reference to the memberdata model i could do something likeclass addressadminadminmodeladmin model address list filter memberdata useris there any equivalent syntax for an indirect manytomany relationship if not is there any workaround to accomplish the same end,['python'] +133412,jquery click everywhere but some element i have some elements which i can select with click function and they became highlightedthere is menu above them with some actions i want to cancel highlight when i click any element but not menustructurebody div idmenu div div idelements selectable elements here divbodyi tried to bind body notmenuclick but when i click on menu then bodys onclick event fired too because menu is bodys childrenhelp me please,"['javascript', 'jquery']" +133434,is there a high resolution microsecond nanosecond datetime object available for the clr i have an instrument that stores timestamps the microsecond level and i need to store those timestamps as part of collecting information from the instrument note that i do not need to generate timestamps these time stamps are pregenerated by the instrument itself using a high resolution realtime operating system parsing out these values is not an issue a they are stored using a standard format in utc time originally i wanted to use the c datetime structure can only store time stamps up millisecond resolutionis there another object supplied with net or a common c library that supports micro and ideally nanosecond resolution timestamps or am i going to have to roll my own,"['c#', '.net']" +133436,mitosis of a human cell i am programming genetic processes in java for my project and i want simulate the mitosis of a human cell a human cell contains 23 pairs of chromosome mitosis is basically a cell division or reproduction in which a cell gives rise to two genetically identical daughter cells you can find a picture about it here scroll a little bit down the pagemitosisi think that this mitosis would be like a java method in a class cell for example so i made a class chromosome with it is own methods to represent a single chromosome and made a class cell containing 23 pairs of chromosomes i plan on putting the method mitosis in the class cell but the problem is that this method should return 2 identical cells and i think it is impossible to create a method that returns 2 cells in this class i thought about making a method that would return an array of 2 cells it does not work any suggestions an how to create this method or maybe another approach than the one i am using thanks,['java'] +133449,thisable edittext editability and focus like textview is there a way to make edittext behaviors like textview in android xml is preferedi have tried the following androideditablefalse androidfocusablefalse androidfocusableintouchmodefalse androidcursorvisiblefalse androidlongclickablefalsethis works but i still can touch the edittext to get focus the orange boarder though the focus lost as soon as i remove my fingeri am not sure what focusableintouchmode does but it does not remove the focus when i keep touchingand the reason why i do not use a white background textview instead is that the textviews background is ugly edittexts background has round corners and shadow effectthanks in advance,['android'] +133454,jquery is undefined in the partial view loaded via ajax in ie i have a web page consisting a jquery ui tabs widget tab widget loads the tabs via ajax in one of the tab pages name it descriptionpage i have a form which will be submitted via ajaxform plugindiv idtabs ul li a hrefdescriptionpagedescription pagea li uldivthis is content of my descriptionpageform idmyform form elements goes here formscript function myformajaxformfunction response myformparentemptyappendresponse scriptafter form is submitted the same descriptionpage is returned both the form and script so the form content is replaced with the response of the server side the response also contains validation messages the problem is the whole scenario works well in chrome and firefox but in internet explorer 8 a strange issue happenswhen the tab is first loaded the javascript is successfully executed when user submits the form and the response is put ie fails to execute my javascript saying jquery is not definedwhy ie fails to call jquery inside the content loaded via ajax is there a workaroundps i thought seperating the script from html but it is not an option at all ps2 my javascript and css files became a mess because of stupid ie,['jquery'] +133470,memory allocation of static members in a class i posted a question recentlyinitialization of static class membersnow please check this codeincludeiostreamclass a static int obj spublic a obj s stdcout aobj s nobjects createdn int aobj s 0int maineven though one has not created any object of class a making the member obj s hold a value 0 wouldnt it need memory since its getting defined,['c++'] +133478,how to split a list into pairs in all possible ways i have a list say 6 elements for simplicityl 0 1 2 3 4 5and i want to chunk it into pairs in all possible ways i show some configurations0 1 2 3 4 50 1 2 4 3 50 1 2 5 3 4and so on here a b b a and the order of pairs is not important ie0 1 2 3 4 5 0 1 4 5 2 3the total number of such configurations is 135n1 where n is the length of my listhow can i write a generator in python that gives me all possible configurations for an arbitrary n,['python'] +133481,php create array where key and value is same i am using the range function to create an array however i want the keys to be the same as the value this is ok when i do range0 10 as the index starts from 0 however if i do range1 11 the index will still start from 0 so it ends up 01 when i want it to be 11how can i use range to create an array where the key is the same as the value,['php'] +133506,empty struct in c vs empty struct in c why is empty struct in c a constraint violation why does this rule get changed in c are there any historical reasons,"['c++', 'c']" +133509,thisable parent panel while keeping child panel enabled i have a winforms app and i have a massive panel in it and inside that panel is a bunch of stuff including a second tiny panelwhen a certain event occurs i want the massive panel to become enabled false and i still want the tiny panel to be enabled can i do this i have tried to just reenable the tiny panel after i have thisabled the massive panel but no workyor how can i make it so the tiny panel is ontop of but not inside the massive paneli took a wild guess and triedtinypanelparent nulland tinypanelparent thisbut that just makes tinypanel thisappear,"['c#', '.net']" +133522,fast way to dynamically fill table with data from json in javascript i am experimenting with jquery json etc and came across following task i have a loader script on the server which returns table data in json format when received the json data i want to fill my table with them i am currently using code similar to following there are more columns and some more advanced processing but you got the ideafor var key0 sizedatalength keysizekey tr append tdhtml datakey0 append tdaddclasswhatever1html datakey1 append tdaddclasswhatever2html datakey2 appendtodatatabletable iddatatabletablethis works pretty much ok but once the data is growing it is getting terribly slow for few hunderts of records it take up to about 5s firefox ie to build the table and that is a bit slow if i eg create the whole html on the server and send it as string which i include in the table it will be pretty fastso is there faster way to fill the tablenote i know what is paging and i will use it in the end so please do not say what do you need such a big table on your page for this question is about how to fill table quickly no matter how many records you will thisplay,"['javascript', 'jquery', 'html']" +133534,what easy zlib tutorials are there i am looking for a good tutorial on zlib i am interested only in decompressing the archives i also want to know how i can access a desired file inside an archive preferably by filename alone if that can be done in zlib at all,"['c++', 'c']" +133549,css stretching image to 100 width hi alli am trying to strech the background of my side to fit the width i only found big workarounds in the internet is there not one single command for thisbody backgroundimage urlmoneyjpg thanks for the answersdoonot,['css'] +133556,what is the best approach to develope a large connectedthisconnected application we need to write an application that has two parts one side of the users will be using it running in a thisconnected environment connecting every few hours to the internet the other side will be fully connected monitoring the thisconnected clients the requirement exists that it must run on a browser we are proficient in php so i think we are going this route my question is how would you lay this out on a high leveluse web services for everything db replication with each client having their own db use of php frameworksthank you,['php'] +133578,uitapgesturerecognizer in uiscrollview subview i am trying to use a single tap recognizer in an imageview that is also a scrollview childin interface builder i have created and referentiated the scrollview onlyworks the scrolling but the single tap event is not recognized nothing is logged heres the code voidloadview super loadviewuiimage myimage uiimage imagenamedimg1jpgimageview uiimageview alloc initwithimagemyimagemyimage release add gesture recognizers to the image viewuitapgesturerecognizer singletap uitapgesturerecognizer alloc initwithtargetself actionselectorhandlesingletapimageview addgesturerecognizersingletapsingletap releaseimagescrollview setcontentsizecgsizemakeimageviewframesizewidth imageviewframesizeheightimagescrollview addsubviewimageview voidhandlesingletapuigesturerecognizer gesturerecognizer single tap handlingnslogsinlgetap called i have looked around for hours and tried many things maybe a look of someone else can help much morethanks,['objective-c'] +133585,reloading submodules in ipython currently i am working on a python project that contains sub modules and uses numpyscipy ipython is used as interactive console unfortunately i am not very happy with workflow that i am using right now i would appreciate some advicein ipython the framework is loaded by a simple import command however it is often necessary to change code in one of the submodules of the framework at this point a model is already loaded and i use ipython to interact with it now the framework contains many modules that depend on each other ie when the framework is initially loaded the main module is importing and configuring the submodules the changes to the code are only executed if the module is reloaded using reloadmain modsub mod this is cumbersome as i need to reload all changed modules individually using the full path it would be very convenient if reloadmain module would also reload all sub modules but without reloading numpyscipy,['python'] +133599,get method name from action is it possible to get a method name from an action i know i could always pass a string but i was hoping for something a little more clever public bool devicecommandaction apicall it would be nice to log the method name that was passed in try apicall catch exception exc logexceptionexc return false return true usage looks like thisvoid mymethod devicecommand apiwriteconfigconfig,['c#'] +133602,are there any benchmarks showing good performance of collectionsdeque i was always intrigued by pythons collectionsdeque object it seems to be like a list except that addingdeleting items in the beginning is faster than in a listthis makes me want to replace list with deque in various places in my code where i have a list that i do left pops on so my question did anyone ever benchmark deque against list in such scenarios,['python'] +133603,cloning an object in javascript the below first logs 0 and then logs 1 how do i store a copy of the object rather than a reference to itdebuglogvidetailssegmentvinextsegment videtailsvinextsegmentsegmentdebuglogvidetailssegment,"['javascript', 'jquery']" +133613,how to get the width of an svg tspan element i am trying to get the rendered width of a tspan element located inside a text element in svgthis is my markuptext tspanvalue 1tspan tspanvalue 2tspantextvisually i want value 1 to float left while value 2 floats right so that a multiple elements will align as suchvalue 1 value 2value 10 value 20value 100 value 200value 10 value 20since i want the width of the tpsan value 1value 2 and not the text element i cannot use getbbox as that method does not apply to tspan elementsoddly enough using jquerys width method will return the correct value in chrome but returns nan in firefox any ideas would be appreciated,"['javascript', 'jquery']" +133623,creating a dialogpreference from xml i have been attempting to use an androidpreferencedialogpreference inflated from xml but the documentation seems to be missing some essential bits and i cannot find a working example anywhere my xml now looks like this i tried many permutations but this seems like a reasonable minimumdialogpreferenceandroidkeyfunthing androidtitlefun thingandroiddialoglayoutlayoutfun layoutandroidpositivebuttontextokandroidnegativebuttontextcancelmy supposition at this point is that it is required to subclass dialogpreference and not to use it directly for one i cannot find a way to associate the actual preference value with an element in the dialog itself which upon reflection is kind of a giveaway and also looking at the source to dialogpreferencejava seems to confirm it and i also just noticed that the official documentation refers to it as a base class but at very least it would be nice to establish a definitiveenough source on the net which would help the next and people figure this out faster than i didfor the record the logfile looks like thisiactivitymanager 61 starting intent cmporgjeremyandroidpreferencesactivity from pid 2755wresources 2755 converting to string typedvaluet0x10d0x4b0 a1wresources 2755 converting to string typedvaluet0x10d0x20 a1dandroidruntime 2755 shutting down vmwdalvikvm 2755 threadid1 thread exiting with uncaught exception group0x40015560eandroidruntime 2755 fatal exception maineandroidruntime 2755 javalangruntimeexception unable to start activity componentinfoorgjeremyandroidorgjeremyandroidpreferencesactivity androidviewinflateexception binary xml file line 28 error inflating class javalangreflectconstructoreandroidruntime 2755 at androidappactivitythreadperformlaunchactivityactivitythreadjava1647eandroidruntime 2755 at androidappactivitythreadhandlelaunchactivityactivitythreadjava1663eandroidruntime 2755 at androidappactivitythreadaccess1500activitythreadjava117eandroidruntime 2755 at androidappactivitythreadhhandlemessageactivitythreadjava931eandroidruntime 2755 at androidoshandlerthispatchmessagehandlerjava99eandroidruntime 2755 at androidoslooperlooplooperjava123eandroidruntime 2755 at androidappactivitythreadmainactivitythreadjava3683eandroidruntime 2755 at javalangreflectmethodinvokenativenative methodeandroidruntime 2755 at javalangreflectmethodinvokemethodjava507eandroidruntime 2755 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava839eandroidruntime 2755 at comandroidinternaloszygoteinitmainzygoteinitjava597eandroidruntime 2755 at dalviksystemnativestartmainnative methodeandroidruntime 2755 caused by androidviewinflateexception binary xml file line 28 error inflating class javalangreflectconstructoreandroidruntime 2755 at androidpreferencegenericinflatercreateitemgenericinflaterjava397eandroidruntime 2755 at androidpreferencegenericinflateroncreateitemgenericinflaterjava417eandroidruntime 2755 at androidpreferencegenericinflatercreateitemfromtaggenericinflaterjava428eandroidruntime 2755 at androidpreferencegenericinflaterrinflategenericinflaterjava481eandroidruntime 2755 at androidpreferencegenericinflaterrinflategenericinflaterjava493eandroidruntime 2755 at androidpreferencegenericinflaterinflategenericinflaterjava326eandroidruntime 2755 at androidpreferencegenericinflaterinflategenericinflaterjava263eandroidruntime 2755 at androidpreferencepreferencemanagerinflatefromresourcepreferencemanagerjava251eandroidruntime 2755 at androidpreferencepreferenceactivityaddpreferencesfromresourcepreferenceactivityjava262eandroidruntime 2755 at orgjeremyandroidpreferencesactivityoncreatepreferencesactivityjava40eandroidruntime 2755 at androidappinstrumentationcallactivityoncreateinstrumentationjava1047eandroidruntime 2755 at androidappactivitythreadperformlaunchactivityactivitythreadjava1611eandroidruntime 2755 11 moreeandroidruntime 2755 caused by javalanginstantiationexception androidpreferencedialogpreferenceeandroidruntime 2755 at javalangreflectconstructorconstructnativenative methodeandroidruntime 2755 at javalangreflectconstructornewinstanceconstructorjava415eandroidruntime 2755 at androidpreferencegenericinflatercreateitemgenericinflaterjava383eandroidruntime 2755 22 morewactivitymanager 61 force finishing activity orgjeremyandroidpreferencesactivitywactivitymanager 61 force finishing activity orgjeremyandroidsplashactivity,['android'] +133632,numpy converting array from float to strings i have an array of floats that i have normalised to one ie the largest number in the array is 1 and i wanted to use it as colour indices for a graph in using matplotlib to use grayscale this requires using strings between 0 and 1 so i wanted to convert the array of floats to an array of strings i was attempting to do this by using astypestr but this appears to create some values that are not the same or even close to the originalsi notice this because matplotlib complains about finding the number 8 in the array which is odd as it was normalised to onein short i have an array phis of float64 such thatnumpywherephisastypestrastypefloat64 phisis non empty this is puzzling as hopefully naively it appears to be a bug in numpy is there anything that i could have done wrong to cause thisedit after investigation this appears to be due to the way the string function handles high precision floats using a vectorized tostring function as from robbles answer this is also the case however if the lambda function islambda x 2f xthen the graphing works curiouser and curiouser obviously the arrays are no longer equal however,['python'] +133635,creating testable wcf service without operationcontext i have implemented a subscribepublish for my own enjoyment wcf service which works reasonably well like all blogs and books i have seen they all use operationcontext to get the clients callback address after a bit of reading due to many people saying not to use operationcontext i found myself not being able to create proper unit tests yet i have not been able to find an alternative i suppose the subscribe method could accept a parameter for it to provide its own address i could see the code being testable from an intergration test stand point of view but not for unit testing since operationcontext would always be nullhow do i get the clients endpoint when they subscribe to my service without using operationcontextlittle bit of an aside but where is a good wcf resource with testing in mind when showing code samples there are tons of blogs out there reiterating the same code without providing sample test casesthank you,['c#'] +133636,fork same memory addresses this is about c in linuxi have fork in main where i create 2 child processes then in both child process a run the function abc where there is a local variable x i write some value in it then i print the address of this variable with printfpx both processes print same address i thought every child gets a independent copy of parents memory i need every process to have its own variable x how can i do that or am i doing something wrong,['c'] +133650,pyinstaller but keeping py files upgradeable i have managed to package my pyqt4 app as a standalone application on windows it workshowever this application can upgrade itself which is done by replacing the actual code written by me py files with new versions downloaded via the internethow can i tell pyinstaller do its job putting together the dlls generating the launcher with the shiny icon etc but let the py files untouchedi need those files directly on thisk in order for the autoupdate to work,['python'] +133655,webview in a dialog loading assets and not laid out i am on android 22 and i am creating a dialog with a webview inside itoverrideprotected dialog oncreatedialogint id dialog dialog new dialogthis dialogsetcontentviewrlayoutdialoghelp webview v webviewdialogfindviewbyidridhelpwebview vloadurlfileandroid assethelphtml return dialogit is working but the first time i open the dialog the webview is not laid out even if the content is actually loadedi know this because with hierarchyviewer i can see the contents and forcing a layout request i get to see them in the emulator too also if i just cancel the dialog and reopen it everything workswhos wrong android or me i tried putting the loading in onpreparedialog but it is the sameediti changed webviews layout params from fill parent to wrap content and this way it works i can see it opening with a 0 height then after the loading it grows up the width worked even before,['android'] +133703,android drawing an animated line i am currently working with graphics and paths and i can successufully thisplay whatever i wantbut instead of drawing a line directly on my surfaceview i would like to draw it progressively in an animationwhat i have done so far is to create a path and then to use pathmeasure to retrieve the coordinates progressively along the path here is basically what i have done so farpathmeasure pm new pathmeasuremypath false float position 0 float end pmgetlength float coord 0 while position end matrix m new matrix put the current path position coordinates into the matrix pmgetmatrixposition m pathmeasureposition matrix flag pathmeasuretangent matrix flag put the matrix data into the coord array coord2 x and coord5 y mgetvaluescoord position 1 the question marks is where i am stuck i want to draw the path progressively and see it animated on the screen i could not find much info about it on the internet so any clue would be much appreciated if you have already come across the same situation the final effect i want to create is like a pencil drawing progressively a text automatically,['android'] +133708,php header excel and utf8 ob startecho dasaa uiheadercontenttype applicationvndmsexcel charsetutf8headercontenttype applicationxmsexcel charsetutf8headercontentthisposition attachment filenametestxls headerexpires 0headercachecontrol mustrevalidate postcheck0 precheck0headercachecontrol privatefalse ob end flushwhat i am getting in the excel file is daasa uihowever i do get dasaa ui when i tryob startecho dasaa uiheadercontenttype texthtml charsetutf8ob end flushany help expertsps the file is saved in dw with titleencoding unicodeutf8,['php'] +133727,c calling native c all functions what types to use i want to make a native c all that can be used from a c project if i want to pass a string from c to the function in the c all what parameter should i usei know that c strings use unicode so i tried wchar t for the function but it did not work i tried catching any exceptions raised from the called function but no exception was throwni also want to return a string so i can test itthe c function is the followingdecldir wchar t settextwchar t alltext return alltextthe c code is the followingdllimportfirstdlldll callingconvention callingconventioncdecl charset charsetauto public static extern string settextstring alltextvar alltext new stringc4try var str1 settextalltextcatch exception ex var str2 exmessagewhat type should i use for the c functions return type so that i can call it from c with a return type of stringthe same q but for the parameter of the function to be string in c,"['c#', '.net', 'c++']" +133731,how to design a proper android app tips and tricks this topic is perhaps more related to designers and who makes graphic design for android devicesfor some reasons i have not found on internet any proper tutorial or explanation on how to design a proper application such as the twitter application dropbox application etcthere are many talks only about development but no tips about how to find the best and comfortable ways to design for many screen sizes resolutions and densities as far as i see android has many ratios relations for width and heightdesigners how do you design the best layout for graphic elementshow are you testing your design eclipse or other toolsis there on internet any android design communityare there any ui touchsmartphone specific tips if in addition to your answers you have any tips and suggestion please share it hereplease share whatever you cani and other designers who just steeped in this area will much appreciate your help,['android'] +133734,mixing php variable with string literal does anyone know a more efficient way of doing thissay i have a variable test and it is defined as test cheesei want to output cheesey which i can do like thisecho test ybut i would prefer to simplify the code to something more like this which of course wouldnt workecho testythis example is trivial but sometimes i want to add a string directly after a variable which i have enclosed in quotes for example when building a mysql query and wondered if there was a way to have the y be treated as though it were separate from the variable without needing to separate itthe following example works which reads better in the echo statement but is not what i wanttest cheesey yecho testy,['php'] +133745,gridview scrolling problem on android this must be somethng very simple i am overlooking but i have the following problem the post is rather lengthy but i want to provide as much info as possible i have a gridview in my android application where each cell holds custom viewxml version10 encodingutf8relativelayout xmlnsandroid androidorientationvertical androidlayout widthfill parent androidlayout heightfill parent gridview androidid idphotosgridview androidlayout widthfill parent androidlayout heightfill parent androidclickabletrue androiddrawselectorontoptrue androidfocusabletrue androidfocusableintouchmodetrue androidnumcolumns6 androidcolumnwidth90dp androidverticalspacing5dp androidhorizontalspacing5dp androidstretchmodecolumnwidth gridviewrelativelayoutand each cell isxml version10 encodingutf8commyappwidgetsimagethumbview xmlnsandroid androidlayout widthwrap content androidlayout heightwrap content androidbackground androidcolortransparent androidpaddingleft 1dip androidpaddingright 1dip androidpaddingtop 2dip androidpaddingbottom 2dip imageview androidididthumbimage androidlayout widthfill parent androidlayout height fill parent androidsrcdrawableicon small relativelayout androidlayout widthfill parent androidlayout height fill parent androidbackground androidcolortransparent imageview androidididiconright androidlayout width40px androidlayout height 40px androidsrcdrawablealbum check androidvisibilitygone androidlayout alignparenttop true androidlayout alignparentright true imageview androidididiconleft androidsrcdrawablealbum check androidvisibilitygone androidlayout width 40px androidlayout height40px androidlayout alignparenttop true androidlayout alignparentleft true relativelayoutcommyappwidgetsimagethumbviewmy adapter looks like thispublic class imageadapter extends baseadapter private liststring mpictures null public imageadapterliststring pictures mpictures pictures public int getcount return mpictures null mpicturessize 0 public object getitemint position return mpictures null mpicturesgetposition null public long getitemidint position return mpictures null position 1 override public view getviewint positionview convertviewviewgroup parent imagethumbview i null try threadsleep100 if convertview null string path mpicturesgetposition logdintegerpositiontostring path i addsingleview li path textview idx textview ifindviewbyidridcaption if idx null idxsettextintegerpositiontostring else logdintegerpositiontostring already not null i imagethumbview convertview these 2 lines were added only in desperate attempt to get it working but it makes no difference string path mpicturesgetposition iupdateviewpath catchinterruptedexception ie ieprintstacktrace return i so initially it works properly ie it shows first 18 images and few pixels from the next row but when i start scrolling the gridvew the images start to appear at random ie after the last image i see few from the beginning and so on out of curiosity i have tried few samples like this one and see the same resultso am i doing something wrong why on earth would gridview thisplay more items than it is supposed to do and why do items appear at the wrong positionsbralex,['android'] +133747,how can i add a checkboxradio botton to qtablewidget how can i add a checkboxradiobuttoncombobox to a qtablewidget or a qlistwidgetis there some tutorial i could read,['c++'] +133748,will a key in sql still stay a key in a view let us say i have a mysql table called fish with fields a b and ci run select from fish this gets me a view with all fields so if a was a key in the original table is it also a key in the view meaning if i have a table fish2 and i ran select from select from fish d select from fish2 e where da eawill the relevant fields still be keysnow let us take this 1 step further if i run select from select concatab as duck c from fish d select concatab as duck2 c from fish2 e where dduck educk2if a and b were keys in the original tables will their concatenation also be a keythanks,"['mysql', 'sql']" +133767,bool to int conversion how portable is this conversion can i be sure that both assertions passint x 45assertx1x 45assertx0do not ask why i know that it is ugly thank you,"['c++', 'c']" +133780,eclipse cdt buildrun on file basis in my scenario i have a c project in cdt eclipse this projects however is rather a collection of individual helper programs than one complex application consequently i want to be able to build and run them individually my project structure is very simple and looks likesrcapp1cppsrcapp2cppsrcnote that i do not have common header files or libraries however i want to be able to add programs to this project just by creating eg srcappxcppideally i want to have shortcuts for build currently opened cpprun binary of currently opened cpp any suggestions on how to achieve this behaviour if possible without additional plugins,['c++'] +133784,what benefits does maven give over ant for building android projects i have recently been trying to setup maven for building my android projects using the mavenandroidpluginwhilst this is a good exercise i am not convinced that the benefits will outweigh the frustration in getting it workingcan anyone give me some proscons on using maven for android i am not looking for subjective answers but the facts on whether its worth the effortregards,['android'] +133788,should google analytics go in the head or bottom of an html page google advises putting the google analytics script right before closing the headhowever i would prefer to combine it with the rest my javascript that are now all together in a cached external file which is loaded at the bottom of my html file can i do it my way if so what am i risking thenwhats the cost of putting the below code not in the head but at the bottom of the htmlscript typetextjavascript var gaq gaq gaqpush setaccount ua221803651 gaqpush setdomainname none gaqpush setallowlinker true gaqpush trackpageview function var ga documentcreateelementscript gatype textjavascript gaasync true gasrc https documentlocationprotocol httpsl httpw googleanalyticscomgajs var s documentgetelementsbytagnamescript0 sparentnodeinsertbeforega s script,"['javascript', 'html']" +133793,cakephp validation problem delimiter must not be alphanumeric or backslash solution foundi misspelled nonempty nothing to see here move alongi am just starting on cakephp and i came across this problemwarning 2 preg match functionpregmatch delimiter must not be alphanumeric or backslash corecakelibsmodelmodelphp line 2611i get that when i try and addedit a post it is getting triggered by this validation codevar validate array title array title not blank array rule nonempty message this post is missing a title title unique array rule isunique message a post with this title already exists body array body not blank array rule notempty message post is missing its body i have no idea what to do any help,['php'] +133814,rails simple form hidden field create how can you have a hidden field with simple formthe following code simple form for movie do f fhidden title some value fbutton submitresults in this errorundefined method hidden for simpleformformbuilder0x01042b7cd0,['ruby-on-rails'] +133828,android creating a simple thread that will updated my seconds counter basically i am trying to run a seconds counter and a levels counter for every 10 seconds i want to levelbut that is not implemented as yet so far i am just trying to get the seconds to thisplay but i am getting runtime exceptions and a crashgoogling i see that its because i am trying to update the ui from my thread and thats not allowed so i guess i am going to need asynctask but i have no idea how to do that with my simple little program please help or give me some alternativespackage comryan1import androidappactivityimport androidosbundleimport androidutillogimport androidwidgettextviewpublic class main extends activity int level 1int seconds running0textview the secondsoverridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain the seconds textview findviewbyidridtextview seconds thread thread1 new thread public void run try sleep10 logdryan ryan updated secs catch exception e eprintstacktrace logdryan e thread1startpublic void updated secs seconds running the secondssettext seconds running,['android'] +133834,automated paypal payments i am looking for a way to automatically send money from my paypal account to other paypal accounts via php is this possiblesomething likerecievers array myaccount mypassword letmeinamounttopay 200 20 usdforeachrecievers as payee sendmoneymyaccount mypassword payee amounttopay is this possible,['php'] +133843,click event on dynamic element without jquery i would like add an event such as onclick or mouseover to a dynamically created element similar to the live function in jqueryhow do i do this using pure javascript without a framework such as jquery here is a simple jsfiddle i would like to be able to do this from the newly created divs class instead of an idany help would be greatly appreciated,['javascript'] +133845,python force nonrelative import i wanted to make a module called utilsdjangopy in my project on the top i have the linefrom djangodb import modelshowever it tries to import from itself and that causes an error i know i can force a relative import with a prepended from djangodb import modelsis there any way to force a nonrelative import,['python'] +133846,c constant objects to use as default parameters is there any way to create a constant objectie it cannot be edited and is created at compile timei am just playing with the c language and noticed the optional parameter feature and thought it might be neat to be able to use a default object as an optional parameter consider the followingthis class has default settingsprivate const settingsclass defaultsettings new settingsclass public void dosomethingsettingsclass settings defaultsettingsthis obviously does not compile but is an example of what i would like to dowould it be possible to create a constant object like this and use it as the default for an optional parameter,['c#'] +133848,c pointer to a reference is it legal to have a pointer of a reference in c for exampleint ref arrayidxfuncrefone reason i can think of why you might want to do this if func already exists in a library which you cannot change,['c++'] +133869,whereargs sqlite database delete i am trying to remove a couple of rows in a sqlite database programmatically for android and am wondering what the whereargs are referring to in this documentation javalangstring20javalangstring20javalangstringcan someone give me an example,['android'] +133870,why does setting lineheight for one of two inlineblock sibling divs effect both divs i have the followingdiv div stylethisplayinlineblock div 1div div stylethisplayinlineblock lineheight20pxdiv 2divdivwhy does having a lineheight property set for the second div also effects the first div and how to correct for this i only need the second div to be effected by lineheight because i need to specify a different lineheight for the first div thanks in advanceupdate check jsfiddle,"['html', 'css']" +133873,json serializing an object with function parameter i have this c objectvar obj new username andrey callback functionself return function selfdosomething this i need to json serialize it to pass to the browser in ajax call i use javascriptserializer but it serializes to the following jsonusernameandrey callback functionself return function selfdosomething this but what i need isusernameandrey callback functionself return function selfdosomething this no quotes around function definitionright now when the json object gets to the browser and is created the callback parameter is not a function but a string any idea how to fix it preferably on the server side,['c#'] +133880,how to catch this error notice undefined offset 0 i want to catch this errora1 jfksjfkstry b a0 catch exception e echo jsdlkjflsjfkjledit in fact i got this error on the following lineparse xmlchildren0children0toarray,['php'] +133884,how to check network connection enable or thisable in wifi and 3gdata plan in mobile i am developing an android applicationin my applicationi want to check network connectionlike i want to check network connection in wifi and 3glike indians mostly like data plan in mobilehow to check network in wifi and 3gnaybody knowsplease give some idea about thatthanks,['android'] +133885,why does the default aspnet forms authentication cookie have a leading period in it is default name aspxauth the default aspnet forms authentication cookie sets it is name as aspxauth notice the first character is a period is there a particular reason for this like does this have an impact on domain names or subdomains for the target domainor is it purely some random thing an ms dev person came up with maybe to help out the ordering of the cookies when they were debugging or something as text with periods prolly get listed before other strings,"['.net', 'asp.net']" +133925,how do i stop tornado web server i have been playing around a bit with the tornado web server and have come to a point where i want to stop the web server for example during unit testing the following simple example exists on the tornado web pageimport tornadoioloopimport tornadowebclass mainhandlertornadowebrequesthandler def getself selfwritehello worldapplication tornadowebapplication r mainhandlerif name main applicationlisten8 tornadoioloopioloopinstancestartonce tornadoioloopioloopinstancestart is called it blocks the program or current thread reading the source code for the ioloop object gives this example in the documentation for the stop functionto use asynchronous methods from otherwisesynchronous code such asunit tests you can start and stop the event loop like this ioloop ioloop async methodioloopioloop callbackioloopstop ioloopstartioloopstart will return after async method has run its callbackwhether that callback was invoked before or after ioloopstarthowever i have no idea how to integrate this into my program i actually have a class that encapsulates the web server having it is own start and stop functions but as soon as i call start the program or tests will of course block anywayi have tried to start the web server in another process using the multiprocessing package this is the class that is wrapping the web serverclass server def init self port8 selfapplication tornadowebapplication r handler def server threadapplication port http server tornadohttpserverhttpserverapplication http serverlistenport tornadoioloopioloopinstancestart selfprocess processtargetserver thread argsselfapplication port def startself selfprocestart def stopself ioloop tornadoioloopioloopinstance ioloopadd callbackioloopstophowever stop does not seem to entirely stop the web server since it is still running in the next test even with this test setupdef setup methodself function selfserver server selfserverstart timesleep05 wait for web server to startdef teardown methodself function selfkstorestop timesleep05how can i start and stop a tornado web server from within a python program,['python'] +133930,uitextview ruled line background but wrong line height i have a uitextview where the user can create notes and save into a plist filei want to be able to show lines just like a normal notebook the problem i have isthat the text would not align properlythe image below explains the problem quite wellthis is the background i use to create the lines like the notesappthis is my code for creating the background for my uitextviewtextviewfont uifont fontwithnamemarkerfeltthin size190 textviewbackgroundcolor uicolor colorwithpatternimage uiimage imagenamed notespngi know that the uifontlineheight property is only available in ios 4xso i wonder if there is another solution to my problem,"['iphone', 'objective-c']" +133961,android finish activity context if i have reference to context is it possible to finish the current activity i do not have the reference to current activity,['android'] +133966,how to get string from selected item of simplecursoradapter i am using an autocompletetextview to suggest user some words from my sqlite db as they type the input string to searchi try to make the suggestion look friendly by using simple list item 2 heres my codepackage comsuitkamusimport androidappactivityimport androiddatabasecursorimport androiddatabasematrixcursorimport androidosbundleimport androidtexteditableimport androidtexttextwatcherimport androidutillogimport androidviewviewimport androidviewviewonclicklistenerimport androidwidgetadapterviewimport androidwidgetarrayadapterimport androidwidgetautocompletetextviewimport androidwidgetbuttonimport androidwidgetsimplecursoradapterimport androidwidgetspinnerimport androidwidgettextviewimport androidwidgetadapterviewonitemclicklistenerpublic class suitauto extends activity implements textwatcherautocompletetextview auto textview resultbutton search button add spinner chooserstring input static string selection string mainstring options en to ina ina to ensimplecursoradapter simple called when the activity is first created overridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain auto autocompletetextviewfindviewbyidridauto autoaddtextchangedlistenerthis result textviewfindviewbyidridresult chooser spinnerfindviewbyidridchooser arrayadapterstring adapter new arrayadapterstringthisandroidrlayoutsimple spinner item options adaptersetdropdownviewresourceandroidrlayoutsimple spinner dropdown item choosersetadapteradapter kamusdbadapter dbhelper new kamusdbadaptergetapplicationcontext dbhelperopen string status dbhelpergetstatedb selection status dbhelperclose if selectionequalsignorecaseen choosersetselection0 else choosersetselection1 logdstatelang selection add buttonfindviewbyidridadd addsetonclicklistenernew onclicklistener override public void onclickview v todo autogenerated method stub startaddingmain choosersetonitemselectedlistenernew adapterviewonitemselectedlistener public void onitemselectedadapterview arg0 view arg1 int arg2 long arg3 todo autogenerated method stub if choosergetselecteditemid 0 selection en select updatedb else selection ina select updatedb public void onnothingselectedadapterview arg0 todo autogenerated method stub autosetonitemclicklistenernew onitemclicklistener override public void onitemclickadapterview arg0 view arg1 int arg2 long arg3 todo autogenerated method stub main autogettexttostring logvcursorfinish resultsettext autosettext public void startaddingstring dword todo autogenerated method stub kamusdbadapter adding new kamusdbadaptergetapplicationcontext addingopen addingfavoritedword addingcloseprotected void updatedb todo autogenerated method stub kamusdbadapter save new kamusdbadaptergetapplicationcontext saveopen saveupdatestatedbselection saveclosepublic static string select todo autogenerated method stub logvstringselection return selectionoverridepublic void aftertextchangededitable arg0 todo autogenerated method stuboverridepublic void beforetextchangedcharsequence arg0 int arg1 int arg2 int arg3 todo autogenerated method stuboverridepublic void ontextchangedcharsequence arg0 int arg1 int arg2 int arg3 todo autogenerated method stub input autogettexttostring kamusdbadapter x new kamusdbadaptergetapplicationcontext xopen cursor cur xgetcallinput selection getcall is in kamusdbadapter class it used to return result cursor from sqlite db i use rawquery select from en to ina where word like input xclose string thisplayfields new string word meaning int thisplayviews new int androidridtext1androidridtext2 simple new simplecursoradapterthis androidrlayoutsimple list item 2 curthisplayfields thisplayviews autosetadaptersimple i got a problem with retrieving the string from clicked item it is inautosetonitemclicklistenernew onitemclicklistener override public void onitemclickadapterview arg0 view arg1 int arg2 long arg3 todo autogenerated method stub main autogettexttostring logvcursorfinish resultsettext autosettext i need both strings from word and meaning fieldsany response would be great,['android'] +133968,protected in interfaces why are all methods in an interface definition implicitly public why does it not allow a protected method,['java'] +133971,c r interface i need to interface r to some c application i installed rscproxy 13 and r scilab dcom301b5 added com references to the statconnectorclntlib statconnectorcommonlib and statconnectorsrvlib but i still cannot get it working when i run following test program using systemusing systemcollectionsgenericusing systemlinqusing systemtextcom referencesusing statconnectorclntlibusing statconnectorcommonlibusing statconnectorsrvlibnamespace r testing class program static void mainstring args statconnector sc1 new statconnectorsrvlibstatconnectorclass sc1initr i get this exceptionunhandled exception systemruntimeinteropservicescomexception exception from hresult 0x80040013 at statconnectorsrvlibstatconnectorclassinitstring bstrconnectornamethanks in advanceupdateok still no lucki will try to explain what i did so farinstalled r2122winexe from rproject to the cprogram filesrr2122downloaded rscproxy 131zip and copypasted it to the cprogram filesrr2122libraryinstalled r scilab dcom301b5exe to the cprogram files x86rdcom serverwith scilab comes a basic test i tried to run it but i got following errorloading statconnector server done initializing rfunction call failed code 2147221485 text installation problem unable to load connector releasing statconnector serverdonethan i looked in the pathsystem variables and found no pathr homer user info also i could not find anything r related in the registry i guess i am doing something terribly wrong so i desperately need help from you guys,['c#'] +133979,how can i rotate thisplay only in landscape mode in android i want that my view rotates only in landscape mode clockwise and counterclockwisei read about the only counterclockwise for android 22 and that is not a problem my app will be 22 for nowi modify my manifest to catch configuration changesandroidconfigchangeskeyboardhiddenorientationi override my activity to catch configuration changesoverridepublic void onconfigurationchangedconfiguration newconfig and i know how to catch orientationthisplay thisplay windowmanager getsystemservicewindow servicegetdefaultthisplayint rot thisplaygetrotationbut i do not know how to trigger the appropiate landscape orientation i am doing thisif rot surfacerotation 90 rot surfacerotation 270 setrequestedorientationactivityinfoscreen orientation landscapebut always rotate to counterclocwise how can i set left and right landscape orientationeditif i set orientation in manifestandroidscreenorientationlandscapethe activitys layout remains always in left landscape and i want change between left and right landscape s,['android'] +134015,using raphael js fill an svg element with with a backgroundimage with an offset i want to this this fill svg element with with a backgroundimage with an offset but using raphael jsthisplaying an rectangle with a background image without the offset is easycanvasrect positionx positiony width heightattr fill urlcontentimage setgifthe code above will thisplay only the upperleft corner of the image i want to shift it and thisplay another part of it how can i do it,['html'] +134035,get the highlightedselected text is it possible to get the highlighted text in a paragraph of a website eg by using jquery,"['javascript', 'jquery']" +134038,how to trigger bind custom events in backbonejs views i have a backbone view that uses iscroll to implement a slideshow iscroll publishes an onscrollend event but i cannot seem to bindsubscribe to it inside the viewappviewsscroller backboneviewextend events onscrollend scrollend initialize function var self this thisscroller new iscrollcontentscroller onscrollend function selftriggeronscrollend scrollend functione never called consoleloge,['javascript'] +134052,using reflection to call a method of a property what i am trying to do is call the method of a property using reflection i have the original control a combobox the propertyinfo of the property comboboxitems and the name of the method comboboxitemsadd i have tried the code below to get alter set but it does not work because items does not have a setter propertyinfo p controltypegetpropertypropertyname gets the property itemsmethodinfo m ppropertytypegetmethodmethodname gets the method itemsaddobject o pgetvaluenewcontrol null gets the current itemsminvokeo new object newvalue invokes add which workspsetvaluenewcontrol o null exception items has no setterdoes anyone have any advicethanks,"['c#', '.net']" +134057,changing project build configuration to debug mode i am using vs 2008 i am getting a popup everytime i run my applicationfollowing is the popupthe following module was built with optimizations enabled or without debug information cwindowsmicrosoftnetframeworkv2050727temporary aspnet filesroot7c06d97fc871fca3assemblydl31ed1f33500d7b454 9450ca01barcodingimagingdllto debug this module change its project build configuration to debug mode to suppress this message thisable the warn inf no user code on launch debugger optioni have tried all the links available on the google to get rid of this error but nothing works actually most of the links are for vs 2005 but i am using vs 2008i used following referenceand one on code guru,['.net'] +134067,generating unique codes that are different in two digits i want to generate unique code numbers composed of 7 digits exactly the code number is generated randomly and saved in mysql tablei have another requirement all generated codes should differ in at least two digits this is useful to prevent errors while typing the user code hopefully it will prevent referring to another user code while doing some operations as it is more unlikely to miss two digits and match another existing user codethe generate algorithm works simply likeretrieve all previous codes if any from mysql tablegenerate one code at a timesubtract the generated code with all previous codescheck the number of nonzero digits in the subtraction resultif it is 1 accept the generated code and add it to previous codesotherwise jump to 2repeat steps from 2 to 6 for the number of requested codessave the generated codes in the db tablethe algorithm works fine but the problem is related to performance it takes a very long to finish generating the codes when requesting to generate a large number of codes like 10the question is there any way to improve the performance of this algorithmi am using perl mysql on ubuntu server if that matters,['mysql'] +134073,rails checkbox ajax call do not want to render anything i have got a little demo setup in which clicking a checkbox toggles an attribute via ajax it is working fine but rails really wants to render something so i have basically resorted to creating a blank togglejserb file in my viewscontroller action in questiondef toggle task taskfindparamsid respond to do format formatjs do if taskstatus true taskstatus true else taskstatus false end tasksave render layout false end endendview in question h1tasksh1 ul styleliststyletype none taskseach do task li id dom idtask check box tagdom idtask value nil checked taskstatus taskaction link to edit edit task pathtask link to delete task confirm are you sure method delete remote true li end ul link to new task new task path script inputeachfunctionel elobserveclick functionevent get the task id var elid elidsplit 1 build the toggle action path var togglepath tasks elid toggle create request thisable checkbox send request enable checkbox on completion new ajaxrequesttogglepath oncreate function elthisable onsuccess functionresponse oncomplete function elenable scriptwithout the blank togglejserb file i have got in the views rails still gives me an error saying that it is trying to render somethingultimately i would like to both not have to have a blank togglejserb file and i would like to get that prototype stuff into my static javascript stuff and out of the viewi am pretty new to rails so there is probably an easier way to be doing this but i am kind of stuck here,['ruby-on-rails'] +134078,how to get the cutset using the edmondsakarp algorithm i implemented the edmondsakarp algorithm using the pseudocode that i found in the edmondsakarp algorithm wiki page algorithmit works great yet the algorithm output is the max flow valuemin cut value i need to the list of edges that this cut containsi tried to change the algorithm with no success can you guys helpthank you,['java'] +134090,replacing extreg xtype in extjs4 i want to use the multiselect from 33 in ext js 4 as described in this previous questionwhy are the ext js multiselect item selector files not included in the ext js 33 download and where are theyit seems like the way to register xtypes has changed in ext js 4 when i try to import this widgetalong with itemselectorjs i get an error on extregextregmultiselect extuxformmultiselectbackwards compatextuxmultiselect extuxformmultiselecthow do i change wdigets to get them to work in ext js 4,['javascript'] +134109,wpf datagrid row strikethrough i am using wpf datagrid i want to strikethrough conditionally just like my below code works for italics i want to replace italics with strikethrough propertytextblocktextdecorations valuestrikethrough does not help i have 5 textcolumns and 1 templatecolumn in the datagrid style xkeyabcrowstyle targettypextype datagridrow styletriggers datatrigger bindingbinding isactive valuefalse setter propertyfontstyle valueitalic datatrigger styletriggers style,['.net'] +134132,when inserting an entity with associations is there a way to just use the fk instead of retrieving the entity i need to insert an entity which has associationsif i already have the fks of the associated entities is there a way to insert the primary entity into the db with just the fks populatedor do i always have toretrieve the associated entities via the fks populate the primary entitys properties referring to the assocations and then invoke the persist method,['php'] +134144,how to add a line break in an android textview i am trying to add a line break in the textviewi tried suggested and but that does nothing here is how i set my textstextview txtsubtitle textviewfindviewbyidridtxtsubtitletxtsubtitlesettexthtmlfromhtmlgetresourcesgetstringrstringsample stringthis is my string string namesample stringsome test line 1 and some test line 2stringit should show like sosome test line 1some test line 2but it shows like so some test line 1 some test line 2am i missing something,['android'] +134146,rails plugin for appointment scheduling hi i have a requirement in which the person a can see a calendar of person b and check what time is the person b available on a particular day and book an appointment by clicking on the available slotsomething likemonday 21st march9am10 am not available10 11 available11 12 available12 1 not availablei tried event calendar plugin but it gives date only and not the time slots for each dayare there any plugin present for railsthanks,['ruby-on-rails'] +134158,broken pipe when socket is closed i have a serverclient app on a linux box if the server is not up when the client attempts to send a request i get a sigpipe and the application terminateshow can i check if the server is available on the socket before i try to writealso of note i do not want to trap the sigpipe because the client is really part of a shared object that is used by many applications that may or may not already define their own signal handling methodsthanks,['c++'] +134161,how can i calculate divide and modulo for integers how can i calculate division and modulo for integer numbers in c,['c#'] +134163,ios 43 uinavigationbar tintcolor leaks in ios43 if i set navigationbartintcolor uicolor colorwithred00 green00 blue00 alpha1i will get a memory leak uidevicergbcolor leakbut if i use navigationbartintcolor uicolor blackcoloreverything is finethis never happened in ios42i did some debug and i found the navigationbartintcolor retaincount seems bigger if i use uicolor colorwithred00 green00 blue00 alpha1does anyone have the same issuethis is the leak codein rootviewcontroller voidviewwillappearboolanimated selfnavigationcontrollernavigationbartintcolor uicolor colorwithred0 green0 blue0 alpha0 super viewwillappearanimated in detailviewcontroller voidviewwillappearboolanimated selfnavigationcontrollernavigationbartintcolor uicolor colorwithred09 green0 blue0 alpha0 super viewwillappearanimated if you go to detailviewcontroller then popback to rootviewcontroller in the instruments you can see the uidevicergbcolor leak,"['iphone', 'objective-c']" +134169,view php session variables not sure if this belongs here or at webapps please move if appropriatei do not even know if such a thing is possible but is there an extension or addon for either firefox or chrome that would let me view all my php session variables the way there are extensions that let you view cookies,['php'] +134172,catch an exception thrown by an async method using the async ctp from microsoft for netis it possible to catch an exception thrown by an async method in the calling methodpublic async void foo var x await dosomethingasync handle the result but sometimes an exception might be thrown for example dosomethingasync gets data from the network and the data is invalid a protocolexception might be thrown public void dofoo try foo catch protocolexception ex the exception will never be caught instead when in debug mode vs2010 will warn and continue when deployed the app will simply crash so basically i want the exception from the async code to bubble up in to my calling codeif that is even possible at all,['c#'] +134178,why use decimalmultiply vs operator multiply decimal result 100 200vsdecimal result decimalmultiply100 200,['c#'] +134199,whats the shortest way to count the number of items in a generatoriterator if i want the number of items in an iterable without caring about the elements themselves what would be the pythonic way to get that right now i would definedef ilenit return sumitertoolsimaplambda 1 it or just map in python 3but i understand lambda is close to being considered harmful and lambda 1 certainly is not prettythe use case of this is counting the number of lines in a text file matching a regex ie grep c,['python'] +134223,planning on writing operating system in objectivec at the moment i am learning objective c 20 and soon i plan on learning assembly language so i can write an operating system i know it would not be easy and i know it will take months perhaps years of time and patience however i plan on writing most of it in objectivecexcluding the stuff you have to write in assembly because not only do i know objectivec better than i know c i barely know any c but i personally also like objectivec a lot better is this possible if not how much c do i need to know should i get a great understanding of c through a book or just learn the basics online,['c'] +134224,iphone downloading zip and extracting in main bundle subdirectory at runtime i want to extend my iphone app that the app downloads a zip file into a sub directory then extracts it and then load images which were inside the zipany ideas how to unzip in runtime and the access the images would be really happy for some ideagreetings,"['iphone', 'ios']" +134249,sealing an interface after implementing it i am working on a small project and i came across that problemthe project output is a library containing an interface i would like to implement that interface and seal the functions in it like this if possiblepublic interface itest void somemethodclass a itest public sealed override somemethod the idea is to have the interface available to everyone and have some specialized class that implements it the exception is that i want to make sure that if someone create a specialized class of type a heshe would not be able to change the methods behaviorthe problem is you cannot put the override keyword in there since the method is not declared as virtual in the interface and you cannot declare it as virtual in the interface since it is not allowed and you cannot remove the override keyword since it is needed by sealedany workaround or brainstorming idea would be welcome but if someone can come up with a solution that includes an interface i would be really happy to learn itthanksedit forget this question like ani said i forgot that by default method in c are sealed seems like it is always good to go back to the basics once in a while,['c#'] +134252,how to thisplay alt text for an image in chrome the image with invalid source thisplays an alternate text in firefox but not in chrome unless the width of an image is adjusted img height90 width90 src allimageslogosimages logo lggif altimage not foundhow to thisplay the alt text for an image,['html'] +134269,segfault on ia64 but not on ia32 i cannot access my original account moderators are requested to merge the accounts if possiblehere is my questionthe following c program segfaults of ia64 but works fine on ia32int main int p p intmallocsizeofint p 10 return 0 why does it happen so,['c'] +134299,measuring the number of queued requests for tomcat so with tomcat you can set the acceptcount value default is 100 which means when all the worker threads are busy new connections are placed in a queue until it is full after which they are rejected what i would like is to monitor the size of items in this queue but cannot work out if there is a way to get at this via jmx ie not what the queue max size is that is just config but what the current number of items are in the queue any ideas appreciatedconfig for tomcat search for acceptcount,['java'] +134326,what is a java strings default initial value consider a java string field named xwhat will be the initial value of x when an object is created for the class xi know that for int variables the default value is assigned as 0 as the instances are being created but what becomes of string,['java'] +134355,how to add a stackpanel in a button in c code behind how to add a stackpanel in a button using c code behind ie convert the following xaml to c there is no buttonchildrenaddbutton stackpanel orientationhorizontal margin10 image sourcefoopng stackpanelbutton,['c#'] +134367,updating custom android app my customer wants the android app to update itself automatically whenever a change is made they do not want to publish the app in the android market for the first time the app will be installed using the android sdk or the numerous other ways to installhow do i ensure that the app is automatically upgraded whenever bug fixes or features are added if not automatically a button from the app is also okthanks,['android'] +134396,stemming english words with lucene i am processing some english texts in a java application and i need to stem themfor example from the text amenitiesamenity i need to get amenitthe function looks likestring stemtermstring term i have found the lucene analyzer but it looks way too complicated for what i need 2 0apiorgapacheluceneanalysisporterstemfilterhtmlis there a way to use it to stem words without building an analyzer i do not understand all the analyzer businessedit i actually need a stemming lemmatization can lucene do this,['java'] +134439,error reporting in zend framework am having trouble with reporting errors in zend framework errors messages are not thisplayed on the browser and i recive errors like thisan error occurred application errorhowever i already use those configuration in my applicationini filephpsettingsthisplay startup errors 1phpsettingsthisplay errors 1phpsettingstrack errors 1phpsettingserror reporting e allthanks in advance d,['php'] +134443,is there a good tutorial on cocoa touch automated ui testing typically i find that nearly all my most important test cases for iphone development revolve around ui testing rather than business logic or data testing i am not very familiar with automated ui testing in the xcode environment can someone point me to a good tutorial or bookupdatethis question was written several years ago and ui testing has come a long way since then using the ui automation is still an option but the kif framework is a much better solution for functional testing now imo from kifs github pagekif which stands for keep it functional is an ios integration test framework it allows for easy automation of ios apps by leveraging the accessibility attributes that the os makes available for those with visual thisabilitieskif builds and performs the tests using a standard xctest testing target testing is conducted synchronously in the main thread running the run loop to force the passage of time allowing for more complex logic and composition this also allows kif to take advantage of the xcode 5 test navigator command line build tools and bot test reports,"['ios', 'iphone']" +134446,iis 7 ignores mappageroute without file extentions i have a project where i want to use the aspnet routing function therefore i added some routes in my globalasax application startthis works fine on my windows 7 sp1 but when i deploy the application to my w2k8 r2 live server i only get 404s when using the urls if i add a defaultaspx at the end of the urls the pages get thisplayt correctlythe iis seems to ignore the urls without a file extensionworking on local server but 404 on live server httpwebsitelist123test working on both servers httpwebsitelist123testindexaspxhow can i get the live server to use the extension less urls,['asp.net'] +134447,override metadata in static constructor i have a class that inherits the textbox class call it mytextboxi would like to redefine the default background value for this claso i looked for a way to do so and found a good option call backgroundpropertyoverridemetadatatrouble is where can i put thisin the apponstartup ugly and not practical i would like that to be in my clas code filein the clas contructor i get an exception propertymetadata is already registered for the type mytextboxseems fine to me i understand why i get this perfectlyso i looked again a found about the static constructor in c did not no about that earlier what a pityso heres my codepublic class mytextbox textbox static mytextbox mytextboxbackgroundpropertyoverridemetadatatypeofmytextbox new frameworkpropertymetadataappcurrentresourcescustombackgroundbrush now i am pretty happy whith this but microsoft is not namely when i use the code analysis feature i get thisca1810 initialize reference type static fields inlinehence my question what can i do about itignore the warning i do not like to ignore warningsmove the call to the overridemetadata method i would like to but whereany hints welcome thanksedit i will add that i do not fully understand why i get this warning since i am not initializing anything per say in my static constructor or am i,"['c#', '.net']" +134461,thispatchertimer not firing tick event i have a thispatchertimer i have initialised like so static thispatchertimer timer new thispatchertimerstatic void main timerinterval new timespan0 0 5 timertick new eventhandler timer tick timerstartstatic void timer tickobject sender eventargs e do somethingthe timer tick event never gets fired have i missed something,['c#'] +134470,is it possible to do active mode ftp using ftpwebrequest due to some firewall issues we need to do ftp using active mode ie not by initiating a pasv commandcurrently were using code along the lines of get the object used to communicate with the serverftpwebrequest request ftpwebrequestwebrequestcreaterequestmethod webrequestmethodsftpuploadfile this example assumes the ftp site uses anonymous logonrequestcredentials new networkcredential anonymous copy the contents of the file to the request streamstreamreader sourcestream new streamreadertestfiletxtbyte filecontents encodingutf8getbytessourcestreamreadtoendsourcestreamcloserequestcontentlength filecontentslengthstream requeststream requestgetrequeststreamrequeststreamwritefilecontents 0 filecontentslengthrequeststreamcloseftpwebresponse response ftpwebresponserequestgetresponseresponseclosebut this seems to default to using passive mode can we influence this to force it to upload using active mode in the same way that the command line ftp client does,['c#'] +134486,are static classes shared among different threads in c i need to share a value between threads without exceeding it is boundary does a static variable do this,['c#'] +134493,can iphone app woken in background for significant location change do network activity i am working on an app that monitors significant location changes in the background i have been reading all the answers well i think all about ios4 and the application lifecycle but what i cannot figure out is whether or not i can do any network access when the app is woken up in the background as a result of a significant location changethe app currently does network access via tcp sockets the socket is shutdown when the app is suspendedcan i reconnect the socket receive some data send the new location and then shutdown the socket all while still in the background as a result of receiving the location change event it is hard to test while stationary in the office we can assume that the network activity takes less than 10 seconds to complete also assume the app is not registered as a voip app couldshould it be any ideas,['iphone'] +134496,are androids broadcastreceivers started in a new thread if i have an inner class that extends broadcastreceiver within my service class should i care about synchronization when the broadcastreceiver class readswrites to objects from the service classor to put it in another way are broadacstreceivers onreceive methods started in an extra thread,['android'] +134513,javascript reference a variable name from the variable itself i want to create a quick function that will consolelog a variable name and the value i would like the result of the function to show in the console foo barmy basic idea for the function looks like thisfunction varlogvar name consolelogvar name evalvar nameand i would call is thuslyfunction somerandomfunction var foo bar some stuff happens varlogfoothis works if foo is global but does not work in the example provided another option that also only works globally is using windowvar name instead of the scary eval i do not think what i am asking is possible but i figured i would throw it out therei am spending a lot of time attempting to be lazy my current method is just consolelogfoo bar which works just fine but now i just want to know if this is possiblesome other questions i referenced in searching for this creating what i have nowvariable name as a string in javascripthow to convert variable name to string in javascriptjavascript refer to a variable using a string containing its namehow to find javascript variable by its nameedit i would love to just call varlogfoo if the name foo can be derived from the variable,['javascript'] +134520,filter json render in rails 3 what is the best way if i would like to only return id and name fields in jsonso far i haveformatjson render json contactsmapattributes only idbut the name attribute does not work in the only section since it is not a column in the database it is defined in the model as firstname lastnamethanks,['ruby-on-rails'] +134531,is there a way to read standard input with javascript i saw this for lots of other languages but not javascripti am trying to do problems like this codechefcom and of course the programs need to be able to read standard in like c and other languages doedit thanks for the answers the primary reason i want this functionality is so i can answer the questions on codechef codechef sends multiple inputs to the filesprograms that are the answers and of course the programs have to respond in the required way for the answer to be correct,['javascript'] +134544,does entity framework use reflection and hurt performance i ultimately have two areas with a few questions each about entity framework but let me give a little background so you know what context i am asking for this information inat my place of work my team is planning a complete rewrite of our application structure so we can adhere to more modern standards this rewrite includes a completely new data layer project in this project most of the team wants to use entity framework i too would like to use it because i am very familiar with it from my using it in personal projects however one team member is opposed to this vehemently stating that entity framework uses reflection and kills performance his other argument is that ef uses generated sql that is far less efficient than stored procedures i am not so familiar with the innerworkings of ef and my searches have not turned up anything extremely usefulhere are my questions i have tried to make them as specific as possible if you need some clarification please askissue 1 questions reflectionis this true about ef using reflection and hurting performancewhere does ef use reflection if it doesare there any resources that compare performance something that i could use to objectively compare technologies for data access in net and then present it to my teamissue 2 questions sqlwhat are the implications of thisis it possible to use stored procedures to populate ef entitiesagain are there some resources that compare the generated queries with stored procedures and what the implications of using stored procedures to populate entities if you can would bei did some searching on my own but did not come up with too much about ef under the hood any help is much appreciatededitthese are all some very informative answers thank you i am going to leave this question unanswered for a while so that maybe some hard references to articles and other external resources can be provided maybe this question will help someone in the future in my predicament,"['c#', 'asp.net']" +134555,how do i convert special utf8 chars to their iso88591 equivalent using javascript i am making a javascript app which retrieves json files with jquery and injects data into the webpage it is embedded inthe json files are encoded with utf8 and contains accented chars like a a and athe problem is that i do not control the charset on the pages that are going to use the appsome will be using utf8 but others will be using the iso88591 charset this will of course garble the special chars from the json fileshow do i convert special utf8 chars to their iso88591 equivalent using javascript,"['javascript', 'jquery']" +134559,use net 20 dll in net 40 wpf application i am trying to add a reference to a net 20 dll in a wpf application that is targeted to the net 4 frameworki added startup uselegacyv2runtimeactivationpolicytrue to the appconfig file the wpf app builds fine but gets a badimageformatexception at runtime when trying to access the net 20 dllan attempt was made to load a program with an incorrect formatthis works with a new test wpf project but does not work on my app my app uses entity framework and mef could these technologies be causing the issueany ideasedit resolvedaccording to the comment by alois below i had my main app targeted to any cpu and the dll was targeted to 32bitstartup uselegacyv2runtimeactivationpolicytrue was not required,['c#'] +134572,animates callback function complete executed at start i am using jquery 151 this is my codecellcontentanimate left 190 easing alertstart ani duration 50 complete alertend anii get both alerts before the animation starts i want the complete function to start after the animation has ended any thoughts,['jquery'] +134597,mpmovieplayerviewcontroller protected url from yahoo hosted site using setdefaultcredential i am using similar code as mentioned in mpmovieplayerviewcontroller documentation but it is not working it says you are not authorized my server is hosted on yahoo url is something like thiscode is belownsurlcredential credential nsurlcredential alloc initwithuserabc passwordxyz persistence nsurlcredentialpersistencepermanent nsurlprotectionspace protectionspace nsurlprotectionspace alloc initwithhostwsomeurlcom port80 protocolhttp realmtmp authenticationmethodnsurlauthenticationmethoddefaultnsurlcredentialstorage sharedcredentialstorage setdefaultcredentialcredential forprotectionspaceprotectionspace protectionspace release credential release mpmovieplayerviewcontroller movie mpmovieplayerviewcontroller alloc initwithcontenturlurl autorelease,"['iphone', 'objective-c']" +134614,aspnet authentication using in webconfig i need to publish a demo website to the web i need to secure access to the sitethe live site with use sql server as the membership provider however for the demo site i can only publish to a simple web host and have no access to sql serveri need only a single user and they do not need option to change password etc therefore i thought easiest way to achieve this would be to use the member of within the webconfig i have created as followsxml version10configuration xmlns systemweb authentication modeforms forms nameprojectapple loginurlloginaspx credentials passwordformatclear user namelawyer passwordsuper12 credentials forms authentication compilation debugtrue systemwebconfigurationi will use sha1 hash when i can get this working problem is it recognises when i have entered an invalid password however when i enter the correct password i get the followingcannot open user default database login failedlogin failed for user rbt510rob description an unhandled exception occurred during the execution of the current web request please review the stack trace for more information about the error and where it originated in the code exception details systemdatasqlclientsqlexception cannot open user default database login failedlogin failed for user rbt510robi do not know why it is looking for sql can anyone help pleasei am using vs2010 and net 35many thanksrob,"['.net', 'asp.net']" +134621,general rules of passingreturning reference of array not pointer tofrom a function we can pass reference of an array to a function likevoid fint a5int x5fx okayint y6fy error type of y is not int 5or even better we can write a function templatetemplatesize t nvoid fint an n is size of the arrayint x5fx okay and becomes 5int y6fy okay and becomes 6now my question is how to return reference of an array from a functioni want to return array of folowing types from a functionint anint amnint anint amnwhere m and n is known at compile timewhat are general rules for passing and returning compiletime reference of an array to and from a function how can we pass reference of an array of type int amn to a functioneditadam commented int an is not an array it is a pointer to an arrayyes but one dimension is known at compile time how can we pass this information which is known at compile time to a function,['c++'] +134631,why is the else line giving an invalid syntax error i am having this errorfile zpy line 70 else syntaxerror invalid syntaxthe line which causes the problem is marked with a comment in the codedef fileparseself table file vars tf opentable file r for line in tf if linestartswith or linestrip pass elif linestartswithn states selfn states strline9strip elif linestartswithneighborhood selfneighborhood strline13strip elif linestartswithsymmetries selfsymmetries strline11strip elif linestartswithvar line line4 ent linereplace replace replace replace replace replacensplit varsent0 for e in ent1 if e in vars varsent0 varse else varsent0appendinte else rule linestripsplit for k in varskeys if k in rule for i in varsk change rulereplacek i change intx for x in change wrulesappendrulechange5change5 else line which causes the problem rule intx for x in rule wrulesappendrulerule5rule5 tfclose selfparse status ok return wruleswrules is variable which is assigned to world classto be honest i have no idea why i get this before everything was fine and now that error shows up after adding some extra instructions in other indented blocksany ideas,['python'] +134653,rubyrails properly thisplayformat text from the text area form control i have a interesting problem i have a text field in my model with thisplays a large chunk of data usually about three paragraphswhen i enter the text in on the new view it might look likeabcimagining that each ab or c is an individual paragraphwith a space between the a b and c lineseg the line break that occurs when you press enter but when i thisplay the very same data on the view the line breaks are not recognized the view seems to concatenate all the text into one big blurb and it thisplays likeabcbut the line breaks are being recorded because going to edit shows the data in the format with the line breaksi thought about adding p s into the text area and parsing the html on the view but that really is not a good option since i dont want to require my users to insert html tagsis there something i am missing to get the text area to thisplay in the same fashion as it was entered,['ruby-on-rails'] +134658,why does a background break a boxshadow inset effect im trying to achieve an innershadow effect on a simple box something likewhere the green box is the content inside another boxmy problem is that if i give the content box any kind of background the outer box boxshadow effect vanishhere an example of my problem with markup and css i have set the content height smaller to evidence the problem atm i really dont care about ie this is just a testany ideaupdatethe content inside the box is a somewhat kind of slide here an example original problemthirtydots answer does the trick but it forces me to make a little hack changing the wrapper background in function of the content example here thirtydot trickthis can be a solution but i dont like it too much and still dont understand why the outer box shadow get behind the inner box background color imageupdate 2talking about this problem on another forum i found another way basically instead of use boxshadow on the wrapper that will act as a mask i use boxshadow and borderradius directly on the content step elementshowever the mask effect is exactly what i was trying to accomplish so this isnt the solution neitheri still do not understand how and why an inner element background interfere with an outer element design or why the shadow dropped from the outer element get behind the inner one could this be a css bugupdate3someone opened a bug on mozilla and got this answer that clearify the problemfrom in terms of stacking contexts and the painting order the outer shadows of an element are drawn immediately below the background of that element and the inner shadows of an element are drawn immediately above the background of that element below the borders and border image if any in particular the backgrounds of children of the element would paint above the inset shadow and in fact they paint above the borders and background of the element itselfso the rendering is exactly what the spec calls forupdate4fabio a pointed out another solution with css3 pointereventslooks good and works on ie8 too,['css'] +134675,validation failed for one or more entities while saving changes to sql server database using entity framework i want to save my edit to database and i am using entity framework codefirst in aspnet mvc 3 c but i am getting errors in my event class i have datetime and timespan datatypes but in my database i have got date and time respectively could this be the reason how can i cast to the appropriate datatype in the code before saving changes to databasepublic class event public int eventid get set public int categoryid get set public int placeid get set public string title get set public decimal price get set public datetime eventdate get set public timespan starttime get set public timespan endtime get set public string description get set public string eventplaceurl get set public category category get set public place place get set method in the controller problem at storedbsavechanges post eventmanageredit386 httppostpublic actionresult editint id formcollection collection var theevent storedbeventsfindid if tryupdatemodeltheevent storedbsavechanges return redirecttoactionindex else viewbagcategories storedbcategoriesorderbyg gnametolist viewbagplaces storedbplacesorderbya anametolist return viewtheevent with public class eventcalendarentities dbcontext public dbsetevent events get set public dbsetcategory categories get set public dbsetplace places get set sql server 2008 r2 database tsql eventdate datatype date starttime datatype time endtime datatype time http form eventdate datatype datetime eg 482011 120 am starttime datatype timespantime not sure eg 0830 endtime datatype timespantime not sure eg 090 server error in applicationvalidation failed for one or more entities see entityvalidationerrors property for more detailsdescription an unhandled exception occurred during the execution of the current web request please review the stack trace for more information about the error and where it originated in the code exception details systemdataentityvalidationdbentityvalidationexception validation failed for one or more entities see entityvalidationerrors property for more detailssource error line 75 if tryupdatemodeltheeventline 76 line 77 storedbsavechangesline 78 return redirecttoactionindexline 79 source file csepmvceventcalendarmvceventcalendarcontrollerseventmanagercontrollercs line 77 stack trace dbentityvalidationexception validation failed for one or more entities see entityvalidationerrors property for more details,"['c#', 'sql']" +134698,hungarian algorithm php version i am trying to implement the job assignment hungarian algorithm algorithmthe algorithm in terms of bipartite graphsi think i understand the algorithm but am not able to appreciate why is it on3 but that is just a curiositywhat i am looking for is a php implementation of hungarian algorithm the wikipedia link does have a link to implementations but i have not found php version yet,['php'] +134728,does jquery support dictionaries key value collection does jquery support dictionaries key value collection i would like to set the following data in a structure 1 false2 true3 falsewith the ability to add lookup delete and updateany help,"['javascript', 'jquery']" +134734,jquery javascript html how to load images after everything else is loaded hey guysi have a very complex page with a lot of scripts and a rather long loading time on top of that page i want to implement the jquery nivo slider in the documentation it says i have to list all images for the slider inside of a divsliderdiv idslider img srcimagesslide1jpg alt a hrefimg srcimagesslide2jpg alt titlehtmlcaption a img srcimagesslide3jpg alt titlethis is an example of a caption img srcimagesslide4jpg alt divhowever i might have 10 images with a 10x400px which is quite big those images would load when the page loads since they are in my header this might take quite a whilei looking for a way to use any jquery slider plugin like the nivo slider but either dynamically load images or load all those images after everything else on my page has loaded any idea how i could solve thatis there even a way to start a javascript process after everything else on the page has loaded if there is a way i might have an solution for my problem using the jquery ajax load method however i have no idea how to wait for everything else to load and then start the slider with all the images,"['javascript', 'jquery']" +134738,escape certain html tags in a string i need to escape all html tags but with some exception like b font etcfor example hello bworldb how are spanyouspanwill result in hello world how are you spanyouspan,['php'] +134774,imageview adjustviewbounds does not work with layout heightfill parent i am trying to place in single row the edittext with the imageview on the left but i cannot get the image to be scaled properly to match the height of text entrythe layout is simple linearlayout androidorientationhorizontal androidlayout widthfill parent androidlayout heightwrap content imageview androidididicon androidlayout widthwrap content androidlayout heightfill parent androidadjustviewboundstrue androidscaletypefitstart androidbackgroundf00 androidsrcdrawableicon edittext androidididtext androidlayout widthfill parent androidlayout heightwrap content linearlayouti highlighted image background by red color to see the actual space allocated by imageviewif i specify the exact height for imageview androidlayout height48dpthen i get the closest view what i neededbut i do not know the exact height of edittext so i cannot specify it for imageview herewhen the height for imageview is specified to fill its parent to match edittext height androidlayout heightfill parentthen i get unexpected extra margin between the image and text entryactually in this case the imageview width equals to unscaled image width whereas the image was scaledit is the similar to picture shown below if i specify layout height to 48dp and set adjustviewbounds to false androidlayout height48dp androidadjustviewboundsfalseso the question here is how to define the layout correctly to scale the image to match edit entry height and in the same time to have width of imageview to be shrunk to scaled image width in other words how to get rid this extra space off,['android'] +134792,android xml layout files and namespace android layouts are defined in xml with this namespace declared in the root element xmlnsandroidexample of an elementtextview androidlayout widthfill parent androidlayout heightwrap content why is the android prefix used instead of ommitting it like xmlnshttp why is the prefix used only in attributes and not in elements,['android'] +134794,gallery default item selected is in center possible duplicateandroid gallery image position problem i am using gallery view within my app now when i run the code gallery has default selected item is no 1 which is in center and left side is blankinstead i want no 1 item should be at left and selectedalso clicking on the any gallery item should not bring that item in the centeri tired hunting it lot on the groups but not found any solution is this possible or not if yes then how come,['android'] +134798,javac strange syntax error illegal start of expression i encountered a strange error which i believe is a bughere is a minimal case please do not comment on the usefulness of the code class foo static public x int bar return 42 public int baz return true 42 foovoidbar 42 41 43 result errjava7 illegal start of expression foovoidbar 42 41 43 i have tried sun sdk javac 160 13 and 160 21the error goes away when i either make bar nongeneric just for curiosity not really an option remove the parentheses around the ternary expression on line 7so it looks like that if e is an expression it is not always valid to write e,['java'] +134811,find hidden dependencies in ivy i am using apache ivy ivyde for getting my projects dependencies which are dependency orgcomgoogleguava nameguava revr08 logging dependency orgorgslf4j namejcloverslf4j rev161 dependency orgchqoslogback namelogbackclassic rev0927 database dependency orgorghibernate namehibernateentitymanager rev362final dependency orgorghibernate namehibernatevalidator rev410final dependency orgorghibernate namehibernatec3p0 rev362final dependency orgmysql namemysqlconnectorjava rev5114 sources are the maven and jboss hibernate repositoriesas you can see i am using logbackslf4j for logging but for some reason ivy will download log4j and slf4jlog4j as well which causes a few small problem in my applicationis there a way to see why this happens to see which of the dependencies above depend on log4j can i get a dependency graphtree generated from ivyivydeand is there then a way to prevent this from happening,['java'] +134818,highlight current row in jtextpane i am trying for more than 2 days to implement a specific requirement for a text editor window unfortunately without success so far the goal is to get a text editor window which will highlight the current row like other text editors do with current row i mean the row where currently the cursorcaret is positioned i already found two different approaches but unfortunately i am not able to adopt them so they work as expectedthe first approach is to overwrite the defaulthighlighter in the second approach the highlighterpainter will be overwritten instead right now i am trying to adopt the first approach in my project but as i said it is not working as desiredat the end of this post i am posting a small sample application which demonstrates the problemif i start the program the caret is placed at the beginning of the first line however the line is not highlightednow i type in some characters those chars will be highlighted but only those chars not the complete linei hit enter to move to the next line the first line is not highlighted anymore what is correct the second line is not highlighted as well what is not correct again when i type in some chars those will be higlighted but not the complete rowwhen i now move back the caret to the first line either by cursor up key or mouse clicking the complete first line will be highlighted not only the existing chars this is the behavior i want right from the starti hope anybody can tell me what i am doing wrong here or explain why it is not possible to resolve that issue at all any alternative solutions how i could realize the line highlighting are also highly appreciatedthanks a lot in advancecheerspreachieimport javaawtcolorimport javaawtdimensionimport javaawtgraphicsimport javaawtinsetsimport javaawtrectangleimport javaxswingjframeimport javaxswingjtextpaneimport javaxswingeventcareteventimport javaxswingeventcaretlistenerimport javaxswingtextdefaulthighlighterimport javaxswingtexthighlighterimport javaxswingtextjtextcomponentpublic class highlightproblem extends jframe private static final long serialversionuid 1l private final jtextpane textpane private final highlighterhighlightpainter cyanpainter public highlightproblem cyanpainter new defaulthighlighterdefaulthighlightpaintercolorcyan textpane new jtextpane textpanesetpreferredsizenew dimension500 300 textpanesethighlighternew linehighlighter textpaneaddcaretlistenernew caretlistener override public void caretupdatecaretevent e sethighlighte getcontentpaneaddtextpane setdefaultcloseoperationjframeexit on close pack setvisibletrue public static void mainstring args new highlightproblem public void sethighlightcaretevent e textpanegethighlighterremoveallhighlights int currentline getlinefromoffsettextpane egetdot int startpos getlinestartoffsetforlinetextpane currentline int endoffset getlineendoffsetforlinetextpane currentline try textpanegethighlighteraddhighlightstartpos endoffset cyanpainter catch exception ex exprintstacktrace textpanerepaint public int getlinefromoffsetjtextcomponent component int offset return componentgetdocumentgetdefaultrootelementgetelementindexoffset public int getlinestartoffsetforlinejtextcomponent component int line return componentgetdocumentgetdefaultrootelementgetelementlinegetstartoffset public int getlineendoffsetforlinejtextcomponent component int line return componentgetdocumentgetdefaultrootelementgetelementlinegetendoffset public class linehighlighter extends defaulthighlighter private jtextcomponent component override public final void installfinal jtextcomponent c superinstallc thiscomponent c override public final void deinstallfinal jtextcomponent c superdeinstallc thiscomponent null override public final void paintfinal graphics g final highlighterhighlight highlights gethighlights final int len highlightslength for int i 0 i len i highlighterhighlight info highlightsi if infogetclassgetnameindexoflayeredhighlightinfo 1 avoid allocing unless we need it final rectangle a thiscomponentgetbounds final insets insets thiscomponentgetinsets ax insetsleft ay insetstop awidth insetsleft insetsright 100 aheight insetstop insetsbottom final highlighterhighlightpainter p infogetpainter ppaintg infogetstartoffset infogetendoffset a thiscomponent override public void removeallhighlights textpanerepaint0 0 textpanegetwidth textpanegetheight superremoveallhighlights,['java'] +134832,sql grouping by month and year i am not sure what should i write in the following sql query to show date column like this monthyear 92011 select monthdate yeardate as mjesec summarketingexpense as sumamarketing sumrevenue as sumazarada from orderwhere idcustomer 1 and date between 20013 and 2013group by monthdate yeardateso what i want to do is to change the data from the first column to show month and year instead of showing month only,['sql'] +134840,is there any adequate scaffolding for django a la ruby on rails is there any adequate scaffolding for djangoit may be in the newly released 13 version but i have not found it yet,['python'] +134842,androidmaven no resource identifier found for attribute instalocation in package android to add support to my android app for instalocation i upped my android level from 7 to 8 in my ide intellij the android app builds fine from intellijwe use maven though and from maven it fails to compileerror cdevsvnlocal5xandroidandroidmanifestxml3 error no resource identifier found for attribute instalocation in package androiderror error when generating sourcesi have also addedusessdk androidminsdkversion7 androidtargetsdkversion8i keep gettingno resource identifier found for attribute instalocation in package androidi would changed my dependency fromdependency groupidandroidgroupid artifactidandroidartifactid version21 r1version scopeprovidedscope dependencyto dependency groupidcomgoogleandroidgroupid artifactidandroidartifactid version221version scopeprovidedscope dependencybut i was still getting this error messagewhats missing,['android'] +134866,causes of javalangnosuchmethoderror main exception in thread main new java programmers often encounter this message when they attempt to run a java programjavalangnosuchmethoderror main exception in thread mainwhat does this mean what can cause it and what should one do to fix it,['java'] +134889,named parameters in ruby structs i am pretty new to ruby so apologies if this is an obvious questioni would like to use named parameters when instantiating a struct ie be able to specify which items in the struct get what values and default the rest to nilfor example i want to domovie structnew title length ratingm movienew title some movie rating rthis does not workso i came up with the followingclass mystruct struct override the initialize to handle hashes of named parameters def initialize args if argslength 1 and argsfirstinstance of hash then argsfirsteach pair do k v if membersinclude k then selfk v end end else super args end endendmovie mystructnew title length ratingm movienew title some movie rating rthis seems to work just fine but i am not sure if there is a better way of doing this or if i am doing something pretty insane if anyone can validaterip apart this approach i would be most gratefulupdatei ran this initially in 192 and it works fine however having tried it in other versions of ruby thank you rvm it worksdoes not work as follows187 not working191 working192 workingjruby set to run as 192 not workingjruby is a problem for me as i would like to keep it compatible with that for deployment purposesyet another updatein this everincreasing rambling question i experimented with the various versions of ruby and thiscovered that structs in 19x store their members as symbols but in 187 and jruby they are stored as strings so i updated the code to be the following taking in the suggestions already kindly givenclass mystruct struct override the initialize to handle hashes of named parameters def initialize args return super unless argslength 1 and argsfirstinstance of hash argsfirsteach pair do k v selfk v if membersmap x xinterninclude k end endendmovie mystructnew title length ratingm movienew title some movie rating rthis now appears to work for all the flavours of ruby that i have tried,['ruby'] +134894,should i convert shared ptr to weak ptr when passed to a method there are already a couple of questions regarding this topic but i am still not sure what to do our codebase uses shared ptr at many places i have to admit that we did not define ownership clearly when writing it we have some methods like void dosomethingshared ptrmyclass ptr dosomething is a member function of a class but usually would not store the ptr ptrfoo after having thiscovered the first indirect circular dependencies i would like to correct the mistakes in our design but i am not exactly sure how is there any benefit in changing the method from above to void dosomethingweak ptrmyclass ptr shared ptrmyclass ptrshared ptrlock ptrsharedfoo i am also confused because some people say including the google style guide that in the first place it is important to get ownership correct which would probably mean introduction of many weak ptrs eg in the example with the methods above but also for many member variables that we have others say see links below that you should use weak ptr to break cyclic dependencies however detecting them is not always easy so i wonder if i really should use shared ptr until i run into problems and realize them and then fix them thanks for your thoughtssee also in c shared ptr and weak ptr differencesboostshared ptr cycle break with weak ptrboost shared ptr vs weak ptr which to use when,['c++'] +134915,what is the encoding of argv it is not clear to me what encodings are used where in cs argv in particular i am interested in the following scenarioa user uses locale l1 to create a file whose name n contains nonascii characterslater on a user uses locale l2 to tabcomplete the name of that file on the command line which is fed into a program p as a command line argumentwhat sequence of bytes does p see on the command linei have observed that on linux creating a filename in the utf8 locale and then tabcompleting it in eg the zw twbig5 locale seems to cause my program p to be fed utf8 rather than big5 however on os x the same series of actions results in my program p getting a big5 encoded filenamehere is what i think is going on so far long and i am probably wrong and need to be correctedwindowsfile names are stored on thisk in some unicode format so windows takes the name n converts from l1 the current code page to a unicode version of n we will call n1 and stores n1 on thiskwhat i then assume happens is that when tabcompleting later on the name n1 is converted to locale l2 the new current code page for thisplay with luck this will yield the original name n but this would not be true if n contained characters unrepresentable in l2 we call the new name n2when the user actually presses enter to run p with that argument the name n2 is converted back into unicode yielding n1 again this n1 is now available to the program in ucs2 format via getcommandlinewwmaintmain but users of getcommandlinemain will see the name n2 in the current locale code pageos xthe thiskstorage story is the same as far as i know os x stores file names as unicodewith a unicode terminal i think what happens is that the terminal builds the command line in a unicode buffer so when you tab complete it copies the file name as a unicode file name to that bufferwhen you run the command that unicode buffer is converted to the current locale l2 and fed to the program via argv and the program can decode argv with the current locale into unicode for thisplaylinuxon linux everything is different and i am extraconfused about what is going on linux stores file names as byte strings not in unicode so if you create a file with name n in locale l1 that n as a byte string is what is stored on thiskwhen i later run the terminal and try and tabcomplete the name i am not sure what happens it looks to me like the command line is constructed as a byte buffer and the name of the file as a byte string is just concatenated onto that buffer i assume that when you type a standard character it is encoded on the fly to bytes that are appended to that bufferwhen you run a program i think that buffer is sent directly to argv now what encoding does argv have it looks like any characters you typed in the command line while in locale l2 will be in the l2 encoding but the file name will be in the l1 encoding so argv contains a mixture of two encodingsquestioni would really like it if someone could let me know what is going on here all i have at the moment is halfguesses and speculation and it does not really fit together what i would really like to be true is for argv to be encoded in the current code page windows or the current locale linux os x but that does not seem to be the caseextrashere is a simple candidate program p that lets you observe encodings for yourselfinclude stdiohint mainint argc char argv if argc 2 printfnot enough argumentsn return 1 int len 0 for char c argv1 c c len printfd intc printfnlength dn len return 0you can use locale a to see available locales and use export lc allmy encoding to change your locale,['c'] +134932,mobile app targetting iphone wp7 android and blackberry is there a sane way to develop a cross platform mobile app we want these to be native apps on each platform and not necessarily some kind of web pagecurrently were thinking to split it into two languagesc backend business logic standard c app for wp7 app built on monotouch for iphoneipadetcjava backend business logic standard android java app monodroid version of c not readyyet standard blackberry java appwe could also develop initially in c and use one of the conversion tools out there to get our c converted into java as a starting pointis there another approach our skillsets include mainly include a strong c net background and minor java experiencewe do not really want to go low level and use something like cc to get the job done these are usually going to be simple lob applications that communicate to some web serviceside question how do game devs like the makers of angry birds do itupdatemonodroid is now officially released so it seems you would only need to use java for the blackberry we are considering not developing for blackberry at all because developing for the other 3 platforms has been simplified there is definitely some cost involved as monotouch and monodroid are both 399 and you would also need a license for visual studio this does not include cost for app store etc,"['iphone', 'android']" +134937,can i combine two decorators into a single one in python is there a way to combine two decorators into one new decorator in pythoni realize i can just apply multiple decorators to a function but i was curious as to whether there is some simple way to combine two into a new one,['python'] +134941,manytomany without join table legacy database i have to apply jpa in a legacy database with an awful design unfortunately is not possible to change it luckily is only for readonly access one of the strangest things i found is a manytomany relationship without a join or intermediate table this is a simplification of the table structureuser access id int primary key id int primary keyname varchar220 name varchar220access group int access group intaccess group columns can be repeated in both tablesone user can be related to and accessone access can be related to and userconceptually this tables must be mapped with java classes this waypublic class user private integer id private string name manytomany private listaccess accesslistpublic class access private integer id private string name manytomany private listuser userlistbut i think this is not possible what do you think is the best approach to access this tables in jpa and navigate through them,"['java', 'sql']" +134943,action delegate how to get the instance that call the method i have an action and i wonder how could i access the instance that call the methodexemplethisfindinstance thisinstanceofaclassmethodthisfindinstance thisinstanceofaclass2methodthisfindinstance thisinstanceofaclass3method public void findinstanceaction action the action is thisinstanceofaclassmethod and i want to get the instance from action thank you,['c#'] +134952,html country list with flags i am looking for a way to select and thisplay a list of countries preferably with flags any suggestionsi started of by trying this jquery plugin but as the list of countries i have is quite large it turned out that the performance was really bad too many http requests to images also the list is bulky when it is larger than 50 elements,"['javascript', 'html']" +134963,why am i missing the qt multimedia functionality i am new to qt and i am creating a simple application which will playback an audio filei realized that i am lacking the qt multimedia api for audio when i wroteinclude qaudiooutputand i get that there is no such file i downloaded the latest qt sdk framework and i cannot find a way to add these apis i am using qt creator ideis there a way to get the multimedia functionality working maybe as an addon or some other waythanks,['c++'] +134973,wpf timer like c timer where can i find a control which is like the c timer control in wpf,['c#'] +134986,how can i show all the localstorage saved variables i want to acess all the localstorage variables saved on a specific page how do i do that i want to show it like i would show an array with the join function,['javascript'] +135006,gwt reduce compiled javascript size i have found that the size of the compiled javascript grows faster than i had expected adding a few lines of java code to my project can increase the script size in several kbsat the moment my compiled project weights 1mb i am not using any external libraries except for those for mvp activities places testing junit and logging i would like to know if there are any coding practicesrecommendations to keep the compiled script as small as possible i am not refering to code splitting but to coding techniques or patterns that can make the compiled javascript effectively smallermany thanks,['javascript'] +135012,python run a daemon subprocess read stdout i need to run a program and gather its output to stdout this program socat needs to run in the background for the duration of the python script socat sits in dameon mode once it is run but first it outputs some lines to stdout that i need for the rest of my scriptcommand socat d d pty ptyoutput20110323 211235 socat7476 and pty is devpts120110323 211235 socat7476 and pty is devpts220110323 211235 socat7476 and starting data transfer loop with fds 33 and 55i basically want to run that at the start of my program and leave it running till script termination but i need to read the two devptsx names into pythoncan anyone tell me how to do thisi came up with this which just hangs i guess because it is blocking for the child process to terminateusrbinpythonfrom subprocess import popen pipe stdoutcmd socat d d pty pty p popencmd shelltrue stdinpipe stdoutpipe stderrpipe close fdstrueoutput pstdoutread process the output printoutputthanks for any helpedit seems it may write to stderr but the script still just hanges with and without the even reading from stderr,['python'] +135020,call a javascript function after updatepanel postback issue i basically have in my updatepanel a literal that generates a javascript array based on a method in my codebehindi do not have an issue when it comes to loading my content on page load but if i try and carry out a search to update my javascript array literal within my updatepanel i found that the literal gets updated on postback after the javascript has already fired here is a basic example of what i havescript typetextjavascriptfunction bindmyfunctionitemlist do somethingscriptaspupdatepanel idupdatepanel1 runatservercontenttemplate literal containing generated js array aspliteral idprofilejavscriptoutput runatserveraspliteral ul idpersonsearch liasptextbox idtxtfirstname runatserver textasptextboxli update literal onclick liaspimagebutton cssclasearchbtn idimagebutton1 runatserver onclickimagebutton1 click li ul some jcarousel rendered aspupdatepaneli have been looking at the following postsaspnet updatepanel and javascriptcall javascript after updatepanel postbackbut i cannot seem to apply it correctly to my codeit works fine when i do not use an updatepanel but it is a requirement so that the page position does not move when searches are carried out,['asp.net'] +135034,base36 representation of digest i would like to be able to take an arbitrary string run it through a hashing function like md5 and then interpret the resulting digest in base36i know there already exists a digest library in ruby but as far as i can tell i cannot get at the raw bytes of a digest the to s function is mapped to hexdigest which is of course base16,['ruby'] +135042,uiimage from uiview higher than onscreen resolution i have got a uiview which i am rendering to a uiimage via the typical uigraphicsbeginimagecontextwithoptions method using a scale of 20 so the image output will always be the retina thisplay version of what would show up onscreen regardless of the users actual screen resolutionthe uiview i am rendering contains both images and text uiimages and uilabelsa the image is appearing in the rendered uiimage at its full resolution and looks greata but the uilabels appear to have been rasterized at a 10 scale and then upscaled to 20 resulting in blurry textis there something i am doing wrong or is there some way to get the text to render nice and crisp at the higher scale levela or is there some way to do this other than using the scaling parameter of uigraphicsbeginimagecontextwithoptions that would have better results a thanks,"['iphone', 'ios']" +135054,c40 int a real subtype of object covariance ienumerable and value types i wonder why ienumerableint cannot be assigned to a ienumerableobject after all ienumerable is one of the few interfaces that supports covariancethe subtype relation and covariance stuff works with reference typesint seems to be a proper subtype of objectthe combination of both features does not work howeverclass aclass b aclass program static void mainstring args bool b b typeofienumerableaisassignablefromtypeoflistb consolewritelineienumerable of ref types is covariant b true b typeofienumerableobjectisassignablefromtypeoflistint consolewritelineienumerable of value tpyes is covariant b false b typeofobjectisassignablefromtypeofint consolewritelineint is a subtype of object b true thanks for your helpsebastian,['c#'] +135057,entity framework code first is not creating the database heres an overview of how my solution looksheres my pizzasoftwaredata classnamespace pizzasoftwaredata public class pizzasoftwaredata dbcontext public dbsetcustomer customers get set public dbsetorder orders get set public dbsetproduct products get set public dbsetuser users get set according to an example on scott guthries blog you have to run this code at the beginning of the application in order to createupdate the database schemadatabasesetinitializerpizzasoftwaredatanew createdatabaseifnotexistspizzasoftwaredatai am running that line of code from programcs in pizzasoftwareuinamespace pizzasoftwareui static class program summary the main entry point for the application summary stathread static void main applicationenablevisualstyles applicationsetcompatibletextrenderingdefaultfalse databasesetinitializerpizzasoftwaredatanew createdatabaseifnotexistspizzasoftwaredata applicationrunnew loginform can anyone tell me why the database is not having the tables created heres the connection string in my appconfig filexml version10 encodingutf8 configuration connectionstrings add namepizzasoftwaredata connectionstringdata sourcesqlexpressinitial catalogsaharapizzaintegrated securitytruepoolingfalse providernamesystemdatasql connectionstringsconfiguration,['c#'] +135062,messagebox buttons how would i say if the yes button on the messagebox was pressed do thisthat and the other in c,['c#'] +135072,pass data from java servlet to jsp i have been a php developer but recently need to work on some project using google app engine java in php i can do something like this in term of mvc model controllersaccountsphpaccounts getaccountsinclude viewsaccountsphp viewsaccountsphpprint raccountsi take a look at some demos of google app engine java using servlet and jsp what they are doing is this in accountsservletjavapublic class accountsservlet extends httpservlet override protected void doposthttpservletrequest req httpservletresponse resp throws servletexception ioexception string action reqgetparameteraccountid do something redirect to an jsp page manually passing querystring along respsendredirectnamedcounterjspname reqgetparametername basically in the java case it is 2 different http requests the second one being automatically forced right so in jsp file i cannot make use of the data calculated in the servletis there some way i can do it similar to the php way,['java'] +135075,custom installed font not thisplayed correctly in uilabel i am trying to use a helvetica neue condensed font which i got from the adobe font collection pro package unfortunately it seems to draw incorrectly when i use it within a uilabelthe line height seems to be calculated correctly i think but when the font is thisplayed it is aligned to the very top of the bounding box i called mylabel sizetofit and only adjusted the width to produce this screen capturei had the same problem with both the bold and regular version of the font i was able to pull a version of helvetica neue bold from osx and put it on my device and it thisplays fine green background in above picturewhat could be wrong with the either the font file or my code that would cause it to draw this way,['ios'] +135078,does x catch all output if i run this codesvn output xsvn update usersradeksitesdb2rft r 105 force putsputs output is svn outputi get this resultsvn working copy usersradeksitesdb2rft lockedsvn run svn cleanup to remove locks type svn help cleanup for details output is but i want the error message from svn inside the variable svn output is that possible,['ruby'] +135079,mssql query issue in php and querying text data i am trying a query in php to connect and extract data from a mssql express 2008 r2 database but i am getting an error when i am pulling ntext based data from the dberror isunicode data in a unicodeonly collation or ntext data cannot be sent to clients using dblibrary such as isql or odbc version 37 or earlier severity 16 inand my script is myserver sqlexpress myuser sa mypass blablabla mydb test connection to the database dbhandle mssql connectmyserver myuser mypass or diecould not connect to sql server on myserver select a database to work with selected mssql select dbmydb dbhandle or diecould not open database mydb declare the sql statement that will query the database query select from dbotable where query2 query from dbotable query where query2 execute the sql query and return records result mssql queryquery numrows mssql num rowsresult echo h1 numrows row numrows 1 s returned h1 thisplay the results whilerow mssql fetch arrayresult echo li rowquery li close the connection mssql closedbhandle any help on this is appreciated thanks,['php'] +135089,export eclipse console view output to text file how to redirect console view output to a text file in eclipse,['java'] +135090,sending pictures to a web server i have to build an application that should send pictures from the phone to a web server unfortunately i really do not know how to do this could someone help me out please,['android'] +135093,time select form helper with 12 hour format for rails 3 is there a userfriendly time select for rails 3 the default time select form helper gives you hours0023 minutes0059 and optionally seconds0059 a dropdown list of hours 023 is pretty frustrating for those of us who are not on military time a userfriendly solution would thisplay hours 112 and an extra ampm dropdown listis there an option or a separate plugin to handle this i cannot be the first person to want this but i have not found any solutionsthanks,['ruby-on-rails'] +135096,how to determine if an nsstring is latin based i am trying to determine if a string is latin based or japanesei have tried something like the following but it returns yes for japanese strings as wellnscharacterset alphaset nscharacterset alphanumericcharactersetbool isalpha mystr stringbytrimmingcharactersinsetalphaset isequaltostringa string might be a word like cafa or something like a or aeao,"['iphone', 'objective-c']" +135104,how to vertically align an image inside a div with dynamic height what we have is a div that contains an image that a user uploads this is the codehtmldiv classcontainer img img height120 width150 srcimage namejpgdivcssdivcontainer img overflow hidden width 150px height 150pxour problem is if the image the user uploads has a height smaller than 150px there is a big space at the bottom so we want to vertically align the image so that it does not look like it is just floating i have tried searching for solutions on the net but i cannot find one that works with dynamic images inside a div some solutions require that you know the dimensions of the imagehas anybody had this problem and solved it,"['jquery', 'html', 'css']" +135107,grep a page in firefox using javascript am writing an extension to provide greping functionality in firefox at my workplace we access all log files using a browser and grep functionality would be ideal for filtering results looking at only particular logging levels infowarnerror etchave setup the extension boilerplatewas wondering if i could get some hints on the required javascript am after a functionfunction greppageregexwhich would apply the regex to each line in loaded text file in firefox and change the loaded text file to only thisplay lines that matchthis is the type of thing i could spend ages trying to work out when i am sure there would be simpler ways of doing thisany help would be highly appreciatedcheersben,['javascript'] +135114,asmx service works on development server returns 404 when deployed to iis 75 i have a web application in aspnet 40 i have added an asmx service primarily as a source for the autocomplete extenders lookup valueswhen i debug on my machine locally everything works fine however when i deploy the web application to iis 75 i get a http 404 response when trying to send data to the servicei am able to browse to the service definition see the available operations tellingly however when i use the test pages to test the service using post i receive an http 404 againi am not sure what is going on i did create the asmx file within my web application and it is deployed in the virtual directory of my otherwise working production applicationis there an issue with the asmx file being deployed in the same virtual directory perhaps,['asp.net'] +135122,listening for the domready event for googlemapsinfowindow class so i am trying to make add a google map to my webpage i want to add a form into the popup bubble when you click on a marker on the mapthe api documentation says that the domreadyevent is fired when the containing the infowindows content is attached to the dom you may wish to monitor this event if you are building out your info window content dynamicallyhow do i listen to this eventthis is the documentation,['javascript'] +135130,how do i thisable form resizing for users in c winforms how do i thisable form resizing for users in c winforms which property is used i tried autosizeautosizemodeany help,['c#'] +135136,understanding the open closed principle i was refactoring some old code of a simple script file parser when i came across the following code stringreader reader new stringreaderscripttexttoprocestringbuilder scope new stringbuilderstring line readerreadlinewhile line null switch line0 case process the entire line as a variable ie add it to a collection of keyvaluepair addtovariablesline break case depending of what comes after the character process the entire scope andor the command in line if line execute executescopescope else if linestartswithcustom command runcustomcommandline scope else if line single line directive processdirectiveline scope new stringbuilder break default no processing directive ie add the line to the current scope scopeappendline break line readerreadlinethis simple script processor seems to me like a good candidate for refactoring by applying the open closed principle the lines beginning with a will probably never be handled differently but what if new directives beginning with a needs to be added or new processing identifiers eg new switchcases are neededthe problem is i could not figure out how to easily and correctly add more directives and processors without breaking ocp the case using scope andor line makes it a bit tricky as does the defaultcaseany suggestions,['c#'] +135147,how can i add boost threads to a vector i have something like this that is incorectvectorboostthread vecforint agent 1 agent numagents agent boostthread agentthreadselltickets agent numticketsnumagents vecpush backagentthreadmaybe i should add pointers to boostthread in the vector but then i do not know how to add dynamic allocated threads how should i do to make this work thank you,['c++'] +135151,timestamp to human readable format well i have a strange problem while convert from unix timestamp to human representation using javascripthere is timestamp1301090400this is my javascriptvar date new datetimestamp 10var year dategetfullyearvar month dategetmonthvar day dategetdayvar hour dategethoursvar minute dategetminutesvar seconds dategetseconds i expected results to be 2011 2 25 22 00 00 but it is 2011 2 6 0 0 0what i miss,['javascript'] +135155,c function to return array summary returns an array of all artworkdata filtered by user id summary param nameusersiduser id to filter onparam returnsreturnspublic static array getdatarecordsint usersid artworkdata labels labels new artworkdata3 return labelsi get a syntax error expected after return labelsam i doing this right,"['c#', 'asp.net']" +135157,c version of sql like is there any way to search patterns in strings in csomething like sql like would be very useful,"['c#', '.net', 'sql']" +135167,c warning statement with no effect when trying to compile my prgram withgcc pedantic wall ansi i get the warning warning statement with no effectreferring to this lineforcurrentdirection currentdirection enddirection currentdirectioncan anyone help me with this,['c'] +135181,mysql sql specific item to be first and then to sort the rest of the items lets say i have the table belowi want to get all the friends but i want the id 5 to be the first item in the list i do not care about the order that i receive the rest of the itemsthe desired query result will befriendsid name5 nahum1 moshe2 haim3 yusuf4 gedalia6 danahow can i do thisusing mysql 51xthanks,"['mysql', 'sql']" +135182,how to check if debugger keyword exists sometimes some developers forgot to remove debugger in javascript code and it produce javascript error on iehow can you check like for the console ifwindowconsoleconsolelogfoo if a debugger existsbtw i do not want to detect if the browser is ie i want a generic method if possiblethanks,['javascript'] +135185,store and retrieve a class object in shared preference in android can we store an object of a class in shared preference and retrieve the object laterif it is possible how to do it if it is not possible what are the other possibilities of doing it i know that serialization is one option but i am looking for possibilities using shared preference,['android'] +135193,thisable the touch events for all the views whats the best way to thisable the touch events for all the viewsthanks a lotgratzi,['android'] +135196,mysql adding hours to datetime in mysql db i need to check if a datetime field is more than 24hours or whatever ago in which case delete the rowhow to add hours to datetime in mysqlthanksluca,['mysql'] +135198,ruby on rails what performance can i realistically aim for i have been building an application in ruby on rails 3 and i am starting to worry about performance optimization now i hope that my question is not too subjective for this site but i am interested in facts not a thiscussion so here goeswhile i am trying to get my views to render faster there is one thing i simply do not know what should i aim for given a reasonably complex page what load time is realistic i simply do not have any referencewhat i am typically seeing for my application is something like thiscompleted 200 ok in 397ms views 3411ms activerecord 177msthis is on my production server running apachepassengeri am the only one making requests on that server it is a root server not virtual running ubuntu amd athlon 64 x2 5600 4 gb ramthat is for most of my more complicated actions not unusually complicated just assume it is a paginated listing of 20 objects with 5 computed properties each or something the activerecord times are almost always fine 2030ms but the views number is usually 200 msnow to my question when i started using ror my expectation maybe unrealistic was that for most consumeroriented applications with average complexity let us say something like facebook twitter etc without the millions of users i would get 20 ms load times as long as i was the only one making requests and that for a single server load times would only approach 100ms or more if there were lots of people making requests at the same timemy expectation was also that database requests would be the major bottleneck since all the rest is just relatively simple computations without any real complexity i thought that it might take 10ms to get all the objects from the database and then maybe another 5 ms to run the controller code build the view etcsince i have never been in charge of any production app i do not know if this expectation was in any way realistic so i would like somebody with experience point out to me what my realistic expectation should beeg pretty much everything but really nasty stuff should render in 50 ms tops as long as you are the only one making requestsor actually 300 ms is not unusual for ror applications even if youre the only useror are you kidding i get 10 ms with 150 concurrent requests on a smaller server than yours there must be something very wrong with your appagain i hope this is not too subjective but i am not really interested in an opinion of whether or not ror is fast i want facts from someone with more experience on what numbers are average and to be expected from production ror applications otherwise i simply have no clue at what point i should stop optimizing and just accept that i will never get 10 ms load times,['ruby-on-rails'] +135203,jquery mouseup outside window a possible i am trying to accomplish a rudimentary drag on mousedown the item starts dragging but not at the same speed as the mouse so i continue dragging when the mouse is outside the window but if the mouse is not over the page i cannot get mouseup eventsi can see other pages do this so i know it is possible appreciate any helpedit egplay any video on vimeo make sure the window is small enough on your screen with space above it then drag the videos progress bar left and right now move the cursor outside the top edge of the window while still dragging leftright see now release mouse button while still outside of the window dragging ends and video continues playingnote vimeo has an option to use a flash player or html5 player and this is with the html5 player,['jquery'] +135205,xcode 4 adding the ios developer library reference to organizer documentation in xcode 4 my organizer documentation window does not appear to have the ios documentation installed only mac os x 106 core library and xcode 40 developer library does anyone know if it is possible to add it without reinstalling the whole of xcode 4 which i really do not want to dothanks,"['iphone', 'ios']" +135263,nutch invoke in java not command line am i being thick or is there really no way to invoke apache nutch through some java code programmatically where is the documentation or a guide or tutorial on how to do this google has failed me so i actually tried bing yes i know pathetic ideas thanks in advancealso if nutch is a crapshoot any other crawlers written in java that are proven to be reliable on an internet scale with actual documentation,['java'] +135276,commons method to test for an empty java object graph i have found myself writing a method like thisboolean isemptymystruct mystruct return mystructgetstringa null mystructgetstringaisempty mystructgetlistb null mystructgetlistbisemptyand then imagine this struct with lots of other properties and other nested lists and you can imagine that this method gets very big and is tightly coupled to the data model does apache commons or spring or some other foss utility have the ability to recursively reflectively walk an object graph and determine that it is basically devoid of any useful data other than the holders for lists arrays maps and such so that i can just writeboolean isemptymystruct mystruct return magicutilityisobjectemptymystruct,['java'] +135282,rvm systemwide install script url broken what is replacement my rvm systemwide installation scripts are broken both in the form of linode stackscripts and chefsolo recipesper the instructions on the rvm website my scripts execute the following commands as root to install rvm on a systemwide basisecho installing rvm systemwide logfilebash curl l cat etcprofile eof load rvm if it is installed first try to load user install then try to load root install if user install is not thereif s homervmscriptsrvm then homervmscriptsrvmelif s usrlocalrvmscriptsrvm then usrlocalrvmscriptsrvmfieofsource etcprofilethe key piece above is the url as of today 3242011 this url no longer in service it results in a github 404 errorthe following url on the rvm website used to contain the instructions for the systemwide install however that url now redirects to the rvm homepagein the interests of getting rvm systemwide installation scripts to work again what are the new instructions,['ruby'] +135292,using jquery to get string value of an onclick event wondered if there was good way to do this thought i would post to the so communitythere is a 3rd party web page that i have no control over how it renders but they allow me to add jqueryusing the jquery i am creating a nav menu on the side of the page it will be a list of links the onclick event of these links i get from existing onclick events already on the page but when i do avar linkloc thelinkattronclicklinkloc returnsfunction onclickevent handlejumptocomwebridgeentityentityoide471cb74a9857542804c7ac56b1f41fb smartforminstead of what i would expecthandlejumptocomwebridgeentityentityoide471cb74a9857542804c7ac56b1f41fb smartformi think jquery is trying to get the event for binding but i need the actual javascript markup since i am creating the html dynamically i guess i could substring the function onclickevent out but seems kind of hackyany ideas of an elegant way i could get the onclick markup,"['javascript', 'jquery']" +135311,returning false from click handler does not work in firefox in the example below return false does not seem to prevent the default action after the link is clicked because the page scrolls to the top in firefox 36 or chrome 10 but works in internet explorer using eventpreventdefault does what i need but i am wondering why return false does not work with the othersside note i do not need to support internet explorerscript addeventlistenerdomcontentloaded function documentgetelementbyidlinkaddeventlistenerclick function alertclicked return false false alertclick handler bound falsescriptdiv stylemargintop 1200px a idlink hrefclick meadiv,['javascript'] +135313,datagrid creating radiobutton column i have objects bound to a datagrid i have created a radio button column bound to the is default property of the objectwhen the app starts up the correct item is shown as default however the binding is then never updated the behaviour i would like is for the user to check a radio box and for that object to become the default datagrid canuseraddrowsfalse autogeneratecolumnsfalse nametest datagridcolumns datagridtextcolumn headervalue bindingbinding pathname modeonetime datagridtemplatecolumn headeris default datagridtemplatecolumncelltemplate datatemplate radiobutton groupnametest ischeckedbinding isdefault datatemplate datagridtemplatecolumncelltemplate datagridtemplatecolumn datagridcolumns datagrid private class test inotifypropertychanged public string name get set bool isdefult public bool isdefault get return isdefult set isdefult value public event propertychangedeventhandler propertychanged public mainwindow thisinitializecomponent test ya new test new test name 1 isdefault false new test name 2 isdefault false new test name 3 isdefault true thistestitemssource ya iave been pulling my hair out all afternoon at this any help would be loved,['.net'] +135321,how do i change a partially transparent images color in ios i have a singlecolor image that has partial transparency i have both normal and 2x versions of the image i would like to be able to tint the image a different color in code the code below works fine for the normal image but the 2x ends up with artifacts the normal image might have a similar issue if so i cannot detect it on account of resolution uiimage newimagefrommaskimageuiimage mask incoloruicolor color cgimageref maskimage maskcgimage cgfloat width masksizewidth cgfloat height masksizeheight cgrect bounds cgrectmake00widthheight cgcolorspaceref colorspace cgcolorspacecreatedevicergb cgcontextref bitmapcontext cgbitmapcontextcreatenull width height 8 0 colorspace kcgimagealphapremultipliedlast cgcontextcliptomaskbitmapcontext bounds maskimage cgcontextsetfillcolorwithcolorbitmapcontext colorcgcolor cgcontextfillrectbitmapcontext bounds cgimageref mainviewcontentbitmapcontext cgbitmapcontextcreateimagebitmapcontext cgcontextreleasebitmapcontext uiimage result uiimage imagewithcgimagemainviewcontentbitmapcontext return resultif it matters the mask image is loaded using uiimage imagenamed also i confirmed that the 2x image is loading when run on the retina simulator update the above code works the artifacts i was seeing were caused by additional transforms done by the consumer of the images this question could be deleted since it is not really a question anymore or left for posterity,['ios'] +135351,how do i return xml from a stored procedure i created a stored procedure that returns xml and i would like to also return that xml in a method i createdi am having two issues first after doing some searching it is not advised to use executescalar because it truncates strings over 2033 charactersso i found a function called executexmlreader but in visual web developer 2010 express that runs on net 40 c it is throwing the error systemdatasqlclientsqlcommand does not contain a definition for executexmlreader and no extension method executexmlreader accepting a first argument of type systemdatasqlclientsqlcommand could be foundhere is my stored procedurecreate procedure dbogetreport reportdate dateasselect from reporttblwhere reportdate reportdatefor xml auto elementsset nocount onreturnhere is my methodusing systemdatausing systemdatasqlclient connect sqlconnection conn new sqlconnectiondata sourcelocalhost user idfoo passwordfoo initial catalogdatabase1 connopen create command sqlcommand cmd new sqlcommanddbogetreport conn cmdparametersaddwithvaluereportdate 3242011 cmdcommandtype commandtypestoredprocedure datareader rd cmdexecutexmlreader this is where error is occuring also it is throwing an error for datareader as well saying there is no type of namespace with that name rdread string s rdreadouterxml also dont know if this is how i should return the xmlsecond in addition to the executexmlreader issue i do not know if returning a string is the proper way of returning xml in the first place is there another object type i should convert it to or another function i should usethank you in advance,"['c#', '.net']" +135361,any way to get your sqlite db off iphone i would like to analyze the data that i have in my iphone app after doing some tests and the data is in a sqlite database is there any way for me to be able to copy it off of the iphone back to my laptop i am not aware of any mechanisms that allows me filesystem style access,['iphone'] +135372,how to query sphinx for an exact matching phrase it seems that sphinx is searching the documents word by word i do not know how to search the documents for an exact phrase i tried sph match all sph match phrase but all search the documents word by word i am using it in my php applicationhow do i query sphinx to match an exact stringheres my codesphinx new sphinxclientmode sph match phrasesphinxsetserver127001 9312sphinxsetlimits01sphinxsetmaxquerytime50sphinxsetmatchmodemodesphinxsetfieldweightsarrayname 100sphinxsetarrayresulttrueresult sphinxquerylorem ipsum dolor sit amet consectetur adipiscing elitprint rresultthe return result is thisarray error warning status 0 fields array 0 name 1 company 2 image 3 price attrs array total 0 total found 0 time 0 words array lorem array docs 0 hits 0 ipsum array docs 0 hits 0 dolor array docs 0 hits 0 sit array docs 0 hits 0 amet array docs 0 hits 0 consectetur array docs 0 hits 0 adipiscing array docs 0 hits 0 elit array docs 0 hits 0 as you can see sphinx is searching the documents word by word,['php'] +135404,aspnet mvc controller created for every request very simple question are controllers in aspnet created for every http request or are they created at application startup and reused throughout requests for some particular http request only the requested controller will created is that right if my previous assumptions are correct can i depend on it i want to create database context entity framework that will live only for one request if i create it as a property initialized in controllers constructor is it granted that new instance of context will be created on for every request,['.net'] +135405,google maps thisplaying a route according to google maps i can plan a route that crosses over several waypoints it is explained herenow the api wants me to add the waypoints like thislocation waypointsso waypoints is an array wich i have to assign to the location parameter but from what ive seen in the demo they fill the array with strings of the locations what i was wondering if it was possible to pass the latitude and longitude instead of the stringsupdate this is the part where i try to create a route i have put the same value in location throughout the entire loop for now but id does not work if i use variable values neitherfunction calcroute var waypts for var i in owtstoresspotstoredatamap wayptspush location new googlemapslatlng123 336 stopovertrue consolelogwaypts var request origin new googlemapslatlng5082788 326499 destination new googlemapslatlng5082788 326499 waypoints waypts optimizewaypoints true travelmode googlemapsdirectionstravelmodedriving directionsservicerouterequest functionresponse status if status googlemapsdirectionsstatusok directionsthisplaysetdirectionsresponse,['javascript'] +135415,linker warnings while building application against mysqlconnectorclibmysqlclientmysql c api i am trying to build mysqlconnectorc from sourceper instructions here and statically link against the library in my application however i am getting the following warnings and i was wondering if anyone has any ideas as to why this ispathtoliblibmysqlclientamf packco in function unpack dirnamemf packctext0x90b warning using getpwnam in statically linked applications requires at runtime the shared libraries from the glibc version used for linkingpathtoliblibmysqlclientalibmysqlco in function read user namelibmysqlctext0x2b06 warning using getpwuid in statically linked applications requires at runtime the shared libraries from the glibc version used for linkingpathtoliblibmysqlclientamf packco in function unpack dirnamemf packctext0x916 warning using endpwent in statically linked applications requires at runtime the shared libraries from the glibc version used for linkingpathtoliblibmysqlclientaclientco in function mysql real connectclientctext0x305c warning using getaddrinfo in statically linked applications requires at runtime the shared libraries from the glibc version used for linkingpathtoliblibmysqlclientalibmysqlco in function mysql server initlibmysqlctext0x2f9b warning using getservbyname in statically linkedapplications requires at runtime the shared libraries from the glibc version used for linkinghere are some of the relevant argsflagsfor building the library cmake is being passed in the followingg unix makefiles dcmake install prefixpathtomyinstallroot dcmake c flagsm64 dcmake cxx flagsm64 for building the applicationcflags cflags werror wall ggdb gdwarf2ldflags ldflags static ggdb gdwarf2,['mysql'] +135418,how to speed up the processing of a large csv using ruby for a project i need to parse some pretty large csv files the contents of some of the entries is stored in a mysql database i am trying to speed this up using multithreading but up to now this only slows things downi parse a csv file up to 10gb and some of these records aprox 5m out of a 20m record csv need to be inserted into a mysql database to determine which record needs to be inserted we use a rethis server with sets that contain the correct ids referencessince we process around 30 of these files at any given time and there are some dependencies we store each file on a resque queue and have multiple servers handling these prioritized queuesin a nutshellclass worker def selfperformfile csvparsereachfile do line next unless check line with rethisline a objectafind or initialize by referencelinereference aobject bsdestroy all aupdate attributesline end endthis works scales nice horizontally more csv files more servers but larger csv files pose a problem we currently have files that take over 75 hours to parse this way there are a number of optimizations i thought of alreadyone is cutting down on the mysql queries we instantiate ar objects while an insert with plain sql if we know the objects id is much faster this way we can probably get rid of most of ar and maybe even rails to remove overhead this way we cannot use a plain mysql load data since we have to map the csvs records to other entities that might have different ids by now we combine a dozen legacy databases into a new databasethe other is trying to do more in the same time there is some io wait time network wait time for both rethis and mysql and even while mri uses green threads this might allow us to schedule our mysql queries at the same time as the io reads etc but using the following codeclass worker def selfperformfile csvparsereachfile do line next unless check line with rethisline create or join threadline do myline a objectafind or initialize by referencemylinereference aobject bsdestroy all aupdate attributesmyline end end def selfcreate or join threadline threadjoin if threadpresent thread threadnewline do myline yield myline end end endthis slowly slows down the process when i ps au it starts off at 100 cpu but as time progresses it goes down to just 23 at that moment it does not insert new records at all it just appears to hangi have straced the process and at first i see mysql queries pass by after a while it appears it is not executing my ruby code at all could be a deadlock it hung after parsing the last line of the csv but the process kept on running at 5 cpu and did not quit or something i read here i am using rails 238 ree 187201002 on ubuntu 1010 any insights on how to handle large numbers of threads or maybe why not to use threads here at all is greatly appreciated,"['ruby-on-rails', 'ruby']" +135421,c if realloc is used is free necessary when using realloc is the memory automatically freed or is it necessary to use free with realloc which of the following is correctsituation aptr1 reallocptr1 3 sizeofintsituation bptr1 reallocptr2 3 sizeofintfreeptr1ptr1 ptr2,['c'] +135431,prompt dialog in windows forms i am using systemwindowsforms but strangely enough do not have the ability to create themhow can i get something like a javascript prompt dialog without javascriptmessagebox is nice but there is no way for the user to enter an input,"['c#', '.net']" +135432,loading environment modules within a python script is there a way for a python script to load and use environment modules ossystemmodule load x does not work since it executes them in a subshell at least i think that is whats happening,['python'] +135435,does ie9 support 3d css transforms has anyone run tests for running 3d css transforms on internet explorer 9if so have they been successfuli cannot find any information on it of course chromesafarifirefox are already adding support for it some wicked new 3d css syntaxtranslate3dx y z translatezz move the element in x y and z and just move the element in z positive z is towards the viewer unlike x and y the z value cannot be a percentagescale3dsx sy sz scalezsz scale the element in x y and z the z scale affects the scaling along the z axis in transformed childrenrotatexangle rotateyangle rotate3dx y z anglethe first two forms simply rotate the element about the horizontal and vertical axes angle units can be degrees deg radians rad or gradians grad the last form allows you to rotate the element around an arbitrary vector in 3d space x y and z should specify the unit vector you wish to rotate around weall normalize it for youperspectivepthis function allows you to put some perspective into the transformation matrix for an explanation of p see below normally perspective is applied via the webkitperspective property but this function allows you to get a perspective effect for a single element with something likewebkittransform perspective500px rotatey20degmatrix3da this function allows you to specify the raw 4a4 homogeneous transformation matrix of 16 values in columnmajor order have fun with thattaken from here,"['html', 'css']" +135457,detect if a jquery object is on the page or not given a jquery object j i need to know if it represents something that is already on the page or if it is something that has not yet been put on the page for example if i have thisj idofsomethingalreadyonthepageorj pwhere is pancake housepappendtothisisalreadytherethen i have something on the page and i do not need to put it on the page but if i just have thisj pi will cook you some eggs margiepthen i would need to append it before it is on the pagethe question is how do you ask j if it is on the page or not i know two ways the work well enoughsee if it has a parent jparentlength 0 implies that it is on the pagesee if it has a valid index jindex 1 implies that it is on the pagei can see the first one failing if j is the html or possibly body i am happy to ignore those two pathological cases i cannot think of any way that the second approach would failis there a standard technique for asking if a jquery object is on the page or not i do not care if j is visible,['jquery'] +135460,pointers and memory scope i have been programming c for a while but still pretty new to c and i am sometimes getting confused of the way the c is handling the memoryconsider following valid c snippetconst char stringvoid where is this pointer variable located in the memory const char s where is this text data located in the memory and when the program allocates memory for it s hello world return sint mainvoid printf s string return 0i am asking what exactly is going on in the memoryis not the pointer variable s a local variable or where is the pointer variable stored in the memory also where is the text constant hello world stored in memory is not this considered to be local variable which isnt accesible after function returnsbasically what kind of variables data are consider to be in local scope of the functions ceases to be accessible after function returnsi hope you understand what i am trying to say d i think i have lot to learn about compilers and executables so feel free enlighten me,['c'] +135462,how does nodejs handle persistent connections without websockets i am really new to nodejs and i am sorry if i sound naive about some stuff and i have been digging into the source code of the example chat applicationhowever i am having trouble understanding one thing i know that websockets helps handle persistent fullduplex bidirectional connections but how does nodejs manage a persistent connection in the aforementioned chat application without the use of websockets and if nodejs can handle a persistent bidirectional connection what exactly is the function of integrating something like socketio in node,['javascript'] +135467,how can i escape single or double quotation marks in css i have the following html codediv idworkingtouch medivdiv idnotworkingdo not touch medivand i have this cssworkinghoverafter content nice touch color 0c6notworkinghoverafter content i said do not touch me color c30 this code is working fine my example is here my problem is that when i use double quotes for i said do not touch me i get a warning cssnotworkinghoverafter content i said do not touch me color c30 warning messagewarning found unclosed string so how exactly can i escape single or double quotes in css,"['html', 'css']" +135479,use xcode for developing web pages i want to know if i can develop a web page in xcode if yes how what is the main difference between a normal web page and a web page for an iphone ipod or ipad where should i start is it possible to develop web pages if yes how,"['iphone', 'objective-c']" +135507,is there a clean way to avoid calling a method on nil in a nested params hash i am interested in getting the nested name parameter of a params hash calling something likeparamssubjectnamethrows an error when paramssubject is empty to avoid this error i usually write something like thisif paramssubject paramssubjectnameis there a cleaner way to implement this,"['ruby-on-rails', 'ruby']" +135510,why is sysmaxint sysmaxint 100 001 in python why is sysmaxint sysmaxint 100 001 in python,['python'] +135515,python how to get information about a function when information about a type is needed you can usemy list dirmy listgets add class contains delattr delitem delslice doc eq format ge getattribute getitem getslice gt hash iadd imul init iter le len lt mul ne new reduce reduce ex repr reversed rmul setattr setitem setslice sizeof str subclasshook append count extend index insert pop remove reverse sortordirmy list36getsappend count extend index insert pop remove reverse sortnow in the documentation of python information can be found about these functions but i would like to get info about these functions in the terminalcommandlinehow should this be done,['python'] +135530,retrieving list items from requestpost in djangopython in my requestpost i am getting a query dictionary one of the items in this dictionary is a list with multiple items pass idegi want to retrieve each of the values in pass id and store in a new list can you suggest the code for this,['python'] +135543,uilabel auto resize on basis of text to be shown i am working on an application in which i am required to autoresize the text area on basis of text to be thisplayedfirstly i am not sure for this either i should use uilabel logically is the best choice for thisplaying static text which is in my case or uitextviewhow i wish to use iti want to simply init my label or text view for that matter with textinstead i define the frame first and then restrict my text in that areaif you can suggest the right solution that will be a great helpi went through documentation and other references but did not find much which could help me here or i could have overlooked it,"['ios', 'objective-c']" +135558,why does not the program crash when i call a member function through a null pointer in c include iostreamusing namespace stdclass apublic void mprint coutn testing null pointer int main a a null amprint return 0i am getting output as testing null pointer can anyone please explain why this program is printing the output instead of crashing i checked it on dev c and acc compiler both gave same result,['c++'] +135561,convert html to docx in c i want to convert a html page to docx in c how can i do it,['c#'] +135589,how do i propagate database changes to my edmx file i generated an edmx file from database i want to know if i make changes to my database schema then how will those changes be reflected in my entity data model designer diagram i made changes to my database schema but found the changes did not appear in my entity data model designer diagram can someone explain to me how to propagate database schema changes to my entity data model designer diagram,['c#'] +135594,get class of generic my class starts withpublic abstract class lastactionheroh extends heronow somewhere in the code i want to write hclass but that is not possible like stringclass or integerclass is can you tell me how i can get the class of the generic,['java'] +135603,access a remote directory from c i am trying to access a remote network share from a c program in aspnet what i need is something likefunction downloaddirname directory this is the part i do not know how to do for dir in directory downloaddir for file in directory copyfilefilemy problem is that the directory requires a username and password for access and i do not know how to provide them thanks for any help you can offer,"['c#', 'asp.net']" +135604,capybaraselemium how to initialize database in an integration test code and make it visible in rails application configurationintegration tests for rails project using rspec capybara selemium driver sqlite databasesituationi had few integration tests with capybara and default rack test driver they create a user registration for devise gem directly in database then they login and test a scenario using capybara dsl like a user would doproblemi tried to change a driver to selenium to test javascript code as well now the tests fail because application does not see a user registration that the tests createdinvestigationit looks like selenium driver works differently with transations so changes made in a test are invisible in the web application possible solution make involveconfiguse transactional fixtures false databasecleanerstrategy truncation,['ruby-on-rails'] +135617,java find out whether function was called with varargs or array is there a way to find out whether a java function or a constructor that takes varargs was actually called with varargs or with an arraysay i have the followingpublic class mycompositeobjects myobject objects mycompositeobjectsmyobjects objects thisobjects arrayscopyofobjectsobjectslength or just thisobjects objects the constructor may be called with a single myobject argument which may change later and if i do not copy the array in the constructor those changes will apply to the member variable objects as well right however if the constructor is called with several myobjects there is no other reference to the array to change it later outside the class so i could assign it directly can i tell inside the constructor or generally any function that takes varargs how it was callednb is there a specific name for this is it simply an anonymous array,['java'] +135618,watin systemiofilenotfoundexception interopshdocvw i have just started to receive the following error when running my watin testssystemiofilenotfoundexception could not load file or assembly interopshdocvw version1100 cultureneutral publickeytokendb7cfd3acb5ad44e or one of its dependencies the system cannot find the file specifiedi have searched the web and tried the following solutions none of which workwatin error could not load assemblycan anyone assist,['.net'] +135630,python is it possible to make a class iterable using the standard syntax i have inherited a project with many large classes constituent of nothing but class objects integers strings etc i would like to be able to check if an attribute is present without needed to define a list of attributes manuallyis it possible to make a python class iterable itself using the standard syntax that is i would like to be able to iterate over all of a clas attributes using for attr in foo or even if attr in foo without needing to create an instance of the class first i think i can do this by defining iter but so far i have not quite managed what i am looking fori have achieved some of what i want by adding an iter method like soclass foo bar bar baz 1 staticmethod def iter return iterattr for attr in dirfoo if attr2 however this does not quite accomplish what i am looking for for x in foo printxtraceback most recent call last file stdin line 1 in moduletypeerror classobj object is not iterableeven so this works for x in foo iter printxbarbaz,['python'] +135654,sql server was not found or was not accessible what is the problem belowa networkrelated or instancespecific error occurred while establishing a connection to sql server the server was not found or was not accessible verify that the instance name is correct and that sql server is configured to allow remote connections provider named pipes provider error 40 could not open a connection to sql serverdescription an unhandled exception occurred during the execution of the current web request please review the stack trace for more information about the error and where it originated in the code exception details systemdatasqlclientsqlexception a networkrelated or instancespecific error occurred while establishing a connection to sql server the server was not found or was not accessible verify that the instance name is correct and that sql server is configured to allow remote connections provider named pipes provider error 40 could not open a connection to sql serverhow can this be solved,['asp.net'] +135660,php xpath endswith possible duplicatehow to use xpath function in a xpathexpression instance programatically i am trying to find all of the rows of a nested table that contain an image with an id that ends with imgproductimagei am using the following query trtdaimgendswithid imgproductimagei am getting the error xmlxpathcompopeval function endswith not foundmy google searches i believe say this should be a valid queryfunction whats the actual function i am looking for if it is not endswith,['php'] +135671,i need a help to understand this code actually this is the first time i see a code like thisclass a public static void mainstring args outer forint i0i10i forint j0j10j ifj i systemoutprintln continue outer systemoutprint i j systemoutprintln two lines i do not understandouter forint i0i10i this seems similar to for eachcontinue outer i know that continue will break the loop and continue the next turn but what will do in this situaton,['java'] +135691,uitableview editdone button i have a tableview and navigation bar on the top i have a edit button on the left of my navigation bar with the following line of code selfnavigationitemleftbarbuttonitem selfeditbuttonitemwhen i click on the edit button it changes to done button all is fine so far where do i add code if i want to do a small operation when the done button is clicked,['iphone'] +135692,pycharm and filters for external tools i am trying out pycharm for django development and so far am extremely happy my team strictly follows pep8 formatting and we use the pep8 command line program to check to make sure our code conformsi have configured an external tool command to run pep8 and it works good i see the capability to create filters that will cause the output to be parsed into something pycharm can use i have read the docs and searched google but cannot find an example to make this work docs are i am using pycharm 12 and the output filter i am using looks like thisfile pathlinecolumnexample output looks like thishomemattsettingspy1330 e261 at least two spaces before inline commenthomemattsettingspy2080 e501 line too long 126 characterswhat would be even more awesome is if this could be run each time the file is saved,['python'] +135693,how to override nested blocks in jinja2 if i define a block inside a block in a jinja template and extend it how do i reference the nested block in the child template,['python'] +135728,showing all errors and warnings update 2i have now removed the following from the php filephp error reporting e all i have set thisplay erros in phpini as followsthisplay errors onerror reporting is set to the following in phpinierror reporting e all e strictafter restarting apache i still get no errorswarningsupdate 1i have changed error reporting in phpini fromerror reporting e all e deprecatedtoerror reporting e all e strictafter which i restarted apache egetcinitdapache2 restartbut the page will still not thisplay errorswarnings of any kindoriginal questionthe following script is generating an warning because the err being inside the if statement why is this warning not being thisplayed on the php page in a web browser i have to look at apache logs to see the warning also if i delibarately change the insert into to delete into it does not thisplay an error on the php page why are the errors not thisplaying on the actual php pagephp error reporting e all html head titletitle link relicon typeimagepng hreffaviconico php if serverrequest methodpost err array if empty postthisplay name err thisplay name field is required if empty postemail err email field is required if empty postpassword err password field is required if err try dbh new pdo mysqlhostlocalhostdbnamedatabase1 user pass dbh setattribute pdoattr errmode pdoerrmode exception sth dbh prepare delete into table1 thisplay name email password values thisplay name email password sth bindparam thisplay name postthisplay name pdoparam str 100 sth bindparam email postemail pdoparam str 100 sth bindparam password postpassword pdoparam str 100 sth execute sth dbh prepare delete into table2 username status users id values username status users id strstatus 1 sth bindparam username postthisplay name pdoparam str 100 sth bindparam status strstatus pdoparam int 1 sth bindparam users id postreferer pdoparam int 1 sth execute dbh null catch pdoexception e echo e getmessage header location serverphp self exit else foreach post as key val formkey htmlspecialcharsval else formthisplay name formemail formpassword head body php foreach err as line div styleerrorphp echo line div php h1registerh1 form methodpost referers idbr input typetext namereferer br br namebr input typetext namethisplay name valuephp echo formthisplay name br br emailbr input typetext nameemail valuephp echo formemail br br passwordbr input typetext namepassword valuephp echo formpassword br br input typesubmit valueregister form bodyhtml,['php'] +135739,html5 video player behavior on iphone and ipod in safari web apps on the iphone and ipod if a youtube video is embedded in a web page the user can touch the video and the video will start playingathe ios media player slides in and the video plays full screen in landscape orientation once the video has finished playing the ios media player slides back out revealing the web page where the video was embedded using the html5 video tag the user can touch the video and the video will zoom to full screen and start playing in whatever the current device orientation is once the video has finished playing the user must tap once to bring up the player controls and then tap done in order to return to the web pageunfortunately uploading my videos to youtube is not an option for this application and i have not found an html5 video player that returns to the website after the video is finished playing i would prefer either that the video player exhibits the same behavior as the youtube embedded videos or that the video plays inline forcing inline video is possible in a customized uiwebview but unfortunately that is not an option as this is meant to be a web app not a native app additionally the video property webkitplaysinline does not workare there any html5 video players that can replicate the embedded youtube video behavior am i missing any obvious javascript workarounds is there a method to tell the window that the video is finished playing without user interactioneditthanks to jan this problem is solved working code follows along with a list of mistakesnotesdoctype htmlhtml langenheadmeta charsetutf8 titlescratchpadtitleheadbodyvideo idvideo source srcmoviemp4 typevideomp4 videoscript typetextjavascriptdocumentgetelementbyidvideoaddeventlistenerendedfunctiondocumentgetelementbyidvideowebkitexitfullscreenfalsescriptbodyhtmlmistakes i made1 forgot to add an id in the video tag2 testing for webkitsupportsfullscreenai could not ever get that property to test as true a comment in code in this forum post says note webkitsupportsfullscreen is false while the video is loadingbut i was unable to create a condition in which it returned true3 completely missed this stackoverflow post,['iphone'] +135747,generate random 5 characters string i want to create exact 5 random characters string with least possibility of getting duplicated what would be the best way to do it thanks,['php'] +135775,how to run arbitrary code after django is fully loaded i need to perform some fairly simple tasks after my django environment has been fully loadedmore specifically i need to do things like signalthisconnect some django signals that are setup by my third party library by default and connect my own signals and i need to do some monkey patching to add convenience functions to some django models from another libraryi have been doing this stuff in my django apps init py file which seems to work fine for the monkey patching but does not work for my signal thisconnecting the problem appears to be one of timingfor whatever reason the third party library always seems to call its signalconnect after i try to signalthisconnect itso two questionsdo i have any guarantee based on the order of my installed apps the order of when my apps init py module is loadedis there a proper place to put logic that needs to run after django apps have been fully loaded into memory,['python'] +135781,android swipe leftright gesture detection was trying to add this gesture function to my first program and almost every search i did came to this threadandroid basic gesture detectioni was able to get it working but in my case i am not sure if it is 100 correctin my layout i have 3 horizontal linearlayouts each one has 5 buttons so it is 3 columns of 5 buttons according to the thread i had toattach your gesture listener to all the views you add to the main layoutthat means for all the 15 buttonsbuttonsetontouchlistenergesturelistenercould not i just say that the linearlayouts with the buttons are the ones looking out for the swipe gestures or because they are hidden on the back of the buttons this cannot be donebecause i have another layout i want to implement with this and it has even more buttons so just looking for a simpler way of detecting on my screen for swipe right left if it does exists thank you in advance,['android'] +135790,find the default application name for a given file in linux is there a way to ask any xdg services or gtk services which application is the default application for a given filei realize that xdgopen will in fact launch the correct application however i want to be able to thisplay the applications name in a context menu so that when the user clicks on the menu item it will then launch xdgopen which will launch that appon osx i can use launchservices for thisdef getdefaultdarwinapplicationpath import launchservices import coredata import urllib url coredatacfurlrefurlwithstring fileurllibquotepath os status app ref appurl launchserviceslsgetapplicationforurlurl launchservicesklsrolesall none none if os status 0 return apath app refas pathname name ospathbasenameapathreplaceapp return namethe hope is that there is something similar on linux i can use a builtin python module would be best but even screen scraping would work,['python'] +135801,verifying signature on android inapp purchase message in python on google app engine the sample application on the android developers site validates the purchase json using java code has anybody had any luck working out how to validate the purchase in python in particular in gaethe following are the relevant excerpts from the android inapp billing example program this is what would need to be converted to python using pycrypto which was rewritten to be completely python by google and is the only security lib available on app engine hopefully google is cool with me using the excerpts below private static final string key factory algorithm rsaprivate static final string signature algorithm sha1withrsastring base64encodedpublickey your public key herepublickey key securitygeneratepublickeybase64encodedpublickeyverified securityverifykey signeddata signaturepublic static publickey generatepublickeystring encodedpublickey try byte decodedkey base64decodeencodedpublickey keyfactory keyfactory keyfactorygetinstancekey factory algorithm return keyfactorygeneratepublicnew x509encodedkeyspecdecodedkey catch public static boolean verifypublickey publickey string signeddata string signature if constsdebug logitag signature signature signature sig try sig signaturegetinstancesignature algorithm siginitverifypublickey sigupdatesigneddatagetbytes if sigverifybase64decodesignature logetag signature verification failed return false return true catch return false,"['python', 'android']" +135826,css selector based on element text possible duplicatecss 3 content selector is there a way to select an element in css based on element textielitextfoolifoolilibarlithat probably does not worki expect the answer is no but thanks in advanceedit also only need to support chrome,['css'] +135858,is there a commonly used rational numbers library in java i am looking for a java library which represents fractions rational numbers for example if i want to store the fraction 13 then it will not be saved as 03 which will lose its accuracyhere is some of the functionality i expect finding in such a librarygetnumeratorgetdenominatoraddrational r1 rational r2 subtractrational r1 rational r2 multiplyrational r1 rational r2 dividerational r1 rational r2ispropergetcommondenominatorcollectionrational rationalsgetsimplifiedi can implement such a library by myself though i was wondering whether something similar already existsedit it would also be nice if the library implements in addition to the above some number theory algorithms such as getegyptianfractionssum etc,['java'] +135870,python multiprocessing poolmap for multiple arguments in the python multiprocessing library is there a variant of poolmap which support multiple argumentstext testdef harvestertext case x case0 return text strxif name main pool multiprocessingpoolprocesses6 case raw dataset poolmapharvestertextcasecase 1 poolclose pooljoin,['python'] +135881,writing to stdin from php in linux i want to run a gnome zenity progress bar window from php how zenity works is like thislinuxshell zenity thisplay 01 progress textbacking up percentage01050100so the first command opens the zenity progress bar at 0 percent zenity then takes standard input numbers as the progress bar percentage so it will go from 10 to 50 to 100 when you type those numbers ini cannot figure out how to get php to type in those numbers though i have triedexeccmdecho 10echo 50andhandle popen cmd w fwrite handle 10 anddescriptorspec array 0 arraypipe r stdin is a pipe that the child will read from 1 arraypipe w stdout is a pipe that the child will write toh proc opencmd descriptorspec pipesfwritepipes1 10but none of them updates the progress bar in what way can i mimic the effect of the stdin on the linux shell to get zenity to update its progress bar,['php'] +135887,closure in java 7 what is closure it is supposed to be included in java 7 closures were thiscussed for inclusion in java 7 but in the end were not included ed can anyone please provide me with some reliable references from where i can learn stuff about closures,['java'] +135892,how to handle too long index names in a rails migration with mysql i am trying to add an unique index that gets created from the foreign keys of 4 associated tables users universities subject names subject types add index studies user id university id subject name id subject type id unique truemysqls limitation for the index name causes the migration to stop here is the error messageindex name index studies on user id and university id and subject name id and subject type id on table studies is too long the limit is 64 charactershow can i handle this can i use an alias,"['mysql', 'ruby-on-rails']" +135899,switching trial and pro builds with android apps in eclipse how to make it less painful i have an application for android which comes in two forms a trial version and a paid pro version the two versions coexists in android market and have different package names let us call them comapptrial and comapro they share the same codebase when i have to switch between trial and pro builds in eclispe i have to spend no less than 20 minutes each time editing the code to make it build the correct version my procedure looks like thisrename package name in androidmanifestxml also rename app versionname and versioncodeclick on main package name comapro if pro was the lastest build and now i want to make a trial build and select refactorrename check update references and rename subpackages and let eclipse do the renamingafter this comes the hard part in my code many files still import the old package name comapro instead of being automatically changed to comapptrial in some cases eclipse adds those references during the renaming for no apparent reasons there are no references to this specific package from within a given java file i have to manually edit all the instances my question ishow do i make this procedure less time consuming i also have been using netbeans where there is a handy support for ifdefs aka abilities which really makes switching between builds a breeze eclipse unfortunately has no support at least no builin support for ifdefsany suggestions would be greatly appreciatedps for the reference i am using eclipse ganymede version 342 but also tried a newer version it does the same,['android'] +135914,search for awhole word matcha with sql server like pattern does anyone have a like pattern that matches whole words onlyit needs to account for spaces punctuation and startend of string as word boundaries i am not using sql full text search as that is not available i do not think it would be necessary for a simple keyword search when like should be able to do the trick however if anyone has tested performance of full text search against like patterns i would be interested to hear editi got it to this stage but it does not match startend of string as a word boundarywhere dealtitle like azazpitazaz i want this to match pit but not spit in a sentence or as a single word eg dealtitle might contain a pit of despair or pit your wits or a pit or a pit or pit or just pit,['sql'] +135924,php domdocument adds headers with doctype declaration i am adding a b hash to each link via the domdocument class dom new domdocument domloadhtmloutput a tags domgetelementsbytagnamea foreacha tags as a value agetattributehref asetattributehref value b return domsavehtmlthat works fine however the returned output includes a doctype declaration and a head and body tag any idea why that happens or how i can prevent that,['php'] +135935,when i build for archive in xcode 4 where does the file go when i build for archive in xcode 4 where does the file go as in where on my computer is the archived app savedthanks,['ios'] +135942,how does the c runtime system know when objects go out of scope i was wondering how the c runtime system detects when an object goes out of scope so thatit calls the destructor accordingly to free up the occupied memorythanks,['c++'] +135943,compare if two variables reference the same object in python how to check whether two variables reference the same objectx a b cy x x and y reference the same objectz a b c x and z reference different objects,['python'] +135945,how to create a non rectangular window form in c is there any way of creating no rectangular window form such as circle or elipse in c or net i saw these unique windows form shapes and they look really neat in several installations i have seenalso is there any thisadvantage in using this kind of design for non standard forms such as sustainability crashes etc,"['c#', '.net']" +135946,string in python with my unicode python 32 r3288445 feb 20 2011 212902 msc v1500 32 bit intel on win32type copyright credits or license for more information str version a typestr versionclass str print str versiona unicode version adecodeutf8traceback most recent call last file pyshell3 line 1 in module unicode version adecodeutf8attributeerror str object has no attribute decode what the problem with my unicode string,['python'] +135956,why is the javalangthread class in java not marked final by the designers what is the essence of allowing the user to create thread by extending the thread class when we can achieve the same functionality by implementing runnable and pass it to the thread constructor,['java'] +135962,multiple itemssource collection bindings how can i binds multiple collections of different types to an itemssource of an itemscontrolusing a single binding works fineitemscontrol itemssourcebinding foo but when i try a compositecollection the items from foo are not thisplayed itemscontrol itemscontrolitemssource compositecollection collectioncontainer collectionbinding foo compositecollection itemscontrolitemssource itemscontrol,['c#'] +135966,my first app error invalid start tag linearlayout why it was working perfectly but then i made some minor edits and now it is not working heres the main layout xml file it gives an error in line 3xml version10 encodingutf8linearlayout xmlnsandroid androidorientationhorizontal androidlayout widthfill parent androidlayout heightfill parent linearlayout androidlayout width0dip androidlayout heightfill parent androidorientationvertical androidlayout weight6 textview androidlayout widthfill parent androidlayout height0dip androidlayout weight2 androidbackgroundf00 androidtextstringyellow androidtextcolorf androidgravitycenter horizontal textview androidlayout widthfill parent androidlayout height0dip androidlayout weight1 androidbackgroundf androidtextstringhelo androidtextcolor0 androidgravitycenter horizontal textview androidlayout widthfill parent androidlayout height0dip androidlayout weight1 androidbackgroundf00 androidtextstringyellow androidtextcolorf androidgravitycenter horizontal linearlayout linearlayout androidlayout width0dip androidlayout heightfill parent androidorientationvertical androidlayout weight4 textview androidlayout widthfill parent androidlayout height0dip androidtextstringblue androidlayout weight3 androidtextcolorf androidbackground0ff textview androidbackgroundf androidtextstringhelo androidlayout widthfill parent androidlayout height0dip androidtextcolor0 androidlayout weight1 textview androidlayout widthfill parent androidlayout height0dp androidlayout weight1 androidtextcolorf androidtextstringyellow androidbackgroundf00 textview androidlayout widthfill parent androidlayout height0dp androidlayout weight1 androidtextstringblue androidbackground0ff androidtextcolorf linearlayoutlinearlayout,['android'] +135967,printing list in python properly so i have a listx 3 band i want the output to bex 3 bhow can i do this in pythonif i do strx 3 b i get one with quotes but i do not want quotes,['python'] +135969,java hash algorithms fastest implementations i want to know what is the best and fastest implementation of hash algorithms for java especially md5 and sha2 512 sha512 or 256 i want a function to get a string as an argument and return the hash as the result thak youedit this is for getting mapping each url to a unique hash since md5 is not that reliable in this area i am more interested in finding the best fastest implementation for sha2 algorithms note that i know even sha2 might produce the same hash for some urls but i can live with that,['java'] +135989,java class execution problem javalangclassnotfoundexception below is what i tried in linux terminal compiled testjava run testclass and got an error then i tried the same command with classpath option and cp option but also failedtestpackage cat testjava package testpackagepublic class test param args public static void mainstring args todo autogenerated method stub systemoutprintlnmay i take your order testpackage javac testjava testpackage java testpackagetestexception in thread main javalangnoclassdeffounderror testpackagetestcaused by javalangclassnotfoundexception testpackagetest at javaneturlclassloader1runurlclassloaderjava217 at javasecurityaccesscontrollerdoprivilegednative method at javaneturlclassloaderfindclassurlclassloaderjava205 at javalangclassloaderloadclassclassloaderjava321 at sunmisclauncherappclassloaderloadclasslauncherjava294 at javalangclassloaderloadclassclassloaderjava266could not find the main class testpackagetest program will exittestpackage java cp testpackagetestexception in thread main javalangnoclassdeffounderror testpackagetestcaused by javalangclassnotfoundexception testpackagetest at javaneturlclassloader1runurlclassloaderjava217 at javasecurityaccesscontrollerdoprivilegednative method at javaneturlclassloaderfindclassurlclassloaderjava205 at javalangclassloaderloadclassclassloaderjava321 at sunmisclauncherappclassloaderloadclasslauncherjava294 at javalangclassloaderloadclassclassloaderjava266could not find the main class testpackagetest program will exittestpackage java classpath testpackagetestexception in thread main javalangnoclassdeffounderror testpackagetestcaused by javalangclassnotfoundexception testpackagetest at javaneturlclassloader1runurlclassloaderjava217 at javasecurityaccesscontrollerdoprivilegednative method at javaneturlclassloaderfindclassurlclassloaderjava205 at javalangclassloaderloadclassclassloaderjava321 at sunmisclauncherappclassloaderloadclasslauncherjava294 at javalangclassloaderloadclassclassloaderjava266could not find the main class testpackagetest program will exittestpackage but if i remove the package testpackage and recompile the source code the resulting class file is executed welltestpackage cat testjavapackage testpackagepublic class test param args public static void mainstring args todo autogenerated method stub systemoutprintlnmay i take your order testpackage javac testjavatestpackage java testmay i take your ordertestpackagewhats wrong with my code or execution command please help methank you,['java'] +136008,mvc requirehttps and redirect if not https i have read thru many of the questions on aspnet mvc requirehttps but cannot find the answer to this question how do you make the requirehttps attribute switch the url to https if it was not https to start withi have this codepublic actionresult dosomething return viewanotheractionrequirehttpspublic actionresult anotheraction return viewbut i get an error saying the requested resource can only be accessed via sslthe mvc futures project has a similar attribute requiresslredirect true but that is outdated now what is the equivalent in mvc 2when someone types in the url or the url i need them to be automatically redirected to the url edit this is the sequence of eventsthe url is called from another website they redirect their users to this url with a responseredirect or similar dosomething then tries to return anotheraction but fails with the error message the requested resource can only be accessed via ssl,['c#'] +136014,uniform html templating language it seems like every web framework has its own pet template language ruby has eruby pythons django uses the django template language haskell has heist and hamlet javas got jsp and then there is phpmy question is has anyone tried creating one templating language to rule them all are there any such templating languages that at least have some widespread support amongst the varying web frameworks,['html'] +136024,adding an oneoutoftwo not null constraint in postgresql if i have a table in postgresqlcreate table education id integer references profilesid finished yearvalue not null started yearvalue qualification text schoolname text studiedat integer references organizationsid primary key idi need to make a constraint so that either schoolname or studiedat needs to not be null one of them has to have information in ithow do i do this,['sql'] +136027,sending sms to multiple people in android i want to know if there is anyway that i can send sms to multiple number of people using the smsmanager i know that i can run a loop through the contacts and send sms individually but i figured that there may be a way to do thisthe code i use is given belowsmsmanagergetdefaultsendtextmessagephone nos nullmsggettexttostring sentpi deliveredpips i have tried using as a separator but the only thing that happens is that it sends an sms only to the first person in the listfor the benefit of people who are seeing this late its not possible to send sms to multiple people as bill mote has pointed out if there was such a thing possible there would have been an api which would have taken a listofnumbers as an argument so the only possible solution is to have an iterator for the numbers and send them one at a time,['android'] +136065,replacing rn with php i have a post form which inserts my text in a mysql databasei use post text mysql real escape stringhtmlspecialchars posttextand want to replace the rn which was automatically addedi tried text str replacern texttext str replacern texttext str replacern texttext str replacern texttext str replacern texttext str replacern texttext str replacern texttext str replacern textbut rn is always included in my database entrieshow can i fix this,"['php', 'mysql']" +136076,how to encode the plus symbol in url the url link below will open a new google mail window the problem i have is that google replaces all the plus sign in the email body with blank space it looks like it only happens with the sign any suggestions on how to remedy this i am working the aspnet web pagetf0tosusome subjectbodyhi therehello therein the body email hi therehello there will show up as hi there hello there,['asp.net'] +136082,accessing a mappers counter from a reducer i need to access the counters from my mapper in my reducer is this possible if so how is it doneas an examplemy mapper ispublic class countermapper extends mappertexttexttexttext static enum testcounters test override protected void maptext key text value context context throws ioexception interruptedexception contextgetcountertestcounterstestincrement1 contextwritekey value my reducer ispublic class counterreducer extends reducertexttexttextlongwritable override protected void reducetext key iterabletext values context context throws ioexception interruptedexception counter counter contextgetcountercountermappertestcounterstest long countervalue countergetvalue contextwritekey new longwritablecountervalue countervalue is always 0am i doing something wrong or is this just not possible,['java'] +136101,heroku postgres error pgerror error relation organizations does not exist activerecordstatementinvalid i am having a problem deploying my rails app to heroku where this error is thrown when trying to access the app pgerror error relation organizations does not exist activerecordstatementinvalidselect aattname format typeaatypid aatypmod dadsrc aattnotnullfrom pg attribute a left join pg attrdef d on aattrelid dadrelid and aattnum dadnumwhere aattrelid organizationsregclass and aattnum 0 and not aattisdroppedorder by aattnumanybody have any ideas this is a first for me especially because i have been working with heroku for a year on other apps and have not see anything like this of course everything works on local sqlite thanks in advance for any helpmark,['ruby-on-rails'] +136104,nested class vs implements actionlistener are there any benefits or drawbacks to creating a nested class that implements actionlistenerpublic class foo foo somethingaddactionlistenernew buttonlistener private class buttonlistener implements actionlistener public void actionperformedactionevent e versus implementing actionlistener in the main class itselfpublic class foo implements actionlistener foo somethingaddactionlistenerthis public void actionperformedactionevent e i have seen both examples quite often and just want to know if there is a best practice,['java'] +136111,60 million entries select entries from a certain month how to optimize database i have a database with 60 million entriesevery entry containsiddatasourceidsome datadatetimei need to select entries from certain month each month contains approximately 2 million entries select from entries where time between 20100401 0 and 20100501 0query takes approximately 15 minutesi would also like to select data from certain month from a given datasourceidtakes approximately 20 secondsthere are about 50100 different datasourceidsis there a way to make this faster what are my optionshow to optimize this databasequeryedit there is approx 60100 inserts per second,"['mysql', 'sql']" +136123,how can i convert class files to java files possible duplicateshow do i decompile java class filesclass file to java file conversion i want to convert a class file to its java equivalent what can i do to see the codejava file,['java'] +136127,ninject wcf extension argumentnullexception using nettcp binding i have a wcf 4 service with 2 endpoints configured to use wshttpbinding and nettcpbinding i am hosting the service within iis 75 using was and am using the ninject wcf extension to di into my service my service works fine when i use the wshttpbinding endpoint to call my service but fails when i use the nettcpbinding when i look in my application event log i get the following error outlined belowi have tried debugging the problem in vs2010 but am getting nowhere fast with this i donat want to have to remove ninject from my wcf service if at all possible i understand that i could just use wshttpbinding but i this is an internal service and i want to get the performance gains that nettcpbindings providewebhost failed to process a request sender information systemservicemodelservicehostingenvironmenthostingmanager30180123 exception systemservicemodelserviceactivationexception the service profileservicesvc cannot be activated due to an exception during compilation the exception message is cannot be nullparameter name root systemargumentnullexception cannot be nullparameter name root at ninjectinfrastructureensureargumentnotnullobject argument string name in cprojectsninjectninjectsrcninjectinfrastructureensurecsline 20 at ninjectresolutionextensionsgettiresolutionroot root iparameter parameters in cprojectsninjectninjectsrcninjectsyntaxresolutionextensionscsline 37 at systemservicemodelactivationservicehostfactorycreateservicehoststring constructorstring uri baseaddresses at systemservicemodelservicehostingenvironmenthostingmanagercreateservicestring normalizedvirtualpath at systemservicemodelservicehostingenvironmenthostingmanageractivateservicestring normalizedvirtualpath at systemservicemodelservicehostingenvironmenthostingmanagerensureserviceavailablestring normalizedvirtualpath end of inner exception stack trace at systemservicemodelservicehostingenvironmenthostingmanagerensureserviceavailablestring normalizedvirtualpath at systemservicemodelservicehostingenvironmentensureserviceavailablefaststring relativevirtualpath process name w3wp process id 8656is there anybody out there that may be able to help with this problem any help on this one would be much appreciated,['.net'] +136129,jquery to change form action i have two buttons in a form and two different pages have to be called when they are clicked when button1 is clicked then page1 must be loaded and when button2 is clicked then page2 must be loaded i know how to do this in javascript but i have no clue about how to do this in jquerycan any one help me,['jquery'] +136130,view reuse in fragments android i am trying to save my view states in my fragment but i am concerned i make be leaking my activity here is what i am doingoverridepublic view oncreateviewlayoutinflater inflater viewgroup container bundle state ifmview null view oldparent mviewgetparent ifoldparent container viewgroupoldparentremoveviewmview return mview else mview inflaterinflateridfragview null return mview i am concerned because i know all views hold onto a context and i do not know if it is the activity context or application context if inflated from the inflater perhaps it would be a better idea to pragmatically create the view and set its attributes using getactivitygetapplication rather than use the inflater i would appreciate any feedback on thisthanksedit confirmed activity leak although this code works great do not do it,['android'] +136137,calling a gwt java function from an html script tag i have a gwt project and i would like to add a script tag to the main html file of the gwt project that calls a java function located in my client codeaccording to the documentation i should add something like the following html tagscript typetextjavascript myfunctionscriptwhere commycompanymyprojectclientmyclass is the class path and myfunction is the java function i would like to callwhen i try this with the following implementation of myfunction nothing happenspublic void myfunction htmlpanel panel new htmlpaneli have been called rootpanelgetaddpanelthat is myfunction is not being calledbut when i make the same call from a jsni method then it worksis it maybe not possible to do the call from an html script or am i doing something wrongthanks,"['java', 'javascript']" +136160,truncate foreign key constrained table why does not a truncate on mygroup workeven though i have on delete cascade set i geterror 1701 420 cannot truncate a table referenced in a foreign key constraint mytestinstance constraint instance ibfk 1 foreign key groupid references mytestmygroup iddrop database mytestcreate database mytestuse mytestcreate table mygroup id int not null auto increment primary key engineinnodbcreate table instance id int not null auto increment primary key groupid int not null datetime datetime default null foreign key groupid references mygroupid on delete cascade uniquegroupid engineinnodb,['mysql'] +136168,how can i get android wifi scan results into a list i know how to get a of android wifi scans but i can not figure out the best way to make a list adapter out of them i would like to just bind ssid and bssid from a of scans to text1 and text2samples of what i have been doing wifistartscan get list of the results in object format like an array listscanresult results wifigetscanresults loop that goes through list for scanresult result results toastmaketextthis resultssid resultlevel toastlength shortshowandprivate void filldatafromdb cursor scancursor dbfetchallscans startmanagingcursorscancursor create an array to specify the fields we want to thisplay in the list only title string from new string wifidbadapterkey bssid wifidbadapterkey ssid and an array of the fields we want to bind those fields to in this case just text1 int to new int ridtext1 ridtext2 now create a simple cursor adapter and set it to thisplay simplecursoradapter scansdb new simplecursoradapterthis rlayoutscan row scancursor from to setlistadapterscansdb,"['java', 'android']" +136173,usage of union inside a class i saw some code as followsclass a private union b rep a next no variables of this anonymous defined void func a p new a pnext null why p has a member variable of next i have compiled the above code with vs2010 without any errorhere is the questionwhy p has member variable next union b rep a next as far as i know this is an anonymous union without even defining a variable how can we access the member variables inside this union like that,['c++'] +136177,thisplaying one div on top of another i have some html with two divsdiv div idbackdropimg alt srcbackdroppng div div idcurtain stylebackgroundimageurlcurtainpngbackgroundposition100px 200px height250px width500pxnbspdivdivi want the second div curtain to appear on top of backdrop the two divs are the same size however i am not sure how to position the second div on top of the otherthank you for your help,"['html', 'css']" +136200,arbitrary length bytes to int builtin in python i am looking for a function that takes an arbitrary length bytes object and converts it to an int obviously endianness is a required parameter to this functioni am certain i encountered a builtin on either bytes or int but cannot find it anymore there are plenty of answers on similar questions involving use of struct and manually enumerating the individual byte values is there a builtin that does this conversion without using clike assumptionsmodulesdef intbytes little int,['python'] +136203,trying to get footer to stick to bottom here is my sitei have tried everything to get the footer to stick to the bottom but nothing wont work other than doing a set height in css on the tag cright but i dont want to do that since dynamic content would go in there can anyone see what im missing or doing wrong thanks,"['html', 'css']" +136231,how do i set the contents of a calayer to a cgimageref i want to set the contents of a calayer to an image the calayer has a contents property the documentation on that property says that a layer can set this property to a cgimageref to thisplay the image as its contents but the property takes an id so in xcode i get the following issuesemantic issue incompatible pointer types assigning to id from cgimageref aka struct cgimage how can i assign a cgimageref to the contents property when it only takes an id what am i missing here,['objective-c'] +136256,session handling in aspnet i am trying to find out how to destroy a aspnet session when the user navigates away from my sitei am using globalascx application file and use session end event its working fine when i click logout button but when i close browser directly its not using global file after 20 minitues i used in webconig file as sessionstate modeinproc timeout20sessionstateplease help me augustine,['asp.net'] +136259,sha1 encryption i have database with following fields id q id text session and i have already 2 record there i want to encrypt each line because every line is unique id session text of course w digestsha1hexdigestidq idtextsession this is not working,['ruby-on-rails'] +136275,mysql alter ignore table add unique what will be truncated i have a table with 4 columns id type owner description id is auto increment primary key and now i want toalter ignore table my table add unique type ownerof course i have few records with type apple and owner apple co so my question is which record will be the special one to stay after that alter table the one with smallest id or maybe the one with biggest as the latest inserted,['mysql'] +136276,where does the x comment prefix in eclipse come from i was just wandering why is the prefix x as far as i know its used for notesreminders or at least this is what i use it for and that is what the people on most of the links i googled use it forso does anyone know where the x prefix come from,['java'] +136280,xml document to string whats the simplest way to get the string representation of a xml document orgw3cdomdocument that is all nodes will be on a single lineas an example fromroot atrgea b156brootthis is only a tree representation in my code it is a orgw3cdomdocument object so i cannot treat it as a stringtoroot atrgea b156b rootthanks,['java'] +136331,android signed apk showing incomplete i have signed the application using eclipses export wizard when i published this users started complaining that the application is behaving incorrectly basically the apk did not have necessary images audio and hence showing incorrect behaviour some information on application and signing which i have tried i have a lite version and paid version both are signed with same keypair the lite version is working perfectly and full version is giving errori have tried to export the signed packages again and tried to install directly in device instead of uploading to market same behaviour ie lite apps works correctly and full version not properboth full version and lite version uses shared library code base is identical differences as followsfull version has 5 times the resources of lite version the lite version apk is 26mb and full version is 104mb in full version i have 170 images mostly pngs of 510 kb and 55mp3 files in lite version i have 45 images and 15 mp3sfull version has lvl license verification implemented and lite version doesnot once lvl is passed the code simply calls the library classif i use eclipse to build and deploy full version to phone or emulator it works correctly i guess this build and deploy will use debug key for signingi have error handling within the code to show code to show a dummypic a question mark if resource is missing all my images are replaced with that question mark just to add this dummypic is in the library and all other resourcesimages are in full version i have checked the resources by renaming the signed apk file to zip thanks to nickt for suggesting this approach all resource files audio and images are present in the zip file any help is appreciated the application is already in market and hence would like to minimise adverse impact removed lvl still same errortried commenting the lvl code and directly calling the intent still same error by commenting the lvl the code base for lite and full version is identical only the resouce count is different the full version has all the resources of lite version 5times the resource update this is how i temporarily fixed it i removed the library project and moved all classes and resources to the implementation project full version now it is working as said this is a temp fix only i still need to know how i can fix this with library else i will have to create a lot of duplication of code,['android'] +136335,game architecture i have a question about a xna game i am making but it is also a generic question for future games i am making a pong game and i do not know exactly what to update where so i will explain better what i mean i have a class game paddle and ball and for example i want to verify the collisions between the ball with the screen limits or the paddles but i come across 2 approaches to do thishigher level approach make paddle and ball properties public and on the gameupdate check for collisionslower level approach i supply every info i need the screen limits and paddles info to the ball class by parameter or in a common public static class and on the ballupdate i check for collisionsi guess my question in a more generic way isdoes an object need to know how to update and draw itself even having dependencies from higher levels that somehow are supplied to themoris better to process it at higher levels in gameupdate or gamedraw or using managers to simplify codei think this is a game logic model question that applies to every game i do not know if i made my question clear if not feel free to ask,['c#'] +136337,manipulating css styles of pseudo elements in firebug is is possible to manipulate css of pseudo element before or after using firebug i know these are specific elements that are handled internally by browsers but firebug has more low level access i suppose so maybe it has the ability to manipulate these as well,['css'] +136354,what continuous integration tool suits for php possible duplicatessetting up a deployment build ci cycle for php projectsrecommended server for continuous integration for php project hello guysrecently i faced the need for continuous integration for some of my projects and to my surprise there exist many tools for this purpose like cruisecontrol with its plugin phpundercontrol xinc written in php hudson with lots of functionality etc also i studied the matter and as far as i understood installing and configuring such a tool takes quite a long time thus it would be very thissapointing to spend much time for setting everything up and get to know that the tool lacks some crucial functionality i address to those who have some experience with this matter and can give a piece of reasonable advice thank you,['php'] +136368,operator precedence expression evaluation for the following code snippet i get the output as 1 i want to know how it camevoid mainint x10y20z5iixyzprintfdi,['c'] +136375,devise with rails 3 and remote true i have a problem using devise with an ajax login i am using the remote true option and the jquery version of the javascript helpers ehen the user enters the correct informations my createjserb inside the sessions view is rendered this is ok because i can redirect my user using js in this file but when an error occurs eg the user enters false information only the flash messages are in the response with an error code 401 unauthorized so no view or createjserb or sth else is renderedbut i want to handle this message by thisplaying it on the side so that the users gets some feedback whats wrongi also tried to implement my own custom controller with respond to js and playing with the recall method of the warden authentication but it does not workdoes anybody know some best practices to solve this problem or should i avoid this helper methods and just use pure jquery for the ajax callsthxtux,"['javascript', 'jquery', 'ruby-on-rails']" +136380,quickly enter commandline parameters for visual studio debugging i want to change my commandline arguments and then debug my executablewith the default visual studio ui this takes me several tortuous mouse and keyboard actionsproject right click configuration properties debugging command arguments type args enter f5is there a way to make this common action as easy as other common operations for example searching all files for a pattern which goescntlshiftf type search pattern enterfor example is there an way to create a custom edit box to allow quick access to the debug commandline arguments or a way to have a keybinding pop up a simple debug dialog where the args can be entered and debugging started directly egaltf5 type args enteri am using c and visual studio 2010 express thanks,['c++'] +136389,android mapview always causes an outofmemoryerror in nested elements i am trying to create a mapview currently without any overlays inside some nested elementsit is basically something like scrollview relativelayout relativelayout mapview comgoogleandroidmapsmapviewandroidididmapviewandroidlayout width420pxandroidlayout height300pxandroidclickablefalseandroidapikeykeyseems fine for me there is nothing more that i do with it on startup but it always causes the following0404 133833910 warndalvikvm13628 threadid1 thread exiting with uncaught exception group0x400155600404 133833996 errorandroidruntime13628 fatal exception main0404 133833996 errorandroidruntime13628 javalangoutofmemoryerror0404 133833996 errorandroidruntime13628 at android maps conflict avoidancecomgooglegooglenavmapmapresizemapjava13680404 133833996 errorandroidruntime13628 at android maps conflict avoidancecomgooglegooglenavmapmapresizemapjava13370404 133833996 errorandroidruntime13628 at comgoogleandroidmapsmapviewonmeasuremapviewjava5900404 133833996 errorandroidruntime13628 at androidviewviewmeasureviewjava83130404 133833996 errorandroidruntime13628 at androidwidgetrelativelayoutmeasurechildhorizontalrelativelayoutjava5810404 133833996 errorandroidruntime13628 at androidwidgetrelativelayoutonmeasurerelativelayoutjava3650404 133833996 errorandroidruntime13628 at androidviewviewmeasureviewjava83130404 133833996 errorandroidruntime13628 at androidwidgetrelativelayoutmeasurechildhorizontalrelativelayoutjava5810404 133833996 errorandroidruntime13628 at androidwidgetrelativelayoutonmeasurerelativelayoutjava3650404 133833996 errorandroidruntime13628 at androidviewviewmeasureviewjava83130404 133833996 errorandroidruntime13628 at androidwidgetscrollviewmeasurechildwithmarginsscrollviewjava10720404 133833996 errorandroidruntime13628 at androidwidgetframelayoutonmeasureframelayoutjava2500404 133833996 errorandroidruntime13628 at androidwidgetscrollviewonmeasurescrollviewjava2960404 133833996 errorandroidruntime13628 at androidviewviewmeasureviewjava83130404 133833996 errorandroidruntime13628 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava31380404 133833996 errorandroidruntime13628 at androidwidgetframelayoutonmeasureframelayoutjava2500404 133833996 errorandroidruntime13628 at androidviewviewmeasureviewjava83130404 133833996 errorandroidruntime13628 at androidwidgetlinearlayoutmeasureverticallinearlayoutjava5310404 133833996 errorandroidruntime13628 at androidwidgetlinearlayoutonmeasurelinearlayoutjava3090404 133833996 errorandroidruntime13628 at androidviewviewmeasureviewjava83130404 133833996 errorandroidruntime13628 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava31380404 133833996 errorandroidruntime13628 at androidwidgetframelayoutonmeasureframelayoutjava2500404 133833996 errorandroidruntime13628 at androidviewviewmeasureviewjava83130404 133833996 errorandroidruntime13628 at androidviewviewrootperformtraversalsviewrootjava8390404 133833996 errorandroidruntime13628 at androidviewviewroothandlemessageviewrootjava18590404 133833996 errorandroidruntime13628 at androidoshandlerthispatchmessagehandlerjava990404 133833996 errorandroidruntime13628 at androidoslooperlooplooperjava1230404 133833996 errorandroidruntime13628 at androidappactivitythreadmainactivitythreadjava36470404 133833996 errorandroidruntime13628 at javalangreflectmethodinvokenativenative method0404 133833996 errorandroidruntime13628 at javalangreflectmethodinvokemethodjava5070404 133833996 errorandroidruntime13628 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava8390404 133833996 errorandroidruntime13628 at comandroidinternaloszygoteinitmainzygoteinitjava5970404 133833996 errorandroidruntime13628 at dalviksystemnativestartmainnative method0404 133834027 warnactivitymanager60 force finishing activity packagehome0404 133834527 warnactivitymanager60 activity pause timeout for historyrecord405336d0 packagehomedo you have any idea why this is and what i can do to get rid of it i cannot take it out of that view as it is the place where i need itthank you,['android'] +136402,sql get numerical day of monthquarter using sql server 2005how can i get the numerical day of the month and day of the quarter in a querydeclare date datetimeset date getdateselect datepartdy date as dayofyear something as dayofquarter something as dayofmonth datepartdw date as dayofweekthanks in advance,['sql'] +136406,logcat would not show up i am somewhat new to android and i am setting up my view perspectives that i am fairly anal about i want to have logcat showing on my normal editing perspective but i go into windowshow viewother views select android and logcat and the window does not show up sometimes it grayed out if i switch to the ddms perspective it shows up just fine what am i doing wrongthanks,['android'] +136442,html preprocessor is there a html preprocessor that can do simple page processing similar to server side includes but produce a static set of html pages,['html'] +136472,aspnet mvc delete action link with confirm td htmlactionlinkdelete deleteuser new routevaluedictionarynew unameitemusername new onclick return confirmare you sure you want to delete this user tdin globalasaxcsroutesmaproute deleteuser accountaspxdeleteuseruname new controller account action deleteuser uname in actioncontorllercspublic actionresult deleteuserstring uname delete userthe value of uname in the controller is being passed is empty string,['asp.net'] +136483,nsinternalinconsistencyexception reason uiviewcontroller loadviewfromnibnamedbundle loaded the gameview nib but the view outlet was not set this is not the same situation as the multitude of other similar questions here terminating app due to uncaught exception nsinternalinconsistencyexception reason uiviewcontroller loadviewfromnibnamedbundle loaded the gameview nib but the view outlet was not setyou might be thinking do as it says connect the files owner to the view in ib but the thing is i do not even have a gameviewxib in my project or even in the project directory i do have a gameviewcontrollerm and matching gameviewcontrollerxib in my project using that gameviewcontroller is what brings up this error but i do not understand where it gets the idea to try and load gameviewxib should not it use gameviewcontrollerxib instead if i grep my project directory i do see it referenced from userinterfacestatexcuserstatestringfilelocalhostusersbemmudropboxb2iphonevalleystoryvalleystorygameviewxibstringthis mentioned file does not exist i might have had a file with that name before and renameddeleted it but it is not being referenced to from anywhere that i can see in ib did i manage to confuse xcode,['iphone'] +136494,why does work with strings in java java cannot do operator overloading but works okay for string and integer and some other classes how is this possibleupdatewhy does this workinteger i 4integer p 5systemoutprintlnip prints 20,['java'] +136496,how to tell if a date is between two other dates in python i have the following codes if date in start end print in betweenelse print nodate start and end are all variables with the format of 11 what should i do to have it print out the right result i tried date as 102 start as 314 and end as 117 and it is print no which means it is not running right i guess have to format them to a date format and then compare them thanks for any help,['python'] +136513,do i need to pin an anonymous delegate i am calling copyfileex from a c application with an anonymous delegate being passed into the lpprogress routine parameter in order to get notifications on the file copy progressmy question is does the anonymous delegate need to be pinned and why or why notin addition does the answer change ifcopyfileex was not blockingif i passed in a delegate that was not anonymousthanks,['c#'] +136522,what is purpose of around create callback in rails model when is around create callback code executed in what situations we should use it,['ruby'] +136531,why should i not make a class serializable i am storing some objects in my viewstate and i was wondering if there are any thisadvantages to making a class serializable is it bad practice to make all of the classes serializable,"['c#', 'asp.net']" +136538,php simple html dom parser find string i am using php simple dom parser but it does not seem to have the functionality to search for text i need to search for a string and find the parent id for it essentially the reverse of normal usageanyone know how,"['php', 'html']" +136542,xpath xml namespaces and java i have spent the past day attempting to extract a one xml node out of the following document and am unable to grasp the nuances of xml namespaces to make it workthe xml file is to large to post in total so here is the portion that concerns mexml version10 encodingiso88591 standalonenoxfdl xmlns xmlnscustom xmlnsdesigner xmlnspecs xmlnsxfdl globalpage sidglobal global sidglobal xmlmodel xmlnsxforms instances xformsinstance idmetadata form metadata metadataver version10 metadataverdate date day05 monthjul year2005 metadataverdate title documentnbr number2062 prefixarmyda scopearmy suffix longtitlehand receiptannex number longtitle titlethe document continues and is well formed all the way down i am attempting to extract the number attribute from the documentnbr tag three from the bottomthe code that i am using to do this looks like this locates the document number information in the file and returns the form number return files selfdeclared number throws invalidformexception thrown when xpath cannot find the documentnbr element in the file public string getformnumber throws invalidformexception try xpath xpath xpathfactorynewinstancenewxpath xpathsetnamespacecontextnew xfdlnamespacecontext node result nodexpathevaluatequery form number doc xpathconstantsnode ifresult null return resultgetnodevalue else throw new invalidformexceptionunable to identify form catch xpathexpressionexception err throw new invalidformexceptionunable to find form number in file where query form number is my xpath expression and xfdlnamespacecontext implements namespacecontext and looks like thispublic class xfdlnamespacecontext implements namespacecontext override public string getnamespaceuristring prefix if prefix null throw new nullpointerexceptioninvalid namespace prefix else if prefixequalsxmlconstantsdefault ns prefix return else if customequalsprefix return else if designerequalsprefix return else if pecsequalsprefix return else if xfdlequalsprefix return else if xformsequalsprefix return else return xmlconstantsnull ns uri override public string getprefixstring arg0 todo autogenerated method stub return null override public iterator getprefixesstring arg0 todo autogenerated method stub return null i have tried many different xpath queries but i keep feeling like this should workprotected static final string query form number globalpageglobalxmlmodelxformsinstancesinstance form metadatatitledocumentnbrnumberunfortunately it does not work and i continually get a null returni have done a fair amount of reading here here and here but nothing has proved sufficiently illuminating to help me get this working i am almost positive that i am going to facepalm when i figure this out but i am really at wit is end as to what i am missingthank you for reading through all of this and thanks in advance for the helpandy,['java'] +136549,conversion of a varchar data type to a datetime data type resulted in an outofrange value i have the following piece of inline sql that i run from a c windows serviceupdate table name set status cd 2 sdate cast03282011 180340 as datetime bat id 33acff9be2b4410ebaaf417656e3c255 cnt 1 attempt date cast03282011 180340 as datetime where id 1855when i run this against a sql server database from within the application i get the following errorsystemdatasqlclientsqlexception the conversion of a varchar data type to a datetime data type resulted in an outofrange value the statement has been terminatedbut if i take the piece of sql and run it from sql management studio it will run without issueany ideas what may be causing this issue,['sql'] +136565,mozbackgroundclip text in mozilla is there a good way to implement this in mozilla i have done it successfully in webkit using webkitbackgroundclip text i have been trying to implement it into firefox with no success mdn has it listed as mozbackgroundclip but there is no text attribute the finalized css3 attribute is backgroundclip but i have not been able to find if text is a valid option across engines or if it is a webkit only thing thanks in advance for the clarification,['html'] +136602,does function definition order matter in the script below does the order in which items are declared matterfor example if the add action points to a function that has not yet been defined does it matter or should the function declaration always precede any code in which its calledadd actionloadcategoriesphp my admin initfunction my admin initdo something,['php'] +136605,jquery using sortable with dynamically added elements live refresh i have a form idform that have a span classcon and inside the span i have many divs that needs to be sortable form idform span classcon div classuistatehighlightitem 1div div classuistatehighlightitem 2div spanformi am using the sortable function to make div sortable spansortable connectwith conthisableselectioni am dynamically adding with divs inside but sortable is not recognizing newly added spans i know there is a refresh option for sortable that is supposed to work like live and reognize newly added content but i do not see how i can use it with this examplecheck click on the button to add more spans with divs inside you will see that you can sort div that were initially in dom but not newly added ones,['jquery'] +136616,javascript not running on jsfiddlenet the code below works on a live site but i cannot get it to run on the site jsfiddle see this for examplecan anyone tell me why it is not working on jsfiddleon the console it logs referenceerror filist is not defined and referenceerror myselectlist is not definedthe code works as you can see when it is embedded here as snippetfunction betterselectosellist thisobjselectlist osellist thisobjselectlistonchange thisselectionchangedbetterselectprototypeclear function thisobjselectlistoptionslength 0betterselectprototypefill functionavalues thisclear for var i 0 i avalueslength i thisobjselectlistoptionsi new optionavaluesi betterselectprototypefind functionstrtofind bselect var indx 1 thisobjselectlistoptionsselectedindex 1 for var i 0 i thisgetcount i if thisobjselectlistoptionsitext strtofind indx i if bselect thisobjselectlistoptionsselectedindex i return indxbetterselectprototypegetcount function return thisobjselectlistoptionslengthbetterselectprototypeselectionchanged function alertselection changedvar myselectlist nullwindowonload function myselectlist new betterselectdocumentgetelementbyidthelistfunction filist myselectlistfillone two three four fivefunction findit myselectlistfinddocumentgetelementbyidtxttofindvalue trueform action methodpost select multiplemultiple nameselect1 idthelist stylewidth 152px height 226px select br input namebutton1 typebutton valuefill the list onclickfilist input namebutton4 onclickmyselectlistclear typebutton valueclear the list br input namebutton2 onclickalertmyselectlistgetcount typebutton valuewhats the count br input nametext1 typetext idtxttofind input namebutton3 typebutton valuesearch onclickfindit form,"['javascript', 'html']" +136637,why is std used by experienced coders rather than using namespace std possible duplicatewhy is using namespace std considered a bad practice in c the other day when i asked a question someone replied saying if someone asks a question show them the right way to do it instead of using namespace std which i thought was a bit weird as using namespace std is way easier but i guess i am failing right now as i am a beginner coder and you guys know betterso i guess my question iswhy std instead of using namespace stdthanks,['c++'] +136646,jquery ajax request from local filesystem windows file i am trying to do an ajax request to get the contents of httplocalhost running on windows wamp serverthe script is running from something like thisfilecmypathindexhtmli am just using a standard ajax request to try and get the contents of localhostajax type get url httplocalhost success functiondata alertsuccess error function data alertfailed i cannot get it to be successful though seems to be some problem with the local filesystem or something i am not too sure,['jquery'] +136684,what is an efficient way to replace many characters in a string string handling in java is something i am trying to learn to do well currently i want to take in a string and replace any characters i findhere is my current inefficient and kinda silly imo function it was written to just workpublic string convertwordstring word return wordtolowercasereplacea a replacea e replacea i replaceao u replacea12 y replacea d replacea3 o replacea o replaceall replaceall replaceall replacealla ae replacealla34 thi ran 10 runs of it and it took 8182ms so how should i proceed in changing this function to make it more efficientsolution foundconverting the function to thispublic string convertwordstring word stringbuilder sb new stringbuilder char chararr wordtolowercasetochararray forint i 0 i chararrlength i single character case ifchararri a sbappenda char to two characters else ifchararri a34 sbappendth remove else ifchararri base case else sbappendwordcharati return sbtostringrunning this function 10 times takes 518ms so i think that is efficient enough thanks for the help guys,['java'] +136692,dynamically change uitableview cell separator line color can anyone give sample code how to change the uitableview cell separator line color dynamically,"['iphone', 'objective-c']" +136700,how to schedule a job for sql query to run daily i need to know how to make an sql query run daily using sql server agent jobs with minimum required configuration settings,['sql'] +136707,how much overhead do realloc calls introduce i am using realloc in every iteration of a for loop that iterates more that 10 timesis this a good practice will realloc cause an error if it was called a lot of times,"['c++', 'c']" +136709,designing a java library with spring i am extracting some functionality from an existing program into a separate librarythis program uses spring for dependency injection and other tasks and i would like to keep using it in the library as wellthis library needs to monitor the filesystem for changes so it will kick off some kind of separate thread to do thisi do not really know what my options are for initialisation of the libraryhow do i initialise the librarys context i cannot assume that library users will make use of spring too but i can thistribute spring with the libraryhow do i manage my filesystem monitoring thread is it good design to expect the program to instantiate a main class of the library and the call init or something like that,['java'] +136720,qt project structure advice needed i am currently working on a project based on qt4qtcreator i would like to ask you for advice on how to organize my application there are 3 seperate tools each has it is own view all views are integrated in main window as nonclosable tabs i have prepare 3 views tool1view tool2view tool3vieweach tool is suppose to perform some task triggered by user actions but these are not database related operations listaddmodify at least the user is not going addmodifylist records in gui elementsi am thinking to implement each tool in 2 classesfirst class toolxview implementing the widget and all tasks related to gui changes second class toolx implementing application logic member functions of this class are triggered by view class whenever this class has to update gui elements it cals specialised functions in view class so no direct calls to widgets are made from hereview class and logic class will be linked with each other to allow 2 way communicationnow i am wondering if this is a good way to go please advice me based on your experiencei am planning to encapsulate pointer to logic class as a property of a view class and pointer to view class as a property of logic class this way i plan to integrade themshould i use signalsslots to provide comuncation or just call member functions i will have to store some data in qtsql database should i provide a seperate class for database access or just implement sepereate member function inside logic class how do you name your classes is this scheme good or should i change it thanks for help i appreciate your comments,['c++'] +136722,which should i be using urlparse or urlsplit which url parsing function pair should i be using and why urlparse and urlunparse orurlsplit and urlunsplit,['python'] +136725,why is it impossible to use the speech recorder on the android emulator i am trying to run the speech recorder that comes with the android 22 emulator the problem is that the moment i click the record buttonit aborts with an error message the application speech recorder process comandroidspeechrecorder has stopped unexpectedly please try againthe problem is that trying again does not helpnow i searched stackoverflow and i combed the entire internet and i found many reports of the same problem without any working solutionmy conclusion is that for some strange reason the android emulator is capable of using the windows audio device for output but not for inputwhy is thati know that other virtualization software eg vmware have no problem using both output and input sections of the hosts audio devicealso if speech recorder never worked for the emulator for anyone why put it theresurely this has worked for someone is there a way to make speech recorder work for me tooi am using windows xp 32bit and my avd is defined with an sd card mounted upon startupdate i followed the suggestion by klaus to try and see whether any exceptions are thrown i did so by simply typing ddmsbat at the command line to launch a standalone version of ddms with a logcat thisplay at the bottom sure enough i receive the following exception upon clicking the record button0329 141658195 erroraudiorecord303 could not get audio input for record source 10329 141658195 errorsrec jni303 initcheck error 22 0329 141658205 debugspeechrecorderactivity303 run audio capture thread0329 141658205 warndalvikvm303 threadid8 thread exiting with uncaught exception group0x4001d80329 141658215 errorandroidruntime303 fatal exception thread90329 141658215 errorandroidruntime303 javalangnullpointerexception0329 141658215 errorandroidruntime303 at comandroidspeechrecorderspeechrecorderactivity4runspeechrecorderactivityjava1920329 141658285 warnactivitymanager59 force finishing activity comandroidspeechrecorderspeechrecorderactivity0329 141658904 debugdalvikvm59 gc for malloc freed 13324 objects 656184 bytes in 197ms0329 141659915 infoarmassembler59 generated scanline 07703515104 0 0 33 ipp 47 ins at 0x20db680x20dc24 in 1247352 ns0329 141705251 debugspeechrecorderactivity303 stoprecordinghow do i proceed from here i did not write the speech recorder app so i do not know what causes the nullpointerexception at speechrecorderactivityjava line 192 i believe this has something to do with an earlier logcat messagecould not get audio input for record source 1but the question again is whywhy was not it able to get audio input for record source 1,['android'] +136777,using dynamic with unit tests i have seen a few questions on here of people asking for criticism of their unit tests i have not seem them get closed so i would like to do the same i whipped up these tests which i believe are made more readable by using dynamic but i was wondering if anyone in the so community had anything to addi know the use of dynamic is for some reason very controversial and for some reason starts religious wars amongst c developers i am really hoping to avoid that i am just trying to write some good tests to help me do my job testmethod public void testallocation searchviewstubpropertynumvaluethensetupsearchviewwelldetailtx propertyworkinginteresttaxsubtypeid presentersetupphaseandfmvvaluesphasephaseidforforrenderappraiser 10 addtheseitems new propnum pn1 can can1 mostrecentfmv 10 new propnum pn1 can can1 mostrecentfmv 10 new propnum pn1 can can1 mostrecentfmv 10 new propnum pn1 can can1 mostrecentfmv 10 new propnum pn1 can can2 mostrecentfmv 40 new propnum pn1 can can2 mostrecentfmv 40 new propnum pn1 can can2 mostrecentfmv 40 new propnum pn2 can can1 mostrecentfmv 50 new propnum pn2 can can1 mostrecentfmv 50 presenterprocesearchview itemstoprocess asserttheseitemsexist new numberoftimes 4 propnum pn1 can can1 fmvcalculated 100 new numberoftimes 3 propnum pn1 can can2 fmvcalculated 400 new numberoftimes 2 propnum pn2 can can1 fmvcalculated 500 private void addtheseitemsparams dynamic massupdatedtos foreachdynamic item in massupdatedtos itemstoprocessaddnew massfmvupdatedtonew welldetail propertynum itempropnum countyaccountnum itemcan new fmvhistory 0 itemmostrecentfmv private void asserttheseitemsexistparams dynamic uniquetargets foreach dynamic target in uniquetargets assertareequaltargetnumberoftimes itemstoprocesscountf fpropertynum targetpropnum fcountyaccountnum targetcan ffmv targetfmvcalculated,['c#'] +136779,reading pdf annotations with itext i trying to get the contents of a pdf annotation to string so i can store that information in a database for searching purposesdoes anyone know how to accomplish this using itextitextsharp,['c#'] +136801,how can i log rails errors into a separate log file our production logs are long and contain a lot more than just errors i would like a second log file with just the errorsexceptions inis this possiblewere using rails 2xthanks,['ruby-on-rails'] +136804,c initializer lists and variadic templates i wanted to create an arraytemplate typename t typename a struct a t x 1 sizeof a a default a t t a y x t y int main a int int p 1 1 ok a a int int a int int q 1 1 3 3 error bad array initializerwhy does not it compile tested with g 46,['c++'] +136810,mysql restoring a database via mysqldump does it overwrite the different destination tables i am using mysqldump to backup a database containing several tables say tables d e f i use the following command mysqldump uuser ppassword sourcedatabase filesql to backup these tables i would like to know if i restored this backup would it overwrite other tables for example if i have a database destinationdatabase containing tables a b and c and after running the command mysql uuser ppassword destinationdatabase filesql would i lose the tables a b and c on the destination database and be left with just d e and f or would i be left with a b c d e and f with the original tables present in destinationdatabase left untouchedthanks in advancetim,['mysql'] +136814,apply a wcf attribute to all method in the service i have a custom attribute that i want to apply to each methods in my wcf servicei proceed like thismyattributevoid mymethodthe problem is that my service contains hundreds of methods and i do not want to write attribute above all of them is there a way to apply the attribute to all my methods in my serviceheres my attributes signatureattributeusageattributetargetsclasspublic class sendreceivebehaviorattribute attribute iservicebehavior ioperationbehavioredit after aliostads answeri tried thispublic void applythispatchbehaviorservicedescription desc servicehostbase host foreach channelthispatcher cthispatcher in hostchannelthispatchers foreach endpointthispatcher ethispatcher in cthispatcherendpoints foreach thispatchoperation op in ethispatcherthispatchruntimeoperations opinvoker new operationinvokeropinvoker and thatpublic void addbindingparametersservicedescription servicedescription servicehostbase servicehostbase collectionserviceendpoint endpoints bindingparametercollection bindingparameters foreach channelthispatcher cthispatcher in servicehostbasechannelthispatchers foreach endpointthispatcher ethispatcher in cthispatcherendpoints foreach thispatchoperation op in ethispatcherthispatchruntimeoperations opinvoker new operationinvokeropinvoker but it still do not work,['c#'] +136827,how to thisassemble the main function of a stripped application let us say i compiled the application below and stripped it is symbolsinclude stdiohint main printfhellonbuild proceduregcc o hello hellocstrip stripunneeded helloif the application was not stripped thisassembling the main function would be easy however i have no idea how to thisassemble the main function of a stripped applicationgdb thisas mainno symbol table is loaded use the file commandgdb info line mainfunction main not definedhow could i do it is it even possiblenotes this must be done with gdb only forget objdump assume that i do not have access to the codea stepbystep example would be greatly appreciated,['c'] +136831,what is the w thing in ruby i am referring to the w operatorconstructorwhatever you may call it used like thisw foo bar baz foo bar bazi have several questions about itwhat is the proper name of that w thing operator literal constructordoes it matter whether i use s instead of sare there any other things like this for example one that gives you an array of symbols insteadcan they be nested one w inside another w in order to create nested arrayswhere can i find documentation about it,['ruby'] +136836,multidimensional array vs onedimensional this is basically a restatement of this question java multidimensional array vs onedimensional but for ci have a set amount of elements that make sense to store as a gridshould i use a arrayxy or a arrayxyedit oh so there are one dimensional arrayxy multidimensional arrayxy and jagged arrayxy and i probably want jagged,['c#'] +136842,how do i expand stack traces in xcode 4 xcode 4 has a really stupid feature that summarizes stack traces in the debugger by showing the first and last two items in the call stack does anyone know how to eliminate the dotted line and show the useful information,['iphone'] +136845,how did jquery implement documentready how did jquery implement documentreadyof course i can read the code but i am looking for the concept,"['javascript', 'jquery']" +136857,can you explain theese thisturbing anomalies of md5 and modulo okay the title is really very subjective but thats just what the problem is to methe background is that i want to thistribute hits of static web contents evenly about a defined number of caching servers also the delivery to clients should speed up because several domains are in use and requests are not blocking each other i also do not need a classic load balancer but generate the right links right away in my html codei also want to ensure that the same url always gets served by the same serverso i just defined a little function that returns the host to use by hashing the request url and calculates the modulo by the number of servers in usefunction pseudocode statifyurl url looks like folder1folder2filejpg return http md5url num of servers mydomaincom urli first had something like hex decoding and substring to prevent overflow in place but found out that it just works fine the way abovehowever my problem is that if i run the following test scriptfori0i10i md5 md5uniqidimicrotimerand19 resultmd52i expected an even thistribution meaning that result0 would be near the value of result1this was not the caseokay this is nothing special sofar i would have just accepted the fact that md5 is not as evenly thistributed as i thought and would have gone vor another hashing algorithm like sha1 or somethingbut i tried to reproduce the findings and found a pattern that i cannot explainthe ratio was always about 21 in fact it was the ratio was always something like 1216 to 1217sample output of some runs of the script aboveoutput was generated by echo ratio result0result1nratio 21757121534504ratio 21729411578062ratio 21726559360393ratio 21676895664225ratio 21667416128848ratio 21667115284133ratio 216791605385ratio 21658969579688ratio 21668508131769ratio 21689292821741now the weird thing was that the ratio of sums 2 equaling 1 and sums 2 equaling 0 sometimes alternatedforj 0 j100j fori0i10i md5 md5uniqidimicrotimerand19 resultmd52 var dumpresulti ran the script from the command line two sperate times and aborted it after 3 runs and it produced theese two outputsjoejoelaptophomeflimmithttpdocs php testphpphp notice undefined variable result in homeflimmithttpdocstestphp on line 6php notice undefined offset 0 in homeflimmithttpdocstestphp on line 6php notice undefined offset 1 in homeflimmithttpdocstestphp on line 6array2 0 int68223 1 int317array2 0 int136384 1 int63616array2 0 int204498 1 int95502cjoejoelaptophomeflimmithttpdocs php testphpphp notice undefined variable result in homeflimmithttpdocstestphp on line 6php notice undefined offset 1 in homeflimmithttpdocstestphp on line 6php notice undefined offset 0 in homeflimmithttpdocstestphp on line 6array2 1 int31612 0 int68388array2 1 int63318 0 int136682array2 1 int94954 0 int205046cjoejoelaptophomeflimmithttpdocs as you can see in the first one the first entry of results is always higher in the second one its the other way round same scriptstrange thing is that i can only reproduce this behaviour when i run the script several timesi wrote this small script to reproduce the swapping and generate enough measure dataforj 0 j100j fori0irand1010i md5 md5uniqidimicrotimerand19 resultmd52 var dumpresult echo ratio result0result1 result0result1 abn sleeprand25but here it only prints b never as which made me think there might be a semantic error in the script but i didnt find anyi am really stuck and this bothers me a lotso my questionscan you recommend any literature weblinks were i could read about md5 a little bit deeper including thistributions etccan you explain reproduce the behaviour do i have an error here in fact thats very likely but i cant find itcan you recommend any other algorithm that would besuitable for my use case it needs not be cryptographic or strong but fast deterministic and evenly thistributed,['php'] +136868,app offline alternative i usually place an app offlinehtm in my root directory when i am releasing a website to a production environment however sometimes if there has been a few big changes to the site i would like to click around first to make sure it is stable without allowing access to anyone other than me as far as i am aware this is not possible but i am hoping someone has a neat solutionthe solution has to include if someone has a deeplink into the site so using a defaulthtmasp page in the root would not do the trick unfortunately,['asp.net'] +136869,how should i thiscover testresource files in a mavenmanaged java project i have a project that uses the normal maven structure egmodule src main java resources test java resourcesetc under testresources i would like to keep a set of test input files for a parser i am writing then run all files in the directory through the test suite as written now the test code works from the command line but fails when run through the eclipse junit pluginfile file new filesrctestresourcesfilelisti am actually using a filenamefilter but i am trying to simplifythe problem after poking through the unit test with a debugger turns out to be that the file i am constructing points to pathtoworkspacemyprojsrctestresources whereas the actual files reside in pathtoworkspacemyprojmodulenamesrctestresources it is a maven multimodule project apparently this is not a problem when running mvn test from the command linei guess my question is twofold one am i doing this wrong i see a lot of people using the class loader to thiscover resources as in this question but i do not want all the resources of a particular type just one directory under testresources two if this is not a terrible idea in the first place do i have a configuration error eg it should work is it eclipses fault a maven problem or what,['java'] +136873,try finally block question found this question here and i cannot understand why on first case it prints coolreturn1 and on second case coolreturn how does it workthankswhat will be printedpublic void testfinally systemoutprintlnsetonetostringprotected stringbuilder setone stringbuilder buildernew stringbuilder try builderappendcool return builderappendreturn finally builderappend1 answer coolreturn1a bit more difficultpublic void testfinally systemoutprintlnsetonetostringprotected stringbuilder setone stringbuilder buildernew stringbuilder try builderappendcool return builderappendreturn finally buildernull answer coolreturn,['java'] +136892,regular expression in ios i am looking for a regular expression to match the following 100101 the meaning of this expression is that the value can increment by 001 and should be in the range 100 to 100any help,['ios'] +136900,google map error a is null i have a program that i want to use google maps for the problem is i get an error that says a is null where a is a var used in the google map api here is how i call my google mapcreates a new center location for the google map var latlng new googlemapslatlngcenterlatitude centerlongitude the options for the google map var myoptions zoom 7 maxzoom 12 center latlng maptypeid googlemapsmaptypeidroadmap creates the new map var map new googlemapsmapdocumentgetelementbyidmap canvas myoptionsand here is what my html tag looks like div id map canvasdivi get the lat and lng on page load through the url these values are passed in correctly so i know that is not the problem i think that it has to do with the var map new googlemapsmapdocumentgetelementbyidmap canvas myoptions not being correct any suggestionsedit here is the error messagea is null fromlatlngtopointanull yganull bobject zoom7 maxzoom12 more document defaultaspxlat30346317lng10546313 ffunction daundefined d break on this error function qfaf9return aiafunction sgaaicaicvb,['javascript'] +136914,c and ld preload open and open64 calls intercepted but not stat64 i have done a little shared library that tries to intercept open open64 stat and stat64 sys callswhen i export ld preload and run oracles sqlplus i can see the traces of the open and open64 calls but no traces of the stat and stat64 callsthe shared library is a single c file with all the definitions of the sys calls in itwhy does it happen that some syscalls are intercepted and others do notthanks for your help,['c'] +136915,override css for html5 form validationrequired popup how can i override the default popup for a required field on a html5 form example make sure you click the submit button to see the popupthe htmlforminput typetext namename idname placeholdername requiredrequired input typesubmit formnote you must view this with a html5 browser like google chrome or firefoxthis link does not solve my question but it might make someone think outside of the box,['css'] +136917,are parentheses allowed in css selectors in the below example i want to create a css rule that applies only to the header with the text blockhead div classgumby span classpokeyspan h3blockheadh3 h3clay rulesh3 divcan i use parentheses such as gumby pokey h3 if not what is my alternative,['css'] +136934,is there a risk in running file put contents on the same file from different php threads i know file put contents makes it really easy to append data to a file in php i would like to try using php threads to file put contents to the same log file from different php threads is there a risk in running file put contents on the same file from different php threads or will these threads happily block if the file is locked or being accessed by another threadedit found a similar question that recommends flock but the risk question does not seem to be fully addressed are these atomic write operations,['php'] +136958,python mongodb cursor iteration too slow i am actually working in a search engine projectwe are working with python mongodbi am having the following problemi have a pymongo cursor after excecuting a find command to the mongo dbthe pymongo cursor have around 20k resultsi have noticed that the iteration over the pymongo cursor is really slow compared with a normal iteration over for example a list of the same sizei did a little benchmarkiteration over a list of 20k strings 01492 secondsiteration over a pymongo cursor with 20k results 1445343 secondsthe difference is really a lot maybe not a problem with this amounts of results but if i have millons of results the time would be unacceptablehas anyone got an idea of why pymongo cursors are too slow to iterateany idea of how can i iterate the cursor in less timesome extra infopython v26pymongo v19mongodb v16 32 bits,['python'] +136964,jsonstringify change the case of the key i am consuming a web service that returns json and storing the json in a local variable the json represents a simple business object such asvar entry firstname john lastname doe the casing is like that because it matches up with the property names from the net class as per our naming conventionwhen a change a few of these properties and pass back the json the web service now expects camel case again as per our naming convention for method parameters instead of the pascal case initially returnedvar entry firstname john lastname doe this of course does not worki am using jsonstringify to send the json back to the web service as a string and i was looking to see if there was an easy way to change the key to camel case however it looks like i can only use the replacer param to work with the valuei could change the serialization of the class but lets pretend that is not an option any ideasthanks,['javascript'] +136972,how to check instanceof on an argument that is a class object i am trying to build a generic class loader i need to check classes that i load against a method argument to determine if they are of the same classthe code mostly explains what i am trying to do private static linkedlistobject loadobjectsindirectoryclass class0 file dir throws classnotfoundexception linkedlistfeature objects new linkedlistobject classloader cl new genericclassloader forstring s dirlist class class1 clloadclas try object x class1newinstance if x instanceof class0 objectsaddx catch instantiationexception ex catch illegalaccessexception ex return objects how is this achieved,['java'] +136997,html form action methodpost or methodpost is there any difference in using noncapticalized post or capitalized post in form action method i just want to strictly follow w3c html specificationthis is no difference when running in modern browsers though,['html'] +137010,cannot play mov file in videoview i am developing an application in which i have to play video from internet i am using videoview to play videowhen buffering is completed my emulator shows me an error which says that it cannot play videoi do not know what is the error,['android'] +137011,c equivalent of javas mkdirs i am trying to convert a java program to cis there a equivalent to javas mkdirs command which recursively makes folders,"['c#', 'java']" +137021,entity framework codefirst define the key for this entitytype hi i am planning to test ef code first in one of my project this is what i want actually i have three tables and the structure is as followspublic partial class app user public int id get set public string name get set public string email address get set public string password get set public int user type get set public listrole roles get set public partial class role public int id get set public string name get set public partial class user role public int user id get set public int role id get set public virtual role role get set public virtual app user app user get set in the third table there is no primary key so it gives an error while running here is the error message systemdataedmedmentitytype entitytype user role has no key defined define the key for this entitytype systemdataedmedmentityset entitytype the entityset user roles is based on type user role that has no keys definedwhy its is happening is there a solution for this,['c#'] +137037,redirect perror output to fprintfstderr if in case a system call function fails we normally use perror to output the error message i want to use fprintf to output perror string how can i do thatplease helpthanks in advancesomething like this fprintfstderr perror output string here,['c'] +137043,how does one convert a hashmap to a list in java in java how does one get the values of a hashmap returned as a list,['java'] +137047,strange classcastexception hibernate 35 glassfish hi i have a problem that i cannot solve on my own i have a war file packaged in ear and running on glassfish 301 with hibernate 35 as jpa provider i compile it with maven and deploy it with idea or manuallyevery other time i get a cast exception in my daosjavalangclasscastexception commyprojectdomainentityuser cannot be cast to commyprojectdomainentityuserother times it works perfectly fine there is no pattern in this behaviourcould someone shine some light on what is happening hereexample method where the exception was thrownat commyprojectdomaindaouserdaoimplcheckusersessionvaliduserdaoimpljava195 public user checkusersessionvalidstring sessionid user user null entitymanager em providerentitymanager try emgettransactionbegin query q emcreatequeryselect you from user you where usessionsessionid sessionid makes no difference query q emcreatequeryselect you from user you where usessionsessionid sessioniduserclass qsetparametersessionid sessionid user user qgetsingleresult emgettransactioncommit catch noresultexception ignored finally emclose return user my librariesinfo orgapachegeronimospecsgeronimojpa 20 specjar10providedinfo javaxvalidationvalidationapijar100gacompileinfo orghibernatehibernateannotationsjar351finalcompileinfo orghibernatehibernatecorejar351finalcompileinfo antlrantlrjar276compileinfo commonscollectionscommonscollectionsjar321compileinfo dom4jdom4jjar161compileinfo xmlapisxmlapisjar10b2compileinfo javaxtransactionjtajar11provided scope managed from compileinfo orghibernatehibernatecommonsannotationsjar320finalcompileinfo orghibernatejavaxpersistencehibernatejpa20apijar100finalcompileinfo orgslf4jslf4japijar152compileinfo orghibernatehibernateentitymanagerjar351finalcompileinfo cglibcglibjar22compileinfo asmasmjar31compileinfo javassistjavassistjar390gacompileinfo orghibernatehibernatevalidatorjar410finalcompileinfo orgslf4jslf4jsimplejar152testinfo mysqlmysqlconnectorjavajar5113testinfo orghsqldbhsqldbjar200test,['java'] +137063,processwaitfor never returns process process runtimegetruntimeexectasklistbufferedreader reader new bufferedreadernew inputstreamreaderprocessgetinputstreamprocesswaitfor,['java'] +137103,split variadic template arguments how do i split variadic template arguments in two halves something liketemplate int d struct a stdarray int d p q template typename t a t t p half of t q other half of t,['c++'] +137109,simple ajaxphp debugging i am testing an ajaxjqueryloaded php module and i was wondering if there is a simple way to debug this without using a full featured debuggermy very simple debugging option is to echo some data and read browser output however due to ajaxloaded modules nature output is hidden while i can return debugging data until the ajaxloaded module is running i cannot track or see program interruptions if error occursis there a way to allow output also in the ajaxloaded modules or,['php'] +137124,eclipse with tomcat eclipse modifies serverxml i use tomcat with eclipse in use tomcat installation mode my problem is that eclipse overwrites tomcats serverxml every time and deletes my crosscontexttrue elementsshould i use custom location or the eclipse setup is wrongthanks,['java'] +137129,minimizing viewstate confused by enableviewstate and viewstatemode in aspnet 40 i am trying to clean up an older aspnet webforms site that has viewstate enabled everywhere this is a performance issue huge viewstates cause noticeable submit delays but most of the forms do not really seem to need viewstate except for some complex control form data even forms with no input controls though generate big viewstates because i guess aspnet is storing all kinds of metatdata about every single server control but the visibility state etc is all controlled in code so i think i can eliminate a lotit is pretty onerous to add enableviewstatefalse to every single control in a page and created in code that does not need it so i am trying to thisable it at a pagecontrol level and selectively enable it for things that need it yes i realize this is risky but there are really just a couple big forms and a couple templates that if addressed would make a big differenceheres what i am not quite gettingif a control or page has enableviewstatefalse it its descriptor or in its tag where it is created in the parent page everything breaks because any viewstate data added in code does not work so i seem to be able to leave it enabled at the control level but set enableviewstate to false for a wrapper control in each container and then set viewstatemodetrue which ovverrides that at a percontrol levelwhat i am not getting is what happens whenviewstatemode viewstatemodeenabled andenableviewstate false for a control that contains other controlsfor a control can inner controls be enabled still with viewstatemode basically which setting has the final word when they conflict for each container i want to be able to thisable everything in a wrapper control but still ensure that1 viewstate settings in code work and2 viewstate is thisabled for all controls by default and3 i can selectively enable viewstate for subcontrolsthis seems to be confounding if i have a wrapper control in the master page that is set to enableviewstatefalse but then set a subcontrol to viewstatemodeenabled it breaks according to ms viewstatemode should supercede any outer viewstate settings yet it does not seem to work,['asp.net'] +137131,how to install or get access to sqlite3 from adb shell i need a way to install or somehow get access to sqlite3 in the adb shell i have rooted my device i have tried to find an answer but the closed i could come is why do i get a sqlite3 not found error on a rooted nexus one when i try to open a database using the adb shellbut i do not think it is good idea to push my windows sqlite3exe on a linux systemso is it possible to install the sqlite3 terminal browser somehowsolutionfrom the different comments and some asking around at androiddev irc i found a solution first i copied the database file to my desktop but fist i had to install busybox because cp is not included after that ran i into the problem that i could not pull or push from anywhere but sdcard i could then use sdcard as a middle station and pullpush my dbthen i got exhausted i really had to have my sqlite terminal explore then i got the idea to start the emulator pull the sqlite binary from systemxbinsqlite3 then remount system with rw mount o remountrw t yaffs2 devblockmtdblock3 systemand push sqlite to the sdcard and from there copy it to systemxbin now it works d,['android'] +137142,what is the difference between an ordinary exe file and the exe file generated from net windows applications what is the difference between an ordinary exe file and the exe file generated from net windows applications,['.net'] +137143,using nslog for debugging i have the following code snippet in my xcodensstring digit sender titlelabel textnslogdigiti tried to build the application and am getting the following warning message for the line nslogdigitwarning format not a string literal and no format argumentscan you advise me how i can resolve this warning message what does the message actually mean,['objective-c'] +137155,page clientvalidate object expected error cant find the validator i have a form homepageaspx containing an empty asppanel a dropdownlist letting the user pick an spfieltype on index changed my homepageaspxcs page will get the text selected and will load a user control inside the panel this user control will generate a control based on the spfieldtype chosen by the user and a button calling the validateform function my problem is that the page clientvalidate function inside the validateform cant find the validator i also tried to give a groupname but still not working when im putting the button inside my aspx page not rendering dynamically it is validating my page aspbutton idsubmitbutton textvalidate runatserver but when im rendering it dynamically cant validate the formthis is what im trying to doprotected override void createchildcontrols try fieldrenderingcontrol thiscreatefieldrenderingcontrolthisfieldtype thiscontrolsaddfieldrenderingcontrol button button new button buttonusesubmitbehavior false buttontext validatebutton buttonid validatebutton buttononclientclick validateform thiscontrolsaddbutton requiredfieldvalidator newvalidator new requiredfieldvalidator newvalidatortext newvalidatorid valide newvalidatorenableclientscript true newvalidatorenabled true newvalidatorsetfocusonerror true newvalidatorthisplay validatorthisplaydynamic newvalidatorcontroltovalidate fieldrenderingcontrolid thiscontrolsaddnewvalidator catch exception ex the createfieldrenderingcontrol function will generate a control based on the argument fieldtype chosen by the userthanks in advance,"['c#', 'javascript', 'asp.net']" +137167,django user registration form best practices django way of customizing the user creation is by adding userprofile model however when i am performing user registration i would like the user to fill all the details including the ones in the user profile as wellusing formsmodelform seems like the easiest way however i am dealing here with two modelswhat is the easiest way to accomplish thatthanks,['python'] +137173,does anyone have a useful mnemonic for implementing comparator every time i need to implement a comparator i get stuck trying to remember when i should return 1 and when 1 and i have to look it upi mean obviously 1 is less so it implies that first is less than second but whenever i say that to myself i get that nagging are you sure feeling i suspect part of my confusion comes from implementing it the other way around whenever i need a descending sortwhat do you use to remember which is which,['java'] +137185,get notified when current tab is selected again i implemented a tabactivity which implements the ontabchangelistenerthe activity will be notified on tab changes ontabchangedstring tabidis it also possible to get notified if the user selects the current tab again i would like to use this event to perform a refresh of the current tab content instead of providing a refresh button on the tab or in the options menuthat is the way i finally solved the problem solution hint was in mistersquonk answer1 define a ontabreselectlistener which must be implemented by an activity which represents a tab content and which will be notified on reselect events interface definition for a callback to be invoked when a current selected tab in a tabhost is selected again public interface ontabreselectlistener called when a current visible tab is selected again will not be invoked on tab changes void ontabreselect2 setontouchlistener for each tabwidget child in oncreate of the tabactivity from mistersquonks answerfor int i 0 i tabwidgetgetchildcount i view v tabwidgetgetchildati vsetontouchlistenerthis3 implement ontouchlistenerontouch in the tabactivity do some logic to decide if the current tab was selected again and notifiy the tabs activity see androidviewviewontouchlistenerontouchandroidviewview androidviewmotionevent overridepublic boolean ontouchview v motionevent event boolean consumed false use gettabhostgetcurrenttabview to decide if the current tab is touched again if eventgetaction motioneventaction down vequalsgettabhostgetcurrenttabview use gettabhostgetcurrentview to get a handle to the view which is thisplayed in the tab and to get this views context view currentview gettabhostgetcurrentview context currentviewcontext currentviewgetcontext if currentviewcontext instanceof ontabreselectlistener ontabreselectlistener listener ontabreselectlistener currentviewcontext listenerontabreselect consumed true return consumed,['android'] +137192,stylesheet link tagall generates reference to allcss on heroku i have stylesheet link tagall in my layoutit behaves as expected on local machine even when i run it in production environment rails s e productionby expected i mean that it emits all the links to existing stylesheets without concating them into allcss and it does not emit the link to allcssbut when i deploy it to heroku the result is the same plus a link to allcss in the beginning this is what i do not want and do not expect especially when production environment on local machine does not emit itso the question is how do i get rid of allcss link on heroku without specifying all files manuallythanks,"['ruby-on-rails', 'ruby']" +137217,use jquery ajax prefilter to inspect response data and conditionally forward to error event handler i may be way off course but i was wondering if it is possible to use the jquery prefilter functionality and analyze the response data in an ajax success and conditionally forward to the error event handler in my ajax calls based on the existence of certain elements in my returned json error messagesit would be nice if this was globally set for any ajax function in the pagemaybe this is not the best way to go about this if anyone has an alternative idea please let me knowthe prefilteronly run prefilter on ajax calls expecting json back in response would this be the right way to do this ajaxprefilter json function options originaloptions jqxhr jqxhrsuccessfunctiondata textstatus jxhr if haserrorsdata forward to error event handler ajax callajax type post data thedata somedata url theurl datatype json cache false success function data textstatus jqxhr do stuff on success error function jqxhr textstatus errorthrown i want to do this stuff if data contains errors from server thank you so much,['jquery'] +137240,why is il code packed into an exe in a c application i was trying to regenerate an exe by doing a round trip of ildasm and then ilasm on a c executable file as i understand the il file generated by ildasm is sufficient to generate exe back i am curious that why net framework is designed to use an exe file for deployment instead of deploying a il file to the users could not c compiler generate il file and the jit compiler use the il file directly as an input is it simply because operating system needs exe extension to invoke the loader or is it because of file size or performance considerationsps the question is not of practical significance i am asking this question to make my concepts more clear as i am sure i am lacking a lot,"['c#', '.net']" +137254,editing user text on the fly i would like to implements something like vbullettin or stackoverflow does when the user clicks edit the html text is converted to plain text into a textareatextarea ready for the editinghow would you implemeent something like that note i can use jqueryi would like especially know the authentication part if users clicks edit on soemone else comments there is a warningthanks,"['javascript', 'jquery']" +137311,what is the c iostream endl fiasco i was listening to a google talk by andrei alexandrescu on the d programming language when he threw out a one liner about the endl fiasco i just thought endl was the preferred way to signify the end of a line and flush the buffer for a stream why is it considered a fiasco should i not be using it in my code,['c++'] +137324,changing background colour of tr element on mouseover i want to have my table rows highlighted on mouse over but i have yet to find a way to do it that is not using javascript is this not possible in cssi have tried thistrhover background 0but that does not work using tdhover works but i want to change the background colour of the whole table rowis there a pure csshtml way to do it or am i going to have to resort to javascript,"['html', 'css']" +137328,what are the best python finite state machine implementations these are the python fsm implementations i have found so farfysom a slick fsm implementation that provides function callbacks for each stateskip montaneros fsmfsm with decoratorspythoncourse fsm tutorial welldocumented example of a fsm for parsing sentencesfsmme a graphical fsm editor w python target also see the fsmme tutorialpython fsm recipe active state code suited for text parsing tasksgof state patternatts weighted fsm in pythonpython fsm for so code golfi need to parse text file configurations and i am looking for an fsm implementation that provides the ability to munge data before inputting to the next state,['python'] +137372,android robolectric frame work instantiated activity returns null on getresource this has to do with using the robolectric framework for unit testing on android i am getting a null pointer exception on code which has no problem when running normally i am just starting on the roboelectric so it is probably pretty simple here is the calling code for testing test public void testinitutilsinitsequencenumberisrandom create an activity for reference initutils initutils new initutils do static initialization to parse questions into memory initutilsinitializeinitutils the call from roboelectric framework retreive app state appstate appstate appstate initutilsgetapplicationcontext fill in later failnot implementedhere is the method called within in initutils which crashes loads the xml into the see mquestions class member variable public static void initializequestionsactivity activity appstate appstate create xml parser xmlresourceparser questionbatch local question variable question question null retrieve the xml for parsing this returns null questionbatch activitygetresourcesgetxmlrxmlquestions parse the xml int eventtype 1 iterate through xml while eventtype xmlresourceparserend document if eventtype xmlresourceparserstart tag get the questions npe exception string strname questionbatchgetname etcis there something special i need to do for this to retrieve the resource,['android'] +137380,cakephp how to use helpers to make an image link with target blank this seems like it should be simple but i am new to cakephp maybe it is just something i should write in good ole html but was hoping to find out how do to this with cakephps html helperi just want an image link that has target blankthis is what i triedphp echo thishtmllinkthishtmlimagetmp728x90jpg arrayaltadvertisement height90 width728 arraytarget blank all in one line just broke up for ease of viewingbut when i do this i get this a href target blankltimg srcquotimgtmp728x90jpgquot altquotadvertisementquot heightquot90quot widthquot728quot gtaany help is greatly appreciatedanswer thanks decezephp image thishtmlimage tmp300x600jpg array altadvertisement height600 width300 echo thishtmllink image array target blank escape false,['php'] +137441,send binary file in http response using c sockets im trying to send a binary file png image in http responsefile filechar bufferint filelenopen filefile fopen1png rbif file returnget file lengthfseekfile 0 seek endfilelenftellfilefseekfile 0 seek setallocate memorybufferchar mallocfilelen1if buffer fprintfstderr memory error fclosefile returnread file contents into bufferfreadbuffer filelen 1 filefclosefilefreebufferchar header102400sprintfheader http11 200 okndate thu 19 feb 2009 122704 gmtnserver apache223nlastmodified wed 18 jun 2003 160558 gmtnetag 56d99892001132c580ncontenttype imagepngncontentlength inacceptranges bytesnconnection closen n filelenchar reply charmallocstrlenheaderfilelenstrcpyreply headerstrcatreply bufferprintfmsg sn replyreturn 0int sd socketpf inet sock stream 0struct sockaddr in addrbzeroaddr sizeofaddraddrsin family af inetaddrsin port htons8081addrsin addrs addr inaddr anyifbindsdaddrsizeofaddr0 printfbind errornif listensd 160 printflisten errornfor int size sizeofaddr int client acceptsd addr size if client 0 printfclient connectedn sendclient reply strlenreply 0 but my browser does not understand this what am i doing wrong exactlyupd i tried to send text data its ok but binary data fails,['c'] +137446,java write dll files from inside a jar to the hard drive i have a signed applet and i want to write out dll files which are contained in the jar from which i launch my appleti am doing this because i then want to do a systemload on the dlls as apparently you cannot load dlls from inside a jar in an applet the second issue is if you can add to the environment variables in an applet for example i want to extract my dlls to a location the hard drive and add the environment variable so systemload can find it,['java'] +137463,parsing java source code i am asked to develop a software which should be able to create flow chart control flow of the input java source code so i started researching on it and arrived at following solutionsto create flow chartcontrol flow i have to recognize controlling statements and function calls made in the given source code now i have two ways of recognizingparse the source code by writing my own grammars a complex solution i think i am thinking to use antlr for thisread input source code files as text and search for the specific patterns may become inefficient am i right here or i am missing something very fundamental and simple which approach would take less time and do the work efficiently any other suggestions in this regard will be welcome too any other efficient approach would help because the input source code may span multiple files and can be fairly complexi am good in net languages but this is my first big project in java i have basic knowledge of compiler design so writing grammars should not be impossible for mesorry if i am being unclear please ask for any clarifications,['java'] +137475,how to call a python script from php i have some code written in php but i have developed a script written in python it is possible to call this python script from the php codeif yes how can i pass parameters to the python script from the phpi have tried to find answers to this but i have not find themcan someone give me a clue,"['php', 'python']" +137476,how to dynamically remove items from listview on a button click i am working on an app that requires to remove items from a listview on a button eventi tried to remove it from arraylist and create the whole new adapter and loaded the list again but as my list is huge it will affect performance of my app so i was wondering if there is any other way by which i could remove item from my list dynamicallyi tried whatever you said guys at first i just tried to remove one item and it was working perfect but as i am increasing the number of selected items it starts giving me indexoutofboundexceptionheres my code public void onclickview view sparsebooleanarray checkedpositions new sparsebooleanarray checkedpositionsclear checkedpositions lvgetcheckeditempositions int size checkedpositionssize ifsize 0 forint i 0 i size i ifcheckedpositionsvalueati listremovenotesgetitemcheckedpositionskeyati notesnotifydatasetchanged elsehere notes is a reference to an object of simpleadapter,['android'] +137497,jquery find last occurance of a div i have 2 divs with the same id pagination one is at the top of the page the other at the bottomwhat i would like to do is find the last id so this would be the div idpaginationdiv at the bottom of the page and add some more html so it looks likediv idpaginationdivhr is this possible in jquerythanks,['jquery'] +137506,creating graph with date and time in axis labels with matplotlib i have my data in an array of the following structure1293606162197 0 0 1293605477994 63 0 1293605478057 0 0 1293605478072 2735 1249 1293606162213 0 0 12936061629 0 0the first column is epoch time in ms second is y1 and third is y2 i need a plot with the time on the xaxis and y1 and y2 on left and right yaxesi have been scouring through the documentation but could not find any way to get my xaxis ticks to thisplay both date and time like 2812 1648 ie datemonth hourmin all the documentation helps me with is to thisplay dates alone but that is not what i want any help would be appreciated on thisand if it may seem like this is not homework it is actually a follow up to my previous question reading and graphing data read from huge files,['python'] +137512,why is an embedded google map altering safaris font rendering if you look at the footer on this page here in safari then look at the same footer on any other page youll see a difference in font rendering it looks the the font smoothing is being applied twice to me if i turn off the google map then the font rendering returns to normal so i am confident the map is at the root of the problem i am applying a transparent font shadow to all text to fix some fontface rendering issues artefacts mainly but this problem is present with or without text shadowit is a mac only problemhas anyone else come across this problem is there a known cause andor fix,['css'] +137522,why does local variable kill my global variable sorry for this question but this issue really screwed up my daythe following code alerts 10 as it shouldvar globalid10 function check alertglobalid checkbut this next code alerts undefinedvar globalid10 function check alertglobalid var globalid checki am aware that if i declare a variable in a function its a local variable but if i already declared it as global how can it be that my alerts says undefinedthis is an easy example but in my original code i did a lot of stuff in between the beginning of the function then a long way down i checked to see if globalid was defined else define it ifglobalidvar globalid this meant that my alert situated at the top of the function generated undefined as if javascript first executed the whole function just to see if any variables might be declared and if so declare them and therefore my alert pointed to an undeclared variablecan anybody explain to me why this happen and if it is true that javascript predeclares all variables before executing a function even variables declared in conditions not even met,['javascript'] +137558,exception to the overflowhidden property how is it possible to make an exception on the overflowhidden container property to a matched set of child elementsheres a sample scenediv style overflowhidden pitemp pitemp p claspecialitem that needs to show itself outside the parent borderspdivi do have a reason why i am doing this i am building a pretty complex scrolling menu whose elements are expanding out of the menus borders the menu obviously clips everything outside its borders since it is scrolling aroundheres a chunk of code relevant to the issueuncomment the marked line in the javascript to see the issue below the special itemyou might notice that the scrolling is not working it is ok i think it is fiddle issue,['css'] +137559,mvc3 model binding causes the parameter conversion from type systemint32 to systemdecimal failed no type converter i am getting the following exceptionexception the parameter conversion from type systemint32 to type systemdecimal failed because no type converter can convert between these types systemexception systeminvalidoperationexceptionthis is after i use jquery ajax post to post the json back to the controllermvc3 is binding the json to the model correctly as i can see all the data in a watch however the modelstate has this errorthe view has a single decimal field and a textbox which holds a numberi get this error even when the textbox has an integer valueany ideas as to why this is failing,['jquery'] +137566,objectiveciphone nsexception capturing as much information as possible i am using the following code to capture exceptions in my appvoid uncaughtexceptionhandlernsexception exception flurryapi logerroruncaught messagecrash exceptionexceptionjust wondering whether i can pinpoint line numbers uiview classes etc that the errors occurring on ideally i would like as much detailed information as i can get since it is captured by flurryapi analyticsflurryapi,"['iphone', 'objective-c']" +137578,what is the use for ihttphandlerisreusable i am writing a ihttphandler and i will need to implement a isreusable property when i look at the msdn documentation it says gets a value indicating whether another request can use the ihttphandler instancethis is not very helpful in which situations should i use a reusable handler and in which situations should it not be reusablefollow up questionswhat is reusecan i maintain state ie class variables when reusable true,"['c#', 'asp.net']" +137602,how to play movie files with no file extension on ios with mpmovieplayercontroller or avplayer i want to play a movie in ios 43 on the ipad i have successfully used mpmovieplayercontroller and avplayer to load files from a remote url when the filename has a file extension however when i use a cdn that does not return the filename just an unguessable random name neither mpmovieplayercontroller or avplayer seem to be able to copeis there a way to tell either player that it really is a movie of type x and it should just get on playing itmpmovieplayercontroller will return the following error from it is changed state notification mpmovieplayerplaybackdidfinishreasonuserinfokey 1 error error domainmediaplayererrordomain code12847 this movie format is not supported userinfo0x5b60030 nslocalizeddescriptionthis movie format is not supportedi know that file is a valid m4v file as when i rename it all is fine,"['iphone', 'ios']" +137606,join two lists of dictionaries on a single key given n lists with m dictionaries as their elements i would like to produce a new list with a joined set of dictionaries each dictionary is guaranteed to have a key called index but could have an arbitrary set of keys beyond that the nonindex keys will never overlap across lists for example imagine the following two listsl1 index1 b2 index2 b3 index3 greeneggsl2 index1 c4 index2 c5b would never appear in l2 since it appeared in l1 and similarly c would never appear in l1 since it appeared in l2i would like to produce a joined listl3 index1 b2 c4 index2 b3 c5 index3 greeneggswhat is the most efficient way to do this in python,['python'] +137620,how to add a drop down next to the search input field in android in the systemwide search on my htc desire froyo i see a little drop down left to the search input field that allows to select where i want to search all web appshow can i implement this in an application of mine the search tutorial on the google developer site does not address thisso in a scenario like the following taken from the android docs i would like to click on the books and then get some sort of menu to eg select words headings as search modeupdate i am not looking for the quickaction dialog itself but rather how to attach something to the books icon that reacts on touch so that i could attach the quickaction or a new activity or and i want to use the standard android search dialog as described in,['android'] +137624,how could someone make a c incremental compiler like java years ago someone asked why c does not allow incremental compilation like java el skeet said it is to do with java outputting class files rather than assembliesnow that its 2011 and groovy things like the mono compilerasaservice have been released what would need to be done to make an incremental compiler for cedit to everyone banging on about how this is not a problem heres a quote from jon skeet from the thread i linked to are you suggesting you never find yourself waiting for a build even 15 seconds if a build takes 15 seconds and you want to build 20 times in an hour which i certainly do with tdd that means i am wasting 5 minutes taking a 5 minute break is one thing that is a good way of relaxing etc but being held up for 15 seconds 20 times can be very frustrating it is not long enough to do anything useful other than maybe sip a drink but it is long enough to irritatei suspect two factors contribute the level of annoyance i feel which others apparently do not 1 tdd really relies on a faster turnaround 2 when working with java in eclipse such delays are very rare,['c#'] +137626,should github be used as a cdn for javascript libraries serving javascript libraries from a cdn instead of your own server comes with tremendous advantages less work for your server possibility for the cdn to have a copy closer to the user than your server but most importantly a good chance that your users browser already has it cached from that url the last one means less total work for everybody so it is clearly a win all around and is more likely the more often we developers rely on the cdns to serve our javascriptbut the popular javascript cdns google microsoft others only host a small number of files for others we have the choice of hosting them ourselves or using the source control server as a kind of cdn it is unlikely github or similar has a geographically thistributed cache of files optimized for serving globally but if it is common practice then there is a decent chance that the users browser will have it cached the argument of offloading work from our servers to github is only valid if github has willingly volunteered to do thisso is it common practice should we encourage each other to do this does github mind do they have an official policy stated,['javascript'] +137647,xauth using pythonoauth2 i am trying to implement xauth for instapaper using pythonoauth2 i am able to find samples for oauth but i didnt find any for xauth can someone share samples or the api documentation,['python'] +137652,implementation of differentiation in c i have the following differentiation i need to implement it in cwtddtlogatwhere at is a array of double datahow can i obtain the resulting wt array from the derivative abovethanks editpublic double derivative dvdt new doubleenvelopegetlength0 envelopegetlength1 int h 1 for int j 0 j envelopegetlength0 j for int i 0 i envelopegetlength11 i dvdtj i envelopej i h envelopej i h return dvdti found this library but i cant understand how the sample code is working and how i can apply it to my problem eh,['c#'] +137654,use camera flashlight in android i am trying to use the cameras led flashlight in a widget i have found several threads about this topic ie the one mentioned later now i am trying to control the light usingcamera cam cameraopen parameters p camgetparameterspsetflashmodeparametersflash mode torchcamsetparameterspcamreleasein the androidmanifestxml tried different permissions currently i haveusespermission androidnameandroidpermissioncamera usespermission androidnameandroidpermissionflashlightusesfeature androidnameandroidhardwarecamera usesfeature androidnameandroidhardwarecameraautofocus usesfeature androidnameandroidhardwarecameraflash i am testing this on my galaxy tab as i do not have any other android devices at hand the light does not turn on so i have a few questions nowis there any way to test the led light behavior in the emulatoram i doing something wrong hereaccording to this question which deals with the same problem it works differently on the galaxy tab howand finally if it does work differently i am starting to wonder if it is just the galaxy tab or if other devices use different methods too it would be hard to test then and it seems rather odd to methanks for any insightby the way i quickly tested with quicksettings which gets mentioned a few times here the flashlight does not work with quicksettings eithernote that the galaxy tab stil uses android 22 i see there were some changes between 22 and 23commenti know it has to work somehow as i have found other apps in the market that work perfectly with the galaxy tabcomment 2 if i set camsetparametersp and directly ask the camera for the current state with getflashmode it correctly returns flash mode torch however if i release the camera and reopen it it returns flash mode off it is almost as if the camera object aknowledges the request but does not really pass it on to the hardwareafter konstantins comment i removed the camrelease part he is right the settings are not persisted if you release the camera if you use camopen again you will get a fresh instance with the light off the lights still not working on the galaxy tab thoughso i guess it is hard to keep the light on if youre trying to control it through a widget then as soon as the background service is finished the camera object is released automatically and therefore the light switches off again my questions still remain especially why the camera does not switch on in the first place,['android'] +137663,event correlation and filtering how to whereto start got an asynchronous stream of events where each event has information like agency one of many agencies possible to be served by my solutionagent one of many agents in an agencyservedentity a personorganization served by 1 or more agenciesdatetimeclassdata tags from a fixed but large set of tagswhat i need to do is to correlate an event based on servedentity datetime and classdata and create a consolidated new event exampleevent 0021 agencyxyz agentabc servedentitymmn datetime12032010337 classdatemisseddeliverynorepeatuntracableorphan event 0193 agencyklm agentday servedentitymmn datetime120320123221 classdatemisseddeliveryorphanlost event 1217 agencyklm agentcare servedentitymmn datetime120320185045 classdateescalated here i find 3 events which are spaced out in time more than 7hr separation which are for the same servedentity mmn occur within a certain time window say 24hours have matching or related classdatafinally create a consolidated new event which could represent an inference drawnbe able to create reports on a per agency per agency per servedentity basis based on things like specific classdata tags eg misseddelivery over a certain period of time this could be done using the originalinput events or the synthesized inference eventswhile this is not a requirement today but quite likely to appear in future that the tags that appear in classdata could grow without any human intervention so not sure if this should then be treated as unstructured dataalso not an immediate requirement but in future there may be a need to identify trends patterns of event occurrences ie event1 led to event2 led to event3the event arrival rate could be quite high possibly thousands of events per minute maybe more and i need to archive the originalsynthesized events for a period of time a month or somy solution needs to be based on foss components preferably some research done so far points in the direction of cep complex event processing bayesiannetworksclassification predictiveanalyticslooking for some suggestions regarding approach to take i would prefer to take the path which meets most of my goals with minimum difficultytime or to put another way learning ai or formal statistical methods is not my shortterm goal,['python'] +137666,how to sort an array of objects with jquery or javascript i have an array of objectsvar array id name valueid name value and so onhow do i get the array to be sorted in ascending order of the atribute name arrayi1i have tried to do this arrayi1sort but that does not workplease help meedit the array can contain more than two objects it can contain hundredseditwhy is this question marked as a duplicate when it was asked 2 years before the duplicated question,"['javascript', 'jquery']" +137679,python mysqldb connectionclose vs cursorclose if i use mysqldb to connect to mysqlserver through python i create a connection and a cursor like thisconnection mysqldbconnectcursor connectioncursor processwhen the mysqlprocessing is done one should close the connection now i was wondering is it sufficient to close the connection bydoingconnectioncloseor do i have to close the cursor first and then the connection like thiscursorcloseconnectionclosethanks for any responses,['python'] +137701,phpunit output causing zend session exceptions i am getting numerous errors exactly like this onezend session exception session must be started before any output has been sent to the browser output started in usrlocalzendsharepearphpunitutilprinterphp173when running my applications test suite this is with phpunit 3510 and php 535there is no mysterious unexpected whitespace output that is causing this i have determined that the output being sent to the browser is the actual output from the phpunit tests being executed if i open up phpunitutilprinterphp and wrap the print buffer line with if strposbuffer phpunit 3510 by sebastian bergmann false effectively stopping the first line of output from phpunit then my first test succeeds until the test case outputs a dot indicating that the test succeeded then the next test fails because the dot was outputanother developer on my team is able to run the full test suite successfully so i know it is not a problem with the application code it must be some configuration setting or problem with my local environmenti have already checked phpini to verify that output buffering is turned on and implicit flush is turned off and they arei have also tried adding zend session unittestenabled true to my test bootstrap but that did not help and should not be necessary anyway because it works on another developers machine and on our ci server without itany suggestions besides ignoring the errors i have never seen anything like this and am truly at a lossthanksupdateto attempt to further isolate the problem i took zf and my application out of the equation by executing the following test scriptphpclass sessiontest extends phpunit framework testcase public function testsession session start thisasserttruetrue the test fails1 sessiontesttestsessionsession start cannot send session cookie headers already sent by output started at homemmsatestphp1however the exact same test works on a friends machine same version of php and phpunit,['php'] +137706,trying to manually sign android package with jarsignerexe and install with adbexe i have been trying to use the jarsignerexe and adbexe to manually sign an android package and install it on a api v8 emulator i created a simple helloandroid project and it would generate a signed helloandroidapk using the debugkeystore located in the users android directory when launching from eclipse it builds and installs the apk on the emulator without a problemi used the android tools to export an unsigned application package to a separate directory i signed and zipaligned the package and used adb to install it but received the errorfailure install parse failed no certificatesi used the following command to sign itjarsigner verbose keystore cusersjhwongandroiddebugkeystore storepass android keypass android digestalg sha1 sigalg sha1withrsa sigfile cert signedjar temphelloworld2apk temphelloworldunsignedapk androiddebugkey adding metainfmanifestmf adding metainfcertsf adding metainfcertrsa signing reslayoutmainxml signing androidmanifestxml signing resourcesarsc signing resdrawablehdpiiconpng signing resdrawableldpiiconpng signing resdrawablemdpiiconpng signing classesdexthat did not give me any errors and just to makes sure i ranjarsigner verify verbose temphelloworld2apkit showed the jar was verified and each file signed and part of the manifest i ran zipalign v 4 temphelloworld2apk temphelloworld3apk which finished without an errorthen used adb install r temphelloworld3apki have seen several related threads and articles suggesting these directions but i am perplexed as to why it does not work manually verses using eclipse to build the signed package i have even taken the package built from eclipse and was able to use adbexe to install it so i have narrowed it to signing the package i have tried keystores that i have generated from the keytool but they did not work as well which is why i tried the debugkeystorei would appreciate any advice if they noticed anything wrong with my jarsigner code,['android'] +137713,java is there no atomicfloat or atomicdouble i have found atomicinteger atomiclong but where is atomicfloat or atomicdouble maybe there is some trick,['java'] +137714,django render to response is not defined error hi i am getting this error while i tried make a simple appnameerror at firstglobal name render to response is not definedrequest method getrequest url httplocalhost80firstpreviewdjango version 13exception type nameerrorexception value global name render to response is not definedexception location homenaveendjango projectsmyprojectfirstviewspy in index line 5python executable usrbinpythonpython version 266python path homenaveendjango projectsmyproject usrlocallibpython26thistpackagespip083py26egg usrlocallibpython26thistpackages usrlocallibpython26thistpackagesdjango evolution062py26egg usrlibpython26 usrlibpython26platlinux2 usrlibpython26libtk usrlibpython26libold usrlibpython26libdynload usrlocallibpython26thistpackages usrlibpython26thistpackages usrlibpython26thistpackagespil usrlibpython26thistpackagesgst010 usrlibpymodulespython26 usrlibpython26thistpackagesgtk20 usrlibpymodulespython26gtk20server time thu 31 mar 2011 145032 0500any ideas,['python'] +137715,hashset contains method strange behavior here is my code public class testgui public static void mainstring arg class tests string t public testsstring t thist t override public boolean equalsobject x systemoutprintlnmy method is called ifx instanceof tests tests z tests x return ztcomparetot0 else return false hashsettests allitems new hashsettests allitemsaddnew testsa allitemsaddnew testsa systemoutprintlnallitemscontainsnew testsa i do not get why the hashset contains method is not calling my equals method as mentionned in their specifications more formally adds the specified element o to this set if this set contains no element e such that onull enull oequalsemy code is returning false and not going into my equals methodthanks a lot for answering,['java'] +137727,javascript jsonstringify does not escape i am using jsonstringify to stringify an object but the quotes are not escaped am i misunderstanding that it is suppose to escape the quoteseditcode looks like thisthis is outputted into the template without any of the quotes being escapedoutput consolefreefalse,['javascript'] +137729,is it possible to install another version of python to virtualenv i have a shared account in a webhosting that has python 24 installed but my code is not compatible with 24 is it possible to install python 26 directly to virtualenv note i dona t have permission to install it in the shared server,['python'] +137739,is there a benefit to putting a class on a script tag i came across this codescript classexample typetextjavascriptand was curious if there is a benefit to writing that into your code,"['javascript', 'html', 'css']" +137753,reading parental control settings in ios i would like to be able to read some of the parental control settings and use those values as the default setting for our applications setting screen our app has a menu showing movies are available for purchase including an adult section movies are beamed to the tv not played in the app the movie thumbnails are safe but risque and of course the movie descriptions well no child needs to know what the babysitter does after darkon ios devices users may set up content restrictions viasettings general restrictions i am particularly interested in restrictions movies and restrictions tv shows where parents can set checkmarks next to each rating if it will be permitteddo not allow moviesgpgpg13allow all moviesi do not want to change those settings only read their current value in an officially supported way i have searched around and cannot seem to find the right apis obviously wed rather not show all content if the user has taken the time to setup some parental controlsps please do not tell me apple will reject the app,['iphone'] +137759,how do i dynamically add an attr reader i expect the following code to work as expected but it gives me a nomethoderror private method foo called for myclassclass myclassendmy object myclassnewmy objectinstance variable setfoo barmyclasendattr reader fooputs my objectfoothe problem is i am using literally identical code in a larger application and it works exactly as i expect but when i simplify it to this most basic example it failsi understand there are many other ways to do what i am doing in ruby,['ruby'] +137786,how to get a property value based on the name is there a way to get the value of a property of a object based on its namefor example if i havepublic class car vehicle public string make get set andvar car new car makeford i want to write a method where i can pass in the property name and it would return the property value iepublic string getpropertyvaluestring propertyname return the value of the property,"['c#', 'asp.net']" +137788,why is this program erroneously rejected by three c compilers i am having some difficulty compiling a c program that i have writtenthis program is very simple and to the best of my knowledge conforms to all the rules set forth in the c standard i have read over the entirety of isoiec 148822003 twice to be surethe program is as followshere is the output i received when trying to compile this program with visual c 2010cdevcl nologo helloworldpngcl command line warning d9024 unrecognized source file type helloworldpng object file assumedhelloworldpng fatal error lnk1107 invalid or corrupt file cannot read at 0x5172thismayed i tried g 452 but it was equally unhelpfulcdevg helloworldpnghelloworldpng file not recognized file format not recognizedcollect2 ld returned 1 exit statusi figured that clang version 30 trunk 127530 must work since it is so highly praised for its standards conformance unfortunately it did not even give me one of its pretty highlighted error messagescdevclang helloworldpnghelloworldpng file not recognized file format not recognizedcollect2 ld returned 1 exit statusclang error linker via gcc command failed with exit code 1 use v to see invocationto be honest i do not really know what any of these error message meanmany other c programs have source files with a cpp extension so i thought perhaps i needed to rename my file i changed its name to helloworldcpp but that did not help i think there is a very serious bug in clang because when i tried using it to compile the renamed program it flipped out printed 84 warnings and 20 errors generated and made my computer beep a lotwhat have i done wrong here have i missed some critical part of the c standard or are all three compilers really just so broken that they cannot compile this simple program,['c++'] +137789,making an object listen to activity lifecycle events one of the classes i have written needs to react when the following activity events occuronstartonpauseonresumeonstopi can react to those on the activity itselfpublic class activity extends applicationcontext protected void oncreatebundle savedinstancestate protected void onstart protected void onrestart protected void onresume protected void onpause protected void onstop protected void ondestroyfrom the activity i could tell the object in question that a certain event has occurred but i do not like this idea it requires the developer to implement the logic outside my objectclass ideally i would like the object to be responsible for registering these events and set itself as a listener independent of the activityany ideas thanks in advance,['android'] +137819,postgresql query to excel sheet i need to export some data from postgresql to excel quick customer wish and the last time excel had serious problems opening or importing my copyd csv files line endings utf8 encoding etc and it took me an hour at bestdoes someone know a quick elegant solution that generates a real excel file like a small shell script or the likei want this to be done either on my linux box debian 50 lenny or on windows xp or higher,['sql'] +137827,how to createbuild multiple instances of a factory in factory girl how do i create multiple records or multiple factories of the same classi triedfactorydefine user do user useremail userpassword somepassword useremail another existing userpassword somepasswordendandfactorydefine user do user useremail userpassword somepasswordendfactorydefine user do user useremail another existing userpassword somepasswordendbut it does not work attribute already defined email,['ruby-on-rails'] +137835,in javadoc what is the difference between the tags throws and exception take the following implementation of a arraybased stack of chars for examplepublic char peek throws underflow if isempty return stackpos else throw new underflowpeeking at an empty stack back when i am using just a text editor i always use the exception tag but now my ide netbeans used throws when generating the javadocso my question is what is the difference between the two and when should one be preferred over another using the above code for example,['java'] +137845,convert string to datetime how to convert string like this 01011970 0344 to javascript datetime,['javascript'] +137846,environment variable with maven i have ported a project from eclipse to maven and i need to set an environment variable to make my project workin eclipse i go to run run configurations and under the tab environment i set wsnshell home to the value confhow can i do this with maventhank you very much,['java'] +137864,capturing sound for analysis and visualizing frequencies in android i am new in android and i am trying to make a program which captures an audio sound and then thisplays the frequencies that exist within it i found an example that draws the graphic portion of a graphic equalizer in this example it is used an object of typeaudiorecord to capture audio sound the technique used to break an audio signal down into component frequencies employs a mathematic transformation called a thiscrete fourier transform dft and to perform dft it is used a fast fourier transform fft this example use a package which implements the fft the package is linked here wnetliborgfftpackjfftpacktgz the problem is that after i run this example the graphic equalizer does not appear on the thisplay after i press the start buttonhere is the source code for the activity class package comaudioprocessingimport androidappactivityimport androidgraphicsbitmapimport androidgraphicscanvasimport androidgraphicscolorimport androidgraphicspaintimport androidmediaaudioformatimport androidmediaaudiorecordimport androidmediamediarecorderimport androidosasynctaskimport androidosbundleimport androidutillogimport androidviewviewimport androidviewviewonclicklistenerimport androidwidgetbuttonimport androidwidgetimageviewimport cauolaigfftpackrealdoublefftpublic class audioprocessing extends activity implements onclicklistener int frequency 80 int channelconfiguration audioformatchannel configuration mono int audioencoding audioformatencoding pcm 16bit private realdoublefft transformer int blocksize 256 button startstopbutton boolean started false recordaudio recordtask imageview imageview bitmap bitmap canvas canvas paint paint called when the activity is first created override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain startstopbutton button thisfindviewbyidridstartstopbutton startstopbuttonsetonclicklistenerthis transformer new realdoublefftblocksize imageview imageview thisfindviewbyidridimageview01 bitmap bitmapcreatebitmapint256int100bitmapconfigargb 8 canvas new canvasbitmap paint new paint paintsetcolorcolorgreen imageviewsetimagebitmapbitmap private class recordaudio extends asynctaskvoid double void override protected void doinbackgroundvoid params try int buffersize audiorecordgetminbuffersizefrequency channelconfiguration audioencoding audiorecord audiorecord new audiorecord mediarecorderaudiosourcedefault frequency channelconfiguration audioencoding buffersize short buffer new shortblocksize double totransform new doubleblocksize audiorecordstartrecording while started int bufferreadresult audiorecordreadbuffer 0 blocksize for int i 0 i blocksize i bufferreadresult i totransformi double bufferi 327680 signed 16 bit transformerfttotransform publishprogresstotransform audiorecordstop catch throwable t logeaudiorecord recording failed return null protected void onprogressupdatedouble totransform canvasdrawcolorcolorblack for int i 0 i totransform0length i int x i int downy int 100 totransform0i 10 int upy 100 canvasdrawlinex downy x upy paint imageviewinvalidate public void onclickview v if started started false startstopbuttonsettextstart recordtaskcanceltrue else started true startstopbuttonsettextstop recordtask new recordaudio recordtaskexecute here is the mainxml xml version10 encodingutf8linearlayout xmlnsandroidandroidorientationverticalandroidlayout widthfill parentandroidlayout heightfill parenttextviewandroidlayout widthfill parentandroidlayout heightwrap contentandroidtextstringhelloimageview androidididimageview01 androidlayout widthwrap contentandroidlayout heightwrap contentimageviewbutton androidtextstartandroidididstartstopbutton androidlayout widthwrap contentandroidlayout heightwrap contentbuttonlinearlayoutin the androidmanifestxml i set the record audio permissionthanks in advance,['android'] +137884,how does line spacing work in core text and why is it different from nslayoutmanager i am trying to draw text using core text functions with a line spacing that is as close as possible to what it would be if i used nstextviewtake this font as an examplensfont font nsfont fontwithnametimes new roman size960the line height of this font if i would use it in an nstextview is 10nslayoutmanager lm nslayoutmanager alloc initnslogf lm defaultlineheightforfontfont this is 10now if i do the same thing with core text the result is 1104 assuming you can calculate the line height by adding the ascent descent and leadingctfontref cfont ctfontcreatewithnamecfstrtimes new roman 960 nullnslogf ctfontgetdescentcfont ctfontgetascentcfont ctfontgetleadingcfont this is 110390625this is very close to 10 but for some fonts the difference is much bigger eg for helvetica nslayoutmanager gives 1150 whereas ctfont ascent descent leading 960 clearly for helvetica i wouldnt be able to use ascent descent leading to calculate the spacing between linesso i thought i would use ctframe and ctframesetter to layout a few lines and get the linespacing from that but that also gives different valuesctfontref cfont ctfontcreatewithnamecfstrtimes new roman 960 nullnsdictionary attrs nsdictionary dictionarywithobjectidcfont forkeyidkctfontattributenamensattributedstring threelines nsattributedstring alloc initwithstringabcdefgnabcdefgnabcdefg attributesattrsctframesetterref threelineframesetter ctframesettercreatewithattributedstringcfattributedstringrefthreelinescgmutablepathref path cgpathcreatemutablecgpathaddrectpath null cgrectmake00 00 60 60ctframeref threelineframe ctframesettercreateframethreelineframesetter cfrangemake0 0 path nullcgpoint lineorigins3ctframegetlineoriginsthreelineframe cfrangemake0 0 lineoriginsnslogspace between line 1 and 2 f lineorigins0y lineorigins1y result 119278125nslogspace between line 2 and 3 f lineorigins1y lineorigins2y result 1136250so the line spacing is now even more different from the 10 that was used in my nstextview and not every line is equal it seems that the line breaks add some extra space even though the default value for paragraphspacingbefore is 00i am working around this problem now by getting the line height via nslayoutmanager and then individually drawing each ctline but i wonder if there is a better way to do this,['objective-c'] +137903,jquery are events handlers removed from objects if they are removed from the dom using html i am concerned about memory leaks in my application as i use jquerys html method a lot to replace content in the the dom i just want to make sure that not of these event listeners are going to be hanging around in browser memoryi have searched the jquery docs with no clear answer does anyone knowthanks guys,['jquery'] +137906,is there a workaround for this c4702 linktime warning i am using boostvariant and am having trouble compiling in release mode i am working in vc2010 with warning level 4 and warnings as errors the code below compiles fine in debug mode but in release mode i get a bunch of unreachable code c4702 warnings emitted at link time presumably i am getting compiler warnings here because there is link time code generation when optimisations are enabledhas anybody successfully thisabled these warnings in this situation i would prefer to keep the high warning level and warnings as errors if possiblepragma warning thisable4702 does not seem to work here here is some sample codeinclude boostvarianthppstruct nulltypedef boostvariant null double variant tclass addition visitor public booststatic visitor variant t public template typename t typename you variant t operator const t const u const throw bad types variant t operator const double left const double right const return variant t left right int mainint argc char argv variant t a 30 b 20 variant t c boostapply visitor addition visitor a b return 0the warning is triggered by the templated operator which i am using to catch attempts to apply the visitor to bad variant types,['c++'] +137912,can i use arial rounded mt bold with css can i use arial rounded mt bold with css fontfamilyarial rounded mt bold arial helvetica sansserifnothing changed when i put fontfamilyarial helvetica sansserif,"['html', 'css']" +137917,explicit specialization of template class member function i need to specialize template member function for some type let us say double it works fine while class x itself is not a template class but when i make it template gcc starts giving compiletime errorsinclude iostreaminclude cmathtemplate class c class xpublic template class t void get astemplate class cvoid xcget asdoubleint main xint x xget ashere is the error messagesourcecpp1127 error templateid get asdouble in declaration of primary templatesourcecpp116 error prototype for void xcget as does not match any in class xcsourcecpp735 error candidate is templateclass c templateclass t void xget ashow can i fix that and what is the problem herethanks in advance,['c++'] +137923,android facebook get all profile information how i can fetch all of user profile information from facebook like first name last name email etci have downloaded the fb sdk but there is no example for getting the profile info,['android'] +137924,java preparedstatement retrieving last inserted id this answer to this question done this way seems to be very difficult to find on the internet basically i am inserting values into a mysql database using preparedstatement i use the preparedstatement to escape the data to prevent sql injection attacks the problem is there is now way retreving those keysstring queryinsert into table aname age string queryinsert into table aname age abc123 does not escapepreparedstatement prestprest conpreparestatementqueryprestsetstring1abcprestsetint2123prestexecuteupdateprestexecuteupdatequery preparedstatementreturn generated keys throws an errorprestexecutequery throws an errorso how can i escape input and use preparedstatements in java,"['java', 'mysql']" +137937,determine debugrelease mode in published dll without debug i have a component which can be referenced in some projects for example componentdll i publish it of course in release mode in another project for example projectexe i reference componentdllif i build projectexe in debug mode is there a way to find out about that in my componentdll libraryto clarify more if i have a class and a method named test within componentdll can i do something likepublic void test ifdebugisindebugmode keep in mind that componentdll is built in release mode,['c#'] +137954,how do i use voice search and voicerecognition on android i want to use voicerecognition in my application but this application needs to install voice search i do not want the user to have to install another other application then return to my application to run it i want voice search to be installed from my application or alternatively i would like to find a tutorial to on how to add voice search capability to my applicationwhat can i do,['android'] +137957,removing non red toned pixels i have a very simple image processing application i am trying to remove the pixels which do not involve red tonesso far a basic code seems to achieve what i want private void removeunredcellsbtn clickobject sender eventargs e byte threshold converttobytedifftxtboxtext byte r g b for int i 0 i m bitmapwidth i for int j 0 j m bitmapheight j r im matrixi jr g im matrixi jg b im matrixi jb if r b threshold r g threshold m bitmapsetpixeli j colorwhite picturearea pictureboximage m bitmap basically if the difference of red and blue or red and green is less than a threshold it sets the pixel to white my results seems to be promising however i am wondering if there is a better solution for determining whether a pixel involves red tones in itmy results for a threshold value of 75 is any algorithm or thought will be very appreciated thanks in advance,['c#'] +137974,desperate for python py2exe help i have been to a few different forums and spent over a week now googling my arse off to try to find a solutioni cannot seem to get py2exe to work properly i have run python setuppy py2exe in cmd as well as python setuppy install and when i try to run my executable setup i get this same error over and overafter a week i am starting to get quite frustrated and i am hoping to be able to resolve the issue todayi am using python 27 and py2exe v069 64bit windows7thanks in advance,['python'] +137983,choosing which ip the http request is using when having multiple ips net i am writing a net program which will run on a computer with several ip addresses the program makes http requests to given web addresses i want to choose which ip address i use so i can determine which ip address will appear on the log of the other serversuggestions,"['c#', '.net']" +137997,is there a standard function to check for null undefined or blank variables in javascript is there a universal javascript function that checks that a variable has a value and ensures that it is not undefined or null i have got this code but i am not sure if it covers all casesfunction isemptyval return val undefined val null vallength 0 true false,['javascript'] +138008,python smooth time series data i have some data in python that is unixtime value1301672429 274 1301672430 302 1301672431 288time constantly steps by one second how might i reduce this data so the timestamp is every second but the value is the average of the surrounding 10 valuesfancier rolling averages would be good too but this data is graphed so it is mostly to smooth out the graphfollow up of tsql rolling average of time groupings after coming to the conclusion that trying to do this in sql is a route of pain,['python'] +138021,bufferedreader read multiple lines into a single string i am reading numbers from a txt file using bufferedreader for analysis the way i am going about this now is reading a line using readline splitting this string into an array of strings using splitpublic inputfile filein null stuff here filein new filereaderfilename txt buffin new bufferedreaderfilein return stuff herepublic string readbigstringin string line null try line buffinreadline catchioexception e return linepublic processmain initcomponents string stringarray string line try inputfile stringin new inputfile line stringinreadbigstringin stringarray linesplit09ee analysis etc this works fine but what if the txt file has multiple lines of text is there a way to output a single long string or perhaps another way of doing it maybe use whilebuffinreadline null not sure how to implement thisideas appreciatedthanks,['java'] +138027,iphone sdk 43 libav compiling problem i faced with strange problem i installed iphone sdk 43 and xcode 4 and now i cannot compile libav from ffmpeg for armv6 architecture this is my script to compile it it works fine for iphone sdk 42configure thisabledoc thisableffmpeg thisableffplay thisableffserver enablecrosscompile enableencoderrawvideo enabledecoderh264 enabledecodermpeg4 enableencodermjpeg enablemuxerrawvideo enabledemuxerh264 enableparserh264 enablecrosscompile archc targetosdarwin enablelibopencoreamrnb enablelibopencoreamrwb ccdeveloperplatformsiphoneosplatformdeveloperusrbinarmappledarwin10gcc421 asgaspreprocessorgaspreprocessorpl developerplatformsiphoneosplatformdeveloper usrbinarmappledarwin10gcc421 sysrootdeveloperplatformsiphoneosplatformdevelopersdksiphoneos43sdk cpuarm1176jzfs extracflagsarch armv6 extraldflagsarch armv6make cleanmake as a result i get library files but when i check it with lipo info command it shows that library was compiled for i386 architecturemaybe somebody faced with such problem help me pleasethanks,['iphone'] +138043,simulate left and right arrow key event with javascript i am using the slidehtml5rockscom framework and i am trying to use to img tags inside of a tag links and i cannot get the javascript onclick to simulate the left and right key events to change slides,['javascript'] +138051,how to write data to a text file in c without overwriting the current data greetings i cannot seem to figure out how to write data to a file without overwriting it i know i can use fileappendtext but i am not sure how to plug that into my syntax here is my codetextwriter tsw new streamwriterchellotxtwriting text to the filetswwritelinehelloclose the filetswclosei want it to write hello every time i run the program not overwrite the previous text file thanks for reading this,['c#'] +138052,how can i force my footer to stick to the bottom of any page in css this is my codefooter fontsize 10px positionabsolute bottom0 backgroundfi have no idea what is wrong with this can anyone helpedit for some more clarity on whats wrong the footer is thisplayed on the bottom as expected when the page loads however when the web pages height is than the dimensions on the screen such that a scroll bar appears the footer stays in that same location that is to say when the height of the page is 100 the footer is at the bottom however when the page height is 100 the footer is not at the bottom of that page but at the bottom of the visible screen insteadedit surprisingly none of the solutions below worked i ended up implementing a sidebar instead,"['html', 'css']" +138054,reflection not finding protected field of nested type i have a class which has a protected nested class and a protected readonly field of the nested class typemy framework calls ogettypegetfieldsbindingflagspublic bindingflagsnonpublicon an instance of the type i can see the field from debugger but the call does not return it why,"['c#', '.net']" +138062,how can i use a very large dictionary in c i want to use a lookup map or dictionary in a c application but it is expected to store 12 gb of data can someone please tell if i will still be able to use dictionary class or if i need to use some other classedit we have an existing application which uses oracle database to query or lookup object details it is however too slow since the same objects are getting repeatedly queried i was feeling that it might be ideal to use a lookup map for this scenario to improve the response time however i am worried if size will make it a problem,['c#'] +138072,thisabling ctrlclick on jquery ui selectable i was wondering if there is an option on the jquery ui selectable that will let me thisable the ctrlclick but still keep the draggable for the multiple selection on my project i want to be able for people to select multiples but only by dragging not by ctrlclickingif there is not does anyone know a way i can achieve thisany information would be really helpful thanks,['jquery'] +138086,how to upload a file using an http put using jquery i would like to upload a file using jqueryfileupload but using http put instead of multipartforms according to their site multipart and file contents stream uploads files can be uploaded as standard multipartformdata or file contents stream http put file uploadbut i cannot find anywhere in their documentation as to how to do this can anyone help,"['javascript', 'jquery']" +138090,is this font shorthand property syntax valid my reading of the spec says yes but half of my installed browsers thisagree is this valid font bold 10px13px inheritaccording to my reading of the specs that should mean a fontweight of bold a fontfamily of inherit a fontsize of 10px and a lineheight of 13pxit appears to work correctly in internet explorer 8 80600118702it works correctly in safari 504 75332027 on windowsopera 1101 build 1190 and firefox 3616 both log errors about iti have not tried chrome or firefox 4 yetif this is indeed supposed to be valied is this parsing bug a known issuea couple extra pointsthe w3 validator also reports this as being invalid none of font bold 10px inherit font bold 10px13px or font bold 10px work correctly in firefox here eitherupdateas pointed out by adam wagner in his answer my attempted value is in fact not valid despite what my naive reading of the spec suggested due to a c31 of the css21 spec,['css'] +138097,downloading normal image vs retina device image 2x when we need to download an image from some url and show it on two kinds of devices retina with 2x image and regular device should we have two different image urls to handle thisfor the images in the resource bundle we are keeping both xyzpng and and its working finefor images we are fetching from server do we need to have separate image urls for both these kind of images and cache them locally with the same naming convention xyzpng and please throw some light here,"['iphone', 'ios']" +138100,mysql 51 partitioning i have the following example tablemysql create table part date3 c1 int default null c2 varchar30 default null c3 date default null enginemyisam partition by range to daysc3 partition p0 values less than to days19950101 partition p1 values less than to days19960101 partition p2 values less than to days19970101 partition p3 values less than to days19980101 partition p4 values less than to days190101 partition p5 values less than to days20101 partition p6 values less than to days20010101 partition p7 values less than to days20020101 partition p8 values less than to days20030101 partition p9 values less than to days20040101 partition p10 values less than to days20100101 partition p11 values less than maxvalue query ok 0 rows affected 0 secsay this is full of data and i want to slot in a 2011 partition at p11 and then make the p12 maxvalue is there an efficient way of doing this without dumping and reloading the entire table,['mysql'] +138102,jquery select all elements after a certain element i have a list similar to below and would like to only select all of the elements after the everything after elementdiv idcontainer div clasomethingdiv div clasomethingdiv div clasomethingdiv div clasomethingdiv div clasomethingdiv div ideverything afterdiv div clasomethingdiv div clasomethingdiv div clasomethingdiv div clasomethingdiv div clasomethingdivdiv,['jquery'] +138113,build hash from collection of activerecord models i am trying to build a hash from a modelthis is the type of hash i want to buildunited sates us united kingdom uk i have tried so many ways now i am just going around in circleshere are just some of my poor attemptsselect arraynewcountrieseach do country selectpushcountryname countrycode selectcountrynamecountrycodeendh countrieseach do c h cname ccode h hname cname hcode ccode hrgrouping idname rname hrgrouping iddescription rdescriptionendplease can some advisethank you,"['ruby-on-rails', 'ruby']" +138140,validate before destroy i have three classes school account and administratorshipschoolhas many administatorshipshas many administrators through administratorshipsaccounthas many administratorshipsadministratorshipbelongs to accountbelongs to schoolbefore destroy confirm presence of alternate administratorship in schoolprotecteddef confirm presence of alternate administratorship in school unless schooladministratorscountadministratorshipsaccount id id 0 errorsadd to base the school must have at least one administrator endendnow what i would like to happen is when i call destroy on an instance of administratorship for it to add an error to the model and prevent the destruction of the model i have removed the unless statement to see if that was preventing the error from being added it was not the case it seems that having errors on the model does not prevent the destroy from occuringso my question is is there any way i can prevent the destroy from occurring using validations i realize i could define a method that destroys only if the above condition is met but it seems that a validation approach is a more elegant solution,['ruby-on-rails'] +138143,check field if empty is the query correct if i wanted to check if the field has other characters other than null and emptyselect case when description is null then null when description is not null then not null else something else end as descriptionfrom milestone where name like test or name like test description not null 1 row in set 0 sec,['mysql'] +138144,how do you get all classes defined in a module but not imported i have already seen the following question but it does not quite get me where i want python get list of all classes within current modulein particular i do not want classes that are imported eg if i had the following modulefrom mynamespace import mybaseclassfrom somewhereelse import someotherclassclass newclassmybaseclass passclass anotherclassmybaseclass passclass yetanotherclassmybaseclass passif i use clsmembers inspectgetmemberssysmodules name inspectisclass like the accepted answer in the linked question suggests it would return mybaseclass and someotherclass in addition to the 3 defined in this modulehow can i get only newclass anotherclass and yetanotherclass,['python'] +138151,sql injection after removing all singlequotes and dashcharacters can anyone show an example of a sql statement when sql injection occurred even after all singlequote and dash characters have been stripped out of the users inputselect myrecord from mytable where myemail and mypasswordfoono ints are involved hereeveryone seems to say yes i can do it but when they are pressed for an example none of ever shownyou can use any version new or old of any sql engine sql server mysql sqllite postgresql oracle and countless others,['sql'] +138180,how do sessions work in expressjs with nodejs using expressjs sessions are dead simple i am curious how they actually work thoughdoes it store some cookie on the client if so where can i find that cookie if required how do i decode iti basically want to be able to see if a user is logged in even when the user is not actually on the site at the time like how facebook knows youre logged in when youre on other sites but i suppose to understand that i should first understand how sessions work,['javascript'] +138197,rails postgres migration to change colomn gives error cannot be cast to type timestamp without time zone a rails migration to turn a deleted at time column to a datetime column failed any ideas on how to solve this it is a fresh install of postgres if that is relevant change columnproducts deleted at datetime pgerror error column deleted at cannot be cast to type timestamp without time zone alter table products alter column deleted at type timestamp,['ruby-on-rails'] +138210,time picker for mobile devices i am working in html5 css3 and using jquery for my project i need to have a time picker only no date picker for mobile devices like ipad galaxy etc it should work with both touchscreen and nontouchscreen devices i found one with a slider but it failed on mobile devices,"['jquery', 'html', 'css']" +138217,html5 local storage vs session storage apart from being non persistent and scoped only to the current window are there any benefits performance data access etc to session storage over local storage,['javascript'] +138221,if you have an iboutlet but not a property is it retained or not i find the documentation on this issue to be unclearsay you are working with ios not the mac case no need to mention the differences say it is strictly 40 no need to mention differences in old os say we are loading the nib strictly automaticallysay you have a uiviewcontroller bigview say there are a dozen socalled toplevel items in the nib filecould be custom controls images or anything elsesay you are definitely going to explicitly create and then get rid of bigview a number of times during the apps run sofor one of these toplevel items in the nib there are three possibilities1 you do not have any sort of iboutlet for it at all2 you do have a connected iboutlet but not a property3 you do have a connected iboutlet property to avoid confusion well say a retain propertyso what happens to the item when bigview is releasedin the case of 3 it seems clear that you must release explicitly if you do not it will hang around after the view is gone no problemin the case of 1 i assume but can anyone actually confirm that the item will be released when bigview is gonein the case of 2 it is not clear what happenslooking at the wellknown reference link it is very dubiousin ios the nibloading code uses the setvalueforkey method to reconnect each outlet that method similarly looks for an appropriate accessor method and so what happens if there is not one tell us apple falls back on other means when that failsgood griefand check out this documentation and scroll down to nib object retentionso objects in the nib file are created with a retain count of 1 and then autoreleased fantasticbut wait read on a few wordshowever which uses the available setter method or retains the object by default if no setter method is availablewhat are they talking aboutdo they mean that if no setter is available ivar but no property that it is again retained other than the retain they just mention in the previous clause or are they just repeating themselves ie the retains the object by default is the same retain they were talking about immediately previously created with a retain count of 1 and then autoreleasedand why would they even mention the autorelease if that is not what happensindeed if anyone actually specifically knows the answer to this question how do you know did you ask dts or through testing or i suggest the key documentation just pasted in is aggressively unclearagain if you have an iboutlet but not a property connected to a toplevel object are you responsible for releasing it is it retained in that situationfor that matter merely in situation 1 is it absolutely the case that the thingy will be released when bigview goes away i would certainly assume this is the case but who knowsthe question is what happens if you do use an iboutlet ivar but not a propertyi have foolishly never thought about this before assumed too much does anyone have the decisive answer cheersfor the record i have made a test projectin fact surprisingly to me the mere act of connecting an ib element to an iboutlet in fact apparently adds one retaini can only assume from the shoddy docu in that situation you get specifically retain autorelease retain leading to one retain on balanceso that is the answeri will post the demo project i also direct any readers to jonahs answer below which flawlessly explains the behavior of setvalueforkey cheers,['iphone'] +138236,pass a datetime from javascript to c controller how do you pass a date time i need it to the second to c using jquery and mvc3 this is what i havevar date new date ajax type post url grouprefresh contenttype applicationjson charsetutf8 data mydate datetoutcstring success function result do something error function req status error error i cannot figure out what format the date should be in for c to understand it,"['c#', 'jquery']" +138254,i want to wait on both a file descriptor and a mutex whats the recommended way to do this i would like to spawn off threads to perform certain tasks and use a threadsafe queue to communicate with them i would also like to be doing io to a variety of file descriptors while i am waitingwhats the recommended way to accomplish this do i have to created an interthread pipe and write to it when the queue goes from no elements to some elements is not there a better wayand if i have to create the interthread pipe why do not more libraries that implement shared queues allow you to create the shared queue and interthread pipe as a single entitydoes the fact i want to do this at all imply a fundamental design flawi am asking this about both c and python and i am mildly interested in a crossplatform solution but primarily interested in linuxfor a more concrete examplei have some code which will be searching for stuff in a filesystem tree i have several communications channels open to the outside world through sockets requests that may or may not result in a need to search for stuff in the filesystem tree will be arrivingi am going to isolate the code that searches for stuff in the filesystem tree in one or more threads i would like to take requests that result in a need to search the tree and put them in a threadsafe queue of things to be done by the searcher threads the results will be put into a queue of completed searchesi would like to be able to service all the nonsearch requests quickly while the searches are going on i would like to be able to act on the search results in a timely fashionservicing the incoming requests would generally imply some kind of eventdriven architecture that uses epoll the queue of thisksearch requests and the return queue of results would imply a threadsafe queue that uses mutexes or semaphores to implement the thread safetythe standard way to wait on an empty queue is to use a condition variable but that would not work if i need to service other requests while i am waiting either i end up polling the results queue all the time and delaying the results by half the poll interval on average blocking and not servicing requests,"['c++', 'python']" +138261,ultraportable small complex config file library in ansi c i am looking for a very portable minimalisticsmall xmlconfiguration language library in ansi c with no external dependencies or very few compiling down to less than 100k i need it for a moderately complex configuration file and it must support unicodesome more requirementsok to useembedstatically link into proprietary code credit will always will be given where credit is duenot necessarily xmlreally clean codeno weird or inconsistent string handlingutf8thank you fellas,['c'] +138263,nstextfield autocompletion delegate method not called i implemented the following delegate method for nstextfield to add autocompletion support nsarray controlnscontrol control textviewnstextview textview completionsnsarray words forpartialwordrangensrangecharrange indexofselecteditemnsinteger indexthe issue is that this method never gets called i can verify that the delegate of the nstextfield is set properly because the other delegate methods function as they should,['objective-c'] +138273,findviewbyid returns null in a dialog i have a custom dialog and when i try to get the value of an edittext it returns nullthis line returns nulledittext et edittextfindviewbyidridusername edithere is the code in its entiretyprotected dialog oncreatedialogint id switch id case dialog text entry layoutinflater factory layoutinflaterfromthis final view textentryview factoryinflaterlayoutalert dialog text entry null return new alertdialogbuildertictactoethis seticonattributeandroidrattralertdialogicon settitlegettitletext setviewtextentryview setpositivebuttonjoin game new dialoginterfaceonclicklistener public void onclickdialoginterface dialog int whichbutton try edittext et edittextfindviewbyidridusername edit playername etgettexttostring catch exception e create return null,"['java', 'android']" +138276,reasons not to use bool in objectivec since c99 c now has a proper boolean type bool objectivec as a strict superset of c inherits this but when it was created back in the 1980s there was no c boolean type so objectivec defined bool as signed charall of cocoa uses bool as does all nonnextapple cocoa code that i have seen obviously for compatibility with existing protocols eg applicationshouldterminateafterlastwindowclosed from nsapplicationdelegate matching the alreadydeclared type is preferable if for no other reason than to avert a warningfor cleanlinessreadability purposes stdboolh defines bool as a synonym for bool so those of us who do not want unnecessary underscores in our code can use thatthree other useful notesencode bool evaluates to b encodebool evaluates to c for signed charsizeof bool evaluates to 1 which follows from c99s definition that bool is only as large as necessary to hold its two possible values edit actually the standard says only that it must be alarge enougha to hold those two values it does not place an upper bound and in fact mac os x on 32bit powerpc defines it as 4 bytes size difference is another thing to file under possible boolvsbool compatibility issueson that note the only two possible values of a bool are 1 and 0 any other values are converted to one of these on assignment as if you had done a doublenegation or tested inequality against 0 0 the only ways to get a bool with some other value are the usual magicks pointer aliasing and unionsis there any reason not to use boolbool in new code,['objective-c'] +138281,ajax vs php for dynamic web pages why use ajax for dynamic web pages when you can do it only with php,['php'] +138283,thisplaying an image stored in a mysql blob when i run the code below it thisplays an image that is stored in a mysql db as a blob variable the problem is if i echo out anything else even something as simple as echo before i call the image the image will not thisplay only random characters thisplay if i echo out anything after the image the image thisplays but nothing does after it can someone tell me why this is and how i can go about thisplaying other items and the image together thanksphpincludeinclibraryphpconnecttodatabasesql select from theblogs where id 1result mysql querysql or diemysql error row mysql fetch arrayresultheadercontenttype imagejpegecho rowimagecontentdbclose,"['php', 'mysql']" +138286,how to change url after an ajax request i have a menu with some links that update the div content and execute the function onsuccess after it is loadedliajaxactionlinkhome index homeliliajaxactionlinkdownload index downloadliif i am on the url home and click the download link the div changes successfully the problem is that the url is not changedhow can i retrieve the requested url so i can call historypushstate on successful requests,"['c#', 'jquery']" +138287,jquery fadeoutemptyappendfadein does not work properly only the first time i am struggling to understand why i am getting the behaviour that i am seeing i have a piece of code that aims to fadeout a container replace the contents and then fade it back in again when it is donei am using jquery so the code looks like thisvar transitiontonewcontent functioncontainer new content containerfadeoutdelay10emptyappendnew contentfadeintransitiontonewcontentid pmagicpthe first time that the link that activates this transition is clicked the content is replaced instantly then the fadeout happens then it fades in againevery time after that when the link is clicked i am seeing the correct behaviour fadeout then fadein with the new contentany idea why this is happeningi have attached a complete html file which shows the behaviouri am fairly new to jquery and i am trying to do things the right way any comments regarding style will be appreciateddoctype htmlhtmlhead style typetextcss main container width 800px marginleft auto marginright auto marginbottom 3em margintop 0 height 100 position relative top 0px bottom 0pxloading float right position relative top 10px left 10px zindex 1sidebar float left width 240px border 078600 1px dashed position relative top 10px left 250px marginright 20px background c zindex 1 padding 10px fontsize 065em thisplay nonemain content zindex 0 position absolute top 0px left 5px width 100 height 100 float right background white paddingtop 0 paddingbottom 3em paddingleft 20px borderright 1px dotted 078600 borderleft 1px dotted 078600 bordertop 3px solid white style link relstylesheet typetextcss hrefmaincss headbody div idmain container div idsidebarh1sidebarh1psome textpdiv div idloading stylethisplay nonenbpsdiv div idmain content h1 idpage titletitleh1 div idpage contenth2headingh2psome testing textpdiv div div script typetextjavascriptvar include functionsrc documentwritescript typetextjavascript src src scr ipt includeincludevar bootstrapsites function var sidebar sidebar sidebardelay10fadein loadsitelistsidebarvar transitiontonewcontent functioncontainer new content containerfadeoutdelay10emptyappendnew contentfadeinvar editsite functionsite transitiontonewcontentpage content pthis is where the magic will happenpvar loadsitelist functioncontainer getjsonsiteslistjson functiondata var data parsejsonid 1 name cool name containeremptycontainer containerappendh2new headingh2 containerappendul idsiteslistul var siteslist siteslist eachdata functionidx site var id show site id site id siteslistappendlia id id href sitename ali idclickfunction editsitesite script script typetextjavascriptdocumentreadyfunction bootstrapsites scriptbodyhtml,"['javascript', 'jquery']" +138288,mysql show columns but exclude everything except the field names i would like to pull a tables field names from mysql into python and i know that show columns from project will work and i have read that you can add where to restrict it to just certain fields but i cannot find an example of how to return just the names of the columns and not type key null extra information what is the matching criteria to pull all field names for columns and none of the other description stuff,['mysql'] +138296,trying to add adb to path variable osx i am trying to develop for android and i want to add the adb to my path so that i can launch it really easily i have added directories before by for some reason adb does not want to be found this is very frustrating has anyone else had this problem beforei created a file profile and added the following to itexport path pathuserssimonlibsandroidsdkmac x86platformtoolsexport path pathuserssimonlibsandroidsdkmac x86toolswhen i check my environment path i see the followingusrbinbinusrsbinsbinusrlocalbinusrx11binlibsandroidsdkmac x86toolslibsandroidsdkmac x86platformtoolsso i know that it is added to my path variable now when i try to run adb i get that it is not found bash adb no such file or directorythis is very very frustrating could it be a problem with permissions has anyone had this problem with osx and android,['android'] +138297,make entire css sheet important is there a way to make an entire css style sheet take precedence over another i know you can do the important but can i do that with one line rather than modify all thousand properties on the sheetthanks,['css'] +138312,how to thisable 4 finger gestures on ipad i am testing an ipad on ios 43 which by default uses 4 finger updown gestures to switch out of apps this interferes with an onscreen piano keyboard i am using however and want to remove this gesture within the frame of the keyboard the keyboard does not use the gesture but it regularly thisrupts input for example when there is multitouch input,['ios'] +138317,difference between public and public static what does static meani know public means that it can be accessed from outside the class and private only from inside the class,['php'] +138325,image map support in firefox chrome and other browsers are image maps supported in chrome and firefox w3schools seems to suggest they are given this why would the following html fail image is thisplayed but no links work it does work correctly in ieimg srcimagesbackgroundfinalpng usemapmainimagemap altmainbackground styleborder none map idmainimagemap area shaperect althome page titlehome page coords309198413223 hrefdefaultaspx target area shaperect altabout me titleabout me coords245334319353 hrefaboutaspx target area shaperect altgallery titlegallery coords437271497300 hrefgalleryaspx target area shaperect alttattoo titletattoo coords249478307503 hreftattooaspx target area shaperect altcontacts titlecontacts coords395521464544 hrefcontactaspx target map,['html'] +138334,what causes a 422 unprocessable entity error in rails 3 this is the error message from the logfilestarted post stages for 127001 at 20110402 232218 0500processing by stagescontrollercreate as js parameters utf8a authenticity tokenob37mmciudhqannxfoeofwyvflnrtxlhfncydszlpsi stageproject id3 namefirst user load 11ms select users from users where usersid 1 limit 1user id 1 email encrypted password 2a10qubngm6lz366jrie0vk0gopxbgxd5jmfqwmh1lfllcec password salt 2a10qubngm6lz366jrie0vk0go reset password token nil remember token nil remember created at nil sign in count 264 current sign in at 20110403 041224 last sign in at 20110403 032137 current sign in ip 127001 last sign in ip 127001 username test f name test l name user created at 20110122 071745 updated at 20110403 041224 invitation token nil invitation sent at nil plan id 3 current state nil confirmation token nil confirmed at 20110211 231915 confirmation sent at 20110211 231820 role load 04ms select roles from roles inner join assignments on rolesid assignmentsrole id where assignmentsuser id 1completed 422 unprocessable entity in 302ms views 02ms activerecord 15msany ideas this is the new create actions in stagedef new project projectnew respond withproject enddef create project current userprojectscreateparamsproject project current userprojectsbuildparamsproject projectcurrent user current user if projectsave respond withproject status created location project do format flashnownotice project was successfully created formathtml redirect toproject formatjs render partial projectsshow locals project project layout false status created end else respond withprojecterrors status unprocessable entity do format formatjs render json projecterrors layout false status unprocessable entity formathtml render action new end end endthis is the form partial that creates the new stage stage stagenew new stage stagenew record form forstage html classajaxform id stageajaxform remote true thisable with new stage adding saving do f fhidden field project id fhidden field client id value projectclientid div classvalidationerror stylethisplaynonediv label forstage namespan classicon stageicon spanlabel input typetext classname size20 namestagename idstage name value stagename fsubmitnew stage add stage save class green awesome end,['ruby-on-rails'] +138335,is there a standard python data structure that keeps thing in sorted order i have a set of ranges that might look something like this0 100 150 220 500 10i would then add a range say 250 400 and the list would look like this0 100 150 220 250 400 500 10i would then try to add the range 399 450 and it would error out because that overlapped 250 400when i add a new range i need to search to make sure the new range does not overlap an existing range and no range will ever be in the list that overlaps another range in the listto this end i would like a data structure that cheaply maintained its elements in sorted order and quickly allowed me to find the element before or after a given elementis there a better way to solve this problem is there a data structure like that available in python i know the bisect module exists and that is likely what i will use but i was hoping there was something betteredit i solved this problem using the bisect module here is a link to the code it is a bit longish so i would not post it hereimplementation of byte range list,['python'] +138400,how to detect internet speed in php how can i create a php page that will detect the users internet speed and show it on the page something likeyour internet speed is kbs,['php'] +138406,sqlite3operationalerror database is locked i am trying to insert all values of a list to my sqlite3 database when i simulate this query by using the python interactive interpreter i am able to insert the single value to db properly but my code fails while using an iterationconnectionliteconnectdb namecursorconnectioncursorfor name in match cursorexecuteinsert into video diziname values nameconnectioncommiterrorcursorexecuteinsert into video diziname values namesqlite3operationalerror database is lockedany way to overcome this problem,['python'] +138423,upload file using nodejs and nodeformidable i succeed uploading file using nodejs and the formidable module yetthe file that got save on the thisk is in some kind of a bad format bad encodingeg if i upload an image i cannot view it if i upload a txt file gedit provide the following msggedit has not been able to detect the character encodingplease check that you are not trying to open a binary fileselect a character encoding from the menu and try againhere is the codeformencoding utf8formparsereq functionerr fields files fswritefiletestjs filesuploadutf8 function err if err throw err consolelogit is saved,['javascript'] +138427,c memory leak auto detection library i am searching for memory leak detection library something like i would just include it into source code then it should start detecting external programs might be good but i was looking for some library which can be linked into executable this i am searching for windows,['c++'] +138437,ruby way catch division by zero i have the following method to compute an averagedef compute averageabcde total abcdesumto f average a 2b 3c 4d 5esum total averageround2endit is nothing special but it has a problem that i expect all average equations have it might divide by zero if inputs are all zeroso i thought of doing thisdef compute averageabcde total abcdesumto f if total0 average 0 else average a 2b 3c 4d 5esum total averageround2 endend and that works but it feels kludgy to me is there a more elegant ruby way to avoid this division by zero problemwhat i am wishing i had was an unless then operator likeaverage numerator denominator unless denominator 0 then 0any suggestions,['ruby'] +138485,jaxl not doing anything using example facebook chat attempt jaxl new jaxlarray user pass not required we will use user session key instead hostchatfacebookcom domainchatfacebookcom function getfacebookkey global session global app secretapi key return array app secret your application secret key api key your application api key sessionsession key connecting user session key function doauthmechanism global jaxl jaxlauthxfacebookplatform function postauthpayload jaxl var dumpjaxl jaxlsendmessage what up register callback on required hook callbackd method will always receive 2 paramsjaxladdpluginjaxl post auth postauthjaxladdpluginjaxl get facebook key getfacebookkey start jaxl corejaxlstartcorestream exitnothing is outputing or showing up in the jaxl log any help would be greatly appreciated,['php'] +138496,python global variable def say boo twice global boo boo boo print boo booboo boo boosay boo twicethe output isboo boonot as i expected since i declared boo as global why is the output notboo boo boo boo,['python'] +138507,rich html emails in outlook 2007 and 2010 how do you remove the top margin i have a rich html email i was wondering how in outlook 2010 and 2007 you get the table in the layout to sit flush with the edge of the browserhave a look at this picthe pink is the background color of the body tag and the grey is the bg of the table they both have 0 everything margin paddting ect but there is still some space the pink should not be visibledoes anyone know how to get rid of this space on the bodyalso hereas some css for the start of the emailhtmlhead style typetextcss html body width100 body backgroundcolorff00ff style meta httpequivcontenttype contenttexthtml charsetutf8 titletesttitlehead body topmargin0 stylemargin0 padding0 width100 backgroundcolorff00ff table topmargin0 aligncenter cellpadding0 cellspacing0 width100 stylebordercollapse collapseborderspacing 0border 0 margin0 padding0 backgroundcolore cheers,"['html', 'css']" +138508,how to thismiss keyboard when using decimalpad i have a uitableview with a custom cell that has a textfield i have the decimalpad comes up and as we all know there is no done key i previously had resolved this type of issue when i had a decimal only textfield on a normal uiview by handling the touchesended event and then checking to see if the textfield was the first responder and if so it would then resign but if that technique could work now then i am not able to figure out whos touchesended i should be using the uiview that everything is presented on the uitableview the cell the cellcontroler the textfield i think i have tried everything i am hoping there is another cleaner way of dealing with thisanyone,['iphone'] +138530,effectively compress strings of 1010 characters in java i need to compress strings written in a known but variable language of anywhere from 10 to 10 characters into individual udp packets what compression algorithms available in java are well suited to this task are there maybe open source java libraries available to do this,['java'] +138538,where does the form submit to if there is no action specified here is the form that is confusing meh1 loginh1form action methodpost table alignleft border0 cellspacing0 cellpadding3 tr td username td td input typetext nameuser maxlength30 td tr tr td password td td input typepassword namepass maxlength30 td tr tr td colspan2 alignleft input typecheckbox nameremember font size2 remember me next time td tr tr td colspan2 alignright input typesubmit namesublogin valuelogin td tr tr td colspan2 alignleft a hrefregisterphpjoina td tr tableformi got the code from this tutorial and it works fine but i cant seem to understand where athe form submit too if no action is present,['php'] +138542,lowest common ancestor of a binary tree this is a popular interview question and the only article i can find on the topic is one from topcoder unfortunately for me it looks overly complicated from an interview answers perspectiveis not there a simpler way of doing this other than plotting the path to both nodes and deducing the ancestor this is a popular answer but there is a variation of the interview question asking for a constant space answer,['java'] +138555,ftpes ftp over explicit tlsl in python i need a python client to do ftpes explicit does anyone has experience with any python package that can do thisi am not able to do this in python but can connect to ftp server using tools like filezillathanks,['python'] +138577,how to stop webpages from capturing keypress with firefox caps policy i am tired of websites blocking my cmdc and cmdv copypaste especially when their javascript code allows controlc and controlv to pass by without being capturedi want to use the new caps security policy of firefox 4 to create a rule that gives noaccess to any site trying to capture onkeypress from event handlers on any element and stop them from reading the ewhichhere is a snip of javascript code that prevents me from pasting a zipcode into a text area because the site author wants numbers only in that field so cmdv paste is captured and dropped on the floorfunction numbersonlymyfield e dec var key keychar if e key ewhich else return true keychar stringfromcharcodekey control keys if keynull key0 key8 key9 key13 key27 return true else if 0123456789indexofkeychar 1 return true else return falsethen the html code will haveinput namezipcode onkeypressreturn numbersonlythis eventhow do i set a policy in firefox4 that thisables a sites ability to call this event handler functionusing the control de scripts extension i have tried adding the following block to the default policy that affects all sites but none worked to allow me to use a firefox metakey combination while focused in a text field that has this event handler listeninghtmlinputelementonkeypresswindownumbersonlywindowonkeypresswindowonkeypresseventpreventdefault now were up to firefox 14 instead of 4 has support for this kind of noaccess been made more availableusable to end firefox users like mei am looking for an answer on how to thisallow keypress event capturing using caps not hunting down each function name on each website and thisabling functions one by one,['javascript'] +138579,specify images for ipad in xcode like 2x for iphone 4 i have upgraded my current target to ipad and made a universal app and the time for adjusting my iphone app to ipad would decrease significantly if there is an answer for this questionby this time everybody know that if you have a image called footballpng and want support for retina thisplay you should double the size of the image and call it my question is if there is something for ipad like footballipad which is another sizepngif there is not a way to do this do i have to connect every image to an iboutlet and set the frame programmatically,"['objective-c', 'ios']" +138591,oracle get foreign keys i would like to get all foreign keys in a schema like thislet us say i have tables usersid username pass address id and addressesid texti have defined a fk on usersaddress id to the id column in addresseshow should i write a query that would return me the fk columns like users address id addresses id thanksselect from all cons columns a join all constraints c on aowner cowner and aconstraint name cconstraint name join all constraints c pk on cr owner c pkowner and cr constraint name c pkconstraint name where cr owner trwbi,['sql'] +138594,using int32tostring without format and iformatprovider why do i get the ca1305 warning i have been wondering about this one for quite some time but i cannot seem to find a definitive answer whenever i convert an integer to a string using the tostring method and i run a code analysis i get the following warning ca1305 microsoftglobalization because the behavior of inttostring could vary based on the current users locale settings replace this call in classmethod with a call to inttostringiformatprovider if the result of inttostring iformatprovider will be thisplayed to the user specify cultureinfocurrentculture as the iformatprovider parameter otherwise if the result will be stored and accessed by software such as when it is persisted to thisk or to a database specify cultureinfoinvariantculturethis is the very wellknown generic ca1305 warning which gets shown whenever you make a call to a method that has an overload that accepts an iformatprovider parameter while this is a very rightly warning in almost all cases i cannot think of anything that could go wrong when calling the default tostring without any format or formatprovider on an integer so please if anyone knows of anything that could go wrong enlighten me i am guessing there must be a good reason for the iformatprovider overloadby the way i do always make the call using the iformatprovider overload because it also seems to have a performance benefit if anyone has any insightful comments on this feel free to share them as well,"['c#', '.net']" +138610,what does t this mean in a delegate declaration i have just added a weak event implementation to a project using dustin campbells weakevent class although blindly using code i found on the internetTM is generally a bad idea it is a far better implementation than what i previously hacked together it seems to work well so far but in an effort to understand the code i came across the followingpublic class weakeventhandlert e iweakeventhandlere where t class where e eventargs private delegate void openeventhandlert this object sender e e i am used to declaring delegates types with just the object sender and eventargs args arguments so what does the t this part achieve obviously it is declaring something of weakeventhandlers t generic type but i have never seen this before and googling it is understandably hopeless,['c#'] +138611,get full url with hash to use as returnurl i have such urllocalhostloginlogonreturnurlqmy20search20wordf144704436524i need to get hash parameters to navigate in the application after authenticationi try to catch it like thisinput namereturnurl value viewcontexthttpcontextrequesturlpathandquery typehidden but result is loginlogonreturnurli tried to take away in the url then i get whole url but i need to use this url as it iswhy was url cuttedappreciate any help,"['c#', 'asp.net']" +138614,static variables in aspnetc i am using extensively static variables in my web application project now i have read from some articles that it is a global variable for the whole project and the data that is in the static variables can be shared or overwritten by other users i mean it is not user specific or session specificso is it general programming practice not to use static variables in the normal web application developmentare static variables not used at all just like goto statementkeyword meaning there are extensive restrictions to use them and preferably not used at all then in what cases do we use the static key wordthen i have this requirement that a particular variable has to be initialized only once in a particular webformaspxcs and the scope has to be restricted to only to that particular aspxcs and to that particular user who has logged in how do i meet this requirement if possible can any one illustrate this with code,"['c#', 'asp.net']" +138635,android horizontal scroll list possible duplicatehorizontal listview in android i want horizontal scroll like gallery im not using gallery because its center lockedcan some one here would help me out with this so i can have horizontal scrolling listi think best example of this is pulse news reader thanks,['android'] +138673,django i18n find supported languages i am determining a users language preference through some third party service he is also registered at this service provides me with a locale code eg en us if i do not have the corresponding language code in settingslanguages does django provide some integrated simple way to determine the best fallback choise from settingslanguages eg engbof course i know i could do a couple of string comparisons of the locale code etc by myself just being curious if there is a handier solution,['python'] +138676,raphaeljs library and smartphones i used the worderfull javascript library called raphaeljs on my website to draw maps animations and animated functionalities i have noticed that the script using this library work perfectly with iphone but not with androidcan someone confirm this just going on the demo page of raphaeljs will tell you if it works of not and if it does not does someone has any idea why and what could be testedthanks,"['javascript', 'android']" +138689,shall i use nodejs instead of rails for realtime webapps i am in the process of building a complex web app that must work a lot with realtime data and showing that data to the user given that i am more used to rails i am wondering if there is a big advantage of dumping rails and use nodejs to build the app or if there is a way i can have the realtime advantages of nodejs in railsbetter would be to be able to use nodejs and rails is that a possibilitythanks,['javascript'] +138706,communicate between a rails app and a nodejs app this question follows a previous one shall i use nodejs instead of rails for realtime webappsthe questionwhats the best way of communicating between a rails app and a nodejs app in order to take advantage of both technologiesthanks,"['javascript', 'ruby-on-rails']" +138718,how can i pass a variable parameter to an anonymous function using jquery can someone tell me what i am doing wrong here i simplified it below but i am basically trying to create a list and have a click event that references a variable only available in the loopfor var i 0 i datalength i newrow rowformat afirst newrowclickfunctioni return function alerti listappendnewrow,"['javascript', 'jquery']" +138726,eventmachine vs nodejs i am going to develop a collaborative site and one of the features will be collaborative editing with realtime changes ie when two or more users are editing the same doc they can see each other changes as soon as they happeni have some experience with ruby on rails so i was thinking about using eventmachine but with all this hype around nodejs i am know considering using it instead so what would be the main benefits of using nodejs instead of eventmachinetldrwhat are the main differences between eventmachine and nodejs besides the language,['ruby-on-rails'] +138734,android eclipse failing to debug debugging of my app is now suddenly broken it has been fine up to now and i even reloaded a known good version of my entire code and it still fails to debug or even run when i hit debug or run the app starts up and right when it is about to thisplay the app it crashes before even entering the main view i have a break point on the first line of code and it never even reaches it it just goes to source not found the source attachment does not contains the source for the file dexfileclassi am 100 certain all the code i have loaded is working as it is a saved backup which was saved when last workingalso what is odd is that if i unplug the cable at this point the app loads normally and works fine so this is definitely a debugging issue it is getting stuck somewhere at boot i have restarted my computer and phone several times to no availlogcat0404 1733462 debugandroidruntime4148 checkjni is off0404 1733462 debugdalvikvm4148 creating instr width table0404 1733502 debugandroidruntime4148 registering native functions 0404 1733712 debugandroidruntime4148 shutting down vm0404 1733712 debugdalvikvm4148 debugger has detached object registry had 1 entries0404 1733712 infoandroidruntime4148 note attach of thread binder thread 3 failed0404 1733902 debugandroidruntime4157 androidruntime start 0404 1733902 debugandroidruntime4157 checkjni is off0404 1733902 debugdalvikvm4157 creating instr width table0404 1733942 debugandroidruntime4157 registering native functions 0404 1734152 infoprocess107 sending signal pid 4137 sig 90404 1734152 infoactivitymanager107 force stopping package orgscanner uid101100404 1734162 erroractivitymanager107 fail to set top app changed0404 1734182 infousagestats107 unexpected resume of comhtclauncher while already resumed in orgscanner0404 1734192 infoactivitymanager107 starting activity intent actandroidintentactionmain catandroidintentcategorylauncher flg0x10 cmporgobdscanneractivityobdreadermainactivity 0404 1734202 debugandroidruntime4157 shutting down vm0404 1734202 debugdalvikvm4157 debugger has detached object registry had 1 entries0404 1734212 infoandroidruntime4157 note attach of thread binder thread 3 failed0404 17342 warninputmanagerservice107 window already focused ignoring focus gain of comandroidinternalviewiinputmethodclientstubproxy464105d80404 1734242 infoactivitymanager107 start proc orgscanner for activity orgobdscanneractivityreadermainactivity pid4165 uid10110 gids3003 30020404 1734332 warnactivitythread4165 application orgscanner is waiting for the debugger on port 810404 1734332 infosystemout4165 sending wait chunk0404 1734352 infodalvikvm4165 debugger is active0404 1734472 debugnorton community watchsmrsd3910 smrsd broadcast intent success0404 1734512 error3910 datadatacomsymantecmonitorapp log item1301930254txtdatadatacomsymantecmonitorapp log item0404 1734542 infosystemout4165 debugger has connected0404 1734542 infosystemout4165 waiting for debugger to settle0404 1734632 infoglobal3898 default buffer size used in bufferedreader constructor it would be better to be explicit if an 8kchar buffer is required0404 1734742 infosystemout4165 waiting for debugger to settle0404 1734862 debugdalvikvm3898 gc for malloc freed 4492 objects 274560 bytes in 41ms0404 1734942 infosystemout4165 waiting for debugger to settle0404 1735142 infosystemout4165 waiting for debugger to settle0404 1735342 infosystemout4165 waiting for debugger to settle0404 17352 infosystemout4165 waiting for debugger to settle0404 1735752 infosystemout4165 waiting for debugger to settle0404 1735952 infosystemout4165 waiting for debugger to settle0404 1736157 infosystemout4165 debugger has settled 14510404 1737296 debugdalvikvm4165 threadid1 still suspended after undo sc1 dc1 sy,['android'] +138759,integer constant is too large for long type possible duplicatelong long in cc writing a simple program for a project euler problem refuses to compile because integer constant is too large for long type even though it should be well within the size limits of an unsigned long long using the devc compilercode in questioninclude iostreambool isprime unsigned long long i ifi1i0 return false ifi2 return true forunsigned long long k2ki1k ifik0 return false return trueint main forunsigned long long i600851475143i0i problematic line ifisprimei stdcouti stdcinget return 0,['c++'] +138781,how start ghunit tests without tapping run button i use ghunit framework for testing static library at this moment i need tap the button run to start my tests but i would like to start tests when application launched because i need teamcity launch my testapp so how can i modified standart ui and start tests automatic,['objective-c'] +138788,how to get a uitableview to go to the top of page on reload i am trying to get a uitableview to go to the top of the page when i reload the table data when i call the following from voidpickerviewuipickerview pickerview didselectrownsintegerrow incomponentnsintegercomponent a bunch of code atableview reloaddataalong those same lines i would also like to be able to go to a specific section when i reload the table datai tried placing the following which seems applicable only to the row before and after the reload but nothing happenstableview scrolltorowatindexpath0 atscrollpositionuitableviewscrollpositiontop animatedyes,['iphone'] +138811,how many memory pages do c compilers on desktop oses use to detect stack overflows this question is related to but different from this one about variable length arrays in c99the answers point out that one danger with allocating variable length arrays or just large arrays of a fixed size in the stack is that the allocation may fail silently as opposed to say calling malloc which explicitly tells the caller whether allocation succeededmodern nonembedded compilation platforms use an invalid memory zone to detect some stack overflows at no additional cost the checks are only the checks already made for free by the mmu this does not protect at 100 from the above problem because a very large local array may cause the stack pointer to jump over the invalid areadoes any one know how many pages are typically allocated for this detection i guess it would be at least 4kib but it could be more is that a choice made by the compiler or the os and in either case is there a way to change it,['c'] +138815,is this the example of polymorphism i kinda know what polymorphism is but failed to understand it clearly also my code is followingclass human public virtual void cleantheroom class womanhuman public override void cleantheroom women clean faster class manhuman public override void cleantheroom men clean slower different code here class childhuman public override void cleantheroom empty children are lazy should i explain this is polymorhism because all derived classes from base class human contain method cleantheroom but each of them it implements differently,['c#'] +138818,soap ui generated code i have a webservice i am trying to build a client fori have the following wsdlit requires authentication looking at the wsdl description i see no method that takes an authentication object nor username and passwords as arguments using netbeans i have generated jaxws sources for the wsdl i however can not figure out what to do after thatusing soapui i can connect to the webservice and run all the methods but once again i want to build this into a client that can be run without my interactionmy problem comes in figuring out how to use this generated code which it appears netbeanstv had a videonetbeans soapui plugin video 2 which has since been lost does anyone know of any tutorials or know of any examples of how i can use this generated code to access the webserviceso i have a method checkifauthorizedrunning in soapui i get the following xmlsoapenvelope xmlnssoap xmlnscmic soapheader cmicauthentication optional cmicusernameusernamecmicusername optional cmicpasswordpasswordcmicpassword cmicauthentication soapheader soapbody cmiccheckifauthorized soapbodysoapenvelopei can then run that request in soap ui and get back the response that authentication was a successwith the jaxws code generated with netbeans and with soapui as well i have the followingpackage javaapplication7 author grant public class main public static void mainstring args boolean result checkifauthorized systemoutprintlnthe result is result private static boolean checkifauthorized javaapplication7cmicdatacenterservice service new javaapplication7cmicdatacenterservice javaapplication7cmicdatacenterservicesoap port servicegetcmicdatacenterservicesoap return portcheckifauthorized this will fail with the following errorrunexception in thread main javaxxmlwssoapsoapfaultexception server was unable to process request object reference not set to an instance of an object at comsunxmlinternalwsfaultsoap11faultgetprotocolexceptionsoap11faultjava178 at comsunxmlinternalwsfaultsoapfaultbuildercreateexceptionsoapfaultbuilderjava1 at comsunxmlinternalwsclientseisyncmethodhandlerinvokesyncmethodhandlerjava108 at comsunxmlinternalwsclientseisyncmethodhandlerinvokesyncmethodhandlerjava78 at comsunxmlinternalwsclientseiseistubinvokeseistubjava107 at proxy30checkifauthorizedunknown source at javaapplication7maincheckifauthorizedmainjava24 at javaapplication7mainmainmainjava17java result 1this is the same problem i ran into when trying to use python for the service i have since chosen to go with java as i feel i may have quicker turnaround on parsing the xml and creating objects as i already have the entities for this createdthank yougranti did not want to answer this because i would still like to figure out what i can do here but i did just end up writing the request by hand with the following now i can just convert this into an xml object and go about my way but i imagine soapui makes all of this much easier what i really do not understand is how to use soapui to build this request and incorporate it into my projectpublic class main public final static string default server public final static string soap action public static void mainstring args string server default server string username username string passwordpassword try url url new urlserver httpurlconnection connection httpurlconnection urlopenconnection connectionsetdooutputtrue connectionsetdoinputtrue connectionsetrequestmethodpost connectionsetrequestpropertycontenttype applicationsoapxml charsetutf8 connectionsetrequestpropertyhost wcmicdataservicescom outputstream out connectiongetoutputstream writer wout new outputstreamwriterout uncomment the following and comment out the previous two lines to see your xml bufferedwriter wout new bufferedwriternew filewritertmptestxmlxml start writing soap request envelope woutwritexml version10 encodingutf8rn woutwritesoap12envelope woutwritexmlnsxsi woutwrite woutwritexmlnsxsd woutwrite woutwritexmlnssoap12 woutwritern soap request header start woutwritesoap12headerrn start writing soap request authentication woutwriteauthentication xmlns woutwritern woutwriteusername username usernamern woutwritepassword password passwordrn end authentication woutwriteauthenticationrn end the header woutwritesoap12headerrn start writing the body woutwritesoap12body woutwritegetcurrentdataver1 xmlns woutwrite rn end the body woutwritesoap12bodyrn end the envelope woutwritesoap12envelopern woutflush woutclose bufferedwriter fout new bufferedwriternew filewritertmptestxmlresponsexml inputstream in connectiongetinputstream createfilein tmptestxmlresponsexml catch ioexception e systemerrprintlne public static void createfileinputstream io string filename throws ioexception fileoutputstream fout new fileoutputstreamfilename byte buf new byte256 int read 0 while read ioreadbuf 1 foutwritebuf 0 read,['java'] +138823,call a function in python and pass only the arguments it expects how do i call a function and only pass it the arguments that it expects for example say i have the following functionsfunc1 lambda a truefunc2 lambda a b truefunc3 lambda c truei want some python code that is able to successfully call these functions without raising a typeerror by passing unexpected arguments iekwargs dicta1 b2 c3for func in func1 func2 func3 funckwargs some magic herei am not interested in just adding kwargs to the functions when i define them,['python'] +138824,comprehensive tutorial on pyinstaller i am looking for a tutorial on pyinstaller that will explain things likehow to create pkg fileshow to includeexclude moduleshow to include data files inside the install directory i cannot make much sense out of the standard pyinstaller documentation,['python'] +138825,validaterequestfalse is acting weird aspnet 40 ci have my httpruntime requestvalidationmode20 in the webconfig andi have my validaterequestfalse in page directorieson one page i send some data html from a ckeditor textarea to a database works fineon another page i fill the ckeditor with data from a database then i update it send it back and i get the famous a potentially dangerous requestform value was detected from the clientmakes me very confused the only difference is that on the second page the data gets dynamically inserted into the textarea where on the first page the textarea is empty on pageload am i missing something here im pretty sure encodingdecoding doesnt mean anything as the framework stops it before i can even start messing with it on the backend,"['c#', 'asp.net']" +138831,how do i thisable an eclipse warning in the derived imarketbillingservicejava file folksi have android application that presently has 1 warning in line 80 of the imarketbillingservicejava file that is part of the inapp purchasing code newly supplied by google the warning readsthe method getinterfacedescriptor from the type imarketbillingservicestubproxy is never used locallythis file is a derived file and may not be edited i realize that i may ignore this warning however i like to have my projects have zero errors and warnings i find this is a helpful principle especially when working with thistributed teamscan someone tell me how to have eclipse thisableignore this warning thanks,['android'] +138867,herokus trying to install development gems even after i have told it not to i am diving into ror and i am using heroku to host the test app i am building when i do a push to heroku it crashes when trying to intall the linecache19 gem which is used by rubydebug19 geminstalling ruby core source 014 installing linecache19 0511 with native extensions usrruby187librubysite ruby18rubygemsinstallerrb483in build extensions error failed to build gem native extension geminstallerextensionbuilderrorafter searching all over the web for this problem everyones solution washeroku config add bundle withouttest development app app namebut the push to heroku still crashes even after i did that heres my gemfilesource gem rails 305gem carrierwavegem mini magickgem foggroup development do gem annotatemodels 104 gem sqlite3 gem rubydebug19 gem sqlite3ruby require sqlite3endi even uninstalled the rubydebug19 gem and it is still crashing and trying to install the linecache19 gem why would not this linecache19 gem go away i am new to all this and as such i am sure i am missing something obvious your thoughtsthanks for your wisdom,['ruby-on-rails'] +138870,const string vs define i need to share some strings in my c program should i use define or const string thanksmystring1h define str1 str1define str2 str2 ormystring2h extern const string str1 extern const string str2 mystringcpp const string str1 str1 const string str2 str2,['c++'] +138871,pil libjpegso8 cannot open shared object file no such file or directory compiled the libjpeg v8 pil 117 and and import for imaging works on the system python but spouts this error inside the virtualenvlibjpegso8 cannot open shared object file no such file or directoryhere is the error run with a python v interpreter inside the virtualenv import imagingdlopenhomeygamretutadevpydjangolibpython26sitepackagespil imagingso 2traceback most recent call last file stdin line 1 in moduleimporterror libjpegso8 cannot open shared object file no such file or directoryand here are the pathshomeygamretutadevpydjangolibpython26sitepackagesthistribute0614py26egghomeygamretutadevpydjangolibpython26sitepackagespip081py26egghomeygamretutadevpydjangolibpython26homeygamretutadevpydjangolibpython26platlinux2homeygamretutadevpydjangolibpython26libtkhomeygamretutadevpydjangolibpython26liboldhomeygamretutadevpydjangolibpython26libdynloadusrlibpython26usrlibpython26platlinux2usrlibpython26libtkhomeygamretutadevpydjangolibpython26sitepackageshomeygamretutadevpydjangolibpython26sitepackagespili am using ubuntu 1010 and this is the unamea outputlinux ygamdesktop 263528generic 49ubuntu smp tue mar 1 144058 utc 2011 i686 gnulinuxi am using python 26i followed the following guides already jpeg resync to restart,['python'] +138873,iphone cgcontextref cgbitmapcontextcreate unsupported parameter combination in my application i need to resize and crop some images stored locally and online i am using trevor harmons tutorial which implements uiimageresizeon my iphone 4ios 431 everything works ok i have no problems but on my iphone 3g ios 32 the resizing and crop methods are not working for any picture the locally stored ones are pngs this is the console outputtue apr 5 0234 andreismacbookprolocal puzzle12453 error cgbitmapcontextcreate unsupported parameter combination 8 integer bitscomponent 32 bitspixel 3component color space kcgimagealphalast 288 bytesrowtue apr 5 0234 andreismacbookprolocal puzzle12453 error cgbitmapcontextcreate unsupported parameter combination 8 integer bitscomponent 32 bitspixel 3component color space kcgimagealphalast 288 bytesrowtue apr 5 0234 andreismacbookprolocal puzzle12453 error cgbitmapcontextcreate unsupported parameter combination 8 integer bitscomponent 32 bitspixel 3component color space kcgimagealphalast 288 bytesrowtue apr 5 0234 andreismacbookprolocal puzzle12453 error cgbitmapcontextcreate unsupported parameter combination 8 integer bitscomponent 32 bitspixel 3component color space kcgimagealphalast 288 bytesrowthis is the crop method uiimage croppedimagecgrectbounds cgimageref imageref cgimagecreatewithimageinrectself cgimage bounds uiimage croppedimage uiimage imagewithcgimageimageref cgimagereleaseimageref return croppedimagethe resize method is this uiimage resizedimagecgsizenewsize transformcgaffinetransformtransform drawtransposedbooltranspose interpolationqualitycginterpolationqualityquality cgrect newrect cgrectintegralcgrectmake0 0 newsizewidth newsizeheight cgrect transposedrect cgrectmake0 0 newrectsizeheight newrectsizewidth cgimageref imageref selfcgimage cgcontextref bitmap cgbitmapcontextcreatenull newrectsizewidth newrectsizeheight cgimagegetbitspercomponentimageref 0 cgimagegetcolorspaceimageref cgimagegetbitmapinfoimageref ifbitmap nil return nil cgcontextconcatctmbitmap transform cgcontextsetinterpolationqualitybitmap quality cgcontextdrawimagebitmap transpose transposedrect newrect imageref cgimageref newimageref cgbitmapcontextcreateimagebitmap uiimage newimage uiimage imagewithcgimagenewimageref cgcontextreleasebitmap cgimagereleasenewimageref return newimagecan someone explain to me way i have this issuethank youandrei,['iphone'] +138878,c entity framework 4 navigation properties causing slow performance on commit i apologize for the lack of detail in this question the first thing i need help on is knowing where to look to find more detaili have a problem with enity framework 4 navigation properties apparently causing poor performance when committing changesthisobjectcontextsavechangesis taking 30 seconds when one of the navigation properties receipts table contains around 80 rows which is not many so should be fine i have used the sql profiler and can see that ef issues a select from receipts and that it is very slowexec sp executesql nselect extent1id as id full field list cut for brevity from dboreceipts as extent1where extent1warehouseid entitykeyvalue1nentitykeyvalue1 intentitykeyvalue11at the moment i cannot even see why it needs to select all rows from this table when objectcontextsavechanges is called it does need to insert 1 row into this table but that does not explain why it does a select all first and does not explain why that select takes so long the same query takes 1 second in query managerso my question right now i do not exactly know what the problem is yet iswherehow can i look for more details about the problem i cannot debug into objectcontextsavechanges so i do not know whats happening inside itwhy would ef try to select from receipts why is it so slow the exact same query copied pasted into query manager is nearly instantedit i have confirmed that it is the receipt code that is slow by commenting out the call to this method private void addreceiptpurchaseinvoice invoice purchaseinvoiceline invoiceline if invoice null invoiceline null product product invoicelineproduct if product null receipt receipt new receipt foo bar warehousedetail detail new warehousedetail foo bar receiptwarehousedetailsadetail invoicereceiptsaddreceipt but i still cannot see why this causes ef to issue that select query i believe that it might be a lazy loading issue caused by invoicereceiptsaddreceipt because before that line invoicereceipts is empty and in order to add to the receipts it must first load the collection but that does not explain why it is selecting by warehouseid1 when it should be selecting by the invoiceidedit 2 i have fixed the problem by replacing the ef code in this method with direct sql commands this is not a great idea i should not be throwing sql around when i have got an otherwise perfectly good orm but right now i still do not understand why ef was running the select query private void addreceiptpurchaseinvoice invoice purchaseinvoiceline invoiceline if invoice null invoiceline null product product invoicelineproduct if product null receipt receipt new receipt foo bar warehousedetail detail new warehousedetail foo bar int id sqlhelperaddwarehousedetaildetail receiptwarehousedetailid id sqlhelperaddreceiptreceipt,['c#'] +138887,php capitalize after dash q durhamregionq ucfirstqq durhamregionhow would i capitalize the letter after the dash durhamregion would i have to split the two and capitalize,['php'] +138891,java explicit reference casting how come there is no compiler error casting number to list i thought the types had to be relatenumber k 10list m new arraylistm listk,['java'] +138893,understanding javaps output for the constant pool when running javap on a very simple helloworld application i have some confusion on the output around the constant pooltest codepublic class testclass public static void mainstring args systemoutprintlnhello world javap c verbose output snipped header consts 122 snippedconst 22 string 23 hello worldconst 23 asciz hello worldpublic static void mainjavalangstring signature ljavalangstringv code stack2 locals1 args size1 0 getstatic 16 field javalangsystemoutljavaioprintstream 3 ldc 22 string hello world 5 invokevirtual 24 method javaioprintstreamprintlnljavalangstringv 8 return debug info snippedok so on line 3 we see a pushing of the hello world constant onto the stack via 22 but const 23 seems to hold the actual value i guess i am a little confused with what the number means when it appears on the righthandside of the printout oraclesuns man page for javap leaves much to be desired,['java'] +138902,git deploy php app to multiple ec2 nodes i have been reading a lot of articles that talk about postupdate hooks to deploy websites using git however i do not understand how this is done on ec2i want to use the auto scaling feature of ec2 to automatically add microsmall nodes behind my load balancer based off an ami of my serverhow can i make it somy nodes automatically fetch the latest version of the site from the repository upon startingpush updates to all nodes trigger update immediately if possible even the ones that are dynamically added therefore no configuration beyond what the ami already contained,['php'] +138921,rails factory girl getting email has already been taken this is my factory girl code and every time i try to generate a review it is telling me that email has already been taken i have reset my databases set the transition in spec helper to true but still have not solved the problem i am new to this am i using the association wrong thanksfactorydefine user do user username testing user useremail userpassword foobar userpassword confirmation foobarendfactorydefine course do course coursetitle course courselink wumnedu coursesections 21 coursedescription test course description courseassociation userendfactorydefine review do review reviewtitle test review reviewcontent test review content reviewassociation user reviewassociation courseend,['ruby-on-rails'] +138970,is shared readonly data copied to different processes for python multiprocessing the piece of code that i have looks some what like thisglbl array a 3 gb arraydef my func args def param glbl array do stuff on args and def paramif name main pool poolprocesses4 poolmapmy func range10is there a way to make sure or encourage that the different processes does not get a copy of glbl array but shares it if there is no way to stop the copy i will go with a memmapped array but my access patterns are not very regular so i expect memmapped arrays to be slower the above seemed like the first thing to try this is on linux i just wanted some advice from stackoverflow and do not want to annoy the sysadmin do you think it will help if the the second parameter is a genuine immutable object like glbl arraytostring,['python'] +138975,java how to insert clob into oracle database i need to write a xml file content into oracle database where the column is of clob datatypehow will i do thatthanks,['java'] +138982,how to prevent calls to systemexit from terminating the jvm i am almost certain this is impossible but it is worth a tryi am writing a command line interface for a certain tool i am talking about a java application that invokes another java application the tool calls systemexit after execution which in turn terminates my own execution environment i do not want thatis there any way to ignore systemexit calls,['java'] +138986,jquery keep link clickable in clickable div what i want to do is prevent the click on the div if a users clicks a link inside that divbut without using the clickfunction on the linkheres the codedivfeatureclickfunction windowlocation thisattrrelheres an example content of the divdiv idfeature relurlnumberonesome texta hrefjavascripttopicchangethis classinsidelinklinkadivand for some specific reason i cannot use something like thisinsidelinkclickfunctionevent eventstopimmediatepropagationi have to use this topicchange function is there any way to prevent the event propagationthanks,"['jquery', 'html']" +138987,using solr for indexing multiple languages were setting up a solr to index documents where title field can be in various languages after googling i found two optionsdefine different schema fields forevery language ie title entitle fr applying differentfilters to each language then queryone of title fields with acorresponding language creatingdifferent solr cores to handle eachlanguage and make our app querycorrect solr corewhich one is better what are the ups and downsthanks,['java'] +139001,is there any tools to help me refactor a method call from using positionbased to namebased parameters i wish to transform code likevar p new personian smith 40 16tovar p new personsurname ian givennamesmith weight40 age16as a first step in making the code more readable i am willing to use a 3rd party refactoring tool if need beplease do not tell me to use parameter objects and factor methods etc these may come later once i can at least read the code,['c#'] +139004,getting array of values from jquery object i have following objectinputcheckboxcheckedinput classali checker typeacheckbox category uida13 category languageadaa input classali checker typeacheckbox category uida131 category languageadaaif there is any helper in jquery which allows me to get value of category uid for all elements and returns it as the another array expected result13 131,"['javascript', 'jquery']" +139016,difference between and case i am new to ruby and am trying to work something out which is confusing me while writing a simple parser i found that comparing a char with a would produce a different result than comparing it with a case expressionfileopenquotetxt do f fcharseach do c puts c quote err puts case c when then quotecase else errcase end p c c c endendassuming quotetxt is a 1byte file containing a single quote character 0x22 this producesquoteerrcasetruetruei am assuming i have done something wrong but i cannot figure out what it is can anyone helpthis is in ruby 192 by the way,['ruby'] +139022,benefit of using parcelable instead of serializing object as i understand bundle and parcelable belongs to the way android performs serialization in it is used for example in passing data between activities but i wonder if there are any benefits in using parcelable instead of classic serialization in case of saving state of my business objects to the internal memory for example will it be simpler or faster than the classic way where should i use classic serialization and where better to use bundles,['android'] +139053,c design pattern for passing a large number of parameters i have a reasonablysized class that implements several logicallyrelated algorithms from graph theory about 1015 parameters are required as input to the algorithm these are not modified by the algorithm but are used to guide the operation of it first i explain two options for implementing this my question is what is a common way to do so whether it is or is not one of the two optionsi personally do not like to pass these values as parameters to the function when n is large especially while i am still developing the algorithmvoid runalgorithmint param1 double param2 bool paramninstead i have a class algorithm that contains the algorithms and i have a struct algorithmglobals that contains these parameters i either pass this struct tovoid runalgorithmalgorithmglobals const globalsor i add a public algorithmglobals instance to the classclass algorithm public algorithmglobals globals void runalgorithmthen elsewhere i would use it like thisint main algorithm algorithm algorithmglobalsparam1 5 algorithmglobalsparam2 73 algorithmglobalsparamn 5 algorithmrunalgorithm return 0note that the constructor of algorithmglobals defines good defaults for each of the parameters so only the parameters with nondefault values need to be specifiedalgorithmglobals are not made private because they can be freely modified before the runalgorithm function is called there is no need to protect them,['c++'] +139054,how to make each unicorn worker of my rails application log to a different file how can i make each unicorn worker of my rails application writting in a different log file the why problem of mixed log filesin its default configuration rails will write its log messages to a single log file logenvironmentlogunicorn workers will write to the same log file at once the messages can get mixed up this is a problem when requestloganalyzer parses a log file an exampleprocessing controller1action1 processing controller2action2 completed in 100mscompleted in 567msin this example what action was completed in 100ms and what action in 567 ms we can never be sure,['ruby-on-rails'] +139056,multiple select element onchange i have a select element that allows for multiple selections i would like to thisplay the selected values in another part of the page in a div or something as the user makes changes to what is selectedis the only way of doing this to iterate over the options and check if selected is true this would not be preferable since each onchange event would require the entire select element to be iterated overheres a fiddle that demonstrates how i am currently doing it but i am hoping maybe there is a better way than having to iterate over all the options on every change multiple select elment onchange fiddle,"['javascript', 'jquery', 'html']" +139076,how can i determine which c compiler is used if i only can alter the c code and inspect console output suppose there is a system like codepadorg a black box that can accept c code compile it run it and present the console output how could i determine what c compiler such system uses,['c++'] +139097,how to connect to a java program on localhost jvm using jmx i should connect to a java program on localhost jvm using jmx in other words i want to develop a jmx client to config a java program on localhostdo not recommend using jconsole jconsole is not suitable because it is general jmx client and have negative effect on main program performancesamples on oracle site use rmiconnector and hostport params but i do not know where should set jmx portjconsole have an option to connect to java processes by pid but i do not find any method in jmx api that have pid as input param,['java'] +139103,how to enable datagridview sorting when user clicks on the column header i have a datagridview on my form and i populate it with thisdatagridview1datasource studentsselects new id sstudentid rude srude nombre sname apellidos slastnamefather slastnamemother nacido sdateofbirth orderbys sapellidos tolistnow i use the sapellidos as the default sort but i would also like to allow users to sort when clicking on the column headerthis sort will not modify the data in any way it is just a client side bonus to allow for easier searching for information when scanning the screen with their eyesthanks for the suggestions,['c#'] +139114,regular expression match a sentence how can i match a sentence of the form hello world or hello world the sentence may contain digit 09 any information will be very helpful to me thank you,['java'] +139119,how to generate qr code in iphone how to generate qr code from iphone with password protection i should generate qr code for given image with password protection when read it from iphone,"['iphone', 'objective-c']" +139129,is there any penaltycost of virtual inheritance in c when calling nonvirtual base method does using virtual inheritance in c have a runtime penalty in compiled code when we call a regular function member from its base class sample codeclass a public void foovoid class b virtual public a class c virtual public a class d public b public c d barbarfoo,['c++'] +139130,android keylistener for an edittext not receiving keys i have an edittext that i want to monitor keyevents for and i have a listener set up as followsmtext edittext thisfindviewbyidridtitlemtextsetonkeylistenernew onkeylistener override public boolean onkeyview v int keycode keyevent event final int view vgetid switch view case ridtitle logdlog tag key handled break return false my problem is that when the edittext is being typed into using the virtual keyboard the only key press that triggers the logging is the backspace key i have verified that all other keypresses are not even triggering onkey i am sure this is something simple but did not find anything on so that seemed to deal with thisthankspaul,['android'] +139131,configuring the builtin c3p0 pooling in hibernate using spring i learned that to configure c3p0 pooling in hibernate we can have write the configuration in hibernatecfgxml such thisproperty namehibernatec3p0min size2property property namehibernatec3p0max size5property property namehibernatec3p0timeout600property property namehibernatec3p0max statements0property property namehibernatec3p0idle test period300property property namehibernatec3p0acquire increment1propertyhowever i configured hibernate using spring when i tried to do below it wouldnt workbean iddatasource classorgapachecommonsdbcpbasicdatasource property namedriverclassname valuecommysqljdbcdriver property nameurl valuejdbcmysqllocalhostnews loader property nameusername valueblah property namepassword valueblah property namehibernatec3p0min size value2 property namehibernatec3p0max size value5 property namehibernatec3p0timeout value600 property namehibernatec3p0max statements value0 property namehibernatec3p0idle test period value300 property namehibernatec3p0acquire increment value1 beani have read about using the standalone c3p0 pooling which can be configured using spring but is there any way that i can configure the builtin c3p0 pooling in hibernate using springenlighten me coz i am a beginner,['java'] +139132,mysql community server minimum system requirements can anyone point me to a link or provide me information about the minimum systemhardware requirements required to runinstall mysql community server on a windows machinethanks,['mysql'] +139137,visiblox wpf getting chart points to scroll horizontally i am using the visiblox wpf api and am having trouble getting the chart points in my line chart to scroll horizontally instead of scrolling the points are get squashed together in which this is not particularly a problem except that i expect to have 100s of data points on the chart i have looked throughout the examples available on the visiblox website but could not find what i was looking for ive attached an example screenshotany ideasthanks for your helpsparky,['c#'] +139151,rails multiple associations between two models i have flight person and glider models in a rails 3 app i have defined custom relationships because i need more than one foreign key referencing a person from the flights table associations work but oneway onlyclass flight activerecordbase belongs to pilot class name person belongs to instructor class name person belongs to towplane pilot class name person belongs to airplane instructor class name person belongs to glider belongs to rep glider class name glider belongs to departure airfield class name airfield belongs to arrival airfield class name airfieldendclass glider aircraft has many flights has many replaced flights foreign key rep glider id class name flightendclass person activerecordbase has many flights foreign key pilot id class name flight has many instructed flights foreign key instructor id class name flight has many towed flights foreign key towplane pilot id class name flight has many instructed towing flights foreign key airplane instructor id class name flightendwhat worksflightfirstgliderflightfirstrep gliderflightfirstpilot flightfirstinstructor flightfirsttowplane pilotflightfirstairplane instructorgliderfirstflights gliderfirstreplaced flights what does not work nomethoderror matchpersonfirstflightspersonfirstinstructed flightspersonfirsttowed flightspersonfirstinstructed towing flightsi am almost there but i do not understand how gliderfirstflights does work when personfirstflights does notupdate associations with airfield works so i am clueless as to why it does not work with personclass airfield activerecordbase has many takeoff flights foreign key departure airfield id class name flight has many grounded flights foreign key arrival airfield id class name flightendworks correctlyairfieldfirsttakeoff flights airfieldfirstgrounded flightsflightfirstdeparture airfieldflightfirstarrival airfield,['ruby-on-rails'] +139174,minimize startup time for aspnet i have multiple web services wcf running in iis when the services are warm loaded typical requests take about 05 seconds to complete however when the application is not warm cold start the first hit takes some 20 seconds before the service is up and running the same happens when an app pool recycle occursi am looking to reduce the cold start times for this web service some actions i have already performed areconfigured the application pool so that it does not recycle after 20 min idle time so that the application stays warm this minimizes the occurence of cold starts but does not make cold starts faster app pool recycles are now limited but do stil occurmodified the machineconfiglike thisruntime see vvs90aspx generatepublisherevidence enabledfalseruntimethis reduces startup times from 20 secs to about 10 secsi have tried using ngen to precompile the assemblieslike thisfor d in dll do ngen install dthis does not reduce startup times only adds complexity to deploymenti would really like to reduce the cold start times even further what options do i have to do thison a side note what is the best way to find out where the time is spend during startup how do i monitor whats going on,"['.net', 'asp.net']" +139184,generics with generic parameters and abstract class i have got two generic base classes the second generic class has a constraint on its parameter of the first classabstract class firstclasst abstract class secondclassu where you firstclass this does not work because firstclass is not defined so i need to do thisabstract class firstclasst abstract class secondclassu t where you firstclasst which works however this makes implementing these abstract classes uglyclass someclass class myfirstclass firstclasomeclass class mysecondclass secondclassmyfirstclass someclass this seems redundant to me because i am specifying someclass twice is there a way to declare it in such a way that t from firstclass is automatically the you for secondclass what i would really like this to look like isclass someclass class myfirstclass firstclasomeclass class mysecondclass secondclassmyfirstclass while i doubt this exact scenario is possible is there a cleaner what to do what i am trying to doeditseveral people have suggested making an ifirstclass interface but my definitions are closer to thisclass firstclasst public t myobj get set class secondclassu t where you firstclasst you myfirstclass get set with an interface i cannot access myfirstclassmyobj from secondclass while i could create a object t myobj get set on ifirstclass then use new to hide it silverlight throws a fit in the binding if i do this,['c#'] +139190,is there any java script web crawler framework is there any javascript web crawler framework,['javascript'] +139208,thisable tab key on a specific div i have the following structurediv idwrapper div iddiv1some contentdiv div iddiv2some contentdivdivi want to thisable the tab key on div2 i mean the elements of div2 would not receive focus when the tab key is pressedis there any easy way to create this tab key blocker using javascriptjquery,"['javascript', 'jquery', 'html']" +139221,missing template blogsindex on ruby on rails project for one of my projects i am getting this exception every now and thenactionviewmissingtemplate missing template blogsindex with handlersrxml erb builder rjs haml rhtml formatsimagejpeg imagepjpeg imagepng imagegif localeen en in view paths varwkeeponpostingreleases20110403083651appviewsit seems someone is requesting an image from a url that is not an imagehttp accept imagejpeg imagepjpeg imagepng imagegifany ideas what to do about it do i have to implement a handler for one of those and return to get rid of this exceptions or is there a better way to handle itnow i am also getting thisactionviewmissingtemplate missing template blogsindex with formatstext handlersrjs haml rhtml erb rxml builder localeen en in view paths varwkeeponpostingreleases20110415040109appviewsis not there a way to send back html no matter what format is requested,['ruby-on-rails'] +139225,free alternative to ubigraph i am trying to generate a large graph visualization using ubigraph and its xmlrpc interface however ubigraphs xmlrpc server is not fast enough to handle the call rate generated by my python code and freezes i have tried all the performance tips listed on the website to no avail the direct wrapper is not available in the free version of ubigraph hence my question are there any free as in speech alternatives to ubigraph,['python'] +139249,build only one project in a solution from command line i have a solution with lots of solution folders with lots of c projects inside themhow do i buildrebuild only one of those projects from command linei guess there is some way to do it using msbuild but i do not know anything about msbuildthanks,['c#'] +139271,changing the base url for rails 3 development i know i am going to deploy to an environment with my application running with a base url which looks like thishttpsomeservermydepartmentmyappmy development environment is set up to use the default rails configuration which looks like thishttplocalhost30myappi would like to model this deployment path in my development environment that is i would like to develop with a base url which looks like thishttplocalhost30mydepartmentmyappthat way i can make all my urls relative to and they will work in both environmentshow can i change it so my application will live at this path in my development environmentsolutions i have found but do not work for mesetting the scope in routesrb does not seem to work for the static content in public using apache is rewriting capabilities i do not want to install apache on my development box ideally the solution would work with webrick though i seem to have mongrel mostly working as well there are some problems with mongrel and ruby 192setting relative url root and similar suggestions which do not work with rails 3dynamically generating cssjavascript and adjusting the paths to compensate between development and production environments,['ruby-on-rails'] +139275,android menu icon size i need to set the menu icon programmatically not through a layout file and also i need to load the icon file from fileandroid asset not load as a compiled drawable i found the size of the thisplayed icon is relatively smaller it looks like android resize it or something and i do not want to achieve the same effect with out codeas you can see in the in the attached screen shot the menu globe36 globe48 and globe72 is populated using code like and their image are 36x36 48x48 and 72x72 this is the way i load my icon in my app i have to menuitem mi menuaddmenunone i i icon drawable d drawablecreatefromstreamgetassetsopenicon png icon miseticondand the menu globeaset and barcodeasset are populated like menuitem mi menuaddmenunone i i globeasset miseticonrdrawableglobe,['android'] +139284,c error undefined reference to function but it is defined just a simple program but i keep getting this compiler error i am using mingw for the compilerheres the header file pointhtype for a cartesian pointtypedef struct double x double y pointpoint createdouble x double ypoint midpointpoint p point qand heres pointcthis is the implementation of the point typeinclude pointhint main return 0point createdouble x double y point p px x py y return ppoint midpointpoint p point q point mid midx px qx 2 midy py qy 2 return midand heres where the compiler issue comes in i keep gettingtestpointc undefined reference to createdouble x double ywhile it is defined in pointcthis is a separate file called testpointcinclude pointhinclude asserthinclude stdiohint main double x 1 double y 1 point p createx y assertpx 1 return 0i am at a loss as to what the issue could be,['c'] +139287,javascript recursion settimeout i have just started looking at javascript so hopefully this will be something simple i want to make a slideshow of images that plays automatically this is very simple and there are a few tutorials on it but for some reason i have not been able to get it to work this is what i havevar image1 new imagevar image2 new image var image3 new imageimage1src imageswebsite6jpgimage2src imageswebsite7jpgimage3src imagessunsetjpgvar images new array imageswebsite6jpg imageswebsite7jpg imagessunsetjpgsettimeoutdelayimages020function delayarrnum documentslidesrc arrnum 3 var number num 1 settimeoutdelayarrnumber10the image i am trying to change has id slide and i also have some evidence that it works what happens is the first image loads then the second image loads which means the original settimeout call must be working then nothing happens which to me suggests it is the recursion that is not workingi am very familiar with recursion in other languages so i think it must just be a syntax thing or something but i cannot seem to figure it out thanks for any help,['javascript'] +139288,suggestions for how to communicate from js running in a uiwebview to the hosting objc app i plan to have a shell iphone app with a uiwebview with the bulk of my application running through javascript in the uiwebviewnow i know it is easy to communicate from the objc environment to the javascript environment by using stringbyevaluatingjavascriptfromstring however is there a good recommended way of communicating from the javascript environment to the objc worldthanks,"['javascript', 'iphone', 'objective-c']" +139294,which stl c container to use for a fixed size list i am having a consuming application which needs to store a maximum of 100 objects in a list to feed to a callback for processing since it will be redundant to keep old data if the consumer does not catch up as new data is arrived it can simply overwrite the oldest elementi was thinking of using circular buffer container and guessed that it would be deque but found that it does not use circular list as well as does not have option to set fixed maximum size there is a max size method in dequeue but documentation says this is the maximum potential size the container can reach due to system or library implementation limitationsis there some other container i can useps i am using visual c 2010 express,['c++'] +139295,how do i handle python unicode strings with nullbytes the right way questionit seems that pywin32 is comfortable with giving nullterminated unicode strings as return values i would like to deal with these strings the right waylet us say i am getting a string like ucusersguestmyfileasyx00x00sy this appears to be a cstyle nullterminated string hanging out in a python unicode object i want to trim this bad boy down to a regular ol string of characters that i could for example thisplay in a window title baris trimming the string off at the first null byte the right way to deal with iti did not expect to get a return value like this so i wonder if i am missing something important about how python win32 and unicode play together or if this is just a pywin32 bugbackgroundi am using the win32 file chooser function getopenfilenamew from the pywin32 package according to the documentation this function returns a tuple containing the full filename path as a python unicode objectwhen i open the dialog with an existing path and filename set i get a strange return value for example i had the default set to cusersguestmyfileisreallyreallyreallyawesomeasyin the dialog i changed the name to myfileasy and clicked savethe full path part of the return value was ucusersguestmyfileasyx00wesomeasyi expected it to be ucusersguestmyfileasythe function is returning a recycled buffer without trimming off the terminating bytes needless to say the rest of my code was not set up for handling a cstyle nullterminated stringdemo codethe following code demonstrates nullterminated string in return value from getsavefilenamewdirections in the dialog change the filename to myfileasy then click save observe what is printed to the console the output i get is ucusersguestmyfileasyx00wesomeasyimport win32gui win32conif name main initial dir cusersguest initial file myfileisreallyreallyreallyawesomeasy filter string all files00 filename customfilter flags win32guigetsavefilenamewinitialdirinitial dir flagswin32conofn explorer fileinitial file defexttxt titlesave as filterfilter string filterindex0 print reprfilenamenote if you do not shorten the filename enough for example if you try myfileisreallyasy the string will be complete without a null byteenvironmentwindows 7 professional 64bit no service pack python 271 pywin32 build 216update pywin32 tracker artifactbased on the comments and answers i have received so far this is likely a pywin32 bug so i filed a tracker artifactupdate 2 fixedmark hammond reported in the tracker artifact that this is indeed a bug a fix was checked in to rev f3fdaae5e93d so hopefully that will make the next releasei think aleksi torhamos answer below is the best solution for versions of pywin32 before the fix,['python'] +139300,whats the best way to do integration testing for a javascript heavy ui in a rails app we have a web application that makes extensive use of ajaxy javascript in the ui we have nearly complete code coverage of our backend using shoulda and webrat and would like to extend our test suite to include full integration testing through the javascript uiwe tried selenium but found it brittle and temperamental are there more reliable optionsupdatefor those still checking this out we ended up using xvfb so we can run firefox without a screen allows us to run the test on a headless jenkins ci server we still have to run tests live locally occasionally to debug but it works pretty well,"['javascript', 'ruby-on-rails']" +139331,are variables used in php functions automatically unset after function execution i have a question regarding the variablesarrays used in php functions after executing the function are all the variables automatically unset if not when do they unset exactly after executing the whole php page after a certain timeis it useful to unset all variables used in a function at the end of the function to release from memorythank you in advance for your help and comments,['php'] +139355,how to scrape https javascript web pages i am trying to monitor daytoday prices from an online cataloguethe site uses https and generates the catalogue pages with javascript how can i interface with the site and make it generate the pages i needi have done this with other sites where the html can easily be accessed i have no problem parseing the html once generatedi only know python and javathanks in advance,"['java', 'javascript', 'python']" +139365,how to identify end of inputstream in java i am trying to read bytes from server using socket program ie i am using inputstream to read the bytes if i pass the length size i am able to read the bytes but i am not sure what may be the length so i am not able initialize the byte arrayalso i tried while inread 1 i observered it loop works fine when the data is sent but the next line after the loop is not executable i feel its still looking for the data in the stream but there is no ata if i close the server connection then my client will execute the next line followed to the loopi am not sure where i am going wrongthisin socketgetinputstreamint dataint thisinread whiledataint 1 systemoutprintidataint i dataint thisinread systemoutprintend of loopi get the output as10262396413151426171338291610481156121130141415128160170180194820021022023024025126027028382911430233120327034203513613748385139494052414942554349445245524654475548504951505251485253535654515548564857575857595760576157625763576456but no output for end of loopplease guide how shall i close the looplooking forward for you response thanking you all in advance,['java'] +139372,calculate duration i have a small android problem i have a requirement to have a timer to calculate the duration from the time a specific activity was open till a certain button in that activity is clicked simply how long the activity was open while googling around i found timertask but this seems to run a thread for a certain interval only though and doesent seem ideal for the job from my little android experienceany idea on how to calculate the duration preferably in a very simple mannerany help is very welcomeregardsmilindad,"['java', 'android']" +139375,how to access the running threadrunnable i have a thread running but from outside i cannot bypass a value to stop that thread how can i send falsetrue value inside mytest or call running thread public methods when i press the button1 ex threadinterrupt runnablestop or runnablestart mainpublic class main extends jframe public static runnable runnable public static thread thread private jbutton b1 new jbuttonstartstop public void init execute a job on the eventthispatching thread try javaxswingswingutilitiesinvokeandwaitnew runnable public void run creategui catch exception e systemerrprintlncreategui did not successfully complete public void creategui container cp getcontentpane b1addactionlistenernew button1 cpaddb1 runnable new mytest thread new threadrunnable threadstart button 1 problem to go inside a running threadpublic class button1 implements actionlistener public void actionperformedactionevent e systemoutprintlnbutton pressed need to access threadinterrupt runnablestop or runnablestart running threadpublic class mytest implements runnable public static boolean onoff false public static boolean status false public void run whiletrue if onoff return else if statusfalse systemoutprintlnrunning public static void stop status true onofftrue public static void start status false onoff false follow up proof readstep 1 main bootstartup public class main extends jframe public static mytest runnable wrong public static runnable runnable public static thread thread private jbutton b1 new jbuttonstart private jbutton b2 new jbuttonstop public void init execute a job on the eventthispatching thread in case freezed for heavy lifting try javaxswingswingutilitiesinvokeandwaitnew runnable public void run creategui catch exception e systemerrprintlncreategui did not successfully complete public void creategui container cp getcontentpane b1addactionlistenernew button1 cpaddb1 runnable new mytest thread new threadrunnable try threadsleep100 value is milliseconds threadstart catch interruptedexception e public static void mainstring args runnew main 500 500 public static void runjframe frame int width int height framesetvisibletrue to start public class button1 implements actionlistener public void actionperformedactionevent e runnablestart to stop public class button2 implements actionlistener public void actionperformedactionevent e runnablestop step 2 thread deals public class mytest implements runnable private static volatile boolean running true public void run whilerunning do stuff public void start running true public void stop running false,['java'] +139380,first letter in uitextfield lowercase how do you make it so that when you start typing on the keyboard after youve clicked on a uitextfield the first letter is not a capital automatically,"['iphone', 'objective-c']" +139383,implicit type conversion rules in c operators i want to be better about knowing when i should cast what are the implicit type conversion rules in c when adding multiplying etc for exampleint float int float float int int float float int int int int float et ceterawill the expression always be evaluated as the more precise type do the rules differ for java please correct me if i have worded this question inaccurately,['c++'] +139387,axis label in flot does anyone know how one can set the label or title of an axis in floti have read the api but it does not seem to have that featurethanks,['javascript'] +139415,difference between and i always thought that operator in java is used for verifying whether both its boolean operands are true and the operator is used to do bitwise operations on two integer typesrecently i came to know that operator can also be used verify whether both its boolean operands are true the only difference is that it checks the rhs operand even if the lhs operand is falseis the operator in java internally overloaded or is there some other concept behind this,['java'] +139423,how should i indicate that my python shell script is returning an error iam writing a shell script in python usrbinenv python iam a bit new to shell scripting in general so apologies if iam misunderstanding somethingmy current understanding is that if my shell script works successfully i should call sysexit to indicate that itas succeeded ie return 0if iave encountered an error specifically that the user has passed in an argument that iam not expecting what should i return and howis it okay just to call sysexit with any nonzero value eg sysexit1,['python'] +139425,why does javas simpledateformat parse this hi i have got a simple date format set up with a custom format stringmmddyyand i give it the following value to parse4 1 01i do not think it should parse this because of the spaces but the simple date format is returning the dateapril 4th 01adany ideas why,['java'] +139449,why is this shell script calling itself as python script obviously this shell script is calling itself as a python script binsh repo default configurationrepo urlgitandroidgitkernelorgtoolsrepogitrepo revstablemagiccallingpythonfrombinshexec python e 0 magicif name main import sys if sysargv1 s magic del sysargv1del magicwhole script can anyone explainthe purpose of calling it this waywhy not having usrbinenv python in the first line so it gets interpretedas python script from the beginningthe purpose of adding that magic last command line argument that is removed afterwards in the beginning of the python code,"['android', 'python']" +139477,still need help understanding why ninject might be better than manual di this is an extension to the question why do i need an ioc container as opposed to straightforward di codei have been learning ninject and came up with the following example the example goes through the manual way of doing di and the ninject way of doing diclass program static void mainstring args ninjectway manualway consolereadkey private static void manualway consolewritelinemanualway iweapon sword new sword samurai samurai new samuraisword consolewritelinesamuraiattackmanualway change weapon iweapon dagger new dagger samuraiweapon dagger consolewritelinesamuraiattackmanualway iweapon weapon new shuriken iwarrior ninja new ninjaweapon consolewritelinemanual way inject shuriken when a ninja ninjaweaponname iwarrior ninja2 new ninjaweapon private static void ninjectway consolewritelineninjectway ikernel kernel new standardkernel kernelbindiweapontosword var samurai kernelgetsamurai consolewritelinesamuraiattackninjectway kernelrebindiweapontodagger samurai kernelgetsamurai consolewritelinesamuraiattackninjectway kernelbindiweapontoshurikenwheninjectedintoninja var ninja kernelgetninja ninjaoffhandweapon new shortsword consolewritelineconditional injectionninjaweaponname consolewritelineconditional injection offhandweapon ninjaoffhandweaponname var ninja2 kernelgetninja consolewritelineconditional injection ninja2weaponname consolewritelineconditional injection offhandweapon ninja2offhandweaponname consolewriteline i hear the benefits happen when the scale of the project increases but i am not seeing it help me understand this better provide more examples in cninject and help me understand where the benefits really become apparent,['c#'] +139491,how to monitor database transaction i have written a webapplication for payroll system which can do insertupdatedelete to mysql databasei want to know how many transaction happened in mysql database how many transaction happened in mysql database during start time and end time,"['java', 'mysql', 'sql']" +139494,can i reference two versions of a dll in the same project without putting them in the gac can i reference two versions of a dll in the same project without putting them in the gac thanks,"['c#', '.net']" +139504,jquery blackberry ajax problems i have an aspnet web application that i am making available to mobile devices im using jquery and jqmobile for the functionality and stylingthe application works great in safari google chrome on the iphone ipad and android devices but i cant get it working on anything other than the blackberry torch i have a requirement to get it working on version 5 and 6 blackberry devices but it seems the ajax request for logging in is always calling the error function and i cant see why the application contains a few pages but i cant even get past the login page on the blackberry has anyone else managed to get ajax calls working on the blackberry i dont really want to have a seperate set of pages just for blackberryshere is the code for the login page aspx page languagec autoeventwireuptrue codebehindloginaspxcs inheritssiconwebwapapagesmobilelogin doctype html public w3cdtd xhtml 10 transitionalen html xmlnshead idhead1 runatserver titletitle link hrefjavascriptsjquerymobilemincss relstylesheet typetextcss script srcjavascriptsjqueryminjs typetextjavascriptscript script srcjavascriptsjquerymobileminjs typetextjavascriptscriptheadbody form idlogin runatserver acceptcharsetutf8 div idinvoices datarolepage datathemeb div dataroleheader datathemeb h1 wap loginh1 div div datarolecontent datathemeb div aligncenter img srcsicon logohz rgb72png div ul datarolelistview datainsettrue li input typetext value nameusername placeholderusername idusername li li input typepassword value namepassword placeholderpassword idpassword li ul a classlogin datarolebutton datathemeblogina a datarolebutton datathemeacancela div div form script typetextjavascript var ajaxenabled true documentreadyfunction ajaxenabled supportajax get base url var baseurl resolveurl function to resolve a url function resolveurlurl if urlindexof 0 url baseurl urlsubstring2 return url login form login link click login aloginclickfunction e get the form var form thisclosestform perform login return apploginform login form submit loginsubmitfunction e get the form var form this perform login return apploginform class to handle login var app login function form var username usernameval var password passwordval call the approve method on the code behind ajax type post url resolveurlpagesmobileloginaspxloginuser data username username password password pass the parameter names and values contenttype applicationjson charsetutf8 datatype json async true error function jqxhr textstatus errorthrown alerterror status textstatus jqxhr status jqxhrstatus jqxhr response text jqxhrresponsetext success function msg if msgd true windowlocationhref resolveurlpagesmobileindexaspx else show error alertlogin failed return false scriptbodyhtmland finally the code behind for the login method summary logs in the user summary param nameusernamethe usernameparam param namepasswordthe passwordparam returnsreturnswebmethod scriptmethodpublic static bool loginuser string username string password try staticstorecurrentuser new user username password check the login details were correct if staticstorecurrentuserisauthentiacted change the status to logged in staticstorecurrentuserloginstatus objectsenumsloginstatusloggedin store the user id in the list of active users httpcontextcurrentapplication sessionkeysactiveusers as dictionarystring int httpcontextcurrentsessionsessionid staticstorecurrentuseruserid return true else return false catch exception ex return false,"['asp.net', 'jquery']" +139510,some questions about push notificatons i am working with my first app for iphone and last part is push notifications its my first iphone app and firs time i am dealing with push notifications in development phase everything is working fine now i have some questions for productions phase whats difference between development push ssl certificate andproduction push ssl certificate can i use the same certificatewhich i used in development phase or do i have to buy a newcertificatei made an app on urban for production push notifications and usedits credentials in my source code is it enough or do i have to makemore changes at urban airships app or in my source codei tried alot to find some kind of document or tutorial which showshow to change development push notifications app to production pushnotifications app but unfortunately i could not find any can yousend me some tutorial or document which shows how to do that,['iphone'] +139518,is it bad using sessionid in queries when person logins he gets sessionid and it becomes his id taken from mysql table then i do mysql queries like select from members where member id sessionid so is it safe can sessionid thisappear or could hacker edit it somehowthank you,"['php', 'mysql']" +139531,linq the type of one of the expressions in the join clause is incorrect i have a complex linq to sql to query which joins onto two tables one is rather simple and works fine but one is fairly complex and i am getting the type of one of the expressions in the join clause is incorrect type inference failed in the call to groupjoinit is a rather long query and i do development on a work with internet access so i thought i would see if the line that seems to be the issue is enoughjoin consignments in dcconsignments firstordefaultx xtripdate datefrom xtripdate dateto xdeliverydepot depotletter xdeliverystatus 2 xdeliverystatus 3 on new reg svehiclereg depot svehicledepot equals new reg consignmentsvehiclereg depot consignmentsdeliverydepot into coni have ensured that the data types are the same but it still does not work any ideas,['c#'] +139535,changing versions of python in command line python 25 came installed on my mac i downloaded python 32 and have it running in my ide when i open the terminal in mac and type in python it tells me i am working with 251 what do i enter in the command line to change from 25 to 32 2 once i get to 32 using your answer how do i get back to 25 if i want tothanks for your help,['python'] +139568,get result from an activity after finish in an android unit test i am currently writing some android unit tests and while i have gotten most things to work the way i want one thing has left me kind of stumped i have the following code in my activity under test intent result new intentresultputextratest testinputgettexttostringsetresultactivityresult ok resultfinishi am trying to figure out how to use instrumentation or whatever to be able to read the result of the activity or get at the intent after the activity is finished can anyone help,"['java', 'android']" +139586,resize event for textarea the current versions of firefox and chrome include a drag handler to resize a textarea box i need to capture the resizing event i thought it would be easy with jquerys resize event but it does not worki have also tried the normal onresize event but the result is the same you can try it on jsfiddleis there a way to capture it,"['javascript', 'jquery', 'html']" +139592,php version of css media queries cannot find anything on the web for this wanted to throw the question out thereis the a php version of css media queries,"['php', 'css']" +139642,c method overload problem with class derived from generic abstract class i am working on a project and i have a generic abstract type that takes a type parameter that is itself derived from the abstract type if you want to know why i would do this please see this questioni have run into an interesting problem with overloading a method in a derived class that is defined in the abstract class here is a code samplepublic abstract class abstractconvertert u where you abstractconvertible where t abstractconvertert u public abstract t convertu convertiblepublic class derivedconvertibleconverter abstractconverterderivedconvertibleconverter derivedconvertible public derivedconvertibleconverterderivedconvertible convertible convertconvertible public override derivedconvertibleconverter convertderivedconvertible convertible this will not be called systemconsolewritelinecalled the most derived method return this public derivedconvertibleconverter convertconvertible convertible systemconsolewritelinecalled the least derived method return this public abstract class abstractconvertible public class convertible abstractconvertible public class derivedconvertible convertible in the sample above the overload of convert that does not exist in the abstract parent and is less derived is called i would expect that the most derived version from the parent class would be calledin trying to troubleshoot this problem i ran into an interesting solutionpublic abstract class abstractconverteru where you abstractconvertible public abstract abstractconverteru convertu convertiblepublic class derivedconvertibleconverter abstractconverterderivedconvertible public derivedconvertibleconverterderivedconvertible convertible convertconvertible public override derivedconvertibleconverter convertderivedconvertible convertible systemconsolewritelinecalled the most derived method return this public derivedconvertibleconverter convertconvertible convertible systemconsolewritelinecalled the least derived method return this public abstract class abstractconvertible public class convertible abstractconvertible public class derivedconvertible convertible when the derived type argument is removed from the base class the most derived version of convert is called i would not expect this difference since i would not have expected the interface of the abstract version of convert to have changed however i must be wrong can anyone explain why this difference occurs thank you very much in advance,['c#'] +139648,difference between range and selection in browser i wanted to know the difference between the range and the selection object in javascript it appears to me that you could get the same functionality out of either of these two in which case are there are any specific circumstances where you know which of the two to use,"['javascript', 'html']" +139656,difference between passing array and array pointer into function in c what is the difference between the two functions in cvoid f1double a void f2double a if i were to call the functions on a substantially long array would these two functions behave differently would they take more space on the stack,['c'] +139662,jquery mobile themes where to get them repurpose jqtouch themes where can i find themes for jquery mobile jqm that go beyond the packaged five themes color variations of themeither cross device or device specific ones for example iphone apple styleandroid specificwhat is the effort to repurpose for example the jqtouch apple theme,['jquery'] +139684,how to parse a cookie string i would like to take a cookie string as it might be returned in a setcookie header and be able to easily modify parts of it specifically the expiration datei see there are several different cookie classes such as basicclientcookie available but i do not see any easy way to parse the string into one of those objectsi see in api level 9 they added httpcookie which has a parse method but i need something to work in previous versionsany ideasthanks,"['java', 'android']" +139697,how to detect if user open two tabs for same session i have done a booking application done using cakephp which involves a few steps before the checkout page in between these steps i store the information in the session how it works is that step 1 requires them to fill in their information when going to step 2 the information in step 1 will be saved into the session object as they proceed in the other steps the process repeats at the end when they checkout all the data is then saved to the databaseeverything works great if the user opens one instance of the application in the browser but once they have another page or another tab opened for the same application in the same browser problem happenslet us say they have two instance of the application open in tab a and tab b in tab a they entered the details in step 1 and proceed to step 2 then the user does the same thing in tab bat the last step when the user does a checkout information in tab a is the same as in tab bright now i can only think the best way is to prevent the user from opening the same application in two browser instance is there a way to detect and prompt the user to complete the booking form in tab a first when they try to open another instance in tab b,['php'] +139726,activerecord list columns in table from console i know that you can ask activerecord to list tables in console usingactiverecordbaseconnectiontablesis there a command that would list the columns in a given table,"['sql', 'ruby-on-rails']" +139747,in rails how to get current url but no paths if i am in a url such as how can i request just the url with no paths such as,"['ruby-on-rails', 'ruby']" +139761,why does swapping values with xor fail when using this compound form i found this code to swap two numbers without using a third variable using the xor operatorcode int i 25int j 36j i i jj iconsolewritelinei i j jnumbers swapped correctlyoutput i36 j25now i changed the above code to this equivalent codemy code int i 25int j 36j i j i i have changed to this equivalent consolewritelinei i j jnot swapped correctly output i36 j0now i want to know why does my code give incorrect output,['c#'] +139842,what use are ejbs i am currently learning jave having plenty of c experience and having learned java se i do not understand the purpose of enterprise java beans can someone clarify this for me i am not interested in legacy uses this is in the context of ejb31 and javaee 6it seems that some people use them to contain the business logic for implementing the business layer of the conventional 3layer architecture that separates the domain logic from the domain objects leading to an anemic domain model but that goes against all my ood instincts i agree with martin fowler that it is an antipattern should i relax my objections to an anemic domain model or do ejbs have other uses,['java'] +139855,jquery crossbrowser scroll to top with animation right now i am using thisgototopeachfunction thisclickfunction htmlanimate scrolltop 0 slow return true which does not work in chrome and in opera i get a small flicker the browser instantly scrolls to the top then back to the bottom and then it begins to scroll slowly back to top like it shouldis there a better way to do this,"['javascript', 'jquery']" +139877,in c how do i get the list of local computer names like what one gets viewing the network in windows explorer there are a lot of questions about getting the name and ip addresses of the local machine and several about getting ip addresses of other machines on the lan not all answered correctly this is differentin windows explorer if i select network on the side bar i get a view of local machines on my lan listed by machine name in a windows workgroup anyway how do i get that same information programatically in c,['c#'] +139884,android how to set a default value for an argument variable android functionphp examplefunction hahaa test print a the question is how to do it in androidpublic void somefunctionint t 5 somethingthe solution above does not work how can i do itthanks,['java'] +139912,django how to access original unmodified instance in post save signal i want to do a data denormalization for better performance and put a sum of votes my blog post receives inside post modelclass postmodelsmodel blog entry author modelsforeignkeyuser title modelscharfieldmax length255 text modelstextfield rating modelsintegerfielddefault0 here is the sum of votesclass votemodelsmodel vote for blog entry post modelsforeignkeypost voter modelsforeignkeyuser value modelsintegerfieldofcourse i need to keep postrating value actual nornally i would use database triggers for that but now i have decided to make a post save signal to reduce database process time vote was savedreceiverpost save sendervotedef update post votessender instance created kwargs update post rating if created instancepostrating instancevalue instancepostsave else if vote was updated we need to remove the old vote value and add the new one but howhow can i access the instance value before it was saved in database triggers i would have old and new predefines for this but is there something like this in post save signalsupdatethe solution based on marks the answer vote was savedreceiverpre save sendervotedef update post votes on savesender instance kwargs update post rating if vote is being updated then we must remove previous value first if instanceid old vote voteobjectsgetpkinstanceid instancepostrating old votevalue now adding the new vote instancepostrating instancevalue instancepostsave,['python'] +139916,android what does this warning message refer to webcore i have a gallery which contains webviews as its children when i scroll the gallery i am getting the following warning0407 193537409 warnwebcore664 cannot get the viewwidth after the first layout 0407 193537470 warnwebcore664 skip viewsizechanged as w is 0what does this warning refer to i have not hardcoded any of the layout paramsany light on why this warning occurs would be really helpfuland these were printed too 0415 1013202 debugwebviewglue617 nativedestroy view 0x257f400415 1013243 debugwebviewglue617 nativedestroy view 0x25d6800415 1013292 debugwebviewglue617 nativedestroy view 0x2406880415 10132 debugwebviewglue617 nativedestroy view 0x2499180415 1013373 debugwebviewglue617 nativedestroy view 0x2266080415 1013423 debugwebviewglue617 nativedestroy view 0x21e4180415 1013482 debugwebviewglue617 nativedestroy view 0x23a4e80415 1013533 debugwebviewglue617 nativedestroy view 0x235c680415 1013572 debugwebviewglue617 nativedestroy view 0x212a28thanks in advance,['android'] +139934,how do i archive multiple targets with one action in xcode 4 i have a project with multiple targets that are all for different ios apps for instance one traget for the lite version and another one for the pro versioni want to build and archive all of my apps at once currently i have a scheme for every target which i use to archive each app independently but now i have to start the archiving wait until it is done and then start the next one is there a way to archive all apps with one single action in xcode 4 or using the command line,"['objective-c', 'ios']" +139950,objective c convert a nsmutablestring in nsstring i have an nsmutablestring how can i convert it to an nsstring,['objective-c'] +139979,proper way to test if a value is numeric in c i just need to know if the value is numeric i do not need to do anything with the value is this the best way feel dirty creating a variable that i would not ever use beyond thisint valifinttryparsetxtfootext out val,"['c#', '.net']" +139982,ordered list showing all zeros in ie9 i have an ol ordered list and in ff safari chrome it is rendered correctly however in ie9 it is showing all zeros it is not a spacingpadding issue because i am able to see the zeros my html is as followsol lienter basic company informationli liselect from our portfolio of productsli liattach your employee censusli lireview your selections and submit your requestli olanyone run into that problem and hopefully a solution,['html'] +139985,what is salt and how do i use it i have been searching around and i am still unsure of what a salt is and how to useimplement it sorry for the noobish question i am self learning php,['php'] +140014,mpi type create subarray and mpi gather i have to solve a little mpi problem i have 4 slaves processes and each of these wants to send a 2d subarray chunk rows x chunk columns to master 0 master 0 collects all chunks in drowscolumns and print it i want to use mpi gatherinclude mpihinclude iostreamusing namespace stddefine rows 10define columns 10define chunk rows 5define chunk columns 5define tag 0int alloca matriceint righe int colonneint matricenullint imatrice int mallocrighe sizeofintifmatrice null matrice0 int mallocrighecolonnesizeofint ifmatrice0null fori1 irighe i matricei matrice0icolonne else freematrice matrice null else matrice nullreturn matriceint mainint argc char argvint my id numprocslengthijint ndims sizes2subsizes2starts2int debug chnullint dnullchar namebufsizmpi datatype subarraynullmpi status statusmpi initargc argv mpi comm rankmpi comm world my id mpi comm sizempi comm world numprocs ottiene quanti processi sono attivimpi get processor namename length ifmy id0 creo una sottomatrice ripulita dalle ghost cells ndims2 sizes0 chunk rows2 sizes1 chunk columns2 subsizes0 chunk rows subsizes1 chunk columns starts0 1 starts1 1 mpi type create subarrayndimssizessubsizesstartsmpi order cmpi intsubarray mpi type commitsubarray debug ch alloca matricechunk rows2chunk columns2 fori0 ichunk rows2 i forj0 jchunk columns2 j ifi0 ichunk rows1 j0 jchunk columns1 debug chij 5 else debug chij 1 mpi senddebug ch01subarray0tagmpi comm worldifmy id0 d alloca matricerowscolumnsmpi gatherdebug ch01subarrayd0chunk rowschunk columnsmpi int0mpi comm worldifmy id fori0 irows i forj0 jcolumns j printfd dij printfn ifmy id mpi type freesubarraympi finalize chiusura di mpireturn 0thanks all,['c'] +140015,keep the leftmost column of a treeview visible while scrolling horizontally i implemented a treeview with columns in wpf using controltemplate and a stackpanel of gridviewrowpresenter i followed this article avalon teamarchive20060301541206aspx it works perfectlyhowever i would like to keep the left column with the names visible while scrolling horizontallyit would be like freeze panes on microsoft excel on the first columnan idea anyonethanksfrederic,['c#'] +140017,running generated nose tests suppose i define a testfilepy python module with as followsdef test evens for i in range0 5 yield check even i i3def check evenn nn assert and 2 0 or nn 2 0when i let nose identify the tests in collectonly mode i gettestfiletest evens0 0 oktestfiletest evens1 3 oktestfiletest evens2 6 oktestfiletest evens3 9 oktestfiletest evens4 12 oki can run all tests using nosetests v testfiletest evenshowever what if i only want to run testfiletest evens2 6 ie not all the tests is there any way to do this from the command line,['python'] +140028,how to draw on a window in wpf best practice i am trying to write a small interactive gamelike application where i need to have a draw method that is gonna draw on screen but cannot figure out how to structure the method for wpfif this was winforms i could usepublic void draw graphics gbut for a wpf window what should i have on it in the xaml currently only have a grid and what should this draw method receive as an argumentfirst i want to do it like this to get it working then i can think about how to make it more wpf etc but now i am more interested in getting this to work,"['c#', '.net']" +140059,would you recommend javascript for gnome desktop apps with the arrival of the new gnome developer center i stumbled across javascript bindings for the gobject libraries now i would love to read a comment from an expert if he or she would recommend consider using those for a desktop application that involves consideration of aspects likeapi simplicity and usabilitydeveloper documentationstabilityscalabilitygjs or seedat once are those apis ready for usage or would it be better to wait a little until it is more established can you develop a whole application in js or would you restrict usage to scripting purposes,['javascript'] +140083,function signature differences in c11 considering c11s lambdas with the following codetemplate typename mvoid callvoid fm m m fmint main callintint n 42 ok int r callintint n r n 42 kois there a signature difference between the lambdas that makes the second one incompatible with the argument of calli use g 461side question why cannot the parameter be inferred if i write callint n 42,['c++'] +140118,does web2py have these i am finishing up a project in php with yii and phing even though yii is the best web framework i have used to date i prefer writing python over php so i have been looking at web2py and have some questionsdoes web2py provide javascript form validation yii has does web2py have a mongo db plugin something comparable to can you write console applications using web2pydoes web2py auto generate sql from model classes or can you generate model classes from a sql schema i prefer the latterwhat deployment tools are available for python web apps is there anything like phing yes i am aware i could use ant maven or even phing but i would rather use something implemented in python,['python'] +140132,crossplatform way to ask for the users documents folder i am writing a crossplatform program in java and want to stick the configuration files in the users documents folder my documents under windows documents under appropriate linux and whatever the folders called under mac os but i am not sure how to ask java for thati would like to stay away from hardcoding things do x if were on windows y if were on linux or z if were on os x as this puts the burden of support on my shoulders rather than the oracle development teami have checked the system properties list but it does not seem to include the users documents folder,['java'] +140136,difference between int p and int p declaration can you please tell the difference between int p and int p declarationthanks,['c'] +140137,what is the standard method for generating a nonce in python can someone share the best practices for creating a nonce for an oauth request in python,['python'] +140138,how to convert a datetime string to a current culture datetime string i have string say 1212011 in english us culture my current machine culture is english uk which is ddmmy format how to convert the 1212011 to 1122011 i have tried the below formatsystemdatetimeparseresultsystemthreadingthreadcurrentthreadcurrentculture tostringsystemthreadingthreadcurrentthreadcurrentculturedatetimeformatshortdatepatternbut i could not able to see any outputlokesh,['c#'] +140142,pause vimeo universal embed when hidden using jquery i have a vimeo video via universal embed iframe hidden on my page clicking a link fades it in and clicking outside of the video lightboxstyle fades it out and hides it but the video keeps playing i read on vimeos api that you can use json objects to pause the video but i do not understand what they are sayinghtmlimg idshow tide classvid srciiframe idtide classvim srcampcolorfapi1 width726 height409 frameborder0iframejavascriptunderlayclickfunction pause visible there are multiple vimeo video via api vim underlayfadeout400,['jquery'] +140155,c how to get the length of string in string i have a collection of string in c my code looks like thisstring lines systemiofilereadalinesdsamplefiletxtwhat i want to do is to find the max length of string in that collection and store it in variable currently i code this manually likeint nmaxlengthofstring 0for int i 0 i lineslengthi if linesilengthnmaxlengthofstring nmaxlengthofstring linesilength the code above does the work for me but i am looking for some built in function in order to maintain efficiency because there will thousand of line in myfile,['c#'] +140172,browser downloads php file from apache web server i have an apache web server let us say this servers domain is examplecomwhen i access examplecom then the indexphp file is correctly thisplayed in the browserhowever when i access eg examplecomuser then the indexphp file of homeuserpublic htmlindexphp file is downloaded rather than thisplayedhow do i fix this problem i changed expose php off in phpini but nothing has changed,['php'] +140182,php search array using wildcard i m trying to search an array which contains patterns likemike 45peter 23jim 12and wants to search the particular pattern someway likearray searchmikearraycan somebody pls suggest me a useful way to do thisthanks in advance,['php'] +140188,how to show html in xaml in c i have got a html string and i just want to show how it looks likehow can i show this string so that it looks like an html page,"['c#', 'html']" +140206,backbonejs raphaeljs backbone view raphael object and now for something complete different how can i delegate events in a backbone view when the dom object is a raphael object does that work at all like this var nodeview backboneviewextend events click click click function alertclicked render function canvasrectthismodelgetxpos thismodelgetypos 50 50attr fill e stroke none cursor move return this i need to update the model when the raphael object changed position when i attach the event direcly to the raphael object i only have access to that and not the whole view and thus not to the model,['javascript'] +140209,why do i get a formatexception when converting a string to a float when i try to convert a string to floatconsolewritelinefloatparse659it throws an exceptionunhandled exception systemformatexception input string was not in a correct f ormat at systemnumberparsesinglestring value numberstyles options numberformat info numfmtwhen i try it like thisconsolewritelineconverttosingle659it throws the same exceptionunhandled exception systemformatexception input string was not in a correct f ormat at systemnumberparsesinglestring value numberstyles options numberformat info numfmt at systemconverttosinglestring valuecan you explain why this happens,['c#'] +140235,pixelgif why do people use it just a simple question why is pixelgif usefull and why should you use it or why not,['html'] +140254,viewdidunload is not getting called at all my problem is like thisparent class loads a child viewchild removes itself during an action by using removefromsuperviewparent class gets a delegate call when the child gets removed and hence makes the child object nilstill the child clas viewdidunload is not called,['iphone'] +140269,is there a dictionary implementation in javascript how can i implement an array with an indexer in javascript is there something like a dictionary in net,"['javascript', '.net']" +140271,is there a trick to prevent gmails quoted text from hiding my email footer i send emails to my users which have the same subject but contain different content aside from the header and footer the header contains a logo a part x of n message and an hr and is never hidden the footer contains an hr the same part x of n text and some functional links next pause tweet that i do not want hiddeni tried enclosing these in a div idtimestamp i also tried adding tstimestamp to the links the links are images so then i created a symbolic link called image2png pointing to image1png and alternated these images none of these workedis there a simple solution that i have not thought of yethere is some htmlnames are really separated by rather than just a commappthis function does not do any checking for problems we assumein this case that the input is always correctpdivdivdivpall that remains now is putting the pieces togetherdivdivdivdivspanhrpart 19 of about 74bra hrefimg border0 src altget next textanbspnbspa hreflistid252itemid2100img border0 src altpause this textanbspnbspa hrefimg border0 src alttweet thisabroriginal page a hrefhereabrand heres a screenshot,['html'] +140292,leverage browser caching according to i should be using browser caching however i do not know howdo i simply add certain tags into the html section or is thing something i need to send via to server to the client something to do with php headers,"['php', 'html']" +140324,fragment transaction custom animation android i am trying to do ftsetcustomanimationsandroidranimatorfade in androidranimatorfade outbut i am getting an exception with unknown animation name objectanimator see details below0408 104541637 errorandroidruntime12 fatal exception main0408 104541637 errorandroidruntime12 javalangruntimeexception unknown animation name objectanimator0408 104541637 errorandroidruntime12 at androidviewanimationanimationutilscreateanimationfromxmlanimationutilsjava1240408 104541637 errorandroidruntime12 at androidviewanimationanimationutilscreateanimationfromxmlanimationutilsjava910408 104541637 errorandroidruntime12 at androidviewanimationanimationutilsloadanimationanimationutilsjava72why is there an error i am not sure how to solve it please help thanksfyi my min sdk is 7 but i am build for sdk 11 with compatibility library,['android'] +140329,detecting arrow key presses in javascript how do i detect when one of the arrow keys are pressed i used this to find outfunction checkkeye var event windowevent windowevent e consolelogeventkeycodethough it worked for every other key it did not for arrow keys maybe because the browser is supposed to scroll on these keys by default,['javascript'] +140351,how to tag a git repo from xcode 4 it might be silly but i just cannot figure it outi added git support for my project after creating it by closing xcode and from terminal git init git commit a m initial commitwhen i reopen xcode it detects my local repository just fine except for the fact that i just cannot get how to create a tag i can create a branch but not a tag how do you create one from xcodeedit did what edc1591 suggested and even created a project with git support from scratch and i still do not see how to create a tag there is only a branch subfolder and the possibility to add one branch but nothing about tags,"['iphone', 'objective-c']" +140355,thisplaynone thisplays none in browser this jsfiddle example works in google chrome but in internet explorer then when the close icon is clicked the browser removes the popup element but results in the text none being thisplayed in the browser window please explain how i can resolve this issuehtmldiv idpopup close popup link a hrefjavascriptdocumentgetelementbyidpopupstylethisplaynonexadiv,"['javascript', 'html', 'css']" +140362,regular expression group capture with multiple matches quick regular expression questioni am trying to capture multiple instances of a capture group in python do not think it is python specific but the subsequent captures seems to overwrite the previous in this oversimplified example i am essentially trying to split a stringx abcdefr recompilew6m rmatchxmgroups f i want to get a b c d e f but because regex overwrites subsequent captures i get fis this how regex is supposed to behave is there a way to do what i want without having to repeat the syntax six timesthanks in advanceandrew,['python'] +140366,forcing numeric values as text on html table exporting to excel i am trying to fix a bug at work where in classic asp a html table is being rendered and then sent to the client as an excel file i will spare the entire source code sample but essentially we have one column that is alpha numeric yet when the value starts with one or more zeros the zeros thisappear i know this is standard excel behavior for handling numbers but i want it to treat the value as text how can i do thisthe cell in questionresponsewritetd classtdsmall alignleft nowrap rspodetailitm id tdexampleshtml excel 00212704 212704 00212336 212336 00212251 212251,"['asp.net', 'html']" +140367,php parse current url i need to parse the current url so that in either of these casesi can get the return value of abc or whatever text is in that position how can i do that,['php'] +140387,saving properties in a file with java formatted is there a way to save properties in java with some formatting using the properties object like is there a way to introduce new lines between entries or comments before each keyi know this can be easilly done with normal io but wondered if there is a way of doing it with the properties object,['java'] +140388,use of null statement in c what are typical uses of null statement in c i know that it is basically used to skip expression where it is expected by the compiler but here i am interested only in realworld examples of such use casesthanks,['c'] +140431,what to use delegate event or func i want to provide objects within a class library the ability to aoutputa messages without worrying about how it is being output the class library could be used in a console app a winform or wpf windows application or a web page iad originally decided that i would use a delegate to handle this i implemented this using classes but the compiler did not like the delegate when i attempted to put the delegate into an interface that each of these objects inherent fromi found that i could move the delegate out of the interface and then was able to compile but i am not sure that this accomplishes what i am trying to do it also seems like a kludge so i wanted to ask if any of you have different ideas to accomplish thisathe interfacenamespace test using system using systemxmllinq public interface iaction thisplaymessagedelegate thisplaymessagestring message void execute xelement serializexname elementname public delegate void thisplaymessagedelegatestring messagefrom there i am not sure how to implement this behavior btw i know that this code will not compilepublic class actionclass1 iaction other methods not shown void execute if thisthisplaymessage null thisthisplaymessageahelloa public class consoleclass actionclass1 class1 new actionclass1 class1thisplaymessage x consolewritelinex public class winformclass actionclass1 class1 new actionclass1 class1thisplaymessage x thisplaytextboxtext x,['c#'] +140457,rails 3 shallow routes in rails 2x i used shallow routes but this seems to be missing from rails 3 at least in the api when i pass this option in rails 3 it does not throw any errors but i am also not getting all of the routes i expectedrails 3 routesrb resources users shallowtrue do resources recipe do resources categories do resources sections do resources details do end end end end endthe routes missing that were generated with the rails 2x equivalent are just a sample for the recipe resourceget new recipe i only have new user recipe andpost recipe to create a new recipe i only have post user recipeit kind of makes sense that these routes wouldnt be generated but my old code worked around it by passing the user id in each form less elegant agreedquestion is is there documentation for shallow routes in rails 3 is there a way to generate the routes i am missing from rails 2xthanks mike,['ruby-on-rails'] +140465,how to build qt for visual studio 2010 i struggled finding a howto which provides a stable solution for using qt with visual studio 2010 so after collecting all the bits of information and some trial and error i would like to write my solution into a guidethe problem or why is it not possible to use prebuilt binariesit seems that using binaries built for visual studio 2008 might work in some special cases but i found them not to work in my case they compiled ok but they produce runtime errors like thisor when started from visual studio 2010update i found a blog post analysing why does it work for some people while it does not for others in one word it depends on whether you have visual studio 2008 installed on the same machine or notthe most important thing that i stupidly didnat realize was the fact that you cannot use the visual studio 2008 compiled libraries and dllas available on the qt webpage if you donat have visual studio 2008 installed the reason is because the qt sdk you download is a debug build which is dependant on the vc90 debugcrt meaning it needs the visual c 2008 debug runtime installed which is not available as a rethistributable installer the only way to install the debugcrt is to install the entirety of visual studio 2008,['c++'] +140468,how can i use member initialization list to initialize an array class a public aprivate char a5 int ptraa a0 ptr0 is this right,['c++'] +140475,cannot drag folder from one project to another in xcode4 i am trying to use facebook connect and you sare supposed to be able to drag and drop folders but it does not work in xcode 4 any ideas,['iphone'] +140526,define enums within a method in c i have mainly a c background and i am learning c so i need some help with c idioms and stylei am trying to write in c a small textfile parsing method in which i need a simple state variable with three states in c i would declare an enum like this for the state variableenum stheader stbody stfooter state stbodyand then use it in my parsing loop like thisif state stheader input endheader state stbodyin c i realize that it is not possible to declare an enum inside a method so what i am supposed to do for sake of clean style declare this internal enum outside of the method use magic numbers 123 create a separate class for thisplease help me clear up my confusion,['c#'] +140539,xml parsing read a simple xml file and retrieve values i have written a task scheduling program for learning purposes currently i am saving the scheduled tasks just as plain text and then parsing it using regex this looks messy code wise and is not very coherent i would like to load the scheduled tasks from an xml file instead i have searched quite a bit to find some solutions but i could not get it to work how i wanted i wrote an xml file structured like this to store my data intasks task nameshutdownname locationcwindowssystem32shutdownexelocation argumentss f t 30arguments runwhen time80 amtime date18032011date days mondayfalsemonday tuesdayfalsetuesday wednesdayfalsewednesday thursdayfalsethursday fridayfalsefriday saturdayfalsesaturday sundayfalsesunday everydaytrueeveryday runoncefalserunonce days runwhen enabledtrueenabled tasktasksthe way i would like to parse the data is like soopen tasksxml load the first task tagin that task retrieve the values of the name location and arguments tagsthen open the runwhen tag and retrieve the values of the time and date tagsafter that open the days tag and retrieve the value of each individual tag withinretrieve the value of enabledload the next task and repeat steps 3 7 until all the task tags in tasks have been parsedi am very sure you can do it this way i just cannot work it out as there are so many different ways to do things in xml i got a bit overwhelmed but what i have go so far is that i would most likely be using xpathdocument and xpathnodeiterator rightif someone can show me an example or explain to me how this would be done i would be very happy,"['c#', '.net']" +140540,how do i create some variable type alias in java let say i have this codemapstring string list new hashmapstring stringlistputnumber1 onelistputnumber2 twohow can i make some alias the typemapstring stringto something that easier to be rewritten like may be something like thisthenewtype hashmapstring stringthenewtype list new thenewtypelistputnumber1 onelistputnumber2 twobasically my question is how to create alias to some type so i can make it easier to write and easier when need to change the whole program codethanks and sorry if this is silly question i am kinda new in java,['java'] +140547,calling barcode scanner on a button click in android application i have downloaded the zxing 16 and was able to successfully run a standalone barcode scanner through it now this scanner is in another project and the captureactivity and i have my apps different project called myproj all i want to do is on click of button in my project call captureactivity in another project how do i import that entire project in my project or what do i do it get this workingthanking in advance,['android'] +140558,using annotations for trace logging i have been working with a codebase of a company that has a policy of writing lots of trace logging so pretty much every method has a piece of code that starts like thisstring log method nameofmethodstringlistlongvoidifloggeristraceenabled object params new object string list loggertracecompanymessagesnewmethodinstancemessagethis log method params and end like this either in a finallyclause or just at the end of the methodifloggeristraceenabled loggertracecompanymessagesleavemethodinstancemessagethis log method there is actually more code to it but this is the basic ideathis is cluttering the code and other coders are constantly messing it up with their own interpretations which do not use the specific companymessagesclass which is needed to format the messages to be read by the monitoring tools so i am looking for a way to get rid of all code above and just provide all methods which need tracelogging with annotations like logbeforeloglevel logafterloglevel the reason i choose this solution is to make it so other developers do not have to learn anything new but to use annotations instead of code i am working in a server environment in which we deploy hundreds of web applications and dozens of developers so i have been looking for a way to implement this in a web application without a lot of extra coding or additional large libraries this means i am looking for a small stable aop implementation using annotations similar to those i proposed easy to configure in each web application performance is also important what is the simplest example to implement this with aop edit i did find something very similar to what i am looking for but this has a couple of problems all classes that need logging must be configured which would be more resource intensive than just using annotations would the spring configuration aopaspectjautoproxy fix that,['java'] +140564,what is the fastest way to learn javascript what is the fastest way to learn javascript for someone eloquent with classbased oop typed functional programming scala java and having some knowledge of metaprogramming python ruby clojure,['javascript'] +140575,how to remove preferencecategory programmatically i need to remove a preferencecategory programmatically i could remove the individual preferences with the following code but i need to remove thisable whole preferencecategory as wellpreferencescreen preferencescreen getpreferencescreenedittextpreference etp edittextpreference preferencescreenfindpreferencepref22preferencegroup findpreferenceprefcatremovepreferenceetpedit heres the working code for a preferencecategory prefcat and a child preference pref22preferencescreen preferencescreen getpreferencescreenedittextpreference etp edittextpreference preferencescreenfindpreferencepref22preferencegroup preferencegroup preferencegroup findpreferenceprefcatif preferencegroup null preferencegroupremovepreferenceetp preferencescreenremovepreferencepreferencegroup,['android'] +140577,why it is so difficult to learn ruby i have learn ruby almost two weeks i am working on java for two years two years ago i do not know whats java and what java can do but now i can use java in my workthough i am not a java experter yetbut when i try to use rubyi found it is so difficultafter two weaksi still can not write a ruby codethe following problem confusing me mostthe ruby syntaxit is too flexiblei can not find any rule when i try to write the ruby code for example the iterator in ruby and too flexible means too many choicesbut sometime too many choices is not a good ideain factmaybe it is my own problemi do not like javascirpts syntaxalso the perlpython i just think the syntax of java is the best for reading and understandingso many people say ruby is simple and fastbut what do you mean simplein my opinion it is difficult to learn than javaeverything in java is subject to the rulesso it is easy to startthough hard to be a experteri post here just want to know if some of you guys have the same problem with me any suggestion to make me feel comfortable when use ruby,['ruby'] +140583,improving wpf performance by breaking up the ui into regions is this possible i have run a very simple performance test on a wpf client apublic partial class mainwindow window private observablecollectionint data new observablecollectionint public observablecollectionint dataobj get return data private void button1 clickobject sender routedeventargs e for int j 0 j 5 j thread t new thread for int i 0 i 100 i threadsleep5 thispatcherinvokenew action dataadd1 updates the count thispatcherinvokenew action richtextbox1appendtext1 updates the string data tstart i then have two controls in the ui a textblock and a richtextbox the textblock is bound to the count property of the datasource whilst the richtextbox appends each new data value to its text string ie thisplays the content of the data if i thisable the richtextbox binding the textblock updates very quickly cycling through the count however enabling the richtextbox binding slows everything down both controls update in globs maybe once or twice per second in otherwords the entire ui runs at the pace of the richtextbox bindingis there a way to break this performance dependency i understand the richtextbox may well be slow but why does it have to slow down the otherwise lightening fast textblock,['c#'] +140593,how do i launch multiple rakes in parallel from a ruby script i have a ruby script from which i want to launch 4 rake tasks to run in parallel how do i do this i think i will need to fork and detach a process but i need the exact syntax,['ruby'] +140607,deletion of pointer to incomplete type and smart pointers when trying to use an auto ptr with a type that was declared with forwarddeclaration like thisclass astdauto ptra athe destructor of a is not called apparently because auto ptr internally deletes the underlying pointer and the destructor for an incomplete type cannot be called however the same code works fine and the destructor is called when using stdshared ptr instead of stdauto ptrhow can that be explained,['c++'] +140637,exclusive serial port access on osx i am working on an open source program that uses gnuio rxtx to talk to a microcontroller over a usb serial port the app runs on windows linux and osx it relies on gnuio for portable serial port access one macbook user has posted a log showing evidence of two thingswhile the application has the serial port open something causes rts to pulse resetting the microcontrollerwhile the application has the serial port open something changes the baudrate temporarily causing garbage to appear on the input normally this microcontrollerfirmwareusb combination is not susceptible to line noise style garbage characteristic of bad baud ratesthis happens periodically while the application sits idle reactinglogging when spontaneous messages arrive after the rts induced reseti suspect that some other program is opening the same serial port occasionally eg searching for a connected device how do i prevent that on osx,['java'] +140647,how to specify py2app icon how do i specify the icon file when using py2app just now i create the setup filepy2applet makesetup myapplicationpyand then build the application bundle python setuppy py2app awhere is it that i specify the icon file getting a little confused thanks for any help according to this link i should add it as an optioncurrently my setuppy file looks like thisthis is a setuppy script generated by py2appletusage python setuppy py2appfrom setuptools import setupapp hellopydata files chalkboardjpgoptions argv emulation trueiconfile usersgrahamethomsondocumentscollegehndoopgamepersonal developomentgiconicnssetup appapp data filesdata files optionspy2app options setup requirespy2app,['python'] +140666,android preventing double click on a button what is the best way to prevent double clicks on a button in android,['android'] +140667,mysql how to use coalesce say i have the following tabletable product product id language id name description 1 1 widget 1 really nice widget buy it now 1 2 lorem 1 how do i query this such that it tries to give me the name and description where language id 2 but fall back to language id 1 if the column contains a nullin the above example i should get lorem 1 for name and really nice widget buy it now for description,['mysql'] +140675,how to ensure a timestamp is always unique i am using timestamps to temporally order concurrent changes in my program and require that each timestamp of a change be unique however i have thiscovered that simply calling datetimenow is insufficient as it will often return the same value if called in quick successioni have some thoughts but nothing strikes me as the best solution to this is there a method i can write that will guarantee each successive call produces a unique datetimeshould i perhaps be using a different type for this maybe a long int datetime has the obvious advantage of being easily interpretable as a real time unlike say an incremental counterupdate heres what i ended up coding as a simple compromise solution that still allows me to use datetime as my temporal key while ensuring uniqueness each time the method is calledprivate static long lasttime records the 64bit tick value of the last timeprivate static object timelock new objectinternal static datetime getcurrenttime lock timelock prevent concurrent access to ensure uniqueness datetime result datetimeutcnow if resultticks lasttime result new datetime lasttime 1 lasttime resultticks return result because each tick value is only one 10millionth of a second this method only introduces noticeable clock skew when called on the order of 10 million times per second which by the way it is efficient enough to execute at meaning it is perfectly acceptable for my purposeshere is some test codedatetime start datetimeutcnowdatetime prev kernelgetcurrenttimedebugwriteline start time starttimeofday debugwriteline start value prevtimeofday for int i 0 i 10 i var now kernelgetcurrenttime debugassert now prev no failures here prev nowdatetime end datetimeutcnowdebugwriteline end time endtimeofday debugwriteline end value prevtimeofday debugwriteline skew prev end debugwriteline getcurrenttime test completed in end start and the resultsstart time 1544073405024start value 1544073405024end time 1544078355307end value 1544083417124skew 05061817getcurrenttime test completed in 04950283so in other words in half a second it generated 10 million unique timestamps and the final result was only pushed ahead by half a second in realworld applications the skew would be unnoticeable,"['c#', '.net']" +140693,show tables statement with multiple like values mysql show tables like cms tables in tianyan cms cms 1 row in set 0 secresultmysql show tables like cms or like roleerror 1064 420 you have an error in your sql syntax check the manualhow can i filter by multiple conditions,"['mysql', 'sql']" +140726,how to flat xml to one line in c code how to flat xml to one line in c code beforecatalogcd titleempire burlesquetitle artistbob dylanartist countryusacountry companycolumbiacompany price1090price year1985yearcdcatalogaftercatalogcdtitleempire burlesquetitleartistbob dylanartistcountryusacountry,"['c#', '.net']" +140749,related name argument not working as expected in django model i recently got a foreignkey clash in my django model i have the need to have two foreign keys owner assigned to ultimately pointing to the same model a userfrom what i understand i need a related name argument to solve that problem so i did thatassigned to modelsforeignkeytaskuser blanktrue nulltrue related nameuser assignmentandowner modelsforeignkeytaskuser related nameuser ownershipbut i am still getting an errortaskstask accessor for field owner clashes with related field taskuseruser ownership add a related name argument to the definition for ownertaskstask reverse query name for field owner clashes with related field taskuseruser ownership add a related name argument to the definition for ownerwhy am i still getting this errorthere is one catch owner is in a super class basewidget and assigned to is in a sub class task are there issues with using related name in an inheritance relationship do i need to just override the inheritance of owner and redefine related name in the sub class instead i would appreciate any help,['python'] +140772,web testing for ie how accurate is ietester i am using ietester for testing web sites with ie i find it quite frustrating that it crashes frequently more importantly it does not seem to be too reliable sometimes a site looks broken in ietesters ie8 but looks fine in real ie8 i suspect that html5shiv did not load correctly in ietester at times anyone experiencing the same problems what alternatives do you use i once resorted to using windows 7s xp mode to run ie7 then use windows 7s ie8 meaning that i did not upgrade to ie9 also i wont be able to test ie9 i think that setting up many virtual pcs for each browser will consume lots of resources say i have a virtual pc for each version of ie or is there another wayeven if i use those web services for browser testing i will be missing out of debugging tools like ie8s developer tools or ietesters debugbar i know they are nothing compared to firebug but its still something,['css'] +140784,remove elements from copyonwritearraylist i am getting an exception when i try to remove elements from copyonwritearraylist using an iteratori have noticed that it is documented elementchanging operations on iterators themselves remove set and add are not supported these methods throw unsupportedoperationexceptionfrom now surprisingly i can iterate it with foreach and use the remove function but then i get the famous bug when trying to remove an item from a list using a for loop you skip the element next to the removed elementany suggestions then,['java'] +140788,listview with choice mode multiple using checkedtext in a custom view there are plenty of questions of how to use checkedtextview but i cannot make it work correctlyi have a cursoradapter with a custom view which has a checkedtextview with androididandroididtext1 i have used androididtext1 because there are different questions that mention that if you use it you will get the choice mode multiple for freeif i do something like thisfinal long checkedids mlistviewgetcheckeditemidsfor int i 0 i mlistviewgetcheckeditemcount i logdtag id checked checkedidsii get all the checked ids without an issue but i cannot see any visual feedback in the listviewin other words the logic is fine but when i click the checkedtextview the green tick does not show upi was reading the listview src code and i could not find any reference to androididtext1 and makes me wonder if i should handle widgets checked state myselfcan anyone spot where androididtext1 is used to make the widget checked or not,['android'] +140789,interpolate sass in haml for backgroundimage object in rails i am trying to have a backgroundimage per list item to be dependent on which object it is linking to should not be too hard but i could not figure out how to do it in sass heres my attempt from haml because that is where i will be iterating through a collection of different facilitiesappviewsfacilitiesindexhtmlhamlfacility facilitieseach do facility ulfacilities li sass backgroundimage urlimage tag logosfacilityimagejpg link to facilityname facility pathfacilitybut the error i am getting looks like the following errorinvalid css after url expected was img altthebi arounnd line 6for one of the generated imagesit cannot be this difficultcan it any help is greatly appreciated,"['ruby-on-rails', 'ruby']" +140799,throwing an httpexception always sends back http 500 error i am trying to throw an http 403 error code back at the client i have read that httpexception is the cleanest way to accomplish this but it is not working for me i throw the exception from within a page like thisthrow new httpexception403you must be logged in to access this resourcehowever this will only give a standard aspnet stack tracewith 500 error when customerrors is off if customerrors is on then this will not redirect to the page i have setup to be thisplayed when a 403 error occurs should i forget about httpexception and instead set all the http codes myself how do i fix thisthe custom errors part of my webconfig is thiscustomerrors modeon defaultredirectgenericerrorpagehtml error statuscode403 redirectforbiddenhtml customerrorsinstead of getting forbiddenhtml i will get genericerrorpagehtml,"['c#', 'asp.net']" +140812,how to initialize autoproperty to not null in c i have a propertypublic dictionarystring string myprop get set when i invoke that property to add an item i get a nullreferenceexceptionhow would i do the null check in the property itself so it gives me a new one if it is null while keeping in the autoproperty patternthanks,"['c#', '.net']" +140841,generating a random hex color code with php i am working on a project where i need to generate an undefined number of random hexadecimal color codesahow would i go about building such a function in php,['php'] +140851,zxing integration into monodroid app i am trying to integrate zxings barcode scanner into a monodroid application i see that normal android java apps have intentintegrationjava and intentresultjava to include into their project to help i was wondering if anyone has ported those to net i did not see them ported in the csharp project i am also wondering if anyone has implemented zxing in another way to get to work with their app if anyone has integrated with monodroid what needs to be done to initiate a scan in a button click handleralso if anyone has any other 3 party barcode scanner that could be implemented instead put those suggestions in the comments,"['c#', 'android']" +140863,web app slider showing days of the months feature for a school project we have to build a web app i will be creating something where people can keep track of their classes their homework and their free time a plannercalendar i am making it sound really lame here but hey i am tired and english is not my first language i will be working in codeigniter for the php logic combined with the usual css jquery mysql php is a requirement for the course i chose to do this in ci because well i wanted to learn the framework we kind of have to show off what we can do at this point of our school career anyway i would like to ask for some insights regarding a feature i want to implement at the top of my page i would like to show a bar which contains the days of the month below the day number i would be showing how many tasks are added on that day by means of some dots when the user clicks previous or next i want to show the previousnext months days i also want some sort of slider underneath this box which the user can use to slide left and right and cycle through the days that way i hope that made senseedit 2 i want the slider to be dynamic if the user slides to the previous or next months or clicks the buttons i want it to load the days of the previousnext months and show those also say were at the 26th of a month the slider would have to show something like 1031 of this month and 110 of the next month i suppose i will also have to change my month indication not like in the image here so a user knows when another month starts i will show them the name of the month heres a picture do not mind the day numbers being messed up i was lazy doing that correctly in photoshop will fix that tomo i have been looking at the jquery ui sliders i suppose i would have to grab the number of days from a database or by using php i guess the cal days in month function could come in handy here when the user clicks on the arrows or slides left or right i do not want the page to refresh should i go with ajax calls there i am not quite sure how to implement this to be honest the numbers are also links to a calendar type of view which shows underneath this bar could i possibly use the ci calendar class for this or is it more for fullfledged google calendartype of calendars i thought this screencast could perhaps be usefulif possible could someone please provide some insights on how to start working on this and which pluginsetc i could perhaps use i am not sure where to start to be honest i am sure i can work this out somehow but i guess it would be nice to get a kickstart by means of some help here the main problem i am seeing is the slidernextprevious thing and loading in the previousnext months days thanks in advanceedit i realise some people might saythink omg why do not you just use the skills you have instead of trying something you have to ask us about well this is because i actually want to learn something while doing this project keep in mind i am not asking for lines of code here i am just asking for some insight on where to start and what stuff to use perhaps little snippets that can help me out thanksupdatei got a very basic day bar working still without a slider nor do the previous and next buttons work but hey at least it fills it in dynamically it shows the 5 days previous to the current day then this month till the end whatever is left to fill in gets filled with days of the next month quite basic however i do have a couple of questions since someone told me yesterday that i was breaking design patterns by doing some stuff the way i was doing it i am extremely paranoid about the way i am working now and i would really like some feedback from codeigniter pros to fill in the day bar i created a helper with a couple of methods one method to dynamically fill that month year thing you see in the picture another method init which loads the list of the days like i explained before i loaded this helper in the controller and i am now using the methods in my view ul php initcurrent day of month current month current year days in current month show history ulthe helper then echoes my day values in my view is this good or bad practice i kept thinking the wrong way when i wanted to start writing the code for this i wanted to have a function somewhere in my controller and then call it from the view but i read that i should not be doing it like that that i had to reverse my logic i find it hard to wrap my head around the fact that i have to do this by sending arrays of data to my view from my controller so i opted for creating the helper good bad any tips resources i should read screencasts i should watch thanks a bunch,"['php', 'jquery', 'mysql']" +140887,mobile safari text input width bug take a look at these screenshotsi am having trouble getting text inputs to render as expected when set to width 100 the text box extends too far to the right past the right padding in the first screenshot and past the right margin of the div in the second screenshotis this a bug in mobile safari if so can anyone suggest a workaround it seems to work fine in other mobile browsers and also in the desktop version of safari the problem seems limited to input elements as select elements seem to have the proper width when styled in the exact same waythanks in advance for any helpheres the code for the first screenshotdiv stylepaddingleft 1em paddingright 1em div stylefontsize 12em username div div input typetext stylewidth 100 fontsize 11em idtbusername nametbusername divdivand heres the code for the second notice how the select elements which are styled the exact same way are unafflicted div classitem hr div classtitlegroup namediv div classcontent asptextbox idtbgroupname runatserver asptextbox div div classconfirmation img alt srcgraphicscheckiconpng runatserver idimgconfirmgroupname div hr divand heres the cssitem paddingtop 5em paddingbottom 5emborderleft 1px solid blackborderbottom 1px solid blackpaddingleft 05emitem title float left width 25item content float left width 67item confirmation floatleft width 8item confirmation img paddingleft 3em height 11emitem hr clear both visibility hidden padding 0 margin 0item select width 100 important fontsize 09emitem input width 100 important fontsize 09em,['css'] +140888,for java developers what is better than hibernate i am unsure if there is a better way to develop databasebacked applications in java but i thought i would askthere is a lot i like about hibernate but there are lots of problems too most of them are not that big of deal when you have as much experience with it as i have but i think the biggest problem that i run into is onesize fits all lazyloading model absolutely hate it there has to be something better out there nothe reason i hate the lazyloading model is that while it is convenient to specify what is lazy and not lazy in the configuration file there are many parts of an application that would prefer lazyloading in one area and no lazy loading in another if you want to satisfy both parts of the program you need put up with lazyloading and manually load entities and their children and their children and so on this is just bloat that does not do anything to solve the real programming problems like the features that get the project doneit seems that the loading strategy that you want to use should be independent of the mapping information but this is not possible as far as i know with hibernate other than writing the loading inside of your java codeanother problem i have with the lazyloading is that it is not easily predictable when you are going to have problems i often do not thiscover lazyloadexceptions until i deploy my application into tomcatit feels even more bloated when these exceptions occur from frameworks like by jackson calling into a collection that has not loaded yet or maybe spring is accessing a property i never asked it to so it throws a lazyinitializationexception anyway for no reason other than that their framework touches all of my bean propertiesanyway because i cannot thiscover these problems during integration tests when i thiscover them in tomcat i often have to shut down tomcat make the changes recompile reload tomcat relogin to my application go back to the page i was at to see if it is fixed this is truly a massive pain it takes so long to fix one of these errors i feel like it is just getting in the way of what i am actually doingin the end i just feel that details like this really weigh me down when i look at my day and ask what did i produce today i find problems like this really get in the way of me feeling like i accomplished somethingof course i can just turn off lazyloading but then i get absolutely dreadful performanceis there a better way something that just does the right thing performs well and easier to reason aboutthanks,['java'] +140899,stop floating divs from wrapping i want to have a row of divs cells that do not wrap if the browser is too narrow to fit themi have searched stack and could not find a working answer to what i think should be a simple css questionthe cells have specified width however i do not want to specify the width of the row the width should automatically be the width of its child cells if the viewport is too narrow to accomodate the rows then the div should overflow with scrollbarsplease provide your answer as working code snippet as i have tried a lot of the solutions i have seen elsewhere like specify width 100 and they do not seem to worki am looking for a htmlcss only solution no javascriptrow float left border 1px solid yellow width 100 overflow autocell float left border 1px solid red width 200px height 100pxdiv classrow div classcelladiv div classcellbdiv div classcellcdivdivat the moment i am actually hard coding the width of the row to a really big number,['html'] +140928,given full path check if path is subdirectory of some other path or otherwise i have 2 strings dir1 and dir2 and i need to check if one is subdirectory for other i tried to go with contains methoddir1containsdir2 but that also returns true if directories have similar names for example cabc and cabc1 are not subdirectories bet returns true there must be a better way,"['c#', '.net']" +140930,i am getting the error certificate identity appears more than once in the key chain when i got this error i checked in my organizer window and found a duplicate identity in my namei tried to delete the duplicate identity in my organizer window but i am not able to select or delete itplease help me to delete this duplicate identity,['iphone'] +140967,net recommended method to obtain user feedback winform i am looking for an effective way to receive feedback from users from within my winform application i have looked around and found only webbased solutions that require users to go to a web page and fill out forms i am looking for something that can be implemented in a way that a user can open a winform dialog fill out the appropriate fields and optionally send a file along with it an error log in this case i have seen many applications implement this but i am not sure how to go about doing it the only method i can think of is sending an email from within the application to my email address the only problem with this is i would need to hard code some email credentials for the email to be sent but i feel as though this is a slight security riskso my question is are there better methods to receive feedback from users without them having to manually send me an email with feedback and attachment,['.net'] +140977,uiscrollview with pagination showing part of the previousfollowing pages i am trying to create a kind of a game mode menu similar to the one used by the cut the rope game to select the level packwhat i want in particular is to achieve the same effect of showing the current item in this case the 2 fabric box item plus a bit of the previous and following items to make sure the user is aware that there are more modes available by scrolling with pagination enabled to make the scroll view automatically center on these itemsthis seems like a natural job for a uiscrollview with pagination enabled however from the documentation it seems the pagination occurs on multiples of the view boundsso if pagination occurs on multiples of the view bounds is there any way to achieve this effect with a uiscrollviewthe fact that we see the full width of the screen would suggest that the uiscrollview frames width would be 320px in this case but each individual item would need to be smaller than that in order to show that little bit of the previous and next items thus messing up the pagination,"['ios', 'iphone', 'objective-c']" +141004,libjpeg decoding to bgr i am using libjpeg to decode a jpeg image from thisk to a memory buffer allocated on the heap i use jpeg read scanlines to read and decode each scanline from the file this is working perfectly decoding each pixel as a 24bit rgb valuethe problem is that i am using an additional thirdparty library which requires a buffer in bgr format rather than rgb when using this library i get odd results as the channels are in the wrong ordertherefore i would like to find a way to make libjpeg decode to bgr format rather than rgb i have trawled the web and cannot find how to configure libjpeg to do this i know i could do an additional pass over the memory buffer and reorder the colour channels manually however the application i am working on is extremely time critical and must be as fast and as efficient as possible,['c++'] +141005,code samples for android bluetooth programming i am new to android i am looking for some code samples for android bluetooth programming could you please post them for me any useful link would be appreciated,"['java', 'android']" +141021,get a form actionurl with jquery how do i get the action url from a form with jquery,['jquery'] +141035,sequence diagram in javascripthtml how to draw sequence diagram in javascripthtmli have seen some charting library like js chart emprise javascript chart etc but those do not support sequence diagramalso seen jointjs but this library also do not support sequence diagram,"['javascript', 'html']" +141046,add custom button to navigation controller without border i add custom button to navigation controller uibarbuttonitem backbutton uibarbuttonitem alloc initwithimageuiimage imagenamedbackpng styleuibarbuttonitemstyleplain targetself actionselectorbackaction selfnavigationitemleftbarbuttonitem backbuttonit works fine but button appears bordered how can i fix thatupdatei found solution uibutton button uibutton alloc initwithframecgrectmake0 0 25 25 button setimageuiimage imagenamedbackpng forstateuicontrolstatenormal button addtargetself actionselectorbuttonfavoriteclicked forcontroleventsuicontroleventtouchupinside uibarbuttonitem back uibarbuttonitem alloc initwithcustomviewbutton button release selfnavigationitemleftbarbuttonitem back,['ios'] +141052,can i have multiple developers test my iphoneipad app if i create an individual account instead of a company account i am wishing to try some iphoneipad development with monotouch 3 net and the first step is to create an accountenrol in the apple development programthe first thing they ask me is if this will be an individual or a company first up this is just myself and a mate so we do not really have some official company set up etc please any suggestions to do this will be met on deaf ears if our rd work out then well get that sortedbut we would like to make it so myself my mate and our familyfriends can test out our rd effort say 1 dev 1 ui guy and 4 or 5 familyfriendswhat type of account should i havei have read some other so posts that it is possible to have other people test out apps on the actual devices with some magic certificate stuff but i just want to make sure i get the correct account set upcheers,"['ios', 'iphone']" +141056,why does objectoutputstreamwriteobject not take a serializable why does objectoutputstreamwriteobjectobject o not take a serializable why is it taking an object,['java'] +141072,java library vs android library what are the differences between java library and android library and what advantagesthisadvantages has each,"['java', 'android']" +141084,attaching file to an email in python leads to a blank file name the following snipit of code works fine except for the fact that the resulting attachment file name is blank in the email the file opens as noname in gmail what am i doing wrongfile name recordingurlsplit1 file namefile name wav urlretrieverecordingurl file name create the container outer email message msg mimemultipart msgsubject new feedback from s aa from intrecordingduration 60 intrecordingduration 60 msgfrom msgto msgpreamble msgsubject file openfile name rb audio mimeaudiofileread fileclose msgattachaudio send the email via our own smtp server s smtplibsmtp sconnect ssendmailmsgfrom msgto msgas string squit,['python'] +141130,avassetexportsession error 11820 i am writing an application that works with video using avfoundation the behaviour of my application is simple i take a video from the camera roll then i create an avmutablecomposition with some audio tracks with the mix composition i initialize an avassetexportsession that stores the video file in the documents directory of my app until this point everything it is ok my video is stored and i am able to play it in another controller if i take the video that i have just stored in my documents folder to make some editing in the same way of the first time avmutablecomposition avassetexportsession it is ok again but the third time i do this process to editing a video the avassetexportsession status becomes fail and with this errordomainavfoundationerrordomain code11820 cannot complete export userinfo0x1a9260 nslocalizedrecoverysuggestiontry exporting again nslocalizeddescriptioncannot complete export i have read that is a general error where the session could not be exported what is the sense of this why only the third time that i made the editing process could it be a memory management mistake a bug this is the code of my avassetexportsession assetexport avassetexportsession alloc initwithassetmixcomposition presetnameavassetexportpresethighestquality assetexportshouldoptimizefornetworkuse yesdata odiernansdateformatter format nsdateformatter alloc initformat setdateformatddmmyhhmmssnsdate now nsdate alloc initnsstring datestring format stringfromdatenownow releaseformat releasensstring ext movnsstring videonamensstring stringwithformat datestring extdata odiernansstring exportpath nssearchpathfordirectoriesindomainsnsdocumentdirectory nsuserdomainmask yes lastobject stringbyappendingpathcomponentvideonameif nsfilemanager defaultmanager fileexistsatpathexportpath nsfilemanager defaultmanager removeitematpathexportpath errornil assetexportoutputfiletype avfiletypequicktimemovie assetexport settimerangecmtimerangemakekcmtimezero videoassetdurationnsurl exporturl nsurl fileurlwithpathexportpath assetexportoutputurl exporturl assetexport exportasynchronouslywithcompletionhandler switch assetexportstatus case avassetexportsessionstatusfailed nslog fail assetexporterror if nsfilemanager defaultmanager fileexistsatpath assetexportoutputurl path nsfilemanager defaultmanager removeitematpath assetexportoutputurl path errornil self performselectoronmainthreadselector ritenta withobjectnil waituntildoneno break case avassetexportsessionstatuscompleted nslog success self performselectoronmainthreadselector savevideotoalbum withobjectexportpath waituntildoneno break case avassetexportsessionstatuscancelled nslog canceled break i have done many searches on the web some people have had a problem in the outputurl of the session but i have tried and seems all ok in my code to assign a unique name to the file i use a nsdate for debugging purposes i have tried to restore a standard string name but the problem remains any ideas can someone suggest to me an alternative method to export to the documents folder an asset with assetwriter insted the avassetexportsession,"['iphone', 'ios']" +141141,enable and thisable a broadcast receiver i try to enable and thisable a broadcast receiver by using this packagemanager methodsetcomponentenabledsettingcomponentname packagemanagercomponent enabled state thisabled packagemanagerdont kill appthe broadcast receiver is registered in the manifest the receiver works fine but when i try to thisable it it still receives the broadcast messageswhen i thisable the receiver in the manifest by androidenabledfalse the receiver does not receive anything but i can not enable iti call the method from inside a service packagemanager pm getapplicationcontextgetpackagemanager componentname componentname new componentnamecomapp broadcast receiversonnetworkchangedreceiver pmsetcomponentenabledsettingcomponentname packagemanagercomponent enabled state thisabled packagemanagerdont kill appandroid manifest receiver androidnamebroadcast receiversonnetworkchangedreceiver androidenabledtrue intentfilter action androidnameandroidnetconnconnectivity change intentfilter receiverthe receiverpublic class onnetworkchangedreceiver extends broadcastreceiver private static final string tag onnetworkchangedreceiveroverridepublic void onreceivecontext context intent intent logdtag in onnetworkchanged i also called the method from inside an activity yesterday i thought it worked but today nothing works anymorecould it be that there is sometimes a big delay in the intent androidnetconnconnectivity change that i misinterpreted yesterday as thisabling the receiveris the approach with the packagemanager the right direction or is there a basic error in the ideathanks a lotsven,['android'] +141145,cannot find package value in androidmanifestxml for module when compiling an android module with intelijidea i get the following error messagecannot find package value in androidmanifestxml for modulethe hover help tell me to fill in the resources page on settings dialogue but what actually do i have to fill inthe manifest file is pretty sort it is a librarymanifest androidversioncode1 androidversionname01 packagecomxdatamodel xmlnsandroid usessdk androidminsdkversion4 androidtargetsdkversion8 usessdkmanifest,['android'] +141150,reordering uitableview without reorder control i need the user to be able to reorder a uitableview by this way he touches a cell for a predetermined period eg 1 second then he can drag and drop it over the other cellsi know how to implement the long touch detection using a gesture recognizer but what is the best way to implement the drag and drop ability without using a reorder control the user should drag the cell from anywhere in the cell not only from the reorder control,['ios'] +141151,rails console running incredibly slowly when editing text in one of my rails apps the console has started running really slowly when i paste in text type and especially delete text i can see in top that irb is using lots of cpu but i do not know how to diagnose this problem any further it just started happening a couple of weeks ago i am wondering if it is possibly readlinewirble related i use both of thosei just tried it in another app pasting in a block of text and it seems just as bad the text is appearing at the rate of one char a second maybe my command line history has filled up or something how can i delete it for the rails console not my bash command line historygrateful for any advice maxedit sorry should have supplied some system details here you gosystem ubuntu 1004ruby version ruby 186 20070924 patchlevel 1 i486linuxi just tried plain irb and i have the same problem it might even be slower it is pretty much ground to a halt halfway through the block of text i pasted in to test iti have rebooted many times my laptop battery is knackered so i have to restart every time i unplug it anywayi am not in a vmi have recently started using rvm ruby version manager and it seems to have coincided with that though it might just be a coincidence the problematic consoles are happening using system ruby though not an rvm heres the output from ps aux grep irbmax 12583 00 00 1756 484 pts7 s apr11 0 sh c irb r irbcompletion r homemaxworkrails appsmillionaire containermillionaireconfigenvironment r console app r console with helpers simplepromptmax 12584 159 27 61872 56956 pts7 s apr11 15826 irb max 13981 644 09 20080 18708 pts9 r 0940 2951 irb max 14625 218 06 15020 12628 pts12 rl 1025 020 irb max 14757 00 00 3048 804 pts13 r 1027 0 grep colorauto irb,"['ruby-on-rails', 'ruby']" +141155,return filename without extension from full path in c i am looking for a way to return filename from full path but without extension private static string returnfilenamewithoutextensionstring varfullpathtofile string filename new fileinfovarfullpathtofilename string extension new fileinfovarfullpathtofileextension return filenamereplaceextension is there more bullet proof solution then replacing extension with empty string,['c#'] +141174,what is the meaning of token ie double ellipsis operator on parameter pack while browsing through gccs current implementation of new c11 headers i stumbled upon token you can check that the following code compiles fine via ideonecomtemplate typename tstruct x template typename t typename ustruct xtu this line is the important one so what is the meaning of this tokenedit looks like so trimmed in question title to i did really mean,['c++'] +141176,why does android allow an apk with an expired certificate to be installed i made an apk signed with a certificate which has a validity of 1 day my aim is to give a trial app to some people but preventing them copying the application after the expiration date if they copy the application before the expiration date that is okay i thought that the android os would block any application with an expired certificate from being installed on the phone however i find that i can install the application on my phone 2 days after the expiration of the certificate with which it is signed jarsigner confirms that the certificate has expired why does android allow an application to be installed with an expired certificate,['android'] +141177,template assignment operator overloading mystery i have a simple struct wrapper thistinguished by two templated assignment operator overloadstemplatetypename tstruct wrapper wrapper template typename u wrapper operatorconst wrapperu rhs cout 1 endl return this template typename u wrapper operatorwrapperu rhs cout 2 endl return this i then declare a and bwrapperfloat a ba bassigning b to a will use the nonconst templated assignment operator overload from above and the number 2 is thisplayedwhat puzzles me is this if i declare c and dwrapperfloat cconst wrapperfloat dc dand assign d to c neither of the two assignment operator overloads is used and no output is thisplayed so the default copy assignment operator is invoked why does assigning d to c not use the const overloaded assignment operator provided or instead why does assigning b to a not use the default copy assignment operator,['c++'] +141202,rspec how to test a helper method that calls a private helper method from the controller heres what i havean application helper method that calls a controller helper method private from itcodeapplicationhelperdef ordenarcoluna titulo nil titulo colunatitleize css class coluna coluna ordenacao direcao ordenacao ordenavel direcao coluna coluna ordenacao and direcao ordenacao asc desc asc link to titulo sort coluna direction direcao class css class end applicationcontrollerhelper method coluna ordenacao direcao ordenacao private def coluna ordenacao return paramssort if paramssort and paramssortsplit size 1 return created at end def direcao ordenacao return wasc descincludeparamsdirection paramsdirection desc end and here is the problem the coluna ordenacao and direcao ordenacao methods cannot be called from rspec it gives me the following errorundefined local variable or method coluna ordenacao for rspeccoreexamplegroupnested 1nested 20x7fbf0a9fe3d8is there any way for that to work btw i am testing the helper not the controller,"['ruby-on-rails', 'ruby']" +141209,make uiicon appear on same line as other text within i am bad with css and i am trying to get the uiicon on the same line as the text in a liul li classuistatedefault spanhellospan span classuiicon uiiconclosespan liulnormally text does not do that within a li so i think it is something with the uiicon css but i could not find what was causing it,['css'] +141214,python print statement with utf8 and nohup i have a some python code that prints log messages when run at the command line it does fine with utf8 log messages that contain special characters print out fine however when run in the background under nohup it barfs on utf8 charactersnohup python27 myprogrampy the error i see is the usual try to encode utf in ascii errorunicodeencodeerror ascii codec cannot encode character uu2013 in position 71 ordinal not in range128i assume this is because nohup signals to python that it does not have a normal terminal so it defaults to ascii is there any way to either tell nohup to run with utf8 enabled or to set this up so that utf8 characters would not cause a crash when running under nohup in the background,['python'] +141217,why was stdpowdouble int removed from c11 while looking into efficient way to compute pq exponentiation where q is an integer and reviewing the c98 and c11 standards i noticed that apparently the stdpowdouble int overload was removed in c11in c98 2656 it has the double powdouble int signaturein c11 268 all i could find was overloads taking a pair of float double or long double and an explicit note that in case of a mixture of parameter types integraldouble that the powdouble double overload should be pickedis this just a clarification of the previous intention were they incorrectly added in c98 were they actually removed in c11 or something elseobviously the powdouble int version provides a nice opportunity for optimization so it seems odd that they would be removed would a compiler still be standards conforming to provide such an optimized overload,['c++'] +141241,net entity framework using contains to find a byte value in a where expression i am building an iqueryable based on parameters i get from the user one of those parameters is a multiselect and i need to retrieve records that contain any of the selected valuesthe code that deals with that isvar ids parametersdeliveryidtoarraycourses courseswherec idscontainsccoursedeliveryidin the above code1 ids is a byte array and i make sure it has multiple values before calling contains2 ccoursedeliveryid that is a byte valuein the database i store coursedeliveryid as tinyint sql server 2008compilation is just finewhen i run the code i get the following argumentexceptiondbexpressionbinding requires an input expression with a collection resulttypeparameter name inputi found the documentation for that exception herewhile trying to solve the problem i found that if i use the same code on shorts ints or longs i do not have any problemi am in touch with microsoft about it since yesterday and will update when i know more but in the meantime i figured i would throw it also here to get more advises if possiblethanks in advance,"['c#', '.net']" +141251,php session not written after outputecho or print r on external ajax call ia m having some serious trouble debugging this particular problem and i hope someone has a clue what ia m doing wrongi have a custom cms system working that uses paragraphs as building blocks that get updated using ajaxprototypejs calls and functions that parse the html chunks in given order clean them up and save this data in associative arrays in a session variableusers log in session is created and i can check for this session without problem in every page i need it the system works directly on the definitive websites so the user can see his updates on realtime and browse the site as a normal user would do but editingso nothing new here but here is the weird thingenduser site on edit modeadmin user logged in path after the logged status is verified a function processes the editable content and saves an associative array to session it also starts some javascript objects for editing every paragraph data is actually saved i can use an external script to check if ita s there after this php script endsif i load a new pagenew content session gets updated with new dataadmin user modifies a paragraph using an inplaceeditor and this html chunk is send via ajax to a php script that starts the named session reads the present session data checks if a paragraph should be modified appended or deleted and reassigns values to existing array keys in session if i make a var dump o print r to session after assigning new data is thereafter that the script echoes the processed html and ajax updates the original paragraph on the calling pagethis script is in admincmsetc that means at least 4 directories inside the root of the sitewhen the script ends i check using the same session dump script to see if data was really writtencommited but no session has only the original data from the calling pagesame id same session name same session start but no data gets writtenthis whole operation is very quick so i though it could be a speed problem scripts ends before session write close can make his work but if i add a new key to session array and put some data there data gets updated and written if i dona t output anything on this script and just process data and set session variables it also geta s updated and writtenita s like some members of session array are getting blocked to updatewhat i did to track this error and what ia m sure ia m not doing wrong1 register globals are off of course2 session name and session start are always present and in the givenorder i used to have multiplesession start close on a same pageto use several named sessions but torefine the problem this is not longerso3 i use session write close after session data is processed alsotried without letting php decide when to commit data but no luck4 im using only cookies for sid5 sessions are stored on tmp i can see the data getting updatedi also tried using a custom savehandler on db but same problem write got only called when no output as presenti searched phpnet stackoverflow google etc for this subject i never ask without investigation this is my first time in many yearsbut ita s just so unlogical it must be something tiny a havena t thought ofthe most weird thing is that when i just process data without output session gets updated ok but if i modify this script afterwards by adding the output and try again instead of just having the newlast value present i get the original value back the one created by the calling page at first place sometimes after playing around a few times php cana t cache values between scripts ori dont have globlals on ia m really clueless this system worked flawless on php43 since ia m using 533 for two moths my users where caliming data where getting mixed up so i checked and yes there are serious problems today i updated to 536 and i cana t get this session values commitedscript code called via ajaxsession cache limiternocache session namecms sessession startincludehtmlawedhtmlawedphpincludeutils cmsphpincludephputils arrayphpvalue postvalueeditorid posteditoridclase postclaseeditoridstr replacepreeditoridvaluehtml entity decodestripslashesvalueent quotesif strlentrimvalue0 die valuediv ideditorid classclasevaluedivnewxhtmlvalueretornocms nuevobloquenewxhtmleditorid sessiondatacmseditoresretorno1 sessiondatacmscontretorno2 session write closeprint rretorno0 offending partwithout everything worksreally nothing strange heremain page code is even simpler no strange php directives etchere is the header of the caller pageinclude phpdbphplen getlensec getseccont getcontadmfin getadmfinfecha getfechatoken gettokencur getcurphp self serverphp selfsession cache limiternocachesession namecms sessession startpassvarunsetadmif empty sessioncms logged and issetadmfin nivelpermisos sessioncms logged group useractual sessioncms logged adm1 elseif empty sessioncms logged unsetuseractual rest of the code update i did late night tests and found someting i dona t understandhelp pleaseit has not only to do with sessions but also with mysql querys same code but instead of trying to write to session array i made a simple update to a innodb table using the session id when i output some code the update does get executedi can output the query string and no mysql error or notice problems but checking the database the row doesna t get updated letting the output out if the script and query does get commited only common thing is sessions are started and output is madei restarted apache etcwho knows but no luck then i made something really stupid because this is a server side thing i changed my browser to firefoxusing safari and everything works ok recheck back to safari nothing works both running side by side same issue php is server side how can different browsers handle code different can a browser say to apache rollback request not handled or call the same script twice without noticechecked safaris developer console and the script is called only once can safari resubmit data silently because it thinks ajax failed i checked headers using firebug and safaris developer tools nothing strange but whenever i make a ajax call with safari the caller page reloads dataaka conection to serveri really dona t understand nothing,['php'] +141266,restorecompletedtransactions broken is restorecompletedtransactions broken in sdk 43 i am trying to restore my autorenewable subscription it is not resulting in callback to updatedtransactions here is my code appdelegateinapp loadstore skpaymentqueue defaultqueue restorecompletedtransactions expecting callback to updatedtransactions but do not receive it voidpaymentqueueskpaymentqueue queue updatedtransactionsnsarray transactions nslogin updatedtransactions transactiontransactionstate for skpaymenttransaction transaction in transactions switch transactiontransactionstate case skpaymenttransactionstaterestored nslogin updatedtransactions skpaymenttransactionstaterestored self restoretransactiontransaction break but i do receive call to this at the endvoid paymentqueuerestorecompletedtransactionsfinishedskpaymentqueue queue,['iphone'] +141273,c line information when parsing xml with xmldocument what are my options for parsing an xml file with xmldocument and still retain line information for error messages later on as an aside is it possible to do the same thing with xml deserialisationoptions seem to includeextending the dom and using ixmllineinfousing xpathdocument,['c#'] +141274,are there php tools to generate crud screens from db schema i have been using phpmyedit to quickly generate crud screens for databases it is a quick way to start interacting with data in my projects and lets me toss together internal admin pages fast but it does not read the db schema so i have to manually set it upi am looking for a toolway to quickly generate crud from beginning to end i give it a db table and it reads the schema generates the html markup for the form and does the crud work on the db itselfdoes this exist my goal is to have zero setup for basic functionality and then i would love the option of being able to extend that basic setup to further refine the experience for example if it can see my database table has four varchar fields that would be ready to go with four editing fields out of the box but then i would like to be able to add a little bit of codeset some flags to specify the one varchar column that is meant to hold an email address so the tool would then do data validation to only allow emails in that fieldupdate i am seeking a solution that i can drop into my existing php projects not an entire framework,['php'] +141275,iphone detecting if the idevice has a front camera apple recommends not searching for hardware version but for the specific feature in which you are interested so how may i detect if there is a front camera on the device to be able to thisable some features uiimagepickercontroller issourcetypeavailable uiimagepickercontrollersourcetypecamera only tells that there is a camera somewhere,['iphone'] +141283,determine correct rgba value for bar tint color given a clients design image i often get given mockup images that define how an iphone app is supposed to look these can come from as many different methods as there are projects sometimes balsamiq or even handdrawn sometimes photoshop one thing that is common is a bar tint color specified usually to match some corporate branding or overall app designif i open one of these design images in an app and use the paint dropper tool to get the rgb value for a color there are many places to do it from the darkest regions at the lower edge of included buttons to the lightest regions at the top of the bar i cannot find a place to sample the color where the programmed result matches the mockups it is always wrong in some regard leading to me squinting at two images trying to tweak one or more color values so they match well enoughgiven an sample of how a client imagines a navigation bar should appear how do you determine the right uicolor to apply to a bars tintcolor attributeignoring mockups containing rainbow effects misapplied gradients and other flights of fancy matching color and brightness along the centre line would be good enough that is at least a defensible position what you ask for just is not how ios works,['iphone'] +141290,rails devise is there a way to ban a user so they cannot login or reset their password i have a lot of users thanks to devise and i want to ban a few problem makers does devise have this support built inthanks,['ruby-on-rails'] +141307,subdomain cookie sharing in rails 3 is not working on heroku i am trying to have cookies on my site dapsharecom work for both the root address and the w subdomaina lot of other stackoverflow answers and the great railscasts vid on this topic have suggested adding this line to session storerbdapshareapplicationconfigsession store cookie store key dapshare session domain allthis does not seem to make a difference if i log in at dapsharecom i still am not logged in at wdapsharecomam i doing something wrong here i am using the following code to store information in the cookiecookiespermanentsignedthing to store store informationthanks for any help,['ruby-on-rails'] +141326,how to send push notification to multiple devices this is the first time i am using push notification in my appi have gone through sample applications along with books and i got how to send push notification to a single devicebut i am not getting exactly what changes should i do in my program to send push notification to multiple devicesi am using pushmebaby application for server side codingpleasehelp me outthanks in advance,['iphone'] +141362,executing unix shell commands using php a text box will be used to capture the command i have been told that i have to use the exec function to execute unix shell commandssomething like this user types ls in the text box the exec function will execute the unix command and the command will be thisplayed on the web pagewhat i want to know how will i get the output of the shell command and thisplay in the web browser using phpi do not know where to start since i am very new to phpi am using ubuntu,['php'] +141369,get the referrer paidnatural and keywords for the current visitor with google analytics is it possible to get the following information about the current visitor using google analytics api with javascriptreferrer site source in gapaid or natural medium in gakeywordfirst timereturningnumber of visitsif it is not possible with google analytics api is there any other easy way to do it apart from parsing http referer storing the visits statistics in db etc,['javascript'] +141393,how to generically format a boolean to a yesno string i would like to thisplay yesno in different languages according to some boolean variableis there a generic way to format it according to the locale passed to itif there is not what is the standard way to format a boolean besides boolvar resourcesyes resourcesnoi am guessing that boolvartostringiformatprovider is involvedis my assumption correct,['c#'] +141394,how to execute google codepro analytix from command line is it possible to run google codepro analytix from command linewhat i am looking for is to run this from a shell script passing the file name as a parameter and get all the metrics generated on file level for the filename i passed in as parameteris it possible to do so and howare there any other tools that can give same metrics for a java file and be executed from a shell script,['java'] +141454,java basics a static function without a name or return type public class main public static final logger logger loggergetloggermainclassgetname static try loggeraddhandlernew filehandlererrorslogtrue catchioexception ex loggerloglevelwarningextostringex i am wondering what is this nameless static function about i never saw anything like this in java which i am currently learningwhat is it for when is it typically used when is this gonna be executed in the program,['java'] +141480,zero an array in c code possible duplicateshow to initialize an array to something in c without a loophow to initialize an array in c how can i zero a known size of an array without using a for or any other loop for examplearr20 0this is the long way i need it the short way,['c'] +141486,what does the constructor is ambiguous mean i would like to know what the error message in eclipse meansthe constructor caseproblem solution double casesource is ambiguous,['java'] +141503,where is nsalerth in the ios sdk according to ioss using and creating error objects one can thisplay a error object with the following codenserror theerror nilbool success mydoc writetourlself docurl oftypehtml errortheerrorif success no maybe try to determine cause of error and recover first nsalert thealert nsalert alertwitherrortheerror thealert runmodal ignore return valueunfortunately i am not smart enough to figure out how to include nsalerthany help would be appreciated,"['iphone', 'ios']" +141513,guarding resources with singleton i have read quite a few blog posts and answers on so pointing to singleton being a bad design previously i implemented a singleton cameracontrol class this class controls a camera which is connected to the system under the following knowledgeunder no circumstance will there be more than one camera the camera api provided by the camera maker control all camerasusing the api of the camera maker in multiple places at the same time have caused problems in the past eg one thread trying to grab an image the other thread trying to set the shutter speedmy class only provides several extra methods to thisplay the image captured in a ui forward the image to a face detector ie it is not memory intensiveis my choice of making this class a singleton class a bad decision,['c++'] +141516,server cpu and gpu with lamp i am trying to figure out more about the hardware that can be utilized when running a php application or even a c compiled php app using hiphop i would like to setup a microserver and use the gpu to help the cpu process requestsanyone,['php'] +141525,overriding protected methods in java testjavapackage aimport bbpublic class test public static void mainstring v new atest new btest ajavapackage apublic class a protected void test bjavapackage bpublic class b extends aa protected void test why does new btest give an error does not that break visibility rulesbtest is invisible in test because they are in different packages and yet it refuses to call the test in bs superclass which is visiblelinks to the appropriate part of the jls would be appreciated,['java'] +141526,how do i debug a slow rails app boot time our rails app is nice and fast once it is loaded but the startup is brutally slow console passenger etc all take almost 10 seconds to kick in seems to be way more than it should be what tools or methods should i use to hone in on the slowest parts what are the usual suspects,"['ruby-on-rails', 'ruby']" +141534,spring mvc using responsestatusreason on a responsebody exception handler in tomcat does anybody know why i cannot use responsestatusreason my message on an exception handler in spring mvc while still returning a responsebody what seems to happen is that if i use the reason attribute this exception handle works the result is a 404 and the http body is the json serialised message the messageexceptionhandlerresponsestatusvalue httpstatusnot foundpublic mapstring string notfoundhandlernotfoundexception e return collectionssingletonmapmessage egetmessage this does not the response is a 404 and the status line reads really really not found but the body is actually the standard tomcat 404 pageexceptionhandlerresponsestatusvalue httpstatusnot found reason really really not foundpublic mapstring string reallynotfoundhandlerreallynotfoundexception e return collectionssingletonmapmessage egetmessagethe code for this example is over on github,['java'] +141561,how can assigning a variable result in a serious performance drop while the execution order is nearly untouched when playing around with multithreading i could observe some unexpected but serious performance issues related to atomiclong and classes using it such as javautilrandom for which i currently have no explanation however i created a minimalistic example which basically consists of two classes a class container which keeps a reference to a volatile variable and a class demothread which operates on an instance of container during thread execution note that the references to container and the volatile long are private and never shared between threads i know that there is no need to use volatile here it is just for demonstration purposes thus multiple instances of demothread should run perfectly parallel on a multiprocessor machine but for some reason they do not complete example is at the bottom of this postprivate static class container private volatile long value public long getvalue return value public final void setlong newvalue value newvalue private static class demothread extends thread private container variable public void prepare thisvariable new container public void run forint j 0 j 10 j variablesetvariablegetvalue systemnanotime during my test i repeatedly create 4 demothreads which are then started and joined the only difference in each loop is the time when prepare gets called which is obviously required for the thread to run as it otherwise would result in a nullpointerexceptiondemothread threads new demothreadnumberofthreads forint j 0 j 100 j boolean prepareafterconstructor j 2 0 forint i 0 i threadslength i threadsi new demothread ifprepareafterconstructor threadsiprepare forint i 0 i threadslength i ifprepareafterconstructor threadsiprepare threadsistart jointhreadsthreads for some reason if prepare is executed immediately before starting the thread it will take twice as more time to finish and even without the volatile keyword the performance differences were significant at least on two of the machines and oses i tested the code heres a short summarymac os summaryjava version 160 24java class version 500vm vendor sun microsystems incvm version 191b02334vm name java hotspottm 64bit server vmos name mac os xos arch x86 64os version 1065processorscores 8 with volatile keywordfinal results31979 ms when prepare was called after instantiation96482 ms when prepare was called before execution without volatile keywordfinal results26009 ms when prepare was called after instantiation35196 ms when prepare was called before execution windows summaryjava version 160 24java class version 500vm vendor sun microsystems incvm version 191b02vm name java hotspottm 64bit server vmos name windows 7os arch amd64os version 61processorscores 4 with volatile keywordfinal results18120 ms when prepare was called after instantiation36089 ms when prepare was called before execution without volatile keywordfinal results10115 ms when prepare was called after instantiation10039 ms when prepare was called before execution linux summaryjava version 160 20java class version 500vm vendor sun microsystems incvm version 190b09vm name openjdk 64bit server vmos name linuxos arch amd64os version 263228genericprocessorscores 4 with volatile keywordfinal results45848 ms when prepare was called after instantiation110754 ms when prepare was called before execution without volatile keywordfinal results37862 ms when prepare was called after instantiation39357 ms when prepare was called before execution mac os details volatiletest 1 4 threads setting variable in creation loopthread2 completed after 653 msthread3 completed after 653 msthread4 completed after 653 msthread5 completed after 653 msoverall time 654 ms test 2 4 threads setting variable in start loopthread7 completed after 1588 msthread6 completed after 1589 msthread8 completed after 1593 msthread9 completed after 1593 msoverall time 1594 ms test 3 4 threads setting variable in creation loopthread10 completed after 648 msthread12 completed after 648 msthread13 completed after 648 msthread11 completed after 648 msoverall time 648 ms test 4 4 threads setting variable in start loopthread17 completed after 1353 msthread16 completed after 1957 msthread14 completed after 2170 msthread15 completed after 2169 msoverall time 2172 ms and so on sometimes one or two of the threads in the slow loop finish as expected but most times they do notthe given example looks theoretically as it is of no use and volatile is not needed here however if youd use a javautilrandominstance instead of the containerclass and call for instance nextint multiple times the same effects will occur the thread will be executed fast if you create the object in the threads constructor but slow if you create it within the runmethod i believe that the performance issues described in java random slowdowns on mac os more than a year ago are related to this effect but i have no idea why it is as it is besides that i am sure that it should not be like that as it would mean that it is always dangerous to create a new object within the runmethod of a thread unless you know that no volatile variables will get involved within the object graph profiling does not help as the problem thisappears in this case same observation as in java random slowdowns on mac os contd and it also does not happen on a singlecorepc so i would guess that it is kind of a thread synchronization problem however the strange thing is that there is actually nothing to synchronize as all variables are threadlocalreally looking forward for any hints and just in case you want to confirm or falsify the problem see the test case belowthanksstephanpublic class unexpectedperformanceissue private static class container remove the volatile keyword and the problem thisappears on windows or gets smaller on mac os private volatile long value public long getvalue return value public final void setlong newvalue value newvalue private static class demothread extends thread private container variable public void prepare thisvariable new container override public void run long start systemnanotime forint j 0 j 10 j variablesetvariablegetvalue systemnanotime long end systemnanotime systemoutprintlnthisgetname completed after end start10 ms public static void mainstring args systemoutprintlnjava version systemgetpropertyjavaversion systemoutprintlnjava class version systemgetpropertyjavaclassversion systemoutprintlnvm vendor systemgetpropertyjavavmspecificationvendor systemoutprintlnvm version systemgetpropertyjavavmversion systemoutprintlnvm name systemgetpropertyjavavmname systemoutprintlnos name systemgetpropertyosname systemoutprintlnos arch systemgetpropertyosarch systemoutprintlnos version systemgetpropertyosversion systemoutprintlnprocessorscores runtimegetruntimeavailableprocessors systemoutprintln int numberofthreads 4 systemoutprintlnnreference test single thread demothread t new demothread tprepare trun demothread threads new demothreadnumberofthreads long createtime 0 starttime 0 forint j 0 j 100 j boolean prepareafterconstructor j 2 0 long overallstart systemnanotime ifprepareafterconstructor systemoutprintlnntest j1 numberofthreads threads setting variable in creation loop else systemoutprintlnntest j1 numberofthreads threads setting variable in start loop forint i 0 i threadslength i threadsi new demothread either call demothreadprepare here in odd loops ifprepareafterconstructor threadsiprepare forint i 0 i threadslength i or here in even loops should make no difference but does ifprepareafterconstructor threadsiprepare threadsistart jointhreadsthreads long overallend systemnanotime long overalltime overallend overallstart ifprepareafterconstructor createtime overalltime else starttime overalltime systemoutprintlnoverall time overalltime10 ms systemoutprintlnfinal results systemoutprintlncreatetime10 ms when prepare was called after instantiation systemoutprintlnstarttime10 ms when prepare was called before executionprivate static void jointhreadsthread threads forint i 0 i threadslength i try threadsijoin catch interruptedexception e eprintstacktrace,['java'] +141568,why numpy correlate and corrcoef return different values and how to normalize a correlate in full mode i am trying to use some time series analysis in python using numpyi have two somewhat mediumsized series with 20k values each and i want to check the sliding correlationthe corrcoef gives me as output a matrix of autocorrelationcorrelation coefficients nothing useful by itself in my case as one of the series contains a lagthe correlate function in modefull returns a 40k elements list that do look like the kind of result i am aiming for the peak value is as far from the center of the list as the lag would indicate but the values are all weird up to 500 when i was expecting something from 1 to 1i cannot just divide it all by the max value i know the max correlation is not 1how could i normalize the crosscorrelation correlation in full mode so the return values would be the correlation on each lag step instead those very large strange values,['python'] +141571,any way to safely call assemblygettypes i have searched high and low but i cannot come up with a solution for thisi need to get all the interface types from an assembly with code like thisienumerabletype interfaces assemblygettypeswherex xisinterfacethe problem is for certain assemblies i run into the following errorunable to load one or more of the requested types retrieve the loaderexceptions property for more informationi am completely clear on why this happens dependant assemblies are not loaded and how it can be worked around if i want to troubleshoot a specific assembly in my case i do not know the assembly up front the user will select itwhat i would like to know is whether there is any way to allow the code to continue past any types that cannot be retrieved and still pull the ones that do not fail,['c#'] +141582,union all vs or condition in sql server query i have to select some rows based on a not exists condition on a table if i use a union all as below it gets executed in less than 1 secondselect 1 from dummytablewhere not existsselect 1 from table twhere data1 tcol1 and data2tcol2union allselect 1 from table twhere data1 tcol2 and data2tcol1but if i use an or condition it takes close to a minute as sql server is doing a table lazy pool can someone explain itselect 1 from dummytablewhere not existsselect 1 from table twhere data1 tcol1 and data2tcol2 or data1 tcol2 and data2tcol1,['sql'] +141588,simple java name based locks mysql has a handy functionselect get locksomenamethis can be used to create simple but very specific name based locks for an application however it requires a database connectioni have many situations likesomemethod do stuff to user a for their data for feature xit does not make sense to simply synchronize this method because for example if this method is called for user b in the meantime user b does not need to wait for user a to finish before it starts only operations for the user a and feature x combination need to waitwith the mysql lock i could do something likesomemethod executequeryselect get lockuserafeaturex only locked for user a for their data for feature x executequeryselect release lockuserafeaturexsince java locking is based on objects it seems like i would need to create a new object to represent the situation for this lock and then put it in a static cache somewhere so all the threads can see it subsequent requests to lock for that situation would then locate the lock object in the cache and acquire its lock i tried to create something like this but then the lock cache itself needs synchronization also it is difficult to detect when a lock object is no longer being used so that it can be removed from the cachei have looked at the java concurrent packages but nothing stands out as being able to handle something like this is there an easy way to implement this or am i looking at this from the wrong perspectiveeditto clarify i am not looking to create a predefined pool of locks ahead of time i would like to create them on demand some pseudo code for what i am thinking islockmanageracquirelockstring name lock lock synchronized map lock mapgetname does not exist yet create and store iflock null lock new lock mapputname lock locklocklockmanagerreleaselockstring name unlock if this was the last hold on the lock remove it from the cache,['java'] +141593,java library for creating straight skeleton i have as an input a 2d polygon with holes and i need to find it is straight skeleton like in the picturemaybe there is a good java library for itand if not can you point me to the good explanation of the algorithm so i could implement it myself i have not found good resources on google,['java'] +141608,array filter in python for example i have two lists a 6 7 8 9 10 11 12subset of a 6 9 12 the subset of athe result should be 7 8 10 11 the remaining elements is there a builtin function in python to do this,['python'] +141614,java whats the bigo time of declaring an array of size n what is the running time of declaring an array of size and in java i suppose this would depend on whether the memory is zeroed out on garbage collection in which case it could be o1 or on initialization in which case it would have to be on,['java'] +141620,how to get file content in java to get the content of a txt file i usually use a scanner and iterate over each line to get the contentscanner sc new scannernew filefiletxtwhileschasnextline string str scnextline does the java api provide a way to get the content with one line of code likestring content fileutilsreadfiletostringnew filefiletxt,['java'] +141626,is there an easy way to make a rails activerecord model readonly i want to be able to create a record in the db but then prevent rails from making changes from that point on i understand changes will still be possible at the db leveli believe attr readonly does what i want on an attribute level but i do not want to have to manually specify fields i would rather have more of a whitelist approachalso i know there is a read only option for associations but i do not want to limit the readonlyness of the object to if it was fetched via an association or notfinally i want to be able to still destroy a record so stuff like dependent destroy works in the associationsso to summarize 1 allow the creation of records 2 allow the deletion of records and 3 prevent changing records that have been persisted,['ruby-on-rails'] +141644,attach getset function to objects property in js i essentially have an objectvar foo function thissettingfalse thisrefresh function let a new fooasettingtruearefresh is triggeredi need to trigger refresh anytime setting is written to i feel like it has something to do with bind but i could not quite get it,['javascript'] +141654,best tool for unit testing in mysql i have been doing a lot of sproc programming in mysql latelyand i must say that i like it a lot however debugging these babies sucksanyone know of any tools that can put some happiness in my mysql debugging,['mysql'] +141674,is it wise to access readonly data from multiple threads simultaneously i have an application that i am trying to make multithreaded each thread will access a large chunk of readonly datais is okay if multiple threads access the data simultaneously i know that if the data were not readonly i would need to use mutexes or some other form of synchronization to prevent raceconditions but i am wondering if it is okay to read the data without regard to synchronizationthe data in question will not be modified for the duration of all threads the application will be running on linux and windows and is written in c if that makes any difference,['c++'] +141676,private property in objective c is there a way to declare a private property in objective c the goal is to benefit from synthesized getters and setters implementing a certain memory management scheme yet not exposed to publican attempt to declare a property within a category leads to an errorinterface myclass nsobject nsarray somearrayendinterface myclass privateproperty nonatomic retain nsarray somearrayendimplementation myclass privatesynthesize somearray somearray error here synthesize not allowed in a categorys implementationendimplementation myclassend,['objective-c'] +141685,jquery validation multiple tabs validate one at a time i am new to jquery and i am trying to use it and the validation plugin to create a multipart form with multiple tabs for different sections right now i have it where there are multiple tabs and the next button switches to the next tab the problem i am having is that when i finally submit on the last page the form validates properly but if there are errors on the other page the user is not notified and validation really only happens once submit is clicked how would i validate each individually when i click next i do not really want to create multiple forms or keep track of hidden fields s any suggestionsthanksscript typetextjavascriptdocumentreadyfunction stuff tabs var tabs tabstabs nexttabclickfunction var selected tabstabsoption selected tabstabsoption selected selected 1 tabstabsselect thishash use link to submit form instead of button aidsubmitclick function thisparentsformsubmit form validation var validator myformvalidate scriptform classcmxform idmyform methodpost action div idtabs ul lia hrefgeneralgeneralali lia hreftab2ali ul div idgeneral stuff p a classnexttab navbutton hreftab2spannextspana p div div idtab2 h2tab2h2 p a classnexttab navbutton hrefgeneralspanprevspana a clasubmit navbutton idsubmit hrefspansubmitspana p div divformeditandrewi did some combination of your 2nd example and thisabling tabs seems to work aside from having the page refresh rethisable the tabsvar tabs tabstabs thisabled 12345 select functionevent ui var valid true var current thistabsoption selected var panelid tabs ul aeqcurrentattrhref ifuiindex current panelidfindinputeachfunction consolelogvalid if validatorelementthis valid valid false return valid in combination withnexttabclickfunction var selected tabstabsoption selected tabstabsenable selected1 tabstabsoption selected selected 1,"['javascript', 'jquery']" +141689,assigning ids to entities with entityframework 4 i would like to implement default id generation support for my entitieswhen saving the entity i would like entityframework to only generate the id value for the entity if it is not already set if the id already has a nonnull nonzero value i want to have that entity id preserved when the entity is saved in the databasei am migrating data from a legacy data model entityframework model created from the old database to a newly created modelfirst entityframework model let us call the old model a and the new model ttypically i would want t entities to get their ids set upon save they are all int64 for the longterm use of the new modelcurrently i am explicitly assigning t entity ids based on the id of the corresponding a entity from which i am migrating this is so the migration results are easy to check however although i can assign the id for a t entity to the same id as the a entity in my migration routine after i save the entities the id values have changedis there a way to override the default saving method for all entities in the t model so the id value is only assigned if it is not already set in the entity before it gets savedi have looked at some of the other entityframeworkid questions here but to my mind none of them are asking the same thingthanks for any leads,['c#'] +141704,how do i transfer files using ssh and scp using ruby calls i have a file in the directory usrsharerubyrb i want to transfer that file to ipbased remote devices using ssh and scp using ruby calls can anyone help me,"['ruby-on-rails', 'ruby']" +141712,what needs to change in this packagejson file to work with npm 030 trying to use a lib but getting this errornpm err jsonparse failed to parse packagejson datanpm err jsonparse note that packagejson must be actual json notnpm err jsonparse just a javascript objectnpm err jsonparse npm err jsonparse this changed in npm 030 and is not a bug in npmnpm err jsonparse tell the package author to fix their packagejson filenot sure what changes are likely needed to make it valid json thanks very much,['javascript'] +141732,i got the error javatextparseexception unparseable date i want the date format as ddmymy code isstring v date strsun mar 06 112816 ist 2011 dateformat formatter formatter new simpledateformatddmy date date tempnull try date temp date formatterparsev date str catch parseexception ex loggergetloggerattendance calculationclassgetnameloglevelsevere null ex systemoutprintlnoutput date tempbut i got the error as the log message is nulljavatextparseexception unparseable date sun mar 06 112816 ist 2011 at javatextdateformatparsedateformatjava337 at orgfespisjsfmainattendance calculationbtn show pending appl actionattendance calculationjava415 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava39 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava25 at javalangreflectmethodinvokemethodjava597 at comsunelparserastvalueinvokeastvaluejava187 at comsunelmethodexpressionimplinvokemethodexpressionimpljava297 at comsunfaceletseltagmethodexpressioninvoketagmethodexpressionjava68 at javaxfaceseventmethodexpressionactionlistenerprocessactionmethodexpressionactionlistenerjava99 at javaxfaceseventactioneventprocesslisteneractioneventjava88 at javaxfacescomponentuicomponentbasebroadcastuicomponentbasejava771 at javaxfacescomponentuicommandbroadcastuicommandjava372 at javaxfacescomponentuiviewrootbroadcasteventsuiviewrootjava475 at javaxfacescomponentuiviewrootprocessapplicationuiviewrootjava756 at comsunfaceslifecycleinvokeapplicationphaseexecuteinvokeapplicationphasejava82 at comsunfaceslifecyclephasedophasephasejava100 at comsunfaceslifecyclelifecycleimplexecutelifecycleimpljava118 at comsunfacesextensionsavatarlifecyclepartialtraversallifecycleexecutepartialtraversallifecyclejava94 at javaxfaceswebappfacesservletservicefacesservletjava265 at orgapachecatalinacoreapplicationfilterchainservletserviceapplicationfilterchainjava427 at orgapachecatalinacorestandardwrappervalveinvokestandardwrappervalvejava315 at orgapachecatalinacorestandardcontextvalveinvokeinternalstandardcontextvalvejava287 at orgapachecatalinacorestandardcontextvalveinvokestandardcontextvalvejava218 at orgapachecatalinacorestandardpipelinedoinvokestandardpipelinejava648 at orgapachecatalinacorestandardpipelinedoinvokestandardpipelinejava593 at comsunenterprisewebwebpipelineinvokewebpipelinejava94 at comsunenterprisewebpesessionlockingstandardpipelineinvokepesessionlockingstandardpipelinejava98 at orgapachecatalinacorestandardhostvalveinvokestandardhostvalvejava2 at orgapachecatalinacorestandardpipelinedoinvokestandardpipelinejava648 at orgapachecatalinacorestandardpipelinedoinvokestandardpipelinejava593 at orgapachecatalinacorestandardpipelineinvokestandardpipelinejava587 at orgapachecatalinacorecontainerbaseinvokecontainerbasejava1093 at orgapachecatalinacorestandardenginevalveinvokestandardenginevalvejava166 at orgapachecatalinacorestandardpipelinedoinvokestandardpipelinejava648 at orgapachecatalinacorestandardpipelinedoinvokestandardpipelinejava593 at orgapachecatalinacorestandardpipelineinvokestandardpipelinejava587 at orgapachecatalinacorecontainerbaseinvokecontainerbasejava1093 at orgapachecoyotetomcat5coyoteadapterservicecoyoteadapterjava291 at comsunenterprisewebconnectorgrizzlydefaultprocessortaskinvokeadapterdefaultprocessortaskjava6 at comsunenterprisewebconnectorgrizzlydefaultprocessortaskdoprocessdefaultprocessortaskjava597 at comsunenterprisewebconnectorgrizzlydefaultprocessortaskprocessdefaultprocessortaskjava872 at comsunenterprisewebconnectorgrizzlydefaultreadtaskexecuteprocessortaskdefaultreadtaskjava341 at comsunenterprisewebconnectorgrizzlysslsslreadtaskproceslreadtaskjava4 at comsunenterprisewebconnectorgrizzlysslsslreadtaskdotasksslreadtaskjava230 at comsunenterprisewebconnectorgrizzlytaskbaseruntaskbasejava264 at comsunenterprisewebconnectorgrizzlysslsslworkerthreadrunsslworkerthreadjava106thanks for any helpbut i want the date in date format as ddmy,['java'] +141750,autoformating of inline code in mvc are there any way to turn of the autoformatting of c code that is inlined inside html when making a mvc applicationit seems that it use the c text editor settings for the inline code as well but i do not want to use the same formatting inside the html file as the normal code filesfor example if i write somecodehere then some html in between and then i put the at the end visual studio automatically reformats the code to this using htmlbeginform for the mvc code i think it looks much tidyer like this using htmlbeginform but i do not see how to change this without messing up the formatting for my normal code files,['c#'] +141751,real world usecase for the at indexing function in the c std library cs container vector deque provide the atindex accessor function in addition to operatorindex to access container elementsthe difference between this member function and member operator function operator is that dequeat signals if the requested position is out of range by throwing an out of range exceptioni have never ever needed this function in my code as it never makes sense in my c code to access elements that are possibly outofrange the code is always written to access correct indexes or produce a meaningful errorexception in case indexes cannot be made to matchi would be interested in real world examples possibly from some open source project as that would add some context where at is used in production codemaybe someone can give an example of an algorithmic problem where using at made sensenote i have recently used it in some unittest code where adding index checking code was not considered worth the trouble and the out of range exception thrown by at is considered enough infocontext in case the test breaksnote regarding this answer by ildjarn i do not want to start a thiscussion or comment war on this i am interesting in positive finds that is concrete examples where it has been used thank you,['c++'] +141756,remove directions from google map api v3 i have a google map using api v3 which gets directions from one location to another the app works great but the window which gets the directions is an overlay on the map i would like it so when this window is closed directions are removed from the map but other markers remaini have tried the followingcontent closeliveclick function contenthidedirectionthisplay new googlemapsdirectionsrendererdirectionthisplaysuppressmarkers truedirectionthisplaysetmapmapreturn falsethis seems to hide the window as expected but does not do anything regards with removing directions from the mapany help is much appreciateddave,"['javascript', 'jquery']" +141761,optimising this c avr code i have an interrupt handler that just is not running fast enough for what i want to do basically i am using it to generate sine waves by outputting a value from a look up table to a port on an avr microncontroller but unfortunately this is not happening fast enough for me to get the frequency of the wave that i want i was told that i should look at implementing it in assembly as the compiler generated assembly might be slightly inefficient and may be able to be optimised but after looking at the assembly code i really cannot see what i could do any betterthis is the c codeconst uint8 t amplitudes6060 127 140 153 166 176 191 202 212 221 230 237 243 248 251 253 254 253 251 248 243 237 230 221 212 202 191 179 166 153 140 127 114 101 88 75 63 52 42 33 24 17 11 6 3 1 0 1 3 6 11 17 24 33 42 52 63 75 88 101 114const uint8 t amplitudes1313 127 176 221 248 202 153 101 52 17 1 6 33 75const uint8 t amplitudes1010 127 176 248 202 101 52 17 1 33 75volatile uint8 t numofamps 60volatile uint8 t amplitudes amplitudes60volatile uint8 t amplitudeplace 0 isrtimer1 compa vect portd amplitudesamplitudeplace amplitudeplace ifamplitudeplace numofamps amplitudeplace 0 amplitudes and numofamps are both changed by another interrupt routine that runs much slower than this one it basically is run to change the frequencies that are being played at the end of the day i would not be using those exact arrays but it will be a very similar set up i will most likely have an array with 60 values and another with just 30 this is because i am building a frequency sweeper and at the lower frequencies i can afford to give it more samples as i have more clock cycles to play with but at the higher frequencies i am very much strapped for timei do realise that i can get it to work with a lower sampling rate but i do not want to go under 30 samples per period i do not think having the pointer to the array makes it any slower as the assembly to get a value from an array and the assembly to get a value from a pointer to an array seems the same which makes senseat the highest frequency that i have to produce i have been told i should be able to get it working with about 30 samples per sine wave period at the moment with 30 samples the fastest it will run is at about half the required max frequency which i think means that my interrupt needs to run twice as fastso that code there when simulated takes 65 cycles to complete again i have been told i should be able to get it down to about 30 cycles at bestthis is the asm code produced with my thinking of what each line does next to itisrtimer1 compa vect push r1push r0in r0 0x3f save status regpush r0eor r1 r1 generates a 0 in r1 used much laterpush r24push r25push r30push r31 all regs savedportd amplitudesamplitudeplacelds r24 0x00c8 r24 amplitudeplace iam pretty surelds r30 0x00b4 these two lines load in the address of the lds r31 0x00b5 array which would explain why itad a 16 bit number if the atmega8 uses 16 bit addressesadd r30 r24 aha this must be getting the address of the element adc r31 r1 at amplitudeplace in the array ld r24 z z low is r30 makes sense i think this is loading the memory located at the address in r30r31 and putting it into r24out 0x12 r24 fairly sure this is putting the amplitude into portdamplitudeplace lds r24 0x011c r24 amplitudeplacesubi r24 0xff subi is subtract imediate 0xff 255 so iam thinking with an 8 bit value x x1 x 255 i might just trust that the compiler knows what itas doing here rather than try to change it to an addi sts 0x011c r24 puts the new value back to the address of the variableifamplitudeplace numofampslds r25 0x00c8 r24 amplitudeplacelds r24 0x00b3 r25 numofamps cp r24 r24 compares them brne 4 0xdc vector 60x54 amplitudeplace 0 sts 0x011c r1 oh this is why r1 was set to 0 earlier pop r31 restores the registerspop r30pop r25pop r24pop r19pop r18pop r0out 0x3f r0 63pop r0pop r1retiapart from maybe using less registers in the interrupt so that i have less pushpops i really cannot see where this assembly code is inefficient my only other thought is maybe the if statement could be gotten rid of if i could work out how to get a and bit int datatype in c so that the number will wrap around when it reaches the end by this i mean i would have 2n 1 samples and then have the amplitudeplace variable just keep counting up so that when it reaches 2n it will overflow and will be reset to zeroi did try simulating the code without the if bit completely and while it did improve the speed it only took about 10 cycles off so that it was at about 55 cycles for one execution which still is not quite fast enough unfortunately so i do need to optimise the code even further which is hard considering without that it is only 2 linesmy only other real thought is to see if i can store the static look up tables somewhere that takes less clock cycles to access the lds instructions it uses to access the array i think all take 2 cycles so i probably wouldnt really be saving much time there but at this stage i am willing to try anythingi am totally at a loss of where to go from here i cannot see how i could make my c code any more efficient but i am only fairly new to this sort of thing so i could be missing something i would love any sort of help i realise this is a pretty particular and involved problem and normally i would try to avoid asking those sort of questions here but i have been working on this for ages and am at a total loss so i will really take any help that i can get,['c'] +141764,c decision tree implementation question think in code i have been coding for a few years but i still have not gotten the hang of pseudocoding or actually thinking things out in code yet due to this problem i am having trouble figuring out exactly what to do in creating a learning decision tree here are a few sites that i have looked at and trust me there were plenty moredecision tree tutorialsdms tutorialsalong with several books such as ian millingtons ai for games which includes a decent rundown of the different learning algorithms used in decision trees and behavioral mathematics for game programming which is basically all about decision trees and theory i understand the concepts for a decision tree along with entropy id3 and a little on how to intertwine a genetic algorithm and have a decision tree decide the nodes for the ga they give good insight but not what i am looking for really i do have some basic code that creates the nodes for the decision tree and i believe i know how to implement actual logic but it is no use if i do not have a purpose to the program or have entropy or a learning algorithm involved what i am asking is can someone help me figure out what i need to do to create this learning decision tree i have my nodes in a class of their own flowing through functions to create the tree but how would i put entropy into this and should it have a class a struct i am not sure how to put it together pseudocode and an idea of where i am going with all this theory and numbers i can put the code together if only i knew what i needed to code any guidance would be appreciated how would i go about this basically adding a learning algorithm such as id3 and entropy how should it be set uponce i do have this figured out on how to go about all thisi plan to implement this into a state machine that goes through different states in a gamesimulation format all of this is already set up i just figure this could be standalone and once i figure it out i can just move it to the other projecthere is the source code i have for now thanks in advancemaincppint main create the new decision tree object decisiontree newtree new decisiontree add root node the very first question or decision to be made is monster health greater than player health newtreecreaterootnode1 add nodes depending on decisions 2nd decision to be made is monster strength greater than player strength newtreeaddnode11 2 3rd decision is the monster closer than home base newtreeaddnode21 3 depending on the weights of all three decisions will return certain node result results run attack newtreeaddnode12 4 newtreeaddnode22 5 newtreeaddnode13 6 newtreeaddnode23 7 others run to base strength surrender monsterplayer needs to be made recursive that way when strength it affects decisions second time around dt thisplay information after creating all the nodes thisplay the entire tree i want to make it look like the actual diagram newtreeoutput askanswer question decision making process newtreequery cout decision made press any key to quit endl pause quit oh wait how did you do that againlook it up and put here release memory delete newtree return random value return 1decision treehthe decision tree classclass decisiontreepublic functions void removenodetreenodes node void thisplaytreetreenodes currentnode void output void query void querytreetreenodes rootnode void addnode1int existingnodeid int newnodeid void addnode2int existingnodeid int newnodeid void createrootnodeint nodeid void makedecisiontreenodes node bool searchaddnode1treenodes currentnode int existingnodeid int newnodeid bool searchaddnode2treenodes currentnode int existingnodeid int newnodeid treenodes m rootnode decisiontree virtual decisiontreedecisionscppint randomint upperlimitfor random variables that will effect decisionsnode valuesweightsint randomint upperlimit int randnum rand upperlimit return randnumconstructorstep 1decisiontreedecisiontree set root node to null on tree creation beginning of tree creation m rootnode nulldestructorfinal step in a sensedecisiontreedecisiontree removenodem rootnodestep 2void decisiontreecreaterootnodeint nodeid create root node with specific id in mo you may want to use thestatic creation of ids like with entities depends on how many nodes you plan to have or have instantaneously created nodeschanging nodes m rootnode new treenodesnodeidstep 51void decisiontreeaddnode1int existingnodeid int newnodeid check to make sure you have a root node cannot add another node without a root node ifm rootnode null cout error no root node return ifsearchaddnode1m rootnode existingnodeid newnodeid cout added node type1 with id newnodeid onto branch level existingnodeid endl else check cout node existingnodeid not found step 61 search and add new node to current nodebool decisiontreesearchaddnode1treenodes currentnode int existingnodeid int newnodeid if there is a node ifcurrentnodem nodeid existingnodeid create the node ifcurrentnodenewbranch1 null currentnodenewbranch1 new treenodesnewnodeid else currentnodenewbranch1 new treenodesnewnodeid return true else try branch if it exists for a third add another one of these too ifcurrentnodenewbranch1 null ifsearchaddnode1currentnodenewbranch1 existingnodeid newnodeid return true else try second branch if it exists ifcurrentnodenewbranch2 null returnsearchaddnode2currentnodenewbranch2 existingnodeid newnodeid else return false return false step 52 does same thing as node 1 if you wanted to have more decisions create a node 3 which would be the same as this maybe with small differencesvoid decisiontreeaddnode2int existingnodeid int newnodeid ifm rootnode null cout error no root node ifsearchaddnode2m rootnode existingnodeid newnodeid cout added node type2 with id newnodeid onto branch level existingnodeid endl else cout node existingnodeid not found step 62 search and add new node to current nodeas stated earlier make one for 3rd node if there was meant to be onebool decisiontreesearchaddnode2treenodes currentnode int existingnodeid int newnodeid ifcurrentnodem nodeid existingnodeid create the node ifcurrentnodenewbranch2 null currentnodenewbranch2 new treenodesnewnodeid else currentnodenewbranch2 new treenodesnewnodeid return true else try branch if it exists ifcurrentnodenewbranch1 null ifsearchaddnode2currentnodenewbranch1 existingnodeid newnodeid return true else try second branch if it exists ifcurrentnodenewbranch2 null returnsearchaddnode2currentnodenewbranch2 existingnodeid newnodeid else return false return false step 11void decisiontreequerytreetreenodes currentnode ifcurrentnodenewbranch1 null if both branches are null tree is at a decision outcome state ifcurrentnodenewbranch2 null output decision question else cout missing branch 1 return ifcurrentnodenewbranch2 null cout missing branch 2 return otherwise test decisions at current node makedecisioncurrentnodestep 10void decisiontreequery querytreem rootnodedebate decisions create new function for decision logic cout nodestringforquestionstep 12void decisiontreemakedecisiontreenodes node should i declare variables here or inside of decisionsh int phealth int mhealth int pstrength int mstrength int thistancefbase int thistancefmonster sets random srandtimenull randomly create the numbers for health strength and thistance for each variable phealth random60 mhealth random60 pstrength random50 mstrength random50 thistancefbase random75 thistancefmonster random75 the decision to be made string example player health monster health player health is lowerhigher cout player health phealth endl cout monster health mhealth endl cout player strength pstrength endl cout monster strength mstrength endl cout thistance player is from base thistancefbase endl cout thisntace player is from monster thistancefmonster endl mh ph mh ph ps ms ps ms db dm db dm good place to break off into different decision nodes not just binary if statement lowerhigher query respective branch ifphealth mhealth else redo question for next branch player strength monster strength player strength is lowerhigher if statement lowerhigher query respective branch ifpstrength mstrength else recursive question for next branch player thistance from basemonster ifthistancefbase thistancefmonster else decision would be made if statement inside query output decision cout querytreenodenewbranch2 makedecisionnodestep8ishvoid decisiontreeoutput take repsective node thisplaytreem rootnodestep 9void decisiontreethisplaytreetreenodes currentnode if it does not exist do not thisplay of course ifcurrentnode null return need to make a string to thisplay for each branch cout node id currentnodem nodeid decision thisplay endl go down branch 1 thisplaytreecurrentnodenewbranch1 go down branch 2 thisplaytreecurrentnodenewbranch2final step at least in this case a way to delete node from tree cannot think of a way to use it yet but i know it is neededvoid decisiontreeremovenodetreenodes node could probably even make it to where you delete a specific node by using it is id ifnode null ifnodenewbranch1 null removenodenodenewbranch1 ifnodenewbranch2 null removenodenodenewbranch2 cout deleting node nodem nodeid endl delete node from memory delete node reset node node null treenodeshusing namespace stdtree node classclass treenodespublic tree node functions treenodesint nodeid string qa treenodes virtual treenodes int m nodeid treenodes newbranch1 treenodes newbranch2treenodescppcontrctortreenodestreenodes newbranch1 null newbranch2 null m nodeid 0deconstructortreenodestreenodes step 3 also step 7 hahtreenodestreenodesint nodeid string nqa create tree node with a specific node id m nodeid nodeid reset nodesmake sure that they are null i wont have any funny business s newbranch1 null newbranch2 null,['c++'] +141769,ruby each with index offset can i define the offset of the index in the each with index loop iteratormy straight forward attempt failedsome arrayeach with indexitem index 1 some funcitem index editclarification i do not want an array offset i want that the index within the each with index does not start from 0 but eg 1,['ruby'] +141776,change value of array element which is being referenced in a each loop how do i get the following to happen i want to change the value of an array element which is being referenced between pipe characters in a each loophere is an example of what i want to do but is not currently workingx whello there worldxeach element ifelement hello element hi change hello to hi puts x output hi there worldit is hard to look up something so general,['ruby'] +141783,logger wrapper best practice i want to use a nlogger in my application maybe in the future i will need to change the logging systemso i want to use a logging facadedo you know any recommendations for existing examples how to write those ones or just give me link to some best practice in this area,"['c#', '.net']" +141784,java is there a way of changing the received http response headers i am using a jaxws generated client using wsimport the one bundled with glassfish 211 to connect to a aspnet generated webservice running in a iis 6when i request compression in the response by including http header acceptencoding gzip through jaxws soap handlers the iis 6 answers with a compressed response but does not includes the contentencoding gzip http response header so i get the following exceptioncomsunxmlwsprotocolsoapmessagecreationexception could not create soap message due to exception xml reader error comsunxmlstreamxmlstreamexception2 parseerror at rowcol11message content is not allowed in prologat comsunxmlwsencodingsoapbindingcodecdecodesoapbindingcodecjava361 at comsunxmlwstransporthttpclienthttptransportpipeprocesshttptransportpipejava173at comsunxmlxwssxwssclientpipeprocessxwssclientpipejava160at comsunxmlwsapipipehelperpipeadapterprocessrequestpipeadapterjava115at comsunxmlwsapipipefiber dorunfiberjava595at comsunxmlwsapipipefiber dorunfiberjava554at comsunxmlwsapipipefiberdorunfiberjava539at comsunxmlwsapipipefiberrunsyncfiberjava436at comsunxmlwsclientstubprocestubjava248at comsunxmlwsclientseiseistubdoproceseistubjava135at comsunxmlwsclientseisyncmethodhandlerinvokesyncmethodhandlerjava109at comsunxmlwsclientseisyncmethodhandlerinvokesyncmethodhandlerjava89at comsunxmlwsclientseiseistubinvokeseistubjava118edited apr 17 2011i have also tried using the same soaphandler i use for requesting compressed response to modify the response headers but the exception occurs before the handler is calledend edit apr 17 2011also when i make the same request to the webservice through soapui 361 with the preference accept compressed responses from hosts i can see what i have said the iis 6 server is not including the http response header for compression and soapui shows the response as binary data and shows these response headershttp11 200 okdate wed 13 apr 2011 085055 gmtserver microsoftiis60xpoweredby aspnetxaspnetversion 2050727cachecontrol private maxage0contenttype textxml charsetutf8contentlength 1104if with soapui i do not request compressed response i get the next response sizecontentlength 2665so the question here is as i have said that iis6 is not adding the contendencoding header in the response my question is is it possible to programmatically add the contentencoding header or it also could be is it possible to ask iis6 to include the contentencoding headerupdateusing charles web debugging proxy 352 i have confirmed the response from iis6 does not include the contentencoding header http11 200 okdate wed 13 apr 2011 105153 gmtserver microsoftiis60xpoweredby aspnetxaspnetversion 2050727cachecontrol private maxage0contenttype textxml charsetutf8contentlength 10i am guessing this may be an issue more related to the webservice than to iis 6,['java'] +141798,a curious string copy function in c when i was reading the nginx code i have seen this function define ngx cpymemdst src n u char memcpydst src n nstatic ngx inline you char ngx copyu char dst you char src size t len if len 17 while len dst src len return dst else return ngx cpymemdst src len it is a simple string copy function but why it tests the length of string and switch to memcpy if the length is 17,['c'] +141838,get all columns from all mysql tables is there a fast way of getting all column names from all tables in mysql without having to list all the tables,['mysql'] +141847,rails migration with adding and removing reference after creating a migration file with rails generate migration addclienttouser i can edit my migration file like soclass addclienttouser activerecordmigration def selfup change table users do t treferences client end end def selfdown change table users do t tremove client id end endendis this the correct way to reverse the reference column added in the migration,['ruby'] +141850,how can i easily compress and decompress files using zlib how can i easily compress and decompress files using zlib,['c++'] +141855,byte to unsigned biginteger motivationi would like to convert hashes md5sha1 etc into decimal integers for the purpose of making barcodes in code128c for simplicity i prefer all the resulting large numbers to be positivei am able to convert byte to biginteger in csample from what i have so farbyte databyte resultbiginteger biresultresult shamcomputehashdatabiresult new bigintegerresultbut rusty cs here am i correct that a byte array can always be interpreted in two ways a as a signed numberb as an unsigned numberis it possible to make an unsigned biginteger from a byte in cshould i simply prepend a 0x00 zero byte to the front of the byteeditthank you to aakashm jon and adam robinson appending a zero byte achieved what i needededit2the main thing i should have done was to read the detailed doc of the bigintegerbyte constructor then i would have seen the sections about how to restrict to positive numbers by appending the zero byte,['c#'] +141871,how do i determine if an array is empty in php i want to check that an array has no values or that the values in the array are empty can someone explain how to do this,['php'] +141891,how does ispostback technically work i am currently having a strange issue whereby all browsers except from google chrome are registering a call to ispostback within a page load event as true when i click an aspnet button which simply posts back to the same pagethis has led me to try and thiscover how the ispostback property within an asp net page is technically implemented something i am struggling to findmy thoughts to date are that it could be related to the followingthe request verb type is post rather than getthe hidden input containing the viewstate information has no information present and therefore no previously submitted control information is availablethe http referer in the request headers is the same as the current urlcan anyone provide an actual breakdown of the conditions used to determine the ispostback boolean propertynote i am looking for the actual implementation rather than perceptions theory as i am hoping to use this to actively resolve an issue i have also searched msdn and to date cannot find any technical article accurately covering the mechanismthanks in advancebrian,['asp.net'] +141899,compiler switch to thisable const cast sematics in cstyle casts recently i stumbled over code such as thisvoid fooconst bar b takes nonconst param fnbarb obviously the developer did not know what he was doing but if the compiler had not silently accepted the cstylecast and at least required a proper const cast he may have though twice before committing thisso this got me thinking do any modern compilers have a switch to prevent const castsemantics for cstylecastsit is simply not practical to prevent all occurrences of cstylecasts and it is a necessary evil to allow their static and reinterpret semantics if only for some library code but my impression is that legitimate usage of cstylecasts to cast away constness is very rare in c code bases so maybe it should be possible to thisable it altogether,['c++'] +141902,returning month name in sql server query using sql server 2008 i have a query that is used to create a view and i am trying to thisplay a months name instead of an integer in my database the datetime is in a column called orderdatetime the lines in the query that return the date isdatenamey s0orderdatetime as orderyeardatepartmonth s0orderdatetime as ordermonththis returns a column of years and a column of months as integers i want to return the month names jan feb etc i have triedconvertvarchar3 datepartmonth s0orderdatetime as ordermonththis is obviously is incorrect as i get incorrect syntax near as message what is the proper syntax for my query,['sql'] +141972,how do i drop table variables in sqlserver should i even do this i have a table variable in a script not a stored procedure two questionshow do i drop the table variable drop table varname gives an incorrect snytax errorshould i always do this i hear it is a good practice is it ever really necessary for small scripts like thisheres my codedeclare projectlist table name varchar40 not nullinsert into projectlistvalues bcr021select from projectlistdrop table projectlist does not work,['sql'] +141984,jquery filter contains for a link a href i have a link that is currentlya href but soon the client will change the link to a hrefsomethingwhen the link becomes something i would like to use jquery to change the css but i am not sure how to write a filter for an attribute href,['jquery'] +141991,java interleaving multiple arrays into a single array i found similar question about interleaving two arraylists into one but its in php i was asked this question in interview as well but couldnt solve it came back to so to look if it was addressed already but i could only find this paperso any pointers to pseudo code or method definition bigo restrictions on time cost and o1 space costexample a a1 a2 an b b1 b2 bn rearrange the arraylist to a1 b1 a2 b2 an bneditv10 arraylists a and b are of same size editv20 what if the question is extended to rearrange in one of given two arrays but not create a new array,['java'] +141999,privately or publicly inherit from boostnon copyable which practice would you recommend and whyclass foo public boostnoncopyable vsclass foo private boostnoncopyable i cannot imagine needing to use an instance of foo as a boostnoncopyable so i am leaning toward private inheritance in this case,['c++'] +142002,plist what it is and how to use it what exactly is a plist file and how would i use it when i view this in xcode it seems to generate some kind of template vs showing me some xml code is there a way that i can extract the data in a plist file by pushing the contents into an array also where can i view the source of the plist,['objective-c'] +142013,sql server 2005 transactional replication fails to publish stored procedure containing an index create i have experienced a bizarre problem with a sql server 2005 transactional publication the issue is this if the publication contains an article that is a stored procedure that contains a create index statement then there is an error thrown when attempting to replicate the schema of the stored procedure to a subscriberthe behavior is very odd because even if the create index statement is commented out it still gives the exception and it will only work if it is removed altogetherhere is the exact error that is being returnedcommand attempted grant execute on dbousp test to companydatabase accesstransaction sequence number 0x01708b9050 command id 5error messages cannot find the object usp test because it does not exist or you do not have permission source mssqlserver error number 15151 get help httphelp15151 cannot find the object usp test because it does not exist or you do not have permission source mssqlserver error number 15151 get help httphelp15151the error is accurate because when i check on the subscriber the stored procedure was not created as expected but that was the purpose of the publicationadditionally i can create the stored procedure manually on the subscriber but when i generate a snapshot it deletes the existing stored procedure and then still returns this error messageand heres a sample publication that creates this issuethe stored procedureuse companydatabasegocreate procedure dbousp testascreate table temptableid intcreate nonclustered index ix temptable on dbotemptableidselect testgogrant execute on dbousp test to companydatabase accessgothe publication script adding the transactional publicationuse companydatabaseexec sp addpublication publication nreplication test description npublication of database companydatabase sync method nconcurrent retention 0 allow push ntrue allow pull ntrue allow anonymous nfalse enabled for internet nfalse snapshot in defaultfolder ntrue compress snapshot nfalse ftp port 21 ftp login nanonymous allow subscription copy nfalse add to active directory nfalse repl freq ncontinuous status nactive independent agent ntrue immediate sync nfalse allow sync tran nfalse autogen sync procs nfalse allow queued tran nfalse allow dts nfalse replicate ddl 1 allow initialize from backup nfalse enabled for p2p nfalse enabled for het sub nfalsego adding the transactional articlesuse companydatabaseexec sp addarticle publication nreplication test article nusp test source owner ndbo source object nusp test type nproc schema only description n creation script n pre creation cmd ndrop schema option 0x04801 destination table nusp test destination owner ndbo status 16go adding the transactional subscriptionsuse companydatabaseexec sp addsubscription publication nreplication test subscriber notherdatabaseserver destination db ncompanydatabase subscription type npull sync type nautomatic article nall update mode nread only subscriber type 0gothe subscription script begin script to be run at subscriber use companydatabaseexec sp addpullsubscription publisher ndatabaseserver publication nreplication test publisher db ncompanydatabase independent agent ntrue subscription type npull description n update mode nread only immediate sync 0exec sp addpullsubscription agent publisher ndatabaseserver publisher db ncompanydatabase publication nreplication test thistributor ndatabaseserver thistributor security mode 1 thistributor login n thistributor password n enabled for syncmgr nfalse frequency type 64 frequency interval 0 frequency relative interval 0 frequency recurrence factor 0 frequency subday 0 frequency subday interval 0 active start time of day 0 active end time of day 235959 active start date 0 active end date 0 alt snapshot folder n working directory n use ftp nfalse job login null job password null publication type 0go end script to be run at subscriber again the odd thing is that the publication will still contain the same error if the create index statement is commented out but it will work if it is removed altogetherfor now i have just removed all stored procedures that contain these create index statements from the publication but i would like to have them replicated to the subscribers so that any ddl updates to the procedures will be automatically reflected on the subscribers edit looking in the snapshot directory the sch file for usp test contains the exact same code block i previously posted for the stored procedure based on the error returned it seems like the snapshot agent decides not to run the create procedure command if it contains a create index but then continues on and tries to run the grant execute command which causes the erroralso my exact version of sql server ismicrosoft sql server 2005 900525400 2005 sp4 cumulative update 1 end edit my question is why is this happening is there an issue with the configuration of my publication or subscription as anyone else experienced anything like this where would i start in troubleshooting this issue update i have been talking to hilary cotter on technet and still no luck if i remove the grant execute permission on the procedure then it creates successfully with the create index so it will work with grant execute or create index but not both hilary suggested that it might be some type of spam appliance in my domain that was preventing the snapshot from being transferred correctly when it contained both of those keywords but if i manually copy the sch file to the subscriber and validate that it contains the expected commands i still get the same issue,['sql'] +142063,how to use shared memory with linux in c i have a bit of an issue with one of my projects i have been trying to find a well documented example of using shared memory with fork but to no successbasically the scenario is that when the user starts the program i need to store two values in shared memory current path which is a char and a file name which is also chardepending on the command arguments a new process is kicked off with fork and that process needs to read and modify the current path variable stored in shared memory while the file name variable is read onlyis there a good tutorial on shared memory with example code if possible that you can direct me tothanksbleepzter,['c'] +142067,remove max and min values from python list of integers i am not completely green to python but i am interested in learningkeeping good practices while i develop my skillsi want to remove the high and low values from a list of numbers which i know how to do but am curious if there is a betterpreferred way to do thismylist 1 4 0 3 2mylistsort 0 1 2 3 4trimmed mylist11 1 2 3i get the desired answer but did i get the right answer appropriately,['python'] +142103,jpa criteria api how to select property in nested collection i have a class customer and customerdependant entities customer has many to many bidirectional relationship with its dependents i need to find customers filtering by name and dependent nameit is done something like this in jpql select c join fetch cdependants d from customer c where cname like foo and dname like foohow i can do the same thing with jpa criteria queriesthank you,['java'] +142138,why should you avoid the then keyword in ruby it is mentioned in several ruby style guides that you should never use then personally i think the then keyword allows you to make code denser which tends to be harder to read is there any other justification for this recommendationedit here is an example of one guide that makes such a recommendation,['ruby'] +142139,free barcode scanner sdk for ios iphone i need a free barcode scanner sdk for iphone 3g and iphone 4 any suggestions it needs to be free,['iphone'] +142157,is there a way to bypass mass assignment protection i have a rails 3 app which json encodes objects in order to store them in a rethis keyvalue storewhen i retrieve the objects i am trying to decode the json and instantiate them from the data like sodef decodejson selfnewactivesupportjsondecodejsonselfnamedowncaseendthe problem is that doing this involves mass assignment which is thisallowed for good reason i am told for attributes i have not given attr writer ability tois there a way i can bypass the mass assignment protection just for this operation only,"['ruby-on-rails', 'ruby']" +142160,what is the difference between servlet response methods addheader and setheader can i use setheader to set an new header or do i need to addheader first then use setheader method,['java'] +142162,what is serialization and deserialization conceptually possible duplicatewhat is object serialization want to get idea behind the serialization and deserialization of objecta simple example would be appreciated,['java'] +142191,javascript to open popup window and thisable parent window i want to open a popup window and thisable the parent window below is the code that i am usingfunction popup popupwindow windowopenchild pagehtmlnamewidth200height200 popupwindowfocusfor some reason the parent window does not get thisabled do i need some additional code or what is the caseagain i am looking for something similar to what we get when we use showmodaldialogie it does not allow to select parent window at allonly thing is i want to get the same thing done using windowopenalso please suggest the code which will be crossbrowser compatible,['javascript'] +142206,how to resolve an error after importing a package in enterprse architect sparx systems everytime i want to change some properties in some class i get the following error messagesmicrosoft cursor engine 2147217864row cannot be located for updating some values may have been changed since it was last readadodbrecordset2146825069operation is not allowed in this contexthow can i solve them,['sql'] +142221,idea for keep information about visited states i making now 15puzzle solver in c but instead of only 15puzzle my program must to solve also 3x4 puzzles 8x8 puzzles etc x x y puzzles i must somehow keep information about visited states my first idea was to make tree for examplepuzzlesstate 1 1 2 3 0 state 2 1 3 0 2i keep in my treeroot1230 302this will work also for puzzle 5x3 6x6 etc for all puzzlesthis idea works but it waste a lot of memory and to add node it need some time so it is very inefficientnext idea was to keep visited states in stls stdmap but i do not know how to make good hash function for making shortcut from puzzle state beacouse i do not must to store puzzle state i need only information has been visited do you have any idea for key to stdmap or other ideas to keep informations about has been state visited,['c++'] +142227,centering 2 divs inside another vertically i have 2 divs that i want to centre vertically inside another div at the moment i havenow i understand what is going on here but i want the left div to be vertically aligned within that container and the right div the same but they are vertically aligning as a pair and not individually i have tried various things but cannot seem to get it work,['css'] +142251,gcd to perform task in main thread i have a callback which might come from any thread when i get this callback then i would like to perform a certain task on the main threaddo i need to check whether i already am on the main thread or is there any penalty by not performing this check befora calling the code belowthispatch asyncthispatch get main queue do work here,['objective-c'] +142269,regexpr advice needed remove all chars from string except of numbers 09 and i need some advice using the regexp objectit should only return numbers and the character from the variable val i am not experienced in the regexp object this is what i got so farvar val gallerystatus inputvalvar regexpr new regexpddgallerystatus inputval only 09 and thanks for any advice,['javascript'] +142286,how to use quartz with quartzinitializerlistener i am having trouble to understand how to use quartz with quartzinitializerlistenerfirst i declare that listener in deployment descriptor but then how to i add my jobs taking a look at quartzinitializerlistener implementation i see it creates the schedulerfactory and scheduler but i do not see any way to add jobs the factory receives a configuration file but again there is nothing related to the jobs therei only found very simples examples from my searches all about instantiating everything in main methodcan anyone point me to a more real example i am using jboss 5 if that matters thanks,['java'] +142294,importerror no module named beautifulsoup i have installed beautifulsoup using easy install and trying to run following scriptfrom beautifulsoup import beautifulsoupimport redoc htmlheadtitlepage titletitlehead bodyp idfirstpara aligncenterthis is paragraph boneb p idsecondpara alignblahthis is paragraph btwob htmlsoup beautifulsoupjoindocprint soupprettifybut not sure why this is happeningtraceback most recent call last file cpython27reading and writing xml file from web1py line 49 in module from beautifulsoup import beautifulsoupimporterror no module named beautifulsoupcould you please helpthanks,['python'] +142329,deploying continuous integration of a symfony 2 application with jenkinshudson i have developed an application which uses the symfony 2 framework the application code resides in a bundle and on my local machine i just downloaded the symfony2 standard thistribution and added the bundle to the src folder as the tutorials describe before editing the config routing files appropriately that is served me well from a development perspectivei am now starting to think about how to handle the framework dependencies with regards to deploying to a production environment a continuous integration setup should i continue as i have to date using a thistribution and perhaps a build tool like phing to check out my bundle and any other dependencies or should i be checking out only the symfony source from github and maintain a custom thistribution for my applicationi am hoping someone else has had to do a similar thing and can recommend a solution that works with minimum fussthanks,['php'] +142339,nsdocument to hold a complete folder i ask sorry if this argument has already been covered but after some research i found nothing precise i need to make a document based application where the document is actually not a single file but a structured collection of files in a directory the windows will show a pdf contained in the folder with a specific filename and enrich it with informations from the other files in the folder i cannot use pdf annotations to achieve this i really need to keep the files separated from the pdfwhats the best approach to achieve this all the sample code i found use a single file,['objective-c'] +142343,android junit test that button has started activity i have a menu with some button which each start an activity i am writing a junit test for this menu and i cannot seem to find out how to test that the button has loaded the correct activity so far i havepublic void testbuttons touchutilsclickviewthis buttonview assertequalscomfgapontracknewsfeedclass getactivityso far i can see that the program loads the correct activity from the emulator but it still fails the junit test,['android'] +142359,aspnet mvc check if user is authorized from javascript i am using aspnet mvc framework 3 and forms authentication i know how to check on servers side if the user is authorized for some action with authorize and i know how to check this within an action or a view with useridentityisauthenticated or other members of userwhat i am trying to do is to define some javascript code that will be executed differently depending if the user is authorizedconsider such script on the pagescript function foo ifuserauthorized alertyoure in the system else alertyoure not authorized scriptfunction foo is triggered by some event say click and i would like to have an ability to check if user is authorized on clients sidethe best solution i have came up with is to actually render global variables initialization in view like thisifuseridentityisauthenticated script var userauthorized true script else script var userauthorized false script but it does not seems to me as a good approach are there any other waysthanks in advanceps this is a usability issue of course i am doing necessary checks on server,['javascript'] +142378,why does not linkedhashmap provide access by index from javadochash table and linked list implementation of the map interface with predictable iteration order this implementation differs from hashmap in that it maintains a doublylinked list running through all of its entries if it is so then why does not it provide object access like list in java listgetindexupdatei had implemented lru cache using linkedhashmap my algorithm required me to access lru object from the cache that is why i required random access but i think that will cost me bad performance so i have changed the logic and i am accessing the lru object just when cache is fullusing removeeldestentrythank you all,['java'] +142392,what type of queue to use in parallel data processing c net 4 scenariodata is received and written to database with timestamps i need to process the raw data in the order that is received based on the time stamp and write it back to the database different table again maintaining the order based on the timestamp i came up with the following design created two queues one for storing raw data from database another for storing processed data before it is written back to db i have two threads one reading to the initial queue and another reading from result queue in between i spawn multiple threads to process data from initial queue and write it to result queuei have experimented with sortedlist manual locking and blockingcollection i have used two approaches to process in parallel parallelforforeach and taskfactorytaskstartnew each unit of data may take variable amount of time to process based on several factors one thread can still be processing the first data point while other threads are done with three or four datapoints each messing up the timestamp orderi have found out about orderingpartitioner recently and i thought it would solve the problem but following msdns example i can see that it is not sorting the underlying collection either may be i need to implement custom partitioner to order my collection of complex data types or may be there is a better way of approaching the problemany suggestions andor links to articles thiscussing similar problem is highly appreciated,['c#'] +142409,simple screen scraping using jquery i have been playing with the idea of using a simple screenscraper using jquery and i am wondering if the following is possiblei have simple html page and am making an attempt if this is possible to grab the contents of all of the list items from another page like somain page jquery script typetextjavascriptdocumentreadyfunctiongetjsonurl to other page functiondata iterate through the li inside of the urls data eachdataitems functionitem livalueappendtodata script html html body div iddatadiv bodyhtmlother pagehtmlbody pbitems to scrapebp ul lii want to scrape what is hereli liand what is hereli liand here as weli liand append it in the main pageli ulbodyso is it possible using jquery to pull all of the list item contents from an external page and append them inside of a div,"['javascript', 'jquery']" +142412,iphone apps that supports url schema do you know how to get information which applications on ios supports url schema from appstore or any wiki resources,"['iphone', 'ios']" +142427,asp mvc3 vs ruby on rails i have mainly developed in the net world but i have a project coming up which needs to really favor the front end lots of ui loveis there value in using to ruby on rails instead of mvc3 how should i go about choosing between the two are there other options worth looking ati know ruby on rails is pretty popular but how does it differ from mvc3,['ruby-on-rails'] +142429,difference between top and limit keyword in sql a quick question suppose i have the following two queriesselect top 2 from personsandselect from persons limit 2i want to know the difference between the execution of the above 2 queriesbasically i want to know when should i use the limit keyword and when it is appropriate to use the top keyword also how does the database return results based on the above 2 queries,['sql'] +142446,ndk how to use a generated so library in another project i have used ndk successfully to build use a so file in one project i need to use this library in another project i would rather not copy the source there but just use the library trying to copy paste the whole libsarmeabilibcommonso to the project root does not work i think because libsarmeabi is an android generated pathso what would be the best way to do iti am using eclipsegalileo ndk5,['android'] +142455,is javascripts double equals always symmetric there are many cases in which javascripts typecoercing equality operator is not transitive for example see javascript equality transitivity is weirdhowever are there any cases in which is not symmetric that is where a b is true and b a is false,['javascript'] +142463,calling threadsleep with interrupted status set the java documentation is not clear on this point what happens if you call interrupt on a thread before it calls threadsleep interrupt reaches thread here try threadsleep30 catch interruptedexception e return will the interruptedexception be thrownedit if you know the answer can you please point me to relevant documentation,['java'] +142473,how do i write nonblocking code in nodejs i can write nonblocking io in nodejs very easily it is what the entire library is set up forbut any computation done is blocking any message passing over event emitters are blockingfor example emitting events are resolved immediately and are thus blockingvar e new processeventemittereonfoo function consolelogeventprocessnexttickfunction consolelognext ticksettimeoutfunction consolelogtimeout 0eemitfoo event next tick timeoutapart from wrapping calls in nexttick how do i make code nonblockingi want to do as little computation per cycle of the event loop as possible so that i can serve as many clients simultaneously as possiblehow do i write my code in a nonblocking fashionand when i have nonblocking code how do i scale that across multiple processesone option is waiting for the webworker subprocess api to be finished,['javascript'] +142519,jquery windowsend to editor could not come up with a good title for thisi have got a build in wordpress where i have multiple image uploads using the built in wordpress media uploader how it is working is after you upload and choose insert jquery is inserting the image path into a text field which contains the id once you save the text field is saved in the options tableworks perfectly if you only have 1 upload field once you add more uploads every upload field gets saved with the same image path just need each upload button to only insert the value for it is associated text fieldi have tried to use each but could not get it working correctly also tried using attrid to the value insert but nothing doing there here is my jquery and the markup jqueryuploadbuttonclickfunction formfield jqueryuploadattrname tb show mediauploadphptypeimageamptb iframetrue return falsewindowsend to editor functionhtml imgurl jqueryimghtmlattrsrc jqueryuploadvalimgurl tb removediv classupload field input typetext nameupload one idupload one classupload value input typebutton classuploadbutton valueupload image divdiv classupload field input typetext nameupload two idupload two classupload value input typebutton classuploadbutton valueupload image divdiv classupload field input typetext nameupload three idupload three classupload value input typebutton classuploadbutton valueupload image divfor further info here is the uploader setup i am using any help as always is greatly appreciated,['jquery'] +142540,trigger events when the window is scrolled to certain positions i would like to call functions when the browser window goes beyond a certain pointeg the user scrolled the window down beyond 200px from the topis there an event i can bind to and then how would i check how much the offset is from the top of the browser to the top of the page,"['javascript', 'jquery']" +142560,how can i extract the mantissa of a double i would like to store in a variable the mantisa of a doublei have post a code to get the binary representation of a double click herewhat should i change to isolate the mantissa,['c++'] +142564,what are user defined runtime attributes in interface builder i cannot seem to find any documentation on this feature at all,['ios'] +142568,mysql connection with phpstorm ide for those of you who are familiar with phpstorm i am using version 201 as writing this questioni am on a mac using mamp i tried to connect my database with phpstorm but it is a bit confusingi went to tools data sourceswhen i press to add and choose db datasourceit wants me to enter a jdbc url to the database the whole time until now i have been using applicationsmamptmpmysqlmysqlsockhow do i get the db to connect with this socket thing the software is amazing but confusing at times,['php'] +142574,downloading a file from spring controllers i have a requirement where i need to download a pdf from the website the pdf needs to be generated within the code which i thought would be a combination of freemarker and a pdf generation framework like itext any better way however my main problem is how do i allow the user to download a file through a spring controller,['java'] +142578,java jtable change cell color i would like to make an editable table and then check the data to make sure its valid im not sure how to change the color of just one cell i would like to get a cell for example 00 and color the foreground to red i have read the other posts on so as well as oracle about the custom colorrenderer but i just do not get how i would use thisthanks,['java'] +142593,jquery flot pie charts show data value instead of percentage i cannot figure out how to get flotpie to change the data shown in the labels from a percentage of the raw data to the actual data in my example i have created a pie chart with the numbers of readunread messages number of read messages 50number of unread messages 150the created pie shows the percentage of read messages as 25 on this spot i want to show the actual 50 messages see image belowthe code i used to create the pievar data label read data 50 color 614e43 label unread data 150 color f5912d and function plotplaceholder data series pie show true radius 1 label show true radius 2 3 formatter function label series return div stylefontsize8pttextaligncenterpadding2pxcolorwhite label br mathroundseriespercent div threshold 01 legend show false is this possiblewith the answer of ryley i came to a dirty solution when i output the seriesdata the values 1150 and 150 were returned i came up with the idea to substract the first 2 characters of the returned value and thisplay the substracted valuestringstrsubstring2 strlenghtthis is the pie chart i created with this solutionthis is not the best solution but it works for me if someone knows a better solution,['jquery'] +142626,efficient python array to numpy array conversion i get a big array image with 12 mpix in the array format from the python standard libsince i want to perform operations on those array i wish to convert it to a numpy arrayi tried the followingimport numpyimport arrayfrom datetime import datetimetest arrayarrayd 0120t datetimenownumpyarraytestprint datetimenow ti get a result between one or two seconds equivalent to a loop in pythonis there a more efficient way of doing this conversion,['python'] +142642,create all combinations of nm values say i have a data structure of ienumerableienumerableobject like this a b 1 2 3 z where the outer array can contain any number of inner arrays and the inner arrays can each independently contain any number of elements and assume for the sake of simplicity that no array will be emptyand i want to transform it to a ienumerableienumerableobject like this a 1 z a 2 z a 3 z b 1 z b 2 z b 3 z which contains every combination of the values from the original structure so each element in each inner array maps by index to an elementarray in the original outer arraywhat is the simplest way to do that in c,['c#'] +142644,php include with get attributes include filephpq1 i want to includerequire a php file located on my server with additional get attributesbut it would not workincludesearchphpq1the error it givesphp warning include failed opening searchphpq1 for inclusionseems like it tries to open a file literally named searchphpq1 instead of opening the searchphp file and sending it the get attributesthank you very muchnote that it does work if i do not put any get attributesincludesearchphp,['php'] +142646,why must the base class be specified before interfaces when declaring a derived class public interface itest int childcount get set public class testpublic class orderpool itest test public int childcount get set the error says base class test must come before any interfaceswhy is it necessary to extend the class first and then implement the inteface,"['c#', '.net']" +142664,android is there a programming way to create a web shortcut on home screen do you know is there a programmatical way to create a web shortcut on the phone users home screenwhat i want to do iswhen the phone user clicks a button in our android application the application will then place a website shortcut onto the phone users home screen,['android'] +142669,can a dbcontext enforce a filter policy i would like to pass a value to the ctor of a dbcontext and then have that value enforce filtering on the related dbsets is this possibleor is there a better approachcode might look like thisclass contact int contactid get set int companyid get set string name get set class contactcontext dbcontext public contactcontextint companyid public dbsetcontact contacts get set using var cc new contactcontext123 would only return contacts where companyid 123 var all from i in contacts select i would automatically set the companyid to 123 var contact new contact name doug contactsaddcontact ccsavechanges would throw custom exception contactcompanyid 456 ccsavechanges,['c#'] +142696,how compilers treat sse or any intrinsic functions a while ago i read somewhere that sse intrinsic functions compile into efficient machine code because compilers treat them differently from ordinary functions i am wandering how actually compilers do it and what c programmers can do to facilitate the process are there any guidelines on how to use intrinsic functions in a manner that makes compilers job of generating efficient machine code easierthanks,"['c++', 'c']" +142705,java why is the date constructor deprecated and what do i use instead i come from the c world so not too experienced with java yet was just told by eclipse that the date was deprecatedperson p new personpsetdateofbirthnew date1985 1 1why and what especially in cases like above should be used instead,['java'] +142706,how to use spring send email with attachment use inputstream the situation is like thisfirst we generate a file in the memorywe can get a inputstream object second the inputstream object must be send as a attachment of a email the language is javawe use spring to send emaili find a lotbut i cannot find how to send email attachment use inputstream i try to do like thisinputstreamsource iss null iss new inputstreamresourcenew fileinputstreamcatxtmimemessagehelper message new mimemessagehelpermimemessage true utf8messageaddattachmentattachment iss1but we the exceptionpassedin resource contains an open stream invalid argument javamail requires an inputstreamsource that creates a fresh stream for every call,['java'] +142721,cssrulesrules are null in chrome my chrome extension needs to modify certain css rules on users page accessing styles via documentstylesheets only gives access to styles linked from within the same domain other elements of documentstylesheets array have cssrulesrules set to nullwhy is it cross domain policy applies here styles are being applied anyway regardless of their origin so what is the point and how to get around it in my caseeditthe reason i need to modify user css rules as opposed to simply adding my own is that i need to protect custom element injected by extension from being affected by rules see details in this question,['css'] +142727,select dropdown menu option with javascript i have a dropdown menu and i cannot figure out how to make a javascript function select a drop down menu option i have tested the output of the variables and they are all correct but it still will not select the option when clicked here is the function and drop down menufunctionfunction formfilla b c theformfromvalue a theformtovalue b forvar i 0i documentgetelementbyidstateselectlengthi ifdocumentgetelementbyidstateselectoptionsivalue c documentgetelementbyidstateselectselected true menu itemselect idstateselect namestateselect option valuenonenoneoption option valuealalabamaoption option valueakalaskaoption,"['javascript', 'html']" +142732,semicolon after the method name in objectivec implementation file void designimageviewnow some code hereis it correct to write semicolon just after the method name before body brackets in the implementation file objectivecwould this workas i am working on an iphone app i put the semicolon after the method name in one of my custom class by mistakenly but there was no warning or any crash in fact it is working fine,"['iphone', 'objective-c']" +142745,it is bad to put tags inside tags only for string manipulation not styling i would like to make groups of the text content of an option tag say i have the following option800 1 houroption the time pattern 800 can be modified then the text in parenthesis 1 hour can also be modifiedi was thinking of doing something like optionspan800spanspan 1 hourspanoptionit is bad to put span tags inside option tags only for string manipulation not styling,['html'] +142758,how does html tags work inside script tag for example viewsource at joel spolskys public career profile script typetexthtml idstackexchangeanswerswidget h3top answersh3 div classanswers divscriptscript typetexthtml idtopanswer div classtopanswer div classtopanswerstats sharedhtmlencodescore div span classtopanswertitlea hrefanswerlink sharedhtmlencodetitle aspan a classaddansweradda br classclear divscriptscript typetexthtml idanswerview div classanswer div classanswerstats sharedhtmlencodesitetolowercasereplace g div clascore strong sharedhtmlencodescore strong div classvotecountvotesdiv div img classanswerlogo src sharedhtmlencodefaviconurl div div classanswercontent span classqqspan div classanswertop a classanswertitle href sharedhtmlencodeanswerlink sharedhtmlencodetitle abr div span classaaspandiv classanswerbody body div div classmorebutton styletextaligncenter clearboth thisplaynonea classmoremoreadiv div divscripthow does html tags work inside script tag andor what kind of technology used for those html tags and template alike codes inside script tags,"['javascript', 'html']" +142760,specifiy the order of the validators in jquery validate plugin i am wondering if it is possible to specify the order in which the validators are runcurrently i wrote a custom validator that check if it is azaz09 to make sure the login validates our rules and a remote validator to make sure that the login is available but currently the remote validator is lauched before my custom validator i would like to launch the remote validator only if the element validates my custom validatorany clue thanks for reading,['jquery'] +142770,how do i manage development and deployment of my website as part of a group i have been reading this site here and there and appears as though you guys have a wonderful communityas for my background i am a sophomore at university familiar with sql c visual basic and some php one of my school projects for the summer term involves building a web application that allows users to log in and schedule specific timeslots over the internet typically i have been the only person working on a project but in this case i will be part of a group since were all relatively new to working as a team i would like to set up source control for my group so were not all working off a shared drive somewhere additionally i would like to make sure that all of us are able to test our changes in some sort of development server that hosts an instance of our websitemy actual question is in regards to the toolset that we should use to achieve this as a group we are most familiar with php and mysql so well end up using that for the code and database i have used svn in the past for my own personal use but my group members are not very familiar with source control well probably stick with something simple like excel for the project management and bug tracking side of things ideally we would like the tools to be free and open sourcehow as a group should we manage the construction of the actual application are there methods out there that i can use that will allow any one of us to move the files to our development machine and keep track of who did it so we do not end up overwriting each others changes if this is not possible one of us will write some scripts to handle it but i would like to avoid building basically a separate software application that will only be used to manage our project another issue i foresee will be updating the database running on the development machine are there any standarthised methods that we can use to manage our sql scripts among the four of usi do not expect a really long winded answer here after all this is our project but any helpful tips would be greatly appreciated once i return from holiday i am looking forward to getting started thanks,"['php', 'mysql']" +142772,what does l do what does this doconst wchar t s ltestif wchar t is two bytes on my machine then why should we tell the compiler that the string should be treated in a way that each element is long ie four bytes in size,"['c++', 'c']" +142780,robustly call a flaky api proper error handling with nethttp i hacked this together as a seemingly robust way to call a flaky webservice that was giving timeouts and the occasional name resolution or socket error or whateveri thought i would put it here in case it is useful or more likely to be told a better way to do thisrequire nethttpretries 5begin url uriparse http nethttpnewurlhost urlport httpread timeout 600 be very patient res nil httpstarthttp req nethttppostnewurlpath reqset form dataparams send a hash of the post parameters res httprequestreq rescue exception should really list all the possible http exceptions sleep 3 retry if retries 1 0end finally do something with resbody like jsonparseresbodythe heart of this question iswhat all exceptions should i be looking for when making a call to a webservice like thisheres an attempt to collect them all but it seems like there is got to be a better way than that,['ruby'] +142794,c remove special characters i want to remove all special characters from a string allowed characters are az uppercase or lowercase numbers 09 underscore white space pecentage or the dot sign i have tried this stringbuilder sb new stringbuilder foreach char c in input if c 0 c 9 c a c z c a c z c c c c sbappendc return sbtostringand this regex r new regexaz09 s regexoptionsignorecase regexoptionscultureinvariant regexoptionscompiled return rreplaceinput stringempty but nothing seems to be working any help will be appreciatedthank you,['c#'] +142797,how to find the highest zindex using jquery i have a number of div elements with different zindex and i want to find the highest zindex among these divs how can i achieve itcsslayer1 zindex 1 layer2 zindex 2 layer3 zindex 3 layer4 zindex 4 htmldiv idlayer1layer1divdiv idlayer2layer2divdiv idlayer3layer3divdiv idlayer4layer4divi do not think this line can find the highest zindex thoughvar index highest parseintdivcsszindex returns 10,"['jquery', 'css']" +142814,add list to a mysql parameter i have this question about the mysqlparameter from the net connectori have this queryselect from table where id in parameterand the mysqlparameter isintarray new listint1234connectioncommandparametersaddwithvalueparameter intarraythis is possibleis possible to pass an array of int to a single mysqlparameterthe other solution will be convert the array of int to a string such like 1234 but this when i pass it to the mysqlparameter and this is recognized as a string it puts in the sql query like 1234 and this do not return the expected values update seems like the mysql connector team should work a little bit harder,"['c#', '.net', 'mysql']" +142817,refresh a table with jqueryajax every 5 seconds so i have a table pulling information from a database and i was wondering how i could make it refresh its information without reloading the whole page,"['php', 'jquery']" +142836,opengles 20 vs opengles 11 which is faster i have written an app using opengles 11 but am wondering if there are speed gains to be found by switching to 20 has anyone done any tests with large polygon count models i only want to render triangles that have different colors nothing fancy however i am wanting to render about 1 million triangles for my comparison test,"['iphone', 'ios']" +142843,job interview test i have a first job interview for a software engineer position but in the email they state that i will have to write out a program at the interview stage does everyone do thiswhat kind of program might it be for a graduatethe job is for a net developer but i can use any language so i will stick with c i am actually sting it i have no clue what they are going to ask me to do,"['c#', 'asp.net', 'html']" +142847,applying operator to generic parameter possible duplicatecanat operator be applied to generic types in c i have a databaselookup class where the parameter t will be used by the lookup methods in the class before lookup i want to see if t was already looked up with something likeif t previouslookupobject this does not compile at all what is preventing me from making a simple comparison like this,"['c#', '.net']" +142862,drawing a line with a certain pixel width i would like to thisplay xy data on a canvas using lines with a certain width in pixels or dp ideally i have tried the setstrokewidth method of paint and that indeed does change the line width but it is not what i need in my case i have scaled my canvas to real engineering units using matrixprescalexscale yscale so the x scale represents 0 to 100 and the y is 0 to 1 the setstrokewidth method of the paint object seems to set the stroke so that it follows my matrix prescale settings in other words horizontal lines are drawn really thin and vertical lines are drawn really thickis there a way to configure the paint so that no matter which direction the line is drawn its width is a consistent number of pixelsi have tried defining a drawable that is a line and making a shapedrawable from that and then applying it to the paint but ran into some nasty class casting errors at run time this made me think that this was the wrong way to go about it but maybe i gave up too sooni understand that are a number of android plottingcharting packages available some with source but i am really looking to understand the platform here rather than using a thirdparty solution thanks for any hintsrich,['android'] +142874,how can you make exception handling fall through multiple catch blocks in a single case let us say you have the following hierarchy you have a base class animal with a bunch of sub classes like cat mouse dog etcnow we have the following scenariovoid ftn throw dogint main try ftn catchdog d some dog specific code catchcat c some cat specific code catchanimal a some generic animal code that i want all exceptions to also run so what i want is that even if a dog is thrown i want the dog catch case to execute and also the animal catch case to execute how do you make this happen,['c++'] +142876,how to use for loop in velocity template i just googled for for loop but it looks like velocity has foreach onlyhow do i use for loop in velocity template,['java'] +142879,how to delete all items from sqlite in android i would like to make an app where the user clicks a button and the sqlite database is cleared heres what i have tried so fardbdeletetable name null nullwhat am i doing wrong,['android'] +142888,can i have multiple not selectors i am trying to select input elements of all types except radio and checkboxmany people have shown that you can put multiple arguments in not but using type does not seem to work anyway i try itform inputnottyperadio typecheckbox css here any ideas,['css'] +142893,finding knearest neighbors for a given vector given that i have the following in my knowledgedatabase1 0 6 20 0 0 6 201 0 3 6 0 0 3 61 0 15 45 0 0 15 451 0 17 44 0 0 17 441 0 2 5 0 0 2 5i want to be able to find the nearest neighbors of the following vector1 0 5 16 0 0 5 16according to a thistance metric so in this case given a particular threshold i should find that the first vector listed is a nearneighbor to the given vector currently the size of my knowledge database is in the order of millions so calculating the thistance metric for each and every point and then comparing is proving expensive are there any alternatives on how to achieve this with a significant speedupi am open to pretty much any approach including using spatial indexes in mysql except that i am not entirely sure on how this problem can be solved or some kind of hashing this would be great but again i am not entirely sure,"['python', 'mysql']" +142907,forcing xcode 4 to compile xib into nib i upgraded an xcode 3 project having three targets to xcode 4 my targets bundles no longer have any nib files only xib files a new xcode 4 project has both at least in the simulator i do not see any difference between the old and the new xcode projects settings to account for this differencehow do i get xcode 4 to compile the xib files and put nibs in my bundle,['iphone'] +142909,silverlight resharper and vs designer cannot deal with staticresource extension basically neither visual studio designer nor resharper seem to deal with the staticresource markup extension when i use it normally without the brackets staticresource resourcekeysomekeyit is not an issue of finding the resource it chokes on the property name of resourcekey so when designer loads or if i use resharpers solution analysis my error windows are always cluttered with endless instances of cannot resolve symbol resourcekeyi am using silverlight 4 with vs2010 but i had this problem with silverlight 3 and 08 too recently reinstalled the whole stack for unrelated reasons problem remainsthis is not a showstopper because everything works fine at runtime and in blend and i turn off vs xaml designer anyhow but it is annoying and most importantly puzzlingdo not know if it is related but when i mouseover the staticresource it tells me that the class is msinternalmetadataexposedtypespresentationstaticresourceextension but i was pretty sure that it lives in the systemwindows namespaceplease overflowers shed some light on this mystery for me,['.net'] +142929,codeigniter 2 uses pdo or php mysql function for it is active record does codeigniter 2 use pdo or php mysql functions for its active record class,"['php', 'mysql']" +142944,how to make an outer class inherited from an inner class how can i make something like this workclass outer int some member abstract class innerbase abstract void method class outerextendsinner extends outerinnerbase outerextendsinnerouter o osuper void method how do i use some member here writing outerthissome member error about outer not being an enclosing class writing just some member nogo either the workaround is to have a method in innerbase that returns outerthis and call that from derived classes but is there another wayi primarily want to extend the innerbase from outside in order to have better codeorganization but i could move all derived classes into outer,['java'] +142956,parallelizing a for loop i have a for loop where the computation at iteration i does not depend on the computations done in the previous iterations i want to parallelize the for loopmy code is in java so that the computation of multiple iterations can be run concurrently on multiple processors should i create a thread for the computation of each iteration ie number of threads to be created is equal to the number of iterationsnumber of iterations are large in the for loop how to do this i am very new to java and implementing multithreading in itprasenjit,['java'] +142964,detect socket hangup without sending or receiving i am writing a tcp server that can take 15 seconds or more to begin generating the body of a response to certain requests some clients like to close the connection at their end if the response takes more than a few seconds to complete since generating the response is very cpuintensive i would prefer to halt the task the instant the client closes the connection at present i do not find this out until i send the first payload and receive various hangup errorshow can i detect that the peer has closed the connection without sending or receiving any data that means for recv that all data remains in the kernel or for send that no data is actually transmitted,"['python', 'c']" +142992,nontype template parameters i understand that the nontype template parameter should be a constant integral expression can someone shed light why is it so template stdstring tempvoid foo error c2993 stdstring illegal type for nontype template parameter tempi understand what a constant integral expression is what are the reasons for not allowing nonconstant types like stdstring as in the above snippet,['c++'] +142993,jquery call ajax every 10 seconds i have a mysql feedback database constructed like thisname location feedbackryan england great supportobviously there is more entries than that i am trying to build a feedback div where it thisplays a new feedback item every 10 seconds via ajaxso i have constructed thisdocumentreadyfunction new get fb function get fbvar feedback ajaxajax type post url feedbackphp async false responsetextend of ajaxdivfeedbackboxhtmlfeedbackdelay10queuefunction new get fb and heres my php fileresult mysql queryselect from feedback order by rand limit 01whilerow mysql fetch arrayresult name rowname location rowlocation feedback rowfeedback echo pname name location location feedback feedbackp however this only shows two it does not keep showing new ones it purely shows the first then the second and stopswhat am i doing wrong thanks,"['php', 'jquery']" +143004,autologin phpmyadmin we want to auto login users in phpmyadmin now we have a webinterface written in php users can login after logging in they can click on the sql link in the menu that opens phpmyadmin is there a way to log them in automatically is it possible to set cookies for phpmyadmin or something to let them use it we do not want to turn off phpmyadmins login each user has his own mysql userpass combination so we need to pass the usernamepassword settings to phpmyadmin,"['php', 'mysql']" +143010,single signon server authentication in rubyrack i write and host web applications on windows servers for intranet usage my server stack uses sinatra which uses rack thin and in some cases apache for reverseproxying onlyi want to support single signon using ntlm or kerberos within our activedirectorybacked domain i have seen that i can use mod ntlm or mod auth kerb when i am behind apache to perform my ntlm authentication i have not tried this yet but i assume it will workmy question is about ntlm or kerberos authentication when i am not behind apache using only thin and sinatra i have seen rackntlm but the usage details there are exceedingly sparseplease provide knownworking code under sinatra or rack that shows how to use ntlm or kerberos on the serverside authenticating with activedirectory presumably via netldapedit emphasized the desired answers as no answers so far come close to providing the explicit help this question is asking for users should be able to find this answer and have a working solution not pointers to external libraries that they must figure out how to use,['ruby'] +143015,can i use white spaces in the name attribute of an html element a question has rised in my project team as we are designing a web pagecan we use white characters like space in the name attribute of an html element eg input typecheckbox namefirst check boxmy concern is mainly the behavior of different browsers with such an attribute valuewe are now in the design phase until we get to write some code and test this a long time will pass so i am asking you experts about thisthank you,['html'] +143037,aspnet mvc dropdownlistfor with model of type list i have a view with a model of type list and i want to place a drop down list on the page that contains all strings from the list as items in the drop down i am new to mvc how would i accomplish thisi tried thismodel liststringhtmldropdownlistforx xbut that threw an error any help is appreciated,['c#'] +143051,difference between ifissetvar and ifvar possible duplicatewhats the difference between ifvariable and ifissetvariable in facebooks php api example they use ifvar do something else do something elsewhick got me thinking about the difference of ifvar and ifissetvar the first sure looks neater but can i surely use it,['php'] +143082,mysql logging in as different user i created a different user when i try to log into mysql it will not let me i think i am missing a step i am using windows 7 when i log in it automatically asks me for a password if i enter the root password i can use mysql if i enter the password i have created for the user i get an error i cannot read and the program exits do i need to first login as root then somehow log in as new user i am very confused the code i used to create the new user is here trouble logging into mysql as non rootthank,['mysql'] +143088,layered service provider in c i am looking to write a lsp in c to capture and redirect udp packets i have little experience with lsps but i have heard they can do this sort of thing please correct me if i am wrong but is this possiblei would love some example code but i will take any information or advice anyone can give on the topic,['c#'] +143107,how to debug systemtypeloadexception errors in net i am getting the following error on one of my referenced assembliescould not load type systemfunc2 from assembly myassembly i will be honest i do not think i can remember the last time i saw a systemtypeloadexception error or if i saw it the solution was obvious my first instinct was to see what msdn had to say about ittypeloadexception is thrown when the common language runtime cannot find the assembly the type within the assembly or cannot load the typeperhaps i am reading this wrong but it is saying that the clr simply cannot find the type that might make more sense if this was not something that was in mscorlib this was all built ontop of net4 with vs2010 so there is no mono or other weird library issues am i over thinking this whats going on,['c#'] +143109,how to completely reset python stdlib logging module in an ipython session i would like to make repeated calls to python scripts using run in an ipython session and for each of those scripts to log based on cmdline arguments passed via runfor example while debugging cmdpy i might over time want to runrun cmdpy logs with default behavior eg to stderr with root level warnrun cmdpy log level debug log file tmpcmdout logs with root level debug to a filerun cmdpy log level errorunfortunately this is difficult because the logging state created by loggingbasicconfig persists after the first run command as is more generally true of all modules and often desirable when using runi realize that in full generality a series of run commands like above will not be the same as running each command in a new process however it would be very convenient if things like the log level and log file could be reinitializedi have tried something like this in cmdpyimport logging config parse logging config from sysargvreloadlogging config reparse cmdline if using run multiple timesand logging configpy does condensedif logging initialized logginggetloggersetlevellvlelse loggingbasicconfiglevellvl logging initialized trueit works for simple cases but not if cmdpy imports libraries that also use logging i have also experimented with loggingshutdown called at conclusion of each cmdpy but that does not seem to help,['python'] +143115,when do we use the operator in rails what is its significance possible duplicatewhat does the operator stands for in ruby i am confused with the usage of operator in rails i could not locate anything useful on the web can anyone please guide medo let me know if there are any weblinks that you are aware ofi would like what the following statement means current user sessioncurrent user id userfindsessioncurrent user id,['ruby'] +143125,conflicting types error when compiling c program using gcc i tried to compile following program with gcc 0 include stdioh1 2 main 34 5 char my string hello there 67 my print my string 8 my print2 my string 910 11 void my print char string12 13 printf the string is sn string 14 15 16 void my print2 char string17 18 char string2 19 int size i 2021 size strlen string 22 string2 char malloc size 12324 for i 0 i size i 25 string2size i stringi2627 string2size1 0 28 printf the string printed backward is sn string2 29 however it fails and the compiler produces following error loggreetingc 11 errorconflicting types for my printgreetingc 7 error previous implicit declaration of my print was heregreetingc 16 errorconflicting types for my print2greetingc8 erroroprevious implicit declaration of my print2 was thereand if i move the my print and my print2 functions before the main function everything goes wellso can anyone explain why the problem happensthanks,['c'] +143127,initialising a struct that contains a vector of itself i have a menu system that i want to initialise from constant data a menuitem can contain as a submenu a vector of menuitems but it only works up to a point here are the bare bones of the probleminclude vectorstruct s stdvectors v s s1 s s2 s s3 g stdc0x version 445 copes with s1 and s2 but s3 comes back withprogcpp622 error template argument 1 is invalidsee ideone am i doing something wrong,['c++'] +143130,navigation property without declaring foreign key all my models contain at least two associations when modeling this in ef4 i have only been able to do this without a second foreign key property through the use of the fluent interface foreignkey seems like the right attribute to use except for the fact that it requires a string parameter so my question is can you have a navigational property and declare it as such using an attributepublic class user iauditable other code public virtual user creator get set public virtual user modifier get set,['c#'] +143138,export datagridview records to excel hey friends i need to export records of datagridview of winform to msexcel i want to do it without using any dll ie with the buid in properties of c so is there any good solution for my problem,"['c#', '.net']" +143153,maximum item size in indexeddb i am working on a simple web utility that makes use of indexeddb similar to a keyvalue db feature of html5i was looking for but i was unable to know what is the maximum size i can store in an item,['javascript'] +143159,how can i create a new directory on the sd card programmatically i want to create a new directory inside the sd card programmatically and i want to delete that directory also how can i do this,['android'] +143168,why is an md5 hash created by python different from one created using echo and md5sum in the shell a python md5 hash is different than the one created by the md5sum command on the shell why import hashlib h hashlibmd5 hupdatemystringforhash print hhexdigest86b6423cb6d211734fc7d81bbc5e11d3 result from python echo mystringforhash md5sum686687dd68c5de717b34569dbfb8d3c3 result on the shell,['python'] +143186,boostfile system how to find out in which directory your executable is so i run my app i need for it to know where its executable is how to find path to it using boost file system,['c++'] +143215,how to get the current firefox profile path from within my applet i am using network security services for java jss by mozilla in my applet in order to allow some lowlevel interaction between my signed java applet and mozilla firefoxone of the first problem i am facing is how to find the current firefox profile path i need it because i have to call the initializestring configdir method of cryptomanager and the socalled configdir has to be the directory of a firefox profilehow can i grab the full path of the current firefox profile is there a clean way or i have to go reading profilesini in appdatafirefox parse it and then choose a random profile hoping it is only one or the one i get is the correct onethanks in advance,['java'] +143216,php regex to ignore escaped quotes within quotes i looked through related questions before posting this and i could not modify any relevant answers to work with my method not good at regexbasically here are my existing linescode preg replace callback array this getphpstring code code preg replace callback array this getphpstring code they both match strings contained between and i need the regex to ignore escaped quotes contained between themselves so data between will ignore and data between will ignore any help would be greatly appreciated,['php'] +143237,how do i store a credit cards expiration date if it only consists of the month and year how do i store a credit cards expiration date if it only consists of the month and yearthe date field in mysql accepts the following format ymmdd an expiration date without a day is not invalid using that formatdo i use varchar instead and does that not prevent me from making calculations to determine when cards expire and what not,['mysql'] +143280,spring autowiring not working hii am using spring 30 with quartz in a scheduler class i have created the application context by private static final classpathxmlapplicationcontext applicationcontextstatic applicationcontext new classpathxmlapplicationcontextconfigapplicationcontextxmlthe problem is that none of the autowired beans actually get autowired so i have to manually set dependencies like this bean classcomsprserviceregistrationserviceimpl idregistrationservice property nameuserservice refuserservice beanexample of where i am using autowired public class registrationservice autowired private userservice userservice setter for userservicepublic class userservice methodsi also made sure to enable the annotation configuration in my spring configcontextannotationconfigbean idregistrationsevice classregistrationservicebean iduserservice classuserservicewhy is autowired not working for me,['java'] +143282,take the average of two signed numbers in c let us say we have x and y and both are signed integers in c how do we find the most accurate mean value between the twoi would prefer a solution that does not take advantage of any machinecompilertoolchain specific workingsthe best i have come up with isa 2 b 2 a 2 b 2 is there a solution that is more accurate faster simplerwhat if we know if one is larger than the other a priorithanksdeditors note please note that the op expects answers that are not subject to integer overflow when input values are close to the maximum absolute bounds of the c int type this was not stated in the original question but is important when giving an answer,['c'] +143288,android out of memory exception when creating bitmap i am getting the following error after creating bitmap second time around0417 182809310 errorandroidruntime3458 javalangoutofmemoryerror bitmap size exceeds vm budgetthis profilebitmap bitmapcreatebitmap profilebitmap xcoor ycoor width heightfrom log0417 182757500 infocameracropview3458 original photo size w 1536 x h 2048 0417 182806170 infocameracropview3458 xcoor 291 0417 182806170 infocameracropview3458 ycoor 430 0417 182806170 infocameracropview3458 width 952 0417 182806170 infocameracropview3458 height 952 since the image is huge i get the error but the interesting thing is the error does not happen the first time only when i take the picture the second time which makes me believe this profilebitmap is not destroyed how do i clean this up,['android'] +143291,why java has a lot of duplicate methods i was playing with java as i am planning to switch from c to it for cross platform purposes i have just noticed that it has a lot of methods that just do the same thing and i just want to know why did they do that an example the boolean class has two methods doing the same thing in addition to the constructor which does the same thing tooboolean b new booleantrueboolean b new booleantrueboolean b booleanparsebooleantrueboolean b booleanparsebooleantrueboolean b booleanvalueoftrueboolean b booleanvalueoftrueand i can get the boolean value either by just calling the variable itself b or the method bbooleanvalue would anyone want to call a method getting the boolean value of a boolean although he can just call the variable itself what is the point,['java'] +143315,how to launch a popupwindow or dialog from an input method service i get the same exception when i try to pop a popupwindow or dialog from inputmethodservicefatal exception mainandroidviewwindowmanagerbadtokenexception unable to add window token null is not valid is your activity running at androidviewviewrootsetviewviewrootjava505 at androidviewwindowmanagerimpladdviewwindowmanagerimpljava177 at androidviewwindowmanagerimpladdviewwindowmanagerimpljava91 at androidwidgetpopupwindowinvokepopuppopupwindowjava828 at androidwidgetpopupwindowshowatlocationpopupwindowjava688 at mypackagemyinputmethodserviceonclickmyinputmethodservicejava123 if i try to pop a dialog instead i get the exact same exception in the exact same line of viewrootjava here is my code abridgedpublic class myinputmethodservice extends inputmethodservice implements viewonclicklistener public void onclickview v this is the handler for viewonclicklistener layoutinflater inflater layoutinflater thisgetsystemservicecontextlayout inflater service popupwindow pw new popupwindowinflaterinflaterlayoutpopup example null false 100 100 true pwshowatlocationminputview gravitycenter 0 0 minputview was previously created and returned by oncreateinputview end of myinputmethodserviceandxml version10 encodingutf8linearlayout xmlnsandroid androidorientationvertical androidpadding10dip androidlayout widthfill parent androidlayout heightwrap content textview androidlayout widthfill parent androidlayout heightwrap content androidlayout margintop10dip androidtexttest popup linearlayouti have tried many variations of the above code but always get the same exception for popupwindows and dialogs for some reason toast alerts work is there a special technique for launching a popupwindow or dialog from a service specifically an inputmethodservice as opposed to an activitythanks in advancebarry,['android'] +143318,detect firefox browser with jquery i facing a problem is my css is have a some bug when firefox is lower than 20i would like to detect the browser to fix my css bugthis is my codedocumentready function if browsermozilla true browserversion 30 imgframemargincssmarginleft35px but this code seem like not workthank for advance,"['jquery', 'css']" +143319,add json package reference new to java i am brand new to java and have always been a c kindofguy that being said i am trying to use the json libraries packages classes java terminology is so damn confusing and am having issues adding them as a referencethese three imports cannot be resolvedimport orgjsonsimplejsonarrayimport orgjsonsimplejsonobjectimport orgjsonsimplejsonvaluei went to jsonorg and downloaded the java libraries but i am not sure what to do with them i have tried to go into project properties and add an external class to no avail i noticed the downloaded folder is full of java files what am i supposed to do with thesesorry to present such a noob question on here but i am stumped,['java'] +143322,google breakpad examples does anyone have any examples of configurations for google breakpad i can build it just fine however there is limited documentation i would like to see examples such as how to modify where crash reports get sent to,['c++'] +143325,php manual gzip encoding i was testing my website with page speed and the result was around 70100 enable compression was the first and most important factor in slowing it downi know that i can do that by modifying the phpini to automatically do that but i was more interested in the manual method gzencode the problem is either all browsers fail in opening the website firefox the page you are trying to view cannot be shown because it uses an invalid or unsupported form of compression chrome 303 err content encoding etc or they thisplay the encoded stringlive headers shows that the browser accepts the encoding and the response has the content type set but it still failsget http11accept texthtmlapplicationxhtmlxmlapplicationxmlq09q08acceptencoding gzipdeflatehttp11 200 okcontentencoding gzipcontentlength 5827vary acceptencodingprivate function compressdata return trimpreg replacearrays ss s array1 data supportsgzip strpos serverhttp accept encoding gzip false ob start if supportsgzip echo gzencodetrimpreg replaces data 9 else echo data content ob get contents headercontenttype texthtml charset utf8 headercachecontrol mustrevalidate offset 60 60 expire expires gmdated d m y his time offset gmt headerexpire headercontentlength strlencontent headervary acceptencoding ob end clean echo contentif i change the contentencoding to zlib i get the encoded stringa1i12i12i12i12i12i12azasawa2oaa a a v iaiajaonaaba2na34aoaalaaiwa eaxa a1aa12oaa a a12tlaa14a ka aa a34i12 a aoaa a6a12aa0za12awa am4ajaxansaf8lrpla2aiaa5a2aama faaj5aara3ai12a3ca12aazaa ba1a ya12acxaida eakv4axa a apa1a ami donat really care anymore about getting the compression as much as i want to know why its not workingcheers,['php'] +143355,how to change bitmap image color in android i am developing an android application in which i set an image to imageview now programmatic i want to change the bitmap image color suppose my image have red color initially and now i need to change it to orange color how can i do that please helphere is my code i managed to change the opacity but i do not know how to change the color override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain imageview iv imageview findviewbyidridimg drawable d getresourcesgetdrawablerdrawablepic1 bitmap mnewbitmap bitmapdrawabledgetbitmap bitmap nnewbitmap adjustopacitymnewbitmap ivsetimagebitmapnnewbitmap private bitmap adjustopacity bitmap bitmap int width bitmapgetwidth int height bitmapgetheight bitmap dest bitmapcreatebitmapwidth height bitmapconfigargb 8 int pixels new intwidth height bitmapgetpixelspixels 0 width 0 0 width height destsetpixelspixels 0 width 0 0 width height return dest,['android'] +143364,what is interlockedincrement actually doing interlockedincrement seems like among the most standardsimple of operations one would need to perform in multithreaded codei assume that the functionality of the method is some sort pattern that anyone with threading experience would be able to replicateso basically what i am wondering is if someone could provide an exact duplicate with explanation of how it works of what the interlockedincrement method is actually doing internally i have looked for the source of the actual method but been unable to find it,['c#'] +143368,php stdclass access fields as field or field i am working on this php code collaboration and it seems that some people access php stdclass fields like this bodyheadand others like bodyheadas far as i can tell these are equivalent are they does it matter which is used which way would you prefer any quirks to look out for here,['php'] +143388,android inapp purchase presently i am developing one application in androidi want to implement in app purchase in my app when i click a buttonplease help me with simple example to implementing in app purchase for our appthanks in advance,['android'] +143403,how to use tamil font in android this is my tamil utf8 unicode string u00e0u00aeu009cu00e0u00afu0086u00e0u00aeu00a9u00e0u00aeu00bfu00e0u00aeu00b2u00e0u00aeu00bfu00e0u00aeu00afu00e0u00aeu00be u00e0u00aeu00aau00e0u00afu0081u00e0u00aeu0095u00e0u00afu0088u00e0u00aeu00aau00e0u00afu008du00e0u00aeu00aau00e0u00aeu009fu00e0u00aeu00aeu00e0u00afu008di want to decode it and thisplay the tamil fontin android is this posiblehow to do please help me,['android'] +143406,getting the warning cast to pointer from integer of different size from the following code the code is pushsize pointergetcari term null 0 1here is the c code push returns abc which is typedef pointer abc typedef void pointer abc size pushabcpointer xyz getcarint typedef struct xyz xyz xyz term null long int iwhat is the reason for the particular warning,['c'] +143412,how to find vertical scrollbar width of a scrollviewer in c i have a scrollviewer and in that i am showing the vertical scrollbar now on changing resolution of the system i want to get the width of the scrollbar i went through one stackoverflow post there they mention to check for systemparametersscrollwidth property but again i din find any help from their can anybody please help me to fix my issue any answer will be appreciated,['c#'] +143413,whats semantically correct way to break headings into lines simple questioni think do not know why that using br is kinda badh1mybrmultiline header notice only firstbrline contains short wordh1is there other suggestionsupdatethe case is one of the lines will be extra shorter then others,['html'] +143420,fixed position div always appear on top i have a fixed position tag that is styled as follows within my cssfacebook height 249pxwidth 50pxposition fixedleft 0pxtop 200pxthere is a flash swf header image on my website and when the resolution of the browser is low enough the facebook div is partially hidden by the flash headerhere is my html body idindex div idfacebookimg srcimagesfacebookpng width50 height249 border0 usemapmap map namemap idmap area shaperect coords215440191 href area shaperect coords320239240 href map div div idwrapper a div idtitle boxobject typeapplicationxshockwaveflash dataimagesflashswf width960 height450 param namemovie valueimagesflashswf img srcimagesheaderjpg objectdivhow do i get it so my facebook fixed position div is always thisplayed on top of this swf contentthanks in advancejon,"['css', 'html']" +143422,whats the most reliable way to prohibit a copy constructor in c sometimes it is necessary to prohibit a copy constructor in a c class so that class becomes noncopyable of course operator should be prohibited at the same timeso far i have seen two ways to do that way 1 is to declare the method private and give it no implementationclass class useful stuff thenprivate class const class not implemented anywhere void operator const class not implemented anywhereway 2 is to declare the method private and give it empty implementationclass class useful stuff thenprivate class const class void operator const class imo the first one is better even if there is some unexpected reason that leads to the copy constructor being called from the same class member function therell be a linker error later on in the second case this scenario will be left unnoticed until the runtimeare there any serious drawbacks in the first method whats a better way if any and why,['c++'] +143436,xml namespaces and xpath i have an application that has to load xml document and output nodes depending on xpathsuppose i start with a document like thisa many nodes here btextb many nodes here btextb many nodes hereawith xpath bso far everything is niceand selection docselectnodesb returns the list of required nodesthen someone uploads a document with one node like myfancynamespacefoo and extra namespace in the root tag and everything breakswhy b does not give a damn about myfancynamespace theoretically it should even be good with myfancynamespacefoo as there is no ambiguity but the expression returns 0 results and that is itis there a workaround for this behaviori do have a namespace manager for the document and i am passing it to the xpath query but the namespaces and the prefixes are unknown to me so i cannot add them before the querydo i have to preparse the document to fill the namespace manager before i do any selections why on earth such behavior it just does not make senseediti am usingxmldocument and xmlnamespacemanageredit2xmldocument doc new xmldocumentdocxmlresolver nullxmlnamespacemanager nsmgr new xmlnamespacemanagerdocnametablei wish i couldnsmgraddnamespacemagic httpmagicnamespaceuridocloadxmlusersuppliedxmlxmlnodelist nodes docselectnodesusersuppliedxpath nsmgrusersuppliedxpath bnodescount should be 0 but with namespaced document they are 0edit3found an article which describes the actual scenario of the issue with one workaround but not very pretty workaround almost seems that stripping the xmlns is the way to go,['c#'] +143462,saving arraylists in sqlite databases so i want to save an ordered set of double values and i want to be able to insert retrieve or delete any value from this easily as of such i am using a an arraylist where i define a class called doubles to store the double valueshow do i store this arraylist in a record in an sqlite database i meanwhat should the columns type be can it be done,['android'] +143469,my eclipse adb server did not ack failed to start daemon after updating the sdk my eclipse shows this error adb server did not ack failed to start daemon when i run an android application it gives me the followingplease ensure that adb is correctly located at dandroidsdkwindowsplatformtoolsadbexe and can be executedhelp me please,['android'] +143482,how to format a timespan for hours not days the following code consolewriteline0h hours 0m minutes new timespantimespanticksperdayproduces this output0 hours 0 minuteswhat i would like is this output24 hours 0 minuteswhat am i missing in this format stringps i know that i could manually bust up the timespan into days and hours and multiply the two but would rather use a custom format string as these timespans are being thisplayed in a silverlight datagrid and people are expecting to see horus not days,['c#'] +143489,python generator vs callback function i have a class that solves an exact cover problem using a recursive backtracking algorithm originally i implemented the class with a callback function i passed to the object during initialization this callback is invoked whenever a solution is found in looking at someone elses implementation of the same problem i saw that they were using yield statements to pass a solution out in other words their code was a python generator i thought this was an interesting idea so i made a new version of my class to use yields i then ran comparison tests between the two versions and to my surprise i found the generator version ran 5 times slower than the callback version note that except for switching in a yield for a callback the code is identicalwhat is going on here i am speculating that because a generator needs to save state information before yielding and then restore that state when restarting at the next call it is this saverestore that is what makes the generator version run so much slower if this is the case how much state information is the generator having to save and restoreany ideas from the python expertsedited 740 pdthere is the solver code which uses yield replace the first yield below with a call to the callback function and change the following loop with the second yield to just a recursive call to solve for the original version of this code def solveself for tp in selfpieces if selfinusetpname continue selfinusetpname true while tpnext orientation is not none if tpinsert piece selfn trials 1 selfpieces in 1 selffree cells tpsize if selfpieces in lenselfpieces or selffree cells 0 selfsolutions 1 selfhavesolution true yield true selfhavesolution false else selftablenext base square for tf in selfsolve yield tf tpremove piece selfpieces in 1 selftableset base squaretpbase square selffree cells tpsize selfinusetpname false tpreset orientationthe mail loop which invokes the solver after initialization of course is start time timetime for tf in ssolve printits end time timetime delta time end time start timein the callback version the loop is gone with just a single call to solve,['python'] +143496,how can i package the whole python interpreter in an android apk i know about sl4a and how i can run python scripts in androidi need to know how i can package the whole python interpreter inside my apk so my endusers would not have to download and install sl4a before running my appthanks,"['android', 'python']" +143503,waiting for localhost forever i have a gridview on my homepage with a view and an edit link that use query strings to thisplay table data in readonly and editable pages respectively i get no error messages from my code it is simple enough that it does not seem to be missing anything but when i try to debug or view in browser i get the permanent pinwheel on my status bar and the message waiting for localhost what am i missing does anyone out there have some experience with this particular issue i am using c and aspnet in visual studios with sql server 2008,"['c#', 'asp.net']" +143532,stackwalk64 on windows get symbol name alright second question on so in one day looks like windows programming makes me happy si am currently trying to get the function call stack on a win32 executablethis morning i have also asked a question about thiswin32 backtrace from c codenow i am pretty sure that the stackwalk64 function is the key for thisi have read some articles on how to use it as well as the ms documentationit actually thisplays frames on my test program so it kinda workthe problem is that i am not able to retrieve the symbol name from the stack informationsi am using the symgetsymfromaddr64 function for this with undecoratesymbolname but i only get junk charactersheres my code hope its not to messy as i am not used to windows programmingvoid printstack void bool result handle process handle thread context context stackframe64 stack ulong frame imagehlp symbol64 symbol dword64 thisplacement char name 256 rtlcapturecontext context memset stack 0 sizeof stackframe64 process getcurrentprocess thread getcurrentthread thisplacement 0 stackaddrpcoffset contexteip stackaddrpcmode addrmodeflat stackaddrstackoffset contextesp stackaddrstackmode addrmodeflat stackaddrframeoffset contextebp stackaddrframemode addrmodeflat for frame 0 frame result stackwalk64 image file machine i386 process thread stack context null symfunctiontableaccess64 symgetmodulebase64 null symbolsizeofstruct sizeof imagehlp symbol64 symbolmaxnamelength 255 symgetsymfromaddr64 process ulong64 stackaddrpcoffset thisplacement symbol undecoratesymbolname symbolname pstr name 256 undname complete printf frame lun symbol name sn pc address 0x08lxn stack address 0x08lxn frame address 0x08lxn n frame symbolname ulong64 stackaddrpcoffset ulong64 stackaddrstackoffset ulong64 stackaddrframeoffset if result break the actual output isframe 0 symbol name a a a a a a a a a a a a pc address 0x00ba2763 stack address 0x0 frame address 0x0031f7e8frame 1 symbol name a a a a a a a a a a a a ao pc address 0x00bb4f stack address 0x0 frame address 0x0031f940frame 2 symbol name a a a a a a a a a a a a a pc address 0x00bb4e2f stack address 0x0 frame address 0x0031f990frame 3 symbol name a a a a a a a a a a a a a pc address 0x75be3677 stack address 0x0 frame address 0x0031f998frame 4 symbol name a a a a a a a a a a a a a pc address 0x770f9d72 stack address 0x0 frame address 0x0031f9a4frame 5 symbol name a a a a a a a a a a a a a pc address 0x770f9d45 stack address 0x0 frame address 0x0031f9e4frame 6 symbol name a a a a a a a a a a a a a pc address 0x770f9d45 stack address 0x0 frame address 0x0031f9e4seems weird that the stack address is always 0 by the way any help appreciated thanks to everyoneediti am looking for a plain c solution without third party libraries,['c'] +143540,appending an item to a jquery ui autocomplete currently i am using jquery ui autocomplete on a textbox that references an ashx file everything is working propertly except i want to append an item at the end of the list that reads item not found click here to request to add a new item i tried the following the lines of code but all it did was format the items i was unable to appenddata catcomplete renderitem function ul item return lili data itemcatcomplete item append a classuimenuitema text itemlabel appendto ullastautocompletecategory hints tips mucho gracias d,['jquery'] +143584,customizing contenteditable behavior with javascript currently under firefox when i press return in a contenteditable paragraph it inserts a br tag creates a new paragraph tag and then puts a br tag inside that new paragraph i would like to modify the behavior such that shiftenter br tag this is already the defaultenter duplicates the current element be it plih1etc and removes any trailing or leading the w3c specification require some events that i could use but i am not at all sure how implement thembackspace at the beginning of an element will merge it with the preceeding sibling if it existsdelete at the end of an element will merge it with the following sibling if it existsi have tried trapping keypress and checking for the return delete and backspace keys but i cannot seem to get the current caret position accurately or to prevent the default behavior if i am overriding iti would find it most helpful if anyone out there knows how toget andor set the current caret position in a contenteditable paragraphprevent the default behavior of contenteditableattach the events required by the w3c recommendation perhaps someone even knows of a user agent browser that already behaves in this way that is acceptable thanksdaniel,"['javascript', 'jquery']" +143585,cut off text in a div if it exceeds set width on a website i am working on users can add a heading to a section of a pagea simple examplem11001 loss of container and goods from manchesterwith some headings the content can be quite indepth in reality for the heading at least this content is not always needed the first few words would suffice to differentiate between records i could just set overflowhidden to the div and ruthlessly cut of anything outside of the set width i would prefer to add to the end like som11001 loss of containerso three fullstops would be added after either x width or x characters is this possible with css or maybe javascript,"['javascript', 'css', 'html']" +143596,jquery datepicker restrict date selection based on week day is it possible to make modify jquery ui datepicker to only allow users to select for example mondays,"['javascript', 'jquery']" +143612,llvm vs clang on os x i have a question concerning llvm clang and gcc on os x what is the difference between the llvmgcc 42 llvm 20 and clang i know that they all build on llvm but how are they different besides faster compiling what is the advantage of llvm over gcc,"['c++', 'c']" +143622,how do you draw text in directx 11 in directx 10 you could use the font interface provided by d3dx10 in directx 11 you are supposed to use directwrite but it looks like directwrite does not speak natively to direct3d is there something basic i am missing how do you draw simple text with directx 11,['c++'] +143624,reasoning for making a method final sorry quick question here just found something in my notes i do not understand in relation to making a method final my notes claim you should make a method final for this reason makes it impossible to enforce invariantsa string should behave as a stringi do not really understand what is meant by this can someone please break it down for me thanks a lot,['java'] +143645,submit a form in a new tab i would like just to test some functions after i will avoid this behaviour to load the page called by submit on a new tab is it possible,"['php', 'jquery']" +143648,communication between c and qml this page shows how to call c functions from within qmlwhat i want to do is change the image on a button via a c function trigger a statechange or however it is donehow can i achieve thisupdatei tried the approach by radon but immediately when i insert this line qobject test dynamic castqobject viewerrootobjectcompiler complains like this error cannot dynamic cast qmlcppbinderthisqmlcppbinderviewerqdeclarativeviewrootobject of type struct qgraphicsobject to type class qobject source is a pointer to incomplete typein case it is relevant qmlcppbinder is a class that i try to build to encapsulate the connections from several qml pages to c code which seems to be trickier than one might expecthere is a skeleton class to give some context for this class qmlcppbinder public qobject q object public qdeclarativeview viewer qmlcppbinder viewersetsourcequrlqmlconnectmainqml viewershowfullscreen error qobject test dynamic castqobject viewerrootobject,['c++'] +143664,openxml file download without temporary file is there a way of providing a download in an aspnet page for a freshly generated openxml docx file without saving it in a temporary folderon msdn i only found a tutorial for using a temp file but i thought about using the wordprocessingdocumentmaindocumentpartgetstream and directly writing the stream out,"['c#', 'asp.net']" +143665,how to rotate a wpf window is it possible to rotate a wpf window by 45 degree using xaml,"['c#', '.net']" +143666,w3schools jquery quiz there is a jquery quiz posted on the w3schools site herequestion 19 is as follows look at the following jquery selector divintro headwhat does it selecta the first element with idhead inside any div element with classintrob all elements with classhead inside the first div element with idintroc all div elements with idintro or classheadi got it correct by picking answer bmy question has to do with the wording of answer bshould not the word first be removed from the answerb all elements with classhead inside the div element with idintroid is defined as a unique identifier to an element so not really understanding why they would refer to the the first div element with idintroi do not believe that it is intentionally trying to be tricky as all the other questions in this quiz are very straightforwardthankyou for your thoughtsediti reported this error to w3schools and directed them to this threadedit 2this is another question from the same quizanother questionable jquery quiz answer at w3schools,['jquery'] +143692,fastcgi scgi i am writing a web server in c and i need to figure out a way to use cgi to execute dynamic content serversidei am looking at the fastcgi protocol and it looks annoying it reminds me of the bit twiddling i had to do in a class when i was converting ascii to utf8 and back that seemed useless then but maybe it was noti found a great library written in php where i could just start up phpcgi b localhost8 and start communicating with it obviously i would like that in ci would appreciate it if someone could find a library for fastcgi clients if not then i am fine with contributing to the open source community by writing onealso how exactly do i use scgi there is barely any documentation on it that i can find anyway what socket do i connect to where do i send the requestsalso phpcgi is only for php so how do things work for perl python etcthanks again,"['php', 'c']" +143693,how to get rid of opensslsslsslerror i am trying to authenticate users with facebook using omniauth initially it was working but along the way it just stopped working and started to give me this error messageopensslsslsslerror ssl connect returned1 errno0 statesslv3 read server certificate b certificate verify failedthe same code works well for twitter and i cannot seem to understand why it does not work for facebook i have looked online for help but i have not been successful this is the link to the website i am building and this url would give you the error message,['ruby-on-rails'] +143698,what happens when the following code executes ball ball ball alloc init autorelease autorelease what happens when the following code executesball ball ball alloc init autorelease autorelease,"['iphone', 'objective-c']" +143723,interview java equals i was asked this question in interview which of the following is better to use myinputequalssomething orsomethingequalsmyinputthanks,['java'] +143727,how can javascript be prevented from accessing php cookie data taken from a job interviewwhich of the following answers are correct use the httponly parameter when setting the cookiethe user must turn off javascript supportit is a cookie setting in the browseronly the issuing domain can access the cookieone is on the client and the other is on the server so it is not an issue,"['php', 'javascript']" +143753,installing rubymine on ubuntu i am new to ubuntu and installed rubymine as they say on site after installation i did not find any app shortcut or new files so for now i am running the using the same script i wrote to install it and i really do not like it the files are in my downloads folderwhat to do,['ruby-on-rails'] +143767,how to equally thistribute columns width in html table when the number of them is unknown i am working with jsficefaces and i need to generate a table from a dynamic tree structure with an unknown at runtime number of rows and columns the table must have width 100 so it occupies all the space inside its containeri am able to generate all the markup required for the table but i found that the cells width is not the sameit would be easy for me to set css width 100numberofcolumns if i knew the number of elements i am rendering unfortunately i cannot modify the classes returned by my backing bean so i can only iterate over them with uirepeater componentdo you know if there is a css way to make sure that all columns in a table have the same width no matter what it isi wouldnt like to use the javascript way just as cleaner code as possible,"['html', 'css']" +143772,mysql auto increment column increments by a random value today i have encountered one of the strangest things with mysql i have seeni have a trivial tablecreate table features feature id mediumint6 unsigned not null auto increment feature name varchar100 character set latin1 collate latin1 general cs not null primary key feature id unique key feature name key feature name engineinnodb auto increment1 default charsetlatin1 collatelatin1 general cii am inserting data inside with java and mysqlconnectorjava5115 librarydata in feature name may duplicate and i want just unique values i may use insert ignore but in case data is too long i may overlook it so i use thispstmt connpreparestatement insert into features feature name values for string featurename data4dbkeyset pstmtsetstring1 featurename try pstmtexecuteupdate catch sqlexception se if segeterrorcode 1062 duplicate entry continue ignore throw se do not ignore anything else after data has been inserted into db i have noticed that there were some problems i have not even expected there are roughly 40 records in above table which is ok the only problem is that some data could not be inserted due to duplicate primary key so i have looked inside how auto inc values look like for this table it turns out that for most of data next adjacent rows id was incremented by 1 as expected for reason i do not know sometimes feature id was incremented by 3 5 10 10 completely random value hence i have run out of place in this table since it could not be inserted once id reached max val for medium inthow can this happenhas anyone encountered sth similarit is worth to say there was only one program with one thread writing to this tablei have one more table almost identical column widths and names are different for this one there is similar problembtw some more datamysql show global variables like auto inc variable name value auto increment increment 1 auto increment offset 1 2 rows in set 001 secmysql show global variables like ver variable name value version 5510 version comment mysql community server gpl version compile machine x86 version compile os win32 thank you for any hints in advance,"['mysql', 'sql']" +143795,gettextbounds in android we used to find the rectangle which fits the given text for example if give testing in gettextbounds api it will give a rectangle that fits the given string testing but could any plz clarify on which basis the rectangle length is calculated whether the font size will be considered if so is it possible for me to check like this 1 way i tried charsequence text gettext canvasdrawtexttext 0 textlength mtextx mtexty getpaint paint pt new paint ptsettextsize10 textpaint tp getpaint string string haa rect currentbounds new rect thissettextsize typedvaluecomplex unit px 10 fontpixelsizehomefltfontratio 32 tpgettextboundsstring text 0 textlength currentbounds loge desired text text loge first ondraw left currentboundsleft loge ondraw top currentboundstop loge ondraw right currentboundsright loge ondraw bottom currentboundsbottom ptsettextsize20 tpgettextboundsstring text 0 textlength currentbounds loge desired text text loge second ondraw left currentboundsleft loge ondraw top currentboundstop loge ondraw right currentboundsright loge nrace ondraw bottom currentboundsbottom2 second way i tried textpaint tp getpaint string string haa rect currentbounds new rect thissettextsize typedvaluecomplex unit px 10 fontpixelsizehomefltfontratio 32 tpgettextboundsstring 0 stringlength currentbounds loge first left currentboundsleft loge top currentboundstop loge right currentboundsright loge bottom currentboundsbottom thissettextsize typedvaluecomplex unit px 10 fontpixelsizehomefltfontratio 10 tpgettextboundsstring 0 stringlength currentbounds loge sefond left currentboundsleft loge top currentboundstop loge right currentboundsright loge bottom currentboundsbottomin the above two methods am trying to find out the various rectangle size for the given text size if this is not a good way plz advise me by posting some sample codes simply to say i have to find the various rectangle which fits the text testing for various font sizethanks in advance,['android'] +143802,should i use the initializer list or perform assignments in my c constructors class nodepublic node parent used during the search to record the parent of successor nodes node child used after the search for the application to view the search in reverse float g cost of this node it is predecessors float h heuristic estimate of thistance to goal float f sum of cumulative cost of predecessors and self and heuristic node parent 0 child 0 g 00f h 00f f 00f userstate m userstatewhy we should use the constructor node parent 0 child 0 g 00f h 00f f 00f instead of node parent null child null g 00f h 00f f 00f thanks,['c++'] +143812,python how to pass more than one argument to the property getter consider the following exampleclass a property def xself return 5so of course calling the a a ax will return 5but imagine that you want to be able to modify the property xthis way for exampleclass a property def xself neg false return 5 if not neg else 5and call it with a a axnegtruethat will raise a typeerror int object is not callable that is quite normal since our x is evaluated as 5so i would like to know how one can pass more then one argument to the property getter if it is possible at all,['python'] +143826,what are the pros and cons of output buffering i have read on many websites that using ob start can enhance your page load times as it stores the php in a variable and thisplays it in one go rather than processing the php a bit of a timealso it is extremely useful forheaderlocation some people say that this is spaghetti code but as long as the code is clear and concise to any programmer then this should not be a problem rightwhat are your thoughts to using it and what do you set as your output buffering are there pros and cons to how when and why i should or should not use it,['php'] +143829,what happens in the kernel during malloc i was asked this question during an interview what they wanted to know was when the user calls malloc4 to allocate 4 bytes of memory how does the operating system linux respond which subsystem responds to this system call i told him that malloc will be serviced by the memory management subsystem the malloc implementation will go through the list of free memoryphysical memory we will call it free list and find an appropriate chunk that is greater than or equal to 4 bytes once it finds such a chunk it will be deleted from free list and added to a used list then that physical memory will be mapped to the process heap vma struct he did not seem to be quite satisfied with this answerhow does the buddy system fit into this any help would be greatly appreciated,['c'] +143835,yield return inside usings if i recall correctly that when i used yield inside using sqlconnection blocks i got runtime exceptionsusing var connection new sqlconnectionconnectionstring var command new sqlcommandquerystring connection connectionopen sqldatareader reader commandexecutereader call read before accessing data while readerread yield reader0 call close when done reading readerclosethose problems were solved when i replaced yield by a list where i added items each iterationthe same problem did not happen yet to me when inside using streamreader blocksusing var streamreader new streamreaderfilename string line while line streamreaderreadline null yield return line is there any explanation why exceptions happened in the former case and not in the latter is this construction advisableedit to get the error early thisposal that i did in the past you should call the first method belowienumerablestring readstring filename using var streamreader new streamreaderfilename return readstreamreader thispose will be executed before readline because of deffered executionienumerablestring readstreamreader streamreader string line while line streamreaderreadline null yield return line the same error can be achieved with other ways of deferring execution such as systemlinqenumerableselect,"['c#', '.net']" +143836,how to set border on jpanel my projects constists of two classes goboard extends jpanelgotestjavaimport javaxswingimport javaawtgraphicsimport javaioimport javaawtimport javaxswingborderborderimport javaxswingborderlineborderclass gotest private static void initgui jframe frame new jframegoboard goboard jboard new goboard jboardsetlayoutnew borderlayout1010 jboardsetborderborderfactorycreateemptyborder0101010 frameaddjboard framesetdefaultcloseoperationjframeexit on close framesetsize400 400 framepack framesetvisibletrue public static void mainstring args javaxswingswingutilitiesinvokelaternew runnable public void run initgui goboardjavaimport javaxswingimport javaawtgraphicsimport javaxswingborderborderclass goboard extends jpanel private int linien public goboard this9 public goboardint plinien thislinien plinien thissetborderborderfactorycreateemptyborder0101010 public void paintcomponentgraphics g superpaintcomponentg int d 0 int h 0 forint i 0 i thislinien i gdrawline0h getwidth h gdrawlined0dgetheight h getheightthislinien d getwidththislinien i want to set a border to have padding according to the frame where i thisplay the panelhowever i get no border any idea,['java'] +143853,string datatype in java i was wondering why is it string and not string when all other primitive data types are lowercase,['java'] +143860,double checked locking in android according to many the somewhat common doublechecked locking idiom is broken for java unless youre running 15 or later and use the volatile keyworda broken doublechecked lock sample broken multithreaded version doublechecked locking idiomclass foo private helper helper null public helper gethelper if helper null synchronizedthis if helper null helper new helper return helper other functions and members the sample comes from this article which also provides details on how to fix itpughs analysis above is for java vms i work on android and frequently use libraries that employ doublechecked locking does the dalvik vms memory model support this idiom,"['java', 'android']" +143867,best practice to implement business logic validation entity framework i am using entity framework for the first time and i need to add business logic before inserting new objects into the db here are the options i thought aboutimplement business logic on the datacontext level by overriding savechanges methodimplement business logic for each entity using onpropertychanging partial methodwrap the generated code in a custom class that implement the validation layerwhich method is best practice when managing business logic on entity framework,['c#'] +143878,how to change the cursor to default on loading i have the following code to change the cursor when a hyperlink is clicked aclickfunction csscursor progress when a link is clicked the cursor changes to progress ie wait cursor exactly as expected however the problem is that the cursor remains progress after a new page is loaded it changes to default only after the mouse moves this is related to another question others expressed the same problemas described by the title i hope to change the cursor to default when a page is loaded,"['jquery', 'css']" +143881,find which of a users tweets were favorited if i understand correctly twitter only lets you check which tweets a user favorited and not which of his tweets were favorited by other users eg sites like favstarfm offer that i wonder howseems unreasonable to crawl all the users favorites to cross them to favorited of a certain user even if you crawl only the friends of that userupdate favstar know of new favorited tweets in real time it seems unlikely they crawl all of your friends to get that,['php'] +143886,how to scale view viewgroup animate layout in a proper way in a few words i want to scale view in the same way that android market does it when you click the more button on the for examplae description i figure it out that the android market has the layout of following structure framelayout androidididartists frame androidlayout widthfill parent androidlayout height64dip androidlayout belowidsomething1 androidlayout aboveidsomething2 some view there which height 64dip framelayoutso i have tried various animations layoutanimations on the framelayout via viewsetanimation viewsetlayoutanimation and scaleanimation but the effect is always the same the view animates but it is real layout height after scaling is still the same so the position of the other views that depend on the given framelayout remain the sameafter that i have thought i change in the loop the layout height of the given framelayoutlayoutparams viewgetlayoutparamslayoutparamsheight scaletolayoutsetlayoutparamslayoutparamsi have it got animating marketlike view but the cost performance is way to highso the question is is there any other proper way to scale change eg height from 50dip to 200dip the given view viewgroup so that the position of the views below the animating view also changes,['android'] +143899,eclipse specify multiple res directories like specifying multiple src directories i need to brand my application and only few images need to be customized the codebase is the same except few generated constantsas aapt allows to specify many resource directories is there any way to specify res directories in eclipse classpath file something likeclasspathentry kindandroidres pathrescommon classpathentry kindandroidres pathresbrandmybrand a or is there any other mean to do thatthanks,['android'] +143920,are asmx webservices compatible with rest i was just wondering are asmx files compatible with rest style requests i have some asmx files which need to service some thirdparty programs which are setup to send rest requests not soap,['asp.net'] +143925,the internal implementation of exception handling today when i write a piece of code like thistry catch exception e i suddenly realize that thecatch exception e statement is so much like a function declaration and i vaguely remembered that the exception handling involves some kind of stack walkingmanipulationso what exactly is the above exception handling code compiled into i have the feeling that the above code is just a specialconvenient syntax to ease our coding but in fact maybe our code is wrapped into an autogenerated exception handling function i hope i made myself clear,['c#'] +143928,jqgrid reposition delete confirmation box i am currently using jqgrid with the navgrid del set to true problem is when a user clicks on delete it pops up a confirmation box in the upper left hand of the grid since we are already scrolled down to the very bottom which i have a large height the user has to go all the way to the top to confirm is there any way to move the position of this a manual offset is just fine but ideally i want to dock it to the bottom left as apposed to top leftthanks in advanceif this is a dupe i am sorry i tried just posting it but it gave me some weird error and is not showing in my history so assumed it did not post,['jquery'] +143950,net how to deprecate a webmethod in net is there a standard way to indicate that a web service method has been deprecated to clarify by web service method i mean a method that has been decorated with the webmethod attributeis standard practice to just use the obsolete attribute to mark it as deprecated just like any other method,['.net'] +143978,does xmlunit have an assert to ignore whitespace i want to compare two xml strings in a test but the test keeps failing due to whitespacetestpublic void testforequality throws exception string mycontrolxml msguuid0x00435a8cuuidmsg string mytestxml msguuid0x00435a8cuuid msg assertxmlequalmycontrolxml mytestxml diff diff new diffmycontrolxml mytestxml asserttruediffsimilar,['java'] +143988,css selector first paragraphs first letter inside a div div p once upon a time p p a beautiful princess pdivhow can i select in my css the first letter of the first paragraph inside this divthanksluca,"['css', 'html']" +143992,how to thisplay all nonenglish characters correctly in a web site it is annoying to see even the most professional sites do it wrong posted text turns into something that is unreadable i do not have much information about encodings i just want to know about the problem that is making such a basic thing so harddoes http encoding limit somecharactersdo users need to send info about thecharsetencoding they are usingassuming everything arrives to theserver as it is is encoding usedsaving that text causing the problemis it something about browserimplementationsdo we need some javascript tricks tomake it workis there an absolute solution to this it may have its limits but stackoverflow seems to make it work,['html'] +144019,uilabel align text to center how do i align text in uilabel,['ios'] +144038,jquery toggle class i am having trouble adding in jquerys toggleclass function into the rest of my code the page has several html5 audio tags on it which are controlled via jquery i attempted to add the toggle function to my jquery audio control function but it is not adding the class and subsequently the audio control does not work so i suppose it is some weird syntax errorwhat do you guys recommend below is a jsfiddle and a my unfortunately weak attempt htmldiv idmusic right div classthumbnail idpaparazzi a classplayback img classplay src a audio source srcaudiofernando garibay paparazzisnlmixogg typeaudioogg source srcaudiofernando garibay paparazzisnlmixmp3 typeaudiompeg your browser does not support html5 audio audio div div classthumbnail iddanceinthedark a classplayback img classplay src a audio source srcaudiofernando garibay danceinthedarkogg typeaudioogg source srcaudiofernando garibay danceinthedarkmp3 typeaudiompeg your browser does not support html5 audio audio div div classthumbnail idbornthisway a classplayback img classplay src a audio source srcaudiofernando garibay bornthiswayogg typeaudioogg source srcaudiofernando garibay bornthiswaymp3 typeaudiompeg your browser does not support html5 audio audio divdivjavascriptvar curplayingfunction playbackclickfunctione epreventdefault var song thisnextaudio0 songtoggleclassplaying ifsongpaused songplay ifcurplaying audio curplaying0pause else songpause curplaying thisparent0id the function below works but does not have the addremove class functionsvar curplayingfunction playbackclickfunctione epreventdefault var song thisnextaudio0 if songpaused songplay if curplaying audio curplaying0pause else songpause curplaying thisparent0id,['jquery'] +144039,how to crop from one image and paste into another with pil hey guys this has probably been asked a million times but i am having a little trouble here with pil i am trying to copy a rectangle out of an image and paste it into another this is my codeimport imageii imageopenramzapngbox 70 70 30 30region iicropboxio imageopentemplatepngiopasteregion boxiosaveoutputpngand i am getting this error valueerror images do not matchdo any of you know a fix to this,['python'] +144065,does using this instead of this provide a performance enhancement assume i have the following exampleexample onemy selector selected more than one elementeachfunction thisstuff thismorestuff thisotherstuff thisherstuff thismystuff thistheirstuff thischildreneachfunction howmuchstuff thistoomuchstuff plus just some regular stuff thiscssthisplaynone thiscssfontweightbold thishashisbabiesstuffcsscolorlight blue thishasherbabiesstuffcsscolorpinknow it could beexample twomy selector selected more than one elementeachfunction this this thisstuff thismorestuff thisotherstuff thisherstuff thismystuff thistheirstuff thischildreneachfunction howmuchstuff thistoomuchstuff plus just some regular stuff thiscssthisplaynone thiscssfontweightbold thishashisbabiesstuffcsscolorlight blue thishasherbabiesstuffcsscolorpinkthe point is not the actual code but the use of this when it is used more than oncetwicethree times or moream i better off performancewise using example two than example one maybe with an explanation why or why noteditnotei suspect that two is better one what i was a little fearful of was peppering my code with this and than inadvertently introducing a potentially difficulttodiagnosis bug when i inevitably forget to add the this to an event handler so should i use var this this or this this for thisthankseditas scott points out below this is considered caching in jqueryjared,"['javascript', 'jquery']" +144096,how do i tell if i am leaking com objects i am writing some code that makes relatively simple use of com calling addref on some objects and releaseing them later other than just checking the code really thoroughly is there a way i can check to see if i am leaking com objects everywherei cannot use reference counted iblahblahptrs because i need to pass the objects to a set of apis who do not know what a com is and so do not understand the whole reference counting pointers thingy they pass the pointer around like a tokenthanks,['c++'] +144102,how to get selected value from uipickerview i know that with a uidatepicker you can use something likensdate mydate pickerdatebut i am using a uipickerview in my view how can i similarly get the value selected or do i have to setup didselectrow type of method to do thisupdatethis code works for picker with 1 component nsinteger row nsstring weightselected row reppicker selectedrowincomponent0 weightselected pickerarray objectatindexrowi tired this code for my picker with 2 components but it is freezing nsinteger row1 row2 nsstring weightselected1 nsstring weightselected2 row1 reppicker selectedrowincomponent0 row2 reppicker selectedrowincomponent1 weightselected1 pickerarray objectatindexrow1 weightselected2 pickerarray objectatindexrow2 nsstring weightselected nsstring stringwithformat weightselected1 weightselected2,"['ios', 'objective-c']" +144106,how to add xelement in specific location in xml document i want to create an xml document like thisi want to create it from scratch using code and linqtoxml in the form load event i have written this codeprivate void form9 loadobject sender eventargs e doc new xdocumentnew xdeclaration10 utf8 yes xelement myroot new xelementemployees docaddmyroothow i can add new person to employees and if i want to insert person in specific location what can i dohow i can delete or update a specific person,['c#'] +144140,is there a throws keyword in c like in java possible duplicatehow to use javastyle throws keyword in c i have a function where an exception occurssay for exampleprivate void functionname throws exception some code that might throw an exceptionthanks,"['c#', 'java']" +144149,how to go to edit mode in formview i have formviewaspformview idfvreport runatserver defaultmodereadonly allowpagingfalse onmodechangingfvreport modechanging datakeynamesidprotected void fvreport modechangingobject sender formviewmodeeventargs e switch enewmode case formviewmodeedit fvreportallowpaging false break in itemtamplate i put linkbuttonasplinkbutton idlbedit runatserver causesvalidationtrue commandnameedit commandargument evalid on n342nnasplinkbuttonof course formview has edititemtemplate sectionwhen i click button formview is refreshed and stays in readonly what am i doing wrong,"['c#', '.net', 'asp.net']" +144157,how to manually log out a user with spring security probably the answer is simple how can i manually logout the currently logged in user in spring securityis it sufficient to callsecuritycontextholdergetcontextgetauthenticationsetauthenticatedfalse,['java'] +144171,how to search in excel file private void openexcelfile excelapplication exlapp new microsoftofficeinteropexcelapplication if exlapp null messageboxshowexcel app object could not be created else exlfileselectorfilename xls if exlfileselectorshowdialog dialogresultok excelworkbook wrkbook exlappworkbooksopenexlfileselectorfilename 0 true 5 true excelxlplatformxlwindows t false false 0 true true true excelsheets sheetlist wrkbooksheets excelrange search exlappget rangea1 c5 searchfindfindme null excelxlfindlookinxlvalues excelxllookatxlwhole excelxlsearchorderxlbyrows excelxlsearchdirectionxlnext false null null this is an answer that codex answered to a previous question asked in this forum but when i copy it to my app the system dont recognize the exlfileselectorfilenamehow can i fix it what am i missing i am trying for some time to do a simple search with in an excel file with no lucki added the excel reference nedded for the projectthanks,"['c#', '.net']" +144209,change installer properties in c custom action how to change installer properties in my c custom action,['c#'] +144242,hacking railsvim to work with padrino i recently cloned railsvim vimrails hoping to modify it to work with padrino projects currently i am trying to get the rcontroller command to look not only in appcontrollers perfect for rails but also in any folder in the project that has a subfolder called controllers so when i type rcontroller in commandmode and hit tab i should be able to tab through admincontrollersbaserb admincontrollersaccountsrb appcontrollerseventsrb etc this will let users of the plugin to jump to controllers in a subapp of a padrino application eg padrino rootadminthe current controllerlist function seems to handle this autocompletion and heres what i have so far only slightly modified from the original sourcefunction scontrollerlistalp let con padrinoapprelglobcontrollersrb call mapconssubvval controller return sautocamelizeconaa endfunctioni added the wildcard before the controllers directory but this gives results likercontroller ersbasercontroller erssessionsrcontroller seventsfor the last one it looks like there is somethings weird going on with string lengths or overlapideally i would like to get it to the point where typing rcontroller admintab should result in autocompletion to rcontroller admincontrollersaccountsrb likewise rcontroller apptab should result in rcontroller appcontrollerseventsrbthe code for the viewlist function has something similar to this and its code is as follows function sviewlistalp let c scontroller1 let top padrinoapprelglobappviewssfuzzyglobaa call filtertopvval if c aa let local padrinoapprelglobappviewsc return scompletion filterlocaltopaa endif return scompletion filtertopaa endfunctionanyone have any suggestions thanks in advance,['ruby'] +144249,max allowed size in text field of mysql i am doing a project where user can post text i have used tinytexti need to know how much input user should be allowed to do i came to know tinytext allows only 255 characters to be entered from but if a user enters then it have to be converted to amp and soso what should be the ideal size allowed to be inputted from the users for these fielddata typestinytext textuser can insert data but can not edit an user can view others data so view will be used mostly,"['php', 'mysql', 'html']" +144251,android get bounding rectangle of a view i am implementing a drag and drop for an android application in order to know if the drop happens inside the drop target i need to know the bounding rectangle of the drop target view i would then see if the getrawxy in the motionevent fall within this rect when i get the action up actioni realize i can call getleftrighttopbottom on the drop target view but these are relative to the parents container it seems i need to know the real or raw values so i can compare them to the raw x y in the motionevent,['android'] +144255,codility absolute thistinct count from an array so i took the codility interview test yesterday and was informed today that i failed unfortunately i wasnt given any other information by either codility nor the employer as to where i screwed up so i would appreciate some help in knowing where i went wrong i know codility pays alot of emphasis on how fast the program runs and how it behaves for large numbers now i didnt copy paste the questions so this the approx of what i remembercount the number of elements in an array a which are absolute thistinct what it means is if an array had 3 and 3 in it these numbers are not thistinct because33 i think an example would clear it up bettera53013the result would be 4 because there are 4 absolute thistinct elements in this arraythe question also stated that alength would be 10 and most importantly it stated that assume that the array is sorted in ascending order but i didnt really understand why we would need it to be sortedif you think i missed something ask and i will try to clear up the question furtherhere is my codeimport javautilhashmapimport javautilhashsetimport javautilsetpublic class test2 int testint a setinteger snew hashsetinteger forint i0ialengthi saddmathabsai return ssize public static void mainstring args test2 tnew test2 int a121 systemoutprintlnttesta,"['c#', 'java', 'python', 'c++']" +144276,how to set fixed background position from right side in css in this caseli background urlimggreyarrownextpng norepeat right center borderbottom 1px solid d4e8ebi want 20px space in right side before to background image and i cannot give margin on li because border should touch the edgesso i need to set 20px but it takes 20px from left side not right sideli background urlimggreyarrownextpng norepeat 20px center borderbottom 1px solid d4e8eb,['css'] +144286,how to create wrapper class for any user defined class someone told me that we can create wrapper class for any user defined class instead of only for primitives if yes then how can we create it i have no idea about that from where to start would you please provide any demo code for this purposeawaiting for your responses,['java'] +144306,finding the selected radiobuttons value in aspnet coding platform aspnet 40 webforms with ci have two aspradiobutton controls which are having the same groupname which essentially makes them mutually exclusive example markupaspradiobutton idonejobpermonthradio runatserver cssclassregtype groupnameregistrationtype tooltip125aspradiobutton idtwojobspermonthradio runatserver cssclassregtype groupnameregistrationtype tooltip200my intention was to find the tooltip text of the radiobutton that is checkednow i am coding like thisint registrationtypeamount 0if onejobpermonthradiochecked registrationtypeamount converttoint32onejobpermonthradiotooltipif twojobspermonthradiochecked registrationtypeamount converttoint32twojobspermonthradiotooltipi find that code ugly and redundant what if i have 20 checkboxes is there a method that would get the checked radiobutton from a set of radiobuttons with same groupname and if not what are the pointers on writing oneps cannot use a radiobuttonlist in this scenario,"['c#', 'asp.net']" +144316,c dependency injection by reference or by boostshared ptr in cases where constructor dependency injection is required what are the considerations for using injection by reference vs using boostshared ptris there another common way of doing it how does it compare to the two methods above,['c++'] +144318,strategy to run tests on a database i have started working on an existing project with over 1800 functionalintegration tests these have been coded with mstestmany of those connect directly to the sql server database the database is generated by a code generator which amongst many things create the database generating the db is slow and cumbersome this as the following problemsthe test clean the db which mean we must maintain a seperate db for tests and another for using the application the procedure right now is to change the database when changing between running test and running the appeach branch needs to have it is own db as the db model can be different in each db which means 2 db per branch with step 1it is slowan installation of sql server and of the db must be present for the test to run i would like the existing tests not to be dependent on such on installation run faster if possible and not have to deal with maintaining databases through the code generator juggling connection strings etci am trying to acheive this as quickly as possible since a rewrite of the tests is not in the budget i have already introduced mocking to help new test be less dependent on the database my problem now is for the existing testsmy first though was to change our base unit test class to connect to a sqlite db which would be created by the code generator which already generates the main db instead of the sql server db the sqlite could then be deleted and recopied to the test folder between each run this would have been fast not require having 2 sql server database in fact if just running the tests no sql server installation would have been requiredmy problems were that the generated code uses many concepts not included in sqlite tsql sql server specific syntax schemas stored procs and embedded clr assemblies i then tried sql server ce 4 which had many of the same limitations as sqliteis there any other alternatives available other than rewriting the code to be compatible with sqlite or ce rewriting the existing tests or a system in which we maintain 2 seperatedb edits changed unit test to functional tests clarified some things put some things in bold i agree that those tests are not proper unit tests i agree that mocking would have been nice here what i am trying to do is try to fix the mess i am faced with,['.net'] +144329,how to add mingw bin directory to my system path i am using windows xp i am trying to add a new library to my dev c for that i need to install mingw and then i have been instructed to add bin directory of mingw to my system path but i donat know how to do it please guide me step by step to add this to my system path,['c++'] +144355,failed to get the task for process 1640 error when trying to run iphone app on device i am getting the following error whenever i try to install my cocos2d game on an iphone device failed to get the task for process 1640i am using xcode 402 which i really hate as it is simply too complicated i have set the build settings for my target but when i click on the project it says no build settings have been configured as shown in the screenshot below although the app fails to run on the device but when i use my iphone and click on the app it does run without using xcode,['iphone'] +144357,rationale for throwing static type according to the c faq when one throws an object it is thrown using the static type of the expression hence if you havecatch some exception const e throw e throws static type possibly causing slicing should just throw insteadand e is actually a reference to some class derived from some exception the above throw will cause the object to be sliced silently yes i know the correct answer is simply to throw but the way things are seems like an unnecessary source of confusion and bugswhats the rationale for this why wouldnt you want it to throw by the dynamic type of the object,['c++'] +144373,mysql select with concat condition i am trying to compile this in my mind i have a table with firstname and lastname fieldsand i have a string like bob jones or bob michael jones and several othersthe thing is i have for examplebob in firstname andmichael jones in lastnameso i am trying to select neededfield concatfirstname lastname as firstlast from users where firstlast bob michael jonesbut it says unknown column firstlast can anyone help please,['mysql'] +144378,java generics obj instanceof t is there a way to determine if an object is an instance of a generic typeifobj instanceof tthat clearly does not work is there an alternative like i want to use java reflection to instantiate a class and then check to make sure it is of type generic t,['java'] +144393,revert a jquery draggable object back to its original container on out event of droppable i have a draggable item which if not dropped in a droppable will revert this works well until a user drops an item in the droppable if they decide they have made a mistake anytime they pull the draggable out it reverts to the droppable i would prefer that on out and deactivate the draggable goes back to its original containermy code is below but i have provided a sample on jsfiddlehtmldiv idorigin div iddraggable classuiwidgetcontent pi revert when i am not droppedp divdivdiv iddroppable classuiwidgetheader pdrop me herepdivjavascriptfunction draggabledraggable revert functiondropped var dropped dropped dropped0id droppable ifdropped alerti am reverting return dropped eachfunction var top thispositiontop var left thispositionleft thisdataorgtop top thisdataorgleft left droppabledroppable activeclass uistatehover hoverclass uistateactive drop functionevent ui thisaddclassuistatehighlightfindphtmldropped out functionevent ui does not work but something like this uidraggablemouseupfunction var top uidraggabledataorgtop var left uidraggabledataorgleft uiposition top top left left,['jquery'] +144424,mvc3 validate input notequalto my forms have inputs with default helper text that guides the user on what to enter rather than using labels this makes validation tricky because the input value is never null how can i extend unobtrusive validation to handle this the form should not be valid if the name input is equal to please enter your namei started reading brad wilsons blog post on validation adapters but i am not sure if this is the right way to go i need to be able to validate against different default values depending on the field thanks,"['javascript', 'jquery']" +144427,detect icc vs gcc at compile time how to detect at compile time if i am using gcc or icci was quite puzzled to find out that icc defines gnuc and even gnuc minor and gnuc patchlevel why,"['c++', 'c']" +144429,sql how to select earliest row i have a report that looks something like thiscompanya workflow27 june5companya workflow27 june8companya workflow27 june12companyb workflow13 apr4companyb workflow13 apr9companyb workflow20 dec11companyb wofkflow20 dec17this is done with sql specifically tsql version server 2005select company workflow datefrom workflowtablei would like the report to show just the earliest dates for each workflowcompanya workflow27 june5companyb workflow13 apr4companyb workflow20 dec11any ideas i cannot figure this out i have tried using a nested select that returns the earliest tray date and then setting that in the where clause this works great if there were only one companyselect company workflow datefrom workflowtablewhere date select top 1 date from workflowtable order by datebut this obviously would not work if there is more than one company in that table any help is appreciated,['sql'] +144450,nsnotifications name best practice in trying to decouple my model from the view controllers that thisplay fetched data when an asynchronous fetch completes i post an nsnotification nsnotificationcenter defaultcenter postnotificationnamefoobarfetchsuccess object fooi have gotten into the habit of using define foo fetch success foobarfetchsuccessin a common header file and then using it for the addobserver and removeobserver as well as the postnotificationname nsnotificationcenter defaultcenter addobserverself selectorgotdata namefoo fetch success object bazso foobarfetchsuccess string is used all over the place and there are many more just like himso whats the best way to declare a string once and use it everywhere,['objective-c'] +144457,jqm jquerymobile push last page out of dom on changepage i notice that the page that i was just viewing is still in the dom is there a way to remove the last page viewed after i transition to the new page using changepagei have thisabled all the back navigation as i do not want the use to go back to the last page when transitioning to the new pagesany suggestionsflow of the sitemain page fill out infosubmit on changepagenext page fill out more info submit on changepageetconce the page has been submitted i do not need it anymoreupdatehere is the first pagediv datarolepage idfirst page datathemez databackbtnfalse dataurlfirst page classuipage uibodyzit appends something to this when adding a new pagediv datarolepage idnext page namenext page datathemez datatitlenext page dataurlgetnextpagephppagenext page classuipage uibodyzcalling the live like this pagenameindex next pagepagenameindexlivepagecreatefunctionevent ui uiprevpageremoveusing changepage like thismobilechangepagegetnextpagephppagepagenameindexslidefalsefalse,['jquery'] +144463,whats the difference between systemtype and systemruntimetype in c i was trying to do some convention tests today and getting all the types in an assembly by calling assemblygettypes when i stumbled into somethingsystemruntimetypefirstnamespacefirstclasswhenever i try to compare that type with typeoffirstclass they are not equal so when i try to find all the types that contain firstclass as a generic parameter i am not finding anywhats the difference between systemruntimetype and systemtypeis there any way to solve my problem,['c#'] +144474,whats an example use case for a python classmethod i have read what are class methods in python for but the examples in that post are complex i am looking for a clear simple barebones example of a particular use case for classmethods in python can you name a small specific example use case where a python classmethod would be the right tool for the job,['python'] +144492,mediascannerconnection produces androidappserviceconnectionleaked i am using the mediascannerconnection example code from the api demos the snippet i am using is mediascannerconnectionscanfilecontext new string permfilegetabsolutepath null new mediascannerconnectiononscancompletedlistener public void onscancompletedstring path uri uri androidutillogiexternalstorage scanned path androidutillogiexternalstorage uri uri when i run this code i get a fc dialog with the following from the logcat420 231745988 erroractivitythread3015 activity commypackagename has leaked serviceconnection androidmediamediascannerconnection40715c70 that was originally bound here0420 231745988 erroractivitythread3015 androidappserviceconnectionleaked activity commypackagename has leaked serviceconnection androidmediamediascannerconnection40715c70 that was originally bound herewhat am i doing wrongfyi i am running this from a background thread using asynctask,['android'] +144524,why does this closurescoped variable lose its value i saw this javascript quiz here and i could not figure out this problemfunction var a 1 var b 2 function a b var b consoleloga a aundefined consolelogb b b2however if you remove the var b declaration from the inner function then a 2 as you would expectwhy is this happeningyou can play with it here,['javascript'] +144527,textmate whitespaceinvisibles show spaces is there a way to show soft tabs spaces in textmate view show invisibles works well for keeping track of indentation if youre using tabs for indentation unfortunately in languages where indentation is semantic you generally have to use spacespython yaml haml coffeescriptany suggestions for showing this whitespace or keeping track of soft indentation in textmate should i keep holding out for textmate2alternative strategies and suggestions are also welcome,['python'] +144529,no operator found while comparing structs in c comparing two instances of the following struct i receive an errorstruct mystruct1 positionconst mystruct2 my struct 2 const int an int 1 my struct 2 my struct 2 an int an int stdstring tostring const mystruct2 my struct 2 int an intthe error iserror c2678 binary no operator found which takes a lefthand operand of type myprojmystruct1 or there is no acceptable conversionwhy,['c++'] +144531,use cactiverecord to get the sum of a column 1 is there a way to get the sum of an integer column using cactiverecord in yiiotherwise i will have to get the column data and sum it up on the server side 2 i also assume getting the sum via one sql query is faster than getting the column of data and sum it up on the server with php if performance matters should the mysql server be bothered to do such operation or just let the php server to take care of this please kindly advice,"['php', 'mysql']" +144560,handling xforwardedproto in java apachetomcat can any one guide me in working with xforwardedproto in java apachetomcatthe application setup is in such a way that tomcat talks with apache webserver which in turn talks with cisco loadbalancer finally the balancer publishes the pages to the client tomcat apache2 load balancer clientthe ssl certificate is installed in loadbalancer and its handling https request my requirement is to make the application behave in such a way that it uses the xforwardedproto and change the pages as http or httpschecking on the header files of my webpages i could not find the xforwardedproto parameter i do not have access to the loadbalancer configuration either and the it has suggested us to use the xforwardedproto to differentiate between http https requestis there any configuration to be done in tomcat or apache level so that it will return the xforwardedproto parameter or is it that the configuration should be handled in loadbalancer,['java'] +144565,look if a method is called inside a method using reflection i am working with reflection and currently have a methodbody how do i check if a specific method is called inside the methodbodyassembly assembly assemblyloadmodule1type type assemblygettypemodule1moduleinitmethodinfo mi typegetmethodinitializemethodbody mb migetmethodbody,"['c#', '.net']" +144622,missmatch between the method signature and actual call when using the java native interface on android i made two silly mistakes that cost me a lot of timehaving this method idjmethodid mymethod methodid envgetmethodidhello cls mymethod iljavalangstringljavalangstringizmy first mistake was calling it using envcallvoidmethodand my second mistake was calling it like this jboolean rv jenvcallbooleanmethodhello obj mymethod methodid myfirst jstring mysecond jstring 1which was obviously missing a jint argument between mymethod methodid and myfirst jstringit took me a long time to track these errors down because there was no relevant output in logcat and the only behavior was not doing anything it did not even crashso the question is how do i get more meaningful errors for these kind of mistakes,['android'] +144643,c mongodb how to correctly map a domain object i recently started reading evans domaindriven design book and started a small sample project to get some experience in d at the same time i wanted to learn more about mongodb and started to replace my sql ef4 repositories with mongodb and the latest official c drivernow this question is about mongodb mapping i see that it is pretty easy to map simple objects with public getters and setters no pain there but i have difficulties mapping domain entities without public setters as i learnt the only really clean approach to construct a valid entity is to pass the required parameters into the constructor consider the following examplepublic class transport ientitytransport private readonly transportid transportid private readonly personcapacity personcapacity public transporttransportid transportidpersoncapacity personcapacity validatenotnullpersoncapacity personcapacity is required validatenotnulltransportid transportid is required thistransportid transportid thispersoncapacity personcapacity public virtual personcapacity personcapacity get return personcapacity public virtual transportid transportid get return transportid public class transportidivalueobjecttransportid private readonly string number region constr public transportidstring number validatenotnullnumber thisnumber number endregion public string idstring get return number public class personcapacityivalueobjectpersoncapacity private readonly int numberofseats region constr public personcapacityint numberofseats validatenotnullnumberofseats thisnumberofseats numberofseats endregion public int numberofseats get return numberofseats obviously automapping does not work here now i can map those three classes by hand via bsonclassmaps and they will be stored just fine the problem is when i want to load them from the db i have to load them as bsondocuments and parse them into my domain object i tried lots of things but ultimately failed to get a clean solution do i really have to produce dtos with public getterssetters for mongodb and map those over to my domain objects maybe someone can give me some advice on this,['c#'] +144649,elegant way of reading a child property of an object say you are trying to read this propertyvar town staffhomeaddresspostcodetownsomewhere along the chain a null could exist what would be the best way of reading towni have been experimenting with a couple of extension methodspublic static t2 ifnotnullt1 t2this t1 t funct1 t2 fn where t1 class return t null fnt defaultt2var town staffhomeaddressifnotnullx xpostcodeifnotnully ytownor public static t2 trygett1 t2this t1 t funct1 t2 fn where t1 classif t null try return fnt catch return defaultt2var town stafftrygetx xhomeaddresspostcodetownobviously these are just abstracting away the logic and making the code a little more readablebut is there a better more efficient wayeditin my particular case the objects are being returned from a wcf service and i have no control over the architecture of those objectsedit 2there is also this methodpublic static class nullify public static tr gettf trtf t functf tr f where tf class return t null ft defaulttr public static tr gett1 t2 trt1 p1 funct1 t2 p2 funct2 tr p3 where t1 class where t2 class return getgetp1 p2 p3 summary simplifies null checking as for the pseudocode var r pharmacyguildmembershipstatename can be written as var r nullify pharmacy p pguildmembership g gstate s sname summary public static tr gett1 t2 t3 trt1 p1 funct1 t2 p2 funct2 t3 p3 funct3 tr p4 where t1 class where t2 class where t3 class return getgetgetp1 p2 p3 p4 from this article,"['c#', '.net']" +144651,ajax jquery always running error everytime i run my ajax jquery function i get an error this goes for all my ajax callshere is an example of my code function findcontactcompanynamedivisionnamefirstnamelastname ajax url path datatype json asyncfalse typepost data firstnamefirstnamelastnamelastnamedivisionnamedivisionnamecompanynamecompanyname success thisplaycontacts error errormsg to get around this i use this function errormsgresult if resultstatus 200 resultstatustext ok thisplaycontactsresult else alertfailed resultstatus resultstatustext this is tough because i need to create method like this for every ajax requestwhy does it run the error code 1stplease help,['jquery'] +144653,how do i allow a aflaga enum to be edited in the winform propertygrid the winform propertygrid copes well with a standard enum but does does have a built in editor for a flag enum someone must have written one i rather not reinvent the weeli am looking for an editor that puts a checkbox next to each member of the enum so the user can control the members that are included my enum looks like flags public enum autopricingcalendar sunday 1 monday 2 tuesday 4 wednesday 8 thursday 16 friday 32 saturday 64,['.net'] +144654,datapointcollection clear performance i have this 2 examples1 example series seria new seriesname forint i 0 i 10 i seriapointsaddnew datapointi i seriapointsclear this line executes 710 seconds series is class from systemwindowsformsdatavisualization dll2 example listdatapoint points new listdatapoint for int i 0 i 10 i pointsaddnew datapointi i pointsclear this line executes 01441 seconds why there is so huge difference between those clear methodsand how can i clear seriapoint faster,['c#'] +144660,portable archive not compiling under gcc i need to deserialize data on both windows and linux and transfer the files in between i wanted to use the portable binary archives of boosts serialization library which can be found in the examples see eg at this works fine on windows vs 2008 but fails to compile under gcc 432 with the following errorscan anybody suggest a solution thanks a lotprojectslibboost1 44 0includeboostarchivebasic archivehpp in member function void portable binary iarchiveinitunsigned intprojectslibboost1 44 0includeboostarchivebasic archivehpp78 error uint least32 t boostarchiveversion typet is privatehomemyfoldersrcportable binary iarchivecpp92 error within this contexthomemyfoldersrcportable binary iarchivehpp in member function void portable binary iarchiveloadt with t boostarchiveclass id typeprojectslibboost1 44 0includeboostarchivedetailiserializerhpp107 instantiated from static void boostarchiveload accessload primitivearchive t with archive portable binary iarchive t boostarchiveclass id typeprojectslibboost1 44 0includeboostarchivedetailiserializerhpp356 instantiated from static void boostarchivedetailload non pointer typearchiveload primitiveinvokearchive t with t boostarchiveclass id type archive portable binary iarchiveprojectslibboost1 44 0includeboostarchivedetailiserializerhpp433 instantiated from static void boostarchivedetailload non pointer typearchiveinvokearchive t with t boostarchiveclass id type archive portable binary iarchiveprojectslibboost1 44 0includeboostarchivedetailiserializerhpp586 instantiated from void boostarchiveloadarchive t with archive portable binary iarchive t boostarchiveclass id typeprojectslibboost1 44 0includeboostarchivedetailcommon iarchivehpp66 instantiated from void boostarchivedetailcommon iarchivearchiveload overridet int with t boostarchiveclass id type archive portable binary iarchivehomemyfoldersrcportable binary iarchivehpp140 instantiated from void portable binary iarchiveload overridet int with t boostarchiveclass id typeprojectslibboost1 44 0includeboostarchivedetailinterface iarchivehpp60 instantiated from archive boostarchivedetailinterface iarchivearchiveoperatort with t boostarchiveclass id type archive portable binary iarchiveprojectslibboost1 44 0includeboostarchivedetailcommon iarchivehpp51 instantiated from void boostarchivedetailcommon iarchivearchivevloadboostarchiveclass id type with archive portable binary iarchivehomemyfoldersrcportable binary iarchivecpp128 instantiated from herehomemyfoldersrcportable binary iarchivehpp107 error call of overloaded class id typeintmax t is ambiguousprojectslibboost1 44 0includeboostarchivebasic archivehpp118 note candidates are boostarchiveclass id typeclass id typesize tprojectslibboost1 44 0includeboostarchivebasic archivehpp115 note boostarchiveclass id typeclass id typeint,['c++'] +144665,how to revert a changeset in team foundation server i am new to team foundation server and someone committed changes that they werent supposed to the night previous i need to revert this changeset so that when people get latest version they will not get these changesi see no easy way to do this does anyone have experience with this,"['c#', '.net', 'asp.net']" +144681,javascript dictionary with names i want to create a dictionary in javascript like the followingmymappings name10 phone10 address50 zip10 comments20i want to populate an html table later and want to set the titles of table to the first column of mymappings and the width of columns to the second as i am new to js having trouble finding the clean way can some pls suggestthanks,['javascript'] +144689,change src value by css for input tag with typeimage is it possible to change the value of src attribute of input typeimage alttext will be shown if pics are thisabled srcsomepicpng by cssthe problem is i want to specify which pic will be shown as submit button just using css so the design team will change only css files if i use the alternative way like input typesubmit classcssclass value alttext will be shown if pics are thisabled and specify the background of this element in css it does not work well if pics are thisabled no any alternative text is shown instead of pic however the first way solves this situation please advice somethingthanks,"['html', 'css']" +144698,pygtk set icon of window with stock image i feel like this should be pretty simple but i guess i am missing somethingso i want to set the icon of a window with one of the stock images i have triedwindowicon gtkimage new form stockgtkstock dialog authentication gtkicon size menuwindowset iconwindowiconget pixbufpython then complains thatfile samplepy line 44 in init windowset iconwindowiconget pixbuf valueerror image should be a gdkpixbuf or emptyi try to convert the gtkimage to a gdkpixbuf because when i did not python complained that typeerror icon should be a gdkpixbuf or nonein the pygtk documentation it saysif the storage type of the image is not either gtkimage empty or gtkimage pixbuf the valueerror exception will be raisedso i guessing that storage type of the stock image is wrong the question is how to i get around this,['python'] +144711,how do you play android inputstream on mediaplayer so i have a small audio file in my assets folder and i wanted to open a inputstream to write to a buffer then write to a temporary file then i open up the mediaplayer to play that temporary file problem is when the media player hits mpprepare it does not play and never reaches the toast has anyone ever done this beforepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain inputstream str try str thisgetassetsopenonestopmid toastmaketextthis successful input stream opened toastlength shortshow takeinputstreamstr catch ioexception e todo autogenerated catch block eprintstacktrace end on createpublic void takeinputstreaminputstream stream throws ioexception filebeingbuffered fileinputstream stream toastmaketextthis sucessful stream conversion toastlength shortshow try convertedfile filecreatetempfileconvertedfile dat getdirfilez 0 toastmaketextthis successful file and folder creation toastlength shortshow out new fileoutputstreamconvertedfile toastmaketextthis success out set as output stream toastlength shortshow right around here byte buffer new byte16384 int length 0 while length streamreadbuffer 1 outwritebuffer0 length streamreadbuffer toastmaketextthis success buffer is filled toastlength shortshow outclose playfile catchexception e logetag etostring eprintstacktrace end catchend grabbufferpublic void playfile try string path convertedfilegetabsolutepath mp new mediaplayer mpsetdatasourcepath toastmaketextthis success path has been set toastlength shortshow mpsetaudiostreamtypeaudiomanagerstream music mpprepare toastmaketextthis media player prepared toastlength shortshow mpstart toastmaketextthis media player playing toastlength shortshow catch illegalargumentexception e logetag etostring eprintstacktrace catch illegalstateexception e logetag etostring eprintstacktrace catch ioexception e logetag etostring eprintstacktrace end playfile,['android'] +144715,zend debug multiple pages i have a pretty simple setupapache server php 53 eclipse php zend debug modulewhen i click on debug it sees my breakpoints and everything works fine but only for the first page if i click on a different page within the integrated browser all breakpoints from that moment forward are ignored i think it has to do with the fact that the first pages url is something similar tohttplocalhostschedulestart debug1debug host127001send sess end1debug session id1003original urlhttp3a2f2flocalhost2fscheduledebug start session1debug no cache1303403971996debug port10whereas pages after do not have these url debug parameters appended is this a limitation with debugging in eclipse or is there some way to append these get parameters to every link i click perhaps a browser extensionlooking under advanced for my debug configuration i see that i have debug all pages checked,['php'] +144751,making multilanguage ios app i need to build an app which will be multilingual for instance the app will be released in france and the netherlands the user needs to select a language when the app first start for the first time is there an easier way to do this in xcode i saw something about localizations does this have anything to do with it,"['ios', 'iphone']" +144753,sql server not in i need to build a query that will show me records that are in table 1 but that are not in table 2 based on the makemodelserial number combinationi know for fact that there are 4 records that differ but my query always comes back blank select from table1 where makemodelserial number not inselect makemodelserial number from table2table 1 has 5 recordswhen i change the query to in i get 1 record what am i doing wrong with the not,['sql'] +144755,is there a good doubleprecision small matrix simd library for x86 i am looking for a simd library focused small 4x4 matrix operations for graphics there is lots of single precision ones out there but i need to support both single and double precisioni have looked at intels ipp mx library but i would prefer something with source i am very interested in sse3 implementations of these particular operationsmat4 mat4 mat4 vec4mat4 array of mat4mat4 array of vec4mat4 inversion nice to haveedit no premature optimization answers please anyone who has worked with small matrices knows gcc does not vectorize these as well as hand optimized intrinsics or asm and in this case it is important or i wouldnt be asking,['c++'] +144777,passing strings with single qoute from mvc razor to javascript this seems so simple it is embarrassing however the first question is when passing a value from the new viewbag in mvc 30 razor into a javascript block is this the correct way to do it and more importantly where and how do you apply the proper string replacement code to prevent a single quote from becoming as in the resultant alert belowadding this into a single script blockalertviewbagstr hi how does it goingresults in the following alert,['javascript'] +144794,invalid django time zone doing a recent build i ran djangos syncdb and i am getting the errortraceback most recent call last file managepy line 11 in module execute managersettings file usrlibpython26sitepackagesdjango13py26eggdjangocoremanagement init py line 438 in execute manager utilityexecute file usrlibpython26sitepackagesdjango13py26eggdjangocoremanagement init py line 379 in execute selffetch commandsubcommandrun from argvselfargv file usrlibpython26sitepackagesdjango13py26eggdjangocoremanagement init py line 252 in fetch command app name get commandssubcommand file usrlibpython26sitepackagesdjango13py26eggdjangocoremanagement init py line 101 in get commands apps settingsinstalled apps file usrlibpython26sitepackagesdjango13py26eggdjangoutilsfunctionalpy line 276 in getattr self setup file usrlibpython26sitepackagesdjango13py26eggdjangoconf init py line 42 in setup self wrapped settingssettings module file usrlibpython26sitepackagesdjango13py26eggdjangoconf init py line 125 in init raise valueerrorincorrect timezone setting s selftime zonevalueerror incorrect timezone setting americanew york est5edt systemvest5edt useasterni have not changed any of my core settings so i do not know why i would suddenly be getting this error the value in my settingspy file is time zone americanew york which is a valid value according to this why is not django accepting this value,['python'] +144808,is there a onexit or leave event on aspnet textbox i need to run some code on server when user leaves the textbox it will do some calc over whats been typed i would rather avoid doing it with jquery because it would involve creating a json server etcis not there a way to do a postback for such an event,"['c#', 'asp.net']" +144814,conditional keyvalue in a ruby hash is there a nice one line way of writing a hash in ruby with some entry only there if a condition is fulfilled i thought ofa a b b if conditionbut that leaves b nil if the condition is not fulfilled i realize this could be done easily in two lines or so but it would be much nicer in one line eg when passing the hash to a functionam i missing yet another one of rubys amazing features here,['ruby'] +144828,best way to strip off symbols last week i released the linux and windows version of an applicationand after the release we realized that the symbols were not stripped off and my manager thinks and i thisagree that it might allow the user to understand our algorithmanyway now i will have to cleanup the symbols and rerelease the applicationmy questionwhat is the best way to strip symbols in linuxwhat is the best way to strip symbols in windows,"['c++', 'c']" +144839,reading an inputstream all at once i have developed a j2me application that connects to my webhosting server through sockets i read responses from the server using my own extended linereader class that extends the basic inputstreamreader if the server sends 5 lines of replies the syntax to read the server replies line by line is lineinputreadline line line n inputreadline line line n inputreadline line line n inputreadline line line n inputreadlinein this case i can write this syntax because i know that there is a fixed number of replies but if i dont know the number of lines and want to read the whole inputstream at once how should i modify the current readline function heres the code for the functionpublic string readline throws ioexception stringbuffer sb new stringbuffer int c while c read 0 c n c r c 1 sbappendcharc by now buf is empty if c r dos or mac line ending c superread if c n c 1 push it back into the buffer buf char c readahead true return sbtostring,['java'] +144844,ways to add javascript files dynamically in a page i have seen scriptaculousjs file to include its required javascript files dynamically is there any better approach to include javascript dynamicallyfor example i would like to include my js files likescript srcsinglejsfilesfirstjssecondjsthirdjsscripthow can i do that in an efficient manner,"['javascript', 'jquery']" +144859,passing a function as an argument in a javascript function i was wondering whether this is legal to do could i have something likefunction functa foox where a is an array and x is an integer argument for another function called foothe idea is to have one function that uses a for loop on the array and calls that function in the params for every element in the array the idea is so call this on different functions so elements of two arrays are multiplied and then the sums are added together for example a0 b0 a1 b1,['javascript'] +144871,camera in android i want to use camera facility in android applicationi want to capture image on click of button control can any one suggest me the best example of it,['android'] +144889,is progress bar possible with php and javascript using ajax i was wondering how to make progress bar like gmaili tried script srcjqueryjsscriptscriptfunction ajax url indexphp success functiondata barhtmldata scriptdiv idbardivand on indexphpedit by sleep i just meant to simulate continuous stream of output like multithreaded programs which is not supported in phpphpfori0 i10 i sleep1 echo iit seems that output is echoed out at once so i get result 012345678910 at oncealso i tried setintervalfunction ajax url indexphp success functiondata barhtmldata 10instead i had trouble maintaining value of progress so i didphpsession startifisset sessionvalue if sessionvalue 10 unset sessionvalue else sessionvalue else sessionvalue 0echo sessionvalueas part of my php but it seems that i am calling ajax function on continuous interval my question is how does google use progress bar while loginng in gmail do they get continuos stream of data like i tried on my first example or send regularly request on some url though not through ajax through jsonp or whatever and upadate the page like second can i do same with php even if not with php can i do it using javascript and other server side scripting language where multithreading is supported,"['php', 'javascript']" +144902,a way to thisable conversion operators is there any way to thisable the conversion operator of a class assume it is a library class and i cannot modify the source code or headers i sometimes encounter a library that thinks to be clever and defines conversions which are silly and sometimes just dangerousfor example given this declaration in a header which i cannot modifyclass tooclever public operator char constis there any way trickery allowed even if compiler specific i can prevent this operator from ever being used in my code,['c++'] +144908,change css of class in javascript i have got a class with the thisplay set to none i would like to in javascript now set it to inline i am aware i can do this with an id with getelementbyid but whats the cleanest way to do it with a class,"['javascript', 'css']" +144934,performing set operations on custom classes in python i would like to use pythons builtin set class with a custom class that i have created if i wantto create sets containing instances of my custom class what functions do i need to implement so that i can perform tests like set a set b,['python'] +144941,thisallow a specific function template instantiation i would like to define a template function but thisallow instantiation with a particular type note that in general all types are allowed and the generic template works i just want to thisallow using a few specific typesfor example in the code below i wish to prevent using double with the template this does not actually prevent the instantiation but just causes a linker error by not having the function definedtemplatetypename tt convert char const in return t this way creates a linker errortemplatedouble convertdouble char const in int main char const str 1234 int a convertint str double b convertdouble str the code is just a demonstration obviously the convert function must do something morequestion in the above code how can i produce a compiler error when trying to use the convertdouble instantiationthe closest related question i can find is how to intentionally cause a compiletime error on template instantiation it deals with a class not a functionthe reason i need to do this is because the types i wish to block will actually compile and do something with the generic version that is however not supposed to be part of the contract of the function and may not be supported on all platformscompilers and in future versions thus i would like to prevent using it at all,['c++'] +144950,are ifelse statements in a view frowned upon in aspnet mvc i know that you want to keep logic out of your views i can elimate most loops by using thisplayforeditorfor and passing ienumerables to the view what about if statements should they be avoided completely in views used sparingly as a last resort say you wanted to show hide an element based on a user rolehow would you go about doing this without an if statementa completely seperate view perhapsjust trying to get an idea of best practicesthanks,"['c#', '.net', 'asp.net']" +144957,what is the best online code editor supporting html javascript css i recently thiscovered this editori wonder if there are more such tools or possibly even better that allow editing sharing executingemulating andor debugging of the code online this tool has also some includable libraries such as mootools and jqeury but i can imagine that it can still be improved,"['javascript', 'html', 'css']" +144961,where do i find systemwindowsinteractivity as rethistributable i tried downloading blend 3 but even with that installed i cannot find the file under net if i try to add a reference from cprogram files x86microsoft sdksexpressionblend 3interactivitylibrarieswpf and use this code i get an error that the file was not found it also adds a lot of folders like en de es fr etc to my debug folder,['.net'] +144962,recommended way to manage global scope data and settings in php after a few years in php development i saw and heard various ways for storing global scope data globals constants inixmlyml files database singleton propertiesby global scope data i meanglobal applicationproject settings such asdatabase configurationsmtp ftp parametersdatabase identifiers eg primary key values for specific languages or countries defined in dbglobal runtime settings such asenable logging debugenvironment is dev test prodetc which are not supposed to change once retrieved and need to be easily reachable in any part of the project codesome global data may need to be stored as associative array so cannot be declared as constantfor example date formats per language btw i saw this other so question about array constants but is not there something more readable than using unserialize everywhere an array constant value is neededmy main question is what is the way you would recommend to store properly i mean clean readable reliable global scope data and why prosconsthanks,['php'] +144964,how to change the default language of android emulator how to change the language of the emulator by default i am getting chinese while filling a form so please help me to get out of this thanks,['android'] +144971,the executable was signed with invalid entitlements so here we are yet again i already have an app on the app store that took me 2 days to get past all the errors and just get the thing on thereright now i am trying to put the 11 update on my brothers ipod touch for testing i pressed use for development that is fine works then i build and go and it says the ipod adans ipod toucha doesnat have the provisioning profile with which the application was signed so i press install and run to install the provisioning profile and then get the executable was signed with invalid entitlementsi will be clear all i want to do right now is to test the app on an ipod touch which is plugged into the computer how do i get past this error and do that i have what i thought was a valid provisioning profile selected in active target and active executable but apparently that is not enough any ideas,['iphone'] +144977,armv7 iphone warnings i get the following warnings when trying to build my project there are about 160 warnings similar to them which is annoyingld warning cpu subtype arm all subtype is deprecated developerplatformsiphoneosplatformdevelopersdksiphoneos32sdkusrlibgccarmappledarwin10421libgcca udivsi3oandwarning armv7 developerplatformsiphoneosplatformdevelopersdksiphoneos32sdkusrlibgccarmappledarwin10421libgcca divdi3o object file developerplatformsiphoneosplatformdevelopersdksiphoneos32sdkusrlibgccarmappledarwin10421libgcca divdi3o does not contain architecture information for armv7all of the warnings are related to libgccai need this application to support ios 32 and later so what can i do to remove these warnings,['iphone'] +145013,create a jquery object collection from separate jquery objects fnsortbydepth function var ar var result thiseachfunction arpushlength thisparentslength elmt this arsortfunctionab return blength alength for var i0 iarlength i resultaddarielmt alertresultlength return resultin this function i try to create a jquery collection from separate jquery object how can i do that the code below does not workresultaddarielmtthe jsfiddle,['jquery'] +145021,how does chaining variable assignments work in sql i am analyzing some old sql code in a stored proceduredeclare var1 money var2 money var3 money etcselect var1 oldvalue var2 var1 etcso i am wondering how these assignments work when they are both in the same select statement i am assuming var2 oldvalue after the select is called but i want to be surewhat are the rules surrounding this situation are the assignments executed in the order that they are declared if so what value would be assigned to var2 in the following caseselect var2 var1 var1 oldvaluethanks,['sql'] +145027,sphinx pdf output apostrophes in python source are replaced by right single quotes i am outputting some documentation as pdf using sphinx it is all very fine except for when python source code are output then single quotes unicode u0027 are output as right single quotes u2019 which look awkwardhere are images of the glyphs in question and here is my generated pdfdoes anybody know how to correct this,['python'] +145032,sending an mcryptencrypted string via a url parameter decoded text is mangled i am messing with a simple authorization scheme i think the easiest way to do it without ssl or other http auth would be a shared key encryption adapting a simple example from the php manual i came up with the followingtext boggles the invisible monkey will rule the worldkey this is a very secret keyiv size mcrypt get iv sizemcrypt blowfish mcrypt mode ecbiv mcrypt create iviv size mcrypt randenc mcrypt encryptmcrypt blowfish key text mcrypt mode ecb iviv base64 encodeivenc base64 encodeencecho a hreftemp2phpivivtextenclinkabr the page that receives this request temp2php looks like thiskey this is a very secret keyiv base64 decode getivenc base64 decode gettextcrypttext mcrypt decryptmcrypt blowfish key enc mcrypt mode ecb ivecho crypttextbrthis gets very close but it does not decode properly it echoesboggles the invisible monkey will rule taea a14gjai am not sure what the hangup is i tried urlencodeurldecode and htmlentities thinking maybe a character was mangled in the request but no difference is there something else i am missing perhaps paddingthanks,['php'] +145037,dragging a div in jquery fine when mouse is slow but fails on fast mouse movement i want to drag a div around using my own jquery codethis example on jsfiddle works fine when the mouse movements are slowbut any fast movement pulls the mouse out of the box and the tracking is lostjquery ui draggable does not have this problem and tracks just fine regardless of how fast you move but i want to roll my own simple version so that i can integrate it with raphael key presses etc i have looked at the jquery ui draggable source but it is for me pretty impenetrable 800 linesi do not think it is an issue with event bubbling any ideas,['jquery'] +145052,java enum getdeclaringclass vs getclass the docs for the java enum class state the following about getdeclaringclassreturns the class object corresponding to this enum constants enum type two enum constants e1 and e2 are of the same enum type if and only if e1getdeclaringclass e2getdeclaringclass the value returned by this method may differ from the one returned by the objectgetclass method for enum constants with constantspecific class bodiesi do not understand when getclass and getdeclaringclass are different can someone provide an example along with an explanation,['java'] +145072,can i connect directly to a rethis server from javascript running in a browser i know there are nodejs libraries for rethis what i would like to do is run a rethis server either on localhost or on a server host somewhere and call it directly via http ie ajax or http get as needed from javascript running inside a browser ie a greasemonkey or chrome extension script or maybe a bookmarklet or script tag does rethis have a native rest or http api,['javascript'] +145120,downside of using transactionscope requiresnew i want to understand what is the tradeofdownside of using transactionscopeoptionrequiresnew on entityframework w sql server 2008 what are the reasons why we should not use requiresnew alwaysregards,"['c#', '.net', 'sql']" +145126,is there any single tool that runs jslint w3c validator both css3 and html5 on files in a given directory i want a single program that recursively finds all js html and css files in a given directory and jslints and w3c validates them respectively and prints out all errors found also it separately jslints and css validates anything found inside script and style tags embedded in the html files i also want this to validate other less common web contents too if possible using the w3c tools the tools should also have option for passing in common javascript frameworks for jslint eg it should work fine with latest jquery where i can buy such a tool,"['javascript', 'html', 'css']" +145145,cocoa deserialize json string to custom objects not nsdictionary nsarray in javaland there are a handful of useful libraries which will convert json strings to objects of matching type the json libraries i have seen for cocoa simply create nested nsdictionaries and nsarrays is there a tool out there which will go the extra step of reconstituting whatever object type i want so for example if i have a class called unicorn with a property manecolor and i have json that looks like this manecolorsilveri can automatically instantiate a unicorn object with manecolor set to silver,['objective-c'] +145146,ping a url when ios application crashes i want to ping a url on my website whenever my ios application crashes where is the best place to put an exception catcher that can quickly ping an external url and then rethrow the exception to the os,"['objective-c', 'ios']" +145162,what is the difference between match parent and fill parent i am a little confused about two xml properties match parent and fill parent it seems that both are the same is there any difference between them,['android'] +145169,java casting order let us say i have the following setupclass a b fooclass c extends b latera a new ac thefoo cafoowe know afoo returns type bwhen i do cafoo is itcasting a to type c then attempting to call foo on itcalling foo on a and casting the result to type ci am finding it difficult to determine and have always just played on the side of caution with extra parenthesis which is not a bad idea for readability but now i am curiousthis is in specific reference to objectinputstreamreadobject although i do not see how that would change the behavior,['java'] +145176,how to transform a opencv cvmat back to ndarray in numpy i14 i follow the code in opencv cookbook for python interface to transform cvmat to numpy array mat cvcreatemat35cvcv 32fc1cvsetmat7a npasarraymatbut with opencv 21 on my pc it does not work the result a here is a object array using print a does not print all element in a only print cvmattype42424005 rows3 cols5 step20 so how to fully transform a opencv mat object to original numpyndarray object,['python'] +145205,how to convert week number and year into unix timestamp i am trying to group together dates into a week number and year and then i want to convert that week number back into a unix timestamp how can i go about doing this thanks in advance for your time cheers,['php'] +145218,why we cannot do list mylist arraylist why we cannot dolistparent mylist arraylistchild,['java'] +145234,unit testing equals and hashcode a complexity story i am having a moral dilemma i have some value objects in my application which are immutable and extremely simple i have generated the equals and hashcode with an ide intellij in my case but doing that made the code coverage drop plus the reports now indicate that those value objects are very complex using the cyclomatic complexity metric when in fact they are dead simpleas an example the following equals is in a value object that has 3 immutable attributes the code complexity is 14 javancss and it has 26 execution branches cobertura i should add too that i fail the build if any method has a complexity greater than 10overridepublic boolean equalsobject o if this o return true if o null getclass ogetclass return false transcripttaskdetails that transcripttaskdetails o if inputfile null inputfileequalsthatinputfile thatinputfile null return false if language thatlanguage return false if outputfile null outputfileequalsthatoutputfile thatoutputfile null return false return truei am wondering what other devs use to circumvent this as i pay quite a lot of attention to the complexity reports as in my experience a high complexity metric relates to more bugs so this autogenerated equals and hashcodes are polluting the reportsi am thinking of using equalsbuilder and hashcodebuilder from apache commonslang to circumvent this but i am not 100 happy sediti should have added that part of the code i am writing for this project is a library that will be used by other business units and will be maintained by a different team too s,['java'] +145261,android relativelayout equal spacing i am using relative layout to create a calculator screen and i have a row of buttons labeled 1 2 and 3 i want them evenly spaced but i am not sure how to do this with relative layouti am used to using the androidlayout weight function in linearlayout and give each of them a value of androidlayout widthfill parent as well as a layout weight1any way to get this to happen on calculator screen without specifying dp or pxthis is what i have set up at the moment and they are aligned in order from left to right under the textview calculator output screen any suggestionssolutions to evenly space filling the width of the screen textviewandroidididtextviewandroidlayout widthfill parentandroidlayout heightwrap contentandroidbackgrounddrawableedit textandroidlayout margin6pxbuttonandroidididbutton1androidtext1androidlayout widthwrap contentandroidlayout heightwrap contentandroidlayout belowidtextviewbuttonandroidididbutton2androidtext2androidlayout widthwrap contentandroidlayout heightwrap contentandroidlayout belowidtextviewandroidlayout torightofidbutton1buttonandroidididbutton3androidtext3androidlayout widthwrap contentandroidlayout heightwrap contentandroidlayout belowidtextviewandroidlayout torightofidbutton2,['android'] +145266,clean way to eliminate unused parameter widget warning generated by qgraphicsitempaint qgraphicsitempaint has the following signaturevoid paintqpainter painter const qstyleoptiongraphicsitem option qwidget widgetwhen i create custom qgraphicsitems i have to provide an implementation for this function the thing is i never need to use the option and widget parameters but i cannot just remove them for obvious reasons i always see these compiler warningswarning unused parameter awidgetawarning unused parameter aoptionais there a proper to get rid of these warnings i know i can hide them by mentioning the unused parameters in the function but this is a very dirty solution and i would like to know if there are better options,['c++'] +145274,can anyone help me understand this error definition of implicitlydeclared aclassaclassaa heres the codeinclude cstdlibinclude iostreamusing namespace stdclass classa protected void setxint a private int pclassa classa error here p 0void classa setxint a p a int main systempause return exit success,['c++'] +145277,java mysql jdbc memory leak ok so i have this program with many 300 threads each of which communicates with a central database i create a global connection to the db and then each thread goes about its business creating statements and executing themsomewhere along the way i have a massive memory leak after analyzing the heap dump i see that the commysqljdbcjdbc4connection object is 70 mb because it has 80 items in openstatements a hash map somewhere it is not properly closing the statements that i create but i cannot for the life of me figure out where every single time i open one i close it as well any ideas why this might be occurring,"['java', 'mysql']" +145283,select from sqlite table where rowid in list using python sqlite3 a dbapi 20 the following works cursorexecuteselect from sqlitetable where rowid in 23the following does not cursorexecuteselect from sqlitetable where rowid in 23 sqlite3interfaceerror error binding parameter 0 probably unsupported typeis there a way to pass in a python list without having to format it into a string first,['python'] +145315,allowing implementing interface only for specific classes is it possible to permit only some specific classes to implement an iterfacelet us say that i created interface imyinterface and i want only classes which derive from usercontrol to have an ability to implement my interface is this possible,['c#'] +145324,how to update a menu item shown in the actionbar i have an activity that has 2 fragments both are listfragments and both contribute menuitems to the menu i have one menuitem that i have set the attribute androidshowasaction to have it show as a button on the actionbar which works finenow the menuitem is state dependent it is a pauseresume menu option for pausing and resuming a queue my problem is i cannot figure out how to set it is initial statue when the fragment is createdit is state is dependent on the whether the queue is paused or not so i have an asynctask that gets the queue and sets a boolean paused based on the state of the queue i am calling onprepareoptionsmenu to set the text for the pause menu item based on the last known state of the queue and this works great if i leave the menuitem in the actual menu you tap the menu icon and onprepareoptionsmenu is fired and the menu is updated before it is thisplayed the problem is if i put that same menuitem on the actionbar showasaction how can i force it to update without having to call onprepareoptionsmenu i need to be able to do this because on first launch of the app i send a request to get the queue but the task returns after the actionbar is setup and thisplayed i have created a handler in my fragment that gets called every time i get a queue update but from there how can i update the text for my menuitem on the actionbar i cannot seem to find a way to get the currently set menu to manipulate it except for in onprepareoptionmenurob w,['android'] +145350,php mysql and time zones i am trying to integrate a timezone system in my app i have really tried hard on avoiding making timezoneaware apps upto now but its a mandatory requirement now so got no choice timezones it just goes over my head i have read several topics on phpnet and also other sites including but not limited to so but i never could get the hang of itso i was wondering if some one can help me out here what i am looking to make is a preference option in my app to allow users to choose their own timezones from a select menu but the app should also be able to setchoose the dst accordingly itself for each userplease i am sure this will help others who are still striving to get the hang of the timezones so please provide as much detailed explanation as possible even if you have to consider me a complete dumbonoobedit for bountyi am adding a bounty to this question because i really thing we need a good canonical question about time zones when writing phpmysql apps thus i am also adding the mysql tag i have found things from many places but it would be good to have it all together charles answer is great but i still feel it is lacking somewhat here are some things i thought ofhow to store the times in the database from a php datetime objectshould they be stored in datetime or timestamp what are the benefits or caveats for eachdo we ever need to worry about time zones with mysql datehow to insert values using now do these need to be converted somehow either before or after the insertis it necessary to set the time zone used by mysql if so how should it be done persistently or upon every http request does it have to be set to utc or can it be anything else or is the servers time sufficienthow to retrieve values from mysql and convert them to a datetime object will putting it straight into datetime construct suffice or do we need to use datetimecreatefromformatwhen to convert to local time and why is there ever a time that we would want to convert it before it is echoed back to the user eg to compare to another datetime object or a static valueis there ever a time we need to worry about daylight savings time dst why or why notwhat should someone do if they have previously inserted data eg using now without worrying about the time zone to make sure everything stays consistentanything else you think of that someone should look out forif possible try to separate it into logical sections to make it easier for future users to find the information be sure to provide code examples where necessary,"['php', 'mysql']" +145372,what is the template keyword doing before class keyword just some code sample not a real life example at file scopetemplate typename t typename ustruct demo template class demoint int is the template keyword optional hereis the template keyword optional in line 3 i have not often seen this usage of the template keyword before which part of the standard says allows thisedit i think g has a bug then template typename t typename ustruct demo class demoint int template keyword omittedcompiles on g 451 whereas fails on comeaucomeautestc line 5 error specializing class demoint int without template syntax is nonstandard class demoint int,['c++'] +145401,has anyone got any code examples of ecl lisp for iphone development i found out about lisp for the iphone recently and wanted to find some code examples,"['iphone', 'ios']" +145437,sorting tournament seeds i am making a htmljs powered singledouble elimination bracket web app i am struggling to figure out how to assign the first round matches from a list of seeded teamsplayers for example in a bracket of 8 players the first round matches are1v84v52v73v6in more generic terms the seeds can be thought of as an arrayas i assign teams to matches by popping them off an array 12345678which needs to be sorted to18452736to clarify the higher seeds need to have the maximum thistance between them in the sorted array this is so that in a bracket with no upsets lower seeds get knocked out first and and matches with high seeds occur as late as possible in practical terms think of a tennis tournament where you want to prevent the top 4 players in a bracket of 16 or 32 etc from playing each other until the semi finals so the correct array output for a 16 seed bracket is11689413512215710314611 which translates to the following 1st round matches1v16 8v9 4v13 5v12 2v15 7v10 3v14 6v11thanks to matt ball for the correct algorithm for an 8 seed bracket,['javascript'] +145443,can we join two tables without primaryforeign key relation if we can get data from two tables without having primary and foreign key relation then why we need this rule can you please explain me clearly with suitable exampleit is a test database do not mind on the bad structure tables structuretable test1columns idlnamefnamedobno primary and foreign key and also not uniquewithout any constraintstable test2columns idnative cityagain no relations and no constraints i can still join these tables with same columns idso if there is no primaryforeign key then what is the use of that,['sql'] +145444,androiddebugkey keystore was tampered with or password was incorrect whenever i enter in the terminalkeytool list alias androiddebugkey keystore androiddebugkeystorestorepass android keypass androidit asks me for a password i have never set a password before i have read somewhere else to put in android but i still receive the following errorkeytool error javaioioexception keystore was tampered with or password was incorrectalso i am new to the mac environment whenever i type in the password the cursor does not move i am not sure if this is default mac behavior for concealing passwords or if the password is just not registering so that is why i get the error any help is appreciated,"['java', 'android']" +145461,time complexity of containsobject o in an arraylist of objects as the title says i was wondering what the time complexity of the contains method of an arraylist is,['java'] +145474,eclipse does not show lib directory during java build path libraries editing i have an eclipsejava project eclipse 352 that i am trying to add some jars to in the root project directory i have 3 subdirectories src bin and lib and all 3 subdirectories are present in the package explorer list i put the needed jars into lib however when i go to project propertes java build path libraries tab add jars and the file dialog comes up it only shows the src and bin directories in the file picker not the lib directory i am guessing it is something really simple but can someone tell me why the file picker dialog does not show the lib directory roschler,['java'] +145479,portability of native c properties in visual studio there is declspecproperty which creates properties similar to c borland c offers the property keyword with the exact same functionality in the c0x there is mention of a implicit keyword that could be expanded to implement the same functionality but it did not make it into the speci am looking for a portable and relatively clean method of declaring syntactically sugared properties that will compile in the latest compilers for windows osx and linux i am not concerned with compiler compatibility just one compiler per platformi am not looking for alternatives to properties that require parenthesis to get or set the property such as overloaded methods separating the getters and settershere is an ideal usage which compiles in visual studio 2010define property type name get put declspecpropertyget get put put type namedefine property readonly type name get declspecpropertyget get type nameclass windowpublic property readonlyvoid handle gethandle propertybool visible getvisible setvisible void gethandle bool getvisible void setvisibleboolvoid main window mainwindow if mainwindowvisible mainwindowvisible true,['c++'] +145503,c network programming hey i would like to expand my knowledge in c so the first thing i am taking on is network programmingi want to make an irc botwhich hopefully will teach me about socket programming and networking topics but i have no idea where to start if anyone could explain to me how irc bots work and how to make them and direct me to some learning resources that would be really great simple snippets as well would be awesomethankseditforgot to mention that i use ubuntu so the windows way is not an option,['c++'] +145510,android on netbeans 691 package name not valid i am new to android development actually i have not started yet because i always get the error package name not valid when trying to create a new project in netbeans 691 i have installed android sdk path is set in nb and platforms are available does anyone know what i have done wrong or how i could solve my problem i want to start soonsincerely,['android'] +145514,sql select countvaluevalue possible i want to count all the rows that only have the value i want like thisselect usersbalance usersfreebids countbidsburned 0 as activebids countbidsburned 1 as burnedbidsfrom users inner join bids on usersid bidsbidderidwhere usersid 2group by usersbalance usersfreebids it says invalid syntax neat it works perfectly without the how can i count the rows that burned1 in them and burned0 in themthanksdan,['sql'] +145521,how to keep an javascript objectarray ordered while also maintaining key lookups i have some data which i originally stored in a generic javascript object with the id as a key 7 id7namehello 3 id3nameworld however i thiscovered that browsers do not guarantee a particular object order when looping through them so in the above 3 would come before 7 i switched to using an array format like this id7namehello id3nameworld now i can loop in the correct order but cannot do fast lookups eg data3 without having to loop through the arrayis there a good way to combine both approaches i would rather avoid using a separate object for each format because the object is pretty large hundreds of elements,['javascript'] +145524,mozillas bind function question had a question about a implementation of bind function that i found on mozillas site for the most part it makes sense to me but i cant figure out what this check is for this instanceof nop this obj in the bind function obviously its checking if this is the empty function but why would you need to bind the empty function i have tried it in firebug it works but what is the point just trying to increase my javascript knowledge so any help would be appreciatedif functionprototypebind functionprototypebind function obj var slice slice args slicecallarguments 1 self this nop function bound function return selfapply this instanceof nop this obj argsconcat slicecallarguments nopprototype selfprototype boundprototype new nop return bound,['javascript'] +145552,run jar file in command prompt possible duplicatehow to run a jar file how do we run a jar file in command prompt,['java'] +145565,programmatically detect if app is being run on device or simulator i would like to know whether my app is being run on device or simulator at run time is there a way to detect thisreason being to test bluetooth api with simulator,"['iphone', 'ios']" +145576,how do i output a compiletime numeric constant during compilation in visual c visual c has pragma message that outputs a string into compiler output now i have a factorytemplateclass typeccomptrtype createcomobject ccomptrtype newobject new ccomobjecttype do some tuning to the object return newobjectand i want to output the size of class that is passed to new namely sizeof ccomobjecttype into the compiler output looks like pragma message only accepts stringshow can i output a compiletime numeric constant,['c++'] +145579,mapping java date object to xml schema datetime format i am having some problem mapping my java data type to standard schema date data typei have a simple class that i annotated like this the period instance variable is of java date object typexmlaccessortypevalue xmlaccesstypenonepublic class chart xmlelement private double amount xmlelement private double amountdue xmlelement private date period constructor getters and settershere is my web servicewebservicepublic class chartfacade webmethod public chart getchart throws parseexception simpledateformat df new simpledateformatymmdd chart chart new chart200205 dfparse20010101 return chart my problem is it returns the date data in a format not according to what i am expectingsenvelope xmlnss sbody ns2getchartresponse xmlnsns2 return amount200amount amountdue205amountdue period20010101t010800period return ns2getchartresponse sbodysenvelopei wanted the period element to be returned like thisperiod20010101periodis there any way i can achieve this,['java'] +145608,what does pragma once mean in c possible duplicatepragma help understanding i saw the pragma many timesbut always confused anyone knows what it doesis it windows only,['c'] +145612,fast implementation of trigonometric functions for c short version i would like to know whether there are implementations of the standard trigonometric functions that are faster than the ones included in mathhlong version i got a program that is quite heavy on numerics it is a physics simulation and that needs to call trigonometric functions mostly sin and cos a lot currently i am simply using the implementations included in mathh profiling shows that the calls to these functions cost more than i was expecting hopingwhile there is most certainly plenty of room for optimization in other parts of the code having faster sin and cos might give me some additional percent so do you guys have any suggestionsin another post the usage of selfmade lookup tables is suggested but maybe there are alternatives or readymade and well tested lookup solutions in some libraries,['c++'] +145615,how to write hover condition for abefore and aafter how to write hover and visited condition for abeforei am trying abeforehover but it is not working,['css'] +145636,check whether an input string contains number i want to check whether an input string contains numberi am trying to validate an input field i want it to contain only alphabet not numbers,['javascript'] +145639,facebook connect showing blank popup on login in internet explorer 8 i am integrating facebook login to my application and it is working fine in browsers except ie it opens the login window after login redirecting to proxyphp and got stuck there thisplaying a blank page in the popup in other browsers it will close the popup and redirect to my site my application url is like so i have given the domain name devmysitecom in facebook application settings i am using facebook javascript sdk and my site is in php some one please help me to figure out the actual problem thanks in advance,['javascript'] +145640,update multiple records in sql how can i update multiple records in a single statement like this with sqlupdate records set nameabc where id3 set namedef where id1,['sql'] +145653,swig ctopython int array i am trying to access a c function with the following prototype from python using swigint cosetcodingint writtendatain int newdata const int memorycells int cellfailure int failedcellswig creates the so with no problems and i can import it into python but when i try to access it with the following cosetcodingcosetcoding101180i get the following tracebacktraceback most recent call last file stdin line 1 in moduletypeerror in method cosetcoding argument 4 of type int the pointer is supposed to be an int array with size defined by memorycells,"['python', 'c']" +145654,will multiple calls to typeidtname return the same pointer in c i can use typeid operator to retrieve the name of any polymorphic classconst char name typeid cmyclass namethe string pointed to by the returned const char will be available to my program for as long as the corresponding class existswill multiple calls of typeidtname return the same pointer value for the same class t or are they allowed to return different pointers,['c++'] +145663,is there a way to thisable android listview animation when we drag a listview to the end or to the top we can always drag it a little further and it will show a blank background then when we release it the listview will bounce back it is a default animation effect of listviewi would like to thisable this animation effect,['android'] +145673,formatting events according to start time still working on my plannercalendar application i am nearly done i got some of the harder parts working but i am stuck at one more difficult part i want to show my events in a grid according to their start time it does not show in this picture but pretend there is a column with hours 8am 11pm or so at the left of the 25th if an event starts at say 1pm i would like it to show somewhere in the middle of the page if an event starts at 830 am it should show between 8am and 9am i guess i could do this with tables but i was wondering if there is another way is this doable with plain htmlcss perhaps some javascript any suggestions on what the best way would be to achieve this if i use a table i am still not sure what would be the best way to do this a cell for every thirty minutes i have access to the start and end time of each event from my view an event array in this example the 25th looks like thisarray1 array title ethiek description ethiek opdracht 1 time start 1130 time end 120 2 array title project management description test project management time start 150 time end 160 event count 2i appreciate any advice you can give me thanks a lotedit started a bounty on this because i am still stuck and i would appreciate some feedback updatei have been breaking my head over this and i honestly cannot figure out the best way to do this first of all i think the reason i am stuck is the way i read out my events from the dbarray this is the code i have to thisplay the events as seen in my screenshot do not mind my complex arrays foreachdetails0 as key detail echo div classgrid header p classdetail header header ucfirstdates0keyname key initcurr month name header img src base url assetsimagescreate eventpng altplan ietsp echo header fori 1 i details0keyevent count i echo div classevent details0keyitype echo p classevent title details0keyititle p echo details0keyidescription echo div echo div it is a bit of a mess not to mention that i have the same code another time to fix some exceptions but more importantly i feel like those loops do not allow me to make a lot of modifications to it i tried adding two divs for am and pm so i could split up the events in beforenoon and afternoon blocks and then just thisplay the time on the event to avoid having to work with a thousand blocks of 15 minutes but yeah that did not work out since it would put a couple of pm divs if there is more than one event in the afternooni am tempted to just leave it like it is for now and just thisplay the startend time in the event divs until i figure out a better way to read them from the array and thisplay them any helpsuggestions appreciated thanks,"['php', 'jquery', 'html', 'css']" +145694,how can i see which wakelocks are active for some reason my android phone would not go to sleep i assume that a wakelock is keeping it awake but there is no way to tell which wakelocks are active the running services does not list anything suspicious and certainly nothing different from usual so my questions aredoes android definitely release wakelocks when a process ends is it possible an app was badly written and did not release a wakelock before exitingis there any way to see the active wakelocksthis is what dumpsys power shows dumpsys powerpower manager state mispoweredtrue mpowerstate0 mscreenofftime226093 ms mpartialcount0 mwakelockstate muserstate mpowerstate mlocksgather mnexttimeout91922738 now92136117 213s from now mdimscreentrue mstayonconditions0 mscreenoffreason3 muserstate0 mbroadcastqueue1 mbroadcastwhy0 mpokey1 mpokeawakeonsetfalse mkeyboardvisiblefalse museractivityallowedfalse mkeylightdelay60 mdimdelay470 mscreenoffdelay70 mpreventscreenonfalse mscreenbrightnessoverride1 mbuttonbrightnessoverride1 mscreenofftimeoutsetting60 mmaximumscreenofftimeout2147483647 mlastscreenontime0 mbroadcastwakelockunsynchronizedwakelockmflags0x1 mcount0 mheldfalse mstayonwhilepluggedinscreendimlockunsynchronizedwakelockmflags0x6 mcount0 mheldfalse mstayonwhilepluggedinpartiallockunsynchronizedwakelockmflags0x1 mcount0 mheldfalse mpreventscreenonpartiallockunsynchronizedwakelockmflags0x1 mcount0 mheldfalse mproximitypartiallockunsynchronizedwakelockmflags0x1 mcount0 mheldfalse mproximitywakelockcount0 mproximitysensorenabledfalse mproximitysensoractivefalse mproximitypendingvalue1 mlastproximityeventtime0 mlightsensorenabledfalse mlightsensorvalue10 mlightsensorpendingvalue10 mlightsensorscreenbrightness35 mlightsensorbuttonbrightness255 mlightsensorkeyboardbrightness0 musesoftwareautobrightnesstrue mautobrightessenabledfalse mscreenbrightness animatingfalse targetvalue1 curvalue00 delta134mlockssize0mpokelockssize1 poke lock phoneapp poke lock ignore cheek events,['android'] +145701,cropping image captured by avcapturesession i am writing an iphone app which uses avfoundation to take a photo and crop itthe app is similar to a qr code reader it uses a avcapturevideopreviewlayer with an overlaythe overlay has a square i want to crop the image so the cropped image is exactly what the user has places inside the squarethe preview layer has gravity avlayervideogravityresizeaspectfillit looks like what the camera actually captures is not exactly what the user sees in the preview layer this means that i need to move from the preview coordinate system to the captured image coordinate system so i can crop the image for this i think that i need the following parameters1 ration between view size and captured image size2 information which tells which part of the captured image matches what is thisplayed in the preview layerdoes anybody know how i can obtain this info or if there is a different approach to crop the imageps capturing a screenshot of the preview is not an option as i understand it might resulting in the app being rejectedthank you in advance,['iphone'] +145726,interpreting return value of function directly as an array is there a way in php to interpret the return value of a function directly as an arraylets say i have a functionfunction getarray return arrayfoo barinstead of writingarray getarrayvar array1i want to access bar directly somewhat likevar getarray1 this causes an error,['php'] +145737,whats the underlying reason this comparison fails surprising result for me context i am prototyping in prep for maybe converting my winforms app to wpfi make very simple tree view event handler for which the code isvar treeviewitem treeviewitemenewvaluevar treeviewitemtag treeviewitemtagif treeviewitemtag viewforams objectqueryaccountmanagerview oq entitiesaccountmanagerviews var q from c in oq select c datagrid1itemssource qtolistand the xaml iswindow xclassaccountingwpfapplication1mainwindow xmlns xmlnsx titlemainwindow height350 width525 loadedwindow loaded dockpanel treeview nametreeview1 itemssourcebinding folders selecteditemchangedtreeview1 selecteditemchanged treeviewitem headeraccount manager view tagviewforams treeview datagrid autogeneratecolumnstrue namedatagrid1 dockpanelwindowwhen i ran it i fully expected to see my data grid get populated but the comparison failed on the second line of code abovethe debugger shows thisquestion why were there no compile or runtime errors same question another way what is actually being compared such that the operator outputs false,['c#'] +145748,how can i indent ruby and rails code in vim i just wonder if ita s possible to auto indent rails code in vim instead of thisvalidates email presence true format with email regex uniqueness case sensitive false to thisvalidates email presence true format with email regex uniqueness case sensitive false,"['ruby-on-rails', 'ruby']" +145779,check if div with certain class name exists using jquery i am programmatically generating a bunch of divs like thisdiv classmydivclass idmyid1some text1divdiv classmydivclass idmyid2some text2divsomewhere else in my code i need to detect if these divs exist the class name for the divs is the same but the id changes for each div any idea how to detect them using jquery,"['javascript', 'jquery']" +145784,how do i print the result of an objectivec class method in gdb when using gdb via the debug console to debug an ipad program in xcode 4 i am trying to print out the result of running a class methodgdb po myclass foobargdb outputs the followingno symbol myclass in current contextis there some way to print the result of nsstring foonsstring string using gdb in xcode 4,['objective-c'] +145793,php add item to beginning of associative array how can i add an item to the beginning of an associative array for example say i have an array like thisarr arraykey1 value1 key2 value2when i add something to it as in arrkey0 value0 i getarray key1 value1 key2 value2 key0 value0how do i make that to bearray key0 value0 key1 value1 key2 value2thankstee,['php'] +145811,onpause onrestore with savedinstancestate i am pretty new to android development and i need some help saving the state of an activitywhat is the correct way to save the instance from onpause and restoring it from onrestore since obviously android is not sending the savedinstancestate bundle as it does with oncreate or onsaveinstancestate for example or is there a better way to save other than using the savedinstancestate bundledoes this make senseeditok i think i know what my real problem is but first i think what i was looking for was to use sharedpreferences instead of savedinstancestateso doing more debug log watching i am noticing that instead of bringing the activity to the top of the stack it is creating a new one yes i realize i am creating a new one intent itemintent new intentmedialistthis audioplayerclass bundle b new bundle putstring some strings to send itemintentputextraandroidintentextraintent b itemintentsetflagsintentflag activity reorder to front startactivityforresultitemintent0but is not flag activity reorder to front supposed to stop it from creating a new activity i am guessing it thinks it has to create a new one since i am sending along some stringsbetter yet how can i check if the activity is already in the stack and switch to it as long as the strings are the same i am starting this activity when the user clicks a media item from a listviewedit,['android'] +145836,how to unit testing delaysign assemblies using nunit we have a project that all assemblies are delaysigned the development machines are set to skip verification using snexe tool snexe vr public key token hereif we test those assemblies using nunit gui version the test would not work all tests are failed because of delaysigned but if those assemblies are resigned the test works were all know that to resign an assembly we need private public key pair file eg mycompanysnk we do not think it is a good practice give the mycompanysnk file to all developersis there any solution so that every developer can unittesting their assemblies without reresigning or without the need of mycompanysnk file,['.net'] +145854,how to trigger validation without using a submit button i am using the jquery validation plugin and trying to trigger the validationsubmit with an alternate button i would like to create a jquery function that will change the css and then run the validate function i have looked at previously answered questions but have not found any that address this issue with regards to the validation plugin and and the submithandler function any suggestions update to question the button that i would like to use is placed outside of the form what is the best way to submit and validate a form with a button located outside of that formhere is the codeeditbuttonclickfunctionevent postaccordion2csspaddingbottom 0pxeditbuttoncssthisplaynoneapplicantformvalidate submithandler functionform formajaxsubmit type post data firstname firstnameval lastname lastnameval datatype json url includesajaxtestphp error function alertdoh success function alertyippee return false errorplacement functionerrorelement return true rules firstname required true minlength 1 lastname required true,['jquery'] +145861,modify nsevent to send a different key than the one that was pressed i am trying to create an os x keyboard hook for assistive technology purposes ie do not worry not a keyloggerwhen a user presses a key i want to prevent the real keypress and send a fake keypress character of my choosing insteadi have the following code void hookthekeyboard cgeventmask keyboardmask cgeventmaskbitkcgeventkeydown id eventhandler nsevent addglobalmonitorforeventsmatchingmaskkeyboardmask handlernsevent keyboardevent nslogkeydown c keyboardevent characters characteratindex0 want to stop the keyboard input want to send another key input instead any help accomplishing either of those goals basically modifying the nsevent keyboardevent to send a different character thanks,['objective-c'] +145904,how to print nsmutableurlrequest how to print nsmutableurlrequest using nslog,"['iphone', 'objective-c']" +145909,nsurlconnection delegate methods are not called i am trying to create a simple nsurlconnection to communicate with a server using a get request connection works well but delegates methods of nsurlconnection are never calledhere is what am doingnsstring post nsstring stringwithformatkey1key2key3fkey4 val1 val4 val3 val4nsmutableurlrequest request nsmutableurlrequest alloc init autorelease request seturlnsurl urlwithstringnsstring stringwithformat postnsurlconnection connection nsurlconnection alloc initwithrequestrequest delegateselfconnection starthave implemented the following delegate methods but none of them is calledvoidconnectionnsurlconnection connection didfailwitherrornserror error nslogdid failvoidconnectionnsurlconnection connection didreceivedatansdata data nslogdid receive datavoidconnectionnsurlconnection connection didreceiveresponsensurlresponse response nslogdid receive response voidconnectiondidfinishloadingnsurlconnection connection nslogdid finish loading connection releaseam i missing something,['iphone'] +145927,what is the reason behind the advice that the substrings in regex should be ordered based on length longest first p recompilesupermanutdsupermanusupermansupermsupershortest first p recompilesupersupermsupermansupermanusupermanutdwhy is the longest first regex preferred,['python'] +145931,how to detect browser type and its version how can i detect browser type and its version in rails i want to put check on the version of specific browser and if its not required browser version than ask user to upgrade it i use below specified command but as its not following a standard pattern am unable to use itrequestenvhttp user agent chrome out put is belowmozilla50 windows u windows nt 51 enus applewebkit53416 khtml like gecko chrome100648205 safari53416safari out put is belowmozilla50 windows u windows nt 51 enus applewebkit533211 khtml like gecko version505 safari533211firefox out put is belowmozilla50 windows nt 51 rv20 gecko20100101 firefox40opera out put is belowopera980 windows nt 51 u en presto28131 version10internet explorer out put is belowmozilla40 compatible msie 80 windows nt 51 trident40 net clr 2050727,"['ruby-on-rails', 'ruby']" +145932,android file download in background i want to download the file from internet and store in external memorythe main thing is it should be downloaded in background like marketwhen click on install it will download the apk fileif some one have any idea then please tell methank you,['android'] +145972,what is the purpose of bootstrap in zend i am wondering what is the real purpose of bootstrap in zend framework what are the methods that go into the bootstrap class any tutorial links could be helpful please forgive me if the question is so vague i am trying to learn zend but the tutorials and books are skipping steps and they are not so clear in the framework website all i can learn from the quick start is that it helps to start the session am i right in thinking that the bootstrap runs first before any controller loads can i write any methods in bootstrap which i need to load from the beginning how do i access those bootstrap methods in controller,['php'] +145996,simple slickgrid sorting does not work is there obvious reason why this slickgrid example should not work basically it does not sort on clicking columns var grid var columns idtitle nametitle fieldtitle sortable true idduration nameduration fieldduration sortable true id name complete fieldpercentcomplete sortable true idstart namestart fieldstart sortable true idfinish namefinish fieldfinish sortable true ideffortdriven nameeffort driven fieldeffortdriven sortable true var options enablecellnavigation true enablecolumnreorder false function var data for var i 0 i 500 i datai id i title task i duration 5 days percentcomplete mathroundmathrandom 100 start 01012009 finish 01052009 effortdriven i 5 0 var dataview new slickdatadataview grid new slickgridmygrid dataview columns options function comparerab var x asortcol y bsortcol return x y 0 x y 1 1 var sortcol json number var sortdir 1 gridonsortsubscribefunctione args sortdir argssortasc 1 1 sortcol argssortcolfield using native sort with comparer preferred method but can be very slow in ie with huge datasets dataviewsortcomparer argssortasc dataviewbeginupdate dataviewsetitemsdata dataviewendupdate gridinvalidate gridrender mygridshow,['javascript'] +146014,wpf slow template instantiation i have a wpf application and it is slowit is not the rendering firstly the rendering is quite simple and secondly i looked at it with wpf performance toolkit nothingit is not in my own code firstly the unit tests work fast and secondly if i replace all datatemplates with blank ones everything works fastso far it looks like the slow part is template instantiation that is when you start the application and open some complicated screen it takes a lot of time and by a lot i mean a lot sometimes can be as much as 35 seconds for example when there is a datagrid with 100 rows but when you go to another tab and then go back to that same screen it opens fast as long as its viewmodel stays putthis is very annoying not just because it is slow but because i cannot do anything about it if i had some control over the slowness i could maybe thisplay some opening please wait message or somethingbesides when i look at some other wpf applications most notably ilspy they seem to work reasonably fast despite the large amounts of data this makes me believe that i am probably doing something wrong but i have no idea where to startany ideas any classic mistakes any tips,['c#'] +146026,and vs list and dict which is better i understand that they are both essentially the same thing but in terms of style which is the better more pythonic one to use to create an empty list or dict,['python'] +146027,c interface multiple inheritance with same method i need to inherit from two interfaces which both have the same method which in both cases should perform exactly the same thing is this code correct or not i need this for some kind of proxy class thanks for answersclass innerinterface virtual int getid const 0 class outerinterface virtual int getid const 0 class foo public innerinterface public outerinterface virtual int getid const all abstract methods,['c++'] +146044,how to open all txt and log files in the current directory search and print the file the search was found i am trying to search for a string in all text and log files in the current directory and if it finds a match print the text or log file where the match was found is this possible and how can i manipulate the code below to accomplish this task file openlogfile r userstring raw inputenter a string name to search for line in filereadlines if userstring in line print line,['python'] +146053,what design pattern can i use to emulate traits mixins in php since traits are not available in php 53 afaik i need to emulate some of the functionality they offer interfaces would not work because i need concrete functionality problemi have two client classes that need to share some functionality but extend from different base classesclassa extends foo classb extends bar i need to be able to implement a function called getcomponent in both classes and it needs to be functionality identicalchanging the base class is not an option i was thinking to do something like thisclass componenthandler function getinstance return singleton function getcomponent required functionality class a extends foo var handler function construct thishandler componenthandlergetinstance i would implement this constructor in both classa and classb in my client i would make calls like thisclass new classaclasshandlergetcomponentclass new classbclasshandlergetcomponent,['php'] +146058,easy install with various versions of python installed mac osx i have various versions of python on a mac osx 106 machine some of them installed with macports python select lavailable versionscurrent none python24 python26 python26apple python27the default or system version is python26apple i am now using python27 which i selected with sudo python select python27i recently tried installing django using easy install but it got installed with the default python i can check that by python selecting python26apple and importing django if instead i download the django tarball expand and use sudo python setuppy installeverything works as expected ie i get django in python 27 now the question is is there a way to get easy install to work with the version of python i have selected with python select update apparently python select is deprecated the following command seems to be equivalentport select list pythonproducingavailable versions for python none python24 python26 python26apple python27 active,['python'] +146064,input name and id changes when set runatserver in my form i need to insert different inputs of type text the inputs must be html controls with name and ids because i send this form to a external urlfor the validation i do runatserver in all inputs and then i can use requiredfieldvalidatorbut the problem is when i look in the source after visiting the page the name and ids are all changedfor exampleinput idfirst name classformright typetext namefirst name runatserver changes to input namectl00cphcontentfirst name typetext idctl00 cphcontent first name classformrighti have to use html controls because the external postbackurl looks at the name and id values to find the control so i cannot use asp controls it is because of that i used html controls with runatserveri appreciate any help,"['.net', 'asp.net']" +146082,is this a good approach for temporarily changing the current threads culture i work on a fairly large asp net web forms application that is currently used primarily in the united states we are in the process of rolling it out to other parts of the world which of course means we are currently working on localizing all areas of the application generally speaking our approach has been to set the current threads currentculture and currentuiculture properties at the beginning of each request to support the proper formatting and resource extraction based on the current users localein some cases however we have a need to run a certain bit of a code using a culture other than the culture of the current user for example user a lives in germany but works for a company that does business with other companies in france when user a wants to create an invoice pdf for one of those french companies we want that invoice generation code to run with the frfr culture rather than the dede culturei have considered a couple ways of doing this easily and am wondering if i am going about this correctly my main concerns are around performance and thread safetyone approach involves a static method designed to run a given task with a provided culture something like this public static void runwithculturecultureinfo culture action task if culture null throw new argumentnullexceptionculture var originalculture new culture threadcurrentthreadcurrentculture uiculture threadcurrentthreadcurrentuiculture try threadcurrentthreadcurrentculture culture threadcurrentthreadcurrentuiculture culture task finally threadcurrentthreadcurrentculture originalcultureculture threadcurrentthreadcurrentuiculture originalcultureuiculture this method could then be invoked like thisvar customerculture new cultureinfocurrentcustomerlocaleculturerunnerrunwithculturecustomerculture invoiceservicecreateinvoicecurrentcustomercustomeridi have also considered creating a class that implements ithisposable that would be responsible for setting the thread culture in it is ctor and then returning the original cultures back in the thispose method so you could call it like thisvar customerculture new cultureinfocurrentcustomerlocaleusingnew culturerunnercurrentcustomerlocale invoiceservicecreateinvoicecurrentcustomercustomeridam i going about this all wrong which if any of these approaches is preferable,"['c#', '.net']" +146090,reasons to strongly type parameters in pdo when you bind parameters to sql statement you can provide parameter type like pdoparam str if you do not type defaults to pdoparam str what can be the reasons to specifically set the type of each parameter pdoparam str works with any parameter as i know at least in mysql i think even with pdoparam str can be used even with blob columnspdoparam str does not introduce any sql injection because you still have prepared queries,['php'] +146111,interactive shell using php just wondering is it possible to create an interactive shell using php alone i mean something like you have with databases python etcif it is how,['php'] +146163,wpf propertychangedcallback triggered only once i have a user control which exposes a dependencyproperty called visibileitemsevery time that property gets updated i need to trigger another event to achieve that i added a frameworkpropertymetadata with propertychangedcallback event for some reason this event gets called only once and does not trigger the next time visibleitems is changed xamlccmyfilterlist visibleitemsbinding currenttables currenttables is a dependencyproperty on myviewmodel currenttables gets changed often i can bind another wpf control to currenttables and i see the changes in the ui here is the way i wired visibleitems with propertychangedcallback public static readonly dependencyproperty visibleitemsproperty dependencypropertyregister visibleitems typeofilist typeofmyfilterlist new frameworkpropertymetadatanull frameworkpropertymetadataoptionsaffectsrender new propertychangedcallbackvisiblepropertychanged public ilist visibleitems get return ilistgetvaluevisibleitemsproperty set setvaluevisibleitemsproperty value by stepping into visiblepropertychanged i can see that it gets triggered the first time currenttables gets set but not subsequent times updateas some of you questioned the way currenttables is modified it is reassigned completely on change ondbchangecurrenttables new liststringmaindatabasedataadaptergettablesthisselectedserver thisselecteddatabasethis line gets called on every change but my visiblepropertychanged handler gets called only the first time updateif i assign visibleitems directly the handler does get called every time testfilterlistvisibleitems new liststring enumerablerange1 datetimenowsecondtolistselects stostringtolist so it looks like the problem stems from the dependencyproperty visibleitems watching another dependencyproperty currenttables somehow the binding works on first property change but not on subsequent onesattempting to inspect this issue with snoop as some of you suggested,"['c#', '.net']" +146178,mysql string last index of i am able to use locate to get the index of a character such as a in wgooglecom thus i can use substring to strip out everything before the first is there a way i can look for the last so i can get testhtm out of i do not want to say the 6th slash i want to say the last slash can this be done,['mysql'] +146189,ruby boolean double negation convention can anybody tell me why a lot of ruby boolean methods use this double negation conventionboolean expression,['ruby'] +146213,maven noclassdeffounderror in the main thread i am currently building a little apachemina server app i am using maven to build itwhen i try to run the jar i get the following error exception in thread main javalangnoclassdeffounderror orgapacheminafiltercodecprotocolcodecfactory caused by javalangclassnotfoundexception orgapacheminafiltercodecprotoc olcodecfactory at javaneturlclassloader1runurlclassloaderjava202 at javasecurityaccesscontrollerdoprivilegednative method at javaneturlclassloaderfindclassurlclassloaderjava190 at javalangclassloaderloadclassclassloaderjava307 at sunmisclauncherappclassloaderloadclasslauncherjava301 at javalangclassloaderloadclassclassloaderjava248could not find the main class defr1zlegpsservergpsserver program will exitrunning in eclipse is not a problemthis is what the generated manifest looks likemanifestversion 10archiverversion plexus archivercreatedby apache mavenbuiltby fr1zlebuildjdk 160 23mainclass defr1zlegpsservergpsserverclasspath commonslang21jar plexusutils11jar junit482jar log4j1214jar slf4jjdk141511jar slf4japi1511jar antlr2 76jar commonscollections31jar dom4j161jar hibernatecommons annotations320finaljar hibernatejpa20api100finaljar jt a11jar hibernateannotations356finaljar hibernatecore356 finaljar mysqlconnectorjava5115jar minacore203jarand this is part of my pomxmlgroupiddefr1zlegpsservergroupid artifactidgpsserverartifactid version001snapshotversion namegpsservername packagingjarpackaging descriptiontracks location of gps modules and the information they submitdescription build plugins plugin groupidorgapachemavenpluginsgroupid artifactidmavenjarpluginartifactid version231version configuration archive manifest addclasspathtrueaddclasspath mainclassdefr1zlegpsservergpsservermainclass manifest archive configuration plugin plugin groupidorgapachemavenpluginsgroupid artifactidmavencompilerpluginartifactid version232version configuration source16source target16target configuration plugin plugins buildwhat am i doing wrong here,['java'] +146214,how to write a jquery function with a callback i have the following functionfunction loadprojectspid ajax url myurl success function datajs x i call this function like so loadprojects1issue is i want to be able to define a callback function after success and i would like to include it when i do loadprojects1 callbackwhatever js is included here gets called back after successhow can i have a function accept a callbackhow can i pass a callback to that functionthanks,"['javascript', 'jquery']" +146220,read a file with unicode characters i have an aspnet c page and am trying to read a file that has the following charater a and convert it to from slanted apostrophe to apostrophefileinfo fileinfo new fileinfofilelocationstring content filereadalltextfileinfofullnamestrip out bad characterscontent contentreplacea this does not work and it changes the slanted apostrophes into marks,"['c#', 'asp.net']" +146222,failed to execute goal maveninstallplugin failed to install artifact access is denied i often getting the following error when compiling a maven project with netbeansfailed to execute goal orgapachemavenpluginsmaveninstallplugin231install defaultinstall on project x failed to install artifact y cm2repository100jar access is denied help 1i do not know what is causing it solution is to erase the problematic m2 content manually and the issue goes but it is annoying anyone has a permanent solutionediterror failed to execute goal orgapachemavenpluginsmaveninstallplugin231install defaultinstall on project plasma failed to install artifact netdwstplasmajar100 cm2repositorynetdwstplasma100plasma100jar access is denied help 1 orgapachemavenlifecyclelifecycleexecutionexception failed to execute goal orgapachemavenpluginsmaveninstallplugin231install defaultinstall on project plasma failed to install artifact netdwstplasmajar100 cm2repositorynetdwstplasma100plasma100jar access is denied at orgapachemavenlifecycleinternalmojoexecutorexecutemojoexecutorjava203 at orgapachemavenlifecycleinternalmojoexecutorexecutemojoexecutorjava148 at orgapachemavenlifecycleinternalmojoexecutorexecutemojoexecutorjava140 at orgapachemavenlifecycleinternallifecyclemodulebuilderbuildprojectlifecyclemodulebuilderjava84 at orgapachemavenlifecycleinternallifecyclemodulebuilderbuildprojectlifecyclemodulebuilderjava59 at orgapachemavenlifecycleinternallifecyclestartersinglethreadedbuildlifecyclestarterjava183 at orgapachemavenlifecycleinternallifecyclestarterexecutelifecyclestarterjava161 at orgapachemavendefaultmavendoexecutedefaultmavenjava316 at orgapachemavendefaultmavenexecutedefaultmavenjava153 at orgapachemavenclimavencliexecutemavenclijava451 at orgapachemavenclimavenclidomainmavenclijava188 at orgapachemavenclimavenclimainmavenclijava134 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava39 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava25 at javalangreflectmethodinvokemethodjava597 at orgcodehausplexusclassworldslauncherlauncherlaunchenhancedlauncherjava290 at orgcodehausplexusclassworldslauncherlauncherlaunchlauncherjava230 at orgcodehausplexusclassworldslauncherlaunchermainwithexitcodelauncherjava409 at orgcodehausplexusclassworldslauncherlaunchermainlauncherjava352 caused by orgapachemavenpluginmojoexecutionexception failed to install artifact netdwstplasmajar100 cm2repositorynetdwstplasma100plasma100jar access is denied at orgapachemavenplugininstallinstallmojoexecuteinstallmojojava139 at orgapachemavenplugindefaultbuildpluginmanagerexecutemojodefaultbuildpluginmanagerjava107 at orgapachemavenlifecycleinternalmojoexecutorexecutemojoexecutorjava195 19 more caused by orgapachemavenartifactinstallerartifactinstallationexception failed to install artifact netdwstplasmajar100 cm2repositorynetdwstplasma100plasma100jar access is denied at orgapachemavenartifactinstallerdefaultartifactinstallerinstalldefaultartifactinstallerjava110 at orgapachemavenplugininstallinstallmojoexecuteinstallmojojava103 21 more caused by orgsonatypeaetherinstallationinstallationexception failed to install artifact netdwstplasmajar100 cm2repositorynetdwstplasma100plasma100jar access is denied at orgsonatypeaetherimplinternaldefaultinstallerinstalldefaultinstallerjava279 at orgsonatypeaetherimplinternaldefaultinstallerinstalldefaultinstallerjava190 at orgsonatypeaetherimplinternaldefaultrepositorysysteminstalldefaultrepositorysystemjava322 at orgapachemavenartifactinstallerdefaultartifactinstallerinstalldefaultartifactinstallerjava106 22 more caused by javaiofilenotfoundexception cm2repositorynetdwstplasma100plasma100jar access is denied at javaiofileoutputstreamopennative method at javaiofileoutputstreamfileoutputstreamjava179 at javaiofileoutputstreamfileoutputstreamjava131 at orgsonatypeaetherimplinternaldefaultfileprocessorcopydefaultfileprocessorjava120 at orgsonatypeaetherimplinternaldefaultinstallerinstalldefaultinstallerjava255 25 more error error error for more information about the errors and possible solutions please read the following articles error help 1,['java'] +146234,backbonejs and its api confusion i have recently started using backbonejs i like the architecture in terms of features it is almost exactly what i need however i found the following caveatsfor collections get means something different than for models there is no set attributes should be accessed in a regular way i find it rather inconsistent it is easy to confuse models and collections sometimes is there anything that can be done to overcome thisassigning initial values inside modelextend does not always work for example assigning url will not override the default behaviour this can only be achieved through a call to set method again very error pronei still do not know whether it is required to use getset inside initialize calli do not understand why i cannot just call bindallthis inside initialize and i have to list specific function names to be bound like this bindallthis firstfunc secondfunc this is not very dryi would like to know what are the best practices regarding the mentioned situations what do you do to make the framework more consistent any monkey patching am i doing anything wrong against the conventioni would be grateful for any good real world examples i did find this and and those do not address any of the mentioned problems in fact they just present the simplest ideas and absolutely no border cases so anything more complicated could be usefuleditok and there is one more fundamental think i do not understandam i ever allowed to place additional attributes on extension like this var somemodel backbonemodelextend myattribute myvalue if so then why do not subsequent calls to new somemodelgetmyattribute work what exactly is this inside initialize is it model class or model instance edit2well i found this it looks like backbonejs 20 shares a similar name too have not tested it yet which might be a bit of a show stopper as the library is very recent however from the docs side of things it looks very promissing it gets rid of most of the problems that i found it simplifies the api it even gets rid of the dependency on underscorejs which for a library is a good thing i will post my further findings here,['javascript'] +146257,java get month string from integer is there a better way to compact this method ie reduce the cyclomatic complexity by avoid the switch casesstring monthstring switch month case 1 monthstring january break case 2 monthstring february break case 3 monthstring march break case 4 monthstring april break case 5 monthstring may break case 6 monthstring june break case 7 monthstring july break case 8 monthstring august break case 9 monthstring september break case 10 monthstring october break case 11 monthstring november break case 12 monthstring december break default monthstring invalid month break systemoutprintlnmonthstring,['java'] +146262,android remove space between tabs in tabwidget i have made an application which has tabs like in hellotabactivity there is also space between these tabs can anyone suggest how to remove this space and also there is a grey line beneath the tabs how can that be removedmainxmlxml version10 encodingutf8linearlayout xmlnsandroidandroidorientationverticalandroidlayout widthfill parentandroidlayout heightfill parenttabhost androididandroididtabhost androidlayout widthfill parent androidlayout heightfill parent linearlayout androidorientationvertical androidlayout widthfill parent androidlayout heightfill parent androidpadding5dp horizontalscrollview androidlayout widthwrap content androidlayout heightwrap content androidscrollbarsnone tabwidget androididandroididtabs androidlayout widthfill parent androidlayout heightwrap content horizontalscrollview framelayout androididandroididtabcontent androidlayout widthfill parent androidlayout heightfill parent androidpadding5dp linearlayouttabhostlinearlayoutstylesxmlxml version10 encodingutf8resourcesstyle namecustomtheme parentandroidstyletheme item nameandroidtabwidgetstylestylecustomtabwidgetitemstylestyle namecustomtabwidget parentandroidstylewidgettabwidget item nameandroidtextappearancestylecustomtabwidgettextitemstylestyle namecustomtabwidgettext parentandroidstyletextappearancewidgettabwidget item nameandroidtextsize10spitem item nameandroidtextstylebolditem item nameandroidtextcolor1589ffitem item nameandroidpadding3dipitemstyleresourcesactivitypublic class infralinetabwidget extends tabactivitypublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain resources res getresources resource object to get drawables tabhost tabhost tabhostgettabhost the activity tabhost tabhosttabspec spec resusable tabspec for each tab intent intent reusable intent for each tab create an intent to launch an activity for the tab to be reused intent new intentsetclassthis topnewsactivityclass initialize a tabspec for each tab and add it to the tabhost spec tabhostnewtabspectopnewssetindicatortop news resgetdrawablerdrawabletab newssetcontentintent tabhostaddtabspec do the same for the other tabs intent new intentsetclassthis poweractivityclass spec tabhostnewtabspecpowersetindicatorpower resgetdrawablerdrawabletab powersetcontentintent tabhostaddtabspec intent new intentsetclassthis energyactivityclass spec tabhostnewtabspecenergysetindicatorrenewable energy resgetdrawablerdrawabletab energysetcontentintent tabhostaddtabspec intent new intentsetclassthis coalactivityclass spec tabhostnewtabspeccoalsetindicatorcoal resgetdrawablerdrawabletab coalsetcontentintent tabhostaddtabspec intent new intentsetclassthis oilngasactivityclass spec tabhostnewtabspecoilngassetindicatoroil gas resgetdrawablerdrawabletab oilngassetcontentintent tabhostaddtabspec tabhostsetcurrenttab0 tabhostgettabwidgetgetchildat0setlayoutparamsnew linearlayoutlayoutparams10025 tabhostgettabwidgetgetchildat1setlayoutparamsnew linearlayoutlayoutparams10025 tabhostgettabwidgetgetchildat2setlayoutparamsnew linearlayoutlayoutparams10025 tabhostgettabwidgetgetchildat3setlayoutparamsnew linearlayoutlayoutparams10025 tabhostgettabwidgetgetchildat4setlayoutparamsnew linearlayoutlayoutparams10025now i want to remove the black spaces between the tabs and it should be like they are connected and also i am not able to remove the grey line below the tabsthanks,['android'] +146284,how to keep this from getting clipped when it exceeds the width of the page i am working with jquery mobile and one of my pages is giving me problemsi have a p embedded in a list like sodiv datarolepage div dataroleheader h1page 1h1 div div datarolecontent ul datarolelistview li datarolelistdivider list heading li li pa very long paragraph that bshouldb be wrapped when it exceeds the length of the visible linep li ul divdivno matter what i do the page looks something like thisthe p is getting clipped i tried wrapping it in a div but it remains the same since the p is pulled from an external source i would prefer solutions that do not modify the p or the contents of it,"['jquery', 'html']" +146293,simple postgresql statement column name does not exists i have been pulling my hair out i have a very simple postgre database one specific table has a column named lname uppercase n now i know with postgre i must quote lname since it contains an uppercase n i am trying to query the database with the following statementselect from employee where lname like smithbut i am receive this error warning pg query functionpgquery query failed error column smith does not exist in what is the issue here why is it saying the column is smith,['php'] +146299,add numeric pager to jqgrid does anyone know of a way to set up jqgrid to use a numeric pagerinstead of page 1 of 20 i want to have the paging be like 1234 and when i click on 4 it would something like 4567 i have seen how other grids do it but i cannot seem to find a built in way for jqgrid to do iti may have a way to implement it but i do not want to reinvent the wheel if there is something already out there it would involve me adding custom buttons after getting userdata from the grids data to determine the pages availableteleriks grid does it,['jquery'] +146313,error no such file to load sqlite3sqlite3 native loaderror my os is windows 7my problem is that when i try to run rails server an error occurs i have installed the sqlite3 gem even the sqliteruby gem and still nothingi already do not know what to do anymoreif anyone needs any additional information ask for it and i will put it upthe complete error iscruby192librubygems191gemssqlite3133x86mingw32libsqlite3rb6in require no such file to load sqlite3sqlite3 native loaderror from cruby192librubygems191gemssqlite3133x86mingw32libsqlite3rb6in rescue in top required from cruby192librubygems191gemssqlite3133x86mingw32libsqlite3rb2in top required from cruby192librubygems191gemsbundler1012libbundlerruntimerb68in require from cruby192librubygems191gemsbundler1012libbundlerruntimerb68in block 2 levels in require from cruby192librubygems191gemsbundler1012libbundlerruntimerb66in each from cruby192librubygems191gemsbundler1012libbundlerruntimerb66in block in require from cruby192librubygems191gemsbundler1012libbundlerruntimerb55in each from cruby192librubygems191gemsbundler1012libbundlerruntimerb55in require from cruby192librubygems191gemsbundler1012libbundlerrb120in require from cusersjorwandesktopjorwanascendstudiororintento2configapplicationrb7in top required from cruby192librubygems191gemsrailties307librailscommandsrb28in require from cruby192librubygems191gemsrailties307librailscommandsrb28in block in top required from cruby192librubygems191gemsrailties307librailscommandsrb27in tap from cruby192librubygems191gemsrailties307librailscommandsrb27in top required from scriptrails6in require from scriptrails6in main,['ruby-on-rails'] +146317,python sqlite create table if not exists problem i am having an issue using sqlite to create a table only if it does not exist basically i have a table that i am dropping and remaking once in a long while however if the table already existed before i drop and remake it then i get the following error when trying to insert for the first timetraceback most recent call last file testpy line 40 in module remake file testpy line 31 in remake insert record1 file testpy line 36 in insert record cexecutesqlsqlite3operationalerror no such table table nameat this point the table does not exist for some reason so the next time i run the script no errors occur basically if i keep running the test script exactly every other run will result in an error and i am stumped as to why but i have determined that creating the database without using if not exists fixes the issue i still do not know what the original problem is though and i would appreciate if anyone could point me in the right direction test script demonstrating the problem belowimport sqlite3location datatable name table namedef init global conn global c conn sqlite3connectlocation c conncursor create databasedef create database sql create table if not exists table name id integer cexecutesql conncommitdef create database2 sql create table table name id integer cexecutesql conncommitdef clear database sql drop table table name cexecutesql conncommitdef remake clear database create database replacing this with create database2 works every time insert record1 conncommitdef insert recordid sql insert into table name id values d id cexecutesql print inserted idinitremakethanks in advance,['python'] +146331,how to compare two nsurls that are practically equivalent but have cosmetic string differences under ios i wish to identify pairs of nsurls that are either identical or differ slightly but refer to the same destination for instance vs isequals reports those nsurls as diferent nor can i find a way to obtain a canonical or normalized form of an nsurl to compare those forms insteadnsurl a nsurl urlwithstringnsurl b nsurl urlwithstringifa isequalb nslogsame not runifa absoluteurl isequalb absoluteurl nslogsame still not runifa urlbystandardizingpath isequalb urlbystandardizingpath nslogsame still not runhow can i compare two nsurls while ignoring string differences that do not affect the intent of the url,"['iphone', 'objective-c', 'ios']" +146339,how to solve bidi bracket issues as you might know some languages are writtenread from right to left and we are trying to support some rtl languages for the web ui using dirrtl in html does most of the job thanks to algorithms that browsers have but i came across this issue with brackets in texthtmlheadmeta httpequivcontenttype contenttexthtml charsetutf8titlebracket problems with bidititleheadbodyp styledirection rtlbracket problem hello worldpp styledirection rtlno bracket problem hello world somethingpp styledirection rtlbracket problem u3uu 1u pp styledirection rtlno bracket problem u3uu 1u 1u pbodyhtmlproblem can be seen herescreenshotso i want that last bracket stay in the end what would be your solution,"['html', 'css']" +146347,how to create an html form with prefilled in instructions that clear when a user clicks in the box i have an html form form methodpost actionhttp username input typetext nameusername size15 password input typepassword namepassword size15 input typesubmit valuelogin div formwhat i need to do to make it so that the text fields have instructions in them that clear when a user clicks in the box so that i can save space and remove the words username and password from outside the forms,['html'] +146349,tomcat connection pool creating too many connections stuck in sleep mode i am using tomcat 6029 with tomcat 7s connection pool and mysql testing my application it does not reuse anything from the pool but ends up creating a new pool to eventually where i cannot use the database because there are hundreds of sleeping connections in the pool when the max active size for the pool is set to 20 see here for reference id user host db command time state info 2 root localhost51877 dbname sleep 9 null 4 root localhost null query 0 null show processlist 5 root localhost49213 dbname sleep 21 null 6 root localhost53492 dbname sleep 21 null 7 root localhost46012 dbname sleep 21 null 8 root localhost34964 dbname sleep 21 null 9 root localhost52728 dbname sleep 21 null 10 root localhost43782 dbname sleep 21 null 11 root localhost38468 dbname sleep 21 null 12 root localhost48021 dbname sleep 21 null 13 root localhost54854 dbname sleep 21 null 14 root localhost41520 dbname sleep 21 null 15 root localhost38112 dbname sleep 13 null 16 root localhost39168 dbname sleep 13 null 17 root localhost40427 dbname sleep 13 null 18 root localhost58179 dbname sleep 13 null 19 root localhost40957 dbname sleep 13 null 20 root localhost45567 dbname sleep 13 null 21 root localhost48314 dbname sleep 13 null 22 root localhost34546 dbname sleep 13 null 23 root localhost44928 dbname sleep 13 null 24 root localhost57320 dbname sleep 13 null 25 root localhost54643 dbname sleep 29 null 26 root localhost49809 dbname sleep 29 null 27 root localhost60993 dbname sleep 29 null 28 root localhost36676 dbname sleep 29 null 29 root localhost53574 dbname sleep 29 null 30 root localhost45402 dbname sleep 29 null 31 root localhost37632 dbname sleep 29 null 32 root localhost56561 dbname sleep 29 null 33 root localhost34261 dbname sleep 29 null 34 root localhost55221 dbname sleep 29 null 35 root localhost39613 dbname sleep 15 null 36 root localhost52908 dbname sleep 15 null 37 root localhost56401 dbname sleep 15 null 38 root localhost46 dbname sleep 15 null 39 root localhost57567 dbname sleep 15 null 40 root localhost56445 dbname sleep 15 null 41 root localhost39616 dbname sleep 15 null 42 root localhost49197 dbname sleep 15 null 43 root localhost59916 dbname sleep 15 null 44 root localhost37165 dbname sleep 15 null 45 root localhost45649 dbname sleep 1 null 46 root localhost55397 dbname sleep 1 null 47 root localhost34322 dbname sleep 1 null 48 root localhost54387 dbname sleep 1 null 49 root localhost55147 dbname sleep 1 null 50 root localhost47280 dbname sleep 1 null 51 root localhost56856 dbname sleep 1 null 52 root localhost58369 dbname sleep 1 null 53 root localhost33712 dbname sleep 1 null 54 root localhost44315 dbname sleep 1 null 55 root localhost54649 dbname sleep 14 null 56 root localhost41202 dbname sleep 14 null 57 root localhost59393 dbname sleep 14 null 58 root localhost38304 dbname sleep 14 null 59 root localhost34548 dbname sleep 14 null 60 root localhost49567 dbname sleep 14 null 61 root localhost48077 dbname sleep 14 null 62 root localhost48586 dbname sleep 14 null 63 root localhost45308 dbname sleep 14 null 64 root localhost43169 dbname sleep 14 null it creates exactly 10 for each request which is the minidle initialsize attribute as seen belowhere is the sample test code embedded into a jsp page the code is not the code in my application and just used to see if the issue was with my code but the problem still persistedcontext envctxenvctx context new initialcontextlookupjavacompenvdatasource datasource datasource envctxlookupjdbcdbnameconnection con nulltry con datasourcegetconnection statement st concreatestatement resultset rs stexecutequeryselect from useraccount int cnt 1 while rsnext outprintlncnt token rsgetstringusertoken firstnamersgetstringfirstname lastnamersgetstringlastname rsclose stclose finally if connull try conclosecatch exception ignore here is my contextxml filexml version10 encodingutf8context resource namejdbcdbname authcontainer typejavaxsqldatasource factoryorgapachetomcatjdbcpooldatasourcefactory testwhileidletrue testonborrowtrue testonreturnfalse validationqueryselect 1 validationinterval30 timebetweenevictionrunsmillis30 maxactive20 minidle10 maxwait10 initialsize10 removeabandonedtimeout60 removeabandonedtrue logabandonedtrue minevictableidletimemillis30 jmxenabledtrue jdbcinterceptorsorgapachetomcatjdbcpoolinterceptorconnectionstateorgapachetomcatjdbcpoolinterceptorstatementfinalizer username password driverclassnamecommysqljdbcdriver urljdbcmysqllocalhost3306dbnameautoreconnecttrueampuseunicodetrueampcharacterencodingutf8watchedresourcewebinfwebxmlwatchedresourcewatchedresourcemetainfcontextxmlwatchedresourcecontexti am sure i can use removeabandonedtimeout to a low number and it would purge all these sleeping connections but that wouldnt fix the real problem would it does anyone know what i am doing wrong thank you very much,"['java', 'mysql']" +146370,html input typefile get the image before submitting the form i am building a basic social network and in the registration the user uploads a thisplay imagebasically i wanted to thisplay the image like a preview on the same page as the form just after they select it and before the form is submittedis this possible,"['javascript', 'html']" +146379,weird behavior of uiview frame after rotation in iphone create a square uiview object testview and add this at viewdidload voidviewdidload super viewdidloadcgrect initialrect testview framenslogbefore rotation w f h f x f y f initialrectsizewidth initialrectsizeheight initialrectoriginx initialrectoriginytestview transform cgaffinetransformmakerotation01nslogafter rotation w f h f x f y f testview framesizewidth testview framesizeheight testview frameoriginx testview frameoriginytestview frame initialrectnslogreassign w f h f x f y f testview framesizewidth testview framesizeheight testview frameoriginx testview frameoriginyi receive this in the console20110427 123032492 test31890207 before rotation w 10 h 10 x 20 y 2020110427 123032494 test31890207 after rotation w 109483757 h 109483757 x 15258121 y 1525812120110427 123032495 test31890207 reassign w 117873589 h 10 x 11063205 y 20i could not figure out the logic behind this change in frame value especially the last one can anyone enlighten me thanks,['iphone'] +146380,javascript nodejs getting line number in try catch i am using try catch on a nodejs scripttry catch err consolelogerri get an output like this stack gettersetter arguments undefined type called non callable message gettersetter is there an easy way to make this more informative include line numbers and function names and such,['javascript'] +146385,how to make a block element adjust to the size of what is inside it if i have this htmlli classnamehilili classnamehellolili classnamewheli and this cssliname border 1px solid a38870 backgroundcolor fa682d liststyle none margin 15px padding 5pxthe background extends all the way across the page like thishow can i make the background adjust to the size of the text like this without explicitly setting the width for each list element,"['html', 'css']" +146397,shake the device to launch an application in android how can we launch a application by just shaking the device i want to do something similar to the app appshaker,['android'] +146403,sql select to find cyclic references in fatheridorganized tree fun with cyclic referencessuppose i have a table elements which contain a hierarchy of elements modeled by a father idthe father id field is null for the rootall other records have a nonnull father id with the autosequenced primary key id of the father elementfor example using select from elementswhere father id not in select id from elementsi can find all elements that have invalid father references father id is not a foreign key let us assume that in this examplebut how can i find elements that do have a valid father reference but whose chain of father references does not end in the root i think this can only happen for cyclic references for example a is the father of b but b is the father of a too such a subtree is not linked to the root and thus is not part of the main tree i want to find such subtreesof course i am looking for a query that delivers those elements that lead to a cyclic reference no matter how long the chain of references may be is that possible in sql or do i need an iterative solution,['sql'] +146438,relationship between important and css specificity looking at the css specificity specification there is no mention about how many points the important rule is worthwhen does one override another what happens if one is declared after the other which rule is declared to be more important is there some sort of patternfrom the looks of it important applies to what has more specificity points to begin with but what will happen if i declare a bazillion ids stacked with classes and nested deeply will it override the rules set in another less specified rule marked with important,['css'] +146441,youtube upload quality i am using googles gdata api in order to upload a video to youtube from my app the upload works fine however the quality of the video uploaded is only 360p whereas the quality of the original video is 720p is this working as intended if so is there any way around this video compression that will allow my app to upload hq moviesheres the code i am using to achieve the video upload if that is any help gdatayoutubemediagroup mediagroup gdatayoutubemediagroup mediagroupmediagroup setmediatitletitlemediagroup setmediadescriptiondescmediagroup addmediacategorycategory mediagroup setmediakeywordskeywordsmediagroup setisprivatenonsstring mimetype gdatautilities mimetypeforfileatpathoutputurlrelativepath defaultmimetypevideoquicktimegdataentryyoutubeupload entryentry gdataentryyoutubeupload uploadentrywithmediagroupmediagroup datadata mimetypemimetype slugfilenamesel progresel selectortickethasdeliveredbytecountoftotalbytecountservice setserviceuploadprogreselectorprogreselgdataserviceticket ticketticket service fetchentrybyinsertingentryentry forfeedurlurl delegateself didfinishselectorselectoruploadticketfinishedwithentryerrorbrenton,['iphone'] +146449,exceptions and error codes mixing them the right way i am developing a c dongle communication library the library would provide an unified interface to communicate with a range of remote code execution dongles like senselock keylok guardant codethe dongles are based on a smart card technology and have an internal file system and rama typical operation routine involves 1 enumeration of dongles connected to the usb ports 2 connection to a dongle selected 3 execution of the named module passing input and collecting output datawell it is trivial that all of these stages can end up with an error there can be many cases but the most general area dongle is not found sure a fatal casea dongle connection failure a fatal casethe execution module specified is not found within the dongle the operation requested failed due to timeout the operation requested needs authorization a recoverable case i supposea memory error occurred while executing a module in a dongle sure a fatal casea file system error occurred in a dongle sure a fatal case i do not know yet if the case is considered fatal or noti am still deciding whether to throw exceptions to return an error codes or to implement a methods for both casesthe questions aredo exceptions replace the error codes completely or maybe i need to use them only for fatal casesis mixing two paradigms exceptions and error codes considered a good ideais it good idea to provide user with two conceptionsare there any good examples of the exceptions and error codes mixing conceptionhow would you implement thisupdate 1it would be interesting to see more opinions from different perspectives so i decided to add a 100 reputation bounty to the question,['c++'] +146475,manytomany relationships in d i am new to d and i am stuck with manytomany relationships eg we have two aggregate roots tasks and workerscontract is definitely not aggregate root because it has no sense without task and worker so it should be part of some aggregate but which aggregate should it belong to we need to know both summary costs of all task contracts and summary costs of all worker contracts and it is natural for me to have contracts collection both in task and in worker well i can move costs calculation to domain service but i afraid it is a step forward to anemic model is there common way to deal with manytomany relationships and preserve reach domain modelthanks,['c#'] +146479,how to connect to my httplocalhost web server from android emulator in eclipse what can i do in eclipses android emulator to connect it to my localhost web server page at httplocalhost or i have tried it but the emulator still takes my request like a google search for localhost or worse it says that it did not found the page while my web server is normally running,['android'] +146483,is mysql good for large databases i work for a company and we are always accessing an external site for information the site was developed by an antiquated software development company who does not even have a website they pretty much have a monopoly in my state since the content provider for the database only uses this extremely dysfunctional site to upload their data the problem with this website is that it is so slow it is not even functionalhaving controlled for things like connection speed and browser type it is clear that the problem lies within the website itself so i am thinking about redoing the site and then offering it to the content provider as a means for uploading their data basically this project requires a very large database to store hundreds of thousands of names addresses and other types of data my only experience with databases is mysql and really my only experience with dynamic content is php so yeah i am trying to figure out if the old php mysql combination is suitable for storing and representing large amounts of data i have only done this on small projects but i think the whole html templates with placeholders for the dynamic content would work fineof course i truly do not know why this website is so slow maybe it is not the db at all maybe it is the server or something else but the key thing i am trying to accomplish is to improve upon the speed and functionality of this site i have no experience with other types of databases so any tips advice you can offer for doing a project like this would be greatly appreciated also any tips regarding how to generally make a fast and functional site that would need to represent dynamic data from an extremely large database would also be helpfuledit i am learning python so if you think this would be a better sidescripting language then i can certainly try to implement something different than the initial plan above,"['php', 'mysql']" +146498,is there an iconv with translit equivalent in java is there a way to achieve transliteration of characters between charsets in java something similar to the unix command or similar php functioniconv f utf8 t asciitranslit some doctxt new doctxtpreferably operating on strings not having anything to do with filesi know you can can change encodings with the string constructor but that does not handle transliteration of characters that are not in the resulting charset,['java'] +146506,python how to convert from windows 1251 to unicode i am trying to convert file content from windows1251 cyrillic to unicode with python i found this function but it does not workusrbinenv pythonimport osimport sysimport shutildef convert to utf8filename gather the encodings you think that the file may be encoded inside a tupleencodings windows1253 iso88597 macgreek try to open the file and exit if some ioerror occurstry f openfilename rreadexcept exception sysexit1 now start iterating in our encodings tuple and try to decode the filefor enc in encodings try try to decode the file with the first encoding from the tuple if it succeeds then it will reach break so we will be out of the loop something we want on success the data variable will hold our decoded text data fdecodeenc break except exception if the first encoding fail then with the continue keyword will start again with the second encoding from the tuple an so on until it succeeds if for some reason it reaches the last encoding of our tuple without success then exit the program if enc encodings1 sysexit1 continue now get the absolute path of our filename and append back to the end of it for our backup filefpath ospathabspathfilenamenewfilename fpath back and make our backup file with shutilshutilcopyfilename newfilename and at last convert it to utf8f openfilename wtry fwritedataencodeutf8except exception e print efinally fclosehow can i do thatthank you,['python'] +146507,c preprocessors and order of operations i am learning c but i do not understand thisdefine squarex xxa square23 a 11when this is run why does a end up being 11,"['c++', 'c']" +146523,requesting iphone location whilst in background simple question i have an application that records a users location at 30second intervals using an nstimer it works perfectly until the application goes inactive and the nstimer stops as a consequence i am looking for options to maintain my location interval 30secs whilst still being able to record fairly accurate location data within 100m accuracyoption 001 brute force let cllocationmanager startupdatinglocation run all the time using uibackgroundmodes location not recommended drains battery regularity upon request accuracy approx 1065m might just be the only realistic optionoption 002 slc i could use significant location change but the frequency of location updates is pretty poor not to mention accuracy this is particularly true if the application is running in a rural or wilderness area with limited numbers of cell towers regularity unknown accuracy approx 500moption 003 hybrid i could use significant location change slc in the background as an indicator of significant movement and then request an gps location based on kcllocationaccuracybest this would work but the slc events are not going to arrive at anywhere near 30second intervals particularly when walking regularity unknown accuracy approx 1050moption 004 something else any ideas would be much appreciatednote i thought i had this working because when you press lock on an iphone connected via usb applicationwillresignactive is called but nstimers do not stop if you try the same with the iphone unconnected ie as the phone would be in normal use the nstimers stop almost immediately after applicationwillresignactive is called,"['iphone', 'objective-c']" +146525,xcode 4 missing drop down lists in build settings i am using xcode 4 and in build settings all drop down lists have gone awayinstead of the drop down lists i have text boxessee this image for examplei am totally puzzled how can i enable drop down lists again,['iphone'] +146541,what is the jdbc driver orggjtmysqldriver for after taking over a coworkers project i noticed he was using orggjtmysqldriver as the jdbc driver for mysql 5 instead of the more common one commysqljdbcdriver they both are contained in the driver i found on maven central that appears to be the standard thistribution of the driverwhen i look up gjtorg i found some old site that talks about marks mysql driver,['mysql'] +146543,how to select jquery drop down val and trigger the event i have a jquery plugin registered on a drop down like thiscountrylinktostatesprovincei am manually selecting the drop down like thiscountryvalunited statesbut the onchange event is not triggering linktostates which was registered before it so it looks like val only changes the drop down position but does not actually change the onchange event can anyone helpbtw this is the code of the registered if it helps fnextend linktostates functionstate select id thischangefunction var country thisattrvalue state select idremoveoption switch country case canada state select idaddoptioncanadian provinces false break case united states state select idaddoptionus states false break default state select idaddoption please select a country false break,"['javascript', 'jquery']" +146547,facebook like widget on fan page comment area out of visible area when using the like or send widget on a fan page no mater if you use iframe tag or fbml for it the overlay for commenting is positioned always to the right see for example i cant find a way to get the widget to respect the 520px boundary of the facebook tabsee 101150316644842 for an exampleanyone an idea how to solve this tiarufinus,['css'] +146553,how can i set the class for an element using jquery do not want to addremove classes i need to set the class for an element in my page with plain javascript i would write something likedocumentgetelementbyidfooclassname my classthis just sets the class which is exactly what i want but i am using jquery on my page and so would like to do this in a jquery way since it seems weird to mix the old style and the jquery style but jquery apparently only allows you use addclass or removeclass like sofooaddclassmy classthe problem is that it merely adds a class to the element it does not replace the currently existing class does this mean i have to keep track of the old class and do a removeclass first is there no way to tell jquery to replace the current class no matter what it is and just replace it with a new one,"['javascript', 'jquery', 'css']" +146577,custom dictionary lookup in python if i have a dictionary like this d 10 3 100 2 10 1i can type something like dget10 dget100 dget103 2 1though i want that if the given key is not found the value corresponding to the nearest key respect the given key is returned dget20 dget60 dget2003 2 2instead the result in python isnone none nonewhats a pythonic way to implement the behavior i describedthanks,['python'] +146600,can i get a javascript object property name that starts with a number var myobj suppliersnamesupplier112m00824m006alertmyobjsuppliers012mis there a different way to get this property or should i just not use a key that starts with a number,['javascript'] +146619,django for social networking i know this is a relatively broad question but is django robust enough to build a social network on i am concerned mainly with performancespeed for example for a site with a small user base 10 users is it possible to create a djangobacked site that would perform at a speed similar to facebookwhat are its potential weaknesses and things that need to be focused on in order to make it as fast as possible,['python'] +146626,javascript alert message alternative on my online page i have a simple alert message i basically need to change the title but i have read that i cannot do thatheres the codescriptalertmy message herescriptin the alert message i get the url of my website and then the message under it what is the quickest alternative to having a javascript alert thanks,"['javascript', 'jquery']" +146638,net how to parse a persian farsi date string jalali calendar into a datetime object i have run across several great code libraries for converting a persian jalali calendar date to a gregorian date however my original source is a string not a datetime object there does not seem to be official support in the net framework for parsing dates using the persian calendar if i am wrong please show me my goalstring persiandatestring13900207datetime persiandatetime mypersianparserparsepersiandatestring ymmddand of course some dates may use word names for months and days of the week so i would like to be able to support the standard format string protocoledit i know about the typical datetimeparse functionality the persian calendar cannot be used because microsoft left it incomplete andor would not fix it if anyone can point me to some persian date parsing code i would be grateful if not i will request someone remove the question and just write it myself,['.net'] +146653,is there a way to specify the build directory for py2exe i can set the final thist directory of py2exe using the command linepython setuppy py2exe d mythistdirbut i cannot seem to set the file to use for the interim build directory i have taken a brief look at the source but unless i am missing something there does not appear to be any way to do it,['python'] +146656,javalangillegalargumentexception column id does not exist i am trying to debug my application on a real device and having an error but when testing on emulator the error did not show up here is the errorerrorandroidruntime981 caused by javalangillegalargumentexception column id does not existthe error is given in the last line of the following code this is in the activityadapter new simplecursoradapterthis rlayoutlist item c new string datahandlerdbcontact name col datahandlerdbcontact number col datahandlerdbcontact duration col datahandlerdbcontact date col new int ridcontact name ridphone number ridduration riddate here is my activitypublic class myactivity extends activity private static final string log tag myactivity private listview listview private simplecursoradapter adapter private datahandlerdb handler private sqlitedatabase db private openhelper helper private cursor c override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain helper new openhelperthis db helpergetwritabledatabase helperoncreatedb setbasiccontent cclose override public void ondestroy superondestroy datahandlerdbmaketheselectionthisclose dbclose helperclose override public void onpause superonpause datahandlerdbmaketheselectionthisclose dbclose helperclose override public void onstop superonstop datahandlerdbmaketheselectionthisclose dbclose helperclose override protected void onresume superonresume setbasiccontent public void setbasiccontent listview listview findviewbyidridlist view logilog tag listview listview c datahandlerdbmaketheselectionthis cmovetofirst ifdbisopen logilog tag db is opened logilog tag cursor cgetcount startmanagingcursorc adapter new simplecursoradapterthis rlayoutlist item c new string datahandlerdbcontact name col datahandlerdbcontact number col datahandlerdbcontact duration col datahandlerdbcontact date col new int ridcontact name ridphone number ridduration riddate logilog tag before setadapter toastmaketextthis before setadapter toastlength shortshow listviewsetadapteradapter dbclose ifdbisopen logilog tag db is opened ifcisclosed logilog tag cursor is opened the method that query and return the cursor is in the class datahandlerdb public class datahandlerdb private static final string database name callsdbprivate static final int database version 1protected static string contact name col contact nameprotected static string contact number col contact numberprotected static string contact duration col durationprotected static string contact date col dateprotected static string contact month col month create the dbpublic static sqlitedatabase createdbcontext ctx openhelper helper new openhelperctx sqlitedatabase db helpergetwritabledatabase helperoncreatedb helperonopendb dbclose return dbpublic static cursor maketheselectioncontext ctx openhelper helper new openhelperctx sqlitedatabase db helpergetwritabledatabase cursor cursor dbquerytable name 2 null null null null null duration desc cursormovetofirst dbclose return cursor class openhelperpublic static class openhelper extends sqliteopenhelper private final context mcontext openhelpercontext context supercontext database name null database version thismcontext context override public void oncreatesqlitedatabase db logilog tag entrou no oncreate string sql mcontextgetstring rstringmyappdatabase oncreatesplitn dbbegintransaction try execmultiplesqldb sql dbsettransactionsuccessful catch sqlexception e logeerror creating tables and debug data etostring throw e finally dbendtransaction private void execmultiplesqlsqlitedatabase db string sql for string s sql if strimlength 0 dbexecsqls override public void onupgradesqlitedatabase db int oldversion int newversion logwmydb database upgrading database this will drop tables and recreate dbexecsqldrop table if exists table name oncreatedb override public void onopensqlitedatabase db superonopendb here is the xml file with the sql commandstring namemyappdatabase oncreate create table if not exists contact data id integer primary key autoincrement contact id integer contact name varchar50 number type varchar50 contact number varchar50 duration time duration sum time date date current time time cont integer type varchar month varchar50 day varchar50 year varchar50stringfrom my point of view i think the application is not creating the db when starting it because it can find the column id but it is explicity written in the xml code to create it with the id column and i think that also because i have explicity written the columns in the select method including the id i did like thiscursor cursor dbquerytable name 2 new string id contact id contact name number type contact number duration duration sum date current time cont type month day year null null null null duration descand the error that comes for this case is almost the samecaused by androiddatabasesqlitesqliteexception no such column id while compiling select id contact id contact name number type contact number duration duration sum date current time cont type month day year from contact data order by duration descanyone has any solution i dont know why i tested it on emulator the error didnt show up but in a real device it happenedupdatei just logged the first column of the database like thislogilog tag cursor0 cursorgetcolumnname0and it printed id not id but as you can see there is exactly id written in the statementthanks in advance,['android'] +146661,cannot execute code from a freed script ie6 ie7 ie8 ie9 i ran into this problem today in ie6 but is reproducible on all recent version of iei noticed quite a few people run into this problem and i have not seen a very practical way to fix thisthere seems to be some other solution floating about regarding the order of script tags and meta tags in the head of the html document i have not confirm this but heres a link anywaywhat causes the error cant execute code from a freed scripti also know the solution to this problem so i am posting it below,['javascript'] +146663,how to validate a date i am trying to test to make sure a date is valid in the sense that if someone enters 2302011 then it should be wronghow can i do this with any date,['javascript'] +146684,change figure window title in pylab how can i set a figure windows title in pylabpythonfig figure9 9 is now the title of the windowfigset titletest does not workfigtitle test does not work,['python'] +146696,custom login aspnet c i am currently making a custom login in aspnet i have modified the code of the login control to use my database instead of the aspnet table heres a sample of my codeusing systemusing systemdatausing systemconfigurationusing systemwebusing systemwebsecurityusing systemwebuiusing systemwebuiwebcontrolsusing systemwebuiwebcontrolswebpartsusing systemwebuihtmlcontrolsusing systemdatasqlclientpublic partial class login systemwebuipage protected void page loadobject sender eventargs e custom login control protected void login1 authenticateobject sender authenticateeventargs e try string uname login1usernametrim string password login1passwordtrim bool flag authenticateuseruname password if flag true eauthenticated true login1destinationpageurl defaultaspx else eauthenticated false catch exception eauthenticated false private bool authenticateuserstring uname string password bool bflag false string connstring serverdevserveruser idsapasswordwhatpassworddatabasecommonuserstring connstring2 serverdevserveruser idsapasswordwhatpassworddatabaseadmins string strsql select from dbousers where username uname and password password dataset userds new dataset sqlconnection m conn sqldataadapter m dataadapter sqlcommand m command try m conn new sqlconnectionconnstring m connopen m dataadapter new sqldataadapterstrsql m conn m dataadapterfilluserds m connclose catch exception userds null if userds null if userdstables0rowscount 0 bflag true return bflag i have another database for the admin users so my question is how can i make it check the database for the admin users also how can i restrict common users from certain pages like adminadminpagesaspx i am currently trying to figure thisany help would be much appreciated thanks in advance,"['c#', 'asp.net']" +146704,difference between size t and stdsize t what are the differences between size t and stdsize t in terms of where they are declared when they should be used and any other differentiating features,['c++'] +146707,how to get sub image from buffered image we can get a sub image from bufferedimage using getsubimageintintintintbut my problem is i want to get exact subimagerectangle image by passing double values as width and height is there any alternative for that,['java'] +146715,android how to register a content observer without an activity i need to listen all incoming and outgoing sms and store it in a text file for this i am using broadcast listener to listen all incoming messages this works fine but for outgoing sms how to register content observer without activity i do not want any activity in my application now the broadcast receiver listens even after reboot will content observer too listen even after reboot how to merge these two functions here is part of my manifestxmlreceiver classmap androidnamemap androidenabledtrue intentfilter action androidvalueandroidprovidertelephonysms received androidnameandroidprovidertelephonysms received intentfilter receiverhere the class that extends broadcast receiverpublic class map extends broadcastreceiver called when the activity is first created private static final string action androidprovidertelephonysms received public void onreceivecontext context intent intent here i store the sms in text file any help is appreciated thanks,['android'] +146734,target before and after pseudoelements with jquery possible duplicatemanipulating css pseudoelements using jquery on pageload i want the before and after elements on a class to appear i have set the liftedbefore and liftedafter to be opacity0 in the css within document ready i haveliftedbeforecssopacity 1liftedaftercssopacity 1this does not work and the after jquery manipulator is only made for inserting content as far as i can tellis there any way i can manipulate the css of these pseudoelements using jquery,['jquery'] +146735,in a framework using rewrite rules how best to integrate css and js i have got a framework that routes all incoming uris through a base file and to deal with static files i have got a subdirectory static in which i put all css js and images ie staticcssmaincss in order to keep things clearmy own code and plugins deal with this fine but some times other code needs to be implemented and often css files will try to style up with calls to uris in those files how can i deal with this in the best wayan example aboutcompanyroutes to scriptqaboutcompanyand locks in the main structure of the site however staticcssmaincssuses a background image from staticimageswidgetbgcolorpngsince this is a framework i am not happy to hardcode the static paths in the css files for one i do not want to restrict websites to only being served from some root directory for all js there is objects that deal with this ie var x xs dirjs scriptjs but nothing exists for css i have five options i think worst have an option in my admin tool that scans all css files for uri references and prepends them with the right static directory and writing all css as if they are static to a root directorypoor rely on the webservers ability to alias any static directory to one root static directory and let the admins deal with itmeh slow serve the css files through the framework filtering uris with the right static pathssimplest but not very easy handcode the static portions of my css files for whatever server setup there might be and just make sure they are easy to find and changeprobably best but complex have a rewrite rule that detects images in current directory forwarding them to the static directory and write all css with some recognized dynamic path ie instead of staticimagesimgpng do imagesimgpng and rely on rewrite rules to push it where it needs to go also restricting the website structure to never have a subdirectory called imagesany additional options ideas i know joomla and similar has some rewriting of files and probably do no 5,['css'] +146740,sorting arraylist of string in android i am having a string arraylist nameswhich contains names of peoplei want to sort the arraylist in alphabetical orderplz help me,"['java', 'android']" +146789,is there a summary of visual studio 2008 runtime versions i have been looking into a strange problem where loading of one of our applications dlls fails on certain systems using the global flags loader snap flag shows it is somewhere within loadlibraryex the logs in windbg show that there seem to be several different versions of msvcr90dll being referenced it appears that the version referenced in our manifest is different to the rethistributable runtime were installingi have been trying to find a definitive list of the different runtime versions for the visual studio service packs and security hotfixes but i cannot find anything usefulon my own machine i have at least five different ones installed but i cannot relate them to what visual studio is building this is what i have found up to now 90210228 this is what my vs2008 sp1 machine appears to be building against90210218 security update for vs2008 9030729 903072917 vs2008 sp1 90307294148 vs2008 sp1 2872009 also seems to include the atl update 90307294974 seems to be part of team foundation server 201090307295570 21 april 2011 security update is there a more complete list than this or one that clarifies which version we are building what is a fullypatched visual studio 2008 installation sp1 atl hotfix are there further security updatesedit i have found this page which does at least put all the downloads in one place enus2019667sdrspid12913edit2 it appears that merely updating to the most recent visual studio libraries does not automatically use them you need to explicitly bind to the latest library version,['c++'] +146795,the code example which can prove volatile declare should be used currently i cannot understand when we should use volatile to declare variablei have do some study and searched some materials about it for a long time and know that when a field is declared volatile the compiler and runtime are put on notice that this variable is shared and that operations on it should not be reordered with other memory operationshowever i still cannot understand in what scenario we should use it i mean can someone provide any example code which can prove that using volatile brings benefit or solve problems compare to without using it,['java'] +146797,delete i cannot specify target table why this query does not workdelete from recent edits where trackid not in select thistinct historytrackid from history join recent edits on historytrackidrecent editstrackid group by recent editstrackidi get this message you cannot specify target table recent edits for update in from clause,['mysql'] +146800,phpini reload in phpcli i have php script that must be runned from console phpcli but configuration of phpini for phpcli was incorrect i fix it but when i run script a had error with php config because phpini uses an old how i can reload phpini for console without restart server,['php'] +146801,automatic tracing of program execution i would like to know if we can enable tracing in any c or c application for example with a gcc option or a small tool i will enable trace and either trace is printed on console or dumped to a filesince there are lots of files and function classes i do not want to start adding the trace prints manuallyif such tools are not available next choice is use scripting and try to add at the trace printingstrace is not much useful as it gives mainly the system calls,"['c++', 'c']" +146802,how to check is timezone identifier valid from code i will try to explain whats the problem hereaccording to list of supported timezones from php manual i can see all valid tz identifiers in phpmy first question is how to get that list from code but that is not what i really needmy final goal is to write function isvalidtimezoneid that returns true if timezone is valid otherwise it should return falsefunction isvalidtimezoneidtimezoneid function body return true or false so when i pass tz identifier using timezoneid string in function i need boolean resultwell what i have so far1 solution using operatorfirst solution i have got is something like thisfunction isvalidtimezoneidtimezoneid savedzone date default timezone get save current zone res savedzone timezoneid it is true if param matches current zone if res 0r date default timezone settimezoneid try to set new timezone res date default timezone get timezoneid it is true if new timezone set matches param string date default timezone setsavedzone restore back old timezone return res set result that works perfectly but i want another solution to avoid trying to set wrong timezone2 solution using timezone identifiers listthen i was trying to get list of valid timezone identifiers and check it against parameter using in array function so i have tried to use timezone identifiers list but that was not so good because a lot of timezones was missing in array returned by this function alias of datetimezonelistidentifiers at first sight that was exactly what i was looking forfunction isvalidtimezoneidtimezoneid zonelist timezone identifiers list list of all valid timezones return in arraytimezoneid zonelist set result this code looks nice and easy but than i have found that zonelist array contains 400 elements according to my calculations it should return 550 elements 150 elements are missing so that is not good enough as solution for my problem3 solution based on datetimezonelistabbreviationsthis is last step on my way trying to find perfect solution using array returned by this method i can extract all timezone identifiers supported by phpfunction createtzlist tza datetimezonelistabbreviations tzlist array foreach tza as zone foreach zone as item if is stringitemtimezone id itemtimezone id tzlist itemtimezone id tzlist array uniquetzlist asorttzlist return array valuestzlist this function returns 563 elements in example 2 i have got just 407i have tried to find differences between those two arraysa1 timezone identifiers lista2 createtzlistprint rarray valuesarray diffa2 a1result isarray 0 africaasmera 1 africatimbuktu 2 americaargentinacomodrivadavia 3 americaatka 4 americabuenos aires 5 americacatamarca 6 americacoral harbour 7 americacordoba 8 americaensenada 9 americafort wayne 10 americaindianapolis 11 americajujuy 12 americaknox in 13 americalouisville 14 americamendoza 15 americaporto acre 16 americarosario 17 americavirgin 18 asiaashkhabad 19 asiacalcutta 20 asiachungking 21 asiadacca 22 asiaistanbul 23 asiakatmandu 24 asiamacao 25 asiasaigon 26 asiatel aviv 27 asiathimbu 28 asiaujung pandang 29 asiaulan bator 30 atlanticfaeroe 31 atlanticjan mayen 32 australiaact 33 australiacanberra 34 australialhi 35 australiansw 36 australianorth 37 australiaqueensland 38 australiasouth 39 australiatasmania 40 australiavictoria 41 australiawest 42 australiayancowinna 43 brazilacre 44 brazildenoronha 45 brazileast 46 brazilwest 47 cet 48 cst6cdt 49 canadaatlantic 50 canadacentral 51 canadaeastsaskatchewan 52 canadaeastern 53 canadamountain 54 canadanewfoundland 55 canadapacific 56 canadasaskatchewan 57 canadayukon 58 chilecontinental 59 chileeasterisland 60 cuba 61 eet 62 est 63 est5edt 64 egypt 65 eire 66 etcgmt 67 etcgmt0 68 etcgmt1 69 etcgmt10 70 etcgmt11 71 etcgmt12 72 etcgmt2 73 etcgmt3 74 etcgmt4 75 etcgmt5 76 etcgmt6 77 etcgmt7 78 etcgmt8 79 etcgmt9 80 etcgmt0 81 etcgmt1 82 etcgmt10 83 etcgmt11 84 etcgmt12 85 etcgmt13 86 etcgmt14 87 etcgmt2 88 etcgmt3 89 etcgmt4 90 etcgmt5 91 etcgmt6 92 etcgmt7 93 etcgmt8 94 etcgmt9 95 etcgmt0 96 etcgreenwich 97 etcuct 98 etcutc 99 etcuniversal 100 etczulu 101 europebelfast 102 europenicosia 103 europetiraspol 104 factory 105 gb 106 gbeire 107 gmt 108 gmt0 109 gmt0 110 gmt0 1 greenwich 112 hst 113 hongkong 114 iceland 115 iran 116 israel 117 jamaica 118 japan 119 kwajalein 120 libya 121 met 122 mst 123 mst7mdt 124 mexicobajanorte 125 mexicobajasur 126 mexicogeneral 127 nz 128 nzchat 129 navajo 130 prc 131 pst8pdt 132 pacificponape 133 pacificsamoa 134 pacifictruk 135 pacificyap 136 poland 137 portugal 138 roc 139 rok 140 singapore 141 turkey 142 uct 143 usalaska 144 usaleutian 145 usarizona 146 uscentral 147 useastindiana 148 useastern 149 ushawaii 150 usindianastarke 151 usmichigan 152 usmountain 153 uspacific 154 uspacificnew 155 ussamoa 156 universal 157 wsu 158 wet 159 zuluthis list contains all valid tz identifiers that example 2 failed to matchthere is four tz identifiers more part of a1print rarray valuesarray diffa1 a2outputarray 0 americabahia banderas 1 antarcticamacquarie 2 pacificchuuk 3 pacificpohnpeiso now i have almost perfect solutionfunction isvalidtimezoneidtimezoneid zonelist createtzlist list of all valid timezones last 4 are not included return in arraytimezoneid zonelist set result that is my solution and i can use it of course i use this function as part of class so i do not need to generate zonelist on every methods callwhat i really need herei am wondering is there any easier quicker solution to get list of all valid timezone identifiers as array i want to avoid extracting that list from datetimezonelistabbreviations if that is possible or if you know another way how to check is timezone parameter valid please let me know i repeat operator cannot be part of solutionps if you need more details and examples let me know i guess you do noti am using php 535 think that is not importantupdateany part of code that throws exception on invalid timezone string hidden using or caught using trycatch block is not solution i am looking foranother updatei have put small bounty on this questionnow i am looking for the easiest way how to extract list of all timezone identifiers in php array,['php'] +146809,behavior of static variable with inheritance i am asking this question for the thiscussionsuppose i have flowing class hierarchy class a public static int varr class b public a class c public a if i create the object of b b1b2b3 and c c1c2c3 and a a1 a21will varr is shared across all the object mentioned above or there will be separate instance for different object2if b1 object change the value it will be reflected for c1 object or not,['c++'] +146837,buildout tries to update systemwide thistribute installation and refuses to run buildout does not like my systemwide thistribute installation and refuses to runplones15447224mybuildout python bootstrappy creating directory homeplonemybuildoutbincreating directory homeplonemybuildoutpartscreating directory homeplonemybuildouteggscreating directory homeplonemybuildoutdevelopeggsgetting thistribution for thistribute0614before install bootstrapscanning installed packagessetuptools installation detected at usrlibpython26thistpackagesnonegg installationremoving elements out of the wayalready patchedusrlibpython26thistpackagessetuptoolsegginfo already patchedafter install bootstrapcreating usrlocallibpython26thistpackagessetuptools06c11py26egginfoerror usrlocallibpython26thistpackagessetuptools06c11py26egginfo permission deniedan error occurred when trying to install thistribute 0614 look above this message for any errors that were output by easy installwhile bootstrapping getting thistribution for thistribute0614error could not install thistribute 0614is there some way to tell buildout to install its own thistribute and not to mess with systemwide python installationi know about virtualenv but it seems to be an overkill just to install virtualenv to make buildout happy there must be some other waypython 26 plone 41 ubuntu 104,['python'] +146855,why would not my element thisplay inline i am trying to apply thisplay inline to the legend element in my fieldset element so that the following span will follow on the same line but my css is having no effectlegend thisplay inlinespan thisplay inlinefieldset legendlegendlegend spanfollowerspanfieldsetjsfiddleediti have no control over the html i can only edit css,"['html', 'css']" +146861,how to stop handler in android in my application my handler does not stop how can i stop the handlerit continues to start after closing the activity what can i do the code is handler new handler override public void handlemessagemessage msg todo autogenerated method stub superhandlemessagemsg ifimax evnetchangethisplayi i handlersendemptymessagedelayed0 50 else i 0 handlersendemptymessagedelayed0 handlersendemptymessagedelayed0,['android'] +146871,whats easy in f that is hard in c possible duplicatein what areas might the use of f be more appropriate than c i am anticipating giving a presentation at the local net user group about f and i am anticipating the why should i look into f question from the audience i know most of the stuff that can be done in f can be done in c tooso i am looking for things that can be done easily in f that are really hard to do in c e g pattern matching and if there are already good answers to this question please just link them in comments and i will close this up i did see a few things but if there is already a question that addresses this i did not find itby the way if any of the moderators want to mark this community wiki please feel free this seems more like a survey question to me anyway,['c#'] +146873,why is our monotouch app breaking in the garbage collector it is not out of memory we have a simple question but the cause is complicated we are experienced developers and have done a lot of research into what may be causing it we are hoping that monotouch developers can work with us to identify what appears to be a common problem that people are having and for which no solution appears to exist yet weve been working on this for over two weeks and not been able to resolve itthe question is why is our monotouch app breaking in the garbage collector it is not out of memorythe situation is that we have an app that checks a web service regularly perhaps every 5 seconds after a period of time it fails with a memory management abort this typically happens after about an hour and a half but can be anywhere from ten minutes to overnight this happens on all of our test devices we have 7 in total covering ios3 and ios4 ipod touch iphones and ipads 12 after looking on stackoverflow we have added a systemgccollect in a timer before we take any action this improved things a little it takes longer to fail but it did not go away it is also worth adding that the memory log from the ipad shows that there are 7 free blocks and 2041 in use by our app with a total of 26488 wired pages since weve garbage collected and are not doing anything different to what we did 5 seconds before it seems odd to run out of memory we upgraded to monotouch 401 but that has not fixed itstackoverflow questions that might be on the same issue but not answering it 56905 4545383 5492469 5426733the stack at failure on an ipad2 is below the failure can happen in the main thread or an http thread but always goes in this gc sequence i have included the code for the memory manager gc remap below with thiscussionthread 10 crashed0 libsystem kerneldylib 0x34b4da1c pthread kill 81 libsystem cdylib 0x3646a3b4 pthread kill 522 libsystem cdylib 0x36462bf8 abort 723 myapp 0x004ca92c mono handle native sigsegv miniexceptionsc22494 myapp 0x004f2208 sigabrt signal handler miniposixc1955 libsystem cdylib 0x36475728 sigtramp 366 libsystem cdylib 0x3646a3b4 pthread kill 527 libsystem cdylib 0x36462bf8 abort 728 myapp 0x0061dc94 gc remap os depc20929 myapp 0x00611678 gc allochblk nth allchblkc73010 myapp 0x00611028 gc allochblk allchblkc561 myapp 0x0061d0e0 gc new hblk new hblkc25312 myapp 0x006133d0 gc allocobj allocc1613 myapp 0x00617d30 gc generic malloc inner mallocc13614 myapp 0x00617f40 gc generic malloc mallocc19215 myapp 0x00618264 gc malloc atomic mallocc26216 myapp 0x005a46d4 mono object allocate ptrfree objectc422117 myapp 0x005a4aa0 mono string new size objectc484818 myapp 0x005c1b14 ves icall system string internalallocatestr stringicallsc21319 myapp 0x002d34c4 wrapper managed to native string internalallocatestr int 5220 myapp 0x002cff5c string tolower system globalization cultureinfo 5621 myapp 0x003e6ac0 system net webrequest getcreator string 4022 myapp 0x003e694c system net webrequest create system uri 4823 myapp 0x003e68d8 system net webrequest create string 6424 myapp 0x004489c4 myapp services client getresponsecontent string 15225 myapp 0x00446288 myapp services client getcurrentquestion long long 91626 myapp 0x00196fcc myapp iphone rootviewcontroller retrievecurrentquestion 86827 myapp 0x002e6368 system threading thread startunsafe 16828 myapp 0x00306890 wrapper runtime invoke object runtime invoke dynamic intptr intptr intptr intptr 19229 myapp 0x004b0274 mono jit runtime invoke minic574630 myapp 0x0059f924 mono runtime invoke objectc275631 myapp 0x005a1350 mono runtime delegate invoke objectc342132 myapp 0x005ca884 start wrapper internal threadsc78833 myapp 0x005ca924 start wrapper threadsc83034 myapp 0x005ef4b8 thread start routine wthreadsc28535 myapp 0x0061f1d0 gc start routine pthread supportc146836 libsystem cdylib 0x3646a30a pthread start 24237 libsystem cdylib 0x3646b4 thread start 0this is the gc remap code that appears to be the point of failure from depcifdef nacl nacl does not expose mprotect but mmap should work fine void mmap result mmap result mmapstart addr len prot read prot write opt prot exec map private map fixed opt map anon zero fd 0 offset if mmap result void start addr abortmmap as mprotect failed fake the return value as if mprotect succeeded result 0 else nacl result mprotectstart addr len prot read prot write opt prot execendif nacl if result 0 gc err printf3 mprotect failed at 0xlx length ld with errno ldn start addr len errno abortmprotect remapping failed gc unmapped bytes lenit would appear that the abort is caused by the mprotect function failing we have been unable to get the failure code as the problem does not manifest itself on the simulator the mprotect function appears to just mark the memory as accessible for readwriteexecute how is the memory manager passing parameters that cause it to fail could it be passing an incorrect pointer or an incorrect length or are certain areas or boundaries handled differently on iosthe code at for gc allochblk nth implies that the gc remap function is only called if the memory block found was valid this file does not quite match the line numbers of the stack trace so presumably it is not exactly the same file iphoneosman2mprotect2html says that it might fail with eacces einval enotsup which are 13 22 45 respectively one of the reports on so says that they get an error 12 enomem i am not sure what that means as mprotect should not be allocating memory and the documentation does not say that is valida more generic documentation at indicates that enomem can be caused by internal kernel structures could not be allocated or addresses in the range addr addrlen are invalid for the address space of the process or specify one or more pages that are not mapped how could this bewe would much appreciate any suggestions on how we might move this forward we are not doing anything other than c code and are not doing anything other than a periodic https read what can we do to improve debugging we cannot trace anything as the app is killed by ios we have tried creating a simpler demonstration but it does not fail fast enough to be worth using if a novell monotouch developer wants our source we can provide it subject to the obvious confidentiality,['ios'] +146874,testunit rails how to assert one number is greater than another one i am writing my first unit tests with testunit and i have reached a point where i need to compare two numbers much to my surprise i have thiscovered that none of the following were availableassert greater thanassert lesser thanassert greater or equal thanassert lesser or equal thanis this normal how should i do it then thanks,['ruby-on-rails'] +146889,problem in firefox when calling windowopen when i am calling this code in the link of a chart in apex javascriptwindowopenmywindowwidth400height200 breplacetrueit opens a new window with google page but puts the chart page with a blank page with object window wrote on ithow can i maintain the chart page,['javascript'] +146903,typesetting math functions in latex to render in android application does anyone know if it is possible to use latex markup language to format text for thisplay in an android applicationfor example the text for a textview can be formatted with html to change the font size to small and superscript etc by using the htmlformhtmlstring methodtextview atextviewtextview findviewbyidridtextview1atextviewsettexthtmlfromhtml2smallsup5supsmall will thisplay 25 in the textviewhowever what i would like to something more advanced and format text using perhaps latex to represent math function and have that render as a correctly format math function in a textview or something elsefor example the latex markup evaluate the sum thisplaystylesumlimits i0n i3 should be rendered toif there is some other way to mark up math functions so they thisplay correctly in an android app other than using latex i am all open to suggestions,['android'] +146904,case insensitive string comp in c i have two postcodes char that i want to compare ignoring caseis there a function to do thisor do i have to loop through each use the tolower function and then do the comparisonany idea how this function will react with numbers in the stringthanks,['c'] +146920,how to make a jquery post request synchronous iave been googling this and avoiding this error in my bug fix list for a long time now but iave finally reached the end of the list the last of which i have to make a function return truefalse to state whether the validation has succeeded or not i am using ajax to compare certain fields with those that are already in the db and by default the post method does it is operations asynchronouslyiam setting a variable inside the call onsuccess and the calling method does not get a response because of this so all my jsjquery fails on pageload i would prefer if i could still keep using the post method,"['javascript', 'jquery', 'html']" +146923,where is jquerydata stored where does jquery store the values of the data that it sets to dom objectsis there some kind of variable like jquerydatadb or something maybe even something privateis there any way to gain access to this object,"['javascript', 'jquery']" +146930,what is the purpose of systemdatasqlclientsqlparameterisnullable i am currently trying to write a simple c wrapper class for all the stored procedures in a database while building some parameters in c i noticed the property sqlparameterisnullable and wondered what this is for as far as i am aware it is not possible to declare a stored procedure parameter as not null and therefore null is always allowed to be passed to any parameterthrough testing it appears that setting the isnullable property to false has no effect and still allows the sqlparametervalue property to be set to nullcan anybody explain the purpose of this propertythanks for lookinganswerers looking for the bounty should review these linkshow to restrict null as parameter to stored procedure sql serversql parameter isnullablei assume sqlparameterisnullable only makes sense whena,"['.net', 'sql']" +146935,what is the jslint approved way to convert a number to a string i have always converted numbers to strings by adding an empty string to themvar string 1 however jslint complains of this method with expected string and instead saw and it does look a little uglyis there a better way,['javascript'] +146947,systemsecuritysecurityexception the source was not found but some or all event logs could not be searched inaccessible logs security i am trying to create a windows service but when i try and install it it rolls back giving me this errorsystemsecuritysecurityexception the source was not found but some or all event logs could not be searched inaccessible logs securityi do not know what this means my application has the bare minimum since i am just testing things out firstmy installer codenamespace windowsservice1 runinstallertrue public partial class projectinstaller systemconfigurationinstallinstaller public projectinstaller set the privileges processinstalleraccount serviceaccountlocalsystem processinstallerusername null processinstallerpassword null serviceinstallerthisplayname my service serviceinstallerstarttype servicestartmodemanual must be the same as what was set in programs constructor serviceinstallerservicename my service thisinstallersaddprocessinstaller thisinstallersaddserviceinstaller private void serviceprocessinstaller1 afterinstallobject sender installeventargs e private void serviceinstaller1 afterinstallobject sender installeventargs e my service codepublic partial class service1 servicebase public service1 thisservicename my service protected override void onstartstring args baseonstartargs protected override void onstop baseonstop,['c#'] +146960,android like permissions in ios in android you define permissions for gps sms sending location in the manifest fileis there anythiing similiar in the ios so the user would know what capabilities of the phone some app uses before instalationor is the user warned during app use when some function wants to use something eg gps sms,"['android', 'ios']" +146971,what are the architectural limitations of php i was reading the article php sucks but it does not matter by jeff atwoodin the comments he writesthat said i absolutely think it is important for php devs to be aware of the architectural limitations of php and understand the alternativeswhat are those limitations and how do they compare with other scripting weakly typed languagesalso what are the alternatives in those conditions where limitations need to be avoided,['php'] +146986,objectivec code blocks equivalent in c how would i write the equivalent code in ctypedef void methodblockint void foowithblockmethodblockblock int a 5 blocka void regularfoo self foowithblockint val nslogd val,"['c#', 'objective-c']" +146988,why does icustomattributeprovidergetcustomattributes return object instead of attribute why does icustomattributeprovidergetcustomattributes return object instead of attributeis there any circumstance when using the icustomattributeprovider implementations from mscorlib and system assemblies will return objects that are not of type attribute,"['c#', '.net']" +147008,python struct arrays i would like to have a struct for every line i find in a text file so yeah basically i want to define my struct then count lines and fill up my structs in c c it is fine but i am always lost in python my structs would look like struct0name foo struct0place shop struct1name bar struct1place home and so onsorry for the lame question hope other newbies like me will find it useful of course feel free to edit the question title to reflect the real thing,['python'] +147010,databind from xaml to code behind i have this text dependency property in code behindpublic static dependencyproperty textproperty dependencypropertyregistertext typeofstring typeofmainwindow new propertymetadatahello worldpublic string text get return stringgetvaluetextproperty set setvaluetextproperty value i want to bind content of label to that text property so that the label thisplays actual value of text property and viceversalabel contentbinding how can i do it i have done that some time before but now i cannot remember how and it is very simple the simplest code will be accepted,"['c#', '.net']" +147011,what sqldbtype maps to varbinarymax what sqldbtype maps to varbinarymax sqldbtypevarbinary says that it is limited to 8k sql server documentation says that varbinarymax can store aprrox 2gb but sqldbtypevarbinary says that it is limited to 8k,"['c#', 'asp.net']" +147026,android column id does not exist i am getting this errorillegalargumentexception column id does not existwhen using a simplecursoradapter to retrieve from my database and the table does indeed have this id column noticing this a common problem i have tried to work around it given some of the solutions online but none of them work this is my cursor querysimplecursoradapter madapter new simplecursoradapterthis rlayoutquoterow mycursor new string id quote new intridquotealthough i should mention the original did not include the id column i added this recently to try and solve the problem has anyone got any ideas that might help solve the problem,['android'] +147029,is there a 3rd party library for android pinch zoom does anybody know whether there is a 3rd paty or built in library that helps in detecting and handling a pinch zoom eventbasically what i am looking for is some class that takes coordinates from a touch event and returns whether its a pinch zoom event or not,['android'] +147046,code to generate gaussian normally thistributed random numbers in ruby what is some code to generate normally thistributed random numbers in rubynote i answered my own question but i will wait a few days before accepting to see if anyone has a better answer editsearching for this i looked at all pages on so resulting from the two searchesnormal thistribution rubyandgaussian random ruby,['ruby'] +147051,how to capture the character on different locale keyboards in wpfc my wpf application handles keyboard presses and specifically the and character as it is a voip phonei have a bug though with international keyboards and in particular the british english keyboard normally i listen for the 3 key and if the shift key modifier is down we fire off an event to do stuff however on the british keyboard this is the a character i found that the uk english keyboard has a dedicated key for obviously we could just listen for that particular key but that does not solve the case for us english which is shift3 and all the countless other keyboards that put it somewhere elselong story short how do i listen for a particular character from a key press whether it is a key combo or single key and react to it,['c#'] +147053,scrapy parse a page to extract items then follow and store item url contents i have a question on how to do this thing in scrapy i have a spider that crawls for listing pages of items every time a listing page is found with items there is the parse item callback that is called for extracting items data and yielding items so far so good everything works greatbut each item has among other data an url with more details on that item i want to follow that url and store in another item field url contents the fetched contents of that items url and i am not sure how to organize code to achieve that since the two links listings link and one particular item link are followed differently with callbacks called at different times but i have to correlate them in the same item processingmy code so far looks like thisclass myspidercrawlspider name examplecom allowed domains examplecom start urls rules rulesgmllinkextractorallowexamplecom start denysort restrict xpaths divclasspagination callbackparse item rulesgmllinkextractorallowitemdetail follow false def parse itemself response main selector htmlxpathselectorresponse xpath h2classtitle sub selectors main selectorselectxpath for sel in sub selectors item exampleitem l exampleloaderitem item selector sel ladd xpathtitle atitletitle yield lload item,['python'] +147057,java runtime process check if waiting for input i wish to create a process using javas runtimefor example process proc runtimegetruntimeexeccmdthen i want to somehow wait for the process until it is in ready for input state which will verify it has finished all of its work anyway on how to do itone thing that is possible is echoing finished and checking if this line was written using the stdin of the process but i thislike the ideais there any better more formal approach to do thisby the way i need this effect as i descriobed it i want to wait before writing new commands to the batch filethank you,['java'] +147058,rails order with nulls last in my rails app i have run into an issue a couple times that i would like to know how other people solvei have certain records where a value is optional so some records have a value and some are null for that columnif i order by that column on some databases the nulls sort first and on some databases the nulls sort lastfor instance i have photos which may or may not belong to a collection ie there are some photos where collection idnil and some where collection id1 etc if i do photoordercollection id desc then on sqlite i get the nulls last but on postgresql i get the nulls firstis there a nice standard rails way to handle this and get consistent performance across any database,['ruby-on-rails'] +147059,is there a stack class in objective c that i can import and use i need a stack adt in my application i would like to avoid making a wrapper on nsmutablearray there must be an efficient implementation in foundation somewhereso how do i access it,['objective-c'] +147066,transaction deadlock for select query occasionally i have the following error for a stored procedure which is only a select query transaction process id 91 was deadlocked on lockmy initial understanding was that a select query would not lock a table or would not cause a deadlock even if the table it tries to query is being updatedlocked by another process but it seems that a select query can cause deadlocks as wellif i set the isolation level to read uncommitted for the query will that solve the problem,['sql'] +147067,workaround for needing an id row for cursoradapter i found out in order for the android cursoradapter class to work i need a row id now i have a specific naming scheme and do not want to change my id column called id to id for all the tables i need cursoradapters for i think this will affect readability of some of my complex queries plus id is ugly pi am debating using custom tableid as id select queries but i like sqlitedatabases nice query methods and it does not look like they support renaming columns in the queryit seems rather inflexible and odd to always require a specific table column name is there a way to specify what column to use as the id column to the cursoradapter or maybe another workaround i have not thought of,['android'] +147068,curl command line post i am trying to simulate a post to my simple rails scaffold web service the files created by the scaffold have not been changed when i post data from the website form a record is created correctlywhen i attempt to post with curl a record is created in the database but it has null values in the fields except for updated at and created at i am new to command line curl so i may not be doing it correctlycurl d namegazoofriendrubble localhost30flintstonesi get back this from webrickstarted post flintstones for 127001 at thu apr 28 180447 0600 2011 processing by flintstonescontrollercreate as parameters namegazoo friendrubble arel 03ms insert into flintstones name friend created at updated at values null null 20110429 04479902 20110429 04479902 redirected to httplocalhost30flintstones4after a get for the jsoncurl localhost30flintstonesjsoni receiveflintstonenamenullcreated at20110429t0958zupdated at20110429t0958zid4friendnullwhy do i get null in my fieldsthanks in advance,['ruby-on-rails'] +147075,php how do i avoid reading partial files that are pushed to me with ftp files are being pushed to my server via ftp i process them with php code in a drupal module os is ubuntu and the ftp server is vsftpat regular intervals i will check for new files process them with simplexml and move them to a done folder how do i avoid processing a partially uploaded filevsftp has lock upload files defaulted to yes i thought of attempting to move the files first expecting the move to fail on a currently uploading file that does not seem to happen at least on the command line if i start uploading a large file and move it just keeps growing in the new location i guess the directory entry is not lockedshould i try fopen with mode a or r just to see if it succeeds before attempting to load into simplexml or is there a better way to do this i guess i could just detect simplexml load failing but that seems messyi do not have control of the sender they would not do an upload and renamethanks,['php'] +147080,httpwebrequest times out on second call why does the following code timeout the second and subsequent time it is runthe code hangs atusing stream objstream requestgetresponsegetresponsestreamand then causes a webexception saying that the request has timed outi have tried this with a webrequest and httpwebrequestedit it seems the code is falling over in requestgetresponseedit this post suggests it may be a gc issue as per this post the issue is mitigated if fiddler is open in the backgroundthe server is there and available for requests private string getqlmresponsestring url httpwebrequest request webrequestcreateurl as httpwebrequest requestcredentials new networkcredentialsettingsdefaultlicenseuser settingsdefaultlicensepassword requestkeepalive false requesttimeout 50 requestproxy null read stream string responsestring stringempty try using var response requestgetresponse using stream objstream responsegetresponsestream using streamreader objreader new streamreaderobjstream responsestring objreaderreadtoend objreaderclose objstreamflush objstreamclose responseclose catch webexception ex throw new licenseserverunavailableexception finally requestabort request null gccollect return responsestring thrown webexception isthe operation has timed out systemnetwebexception the operation has timed out data systemcollectionslistdictionaryinternal helplink null innerexception null message the operation has timed out source system stacktrace at systemnethttpwebrequestgetresponsern at iqxlicensinglicensegetqlmresponsestring url in cusersjdsvnjdproductsdevelopmentjadlicensingjadlicensinglicensecsline 373 targetsite systemnetwebresponse getresponseupdate ok so the following code now works the servicepoint was setting the timeout to be near 4 minutes changing servicepointconnectionleasetimeout on the request object means that the request is now destroyed after 50ms thanks to all for your help and also to these 2 pagesvvs80aspxprivate string getqlmresponsestring url httpwebrequest request webrequestcreateurl as httpwebrequest requestcredentials new networkcredentialsettingsdefaultlicenseuser settingsdefaultlicensepassword requestkeepalive false requesttimeout 50 requestproxy null requestservicepointconnectionleasetimeout 50 requestservicepointmaxidletime 50 read stream string responsestring stringempty try using webresponse response requestgetresponse using stream objstream responsegetresponsestream using streamreader objreader new streamreaderobjstream responsestring objreaderreadtoend objreaderclose objstreamflush objstreamclose responseclose catch webexception ex throw new licenseserverunavailableexception finally requestabort return responsestring,['c#'] +147086,create nsdate from unix timestamp how do i create an nsdate from a unix timestampchannelstartdate nsdate datewithtimeintervalsince1970nstimeintervalchanneljson objectforkeybroadcaststartedtimei get this error104 error pointer value used where a floating point value was expectedchannelsstartdate is an nsdate the value for the key broadcaststartedtime is a javascript number converted into an nsnumber or nsdecimalnumber by the sbjson parser library,['objective-c'] +147089,javascript function leading bang syntax i have been seeing this syntax on a few libraries now and i am wondering what the benefit is note i am well aware of closures and what the code is doing i am only concerned about the syntactical differencesfunction do stuffas an alternative to the more commonfunction do stufor self invoking anonymous functionsi am wondering a few things first off what is allowing the top example to actually work why is the bang necessary in order to make this statement syntactically correct i am told also that works and i am sure some others in place of second what is the benefit all i can tell is that it saves a single character but i cannot imagine that is such a huge benefit to attract numerous adopters is there some other benefit im missing the only other difference i can see would be the return value of the self invoking function but in both of these examples we do not really care about the return value of the function since it is used only to create a closure so can someone tell me why one might use the first syntax,['javascript'] +147097,css styling in django forms how do i style the followingin formspy from django import formsclass contactformformsform subject formscharfieldmax length100 email formsemailfieldrequiredfalse message formscharfieldwidgetformstextareain contact formhtml form action methodpost table formas table table input typesubmit valuesubmit formfor example how do i set a class or id for the subject email message to provide an external style sheet to thank you,['css'] +147108,how to emulate extending a class with database tables i will have several different types of users that will use my system for all users i need to store such things as username password email address etc but if they are a user of category a i also need to store values for fields a b and c but if they are a user of category b i need to store values for fields d e f and guseridusernamepasswordcat aidabccat biddefgi most likely need to use a bridge table of some sort to link a user to one of the cat tables but how do i go about doing that i cannot use something like thisextenduser idcat idbecause i wouldnt know which cat table the cat id refers to would i need a field for each of the categories if so that does not seem normalized since there would be a lot of empty fields especially if i have 3 categoriesextenduser idcat a idcat b idany input is much appreciatedryan,['mysql'] +147110,python join equivalent i have a dictionary saydict a b c din php i would to something like implode dict and get the output abcdhow do i do that in python,['python'] +147126,convert nvarchar to bigint in sql server 2008 i want insert all rows of a table into another table and i also want convert a nvarchar field into bigint but when i use convertbigint col1 sql server shows an errorerror converting data type nvarchar to biginthow can i fix this problem,['sql'] +147174,class static member function chosen over global function with same name doubt originated from hereint g cout in function g endl return 0class x public static int g cout in static member function xg endl return 1 class y public x public static int iint yi g initially i though that as symbol resolution happens from inner most scope to outer most scope that is why xg would be called but then i closely noticed the code int yi ghow are we able to access xg without namescope and scope in which this statement lies should be global not y or x so symbol resolution should give global version of the function g,['c++'] +147187,how i can return 500 error in json format in aspnet mvc when aspnet mvc throws an exception it returns a 500 error with response type texthtml which of course is invalid jsoni want to respond to an ajax request expecting json with an error i can receive and thisplay to the user is it possible to return json with an http status code of 500when the problem is a missing parameter the 500 error occurs before the controller is even called so a controller solution might not work for example leaving a required parameter out in a call to an action that normally returns a jsonresult aspnet mvc sends this back to the clientserver error in application the parameters dictionary contains a null entry for parameter id of nonnullable type systemint32 for method systemwebmvcjsonresult edituserint32 systemstring systemstring systemstring systemstring systemstring systemstring systemstring systemstring in bhh an optional parameter must be a reference type a nullable type or be declared as an optional parameter parameter name parametersi am using jquery is there a better way to handle this,['jquery'] +147209,how to sign out in linkedin using authrequest using android i developed one app integrated with linkedini do signin authentication in linkedin using oauth service to post the network updatebut now how to sign out deauthenticate to the linkedin automaticallythanks in adv,['android'] +147211,how to launch the beforeshowday of datepicker from another function i have a datepicker with the following code i have a dropdownbox and upon a change in the dropdown box i want to launch the datepicker beforeshowday function how can i do thisvar freedatepart of my code is as followsmydivdatepicker showothermonths true selectothermonths true dateformat yymmdd onselect functiondatetext inst onchangemonthyear functionyear month inst ajax contenttype applicationjson charsetutf8 datatype json url urlactionlistdates party data date new dateyear month 1 1tostringymmdd userid userid success functiondata freedate evaldata error functionrequest status error beforeshowday functiondatetoshow var returnresult new array returnresultpushtrue var itemmatched false eachfreedate functionkey value if new dateparseintvaluesubstr6comparetodatetoshow 0 itemmatched true returnresultpushtimenotfree return if itemmatched returnresultpush returnresultpush return returnresult amylistchangefunction userid userlist optionselectedattrvalue mylist is used to have freedate and the datepicker must be shown accordingly ajax contenttype applicationjson charsetutf8 datatype json url urlactionlistdates party data date new datemydivdatepickergetdatetostringymmdd userid userid success functiondata freedate evaldata error functionrequest status error mydivdatepickersetdate mydivdatepickergetdatetostringymmdda,['jquery'] +147236,sinatra configuring environments on the fly i have successfull written a little sinatra application and already successfully deployed it on herokuhowever i want to run that application in development mode on my local computer and i want to have it production mode on heroku once i push it to the remote repositorycurrently i can achieve either one of thos options when i change my configru to the following valuesrequire rubygemsrequire sinatrarequire sinatrareloaderrequire calcrbenable loggingset environment developmentset port 4567i am able to run it locally on port 4567 via ruby configru when i change the configru to thisrequire rubygemsrequire sinatrarequire sinatrareloaderrequire calcrbenable loggingset environment productionset port 4567run sinatraapplicationi am able to get it to run on heroku on port 80but i can not use the same configuration for both development and productioni would like to have something likeruby configru dev for development and ruby configru for productionadditional informationwhen i try to run the production configru on my local machine i get ruby configrueval2in method missing undefined method run for mainobject nomethoderror from eval4in send from eval4in method missing from configru10,['ruby'] +147258,simple natural language processing startup for java i am willing to start developing a project on nlp i dont know much of the tools available after googling for about a month i realized that opennlp can be my solutionunfortunately i dont see any complete tutorial over using the api all of them are lacking of some general steps i need a tutorial from ground level i have seen a lot of downloads over the site but dont know how to use them do i need to train or something here is what i want to knowhow to install set up a nlp system which canparse a english sentence wordsidentify the different parts of speech,['java'] +147283,php effect of code after headerlocation abchtml lets say the code looks something like this iftest headerlocation somefilehtml some php code headerlocation anotherfilehtmlis some php code above executed if yes then what happens to further http responses therein eg the second header statement in the code,['php'] +147292,import tlb into c i want to import a type library tlb into chow do i import a tlb into a cs code fileborland delphi can import a tlb into pas by using the command line tool tlibimpexecdeveloptlibimpexe sopquotingengineactivextlbborland tlibimp version 51 copyright c 1997 20 inprise corporationtype library loadedcreated cdevelopsopquotingengineactivex tlbdcrcreated cdevelopsopquotingengineactivex tlbpasand now there is a pas source code file containing constants enumerations interfaces that were inside the compiled type library tlb filesopquotingengineactivex tlbpasunit sopquotingengineactivex tlbinterfaceconst class xsopquotingengine tguid 3a46ffb880924920aee40a1acf81a0 interface ixsopquotingengine flags 4416 dual oleautomation thispatchable guid aa3b73cc8ed64261ab68e6ae154d7d52 ixsopquotingengine interfaceithispatch aa3b73cc8ed64261ab68e6ae154d7d52 procedure onstartpageconst ascriptingcontext iunknown safecall procedure onendpage safecall procedure connectconst connectionstring widestring safecall procedure thisconnect safecall function xmlratequoteconst xmlquote widestring widestring safecall end coxsopquotingengine class class function create ixsopquotingengine endwhat is the net c equivalent for importing a type library into native c codenote i have tried using tlbimpexe that comes with the windows sdk but that imports a type library into a managed assembly dllcdevelopcprogram filesmicrosoft sdkswindowsv71binnetfx 40 toolsx64tlbimp sopquotingengineactivextlbmicrosoft r net framework type library to assembly converter 40303191copyright c microsoft corporation all rights reservedtlbimp warning ti3002 importing a type library into a platform agnostic assembly this can cause errors if the type library is not truly platform agnostictlbimp type library imported to sopquotingengineactivexdllwhat is the net c equivalent for importing a type library into native c codenote what i want to see is a cs code file with all the required interfaces constants enumerations everything required to call the com object for examples sakesopquotingengineactivexcscomimport guidaa3b73cc8ed64261ab68e6ae154d7d52 public interface ixsopquotingengine void onstartpageobject ascriptingcontext void onendpage void connectstring connectionstring void thisconnect string xmlratequotestring xmlquotecomimport guid3a46ffb880924920aee40a1acf81a0public class xsopquotingengineclassexcept without the bugssee alsoconvert interface idl file to chow to read tlbtype librariesof unmanaged code from c net c is it possible to import tlb semiautomatically and add preservesig to one typetype library importer tlbimpexe,['c#'] +147340,apscheduler not starting i would like to run a python script during the night and so i was thinking of using apscheduler i will start running it at 1am of the following night and it will run once every nightmy scheduler script looks like this schedulerpyfrom apschedulerscheduler import schedulerfrom datetime import datetime timedelta time datedef myscript print okif name main sched scheduler startdate datetimecombinedatetoday timedeltadays1time1 schedstart schedadd interval jobmyscript start date startdate days1in the shell i dopython myschedulerpy thisown i am running it remotely so i want to run it in the background and thisown it immediately a number pid appears below the line as every other python script would do but when i do ps e grep python that number is not there i tried to do kill 9 pid and i got a message saying that the job does not exist is the scheduler running if yes how can i stop it if not what am i doing wrong,['python'] +147366,color values in imshow for matplotlib i would like to know the color value of a point i click on when i use imshow in matplotlib is there a way to find this information through the event handler in matplotlib the same way as the xy coordinates of your click are available if not how would i find this informationspecifically i am thinking about a case like thisimshownprandomrand1010255 interpolationnearestthankserin,['python'] +147370,css javascript show hide div using a css class i have googled around and found many scripts for hiding and showing div contents as a toggle on button click but they are work using idsi would like to do the same thing but i want to use a class instead of an id so that if i want to have 20 divs that toggle hide show i do not have to add extra codehere is some codescript languagejavascript function toggle var ele documentgetelementbyidtoggletext var text documentgetelementbyidthisplaytext ifelestylethisplay block elestylethisplay none textinnerhtml show else elestylethisplay block textinnerhtml hide scripta idthisplaytext hrefjavascripttoggleshowa click herediv idtoggletext stylethisplay noneh1peekabooh1divcan anyone help with this pleasethanks,"['javascript', 'jquery', 'html', 'css']" +147400,systemclocksleep vs threadsleep while waiting for a semaphore loop in order to synchronizequeue access to a shared resource i am about to use a semaphore aided by a wait loop in order not to run into cpu pegging i would like to sleep a little bit inside that while loopi searched the reference and found two such sleep functions and i am confused as to which one fits which scenariothreadsleepsystemclocksleepwhich one better suits the case i described and why,['android'] +147417,testing a custom contentprovider in android i have written my content provider supposed to wrap access to 2 tables in a sqllite database now i would like to write some test cases for it but i have never done it after reading the section on the developer guide i must say that i did not manage to get anything tested below is my code so far this is the only class in the test project that corresponds to my main project when i execute it in eclipse the emulator starts correctly the packages get installed but it does not run the testtest run failed test run incomplete expected 1 tests received 0here is the test classpublic class articleprovidertest extends providertestcase2articleprovider static final uri validuris new uri articlescontent uri picturescontent uri picturesgetcontenturiforarticleid1 public articleprovidertestclassarticleprovider providerclass string providerauthority superproviderclass providerauthority override protected void setup throws exception supersetup public void testquery contentprovider provider getprovider for uri uri validuris cursor cursor providerqueryuri null null null null assertnotnullcursor and the manifest file if it helps manifest xmlnsandroid packagefrmarvinlabsx androidversioncode1 androidversionname10 usessdk androidminsdkversion7 instrumentation androidtargetpackagefrmarvinlabsx androidnameandroidtestinstrumentationtestrunner application androidicondrawableicon androidlabelstringapp name useslibrary androidnameandroidtestrunner applicationmanifestwhen i launch in debug configuration breakpoints in the constructor and in the setup do not get triggered i also did not find much info on the net could anybody help me get some understanding on how the testing should be setup basically create a test database file fill it with some data query it,['android'] +147443,how to set the color of placeholder text is that possible to set the color of placeholder text textarea placeholderwrite your message heretextarea,"['html', 'css']" +147468,how to get the field names of the table in cakephp i am a complete newbie in cakephp i want to read the field names of the table in the controller i want the controller to list all the field names in the table how do i do that,['php'] +147474,how to minify different javascript files at runtime using java i am trying to build or find an existing one i can use a web filter that will compress a javascript file at runtime i have tried building one based on yuicompressor but i am getting weird errors out of it when i try and pass a string based source into it instead of an actual filenow i am expecting to get bombarded with responses like real time compressionminification is a bad idea but there is a reason i am not wanting to do it at build timei have got a javascript web application that lazy loads it is javascript it will only load what it actually needs the javascript files can specify dependencies and i already have a filter that will concatenate the requested files and any dependencies not already loaded into a single response this means that there is a large number of different combinations in the javascript that will be sent to the user which makes trying to build all the bundles at build time impracticalso to restate ideally i am looking for an existing real time javascript filter i can just plug into my appif one does not exist i am looking for tips on what i can use as building blocks yuicompressor has not quite got me there and googleclosure seems to only be a web apicheerspeter,"['java', 'javascript']" +147481,change internet explorer settings programmatically any idea how do i do the following using c going to tools internet options securityselect the security tabclick the custom level buttonin the miscellaneous section change thisplay mixed content to enable,"['c#', '.net']" +147491,c0x nested initializer lists i would like to use c0x new initializer list feature to initialize a stdvector with a compile time defined number of items for a new api i am currently working on something like thistemplateint nstdinitializer liststdstring duplicatestdstring s return s duplicated and times return s s s stdvectorstdstring v foo duplicate3bar do you have any idea how to accomplish this is it even possible i am aware of that i will need to use tmp and recursion to build up the list of duplicated strings and finally access it somehow through a constant eg enum but it seems that i cannot even nest the initializer list like this,['c++'] +147507,cannot get my ec2 windows server 2008 web stack instance to receive publishings of my website i installed a fresh ami for ec2 and have installed web deploy 21 on itthe web deploy 21 service is running for real asnetstat anshows 8172 is being listened on by the web deployment agent servicebut when i try to deploy to this site using projectrightclickpublish via web deploy i receive the following error message build started project cirweb configuration debug any cpu cirweb cprojectscrazyinsanerobotsourcecirwebbincirwebdll publish started project cirweb configuration debug any cpu transformed webconfig using webdebugconfig into objdebugtransformwebconfigtransformedwebconfigauto connectionstring transformed viewswebconfig into objdebugcsautoparameterizetransformedviewswebconfigauto connectionstring transformed objdebugtransformwebconfigtransformedwebconfig into objdebugcsautoparameterizetransformedwebconfigcopying all files to temporary location below for packagepublishobjdebugpackagepackagetmpstart web deploy publish the applicationpackage to cprogram files x86msbuildmicrosoftvisualstudiov100webmicrosoftwebpublishingtargets38475 warning retrying the sync because a socket error 10054 occurred retrying operation serialization on object sitemanifest sourcepath attempt 1 of 10cprogram files x86msbuildmicrosoftvisualstudiov100webmicrosoftwebpublishingtargets38475 warning retrying the sync because a socket error 10054 occurred retrying operation serialization on object sitemanifest sourcepath attempt 2 of cprogram files x86msbuildmicrosoftvisualstudiov100webmicrosoftwebpublishingtargets38475 warning retrying the sync because a socket error 10054 occurred retrying operation serialization on object sitemanifest sourcepath attempt 10 of 10cprogram files x86msbuildmicrosoftvisualstudiov100webmicrosoftwebpublishingtargets38475 error web deployment task failedcould not complete the request to remote agent url web sitethis error indicates that you cannot connect to the server make sure the service url is correct firewall and network settings on this computer and on the server computer are configured properly and the appropriate services have been started on the servererror detailscould not complete the request to remote agent url web sitethe underlying connection was closed an unexpected error occurred on a sendunable to read data from the transport connection an existing connection was forcibly closed by the remote hostan existing connection was forcibly closed by the remote hostpublish failed to deploy build 1 succeeded or uptodate 0 failed 0 skipped publish 0 succeeded 1 failed 0 skipped my firewall on the ec2 instance has been turned off and my aws firewall settings arewhich are the recommended settingsother notesthoughtsmy web deploy error log in the windows error log is completely emptyi have used web deploy before using a different ami in the past and succeeded without problemsif anyone has any suggestions about how to debug this i would be so ever grateful,['asp.net'] +147509,constructor in objective c i am beginner in iphone developmenti was trying this sample program belowi am not calling the voidinitialise and idinit method in the class bbut its getting called automaticallyis the voidintialise is equal to the default constructor in objective cdoes the super init points to the nsobjectif i am not using the idinit method i am getting a warning that the class is with incomplete implementation classahimport foundationfoundationhstatic int abinterface classa nsobject int a void initialize id init void thisplaynumofinstance void thispendclassamimport classahimplementation classa void initialize ab0 id init self super init if selfnil ab return self void thisplaynumofinstance nslognumber of instances of this classdab void thisp nslogthe value is dabendclassbhimport foundationfoundationhimport classahinterface classb classa void thisplayendclassbmimport classbhimplementation classb void thisplay ab20 nslogthe value ab is dabendclass2mimport foundationfoundationhimport classahint main int argc const char argv classa a classa allocinit a thisp a release classb b classb allocinit b thisplay b release classa a1 classa allocinit a1 thisp a1 release classb b1 classb allocinit b1 thisplay b1 release return 0output20110430 153142490 class21674a0f 120110430 153142493 class21674a0f the value ab is 2020110430 153142494 class21674a0f 220110430 153142495 class21674a0f the value ab is 20,['objective-c'] +147510,generating javascript documentation i am looking for a way to generate documentation automatically from my javascript project anyone know how can i do thisas far as i know therere some tools like jsdoc but i want to know your opinion your best choice and whythanksedit just to be clear i need something like javadoc or phpdocumentor but to use with my javascript source code,['javascript'] +147516,jquery get id of element by searching for it by class this is my html div idmy box one classheaddiv div div clasome boxadiv div clasome boxbdiv divdivi want to get the id of the parent divmy box one using the class of that divheaddiv documentreadyfunctionsome boxclickfunction var abc thisparentsuntilheaddivattrid also tried thisparentheaddiv same effect alertabc shows as undefined i can do the following and it will work okay but it does not seem rightvar abc thisparentdivparentdivattrid,['jquery'] +147519,get user image from facebook graphapi i want to show the users profile picture in a list view when i try to call the graphapi from android to retrieve the image i always get the following error javaioioexception hostname fbcdnprofileaakamaihdnet was not verified at orgapacheharmonyluniinternalnetwprotocolhttphttpconnectiongetsecuresockethttpconnectionjava170 at orgapacheharmonyluniinternalnetwprotocolhttpshttpsurlconnectionhttpsengineconnecthttpsurlconnectionjava398 at orgapacheharmonyluniinternalnetwprotocolhttphttpurlconnectionsendrequesthttpurlconnectionjava1224 at orgapacheharmonyluniinternalnetwprotocolhttphttpurlconnectiondorequestinternalhttpurlconnectionjava1558 at orgapacheharmonyluniinternalnetwprotocolhttphttpurlconnectiondorequesthttpurlconnectionjava1551 at orgapacheharmonyluniinternalnetwprotocolhttphttpurlconnectiongetinputstreamhttpurlconnectionjava1052 at orgapacheharmonyluniinternalnetwprotocolhttpshttpsurlconnectiongetinputstreamhttpsurlconnectionjava252 at comfacebookandroidutilopenurlutiljava200 at comfacebookandroidfacebookrequestfacebookjava559this is the code used by meprivate static void retrieveprofilepicturestring userid throws malformedurlexception ioexception facebook facebookhelpergetinstance bundle bundle new bundle bundleputstringfacebooktoken facebookgetaccesstoken object picture facebookrequestuseridpicture bundle getwhen i do the same call in the browser token then i get the image returned on a url like this in which format is the image delivered to me json with a ref to image url,['android'] +147530,dynamically set frame src using javascript i have a html elementframe src titlecontent frame namecontent idcontent i want to set it is src dynamically using javascript on page load how can i do that i am trying something likedocumentgetelementbyidcontent2contentwindowlocation xyz framehtmlbut for some reason it is not workingagain it is a element and not a rough codehtmlheadscript languagejavascript function loadpage documentgetelementbyidcontent2src ipad lrd framehtmlscript headbody onloadloadpageframe idcontent2framebodyhtml,"['javascript', 'html', 'css']" +147535,how to detect ctrlf in my swt application i have written an swt ui which has a primary function of thisplaying text in a styledtext control i want to add a handler for ctrlf so that when that shortcut is pressed the focus is set to a search box i have tried using the following code to detect the keypreswindow new shellswindowgetthisplayaddfilterswtkeydown new listener override public void handleeventevent e systemoutprintlnfilterctrl swtctrl systemoutprintlnfiltermask estatemask systemoutprintlnfilterchar echaracter i was expecting that when i pressed ctrlf i would see the following outputfilterctrl 262144filtermask 262144filterchar fhowever in practice i actually see the followingfilterctrl 262144filtermask 262144filterchar unprintable char thisplayed as a box in eclipse consolei have two questionsis thisplayaddfilter the best way to add a global shortcut i tried thisplayaddlistener but this did not receive any events at allwhy do not i get the pressed character when i am holding down ctrl when i hold down alt or shift i get the expected mask and the pressed character,['java'] +147542,background image dark or light i am doing a odphtml conversion with php i have problems with the followinguse the styleusewindowfontcolor property to specify whether or not the window foreground color should be as used as the foreground color for a light background color and white for a dark background coloropendocument specification version 10 1544if i have a background image how do i check if this image is light or darkdo you have any ideasthanks in advancelevu,['php'] +147548,how to deploy war of maven project to jboss server from eclipse i want to deploy war of maven project to jboss server i know that from eclipse exportwar deploy the war file to jboss but how can i do this for maven project any step by step information or useful website link will be very helpful to me thank youedit i have added plugingroupidorgcodehausmojogroupidartifactidjbossmavenpluginartifactidversion150versionconfiguration jbosshomehometanmoyjbossjbosshome servernameallservername filenametargetloginexample10warfilenameconfigurationpluginto my pomxml and import again as maven project but on right clicking into pomxml for run as i do not see any option for deployment,['java'] +147549,backbonejs and threejs mvc with canvas i am in the planning stages of developing a small webapp that does some interactive data visualization in a 3d spacefor widest browser compatibility threejs looks like the best choice as i can render the same scene using webgl canvas or svg ideally i am wanting to use backbonejs to provide a nice mvc layer and avoid some tediousness of writing the ajax but before i get to far with it i was wondering if anyone had any experiencetipswords of advice in trying to make that workassuming canvas or webgl it seems like the backboneview could be pretty easily abstracted to support a threejs model the render function is meant to be overridden i could attach a simple listener on the canvas and then us some threejs trickery to pull out the specific model for firing off events which seems like it would be the most difficult task backbone models and collections would work just fine with my api i think the controllers would probably be a bit more difficult but could possibly even be used by saving the position of the camera or something similarwith svg rendering this is obviously simplified with all the elements being in the dom but i question if svg would even be a good option when there are 10 objects in the scene anyone have experience with large scene graphs in svg is there other libraries either for rendering or similar to backbone that would be a better route to take i am open to suggestion on the matter,['javascript'] +147559,a permanent way of doing mysqliset charset after setting all config file and runtime options for charset that i can find to utf8 new mysqli connections made with php still has its charset set to latin1 which effectively means that i have to call mysqliset charsetutf8 each time i connectmysqli new mysqlidb host db user db pass db name if mysqliconnect error err handlemysql connect errormysqliconnect errno if mysqliset charsetutf8 err handledb errormysqlierrnoi wonder if there is a permanent way of doing thissimilar problem was encountered in this posta show variables like character set query on the mysql server before calling mysqliset charsetutf8 showsthis part was ambiguous in previous revscharacter set client latin1 character set connection latin1 character set database utf8 character set filesystem binary character set results latin1 character set server utf8 character set system utf8 the client connection and results charset can only be changed to utf8 with mysqliset charsetutf8 at runtime after that it showscharacter set client utf8 character set connection utf8 character set database utf8 character set filesystem binary character set results utf8 character set server utf8 character set system utf8 i have default charset utf8set in phpini and client defaultcharactersetutf8 mysqld this option is deprecated in favor of charactersetserverdefaultcharactersetutf8 set in mycnfthe default charset for my tables is also utf8seems like the client options only affect the cmd mysql tool and have nothing to do with phpthe return value of mysqlicharacter set name is always latin1 no matter what i do until mysqliset charsetutf8 is calledi guess latin1 is a mysql thing since i cant recall anything else that defaults to latin1 on my systemupdate according to mysql manual 914 915 and 513 character set client should be provided by the client i guess php does not provide it upon connection and mysql uses the fallback charset latin1i am running php 53 on debian wheezy with mysql 51any suggestionupdated with info from commentsi forgot to mention the skipcharactersetclienthandshake directive and why i was reluctant to use itupon first sight i thought ignoring the handshake might result in the situation that the client talks latin1 while the server talks utf8 how does the server convert the string from charset character set client to character set server without knowing the charset currently in usecorrect me if i am wrong plz i will experiment with this setting later today to see if it worksupdated with workaroudmake sure everything works under utf8 or any preferable charset then add the skipcharactersetclienthandshake line to mycnfthis works for me so far i experimented with some doublewidth utf8 characters both insert and select succeeded and thisplayed properly in the browserwhat skipping the handshake means is still unclear and the mysql server now becomes uncapable of using any charset except utf8 whick makes this workaround quite impractical since i simply cant apply this setting to all the servers that my website runs onso i am not adopting this workaround further comments and answers are much appreciated,"['php', 'mysql']" +147575,cannot load view in area in aspnet mvc 3 using vbnet i have the latest versions of vs 2010 net 40 and mvc 3 and i have a problem using areas in aspnet mvc 3 when using vbneti do the followingcreate a new visual basic aspnet mvc 3 project select razor as the view engin and call the project testappcreate a new area called test it will be in the folder areastestadd a new empty controller called pagecontrollervb in areastestcontrollersadd a new folder in areastestviews called pageadd a new empty view called indexvbhtml in areastestviewspagerun the projectmanually type the url httplocalhostxyztestpage in the browser where xyz is the automatically added portnumber generated by vsat step 7 i get the message the resource cannot be foundif i do exactly the same thing using c then i will get to the correct page and it will show the word index as expectedis this a bug or am i missing something i have been scanning the web for hours trying to solve this but i am getting nowarethis is the automatically created testarearegistrationvb filenamespace testappareastest public class testarearegistration inherits arearegistration public overrides readonly property areaname as string get return test end get end property public overrides sub registerareabyval context as systemwebmvcarearegistrationcontext contextmaproute test default testcontrolleractionid new with action index id urlparameteroptional end subend classend namespaceand this is the automatically created globalascx file note for instructions on enabling iis6 or iis7 classic mode visit public class mvcapplication inherits systemwebhttpapplicationshared sub registerglobalfiltersbyval filters as globalfiltercollection filtersaddnew handleerrorattributeend subshared sub registerroutesbyval routes as routecollection routesignorerouteresourceaxdpathinfo maproute takes the following parameters in order 1 route name 2 url with parameters 3 parameter defaults routesmaproute default controlleractionid new with controller home action index id urlparameteroptional end subsub application start arearegistrationregisterallareas registerglobalfiltersglobalfiltersfilters registerroutesroutetableroutesend subend classthese are identical with what you get if you repete steps 17 and use c only difference is that you will get c code that is equal to above vbnet codei repete if i do the steps 17 in c it works but it will not work in vbnet what is wrong,['c#'] +147584,how come cpython is faster than pypy on the two tests slowspitfire and waf judging from the benchmarks posted on the pypy speed center it appears as if pypy is faster than cpython for all but two of the tests presentedcpython is faster than pypy on the two tests slowspitfire and waf why is that what kind of operations do those two tests test what makes cpython faster for those operations can pypy be expected to catch up and beat cpython also for those two tests,['python'] +147612,how to thisable the collapsing of an expandablelistview i would like to implement a expandablelistview which should be expandable only after all the values have been set up within the adapter also i would like to be able to thisable the collapsing of the expander can i achieve this within an android xml layoutregardsa jabeer ali,['android'] +147622,getscript how to only call if not already called on a click the following gets loadedgetscriptjavascriptscontactsjshow can i write a statement that saysif the getscript above is already loaded do x if not loaded it do ythanks,['jquery'] +147638,contractrequires throwing pex errors possible duplicatehow do you configure pex to respect code contracts currently when i run a pex exploration the code contracts i created in my classes are being treated as errors in the pex exploration results i thought when you ran pex exploration using code contracts the contract failures should be treated as expected behaviorhere is the code causing the exceptionstest methodpexmethodpublic void testequalityguid userid string username string password string securityquestion string securityanswer usersecurity user usertoolscreateuserguidnewguid username password securityquestion securityanswer bool passwordresult usertoolsverifyinputpassword userpassword userpasswordsalt bool securityanswerresult usertoolsverifyinputsecurityanswer usersecurityanswer usersecurityanswersalt assertistruepasswordresult password did not correctly rehash assertistruesecurityanswerresult security answer did not correctly rehashfailing method callpublic static usersecurity createuserguid userid string username string password string securityquestion string securityanswer contractrequiresuserid guidempty contractrequiresstringisnullorwhitespaceusername contractrequiresstringisnullorwhitespacepassword contractrequiresstringisnullorwhitespacesecurityquestion contractrequiresstringisnullorwhitespacesecurityanswer contractensurescontractresultusersecurity null byte passwordsalt byte securityanswersalt return new usersecurity userid userid username username password securityutilitiesgeneratehashpassword out passwordsalt passwordsalt passwordsalt securityquestion securityquestion securityanswer securityutilitiesgeneratehashsecurityanswer out securityanswersalt securityanswersalt securityanswersalt descriptionfailing test contractexception precondition failed stringisnullorwhitespaceusernameguid s0 new guiddefaultint short32 short32 defaultbyte defaultbyte defaultbyte defaultbyte defaultbyte defaultbyte defaultbyte defaultbytethistestequalitys0 stringnull stringnull stringnull stringnulltestmethodpexgeneratedbytypeofhashtestspexraisedcontractexceptionpublic void testequalitythrowscontractexception173 guid s0 new guiddefaultint short32 short32 defaultbyte defaultbyte defaultbyte defaultbyte defaultbyte defaultbyte defaultbyte defaultbyte thistestequalitys0 stringnull stringnull stringnull stringnull,['c#'] +147656,can i typedef a template template parameter in c library headers well sometimes see the following to improve legibility of the code inside a classtemplatetypename myexplicitelylongtemplateparameterclass cpublic typedef myexplicitelylongtemplateparameter p use p and keep your sanitymy question is can one do the same with template template parametertemplatetemplatetypename typename myexplicitelylongtemplateparameterclass cpublic typedef p use p and keep your sanity,['c++'] +147659,android rdrawable not showing my image in my android 22 app i have added my image to the resdrawablemdpi folder however i cannot seem to access it using rdrawable as far as i know there is not any additional configuration i need to do any help,['android'] +147688,how to extend class object in rails i would like to add method nil or empty to all classes therefore i definemodule objectextensions def nil or empty return selfnil selfrespond toempty selfempty endendobjectclass eval include objectextensions it works fine in a simple ruby scriptp nilnil or empty truep nil or empty truep nil or empty truep 0nil or empty falsehowever when i add it to my library file libextensionsrb in a rails 3 app it seems to be not addednomethoderror undefined method nil or empty for nilnilclass appcontrollersapplication controllerrb1in before filter testi do load the library file all other extensions from that file are working fine and configapplicationrb configautoload paths libwhere am i wrong,"['ruby-on-rails', 'ruby']" +147691,how to thisplay consolelog output in phonegap app using eclipse and htc desire hd i am developing phonegap webapp where i use some javascript and sometimes i need to see consolelog output i can easily see it when running in chrome it also works fine when running this app in android emulator output of consolelog shows up in eclipse logcat window but when i run this app on my htc desire hd logcat just shows some androidspecific output but nothing coming from my webapp anybody has idea how to thisplay consolelog output from phonegapapp running on htc desire hd,['android'] +147692,what is the nondeprecated way to initialise a char in c when i initialise a local char variable like so in cchar pattern oggsthe compiler warns mefoocpp34 warning deprecated conversion from string constant to acharawhat is the nondeprecated way to do this in cin case it matters heres how i am invoking the compiler from eclipseg45 o0 g3 wall stdc0x c fmessagelength0 mmd mp mffood mtfood ofo foocpp,['c++'] +147699,use convolution to find a reference audio sample in a continuous stream of sound in my previous question on finding a reference audio sample in a bigger audio sample it was proposed that i should use convolutionusing dsputil i was able to do this i played a little with it and tried different combinations of audio samples to see what the result was to visualize the data i just dumped the raw audio as numbers to excel and created a chart using this numbers a peak is visible but i do not really know how this helps me i have these problemsi do not know how to infer the starting position of the match in the original audio sample from the location of the peaki do not know how i should apply this with a continuous stream of audio so i can react as soon as the reference audio sample occursi do not understand why picture 2 and picture 4 see below differ so much although both represent an audio sample convolved with itselfany help is highly appreciatedthe following pictures are the result of the analysis using excela longer audio sample with the reference audio a beep near the endthe beep convolved with itselfa longer audio sample without the beep convolved with the beepthe longer audio sample of point 3 convolved with itselfupdate and solutionthanks to the extensive help of han i was able to achieve my goalafter i rolled my own slow implementation without fft i found alglib which provides a fast implementationthere is one basic assumption to my problem one of the audio samples is contained completely within the otherso the following code returns the offset in samples in the larger of the two audio samples and the normalized crosscorrelation value at that offset 1 means complete correlation 0 means no correlation at all and 1 means complete negative correlation private void calccrosscorrelationienumerabledouble data1 ienumerabledouble data2 out int offset out double maximumnormalizedcrosscorrelation var data1array data1toarray var data2array data2toarray double result alglibcor1ddata1array data1arraylength data2array data2arraylength out result var max doubleminvalue var index 0 var i 0 find the maximum cross correlation value and its index foreach var d in result if d max index i max d i if the index is bigger than the length of the first array it has to be interpreted as a negative index if index data1arraylength index 1 var matchingdata1 data1 var matchingdata2 data2 var biggersequencecount mathmaxdata1arraylength data2arraylength var smallersequencecount mathmindata1arraylength data2arraylength offset index if index 0 matchingdata1 data1skipoffsettakesmallersequencecounttolist else if index 0 offset biggersequencecount smallersequencecount index matchingdata2 data2skipoffsettakesmallersequencecounttolist matchingdata1 data1takesmallersequencecounttolist var mx matchingdata1average var my matchingdata2average var denom1 mathsqrtmatchingdata1sumx x mx x mx var denom2 mathsqrtmatchingdata2sumy y my y my maximumnormalizedcrosscorrelation max denom1 denom2bountyno new answers required i started the bounty to award it to han for his continued effort with this question,"['c#', '.net']" +147700,django is so slow errno 32 broken pipe dcramerdjangosentry static folder i have been using django 13 with python 26 on ubuntu 1010 i have 3 questionsi recall having this problem on windows 7 when i used django a while ago however i also remember that when i first used django this problem did not occurwhen i access django via 12700180 after starting a brand new project i can reach the site but sometimes it takes a good 1020 secs and sometimes more to reach it also on a project i have barely worked on i have the same problems and also get errors likeexception happened during processing of request from 127001 47758traceback most recent call last file usrlibpython26socketserverpy line 283 in handle request noblock selfprocess requestrequest client address file usrlibpython26socketserverpy line 309 in process request selffinish requestrequest client address file usrlibpython26socketserverpy line 322 in finish request selfrequesthandlerclassrequest client address self file usrlocallibpython26thistpackagesdjango13py26eggdjangocoreserversbasehttppy line 570 in init basehttprequesthandler init self args kwargs file usrlibpython26socketserverpy line 618 in init selffinish file usrlibpython26socketserverpy line 661 in finish selfwfileflush file usrlibpython26socketpy line 297 in flush self socksendallbufferdata write offset buffer sizeerror errno 32 broken pipealso whenever i get an error i expect dcramers djangosentry to log the error in the database but when i go into mysql and check the tables there is nothing there i followed the instructions on the site to install the appi placed this in my urlspy fileurlrstaticppath djangoviewsstaticserve document root homeuserapache2wdjangoecomstorestatichowever when i go to 12700180staticcsscss i cannot find the file i placed in the folder what did i do wrongthanks for all the help,['python'] +147704,how to extend a class at runtime with reflection imagine that i have two class a and b b extends a likeclass b extends a however in my case class a is encrypted and can be only loaded by my classloader at runtime at compiling time aclass can not be recognized as a class file because it is encrypted this means class a does not exist at compiling time my questions arehow can write the code for class b as some methods override the methods in class ahow can i specify class b extends to class a at runtime,['java'] +147724,equals and operator in java i know that equals will compare the value of objects the operator will check if the variable point to the same memoryi do not understand how equals compare the value of objects for exampleclass test public testint x float y thisx x thisy y int x float ytest test1 new test120test test2 new test120so if i use equals will it compare each properties in each objectand what about if we are talking about string using equals and operator aa do we still need to override the equals,['java'] +147730,how can an anonymous class use extends or implements how can an anonymous class extend a superclass or implement an interface,['java'] +147745,mvc html helpers and lambda expressions i understand lambda queries for the most part but when i am trying to learn mvc and i see the default scaffolding templates they use lambda expressions for so many componentsone for example is the thisplayfor html helper the code goes htmlthisplayformodel modelnamei hope no one thinks this is a stupid question it is just that whilst i think i understand lambda expressions for the most part they do not flow like regular code and i have to think about it quite hard to understand what is actually happeningso the question really is 1 is there any benefit that i am missing to them using lambda queries for these html helpers2 as far as i can tell the thisplayfor will only ever be hooked up to one item so why is not this just htmlthisplayformodelname or similarand please give any other information that can make a mvc newbie better,['c#'] +147757,net getting all implementations of a generic interface an answer on implementations of interface through reflection shows how to get all implementations of an interface however given a generic interface iinterfacet the following does not workvar types typesimplementinginterfacetypeofiinterfacecan anyone explain how i can modify that method,"['c#', '.net']" +147761,one xib file with multiple files owners i have got three different uitableviews each in it is own view accessed via tabs all three tables would ideally share the same custom uitableviewcell class and xib file i started with one table setting the class of the xib to my custom class and the files owner of the xib to the tables parent uiviewcontroller which works great all of the custom viewrelated code is in the cells class background images based on a property set by the controller custom cell height based on the number of lines a label requires based on a cell property set by the controller etcthe result is nice the cell is responsible for all of the visual layout and responding to user actions on the cells controls while the view controller is responsible for creating the cells and setting their data now that i need to reuse the cell in other tables though the fact that the custom cells xib has a single files owner is a problem rather than duplicating the xib file is there a simple way to allow multiple controllers to own it,"['iphone', 'ios']" +147762,get the event object in an event handling function without pass the event object as parameters with jquery i have this a href onclickmyfunc123clickaand the javascript also defines this function myfuncp1p2p3 need to refer to the current event object alertevttype since the event object evt is not passed from the parameter is it still possible to obtain this object i tried windowevent or windowevent but both are undefinedany idea,"['javascript', 'jquery']" +147769,how to check if a file is set in php i have created a form with 3 input typefilei see that i get an array with arraynameso i check if filemyfilenamename insteadthis works but it seems rather unusual to mei was wondering if there was a better way to check if a file input is set or not,['php'] +147771,tic toc functions analog in python what is the best analog of matlab tic and toc functions in python,['python'] +147780,cost of file modification time checks for a file containing few bytes under linux i need only to process when it was changed since the last time it was processedi check whether the file was changed by calling php clearstatcache filemtime periodicallysince the entire file will always be tiny would it be a performance improvement to remove the call to filemtime and check for a file change by comparing the contents with the past contentsor what is the best method for that in terms of performance,['php'] +147810,is it safe to access a default argument by reference i have a function that looks like thisclass someclass void some functionconst someclass arg someclassthe function some function accesses its argument by reference and has a default value is it safe to do this or will the reference be invalid when i call the function without an argument,['c++'] +147816,reinventing the wheel random number generator so i am new to c and am trying to learn some things as such i am trying to make a random number generator rng or prng if you will i have basic knowledge of rngs like you have to start with a seed and then send the seed through the algorithm what i am stuck at is how people come up with said algorithms here is the code i have to get the seedint getseed time t randseed randseed timenull return randseednow i know that there is are prebuilt rngs in c but i am looking to learn not just copy other peoples work and try to figure it outso if anyone could lead me to where i could read or show me examples of how to come up with algorithms for this i would be greatly appreciative,['c++'] +147827,how do you add join information to a rails seedsrb file i am trying to build a seedsrb file to add an initial admin user to the database i have a users table and model and a roles table and model i have a join table roles users to join the users role and permissions heres the schema create table roles force true do t tstring name tdatetime created at tdatetime updated at end create table roles users id false force true do t tinteger role id tinteger user id end create table users force true do t tstring email default null false tstring encrypted password limit 128 default null false tstring reset password token tdatetime remember created at tinteger sign in count default 0 tdatetime current sign in at tdatetime last sign in at tstring current sign in ip tstring last sign in ip tdatetime created at tdatetime updated at tstring first name tstring last name endi have figured out how to add the users and the roles using the repsective models for eachsetup our default rolesrolecreatename super adminrolecreatename school leaderrolecreatename school staffrolecreatename studentsetup and initial super admin userusercreatefirst name admin email password adminhow do i add the join to make grant the admin super admin privileges database being used is sqlite3,"['ruby-on-rails', 'ruby']" +147829,securing aspnet mvc controller action which returns json i have an mvc3 application and my controller actions are secured using the authorize attribute so far so good forms auth works great now i want to add a json api to my application so some actions are accessible to nonbrowser clientsi am having trouble figuring out the right design1 each user has secret api key2 user id 5 calls param2value2secure hashsomevalue here secure hash is simply the sha1 hash of param1 and param2s values appended with the secret api key for the user2 foocontrollerbaraction will be decorated with customauthorize this will be an implementation of authorizeattribute which will check if the request is coming in as json if it is it will check the hash and see if it matches otherwise if the request is html then i call into existing authorizationi am not at all sure if this will work is it normal to pass a secure hash in the query string or should i be passing it in as an http header is it better to use http basic auth instead of a hash made using the secret api keytips from anyone who has made a web api using aspnet mvc would be welcome,['asp.net'] +147848,django admin thisplay multiple fields on the same line i have created a model it will automatically thisplay all the fields from the model and thisplay it on the admin pagenow i have a problem i would like to have two fields on the same line to do this i have to specify the fieldsets at modeladminfieldsets none fields firstname lastname do i have to specify all the fields because there are many fields in the database i need to specify,['python'] +147849,applying oop with jquery i am working with jquery and trying to apply some basic javascript oop principles to a set of functions that control hover behavior however i cannot figure out how to get the this keyword to refer to the instance of the object i am creating my sample code isvar zoomin new objectzoomin function constructor goes herezoominprototype hoveron function thishoverreset more logic here using jquerys this hoverreset function some logic here create new instance of zoomin and apply event handler to matching classesvar my zoomin new zoominsome classhovermy zoominhoveron function return null the problematic line in the above code is the call to thishoverreset inside the hoveron function since this now refers to element that was hovered on it does not work as intended i would basically like to call the function hoverreset for that instance of the object my zoominis there any way to do thisthanks,"['javascript', 'jquery']" +147851,why do includes in rails engine initializers malfunction when cache classes false i have an engine which is extending another engines classes in its initializers like somodule myapp class engine railsengine initializer extend product do anotheraproductsend include myaproductextender end endendthe productextendermodule calls some methods on the anotheraproduct when it is included egmodule productextender def selfincluded model modelsend include methodstocall end module methodstocall def selfincluded m mhas many variations end endendthis works in test and production environments but when configcache classes false it throws a nomethoderror at me when i try to call something defined by the productextender like productvariations needless to say it is chilling to see all my tests pass and then get slammed with an error in development it does not happen when i set cache classes true but it makes me wonder if i am doing something i should not bemy question is twofold why is this happening and is there a better way i should be achieving this functionality of extendingcalling methods on another applications objectthanks all,['ruby-on-rails'] +147856,auto break line in html i have been doing a comment box and i have a problem after viewing my comment all i want is to make my comment auto break line when it exceeds the container but what i have got right now is a straight line for exampleti hope my text can be like thist t t what should i use to make my text auto break line,"['html', 'css']" +147876,php get number of week for month so i have a script that returns the number of weeks in a particular month and year how can i take a specific day from that month and determine if it is part of week 1234 or 5 of that month,['php'] +147882,using variables in sql queries in aspnet c i have an sql query of this formstring cmdtext select from searchtable where searchtable name searchvalue basically what i am trying to do is get a particular actors info from the databases actors table the variable searchtable has the value actor which is the table name and searchvalue has the actors name which is represented by the actorname attribute in the actors table here i am trying to form the name of the attribute by concatenating the words actor and name so well all this concatenation results in or at least should result in a query of the formselect from actor where actorname some actorbut when i try to run this it gives me the error incorrect syntax near in the browser could anyone please help,"['c#', 'asp.net', 'sql']" +147900,why does resuming an activity in android cause badtokenexception folks can anyone explain this stack note that my code is nowhere on it if you google for any of these exceptions everyone who has experiencing this issue was trying to create dialogs after an activity was terminated which does not seem to be the case here it is just a simple activity resume i am seeing this exception reported from clients in the field quite frequently and would like to correct it if possible androidviewwindowmanagerbadtokenexception unable to add window token androidosbinderproxy405177d8 is not valid is your activity runningat androidviewviewrootsetviewviewrootjava527at androidviewwindowmanagerimpladdviewwindowmanagerimpljava177at androidviewwindowmanagerimpladdviewwindowmanagerimpljava91at androidviewwindowlocalwindowmanageraddviewwindowjava424at androidappactivitythreadhandleresumeactivityactivitythreadjava2268at androidappactivitythreadhandlelaunchactivityactivitythreadjava1721at androidappactivitythreadhandlerelaunchactivityactivitythreadjava2955at androidappactivitythreadaccess1600activitythreadjava124at androidappactivitythreadhhandlemessageactivitythreadjava972at androidoshandlerthispatchmessagehandlerjava99at androidoslooperlooplooperjava123at androidappactivitythreadmainactivitythreadjava3806at javalangreflectmethodinvokenativenative methodat javalangreflectmethodinvokemethodjava507at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava839at comandroidinternaloszygoteinitmainzygoteinitjava597at dalviksystemnativestartmainnative methodupdatehere is how i am able to retrieve this stack remotely first i add an uncaughtexceptionhandler at the top of my activitys oncreatetry file crashlogdirectory new fileenvironmentgetexternalstoragedirectorygetcanonicalpath constantscrashlogdirectory crashlogdirectorymkdirs threadsetdefaultuncaughtexceptionhandlernew remoteuploadexceptionhandlerthis crashlogdirectorygetcanonicalpath catch exception e if myactivitywarn logemyactivitytag exception setting up exception handler etostringin my remoteuploadexceptionhandler class i have the following codepublic void uncaughtexceptionthread t throwable e string timestamp calendargetinstancegettimetogmtstring string filename timestamp stacktrace final writer result new stringwriter final printwriter printwriter new printwriterresult eprintstacktraceprintwriter string stacktrace resulttostring printwriterclose sendtoserverstacktrace filename defaultuehuncaughtexceptiont eprivate void sendtoserverstring stacktrace string filename defaulthttpclient httpclient new defaulthttpclient httppost httppost new httppostconstantsremoteuploadurl listnamevaluepair nvps new arraylistnamevaluepair nvpsaddnew basicnamevaluepairfilename filename nvpsaddnew basicnamevaluepairstacktrace stacktrace nvpsaddnew basicnamevaluepairplatform version platformversion nvpsaddnew basicnamevaluepairdevice id deviceid nvpsaddnew basicnamevaluepairbuild device builddevice nvpsaddnew basicnamevaluepairbuild brand buildbrand nvpsaddnew basicnamevaluepairbuild product buildproduct nvpsaddnew basicnamevaluepairbuild manufacturer buildmanufacturer nvpsaddnew basicnamevaluepairbuild model buildmodel nvpsaddnew basicnamevaluepairbuild version stringformatdbuildversionsdk int try httppostsetentity new urlencodedformentitynvps httputf 8 httpclientexecutehttppost catch ioexception e eprintstacktrace this is the code that is sending me many stacks per hour like the one i have shown above moreover if you look at the activitythread code through google code search you can see this check prior to the call to addviewif rwindow null amfinished willbevisible thus the activity has not finished and as such it should be still valid additionally the line numbers do not seem to match with what you can see in the google source code checkout the activitythreadjava file in the 233 source line 2268 is in the private method createthumbnailbitmap the build version uploaded by the crashing client is 10 which indicates sdk int is 10 and so it is 233,['android'] +147924,argparse incorrect order of positional and optional parameters why would not argparse parse these argumentsfoo 1 2 3 barusingparser argparseargumentparserparseradd argumentfoo nargs parseradd argumentbarwhich gives the following errorerror too few argumentsif i pass the bar argument first though it worksbar foo 1 2 3 now this in itself is not too bad i can live with having the positional arguments first it is just that this behaviour is inconsistent with the help argparse creates for us which states that bar should be lastusage argparsetestpy h foo foo foo barso how do you make this work with consistent help textheres a complete test program,['python'] +147928,add listener vs set listener what is the difference between adding a listener and setting a listeneregaddtextchangedlistenertextwatchersetonclicklistenerclicklisteneranswerafter aioobes answer i have tested this in my project so we can do thisedittextaddtextchangedlistenertextwatcher1edittextaddtextchangedlistenertextwatcher2but we cannot do thisit will set only the last listener in this case clicklistener2buttonsetonclicklistenerclicklistener1buttonsetonclicklistenerclicklistener2another doubti am not able to think any use case in which i need two textwatcher for single edittext can anybody give such a use case should i ask this question as separate question,"['java', 'android']" +147950,web controls within usercontrol null i have built a small user control which is essentially a dropdownlist with some preset values based on what the targetproperty is set onheres the codepublic partial class selector systemwebuiusercontrol public string selectedvalue get return thisddlselectedvalue public int selectedindex get return thisddlselectedindex public listitem selecteditem get return thisddlselecteditem private string target public string target get return thistarget set thistarget value protected void page loadobject sender eventargs e ddldatasource targetgrouputilgetallgroupssessionsessionidtostringutilgetalluserssessionsessionidtostring ddldatabind aspmarkup control languagec autoeventwireuptrue codebehindselectorascxcs inheritsinspireclientcustomcontrolsselector aspdropdownlist runatserver idlaspdropdownlistif i insert my selector into an aspxpage it works just fine examplesclselector targetgroup runatserver however if i programmatically add it like thisctrl new selectorctrltarget userthe dropdownlist ddl is null and the application logically throws an error is page load the wrong method to do such a thing what am i doing wrongi should add ctrl is of type dynamic not sure if this has anything to do with itthanks in advancedennis,"['c#', 'asp.net']" +147991,what is the difference between richcolumn and richcolumns can anyone tell me the difference between richcolumn and richcolumns,['java'] +148004,why there is no placement delete expression in c why c has not placement delete that directly corresponds to the placement new ie calls the destructor and calls appropriate placement delete operatorfor examplemytype p newarena mytypecurrent techniquepmytypeoperator deletep arenaproposed techniquedeletearena p,['c++'] +148022,default model binder does not bind for nullable types in ienumerable i have a controller action whose definition looks likepublic actionresult changemodel ienumerablemymodel info long destinationidand the modelpublic class mymodel public string name gets populated by default binder public long sourceid remains null though the value is set when invokedthe name property gets populated in the controller action however the sourceid property remains null the destinationid which is a long parameter gets populated as wellwhile stepping through the mvc version 2 source code this is the exception thrown by defaultmodelbinderthe parameter conversion from type systemint32 to type systemnullable1systemint64 mscorlib version20 cultureneutral publickeytokenb77a5c561934e089failed because no type converter can convert between these typesif the model is changed to long instead of long the default model binder sets the valuepublic class mymodel public string name getset gets populated by default binder public long sourceid getset no longer long so value gets setis this a known issue since the mvc source code is optimized i am not able to step through most of the codeupdate the request being sent is a http post using json with the source json resembling infonamecl1sourceid2 destinationid1,['c#'] +148025,how to write optimal sql queries i have searched around stackoverflow but everybody asks to optimize queries they have already donei want to know the basic stuff on what to do what to avoid when creating a queryfor example it is a known fact that writing select from is a thing to avoid given that the sql engine has to make an invisible query to know what columns should be shownalso know that between min number and max number works better than id min number and id max number but i do not recall why it can be because between is a sentence controlled at a lower level by the engine and creates the iterations to show the regs somehow handled but i just do not know for surecould someone validate those and make a list of the most common what to do what to avoid,['sql'] +148037,assigning a final field in a trycatch block within a constructor so i am trying to initialize a datagramsocket in a constructor and i want this field to be final but my compiler ie eclipse is giving me the following errorthe blank final field datagramsocket may not have been initializedthis is understandable heres a code snippet public class foo private final int default udplistenport 49400 private final datagramsocket datagramsocket public foo synchronizedthis try datagramsocket new datagramsocketdefault udplistenport catch socketexception e log error loggererrortrouble opening udp port e now i know there is a way to bypass this but it requires me to create a temporary variable heres a code snippet public class foo private final int default udplistenport 49400 private final datagramsocket datagramsocket public foo synchronizedthis datagramsocket tempsocket null try tempsocket new datagramsocketdefault udplistenport catch socketexception e log error loggererrortrouble opening udp port e datagramsocket tempsocket so i suppose my question is is there a more elegant way of doing this or is this something that i will just have to live with if i want that field to be final editfor those of you who are interested heres the solution i came up with from your recommendationspublic class foo private static final foo instance static try instance new foo catch socketexception e throw new exceptionininitializererrore private final int default udplistenport 49400 private final datagramsocket datagramsocket public foo throws socketexception synchronized this datagramsocket new datagramsocketdefault udplistenport public static foo getinstance return instance please let me know if this is correct or if you have any other suggestions i appreciate the help,['java'] +148042,java ignores classpath i am writing a java program which uses the oracle jdbc driver i have set it up in my classpath when i run the program inside my ide added as jdbc as library the program runs fine when i try to deploy it it totaly ignores the listing in classpath and gives me a noclassdeffounderrori want to use the clients jdbc driver the one installed and do not supply my own i package the program from jdeveloper deployment as jar filerunning with java jar testjarwhen i put the library in java homelibext it works properlyanyone knows how to resolve this issue,['java'] +148050,f records vs net struct is f records is the same as net struct i saw people talk about f structare they use this term interchangable with f records like in fsharp runs my algorithm slower than python talking about using struct as dictionary key but with code type tup x int y int why is this faster than a tuple as a dictionary key in the link above,['.net'] +148056,jquery pivot table i have been researching different jquery or javascript based pivot tables i have found a couple gumption pivot tables and oat framework these 2 apps fail with the amount of sales data i need to push into a pivot table can anyone recommend a pivot table solution please,['jquery'] +148061,what does enable dom storage api mean i came across this android webview function websettingssetdomstorageenabledtrue and from the name alone i can infer that it simply enables dom storagethe android documentation however suggests something slightly differentset whether the dom storage api is enablediow it enables the api rather than the storage itselfmy problem is i did not know about the existence of such an api until i encountered this functionmy google search suggests that this api is closely associated with html5does that mean that this function isirrelevant to web sitespages thatdo not use html5 iow does itaffect existing nonhtml5 pageloading rendering at allwhere can i learn more about the domstorage apiin particular are there any gotchasor caveats that i need to watch forwhen callingwebsettingssetdomstorageenabledtruein an android appwhy is it thisabled by defaultupdate i now can at least answer question 2 it turns out that the common name for dom storage is web storage and there is an entire wikipedia article about this storage,['android'] +148063,process the value of preference before save in android i need to crypt my password before save it to local android database everything work fine without encryption i have preferencesxml and so how can i call a function after i change value of preference for example password here is my codepublic class preferences extends preferenceactivity override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate addpreferencesfromresourcerxmlpreferences get the custom preference preference custompref preference findpreferencepass customprefsetonpreferencechangelistenernew onpreferencechangelistener override public boolean onpreferencechangepreference preference object newvalue string crypto simplecryptoencryptmysecretkey newvaluetostring encrypt here is where i am wrong i guess sharedpreferences settings getsharedpreferencespreferences mode private sharedpreferenceseditor editor settingsedit editorputstringpass crypto editorcommit ps like this when i change password it stores password without encryption,['android'] +148068,revert back to a specific commit in git build then revert to the latest changes there has been some question on reverting back to a commit in git but i wanted to make sure this so page is one that helps the mostgit revert to previous commit howi have a previous commit say 10 for a customer and it is complete i commit not sure if i push and then create a new branch to work on the next version now for some reason the binary for 10 is corrupted and i need to go back but also keep the current modificationsgit log reveals thiscommit be01d2a99ec35bbfcdbca47d5570acef8c69b275author yko date mon apr 25 102535 2011 0400so the steps i need to take is this1 git add 2 git commit good stopping point for v113 git checkout be01i am assuming step 3 modifies all the source code this is an xcode project iphone app so i just have to reload the project file build and have the new binary appthen goes back to the latest version 11 withgit checkout latest commit thanksi am new and do not want to lose any work appreciate the helpedit based on a few answers i want to clarify1 i do not want to merge any branches i want to go back to version 10 and rebuild the source to create a new binary then hop back to where i was suppose verision 10 have apples to be 100 and version 110 have apples to be 110 i want to go back to version 10 rebuild the source code where apples are 100 give the binary to customer x then hop back to version 110 keep working on itthanks again,['iphone'] +148077,rails dynamically generated path is adding a period and the id at the end i have the following configroutesrbresources employees as firm employments controller firm employments do resource user accountendhowever i am getting the followingfirm employment firmemploymentfind1user account firm employmentemployeeuser accountfirm employment user account pathfirm employment user account employees1user account3why is a period and the user account id being appended to this path i am trying to get it to return simply employees1user accountthanks in advance,['ruby-on-rails'] +148093,invalid postback or callback argument why so i get the exception invalid postback or callback argument event validation is enabled using in configuration or page enableeventvalidationtrue in a page for security purposes this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them if the data is valid and expected use the clientscriptmanagerregisterforeventvalidation method in order to register the postback or callback data for validationwith the following stack tracesystemargumentexception untrapped exception invalid postback or callback argument event validation is enabled using in configuration or page enableeventvalidationtrue in a page for security purposes this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them if the data is valid and expected use the clientscriptmanagerregisterforeventvalidation method in order to register the postback or callback data for validation at systemwebuiclientscriptmanagervalidateeventstring uniqueid string argument at systemwebuicontrolvalidateeventstring uniqueid string eventargument at systemwebuiwebcontrolslinkbuttonraisepostbackeventstring eventargument at systemwebuiwebcontrolslinkbuttonsystemwebuiipostbackeventhandlerraisepostbackeventstring eventargument at systemwebuipageraisepostbackeventipostbackeventhandler sourcecontrol string eventargument at systemwebuipageraisepostbackeventnamevaluecollection postdata at systemwebuipageprocessrequestmainboolean includestagesbeforeasyncpoint boolean includestagesafterasyncpointthe exception occurs after submitting a form and then quickly clicking on a linkbutton to download a file on the same page before the page reloads again can someone explain the details of why this exception is occurring upon executing the actions described abovethanks in advance,['asp.net'] +148094,performance penalties for unused joins i am writing a script that generates a report based on a query that uses several tables joined together one of the inputs to the script is going to be a list of the fields that are required on the report depending on the fields requested some of the tables might not be needed my question is is there a significant performance penalty for including a join when if it is not referenced in a select or where clauseconsider the following tablesmysql select from books title authorid animal farm 3 brave new world 2 fahrenheit 451 1 nineteen eightyfour 3 mysql select from authors id lastname firstname 1 bradbury ray 2 huxley aldous 3 orwell george doesselect authorslastnamefrom authorswhere authorsid 1outperformselect authorslastnamefrom authorsjoin books on authorsid booksauthoridwhere authorsid 1it seems to me that mysql should just know to ignore the join completely since the table is not referenced in the select or where clause but somehow i doubt this is the case of course this is a really basic example the actual data involved will be much more complexand really it is not a terribly huge deal i just need to know if my script needs to be smart about the joins and only include them if the fields requested will rely on them,['mysql'] +148119,android device database i am wondering if there are any android device databases aroundone of the apps i am working on now allows users to install an app on their devices once installed the application registers with a server the device becomes tied to the user account at a website in the website i would like to thisplay an icon for each of the devices the user has associated with his accountideally the icon would depict the actual device they have an android device database would ideally allow me to get this picture as it stands even trying to figure out if the device is a phone or a tablet is tricky and mostly guess work look at screen res etc i have googled around and have not found anythingideally the device database would expose a rest api which i could query to get information about my device including icons etci am thinking of building such a service as well as an app that could be used to extract device info and upload it to the device database the website would allow users to tie images to devicesi thought i should double check that it does not already exist,['android'] +148127,setting session timeout in rails 3 this seems simple i am trying to get my rails active record session to timeout after 2 minutes so after two minutes i want my users to have to relogin i am just running rails server ie webbrick on my local dev machine i know this is something to do with the following code in configinitalizerssession storerb but i do not think i have quite nailed it codedonapplicationconfigsession store active record storecodedonapplicationconfigure do configaction controllersession expire after 2minutesendthis does not seem to work or at least my session does not appear to timeout i cannot find much about the rails 3 way to do this as i know things have changed from rails 2x can some one help me out,['ruby-on-rails'] +148134,populating one select box based on the selection in another select box jquery i am trying to populate one select box based on the selection made in the first select box i have looked online and found a lot of helpful information on hardcoded options but i need my options to come from a query like cfquery in coldfusion i know that a cfquery is serverside so i cannot include it in my jquery but is there another optioni was using the following examplehtmlselect idcounties option option option somerset option option hertfordshire optionselectselect idtowns thisabledtrueselectjsvar countytowns bath bristol letchworth hitchincountieschangefunction var county thisselectedindex 1 townsempty if county 1 townsattrthisabled true else var towns countytownscounty for var i 0 i townslength i townsappendoptionoptiontexttownsi townsattrthisabled false what i would need is for towns to be dynamic and able to be read from a database any help is greatly appreciatedthanks,['jquery'] +148142,why does contentvalues have a put method that supports boolean the contentvalues class contains a method that allows booleans to be put into the values collection afaik sqlite does not contain a native boolean format that android could push the boolean values into so what magic does android do behind the scenes to store these values also why is there no complimentary getboolean method on a cursor to me this appears to be a pretty awkward design oversight since there seems to be no safe way of retrieving a boolean value that was put into the db via contentvalues what am i missingthis question may seem a bit frivolous since i suspect that the booleans are stored as a 1 or 0 integer but why would android commit to developers making that assumption its not even documented as far as i am aware,['android'] +148157,actionbar background image i have inherited the holo light theme and customized the background of the actionbar with the followingcontent of stylesxmlxml version10 encodingutf8resourcesstyle nameactionbar parentandroidstylewidgetholoactionbaritem nameandroidbackgrounddrawableactionbar backgrounditemstylestyle namemytheme parentandroidstylethemehololightitem nameandroidactionbarstylestyleactionbaritemstyleresourcescontent of actionbar backgroundxmlxml version10 encodingutf8bitmap xmlnsandroidandroidsrcrawactionbar backgroundandroidtilemoderepeat instead of being repeated the image is stretched any idea of why androidtilemoderepeat is not appliedthanks in advance,['android'] +148179,java executorservice callback on thread terminate i am using cached thread pool executorservice to run some asynchronous background tasks i have provided my threadfactory that hands out threads to the executorservice whenever it needs them my understanding of the cached thread pool is that after the thread is sitting idle for 60 seconds it is termniated by the executorservice i want to perform some state cleanup when my thread is about to be terminated what is the best way to achieve this the executorservice does not readily provide hooks into the threads lifecyclei do not want to shutdown my executorservice useful for running tasks as and when they comeexecutorservice executor executorsnewcachedthreadpoolnew mythreadfactory do some workexecutorsubmitnew mycallable need a way for the executorservice to notify me when it is about to terminate my thread need to perform some cleanupthanksshreyas,['java'] +148180,whats the advantage of persist vs save in hibernate can anyone tell me whats the advantage of persist vs save in hibernate,['java'] +148203,cannot get simple html5 manifest cache to work i am trying to get a simple html5 webcache to workthis is my one and only html page indexhtmldoctype htmlhtml manifestmainmanifest body phip bodyhtmlthis is my only cache file mainmanifestcache manifest 2011050203indexhtmli am running on apache shared hosting i put a htaccess file in my web directory where these other two files are because i thought maybe i have to define the mime typeaddtype textcachemanifest manifestso in the end i just have these three files in that directoryindexhtmlmainmanifesthtaccesswhen i visit the page on chrome from my mac safari from my iphone or chrome from my android 23 device nothing happens the page just loads as usual if i turn airplane mode on killing all connections the page cannot be loaded so i guess caching failedwhat am i missing herethanks update i think the mime type was not being recognized correctly i updated htaccess toaddtype textcachemanifest manifestnow if i run in google chrome with console on i seedocument was loaded from application cache with manifestapplication cache checking eventapplication cache noupdate eventfirefox prompts me when i load the page about the website wanting to let me store it to thisk so that is good looks like it is also working on android 234 the browser still says this page cannot be loaded because you are not connected to the internet but then it loads anywaythanks,['html'] +148208,nsset implementation this question is just out of curiosity but how is nsset implemented what data structure is behind it and what are the access times for adding and removing elements if i had to guess i would say it was some sort of hashtabledictionary data structure but in that case why differentiate between nsset and nsmutableset,['objective-c'] +148219,how should a model be structured in mvc i am just getting a grasp on the mvc framework and i often wonder how much code should go in the model i tend to have a data access class that has methods like thispublic function checkusernameconnection username try data array datausername username sql sql select username from thisuserstablename where username username execute statement return thisexecuteobjectconnection sql data catchexception e throw e my models tend to be an entity class that is mapped to the database tableshould the model object have all the database mapped properties as well as the code above or is it ok to separate that code out that actually does the database workwill i end up having four layers,['php'] +148241,how to run ruby in haml in javascript definition how can i run ruby code inside javascript in hamlif i use var message in my example i get undefined local variable or method messagewhen i move message it works above javascript everything works finei want to run iteration each inside javascript see the last code sample for what i need in final javascript code where i need to loop few ruby variables or one hash of hashes of hashes to get this data basics can have few elemenets it can have children with few elements etcso this haml code html head javascript documentreadyfunction message it works var message body message2 hi message2 divid jstreegives me this html codehtml head script typetextjavascript cdata documentreadyfunction message hi var message script head body hi div idjstreediv bodyhtmlthe final javascript code i want to produce using haml is the javascript variablevar data data basics attr children data login attr run run children data login attr data academic year attr run run children data login attr data academic year attr filter mini sof yes,['ruby'] +148243,infinite loop with cin when typing string while a number is expected in the following loop if we type characters as the cin input instead of numbers which are expected then it goes into infinite loop could anyone please explain to me why this occurswhen we use cin if the input is not a number then are there ways to detect this to avoid abovementioned problemsunsigned long ul x1 ul x2while 1 cin ul x1 ul x2 cout ux x1 is ul x1 endl ul x2 is ul x2 endl,['c++'] +148252,how to show the soft keyboard on native activity when i try to use anativeactivity showsoftinput it does not bring up the soft keyboardi have tried using anativeactivity showsoftinputengineappactivity anativeactivity show soft input forced and anativeactivity showsoftinputengineappactivity anativeactivity show soft input implicit to show softinput but also failedi read the source code and i found after start nativeactivity nativecontentviewextend view will be created and when call anativeactivity showsoftinput it will call showsoftinput in java side i think maybe the softkeyboard is not turned on can you help me,"['java', 'android']" +148253,request uri is not overridden by using apache rewriterule problem am using kohanaphp to develop a hosted website for other companiesi get the customer to put in a cname entry in their dns server to point to my domain eg is pointing to thus the http host entry on my apache server is invitessomecompanycomi want to rewrite to even though apache seems to be doing that the serverrequest uri is still the problem is kohana uses serverrequest uri to route the request to the appropriate controller code in this case it routes it to the base index controller instead of the invites controllerfacts the apache mod rewrite directives i am using in the htaccess file rewritecond http host wmydomaincomrewritecond request uri invitesrewriterule invites1 for kohanarewriterule indexphpkohana uri0 ptqsalin the indexphp i do var dump serverand i get request uri string query string string kohana uriinvitesindexphpkohana uriinvitesinviteredirect query string string kohana uriinvitesinviteso the mod rewrite does not modify the request uri need request uri invitesinvitequery string string kohana uriinvitesinvitehow do i get thateditrewrite log entries strip perdir prefix usersprojectinvite invite applying pattern applicationmodulessystemb to uri invite strip perdir prefix usersprojectinvite invite applying pattern git to uri invite strip perdir prefix usersprojectinvite invite applying pattern to uri invite rewrite invite invitesinvite add perdir prefix invitesinvite usersprojectinvitesinvite strip perdir prefix usersprojectinvitesinvite invitesinvite applying pattern to uri invitesinvite rewrite invitesinvite indexphpkohana uriinvitesinvite add perdir prefix indexphp usersprojectindexphp strip document root prefix usersprojectindexphp indexphp internal redirect with indexphp internal redirect strip perdir prefix usersprojectindexphp indexphp applying pattern applicationmodulessystemb to uri indexphp strip perdir prefix usersprojectindexphp indexphp applying pattern git to uri indexphp strip perdir prefix usersprojectindexphp indexphp applying pattern to uri indexphp rewrite indexphp invitesindexphp add perdir prefix invitesindexphp usersprojectinvitesindexphp strip perdir prefix usersprojectinvitesindexphp invitesindexphp applying pattern to uri invitesindexphp rewrite invitesindexphp indexphpkohana uriinvitesindexphp add perdir prefix indexphp usersprojectindexphp initial url equal rewritten url usersprojectindexphp ignoring rewrite,['php'] +148272,how to use sinatrareloader i have my webrb where i have require rubygems require sinatra require sinatrareloaderthen i start my web application by double click on the webrb short cut after any change in webrb i have to exit the sinatra and run it again i thought that sinatrareloader would help me not to manual realoadconfiguration ms windowsruby 187 20100816 patchlevel 302 i386mingw32sinatra 126 10sinatraadvancedroutes 051sinatrareloader 050sinatrasugar 051 050thin 127 x86mswin32,['ruby'] +148275,how is mvvm in net different than mvc in cocoa i am reading up on mvvm and for the life of me cannot tell how the modelview of mvvm is radically different than the controller in mvc as used in cocoa programmingi have even read some explanations that were supposedly aha moments for others and have still failed to catch the difference the limited cocoa gui programming i have done has involved treating the controller as the central point for managing data going to and from the view to the model with the use of keyvalue observingin all the important aspects this seems to me what the modelview does except that it might be a subtle implementation difference that pertains to the wpf c bridge in net that is mvc in cocoa might be called mvvm if the cocoa gui was specified in a different language than the application code and the controller was coded in the same language as the gui instead of the application ie wpf is specified in xaml rather than cor perhaps mvc in noncocoa environments without all the keyvalue observing etc is far different than mvc as applied in cocoa and that has led people to find larger differences between mvvm and mvc than i haveam i crazy please educate me,['.net'] +148296,recaptcha https problem on i am using recpatcha on an ssl site but i am not getting the image on some browsers because the ssl certificate of it has been expired if i reference the nonsecure link the browser will give warning messageso what is the alternativei am using it under aspnet mvc,['asp.net'] +148304,how to call a servlet from java code i want to call servlet with some parameters and receive a response the code is written in javawhat is the best cleanest way to do thatalso can i call a servlet and continue with the code withoud waiting the servlet to finish close the connection and forget about it,['java'] +148311,how to cancel uigesturerecognizer if subviews button pressed i am struggling to get the behaviour i would like from the gesture recognisers specifically cancelling certain gestures if others have firedi have a scrollview set to paging and multiple subviews in each page i have added a touch gesture recogniser to scroll to the next or prev page if the user taps to the right or left of the page add a gesture recogniser turn pages on a single tap at the edge of a page uitapgesturerecognizer tapgesture uitapgesturerecognizer alloc initwithtargetself actionselectortapgesturehandler tapgesturecancelstouchesinview no self addgesturerecognizertapgesture tapgesture releaseand my gesture handler void tapgesturehandleruigesturerecognizer gesturerecognizer const cgfloat ktapmargin 180 get the position of the point tapped in the window coordinate system cgpoint tappoint gesturerecognizer locationinviewnil if the tap point is to the left of the page then go back a page if tappointx selfframesizewidth ktapmargin self scrollrecttovisiblepageviewrightframe animatedyes if the tap point is to the right of the page then go forward a page else if tappointx ktapmargin self scrollrecttovisiblepageviewleftframe animatedyesall works well except where i have a subview on the page that has buttons in it i want to be able to ignore the tap to turn the page if the user touches a button on the subview and i cannot figure out how to do thischeersdave,['iphone'] +148322,using holtwinters for forecasting in python i have been trying to use this implementation of the holtwinters algorithm for time series forecasting in python but have run into a roadblock basically for some series of positive inputs it sometimes forecasts negative numbers which should clearly not be the case even if the forecasts are not negative they are sometimes wildly inaccurate orders of magnitude higherlower than they should be giving the algorithm more periods of data to work with does not appear to help and in fact often makes the forecast worse the data i am using has the following characteristics which might be problems very frequently sampled one data point every 15 minutes as opposed to monthly data as the example uses but from what i have read the holtwinters algorithm should not have a problem with that perhaps that indicates a problem with the implementationhas multiple periodicities there are daily peaks ie every 96 data points as well as a weekly cycle of weekend data being significantly lower than weekday data for example weekdays can peak around 40 but weekends peak at 10 but even when i only give it weekday data i run into the negativenumber problem is there something i am missing with either the implementation or my usage of the holtwinters algorithm in general i am not a statistician so i am using the default values of alpha beta and gamma indicated in the link above is that likely to be the problem and is there a better way to calculate those values or is there a better algorithm to use here than holtwinters ultimately i just want to create sensible forecasts from historical data here i have tried single and doubleexponential smoothing but as far as i understand neither support periodicity in dataany helpinput would be greatly appreciated,['python'] +148330,hibernate list i seem to have problems with mapping a list in hibernate in our project there a class card with contains a class answer with answer containing a liststringis a liststring mappable by hibernate using annotations i mean since it does not have the entity annotationregards,['java'] +148338,trigger click jquery not working i am figuring out why this simple script is not workingjquerynoconflictjquerydocumentreadyfunction jquerynext button atriggerclicknoconflict is necessary because i also load prototypescriptaculous in this pageif i replace triggerclick with another function es css this works well only triggering seems to go broken,['jquery'] +148356,struts 1x vs struts 2x i have reviewed a few struts 1 vs 2 questions on so but none seem to answer the question in the perspective that i am looking at it withi am about to start work architecting a new system a complete reengineering of a very old desktop application the goal is to make it web based add more functionality make it more usable etc the usual reengineering reasonsthe team who will be developing the system are mainly java developers and have worked on struts 1x extensively over the past 5 years the system is intended to live for many years to come so the idea of reengineering again in 35 years time when a better framework comes out is not an option it is not intended to heavily use ajaxmy question is why would i bother moving to struts 2 when my team are so experienced with struts 1x i understand that there are some improvements but i worry that the time lost in getting the team up to speed rework due to incorrect usage etc will far outweigh any benefit we would get from struts 2 we like struts 1 it does what we need to it do and all the design patterns standards best practices etc are in place are there any killer features with struts 2 or serious problems i do not know about in struts 1 that would sway the decision to stay with struts 1,['java'] +148358,generating all dates within a given range in python i have two string variables which contain dates in ymmdd format as follows date1 20110503date2 20110510i want to write code that generates all dates in the range date1 to date2 how can this be done in python,['python'] +148381,creating list of objects in javascript is it possible to do create a list of your own objects in javascript this is the type of data i want to store date 1212011reading 3id 20055date 1312011reading 5id 20053date 1412011reading 6id 45652,['javascript'] +148396,add image to uitableview cell i have a tableview how can i add image to the left of this cells,['ios'] +148399,python regex strange behavior i have thiscovered something that i cannot explain in python re modulecompilation of a or ab throws an errorraise error v invalid expression sre constantserror nothing to repeati have tested this regexp in javascript and it seems to be okis it a bug,['python'] +148401,how to thisable ravendb replication how do i thisable ravendb replication the reason for that is i have a simple database on one server and i do not need any replication at this point idocumentstore tmpstore new documentstore url urltmpstoreinitializetmpstoredatabasecommandsensuredatabaseexistsdbname webexceptionif i try to ensure that database was created i get a webexception with http status 404 this error occurred when ravendb makes request to docsravenreplicationdestinations or shall i just ignore this exception,['c#'] +148417,setthreadexecutionstate is not working when called from windows service i want prevent system from going to sleephibernate from a windows service i am calling setthreadexecutionstate function to do thatbut it seems to have no effecti just want to know whether the function setthreadexecutionstate will for windows services if not what will be the alternative ways to thatbelow is the c code i am using i am calling it on onstart method of servicedllimportkernel32dll charset charsetauto setlasterror truestatic extern uint setthreadexecutionstateexecution state esflagsprivate void keepalive setthreadexecutionstateexecution statees thisplay required execution statees system required execution statees continuous,['c#'] +148418,cache manifest offline app not refreshing javascript files in chrome i am working on an offline web app using a cache manifest file i am having trouble refreshing my javascript files if i change a js file which is listed in the manifest file and i then change the manifest file version no and save it then the changed js file does not get reloaded on the client what do i have to do to get js files to refreshthanks,['javascript'] +148442,how to dynamically set a functionobject name in javascript as it is thisplayed in chrome this is something which has been bugging me with the google chrome debugger and i was wondering if there was a way to solve iti am working on a large javascript application using a lot of object oriented js using the joose framework and when i debug my code all my classes are given a nonsensical initial thisplay value to see what i mean try this in the chrome consolevar f function var myobj new fconsolelogmyobjthe output should be a single line which you can expand to see all the properties of myobj but the first thing you see is just a fmy issue is that because of my oo framework every single object instantiated gets the same name the code which it looks is responsible for this is like sogetmutablecopy function object var f function fprototype object return new fwhich means that in the debugger the initial view is always a fnow i really do not want to be changing anything about how joose instantiates objects getmutablecopy but if there was something i could add to this so that i could provide my own name that would be greatsome things that i have looked at but could not get anywhere with function foo fooname foo fooname bar bar fooname foo looks like it is read only,['javascript'] +148448,why are jsrret deprecated java bytecode does anyone know why the jsrret bytecode pair is deprecated in java 6the only meaningful explanation i found on the net was that they made code analysis by the runtime harder and slower to perform does anyone know another reason,['java'] +148449,is it possible to replace malloc on ios i would like to use a custom malloc and free for some allocations in an ios app including those made by classes like nsmutabledatais this possibleif so how do i do itwhat i would actually like to do is zero out certain data after i have used it in order to guarantee forward security in case the device is lost or stolen as much as possible if there is an easier way to do this that does not involve replacing malloc then that is greati believe i need to replace malloc in order to do this because the sensitive data is stored in the keychain and i have no option other than to use nsdictionary nsstring and nsdata in order to access this data i cannot even use the mutable versions,"['objective-c', 'ios']" +148458,can i programmatically save part of a web page as an image if possible i would like to do this with a simple button the users are not terribly comfortable with computers which is why i have not just told them to print screen or use the snipping tooli know it can be done in mozillabased browsers with canvas and drawwindow but this application is running on internet explorer 7 and 8the page shows some graphs generated by a reportviewer control based on the input of a couple of dropdowns does that mean a clientside script is the only option or could i do it in the aspnet back end somehow perhaps regenerating an image any time the dropdowns are changedi have been a desktop dev for so long that i do not quite get what you can and cannot do in web apps yet,"['javascript', 'asp.net']" +148459,why is using onclick in html a bad practice i have heard many times that using javascript events such as onclick in html is a bad practice because it is not good for semantics i would like to know what the downsides are and how to fix the following codea href onclickpopupmap 300 300 map return falselinka,"['javascript', 'html']" +148460,removing new lines before empty blocks in eclipse i prefer allmanstyle braces for exampleif foo magical prancing unicorn stuffrather thanif foo unmagical boring pony thingsthe java formatter in eclipse handles this pretty well except for empty code blocks which it formats like thissomedefaultctori would like to use this special format for empty blocks insteadsomedefaultctor is there any way to tell eclipse to leave braces on the same line when the braces surround an empty code block so far i cannot see one,['java'] +148479,get redirect of a url in ruby according to facebook graph api we can request a user profile picture with this examplebut the real image url of the previous link is 1489686594 527 qjpgif you type the first link on your browser it will redirect you to the second linkis there any way to get the full url second link with rubyrails by only knowing the first urlthis is a repeat of this question but for ruby,"['ruby-on-rails', 'ruby']" +148490,gridview auto fit images im trying to get images thisplayed in a gridview and get the columns automatically set so far i have had to manually set the number of columns which is not what i want to do as this will affect how big the images are on different sized screens i ahve tried setting it to auto fit but it only thisplays 2 columns in the middle of the screen this is what im trying to achieve each red square represents an imagethen when turned to landscape mode i want the columns to auto fit so that its all evenany help would be much appreciated thank you,['android'] +148508,generate class from database table how can i generate a class from a table at a sql serveri am not talking about using some orm i just need to create the entities simple class something likepublic class person public string name getset public string phone getset,"['c#', 'sql']" +148515,calling method in current view controller from app delegate in ios i have two view controllers buildingsviewcontroller and roomsviewcontroller that both use a function within the app delegate called upload the upload function basically does an http request and if its successful or unsuccessful triggers a uialertview this is working finethe part i am struggling with is from within the app delegates connectiondidfinishloading method i need to be able to basically refresh the current view controller via perhaps viewwillappear method of that view controller inside the viewwillappear function of each view controller i have code which determines the buttons on the bottom toolbar i want the upload button in the toolbar of each view controller to automatically be removed when the uploading is done via the app delegatei have tried doing viewcontroller viewwillappearyes from within the connectiondidfinishloading method of the app delegate but it never gets calledi hope i am clear enough any help is greatly appreciatedthanks,"['iphone', 'objective-c', 'ios']" +148527,how can i get last characters of a string using javascript i have var idctl03 tabs1using javascript how might i get the last five characters or last character,['javascript'] +148546,how do you use https ssl on localhost i would like to know how to setup ssl on my web application on the localhost i have no background in doing this would appreaciate guidance i already finished implementing my web application and i need it to use https on the localhost or while i host it on a server any ideas regards,['asp.net'] +148552,find string between two strings in javascript or jquery i have been trying to get a string between two strings in a line i found a lots of tutorials using regex but as i am not that good at regex i am not being able to figure out how to do it any help will be appreciatedvar fullurl ip0catblogusermanddefaultmarket4080i need to figure out a way to get the string between and ip and just return i dont want to split the strings from and get the middle string as it corrupts some urls with the character in it any help would be appreciated thanks,['javascript'] +148557,how to cancelrevert changes to an observable model or replace model in array with untouched copy i have a viewmodel with an observablearray of objects with observable variablesmy template shows the data with an edit button that hides the thisplay elements and shows input elements with the values bound you can start editing the data and then you have the option to cancel i would like this cancel to revert to the unchanged version of the objecti have tried clone the object by doing something like thisviewmodeltempcontact jqueryextend contactorviewmodeltempcontact jqueryextendtrue contactbut viewmodeltempcontact gets modified as soon as contact doesis there anything built into knockoutjs to handle this kind of situation or am i best off to just create a new contact with exactly the same details and replace the modified contact with the new contact on cancelany advice is greatly appreciated thanks,['javascript'] +148558,drupal 6 and jquery 1415 is there a way in drupal 6 to use in non admin pages jquery 15 14 without breaking the core functionality on nonadmin pages,"['javascript', 'jquery']" +148561,set max execution time in php cli i know that php cli is usually used because of none time limits and primary because it is not using apache threadsprocessesbut is there any way how to explicitly set the max execution time for some scripts which i do not want to have the freedom of unlimited time and just want to keep those script under controlif you think this question may be better answered on superusercom and have permission to move it do it edit i have been googling a bit and found the right parameterphp d max execution time5 scriptphp,['php'] +148568,possible to create a single multitype collection of multitype lambda functions in c 40 for instance something likedictionarystring funct1 t2 bool comparisons comparisonsadd x y x y comparisonsadd x y x y comparisonsadd x y x yat this point i do not know enough about c lambdas and multitype generic containers to be able to put this together correctly is this even possible,"['c#', '.net']" +148593,what is the best way to marshall data inout of the plugins i am building my workstation agent application using mef and entityframework 4the application is a simple agent that runs on a computer with a plugin architecture and many plugins in the form of dll fileseach plugin will query their own pluginspecific table the master program or agent needs to pass information to the plugin and receive information from the pluginthe plugins will use the entity framework 41 to retrieve the data so it will already have the data formatted as objects perhaps heavy objects since they are tied to the ef context also the data i am pulling back from the database is a series of joins so the data does not match any of the poco identitiesclasses i had already createdwhat is the best way to marshall data inout of the plugins taking into consideration that i am using mef to tie the pieces together and that i already have objects for the data in the plugins should i create a new poco and move the entity data into it then shuffle arrays should i create a list i am not only interested on what can be done but what are best practices,['.net'] +148621,what is a controller in sinatra i was asked why i was creating complex ruby variables in my viewshould not have these variables been declared by my controlleris my sinatra controller my rb file i have one rb file and view views,['ruby'] +148633,add to a css class using jquery is it possible to addupdate a css class using jqueryi know i can add css to a dom element using this add css rule using jquery but i would like to addremove from the css class itself,"['jquery', 'css']" +148647,orientation from android accelerometer i testing the accelerometer output on 2 different deviceselocity a7 and archos 7 home tablet but the sensor seems to be giving different results i have it programmed to set to landscape mode but the x and y axis seem to be the oppisite between the 2 devices the x axis returns 10 when held perpendicular to the ground and the archos x axis returns 0 the elocity tablet is android 22 and the archos is 21 can someone point me in the right direction as how to get orientation from the accelerometer in sync between these 2 devices,['android'] +148657,android is there a way to create hidden folders and hidden files i am a newbie android developer i need to know if there is a way to create hidden folders and hidden files in android programatically there must be a way to create hidden folders in sdcard but i do not know how any help is appreciated thanks,['android'] +148686,how to thisable edittext in android how to thisable typing in edittext field in android,['android'] +148708,dynamic linq and select considering the following pointless but it is for illustration purpose test class public class test public ienumerablestring toenumerablestrswontcompileienumerabledynamic t return tselectx tostrx public ienumerablestring toenumerablestrswillcompileienumerabledynamic t var res new liststring foreach var d in t resaddtostrd return res public string tostrdynamic d return new stringdgettype why does not it compile with the following error on tselectx tostrx cannot implicitly convert type systemcollectionsgenericienumerabledynamic to systemcollectionsgenericienumerablestring an explicit conversion exists are you missing a castno error on the second method,['c#'] +148729,maximum size of native heap on android if i have understood correctly an android process has two heaps one managed by the vm and one nativethe size of the vm heap cannot exceed 16mb at least this value can be higher on some phonesbut what about the maximum size of the native heap the 16 mb limit does not seem to be a hard limit in that an app can allocate more than 16mb through the ndk but the os will start killing other processes and possibly the foreground process as well when a high amount of memory is used when does the os start behaving this way when the native heap vm heap size exceeds 16mbdebuggetnativeheapsize gives the size of the native heap but is there a function to check the combined native vm heap sizecurious to hear from someone who knows how this works,['android'] +148766,how to set bitmap in circular imageview i have 1 circular imageview and i want to place bitmap inside the imageviewbut when i set the compressed bitmap image it is always rectangleplease help me to set bitmap in circular imageviewthanks,['android'] +148770,outoforder returns from java futures the only model that i can come up with for running multiple similar processes simd using java futures javautilconcurrentfuturet is as followsclass job extends callablet public t call listjob jobs listfuturet futures executorserviceinvokealljobsfor futuret future futures t t futureget do something with t the problem with this model is that if job 0 takes a long time to complete but jobs 1 2 and 3 have already completed the for loop will wait to get the return value from job 0is there any model that allows me to get each future result as it becomes available without just calling futureisdone and busy waiting or calling threadsleep if none are ready yet,['java'] +148780,how to execute a shell script in php i have a script in varwmyscriptsh which creates folders and run an svn update command for my projects i need to execute this script by calling it in a php file in the browserlocalhosttestphp i tried the shell exec and exec but did not work i ran my shell script in terminal with su wdata myscriptsh and it worked what else am i missingphpoutput shell execmyscriptshi added wdata allall nopasswdall to etcsudoers worksbut this is very insecure is there another way to do this,['php'] +148831,what is the syntax for including multiple navigation properties in entity framework i am querying an entityapplicant which has multiple navigation properties need to include two navigation properties worker and statustype in the include part of the querytried including one property worker as includeworker this works but when i use includeworker statustype to get both the navigation properties the query fails with the message invalid include path what is the syntax for including multiple navigation properties in entity framework,"['.net', 'asp.net']" +148849,alternatives to java web start were having huge issues with java web start in production were afraid to release because every time we do help desk gets calls from 13 users getting an unable to launch error it is hard to tell whether it is because of user error cancellation in the middle of download poor network connection or anything but the bottom line is we find it terribly unreliablewhat are the alternatives for deploying and updating a rich swing application either free or commercial i am more interested in features and robustnessreliability is key but i would also like to have the followinginstall once update automatically from a simple http hosting like jwsdifferential updatessupport for multiple configurations think of 30 instances which may have different versions of the application or different launch parameters would be nice not to build 30 artifacts each timewin mac linux support hopefully one that does not mean i have to maintain 3 builds for each instance,['java'] +148850,detecting usb power state windows has the option of powering down certain peripherals such as usb ports to save power this behavior can be enabledthisabled via device manager the power down happens under various conditions such as when the lid of a laptop is closed this is causing a problem for me as i have a gui which talks to hardware attached to the usb port and communications are severed every time the laptop lid is closed is there a way to programmatically detect this powerdown standby event before it happens and more gracefully shut down my usb device is there a way to programmatically configure each of the systemas usb ports to thisable this behaviorright now i am looking at systemeventspowermodechanged is this the right event to detect this,['c#'] +148862,how to call javascript function from pyqt i am trying to interact with a google map using python i have built an application in pyqt with a qwebview the qwebview loads a local html page as shown herebrowser qwebviewbrowserloadqurlfilecmainhtmlframe browserpagecurrentframeframeevaluatejavascriptqstringaddmarker3389 151275the html page is as followsdoctype htmlhtmlheadmeta nameviewport contentinitialscale10 userscalableno style typetextcss html height 100 body height 100 margin 0px padding 0px map canvas height 100 stylescript typetextjavascript srcscriptscript typetextjavascriptvar mapfunction initialize var latlng new googlemapslatlng34397 150644 var myoptions zoom 8 center latlng maptypeid googlemapsmaptypeidroadmap map new googlemapsmapdocumentgetelementbyidmap canvas myoptions function addmarkerlat lng var mylatlng new googlemapslatlnglat lng var beachmarker new googlemapsmarkerposition mylatlng map map scriptheadbody onloadinitialize div idmap canvas stylewidth100 height100divbodyhtmlhow can i call addmarker from pythoni have tried calling addmarker from the html added the call to the onload call and i tried using a simple javascript expression from the python frameevaluatejavascriptalert5 both of those worked so i know that addmarker and evaluatejavascript can work i just do not know how i also tried calling evaluatejavascriptaddmarker3389151275 on the framedocumentelement object and that did not work either,"['javascript', 'python']" +148871,installing python eggs under pypy how do i install python egg under pypyduring installation pypy created usrlib64pypy15sitepackages directory so i tried using easy install with prefix set to this directory however it complains that this is not a valid directory for eggs do i just copy eggs from usrlibpython27sitepackages or is it as easy as using easy install with some changes in configuration perhapsmy working environment is fedora 15 beta python 271 usrbinpython pypy 150alpha0 with gcc 460 in usrbinpypy installed from rpm using yum easy install version is thistribute 0614 usrbineasy install,['python'] +148901,zindex how does it affect performance how does the css zindex value affect performanceif i have multiple images on a page does it matter if i use high zindex values like 10for example a page contains 15 images with zindexes ranging from 500 10 and if the images are moveable jquery draggable does it impact upon performance by using high values if the page is redrawn so frequently,['css'] +148906,does a method name starting with does look good is it a good practice to start a method name with does in c it looks a little bit weird to me so i would like to get your opinion i am writing a method which check if an account exists or not should the signature be bool doesaccountexistid is there a better namethanks,['c#'] +148921,sparql query on the remote remote endpoint rdflib redland i am trying to query remote endpoints and get get owlsameas mappings i have tried both rdflib and redland but neither worked for me probably i am not dealing with namespaces correctlyhere is my attempt in rdflib import rdflib rdflibpluginregistersparql rdflibqueryprocessor rdfextrassparqlprocessor processor rdflibpluginregistersparql rdflibqueryresult rdfextrassparqlquery sparqlqueryresult g rdflibgraph query select from where s a o limit 50 for row in gqueryquery print rowand here is redlandimport rdfmodel rdfmodelquery select from where s a o limit 50for statement in rdfqueryquery query languagesparqlexecutemodel print statementcan you please give a hint what is wrong in any one of thoseyet another difficulty i have is it possible to get dataset name of the object for example if there iss predicate 0 boy least likely tocan i get name of the dbpedia in this example or any other dataset to which i am having sameas link or probably i could just lookup interested dataset names in the object string thank you very very much in advance,['python'] +148922,ajax post with jquery changing the name of an array parameter i am doing a simple ajax post using jquery works greatvar parameters firstname john lastname smithpost parameters functiondata alertresponse datasomeresulthowever when i add an array to the parameters like sovar parameters firstname john lastname smith children susy billythen the problem is the parameter name children gets changed to children it is actually url encoded to children5b5d when posting to the server i cannot change the server to look for parameters with the name children so what do i do how can i post multiple values with the name children why is jquery changing the name of my parameter,['jquery'] +148942,error cannot create table on adding foreign key i have created the table by scriptset sql modeno auto value on zerodrop table if exists table1create table if not exists table1 id bigint20 not null auto increment parentid bigint20 default null name varchar1024 not null description varchar16384 not null default imageid bigint20 default null primary key id key name name255 key parentid parentid key imageid imageid engineinnodb default charsetutf8 auto increment27 insert into table1 id parentid name description imageid values0 null name1 null12 0 name2 nullthen i try to add foreign keyalter table table1 add constraint table1 ibfk 2 foreign key parentid references table1 idand obtain the following errorerror 1005 hy0 cannot create table sandboxsqlc28 4c errno 150what is wrongi run show engine innodb statusthere latest foreign key error followslatest foreign key error110504 220655 error in foreign key constraint of table sandboxsqlc28 61 foreign key parentid references table1 idcannot resolve table name close to idbut it does not help me to realize what is wrongi use windows vista mysql 5511updatethe issue appears when i upgrade from mysql 5067,['mysql'] +148947,how do i compile a pyqt script py to a single standalone executable file for windows exe andor linux i started to fiddle with pyqt and made a beautiful script from the pyqt whitepaper example app pastebinit works perfectly in windows and linux with qt environment already installed on bothnow my question is since i am trying to use qt because it is compiled at least pure old c based qt how can i compile some exe file to run it on windows or a standalone executable for linuxthe point is that i want the program to be compiled because of speed and portability instead of interpreted from source which would require a previous setup on any machine one of the goals for example is sending small gui scripts via email to coworkers who are not programmers at all,['python'] +148953,should i accept an oscp responder certificate signed by the trust anchor could someone please help me on the followingrfc2560 defines when an ocsp responder certificate sigining the response could be accepted 1 matches a local configuration of ocsp signing authority for the certificate in question or 2 is the certificate of the ca that issued the certificate in question or 3 includes a value of idadocspsigning in an extendedkeyusage extension and is issued by the ca that issued the certificate in questionmy question isif the certificate of the ocsp responder is signed by the trust anchor of the validation path is it also considered acceptedi have the impression that it should be but this is not stated explicitely above from rfc and could not found an explicit reference on thisfrom my reading of the rfc though is that even if it is signed by the ta it is still is not valid for ocsp responseany help is appreciatednote i am working in java on this in case it mattersupdatein section 22 of the rfc all definitive response messages shall be digitally signed the key used to sign the response must belong to one of the following the ca who issued the certificate in question a trusted responder whose public key is trusted by the requester a ca designated responder authorized responder who holds a specially marked certificate issued directly by the ca indicating that the responder may issue ocsp responses for that ca point 2 seems ambiguous to meit could meana any pk trusted so trust anchor is acceptableorb have the meaning of point 1 in the first quotation which means preconfigure a certificate any to trust as being the ocsp responders as for example is done in java here securitysetpropertyocsprespondercertsubjectnameocspcertgetsubjectdngetname listx509certificate list new arraylistx509certificate listaddocspcert collectioncertstoreparameters p new collectioncertstoreparameterslist certstore store certstoregetinstancecollection p pkixparameters params new pkixparameterscollectionssingletonanchor paramsaddcertstorestore,['java'] +148958,unable to serialize the session state when putting my application online and trying to log in i got this errorserver error in applicationunable to serialize the session state in stateserver and sqlserver mode aspnet will serialize the session state objects and as a result nonserializable objects or marshalbyref objects are not permitted the same restriction applies if similar serialization is done by the custom session state store in custom modedescription an unhandled exception occurred during the execution of the current web request please review the stack trace for more information about the error and where it originated in the codeexception details systemwebhttpexception unable to serialize the session state in stateserver and sqlserver mode aspnet will serialize the session state objects and as a result nonserializable objects or marshalbyref objects are not permitted the same restriction applies if similar serialization is done by the custom session state store in custom modesource erroran unhandled exception was generated during the execution of the current web request information regarding the origin and location of the exception can be identified using the exception stack trace belowstack traceserializationexception type gebruiker in assembly app codeqzuhycmn version0 cultureneutral publickeytokennull is not marked as serializable systemruntimeserializationformatterservicesinternalgetserializablemembersruntimetype type 9452985 systemruntimeserializationformatterservicesgetserializablememberstype type streamingcontext context 247 systemruntimeserializationformattersbinarywriteobjectinfoinitmemberinfo 160 systemruntimeserializationformattersbinarywriteobjectinfoinitserializeobject obj isurrogateselector surrogateselector streamingcontext context serobjectinfoinit serobjectinfoinit iformatterconverter converter objectwriter objectwriter serializationbinder binder 218 systemruntimeserializationformattersbinarywriteobjectinfoserializeobject obj isurrogateselector surrogateselector streamingcontext context serobjectinfoinit serobjectinfoinit iformatterconverter converter objectwriter objectwriter serializationbinder binder 54 systemruntimeserializationformattersbinaryobjectwriterserializeobject graph header inheaders binarywriter serwriter boolean fcheck 542 systemruntimeserializationformattersbinarybinaryformatterserializestream serializationstream object graph header headers boolean fcheck 133 systemwebutilaltserializationwritevaluetostreamobject value binarywriter writer 1708httpexception 0x804005 unable to serialize the session state in stateserver and sqlserver mode aspnet will serialize the session state objects and as a result nonserializable objects or marshalbyref objects are not permitted the same restriction applies if similar serialization is done by the custom session state store in custom mode systemwebutilaltserializationwritevaluetostreamobject value binarywriter writer 1793 systemwebsessionstatesessionstateitemcollectionwritevaluetostreamwithassertobject value binarywriter writer 34 systemwebsessionstatesessionstateitemcollectionserializebinarywriter writer 638 systemwebsessionstatesessionstateutilityserializesessionstatestoredata item stream stream 244 systemwebsessionstatesessionstateutilityserializestoredatasessionstatestoredata item int32 initialstreamsize byte buf int32 length boolean compressionenabled 67 systemwebsessionstateoutofprocsessionstatestoresetandreleaseitemexclusivehttpcontext context string id sessionstatestoredata item object lockid boolean newitem 114 systemwebsessionstatesessionstatemoduleonreleasestateobject source eventargs eventargs 807 systemwebsessionstatesessionstatemoduleonendrequestobject source eventargs eventargs 184 systemwebsynceventexecutionstepsystemwebhttpapplicationiexecutionstepexecute 148 systemwebhttpapplicationexecutestepiexecutionstep step boolean completedsynchronously 75version information microsoft net framework version4030319 aspnet version40303191 the only thing i do there with sessions is this sessionrechten globaaladmin example sessiongebruikerid txtidtext the id they log in withand redirect them to another page responseredirectloggedinaspxtrue putting the gebruiker into a sessionthere have been multiple topics about this problem but none of them seem to have helped meeverything works locally but online it does not,"['c#', 'asp.net']" +148976,how do i create kanji japanese letters animations from svg data in objectivec i have seen several iphoneipad apps that show animated kanji for those of you who are unfamiliar with kanji stroke order is a very important part of kanji studying so if you are doing an app showing the animated stroke order is an essential partall the apps i have seen that do this credit the kanjivg project as their source for the stroke order data after some research i found that the kanjivg project gives you the data in svg format encoded in xml having never programmed graphics before and being relatively new to ios i am at a loss to where to keep looking for info i think i need toparse the xml into svgrender the svgbut i am not sure for what i could see how this is done in the iphoneipad apps i bought the animations all look surprisingly similar so there must be a common library that these guys are using that i am failing to find probably because i do not know exactly what i am looking forany pointers that anyone can give me will be greatly appreciatedcheers,"['ios', 'objective-c']" +148980,strange error when opening package for writing first things first i am using net 4i am trying to write some files to a package and i am encountering something strange when i do thisusing var package packageopenfilename filemodeopenorcreate fileaccesswrite do something with packagepackage refers to systemiopackagingpackagethe weird thing is that packageopen method throws an exception that sayscannot get stream with filemodecreate filemodecreatenew filemodetruncate filemodeappend when access is fileaccessreadi found an old bug report from 2009 on microsoft connectbut it does not helpso anyone got an idea,"['c#', '.net']" +148981,better way to concatenate multiple strings in c is there a better way to concatenate multiple strings together in c other than having multiple calls to strcat all in a row like belowchar prefix100 strcatprefix argv0strcatprefix strcatprefix cmd argv0strcatprefix strcatprefix cmd argv1perrorprefix,['c'] +148994,on delete cascade in sqlite3 i have the following structure sorry for awkward names it is because it is a sqlite database for my iphone app which is not released yetcreate table klb log id integer primary key autoincrement not null log comment varchar512create table klb log food maps uid integer did integer primary key uiddid foreign key uid references klb logid on delete cascade foreign key did references klb foodid on delete cascadecreate table klb food id integer description varchar255 primary key idis there a reason why the row in klb log food maps is not removed when i delete a row in klb log,['sql'] +149008,how to get generators call other generators in rails 3 i am experimenting with gem development right now specifically generators so far i have successfully created two generators that do their job just perfectly these two generators are in the same directoryhowever right now i have to call each of them separatelywhat i would like to do is just call one generator and have that generator call all the other ones just would typerails g generator nameand this would call x other generatorsdoes anyone know how would i got about doing thishelp is much appreciated thanks,"['ruby-on-rails', 'ruby']" +149033,whats the maximum key length for php apc you would think this would be supereasy to find but i cannot seem to,['php'] +149034,numpy array initialization fill with identical values i need to create a numpy array of length n each element of which is vis there anything better thana emptynfor i in rangen ai vi know zeros and ones would work for v 0 1 i could use v onesn but it would not work when v is none and also would be much slower,['python'] +149038,monitor changes in a file or directory in android how do i monitor changes made by others app internet bluetooth dll to a file or directory,['android'] +149039,how to remove characters from a string for example i have a user input a phone numbercout enter phone number input 5 5cin phonei want to remove the and characters from the string i have looked at the string remove find and replace functions however i only see that they operate based on positionis there a string function that i can use to pass a character for example and have it remove all instances within a stringthank you for your time,['c++'] +149043,how to use javascript variables in jquery selectors how do i use the javascript variables as a parameter in a jquery selectorscript typetextjavascriptfunction inputclickfunction var x thisattrname inputidxhide scriptinput typetext idbxinput typebutton namebxinput typetext idbyinput typebutton namebybasically what i want to do is to be able to hide the element which has id that is equal to the name of the element that is being clicked,"['javascript', 'jquery']" +149061,core data sorting by transient property workaround let us say i have a core data entity called event which represents recurrent yearly events each event has a date propertyi need to present this events to the user sorted by next occurrence of date this property of course depends on the current date and as such should be marked as transient there is no point in storing it in the databasebut as you know you cannot query sorting by a transient property in core datais there a smart way to keep this property transient and still have core data sort for me i do not want to fetch and then sort myself but i would also like to avoid storing this transient info in the database,['ios'] +149093,boost mpl list of templates i want to take a list of class templates t1 t2 tn and have a list an mpl list of classes where each template is instantiated with the same parameterboostmpllist cannot be used with a list of template template parameters just regular type parametersso the following does not workclass a templatetemplate class class tstruct applyparametera typedef ta typetypedef boostmpltransform boostmpllist t1 t2 t3 t4 applyparameteraboostmpl 1type typelisthow can i make it work,['c++'] +149116,springmvc is not recognizing request body parameters if using put maybe this is supposed to not work but at least i would like to understand why then i am passing a simple valsomevalue in the put body but spring sends back a 400 bad request as it does not seem to recognise the val parametersimilar request works with post could it be springmvc is not recognizing the put request body as source for parameterscontenttype is set correctly to applicationxwformurlencoded in both casesthe method that spring refuses to call is thisrequestmappingvalue configkey method requestmethodputresponsebodypublic void configupdatecreatefinal model model pathvariable final string key requestparam final string val final httpservletresponse response throws ioexception for completeness here is the jquery ajax call i cannot see anything wrong with that client is firefox 4 or chrome both show the same resultajax urlurl typeput dataval encodeuricomponentconfigvalue success functiondata any ideas,['jquery'] +149120,why does 0 hello return true in php hey if you have got the following code and want to check if key matches hello i have found out that the comparison always returns true if the variable is 0 i have came across this when an array for a special key and wondered why it is was not working as expectedsee this code for an examplekey 1if key hello echo hello echoes hellokey 2if key hello echo hello echoes hellokey 0if key hello echo 0hello doesnt echo hello whyif key hello echo hello echoes hellocan anyone explain this,['php'] +149121,does jquery ajax work in modern browsers with put and delete the jquery ajax call has a type parameter that allows to specify the method for an async call getpostputdelete documentation states thatthe type of request to make post or get default is get note other http request methods such as put and delete can also be used here but they are not supported by all browserswhat does this mean for modern browsers can i count on jquery ajax to make fully restful calls which rely on the put and delete verbs,['jquery'] +149123,what is difference between jpa project and ejb project in eclipse which one is used whenwhen i want jsf stateless bean jpa entity application i need ejb project and dynamic web project integrates in ear project,['java'] +149125,sensor fusion on ios devices i am trying to find out how could i start to implement sensor fusion on the iphone i have started from this talk from david sachssensor fusion on android devicesalthough davids talk is very illustrative it does not show any code it makes sense i have seen both the glgravity to extract the gravity vector and the accelerometergraph examples but i need some help or at least guidance on how to combine the accelerometer gyroscope and compass inputs so that the result is similar to what david showsthanks,"['iphone', 'ios']" +149133,log4net smtp appender only send email when error with full logdebug info error only when the application ends i am trying to configure a smtp appender in the log4netconfig file that i have the problem is that i have looked all over the internet and cannot find how to send an email when an error occurs with all the other log information included such as info debug error fatal only when the application ends not every time an error occursso i only want to receive this email when the application ends with all the log information debug info error fatal only if an error has occuredelaborating some more this is because of the way i handle my exceptions in c sharp with multiple level handling all over the place and so if an error occurs no matter how many times i only want to receive one email also i do not want to use multiple logs but ratherjust one in rootthanks,"['c#', '.net']" +149134,why does nsstring respond to appendstring i was playing with the respondstoselector method in objectivec on macosx 1067 and xcode 402 to identify if an object would respond to certain messages according to the manuals nsstring should not respond to appendstring while nsmutablestring should heres the piece of code which tests itint main int argc const char argv nsautoreleasepool pool nsautoreleasepool alloc init nsstring mystring nsstring alloc init if mystring respondstoselectorselectorappendstring nslogmystring responds to appendstring else nslogmystring does not respond to appendstring do stuff with mystring mystring release pool drain return 0and heres the outputclass0210241903 mystring responds to appendstringi would sort of expected the opposite how does an nsstring object respond to appendstring whats going on here that i am missing,['objective-c'] +149135,calling the constructor of the base class after some other instructions in c as far as i know it is not possible to call the constructor of the base class the only way i know is thismyclassmyclass args base args but this would invoke the constructor at the beginningis there any way to call it somewhere else in the constructor something like thismyclassmyclass args instructions basebase args other instructionsaccording to this c superclass constructor calling rules question i understand there is no way but i read here and i guessed it was possible but if i try i geterror invalid use of class baseam i doing something wrong is it possible to do this some way or is there any other possible solution to this needthanksedit i understand i forgot a key point the base class is part of a framework and therefore it would be good not to have to modify it if possible,['c++'] +149142,pattern needed create new object that returns an executeable function and inherits from a prototype scenario 1 everything worksvar awesomeobject function var self this selfwhatstuff really awesomeawesomeobjectprototypedostuff function var self this consolelogi did selfwhatstuff stuff return selfvar awesome new awesomeobject returns a new awesomeobjectawesomedostuff prints i did really awesome stuff on the consolenow i want it even awesomervar awesomeobject function var f function consolelogi am awesome var self f selfwhatstuff really awesome return selfawesomeobjectprototypedostuff function var self this consolelogi did selfwhatstuff stuff return selfvar awesome new awesomeobject returns the interal f objectawesome prints i am awesomeawesomedostuff throws an errornew awesomeobject should return an executable function itself so that i can say awesomebut i want it to inherit the awesomeobjectprototype tooadding selfprototype awesomeobjectprototype does not helpvar awesomeobject function var f function consolelogi am awesome var self f selfwhatstuff really awesome selfprototype awesomeobjectprototype return selfok i can copy the awesomeobjectprototype functions one after the other into the scope of f var awesomeobject function var f function consolelogi am awesome var self f selfwhatstuff really awesome selfdostuff function awesomeobjectprototypedostuffapplyselfarguments return selfbut i think there must be a better way a better pattern what is itthis issue drives me crazy help would be really appreciated in general how to create a function object that can be created with newreturns a function object that can be executedinherits all properties and methods of a given prototype is there a waythxfranz,['javascript'] +149146,get an attribute of a dom node i am trying to get an attribute of an xml node examplecar nametestcari want to grab the name attribute of the car node documentbuilderfactory dbf documentbuilderfactorynewinstancedocumentbuilder db dbfnewdocumentbuilder document doc dbparseconfigfiledocgetdocumentelementnormalize nodelist layerconfiglist docgetelementsbytagnamecarnode node layerconfiglistitem0 get the name attribute out of the nodethis is where i get stuck because the only method that looks like i can use is getattributes with returns a namednodemap and im not sure how to extract it from that,['java'] +149165,android eclipse exclamation mark next to project name i changed the dependent projects of one of my project and moved one of my files there as an experimenti now moved it back but the project would not runit tells me i have an error even though i cannot see one and clean project does not helphowever the project has an exclamation mark next to it what does that mean,['android'] +149171,how to use windows tooltip control without bounding to a tool i want to use the native windows tooltip control pure win32 api no mfc stuffi read the doc it seems that i have to send a ttm addtool message to bond a tool to the tooltip control only after that can i send ttm trackactivate ttm trackposition to show the tooltipbut i want to thisplay the tooltip anywhere i want it to be for example when the mouse hovers over a region of my window this region is not a tool in the eye of windows it is just a region in my windowperhaps i can bond the window to the tooltip control but does not this mean that i have to bond every window i created to the tooltip controlis there an easy solution so that i do not have to send ttm addtool messages for every windowi actually have written some code but the tooltip just does not appear anders answer solves some questions actually and after i poke around my code i make it workin case someone wants to know how it workhwnd tooltipwnd createwindowexwws ex topmost tooltips classw0ws popup tts noprefix tts alwaystip cw usedefault cw usedefaultcw usedefaultcw usedefault 00apphandle0toolinfow ti ticbsize sizeoftoolinfowtiuflags ttf absolute ttf ithishwnd ttf track do not specify ttf track here otherwise the tooltip would not show uptihwnd tooltipwnd by doing this you do not have to create another windowtihinst nulltiuid uinttooltipwndtilpsztext lsendmessagewtooltipwnd ttm addtoolw 0 lparamtisendmessagewtooltipwnd ttm setmaxtipwidth0 lparam350this will create a tooltip window which is not bound to any other windowso when you want to show the tooltip eg in responds to wm mousehover message call thistoolinfow ti ticbsize sizeoftoolinfowtihwnd tooltipwndtiuid uinttooltipwndtilpsztext lsample tip textsendmessagewtooltipwndttm updatetiptextw0lparamti this will update the tooltip contentsendmessagewtooltipwndttm trackactivatewparamtruelparamtisendmessagewtooltipwnd ttm trackposition0lparammakelongxy update the position of your tooltip screen coordinatesendmessagewtooltipwndttm popup00 ttm popup not working do not know why,['c++'] +149185,https connection using pem certificate i am trying to post https requests using a pem certificate like following import httplib cert file pathcertifpemconn httplibhttpsconnection10101010443 cert file cert file connrequestpost response conngetresponse print responsestatus responsereasonconnclosei have the following errortraceback most recent call lastfile stdin line 1 in modulefile usrlibpython26httplibpy line 914 in requestself send requestmethod url body headersfile usrlibpython26httplibpy line 951 in send requestselfendheadersfile usrlibpython26httplibpy line 908 in endheadersself send outputfile usrlibpython26httplibpy line 780 in send outputselfsendmsgfile usrlibpython26httplibpy line 739 in sendselfconnectfile usrlibpython26httplibpy line 16 in connectselfsock sslwrap socketsock selfkey file selfcert filefile usrlibpython26sslpy line 338 in wrap socketsuppress ragged eofssuppress ragged eofsfile usrlibpython26sslpy line 118 in init cert reqs ssl version ca certslsslerror errno 336265225 sslc339 error140b09ssl routinesl ctx use privatekey filepem libwhen i remove the cert file from httplib i have the following response200 okwhen i add the authentication header like advised by matth with empty post payload it works alsohowever when i put the good request with the path the body and the header like following i simplified thembody senvelope xmlnssblablablasenvelopeurlprov syncaxis2servicesxsyncserviceauth header basic s joinxencodebase64striprnconnrequestposturlprovbodyauthenticateauth headeri have 401 unauthorized response as you can see first i am asked to provide the privatekey why did i need the privatekey if i am a client then when i remove the privatekey and the certificate and put the pathbodyheaders i have 401 unauthorized error with the message wauthenticate basic realmsyncnb server realmcould any one explain this issue is there another way to send https request using a certificate in python,['python'] +149188,adding borderradius to tinymce textarea is it possible to add a borderradius to tinymced textareas it is kinda killing me that i have rounded corners on my input fields etc but i cannot get it working on my textarea probably because tinymce is turning it into an iframe is there any way around this thanks a lot,['css'] +149198,int array to byte array i know how to do this the long way create a byte array of the necessary size then used a for loop and casting every element from the int array but was wondering if there was a faster wayseems the way above would break if the int was bigger than an sbyte,['c#'] +149222,pass complex url as parameter in php i am trying to pass a complex url as a url parameter but the problem occurs if the url contains for example i want to pass the following link as a parameter clientfirefoxahs42frlsorgmozilla3aenus3aofficialqthetype27microsoftpracticesobjectbuilderlocator27isdefinedinanassemblythatisnotreferencedyoumustaddareferencetoassemblyaqfaqiaqloqi am trying to get a url as a parameter from a user and redirect user to this urlhow could i handle this in phpthe whole storyi am trying to make some ads analytics on flash files so user submit flash ads to a website which contains a link to the required webpagenowmy client needs to know how many times this flash file was clickedto solve this i ll till every one who submits flash to write a link to my client webpage and pass the required url as a parameter as followsid16by this way i can update my database and get a count for how many times this link was clicked,['php'] +149230,how to find out whitepixelvalue when person smile using cvrect i am able to detect faces coordinate detectfaceiplimage pimg cvhaarclassifiercascade pcascade cvmemstorage pstoragebut my problem is how to find out whitepixelvalue when person smile and what smile offset is appropriate 150 value is accurate smile haarcascade wont work at all need to do something with logic only with white pixelsplease helpupdate i think my bounty going to be waste did not get expert response on this thread i was looking for algorithm,['iphone'] +149276,transactionscope always tries to promote to msdtc i am trying to use a transaction scope inside a loop the entire loop takes place using a single connection to the database i am using entity framework 4 for database access during the second iteration of the loop when the linq to entites query executes an exception is thrown stating that the msdtc on the server is unavailable i have read that explicitly opening the connection and then enlisting the transaction is supposed to solve this problem but it has not below is sample code that mirrors the basic operation that is taking placeany ideas on how to prevent an escalation to msdtcusing context new myentities dim connection contextconnection connectionopen for index 0 to mefilescount 1 dim query from d in contextdocuments where ddocumentid documentid select dstatus dim status queryfirstordefault using trans new transactionscope connectionenlisttransactiontransactioncurrent dim result contextupdatestatustrue if result 1 then writetofile transcomplete end if end using nextend usingedit instead of transactionscope if i use connectionbegintransaction transactioncommit and transactionrollback it works fine however i would still like to find a way to make transactionscope work,['.net'] +149318,post nested object to spring mvc controller using json i have a controller with the post handler defined like sorequestmappingvalueajaxsavevendordo method requestmethodpostpublic responsebody ajaxresponse savevendor valid uivendor vendor bindingresult result locale currentlocale the uivendor object when viewed in json format looks likevar vendor vendorid 123 vendorname abc company emails emailaddress flags 2 emailaddress flags 3 the uivendor bean has a field called emails of type arraylist with appropriate setters and getters getemailssetemails the notificationemail object has the appropriate public settersgetters as wellwhen i try to post the object using the following codepostajaxsavevendordo paramvendor saveentitycallback json i get this error in the logsinvalid property emails0emailaddress of bean class beansuivendor property referenced in indexed property path emails0emailaddress is neither an array nor a list nor a map returned value was how do i correctly post a nested object like this to a spring controller and have it correctly deserialize into the appropriate object structureupdateper bohzos request here is the content of the uivendor class this class wraps a webservicegenerated bean class exposing the vendorattributes as individual fieldspackage commycompanybeansimport javautilimport orgapachecommonslangimport commycompanydomainvendorimport commycompanydomainvendorattributesimport orgapachecommonsloggingimport orgcodehausjacksonannotatejsonignorepublic class uivendor private final log logger logfactorygetlog thisgetclass private vendor vendor private boolean ftpflag private string ftphost private string ftppath private string ftpuser private string ftppassword private listuinotificationemail emails null public uivendor this new vendor public uivendor vendor vendor thisvendor vendor loadvendorattributes private void loadvendorattributes thisftpflag false thisftphost thisftppassword thisftppath thisftpuser thisemails null for vendorattributes a thisvendorgetvendorattributes string key agetvendorfakey string value agetvendorfavalue int flags agetflags if stringutilsisblankkey stringutilsisblankvalue continue if keyequals ftpflag thisftpflag booleanutilstoboolean value else if keyequals ftphost thisftphost value else if keyequalsftppath thisftppath value else if keyequalsftpuser thisftpuser value else if keyequalsftppassword thisftppassword value else if keyequalsemail uinotificationemail email new uinotificationemailvalue flags thisgetemailsadd email private void savevendorattributes int id thisvendorgetvendorid listvendorattributes attrs thisvendorgetvendorattributes attrsclear if thisftpflag vendorattributes flag new vendorattributes flagsetvendorid id flagsetstatus a flagsetvendorfakey ftpflag flagsetvendorfavalue booleanutilstostringtruefalse thisftpflag attrsadd flag if stringutilsisnotblank thisftphost vendorattributes host new vendorattributes hostsetvendorid id hostsetstatus a hostsetvendorfakey ftphost hostsetvendorfavalue thisftphost attrsadd host if stringutilsisnotblank thisftppath vendorattributes path new vendorattributes pathsetvendorid id pathsetstatus a pathsetvendorfakey ftppath pathsetvendorfavalue thisftppath attrsadd path if stringutilsisnotblank thisftpuser vendorattributes user new vendorattributes usersetvendorid id usersetstatus a usersetvendorfakey ftpuser usersetvendorfavalue thisftpuser attrsadd user if stringutilsisnotblank thisftppassword vendorattributes password new vendorattributes passwordsetvendorid id passwordsetstatus a passwordsetvendorfakey ftppassword passwordsetvendorfavalue thisftppassword attrsadd password for uinotificationemail e thisgetemails loggerdebugadding email e vendorattributes email new vendorattributes emailsetstatus a emailsetvendorfakey email emailsetvendorfavalue egetemailaddress emailsetflags egetflags emailsetvendorid id attrsadd email jsonignore public vendor getvendor savevendorattributes return thisvendor public int getvendorid return thisvendorgetvendorid public void setvendorid int vendorid thisvendorsetvendorid vendorid public string getvendortype return thisvendorgetvendortype public void setvendortype string vendortype thisvendorsetvendortype vendortype public string getvendorname return thisvendorgetvendorname public void setvendorname string vendorname thisvendorsetvendorname vendorname public string getstatus return thisvendorgetstatus public void setstatus string status thisvendorsetstatus status public boolean isftpflag return thisftpflag public void setftpflag boolean ftpflag thisftpflag ftpflag public string getftphost return thisftphost public void setftphost string ftphost thisftphost ftphost public string getftppath return thisftppath public void setftppath string ftppath thisftppath ftppath public string getftpuser return thisftpuser public void setftpuser string ftpuser thisftpuser ftpuser public string getftppassword return thisftppassword public void setftppassword string ftppassword thisftppassword ftppassword public listuinotificationemail getemails if thisemails null thisemails new arraylistuinotificationemail return emails public void setemailslistuinotificationemail emails thisemails emails update 2heres the output from jackson vendornamemail vendorid45 emails emailaddressdfg successfalse failurefalse flags0 vendortypedfg ftpflagtrue ftphostkdsfjng ftppathdsfg ftpusersdfg ftppasswordsdfg statusaand here is the structure of the object i am returning on the post vendorid45 vendornamemail vendortypedfg ftpflagtrue ftphostkdsfjng ftpusersdfg ftppathdsfg ftppasswordsdfg statusa emails successfalse failurefalse emailaddressdfg successtrue failuretrue emailaddress i have tried serializing using the json library from wjsonorg as well and the result is exactly what you see above however when i post that data all of the fields in the uivendor object passed to the controller are null although the object is not,['jquery'] +149328,is there a full working example for a jqgrid columnchooser at ui methods there are instructions for building a jqgrid column chooser dlog opts is either an option object to be passed to adloga or more likely a function that creates the options object the default produces a suitable options object for uidialog but not complete working code no example is provided of the function that is requiredis there a complete working example for building a jqgrid column chooser that will allow hiding showing and moving columns,"['javascript', 'jquery']" +149336,warning nokogiri was built against libxml version 277 but has dynamically loaded 2616 i canat work out why iam getting this error from nokogiri when i start up rails from the little i know it seems like something else is causing an older version of libxml2 to be loaded which nokogiri then ends up using rather than the version it was compiled againstwhat do i need to do to get this working without the warning and with the right libxml2iam running this on a macbook with os x 1058 rake dbcreatein usersgarethsitesrails3ngtestwarning nokogiri was built against libxml version 277 but has dynamically loaded 2616hi youre using libxml2 version 2616 which is over 4 years old and hasplenty of bugs we suggest that for maximum htmlxml parsing pleasure youupgrade your version of libxml2 and reinstall nokogiri if you like usinglibxml2 version 2616 but do not like this warning please define the constanti know i am using an old and buggy version of libxml2 before requring nokogiringtest test already existsngtest development already exists dyld print libraries1 rake dbcreatedyld loaded usersgarethrvmrubiesruby192p136binrubydyld loaded usersgarethrvmrubiesruby192p136liblibruby191dylibdyld loaded usrliblibsystembdylibdyld loaded usrliblibobjcadylibdyld loaded usrliblibgcc s1dylibdyld loaded usrlibsystemlibmathcommonadylibdyld loaded usrliblibautodylibdyld loaded usrliblibstdc6dylibdyld loaded usersgarethrvmrubiesruby192p136libruby191i386darwin980encencdbbundledyld loaded usersgarethrvmrubiesruby192p136libruby191i386darwin980enctranstransdbbundledyld loaded usersgarethrvmrubiesruby192p136libruby191i386darwin980etcbundlein usersgarethsitesrails3ngtestdyld loaded usersgarethrvmrubiesruby192p136libruby191i386darwin980stringiobundledyld loaded usersgarethrvmrubiesruby192p136libruby191i386darwin980syckbundledyld loaded usersgarethrvmrubiesruby192p136libruby191i386darwin980digestsha1bundledyld loaded usrliblibcrypto097dylibdyld loaded usersgarethrvmrubiesruby192p136libruby191i386darwin980digestbundledyld loaded usersgarethrvmrubiesruby192p136libruby191i386darwin980enciso 8859 1bundledyld loaded usersgarethrvmrubiesruby192p136libruby191i386darwin980zlibbundledyld loaded usrliblibz1dylibdyld loaded usersgarethrvmrubiesruby192p136libruby191i386darwin980strscanbundledyld loaded usersgarethrvmrubiesruby192p136libruby191i386darwin980bigdecimalbundledyld loaded usersgarethrvmgemsruby192p136gemsmysql281libmysql apibundledyld loaded usrlocalcellarmysql5154libmysqllibmysqlclient16dylibdyld loaded usersgarethrvmrubiesruby192p136libruby191i386darwin980opensslbundledyld loaded usrliblibssl097dylibdyld loaded usersgarethrvmrubiesruby192p136libruby191i386darwin980fcntlbundledyld loaded usersgarethrvmgemsruby192p136gemseventmachine01210librubyeventmachinebundledyld loaded usersgarethrvmgemsruby192p136gemsthin127libthin parserbundledyld loaded usersgarethrvmrubiesruby192p136libruby191i386darwin980digestmd5bundledyld loaded usersgarethrvmrubiesruby192p136libruby191i386darwin980iconvbundledyld loaded usrliblibiconv2dylibdyld loaded usersgarethrvmgemsruby192p136gemsjson146extjsonextjsonextparserbundledyld loaded usersgarethrvmrubiesruby192p136libruby191i386darwin980encutf 16bebundledyld loaded usersgarethrvmrubiesruby192p136libruby191i386darwin980encutf 16lebundledyld loaded usersgarethrvmrubiesruby192p136libruby191i386darwin980encutf 32bebundledyld loaded usersgarethrvmrubiesruby192p136libruby191i386darwin980encutf 32lebundledyld loaded usersgarethrvmgemsruby192p136gemsjson146extjsonextjsonextgeneratorbundledyld loaded usersgarethrvmgemsruby192p136gemsrpegmarkdown146libpeg markdownbundledyld loaded usrlocalcellarglib2242liblibglib200dylibdyld loaded usrlocalcellargettext017liblibintl8dylibdyld loaded systemlibraryframeworkscarbonframeworkversionsacarbondyld loaded systemlibraryframeworkscoreservicesframeworkversionsacoreservicesdyld loaded systemlibraryframeworkscorefoundationframeworkversionsacorefoundationdyld loaded systemlibraryframeworkscarbonframeworkversionsaframeworkscarbonsoundframeworkversionsacarbonsounddyld loaded systemlibraryframeworkscarbonframeworkversionsaframeworkscommonpanelsframeworkversionsacommonpanelsdyld loaded systemlibraryframeworkscarbonframeworkversionsaframeworkshelpframeworkversionsahelpdyld loaded systemlibraryframeworkscarbonframeworkversionsaframeworkshitoolboxframeworkversionsahitoolboxdyld loaded systemlibraryframeworkscarbonframeworkversionsaframeworkshtmlrenderingframeworkversionsahtmlrenderingdyld loaded systemlibraryframeworkscarbonframeworkversionsaframeworksimagecaptureframeworkversionsaimagecapturedyld loaded systemlibraryframeworkscarbonframeworkversionsaframeworksinkframeworkversionsainkdyld loaded systemlibraryframeworkscarbonframeworkversionsaframeworksnavigationservicesframeworkversionsanavigationservicesdyld loaded systemlibraryframeworkscarbonframeworkversionsaframeworksopenscriptingframeworkversionsaopenscriptingdyld loaded systemlibraryframeworkscarbonframeworkversionsaframeworksprintframeworkversionsaprintdyld loaded systemlibraryframeworkscarbonframeworkversionsaframeworkssecurityhiframeworkversionsasecurityhidyld loaded systemlibraryframeworkscarbonframeworkversionsaframeworksspeechrecognitionframeworkversionsaspeechrecognitiondyld loaded systemlibraryframeworksapplicationservicesframeworkversionsaapplicationservicesdyld loaded systemlibraryframeworkscoreaudioframeworkversionsacoreaudiodyld loaded systemlibraryframeworkscoreservicesframeworkversionsaframeworkscarboncoreframeworkversionsacarboncoredyld loaded systemlibraryframeworkscoreservicesframeworkversionsaframeworkscfnetworkframeworkversionsacfnetworkdyld loaded systemlibraryframeworkscoreservicesframeworkversionsaframeworksmetadataframeworkversionsametadatadyld loaded systemlibraryframeworkscoreservicesframeworkversionsaframeworksosservicesframeworkversionsaosservicesdyld loaded systemlibraryframeworkscoreservicesframeworkversionsaframeworkssearchkitframeworkversionsasearchkitdyld loaded systemlibraryframeworkscoreservicesframeworkversionsaframeworksaeframeworkversionsaaedyld loaded systemlibraryframeworkscoreservicesframeworkversionsaframeworkslaunchservicesframeworkversionsalaunchservicesdyld loaded systemlibraryframeworkscoreservicesframeworkversionsaframeworksdictionaryservicesframeworkversionsadictionaryservicesdyld loaded systemlibraryframeworksiokitframeworkversionsaiokitdyld loaded usrliblibicucoreadylibdyld loaded systemlibraryframeworksthiskarbitrationframeworkversionsathiskarbitrationdyld loaded usrliblibbsmdylibdyld loaded systemlibraryframeworkssecurityframeworkversionsasecuritydyld loaded systemlibraryframeworkssystemconfigurationframeworkversionsasystemconfigurationdyld loaded usrliblibsqlite30dylibdyld loaded usrliblibresolv9dylibdyld loaded usrliblibxml22dylibdyld loaded usrliblibxslt1dylibdyld loaded systemlibraryframeworksfoundationframeworkversionscfoundationdyld loaded systemlibraryframeworksapplicationservicesframeworkversionsaframeworksatsframeworkversionsaatsdyld loaded systemlibraryframeworksapplicationservicesframeworkversionsaframeworkscolorsyncframeworkversionsacolorsyncdyld loaded systemlibraryframeworksapplicationservicesframeworkversionsaframeworkscoregraphicsframeworkversionsacoregraphicsdyld loaded systemlibraryframeworksapplicationservicesframeworkversionsaframeworkscoretextframeworkversionsacoretextdyld loaded systemlibraryframeworksapplicationservicesframeworkversionsaframeworkshiservicesframeworkversionsahiservicesdyld loaded systemlibraryframeworksapplicationservicesframeworkversionsaframeworksimageioframeworkversionsaimageiodyld loaded systemlibraryframeworksapplicationservicesframeworkversionsaframeworkslanganalysisframeworkversionsalanganalysisdyld loaded systemlibraryframeworksapplicationservicesframeworkversionsaframeworksprintcoreframeworkversionsaprintcoredyld loaded systemlibraryframeworksapplicationservicesframeworkversionsaframeworksqdframeworkversionsaqddyld loaded systemlibraryframeworksapplicationservicesframeworkversionsaframeworksspeechsynthesisframeworkversionsaspeechsynthesisdyld loaded systemlibraryframeworksaccelerateframeworkversionsaacceleratedyld loaded systemlibraryframeworksaccelerateframeworkversionsaframeworksvimageframeworkversionsavimagedyld loaded systemlibraryframeworksaccelerateframeworkversionsaframeworksveclibframeworkversionsaveclibdyld loaded systemlibraryframeworksaccelerateframeworkversionsaframeworksveclibframeworkversionsalibvmiscdylibdyld loaded systemlibraryframeworksaccelerateframeworkversionsaframeworksveclibframeworkversionsalibvdspdylibdyld loaded systemlibraryframeworksaccelerateframeworkversionsaframeworksveclibframeworkversionsalibblasdylibdyld loaded systemlibraryframeworksaccelerateframeworkversionsaframeworksveclibframeworkversionsaliblapackdylibdyld loaded systemlibraryframeworksapplicationservicesframeworkversionsaframeworksimageioframeworkversionsaresourceslibjpegdylibdyld loaded systemlibraryframeworksapplicationservicesframeworkversionsaframeworksimageioframeworkversionsaresourceslibtiffdylibdyld loaded systemlibraryframeworksapplicationservicesframeworkversionsaframeworksimageioframeworkversionsaresourceslibgifdylibdyld loaded systemlibraryframeworksapplicationservicesframeworkversionsaframeworksimageioframeworkversionsaresourceslibpngdylibdyld loaded systemlibraryframeworksapplicationservicesframeworkversionsaframeworksimageioframeworkversionsaresourceslibradiancedylibdyld loaded usrliblibcups2dylibdyld loaded systemlibraryframeworkskerberosframeworkversionsakerberosdyld loaded systemlibraryprivateframeworkscoreuiframeworkversionsacoreuidyld loaded systemlibraryframeworksquartzcoreframeworkversionsaquartzcoredyld loaded systemlibraryprivateframeworksdesktopservicesprivframeworkversionsadesktopservicesprivdyld loaded systemlibraryframeworksopenglframeworkversionsaopengldyld loaded systemlibraryframeworksopenglframeworkversionsalibrarieslibglimagedylibdyld loaded usrliblibffidylibdyld loaded systemlibraryframeworkscorevideoframeworkversionsacorevideodyld loaded systemlibraryframeworksopenglframeworkversionsalibrarieslibgludylibdyld loaded systemlibraryframeworksopenglframeworkversionsalibrarieslibgldylibdyld loaded systemlibraryframeworksopenglframeworkversionsalibrarieslibglprogrammabilitydylibdyld loaded systemlibraryprivateframeworksinstallserverframeworkversionsainstallserverdyld loaded usersgarethrvmgemsruby192p136gemsnokogiri144libnokogirinokogiribundledyld loaded usrlocalcellarlibxslt1126liblibexslt0dylibdyld loaded usrlocalcellarlibxslt1126liblibxslt1dylibdyld loaded usrlocalcellarlibxml2277liblibxml22dylibwarning nokogiri was built against libxml version 277 but has dynamically loaded 2616hi youre using libxml2 version 2616 which is over 4 years old and hasplenty of bugs we suggest that for maximum htmlxml parsing pleasure youupgrade your version of libxml2 and reinstall nokogiri if you like usinglibxml2 version 2616 but do not like this warning please define the constanti know i am using an old and buggy version of libxml2 before requring nokogiridyld loaded usersgarethrvmrubiesruby192p136libruby191i386darwin980racparsebundledyld loaded usersgarethrvmrubiesruby192p136libruby191i386darwin980socketbundlengtest test already existsngtest development already exists nokogiri v warnings nokogiri 144ruby version 192 platform i386darwin980 engine rubylibxml binding extension compiled 277 loaded 277,['ruby-on-rails'] +149339,turning one annotation into many annotations with aspectj i have thiscovered a pattern in my jpa mappings that i would like to codify a simple example followsonetomanyfetchfetchtypeeagersorttypesorttypenaturalprivate sortedsetitem itemsi would like to create a single annotation called sortedonetomany that i can apply to the above setpublic interface sortedonetomany fetchtype fetch default eager sorttype sort default natural class comparator default voidclassi have written the following aspect to attach the jpa annotations whenever it sees my annotationpublic aspect sortedonetomanyaspect declare field sortedonetomany onetomanyfetchfetchtypeeager declare field sortedonetomany sorttypesorttypenaturalbut i do not know how can i access the values of the sortedonetomany annotation parameters and use them when defining the onetomany and sort annotations there may be cases where i want to change one of the default values like sosortedonetomanysortsorttypecomparatorcomparatoritemcomparatorclassprivate sortedsetitem itemsso how can i pass the annotation values from sortedonetomany to the sort annotation,['java'] +149346,how to extract parameters from a given url in java i havestring params depcityparroomtypeddepcitynyci want to get values of depcity parameters parnycso i created regexstring regex depcitypattern p patterncompileregexmatcher m pmatcherparamsmfind is returning false mgroups is returning illegalargumentexceptionwhat am i doing wrong,['java'] +149352,how to implement an androidbackground that does not stretch i found this great thread describing how to eat the cake and have it too ie use image for a button instead of imagebutton which does not allow settext resizing etcthis is achieved by using the view attributeandroidbackgrounddrawablebgimagethe only problem with this is that it stretches the image to fit the button sizeshort of hardcoding a fixed button size in pixels is there a way to tell android not to stretch the background image at all and either crop or pad it,['android'] +149354,jquery flot and graphtable colors how can i change the line colors with the flot plugin and graphtabletablestaticsgraphtableseries columns position replace height 180pxbut i would like to change the colors in the options of graphtable something liketablestaticsgraphtableseries columns position replace height 180px colors 92d5ea 699 be1e2d ee8310 8d10eeand then each line in the resulting flot graph would have the corresponding colors from the column,['jquery'] +149362,parsing an iso datetime in python possible duplicateconverting string to datetime object in python given the below pythonimport datetime a20110504 162009 0700 datetimedatetimestrptimea ymd hms ztraceback most recent call last file stdin line 1 in module file usrlibpython26 strptimepy line 317 in strptime bad directive formatvalueerror z is a bad directive in format ymd hms z i do not really understand how z is a bad directivereferencethis is from hg which says that it is in iso8601 format,['python'] +149365,increasing maximum response size from aspnet page method i have got a page method on an aspx page that gets called by a jquery ajax post request when i try to return too many results the request fails is there a webconfig setting or class attribute i can use to increase the default maximum response size,"['c#', 'javascript', 'jquery', 'asp.net']" +149398,recursive diff of two python dictionaries keys and values so i have a python dictionary call it d1 and a version of that dictionary at a later point in time call it d2 i want to find all the changes between d1 and d2 in other words everything that was added removed or changed the tricky bit is that the values can be ints strings lists or dicts so it needs to be recursive this is what i have so fardef d1 d2 ctx print changes in ctx for k in d1 if k not in d2 print k removed from d2 for k in d2 if k not in d1 print k added in d2 continue if d2k d1k if typed2k not in dict list print k changed in d2 to strd2k else if typed1k typed2k print k changed to strd2k continue else if typed2k dict d1k d2k k continue print done with changes in ctx returnit works just fine unless the value is a list i cant quite come up with an elegant way to deal with lists without having a huge slightly changed version of this function repeated after a iftyped2 list any thoughtsedit this differs from this post because the keys can change,['python'] +149407,writing oo javascript with jquery i come from a prototype js background where oo javascript is encouraged through the use of classcreate now i am doing some jquery work and i am trying to write some properly structured jquery code where i can for example call the same object function from two different click event handlers here is the code in prototypedocumentobservedomloaded function create document apagehelper new apagehelper namespace our codewindowapp my classapagehelper classcreate automatically called initialize functionname sound thismyvalue foo attach event handlers binding to this object mybuttonobserveclick thisthisplaymessagebindthis thisplaymessage function consolelogmy value thismyvalue this is the object not the clicked button i am wondering how the following code can be replicated in jquery where there is no way to bind a function call to the object it is called in and this is always the element clicked i have heard of a way to do it the douglas crockford module pattern but i would love if someone could show me how you would implement the code above using jquery and that pattern thanks in advance,"['javascript', 'jquery']" +149416,jquery css borderwidth i am unable to get the border width of an element i tried the following but it shows empty results check divcssborderwidth,['jquery'] +149422,how do header and source files in c work i have perused the possible duplicates however none of the answers there are sinking intldr how are source and header files related in c do projects sort out declarationdefinition dependencies implicitly at build timei am trying to understand how the compiler understands the relationship between c and h filesgiven these filesheaderhint returnsevenvoidsourcecint returnsevenvoid return 7maincinclude stdiohinclude stdlibhinclude headerhint mainvoid printfd returnseven return 0will this mess compile i am currently doing my work in netbeans 70 with gcc from cygwin which automates much of the build task when a project is compiled will the project files involved sort out this implicit inclusion of sourcec based on the declarations in headerh,['c'] +149442,showing preference screen first time app is run and related questions i have an app with 2 activities the preference and the main activity i need the preference screen to show first time the app is run so the user can do some configuration i have checked through the answers on this topic and they do not seem very clear but i gather it has to do with checking that there are sharedpreference file is emptycan someone please give me a code to sort this out and on which activity would i put the codealso i am still in the developing stage so i already have my preferences setup how do i undo thisthanks in advance,['android'] +149450,jquery autocomplete remote example i was really hoping to avoid posting a new question but i cannot find a functioning example of the jquery autocomplete remote feature that includes both the calling page and the search page the jqueryui demos documentation section does not include the source of searchphpi have tried dozens of combinations but heres what i started withstyle uiautocompleteloading background white urlimagesuianim basic 16x16gif right center norepeat style script function function log message div text message prependto log log attr scrolltop 0 birds autocomplete source searchphp minlength 1 select function event ui log uiitem selected uiitemvalue aka uiitemid nothing selected input was thisvalue scriptdiv classdemodiv classuiwidget label forbirdsbirds label input idbirds divdiv classuiwidget stylemargintop2em fontfamilyarial result div idlog styleheight 200px width 300px overflow auto classuiwidgetcontentdivdivdivand searchphp conn mysql connectlocalhost username password mysql select dbdatabase conn q strtolower getbirds query mysql queryselect field from table where field like q while row mysql fetch arrayquery echo json encoderowdoes anyone have code snippets that show both sides of this equation that they can share thanks so much to any help you can provide,"['php', 'jquery', 'mysql']" +149453,why does iis on azure web roles need to recompile aspnet apps so often i have aspnet applications deployed on a number of different environments appharbor azure thiscountaspnet godaddy etc and one thing that bothers me with my deployments on azure is that my lowtraffic websites get jitcompliled if there has not been a request for more than a couple of hoursobviously i could solve this by increasing the amount of traffic to my site i am being facetious or by trying to do some hacky things with precompilation but i would rather understand why the site needs to be compiled constantly in azure i have never noticed this issue on other providers even godaddy for lowtraffic sites is there some reason for this and is there anything i can do in the azure config files to stop this,['asp.net'] +149459,location service ios alert call back when we use location services in an application we receive an ios alert saying the application is trying to use the current location allowdo not allow do we have a delegate call back for these buttonsi want to handle tap on do not allow,"['iphone', 'objective-c']" +149467,detecting chess moves from successive image differences using opencv tools hey i am coding up a simple chess playing robots vision system i am trying to improve on some previous research to allow camera and a standard chess set be used and both be allowed to move during the game so far i can locate the board in an image acquired via webcam and i want to detect moves by taking difference of successive images to determine what has changed then use previous information about the board occupancy to detect movesmy problem is that i cannot seem to reliably detect changes at the moment my current pipeline goes like thissubtract two images histogram equalize the difference image erode and dilate diff image to remove minor changes make a binary copy and do thistance transform get the largest blobcorresponding to the highest value after dt and flood fill that blob repeat again until dt returns a value small enough to ignore changei am coding all this in opencv and c but my flood fill seem to always either not fill the blobs hence most cases i just get one change detected i have tried also using cvinpaint but that did not help either so my question is am i just using the wrong approach or somehow turing can make the change detection more reliable in case of the former could people suggest alternative routes preferable codable in cpython andor opencv in a reasonable timethanks,['c++'] +149485,mysql concat and lower weirdness any idea why this works sensiblymysql select lowerab100c lowerab100c ab100c 1 row in set 0 secbut this does notmysql select lowerconcata b 100c lowerconcata b 100c ab100c 1 row in set 0 secsensibly the way i think it should work,['mysql'] +149508,performance considerations of inheritance in c does the compiler produce the same il if i make a class with public int i or any other field vs making a class that inherits from a base class that has public int ieither way the resulting class behaves identically but does the compiler behave identicallyie is the compiler just copypasting code from base classes into the derived classes or is it actually creating two different class objects when you inheritclass a public int iclass b anow is there any performance difference between the following two dosomething callsvar a new avar b new bdosomethingaidosomethingbi is this line slower than the above line due to inheritancetry to ignore any optimizations the compiler might do for this special case my question is about whether inheritance in c in general has an associated performance penalty most of the time i do not care but sometimes i want to optimize a piece of high frequency code,['c#'] +149545,how to fill a list with 0 using python i want to get a fixed length list from another list likea abcb 0and i want to get a list like this abc0 in other words if lena lenb i want to fill up list a with values from list b up to length of the list b somewhat similar to what strljust doesthis is my codeaabcb 0 for i in range5b ai for i in b if ai else iprint abut it shows error file cpy line 7 b ai for i in b if ai else i syntaxerror invalid syntaxwhat can i do,['python'] +149569,jquery 16 formvalidate not working in ie7 ie8 updatei have created a new mvc 3 project with razor html 5 then i have updated the project with nuget at jquery 16 and the validation plugin does not work any more it does a post back every time and returns the error message from server i think the validation plugin is broken with jquery 16i have a mvc 3 app that uses jquery ui dialog loaded from a partial view that contains a form in order to submit information over ajax to the server i want to trigger the validation of my form on the client side before i do the ajax post on firefox and ie9 works fine in ie7 ie8 the formvalidate always returns truehere is the js code attached to my submit button var wizard wizard div that holds the modal dialog var myform wizard form var submitfunction function e epreventdefault no postback myformvalidate if myformvalid thisattrthisabled thisabled submited true post superadmincreateeditcontroller thisserialize function data if datasuccess wizarddialogdestroy else wizardhtmldatahtml json end json post myformsubmitsubmitfunctioni am using the following includesscript srcurlcontentscriptsjquery16minjs typetextjavascriptscriptscript srcurlcontentscriptsjqueryvalidatejs typetextjavascriptscriptscript srcurlcontentscriptsjqueryvalidateunobtrusivejs typetextjavascriptscriptthe jquery validation plugin was upgraded with nuget at version 180 and jquery library to 16updatei have tested the code generated with scaffolding default template and it does the same thing no client side validation maybe jquery 16 is not compatible with the razor scaffolding template,['jquery'] +149573,data access architectures with raven db what data access architectures are available that i can use with raven dbbasically i want to separate persistence via interfaces so i do not expose underline storage to the upper layers ie i do not want my domain to see idocumentstore or idocumentsession which are from raven dbi have implemented the generic repository pattern and that seems to work however i am not sure that is actually the correct approach maybe i shall go towards commandquery segregation or something elsewhat are your thoughts,['c#'] +149587,edittext not restoring state in dialogfragment i currently have a dialogfragment that has a couple of edittext widgets as part of it is view when there is an orientation change happens the edittext widgets are not repopulated by the text that was in them i have looked through the saveinstancestate and the text is being persisted though the orientation change dialogfragment public final class logindialog extends dialogfragment override public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate view v inflaterinflaterlayoutlogin container false return v an example edittextedittextandroidtextandroidididloginusernameandroidlayout width180dipandroidlayout heightwrap contentandroidlayout marginright5dipi am using the android compatibility package,['android'] +149628,how to get the private fields of class and its parent classes by reflection i have the class b and its parent class a both in namespace domainclass a has the private field aclass b has the private field bthen i have a reflection util in namespace reflectif i use this lineinstanceofbgettypegetfieldsbindingflagsnonpublic bindingflagspublic bindingflagsinstance to to find all fields a b i get only b but when i make a protected or public i find them toowhat do i need to do to find the private fields of the base class too,['c#'] +149633,jquery draggable revert and stop event first question so be kind what i am trying to do is call a function when the user releases the draggable and before the revert animation has completedas far as i can see the stop event is called only when the revert has finished i have tried passing a function to the revert option of draggable but it does not seem to work here is a bit of my code to demonstrateadraggable helperfunction return dividmydragtextlinkappendtobody revertfunctionevtui mydragfadeoutslow return true stopfunctionevtui consolelogfin if i uncomment the first line of the revert function fadeout then the element fades out but does not revert the console only logs fin when the revert animation has completedcan anyone help me needless to say i have googled a lot for an answer but with no luckbuster,['jquery'] +149635,how can i count unique pairs of values in sql with the following sql statement i can get all unique values with their counts for a given columnselect column countcolumn as count from table group by column order by count deschow would i get all unique pairs of values with counts for instance if i had a table of with columns first name and last name i might find results something like thisfirst name last name count john smith 42 john johnson 39david smith 37etccan i do this in basic sql i generally use mysql but i assume whatever solution you come up with should be translatable to any db,['sql'] +149639,api errors customization for rails 3 like github api v3 i am adding an api on a rails3 app and its pretty going goodbut i saw the following github api v3 at http11 422 unprocessable entity contentlength 149 message validation failed errors resource issue field title code missing field i liked the error messages structure but could not get it to reproducehow can i make my apis to make the response like it,['ruby'] +149660,android junit testing how to expect an exception im attempting to write some tests using the built in android junit testing framework i am running into a problem with a test where i am expecting an exception to be thrown in junit the annotation for the test method would be testexpected arithmeticexceptionclasshowever in android this test fails with an arithmeticexceptioni understand that the android implementation is only a subset of junit 3 and doesnt even allow the annotation test must be smalltest mediumtest or largetest and none of those allow for the expected parameter but this seems like a fairly significant test and seems like the android testing framework would be seriously lacking if it did not have this featurenote i tested this by adding the junit jar to the project and by adding and the annotations to my test methods it makes sense to me why the annotations would be completely ignored because the android framework runner is not looking for that annotation and just ignores it basically i am just looking for the right way to do this within the framework,['android'] +149666,splitting a rectangular image to polygons to simulate breaking glass i am working on some c code in which i would like to take a 2d rectangle and split it to smaller 2d polygons i would like the effect to look like the rectangle was made of glass and it was hit with a hammer in a random spot i was wondering if anyone knows of a good algorithm to help me with this i have tried the fortunevoronoi code using random points to simulate this effect but am having a hard time turning the finished voronoigraph in to a set of non intersecting polygons in a reasonable amount of cpu time,['c#'] +149673,additional parameter in form for in rails is it possible to submit another parameter outside the form data in rails my problem is that i render different forms for different classes and send them to the same create method i would like to send the class with the form as value not as key in the hashsomething like the type parameter that actually does not work form foran object url controller a controller action create type an objectclassto sunderscore do f the post message looks likecommitcreate class of an object authenticity tokeniqu0a8aocdt3hyjl5bkzilkyr4fe71umc8wx0y utf8a class of an objectnamea name descriptiona descriptionand i would have a type class of an object but directly in the hash an not within the class of an object hash,['ruby-on-rails'] +149674,is there a gem that normalizes and format us phone numbers in ruby i was using phony to format phone numbers meaning if i put in x it would convert to a string and also tell if there is a 1 before to remove itbut it really does not work for us phone number it is designed for international numbersis there an equivalentthanks,"['ruby-on-rails', 'ruby']" +149680,select last 20 order by ascending phpmysql this is my table structure mytableidpkauto increment topicid uid commentnow i want to get the last 20 comment for a topicid but it should be sorted in ascending order just like facebook by default shows last 20 comment onlyi am looking for an optimized version i can do this with 23 query and php sort array but looking for some better alternativesample result with datamytable id topicid uid comment 1 1 10 a 2 1 11 b 3 1 10 c 4 1 10 d 5 1 11 e 6 1 10 fi want to get the last 3 result for a topicid the result should be 4 1 10 d 5 1 11 e 6 1 10 fand not6 1 10 f 5 1 11 e 4 1 10 d,"['php', 'mysql']" +149681,a function inside an if structure can i put a function in php inside a if structure like thisphp iftrue function helloworld echo hello world helloworld because i have tried and it works but i do not know if it is correct or not thanks,['php'] +149694,do not reload application when orientation changes i simply need nothing to change when the screen is rotated my app thisplays a random image when it first loads and rotating the device should not select another random image how can i simply make this behavior stop,['android'] +149705,are gcc3 binaries compatible with gcc4 i have a static library that has been compiled with gcc 343 i would like to use this in code that will now be compiled with gcc4i have read vaguely that gcc3 and gcc4 binaries are not compatible and that the library will need to be recompiled but just want confirmation on this is not there anyway a gcc3 library can be used with gcc4,"['c++', 'c']" +149710,can you suggest free javascript plugin for intellij idea downloaded intellij idea community edition realized that it has no javascript support and debuggerany suggestions for good free plugin,"['javascript', 'jquery']" +149720,core graphics drawing a line at an angle i have been searching struggling with this for a while now and need some help i just want to draw 25 lines from the centre of my thisplay 160200 at 144 degrees separation i have been using this line of code in a for loop where x is the 144 degree multiplier uiimagebackgroundimage uiimage imagenamedprimate background onlypngbackgroundimage drawinrectcgrectmake0 0 320 480 draw outer circle rect cgrectmake00 350 3200 3200 cgcontextref contextref uigraphicsgetcurrentcontext get the contextrefcgcontextsetlinewidth contextref 05 set the border widthcgcontextsetrgbfillcolor contextref 2190f2550f 2190f2550f 2190f2550f 005f set the circle fill color to greencgcontextsetrgbstrokecolor contextref 00 00 00 02 set the circle border color to black cgcontextfillellipseinrect contextref rect fill the circle with the fill colorcgcontextstrokeellipseinrect contextref rect draw the circle border draw inner circlerect cgrectmake250 600 2700 2700 get the contextrefcgcontextsetlinewidth contextref 05 set the border widthcgcontextsetrgbfillcolor contextref 2190f2550f 2190f2550f 2190f2550f 025fcgcontextsetrgbstrokecolor contextref 00 00 00 02 set the circle border color to black cgcontextfillellipseinrect contextref rect fill the circle with the fill colorcgcontextstrokeellipseinrect contextref rect draw segments cgcontextref context uigraphicsgetcurrentcontextcgcontexttranslatectmcontext 00 00 for x1 x26 x cgcontextsetlinewidth context 05 cgcontextsetrgbstrokecolor context 00 00 00 025 cgcontextmovetopoint context 160 200 cgcontextaddlinetopoint context 1600 cosx144m pi180 1600 sinx144m pi180 the angle is in degrees cgcontextaddlinetopoint context 200 65 cgcontextaddlinetopoint context 160 200 cgcontextstrokepathcontext why is this not showing both line color and infill cgcontextsetfillcolorwithcolor context uicolor whitecolorcgcolor cgcontextfillpath context cgcontextref context uigraphicsgetcurrentcontext i intended to post an image here but it would not permit mecan someone please correct my trig functions this is meant to draw 25 lines clockwise from 1200 of the clock to 2400 instead it draws backwards only 90 degrees then returns all lines are way out in length alsovery gratefulabove is a bigger sample of the code used to draw tow outer circles and the interior segments as requested i will try and upload the image next,"['iphone', 'objective-c']" +149722,javascript date to string here is what i need to do get date convert to string and pass it over to a third party utility the response from the library will have date in string format as i passed it so i need to convert the date to string like 20110506105524 ymmddhhmmssfunction printdate var temp new date var datestr tempgetfullyeartostring tempgetmonthtostring tempgetdatetostring tempgethourstostring tempgetminutestostring tempgetsecondstostring debug datestr the problem with above is that for months 19 it prints one digit how can i change it to print exactly 2 digits for month date,['javascript'] +149723,onbackpressed to hide not destroy activity i know how to cancel back keypress so that the activity main window stays visiblepublic void onbackpressed return my aim is to hide the activity however without finishing it how do you do that in the onbackpressed event ie i would like to get as far as onpause but not evoke the onbackpressed default behaviour that essentially calls finish another way to put it is that i would like to mimic onuserleavehint any help appreciated,['android'] +149726,how to get the index of an in a possible duplicateshow to get index of li elementjquery get the index of a element with a certain class i haveul idparent li idli1li1li li idli2li2li li idli3li3liulthere are some other ul and li tags elsewhere i want to get the index of li2 which is in the ul with id parent using jquery,"['javascript', 'jquery']" +149734,why is not my transaction escalating to dtc dtc is thisabled on my machine it is my understanding that this code should fail because it uses two data contexts in the same transaction so why does it work note i tried this using net 35 and net 40using transactionscope transactionscope new transactionscope updateeta updatebin transactionscopecompletehere are the dal methods that get calledpublic static void updatebinbin updatedbin using devproddatadatacontext datacontext new devproddatadatacontextconnectionstring binrecord binrecord from bin in datacontextbinrecords where binbinid updatedbinbinid select binfirstordefault binrecordbinid updatedbinbinid binrecordbinname updatedbinbinname datacontextsubmitchanges public static void updateetaeta updatedeta using devproddatadatacontext datacontext new devproddatadatacontextconnectionstring etarecord etarecord from eta in datacontextetarecords where etaid updatedetaid select etafirstordefault etarecordid updatedetaid etarecordtitle updatedetatitle datacontextsubmitchanges,['c#'] +149740,php caching techniques hi this is more of an information request reallyi am currently working on a pretty large event listing website and have started thinking about some caching for the data sets being usedi have been messing with apc this week and have seen some real improvements during testing however what i am struggling to get my head around is best practices and techniques required when trying to cache data that changes frequentlysay for example the user hits the home page this by default thisplays the latest 10 events happening and if that user is logged in those events are location specific is it possible to deploy some kind of caching system when dealing with logged in states and data that changes frequently the system currently allows the user to show more events which is an ajax request to pull extra results from the dbi have not really found anything on this as i am not sure what to search for but i am really interested to know the techniques used for advanced caching systems that deal especially with data that changes and data specific to usersi mean is it even worth it are the other performance boosters when dealing with this sort of criteriaany articles or tips and info on this will be greatly appreciated please let me know if any other info is required,['php'] +149759,how to convert a typecode to an actual type in the code below i get coltype which is a code number for the type but how would i convert that number into the actual type thxfor int j 0 j dvcolumnscount j get the name of the column drvcols dvcolumnsj colname drvcolsrowitemarray3tostring get columns data type code and save it off coltype converttoint32drvcolsrowitemarray11,['c#'] +149763,should not if1 null cause an error int32 struct does not define operator overload method for operator so why does not the code cause compile time errorif1 null,['c#'] +149768,python telling a raw string r from a string i am currently building a tool that will have to match filenames against a pattern for convenience i intend to provide both lazy matching in a globlike fashion and regexp matching for example the following two snippets would eventually have the same effectsmylibrulestatichtmldef myfunc passmylibrulerstatichtmldef myfunc passafaik r is only useful to the python parser and it actually creates a standard str instance after parsing the only difference being that it keeps the is anybody aware of a way to tell one from anotheri would hate to have to provide two alternate decorators for the same purpose or worse resorting manually parsing the string to determine if it is a regexp or not,['python'] +149777,pythons webbrowser launches ie instead of default on windows 7 i am attempting to launch a local html file from python in the default browser right now my default is google chrome if i doubleclick on a html file chrome launcheswhen i use pythons webbrowseropen ie launches instead with a blank address barpython 271 r27186832 nov 27 2010 171903 msc v1500 64 bit amd64 on win32type help copyright credits or license for more information import webbrowser filename testhtml webbrowseropenfilefilenametrue printwebbrowserget class name windowsdefaulti have checked my default programs and they look correct i am on win 7 sp1 why is chrome not launchingupdate the code will be running on unknown oss and machines so registering browsers or path updates are not options i am thinking that parsing the url for file and then doing an ospathexists check and ospathrealpath might be the answer,['python'] +149779,how to use notify and wait can waitnotify be used within one threadi am mean i have a listener and in the moment when that listener gets called i wanna enable a thread to do his workhow could i do thatupdatemy data is written in a databaseand is written each time the listener is callednow the thread that i have created reads that data and sends it somewherenexti get some other data and do the same thingthe other thread needs to know what was the last data he read it so he can start reading from where he lefttake a look in hereusing wait and notify within one threadthis is how my problem looks likethxi have the followingsynchronized synctoken try synctokenwait catch interruptedexception e eprintstacktrace systemoutprintlnmythread sin mythreadso when i domythread t new mythreadsynctokentstarti put my thread on waitingyesand when i do thissynctokennotifyi get my thread back on trackbut the execution of the next line is the one after waiti mean this systemoutprintlnmythread s when you notify a thred does he continues his execution with the line after waitthx,['android'] +149792,can someone explain this code to me i was looking at this question how to implement multiplication without using multiplication operator in net and actually had a lot of fun trying to think of ways to multiply without using but i was left scratching my head at this answer i have no idea what is going on in this code can someone explain it to meusing systemusing systemruntimeinteropservicesdelegate uint binaryopuint a uint bstatic class program dllimportkernel32dll setlasterror true static extern bool virtualprotect intptr address intptr size uint protect out uint oldprotect static void main var bytes intptrsize sizeofint 32bit it is slower btw new byte 0x8b 0x44 0x24 0x04 0x0f 0xaf 0x44 0x24 0x08 0xc3 new byte 0x0f 0xaf 0xca 0x8b 0xc1 0xc3 var handle gchandleallocbytes gchandletypepinned try uint old virtualprotecthandleaddrofpinnedobject intptrbyteslength 0x40 out old var action binaryopmarshalgetdelegateforfunctionpointer handleaddrofpinnedobject typeofbinaryop var temp action3 2 6 finally handlefree credit for this code goes to mehrdad,"['c#', '.net']" +149796,how can you detect the version of a browser i have been searching around for code that would let me detect if the user visiting the website has firefox 3 or 4 all i have found is code to detect the type of browser but not the versionhow can i detect the version of a browser like this,['javascript'] +149809,test existence of json value in javascript array i have an array of json objects like sovar myarray namefoonumber2 namebarnumber9 etchow do i detect if myarray contains an object with namefoo,"['javascript', 'jquery']" +149811,interview question interface implementation could your please help me with following interview questiongiven function aasleepint seconds implement following interface so timers could be usedfunction aavoid createtimervoid func int seconds that her purpose is to create timerfunction avoid starttimers that her purpose to start all the timersevery timer that started should delay for several seconds and then use a callback to call a functionexamplecreatetimerfunc13createtimerfunc27createtimerfunc310starttimersthe folowing should be happeningdelay for 3 seconds and then call for function 1delay for 4 seconds and then call for function 2delay for 3 seconds and then call for function 3the question is how implement such interface,['c++'] +149822,mysql and the chance of the wrong id being returned by last insert id from what i have read last insert id retrieves the id of the last insert statement to run if that the last insert statement run on your connection or the last insert run on the database for all connections i guess what i am trying to ask is on a busy database driven website what are the chances the following code would return the wrong id and is there a method to prevent that other then locking the databaseinsert into example string value somethingselect last insert idwould phps mysql insert id be a better solution or should i just query for data that was just inserted and grab id that way,['mysql'] +149835,dynamically add textviews to a linearlayout i read this somewhere here and i totally lost it but could use some assistancemy app is pulling the column names from sqlite into an array i want to create a textview and edit text for each one via the size of the array and i remember reading somewhere that you can treat the textviews variable names like an array but i do not know where that is nowso how would i dynamically create a textview and edittext for however many listings are in an arrayit was something like textview tv new textviewfortviis this righti appreciate your help,['android'] +149843,repl environment for the web i am looking to find a repl system that can be executed on a web page and that the server can react to is there anything out there i would assume it would have to be using javascriptajax if there is a php implementation it would be even more awesome but for now i am just looking for some kind of an implementation,"['php', 'javascript', 'jquery']" +149852,understanding custom android launcher i want to learn custom android launcheri donot know how to startcan you give me some advicesome blog link or other example and so on,['android'] +149859,boost python and vectors of shared ptr i have read how to expose normal vectors to python in boost python but i want to know how to expose and make use of a vector for instance i have a vector of shared ptrs as followsstdvectorshared ptrstatuseffect effectsbased on the material for exposing vectors i should be able to expose this type of class what i want to know is how can i actually add to it how do i create instances of shared ptrstatuseffect since i do not have access to new and the shared ptr can point to multiple derived types making adding a static creation method to each class a little tediousdoes anyone have some pointers or can suggest how to do this finding good example for boostpython for what i want to do has been abit trickythanks in advance,['c++'] +149860,applying zoom effect in cocos2d gaming environment i am working on a game with cocos2d game engine and make load all the sprites while it load the level now as because some of sprites obstacles are taller than 320 pixel thus it seems difficult to check them out so for the convenience sake i want to apply zoom in and zoom out effect which minimizes entire levels all sprites at once and in zoom out case these will resided to there old positioncan i achieve thisif yes then howplease tell about pinch zoom also,"['iphone', 'objective-c']" +149864,why does this program swap the values i have the following codeinclude stdafxhinclude iostreamusing namespace stdinclude coniohinclude cstringinclude iomanipvoid swaplong a long b long temp tempa ab btempint tmainint argc tchar argv int x 5 y 3 cout x cout y endl swapx y cout x cout y endl getch return 0the program gives the output5 33 5the program actually swaps the values why is that the parameters of the swap are not pointers or referencesi am using vs 2005,['c++'] +149866,increment decrement vs additive subtractive assignment operators thisclaimer i am a rather new programming so this question might be sillyin the past whenever i have wanted to increase or decrease an integer i would use integer or integer however after reading more programming books i have thiscovered the operators and which upon further research i thiscovered are known as the additive and subtractive assignment operatorsobviously the assignment operators are most robust as you can vary the amount that you want to increase or decrease an integer by what i am wondering is are there are any benefits or thisadvantages to using integer vs integer 1,['objective-c'] +149869,what is the pythonic way to calculate dot product i have two lists one is named as a another is named as b each element in a is a triple and each element in b is just an number i would like to calculate the result defined as result a00 b0 a10 b1 an10 bn1i know the logic is easy but how to write in pythonic waythanks,['python'] +149876,about armeabigcc and crosscompiling i have a complicated open source library that needs to be ported to android ndk first i need to configure configure i understand i have to do crosscompile with homeuserandroidndkbuildprebuilt linuxx86armeabi440binarmeabigcc i think right this utility will correctly configures a library if yes then question 2 1i am trying to compile such a library libao use these commands prebuilt homeuserandroidndkbuildprebuiltlinuxx86arm eabi440 platform homeuserandroidndkbuildplatformsandroid3archarm install homeusersox1432com export cc homeuserandroidndkbuildprebuiltlinuxx86arm eabi440binarmeabigcc export cflags fpicdandroid export ldflags wlt prebuilt armeabi lib ldscripts armelfxwlrpathlink platform usr libl platform usr libnostdlib prebuilt libgccarmeabi440crtbegino prebuilt libgccarmeabi440crtendolclmldl configure host arm withgnuld enableshared at the end of the assembly receive the following configure error no 16 bit type found on this platform what could this mean how to fix and properly configure the librarymaybe i can somehow easier you can configure the library,['android'] +149890,why cannot you mix aggregate values and nonaggregate values in a single select i know that if you have one aggregate function in a select statement then all the other values in the statement must be either aggregate functions or listed in a group by clause i do not understand why that is the caseif i doselect name jones as surname from peoplei getname surnamedave jonessusan jonesamy jonesso the dbms has taken a value from each row and appended a single value to it in the result set that is fine but if that works why cannot i doselect name countname as surname from peopleit seems like the same idea take a value from each row and append a single value but instead ofname surnamedave 3susan 3amy 3 i getyou tried to execute a query that does not include the specified expression contactname as part of an aggregate functioni know it is not allowed but the two circumstances seem so similar that i do not understand why is it to make the dbms easier to implement if anyone can explain to me why it does not work like i think it should i would be very grateful,['sql'] +149926,xmlstreamreader not closing opened xml file to use xmlstreamreader i am initializing it like xmlinputfactory f xmlinputfactorynewinstancexmlstreamreader reader fcreatexmlstreamreadernew filereader somefilexmliterating over it like if readerhasnext readernext do something with xml datafinally closing it like readerclosethis looks to be a normal flow but i am seeing some strange behavior even after closing reader os does not allow me deletemove the xml file unless i exit from java program when run on win2k8server i get error message saying javaexe is using this xml fileso i have couple of questions do i need to explicitly close each filereaders closehow can i find out which java code path is keeping this file handle openlooking the documentation of xmlstreamreaders close i get following frees any resources associated with this reader this method does not close the underlying input sourcewhat is the meaning of underlying input sourcewhy is that not closed by readers close,['java'] +149938,uitableview cell background color how to set different background colors for cells in a uitableview specifically rainbow color for seven cells,['iphone'] +149957,difference between initialization of static variables in c and c i was going through the code at includestdiohint initializervoid return 50int main static int i initializer printf value of i d i getchar return 0this code will not compile in c because static variables need to be initialised before main starts that is fine but this code will compile just fine in a c compilermy question is why it compiles in a c compiler when static has the same usage in both languages of course compilers will be different for these languages but i am not able to pin point the exact reason if it is specified in the standard i would love to know thati searched for this question on so found 3 similar links but in vainlink1link2link3thanks for your help,"['c++', 'c']" +149959,css horizonal navigation list items to fill all available spce using css how is it possible to have a horizontal list and have all list items to fill the available width of the parent spacei am floating the lis left and then applying some padding to each but i cannot seem to get the full width filled thus leaving a gap on the right hand sidei could potentially float the last item right but what happens is that the active state of the navigation items would therefore highlight the gap as there is a border applied to the top of the active list item this would show the gap,['css'] +149976,how to execute a shell command through python i am new to python programming i want to execute a shell command at from a python program can any one of the python gurus help me out thanks in advance,['python'] +149984,iselementpresent in selenium 20 hello alli am using webdriver so if i want to use seleniums rc function iselementpresent i have to emulate selenium rc so i do something like thisimport orgopenqaseleniumbyimport orgopenqaseleniumwebdriverimport orgopenqaseleniumwebdriverbackedseleniumimport orgopenqaseleniumwebelementimport orgopenqaseleniumfirefoxfirefoxdriverpublic class new private static void one sec threadsleep40 public static void mainstring args webdriver driver new firefoxdriver drivergetsomething1 selenium selenium new webdriverbackedseleniumdriver something1 seleniumclickhtml one sec systemoutprintlnseleniumiselementpresenttext webdriver driverinstance webdriverbackedselenium seleniumgetwrappeddriver and i always get false as result of iselementpresent and of course element text is on the web which is using gwt,['java'] +149997,visual studio 2010 intellisense and pch what are the alternatives to ugly stdafxh i recently switched to visual studio 2010 and for intellisense not to take half a minute to show up when using boost libraries microsofts suggestion seems to use precompiled headersexcept that i never used them before except when forced to by ugly atl wizards tm so i searched around to figure out how they workbasically the big centralized stdafxh approach seems plain wrong i never want to include even cheaply a whole bunch of header files in all my sources since i do not use windows libraries i make ccli higher level wrappers then use net for talking to the outside world i do not have a whole truckload of nonchanging enormous headers just boost and standard library headers scattered aroundthere is an interesting approach to this problem but i cannot quite figure out how to make this work it seems that each source file must be compiled twice please correct me if i am wrong once with yc and once with yu this adds burden on the developper which must manually tweak the build systemi was hoping to find some automatically generate one precompiled header for each source file trick or at least some best practices but most people seem happy with including the world into stdafxhwhat are the options available to me to use precompiled headers on a per source file basis i do not really care about build times as long as they do not skyrocket i just want intellisense to work fast,['c++'] +150001,razor rendersection within script tags how to insert script from view into template function i am using mvc 3 with the razor view engine and i would like to inject script from my views into one documentreadyfunction function in the master pagei have tried script typetextjavascript documentreadyfunction onload script load area rendersectiondocumentready false scriptin my master and thensection documentready alertin my view but unsuprisingly this does not work is there a simple way to add js code to a master function i may be missing something really simple here my point is that i have a lot of small view control that use the documentready function and i dont want the client page to be littered with these and their accompanying script tagsthanks,['javascript'] +150017,how do you enable a microphone input in the android emulator i have been on a rough ride trying to do something using the speech recognition on an android emulatorhaving finally installed the market place and the google voice search app i am so close to enabling my emulator to do what i want recognize my speech first i need to enable the emulator to record audio or at least think that a microphone is presenti believe adb used to have the mic option however i dont think it exists anymorehas anyone done this or can anyone shed some light on it,"['java', 'android']" +150025,arithmetic operator return type int mainint argc char argv unsigned char a 10 b 100 stdcoutsizeofabendl return 1output 4what is the return data type,['c++'] +150027,what is decltype0 0 prompted by an answergiven n3290 a7162p4 where the list items are unnumbered but numbered here for our conveniencethe type denoted by decltypee is defined as followsif e is an unparenthesized idexpression or an unparenthesized class member access 525 decltypee is the type of the entity named by e if there is no such entity or if e names a set of overloaded functions the program is illformedotherwise if e is an xvalue decltypee is t where t is the type of eotherwise if e is an lvalue decltypee is t where t is the type of eotherwise decltypee is the type of ewhat is the type specified by decltype0 0item 1 does not apply 2 might but if not then 3 does not apply and 4 would be the result so what is an xvalue and is 0 0 an xvaluea310p1an xvalue an aexpiringa value also refers to an object usually near the end of its lifetime so that its resources may be moved for example an xvalue is the result of certain kinds of expressions involving rvalue references 832i do not see anything in a832 that would be helpful here but i do know 0 0 does not involve any rvaluereferences the literal 0 is a prvalue which is an rvalue that is not an xvalue a310p1 i believe 0 0 is also a prvalue if that is true decltype0 0 would be int not inthave i missed something in my interpretation is this code wellformeddecltype0 0 x not initializedthe code compiles on gcc 470 20110427 and clang 29 trunk 126116 it would not be wellformed if the decltype specified an int type for example,['c++'] +150036,python inside gnu screen eventually becomes idle if screen is dettached i have a python script which uses multiprocessing and subprocess to launch multiple external commands in parallel with different arguments the code can be found herefor convenience i launch this script inside a gnu screen session the machine where this script is running has 12 processors which are idle until processes become activeeach of the processes takes between a few hours to a couple of days to run hence i often thisconnect from the machine and detach the screen sessionhowever recently i have noticed a behavior which i never experienced before on several occasions i have returned to the machine to find it idle with a load of zero if i get a list of active processes either via ps ux or top i can still find the script and the subprocesses on the list of processesi then reattach the screen session to check the state of the program and immediately a new batch of processes is sent to the queue and the load of the system goes back to 12 in a matter of seconds note that i did absolutely nothing to the script other than reattaching the screen sessioni have installed a monitoring tool on the system and what happens is that some processes finish after a certain time and no new processes are launched so the system is active until subprocesses are busy and becomes idle as soon as no more jobs are released from the queueso my question is does anyone know of any reason that explains this behavioredit after a year or so this problem is no longer reproducible either some patch on screen or python itself i am accepting the answer as it provided good directions for testing,['python'] +150040,how to do dependency injection in c i am looking for a good technical solution to doing di in c i have seen some of the di questions here already but i have not seen one with any actual examples or concrete implementation suggestions so lets say we have the following situationwe have a set of modules in c we want to refactor those modules so that we can use di to run unit tests and so oneach module effectively consists of a set of c functionsmodule functionmodules depend on each other ie typically you may have a call such asint module1 doitint x int y module2 dosomethingelsex y 2 returnywhat is the correct approach to di for thispossible solutions seem to be1 using function pointers for all module functions and when invoking a function do this or similarint y modulesmodule2dosomethingelsex2 compile multiple libraries mock std etc of with the same symbols and dynamically link in the correct implementation2 seems to be the correct way of doing it but is difficult to configure and annoyingly forces you to build multiple binaries for each unit test1 seems like it might work but at some point your di controller is going to get stuck in a situation where you need to dynamically invoke a generic factory function void factory say with a number of other modules that need to be injected at runtimeis there another better way of doing this in cwhats the right way of doing it,['c'] +150042,how to create a string from string array or arraylist how can i extract all the elements in a string or arraylist and combine all the words with proper formatingwith a single space between them and store in a arraystring a java is cooloutput java is cool,['java'] +150055,dynamically adding to in jquery mobile i am trying to add list items to unordered lists in jquery mobile but the formatting does not seem to be created properlyul datarolelistview datathemec datadividerthemeb li datarolelistdivider title divider li li a hreftesthtml datatransitionslidelist item 1a li ulscriptulappendliahelloalifor some reason the li generated dynamically does not thisplay the same way as the one that is statically created does anyone know why and how i can make it the same,['jquery'] +150076,html comments inside opening tag of the element when i try thisoption thisabled thisabled used to thisable any particular option selected selected used to preselect any particular option label string used to provide a short version of the content in the option value value the actual value that will be send to the server if omitted the content between the option opening and closing tags will be send option 1optioni am trying to comment the attributes and values inside the openning tag of the element however this does not work as browsers tested on ie9 ff401 gg11 af5 and opera11 treat everything followed after the thisabledthisabled as either comment or contentare html comments not allowed inside the opening tag of elements,['html'] +150079,why does proguard keep the oncreate method i am trying to wrap my head around this but i simply do not understand why this is happening as per the default proguardcfg file i define the following rulekeep public class extends androidappactivityas far as i understand this means keep any activity class as an entry point but feel free to shrinkobfuscateoptimize anything inside it otherwise i would have to use eg the methods wildcard to preserve methods too rightnow my test activity looks like thispublic class myactivity extends activity public void oncreatebundle savedinstancestate public void unusedmethod if i now export a signed apk and proguard is invoked it will remove unusedmethod as expected but it will keep the oncreate method and not obfuscate its name why is that,['android'] +150089,removing data from a numpyarray i have a rank1 numpyarray of which i want to make a boxplot however i want to exclude all values equal to zero in the array currently i solved this by looping the array and copy the value to a new array if not equal to zero however as the array consists of 86 0 0 values and i have to do this multiple times this takes a lot of patienceis there a more intelligent way to do this thx in advance,['python'] +150107,call java method from api in net i have a java api in jar file with some dependencies from other jar filesis there any way to call a specific method from this api like using pinvoke from netthank you,"['c#', 'java']" +150125,determine if css attribute is a certain value just wondering how to determine a jquery statement like thisif testcssthisplay block true return truebasically i want to be able to determine if an element has is currently being shown or hidden via the thisplayblock attribute,['jquery'] +150135,nextdouble throws an exception when i enter a double import javautilclass averager public static double unlimited int count 0 double sum 0 scanner scan new scannersystemin whilescanhasnext double d scannextdouble sum d count double ave sumcount return ave public static void mainstring args systemoutprintlnunlimitedn there is no error when i use integers but if i use numbers with point in it a error appears javac averagerjava java averager05exception in thread main javautilinputmismatchexception at javautilscannerthrowforscannerjava840 at javautilscannernextscannerjava1461 at javautilscannernextdoublescannerjava2387 at averagerunlimitedaveragerjava12 at averagermainaveragerjava21to my best understanding 05 should be covered by double if not please can someone correct me,['java'] +150150,calling python functions from inline c with scipyweave can i call a python function from inline c code using weavemotivationi have a bit of code that i would like to optimize and i have identified the bottleneck in one function after my usual tricks i usually turn to scipyweaveinline for optimization unfortunately in this case my function is calling another python function in an inner loop i have made sure that the inner function is not causing the speed issue and i really do not want to have to write it in c as wellminimal examplefrom weave import inlinedef foox return x2def bar a 0 for i in xrange10 a fooi return adef bar weave code int a 0 for int i0i10i a fooi what i would like to do but does not work return val a return inlinecodefooprint barprint bar weave,['python'] +150159,passing data in form submission via jqueryajax i want to submit a form with about 10 input using jqueryajaxbut i do not know how can i pass the data to it through data parameters of ajaxshould i serialize them,['jquery'] +150168,prevent ie6 visitors how can i drop the using of ie6 to browse my website something like if ie6 die i am using aspnet thanks,['asp.net'] +150189,removing content from database security precautions updatei added the csrf protection like berdir told me with the help of the link below to make my application work again however i am not quite sure what i did right now d how is this going to make my app more secure i am particularly bothered by the fact that i am now getting a cookie value in my ajax code because i have to pass it with my ajax call otherwise it just does not work does not this give away some crucial information about the cookie or am i just being paranoid thanksoldhiin this web app i am building i have a functionality to add tips and tricks about certain subjects these pages can be added only by accounts with the admin role however i also want the ability to remove these pages always handy right since i am using codeigniter i was thinking of just making a controller function which takes an id and passes this id to the model where the page corresponding to that id would get deleted from the databasejust to make this clearcontrollerpublic function del contentid thiscontent modeldel contentidmodelpublic function del contentid database code which i cannot be bothered to look up now something like thisdbwhere thisdbdeletethis is all really simple but i am scared that it might be too simple this does not really seem oh so very secure to me is it since you would be able to call the function from the url address bar in your browser you could basically remove the whole content table through that since youd be doing httpmywebsitecontrollerdel content3 for the item with id 3 of course only administrator accounts would have access to that function but stilli have never programmed anything like this before and thus never had to think about the security measures i should take in this case would anyone be kind enough to give me some things i should keep an eye out for and perhaps some ideas suggestions on how to make this more secure thanks a lot,['php'] +150216,php mysql error column count does not match value count at row 1 i am getting this errorcolumn count does not match value count at row 1from the following codename getnamedescription getdescriptionshortdescription getshortdescriptioningredients getingredientsmethod getmethodimage getimageusername getusernamelength getlengthdateadded uk dateconn mysql connectlocalhost dbname passmysql select dbdbnamequery sprintfinsert into dbname id name description shortdescription ingredients method length dateadded username values s s s s s s s mysql real escape stringname mysql real escape stringdescription mysql real escape stringshortdescription mysql real escape stringingredients mysql real escape stringimage mysql real escape stringlength mysql real escape stringdateadded mysql real escape stringusername result mysql queryquery or diemysql errorwhat does the error mean,"['php', 'mysql']" +150229,recursively add sequence of numbers hey im trying to refresh my mind with a bit of recursioni want to add all numbers from start to end inclusiveie if start was 1 and end was 5 then the answer would be 12345 15so far i have got this int calcint start int end ifstart end return total else total total start return sum1start end its not working i get seg fault what am i doing wrongedit sorry i am using the same variables in my actual code when i wrote this i ended up reffering to them as startend and forgot to change all the code,['c'] +150233,is there a way to get the c compiler to emit an error if a switchenum val is missing a case statement i just realized i added a value to the list of musthandle values in my enum but i did not catch it until runtime i know the c compiler is really powerful when it comes to reflection and introspection of types so i was wondering if there was a way to force a switchcase statement to cover all possible enum valuesexampleenum colors red blue green yellowcolors c switch c case colorsred no error red is a color break case colorsblue case colorsgreen no error blue and green handled as well break whoops error colorsyellow unhandled or even error no default and colorsyellow unhandledi want a compiletime solution,['c#'] +150237,how to determine if a object type is a built in system type i am writing a simple listt to csv converter my converter checks the all the ts in list and grabs all public properties and places them into the csvmy code works great as intended when you will use a simple class with a few propertiesi would like to get the listt to csv converter to also accept the system types such as string and integer with these system types i do not want to get their public properties such as length chars etc thus i would like to check if the object is a system type by system type i mean one of the built in net types such as string int32 double etcusing gettype i can find out the followingstring myname joe doebool isprimitive mynamegettypeisprimitive falsebool issealed mynamegettypeissealed true from memory all of the system types are sealedbool isvaluetype mynamegettypeisvaluetype false linqpad users isprimitivedumpissealeddumpisvaluetypedumphow can i find if variable myname is a built in system type assuming we do not know its a string,"['c#', '.net']" +150242,changing googlemaps polygon colorfill on click i have the following code which has been passed on to me and creates polygonsscript typetextjavascriptvar mapfunction initialize var mylatlng new googlemapslatlng3642145710 var myoptions zoom 15 center mylatlng maptypeid googlemapsmaptypeidsatellite map new googlemapsmapdocumentgetelementbyidmap canvas myoptions create polygon overlays from site data in file datajs included above overlays are defined by a set of coordinates we will also be setting up an infowindow with the site name the infowindow will be designed to point to the center of each site so we calculate the centroid of each overlay in the code below as well var overlay var number of overlays 29 for var k 0 k number of overlays k var pk primarykeysk var verticesarray new arrayevalsitevertices pklength 2 var m 0 var centroidlat 0 var centroidlng 0 for var and 0 and evalsitevertices pklength and 2 verticesarraym new googlemapslatlngevalsitevertices pkn evalsitevertices pkn 1 m m 1 centroidlat evalsitevertices pkn centroidlng evalsitevertices pkn 1 var cent new googlemapslatlngcentroidlatm centroidlngm var overlay new googlemapspolygon paths verticesarray strokecolor ff0 strokeopacity 05 strokeweight 1 fillcolor ff0 fillopacity 020 position cent mapmap attachinfowindowoverlay k function attachinfowindowoverlay number var infowindow new googlemapsinfowindow content sitenamesnumber googlemapseventaddlisteneroverlay mouseover function infowindowopenmap overlay googlemapseventaddlisteneroverlay mouseout function infowindowclosemap overlay scriptthe code uses datajs which looks a lot like thisvar primarykeys 1 2 3var sitenames area 1 area 2 area 3var sitevertices 1 3642716187286321 14570407427405 36426678448311414 14570408500657655 3642786542285944 14570926703439332 36428335891385544 14570912755952455var sitevertices 2 3642664391787113 14570415474401094 3642616912275949 14570439077840425 3642733884002687 14570942796693421 36427804995502726 14570927239881135var sitevertices 3 3642611732675347 1457044176004944 3642570295746138 14570467509255982 3642684246769319 14570961035714723 3642730862614943 1457094601534424currently the polygons are created using a red outline and fill i would like to add a behavior so that when the user clicks on a polygon the polygon becomes active and the outline and fill become yellowi am not great at javascript and am not sure how to go about this i know i need to add a listener for click but beyond that i am stuck assistance would be much appreciated mtia,['javascript'] +150244,c determine if an ip address range contains a particular address in c assume that you have an ip address range represented as a string value192168192168230and you also have a single ip address represented as a string value like1921681150what would be the most elegant way to determine if the address range contains the single ip address,['c#'] +150255,is there any free ocr api for net in my project i need to automate a web application which uses captha i read in many thiscussion forums that ocr can be used to solve the problem of captcha so i want to know that can ocr solve my problem if yes then are there any open source ocr apis for net if ocr is not a solution please provide me with some solutionsthank you,['c#'] +150257,javascript image onload why does the onload not get triggered function full imagefimage documentgetelementbyidfull srconload function offsettop documentgetelementbyidfull srcheight 2 offsetleft documentgetelementbyidfull srcwidth 2 documentgetelementbyidfull srcstylemargintopoffsettoppx documentgetelementbyidfull srcstylemarginleftoffsetleftpx documentgetelementbyidfull srcsrcfimage documentgetelementbyidfull viewstylethisplayblock,['javascript'] +150259,search bar cancel button is not working my app is having a search bar for searching records from the table viewwhich is populated by sqlite dbmy problem is that when the view opens the cancel button is not enabled and also i cant touch on that just like a image onlyit is there but no action is with thatwhen we click on that search bar text the cancel button will be changed to done it is enabled oneso here is my codethis is my search bar viewsee that cancel buttonit is not enabled voidsearchbartextdidbegineditinguisearchbar searchbar newsearchbar setshowscancelbuttonyes animatedyes newsearchbarautocapitalizationtype uitextautocapitalizationtypeallcharacters nslogsearch begin edit searchstring searchbartext nslogprint did edit searchstring searchstring foruiview view in searchbar subviews shareitemid newsearchbartext ifview iskindofclassnsclassfromstringuinavigationbutton class uibaritem view settitledone voidsearchbartextdidendeditinguisearchbar searchbar nslogsearchbartextdidendediting searchbar resignfirstresponder self thismissmodalviewcontrolleranimatedyes voidsearchbarsearchbuttonclickeduisearchbar searchbar nslogsearchbarsearchbuttonclicked searchstring searchbartext nslogsearch searchbartext newsearchbar setshowscancelbuttonno animatedyes searchbar resignfirstresponder self thismissmodalviewcontrolleranimatedyes voidsearchbarcancelbuttonclickeduisearchbar searchbar nslog searchbarcancelbuttonclicked searchbar resignfirstresponder shareitemname newsearchbartext self thismissmodalviewcontrolleranimatedyes boolsearchbarshouldbegineditinguisearchbar searchbar nslogsearchbarshouldbeginediting newsearchbar setshowscancelbuttonyes animatedyes return yesthese are my delegates for thatplease check my code and give me the answer i need to enable the cancel button when the view is loaded and it action will be go back to previous viewi need like thisor else how can i add a another cancel button on exciting cancel buttonso that i can enable thatplease give me all the details,"['iphone', 'objective-c']" +150260,sharekit in xcode 4 lots of deprecated i have just loaded the sharekit files into my project which worked nicely otherwise and went to build and run with no code additions as yeti received 11 warnings and 37 errorsis there something i am missing here the warnings are for deprecated functions in the shk filesany ideasusing xcode 4thanks for any assistancekolya,['iphone'] +150271,how to add custom image in navigation bar button item uibarbuttonitem doneitemuibarbuttonitem allocinitwithbarbuttonsystemitemuibarbuttonsystemitemdone targetself actionselectordonepressedautorelease selfnavigationitemrightbarbuttonitemdoneitemthis is the code of my app i need to add a image on this button please help me,"['objective-c', 'iphone']" +150282,check whether activity is active i am having a problem with a listener in a certain activity the problem is that this listener contains an alertshow which can be called after we try to push a new activity which then gives an exceptioneg i am listening in activity a for a signal from an other phone i press back and try to run a new activity b but the program crashes because of the alertshow as listenererrorandroidruntime3573 androidviewwindowmanagerbadtokenexception unable to add window token androidosbinderproxy476c21c0 is not valid is your activity runningcan i check in as listener whether this activity is active and then show the alert or not depending on this value,['android'] +150283,what is the right way to manage multiple ajax requests weve all seen some examples in ajax tutorials where some data is sent they all more or less look likevar http createrequestobject shared between printresult and doajaxfunction createrequestobject if ffsafarichromeie function printresult if httpreadystate 4 function doajax var request someurl httpopenpost request httponreadystatechange printresult data fill in the data httpsenddata trigger doajax from html code by pressing some buttonhere is the scenario i do not understand completely what if the button is being pressed several times very fast should doajax somehow reinitialize the http object and if if the object is reinitialized what happens with the requests that are being already on airps to moderator this question is probably more communitywiki related as stated here if i have got it right please mark this question appropriately,['javascript'] +150329,how to set full control to a directory i am using the following code to set full controldirectorysecurity mydirectorysecurity sourcegetaccesscontrolstring user srinivassadminmydirectorysecurityaddaccessrulenew filesystemaccessrule user filesystemrightsmodify inheritanceflagsobjectinherit propagationflagsinheritonly accesscontroltypeallow sourcesetaccesscontrolmydirectorysecuritybut it is giving special permissions to this folder onlyi want to give full controll permissions to all subfoldersplease anyone can help me,['c#'] +150352,internationalization of dates on the web does anyone have any good architecture for the internationalization of dates like in english its monday chinese a dutch maandag japanese so my first idea is to create some sort of class that stores the strings of monday to sunday in 59 different languages apparently this is not scalable at all imagine now i need to thisplay 1234 am monday 1st jan 20 i will then need another translation for am pm the months both long and short forms the ordinals etc etcit is too much work whats the solution,['javascript'] +150375,net razor engine implementing layouts i am using the following snippet to enable razor templating in my solution outside of aspnet mvc3 is it possible to easily implement layoutsbackground infoi am at this point templates are compiled into compiledtemplateassemblyvar template razortemplatebasetmodel compiledtemplateassembly createinstancerazorspace entrytemplatename templatetemplatemodel modeltemplateexecutevar output templatebuffertostringtemplatebufferclearreturn outputi can imagine having a layout property on my razortemplatebase class but then i understand that htmlpartial is a helper function which i can just implement to parse a template but how do i parse those method calls renderbody or rendersection to accept other razor views,['.net'] +150378,determine cell location in datagridview given a specific row number and column index how can i calculate the cell location ie locationpoint inside a datagridviewthe reason i need the location of the cell is so i can position a button inside the cell to allow for folder browsing the datagridview shows folderpaths alternative suggestions about how to accomplish this welcome,"['c#', '.net']" +150383,iphone image processing with accelerate framework and vdsp update please see additional question below with more codei am trying to code a category for blurring an image my starting point is jeff lamarche is sample here whilst this after the fixes suggested by others works fine it is an order of magnitude too slow for my requirements on a 3gs it takes maybe 3 seconds to do a decent blur and i would like to get this down to under 05 sec for a full screen faster is betterhe mentions the accelerate framework as a performance enhancement so i have spent the last day looking at this and in particular vdsp f3x3 which according to the apple documenation filters an image by performing a twodimensional convolution with a 3x3 kernel single precisionperfect i have a suitable filter matrix and i have an image but this is where i get stumpedvdsp f3x3 assumes image data is float but my image comes fromsrcdata unsigned char cgbitmapcontextgetdata contextand the context comes from cgbitmapcontextcreate with kcgimagealphapremultipliedfirst so my srcdata is really argb with 8 bits per componenti suspect what i really need is a context with float components but according to the quartz documentation here kcgbitmapfloatcomponents is only available on mac os and not ios is there a really fast way using the accelerate framework of converting the integer components i have into the float components that vdsp f3x3 needs i mean i could do it myself but by the time i do that then the convolution and then convert back i suspect i will have made it even slower than it is now since i might as well convolve as i gomaybe i have the wrong approachdoes anyone have some tips for me having done some image processing on the iphone using vdsp the documentation i can find is very reference orientated and not very newbie friendly when it comes to this sort of thingif anyone has a reference for really fast blurring and high quality not the reduce resolution and then rescale stuff i have seen and looks pants that would be fabeditthanks jason i have done this and it is almost working but now my problem is that although the image does blur on every invocation it shifts left 1 pixel it also seems to make the image black and white but that could be something elseis there anything in this code that leaps out as obviously incorrect i have not optimised it yet and it is a bit rough but hopefully the convolution code is clear enoughcgimageref createcgimagebyblurringimagecgimageref inimage nsuinteger pixelradius nsuinteger gaussfactorunsigned char srcdata finaldatacgcontextref context createargbbitmapcontextinimageif context null return nullsize t width cgbitmapcontextgetwidthcontextsize t height cgbitmapcontextgetheightcontextsize t bpr cgbitmapcontextgetbytesperrowcontextint componentsperpixel 4 argbcgrect rect 00widthheight cgcontextdrawimagecontext rect inimage now we can get a pointer to the image data associated with the bitmap contextsrcdata unsigned char cgbitmapcontextgetdata contextif srcdata null size t datasize bpr height finaldata mallocdatasize memcpyfinaldata srcdata datasize generate gaussian kernel float kernel limit the pixelradius pixelradius minmax1pixelradius 248 int kernelsize pixelradius 2 1 kernel mallockernelsize sizeof kernel int gauss sum 0 for int i 0 i pixelradius i kerneli 1 gaussfactori kernelkernelsize i 1 1 gaussfactor i gauss sum kerneli kernelkernelsize i 1 kernelkernelsize 12 1 gaussfactorpixelradius gauss sum kernelkernelsize12 scale the kernel for int i0 ikernelsize i kerneli kerneligauss sum float srcasfloat resultasfloat srcasfloat mallocwidthheightsizeoffloatcomponentsperpixel resultasfloat mallocwidthheightsizeoffloatcomponentsperpixel convert uint source argb to floats vdsp vfltu8srcdata1srcasfloat1widthheightcomponentsperpixel convolve hence the 1 with the kernel vdsp convsrcasfloat 1 kernelkernelsize11 resultasfloat 1 widthheightcomponentsperpixel kernelsize copy the floats back to ints vdsp vfixu8resultasfloat 1 finaldata 1 widthheightcomponentsperpixel freeresultasfloat freesrcasfloatsize t bitmapbytecount bpr heightcgdataproviderref dataprovider cgdataprovidercreatewithdatanull finaldata bitmapbytecount providerreleasecgimageref cgimage cgimagecreatewidth height cgbitmapcontextgetbitspercomponentcontext cgbitmapcontextgetbitsperpixelcontext cgbitmapcontextgetbytesperrowcontext cgbitmapcontextgetcolorspacecontext cgbitmapcontextgetbitmapinfocontext dataprovider null true kcgrenderingintentdefaultcgdataproviderreleasedataprovidercgcontextreleasecontext return cgimagei should add that if i comment out the vdsp conv line and change the line following to vdsp vfixu8srcasfloat 1 finaldata 1 widthheightcomponentsperpixelthen as expected my result is a clone of the original source in colour and not shifted left this implies to me that it is the convolution that is going wrong but i cannot see where thought actually thinking about this it seems to me that the convolve needs to know the input pixels are in argb format as otherwise the convolution will be multiplying the values together with no knowledge about their meaning ie it will multiple r b etc this would explain why i get a bw result i think but not the shift again i think there might need to be more to it than my naive version here final thought i think the shifting left is a natural result of the filter and i need to look at the image dimensions and possibly pad it out so i think the code is actually working ok given what i have fed it,['iphone'] +150390,serialize class to xml i have the follow class and the list that holds itpublic class transport public string transporttype get set public string mode get set public class coordinates public float id get set public float locx get set public float locy get set public float locz get set public objectstate state get set public listint connections new int public enum objectstate fly ground waterpublic static listtransport tracking new listtransporthow do i serialize the tracking to xml i know i can use serializable on the list and serialize it to file but i am not sure on how i define it to be saved as xml,['c#'] +150391,how to create the upload file for application loader when i use application loader i get to the point where it asks me to choose the file to be uploadedif i understand correctly it supposes to be the appnameapp file i see under products on my app bundle i right click it and select show in finder to get to the specific file in library then i am supposed to zip it and the zip file is what i will choose in application loader first am i correct with this assumptionif yeswhat should i define different in xcode than the way i used to build the application for testing on simulator and on my personal iphoneshould i change the infocommandline build use from debug to releasehow should i define the build settingscode signing section in which field should i select the iphone developer option and in which should it be iphone thistributionare there any other important infobuild settingsplistetc fields i should relate toany help will be appreciated,['ios'] +150397,why doesnat my nsmutablearray subclass work as expected i have subclassed nsmutablearray as followsbase classinterface mybasemutablearray nsmutablearray database variables nsstring databasename nsstring databasepathproperty nonatomic retain nsstring databasepath idinitwithcontentsofsqlitedbnsstring dbtablevoid checkandcreatedatabasevoid readfromdatabaseendsubclassinterface ingredientsmutablearray mybasemutablearrayvoid readfromdatabaseendwhen i create an ingredientsmutablearray i do the followingingredientsmutablearray i ingredientsmutablearray alloc initwithcontentsofsqlitedbmyingredientsdbsqlbut when i try to perform the self addobjectingred i throw an exception as follows terminating app due to uncaught exception nsinvalidargumentexception reason nsarray count method only defined for abstract class define ingredientsmutablearray counti believe i am not initializing the nsmutablearray correctly i was going to us initwithcapaciity but i do not know the count before the sql call i think i am overlooking something obvious but being somewhat of a newbie to objective c i am slightly befuddledany help is appreciated,['objective-c'] +150415,making a multiplayer game playable over a network or on the internet hi i have written a multiplayer game in java and i was wondering what i need to learn andor what i should use in order to make the game playable over a network or on the internet by multiple computers i am really kind of clueless as to where to start so any advice would be helpful thanks,['java'] +150421,nsdateformatter setdateformat according to currentlocale i am going mad with probably a stupid problemi have 3 strings year month and day i need to have a date in the right format based on currentlocale so ie if currentlocale localeidentifier is en us my dateformat should bemddyif it is fr fr the dateformat should be ddmyi do not think the only way to do this is to get currentlocale localeidentifier and start with a bunch of if thenthanks in advancemax,['ios'] +150428,setting different replyto message in python emailsmtplib i am using python email and smtplib to send an email from python i am doing this via the gmail smtp server using my gmail credentials this works fine however i would like to specify a replyto email address different from the from address so that replies go to a separate address nongmaili have tried creating a reply to parameter like this msg mimemultipart msgfrom msgto to msgsubject subject msgreplyto but this does not work cannot find any info on this in the python docsthanks,['python'] +150431,android multitouch hack anyone i have to let this slip for now as a purely academic issue but i would very much like to see a solution in near timedue to the way that android handles multitouch you can as i see it only trap the event in a single view i have tried an hack for this envolving a container layout that intercepts the events sees what view it belongs by seeing the coords and changing the action itself so that it seems to the component that it is a single touch event i compose such events and then route it to the viewsdoes anyone have a better idea to do thisif someone wants the code for what i described above just ask and i post ithave fun and good luck djqcorreiapublic class container extends linearlayout linkedhashmapintegerview pointers new linkedhashmapintegerview arraylistview views new arraylistview public containercontext context supercontext initializecontext public containercontext context attributeset attrs supercontext attrs initializecontext private void initializecontext context override public void onlayoutboolean changed int l int t int r int b superonlayoutchanged l t r b views layoututilflattenlayoutthisfalse forview foo views rect rect new rect foogetglobalvisiblerectrect override public boolean onintercepttoucheventmotionevent event return true override public boolean ontoucheventmotionevent event int action eventgetaction motioneventaction mask ifactionmotioneventaction down forview v views rect r new rect vgetglobalvisiblerectr if eventgetx rleft eventgetx rright eventgety rtop eventgety rbottom pointersputeventgetpointerid0v pointersgeteventgetpointerid0ontoucheventevent break ifactionmotioneventaction pointer down int pid eventgetaction motioneventaction pointer id shift int index eventfindpointerindexpid forview v views rect r new rect vgetglobalvisiblerectr if eventgetxindex rleft eventgetxindex rright eventgetyindex rtop eventgetyindex rbottom pointersputpidv motionevent copy motioneventobtainevent copysetactionmotioneventaction down copysetlocationeventgetxindex eventgetyindex pointersgetpidontoucheventcopy ifactionmotioneventaction pointer up int pid eventgetaction motioneventaction pointer id shift int index eventfindpointerindexpid ifpointersgetpidnull if the touch was outside any view motionevent copy motioneventobtainevent copysetactionmotioneventaction up pointersgetpidontoucheventcopy pointersremovepid ifactionmotioneventaction move forint i 0 ieventgetpointercounti int pid eventgetpointeridi motionevent copy motioneventobtainevent copysetlocationeventgetxi eventgetyi ifpointersgetpidnull continue if the touch was outside any view pointersgetpidontoucheventcopy ifactionmotioneventaction up ifpointersgeteventgetpointerid0null pointersgeteventgetpointerid0ontoucheventevent pointersremoveeventgetpointerid0 return true this is the layoututilflattenlayout method public static arraylistview flattenlayoutview view boolean addviewgroups arraylistview viewlist new arraylistview ifview instanceof viewgroup ifviewgroupviewgetchildcount0 viewlistaddview else ifaddviewgroups viewlistaddview viewgroup viewgroup viewgroup view forint i 0 i viewgroupgetchildcounti viewlistaddallflattenlayoutviewgroupgetchildatifalse else ifview instanceof view viewlistaddview return viewlist,['android'] +150432,how to check if insert went well in stored function i am creating a stored function which should insert new row to table in this table is also one unique column how can i check if everything goes well and row really was inserted how can i check exactly that it is this unique column found for example try to add duplicate value,"['mysql', 'sql']" +150441,systemstackoverflowexception was unhandled c net how to fix itit look like this page is dedicated to that kind of error,"['c#', '.net']" +150458,how to use is callable with call i use php 53 which introduces closures because i now have closures available throughout my app and framework i use is callable to see what kind of handler callback isif callback is callable i know enough and use that functionmethodclosure if it is not callable and it is a string it is probably the name of a method in this class it might exist and it might not if i let it up to php it will throw a nice fatal error i like thosebut i want to use mixins which means i need the magic method call call is very cool because it can contains logic before the actual function call but what happens if after call the called method does not exist i can throw an exception sure but we would not know until afterthe problem is now the usefulness of is callable because after implementing call everything will return true because everything has a fallback being callis there a way to have both dynamic methods and useful is callablewhat i would love to see is some sort of cachable magic method is callable that php will consult when is callablearrayobject method is calledon phpnet i cannot find anyone who is as bumbed about this as me this cannot be it if you use call you cannot use is callable anymoream i making any senseps i have looked into method exists but that is just not good enough even if i can filter out all closures and global functions because it will return true for private and protected methods as well as publicediti made a better is callable that checks for mixins but i think it is pretty expensive,['php'] +150465,null pointer exception when calling measure on inflated layout so i have a layout that is a separate file so i inflate it then i change my text views and image in my layout and call measure but i get a null pointer when i try to measure the layout i cannot for the life of me figure out why this is i am trying to convert the layout to a bitmap eventually view inflatedview activitygetcontextgetlayoutinflaterinflaterlayoutmy layout nullinflatedviewmeasuregetwidth getheightinflatedviewlayout0 0 inflatedviewgetmeasuredwidthinflatedviewgetmeasuredheightbitmap viewasimage bitmapcreatebitmapinflatedviewgetwidth inflatedviewgetheight bitmapconfigargb 8canvas viewcanvas new canvasviewasimagehere is the xmlrelativelayout xmlnsandroid androidlayout widthfill parent androidlayout heightwrap content androidlayout gravitybottom androidididmy layout androidbackgroundcolortransparent black imageview androidididimage left androidlayout width48dip androidlayout height48dip androidlayout centerverticaltrue androidlayout alignparentlefttrue androidscaletypefitxy androidmaxwidth48dip androidmaxheight48dip androidpadding5dip imageview androidididimage right androidlayout widthwrap content androidlayout heightwrap content androidlayout marginright20dip androidsrcdrawablearrow androidlayout centerverticaltrue androidscaletypefitxy androidmaxwidth48dip androidmaxheight48dip androidlayout alignparentrighttrue textview androidpaddingleft4dip androidpaddingright1dip androidlayout widthwrap content androidlayout heightwrap content androidlayout torightofidimage left androidlayout toleftofidimage right androidididsome name androidmaxlines1 androidellipsizeend androidtextsize20sp androidtextcolorcolorwhite androidlayout centerverticaltrue androidtextstylenormal relativelayoutat the measure line it throws a null pointer and i have verified that getwidth and getheight are giving legitimate values any ideas thanks,"['java', 'android']" +150466,python default keyword arguments after variable length positional arguments i thought i could use named parameters after variablelength positional parameters in a function call but i get a syntax error when importing a python class i am writing with the following get method for exampleclass fobject def init self print you have created a foo def getselfargsrawfalsevarsnone print lenargs print raw print varsthe error looks likedef getselfargsrawfalsevarsnone syntaxerror invalid syntaxi would like to be able to call the method several waysf foofgetarg1arg2fgetarg1rawtruefgetarg1arg2rawtruevarssomethingetci have rtfm as much as i can but it does not quite click why this would not work thanks in advance for your help j,['python'] +150472,nodejs mysql handling transactions i am building an app on nodejs using express and nodemysql driver there is a couple of cases in my app when i need to make a series of database insertsupdates i want them in a transaction such that if the second or third one fails the previous inserts are rolled back completely currently the way i am doing this is to have some kind of middleware which does a start transaction when a request arrives during the course of processing of the request if any error is thrown i catch this error and do a rollback if no error occurs i do a commit before sending the response to the browserhowever i am now concerned that this would not work when multiple users access the application simultaneously as mysql does a forced commit if another request tries to begin it is own transaction with start transaction i am currently using only a single instance of node and a single mysql connection for all the requestscan someone please advice me if my concerns are valid and how should i get in transactions support,"['javascript', 'mysql']" +150479,android email intent and message body i am using intent to launch email application from my application i set subject short message and email address using the intent everything works fine except that cursor position in the email message section my email message is like thank for choosing do not write below this line i see the message in the email body but my cursor is blinking below the do not write line how can i make the cursor appear before my message so that user can just start to typehere is my code intent emailintent new intentandroidcontentintentaction send emailintentsettypeplaintext emailintentputextraandroidcontentintentextra email new string getresourcesgetstringrstringhelpsenderaddress emailintentputextraandroidcontentintentextra subject getresourcesgetstringrstringhelpsubjectemailintentputextraandroidcontentintentextra text stringformatgetresourcesgetstringrstringhelpmessagebuildversionreleasegetpackagemanagergetpackageinfogetpackagename0versioncode,['android'] +150498,vectorize over the rows of an array i have an array x and i want to apply a function f to all the rows of x silly examplex numpyarray1 2 3 4 5 6 7 8 9 0 idef frow return sumrowy numpyvectorizef irowsxnow y should be array1530 i which method or slicing magic will implement rows in the most efficient way,['python'] +150512,how to implement a listener i have a design issue i need to implement a listener i saw the following so questionhow to create our own listener interface in androidbut in the link it provides in the answer author creates a listener which just extends the systemdefined listener eg onclick you would do some validation then call another method called whenvalidatedlisteneri need to define listeners which are not linked to existing event listeners basically there would be some processing going on in nativecc code in the android code i need a listener to respond to certain messages from iti think i could do this using handlers but asynctask is the recommended approach for multithreading is there a way to implement a userdefinedlistener using asynctask,['android'] +150525,how to cope with refreshing page with js history api pushstate a small website i was creating more like fiddling uses ajax to load each page previously i was changing the hash of the url this worked great but was ugly and the user could refresh the page and it would stay on the same pagenow i have switched to using pushstate in the js history api which looks much better and the back and forward work but refreshing does not for examplegoing to goes to a 404 as there is no real page called page 2 but if i click on the button which uses the pushstate method to change the url it works as it shouldhow can allow refreshes and permalinks with the new history apiand how do search engines treat this seeing as google had to create a way of indexing hash urls by making the developer switch to is it possible they will do something similar for the history api in the future,['javascript'] +150531,when transforming textures drawn as flat 3d objects to mimic depth black lines appear randomly we are developing a topdown rpg using xna recently we bumped into a setback when writing the code to thisplay our maps when drawing the map topdown view with a normal transformation matrix everything seems to be fine when using a nonflat transformation matrix such as squeezing the top or bottom to mimic depth black lines rows when top or bottom column when left or right is squeezed that move around when the camera changes position appear the movement and placement appear to be random image provided further downbackground informationthe maps consist of tiles the original texture has tiles consisting of 32x32 pixels we draw the tiles by creating 2 triangles and thisplaying part of the original texture on these triangles a shader does this for us there are three layers of triangles first we draw all the opaque tiles and all opaque pixels of all semiopaque and partialtransparent tiles then all the semiopaque and partialtransparent tiles and pixels this works fine but when we zoom by a floating point factor sometimes colorblended lines are in between tile rows andor columns renderstateswe use the same rasterizerstate for all tiles and we switch between two when drawing solid or semitransparent tiles rasterizerstate new rasterizerstate rasterizerstatecullmode cullmodecullcounterclockwiseface soliddepthstate new depthstencilstate soliddepthstatedepthbufferenable true soliddepthstatedepthbufferwriteenable true alphadepthstate new depthstencilstate alphadepthstatedepthbufferenable true alphadepthstatedepthbufferwriteenable falsein the shade we set the spriteblendmode as followsthe first solid layer 1 uses alphablendenable false srcblend one destblend zero all the other solid and transparent layers drawn later use alphablendenable true srcblend srcalphadestblend invsrcalpha other shaders use this too the spritebatch for the spritefonts used uses default settinggenerated texturesome tiles are generated on the fly and saved to file the file is loaded when the map is loaded this is done using a rendertarget created as followsrendertarget2d rt new rendertarget2dsbgraphicsdevice 768 1792 false surfaceformatcolor depthformatnone sbgraphicsdevicesetrendertargetrtwhen generated the file is saved and loaded so we do not lose it when the device resets because it no longer will be on a rendertarget i tried using mipmapping but it is a spritesheet there is no information on where tiles are placed so mipmapping is useless and it did not solve the problemverticeswe loop through every position no floating points here yet but position is a vector3 float3for uint16 x 0 x width x for uint16 y 0 y heigth y positionz priority this is a byte 05to position the tiles the following code is usedtilepositionx positionxtilepositiony positiony positionztilepositionz positionzas you know floats are 32 bit with 24 bits for precision the maximum bit value of z is 8 bits 5 0101 the maximum values for x and y are 16 bits resp 24 bits i assumed nothing could go wrong in terms of floating pointsthisposition tilepositionwhen the vertices are set it does so as follows so they all share the same tile positionvector3 offsets new vector3 vector3zero vector3right vector3right thisisvertical vector3forward vector3up thisisvertical vector3forward vector3up vector2 texoffset new vector2 vector2zero vector2unitx vector2one vector2unity for int i 0 i 4 i setvertexout arrstart i arrstart ivertexposition position offsetsi if thistiles0 null arrstart itexturepos1 texoffseti thistiles0texturewidth if thistiles1 null arrstart itexturepos2 texoffseti thistiles1texturewidth if thistiles2 null arrstart itexturepos3 texoffseti thistiles2texturewidthshaderthe shader can draw animated tiles and static tiles both use the following sampler statesampler2d statictilessampler sampler state texture statictiles magfilter point minfilter point mipfilter point addressu clamp addressv clampthe shader does not set any different sampler states we also do not in our code every pass we clip at the alpha value so we do not get black pixels using the following line clipcolora alphaalpha is 1 for solid layer 1 and almost 0 for any other layer this means that if there is a fraction of alpha it will be drawn unless on the bottom layer because we wouldnt know what to do with itcamerawe use a camera to mimic lookup from top down at the tiles making them appear flat using the z value to layer them by external layering data the 3 layers are not always in the right order this also works fine the camera updates the transformation matrix if you are wondering why it has some weird structure like thisaddchange the code is double buffered this also works the transformation matrix is formed as follows first get the position we will be looking at zoom is normally 32single x singlemathroundnewpositionx newshakeoffsetx thiszoom thiszoomsingle y singlemathroundnewpositiony newshakeoffsety thiszoom thiszoom translationmatrix translation matrixcreatetranslationx y 0 projectionmatrix obliqueprojection new matrix1 0 0 0 0 1 1 0 0 1 0 0 0 0 0 1matrix taper matrixidentity base it of center screenmatrix orthographic matrixcreateorthographicoffcenter resolutionx thiszoom 2 resolutionx thiszoom 2 resolutiony thiszoom 2 resolutiony thiszoom 2 10 10 shake rotation this works fine matrix shakerotation matrixcreaterotationz newshakeoffsetz 001 newshakeoffsetz 20 0 projection is used in drawrenderthisaddchange thisprojection translation obliqueprojection orthographic taper shakerotation reasoning and flowthere are 3 layers of tile data each tile is defined by issemitransparent when a tile is issemitransparent it needs to be drawn after something not issemitransparent tile data is stacked when loaded on a splattedtile instance so even if layer one of tile data is empty layer one of the splattedtile will have tile data in the first layer given that at least one layer has tile data the reason is that the zbuffer does not know what to blend with if they are drawn in order since there might be no solid pixels behind it the layers do not have a z value individual tile data has when it is a ground tile it has priority 0 so tiles with the same priority we be ordered on layer draw order and opaqueness semitransparent after opaque tiles with different priority will be drawn according to their prioritythe first solid layer has no destination pixels so i set it to destinationblendzero it also does not need alphablending since there is nothing to alphablend with the other layers 5 2 solid 3 transparent might be drawn when there is already color data and need to blend accordinglybefore iterating through the 6 passes the projection matrix is set when using no taper this works when using a taper it does notthe problemwe want to mimic some more depth by applying the taper using the some matrix we tried several values but this is an examplenew matrix1 0 0 0 0 1 0 01f 0 0 1 0 0 0 0 1the screen everything with height value 0 all flat stuff will be squeezed the lower the y higher on the screen the more it is squeezed this actually works but now random black lines appear almost everywhere it seems to exclude a few tiles but i do not see whats the correlation we think it might had something to do with interpolation or mipmaps and here is an image to show you what i am talking aboutthe tiles not affected seem to be static tiles not on the bottom layer however transparent tiles on top of those show other graphical artifacts they miss lines so rows just get deleted i marked this text because i think it is a hint to whats happening the vertical lines appear if i put the mip mag and minfilter to linearhere is an image zoomed in in game zoom showing the artifact on tiles on layer 2 or 3we already triedmipfilter on point or linear setting generatemipmaps on the original textures setting generatemipmaps on the generated textures true flag constructor of rendertarget turning on mipmapping only gave more artifacts when zoomed out because i was mipmapping a spritesheetnot drawing layer 2 and 3 this actually makes all the tiles have black lines depthbufferenable false setting all solid layers to srcblend one destblend zerosetting all solid layers to scrblend srcalpha destblend invsrcalphanot drawing transparent layer lines are still thereremoving clipopacity in the shader this only removes some lines we are investigating this furthersearching for the same problem on msdn stackoverflow and using google with no luckdoes anyone recognize this problem on a final note we do call the spritebatch after drawing the tiles and use another shader for avatars show no problems because they have height 0 does this undo our sampler state or,['c#'] +150534,in jqgrid can you inline edit mulitple rows at once and then do a single commit we are using the jquerygrideditrow feature of jqgrid that allows you to edit fields in a row inlinedoes jqgrid support inline editing of multiple rows at once where i can make changes on multiple rows and then submit all at oncewe are trying to avoid having to make changes to each row one by one and do a separate round trip to the server to commit each time for cases were we want to bulk edit a number of fields for a number of records and have a single commit,['jquery'] +150538,why is it a security risk to allow encoded slashes in a uri i have a situation where i want encoded slashes in a uri 2f but my htaccess rules are ignored when i make the request sending me instead to a 404 page i quickly found the apache directive allowencodedslashes which i plan to turn on but i still do not understand why it is a security risk in the first place could not anyone manually transform the encoded slashes to real slashes if they were trying to be nefarious although i cannot see what harm they could dothe application i am testing is written in php and the mod rewrite rule that interfaces with it looks likerewritecond request filename frewritecond request filename drewriterule test testphp escaped fragment 1 neqsali just want to make sure i understand the risks before proceedingto clarify apache does not allow encoded slashes in the path but they are allowed in the query string the query string is just as susceptible to the exploits listed by christian below remote code execution local file access and directory traversalso why did the asf go so far as to create a special directive just to allow this behavior i am not trying to be difficult i just really do not understand i think it goes without saying that any user input including the uri needs to be verified before using it in any database or file system function,['php'] +150543,entity framework transaction with multiple threads i have an application running multiple threads the threads do not share an objectcontext each thread has its own i know they are not thread safe however the threads are all operating under a shared transaction the original thread creates a transactionscope and each thread it spawns creates a transactionscope using a dependenttransaction from the transaction on the main threadwhen multiple objectcontext requests run at the same time i sometimes not consistently get the errorsystemdataentityexception occurred messagean error occurred while closing the provider connection see the inner exception for details innerexception systemtransactionstransactionexception messagethe operation is not valid for the state of the transaction sourcesystemtransactions stacktrace at systemtransactionstransactionstatepspeoperationget statusinternaltransaction tx at systemtransactionstransactioninformationget status at systemdataproviderbasedbconnectioninternalcloseconnectiondbconnection owningobject dbconnectionfactory connectionfactory at systemdatasqlclientsqlinternalconnectioncloseconnectiondbconnection owningobject dbconnectionfactory connectionfactory at systemdatasqlclientsqlconnectionclose at systemdataentitycliententityconnectionstoreclosehelper innerexception i only know they are running at the same time because when i run my unit tests in debug mode and this exception pops up if i look at the different threads that are running i always see at least one other thread halted at an objectcontext operationalso after doing some reading i tried adding multipleactiveresultsetsfalse to my connection string and that made no differenceis this a bug in entity framework,['c#'] +150555,common elements in two lists i have two arraylists with 3 integer i want to find a way to return the common elements of the two lists has anynody idea how can i achieve this,['java'] +150562,if not exists in trigger i have tow tables concept access and concept access log i want to create a trigger that works every time something is deleted from concept access check if there is similar record in log table and if not inserts new one before it is deleted from concept accessi modified trigger and now it looks like thisdrop trigger if exists before delete concept accessdelimiter create trigger before delete concept access before delete on concept access for each row begin if select 1 from concept access log where mapoldmap and accesstypeoldaccesstype and startdateoldstartdate and stopdateoldstopdate is null then insert into concept access log map accesstype startdate stopdate values oldmap oldaccesstype oldstartdate oldstopdate end if enddelimiter sample data in concept access before deletemap accesstype startdate stopdate1 public null null 1 loggedin 20110511 null 1 friends null null log table already has first 2 rows and they are exactly the same as in concept access when i delete first row from concept access table i get this in log tablemap accesstype startdate stopdate1 public null null 1 loggedin 20110511 null 1 friends null null 1 public null null while it is not supposed to insert anything because 1publicnullnull already exists therethis table has no primary key i was not creating structure so do not ask me why changing it will ruin a lot of already existing functionality i just need to keep log of what was removed from table concept access and store it in log without duplicatesi would really appreciate if anyone can figure out what is going wrong,"['mysql', 'sql']" +150564,aspnet mvc controller unit testing problem with urlhelper extension trying to do some controller unittesting in my aspnet mvc 3 web applicationmy test goes like thistestmethodpublic void ensure createreviewhttppostaction redirectsappropriately arrange var newreview createmockreview act var result controllercreatenewreview as redirectresult assert assertisnotnullresult redirectresult was not returnedpretty simple basically testing a httppost action to ensure it returns a redirectresult prg pattern i am not using redirecttorouteresult because none of the overloads support anchor links moving onnow i am using moq to mock the http context including server variables controller context session etc all going well so faruntil i have hit this line in my action methodreturn redirecturllandingpagewithanchorsomeobjecturi reviewurilandingpagewithanchor is a custom html helperpublic static string landingpagewithanchorthis urlhelper helper string uri1 string uri2 const string urlformat 01 return stringformaturlformat helperrouteurllanding page new uri uri1 uri2basically i redirect to another page which is a landing page for new content with an anchor on the new review coolnow this method was failing before because urlhelper was nullso i did this in my mockingcontrollerurl new urlhelperfakerequestcontextwhich got it further but now it is failing because the route tables do not contain a definition for landing pageso i know i need to mock something but im not sure if it isa the route tablesb the urlhelperrouteurl methodc the urlhelperlandingpagewithanchor extension method i wrotecan anyone provide some guidanceeditthis particular route is in an area so i tried calling the area registration in my unit testarearegistrationregisterallareasbut i get an invalidoperationexceptionthis method cannot be called during the applications prestart initialization stage,['c#'] +150567,how do i print the size of int in c i am trying to compile the below on rhel 56 64 bit and i keep getting a warning varc7 warning format ada expects type ainta but argument 2 has type along unsigned intahere is my codeinclude stdiohinclude stdlibhint main unsigned int and 10 printfthe size of integer is dn sizeofnit does not matter if i change the declaration for n to following signed int and 10 int and 10 all i want to do is print the size of integer on my machine without really looking into limitsh,['c'] +150568,fastest way to fill an array with a single value i would like to fill a 2d array with a single value that i have however i would like to do it the quickest way possible has the 2d arrays length will be a total of 200k and over time there will be over 200 of these arrays i have looked into bufferblockcopy and arraycopy however they both take in arrays as the sourcedestination where the only array i have is the destination with the source being a single valuewhat is the fastest way to fill in an array with the source being a single value and not an array,['c#'] +150573,cathisplaylink opengl rendering breaks uiscrollview behaviour there are a few similar questions out there on so links at end but none of them has allowed me to fix my problem so here goesi am using opengl rendering to make an image tiling and caching library for use in a game project and i want to hijack the physics of the uiscrollview to allow the user to navigate around the images since it has nice bounce behaviour might as well use it so i have a uiscrollview which i am using to get the rendering view for my textures but there is a problem moving around on the scroll view prevents the cathisplaylink from firing until the user has finished scrolling which looks horrible one temporary fix has been to use nsrunloopcommonmodes instead of the default run mode but unfortunately this breaks some aspects of scroll view behaviour on certain phones i am testing on the 3gs and simulator seem to work fine while the iphone4 and the 3g do notdoes anyone know how i could get around this clash between the cathisplaylink and the uiscrollview or know how to fix the uiscrollview working in other run modes thanks in advance promised links to similar questionsuiscrollview broken and halts scrolling with opengl rendering related cathisplaylink nsrunloopanimation in opengl es view freezes when uiscrollview is dragged on iphone,['iphone'] +150585,python wrapper to access hg git and possibly bazaar repositories i am looking for a python library that can do basic manipulation of repositories but is independent of the backend version control systemby basic manipulation i am referring to initialize a repo add files commit pull push get current revision numberusers of the library could do something thisimport dvcs wrapper as dvcsdvcsset backendhg could choose git bzrrepo dvcsinithomememy reporepoaddhomememy repopyrepocommitinitial commitrepopushprintat revision d reporevision numany pointers to something like the above my google searches turn up nothingupdate for what it is worth i have started working on something like this code is here with unit testsfor hg repositories i might get around to git and bazaar contributions welcome,['python'] +150589,what is rubys threadgroup for i was flicking through the pickaxe looking for the documentation on thread and came across threadgroupthe documentation describes what it does but it does not explain what it is foris a thread group related to a thread pool which i assumed ruby does not have,['ruby'] +150609,android changing nfc settings onoff programmatically i trying to change nfc settings onoff programmatically on android 233on the phone under the wireless network settingsyou can choose to set whether you want to use nfc to read and exchange tags or notso i would like to toggle this setting in my applicationbut i cannot seem to find an api for thisi am looking for some code that would probably look like this wifimanager wifi wifimanager contextgetsystemservicecontextwifi servicewifisetwifienabled onoff,['android'] +150613,can we push notification without using apns is it possible to push notification from my 3rd party server directly to my device in intranetwifi i have achieved to push notification to the device with the help of apns but my requirement to achieve the same without using any external service say my server and my device is connected to an intranet i need to detect the availability of the device in the intranet and send notification directly any idea thanks in advance,['iphone'] +150620,sql server 2008 how to query all databases sizes i have ms sql 2008 r2 500 databaseswhat is the most efficient easiest and modern way to query all databases sizesthe output should have columnsdatabasenamedatafilessizelogfilessize,['sql'] +150684,is there a nicer way to do c named arguments i am trying to implement a flexible debug macrofunction lib and namedoptional arguments seem like the best way to implement the functionsis there a nicer way to do named arguments in c then the followingenum named args nameadressagena sentinelvoid named arg initializersstruct person p enum named args enum named args current name enum named args current arg ifnamed argsnull return current name named args0 current arg named args1 whilecurrent namena sentinel current name2 current arg2 ifcurrent namename pnamecurrent arg else if,['c'] +150718,whats the difference between nil and nil in objective care they really the same thinghow to test that an object is nil,['objective-c'] +150733,implementing a cast operator in a generic abstract class i am trying to be lazy and implement the cast operators in the abstract base class rather than in each of the derived concrete classes i have managed to cast one way but i am unable to cast the other i think it might not be possible but wanted to pick the collective so mind before giving uppublic interface ivaluetypet t value get set public abstract class valuetypet ivaluetypet public abstract t value get set public static explicit operator tvaluetypet vt ifvt null return defaultt return vtvalue public static implicit operator valuetypett val valuetypet vt new valuetypet obviously this would not work as its abstract vtvalue val return vt,['c#'] +150760,ruby version for production i am developing for years with ruby on rails on ruby 187 enterprise edition and there is 192 latest versionwhat benefits can i get using 192 what about encoding support i heard about some issues is it faster is it more stable etcat the moment i am about to start a new project so i am thinking about using 192 in production,"['ruby-on-rails', 'ruby']" +150780,executing asynchronous calls in a synchronous manner i have been trying to wrap my head around this issue for the last hours but cannot figure it out i guess i still have to get used to the functional programming style i wrote a recursive function that traverses through a directory structure and does things to certain files this functions uses the asynchronous io methods now i want to perform some action when this whole traversing is donehow would i make sure that this action is performed after all parse calls have been performed but still use the asynchronous io functionsvar fs requirefs path requirepathfunction parsedir fsreaddirdir function err files if err consoleerrorerr else f filename p path var each function f p return function err stats if err consoleerrorerr else if statsisdirectory parsep else if statsisfile do some stuff var i for i 0 i fileslength i var f filesi var p pathjoindir f fsstatp eachf p parse do some stuff here when async parse completely finished,['javascript'] +150793,jquery notcontains what is the best way to select an element that does not contain a numberegdivnotcontains1notcontains2notcontains3sorry chad i have worded my example wrongi have about 20 divs selected already and need to then filter out the ones that dont contain a number to pass them into a functioni have tried gettin your example to work like ifthisregexhtml 09length 1 but having no luck,['jquery'] +150814,setting a php script as a windows service i need to set up a php script as a windows service i need it to run regardless of which user is logged in and on system start up so it sounds like a windows service is best but am happy to hear other suggestionsthis script runs continuously it is not a run every 5 mins thing i could use the scheduled task manager for covers using the scexe program to install your servicebut from what i have read i need to have a wrapper round the php script to accept the special commands from the windows service manager can anyone help with this,['php'] +150815,how can i change default python version emacs 23 uses trying to change the version of python emacs uses osx106in terminal pythonbrings up the version i have set up in path but in emacs it does nothow can i change this,['python'] +150820,switch from the mainxml layout to another layout i have a basic android question herei have a mainxml layout that loads up when the app is launched this page has a menu button that i would like to when clicked send the user to another layout aboutxmli doubt this is the right when clicked this command is kicked insetcontentviewrlayoutaboutand it seems to work i do see the aboutxml page but i cannot navigate back to the mainxml layout when i hit the back button on my android device the app just closesi doubt that this is the right way to navigate between xml layout files can you please help or point me to a page that spells this out for a computer programmer beginner like myselfthank you very muchpateditthanks for all the answers you helped point me in the right direction in an effort to help future noob programmers like myself to understand activities heres a great simple tutorial that i found online that mapped it out for us beginners,['android'] +150835,c administrator privilege checking i know that there are some similar questions but i want to check only one thingi only want to know if program is running as administratori want to check that because i want to edit some secured filesuser do not have to be administrator i only want to know if my application has rights to edit some secured files that are editable when running as administrator,"['c#', '.net']" +150854,how can a slidingdrawer be animated i try to openclose my slidingdrawer with animateopen and animateclose but it seems it opens and closes instantaneously like open and close whats wrongi have seen that slidingdrawer cannot be customized cannot be animated with custom animation for instance even not with custom openclose duration do i have to copy slidingdrawers code just to change the animation durationthanksprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayouthome open and close banner final slidingdrawer banner slidingdrawer findviewbyidridbanner banneranimateopen handler handler new handler handlerpostdelayednew runnable public void run banneranimateclose 20 editdoingfinal slidingdrawer banner slidingdrawer findviewbyidridbannerfinal animation hidebanner animationutilsloadanimationthis ranimhide bannerbannersetanimationshowbanneranimates the handler only even though i do not do banneranimateopen or bannerstartanimationshowbanner,['android'] +150859,retrieve dll from directory with windsor castle i currently have a pluginfolder folder where i want to copy my custom plugin as dll library every plugin implements my iplugin interfacei want to retrieve them at runtime with windsor castlei have tried something like this without resultscastlecontainerinstance install fromassemblyindirectorynew assemblyfilterpluginfolder castlecontainerinstanceregistercomponentforiplugin iplugin plugin castlecontainerinstanceresolvealliplugin i receive this errortype imageeditorinterfacesiplugin is abstractas such it is not possible to instansiate it as implementation of service imageeditorinterfacesiplugin,['c#'] +150860,dumping c structure sizes from elf object file how can you extract the sizes of all c structures from an elf object file with debugging symbolsindividual struct sizes can be obtained from gdb using print sizeofsome struct but what i need is to get a listing of all structuresi have looked at nm and objdump but i do not see options to do what i am looking for is there a way to do this with standard unix tools or do i need to extract the debug symbol section from the elf file and process it myself i am hoping it is not the latterthanks in advance for any adviceray,['c'] +150862,default substituting s in python scripts sometimes in python scripts i see lines likecmd ss tb cm condlinefsm ucli do swhere is the s in the above line substituted does python have some stack of strings and it pops them and replaces s,['python'] +150878,strange activerecordassociationtypemismatch i am getting a very strange error when running a specfailureerror entity factorycreateentity name test entity creator user activerecordassociationtypemismatch user97318850 expected got user92770800this is the code that results in the above error factory is a factory girl factory user factoryuser username kai email password testing entity factorycreateentity name test entity creator userwhen i use creator userfirst then everything works as expected i printed out userfirst and user but see no differenceany suggestions what the heck is wrong hereupdatei also got this error when running this simple request specdescribe entities do it should succeed do entity factorycreateentity name test entity 1 visit root path end it should also succeed do entity factorycreateentity name test entity 2 property factorycreateproperty entity entity endendthis time i getfailureerror property factorycreateproperty entity entity activerecordassociationtypemismatch entity103620190 expected got entity96047070when i delete visit root path everything works fine also when running each spec on its own it just seems to be a problem for request specs the other specs model controller seems to run fine i use capybara 100beta1 and rspec 25what does this number behind the class name mean,"['ruby-on-rails', 'ruby']" +150885,jsf page redirecting from java bean is there some way how to redirect page to other page from java method i am able only to forward it using facescontextgetcurrentinstancegetexternalcontextthispatchfooxhtmlor using navigationrules of facesconfigxml do you have any ideas,['java'] +150897,how to monkeypatch ruby properly i am trying to monkeypatch a line in net class in the standard library i created a file called patchesrb into the lib folder of the project and added thismodule net class http protocol module httpheader def initialize http headerinitheader header return unless initheader initheadereach do key value headerkeydowncase valuestrip rescue end end end endendbut it does not work am i doing this right that parallels the inheritance hierarchy exactlyedit part of the problem was i had to put the file in the initalizers folder but still seeing the same error,['ruby'] +150900,using git to manage virtualenv state will this cause problems i currently have git and virtualenv set up in a way which exactlysuits my needs and so far has not caused any problems however i am aware thatmy setup is nonstandard and i am wondering if anyone more familiar with virtualenvsinternals can point out if and where it is likely to go wrongmy setupmy virtualenv is inside my git repository but git is set to ignore the bin and include directories and everything in lib except for the sitepackages directorymore precisely my gitignore file looks like thispyc ignore all the virtualenv stuff except the actual packages themselvesbinincludelibpythonlibpythonsitepackages ignore easyinstall and setuptoolslibpythonsitepackageseasyinstallpthlibpythonsitepackagessetuptoolspthlibpythonsitepackagessetuptoolslibpythonsitepackagespipwith this arrangement i and anyone else working on a checkout of the project can use virtualenv and pip as normal but with the following advantages if anyone updates or installs a package and pushes their changes anyone else who pulls those changes automatically gets the update they do not need to notice that a requirementstxt file has changed or do any postreceive hook magicthere are no network dependencies all the code to make the application work lives in the git repositoryi am aware that this only works with purepython packages but that is all i am concerned with at the momentdoes anyone know of any other problems with this approach that i should be aware of,['python'] +150923,how to select first 10 words of a sentence how do i from an output only select the first 10 words,['php'] +150945,doctrine 2 mysql field function in order by i am trying to use the mysql field function in an order by clause in a query i am assuming that doctrine 2 does not support the field function out of the box is that true if so how can i use it will i have to turn my whole query into a native query is there a doctrine 2 extension that adds this functionality,['mysql'] +150948,convert structured array to regular numpy array the answer will be very obvious i think but i do not see it at the moment how can i convert a record array back to a regular ndarraysuppose i have following simple structured arrayx nparray10 40 20 10 dtypef0 f8 f1 f8then i want to convert it toarray 1 4 2 1i tried asarray and astype but that did not workupdate solved float32 f4 instead of float64 f8ok i tried the solution of robert xviewnpfloat64reshapexshape 1 and with a simple array it works perfectly but with the array i wanted to convert it gives a strange outcomedata nparray 0014793682843446732 06681123282760382 00 00 00 08984912419691682 00 0013475529849529266 00 00 0014793682843446732 06681123282760382 00 00 00 08984912419691682 00 0013475529849529266 00 00 0014776384457945824 06656022742390633 00 00 00 08901208057068288 00 0013350814580917358 00 00 0011928378604352474 02819152781739831 00 00 00 012627150863409042 00 0018906937912106514 00 00 0011928378604352474 02819152781739831 00 00 00 01259754877537489 00 001886274479329586 00 00 00119691959631443 0287067401288465 00 00 00 07433745195157826 00 00164642870426178 00 00 dtypea soil f4 b soil f4 ea v f4 kcc f4 koc f4 lmax f4 malfarquhar f4 mrn f4 tcc f4 vcmax 3 f4and thendata array dataviewnpfloatreshapedatashape 1givesin 8 data arrayout8 array 228080997e20 0e00 278023241e27 624133580e18 0e00 228080997e20 0e00 278023241e27 624133580e18 0e00 2214197e20 0e00 255866881e27 579825816e18 0e00 204776835e23 0e00 347457730e26 932782857e17 0e00 204776835e23 0e00 341189244e26 9202417e17 0e00 232706550e23 0e00 476375305e28 124257748e18 0e00wich is an array with other numbers and another shape what did i do wrong,['python'] +150951,jquery validate dropdown required if field empty i am trying to make the dropdown required if the category field is emptythanksjquery attempt 1uploaddocsformvalidate rules name required true minlength 2 maxlength 255 cat id required functionelement return categoryval messages name please enter a bdocument nameb cat id please select a bcategoryb jquery attempt 2uploaddocsformvalidate rules name required true minlength 2 maxlength 255 cat id required depends functionelement return categoryval messages name please enter a bdocument nameb cat id please select a bcategoryb htmlform nameuploaddocsform iduploaddocsform label fornamedocument namelabel input namename idname typetext classtextbox label forcat idcategorylabel select namecat id idcat id classdropdown option selectedplease select categoryoption optionoption option value1test catoption select label forcategorynew categorylabel input namecategory idcategory typetext classtextbox form,['jquery'] +150953,matlabstyle find function in python in matlab it is easy to find the indices of values that meet a particular condition a 123123123 finda 2 find the indecies where this condition is true3 6 9 matlab uses 1based indexing afinda 2 get the values at those locations3 3 3what would be the best way to do this in pythonso far i have come up with the following to just get the values a 123123123 val for val in a if val 23 3 3but if i want the index of each of those values it is a bit more complicated a 123123123 inds i for i val in enumeratea if val 2 inds2 5 8 val for i val in enumeratea if i in inds3 3 3is there a better way to do this in python especially for arbitrary conditions not just val 2i found functions equivalent to matlab find in numpy but i currently do not have access to those libraries,['python'] +150962,if javascript interpreter does jit compilation does it cache results of it for use on the same script next time i load the website to make it more specific i mostly care about spidermonkey interpreter in firefoxso suppose i want to speed up the loading of a particular website in my browser or else speed up loading of all websites that have some popular script eg jquery presumably the scripts involved do not change between the page reloads will seamonkey understand that much and avoid full recompilationif spidermonkey wouldnt will any other interpreter or is this basically a potential new feature which nobody cares about since computers are fast as is,['javascript'] +150973,is it okay to include markup after the closing tag since closing the html tag is optional is it okay to include markup after a closing html tagan example of this exists with phil haacks routedebugger library some sample output looks like thisdoctype htmlhtmlhead titleindextitle link hrefcontentsitecss relstylesheet typetextcss script srcscriptsjquery144minjs typetextjavascriptscriptheadbodyh2indexh2bodyhtml extra content after closing html tag htmldiv idhaackroutedebugger stylebackgroundcolor f style haackroutedebugger haackroutedebugger td haackroutedebugger th backgroundcolor f fontfamily verdana helvetica sanserif fontsize small haackroutedebugger trheader td haackroutedebugger trheader th backgroundcolor ffc style hr stylewidth 100 border solid 1px 0 margin0 padding0 h1 stylemargin 0 padding 4px borderbottom solid 1px b paddingleft 10px fontsize 12em backgroundcolor ffcroute debuggerh1 div idmain stylemargintop0 paddingtop0 p stylefontsize 9em paddingtop0 type in a url in the address bar to see which defined routes match it a catchall route is added to the list of routes automatically in case none of your routes match p p stylefontsize 9em to generate urls using routing supply route values via the query string example codehttplocalhost14230id123code p plabel stylefontweight bold fontsize 11emmatched routelabel controlleractionidp div stylefloat left table border1 cellpadding3 cellspacing0 width300 caption stylefontweight boldroute datacaption tr classheaderthkeyththvaluethtr trtdcontrollertdtdhomenbsptdtr trtdactiontdtdindexnbsptdtr table div div stylefloat left marginleft 10px table border1 cellpadding3 cellspacing0 width300 caption stylefontweight bolddata tokenscaption tr classheaderthkeyththvaluethtr table div hr styleclear both table border1 cellpadding3 cellspacing0 caption stylefontweight boldall routescaption tr classheader thmatches current requestth thurlth thdefaultsth thconstraintsth thdatatokensth tr trtdspan stylecolor c00falsespantdtdresourceaxdpathinfotdtdnulltdtdemptytdtdnulltdtrtrtdspan stylecolor 0c0truespantdtdcontrolleractionidtdtdcontroller home action index id urlparameteroptionaltdtdemptytdtdemptytdtrtrtdspan stylecolor 0c0truespantdtdcatchalltdtdnulltdtdnulltdtdnulltdtr table hr h3current request infoh3 p apprelativecurrentexecutionfilepath is the portion of the request that routing acts on p pstrongapprelativecurrentexecutionfilepathstrong p divdivi notice that his appended markup begins with an html tag does the presence of this tag somehow validate the location of this content,['html'] +150980,devise and user registration requiring admin approval i would like to implement the following registration system user signs up and is redirectedto a thank you for signing up pageis not sent an email and cannot yet log inadmin logs in and sees list of newly registered but as yet unapproved users admin edits user details and clicks approved which then sends email with password to new userhow can i do this with devise,['ruby-on-rails'] +150987,android mkdir not making folder tonight i am currently having issues doing something that i thought would be simple making a folder in mntsdcardi have set the follow permissionusespermission androidnameandroidpermissionwrite external storageusespermissionmy mainjava has the following to make the folderpublic class main extends tabactivity static int index 1 private static final string tag main public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain file folder new fileenvironmentgetexternalstoragedirectory tallgrassimages boolean success false iffolderexists success foldermkdir if success logdtagfolder not created else logdtagfolder created i get the folder created message in my log but when i check both mntsdcard and sdcard neither one has the folder i have tried callingenvironmentmedia mountedequalsenvironmentgetexternalstoragestateand it returns true i just cannot figure this one out because all signs are pointing that it should work i have also tried it with the phone thisconnected from the pc in case the sd card was mounting or something as i am currently using my phone instead of the emulator for developing speaking of which does debuggable to true maybe prevent it from making the folderthanks,['android'] +151013,how to add core data to my exisiting ios project in xcode possible duplicateadding core data to existing iphone project in my existing ios project in xcode there is no core datai need to add core data back to the project how to do that thanks,"['iphone', 'ios']" +151018,programatically set height on layoutparams as densityindependent pixels is there any way to set the heightwidth of a layoutparams as densityindependent pixels dp it looks like the heightwidth when set programatically are in pixels and not dp,['android'] +151023,iphone uitableview cellaccessory checkmark in iphone app on click of table view cell i want to thisplay table view cell accessory type check mark for that on didselectrowatindexpath i am writing codeifindexpathrow 0tableview cellforrowatindexpathindexpathaccessorytypeuitableviewcellaccessorycheckmark and thisplaying check marksbut in my case i wnt to allow user to check only on cell at a time means if user select other row then that row should checked and previously checked should be uncheckedhow can i achieve that,"['iphone', 'objective-c']" +151035,how to extend nstextstorage according to documentation i try to subclass nstextstorage and use it in text view nstextstorage is a semiabstract subclass of nsmutableattributedstring it implements change management begineditingendediting verification of attributes delegate handling and layout management notification the one aspect it does not implement is the actual attributed string storage this is left up to the subclassers which need to override the two nsmutableattributedstring primitives voidreplacecharactersinrangensrangerange withstringnsstring str voidsetattributesnsdictionary attrs rangensrangerangeso i try to use delegate to handle all needed events with same functionalityimplementation mytextstorage id init self super init if self nil storage nsmutableattributedstring alloc init return self void dealloc storage release super dealloc nsstring string return storage string void replacecharactersinrangensrangerange withstringnsstring str storage replacecharactersinrangerange withstringstr voidsetattributesnsdictionary attrs rangensrangerange storage setattributesattrs rangerangeendit is no matter what i am use as delegate nstextstorage or nsmutableattributedstring the result is the samean uncaught exception was raised nsrunstorage nsblocknumberforindex index 18446744073709551615 beyond array bounds 0 terminating app due to uncaught exception nsrangeexception reason nsrunstorage nsblocknumberforindex index 18446744073709551615 beyond array bounds 0stack trace0 corefoundation 0x07f840cd7b4 exceptionpreprocess 180 1 libobjcadylib 0x07f885390f3 objc exception throw 45 2 corefoundation 0x07f840cd5d7 nsexception raiseformatarguments 103 3 corefoundation 0x07f840cd564 nsexception raiseformat 148 4 appkit 0x07f86cc6288 nsblocknumberforindex 86 5 appkit 0x07f86cc71d5 nslayoutmanager textcontainerforglyphatindexeffectiverange 364 6 appkit 0x07f86d1f121 nstextviewnssharing didchangetext 340 7 appkit 0x07f86d44b68 nstextview inserttextreplacementrange 2763 8 cocoacalculator 0x0102312 calctextview inserttext 65 9 cocoacalculator 0x01027ac calctextcontainer initwithframe 1176 10 appkit 0x07f86c23d44 nscustomview nibinstantiate 646 11 appkit 0x07f86b7be17 nsibobjectdata instantiateobject 259 12 appkit 0x07f86b7b202 nsibobjectdata nibinstantiatewithownertoplevelobjects 336 13 appkit 0x07f86b7988d loadnib 226 14 appkit 0x07f86b78d9a nsbundlensnibloading loadnibfilenametablewithzoneownerbundletermination start when i try to call textview inserttext123but in standard nstextstorage version all works properlywhat i need to do to extend this class,['objective-c'] +151037,convert text into number in mysql query is it possible to convert text into number within mysql query i have a column with an identifier that consists a name and a number in the format of namenumber the column has varchar type i want to sort the rows according the number rows with the same name but the column is sorted according do character order iename1name11name12name2if i cut of the number can i convert the varchar number into the real number and use it to sort the rows i would like to obtained following ordername1name2name11name12i cannot represent the number as a separate columnedited 20110511 932i have found following solution order by column 1 if the name will not contain any numbers is it save to use that solution,"['mysql', 'sql']" +151045,javascript sign concatenates instead of giving sum of variables why when i use this assuming i1divid question i1i get question11 and not question2,['javascript'] +151053,adding attributes to customer entity my current goal is to add a new customer attribute with int type which should appear as select with predefined options loaded from a model with entries editable in backend which is donei am struggling with proper use of installeraddattribute method especially specifying correct source option other problem is the new attribute is not saved to eav entity attribute tablei am on magento ce 1510,['php'] +151055,possible bug in c jit optimizer working on a sqlhelper class to automate stored procedures calls in a similar way to what is done in the xmlrpcnet library i have hit a very strange problem when running a method generated manually from il code i have narrowed it down to a simple generated method probably it could be simplified even more i create a new assembly and type containing two methods to comply with public interface itestdecimal void testokref decimal value void testwrongref decimal valuethe test methods are just loading the decimal argument into the stack boxing it checking if it is null and if it is not unboxing itthe generation of testok method is as followsstatic void buildmethodoktypebuilder tb create a method builder methodbuilder mthdbldr tbdefinemethod testok methodattributespublic methodattributesvirtual typeofvoid new type typeofdecimalmakebyreftype parameterbuilder parambldr mthdbldrdefineparameter1 parameterattributesin parameterattributesout value generate il ilgenerator ilgen mthdbldrgetilgenerator load argument to stack and box the decimal value ilgenemitopcodesldarg 1 ilgenemitopcodesdup ilgenemitopcodesldobj typeofdecimal ilgenemitopcodesbox typeofdecimal some things were done in here invoking other method etc at the top of the stack we should have a boxed t or null copy reference values out skip unboxing if value in the stack is null label valisnotnull ilgendefinelabel ilgenemitopcodesdup this block works ilgenemitopcodesbrtrue valisnotnull ilgenemitopcodespop ilgenemitopcodespop ilgenemitopcodesret end block ilgenmarklabelvalisnotnull ilgenemitopcodesunbox any typeofdecimal just clean the stack ilgenemitopcodespop ilgenemitopcodespop ilgenemitopcodesretthe building for testwrong is nearly identicalstatic void buildmethodwrongtypebuilder tb create a method builder methodbuilder mthdbldr tbdefinemethodtestwrong methodattributespublic methodattributesvirtual typeofvoid new type typeofdecimalmakebyreftype parameterbuilder parambldr mthdbldrdefineparameter1 parameterattributesin parameterattributesout value generate il ilgenerator ilgen mthdbldrgetilgenerator load argument to stack and box the decimal value ilgenemitopcodesldarg 1 ilgenemitopcodesdup ilgenemitopcodesldobj typeofdecimal ilgenemitopcodesbox typeofdecimal some things were done in here invoking other method etc at the top of the stack we should have a boxed decimal or null copy reference values out skip unboxing if value in the stack is null label valisnull ilgendefinelabel ilgenemitopcodesdup this block fails ilgenemitopcodesbrfalse valisnull end block ilgenemitopcodesunbox any typeofdecimal ilgenmarklabelvalisnull just clean the stack ilgenemitopcodespop ilgenemitopcodespop ilgenemitopcodesretthe only difference is i am using brfalse instead of brtrue to check if the value in the stack is nullnow running the following codeitestdecimal testiface itestdecimalsimplecodegencreatedecimal dectest 1testifacetestokref dectestconsolewriteline dectest dectesttostringthe simplecodegencreate is creating a new assembly and type and calling the buildmethodxx above to generate the code for testok and testwrongthis works as expected does nothing value of dectest is not changed however runningitestdecimal testiface itestdecimalsimplecodegencreatedecimal dectest 1testifacetestwrongref dectestconsolewriteline dectest dectesttostringthe value of dectest is corrupted sometimes it gets a big value sometimes it says invalid decimal value and the program crashesmay this be a bug in the jit or am i doing something wrongsome hintsin debugger it happens only when suppress jit optimizations is thisabled if suppress jit optimizations is enabled it works this makes me think the problem must be in the jit optimized coderunning the same test on mono 246 it works as expected so this is something specific for microsoft netproblem appears when using datetime or decimal types apparently it works for int or for reference types for reference types the generated code is not identical but i am omiting that case as it worksi think this link reported long time ago might be relatedi have tried net framework v20 v30 v35 and v4 and behavior is exactly the samei am omitting the rest of the code creating the assembly and type if you want the full code just ask methanks very muchedit i am including the rest of the assembly and type creation code for completionclass simplecodegen public static object create type proxytype guid guid guidnewguid string assemblyname testtype guidtostring string modulename testtype guidtostring dll string typename testtype guidtostring build the new type assemblybuilder assbldr buildassemblytypeofitestdecimal assemblyname modulename typename proxytype assbldrgettypetypename create an instance return activatorcreateinstanceproxytype static assemblybuilder buildassemblytype itf string assemblyname string modulename string typename create a new type assemblyname assname new assemblyname assnamename assemblyname assnameversion itfassemblygetnameversion assemblybuilder assbldr appdomaincurrentdomaindefinedynamicassemblyassname assemblybuilderaccessrunandsave modulebuilder modbldr assbldrdefinedynamicmoduleassnamename modulename typebuilder typebldr modbldrdefinetypetypename typeattributesclass typeattributessealed typeattributespublic typeofobject new type itf buildconstructortypebldr typeofobject buildmethodoktypebldr buildmethodwrongtypebldr typebldrcreatetype return assbldr private static void buildconstructortypebuilder typebldr type basetype constructorbuilder ctorbldr typebldrdefineconstructor methodattributespublic methodattributesspecialname methodattributesrtspecialname methodattributeshidebysig callingconventionsstandard typeemptytypes ilgenerator ilgen ctorbldrgetilgenerator call the base constructor ilgenemitopcodesldarg 0 constructorinfo ctorinfo basetypegetconstructorsystemtypeemptytypes ilgenemitopcodescall ctorinfo ilgenemitopcodesret static void buildmethodoktypebuilder tb code included in examples above static void buildmethodwrongtypebuilder tb code included in examples above,"['c#', '.net']" +151058,java read values from text file i am new to java i have one text file with below contenttrace structure list a structurec0748701024380202272210752231026180263976119737022047025840835411 b structurec140190486955012714406427780379787010524910063061308301657030695775 now what i want is i need to get a and b as two different array list,['java'] +151073,access a derived private member function from a base class pointer to a derived object possible duplicatewhy can i access a derived private member function via a base class pointer to a derived object include iostreamusing namespace stdclass b public virtual void fn1void cout class b fn one n virtual void fn2void cout class b fn two n class d public b void fn1void cout class d fn one n private void fn2void cout class d fn two n int mainvoid b p new d pfn1 pfn2why does pfn2 call the derived class function even though fn2 is private in d,['c++'] +151086,error message unexpected termination of script debugging ended when debugging php with xdebug and eclipse i am getting the following error when debuggingphpini settings xdebugremote enabletrue xdebugremote hostlocalhost xdebugremote port90 xdebugremote handlerdbgp,['php'] +151117,python option parser boolean flag with optional parameters i am using optparseoptionparser to manage arguments for some scripts and something i was wondering would like to do is have boolean flags ie actionstore true that can also accept a parameterto put this into context i have got a application that can use as many gpuprocessors as it finds on the machine for a variety of reasons sometimes you want to limit the number of devices it uses and instead of further cluttering the command line i would like to be able toscript c gmeaning use all you can of all cpus and gpus and script c 2 g 3meaning limit the script execution to 2 cpus and 3 gpus after reading the optparse documentation i am none the wiser oh great so gurus lend me your wisdom,['python'] +151120,how can i cast or convert boost bind to c function pointer suppose i have thisvoid funcwchar pythonstatement do something with pythonstatementand i need to convert it to void functionvoid like thisbindfunc textconsolewritetestnow i have struct like thistypedef void cdecl pfuncplugincmdstruct funcitem pfuncplugincmd pfunc how can i set the pfunc of my struct to bindfunc something bind returns lambda functor not a function pointer so how can i cast this functor to function pointerthanksended up using the wrapping solution github,['c++'] +151136,how to force instantiation of static fields i was quite surprised of the output of the following codecountry classpublic class country private static mapstring country countries new hashmapstring country private final string name suppresswarningsleakingthisinconstructor protected countrystring name thisname name registerthis get country by name public static country getcountrystring name return countriesgetname register country into map public static void registercountry country countriesputcountryname country override public string tostring return name countries in europe public static class europecountry extends country public static final europecountry spain new europecountryspain public static final europecountry france new europecountryfrance protected europecountrystring name supername main methodsystemoutprintlncountrygetcountryspainoutputnullis there any clean way of forcing the class that extend country to be loaded so the countries map contains all the country instances,['java'] +151167,does php have autovivification searching phpnet for autovivification gives no results at the time of writing wikipedia claims that only perl has it there are no clearly definitive results when searching google for php autovivification this php code runs finetesta46b hello worldvar dumptestarray a array 4 array b array can anyone provide a canonical answer preferably with references that php does have this feature and any details such as the version it was introduced in quirks shortcuts etc,['php'] +151195,client side validation with dynamically added field i am using jquerys unobtrusive validation plugin in with aspnet mvc the problem is that all the fields that are rendered server side gets validated with this scheme but if i dynamically add a field in the form using javascript it is not validated despite adding html5 data attributes to the field can anyone guide me in right direction on how i can achieve this goalthanksadeel,['jquery'] +151196,onetoone association in form in symfony 20 how to create a drop down list using onetoone association in form can you guys put good example please,['php'] +151219,rails 3 and heroku automatically rake dbmigrate on push i have a slight annoyance with my heroku pushdeploy process which otherwise has been a joy to thiscover and use if i add a new migration to my app the only way i can get it up onto the heroku server is to do a push to the heroku remote this uploads it and restarts the app but it does not run the migration so i have to do heroku rake dbmigrate app myapp then heroku restart app myapp in the meantime the app is broken because it has not run the migrations and the code is referring to fieldstables etc in the migrationthere must be a way to change the deployment process to run the rake dbmigrate automatically as part of the deploy process but i cannot work it out is it something i set in a heroku cpanel is it an option i pass to heroku from the command line is it a git hook can anyone set me straight thanks max,['ruby-on-rails'] +151227,how to change a nullable column to not nullable in a rails migration i created a date column in a previous migration and set it to be nullable now i want to change it to be not nullable how do i go about doing this assuming there are null rows in that database i am ok with setting those columns to timenow if they are currently null,['ruby-on-rails'] +151230,generate unique random string with letters and numbers in lower case how can i fix this code so it generates unique random letters and numbers in lower caseapi string 032map65rand25chrjoin at the moment it generates only letters,['ruby'] +151235,mysql select one column thistinct with corresponding other columns id firstname lastname1 john doe2 bugs bunny3 john johnsoni want to select thistinct results from the firstname column but i need the corresponding id and lastnamethe result set needs to show only one john but with an id of 1 and a lastname of doe,['mysql'] +151240,ie equivalent for gm setvalue and gm getvalue greasemonkey storage i have made a script that runs with no glitch on firefox i am retrieving some data from external domain in an iframe to insert them in the page by using setintervali have tried to use trixie so that it runs in ie but it seems that functions gm getvalue and gm setvalue were not definedi have added these replacement functions based on cookies but i cannot get it to work in a crossdomain way the cookie is created and the data stored but it is only accessible from the iframe not from the top document here is the basic structure i used in test i have access to the value stored with gm getvaluedestination but it does not work inside function check1 is there a way to make the cookie crossdomain2 are there other ways to store data in ie in a crossdomain way i have briefly heard of flash objects but it does not seem quite a light solution other implementations of these functions getvalue and setvalue are quite hard to find3 i am using trixie maybe it is not the best solution any advice on what plugin i should better use to have those functions,['javascript'] +151249,how to correctly sort a string with a number inside possible duplicatedoes python have a built in function for string natural sort i have a list of strings containing numbers and i cannot find a good way to sort themfor example i get something like thatsomething1something12something17something2something25something29with sort methodi know that i probably need to extract numbers somehow and then sort the list but i have no idea how to do it in the most simple way,['python'] +151262,sql parentheses use in an or clause was wondering whether anyone would know why do we use the parentheses in this sqlso the format goes as followsnamelocation and department of the service of the employees whose name starts with a or b a rough translation from frenchi answered the following wayselect servicenom serv localiteville localitedepartemenfrom service localite employewhere servicecode loclocalitecode locand employeserviceservicecode servand employenom like a or employenom like bbasically where the last and is concerned for the where could not i simply do without the parenthesis in order to have the sql select for me employees with their name starting either with an a or a b what difference does positioning a parenthesis in that way make and ahy is there a double use of parentheses or is it to prioritize the or in the last clause since an and is preceding it,['sql'] +151291,handle null parameters while calling a method using reflection i am trying to write code that will infer types from a parameter list and then call the method that matches those parameters this works very well except when the parameter list has a null value in iti am wondering how i might cause the typegetmethod call to match a functionoverload even with a null parameter in the parameters listobject callmethodreflectionobject o string namemethod params object args try var types typesfromobjectsargs var themethod ogettypegetmethodnamemethod types return themethod null null themethodinvokeo args catch exception ex return null type typesfromobjectsparams object pparams var types new listtype foreach var param in pparams typesaddparam null null paramgettype return typestoarraythe main problem line is the typesaddparam null null paramgettype which will cause the getmethod call to fail with a null value in the types arrayvoid function1string arg1 void function1string arg1 string arg2 void function1string arg1 string arg2 string arg3 void function2string arg1 void function2string arg1 int arg2 void function2string arg1 string arg2 1 callmethodreflectionobj function1 string string this works2 callmethodreflectionobj function1 string null this does not work but still only matches one overload3 callmethodreflectionobj function2 string string this works4 callmethodreflectionobj function2 string null this does not work and i can see why this would cause problemsmainly i am trying to determine how to change my code so that line 2 works as well,['c#'] +151306,what is the l unicode category i came across some regular expressions that contain pl i understand that this is using some form of a unicode category but when i checked the documentation i found only the following l categorieslu uppercase letter uppercase letterll lowercase letter lowercase letterlt titlecase letter titlecase letterlm modifier letter modifier letterlo other letter other letterwhat is l in this context,['java'] +151313,can mockito stub a method without regard to the argument i am trying to test some legacy code using mockitoi want to stub a foodao that is used in production as followsfoo foodaogetbarnew bazooi can writewhenfoodaogetbarnew bazoothenreturnmyfoobut the obvious problem is that getbar is never called with the same bazoo object that i stubbed the method for curse that new operatori would love it if i could stub the method in a way that it returns myfoo regardless of the argument failing that i will listen to other workaround suggestions but i would really like to avoid changing the production code until there is reasonable test coverage,['java'] +151324,explain inexplicable deadlock first of all i do not see how i could be getting any deadlock at all since i am using no explicit locking there is only one table involved there is a separate process each to insert select and update rows only one row is inserted or updated at a time and each process only rarely perhaps once a minute runs at allit is an email queuecreate table emails queue id varchar40 not null email address varchar128 default null body text status time timestamp not null default current timestamp on update current timestamp status enumpendinginprocesentthiscardedfailed default null key status status key status time statusstatus time engineinnodb default charsetlatin1 the generating process in response to some user action but roughly every 90 seconds does an insert to the table setting the status to pendingthere is a monitoring process that every minute checks that the number of pending and failed emails is not excessive it takes less than a second to run and has never given me any troubleevery minute the sending process grabs all the pending emails it loops through and one email at a time sets its status to inprocess tries to send it and finally sets its status accordingly to sent thiscarded it has reasons for deciding an email should not go out or failed rejected by the smtp systemthe statement for setting the status is unusualupdate emails queue set status status timenow where id and status that is i only update the status if the current status it already what i believe it to be before this mechanism i accidentally kicked off two sending processes and they would each try to send the same email now if that were to happen one process would successfully move the email from pending to inprocess but the second one would update zero rows realize there is a problem and skip that emailthe problem is about one time in 100 the update fails altogether i get commysqljdbcexceptionsjdbc4mysqltransactionrollbackexception deadlock found when trying to get lock try restarting transactionwththis is the only table and only query that this happens to and it only happens in production to maximize difficulty in investigating itthe only two things that seem at all unusual are 1 updating a column that participates in the where clause and 2 the unused automatic updating of the status timei am looking for any suggestions or diagnostic techniques,['mysql'] +151326,how to cast variable to array i have a variable v that can be either single string or array of stringsand i have a codea arrayif is arrayv a v else a vhow it can be done in more elegant way in other words how to cast a variable to array,['php'] +151338,jqgrid error bjgridjqid is not a function i am trying to get started with the jquery plugin jqgrid however it is giving me the error bjgridjqid is not a function i downloaded the plugin from id6 with all features included and am referencing both jqueryjqgridminjs and gridlocaleenjshere is the htmltable idlisttablediv idpagerdivand here is the jsjqueryfunction jquerylistjqgrid url admincampusgetnearbybusinesses datatype json colnames name location colmodel name name index name width 150 name location index location width 150 rownum 10 rowlist 10 20 30 pager pager sortname name viewrecords true sortorder asc caption businesses jquerylistjqgridnavgrid pager edit false add false del false,['jquery'] +151339,how to find android textview number of characters per line so i have a textview in android that has the width of the whole length of the screen and a padding of dip 5 how can i calculate the number of characters that will fit a single line on the screen i guess in other words i am trying to get the number of columns of a textviewi considered manual calculation depending on textsize and width but 1 do not know the correlation and 2 due to the padding in the units of dip different screens will use different number of actual pixels to padoverall question i am trying to use this to solve if given a string how can i manually edit to string such that when the textview prints the string character by character i will know when to start a word that would not fit on one line on the next note i know that textview automatically puts words that would not fit onto the next line however since i am printing character by character like typing animation textview does not know the word would not fit until it prints out the overflowing characters of that wordbeen searching everywhere for thisthanksadded solutionsone possible solutionpublic string measure2 textview t string s string you int start 0 int end 1 int space 0 boolean ellipsized false float fwidth tgetmeasuredwidth for tsettextssubstringstart end float twidth tgetpaintmeasuretextssubstringstart end if twidth fwidth if end slength end else if ellipsized return s return you ssubsequencestart end else ellipsized true space u ssubstringstart endlastindexof if space 1 space end 1 you ssubsequencestart space n start space 1 end start 1 solution 2 but still uses solution1 sometimespublic string measure3 textview t string s liststring wlist arraysaslistssplit if wlistsize 1 return measure2t s string you int end 1 float fwidth tgetmeasuredwidth for tsettextssubstringstart end if wlistisempty return u string temp liststrwlist end float twidth tgetpaintmeasuretexttemp if twidth fwidth if end wlistsize end else return you temp else temp liststrwlist end1 if end 1 temp measure2t temp if wlistisempty return you temp else you you temp n wlist wlistsublistend 1 wlistsize end 1 public string liststr liststring arr int end string s for string e arrsublist0 end s s e return strimi used the above code to generate off a original string s a string you that would be printed however i think this approach is very inefficient is there another approach or a better algorithm note there are some errors in measure3 that i fixed but was too lazy to edit,['android'] +151344,how do i set the value of an nsnumber variable without creating a new object in objectivec how do i set the value of an nsnumber variable without creating a new object in objectivecbackgroundi am using core data and have a managed object that has an nsnumber dynamic propertypassing by reference this to another method which will update itnot sure how to update it if i allocate it another new nsnumber things do not work which i guess makes sense it is then got a pointer to a different object not the core data object i guess,"['iphone', 'objective-c', 'ios']" +151350,how does php assign and free memory for variables i was wondering when does php free the memory which is used for a variablesfor examplefunction foo foo data return foo is the memory space for foo emptied at this pointis it slower than function foo return data,['php'] +151354,programmatically changing button icon in wpf i currently have a button which has an iconimage on it i have configured the button and image in xamlbutton height69 horizontalalignmentleft margin20 nametogglebroadcast verticalalignmenttop width64 gridrow1 opacity05 clickchangebroadcaststate click image sourceimagesplayiconpng buttoni need to be able to programmatically change this buttons image from playicon to stopicon how can i do this,['c#'] +151361,easiest way to transfer data over the internet python i have two computers both are connected to the internet i would like transfer some basic data between them strings ints floats i am new to networking so i am looking for the most simple way to do this what modules would i be looking at to do this both systems would be running windows 7,['python'] +151367,how can i close all notifications of a page before unload it without use windowonunload i have a page that notifies the user about server updates using windowwebkitnotificationsit is not a google chrome extensioni want to close all page notifications before the page unloadi am trying to do it withvar notifications new array var popup windowwebkitnotificationscreatenotification notificationspushpopup function closeall for notification in notifications notificationsnotificationcancel windowunloadfunction closeallbut the notifications are not closed when i reloads the pagei found this issue on chromium project how can i ensure that page notifications are closed without use the windowonunload,['javascript'] +151381,tracking user metrics in ios app what is a good way to keep track of the areas in an app that a user visits or the features that he or she uses i know there are several preexisting opensource frameworksgoogle analytics sdk for iosiloggr analyticsand i know that there are services such as flurry that also help does anyone know of any other options and has anyone attempted to write a system that can keep track of some simple user metrics a tutorial or example would be really appreciated,"['iphone', 'ios']" +151406,error functions in index expression must be marked immutable in postgres i want to create a multicolumn expression index but when i create the index the following message is outputdetail message wapgrowth create index concurrently idx test on tmp table using btree skyid to charcreate time ymmdd actiontype error functions in index expression must be marked immutabletable ddlwapgrowth d tmp table table wapgrowthtmp table column type modifiers id integer not null actiontype character varying20 apptype character varying20 score integer create time timestamp without time zone default now skyid integer indexes,['sql'] +151417,syntax use variable for css value trying to keep a box centered vertically within another box i know there is css that can do this but i would rather use jquery more reliablevar texth textheightvar vertalign 140 texth2textcss margintop vertalignnot sure what detail i am missing the output should be half the available vertical space in pixelseditoriginally the text block was a span contained by a div the div had a set height 140 px in this case and the text block the span would be variable height based on how much text was in it however i need this text block to be editable so i changed it to a text area however the behavior for the dimensions of the text area is awkward and i had to set a static height and width to it now the height of this text block is not variable so there is no difference in height between it and it is parent with which to derive the margintop spacing from what should i do,"['jquery', 'css']" +151419,iphone having a ripple effect on a uiimageview hey guys i am attempting to create a ripple like effect on an imageview when it is touched down on however i do not understand how to implement opengl for windows and porting it to ios i have attempted to use as well as cocos2d however i find the latter completely and utterly confusing would anyone be willing to give some suggestions or can point me in the right direction many thanks,['iphone'] +151425,can i optimize a select thistinct x from hugetable query by creating an index on column x i have a huge table having a much smaller number by orders of magnitude of thistinct values on some column xi need to do a query like select thistinct x from hugetable and i want to do this relatively fasti did something like create index hugetable by x on hugetablex but for some reason even though the output is small the query execution is not as fast the query plan shows that 97 of the time is spent on index scan of hugetable by x with an estimated number of rows equal to the size of the entire table this is followed by among other things a hash match operationsince i created an index on column x can i not expect this query to run very quicklynote that i am using microsoft sql server 2005,['sql'] +151426,how to use log4j to write a file inside my project directory i have a log4j properties file which is creating a file inside my tomcatbin folder but instead can it write the log file to my projects root dir webappstest here is my log4j properties file contentsdefine the console appenderlog4jappenderconsoleappender orgapachelog4jconsoleappender now define the layout for the appenderlog4jappenderconsoleappenderlayout orgapachelog4jpatternlayoutlog4jappenderconsoleappenderlayoutconversionpatternt 5p c3 mnlog4jappenderrollingfileorgapachelog4jrollingfileappenderlog4jappenderrollingfilefiletestaloglog4jappenderrollingfilemaxfilesize10mblog4jappenderrollingfilemaxbackupindex2log4jappenderrollingfilelayout orgapachelog4jpatternlayoutlog4jappenderrollingfilelayoutconversionpatternp t c mn now map our console appender as a root logger means all log messages will go to this appenderfor console printinglog4jrootlogger debug consoleappender for file printinglog4jrootlogger debug rollingfile,['java'] +151438,rspec difference between let and before block what is difference between let and before block in rspecand when to use these block what will be good approach let or before in below example letuser usermake letaccount useraccountmakebeforeeach do user usermake account useraccountmakeendi studied this stackoverflow postbut is it good to define let for association stuff like above,['ruby-on-rails'] +151456,xml serializing with xmlwriter via stringbuilder is utf16 while via stream is utf8 i was surprised when i encountered it and wrote a console application to check it and make sure i was not doing anything elsecan anyone explain thisheres the codeusing system using systemcollectionsgenericusing systemiousing systemlinqusing systemtextusing systemxmlusing systemxmlserializationnamespace consoleapplication1 public class program static void mainstring args var o new someobject field1 string value field2 8 consolewritelineobjecttoxmlviastringbuilder consolewriteobjecttoxmlviastringbuildero consolewriteline consolewriteline consolewritelineobjecttoxmlviastream consolewritestreamtostringobjecttoxmlviastreamo consolereadkey public static string objecttoxmlviastringbuildersomeobject someobject var output new stringbuilder var settings new xmlwritersettings encoding encodingutf8 indent true using var xmlwriter xmlwritercreateoutput settings var serializer new xmlserializertypeofsomeobject var namespaces new xmlserializernamespaces xmlwriterwritestartdocument xmlwriterwritedoctypefield1 null someobjectdtd null namespacesaddstringempty stringempty serializerserializexmlwriter someobject namespaces return outputtostring private static string streamtostringstream stream var reader new streamreaderstream return readerreadtoend public static stream objecttoxmlviastreamsomeobject someobject var output new memorystream var settings new xmlwritersettings encoding encodingutf8 indent true using var xmlwriter xmlwritercreateoutput settings var serializer new xmlserializertypeofsomeobject var namespaces new xmlserializernamespaces xmlwriterwritestartdocument xmlwriterwritedoctypefield1 null someobjectdtd null namespacesaddstringempty stringempty serializerserializexmlwriter someobject namespaces outputseek0l seekoriginbegin return output public class someobject public string field1 get set public int field2 get set this is the resultobjecttoxmlviastringbuilderxml version10 encodingutf16doctype field1 system someobjectdtdsomeobjectfield1string valuefield1field28field2someobjectobjecttoxmlviastreamxml version10 encodingutf8doctype field1 system someobjectdtdsomeobjectfield1string valuefield1field28field2someobject,['c#'] +151472,set item click event on setonitemclicklistener of listview android i have three textviews in a row of a listview using custom adapter and on click of the row i want to perform the click event of the selected text viewbelow is my sample code for the click event here on the first click the listeners are set and only on the second click the actual click event happens i want to find this on the first click itself is it possiblelistviewsetonitemclicklistenernew onitemclicklistener override public void onitemclickadapterview adapter view view int pos long id final order orderbooking orderadaptergetitematpositionpos sku listener final textview tvskuid textview viewfindviewbyidorderbookinggetselectedskuid tvskuidsetonclicklistenernew onclicklistener override public void onclickview view onskuclicklistenerview orderbooking so listener final textview tvsoid textview viewfindviewbyidorderbookinggetselectedsoid tvsoidsetonclicklistenernew onclicklistener override public void onclickview view onsoclicklistenerview orderbooking or listener final textview txtorid textview viewfindviewbyidorderbookinggetselectedorid onorclicklistenerview orderbooking txtoridsetonclicklistenernew onclicklistener override public void onclickview view onorclicklistenerview orderbooking,['android'] +151481,acl in aspnet mvc 3 i am looking for a solution in aspnet mvc for acl like the cakephp is giving by her acl componenti want to create the acl so i can assign permission on role and user basisthanks,['asp.net'] +151501,change the network operator with an android app i am trying to develop an android app which shows the signal strength of various network operators on a map the problem is that the only way to change the network operator is by doing it by hand any ideas on how i can get this information without changing it manually i think that there are internalprivate android classes to do this,['android'] +151514,how to add soap header in java i have a nonet webservice from oracleto access i need to add the soap header how can i add the soap header in javaauthenticatorsetdefaultnew proxyauthenticatorusername password systemgetpropertiesputproxyset true systemsetpropertyhttpproxyhost ip systemsetpropertyhttpproxyport port proxy new regpresmed servicenew urlwebservicegetregpresmed bindingprovider proxygetrequestcontextputbindingproviderendpoint address property realwebservice bindingprovider proxygetrequestcontextputcomsunxmlwsrequesttimeout new integer60 bindingprovider proxygetrequestcontextputbindingproviderusername property webserviceusername bindingprovider proxygetrequestcontextputbindingproviderpassword property webservicepasswordis this necessary bindingprovider proxygetrequestcontextputbindingproviderusername property webserviceusername bindingprovider proxygetrequestcontextputbindingproviderpassword property webservicepasswordmy soap header is like thiswssesecurity soapenvmustunderstand1xmlnswsse wsseusernametoken wsuidusernametoken6xmlnswsu wsseusernameusernamewsseusername wssepasswordtypepasswordwssepassword wssenonceencodingtyperandomnaumberwssenonce wsucreateddatecreatedwsucreated wsseusernametokenwssesecurity,['java'] +151519,using lambdaj in android does anyone tried to use lambdaj library in android developmentit works fine for me when i create a simple small java application but i cannot manage to use it in an android applicationupdatei am adding lambdaj lambdaj232withdependenciesjar downloaded from and then when building my application get the following error dx warning ignoring innerclasses attribute for an anonymous inner classorghamcrestgeneratorqdoxdirectorywalkerdirectoryscanner1 that does not come with anassociated enclosingmethod attribute this class was probably produced by acompiler that did not target the modern class file format the recommendedsolution is to recompile the class from source using an uptodate compilerand without specifying any target type options the consequence of ignoringthis warning is that reflective operations on this class will incorrectlyindicate that it is not an inner class20110512 154530 myappname dx warning ignoring innerclasses attribute for an anonymous inner classorghamcrestgeneratorqdoxjavadocbuilder1 that does not come with anassociated enclosingmethod attribute this class was probably produced by acompiler that did not target the modern class file format the recommendedsolution is to recompile the class from source using an uptodate compilerand without specifying any target type options the consequence of ignoringthis warning is that reflective operations on this class will incorrectlyindicate that it is not an inner class20110512 154530 myappname dx warning ignoring innerclasses attribute for an anonymous inner classorghamcrestgeneratorqdoxjunitapitestcase1 that does not come with anassociated enclosingmethod attribute this class was probably produced by acompiler that did not target the modern class file format the recommendedsolution is to recompile the class from source using an uptodate compilerand without specifying any target type options the consequence of ignoringthis warning is that reflective operations on this class will incorrectlyindicate that it is not an inner class20110512 154530 myappname dx unexpected toplevel exceptioncomandroiddxcfcodesimexception local variable type mismatch attempt to set or access a value of type javalangobject using a local variable of type int this is symptomatic of class transformation tools that ignore local variable informationskipped stack tracewhile working on block 001bwhile working on method yylexiwhile processing yylex iwhile processing orghamcrestgeneratorqdoxparserimpljflexlexerclass20110512 154530 myappname dx 1 error aborting20110512 154530 myappname conversion to dalvik format failed with error 1,"['java', 'android']" +151525,uipagecontrol views not changing on click of dots i am using pagecontrol in my application views are not changing on click on dots but on the either ends of pagecontrol when i click views are changing i want them to change on clicks on dot what to do is there any method i need to implement heres the codeimport scrollingviewcontrollerhimplementation scrollingviewcontrollersynthesize scrollviewsynthesize pagecontrol voidviewdidload super viewdidload self setuppage pagecontrol uipagecontrol alloc initwithframecgrectmake0390320100 pagecontroluserinteractionenabled yes pagecontrolnumberofpages 5 pagecontrolcurrentpage 0 selfpagecontrol setbackgroundcoloruicolor blackcolor pagecontrolenabled true pagecontrol sethighlightedyes pagecontrol addtargetself actionselectorchangepage forcontroleventsuicontroleventvaluechanged selfview addsubviewpagecontrol voiddidreceivememorywarning super didreceivememorywarning voidviewdidunload scrollview release pagecontrol release voiddealloc super dealloc voidsetuppage scrollview uiscrollview alloc initwithframecgrectmake00320400 scrollview setcontentsizecgsizemake10 800 scrollviewcontentsize cgsizemake10800 scrollviewscrollstotop no selfscrollview setbackgroundcoloruicolor blackcolor scrollview setcancancelcontenttouchesno scrollviewindicatorstyle uiscrollviewindicatorstylewhite scrollviewclipstobounds yes scrollviewscrollenabled yes scrollviewpagingenabled yes nsuinteger nimages 0 cgfloat cx 0 for nimages nsstring imagename nsstring stringwithformatimagedjpg nimages 1 uiimage image uiimage imagenamedimagename if image nil break uiimageview imageview uiimageview alloc initwithimageimage cgrect rect imageviewframe rectsizeheight imagesizeheight rectsizewidth imagesizewidth rectoriginx scrollviewframesizewidth imagesizewidth 2 cx rectoriginy scrollviewframesizeheight imagesizeheight 2 imageviewframe rect scrollview addsubviewimageview imageview release cx scrollviewframesizewidth selfpagecontrolnumberofpages nimages scrollview setcontentsizecgsizemakecx scrollview boundssizeheight scrollviewdelegate self selfview addsubviewscrollview voidscrollviewdidscrolluiscrollview scrollview if pagecontrolischangingpage return cgfloat pagewidth scrollviewframesizewidth int page floor scrollviewcontentoffsetx pagewidth 2 pagewidth 1 pagecontrolcurrentpage page voidscrollviewdidenddeceleratinguiscrollview scrollview pagecontrolischangingpage no ibactionchangepageidsender change the scroll view cgrect frame scrollviewframe frameoriginx framesizewidth pagecontrolcurrentpage frameoriginy 0 scrollview scrollrecttovisibleframe animatedyes pagecontrolischangingpage yesend,"['iphone', 'ios']" +151532,converting a hexadecimal number to binary in ruby i am trying to convert a hex value to a binary value each bit in the hex string should have an equivalent four bit binary value i was advised to use thisnum 0ff say for egbin 0numsize4b numhexto ithis gives me the correct output 01 i am confused with how this works especially 0numsize4b could someone help me with this,['ruby'] +151536,uiscrollview and setcontentoffset my question is about this methodvoidsetcontentoffsetcgpointcontentoffset animatedboolanimatedi have read the documentation but i do not understand what this method is forthanks for your answers,"['iphone', 'ios']" +151554,how to set margin for vertical scrollbar from the right edge in listview for android platformi need to put margin on right side of the vertical scrollbar in listview it is customized please see the attached image default scrollbar sticks to the extream right side of the listviewneed your hand thanks,['android'] +151557,ipad html focus i have an issue with focusing a text field on the ipad where i usedocumentbindclickfunctionevent alertclick focustextareathe focus is set to the text area and a keyboard appears however when called with touchend focustextarea is not called and the keyboard is not made visible my focustextarea function isfunction focustextarea textareafocusdoes anybody know why this occurs and how i might be able to get this to worktiaadam,"['jquery', 'html']" +151559,regex to match date i want to match dates with format mmddyy or mmddy but it should not pick 23092010 where month is 23 which is invalid nor some invalid date like 00122020 or 12002011,['ruby'] +151577,which is better to use converttox or xparse i am using reflection to create some objects the values i am setting are read in from a file so they are natively in a string format and i need to convert them to the datatype of the propertymy question is which is fasterbetter to use the converttox methods or the xparse methods,"['c#', '.net']" +151581,how do i filter a string on just numbers dots and commas okay so ive got a long string and i want to remove everything thats inside except for decimal numbers commas and dotsi have triedstr strreplace09but this just ends up in nothingcan anyone help methanks,['java'] +151587,practical applications of php magic methods get set and call i have generally tried to stay away from phps magic methods because they seem to obfuscate an objects public interface that said they seem to be used more and more at least in the code i have read so i have to ask is there any consensus on when to use them are there any common patterns for using these three magic methods,['php'] +151593,jquery js get the scrollbar height of an textarea i have got a textarea with a fixed height when the user types text into the textarea a scrollbar will show up after the user typed some text in ithow can i get the scrollbar height using jquery or plain javascript i have been searching for this for hours but could not find anything i cannot just insert a div and get the scrollbar height via the div offset because a textarea is not allowed to have child elementsplease do not give me a link to a jquery plugin that does the job i want to learn something,"['javascript', 'jquery']" +151607,static methods in c i am having a little trouble working with static methods in cexample hclass ic utility public ic utility ic utility stdstring cp pstringtostring const unsigned char outstring void cp stringtopstring stdstring instring unsigned char outstring short inmaxlength static void cp stringtopstring stdstring instring unsigned char outstring void cp stringtopstring fxstring instring fxuchar outstringexample cppstatic void ic utilitycp stringtopstringstdstring instring unsigned char outstring short length instringlength if outstring null if length 1 cplatcp utilitycp copymemory instringc str outstring 1 length outstring 0 length i wanted to make a call likeic utilitycp stringtopstringdirectorynamestring directoryname but i get an errorerror cannot declare member function static void ic utilitycp stringtopstringstdstring unsigned char to have static linkagei dont understand why i cannot do this can anyone help me understand why and how to achieve what i want,['c++'] +151617,difference between icomparable and icomparer possible duplicatewhen to use icomparablet vs icomparert what is the difference between icomparable and icomparer interfaces is it necessary to use this interface always with arraysort method,"['c#', '.net']" +151622,jcarousel lite with zoom and fade effect i am stuck on this one so hopefully someone can helpi have a website i am using jcarousel lite on and i have added a zoom in effect as well as a fade effect on the images here is the code for initializing jcarousel litewindowonload function jquerymidbodyjcarousellite auto 30 speed 0 circular true beforestart functiona width jqueryafindimgwidth zoom height jqueryafindimgheight zoom jqueryastopfalsetruefindimganimatewidthwidth heightheight topmove leftmove 20 linear function jquerythisremoveattrstyle jqueryaparentfadeto10 0 afterend functiona jqueryaparentfadeto10 1 visible 1 here is the website i have been trying to get this working onlinkif you watch the carousel everything runs fine the first go around but after that the first image in my unsorted list no longer zooms the rest of the images in the list will continue to zoom it is just the first one that is having this problem i think it might be jcarousellite that is at fault but i could not find anything thanks edit stackoverflow wouldnt allow me to answer my own question since i just created this account so i figured i would just edit the original and add it in sorry if this is not considered kosherok i have come up with a solution instead of firing an animation on the individual image that is visible i had to fire the animation on each image in the carousel then i used the callback of jcarousellite for after completing to stop all animations on all the images and reset the style attribute here is the revised codewindowonload function jquerymidbodyjcarousellite auto 50 speed 0 circular true beforestart functiona width jqueryafindimgwidth zoom height jqueryafindimgheight zoom jqueryaparentfindimganimatewidthwidth heightheight topmove leftmove 20 linear jqueryaparentfadeto10 0 afterend functiona jqueryaparentfindimgstoptruetrueremoveattrstyle jqueryaparentfadeto10 1 visible 1if someone knows of a better solution or how to get it work on the individual images please let me know thanks,"['javascript', 'jquery']" +151637,optimization by java compiler recently i was reading this articleaccording to that article java compiler ie javac does not perform any optimization while generating bytecode is it really true if so then can it be implemented as an intermediate code generator to remove redundancy and generate optimal code,['java'] +151667,objective cobject deallocated while key value observers were still registered with it i am hitting the below error after i added 2 additional fields to my core data modelcarpark carpark was deallocated while key value observers were still registered with it observation info was leaked and may even become mistakenly attached to some other object set a breakpoint on nskvodeallocatebreak to stop here in the debugger heres the current observation infonskeyvalueobservationinfo 0x1b6510 nskeyvalueobservance 0x19b210 observer 0x1a8cf0 key path coordinate options new no old no prior yes context 0x0 property 0x1b7e00i am a little lost on what to do next any guidance on this will be greatly greatly appreciated please let me know what other information is required,"['objective-c', 'ios']" +151675,rotating an image context cgcontextrotatectm causing it to become blank why define radiansdegrees degrees m pi180uiimage rotateuiimage image cgsize size imagesize uigraphicsbeginimagecontextsize cgcontextref context uigraphicsgetcurrentcontext if this is commented out image is returned as it is cgcontextrotatectm context radians90 image drawinrectcgrectmake0 0 sizewidth sizeheight uiimage newimage uigraphicsgetimagefromcurrentimagecontext uigraphicsendimagecontext return newimagecould something else be wrong out of ideas,"['iphone', 'objective-c', 'ios']" +151676,importerror cannot import name signals i am using django 130 with python 271in every test i write the following imports i get the importerror abovefrom djangoutils import unittestfrom djangotestclient import clientthe full stack trace file cprogram files x86j2eepluginsorgpythonpydevdebug 1632010100513pysrcrunfilespy line 342 in get module from str mod import modname file cusersbenjaminworkspacebookitsrcbookittestsbasic flowpy line 11 in from djangotestclient import client file cpython27libsitepackagesdjangotest init py line 5 in from djangotestclient import client requestfactory file cpython27libsitepackagesdjangotestclientpy line 21 in from djangotest import signalsimporterror cannot import name signalserror module basic flow could not be importedany ideas why this happening,['python'] +151689,mysql if then statements in stored procedures i am writing a stored procedure that uses multiple if then statements that also need to execute multiple queries if they evaluate to true problem is i cannot seem to find any examples of the appropriate syntax from the mysql dev handbook it seems like i could have multiple queries in the statement list but so far i cannot get it to workheres what i am trying to doset agency coalesceselect org agency o id from orgs agencies where org agency code maj agency cat select minorg id from orgs where org name like concatussubstringmaj agency cat5 if agency is null then execute multiple queries insert into orgs org name org name length org type org sub types values concatus substringmaj agency cat5 lengthconcatus substringmaj agency cat5 orgorggovernmententityfederalagencyset agency last insert idend ifthe erroryou have an error in your sql syntax check the manual that corresponds to your mysql server version for the right syntax to use near if agency is null then insert into orgs org nameorg name lengthorg type at line 53any ideas i know it has to be something simple so i would greatly appreciate anybodys input,['mysql'] +151707,in quartznet is there a way to set a property that will only allow one instance of a job to run i have a service that will run every x minutes if that job takes longer than x minutes for some unforeseen reason i want to make sure that the trigger does not kick off a second instance of this job sample scenarioi have job x picks up files and is triggered by quartz every 1 minute job x can typically process 100 files in 1 minute anything over 100 files will take longer than 1 minutesince the last run time 150 files happen to be out there so job x kicks off and begins processing when 1 minute is reached 100 files were processed 50 files remain and job x continues to runhowever a second instance of job x is kicked off because the trigger fires every 1 minutei now have 2 instances of job x picking up the same 50 filesis there a way to wire up quartznet to only allow 1 instance of a job i am ok with the second trigger waiting for the first to complete or i am also ok with an option for it to skip the second trigger since it will be triggered again in a minutei took a look at the java version of quartz api and found a property thisallowconcurrentexecution but did not find one similar in the net versionmy code for the quartznet implementationpublic ischeduler scheduler get set public ijoblistener autofacjoblistener get set public void start var trigger triggerutilsmakeminutelytrigger1 triggername document import trigger schedulerschedulejobnew jobdetaildocument import null typeofdocumentimportjob trigger scheduleraddglobaljoblistenerautofacjoblistener schedulerstart,['.net'] +151708,inverting y axis and setting coordinate system in opengl in opengl i am trying to invert the y axis and set a specific type of coordinate system just like how allegro has it assuming my window is 640x480 i want the top left of the screen be axis 0 0 and the bottom right 640 480 so far i managed to get the proper coordinate system i want but i do not know if it is done the proper way as for flipping the y axis i was unable to invert it without modifying the coordinate system i currently have i do not want something hackish only to flip 1 shape i want it to flip all future shapes i make on the y axis while maintaining the coordinate system here is what i have so farinitializeconst gldouble xsize 640 ysize 480glmatrixmodegl projectionglloadidentityglortho0 xsize ysize 0 1 10glmatrixmodegl modelviewrenderfloat size 30glcleargl color buffer bit gl depth buffer bitglloadidentitygltranslatef0 0 500glpushmatrixgltranslatefsize size 00fglbegingl trianglesglcolor3f01 03 08glvertex3f 00f size 00fglvertex3fsizesize 00fglvertex3f sizesize 00fglendglpopmatrixediti figured out that addingglscalef1 1 1will flip my shape but i have to include it inside glpushmatrix of my shapes and i do not know if this is the proper way to do this or if its a hackish solution,['c++'] +151721,how do i increase memory on tomcat 7 when running as a windows service i am trying to run tomcat 7 as a windows service xp and windows 7i see places to set the xmx and xms jvm args in catalinabat but i am not sure how to do it when using catalina homebinservicebat install servicename i looked around but the best i could find was that i needed to update windows registry key though i am not sure which one to editi am hoping there is an easier way is thereupdate i am not using the windows installer mainly because i am running multiple instances of tomcat on the same machine but with different ports for reasons i would rather not go into here if i can use the installer with multiple instances using different ports then i would like to know how but regardless is it possible to do increase the memory on a tomcat windows service without the ui tools that come with the installer,['java'] +151724,how to programmatically create windows user accounts on windows 7 or windows server 2008 i have been trying to create new local user accounts on windows 7 machine i used the systemdirectoryservicesdirectoryentry class as in here but it does not seem to work heres the code in the articlestatic void mainstring argstry directoryentry ad new directoryentrywinnt environmentmachinename computer directoryentry newuser adchildrenaddtestuser1 user newuserinvokesetpassword new object 12345abc newuserinvokeput new object description test user from net newusercommitchanges directoryentry grp grp adchildrenfindguests group if grp null grpinvokeadd new object newuserpathtostring consolewritelineaccount created successfully consolereadlinecatch exception ex consolewritelineexmessage consolereadlinewhen executing this line directoryentry newuser adchildrenaddtestuser1 user i get a systemruntimeinteropservicescomexception with unknown error 0x8050 as the exception message and 2147463168 as the error codei assume this is probably because the article targets windows xp and below machines and i am targeting windows 7 and windows server 2008 any help appreciated update for some mysterious reason i am no longer seeing that systemruntimeinteropservicescomexception however when committing the changes here newusercommitchanges i get a unauthorizedaccessexception i tried running the app as administrator but still not workingupdate 2 ok after changing to the userprincipal class i got the follwoing code to workpublic userprincipal createnewuserstring susername string spassword first check that the user does not exist if getusersusername null principalcontext oprincipalcontext getprincipalcontext userprincipal ouserprincipal new userprincipaloprincipalcontext ouserprincipalname susername ouserprincipalsetpasswordspassword user log on name ouserprincipaluserprincipalname susername ouserprincipalsave return ouserprincipal if it already exists return the old user return getusersusername this code runs well when i run it as a console app of course run as administrator but when i deployed it as a windows service with the security account set as localsystem i get an invlaidoperationexception saying the underlying store does not support this property thoughts,['c#'] +151729,statsd and graphitelike tools for net and windows i was recently sent this link to statsd which would be an interesting tool for us to monitor various aspects of our product but it would be a hardsell for us because of the php and nonwindows toolset this question asks about installing this on windows without an answercan anyone recommend windows net toolsets that might provide similar lowoverhead monitoring of systems within reason paying for a toolset should not be a problemi did find this microsoft page that looks quite interesting but let us be honest it does not have as many cool graphs that show the kind of thing that would be nice to have as an endresult your experiences and thoughts on direction would be appreciated i think our ultimate goal would be wallboards eg large screens cycling through several key graphs or views so the whole team could understand and monitor some key metrics of the products we are supporting our client uses sql server reporting services for this but their reports seem to be mostly statistical and very little graphical,"['c#', '.net']" +151731,debugging a strange memory leak javatomcat i am experiencing a very odd problem with a java application running under tomcatwe tried to update the production code from a fresh newly produced in a 1week sprint the application has been running over months without hiccups and then this new code makes our linux servers start swapping after some timethe very strange thing is that when looking at visualvm for memory usage it never exceeds the maximum heap size the jvm does not throw an outofmemory the machine only starts swapping and the jvm keeps running even after thatso it seems that is leaking memory from somewhere it seems like it is from the new code but it is odd that it is not inside the jvm any ideas in how to debug thatthanks,['java'] +151758,what is the idiomatic hamcrest pattern to assert that each element of an iterable matches a given matcher examine the following snippet assertthat arraysaslist1x 2x 3x 4z nothasitemnotendswithx this asserts that the list does not have an element that does not end with x this of course is the double negatives way of saying that all elements of the list ends with xalso note that the snippet throwsjavalangassertionerror expected not a collection containing not a string ending with x got 1x 2x 3x 4zthis lists the entire list instead of just the element that does not end with xso is there an idiomatic way ofasserting that each element ends with x without double negativeson assertion error list only those elements that does not end with x,['java'] +151764,how do you get the current seed of random in c in my game i am going to use random values to pick the reward the player gets from a chest the problem is that you can quick save and quick load and that means they can keep reloading to rerandomize until they get what they want is there some way that i could get the current seed value of my random object and possibly return to that same point when they load so that they could not abuse the randomization,['c#'] +151765,error compiling cuda program hey this program seems be fine but i still getting an erro some suggestionprograminclude dothinclude cudahinclude cuda runtimehinclude stdiohint mainint argc char argv int a b c int dev a dev b dev c int size and sizeofint cudamallocvoiddev a size cudamallocvoiddev b size cudamallocvoiddev c sizeofint a int malloc size b int malloc size c int malloc sizeofint random intsa n random intsb n cudamemcpydev a a size cudamemcpyhosttodevice cudamemcpydev b b size cudamemcpyhosttodevice int res nthreads per block dot res threads per block dev a dev b dev c helloworld dimgrid dimblock d str cudamemcpy c dev c sizeofint cudamemcpydevicetohost freea freeb freec cudafreedev a cudafreedev b cudafreedev c return 0the errordotproductcudacpp27 error expected primaryexpression before token dotproductcudacpp27 error expected primaryexpression before token,['c++'] +151767,thisabling spinner in android i am having problems when using androidenabledfalse it is not thisabling the component in the case it is a spinner do not know if it is relevant but it belongs to a layout that is part of a viewflipperany hints or workarounds thanks,['android'] +151792,function is not defined error in python i am trying to define a basic function in python but i always get the following error when i run a simple test program pyth test1 2traceback most recent call last file pyshell2 line 1 in module pyth test1 2nameerror name pyth test is not definedhere is the code i am using for this functiondef pyth test x1 x2 print x1 x2update i have the script called pythpy open and then i am typing in pyth test12 in the interpreter when it gives the error thanks for the help i apologize for the basic question i have never programmed before and am trying to learn python as a hobbyimport syssyspathappend usersclancdocumentsdevelopmentimport testprintline the function printline in the testpy filedef printline print i am working,['python'] +151797,is not defined in iframe i have a page with an iframe in it my iframe page is iframephp and my main page is mainphp when i load iframephp directly my jquery code executes fine but when i load mainphp which contains iframephp as an iframe i get an error is not defined could this be because both mainphp and iframephp usescript typetextjavascript srcscriptif so how can i use jquery in the iframe page without including this line,['jquery'] +151798,convert float to double loses precision but not via tostring i have the following codefloat f 03fdouble d1 systemconverttodoublefdouble d2 systemconverttodoubleftostringthe results are equivalent tod1 0301192092896d2 03i am curious to find out why this is,['c#'] +151801,can the linker inline functions in the file file1c there is a call to a function that is implemented in the file file2cwhen i link file1o and file2o into an executable if the function in file2 is very small will the linker automatically detect that the function is small and inline its call,['c'] +151811,visualvm vs jprobe vs jprofiler there are multiple tools available for cpu and memory profiling jvisualvm is fairly new among theseare there any comparisonbenchmarking between these tools which tool is better than other,['java'] +151827,socket bufferedreader hangs at readline i have a server which initially does thisbufferedreader br new bufferedreadernew inputstreamreadersgetinputstreamfor string cmdline brreadline if cmdline null cmdlinelength 0 break later it passes the socket to another class foothis class wait for application specific messages bufferedreader br new bufferedreadernew inputstreamreadersgetinputstream appcmdbrreadlinemy client sends this sequencebarnhow are unnpassing it to foonnthe problem is that sometimes foo does not get its response it hangs in the readlinewhat is the chance that readline in the server is buffering up the data using the read ahead and foo class is getting starvedif i add a sleep in the client side it works but what is the chance that it will always workbarnhow are unnsleep10passing it to foonnhow to fix the problem appreciate any help on this regard,['java'] +151834,ipad safari touch events which all touch events are provided or detected by mobile safari browser in ipadbasically what all does webkit provide i am kind of looking for the native app ios sdk equivalent of touchesbegan touchesmoved etc in safari,"['javascript', 'html']" +151835,can i do sendkeys in javascript sendkeys is method to sending keystroke to an applicationcan i do it in javascript to send keystroke in browser ref,['javascript'] +151842,difference between 2 dates in seconds possible duplicatesnumber of seconds from now to sunday midnightcalculates difference between two dates in php hello allin my project i need to calculate the difference in seconds between two datesfor example firstday 20110512 182020secondday 20110513 182020then i should get 86400 seconds that is 24 hours similarly for firstday 20110513 115920secondday 20110513 120020it should return 60 secondsi read lots of questions in the stackoverflow but they only deals with the difference between 2 minute fields like 115001 and 121057,['php'] +151846,how to calculate the current speed and average speed of user travelling from current location to particular loaction in map in iphone i am having a map applicationwhen a person travels from current location to particular location i want to calculate the thistance covered by the person the current speed of the person average speed of the person can anybody help me in solving this problemplease provide me any sloution to solve this problemthanks,"['iphone', 'objective-c']" +151875,what is the correct way to delete char i have a char basically an array of strings that i need to delete what is the correct way of doing this to ensure all pointers are cleared up,['c++'] +151880,iphone focus effect just like uialertview i know title of my question is so bad but i do not know how to describe itwhen an uialertview pops up anything else on the screen except the uialertview becomes a bit darker but can be seen i call this as focus effect because you will know clearly and directly that now the uialertview is the focusso how can i implement such a focus effect thanks,['iphone'] +151912,add column to magento admin catolog manage products hi i want to add a column to the catolg manage products section not the product but the list of products this column needs to list any related products the product has identified with it maybe by sku or name no preferance therei added a column for manufacturer but forgot where i obtained the code fromthanks,['php'] +151922,thisable gesture recognizer i have two types of recognizer one for tap and one for swipeuigesturerecognizer recognizertaprecognizer uitapgesturerecognizer alloc initwithtargetself actionselectornumtap1uitapgesturerecognizer recognizer setnumberoftouchesrequired1selfview addgesturerecognizerrecognizerselftaprecognizer uitapgesturerecognizer recognizerrecognizerdelegate selfrecognizer releaseswipe rightrecognizer uiswipegesturerecognizer alloc initwithtargetself actionselectorswiperightselfswiperightrecognizer uiswipegesturerecognizer recognizerswiperightrecognizerdirection uiswipegesturerecognizerdirectionrightselfview addgesturerecognizerswiperightrecognizerselfswiperightrecognizer uiswipegesturerecognizer recognizerrecognizer releasewith this function i can thisable taps on some objects boolgesturerecognizeruigesturerecognizer gesturerecognizer shouldreceivetouchuitouch touch if touchview loseview touchview subbgview touchview btnagain return noreturn yeshow can i thisable swipesthanks a lot,['objective-c'] +151926,handling the null value from a resultset in java i currently have a resultset returned and in one of the columns the string value may be null i mean no values at all i have a condition to implement like following rs stexecutequeryselectsql output rsgetstringcolumnsince the column may be null in the database the rsgetstring will throw a nullpointerexception when column is null if column is null i want output to be an empty string like output i cannot check ifrsgetstringcolumn null either how can i tackle this situationmy real problem try rs stexecutequerysql int i 0 whilersnext outputi rsgetstringcolumn column field in the database contains multiple results but sometimes may be null i catchsqlexception e eprintstacktrace other than tracing the exception i want to fill the array too return outputnow if one of the column values contains no value ie null i want outputi defined as na all this problem stems from the fact that the column field is null allowed in the database and sorry guys for telling you that its a npe while in fact its sqlexceptionnoob here,['java'] +151961,boxshadow over floating divs i got a problem rendering boxshadows over floating divsive tested in chrome and firefox with the same result html head head body div stylefloatleft clear left backgroundcolor a mozboxshadow 0px 8px 8px 0 width 200px height 200px div div stylefloatleft clear left backgroundcolor a mozboxshadow 0px 8px 8px 0 width 200px height 200px div body htmledit the div on top does not render its shadow on the div below is there any fix for this problem or do i have to try a different solutionregards joel,"['css', 'html']" +151966,can i temporarily override dns resolution within a net application i have some wrapper code that runs a set of nunit tests that scan live websites for certain response codesi would like to run these tests against a different server when running manually i can do this by editing the etchosts file in windowssystem32drivers and temporarily setting wmysitecom to 10whateveris there any way i can do the same within a net console application temporarily override a dns record or somehow intercept the resolution and return a different ip addressedit this is for testing multiple servers in a web farm i have three live servers all of which think they are wmysitecom because the servers use http host headers i cannot just run a test against server1 then server2 then server3 because an http request to httpserver1 will not return the same thing as a request to that is resolved to server1,['c#'] +151967,android application in haskell hi i know there are similar questions but maybe thare are any updates or new libraries in this areawhat i am looking forbest practices of writing androidaplication in haskell i know incmonodroidjava there are millionsof samplesdo you know bloggers articles which write about androidhaskelli saw these useful linkshaskell interpreter on androidrunning a haskell program on the android osand i understand that i could useghc targeting ndk gccjhcwhat about converting haskell to c and using nativeactivity if you want to do android ui code in haskell somebody will have to write haskell bindings to java through jnicare there any haskell android experts,"['java', 'android']" +151986,how can i pass a state object to a continuation task i am using the net 40 task parallel library with c my first time using tpli have a task a which i want to run to completion before firing off a bunch of other tasks bcd etc i therefore want to create tasks bcd etc as continuations of task a however i want to pass a state object to task b another state object to task c etci can pass a state object to task a by simply using a task constructor overload that takes a state object for example describes this task constructor overloadtaskactionobject object cancellationtoken this works fine and the second argument is my state objecti want to create a continuation task eg for task btask taskb taskacontinuewith args herehowever i cannot see a continuewith overload see which allows me to pass a state object to a continuation task how can this be donenotes i do not have the state object for taskb available at the time i create taskathe state object for taskb is not an output return value of taskafor some context what i am doing is creating taskb taskc etc inside a couple of loops and so i am passing the value of the loop variables to taskb taskc etc using a state object in order to avoid the problem of always ending up with the final value of the loop variables in the tasks the closure issue,"['c#', '.net']" +152007,not able to befriend typedefs any particular reason struct a typedef a bstruct c friend struct b gcc 470 20110427 tells me error using typedefname b after structso far this seems pretty selfexplanatory after all my example code is trying to declareandfriend a struct called b which is in fact not a structkeyhowever i have to write friend struct a if a is in fact a complex longwinded mess of template metahackery this is not desirableam i missing something or can we in fact not friend types through type aliases if not is there any particular reason or is it just a quirk of the languagethis question brought up the issue before but is dated and makes assertions on the matter regarding c0x that do not appear to be true this question instead regards the c0x fthis,['c++'] +152014,implementing oauth 20 authentication for my api i have been using the facebook graph api uses oauth 20 for authentication successfully for a while now i now need to write my own api which allows developers to connect to it in a similar fashion i have looked into various libraries but i would like something a little leaner so i have decided to roll my own looking at the code i have to authenticate a user on facebook it looks relatively simple but please correct me if i am going off trackfirst i would need to provide a secure page which the consumer would need to redirect to eg idconsumer keyredirect urlcallback url the user would verify the application then i would redirect back to the url provided in the callback url with the oauth token in the query string i suppose i could just generate a random unique string here for the oauth token and store it against the user for this particular consumer edit please see the answer below this should be unique for each consumer application and not the userthat is step 1 out the way i now need to provide a second secure page which the consumer would trigger a web request to eg tokenclient idconsumer keyclient secretconsumer secretoauth tokenoauth token returned above this would allow the consumer to exchange the oauth token returned above for an access token i would again simply generate a random unique string and store it against the user for this particular consumernow my api would accept the access token for methods which try to grab information specific to the user who is using iti would like to know if i have understood things correctly the oauth 20 spec seems extremely trivial if that is the case also why do we have to exchange the oauth token with an access token i have my own idea but i would appreciate it if someone could help clarify thisi would really appreciate your feedback as i do not wish to go ahead and waste hours implenting this when it is completely wrongthanks,"['c#', '.net']" +152023,changing south migration directory how do you change the location where south looks for an apps migrationsby default south assumes an apps migrations are in migrations however i have migrated the model of a thirdparty package which is installed at usrlocallibpython26thistpackages so south is looking for migrations there instead of the location of my custom codebase,['python'] +152036,how to change the user and group permissions for a directory by name oschown is exactly what i want but i want to specify the user and group by name not id i do not know what they are how can i do that,['python'] +152044,models viewmodels dtos in mvc 3 application i have a web solution in vs2010 with two subprojectsdomain which holds the model classes mapped to database tables via entity framework and services which besides other stuff are responsible for crud operations webui which references the domain projectfor the first pages i have created i have used the model classes from the domain project directly as model in my strongly typed views because the classes were small and i wanted to thisplay and modify all propertiesnow i have a page which should only work with a small part of all properties of the corresponding domain model i retrieve those properties by using a projection of the query result in my service class but i need to project into a type and here come my questions about the solutions i can think ofi introduce viewmodels which live in the webui project and expose iqueryables and the ef data context from the service to the webui project then i could directly project into those viewmodelsif i do not want to expose iqueryables and the ef data context i put the viewmodel classes in the domain project then i can return the viewmodels directly as result of the queries and projections from the service classesin addition to the viewmodels in the webui project i introduce data transfer objects which move the data from the queries in the service classes to the viewmodelssolution 1 and 2 look like the same amount of work and i am inclined to prefer solution 2 to keep all the database concerns in a separate project but somehow it sounds wrong to have viewmodels in the domain projectsolution 3 sounds like a lot more work since i have more classes to create and to care about the modeldtoviewmodel mapping i also do not understand what would be the difference between the dtos and the viewmodels are not the viewmodels exactly the collection of the selected properties of my model class which i want to thisplay wouldnt they contain the same members as the dtos why would i want to differentiate between viewmodels and dtowhich of these three solutions is preferable and what are the benefits and downsides are there other optionsthank you for feedback in advanceedit because i had perhaps a too long wall of text and have been asked for codeexample i have a customer entity public class customer public int id get set public string name get set public city get set and many more properties and want to create a view which only shows and perhaps allows to edit the name of customers in a list in a service class i extract the data i need for the view via a projectionpublic class customerservice public listsomeclass1 getcustomernamelist using var dbcontext new mydbcontext return dbcontextcustomers selectc new someclass1 id cid name cname tolist then there is a customercontroller with an action method how should this look likeeither this way a public actionresult index listsomeclass1 list servicegetcustomernamelist return viewlist or better this way bpublic actionresult index listsomeclass1 list servicegetcustomernamelist listsomeclass2 newlist createnewlistlist return viewnewlistwith respect to option 3 above i would say someclass1 lives in domain project is a dto and someclass2 lives in webui project is a viewmodeli am wondering if it ever makes sense to thistinguish the two classes why wouldnt i always choose option a for the controller action because it is easier are there reasons to introduce the viewmodel someclass2 in addition to the dto someclass1,['asp.net'] +152047,thisabling user selection in uiwebview i have an app where i load content to a uiwebview and present this i cannot thisable user interaction completely because i want the user to be able to click links i just need to thisable user selection i found somewhere in the internets that you can usedocumentbodystylewebkituserselectnonei tried inserting this as selfcontentview stringbyevaluatingjavascriptfromstringdocumentbodystylewebkituserselectnone in webviewdidfinishloadhowever it does not work i am still able to select and copy text inside the webview any ideas what might be going wrongupdate this only seems to happen starting with ios 43,['ios'] +152051,equivalent of abc possible duplicatepython ternary operator i want to print out a string in python i do not want to doif isfemale bit print felse print mthe best i have right now is print m fintisfemale bitis there a better alternativei needs my syntactic sugar,['python'] +152056,expose a javascript api with coffeescript i recently started using coffeescript and was curious what is the right way to expose an object that i create with coffeescript to other javascript pages because of coffeescripts wrapping functionality is it acceptable behavior to call windowcoffeeobject externalobjectexampleexamplecoffexternalobject method1 return value method2 return method2windowmyapi externalobjectexamplejs compiled from examplecoffeefunction var externalobject externalobject method1 function return return value method2 function return return method2 windowmyapi externalobjectcallthisotherjsalertmyapimethod1 should return return value,['javascript'] +152079,inheritance with silverlight user control partial classes i am trying to allow several classes to inherit a more general silverlight user control to avoid redundancy in my code the classes inherit the extended control which then inherits the user control class the issue i have been running into is that the extendedcontrolextensiongcs file regenerates every time i compile with the incorrect inheritance it inherits user control not my extended control note that i have been inheriting the extended control in the cs and gcs files but continuing to use the user control tag in the aspx file as this causes the errorerror 29 the tag extendedcontrol does not exist in xml namespace is there a way to fix this thanks,['c#'] +152080,net timezoneinfo from olson time zone how can i convert the following into a systemtimezone or systemtimezoneinfo timezone americalos angeles currentoffsetms 2520this is data i am getting back from a 3rd party web servicei am assuming the offset is the difference from utc and i am told that the americalos angeles is an olson time zone java has no problems parsing this into a java timezone but i need to parse this into a c timezoneinfo object,"['c#', '.net']" +152100,jquery validate plugin prevent double submit on validation i am using a jquery validation plugin ati want to thisabled submit button only when validation passesit tried submitclickfunction thisattrthisabled thisabledbut this thisables the submit button even if validation fails is there a way to only thisable the submit when validation passes and a submit event occurs,['jquery'] +152112,locking a resource via lock within try is it wrong is there anything wrong with using lock with a try block i remember reading somewhere that we should always try to put minimum amount of code within try block and lock itself internally uses a tryfinally block do you guys see something wrong herei need to deal with the fact that the code within that lock block can throw exceptiontry locksyncblk do some processing catchexception e do something with exception,['c#'] +152115,append to url and refresh page i am looking to write a piece of javascript that will append a parameter to the current url and then refresh the page how can i do this,"['javascript', 'jquery']" +152123,how to convert datetime to eastern time i am trying to create an application that triggers some code when the financial markets are open basically in pseudo codeif930am et timenow 400pm et do somethingis there a way i can do this using the datetime object in c,"['c#', 'asp.net']" +152129,how should i organize a generalpurpose programming librarys directory structure i have been writing my own generalpurpose php library for a while and i am thinking about how to organize the directory structure but i wanted to get peoples ideas before i formalized the directory structure for the libraryhere is what i have so far i was thinking i could either do it by topic or by category so far i can only think of one example that i like of the by category boost 46 1viewcategorizedalso qt is organized by module but i think it is a bit messy because everything is kinda stuffed into qtcore any ideasthanks in advanceupdatei found a really great book that has shown me a number of great library design conventions to follow updatei found an interesting article that mentions organization of code at the bottom it sayswhat is your code tree going to look like he wants these words to describe it simple pragmatic elegant orthogonal composable this is an ideal reality is a bit different,['php'] +152134,how to remove class from all elements jquery i am changing the class of an element with the following dataidaddclasshighlightgiven the list below div idmenuitems ul idcontentleft classedgetoedge li clasep shakes and floatsli li id297a href onclickcart297addsmall500smallbvanillab ali li id298a href onclickcart298addsmall500smallbpeanut butterbali li id299a href onclickcart299addsmall500smallbcombobali li id300a href onclickcart300addsmall500smallbchocolatebali li id301a href onclickcart301addsmall500smallbstrawberrybali li id303a href onclickcart303addsmall500smallbbananabali li id304a href onclickcart304addsmall500smallbroot beer floatbali li id305a href onclickcart305addsmall500smallbespressobali ul div i assumed i could remove the class with this edgetoedgeremoveclasshighlightbut this does not work how can i remove the class,['jquery'] +152138,using fork in windows with ruby when i call kernelfork on windows i get this error unexpected error while processing request fork function is unimplemented on this machineis there an alternative way to fork while on windows,['ruby'] +152145,slice a string in groovy i have a 18 character string i want characters 28 from in python i can do thissliceme nnynprint sliceme28printsyi am looking for a way to do this same thing in groovy and every explanation is really long whats the elegant accepted way to do this in groovy or java for that matter,['java'] +152147,is there anyway to have instances share the same function yet at the same time have private variables i have this piece of codevar humanfunctionname this namenamehumanprototypeshoutfunction alertthis namevar tomnew humantomvar johnnew humanjohnalerttomshoutjohnshoutright now name is not private i want to make name private but at the same time i do not wish to create additional functions for each instance of human in other words tomshout must be to johnshout because creating additional functions for each instance is just well unnecessary ok offtopic we can debate this on another threadmy conclusion is that what i am trying to achieve having name be private and at the same time having tomshoutjohnshout is impossiblebut i just want to be 200 sure before jumping into any conclusions i welcome any hacks as long as the requirements are met ie no creating of additional functions for each instanceif we have to create additional functions to do scoping that is fine but that number should be a fixed number and that number should not increase with each additional instance of human,['javascript'] +152149,ie8 stretching table cell height i have a page layout that is based on tables and as much as i would like to restructure it with more modern markup that is not an option the layout uses a cell that spans two rows as a sidebar on the right side while the upper left cell contains a simple header and the lower left cell contains the main content of the page the top left cell has a fixed height and the height of the bottom cell and right cell is not specified i have created a simplified example that illustrates my problemdoctype html public w3cdtd html 401en htmlheadstyle typetextcssfixed height 100px table border 1px solid 0 td border 1px solid d verticalalign top tr border 1px solid cfc padding 15px styleheadbodytabletr classfixedtdlefttdtd rowspan2div styleheight 500pxrightdivtdtrtr clastretchtdlefttdtrtr classfootertd colspan2footertdtrtablebodyhtmli have set the height of the right column inline at 500px to simulate content that is taller than the height of the two left columns this behaves as expected in modern browsers the height of the top left cell remains fixed and the lower cell stretches to fill the extra space but in ie8 both left cells are stretched vertically i need the top cell to keep its fixed height how do i get ie8 to honor the height specified for the top left cell using only csseditinstead of setting the height on the right column td i am setting the height on a div inside the right column,"['html', 'css']" +152154,javascript finger slide detection heyi am trying to create a sliding checkbox like the one on the iphonei started with this scriptinputtypecheckboxlivetouchstart function e down x eoriginaleventtouches0pagex inputtypecheckboxlivetouchmove function e up x eoriginaleventtouches0pagex if down x up x 1 thischange but it does not seem to work any idea on how to implant thisthanks a lot guys,"['javascript', 'jquery', 'iphone']" +152158,is there a block until condition becomes true function in java i am writing a listener thread for a server and at the moment i am usingwhile true try if condition do something conditionfalse sleep10 catch interruptedexception ex loggergetloggerserverclassgetnameloglevelsevere null ex with the code above i am running into issues with the run function eating all the cpu time looping the sleep function works but it seems be a makeshift fix not a solutionis there some function which would block until the variable condition became trueor is continual looping the standard method of waiting until a variables value changes,['java'] +152166,converting between nsdata and base64a strings what is the easiest and fastest code to do a conversion between nsdata and a base64 string i have read a bunch of solutions at so and mostly they involve in adding another class etc i found a great solution here but it is too complex,"['ios', 'objective-c']" +152173,overloaded operators inheritance templates a formidable combination greetings alli am writing some code using the boost units library and have run into a problemi have managed to abstract the problem from boost code so you would not be looking through reams of boost template meta programming though i am sure if you have experience with that it could help here is the reproductionclass baseclass derived public basepublic derived derivedconst base class q class upublic template typename y q operator y q r return r base operator u const base base r return rint mainint argc char argv base mybase you myu base myotherbase myu mybase derived myderived derived myotherderived myu myderived return 0so the problem specifically is as follows myu mybase uses operator u const base and returns type of base all good so far whereas myu myderived insists on using generalised uoperator y and hence returns a q no good because i wanted a base againnow all classes other than base and derived are boost library classes so i cannot modify the members of u how do i beat uoperator y for overloadtemplate deductioninstantiation in this case in an elegant and solved once and for ever manneri am using msvc 2008 in case it is relevant to anyoneedit added a possible quite likely solution in answers,['c++'] +152215,printing with t tabs does not result in aligned columns very weird problemafter writing thisfor file f currentfilelistfiles if fisdirectory systemoutprintlnfgetnametdirtcommandgetpremissionftfgettotalspace else systemoutprintlnfgetnametfiletcommandgetpremissionftfgettotalspace i get this printingseetxt file rw 267642728448see1txt file rw 267642728456see2txt file rw 267642728448why there is a problem with the tabs what do i do wrong with the tabs,['java'] +152267,android serializable problem i created a class which has several member variables all of which are serializable except one bitmap i tried to extend bitmap and implement serializable not thinking bitmap is a final classi want to save the class it basically forms the current state of a game so a player can pickup and load the game the way i see it i have two options1 find another way to save the game state any help here would be appreciated2 change the bitmap member variable to an int say and create a bitmapgetter class that has a static method returning bitmaps based on ints this option is not easy as my class contains so many bitmap possiblities and the way i created the game means this will require an incredible amount of effortbasically i have no one to blame but myself for lazily creating a bitmap variable without thinking but i would appreciate any help,['android'] +152280,cannot use a contains or freetext predicate on table or indexed view because it is not fulltext indexed i am getting following error in my sql server 2008 r2 databasecannot use a contains or freetext predicate on table or indexed view tblarmy because it is not fulltext indexed,['sql'] +152282,how to place cursor at end of text in textarea when tabbed into possible duplicatejavascript move caret to last character i have a standard textarea with some text in it i am looking for a way to have the cursor automatically be placed at the end of the existing text so a user can simply start typing to add more text this should happen whenever the textarea becomes active such as when a user tabs into it any ideas,['javascript'] +152288,reading values from sql database in c i have just started learning c and i can write data to the database without a problem but i am having problems with reading the sql executes fine but i am having issues with storing it how would i store the four columns that should be returned and then show them as a message box thankssqlcommand mycommand new sqlcommandselect from requests where complete 0 myconnectionsqldatareader myreader mycommandexecutereaderwhile myreaderreadconsolewritelinemyreaderusernametostringconsolewritelinemyreaderitemtostringconsolewritelinemyreaderamounttostringconsolewritelinemyreadercompletetostring,"['c#', '.net']" +152289,convert date day 05122011 to 12th i am trying to covert the date to the day number followed by st nd rd or th depending on the day i am new to javascript so have no idea where to starteg05012011 1st05022011 2nd05032011 3rd05122011 12th052011 22ndthanks,['javascript'] +152308,which templating engine can i use with both js and php i am looking for a simple template engine that works both on client side with js and on server side with phpthat means i want to be able to use the same template definition for both use casesdo you know any templating engines that have official implementations in both js and php,"['javascript', 'php', 'html']" +152328,cannot debug small program on eclipse helios cdt using mingwgdb under windows console freezes i have been trying to use eclipse cdt to do some c examples i can run them just fine with the run command but whenever i try to debug the console window freezes up i am able to input but the program does not continue when i debug i get the following output on the console window no breakpoints but breaks on main because of default settings hello worldput your name 15runningthe continue button is thisabled and does not do anything when i input something and hit enter the 15 is a random number sometimes its 16 20 etcif i run the program under eclipse i get the input prompt just fine hello worldput your name testhello testthis is the code i try to debuginclude iostreaminclude stringint main stdcout hello world stdendl stdstring name stdcout put your name stdcin name stdcout hello name stdendl return 0my path varcwindowssystem32cwindowscwindowssystem32wbemcprogram filesjavajdk160 14bincmingwbineclipse version helios service release 2cdt version 702os windows xpgdb version gnu gdb gdb 72how can i debug this small example under cdt without issues,['c++'] +152329,configuring an nspredicate with multiple conditions i am not certain how one would go about cascading several conditions into an nspredicatei am fairly new to core data and not sure if that is the right way to achieve what i am looking to dohere is what i am trying to dothere is a photo object that has a wheretook relationship to a location object which has an inverse of photostooktherethe photo in turn has an nsnumber attribute called isfavouritei would like to configure an nsfetchrequest that will first check that photostookthere exists and if so check each resulting photo object and return only the ones that are set as favouriteshere is the code so farrequestentity nsentitydescription entityfornamelocation inmanagedobjectcontextcontextrequestsortdescriptors nsarray arraywithobjectnssortdescriptorsortdescriptorwithkeylocationid ascendingyesrequestpredicate nspredicate predicatewithformatphotostooktherecount 0how would i cascade the second condition into the predicate and return the correct results,"['iphone', 'objective-c', 'ios']" +152335,why do we need single in linq why is the main purpose of the extension method singlei know it will throw an exception if more than an element that matches the predicate in the sequence but i still do not understand in which context it could be useful editi do understand what single is doing so you do not need to explain in your question what this method does,"['c#', '.net']" +152348,implementing permissions based on reputation i am creating a website in which there are projects users and permissions for each user or groups of users what this is is a community collaboration tool and i have 4 different permissionscreator make changes accept changes change permissionsaccept changesmake changesviewhow could i implement in a database this kind of permission system for groups of usersedit groupspermissions are defined by reputation like on stackoverflowedit 2 more in detail each file needs to have a permission projects need default permissions for newly created files and i also need to set up mysql database permissions,"['php', 'mysql', 'sql']" +152373,how to make rails 31 use sass over scss as the default having a hard time figuring out how to make sass not scss as the default for stylesheetsi have tried making a sass configrb file with thissasspluginoptionssyntax sasasspluginoptionsstyle compressedi have also tried adding that to the environmentrb file either way i get this errorconfigenvironmentrb7in top required uninitialized constant sassplugin nameerror,"['ruby-on-rails', 'ruby']" +152375,rails 3 and saving decimal values from a form i have an odd bug in one of my applications when i am using the sqlite3 database the bug is not present however when i use mysql2 as the database adapter i run into an error saving decimal values from a form if i submit the value 19 my input after the decimal is removed and it is stored in the database as 1900 what would cause this the database has the correct settings for the column and i can create a correct record using the rails consoleedit said integer when i really wanted to say decimal,"['mysql', 'ruby-on-rails']" +152381,maintain centre coordinate while pinching mkmapview if you pinch to zoom inout in apples maps application while tracking the devices location the pan component of the pinch gesture is ignored and the blue location indicator remains fixed in the centre of the screen this is not the case when using a plain mkmapviewassuming i already have the users location how could i achieve this effect i have tried resetting the centre coordinate in the delegates regiondidwillchangeanimated methods but they are only called at the start and end of the gesture i also tried adding a uipinchgesturerecognizer subclass that resets the centre coordinate when the touches move but this resulted in rendering glitchesedit for those who are interested the following works for me centergesturerecognizerhinterface centergesturerecognizer uipinchgesturerecognizer idinitwithmapviewmkmapview mapviewend centergesturerecognizerminterface centergesturerecognizer voidhandlepinchgestureproperty nonatomic assign mkmapview mapviewendimplementation centergesturerecognizer idinitwithmapviewmkmapview mapview if mapview nil nsexception raisensinvalidargumentexception formatmapview cannot be nil if self super initwithtargetself actionselectorhandlepinchgesture selfmapview mapview return self boolcanbepreventedbygesturerecognizeruigesturerecognizer gesturerecognizer return no boolcanpreventgesturerecognizeruigesturerecognizer gesturerecognizer return no voidhandlepinchgesture cllocation location selfmapviewuserlocationlocation if location nil selfmapview setcentercoordinatelocationcoordinate synthesize mapviewendthen simply add it to your mkmapviewselfmapview addgesturerecognizercentergesturerecognizer alloc initwithmapviewselfmapview autorelease,"['iphone', 'objective-c', 'ios']" +152382,how do i use the empty variable in mysql more than once i am trying to check for 2 empty variables in a mysql statement but i can seem to get the syntax quite right for it here is what i have now and it keeps giving me an error can anyone please tell me how i can do this properly select threads userid username usergroupid from table prefix user where iifemptyexuserids and userid not in exuserids iifemptyexgroups and usergroupid not in exgroups order by threads desc limit 1,"['php', 'mysql', 'sql']" +152388,why should one not derive from c std string class i wanted to ask about a specific point made in effective c it saysa destructor should be made virtual if a class needs to act like a polymorphic class it further adds that since stdstring does not have a virtual destructor one should never derive from it also stdstring is not even designed to be a base class forget polymorphic base class i do not understand what specifically is required in a class to be eligible for being a base class not a polymorphic oneis the only reason that i should not derive from stdstring class is it does not have a virtual destructor for reusability purpose a base class can be defined and multiple derived class can inherit from it so what makes stdstring not even eligible as a base classalso if there is a base class purely defined for reusability purpose and there are many derived types is there any way to prevent client from doing base p new derived because the classes are not meant to be used polymorphically,['c++'] +152391,cannot connect to sql server express from ssms i have installed sql server management studio 2005 i cannot find my server name when i click browse for more but i know that my server name will be the same as the user name as in the picture below,['sql'] +152393,how do i grab a single image and put it in localstorage how is it done of course without external libraries in regular html with javascript this seems like it should be a simple onelineri would like to just doscriptlocalstorageimagesrchttprandomflikrimagejpgscript,['javascript'] +152423,launching blackberry apps from the command line i am trying to make use of the fledgecontroller to launch my app from the command line but when i execute the following line nothing happens no errorsthe 9800 simulator does not change from the homescreen to my app why is thatfledgecontroller session9800 executeloadcodcdocuments and settingsabsworkspace2bbdeliverablesstandard600bbcodin addition is there anyway i can pass a parameter to my app it will really help with testingthanks all for any help,['java'] +152428,how to override global style for img tag in css i have a template which sets global img tag properties as suchcontent img background none repeat scroll 0 0 f border 1px solid cfcfcf marginbottom 2px padding 2pxi have a list on my page and one of the items needs to have a small transparent image the styling above is causing the image to get a background and borders that i do not want the list html isdiv idland itemsulli classtrace itema hrefimglinkimg srcimgpopuppngaliuldivi have tried to override the img tag with the code below but firebug continues to show these rules with a strikethrough indicating the global img styling above is taking precedence i hear this could be because id css styles override class styles how do i accomplish thislitrace item img backgroundcolor transparent border none padding 0 margin 0,['css'] +152438,catch segfault or any other errorsexceptionssignals in c like catching exceptions in java i wrote a linux program based on a buggy open source library this library sometimes triggers segfaults that i cannot control and of course once the library has segfaults the entire program dies however i have to make sure my program keeps running even if the library has segfaults this is because my program sort of serves as a server and it needs to at least tell the clients something bad happened and recover from the errors rather than chicken out is there any way to do that i understand in java one just needs to catch an exception but how does c handle this updatei understand there is also exception handling in c but segfault is not an exception is it i do not think anything is thrown when segfault happens you have to explicitly throw something to use try catch as far as i know thanks so much i am quite new to c,['c++'] +152454,netbeans 69 cmake and c how to specify the build path i prefer to have a separate build directory when working with cmakecan i tell netbeans 69 to use that directory such that cmakecachetxt etc go there,['c++'] +152455,examples for using apache uima in a java program i have been searching for examples of using apache uima in a java program are there examples on how to use the example annotators in a java program,['java'] +152490,adding cure clustering algorithm to weka i have written a java program to perform cure clusteringi wish to add this program to weka as a clustering algorithm and visualize the clusteringhas anyone already implemented it on wekaany links to that would be very much helpfulhow do i proceed with it,['java'] +152492,parentremove issue i have a jquerybased form where you can add extra people to the application i am cloning the first fieldset and adding it onto the end up to a max of 3 additional people when youve added 1 extra person then you have the option to remove that person however my remove button is not working it was earlier until i added the extra functions to the cloning to change the ids of other elements within the fieldseti am usingremoveclickfunction thisparentremovewhich was working originally but now it is not and i cannot figure out whyi have taken out the lines that stop the first delete this person just to show that the first one still works but the rest do not i will be positioning the first one off stage eventually when it is fixedprobably easier to see it so i put it up here so essentially any ideas why my delete this person is not working on everything but the first section,['jquery'] +152505,cannot activate binary http binding on server i am trying to use binary message encoding in a wcf service following the many examples on this site on the server i have the binding declared as socustombinding binding namebinaryhttpbinding binarymessageencoding maxreadpoolsize40960 maxsessionsize40960 maxwritepoolsize40960 readerquotas maxdepth32 maxstringcontentlength40960 maxarraylength40960 maxbytesperread4096 maxnametablecharcount16384 binarymessageencoding httptransport maxbufferpoolsize40960 maxbuffersize40960 maxreceivedmessagesize40960 bindingcustombindingthe service is set to use it i thinkservice behaviorconfigurationmyserviceservicebehavior namemyservicecontentuploadservice endpoint address bindingcustombinding bindingconfigurationbinaryhttpbinding contractmyserviceicontentupload namemyservicecontentuploadservice the client has the same declarationscustombinding binding namebinaryhttpbinding binarymessageencoding maxreadpoolsize40960 maxsessionsize40960 maxwritepoolsize40960 readerquotas maxdepth32 maxstringcontentlength40960 maxarraylength40960 maxbytesperread4096 maxnametablecharcount16384 binarymessageencoding httptransport maxbufferpoolsize40960 maxbuffersize40960 maxreceivedmessagesize40960 bindingcustombindingandendpoint address bindingcustombinding bindingconfigurationbinaryhttpbinding contractmyserviceicontentupload namemyservicecontentuploadservicethe client appears to be working but the server throws an exception that indicates that the binding is not in placecontent type applicationsoapmsbin1 was sent to a service expecting textxml charsetutf8 the client and service bindings may be mismatchedimmediately prior to this error in the log file is this one thrown when trying to open the service host which must be the causeconfiguration evaluation context not foundnone of the search links i have tried for this message have been helpful so what basic piece am i missing,"['c#', '.net']" +152507,using jquery to toggle between styles good afternooni am searching for a way to toggle between stylesexamplei have two stylesclasses one makes the paragraph red and the other makes the paragraph blue i only want to use jquery to call the styles not to hold the styles itselfso when i click a button the paragraph turns red when i click again it turns blueagain i would rather have the style separate and given class names and have jquery switch between the twoi have search the net but keep coming up with showhide examples where the styles are embedded into the jquery functionany ideas will be appreciatedovermarshello everyone this is what i did as i mentioned i was simply trying to toggle between two styles one styles does something example make a text red or change an image and the other style makes another thing happenedthanks every one for your time a patience you all do make a differencei found the answer in my jquery cook book chapter 3 event handling page 69 here is the codedocumentreadyfunction normalstyleclickfunction thistoggleclassnewstyle,"['jquery', 'css']" +152509,read modify write xml file in cocoa i am looking for a short exampletutorial on how to read modify one value and write an xml file using cocoa everything that i found is either to simple just read or write or to complex being a full xml editor this seems like a pretty standard usage scenario so i am hoping that there is something out there,['objective-c'] +152539,fixed size buffer cannot be directly used from this object i am used a structure to represent pure data one of the fields is a fixedsize buffer as shown belowstructlayoutlayoutkindsequential pack2unsafe struct imagedosheader private fixed ushort e res4 descriptionreserved thisplaynamee res0 public ushort e res 0 get set within the getset functions i tried to do the following but i get compiler error cs16 you cannot use fixed size buffers contained in unfixed expressions try using the fixed statementreturn this e res0however the following workfixed imagedosheader p this return p e res0imagedosheader local thisreturn local e res0i can easily use the workarounds however i am wondering why directly accessing the fixedsize buffer from this is illegal or is this a bug that i should reporti am using net 20,['c#'] +152541,adding libxml2 in xcode i have added libxml2 to my xcode 4 project following this guidebut it is not working xcode gives me error saying it no such libxml2 directory what am i doing wrong heres the screenshots of the target settings of my projectthanks,['objective-c'] +152546,adding a controller with readwrite actions and views using entity framework what is data context class so in visual studio when i go to add a controller i get this dialogi was curious what visual studio would create if i chose controller with readwrite actions and views using entity framework as i am using efso i set my model class to a view model created chose razor for my views but i do not know what data context class is the only thing in the dropdown is my view model i created,"['c#', 'asp.net']" +152555,why does this generics scenario cause a typeloadexception this got a bit longwinded so heres the quick versionwhy does this cause a runtime typeloadexception and should the compiler prevent me from doing itinterface i void footclass ct1 public void foot2 where t2 t1 class d csystemobject i the exception occurs if you try to instantiate dlonger more exploratory versionconsiderinterface i void footclass ct1 public void foot2 where t2 t1 class some other class class d csome other class i compiler error cs0425this is illegal because the type constraints on cfoo do not match those on ifoo it generates compiler error cs0425but i thought i might be able to break the ruleclass d csystemobject i yep it compilesby using object as the constraint on t2 i am negating that constraint i can safely pass any type to dfoot because everything derives from objecteven so i still expected to get a compiler error in a c language sense it violates the rule that the constraints on cfoo must match the constraints on ifoo and i thought the compiler would be a stickler for the rules but it does compile it seems the compiler sees what i am doing comprehends that it is safe and turns a blind eye i thought i would gotten away with it but the runtime says not so fast if i try to create an instance of d i get a typeloadexception method c1foo on type d tried to implicitly implement an interface method with weaker type parameter constraints but is not that error technically wrong does not using object for ct1 negate the constraint on cfoo thereby making it equivalent to not stronger than ifoo the compiler seems to agree but the runtime does notto prove my point i simplified it by taking d out of the equationinterface it1 void foot2 where t2 t1class some other class class c isome other class compiler error cs0425 public void foot butclass c iobject compiles public void foot this compiles and runs perfectly for any type passed to footwhy is there a bug in the runtime or more likely is there a reason for this exception that i am not seeing in which case should not the compiler have stopped meinterestingly if the scenario is reversed by moving the constraint from the class to the interfaceinterface it1 void foot2 where t2 t1class c public void foot class some other class class d c isome other class compiler error cs0425 as expectedand again i negate the constraintclass d c isystemobject compilesthis time it runs fined d new ddfooint32dfoostringdfooenumdfooiappdomainsetupdfooinvalidcastexceptionanything goes and that makes perfect sense to me same with or without d in the equationso why does the first way breakaddendumi forgot to add that there is a simple workaround for the typeloadexceptioninterface i void footclass ct1 public void foot2 where t2 t1 class d cobject i void ifoot foot explicitly implementing ifoo is fine only the implicit implementation causes the typeloadexception now i can do this i d new d dfooany type i likebut it is still a special case try using anything else other than systemobject and this would not compile i feel a bit dirty doing this because i am not sure if it intentionally works this way,['c#'] +152567,locking strategies and techniques for preventing deadlocks in code the common solution to preventing deadlock in code is to make sure the sequence of locking occur in a common manner regardless of which thread is accessing the resourcesfor example given threads t1 and t2 where t1 accesses resource a and then b and t2 accesses resource b and then a locking the resources in the order they are needed causes a deadlock the simple solution is to lock a and then lock b regardless of the order specific thread will use the resourcesproblematic situationthread1 thread2 lock resource a lock resource b do resource a thing do resource b thinglock resource b lock resource a do resource b thing do resource a thingpossible solutionthread1 thread2 lock resource a lock resource alock resource b lock resource b do resource a thing do resource b thing do resource b thing do resource a thingmy question is what other techniques patterns or common practices are used in coding to guarantee dead lock prevention,['c++'] +152572,how to read lines of a file in ruby i was trying to use the following code to read lines from a file but when reading a file the contents are all in one lineline num0fileopenxtxteach do line print line num 1 lineendbut this file prints each line separatelyi have to use stdin like ruby my progrb filetxt where i cannot assume what the lineending character is that the file uses how can i handle it,['ruby'] +152626,webtrends api authentication php i am trying to connect to webtrends api using php but have not been able to authenticatethe example given on the wts documentation is for net or ruby the net example is like thisvar svc new webclient svccredentials new networkcredentialyourwebtrendsaccountwebtrendsusername yoursupersecretpassword svcdownloadstringcompleted svc downloadstringcompleted svcdownloadstringasyncnew uribaseurii am not familiar with net but is there an equivalent of that webclient class on phpi have been trying to authenticate using curl using username my account namemy login name password my password but so far no luck i get an error message saying that the parameters are not correctupdate adding code usernameurlencodemy account namemy login name passwordmy password postdatausernameusernamepasswordpassword ch curl init curl setopt ch curlopt urlperiod2011w14formatxml curl setopt ch curlopt ssl verifypeer true curl setopt ch curlopt useragent mozilla50 windows u windows nt 51 enus rv1816 gecko20070725 firefox2006 curl setopt ch curlopt timeout 60 curl setopt ch curlopt followlocation 1 curl setopt ch curlopt returntransfer 1 curl setopt ch curlopt postfields postdata curl setopt ch curlopt post 1 result curl exec ch curl closech var dumpresulti also triedcurl setoptch curlopt userpwd usernamepasswordbut no luck so far,"['php', '.net']" +152632,copying a stream in python how do i transfer the contents of a stream to another in pythonthe trivial solution would beoutputwriteinputreadbut that fails if the input file is larger than the available memory or even infinitely large and it does not work well when a partial copy is useful as well basically i am looking for the equivalent of orgapachecommonsioutilscopy,['python'] +152641,is overriding to s methods in ruby bad i have been experimenting and find that i like redefining objects to s methods is this a bad idea or is it good practice,['ruby'] +152671,custom event library for javascript are there any recommendations i am looking for a javascript library that will allow me to use custom events that i can subscribe to and fire i also need the event namescope to work similarly to that of topics in a message queue where you can subscribe to a namespace and get all events for that namespacefor examplevar mycustomeventhandler new customeventhandlermycustomeventhandlerbindmyevent functiondata consolelogevent 1 mycustomeventhandlerbindmyotherevent functiondata consolelogevent 2 mycustomeventhandlerbindmy functiondata consolelogevent 3 mycustomeventhandlertriggermyevent logs event 1 and event 3mycustomeventhandlertriggermyotherevent logs event 2 and event 3mycustomeventhandlertriggermysomethingelse logs event 3i could write something custom but i would prefer to use an open source library if there is onecheers,['javascript'] +152682,how to open phones gallery through code i wanna to open phones gallery through a button clickin my activity i have a button i want to open the gallery through that button click,['android'] +152688,relative url to a different port number in a hyperlink is there a way without javascript serverside scripting to link to a different port number on the same box if i do not know the hostnameega href8080look at the other portathis example doest work as it will just treat 8080 as a string i want to navigate to,['html'] +152701,windows phone 7 sqlite with encryption i was using systemdatasqlite for sqlite in windows mobile it has builtin encryption support i have found many sqlite implementation for windows phone 7 but none of them have builtin support for encryption anybody knows any sqlite implementation for windows phone 7 that supports encryption,['c#'] +152724,only show warnings from some folders in eclipse i am working in a larger java codebase in eclipse which currently issues around 70 warnings however i am working in rather isolated parts in a few specific source folders and namespaces i would like eclipse to only show warnings for my modules in the problems tab and not for the entire codebase currently it shows the first 100 warnings which are not related to my modules is this possibleupdatethanks for all the nice answers updated the question a bit to make it clear that i am talking about multiple albeit a rather small number of folders and namespaces,['java'] +152734,how to add a gridview column on codebehind i am trying to add a column to a gridview in aspnet 20gridviewpococolumnsaddhowever i cant find the right option i would like equivalents to the followingaspboundfieldasptemplatefield,"['c#', 'asp.net']" +152739,eclipse c hello world projects error i am using a 64bit winodws 7 i have downloaded a cdt eclipse and have downloaded mingw after that i created a c hello world projectthis is the codeinclude iostreamusing namespace stdint main cout hello world endl this is supposed to print hello world return 0but when i want to run it this error pops uplaunch failed binary not foundany help would be highly welcomed,['c++'] +152749,c how to replace an accent insensitive string with regex i would like to perform an accentinsensitive replace in a string i want client to match cliant and vice versamy code looks like thisregex reg new regexclientstring result regreplacehere goes the content with client and cliant replacementwithso how do i make sure that client matches client and cliant and vice versa,['c#'] +152754,capturing group with findall how can i access captured groups if i do findallrregexwithcapturinggoeshere i know i can do it through finditer but i do not want to iterate,['python'] +152773,jquery datepicker limit mindate according to previous calendar i have 2 datepickers as followingfunction datepicker1 datepicker2 datepicker mindate today maxdate 90d showon button buttonimage imagescalendargif buttonimageonly true dateformat d dd mm yy i want datepicker2 have the minimumdate value selected in the first calendar 1 dayie if first calendar date was may 16th 2nd calendar should have the min date set to may 17th,['jquery'] +152781,mouseup event on drag i have a link which has mousedown and mouseup handlers to animate some objects on page when dragged drag and drop link fires mousedown event but it does not fire mouseup when released is there a workaround for this problemhere is a example if you click link normally it works but when you drag the link mouse up does not happen,"['javascript', 'jquery']" +152802,what are some advantages thisadvantages of type inference in c i have a coworker that is against type inference in c i believe most of his arguments surrounded lack of readability my argument against that is that visual studios intellisense features provide a simple way of viewing types and reading them from the code is not as necessary as it might be if we were coding out of notepadhowever i am curious about the advantages and thisadvantages of using type inference in c i come from c and i know that c0xs auto has a more objective benefit in that you do not always know the types youre getting especially when doing heavy template programming an example is using auto to store the value of boostbindin c type inference does not seem to be as much of a requirement so much as it is a nice to have or sugarcoating feature i think it would be useful for when you are dealing with long types eglazylistmynamespaceisomeverylonginterfacetype myvar objgetlazyit would bevar myvar objgetlazythis is much cleaner in my opinion however are there any objective arguments for or against type inference is it good programming practice to use it even in situations where it is arguable that it provides no benefit eg using var instead of intsome help in understanding how i should use var in my daytoday coding would be great,"['c#', 'c++']" +152819,showing androids soft keyboard when a field is focusd using javascript in a webpage i have got a search field i have added a clear button so that users can clear the search field and start again as a convenience i focus the search fields text box and the cursor does appear in the box however the soft keyboard does not seem to show up on android devices that use the default browser in ios and opera mobile it works as i would expectis there an additional method i can call that will cause the keyboard to show on androids browser so the user can start typing right awayfunction clear search ifsearchinputval searchinputval searchinputfocus,"['javascript', 'jquery', 'android']" +152823,android how to maintain aspectratio in animation the animation i am running inside an imageview refuses to maintain the aspectratio of the image frames the following answers in so are quite informative but do not seem to work for mehow to scale an image in imageview to keep the aspect ratiohere is the codeprivate void startanimation mimageviewsetadjustviewboundstrue mimageviewsetscaletypescaletypecenter mimageviewsetbackgroundresourceranimmy animation animationdrawable frameanimation animationdrawable mimageviewgetbackground start the animation looped playback by default frameanimationstartranimmy animation is just an animation listanimationlist xmlnsandroidandroidididselectedandroidoneshotfalseitem androiddrawabledrawablephoto 1 androidduration100 item androiddrawabledrawablephoto 2 androidduration100 and so onanimationlist,['android'] +152853,cookie vs session based flash message a neat feature which i found in cakephp was the ability to set a flash message say on some save script then have that message thisplayed on the following page something like post updated or error no file foundthe way cake does it is with this session object i am trying to avoid sessions like the plague because of their odd requirements for scalability can i not just simply store the flash message in a cookie client side and then delete that cookie once it is thisplayed on the following page what would be some proscons to this approach or more simply why does cake uses session i am assuming that relates to the session collectioncheersps in my implementation i also make it fade out with a settimeout command in javascript i find that is a nice way to end the whole process,['php'] +152861,c nested include avoiding include nested too deeply error what is the best way of declaring my header files if i want to have the following connections in my c code just so that i do not get the include nested too deeply error on my edge class i have some functions that need to return a node object same for the edge class i have functions that need to return a node object however the compiler thisallow me to have this nested loop thing nodeh ifndef node h define node h include edgeh public node node void setnamestring string getname void addedgeedge vectoredge getedges return edges endifedgeh ifndef edge h define edge h include nodehclass edge public edge edgebool edge bool hasbeenseen return seen void reset seen false resets seen param to false node getsource return source node gettarget return target void setsourcenode source source source void settargetnode target target target endif,['c++'] +152862,how do i use fftw plan many dft on a transposed array of data i have a 2d array of data stored in columnmajor fortranstyle format and i would like to take the fft of each row i would like to avoid transposing the array it is not square for example my array fftw complex data new fftw complex21256contains entries r0 val0 r1 val0 r20 val0 r0 val1r20 val255i can use fftw plan many dft to make a plan to solve each of the 21 ffts inplace in the data array if it is rowmajor eg r0 val0 r0 val1 r0 val255 r1 val0r20 val255int main int and 256 int howmany 21 fftw complex data new fftw complexnhowmany fftw plan p this plan is ok p fftw plan many dft1nhowmanydatanull1ndatanull1nfftw forwardfftw measure do stuff return 0according to the documentation section 441 of the fftw manual the signature for the function isfftw plan fftw plan many dftint rank const int n int howmany fftw complex in const int inembed int istride int ithist fftw complex out const int onembed int ostride int othist int sign unsigned flagsand i should be able to use the stride and thist parameters to set the indexing from what i can understand from the documentation the entries in the array to be transformed are indexed as in jistride kithist where j0n1 and k0howmany1 my arrays are 1d and there are howmany of them however the following code results in a seg fault edit the stride length is wrong see update below int main int and 256 int howmany 21 fftw complex data new fftw complexnhowmany fftw plan p this call results in a seg fault p fftw plan many dft1nhowmanydatanulln1datanulln1fftw forwardfftw measure return 0updatei made an error choosing the stride length the correct call is the correct stride length is howmany not nint main int and 256 int howmany 21 fftw complex data new fftw complexnhowmany fftw plan p ok p fftw plan many dft1nhowmanydatanullhowmany1datanullhowmany1fftw forwardfftw measure do stuff return 0,['c'] +152863,answer incoming phone call from my application i want to make my application answer the phone calls so i can have the ability to do some processing before allowing the user to answer maybe just thisplay my activity over the incallscreen but i cannot accomplish thiswhen i used intentfilter with action androidnameandroidintentactionansweraction when incoming call the incallscreen start and not my activity and when using broadcastreciever with action androidnameandroidintentactionphone stateaction i cannot use abortbroadcast method because its nonordered broadcastany help pleaseedit 1i managed to thisplay my activity over the incallscreen by wait 1 second before starting my activity in onreceive of broadcastreceiver method but the incallscreen is thisplayed first for portion of time which may allow the user to answer before the processing start and if i reduced the time to wait this may cause incallscreen to be thisplayed above my activity any other solution will be appreciated,['android'] +152875,gradle zip task to do multiple subtrees were trying to build up a minorly complicated zip file in gradle from multiple filesystem source trees but no matter how many into specifications we give it all puts them in the same one is this possible to do in gradlebuildlibsfoojar foojarbar barwere getting this insteadbuildlibsfoojar barfoojarbar barusing thistask installziptype zip dependson jar frombuildlibsfoojarinto frombarintobarany help would be appreciatededit gradle 10milestone3,['java'] +152876,how do i grab an element with jquery without a way to reference it via class id etc i have a table like sotablethead tr thhostnameth thactionth trtheadtbody tr td127001td tda namedelete onclickremove host127001removeatd tr tr td127002td tda namedelete onclickremove host127002removeatd tr tr td127003td tda namedelete onclickremove host127003removeatd trtbodywhat i am trying to do is when a user clicks on remove that the link is replaced with one of those loading images so the user cannot repeatedly hit the linkhow do i get the a element so to speak so i can set the html accordingly with jqueryon other parts of the site i am able to attach a relhost1 or similar to the link so i can easily reference it to change out the html,"['jquery', 'html', 'css']" +152889,jaxb xmlelements to have minoccurs 1 so i want to have a list to be annotated with xmlelements like the following xmlelements xmlelementname apple type appleclass xmlelementname orange type orangeclass xmlelementname mango type mangoclass public listfruit getentries return fruitlisti am wondering whether there is a way to enforce the list to contain at least 1 element because right now the xsd looks likexscomplextype namefruitlist xssequence xschoice minoccurs0 maxoccursunbounded xselement nameapple typetnsapple xselement nameorange typetnsorange xselement namemango typetnsmango xschoice xssequence xscomplextype,['java'] +152903,how can i create a url based on controller and action method in spring mvc i am using spring mvc 30i have a guestbookjsp page where i want to create a link that points to guestbookcontrollers login methodthis is a simple task that most web frameworks handle this eg grails does it with glink tag but i could not find any documentation on this in the official springmvc docs so i am scratching my head is this functionality in some tag library does the framework expose it do i have to extend the framework to get this to worknote i am not taking about hardcoding the url which is an obvious but weak solution but rather generating it based on controller and action nameupdatespring mvc does not provide this functionality there is a jira ticket though you can vote here,['java'] +152917,opengl es texture coordinates slightly off i am trying to draw a subregion of a texture in opengl by specifying the coordinates i want whats happening though is that depending on the size of the image it seems there is a slight offset in the origin of where it selects the texture coordinates the offset amount seems to be less than the size of a pixel the output is is blurred combination of neighboring pixelsheres an idea of what i am describing in this case i would want to select the 6x5 greenwhite region but what opengl is rendering includes a slight pink tint to the top left pixelswhat the output would look likei can fix it by adding an offset to the texture coordinates before passing them to gltexcoordpointer but the problem is that i have no way to calculate what the offset is and it seems different for different texturespseudocodefloat ufactor regionwidth texturewidth for the example 06ffloat vfactor regionheight textureheight for the example 05fdata0t0 00f ufactordata0t1 00f vfactordata1t0 10f ufactordata1t1 00f vfactordata2t0 00f ufactordata2t1 10f vfactordata3t0 10f ufactordata3t1 10f vfactorglpushmatrix translatescalebind operationsgltexcoordpointer2 gl float 0 data0t,['c++'] +152923,how to securely create php variables with extract in my previous post i ask how to create variables from an array php variables made with foreach i got several answers and i was testing extract but i have seen several against it for security reasonsnow my question here is how can i use extract in a secure way from a post that has an array that was made using jquery serializedwith secure i mean that if a user inputs the wrong data the secure way can take care of that with no problemsthe php site has a small warning in the extract command the says the followingdo not use extract on untrusted data like user input ie get files etc if you do for example if you want to run old code that relies on register globals temporarily make sure you use one of the nonoverwriting extract type values such as extr skip and be aware that you should extract in the same order that is defined in variables order within the phpiniit warns about the use but does not provide an example at least of how to solve the user of extract in a secure way,['php'] +152948,does heroku protect individual sites from dos ddos attacks heroku is it seems under a ddos attack right now which is causing intermittent availability issues across the site manifesting themselves on of course my appi have seen a number of these kinds of attacks recently including the huge ddos attack on registercom a few months agomy question is what were to happen if attackers zeroed in on one of herokus clientsdoes heroku protect individual apps from dos and ddos attacks,['ruby-on-rails'] +152958,instruct browser to only prompt for saving usernamepassword when they have logged in successfully i noticed that some site would trigger the browser to prompt for saving usernamepassword only when they have logged in successfully how to achieve that response with http 401 403 on error along side with the login form with error messageright now when i try logging in with invalid usernamepassword the server will redirect the browser back to the login form with some error message that indicates to the user that the usernamepassword is incorrect but the browser would ask if the client want to save the usernamepassword which is inappropriatethank you,['php'] +152971,java how to suppresswarnings unreachable code sometimes when you are debugging you have unreachable code fragment is there anyway to suppress the warning,['java'] +152976,how to ignore case in stringreplace string sentence we know it contains camel word camel can be in different casesstring s1 camelstring s2 camelstring s3 camel string s4 camel string s5 camelhow to replace camel in sentence with horse despite of stringreplace does not support ignorecase on left string,['c#'] +152995,how to use unix pipes in android i need to send some data to a c program from my app in android and i think about using pipes i read that java can access to existing pipes and open them as if it is a normal file but i am unable to do such a thing in my application when i try the app just block until the message wait close appears without writing anything special on logcati found a thread on android mailing lists about this subject but it was not very clear and it refers to a folder that does not exist on my phonefurthermore i know it is not possible to make pipes on the sdcard but when i try to do so indata i think i have root issuesa do you know if it is possible to access to that pipe i try in and out of the app folder without successi made the pipe with mkfifo and the permissions seems ok to be open by any userprwrwrw root root 201018 0453 video pipei tried to add the x permission who knows here is what i have back chmod ux video pipe bad modethe code that blocks is the camera initialisation path is just the path to the piperecordersetoutputfilepathhere is the whole source commit 22dba257f6thanks for your help,['android'] +153006,inconsistency in receiving push notification i found some weird behavior in push notification my ipod app receives push notifications till last week with no issues then i found that my app is not receiving push notifications and i changed the certificates and it worked fine and after 2 days its not working and i repeated the same process and same kinda problem i was wondering why this happens note i am using my own java based server to send push notification i am sure that my certification are not expired at the time of this problem the badge id is also not visible with my application iconthanks in advance,['iphone'] +153034,is it possible to get reference to comment elementblock by javascript this sounds a little crazy but i am wondering whether possible to get reference to comment element so that i can dynamically replace it other content with javascripthtmlheadheadbodydiv idheaderdivdiv idcontentdiv sidebar place holder some idbodyhtmlin above page can i get reference to the comment block and replace it with some content in local storage i know that i can have a div place holder just wondering whether it applies to comment block thanks,['javascript'] +153039,python how to read a static file from inside a package could you tell me how can i read a file that is inside my python packagei have a following situationa package that i load has a number of templates text files used as strings that i want to load from within the program but how do i specify the path to such fileimagine i want to read a file from packagetemplatestemp filesome kind of path manipulation package base path trackingthanks,['python'] +153061,what does this lambda expression do just come across the following line of code and having a hard time finding documentation for it is it a lambda expression what does this dotemp regexreplaceurl regex cookie replacematch cookievaluesmatchgroupscookievarvaluespecifically interested in the,"['c#', '.net']" +153062,how to assert an actual value against 2 or more expected values i am testing a method to see if it returns the correct string this string is made up of a lot of lines whose order might change thus usually giving 2 possible combinations that order is not important for my applicationhowever because the order of the lines might change writing just an assert statement will not work since sometimes it will pass the test and sometimes it will fail the testso is it possible to write a test that will assert an actual string value against 2 or more expected string values and see if it is equal to any of them,['java'] +153074,passing value from dialog form to main form possible duplicatehow do you pass an object from form1 to form2 and back to form1 i am used to passing variables between windows forms by simply passing them as a parameternow i have a form that is already open let us call it formmain and another form that should act like a dialog formtask the user cannot interact with the main form until he has filled in the information on formtask formtask simply contains a single textbox and the value of this textbox should be returned to formmain and kept track of as a variable formtask requires a parameter exercisetype when formtask opens it checks the value of this parameter and sets the default value of the textbox accordingly this already works i am just kind of clueless on how to return my string value to the already open mainformthese dialogs only seem to be able to return dialogresults which is not what i am after i am not too experienced either and i would rather avoid fumbling around to make my own custom dialogformmainformtask formtask new formtaskexercisetypeformopgaveinvokershowdialogformtaskprivate void button1 clickobject sender eventargs e string opgave textboxopgavetext return string value to mainform here,['c#'] +153121,control access to files based on db values with phpapache what i wanti am making a system where when a user uploads an image it goes to the folder images where there is two copies of the image a thumb and a bigger onenow when a user uploads an image it is done alongside insertion of a row in a mysql database where the image gets an id and the row holds a value that determines if the images is available to the public or not 1 for only thumb available 2 for both along with the owneradmin of the imagewhat i want to do is if a user tries to reach the image by going to the images url and the value in the database says that it should not be publicly available and the session of that user is not the owner of the image admin not logged in it should either say image not found or access deniedwhat i imagineif it could be done with php i imagine something like thisuser tries to go to url imagesimageid thumbjpgifimgaccess 1 sessionadmin id imgowner id show image thumbelse access deniedi could maybe hide the images in a htaccess protected folder make a imgae getphp that accepts url variables sees if the image is available and loads the image if so i just want to avoid having to derecompile the image and other server power consuming processesmy question is can i control the image like this is there a way to make a php script appear as an image it loads internallyor is there maybe some otherbetter way than through php apache maybe any suggestions is much appreciated,['php'] +153152,any good libraries for doing tearaway tabs in java was thinking about implementing tearaway tabs on a java project i am working on wondering if there are any libraries out there that make it easy or if i am on my own,['java'] +153166,selenium 2 open link in new tab and close tabs i want to be able to open a link in a new tab in selenium 2 also i want to close the tab when i am finished interacting with the page how is this possible if i have a webelement of an a tagi am using the java api of selenium 2 with the firefox driver running on firefox 4,['java'] +153187,equivalent of data protection api on linux microsoft windows 20 and later versions expose the data protection api dpapi that encrypts data for a peruser or persystem context the caller does not provide a key with which to encrypt the data rather the data is encrypted with a key derived from the user or system credentialsthis api is conveniently exposed in net via the protecteddata class encrypts the data in a specified byte array and returns a byte array that contains the encrypted datapublic static byte protect byte userdata byte optionalentropy dataprotectionscope scope decrypts the data in a specified byte array and returns a byte array that contains the decrypted datapublic static byte unprotect byte encrypteddata byte optionalentropy dataprotectionscope scopeis there an equivalent api on linux a bonus would be that it integrates conveniently with javawhat are my alternatives if there is not one,"['java', '.net']" +153191,how to capture the key event from a view i am trying to capture the key event from a view as followsmyview backboneviewextend el somediv initialize function initialize some subviews render function return this events keypress somediv showkey showkey functione consolelogekeycode that does not work ps there a no input elements in the view or its subviews i just need to know if the user presses any key and then do something on the view,['javascript'] +153192,speed of paged queries in oracle this is a neverending topic for me and i am wondering if i might be overlooking something essentially i use two types of sql statements in an applicationregular queries with a fallback limitsorted and paged queriesnow were talking about some queries against tables with several million records joined to 5 more tables with several million records clearly we hardly want to fetch all of them that is why we have the above two methods to limit user queriescase 1 is really simple we just add an additional rownum filterwhere and rownum that is quite fast as oracles cbo will take this filter into consideration for its execution plan and probably apply a first rows operation similar to the one enforced by the first rows hintcase 2 however is a bit more tricky with oracle as there is no limit offset clause as in other rdbms so we nest our business query in a technical wrapper as suchselect outer from select from select inner rownum as rnum maxrownum overpartition by 1 as total rows from user sorted business query inner where rownum outerwhere outerrnum note that the total rows field is calculated to know how many pages we will have even without fetching all data now this paging query is usually quite satisfying but every now and then as i said when querying 5m records possibly including nonindexed searches this runs for 23minutesedit please note that a potential bottleneck is not so easy to circumvent because of sorting that has to be applied before pagingi am wondering is that stateoftheart simulation of limit offset including total rows in oracle or is there a better solution that will be faster by design eg by using the row number window function instead of the rownum pseudocolumn,['sql'] +153200,how to get uiview given a cgpoint i am trying to find a way to get a particular uiview given a cgpoint briefly i want to do a hit testfor example i have a uiview which has many subviews whose sizes are smaller than the parent uiview what i want to do is when a touchmoved event happens to check the other subviews around the touched subviewfor that purpose it would be nice to be able to convert a cgpoint to a subview uiviewi am new to objectivec is there good way to do it any suggestion would be really helpful,"['objective-c', 'ios']" +153207,what is the most reasonable way to find out if entity is attached to dbcontext or not when i try to attach entity to context i get an exceptionan object with the same key already exists in the objectstatemanager the objectstatemanager cannot track multiple objects with the same keythis is expected behaviourbut i would like to know how objectstatemanager knows that i would like to do this check by myself before,['c#'] +153232,compiling with cython and mingw produces gcc error unrecognized command line option mnocygwin i am trying to compile a python extension with cython in win 7 64bit using mingw 64biti am working with python 26 active python 266 and with the adequate thistutilscfg file setting mingw as the compilerwhen executing cpython26programascythonpython setuppy build ext inplacei get an error saying that gcc has not an mnocygwin option cpython26programascythonpython setuppy build ext inplacerunning build extskipping hello2c cython extension uptodatebuilding hello2 extensioncmingwbingccexe mnocygwin mdll o wall icpython26include icpython26pc c hello2c o buildtempwinamd6426releasehello2ogcc error unrecognized command line option mnocygwinerror command gcc failed with exit status 1gcc iscgcc versiongcc gcc 470 20110430 experimentalcopyright c 2011 free software foundation inchow could i fix it,['python'] +153233,before filter with devise i am using devises built in before filter authenticate user i want to call my own custom method in my application helper if a user fails the before filter tries to do an action when logged out how and where can i do this,['ruby-on-rails'] +153234,how do i read a file in app engine i have a file at webinfconfigtxt on app engine what is the path to the file on app engineeg new filewhat path do i put here,['java'] +153282,gpu accelerated math in the browser i am starting a project for browsers which requires some complex data processingthe algorithm i am using is 50100x faster when accelerated with gpui could use javascript flash or other technologies with the browseris there any way i can access the gpu to accelerate the processing of my math,"['javascript', 'html']" +153284,is there a way to force phpinfo to output its stuff without formatting just like in cli mode but of course in normal mode not cli formated output included among other html destroys existing webpage layout,['php'] +153292,repository unitofwork pattern for entity framework i was searching the net up and down and i did not manage to find a suitable design for my applicationi am looking for repositoryunitofwork pattern that will manage connections and thispose them automatically when donei need to support both web application where each request will have its own unitofwork and windows application where each thread will have its own unitofwork i need the patters to thispose automatically the unitofwork whrn requestthread is donei also would like to support rolback in case of exceptionright now i use structuremap so i do not care to continue use it in the suggest answersthe reason i need repository pattern is to achieve all the abilities i need to all my entitiesthe reason i need unitofwork is to allow changes in more then one entityi will really appriciate any helpthanks,"['c#', '.net']" +153294,parallelforeach slower than foreach here is the codeusingvar contextnew aventureworksdatacontext ienumerablecustomer customerquery from c in contextcustomers where cfirstnamestartswitha select c var watch new stopwatch watchstart var result parallelforeach customerquery cconsolewritelinecfirstname watchstop debugwritelinewatchelapsedmilliseconds watch new stopwatch watchstart foreach var customer in customerquery consolewritelinecustomerfirstname watchstop debugwritelinewatchelapsedmilliseconds the problem is parallelforeach takes about 400 ms vs a regular foreach takes about 40ms so what exactly am i doing wrong why does not this work as i expect it,['c#'] +153301,powermock mockito vs mockito alone can anyone please summarize what exactly features gives you adding powermock on top of the mockitoso far i have found thesemock static final and private methodsremove static initializersallow mocking without dependency injection this one is not clear to me can you elaboratedoes it add anything else can you please sum up in several linesand do i need to sacrifice something when using powermock,['java'] +153309,why does the php version run faster than mysql i have two very large tables to merge and so i have been trying to optomize the update for speed i noticed that doing the update partially in php speeded it up significantly so i assumed this means i am not be doing the mysql properlyi have simplified the problem to try and narrow it down grid table postcode tableidno lat lng nearestpostcode postcode lat lng 1 571 23 ab12 3ba 563 252 568 19 ab12 1ya 562 23 200 entries 350 entriesi want to update the grid table with the nearestpostcode from the postcode table using latitude lat and longitude lng to find the nearest postcode to each grid pointupdate grid table set nearestpostcode select postcode from postcode table where lat grid tablelat 037 and lat grid tablelat 037 and lng grid tablelng 068 and lng grid tablelng 068 order by powlat grid tablelat2 powlng grid tablelng 05462 limit 1 the idea is that the where clause speeds up the search by using indexes to narrow the set down to a few candidates and then the order by clause finds the nearest one within this setthis mysql update takes 30 secs but if i instead update each grid table row individually in php it is over in the blink of an eye querystg select from grid table sqlquery1 mysqli querymysqlilink querystgwhile sqlrow mysqli fetch assoc sqlquery1 idno sqlrowidno lat sqlrowlat lng sqlrowlng querystg update grid table set nearestpostcode select postcode from postcode table where lat lat 037 and lat lat 037 and lng lng 068 and lng lng 068 order by powlat lat 2 powlng lng 0546 2 asc limit 1 where idno idno sqlquery2 mysqli querymysqlilink querystgsurely the mysql version should be faster than the php version here is the mysql for the tablescreate table grid table idno int11 not null auto increment lat float64 not null comment latitude lng float64 not null comment longitude nearestpostcode char8 not null primary key idno index lat lng lat lngenginemyisamrow formatdefaultauto increment30047create table postcode table postcode char8 not null lat float64 not null comment latitude lng float64 not null comment longitude primary key postcode index lat lat index lng lng index lat lng lat lngenginemyisamrow formatdefaultmysql import file is here cm2y2zdk1y2ytmgq3yy00otixltk0zdatzme2nmq3ytc1zwrmhlenif you run the update 10 nearestpostcodes will be addedupdate after answersi ran thisexplain extended select postcode from postcode table where lat 570 and lat 570074 and lng 2013 and lng 2 order by powlat 570 2 powlng 2 0546 2 asc it returnedidselect typetabletypepossible keyskeykey lenrefrowsfilteredextra1simplepostcode tablerangelatlnglat lnglat lng8null6510using where using filesortremoving the order by caluse no difference in speedsimplifying the where clause by removing lng iewhere lat between grid tablelat 037 and grid tablelat 037 faster 3 secs rather than 30 secsusing spatial column and index see below much slower 190 sec not sure if i implemented this correctly thoughalter table grid table add column coords point not nullupdate grid table set coords pointlat lngalter table grid table add spatial index coords coordsalter table postcode table add column coords point not nullupdate postcode table set coords pointlat lngalter table postcode table add spatial index coords coordsanalyze table grid tableoptimize table grid tableanalyze table postcode tableoptimize table postcode tableupdate grid table set nearestpostcode select postcode from postcode table where mbrcontainsgeomfromtextconcat polygon grid tablelat 037 grid tablelng 068 grid tablelat 037 grid tablelng 068 grid tablelat 037 grid tablelng 068 grid tablelat 037 grid tablelng 068 postcode tablecoords order by powlat grid tablelat2 powlng grid tablelng 05462 limit 1,"['php', 'mysql']" +153319,rails bundle install via proxy on windows i am trying to run bundle install from behind a proxy in windows it is not working is there a setting somewhere i can change to make it happeni know the proxy is the issue because it worked before and that is the only thing that could have messed things up,['ruby-on-rails'] +153350,cannot find facebook contacts in rawcontacts i am trying to build a contactsmanaging application on my phone i have contacts from a couple of accounts including facebook and htc facebook for some reason i cannot retrieve these contacts from the rawcontacts table of contactscontractmanagedquerycontactscontractrawcontactscontent uri new string contactscontractrawcontacts id contactscontractrawcontactscontact id contactscontractrawcontactsaccount name contactscontractrawcontactsaccount type contactscontractrawcontactsaccount type comfacebookauthlogin null nullthis query returns no results if i repace the account type with comhtcsocialnetworkfacebook i still get no results there are many facebook contacts on my phone how to retrieve them,['android'] +153351,how is llvm isa implemented from rtti exceptionsllvm does make extensive use of a handrolled form of rtti that use templates like isa cast and dyn cast this form of rtti is optin and can be added to any class it is also substantially more efficient than dynamic casthow is isa and the others implemented,['c++'] +153362,aes encrypt in nodejs decrypt in php fail in nodejs i use the build in function to encrypt data like thatvar text yesvar password 123456var encrypt cryptocreatecipheraes256cbc passwordvar encryptoutput1 encryptupdatetext base64 base64var encryptoutput2 encryptfinalbase64var encryptedtext encryptoutput1 encryptoutput2the output encrypted text is onninwxf6u8xmlgkjj48iathen i use decrypt it in phpencrypted onninwxf6u8xmlgkjj48iaor encrypted base64 decodeonninwxf6u8xmlgkjj48ia dtext2 mcrypt decryptmcrypt rijndael 256 key encrypted mcrypt mode cbcecho decrypted dtext2i will get some funny characters which i cannot decrypted it i tried withwithout base64 decode or mcrypt rijndael 128 all failthen i check how the encryption in php it looks very different from the output from nodejstext yes key 123456 etext mcrypt encryptmcrypt rijndael 256 key text mcrypt mode cbc echo encrypted etext n echo base64 base64 encodeetext n dtext1 mcrypt decryptmcrypt rijndael 256 key etext mcrypt mode cbc echo decrypted dtext1 nnit can encrypt and decrypt and the encrypted data is njcefk3pld1jfiquyva6w5hqbutbit3m7lacetmwhich is very different from the output from nodejs please advise how i can encrypt and decrypt between nodejs php thanks mel here is what i have in phptext yeskey 32byteslongkey560123456789abcdef iv sixteenbyteslong open the cipher td mcrypt module openmcrypt rijndael 128 mcrypt mode cbc intialize encryption mcrypt generic inittd key iv encrypt data etext mcrypt generictd textecho encrypted data etext necho base64 base64 encodeetext n terminate encryption handler mcrypt generic deinittd initialize encryption module for decryption mcrypt generic inittd key iv decrypt encrypted string dtext mdecrypt generictd etext terminate decryption handle and close module mcrypt generic deinittdmcrypt module closetd show string echo trimdtext nhowever it still does not workthe encrypted base 64 in php is 80022agm44qqtigu5ojdqthe encrypted base 64 in nodejs is eoyrm5sck7epe847cwkffqthus i cannot decrypt the nodejs one in php i wonder if it is because nodejs does not require iv,['php'] +153365,css backgroundposition not working i have 3 a tags thisguised as roll over buttonsdiv idbuttons a classbutton idbut1 hrefa a classbutton idbut2 hrefa a classbutton idbut3 hrefadiveach button is getting its initial image from the css as followsbutton backgroundurltheimagejpg widthheight etcnow when i try to assign initial background position for each specific element as suchbut1 backgroundposition0 0but1hover backgroundposition0 50pxbut2 backgroundposition0 100pxbut2hover backgroundposition0 150pxbut3 backgroundposition0 200pxbut3hover backgroundposition0 250pxthe issue each button defaults to position 0 0note that the hover positions work as expectedi am kind of sick right now so this is probably an oversight but i have been stairing at this for an hour now and cannot figure it out any thoughtsthanksedit pastebin love,['css'] +153388,is there any harm in calling free for the same pointer twice in a c program if i have a c program likesometypeptr my typemy type mallocsizeofsometype do stuff freemy type do a bunch of more stuff freemy typedoes the calling of free for my type do any harm after i call freemy type does the pointer become a null pointer once again,['c'] +153399,how to generate json programatically using json framework for iphone i am creating an application in that i need to send a json to the server to get some responsecan any one help me out how to generate json using json framework for iphone any other way if possible then please suggest me or provide me some code or tutoriali tried to find out but can not get the solutions,"['iphone', 'objective-c']" +153421,thisplay an image contained in a byte with aspnet mvc3 i have a view with a strong type this strong type has a field consisting of a byte this array contains a pictureis it possible to thisplay this image with something like htmlimagemodelmyimage thank you very much,['c#'] +153431,cardio graph for android i want to make an app which shows cardio graph in real time that means i want to measure heart bit and want to show the bit rate in graph in my application but i wondering to draw the cardio graph i have gone through many sample graph codes but dint get any clue to draw cardio graph is there any clue from any bodythanks regards,['android'] +153433,how to check if a file exists under include path you get the current include path in php by using get include pathi am wondering what is the lightweight way to check if the file can be included without issuing a php error i am using yii framework and i want to an import without issuing php error but i fail,['php'] +153446,which exception should i throw when building cache fail i have a class that contains a cache set and the cache is built on instantiation i am confused which exceptionerror should i throw if building cache fail cannot connect to database or someclass provider public provider buildcache private void buildcache try thiscache getdatafromdb catch exception ex throw new one exception comes in my mind is exceptionininitializererror but javadoc says it is thrown on initialize static membersshould i throw an illegalstateexception cause the cache is not built so this class is uselessclearly i can create my own erroronbuildingcache and throw it but i wonder if any exception in java library suits this circumstance,['java'] +153450,wsservlet classnotfoundexception error on tomcat 7011 using metro 21 i am trying to create a simple webservice using tomcat 7011 on windows server 2008 r2 using metro 21 i am coming from a cwcf background trying to get a better understanding on web service interopability i am actually following an example from martin kalins book java web services up and running i have the followingcatalina homectomcat7011in the catalinaproperties file i haveserverloadercmetro21binjar note i also tried adding this path to commonloader tooi have copied to the following metro jar files to calalina homelibwebservicesapijar webservicesextrajar webservicesextraapijar webservicesrtjar webservicestoolsjarand to calalina homeendorsedwebservicesapijarnote i originally tried using the metroontomcatxml ant file but it does not seem to have been updated for tomcat 7i have also copied webservicesapijar to java homejrelibendorsedi have tried putting the other metro jars in the above locations aswell too but to no helpnow tomcat starts up ok and initializes metro ok heres the relevant section from the catalina log fileinfo deploying web application directory root 18may2011 080055 comsunxmlwstransporthttpservletwsservletcontextlistener contextinitialized info wsservlet12 jaxws context listener initializing 18may2011 080107 comsunxmlwsservermonitorbase createroot info metro monitoring rootname successfully set to comsunmetropptypewsendpointnametempconvertimplservicetempconvertimplport 18may2011 080108 comsunxmlwstransporthttpservletwsservletdelegate info wsservlet14 jaxws servlet initializingso from that youd think that tomcat had loaded all the metro classes from what i have gathered wsservlet is part of jaxws 21 which is shipped as part of metro so it should have been loaded but when i actually try to browse to the wsdl of my service i get the following in the localhost logsevere allocate exception for servlet tempconvertws javalangclassnotfoundexception comsunxmlwstransporthttpwsservlet at orgapachecatalinaloaderwebappclassloaderloadclasswebappclassloaderjava1676 at orgapachecatalinaloaderwebappclassloaderloadclasswebappclassloaderjava1521 at orgapachecatalinacoredefaultinstancemanagerloadclassdefaultinstancemanagerjava415 rest of stack tracemy sunjaxwsxml looks like thisendpoints xmlns version20 endpoint nametempconvertws implementationtimeservertempconvertimpl urlpatterntc endpointsand the relevant section from my webxml file is listener listenerclasscomsunxmlwstransporthttpservletwsservletcontextlistenerlistenerclass listener servlet servletnametempconvertwsservletname servletclasscomsunxmlwstransporthttpwsservletservletclass servlet servletmapping servletnametempconvertwsservletname urlpatterntcurlpattern servletmappingcan anyone see from that why tomcat cannot findload the wsservlet class when browsing to the service,['java'] +153461,how to concatenate multiple files for stdin of popen i am porting a bash script to python 26 and want to replace some codecat ls tr xyz date f log filter args bzip2i guess i want something similar to the replacing shell pipe line example at alap1 popenfilter args stdinwhat stdoutpipep2 popenbzip2 stdinp1stdout stdoutpipeoutput p2communicate0but i am not sure how best to provide p1s stdin value so it concatenates the input files seems i could addp0 popencat file1 file2 stdoutpipep1 stdinp0stdout but that seems to be crossing beyond use of slow inefficient pipes to call external programs with significant functionality any decent shell performs the cat internallyso i can imagine a custom class that satisfies the file object api requirements and can therefore be used for p1s stdin concatenating arbitrary other file objects edit existing answers explain why this is not possibledoes python 26 have a mechanism addressing this needwant or might another popen to cat be considered perfectly fine in python circlesthanks,['python'] +153471,how to detect shake motion in iphone on the shake of the iphone device i want some function to be called i dont know how to recognize shake so i tried some link and tried this code voidmotionbeganuieventsubtypemotion witheventuievent event ifeventtype uieventsubtypemotionshake nslogcalled selfview setbackgroundcoloruicolor greencolor boolcanbecomefirstresponder return yes but alas no luck so can you please let me know how i can do the samethanks and regards,['objective-c'] +153472,how can i use delphi code from a c application i have a delphi project and i need to write a c application but i want to use some functions from this delphi project i have not worked in delphi beforei found that i can create a dll from the delphi code and use it directly in c how can i do that or i also found some conversion tools to convert to c but it was not so good so what is the best way dll or convert,['c#'] +153473,constructing array of noncopyable objects i have a class that is inhenerently noncopyable a thread so there is no copy semantics that make sense and i want to have a largeish array of these identically constructed with a nondefault constructor note that the array is fixed sizei can only use the default constructor with c arrays unless i initialise each one independentlythread myarray128 uses default constructor wrongi can list the object constructors and parameters explicitly but that is verbose and uglythread myarray128 threadparams threadparams x 128 uglyit seems i cannot use stl vectors because the object is noncopyable event though the vector never changes size i guess the constructor actually does copyingstdvectorthread myvector128 threadparams would not compilethe way i have though of doing this is with an array of smart pointers and an initialization loop but maybe i am missing something is there any other way maybe with boost containers or a different container type,['c++'] +153490,pthread detach question till recently i was under the impression that if you detach a thread after spawning it the thread lives even after the main thread terminates but a little experiment listed below goes contrary to my belief i expected the detached thread to keep printing speaking from the detached thread even after main terminated but this does not seem to be happening the application apparently terminatesdo the detached threads die after main issues return 0include pthreadhinclude stdiohvoid funcvoid data while 1 printfspeaking from the detached threadn sleep5 pthread exitnullint main pthread t handle if pthread createhandle null func null printfthread create successfully n if pthread detachhandle printfthread detached successfully n sleep5 printfmain thread dyingn return 0,['c'] +153493,aspnet mvc and windows authentication with custom roles i am trying to implement windows authentication in my aspnet mvc2 applicationi have followed all the steps suggested by the official documentationauthentication modewindows authorization deny users authorizationi have specified ntlm authentication so far so good everything works fine i would like to check the users loggedin against my database i would like to fetch roles from my table and then manage the authorization using a custom attributei do not want to use membership and roles provider ialready have my tables usersroles in place cause they have been used for an internet app this is the intranet app in my internet app i had a form where the user inputs the data the form is posted to a controller which checks everything and creates a cookie with the user and roles of the loggedin userin my globalasax i have trapped the authenticaterequest event where i read the cookie and create a custom principal which i use all over the app to check the authorizations how can i do implement this with windows authentication,['asp.net'] +153520,format javascript current date and time possible duplicatehow do i thisplay a datetime in the users locale format and time offset hi simple question i just want to take thisdocumentgetelementbyidtimeinnerhtml new dateand format it into something legible like thismay 18 2011 745 ammaking sure it is localized to whomever might be seeing it currently it prints out as thiswed may 18 2011 074625 gmt0400 edthow do i do this,['javascript'] +153527,ffmpegc what are pts and dts what does this code block do in ffmpegc in simple terms what are pts and dts valueswhy are they important while transcoding decodeencode videos what does this code bit do in ffmpegc what is its purpose01562 istnext pts istpts picturebest effort timestamp01563 if iststcodectime basenum 0 01564 int ticks iststparser iststparserrepeat pict1 iststcodecticks per frame01565 istnext pts int64 tav time base 01566 iststcodectime basenum ticks 01567 iststcodectime baseden01568,['c'] +153537,difference between yield statement in python and myhdl i am currently learning myhdl for my summer projecti have a problem grasping the functioning of yield statement in it though its true that the myhdl is based upon python it uses its yield statement in a specialized waythe link for the same is it statesmyhdl generators are standard python generators with specialized yield statements in hardware description languages the equivalent statements are called sensitivity lists the general format of yield statements in in myhdl generators isyield clause clause when a generator executes a yield statement its execution is suspended at that point at the same time each clause is a trigger object which defines the condition upon which the generator should be resumed however per invocation of a yield statement the generator resumes exactly once regardless of the number of clauses this happens on the first trigger that occurs i am not able to comprehend it could someone please explain it in simple words or perhaps redirect me to another sourcei will be grateful if you could helpthanksregards,['python'] +153561,unable to install rails with jruby i am trying to install the rails with jruby with the following command jruby s gem install rails v 306but stuck with the error jruby limited openssl loaded gem install jrubyopenssl for full supportsystemjava2in arraycopy javalangarrayindexoutofboundsexception from defaultresolverjava1in maketime from defaultresolverjava277in create from defaultresolverjava317in handlescalar from defaultresolverjava435in orghandler from defaultresolverjava455in node import from orgyechtrubydefaultresolvers method 1 0rubyinvokernode importgen65535in call from cachingcallsitejava146in call from rubyloadhandlerjava40in handle from parserjava300in addnode from defaultyamlparserjava676in yyparse from parserjava290in yechtparse from parserjava284in parse from yparserjava152in load from orgyechtrubyyparsers method 0 1rubyinvokerloadgen65535in call from javamethodjava630in call from dynamicmethodjava186in call from cachingcallsitejava309in cacheandcall from cachingcallsitejava148in call from calloneargnodejava57in interpret from localasgnnodejava123in interpret from newlinenodejava104in interpret from interpretedmethodjava180in call from defaultmethodjava174in call from cachingcallsitejava309in cacheandcall from cachingcallsitejava148in call from calloneargnodejava57in interpret from localasgnnodejava123in interpret from newlinenodejava104in interpret from blocknodejava71in interpret from interpretedmethodjava180in call from defaultmethodjava174in call from cachingcallsitejava309in cacheandcall from cachingcallsitejava148in call from calloneargnodejava57in interpretanyone can help me to out of this error thanks in advance,"['ruby-on-rails', 'ruby']" +153569,styling form with label above inputs i would like to produce the following form stylename email subjectmessagethe html code i have isform namemessage methodpost section label fornamenamelabel input idname typetext value namename label foremailemaillabel input idemail typetext value nameemail section section label forsubjectsubjectlabel input idsubject typetext value namesubject label formessagemessagelabel input idmessage typetext value namemessage sectionformat the moment it is producingname email subject messagewhat would be the best way to do this i keep getting in a muddle my floats,"['html', 'css']" +153584,stored procedure to drop table i have created a stored procedure that will drop a table if it exists in a database when running the stored procedure with exec i am getting the following error msg 203 level 16 state 2 procedure sp dropifexists line 13 the name if existsselect 1 from sysobjects where object id object idntable name and type nu drop table table name is not a valid identifierhowever if i copy and paste the tsql that is generated into management studio it seems to be running fine can someone explain why this is not valid the fix would be nice but i am really after the why primarily the how would be nice to though thanks in advance alter procedure dbosp dropifexiststablename varchar255 asbegin set nocount on declare sql varcharmax set sql if existsselect 1 from sysobjects where object id object idn tablename and type nu drop table tablename print sql exec sqlend,['sql'] +153595,in query string messing up i was working with queries that the data is being used for the meta description update cards set meta description amys bugs address labels are printed on recycled label paper available in quantities of 30 each label is 25 x 1 inch with rounded corners where card id al007i have noticed though that the period after paper is shortening the meta description to just amys bugs address labels are printed on recycled label paper if i remove the period the entire description will show up then does anyone know how to solve this tiny dilemma,['mysql'] +153597,jtable column header not visible column header not visible in my jtable i have created a jpanel and added the jtable to the jpanelobject rowdata row1column1 row1column2 row1column3 row2column1 row2column2 row2column3 object columnnames column one column two column three jtable jtable new jtablerowdata columnnames,['java'] +153599,using spring resourceservlet to serve multiple resources simultaneously the javadoc for the resourceservlet states that it can return a list of resources but examples of this usage pattern seem to be sparse at bestwe have a webxml with the followingservlet servletnameresourceservletname servletclassorgspringframeworkwebservletresourceservletservletclass loadonstartup1loadonstartupservletservletmapping servletnameresourceservletname urlpatterncombourlpatternservletmappingwhen we make a request to url along the lines ofhttplocalhost8080appcomboresourcejsfile1jsjsfile2jswe only seem to get file1 in the responsewhat would a proper configuration be for this use case,['java'] +153607,how to loop through an json associative array in javascript i am getting a json response from the server and i have to loop through the array in javascript and get the values but i cant seem to loop throught itthe json response of the array looks like thisa a a 1 schoolsa a a 20 profilesa a a 31 statisticsa a a 44 messagesa a a 50 contactsi just want to loop through it to get the id and name and populate some values on the pagei have triedeachresponse functionkey value alertkey value and for var key in response alertkey responsekeybut neither give the right valuesthanks in advance for any helpreplyhithe response i am getting with the second loop is0 1 2 13 4 5 6 setc etcso that means its going through the whole response as a string and spliting it as keyvaluethanks,"['javascript', 'jquery']" +153613,pip specifying minor version in my requirementstxt file i want to specify that my app needs django version 13x that is either 130 or 131 or 132 etc when these come out but not 14 when it comes outwhats the syntax for this,['python'] +153617,does an allocatorconstruct loop equal stduninitialized copy in this context t is a certain type and allocator is an allocator object for that type by default it is stdallocatort but this is not necessarily truei have a chunk of memory acquired by allocatorallocaten i also have a container con of t objects say a stdvectort i want to initialize that chunk of memory with the t objectsthe location of the chunk of memory is stored in t dataare these two code examples always identicalinclude memory example 1stduninitialized copyconbegin conend data example 2stdvectortconst iterator in conbeginfor t out data in conend out in allocatorconstructout inand for these twoinclude memoryt val t could be any t value example 3stduninitialized filldata data n val example 4for t out data out data n out allocatorconstructout val,['c++'] +153628,python serial communication i am working on an arduino project and i am interfacing it with a python script due to memory limitations on the python side i have a 2 dimensional matrix containing respective x y values for coordinates and in this list is 260 coordinate pairs so in interest of clarifying the data structure for all of you pathlist00 would return the x value of the first coordinate of my list performing different operations etc on this list in python is posing no problems where i am running into trouble however is sending these values to arduino over serial in a way that is usefuldue to the nature of serial communication at least i think this is the case i must send each each integer as a string and only one digit at a time so a number like 345 would be sent over as 3 individual characters those being of course 3 4 then 5what i am struggling with is finding a way to rebuild those integers on the arduinowhenever i send a value over it is receiving the data and outputting it like so python is sending over the number 25 2aa52 python is sending the number 431 4aa321a2the arduino code isstring strint ds 4void setup serialbegin9600void loop if serialavailable0 for int i0 i4 ii1 char d serialread strconcatd char tstrlength1 strtochararrayt sizeoft int intdata atoit serialprintintdata and the python code looks like this import serial s serialserialportdevttyusbmodemfd131 baudrate9600 swritestr25i am almost certain that the problem is not stemming from the output method serialprint seeing as when i declare another int it formats fine on output so i am assuming the problem lies in how the intdata variable is constructedone thing of note that may help diagnose this problem is that if i change serialprintintdata to serialprintintdata5 my result is 2aa57 where i would expect 30 255 this 7 is present regardless of the input for instance i could write 271 to the serial and my result would look as followsfor input 2712aa771a7it appears to me that arduino is chunking the values into pairs of two and appending the length to the end i cannot understand why that would happen thoughit also seems to me that the a are being added in the for loop meaning that they are added because nothing is being sent at that current moment but even fixing that by adding yet another ifserialavailable0 conditional the result is still not treated like an integeralso would using pickle be appropriate herewhat am i doing wrong,['python'] +153639,backbonejs fetch problem cannot refresh data immediately i have such codevar mymodel backbonemodelextendvar mycollection backbonecollectionextend url url model mymodelvar coll new mycollectionthe url is correct and returns correct json but if i try to use the next codefetchclickfunction collfetch consolelogcolltojsonit shows me data only after the second click httpresponse in firebug i see after the first one it seems that data is not refreshed in timeif i put each statement in different event it works correct but i need to know the length of collection immediately how to do this,['javascript'] +153647,how to thisable validation in a httppost action in aspnet mvc 3 i have a createview like this script srcurlcontentscriptsjqueryvalidateminjs typetextjavascriptscriptscript srcurlcontentscriptsjqueryvalidateunobtrusiveminjs typetextjavascriptscriptusing htmlbeginform htmlvalidationsummarynull new class validation input classcancel typesubmit valueok input namesubmit typesubmit valuesave and a corresponding controller actionhttppostpublic actionresult createstring submit myviewmodel myviewmodel if submit null true if save button has been clicked if modelstateisvalid save model data return redirecttoactionindex else if ok button has been clicked thisable somehow validation here so that no validation errors are thisplayed in validationsummary prepare some data in myviewmodel return viewmyviewmodel and thisplay page againi have found that i can thisable clientside validation by setting classcancel on the ok button this works finehowever serverside validation still happens is there a way to thisable it in a controller action see the elseblock in the create action abovethank you for help,['asp.net'] +153650,can i apply the required attribute to fields in html5 how can i check if a user has selected something from a select field in html5i see select does not support the new required attribute do i have to use javascript then or is there something iam missing,['javascript'] +153655,how do i specify the interface language for ckeditor jquery version my code atm is this simpledocumentreadyfunction textareackeditorit works flawlessly i just need to add one more thing i need to specify the interface language localisation i tried reading the ckeditor help site but it is not very helpfulcan anyone tell me where and how do i add any code to specify the language,['jquery'] +153660,fully qualified machine name java with etchosts i am trying get the fully qualified name of my machine windows 7 x64 in java on my machine i have updated the cwindowssystem32driversetchosts file such that it has an entry like this10442167 myserver myserverdomaincomall our systems have an entry in the etchosts file in the above format which i cannot changethe following code always returns myserver and i am never able to get the fully qualified nameinetaddress addr inetaddressgetlocalhoststring fqname addrgetcanonicalhostnamehow do i achieve this in javathanksshreyas,['java'] +153664,how to make a checkbox without a form i have been trying to make a simple app with 3 fields like this div id nameinput namedivinput id nameinputfield type text name username div id emailinput emaildivinput id emailinputfield type text name email input id termscheck type checkbox name terms the problem i am having is that i keep needing to try to wrap it in a form to get the checkbox to register as checked when it is i do not want to use a form because i do not ever want to submit anything here is the js for the checkbox as well it is always marked as uncheckedif termschecked true rest of codeis there a way to make this without using a form or is there a reason that my checkbox is never registered as checked,"['javascript', 'jquery', 'html']" +153665,can apache commons cli options parser ignore unknown commandline options i am writing a java application that takes command line arguments which are processed using apache commons cli with the gnuparser for reasons that are not interesting to get into i would like it to silently ignore unknown command line options instead of throwing a parseexception but i do not see a way to do that i see that there is a stopatnonoption boolean option on gnuparserparse but what i want is more like ignoreatnonoption where it will keep processing options after encountering an unknown tokeni could implement my own parser to accomplish this but i am surprised there is not this functionality built in so i thought i would check before going down that roadexample code for what i am talking abouttry commandline commandline parserparseoptions args stopatnonoption set to true below is also not what i want commandline commandline parserparseoptions args true catch parseexception e logerrorerror parsing arguments e throw new runtimeexceptione,['java'] +153694,rounded uiscrollview peformance this runs great on iphone 4 and 3gsscrollviewlayercornerradius 11scrollviewlayermaskstobounds yesbut on iphone 3g and ipod touch 2nd gen it makes scrolling really jerky i know there are some tricks on how to improve performance of calayer drop shadows for instance setting shouldrasterize to yes and the shadowpath property is there anything similar that can be done for calayers cornerradius,"['iphone', 'ios']" +153711,expandablelistfragment with loadermanager for compatibility package i want to make my expandablelistactivity compatible with honeycombi am wondering why there is no expandablelistfragment for the compatibility packageis there a way to make expandablelistview work with the normal fragment classhow do i load the cursors with the loadermanager,['android'] +153712,how can i escape characters in yaml how can i escape characters in yaml,['ruby'] +153716,where to place an xml file containing data within an android app i am new to android development i have an xml file with data that the app will read where should i keep this xml file should it be stored within the value folder,['android'] +153731,linearlayoutlayoutparams how to use dip i am trying to set the height of my linearlayout to 45 dip how can i do this when extending linearlayoutright now i just did linearlayoutlayoutparams params new linearlayoutlayoutparamslayoutparamsfill parent 45,['android'] +153747,thisable autorotate in jquery mobile or phonegap although cross platform development for mobile devices is so good there is not a simple option to thisable autorotate or lock into one orientation ie portrait or landscapeis there anyway either in jquery mobile phonegap xui anywhere if yes then please help its driving me nuts,"['jquery', 'iphone']" +153752,in c is there an eval function i am typing an equation into a textbox that will generate the graph of the given parabola is it possible to use an eval function my c 2010 does not have microsoftjscript,['c#'] +153756,put animated gif in overlay over mapview i have been pulling my hair out trying to get this seemingly simple task to worki need to put an animated gif in an overlay on a mapviewi have the following code animationdrawable anim animationdrawablegetresourcesgetdrawablerdrawableexplosionhowever how do i now pop that in an overlay and throw it over the mapviewcurrently to put static images i have thisclass drawableicon extends itemizedoverlay private arraylist moverlays new arraylist public drawableicondrawable defaultmarker superboundcenterbottomdefaultmarker public void addoverlayoverlayitem overlay moverlaysaddoverlay populate override protected overlayitem createitemint i return moverlaysgeti override public int size return moverlayssize which i then use as such gp is the geopoint of the spot i want to put the image indrawableicon image new drawableiconthisgetresourcesgetdrawableresourceidimageaddoverlaynew overlayitemgp mapoverlaysaddimageso how would i go about modifying this code so that when resourceid is the id of an animated gif image the gif image would play it is animation over the mapviewthanks in advance,['android'] +153766,objective c how to make background color of uitableview consistent i have been trying to set the background color of my table view but am facing an issuethis is what i am trying to doset background color of table view translucentselftableviewbackgroundcolor uicolor colorwithred00 green02 blue05 alpha07set frame for tableviewselftableview setframecgrectmake0 0 selfviewframesizewidth selfviewframesizeheightselfpickerframesizeheightafter setting the table cells i saw that there is an inconsistency in the alpha level around the table view cell see screenshot belowis there anyway to make the color alpha level consistent for the backgroundnote i am not setting a background image only color and alpha levelthankszhen hoe,"['objective-c', 'ios']" +153767,how should i capitalize ruby ruby ruby ruby whats good stylei know the answerai just wanted to make sure the question was out there and questioners were aware that there is a correct formalso should i capitalize gem as gemclass testlanguagename testunittestcase def test language name assert correct language name stackoverflownewdescribe languageruby endendclass stackoverflow def describe languagestring which of the following methods upcase capitalize downcase stringsendmethodsrand3 endend,['ruby'] +153772,javascript check a string that must contain another string hii want to check if string b is completely contain in string ai triedvar a helloworldvar b woldifaindexofb documentwriteyes else documentwriteno the output is yes it is not my expected output because string bwold is not completely contained in string ahelloworld wold vs worldany suggestion to check the stringthanks,['javascript'] +153777,how to include bit type column in select part with out including it on the group by in tsql here is my tsql queryselect productid vendorid productname maxproductname vendorname maxvendorname isactive maxisactive this brings error from productvendorassoc group by productid vendoridi want to apply group by only for the productid and vendorid fields but need to populate the productid vendorid productname vendorname isactive fieldshere i used the agreggate function maxproductname to avoid productname in the group by list but the same trick is not working for bit columns as operand data type bit is invalid for max operatorhow can i include bit type column in select part with out including it on the group byupdatewhat should i need to do if i need to include an int column like userid in select in the same way,['sql'] +153785,using jquery to update a page when a database is modified i want to update a page when my database is modified i want to use jquery for doing this question not clear then have a look at this suppose this is my pagephp querymysql queryselect from tbl1 where useradmin ifmysql num rowsquery0 echo table 1 has values else echo table1 is emptythis action should be performed whenever any new entry is added to the database now suppose i add an entry to the database manually then the page should automatically show the result as table1 has values i know it can be used by using refresh page periodically but i do not want to use it instead i want to try something other like ajax polling can someone give me a demo,"['php', 'jquery']" +153809,adjust the width of 2 divs using jqueryresizable i currently work on the following pagedivresizable has been modified by jquery using the following code in ready divresizanleresizable handles e divresizablebindresize function event ui divcontentwidth850 uisizewidth 175 as you can see i try to increase the width of divcontent when divresizable gets smaller and the other way around however with this code divcontent does not always grow to the left side only it sometimes extends to the right side to the irrelevant div which does not make the resizing look good at allis there any input for a more sophisticated method to let the width of those 2 divs correspond something i could think of would be to set width of divcontent tostart of irrelevant eg at 1025px divresizablewidth eg 175px 850pxhow exactly would i do this using jquerythanksdennis,"['javascript', 'jquery', 'css']" +153829,how to create xlsx file without using any excel library php this is right now i am usingmimetype applicationvndopenxmlformatsofficedocumentspreadsheetmlsheetheadercontentdescription file transferheadercontenttype mimetypeheadercontentthisposition attachment filenamebasenametypexlsxheadercontenttransferencoding binaryheaderexpires 0 headercachecontrol mustrevalidate postcheck0 precheck0headerpragma publicprint headerndataexitheader variable contains the header row of excel to be generated and looks like this header business nametbusiness typettypeseparated by tand data contains rows to be generated under header columns they are also separated by t and a row is terminated by nwith the current setup file is downloaded but it is not opening with ms excel and showing this messageexcel cannot open the file file name because the file format or file extension is not valid verify that the file format has not been corrupted and that the file extension matches the format of the filewhat header should be sent to server or how do i generate that file,['php'] +153840,gridview elements changes their place dynamically when scroll screen i have a gridview layout and all items are insert very finenow if i check on big screen then all work done is fine because no scrolling is requiredbut if i check on small screen then items are changed their position dynamicallybereif example is given belowlike i have 28 items and arranged in a grid view 74 now if upto 20 items are shown in first screen now remaining 8 is shown while i scroll screen down but now some elements of first or second row is aslo put in last rowcode is herepublic class imageadapter extends baseadapter context mcontext public static final int activity create 10 public imageadaptercontext c mcontext c override public int getcount todo autogenerated method stub return providerslength override public view getviewint position view convertview viewgroup parent todo autogenerated method stub view v ifconvertviewnull layoutinflater li getlayoutinflater v liinflaterlayouticontext null textview tv textviewvfindviewbyidridicon text tvsettextprovidersposition imageview iv imageviewvfindviewbyidridicon image ivsetimageresourcerdrawableicon else v convertview return v,['android'] +153849,is it possible to have vim prevent the saving of a php file that has a parse error i use vim and would like it to prevent me from saving php files that has parse errors if i would like to use for instance php l file to achieve this how would the autocmd in vimrc look likei know i can hook into bufwritepre with something likeautocmd filetype php autocmd bufwritepre php l but i want it to abort the write if the php command fails,['php'] +153891,python deleting a class attribute in a subclass i have a subclass and i want it to not include a class attribute that is present on the base classi tried this but it does not work class aobject x 5 class ba del xtraceback most recent call last file pyshell1 line 1 in module class ba file pyshell1 line 2 in b del xnameerror name x is not definedhow can i do this,['python'] +153898,is there any drawback to set clientidmode static on every object set on maincontent of master page i am working on aspnet project and each time i need to use jquery identifier objectid i have to change the clientidmode on each object to be static since i have noticed that the default client id mode is inherit so i set the maincontent client id mode to be static and i have found that all the object became staticthis will sure save a lot of time when working with jquery but i just want to know is there any drawback from this and is there any reason why should not clientidmode set to be static at the first place,"['jquery', 'asp.net']" +153900,python super should be working but is not as far as i can tell and everything i have been finding online this should work but it does not which is why i am asking here class tigoncrossbreeds predator lion def init self super init def printsizeself printhugeboth crossbreeds and predator inherit from mammal and lion inherits from predator the compilation of those works fine i am working on python 32 though i did also try the earlieredit sorry part of my post did not come through for some reason i also triedclass tigoncrossbreeds predator lion def init self supertigon self init def printsizeself printhugeand both of them gave meclass tigoncrossbreeds predator liontypeerror cannot create a consistent method resolutionorder mro for bases predator mammal lionany suggestions,['python'] +153906,aspnet entity framework 4 navigation entity not reflecting changes made to database i have two database tables news and news images that i have produced an entity model for with a one to many association made between them in the modelhowever when i query the model using the navigation property news images it does not return any recent database inserts but if i query the navigation entity itself then i get all latest changesfirst method using navigation propertyienumerablenews images imgs dalnewswheren nnews id newsidfirstordefaultnews images second method using the actual entity returns all recent changesienumerablenews images imgs dalnews imageswherei inews id newsidthis is the code that inserts a record to the news images entitynews images img new news images news id newsid news image filename small file sm news image filename medium file med news image filename large file lrge news image order imgcnt 1 dalnews imagesaddobjectimg dalsavechanges,['asp.net'] +153908,how do you capture and reuse a match with java regex i am trying to remember the correct notation for doing findreplace regex matches in java say i have the string string s my name is eric and i have a bee called eric and a fish called wandai want to do something like the followingsreplaceall to give my name is eric and i have a bee called eric and a fish called wandabut i know is not the correct notation to capture whatever is in the and use it to replace the found matchwhats the particular notation i am looking for herethanks in advancedave,['java'] +153909,c how to read xml attributes with xelement i have a xml with this stringmediathumbnail xmlnsmedia url height72 width72 how can i read the attribute url with xelement,['c#'] +153922,wpf binding list to listbox i have a classpublic class a inotifypropertychanged public listb blist get set public void addbb b blistaddb notifypropertychangedblist public event propertychangedeventhandler propertychanged private void notifypropertychangedstring info if propertychanged null propertychangedthis new propertychangedeventargsinfo and a binding datacontext of usercontrol is an instance of alistbox itemssourcebinding pathblist elements are shown the listbox is not updated after new object is added to list after changing list to observablecollection and removing the notifypropertychanged handler everything workswhy the list is not working,['c#'] +153927,when to use which for edit additional options and a slightly extended question belowconsider this contrived and abstract example of a class body it demonstrates four different ways of performing a for iterationprivate abstract class someclass public void someactionvoid examples listsomeclass somelist new listsomeclass a for for int i 0 i somelistcount i somelistisomeaction b foreach foreach someclass o in somelist osomeaction c foreach extension somelistforeacho osomeaction d plinq somelistasparallelforallo osomeactionedit addition of some options from answers and research e parallelenumerable parallelenumerablerange0 somelistcount 1 foralli somelistisomeaction f foreach parallel extension parallelforeachsomelist o osomeaction g for parallel extension parallelfor0 somelistcount 1 i somelistisomeactionmy question comes in two parts have i missed some significant option which option is the best choice considering readability but primarily performance please indicate if the complexity of the someclass implementation or the count of somelist would effect this choiceedit with such a dizzying array of options i wouldnt like my code to be spoilt by choice to add a thrid part to my question if my list could be any length should i default to a parallel optionas a straw man i suspect that over all implementations of someclass and all lengths of somelist option e parallelenumerable would offer the best average performance given the prevalanece of multi processor architechtures i have not done any testing to prove thisnote the parallel extensions will require the use of the systemthreadingtasks namespace,"['c#', '.net']" +153930,problem json encode utf8 i have a problem with json encode function with special charactersfor example i try thisstringsvraekecho encodingmb detect encodingstring encodingutf8echo jsonjson encodestring jsonsvru010dekwhat can i do to thisplay the string correctly so jsonsvraekthank you very much,['php'] +153948,getting selected value from net dropdown using jquery i am trying to get the value of a net dropdown list in jquery but i am only able to get the id of the selected item not the selected value is it possible to do this this is my current code which gets the id of the selected item alertddlreportperiodsclientid val,"['jquery', 'asp.net']" +153949,when is it appropriate to use virtual methods i understand that virtual methods allow a derived class to override methods inherited from a base class when is it appropriateinappropriate to use virtual methods it is not always known whether or not a class will be sub classed should everything be made virtual just in case or will that cause significant overhead,['c++'] +153953,is there a tool to convert tsql stored procedures to c i have a few projects to maintain that use a lot of sql server stored procedures in tsql i know how to maintain them but since there are many tools to automatically convert between different languages i am wondering if there is any tool to convert the stored procedures to c codei do not want to convert them to clr stored procedures i simply want to migrate the logic in my data layer to the c end of my project and automate the grunt work most of the stored procedures maybe 70 are simple select from table where id id affairs and they could be done just as well with entity frameworki know that it is not a straight line between tsql and c as it is from vbnet to c and that conversion is not as straightforward you will need to introduce a data layer in c for example and some things like cursors do not have corresponding concepts i just want to move off of stored procedures without the repetitive manual labor if possiblesince this has been put into question by faulty assumptions i already know tsql and given the code of any one of these stored procedures i could tell you what they do there are very good practical reasons why i do not want the logic to continue residing in stored procedures,['c#'] +153969,memorycacheadd returns true but does not add item to cache i am trying to add items to the memorycachedefault instance using the add method as belowbool result memorycachedefaultaddcachekey datatocache cacheitempolicythe value of result is true indicating that the item has been added to the cache yet when i attempt to retrieve it immediately afterwards the cache is empty i have also tried to add the item using the set method with the same result of an empty cachethe cache has the default 99mb memory limit so it does not appear as if there is no space to add new itemsany ideasprivate static void insertcacheddatastring cachekey object datatocache string dependantcachekeys cacheitempolicy cacheitempolicy new cacheitempolicy cacheitempolicyabsoluteexpiration new datetimeoffsetdatetimenow new timespanhours 0 minutes 0 seconds 3600 if dependantcachekeys null dependantcachekeyslength 0 cacheitempolicychangemonitorsaddmemorycachedefaultcreatecacheentrychangemonitordependantcachekeys memorycachedefaultaddcachekey datatocache cacheitempolicy loggerdebugformatcache miss for vehiclesprovider call with key 0 cachekey,"['c#', '.net']" +153973,a tricky oop problem i never got my head around say i have two cpp files orangescpp and basketcpp they have the classes orange and basket respectively my main program generates many baskets which in turn generate many oranges so basically main will have many objects of baskets and baskets will have many objects of oranges if i have a function in orange that needs to know the color of my basket how would i go about finding the color of the basketoranglecppclass oranges void whichcolorbasket get the color of the basket the orange is in basketcppclass basket int color void basket forint i 0 i 10 i oranges o new oranges i know my syntax may not be perfect but how would i access the datamember of basket from a function in orange orange is an object created by basketsending the color a parameter is not an option as there are too many oranges and the color of the basket may change during runtimei read somewhere that static functions would do the trick but they only work if they are in the same cpp fileso what do i do,['c++'] +153989,trying to integrate launch4j in a maven project using alakai plugin i am trying to integrate the generation of an installer as part of a maven compilation processi have found alakais plugin for launch4j i have create a simple hello world application using maven i have tried to use configuration examples provided by alakai but when i compile my project i get failed to execute goal orgbluestemsoftwareopenmavenpluginlaunch4jplugin1500launch4j launch4j on project launch4j failed to build the executable please verify your configuration application jar doesnt exist help 1unfortunately alakais documentation is limited and i could not find much with googlingdoes anyone know where the launch4j configxml should be set is it within the project is it in a separate directorydo i need to use the assembly plugini have installed launch4j on my pc do i need to specify the installation directory in my pomxml if yes howdoes anyone have an operational pomxml sampleexample to share thanks,['java'] +154002,why is not there a mathfloorfloat why is there only mathfloordouble i have a float and i want to round it downdo i have to cast it to double,['java'] +154011,problems with easy install pycrypto i am trying install pycrypto on osx with easy install and i am getting the following erroreasy install pycryptosearching for pycryptoreading reading reading reading best match pycrypto 23downloading processing pycrypto23targzrunning pycrypto23setuppy q bthist egg thistdir varfolders3d3d07iptvhzuzuyaeqdmfiutitmpeasy install00hgrupycrypto23eggthisttmpbwgysgwarning gmp library not found not building cryptopublickey fastmathusrlibexecgccpowerpcappledarwin10421as assembler usrbinlibexecgccdarwinppcas or usrbinlocallibexecgccdarwinppcas for architecture ppc not installedinstalled assemblers areusrbinlibexecgccdarwinx86 64as for architecture x86 64usrbinlibexecgccdarwini386as for architecture i386srcmd2c134 fatal error error writing to broken pipecompilation terminatedlipo cannot open input file varfolders3d3d07iptvhzuzuyaeqdmfiutitmpccoxuproout no such file or directoryerror setup script exited with error command gcc42 failed with exit status 1,['python'] +154012,how to draw a concentric circle in iphone i want to draw a ring ring should filled in a outer circle i referred a documentation pathsdq pathshtmlapple refdocuidtp301066ch211tpxref101 but still had problem to get the outcome here is the code cgcontextref ctx uigraphicsgetcurrentcontextcgcontextclearrectctx rectcgcontextsetrgbfillcolorctx 00 2550 10 10cgcontextfillpathctxcgcontextstrokeellipseinrectctx cgrectmake125 125 150 150cgcontextbeginpathctxcgcontexteofillpathctxcgcontextfillellipseinrectctx cgrectmake100 100 200 200,"['iphone', 'objective-c']" +154017,why dictionary values are not in the inserted order when i declare a list 1234 and i do something with it even just print i get back the same sequence 1234 but when i do anything with dictionaries they always change number sequence like it is being sorted in a twisted way i cannot understand test1 412365print test1test2 c3a1b2d4print test2 4 1 2 3 6 5a 1 c 3 b 2 d 4how in the world did a become the first element and c even if it alphabetically sorted the dictionary it should have been 1234 or abcd not 1324 wtf so how do i print get values from dictionary without changing the positions of the elements,['python'] +154029,array order in numpydot in pythons numerical library numpy how does the numpydot function deal with arrays of different memoryorder numpydotcorder forder vs dotforder corder etcthe reason i ask is that long time ago numpy 104 i made some tests and noticed numpydot performed worse than calling dgemm from scipylinalg directly with the correct transposition flags though both call the same blas library internally i suspected the reason was copying of the input matrices inside numpydot which is tragic if the input is largenow i tried again and actually numpydot performs the same as dgemm so there is no reason to keep the arrays in specific order and set transposition flags manually much cleaner codeso my question is how does a recent let us say 160 numpydot work guarantees on when things are copied and when not i am concerned about 1 memory 2 performance here cheers,['python'] +154039,html5 canvas circle text how do i create circle text text in a circle shape with canvas,['javascript'] +154050,confirmation that php static variables do not persist across requests i am looking for assurance that static variables are not stored between php requests the following previous questionsphp static variables across multiple php pagesdoes static variables in php persist across the requestsphp static variables across sessionsclearly say that they are not but they are more in the context of providing a way to maintain state rather than a specific thiscussion of what is the expected behaviouras an example if i have php code as followsfunction myfunc static a0 print afor i0i10i myfuncthen i get output of 0123456789 every time i run it my instinctunderstanding of php makes me fairly sure that this has to be the casein my own experiments i have shut a preforking apache down to one child to make sure that the variable is not remembered between requests it is not remembered between requests as i would expect but this is only one scenario in which php runswhat i am looking for isa link to an official piece of documentation that says this is the expected behaviour and would not change the relevant piece of php documentation does not mention this explicitly except in the commentsor an example of when static variables are remembered across requests such as webservers or performance enhancing php frameworks out there which will potentially not clear static variables to increase speed between requests,['php'] +154053,how to find the comment tag with beautifulsoup i tried soupfind but it does not seem to work thanks in advance edit thanks for the tip on how to find all comments i have a follow up question how do i specifically search out for a comment for example i have the following comment tag span classtitlefont iwednesday 110518i0500pmbr span i really just want this stuff iwednesday 110518i the 110518 is the date yymmdd which i am leaning on using as my search target however i do not know how to find something within a specific comment tag,"['python', 'html']" +154056,python subprocess output to stdout i am using the subprocess module to run binaries from pythonto capture the output produced by the binary i am usingproc subprocesspopen command args shellfalse stdoutsubprocesspipeout proccommunicate0print the output of the child process to stdoutprint outwhat this does is print the output of the process after it has finished executing is there anyway i can print this output to stdout while the program is executing i really need to see what the output is because these programs can run for a long timethanks for the help,['python'] +154058,core text performance i am seeing some performance issues with core text when it is run on the original ipadi have created an editable view using core text and the uitextinput protocol which is based around omnigroups ouieditableframewhen there is a fair amount of text in the view say 180 lines typinginput lags greatly behind and one tap on a key usually takes 12 secondsusing instruments with the simulator i was able to narrow down the problem and find out what was taking so much time turns out it is because i redraw the frame with every key stroke what takes up so much time is calling ctframesettercreatewithattributedstring and ctframesettercreateframei have to redraw with every key stroke so that the text gets updated this means calling ctframesettercreatewithattributedstring and ctframesettercreateframehas anyone else come upon this problem and if so how did they get around iteditdid some further investigating and turns out that if the attributed string has no attributes then everything draws so much faster and without any lag changing the font color or paragraphs style all slow it down any idea if this could have something to do with it,"['objective-c', 'ios']" +154064,nested using statements which one wont get thisposed if i have some code like this and an error occurs in the second using statement will the thispose method on 1st using not be calledusing systemdatasqlclientsqlconnection cn new systemdatasqlclientsqlconnectioncnstr cnopen using sqltransaction tran cnbegintransactionisolationlevelserializable editalso is it better to write try finally block or using statement internally compilter will generate try finally for using statement but as per coding standards which one is better,"['c#', '.net']" +154088,android best way to save data stored in application singleton class whats the best way to save the data stored in the application class singleton of an android applicationi have a quiet big app that shares a lot data between the activities so most of it is stored on the application singleton it all works great util the application is killed by the os on low memory then when it comes back it tries to resume the activity without success due to the lack of necessary data that was before on applicationdue to the lack of a much appreciated and needed method to save data on application according to your experience what are the best approachescan i save stuff besides the normal strings booleans etc like bitmapsi have already seen this android how to declare global variables but the question is not focusing on what is important in this case how to save the data when the application is killed due to low memory,['android'] +154096,mkmapview zoom to users location on viewdidload i am trying to zoom a map into the users current location once the view loads but i am getting the error terminating app due to uncaught exception nsinvalidargumentexception reason invalid region when the view loads please can someone helpcheers voidviewdidload super viewdidload mkcoordinateregion mapregion mapregioncenterlatitude mapuserlocationcoordinatelatitude mapregioncenterlongitude mapuserlocationcoordinatelongitude mapregionspanlatitudedelta 02 mapregionspanlongitudedelta 02 map setregionmapregion animated yes,"['iphone', 'objective-c']" +154097,inner workings of innerhtml i was trying to iteratively change the innerhtml of an id likedocumentgetelementbyidtestinnerhtml br anddocumentgetelementbyidtestinnerhtml table blahblah tablebut i found that it did not necessarily put my tags in sequenceof course this method sucks and i just changed everything to keep adding to a string which i assign at the end to the innerhtml of the idmy question is what exactly is innerhtml doing to the tags i am inserting is it deterministic is it browerspecific,['javascript'] +154111,how to get ip address of the device is it possible to get the ip address of the device using some code,['android'] +154113,get angle from 2 positions i have got 2 objects and when i move one i want to get the angle from the otherfor example object1x 2110 object1y 4290object2x 24650 object2y 44150i have tried the following and every variation under the sundouble radians ccpangleobject1object2double degrees radians 180 pi but i just get 2949023 returned where i want something like 45 degrees etcplease helpthanksjonathan,['ios'] +154118,c linq first faster than toarray0 i am running a testit looks likemethod 1 listint new listint124 assume 10kvar result errorcodeswherex returnederrorcodescontainsxfirstmethod 2 listint new listint124 assume 10kvar result errorcodeswherex returnederrorcodescontainsxtoarray0why is method 2 is so slow compared to method 1,['c#'] +154122,how do i force a specific uiinterfaceorientation on an individual view in a uinavigationcontroller okay so heres the situationi have an app in which i only want one specific view in a uinavigationcontroller to have a landscape orientation this view is a uiimageview that i am capturing a signature on that part works awesome so like thisprevious view signature view next view portrait landscape portraiti cannot seem to find a good way to force the device orientation to landscape on that signature screen it will never make sense to have a portrait orientation on the signature view because there is really not adequate room for signing in that screen widthso any bright ideas on how to accomplish this i have considered possibly doing the signature view modally thus breaking out of the navigation controller thoughts,['ios'] +154126,is mysql database access speed limited primarily by the db or by the language used to access it i need to update a large db quickly it may be easier to code in a scripting language but i suspect a c program would do the update faster anybody know if there have been comparative speed tests,"['php', 'mysql', 'c']" +154139,how does javas priorityqueue differ from a minheap if no difference then why was it named priorityqueue and not heap why did they name priorityqueue if you cannot insertwithpriority it seems very similar to a heap are there any differences,['java'] +154141,why fatal error class phpunit framework testcase not found in why i am getting this php errorfatal error class phpunit framework testcase not found in,['php'] +154144,how to implement folding with variadic templates i have an almost working solution however it fails to compile some simple cases and i cannot decipher the error messagemy current solutiondefine auto return expr decltype expr return expr template typename binaryfunc typename first typename second auto foldl binaryfunc func first first second second auto return func stdforwardfirstfirst stdforwardsecondsecond templatetypename binaryfunc typename first typename second typename rest auto foldl binaryfunc func first first second second rest rest auto return foldl stdforwardbinaryfuncfunc func stdforwardfirstfirst stdforwardsecondsecond stdforwardrestrest this works as expectedstruct adder template int lhs int rhs stdintegral constantintlhsrhs operator stdintegral constantintlhs stdintegral constantintrhs return auto result foldl adder stdintegral constantint19 stdintegral constantint23 assert resultvalue 42 however this fails to compilefoldl adder stdintegral constantint1 stdintegral constantint2 stdintegral constantint3 stdintegral constantint4 oddly if i remove all stdforward and rvalue refs from the code it works finewhat am i doing wrongis this a compiler bug,['c++'] +154150,read only file system on android i recently rooted my droid x and everything seems to be working perfectly i made some changes to buildprop and when i do adb push buildprop system i get the following error failed to copy cbuildprop to systembuildprop readonly file systemhow can i fix this,['android'] +154157,what is the correct way to free memory in c i have a timer in c which executes some code inside it is method inside the code i am using several temporary objectsif i have something like foo o new foo inside the method does that mean that each time the timer ticks i am creating a new object and a new reference to that objectif i have string foo null and then i just put something temporal in foo is it the same as abovedoes the garbage collector ever delete the object and the reference or objects are continually created and stay in memoryif i just declare foo o and not point it to any instance is not that thisposed when the method endsif i want to ensure that everything is deleted what is the best way of doing itwith the using statement inside the methodby calling thispose method at the endby putting foo o outside the timers method and just make the assignment o new foo inside so then the pointer to the object is deleted after the method ends the garbage collector will delete the object,['c#'] +154163,commandline tool for converting plist to json is there a command line tool available for converting plist files to jsonif not what would be the approach for creating one using objectivec or c on a mac for instance there is jsonkit for objectivec how would one go about opening a plist file pass it to jsonkit and serialize that as json,['objective-c'] +154174,placeholder issue with jquery validate i noticed today that we have an issue with jquery validate when used in conjunction with placeholder textexamplediv clasort leftlabel forusername classinlineelementusernamelabelinput idregistername typetext placeholderyour name autocompleteoff classrequiredinputi noticed that if we validate our form using jquery validate is there a work around for this or should be go back to focus html placeholder text within our form fields,['jquery'] +154183,excel date field import problem in oracle sql developer i have an excel file which has data imported from oracle 10g database one of the fields is a date filed which has values like 28jan11 0325110 pm date field is oracle time stamp6 in database when i am trying to import that excel file to another oracle 10 g database for another databaseapplication i get an error because the data field is not being recognized by oracle 10g import is being done by oracle sql developer table field has timestamp6 as the datatypehow can i import that field for time being i made the timestamp to varchar2 and its working but i could not convert that to date field again in c code it says not a valid date type,['sql'] +154219,count nonempty input field with jquery how do i count how many fields of my array field are not empty sample of the input fieldinput typefile namearquivo idarquivoi was trying to make something up using map and get but it is not coming along wellvar total 0var count arquivovaluemapfunction total total1 getbut no matter how many fields i have filled it always end up with the value of 1 and if i have no fields filled 0,['jquery'] +154232,checking a line segment is within a thistance from a point i have two points a and b that define a line segment on a device screen plus another point c using efficient and short algorithm that is easy to code preferably using standard math library how do i check if the line segment ab is within a thistance r from ci know there is a simple way to find the shortest thistance from a point to a line but it assume the line is infinitely long what i have is a line segment with two endpointsi considered posting this in math se but decided not to since i do not want to get all those long math formula as the answer like in what i need is an efficient and readable computer algorithm not a formal math theoremps i have the following objectivec method skeleton that needs to be implementedtypedef struct cgpoint a cgpoint b cglinesegment boolislinesegmentcglinesegmentline withinradiuscgfloatradius frompointcgpointpoint edit with solutionthanks to answer from veredesmarald which i already accepted i have implemented the method put here as reference for other people boolislinesegmentcglinesegmentline withinradiuscgfloatradius frompointcgpointpoint cgpoint v cgpointmakelinebx lineax lineby lineay cgpoint w cgpointmakepointx lineax pointy lineay cgfloat c1 dotproductw v cgfloat c2 dotproductv v cgfloat d if c1 0 d thistancepoint linea else if c2 c1 d thistancepoint lineb else cgfloat b c1 c2 cgpoint pb cgpointmakelineax b vx lineay b vy d thistancepoint pb return d radiuscgfloat thistanceconst cgpoint p1 const cgpoint p2 return sqrtpowp2x p1x 2 powp2y p1y 2cgfloat dotproductconst cgpoint p1 const cgpoint p2 return p1x p2x p1y p2y,['objective-c'] +154263,find total number of days between two dates in iphone i would like to find total number of days between two dateseg today is 01012011ddmmy and second date is 25032011 how would i find the total number of daysnsdate currentdatensdate datenslogcurretdate is currentdatensdateformatter tempformatter1 nsdateformatter allocinitautoreleasetempformatter1 setdateformatddmmy hhmmssnsdate todate tempformatter1 datefromstring20042011 090nslogtodate todate,['ios'] +154266,java enums ordering im using java enums to define how to render a modal window with buttons vaadin handles the rendering my problem is that when i run the gui my buttons comes in a randomized order each time so my question is this since i use a enum set to hold my buttons will that be unordered whats the best way to make it into a ordered listmy settings enumpublic enum modal settings new modal windowmenucontextnew 400 modal buttonsave modal buttoncancel edit modal windowmenucontextmodify400 modal buttonupdate modal buttoncancel delete modal windowmenucontextdelete 250 false modal buttondelete modal buttoncancel private enumsetmodal button buttons private string caption private string width private boolean isresizable true private modal settingsstring caption string width modal button buttons thissetcaptioncaption thissetwidthwidth thisbuttons enumsetcopyofarraysaslistbuttons private modal settingsstring caption string width boolean isresizable modal button buttons thissetcaptioncaption thissetwidthwidth thisisresizable isresizable thisbuttons enumsetcopyofarraysaslistbuttons public enumsetmodal button getbuttons return buttons override public string tostring string s supertostring ssreplaceall return s public void setcaptionstring caption thiscaption caption public string getcaption return caption public void setwidthstring width thiswidth width public string getwidth return width public boolean isresizable return isresizable my buttons enumpublic enum modal button save update cancel delete,['java'] +154271,how to compare two datetimes on time only ignoring the date seems like everyone always ignores the time part but how would you compare two datetimes ignoring the date if we just compare them as time it seems to still favor the oldest date12022004 900 12022011 824 this would be truethe below code works but it feels a bit a bit beating around the bush comparing the hours and minutes separatelyvar results from x in datacontextgettablescheduleentity where xlastrundate datedate xreportingtimehour datehour xreportingtimeminute dateminute xreportingfequencysubstringposition 1 scheduled select x also the reason we are doing this is because we could not get our sql time to compare to a timespan this says it would be the same but linq is returning a time to bigint conversion error,['c#'] +154279,c referring to a sibling namespace givennamespace root namespace parent namespace childa class hard to get atnamespace root namespace parent namespace childb how do i refer refer to namespace childb relative to the current namespace hard to get at instance of childa class psuedo syntaxdo i need to specify the full path of the namespace is there some way around it,['c++'] +154281,itunesconnect using application loader behind a firewall i was trying to upload the app store build zip file of my app to app store when using behind my office firewall the tcpip connection failed i need to know what exact port should be open to upload iphone application by using application loader so that the port can be opened or any other configurations if you know,"['iphone', 'ios']" +154302,extending marc gravells dynamic linq orderby i found marc gravells dynamic order by greatdynamic linq orderbyi have put it in a class linqhelper in this class i also have created two new classes so that in my code i can do thisvar q dbtbljobheaderslinqhelperorderbycollection obys new linqhelperorderbycollectionobysaddorderbysome field trueobysaddorderbyanotherfield falseobysexecuteorderbysqthe classes to acheive this are summary a collection of order bys summarypublic class orderbycollection private arraylist orderings new arraylist public orderbycollection summary add an order by to this collection summary public void addorderbystring field bool descending orderbyobj newobj new orderbyobjdescending field thisorderingsaddnewobj summary executes the order bys summary public iorderedqueryablet executeorderbystthis iorderedqueryablet source int executionindex 0 foreach orderbyobj o in thisorderings if executionindex 0 if odescending source linqhelperorderbydescendingsource ofield else source linqhelperorderbysource ofield else if odescending source linqhelperthenbydescendingsource ofield else source linqhelperthenbysource ofield executionindex return iorderedqueryabletsource summary an order by object summaryprivate class orderbyobj public bool descending get set public string field get set public orderbyobjbool isdescending string databasefield thisdescending isdescending thisfield databasefield howver i am pretty new to passing linq vars through to functions the confuses me a bit i currently get the error onobysexecuteorderbysqwhich gives the errorthe type arguments for method linqhelperorderbycollectionexecuteorderbyssystemlinqiorderedqueryable cannot be inferred from the usage try specifying the type arguments explicitlyi am a bit confused about this if anyone could help am i passing the var q in properly and then returning it properly,['c#'] +154313,measuring thistance along ellipse suppose we have an ellipse x2a2 y2b2 taking a point acostbsintt on the ellipse what is the fastest way to find another point on the ellipse such that thistance between them is a given d d is less than piabthe problem was encountered when i have a corner quarter ellipse and need to find points along it seperated by some d,['c++'] +154316,python how to tell the for loop to continue from a function sometimes i need the following pattern within a for loop at times more than once in the same loop try var attempt to do something that may fail on a number of levels except exception e loge continuenow i do not see a nice way to wrap this in a function as it can not return continuedef attemptthis try return this except exception e loge 1 continue syntax error continue not properly in loop or 2 return continue invalid syntax 3 return false this sort of works but makes me feel powerlessif i return false than i could var attemptto do something that may fail on a number of levels if not var continuebut i do not feel that does it the justice i want to tell the for loop to continue or fake it from within attempt function,['python'] +154322,php get parent class file path exampleindexphp i know where this file isclass new childclassclass initcomponentssomefilephp i know where this file isclass childclass extends parentclass someparentfilephp i do not know where this file isclass parentclass function initcomponents does something i need to find out where someparentfilephp isreasoni am debugging some difficult php code that someone else wrote i need to find out what file contains the code that defines a class parameteri found it as far as a class method calling a function that does thisclass initcomponentsthe parameter is defined somewhere in therethe problem is that this function is within a parent class myclass of the above class and i have no idea where the parent class isis there a way or some debug function by which i can find out the location of this parent class or at least where the parameter was definedps downloading the whole application and then using text search would be unreasonable,['php'] +154346,threadsafe implementation of max i need to implement global object collecting statistics for web server i have statistics singleton which has method addsamplelong sample which subsequently call updatemax this has to be obviously threadsafe i have this method for updating maximum of whole statisticsatomiclong maxprivate void updatemaxlong sample while true long curmax maxget if curmax sample boolean result maxcompareandsetcurmax sample if result break else break is this implementation correct i am using javautilconcurrent because i believe it would be faster than simple synchronized is there some other better way to implement this,['java'] +154350,how to get access to the object bound to node in devexpress xtratreelist i have created an xtratreelist control that is bound to my bindingsource and it uses a list of custom objects the multiselect property is set to true so when the user selects multiple nodes i want to define what objects are bound to them but unfortunately i have not found any property related to contained data except the data which is obsolete and is always null i also tried to use treelistnodegetvalue but it only gives me a thisplayed value and not the object itselfis there a way to get access to the object bound to node in xtratreelistthe last resort is to use unbound mode and to create them manually but i would like to know if there is a simple solution for that,['c#'] +154356,why is filecreate needed to be closed the following throws an exception the process cannot access the file dmydirfirsttxt because it is being used by another procestatic void mainstring args directorycreatedirectorydmydir filecreatedmydirfirsttxt filewritealltextdmydirfirsttxt stackoverflowcomhowever following worksusing filecreatedmydirfirsttxt orfilecreatedmydirfirsttxtclosewhy what in filecreate needs to be closed,"['c#', '.net']" +154362,cache server for netexample memcached i am looking for cache server for net what can you suggest as i know memcached has provider for net is it good enough to use for net in production,"['c#', '.net', 'asp.net']" +154363,how to match an empty dictionary in javascript from the node repl thing d d false d falsegiven i have an empty dictionary how do i make sure it is an empty dictionary,['javascript'] +154364,is androidffmpeg friendship really available the question does not mean that i am interested if ffmpeg code can be used on andoid i know that it can i am just asking if somebody has the real performance progress with that stuffi have created the question after several weeks of experiments with the stuff and i have had enoughi do not want to write to branches where people even do not say what kind of video they decode resolution codec and talk only about some mystical fps i just do not understand what they want to do also i am not going to develop application only for my phone or for android 22 phones that have some extended opengl features i have quite popular phone htc desire so if the application does not work on it so whats nextwell what do i haveffmpeg source from the latest head branch actually i could not buld it with ndk5 so i decided to use stolen onebambusers build script bash with appropriate ffmpeg source web it builds well after some corrections by using ndk5rockplayers gelded ffmpeg source code with huge androidmk in the capacity of build script web ffmpeg git 20100418zipit builds by ndk3 and ndk5 after some corrections rockplayer is probably the most cool media player for android and i supposed that i would have some perks using it is build i had suitable video for a project is not big and is not small 600x360 h264both libraries we got from clauses 2 and 3 provide us possibility to get frames from video framebyframe seek etc i did not try to get an audio track because i did not need one for the project i am not publishing my source here because i think that is traditional and it is easy to findwell whats the results with videohtc desire android 22600x360 h264decoding and rendering are in different threadsbambuser ndk5 buld for armv5te rgba8 33 msframe averagerockplayer ndk3 build for neon rgb565 27 msframe averageit is not bad for the first look but just think that these are results only to decode framesif somebody has much better results with decoding time let me knowthe most hard thing for a video is rendering if we have bitmap 600x360 we should scale one somehow before painting because different phones have different screen sizes and we can not expect that our video will be the same size as screenwhat options do we have to rescale a frame to fit it to screeni was able to check the same phone and video source those casessws scale c function in bambusers build 70 msframe unacceptablestupid bitmap rescaling in android bitmapcreatescaledbitmap 65 msframe unacceptableopengl rendering in ortho projection on textured quad in this case i did not need to scale frame i just needed to prepare texture 1024x512 in my case it was rgba8 containig frame pixels and than load it in gpu glglteximage2d result 220 msframe to render unacceptable i did not expect that glteximage2d just sucked on snapdragon cputhat is alli know that there is some way to use fragment shader to convert yuv pixels using gpu but we will have the same glteximage2d and 200 ms just to texture loadingbut this is not the end my only friend the end it is not hopeless conditiontrying to use rockplayer you definitely will wonder how they do that damn frame scaling so fast i suppose that they have really good experience in arm achitecture they most probably use avcodec decode video2 and than img convert as i did in rp version but then they use some tricks depends of arm version for scalingmaybe they also have some magic buld configuration for ffmpeg decreasing decoding time but androidmk that they published is not the androidmk they use dunnoso now it looks like you can not just buld some easy jni bridge for ffmpeg and than have real media player for android platform you can do this only if you have suitable video that you do not need to scaleany ideas i hope for you,['android'] +154469,doctrine2 doesent set sequence to default for id column postgres just a simple example if i want create a table with auto fill id in postgres i run this sqlcreate sequence person id seq start 1create table person id integer primary key default nextvalperson id seq name varchar100 not nulland in doctrine i set all propertyclass person id columntypeinteger nullablefalse generatedvaluestrategysequence sequencegeneratorsequencenameperson id seq initialvalue1 allocationsize100 private idbut when i generated sql php doctrine ormschematoolcreate dumpsql i got itcreate table person id int not null name varchar100 not nullcreate sequence person id seq increment by 100 minvalue 1 start 1but do not set it to defaultd person column type modifiers id integer not null,['php'] +154473,python lambda function in list comprehensions why is the output of the following two list comprehensions different even though f and the lambda function are the same f lambda x xxfx for x in range10andlambda x xx for x in range10mind you both typef and typelambda x xx return the same type,['python'] +154477,resqueweb fails to start with a 500 server error i am following the configuration guidelines for installing resque i am met with a openurihttperror i am using rvm 192p180 rails 306 and powresqueweb fails to start with a 500 server error what the heck is going on hereto replicate problemstart rethis with rethisserverstart a worker with vverbose1 queuefile serve rake environment resqueworktry to start resqueweb with rails envdevelopment resqueweb configinitializersresquerbconfigresqueymldevelopment localhost6379test localhost6379staging localhost6379fi localhost6379initializersresquerbrails root envrails root filedirname file rails env envrails env developmentrequire resque require yamlunless definedrethis rethis rethisnewrethis rethisnewhost localhost port 6379endresquerethis rethisterminal master projectsmyapp rails envdevelopment resqueweb configinitializersresquerb20110520 114248 0700 starting resquewebusersborisrvmrubiesruby192p180libruby191openurirb346in open http 500 internal server error openurihttperror from usersborisrvmrubiesruby192p180libruby191openurirb769in buffer open from usersborisrvmrubiesruby192p180libruby191openurirb203in block in open loop from usersborisrvmrubiesruby192p180libruby191openurirb201in catch from usersborisrvmrubiesruby192p180libruby191openurirb201in open loop from usersborisrvmrubiesruby192p180libruby191openurirb146in open uri from usersborisrvmrubiesruby192p180libruby191openurirb671in open from usersborisrvmrubiesruby192p180libruby191openurirb33in open from usersborisrvmgemsruby192p180gemsvegas018libvegasrunnerrb142in port open from usersborisrvmgemsruby192p180gemsvegas018libvegasrunnerrb159in check for running from usersborisrvmgemsruby192p180gemsvegas018libvegasrunnerrb104in start from usersborisrvmgemsruby192p180gemsvegas018libvegasrunnerrb77in initialize from usersborisrvmgemsruby192p180gemsresque1161binresqueweb13in new from usersborisrvmgemsruby192p180gemsresque1161binresqueweb13in top required from usersborisrvmgemsruby192p180binresqueweb19in load from usersborisrvmgemsruby192p180binresqueweb19in mainrethisserver i am connecting an extra client when i hit localhost6379324 20 may 110208 1 clients connected 0 slaves 932400 bytes in use324 20 may 110212 accepted 12700153028324 20 may 110213 db 0 7 keys 0 volatile in 8 slots ht324 20 may 110213 2 clients connected 0 slaves 942976 bytes in use324 20 may 110218 db 0 7 keys 0 volatile in 8 slots htinitializersrethisrbrethis rethisnewhost localhost port 6379terminal proof of rethis rethisrethis client v220 connected to rethislocalhost63790 rethis v225ruby192p180 003 rethissetpepper bacon okruby192p180 004 rethisgetpepper bacon,"['ruby-on-rails', 'ruby']" +154487,verbose level with argparse and multiple v options i would like to be able to specify different verbose level by adding more v options to the command line for example myprogrampy myprogrampy v myprogrampy vv myprogrampy v v vwould lead to verbose0 verbose1 verbose2 and verbose3 respectively how can i achieve that using argparseoptionally it could be great to also be able to specify it like myprogram v 2,['python'] +154489,ie7 bullet or number shown outside of div i am having issues with the ie7 list element bugs the bullets or numerals of and are being shown outside of the margin how do i fix this for ie from what i have read this seems to be a problem when specifying the heightwidth in an ie7 li images can be found herefirefoxie7i have a stylesheet with the meyer resetcreate request li thisplay listitem width 313px height 23px backgroundcolor e3e3e3 liststyle decimal liststyleposition inside paddingleft 25px paddingtop 5pxcreate request lialternate backgroundcolor whitecreate left lihover width 356px background urlimageslist addpng 100 100 norepeat backgroundcolor b0b0b0 cursor pointer,"['html', 'css']" +154496,setting up cruisecontrolnet i am trying to set up cruisecontrolnet 16the installation completes successfully however i cannot seem to start the actual servicewhen running the ccnetexe i get a console window that the last thing it writes is initialising securityrunning the service from service control manager also does not worktrying to access localhostccnet returns no responsewhat am i missing here i have installed the product in the past with success not sure what is wrong this time,['c#'] +154509,changing the button text color when selected i have a custom button and i am setting the different image when it is highlighted now i want to change the color of the text on the button when button is highlighted is it possible to do this,"['iphone', 'objective-c', 'ios']" +154515,how do i split this string with javascript javascriptvar string 37961523 7940918remove brackets replace or regex remove whitespacesarray stringsplitvar split 1 array0var split 2 array1outputvar split 1 37961523var split 2 7940918should i just use stringreplace replace replacesg or regex,['javascript'] +154522,not getting didreceivememorywarning when app is in the background i am noticing that my view controllers are not getting their didreceivememorywarning methods called when my application is in the background state on the ipad simulator more specifically i see the call to applicationdidenterbackground in my logs then i hit the simulate memory warning button and then i notice a peculiar lack of any didreceivememorywarning callshowever when i bring the application back to the foreground i suddenly get the didreceivememorywarning call as if it had been queuedwhat i am confused about here is if my application is really in the background or if it is just flat out suspended is there any way to tell in the simulatoralso if it is not yet suspended and really is just in the background then i would find it silly that i am unable to process didreceivememorywarning because that would then mean that only the foreground application can process memory warnings to free up space which is of course odd given that the foreground app could be only one of possibly dozens of running apps and it would make so much more sense if they could all free up memoryanyway the main questions are why are not i getting didreceivememorywarning in the background state and also am i really suspended and how do i tell,['ios'] +154533,is there any signalprocessing algorithm that could reverseengineer how the sound wave was produced through the vocal system of group of humans having long sound tape with 3 speakers on it how to get info on how there mouthes openclose we have audio recording with more than one speaker sound is clear and does not require noise reduction we want to create some animation with speaking 3d heads generally we want to find out from sound data mouthes movementreally we have 3d heads moving somehow via some default animation like we have prepared animation for o sound for each person we need some info on which millisecond which person produced which sound so it is like voice to text but for sounds and for more than one person on one recordingin general perfect case we want to obtain some signals on movements of d9 d6 d5 point pairs from more than one speaker english language of courseare there any papers with algorithms or opensource librariesso far i have found some libraries but i had never used any of them yet,"['c++', 'c']" +154553,how to encode a url in winforms i am creating a windows application and i need to pass an encoded url but i am not sure how to encode it in winforms c,['c#'] +154566,how to save firebug changes using eclipse windows how to save firebug changes using eclipse windowsi found here that it is possible to save firebug changes if we use eclipse and fireeclipseis anyone using this combination successfully can anyone explain the step of installingi am on windows7 64 bitand if fireeclipse works with eclipse then will it also work with aptana port of eclipse,['css'] +154577,you have already activated rake 090 but your gemfile requires rake 087 i am trying to run rails projecti get your bundle is complete use bundle show gemname to see where a bundled gem is installedif i do bundle installbuti am getting you have already activated rake 090 but your gemfile requires rake 087while doingrake dbmigrate,['ruby-on-rails'] +154578,how does jquerys promise method really work i do not really understand this delegate and promise thing according to the docs delegate would bind an selector and event to some sort of wrapping container that can be used again at a later time for current and future itemspromise would remap things back to when it was first bounded if everything newly loaded matches maybe i do not really understand this promise methodwhat if the wrapper is still there but the contents in the wrapper container has changed and or reloaded via ajax why is it broken that the events are not triggering or working as it would the first time it is bindedand yes i have been to the docs page i just do not understand their explanations completely,['jquery'] +154588,prevent multiple form submits in mvc 3 with validation i have a form with many input fields on it some with validation i use the default validation plugin in mvc 3 if the server response is slow the user may click to submit another time which may cause undesired behavior how to prevent this i have tried injecting code in the submit event of the form but this event is raised even if the validation fails,['jquery'] +154589,java string align to right i have an array of these numbers6167284149264957i use a decimalformat object like this decimalformat formatter new decimalformat bytesto get these results61672 bytes84149 bytes264957 bytesbut i need the results to be aligned to right like the following 61672 bytes84149 bytes 264957 bytesyour help is already appreciated,['java'] +154594,voipsip soft phone c wpf i need to write voipsip soft phone in c using wpf interface with audio support onlyi need to have call transfer call conference and recording of conversations in mp3i have looked at voip sdk from abto llc but it is slow at application startup 30 seconds to start application i think it is related to loading activex part of this sdki have also looked at sipnet but it is only for sip and does not contain components for voice data transfer i have very limited time only 2 months from zero to fully working app what sdk can i use to accomplish this taskwindows 7 must be supported,['c#'] +154599,matlab php java i am trying to create a web app which uses a matlab function using a phpjava bridge let me explaini need to write the function in matlabconvert the function into a jar file using the matlab ja builderuse a phpjava bridge to call this function in php and thisplay resultsso far i have done this i created a very simple matlab file named makesqrm which is as below function ymakesqrx y magicx endi packaged this into a jar file named themagicjar using matlab builder jainstalled tomcat and phpjava bridge and wrote a php function which calls the makesqr func like thisphp require oncehttplocalhost8080javabridgetemplate621javajavainc myclassnew javathemagicmksqrmksqr is the class which has the method named makesqr input new javajavalangdouble 5 noofoutputsnew javajavalanginteger1 matinpnew javacommathworkstoolboxjavabuildermwnumericarrayinput myclassmakesqrnoofoutputsmatinp i just keep getting this erroruncaught oexceptionjavalangexception invoke failed omksqrmakesqrointointeger oobjectomwnumericarray cause javalangillegalargumentexception argument type mismatch vm 160 25 at 9 sunreflectnativemethodaccessorimplinvoke0native method 8 sunreflectnativemethodaccessorimplinvokeunknown source 7 sunreflectdelegatingmethodaccessorimplinvokeunknown source 6 javalangreflectmethodinvokeunknown source 5 phpjavabridgejavabridgeinvokejavabridgejava1044 4 phpjavabridgerequesthandlerequestrequestjava417 3 phpjavabridgerequesthandlerequestsrequestjava500 2 phpjavabridgehttpcontextrunnerruncontextrunnerjava145 1 phpjavabridgethreadpooldelegaterunthreadpooljava60 0 httplocalhost8080javabridgetemplate621javajavainc232 java throwexceptionproxyfactorygetproxy7 commathworkst t true 1 httplocalhost8080javabridgetemplate621javajavainc360 java argget in httplocalhost8080javabridgetemplate621javajavainc on line 195i dont understand what is to be done hereeditrenick hi i used the caucho quercus and wrote the php filetestjavaphp as belowmyclassnew javathemagicthemagicinput new javajavalangdouble 5outputnew javajavalanginteger1resultnew javajavalangobjectnnew javacommathworkstoolboxjavabuildermwnumericarrayinputmwclassiddoubleresultmyclassmakesqroutputnnow when i call this file as localhost8080testjavaphp i get the below errorhttp status 500 type exception reportmessagedescription the server encountered an internal error that prevented it from fulfilling this requestexceptioncomcauchoquercusquercusexception themagicthemagicmakesqr null comcauchoquercusenvjavamethodinvokejavamethodjava131 comcauchoquercusenvjavainvokercallmethodjavainvokerjava737 comcauchoquercusenvjavaoverloadmethodcallmethodjavaoverloadmethodjava179 comcauchoquercusprogramjavaclassdefcallmethodjavaclassdefjava658 comcauchoquercusenvjavavaluecallmethodjavavaluejava327 comcauchoquercusexprabstractmethodexprevalabstractmethodexprjava97 comcauchoquercusexprobjectmethodexprevalobjectmethodexprjava97 comcauchoquercusexprabstractmethodexprevalcopyabstractmethodexprjava63 comcauchoquercusexprbinaryassignexprevalbinaryassignexprjava88 comcauchoquercusexprexprevaltopexprjava523 comcauchoquercusstatementexprstatementexecuteexprstatementjava67 comcauchoquercusstatementblockstatementexecuteblockstatementjava105 comcauchoquercusprogramquercusprogramexecutequercusprogramjava413 comcauchoquercuspageinterpretedpageexecuteinterpretedpagejava89 comcauchoquercusenvenvexecutepagetopenvjava3951 comcauchoquercusenvenvexecutetopenvjava3892 comcauchoquercusservletquercusservletimplservicequercusservletimpljava188 comcauchoquercusservletquercusservletservicequercusservletjava594 javaxservlethttphttpservletservicehttpservletjava717root causejavalangnullpointerexception commathworkstoolboxjavabuilderinternalmwmcrinvokemwmcrjava492 themagicthemagicmakesqrthemagicjava158 sunreflectnativemethodaccessorimplinvoke0native method sunreflectnativemethodaccessorimplinvokeunknown source sunreflectdelegatingmethodaccessorimplinvokeunknown source javalangreflectmethodinvokeunknown source comcauchoquercusenvjavamethodinvokejavamethodjava117 comcauchoquercusenvjavainvokercallmethodjavainvokerjava737 comcauchoquercusenvjavaoverloadmethodcallmethodjavaoverloadmethodjava179 comcauchoquercusprogramjavaclassdefcallmethodjavaclassdefjava658 comcauchoquercusenvjavavaluecallmethodjavavaluejava327 comcauchoquercusexprabstractmethodexprevalabstractmethodexprjava97 comcauchoquercusexprobjectmethodexprevalobjectmethodexprjava97 comcauchoquercusexprabstractmethodexprevalcopyabstractmethodexprjava63 comcauchoquercusexprbinaryassignexprevalbinaryassignexprjava88 comcauchoquercusexprexprevaltopexprjava523 comcauchoquercusstatementexprstatementexecuteexprstatementjava67 comcauchoquercusstatementblockstatementexecuteblockstatementjava105 comcauchoquercusprogramquercusprogramexecutequercusprogramjava413 comcauchoquercuspageinterpretedpageexecuteinterpretedpagejava89 comcauchoquercusenvenvexecutepagetopenvjava3951 comcauchoquercusenvenvexecutetopenvjava3892 comcauchoquercusservletquercusservletimplservicequercusservletimpljava188 comcauchoquercusservletquercusservletservicequercusservletjava594 javaxservlethttphttpservletservicehttpservletjava717note the full stack trace of the root cause is available in the apache tomcat6032 logsapache tomcat6032would anyone have any idea as to what i am doing wrongnote i dont know a word of java but am stuck in a situation where i have to handle this,"['java', 'php']" +154606,how can i update a datatable in c without using a loop let suppose there are three columns in my datatablecodenamecolorif i know the code and name how can i update the color of that specific row whose code and name match my criteria i want to do this without using loops,"['c#', '.net']" +154620,is there ever a good reason to pass a string to settimeout we all know that passing a string to settimeout or setinterval is evil because it is run in the global scope has performance issues is potentially insecure if youre injecting any parameters etc so doing this is definitely deprecatedsettimeoutdosomethingsomevar 10in favour of thissettimeoutfunction dosomethingsomevar 10my question is can there ever be a reason to do the former is it ever preferable if it is not why is it even allowedthe only scenario i have thought of is of wanting to use a function or variable that exists in the global scope but has been overridden in the local scope that sounds to me like poor code design however,['javascript'] +154622,whats the real lower limit for signed long long checking the limits of the type long long usingstdcout stdnumeric limitslong longmini get 9223372036854775808however when compiling the following codeint main long long l l9223372036854775808lli get the warningstestcpp37 warning integer constant is so large that it is unsignedtestcpp3 warning this decimal constant is unsigned only in iso c90what am i missingmany thanks in advance for your helpgiorgio,['c++'] +154623,initialize array in method argument in php you can do the followingmethodarraya bcan you in java initialize a string array as an argument in the method call something like tihsmethodnew string a bthanks,['java'] +154645,how to have a checkbox fire an ajax call when checked or unchecked in rails3 in my rails3 application i have a group of check boxes for a list of tasks i would like to fire off an ajax call back to the server whenever one of the check boxes are checked or unchecked this code is part of a much larger form providertasks assignedeach do task assigned form for task assigned url controller tasks assigned action update remote true do t thidden field id value task assignedid tcheck box provider completed checked task assignedprovider completed onclick thisparenttriggersubmitrails tlabel provider completed task assignedtask descgsubnrrnn brhtml safe style color 6 margintop 0px br end end this is the generated htmlform acceptcharsetutf8 actiontasks assignedupdate dataremotetrue methodpost div stylemargin0padding0thisplayinlineinput nameutf8 typehidden valuex2713 input nameauthenticity token typehidden valuejecj4fkv48t5egcee0hhpvsbwjgwgxn59l2knmv7no div input idtask assigned id nametask assignedid typehidden value25 input nametask assignedprovider completed typehidden value0 input idtask assigned provider completed nametask assignedprovider completed onclickthisparenttriggersubmitrails typecheckbox value1 label fortask assigned provider completed stylecolor 6 margintop 0pxabclabel br formform acceptcharsetutf8 actiontasks assignedupdate dataremotetrue methodpost div stylemargin0padding0thisplayinline input nameutf8 typehidden valuex2713 input nameauthenticity token typehidden valuejecj4fkv48t5egcee0hhpvsbwjgwgxn59l2knmv7no div input idtask assigned id nametask assignedid typehidden value24 input nametask assignedprovider completed typehidden value0 input idtask assigned provider completed nametask assignedprovider completed onclickthisparenttriggersubmitrails typecheckbox value1 label fortask assigned provider completed stylecolor 6 margintop 0pxprovider completedlabel br formform acceptcharsetutf8 actiontasks assignedupdate dataremotetrue methodpost div stylemargin0padding0thisplayinline input nameutf8 typehidden valuex2713 input nameauthenticity token typehidden valuejecj4fkv48t5egcee0hhpvsbwjgwgxn59l2knmv7no div input idtask assigned id nametask assignedid typehidden value22 input nametask assignedprovider completed typehidden value0 input idtask assigned provider completed nametask assignedprovider completed onclickthisparenttriggersubmitrails typecheckbox value1 label fortask assigned provider completed stylecolor 6 margintop 0pxabrbbrclabel br formif i add a submit button in the form it works without any problem but this does not look very appealingthe onclickthisparenttriggersubmitrails is my vain attempt to trigger the rails submit code when the check box is checked the parent the form is never found a javascript error is generated object has no method parenti believe i am very close to getting it figured out but i am obviously missing something,['jquery'] +154651,uploading files greather than 4096kb fails i am setting up an aspnet aspnet framework 40 webproject with visual studio 2010 in one of my webpage i use a silverlight mulit file uploader from the link belowsilverlight mulit file uploaderi set the max upload size from the plugin to 100 mb as you can see on the code below object idmultifileuploader datadataapplicationxsilverlight2 typeapplicationxsilverlight2 width465 height220 param namesource valueclientbinmpostsilverlightmultifileuploadxap param nameonerror valueonsilverlighterror param nameinitparams valuemaxfilesizekb102400maxuploads2filefilterbilderjpg png gifjpgpnggifdokumentepdfpdfvideosmpeg avi wmampegaviwmaaudiomp3mp3chunksize4194304customparamsyourparametersdefaultcolorwhite param namebackground valuewhite param nameonload valuepluginloaded param nameminruntimeversion value40504010 param nameautoupgrade valuetrue a hrefv40504010 styletextdecoration none img src altget microsoft silverlight styleborderstyle none aobjectiframe stylevisibility hidden height 0 width 0 border 0pxiframei also made some entries in the webconfig filexml version10configuration systemweb compilation debugtrue targetframework40 compilation httpruntime maxrequestlength102400 executiontimeout360 sessionstate modeinproc timeout30 cookielessfalse cookienamemmadminpfynsession authentication modewindows systemweb systemwebserver security requestfiltering requestlimits maxallowedcontentlength104857600 requestfiltering security systemwebserverconfigurationeverytime i upload a file bigger than 4096 kb the uploadprocess fails i start my webapplication out from visual studio 2010 while pressing ctrlf5 any ideasgreez marc,"['c#', 'asp.net']" +154652,how do i submit a form to a controller on the server i am new to angular and would like to know how to actually submit a form to the server once the data is filled inthe cookbook form examples on angularjsorg only save the state on the client how do i submit to the serveralternatively how do i use jquerys formsubmit on the form in the ngclicksave functionedit found 2 ways to do this i also removed the html markup i pasted before just refer to the advanced form cookbook example for the source by dobrica pavlinusic to go the angular way using a resource to send the data to the server in json format i had issues with that on the server side angular was sending it fine but grails was mangling it according to firebug and request contentlength i need to look into this more how do i change the contenttype in angular for a resource method like save put a form in and use a submit button since i am not doing a single page web app i used this method most validations were on the client and a few more on the server which were sufficient for me just putting this here so that someone else can use this for possible solutions as well as to get the reaction of the javascriptangular experts on the best approachthanks rajesh,['javascript'] +154655,questions on a haskell c conversion backgroundi was dragged into seeing this questionfibonaccis closedform expression in haskellwhen the author initially tagged with many other languages but later focused to a haskell question unfortunately i have no experience whatsoever with haskell so i could not really participate in the question however one of the answers caught my eye where the answerer turned it into a pure integer math problem that sounded awesome to me so i had to figure out how it worked and compare this to a recursive fibonacci implementation to see how accurate it was i have a feeling that if i just remembered the relevant math involving irrational numbers i might be able to work everything out myself but i do not so the first step for me was to port it to a language i am familiar with in this case i am doing ci am not completely in the dark fortunately i have plenty experience in another functional language ocaml so a lot of it looked somewhat familiar to me starting out with the conversion everything seemed straightforward since it basically defined a new numeric type to help with the calculations however i have hit a couple of roadblocks in the translation and am having trouble finishing it i am getting completely wrong resultsanalysisheres the code that i am translatingdata ext ext integer integer deriving eq showinstance num ext where frominteger a ext a 0 negate ext a b ext a b ext a b ext c d ext ac bd ext a b ext c d ext ac 5bd ad bc easy to work out on paper remaining instance methods are not neededfib and divide twophin 2twophin where twophi ext 1 1 divide ext 0 b b div 2n effectively divides by 2n sqrt 5so based on my research and what i can deduce correct me if i am wrong anywhere the first part declares type ext with a constructor that will have two integer parameters and i guess will inherit the eq and show typesmodulesnext is the implementation of ext which derives from num frominteger performs a conversion from an integer negate is the unary negation and then there is the binary addition and multiplication operatorsthe last part is the actual fibonacci implementationquestionsin the answer hammar the answerer mentions that exponentiation is handled by the default implementation in num but what does that mean and how is that actually applied to this type is there an implicit number field that i am missing does it just apply the exponentiation to each corresponding number it contains i assume it does the latter and end up with this c codepublic static ext operator ext x int p exponent just apply across both parts of ext return new extbigintpowxa p bigintpowxb p ext ap bphowever this conflicts with how i perceive why negate is needed it wouldnt need it if this actually happensnow the meat of the code i read the first part divide twophin 2twophin asdivide the result of the following expression twophin 2twophinpretty simple raise twophi to the nth power subtract from that the result of the rest here were doing binary subtraction but we only implemented unary negation or did we not or can binary subtraction be implied because it could be made up combining addition and negation which we have i assume the latter and this eases my uncertainty about the negationthe last part is the actual division divide ext 0 b b div 2n two concerns here from what i have found there is no division operator only a div function so i would just have to divide the numbers here is this correct or is there a division operator but a separate div function that does something else speciali am not sure how to interpret the beginning of the line is it just a simple pattern match in other words would this only apply if the first parameter was a 0 what would the result be if it did not match the first was nonzero or should i be interpreting it as we do not care about the first parameter and apply the function unconditionally this seems to be the biggest hurdle and using either interpretation still yields the incorrect resultsdid i make any wrong assumptions anywhere or is it all right and i just implemented the c incorrectlycodeheres the nonworking translation and the full source including tests so far just in case anyone is interested code removed to keep post size down full source still available through link aboveprogressok so looking at the answers and comments so far i think i know where to go from here and whythe exponentiation just needed to do what it normally does multiply p times given that weve implemented the multiply operation it never crossed my mind that we should do what math class has always told us to do the implied subtraction from having addition and negation is a pretty handy feature tooalso spotted a typo in my implementation i added when i should have multiplied ext a b ext c d ext ac 5bd ad bcpublic static ext operator ext x ext y return new extxa ya 5xbyb xayb xbya oopsconclusionso now it is completed i only implemented to essential operators and renamed it a bit named in a similar manner as complex numbers so far consistent with the recursive implementation even at really large inputs heres the final codestatic readonly complicated two phi new complicated1 1static bigint fib xint n var x complicatedpowtwo phi n complicatedpow2 two phi n systemdiagnosticsdebugassertxreal 0 return xbogus bigintpow2 nstruct complicated private bigint real private bigint bogus public complicatedbigint real bigint bogus thisreal real thisbogus bogus public bigint real get return real public bigint bogus get return bogus public static complicated powcomplicated value int exponent if exponent 0 throw new argumentexception only nonnegative exponents supported exponent complicated result 1 complicated factor value for int mask exponent mask 0 mask 1 if mask 0x1 0 result factor factor factor return result public static implicit operator complicatedint real return new complicatedreal 0 public static complicated operator complicated l complicated r var real lreal rreal var bogus lbogus rbogus return new complicatedreal bogus public static complicated operator complicated l complicated r var real lreal rreal 5 lbogus rbogus var bogus lreal rbogus lbogus rreal return new complicatedreal bogus and heres the fully updated source,['c#'] +154660,how to do a fast but innacurate innodb row count the faq of phpmyadmin has this to say about its approximate row counts for innodbphpmyadmin uses a quick method to get the row count and this method only returns an approximate count in the case of innodb tablesi would like to use this quick method but everywhere i search seems to have a different answerdoes anyone know,['mysql'] +154664,list global variables in a c program is there a tool around that will list all the global variables in a c program more specifically is there a simple commandline tool that will do this ie not a heavyweight ide case graphical toolkit system etc but just something that can be run like foo c,['c'] +154665,extracting motion data from a list of coordinates i have a series of csv files of timestamped coordinates x y and z in mm what would be the simplest way to extract motion data from themmeasurablesthe information i would like to extract includes the followingnumber of direction changesinitial acceleration of the first and last movementsand the bearing angle of these movementsaverage speed whilst nonstationaryideally i would eventually like to be able to categorise patterns of motion so bonus points for anyone who can suggest a way of doing this it strikes me that one way i could do this would be to generate picturesvideos of the motion from the coordinates and ask humans to categorise them suggestions as to how i would do this are very welcomenoisea complication is the fact that the readings are polluted with noise in order to overcome this each recording is prefaced with at least 20 seconds of stillness which can serve as a sort of noise profile i am not sure how to implement this thoughspecificsif it helps the motion being recorded is that of a persons hand during a simple grabbing task the data is generated using a magnetic motion tracker attached to the wrist also i am using c but i guess the maths is language agnosticeditsmagnetic tracker spec 800phpsample data file bountyfor the bounty i would really like to see some pseudocode examples,['c#'] +154674,how do i set the windows system clock to the correct local time using c how do i set the windows system clock to the correct local time using c,"['c#', '.net']" +154682,marker bar for c application is there a marker bar component for a c application what i could use in my application as marker bar i mean something like resharper adds to visual studioanother example for something similar the bar on the leftedit i found nonfree component for java bardocsosmarkerjmarkerbarhtml what does exactly what i want to do it doesnt suite for me but maybe it helps someone,['c#'] +154729,how to get all implementorssubclasses of an interface with guice with spring you can define an array property and have spring inject one of every component class that derives from the given typeis there an equivalent for this in guice or an extension point to add this behavior,['java'] +154730,thistributed cachesession solution for aspnet web app i am looking for a thistributed cachesession solution below is what i found i hope anyone could share information regarding pros and cons of using itncachewindows server appfabricmemcached as recommended by tfdi am using aspnet 4 and sql server 2008any idea would be very much appreciated,['asp.net'] +154744,ruby on rails and rake problems uninitialized constant rakedsl i am having a really frustrating issue rake is being dumbheres how the problem comes about rails new test app rails generate scaffold new scaffold field1string field2textboth of those work just fine but then when i do this rake dbmigratei get the following errorin homemikhailtest apprake aborteduninitialized constant rakedslusrlibruby191rakerb2482in const missingusrlibrubygems191gemsrake090libraketasklibrb8in classtasklibusrlibrubygems191gemsrake090libraketasklibrb6in modulerakeusrlibrubygems191gemsrake090libraketasklibrb3in top requiredusrlibrubygems191gemsrake090librakerdoctaskrb20in requireusrlibrubygems191gemsrake090librakerdoctaskrb20in top requiredusrlibrubygems191gemsrailties307librailstasksdocumentationrake1in requireusrlibrubygems191gemsrailties307librailstasksdocumentationrake1in top requiredusrlibrubygems191gemsrailties307librailstasksrb15in loadusrlibrubygems191gemsrailties307librailstasksrb15in block in top requiredusrlibrubygems191gemsrailties307librailstasksrb6in eachusrlibrubygems191gemsrailties307librailstasksrb6in top requiredusrlibrubygems191gemsrailties307librailsapplicationrb214in requireusrlibrubygems191gemsrailties307librailsapplicationrb214in initialize tasksusrlibrubygems191gemsrailties307librailsapplicationrb139in load tasksusrlibrubygems191gemsrailties307librailsapplicationrb77in method missinghomemikhailtest apprakefile7in top requiredusrlibruby191rakerb2373in loadusrlibruby191rakerb2373in raw load rakefileusrlibruby191rakerb2007in block in load rakefileusrlibruby191rakerb2058in standard exception handlingusrlibruby191rakerb2006in load rakefileusrlibruby191rakerb1991in runusrbinrake31in maini have looked about the internet for similarsame errors and people have had them just no one ever seems to solve the problemhow do i fix this problem,['ruby-on-rails'] +154746,how to use itextsharp so i need a pdf generator for my aspnet application i downloaded itextsharp because it seems to be the most popular free one but after searching the internet i am not really finding the information i need to get me started the few tutorials i have found so far are too confusing i know there is a book out there but i am a student and do not want to spend the money i just need really basic stepbystep information preferably with code in vb the most basic tutorial i have found so far is but it is not working for me i tried to follow it and came up with this codeusing systemusing systemcollectionsgenericusing systemlinqusing systemwebusing systemwebuiusing systemwebuiwebcontrolsusing itextsharptextusing itextsharptextpdfusing systemio public partial class default3 systemwebuipageprotected void page loadobject sender eventargs e var doc1 new document string path servermappathpdfs pdfwritergetinstancedoc1 new filestreampath doc1pdf filemodecreate doc1open doc1addnew paragraphmy first pdf doc1closebut it gives me an error cs1502 the best overloaded method match for itextsharptextpdfpdfwritergetinstanceitextsharptextdocument systemiostream has some invalid arguments and the line highlighted is pdfwritergetinstanceso anyway i was wondering if anyone knows either what i did wrong on this tutorial or what other tutorials i can use or if you want to give me a basic explanation of how to get started in your own words that would be great keep in mind i unfortunately know absolutely nothing about this thanks,['asp.net'] +154751,subquery returning multiple columns or a close approximation i have an interesting problem however i do not know quite how to articulate it better than saying i have a subquery that needs to return multiple columns postgresql throws an error when i attempt to do this so while my sql looks somewhat logically sound to me obviously there is a better way to do this i am attempting to merge user permissions into one table hoping to throw this in to a view or even a materialized view of sorts here are my tablescreate table users user id integer not null username character varying32 not null passwd character varying32 not null dept id integer not null last activity timestamp with time zone not null default now constraint pkusersuser id primary key user idcreate table groups group id integer not null group name character varying32 not null add posts integer not null default 0 remove posts integer not null default 0 modify users integer not null default 0 add users integer not null default 0 delete users integer not null default 0 constraint pkgroupsgroup id primary key group idcreate table user groups user id integer not null group id integer not null constraint fkuser groupsgroup id foreign key group id references groups group id match simple on update no action on delete no action constraint fkuser groupsuser id foreign key user id references users user id match simple on update no action on delete no actioncreate table user rights user id integer not null add posts integer not null default 0 remove posts integer not null default 0 modify users integer not null default 0 add users integer not null default 0 delete users integer not null default 0 constraint fkuser rightsuser id foreign key user id references users user id match simple on update no action on delete cascadeand some data to populate theminsert into usersuser id username passwd dept id values 1 nicole12345612insert into usersuser id username passwd dept id values 2 john32463411insert into usersuser id username passwd dept id values 3 susan6123614insert into usersuser id username passwd dept id values 4 mary12136122insert into user rightsuser id add posts remove posts modify users add users delete users values 1001insert into user rightsuser id add posts remove posts modify users add users delete users values 21insert into user rightsuser id add posts remove posts modify users add users delete users values 30insert into user rightsuser id add posts remove posts modify users add users delete users values 40insert into groupsgroup id group name add posts remove posts modify users add users delete users values 1poster110insert into groupsgroup id group name add posts remove posts modify users add users delete users values 2user mgr001insert into groupsgroup id group name add posts remove posts modify users add users delete users values 3admin1insert into user groupsuser id group id values 11insert into user groupsuser id group id values 22insert into user groupsuser id group id values 32insert into user groupsuser id group id values 43insert into user groupsuser id group id values 12what i am trying to do is create a query that can calculate the effective permissions a user might have users are stored in the you guessed it users table groups in groups whatever groups a user might be assigned to are in user groups finally each user can have individual permissions that should override the group permissions those are stored in user rightsi can pull a query of all this information using and yes i know this is uglyselect maxadd posts as add posts maxremove posts as remove posts maxmodify users as modify users maxadd users as add users maxdelete users as delete usersfromselect maxadd posts as add posts maxremove posts as remove posts maxmodify users as modify users maxadd users as add users maxdelete users as delete usersfrom groupswhere group id in select group id from user groups where user id 3union allselect maxadd posts as add posts maxremove posts as remove posts maxmodify users as modify users maxadd users as add users maxdelete users as delete usersfrom user rightswhere user id 3 as combined user groupswhich given the above data will give me the effective permissions for any user i specify in the where clauses what i want to do is create a materialized view that is only updated when the user or group data changes but is otherwise static this i know how to do with no problem the problem i am encountering is generating this view my idea is using the above query but having it run for each user in the users table and creating a user id column so my effective permissions table would look like thisuser id add posts remove posts modify users add users delete users1 1 1 1 1 12 1 1 1 1 13 0 0 1 1 1and so on i just cannot figure out how to add user id to this result and show multiple rows i hope i have provided enough information for someone to understand what it is i am trying to do i realize that ultimately this method can become rather costly performancewise once the tables group in size and this solution seems to be the best one i can come up with to mitigate that problemthe examples provided should work if you want to recreate the sample data for testing purposes i just rebuilt it on my local pg server real quick though it is much simpler than the real tables the same concepts apply,['sql'] +154759,helper fields for not working i am using nested attributes but the fields are not loaded in my viewsomeone know what i missingrails 31 ruby 192model 1class traditionsmaterial activerecordbase has one material asset dependent destroy validates presence of title accepts nested attributes for material assetendmodel 2class traditionsmaterialasset activerecordbase belongs to material has attached file asset validates attachment presence assetendview haml form for material html class form multipart true do f errors for material field flabel title ftext field title field flabel description ftext area description rows 5 field ffields for material asset do ma malabel asset mafile field asset buttonrow fsubmit saveresult html partdiv classfielddivdiv classbuttonrow input namecommit typesubmit valuesave divin above divfield is empty,['ruby-on-rails'] +154761,can i read the c 2011 fthis anywhere i probably cannot but i really would like to can i read the c 2011 fthis anywhere,['c++'] +154763,using ocunit to test if an uialertview is presented i am working on an app that will thisplay a uialertview upon hitting it is exit button only if progress in the game has been made i was wondering how you would use ocunit to intercept the uialertview and interact with it or even detect if it has been presented the only thing i can think of is to monkeypatch uialertviewdelegate willpresentalertview but that makes me want to crydoes anyone know of a better method of doing this,['iphone'] +154774,is there a python equivalent to rubys respond to is a way to see if a class responds to a method in python like in rubyclass fun def hello puts hello endendfun funnewputs funrespond to hello truealso is there a way to see how many arguments the method requires,"['python', 'ruby']" +154787,rails 3 database indexes and other optimization i have been building rails apps for a while now but unfortunately for me none of my apps have had a large amount of data or traffic but now i have one that is gaining steam so i am diving in head first into scaling and optimizing my app it seems the first and easiest step to do this is with database indexes i have got a good huge list of indexes that should cover pretty much all of my queries but when i added them to my database via migrations it only took a few seconds to add them for some reason i thought they would have to go through all of my entries of which there are thousands and index them does this mean my indexes have not been applied to my already existing data will they only be added to new entriesadditionally i am looking into other scaling solutions such as memcached and all around slimming down my queries etcif anyone can point me to some good resources for optimizing my rails 3 app i would greatly appreciate itthankseditthanks for all the great answers regarding database indexes what else should i be looking at in terms of optimizing and scaling my app memcached what has the best performance boosteffort ratio in terms of optimization,['ruby-on-rails'] +154821,inapp purchase ready to submit but would not let me submit it i have some inapp purchases setup for an application the inapp purchases are all tested and working great however i cannot submit them for review i submitted the application binary for review then visited the inapp purchase section all of the inapp purchases say ready to submit but the submit for review button is greyed out and unclickablewhen apple reviews the actual application will they also just review the inapp purchases for it or am i doing something wrongthanksupdate i do not know if it was by switching to chrome or by waiting 30 minutes or so but it enabled me to submit my inapurchases for review,['iphone'] +154823,getter property with arguments i guess i have seen somewhere before but now i cannot remember neither find it is there a way to make a getter property with argumentsi mean as i can convert float getsize to float sizefloat getsize return thissizefloat size get return thissize then could i convert for example float getsizestring unit to float sizestring unit or something like thatfloat getsizestring unit return thissizefloat sizestring unit get if unit unitmeters return thissize100 else return thissize i think there is no really problem of using function at all but may look better this way p,['c#'] +154836,whats your folder layout for a flask app divided in modules i am experimenting with flask coming from django and i really like it there is just one problem that i ran into i read the flask docs and the part about big applications or something like that and it explains a way to divide your project in packages each one with its own static and templates folder as well as its own views module the thing is that i cannot find a way that works to put the models in there using sqlalchemy with the flask extension it works from the interactive prompt to create the tables but when i use it inside the code it breaks so i wanted to know how more experienced flask developers solved this,['python'] +154838,resource interpreted as stylesheet but transferred with mime type texthtml in aspnet iis i am having a login page when executed the page is stripped out of cssi found out this message from from chrome debugger i am using aspnet 2008any ideashead idhead1 runatserver titlecalibprotitle link hrefcsslogincss relstylesheet typetextcss link hrefcsscommoncss relstylesheet typetextcss headedited as per robx advice,"['asp.net', 'css']" +154841,gcov with cmake using a separate build directory i am struggling to get coverage information for gcov no errors during compilation and linking but when i run the executable no coverage data is produced i am using cmake with a separate build directory passing flags to the compiler and linker in this wayadd definitionscoveragesetcmake exe linker flags cmake exe linker flags coveragedoes the executable expect the source code to be in a specific locationwhat do i have to add to my cmakeliststxt to get things goingkind regardsbjoern,['c++'] +154846,can my app integrate with the default android gallery like picasa i am writing an app that involves some media syncing i really love the way picasa integrates into the default gallery mainly the picasa icon on the folder and the thumbnail mechanism ie it loads a thumbnail at first and only if you open the picture it actually gets the full size from the webi know an application can show custom data in the native contacts app for instance using sync adapters so i am looking for ways to do something similar but in the native gallery app without developing a new gallery of coursei guess the question is whether the gallery app is open for addonsplugins or custom behaviors etcfrom what i gather this is impossible but maybe i am missing something thanks,['android'] +154848,decorating a jtextfield with an image and hint i am trying to create some nicer looking jtextfields with an image and a hint to do this i made a decorator that overrides the paintcomponent method the reason i used a decorator is that i wanted to apply it to other types of jtextfield such as jpasswordfield here is what i have made so farthe problem as seen in the form on the left is that even though i have used a jpasswordfield the paintcomponent seems to ignore what i assume is the passwords paintcomponent which presumably does the password masking symbolsso the question is how can i avoid duplicating the code for jtextfields and jpasswordfields but still have the different functionality such as password maskingthis is the decorator codepublic class jtextfieldhint extends jtextfield implements focuslistenerprivate jtextfield jtfprivate icon iconprivate string hintprivate insets dummyinsetspublic jtextfieldhintjtextfield jtf string icon string hint thisjtf jtf seticoncreateimageiconiconsiconpngicon thishint hint border border uimanagergetbordertextfieldborder jtextfield dummy new jtextfield thisdummyinsets bordergetborderinsetsdummy addfocuslistenerthispublic void seticonicon newicon thisicon newiconoverrideprotected void paintcomponentgraphics g superpaintcomponentg int textx 2 ifthisiconnull int iconwidth icongeticonwidth int iconheight icongeticonheight int x dummyinsetsleft 5 textx xiconwidth2 int y thisgetheight iconheight2 iconpainticonthis g x y setmarginnew insets2 textx 2 2 if thisgettextequals int width thisgetwidth int height thisgetheight font prev ggetfont font italic prevderivefontfontitalic color prevcolor ggetcolor gsetfontitalic gsetcoloruimanagergetcolortextinactivetext int h ggetfontmetricsgetheight int textbottom height h 2 h 4 int x thisgetinsetsleft graphics2d g2d graphics2d g renderinghints hints g2dgetrenderinghints g2dsetrenderinghintrenderinghintskey text antialiasing renderinghintsvalue text antialias on g2ddrawstringhint x textbottom g2dsetrenderinghintshints gsetfontprev gsetcolorprevcolor protected imageicon createimageiconstring path string description javaneturl imgurl getclassgetresourcepath if imgurl null return new imageiconimgurl description else systemerrprintlncould not find file path return null overridepublic void focusgainedfocusevent arg0 thisrepaintoverridepublic void focuslostfocusevent arg0 thisrepaintand this is where i create the fieldsjtextfield usernamefield new jtextfieldhintnew jtextfielduser greenusernamejtextfield passwordfield new jtextfieldhintnew jpasswordfieldbullet keypasswordhopefully i have not went completely off in the wrong direction herethanksedit again the more i look at it it is obvious that calling superpaintcomponentg is going to call the jtextfields paintcomponent but i cannot see how to solve this without duplicating the code,['java'] +154849,how to let user know heshe needs to install another app that my app depends on i am developing an application which has defined some intent filters in the form of action strings eg comexampleprojectupload for other applications to use consider a device that did not have my application but with applications that use my intent filters the intent created will fail the action test as described in the documentation is there any way to prevent this happening or give a better user experience here are some of the approaches i can think of but do not know if there are feasiblewhile installing an application that depends on another applications to handle some of the intents suggest user to install the application that can handle the intentdynamically determine if the intent can be handled if not launch the market showing the application that can handle the intentwhat is the best approach to handle this please provide some implementation references if possible,['android'] +154862,mysql query to select data from last week hi i have a table with a date field and some other informationsi want to select all entries from the last week week start from sundaytable values id date2 20110514 0917255 20110516 0917256 20110517 0917258 20110520 09172515 20110522 091725i want to select all ids from last week expected out out is 5 6 8id 2 not in last week and id 15 is in current weekhow to write and sql query for the same,"['mysql', 'sql']" +154867,cannot save image as blob to sqlite i am using sqlite and i cannot save a image to the database this is my code file file new fileurl try fis new fileinputstreamfile catch filenotfoundexception e filelenght int filelengthstatexecuteupdatecreate table tablename id intname string image blob features stringprep connpreparestatementinsert into tablename values prepsetbinarystream3 fis filelenghtthis is the error i am gettingjavasqlsqlexception not implemented by sqlite jdbc driver at orgsqliteunusedunusedunusedjava29 at orgsqliteunusedsetbinarystreamunusedjava58i am using the following jar sqlitejdbcv056jar any ideasthanks,['java'] +154870,jquery datatables return additional information from server using jquery datatables and all is going well i have worked out how to send addtional information from the client to the server now i want to go back the other wayso how do i send extra information from the server to the client i would have thought i could add an extra entry in the returned json and pull it out somewhere one item i would perhaps like to send back is how long the server took to handle the response i can then show this information to the userany help would be much appreciated thanks,['jquery'] +154885,is there a parent child relationship between absolute and relative positioning in css i am new to the world of coding as well as css having read a number of articles regarding relative and absolute positioning my understanding is as follows however i am unsure if an absolute position should be the child of a parent relative position or vice versa there are 4 position properties that is static relative absolute and fixedif an element has a relative position it is still part of the normal flow of the document however it has the ability to be offset by the properties top right bottom and leftit also is able to be given a zindex value and is automatically positioned above static elementsit also provides a method of containing child elements that are part of its code block although i am unsure exactly what this meansbased on this information does this mean that elements with the position absolute should be children of elements with the position relative or vice versa or does it not matterif it does not matter when would you make them dependent upon one another eg parentchild relationship,"['html', 'css']" +154896,codeigniter load controller within controller i have a home controller with an index action that thisplays a set of featured products however the products are managed through a product controller including a proprietary model and viewshow do i access product information from within the index action in the home controller instancing product would not work as the class is not loaded at runtime and codeigniter does not provide a way to dynamically load controllers putting the product class into a library file does not really work eitherto be precise i need the product views filled with data processed by the product controller inserted in the index view i am running codeigniter 202,['php'] +154899,how can i keep my android service running when the screen is turned off when the screen turns off my application service is pausedi start my service with the following codeif msharedprefsgetbooleanprefautoupdatesmain false intent svc new intentthis myserviceclass startservicesvchow can i can avoid the service pausewhat i have to do in myservice is to download some data from internet if i have understand the process i have to follow isacquire wakelockdownload datarelease wakelockin downloading data method there are no reference to wakelock it is the application to have the wakelock is it correctwake locks are reference counted by default i think it is better a wakelock without reference counting to be sure to release it am i wrong,['android'] +154915,doing native gui with ruby i would like to develop a desktop app with ruby however i would like to have a native gui on every platform as opposed to a crossplatform gui toolkit that looks consistently awful across all platformsi expect to have to do different guis for each platform as it is not just looks but also behaviors and idioms that are different but i wonder what my options are especially wondering if there is a clean way to separate front and backend and bind the data properlytarget platforms are windows vista 7 xp is a bonus mac os x cocoa and linux gtk qt no idea,['ruby'] +154918,check content in class files suppose one learned that certain developer hardcoded a bunch of usernames and passwords into application which made it into production ohoh you know both username and password is there a way to scan the bytecode and identify whether in fact username password was hardcoded,['java'] +154924,google maps api and kml file localhost development options the google maps javascript version 3 api library documentation clearly explainsthe google maps api supports the kml and georss data formats for thisplaying geographic information these data formats are thisplayed on a map using a kmllayer object whose constructor takes the url of a publicly accessible kml or georss filethere are even several stack overflow questions about how to load local dataloading a local kml file using google mapsgoogle maps kml filessome of the answers have pointed to third party libraries which can parse kml locally without the file needing to be publicgeoxml3geoxmlegeoxmland while these solutions are good if you have a need to keep your data private i simply want to make development easier when running locally i obviously cannot parse my kml and therefore lose functionality that i am trying to test i have posted a single generic kml file on a publicly available site but then have to have different development code to render one thing vs something else when running for realwhat are my options for local development to render what would be publicly available dynamically generated kml files,['javascript'] +154925,how to include a module to a rake namespace in separate files i have a module and a child class where i have all the functionality inside the module and inside the child class i just call the methods from the module i want this module to be linked with a rake task under a namespace and these two files are in the same directory rails rootlib how do i do this i am running rails 303,"['ruby-on-rails', 'ruby']" +154926,how to fix an unsatisfiedlinkerror cannot find dependent libraries in a jni project i am working on a java project that uses the jni the jni calls a custom library that i have written myself let us say mylibdll and that depends on a 3rd party library libsndfile1dllwhen i run my program it crashes with javalangunsatisfiedlinkerror cpathmylibdll cannot find dependent librariesi have searched this site and others and i have tried a number of fixesi ran dependency walker dw gave a couple of warnings that two libraries required by libsndfile mprdll and shlwapidll had unresolved imports but the dw faq said that these warnings could be safely ignored i fixed the method names in mylibdll as suggested here the method names had somehow gotten mangled by the compiler but i added linker flags and the dll method names now match those in my jni header file exactlyi put all of these dlls in the same directory the same directory as the jar that calls them to ensure that they are on the right pathno dicedoes anyone have any idea whats going oni am doing my development in visual studio 2010 on a macbook pro via parallels i am doing my testing in windows xp on a toshiba laptop,['java'] +154931,is there a way to check if geolocation has been declined with javascript i need javascript to thisplay a manual entry if geolocation is declinedwhat i have triedmodernizrgeolocationnavigatorgeolocationneither describes if user has previously declined access to geolocation,['javascript'] +154946,isproj cannot be opened because of its project type isproj is not supported i have got 2 vs 2008 based solutions i am opening up and both have projects that are net 35 but when i open both solutions in vs 2008 both have some isproj files and i get this stupid error right after i open the solutioncsomefilenameisproj cannot be opened because its project type isproj is not supported by this version of the applicationwhen i open the isproj i see that the project version appears to be vs 20089030729so i do not understand why i would still be getting this error and i have never even seen or at least had an error with a file of extension isproj in any of my apps before i guess it is used for ms build,['asp.net'] +154953,how to remove lowercase on a textbox i am trying to remove the lower case letters on a textbox for example short alpha code representing the insurance eg bcbs for blue cross blue shieldtxtdesctext blue cross blue shieldstring code this must be bcbs is it possible please help me thanks,"['c#', '.net']" +154968,php in array horrible performance fatest way to search array for value i have the following simple code to test against collision on a primary key i am creatingmachine ids arrayfori 0 i 10 i generate machine id returns a 15 character alphanumeric string mid functionsgenerate machine id ifin arraymid machine ids diecollision else machine ids mid diesuccessany idea why this is taking many minutes to run anyway to speed it up,['php'] +154978,windowlocation not working not opening page i have a submit button with a onclickdiv idmessagedivformtextarea namemessage rows10 cols20textareatextareabr br input typesubmit valuesend onclicksendmailinput typereset valuereset nameresetformdivthen i have my sendmail function sendmail windowlocationhref mailid windowlocationmailid return true mailid is a global variable that gets set in another js function and it does contain the correct value how come windowlocation is not opening my pageif i manually open it with a mailid it works fine,"['javascript', 'html']" +155008,maximum call stack size exceeded error i am using a direct web remoting dwr javascript library file and am getting an error only in safari desktop and ipadit says maximum call stack size exceededwhat exactly does this error mean and does it stop processing completelyalso any fix for safari browser actually on the ipad safari it says jsexecution exceeded timeout which i am assuming is the same call stack issue,"['javascript', 'html']" +155026,how to find out ios version is it possible to read the ios version 421 433 etc running a monotouch app if so how,['ios'] +155033,speed up msbuild with fsutil hardlink create instead of slow copy tasks i am trying to do speed up our build csharp msbuild net 35 replace copy with fsutil hardlink createpreviously i almost got it with running a script over sln files and making the dll references private false then having a post build event create the hardlinks problem is transitive dependencies are not included so i think i need to reference the resolveassemblyreference task in msbuild to get the transitive dependencies i need to hardlink any ideas this person tried the same thing but did not post an final solutionto be clear what i want is to keep separate bin directories but instead of copying file from one to another to create a hard link from a source of a reference or a dependency to the destination the current projects bin which is much faster and gives approximately the same effect as copying,"['c#', '.net']" +155054,how do i write a custom json deserializer for gson i have a java class userpublic class user int id string name timestamp updatedateand i receive a json list containing user objects from a webserviceid1namejonasupdate date1300962900226id5nametestdate date1304782298024i have tried to write a custom deserializeroverridepublic user deserializejsonelement json type type jsondeserializationcontext context throws jsonparseexception return new user jsongetasjsonprimitivegetasint jsongetasstring jsongetasint timestampcontextdeserializejsongetasjsonprimitive timestampclassbut my deserializer does not work how can i write a custom json deserializer for gson,['java'] +155063,javascript on ios opening an html select element i am not hopeful but i will ask just in casei would like to be able to use javascript to open a select element in mobile safari for iphoneipadan extensive google stack overflow search shows that a lot of people would like to be able to do this in browsers in general but it is not supported why not i wonder various hacks have been suggested from calling focus on the select element and changing its size property to make more option elements visible or constructing an entirely mock select element with div and ul elements i would however like to use the native browser select controls in ipad and iphonei wondered just maybe someone might know of a proprietary apple webkit method to do this it would be something likevar myselect documentgetelementsbytagnameselect0myselectopen this method does not existas a bonus it would also be handy to know of a boolean property that says whether the select element is currently openactive or not ie not just whether the element has focus i know i can work this out by tracking click and change events but a simple property would be usefulwishful thinkingupdatei do not yet have the answer but i have found that simulating a mousedown successfully opens a select element in google chrome but not ipad or firefox and so onfunction simulatemouseeventeventname element var evt documentcreateeventmouseevents evtinitmouseeventeventname true true window 0 0 0 0 0 false false false false 0 null elementthispatcheventevtsimulatemouseeventmousedown selectupdatei have asked a related but different and similarly unanswered question on select boxes here is there a dom event that fires when an html select element is closed,"['javascript', 'iphone', 'html', 'ios']" +155064,how can i make a textbox control that is multiline not be resizable how can i make a textbox control that is multiline not be resizablei am using aspnet with c and i cannot find an option to do this,['asp.net'] +155088,inplace way to apply a permutation to a list inverse of sortingbykey heres a example of what i want to dospam list we are the knights who say nispam order 0124563spam listmagical sortspam orderprintspam listwe are the who say ni knightsi can do it with enumerate list and so on but i would like to directly affect spam list like listsort and not copy it like sortededit pushed a string example to avoid confusion between indices and values of spam listedit turned out this is a duplicate of python sort parallel arrays in place well i cannot delete so much efforts for so consistency arguments,['python'] +155109,are mixin class init functions not automatically called in python i would like to use a mixin to always add some init functionality to my child classes which each inherit from different api base classes specifically i would like to make multiple different child classes that inherit from one of these different apisupplied base classes and the one mixin which will always have the mixin initialization code executed in the same way without code replication however it seems that the init function of the mixin class never gets called unless i explicitly call it in the child clas init function which is less than ideal i have built up a simple test caseclass apibaseclassoneobject def init self args kwargs print base class somemixinobject def init self args kwargs print mixin before supersomemixin self init args kwargs print mixin after class myclassapibaseclassone passclass mixedclassmyclass somemixin passas you can see in the following output the mixin functions init never gets called import test testmixedclass basetestmixedclass object at 0x1004cc850is there a way to do this have an init function in a mixin get called without writing every child class to explicitly invoke the mixins init function ie without having to do something like this in every classclass mixedclassmyclass somemixin def init args kwargs somemixin init self args kwargs myclass init self args kwargs btw if all my child classes were inheriting from same base class i realize i could create a new middle class that inherits from the base class and the mixin and keep it dry that way however they inherit from different base classes with common functionality django field classes to be precise,['python'] +155111,find out the differences between two java beans for version tracking say i have a java beanan entity with 100 fields inherited or not it is not relevant in this case after update operations in a transaction i want to determine which fields are modified to track updates like a cvs what is the easiest way to do this any framework suggestion should i make two instances of this object and iterate over all fields and match the values of fields how would the best equals method seem in such situations the following equals seems very awkward return field1equalsofield1 field2equalsofield2 field3equalsofield3 field100equalsofield100,['java'] +155118,django template context processors breaking my app i was trying to set up a template context processor like this article mentions so that i could provide information to every templatei wrote this function in viewspydef items in cartrequest used by settingstemplate context processors to provide an item count to every template cart lines get users cart and linesrequest return items in cart linescountand then i added this line to settingspytemplate context processors storeviewsitems in cartbut now whenever i go to any page i get this errorimproperlyconfigured at put djangocontribauthcontext processorsauth in your template context processors setting in order to use the admin applicationdid i do something wrong whats going on here i tried doing what the error said and then it will render a page with all of my style sheets and images missing,['python'] +155124,multiple cursors in nested loops in mysql i wish to do something which appear a bit complicated in mysqlin fact i wish to open a cursor do a loop and in this loop open a second cursor using the data from the previous fetch to be executed and reloop on the results declare idind int declare idcrit int declare idindid int declare done int default 0 declare done2 int default 0 declare curindicateur cursor for select id indicateur from indicateur declare curcritereindicateur cursor for select cid critere from critere c where cid indicateuridind declare continue handler for sqlstate 020 set done 1 set idindid54 open curindicateur repeat fetch curindicateur into idind open curcritereindicateur repeat fetch curindicateur into idcrit insert into sla demande status iddemandeidindicateurindicateur statusprogression values09idcritok100 until done end repeat close curcritereindicateur until done end repeat close curindicateurin fact how to do until done differently for the two cursors because you can only declare one handler for sqlstateif the first ends the second ends too,['mysql'] +155126,sql query for updating database if value is not null i am having a table which has about 17 fields i need to perform frequent updates in this table but the issue is each time i may be updating only a few fields whats the best way to write a query for updating in such a scenario i am looking for an option in which the value gets updated only if it is not nullfor example i have four fields in database say abcduser updates the value of say d all other values remains the same so i want an update query which updates only the value of d keeping the others unaltered so if i put ab and c as null and d with the value supplied by user i want to write an update query which only updates the value of d as ab and c is nullis it something achievable i am using sqlite databasecould someone please throw some light into it,['sql'] +155140,javascript catch parameter already defined i am trying to understand why i am getting the following error not how to work around itpassing the following code to jslint or jshint yields the error err is already definedjslint white true devel true onevar true browser true undef true nomen true regexp true plusplus true windows true bitwise true newcap true strict true maxerr 50 indent 4 function xyzzy use strict try step 1 catch err try step 2 catch err the obvious assumption here is that catch behaves or should behave like a function thus err is neither a global variable nor a local variable to xyzzy but a parameter for the catch blockin browsing the ecma262 standard section 1214 describing the try statement indicates that the catch clause takes an identifier that is bound to an exception additionally the semantic production rule for catch refers to a parameter that is passed calling out identifier as an argumentthis seems to suggest to the casual reader that the above code is valid and that perhaps the lint tools have a bugeven intellijs strictest javascript code inspection analysis does not report there being a problem with err being redefinedmore of a concern if it is a variable scoping concern then one might surmise that the err is bleeding into the global space which poses a whole host of other problems and that instead one should declare it up front like thisjslint white true devel true onevar true browser true undef true nomen true regexp true plusplus true windows true bitwise true newcap true strict true maxerr 50 indent 4 function xyzzy use strict var err declare err so it is certainly local try step 1 catch err try step 2 catch err but this only results now in two errors about err at each of the catch statements making the problem worse and potentially introducing variable shadowingthe lint tools are suggesting that each catch block introduces not just it is own lexical scope but a new variable as well this cannot be rightsimply making err1 err2 to placate the static analysis tools merely hides the symptom and does not contribute to cleaner codejavascript gurus is this a bug in the lint tool a dark corner with the javascript spec or a fundamental misunderstanding of whats happening hereupdate wrote to douglas crockford author of jslint and it turns out there is a very valid reason for this warning see answer below,['javascript'] +155158,what is nsindexpath what exactly is the job of nsindexpath what i understand is indexpath variable is used to refer the cell which we want to thisplay o but what value does it store i mean what is the internal process that happen to setup an indexpath variable,"['iphone', 'objective-c']" +155178,process crashes during creation of roboguice injector if there is a mocked instance in any module i have a problem with using roboguice and androidmock frameworks in unit testingi have created a simple project to show my problem here i create a mocked instance and register it in the roboguicebut the process crashes between the setup and test01 methodsas i guess actually the process crashes when the injector is created if any module has a mocked instance insideif i replace the mocked instance with an instance of a class that implements the interface then everything works finedoes anybody know how to fix this problemhere is my test codepublic class testinjectmock extends robounittestcasemyapplication protected void setup throws exception interfacetomock instance androidmockcreatenicemockinterfacetomockclass androidmockexpectinstancesimplemethodandstubreturnhello mymodule mymockmodule new mymodule mymockmodulesetmockedinstanceinstancecomment this string to get into the test01 method myapplicationsetmymodulemymockmodule supersetup public void test01 it never comes here module source codepublic class mymodule extends abstractandroidmodule protected interfacetomock mockedinstance public void setmockedinstanceinterfacetomock mockedinstance thismockedinstance mockedinstance override protected void configure ifmockedinstance null bindinterfacetomockclasstoinstancemockedinstance the logcat output0523 161707135 infodebug27 build fingerprint genericsdkgeneric21update1eclair35983engtestkeys0523 161707135 infodebug27 pid 2025 tid 2031 injectmocktest 0523 161707145 infodebug27 signal 11 sigsegv fault addr 0523 161707155 infodebug27 r0 0011b218 r1 43d1caa0 r2 0 r3 0523 161707155 infodebug27 r4 43d1caa0 r5 0011b218 r6 451c0e30 r7 40a9580523 161707155 infodebug27 r8 ad00f380 r9 00138de0 10 426bda34 fp 00138de00523 161707155 infodebug27 ip 02 sp 451c0dc0 lr ad05ad1d pc ad05a804 cpsr 0300523 161707295 infodebug27 00 pc 05a804 systemliblibdvmso0523 161707305 infodebug27 01 pc 05ad18 systemliblibdvmso0523 161707305 infodebug27 02 pc 054a4a systemliblibdvmso0523 161707315 infodebug27 03 pc 013f58 systemliblibdvmso0523 161707325 infodebug27 04 pc 0198 systemliblibdvmso0523 161707335 infodebug27 05 pc 018d5c systemliblibdvmso0523 161707335 infodebug27 06 pc 04d6d0 systemliblibdvmso0523 161707345 infodebug27 07 pc 04d702 systemliblibdvmso0523 161707355 infodebug27 08 pc 041c78 systemliblibdvmso0523 161707365 infodebug27 09 pc 010 systemliblibcso0523 161707365 infodebug27 10 pc 0fad4 systemliblibcso0523 161707375 infodebug27 code around pc0523 161707385 infodebug27 ad05a7f4 f5ae0 fe57c4 6801b5f8 6a8b1c05 0523 161707385 infodebug27 ad05a804 1c30681e ff5ef7ff 28001c04 6840d018 0523 161707395 infodebug27 ad05a814 d0152800 37101c27 d0112f00 f7ff1c28 0523 161707395 infodebug27 code around lr0523 161707405 infodebug27 ad05ad0c f7ff1c20 bd10ff7b 6804b510 fd70f7ff 0523 161707405 infodebug27 ad05ad1c 28001c01 f7ffd102 e002f859 f7ff1c20 0523 161707415 infodebug27 ad05ad2c bd10ff6d 4c24b5f0 1c0d1c06 48236a81 0523 161707425 infodebug27 stack0523 161707425 infodebug27 451c0d80 43d20870 devashmemmspacedalvikheap2 deleted0523 161707425 infodebug27 451c0d84 0354 0523 161707425 infodebug27 451c0d88 022 0523 161707425 infodebug27 451c0d8c ad043693 systemliblibdvmso0523 161707425 infodebug27 451c0d90 ad07ff50 systemliblibdvmso0523 161707425 infodebug27 451c0d94 024 0523 161707425 infodebug27 451c0d98 0354 0523 161707425 infodebug27 451c0d9c ad0170ac systemliblibdvmso0523 161707425 infodebug27 451c0da0 0 0523 161707435 infodebug27 451c0da4 afe0f2c0 systemliblibcso0523 161707435 infodebug27 451c0da8 ad080c00 systemliblibdvmso0523 161707435 infodebug27 451c0dac 02 0523 161707435 infodebug27 451c0db0 0354 0523 161707445 infodebug27 451c0db4 43d20870 devashmemmspacedalvikheap2 deleted0523 161707445 infodebug27 451c0db8 df0027 0523 161707455 infodebug27 451c0dbc e3a070ad 0523 161707455 infodebug27 00 451c0dc0 0 0523 161707455 infodebug27 451c0dc4 43d1caa0 devashmemmspacedalvikheap2 deleted0523 161707455 infodebug27 451c0dc8 451c0e38 0523 161707455 infodebug27 451c0dcc 451c0e30 0523 161707455 infodebug27 451c0dd0 40a958 devashmemmspacedalvikheapzygote0 deleted0523 161707455 infodebug27 451c0dd4 ad05ad1d systemliblibdvmso0523 161707465 infodebug27 01 451c0dd8 417a0b5c datadalvikcachesystemclassesdex0523 161707475 infodebug27 451c0ddc ad054a4f systemliblibdvmso,"['java', 'android']" +155180,creating a dialog jquery mobile i am trying to create a dialog with jquery mobile i have tried to refer to the accepted answer in this so question but it did not work for me here is my code div datarolepage idfirst code div id dialog datareldialog div id errortextdiv button id closedialogokbutton divdivand here is the js to make it inside a functionnothing checked cannot continue add error message to diverrortexthtmlyou must check the checkbox next to i agree to continueopen dialogdialogdialogwhen the code to create the dialog is reached nothing happens suggestions,['jquery'] +155183,how to correctly use textswitcher in listview my textswitcher for each record in listview should thisplay first value text1 and then another value text2 then first value again and so on it should happen only if text2 not empty otherwise text1 should be always shown without any changes and animationi have created runnable which changes boolean variable time2 to then call itemsnotifydatasetchanged it works as expected and in result setviewvalue for my listview is calledhere is the codeitemssetviewbindernew simplecursoradapterviewbinder override public boolean setviewvalueview view cursor cursor int columnindex int viewid viewgetid switchviewid case ridtimetext textswitcher itemtime textswitcher view if itemtimegetchildcount 2 itemtimeremoveallviews itemtimesetfactorynew viewswitcherviewfactory override public view makeview textview t new textviewmyactivitythis tsettextsize18 tsettypefacenull typefacebold tsettextcolorcolorwhite return t itemtimesetanimatefirstviewtrue itemtimesetinanimationanimationutilsloadanimationmyactivitythis ranimpush up in itemtimesetoutanimationanimationutilsloadanimationmyactivitythis ranimpush up out if text2equals if time2 itemtimesettexttext1 else itemtimesettexttext2 else itemtimesetcurrenttexttext1 return true return false it works almost as expected with one minor item when text2 should be shown it changes thisplayed value to some other value first from another record and then animation is played change of text2 to text1 happens correctlymy understanding that the reason is the following before thisplaying text2 all views of itemtime are removed and hence it is recreated and that is why some other value is shown for a second but why does it show value from some other recordactually text2 and text1 are values from the database for extext2 cursorgetstringcursorgetcolumnindexorthrowdbadapterkey time 2 probably something is wrong here and setviewvalue called with wrong parametersupd text1 and text2 are read from the database at setviewvalue here is example of the full code itemtimesettextcursorgetstringcursorgetcolumnindexorthrowdbadapterkey close time 1 cursorgetstringcursorgetcolumnindexorthrowdbadapterkey open time 1,['android'] +155195,binary search on keys of sortedlist i need to write some code for linear interpolation and i am trying to figure out the most efficient way to search the keys of a sortedlistk v for the upper and lower keys that surround my target keysortedlistint double xytable new sortedlistint double 1 10 2 20 3 30 440double targetx 35what is the most efficient way to search the list and determine that 35 is between 3 and 4 i have a method cheat that works for integers temporarily insert the target key into the list then find the index but i figured i would ask the pros so i could produce quality codethanks,['c#'] +155201,how to implement a qthread that runs forever with a qwaitcondition but still needs to catch another slot while doing that i implemented a class that can write data to a serial port via a qqueue and read from it by a slot i use qasyncserial for this which in turn uses boostasio with a callbackthe class is moved to a thread and its start method is executed when the qthread emits startedthe problem is that i dequeue the qqueue in the startmethod using forever and a qwaitcondition while this is running which obviously runs forever the slot connected to the datareceived signal of qasyncserial can not be called thus i never read anything from the serial portwhat is the usual approach to this problemserialporthandlerserialporthandlerserialport serialport qobject parent qobjectparent serialportserialport m enqueuemessagemutex new qmutex m messagequeue new qqueuebasemessage m waitcondition new qwaitcondition serialopenserialportdevicename 2400 connectserial signaldatareceivedqbytearray this slotserialslotreceiveddataqbytearrayvoid serialporthandlerserialslotreceiveddataqbytearray line qdebug qstringlinetoasciivoid serialporthandlersendtestping pingmessage msg new pingmessage enqueuemessagemsgvoid serialporthandlerenqueuemessagebasemessage msg qmutexlocker lockerm enqueuemessagemutex m messagequeueenqueuemsg m waitconditionwakeallvoid serialporthandlerstart if serialisopen return forever m enqueuemessagemutexlock if m messagequeueisempty m waitconditionwaitm enqueuemessagemutex basemessage msg m messagequeuedequeue serialwritemsgencodeforwriting m enqueuemessagemutexunlock the changed qasyncserial callback used by boostasiovoid qasyncserialreadcallbackconst char data size t size emit datareceivedqbytearrayfromrawdatadata int sizeediti solved this problem with another approach i ditched qasyncserial and instead used the callbackasyncserial which is also thistributed by qasyncserial directly now the callback used by boostasio is the serialslotreceiveddata slot this solves the problem since the callback is called in the thread boostasio runs in since it has its own thread it does not matter that the thread serialporthandler runs in is blocked by the forever loopnew code since qasyncserial is something like a wrapper to callbackasyncserial only some trivial things changedserialporthandlerserialporthandlerserialport serialport qobject parent qobjectparent serialportserialport m enqueuemessagemutex new qmutex m messagequeue new qqueuebasemessage m waitcondition new qwaitcondition serial is now callbackasyncserial and not qasyncserial serialopenqstringserialportdevicenametostdstring 2400 serialsetcallbackbindserialporthandlerserialslotreceiveddata this 1 2 m messageprocessingstate messageprocessingstateinactivevoid serialporthandlerstart if serialisopen return forever m enqueuemessagemutexlock if m messagequeueisempty m waitconditionwaitm enqueuemessagemutex basemessage msg m messagequeuedequeue qbytearray encodedmessage msgencodeforwriting serialwriteencodedmessageconstdata encodedmessagelength m enqueuemessagemutexunlock,['c++'] +155216,combination of like and in using tsql how can i do this kind of selectionselect from street where streetname like in main street foo please do not tell me that i can use or because these actually comes from a query,['sql'] +155231,remove all the characters after sign using javascript i want to remove all the characters that appear after sign in my string using javascriptis there any function in javascript which can help me achieve this i am quite new to client side scriptingthanks,['javascript'] +155239,visual studio 2010 debug not starting f5 or click on play not working not doing anything waiting 23 minutes solves the issue i have a relatively simple c framework 4 console application when i click the play icon or hit f5 ie start the program in debug mode the icon becomes gray for a second then goes back to green but nothing happens if i wait 2 or 3 minutes and try again the debug session starts up normally breakpoints are hit and everything things i have tried without successcleaning the solution then rebuildingrenaming the output assemblyrestarting visual studio the only thing that works is just waiting i do not see any related processes still running during these 23mins svchost conhost vshost or cmd,['.net'] +155255,how to generate unique number of 8 digits i am using this code to generate a 8 digit unique numberbyte buffer guidnewguidtobytearrayreturn bitconvertertouint32buffer 8tostringdoes this code really generate a unique number or might it repeat the same number again,['c#'] +155271,deleting cookies from a controller i set some cookie values in my form using jquery i can read them just fine in my rails controller via the cookies method when i call cookiesdeletemy key they appear to be gone when i call cookies again but when i reload the page the cookies are back againis there a way to delete the cookies for good from inside my controllereditthis is very strange since i am looking at the response headers and they seem to be deleting the cookie maybe it is because it is a 302 requestsetcookie my key path expiresthu 01jan1970 0 gmt,['ruby-on-rails'] +155278,how do i strip non alphanumeric characters from a string and keep spaces i want to create a regex that removes all nonalphanumber characters but keeps spaces this is to clean search input before it hits the db heres what i have so farsearch query search querygsub09azi problem here is it removes all the spaces solutions on how to retain spaces,"['ruby-on-rails', 'ruby']" +155295,richtext wysiwyg editor without ui javascript api only i am looking for a very clean project to add crossbrowser javascript api to contenteditable divif it has ui then it should be possible not to load it as opposed to thisabling it or completely remove from sourcesi am looking for basic features really without huge focus on backwardcompatibility but rather a cleaner codesome of the features i would expect from this api would beinsert html snippet at the position of the cursorclean up contents after paste such as spans and font sizesreturn node where cursor currently is positionedadd new item to item listi suppose i could code them with some jquery but if someone have it why not reuse it,['javascript'] +155299,what is the preferred method for passing server data to a requirejs module is there a preferred way to pass server data in a requirejs module our current implementation looks like the following code snippets using a page object to hold any serverdynamic data and passing that to the main bootstrap we do not want to use ajax to populate any dependencies at this timefrom a server page script datamainscriptsmain srcscriptsrequirejqueryjsscriptscript typetextjavascript definepage function return guid guidnewguid scriptmainjsrequirejquery jqueryalpha page function alpha page alphainitializepagejqueryaphajsdefinejquery page function page return initialize function consolelogpageguid logs guid as expected,"['javascript', 'jquery']" +155343,php convert a blob into an image file is this possible with php and a mysql database to convert a blob into an image file,"['php', 'mysql']" +155364,sphinx the best practices i just started to use sphinx tool to generate a documentation for my code but i am a bit confused because it is not as easy as i expected i create the sphinx doc usingsphinxquickstartand then i create my rst files into the source folder seems like i need to create a rst file for each module i want to create a document for for testpy i create testrst inside testrst i have automodule test members showinheritancethen inside testpy i have module test platform unix windows synopsis a useful module indeedthen i generate the documentation usingsphinxbuild b html source buildeverything works as expected but the problem is that it is not as easy as i expected i guess that there must be an easier way to do it with skipping some of these steps i wonder if there is any way to generate a documentation for all the modules inside a package instead of generating a rst file for each modulethanks,['python'] +155368,how to wrap lengthy text in a spinner i have two spinner and edittext controls within a table layout view on a separate row the spinners are populated with data my problem is the data texts that are populated into the spinners are too lengthy to fit the screen size therefore the spinners are forced to stretch unnecessarily stretching other controls on another rowit is a must for me to show the texts in the spinner hence using ellipses is not an option if it is possible how can i wrap the lengthy text on the spinners,['android'] +155374,tool to extract java stack traces from log files is there any tool that can extract a list of stack traces appearing in the log file and probably count unique ones edit i would preffer something that is not guibased and be run on the background and give some kind of report back i have quite many logs gathered from several environments and just would like to get quick overview,['java'] +155379,why would magento fail to save a customer after generating an id i am attempting to track down the cause of a rare bug love those intermittent bugs where a customer selects to register at time of checkout but when the order is completed magento somehow fails to save the customer record this results in an orphan order with no email address a difficult customer service situation here are the results of my investigations so far the sales order view in adminhtml reports that the customer is a guest and the email address is blank billing and shipping addresses are visiblecustomer is guest is false in sales flat orderthe sales flat order entry links to a valid record in sales flat order address the sales flat order address record contains values for customer id and customer address id however those linked records do not existthere is no thiscernible pattern in customer information products ordered payment methodsthere are no relevant entries in systemlog exceptionlog apache error logs varreports or any other logs that i am aware ofthoughts the customer save is progressing far enough that an id is generated there is an observer on customer save after that is causing a rollback of the savea lowlevel database error is causing the save to faildoes anyone have any suggestions on how to track this downversion is enterprise 19,"['php', 'mysql']" +155381,changing thisplayed android device name in eclipse when attaching several android devices to my development machine it quickly becomes difficult to determine which device is which from eclipse because the device names appear to be represented as their serial numbersfor instance the devices listis there any way to thisplay the phone model or to change the device name,['android'] +155391,autorotation lock programmatically does anybody know if there is a possibility to lock autorotation of iphone programmatically for just one viewi want to make some kind of help with semitransculent view but i want to support only landscape orientation even all other views can rotateso i wish to lock rotation when this view is on the toptnxedit more details one uicontroller has 7 uiviewand i wish to lock the autorotation just when the last one occurs on the top,"['iphone', 'objective-c']" +155393,checking for interactive shell in a python script i need to determine whether the shell which invoked my python script was in interactive mode or not if it was in interactive mode the program should pipe output to less1 for easy reading if not it should simply print its output to stdout to allow it to be piped away to a printer file or a different pagerin a shell script i would have checked if the prompt variable ps1 was defined or looked for the i option among the flags stored in the variablewhat is the preferred method for testing interactivity from within python,['python'] +155394,rails how to add add index to existing table i already migrated a table called units with several columns i was wondering how to migrate in a stand alone add index to this table using the cmd is this code correctclass addindextounits activerecordmigration def selfup add index units lesson id end def selfdown remove units endendi have a feeling the selfdown could be wrong i am unsure,['ruby-on-rails'] +155415,dotnetzip extractprogress bug the extractprogresseventargsentriestotal and extractprogresseventargsentriesextracted is always zero is this a known bug see my code belowpublic static void unzipstring zipfile string destination usingzipfile zip zipfilereadzipfile zipextractprogress new eventhandlerextractprogresseventargszip extractprogress foreach zipentry entry in zip entryextractdestination extractexistingfileactionoverwritesilently consolewritelinedone static void zip extractprogressobject sender extractprogresseventargs e ifeeventtype zipprogresseventtypeextracting afterextractentry consolewritelinestringformat0 1 2 3 ecurrententryfilename eentriestotal eentriesextracted doublentriestotal doublentriesextracted 10,"['c#', '.net']" +155416,cellbased liquid simulation local pressure model i am attempting to add semirealistic water into my tilebased 2d platformer the water must act somewhat lifelike with a pressure model that runs entirely local ie can only use data from cells near it this model is needed because of the nature of my game where you cannot be certain that the data you need is not inside an area that is not in memoryi have tried one method so far but i could not refine it enough to work with my constraintsfor that model each cell would be slightly compressible depending on the amount of water in the above cell when a cells water content was larger than the normal capacity the cell would try to expand upwards this created a fairly nice simulation abeit slow not lag changes in the water were taking a while to propagate at times when i tried to implement this into my engine i found that my limitations lacked the precision required for it to work i can provide a more indepth explanation or a link to the original concept if you wishmy constraintsonly 256 thiscrete values for water level no floating point variables edit floats are finefixed grid size2d onlyubend configurations must workthe language that i am using is c but i can probably take other languages and translate it to cthe question is can anyone give me a pressure model for water following my constraints as closely as possible,['c#'] +155422,using a custom font with bold text in a uilabel i have an app where i am setting the font for a uilabel programmatically as below label setfontuifont fontwithnamefontname sizefontsize intvaluewherein fontname is a string type variable that hold font name such as helveticaand fontsize will hold the size of the font this works fine for menow i want to make this text bold how can i do thatboldsystemfontofsize works for system font how can i achieve the same for user defined fonts thanks,"['iphone', 'objective-c', 'ios']" +155434,deploying vsix using msi installer can anyony help me in how to install vsix using msi installerfor msi installer i am using visual studio installer setup projectwhen i use vsix with extension manager it works finei want to have it as a installerusing msi instead of using enstension manageror any best wa yto install and unstall vsix files,['c#'] +155444,not showing android and avd manager in eclipse i have installed andorid sdki installed android plugin alsobut eclipse not showing android and avd manager and it is also not showing android in windowspreferences alsohelp me out,['android'] +155452,c using systemlinq error why might using systemlinq cause the following errorthe type or namespace name linq does not exist in the namespace system,['c#'] +155453,porting tomcat 6 to 7 problem with i tried to deploy my tomcat 6 webapp on a tomcat 7 server but encounter the following problem which occurs if i add elements to my webxmljavalangnosuchmethodexception orgapachecatalinadeploywebxml addfilter at orgapachetomcatutildigesterdigestercreatesaxexceptiondigesterjava2687 at orgapachetomcatutildigesterdigestercreatesaxexceptiondigesterjava2713 at orgapachetomcatutildigesterdigesterendelementdigesterjava1060 at comsunorgapachexercesinternalparsersabstractsaxparserendelementabstractsaxparserjava601 at comsunorgapachexercesinternalimplxmldocumentfragmentscannerimplscanendelementxmldocumentfragmentscannerimpljava1782 at comsunorgapachexercesinternalimplxmldocumentfragmentscannerimplfragmentcontentdrivernextxmldocumentfragmentscannerimpljava2938 at comsunorgapachexercesinternalimplxmldocumentscannerimplnextxmldocumentscannerimpljava648 at comsunorgapachexercesinternalimplxmldocumentfragmentscannerimplscandocumentxmldocumentfragmentscannerimpljava511 at comsunorgapachexercesinternalparsersxml11configurationparsexml11configurationjava808 at comsunorgapachexercesinternalparsersxml11configurationparsexml11configurationjava737 at comsunorgapachexercesinternalparsersxmlparserparsexmlparserjava119 at comsunorgapachexercesinternalparsersabstractsaxparserparseabstractsaxparserjava1205 at comsunorgapachexercesinternaljaxpsaxparserimpljaxpsaxparserparsesaxparserimpljava522 at orgapachetomcatutildigesterdigesterparsedigesterjava1543 at orgapachecatalinastartupcontextconfigparsewebxmlcontextconfigjava1694 at orgapachecatalinastartupcontextconfigwebconfigcontextconfigjava1209 at orgapachecatalinastartupcontextconfigconfigurestartcontextconfigjava882 at orgapachecatalinastartupcontextconfiglifecycleeventcontextconfigjava317 at orgapachecatalinautillifecyclesupportfirelifecycleeventlifecyclesupportjava119 at orgapachecatalinautillifecyclebasefirelifecycleeventlifecyclebasejava89 at orgapachecatalinacorestandardcontextstartinternalstandardcontextjava5081 at orgapachecatalinautillifecyclebasestartlifecyclebasejava145 at orgapachecatalinacorecontainerbasestartinternalcontainerbasejava1033 at orgapachecatalinacorestandardhoststartinternalstandardhostjava774 at orgapachecatalinautillifecyclebasestartlifecyclebasejava145 at orgapachecatalinacorecontainerbasestartinternalcontainerbasejava1033 at orgapachecatalinacorestandardenginestartinternalstandardenginejava291 at orgapachecatalinautillifecyclebasestartlifecyclebasejava145 at orgapachecatalinacorestandardservicestartinternalstandardservicejava443 at orgapachecatalinautillifecyclebasestartlifecyclebasejava145 at orgapachecatalinacorestandardserverstartinternalstandardserverjava727 at orgapachecatalinautillifecyclebasestartlifecyclebasejava145 at orgapachecatalinastartupcatalinastartcatalinajava620 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava39 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava25 at javalangreflectmethodinvokemethodjava597 at orgapachecatalinastartupbootstrapstartbootstrapjava303 at orgapachecatalinastartupbootstrapmainbootstrapjava431caused by javalangnosuchmethodexception orgapachecatalinadeploywebxml addfilter at orgapachetomcatutilintrospectionutilscallmethod1introspectionutilsjava802 at orgapachetomcatutildigestersetnextruleendsetnextrulejava201 at orgapachetomcatutildigesterdigesterendelementdigesterjava1057 36 moreis there a change in the filter notation in tomcat 7 i can just not get rid of the problem,['java'] +155470,how to select only a few columns in my nhibernate query i have a one class to one table mapping unfortunately this table has 110 columns and queries take a long time process especially when most of the time i only want to view 10 columns my problem is that the queries are dynamically generated based on what the user wants to look at i cannot really create different mappings with different columns because there would be a very large number of combinations i am using the criteria api to generate the queries can i also use this to only select the columns the user wants or some other methodthanks,['c#'] +155477,list as out parameter causes an error why in this codepublic bool somemethodout listtask tasks var task taskfactorystartnew procestartinfo tasksaddtaski get an error use of unassigned out parameter tasks whyin an msdn example there is just use of out parameterclass outexample static void methodout int i i 44 static void main int value methodout value value is now 44 is it because of listt,['c#'] +155491,stdout redirect changing output i have a program called abcwhen i run the following command abc infilei get the following outputijklmhowever when i run abc infile outfile cat outfilei am given this outputijkoonow i am assuming this is a bug with my program however regardless of what my program is doing i do not know how this is possibleeditnow that i know it is possible i am curious as to what it is in my program that is causing thisthere is a block inside a loop in my program that containsbyte ascii to byteasciibyteputcharbytebyte is of type charnow if i change putcharbyte to printfc byte all the output stays the samehowever if i change it to printfd byte then abc infile outputs1051061071which is the decimal representation of those ascii characters as they were in outfile but it is not the decimal representation of the characters as they actually appeared when they just got sent to stdout i do not understand why there could be this differenceedit 2if i change the printing line to printfcn byte then abc infile outputsijkoothis is consistent with what goes into outfile again not sure what the difference isedit 3i just tested this on a 32 bit machine and the program works outputfile contains ijklm wierdedit 4here is the main functionint main char asciibyte8 char byte int c using int to avoid the eof pitfall long charcount 0 whilec getchar eof ifc 0 c 1 continue asciibytecharcount 8 c ifcharcount 8 7 testing revealed that at this point asciibyte does contain what it should contain eight ascii ones and zeros representing a byte read in from stdin byte ascii to byteasciibyte print statements such as printfd byte printfcn byte reveal that the ascii to byte function works incorrectly on my 64 bit machine however these statements putcharbyte printfc byte make it appear as though the function operates as it should except if i redirect that output to a file putcharbyte charcount return 0and here is the ascii to byte functionchar ascii to bytechar asciibyte char byte int i fori 0 i 8 i ifasciibyte7i 1 byte byte 1 i return bytefinal editi noticed that i should have initialized byte to 0x00 problem solved why am i this retarded i will give answer points to whoever can explain specifically how this caused the problem,['c'] +155507,how can i have an opaque uiview as a subview of a semitransparent uiview i have a uiview with an alpha of 05 which i add as a subview to my primary view in order to grayout everything else i want to add an additional uiview to this gray uiview as a subview the problem is that when i do this my newlyadded subview is also partially transparentis there any way to make a subview ignore the alpha value of its superview and be itself fully opaque,"['iphone', 'ios']" +155511,javascript settimeout call error i want to invoke the windowsettimeot function with my custom scope so i use the call method but there is something wrongfunction foo thisbar function consolelogkeep going windowsettimeoutcallthisthisbar100 thisbarnew foounder firefox this prints to the console only 1 line and then nothing and under google chrome it throws a typeerrorwhat is the problem in my code,['javascript'] +155513,how to get info about thisk filesystem is possible to read info about the filesystem of a physical thisk eg if it is formatted as ntfs fat etc using net c 35if so which class should i use to determine this,"['c#', '.net']" +155515,mongoid query caching rails activerecord has a feature called query caching activerecordquerycache which saves the result of sql query for the lifespan of a request while i am not very familiar with the internals of the implementation i think that it saves the query results somewhere in the rack env which is thiscarded in the end of the requestthe mongoid unfortunately does not currently provide such feature and this is exacerbated by the fact that some queries occur implicitly referencesi am considering to implement this feature and i am curious where and how mongoid or perhaps mongo driver should be hooked in order to implement this,['ruby'] +155521,are we heading for jar hell in java platform similar to dll hell last night i was trying to put a simple tutorial to build an application using the stack spring 25 jpa 10 hibernate downloading for first time so did not know which version to use unfortunately i didnt want to use maven as the target participants were on ant build as usual hit the search engine and got somehow the steps in the appcontext persistencexml and in the java classes the moment i started getting required libraries i lost in the jar hell luckily not much of a problem on the spring side as all the dependent jars are packaged together for my spring 256when it came to hibernate i had no clue which all jars to be included on the first place on the next challenge did not know which version for each to addfinally i got the whole thing working but it looks so scary to enter this jar hell again unless i am taken through maven heavenwith lots of interceptors and weaving it is becoming more complicated for the conventional java programmer who once liked java primarily for lots of transparency on what my code is doingam i right in the thought process,['java'] +155524,how to automatically change the text size inside a div i have a background image with a div i want to write some text but this text should change the font size through the div,"['jquery', 'html', 'css']" +155556,can editorfor be used to create given this model is it possible to use the htmleditorfor to render a file upload input element to the page i played around with the datatype of the property filename and it was definitely impacting the editor form renderedpublic class dr405model datatypedatatypetext public string taxpayerid get set datatypedatatypetext public string returnyear get set public string filename get set strongly typed aspx page looks like this div classeditorfield htmleditorformodel modelfilename htmlvalidationmessageformodel modelfilename div,['c#'] +155557,improve performance of php on local server i have a xampp install with pretty much the default config performance is not much of a problem in general as i use php mostly to run web pages and small web apps waiting a couple seconds for a page is not unusualhowever i have recently taken up the problems from project euler and decided to do them in php try as i may i could not get my code to run in less than 1 minute 1 second optimized down from almost 3 min and i was getting pretty embarrassed especially considering most posters on pjt euler reported times of 13 seconds 7 find the 101th primei ported my code to c and the same task completed in a blink 04 seconds same algorithm the only notable difference in the code is that i used a list in c to replace the array i was using in phpwhile i did expect c to outperform php this difference leads me to suspect a gross configuration problem but i have no idea where to look what could be the cause of this poor performanceedit here is the codein php project euler 7 by listing the first six prime numbers 2 3 5 7 11 and 13 we can see that the 6th prime is 13 what is the 101st prime number ini setmax execution time 300 echo start time dateisu br function isprimenumber prevprimes foreach prevprimes as key prime if prime 1 continue elseif number prime 0 return 0 if we get to here number is prime return number primes arrayi 0nbprimes 0while nbprimes 101 i if i 2 0 result isprimei primes if result 0 primes i nbprimes echo nbprimes resultbrecho end time dateisu br in cpublic static void runsnippet stopwatch stopwatch new stopwatch stopwatchstart listint primes new listint int i 0 int nbprimes 0 int result 0 while nbprimes 101 i if i 2 0 result isprimei primes if result 0 primesaddi nbprimes stopwatchstop consolewritelinetime elapsed 0 stopwatchelapsed consolewriteline nbprimes resulttostringpublic static int isprimeint number listint prevprimes foreach int prime in prevprimes if prime 1 continue else if number prime 0 return 0 if we get to here number is prime return number,['php'] +155561,jquery stop submitting form perform script continue submitting form i have a form and when i submit him i execute multiple script here is my coderequestcreateformsubmitfunction e if requestcreateformvalidatecheckform false return epreventdefault many scripts how to continue submittingis it possible to continue submitting the form which is stopped with epreventdefault after many scriptsthank you,"['javascript', 'jquery']" +155564,optimized way to do rpc in net i am considering to move parts of a net application to other computers the obvious way to do this is simply using wcf with a binary tcp protocol for example as describer in easiest way to get fast rpc with net i will be making a vast amount of calls and latency is a big issue basically one computer will be running a physics simulator and the others will be interacting with it using a api of several hundred commandsi am thinking the best way is to make a custom binary protocol where api commands are identified by int16 and a sequence number and followed by the required parameters hardwiring the send and receive classes would remove any unnecessary overheadbut that is a lot of work since we are talking several hundred api commandsany thoughts on the best way to do implement iteditto clarify afaik serialization in net is not optimized there is a relatively high penalty in serializing and deserializing objects in for example the internal use of reflection this is kind of what i want to avoid and hence my though around directly mapping hardwiring methodsafter some searching i found one app i had a vague recollection of,['.net'] +155569,how do i get the coordinates for finger tapping in uiview how do i get the coordinates for finger tapping in uiviewi would prefer not to use a big array of buttonsthank you,['iphone'] +155581,in javascript is returning out of a switch statement considered a better practice than using break option 1 switch using returnfunction myfunctionopt switch opt case 1 return one case 2 return two case 3 return three default return option 2 switch using breakfunction myfunctionopt var retval switch opt case 1 retval one break case 2 retval two break case 3 retval three break return retvali know that both work but is one more of a best practice i tend to like option 1 switch using return best as it is cleaner and simplerhere is a jsfiddle of my specific example using the technique mentioned in ic3b3rgs commentsvar sfaic sfaiccommon masterpages cs cs cp cp contentpages cs cscontent cp cpcontent function getelementprefixpage return page in sfaiccommonmasterpages sfaiccommonmasterpagespage page in sfaiccommoncontentpages sfaiccommoncontentpagespage undefinedto call the function i would do so in the following waysgetelementprefixsfaiccommonmasterpagescsgetelementprefixsfaiccommonmasterpagescpgetelementprefixsfaiccommoncontentpagescsgetelementprefixsfaiccommoncontentpagescpproblem here is that it always returns undefined i am guessing that it is because it is passing in the actual value of the object literal and not the property what would i do to fix this using the technique described in ic3b3rgs comments,['javascript'] +155589,ie prompts to open or save json result from server internet explorer in compatibility mode gets the data from the server in an ajax callback method and popsup a dialog if i want to save the data or open how to get rid of that client says ajax typepost data uidlgholder formserialize url uidlgholder formattraction success function data textstatus jqxhr alertdatamessage server answersreturn new jsonresult data new result false message yay,['jquery'] +155610,mysql 51 using filesort event when an index is present probably i am missing some silly thing apparently mysql 51 keeps doing a filesort even when there is an index that matches exactly the column in the order by clause to post it here i have oversimplified the data model but the issue is still happeningtable definitioncreate table event id int11 not null auto increment name varchar255 default null owner id int11 default null date created datetime default null primary key id key owner id owner id key date created date created constraint event ibfk 1 foreign key owner id references user profile id engineinnodb auto increment7 default charsetutf8my problem is that event a simple select is showing using filesortexplain select from event order by date created descand the result for the query explainid select type table type possible keys key key len ref rows extra 1 simple event all null null null null 6 using filesortis there any way for this type of queries to use the index insteas of doing a filesortthanks in advance to everybody,['mysql'] +155613,python shelve module memory consumption i have been assigned the task of reading a txt file which is a log of various events and writing some of those events into a dictionarythe problem is that the file can sometimes get bigger than 3gb in size this means that the dictionary gets too big to fit into main memory it seems that shelve is a good way to solve this problem however since i will be constantly modifying the dictionary i must have the writeback option enabled this is where i am concerned the tutorial says that this would slow down the readwrite process and use more memory but i am unable to find statistics on how the speed and memory are affectedcan anyone clarify by how much the readwrite speed and memory are affected so that i can decide whether to use the writeback option or sacrifice some readability for code efficiencythank you,['python'] +155623,creating a mysql index on a varchar always makes 2 indexes i have an email column in my table which is a varchar255 most emails would only be 4050 characters long and the rest of the characters are there just there for a rare case therefore i want to only index the first 50 characters of the email columni have tried to do it with this queryalter table users add index email50 however that creates 2 indexes one named email and the other email 2 the first index has no length limits the second one has got the 50 character limitwhy is this is there any workaround or do i have no option but to index the full column,['mysql'] +155658,whats the equivalent of rubys pnormalthist statistics function in haskell as seen here heres the ruby code itself implemented in the statistics2 library inverse of normal thistribution 2 pr infty x qn xdef pnormalthistqn b 1570796288 003706987906 08364353589e3 02250947176e3 06841218299e5 05824238515e5 0104527497e5 08360937017e7 03231081277e8 03657763036e10 06936233982e12 ifqn 00 10 qn stderrprintferror qn 0 or qn 1 in pnormn return 00 end qn 05 and return 00 w1 qn qn 05 and w1 10 w1 w3 mathlog40 w1 10 w1 w1 b0 1upto 10 do i w1 bi w3i end qn 05 and return mathsqrtw1 w3 mathsqrtw1 w3end,['ruby'] +155660,stream live video from phone to phone using socket fd i am new to android programming and have found myself stuck i have been researching various ways to stream live video from phone to phone and seem to have it mostly functional except of course the most important part playing the stream it appears to be sending the stream from one phone but the second phone is not able to play the streamhere is the code for the playing sidepublic class videoplayback extends activity implements callback mediaplayer mpprivate surfaceview mpreviewprivate surfaceholder holderprivate textview mtextviewpublic static final int serverport 6775public static string serverip1921681126socket clientsocketprivate handler handler new handler called when the activity is first created overridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain mpreview surfaceview findviewbyidridsurfaceview1 mtextview textview findviewbyidridtextview1 holder mpreviewgetholder holderaddcallbackthis holdersettypesurfaceholdersurface type push buffers mtextviewsettextattempting to connect mp new mediaplayer thread t new thread public void run try clientsocket new socketserveripserverport handlerpostnew runnable override public void run mtextviewsettextconnected to server handlerpostnew runnable override public void run try parcelfiledescriptor pfd parcelfiledescriptorfromsocketclientsocket pfdgetfiledescriptorsync mpsetdatasourcepfdgetfiledescriptor pfdclose mpsetthisplayholder mpprepareasync mpstart catch ioexception e todo autogenerated catch block eprintstacktrace catch unknownhostexception e todo autogenerated catch block eprintstacktrace catch ioexception e todo autogenerated catch block eprintstacktrace tstartand here is the code for the streaming sidepublic class videostreaming extends activity user interface elementsvideoview mviewtextview connectionstatussurfaceholder mholder video variablemediarecorder recorder networking variablespublic static string serverippublic static final int serverport 6775private handler handler new handlerprivate serversocket serversocket called when the activity is first created overrideprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain define ui elements mview videoview findviewbyidridvideo preview connectionstatus textview findviewbyidridconnection status textview mholder mviewgetholder mholdersettypesurfaceholdersurface type push buffers serverip 1921681126 run new thread to handle socket communications thread sendvideo new threadnew sendvideothread sendvideostart public class sendvideothread implements runnable public void run from serverjava try ifserveripnull handlerpostnew runnable override public void run connectionstatussettextlistening on ip serverip serversocket new serversocketserverport whiletrue listen for incoming clients socket client serversocketaccept handlerpostnew runnable override public void run connectionstatussettextconnected try begin video communication final parcelfiledescriptor pfd parcelfiledescriptorfromsocketclient handlerpostnew runnable override public void run recorder new mediarecorder recordersetvideosourcemediarecordervideosourcecamera recordersetoutputformatmediarecorderoutputformatthree gpp recordersetoutputfilepfdgetfiledescriptor recordersetvideoframerate20 recordersetvideosize176144 recordersetvideoencodermediarecordervideoencoderh263 recordersetpreviewthisplaymholdergetsurface try recorderprepare catch illegalstateexception e todo autogenerated catch block eprintstacktrace catch ioexception e todo autogenerated catch block eprintstacktrace recorderstart catch exception e handlerpostnew runnable override public void run connectionstatussettextoopsconnection interrupted please reconnect your phones eprintstacktrace else handlerpostnew runnable override public void run connectionstatussettextcould not detect internet connection catch exception e handlerpostnew runnable override public void run connectionstatussettexterror eprintstacktrace end from serverjava i receive the following error when trying to create the mediaplayer0524 162539360 errormediaplayerservice88 offset error0524 162539360 errormediaplayer11895 unable to to create media player0524 162539360 warnsystemerr11895 javaioioexception setdatasourcefd failed status0x80524 162539360 warnsystemerr11895 at androidmediamediaplayersetdatasourcenative method0524 162539360 warnsystemerr11895 at androidmediamediaplayersetdatasourcemediaplayerjava8110524 162539360 warnsystemerr11895 at comcontivideoplaybackvideoplayback12runvideoplaybackjava630524 162539360 warnsystemerr11895 at androidoshandlerhandlecallbackhandlerjava5870524 162539360 warnsystemerr11895 at androidoshandlerthispatchmessagehandlerjava920524 162539360 warnsystemerr11895 at androidoslooperlooplooperjava1320524 162539360 warnsystemerr11895 at androidappactivitythreadmainactivitythreadjava40250524 162539360 warnsystemerr11895 at javalangreflectmethodinvokenativenative method0524 162539360 warnsystemerr11895 at javalangreflectmethodinvokemethodjava4910524 162539360 warnsystemerr11895 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava8410524 162539360 warnsystemerr11895 at comandroidinternaloszygoteinitmainzygoteinitjava5990524 162539360 warnsystemerr11895 at dalviksystemnativestartmainnative methoddoes anyone have a fix for this thanks in advance,['android'] +155663,difference between androidorientationvertical vs androidorientationhorizontal i was wondering what the difference are between these two benefits of one over the other etc,['android'] +155664,thisable future dates in android date picker hello allhow to thisable future dates in datepickerdialog in androidi am using following implementationthanksashwani,['android'] +155665,what do moduleexports and exportsmethods mean in nodejs express looking at a random source file of the express framework for nodejs there are two lines of the code that i do not understand these lines of code are typical of almost all nodejs files expose router constructor exports moduleexports routerand expose http methods var methods exportsmethods requiremethodsi understand that the first piece of code allows the rest of the functions in the file to be exposed to the nodejs app but i do not understand exactly how it works or what the code in the line means what do exports and moduleexports actually meani believe the 2nd piece of code allows the functions in the file to access methods but again how exactly does it do thisbasically what are these magic words module and exports,['javascript'] +155671,how to use coffeescript in developing websites how do you use coffeescript it need to be compiled so you write code in coffescript compile it and insert real javascript on your sitedoes not it take a lot of time or is there some another wayps i have seen another way to insert in development stage coffeescript in textcoffeescript scripttags with coffeescriptjs library about 150k and compile only for production version and insert real javascript,['javascript'] +155674,mfc stdstring vs cstring using c with mfc coming from a c background i typically just use string for all well strings i use them for class members method parameters and method return values now in c i have got stdstring cstring char lpctstr and more as i design my data members method parameters and method return values which types should i be using ease of use is important and cstring seems to offer that but my instinct is toward portable standards although portability is pretty low on my list of priorities now also i do not like the c semantics of creating string buffers and passing them into methods and functionsi think from an immediate ease of coding perspective cstrings probably have the edge but overall what is the high code quality way to do thisediti am especially concerned about the interface points in my code ie method parameters and return values egshapesetcaptionconst char caption shapesetcaptioncstring caption shapesetcaptionstdstring caption shapesetcaptionstdwstring caption,['c++'] +155689,tornado asynchttpclient fetch callback extra parameters i am sort of new to this whole async game mostly been a django guy but i was wondering how can i pass extra parameters to tornados asynchttpclientfetch callback for example i am tracking the number of times a callback has been called in order to wait until a certain number have executed before working on the data and i would like to do something likedef getpageself itemsiteration http asynchttpclient httpfetchfeed callbackselfrespitemsiterationdef respself response items iteration do stuff selffinish,['python'] +155712,codeigniter no input file specified hi i am a beginner in codeigniter and i saw a ci tutorial and was just trying to do a simple thing i downloaded the ci and added this file to controller directory but it would not workphpclass site extends ci controller public function index echo hello world function dosomething echo do something when i try to access it using httpindexphpsite i get the output no input file specified by the way i named the file sitephp,['php'] +155717,how to send a value from arduino to python and then use that value i am in the process of building a robot that is remote controlled using python to send control messages via the internet through a simple guii have gotten part of my code working pretty well the gui and control systems but i am stuck i am trying to use a parallax ping sensor to get thistance to objects information from an arduino mega and send that value to my python control script to be thisplayed on the remote guithe main problem that i am having is how to integrate python code that will use the already established com port with the arduino and send a message to tell the arduino to poll the ping sensor and then send to a python program which will receive the value and then let me insert that value into my guii already have this code to control the arduino and it works with my simple guiimport serialser serialserialdevttyusb0 9600from pythoncard import modelclass mainwindowmodelbackground def on spdbtn mouseclickself event spd selfcomponentsspdspinvalue def on fbtn mouseclickself event spd selfcomponentsspdspinvalue serwrite serwritef serwritechrspd def on bbtn mouseclickself event spd selfcomponentsspdspinvalue serwrite serwriteb serwritechrspd def on lbtn mouseclickself event spd selfcomponentsspdspinvalue serwrite serwritel serwritechrspd def on rbtn mouseclickself event spd selfcomponentsspdspinvalue serwrite serwriter serwritechrspd def on sbtn mouseclickself event spd selfcomponentsspdspinvalue serwrite serwrites serwrite0 def on pngthisbtn mouseclickself event serwrite serwritep1 serwritep2app modelapplicationmainwindowappmainloopwhat i would really like to do is improve the above code and add a button to click to tell python to send a message to the arduino to check the ping sensor and return the valuei am very literate with the arduino code but i just started playing with python in the last two weeks,['python'] +155774,why constructor is not called for given casting operator struct a struct b b a pa b operator a pa return this templatetypename tstruct wrap t x operator t return x int main wrapa a b ob a error conversion from awrapaa to nonscalar type aba requested ob a okwhen ob is constructed then why bba is not invoked for wraptoperator t note boperator a is invoked for wraptoperator t in the next statement,['c++'] +155785,how to show the full message when click on label message in aspnet at present i am thisplaying the full message at a time in label in grid like thisasptemplatefield headertextmessage itemstylecssclassgridlabeltextleftalign itemtemplate div stylewordwrap breakword width 240px textalign left asplabel idlblmessage runatserver fontsize12px textdatabinderevalcontainerdataitem message asplabel div itemtemplate asptemplatefieldi want thisplay message in single line when click on it then thisplay the whole message pls tell me,['asp.net'] +155790,ehcache vs static map cache implementation i have few tables with very few entries in them and they will never change dynamically so i want to cache the whole table in memory to reduce load on db i can easily achieve that by a static map and populating the map in a static block i was wondering whether the same is possible in a more effective way by ehcache hibernate,['java'] +155792,how to add an xml namespace xmlns when serializing an object to xml i am serializing objects to xml with the help of xstreamhow do i tell xstream to insert an xmlns to the xml output of my object as an example i have this simple object i want to serializexstreamaliasvaluedomainpublic class domain xstreamasattribute private string type private string os how do i achieve exactly the following output with xstreamdomain typekvm xmlnsqemu oslinuxosdomain,['java'] +155799,guice inject in servlet i am fresh new in google guice framework and i have a question regarding injecting in guice servlet and using requestscope ok let me give some example from my code just to make the things clearlyi have a bean class for example bean requestscopepublic class bean private string user private string pass constructor which is inject getters and settershere i have got a servlet singletonpublic class mainservlet extends httpservlet dogethttpservletrequest request httpservletresponse response some code injector injector guicecreateinjector validuser validuser injectorgetinstancevaliduserclass here i got the below exception comgoogleinjectconfigurationexception guice configuration errors1 no scope is bound to comgoogleinjectservletrequestscoped at beanclass while locating beanit is interesting here that servlet scope is singleton as we know and also how can i get from the http request bean instance because as far as i understand after a instance of a bean class is injected it goes in the http request right any help or example is welcomethanksbr,['java'] +155801,activity restarts on force close i have an application with a single root activity i have recently had it brought to my attention that any kind of force close on my activity results in it restarting and i have no idea why this might happen if i force an uncaught exception or use the long back press to force close option they both result in the samemy only guess would have been some form of quirk relating to retained references to some part of the activity only i do not have any outside of some weakreference entries at the application levelrelevant logcat entries0525 082549137 infoactivitymanager18449 thisplayed ukcorandomiconrstbtreebuilderactivity 8s82ms0525 0825542 debugdalvikvm18546 gc explicit freed 12k 57 free 3640k8327k external 8323k10136k paused 72ms0525 0825373 warninputmanagerservice18449 got remoteexception sending setactivefalse notification to pid 19122 uid 100690525 082559217 debugdalvikvm18646 gc explicit freed 128k 48 free 2980k5703k external 0k0k paused 67ms0525 082600238 debugdalvikvm18991 gc concurrent freed 343k 51 free 2794k5639k external 303k532k paused 3ms3ms0525 082602950 infoprocess18449 sending signal pid 19554 sig 90525 082602980 infoactivitymanager18449 process ukcorandomiconrstb pid 19554 has died0525 082602990 errorinputthispatcher18449 channel 40a16ec8 ukcorandomiconrstbukcorandomiconrstbtreebuilderactivity server consumer closed input channel or an error occurred events0x80525 082602990 errorinputthispatcher18449 channel 40a16ec8 ukcorandomiconrstbukcorandomiconrstbtreebuilderactivity server channel is unrecoverably broken and will be thisposed0525 082602990 infowindowmanager18449 window died window40a16ec8 ukcorandomiconrstbukcorandomiconrstbtreebuilderactivity pausedfalse0525 082603010 warnwindowmanager18449 failed looking up window0525 082603010 warnwindowmanager18449 javalangillegalargumentexception requested window androidosbinderproxy40c774e0 does not exist0525 082603010 warnwindowmanager18449 at comandroidserverwindowmanagerservicewindowforclientlockedwindowmanagerservicejava81770525 082603010 warnwindowmanager18449 at comandroidserverwindowmanagerservicewindowforclientlockedwindowmanagerservicejava81680525 082603010 warnwindowmanager18449 at comandroidserverwindowmanagerservicewindowstatedeathrecipientbinderdiedwindowmanagerservicejava70260525 082603010 warnwindowmanager18449 at androidosbinderproxysenddeathnoticebinderjava3850525 082603010 warnwindowmanager18449 at dalviksystemnativestartrunnative method0525 082603010 infowindowmanager18449 win death null0525 082603020 infoactivitymanager18449 start proc ukcorandomiconrstb for activity ukcorandomiconrstbtreebuilderactivity pid19565 uid10069 gids1015any ideas where to even begin poking would be gratefully receivededit this was caused by me setting androidstatenotneededtrue in my manifest while i do not need the state this caused android to decide it was best to relaunch my app on the assumption the user would want that,['android'] +155808,net find dead code across multiple solutions we have a product with 15 solutions with each a number of projectsthe question is quite simple which tool will enable us to search the entire codebase for dead code searching within a single solution is easy enough lots of answers on so for that onebut what about determining if public void foo in project alphaproj of solution alphasol which is not used within alphasol itself is actually used in eg betasol,['.net'] +155809,how to write mysql query where a contains a or b i must use this format where a operand b a is the field i want b to be either text 1 or text 2 so if a has data like text 1 texttext or texttext 2 the query will have result but how do i write this does mysql support something likewhere a contains text 1 or text 2,['mysql'] +155840,is adding strings with placeholders 0 into resources a good idea i have added a string into a resources file my application will be localizedbut is adding strings with placeholders 0 into resources a good ideawhat if some nontechnical person does localization is there a way for him to screw it up unknowinglyif this is not a good idea what should i dohere is simple example i will be using wpf resource dictionaries example resource1resx name value relationship status msg 0 is in relationship with 1 class program static void mainstring args string msg stringformatresource1relationship status msg romeo juliot consolewritelinemsg,['c#'] +155842,will objectivec runtime release retained associative references for user when some codes like thisobjc setassociatedobject obj key val objc association retaindo i need to call relatedobjc setassociatedobject obj key nil objc association retainto release the retained value does objectivec runtime auto release the associative references in dealloc or somewhere,['objective-c'] +155895,javascript resizing of firefox popup window i am just learning javascript and jquery but i am an htmlr trying to take the next stepi am attempting to drop content into a table which can be any size at all it is for a news site i check for size and then resize the popup accordingly while the window is not exactly right it works but in firefox it is not even resizing using a generic link to popopen a basic windowa onclickwindowopenpopupwidth1height1popupa i am pointing it to a default page where the cms is placing all content into a table idtop it has a default width1 to force a constraint and then letting the content expand the table to set the real size i then check the table size to see and resize the window on documentreadyscript typetextjavascript documentreadyfunction var divh documentgetelementbyidtopoffsetheight var divw documentgetelementbyidtopoffsetwidth test size alerttable width divw px height divh px resize windowresizetodivwdivh scripti need to be able to resize a window already opened in firefox all the window sizes except firefox are off but i can pad them a little larger is better than cutoff firefox unfortunately generates a tiny 180w x 249h window and never resizes i have searched here unsuccessfully most suggest editing a setting in firefox which i clearly cannot expect users to do any ideas,"['javascript', 'jquery']" +155898,android paintsettypeface is not working for italic the paintsettypeface is not working for italic or i am doing something the wrong way i can create normal bold monospace and serif text but i cannot create italic text it always looks normal or in the case of bolditalic it looks bold this will appear monospace paintsettypefacetypefacemonospace canvasdrawtextfoo 10 10 paint this will appear serif paintsettypefacetypefaceserif canvasdrawtextfoo 10 10 paint this will appear bold paintsettypefacetypefacedefaultfromstyletypefacebold canvasdrawtextfoo 10 10 paint this will not appear italic problem paintsettypefacetypefacedefaultfromstyletypefaceitalic canvasdrawtextfoo 10 10 paint this is not working either problem paintsettypefacetypefacecreatetypefacesans serif typefaceitalicso now the question is there a known workaround for this my simple goal is to draw some words with italic style,['android'] +155914,cons of using internet explorers compatibility mode what are cons of force a web site viewed in ie to compatible mode say we force ie9 to ie8 compatiblity modeperformance drawbackscannot use any new ie9 specific features like html5css3svg whywe run legacy web app which is developed since 20 so it is a mess ball fighting to be compatible with chrome opera firefox ie678 and now we decide to add ie9 to the list but with ie9 we run in issues with printing permission deniend javascript errors probably something about crossframe javascript calls and next issues the easy workaround is to force ie9 to behave as a ie8 and then everything works fine but i am still not sure if it is way to go,['javascript'] +155918,use special symbol in layout design in android i need two navigation buttons with their texts are and however the compiler does not allow me use those symbols even if i use and is there anyway to put these symbol into the xml design filethanks,['android'] +155923,javascript navigatorcookieenabled browser compatibility how well supported is navigatorcookieenabled can i safely rely on it for all browsers,['javascript'] +155931,using a private auto property instead of a simple variable for a programming standard in a thiscussion with a peer it was brought up that we should consider using auto properties for all class level variables including private onesso in addition to a public property like sopublic int myproperty1 get set our private classlevel variables would look like thisprivate int myproperty2 get set instead ofprivate int myproperty2i am on the fence about why someone would want to do this but i cannot decide if my reluctance to accept this is because of my own internal brainwashing with how i write my code to the same programming standards and naming conventions i have used for 10 years or because i have never seen this before for a reasoni realize it is extra code to type but to be honest when using autoproperties i do not think i have ever typed it out due to the prop and propg snippets so it would be very simple to set up a new snippet to create a private auto property so the extra code does not bother me too much since i never have to type itother than aesthetics which may just be my subconscious are there any issues that could result from using fully private auto properties are there any good reasons to do this or not to do it i have seen a lot of code in my day on stackoverflow codeplex codeproject etc and i have never seen anyone use this standard is there a reason why,['c#'] +155932,ruby are comments tokens i have just read here that comments are tokens i have never thought of comments as tokens as they are either annotations or for a postprocessorare comments really tokens or is this source wrong,['ruby'] +155939,load additional css file through browser add on is there a way eg a firefox add on that lets you load a css file on your hard drive to a site your viewing im looking for something similar to firebug but where i can make more complicated changes and refresh the page to see them in actionthanks,['css'] +155986,querying embedded documents on a document with mongomapper what is a good pattern for querying embedded documents on a document for instance my user document has an embedded alerts document if i want to see if a given user has an alert with name i can do it two ways as far as i can tell in memory a laalert current useralertsselecta aname paramsnamefirstor via the actual document interface a la note that i am not 100 sure this is semantically valid but you get the pointuserwherealertsname paramsname id current useridfirstthere must be a better way something likecurrent useralertswherename paramsnameperhaps or maybe i am just not thinking about the problem right,['ruby'] +155994,why is eventmachine so much slower than node in my specific case at least not trying to make general statements herei have got this web crawler that i wrote in nodejs i would love to use ruby instead so i rewrote it in eventmachine since the original was in coffeescript it was actually surprisingly easy and the code is very much the same except that in eventmachine i can actually trap and recover from exceptions since i am using fibersthe problem is that tests that run in under 20 seconds on the nodejs code take up to and over 5 minutes on eventmachine when i watch the connection count it almost looks like they are not even running in parallel they queue up into the hundreds then very slowly work their way down though logging shows that the code points are hit in paralleli realize that without code you cannot really know what exactly is going on but i was just wondering if there is some kind of underlying difference and i should give up or if they really should be able to run about as fast a small slowdown is fine and i should keep trying to figure out what the issue isi did the following but it did not really seem to have any effectputs running with ulimit emset descriptor table size60to semset effective usernobodyemkqueueoh and i am very sure that i do not have any blocking calls in eventmachine i have combed through every line about 10 times looking for anything that could be blocking all my network calls are emhttprequest,"['javascript', 'ruby']" +155996,enabling error thisplay in php via htaccess only i am testing a website onlineright now the errors are not being thisplayed but i know they existi have access to only the htaccess filehow do i make all errors to thisplay using my htaccess fileediti added these lines to my htaccess php flag thisplay startup errors onphp flag thisplay errors onphp flag html errors onand the pages now thisplay internal server error,['php'] +156005,where should flash files be stored in 31 in rails 30x i would store my flash files in publicflash flash files such as jwplayer uploadify etcwith the introduction of the new directory structure in 31 ie appassets should flash files still be stored in publicflash or should i create a new directory called flash in appassets,['ruby-on-rails'] +156009,packaging a readonly data file with a ruby gem i am working on a ruby application that is deployed as a gem i would like to include a readonly data file with the gem and am not sure howwhere that should be packagedfor a little background this application deals with the midi spec which includes hundreds of constant values for instance controller channel volume is always identified by the value 7 sustain is identified by 64 etc etc in the past people have included these values as a large set of constants in their code that is fine but it seems more appropriate to me to include those in a language agnostic format such as yamlusing the gem path to locate the yaml file is ugly and also wouldnt work when using the library in a nongem deploymentthank you for your help,['ruby'] +156010,how does aspnet determine whether to queue a request or not when aspnet receives a request how does it determine whether to serve it or to queue it i ask because i am monitoring performance counters on a server and the cpu is not maxed out and there are a boatload of available worker threads but i am still seeing up to 200 requests get queued up,['asp.net'] +156018,is a union more efficient than a shift on modern compilers consider the simple codeuint64 resultuint32 high lowresult uint64high 32 uint64lowdo modern compilers turn that into a real barrel shift on high or optimize it to a simple copy to the right locationif not then using a union would seem to be more efficient than the shift that most people appear to use however having the compiler optimize this is the ideal solutioni am wondering how i should advise people when they do require that extra little bit of performance,['c'] +156038,how to iterate over all image files in a directory my app uses itunes file sharing the user can add files to the documents directoryi must read these files but make sure they are only images and not text files or other garbagehow can i iterate over the files in a directory and recognize only those which are imagesi assume that i would have to do it somehow like thisnsmutablearray retval nsmutablearray arraynsarray files filemanager contentsofdirectoryatpathdocumentsdirpath errorerrorif files nil errorfor nsstring file in files if filepathextension comparepng optionsnscaseinsensitivesearch nsorderedsame nsstring fullpath documentsdirpath stringbyappendingpathcomponentfile retval addobjectfullpath but this is bad for some reasons i would need a huge ifclause to catch all possible image file types and there are dozens of them is there a more intelligent way to really collect all image files no matter if png bmp jpg jpeg jpeg20 tiff raw etci slightly remember that there were some kind of file attributes that told the general type of file there was some abstract image key i believe but maybe there is an even better method,"['iphone', 'objective-c', 'ios']" +156044,android merge two images i have these two images which i basically merge on canvas now i want to save that canvas into an image how should i do it or if there is any other way to merge two imagesmy sample code is bitmap bmp1 bitmapfactorydecoderesourcegetresources rdrawableduckpic bitmap bmp2 bitmapfactorydecoderesourcegetresources rdrawableimg canvasdrawcolorcolorblack canvasdrawbitmap scratch 10 10 null bitmap bmoverlay bitmapcreatebitmapbmp2getwidth bmp2 getheight bmp2getconfig canvas cs new canvasbmp2 canvasscalefloat 05 float 05 canvasdrawbitmapbmp2 new matrix null canvasdrawbitmapbmp1 new matrix null canvassavei got it working by doing this cs bitmapcreatebitmapcgetwidth cgetheight bitmapconfigargb 8 canvas comboimage new canvascs comboimagedrawbitmaps new matrix null comboimagedrawbitmapc new matrix null comboimagesave this is an extra bit i added just incase you want to save the new image somewhere and then return the location string tmpimg stringvalueofsystemcurrenttimemillis png outputstream os null try os new fileoutputstreamsdcard tmpimg cscompresscompressformatpng 100 os catch ioexception e logecombineimages problem combining images e basically it is given here 2 images in android using canvas,['android'] +156050,module name is invalid when exporting an existing eclipse project to a war file i am trying to export an existing eclipse project to a war file but whatever i typed in the war export dialog page the system always returned module name is invalid i do not know how to fix this issue thanks for the help,['java'] +156089,filter core data results by property in array i currently have core data successfully returning all of the results for a specific entity titled eventnsmanagedobjectcontext context delegate managedobjectcontextnsentitydescription entitydescription nsentitydescription entityfornameevent inmanagedobjectcontextcontextnsfetchrequest request nsfetchrequest alloc initrequest setentityentitydescriptionnserror errornsarray fetchresults context executefetchrequestrequest errorerrorone property of the event entity is a string titled tid i also have an array filterarray that contains all allowed tid valueshow can i get my core data request to only return events that have a tid property that matches one of the values in filterarray i believe the answer relates to nspredicate but i am not familiar enough with it yet to get it to bend to my will,"['objective-c', 'ios']" +156093,let user type only three different characters in an input text field is there a way to let the user type only three characters for example i want to only allow 3 6 or 9 in an input text field,"['javascript', 'html']" +156120,c optional parameters or method overload since c added optional parameters is it considered a better practice to use optional parameters or method overloads or is there a particular case where you would want to use one over the other ie a function w lots of parameters would be better suited w optional parameters,['c#'] +156161,in eclipse how to copy an exisiting project to another project in eclipse i have one existing project a right now i have just created another project b which is empty is that possible to copy all the files of project a including its source code and related libraries to project b there are a lot of involved libraries in project a how to do this copying process correctly to ensure the copied file can still be compiled,['java'] +156177,recursive beanutilsdescribe is there a version of beanutilsdescribecustomer that recursively calls the describe method on the complex attributes of customerclass customer string idaddress addresshere i would like the describe method to retrieve the contents of the address attribute as wellcurrently all i have can see the name of the class as followsid123 addresscomtestentitiesaddress2a340e,['java'] +156181,html5 file api readasbinarystring reads files as much larger different than files on thisk full code at i am using html file api and dragdrop to upload files via xhr post to a php script procedurally everything seems to be working ok however when i try to open the uploaded files any nontext file is much larger than the source file and would not open it is clearly not the same data as was on the source thisk however text files are exactly the same and open just finesome examples on a 3file dragdrop uploadfile 1 textxml on thisk 13 kb uploaded 13 kb works perfectlyfile 2 imagepng on thisk 14 kb uploaded 18 kb would not openfile 3 applicationxlsx on thisk 12 kb uploaded 14 kb would not openit all boils down to this after xhr headers are setup file object is ready etc var reader new filereader readeronload functionevt xhrsendevttargetresult readerreadasbinarystringfreturning large bad data is there anything clearly wrong with it,['javascript'] +156182,are regular expressions universal i would like to know if regular expressions are universal for all languages like php javascript etc,"['php', 'javascript']" +156193,how to thisplay ajax loading image i want to show ajax loading image but do not know how to do that here is my working ajax script please help me to integrate ajax loading gifthanks function slider slider stop functionevent ui ajax url ajaxphp cache false async false data success functionhtml result listhtmlhtml,['jquery'] +156195,descrip top command in android i am making a small android application to show current total cpu usage like tab performance in windows task manageri use top m 1 n 1 d 1 to get cpu usage but i do not really understand the result of topthe result likeuser 5 system 15 iow 0 irq 0user 5 nice 0 sys 14 idle 73 iow 0 irq 0 sirq 0 92pid cpu s thr vss rss uid name213 11 r 1 900k 340k app 16 topcpu usage how can i calculated total cpu usage,['android'] +156200,difference between java and libjvmso linux or jvmdll windows what are the differences in starting an application through the plain java command against directly invoking the jvm through libjvmso in linux or jvmdll in windows recently i saw on a forum that starting eclipse using the dll or so file will give better performance i would like to get to know how this happensthanks,['java'] +156206,synonym finder algorithm i think example will be much better than long description let us assume we have an array of arraysserver1 server 1 main server 19216803server 1 vip server main serverserver 2 1921680419216803 19216805server 2 backupeach line contains strings which are synonyms and as a result of processing of this array i want to get thisserver1 server 1 main server 19216803 vip server 19216805server 2 19216804 backupso i think i need a kind of recursive algorithm programming language actually does not matter a i need only a little help with idea in general i am going to use php or pythonthank you,"['php', 'python']" +156234,rtsp live stream on android i try to make a live stream on android i tried lots of ways but none of themworked how can i do itthis is example of rtspmmediaplayer new mediaplayermmediaplayersetdatasourcekralstreamgettvstreamurltostringmmediaplayersetthisplayholdermmediaplayerprepareasyncmmediaplayersetonbufferingupdatelistenerthismmediaplayersetoncompletionlistenerthismmediaplayersetonpreparedlistenerthismmediaplayersetonvideosizechangedlistenerthismmediaplayersetaudiostreamtypeaudiomanagerstream musicmmediaplayersetloopingtrueexeption 0526 102246186 errormediaplayerservice10157 create pvplayer 0526 102306382 errorplayerdriver10157 command player init completed with an error or info 1 0526 102306382 errormediaplayer23800 error 1 1 0526 102306382 errormediaplayer23800 error 11 rtspvideoview videoview videoviewfindviewbyidridvideoview1uri uri uriparsertspstrm3trmedianovatvrkraltvrkraltvvideoviewsetvideouriurivideoviewstartit gives this messagesorry this video cannot ve played exeptions0526 104008979 errormediaplayerservice10157 create pvplayer 0526 104009188 infoactivitymanager10163 thisplayed activity comgiantrabbitnagarekraltvnow 433 ms total 433 ms 0526 104011702 warnpowermanagerservice10163 timer 0x30x30x1 0526 104029061 warnmediaplayer24284 infowarning 1 26 0526 104029061 infomediaplayer24284 info 126 0526 104029100 errorplayerdriver10157 command player init completed with an error or info 1 0526 104029104 errormediaplayer24284 error 1 1 0526 104029108 errormediaplayer24284 error 11 rtspmpreview surfaceview findviewbyidridsurfaceholder mpreviewgetholderholderaddcallbackthisholdersettypesurfaceholdersurface type push buffersextras getintentgetextraspublic void play try uri video kralstreamgettvstreamurl toastmaketextthis videotostring toastlength shortshow mmediaplayer new mediaplayer mmediaplayersetdatasourcepath mmediaplayersetthisplayholder mmediaplayerprepare mmediaplayersetonbufferingupdatelistenerthis mmediaplayersetoncompletionlistenerthis mmediaplayersetonpreparedlistenerthis mmediaplayersetonvideosizechangedlistenerthis mmediaplayersetaudiostreamtypeaudiomanagerstream music catch exception e logetag error egetmessage e exeption0526 103657589 errormediaplayerservice10157 create pvplayer 0526 103720542 errorplayerdriver10157 command player init completed with an error or info 1 0526 103720542 errormediaplayer24240 error 1 1 0526 103720565 warnplayerdriver10157 pvmfinfoerrorhandlingcomplete 0526 103720682 errormediaplayerdemo24240 error prepare failed status0x1 0526 103720682 errormediaplayerdemo24240 javaioioexception prepare failed status0x1 0526 103720682 errormediaplayerdemo24240 at androidmediamediaplayerpreparenative method 0526 103720682 errormediaplayerdemo24240 at comgiantrabbitnagarekraltvnowplaykraltvnowjava162 0526 103720682 errormediaplayerdemo24240 at comgiantrabbitnagarekraltvnowsurfacecreatedkraltvnowjava215 0526 103720682 errormediaplayerdemo24240 at androidviewsurfaceviewupdatewindowsurfaceviewjava536 0526 103720682 errormediaplayerdemo24240 at androidviewsurfaceviewthispatchdrawsurfaceviewjava339 0526 103720682 errormediaplayerdemo24240 at androidviewviewgroupdrawchildviewgroupjava1638 0526 103720682 errormediaplayerdemo24240 at androidviewviewgroupthispatchdrawviewgroupjava1367 0526 103720682 errormediaplayerdemo24240 at androidviewviewgroupdrawchildviewgroupjava1638 0526 103720682 errormediaplayerdemo24240 at androidviewviewgroupthispatchdrawviewgroupjava1367 0526 103720682 errormediaplayerdemo24240 at androidviewviewdrawviewjava6796 0526 103720682 errormediaplayerdemo24240 at androidwidgetframelayoutdrawframelayoutjava352 0526 103720682 errormediaplayerdemo24240 at androidviewviewgroupdrawchildviewgroupjava1640 0526 103720682 errormediaplayerdemo24240 at androidviewviewgroupthispatchdrawviewgroupjava1367 0526 103720682 errormediaplayerdemo24240 at androidviewviewdrawviewjava6796 0526 103720682 errormediaplayerdemo24240 at androidwidgetframelayoutdrawframelayoutjava352 0526 103720682 errormediaplayerdemo24240 at comandroidinternalpolicyimplphonewindowdecorviewdrawphonewindowjava1894 0526 103720682 errormediaplayerdemo24240 at androidviewviewrootdrawviewrootjava1407 0526 103720682 errormediaplayerdemo24240 at androidviewviewrootperformtraversalsviewrootjava1163 0526 103720682 errormediaplayerdemo24240 at androidviewviewroothandlemessageviewrootjava1727 0526 103720682 errormediaplayerdemo24240 at androidoshandlerthispatchmessagehandlerjava99 0526 103720682 errormediaplayerdemo24240 at androidoslooperlooplooperjava123 0526 103720682 errormediaplayerdemo24240 at androidappactivitythreadmainactivitythreadjava4627 0526 103720682 errormediaplayerdemo24240 at javalangreflectmethodinvokenativenative method 0526 103720682 errormediaplayerdemo24240 at javalangreflectmethodinvokemethodjava521 0526 103720682 errormediaplayerdemo24240 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava871 0526 103720682 errormediaplayerdemo24240 at comandroidinternaloszygoteinitmainzygoteinitjava629 0526 103720682 errormediaplayerdemo24240 at dalviksystemnativestartmainnative method 0526 103720737 infomediaplayer24240 info 126 0526 103720737 errormediaplayer24240 error 11 0526 103720868 infoactivitymanager10163 thisplayed activity comgiantrabbitnagarekraltvnow 25864 ms total 25864 ms 0526 1037237 warnpowermanagerservice10163 timer 0x30x30x1 this is an example of httpmmediaplayer new mediaplayermmediaplayersetdatasourcemmediaplayersetthisplayholdermmediaplayerprepareasyncmmediaplayersetonbufferingupdatelistenerthismmediaplayersetoncompletionlistenerthismmediaplayersetonpreparedlistenerthismmediaplayersetonvideosizechangedlistenerthismmediaplayersetaudiostreamtypeaudiomanagerstream musicmmediaplayersetloopingtrueexception0526 101624276 errormediaplayerservice10157 create pvplayer 0526 101624292 error10157 i inside constructor of pvmfmemorybufferwritedatastreamimpl 0526 101624346 infoplayerdriver10157 buffering 100 0526 101624346 error10157 i inside constructor of pvmfmemorybufferreaddatastreamimpl 0526 101624346 error10157 i inside constructor of pvmfmemorybufferreaddatastreamimpl 0526 101624346 error10157 i inside constructor of pvmfmemorybufferreaddatastreamimpl 0526 101624346 error10157 i inside constructor of pvmfmemorybufferreaddatastreamimpl 0526 101624346 error10157 i inside constructor of pvmfmemorybufferreaddatastreamimpl 0526 101624346 error10157 i inside constructor of pvmfmemorybufferreaddatastreamimpl 0526 101624346 error10157 i inside constructor of pvmfmemorybufferreaddatastreamimpl 0526 101624346 error10157 i inside constructor of pvmfmemorybufferreaddatastreamimpl 0526 101624346 error10157 i inside constructor of pvmfmemorybufferreaddatastreamimpl 0526 101624346 error10157 i inside constructor of pvmfmemorybufferreaddatastreamimpl 0526 101624346 error10157 i inside constructor of pvmfmemorybufferreaddatastreamimpl 0526 101624346 error10157 i inside constructor of pvmfmemorybufferreaddatastreamimpl 0526 101624350 warnmediaplayer23736 infowarning 1 26 0526 101624354 errorplayerdriver10157 command player init completed with an error or info 10 0526 101624354 errormediaplayer23736 error 10 10 0526 101624354 warnplayerdriver10157 pvmfinfoerrorhandlingcomplete 0526 101624393 infomediaplayer23736 info 126 0526 101624393 errormediaplayer23736 error 1010 httpvideoview videoview videoviewfindviewbyidridvideoview1uri uri uriparsevideoviewsetvideouriurivideoviewstartit gives the messagesorry this video cannot ve played,['android'] +156237,how do i move a column with contents to another table in a rails migration i need to move some columns from one existing table to another how do i do it using a rails migrationclass addpropertytouser activerecordmigration def selfup add column users someprop string remove column profiles someprop end def selfdown add column profiles someprop string remove column users someprop endendthe above just creates the new columns but values are left emptyi want to avoid logging in to the database to manually update the tablesif there is a way to move column values programmatically what are the performance characteristics would it do rowbyrow or is there a way to update in bulk,['ruby-on-rails'] +156256,is using an union in place of a cast well defined i had a thiscussion this morning with a colleague regarding the correctness of a coding trick to detect endiannessthe trick wasbool is big endian union int i char csizeofint foo fooi 1 return fooc0 1to me it seems that this usage of an union is incorrect because setting one member of the union and reading another is not welldefined but i have to admit that this is just a feeling and i lack actual proofs to strengthen my pointis this trick correct who is right here,['c++'] +156263,difference between style and controltemplate could you tell me what is the main differences between style and controltemplate when or why to use one or the other to my eyes they are exactly the very same as i am beginner i think that i am wrong thus my question,"['c#', '.net']" +156272,a non well formed numeric value encountered i have a form that passes two dates start and finish to a php script that will add those to a db i am having problems validating this i keep getting the following errors a non well formed numeric value encounteredthis is when i use the following dated getstart datebut when i use the strtotime function as advised by many sites i get a unix timestamp date of 1970any ideas how i can get the correct date,['php'] +156276,compare buffers as fast as possible i need to compare two buffers chunkwise for equality i do not need information about the relation of the two buffers just if each two chunks are equal or not my intel machine supports up to sse42the naive approach isconst size t chunk size 16 128bit for sse2 integer registersconst int array size 20char array 1 char aligned mallocarray size 16char array 2 char aligned mallocarray size 16for size t i 0 i array size volatile bool result memcmparray 1i array 2i chunk size i chunk sizecompared to my first try using sse everunion u m128i m volatile int i4 resfor size t i 0 i array size m128i pa1 m128iarray 1i m128i pa2 m128iarray 2i resm mm cmpeq epi32pa1 pa2 volatile bool result resi00 resi10 resi20 resi30 i chunk sizethe gain in speed is about 33 could i do any better,['c'] +156278,android dynamic array listpreference how to create dynamic array for listpreference from java sidei do not use below xml xml version10 encodingutf8resourcesstringarray namelistarray itemvalue 1item itemvalue 2itemitemvalue 3itemstringarraystringarray namelistvalues item1item item2item item3itemstringarrayresources,['android'] +156281,unicode test strings for unit tests i need some utf32 test strings to exercise some cross platform string manipulation code i would like a suite of test strings that exercise the utf32 utf16 utf8 encodings to validate that characters outside the bmp can be transformed from utf32 through utf16 surrogates through utf8 and back properlyand i always find it a bit more elegant if the strings in question are not just composed of random bytes but are actually meaningful in the various languages they encode,['c++'] +156287,object mapping library from json to nsobjects i am trying to build a parserobjectmapper that will build objective c objects for the json i consume from a rest servicei took some inspiration from restkit by having my entities all hold a decoding list which tells a mapper which json keys goes with which objects like thisobjectentity implementation nsdictionary mapproperties localpropertiy jsonproperty return name name category category possible scopes possiblescopes possible descriptions possibledescriptions key keys nsdictionary maprelations return nsdictionary dictionaryi did so because i like the encapsulation of these changeable values to be in the object that they reference making the mapper know as little as possiblethe mapper does something like this nsarray parsedatansdata jsondata intoobjectsoftypeclass objectclass parser result from web service nserror error nil cjsondeserializer deserializer cjsondeserializer deserializer deserializer setnullobjectnil nsarray objects deserializer deserializeasarrayjsondata errorerror nsmutablearray result nsmutablearray array for nsdictionary o in objects id entityprotocol entity objectclass alloc init nsdictionary jsonkeys objectclassmapproperties for nsstring key in jsonkeysallkeys nsstring objectproperty jsonkeyskey nsstring value okey if value entity setvaluevalue forkeyobjectproperty result addobjectentity return nsarrayresultso i message the parsermapper like thisnsarray objects objectparser parsedataselfresponsedata intoobjectsoftypeobjectentityclassthis means that the parser must know what my root object is which is fine as the object retrieving it from the web service of course has this knowledgethe above only works for json without nested objects i have been trying to build the parser so that it will take the relationships into account as well building the needed objects and inserting them into the root object this needs to be recursive and i keep running into dead endsi would like some help to how i could approach this or any insight to as if something like this exists out as a library maybe for using or maybe just for tackling the parts i have problems withthank you in advance,"['objective-c', 'ios']" +156301,resqueenqueue failing on second run i am trying to port an app from rails 303 to rails 31rc i do not think i have missed out anything in terms of configuration the process works perfectly in rails 30x and not in 31rcin console i doresqueenqueueencodesong songfind20id songfind20unencoded urleverything works so far resqueweb reports no failed jobs and i get the two puts from module encodesong however running resqueenqueueencodesong songfind20id songfind20unencoded url a second time will return the following error in resqueweb below to make the error go away i would have to close the process thats running queue rake environment resquework and rerun it in the console window but the problem comes back after trying to resqueenqueue after the first timeclass encodesongarguments 20 httpsbucket names3amazonawscomunencodedusers1songstestmp3exception pgerrorerror server closed the connection unexpectedly this probably means the server terminated abnormally before or while processing the request userschrisrvmgemsruby192p136railspregemsactiverecord310rc1libactive recordconnection adapterspostgresql adapterrb272in exec userschrisrvmgemsruby192p136railspregemsactiverecord310rc1libactive recordconnection adapterspostgresql adapterrb272in block in clear cache userschrisrvmgemsruby192p136railspregemsactiverecord310rc1libactive recordconnection adapterspostgresql adapterrb271in each value userschrisrvmgemsruby192p136railspregemsactiverecord310rc1libactive recordconnection adapterspostgresql adapterrb271in clear cache userschrisrvmgemsruby192p136railspregemsactiverecord310rc1libactive recordconnection adapterspostgresql adapterrb299in thisconnect userschrisrvmgemsruby192p136railspregemsactiverecord310rc1libactive recordconnection adaptersabstractconnection poolrb191in block in thisconnect userschrisrvmgemsruby192p136railspregemsactiverecord310rc1libactive recordconnection adaptersabstractconnection poolrb190in each userschrisrvmgemsruby192p136railspregemsactiverecord310rc1libactive recordconnection adaptersabstractconnection poolrb190in thisconnect userschrisrvmgemsruby192p136railspregemsactivesupport310rc1libactive supportcore extmodulesynchronizationrb35in block in thisconnect with synchronization userschrisrvmrubiesruby192p136libruby191monitorrb201in mon synchronize userschrisrvmgemsruby192p136railspregemsactivesupport310rc1libactive supportcore extmodulesynchronizationrb34in thisconnect with synchronization userschrisrvmgemsruby192p136railspregemsactiverecord310rc1libactive recordconnection adaptersabstractconnection poolrb407in remove connection userschrisrvmgemsruby192p136railspregemsactiverecord310rc1libactive recordconnection adaptersabstractconnection specificationrb116in remove connection userschrisrvmgemsruby192p136railspregemsactiverecord310rc1libactive recordconnection adaptersabstractconnection specificationrb79in establish connection userschrisrvmgemsruby192p136railspregemsactiverecord310rc1libactive recordconnection adaptersabstractconnection specificationrb60in establish connection userschrisrvmgemsruby192p136railspregemsactiverecord310rc1libactive recordconnection adaptersabstractconnection specificationrb55in establish connection userschrissitessite namelibtasksresquerake17in block 2 levels in top required userschrisrvmgemsruby192p136railspregemsresque1161libresqueworkerrb355in call userschrisrvmgemsruby192p136railspregemsresque1161libresqueworkerrb355in run hook userschrisrvmgemsruby192p136railspregemsresque1161libresqueworkerrb162in perform userschrisrvmgemsruby192p136railspregemsresque1161libresqueworkerrb130in block in work userschrisrvmgemsruby192p136railspregemsresque1161libresqueworkerrb116in loop userschrisrvmgemsruby192p136railspregemsresque1161libresqueworkerrb116in work userschrisrvmgemsruby192p136railspregemsresque1161libresquetasksrb27in block 2 levels in top required userschrisrvmgemsruby192p136railspregemsrake090libraketaskrb205in call userschrisrvmgemsruby192p136railspregemsrake090libraketaskrb205in block in execute userschrisrvmgemsruby192p136railspregemsrake090libraketaskrb200in each userschrisrvmgemsruby192p136railspregemsrake090libraketaskrb200in execute userschrisrvmgemsruby192p136railspregemsrake090libraketaskrb158in block in invoke with call chain userschrisrvmrubiesruby192p136libruby191monitorrb201in mon synchronize userschrisrvmgemsruby192p136railspregemsrake090libraketaskrb151in invoke with call chain userschrisrvmgemsruby192p136railspregemsrake090libraketaskrb144in invoke userschrisrvmgemsruby192p136railspregemsrake090librakeapplicationrb112in invoke task userschrisrvmgemsruby192p136railspregemsrake090librakeapplicationrb90in block 2 levels in top level userschrisrvmgemsruby192p136railspregemsrake090librakeapplicationrb90in each userschrisrvmgemsruby192p136railspregemsrake090librakeapplicationrb90in block in top level userschrisrvmgemsruby192p136railspregemsrake090librakeapplicationrb129in standard exception handling userschrisrvmgemsruby192p136railspregemsrake090librakeapplicationrb84in top level userschrisrvmgemsruby192p136railspregemsrake090librakeapplicationrb62in block in run userschrisrvmgemsruby192p136railspregemsrake090librakeapplicationrb129in standard exception handling userschrisrvmgemsruby192p136railspregemsrake090librakeapplicationrb59in run userschrisrvmgemsruby192p136railspregemsrake090binrake31in top required userschrisrvmgemsruby192p136railsprebinrake19in load userschrisrvmgemsruby192p136railsprebinrake19in mainhere is the rest of my relevant codeconfiginitializersresquerbrequire resqueuri uriparseapp configrethis to go urlresquerethis rethisnewhost urihost port uriport password uripassword load all jobs at appjobsdirrailsrootappjobsrbeach file require file appjobsencode songrbmodule encodesong queue encode song def selfperformmedia id s3 file url begin media songfindmedia id puts foo1 puts mediaid rescue puts error end endendlibtasksresquerakerequire resquetaskstask resquesetup environment do envqueue only on heroku since they are still running postgresql 8 on their shared plan this block of code is not needed on postgresql 9 as tested on local environment issue my best guess is that master resque process establishes connection to db while loading rails app classes models etc and that connection becomes corrupted in forked process on exit possible fix is to reestablish the connection the ar after a resque fork resqueafter fork do job activerecordbaseestablish connection endenddesc alias for resquework to run workers on herokutask jobswork resqueworknot very sure but it may be somewhat related to this issue my guess is that master resque process establishes connection to db while loading rails app classes models etc and that connection becomes corrupted in forked process on exitany help direction will be appreciatededitif i remove the following block from libtasksresquerake resqueafter fork do job activerecordbaseestablish connection endand in console run resqueenqueueencodesong songfind20id songfind20unencoded urli get a new error in console where queue rake environment resquework was runerror pgerror error prepared statement a3 already exists select songs from songs where songsid 1 limit 1it seems this may be a bug with the adapter could be wrong here your thoughts,['ruby-on-rails'] +156318,rails i18n default scope i am using the defaul i18n module for rails to translate my strings in views tregistrationheading now when i am in the registrationview all my strings start with registration i always have to write tregistrationheadingnotice or theading scope registration it would be nice to define a default scope for that file maybe even in the controller so a call to t automatically adds the defined scope controllerset i18n default scope registration view theading looks in registrationheadingis this possible,['ruby-on-rails'] +156327,is there any way to change androidwindowsoftinputmode value from java class i want to act my tabs to have different windowsoftinputmode properties for each tab how to access this property from java class when all handling of your tab is done from one single activityis there any way to access this manifest property from java code,['android'] +156335,how does a service layer fit into my repository implementation i have created a poco model class and a repository class which handles persistence since the poco cannot access the repository there are lots of business logic tasks in the repository which does not seem right from what i have read it looks like i need a service layer that sits between the ui consumers and the repository layer what i am not sure of is exactly how it is supposed to workin addition to the service layer should there also be a separate business logic layer or is that the role of the service layershould there be one service per repositoryis the service layer the only way that the ui can instance the model objects or does the repository provide the new model instance to the servicedo i put my parameter model and other validations in the service layer that do things like check to make sure a input is valid and that a item to update exists in the database before updating can the model repository and ui all make calls to the service layer or is it just for the ui to consumeis the service layer supposed to be all static methodswhat would be a typical way to call the service layer from the uiwhat validations should be on the model vs the service layerhere is some sample code for my existing layerspublic class giftcertificatemodel public int giftcerticiateid getset public string code getset public decimal amount getset public datetime expirationdate getset public bool isvalidcodepublic class giftcertificaterepository only way to access database public giftcertificatemodel getbyidint giftcertificateid public listgiftcertificatemodel getmany public void savegiftcertificatemodel gc public string getnewuniquecode code has to be checked in db public giftcertificatemodel createnew giftcertificatemodel gc new giftcertificatemodel gccode getnewuniquecode return gc update i am currently using web forms and classic adonet i hope to move to mvc and ef4 eventuallyupdate big thanks to lester for his great explanation i now understand that i need to add a service layer for each of my repositories this layer will be the only way the ui or other services can communicate with the repository and will contain any validations that do not fit on the domain object eg validations that need to call the repopublic class giftcertificateservice public void redeemstring code decimal amount giftcertificate gc new giftcertificate if gcisvalidcodecode throw new argumentexceptioninvalid code if amount 0 getremainingbalancecode amount throw new argumentexceptioninvalid amount giftcertificaterepository gcrepo new giftcertificaterepository gcreporedeemcode amount public decimal getremainingbalancestring code giftcertificate gc new giftcertificate if gcisvalidcodecode throw new argumentexceptioninvalid code giftcertificaterepository gcrepo new giftcertificaterepository gcrepogetremainingbalancecode public savenewgcgiftcertificate gc validates the gc and calls the repo save method updates the objects new db id questionsdo i add the same and possibly more properties to the service as i have on my model amount code etc or do i only offer methods that accept giftcertificate objects and direct parameters do i create a default instance of the giftcertificate entity when the service constructor is called or just create new ones as needed eg for validation methods in the service that need to call validation methods in the entity also same question about creating a default repository instancei know i expose the functionality of the repo via the service do i also expose the methods from the entity as well eg isvalidcode etcit is ok for the ui to simply create a new giftcertificate object directly without going through the service eg to call parameter validation methods from the entity if not how to enforce iton the ui layer when i want to create a new gift certificate do i call the modelservice validations like isvalidexpirationdate etc directly from the ui layer or do i hydrate the object first then pass it in to be validated and then return some sort of validation summary back to the ui also if i want to redeem from the ui layer do i first call the modelservice validation methods from the ui to give user feedback and then call the redeem method which will run the same checks again internallyexample for calling service to do a redeem operation from uistring redeemcode redeemcodetextboxtextgiftcertificateservice gcservice new giftcertificateservicegiftcertificate gc new giftcertificate do this to call validation methods should be through service somehowif gcisvalidredeemcode give error back to userif gcservicegetremainingbalanceredeemcode amount give error back to userif no errorsgcserviceredeemcodeamountexample for creating a new gift certificate from uigiftcertificateservice gcservice new giftcertificateservicegiftcertificate gc new giftcertificateif gcisvalidexpdateinputexpdate give error to userif no errorsgccode gcservicegetnewcodegcamount 10mgcexpirationdate inputexpdategcservicesavenewgcgcmethod updates the gc with the new idsomething feels wrong about way gcs are being created and how the validations are separated between entityservice the userconsumer should not have to be concerned with what validations are in which place advice,"['c#', 'asp.net']" +156361,how to determine table name within a rails 3 model class i want to get table name in a model method i found there should be method table name but when i try to call it i get nameerror exception undefined local variable or method table name it is obviously not there pp methodsgreptatable name prefix table name suffix taint taguri taguri tainted table name prefix table name suffix taphow to get a real table name no lowecase pluralize tricksthanks,['ruby'] +156380,what are the most common fontsizes for h1h6 tags i have always been unsure of where to start as a general best practice baseline yes i know it depends on your design but whats most commonheres what i currently have as a starterh1 fontsize 24pxh2 fontsize 22pxh3 fontsize 18pxh4 fontsize 16pxh5 fontsize 12pxh6 fontsize 10pxyes we do not use ems at my current job thanks,"['html', 'css']" +156389,jquery sortable placeholder height problem for some reason the placeholder for my sortable items is about 10px all my sortable items have different heights how can i change the height of each placeholder to match the item being moved,['jquery'] +156399,mac os x 1067 java path current jdk confusing i have trouble understanding actual paths vs links for multiple java versions on my mac osx normally in windows if i have multiple versions installed in my machine i can just take the path of which ever version i want and use it but in mac os x i undertand that there is something called links that is being pointed to currentjdk and if i want to use a different version i will need to change the link to currentjdk right but what is confusing for me is that as you can see below all my versions are pointing to the same currentjdk which means all versions point to current version i was expecting only one of them would be pointing to currentjdk and i could just change it to which ever one i need which is not the case here all i need to know is how to find the bincommands folder path for each version so that i can just use it to point to currentjdk also tell me how to change the link to currentjdk java versionjava version 160 24javatm se runtime environment build 160 24b0733410m3326java hotspottm 64bit server vm build 191b02334 mixed mode pwdsystemlibraryframeworksjavavmframeworkversions ls llrwxrxrx 1 root wheel 5 mar 20 12 13 131drwxrxrx 3 root wheel 102 dec 2 2009 131lrwxrxrx 1 root wheel 10 mar 20 12 14 currentjdklrwxrxrx 1 root wheel 10 mar 20 12 142 currentjdklrwxrxrx 1 root wheel 10 mar 20 12 15 currentjdklrwxrxrx 1 root wheel 10 mar 20 12 150 currentjdklrwxrxrx 1 root wheel 10 mar 20 12 16 currentjdklrwxrxrx 1 root wheel 10 mar 20 12 160 currentjdkdrwxrxrx 10 root wheel 340 mar 20 13 alrwxrxrx 1 root wheel 1 mar 20 12 current alrwxrxrx 1 root wheel 59 mar 20 12 currentjdk systemlibraryjavajavavirtualmachines160jdkcontents,['java'] +156405,android devices with pressure sensor are there any android devices out there that have a barometric pressure sensori know that the androidhardwaresensor class has a type pressure constant and the getaltitude method in sensormanager almost mentions atmospheric pressureso are there any android phones out there that have a barometer on them,['android'] +156414,setting maxlength of textbox with javascript or jquery i want to change the maxlength of a textbox with javascript or jquery i tried the following but it did not seem to helpvar a documentgetelementsbytagnameinputforvar i0 ialength i ifaitype radioaitype checkbox aimaxlength 5documentgetelementsbytagnameinput1maxlength3readyfunction inputidmaxlength6what am i doing wrong,"['javascript', 'jquery']" +156422,android center gridview horizontally i need to center grid view horizontally in my android layoutxml i have searched google for quite a while but didnt succeed in finding an answer i can only change gridview horizontal position by changing strechmode but then my items are not near one anotherthat i need is items be one near another without spaces and centered horizontally i choose strechmode none so now my items are near one another but they are on the left of the screen i just want them to be centered horizontallyhere is my layout xmllinearlayout xmlnsandroid androidlayout widthfill parent androidlayout heightfill parent androidbackgrounddrawablebackground androidgravitycentergridview androidididlw gridview androidlayout widthwrap content androidlayout heightwrap content androidnumcolumns3 androidcolumnwidth48dp androidhorizontalspacing0dp androidverticalspacing0dp androidstretchmodenone linearlayouthere is fragment of an image which is set on gridview by image adapterimageview new imageviewcontextimageviewsetlayoutparamsnew gridviewlayoutparams4848 on medium densityimageviewsetscaletypeimageviewscaletypecenterimageviewsetpadding0 0 0 0how can i succeed,['android'] +156440,how do i force a polymorphic call to the super method i have an init method that is used and overridden through out an extensive heirarchy each init call however extends on the work that the previous did so naturally i wouldoverride public void init superinitand naturally this would ensure that everything is called and instantiated what i am wondering is can i create a way to ensure that the super method was called if all of the init is are not call there is a break down in the obejct so i want to throw an exception or an error if somebody forgets to call supertyft aedon,['java'] +156442,unexpected end in evald code i hate to ask such a specific question but i am getting an error i cannot figure out this is in a cron job which runs on the hour i am creating an array of tasks each of which has a date check which is supposed to be evaldtodo arraytodo array datez3 0 task 1 todo array daten 1 task 2 foreach todo as task if evaltask0 echo task1 for some reason the eval line is giving me this error note that i am getting this error for both tasksparse error syntax error unexpected end in filephp21 evald code on line 1any suggestions i tried searching for this but could not find anything thank you,['php'] +156445,cannot find systemwindowsvector in c i am making a windows forms application in visual studio 2010 ultimate but cannot get the builtin vector to workmicrosoft says that there is a systemwindowsvector in the net framework 4 maybe i am making some large mistake but visual studio complains about trying to use vector in any way and it does not come up in the intellisense autocompletethe line vector v new vector20 30 givescompile error error 1 the type or namespace name vector could not be found are you missing a using directive or an assembly referencei tried including a using systemwindows at the top but that did not solve the problemi went to references add reference to try to find something to add but nothing was obviousthe problem may be also listed with vector in the systemwindows namespace there are other classes like rect or application i could use these as systemdrawingrectangle or systemwindowsformsapplication but none of these show up as part of some systemwindows namespacei have tried different things for about 2 hours and found this related post but vector is part of net 4 so their fix does not seem worthwhile and this possibly related post but i do have net framework 4 installeddoes anyone have an example of vector i know i could get a third party class but i feel i am missing something and want to learnhave the solution posted for other people googling the same problem,"['c#', '.net']" +156449,how do i initialize a stl vector of objects who themselves have nontrivial constructors suppose i have the following classclass myinteger private int and public myintegerint n and n more stuffand suppose this class do not have a default trivial constructor myinteger i must always supply an int to initialize it for some reason and then suppose that somewhere in my code i need a vectormyinteger how do i initialize each myinteger component in this vectori have two situations probably the solution is the same but i will state them anyway a normal variable inside a functionint main vectormyinteger foo10 how do i initialize each myinteger field of this vector dostufooand as data in a classclass myfunclass private vectormyinteger myvectorpublic myfunclassint size int myintegervalue myvectorsize what do i put here if i need the initialization to call myintegermyintegervalue for all components of myvectoris it possible to do it just in the initialization list or must i write the initialization by hand in the myfunclassint int constructor this seems so very basic and yet i somehow missed it inmy book and cannot find in the web,['c++'] +156452,using a keyword as variable name in an ini file i have the following in an ini filecountryse swedenno norwayfi finlandhowever when var dumping phps parse ini file function i get the following outputphp warning syntax error unexpected bool false in testini on line 2in usersandrewsandboxtestphp on line 1boolfalseit appears that no is reserved is there any other way i can set a variable named no,['php'] +156470,how search for thousands of possible keywords in a string i have a database of thousands about 10 keywords when a user posts a blog on my site i would like to automatically search for the keywords in the text and tag the post with any direct matchesso far all i can think of is to pull the entire list of keywords loop through it and check for the presence of each tag in the postwhich seems very inefficient that is 10 loopsis there a more common way to do this should i maybe use a mysql query to limit it downi imagine this is not a totally rare task,"['php', 'mysql']" +156483,how can i override the http methods for put and delete in a flask module i am having a hard time trying to modify the flask request object before routing occursmy api module not my entire flask app depends on faking put and delete operations by sending a special header i need to check out the contents of the method header and modify the flask request object accordingly before flask does its routingthis is the short pythonic explicit code i would like to workapibefore requestdef method scrubbing if requestheadershas keymethod method requestheadersmethodupper tagaloglogin before request method formatmethod force if method not in put delete raise apimethodexceptionmethod else requestmethod methodbut i get a read only property error from werkzeug i have seem armins post at but this appears to be appwide not specific to a module,['python'] +156502,creating a collection of beans in spring using configuration how can i create a collection of beans that will be properly managed by spring using a class with a configuration annotationi would like to do something like thisconfigurationpublic config autowired private someconfiguration config bean public listmybean mybeans listmybean beans new arraylistmybean for device device configgetdevices beansaddnew mybeandevice return beans but the mybean instances are not post processed so their autowired methods are not called the beans are not registered as mbeans and etc the list is however accessible so that i can autowire a list of mybean objectsi cannot use something likeconfigurationpublic config autowired private someconfiguration config bean public mybean mybean1 bean public mybean mybean2 since the number of mybean instances are not known before runtime the reason i want to do this is because we are controlling a physical machine that have a variable amount of components and i want to have one bean per componenti am currently achieving our goal by using a beanfactorypostprocessor like thiscomponentpublic class mybeansfactorypostprocessor implements beanfactorypostprocessor autowired private someconfiguration config override public void postprocessbeanfactoryconfigurablelistablebeanfactory beanfactory throws beanexception for device device configgetdevices createandregisterbeandefinitionregistry beanfactory device private void createandregisterbeandefinitionregistry registry device device registerregisterbeandefinitiondevice devicegetid beandefinitionbuildergenericbeandefinitionmybeanclassaddconstructorargvaluedevicegetbeandefinition but this just feels like a really ugly hack,['java'] +156523,uicolor clearcolor the documentation says the clearcolors grayscale and alpha 0 what does that actually mean is it just a color to match whatever the background is,"['iphone', 'objective-c']" +156525,python zip behavior in bash is there similar python zip functionailty in bash to be specific i am looking for the equivilent functionality in bash without using python echo a test a echo b test a echo 1 test b echo 2 test b python c print njoin joinastripbstrip for ab in zipopentest aopentest ba 1b 2,['python'] +156532,c crystal report problem and chart i have 4 charts at my application drawn with custom codei also have a rdlc crystal report that outputs the data but not the chartwhat i have to do is to add the chart at the reporti can add a chart object at the report but i dont know how to program it since it is in the report and i dont know how to refer to it via the reportviewer only solution seems to be dataset binding but i am too confused it should be customized a lot dont know if it is possible without writing source codeany ideasplease help this is a headache,['c#'] +156535,cross platform native opensave file dialogs i am writing a ui for my program using opengl with sdl in a combination of lua and cwhat i need now is some library that will allow me to call a function that presents the user with a file select dialog for openingsaving a file but if the os offers native functionality for such a dialog then i want to use that dialog eg windows getopenfilenamethe only platforms i need to support are windows and linux but i want to be able to still use most of the sdl opengl code i have already writtenwhat options are available,['c++'] +156537,how to stop a vimeo video with jquery when i hide a youtube video it stops playing however this is not the case for vimeo videos is there another way to stop a vimeo video,"['javascript', 'jquery']" +156542,plotting a line over several graphs i do not know how this thing is called or even how to describe it so the title may be a little bit misleadingthe first attached graph was created with pyplot i would like to draw a straight line that goes through all graphs instead of the three red dot i currently use is it possible in pyplot second image is what i am looking for,['python'] +156548,jsonnet exclude properties of a specific type at runtime i am wondering how to excludestrip certain properties of given types or collections of those from being serialized using jsonnet library i tried to write my own contract resolver inheriting from defaultcontractresolver with no lucki know that i could be done using dataannotations decorating the excluded properties with scriptignoreattribute but it is not applicable in my scenario the objects serialized can be virtually anything so i do not know which properties to exclude at designtime i know only the types of properties that should not be serializedit looks like a rather simple task but unfortunately i could not find a decent solution anywherebtw i am not bound to jsonnet library if it can easily be done with defaultother net json serializers it would be an equally good solution for meupdatethe properties has to be excluded before trying to serialize them why basically the types of objects i am receiving and serializing can have dynamic properties of type inheriting from idynamicmetaobjectprovider i am not going to describe all the details but the dynamicmetaobject returned from getmetaobject method of these objects does not have dynamicmetaobjectgetdynamicmembernames method implemented throws notimplementedexception summarizing the problem is those objects i need to exclude does not allow to enumerate their properties what jsonnet serializer tries to do behind the scenes i always end up with notimplementedexception being thrown,"['c#', '.net']" +156549,is it possible to have the url change while you scroll down a single page is it possible to have the url change while you scroll down a single page with ajax i have a website all on one page and want to have this effectexamplewblablablacombloguser scroll downwblablablacomblogentrynamei know about hashing can i mask the url,['javascript'] +156560,jquery masked input existing input value i am using jquery masked input plugin however when i set the mask any existing value in the input field is being destroyed doing the followingpriceskuidmask placeholder there must be a way to deal with existing values which are programmatically placed into the input field,['jquery'] +156564,division not crossing over bytes i am trying to do division on a uint128 t that is made up of 2 uint64 ts weirdly enough the function works for uint64 ts with only the lower value set and the upper value 0 i do not understand whyheres the code for the division and bit shiftclass uint128 t private uint64 t upper lower public lots of stuff uint128 t operatorint shift uint128 t out if shift 128 out uint128 t0 0 else if 128 shift shift 64 out uint128 tlower 64 shift 0 else if shift 64 out uint128 tupper shift lower 64 shift lower shift return out uint128 t operatorint shift this this shift return this uint128 t operatoruint128 t rhs copy of numerator copyn uint128 t copynthis quotient 0 constructor uint128 tt uint128 ts t uint128 tuint128 t etc while copyn rhs copy of denomiator copyd temp is the current quotient bit being worked with uint128 t copydrhs temp1 shift the divosr to the highest bit while copyn copyd 1 copyd 1 temp 1 copyn copyd quotient temp return quotient more stuffplease ignore my blatant thisregard for memory management,['c++'] +156579,javalangindexoutofboundsexception source does not fit in dest on the following codestatic void findsubsets arraylistinteger numbers int amount int index arraylist integer numberscopy new arraylistintegernumberssize collectionscopynumberscopy numbersi am getting the errorexception in thread main javalangindexoutofboundsexception source does not fit in dest at javautilcollectionscopycollectionsjava548 at backtracking2mainfindsubsetsmainjava61why,['java'] +156587,blocks and stack i know that blocks are created in the stack however since i do not have enough knowledge about stack and local variables i can not understand why i should move the block to heap in order to have expected result intuitively i feel like the block code chunk has only 1 instance in the stack this code is referencing to local variable i 3 times if i copy it to heap it will have 3 different instances and each time it will capture 3 different values of i during copy procedure but i would really like to know more about block code in stack heap and referencing local variablesfor int i0 i3 i bi return ifor int i0 i3 i printfb dn bi,['objective-c'] +156615,append data to a post nsurlrequest how do you append data to an existing post nsurlrequest i need to add a new parameter userid2323,"['ios', 'objective-c']" +156622,how to understand and choose values when working with colormatrix i have read the colormatrix documentation and it says the following5x4 matrix for transforming the coloralpha components of a bitmap the matrix is stored in a single array and its treated as follows a b c d e f g h i j k l m n o p q r s t when applied to a color r g b a the resulting color is computed as after clampingr ar bg cb da e g fr gg hb ia j b kr lg mb na o a pr qg rb sa t i know how to get the result but i still have some questionswhat is the value of color r g b a is color r g b a calculated by systemi know that a d c d and so on can be negative values what is the difference between positive values and negative valuesi have no graphic knowledge it is very hard to get a satisfactory image i have to usual try many times to get a good result are there any tools or website that can give some guidance on how to get the valve of a b c dt possibly with examples,['android'] +156632,forgot keystore password thinking of bruteforce detection will it corrupt the keystore i recently realized that i have lost the password to my keystore or perhaps the keystore got corrupted somehowit keeps giving me the error keystore tampered or password incorrecti created an quite unoptimized algorithm to bruteforce the password by letting it run all the night however i am not sure how many unsuccessful password attempts will lock the keystore downdoes anyone know anything like thisupdatethe algorithm i devised works okay i am using java but i realized that normally the keystore tool asks for the password only when i press enter but to get the bruteforce to work i would want it to have a switch and accept password in the same line is it possible,['android'] +156633,animating from offscreen with translateanimation causes adjacent view to be clipped right now i have a view that i am just popping onto the screen by changing the view from gone to visible and i instead want to have a translateanimation that shifts the view onto the screen as soon as the animation starts the view on the right becomes clipped though i assume this is because the parent view is taking the width of the view on the left and factoring that into the view calculation is there any way to not have that happen so it looks like both views are shifting onto and off of the screen setting androidclipchildrenfalse androidcliptopaddingfalsedid not seem to help,['android'] +156638,what is the difference between using regexp and using forward slash notation to test against string is there any difference between using new regexpregex and same regex to test against a target string i am asking this question because i got different validating result while use these two approaches here is the snippet i used to validate an email fieldvar emailfoocomvar regex1 new regexpaz09 az09 az09az09az09az09az09az09 var regex2 az09 az09 az09az09az09az09az09az09using regexp objectifregex1testemail consolelogemail matched regex1 else consolelogemail mismatched regex1 using slash notationifregex2testemail consolelogemail matched regex2 else consolelogemail mismatched regex2 i got two inconsistent resultsemail matched regex1email mismatched regex2i am wondering if there is any difference here or i omitted something in this specific example for an executable example please refer to here,['javascript'] +156641,weird ie8 layout glitch why does the body background thisappear this is one of those what the bloody hell problems that i do not even know how to approachi have this website and if you open it in ie8 it loads fine and after half a second the layout gets messed up if you then resize the window it gets back to normal also if you open developer tools and thisable and reenable a css property does not matter which one the layout gets fixed toounfortunately i cannot remember when this started happening so i do not know what i did that caused this and i really have no idea what to do i have spent 3 hours searching for a solution on google without any luck to be honest i am not really sure what to search forhere is the messedup screenshotand this is how it should looki am using internet explorer 8 v 80760117514 on windows 7edit i have now managed to kinda isolate the problem if jquery v161 is included on the page then this thing happens including jquery v132 does not cause this problem,"['jquery', 'css']" +156642,ruby on rails running a rb file from irb i am starting out with ruby on rails i am currently going through a tutorial where it says that i have to run a rb file from irb and that that will create a xml file in my current directory my question is how do i run a rb file in irb and do i have to be in the directory where this rb file lives when i run it in irb i tried the following just typing irb on the command line in the directory of the file that starts an irb session as far as i understand then i typed irb filenamerb which went through but did not create anything in the current directory but at least it did not give any errors i also tried a whole bunch of other stuff that plain gave me errors so i do not think i can solve this myself and googling the matter did not help at all please help thank you i am running leopard,"['ruby-on-rails', 'ruby']" +156652,vc error when using a pointer to a template function i am trying to write a template callback function for libcurl however when using a pointer to an instance of the template function vc 2008 and 2010 keep giving me this errortemplatecallbackcpp27 error c2664 curl easy setopt cannot convert parameter 3 from size t cdecl void size tsize tvoid to context does not allow for thisambiguation of overloaded functionbut gcc 451 compiles the code without a problem this is a trimmed version of the codeinclude stringtemplatetypename stringsize t callback void ptr size t size size t nmemb void userdata string str static caststringuserdata size t len sizenmemb strappendstatic castchar constptr len return lentypedef size t write callbackvoid size t size t voidstruct curlenum curloption none void curl easy setoptcurl curloption void f curl curl null curloption option none this gives an error curl easy setoptcurl option callbackstdstring this does not write callback cb callbackstdstring curl easy setoptcurl option cbis this a bug in vc or am i doing something wrong,['c++'] +156654,best way to preload images whats the best way to preload images i am trying to create an image tab that has around 59 png images heres the code i have so fardoctype html public w3cdtd html 401 frameseten html head titlechecklisttitle meta httpequivcontenttype contenttexthtml charsetutf8 link relstylesheet typetextcss hrefsystems hrstyle20libraryglobalstyles testcss style typetextcss innerframe width 100 height 63em style script typetextjavascript srcsystems hrstyle20libraryjavascriptsstylesjsscript script typetextjavascript srcscript script typetextjavascript srcscript script typetextjavascript var id1 new image id1src imagesid1png var id11 new image id11src imagesid11png var id12 new image id12src imagesid12png var id13 new image id13src imagesid13png var id2 new image id2src imagesid2png var id21 new image id21src imagesid21png var id22 new image id22src imagesid22png var id23 new image id23src imagesid23png var id3 new image id3src imagesid3png var id31 new image id31src imagesid31png var id32 new image id32src imagesid32png var id33 new image id33src imagesid33png var id4 new image id4src imagesid4png var id41 new image id41src imagesid41png var id42 new image id42src imagesid42png var id43 new image id43src imagesid43png var iw1 new image iw1src imagesiw1png var iw11 new image iw11src imagesiw11png var iw12 new image iw12src imagesiw12png var iw13 new image iw13src imagesiw13png var iw14 new image iw14src imagesiw14png var iw2 new image iw2src imagesiw2png var iw21 new image iw21src imagesiw21png var iw22 new image iw22src imagesiw22png var iw23 new image iw23src imagesiw23png var iw24 new image iw24src imagesiw24png var iw3 new image iw3src imagesiw3png var iw31 new image iw31src imagesiw31png var iw32 new image iw32src imagesiw32png var iw33 new image iw33src imagesiw33png var iw34 new image iw34src imagesiw34png var iw4 new image iw4src imagesiw4png var iw41 new image iw41src imagesiw41png var iw42 new image iw42src imagesiw42png var iw43 new image iw43src imagesiw43png var iw44 new image iw44src imagesiw44png var im1 new image im1src imagesim1png var im11 new image im11src imagesim11png var im12 new image im12src imagesim12png var im13 new image im13src imagesim13png var im2 new image im2src imagesim2png var im21 new image im21src imagesim21png var im22 new image im22src imagesim22png var im23 new image im23src imagesim23png var im3 new image im3src imagesim3png var im31 new image im31src imagesim31png var im32 new image im32src imagesim32png var im33 new image im33src imagesim33png function changeframe framesrc var myframe documentgetelementbyidfracontent myframecontentwindowlocation framesrc function rolloverareaarea orgimgsrc tgtimgsrc orgcursor tgtcursor jquery script for rollover effect imgtabattrsrc orgimgsrc areahover function imgtabattrsrc tgtimgsrc imgtabcsscursortgtcursor function imgtabattrsrc orgimgsrc imgtabcsscursororgcursor function initload function changeimgstateimg tab interface of day week and month arrows var myimgtab documentgetelementbyidimgtab switch img case id1 myimgtabsrc id1src rollover effect for the image rolloverareaarea1id1srcid1srcautoauto rolloverareaarea2id1srcid11srcautopointer rolloverareaarea3id1srcid12srcautopointer rolloverareaarea4id1srcid13srcautopointer rolloverareaarea5id1srcid1srcautoauto onclick effect area2clickfunction innerframeattrsrcd2html changeimgstateid2 area3clickfunction innerframeattrsrcd3html changeimgstateid3 area4clickfunction innerframeattrsrcd4html changeimgstateid4 break case id2 myimgtabsrc id2src rollover effect for the image rolloverareaarea1id2srcid21srcautopointer rolloverareaarea2id2srcid2srcautoauto rolloverareaarea3id2srcid22srcautopointer rolloverareaarea4id2srcid23srcautopointer rolloverareaarea5id2srcid2srcautoauto onclick effect area1clickfunction innerframeattrsrcd1html changeimgstateid1 area3clickfunction innerframeattrsrcd3html changeimgstateid3 area4clickfunction innerframeattrsrcd4html changeimgstateid4 break case id3 myimgtabsrc id3src rollover effect for the image rolloverareaarea1id3srcid31srcautopointer rolloverareaarea2id3srcid32srcautopointer rolloverareaarea3id3srcid3srcautoauto rolloverareaarea4id3srcid33srcautopointer rolloverareaarea5id3srcid3srcautoauto onclick effect area1clickfunction innerframeattrsrcd1html changeimgstateid3 area2clickfunction innerframeattrsrcd2html changeimgstateid2 area4clickfunction innerframeattrsrcd4html changeimgstateid4 break case id4 myimgtabsrc id4src rollover effect for the image rolloverareaarea1id4srcid41srcautopointer rolloverareaarea2id4srcid42srcautopointer rolloverareaarea3id4srcid43srcautopointer rolloverareaarea4id4srcid4srcautoauto rolloverareaarea5id4srcid4srcautoauto onclick effect area1clickfunction innerframeattrsrcd1html changeimgstateid3 area2clickfunction innerframeattrsrcd2html changeimgstateid2 area4clickfunction innerframeattrsrcd4html changeimgstateid4 break case iw1 myimgtabsrc iw1src rolloverareaarea1iw1srciw1srcautoauto rolloverareaarea2iw1srciw11srcautopointer rolloverareaarea3iw1srciw12srcautopointer rolloverareaarea4iw1srciw13srcautopointer rolloverareaarea5iw1srciw14srcautopointer break case im1 myimgtabsrc im1src rolloverareaarea1im1srcim1srcautoauto rolloverareaarea2im1srcim11srcautopointer rolloverareaarea3im1srcim12srcautopointer rolloverareaarea4im1srcim13srcautopointer rolloverareaarea5im1srcim1srcautoauto break function changetabtab switchtab case day1 var mytab documentgetelementbyidday1 documentgetelementbyidweek1classname active documentgetelementbyidmonth1classname active mytabclassname current changeimgstateid1 innerframeattrsrcd1html break case week1 documentgetelementbyidday1classname active documentgetelementbyidmonth1classname active documentgetelementbyidweek1classname current changeimgstateiw1 innerframeattrsrcw1html break case month1 documentgetelementbyidweek1classname active documentgetelementbyidday1classname active documentgetelementbyidmonth1classname current changeimgstateim1 innerframeattrsrcm1html break function testtab alertdocumentgetelementbyidid documentgetelementbyidtabclassname script head body onloadchangetabday1 table border0 width100 tr td colspan2 alignleft div idnavcontainer ul idnavlist lia classactive idday1 onclickchangetabday1first dayali lia classactive idweek1 onclickchangetabweek1first weekali lia classactive idmonth1 onclickchangetabmonth1first 30daysali ul div div idpage viewer table border0 width1020px cellpadding0 cellspacing0 tr td img src styleborder 0px width 10px height 72px alt usemapimgtabmap nameimgtab idimgtab map idimgtabmap nameimgtabmap area shaperect alt title coords7160 idarea1 area shaperect alt title coords2061036559 idarea2 area shaperect alt title coords4051156659 idarea3 area shaperect alt title coords6051076360 idarea4 area shaperect alt title coords805996360 idarea5 created by online image map editor map td tr tr td width100 iframe namefracontent idinnerframe frameborder0 scrollingno width10pxiframe td tr table div td tr table bodyhtmlthe thing is now my page takes a while to load and i cannot figure out why clicking on a tab seems to load the iframe slowly does loading the src of the iframe cause the images to be preloaded again would it be better to load the relevant images onclick instead of having them all load when the page opensi also found a good alternative in the form of lieldulevs parallel loading script imagesqueue but i do not know how to use itbtw i am not wellversed in javascript so i am trying to learn as i work right now what i am doing is implementing techniques that i research and trying to understand their functions hence the reason why my coding is not as clean as i would like it to be sometimes even just using inefficient brute force codes to get the desired effect i would like to improve on that though and any help would be appreciatedregarding the parallel cache script heres a test page i set up patterned after nicks demo html head titleliels smij dev pagetitle style typetextcss m1 width400px height300px backgroundcoloradf canvas width100 height100 show mefloatleftwidth100px console logfontsize10pxfloatright style script typetextjavascript srcsystems hrstyle20libraryjavascriptsimagesqueuejsscript head body h1imagesqueuejs demoh1 img idshow me srcimagesid1png img idshow me alt div idconsole loglogdiv script typetextjavascript imagesqueue usage example the img element to show show img documentgetelementbyidshow me log e documentgetelementbyidconsole log log functionoutputlog einnerhtml broutput imagesqueue imagesq on every image loaded show progress imagesqueueonloaded function show imgsrc imagesqueuecurrentsrc var output q1 imagesqueueimageslengthimagesqueueqlength imagesqueuecurrentsrc loaded onloaded logoutput when done say so imagesqueueoncomplete function queuescompleteall logq1 queued 10 images queue images var now new dategettime make sure to get noncached images imagesqueuequeue imagesimagesid1pngnow imagesid11pngnow imagesid12pngnow imagesid13pngnow imagesid2pngnow imagesid21pngnow imagesid22pngnow imagesid23pngnow imagesid3pngnow imagesid31pngnow logstarting the queue process queue var start new dategettime imagesqueueprocess queue logthis is the next line in the code after process queue to avoid this you should design create a function for the rest of your code and call it upon oncomplete function queuescompleteall var diff new dategettime start logall done diffms script body htmlat the moment i could not get it to work i uploaded the imagesqueue script and linked it to the page and replaced the image values from the original demo page to whats in my development site,"['javascript', 'jquery']" +156655,set a menu item as checked from code i have an android application with the following menu item in one of the activities which concerns handling a list of names and mac numbersitem androidididmenu sort tagg androidiconandroiddrawableic menu sort by size androidtitlestringmenu sort list menu group androidcheckablebehaviorsingle item androidididsort by name androidtitlestringsort by name item androidididsort by mac androidtitlestringsort by mac menuitemand as the application state changes i want to be able to precheck which item in the sort options list that was used last time with the following codemenuitemfindviewbyidridsort by namesetcheckedtruethe problem is that this specific line gives me a runtime exception does anyone have a clue why a look at the log reveals that the runtime exceptions is triggered by a null pointer exception by changing the code in this waymenuitem mi menuitemfindviewbyidridsort by namemisetcheckedtrueit becomes clear that the exception occurs in the seconds statement ie the menuitem mi is null so why fails the first statement to bring a pointer to the correct menuitem,['android'] +156662,get the iso 8601 with secondsdecimalfractionofsecond date in php i echo this php echo dateymdthis 20110527t112123how can do with date function to get this date format20110112t14413570422520100 for example357042252 secondsdecimalfractionofsecondi have triedphp function gettimestamp return dateymdthis substrstringmicrotime 1 8 php echo gettimestamp20110527t1534356688370 missing 0100 how can i do,['php'] +156667,whats your naming convention for the view ids i believe that many of us were bothered while naming the view ids unlike the package mechanism the ids of the resources in a project are using one common namespace therefore we have to figure out some ways to name the fields with the same functionality but in different layout filesmy way is to add the noun or the verb that the layout files acitvity class name used in the front of the original id separated by a dot for examplean id originally named description in a activity thisplaying a movies information may become moviedetailsdescriptionis there any better ideas,['android'] +156692,onfling in a listview get the swiped item info i would like to have in my app the same behaviour of native contacts app specifically i would like to implement the swipe right for call and the swipe left for the textmsgi have a listview i setted the arrayadapter and iva implemented the gesture detector for the onflingmethodi correctly intercept the swipe side and i can lauch the call appi need to put the item number and other info to the intent so i need to get the swiped item here my code public class contacts extends activity implements ongesturelistener private static final string tag contacts arraylist contactinfo mdata private static final int swipe min thistance 120 private static final int swipe max off path 250 private static final int swipe threshold velocity 200 called when the activity is first created private gesturedetector detector new gesturedetectorthis button btncontacts button btnprofile button btnsettings imagebutton btnstatus handleserver cubeserver button slidehandlebutton slidingdrawer slidingdrawer string filter n arrayadapter contactinfo adapter listview listview public boolean oncreateoptionsmenumenu menu return true public boolean onoptionsitemselectedmenuitem item return true public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutcontact listview listview findviewbyidridarraylist listviewsetcachecolorhintrcolorwhite mdata getcontact adapter new arrayadapter contactinfo thisgetapplicationcontext rlayoutrow ridnome mdata public view getviewfinal int position view convertview viewgroup parent viewholder viewholder null if convertview null layoutinflater inflater layoutinflater getsystemservicecontextlayout inflater service convertview inflaterinflaterlayoutrow null viewholder new viewholder final contactinfo item getitemposition viewholdernamesettextitemgetname convertviewsetclickabletrue onclicklistener myclicklistener new onclicklistener public void onclickview v intent intent new intentvgetcontext contacttabsclass intentaddflagsintentflag activity new task logitagid valueitemgetid intentputextraid itemgetid intentputextraname itemgetname aggiungi quello che serve per gli extra ed i task intentputextracalendar itemgetcalendardraw intentputextragmail itemgetgmaildraw intentputextraoperator itemgetoperatordraw intentputextraimgstatus itemgetimgstatusdraw startactivityintent convertviewsetonclicklistenermyclicklistener convertviewsetontouchlistenernew ontouchlistener public boolean ontouchview view motionevent e detectorontouchevente return false return convertview listviewsetadapteradapter public boolean ondownmotionevent e todo autogenerated method stub return false public boolean onflingmotionevent e1 motionevent e2 float velocityx float velocityy try if mathabse1gety e2gety swipe max off path return false right to left swipe if e1getx e2getx swipe min thistance mathabsvelocityx swipe threshold velocity callnativeapp cna new callnativeappgetapplicationcontext cnasendsms1 toastmaketextgetapplicationcontext left swipe toastlength shortshow else if e2getx e1getx swipe min thistance mathabsvelocityx swipe threshold velocity callnativeapp cna new callnativeappgetapplicationcontext cnacall1 toastmaketextgetapplicationcontext right swipe toastlength shortshow catch exception e nothing return true public void onlongpressmotionevent e todo autogenerated method stub public boolean onscrollmotionevent e1 motionevent e2 float thistancex float thistancey todo autogenerated method stub return true public void onshowpressmotionevent e todo autogenerated method stub public boolean onsingletapupmotionevent e todo autogenerated method stub return true,['android'] +156742,how to convert a simple array to an associative array what is the fastest way to convert a simple array to an associative array in php so that values can be checked in the issetarrayvalueie fastest way to do the following conversionarray array1 2 3 4 5assoc arrayforeach array as i value assocvalue 1,['php'] +156746,execute wkhtmltopdf from php i have this working fine from linux command linewkhtmltopdf entryhtml outputpdfbut the following does not work from php codeexec wkhtmltopdf entryhtml outputpdfinteresting i have googled and a lot of nonchecked solutions and with no explanation why this is a problemthanks if you have the good ones,['php'] +156749,ios how do i generate 8 unique random integers i need to generate 8 random integers but they need to be unique aka not repeatedfor example i want 8 numbers within the range 1 to 8i have seen arc4random but i am not sure how to make them unique solutionnsmutablearray getrandomintsintamount fromintfromint tointtoint if toint fromint 1 amount return nil nsmutablearray uniquenumbers nsmutablearray alloc init autorelease int r while uniquenumbers count amount r arc4random toint fromint if uniquenumbers containsobjectnsnumber numberwithintr uniquenumbers addobjectnsnumber numberwithintr return uniquenumbers,"['iphone', 'objective-c', 'ios']" +156750,hbase client connectionloss for hbase error i am going completely crazy installed hadoophbase all is running optjdk160 24binjps23261 thriftserver22582 quorumpeermain21969 namenode23500 jps23021 hregionserver211 tasktracker22891 hmaster22117 secondarynamenode21779 datanode22370 main22704 jobtrackerpseudo thistributed environment hbase shell is working and coming up with correct results running list andhbase shellhbase shell enter helpreturn for list of supported commandstype exitreturn to leave the hbase shellversion 0901cdh3u0 r fri mar 25 161051 pdt 2011hbasemain0010 status1 servers 0 dead 80 average loadwhen connecting via ruby thrift everything is working fine we are adding data it is getting in the system we can queryscan it everything seems fine however when connecting with javagroovy import orgapachehadoophbasehbaseconfiguration groovy import orgapachehadoophbaseclienthbaseadmin groovy conf hbaseconfigurationcreate groovy confsethbasemaster12700160 groovy hbase new hbaseadminconf exception thrownorgapachehadoophbasezookeeperconnectionexception orgapachehadoophbasezookeeperconnectionexception orgapachezookeeperkeeperexceptionconnectionlossexception keepererrorcode connectionloss for hbase at orgapachehadoophbaseclienthconnectionmanagerhconnectionimplementationgetzookeeperwatcherhconnectionmanagerjava10 at orgapachehadoophbaseclienthconnectionmanagerhconnectionimplementationsetupzookeepertrackershconnectionmanagerjava303 at orgapachehadoophbaseclienthconnectionmanagerhconnectionimplementationinithconnectionmanagerjava294 at orgapachehadoophbaseclienthconnectionmanagergetconnectionhconnectionmanagerjava156 at orgapachehadoophbaseclienthbaseadmininithbaseadminjava84i have been trying to find the cause but i really have no clue at all everything seems to be correctly installed netstat lnpgrep 60tcp6 0 0 60 listen 22891java looks fine as well telnet localhost 60trying 127001connected to localhostescape character is connects and dies if you type anything enter not sure if that is the idea thrift on 9090 does the same can anyone help me,"['java', 'ruby']" +156755,django pre save signal does not work i tested the pre save signal of django in the following ways but cannot catch the signal in either of them from djangodbmodelssignals import pre saveimport loggingdef my callbacksender kwargs loggingdebugpre saveconnectmy callbackrun the above code in managepy shellthen i run my website and see modelssave work successfully but the callback function does not runalternatively i run the above code on shell again and then run modelssave in the shell save works well again but still nothing happens to the callback functionfinally i embed the above code in an init py file and still run the save function on the website still nothing occurswould you please help me figure out why pre save signal seems not work,['python'] +156759,in python how can i detect whether the computer is on battery power i am playing around with pygame and one thing i would like to do is reduce the number of frames per second when the computer is on battery power to lower the cpu usage and extend battery lifehow can i detect from python whether the computer is currently on battery poweri am using python 31 on windows,['python'] +156761,i want to apply an existing css style to all labels on a page how note this is different than the older question how can i apply css on all buttons which are present in that page because this is an already existing style so given that a style which well call standard label style already exists in an included css file what can i do to say that all the labels on this page should have that style short of addingclastandard label styleto each and every one and yes i know i could apply the styles expostfacto with a snippet of jquery or javascript code i am just trying to learn how i am supposed to do it with cssfollow upi have gotten several comments that say just use syntax like this standard label style label unfortunately that does nothing like what i want that would allow me to apply additional rules to the standard label style class as well as rules to labels within this page but would not allow me to apply that style to all the labels on this page to see an example of this here is a stylesheet and html to demonstrate the label without a class will still not appear in red but that is what i am hoping to have happen i want to apply an existing class to all those labels on the page not just the one with the class and without adding new styling on this page the existing style should be the only styleincludedcstandard label style color red testhtmlhtml head link relstylesheet typetextcss hrefincludedcss style standard label style label style head body label clastandard label styletest labellabelbr labelunclassed test labellabel bodyhtml,"['html', 'css']" +156766,access thisplayname in xaml how can i access thisplaynames value in xamli have gotpublic class viewmodel thisplaynamemy simple property public string property get return property xamltextblock textbinding propertythisplaynametextblock textbinding propertyis there any way to bind thisplayname in such or simmilar way the best idea will be to use this thisplayname as key to resources and present something from resources,['c#'] +156778,android move object along a path i ave created a path a circle and thisplayed both of them on screen as followspublic void ondrawcanvas canvas path spath new path spathmoveto100 100 spathlineto300 100 spathlineto300 300 spathlineto100300 spathlineto100100 spathclose paint ballpaint new paint ballpaintsetcolorcolorgreen paint pathpaint new paint pathpaintsetcolorcolorblue canvasdrawpathspath ballpaint canvasdrawcircle10010020pathpaint i would like to have the circle move along the path how can i do this,['android'] +156779,how do i mimic hybridurlcodingstrategy in wicket 15 we have an existing java wicket 14 application which uses the hybridurlcodingstrategy extensivelymountnew hybridurlcodingstrategymyurl mypageclassthis results in our urls looking likehttphostmyurlparamname1paramvalue1paramname2paramvalue2i would like to maintain this url format in wicket 15 however the hybridurlcodingstrategy has been removed in wicket 15 pages are mounted asmountpagemyurl mypageclasswhich results in traditional urls likehttphostmyurlparamname1paramvalue2paramname2paramvalue2i have read that we should be using the mountedmapper class but looking at the wicket 15 examples api docs and source code it is still not clear to me how to get the same behavior with mountedmapper as we are getting with the hybridurlcodingstrategydoes anyone know how to do this,['java'] +156789,sqlite multiprimary key on a table one of them is auto increment i have multiple composite primary keys on a table and one of them will be auto increment however interestingly sqlite allows usage of autoincrement keyword just after an obligatory primary key keywordmy query iscreate table ticket id integer primary key autoincrement seat text payment integer primary key id seathowever the error is table ticket has more than one primary keyactually i can avoid other primary keys for this table but i am coding an orm framework hell yeah i am crazy and do not want to change structure of primary key constraint generation for a table because it is allowed in mysql afaikdo you know any solution,['sql'] +156814,how to force jsonlibs jsonobjectput to escape a string containing json when using jsonlibs jsonobject how can i stop the put method from storing a string which contains json as json rather than as an escaped stringfor instancejsonobject obj new jsonobjectobjputjsonstringvaluehelloworldobjputnaturalstringvalue hello worldsystemoutprintlnobjtostringsystemoutprintlnobjgetstringjsonstringvaluesystemoutprintlnobjgetstringnaturalstringvalueprintsjsonstringvaluehelloworldnaturalstringvaluehello worldhelloworldhello worldand i want it to printjsonstringvaluehelloworldnaturalstringvaluehello worldhelloworldhello worldyes i realize this is obnoxious however this is in support of a json serialization pipeline for which for interoperabilitys sake this is the expected behavior there are cases in which we would be serializing user input which may becontain valid json we wouldnt want the user input to become a part of the json object that were serializing said input tomanual escaping does not work because it causes jsonlib to escape the charactersjsonobject obj new jsonobjectobjputnaturaljsonvaluehelloworldobjputescapedjsonvalue helloworldsystemoutprintlnobjtostringsystemoutprintlnobjgetstringnaturaljsonvaluesystemoutprintlnobjgetstringescapedjsonvalueoutputnaturaljsonvaluehelloworldescapedjsonvaluehelloworldhelloworldhelloworldat this point any workarounds to enable manual selective escaping of a complex json object would completely negate the value of using jsonlib in the first placealso i understand that this question has been asked before but unfortunately i cannot accept its answer so easily jsonlib is a heavilyused dependency in many areas of my project and swapping it out would be a big undertaking i need to be absolutely sure that there is no way to achieve this goal with jsonlib before i can entertain a swap to jackson simplejson or gson,['java'] +156826,why list implements ilist possible duplicatewhy does does it really list implement all these interfaces not just ilist out of curiosity what is the reason behind generic list implementing nongeneric interface ilist sample codeilistint list new listintlistadd1compiles but argumentexception thrown at run timeilistlistaddnew object,"['c#', '.net']" +156838,jquery setting an elements text only without removing other element anchor i have an element like thistd aanchora some text tdand i need to set it is text in jquery without removing the anchorthe elements contents could vary in order text before or after and the actual text is unknownthanksnew updatethis is what i came up using assumes only a single text node function settextcontentselem text elemcontentsfilterfunction if thisnodetype nodetext node thisnodevalue text settextcontents td new text,"['javascript', 'jquery']" +156840,replacing the wpf entry point wpf defines its own main method how should i go about replacing it with my own main method that normally opens the wpf mainwindow eg to add a nonwpf scripting mode via commandline arguments,['.net'] +156854,how to copy protect phonegap android app is android market copy protect feature useful i have phonegap app in android now i am ready to publish it but i would like to protect the app from eyes of scriptkiddies i first thought that it is impossible than i have thiscovered copy protection feature when publishing the app on the market so i was excited but when i turned it on it did not actually does nothingi can install the app on the rooted phone with no problem i can copy it on sd card and see all the sources i thought that this copy protection feature will not allow people with rooted phones to install the app or am i missing something is there any way how to make it at least difficult if not thisable it at all for people to see all my html and js sources in my app,['android'] +156867,signed division with unsigned numerator i am trying to calculate a rolling average and to try and get and optimize a bit i have simplified the calculation so there is only one division when the value is decreasing there is a point where the current value is lowered to less than the average at this point the average jumps i imagine this is because the division is unsigned and my numerators sign bit is interpreted as a massive unsigned number i am just not sure where i need to cast unsigned to insure this problem does not reappearunsigned int averageusageunsigned int totalusageunsigned int inccount averageusage totalusage averageusageinccount averageusageaverageusage will always be positive but when totalusage drops below averageusage i am not sure what to expect with the division averageusage signed inttotalusage averageusageinccount averageusagewill set the numerator to signed but i am not sure how the division will occur averageusage signed intsigned inttotalusage averageusageinccount averageusageshould work i can guarantee the result of this full operation will never be negative but i am worried about cases when inccount reaches a value that looks negativeis there a simple solution to this that hopefullydoes not need an if statementdoes not require qwordsthanks,['c'] +156870,what is the difference between a pkcs12 keystore and a pkcs11 keystore i am interested in javanss libraries and i am reading the suns p11 guidei am confused on the followingwhat is the difference between using a pkcs12 keystore and a pkcs11 keystorea keystore is just a keystore right are there some differences can they be used interchangeably in any aspect,['java'] +156879,rails orm for cassandra this question may have been asked many times but could not find any suitable answer is there any orm on rails3 for cassandrai have searched google and found followingfaunacassandra cassandra client for railscarbonfiveactive column last updated 13may2011winebarrelactiverecordcassandraadapter last updated 5 months agoscrum8cassandrb last updated 01mar2011nzkozcassandra object last updated 30may2010astrailssmallrecord last updated 14apr2010azatiactivecassandra last updated 03jun2010please help me out in deciding which one i should go withthanks,['ruby-on-rails'] +156906,recursive friend classes is there any way around thisclass bclass c public c private int i friend bbclass b public b private int i friend ccgives errorprogcpp8 error invalid use of incomplete type astruct baprogcpp1 error forward declaration of astruct ba,['c++'] +156930,spring mvc ajax how to thisplay errors my spring web application is using ajax with spring and it based in general on the demo application provided by springadditional info on the clientside i have a form jspformform modelattributecreatelevel actioncreatelevel methodpost div classformitem formlabel idnamelabel forname pathname csserrorclasserrorlevel nameformlabelbr forminput pathname formerrors pathname div div classformitem input typesubmit valuesubmit div formformi submit the form to the server by the following js methodcreatelevelsubmitfunction var level thisserializeobject postjsoncreatedo level functiondata alertdata return false on the serverside i have a validation as it shown belowpublic final class leveldto extends abstractdto implements serializable private static final long serialversionuid 1l private int id notnull sizemin 2 max 30 levelexistsconstraintmessage level with provided name is exists private string name set getand controller requestmappingvalue admincreatedo method requestmethodpost public responsebodymapstring extends object createlevelrequestbody leveldto level httpservletresponse response jsr303 setconstraintviolationleveldto failures validatorvalidatelevel if failuresisempty responsesetstatushttpservletresponsesc bad request return validationmessagesfailures else return collectionssingletonmapid 10 when i submit incorrect data to the server i see that all things are going on correctly my validator is processing data and the client is receiving an error response moreover in the response content i see the followingnamesize must be between 2 and 30my problem is that i do not know how to bind received error message correctly obviously i can do it by js but i thought that spring is binding all error messages automatically to the view any help is really appreciatedcyril,['java'] +156940,correct way to write line to file in python i am used to doing print f hi therehowever it seems that print is getting deprecated what is the recommended way to do the line aboveupdateregarding all those answers with nis this universal or unixspecific ie should i be doing rn on windows,['python'] +156950,c how to control chrome browser i wanted to make an application wherein you specify the name of the websites your username and password and that application automatically logs in to all your accounts in the specified websites i have done this using windows form application using a web browser but i wanted my application to open all these websites in chrome and log it in there plz help,['c#'] +156958,consistent random ordering in a mysql query i have a database of pictures and i want to let visitors browse the pictures i have one next and one previous link but what i want is to show every visitor anther order of the pictures how can i do that if i will use order by random i will show sometimes duplicate imagescan someone help me please thank you,['mysql'] +156971,what is the order of dictionaryvaluestoarray if i am adding values to a dictionary and then later in the code somewhere i want to convert that dictionary to an array usingmydictionaryvaluestoarraywill the array come out in the order i entered it or is it sorted at some stage,['c#'] +156977,raw sql query with zend framework is there a way to execute a sql string as a query in zend frameworki have a string like thatsql select from testtable where mycolumn 5now i want to execute this string directly withput parsing it and creating a zend db table select object from it by hand or if thats possible create a zend db table select object from this string to execute that objecthow can i do that i did not find a solution for this in the zend doc,"['php', 'mysql', 'sql']" +156979,starting windows service automatically at windows startup that is dependent on oracle i have developed a windows service that must start automatically during windows startup this service connects to an oracle db so i made my service dependent on oracle services by sc command line utilitysc config myservice depend oracleservicexeoraclexetnslistenerso far so good dependency was set succesfully but when windows starting my service could not start i get the following oracle error message ora12528 tnslistener all appropriate instances are blocking new connectionsas i think the oracle services are started when my service starts but they are not fully initialized after some seconds i can start my service from service consol without any problemso how can i start automatically my service at windows startup which is dependent on an oracle db connectionmy service was developed in c on net 4 platform in vs 2010 environmentpls help me it is a really important task form me,['c#'] +156984,illegalaccessexception when using call dynamic methods i am trying to use reflection in java but i am getting a weird error what are the possible issues when i get an error that saysjavalangillegalaccessexception class commyappcoreutilseventthispatcher can not access a member of class appapp1 with modifiers publicat sunreflectreflectionensurememberaccessunknown sourceat javalangreflectmethodinvokeunknown sourcei just trying to create my own eventthispatcher class and inside it the part that i used reflection which is also the line of code that causes the problem ispublic void thispatcheventevent e string callmethname ieventlistener list ieventlistenerlistenersi listgetclassgetmethodcallmethname eventclassinvokelist eon my main class i have something that calls addlistener which will just add the listener into a list in the eventthispatcher class this waytry objaddlistenerontesthandler new mytesteventlistener override public void ontesthandlerevent e systemoutprintlnhello catch securityexception e eprintstacktraceso the first parameter that says ontesthandler will pass into the eventthispatcher class and eventually as part of the parameter callmethname in the thispatchevent method which will call the method dynamicallythe passing of methods and everything is correct it is the part that has the reflection somehow has problems it seems to be able to find the method but for some reason throws an illegalaccessexception and cannot call the methodwhy is it like thisthanks,['java'] +156992,jquery mobile add the home screen options i know that there is no way of auto adding the jquery mobile app to the home screeni have read that the best way is to detect if the app is in full screen and if not give instructions how would i do thiswhat are the cross browser options available and are there any tutorials samples anywherecan anyone put some light on this pleasethanks,"['html', 'css']" +157000,whats the scope for objective c category if i override a method in a category will it just affect the files including it or it affects the whole project i want to override methodsignatureforselector and forwardinvocation to ignore the undefined selector error for nsnull so i want to know if this affects just the files including it thanks in advance,"['objective-c', 'ios']" +157003,how to find out the time spent inside a php script i am executing a php script that takes about a minute to finish and although the default time limit is set to 30 seconds the script continues its execution after that limiti found out that the limit only affects the time that is spent inside the script itself and not the time spent in library functions like database queries etc is there a way to find out the time that is actually spent inside the script i tried to use getrusage but it does not seem to return the appropriate values for this problemexamplephptime microtimetruesleep100echo time microtimetrue timethe script waits for 100 seconds and does not terminate after the time limit of 30 secondsaccording to the documentation of set time limit the time that is spent inside the sleep function 100 seconds is not involved in the calculation of the execution time because it is an external library function,['php'] +157008,how do you split a javascript string by spaces and punctuation i have some random string for example hello my name is john i want that string split into an array like this hello my name is john i tried strsplitws g but it does not seem to work any ideas,['javascript'] +157019,strange behavior of copyinitialization does not call the copyconstructor i was reading the difference between directinitialization and copyinitialization a8512t xa directinitializationt y a copyinitializationwhat i understand from reading about copyinitialization is that it needs accessible nonexplicit copyconstructor or else the program wouldnt compile i verified it by writing the following codestruct a int i aint i ii stdcout aint i stdendl private aconst a a stdcout aconst a stdendl int main a a 10 error copyctor is privategcc gives an error ideone sayingprogcpp8 error aconst aa is privateso far everything is fine reaffirming what herb sutter sayscopy initialization means the object is initialized using the copy constructor after first calling a userdefined conversion if necessary and is equivalent to the form t t uafter that i made the copyctor accessible by commenting the private keyword now naturally i would expect the following to get printedaconst abut to my surprise it prints this instead ideoneaint iwhyalright i understand that first a temporary object of type a is created out of 10 which is int type by using aint i applying the conversion rule as its needed here a8514 and then it was supposed to call copyctor to initialize a but it did not why if an implementation is permitted to eliminate the need to call copyconstructor a8514 then why is it not accepting the code when the copyconstructor is declared private after all its not calling it its like a spoiled kid who first irritatingly asks for a specific toy and when you give him one the specific one he throws it away behind your back could this behavior be dangerous i mean i might do some other useful thing in the copyctor but if it does not call it then does it not alter the behavior of the program,['c++'] +157028,serverside browser detection nodejs most implementations i have seen are for browser detection on the client side i was just wondering if it was possible to do browser detection before sending any resources to the client thanks,['javascript'] +157029,how to detect whether uiswitch is onoff i am trying to detect when a uiswitch it on off hiboutlet uiswitch privateswitchproperty nonatomic retain iboutlet uiswitch privateswitchmsynthesize privateswitchprivateswitch uiswitch alloc inithowtothisplay no in my cellforrowsatindexpathuiswitch privateswitch uiswitch alloc initwithframecgrectmake199 8 0 0privateswitch addtargetself actionselectorswitchtoggled forcontrolevents uicontroleventtouchupinsidecellcontentview addsubviewprivateswitchif howtothisplay isequaltostringno privateswitch setonno animatedno else privateswitch setonyes animatedno void switchtoggledidsender if privateswitch ison nslogits onhowtothisplay yesformdatatwo removeallobjectsformtableview reloaddataprivateswitch setonyes animatedyes else nslogits offhowtothisplay noformdatatwo removeallobjectsformdatatwo addobjectfacebookformdatatwo addobjecttwitterformdatatwo addobjectflickrformdatatwo addobjecttumblrformdatatwo addobjectemailformdatatwo addobjectmmsformtableview reloaddataprivateswitch setonno animatedyeshowever when i switch it on it will say it is off what givesthanks,['objective-c'] +157045,set response status code i have an api call for which i need to be able to run some checks and potentially return various status codes i do not need custom views or anything i just need to return the proper code if the user has not passed proper credentials i need to return a 401 status if they have not sent a supported request format i need to return a 400 statusbecause it is an api all i really want to do is set the response status and exit with a simple stupid message about why the request failed probably using a exit just enough to get the job done but i have not been able to get this to work right i have tried using phps header and cakes thisheader this is all in the controller but although i get the exit message the header shows a 200 ok statususing the code below i get the message but the header is not set what am i missing if thisauth api header 401 not authorized exit not authorized,['php'] +157046,java random little change in seed causes only little change in output while making a map generator in java i found a rather unnerving problem with their random number generator to specify when two rngs have very similar seeds differing in small integers their first output value will become very similarexample coderandom r new randomlong and 10 choose any numberrsetseedn systemoutprintlnrnextintrsetseedn1systemoutprintlnrnextintthis pretty much broke my faith in the original java rng since i use coordinates to seed a map generatorcould someone suggest either a redefinition for the randomnextint bits method or some other fix for this problemthank you for your help,['java'] +157047,how can i create my own html tag how can i create my own html tags in html or html5 so i can make my own html tag and css librarysuch as mymenu ul li or some text mymenuheading yeah my own headingheadingis their a way to do that if yeah please tell me how i am really curious about it and tell me what problems should i will be having after making my personalize tags if you know any,['html'] +157051,mapreduce count example my question is about mapreduce programming in java suppose i have the wordcountjava example a standard mapreduce program i want the map function to collect some information and return to the reduce function maps formed like slavenode idsome info collectedso that i can know what slave node collected what data any idea how public class wordcount public static class map extends mapreducebase implements mapperlongwritable text text intwritable private final static intwritable one new intwritable1 private text word new text public void maplongwritable key text value outputcollectortext intwritable output reporter reporter throws ioexception string line valuetostring stringtokenizer tokenizer new stringtokenizerline while tokenizerhasmoretokens wordsettokenizernexttoken outputcollectword one public static class reduce extends mapreducebase implements reducertext intwritable text intwritable public void reducetext key iteratorintwritable values outputcollectortext intwritable output reporter reporter throws ioexception int sum 0 while valueshasnext sum valuesnextget outputcollectkey new intwritablesum public static void mainstring args throws exception jobconf conf new jobconfwordcountclass confsetjobnamewordcount confsetoutputkeyclasstextclass confsetoutputvalueclassintwritableclass confsetmapperclassmapclass confsetcombinerclassreduceclass confsetreducerclassreduceclass confsetinputformattextinputformatclass confsetoutputformattextoutputformatclass fileinputformatsetinputpathsconf new pathargs0 fileoutputformatsetoutputpathconf new pathargs1 jobclientrunjobconf thank you,['java'] +157052,why does not haskell have symbols a la ruby atoms a la erlang the two languages where i have used symbols are ruby and erlang and i have always found them to be extremely usefulhaskell does have algebraic datatypes but i still think symbols would be mighty convenient an immediate use that springs to mind is that since symbols are isomorphic to integers you can use them where you would use an integral or a string primary keythe syntactic sugar for atoms can be minor something or something is an atom all atoms are instances of a type called atom which derives show and eq you can then use it for more descriptive error codes for exampletype errorcode atomtype message stringdata error error errorcode messageloginerror error redirect please login firstin this case redirect is more efficient than using a string redirect and easier to understand than an integer 404the benefit may seem minor but i say it is worth adding atoms as a language feature or at least a ghc extensionso why have symbols not been added to the language or am i thinking about this the wrong way,['ruby'] +157055,check what version of the app is being used possible duplicatehow to thisplay the current project version of my app to the user is there a way to check the version number of my app is it supplied somewhere once the app is in the app store,"['objective-c', 'ios']" +157057,how to use edittextpreference as a masked password text field i have a very simple questioni have a edittextpreference dialog which i want to use for getting the users password and i want it to be maskedhow can i do that,['android'] +157059,getting two strings in variable from url in django i am having some trouble sending along more than one variable to the viewmy urlspy is as followsurlpatterns patterns urlrrsspanything rssrssamaviewsmakerss nameanything urlr rssrssamaviewshome viewspy def maakrssrequest anythingso now it takes from wmydomaincomrssanything and sends anything to my view however i also want it to send along another string to viewspy likewmydomaincomrssanynumberanystringi tried this but that did not work urlrrsspanynumberpanystring rssrssamaviewsmakerss nameanynumber name2anystringbut this does not work it gives this error keyword argument repeated urlspy line 17so my question how can i make it to give along two string from the url,['python'] +157066,why are unused variables bad i would like to know why an unused variable is badis it because the compiler would create a bigger binary if yes is there a toolscript wich can add an unused keyword or something like that,['c'] +157076,uiview how do i find the root superview fast i have a random child view in a view hierarchy what is the bestfastestcleverest way to get to the root superviewcheersdoug,['ios'] +157078,receiver not registered exception error in my developer console people keep reporting an error that i cannot reproduce on any phone i have one person left a message saying he gets it when they try to open the settings screen of my battery service as you can see from the error it says that the receiver is not registeredjavalangruntimeexception unable to stop service batteryservice4616d688 javalangillegalargumentexception receiver not registered comappnotifymebatteryservicebatterynotifyreceiver4616d9d0at androidappactivitythreadhandlestopserviceactivitythreadjava3164at androidappactivitythreadaccess3900activitythreadjava129at androidappactivitythreadhhandlemessageactivitythreadjava2173at androidoshandlerthispatchmessagehandlerjava99at androidoslooperlooplooperjava143at androidappactivitythreadmainactivitythreadjava4701at javalangreflectmethodinvokenativenative methodat javalangreflectmethodinvokemethodjava521at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava860at comandroidinternaloszygoteinitmainzygoteinitjava618at dalviksystemnativestartmainnative methodcaused by javalangillegalargumentexception receiver not registeredcombatteryservicebatterynotifyreceiver4616d9d0at androidappactivitythreadpackageinfoforgetreceiverthispatcheractivitythreadjava805at androidappcontextimplunregisterreceivercontextimpljava859at androidcontentcontextwrapperunregisterreceivercontextwrapperjava331at comappnotifymebatteryserviceondestroybatteryservicejava128at androidappactivitythreadhandlestopserviceactivitythreadjava3150i register is in my oncreateoverridepublic void oncreate superoncreate sharedpreferences pref preferencemanagergetdefaultsharedpreferencesthis intentfilter filter new intentfilterintentaction battery changed filteraddactionintentaction power connected filteraddactionintentaction power thisconnected registerreceiverbatterynotifyreceiverfilter prefregisteronsharedpreferencechangelistenerthisunregister in ondestroy and also with a preference listener overridepublic void ondestroy superondestroy unregisterreceiverbatterynotifyreceiverand this is my receiver in the serviceprivate final class batterynotifyreceiver extends broadcastreceiver boolean connected override public void onreceivecontext context intent intent sharedpreferences prefs preferencemanagergetdefaultsharedpreferencescontext sharedpreferenceseditor edit prefsedit updatepreferencesprefs level intentgetintextrabatterymanagerextra level 1 ifintentgetactionequalsintentaction power connected connected true else ifintentgetactionequalsintentaction power thisconnected connected false else ifintentgetactionequalsintentaction battery changed iflevel lastlevel iflevel 40 editputbooleanfirst falsecommit editputbooleansecond falsecommit editputbooleanthird falsecommit editputbooleanfourthfalsecommit editputbooleanfifth falsecommit iflevel 40 iffirst notificationcontextbattcolorbattblinkbattvibbattsound editputbooleanfirst truecommit else iflevel 30 ifsecond notificationcontextbattcolorbattblinkbattvibbattsound editputbooleansecond truecommit else iflevel 20 ifthird notificationcontextbattcolorbattblinkbattvibbattsound editputbooleanthird truecommit else iflevel 15 iffourth notificationcontextbattcolorbattblinkbattvibbattsound editputbooleanfourth truecommit else iflevel 5 iffifth notificationcontextbattcolorbattblinkbattvibbattsound editputbooleanfifth truecommit lastlevel temp intent i new intentcontextbatterynotifyreceiverclass contextstartservicei any idea why they would be getting that error,['android'] +157093,add query string as route value dictionary to actionlink i am trying to create an actionlink to export data from a grid the grid is filtered by values from the query string heres an example of the urldirectionascendingsearchnametextheres the code to add my actionlink to the pagehtmlactionlinkexport to excel link text export action name gridpage controller name requestquerystringtoroutedic route values new class export html attributeswhen the link is thisplayed the url is thiskeyssystemcollectionsgenericdictionary6022bkeycollection5bsystemstring2csystemobject5dvaluessystemcollectionsgenericdictionary6022bvaluecollection5bsystemstring2csystemobject5dwhat am i doing wrong,"['c#', 'asp.net']" +157101,how to do bundle install using specific rvm gemset from git hook postreceive so i am trying to implement a herokulike deployment without using capistranoto check and install gems i am trying to use git hook and put the following commands in hookspostreceivebundle check bundle installbut when i run git push i get remote hookspostreceive line 20 bundle command not found i understand that a hook probably launches commands from the wrong environment and somehow i have to switch rvm environment from hook i tried to use rvm use 187rails3 in postreceive but it did not help any ideas,"['ruby-on-rails', 'ruby']" +157118,google app engine go vs python recommendations i am looking into writing my first application of google app engine c is my native language and so writing the app in java would of course be most logical but i am a geek and would like to take to opportunity to learn something newtherefore its a tossup between python and go do you have a strong preference based on experience ideally in the context of writing on app engineif youve come from c or another similar language how was the transition,"['java', 'python']" +157127,compilation error undefined symbols on osx i am trying out a very simple cpp program on osx just to get myself familiar with the osx platform so i am very surprised to encounter any error messagehere is the codeinclude iostream using namespace std int main cout hello world endl return 0 i compile it by runninggcc wall hellocpp o hellothen i get this undefined symbols messageundefined symbols stdbasic ostreamchar stdchar traitschar stdoperator stdchar traitschar stdbasic ostreamchar stdchar traitschar char const referenced from main in cca9oelqo stdios baseinitinit referenced from static initialization and destruction 0int intin cca9oelqo stdbasic stringchar stdchar traitschar stdallocatorchar size const referenced from std verify groupingchar const unsigned long stdbasic stringchar stdchar traitschar stdallocatorchar constin cca9oelqo stdbasic stringchar stdchar traitschar stdallocatorchar operatorunsigned long const referenced from std verify groupingchar const unsigned long stdbasic stringchar stdchar traitschar stdallocatorchar constin cca9oelqo std verify groupingchar const unsigned long stdbasic stringchar stdchar traitschar stdallocatorchar constin cca9oelqo std verify groupingchar const unsigned long stdbasic stringchar stdchar traitschar stdallocatorchar constin cca9oelqo gxx personality v0 referenced from std verify groupingchar const unsigned long stdbasic stringchar stdchar traitschar stdallocatorchar constin cca9oelqo main in cca9oelqo tcf 0 in cca9oelqo unsigned long const stdminunsigned longunsigned long const unsigned long constin cca9oelqo static initialization and destruction 0int intin cca9oelqo global constructors keyed to mainin cca9oelqo cie in cca9oelqo stdios baseinitinit referenced from tcf 0 in cca9oelqo stdbasic ostreamchar stdchar traitschar stdendlchar stdchar traitschar stdbasic ostreamchar stdchar traitschar referenced from main in cca9oelqo stdbasic ostreamchar stdchar traitschar operatorstdbasic ostreamchar stdchar traitschar stdbasic ostreamchar stdchar traitschar referenced from main in cca9oelqo stdcout referenced from main in cca9oelqold symbols not foundcollect2 ld returned 1 exit statusi do not know if it is related i have both xcode 3 and xcode 4 installed on my mbphere is the version information gcc vusing builtin specstarget i686appledarwin10configured with vartmpgccgcc5636srcconfigure thisablechecking enablewerror prefixusr mandirshareman enablelanguagescobjccobjc programtransformnamecgs42 withslibdirusrlib buildi686appledarwin10 programprefixi686appledarwin10 hostx86 64appledarwin10 targeti686appledarwin10 withgxxincludedirincludec421thread model posixgcc version 421 apple inc build 56 dot 3system information uname adarwin mbp002local 1070 darwin kernel version 1070 sat jan 29 151716 pst 2011 rootxnu15049371release i386 i386,['c++'] +157162,how to parse a url if there is one thing i just cant get my head around it is regexso after a lot of searching i finally found this one that suits my needsfunction get domain name a a domain name parts amatch1split ifdomain name partslength 3 domain name parts0 var domain domain name partsjoin ifdomainindexof 0 alert1 domainsubstr1 else alert2 domain it basically gives me back the domain name is there anyway i can also get all the stuff after the domain name in this case it would be blahsdgsdgsdgs from the a variable,['javascript'] +157199,php json encode encode a function how to encode a javascript function in php i want to encode the callback function with arrayoptions arraytitle titlefncallback somecallbackequivalent ini javascriptvar options title titlefncallback somecallback i know my php code is wrong how can i fixed it thanks for advanced,"['php', 'javascript']" +157228,ruby setting env variables on a mac i would like to try an keep my development machine as close as the production server heroku in this caseheroku lets you define config vars ieconfigadd keyvalthis is now pretty secure as secret key values are not stored in my codedo you know how and where can i create such environment variables per app on my local mac machinei have googled this and as of yet not found a good solution any ideas thanks in advance,['ruby-on-rails'] +157241,building python and more on missing modules i have another thread asking help on missing zlib with the nice help the problem has been resolved almostnow i am interested in building python myself on ubuntu 1010a few important questions have caught my attentionafter building python say 271 do i need to rebuild python if i have missing modulesis there a way to find out what modules will be missing prior to building python say sqlite3 i have sqlite3 installed for the system default python 266 and i can import that into python 266 shell now i use pythonbrew to build 271 and in the shell i cannot import sqlite3 because sqlite3 is not available i am sure there are a few more important one missing which i need for future development such as django i am willing to learn how to build without using pythonbrew please share with me your experience in building another version of python and how would you address the problem of missing modules is there a practical solution to building pythoni have never bothered building one myself so please bear with me i am beginning to realize the importance of learning and building one myself thank you very mucheditfirst i thank you all of your inputs they meant a lot i did the building python build finished but the necessary bits to build these modules were not found bsddb curses curses panel tkinter bsddb185 bz2 dbm gdbm readline sunaudiodev sqlite3 to find the necessary bits look in setuppy in detect modules for the modules namei got sqlite3 and readline away bysudo aptget install libreadline6 libreadline6devsudo aptget install libsqlite3devi tried to import them but still no named module xat askubuntu i actually asked people how to get previous commands because i could not use that feature when i am in python 271 shell i believe it is due to readlinereadlinei installed the python271 under this directory homejwxie518python27i looked into setuppy i found the following lines the sqlite interfacesqlite setup debug false verbose debug prints from this script we hunt for define sqlite version n we need to find sqlite version 308sqlite incdir sqlite libdir nonesqlite inc paths usrinclude usrincludesqlite usrincludesqlite3 usrlocalinclude usrlocalincludesqlite usrlocalincludesqlite3 all the paths listed above do not exist so i guess i have to install sqlite3 manually i got another reference here it is in chinese however download the latest and extract go into the extracted directoryconfigure prefixhomejwxie518python27pythonmake make install then edit python27 s setuppy before rebuild it sample add these two lines to the endsharesoftwarepythonsqlite3620includesharesoftwarepythonsqlite3620includesqlite3 then rebuild python like how we did beforei went into my directory where i installed sqlite3 i found includesqlite3h only so i went back and check usrinclude i can only find sqlite3h tooso what is going on here readline is also nonimportable3rd editi started everything over except i did not reinstall sqlite3 extract python271 cd into python271 configuremake makeout 21less makeoutmakeout is here i still could not import sqlite3 so i went into setuppy and made changes we hunt for define sqlite version n we need to find sqlite version 308sqlite incdir sqlite libdir nonesqlite inc paths usrinclude usrincludesqlite usrincludesqlite3 usrlocalinclude usrlocalincludesqlite usrlocalincludesqlite3 homejwxie518pythonmodincludesqlite homejwxie518pythonmodincludesqlite3 then again ran everything over this time i also did make cleanoutput is here according to the output i do not think the custom path is included for complete output please go to the link above and search for sqlitebuildtemplinuxi68627homejwxie518python271modules sqliteutilo lusrlib lusrlocallib wlrusrlib lsqlite3 o buildliblinuxi68627 sqlite3soi still cannot import sqlite3thanksthank you very much michael dillon for helping me out your tutorial was neat and cleari solved the problem as soon as i realized whenever i tried python271 i was actually using the one installed by pythonbrew the moral of the story is read all the errors i neglected the errors generated by importing sqlite3 the one installed by pythonbrew did not have sqlite3 installed the development package for sqlite3 was installed after pythonbrew installed the python271thanks,['python'] +157244,how to pass data to running thread when using pthread i can pass data at thread creation timewhat is the proper way of passing new data to an already running threadi am considering making a global variable and make my thread read from thatthanks,"['c++', 'c']" +157245,what serious alternatives exist for the iostream library besides cstdio i am looking for a library which operates similar to iostreams in that it performs conversions and allows writing to memory buffers files and the console however i would like something type safe as iostream is are there any serious libraries which do thisbeing able to specify the output encoding for things would be a plusnote that i am not interested in libraries which simply front iostreams because they just add more complexity to what iostreams is doing eg boostformatpreemptive comment response i do not want to use cstdio because using that system it is impossible to have code be output location agnostic that is you have to call one function for sending things to buffers and you have to call another function to send things to files and another for the console etcedit2 in response to the flurry of comments below i am fed up with both iostreams and cstdio here are more specific reasons i tried to keep my rant out of this question but people keep asking my if i am off my rocker so heres my rationalecstdiocannot handle unicode characters correctlycannot write into something like a string without doing manual buffer managementoften requires support of nonstandard extensions eg vsnprintf in order to be usable edit okay c99s standard library being in c11 adds mostall of these nowcannot change the location of output without changing the original code nonstandard extensions eg in glibc allow you to treat a file pointer as a buffer which kind of does this but it is still just that a nonstandard extensionmakes security fun to the point where entire chapters are dedicated in security docs explaining issues eg with printfs format strings and suchnot type safeiostreamsslowentirely too complicated to a client if you use only what comes with the standard library it is great but attempting to extend things is next to impossible i read the entire standard c iostreams and locales book the only book seemingly available on the topic twice and i still do not know whats going oni love iostreams in concept even the use of operator which some people seem to not like but it seems entirely too over engineered to me someone should not have to spend countless hours reading books in order to be a simple client of your library sure if youre adding a new output source or something like that i could understand but clients should be shielded from that complexity is not that what a librarys forthis is about the only thing that is painful in c that just works in other programming languages that i see no reason to be complicated,['c++'] +157251,what does control reaches end of nonvoid function mean i have been getting strange compiler errors on this binary search algorithm i get a warning that control reaches end of nonvoid function what does this meanint binaryint val int sorted int low int high int mid lowhigh2 ifhigh low return 1 ifval sortedmid return binaryval sorted low mid1 else ifval sortedmid return binaryval sorted mid1 high else ifval sortedmid return mid,['c'] +157257,why is not operator overloading for pointers allowed to work as per the comment under this answer references were introduced primarily to support operator overloading which quotes bjarne stroustrupreferences were introduced primarily to support operator overloading c passes every function argument by value and where passing an object by value would be inefficient or inappropriate the user can pass a pointer this strategy doesnat work where operator overloading is used in that case notational convenience is essential so that a user cannot be expected to insert addressa of operators if the objects are largewhich implies that operator overloading cannot work with pointer but it does not clearly explain why operator overloading with pointers cannot work why wouldnt operator overloading work for pointersimo where references are used pointers can also be used in its place,['c++'] +157270,xml serializing a list of a base class i have class a inherits from class b i have a list of class b that contains a and b itemslistb mylist new listbmylistaddnew awhen i try to serialize this list using xmlserializable an exception is thrown if i define the list to of type b then i do not get this exception what is the best way to serialize the derived class,"['c#', '.net']" +157282,select more than one count in mysql is it possible in mysql to do something like thisselect count as totalcount count where foo is null as conditional count from bazie get two counts one of everything and one of things matching a where clause in a single select,"['mysql', 'sql']" +157298,how to hide a button programmatically i have a relativelayout which contains two buttons which are overlapped on each otherxml version10 encodingutf8relativelayout xmlnsandroid androidorientationvertical androidlayout widthfill parent androidlayout heightfill parent androidbackgroundfbutton androidtextplay androidididplay androidlayout widthfill parent androidlayout heightwrap content androidlayout alignparentbottom truebuttonbutton androidtextstop androidididstop androidlayout widthfill parent androidlayout heightwrap content androidlayout alignparentbottom truebuttonrelativelayouti want to programmatically show only one button at a time when its click event is calledi tried it with playbuttonsetvisibility1but it does not worked following is an example what i am trying to doplaybutton button findviewbyidridplayplaybuttonsetvisibility1playbuttonsetonclicklistenernew onclicklistener override public void onclickview v when play is clicked show stop button and hide play button,['android'] +157310,douglas crockfords javascript the good parts chapter 55 i was reading ch 55 of the book in title i have still have trouble in seeing how we can compose objects out of sets of parts using the eventuality function in the chapterare objects to be composed by a event system with the on and fire functions code from the section of the book belowvar eventuality function that var registry thatfire function event fire an event on an object the event can be either a string containing the name of the event or an object containing a type property containing the name of the event handlers registered by the on method that match the event name will be invoked var array func handler i type typeof event string event eventtype if an array of handlers exist for this event then loop through it and execute the handlers in order if registryhasownpropertytype array registrytype for i 0 i arraylength i 1 handler arrayi a handler record contains a method and an optional array of parameters if the method is a name look up the function func handlermethod if typeof func string func thisfunc invoke a handler if the record contained parameters then pass them otherwise pass the event object funcapplythis handlerparameters event return this thaton function type method parameters register an event make a handler record put it in a handler array making one if it does not yet exist for this type var handler method method parameters parameters if registryhasownpropertytype registrytypepushhandler else registrytype handler return this return that,['javascript'] +157312,when should i use unordered map and not stdmap i am wondering in which case i should use unordered map instead of stdmapi have to use unorderd map each time i do not pay attention of order of element in the map,['c++'] +157314,zlib compression using deflate and inflate classes in java i want trying to use the deflate and inflate classes in javautilzip for zlib compression i am able to compress the code using deflate but while decompressing i am having this error exception in thread main javautilzipdataformatexception unknown compression method at javautilzipinflaterinflatebytesnative method at javautilzipinflaterinflateinflaterjava238 at javautilzipinflaterinflateinflaterjava256 at zlibcompressionmainzlibcompressionjava53here is my code so far import javautilzipimport javaiopublic class zlibcompression param args public static void mainstring args throws ioexception dataformatexception todo autogenerated method stub string fname book1 filereader infile new filereaderfname bufferedreader in new bufferedreaderinfile fileoutputstream out new fileoutputstreambook1outdfl bufferedinputstream in new bufferedinputstreamnew fileinputstreamfilename deflater compress new deflater inflater decompress new inflater string readfile inreadline byte bx readfilegetbytes whilereadfilenull byte input readfilegetbytes byte compresseddata new byte1024 compresetinputinput compressfinish int compresslength compressdeflatecompresseddata 0 compresseddatalength systemoutprintlncompresseddata outwritecompresseddata 0 compresslength readfile inreadline file abc new filebook1outdfl inputstream is new fileinputstreambook1outdfl inflaterinputstream infl new inflaterinputstreamnew fileinputstreambook1outdfl new inflater fileoutputstream outfile new fileoutputstreamdecompressedtxt byte b new byte1024 whiletrue int a inflreadb01024 ifa0 break decompresetinputb byte fresult new byte1024 decompressin int reslength decompressinflatefresult outfilewriteb01 string outt new stringfresult 0 reslength systemoutprintlnoutt systemoutprintlncomplete,['java'] +157323,local inner class i have read through inner class tutorial and do not understand one thing it is being said that inner class holds hidden reference to outer class so i come up with several questions via this plain class public class outerclass public void dosomething jbutton button new jbutton buttonaddactionlistenernew actionlistener public void actionperformedactionevent e so we have one local inner class which resides inside method dosomething and i have some questions involveddoes this local inner class hold reference to outerclass since it is localdoes this local inner class remain memory after the method dosomething terminatesis there any situation in which outerclass is eligible for gc but local inner class still be referenced by other classes what would happen,['java'] +157329,eclipse java debugging source not found while debugging a java app in eclipse i receive a source not found error in two casesstepping in to a file in a different project which is already importedstepping in to a file in an installed maven repositorythe files are there but eclipse would not step into them instead it shows a button to attach sourcei tried attaching which opened a dialog to define a variable and eclipse did jump to the file but the debugger could not inspect any variables there also manually attaching the source for each dependency is not practical as in my case there are thousands of dependency filesi am new to eclipsejava so an explanation of why this is happening how to resolve this would help a lot,['java'] +157341,finding the common ancestor in a binary tree this question was asked to me in an interview i have a binary tree and i have to find the common ancestor parent given two random nodes of that tree i am also given a pointer to the root nodemy answer istraverse the tree separately for both the nodes till you reach the node that is expectedparallel while traversing store the element and the next address in a linked list then we have two linked lists with us so try comparing the two linked lists and the last common node in both the linked lists is the parenti am thinking that this solution is correct correct me if i am wrongif this solution is correct may i know is this the only better solution for this task or is there any other better solution than this,['c'] +157371,how do i get actual creation time for a file in php on a mac when you choose a file in finder and hit cmdi on a mac you get the time the file was actually created and the time it was last modified my question is simply how can i get the actual time of creation from an already existing mac file with phpnow having researched the topic i have read posts that say it is impossible but in my world impossible only means that a thing takes a bit longer to accomplish workarounds and hacks are welcomed i do not want mtime or ctime related advice as these only access the last time the file was updated or modifiedalso were probably talking mac only here but os independent solutions are also welcome if they really work on all systems,['php'] +157385,detect parenthesis in binaryexpression i am building a expression analyser from which i would like to generate database query code i have gotten quite far but am stuck parsing binaryexpressions accurately it is quite easy to break them up into left and right but i need to detect parenthesis and generate my code accordingly and i cannot see how to do thisan example please ignore the flawed logic a aline2 1 aline2 a aline2 b aline1endswithai need to detect the set in the middle and preserve their grouping but i cannot see any difference in the expression to a normal binaryexpression during parsing i would hate to check the string representation for parenthesisany help would be appreciatedi should probably mention that i am using cediti failed to mention that i am using the standard net expression classes to build the expressions systemlinqexpressions namespaceedit2ok i am not parsing text into code i am parsing code into text so my parser class has a method like thisvoid filterwithtexpressionfunct bool filterexpressionwhich allows you to write code like thisfilterwithcustomerc cname asd csurname qwewhich is quite easy to parse using the standard net classes my challenge is parsing this expressionfilterwithcustomerc cname asd csurname qwe cstatus 1 cthisabledmy challenge is to keep the expressions between parenthesis as a single set the net classes correctly splits the parenthesis parts from the others but gives no indication that it is a set due to the parenthesis,"['c#', '.net']" +157398,javascriptjquery replace part of string with text like thisdiv classelementspanna categoryspandivi want to get rid of every occurrence of nahere is my attemptelement spaneachfunction consolelogthistext thistextreplacena the logged text is the text inside of the span so the selector is okaywhat am i doing wrong here,"['javascript', 'jquery']" +157403,javascript and differences possible duplicatewhat is the operator in javascript what is the difference between these two operators does have special meaning or does it simply mean you are doing two operations i know there are truth and truthy concepts in javascript but i am not sure if is meant for truth,['javascript'] +157424,in c is there way to define an enum and an instance of that enum at the same time looking for a code optimization in c that allows me to both define an enum and create a variable of that enums type simultaniouslybefore enum state state1 state2 state3 state state statestate1after does not work enum state state1 state2 state3 state state statestate1does anything like that exist,['c#'] +157425,java calculate time between two timestamps i need to calculate the time passed between two datesthe catch here is that i need to show it as youtube does with its video comments timestamps that is to show it by just the largest measurefor exampleif the time is 50 seconds ago it should say 50 seconds agoif the time is more than one minute it should say one minute agoten minutes ago etcif the time difference is 1 hour 30 mins it should show an hour agoif the time is one and a half week than it should say one week ago if the time is more than a month it should say one month agotwo months ago etcand so on and so onso what is the best way to handle thisshould i make a method with case or if statements that would return something like this or is there a better approach maybe a library which already does something like it,"['java', 'android']" +157453,java possible to replace tablemodel in an existing jtable is it possible to replace the entire tablemodel in an existing jtable or do i have to recreate the jtable,['java'] +157460,getting window number through osx accessibility api i am working on an application that moves windows of third party applications around on the screento get an overview of all currently open windows i usecgwindowlistcopywindowinfokcgwindowlistoptiononscreenonly kcgwindowlistexcludedesktopelements kcgnullwindowidthis returns an array of dictionaries defining every open windowheres an exemplary dictionary returned kcgwindowalpha 1 kcgwindowbounds height 442 width 475 x 3123 y 118 kcgwindowisonscreen 1 kcgwindowlayer 0 kcgwindowmemoryusage 907184 kcgwindowname untitled kcgwindownumber 7328 kcgwindowownername textedit kcgwindowownerpid 20706 kcgwindowsharingstate 1 kcgwindowstoretype 2 kcgwindowworkspace 3the dictionary is full of good information used elsewhere but lacks an accessibility object that could be used to modify the windows positions windows are clearly identified by the window numberi am now using the pid kcgwindowownerpid to create an accessibility object for the windows applicationaxuielementref app axuielementcreateapplicationpidfollowed by retrieving a list of all windows the application has opened using axuielementcopyattributevaluesnsarray resultaxuielementcopyattributevalues axuielementref app kaxwindowsattribute 0 9 cfarrayref result this works and returns an array of axuielementsthis is where i am stuck there seems to be no api call to retrieve the window number of an accessibility object is there any way to eithera find the accessibility objects window number to ultimately iterate over the array and find the right windoworb otherwise clearly match a window described in the array returned by cgwindowlistcopywindowinfo to the accessibility objects returned by axuielementcopyattributevalues,['objective-c'] +157462,overide default pluralize for modelname in rails3 my locale is de and i like to get thissheetmodel namehumanpluralize belegsto add me a trailing e instead of ssheetmodel namehumanpluralize belegejust for the sheetclasscan i add it somehow in my configlocalesmodelsdeyml regards kai,['ruby-on-rails'] +157477,jquery class selector performance confused so is tableselectable tdcapable inputtext preferable to tableselectable td inputtext in other words does specifying a class speed up or slow down the selection assuming it is not absolutely required in this scenario,['jquery'] +157487,alternate div background color i have a structure like the followingdiv classwrapper a hrefblaha div classpoststuffdivdivand it repeats throughout a dynamic page a few times i would like to alternate the background colors of the div class post with two colors but cs nthchild pseudo class only seems to work with items that are directly sequentialis there a way css javascript jquery etc that i can alternate the div background colors,"['javascript', 'jquery', 'css']" +157517,getting ui thispatcher in class library i would like to design a class library and plan to use mutlithreading ie backgroundworker i will have to watch out for the thread context from which updates are made for fields if i plan to bind them to the gui of the library consuming frontend it is not a good idea to pass the reference of the gui thispatcher to the library as i read but how can i get access to the thispatcher of the application that will use the library is this possiblei tried applicationcurrentthispatcher and added a reference to windowbase as i did not have the possibility to add systemwindows but still cannot resolve the thispatcher object,['c#'] +157559,fetching objects from core data not in a set i am trying to fetch objects from core data that are not in a given set but i have not been able to get it to workfor instance suppose that we have a core data entity named user which has a few attributes such as username familyname givenname and active given an array of strings representing a set of usernames we can easily fetch all the users corresponding to that list of usernamesnsmanagedobjectcontext moc nsmanagedobjectcontext alloc initnsfetchrequest request nsfetchrequest alloc initnsentitydescription entity nsentitydescription entityfornameuser inmanagedobjectcontextmocrequest setentityentitynsarray usernames nsarray arraywithobjectsuser1 user2 user3 nilnspredicate predicate nspredicate predicatewithformatusername in usernamesrequest setpredicatepredicatensarray users moc executefetchrequestrequest errornilhowever i want to fetch the complement of that set ie i want all the users in core data that do not have the usernames specified in the usernames array does anyone have an idea how to approach this issue i thought it would be simple enough to add a not in the predicate ie username not in but xcode throws an exception saying the predicate format could not be parsed i also tried using the predicate builder available for fetch requests with no luck the documentation was not particularly helpful either suggestions comments thanks for all your help,"['iphone', 'objective-c']" +157565,ruby netftp extract filename from ftplist i am using the following code to try and get all files from ftp using rubyfiles ftplistfileseach do file ftpgettextfilefileendthe problem is ftplist returns a whole line of information not just the filename egrwrr 1 ftp ftp 0 may 31 18 bretxthow do i extract the filname from this stringmany thanks,"['ruby-on-rails', 'ruby']" +157625,how can i control the height of text inputs and submit input buttons in different browsers i have a very little but hard for me problem to solvei have a text input and a submit button i need them to be the exact same height and for this to be true across chrome and firefox ideally internet explorer alsohtmlinput typetext nameemail input typesubmit valuea cssinputtypetext width 218pxinputtypesubmit background 0 color finputtypesubmit inputtypetext padding 9px fontsize 18px lineheight 18px float left border 0 thisplay block margin 0i have setup this basic code on a jsfiddle hereyou should notice if you load it in chrome the button is less height than the text input and in firefox its larger what am i missing,"['html', 'css']" +157649,initializing member variables using the same name for constructor arguments as for the member variables allowed by the c standard i figured out that it is possible to initialize the member variables with a constructor argument of the same name as show in the example belowinclude cstdioinclude vectorclass blah stdvectorint vecpublic blahstdvectorint vec vecvec void printvec forunsigned int i0 ivecsize i printfi vecati printfn int main stdvectorint myvector3 myvectorat0 1 myvectorat1 2 myvectorat2 3 blah blahmyvector blahprintvec return 0g 44 with the arguments wall wextra pedantic gives no warning and works correctly it also works with clang i wonder what the c standard says about it is it legal and guaranteed to always work,['c++'] +157665,android fbreaderjgen already exists but is not a source folder convert to a source folder or rename it i downloaded the fbreaderj source its say fbreaderjgen already exists but is not a source folder convert to a source folder or rename iti cannot run it why i cannot delete gen too,['android'] +157666,how to handle com events from a console application i am using a com object from a third party library that generates periodic events when i use the library from a winforms app having the object as a class member and creating it in the main form thread everything works however if i create the object from another thread i do not receive any eventmy guess is that i need to have some kind of event loop in the same thread used to create the object i need to use this object from a console application i guess i could use applicationdoevents but i would rather not include the winforms namespace in a console apphow can i solve this problemupdate 3 20110615 the vendor has answered at last in short they say there is some difference between the message pump created by applicationrun and the one created by threadjoin but they do not know what that difference is i agree with them any light shed on this matter would be very appreciatedupdate from richard comment to mdm answerif there other component is single threaded and instantiated from an mta then windows will create the worker thread window message pump and do the necessary marshallingtrying to follow his advice i am doing the followingupdate 2 i am changed the code following joao angelo answerusing systemnamespace consoleapplication2 class program stathread static void mainstring args mycomobjectwrapper wrapper new mycomobjectwrapper class mycomobjectwrapper mycomobject m object autoresetevent m event public mycomobjectwrapper m event new systemthreadingautoreseteventfalse systemthreadingthread t new systemthreadingthread createobject tsetapartmentstate systemthreadingapartmentstatesta tstart wait void objectevt void wait m eventwaitone void createobject m object new mycomobject m objectonevent objectevt systemthreadingthreadcurrentthreadjoin i have also tried the following instead public mycomobjectwrapper createobject,['c#'] +157686,how to decide between using ifelse vs trycatch when writing code how does one decide between using ifelse or trycatch for example in checking for a file should this be based on ifelse if fileexists or a trycatch block for example writing to a file can be handled via an ifelse block to create a file and then write to it or a trycatch with an assumption that the file exists what considerations are there in choosingthanks,['c#'] +157694,are bcrypt salts accessible separately when using has secure password in rails 31 bcrypt randomly generates a salt for each users password based on this response i understand the salt is stored as part of the password hash is there a method or attribute available to access that salt separately for example to use in writing secure cookies,['ruby-on-rails'] +157703,ajax request return 200 ok but error event is fired instead of success i have implemented an ajax request on my website which i am calling from a webpage it always returns 200 ok but jquery executes the error event i tried a lot of things but could not figure out the problem i am adding my code belowjquery codevar row 1var json twitterid row ajax type post url jqueryoperationaspxoperationdeleterow contenttype applicationjson charsetutf8 data json datatype json cache false success ajaxsucceeded error ajaxfailedfunction ajaxsucceededresult alerthello alertresultdfunction ajaxfailedresult alerthello1 alertresultstatus resultstatustextc code for jqueryopeartionaspxprotected void page loadobject sender eventargs e testprivate void test responsewritescript languagejavascriptalertrecord deletedscripti need the record deleted string after successfully deletion i am able to delete content but i am not getting this message is this correct or am i doing anything wrong please suggest the correct way to solve this issue,"['javascript', 'jquery', 'asp.net']" +157709,determine if a byte is a pdf file is there any way of checking if a byte is a pdf without openingi have some code to thisplay a list of byte as pdf thumbnails i previously knew all the byte were pdfs because we filtered the servlet to only return these now the requirement has changed and i need to bring all file types back is there any way of checking what the byte is or more specifically determining if it is not a pdf,"['c#', '.net']" +157713,using windows authentication inside my own login form i have wpf application that has a login form i would like to make all existing windows users that belong to some specific group able to log into my applicationso what i need is a way after the user have given his username and password to see if this is a user belonging to the wanted group and that the password is correct the feedback i can use to decide if the user gets logged in or not,"['c#', '.net']" +157759,mapping a boolean with hibernate i am running into trouble with hibernate i recently set my hbm2ddl to validate and it has been complaining a lot about wrong datatypes i have fixed every problem except for booleansi have a field opener in my class which is mapped as property columnopener nameopener typebooleanthe column opener is a tinyint 4 and has a value of 1 or 0 so far i have tried changing the types but to no avail i have also tried using the following setting in my hibernatecfg property namehibernatequerysubstitutionstrue 1 false 0propertybut i am still getting the same error what am i doing wrongorghibernatehibernateexception wrong column type opener expected bit at orghibernatemappingtablevalidatecolumnstablejava261 at orghibernatecfgconfigurationvalidateschemaconfigurationjava1083 at orghibernatetoolhbm2ddlschemavalidatorvalidateschemavalidatorjava116 at orghibernateimplsessionfactoryimplinitsessionfactoryimpljava317 at orghibernatecfgconfigurationbuildsessionfactoryconfigurationjava1294 at orghibernatecfgannotationconfigurationbuildsessionfactoryannotationconfigurationjava859note i have no access to the database,['java'] +157772,how to make a ssh connection with python can anyone recommend something for making a ssh connection in pythoni need it to be compatible with any os i have already tried pyssh only to get an error with sigchld which i have read is because windows lacks thisi have tried getting paramiko to work but i have had errors between paramiko and crypto to the point where the latest versions of each would not work togetherpython 261 currently on a windows machine,['python'] +157818,how to convert linq query to sql just trying to get the sql that is generated by a linq query,['sql'] +157821,jquery addclass problem i am using ie7 i have an input box as followsinput namelocation typetext idlocation maxlength512 size20 classeditable textand i am trying to do the followinglocationaddclassflaggedbut this wipes out all existing styling of the text box the class flag does not have any styling associated with it the existing classes have the following cssinputeditable height 18px backgroundcolor fcc paddingtop 0px paddingright 0px paddingbottom 0px paddingleft 0px borderfcc 1px solid margin0pxinputtext textalignleft height19px width100pxif i manually add the class flagged to the input box all styling remains intact in firefox the jquery addclass does not clear all styling why is this happening in ie7editedi have narrowed it down to thisif stringprototypetrim stringprototypetrim function stuff the stringprototypetrim functiondeclaration seems to be causing the problem any ideasedited again it seems to not like the fact that it is being called trim 2 hours of the day well spent,"['jquery', 'html', 'css']" +157822,current year in aspnet mvc 3 i want to add copyright current year to the footer in cshtml file of my page i often made it using javascript but since i am using aspnet mvc 3 i would like to do this using asp i was trying construction likeresponsewritecurrent year yeardatebut it did not work in mvc 3 and i cannot find solution that is working,['.net'] +157823,android listactivity how to add a view below the listview i am trying to put a progressbar view below a listview for a listactivity i want it to be always below the last row in the listview the progressbar which is placed in a linearlayout does appear as long as the list which is filled by an adapter at runtime is not exceeding the screen as soon as the list is larger than the screen the progressbar is no longer visiblethe layout xml looks like thisxml version10 encodingutf8linearlayoutxmlnsandroidandroidididdb1 rootandroidlayout widthfill parentandroidlayout heightfill parentandroidorientationvertical title bar linearlayout stylestyletitlebar textview stylestyletitlebartext androidtextsome title text imagebutton stylestyletitlebaraction androidcontentdescriptionstringdescription search androidsrcdrawabletitle search linearlayout content linearlayout androidlayout heightwrap content androidlayout widthfill parent listview androiddividerdrawablecategory item divider androiddividerheightdimenlist divider height androidlayout heightwrap content androidididandroidlist androidlayout widthfill parent androidlayout weight1 textview androidididandroidempty androidlayout widthfill parent androidlayout heightfill parent androidtextstringcategory no items linearlayout progress bar linearlayout androidlayout heightwrap content androidlayout widthwrap content progressbar androidididproductlist progressbar androidlayout widthwrap content androidlayout heightwrap content linearlayout linearlayoutis this not possible with a linearlayout any help appreciated,['android'] +157834,core data inverse relationship not being set i have got two entities that i will call a and b they are configured with tomany relationships in both directions so amybs and bmyas are both nssets here is my bizarre problem when i add a b to my a entity i do it using the mutablesetvalueforkey like thisnsmutableset mybset mya mutablesetvalueforkeymybsmybset addobjectthebtoaddthis does add the thebtoadd to the a entity but does not add the inverse relationship core data context save does not kick any errors but my a object does not have the b inverse set if i exit the application even the partial relationship is not savedheres the strange part if i just switch my code around and do the opposite there are reasons why this is harder to do for my particular application add a to b instead of adding b to a like thisnsmutableset myaset myb mutablesetvalueforkeymyasmyaset addobjecttheatoaddit works just fine by the way i have plenty of other tomany relationships that work just this one does not couple of other things1 my core data object model looks good but this is the first new entity that i have added under xcode 42 i have check rechecked and gone blind looking at my custom nsmanagedobjects but they look fine declared dynamic nsset no conflicting settersgetters etcany help or debugging suggestions would be greatly appreciated thank you,['ios'] +157835,orchard cms on load balanced web servers i am considering running orchard cms on load balanced servers two web servers with hardware load balancers and a san file sharei have been unable to find any info on thisi am wondering if there will be update and cacheing issues if pages are cached will updates be propagated to the other serveri am also wondering if there are likely to be any install pitfallsdoes anyone have any info or experience on thismany thanks,['asp.net'] +157845,objectivec init vs initialize in objectivec what is the difference between the init method ie the designated initializer for a class and the initialize method what initialization code should be put in each,['objective-c'] +157850,css media query on iphone i am trying to use a css media query specifically targeting the iphoneit works when i use a regular link rellink relstylesheet typetextcss hrefcssmobilecss however when i try this media query it does not worklink relstylesheet typetextcss hrefcssmobilecss mediaonly screen and maxwidth 640px how can i use a css media query to target the iphone,"['iphone', 'css']" +157858,am i implementing a genericsbased java factory correctly i do not believe i am implementing the factory pattern correctly because the application class createdocument method accepts any class type not just subclasses of documentin other words is there a way i can restrict the createdocument method to only accept subclasses of documentdocumentjavapackage comexamplefactorypublic abstract class document public document systemoutprintlnnew document instance created thistostring drawingdocumentjavapackage comexamplefactorypublic class drawingdocument extends document public drawingdocument systemoutprintlnnew drawingdocument instance created thistostring applicationjavapackage comexamplefactorypublic class application public t t createdocumentclasst documentclass try return documentclassnewinstance catch instantiationexception e throw new illegalargumentexceptione catch illegalaccessexception e throw new illegalargumentexceptione mainjavapackage comexamplefactorypublic static void mainstring args application application new application applicationcreatedocumentdrawingdocumentclass,['java'] +157873,managed bean creation exception in jsf i have a jsf managedbean i am getting the error when a managed bean is referred from from jsf page in websphere appserverhinputtext valuebeanthe bean is defined in the facesconfigxml as managedbean managedbeannamebeanmanagedbeanname managedbeanclasscomtestbeanmanagedbeanclass managedbeanscopesessionmanagedbeanscopemanagedbeanthis is the exceptioncomsunfacesmgbeanmanagedbeancreationexception an error occurred performing resource injection on managed bean mailingcitysuggestionsupdate this is the stacktrace comsunfacesmgbeanmanagedbeancreationexception an error occurred performing resource injection on managed bean mailingcitysuggestions531 133710506 cdt 0126 systemerr r at comsunfacesmgbeanbeanbuilderinjectresourcesbeanbuilderjava213531 133710506 cdt 0126 systemerr r at comsunfacesmgbeanbeanbuilderbuildbeanbuilderjava108531 133710506 cdt 0126 systemerr r at comsunfacesmgbeanbeanmanagercreateandpushbeanmanagerjava374531 133710506 cdt 0126 systemerr r at comsunfacesmgbeanbeanmanagercreatebeanmanagerjava2531 133710506 cdt 0126 systemerr r at comsunfaceselmanagedbeanelresolvergetvaluemanagedbeanelresolverjava88531 133710506 cdt 0126 systemerr r at javaxelcompositeelresolvergetvaluecompositeelresolverjava143531 133710506 cdt 0126 systemerr r at comsunfaceselfacescompositeelresolvergetvaluefacescompositeelresolverjava73531 133710506 cdt 0126 systemerr r at comsunfaceselchainawarevariableresolverresolvevariablechainawarevariableresolverjava107531 133710507 cdt 0126 systemerr r at comibmfacesportletportletvariableresolverresolvevariableportletvariableresolverjava91531 133710507 cdt 0126 systemerr r at comsunfaceselvariableresolverchainwrappergetvaluevariableresolverchainwrapperjava112531 133710507 cdt 0126 systemerr r at javaxelcompositeelresolvergetvaluecompositeelresolverjava143531 133710507 cdt 0126 systemerr r at comsunfaceselfacescompositeelresolvergetvaluefacescompositeelresolverjava73531 133710507 cdt 0126 systemerr r at orgapacheelparserastidentifiergetvalueastidentifierjava45531 133710507 cdt 0126 systemerr r at orgapacheelvalueexpressionimplgetvaluevalueexpressionimpljava185531 133710507 cdt 0126 systemerr r at comsunfacesapplicationvaluebindingvalueexpressionadaptergetvaluevaluebindingvalueexpressionadapterjava113531 133710507 cdt 0126 systemerr r at comibmfacesrenderkithtml extendedtypeaheadrendererdoanswertypeaheadrendererjava278531 133710507 cdt 0126 systemerr r at comibmfacesrenderkithtml extendedtypeaheadrendererencodebegintypeaheadrendererjava81531 133710507 cdt 0126 systemerr r at comibmfacesrenderkitdefaultajaxrendererencodebegindefaultajaxrendererjava64531 133710507 cdt 0126 systemerr r at javaxfacescomponentuicomponentbaseencodebeginuicomponentbasejava802531 133710507 cdt 0126 systemerr r at javaxfacescomponentuicomponentencodealluicomponentjava934531 133710507 cdt 0126 systemerr r at javaxfacesrenderrendererencodechildrenrendererjava148531 133710507 cdt 0126 systemerr r at comibmfacesrenderkitdefaultajaxrendererencodechildrendefaultajaxrendererjava73531 133710507 cdt 0126 systemerr r at javaxfacescomponentuicomponentbaseencodechildrenuicomponentbasejava826531 133710507 cdt 0126 systemerr r at comsunfacesrenderkithtml basichtmlbasicrendererencoderecursivehtmlbasicrendererjava234531 133710507 cdt 0126 systemerr r at comsunfacesrenderkithtml basicgrouprendererencodechildrengrouprendererjava118531 133710508 cdt 0126 systemerr r at comibmfacesrenderkitdefaultajaxrendererencodechildrendefaultajaxrendererjava73531 133710508 cdt 0126 systemerr r at javaxfacescomponentuicomponentbaseencodechildrenuicomponentbasejava826531 133710508 cdt 0126 systemerr r at comsunfacesrenderkithtml basichtmlbasicrendererencoderecursivehtmlbasicrendererjava234531 133710508 cdt 0126 systemerr r at comsunfacesrenderkithtml basicgrouprendererencodechildrengrouprendererjava118531 133710508 cdt 0126 systemerr r at comibmfacesrenderkitdefaultajaxrendererencodechildrendefaultajaxrendererjava73531 133710508 cdt 0126 systemerr r at javaxfacescomponentuicomponentbaseencodechildrenuicomponentbasejava826531 133710508 cdt 0126 systemerr r at comsunfacesrenderkithtml basichtmlbasicrendererencoderecursivehtmlbasicrendererjava234531 133710508 cdt 0126 systemerr r at comsunfacesrenderkithtml basicgrouprendererencodechildrengrouprendererjava118531 133710508 cdt 0126 systemerr r at comibmfacesrenderkitdefaultajaxrendererencodechildrendefaultajaxrendererjava73531 133710508 cdt 0126 systemerr r at javaxfacescomponentuicomponentbaseencodechildrenuicomponentbasejava826531 133710508 cdt 0126 systemerr r at javaxfacescomponentuicomponentencodealluicomponentjava936531 133710508 cdt 0126 systemerr r at javaxfacesrenderrendererencodechildrenrendererjava148531 133710508 cdt 0126 systemerr r at comibmfacesrenderkitdefaultajaxrendererencodechildrendefaultajaxrendererjava73531 133710508 cdt 0126 systemerr r at javaxfacescomponentuicomponentbaseencodechildrenuicomponentbasejava826531 133710508 cdt 0126 systemerr r at javaxfacescomponentuicomponentencodealluicomponentjava936531 133710508 cdt 0126 systemerr r at javaxfacescomponentuicomponentencodealluicomponentjava942531 133710508 cdt 0126 systemerr r at javaxfacescomponentuicomponentencodealluicomponentjava942531 133710508 cdt 0126 systemerr r at javaxfacescomponentuicomponentencodealluicomponentjava942531 133710509 cdt 0126 systemerr r at comsunfacesapplicationviewhandlerimpldorenderviewviewhandlerimpljava289531 133710509 cdt 0126 systemerr r at comsunfacesapplicationviewhandlerimplrenderviewviewhandlerimpljava220531 133710509 cdt 0126 systemerr r at comibmfacesportletportletviewhandlerimplrenderviewportletviewhandlerimpljava79531 133710509 cdt 0126 systemerr r at comsunfaceslifecyclerenderresponsephaseexecuterenderresponsephasejava110531 133710509 cdt 0126 systemerr r at comsunfaceslifecyclephasedophasephasejava100531 133710509 cdt 0126 systemerr r at comsunfaceslifecyclelifecycleimplrenderlifecycleimpljava139531 133710509 cdt 0126 systemerr r at hhscitmtpcorelistnerinterceptinglifecyclerenderinterceptinglifecyclejava84531 133710509 cdt 0126 systemerr r at comibmfacesportletfacesportletdorenderfacesportletjava374531 133710509 cdt 0126 systemerr r at comibmfacesportletfacesportletdoviewfacesportletjava415531 133710509 cdt 0126 systemerr r at hhscitmtpportletindividualsearchportletdoviewindividualsearchportletjava36531 133710509 cdt 0126 systemerr r at comibmfacesportletfacesportletdothispatchfacesportletjava303531 133710509 cdt 0126 systemerr r at javaxportletgenericportletrendergenericportletjava233531 133710509 cdt 0126 systemerr r at comibmwsportletcontainerinvokerimplportletfilterchainimpldofilterportletfilterchainimpljava128531 133710509 cdt 0126 systemerr r at comibmwpspropertybrokerstandardfilterc2aportletfilterdofilterc2aportletfilterjava183531 133710509 cdt 0126 systemerr r at comibmwsportletcontainerinvokerimplportletfilterchainimpldofilterportletfilterchainimpljava120531 133710509 cdt 0126 systemerr r at comibmwsportletcontainerinvokerimplportletservletdothispatchportletservletjava573531 133710509 cdt 0126 systemerr r at comibmwsportletcontainerinvokerimplportletservletcollaboratorchainimpldocollaboratorportletservletcollaboratorchainimpljava114531 133710510 cdt 0126 systemerr r at comibmwsportletcontainerdrrdserverportletservletcollaboratordorenderdserverportletservletcollaboratorjava123531 133710510 cdt 0126 systemerr r at comibmwsportletcontainerinvokerimplportletservletcollaboratorchainimpldocollaboratorportletservletcollaboratorchainimpljava105531 133710510 cdt 0126 systemerr r at comibmwsportletcontainercachecachecollaboratordorendercachecollaboratorjava92531 133710510 cdt 0126 systemerr r at comibmwsportletcontainerinvokerimplportletservletcollaboratorchainimpldocollaboratorportletservletcollaboratorchainimpljava105531 133710510 cdt 0126 systemerr r at comibmwpspepcwaspccoreimplportletservletcollaboratorimpldorenderportletservletcollaboratorimpljava156531 133710510 cdt 0126 systemerr r at comibmwsportletcontainerinvokerimplportletservletcollaboratorchainimpldocollaboratorportletservletcollaboratorchainimpljava105531 133710510 cdt 0126 systemerr r at comibmwsportletcontainerinvokerimplportletservletdothispatchportletservletjava273531 133710510 cdt 0126 systemerr r at comibmwsportletcontainerinvokerimplportletservletcollaboratorchainimpldocollaboratorportletservletcollaboratorchainimpljava82531 133710510 cdt 0126 systemerr r at comibmwsportletcontainerdrrdserverportletservletcollaboratordothispatchrrdserverportletservletcollaboratorjava60531 133710510 cdt 0126 systemerr r at comibmwsportletcontainerinvokerimplportletservletcollaboratorchainimpldocollaboratorportletservletcollaboratorchainimpljava74531 133710510 cdt 0126 systemerr r at comibmwsportletcontainercachecachecollaboratordothispatchcachecollaboratorjava74531 133710510 cdt 0126 systemerr r at comibmwsportletcontainerinvokerimplportletservletcollaboratorchainimpldocollaboratorportletservletcollaboratorchainimpljava74531 133710510 cdt 0126 systemerr r at comibmwpspepcwaspccoreimplportletservletcollaboratorimpldothispatchportletservletcollaboratorimpljava121531 133710510 cdt 0126 systemerr r at comibmwsportletcontainerinvokerimplportletservletcollaboratorchainimpldocollaboratorportletservletcollaboratorchainimpljava74531 133710510 cdt 0126 systemerr r at comibmwsportletcontainerinvokerimplportletservletthispatchportletservletjava208531 133710510 cdt 0126 systemerr r at comibmwsportletcontainerinvokerimplportletservletserviceportletservletjava165531 133710510 cdt 0126 systemerr r at javaxservlethttphttpservletservicehttpservletjava831531 133710511 cdt 0126 systemerr r at comibmwswebcontainerservletservletwrapperserviceservletwrapperjava16531 133710511 cdt 0126 systemerr r at comibmwswebcontainerservletservletwrapperserviceservletwrapperjava1595531 133710511 cdt 0126 systemerr r at comibmwswebcontainerfilterwebappfilterchaindofilterwebappfilterchainjava104531 133710511 cdt 0126 systemerr r at comibmwswebcontainerfilterwebappfilterchain dofilterwebappfilterchainjava77531 133710511 cdt 0126 systemerr r at comibmwswebcontainerfilterwebappfiltermanagerdofilterwebappfiltermanagerjava895531 133710511 cdt 0126 systemerr r at comibmwswebcontainerservletservletwrapperhandlerequestservletwrapperjava932531 133710511 cdt 0126 systemerr r at comibmwswebcontainerservletservletwrapperhandlerequestservletwrapperjava500531 133710511 cdt 0126 systemerr r at comibmwswebcontainerservletservletwrapperimplhandlerequestservletwrapperimpljava178531 133710511 cdt 0126 systemerr r at comibmwsspiwebcontainerservletgenericservletwrapperhandlerequestgenericservletwrapperjava121531 133710511 cdt 0126 systemerr r at comibmwswebcontainerwebappwebapprequestthispatcherincludewebapprequestthispatcherjava673531 133710511 cdt 0126 systemerr r at comibmwsportletcontainerinvokerimplportletinvokerimplinvokeportletinvokerimpljava214531 133710511 cdt 0126 systemerr r at comibmwsportletcontainerinvokerimplportletinvokercollaboratorchainimpldocollaboratorportletinvokercollaboratorchainimpljava78531 133710511 cdt 0126 systemerr r at comibmwsportletcontainercacheportletinvokercachecollaboratordorenderportletinvokercachecollaboratorjava58531 133710511 cdt 0126 systemerr r at comibmwsportletcontainerinvokerimplportletinvokercollaboratorchainimpldocollaboratorportletinvokercollaboratorchainimpljava67531 133710511 cdt 0126 systemerr r at comibmwsportletcontainerextportletinvokerperformancecollaboratorinvokeportletinvokerperformancecollaboratorjava313531 133710511 cdt 0126 systemerr r at comibmwsportletcontainerextportletinvokerperformancecollaboratordoinvokeportletinvokerperformancecollaboratorjava101531 133710511 cdt 0126 systemerr r at comibmwsportletcontainerextportletinvokerperformancecollaboratorinvokepmiportletinvokerperformancecollaboratorjava163531 133710512 cdt 0126 systemerr r at comibmwsportletcontainerextportletinvokerperformancecollaboratordoinvokeportletinvokerperformancecollaboratorjava91531 133710512 cdt 0126 systemerr r at comibmwsportletcontainerextportletinvokerperformancecollaboratordorenderportletinvokerperformancecollaboratorjava74531 133710512 cdt 0126 systemerr r at comibmwsportletcontainerinvokerimplportletinvokercollaboratorchainimpldocollaboratorportletinvokercollaboratorchainimpljava67531 133710512 cdt 0126 systemerr r at comibmwsportletcontainerinvokerimplportletinvokerimplrenderportletinvokerimpljava97531 133710512 cdt 0126 systemerr r at comibmwsportletcontainerportletcontainerimpldorenderportletcontainerimpljava119531 133710512 cdt 0126 systemerr r at comibmwsportletcontainerportletcontainerinvokercollaboratorchainimpldocollaboratorportletcontainerinvokercollaboratorchainimpljava80531 133710512 cdt 0126 systemerr r at comibmwsportletcontainerextextcollaboratordorenderextcollaboratorjava74531 133710512 cdt 0126 systemerr r at comibmwsportletcontainerportletcontainerinvokercollaboratorchainimpldocollaboratorportletcontainerinvokercollaboratorchainimpljava67531 133710512 cdt 0126 systemerr r at comibmwsportletcontainercachecacheinvokercollaboratordorendercacheinvokercollaboratorjava66531 133710512 cdt 0126 systemerr r at comibmwsportletcontainerportletcontainerinvokercollaboratorchainimpldocollaboratorportletcontainerinvokercollaboratorchainimpljava67531 133710512 cdt 0126 systemerr r at comibmwsportletcontainerportletcontainerimplrenderportletportletcontainerimpljava89531 133710512 cdt 0126 systemerr r at comibmwsportletcontainerpcinvokerportletinvokerimpl2runportletinvokerimpljava100531 133710512 cdt 0126 systemerr r at javasecurityaccesscontrollerdoprivilegedaccesscontrollerjava251531 133710512 cdt 0126 systemerr r at comibmwsportletcontainerpcinvokerportletinvokerimplinvokerenderportletinvokerimpljava96531 133710512 cdt 0126 systemerr r at comibmwpspepcwaspccoreimplportletinvokerimpl1invokeportletinvokerimpljava98531 133710513 cdt 0126 systemerr r at comibmwpspepcwaspccoreimplportletinvokerimplinvokeportletinvokerimpljava182531 133710513 cdt 0126 systemerr r at comibmwpspepcwaspccoreimplportletinvokerimplinvokerenderportletinvokerimpljava96531 133710513 cdt 0126 systemerr r at comibmwpspepcwaspcportletcontainerimplrenderportletportletcontainerimpljava116531 133710513 cdt 0126 systemerr r at comibmwpspepcportletcontainerimpldorenderportletportletcontainerimpljava641531 133710513 cdt 0126 systemerr r at comibmwpspeextrenderabstractrendermanagerperformserviceabstractrendermanagerjava264531 133710513 cdt 0126 systemerr r at comibmwpspepcportletcontainerimplrenderportletportletcontainerimpljava132531 133710513 cdt 0126 systemerr r at comibmwpsengineextensionrenderportletfragmentrendererrenderportletfragmentrendererjava218531 133710513 cdt 0126 systemerr r at comibmwpsengineextensionrenderportletfragmentrendererrenderportletfragmentrendererjava166531 133710513 cdt 0126 systemerr r at comibmwpsenginephaseswpfragmentrenderphaseprocessrenderingwpfragmentrenderphasejava248531 133710513 cdt 0126 systemerr r at comibmwpsenginephaseswpfragmentrenderphaseprocessrenderingwpfragmentrenderphasejava186531 133710513 cdt 0126 systemerr r at comibmwpsenginephaseswpbaserenderphaseexecutewpbaserenderphasejava194531 133710513 cdt 0126 systemerr r at comibmwpsstatephasesabstractrenderphasenextabstractrenderphasejava106531 133710513 cdt 0126 systemerr r at comibmwpsenginephaseswpabstractrenderphasenextwpabstractrenderphasejava97531 133710513 cdt 0126 systemerr r at comibmwpsengineservletcallportalservletjava860531 133710513 cdt 0126 systemerr r at comibmwpsengineservletdogetservletjava617531 133710513 cdt 0126 systemerr r at comibmwpsengineservletdopostservletjava8531 133710514 cdt 0126 systemerr r at javaxservlethttphttpservletservicehttpservletjava738531 133710514 cdt 0126 systemerr r at comibmwpsengineservletdofilterservletjava1257531 133710514 cdt 0126 systemerr r at comibmwpsresolverservletcontenthandlercleanupdofiltercontenthandlercleanupjava648531 133710514 cdt 0126 systemerr r at comibmwpsresolverservletabstractfilterdofilterabstractfilterjava93531 133710514 cdt 0126 systemerr r at comibmwpsengineservletserviceservletjava1248531 133710514 cdt 0126 systemerr r at comibmwswebcontainerservletservletwrapperserviceservletwrapperjava16531 133710514 cdt 0126 systemerr r at comibmwswebcontainerservletservletwrapperserviceservletwrapperjava1595531 133710514 cdt 0126 systemerr r at comibmwswebcontainerfilterwebappfilterchaindofilterwebappfilterchainjava131531 133710514 cdt 0126 systemerr r at comibmwpsengineextendedlocalefilterdofilterextendedlocalefilterjava113531 133710514 cdt 0126 systemerr r at comibmwswebcontainerfilterfilterinstancewrapperdofilterfilterinstancewrapperjava184531 133710514 cdt 0126 systemerr r at comibmwswebcontainerfilterwebappfilterchaindofilterwebappfilterchainjava116531 133710514 cdt 0126 systemerr r at comibmwpsresolverfriendlyservletfriendlyselectionfilterdofilterfriendlyselectionfilterjava191531 133710514 cdt 0126 systemerr r at comibmwswebcontainerfilterfilterinstancewrapperdofilterfilterinstancewrapperjava184531 133710514 cdt 0126 systemerr r at comibmwswebcontainerfilterwebappfilterchaindofilterwebappfilterchainjava116531 133710514 cdt 0126 systemerr r at comibmwpsmappingurlimplurlanalyzerdofilterurlanalyzerjava381531 133710514 cdt 0126 systemerr r at comibmwswebcontainerfilterfilterinstancewrapperdofilterfilterinstancewrapperjava184531 133710514 cdt 0126 systemerr r at comibmwswebcontainerfilterwebappfilterchaindofilterwebappfilterchainjava116531 133710514 cdt 0126 systemerr r at comibmwpsenginevirtualportalfilterdofiltervirtualportalfilterjava88531 133710515 cdt 0126 systemerr r at comibmwswebcontainerfilterfilterinstancewrapperdofilterfilterinstancewrapperjava184531 133710515 cdt 0126 systemerr r at comibmwswebcontainerfilterwebappfilterchaindofilterwebappfilterchainjava116531 133710515 cdt 0126 systemerr r at comibmwpsstatefilterstatecleanupdofilterstatecleanupjava94531 133710515 cdt 0126 systemerr r at comibmwswebcontainerfilterfilterinstancewrapperdofilterfilterinstancewrapperjava184531 133710515 cdt 0126 systemerr r at comibmwswebcontainerfilterwebappfilterchaindofilterwebappfilterchainjava116531 133710515 cdt 0126 systemerr r at comibmwswebcontainerfilterwebappfilterchain dofilterwebappfilterchainjava77531 133710515 cdt 0126 systemerr r at comibmwswebcontainerfilterwebappfiltermanagerdofilterwebappfiltermanagerjava895531 133710515 cdt 0126 systemerr r at comibmwswebcontainerservletservletwrapperhandlerequestservletwrapperjava932531 133710515 cdt 0126 systemerr r at comibmwswebcontainerservletservletwrapperhandlerequestservletwrapperjava500531 133710515 cdt 0126 systemerr r at comibmwswebcontainerservletservletwrapperimplhandlerequestservletwrapperimpljava178531 133710515 cdt 0126 systemerr r at comibmwswebcontainerwebappwebapphandlerequestwebappjava3810531 133710515 cdt 0126 systemerr r at comibmwswebcontainerwebappwebgrouphandlerequestwebgroupjava276531 133710515 cdt 0126 systemerr r at comibmwswebcontainerwebcontainerhandlerequestwebcontainerjava931531 133710515 cdt 0126 systemerr r at comibmwswebcontainerwswebcontainerhandlerequestwswebcontainerjava1583531 133710515 cdt 0126 systemerr r at comibmwswebcontainerchannelwcchannellinkreadywcchannellinkjava183531 133710515 cdt 0126 systemerr r at comibmwshttpchannelinboundimplhttpinboundlinkhandlethiscriminationhttpinboundlinkjava4531 133710515 cdt 0126 systemerr r at comibmwshttpchannelinboundimplhttpinboundlinkhandlenewinformationhttpinboundlinkjava384531 133710515 cdt 0126 systemerr r at comibmwshttpchannelinboundimplhttpiclreadcallbackcompletehttpiclreadcallbackjava83531 133710516 cdt 0126 systemerr r at comibmwstcpchannelimplaioreadcompletionlistenerfuturecompletedaioreadcompletionlistenerjava165531 133710516 cdt 0126 systemerr r at comibmioasyncabstractasyncfutureinvokecallbackabstractasyncfuturejava217531 133710516 cdt 0126 systemerr r at comibmioasyncasyncchannelfuturefirecompletionactionsasyncchannelfuturejava161531 133710516 cdt 0126 systemerr r at comibmioasyncasyncfuturecompletedasyncfuturejava138531 133710516 cdt 0126 systemerr r at comibmioasyncresulthandlercompleteresulthandlerjava204531 133710516 cdt 0126 systemerr r at comibmioasyncresulthandlerruneventprocessingloopresulthandlerjava775531 133710516 cdt 0126 systemerr r at comibmioasyncresulthandler2runresulthandlerjava905531 133710516 cdt 0126 systemerr r at comibmwsutilthreadpoolworkerrunthreadpooljava1550531 133710516 cdt 0126 systemerr r caused by comsunfacesspiinjectionproviderexception javalangnullpointerexception531 133710517 cdt 0126 systemerr r at comsunfacesvendorwebsphereinjectionproviderinjectwebsphereinjectionproviderjava51531 133710517 cdt 0126 systemerr r at comsunfacesmgbeanbeanbuilderinjectresourcesbeanbuilderjava207531 133710517 cdt 0126 systemerr r 168 more531 133710517 cdt 0126 systemerr r caused by javalangnullpointerexception531 133710518 cdt 0126 systemerr r at javalangstringvalueofstringjava1511531 133710518 cdt 0126 systemerr r at comibmwswebcontainerannotationwasannotationhelperinjectwasannotationhelperjava261531 133710518 cdt 0126 systemerr r at comibmwswebcontainerannotationwasannotationhelperinjectwasannotationhelperjava248531 133710518 cdt 0126 systemerr r at comsunfacesvendorwebsphereinjectionproviderinjectwebsphereinjectionproviderjava49531 133710518 cdt 0126 systemerr r 169 more531 133710562 cdt 0126 systemerr r fatal error javalangillegalstateexception preparethread not called for thread threadwebcontainer 235main,['java'] +157875,using 2 domains on one website i have a dedicated server apache php mysqlthere is a primary domain let us call it wdomain1com that actually holds all the files like any other regular web hosting account another domain call it domain2com needs to forward to it but with masking so domain2comfilenamephp domain2comfilenamephp432r23gjfdlafdjslaf all need to show the corresponding content of domain1coms content but the browser should still show domain2com instead of domain1com and it also has to be detectable by serverhttp host so my server knows which domain was used to contact the website this is because i have 2 clients who are in a partnership so they would like each visitor to retain whatever url they entered for independent presentation but make the content unilateral without having to update two sites at once,['php'] +157886,autorenewable subscription receipt date format i am struggling to figure out the formatting for the following date20110524 190232 etcgmtthis date is returned from apples receipt validation service and i need to turn it into a nsdate for some comparison operations the real trouble is related to the timezoneheres some code i have already written nsdictionary receiptdata info valueforkeyexpires date nsdateformatter f nsdateformatter alloc init f setlocalenslocale currentlocale f settimezonenstimezone timezoneforsecondsfromgmt0 f setdateformatymmdd hhmmss v nslog f stringfromdatensdate date nsdate subpurchasedate f datefromstringreceiptdata valueforkeyoriginal purchase date f releasei have tried all combinations of vs and zs that i can think of any insight,"['iphone', 'objective-c', 'ios']" +157887,converting a txt file from ansi to utf8 programaticaly hey everyone i need your help here pleasei am working on a java application that convert data from a txt file into the database the problem is that the file have ansi encoding which i cannot change because it comes from outside my application and when i write the data to the database i got some insidemy question is how can i convert the data that i read from the file from ansi to utf8 which can handle those weired symbolsi have tried the byte to string converting but it did not work any ideas,['java'] +157888,store a value in viewbag from javascript how can i store a value in the viewbag accessing it from javascript,['javascript'] +157890,how to determine if compilation debugtrue in webconfig i am drawing a blank here for something that should be simplei am trying to do something like mycontrol runatserver idmyid visible is compilation debug mode,"['c#', 'asp.net']" +157902,convert psd to android xml layout format i am coding an android app for a research project at my institution and have been working with a designer who has rendered some attractive ui mockups in photoshop using cs5 i would like to implement her designs as layouts for my android application and this would be worlds simpler if there were some way i could convert the files to xml format i think it is rather counterintuitive that ps offers android templates but no real way to apply these in the android designlayout process short of attempting to mimic her artwork in xml code which i cannot do by any stretch is this conversion possible is there something i am missingthankstaichou,['android'] +157909,excluding items selectively from sitecores lucene search index works when rebuilding with indexviewer but not when using sitecores builtin tools on a site powered by sitecore 62 i need to give the user the ability to selectively exclude items from search resultsto accomplish this i have added a checkbox field entitled include in search results and i created a custom database crawler to check that fields valueapp configincludesearch indexeswebsiteconfigsearch configuration typesitecoresearchsearchconfiguration sitecorekernel singleinstancetrue indexes hintlistaddindex index idwebsite singleinstancetrue typesitecoresearchindex sitecorekernel locations hintlistaddcrawler master typemyprojectlibsearchindexingcustomcrawler myproject master similar entry for web database locations index indexes configurationsearchlibsearchindexingcustomcrawlercsusing lucenenetdocumentsusing sitecoresearchcrawlersusing sitecoredataitemsnamespace myprojectlibsearchindexing public class customcrawler databasecrawler summary determines if the item should be included in the index summary param nameitemparam returnsreturns protected override bool ismatchitem item if iteminclude in search results 1 return false return baseismatchitem whats interesting is if i rebuild the index using the index viewer application everything behaves as normal items whose include in search results checkbox is not checked will not be included in the search indexhowever when i use the search index rebuilder in the sitecore control panel application or when the indexingmanager autoupdates the search index all items are included regardless of the state of their include in search results checkboxi have also set numerous breakpoints in my custom crawler class and the application never hits any of them when i rebuild the search index using the builtin indexer when i use index viewer it does hit all the breakpoints i have sethow do i get sitecores builtin indexing processes to respect my include in search results checkbox,['c#'] +157926,csrf with jquery and post in django 13 in django 13 you now have to use csrf even with ajax i use jquery and i now want to add the csrf token to the post how can i do this i am not very skilled in jquery so it would be nice with a good descriptionit is a rating app and the post is send when a star is clickedi have seen the django docs but do not understand what to do in my situation my code is belowfunction avgchildrennotinputhide ratingwidgetchildrennotselecthide caption span avgstarscaptionel caption ratingwidgetstars inputtype select cancelshow false captionel caption callback functionui type value postratingwidgetattraction score value functiondata captionappendtoratingwidgetit should be said that the javascript is not in a template but in a static filewould it be best to put it in a template so i could use csrf token thanks in advance,['jquery'] +157938,what does the single pipe do in javascript consolelog05 0 0consolelog1 0 1consolelog1 0 1why does 05 0 return zero but any integer including negative returns the input integer what does the single pipe do,['javascript'] +157944,what is the fastest way to check whether string has uppercase letter in c my first implementation idea is to do simplybool hasuppercase string str ifstringisnulloremptystr return false for int i 0 i strlength i if charisupper stri return true return falsebut maybe there is another faster way to do that,['c#'] +157952,how to force download of big files without using too much memory i am trying to serve large zip files to users when there are 2 concurrent connections the server runs out of memory ram i increased the amount of memory from 300mb to 4gb dreamhost vps and then it worked fine i need to allow a lot more than 2 concurrent connections the actual 4gb would allow something like 20 concurrent connections too badwell the current code i am using needs the double of memory then the actual file size that is too bad i want something like streaming the file to user so i would allocate not more than the chunk being served to usersthe following code is the one i am using in codeigniter php frameworkini setmemory limit 300m it was the maximum amount of memory from my serverset time limit0 to avoid the connection being terminated by the server when serving bad connection downloadsforce downloaddownloadzip file get contentsdownloadsbig file 80mzipexitthe force download function is as follows codeingiter default helper functionfunction force downloadfilename data if filename or data return false try to determine if the filename includes a file extension we need it in order to set the mime type if false strposfilename return false grab the file extension x explode filename extension endx load the mime types includeapathconfigmimesext set a default mime if we cannot find it if issetmimesextension mime applicationoctetstream else mime is arraymimesextension mimesextension0 mimesextension generate the server headers if strpos serverhttp user agent msie false headercontenttype mime headercontentthisposition attachment filenamefilename headerexpires 0 headercachecontrol mustrevalidate postcheck0 precheck0 headercontenttransferencoding binary headerpragma public headercontentlength strlendata else headercontenttype mime headercontentthisposition attachment filenamefilename headercontenttransferencoding binary headerexpires 0 headerpragma nocache headercontentlength strlendata exitdatai tried some chunk based codes that i found in google but the file always was delivered corrupted probably because of bad codecould anyone help me,['php'] +157956,how do i know if my jscss files is too huge what is the optimal filesize of a javascript and css files of a websites,"['javascript', 'css']" +157984,datagridview export to excel hey guys i was able to export data of datagridview to excel but the actual format of datagridview was not exported ie font color and space so is there any best way to export datagridview to excel ie not only data but also the lookthe sample look is,['c#'] +157998,how to setup a mail interceptor in rails 303 i am using rails 303 ruby 192p180 mail 2213 i m trying to setup a mail interceptor but i am getting the following error homeabhimanyuaptana studio 3 workspacedelivery health dashboard 03configinitializersmailer configrb16in top required uninitialized constant developmentmailinterceptor nameerrorhow do i fix itthe code i am using is shown belowconfiginitializermailer configrbactionmailerbasedefault charset utf8actionmailerbasedefault content type texthtmlactionmailerbaseraise delivery errors trueactionmailerbaseperform deliveries trueactionmailerbasedelivery method smtpactionmailerbasesmtp settings enable starttls auto trueaddress secureemailsrvrcomport 25domain domainuser name user namepassword passwordauthentication plainactionmailerbaseregister interceptordevelopmentmailinterceptor if railsenvdevelopmentlibdevelopment mail interceptorrbclass developmentmailinterceptor def selfdelivering emailmessage messageto email endendthanks in advance,['ruby'] +158024,snooze local notification i am working on an alarm application and i am using local notification for that now i want to add snooze functionality to my alarm i searched on google and found that iphone does not support such functionalitybut is there another way to do this,['iphone'] +158026,nosetest including unwanted parent directories i am trying to limit nosetests to a specific directory however during the test run it is including the parent directories of the dir i am targetting and in doing so throws errorsheres the key elements of output from the test runnoseimporter debug add path projectsmyprojectmyprojectspecsnoseimporter debug add path projectsmyprojectmyprojectnoseimporter debug add path projectsmyprojectnoseimporter debug insert projectsmyproject into syspathi am using buildout with pbprecipenoserunner heres the relevant projectsmyprojectbuildoutcfg sectionspecsrecipe pbprecipenoserunnereggs pbprecipenoserunner buildouteggs figleaf pinocchioworkingdirectory myprojectspecsdefaults v exe include itensuremustshouldspecsexamples include specspyexamplespy withspec speccolori have also tried setting wheremyprojectspecs as one of the defaults parameters to help limit the import but still no joyany suggestions on where i am going wrongediti have tried to exclude the parent directories but no joy,['python'] +158036,does using small datatypes for example short instead of int reduce memory usage my question is basically about how the c compiler handles memory allocation of small datatypes i do know that for example operators like add are defined on int and not on short and thus computations will be executed as if the shorts are int members assuming the followingthere is no business logicvalidation logic associated with the choice of short as a datatypewere not doing anything with unsafe codedoes using the short datatype wherever possible reduce the memory footprint of my application and is it advisable to do so or is using short and the like not worth the effort as the compiler allocates the full memory ammount of a int32 for example and adds additional casts when doing arithmeticany links on the supposed runtime performance impact would be greatly appreciatedrelated questionswhy should i use int instead of a byte or short in cinteger summing blues short short problem,['c#'] +158038,how to use partition by or max i have the following table my datayear x y2010 a 102011 a 202011 b 992009 c 302010 c 40what is the best smallest sql statement to retrieve only the data related to the highest year and grouped by x like thisyear x y2011 a 202011 b 992010 c 40note that this result table will be used in a join,['sql'] +158060,how do i debug the child process after fork in gdb after calling forkthe current process will call exit0but the child will continueswitchfork case 1 exit1 case 0 child processcontinue break default the current processexit exit0how can i continue debug the child process in this case,['c'] +158082,jquery droppable receiving events during drag over not just on initial drag over i am using jquery droppable in conjunction with jquery draggable to allow the user to add rows to an html table by dragging items from a list and dropping them on the tablethis works well however at present the logic is that when the user dragdrops on a table row the new row gets added below the row they dropped onit would be better if the new rows add position was based on whether the user dropped in the upper or lower half of an existing rowthis is easy enough to calculate in the drop event but i need to give ui feedback as the user drags which i would do by means of two css classes droppableabove and droppablebelow for examplethis does not seem to be possible as the over event only fires once when the user initially drags over the droppable elementis it possible to get the over event to fire for every mouse move while the user is over a droppable elementif so then i would be able to do thistrdroppabledroppable over functionevent ui if mouse is in top half of row thisaddclassdroppableaboveremoveclassdroppablebelow else thisremoveclassdroppableaboveaddclassdroppablebelow out functionevent ui thisremoveclassdroppableaboveremoveclassdroppablebelow drop functionevent ui thisremoveclassdroppableaboveremoveclassdroppablebelow if mouse is in top half of row add new row above the dropped row else add new row below the dropped row the css styles would be something likedroppableabove bordertop solid 3px blue droppablebelow borderbottom solid 3px blue,"['javascript', 'jquery']" +158093,decorator to print function call details parameters names and effective values i want to make a function that being a decorator to another function will print that function call details parameters names and effective values my current implementation is this def describefunccallfunc decorator to print function call details parameters names and effective values def wrapperfunc args func kwargs print func codeco varnames funcfunc codeco varnames print func codeco argcount funcfunc codeco argcount print func args func args print func kwargs func kwargs params for argno in rangefuncfunc codeco argcount argname funcfunc codeco varnamesargno argvalue func argsargno if argno lenfunc args else funcfunc defaultsargno funcfunc codeco argcount paramsappendargname argvalue for argname argvalue in func kwargsitems paramsappendargname argvalue params argname reprargvalue for argname argvalue in params printfunc name joinparams return funcfunc args func kwargs return wrapperdescribefunccalldef testa b 4 c blahblah args kwargs passtest1test1 3test1 d 5test1 2 3 4 5 d 6 g 129kinda works but with some bugsfor call test1 2 3 4 5 d 6 g 129it prints test a 1 b 2 c 3 d 6 g 129 the expected result is test a 1 b 2 c 3 args 4 5 kwargs d 6 g 129 i got stuck here can you help me to find the right solution,['python'] +158106,relationship between scipy and numpy scipy appears to provide most but not all 1 of numpys functions in its own namespace in other words if there is a function named numpyfoo there is almost certainly a scipyfoo most of the time the two appear to be exactly the same oftentimes even pointing to the same function objectsometimes they are different to give an example that came up recentlynumpylog10 is a ufunc that returns nans for negative argumentsscipylog10 returns complex values for negative arguments and does not appear to be a ufuncthe same can be said about log log2 and logn but not about log1p 2on the other hand numpyexp and scipyexp appear to be different names for the same ufunc this is also true of scipylog1p and numpylog1panother example is numpylinalgsolve vs scipylinalgsolve they are similar but the latter offers some additional features over the formerwhy the apparent duplication if this is meant to be a wholesale import of numpy into the scipy namespace why the subtle differences in behaviour and the missing functions is there some overarching logic that would help clear up the confusion1 numpymin numpymax numpyabs and a few others have no counterparts in the scipy namespace2 tested using numpy 151 and scipy 090rc2,['python'] +158125,aspnet how to detect iosandroid i have recently launched a web app written in cnet 40 making extensive use of jquery jquery ui to give the best possible user experiencehowever some users have reported problems when using the site through an iphone or android deviceswhat is the best accepted method of detecting both ios and android so that i can then tweak the ui for each browser,"['c#', 'asp.net', 'android', 'ios']" +158128,imageview one dimension to fit free space and second evaluate to keep aspect ration i need something likeimg width100 for android imageview i mean resize width to all available space shrink or enlarge width of image and automatically change height to keep aspect ratio something like imageview androidlayout widthmatch parent androidlayout heightautouseandroidscaletypefitcenterdo with image what i want but only with image does not change height of view itself when i set booth dimensions to match parent i will get what i want but only if i have only one image on the screen but i need some texts under imageit is only way create child of imageviewfor exampleandroidadjustviewboundstruedoest do anything for me,['android'] +158135,auto save wpf c is there a way in which i can save details from a listview that doesnt require me to use the save dialog box everytime and allows me to call it within a certain time span so save rather than save as everytime,['c#'] +158139,java how do you find out the cap height and xheight of a font fontmetrics does not have getters for cap height and xheight of a fonthow can i obtain these valuesas far as cap height goes there is no guarantee for a particular capital letter that the letters ascent is the same as the cap height eg a capital h is not guaranteed to be flat on the topas far as x height goes i assume it is probably the same as the height of an x but again there is no guarantedit grr i just tried fontmetricsgetbounds and fontmetricsgetlinemetrics for specific character sequences and i always get the same answer for heights getbounds does differ for widths obviously there is a note in the hasuniformlinemetrics method about a fontmetrics having several fonts to cover the character set but that covers character groups not individual characters,['java'] +158140,set html entity in javascripts documenttitle i am setting documenttitle with javascript and i cannot find a way to supply raquo without it appearing as literal textheres my code documenttitle home raquo sitecom if i use raquo in the title tag of the document it works great and thisplays correctly as but it seems to be unescaping when i include it in documenttitleany ideasthanks,"['javascript', 'html']" +158161,how to run logcat on multiple devices how can i run logcat on multiple devices at the same time adb logcat command gives an errorerror more than one device and emulator,['android'] +158162,is there a meaningful way to use context managers inside generators from contextlib import contextmanagercontextmanagerdef context print entering yield print exitingdef test with context for x in range10 yield xfor x in test if x 5 break or raiseoutputenteringis there a way to make python automatically invoke the exit method of context when the forloop is interrupted or some other way of achieving the same aim what i know about generators and context managers makes me suspect it is not possible but this makes context managers rather useless inside generators does not it it seems to me a yield statement inside a with block should raise a red flag context manager exit may not run,['python'] +158168,how to copy net api documentation if a class implements a method defined in an interface you can choose whether you duplicate the documentation or reference it with see cref public interface iperformer summary do something useful summary param namesomethingobject to do something withparam void dosomething somethingpublic class implementation iperformer copy fromiperformer that is what i want public void dosomething something implementation is it possible to let the api documentation tool sandcastle copy the documentation automatically what would make reading the api documentation more comfortable something like inheritdoc from java doc,"['c#', '.net']" +158172,can you fire an event when android dialog is thismissed say i have a created a dialog in my android app like soprivate static progressdialog dialogdialog progressdialogshowmainactivitythis downloading files please wait truenow is it possible to fire an event when the following is calleddialogthismissthe reason i want to do this and not just call my method after dialogthismiss is because the dialog thismiss is called within a static class and the next thing i want to do is load a new activity which cannot be done using intents within a static class,['android'] +158174,spring web mvc validate individual request params i am running a webapp in spring web mvc 30 and i have a number of controller methods whose signatures are roughly as followsrequestmappingvalue level1level2foo method requestmethodpostpublic modelandview createfoopathvariable long level1 pathvariable long level2 requestparamfoo name string fooname requestparamvalue description required false string descriptioni would like to add some validation for example description should be limited to a certain length or fooname should only contain certain characters if this validation fails i want to return a message to the user rather than just throw some unchecked exception which would happen anyway if i let the data percolate down to the dao layer i am aware of jsr303 but have not worked with it and do not quite understand how to apply it in a spring contextfrom what i understand another option would be to bind the requestbody to an entire domain object and add validation constraints there but currently my code is set up to accept individual parameters as shown abovewhat is the most straightforward way to apply validation to input parameters using this approach,['java'] +158199,css clean solution to the margin collapse issue when floating an element example htmlcsshtml body stylepadding 0 margin 0 div stylefloat rightfirstdiv div stylemargintop 2emseconddiv bodyhtmldesired behavior the first div floats to the topright of the window actual behavior it floats 2em below the desired position reason margin collapsingdespite identifying the problem the solutions i can come up with feel like hackschange body style to margin 1px 0 0 0 bordertop 1px solidinsert div styleheight 1px marginbottom 1pxdiv before firstinsert the above div between the first and secondis there a clean idiomatic way of avoiding this issue,['css'] +158201,fancybox on cdn is there fancybox available anywhere on the cdnthanks,['javascript'] +158212,is this how to schedule a java method to run 1 second later in my method i want to call another method that will run 1 second later this is what i havefinal timer timer new timertimerschedulenew timertask public void run mymethod logwgeneral this has been called one second later timercancel 10is this how it is supposed to be done are there other ways to do it since i am on android can it be repeated without any problems,"['java', 'android']" +158230,how to determine type of widget in a qtable cell i have created a qtable with lots of gui elements like combo boxes and checkboxes in various cels i am able to access these elements by creating pointers to them what i want to know is is there any way to know what type of widgetcombo box or checkbox a cell is having,['c++'] +158232,php largest whole number from sum of unsorted array can someone tell me the best way to find the largest whole number summed from an unsorted arrayeg01 02 09 05largest whole number possible is 1 01 0909 02 05 03 09largest possible is 2 09 09 02thanksupdatei have accepted the method that i used but some of the below will be programmatically correct,['php'] +158233,how do i build a runtime version agnostic dll in c my product is a c library which on windows is thistributed as a dll it makes very little use of the cruntime basic iostream and that is it so i am sure that all recent versions of the crt will be finesince my client is supposed to build his application using my dll i do not want to impose upon him any specific runtime version i would like my dll to bind to whatever runtime library version my clients app is using and i can assume that he will use dynamic linking for his crt after all is not that what dynamic linking is all about is that possibleedit linking the dll against the static runtime libs would not work either because then the static runtime from the dll and the dynamic runtime from the clients application will be mixed which is badedit what i am mainly asking is how do i tell the runtime loader to link my dll against whatever crt the application is linked with something with the manifest perhapsmore generally my question is how to build a nicelybehaving dll that is to be used by clients building they are own applicationsedit thanks to the advice in the answers i have transferred all references to std classes into inlined functions in my headers and linked my dll with the static runtime libraries it now seems to work even in applications linked with different crt versions,['c++'] +158240,how to use condition variable the linux programming interface book has a piece of code producerconsumer to show how condition variable worksstatic pthread mutex t mtx pthread mutex initializerstatic pthread cond t cond pthread cond initializerstatic int avail 0while true s pthread mutex lockmtx while avail 0 wait for something to consume s pthread cond waitcond mtx while avail 0 consume all available units avail s pthread mutex unlockmtxwhy we use pthread mutex lock in while why we do not use it in an if,['c'] +158250,using websockets efficiently i have read pretty much every guide and tutorial i can find on websockets but not one of them has covered how to use them efficiently does anyone have any sort of guide on how to do this i am concerned about the amount of bandwidth a single connection can take up especially when applications have hundrends of connections opened,['javascript'] +158251,sqlalchemy subquery in a where clause i have just recently started using sqlalchemy and am still having trouble wrapping my head around some of the conceptsboiled down to the essential elements i have two tables like this this is through flasksqlalchemyclass userdbmodel tablename users user id dbcolumndbinteger primary keytrueclass postsdbmodel tablename posts post id dbcolumndbinteger primary keytrue user id dbcolumndbinteger dbforeignkeyusersuser id post time dbcolumndbdatetime user dbrelationshipuser backrefpostshow would i go about querying for a list of users and their newest post excluding users with no posts if i was using sql i would doselect whateverfrom posts as p left join users as you on uuser id puser idwhere ppost time select maxpost time from posts where user id uuser idso i know exactly the desired sql to get the effect i want but no idea how to express it properly in sqlalchemyedit in case it is important i am on sqlalchemy 066,['python'] +158261,functions in coffeescript i am trying to convert a function from javascript to coffeescript this is the codefunction convertnum1 num2 num3 return num1 num2 num3but how i can do that in coffeescripti am trying to run the function from an html source like thisscript typetextjavascript srccoffeeconvertjsscriptscript typetextjavascript convert6 3 10scriptbut it would not work and i get an error saying referenceerror cannot find variable converthow to correct this,['javascript'] +158274,how do i reference libraries in netbeans i have a java web services project that was created in an older version of netbeans and i have not accessed it in many months so my paths and installed libraries are different when i try to open the project i get a resolve reference problems dialog and two reference problems are listedmetro library could not be foundjaxwsendorsed library could not be foundi have a fresh installation of jdk 6 update 25 with netbeans 70 and am running windows 7 what steps can i take to solve this i do not even know where to start as every approach i have taken so far has not gotten me anywherenote jaxwsendorsed does not appear in my libraries listing so i cannot remove it something hidden is referencing it how would i find this,['java'] +158283,what does cg inline do i was poking around the definitions for things like cgpoint for hints on how to create my own functions but i do not know the purpose of cg inline what is happening behind the scenes herecg inline cgpointcgpointmakecgfloat x cgfloat y cgpoint p px x py y return pcg inline cgsizecgsizemakecgfloat width cgfloat height cgsize size sizewidth width sizeheight height return size,"['objective-c', 'ios']" +158307,why does not case with when 2 work why is this not workingcase argvlength when 0 abort error 1 when 2 abort error 2end,['ruby'] +158320,sorting a list of rgb triplets into a spectrum i have a list of rgb triplets and i would like to plot them in such a way that they form something like a spectrum i have converted them to hsv which people seem to recommend from pil import image imagedrawimport colorsysdef make rainbow rgbcolors width height colors is an array of rgb tuples with values between 0 and 255 img imagenewrgba width height canvas imagedrawdrawimg def hslx to float lambda x x 2550 r g b mapto float x h s l colorsysrgb to hsvrgb h h if 0 h else 1 0 1 return h s l rainbow sortedcolors keyhsl dx width floatlencolors x 0 y height 20 for rgb in rainbow canvaslinex y x dx y widthheight fillrgb x dx imgshowhowever the result does not look very much like a nice rainbowy spectrum i suspect i need to either convert to a different color space or handle the hsl triplet differently does anyone know what i need to do to make this data look roughly like a rainbowupdate i was playing around with hilbert curves and revisited this problem sorting the rgb values same colors in both images by their position along a hilbert curve yields an interesting if still not entirely satisfying result,['python'] +158339,how to replace backslash with double backslash i am trying to replace backslashes in my string with two backslashes like sostrgsub but it does not do anything i am confused,['ruby'] +158348,is it possible to detect android app uninstall my app is using googles c2dm push notification to notify users about new activity from friends once they install the app i register the device with c2dm servers and store users phone number so i know that the user is using my app and i can send himher the push notifications but what happens if users uninstalls my app is there a way to catch it in my app or the only way is to catch an error on my server when i send a c2dm and it is unreachable then mark a user as inactive i would love to notify users when their friends are using an app and when they no longer dowhats is the best solution for this scenario,['android'] +158360,javascript how to set selectedindex of select element using thisplay text how to set selectedindex of select element using thisplay text as referenceexampleinput idanimaltofind typetext select idanimals option value0chickenoption option value1crocodileoption option value2monkeyoptionselectinput typebutton onclickselectanimal script typetextjavascript function selectanimal set selected option of animals based on animaltofind value scriptis there any other way to do this without a loop you know i am thinking of a builtin javascript code or something also i do not use jquery,['javascript'] +158363,the compiler is complaining about my default parameters i am having trouble with this piece of code after i took this class from the maincpp file and splitted it in to h and cpp the compiler started complaining about the default parameters i was using in a void pbaseh class pbase public sfthread private bool runningpublic sfmutex mutex word originalcolor pbase launch running true originalcolor 0x7 void progressbarint int bool key pressed void setcolor int void settitle lpcwstr bool test connection ifrunning false return 0 else return 1 return 0 void stop running false ifrunning false wait pbasecpp other stuff above void pbasesetcolor int color 1 if color 1 setconsoletextattribute getstdhandle std output handle foreground intensity originalcolor return setconsoletextattribute getstdhandle std output handle foreground intensity colorand the error taken from vc2010error 4 error c2572 pbasesetcolor redefinition of default parameter parameter 1,['c++'] +158374,file picker for android is there any picker available to pick file from the sdcard or device memorylike filepicker available in blackberryif not then any alternative for doing thisplease help methanks in advance,['android'] +158379,how do i thisable a uibutton i am working on a project in which i have to show all photos of photo library in a plist and show them horizontally on uibuttons my app will also have an edit button when the user clicks this button a delete mark such as usually appears in other iphoneipad apps should show on each button but heres the crucial bit as soon as this delete mark appears the functionality of the button should be thisabled i have tried accomplishing this with the following editbuttonenablednobut it neither produces an error nor works what should i do,"['ios', 'objective-c']" +158381,does returned struct of localtime need to be freed struct tm localtimeconst time t timepi checked man localtime but there is no words on whether it is my duty to clean it after usingand in fact i have many similar doubts on functions returning a pointer how do you determine it should be freed or not,['c'] +158383,how to pass post parameters in a url basically i think that i cannot but would be very happy to be proven wrongi am generating an html menu dynamically in php adding one item for each current user so that i get something like a hrefprocess userphpuseruser but i have a preference for post over getis there any way to pass the info as a post parameter rather than get from a clickable href link update sorry i am not allowed to use js i shoulda said my badupdate to the update it looks like rob is on to somethign with you could use a button instead of an anchor and just style the button to look like a link that way you could have your values in hidden fields inside the same form to be sent via post,['php'] +158420,tabindex vs keyboardnavigationtabindex in wpf what is the difference between tabindex and keyboardnavigationtabindex in wpf when to use each,['.net'] +158460,outofmemory error while joining large images i am joining two images using the code below but it throws an outofmemory error my images are around 1mb eachprivate bitmap overlaymarkstring first string second bitmap bmp1 bmp2 bmp1 bitmapfactorydecodefilefirst bmp2 bitmapfactorydecodefilesecond if bmp1 null bmp2 null return bmp1 int height bmp1getheight if height bmp2getheight height bmp2getheight bitmap bmoverlay bitmapcreatebitmapbmp1getwidth bmp2getwidth height bitmapconfigargb 8 out of memory canvas canvas new canvasbmoverlay canvasdrawbitmapbmp1 0 0 null canvasdrawbitmapbmp2 bmp1getwidth 0 null bmp1recycle bmp2recycle return bmoverlayupdate i tried below two answers but it still not allwoing me to create bitmap of such big size the problem is that the resultant bitmap is too large in size around 2400x3200 so its going out of memoryhow can i join large images without running out of memory,['android'] +158482,linq to xml elements works but elementsxname does not work given below is my xml xml version10 encodingutf8report xmlnsrd xmlns body reportitems textbox nametxtcurrentdate cangrowtruecangrow keeptogethertruekeeptogether paragraphs paragraph textruns textrun valuetodayvalue style fontweightmediumfontweight formatdformat style textrun textruns style textalignlefttextalign style paragraph paragraphs left036958inleft height022917inheight width1inwidth style border stylenonestyle border paddingleft2ptpaddingleft paddingright2ptpaddingright paddingtop2ptpaddingtop paddingbottom2ptpaddingbottom style textbox textbox nametxtname cangrowtruecangrow keeptogethertruekeeptogether paragraphs paragraph textruns textrun valuemark wilkinsonvalue style textrun textruns style paragraph paragraphs top022917intop left036958inleft height020833inheight width322917inwidth zindex1zindex style border stylenonestyle border paddingleft2ptpaddingleft paddingright2ptpaddingright paddingtop2ptpaddingtop paddingbottom2ptpaddingbottom style textbox reportitems height601667inheight style body width7923inwidth reporti want to get all the textbox names and values this is what i tried and it does not workxdocument data xdocumentloadtestxmlrdl var elements from c in dataelementsreportitems select c foreach var element in elements consolewritelineelement elementattributenamevalue consolereadkeybut when i change the query to something like thisvar elements from c in dataelementselementselementat0elementselementat0elements select cit worksany help in this regard is much appreciatededit with the help of answers i was able to get the desired results thank you so much xdocument data xdocumentloadtestxmlrdl xnamespace ns datarootnamenamespace var elements from c in datadescendantsns textbox select c foreach var element in elements consolewritelineelement elementattributenamevalue consolereadkeytiaraja,['c#'] +158485,css3 boxshadow showing behind sibling div element i am usingboxshadow 0px 1px 0px 3on my footer but it is hiding behind or thisappearing where the div before it is hard to explain but heres what it looks like is there a way do have the boxshadow be on top of the other div before the footer i have tried adding a zindex but it does not work,['css'] +158488,converting ruby 192 code to javascript is it possible to convert ruby code to javascript at alli have heard of rubyjs but this appears to not work with ruby 192 is this the case,"['javascript', 'ruby']" +158493,android fragments vs compound controls why should android 30 fragments be used instead of compound controls one can create a view inheritor or compound control once and use it everywherei have read but did not find the answer,['android'] +158514,boost serialization and doubles i am trying to serialize a class to a string using the boost serialization library and included in my class are several double member variablesbelow is the code i am using to serializeinclude boostarchivetext oarchivehppinclude boostarchivetext iarchivehppinclude boostserializationstringhppstdstringstream ssboostarchivetext oarchive oassoa mpointhere is the serialiation method within my point classfriend class boostserializationaccesstemplateclass archivevoid serializearchive ar const unsigned int version if version 0 ar mlatitude ar mlongitude when i serialize to a string boost does not appear to handle the double to string conversion as i would expect there appear to be rounding issues researching a bit it looks like others have reported the same behavior i also understand the precision related issues associated with converting a double to a string and vice versa and how this could cause the issue what is strange and i do not understand though is this does not appear to happen when i am using a stringstream itself and redirecting the double to the stream nor when i use boosts lexical cast function to convert from a stringstreamstr back to a double before thiscovering boost had its own serializationdeserialization classes i had actually written my own using stringstream and lexical cast calls and it worked wo issue i am really hoping i do not have to abandon the serialization library and go back to what i had before hopefully there is just some settingtraitetc i am missing,['c++'] +158524,static variable across multiple different subclasses corrected i was wondering what happened if i define a base activity object with all my activities as subclasses of that then i declare a static variable in the base class will all the subclasses use the same static or will there be one per subclassfor example my base classpublic class mybaseactivity extends activity static int mystatic thenpublic class myactivity1 extends mybaseactivity private void somemethod1 mystatic 1 andpublic class myactivity1 extends mybaseactivity private void somemethod2 if mystatic 1 dosomething if i now start myactivity1 and it sets a value in mystatic it then exits and then i start myactivity2 should i still have the value set by the first activityin the example above would the if statement be true or falsei know that if i instantiate activity1 more than once then obviously i would get the same static variable however here i am instantiating a different subclass each timei am getting the impression that that is what is happening to me but want to be sure,"['java', 'android']" +158531,ipad zoom scale detection i am trying to find a way to detect how zoomed in someone is on a web app so that when they click to pull up a menu the menu stays the same size regardless of the zoom to do that i need to be able to scale the size of the menu appropriately relative to the zoom is there a way to do this,['html'] +158536,javascript how to make sense of all the frameworks and design philosophies i have been a user of jquery and some of its minor plugins for a while the javascript code i have developed over the years could be described best as messy it used a ton of global variables and functions here and there did not use standard ways of organizing the code nor any design patterns whatsoeveri am currently building the new version of a website and i have completed doing the backend with pearmdb2 and smarty templates the rest is just homebrew php with some classesnow i am at the point where i will add the javascript layer on top of the website to improve the userfriendliness of some features while making sure everything degrades gracefully i want to write better cleaner more organized javascript than i used to so i did a little research i read stefanovs objectoriented javascript to have a better grasp on some concepts i knew only loosely about prototypes constructors etc as well now i am stuck at a point where i wonder which javascript frameworks i should use and how to organize it all after conducting my research i understood cappuccino objectivej and sproutcore were not what i was looking for to quote cappucinos about page cappuccino is not designed for building web sites or making existing sites more dynamic we think these goals are too far removed from those of application development to be served well by a single framework projects like prototype and jquery are excellent at those tasksso there is that then i found out about coffee script which is more of a onetoone compiler and wouldnt help me with the actual organization of my code i also stumbled on some articles that give guidelinesusing inheritance patterns to organize large jquery applicationsa javascript module patterni also found out about backbonejs shoestring javascriptmvc google loader jquery tools jquery ui i do not really know what to do of all this the things i knowi do not want to invest too much time in learning something too complex i want to keep things simple and flexible as much as possible that is why i do not use symfony on the backend for example yet clean and organizedi want to use jquery the question is what should i use with it that is compatible tooright now i would use jquery and jquery tools and organize all that in a simple namespaceobject literal with simple properties and methods and also since the site is localized i just plan on using the simple vsprintf as i do on the backend with keyvalue pairs loaded from an object literal provided by the backend javascriptmvc seems interesting but i fear it would bring way too much complexity for a project that is fairly small sized that is where i need your advice thank you very much in advance,"['javascript', 'jquery']" +158543,always output raw html using mvc3 and razor iave got a class with a property that looks like thisallowhtmldatatypedatatypemultilinetextpublic string description get set iave already put in the allowhtml attribute to let me submit html to this property via the form that iave built but what i want to do is output the value of the property as the raw html without it being escapedi know i can use htmlrawmodeldescription but what iam looking for is some way of telling htmlthisplayform mdescription to always output the raw html is there an attribute i can use to decorate the properties in my class that i wish to behave like thatbasically itas me being lazyai donat want to have to remember which properties might contain html so i donat want to have to think about using htmlrawa when i need to do the aboveaiad much rather my model know what it should do and do it automatically iave tried searching for an answer but either iam not phrasing it correctly or thereas no way of doing it thanks,"['c#', 'asp.net']" +158582,uiscrollview reaching the bottom of the scroll view i know the apple documentation has the following delegate method voidscrollviewdidenddeceleratinguiscrollview scrollview called when scroll view grinds to a halthowever it does not necessarily mean you are at the bottom cause if you use your finger scroll a bit then it decelerates but you are not actually at the bottom of your scroll view then it still gets called i basically want an arrow to show that there is more data in my scroll view and then thisappear when you are at the bottom like when it bounces thanks,['iphone'] +158607,resolving springmessages in javascript for i18n internationalization i am attempting to internationalize some of our code i have a page in jspx which is using the springmessage tag to resolve strings from a messageproperties file this works fine for the html and css that is in the jspx page however there a javascript file is sourced and substituting the springmessage tag for the string in there just means that it gets printed out verbatim my jspx sources the javascript like sospringtheme codejsfile varjs script typetextjavascript srcjs the js where i am looking the replace the string is belowbuildlistsettings name springmessage codeprojsettingstoggle javascriptescapetrue idsetting1 description springmessage codeprojsettingstoggledescription javascriptescapetrue installed trueand finally the messageproperties is something likeprojsettingstoggleclick here to toggleprojsettingstoggledescriptionthis toggles between on and offso what i am wondering is should this work it seems to me like it should from what i have gathered on various forums but i cannot figure out where i am going wrong is there a better way to go about thisi should also note that these files are outside the webinf folder but by placing the reloadableresourcebundlemessagesource in the root applicationcontextxml the spring tags are picked upthanks for any help,['javascript'] +158617,c initializing a static map as a private class member let us say i was quite bored one late evening and after catatonically staring at the computer monitor for a few hours i decided to implement an aggregate c class to manage colors for drawing pixels because i have obviously gone mad for starters well just tell the probably singleton colormanager object what color we want to use and it will return a color object whatever that may be a simple implemention followsinclude colorhinclude mapenum color red 0 blue green yellow orange white black bricks from a thistance on an unusually sunny afternoon etc color count class colormanagerpublic colormanager colormanager color getcolorcolor color constprivate typedef stdmapcolor color colormap static colormap colormapso hopefully this simple codecolormanger colormanagercolor blue colormanagergetcolorblueshould make it real easy for us to do whatever nonsense for which youd need color objectsthe problem is that you need to initialize your static private colormap somewhere so that each color enum corresponds to a proper color object and vc 2010 does not seem to like anything you try so the question is how and where do i initialize this mapobviously this is a contrived example but beyond that perhaps defining static varibles for a class that functions as a singleton is not worth the trouble or perhaps i might as well just declare the variable static inside of getcolor since that is the only function that uses it and just incur the overhead the first time the function is called although for this simple example that is not much better than just putting a giant switch statement in there whatever the case i appreciate the feedback,['c++'] +158639,javascript match against array hello stackoverflowi would like to know how to match a string against an array of regular expressionsi know how to do this looping through the arrayi also know how to do this by making a long regular expression separated by i was hoping for a more efficient way like if string contains one of the values in array for example string the word tree is in this sentence array0 dog array1 cat array2 bird array3 birds can fly in the above example the condition would be falsehowever string she told me birds can fly and i agreed would return truethanks in advance,['javascript'] +158652,jquery keyup how do i prevent the default behavior of the arrow up down and enter key javascript jqueryinputkeyupfunctione var code ekeycode ekeycode ewhich switchcode case 38 break case 40 break case 13 break default return htmlform methodpost actioninput typetext nametext button typesubmitsubmitbuttonformi have 2 problems1 the caret should not move when i hit the up arrow keyfor example in chrome when i hit the upkey it moves the caret to the left but i only have this problem in chrome it works fine in ff2 when i hit the enter key i do not want the form to be submittedbtw i want to get this to work with keyup and not keypressi would appreciate any ideas thanks,"['javascript', 'jquery']" +158657,what does if do where the semicolon is right after the parentheses it happens that when writing some php code i accidentally put a semicolon right after an if statement for exampleifa 1 i thought that php should raise an error in this case but it is not that kind of syntax should have a meaning i am just wondering what it isfor what i could see the condition seems to be always true when the is added but i am not sure at all this is the meaning,['php'] +158663,calculating the length of mp3 frames in milliseconds lets say one mp3 frame length in bytes is 104 how to get that in milliseconds is there any formula or something to do that,"['c#', '.net']" +158665,whats the best way to calculate available memory in java i am trying to calculate how much memory is available to my java programi have this current implementationlong getavailablememory runtime runtime runtimegetruntime long totalmemory runtimetotalmemory long freememory runtimefreememory long maxmemory runtimemaxmemory long usedmemory totalmemory freememory long availablememory maxmemory usedmemory return availablememoryis that right is there an easiermore accurate way of calculating this information after looking at someone else code i saw something like this which is slightly differentlong getavailablememory long totalvmheap runtimegetruntimetotalmemory long freevmheap runtimegetruntimefreememory long usedvmheap totalvmheap freevmheap long maxvmheap runtimegetruntimemaxmemory long availablevmheap maxvmheap usedvmheap freevmheap return availablevmheapanyway whats the right way to get at this information,['java'] +158668,how to dynamically change the color of progress bar background android i would like to dynamically change the background color of a progress bar in android i followed the bonus part near the end of the page of this tutorialit changes the color but only once if called more than once the progress bar thisappears heres the codeheres the progress bar definitionprogressbar androidididprogress bar androidlayout widthfill parent androidlayout heightwrap content styleandroidstylewidgetprogressbarhorizontal androidlayout marginright5dp this is the drawable definition in resdrawablegreen progressxmlxml version10 encodingutf8layerlist xmlnsandroiditem androididandroididbackground shape corners androidradius5dip gradient androidstartcolorff9d9e9d androidcentercolorff5a5d5a androidcentery075 androidendcolorff747674 androidangle270 shapeitemitem androididandroididsecondaryprogress clip shape corners androidradius5dip gradient androidstartcolor80ffd300 androidcentercolor80ffb600 androidcentery075 androidendcolora0ffcb00 androidangle270 shape clipitemitem androididandroididprogress clip shape corners androidradius5dip gradient androidstartcolorcolorgreenstart androidcentercolorcolorgreenmid androidcentery075 androidendcolorcolorgreenend androidangle270 shape clipitemlayerlistene entries to rexvaluescolorsxmlcolor namegreenstartff33dd44colorcolor namegreenmidff0a8815colorcolor namegreenendff1da130colorand finally in the codem barsetprogressdrawablegetresourcesgetdrawablerdrawablegreen progress again the problem is it works the first time but then makes the bar thisappear,['android'] +158676,how to localize the documentation of a net library i have an opensource project here whose documentation is currently in french the documentation is generated from xml comments in code using sandcastle now i would like to translate the documentation to english and provide documentation in both languages but i do not really know where to startdo i need to extract the xml comments from the code and put them in a separate file if yes are there any tools to automate the processi am using sandcastle help file builder to build the documentation do i need to create a separate project to build the doc in english or can it be done from the same projectare there any tools to help in the translation process eg thisplay the original and translated doc side by sidei am also interested in links on how to produce multilingual documentation as i could not find anything useful on google,"['c#', '.net']" +158683,django calling save on a queryset object queryset object has no attribute save how would i get the below to workplayer playerobjectsgetpkplayer idgame gameobjectsgetpkgame idgame participant gameparticipantobjectsfilterplayerplayer gamegamegame participantsavei when the object already exists in the datbase then i getqueryset object has no attribute save in terms of my models gameparticipant has foreignkey to both game and player i understand that filter returns a queryset but i am not sure how to cast that to a gameparticipant or is that not the right thinkingclass playermodelsmodel name modelscharfieldmax length30 email modelsemailfieldclass gamemodelsmodel game date modelsdatetimefield team modelsforeignkeyteam description modelscharfieldmax length100 nulltrue blanktrue score modelscharfieldmax length10 nulltrue blanktrueclass gameparticipantmodelsmodel status choices yyesnnommaybe status modelscharfieldmax length10 choicesstatus choices game modelsforeignkeygame player modelsforeignkeyplayeror is there a better way to do what im trying to do ie with a get instead of a filter but then i run into other issues,['python'] +158702,running a c console application as a windows service i have a basic c console application that i would like to run as a windows servicei have created the windows service using sc create this worked fine and i can see my service under servicesmsc when i try and start this service i get the following errorcould not start the project service on local computer error 1053 the service did not respond to the start or control request in a timely fashioni read that this might be due to the service code taking longer than 30 ms to execute therefore i removed the bulk of the code so that hardly anything is being executed yet the same error persistsi am using net 35 for this projectwhat would cause this,"['c#', '.net']" +158707,visualvm hanging on startup computing description i have got two remote servers both running recent centos both running recent tomcat6 recent jdk6 and visualvm 132ssh x forwarding works on one server i can start up visualvm from that machine it port forwards and runs fine i see all the jvm processes running on that remote machine as local in vvmssh x forwarding on the second machine then running visualvm brings up an x windows with vvm in it but it just shows one local process the visualvm itself and the lower right corner has a bouncing progress bar that says computing description and it never endsi cannot find anything about this anywhere anyone ever hit this how do i get past this,['java'] +158710,aspnet get web response when http status is not 200 ok i need to read the response from an http get in situations where the response status code is not 200 ok sometimes it is 401 other 403 however there will be a response content if i try to use the httpwebresponse and httpwebrequest classes it throws an exception when the response status is not 200 ok any suggestions,"['c#', '.net', 'asp.net']" +158711,is it possible and how to do assisted injection in spring in guice 2 or 3 exists so called assistedpartial inject described here with this guice synthesizes factory implementation implementing my interface for my object and some of the constructor arguments are injected by guice and some are provided from the contextis it possible and how to do the same thing with spring,['java'] +158717,transactional method calling another method without transactional anotation i have seen a method in a service class that was marked as transactional but it was also calling some other methods in that same class which were not marked as transactionaldoes that mean the call to separate methods are causing the application to open separate connections to db or suspend the parent transaction etcwhats the default behavior for a method without any annotations that is called by another method with transactional annotationthanks,['java'] +158719,apostrophe got through filter in c i am really sorry to do this but this problem represents a possibly exploitable security issue on a site i work on so i am posting this with a new accountwe have a script that takes in user comments all comments are in english we have amassed approximately 30 comments in two years i was checking the comments table for any signs of malicious behavior and this time i did a scan for the apostrophe this should have been converted to an html entity 39 in all cases but i found 18 records out of 3 million in which the character survived the thing that is really breaking my head is that in one of these 18 comments one apostrophe actually was successfully converted the other survivedthis indicates to me that we have a possible xss vulnerabilitymy theory for whats going on is that a user is hitting the page on a computer system that uses a nonwestern codepage and that their browser is ignoring our pages utf8 charset specification that hisher input is not getting converted to the servers local codepage until it hits the database so c is not recognizing the character as an apostrophe and thus is unable to convert it but the database is when it tries to write it to a latin1 table but that is a total guesshas anyone encountered this before or know whats going onand more importantly does anyone know how i can test my script moving to httputility will probably fix the situation but until i know how this happened i cannot know the problem is fixed i need to be able to test this to know our solution workseditwow already at 20 points so i can edit my question i mentioned in one of my comments that i found several characters that appear to be problematic they include 0x2019 0x02bc 0x02bb 0x02ee 0x055a 0xa78c these pass right through our filter unfortunately they pass right through all httputility encoding methods too but once they get inserted into the database they get converted either into a actual apostrophe or into a in review i think the problem is that these characters do not in themselves pose a threat so httputility has no reason to convert them in a block of javascript they are harmless in a block of html they are just character data and are harmless and in a block of sql they are harmless if the database shares the same codepage the problem for us is that because the codepage were using in the database is different the insertion process in the database involves converting these unprintable characters into either known equivalents which in this case are bad and unknown equivalents which get rendered as this totally blindsided us and i am a little thisappointed in ms for not building more into their httputility encoding functionsi think the solution is to change the collation of the affected tables but if anyone else has a better idea please post below,['c#'] +158733,after importing into eclipse using egit cannot compile and run what do i do after importing a standard java file into eclipse using git i tried to compile and run the file eclipse gave me this error unable to launch the selection cannot be launched and there are no recent launcheswhat do i do,['java'] +158740,how can i use stdhex for my custom uint128 type what is the correct syntax to overload or whatever is actually is stdhex so that its functionality can be extended to non standard integers i wrote this version of uint128 t,['c++'] +158755,how to get actual javascript value in onclick from webbrowser control i am looking for a way to get the javascript code defined inside of onclicki am using net 20 c visual studio 2005examplespan idfoo onclickwindowlocationhrefsomeurlclick herespanmy goal is to get the string windowlocationhrefsomeurlscenarioa user clicks on web page element the tag shown above for instance inside of webbrowser control then the clicked tag is refereed to htmlelement objectin webbrowser control i then call htmlelement objects getattributeonclick it just gives me system comobjecti have searched how to deal with it then found that it can be casted then get the valueif taggetattributeonclickequalssystem comobject consolewritelinedom elem tagdomelementtostring mshtmlhtmlspanelementclass span mshtmlhtmlspanelementclasstagdomelement consolewritelinejs value spanonclickoutputdom elem mshtmlhtmlspanelementclassjs value system comobjectas it shown spanonclick still give me system comobject what am i doing wrongin why does htmlelements getattribute method return amshtmlhtmlinputelementclassa instead of the attributes value this guy said it worked in his case and i have followed it but mine is somewhat not workingupdateresearch researchi can add reference visualbasicdll to my c project then call the method to find out who is this system comobject really isconsolewritelinemicrosoftvisualbasicinformationtypenamespanonclickoutputjscripttypeinfoit looks like this is a jscript type how can i access this objectmore detailthe above description is based on my current project the project is to create something like selenium ide it uses webbrowser control instead selenium ide creates 3 different things to record an element in the web document 1 actiontype2 xpath3 valuefor instancetype inputidfoo hello worldclickandwait linklogin selenium ide recognize page load so it changes actiontype between click and clickandwait my case i want to make it simple if i click on the element and if it is anchor tag or has page load kind of javascriptsuch as onclickwindowlocationhrefblah then i want to set the actiontype to clickandwait,['c#'] +158767,understanding nested php ternary operator i dont understand how that output four comesa 2echo a 1 one a 2 two a 3 three a 5 four other prints fouri do not understand why four gets printed,['php'] +158779,set imageview to show image in sdcard i have a image stored in sd card of my phone i want to show it in a image view i know the location of the file on the oncreate of the activity is there a simple way to say something like imageview img imageview findviewbyidridimageview1 string path environmentgetexternalstoragedirectorytostring imagesimagejpg imgsetsrc path please let me know if there is any way to do this thank you,['android'] +158781,firebird backup restore is frustrating is there a way to avoid it i am using firebird but lately the database grows really seriouslythere is really a lot of delete statements running as well updateinserts and the database file size grows really fastafter tons of deleting records the database size does not decrease and even worse i have the feeling that actually the query getting slowed down a bitin order to fix this a daily backuprestore process have been involved but because of it is time to complete i could say that it is really frustrating to use firebirdany ideas on workarounds or solution on this will be welcomeas well i am considering switching to interbase because i heard from a friend that it is not having this issue it is so,['sql'] +158784,c trying to swap values in a vector this is my swap functiontemplate typename tvoid swap t x t y t temp x x y y temp returnand this is my function on a side note v stores strings call to swap values but whenever i try to call using values in a vector i get an error i am not sure what i am doing wrongswapvposition vnextposition creates errors,['c++'] +158790,is there an equivalent of gccs wshadow in visual c wshadow will warn whenever a local variable shadows another local variable is there an equivalent in visual c 2008 i tried w4 but it did not pick up on it i also tried cppcheck but that did not see it eithereg if i inadvertently doclass a private int membervar public void fn int membervar 27 i would really like to know about it,['c++'] +158794,uisearchthisplaycontroller how to preload searchresulttableview i want to show some default content when the user taps the searchbar but before any text is enteredi have a solution working using settext void searchthisplaycontrollerdidbeginsearchuisearchthisplaycontroller controller searchthisplaycontrollersearchbar settext this works but it is not elegant and the hint text in the searchbar thisappearsis there a better way to preload data to the searchresulttableview in a uisearchthisplaycontroller without having to implement the whole uisearch functionality yourself in a custom controllerfor a demo of the desired effect look at safaris search box if you tap it the search interface opens with previous searches showing,['ios'] +158812,c null is it an object when i was writing c code a few days ago i noticed that the compiler complained that i had to cast null to a specific objectdoes this mean that null is simply an uninstantiated version of the type or is it a singleton value of a null class like java even though it has special privilegesedit an example of the code giving the error would bepublic string duplicatestring toduplicate return toduplicate toduplicatepublic string duplicateint toduplicate string asstring toduplicatetostring return asstring asstringpublic static int mainstring args this needs to be cast duplicatenull to duplicatestringnullthe reason i commented on null in java was after reading thisthere is also a special null type the type of the expression null which has no name because the null type has no name it is impossible to declare a variable of the null type or to cast to the null type the null reference is the only possible value of an expression of null type the null reference can always be cast to any reference type in practice the programmer can ignore the null type and just pretend that null is merely a special literal that can be of any reference typefound here is null an object,['c#'] +158820,detect re regexp object in python i wonder what is the proper pythonic backward and forwardcompatible method how check if an object is compiled re objectisinstance method cannot be easily used while the resulting object claims to be sresre pattern object import re rex recompile rex sresre pattern object at 0x7f63db414390but there is no such one import sre sresre patternattributeerror module object has no attribute sre pattern import sre main 1 deprecationwarning the sre module is deprecated please import re sresre patternattributeerror module object has no attribute sre pattern resre patternattributeerror module object has no attribute sre patterni do not want to use duck typing ie checking for the availability of some specific methods because this could collide with some other typesfor now i am using regexptype typerecompile typerex regexptypetruebut there might be a better way,['python'] +158821,writing a double type value to a text file the below code is writing unreadable characters to the text fileint main ofstream myfile exampletxt if myfileis open double value 11234556 char conversion char value strcat conversion 0 myfilewrite conversion strlen conversion myfileclose return 0i want to see the actual number written in the file hints pleaseeditseeing the answers below i modified the code asint main ofstream myfile exampletxt if myfileis open double value 11234556 myfile value myfileclose return 0this produces the putput 112344 while the actual number is 11234556 i want the complete numberediting the post to notify everyonethe unreadable characters are due to ofstreams write function this is an unformatted output functionthis quote is from,['c++'] +158823,default value of boolean in java possible duplicatewhy is javas default value for boolean set to truewhat is the default value of boolean primitive wrapper in java,['java'] +158835,facebookiossdk logout question i have seen a lot of questions here regarding the facebook graph api but i still have not find a solution for simple loginlogout operations using it looks like the single signon style is causing more confusion than benefitsi would like to know if it is possible have the following situationenter in the app no accesstokenexpirationdate createdperform a login using sso by calling authorizedelegate method application goes background and the login is made in the global scope facebook appmobile safari asking for the user credentialsenter back in the app now logged in both accesstoken and expirationdate are saved to nsuserdefaultsperform a logout by calling the logout method now logged out both accesstoken and expirationdate are removed from nsuserdefaultsattempt to perform a login again with exactly the same steps done in 2i realize that when i call logout i do really log out from facebook accesstoken is invalidated from my app scope not from the global scope facebook appmobile safari in 5 when i try to log in again the application goes to background and the login attempt is made again in facebook appmobile safari as usual however i am getting a screen saying that i am already logged inyou have already authorized press okay to continue logged in as not youit is a strange behavior for the user that has just logged out in my appmy question is can i really log out from facebook i mean global scope from inside my app this would affect other apps using the facebook credentials too however if i cannot to do this how can i avoid the strange behavior describe abovethanks,['iphone'] +158851,finding the users my documents path i have this small program and it needs to create a small txt file in their my documents folder heres the code i have for thattextfileopencusersmynamedocumentswlinesstuff goes heretextfilewritelineslinestextfileclosethe problem is that if other people use it how do i change the myname to their account name,['python'] +158852,how to remove a key from hash and get the remaining hash in rubyrails to add a new pair to hash i doa 1 b 2mergec 3 a1 b2 c3is there a similar way to delete a key from hash this worksa 1 b 2reject k k a b2but i would expect to have something likea 1 b 2deletea b2it is important that the returning value will be the remaining hash so i could do things likefoomy hashreject k k my key in one line,"['ruby-on-rails', 'ruby']" +158866,dustjs what about perfomance i like syntax of this template library for js i am going to use it in nodejs script so performance is quite important have anybody tried this one their website works too slow to make me think their library works fast enough,['javascript'] +158894,obtaining ipad touchstart coordinates i would like to obtain the coordinates of a touch event on the ipad in javascript how would i do this,['javascript'] +158897,interfacing with a thirdparty api in rails opeing urls and parsing xmljson i am working on a rails project which will need to interface with multiple thirdparty apis i am pretty new to rails and i have never done this before so i am lacking some basic information here specifically what is the preferred rails way of simply querying an external urlin the php world it was curl you take whatever the resource url is throw curl at it and start processing the response whether it be xml json etcso whats the curl equivalent in rails while were at it what is the preferred method of parsing xml and json responses my instincts are to google around for some ruby gems to get the job done but this is such a practical problem that i wouldnt be surprised if the rails community had already worked out a triedandtrue solution to this kind of problemif it is of any contextual value i plan to run these thirdparty api interactions as nightly cronjobs probably all packaged up as custom rake tasksthanks for sharing your expertise,['ruby-on-rails'] +158899,how to set the contenttype charset in the request header using a html link i have a simple htmlpage with a utf8 encoded link html head meta httpequivcontenttype contenttexthtml charsetutf8 head body a charsetutf8 hrefhttpserversearchqc3bcsearch for a14a bodyhtmlhowever i do not get the browser to include contenttypeapplicationxwformurlencoded charsetutf8 into the request header therefore i have to configure the webserver to assume all requests are utf8 encoded uriencodingutf8 in tomcat serverxml but of course the admin would not let me do that in the production environment webspherei know it is quite easy to achieve using ajax but how can i control the request header when using standard html links the charset attribute does not seem to work for me tested in ie8 and ff 35the 2nd part of the required solution would be to set the url encoding when changing an iframes documentlocation using javascript,['html'] +158913,how to change a javascript singleton to something that can be used multiple times a bit of an architectural questioni originally created a javascript singleton to house methods needed to operate a photo gallery module in a template file for a cms system the original specification only called for one instance of this photo gallery module on a page the code below is a gross simplification of what i actually wroteshortly after releasing the code it dawned on me that even though the specification called for one instance of this module this code would fall apart if a page had two instances of the module ie the user adds two photo galleries to a page via the cms now the html markup is safe because i used class names but how would i go about restructuring my javascript and jquery event listeners to be able to handle multiple modules you may assume that each photo gallery has its own jsonp file or you may assume a single jsonp file if you think it can be handled more elegantly with one jsonp filei think my original jquery event listeners might have to be converted to delegate but i have no clue what to do after that and what to do about converting my singleton any leads would be appreciated if you offer code i prefer readability over optimization i am not asking this question because i have an immediate need to solve the problem for work i am asking this question to be forwardthinking and to be a better javascript developer because i am expecting to run into this problem in the future and want to be preparedthank you for readinghtmldiv classphotogallerymod div classphotogalleryimgboximg src altintro photo div div classphotogalleryimgcappcaptionpdiv a href classphotogalleryprevimglnka a href classphotogallerynextimglnka divthe javascript is an external static file and makes a call to a jsonp file via getscript created by the cmsjavascriptjqueryfunction photogallerymodule json numslidesinjson currentslide updateslide function arg slidnum update the slide here init function arg jsonobj thisjson arg jsonobj thisnumslidesinjson thisjsonphotogalleryslideslength thiscurrentslide 0 documentreadyfunction getscriptphotogalleryjson photogalleryprevimglnkliveclick functionevent photogallerymodulecurrentslide photogallerymodulecurrentslide 1 photogallerymoduleupdateslidephotogallerymodulecurrentslide eventpreventdefault photogallerynextimglnkliveclick functionevent photogallerymodulecurrentslide photogallerymodulecurrentslide 1 photogallerymoduleupdateslidephotogallerymodulecurrentslide eventpreventdefault jquerycontents of photogalleryjsonphotogallerymoduleinit photogalleryslides type intro pagetitle intro photo imgurl imgaltattr intro photo captiontext the intro photo type normal pagetitle first photo imgurl imgaltattr first photo captiontext the first photo type normal pagetitle second photo imgurl imgaltattr second photo captiontext the second photo,"['javascript', 'jquery']" +158926,convert international string to you codes in java how can i convert an international eg russian string to u numbers unicode numberseg u041eu041a for ok,['java'] +158930,keeping stdlist iterators valid through insertion note this is not a question whether i should use list or deque it is a question about the validity of iterators in the face of insertthis may be a simple question and i am just too dense to see the right way to do this i am implementing for better or worse a network traffic buffer as a stdlistchar buf and i am maintaining my current read position as an iterator readposwhen i add data i do something likebufinsertbufend newdatabegin newdataendmy question is now how do i keep the readpos iterator valid if it points to the middle of the old buf then it should be fine by the iterator guarantees for stdlist but typically i may have read and processed all data and i have readpos bufend after the insertion i want readpos always to point to the next unread character which in case of the insertion should be the first inserted oneany suggestions short of changing the buffer to a stddequechar which appears to be much better suited to the task as suggested belowupdate from a quick test with gcc44 i observe that deque and list behave differently with respect to readpos bufend after inserting at the end readpos is broken in a list but points to the next element in a deque is this a standard guaranteeaccording to cplusplus any dequeinsert invalidated all iterators that is no good maybe using a counter is better than an iterator to track a position in a deque,['c++'] +158939,when tracking outbound links with google analytics why delay the outbound click instead of pushing a function into the queue the official suggestion for tracking outbound links with the asynchronous version of google analytics is to push an tracking event into the queue likegaqpush trackevent outbound settimeoutdocumentlocation 100would it not be better to push an anonymous function into the ga queue likegaqpush trackevent outbound gaqpushfunction documentlocation in the settimeout version there is no guarantee that the event will be processed before the redirect occurs whereas in the second version it would only redirect after the event is processedaright,['javascript'] +158955,linq query to return thistinct field values from a list of objects class objint typeid 10 types 09 string uniquestring this is uniqueassume there is list with 100 elements of obj but only 10 unique typeidsis it possible to do write a linq query return the 10 unique ints from the list of objs,['c#'] +158969,php checking for return false just a quick question and i am sure really basici have the following codefunction checkthingsfoo bar if valid return results else return false on the other end of this i am currently doingcheck checkthingsfoo barif check false echo error else echo checkis writing the following the samecheck checkthingsfoo barif check echo error else echo checkwhich method is the preferred method if both are correctthanks,['php'] +158974,how to check all checkboxes within a div in jquery editthanks for the answers guys it does look correct and it works on jsfiddlenet but in my code the alert fires well yet nothing happens to the checkboxes selectchbclickfunction checkboxpropchecked true alert1 deselectchbclickfunction checkboxpropchecked false alert2 div idchbdiv classuiwidget uiwidgetcontent uicornerall brbr table width90 border0 aligncenter cellpadding5 cellspacing0 tr td colspan2followingtd tdnbsptd tr tr td width25 alignleftinput typecheckbox idcheck1 label forcheck1nbsplabeltd td width45 aligncenterimg srcface 01jpg width32 height32td tdandrew lloyd webbertd tr tr td width25 alignleftinput typecheckbox idcheck2 label forcheck2nbsplabeltd td width25 aligncenterimg srcface 02jpg width32 height32td tdrichard bransontd tr tr td width25 alignleftinput typecheckbox idcheck3 label forcheck3nbsplabeltd td width25 aligncenterimg srcface 03jpg width32 height32td tddmitry medvedevtd trtable br table width90 border0 aligncenter cellpadding5 cellspacing0 tr tda href idselectchb classuistatedefault uicornerallspan classuiicon uiiconcheckspanselect allanbsp a href iddeselectchb classuistatedefault uicornerallspan classuiicon uiiconclosespandeselect allatd tdnbsptd tdnbsptd tr tablebrdiv br div classuiwidget uiwidgetcontent uicornerall,['jquery'] +158983,is there a proved mouseover workaround for firefoxdriver in selenium2 i am using selenium java 20b3 i have this codewebdriver driver new internetexplorerdriverselenium seleniumdriver new webdriverbackedseleniumdriver httplocalhost8088sistemarenderedwebelement menuregistrar renderedwebelementdriverfindelementbyxpathanormalizespaceregistrarseleniumdrivermouseoveranormalizespaceregistrar makes element visible menuregistrarclickseleniumdrivermouseoutanormalizespaceregistrarworks like a charm with internetexplorerdriver with ie 8 but it does not with the firefoxdriver with firefox 4 i have tried a lot of things with the code and nothing works and i must use the firefoxdriver because the application i am testing does not behave well with ieas you might guess the registrar link is hidden until the mouseover event triggersany proved workarounds thanks for your timeedit also tried chromedriver with chrome 11 did not work either if there is a workaround that works with chrome i will take itanswer working code with selenium java 20rc1 windows 7 firefox 4 thanks to andy tinkham and luke inmansemerauget the element that shows menu with the mouseover eventwebelement menu driverfindelementbyxpathdividnavli3the element that i want to click hiddenwebelement menuoption driverfindelementbyxpathanormalizespaceregistrarbuild and perform the mouseover with advanced user interactions apiactions builder new actionsdriver buildermovetoelementmenubuildperformthen click when menu option is visiblemenuoptionclicknote the advanced user interaction api uses nativeevents on the browsers which is not supported cross platform so this code might not work just like that if you change the os that is why i added the os and browser detail see question in selenium users group,['java'] +159011,jquery isotope possible chrome bug i am using jquery isotope to fill in the spaces on a multiwidth multiheight grid equal proportionsthe grid is sorted using uisortable with a button to toggle back to isotope after sorting there are some sort orders that leave empty blocks how can i use isotope to fill in the spacesi have experimented with multiple isotope layout methods see documentreadyfunction var itemlist sortable itemlistisotope resizescontainer false masonry rowheight 250 columnwidth 325 wpadminbareditclickfunction itemlistisotopedestroy itemlistsortable do ajax stuff with uisort order toggle back to isotope after jquery uisortable ajax stuffdocumentreadyfunction wpadminbarsortclickfunction sortableisotope resizescontainer false masonry rowheight 250 columnwidth 325 udatethe desired affect is achieved in firefox 4 and ie 8 9 but the issue seems to be with google chrome latest version stable channelchromefirefox 4,['jquery'] +159023,php code deployment tips in the past i have been developing in a very amateurish fashion meaning i had a local machine where i developed and tested code and a production machine to which i copied the code when i was done recently i modified this slightly to where i developed locally checked the code into svn and then updated the production machine through svnnow i would like to start a new project and improve my workflow ideally i had the following in mindhave one or more local dev environmentsdevelop and test on local machinesuse svn or git as code repositoryuse a build tool to set up new environments either dev staging or production and deploy codesince i am not very familiar with this process i am looking for suggestions on how to best set this idea up and the tools to use especially when it comes to the build tools i was looking into ant and phing possibly make but i am so new to this that i would really like to get some guidance are there any good tutorials or books about php deployment especially for beginners what i am especially interested in are the following topicsdeployment to different types of servers with different settings eg dev uses different db db passwords php error reporting than production or stagingdeployment that automatically pulls code from svndeployment that temporarily sets a maintenance page for production environmentonce i mastered the above maybe even do some testing in the build processi know my question might sound quite confused i admit i am new to this and might be a little off the target in what i really need that is why any help is greatly appreciated,['php'] +159038,where to find the implementation of stdioh possible duplicatewhere to find stdioh functions implementations hi i am trying to find the function definitions of the functions defined in stdioh header file i want to learn how functions like printf is achieved but i cannot find any preprocessor directives link in stdioh to the implementation file elsewhere how can a c compiler know where to find the implementations when there are no direct references to the function definition file i learned that h file may accompany with a same name c implementation file from an objectivec book could you help me thanks i am using gcc on mac os x,['c'] +159059,how to make apk secure protecting from decompile helloi am developing an application for a company and our application contain a database of sqlite which contain personal information and we want to protect ithow can we protect it because an apk is easily decompile completely because i did it myselfso now the question is how to secure an apk and also how to protect my database that is in the phone after installing app on phone,['android'] +159090,how to limit speed of internet connection on android emulator i need to test app for work with slow internet connectionhow to simulate slow internet connection on android emulator,['android'] +159091,customizing seekbar in android i want to customize seekbar in android can anybody guide me how it can be done i am new to android,['android'] +159109,android thisable listview selection i have a listview that i rethisplay with the correct answer highlighted when the user selects an item however at that point i would like to thisable selection of list view items the user can only get to the next question by pressing a button however even if i thisable the items like so private void thisableitemselection listview lv getlistview for int i 0 i lvgetchildcount i view v lvgetchildati vsetenabledfalse it still highlights the selection when the user selects it any thoughts,['android'] +159111,motionevent gety and getx return incorrect values i have following situationi have a custom listview with imageview and textview in a rowthe imageview has an ontouchlistener wchich invokes my ontouch method here are some lines from itif eventgetactionmotioneventaction move layoutleftmargin int eventgetx dragicongetwidth2 layouttopmargin int eventgety dragicongetheight2 logdtag pozycja eventgetx eventgetydragiconsetlayoutparamslayoutwhen move is detected i am showing up new image not this in listview and i am starting to move it according to x and y coordinatesthe problem is that getx and gety return positions relative to imageview in the list not the whole listview i think so so when i touch an item in the middle and swipe finger up then gety returns negative values above imageview boundaryhope i explained clearlyany ideas how to get this coordinates relative to the screen sizethank you,['android'] +159114,getasynckeystate and virtualkeysspecial characters using jna java i am working on a twoway private chat that will work in a full screen gamethis is required to let the user to type into a semitransparent textbox at the top of the screen even when it does not have focususing the following code i can detect all physical keys but have a tough time with virtual keys shift is detected2 is detectedhowever shift 2 are detected both as separate keys even though shift2 gives on my keyboard ie the program outputs both shift and 2 but not what they produce the problem is how will i convert to a character depending on the keyboardfor exampleon a uk keyboard shift2 will give me quoteson a us keyboard shift 2 will give me how can i convert to a specific character depending on the keyboardhere is the code so farstatic interface user32 extends library public static user32 instance user32 nativeloadlibraryuser32 user32class short getasynckeystateint key short getkeystateint key intbyreference getkeyboardlayoutint dwlayout int mapvirtualkeyexw int ucode int nmaptype intbyreference dwhkl boolean getkeyboardstatebyte lpkeystate int tounicodeexint wvirtkey int wscancode byte lpkeystate char pwszbuff int cchbuff int wflags intbyreference dwhklpublic static void mainstring args long currtime systemcurrenttimemillis while systemcurrenttimemillis currtime 20 for int key 1 key 256 key if iskeypressedkey getkeytypekey private static boolean iskeypressedint key return user32instancegetasynckeystatekey 32767private static void getkeytypeint key boolean isdownshift user32instancegetkeystatevk shift 0x80 0x80 boolean isdowncapslock user32instancegetkeystatevk caps 0 byte keystate new byte256 user32instancegetkeyboardstatekeystate intbyreference keyblayoutid user32instancegetkeyboardlayout0 int scancode user32instancemapvirtualkeyexwkey mapvk vk to vsc keyblayoutid char buff new char10 int bufflen bufflength int ret user32instancetounicodeexkey scancode keystate buff bufflen 0 keyblayoutid switch ret case 1 systemoutprintlnerror break case 0 no translation break default systemoutprintlnoutput stringvalueofbuffsubstring0 ret it works fine and outputs the keys pressed but does not work with shift combinations i realize that i could do a switch and change shift3 to a but this will not work with different keyboards,['java'] +159128,dkim in net mailmessage and alternativeviews i am using dkimnet to sign a mailmessage before sending it to a recipient the problem i am facing is that the component above signs mailmessages body mailmessagebody while i am inserting content as both html and plain text in the form of alternativeviewsthe result is that my mailmessagebody is null but the received mesages body contains my alternative views therefore dkim does not verify correctlyis there any way to resolve this problem maybe sign the html and plain text alternative views before assigning them to the mailmessage object or maybe using another componentedit since i started this question i ve created a project at this is by no means complete or stable but i m posting it here in case its of any use to anyone looking to find a solution for signed alternative views in net,"['c#', '.net']" +159139,multivariate spline interpolation in pythonscipy is there a library module or other straightforward way to implement multivariate spline interpolation in pythonspecifically i have a set of scalar data on a regularlyspaced threedimensional grid which i need to interpolate at a small number of points scattered throughout the domain for two dimensions i have been using scipyinterpolaterectbivariatespline and i am essentially looking for an extension of that to threedimensional datathe ndimensional interpolation routines i have found are not quite good enough i would prefer splines over linearndinterpolator for smoothness and i have far too many data points often over one million for eg a radial basis function to workif anyone knows of a python library that can do this or perhaps one in another language that i could call or port i would really appreciate it,['python'] +159159,retrieving the coordinates of the mysql point type i am storing latlong pairs in mysql as a point using something likegeomfromtextpoint32 122given the point how do i retrieve the individual xy coordinates,['mysql'] +159164,migrating small app to high replication datastore the current recommendation from google is that all apps start migrating to the high replication datastore my app is small and still in development my understanding is that the more data my app accumulates the more involved the transition process will be so i have decided to migrate asap while i still only have 56k of user data i followed the documentation on downloading all data from a masterslave app i have the downloaded data i have deployed my app to high replication when i try to use the upload command from the same section in the documentation however i get an error heres what i am trying to runcusershankdocumentsaptana studio 3 workspacehanksandboxappcfgpy upload data applicationessayhost kinduser filenamesandboxed and the error i get file cprogram files x86googlegoogle appenginegoogleappenginedatastoredatastore rpcpy line 1048 in check rpc success raise todatastoreerrorerrgoogleappengineapidatastore errorsbadrequesterror app sessayhost cannot access app essayhosts datathat is the last line of a very long traceback if you need more let me know if you know of a good thorough walkthrough for this process please link it most of what i am finding is a little out of my depth ps anyone know how to upload all kinds at once,['python'] +159168,java networking best practice mixed synchronous asynchronous commands i am developing a small clientserver program in javathe client and the server are connected over one tcpconnection most parts of the communication are asynchronous can happen at any time but some parts i want to be synchronous like acks for a sent commandi use a thread that reads commands from the sockets inputstream and raises an oncommand event the command itself is progressed by the commanddesignpatternwhat would be a bestpractice approach java to enable waiting for an ack without missing other commands that could appear at the same timeconsendpacketnew packetabc wait for abc ackedit1think of it like an ftpconnection but that both data and controlcommands are on the same connection i want to catch the response to a controlcommand while dataflow in the background is runningedit2everything is sent in blocks to enable multiple different transmissons over the same tcpconnection multiplexingblock1 byte blocks type2 byte blocks payload lengthn byte blocks paylod,['java'] +159171,ruby mechanize multiline value for textarea gets merged edit upon further testing it seems like the issue is sitespecific and should theoretically work just finetextarea values which should be on multiple lines are being submitted all on one linetextarea values value1nvalue2form pageform withid form id hereformmy textarea textarea valuessubmit formbutton withvalue submitformclick buttonsubmitthe value being submitted is value1nvalue2 instead of being on multiple lines as intendedis there another way to add form values that i can try,['ruby'] +159173,trouble with constnonconst overload resolution i have a class that looks something like thisclass classa public float getint num const protected float getint numoutside of the class i call the get function float foo classainstancegetii expect this to call the public version but instead visual studio errors outerror c2248 classaget cannot access protected member declared in class classawhen commenting out the protected overload and removing all references to it the code compiles why does the compiler try to use the inaccessible member when an accessible one is available is there an accepted way to force the compiler to choose the correct overload is there a reference to the resolution rules for member functions somewhere,['c++'] +159185,resharper red underline on type inference in vs 2010 i am getting a strange error in vs 2010 i have a project set to use net framework 4 when i type the codevar record returns ienumerablestaffvar staff new staffrepositorygetall the method has two signatures createselectlistienumerableobject enumerable string value createselectlistidictionaryobject object enumerable string valuestafflist selectlisthelpercreateselectliststaff recordstaffcreateselectlist basically takes an enumerable of objects converts them to strings using tostring and then autoselects the string passedthe problem is this code gets a red underline in vs 2010 with an error saying that it cannot resolve the methodhowever if i change the code to explicitly say the typeienumerablestaff staff new staffrepositorygetallstafflist selectlisthelpercreateselectliststaff recordstaffvs 2010 no longer gives the error my understand of generics is that these two fragments of code should be the same to the compiler so why is it giving me an error underlinealsothis will also fix the problemvar staff new staffrepositorygetallstafflist selectlisthelpercreateselectlistfrom s in staff select s recordstaffresharperi have tried deleting my resharper directory but no luck i still get the underline however if i suspend ie turn off resharper the red underline goes away so it is definitely being caused by resharpercodeas requested heres the codeheres staffrepositorynamespace fooclientbusinessrepositories public class staffrepository staffrepositorybasestaff staffcriteria thiscriminator public staffrepositorythiscriminator thiscriminator basethiscriminator protected override staff createstaffmembershipuser user return new staffuser end classheres staffrepositorybase where getall is definednamespace foocommonbusinessrepositories public abstract class staffrepositorybasetstaff tstaffcriteria tthiscriminator istaffrepositorytstaff tstaffcriteria tthiscriminator where tstaff class istafftthiscriminator where tstaffcriteria class istaffcriteria protected abstract tstaff createstaffmembershipuser user public virtual ienumerabletstaff getall return from you in membershipgetalluserscastmembershipuser let s createstaffu where sthiscriminatorequalsthiscriminator select s public virtual ienumerabletstaff getalimitcriteria criteria var staffs getall skipcriteriaskipgetvalueordefault takecriteriatakegetvalueordefault return staffs public virtual ienumerabletstaff getall return from you in membershipgetalluserscastmembershipuser let s createstaffu where sthiscriminatorequalsthiscriminator select s,['c#'] +159195,memory alignment check i want to check whether an allocated memory is aligned or not i am using aligned mallocsize align and it returns a pointer can i check it by simply dividing the pointer content by 16 for example if the the pointer content is divisible by 16 does it mean that the memory is aligned by 16 bytes,['c'] +159213,overloading virtual operator this is just an experiment codestruct b virtual b operator return this void foo edit intentionally not virtualstruct d b virtual d operator return this void foo int main b pb new d pbfoo calls bfoo i know that operator has to be called using object or reference thus in above case does reference pb still resolute to the object of b though it will not be practical but for curiosity is there any way to invoke doperator through pb,['c++'] +159215,platform independent devnull in c possible duplicateimplementing a noop stdostream is there any stream equivalent of null in c i want to write a function that takes in a stream if the user wants to have the internal outputted to somewhere but if not the output goes into some fake placevoid datastdstream stream fake stream stream data i want to be able to chose to do data or datastdcout,['c++'] +159224,how can i see the details of an exception in pythons debugger sometimes while i am debugging an exception will be raisedfor example consider this codedef some function pretend this function is in a library and deep within the library is an exception raise exceptionan exception message with valuable informationimport pdb pdbset tracetry some function pretend i am debugging from this point using pdbexcept passwhile debugging from the some function call if i issue a next command i will see the following details about the exception that was raised and caughtexception exceptioationheres a straight copy paste from the terminal i was working in tmptestpy7module some function pretend i am debugging from this point using pdbpdb nextexception exceptioation tmptestpy7module some function pretend i am debugging from this point using pdbpdb it would be useful to see the entire exception message how can i do this in pdb,['python'] +159226,python named pipes problem i am trying to setup two way communication beween a daemon and a client using named pipes the code hangs while trying to open the named pipe used for input whyclass commthreadingthreaddef init self selfsrvoutf tmpserverout selfsrvinf tmpserverin if ospathexistsselfsrvoutf selfpipein openselfsrvoutf r hangs here else osmkfifoselfsrvoutf selfpipein openselfsrvoutf r or here if ospathexistsselfsrvinf selfpipeout osopenselfsrvinf oso wronly else osmkfifoselfsrvinf selfpipeout osopenselfsrvinf oso wronly threadingthread init self,['python'] +159228,about showing continuous slider value in uislider heres what i want to do with ui slider i have a bunch of files with times and i show them based on slider value the problem is i want to show the slider value when the user is changingmoving the slider in other words the value should change and be shown on the screen as the user is moving the slider and not afterwardscan anyone please give me any idea how to do it thanks,['ios'] +159232,moving text around in a div without moving the div i have a div inside the div is a background image that looks like a button and i have text in the div saying home by default the text is snapped to the top and does not look right how could i move the text around in the div without moving the divcss filehtml file,"['css', 'html']" +159267,aspnet mvc why model is null i have the following structure controllercspublic actionresult pagemainstring param return viewpagemaincsnamespace project1models public class pagemain public datatable dtable get some code that returns a datatable and finally in the viewusing project1modelsmodel pagemainvar datatable modeldtable but this is throwing an error since the model is nulldoes anyone know why my model is returning null how can i access the datatable in the pagemaincs i am new to mvc so if i have any logical error in the structure please do not hesitate in warning me,['c#'] +159274,css textalign center not working i have the following htmldiv idfooter ul idmenuutilitynavigation classlinks clearfix li classmenu685 menusite map firstsite map li li classmenu686 menuprivacy policyprivacy policy li li classmenu687 menuterms conditionsterms amp conditions li li classmenu688 menucontact us lastcontact us li uldivwith the following cssdivfooter fontsize 10px margin 0 auto textalign center width 700pxi threw in the fontsize bit just to see if the style was working firebug reports it is working but i wanted to see it is working but the text is not centered in the footer in firefox or in safari have yet to check it in ie i tried with and without margin 0 auto and with and without textalign center no combo of those things worked here is out put from firebugdivfooter fontsize 10px margin 0 auto textalign center width 700pxinherited fromdivpageskiptonav page lineheight 15eminherited frombodyhtmlbody color 6 fontfamily verdanaarialsansserifhelp,['css'] +159276,programmatically put a mac into sleep i cannot find any instructions how to put a mac programmatically into sleep mode in objectivec i am sure it should be only one line but could you give me a hint,['objective-c'] +159280,how to align text in richtextbox c how do i align the text in a richtextboxbasically the rtb containstestingtestingtestingtestingwhich all have the same number of characters but have different alignments how can i align them properly im fairly new to c and confused since it aligned properly in javas textareathank you,['c#'] +159286,python lambda function what is happening herereducelambda xy xy x for x in range110 if x 3 0 or x 5 0i understand how x is iterating through all of the numbers from 1 to 9 and taking out those that are divisible by 3 or 5 but the lambda xy xy part is stumping me,['python'] +159303,how is the memory of returned c types handled under gc according to the documentation for nsstrings method utf8stringthe returned c string is automatically freed just as a returned object would be released you should copy the c string if it needs to store it outside of the autorelease context in which the c string is createdso under retainrelease memory management the following method const char givemeacstring nsstring string i am a string return string utf8stringis fine so long as the calling method treats the returned const char as it would an autoreleased objecthowever under garbage collection there is not an autorelease context as far as i am aware and c types are not garbage collected so it does not look like the gc will treat the returned pointer as it would a returned objectwhat is its lifespan tied to is it still freed at a point in the threads runloop that is reliably later on or does it behave differently under gc than under nongc,['objective-c'] +159311,is arrayadapter thread safe in android if not what can i do to make it thread safe lets say i extend arrayadapter and in the code where i am overriding getviewint i view v viewgroup g i retrieve the current item using getitemi can i be sure that getitemi will return an item even if other threads manipulate the same arrayadapteri am not sure but i think the answer is no if it is what do you suggest i do to make it threadsafe,['android'] +159320,java using multiple delimiters in a scanner i am using a scanner to take input and hopefully split it into chunks i want it to split it up using whole word delimiters so right now i have scanner scanner new scanner1 imported bottle of perfume at 2799 scannerusedelimitersdelimitonesso with input word word delimitone word word delimittwo word word i get outputword wordword word delimittwo word wordi was hoping scannerusedelimitersdelimitonessdelimittwosmight work but alas nothow do i go about achieving the following outputword wordword wordword word,['java'] +159324,jquerypjax vs historyjs to load specific content when clicked i need to ajaxify my site like loading a spinner or something for rendering specific content in a page when clicking a linki have found 2 good jquery pluginswhat is their main difference it seems they are doing the same job well maybe one uses the ajax then returns the html pjax and one uses a socalled html5 push state or somethingis there another way doing this simpler or with only jquery i think it is too overkill to use either of those plugins but i am not sure if there is a simpler way for doing this,['jquery'] +159330,what is the difference between map and grep in jquery what is the difference between map and grep in jqueryi want a simple answer as far as possible,"['javascript', 'jquery']" +159337,is it a good idea to dynamically change the names of processing threads in java we have a java application that processes requests naturally there is a thread pool with threads named with some insignificant names like processor1 processor2 etc we are wondering whether it is a good idea to rename the processing thread each time it gets a request to a name that would indicate which request is being processedi have a feeling that something is wrong about it but cannot think of a good reason i can remember several cases of analyzing multithreading issues from thread dumps and it was very important to me to know whether i see the same thread in two consecutive dumps or not however i realize that i could look at the thread id instead in log4j logs it is a common practice to write the thread name and i remember many cases of filtering by it but still i am not sure i have a good line of defense herewhat is the common practice is it a good idea to keep renaming threadsthere are related questions like renaming threads in java or should threads in java be named for easier debugging but they do not address this specific issue,['java'] +159354,mouse hover on webelement using selenium 2 in java possible duplicateis there a proved mouseover workaround for firefoxdriver in selenium2 i want to be able to mouse hover a webelement with the java selenium2 api is that possible i am using the current beta 3,['java'] +159358,linux ubuntu c language virtual to physical address translation as the title suggests i have a problem of obtaining the physical address from a virtual onelet me explain given a variable declaration in process space how can i derive it is physical address mapped by the osi have stumbled upon some sys calls asmioh where the virt to phys function is defined however it seems this header is outdated and i cannot find a work around however ioh is available at usrsrclinuxheaders263528genericarchx86includeasm my current kernel is 263528 but ioh is not included in usrincludeasmso to reiterate i need a way to get the physical address from virtual preferably derived from within the application at runtime but even a workaround of using a monitor of procpidmaps will doany ideas or comments would be greatly appreciatededitafter doing a bit of research on this topic i found something that helps in this regardit turns out this is more than doable although requires a bit of a workaroundhere is a link to a simple app that analyses the current mapped pagesthe file in question turns out is a binary file procpidpagemap contains the physical mapping of virtual pages anyway the code in that link can be modified to serve as a monitor app or somethingi needed the physical address for cache simulation purposesthanks for all the help and answers,['c'] +159389,jquery new line n possible duplicatewhats the cleanest way to write a multiline string in javascript how does one go onto a new line in writing jquery code not the actual output of the code for examplefooappenddiv idbla n divsomething like that,"['javascript', 'jquery']" +159401,out of memory exception when using httpwebrequest to stream large file i get an out of memory exception when using httpput of a large file i am using an asynchronous model as shown in the code i am trying to send 8k blocks of data to a windows 2008 r2 server the exception consistently occurs when i attempt to write a block of data that exceeds 536868864 bytes the exception occurs on the requeststreamwrite method in the code snippet below looking for reasons why note smaller files are put ok logic also works if i write to a local filestream running vs 2010 net 40 on win 7 ultimate client computer httpwebrequest request httpwebrequestwebrequestcreatehttpwebsitefileserverfilename requestmethod webrequestmethodshttpput requestsendchunked true requestallowwritestreambuffering true requestbegingetrequeststream new asynccallbackendgetstreamcallback state int chunk 8192 other values give same result private static void endgetstreamcallbackiasyncresult ar long limit 0 long filelength httpstate state httpstatearasyncstate stream requeststream null end the asynchronous call to get the request stream try requeststream staterequestendgetrequeststreamar copy the file contents to the request stream filestream stream new filestreamstatefilename filemodeopen fileaccessread filesharenone chunk fileoptionssequentialscan binaryreader binreader new binaryreaderstream filelength streamlength set position to the beginning of the stream binreaderbasestreamposition 0 byte filecontents new bytechunk read file from buffer while limit filelength filecontents binreaderreadbyteschunk the next 2 lines attempt to write to network and server requeststreamwritefilecontents 0 chunk causes out of memory after 536868864 bytes requeststreamflush i get same result with or without flush limit chunk important close the request stream before sending the request streamclose requeststreamclose,['c#'] +159422,how do i integrate mongodb with solr i have seen this question before but it is never received a real answer so i was wondering can someone point me in the right direction as to how i can integrate mongodb with solr i am looking for pseudo realtime and eventual consistencycan anyone that is done this shed some lighti am also using phpzend with doctrine mongo if that helpsthanks in advance,['php'] +159434,what is the mime type for properties files what is the mime type for properties file here is a list of all the files with different extensions but here i could not see any mime type for the properties filemime typesi have a properties file in my scripts folder and i am trying to read it in another scripts when run as simple html file and a script file it works properly but when i put it in my web application which uses spring mvc its not able to read the properties filethe error i get is no media type found for servletcontext resource messages enproperties returning 404please help,['javascript'] +159452,templates for code which is similar but not identical i have a bunch of functions which read completely identical except for one line of code which is different depending on the type of input parameterexamplevoid funcstdvectorint input dosomethinggeneral1 dosomethingspecialwithstdvectorinput dosomethinggeneral2void funcint input dosomethinggeneral1 dosomethingspecialwithintinput dosomethinggeneral2void funcstdstring input dosomethinggeneral1 dosomethingspecialwithstdstringinput dosomethinggeneral2i wonder how i could avoid this duplication using a templatelike mechanism if i understand specialization correctly it does not avoid to have the code of the specialized functions twice,['c++'] +159459,expressions in javascript ternary operator and jslint i recently received a comment on one of my blog posts about jslint asking why jslint threw an error with the followings test myfunc myfunc2the error generated wasexpected an assignment or function call and instead saw an expressionclearly jslint is expecting an assignment here somthing more likevar y s test myfunc myfunc2but i do not really see the problem with the first example is it really the case that ternary operators should only be used for assignmentsi could not see anything on jslintcom nor was there anything apparent in the book javascript the good parts and the same error is also reported in the community fork jshintanyone,['javascript'] +159478,jquery bug animation problem on mouse out i have a div on a page with the following properties div width100px background0ff height100px i am animating the borderradius of the div on mouse hover event the animation works fine when the mouse is entering but the animation stops working when the mouse is coming out of the div you can see the live code on jsfiddle here when you will enter the div the borderradius is smoothly getting animated but when the mouse is coming out the animation doesnt work and the borderradius changes instantaneouslywhere is the problem with the codeand one more thing if i move the mouse inandout on the div too fast and then wait the divanimation is going on it does not stopthe link to the code,['jquery'] +159495,how to get the size of an image in java hi i am using jtidy parser in javaurl url new url image image new imageiconurlgetimageint imgwidth imagegetwidthnullint imgheight imagegetheightnullabove code is working finei am getting height width properlybut i want to see the size of an image for example whether it is in kbor in mb please help mehow to get the size of an imageis there any method,['java'] +159497,how to add a scrollbar to a stackpanel in my wpf application i have a stackpanel containing several controls inside them how can i add a scrollbar to this stackpanel,['c#'] +159504,fragment already added illegalstateexception i use this method on my container activity to show a bfragpublic void showbfrag start a new fragmenttransaction fragmenttransaction fragmenttransaction mfragmentmgrbegintransaction ifmbfragisadded logdlog tag show bfrag fragmenttransactionshowmbfrag else logdlog tag replacing afrag bfrag fragmenttransactionreplaceridoperation fragments frame mbfrag keep the transaction in the back stack so it will be reversed when backbutton is pressed fragmenttransactionaddtobackstacknull commit transaction fragmenttransactioncommit i call it from my container activity for the first time gets into the else statement and mbfrag replace mafrag then i press the back buttonand the operation is reversed mafrag is shown but does mbfrag is removed then i go forward again by calling showbfrag from the same activity and it gets again into the else statement so i can deduce that mbfrag is not addedbut i got a fragment already added illegalstateexception so why it did not get into the if statement insteadsowhy is the isadded method not returning true if i am getting a fragment already added illegalstateexception does popbackstack operation completely remove previously added fragmentswhat behaviour am i misunderstanding edithere is the complete info of the exception0607 120832730 errorandroidruntime8576 javalangillegalstateexception fragment already added bfrag40b28158 id0x7f0c00850607 120832730 errorandroidruntime8576 at androidappbackstackrecorddoaddopbackstackrecordjava3220607 120832730 errorandroidruntime8576 at androidappbackstackrecordreplacebackstackrecordjava3600607 120832730 errorandroidruntime8576 at androidappbackstackrecordreplacebackstackrecordjava3520607 120832730 errorandroidruntime8576 at mypackagenamecontaineractivityshowbfrag this line fragmenttransactionreplaceridoperation fragments frame mbfrag,['android'] +159524,what is the meaning of double curly braces initializing a cstruct i am currently working with legacy c code successfully compiled with gcc 29xi have been asked to port this legacy code to gcc 34x most of the errors were easily corrected but this particular one puzzles methe context struct tmessage theader header tdata data struct theader tenum myenum tbool validity what was done const tmessage init 0 later in the code tmessage message initmy questions what is the meaning of the operator does it initialize the first field the header to a binary 0 does it initialize the first field of the first structure the enum to literal 0 the 346 error i get is invalid conversion from int to tenum either with one or two pairs of curly brackets how can i set my structure to a bunch of 0s without using memset thanks in advance,"['c++', 'c']" +159526,multiple background images gradient sprite this relates specifically to the compass framework for sassi have created a sprite and also a gradient mixin is it possible to combine the two on the same item and if so howimport compasscss3import iconpnginclude alliconspritesmixin lightgradient include backgroundimagelineargradienttop dark 20 light 100 color dark textshadow lightbutton include lightgradient include iconspritesearchupdatei have come up with this solution can anybody improve on itimport compasscss3import compassutilitiesspritesicon spritemapiconpnglightgradient lineargradientbottom shade2 20 shade3 100iconsearch spriteicon search norepeatbutton include backgroundlightgradient iconsearch,['css'] +159548,pagination using ajax in jquery datatables i am using datatables plugin for a table on a page i am working on its basically fetching rows through an ajax call and in this ajax call i send the search params that the user selects and the page number requiredi need the next previous first and last buttons to also fire the same ajax call but with different page numbers as the backend interceptor depends on the page numberthis api call would return total no of rowssay 10 belonging for these search params and the rows with the page size say 50is there any way i can use data table to do this,['jquery'] +159559,find the most frequent number in a numpy vector suppose i have the following a 1231213221how to find the most frequent number in this list in a neat way,['python'] +159600,how to add an object into an array how can i add an object into an array in javascript or jqueryfor example what is the problem this code language langjs function var a new array var b new object a0bi would like to use this code to save many objects into the array in function1 and call function2 to use the object in arrayhow can i save an object into an arrayhow can get an object in an array and save it to a variable,['javascript'] +159607,what is the correct usage of datacontextrefresh i have a linqtosql object in memory whose field values on the database are expected to change during the lifetime of the object so periodically i need to check if everything is still in sync i was expecting to be able to do this like somydatacontextrefreshrefreshmodekeepcurrentvalues myobjbut unfortunately this seems to have no effect the values on myobj remain the same even when the db values have changed msdn documentation on this method is pretty scant can anyone tell me what i am missing here,['c#'] +159634,python thinking of a module and its variables as a singleton a clean approach i would like to implement some sort of singleton pattern in my python program i was thinking of doing it without using classes that is i would like to put all the singletonrelated functions and variables within a module and consider it an actual singletonfor example say this is to be in the file singleton modulepy singleton modulepy singletonrelated variablesfoo blahbar stuff functions that process the above variablesdef worksome parameter global foo bar if some parameter bar else foo then the rest of the program ie other modules would use this singleton like so another modulepyimport singleton module process the singleton variables which changes them across the entire programsingleton modulework freely access the singleton variables at least for readingprint singleton modulefoothis seemed to be a pretty good idea to me because it looks pretty clean in the modules that use the singletonhowever all these tedious global statements in the singleton module are ugly they occur in every function that processes the singletonrelated variables that is not much in this particular example but when you have 10 variables to manage across several functions it is not prettyalso this is pretty errorprone if you happen to forget the global statements variables local to the function will be created and the modules variables would not be changed which is not what you wantso would this be considered to be clean is there an approach similar to mine that manages to do away with the global messor is this simply not the way to go,['python'] +159640,how to customize hashcode and equals generated by eclipse it is recommended and sometimes necessary classes that represent values value classes to override hashcode equals and optionally tostring methodsthe values that these methods return depend on all or subset of the member variables of the class and its superclass to implement them properly you have to know a little bit of theory about hashing and a little bit of algebra and set theory not too much and almost everything is explaind in the javadocs for these methods and in effective java form josh blochin most of the cases the implementation of this methods follow a template and ides like eclipse jdt include tools to generate them however the tool generators can not make any assumptions and generate these methods using only constructs available in the language and the standard library because of that these methods usually look very uglyanother way to implement these methods is to use library like apache is commonslang hashcodebuilder equalsbuilder and tostringbuilder using these utilities one can implement their own hashcode and equals methods that look much bettermy question is about combining these two approaches i would like to be able to customize eclipses hashcode and equals generators so that will generate them using hashcodebuilder and friendsis it possible and how to do this without tweaking the jdt only writing small plugin that will override the default implementations but without changing jdt codethanks,['java'] +159679,updating table rows in postgres using subquery using postgres 84 my goal is to update existing tablecreate table publicdummy address id serial addr1 character40 addr2 character40 city character25 state character2 zip character5 customer boolean supplier boolean partner booleanwith oidsfalseinitially i tested my query using insert statementinsert into address customersupplierpartnerselect case when custaddr1 is not null then true else false end customer case when suppladdr1 is not null then true else false end supplier case when partnaddr1 is not null then true else false end partnerfrom select from address pa left outer join cust original cust on paaddr1custaddr1 and paaddr2custaddr2 and pacitycustcity and pastatecuststate and substringcustzip15 pazip left outer join supp original suppl on paaddr1suppladdr1 and paaddr2suppladdr2 and pacitysupplcity and pastatesupplstate and pazip substringsupplzip15 left outer join partner original partn on paaddr1partnaddr1 and paaddr2partnaddr2 and pacitypartncity and pastatepartnstate and pazip substringpartnzip15 where paaddress id address idbeing newbie i am failing converting to update statement ie updating existing rows with values returned by select statementany help is highly appreciated,['sql'] +159693,how to read shapes properties in visio i have the following task i am writing an addin for visio 2010 on c in studio 2010 let us say that i have a diagram opened and i have a shape of any kind in this diagram let us try to manage one shape for the begining the question is how can i read any properties of this shape which api should i usebasic algorithmscan opened document for shapesif there are any shapes in document then return an array or a list of all shapes null is returned in case of no shapes in current documentrun over shapes array and read any property for each element that would be great to have a chance to writemodify propertycode example would be greatly appreciated,['c#'] +159708,count all duplicates of each value i would like a sql query for ms jet 40 mssql to get a count of all the duplicates of each number in a databasethe fields are id autonum number text i have a database with a lot of numberseach number should be returned in numerical order without duplicates with a count of all duplicatesnumberfields containing 1 2 2 3 1 4 2 should return1 2 2 3 3 1 4 1,['sql'] +159722,unloading the assembly loaded with assemblyloadfrom i need to check the time amount to run gettypes after loading the dllthe code is as followsassembly assem assemblyloadfromfilesw stopwatchstartnewvar types1 assemgettypesswstopdouble time1 swelapsedtotalmillisecondsi would like to unload and reload the dll to check the time to spend in running gettypes againhow can i unload it assem null is good enough is there an explicit way to call garbage collector to reclaim the resource allocated to assem,['c#'] +159726,java replace issues with apostrophesingle quote and backslash together i seem to be having issues i have a query string that has values that can contain single quotes this will break the query string so i was trying to do a replace to change to here is a sample codethis is itreplace the output for this is stillthis is itit thinks i am just doing an escape character for the quoteso i tried these two pieces of codethis is itreplace for the backslash and a charthis is itreplace for the backslash and for the charboth of the above still results in the same outputthis is iti can only seem to get this to actually spit out a slash withthis is itreplace which results inthis is itany suggestions i just want to replace a with it does not seem like it should be that difficult,['java'] +159737,is there any way to change the color of text halfway through a character on a webpage one thing i have seen in some desktop applications is the ability to change the color of text as the background changes to effectively have multiple colors on a single character i have seen this most commonly with progress bars that thisplay the percentage inside the bar generally a darker background color will be used as the progress bar color and as it progresses the dark color does not contrast enough with the dark text so the text color changes as soon as the bar overlaps with the text this image should explain what i meanas you can see the text is black when it is at 0 when there is no dark background when the background image fully progresses to 100 the text is completely white but in the middle as you can see at 50 the text is half blackhalf white and it is actually split on the 0 character in this exampleis there any way to do this at all on a webpage css images jquery otherwise preferably not flash or a java applet though i am really wondering whether an htmlbased solution is possible thanks,"['html', 'css']" +159745,am i supposed to thispose redirected standardoutputstandarderror if i redirect standardoutputstandarderror when creating a process object should i thispose the streamreaders when i no longer need the process object using reflector i see that processthispose does not do this for me unless i am missing something,['.net'] +159751,how to pass string value from one form to another forms load event in c i need to pass a string value from form1public void button1 clickobject sender eventargs e string departmentname it form2 frm2 new form2 frm2show thishideinto the form2 load event for exampleprivate void form2 loadobject sender eventargs e messageboxshowdepartmentname or string sql1 select service name from service employeeservice where e dep departmentname and s id service id,['c#'] +159756,ruby bindings for gtk 3 iave spent some time learning ruby and i wanted to move over to some gui programming gnome 3 is the environment most appealing to me at the moment so i thought i would have a look at gtk 3 however the gtk 3 documentationas getting started examples in c were quite offputting are there less scary ruby bindings and hello world examples availableedit the gtk language bindings overview does not leave much room for hope,['ruby'] +159772,generic operations on c containers how to write generic operations on c stl containers for example java has collection interface which every java containers except for maps implements i can do operations like add remove contains and iterations regardless of whether the actual container is linkedlist hashset arrayblockingqueue etc i find it very powerfulc has iterators but what about operations like add and removevector has push back set has insert queue has push how to add something to c container in a generic way,['c++'] +159798,should i use stdfor each i am always trying to learn more about the languages i use different styles frameworks patterns etc i have noticed that i never use stdfor each so i thought that perhaps i should start the goal in such cases is to expand my mind and not to improve the code in some measure readability expressiveness compactness etcso with that context in mind is a good idea to use stdfor each for simple tasks like say printing out a vectorfor eachvbegin vend int n cout and endl the int n being a lambda function instead offorint i0 ivsize i cout vi endl i hope this question does not seem pointless i guess it almost asks a larger question should an intermediate programmer use a language feature even though he does not really need to at this time but just so that he can understand the feature better for a time that may actually greatly benefit from it although this larger question has probably already been asked eg here,['c++'] +159803,how to convert bool to int in mysql i am new to mysql so i do not know many things like casting of data types how can i convert bool to int in mysql and also how can i convert decimal to int in mysql,['mysql'] +159843,thread confinement i am reading java concurrency in practice and kind of confused with the thread confinement concept the book says thatwhen an object is confined to a thread such usage is automatically threadsafe even if the confined object itself is notso when an object is confined to a thread no other thread can have access to it is that what it means to be confined to a thread how does one keep an object confined to a threadeditbut what if i still want to share the object with another thread let us say that after thread a finishes with object o thread b wants to access o in this case can o still be confined to b after a is done with itusing a local variable is one example for sure but that just means you do not share your object with other thread at all in case of jdbc connection pool does not it pass one connection from one thread to another once a thread is done with that connection totally clueless about this because i never used jdbc,['java'] +159853,thisplay javautildate in a specific format i have the following scenario simpledateformat dateformat new simpledateformatddmmysystemoutprintlndateformatparse31052011gives an output tue may 31 0 sgt 2011but i want the output to be 31052011 i need to use parse here because the dates need to be sorted as dates and not as stringany ideas,['java'] +159858,how to retrieve day month and year from timestamplong format i need to retrieve day year and month from a timestamp object as long numberspublic long gettimestampday string idate new simpledateformatddmmy formatnew dateborn dategetdate return day just the day public long gettimestampmonth string idate new simpledateformatddmmy formatnew dateborn dategetdate return month just month public long gettimestampyear string idate new simpledateformatddmmy formatnew dateborn dategetdate return year just year born date is a timestamp objectis it possible to do thatthanks in advance,['java'] +159864,javascript performance global variable vs jquerys data i need to store relatively larget bit of json for global access in my web appshould i use jquerys datadocumentbody somereferencehere myjsonobj or a globali know binding data to documentbody is faster than to a jquery object but how does this compare to global variablei am interested the most efficient memory usage,"['javascript', 'jquery']" +159867,unit testing with moq let us say i have a plain class with several functionspublic class myclass public int gettotalint myvalue string mystring if myvalue 10 return gettotalmyvalue else return gettotalmystring public int gettotalint myvalue return myvalue 25 12 156 public int gettotalstring mystring return mystringlength 25 48 27 i would like to unit test my first function and mock the others int gettotalint myvalue and int gettotalstring mystring in order to test only the code inside the main function i am using moq as the mocking framework are there some tricks which would allow me to get the code from the function i want to test and mock the inner call to the other functions or should i have to call a second object like this to mock everythingpublic class mycalculator public int gettotalint myvalue return myvalue 25 12 156 public int gettotalstring mystring return mystringlength 25 48 27 public class myclass mycalculator calculator public myclassmycalculator calculator calculator calculator public int gettotalint myvalue string mystring if myvalue 10 return calculatorgettotalmyvalue else return calculatorgettotalmystring i know the latest is the cleanest way but i have a lot of functions calling themselves one after the other so that would make a lot of classes to writeupdatemock implementation of thomas answerpublic class myclass public int gettotalint myvalue string mystring if myvalue 10 return gettotalmyvalue else return gettotalmystring public virtual int gettotalint myvalue return myvalue 25 12 156 public virtual int gettotalstring mystring return mystringlength 25 48 27 testclasspublic class test testmethod public void myclass gettotal mockmyclass mymockedclass new mockmyclass callbase true mymockedclasetupx xgettotalitisanyintreturns1 mymockedclasetupx xgettotalitisanystringreturns2 var actual mymockedclassobjectgettotal0stringempty assertareequal2actual update 2see gishu answer also for a more global look on this issue,['c#'] +159870,get cstyle type reference from clrstyle type full name given a net type object found through reflection is it possible to pretty print or decompile this type as a c declaration taking into account c type aliases etcfor exampleint32 intstring string nullableint32 intlistaunetexampleobject listexampleobjecti want to be able to print out methods close to what was originally written in the sourceif there is not anything in the net framework is there a thirdparty library i might possibly have a look at ilspy,['c#'] +159878,convert pixels to sp i need the current textsize of the textview in sp units but gettextsize returns the size in pixels so is there a way to convert pixels to sp,['android'] +159893,jschexception algorithm negotiation fail i am trying to connect to remote sftp server over ssh with jsch 01441 but during sessionconnect i am getting this exception comjcraftjschjschexception algorithm negotiation fail at comjcraftjschsessionreceive kexinitsessionjava529 at comjcraftjschsessionconnectsessionjava291 at comjcraftjschsessionconnectsessionjava154 logs from jschinfo connecting to xport 22 info connection established info remote version string ssh20weonlydo 206 info local version string ssh20jsch0144 info checkciphers aes256ctraes192ctraes128ctraes256cbcaes192cbcaes128cbc3desctrarcfourarcfour128arcfour256info aes256ctr is not available info aes192ctr is not availableinfo aes256cbc is not available info aes192cbc is not availableinfo arcfour256 is not available info ssh msg kexinit sentinfo ssh msg kexinit received info thisconnecting from x port 22 i am able to log in to remote server with linux sftp command i was trying to find any kind of clue in the internet but i faileddebug output from linux sftp commandopenssh 55p1dam 12 openssl 098r 8 feb 201debug1 reading configuration data etcdamsshssh configdebug1 applying options for debug1 applying options for debug1 connecting to x x port 22debug1 connection establisheddebug1 identity file spv id rsakey type 1debug1 identity file spv id rsakeycert type 1debug1 remote protocol version 20 remote software version weonlydo 206debug1 no match weonlydo 206debug1 enabling compatibility mode for protocol 20debug1 local version string ssh20openssh 55p1dam 12debug1 ssh2 msg kexinit sentdebug1 ssh2 msg kexinit receiveddebug1 kex serverclient aes256cbc hmacmd5 nonedebug1 kex clientserver aes256cbc hmacmd5 nonedebug1 sending ssh2 msg kexdh initdebug1 expecting ssh2 msg kexdh replydebug1 host x is known and matches the rsa host keydebug1 found key in sshknown hosts8debug1 ssh rsa verify signature correctdebug1 ssh2 msg newkeys sentdebug1 expecting ssh2 msg newkeysdebug1 ssh2 msg newkeys receiveddebug1 roaming not allowed by serverdebug1 ssh2 msg service request sentdebug1 ssh2 msg service accept receiveddebug1 authentications that can continue publickeydebug1 next authentication method publickeydebug1 trying private key spv id rsakeydebug1 read pem private key done type rsadebug1 authentication succeeded publickeydebug1 channel 0 new clientsessiondebug1 entering interactive sessiondebug1 sending subsystem sftpconnected to xsftp,['java'] +159896,first letter is number in string i was trying to find a quick and easy method to check if the first letter in a string is a number a lot of the functions and methods i have seen on so seem over complicated i am wondering would something like this workis numericstring0,['php'] +159899,how to create a shared object file from static library how to create a shared object file from a static library i am using cygwinis the following syntax correctgcc shared o libexampleso libexamplea,['c'] +159905,rake runs all my cucumber tests fine but cucumber does not have the steps i have inherited a rails 3 app and am trying to get to grips with the existing cucumber tests i have got the following setup in the apps features folder i have missed out any files which are not relevant eg extra features and stepsfeatures people newpersonfeature step definitions people stepsrb web stepsrb support envrb pathsrb selectorsrbif i run rake then it runs all the features in featurespeoplenewpersonfeature correctly using the steps listed in step definitions however i do not want to run rake every time as it takes too long i just want to run a specific test in cucumber eg cucumber featurespeoplenewpersonfeature l 8when i do this it runs the feature but has not loaded the steps i get this backusing the default profilefeature add a new person in order to allocate tasks to people as a community manager i want to add a new person scenario secondary navigation should contain add new person featurespeoplenewpersonfeature8 given i am on the new person page featurespeoplenewpersonfeature9 undefined step i am on the new person page cucumberundefined featurespeoplenewpersonfeature9in given i am on the new person page then i should not see add new person featurespeoplenewpersonfeature10 undefined step i should not see add new person cucumberundefined featurespeoplenewpersonfeature10in then i should not see add new person1 scenario 1 undefined2 steps 2 undefined0m05syou can implement step definitions for undefined steps with these snippetsgiven i am on the new person page do pending express the regexp above with the code you wish you hadendthen i should not see do arg1 pending express the regexp above with the code you wish you hadendif you want snippets in a different programming language just make sure a filewith the appropriate file extension exists where cucumber looks for step definitionswhy is not cucumber loading the steps in i am guessing that i need to require the steps somewhere but i cannot work out wherethanks maxedit found the answer here in configcucumberyml there is a line that looks like thisstd opts format envcucumber format pretty strict tags wipchange it to std opts format envcucumber format pretty strict tags wip require featuresthis is like adding require features to the end of your cucumber test run and makes it load everything up properly,['ruby-on-rails'] +159917,predefined function for minimum possible duplicateis there a convenient function in objectivec cocatouch to find a lowest number import foundationfoundationhint main int argc const char argv nsautoreleasepool pool nsautoreleasepool alloc init int a10b5c cminab nslogmindc pool drain return 0i have to calculate the minimum value of two numberswe can use ifab to find out the minimum valuebut is there any predefined function to calculate the minimum of two numbers,['objective-c'] +159940,java are all monitors released when thread waits on an object before a thread can wait on an object it has to acquire a monitor on that object the monitor is then released and the thread attempts to reacquired it once it awakesbut what happens to other monitors the thread holds when it calls waitconsider this example object a object b synchronizeda synchronizedb bwait continue when the thread calls bwait will it release the locks on both a and b or only b,['java'] +159966,how can nsarray be this slow i am coming from a cstl world and i wanted to check how objectivec containers are in comparison to stl i wanted to compare an array of numbers but the only way to add a number to an nsarray is using nsnumber which is utterly slow and drank my ram empty so i guess i need to dealloc them manually but i do not want to test side effects so i just added nsnull null into the array the results of adding 10k things into array 1k timesnsarray 0923411 secondsvectorint 0129984 seconds i thought it might be allocations and deallocations so i set the number of arraysimax in the code to 1 and number of additions to 10jmax but it was even slowernsarray 219859 secondsvectorint 0223471 seconds editas mentioned in the comments the constant increasing size of the array might be the problem so i made nsarray using arraywithcapacity but vector with reserve too and it was even slower than before imax 1 jmax 10nsarray 255942vectorint 019139end edit why is this so slowmy code for referenceimport foundationfoundationhinclude vectorinclude iostreaminclude timehusing namespace stdint main int argc const char argv int imax 10 int jmax 10 nsautoreleasepool pool nsautoreleasepool alloc init cout vector insertions endl clock t start clock forint i 0 i imax i vectorint v new vectorint forint j 0 j jmax j vpush backj delete v double interval clock start doubleclocks per sec cout interval seconds endl cout nsarray insertions endl start clock forint i 0 i imax i nsmutablearray v nsmutablearray alloc init forint j 0 j jmax j v addobjectnsnull null v dealloc interval clock start doubleclocks per sec cout interval seconds endl pool drain return 0,['objective-c'] +159975,what are patterns you could use with prototype inheritance that you cannot with class everyone seems to generally agree that prototype inheritance is simpler and more flexible than class inheritance what i have not seen in the literature that i have read is very many examples of things that you can do with prototype inheritance that you cannot with classical so i pose a simple questionwhat are some patterns that you can use with prototype inheritance that you cannot with class inheritance and what is the guidance you would give as far whenif to use it,['javascript'] +159980,working example of createjobobjectsetinformationjobobject pinvoke in net i am struggling to put together a working example of pinvokeing createjobobject and setinformationjobobject through various google searches including russian and chinese posts i have cobbled together the following code i think the definition of jobobject basic limit information changes based on platform 3264bit the createjobobjectassignprocesstojobobject seems to work setinformationjobobject fails either with error 24 or 87 process myprocess populated somewhere else create job assign this process and another process to the jobintptr jobhandle createjobobject null null assignprocesstojobobject jobhandle myprocesshandle assignprocesstojobobject jobhandle processgetcurrentprocesshandle ensure that killing one process kills the others jobobject basic limit information limits new jobobject basic limit informationlimitslimitflags shortlimitflagsjob object limit kill on job closeintptr pointertojoblimitinfo marshalallochglobal marshalsizeof limits marshalstructuretoptr limits pointertojoblimitinfo false setinformationjobobject job jobobjectinfoclassjobobjectbasiclimitinformation piontertojoblimitinfo uint marshalsizeof limits dllimport kernel32dll entrypoint createjobobjectw charset charsetunicode public static extern intptr createjobobject securityattributes jobattributes string lpname public class securityattributes public int nlength useless field 0 public intptr psecuritydescriptor n public bool binherithandle 3414341234n 12n 34212 n public securityattributes thisbinherithandle true thisnlength 0 thispsecuritydescriptor intptrzero dllimport kernel32dll static extern bool setinformationjobobject intptr hjob jobobjectinfoclass jobobjectinfoclass intptr lpjobobjectinfo uint cbjobobjectinfolength public enum jobobjectinfoclass jobobjectassociatecompletionportinformation 7 jobobjectbasiclimitinformation 2 jobobjectbasicuirestrictions 4 jobobjectendofjobtimeinformation 6 jobobjectextendedlimitinformation 9 jobobjectsecuritylimitinformation 5 structlayout layoutkindsequential struct jobobject basic limit information public int64 perprocessusertimelimit public int64 perjobusertimelimit public int16 limitflags public uintptr minimumworkingsetsize public uintptr maximumworkingsetsize public int16 activeprocesslimit public int64 affinity public int16 priorityclass public int16 schedulingclass public enum limitflags job object limit active process 0x08 job object limit affinity 0x010 job object limit breakaway ok 0x0800 job object limit die on unhandled exception 0x0400 job object limit job memory 0x0200 job object limit job time 0x04 job object limit kill on job close 0x020 job object limit preserve job time 0x040 job object limit priority class 0x020 job object limit process memory 0x0100 job object limit process time 0x02 job object limit scheduling class 0x080 job object limit silent breakaway ok 0x010 job object limit workingset 0x01 dllimport kernel32dll return marshalas unmanagedtypebool static extern bool assignprocesstojobobject intptr hjob intptr hprocess structlayout layoutkindsequential public struct security attributes public int nlength public intptr lpsecuritydescriptor public int binherithandle,"['c#', '.net']" +159998,mvvm and ioc handling view models class invariants this is an issue i have been struggling with since i started using mvvm first in wpf and now in silverlighti use an ioc container to manage the resolution of views and viewmodels views tend to be very basic with a default constructor but viewmodels tend to access real services all of which are required for their construction again i use an ioc container for resolution so injecting services is not a problemwhat does become a problem is passing required data to the viewmodel using ioc as a simple example consider a screen that allows the editing of a customer in addition to any services it might require the viewmodel for this screen requires a customer object for thisplayingediting the customers datawhen doing any type of nonmvvm library development i consider it an unbendable rule that class invariants be passed via the constructor in cases where i need contextspecific data for class construction time and the class in question is containermanaged i tend to use an abstract factory as a bridge in mvvm this seems like overkill as most viewmodels will then require their own factorya few other approaches i have triedconsidered included 1 an initializeload method in which i pass the data which violates the rule of forcing class invariants through the constructor 2 passing data through the container as parameter overrides unity and 3 passing data through a global state bag ughwhat are some alternative ways to pass contextspecific data from one viewmodel to the next do any of the mvvm frameworks address this specific problemwhich can have its own problems like requiring a choice between a call to containerresolve or not having your viewmodel containermanaged castle windsor has a good solution to this but afaik no other framework doesediti forgot to add some of the options i listed are not even possible if you are doing view first mvvm unless you pass data first to the view and then to the viewmodel,['c#'] +160068,jquery can the empty method be given a duration in jquery can the empty method be given a duration such that the object fades to empty over a period of time for example 500 millisecondshere is the current codeobject to be emptiedempty,['jquery'] +160077,same jquery event separate function say that i have a function that needs to execute on documentmousemove then i decide i have another function that needs to execute on the same event perhaps these two functions are unrelated so in the name of modularity one could have two separate functions listening for documentmousemove is this bad form are there performance implications,"['jquery', 'html']" +160119,how to iterate over a wildcard generic how can i iterate over a wildcard generic basically i would like to inline the following methodprivate t extends fact void iteratefactsfactmanagert factmanager for t fact factmanager factmanagerdosomethingfact if this code is in a separate method as shown it works because the generic method context allows to define a wildcard type here t over which one can iterate if one tries to inline this method the method context is gone and one cannot iterate over a wildcard type anymore even doing this automatically in eclipse fails with the following uncompilable codefor factmanager factmanager factmanagers for fact factmanager factmanagerdosomethingfact my question is simply is there a way to put some wildcard type one can iterate over or is this a limitation of generics meaning it is impossible to do so,['java'] +160121,do any php libraries exist for parsing asn1 or generating php code based on it i have already looked myself but it seems my googlefu is not strong todayi am working to develop a standardized protocol for exchanging data structures over a tcpip connection between an apache php server and embedded c code on a microcontrollerwe are using asn1 notation and what i would really like to do is to have a piece of php code that can parse the asn1 document and use it to interpret incoming data it would produce a php object or array that is structured appropriately based on the asn1 the goal here would be for the php that parses the document and creates the objects to be agnostic of the document specifics ie not handcoded to match the document contentsalternatively if this is not possible does something exist that would let me generate simple php data transfer object classes that i could rerun each time the asn1 protocol document changed this might actually be preferable from an efficiency perspective as you wouldnt have to reinterpret the asn1 for each incoming requestthanks let me know if i can provide any additional clarification that would help to answer this question,['php'] +160123,backbonejs and rails how to handle params from backbone models in a standard rails controller i would create a record like thisuser usernewparamsuserthis assumes that the form parameters that come in are nestedi have been playing with backbonejs and i noticed that by default backbone does not nest the parameters the way a normal rails form might which is actually something i expected so i am wondering what i should dodo ifigure out on the serverside if it is a request from backbone by looking at accepts headers etc and manipulate the params myself so i can keep my controller code smalldo some params manipulation withparamsuser usernewparamsuserrespond to do format if usersave formathtml redirect to users url formatjson render json userto json endendor do i instantiate the object in each branch which ends up with repeated code but might be more maintainable in the long runrespond to do format formathtml do user usernewparamsuser if usersave redirect to users url end end formatjson do user usernewparams and rely on massassignment protection if usersave render json userto json end endendor do i modify my backbonejs models by overriding the tojson method which i am not entirely sure how to do because i do not know enough about backbonejs yet so that it nests the paramsin this situation i have access to both sides of the app but i am interested in what others are doing,['ruby-on-rails'] +160139,is there a way to pass command line options to my ios app from xcode i am hoping to find a method to pass certain information in to my app when i launch it during testing so that i can perform special debug tasks xcode has a section arguments passed on launch and i assumed they would show up in my uiapplicationdelegates applicationdidfinishlaunchingwithoptions but the dictionary that is passed in is always nil am i going about this the wrong way,['ios'] +160145,keep nsthread alive and run nsrunloop on it so i am starting a new nsthread that i want to be able to use later by calling performselectoronthread from how i understand it calling that methods add that call to the runloop on that thread so on its next iteration it will pop all these calls and subsequently call them until there is nothing left to call so i need this kind of functionality an idle thread ready for work that i just can call upon it my current code looks like this voiddoinitialize mthread nsthread alloc initwithtargetself selectorselectorrunthread objectnil mthread start voidrunthread nsautoreleasepool pool nsautoreleasepool alloc init from what i understand from the google machine is that this call should start the runloop on this thread but it does not the thread dies and is uncallable nsrunloop currentrunloop run pool drain voidschedulesomethingonthread self performselectorselectorhardwork onthreadmthread withobjectnil waituntildoneno but the thread is not kept alive and the performselectoronthread does not do anything how do i go about this the right way,['objective-c'] +160177,tuple aggregate construction which infers types and elides movecopy constructor calls consider the following mypair class i am not sure if this is the best way to do things but it seems to workinclude iostreamstruct a a aconst a stdcout copy stdendl aa stdcout move stdendl stdstring stemplate class t0 class t1struct mypair t0 x0 t1 x1template class t0 class t1 int and 1struct get class templateclass t0 class t1struct get classt0 t1 0 static t0 get funcmypairt0 t1 x return xx0 static const t0 get funcconst mypairt0 t1 x return xx0 static t0 get funcmypairt0 t1 x return stdmovexx0 templateclass t0 class t1struct get classt0 t1 1 static t1 get funcmypairt0 t1 x return xx1 static const t1 get funcconst mypairt0 t1 x return xx1 static t1 get funcmypairt0 t1 x return stdmovexx1 template int n class t0 class t1auto getmypairt0 t1 x decltypeget classt0t1nget funcx return get classt0t1nget funcx define make pairx1 x2 mypairdecltypex1 decltypex2x1 x2int main auto x make paira a get0x get1xideone linkthe answer when is aggregate initialization valid in c11 says we can elide copiesmoves by doing aggregate initialization hence we can construct mypairs using make pair without the need to perform any moves or copiesi would like to generalize make pair to make tuple ie take any number of argumentsrequirements are as with make pair1 types are inferred 2 movescopies are elided when constructing from temporaries ie construction happens in placeexisting library solutions eg boost will be fine though i would prefer something which accepts rvalue references or just code here is great also or a mix of the twoif it is at all possible i would like it if it optimized out empty members whilst still eliding movescopy constructor calls but i have a feeling that is asking too much,['c++'] +160193,why does not stringsubstring share memory with the source string as we all know strings in net are immutable well not 100 totally immutable but immutable by design and used as such by any reasonable person anywaythis makes it basically ok that for example the following code just stores a reference to the same string in two variablesstring x sharkstring y xsubstring0 prooffixed char c y c4 pconsolewritelinexconsolewritelineythe above outputssharpsharpclearly x and y refer to the same string object so heres my question why wouldnt substring always share state with the source string a string is essentially a char pointer with a length right so it seems to me the following should at least in theory be allowed to allocate a single block of memory to hold 5 characters with two variables simply pointing to different locations within that immutable blockstring x sharkstring y xsubstring1 does c0 point to the same location as x1fixed char c y c0 p apparently notconsolewritelinexconsolewritelineythe above outputssharkpark,"['c#', '.net']" +160196,insert contact to sim from android i have an issue while i try to copy a contact which exists in the android contacts application to the sim card following is the codecontentvalues cv new contentvaluescvputtag cnamecvputnumber cnumberuri uri contextgetcontentresolverinsertsim content uri cvlogdtag log uri is urii have values inside cname and cnumber variables but when i print the log to see the value of the uri variable it is nullcan anyone please let me know if i have gone wrong somewhere in the code above for inserting to sim,['android'] +160211,php mail attachment problems can someone help me figure out why this keeps returning falseto from website subject test attachment emailseparator md5time carriage return type we use a php end of line constanteol php eol attachment namefilename documentpdfpdfdoc is pdf generated by fpdfattachment chunk splitbase64 encodepdfdoc main headerheaders from fromeolheaders mimeversion 10eol headers contenttype multipartmixed boundaryseparatoreoleol headers contenttransferencoding 7biteolheaders this is a mime encoded messageeoleol messageheaders separatoreolheaders contenttype texthtml charsetiso88591eolheaders contenttransferencoding 8biteoleolheaders messageeoleol attachmentheaders separatoreolheaders contenttype applicationoctetstream namefilenameeol headers contenttransferencoding base64eolheaders contentthisposition attachmenteoleolheaders attachmenteoleolheaders separator send messageif mailto subject headers echo mail send ok else echo mail send error,['php'] +160221,does html entity decode replaces also if not how to replace it i have a situation where i am passing a string to a function i want to convert nbsp to a blank space before passing it to function does html entity decode does it if not how to do iti am aware of str replace but is there any other way out,"['php', 'html']" +160237,stringreplace ignoring case i have a string called hello worldi need to replace the word world to csharpfor this i usestringreplaceworld csharpbut as a result i do not get the string replaced the reason is case sensitiveness the original string contains world whereas i am trying to replace worldis there any way to avoid this case sensitiveness in stringreplace method,['c#'] +160247,how to make accountmanager authtoken and openid work together without appengine i am making an android app which should be able to get data from a web service which is not part of gae users are able to log in to web service through their browser by using openid only google accounts are allowed accountmanager can give me authtoken i could save this authtoken on my server together with users google account name email and then use this account name to connect his openid login with app registrationbut this does not solve anything because i have no way to verify this token against users openid information or do i i thought i could use users authtoken to somehow link his android account to the web accountthis looks more and more like a wrong way to handle this but i do not want to save users googles usernamepassword in sharedpreferences and use these data for loginany creative ideas thanks,['android'] +160251,how to get mac address of the wifi interface in android i am using the following codewifimanager wifimgr wifimanager appgetsystemservicecontextwifi servicereturn wifimgrgetconnectioninfogetmacaddressproblem is the wifi must be enabled in the device in order for me to read its addresshow can i still read the mac of the wifi even if the wifi is off,['android'] +160258,jquery ui when using multiple buttonsets radiobuttons they forget their state i am coding a form with two different button sets once one of them is clicked the other one does not thisplay that it is checked any longerscript typetextjavascript documentreadyfunction mode buttonset language buttonset scriptdiv idlanguage input typeradio idlang de namemode checkedchecked valuede label forlang dedeutschlabel input typeradio idlang en namemode valueen label forlang enenglischlabeldivdiv idmode input typeradio idmode1 namemode checkedchecked valuehtml label formode1mailoutputlabel input typeradio idmode2 namemode valuesource label formode2mailsourcecodelabeldivonce clicked the other one is not checked any longer or at least it isnt thisplayed as checked has someone else stumpled upon this problemcheers,"['jquery', 'html']" +160260,concurrency in amazon s3 i am currently building a system where s3 will be used as a persistent hashset the s3 url is inferred from the data by lots of computers across the internet if two nodes store the same data then it will be stored using the same key and it will therefore not be stored twice when an object is removed i need to know whether some other nodes is using that data as well in that case i will not remove it right now i have implemented it by adding a list of the storing nodes as part of the data written to s3 so when a node is storing the data the following happensread the object from s3deserialize the objectadd the new nodes id to the list of storing nodesserialize the new object the data to store and the nodelistwrite the serialized data to s3this create a form of idempotent reference counting since requests over the internet can be quite unreliable i do not want to just count the number of storing nodes that is why i am storing a list instead of a counter in case a node sends the same request 1 times this approach works as long as two nodes are not writing simultaneously s3 does not as far as i know provide any way to lock the object so that all these 5 steps become atomic how would you solve this concurrency issue i am considering implementing some form of optimistic concurrency how should i do that for s3 should i perhaps use a completely different approach,['c#'] +160279,phonegap api to query calogs i have just started with phonegap and android built basic samplesi would like to know if there is an api to get the call logs i wish to create a grid showingnumber of missed calls over a period of timenumber of received calls number of calls madetotal time of the received calls and calls madethanks in advance,['android'] +160301,can i use linqs except with a lambda expression comparer i know i can call linqs except and specify a custom iequalitycomparer but implementing a new comparer class for each data type seems like an overkill for this purpose can i use a lambda expression to provide the equality function like when i use where or other linq functionsif i cannot is there an alternative,"['c#', '.net']" +160307,how to encrypt long strings in php i am using phps openssl public encrypt to encrypt data using rsa but it would not encrypt data larger than a certain sizehow can i get it to encrypt data of an arbitrary length,['php'] +160326,stl container that preserves order of insertion but allows no duplicates possible duplicatea stdmap that keep track of the order of insertion i am looking for an stl container that preserves order of insertion no sorting but does not allow duplicates is there one if not any tricks i can use to customize one,['c++'] +160328,wpf toggle panel visibility i have two panels only one should be visible at the same time i change between them by clicking a button one on each panel is there a nice way to do this in xaml without codebehind or viewmodel,['c#'] +160333,scheduling a regular event croncron alternatives including celery something i have had interest in is regularly running a certain set of actions at regular time intervals obviously this is a task for cron rightunfortunately the internet seems to be in a bit of thisagreement therelet me elaborate a little about my setup first my development environment is in windows while my production environment is hosted on webfaction linux there is no real cron on windows right also i use django and whats suggested for djangocelery of course unfortunately setting up celery has been more or less a literal nightmare for me please see error message no handlers could be found for logger amultiprocessinga using celery and this is only one of the problems i have had with celery others include a socket error which it i am the only one ever to have gotten the problemdo not get me wrong celery seems really cool unfortunately there seems to be a lack of support and some odd limitations built into its preferred backend rabbitmq unfortunately no matter how cool a program is if it does not work well it does not workthat is where i hope all of you can come in i would like to know about cron or a cronequivalent which can be set up similarly preferably identically in both a windows and a linux environmenti have been struggling with celery for about two weeks now and unfortunately i think it is time to toss in the towel and give up on it at least for now,['python'] +160348,tsql select previous dates records i want to select all records from a table log where the dateandtime field values of type datetime are for the day before today whatever day it isso if today is 20110608 i want to select all rows where dateandtime is greater than or equal to 20110607 0 and also less than 20110608 0i am guessing the potential pitfall here would be it is behaviour on the 1st day of the month as obviously a date like 20110600 is invalid and should be 20110531,['sql'] +160353,join if exists in a mysql query i am running a report that exports the information for members of committees into an excel spreadsheetheres my queryselect membership organizationname as firm membership individualfirst as firstname membership individualmiddle as middlename membership individuallast as lastname membership individualemail as email membership individualphone as phone membership locationaddr1 as address1 membership locationaddr2 as address2 membership locationcity as city membership locationstate as state membership locationzipcode as zip from membership individual join membership organization on membership individualorg name id membership organizationid join membership location on membership individuallocation id membership locationid where membership individualid in list if ids order by lastnamethe problem is some of the members do not have a location id set or it is set to 0 so those members do not show up in the reportis there a way i can qualify the location join if the members location id exists pull the info if not show me the info that is available,"['mysql', 'sql']" +160364,cannot remove or find an object in javas copyonwritearrayset i use copyonwritearrayset to store one instance of a custom class which looks like thispublic class myclass string name public myclastring name name name override public int hashcode return namehashcode override public boolean equalsobject obj if obj this return true if obj instanceof myclass false return false myclass otherobject myclass obj return nameequalsotherobject name override public string tostring return name when i print the set everything seems okmyclass theobject new myclassobject 1copyonwritearraysetmyclass theset new copyonwritearraysetthesetaddtheobjectfor myclass tmp theset systemoutprintlntmptostringthe result isobject 1so obviously the object is in the setnow i want to remove the object from the setthesetremovetheobjectthen i print the content of the set againthe resultobject 1very weird so i tried thissystemoutprintlnstringvalueofthesetcontainstheobjectthe resultfalseobviously the set cannot find theobject although it is thereso i thought there is something wrong with the equals methodthus i changed the method overrides of equals and hashcode by adding a console print to the first line of each function override public int hashcode systemoutprintlnhashcode called return namehashcode override public boolean equalsobject obj systemoutprintlnequals called if obj this return true if obj instanceof myclass false return false myclass otherobject myclass obj return nameequalsotherobjectname then i call againthesetremovetheobjectthe resulthashcode calledso the equals method is not called at allcan someone explain whats going on therei already tried to compare the hashcodes of theobject and the instance inside the set and they are both equal,['java'] +160375,why does not blueimps jqueryfileupload plugin fire callbacks i am experimenting with blueimps jqueryfileupload plugin which judging by the demo looks very promisingit is really easy to implementvar uploadbutton fileopupload input typefile idfileopupload etc uploadbuttonfileupload url domainpathtoreceiveuploadedfilesthe selected files are uploaded fine without refreshing the page as expected but of course with a minimal configuration like this the user would not get any notification heres where the plugins callbacks would come in handyaccording to the documentation there are two ways to define callbacks for example the add event which fires whenever a file is selected for uploading can be added in the original configuration object like thisuploadbuttonfileupload add addfilelistener url domainpathtoreceiveuploadedfilesor alternativelyuploadbuttonbindfileuploadadd addfilelistenerhowever i have found that only the first approach works the second one does not do anythingit is even more curious that no other callbacks especially progress and start seems to be firing not matter how i bind themuploadbuttonfileupload add addfilelistener progress progresslistener start startlistener url domainpathtoreceiveuploadedfilesoruploadbuttonfileupload add addfilelistener url domainpathtoreceiveuploadedfilesuploadbuttonbindfileuploadprogress progresslisteneruploadbuttonbindfileuploadstart startlisteneri have the referred listener functions defined and the code does not report any errors or warningswhat is the explanation for the bind methods failure and why does not the progress or the start listeners ever activate,['jquery'] +160390,remote form in rails 3 app is submitting as html i have come to my first remote form in a new rails 3 app and i cannot get it to submit remotely it keeps submitting as html i have done this ok in other rails 3 apps so am thinking it must just be something i have forgotten heres my form in my htmlerb file form for assignmentnew remote true do f hidden field tag assignmenttask id taskid hidden field tag assignmentperson id personid submit tag add to task end and heres how it renders out on the page i have included the javascript file links as i have a feeling the problem is something to do with the js not being set up properlydoctype html html langen head meta charsetutf8 script srcjavascriptsjqueryjs1306857355 typetextjavascriptscript script srcjavascriptspersonjs1306857355 typetextjavascriptscript script srcjavascriptsjqueryui1811customminjs1306857355 typetextjavascriptscript script srcjavascriptsjquery ujsjs1306857355 typetextjavascriptscript script srcjavascriptsjqueryuidatepickerjs1306857355 typetextjavascriptscript script srcjavascriptsjquerycolorboxminjs1306857355 typetextjavascriptscript script srcjavascriptsjquerytiptipminifiedjs1306857355 typetextjavascriptscript script srcjavascriptsapplicationjs1306857355 typetextjavascriptscript meta namecsrfparam contentauthenticity token meta namecsrftoken contenteri0bma1e0jaxwvyvmistpswc4fg2dg5tdpogeur358 head body classtasks form acceptcharsetutf8 actionassignments classnew assignment dataremotetrue idnew assignment methodpost div stylemargin0padding0thisplayinline input nameutf8 typehidden valuex2713 input nameauthenticity token typehidden valueeri0bma1e0jaxwvyvmistpswc4fg2dg5tdpogeur358 div input idassignment task id nameassignmenttask id typehidden value2 input idassignment person id nameassignmentperson id typehidden value1 input namecommit typesubmit valueadd to task form body html it all looks like it is being set up properly but when i submit i get this through in my log started post tasks2 for 127001 at 20110608 155642 0100 processing by taskscontrollerupdate as html parameters utf8a authenticity tokeneri0bma1e0jaxwvyvmistpswc4fg2dg5tdpogeur358 assignmenttask id2 person id1 commitadd to task id2like i was saying i think i have just missed out something that i needed to do to hook this up properly heres my gemfile as well in case that is relevantsource gem rake 087gem rails 307gem hamlgem herokugem heroku backup taskgem authlogic 302gem rails3generatorsgem txtlocal git gitgithubcomepigenesystxtlocalgitgem chronicgem sqlite3ruby require sqlite3gem bcryptrubygem taps for heroku db importexportgem jqueryrails 103gem jrailsgroup development test do gem rspec gem mocha gem rspecrails 24 gem database cleaner 052 gem capybara git gitgithubcomjnicklascapybaragit gem seleniumclient gem machinist gem fakerendcan anyone see whats missingthanks maxedit dumb mistake on my part the partial containing the remote form was being called from inside another nonremote form which was calling the same action so the outer form was being triggered by the submit button not the inner remote one doh thanks for reading,"['jquery', 'ruby-on-rails']" +160411,charting in aspnet mvc 3 i am using chart web helper in aspnet mvc 3 i have seen a range of shiny images online showing capabilities of this api but there is hardly any documentation on how to style the charts for example i need to thisplay labels outside of the chart i would like to specify percentage rather than decimal values etc there is a webforms project for download and very simple class documentation that explains how to assign values and specify basic dimensionsi understand that no books have been published yet on mvc 3 but surely there should be some sort of documentation explaining how to use the toolthank youeditfrom what i have read aspnet mvc 3 either took a step back with charting tool by removing ability to style charts or it has not been documented at all came across this article a very similar issue is described there edit 2it appears that microsoft have partially implemented mscharts functionality in mvc 3 in order to use mscharts the systemwebdatavisualization assembly must be imported and registered in webconfiguration file tthis way requests are sent from view to controllers controllers generate image of a graph and pass back an image result result is then thisplayed in the view this is useful as it provides some sort of seperation i still do not understand why systemwebhelperschart does not already offer this functionality but hopefully it will be addressed in near future edit 3few more points to make do not construct your graphs in the view they should be served by a controller if you do decide to use views for constructing graphs then make sure you update webconfig in views folder to include add namespacesystemwebuidatavisualization in the namespace section names of assemblies and namespaces are slightly confusing assembly is called systemwebdatavisualization when namespace is called systemwebuidatavisualization finally i think that charting api is great it serves images which means that charts will be accessible from all web browsers quality of the charts is great i have looked at alternatives such as fusion charts highcharts and few other jqueryjavascriptflash powered charts they all try to take a300a10 from you without trying to meet the most basic needs of developers,"['c#', 'asp.net']" +160425,what is the most accepted method for hiding password for connectphp file as my server is getting a bit bigger and more users are getting access to it i do not want them to see the password that mysql is using to connect to php which is stored in my connectphp file and required by every page however it is just sitting in the same directory as the rest of the php filesi have considered using a second connectphplike file with access to only one table that stores the encrypted passwords to connect to mysql but then i would have the problem of hiding the key to itchanging permissions would not work either if you chmod or or something similar nobody will be able to access the web application obviouslyis there an accepted method to get around this problem or should i just solve it on my own the problem is that i do not want it to be too convoluted if there is an accepted method,"['php', 'mysql']" +160448,determining relative path with jquery i have several wordpress sites installed in subfolders under a top level domaini need to load an ajax file in each of them and i have used the following code initiate asynchronous load of xml datajqueryajax type get url wpcontentthemesmythemedataxml datatype xml success parsedataxmlbut that ends up searching for the file in the domains root pathinstead of the sites root path,"['javascript', 'jquery']" +160452,simple php code sample to serve backbonejs experience level newbiethe backbonejs todos demo uses localstorage this question is about how to use php to serve the page instead assuming that a mysql db has been set upi checked out php frameworks such as codeigniter but found them difficult to follow and possibly overkill for my learning purposesi understand the concept that a rest api needs to be set up i am really looking for simple code samples thanks in advanceupdate is there a full backbonejs tutorial somewhere that includes a full working example of how to wire up to server side php,['php'] +160465,what does yellow tinting represent when using color misaligned images on iphoneios soi switched on color misaligned images to improve drawing performance in our app the documentation states puts a magenta overlay over images whose source pixels are not aligned to destination pixelsi do not know what the yellow means however there is a color offscreenrendered option that uses yellow does color misaligned images also turn on this optionanybody knowtia,"['iphone', 'ios']" +160471,p3p and php session problem with iframes in internet explorer 9 i have a contact form inside of an iframe which uses captcha and therefore requires session variables it works fine in every browser except ie9 to make it work in ie8 i added the following line at the beginning of the php documentheaderp3pcpcao idc dsp cor adm devi taii psa psd ivai ivdi coni his our ind cnt however this does not appear to work in ie9 any ideas,['php'] +160497,preventing xss attacks on user submitted html content in php the ebay way i have read so many articles describing methods to prevent xss attacks in user submitted html content using functions such a htmlspecialchars and regexs whitelistingblacklisting and using html filtering scripts such as html purifier htmlawed etc etc unfortunately none of these explain how a site like ebay is able to allow such a vast array of potentially malicious html tags such as link script object and css styles and html attributes such as background url etc it seems as if they allow users to submit pretty much anything into their item descriptions i have seen some of the most elaborate html javascript and flash templates in item descriptions what is ebay doing differently is there another technique or layer that i am missing that allows them to block xss attacks while still allowing pretty much anything to be included in users item descriptionany ideas or insight into this would be greatly appreciated,"['php', 'html', 'css']" +160502,undefined reference c i am trying to compile my first legit program that i am converting from java i ran a test hello world type program to check my compiler and it worksthere are three filesmaincppinclude iostreaminclude skewnormalhusing namespace stddouble getskewnormaldouble doubleint mainint argc char argv cout getskewnormal100 05 endlskewnormalcppdefine use math definesinclude iostreaminclude mathhusing namespace stdinclude skewnormalhdouble skewnormalevalutatableevaluatedouble x return 1 sqrt2 m pi powm e x x 2skewnormalevalutatableskewnormalevalutatabledouble sum double start double stop double stepsize evaluatable evalobj double sum 00 current start while current stop sum evalobjevaluatecurrent current stepsize returnsumdouble integrate double start double stop int numsteps evaluatable evalobj double stepsize stop start doublenumsteps start start stepsize 20 return stepsize sumstart stop stepsize evalobjdouble getskewnormaldouble skewvalue double x skewnormalevalutatable e return 2 sqrt2 m pi powm e x x 2 integrate10 skewvalue x 10 eskewnormalhifndef skewnormal h includeddefine skewnormal h includedclass evaluatable public virtual double evaluatedouble xclass skewnormalevalutatable evaluatablepublic skewnormalevalutatable double evaluatedouble xdouble getskewnormaldouble skewvalue double xdouble integrate double start double stop int numsteps evaluatable evalobjdouble sum double start double stop double stepsize evaluatable evalobjendif skewnormal h includedcompiling yielded the following errormaincpp9 undefined reference to getskewnormaldouble doublei am using codeblocks on ubuntu 1010,['c++'] +160505,procpidpagemaps and procpidmaps linux i am trying to get my head around the two files mentioned in the titlei have looked up what the bits are however i am failing to understand how to extract useful info from them or i am simply approaching it the wrong waylet me explain the pagemaps is a rather newer feature pseudo file that contains the physical frame information of virtual pages assigned to a current pid that is given a virtual page that starts at address x say vas for virtual address start i can index the pagemap file using vas to get the 64bits of the mapped physical page frame these bits contain info about that virtual pagehowever when i extract the bits and do a bit of shifting i am getting lost with what i am seeingthe bits are represented as follows 054 is the page frame number 5560 is the page shift 63rd bit is the present bit there are other bits of little interest to meafter i do a bit of mapping using vas addresses from procpidmaps it seems that just about every process page is swapped ie the 63rd bit is always a zero i guess the question would be how should i go about effectively using pagemaps to get the equivalent physical address of the address given by procpidmapsto be fair i have posted a similar question but the approach was a bit different a few days earlierif anyone can shed some light on this matter i would be greatly appreciativeeditto address the comment belowi am reading a line from procpidmaps and the lines look like00404010 rxp 0 0801 8915461 homejanjustmy programsshared mem 7fef1b07fef3c0 rwp 0 0 0 stackthen i am extracting the number of virtual pages it touches and indexing a binary file procpidpagemaps and for each virtual page i can extract the physical page it is assigned tothe output looks like00404010 rxp 0 0801 8915461 homejanjustmy programsshared mem num pages 1 8601464c6one physical address for each virtual page in the virtual rangethe code for reading the line and extracting the physical address is74 process procpidmaps by line75 whilefgetsline 256 in map null76 unsigned long vas77 unsigned long vae78 int num pages79 80 print line81 printfs line82 83 scan for the virtual addresses84 and sscanfline lxlx vas vae85 ifn 286 printfinvolid line read from snmaps87 continue88 89 90 num pages vae vas page size91 printfnum pages dn num pages92 93 ifnum pages 094 long index vas page size sizeofunsigned long long95 off64 t o96 ssize t t97 98 seek to index in pagemaps 99 o lseek64pm index seek set100 if o index101 printferror seeking to old indexldn o index102 103 104 map the virtual to physical page 105 whilenum pages 0106 unsigned long long pa107 108 read a 64bit word from each pagemap file 109 t readpm pa sizeofunsigned long long110 ift 01 printferror reading file s n page map112 goto next line113 114 printf 016llxn pahowever although i think i am getting the right output the index seems to be either a type mismatch or something else is going onthe output say for instance for the shared mem line in maps gives a wrong index yet i am still able to scan through the binary file and get the physical page addressthe example of that output is below969 7f7f08d5807f7f08d590 rws 0 04 0 sysv03039 deleted970 num pages 1971 error seeking to o1081840960 index273796065984972 860148267ok now lastly i should say that this is under a 64bit os and this problem does not persist in a 32bit os,['c'] +160511,downcasting shared pointer to derived class with additional functionality is this safe consider the following outlineclass base class derived public basepublic void additionalfunctionalityint i typedef stdshared ptrbase pbasetypedef stdshared ptrderived pderivedint mainvoid stdvectorpbase v vpush backpbasenew derived pderived p1 stddynamic pointer castderivedv0 copy pderived p2 stddynamic pointer castderivedv0 assignment p1additionalfunctionality1 p2additionalfunctionality2 a return 0here i am extending the base class with a derived class that adds functionality the additionalfunctionality methodfirst question is this ok i have read a lot of questions that say this is not okay and you should declare the additional functionality in the base class often suggested as making them pure virtual methods in the base class however i do not want to do this i want to extend the functionality of the base class not just implement it differently is there a better solution to accomplish this goalokay so in this code i am also using an stl container to store these pointers which allows me to store pointers to both objects of type base as well as objects of type derived without slicing the objectssecond question this makes sense right i am in fact avoiding slicing by using pointers to base class objects rather than the base class objects themselvesif i know that a certain pointer is to a derived object i then use stddynamic pointer cast to cast the smart pointerthird question this compiles without warning and works but is it safe valid will it break the reference counting aspect of shared pointers and fail to delete my objects or delete them before i expectlastly i can do this cast using either the copy constructor or via assignment as shown for p1 and p2 is there a preferred correct way of doing thissimilar questionsdowncasting shared ptrbase to shared ptrderived this is very close however the dervied class does not add additional functionality like mine does so i am not sure it is completely the same also it uses boostshared ptr where i am using stdshared ptr although i understand boost donated shared ptr to the std library so they are likely the samethank you for your helpeditone reason i ask is that i realize that the following could be done incorrectly intentional error vpush backpbasenew base pderived p3 stddynamic pointer castderivedv1 p3additionalfunctionality3 note 1 where i attempt to downcast a pointer to a base object to a pointer of a derived object and then call a method that is only implemented in the derived class in other words the object pointed to does not define or is not even aware of the methodthis is not caught by the compiler but may cause a segfault depending on how additionalfunctionality is defined,['c++'] +160519,uiactionsheet for deleting a uitableview cell on cancel keeps showing pressed delete button when deleting a row in a table view i want to show an action sheet asking for confirmation in certain situations when the action sheet is answered with yes the destructive action i delete the table row and everything is fine but when cancel is pressed i still see the delete button in a pressed statewhat i do in tableviewcommiteditingstyle when deleting is thisblockbasedactionsheet asksheet blockbasedactionsheet alloc initwithtitledelete entry cancelbuttontitleno destructivebuttontitleyes delete child also records cancelaction uitableviewcell cell self tableviewtableview cellforrowatindexpathindexpath if cellshowingdeleteconfirmation cellediting no celleditingaccessoryview nil cellediting yes destructiveactiondeleteblockasksheet showinviewselfviewasksheet releasewhats also strange is that the cells property showingdeleteconfirmation is no although the delete button is still visiblei am using a selfmade blockbased action sheet implementation maybe there lies the error although i seem to get the correct cell in the cancel blockso how can i reset the delete button state back to unpressed and remove it and turn the round delete button back to horizontal like it happens when i tap somewhere on the screenhelper class blockbasedactionsheethinterface blockbasedactionsheet uiactionsheetuiactionsheetdelegate property copy void cancelblockproperty copy void destructiveblock idinitwithtitlensstring title cancelbuttontitlensstring cancelbuttontitle destructivebuttontitlensstring destructivebuttontitle cancelactionvoid cancelblock destructiveactionvoid destructiveblockendimplementation file blockbasedactionsheetmimport blockbasedactionsheethimplementation blockbasedactionsheetsynthesize cancelblock cancelblock destructiveblock destructiveblock idinitwithtitlensstring title cancelbuttontitlensstring cancelbuttontitle destructivebuttontitlensstring destructivebuttontitle cancelactionvoid cancelblock destructiveactionvoid destructiveblock self super initwithtitletitle delegateself cancelbuttontitlecancelbuttontitle destructivebuttontitledestructivebuttontitle otherbuttontitles nil if self cancelblock block copycancelblock destructiveblock block copydestructiveblock return selfvoidactionsheetuiactionsheet actionsheet clickedbuttonatindexnsintegerbuttonindex nsassertactionsheet self wrong action sheet passed if buttonindex self cancelbuttonindex if selfcancelblock selfcancelblock else if selfdestructiveblock selfdestructiveblock end,"['iphone', 'ios']" +160549,touches began in uitableviewcontroller i am defining this method in my uitableviewcontroller subclass voidtouchesbegannsset touches witheventuievent event super touchesbegantouches witheventevent nslogtouch beganbut it is not being triggered uiviewcontroller is a subclass of uiresponder so it should work rightthanks,['objective-c'] +160555,can you begin programming opencl without downloading an sdk i am trying to get a program that will run on both ati and nvidia and as such i want to avoid using either sdk is it possible to do this without an sdk using only vs2010 and windows xp or 7 if so how can i go about configuring vs2010 linker so that it will work,['c++'] +160577,calculating plugin dependencies i have the need to create a plugin system that will have dependency support and i am not sure the best way to account for dependencies the plugins will all be subclassed from a base class each with its own execute method in each plugin class i would planned to create a dependencies attribute as a list of all the other plugins it depends onwhen loading the plugins i would import all of them and put them in a list and sort them based on the dependencies once they are all in the correct order so anything with a dependency is in the list after its said dependencies i would loop through the list executing each methods execute methodwhere i am keep getting fuzzy is the logic behind the sorting i can just start putting them in alphabetical order until i come across one that has a dependency if its dependencies is not in the list yet put it into a tmp list at the end of the first round of imports start at the end of the temp list a list with nothing but plugins that have dependencies and check the run list again if i find its dependencies in the run list make sure it has a higher index number than its highest dependency if its dependencies are not in the list hold off on it and move to the next plugin in the temp list once i get to the end of the tmp list start back at the top and try again once either all the plugins are sorted or the tmp list does not change size after looping over it start executing pluginswhat would be left in the temp list are plugins that either do not have they are dependencies found or have a circular dependency 2 plugins in the tmp list that depend on one anotherif youre still reading and you were able to follow my logic is this a sound plan is there a simpler way if i wanted to implement sequence numbers for execute order is there an easy way to have both sequence and dependencies with dependencies beating sequencing if there was a conflict or should a plugin use a sequence or dependencies run the plugins with sequence numbers first than the ones with dependenciestldrhow would you write the logic for calculating dependencies in a plugin systemeditalright i think i implemented the topological sort from the wikipedia page following its logic example for the dfs it seems to work but i have never done anything like this before sortingexamplesdata 10 11 3 3 5 7 11 7 5 9 8 11 2 11 8 7 3l visited def nodepsdata s for each in datakeys if not lendataeach sappendeach return sdef dependsonnode r for each in datakeys for and in dataeach if and node rappendeach return rdef visitnode if not node in visited visitedappendnode for m in dependsonnode visitm lappendnodefor node in nodepsdata visitnodeprint l1,['python'] +160580,bad url when requesting with nsurl i am trying to request this kind of url in iphone 40 sdk access token slightly modified because you do not really need to see itsdk version2access token1239028179878cb9e8408d2685cef853cd809747882379ugu5nvcahixugegzkqformatjsonlimit40until1286619821but i got this messagefailed with error error domainnsurlerrordomain code10 bad url userinfo0x9e657a0 nsunderlyingerror0x9e656a0 bad url nslocalizeddescriptionbad urlwhen i copied and pasted in safari or chrome it works i tried replacing with as suggested here but does not workasking it from the terminal looks like thiscurl sdk version2access token9558179878ab9e8408d2685cef3747882379uguxwdumformatjsonlimit40until12866198211 161902 161913 161944 161955 161962 done sdk version24 done formatjson bash ugu5nvcahixugegzkq3kp8xwdum command not foundbash 8ab9e8408d2685cef853cd803747882379 command not founderrortypeoauthexceptionmessagean active access token must be used to query information about the current user1 done curl 3 exit 127 access token955817987 8ab9e8408d2685cef3747882379 uguxwdum5 done limit40any ideas,"['iphone', 'objective-c']" +160587,rails 3 good rule of thumb for where to put javascript when writing javascript for a specific page in a site when do you want to turn the javascript into a function and include it in applicationjsi have seen suggestions about doing this and minifying or gziping to minimize http requests that makes sense but what about maintainability if i have js code specific to one view it seems like more work to look into a potentially massive applicationjs that code could be embedded into that view or put in its own js or jserb or rjs file in that view folderi have seen another suggestion that rails automatically merges all javascript into one file is this truetldr how much or how little should a developer worry about optimization when writing javascript,['javascript'] +160589,make sure all threads exited in a win form application i have an array of threads which are started like thisbool stop falsethread threads new thread10for int i 0 i threadslength i threadsi new threadnew threadstartjob how to make sure all threads have exited when the boolean falsevoid job while stop do somethingnow if user press stop the boolean value for stop will set to true so threads exit the job method one after another how can i make sure all threads are exitednote i need traditional threading for my case and tasklibrary does not fit my scenario,['c#'] +160597,rendering svg with opengl and opengl es i am currently investigating the possibility of rendering vector graphics from an svg file using opengl and opengl es i intend to target windows and android my ideal solution would be to have a minimal c library that generates a polygon triangulation from a given svg file this would then generate standard opengl or opengl es calls and use a thisplay list or vbo for optimization when redrawing i would simply draw a thisplay list to draw the vector image after translating and rotating allowing me to mix this with other opengl callsso far i see that the suggestions are to firstly use qt or cairo this is not an option given that i wish to manage my own opengl context without bloated libraries in the context of what i am trying to achieve nor is this suitable for androidsecond option is to use libraries that render to a texture while this might be ok for static vector graphics it is not an efficient or feasible option for games where scaling and rotations occur frequentlythirdly there is the possibility of using openvg there are some opensource implementations of the openvg specification shivavg etc but i am yet to find a library that is capable of generating the appropriate openvg calls from a given svg file at runtime and i cannot see how to optimize this as we might wish to with a thisplay list or vboall three methods suffer limitations i think the most promising option is using an openvg implementation if no other solution exists so my question is are there any libraries out there that do what i want or close to what i want if not is there a good reason why not and would it be better to attempt to do this from the ground up instead,['android'] +160611,php foreach statement by reference unexpected behaviour when reusing iterator this code produce an unexpected outputarraystr splitabcdeforeacharray as item echo itemecho nforeacharray as item echo itemoutputabcdeabcddif use item for second loop everything works finei do not understand how this code would affect the content of array i could consider that an implicit unsetheader would delete the last row but where does the double dd comes from,['php'] +160639,net ensuring json keys are lowercase hi all is there simple way using json in net to ensure that the keys are sent as lower caseat the moment i am using the newtonsoftjson library and simply usingstring loginrequest jsonconvertserializeobjectauthin this case auth is just the following objectpublic class authority public string username get set public string apitoken get set this results in usernamemarkapitokenxyzabc1234is there away to ensure that the username and apitoken keys come through as lowercase i do not want to simply run it through stringtolower of course because the values for username apitoken are mixed casei realise i can programically do this and create the json string manually but i need this for approx 20 or so json data strings and seeing if i can save myself some time wondering if there are any already build libraries that allow you to enforce lowercase for key creation,['.net'] +160663,strictmode analytics i am using google analytics for android but after turning on strictmode i get a lot of message like this strictmode policy violation duration349 ms androidosstrictmodestrictmodethiskreadviolation policy23 violation2 at androidosstrictmodeandroidblockguardpolicyonreadfromthiskstrictmodejava745 at androiddatabasesqlitesqlitedatabaserawquerywithfactorysqlitedatabasejava1345 at androiddatabasesqlitesqlitedatabasequerywithfactorysqlitedatabasejava1235 at androiddatabasesqlitesqlitedatabasequerysqlitedatabasejava1189 at androiddatabasesqlitesqlitedatabasequerysqlitedatabasejava1309 at comgoogleandroidappsanalyticspersistenteventstorepeekeventsunknown source at comgoogleandroidappsanalyticspersistenteventstorepeekeventsunknown source at comgoogleandroidappsanalyticsgoogleanalyticstrackerthispatchunknown source at comgoogleandroidappsanalyticsgoogleanalyticstracker1rununknown source at androidoshandlerhandlecallbackhandlerjava587 at androidoshandlerthispatchmessagehandlerjava92 at androidoslooperlooplooperjava123 at androidappactivitythreadmainactivitythreadjava3647 at javalangreflectmethodinvokenativenative method at javalangreflectmethodinvokemethodjava507 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava839 at comandroidinternaloszygoteinitmainzygoteinitjava597 at dalviksystemnativestartmainnative methodcan i ignore thati also tried to put trackertrackingpageview into asynctask same resulthere are my settings for strictmode strictmodesetthreadpolicynew strictmodethreadpolicybuilder detectthiskreads detectthiskwrites detectnetwork penaltylog build strictmodesetvmpolicynew strictmodevmpolicybuilder detectleakedsqlliteobjects penaltylog penaltydeath buildi would really appreciate any help thanks in advancemike,['android'] +160681,are there any tools for parsing a c header file and extract a function protoype from a c header file especially getting the function return typeand if possible whether its a pointer typei am trying to write auto generation of ioctldlsym wrapper libsto be ld preload ed a python or ruby library would be preferred but any workable solution is welcome,['c'] +160694,ifelse statement in sse intrinsics i am trying to optimize a small piece of code with sse intrinsics i am a complete beginner on the topic but i am a little stuck on the use of conditionalsmy original code isunsigned long cunsigned long constant 0x12345678unsigned long table256int n kfor and 0 and 256 n c n for k 0 k 8 k if c 1 c constant c 1 else c 1 tablen cthe goal of this code is to compute a crc table the constant can be any polynomial it does not play a role herei suppose my optimized code would be something like m128 x m128 y m128 tablex mm set ps3 2 1 0y mm set ps3 2 1 0offset for incrementationoffset mm set1 ps4for and 0 and 64 n y x for k 0 k 8 k if do something with y else do something with y tablen y x mm add epi32 x offseti have no idea how to go through the ifelse statement but i suspect there is a clever trick has anybody an idea on how to do thataside from this my optimization is probably quite poor any advice or correction on it would be treated with the greatest sympathy,['c++'] +160695,eclipse debugger always blocks on threadpoolexecutor without any obvious exception why i am working on my usual projects on eclipse it is a j2ee application made with spring hibernate and so on i am using tomcat 7 for this no particular reason i do not exploit any new feature i just wanted to try that every time i debug my application it happens that eclipse debugger pops out like it has reached a breakpoint but it is not the case in fact it stops on a java source file that is threadpoolexecutor there is no stack trace on the console it just stops then if i click on resume it goes on and the app works perfectly this is what shows in the debugger windowdaemon thread httpbio8080exec2 suspended exception runtimeexception threadpoolexecutorworkerrun line 912 taskthreadthreadrun line 619i really cannot explain this because i am not using threadpoolexecutor at all must be something from tomcat hibernate or spring it is very annoying because i always have to resume during debuggingany clues,['java'] +160718,xll excel addin in unmanaged c i have a few mathematical simulations in unmanaged c and now i need to integrate them with excel so that it is possible to call the functions from excel and get the values back i do not want to use any vba so i guess i have to implement an xll addin i would like to use as few third party additional frameworks as possible could someone point me to a good tutorial,['c++'] +160721,change the default domain of client in unittest of django i am writing a unit test for django viewsclass testlogunittesttestcase test for contact def setupself selfc client try selfbob userobjectscreate usermojo bmojo except print def test get emailsself response selfcgettext selfassertequalresponsestatus code 200 def test htmlemilsself response selfcgetemailshtmlupload selfassertequalresponsestatus code 200the c client takes the httptestserver as domain which i want to overwrite i want to add my real domain in that test client is their way to customize the test client,['python'] +160722,static virtual functions in c i have a base class and a derived one and i want to change base functions while keeping them static as they should be passed to other functions as statichow can i do that,['c++'] +160728,decorator design pattern function bug this is homeworki am not asking for answers i just have a bug i am not sure what to do with thanksthe bug in question probably has nothing to do with the assignment itself but here is the assignment description anywaysi am working on an assignment in c meant to teach use of the decorator design pattern through the classic example of a pizza with toppings my professor may as well have lifted it straight from i am running into a little problem that i was wondering if someone could help me withi have a main menupizzeria object that takes input from the user and performs the desired actions on a pizza users start with a basic pizza and then can add toppings to it until they are done so the first thing that my newpizza function does is declare the new pizza as a plain which is a subclass of abstract class pizzathen they get to enter their choice of toppings each time a pointer to the same pizza object is sent to the addtoppings function the new decoration is added and the pointer is returned each decoration inherits from a price category which inherits from pizzatoppings which inherits from pizzathis is the relevant part of the main order functionpizza menunewpizzacout nnew pizzaaccept the next choiceint choose 0create the new pizzaplain currentpizza new plainuntil they choose to end the orderwhile choose 3 accept the choice cin choose switch choose if they want to add a new topping case 1 add topping to current pizza and this is where the problem is spotted by the compiler addtoppingcurrentpizza break the issue is that when i try to send the pointer currentpizza to the function addtopping i get runtime check failure 3 the variable currentpizza is being used without being initializeddid not i just initialize it right there on line 7if i hit continue the program keeps going and works but i get that same error every time i call the function is it just a syntax error somewhere or do i have some actual issue herethankseditthe addtopping functionpizza menuaddtoppingpizza thispizzacout nadd toppingdeclare choose intint choose 0accept number of toppingcin choosedecide which one to addswitch choosemozzarellacase 1 thispizza new mozzarellathispizza break mushroomscase 2 thispizza new mushroomsthispizza break another 13 possible toppings would not bore you with the details cout nend add toppingnreturn thispizza,['c++'] +160730,how to get value of checked checkbox in php heres the codephp operator pageinclude classesdbhelperphpinclude confconfphpconf new dbconfdburl confget databaseurldbuname confget databaseunamedbpword confget databasepworddbname confget databasenamenameofdbwithcustomers confget tablenamecustomerifisset requestsession name session startelse headerlocation authorizephpif sessionusr id md5crypt sessionlogin sessionpass echo script typetextjavascript srcjquery16jsscript form methodpost name input typetext namename size10 value post input typetext namepost size10 value section input typetext namesection size10 value company input typetext namecompany size10 value phone number input typetext namephone number size10 value email input typetext nameemail size10 value active input typecheckbox nameactive value input typesubmit namesearch size10 valuesearch br input typereset namereset valuereset form form method post sms input typecheckbox name sms email input typecheckbox name email idmailcheckbr textarea namemessage wrapvirtual cols40 rows3 textareabr input type submit name send size 10 value send form form actionuploadphp methodpost enctypemultipartformdata input typefile namefilenamebr input typesubmit value3nn nnbr form if issetpostsend if isset postsearch query name isset postname postname 0 post isset postpost postpost 0 section isset postsection postsection 0 company isset postcompany postcompany 0 phonenumber isset postphone number postphone number 0 email isset postemail postemail 0 active isset postactive 1 0 array array name name post post section section company company phone number phonenumber email email status active sql select from nameofdbwithcustomers sql where array foreacharray as key value ifemptyvalue sql where key value ifcountsql where 0 sql where sql implode and sql where end query dbhelp new dbhelperdburl dbuname dbpword dbname queryresult dbhelpgetdatafromdbbyquerysql table table border1 width100 aligncentern table trn i 1 while i mysql num fieldsqueryresult meta mysql fetch fieldqueryresult i i table tdmetanametdn table td n 2n input typecheckbox namecbname3 valuemain idchkselectalltdn table trn i 1 while row mysql fetch assocqueryresult table trn table tdrownametdn table tdrowposttdn table tdrowsectiontdn table tdrowcompanytdn table tdrowphone numbertdn table tdrowemailtdn table tdrowstatustdn table tdrowlock timetdn table tdrowreason for blockingtdn table tdinput typecheckbox classcheck namecbname3 idchkitems valuerowid td table trn i table tablen echo table script typetextjavascript documentreadyfunction chkselectallclientid clickfunction chkitemsclientid inputcheckboxattrcheckedthischecked chkitemsclientid inputcheckboxclickfunction if chkselectallclientid attrchecked true thischecked false chkselectallclientid attrcheckedfalse ifthischecked true checkselectall function checkselectall var flag true chkitemsclientid inputcheckboxeachfunction ifthischecked false flag false chkselectallclientid attrcheckedflag i want to get value of checked checkbox from table when user press on send button how can i do that,['php'] +160733,do you need to unwire an anonymous functionlambda my understanding is that any event handlers wired up in c need to be unwired as suchobject myobject new objectmyobjectevent eventhandler wiredmyobjectevent eventhandler unwiredbut do you need to unwire the following code and if so howobject myobject new objectmyobjectevent object sender eventargs e wiredmyobjectevent unwire howmy assumption is no,['c#'] +160789,mapping xml values to enum type i need to parse a xml file which i get from third party to c objectssome of the xml i receive have enumeration values which i want to store in an enum typefor example i have got the following xsd of the xml filexsdsimpletype namebrandstof xsdrestriction basexsdstring benzine xsdenumeration valueb diesel xsdenumeration valued lpggas xsdenumeration valuel lpg g3 xsdenumeration value3 elektrisch xsdenumeration valuee hybride xsdenumeration valueh cryogeen xsdenumeration valuec overig xsdenumeration valueo xsdrestrictionxsdsimpletype i want to map this to an enum and i got this far public enum fuel b d l e h c othe problem i have is that the xml can contain a value of 3 which i cannot seem to put in the enum type is there any solution to put this value in the enum i also can get other values with a or a in them and which i want to put in an enum typeanu suggestions are welcome,['c#'] +160803,why is the last number wrong why is only the last number wrong in the output this codepublic class test public static void mainstring args systemoutprintlnhello world systemoutprintlni wounder is the sqaure root of 23 the same as the sqaure root of 2 and 3 multiplied double squareroot0 mathpow32 05 double squarroot1 mathpow3 05 mathpow2 05 systemoutprintlnso is it the same systemoutprintlnis squareroot0 the equvielant of squarroot1 ifsquareroot0 squarroot1 systemoutprintlnyes number one and number two are the same congrats else systemoutprintlnno they are not systemoutprintlnsquareroot0 systemoutprintlnsquarroot1 outputhello worldi wonder is the sqaure root of 23 the same as the sqaure root of 2 and 3 multipliedso is it the sameis 2449489742783178 the equvielant of 24494897427831783no they are not 244948974278317824494897427831783mathematically they are equivalent so what is going onmathsqrt and mathpow05 is just as accurate,['java'] +160817,linker error in xcode 42 developer preview d usersyariksmirnovlibrarydeveloperxcodederiveddatagoozzycugjuvvsrzjqwvfiicxtykbqaguxbuildproductsdebugiphonesimulatorgoozzyappgoozzy normal i386cd usersyariksmirnovdesktopgoozybranchesnewsetenv macosx deployment target 106setenv path developerplatformsiphonesimulatorplatformdeveloperusrbindeveloperusrbinusrbinbinusrsbinsbindeveloperplatformsiphonesimulatorplatformdeveloperusrbinllvmgcc42 arch i386 isysroot developerplatformsiphonesimulatorplatformdevelopersdksiphonesimulator50sdk lusersyariksmirnovlibrarydeveloperxcodederiveddatagoozzycugjuvvsrzjqwvfiicxtykbqaguxbuildproductsdebugiphonesimulator fusersyariksmirnovlibrarydeveloperxcodederiveddatagoozzycugjuvvsrzjqwvfiicxtykbqaguxbuildproductsdebugiphonesimulator filelist usersyariksmirnovlibrarydeveloperxcodederiveddatagoozzycugjuvvsrzjqwvfiicxtykbqaguxbuildintermediatesgoozzybuilddebugiphonesimulatorgoozzybuildobjectsnormali386goozzylinkfilelist mmacosxversionmin106 xlinker objc abi version xlinker 2 d iphone os version min required40300 framework coredata lz123 framework mobilecoreservices framework systemconfiguration framework cfnetwork framework quartzcore framework uikit framework foundation framework coregraphics o usersyariksmirnovlibrarydeveloperxcodederiveddatagoozzycugjuvvsrzjqwvfiicxtykbqaguxbuildproductsdebugiphonesimulatorgoozzyappgoozzyld library not found for lz123collect2 ld returned 1 exit statuscommand developerplatformsiphonesimulatorplatformdeveloperusrbinllvmgcc42 failed with exit code 1how do i fix this errorit is very strange i compile a build for ios but get a error about mac os deployment target,"['iphone', 'ios']" +160827,ios coregraphics stroking with semitransparent patterns leads to colors corruption my task is to make something like an erasing tool operated with a finger that will reveal a background image instead of an erased imagehere are my source and destination images just for test real ones will differand heres my code creating the pattern voidsetframecgrectframe super setframeframe ifrevealpattern cgpatternreleaserevealpattern cgpatterncallbacks callbacks 0 patterncallback null revealpattern cgpatterncreateself selfbounds cgaffinetransformidentity selfboundssizewidth selfboundssizeheight kcgpatterntilingconstantspacing true callbacks pattern callback function info contains the pointer to selfvoid patterncallbackvoid info cgcontextref context cgrect rect drawview infobounds cgimageref imageref drawview infobackgroundimagecgimage cgcontexttranslatectmcontext 0 rectsizeheight cgcontextscalectmcontext 10 10 cgcontextdrawimagecontext rect imagerefand the drawing method voiddrawpointscgcontextrefcontext ifpoints count 2 return cgpoint lastpoint points objectatindex 0 cgpointvalue cgcontextbeginpathcontext cgcontextmovetopointcontext lastpointx lastpointy cgcontextsetblendmodecontext kcgblendmodenormal cgcolorspaceref revealpatternspace cgcolorspacecreatepatternnull cgcontextsetstrokecolorspacecontext revealpatternspace cgfloat revealalpha 10 cgcontextsetstrokepatterncontext revealpattern revealalpha cgcontextsetalphacontext 01 cgcolorspacereleaserevealpatternspace cgcontextsetlinecapcontext kcglinecapround cgcontextsetlinejoincontext kcglinejoinround cgcontextsetlinewidthcontext selflinewidth forint i 1 i points count i cgpoint currpoint points objectatindex i cgpointvalue cgcontextaddlinetopointcontext currpointx currpointy lastpoint currpoint cgcontextstrokepathcontextif the local variable revealalpha has value 10 as shown in the last code piece everything works finebut i need the erasing to be semitransparent so that a user needs to swipe the same place several times to erase it fully and here the problem appears if i make revealalpha to be less than 10 the revealed destination image looks corruptedhere are the results for revealalpha 10 and revealalpha 01if you look close enough you will notice that the blue gradient on the right picture is not smooth anymore,"['iphone', 'ios']" +160831,in what architecturesos other thread can see default nonfinal field values after constructor call i am trying to reproduce a memory visibility issue in case of insufficient object initialization for nonfinal fields jls 175 final field semantics finalfieldexample class example where it stated however fy is not final the reader method is therefore not guaranteed to see the value 4 for iti have tried this codepublic class reorderingtest2 public static void mainstring args for int i 0 i 2500 i new threadnew readeristart new threadnew writeristart static class reader implements runnable private string name readerint i thisname reader i override public void run systemoutprintlnname started while true finalfieldexamplereadername static class writer implements runnable private string name writerint i thisname writer i override public void run systemoutprintlnname started while true finalfieldexamplewriter static class finalfieldexample int x int y static finalfieldexample f public finalfieldexample x 3 y 4 static void writer f new finalfieldexample static void readerstring name if f null int i fx int j fy if i 3 j 4 systemoutprintfreader s sees itn name as in previous my similar topic i have tried on different pcs from 2 to 8 cores with windows and even on our serverside solaris 32 core box i could not reproduce it fx and fy are always already properinitializedfor intelx86x64 architecture as i got the answer they have pretty much default memery guarantees which prevent such constructor logic reorderingseems the same is true for solarissparc tooso in what architectureoses this reordering can be reproduced,['java'] +160869,bitwise signed division algorithm in c well to be honest this is actually my homework where i have to implement an algorithm which has to be able to divide two values without taking the absolute values of them to do the division it also has to find out the remainderthe dividend is the one with bigger absolute value and the divider has smaller absolute valuei have done a lot of googling but most of the examples only cover unsigned valuesi tried to implement it by the scheme mentioned in the first replyimplement division with bit wise operatorthat did not get me very far for some reasonthen i found thisi got it working when i wrote the code below using the example in the end of the documentthis one gets it right if the first value is positive and the second is noti have worked on it for at least 2 days now maybe somebody can say where am i going wronghere is the code i managed to put together with the help of dysaster it does not work when both values are either negative or positive but i managed to get 20 points out of 25 for it at the protectioninclude stdiohinclude stdlibhchar bitschar rg unsigned char bit 0x80 int i char bits bits char malloc9 for i0 i 8 i bitsi rg bit 1 0 bit 1 bitsi 0 return bitsint dividechar rg1 char rg2 char rg3 r0 int i printfrg1 s 2dn bitsrg1 rg1 printfrg2 s 2dn bitsrg2 rg2 rg3 rg1 printfrg3 s 2d copy of rg1n bitsrg3 rg3 if rg1 0 r 0xff printfrem s 2d remainder after sign checkn bitsr r for i 0 i 8 i printfn d iteration n i1 if rg3 0x80 printf left shift r and rg3 carryn rg3 1 r 1 r 1 printf s 2d s 2dn bitsr r bitsrg3 rg3 else printf left shift r and rg3n rg3 1 r 1 printf s 2d s 2dn bitsr r bitsrg3 rg3 printf add in the divisorn r rg2 printf s 2d s 2dn bitsr r bitsrg3 rg3 if rg1 0 rg2 0 r 0 rg1 0 rg2 0 r 0 real ugly i know printf subtract the divisor and set the lowest bit of rg3 to 1n r rg2 rg3 0x01 printf s 2d s 2dn bitsr r bitsrg3 rg3 else printf lowest bit of rg3 stays 0n printf s 2d s 2dn bitsr r bitsrg3 rg3 post division sign check if rg1 0 rg2 0 rg1 0 rg2 0 rg3 printfns d s d s d r s dnn bitsrg1 rg1 bitsrg2 rg2 bitsrg3 rg3 bitsr rint mainint argc char argv divide13 4 buggy divide29 4 ok divide19 8 ok divide17 5 buggy return 0,['c'] +160889,hebrew and numbers i have a database and use it with phpmyadmin and values in one of the fields are mixed hebrew letters with numbers like 12first character is second character is third character is 1fourth character is 2 the above is written in correctly though this value first character is 1second character is 2third character is fourth character is looks the same here and in the databaseis it possible to make it look differentps hebrew is right to left,['mysql'] +160927,classgetresource and classloadergetsystemresource is there a reason to prefer one to another i saw both classgetresource and classloadergetsystemresource used to locate a resource in java is there any reason to prefer one to another,['java'] +160932,can i use visual studio with unity i have been checking out unity and it looks quite interesting in particular after reading you can use c as the scripting language i am left wondering if there is some sort of visual studio integration to leverage intellisense and all that jazz built into vs,['c#'] +160937,force load an assembly from the bin and not the gac i have two assemblies created through conditional compilation dev and realthe public surface of these assemblies is 100 identical both are strongly named both are signed with the same snk and therefore have the same publickeytoken both have the same culture and the same version i cannot change this making them appear identical is the whole pointhowever on my machine the real assembly is in the gac i have an aspnet 35 webforms app that references the dev assembly it absolutely must do that the real assembly crashes the appis there a way to force a specific aspnet application to use the dev one which is in bin given thatthere is one in the gacboth have the same version and publickeytokenboth are strongly namedsigned with the same keyi can not change them cannot change the version and cannot remove the keyi noticed that someone already asked this in 991293 but the accepted answer involved removing the signing which is not an option heream i out of luck,"['.net', 'asp.net']" +160938,using setvaluesforkeyswithdictionary with child objects and json i have a json stringnametestbarnametestbarin objective c i have an objectinterface foo nsobject property nonatomic retain nsstring nameproperty nonatomic retain bar barendand i just synthesize those properties and i have a child object with synthesized propertiesinterface bar nsobject property nonatomic retain nsstring nameendthen here is the code where i am trying to get into the foo object where response is the json string above sbjsonparser json sbjsonparser new autorelease parsedresponse json objectwithstringresponse errorerror foo obj foo new autorelease obj setvaluesforkeyswithdictionaryparsedresponse nslogbar name objbarnamethis throws an exception on the nslog statement of nscfdictionary name unrecognized selector sent to instance 0x692ed70but if i change the code to it worksnslogbar name objbar valueforkeynamei am confused at why i cannot do the first example or am i doing something wrong,['objective-c'] +160957,tersest way to create an array of integers from 120 in javascript what would be the tersest way to create this arrayvar x 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20for example a for loopvar x for var i1i20i xpushior a while loopvar x i 1 endint 20while i endint xpushi iwould there be other examples that would be terser in other words less code i am thinking of things like in ruby where the equivalent code i believe would be as simple as 120 i am not aware of syntax like that in javascript but i am wondering if there are shorter ways to do that same thingupdate i was not thinking of removing semicolons or var for answers in the question but i have to admit the question implies that i am more curious about algorithms than shaving bytes sorry if i was unclear also making it into a function is simple enough just slap function rangestart end guts here around it and youre there the question is are there novel approaches to the guts,['javascript'] +160971,sql difference between rows i have a sql 2008 database table like thisname scoresteve 207steve 205steve 200steve 139i want to get the difference between the rows eqn row row 1so i would ideally want it to besteve 2 207 205steve 5 205 200steve 61 200 139steve 139 139 0what is the best way to do this thanks,['sql'] +160987,rails using included helpers inside class methods does anybody know why the included method does not work inside a class methodclass myclass include actionviewhelpersnumberhelper def test puts uploading number to human size 123 end def selftest puts uploading number to human size 123 endendree187201103 004 myclassnewtestuploading 123 bytes nil ree187201103 005 myclasstestnomethoderror undefined method number to human size for myclassclass from pathtomycoderb9in test from irb5ree187201103 006,"['ruby-on-rails', 'ruby']" +161000,how to script sql server database role i need to make a script to copy one particular database role from one sql server to anotheris there an easy way to generate a script that creates the role and all the role permissions,['sql'] +161026,delayed job giving a undefined method error delayed job 214 is working perfectly on my development machine sending emails with gay abandon however it is failing miserably when running on my server using apachepassenger307 rails 307 and ruby 192 on both btwi have seen that there is a problem when using thin where the job is created like this rubystructdelayedperformablemailerobject rubyobjectclass usermailerwhen it should read rubystructdelayedperformablemailerobject rubyclass usermailer mine are created correctly on my development machine but the wrong way when created on the serverhas anyone else had this problem where should i start lookingstacktraceundefined method standard message for class0xc6ad054homesafreasitesharedbundleruby191gemsdelayed job214libdelayedperformable mailerrb6in performnhomesafreasitesharedbundleruby191gemsdelayed job214libdelayedbackendbaserb87in invoke jobnhomesafreasitesharedbundleruby191gemsdelayed job214libdelayedworkerrb120in block 2 levels in runnusrlocalrvmrubiesruby192p180libruby191timeoutrb57in timeoutnhomesafreasitesharedbundleruby191gemsdelayed job214libdelayedworkerrb120in block in runnusrlocalrvmrubiesruby192p180libruby191benchmarkrb309in realtimenhomesafreasitesharedbundleruby191gemsdelayed job214libdelayedworkerrb119in runnhomesafreasitesharedbundleruby191gemsdelayed job214libdelayedworkerrb177in reserve and run one jobnhomesafreasitesharedbundleruby191gemsdelayed job214libdelayedworkerrb104in block in work offnhomesafreasitesharedbundleruby191gemsdelayed job214libdelayedworkerrb103in timesnhomesafreasitesharedbundleruby191gemsdelayed job214libdelayedworkerrb103in work offnhomesafreasitesharedbundleruby191gemsdelayed job214libdelayedworkerrb78in block 2 levels in startnusrlocalrvmrubiesruby192p180libruby191benchmarkrb309in realtimenhomesafreasitesharedbundleruby191gemsdelayed job214libdelayedworkerrb77in block in startnhomesafreasitesharedbundleruby191gemsdelayed job214libdelayedworkerrb74in loopnhomesafreasitesharedbundleruby191gemsdelayed job214libdelayedworkerrb74in startnhomesafreasitesharedbundleruby191gemsdelayed job214libdelayedcommandrb104in runnhomesafreasitesharedbundleruby191gemsdelayed job214libdelayedcommandrb83in block in run processnhomesafreasitesharedbundleruby191gemsdaemons113libdaemonsapplicationrb249in callnhomesafreasitesharedbundleruby191gemsdaemons113libdaemonsapplicationrb249in block in start procnhomesafreasitesharedbundleruby191gemsdaemons113libdaemonsdaemonizerb199in callnhomesafreasitesharedbundleruby191gemsdaemons113libdaemonsdaemonizerb199in call as daemonnhomesafreasitesharedbundleruby191gemsdaemons113libdaemonsapplicationrb253in start procnhomesafreasitesharedbundleruby191gemsdaemons113libdaemonsapplicationrb293in startnhomesafreasitesharedbundleruby191gemsdaemons113libdaemonscontrollerrb70in runnhomesafreasitesharedbundleruby191gemsdaemons113libdaemonsrb195in block in run procnhomesafreasitesharedbundleruby191gemsdaemons113libdaemonscmdlinerb109in callnhomesafreasitesharedbundleruby191gemsdaemons113libdaemonscmdlinerb109in catch exceptionsnhomesafreasitesharedbundleruby191gemsdaemons113libdaemonsrb194in run procnhomesafreasitesharedbundleruby191gemsdelayed job214libdelayedcommandrb81in run processnhomesafreasitesharedbundleruby191gemsdelayed job214libdelayedcommandrb75in block in daemonizenhomesafreasitesharedbundleruby191gemsdelayed job214libdelayedcommandrb73in timesnhomesafreasitesharedbundleruby191gemsdelayed job214libdelayedcommandrb73in daemonizenscriptdelayed job5in main,['ruby-on-rails'] +161043,facebook app via php sdk redirecting back to page where someone added my app after getting permissions i have little problem when i need my app to ask user to grant permissions to the app i use following codephploginurl facebookgetloginurlarray canvas 1 fbconnect 0 scope emailpublish streamoffline accessecho script typetextjavascripttoplocationhref loginurlscripti works ok but after user press grant permissions he is redirected to my app url i mean like directly not my app page on facebook i can work around it i know my apps facebook address so i redirect him to proper it works ok too but when somebody adds my application on some page tab here is where problem appears because i do not know where to redirect user anymore i do not know from what page my app was called is there any way to get to know from what page my app was called or even better to make facebook properly redirect user to the facebook page where app tab were added after grant permission dialog,['php'] +161057,how to perform file upload monitoring with play framework is it possible to monitor file uploads somehow with play framework also if the file should be big ie 500mb would it be possible to save the received bytes into a temporary file instead of keeping it in memory see update belownote there is no code to show as i am wondering these questions and cannot seem to find the answers with googlethanks update i almost forgot about this question well apparantly files uploaded are stored in temporary files and the files are not passed as a byte array or something but as a java file object to the action controllerbut even in a restful environment file monitoring can be achieved update 2 is there a way to get early event listeners on incoming http requests this could allow for monitoring request data transfer,['java'] +161062,eclipse plugin for generating a class diagram what is a good eclipse plugin for generating a class diagram for a projectthis image right here is exactly what i am talking about,['java'] +161070,android multiple videoview problem galaxy tab specific i am having problems with multiple videoviews specifically on galaxy tabin my app i have two different video files which i want to play simultaneously so i designed my app to have two videoviews side by side tried to run it on two non galaxy tabs and it worked easy as that but then i tried to test it on my galaxy tab and the problem comes out the two video file does not play at some point the first video file plays and then stops and pops up the cannot play video error i spent almost two days looking for the cause of the problem and i failed that is why i resorted to guessing what could be the causemy suspicion was that it cannot render two videos at the same time so i tried to play only the sound of the first file using mediaplayer and play the other one in the videoview and i think my suspicioin was right because it works the first video file plays only the sound and the other one plays the full video and the soundi am looking for someone with this kind of problem or someone who knows a workaround for this i will post my simple code here for you to take a look at it i would really appreciate your help thanks in advancejunmatsfinal videoview v1 videoview findviewbyidridvideoview1final videoview v2 videoview findviewbyidridvideoview2 thread th1 new threadnew runnable override public void run uri urifile uriparsemyfile v1setvideouriurifile v1start th1start thread th2 new threadnew runnable override public void run uri urifile uriparse v2setvideouriurifile v2start th2start,['android'] +161073,application shown as threat by avg i am working on project in vbnet that includes socket communication and embedded httplisteners this is a group of applications that intercommunicate using sockets my problem is from few days i received report of antivirus avg showing one of executable as threat looking into the matter i was thinking to replace sockets with namedpipes but still http listener would remain therehow can i solve this problem,"['c#', '.net']" +161077,how to use windowscroll to automatically scroll on pageload function scrolldown windowscroll0300 how can i use this function or a similar one to automatically scroll down when the page loads without clicking a linkregardstaylor,['javascript'] +161090,whats the difference between html and tags whats the difference between head tags and body tagsmost html books only briefly mentions head and body tagsbut they just go away really fastdo they affect how browsers render web pagesalso do they affect the order in which javascripts are runi mean if i have a javascript inside a head tag would it run before another javascript inside body tag even when body came before headthis is too confusingi have not ever used a headbody tags but i never had any trouble with itbut while reading jquery tutorial i saw people recommending putting some codes inside head and the others inside body tagsthank you,"['javascript', 'html']" +161097,unitintegration testing ftp access a member of my team is writing an application that accesses an external ftp site to download files having written the code we would like to be able to do integration testing without using a physical ftp server as it is an external sitewe have done similar things in the past using ndumpster for simulating an smtp server in code and we are wondering if there are any equilivent compliant ftp servers that can be usedediti should add that these are not for true unit tests we have those and mock our ftp implementation however we are using webftprequestcreate in the actual implementation of the interface so testing this code requires an actual server unless we register our own protocol in the tests eventually we will have to test against an actual server we want to be able to start and stop the ftp server in code much like you can ndumpster and examine that our calls are correct,['c#'] +161098,remove seconds from timespan editorfor i am creating a view containing a form in aspnet mvc3 for a model containing time spans i was wondering if there is a way that i can prevent the text box that is rendered from showing the seconds part so that instead of 1230 i would get 1230 here is what i have in the model and viewmodelrequireddatatypedatatypetimepublic timespan start get set viewdiv classeditorfield htmleditorformodel modelstart htmlvalidationmessageformodel modelstart divany advice would be much appreciated,['c#'] +161109,real world example about how to use property feature in python i am interested in how to use property in python i have read the python docs and the example there in my opinion is just a toy codeclass cobject def init self self x none property def xself i am the x property return self x xsetter def xself value self x value xdeleter def xself del self xi do not know what benefits i can get from wrapping the x filled with the property decorator why not just implement asclass cobject def init self selfx nonei think the property feature might be useful in some situations but when could someone please give me some realworld examplesthanks,['python'] +161124,split nsstring multiple times on the same separator i am currently receiving a string like thissam26hannah22adam30carlie32jan54and i am splitting it like thistestarray nsarray alloc initnsstring teststring nsstring alloc initwithformatsam26hannah22adam30carlie32jan54steve56matty24bill30rob30jason33mark22stuart54kevin30testarray teststring componentsseparatedbystringdict nsmutabledictionary dictionaryfor nsstring s in testarray testarray2 s componentsseparatedbystring dict setobjecttestarray2 objectatindex1 forkeytestarray2 objectatindex0i will now be receiving a string like thissam26developerhannah22team leaderadam30directorcarlie32pajan54cleanercan i and how use the same method as above to separate the string more than once using the separator,['objective-c'] +161127,how can i modify a web page using google chrome content script before the dom is processed using chrome content scripts i want to remove several iframes in a webpage before their content is loaded i found that using the property run atdocument start in the extentions manifest my javascript is executed just after the main page request and before the dom is processed and images iframes etc are loaded logicaly at this point the dom structure is not availabel and i can not modify the page using commands likemyelementdocumentgetelementbyidiframexmyelementparentnoderemovechildmyelementhow can i access and modify the reqeusted page data then,['javascript'] +161167,akka remote actor server thiscovery i would like to deploy a remote actors software made with akka on a cluster the system is composed of several worker nodes and a single master node the problem is that i cannot know in advance the ip address of the cluster nodes but i know they are all part of the same subnetwork so i need a nice way of thiscovering the ip address of everyone after startup to create the correct actor refs on each nodei am looking for a ligtweight solution i just need it for the initial setup thistributed under any free software license,['java'] +161179,c equivalent of cs func the following code computes the average of a particular property of t in the items collectionpublic double averagetilistt items funct double selector double average 00 for int i 0 i itemscount i average selectoritemsi return average itemscounti can then call this with a lambda expressiondouble average averageitems p ppropertynamehow would i go about doing this in c heres what i have so fartemplate typename tdouble averageconst vectort items double average 00 for int i 0 i itemssize i average return average itemssizehow might i go about calling this with a c lambdaedit thank you all very much heres what i ended up withtemplate typename tdouble averageconst vectort items functiondoublet selector double result 00 for auto i itemsbegin i itemsend i result selectori return result itemssizeand in mainzombie z1z1hit points 10zombie z2z2hit points 5itemspush backz1itemspush backz2double average averagezombieitems const zombie z return zhit points,"['c#', 'c++']" +161193,ruby on rails passing parameter in url this is probably a very simple fix but i have been unable to find an answer just yetmy application has orders and tasks orders have many tasks when a user clicks new task in the show order view it passes the orderid link to new task new task pathorder id orderid the url showstasksneworder id1i just do not know how to extract this and use it in my form i have tried ftext field order id value order id but it is not working,['ruby-on-rails'] +161204,a question about class definition in c 1 possible duplicatewhat does unsigned temp3 means i encountered a problem when i am reading the code of clangclass langoptions public unsigned trigraphs 1 trigraphs in source files unsigned bcplcomment 1 bcplstyle comments this is the first time i saw the syntax 1 whats the 1 stands for thanks,['c++'] +161211,load https url in a uiwebview i begin iphone programming and i have big problem i cant resolveso i have a uiwebview i can load http url without problems nsstring urladressurladress httpservernamensurl url nsurl urlwithstringurladressnsurlrequest requestobj nsurlrequest requestwithurlurlwebview loadrequestrequestobjits work my page is load in my uiwebview but when i replace urladress httpservernamebyurladress httpsservernamei have blank screeni read its normal but is there easy method to load https url in my webview i read about asihttprequest but i didnt arrive to implement iti just want to load https url,['ios'] +161225,determine device public ip does anyone know how i could get the public ip address of an android devicei am trying to run a server socket just experimenting with simple p2pthis requires informing the local and remote users of each others public ip i did find this thread how to get ip address of the device which contains a link to an article that shows how to get the ip however this returns the local ip when connected through a router and i would like to get the actual public ip insteadtia,['android'] +161235,ruby method that returns itself i am doing some reflection and ran into an unexpected road blockis there an object method in ruby or rails that returns itselfruby192 o objectnew object0x0104750710 ruby192 oclass object ruby192 osend selfnomethoderror undefined method self for object0x0104750710what i wantruby192 osend self object0x0104750710 is this built in or do i need to extend object it always gets me nervous opening up objectclass object def itself self endendand then soruby192 osend itself object0x0104750710 ok some background on what i am trying to achieve i have a generic table helper in my rails app and you call if like so render list person field name link to itself field address name link to addressi was struggling on the right way to call itself but i am thinking that my patch is the way to go,"['ruby-on-rails', 'ruby']" +161247,mvc mini profiler includes not respecting applications path i have got the mvc mini profiler set up as described on its project page and the includes are indeed being written on the pageproblem is my application sits at httplocalhost8080web and the markup written by the profiler includes looks like thislink relstylesheetless typetextcss hrefminiprofilerincludeslessv20417717902script typetextjavascript srcminiprofilerincludesjsv20417717902scriptscript typetextjavascript jqueryfunction miniprofilerinit idfb4dc30ec1aa4be6902cef2812dd1fe2 renderdirectionleft scriptthese all of course give 404 errors but if i navigate to webminiprofilerincludesless it loads finethe source that creates that string can be found here miniprofilerhandlercs summary understands how to route and respond to miniprofiler ui urls summarypublic class miniprofilerhandler iroutehandler ihttphandler internal static htmlstring renderincludesminiprofiler profiler renderposition position null bool showtrivial false bool showtimewithchildren false const string format link relstylesheetless typetextcss href0miniprofilerincludeslessv1 script typetextjavascript src0miniprofilerincludesjsv1script script typetextjavascript jqueryfunction miniprofilerinit id2 path0 renderdirection3 showtrivial 4 showchildrentime 5 script var pos position miniprofilersettingsrenderpopupbuttononright renderpositionright renderpositionleft var result profiler null stringformatformat ensureendingslashhttpcontextcurrentrequestapplicationpath miniprofilersettingsversion profilerid postostringtolower showtrivial true false showtimewithchildren true false return new htmlstringresult rest of the codewhy is not requestapplicationpath returning my applications path am i doing something wrong or should i file an issue on the mvcminiprofiler pageedit to make things even weirder i put a breakpoint on the miniprofilerrenderincludes call and checked what the value of httpcontextcurrentrequestapplicationpath was at that moment and it was web very mysteriousedit 2 looks like they may have added support for virtual paths in the latest version 2 hours ago and the nuget package which is how i installed it is not completely up to date investigating,['asp.net'] +161274,if contains certain text then run jquery i need to run a jquery only if the bold element contains particular text what am i doing wrong script if bcontainschoose a sub category tdcolors backgroundneutralcssbackgroundcolortransparent tdcolors backgroundneutralchildrenfirstchildattrcellpadding0 script,['jquery'] +161284,difference between class initializers in c possible duplicatewhy are c 30 object initializer constructor parentheses optional what is the difference between instatiating an object by usingclassinstance new class prop1 prop2 andclassinstance new class prop1 prop2,"['c#', '.net']" +161294,how to get relative path in javascript in my aspnet web project i have written the following javascript code in a js filefunction getdevicetypes var devicetypes ajax async false type post url controlsmodelselectorwebmethodsaspxgetdevicetypes data contenttype applicationjson datatype json success functionresponse devicetypes responsed error functionxhr status debugger alerterror getting device types end ajax return devicetypesit was working great until i tried to load this js file into a page in a subdirectorylet us suppose that the name of my project is widgetwhen i use this code in the main virtual directory javascript interprets controlsmodelselectorwebmethodsaspxgetdevicetypes to mean and all is well however from the page in a subdirectory javascript interprets it to mean and it does not workhow can i write my javascript code so that the ajax web method can be called from pages in any directory in my application,"['javascript', 'jquery', 'asp.net']" +161295,declare a memberfunction of a forwarddeclared class as friend is it possible to declare a member function of a forwarddeclared class as friend i am trying to do the followingclass bigcomplicatedclassclass storage int data public int data return data ok but provides too broad access friend class bigcomplicatedclass error invalid use of incomplete type friend void bigcomplicatedclassmodifystorage so the goal is to i restrict the friend declaration to a single method and ii not to include the definition of the complicated class to reduce compile timeone approach might be to add a class acting as an intermediary in storagehclass bigcomplicatedclass helperclass storage friend class bigcomplicatedclass helper in bigcomplicatedclasshclass bigcomplicatedclass helper static int accessdatastorage storage return storagedata friend void bigcomplicatedclassmodifystoragehowever this seems a bit clumsy so i assume that there must be a better solution,['c++'] +161311,keypress event not working in ie and chrome but working in ff any idea why this might happen i would usually think that chrome would be more forgiving with the codesdocumentkeypressfunctione ifekeycode 39 rightimage ifekeycode 37 leftimagethats what my keypress key looks like am i missing something rightimage and leftimage are functions which should be working becase i am using those functions somewhere else toothanks for the help,['jquery'] +161330,cxf no message body writer found for class automatically mapping nonsimple resources i am using the cxf rest client which works well for simple data types eg strings ints however when i attempt to use custom objects i get thisexception in thread main orgapachecxfinterceptorfault no message body writer found for class class comcompanydatatypenormalmyobject at orgapachecxfjaxrsclientclientproxyimplbodywriterhandlemessageclientproxyimpljava523 at orgapachecxfphasephaseinterceptorchaindointerceptphaseinterceptorchainjava263 at orgapachecxfjaxrsclientclientproxyimpldochainedinvocationclientproxyimpljava438 at orgapachecxfjaxrsclientclientproxyimplinvokeclientproxyimpljava177 at proxy13executeunknown source at comcompanyjaxtestclientmainjaxtestclientjava26caused by orgapachecxfjaxrsclientclientwebapplicationexception no message body writer found for class class comcompanydatatypenormalmyobject at orgapachecxfjaxrsclientabstractclientreportmessagehandlerproblemabstractclientjava491 at orgapachecxfjaxrsclientabstractclientwritebodyabstractclientjava401 at orgapachecxfjaxrsclientclientproxyimplbodywriterhandlemessageclientproxyimpljava515 5 morei am calling it like thisjaxexample jaxexample jaxrsclientfactorycreate httplocalhost81 jaxexampleclass myobject before myobject after jaxexampleexecute before here is the method in the interfacepostpath execute produces applicationjson myobject execute myobject myobject the restlet library does this quite simply by adding the xstream dependency to your path it just works does cxf something similaredit 1i have posted this as a feature improvement to the cxf issue management system here i can only hope this will get attended to,['java'] +161331,firefox 3 html commenting issue so i have a site where there are a lot of places where html comments are written as i noticed that when you write divhellodiv comment divhello2divonly hello2 shows if you do not type in the dashes at the end divhello3div comment divhello4divthen both hello3 and hello4 are printed now is there a way for me to make this work how it is suposed to without going through the whole site and changing all the commentsbtw it shows fine in all browsers including firefox 4 and even ie the problem only occurs on ff 36,['html'] +161350,restsharp json parameter posting i am trying to make a very basic rest call to my mvc 3 api and the parameters i pass in are not binding to the action methodclientvar request new restrequestmethodpostrequestresource apiscorerequestrequestformat dataformatjsonrequestaddbodyrequestjsonserializerserializenew a foo b bar restresponse response clientexecuterequestconsolewritelineresponsecontentserverpublic class scoreinputmodel public string a get set public string b get set apiscorepublic jsonresult scorescoreinputmodel input inputa and inputb are empty when called with restsharpam i missing something here,['c#'] +161351,dynamic method call in objectivec how can i call a selector with its name in nsstring in objective c i also need to call the selector only if the target will accept it egvoid callmethod nsstring method onobject id object do some magicwhen i call callmethod foo onobject obj if obj implements foo then obj foo should be called if it does not implement it nothing should happen,['objective-c'] +161364,codeigniter passing arguments from view to controller edit with the code below now i am unsure on how to print out the bookmarks and the tags correctlyiam completely new to ci and i have recently hit a road block iam very unsure how i would go about passing a function argument from the view file to the controller so i could use it on a functioni have a foreach loop on the view going through the all the items passed by function get latest bookmarks that function returns a id for each item and i am wanting to use this with another function called get bookmark tags which will get the tags of the bookmark from another table i have provided the code i have done so far belowmodelphp class bookmark model extends ci model function construct parent construct function get latest bookmarkslimit load database thisloaddatabase query database query thisdbgetbookmark limit return result return query function get bookmark tagsid load database thisloaddatabase query thisdbqueryselect tagtitle from tag inner join bookmarktag where bookmarktagbookmarkid id and tagtagid bookmarktagtagid return query controller php if definedbasepath exitno direct script access allowedclass welcome extends ci controller public function index load url helper thisloadhelperurl load user library thisloadlibraryion auth is user logged in if thision authlogged in datauser thision authget user array else redirectauthlogin load bookmark model thisloadmodelbookmark model create arrays bookmarks array tags array query database query thisbookmark modelget latest bookmarks4 foreach queryresult as row array pushtags thisbookmark modelget bookmark tagsrowbookmarkid array pushbookmarks row datatags latest tags databookmarks latest bookmarks thisloadviewwelcome message data view h1latest bookmarksh1php foreach bookmarks latest as bookmark php print rbookmark php print rtags latestresult php endforeach,['php'] +161374,dynamically create an activity i want to create an activity dynamically something likeactivity a new activityis it possible do i need a special permission or is it simply not possible the error i get i do not get any exception but the program stops when i try to use this instruction,['android'] +161378,does constcorrectness give the compiler more room for optimization i know that it improves readability and makes the program less errorprone but how much does it improve the performanceand on a side note whats the major difference between a reference and a const pointer i would assume they are stored in the memory differently but how sothanks,"['c++', 'c']" +161380,post an array of custom objects to a struts 2 action how do i post an array of custom objects to a struts 2 action in javafor example if i have the following java objectpublic class person private string name private string lastname public string getname return name public void setnamestring name thisname name public string getlastname return lastname public void setlastnamestring lastname thislastname lastname and the following actionpublic class savepersons extends actionsupport private listperson persons override public string execute throws exception do something return success public void setpersonslistperson persons thispersons persons i would like to do something like this in an html formhtmlbodyform methodpost actionhttpposthere input typetext namepersons0name valuename1 input typetext namepersons0lastname valuelastname1 input typetext namepersons1name valuename2 input typetext namepersons1lastname valuelastname2 input typesubmit formbodyhtmlany tips,['java'] +161422,javascript search array of arrays let us say we have the following js arrayvar ar 268945 35662379 434677923var val 35662379is there a js builtin function or jquery one with which you can search the array ar for valthanksupdatetaking fusions response i created this prototypearrayprototypecontainsarray functionval var hash forvar i0 ithislength i hashthisi i return hashhasownpropertyval,['javascript'] +161433,how to solve attributeerror when importing igraph when i import the igraph package in my project i get an attributeerror this only happens in the project directory1234 python2python 271 r27186832 apr 15 2011 120910 gcc 452 20110127 prerelease on linux2type help copyright credits or license for more information import igraph 1234 cd projectdir1234projectdir python2python 271 r27186832 apr 15 2011 120910 gcc 452 20110127 prerelease on linux2type help copyright credits or license for more information import igraphtraceback most recent call last file stdin line 1 in module file usrlibpython27sitepackagesigraph init py line 42 in module import gzip file usrlibpython27gzippy line 36 in module class gzipfileiobufferediobaseattributeerror module object has no attribute bufferediobasethere is no file igraphpy in the project directory1234projectdir ls alr grep igraph wc l0and there are no circular importshow can i solve this error,['python'] +161438,when an array is created by a subexpression what happens with the temporaries therein i was reading these two paragraphs of the fthis 122p45there are two contexts in which temporaries are destroyed at a different point than the end of the fullexpression the first context is when a default constructor is called to initialize an element of an array if the constructor has one or more default arguments the destruction of every temporary created in a default argument is sequenced before the construction of the next array element if anyandthe second context is when a reference is bound to a temporary the temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference except a temporary bound to a reference parameter in a function call 522 persists until the completion of the fullexpression containing the callthese two two seem to contradict for the following casestruct a a stdcout c stdendl a stdcout d stdendl struct b ba const a a typedef b array2int main arraywill this output cdcd as required by the first context or will this output ccdd as required by the second context gcc seems to follow the second context description and outputs ccdd have i overlooked something important edit i do not think it needs c0x this newexpression is affected too by my questionnew array cdcd or ccdd in this case though gcc follows the first context and outputs cdcd,['c++'] +161444,wrong output when using array indexing on utf8 string i have encountered a problem when using a utf8 string i want to read a single character from the string for examplestring a14aecho string0i am expecting to see a14 but i get i12 why,['php'] +161455,facebook api invalid signed request invalid signature i am tryng to use facebook authentication at but after logging in with facebook the callback page thisplays invalid signed request invalid signature the app id and secret are correct and no other information seems to be logged this happens every time i try to log in with facebookeditto make the call i am using pretty much the exact code as the samplein the markupiframe src thisregistrationurl scrollingauto frameborderno stylebordernone allowtransparencytrue width100 height500 iframein the codebehindpublic string registrationurl get var url stringformat id0redirect uri1fields2 facebookapplicationcurrentappid httputilityurlencodeappbllgetabsoluteurlaccountfbregcallbackaspx httputilityurlencodenamenamenameemailnamelocationnamepasswordviewnot prefillednamecaptcha thisregisterusercontinuedestinationpageurl thisrequestquerystringreturnurl thishdnpasslengthvalue membershipminrequiredpasswordlengthtostring httputilityurlencodenamenamenameemailnamelocationnamepasswordviewnot prefillednamecaptcha thishdnpasslengthvalue membershipminrequiredpasswordlengthtostring,['asp.net'] +161472,how to make layout with view fill the remaining space i am designing my application ui i need a layout looks like this and are buttons the problem is i do not know how to make sure the textview will fill the remaining space with two buttons have fixed sizeif i use fill parent for text view the second button cannot be shownhow can i craft a layout that looks like the image,['android'] +161482,virtual constructors i was wondering what is the meaning of a virtual constructor and how would it be usedin addition i know that c does not allow for a virtual constructor and i was wondering why,['c++'] +161491,object was probably modified after being freed i am working on a project on iphone i am now initiating a new uiviewcontroller from another uiviewcontroller and then switch between them here is my codeigreenappdelegate delegate uiapplication sharedapplicationdelegateifcheckinviewcontroller checkinviewcontroller release checkinviewcontroller nilcheckinviewcontroller checkinviewcontroller alloc initwithcheckpointcheckpointuiview beginanimationsnil contextniluiview setanimationduration08uiview setanimationtransitionuiviewanimationtransitionflipfromleft forviewdelegate window cacheyesdelegate roottabbarcontrollerview removefromsuperviewdelegate window addsubviewcheckinviewcontrollerviewuiview commitanimationsthe problem is the second time i initiate the uiviewcontroller i want to release it to avoid causing memory leak the debugger thisplaysigreen9160x3f60348c malloc error for object 0x130350 incorrect checksum for freed object object was probably modified after being freed set a breakpoint in malloc error break to debugthis is strange because similar codes in other parts do not return such error moreover i tried autorelease but the program will immediately crash and the debugger says i am modifying finalized layersi have been working on the problem for a whole night and still confused about it,['ios'] +161492,using nsdate within an nspredicate is there a particular way to configure an nspredicate to compare datesessentially i have a photo object that has an nsdate lastviewedi would like to configure an nspredicate that will return all the photo objects that have been viewed more recently than a specified time period typically two daysi am obtaining the past date like sonstimeinterval secondspast 172800nsdate twodayspast nsdate datewithtimeintervalsecondspast sincedatensdate dateand configuring the nspredicate thuslyrequestpredicate nspredicate predicatewithformatlastviewed twodayspasthowever i am getting no results back and i am not quite certain whyi know that all my photo objects have lastviewed set it is set to a default value of now whenever the photo is added to core data so by default i should be seeing every photo created as lastviewed will be more recent than my twodayspast nsdatecan i directly compare two instances of nsdate in this manner,"['iphone', 'ios']" +161495,can i use moq to verify that a mocked method was called with specific values in a complex parameter so assume i am mocking the following classpublic class classaparams public int requestedid get set public string somevalue get set public class classa public void executeactionclassaparams executeparams now say i have another class let us call it classb that i am creating a unit testing for and i want to make sure that when classbexecute is called that classb calls classaexecuteaction but i want to make sure that the parameter it calls that method with has a classaparamsrequestedid value of 1normally i would handle this by doing mymockverifyx xexecuteactionnew classaparams requestedid 1 somevalue something the problem is i do not want to check the value of the somevalue parameter or any other classaparams properties in this unit test the other properties will be checked in other unit tests but having to verify that it is called with the correct properties in every unit test even when i do not care in the scope of a specific unit tests will make unit maintenance annoyingis there any way to use moq to verify that the structure that gets passed into a mocked method only has certain properties as a specific value and ignore the rest,['c#'] +161499,how can i splice a string i know i can slice a string in python by using array notation str16 but how do i splice it ie replace str16 with another string possibly of a different length,['python'] +161506,how to convert systemcurrenttimemillis to seconds how to convert systemcurrenttimemillis to secondslong start6systemcurrenttimemillissystemoutprintlncountercountprimes10 for start6the console shows me 5761455 for 1307816001290i cannot read how many seconds that isany help,['java'] +161509,should i bind to icollectionview or observablecollection should one bind datagrid to theicollectionview collectionviewsourcegetdefaultviewcollectionor to theobservablecollectiont collection what is the best practice for mvvm and why,"['c#', '.net']" +161513,you have already activated x but your gemfile requires y when running rake i get this erroryou have already activated rake 092 but your gemfile requires rake 087 consider using bundle execusing bundle exec rake instead of just rake seems to work but is it the best way to fix this,['ruby'] +161539,javascript equivalent of perls q e or quotemeta in perl regular expressions you can surround a subexpression with q and e to indicate that you want that subexpression to be matched as a literal string even if there are metacharacters in there you also have the quotemeta function that inserts exactly the right number of backslashes in a string so that if you subsequently interpolate that string into a regular expression it will be matched literally no matter what its contents weredoes javascript as deployed in major browsers have any built in equivalent i can write my own just fine but i would like to know if i do not have to bother,['javascript'] +161542,is there a way to force eclipse to automatically restart remote debugging in listen mode i am using eclipse to remote debug an application that is in debug clientmode ie xrunjdwptransportdt socketaddress12700180 jvm startup parameters and eclipse has socket listen mode selected in the debugger settings instead of the default socket attach mode problem is once the remote application is started connects to the eclipse debugger and finally exits the eclipse debugger stops listening for connections on the specified port just an annoyance but it would be nice not to have to keep clicking on the debug button in eclipse every time i need to debug the application which needs to be started from outside of eclipse obviously any ideas or tools out there for making this a little more automatic,['java'] +161562,is there a tool that generates pinvoke signatures for arbitrary unmanaged dll i stumbled upon a tool that generates pinvoke signatures for microsofts own unmanaged dlls pinvoke interop assistantis there a similar tool that will generate pinvoke signatures for thirdparty unmanaged dllsalternately any way to feed a thirdparty dll to pinvoke interop assistantedit actual issue i am trying to resolve,"['c#', '.net']" +161571,iphone custom pin position issue i have an application that uses iphone map kit it shows set of standard pinsnow i switch to custom images for pins using mkmapviewdelegatethe problem is that custom pins are not centered right custom pin pointing to a location near originalthe question is how iphone works with custom pin for example let us have a image for pin 50x50 pixels and we have global coordinate long lat xyhow will iphone center imagethank you,['iphone'] +161587,drawing smoke effects with java is there any way to draw a smoke effect in java by using java2d api i want to achieve this when a user provides the color for the smoke the program automatically draws a smoke effect with that color how could i do this,['java'] +161592,debugging and preprocessor directive for debugging i have many calls to a debug log function in my application of course in the production version these debugging calls need to be skipped instead of writingif devel 1 logdebugendifaround all calls to the debug function i decided the write the following in the debug function itselfif devel 1 returnendifwill the overhead of the useless function call be avoided by the compiler or am i better off by using many ugly if endif construction for performance reasons,['c++'] +161605,python logging how to set time to gmt is it possible and how to set the logging timezone to gmtie the asctimes parameter in the format,['python'] +161606,is there any advantage to using powx2 instead of xx with x double is there any advantage to using this codedouble xdouble square powx2instead of thisdouble xdouble square xxi prefer xx and looking at my implementation microsoft i find no advantages in pow because xx is simpler than pow for the particular square caseis there any particular case where pow is superior,['c++'] +161607,how expensive is fileexists in java i am wondering how fileexists works i am not very aware of how filesystems work so i should maybe start reading there firstbut for a quick pre informationis a call to fileexists a single action for the filesystem if that path and filename are registered in some journal or does the os get the content of the directory and then scan through it for matchesi presume this will be filesystem dependant but maybe all filesystems use the quick approachi am not talking about network and tape systems lets keep it to ntfs extx zfs jfs,['java'] +161617,passing a 2d array in a function in c program below program a toy program to pass around arrays to a function does not compileplease explain me why is the compiler unable to compileeither because of technical reason or because of standard reasoni will also look at some book explaining pointersmulti dimensional arraysas i am shaky on these but any offtheshelf pointers here should be usefulvoid print2int arrayint n int mmain int array412345678 int array2212345678 print2array24void print2int arrayint nint m int ij fori0ini forj0jmj printfd arrayij printfn,['c'] +161624,why there is no class like parameterizedthreadstart the class parameterizedthreadstart always takes object as parameter which i suppose was introduced in net 1011but after generics was introduced i am expecting a class like parameterizedthreadstartt which is still not therewas it missed oris there any other reason,['c#'] +161627,how to launch getattr function in python with additional parameters i want to call some unknown function with adding parameters using getattr function is it possible,['python'] +161640,how do positional arguments like 1 work with printf by man i find printfd width numand printf21d width numare equivalentbut imo the second style should be the same as printfd num widthhowever via testing it seems man is right why,['c'] +161649,should annotations in jar305jar be preferred over similar annotations in annotationjar for findbugs in the findbugs thistribution annotationsjar is not a subset of jsr305jar however several annotations seem to be duplicated either exactly or very closely should i prefer an annotation in jsr305jar if i have a choicenote that i am not just interested in knowing that it would be better to use annotations from jsr305jar simply because they represent a standard rather i want to know whether the findbugs tool will perform the same or better analysis if i prefer the jsr305jar version of a particular annotation it could be the case that some jsr305jar annotations should be preferred but others should noti am using findbugs 139 which is the most recent version as of this writing with this version i see the following choices please update this table if there are otherseduumdcsfindbugsannotationscheckfornull javaxannotationcheckfornulleduumdcsfindbugsannotationscheckreturnvalue javaxannotationcheckreturnvalueeduumdcsfindbugsannotationsnonnull javaxannotationnonnull nb capitalizationeduumdcsfindbugsannotationsnullable javaxannotationnullableeduumdcsfindbugsannotationswhen javaxannotationmetawhenalso all of the jcip annotations are duplicatednetjcipannotationsguardedby javaxannotationconcurrentguardedbynetjcipannotationsimmutable javaxannotationconcurrentimmutablenetjcipannotationsnotthreadsafe javaxannotationconcurrentnotthreadsafenetjcipannotationsthreadsafe javaxannotationconcurrentthreadsafe,['java'] +161651,should stdvectorswap with stateful allocators invalidate all iterators given allocators a1 and a2 where a1 a2and stdvectors v1a1 and v2a2then v1swapv2 invalidates all iteratorsis this expected behavior,['c++'] +161681,sibling package imports i have tried reading through questions about sibling imports and even thepackage documentation but i have yet to find an answerwith the following structurea licensemda readmemda apiaa a a init pyaa a a apipyaa a a api keypya examplesaa a a init pyaa a a example onepyaa a a example twopya testsaa a a init pyaa a a test onepyhow can the scripts in the examples and tests directories import from theapi module and be run from the commandlinealso i would like to avoid the ugly syspathinsert hack for every file surelythis can be done in python right,['python'] +161691,floating div madness upon window resize i am trying to create a purely html and cssbased layout that presents the main content of a page on the left which expands to the full width of the page minus the box and a smaller box on the right say for navigation or information of some sort here is an example of the code that is causing the problem with the problems described thereindoctype htmlhtml langen dirltrhead titlefloating div madness upon window resizetitle style margin0 padding0 body margin20px fontsize0px color0 divpage marginright120px backgroundcoloraff floatleft divwide width300px backgroundcoloraaffaa divbox width100px marginleft100px backgroundcolorffa floatleft h1 fontsizexlarge p paddingbottom5px fontsizesmall styleheadbody div classpage h1main pageh1 pthis is the main portion of the page light blue it is currently floated left with a right margin of 120px to account for the box light red as well as the white space between it and the box light red all may look well on the surface butp presize the window in firefox i tested both 35 and 4 and the white margin of the body can be cut off not only on the right side but on the bottom of the page toop premove enough text and this div will shrink to fit it no longer taking up the entire width of the page minus the boxp div classwide pif i nest another nonfloating div with a fixed width light green something even stranger happens when i resize the window this time in internet explorer 6 maybe in other versions too the text in the page div light blue is squished i think by the margin of the box light red the fixed width div light green is unaffected by thisp div div div classbox h1boxh1 pthis could be navigation or anything elsep divbodyhtmli would like to keep the box light red later in the code for semantic reasons but this is optional here are some of the more successful things i have already tried and why they do not seem to workabsolute positioning this appears just as nicely as my own code when the browsers are not resized it does address the thisappearing body margin in firefox to some degree however when the window size gets small enough the box light red will go over or under the main page div light blue depending on the which zindex i have higher or lowerfloating only the box this involves changing the html and placing the box light red before the rest of the content in the code this automatically expands the main page div light blue something i have not found a way to do without a given amount of content using the float method however the margins of the body are still removed in firefox the text still squishes in ie and box light red will still go over or under again depending on the zindex the main page div light blue when the window gets small enoughassigning minwidth to everything this was very successful in stopping the ie problem but requires some css work on a page that is any more complex than this and which will support different media types and it still does not address the body margin in firefox or give me a way to expand the main page div light blue without content since it is still floatingchanging the body margin to a border this does not solve the firefox problem either whether it is a border or a margin it gets chopped off on the right and bottom of the page when i use floatsadd the margin to the box this does not work for firefox either i can get a bottom margin on the main page content light blue to stay in place this is something that seems especially curious to me but a right margin on the box light red still gets cutany help would be greatly appreciated as i cannot find any sites or posts answering these problems much less describing that these problems exist i have certainly put in a large number of hours looking for and testing solutions,"['css', 'html']" +161703,server side validation in jquery dialog sorry for my language in english i can only read i want to do in aspnet mvc something like this1 show user a page2 open modal dialog jqueryui and show partial view3 validate user input data on client side4 if it is ok then validate input data on server5a if it is ok then i want reload page5b if there is a errors i want show its to user6 user can close dialog at any time with button on iti have problem width 5a and 6in firefox when i do server validate and click close button dialogclose when i get redirect to page that was call to validate data if i click x in header of dialog box it is close ok in opera it is the same situationadditional in firefox when i insert a good data and validation on server pass dialog box do not close it is work in operai do not have big experience in mvc and do not know if i do it right please look at my code and tell me if it is wrong and i should not do it that waycontroler codepublic actionresult createbr return partialviewnew userdtohttppostpublic actionresult createuserdto model ifmodelemail modelstateaddmodelerroremail wrong email return partialviewmodel return new emptyresult javascript on index pagescript typetextjavascriptvar dialog documentreadyfunction dialog divinsertdialog title insert resizable false modal true autoopen false ashowinsertclickfunction divinsertempty divinsertloadhomecreate function inputclosemodalclickfunction dialogdialogclose return false dialogdialogopen return false scriptdiv iddivinsert its a dive where i loads forma idashowinsertadd elementa link thats open dialogi import js files in order jquery161js jqueryui1813js jqueryvalidatejs jqueryvalidateunobtrusivejsthe form view looks like that import jsusing htmlbeginformhtmlvalidationsummarytruediv classeditorlabel htmllabelformodel modelnamedivdiv classeditorfield htmleditorformodel modelname htmlvalidationmessageformodel modelnamedivdiv classeditorlabel htmllabelformodel modelsurnamedivdiv classeditorfield htmleditorformodel modelsurname htmlvalidationmessageformodel modelsurnamedivdiv classeditorlabel htmllabelformodel modelemaildivdiv classeditorfield htmleditorformodel modelemail htmlvalidationmessageformodel modelemaildivp input typesubmit valuecreate idinputsubmit input typesubmit valueclose idinputclosemodal pscript typetextjavascriptinputsubmitclickfunction e epreventdefault var form divinsert form formvalidate if formvalid ajax url homecreate data formserialize type post success function data if data locationreload else divinserthtmldata validatorunobtrusiveparsedivinsert return false,['jquery'] +161708,using webbrowser in a console application i want to use it to invoke some js scripts on the webpage i have this static void stuff webbrowser browser new webbrowser browsernavigate htmldocument doc browserdocument docinvokescriptsomescript consolewritelinedoctostring static void mainstring args consolewritelinehi var t new threadstuff tsetapartmentstateapartmentstatesta tstart question 1 i get an object reference not set exception when i try to get doctostring whyquestion 2 how do i get some data from the html document into the main program webbrowser requires a separate thread which requires a static method which cannot return any value how do i return say doc to the main so i can do something with it,['c#'] +161736,how detect malloc failure what is the portable way to check whether malloc failed to allocate nonzero memory block,['c'] +161751,about the ambiguous description of sigwait if no signal in set is pending at the time of the call the thread shall be suspended until one or more becomes pending the signals defined by set shall have been blocked at the time of the call to sigwait otherwise the behavior is undefined the effect of sigwait on the signal actions for the signals in set is unspecifiedthis is really ambiguous whats the difference between pending and block hereand its conclusion on how to choose between sigwait and sigaction is not clear at allin summary when it is necessary for code run in response to an asynchronous signal to notify a thread sigwait should be used to handle the signal alterna tively if the implementation provides semaphores they also can be used either following sigwait or from within a signal handling routine previously registered with sigactioncan someone make the reason of sigwait more rational,['c'] +161758,best way to find a single record using activerecord 3 arel where i used to do thisfoofind by baravaluei can now do thisfoowherebar avaluelimit1firstis this recommended is this the best way should i continue to use the old way because it continues to be useful syntactic sugar or is there an even better way i can do that now which will support chaining and all the other good stuff,"['ruby-on-rails', 'ruby']" +161766,objective c how can you rotate text for uibutton and uilabel how can you rotate text for uibutton and uilabel 90 degrees 180 degreesthanks,"['iphone', 'objective-c']" +161768,ios and thisabling keyboard search or enter key is there any way to thisable the keyboards search or enter buttons in ios i would like to thisable these while the text in my uisearchbar is too short to commit a search,['ios'] +161812,can custom c classes replicate the performance of inbuilt types i am trying to create a c class that behaves exactly like the inbuilt int type with one exception everywhere that operator or operator is called addition is called insteadat first the performance of my class was very poor 12 that of the inbuilt int type but i noticed this was because i forgot to include the copy constructor belowstruct almostint almostint almostint const almostint a valaval forgetting this killed performance almostint operatorconst almostint a const almostint result this resultval aval return result almostint operatorconst almostint a const almostint result this resultval aval return result almostint operatorconst almostint a const almostint result this resultval resultval aval return result almostint operatorconst almostint a thisval aval return this almostint operatorconst almostint a thisval aval return this almostint operatorconst almostint a thisval thisval aval return this private int valunfortunately my program remains 25 slower than it should be examining the assembly generated for the two different versions of the program one using int the other using almostint i see that there is an identical number of and operations so things are working at some levelthe problem is that there are significantly more load and store operations in the code using the almostint class and not the native int operationdoes anyone have any ideas on where this overhead might be coming from the only guessi had was that perhaps the compiler does not understand that almostint has all thesame properties int does eg associativity commutativity but if this were reallya problem i would have expected a different number of or instructions in the code and this does not happeni suspect that the additional loads and stores are related to extra stack activity butall i can say at this point is it is not merely a few extra stack loads and stores at thetop and bottom of each function but the extra loads and stores occur throughout the codeany ideas i wonder if anyone can point me to a compiler that does allowone to reach ints level of performance with a custom classupdatehere is a simple function you can cut and paste to see whats going on for yourself on x8664 linux g 43 44 aix6 xlc and a couple of other platforms changing the choose one lines below should lead to the same code being generated or at least code of the same performance but in practice the code bloats significantly can anyone explain what is going on for any particular platformcompiler or how to fix itclass almostint int valuepublic almostint operatoralmostint that value thatvalue return this almostint operatoralmostint that value thatvalue return this almostint operatoralmostint that value thatvalue return this almostint operatoralmostint lhs almostint rhs lhs rhs return lhsalmostint operatoralmostint lhs almostint rhs lhs rhs return lhsalmostint operatoralmostint lhs almostint rhs lhs rhs return lhs choose one of the following two linestypedef int realtypedef almostint realtypedef struct real re real im complexdefine ra0a1b0b1wrewim t1 a0 a1 t2 b0 b1 t5 t1 wim t6 t2 wim t3 a0 t1 wre t3 a1 t2 wre t1 t6 t4 b0 t2 t5 t4 b1 a0 t3 b1 t2 a1 t4 b0 t1 define rzeroa0a1b0b1 t1 a0 a1 t2 b0 b1 t3 a0 a1 t4 b0 b1 b0 t1 a0 t3 b1 t2 a1 t4 void rpassreal a const complex w unsigned int n real t1 t2 t3 t4 t5 t6 t7 t8 real b unsigned int k b a 4 n k and 2 rzeroa0a1b0b1 ra2a3b2b3w0rew0im ra4a5b4b5w1rew1im ra6a7b6b7w2rew2im for ra8a9b8b9w3rew3im ra10a11b10b11w4rew4im ra12a13b12b13w5rew5im ra14a15b14b15w6rew6im if k 2 break a 8 b 8 w 4 credit where credit is due this little benchmark comes from the djbfft library by dan bernstein,['c++'] +161816,require returns an array instead of a boolean according to the documentation for kernelrequire the method returns a boolean value i noticed in a irb session however that for some files require returns an arrayruby187p330 001 require nethttp true ruby187p330 002 require date true ruby187p330 003 require libdata provider dataproviders the returned array contains the name of a module defined in data providerrbmodule dataproviders module cached class foo end end class foo endendis this a sign of me doing something wrong or some undocumented behavior of require,['ruby'] +161821,authorization in social networking website i need to accomplish the following related to privilegesi have 3 users user a user b user ceach of the users has the following documents with associated access settings user a document a1 only allow contacts to view document a2 allow everyone to view document a3 allow no one to view except myself document a4 allow contacts and contacts of contacts to view user b documents b1 b2 b3 b4 with similar privileges user c documents c1 c2 c3 c4 with similar privilegesuser a has user b as a contact but is not a contact of user c user b and user c are contactsthus user a would be able to view the following document b1 contacts can view document b2 everyone can view document b4 contacts of contacts document c2 everyone can view document c4 contacts of contactscould someone please explain how these privileges would be handled and if you could link me to any documentation or articles that would help me hit the ground running thank you,['python'] +161841,regex to match a css class name i am trying to write a regex that matches a valid css class name structure i have this so farpattern azazazazsregex preg match allpattern html matcheshowever a class name can be in the following formats that my regex would not matchpmy classpthisclas45these are just some cases i have looked around to find the rules of how you can name a class in a style block but could not find anything anyone know where the rules for the class naming conventions areare there any more cases that i need to consider what regex would you use to match a class name i have already narrowed it down to a style block using the php dom document class,"['php', 'css']" +161846,how to set dialog to show with full screen i have a gridview which show a lot of images and when i click any image it will show full image in a full screen dialog please tell me how to do that thanks,['android'] +161850,how can this recursive function for creating a range work from the selected answer in this soquestion this very ingenious function creates an array with a range from 1 to ifunction range1ireturn irange1i1concatiit works perfect call me stupid but i just cannot get my head around how it works let us say we have range15 now entering the function we have i so it returns itself with parameter i1 4 and concats i 5 to it but here i am stuck how does range1 know it has to do with an array i would say after the first run the return value as long as we have i so i0 would be a number and number has no concat method can someone explain this what am i missing,['javascript'] +161856,how to set the default value of a select box using jquery in ie9 i have the following select boxselect idselid option id1 value11option option id2 value22option option id3 value33option option id4 value44option option id5 value55optionselectin jquery i am doing the following to select the value 2 in the select boxselectselidfindoption2attrselected selectedthe same code sets the value of 2 in the select box in ie8 and firefoxbut its not working in ie9 i am using jquery 161 version,['jquery'] +161871,how to quit android application programmatically i found some codes for quit an android application programatically by calling any one of the following code in ondestroy will it quit application entirely systemrunfinalizersonexittrue orandroidosprocesskillprocessandroidosprocessmypidi dont want to run my application in background after clicking quit button pls suggest me can i use any one of these code to quit my app if so which code can i use is it good way to quit the app in android,['android'] +161873,finish all previous activities my application has the following flow screens homescreen 1screen 2screen 3screen 4screen 5now i have a common log out button in each screenshome screen 1 screen 2 screen 3 screen 4 screen 5 i want that when user clicks on the log out buttonfrom any screen all the screens will be finished and a new screen log in will open i have tried nearly all flag activity to achieve thisi also go through some answers in stackoverflow but not being able to solve the problemmy application is on android 16 so not being able to use flag activity clear task is there any way to solve the issue,"['java', 'android']" +161905,android market filesize limit 50mb or 4gb i have a game i want to publish but my apk size is 105 mb i saw that google announces they want to raise their limit to 4gb but i just tried to upload my 105 mb file and i received an error message saying my application was too big is the 4gb limit is a rumor or it is something that we will see pretty soonthankssimon,['android'] +161914,how to use typedef for a generic class in c i am trying to use unordered map but in some of the servers we do not have tr1 library in those cases i want to use the mapso i want to write a header file where i will use one of the following linestypedef tr1unordered map hashmaptypedef map hashmapmy problem is i am using different types of maps heremapstring stringmapstring intmap string mapstringint etcif i can use the typedef to alias map or unordered map as hashmap then i can use the map as hashmapstring string hashmapint int in the codeis there any way to do this or if there is any better way please suggest methanksvinod,['c++'] +161925,what is entity framework fluent api i keep hearing about the entity framework fluentapi but i am struggling to find a good reference on this what is itwe use the entity framework and the modeling tool provided is that all that is or is it something differentsimilarly if it is not too broad a question what is poco i know it stands for plain old clr objects but what does that mean to me as somebody who uses ef already with the designer model tool if that question is too vague then please ignore it i am just learning here and any information you are willing to provide is helpful,['c#'] +161949,adding images to buttons in interface builder i want to add an image to my button instead of text can i do this in interface builder any example i can look atthanksdeshawn,['ios'] +161957,how do i run until this variable changes when debugging when debugging my c i often want to know when a variables value changes and then investigate the state of the programcurrently i do it like thiswatchlist the offending variablephysically spam f10 shortcut for step over until i see the value changehowever the number of f10s required is annoyingsurely this has been automated i thought but i cannot find this feature in my microsoft visual c express which surprises me after all the watchlist does automatically highlight changed values in bright redam i missing something,['c#'] +161960,how to compare two lists of dicts in python how do i compare two lists of dict the result should be the odd ones out from the list of dict bexamplelda usernamea a76 b10 c455 d489 usernameb a467 b673 c00 d55ldb usernamea a76 b9 c455 d437 usernameb a677 b673 c11 d55 usernamec a899 b773 c22 d65here i want to compare lda with ldb it should print the below outputldb usernamea b9 d437ldb usernameb a677 c11 ldb usernamec a899 b773 c22 d65i have gone through the below link but there it return onlys the name but i want name and value like abovelist of dicts comparision to match between lists and detect value changes in python,['python'] +161962,does key value observing work on uitextviews text property i am having the worst time getting key value observing working in with a uitextviews text property i can successfully add the observer i can even remove that same observer i have a tableview with several cells some have uitextfields some have uisegmentselectors and one has a uitextview all the rest of the fields are successfully observed by my core data object subclass of nsmangedobject except for the uitextview i can post code if neededposted code uitableviewcell tableviewuitableview tableview cellforrowatindexpathnsindexpath indexpathstatic nsstring userprofilecellidentifier userprofilecellidentifieruitableviewcell cell tableview dequeuereusablecellwithidentifier userprofilecellidentifierif cell nil tablecellsnib instantiatewithownerself optionsnil switch indexpathrow username row case usernamerowindex textfieldcellcelabeltext nslocalizedstringusernamelabel user profile tableview textfieldcellcelltype celltypenormal textfieldcellboundproperty username textfieldcelltag indexpathrow textfieldcellerrorhandler self textfieldcellboundcontrol textfieldcellcelltextfield textfieldcell addobservermbutilities getappdelegateuserprofile forkeypathcelltextfieldtext optionsnskeyvalueobservingoptionnew contextnull cell textfieldcell selftextfieldcell nil break case passwordrowindex textfieldcellcelabeltext nslocalizedstringpasswordlabel user profile tableview textfieldcellcelltype celltypenormal textfieldcellcelltextfieldsecuretextentry yes textfieldcellboundproperty password textfieldcelltag indexpathrow textfieldcellerrorhandler self textfieldcellboundcontrol textfieldcellcelltextfield textfieldcell addobservermbutilities getappdelegateuserprofile forkeypathcelltextfieldtext optionsnskeyvalueobservingoptionnew contextnull cell textfieldcell selftextfieldcell nil break case passwordconfirmrowindex textfieldcellcelabeltext nslocalizedstringpasswordconfirmlabel user profile tableview textfieldcellcelltype celltypenormal textfieldcellcelltextfieldsecuretextentry yes textfieldcelltag indexpathrow cell textfieldcell selftextfieldcell nil break case firstnamerowindex textfieldcellcelabeltext nslocalizedstringfirstnamelabel user profile tableview textfieldcellcelltype celltypenormal textfieldcellboundproperty firstname textfieldcelltag indexpathrow textfieldcellerrorhandler self textfieldcellboundcontrol textfieldcellcelltextfield textfieldcell addobservermbutilities getappdelegateuserprofile forkeypathcelltextfieldtext optionsnskeyvalueobservingoptionnew contextnull cell textfieldcell selftextfieldcell nil break case lastnamerowindex textfieldcellcelabeltext nslocalizedstringlastnamelabel user profile tableview textfieldcellcelltype celltypenormal textfieldcellboundproperty lastname textfieldcelltag indexpathrow textfieldcellerrorhandler self textfieldcellboundcontrol textfieldcellcelltextfield textfieldcell addobservermbutilities getappdelegateuserprofile forkeypathcelltextfieldtext optionsnskeyvalueobservingoptionnew contextnull cell textfieldcell selftextfieldcell nil break case dateofbirthrowindex textfieldcellcelabeltext nslocalizedstringbirthdatelabel user profile tableview textfieldcellcelltype celltypedatepicker textfieldcellboundproperty dateofbirth textfieldcelltag indexpathrow textfieldcellerrorhandler self textfieldcellboundcontrol textfieldcellcelltextfield textfieldcell addobservermbutilities getappdelegateuserprofile forkeypathcelltextfieldtext optionsnskeyvalueobservingoptionnew contextnull cell textfieldcell selftextfieldcell nil break case genderselfrowindex genderselectcellcelabeltext nslocalizedstringusersexlabel user profile tableview genderselectcellboundproperty genderself genderselectcellerrorhandler self genderselectcellboundcontrol genderselectcellcellgendersegment genderselectcelltag indexpathrow genderselectcell addobservermbutilities getappdelegateuserprofile forkeypathcellgendersegmentselectedsegmentindex optionsnskeyvalueobservingoptionnew contextnull cell genderselectcell selfgenderselectcell nil break case genderinterestedinrowindex genderselectcellcelabeltext nslocalizedstringuserinterestedinlabel user profile tableview genderselectcellboundproperty genderinterestedin genderselectcellerrorhandler self genderselectcellboundcontrol genderselectcellcellgendersegment genderselectcelltag indexpathrow genderselectcell addobservermbutilities getappdelegateuserprofile forkeypathcellgendersegmentselectedsegmentindex optionsnskeyvalueobservingoptionnew contextnull cell genderselectcell selfgenderselectcell nil break case introductionrowindex textviewcellcelabeltext nslocalizedstringintroductionlabel user profile tableview textviewcellboundcontrol textviewcellcelltextview textviewcellerrorhandler self textviewcellboundproperty introduction textviewcelltag indexpathrow textviewcell addobservermbutilities getappdelegateuserprofile forkeypathcelltextviewtext optionsnskeyvalueobservingoptionnew contextnull cell textviewcell selftextviewcell nil break return cellthiscussion each cell is loaded from an external nib file then initialized with different properties all of the cells work with key value observing except for the very last one with the uitextview let me know if any additional info is needed,"['iphone', 'objective-c', 'ios']" +161968,no such file or directory after removing a duplicate subdirectory my app was building and running fine on the simulator and device but i noticed that for some reason i had a duplicate directory within my main directory and some duplicate files as well so while my main directory was myappname there were also files in myappnamemyappnamei carefully moved any nonduplicate files out of the subdirectory deleted the directory and updated the paths for my prefix header and infoplist files i cleaned and built the project however i am still getting an error from the compiler looking in the duplicate subdirectory which is deleted like soarmappledarwin10llvmgcc42 myappnamemyappnamemainm no such file or directorybecause mainm is now in myappnamemainmi do not see a variable or setting to look for other than the prefix header and infoplist files is there somewhere else i should look clearly something is still referencing the duplicate subdirectory but i do not see where,['iphone'] +161980,how does html5 deal with being able to run net managed code like silverlight does ok i am in the infancy stages of understanding html5 so bear with me i understand html5 is the obvious future for video streaming interactivity etc no question but one of the big pluses for silverlight since version 2 is the ability to run net managed code on the client yes it requires the silverlight plugin but this aside being able to run managed code is a powerful feature using wcf to get back to the server is a cinch so i like this ability and have embedded several silverlight controls on my aspnet pages because of its rich abilitywith all the talk about html5 pushing silverlight aside even directly or indirectly from msft is html5 going to be able to facilitate the running of managed net code clientside from the web like silverlight doesthanks,['.net'] +161989,where to initialize something once in a uiviewcontroller i have a uiviewcontroller subclass and i am trying to figure out what to override such that i can run some initialization code only once per object instancethe viewdidload method might seem like the obvious answer but the problem is that viewdidload may run more than once if the controller resets the view due to a memory warning the initwithnibnamebundle init and initwithcoder methods also seem like good choices but which one to override the awakefromnib method is another consideration but that does not seem to be executed in my view controlleris there a way to do this that i am missing,"['iphone', 'objective-c', 'ios']" +161991,php possible to automatically get all posted data simple question is it possible to get all the data posted to a page even if you do not know all the fieldsfor example i want to write a simple script that collects any posted data and emails it i can foresee that the fields in the form are likely to change a lot over time and so to save myself some time in the long run i was wondering if i could write something that automatically gathered everythingis it possible,['php'] +162000,how to instantiante object call setter on same line if i have an employee class with a default constructorprivate string firstnamepublic employeeand a setterpublic void setfirstnamestring firstname thisfirstname firstnamewhy does this attempt fail to instantiate and call the setter in the same lineemployee employee new employeesetfirstnamejohn,['java'] +162024,zombie process cannot be killed is there a way to kill a zombie process i have tried calling exit to kill the process and even sending sigint signal to the process but it seems that nothing can kill it i am programming for linux,['c'] +162029,heroku app crashed receiving invalid database url when attempting heroku rake dbmigrate i am new to programming and was following the rails tutorial by michael hartl when i ran into this while attempting heroku rake dbmigratein appappbundlegemsruby191gemsrake092librakefile utilsrb10 warning already initialized constant rubyappbundlegemsruby191gemsrake092librakefile utilsrb84 warning already initialized constant ln supportedrake abortedinvalid database urlerb9in rescue in mainerb6in mainusrruby192libruby191erbrb753in evalusrruby192libruby191erbrb753in resultappbundlegemsruby191gemsrailties301librailsapplicationconfigurationrb86in database configurationappbundlegemsruby191gemsactiverecord301libactive recordrailtierb58in block 2 levels in classrailtieappbundlegemsruby191gemsactivesupport301libactive supportlazy load hooksrb36in instance evalappbundlegemsruby191gemsactivesupport301libactive supportlazy load hooksrb36in execute hookappbundlegemsruby191gemsactivesupport301libactive supportlazy load hooksrb43in block in run load hooksappbundlegemsruby191gemsactivesupport301libactive supportlazy load hooksrb42in eachappbundlegemsruby191gemsactivesupport301libactive supportlazy load hooksrb42in run load hooksappbundlegemsruby191gemsactiverecord301libactive recordbaserb1867in top requiredappbundlegemsruby191gemsactiverecord301libactive recordmigrationrb486in initializeappbundlegemsruby191gemsactiverecord301libactive recordmigrationrb433in newappbundlegemsruby191gemsactiverecord301libactive recordmigrationrb433in upappbundlegemsruby191gemsactiverecord301libactive recordmigrationrb415in migrateappbundlegemsruby191gemsactiverecord301libactive recordrailtiesdatabasesrake142in block 2 levels in top requiredusrruby192libruby191rakerb634in callusrruby192libruby191rakerb634in block in executeusrruby192libruby191rakerb629in eachusrruby192libruby191rakerb629in executeusrruby192libruby191rakerb595in block in invoke with call chainusrruby192libruby191monitorrb201in mon synchronizeusrruby192libruby191rakerb588in invoke with call chainusrruby192libruby191rakerb581in invokeusrruby192libruby191rakerb2041in invoke taskusrruby192libruby191rakerb2019in block 2 levels in top levelusrruby192libruby191rakerb2019in eachusrruby192libruby191rakerb2019in block in top levelusrruby192libruby191rakerb2058in standard exception handlingusrruby192libruby191rakerb2013in top levelusrruby192libruby191rakerb1992in runusrruby192binrake31in main the application works perfectly on localserver but has crashed completely sayingan error occurred in the application and your page could not be served please try again in a few momentsif you are the application owner check your logs for detailsi get this error in logs20110613t2020470 appweb1 from appbundlegemsruby191gemsrailties301librailsinitializablerb25in instance exec20110613t2020470 appweb1 from appbundlegemsruby191gemsrailties301librailsinitializablerb25in run20110613t2020470 herokuweb1 process exited20110613t2020480 herokuweb1 state changed from starting to crashed20110613t2021290 herokurouter error h10 app crashed get deepbeach590herokucom dyno queue wait service bytes20110613t1321300700 herokunginx get http11 8644102112 796 http 50320110613t2024250 herokuweb1 state changed from crashed to created20110613t2024250 herokuweb1 state changed from created to starting20110613t2024310 herokuweb1 starting process with command thin p 16433 e production r homeheroku rackherokuru startanyone think they know whats causing the app to crashedit with more logs after restart20110614t12460 herokuweb1 state changed from starting to crashed20110614t1232320 herokuweb1 state changed from crashed to created20110614t1232320 herokuweb1 state changed from created to starting20110614t1232420 herokuweb1 starting process with command thin p 14587 e production r homeheroku rackherokuru start20110614t1232450 appweb1 erb9in rescue in main invalid database url runtimeerror20110614t1232450 appweb1 from erb6in main20110614t1232450 appweb1 from usrruby192libruby191erbrb753in eval20110614t1232450 appweb1 from usrruby192libruby191erbrb753in result20110614t1232450 appweb1 from appbundlegemsruby191gemsrailties301librailsapplicationconfigurationrb86in database configuration20110614t1232450 appweb1 from appbundlegemsruby191gemsactiverecord301libactive recordrailtierb58in block 2 levels in classrailtie20110614t1232450 appweb1 from appbundlegemsruby191gemsactivesupport301libactive supportlazy load hooksrb36in instance eval20110614t1232450 appweb1 from appbundlegemsruby191gemsactivesupport301libactive supportlazy load hooksrb36in execute hook20110614t1232450 herokuweb1 process exited20110614t1232460 herokuweb1 state changed from starting to crashed20110614t1245030 herokuweb1 state changed from crashed to created20110614t1245030 herokuweb1 state changed from created to starting20110614t1245080 herokuweb1 starting process with command thin p 15727 e production r homeheroku rackherokuru start20110614t1245110 appweb1 erb9in rescue in main invalid database url runtimeerror20110614t1245110 appweb1 from erb6in main20110614t1245110 appweb1 from usrruby192libruby191erbrb753in eval 20110614t1245110 appweb1 from usrruby192libruby191erbrb753in result20110614t1245110 appweb1 from appbundlegemsruby191gemsrailties301librailsapplicationconfigurationrb86in database configuration20110614t1245110 appweb1 from appbundlegemsruby191gemsactiverecord301libactive recordrailtierb58in block 2 levels in classrailtie20110614t1245110 appweb1 from appbundlegemsruby191gemsactivesupport301libactive supportlazy load hooksrb36in instance eval20110614t1245110 appweb1 from appbundlegemsruby191gemsactivesupport301libactive supportlazy load hooksrb36in execute hook20110614t1245110 appweb1 from appbundlegemsruby191gemsactivesupport301libactive supportlazy load hooksrb43in block in run load hooks20110614t1245110 appweb1 from appbundlegemsruby191gemsactivesupport301libactive supportlazy load hooksrb42in each20110614t1245110 appweb1 from appbundlegemsruby191gemsactivesupport301libactive supportlazy load hooksrb42in run load hooks20110614t1245110 appweb1 from appbundlegemsruby191gemsactiverecord301libactive recordbaserb1867in top required20110614t1245110 appweb1 from appappmodelsuserrb14in top required20110614t1245110 appweb1 from appbundlegemsruby191gemsactivesupport301libactive supportdependenciesrb239in require20110614t1245110 appweb1 from appbundlegemsruby191gemsactivesupport301libactive supportdependenciesrb239in block in require20110614t1245110 appweb1 from appbundlegemsruby191gemsactivesupport301libactive supportdependenciesrb227in load dependency20110614t1245110 appweb1 from appbundlegemsruby191gemsactivesupport301libactive supportdependenciesrb239in require20110614t1245110 appweb1 from appbundlegemsruby191gemsactivesupport301libactive supportdependenciesrb346in require or load20110614t1245110 appweb1 from appbundlegemsruby191gemsactivesupport301libactive supportdependenciesrb300in depend on20110614t1245110 appweb1 from appbundlegemsruby191gemsactivesupport301libactive supportdependenciesrb216in require dependency20110614t1245110 appweb1 from appbundlegemsruby191gemsrailties301librailsenginerb138in block 2 levels in eager load20110614t1245110 appweb1 from appbundlegemsruby191gemsrailties301librailsenginerb137in each20110614t1245110 appweb1 from appbundlegemsruby191gemsrailties301librailsenginerb137in block in eager load20110614t1245110 appweb1 from appbundlegemsruby191gemsrailties301librailsenginerb135in each20110614t1245110 appweb1 from appbundlegemsruby191gemsrailties301librailsenginerb135in eager load20110614t1245110 appweb1 from appbundlegemsruby191gemsrailties301librailsapplicationrb108in eager load20110614t1245110 appweb1 from appbundlegemsruby191gemsrailties301librailsapplicationfinisherrb41in block in modulefinisher20110614t1245110 appweb1 from appbundlegemsruby191gemsrailties301librailsinitializablerb25in instance exec20110614t1245110 appweb1 from appbundlegemsruby191gemsrailties301librailsinitializablerb25in run20110614t1245110 appweb1 from appbundlegemsruby191gemsrailties301librailsinitializablerb50in block in run initializers20110614t1245110 appweb1 from appbundlegemsruby191gemsrailties301librailsinitializablerb49in each20110614t1245110 appweb1 from appbundlegemsruby191gemsrailties301librailsinitializablerb49in run initializers20110614t1245110 appweb1 from appbundlegemsruby191gemsrailties301librailsapplicationrb134in initialize20110614t1245110 appweb1 from appbundlegemsruby191gemsrailties301librailsapplicationrb77in method missing20110614t1245110 appweb1 from appconfigenvironmentrb5in top required20110614t1245110 appweb1 from internallibrubygemscustom require29in require20110614t1245110 appweb1 from internallibrubygemscustom require29in require20110614t1245110 appweb1 from configru3in block 3 levels in main20110614t1245110 appweb1 from homeheroku rackherokuru23in eval20110614t1245110 appweb1 from homeheroku rackherokuru23in block 3 levels in main20110614t1245110 appweb1 from appbundlegemsruby191gemsrack123librackbuilderrb46in instance eval20110614t1245110 appweb1 from appbundlegemsruby191gemsrack123librackbuilderrb46in initialize20110614t1245110 appweb1 from appbundlegemsruby191gemsrack123librackbuilderrb63in new20110614t1245110 appweb1 from appbundlegemsruby191gemsrack123librackbuilderrb63in map20110614t1245110 appweb1 from homeheroku rackherokuru18in block 2 levels in main20110614t1245110 appweb1 from appbundlegemsruby191gemsrack123librackbuilderrb46in instance eval20110614t1245110 appweb1 from homeheroku rackherokuru11in block in main20110614t1245110 appweb1 from appbundlegemsruby191gemsrack123librackbuilderrb46in initialize20110614t1245110 appweb1 from homeheroku rackherokuru1in new20110614t1245110 appweb1 from usrruby192librubygems191gemsthin126libthinrunnerrb143in run20110614t1245110 appweb1 from usrruby192binthin19in load20110614t1245110 herokuweb1 process exited20110614t1245110 herokuweb1 state changed from starting to crashed20110614t1245110 herokuweb1 state changed from crashed to created20110614t1245110 herokuweb1 state changed from created to starting20110614t1245160 herokuweb1 starting process with command thin p 46054 e production r homeheroku rackherokuru start20110614t124520 appweb1 erb9in rescue in main invalid database url runtimeerror20110614t124520 appweb1 from erb6in main20110614t124520 appweb1 from usrruby192libruby191erbrb753in eval20110614t124520 appweb1 from usrruby192libruby191erbrb753in result20110614t124520 appweb1 from appbundlegemsruby191gemsrailties301librailsapplicationconfigurationrb86in database configuration20110614t124520 appweb1 from appbundlegemsruby191gemsactiverecord301libactive recordrailtierb58in block 2 levels in classrailtie20110614t124520 appweb1 from appbundlegemsruby191gemsactivesupport301libactive supportlazy load hooksrb36in instance eval20110614t124520 appweb1 from appbundlegemsruby191gemsactivesupport301libactive supportlazy load hooksrb36in execute hook20110614t124520 appweb1 from appbundlegemsruby191gemsactivesupport301libactive supportlazy load hooksrb43in block in run load hooks20110614t124520 appweb1 from appbundlegemsruby191gemsactivesupport301libactive supportlazy load hooksrb42in each20110614t124520 appweb1 from appbundlegemsruby191gemsactivesupport301libactive supportlazy load hooksrb42in run load hooks20110614t124520 appweb1 from appbundlegemsruby191gemsactiverecord301libactive recordbaserb1867in top required20110614t124520 appweb1 from appappmodelsuserrb14in top required20110614t124520 appweb1 from appbundlegemsruby191gemsactivesupport301libactive supportdependenciesrb239in require20110614t124520 appweb1 from appbundlegemsruby191gemsactivesupport301libactive supportdependenciesrb239in block in require20110614t124520 appweb1 from appbundlegemsruby191gemsactivesupport301libactive supportdependenciesrb227in load dependency20110614t124520 appweb1 from appbundlegemsruby191gemsactivesupport301libactive supportdependenciesrb239in require20110614t124520 appweb1 from appbundlegemsruby191gemsactivesupport301libactive supportdependenciesrb346in require or load20110614t124520 appweb1 from appbundlegemsruby191gemsactivesupport301libactive supportdependenciesrb300in depend on20110614t124520 appweb1 from appbundlegemsruby191gemsactivesupport301libactive supportdependenciesrb216in require dependency20110614t124520 appweb1 from appbundlegemsruby191gemsrailties301librailsenginerb138in block 2 levels in eager load20110614t124520 appweb1 from appbundlegemsruby191gemsrailties301librailsenginerb137in each20110614t124520 herokuweb1 process exited20110614t1245210 herokuweb1 state changed from starting to crashed20110614t1245210 herokurouter error h10 app crashed get deepbeach590herokucom dyno queue wait service bytes20110614t0545210700 herokunginx get http11 8644102112 796 http 50320110614t1245210 herokurouter error h10 app crashed get deepbeach590herokucomfaviconico dyno queue wait service bytesi think the simpler solution here might be to destroy the app and start again,['ruby-on-rails'] +162047,access a single image with alassetslibrary allow me to preface this by saying this is my first time using the alassetslibrary i need to access the most recent photo in the users saved photo gallery it seems that to do this i have to create an alassetslibrary instance and iterate over every item in the users gallery before selecting the last image this is always worstcase scenario is there a fasterbetter way to approach this problem,"['iphone', 'objective-c']" +162053,fontface rendering thick using standard fontsquirrel based fontface mark up the font is rendering on the thick side below is a screenshot demonstrating the font in a few different ways top is photoshops render second is chromes render of the same font obviously much thicker and third is chromes render of a similar font which is also rendering kind of chunkytried using fontweightlighter with no avail is there any trick to lighten it upthanks,['css'] +162073,pros and cons of listeners as weakreferences what are the pros and cons of keeping listeners as weakreferencesthe big pro of course is thatadding a listener as a weakreference means the listener doesnt need to bother removing itselfupdatefor those worried about the listener having the only reference to the object why cant there be 2 methods addlistener and addweakreflistener those who dont care about removal can use the latter,['java'] +162074,i do not understand why stringsize returns what it does long string eosit was the best of timesit was the worst of timeseosthat returns 53 why the whitespace counts even still how do we get 53how about this def test flexible quotes can handle multiple lines long string it was the best of timesit was the worst of times assert equal 54 long stringsize end def test here documents can also handle multiple lines long string eosit was the best of timesit was the worst of timeseos assert equal 53 long stringsize endis this the case because the case counts each n as one character and theres considered to be one before the first line one at the end and then at the end of the 2nd line whereas in the eos case theres just one before the 1st line and one after the 1st line in other words why is the former 54 and the latter 53,['ruby'] +162075,why does isdot fail on me php i am finalizing a code segment that lists the files in a directory i have no problems listing the files in a directory but for some reason i can get the isdot method to work to make sure the file is not a or the following below results in this errorfatal error call to undefined method splfileinfoisdot in before i switched over to using the recursive iterator i was using the directory iterator and it worked fine is there anything wrong with the code below it should workfiles new recursiveiteratoriteratornew recursivedirectoryiteratorpathtofolderif there is a subdirectory it makes sure the proper extension is passedforeachfiles as name file if fileisdot this is where it shuts me down realfile str replacepathtofolder file url getdownloadlinkfolderid realfile filearray url,['php'] +162087,repopulating checkboxes in codeigniter after unsuccessful form validation i have a problem repopulating a set of checkboxes after an unsuccessful form validation returns the user back to the same form dropdown menus and text inputs could be repopulated but not checkboxesheres a snippet of the code for the checkboxes td php echo form checkboxambience casual set checkboxambience casual casual br php echo form checkboxambience romantic set checkboxambience romantic romantic br php echo form checkboxambience outdoor set checkboxambience outdoor alfresco br php echo form checkboxambience trendy set checkboxambience hip trendy br php echo form checkboxambience vibrant set checkboxambience vibrant br php echo form checkboxambience up scale set checkboxambience upscale br tdthe code snippet for text input which successfully repopulated isphp echo form dropdownprice range options set valueprice range any ideas i am really confused why set checkbox does not work as advertised,['php'] +162096,small language in python i am writing what might not even be called a language in python i currently have several operators fac fac computes a factorial returns the value of a variable sets a variable the code is below how would i go about writing a way to define functions in this simple languageedit i updated the codeimport sys shlex readline os stringlist assign call add sub div pow mul mod fac duf readkill clr sto ret fib curs set get fact func read kill clear fib varsdef factnum if num 1 return 1 else return numfactnum1def simpop num2 num1 global list try num1 num2 floatnum1 floatnum2 except try num1 floatnum1 except try num2 floatnum2 except pass if op mul return num1num2 elif op div return num1num2 elif op sub return num1num2 elif op add return num1num2 elif op pow return num1num2 elif op assign listnum1 num2 return ok elif op call return listnum1 elif op fac return factnum1 elif op duf return s s sduf num1 num2 elif op mod return num1num2 elif op kill del listnum1 return ok elif op clr ossystemclear elif op sto listnum2 num1 return ok elif op ret return listnum1 elif op curs return list elif op read listnum1 evalraw inputs num1 return okdef evalexpr ops s s s s s s s s s s s s s s s smul add sub div pow assign call fac duf mod read kill clr sto ret curs stack expr ops shlexsplitstringlowerexpr opssplit for i in expr if i0 if i not in ops stackappendi elif i in ops stackappendsimpi stackpop stackpop else stackappendok return stack0def shell try x while x quit x raw inputstar try l evalx except keyerror l does not exist except l parse error if l none print ln except eoferror keyboardinterrupt printif lensysargv 1 x opensysargv1 r l xreadlines xclose for i in l if i0 i joinisplit x evali if x none print in xn else pass shellelse shell,['python'] +162107,is there a fiddle type thing for c and other languages i remember seeing once a jsfiddle type of thing online compiler where you can specify the language c c asm and the input and output and it compiles it and thisplays the output from the websiteanyone know what i am talking about,"['c++', 'c']" +162108,how to implement a short url like urls in twitter if there is a long url i want to generate a short url like those in twitter is there some way to implement in rubythank you in advance,['ruby'] +162116,which objectivec type is appropriate for handling money which objectivec type is appropriate for handling money i need something which is core data compatible,['objective-c'] +162117,php variable overriding when i try to override the class variable same way as override the class method in php likeclass datamapper protected name null public function printname echo this name class model extends datamapper protected name anatest new modeltestprintnameit is print anawhy php can do such a thing like that it break the law of object oriented paradigm,['php'] +162121,hide activity without finish i want my application to launch another activityapplication in this case the browser application but currently when the user presses the back button to exit the browser they return back to my activityhow can i make it so they do not come back to my activity after leaving the browser but if they relaunch my application later the activity stack of my application is as it was previously ie cannot finish because that will remove the current activity from the stack,['android'] +162124,how to detect if a browser is chrome using jquery i have a bit of an issue with a function running in chrome that works properly in safari both webkit browsersi need to customize a variable in a function for chrome but not for safarisadly i have been using this to detect if it is a webkit browserif browserwebkit but i need to detectif browserchrome is there any way to write a similar statement a working version of the one above,['jquery'] +162133,how to deserialize json response from jersey rest service to collection of java objects i write client that makes get request to rest service using jersey client apiresponse is a collection of objects and i need to deserialize it here is my code clientconfig clientconfig new defaultclientconfig clientconfiggetfeaturesputjsonconfigurationfeature pojo mapping booleantrue client client clientcreateclientconfig webresource r client resourcehttplocalhost8080restgadgetsand class that represents gadget model annotated with xmlrootelement for jaxb processing xmlrootelementpublic class gadget private string url private string title private string name public gadget public string geturl return urlpublic void seturlstring url thisurl urlpublic string gettitle return titlepublic void settitlestring title thistitle titlepublic string getname return name public void setnamestring name thisname name if response would just gadget copy not a collection the could looked as gadget result rgetgadgetclassbut json in response contains a list of gadgets and i need to read it to java collection something like listgadget result rgetlistgadgetclassdoes not compile can somebody help me here i do not want to use any additional libs i believe this can be done using jerseyjsonjar and jaxb but do not know how,['java'] +162143,how to get the references of all already opened child windows i want to get the references of all already opened child windows is there any way i am not using child windowopen just using windowopen and opening multiple child windows,['javascript'] +162144,regex to get the number from the end of a string i have a id like stringnumber variable like the one as follows example12i need some javascript regex to extract 12 from the stringexample will be constant for all id and just the number will be different,['javascript'] +162155,value was either too large or too small for an int32 possible duplicatewhat is the maximum value for a int32 mobileno converttoint32txmobilenotexterror i amm getting while inserting in to database,"['c#', 'asp.net']" +162167,html forms in your opinion how should they be done and why vs i have been a developer for a long time however forms have always been my least favourite part more specifically designing themi would really like to know how you do you forms and why i have had a few thiscussions with fellow developers over div vs p on form fields which one would you stick with and whyan example of what i am talking aboutform action methodpost p label forusernameusernamelabel input typetext nameusername idusername p p label forsubmitlabel input typesubmit namesubmit idsubmit valuelog in pformvsform action methodpost div label forusernameusernamelabel input typetext nameusername idusername div div label forsubmitlabel input typesubmit namesubmit idsubmit valuelog in divformwhen it comes to styling it seems you can do pretty much the same with both so is it just personal preference or is there logic behind using one over the otherthanks for your time updatei ended up following a nice article on html5 forms and have actually found it to allow much better styling of forms they are much more organised from a development perspective too for anyone interested it is located here,"['html', 'css']" +162175,use request value from list of values in jmeter i am sure i have already done this in the past but somehow i cannot figure out how so heres my problemi am trying to create a junit test plan in which a http request is modified each iteration by altering a specific parameter so for example in five iterations i want the following http requests to be madehttplocalhost8080testfoohtmlid1httplocalhost8080testfoohtmlid2httplocalhost8080testfoohtmlid3httplocalhost8080testfoohtmlid4i want to configure the identifier values globally for the test plan and use them within the http request samplerer like thispath testfoohtmlidcategoryidthe question now how do i configure the identifiers values globally i do not want to use stringfromfile and how do i reference them in the sampler,['java'] +162191,problem when calling template cuda kernel i have been trying to create template kernels but i am been having some trouble calling them in my program i have a matrixt template class and some methods defined inside itmatrixhtemplate typename t class matrix void summatrixt m1 matrixt m2 matrixt sum include matrixcumatrixcuinclude matrixkernelhtemplatetypename t void matrixtsumconst matrixt m matrixt sum sumkerneltdimgrid dimblockmatrixt m1 matrixt m2 matrixt sum matrixkernelhtemplatetypename t global void sumkernelconst matrixt m1 const matrixt m2 matrixt sum the problem is that when i call sumkernel from inside of sum the compiler gives me the following errorerror c2059 syntax error does somebody know whats going on the code compiled fine just before i included the sumkernel callthanks,['c++'] +162212,generate word combinations for example this is my text str buy new microsoft windowsi explode text and list with array array 0 buy 1 new 2 microsoft 3 windowsi want to generate words in array to something like thisbuy newbuy new windowsbuy microsoft buy microsoft windowsbuy windowsnew microsoftnew microsoft windowsnew windowsmicrosoft windowsi tried with foreach and rand but i could not generate like showed is there any chance to generate just like my request,['php'] +162219,importing a long list of constants to a python file in python is there an analogue of the c preprocessor statement such asdefine my constant 50also i have a large list of constants i would like to import to several classes is there an analogue of declaring the constants as a long sequence of statements like the above in a py file and importing it to another py fileeditthe file constantspy readsusrbinenv python encoding utf8constantspymy constant one 50my constant two 51and myexamplepy readsusrbinenv python encoding utf8myexamplepyimport sysimport osimport constantsclass myexample def init self selfsomevalueone constantsmy constant one 1 selfsomevaluetwo constantsmy constant two 1if name main x myclasseditfrom the compilernameerror global name my constant one is not definedfunction init in myexample at line 13 selfsomevalueone constantsmy constant one 1 copy output program exited with code 1 after 006 seconds,['python'] +162225,generating sound on the fly with javascripthtml5 is it possible to generate a constant sound stream with javascripthtml for example to generate a perpetual sine wave i would have a callback function that would be called whenever the output buffer is about to become emptyfunction getsampleattimestep return mathsintimestepthe idea is to use this to make an interactive synth i do not know in advance how long a key will be pressed so i cannot use a fixed length buffer,"['javascript', 'html']" +162231,gridview must be placed inside a form tag with runatserver even after the gridview is within a form tag form runatserver idf1 div runatserver idd grid view aspgridview runatserver idg aspgridview div asptextbox runatserver idt textmodemultiline rows20 columns50asptextboxformcode behindpublic partial class scripttest systemwebuipage protected void page loadobject sender eventargs e gdatasource new string a b c gdatabind textwriter tw new stringwriter htmltextwriter h new htmltextwritertw drendercontrolh ttext twtostring even the gridview is within a from tag with runatserver still i am getting this errorany clues please,"['c#', '.net', 'asp.net']" +162234,when to use statement over prepared statement when to use statement instead of prepared statement i suppose statement is used in queries with no parameter but why not use prepared statement which one is faster for queries with no params,['java'] +162247,how to go through the collection without using any loop construct a java interview question is there any way in java programming other then the loop constructs to iterate through a given collectionan array and work on the each element of the collection,['java'] +162248,eclipse androidmanifestxml format when i format the xml using ctrlshiftf the result is being like thatbut it would be nice if something can make xml like thatis there any way to format the formatting on eclipse,['android'] +162250,100 div width is not really 100 when i have a div with width 100 it is not really 100div iddivtesttesttesttesttestdivdiv width 100 backgroundcolor rednow when you resize the window so there is a horizontal scrollbar and you scroll to the right then the background is vanished how can i remain the background in this casehere you can see the problem in actionnow when you resize the window and scroll to the right you cannot see the background anymore how to fix this,"['css', 'html']" +162263,execute stored procedure from a function i know this has been asked to death and i know why sql server does not let you do itbut is there any workaround for this other than using extended stored proceduresand please do not tell me to convert my function into a procedureso what i am really asking is is there any way to run a stored procedure from within a functioneditpoint proven there is a way around it but it is so wrong i wouldnt do it i am gonna change it to a stored procedure and execute it elsewhere,['sql'] +162266,sql query to get aggregated result in comma seperators along with group by column in sql server i need to write a sql query on the table such that the result would have the group by column along with the aggregated column with comma separatorsmy table would be in the below format id value 1 a 1 b 2 c expected result should be in the below format id value 1 ab 2 c,['sql'] +162271,what is the most maturestable mysql nodejs module i am looking to do some work around mysql and nodejs and have found a few different modules out there but i cannot get a good bead on their stabilitymaturity i know each author puts very hard work into each one but for the work were doing i need to know i have got a solid mysql foundation the modules i have found that look pretty good aredbmysql this appears pretty activenodemysql this is a pretty pervasive module i have seen so far it appears to be in a maintenance phase and seems solidnodemysqlnative i like the async work being done here but i am not sure how well it works yetnodemysqllibmysqlclient i am not sure about this one but it appears to be active as welli do not have many needs that are too far out of the ordinary i need regular query support extras would be nice i just need a good foundation to start from any input as to the strengths and weaknesses of these modules would be great if there is another quality contender i have not found i am not at all against considering another option,['mysql'] +162275,how to add scroll bar to my dynamic table if i defined an empty table in my indexhtmlbodytable width800 border0 classmytable tr trtablebodythen i add row and columns to mytable by invoke the following javascript codevar mytable mytablevar myarrget from server server returns an arry of object myarrlength50forvar i0 imyarrlengthmytableappendtr idi tdmyarrinametd tdmyarriaddresstd trmyarr is an array of object get from server the length of this array could be more than 50 i got all of this working successfully my question is how can i add scroll barto this table so that if there are too many rows user could use scroll bar to check the table content,"['javascript', 'jquery', 'html', 'css']" +162293,whats the best way to initialise and use contants across python classes heres how i am declaring constants and using them across different python classes projectconstantspygood 1bad 2awful 3 projectquestionpyfrom constants import awful bad goodclass question def init self is the above a good way to store and use contant values i realise that after a while the constants file can get pretty big and i could explicitly be importing 10 of those constants in any given file,['python'] +162298,how do i drop multiple columns with a single alter table statement i would like to write a single sql command to drop multiple columns from a single table in one alter table statementfrom msdns alter table documentationdrop constraint constraint name column column name specifies that constraint name or column name is removed from the table drop column is not allowed if the compatibility level is 65 or earlier multiple columns and constraints can be listedit says that mutliple columns can be listed in the the statement but the syntax does not show an optional comma or anything that would even hint at the syntaxhow should i write my sql to drop multiple columns in one statement if possible,['sql'] +162311,how to get the autoincrement primary key value in mysql using hibernate i am using hibernate to access mysql and i have a table with an autoincrement primary key everytime i insert a row into the table i do not need to specify the primary key but after i insert a new row how can i get the relative primary key immediately using hibernateor i can just use jdbc to do this,['mysql'] +162322,phpunit tests real example i have created a mail wrapper class i know that there are lots of libraries to send emails but i want to learn tdd so i have created some tests and i have some code now i can set the email address on constructor and validate it if the email address is wrong an exception raise up the email address is the only one required field i do not have sets and gets because user will setup all email data on constructornow i am going to write the send tests i do not know how to start it how could i test if the values are there subject mail body headers if i do not want to have setters and getters how could i test if an email could be sentreal world tdd examples are hard to me i have tried to learn about it i have read lots of things but i cannot test real codethanks,['php'] +162355,persistence of jquery mobile page loading message i am using jquery mobile and have turned off the default ajax handling of forms and links and i am usingmobileshowpageloadingmsgto thisplay the page loading message when i submit a form that transitions me to a different page this works fine except for the fact that if i use the hardware back button on the device or the browsers back button to go back to the form the page loading message is still running i have tried callingmobilehidepageloadingmsgon document ready but this did not seem to fire when i used the back button to go back,['jquery'] +162371,c object oriented php extension following the tutorial i have tried to wrap a couple of c classes to a php extension unfortunately it fails i hope there is someone who could help me in order to try simplify the problem resolution i also simplified my classesthe objective is to have classes that allow me to execute some polygonal operations then i have created the point class and the polygon class as followspolygonhifndef polygon hdefine polygon h 1include vectorclass point double x double ypublic pointdouble x double y double xvoid double yvoidclass polygon stdvectorpoint ptspublic void addpoint pnt point getunsigned long idx unsigned long sizevoidendifpolygoncppinclude polygonhpointpointdouble x double y xx yy double pointxvoid return xdouble pointyvoid return yvoid polygonaddpoint pnt ptspush backpntpoint polygongetunsigned long idx return ptsatidxunsigned long polygonsizevoid return ptssizeconfigm4php arg enablegeometry whether to enable the geometry extension enablegeometry enable geometry extension supportif test php geometry no then php require cxx php substgeometry shared libadd php add librarystdc 1 geometry shared libadd php new extensiongeometry geometrycpp polygoncpp ext sharedfiphp geometryhifndef php geometry hdefine php geometry h 1define php geometry extname geometrydefine php geometry extver 01ifdef have config hinclude confighendifextern c include phphextern zend module entry geometry module entrydefine phpext geometry ptr geometry module entryphp methodpoint constructphp methodpoint xphp methodpoint yphp methodpolygon constructphp methodpolygon addphp methodpolygon getphp methodpolygon sizeendifgeometrycppinclude php geometryhinclude polygonhzend object handlers point object handlerszend object handlers polygon object handlersstruct point object zend object std point pointstruct polygon object zend object std polygon polygonzend class entry point cezend class entry polygon cevoid point free storagevoid object tsrmls dc point object obj point objectobject delete objpoint zend hash destroyobjstdproperties free hashtableobjstdproperties efreeobjvoid polygon free storagevoid object tsrmls dc polygon object obj polygon objectobject delete objpolygon zend hash destroyobjstdproperties free hashtableobjstdproperties efreeobjzend object value point create handlerzend class entry type tsrmls dc zval tmp zend object value retval point object obj point objectemallocsizeofpoint object memsetobj 0 sizeofpoint object objstdce type alloc hashtableobjstdproperties zend hash initobjstdproperties 0 null zval ptr dtor 0 zend hash copyobjstdproperties typedefault properties copy ctor func tzval add ref voidtmp sizeofzval retvalhandle zend objects store putobj null point free storage null tsrmls cc retvalhandlers point object handlers return retvalzend object value polygon create handlerzend class entry type tsrmls dc zval tmp zend object value retval polygon object obj polygon objectemallocsizeofpolygon object memsetobj 0 sizeofpolygon object objstdce type alloc hashtableobjstdproperties zend hash initobjstdproperties 0 null zval ptr dtor 0 zend hash copyobjstdproperties typedefault properties copy ctor func tzval add ref voidtmp sizeofzval retvalhandle zend objects store putobj null polygon free storage null tsrmls cc retvalhandlers polygon object handlers return retvalfunction entry point methods php mepoint construct null zend acc public zend acc ctor php mepoint x null zend acc public php mepoint y null zend acc public null null nullfunction entry polygon methods php mepolygon construct null zend acc public zend acc ctor php mepolygon add null zend acc public php mepolygon get null zend acc public php mepolygon size null zend acc public null null nullphp minit functiongeometry zend class entry ce init class entryce point point methods point ce zend register internal classce tsrmls cc point cecreate object point create handler memcpypoint object handlers zend get std object handlers sizeofzend object handlers point object handlersclone obj null init class entryce polygon polygon methods polygon ce zend register internal classce tsrmls cc polygon cecreate object polygon create handler memcpypolygon object handlers zend get std object handlers sizeofzend object handlers polygon object handlersclone obj null return successzend module entry geometry module entry if zend module api no 20010901 standard module headerendif php geometry extname null functions php minitgeometry minit null mshutdown null rinit null rshutdown null minfo if zend module api no 20010901 php geometry extverendif standard module propertiesifdef compile dl geometryextern c zend get modulegeometryendifphp methodpoint construct double x 0 double y 0 zval object getthis if zend parse parameterszend num args tsrmls cc dd x y failure return null point object obj point object zend object store get objectobject tsrmls cc objpoint new pointx yphp methodpoint x point object obj point object zend object store get objectgetthis tsrmls cc point point objpoint ifpoint null return doublepointxphp methodpoint y point object obj point object zend object store get objectgetthis tsrmls cc point point objpoint ifpoint null return doublepointyphp methodpolygon construct zval object getthis polygon object obj polygon objectzend object store get objectobject tsrmls cc objpolygon new polygonphp methodpolygon add polygon object obj polygon objectzend object store get objectgetthis tsrmls cc polygon polygon objpolygon ifpolygon null zval oth if zend parse parameterszend num args tsrmls cc o oth point ce failure return null point object ooth point objectzend object store get objectoth tsrmls cc polygonaddoothpoint php methodpolygon get polygon object obj polygon objectzend object store get objectgetthis tsrmls cc polygon polygon objpolygon ifpolygon null long index if zend parse parameterszend num args tsrmls cc l index failure return null if object init exreturn value point ce success else struct point object vobj struct point object zend object store get objectreturn value tsrmls cc assert vobj null vobjpoint polygongetindex php methodpolygon size polygon object obj polygon objectzend object store get objectgetthis tsrmls cc polygon polygon objpolygon ifpolygon null return longpolygonsizethen after compiling i try the following php codephpecho prept new pointvar dumpptpl new polygonpladdptpladdnew point10 0pladdnew point10 10fori 0 i plsize i var dumpplgetialways crashes when executing the polygonget method if i comment it nothing wrong happens,"['php', 'c++']" +162376,getting started with nhibernate 32 loquacious api i am starting a new project and i want to use nhibernate 32 i know that it can now do something similar to fluentnhibernate and i want to give it a trybut i am having a hard time finding documentation on the loquacious api i have seen blog posts on how to configure the isessionfactory but i am getting lost after this i know that the 32 api is moving fast and that article about 3 to 4 months old are already out of date but i am looking for the most recent informationwhere can i find the resources concerninghow to setup nhibernate 32 without using xml without using fluentnhibernate and without using conformhow to register the mappingshow to create conventionsplease remember that this is concerning nhibernate 32 and probably above if any of the concepts like mappings and conventions no longer apply please can you point me into the right directioni have some experience with nhibernate and fluentnhibernate as i used them for a small project but it was not very complicated,['c#'] +162389,how to properly authenticate mvcminiprofiler with aspnetsqlmembershipprovider i tried to check if the user is in role at application beginrequest and application authenticaterequest with this code and it will not work at beginrequest the code is never hit and authenticate it is hit with some of the request and the profiler does not show upchecking only for requestislocal works fineifrequestisauthenticated ifuserisinroleadmin miniprofilerstart any idea or why it is not working or better way to do itupdate i accepted the awnser but undid it as i did not quite get it do worki did the following but the profiler is not showing up at firstafter a few tries it started showing up even when i tried to acess the site with incognito mode so no cookieprotected void application postauthorizerequestobject sender eventargs e if userisinroleadmin httpcookie cookie httpcontextcurrentrequestcookiesgetroleprofiler if cookie null cookie new httpcookieroleprofiler cookievalue yes cookieexpires datetimenowadays1d responsecookiesaddcookie and i am checking withprotected void application beginrequestobject sender eventargs e httpcookie cookie httpcontextcurrentrequestcookiesgetroleprofiler if cookie null cookievalue yes mvcminiprofilerminiprofilerstart and ending at the end of the requestprotected void application endrequest mvcminiprofilerminiprofilerstopupdate2 closing question ignore this i was being owned by outputcache,['asp.net'] +162391,ef 41 dbcontext generattor put entities in different project as a part of our application architecture we like to define clear lines between our functional layers a typical application solution therefore will containentitymodeltaskpresenterfrontendthese end up being completely thistinct assembliesthe entitymodel delineation is done to keep database access functionality in a separate layer from our pocos so that only task ever need know about model while everyone up to presenter knows about entitythis works well when using codefirst or fluentapi but due to the lack of support for sprocs in those paradigms it turns out that under ef 41 i must use edmx models so i am generating pocos using a dbcontext generator but the resulting classes end up under model and while i can force their namespace into entity instead they still live in the model assembly which means now presenter must reference model to get to classes that should be in entityis there a way to force or trick ef to dump its generated output into a different project,['c#'] +162422,why should not i use the menu icons provided by the os i would like to use some of the default menu icons provided by the android os the xml would be something like thisitem androidididmenu refresh androidiconandroiddrawableic menu refresh androidtitlestringmenu refresh but the documentation says this is unadvised warning because these resources can change between platform versions you should not reference these icons using the android platform resource ids ie menu icons under androidrdrawablei thought the whole point of using the default icons is because the design does change from os to os by using the default icons your app will look and feel appropriate for the os it is running on so what is so bad about using the default icons it seems like not using the default icons would hurt the appearance of the app,['android'] +162423,simulate iphone environment in firebug is there a way i can get firebug or firefox to send an iphone user agent string to the browser so i can debug the iphone layout of my site more easilythankskevin,['iphone'] +162433,jquery mobile form validation which plugin to choose which framework would you choose to validate forms in a jquery mobile app in addition my webapp runs in the phonegap native wrapper on iphone and androidthere are numerous jquery form validation frameworks out there but from your experience what works well with the mobile version of jquerycriteria that would be interesting in the mobile contexttouchenabled notification messages in case of wrong validation the message is ideally optimized for small screen estatemessage in place with the wrong form fieldoffline functionality since the phonegap app runs occasionally without network access,"['javascript', 'jquery']" +162443,using preg match to find all words in a list with help from so i was able to pull a keyword out of an email subject line to use as a category now i have decided to allow multiple categories per image but cannot seem to word my question properly to get a good response from google preg match stops at the first word in the list i am sure this has something to do with being eager or simply replacing the pipe symbol with something else but i just cannot see itbamsterdampariszurichmunichfrankfurtbulleb the whole string i am currently using ispreg matchbamsterdampariszurichmunichfrankfurtbullebi subject matchesall i need to do is pull all of these words out if they are present as opposed to stopping at amsterdam or whatever word comes first in the subject it is searching after that it is just a matter of dealing with the matches array rightthanksmark,['php'] +162450,fabric put command gives fatal error no such file exception i am using fabric 101 and in my fabfile i am using the put command the line isputfiletargz filetargzthe server is in the envhosts list filetargz is in the same directory as the fabfile and i am running the code from this directorywhen i run the code it gets up to the point where it is running this put command just before failing the output is put filetargz filetargzfatal error put encountered an exception while uploading filetargzunderlying exception message no such fileanyone know where this is coming from the file definitely exists on my local machine and i have also tried the second put argument as just serverpathto and i have tried using the absolute path of the file for the first put argument all to no avail,['python'] +162460,what data structures are commonly used for lru caches and quickly locating objects i intended to implement a hashtable to locate objects quickly which is important for my applicationhowever i do not like the idea of scanning and potentially having to lock the entire table in order to locate which object was last accessed tables could be quite largewhat data structures are commonly used to overcome thateg i thought i could throw objects into a fifo as well as the cache in order to know how old something is but that is not going to support an lru algorithmany ideas how does squid do it,['c++'] +162473,adding blank spaces to layout i am trying to make empty lines within android this is what i have been doingandroidlayout widthfill parent androidlayout heightwrap content androidtextnni want to know if there is a better way thanks,['android'] +162499,matplotlib label each bin i am currently using matplotlib to create a histogramimport matplotlibmatplotlibuseaggimport matplotlibpyplot as pyplotfig pyplotfigureax figadd subplot1n bins patches axhistmeasurements bins50 rangegraph minimum graph maximum histtypebaraxset xticklabelsn rotationverticalfor patch in patches patchset facecolorrpyplottitlespam and hampyplotxlabeltime in secondspyplotylabelbits of hampyplotsavefigoutput filenamei would like to make the xaxis labels a bit more meaningfulfirstly the xaxis ticks here seem to be limited to five ticks no matter what i do i cannot seem to change this even if i add more xticklabels it only uses the first five i am not sure how matplotlib calculates this but i assume it is autocalculated from the rangedatais there some way i can increase the resolution of xtick labels even to the point of one for each barbinideally i would also like the seconds to be reformatted in microsecondsmilliseconds but that is a question for another daysecondly i would like each individual bar labeled with the actual number in that bin as well as the percentage of the total of all binsthe final output might look something like thisis something like that possible with matplotlibcheersvictor,['python'] +162502,how can i write a single for loop running from a to z and a to z in c i want to combine both the for loops into single for loop how can i do thati want to loop through a to z and a to z like sochar chfor ch a ch z ch for ch a ch z ch but using a single loop,['c'] +162510,using ion auth as a separate module in the hmvc structure i am interested in using ion auth for a project of mine which is running on the hmvc pattern the application is written in codeigniterthe problem i face is once the ion auth is placed in the appmodulesauth folder when i try to access the module i get the below errorhttp error 500 internal server error an unexpected condition was encountered while the server was attempting to fulfill the requestplease help me out here i am sure that i am having some sort of a configurationpath problem but just cannot figure out where i have simply downloaded the ion auth files from github and placed the extracted files as it is in the module folder i removed all the lines where it loads the libraries such as database session since i have used the config to auto load them but i left the loading of the ion auth libraryin the module folder modulesauth i have a similar application structure with the module specific config libraries etc folderslet me know where i must have done wrong i will continue to search and fix this problem and post if i have any luck,['php'] +162537,is there a select into outfile equivalent in sql server management studio mysql had a nifty command select into outfile that could write the result set into a file csv format or some other optional format i am currently using sql server management studio to query an mssql backend server i have multiple sql queries and would like to write the output result set into a file is there any way i could store the results from a query directly into a file,['sql'] +162554,javascript dom childnodeslength also returning number of text nodes in javascript dom childnodeslength returns the number of both element and text nodes is there any way to count only the number of elementonly child nodesfor example childnodeslength of divposts will return 6 when i expected 2div idposts some comment another comment divan element nodediv another comment spanan element nodespan a text nodediv,"['javascript', 'html']" +162565,copy to clipboard without flash i found many solutions for copying to the clipboard but they all either with flash or for websites sidei am looking for method copy to clipboard automatically without flash and for user side it is for userscripts and of course crossbrowser,"['javascript', 'jquery']" +162573,is it possible to attach uitapgesturerecognizer to uilabel subclass i am trying to attach gesture recognizer to my own class which is subclass of uilabel but it does not work can you help me to understand whats wrong in the code interface card uilabel void addbacksidewordendimport cardhimplementation card idinitwithframecgrectframe if self super initwithframeframe uitapgesturerecognizer taprecognizer uitapgesturerecognizer alloc initwithtargetself actionselectoraddbacksideword taprecognizer setnumberoftouchesrequired2 taprecognizer setdelegateself self addgesturerecognizertaprecognizer return self void addbacksideword do somethingend,"['iphone', 'ios']" +162578,iphone app does not run on old device 3g 3gs possible duplicateis it possible to target older ios versions when using xcode 42 and ios 5 sdk i have developed an app which works on iphone 4 ios 43 5 which used during developing now i have tried to test on 3gs ios 433 and 3gios 42 but app does not load into these devices i can see following messages on consol when try to deploy to devicesat jan 1 172738 unknown lockdownd16 error 2ff680 handle connection could not receive usb message 6 from xcode killing connection sat jan 1 172738 unknown comapplemobilelockdown16 notice could not receive size of messagei have tested on xcode 402 as well as 42 beta restarted devices and mac but still same can anybody know about this issuethanks,['iphone'] +162580,blackmagic sdk in c i am attempting to capture 720p from one a blackmagic intensity pro cards using the newest sdk june 2011 on windows7 64x and with c vs 2010 express i have successfully compiled and run a program that captures frames at yuv however capture stops after 56 frames the callback function stops being called i am wondering if i am missing something simple here especially given that i am almost there i get frames with the correct content at the correct size etc but only for a brief timealso some other information that may be relevantif i unplug the camera capture does not stopi have also tried this at 1080i and pal and the same happenssame thing happens even if the videoinputframearrived function is empty ie with just a frame counter in ithere is the codepublic partial class mainwindow window idecklinkinputcallback private idecklinkiterator decklinkiterator private listidecklink decklinklist new listidecklink private idecklink currentdevicenull private idecklinkinput decklinkinput null private int width1280 private int height720 private writeablebitmap writeablebitmap null intptr temprgbdata byte temprgbdatabytes thispatchertimer timer new thispatchertimer public mainwindow initializecomponent random random new random void timer tickobject sender eventargs e randomnextbytes temprgbdatabytes writeablebitmapwritepixelsnew int32rect0 0 width height temprgbdata height width 3 width 3 private void window loadedobject sender routedeventargs e writeablebitmap new writeablebitmap width height 72 27 pixelformatsbgr24 null captureimagesource writeablebitmap temprgbdata marshalallochglobal3 width height marshalsizeoftypeofbyte temprgbdatabytes new byte3 width height decklinkiterator new cdecklinkiterator idecklink dlnull whiletrue decklinkiteratornextout dl ifdlnull break else decklinklistadl foreach idecklink device in decklinklist string name devicegetmodelnameout name consolewriteline name currentdevice decklinklist1 decklinkinput idecklinkinput currentdevice uint framecount0 decklinkinputgetavailablevideoframecountout framecount consolewritelineavailable frame count framecount idecklinkthisplaymodeiterator thisplayiteratornull decklinkinputgetthisplaymodeiteratorout thisplayiterator bmdthisplaymodesupport thisplaymodesupport idecklinkthisplaymode thisplaymodenull bmdthisplaymode setthisplaymode bmdthisplaymodebmdmodehd720p50 bmdpixelformat setpixelformat bmdpixelformatbmdformat8bityuv bmdvideoinputflags setinputflag bmdvideoinputflagsbmdvideoinputflagdefault decklinkinputdoessupportvideomodesetthisplaymode setpixelformat setinputflag out thisplaymodesupport out thisplaymode try decklinkinputthisableaudioinput decklinkinputenablevideoinputsetthisplaymode setpixelformat setinputflag catch exception em consolewritelinedeck link init failed emmessage decklinkinputsetcallbackthis consolewritelinedone timerinterval timespanfromseconds1f 30f timertick new eventhandler timer tick timerstart int framecount 0 public void videoinputframearrivedidecklinkvideoinputframe video idecklinkaudioinputpacket audio get image data intptr pdata videogetbytesout pdata keeping it simple so just counting frames this gets called 56 times then stops consolewritelinevideo frame arrived framecount framecount public void videoinputformatchanged bmdvideoinputformatchangedevents events idecklinkthisplaymode thisplaymode bmddetectedvideoinputformatflags flags consolewritelinevideo format changed start stream private void button1 clickobject sender routedeventargs e decklinkinputstartstreams stop stream private void button2 clickobject sender routedeventargs e decklinkinputstopstreams private void button4 clickobject sender routedeventargs e decklinkinputpausestreams private void button3 clickobject sender routedeventargs e decklinkinputflushstreams,['c#'] +162588,some services stop automatically if they are not in use by other services error some services stop automatically if they are not in use by other services while trying to start a windows service i have a service that does not use the windows service config file and uses static properties it works finenow i make use of appconfig file and rebuild my setup project the service project now i install the service and then try to start the service i get the following errorsome services stop automatically if they are not in use by other servicesservice logs on as local systemany input is welcome please thanks,['c#'] +162591,how should i open and close my database properly i have an app which stores some data in a sqlite dbalso i am doing a lot of query an requery in my appi have about 15 activities in itand almoust all use the db to query for databut what i am doing is opening my db in every activity and close it in ondestroy of every activitythe problem is that ondestroy may never get called and sometimes my app stays on for a long time and i switch from an activity to another opening for to many times my dband sometimes i get errors likedatabase too many times opened and never closedi would try to close my db exactly after i get my data from it and close itmoving to my next activity and reopening and so onbut the problem is that in some activities i come back from other activitiesclosing my db and coming back to that activity would produce a big force closewhat i wanna do is open my db at the beginning of my app and close it at the end of it but i am facing 2 problems1should i make my sqliteopenhelper class a singletonget an instance of itopen it in my first activity and then in my following activities just get an instance of my db which is already opened2where is the end of my apphow should i know where is the end of my app and where to close my dbeditpublic class dbadapter extends sqliteopenhelper public dbadaptercontext context supercontext database name null 1 thismycontext context public void opendatabase throws sqlexception string mypath database path database name db sqlitedatabaseopendatabasemypath null sqlitedatabaseopen readwrite that is a piece of code from my class that manages my dbto make this singleton i should use a constructor likw thisprivate dbadapternothing in herebut this is undefined for sqliteopenhelperedit finalthis is how i did it according with zirael advicepackage comserver 1import androidappapplicationpublic class myapplication extends applicationprivate static dbadapter dbpublic void oncreate dbnew dbadaptergetapplicationcontext dbcreatedatabase dbopendatabasepublic static dbadapter getdatabaseadapter return dbin every activity i where i need db connection i do thismyapplication myapplication myapplication thisgetapplicationdbadapter db myapplicationgetdatabaseadapterand finally my manifest looks likeapplication androidicondrawableicon androidlabelstringapp name androidnamemyapplication androiddebuggabletrue,['android'] +162594,how to compare generic nodes in a linked list using comparable i am implementing a sorted list using linked lists my node class looks like thispublic class nodee e elem nodee next previousin the sorted list class i have the add method where i need to compare generic objects based on their implementation of compareto methods but i get this syntax errorthe method comparetoe is undefined for type e i have tried implemnting the compareto method in node but then i cannot call any of objects methods because e is generic type here is the nonfinished body of adde elem methodpublic void adde elem nodee temp new nodee tempelem elem if isempty tempnext head headprevious temp head temp counter else fornodee cur head curnext null cur curnext iftempelemcompartocurelem do the sort else curprevious temp else insert at the end here is one of the object implemnting compareto methodpublic class patient implements comparablepatient public int comparetopatient that return thisgetpriority thatgetpriority 1 0,['java'] +162598,killing a process using java i would like to know how to kill a process that has started up i am aware of the process api but i am not sure if i can use that to kill an already running process such as firefoxexe etc if the process api can be used can you please point me into the correct direction if not what are the other available options thanks,['java'] +162602,therubyracer gem on windows i have been peacefully developing on windows without adding any gems for a few weeks now and today i decided to to a bundle update but i cannot get through this gem called therubyracer i have the devkit installed and it is working according to the documentations verification procedure my question is is there a way to install this gem at all on windows and is this gem going to be required by rails 31 and this is why now that i do a bundle update it is being slipped into the rails 308 as a gesture of early kick start for future 31 migrationedit including gemfile and gemfilelock gemfile source source rubygemsgem railsgem rake 087gem youtube itgem pandagem niftygenerators gem mongoid 200rc7gem mongoidgem mongoideagerloading gem mongoid searchgem bson ext 115gem devisegem cancangem hirb gem herokugem restclientgem less needs the more plugin gem hash extensiongem awss3 require awss3 s3rbgem jqueryrails 027 rails g jqueryinstall gem mongrel 120pre2gem delayed jobgem delayed job mongoidgem kaminari gemfilelockgem remote specs abstract 100 actionmailer 308 actionpack 308 mail 2219 actionpack 308 activemodel 308 activesupport 308 builder 212 erubis 266 i18n 050 rack 121 rackmount 0614 racktest 057 tzinfo 0323 activemodel 308 activesupport 308 builder 212 i18n 050 activerecord 308 activemodel 308 activesupport 308 arel 2010 tzinfo 0323 activeresource 308 activemodel 308 activesupport 308 activesupport 308 arel 2010 awss3 062 builder mimetypes xmlsimple bcryptruby 214x86mingw32 bson 131 bson ext 131 builder 212 cancan 165 daemons 113 delayed job 214 activesupport 30 daemons delayed job mongoid 102 delayed job 211 mongoid 200rc devise 134 bcryptruby 212 orm adapter 003 warden 103 erubis 266 abstract 100 hirb 045 i18n 050 jqueryrails 1010 railties 30 thor 014 json 152 kaminari 0124 rails 300 less 1221 mutter 042 treetop 142 mail 2219 activesupport 236 i18n 040 mimetypes 116 treetop 148 mimetypes 116 mongo 131 bson 131 mongoid 202 activemodel 30 mongo 13 tzinfo 0322 mongoideagerloading 031 mutter 053 niftygenerators 046 oauth 044 orm adapter 005 panda 142 json restclient rubyhmac 032 polyglot 031 rack 123 rackmount 0614 rack 100 racktest 057 rack 10 rails 308 actionmailer 308 actionpack 308 activerecord 308 activeresource 308 activesupport 308 bundler 10 railties 308 railties 308 actionpack 308 activesupport 308 rake 087 thor 0144 rake 087 restclient 161 mimetypes 116 rubyhmac 040 thor 0146 treetop 149 polyglot 031 tzinfo 0328 warden 104 rack 10 xmlsimple 1016 youtube it 142 builder oauth 044platforms x86mingw32dependencies awss3 bson ext 115 cancan delayed job delayed job mongoid devise hirb jqueryrails 027 kaminari less mongoid mongoideagerloading niftygenerators panda rails rake 087 restclient youtube it,['ruby-on-rails'] +162635,android multiline notifications notifications with longer text i need to create a notification with a longer text is that possible by default it is not but you can use a custom layout which is what i did now i can thisplay multiple lines but as you can see the text is still broken not thisplayed completely can someone please tell me what i am doing wrong if there is a fixed limit for the size of notifications if you look at the screenshot you will notice that there is still a lot of space left thanks for any hintbtw heres the xml used for the custom layout based on linearlayout xmlnsandroid androidorientationhorizontal androidlayout widthfill parent androidlayout heightfill parent androidpadding3dp imageview androidididimage androidlayout widthwrap content androidlayout heightfill parent androidlayout marginright10dp textview androidididtext androidlayout widthwrap content androidlayout heightfill parent androidtextcolor0 linearlayout,['android'] +162648,how do i run some python code in another process i want to start from python some other python code preferably a function but in another process it is mandatory to run this in another process because i want to run some concurrency tests like opening a file that was opened exclusively by the parent process this has to failrequirementsmultiplatform linux osx windowscompatible with python 263x,['python'] +162649,scrollbar on browser and div margin 0 auto jumping i am using divwrapper margin 0 auto to center the div there is scroll bar on this page however when it transition to second page where there is no scroll bar it appears as jumpy because there is no scroll bar i guessbodydiv idwrapdiv idwrapperwrapper width 970px margin 0 auto what would be the best solution for this not to make it jumpy,"['html', 'css']" +162658,pushing array value to first index var config windows applemangilemoni have a condition and based on that i want to push the banana value in my array ifcondition passed configwindowsunshiftbanana windows bananaapplemangilemon configwindowsreverse the way the array elements are now reversed and first banana is accessed else configwindowsreverse it does not do it when i use the configwindows in my other function there is no banana value at allfor eachvar item in configwindowsreverse tiapiinfoitem this does not print banana,['javascript'] +162661,why do i get different results when comparing strings after using different concatenation in java i was working on the basic java program and i found verry funny thing which i am sharing with you foo gives output ss1 false and bar gives ss1 truei want to know why this happenspublic class stringtest public static void mainstring args foo bar public static void foo string s str4 string s1 str slength systemoutprintlnss1 s1s public static void bar string s str4 string s1 str 4 systemoutprintlnss1 s1s,['java'] +162665,phone number validation android how do i check if a phone number is valid or not it is up to length 13 including character in fronthow do i do thati tried thisstring regexstr 09string numberentered numbergettexttostring ifentered numbergettexttostringlength10 numberlength13 numbermatchesregexstrfalse toastmaketextmydialogthisplease enter n valid phone numbertoastlength shortshow am checked0and i also tried thispublic boolean isvalidphonenumberstring number for char c numbertochararray if valid charscontainsc return false all characters were valid return trueboth are not workinginput type sign to be accepted and from 09 numbers and length bw 1013 and should not accept other characters,['android'] +162715,save image created via pil to django model i have successfully created and rotated an image that was uploaded via email to a directory on my server using the following code image contentfileb64decodepartget payload im imageopenimage tempfile imrotate90 tempfilesavesrvwmysitecompublic htmlmediaimagesrotatejpg jpeg img photouseruser imgimgsaverotatejpg tempfile imgsavethe rotated image exists in the directory however when i try to add that image to my model it is not saving what am i missing any help would be greatly appreciated,['python'] +162721,proper linq where clauses i write a fair amount of linq in my day to day life but mostly simple statements i have noticed that when using where clauses there are many ways to write them and each have the same results as far as i can tell for examplefrom x in collection where xage 10 where xname fido where xfat true select xappears to be equivalent to this at least as far as the results are concernedfrom x in collection where xage 10 xname fido xfat true select xso is there really a difference other than syntax if so what is the preferred style and why,['c#'] +162737,trying to implement understand the decorator pattern in php i am trying to understand the decorator pattern and i have read other related questions on so then i decided to try it with a trivial example i am a php noviceinterface ititle public function gettitleclass title implements ititle protected text public function construct this textour page public function gettitle return this text abstract class titledecorator implements ititle protected title public function constructititle title this titletitle class beforetitle extends titledecorator public function gettitle return welcome to this titlegettitle class aftertitle extends titledecorator public function gettitle return this titlegettitle dear user is this a kind of right implementation of the decorator patternif no what would be the right wayif yes could this be improved and howor maybe this would be more suitable for another patternany helpideas would be appreciated thanks in advance,['php'] +162764,aspnet updatepanel and javascript dopostback i am calling a partial postback from javascript like sofunction getpolicyclick dopostbackupdatepanel1 postcallit does 12 of what i need it to it does call a partial postback just for my updatepanelnow the tricky part i am trying somehow to reference the second argument of dopostback in my code behind this does not workprivate sub updatepanel1 loadbyval sender as object byval e as systemeventargs handles updatepanel1load dim myarg as string request eventargumentend subi just get an empty stringof course what i am trying to do might be completely wrong as with everything else i try to do with asp i am suspecting that my codebehind is grabbing the event argument from the page instead of the panel but i really do not know any ideas,"['javascript', 'asp.net']" +162796,where does the context live in an oop javascript pong game to practice my oop knowledge i am making a pong game in javascript i know i know it is like playing stairway to heaven in a guitar shop i have had several functioning versions of the game by implementing several different techniques including prototypal based oop and functional style however i am not doing this to get a functional game i am doing it to learni am using the html5 canvas and plain ol javascript no frameworks ok a little bit of jquery for the keyboard capture i had my pong object which represented my game pong had an attribute ctx that contained a reference to the canvasgetcontext2d context it also had a player1 player2 and ball attribute for holding you know what when the ball and two players were instantiated the context was passed in to their constructor so that they too could hold a reference to the context for use in their drawctx methods pong had a draw method that would get called using a setintervalthisdraw 10 pongs draw method would call the draw method of the two players and the ball it does not sit well with me that the two players and ball have the context as an attribute they do not own the context and therefore it should not be an attribute however the nature of using javascript and the canvas seems to be that this is the best way who or what should own the context in this situation ideally i wouldnt want the players and ball objects to have a draw object at all i feel like they should have attributes that describe their geometry and position and a dedicated object should be tasked with rendering them to the screen this way if in the future i decided i wanted to use divs instead of the canvas i could just change the rendering object and everything else would be obliviousi know i am making a javascript pong game more complicated than it needs to be but i want to practice the techniques and really grok the concept of oop but every time i think i have cracked it a completely new problem created by my solution presents itselfedit if it would help if you had a nosy at my code here is an almost fully working versionlibraryjs pongjs try it out,['javascript'] +162803,new chrome incognito window via htmljs possible duplicatehow to open new incognito window with javascript google chrome is it possible to open a new incognito window to a url of my choosing via either some attributes on a hyperlink or some javascript if it is how do i do it,"['javascript', 'html']" +162830,what h264 format loads on android and ios theoretically both ios and android will play h264 files but i cannot figure out a setting to encode them so they actually work cross platform does anybody know how to encode for both android and ios using one file ps i know all about html5 video and the fallback sources i just do not want to encode and host a new video for every device that comes down the pike,"['iphone', 'android']" +162832,starting gridbaglayout from top left corner in java swing i am new to java swing and i have been struggling to start the gridbaglayout from top left corner so that cgridx0 cgridy0 will put my object on the top left corneri would appreciate if you could help me by telling what i need to do after this point jpanel panel new jpanelnew gridbaglayout frameaddpanel gridbagconstraints c new gridbagconstraintsi know that i have to use northwest or first line start constants but i do not know how i tried to do it this way but it did not realize the constants framegetcontentpaneaddpanel borderlayoutnorthwestthanks for your help,['java'] +162833,dynamic text fitting into div div rownumber0 messageid141 classpost styleposition relative top 0px div classpost bodytestboxdiv div classpost info styletop 0px ul li classvote idvotelia hrefvote upali li classflag idflaglia hrefflagali ul divdivso these divs are generated on the fly and placed into a container div on the front end these are generated on the backend and are returned as html through jsonthe div classpost body is what holds the user message current the one that says testbox now the issue i am having is when a user writes a message that extends beyond the width of the div it just keeps going it does not bump onto the second lineheres the two things i want to achievei want to make sure when the text does not fit horizontally it goes onto a second line within the same divi want to shrink the text if it needs to go on two lines that way the height of the post body div can stay consistent every timehow can i do thisthanks,"['jquery', 'html', 'css']" +162837,how are basic data types strings and integers implemented in python and perl i have been wondering lately how various operations i perform on basic types like strings and integers work in terms of performance and i figure i could get a much better idea of this if i knew how those basic types were implemented ie i have heard strings and integers are immutable in python does that mean any operation that modifies one character in a string is on because a completely new string has to be created how about adding numbersi am curious about this in both python and perl and felt silly asking basically the same question twice so i am just wrapping it into oneif you can include some example operation costs with your answer that would make it even more helpful thanksedit fixed a stupid python error edit,['python'] +162844,camelcasing htmlreport vs htmlreport often you would use well or somewhat established abbreviations in class or method names but how do you camelcase or camelback themhtmlreport vs htmlreportcustomerdao vs customerdaoxmlrpc vs xmlrpcwhich side is correct or which would you prefer,"['c#', 'java']" +162846,setting recovery options on windows services i have recently written a small class to help me change recovery options on a windows service most of code i found online somewhere the code creates a failureaction for the first second and subsequent failures each failure object contains a type none restart reboot runcommand and a delay int in milliseconds these objects are packaged inside a struct and passed into changeserviceconfig2 winapi pinvoke however when i actually rightclick on a service on the console and go to the recovery tab you can only set the delay restart server after field once for all failures first second and subsequent when i set this programmatically it takes the delay from the first failureaction and ignores all others does anyone know why this is the case why do we have to pass in a delay value for all failureaction objects when only the first one gets used am i misunderstanding somethingalso setting dwresetperiodreset fail count after does not seem to have any effectcodepublic class serviceconfigurator private const int service all access 0xf01ff private const int sc manager all access 0xf003f private const int service config description 0x1 private const int service config failure actions 0x2 private const int service no change 1 private const int error access denied 5 structlayoutlayoutkindsequential charset charsetunicode private struct service failure actions public int dwresetperiod marshalasunmanagedtypelpwstr public string lprebootmsg marshalasunmanagedtypelpwstr public string lpcommand public int cactions public intptr lpsaactions dllimportadvapi32dll entrypoint changeserviceconfig2 private static extern bool changeservicefailureactionsintptr hservice int dwinfolevel marshalasunmanagedtypestruct ref service failure actions lpinfo dllimportadvapi32dll entrypoint changeserviceconfig2 private static extern bool changeservicedescriptionintptr hservice int dwinfolevel marshalasunmanagedtypestruct ref service description lpinfo dllimportkernel32dll private static extern int getlasterror private intptr servicehandle public intptr servicehandle get return servicehandle public serviceconfiguratorservicecontroller svccontroller this servicehandle svccontrollerservicehandledangerousgethandle public void setrecoveryoptionsfailureaction pfirstfailure failureaction psecondfailure failureaction psubsequentfailures int pdaystoresetfailurecount 0 int num actions 3 int arractions new intnum actions 2 int index 0 arractionsindex intpfirstfailuretype arractionsindex pfirstfailuredelay arractionsindex intpsecondfailuretype arractionsindex psecondfailuredelay arractionsindex intpsubsequentfailurestype arractionsindex psubsequentfailuresdelay intptr tmpbuff marshalallochglobalnum actions 8 try marshalcopyarractions 0 tmpbuff num actions 2 service failure actions sfa new service failure actions sfacactions 3 sfadwresetperiod pdaystoresetfailurecount sfalpcommand null sfalprebootmsg null sfalpsaactions new intptrtmpbufftoint32 bool success changeservicefailureactions servicehandle service config failure actions ref sfa ifsuccess ifgetlasterror error access denied throw new exceptionaccess denied while setting failure actions else throw new exceptionunknown error while setting failure actions finally marshalfreehglobaltmpbuff tmpbuff intptrzero trevor,['c#'] +162883,missing run as junit test i created a junit 4 test in eclipse by rightclicking on a java class and selecting new junit test case when i rightclick the test class i get run on server but not run as junit test i am using eclipse 361,['java'] +162893,objectivec if object vs if object nil assuming object is a kind of nsobject the following if statements are equivalent but which style should i useif object orif object nil,['objective-c'] +162908,average 2 hex colors together in javascript alright thought i would throw this one out there for the crowd to think overgiven a function written in javascript that expects two strings formated like a hex color ex ff0return a hex color that is the average of both of the colors passedfunction averagecolorsfirstcolorsecondcolor return avgcoloreditaverage would be defined as if the color passed was yellow and the second was light purple the returned color would be a medium orange,['javascript'] +162918,winforms binding question i am relatively new to binding in win forms in order to learn the subject i setup the following test application a basic winform with a listbox and a buttonpublic partial class form1 form public liststring stringlist new liststring public form1 initializecomponent stringlistaddfirst listbox1datasource stringlist private void button1 clickobject sender eventargs e stringlistaddsecond the string first shows in listbox1 on application launch however when i push the button which adds a new string to the stringlist the new item is not shown in listbox1 could anyone help me understand the basics of collection data binding,"['c#', '.net']" +162929,using parameters in backgroundworker handlers for passing data to a backgroundworkers dowork i use a separate wrapper class instancemyparams mpar new myparamsmparpar1 par1valmparpar2 par2valmparpar3 par3valvar worker1 new systemcomponentmodelbackgroundworkerworker1dowork new doworkeventhandlerworker1 doworkworker1runworkercompleted new runworkercompletedeventhandlerworker1 runworkercompletedworker1runworkerasyncmparthen i can use parameters of mpar instance in worker1 dowork operating in another threadvoid worker1 doworkobject sender doworkeventargs e here we use mparpar1 mparpar2 and so on in runworkercompletedeventhandler we do some postactions in ui threadmy question is can we use in runworkercompleted handler the mpar instance which worked just before in dowork handler and can we be sure its values are the same it had in dowork if not what is the correct approach for sharing parameters for various stages of backgroundworker operationvoid worker1 runworkercompletedobject sender runworkercompletedeventargs e thispatcherbegininvokeaction can we use the mpar instance here,['c#'] +162934,how to convert icon from jlabel into bufferedimage simple very straight forward but seems uncle google and me getting confusedi have single jlabel that already has its own iconhow do i convert the icon obtained from jlabel into a bufferedimageis there any way around i tried to multiple casting like this final bufferedimage bf1 bufferedimageimagejll imggeticonbut it failed,['java'] +162946,some questions about automatic reference counting in ios5 sdk i am currently developing an app for ipad the development started for ios 42 and is now continuing and i think will be completed for ios 43i just read about arc in ios 5 and basically i understood that we will never need to release and retain objects anymore my questions areif i decide to upgrade to ios 5 do i need to remove all myobject retain and myobject release statements from my codeif i develop a new app for ios 5 using arc will i need to implement some sort of retrocompatibility checks ie will i need to check the version of ios and call retain and release accordingly so basically is arc available for all ios versions or just for ios 5,['objective-c'] +163004,nsbutton set text color in thisabled mode for some reason when my button is thisabled the text color turns whitei want it to stay black how can i do that,['objective-c'] +163008,media queries how to target desktop tablet and mobile i have been doing some research on media queries and i still do not quite understand how to target devices of certain sizes i want to be able to target desktop tablet and mobile i know that there will be some thiscrepancies but it would be nice to have a generic system that can be used to target these devices some examples i have found mobileonly screen and minwidth 480px tabletonly screen and minwidth 768px desktoponly screen and minwidth 992px hugeonly screen and minwidth 1280px or phoneonly screen and maxwidth320px tabletonly screen and minwidth321px and maxwidth768px desktoponly screen and minwidth769pxwhat do you think these breakpoints should be for each device,['css'] +163024,comparing two strings ignoring case in c possible duplicatewhat is difference between different string compare methods which of the following two is more efficient or maybe is there a third option that is better stillstring val astringvalueif valequalsastringvalue stringcomparisoninvariantcultureignorecaseorif valtolowercase astringvalue,['c#'] +163033,sql server how to insert random integers into table i have a test table like thiscreate table temp rid int identity 1 1 not null val int null constraint pk temp rid primary key ridwhat are the different methods in sql server to insert random integers into this table eg for 10 rows while loop cross join or what i tried this but the result is not correctdeclare val as int 1while val 10 begin insert temp val select randval set val val 1 endselect from temp,['sql'] +163051,voice recognition as a background service is it possible to implement an activity as a service my activity is a voice recognition activity i want to have the activity running in the background of the app constantly checking for voice and when the user says a command it will recognize it and then perform the action my question isis it possible to do this and if so how can the background service notify the current activity or application there was a pervious post on this but no clear answerthanks for any input or help here is the voice activitytaken from another stackoverflow postimport androidappactivityimport androidcontentintentimport androidosbundleimport androidviewviewimport androidviewviewonclicklistenerimport androidspeechrecognitionlistenerimport androidspeechrecognizerintentimport androidspeechspeechrecognizerimport androidwidgetbuttonimport androidwidgettextviewimport javautilarraylistimport androidutillogpublic class voicerecognitiontest extends activity implements onclicklistener private textview mtext private speechrecognizer sr private static final string tag mystt3activity override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain button speakbutton button findviewbyidridbtn speak mtext textview findviewbyidridtextview1 speakbuttonsetonclicklistenerthis sr speechrecognizercreatespeechrecognizerthis srsetrecognitionlistenernew listener class listener implements recognitionlistener public void onreadyforspeechbundle params logdtag onreadyforspeech public void onbeginningofspeech logdtag onbeginningofspeech public void onrmschangedfloat rmsdb logdtag onrmschanged public void onbufferreceivedbyte buffer logdtag onbufferreceived public void onendofspeech logdtag onendofspeech public void onerrorint error logdtag error error mtextsettexterror error public void onresultsbundle results string str new string logdtag onresults results arraylist data resultsgetstringarraylistspeechrecognizerresults recognition for int i 0 i datasize i logdtag result datageti str datageti mtextsettextresults stringvalueofdatasize public void onpartialresultsbundle partialresults logdtag onpartialresults public void oneventint eventtype bundle params logdtag onevent eventtype public void onclickview v if vgetid ridbtn speak intent intent new intentrecognizerintentaction recognize speech intentputextrarecognizerintentextra language modelrecognizerintentlanguage model free form intentputextrarecognizerintentextra calling packagevoicerecognitiontest intentputextrarecognizerintentextra max results5 srstartlisteningintent logi1,['android'] +163055,correct syntax for include css file depending on where i look i see different way to include cssexampleslink relstylesheet typetextcss mediascreen projection hreflink relstylesheet typetextcss mediaall hreflink relstylesheet typetextcss mediascreen hreflink relstylesheet hrefdo they all do the sameis one of them the correct way,['css'] +163065,trailing commas and c i have read somewhere that the c standard does not allow something like enum an enum a b c while later versions of ci think from mid90s do allow such declarationswith trailing commas if c is supposed to have backwards compatibility with c how come this feature is forbidden any special reasoni also read that such trailing commas are actually good so that just adds to the confusion,"['c++', 'c']" +163084,how to uninstall all ruby gems on windows how to uninstall all ruby gems on windows is it possible with single command,['ruby-on-rails'] +163086,what is the difference between hostingenvironment class and httpruntime class as you can see here aspnet application life cycle there are two pictures on the first there is created hostingenvironment class in appdomain on the second is created httpruntime class in it from their definitions i dont understand the difference between them when is created one and when is created the second during application life cycle what is the difference between hostingenvironment class and httpruntime class in context of apllication life cycle,['asp.net'] +163100,use reflection to create a generic parameterized class in java how can i use reflection to create a generic parameterized class in javai have public class someclasst public someclasst and i need an instance of iti have tried variations ofclass c classfornamesomeclassbut could not find a syntax that would allow me to get an appropriately typed instance like saysometype instance sometypeclassfornamesomeclasometypecreateinstanceso how could i go about doing this,['java'] +163110,stringsplit not on regular expression since stringsplit works with regular expressions this snippetstring s strstrarghssplitr yields s t s t a g hwhats the most elegant way to split this string on the r sequence so that it produces st st arghedit i know that i can escape the problematic the trouble is i do not know the delimiter offhand and i do not feel like working this around by writing an escapegenericregex function,['java'] +163112,how to set a fragment tag by code i have not found something like settagstring tagname method in the fragment class the only way to set a fragment tag that i have found is by doing a fragmenttransaction and passing a tag name as parameteris this the only way to explicitly set a fragment tag by code,['android'] +163116,rename aspnet mvc project resulting in multiple types for controller error this has happenned before and i cannot remember how i solved it i renamed an mvc project then did a resharper refactor to update the namespaces now when i run i get the following error when i run the projectmultiple types were found that match the controller named dashboard this can happen if the route that services this request controlleractionid does not specify namespaces to search for a controller that matches the request if this is the case register this route by calling an overload of the maproute method that takes a namespaces parameterthe request for dashboard has found the following matching controllersekmdomainsfrontendcontrollersdashboardcontrollerekmdomainswebcontrollersdashboardcontrolleri have done a search for everywhere in the solution where the old ekmdomainsfrontend namespace ocurrs and replaced it with the new one but to no availanyone have any ideas,['c#'] +163124,c net garbage collection not functioning i am working on a relatively large solution in visual studio 2010 it has various projects one of them being an xna gameproject and another one being an aspnet mvc 2projectwith both projects i am facing the same issue after starting them in debug mode memory usage keeps rising they start at 40 and 100mb memory usage respectively but both climb to 15gb relatively quickly 10 and 30 minutes respectively after that it would sometimes drop back down to close to the initial usage and other times it would just throw outofmemoryexceptionsof course this would indicate severe memory leaks so that is where i initially tried to spot the problem after searching for leaks unsuccesfully i tried calling gccollect regularly about once per 10 seconds after introducing this hack memory usage stayed at 45 and 120mb respectively for 24 hours until i stopped testingnets garbage collection is supposed to be very good but i cannot help suspecting that it just does not do its job i have used clr profiler in an attempt to troubleshoot the issue and it showed that the xna project seemed to have saved a lot of byte arrays i was indeed using but to which the references should already be deleted and therefore collected by the garbage collectoragain when i call gccollect regularly the memory usage issues seem to have gone does anyone know what could be causing this high memory usage is it possibly related to running in debug mode,"['c#', '.net']" +163138,unknown screen output of manually installed python 27 i installed python 27 today usingconfigure prefixhomezhanwulocal enableshared enableprofiling withpydebugmake installthen i keep getting something like 37745 refs on screen after each function callzhanwucluster localbinpythonpython 271 r27186832 jun 16 2011 174505 gcc 412 20080704 red hat 41244 on linux2type help copyright credits or license for more information import sys37745 refs print testtest37745 refs sysexit18048 refszhanwucluster what does those numbers mean anything wrong here and can i get rid of themuname a resultzhanwucluster uname alinux clusterx 2618128114el5 1 smp wed jun 17 063805 edt 2009 x86 64 x86 64 x86 64 gnulinux,['python'] +163166,how does this array size template work i came across this snippettemplate typename t size t n char arraysizehelpert arraynn define arraysizearray sizeofarraysizehelperarray in this article i have seen other templates to do the same thing like this oneuse templates to get an arrays size and end addressand i understand those but i have been having difficulty with this oneany help would be appreciated,['c++'] +163169,is there a way to specify to spring that a bean should be used upon initialization and then immediately thiscarded i am interested to know if there is an interface that i can use to tell spring to start a particular bean up invoke its initialization procedure either as an initializingbean via afterpropertiesset or via an initmethod or some other way and then throw it awaymy use case is a simple sanitychecker that will check the database for valid values upon startup for a web application although the overhead would be small for our particular bean keeping that bean for all eternity in the application context is pointless as once the bean had initialized it is no longer neededi am sure there are other use cases for this type of behavior but i have not found anything like this yet in springin particular i am looking for it in the java variant of spring i have access to 3x and up as needededit based on the accepted answer the following is a simple hack to provide the solutionpublic final class nullreturningbeanpostprocessor implements beanpostprocessor private liststring beannamestothiscard new arrayliststring creates a new link nullreturningbeanpostprocessor instance public nullreturningbeanpostprocessor super public object postprocessbeforeinitializationobject bean string beanname throws beansexception return bean public object postprocessafterinitializationobject bean string beanname throws beansexception if beannamestothiscardcontainsbeanname return null return bean public void setbeannamestothiscardliststring beannamestothiscard if beannamestothiscard null thisbeannamestothiscard beannamestothiscard placing this bean post processor with the appropriate beans to thiscard in the application context will make them null and eligible for garbage collection after they have been initialized the bean configuration metadata unfortunately will still remain in the application context,['java'] +163178,zxing android generate 1d barcode i have gone through the examples here regarding encoding barcode but all it generates are qr i am looking for 1d barcode generation encoding whats the right encode typeintent intent new intentcomgooglezxingclientandroidencodeintentsetpackagecomgooglezxingclientandroidintentputextraencode type barcode scanner does not like encode type code 39 nor code 93 any ideas,['android'] +163180,how to mute an html5 video player i have found how to pause and play the video using jqueryvideoget0playvideoget0pausebut i cannot find the mute button if there is not a jquery solution i am fine with just an onclick js solution i need it asapalso is there a way to fix the mute delay i want it to muteunmute the sound as soon as the button is clicked,"['javascript', 'jquery']" +163187,can resource be used to inject primitives in ejb30 using glassfish i can setup a string jndi entryjndi name comxyzcompanyechoechoservicebeanviewnamefactory class orgglassfishresourcescustomfactoryprimitivesandstringfactoryproperties valuetesting123i can then inject this container configured string into my ejb resourcelookup comxyzcompanyechoechoservicebeanviewname string viewnamethe lookup appears to internally do an initialcontextlookup however this uses ejb31 but unfortunately my prod environment is only ejb30i guess i am trying to figure out is there a way to use resourcename or resourcemappedname to do something similar name appears to be application specific so i should be able to somehow map a relative name to a global jndi name but i cannot figure out what annotation does the mappingthanks,['java'] +163188,memcached or mysql for session storage php is it good idea to use memcached for session storage with php we will have a lot of servers and we must access the session data from everywhere so we are forced to use database in our case that will be mysql as session storage or memcached what do you think,['mysql'] +163198,trycatch async exceptions this example failsstatic async void mainstring args try await taskexrun throw new exceptionfailure catch exception throw new exceptionsuccess that is the exception with the text failure bubbles upthen i tried this workaroundstatic async void mainstring args try await saferun throw new exceptionfailure catch exception throw new exceptionsuccess static async task saferunaction action var ex defaultexception await taskexrun try action catch exception ex if ex defaultexception throw exthat did not help eitheri suppose my async ctp refresh installation could be hosedshould this code work as i expect success bubbles up not failure or is this not supposed to work that way and if not how would you work around it,['c#'] +163202,modify log format and content from default actioncontroller logsubscriber in rails 3 contextin a rails 3 project i want to customise heavily the format and content of the processing and completed in log lines from actioncontroller this is in order to have them match the also custom format of an older rails 23 app allowing reuse of various analysis tools making them fixedfield by use of placeholders where necessary also makes it far easier to do adhoc queries on them with say awk or to load them into a db or splunk without smart parsingi have achieved this goal quickly and heavyhandedly by forking rails and patching the logsubscriber in question but i am now looking to do it the right wayheres what i think i want to docreate a logsubscriber inheriting actioncontrollerlogsubscriberoverride only the start processing and process action methodsunsubscribe the original actioncontrollerlogsubscriber which sadly registers itself as soon as the class is loaded this is the step i am stuck onattach my custom subscriber to action controller using attach toi note that things would be easier if the hookup of the default actioncontrollers log subscriber were done as a config step rather than on class loadquestionassuming the approach outlined above is suitable how can i unsubscribe or unattach the default log subscriber actioncontrollerlogsubscriber the base class activesupportlogsubscriber provides attach to but no means of detachingalternatively what is the cleanest way of altering the behaviour of or entirely suppressing the two methods start processing process action in the above mentioned class actioncontrollerlogsubscriberof course i would also welcome any other maintainable approach which provides full freedom in customizing the log format of the two lines mentionedunsuitable approachesmy problem cannot be solved by adding instrumentation as documented nicely by mnutti would like to avoid monkeypatching or hacking in a way that may break when the rails implementation not interface changesreferencesdocs and source for activesupportlogsubscribersource for actioncontrollerlogsubscriberdocs source and railscast for activesupportnotifications,"['ruby-on-rails', 'ruby']" +163217,how to rekey array with nonsequential numeric keys i have an arrayarray 0 ololo 2 test 3 haha 7 nicehow can i change the indexes of the array to thisarray 0 ololo 1 test 2 haha 3 nice,['php'] +163227,jquery each this and element inside a each callback is there any difference between this and the second argument of the callback functionfor example in the following codeexampleeach functionindex element bodyis there any difference between this and element is the second argument just provided so you can choose a name,['jquery'] +163244,get all the values of a dropdownlist to an array using javascript how can i get the values of dropdownlist to an array,['javascript'] +163247,different appender per method just started using log4net and trying to get my head around the config and logger hierarchy is this hierarchy based on namespaces or class and methodfunction hierarchylets say i have the following class structurepublic class myclass private static readonly ilog log logmanagergetloggertypeofmyclass public void method1 log4netinfomessage public void method2 log4netinfomessage is it possible to setup in the config for the log4netinfo in method1 to use one appender and the log4netinfo in method 2 to use another appender even if they are off the same type eg smtpappender if so how would the config look here is my first attempt at itappender namesmtp1 typelog4netappendersmtpappenderappenderappender namesmtp2 typelog4netappendersmtpappenderappenderlogger namemyclassmethod1 level valueinfo appenderref refsmtp1 loggerlogger namemyclassmethod2 level valueinfo appenderref refsmtp2 logger,"['c#', '.net', 'asp.net']" +163255,the applicationidentifier entitlement is not formatted correctly ios xcode 4 i have migrated to xcode 4 and can no longer submit my application to the app store every time i submit either via xcode or application loader i get the same errorthe applicationidentifier entitlement is not formatted correctly googling this points to the entitlementsplist file where the applicationidentifier key should match my application bundle id j1234567885comdomainappname for examplething is it is the bundle identifier in my aplist and in the entitlementsplist are identical what am i doing wrong heres my entitlementsplist file which has never changed looking backxml version10 encodingutf8doctype plist public appledtd plist 10en plist version10dict keyapplicationidentifierkey stringj1234567885comdomainappnamestring keygettaskallowkey truedictplisti have changed the identifier above but just to give you an idea,"['iphone', 'ios']" +163257,where are net user settings stored if user system i have been working with an updated to update one of my apps and using propertiessettingsdefaultupgrade and thiscovered that after my updater restarts my app it is run under the system user instead of the defaultlogged in user this got me wondering where is the userconfig for system storedi know where the userconfig is stored normally cdocuments and settingsuserprofilelocal settingsapplication dataetc but there is not a folder in documents and settings for the system user does anybody know where it is orhow net handles this,['c#'] +163260,custom config section containing collection i am having trouble getting a custom config section to work it is some code i got from the web in an effort to try to understand this area a little better and enable me to get to where i want to ultimatly be my own custom config sectionthe error i get when i run the code in a console app isunrecognized attribute extension note that attribute names are casesensitivethe code in the main app to get things going isvar conf configurationmanagergetsectionuploaddirectorand this is where the exception appearsthis is the config section i am hopingtrying to achieveauthorisedclients authorisedclient nameclient queue id1 queue id7 authorisedclient authorisedclient nameclient2 queue id3 queue id4 authorisedclient authorisedclientsheres the code i have got from the webconfig fileuploaddirector filegroup namedocuments defaultdirectorydocuments clear add extensionpdf mimeapplicationpdf maxsize100 add extensiondoc mimeapplicationword maxsize500 filegroup filegroup nameimages clear add extensiongif mimeimagegif maxsize100 filegroup uploaddirectoruploaddirectorconfigsectioncspublic class uploaddirectorconfigsection configurationsection private string rootpath public uploaddirectorconfigsection configurationpropertyrootpath defaultvalue isrequiredfalse iskeyfalse stringvalidatorinvalidcharacters public string rootpath get return rootpath set rootpath value configurationproperty isrequired true iskey false isdefaultcollection true public filegroupcollection filegroups get return filegroupcollection base set base value filegroupcollectioncspublic class filegroupcollection configurationelementcollection protected override configurationelement createnewelement return new filegroupelement protected override object getelementkeyconfigurationelement element return filegroupelement elementname public override configurationelementcollectiontype collectiontype get return configurationelementcollectiontypebasicmap protected override string elementname get return filegroup protected override bool iselementnamestring elementname if stringisnullorwhitespaceelementname elementname filegroup return false return true public filegroupelement thisint index get return filegroupelement basegetindex set ifbasegetindex null baseremoveatindex baseaddindex value filegroupelementcspublic class filegroupelement configurationelement configurationpropertyname iskeytrue isrequired true stringvalidatorinvalidcharacters public string name get return string basename set basename value configurationpropertydefaultdirectory defaultvalue public string defaultdirectory get return string basepath set basepath value configurationproperty isdefaultcollection true isrequired true public fileinfocollection files get return fileinfocollection base fileinfocollectioncspublic class fileinfocollection configurationelementcollection protected override configurationelement createnewelement return new fileinfocollection protected override object getelementkeyconfigurationelement element return fileinfoelement elementextension fileinfoelementcspublic class fileinfoelement configurationelement public fileinfoelement extension txt mime textplain maxsize 0 configurationpropertyextension iskey true isrequired true public string extension get return stringbaseextension set baseextension value configurationpropertymime defaultvalue textplain public string mime get return string basemime set basemime value configurationpropertymaxsize defaultvalue 0 public int maxsize get return int basemaxsize set basemaxsize value,"['c#', '.net']" +163273,selenium 2 interrupt a page load i have an issue when clicking on a button with selenium 20b3 java api with firefoxdriver clicking on the button sends a form to the webserver and then browser goes to a new page as a result of the form submissionwhen clicking on an element with elementclick selenium is waiting for the browser to complete its operations the browser waits until the page load is finished but sometimes the page load takes an enormous amount of time due to some advertisement requestshow to work around the synchronisation between elementclick and the page loadeditas explained in the webelement javadocclick this element if this causes a new page to load this method will block until the page has loadedthanks,['java'] +163296,why does python not perform type conversion when concatenating strings in python the following code produces an errora abcb 1printa bthe error is typeerror cannot concatenate str and int objectswhy does the python interpreter not automatically try using the str function when it encounters concatenation of these types,['python'] +163339,nunit not working in windows 7 at all i am new to unit testing and this ism y first time trying nunitmy environment is windows 7 professional 64 bit visual studio 2010 and i am working on a windows application in c i just wrote a single test and i am trying to run the test using nunit gui my nunit version is 2510 i also tried 4 other versions below this and i get the same errorthe error issystembadimageformatexception could not load file or assembly datalogger version10 cultureneutral publickeytokennull or one of its dependencies an attempt was made to load a program with an incorrect formatyou may be attempting to load an assembly built with a later version of the clr than the version under which nunit is currently running2050727 or trying to load a 64bit assembly into a 32bit processfor further information use the exception details menu itemwhat i did is i loaded the application exe in the debug folder of the project into the nunit gui i mentioned this because i have a doubt that this could be the wrong way any help on this would be useful for me,['c#'] +163362,tree with multiple child nodes and next node i want to build a tree with the following characteristicsevery node can have 1 next nodeevery node can have multiple child nodesthe number of child nodes can vary from one node to the otheri was thinking of a struct which looked like thisstruct tree int value struct tree nextnode struct tree childnodethe number of children at each node has to be parametrized i am not sure how to do this thanks in advanceedit let me try to define it using an example let us take the starting node now i will define at compile time that there will be 3 nextnodes and each of these nextnodes will have 2 childnodes this is at depth0 at depth 1 ie for each child node from depth0 i specify that there will be 4 nextnodes and for each of these nextnodes there will be 3 childnodes and so on hope i am able to convey it properly please do ask if i am not clear somewhereedit2 here is a pic,['c'] +163367,playframework owasp top 10 i am thinking about using play for a largescale project so has anyone battletested play framework for owasp top 10 are there any security problems you know of in play framework,['java'] +163374,net remove javascript and css code blocks from html page i have html as string with javascript and css code blockssomething like thisscript typetextjavascript alerthello worldscriptstyle typetextcss alink textdecoration none avisited textdecoration none aactive textdecoration none ahover textdecoration underline color redstylebut i dont need them how can i remove with reqular expressions those blocks,"['c#', '.net', 'html']" +163376,python mysqldb library not loaded libmysqlclient18dylib i just compiled and installed mysqldb for python 27 on my mac os 106 i created a simple test file that imports import mysqldb as mysqlfirstly this command is red underlined and the info tells me unresolved import then i tried to run the following simple python codeimport mysqldb as mysqldef main conn mysqlconnect charsetutf8 use unicodetrue hostlocalhostuserroot passwddb if name main mainwhen executing it i get the following error messagetraceback most recent call last file pathtoprojectpythonsrccvdvtestmysqldbpy line 4 in module import mysqldb as mysql file buildbthistmacosx106inteleggmysqldb init py line 19 in module namespace cvdv file buildbthistmacosx106intelegg mysqlpy line 7 in module file buildbthistmacosx106intelegg mysqlpy line 6 in bootstrap importerror dlopenuserstoompythoneggsmysql python123py27macosx106inteleggtmp mysqlso 2 library not loaded libmysqlclient18dylib referenced from userstoompythoneggsmysql python123py27macosx106inteleggtmp mysqlso reason image not foundwhat might be the solution to my problemeditactually i found out that the library lies in usrlocalmysqllib so i need to tell my pydev eclipse version where to find it where do i set this,['python'] +163377,how to combine two array list and show in a listview in android i want to combine two arraylist into a single onemy first arraylist looks like this asdfghmy second arraylist looks like this zxcvbthen i want to combine both to be as asdfghzxcvbfirst list isarrayliststring firstname1 new arrayliststringwhere as the second list is asarrayliststring first new arrayliststringnow i want to combine all this together and i want it to be listed out in list viewhow to do this,['android'] +163409,how to set savon default timeout value i am using savon to make some api calls but its taking long time to respond because of that i am getting time out errorsso is there any way to change the default value of timeout i am using savon 079 ruby 187 and rails v 232,['ruby-on-rails'] +163410,how to parse a url from a string in android i want to parse the url from a string in android the example string is this is a new message the content of the message is in i want to parse the url from the string without using the substring method,"['java', 'android']" +163415,update with sub select how to handle null values i am trying an update with a conditional subselect which could return nullupdate atable set acolumn select top 1 case when btablesomecolumn 1 then somevalue1 when btablesomecolumn 2 then somevalue2 else somevalue3 end from btable where btable somecriteria order by somesortcolumn where atableid someidif the btable somecriteria clause causes no results to be returned from the select it attempts to insert a null into acolumn which in this case is a not null columnquestionhow do i get it to simply leave acolumn alone in this circumstancemany thanks,['sql'] +163427,why is a dictionary not ordered i have read this in answer to many questions on here but what exactly does it meanvar test new dictionaryint stringtestadd0 zerotestadd1 onetestadd2 twotestadd3 threeasserttestelementat2value twothe above code seems to work as expected so in what manner is a dictionary considered unordered under what circumstances could the above code fail,"['c#', '.net']" +163437,correctness of sakamotos algorithm to find the day of week i am using sakamotos algorithm to find out the day of week from a given datecan anybody tell me the correctness of this algorithm i just want this from 20 to 2099the algorithm from wikipedia is given for referenceint dowint y int m int d static int t 0 3 2 5 0 3 5 1 4 6 2 4 y m 3 return y y4 y100 y400 tm1 d 7,['c'] +163460,pointerarrayextern question file 1cint a10file maincextern int aint main printfdn a0 return 0gives me a segfault whats going wrong,['c'] +163466,validating css color names i have written a jquery plugin that accepts css colors for some of its parametersi want to validate them if it was just a hex or rgb value i could do that with a regular expression but how do i validate all 147 valid color names without bloating the plugini was wondering if there is some way of attempting to apply a style maybe with jquery and then catching an error from the browser if it is not validedit powtac and pantelis came up with a solution but they both missed edge cases so i am including a full solution here var validatecsscolour functioncolour var rgb div stylecolor28e32a use a non standard dummy colour to ease checking for edge cases var valid rgb rgb40 227 42 rgbcsscolor colour ifrgbcsscolor valid rgb colour 28e32a colourreplace g valid rgbreplace g return false else return true,"['javascript', 'jquery', 'css']" +163472,want a regex for validating indian vehicle number format hello everyone herei need to build up a swing application related to vehicle registration and in which i want to do input the vehicle number of indian standard likemp 09 ab 1234ah 17 ft 2387ut 32 dr 6423more specificallyplease if any one can help medocumentfilter type class can also help me,['java'] +163487,learning kohana i am a reasonably intelligent guy and have been involved in a lot of stuff like html php java c c c assembly and so on and so forth all in all i think that there is very little i do not have basic understanding of though of course i am by no means an expert in all the subjects it is simply to illustrate that i am not as green as i may very well soundnow the thing is that i have been instructed to learn about the kohana framework in order to help with some web development at work well that is all well and good especially as i am kinda tired of spending my time correcting other peoples htmlcss mess to do some proper coding for a change would indeed be niceso i set out to learn what i thought would be easy as pie and not only did i think so i was told so imagine my thisappointment when after making an effort i still did not have the most basic understanding of the subjectthe documentation is unsatisfying to say the least and i have yet to find a proper explanation of the subject as a wholein short i understand close to nothing and the more effort i make the more confused i get i honestly do not know where to begin and endi cannot really tell you what i need to get going as my understanding is not even significant enough to know what i need to learn i suppose a tutorial explaining step by step how to make something useful would be in order but i have been unable to find anything in the many hours i have spent searchingthis is my last way out and the only possibly solution i could come up with to ask you how you initially learned to use kohanai do apologize for the lack of an actual question but i do hope that youll do your best to help anyway,['php'] +163504,creating a flash game bot does anyone have any recommendations for resources or methods on how to create a bot in java which can play a flash gamei am thinking of using the robot class to watch the screen and make actions but i need ways of finding images in images etc i am sure this has been done before but google searches return alot of nonsense,['java'] +163528,change the name of android project is there any posibility that i could change the name of my project as it appears in package exploreri am using eclipse idei tried to edit the stringxml in resvalue folder but that would not change it in the explorer viewthank u,['android'] +163551,consuming soap web services on ios i am trying to write applications for ipad which take advantage of web services i know the concept of a web service and have used it in cnet i need to know how to do this on an ipad can anyone recommend a good book or reading material on webservices for ios,['ios'] +163566,quick and easy trayicon with python i would just need a quick example on how to easily put an icon with python on my systray this means i run the program no window shows up just a tray icon i have got a png file shows up in the systray and when i rightclick on it a menu appears with some options and when i click on an option a function is runis that possible i do not need any window at allexamples code snippets are really appreciated d,['python'] +163569,how to use emacs and cedet with scons how to integrate scons and emacs cedet without breaking semantic and autocomplete,['c++'] +163576,c making a procestart wait until the process has startup i need to make sure that a process is running before moving on with a methodthe statement isprocestartpopupexecan you do a wait command or set a delay on this value,"['c#', '.net']" +163582,how do i see the django debug toolbar i have a django webapp i have installed the debug toolbar middleware and modulehowever my webapps do not have the debug toolbar pullouthow do i actually see the debug toolbar is there something more i need to dodo i need to use a particular template for my webapp i have followed all the steps in the readme but that is not enough there seems to be some other dependency or something else i am missingalso when looking at the set of url patters for my webapp the debug prefix is not found among the recognized patterns i have put a log in urlspy in debug toolbar to make sure that modules is getting loaded by the activated debug toolbar application and it isthis has me totally mystified and i can find no google or readme on what to do to make this actually show up or what the requirements are so any pointer you can provide would be greatedit it turns out i was testing this with a ssh tunnel from the machine running the browser to the machine running the djangoapache in this case the ip address actually seen for the remote machine was not what i thought it was so the list of good ips did not contain the browsers apparent remote machine fixing that fixed the problem,['python'] +163593,implement a simple factory pattern with spring 3 annotations i was wondering how i could implement the simple factory pattern with spring 3 annotations i saw in the documentation that you can create beans that call the factory class and run a factory method i was wondering if this was possible using annotations onlyi have a controller that currently calls myservice myservice myservicefactorygetmyservicetestresult myservicecheckstatusmyservice is an interface with one method called checkstatusmy factory class looks like thiscomponentpublic class myservicefactory public static myservice getmyservicestring service myservice myservice service servicetolowercase if serviceequalsone myservice new myserviceone else if serviceequalstwo myservice new myservicetwo else if serviceequalsthree myservice new myservicethree else myservice new myservicedefault return myservice myserviceone class looks like this autowiredprivate locationservice locationservicepublic boolean checkstatus do stuffwhen i run this code the locationservice variable is alwasy null i beleive this is because i am creating the objects myself inside the factory and autowiring is not taking place is there a way to add annotations to make this work correctlythanks,['java'] +163624,how exactly to use notificationbuilder i found that i am using a deprecated method for noficitations notificationsetlatesteventinfoit says to use notificationbuilder how do i use itwhen i try to create a new instance it tells menotificationbuilder cannot be resolved to a type,['android'] +163630,rails 3 one app multiple domains how implement a different root route for one of the domains several different domains names point to my app on heroku for example foocom and barcom both point to the app we host specialized blog pages and foocom is the domain used by our users who are creating web pages and barcom is the public facing domain where the blog pages areall the userediting pages have devise authentication and the root on foocom is the users dashboard page and a loggedin user can preview their blog page at foocomreviewpageuserideach user acount also has a unique friendly url name such as acmeincdallastxon the publicfacing web page barcom but only this one domain i need to somehow map to controller mycontroller action myactioni assume that means i need to remap root on barcom but only barcom to a method find friendly url that looks up the appropriate page and thisplays itif that is the right way to proceed how would i remap root for one and only one domain that points to my app,['ruby-on-rails'] +163638,how to label set title for iis express process i have a solution with multiple websites and i have been using cassini for development when iis express came out i transitioned one of the websites to use it and everything has been running fine i just moved another website to use iis express and immediately ran into a problem with debugging iis express does not label its processes so now that i have two of them running i cannot tell them apart in the attach to process dialogis there a way to have iis express set the process title anyone have any tips for telling multiple iis express instances apart for the purposes of attaching the debuggerupdatea roundabout way of doing this is to execute show all applications context menu of the iis express tray icon and reference the pid from the list when attaching the debugger better than nothing but would be nice if there was a better wayupdate 2i added a connect issue,['asp.net'] +163645,devise migration not working i created a user model using devise and whenever i use rake dbmigrate i get the following issue devisecreateusers migrating create tableusersrake abortedan error has occurred this and all later migrations canceledundefined method database authenticatable for activerecordconnectionadapterstabledefinition0x0103fa1ff0tasks top dbmigratesee full trace by running task with tracei run the full trace with the trace function but cannot seem to figure out what the issue is here is the migration fileclass devisecreateusers activerecordmigrationdef selfupcreate tableusers do t tdatabase authenticatable null false trecoverable trememberable ttrackable tconfirmable tencryptable tlockable lock strategy failed attempts unlock strategy both ttoken authenticatable ttimestamps endadd index users email unique trueadd index users reset password token unique trueadd index users confirmation token unique true add index users unlock token unique true add index users authentication token unique trueenddef selfdown drop table users endend,['ruby-on-rails'] +163654,ruby on rails looks for css in assets instead of publicstylesheets i am new to ruby using ruby 192p180 and rails 310rc2i have screencss in my app rootpublicstylesheetsscreencss and in my applicationhtmlerb stylesheet link tag screencss media screen according to here it should work but my rails server saysprocessing by pagescontrollerhome as html rendered pageshomehtmlerb within layoutsapplication 00ms completed 200 ok in 4ms views 36ms activerecord 00msstarted get assetsscreencss for 127001 at 20110618 112753 1200 served asset screencss 404 not found 2ms pid 10966actioncontrollerroutingerror no route matches get assetsscreencsswhat am i doing wrong herethanks in advance,"['ruby-on-rails', 'css']" +163669,paste image into rich text like gmail i want to be able to copy an image from clipboard specifically screenshots and paste them right into a rich text editor andor have that file uploaded we only use chrome so it only has to work for chromenow when youare running the latest version of google chrome you can paste images right from your clipboard too so if you copy an image from the web or another email you can paste it right into your messagedoes anyone know if this new gmail feature is something javascript that id be able to implement myself or any other insight into this,['javascript'] +163672,jquery html5 speech input i am trying to make jquery make the search boxes on my page use xwebkitspeech and submit automaticallythe html would obviously be input typetext ids names xwebkitspeechxwebkitspeech onwebkitspeechchangethisformsubmit i can add the xwebkitspeech attribute with jquery but i cannot seem to get onwebkitspeechchange to workthis does not work since jquery does not have a onwebkitspeechchange method jquerynamesattrxwebkitspeech xwebkitspeechonwebkitspeechchangethisformsubmitbut i figured something like this would work jquerynamesattrxwebkitspeech xwebkitspeechattronwebkitspeechchange thisformsubmitbut it does not it just does not do anything how can i add onwebkitspeechchangethisformsubmit using jquery,"['javascript', 'jquery']" +163690,an algorithm to calculate probability of a sum of the results happening the algorithm i am talking about using would allow you to present it with x number of items with each having a range of a to b with the result being y i would like to have an algorithm which would when presented with the values as described would output the possibility of it happeningfor example for two die since i already know themdue to the possible results being so low it would be able to tell you each of the possibilitiesthe setup would be something like x2 a1 b6 if you wanted to know the chance of having it result in a 2 then it would simply spit out 136or it is float value if you put in 7 as the total sum it would tell you 6so my question is is there a simple way to implement such a thing via an algorithm that is already written or does one have to go through every single iteration of each and every item to get the total number of combinations for each valuethe exact formula would also give you the combinations to make each of the values from 112so it would give you a thistribution array with each ones combinations at each of the indexes if it does 012 then 0 would have 0 1 would have 0 and 2 would have 1i feel like this is the type of problem that someone else has had and wanted to work with and has the algorithm already done if anyone has an easy way to do this beyond simply just looping through every possible value would be awesomei have no idea why i want to have this problem solved but for some reason today i just had this feeling of wanting to solve it and since i have been googling and using wolfram alpha along with trying it myself i think it is time to concede defeat and ask the communityi would like the algorithm to be in c or maybe phpeven though i would rather it not be since it is a lot slower the reason for c is simply because i want raw speed and i do not want to have to deal with classes or objectspseudo code or c is the best ways show your algorithmeditalso if i offended the person with a b in his name due to the thing about mathematics i am sorry since i did not mean to offend but i wanted to just state that i did not understand it but the answer could have stayed on there since i am sure there are people who might come to this question and understand the mathematics behind italso i cannot decide which way that i want to code this up i think i will try using both and then decide which one i like more to seeuse inside of my little librarythe final thing that i forgot to say is that calculus is about four going on five years ago my understanding of probability statistics and randomness come from my own learning via looking at codereading wikipediareading books if anyone is curious what sparked this question i had a book that i was putting off reading called the drunkards walk and then once i say xkcd 904 i decided it was time to finally get around to reading it then two nights ago whilst i was going to sleep i had pondered how to solve this question via a simple algorithm and was able to think of one my coding understanding of code comes from tinkering with other programs seeing what happened when i broke something and then trying my own things whilst looking over the documentation for the build in functions i do understand big o notation from reading over wikipediaas much as one can from that and pseudo code was because it is so similar to python i myself cannot write pseudo codeor says the teachers in college i kept getting notes like make it less like real code make it more like pseudo code that thing has not changededit 2 incase anyone searching for this question just quickly wanted the code i have included it below it is licensed under the lgplv3 since i am sure that there exists closedsource equivalents of this codeit should be fairly portable since it is written entirely in c if one was wanting to make it into an extension in any of the various languages that are written in c it should take very little effort to do so i chose to mark the first one that linked to ask dr math as the answer since it was the implementation that i have used for this questionthe first files name is sum probabilitycinclude mathhinclude stdlibhinclude stdiohinclude limitsh file name sum probabilityc set of functions to calculate the probabilty of and number of items adding up to s with sides x the question that this program relates to can be found at the url of copyright 2011 macarthur inbody this program is free software you can rethistribute it andor modify it under the terms of the lesser gnu general public license as published by the free software foundation either version 3 of the license or at your option any later version this program is thistributed in the hope that it will be useful but without any warranty without even the implied warranty of merchantability or fitness for a particular purpose see the gnu general public license for more details you should have received a copy of the lesser gnu general public license along with this program if not see 20110620 060357 pm 0400 these functions work by any input that is provided for a function demonstrating it please look at the second source file at the post of the question on stack overflow it also includes an answer for implenting it using recursion if that is your favored way of doing it i personally do not feel comfortable working with recursion so that is why i went with the implementation that i have included the following functions implement falling factorials so that we can do binomial coefficients more quickly via the following formula k prod nkii i1unsigned int returnunsigned int m product c int k int n int i1 float result1 fori1iki resultnkiiresult return resultfloat returnfloat m product cffloat n float k int i1 float result1 fori1iki resultnkiiresult return result the following functions calculates the probability of and items with x sides that add up to a value of s the formula for this is included below the formula comes from ssumnnumber of itemsxsidessnx sum 1k cnk csxk1n1 k0float chance calc singlefloat min float max float amount float desired result float rangemaxmin1 float seriesceildesired resultamountrange float i amount float chances00 fori0iseriesi chancespow1im product cfamountim product cfdesired resultrangei1amountchances return chancesand here is the file that shows the implementation as i said in the previous fileinclude sum probabilityc file nametestc function showing off the algorithms working user provides input via a cli and it will give you the final resultint mainvoid int amountminmaxdesired results printfsplease enter the amount of itemsn scanfiamount printfsplease enter the minimum value allowedn scanfimin printfsplease enter the maximum value allowedn scanfimax printfsplease enter the value you wish to have them add up to n scanfidesired results printfthe total chances for i is fn desired results chance calc singlemin max amount desired results,['c'] +163692,very basic python question strings formats and escapes i am starting to learn python with an online guide and i just did an exercise that required me to write this scriptfrom sys import argvscript filename argvprint were going to erase r filenameprint if you do not want that hit ctrlc cprint if you do want that hit returnraw inputprint opening the filetarget openfilename wprint truncating the file goodbyetargettruncateprint now i am going to ask you for three linesline1 raw inputline 1 line2 raw inputline 2 line3 raw inputline 3 print i am going to write these to the filetargetwriteline1targetwritentargetwriteline2targetwritentargetwriteline3targetwritenprint and finally we close ittargetclosei got it to run fine but then the guide saidthere is too much repetition in this file use strings formats and escapes to print out line1 line2 and line3 with just one targetwrite command instead of 6i am not sure how to do this can anyone help thanks,['python'] +163696,two 1 and relations in mongoid rails the scenario is how can an account give ratings to another account this results in two lists on the account those who i have rated and those who have rated me my ratings and ratings giventhis boils down tohow can multiple 1 and relationsips to the same entity work in mongoidin mongoids docs it says you can use has many and belongs to to link the entities togetheri currently have this on account has many ratings as my ratings has many ratings as ratings givenand this on ratings belongs to user as rater belongs to user as ratiethe docs do not cover this case so i thought you would have to differentiate between the two with an as parameteris this even remoting correct,['ruby-on-rails'] +163698,what would be the most ethical way to consume content from a site that is not providing an api i was wondering what would be the most ethical way to consume some bytes 386 precisely of content from a given site a with an application eg google app engine in some site b but doing it right no scraping intended i really just need to check the status of a public service and they are currently not providing any api so the markup in site a has a javascript array with the info i need and being able to access that let us say once every five minutes would sufficeany advice will be much appreciatedupdatefirst all thanks much for the feedback site a is basically the website of the company that currently runs our public subway network so i am planning to develop a tiny free android app for anyone to have not only a map with the whole network and its stations but also updated information about the availability of the service and those are the bytes i will eventually be consuming etcatera,['javascript'] +163739,get data from php array ajax jquery i have a page as belowheadscript typetextjavascript srcjquery161jsscriptscript typetextjavascriptdocumentready function prevclickfunction ajax type post url ajaxphp data idtestdata cache false success functionresult content1htmlresult0 scriptheadbodytabletrtd idprevprevtdtd idcontent1xtdtd idnextnexttdtrtablebodyand a php file ajaxphp to handle ajax requests asphparray array123456echo arraybut when i click i am getting a instead of array0 how can i fix thisthanks in advance,"['javascript', 'jquery']" +163745,how to double strikeout a text in html i know about s del and strike tags these tags strike out a text once however i want to strike out a text 2 times thiscontinuously can anyone please tell me how to do it thanks in advance,"['html', 'css']" +163752,performance when generating cpu cache misses i am trying to learn about cpu cache performance in the world of net specifically i am working through igor ostovskys article about processor cache effectsi have gone through the first three examples in his article and have recorded results that widely differ from his i think i must be doing something wrong because the performance on my machine is showing almost the exact opposite results of what he shows in his article i am not seeing the large effects from cache misses that i would expectwhat am i doing wrong bad code compiler setting etchere are the performance results on my machineif it helps the processor on my machine is an intel core i72630qm here is info on my processors cachei have compiled in x64 release modebelow is my source codeclass program static stopwatch watch new stopwatch static int arr new int64 1024 1024 static void mainstring args example1 example2 example3 consolereadline static void example1 consolewritelineexample 1 loop 1 watchrestart for int i 0 i arrlength i arri 3 watchstop consolewriteline loop 1 watchelapsedmillisecondstostring ms loop 2 watchrestart for int i 0 i arrlength i 32 arri 3 watchstop consolewriteline loop 2 watchelapsedmillisecondstostring ms consolewriteline static void example2 consolewritelineexample 2 for int k 1 k 1024 k 2 watchrestart for int i 0 i arrlength i k arri 3 watchstop consolewriteline k k watchelapsedmillisecondstostring ms consolewriteline static void example3 consolewritelineexample 3 for int k 1 k 10241024 k 2 256 4bytes per 32 bit int k k kilobytes arr new int256k int steps 64 1024 1024 arbitrary number of steps int lengthmod arrlength 1 watchrestart for int i 0 i steps i arri 16 lengthmod x lengthmod is equal to x arrlength watchstop consolewriteline array size arrlength 4 bytes intwatchelapsedtotalmilliseconds 10 arrlength nanoseconds per element consolewriteline,"['c#', '.net']" +163756,why should i use c str in functions i am reading the book c primer and at the file input output chapter it usesifstream infileifilec strto open a file whose name is in the string ifilei tried the code and it works perfectly even without c str so what is the point of using itshould i use c str when i am trying to open a file from a command line argument i mean which is the correct usageifstream fin argv1 or ifstream fin argv1c str,['c++'] +163760,why does ie respect label css width but not firefox or chrome i am trying to write a contact form however my label widths are not being forced in firefox or chrome ie seems to be working okay though for once heres my html form name id action methodpost div idmy form div label forusernameusernamelabel input typetext nameusername idusername div divformand heres my cssmy form div labelwidth200pxthisplayinlineblockany ideas how i can force the label width they seem to collapse,"['html', 'css']" +163762,php echoing content as page loads so i am doing some experimenting with phpapachelet us say i have this codedivdiv 1divphp sleep2 divdiv 2divphp sleep2 divdiv 3divphp sleep2 divdiv 4divphp sleep2 for some reason on my local apache webserver all the data appears in the browser at once after all 4 sleeps have been executed 8 secondshowever if i run it on my hosts server the data is echoed to the browser in real timeas in div1 appears after 2 seconds div 2 appears etcwhy is that is this some setting in apache,['php'] +163768,how do i get autosuggestions for array options when typing in vim let us say i typea 1 2in a py file in vim and when i type a and hit tab i would like to get suggestion menu that is related to listsedit 1 in response to robins commenti think it is possible in vim because there is a plugin that checks if a given python code is a valid code i do not know what the plugin is called take a look,['python'] +163781,if else statement how to say donothing or continue i have an if else statement although i would like to know how to tell the else part to do nothing if it is true egifx x run calcexeelsedonothingor i am write in saying that if i just remove the else statement it will continue anyway if the if condition is not matched,"['c#', '.net']" +163786,uitableview grouping sections from nsmutablearray i have an app that basically reads an xml file and thisplays the results in a uitableview i am trying to group the list items by country an attribute of the xml file elements and thisplay them in uitableview sectionscurrently i read the xml file and store each element as a custom object in an nsmutablearray the array has the following structurearray 0 title description date country 1 title description date country 2 title description date country 3 title description date countryi have tried creating another array of unique countries which has allowed me to create the section headers correctly but i am struggling to work out a way to thisplay the correct items beneath each section headerifcountryarray containsobjectitemcountry if country not already in array countryarray addobjectitemcountry add nsstring of country name to arraywhere itemcountry is the country attribute of each element as i loop through the xml filecountryarray count gives me the amount of sections neededso i guess my question is how do i work out how many rows need to go in each sectionhow do thisplay the correct array items for each sectionany help or pointers would be great,"['iphone', 'ios']" +163787,make classes final by default in eclipse is there a way to make classes final by default in eclipse ie on save actions or in the create new class dialog,['java'] +163819,redefine wait method in a java interface i would like to use waitint as the signature of a method in a fluent api used for the goal is to be able to construct sql queries like this exampleselect from t authorwhere rownum 1for update of first name last namewait 5the full for update clause syntax specification at least for oracle can be seen herefor update of schema table view column schema table view column nowait wait integer skip locked 01server1b28286img textfor update clausehtmwith jooq i really want to stay close to the sql syntax so i would like to be able to model the above sql clause with the jooq fluent api like thisresultrecord result createselect fromt author limit1 forupdate offirst name last name wait5 heres the issue fetchthe fetch method is used to render the apis underlying object as sql and run the sql statement against an oracle or any other database the above can be legally specified in an interface a type that models a step in the creation of a query using the fluent api public interface selectforupdatewaitstep extends selectfinalstep add a for update wait n clause to the query selectfinalstep waitint seconds i have some doubts about this though because there is a risk of collision with another methodpublic class object public final native void waitlong timeout throws interruptedexception thanks to methodoverloading int vs long arguments i can actually do this but i am afraid it might confuse my users and lead to mistakes so this would be wrong forupdate offirst name last name waitlong 5 this does not make sense fetch this does not compileso my questions arecan i somehow prevent callingaccessing objectwaitlong altoghether i do not think so because it is declared final but maybe someone knows a compilertrick or something elsedo you have a better idea for my api design apart from just renaming the method to something silly like dowaitint or waitint,"['java', 'sql']" +163820,how do you send null as a variable from php to sql i want to send a value of null to a column in mysql parenteventid null mysql queryupdate events set parenteventid parenteventidthe column keeps defaulting to 0 i have the column set to accept null and i can edit the cell with the null check boxi need to not set the default to null because it may effect code in other places,"['php', 'mysql']" +163829,c convert vector to vector what is a good clean way to convert a stdvectorint intvec to stdvectordouble doublevec or more generally to convert two vectors of convertible types,['c++'] +163852,rails select drop down for states i was wondering if maybe there was some already built in function for rails so that it would create a select drop down list with all the us states so i wouldnt have to enter it manually i searched online but i was unable to find any any suggestions on what to do so i do not have to manually enter all the states,"['ruby-on-rails', 'ruby']" +163861,how to printf long long i am doing a program that aproximate pi and i am trying to use long long but it is not workinghere is the codeincludestdiohincludemathhtypedef long long nummain num pi pi0 num e n scanfd n fore0 1e pi pow10e20e10 ifen0 printf15lld 116lldne 4pi printflldn4pi,['c'] +163863,https and ssl3 get server certificatecertificate verify failed ca is ok i am using xampp for development recently i upgraded my installation of xampp from an old version to 173 now when i curl https enabled sites i get the following exceptionfatal error uncaught exception requestcore exception with message curl resource resource id 55 curl error ssl certificate problem verify that the ca cert is ok details error14090086ssl routinesl3 get server certificatecertificate verify failed 60everyone suggest using some specific curl options from php code to fix this problem i think this should not be the way because i did not have any problem with my old version of xampp and happened only after installing the new version i need help to figure out what settings change in my php installation apache etc can fix this problem,['php'] +163866,case insensitive sorting using google guava current i am using the following 2 pieces of code in 2 different places to create a sorted immutable listreturn orderingnaturalimmutablesortedcopyiterableand return orderingusingtostringimmutablesortedcopymachineshowever this makes the ordering case sensitivehow do i use the guava apis to make a caseinsensitive sorted immutable list,['java'] +163893,rails mongrel with rvm fails to startup mongrel rails missingsourcefile i am having trouble with rvm and mongrel rails getting along so any help would be greatly appreciatedi can happily start my rails 2x application with scriptserver using the ruby gem mongreldetailswhich railsoptlocalbinrailswhich mongrel railsoptlocalbinmongrel railswhich gemoptlocalbingemhowever i have just added rvm with ruby 187 and installed all my gems including mongrel but when i try to start my rails app with scriptserver i now getno such file to load mongrel rails missingsourcefilerunning a few checks i findwhich mongrel railsusersdaniellewisrvmgemsruby187p334nacorebinmongrel railswhich railsusersdaniellewisrvmgemsruby187p334nacorebinrailswhich gemusersdaniellewisrvmrubiesruby187p334bingemprofile hasexport pathoptlocalbinoptlocalsbinusrlocalmysqlbinpath s homervmscriptsrvm homervmscriptsrvmi am using macportsany ideas on why scriptserver cannot find mongrel rails i can only guess it is to do with profile but i am not sure whatthanks,['ruby-on-rails'] +163897,camera focus thistances i am trying to read the focus thistance thistance of subject in a photo from an android camera i keep getting 0 for all focus thistances on my htc desire even when it correctly autofocuses heres the whole app only works on v233 and aboveimagecapturejava package testtestimport javaioioexceptionimport javaiooutputstreamimport javatextsimpledateformatimport androidappactivityimport androidcontentintentimport androidgraphicspixelformatimport androidhardwarecameraimport androidhardwarecameraautofocuscallbackimport androidhardwarecamerapicturecallbackimport androidneturiimport androidosbundleimport androidprovidermediastoreimagesmediaimport androidutillogimport androidviewkeyeventimport androidviewmenuitemimport androidviewsurfaceholderimport androidviewsurfaceviewthis class reads the focus thistancesclass imagefocuscallback implements autofocuscallback override public void onautofocusboolean success camera camera read focus thistances here cameraparameters parameters cameragetparameters float thistances new float3 if success only available with android 9 23 focus mode is always reported as auto but thistances do not appear to be updating always 01 12 infinity on my device it is 0 logdfocus mode parametersgetfocusmode parametersgetfocusthistancesthistances logdfocus thistance near floattostringthistances0 logdfocus thistance optimum floattostringthistances1 logdfocus thistance far floattostringthistances2 public class imagecapture extends activity implements surfaceholdercallback call auto focus here override public boolean onkeydownint keycode keyevent event if keycode keyeventkeycode dpad center imagefocuscallback autofocuscallback new imagefocuscallback autofocus is called here cameraautofocusautofocuscallback return true return false rest of the code private camera camera private boolean ispreviewrunning false private simpledateformat timestampformat new simpledateformatymmddhhmms private surfaceview surfaceview private surfaceholder surfaceholder private uri target mediaexternal content uri override public void oncreatebundle icicle superoncreateicicle logegetclassgetsimplename oncreate getwindowsetformatpixelformattranslucent setcontentviewrlayoutmain surfaceview surfaceview findviewbyidridsurface surfaceholder surfaceviewgetholder surfaceholderaddcallbackthis surfaceholdersettypesurfaceholdersurface type push buffers override public boolean oncreateoptionsmenuandroidviewmenu menu menuitem item menuadd0 0 0 goto gallery itemsetonmenuitemclicklistenernew menuitemonmenuitemclicklistener override public boolean onmenuitemclickmenuitem item intent intent new intentintentaction view target startactivityintent return true return true override protected void onrestoreinstancestatebundle savedinstancestate superonrestoreinstancestatesavedinstancestate camerapicturecallback mpicturecallbackraw new camerapicturecallback override public void onpicturetakenbyte data camera c logegetclassgetsimplename picture callback raw data camerastartpreview camerapicturecallback mpicturecallbackjpeg new camerapicturecallback override public void onpicturetakenbyte data camera c logegetclassgetsimplename picture callback jpeg datalength data camerashuttercallback mshuttercallback new camerashuttercallback override public void onshutter logegetclassgetsimplename shutter callback imagecapturecallback iccb null if keycode keyeventkeycode dpad center try string filename timestampformatformatnew date contentvalues values new contentvalues valuesputmediatitle filename valuesputmediadescription image capture by camera uri uri getcontentresolverinsertmediaexternal content uri values string filename timestampformatformatnew date iccb new imagecapturecallbackgetcontentresolveropenoutputstreamuri catch exception ex exprintstacktrace logegetclassgetsimplename exgetmessage ex if keycode keyeventkeycode back return superonkeydownkeycode event if keycode keyeventkeycode dpad center cameratakepicturemshuttercallback mpicturecallbackraw iccb return true return false override protected void onresume logegetclassgetsimplename onresume superonresume override protected void onsaveinstancestatebundle outstate superonsaveinstancestateoutstate override protected void onstop logegetclassgetsimplename onstop superonstop override public void surfacecreatedsurfaceholder holder logegetclassgetsimplename surfacecreated camera cameraopen cameraparameters parameters cameragetparameters float thistances new float3 logdfocus mode parametersgetfocusmode parametersgetfocusthistancesthistances logdfocus thistance 0 floattostringthistances0 logdfocus thistance 1 floattostringthistances1 logdfocus thistance 2 floattostringthistances2 override public void surfacechangedsurfaceholder holder int format int w int h logegetclassgetsimplename surfacechanged if ispreviewrunning camerastoppreview cameraparameters p cameragetparameters psetpreviewsizew h camerasetparametersp try camerasetpreviewthisplayholder catch ioexception e todo autogenerated catch block eprintstacktrace camerastartpreview ispreviewrunning true override public void surfacedestroyedsurfaceholder holder logegetclassgetsimplename surfacedestroyed camerastoppreview ispreviewrunning false camerarelease class imagecapturecallback implements picturecallback private outputstream filoutputstream public imagecapturecallbackoutputstream filoutputstream thisfiloutputstream filoutputstream override public void onpicturetakenbyte data camera camera try logvgetclassgetsimplename onpicturetaken data length datalength filoutputstreamwritedata filoutputstreamflush filoutputstreamclose catch exception ex exprintstacktrace mainxmllinearlayout xmlnsandroid androidlayout widthfill parent androidlayout heightfill parent androidorientationvertical surfaceview androidididsurface androidlayout widthfill parent androidlayout height10dip androidlayout weight1 surfaceviewlinearlayout androidmanifestxmlxml version10 encodingutf8manifest xmlnsandroid packagetesttest androidversioncode1 androidversionname10 usessdk androidminsdkversion10 usespermission androidnameandroidpermissioncamera usesfeature androidnameandroidhardwarecamera usesfeature androidnameandroidhardwarecameraautofocus application androidicondrawableicon androidlabelstringapp name activity androidnameimagecapture androidlabelstringapp name intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity applicationmanifestcould it be that that there is a bug in the device driver in the android source camerajava call native autofocus and native getparameters to read the thistances does anyone know where to get the source for the native calls,['android'] +163901,is akka suitable for systems with transient network coverage is akka suitable to use in a system where nodes are expected to be moving in and out of wifi coverage what aspects have to be considered eg what transport protocols are preferred,['java'] +163924,targeting the first class instance on a page with css i have a bunch of divs with the class of showreel and i would like the first one to have a higher margin value i am trying to achieve this using css advanced selectors but cannot seem to figure it outi know that you can target native elements like pfirstchildbut can i use it for div classes eg showreelfirstlooked around quite a bit but i just find information on native elements any help appreciated but would rather have a css solution vs a js solutionthanks,['css'] +163936,mysqls exception variable character set client cannot be set to the value of utf16 previously i use sql server 2005 as my website database and everything works wellnow i have changed to mysql server 55 database because it is open sourcei used navicat premium to transfer my data from sql server to mysql i use mysql workbench and navicat to manage my database problems come when i declare the connection to mysql database here is my code mysqlcommand cmdselect mysqlconnection conndb mysqldatareader mydtr string server localhost string database maindb string uid root string password abc123 string strcon server server database database uid uid password password string strselect select from announcement conndb new mysqlconnectionstrcon conndbopen cmdselect new mysqlcommandstrselect conndb mydtr cmdselectexecutereader rptannouncedatasource mydtr rptannouncedatabind mydtrclose conndbclosereference to mysqldata already set here i got this error message exception details mysqldatamysqlclientmysqlexception variable character set client cannot be set to the value of utf16 error message stated this error occurs during connectionopenwhen i keep on refreshing the error page i got another error sometime here is itexception details mysqldatamysqlclientmysqlexception expected end of data packet error message stated this error occurs during mydtr cmdselectexecutereaderi am new to mysql i don know what problem is this i guess this problem comes from databases setting or data not my source codeanyone knows the solution your help is greatly appreciated i been trying for 4 days but cannot solve,"['c#', 'asp.net', 'mysql']" +163956,keyvalue observing an nsmutableset in a plain class i have a nsmutableset property whenever objects are added to or removed from the set i want to perform some custom code i know i could write a few addobjecttosetlike methods to the class but i was wondering if there is a more elegant solution with direct kvo on the setas it turns out nsset will raise an exception when you try to add an observer to it not surprisingly for there is probably no named keypath to observe the documentation is pretty clear about the exception but i do not understand the suggested workaroundinstead of observing a set observe the unordered tomany relationship for which the set is the collection of related objectscould someone reiterate what this means and what a workaround would then look like,['objective-c'] +163961,rspec devise test helpers according to this from the devise wiki i should be able to use a login user helper method in my controller tests accordingly i have the following within the spec directoryspec helperrbdirrailsrootjoinspecsupportrbeach f require frspecconfigure do config configinclude devisetesthelpers type controller configextend controllermacros type controllerandsupportcontroller macrosrbmodule controllermacros def login user beforeeach do requestenvdevisemapping devisemappingsuser user factorycreateuser sign in user end endendhowever calling the helper does not workrequestssome specrbrequire spec helperdescribe get guidesedit do login user endcan someone point toward where i am going wrong the test suite works about from this i get a undefined local variable or method message so i guess the module is not being includedrails 307rspec 260devise 134backtrace,['ruby-on-rails'] +163972,sort a stdlist with myclassoperator i have a stdlistmyclass and in my class i have myclassoperatormyclass other definedi use the stdlistsort function but it does not change anything in that list maybe it just sorts the pointershow can i sort the actual items in that list,['c++'] +163977,how to deploy an orchard cms site including all settings and content from development environment i have been trying to build and deploy a website running on orchard cms i have previously downloaded orchard set up a development environment made a few modifications to the source added and modified a theme added some content and so forth i have been using the sql ce as database now i want to build and deploy the complete website i have built a deployment package by running the build script as described here it is easy to simply ftp the built package to the hosting server however when visiting the site i now get the install a new site procedure apparently the cms settings and content from my development environment have not been reflected in the deployment package thus i need to copy all the content and redo all the settings including creating all widgets etc again does anyone have any good ideas on how to publish an orchard site from a development to a production environment including the cms settings widget settings content etc all guides i have found on the web describe how to use webmatrix to deploy an orchard site to shared hosting or azure but all of those guides end up with having a clean orchard installation what i would like to achieve is to develop the site locally and then push the entire site to the hosting server,['.net'] +163980,how should retinanormal images be handled when loading from url i understand how to programmatically load images for my app from a url instead of packaging them within the app but how do i handle the 1x vs 2x issue i can serve both versions from the external source if need be but how do i handle that when setting the uiimage,['ios'] +164007,eclipse task tags in javascript blocks inside html files is it possible to enable task tags like todo and fixme for html files in eclipse i have already checked in eclipses settings and there is no task tags section for html files the issue is that i am not really using these task tags in the html itself they are in blocks of javascript inside the html files it would be nice to somehow capture them even though they reside in an html file,"['javascript', 'html']" +164020,how do i query using multiple conditions in indexeddb i recently thiscovered sadly that websql is no longer being supported for html5 and that indexeddb will be replacing it insteadi am wondering if there is any way to query or search through the entries of an indexeddb in a similar way to how i can use sql to search for an entry satisfying multiple conditionsi have seen that i can search through indexeddb using one condition with the keyrange however i cannot seem to find any way to search two or more columns of data without grabbing all the data from the database and doing it with for loopsi know this is a new feature that is barely implemented in the browsers but i have a project that i am starting and i am researching the different ways i could do itthank you,['javascript'] +164034,rails jquery ujs callbacks not triggering i am attempting to trigger the ajaxsuccess callback for a remote link i am on rails 308 and jqueryrails 1011 i ran the jquery generator to install the javascripts both jquery and jquery ujs are included in my defaults and i can verify they are being included on the pageheres my javascriptjqueryfunction deactivate bindajaxsuccess function alerthello bindajaxerror function alertgoodbye the link link to deactivate activate patient pathpatient id deactivate class button buttonred remote truethe activate actiondef activate patient patientfindparamsid patientdo not call patientdo not call if patientsave render nothing true else render status 500 nothing true endendthe ajax call seems to be working fine the action is triggered and i can see the changes in the database however the ajax callbacks are not being triggered i cannot get any of them to work i can get other events such as click to work perfectlyif i debug rails ujs in firebug i see that the following code gets ran from the rails ajax blocksuccess functiondata status xhr elementtriggerajaxsuccess data status xhri am stumped any ideas,['jquery'] +164042,how to view javadoc in eclipse i am using a third party library i have included into my project it contains classes for the application but no sources or javadoc as expected mouseover imported object shows no javadocnote this element neither has attached source nor attached javadoc and hence no javadoc could be foundafter googling for a bit i came across 3 versions of jarsappjarappsourcesjarappjavadocjarit appears and appjavadocjar contains nothing but html pages and appsources contans nothing but java files with javadoc commentswhat i didadded all 3 files to the list ofreferenced libraries afterrefreshing the project javadocstill does not showadditionally under properties forthe project i pointed javadoclocation path to unzipped content ofappjavadocjar validated okstill after having done all that my eclipse fails to thisplay javadocplease advisethank you,['java'] +164048,java simpledateformat in java how to parse a date string that contains a letter that does not represent a pattern20071102t1446030100string date 20071102t1446030100string format ymmddthhmmssznew simpledateformatformatparsedateexception in thread main javalangillegalargumentexception illegal pattern character t at javatextsimpledateformatcompilesimpledateformatjava769 at javatextsimpledateformatinitializesimpledateformatjava576 at javatextsimpledateformatsimpledateformatjava501 at javatextsimpledateformatsimpledateformatjava476,['java'] +164051,what are the usecases for islittleendian in bitconverter class i was so happy when i thiscovered islittleendian field in bitconverter i thought of course it should be there and i should be able to specify whatever endian i like well my happiness didnat last long spent some time till found out that there is no way to set the fieldthe field is readonly and it is only set to true in static constructorstatic bitconverter islittleendian trueit is funny that the field is actually used in the code for example toint32 method implementation looks like thisif islittleendian return numref0 numref1 8 numref2 0x10 numref3 0x18return numref0 0x18 numref1 0x10 numref2 8 numref3so seems like the toint32 is perfectly capable to handle both little and big endiansmy question is how come there is very useful piece of code that is already implemented and sitting there in the fcl but there is no way to use it unless you start messing with reflection of course is it just because some developers didnat meet the deadline and left the job halfdone even if so why the code is not available but the field isi hope there is a good reason for thisi want to make myself clear i do not need a solution on how to handle bigendian values i do have a solution the solution is actually shown in my question,"['c#', '.net']" +164052,web deploy in visual studio 2010 web management service is missing i am setting up a new server on windows 2008 x64 with iis 75 i have installed web deploy 21 from the web platform installerbut the server is missing the web management service and as a result any web deploy fails with this messageerror 1 web deployment task failedcould not complete the request to remote agent url httpsurl8172msdeployaxdsitedefault web sitethis error indicates that you cannot connect to the server make sure the service url is correct firewall and network settings on this computer and on the server computer are configured properly and the appropriate services have been started on the servererror detailsunable to connect to the remote serverno connection could be made because the target machine actively refused it i checked the services and found the necessary service is missingthe web deployment agent service is installed this is the iis6 service but not the web management service the iis7 deploy servicehow can i fix this does the web platform installer not work for web deploy,['c#'] +164054,updating an ongoing notification quietly i have a service which connects to other devices wirelessly when the service is enabled i have an ongoing notification which states it is enabledafter the service is enabled the user then connects to another device at this point i would like to update my ongoing notification to state the name of the device which has been connected to this is easy enough to do by calling startforegroundongoing notification notification again with the updated information however this flashes the notification on the bar each time it is called what i would really like is the notification to quietly update in the background without flashing on the notification bar so the user does not know the difference until he or she opens the notification area to lookis there someway to update the notification without calling startforegroundthis behavior only occurs in honeycomb gingerbread devices and i assume froyo etc behave the desired way,['android'] +164060,nslog on the device is that a problem or must i remove that i have read this post what happens to nslog info when running on a devicebut wondering if nslog is a problem when thistributing the app such as filling up the memory or something i am only interested to see it when i test the consistency of my input data to the databasethe reason is that i have nslog to control when i load the data into my database in the simulator i could remove it when i upload but it would be good if i do not need to,"['iphone', 'objective-c']" +164096,high performance pdf viewer for web i need a high performance solution for thisplaying pdf files 100250mb per file scanned documents on web pages without any plugin icepdf does not have the needed options like cashing autosetting quality thumbnails prepairment moreover it has only basic web ui components best match for solutions with javascript on clientside and java on serverside but other techologies are welcome too,"['java', 'javascript']" +164112,using google docs and google spreadsheet apis for android i am planning on using the google documents list and google documents spreadsheet apis for uploading a database from my app to a spreadsheet online and then editing it i just wanted to know if these apis would be the right approach for using google docs as an online storage space for the data that i have collected in my app i was hoping that i could just get feedback from some of you who might have experience with this the links for both apis are listed belowthanks in advance,['android'] +164118,about ambient light sensor in iphone thanks in advancei got the information about the iphone sensors from but i did not get information about how to use ambient sensor in iphone,['iphone'] +164131,uitableview reloaddata automatically calls resignfirstresponder i have this uitableview with custom cells that can get only predefined values therefore i use a uipickerview as their inputview all is jolly good until i edit a field and need to show its updated valuein order to make things clearer and easier to maintain i made delegates and data sources as separate classes and use notifications to make them interact with the tableview so after a value has been chosen from the uipickerview the tableviews data source gets notified and in turn notifies the main viewcontroller that holds a reference to the tableview from there i call tableview reloaddataand everything seems to work except that the uipickerview thisappears i think because the cells are regenerated and somewhere some resignfirstresponder is called or something like thatis there any other way to make the tableview updating its values without having to implement a custom method somewhere that does it which would be quite ugly,['ios'] +164135,how to run a java class with a jar in the classpath so i can do this very welljava mypackagemyclassif mypackagemyclassclass exists i can also happily do thisjava cp myjarjar mypackagemyclassif the class file exists in the appropriate part of the jar easy stuff but i cannot for the life of me manage to do something like thisjava cp utilitiesjar mypackagemyclasswhere mypackagemyclassclass exists and where utilitiesjar exists not containing myclass of courseam i about to feel stupid,['java'] +164151,net microbenchmarking api i am looking for a library for doing microbenchmarking of unit tests to monitor how code changes impact performance over time that is i would like the library to output results to eg xml to preserve history it must be able to do this without any human assistant ie run continously on our build server without too much hasslethe library should be very simple and work on existing unit tests preferably i want to mark a test with a benchmark attribute on the test i want to test or using a usingblock egusing var benchmarker new benchmarker code to profile thispose stores measurementsnote that i am not interrested in profiling tools as i programatically want to specify what parts of the code i want to profile the library should be actively maintainedi have had a look at jon skeets solution but found it to be a bit too intrusive and ntime which has been dead for a few years,"['c#', '.net']" +164157,android detect if user touches and drags out of button region in android how can we detect if a user touches on button and drags out of region of this button,['android'] +164160,send public keygenerated as seckeyref in iphone to serverin java i need to send my public key that has been generated by seckeygeneratepair as a seckeyref objectnow to send this i need this keyref object to be in a string format how do i convert the seckeyref object to nsstring object,['iphone'] +164164,generics in c how can i create an instance of a variable type with an argument i have got a generics class where i want to instantiate an object with the generic type i want to use an argument for the constructor of the typemy codepublic class genericclasst where t some base class new public static t somefunctionstring s if stringisnulloremptys return new tsome param i get an error on thenew tsome paramt cannot provide arguments when creating an instance of a variable typeany ideas how can i do this,['c#'] +164176,how to do a webkit css endless rotationanimation i want to make a rotation of my loading icon by cssi have an icon and the following codestyletest width 32px height 32px background urlrefreshpngrotating webkittransform rotate360deg webkittransitionduration 1s webkittransitiondelay now webkitanimationtimingfunction linear webkitanimationiterationcount infinitestylediv idtest classrotatingdivbut it does not work how can the icon be rotated using css,['css'] +164178,rails not decoding json from jquery correctly array becoming a hash with integer keys every time i want to post an array of json objects with jquery to rails i have this problemif i stringify the array i can see that jquery is doing its work correctlyshared itemsentity id253position1entity id823position2but if i just send the array it as the data of the ajax call i getshared items0entity id253 position1 1entity id823 position2whereas if i just send a plain array it worksshared itemsentity 253why is rails changing the array to that strange hash the only reason that comes to mind is that rails cannot correctly understand the contents because there is no type here is there a way to set it in the jquery callprocessing by sharedlistscontrollercreate as thank youupdatei am sending the data as an array not a string and the array is created dynamically using the push function tried with post and ajax same result,"['jquery', 'ruby-on-rails']" +164187,nodejs socketio simple clientserver example not working iam using nodejs v048 and the latest version of socketio fromnpm install socketioon ubuntulinux mars 26388generic 42ubuntu smp mon apr 11 033150 utc 2011 i686 i686 i386 gnulinuxthe following code unfortunately does not produce any output wheter on client nor on server sidedoes anybody have a clueserversidevar http requirehttp io requiresocketiofs requirefssys requiresysrespcont fsreadfilesynctestclientjsserver httpcreateserverfunctionreq res reswritehead200 contenttype texthtml resendrespcontserverlisten8082var socket iolistenserver socketonconnection functionclient sysputsnew client is here clientsendhello world clientonmessage functionmsg sysputsclient has sentmsg clientonthisconnect function sysputsclient has thisconnected clientsidehtmlbodyscript typetextjavascript srchttplocalhost8082socketiosocketiojsscriptscript var socket new iosocketnullport8082remembertransporttruetimeout1500 socketconnect socketonconnect function consolelogconnected to server socketsendhi server socketonmessage function consolelogreceived a message socketonthisconnect function consolelogthisconnected from server script bodyhtmlthe output from nodejs not the sysputs calls isinfo socketio started debug served static socketiojs debug client authorized info handshake authorized info handshaken b61a5c2751c1c8c8493db4b79d19e779,['javascript'] +164196,what does the carries dependency attribute mean can someone explain it in a language that mere mortals understand,['c++'] +164197,mongodb how to check for existence i would like to know how can i check the existence of an object with mongodb and ci have found a way to do it but i had to use linq thanks to any method but i would like to know if it is possible to do it without linq databasegetcollectionapplicationviewmodelapplicationsfindqueryeqname applicationnameanythanks guys,"['c#', '.net']" +164203,why are antlr3 c parser methods private i am building a parser in antlr which compiles to a working java target when i retarget for c2 it produces a parser in which all of the parse methods are private but marked with a grammarrulerulename attributewhat is the approved means to actually invoke the parseri am using antlr 33 nov 30 2010 124530thanksandy,['c#'] +164204,how to convert character encoding from cp932 to utf8 in nodejs javascript using the nodejsiconv module or other solution i am attempting to convert a string from cp932 aka windows31j to utf8 in javascript basically i am crawling a site that ignores the utf8 request in the request header and returns cp932 encoded text even though the html metatag indicates that the page is shift jisanyway i have the entire page stored in a string variable called html from there i am attempting to convert it to utf8 using this codevar iconv requireiconviconvvar conv new iconvcp932 utf8translitignorevar mybuffer new bufferhtmllength 3mybufferwritehtml 0 utf8var utf8html convconvertmybuffertostringutf8the result is not what it is supposed to be for example the string c ea c aa coa aa aa3a 3aa comes out as i12i1212i12i1212i12i1212ei12i1212i34ai12i1212i12i1212i12i1212i12i1212i12i1212 i12i1212ti12i1212i12i1212i12i1212si12i1212i12i1212i12i1212i12i1212i12i1212zi12i1212ei12i1212i12i1212 i12i1212i34a i12i1212i12i1212ri12i1212 i12i1212i12i1212i12i1212zi12i1212ei12i1212i12i1212i12i1212i12i1212if i remove translitignore which should cause it to return similar characters for missing characters and failing that omit nontranscodeable characters i get this errorerror eilseq illegal character sequencei am open to using any solution that can be implemented in nodejs but my search results have not yielded many options outside of the nodejsiconv modulenodejsiconv ref thanksedit 24062011i have gone ahead and implemented a solution in java however i would still be interested in a javascript solution to this problem if somebody can solve it,['javascript'] +164221,why do both ways of accesing module functions exist in ruby module a def selffunc puts func endend afuncfunc afuncfuncwhy do both and exist why not only,['ruby'] +164241,sql server agent jobs how to execute a job step without executing the entire job i have a sql server agent job that previously had two steps today i have had to integrate a third step and soon i will need to integrate a fourthi want to be sure that the step will execute properly but i do not want to execute the entire jobthe first two steps take quite a bit of time to execute and during the day they hog a significant amount of the sql resources that my users needis there a way that i can execute a job step and not an entire job processwithin ssms if i rightclick on the job there is an option that states start job at step except when i try that options it brings up a dialog that seems to imply that the entire job has been started what can i do to test one step within a jobthanks in advance,['sql'] +164264,android proper way to use onbackpressed i wrote a piece of code that will give the user a prompt asking them to press back again if they would like to exit i currently have my code working to an extent but i know it is written poorly and i assume there is a better way to do it any suggestions would be helpfulcodepublic void onbackpressed backpress backpress 1 toastmaketextgetapplicationcontext press back again to exit toastlength shortshow if backpress1 thisfinish,['android'] +164274,is the comma in a variable list a sequence point in the following type of code is there a sequence point between each variable construction or is the result undefinedint a 0int b a c ai was not able to find in the standard a specific reference to a sequence point here does that mean it is undefined or just that i failed in my search the completion of an expression is a sequence point but does the above initialization also count,['c++'] +164290,missing copypaste menu in uitextfielduiwebview i am having a problem and i cannot find a workaround for iti have a view with a uiwebview implementation and a uitextfieldon both when i tap i do not get the copypaste menu to appearthe uiwebview has text in it text only and i can select either a word or a paragraph or make the magnification glass appear and manually select the text i wanton the other hand uitextfield can take input and works as intended except for the copypaste functionsnothing is subclassed i need only the default implementation of ios for the copypaste functionsthis problem is not in a single view i have another uiwebview with the same problem elsewhere so i think this is a global problemi have done all the obvious import uikit and foundation frameworks assign properties releasing etc but again i am stuck on thiswhat might interactinterfere with such a simple functionality thisabling itmoreover always under the simplest implementation what else is needed for this to work any framework i am missing any property etcsuch a simple thing and i am stuck with itif anyone has any idea its much appreciated edit the problem is not caused by my code in any view or classi have added a new view the application is tabbar based with only a uitextfield and a uitextview with the default lorem ipsum text on the textview i can also select text but no menu to copypasteselectselect allthis also happens in the textfield empty where no paste menu appears i copy some text from another app ex safari or notesit seems the problem is somewhere else affecting universally the app in all viewsi have removed frameworks references and put them back but nothing happenedi am still trying to figure from where this comes,"['iphone', 'ios']" +164304,jframe repaint issues java i want to be able to draw using javas paint on a jframe when i click the jframe anywhere for now i want the jframe to be repainted with the coordinates of the click similar to this java applet currently workingeverything is drawn initially and the jframe is properly thisplayednot workingjframe does not repaint and update even when repaint is declaredhere is my code please be as stringent as possible with it i would like to improve my java programming technique so if you have time that is point out every aspect i could improve onany help would be very much appreciatedimport javaawtimport javaawteventimport javaxswingclass areafortext extends jpanel implements mouselistener int xpos int yposjframe myjframe new jframepublic void setjframe myjframesetsize300 150 myjframesettitlebigger text myjframesetdefaultcloseoperationjframeexit on close myjframesetvisibletrue myjframegetcontentpaneaddnew areafortext myjframeaddmouselistenernew areafortextpublic void mouseclickedmouseevent me save the coordinates of the click lke this xpos mouseinfogetpointerinfogetlocationx ypos mouseinfogetpointerinfogetlocationy systemoutprintclick x xpos y ypos myjframeinvalidate repaint revalidatepublic void mouseenteredmouseevent epublic void mousereleasedmouseevent e public void mousepressedmouseevent e public void mouseexitedmouseevent e public void paintgraphics g systemoutprinthello gdrawstringhello world 30 80 gfillrect20202020 gdrawstringxposyposxposypos class enlargetext public static void mainstring args areafortext test new areafortext testsetjframe,['java'] +164309,c dropdownlist change event aspdropdownlist runatserver idmylistdropdown cssclasstext onselectedindexchangedmylistdropdown change there is the aspx aboveprotected void mylistdropdown changeobject sender eventargs e stuff that never gets hit i put a break point on the mylistdropdown method but it never gets hit any suggestions,['c#'] +164318,undefined local variable or method acts as gmappable i attempted to install the gmaps4rails gemi added gem gmaps4rails to my gemfile and ran bundle install it said that my bundle installed successfully i can find using gmaps4rails 088 with gem list i added the specified columns to my users table with rake dbmigrate and added acts as gmappable and the gmaps4rails address method to my user modelvisiting pages that involve the user model gives me undefined local variable or method acts as gmappableerroris there something that i am missingfor greater context the code i am using is from the rails 3 tutorialos x 1066ruby 187rails 307passenger 307,['ruby-on-rails'] +164336,how to create a trie in c does anyone know where i can find an example of how to construct a trie in c i am trying to take a dictionarylist of words and create a trie with it,['c#'] +164349,has anyone been able to get attachment fu to work with rails 3 i have a rails application that is being upgraded from rails 235 to rails 3 it uses attachment fu for file uploads were trying to do this conversion without making db changes so i would like to avoid changing to paperclip or carrierwave at this time has anyone succeeded in using attachment fu with rails 3 and ruby 192 were using the most recent version of attachment fu that claims to be ok for rails 3 and ruby 192 but getting typeerror cannot convert nil into integer on any forms that include a file uploadall the answers to previous questions seem to be just switch to paperclip or carrierwave as inattachment fu or paperclip for rails3ortypeerror cant convert nil into integerthanks,"['ruby-on-rails', 'ruby']" +164361,serializing dictionaries with javascriptserializer apparently idictionarystringobject is serialized as an array of keyvaluepair objects eg keyfoo valuebar is is possible to serialize it as an object instead eg foobar,['c#'] +164367,jquery cookie plugin multiple values i am using popular jquery cookie plugin wonder how to set and read a cookie with multiple values or maybe it is possible to addremove values for that cookie cookiemytestcookie email expires 10 i want to add username to the same cookieupdate just an example in net storing multiple values in cookies,['jquery'] +164381,android format timestamp in listview with cursor adapter i am using a simplecursoradapter to populate an android listview and was wondering how i should go about getting all of the timestamps i get from a database each in date date into human readable dates maybe using simpledateformatcursor programdatecursor mdbadapterloadprogramdatesstartmanagingcursorprogramdatecursorstring from new string date date int to new int ridtext1 simplecursoradapter programdates new simplecursoradapterthis rlayoutprogram date programdatecursor from tosetlistadapterprogramdatesi have not done much work with java so is there a better way any way to do this other than storing the preformatted dates in the database before hand that is,"['java', 'android']" +164383,how to thisable highlight subviews message for uiviewuiviewcontroller in ios sdk i want to use the default highlight on a uitableviewcell when it is tapped however i do not want custom subviews and their subviews to receive the message to update their highlighted states and therefore thisrupt the backgroundcolor property editby subview i mean any uiview subclass not just uitableviewcellsperhaps this hypothetical situation will better articulate what i am looking for i have one uitableviewcell call it c i then add one uiview call it v as a subview of c when i tap c i want c to become highlighted standard blue background with white font color but i do not want v to become highlighted how do i make this happen,['ios'] +164384,java thread dump summarisation tool i sometimes have to look at thread dumps from a tomcat server however this is a very slow process as my application uses thread pools with a couple of hundred threads most of the thread dumps i look at include the same stack trace for many of the threads as they are idle waiting for workare there any tools which would parse a thread dump and only show me the unique stack traces along with a count of the number of threads in each state this would allow me to quickly ignore the tens or hundreds of threads which are waiting in a common location for worki have tried the thread dump analyzer but this does not do any summarisation of common stack traces,['java'] +164385,protect the source code on delivery to client i have recently learnt that the company that will handle the installation of one of our core products have previously tried to reverse engineer suppliers work in evil purposes due to this i want to learn more about how to protect our work and so far i have thought of the following1 obviously to use an obfuscator question is which one2 encrypt config files as much as possible especially endpoint information3 move as much of the logic as possible to the web service4 use ssl for data transfersthe project is written in cwpf and connects to a set of web services hosted on a iis 7 we package our deliveries with wix does wix have anything to provide i understand that in the end all binaries can be hacked and that as a minor company we should probably concentrate on writing code instead of protecting it but these minor steps will at lease make it harder what else can be done does the community have any more advices regarding this links to internalexternal resources would be much appreciated,['c#'] +164386,createthisplay image from dataurl is it possible to create and thisplay a picture file from dataurl received by postsomething likeimgstr postimgdata dataimagepngbase64 etc it is always pngecho base64 decodeimgstr idk what this really doesi cannot use img tag to thisplay it it needs to act like a normal image file,['php'] +164402,javascript send json object with ajax is this possiblexmlhttpsend test 1 test2 2maybe with a header with content type applicationjsonxmlhttpsetrequestheadercontenttype applicationjsonotherwise i can usexmlhttpsetrequestheadercontenttype applicationxwformurlencodedand then jsonstringify the json object and send it in a parameter but it would be cool to send it in this way if it is possible,['javascript'] +164411,jquery ajax and ssl in our site certain pages use ssl most pages however do not as they need to be crawled by web botsit pretty much boils down to any page where the user is logged in with a few exceptions is under sslbut the user first has to login from a non https page the login form is a form that drops from the top of the screen on any pagesohow can i force the requests over ajax to use sslis this even secure,['jquery'] +164415,replacing the auto link method in ruby on rails 31 i am using ruby on rails 307 and i know that in the 31 version there would not be the auto link method anymore see the actionpacklibaction viewhelperstext helperrb for ror 31 is there another way to have similar functions as the old auto link method that is how can i replace that useful method in ruby on rails 31btw why will the auto link method will be removed,"['ruby-on-rails', 'ruby']" +164459,how does this stop mass assignment i wanted to start using attr accessible with my models to stop the problem with mass assignment i understand how it works and have researched as much as i couldwhat i do not understand is the difference between using update attributesparamsmy form or createparamsmy form and setting the fields one by one are not both just as vulnerablewhat is the difference between not having attr accessible and doing thismodel object modelobjectnewmodel objectcreateparamsmodel object paramsand having attr accessible and doing thismodel object modelobjectnewmodel objectfield1 paramsmodel object paramsfield1model objectfield2 paramsmodel object paramsfield2model objectfield3 paramsmodel object paramsfield3model objectsaveare not both these methods of creating the record just as vulnerable the hackercracker could send a url to both these methods and both would do just the same rightor does using attr accessible and updating the fields onebyone do something different or somehow become saferthere is where all these methods i am finding of using attr accessible do not make any sense to me it seems to be doing the same thing two different ways what am i missingthanks,['ruby-on-rails'] +164463,thisplay 2 weeks in jquery fullcalendar been looking around for a way to thisplay only the current week and the next week in the month view for fullcalendar so far it looks like it was suggested as a feature for an upcoming version but in the meantime has anyone been able to hack it inupdatethanks to doomsdays suggestion i was able to create a custom view that shows 2 weeks starting on the current week you are changing the visible start date to todays date and changing the row count to 2function twoweeksviewelement calendar var t this exportstrender render importsbasicviewcallt element calendar monthvar opt toptvar renderbasic trenderbasicvar formatdate calendarformatdatefunction renderdate delta if delta addmonthsdate delta datesetdate1 var start clonedatedate true startsetdate1 var end addmonthsclonedatestart 1 var visstart clonedatestart var visstart date var visend clonedateend var firstday optfirstday var nwe optweekends 0 1 if nwe skipweekendvisstart skipweekendvisend 1 true adaysvisstart visstartgetday mathmaxfirstday nwe 7 7 adaysvisend 7 visendgetday mathmaxfirstday nwe 7 var rowcnt mathroundvisend visstart day ms 7 if optweekmode fixed adaysvisend 6 rowcnt 7 rowcnt 6 rowcnt 2 ttitle formatdatestart opttitleformat tstart start tend end tvisstart visstart tvisend visend renderbasic6 rowcnt nwe 5 7 true,['jquery'] +164469,in rails 31 is it really impossible to avoid including duplicate copies of stylesheets i am running into an upsetting issue when trying to share variables and mixins across sass stylesheets if i use import to include a global stylesheeta a one which includes global colors mixins etc a it gets included again when rails combines all stylesheets referenced in the manifest filealternatively if my manifest file does not include the global stylesheet but multiple files in the manifest import it the global stylesheet will still be included more than once gahhow can you get around this does sass have secret inclusion guards am i doing something terribly wrong,['ruby-on-rails'] +164471,what is the syntax for new line in objectivec can anyone tell me what is the symbol used for new linein the c language we use n for new line what do we use in objectivecis it same,"['iphone', 'objective-c']" +164477,how can i read linebyline using boost iostreams interface for gzip files i managed to integrate the boost iostream apis for reading zipped files i followed the documentation in boost page and have the following code sofar stdstringstream outstr ifstream filefilegz ios basein ios basebinary try boostiostreamsfiltering istreambuf in inpushboostiostreamsgzip decompressor inpushfile boostiostreamscopyin outstr catchconst boostiostreamsgzip error exception int error exceptionerror if error boostiostreamsgzipzlib error check for all error code the code works fine so please ignore any typos and errors above looks like the above code will read the complete the file and store it in the memory while creating the filtering istreambuf is that true from my investigation it looks so to me if the file is read into memory this code can be an issue for large files which is what i am dealing with my current code reads the gzipped using gzgets api from zlib line by line is there a way to do line by line reading using boost apis,['c++'] +164490,decent way to thisallow virtual functions due to placement new usage what would be a decent approach to check at compileruntime that a particular structclass does not have any virtual functions this check is required in order to ensure the proper byte alignment when doing placement newhaving so much as a single virtual function will shift the entire data by a vtable pointer size which will completely mess things up in conjunction with the placement new operatorsome more details i need something that works across all major compiler and platforms eg vs2005 vc10 gcc 45 and sun studio 121 on top of windows linux and solarissomething that is guaranteed to work with the following scenario should sufficestruct a char c void m struct b a void m should someone decide to make this changestruct a char c virtual void m struct b a void m it would be great to see a compiletime error that says struct a must not contain virtual functions,['c++'] +164491,basic avassetreader problems reading video samples i am looking to read video samples via avassetreader and i am running into all kinds of road blocks can some one post code that sets up an avasset from a video named moviem4v from the application bundle and uses avassetreader to loop through the video frames cmsamplebufferrefheres some of the code i am using now that does not worknsstring path nsbundle mainbundle resourcepath stringbyappendingpathcomponentmoviem4vavasset avasset avurlasset alloc initwithurlnsurl urlwithstringpath optionsnilnserror error nilavassetreader reader avassetreader alloc initwithassetavasset errorerror crashing right around here i have gotten avassetreader to not crash upon initialization by grabbing an asset from the alassetslibrary but it says it has 0 tracksnsarray videotracks avasset trackswithmediatypeavmediatypevideo avassettrack videotrack videotracks objectatindex0nsdictionary options nsdictionary dictionarywithobjectnsnumber numberwithintkcvpixelformattype 32bgra forkeyidkcvpixelbufferpixelformattypekeyavassetreadertrackoutput asset reader output avassetreadertrackoutput alloc initwithtrackvideotrack outputsettingsoptionsreader addoutputasset reader outputreader startreadingcmsamplebufferref bufferwhile reader statusavassetreaderstatusreading buffer asset reader output copynextsamplebuffer nslogreading,"['iphone', 'objective-c', 'ios']" +164499,how to thiscover which test unit checks which lines of code i was fooling around the nuint hoping to thiscover a way to realize which line of code passes in which testimagine i have a method for which i have 3 tests is there any way to find out which test checks which line of codehaving used ncover i know you can find out which lines have been tested and which have not however you really cannot see which unit checked that codeit can be really useful when dealing with tons of tests,['c#'] +164516,php pdo vs normal mysqli speed performance benchmark i m working on a project about social networking website where speed optimization is very critical is pdo is faster i am thinking to switch to pdo is it recommended for use pdo for such a site,['php'] +164519,is there a tutorial on how to implement google authenticator in net apps i am looking for a tutorial on how to use google authenticator in netapps does this exist and if so where can i find iti understand that this can be used to add twofactorauthentication to your own apps,['.net'] +164528,how to create an email account in cpanel via php how do i create email accounts with php using the xmlapiphp library from cpanelnote i need to create more than 10 email accounts and want to know if this is possiblethanks,['php'] +164549,how to get indices of a sorted array in python i have a numerical listmylist 1 2 3 100 5now if i sort this list to obtain 1 2 3 5 100 what i want is the indices of the elements from the original list in the sorted order ie 0 1 2 4 3 ala matlabs sort function that returns both values and indices,['python'] +164555,css create white glow around image how can i create a white glow as the border of an unknown size image,['css'] +164600,nesting enums in java i want to nest some enums the object i am representing are flags with a type and a value there are a thiscrete number of types and each type has a thistinct set of possible valuesso if type a can have values 1 2 or 3 and type b can have values 456 i would like to be able to do things likeflag f flaga1fgettype returns afgetvalue returns 1flag f2 flaga4 syntax errori am driving myself crazy trying to nest enums within enums is what i am trying possible do i need to ditch enums altogether and handcraft a static class with static membersmy best effort so far ispublic class flag enum a extends flag oneone twotwo threethree private astring value flagtype a flagvalue value private static string type private static string valuebut if i doflag f flagaonethe types are incompatible,['java'] +164603,how to sort a list by a integer stored in the struct my list holds i need to sort a highscore file for my game i have writteneach highscore has a name score and date variable i store each one in a listhere is the struct that holds each highscores datastruct highscore public string name public int score public string date public string dataasstring return name scoretostring date so how would i sort a list of type highscores by the score variable of each object in the listany help is appreciated d,['c#'] +164673,opera mini like software as open source i am looking for anyrelated opensource project that render webpages at server side and deliver as images to client mobiles just like opera mini and skyfire so far google does not give me a clue as i cannot figure it out which term to use could you guys give me a cluethanks,['html'] +164676,regular expression pattern to match url with or without httpw i am not very good at regular expressions at alli have been using a lot of framework code to date but i am unable to find one that is able to match a url like but also is able to catch something like wexamplecometcetc and examplecometcetcany help would be great thanks guys,['php'] +164688,what data structure thiscards the oldest item when a new one is added i have been trying to remember this and it is driving me crazybasically it is like a small array of let us say size five and as you add items it starts to fill up when it is full and you add a new item the oldest one first added is removedyou can access the values by something like variable0 variable1 etc where variable 0 is the oldest value and variable 4 the newestany ideas on what this is called is it a standard c type or did i just see it somewhere as a custom class,['c++'] +164693,html5 file api security error while reading a file problem solved read commentthe third problem i have with the html5 file apii still use chrome 12 on mac os x snow leopard and i am still trying to read files with the html5 file api but filehandlererror get called because a security err occurresthe file i try to read is a regular txt file from my desktop but it neither works with other files although i can open them with regular applicationsfunction filehandlerfiles action consolelogfilehandler called thisfiles files thisreader new filereader thisaction action thishandle function consolelogfilehandlerhandle called for var i 0 i thisfileslength i thisreaderreadasdataurlfilesi thisupload function consolelogfilehandlerupload called consolelogthisreader data content thisreaderresult consolelogdata thiserror function consolelogan error occurred while reading the file consolelogthisreadererror thisreaderonload thisuploadbindthis thisreaderonerror thiserrorbindthisthe code generates the following console output,['javascript'] +164697,rails using form for multiple times dom ids i would like to use the form for helper multiple times for the same model in the same page but the input fields use the same id attribute in the html so clicking on the label of a field in another form will select the same input in the first formis there a solution besides settings all attributes manually via for title itemid and id title itemidusing rails 309,['ruby-on-rails'] +164701,ios is is possible to make a uinavigationbar taller and push the other views down the screen is there a way to make the content area of an iphone app aware of a larger navigation barsimilar to these questions ios adding a fixed image just below the navigation barios positioning navigation bar buttons within custom navigation bari have managed to use the 1st questions sample code to add a category on uinavigationbar and change its height and added a subview where i need it but i cannot see a way to cause the uitableview or indeed any content views to take its height into considerationthe colors are only to make the different views thistinguishable,"['iphone', 'ios']" +164717,xcode4 and core data how to enable sql debugging i am working on a universal ios app and i would like to see the raw sql in the logs when i am debugging there is some info in this blog post about how to enable raw sql logging for ios core data development the given example is for xcode 3 and it is just not clear to me how to enable this in xcode 4i have tried product edit scheme and added comapplecoredatasqldebug 1 to arguments passed on launch but i am still not seeing any output in the logs not sure if i am looking in the wrong place or just passing the arguments incorrectly,"['sql', 'ios']" +164718,how to fix an application that has a problem with decimal separator this post is about c and net but some info is valuable for other techonolgiessince i can remember i have been having problems with apps or games that crash because of a different style of parsing decimal numbers it happens very often from cad apps libraries to web pages i am not sure whether it is ignorance or lack of knowledge but it is really annoyingwhats the problem here is a wiki article about it but it shorthere is a map that shows what kind of decimal separator decimal mark is used around the worlddecimal marksperiod a blue comma a greennonwestarabic numerals a redunknown a greymost of the europe south america write 1 0 0 or 10 sometimes 10 as opposite to imperial marked as blue write 10let me just give you a few from all problems that i encoutered last monthnumber on webpages hard to read let us take one of the most viewed yt videosit shows me 390159851 number above one million are very hard to read whats the order of magnitude is it 39 mln or 390mirosoft xna for windows phone 7 example there is a very neat class that parse xml file to produce xna animation summary loads animation setting from xml file summaryprivate void loadanimiationfromxml xdocument doc xdocumentloadcontenttexturesanimationsdefinitionxml xname name xnamegetdefinition var definitions docdocumentdescendantsname if animationdefinitionattributespeed null animationsetframeinvtervaltimespanfrommilliseconds doubleparseanimationdefinitionattributespeedvalue doubleparse throws an exception one simple soultion is to use xmlconverttodouble or parse with invariantculturenet app that use csv files to store input vector as csv also throwsanother net app that has some parsing inside the class throwsso how can we fix thisfix the bug in code possible only with avaible source code and tediouschange the data cvs xml etc even with possible not very happy with mutating the datachange the os default decimal separator not gonna happenis there any other way to slove this can i make the app be invariant like starting the app in a different environmentps i would like to run the app but i do not have the code,"['c#', '.net']" +164723,how to flatten nested objects with linq expression i am trying to flatten nested objects like thispublic class book public string name get set public ilistchapter chapters get set public class chapter public string name get set public ilistpage pages get set public class page public string name get set let me make an example this is the data i havebook pro linq chapter 1 hello linq page 1 page 2 page 3 chapter 2 c language enhancements page 4 the result i am looking for is the following flat listpro linq hello linq page 1pro linq hello linq page 2pro linq hello linq page 3pro linq c language enhancements page 4how could i accomplish this i could do it with a select new but i have been told that a selectmany would be enough,"['c#', '.net']" +164740,how can i make clickable links like the twitter and facebook app possible duplicatehow to make an expression clickable on ios on twitter and facebook usernames like and hashtags like are clickable and do something native within the appwhat is the best way to implement something like this it would be nice if there was a drop in replacement for a uilabel for example,"['iphone', 'objective-c']" +164741,xcode 4 strip all symbols error when archiving i have some static libraries in my xcode 4 ios 43 sdk project when i archive the project i am getting the following error below when the tool attempts to strip symbols i have the same settings i used for xcode 32 i have noticed if i change the strip style option in build settings from all symbols to debugging symbols then the archive is built successfully command developerplatformsiphoneosplatformdeveloperusrbinstrip failed with exit code 1as mentioned above i have not changed this setting from 32 so am wondering how to fix this issuethanks,['iphone'] +164754,how to get or compute the widthheight of an inflated view how do i compute the width and height of an inflated view if the parent is a popupwindow not a viewgroup i cannot use layoutinflatorinflateint resid viewgroup parent attachtoroot boolean because popupwindow is not a viewgroup so i use layoutinflatorinflateint resid instead but after that i getwidth and getheight return zero i need to resize the popupwindow to fit the view but cannot do so until the view has a parent do i have a chickenandegg problemby the way the view is a subclass of relativeview so calculating it manually is essentially out of the questionthanks in advancebarry,['android'] +164758,high memory usage with consolewriteline public static void main int size 250 var a new intsize for int i 0 i size i consolewriteline0 aiwhen i tested the above code with clrprofiler it told me that the code allocates roughly 40 mb around 20 mb is allocated to string 9 mb to char 5 mb to stringbuilder and 3 mb to int32public static void main int size 250 var a new intsize for int i 0 i size i consolewriteline0 this one allocates around 5 mb 4 mb is allocated to char the only thing i get is that array a should require 1 mb 250 4why is there such a massive difference why are all those objects required for the first code and how do i reduce the memory allocation,['c#'] +164775,iterator for second to last element in a list i currently have the following for loopforliststringiterator jtitbegin jtitend1 jti have a list of strings which is in a larger list listliststring i want to loop through the contents of the innerlist until i get to the 2nd to last element this is because i have already processed the contents of the final element and have no reason to process them againhowever using itend1 is invalid i cannot use the operator here while i could use the operator this would decrement this final iterator on each cyclei believe a stl list is a doubly linked list so from my perspective it should be possible to do thisadvice thanks in advance,['c++'] +164813,how to change ui depending on combo box selection in dialog i need to thisplay one group of controls if some combo is checked and another group of controls otherwiseie i need 2 layers and i need to switch between them when combo is checkedunchecked how can i do thatthanks,['java'] +164815,eclipse organize packages into folder hierarchy i have a bunch of packages in an eclipse project they have names likeeduxprojappeduxprojdemoeduxprojutilsis there a way in eclipse to automatically collapse them into a folder structure i would like them to be as follows on the workbenchedu x proj app demo utils,['java'] +164823,preparedstatement is not reading all my parameters for postgis geography i have the following jdbc code note that i am attempting to use postgis geographypreparedstatement stmt dbpreparestatementinsert into source imagery image path boundary image time values st geographyfromtextpolygon stmtsetstring1 filegetabsolutepath stmtsetdouble2 boundsgety stmtsetdouble3 boundsgetx i am getting the following exception on the last line of codeorgpostgresqlutilpsqlexception the column index is out of range 3 number of columns 2i understand that it thinks i only have 2 parameters there but you can see that i intended there to be 10 i am not sure why it is not reading any of the parameters within the polygon i know that this sql statement works if i use it directly in the database but i am not sure what i have to change to make it work in my java code any ideas,['java'] +164832,jsoup posting and cookie i am trying to use jsoup to login to a site and then scrape information i am running into in a problem i can login successfully and create a document from indexphp but i cannot get other pages on the site i know i need to set a cookie after i post and then load it when i am trying to open another page on the site but how do i do this the following code lets me login and get indexphpdocument doc jsoupconnect datausername myusername password mypassword posti know i can use apache httpclient to do this but i do not want to,['java'] +164858,syncing html5 with playback i am having track from one source mute and i would like to play background music over it using element the tracks contain some time critical elementswhat would be the options to sync these two different media players in html5 javascript would give the master clock as it audio playback is very time sensitive loosing video frames now and then is not critical,['javascript'] +164873,how do you add csrf validation to pyramid i am passing in a csrf token for every post and xhr request and want to validate the token against the session csrf token if they do not match i throw a 401i have used the newresponse subscriber in pyramid to inspect the request and validate the csrf token in the request params against the token in the session the validation works but it still calls the view so it def does not work as it shouldany suggestions on the proper way to do thissubscribernewresponsedef new responseevent check the csrf token if the user is authenticated and the request is a post or xhr req request eventrequestresponse eventresponseuser getattrrequest user none for now all xhr request are csrf protectedif user and useris authenticated and requestmethod post or requestis xhr and not requestparamsgetcsrf token or requestparamsgetcsrf token unicoderequestsessionget csrf token responsestatus 401 unauthorized responseapp iter,['python'] +164883,difference between rlayout and androidrlayout what is the difference between setcontentviewrlayoutmainandarrayadapter arrayadapter new arrayadapterthis androidrlayoutsimple spinner dropdown item sarraywhat is the difference between rlayout and androidrlayout,['android'] +164891,actioncontrollerroutingerror no route matches javascriptsrailsjs i am using the jquery gem and have installed everything which removes protoni am getting this error and i do not understand whyactioncontrollerroutingerror no route matches javascriptsrailsjsi see it in the logany ideasthanks,['jquery'] +164901,not able to return jsonresult the following query is working successfullyvar tabs from r in dbtabmasters orderby rcolid select new rcolid rfirstname rlastname skiprows page 1takerowsnow i want to return jsonresult as likevar jsondata new total intmathceilingfloattotalrecords floatrows page page records totalrecords rows from r in tabs select new id rcolid cell new string rfirstname rlastname toarray return jsonjsondata jsonrequestbehaviorallowgetbut it will gives me an error likethe array type systemstring cannot be initialized in a query result consider using systemcollectionsgenericlist1systemstring insteadwhat should i do to get expected result,['asp.net'] +164923,restclient strips out the array of hashes parameter with just the last hash i have a condition where i need to pass a parameter as an array of hashes which looks like thisthe following is the racktest post method for api callpost urljsonapi key applicationkeydata companyappleincwebsiteapplecomcompanygooglewebsitegooglecomrun title the first run and this is the log of the rails aparameters api key6a9acb84d0ea625be75e70a1e04d26360606ca5b datacompanyappleinc websiteapplecom companygoogle websitegooglecom runtitlethe first run line id4e018e2c55112729bd0anow this is the restclient post method i am using to call the apirestclientpostlineslineidrunsjson run title title param for input param dataand this is the log of the rails aparameters runtitlerun name datacompanygoogle websitegooglecom api keyf488a62d0307e79ec4f1e6131fa220be47e83d44 line id4e018a505511271f820144the difference is in the data parameter when sending with racktest method the data is passed as datacompanyappleinc websiteapplecom companygoogle websitegooglecom but via restclient way the parameter data array is stripped out and only the last hash is passed as datacompanygoogle websitegooglecomwhy the restclient is stripping out the array of hashes to just a last hash of the array,['ruby-on-rails'] +164943,is it possible to have a memory leak in managed code specifically c 30 for instance if i have a hierarchical data structureclass node public listnode childrenand it is populated to many levels down then in one of the parents gomynodechildrenclearwhich will clear all the references to the immediate children but how about all the grand children grand grand children etc that were referenced by those immediate children is c clever enough to know they are no longer needed and they will be garbage collectedi have read using wpf data binding without implementing interface inotifychanged can cause memory leaks how is that possible in a managed environment,"['c#', '.net']" +164963,how can i ensure two floated items stay sidebyside even if there isnat enough width for both of them i have the following htmldiv div div stylefloat left input typecheckbox valuefalse div div stylefloat left x div divdivit thisplays the x to the right of the checkbox however if i reduce the screen width the x goes under the checkboxis there any way that i can lock the x text inside the div so the x always appears to the right and on the same linenote that i want to keep using div as later on i do some jquery things with the divs,"['html', 'css']" +164971,jdbc get the sql type name from javasqltype code i have an array with field names and jdbc type codesthose int codes that you can find in i use a level 4 driveri cannot figure out how to ask the driver for the corresponding sql ddl type namesit would be useful in jdbc and in native dialectsi havecustomerid 1customername 8and i wantcustomerid intcustomerid varchar200where can i find functions that help me with thati am using jdbc in jython via zxjdbcso i can use all java and python db api 20 functionality,['java'] +164998,how to jsdoc annotate backbonejs code has anyone ever documented backbonejs code with jsdoci am having problems annotating backbone constructs such asuser backbonemodelextend defaults a 1 initialize function dosomething function p any advice appreciated thanks,['javascript'] +165008,int010710 7 in several languages how to prevent this recently i came across a bugfeature in several languages i have a very basic knowledge about how it is caused and i would like some detailed explanation but when i think of all the bugs i must have made over the years the question is how can i determine hey this might cause a riddiculous bug i would better use arbitrary precision functions what other languages do have this bug and those who do not why also why 0107 does this and ie 0103 does not are there any other wellknown examplesphp the first one actually does not make any sense to mewhy 7 after typecast if it is represented internally as 8debug zval dump010710 double8 refcount1debug zval dumpint010710 long7 refcount1debug zval dumpfloat010710 double8 refcount1python 010710791 int0107107javascriptalert010710 79alertparseint070110 7ruby 010710to i 7 010710 79,"['php', 'javascript', 'python', 'ruby']" +165010,how to go through mysql result twice for whatever reason i need to go through a mysql result set twice is there a way to do iti do not want to run the query twice and i do not want to have to rewrite the script so that it stores the rows somewhere and then reuses them later,"['php', 'mysql']" +165011,parentheses after new optional possible duplicatenew myobject vs new myobject i have run the following pair of code snippets in chrome console with the same resultstest new function var a 1 var b 2 var c 3 thisdebugbase functionconsolelog a b ctestdebugbase function consolelog a b c proto objectversustest2 new function var a 1 var b 2 var c 3 thisdebugbase functionconsolelog a b ctest2debugbase function consolelog a b c proto objectam i missing something is there any significance to the parentheses after the function if not why do people put them there,['javascript'] +165024,sending a reset in tcpip socket connection i am using pythonas socketpy to create a connection to an ftpserver now i want to reset the connection send a rst flag and listen to the response of the ftpserver fyi using socketsendr does not work as the os sends fin flag instead of rst,['python'] +165028,modifier static is only allowed in constant variable declarations i have an inner class that stores the info of the controls i am using for a game now i want to store a static arraylist in it that holds all the names of the controls but i am getting this error modifier static is only allowed in constant variable declarationsprivate class control public arrayliststring keys new arrayliststring public final string key public final trigger trigger controlstring k trigger t key k trigger t keysaddkey now i know this can easily be solved by taking the arraylist out of the class and storing it in the main class but i would prefer to keep all the information in one class where i can access everythingcontrolkey controltrigger controlkeysis just more elegantreadable thankey trigger keysor maybe i just have obsessiveacompulsive thisorder still i would like to do it my way,['java'] +165034,how java linker works i want to know how java linker works specifically in which order it combines classes interfaces packages methods and etc into jvmexecutable format i have found some information here but there is not so much information about linking order,['java'] +165063,tagbuildermergeattributes does not work i am creating my own helper in mvc but the custom attributes are not added in the htmlhelperpublic static mvchtmlstring menuitemthis htmlhelper helper string linktext string actionname string controllername object htmlattributes var currentcontrollername stringhelperviewcontextroutedatavaluescontroller var currentactionname stringhelperviewcontextroutedatavaluesaction var builder new tagbuilderli if currentcontrollernameequalscontrollername stringcomparisoncurrentcultureignorecase currentactionnameequalsactionname stringcomparisoncurrentcultureignorecase builderaddcssclaselected if htmlattributes null var attributes new routevaluedictionaryhtmlattributes buildermergeattributesattributes false dont work builderinnerhtml helperactionlinklinktext actionname controllernametohtmlstring return mvchtmlstringcreatebuildertostringtagrendermodenormalcshtmlhtmlmenuitemnossa igreja2 index home new class gradienttop final result htmlli claselecteda hrefnossa igreja2alinote that it did not add the class gradienttop that i mentioned in the helper call,"['c#', 'html']" +165074,lsof counterpart for a jvm lsof is a nice tool for unix showing all currently open file handlesdoes anyone know a similar tool that would show all open files inside a running jvm via jvmti or any similar interfacein this particular case it would be sufficient for me to know which class has a handle open methodline or even an entire chain to gc root would be fantastic but handler owner class is already a good starti know i could make a heap dump open it in a profiler and find this out but this is a tedious task especially for the big heaps,['java'] +165076,why do different block animation constants have the same value uiviewanimationoptionsoptions for animating views with blocksenum uiviewanimationoptionlayoutsubviews 1 0 uiviewanimationoptionallowuserinteraction 1 1 uiviewanimationoptionbeginfromcurrentstate 1 2 uiviewanimationoptionrepeat 1 3 uiviewanimationoptionautoreverse 1 4 uiviewanimationoptionoverrideinheritedduration 1 5 uiviewanimationoptionoverrideinheritedcurve 1 6 uiviewanimationoptionallowanimatedcontent 1 7 uiviewanimationoptionshowhidetransitionviews 1 8 uiviewanimationoptioncurveeaseinout 0 16 uiviewanimationoptioncurveeasein 1 16 uiviewanimationoptioncurveeaseout 2 16 uiviewanimationoptioncurvelinear 3 16 uiviewanimationoptiontransitionnone 0 20 uiviewanimationoptiontransitionflipfromleft 1 20 uiviewanimationoptiontransitionflipfromright 2 20 uiviewanimationoptiontransitioncurlup 3 20 uiviewanimationoptiontransitioncurldown 4 20typedef nsuinteger uiviewanimationoptionsconsider the about enum definitions from the ios documentation my question is for uiviewanimationoptioncurveeaseinout the constant is 0 16 but if my understanding is correct 0 left shift by 16 positions is still 0 and it should be the same as uiviewanimationoptiontransitionnone which is 0 20 since it should also be 0 having 2 very different options equal to the same value does not seem to make sensealso my testing shows uiviewanimationoptioncurveeaseinout does not seem to have any effect at all there could be some misunderstanding on my part hope that somebody knowledgeable would help classuiviewuiviewhtml23apple refctdefuiviewanimationoptions,"['ios', 'objective-c']" +165079,python equivalence to inline functions or macros i just realized that doingxrealxrealximagximagis three times faster than doingabsx2where x is a numpy array of complex numbers for code readability i could define a function likedef abs2x return xrealxrealximagximagwhich is still far faster than absx2 but it is at the cost of a function call is it possible to inline such a function as i would do in c using macro or using inline keyword,['python'] +165106,when auto is used against array why it is converted to pointer and not reference see the below exampleint arr10int p arr 1st valid choiceint r10 arr 2nd valid choicenow when we use auto against arr then it chooses the 1st choiceauto x arr x is equivalent to pis there a reason for choosing a pointer and not reference for array,['c++'] +165124,javascript calculate brighter colour i have a colour value in js as a stringff0how would i go about programatically calculating a brighterlighter version of this colour for example ff4848 and be able to calculate the brightness via a percentage egincrease brightnessff0 50 would make it 50 brighter,['javascript'] +165147,why is it so much harder to enable ssl transport security over nettcp than http implementing a web service that uses transportlevel security with wcf over http is pretty easy enable ssl for my wcf serviceimplementing a web service that uses transportlevel security with wcf over nettcp is pretty hard wcf with nettcpbinding and certificate transport security and the nettcp solution usually involves something like this on both the server side and the client side servicecertificate findvaluemyservicecertificate storelocationlocalmachine storenamemy x509findtypefindbysubjectname in the http case you do not need to even mention a certificate on either the client or the server in the nettcp case you have to store locate and specify a certificate on both the client and the server in most of the sources i have readwhat is the thing doing the magic that makes you not have to worry about the certificates in http mode and why is this magic not available to you when using nettcp,['.net'] +165162,forward declaration and namespaces c my problemgot two classes class a and b so i got ah and acpp and bh and bcppa needs to know b and b needs to know a i solved it the following way i do not know why it has to be soahinclude bhclass a acppinclude ahbhinclude ahclass a forward declarationclass b bcppinclude bhi used one forward declaration and it worksthe problem is that both classes need to be in the namespace ui or at least i think this is the meaningahinclude bhnamespace ui class aclass a bhinclude ahnamespace ui class bclass b this does not work anymore what do i have to do now to make it work again with namespace and forward declarationboth have to be in this namespace i am working with qt and the lines namespace ui etc are needed and both classes need to know each otheri already tried just to make thisnamespace ui class a class bin both headers but this does not workbtw all headerfiles also got the ifndefmechanism,['c++'] +165164,using guid as pk in big partitioned mysql table we have a huge innodb table with hundreds of millions of rows and only 3 columns guid enum smallintall lookups are done by guidwere considering making guid the pk and partitioning it by key weve heard that using guid as pk is bad because of its random thistribution and the fact that pk creates clustered index so storing rows in random order of guids increases fragmentation and page splitsthe alternative to using guid as pk is to create a surrogate autoincrement key and use that as pk however if we want to partition the table by guid that guid has to be part of pk as well also since all queries are done by guid we need an additional guid indexthat index essentially maps guidpk while if we use guid as pk the table itself maps guidenumsmall intso my question is whether we gain anything by adding autoinc pk and having additional guid indexthanksphilopator,['mysql'] +165181,sql statement with multiple sets and wheres i am wondering if this is a valid queryupdate tableset id 1259where id 25and set id 1261where id 2724and set id 1263where id 2021and set id 1264where id 2017,['sql'] +165183,ie 7 does not work with css inlineblock or fixes i know that this has been asked a million times before but nothing that i have tried has solved the problem i am working on a nice looking select type thing i am basing it off of common css drop down navigation menus using nested uls and lis just with a few tweaks one of the tweaks is that i need it to thisplay inline without floating it because it goes past any other elements in the same line as it and i do not want to float everything else around it i have got it working well in the browsers besides ie 7 and probably anything lower but i do not need anything lower than ie7 here is the code if you look at that in any nonie7 browser it looks like how i want it tobut if you look at it in ie7 it looks like thisone site that i saw come up a lot for the inlineblock fix is this that worked for ie8 but unfortunately ie7 still does not look rightis there any other way to fix inlineblock for ie7 or is there a css alternative to make sure the the second level lis are always vertically aligned with the the first level li thanks,"['html', 'css']" +165250,what happens to android app when a phone call interrupts the app i am working on an app and in one of my activities i thisplay a progressdialog i have managed it so that it thisplays correctly during rotations and i thought that would handle the case of a phone call too but when i test it with a phone call the dialog goes away so what exactly does the phone call do to the application and how is a part of the application lifecyclethanks,['android'] +165253,what does urllib2request do and how do i printview it i am trying to learn how urllib2 works and how it encapsulates its various components before sending out an actual request or responseso far i havetheurl wexamplecomthat obviously specifies the url to look atreq urllib2requesttheurl do not know what this does hence the questionhandle urllib2urlopenreqthis one gets the page and does all the requests and responses requiredso my question is what does urllib2request actually doto try and look at it to get an idea i tried print req and just got urllib2request instance at 0x123456789i also triedprint reqread and gottraceback most recent call last file stdin line 1 in file usrlib64python24urllib2py line 207 in getattr raise attributeerror attr attributeerror readso i am obviously doing something wrong if anyone can help in one of both my questions that would be great,['python'] +165266,linq sort child in query i have an ef model as followson this model i can obviously use categoriesproducts to receive a list of productsi have a query as follows to return a list of categories with products as a list to be used in an aspnet mvc 3 viewvar categories from a in contextcategoriesincludeproducts orderby asortorder ascending select atolistreturn viewcategoriesin order to show the products in order of their sortorder i currently have to doulforeach var category in model licategorytitle ul foreach var product in categoryproductsorderbya asortorder liproductdescriptionli ul liulthe offending line is foreach var product in categoryproductsorderbya asortorder as this is handling a bit of my model in the viewis there a way to sort this in the query,['c#'] +165269,android how to translate app into different languages and sell on marketplace say i have an app consisting of some preference lists some toasts etc strings are set both in the xml files and appendingcreated dynamically in java sometimes how does one go about making the app in like 8 different languages and selling them based on language does the android marketplace let you set a dropdown list for language to download in also on the programming side is having the translations in a word file and then doing copyandpaste into eclipse going to work perhaps i am asking in the wrong place but i am not too sure where to start here,['android'] +165281,make jspinner completely numeric i have a jspinner that can vary from minimum to maximum at steps of 01 this is working perfectly fine now i set the editor of jspinner as numbereditor as the user can edit the textbox and i want only numeric values from this this is also working that is whatever the user may enter the editor gives me only the numbers in the editor when i get the value using myspinnergetvaluetostring now cones the problem i want the textbox to accept only numeric values and decimal point that is if the user tries to enter anything apart from 09 and it should not echo it in the textbox jspinner myspinner new jspinnermyspinnersetmodelnew spinnernumbermodeldefaultminimummaximum01myspinnerseteditornew jspinnernumbereditormyspinnercan someone help me with this thanks,['java'] +165308,jsmin usage problem i want to use jsmin to minify js files but i am confused how to install it in my windows machine and how to use it i tried to find any resource by no luck can anyone please help me with thisthanks a lot,['javascript'] +165313,jpa composite primary key i have the following classes in my jpa model getters setters and irrelevant fields omittedentity inheritancestrategy inheritancetypetable per classpublic class currency id private integer ixentity inheritancestrategy inheritancetypetable per classpublic class product id generatedvaluestrategy generationtypeidentity private integer idi need to define a class price such that when the ddl is generated from the classes the primary key of the corresponding table is composed of the keys for product and currency i have tried the followingentity inheritancestrategy inheritancetypetable per classidclasspricepkclasspublic class price id manytooneoptional false private product product id manytooneoptional false private currency currencyembeddablepublic class pricepk implements serializable integer product integer currencybut this generates the following for the price tablecreate table price currency id int null product id int null primary key currency id product idnotice that both currency id and product id are nullable which causes the following error when i try to load the ddl into sql servercannot define primary key constraint on nullable column in table pricei do not understand why these are nullable because in the domain model they are annotated manytooneoptional falsethe ddl is generated using the orghibernatedialectsqlserverdialect sql dialect,['java'] +165325,the type must be a reference type in order to use it as parameter t in the generic type or method i am getting deeper into generics and now have a situation i need help with i get a compile error on the derived class below as shown in the subject title i see many other posts similar to this one but i am not seeing the relationship can someone tell me how to resolve thisusing systemusing systemcollectionsgenericnamespace example public class viewcontext viewcontext public interface imodel public interface iviewt where t imodel viewcontext viewcontext get set public class somemodel imodel public somemodel public int id get set public class baset where t imodel public baseiviewt view public class derivedsomemodel basesomemodel where somemodel imodel public derivediviewsomemodel view baseview somemodel m somemodelactivatorcreateinstancetypeofsomemodel servicesomemodel s new servicesomemodel sworkm public class servicesomemodel where somemodel imodel public service public void worksomemodel m,['c#'] +165414,how to include external font in wpf application without installing it how to include external font in wpf application without installing iti tried this code systemdrawingtextprivatefontcollection privatefonts new systemdrawingtextprivatefontcollection privatefontsaddfontfilecdocuments and settingssomefontf systemdrawingfont font new fontprivatefontsfamilies0 12 thislabel1font fontit working correctly in windows form application but not in wpf,['c#'] +165448,passing an enum type as an argument possible duplicatec enums as function parameters i was wondering how i can pass an enum type as a method argument i am trying to create a generic method that will take a combo box and enum and fill the combo box with each item of the enum,['c#'] +165457,how can i tell when i have reached the end of the file when using the readblock method in c i noticed that it will keep returning the same read characters over and over but i was wondering if there was a more elegant way,['c#'] +165467,deleted file still appears in directorygetfiles result i have two webmethods the first isvoid deletefilestring filepath filedeletefilepaththe other isstring getallfile at the same folder directorygetfilesxml return i am calling these methods like sodeletefile1xmlgetallfiledespite deleting the 1xml file the call to directorygetfilesxml still returns 1xml in the results in other words it does not seem to have been deletedand then when i loop the result try to read the file get the filenofoundexception,['c#'] +165471,how to get column names from sqlalchemy result declarative syntax i am working in a pyramid project and i have the table in sqlalchemy in declarative syntaxmodelspyclass projectsbase tablename projects table args autoload truei get the results by usingviewspysession dbsessionrow data sessionqueryprojectsfilter byid1onehow can i get the column names from this resultps i am unable to use this method since i am using the declarative syntax,['python'] +165480,the relative virtual path is not allowed here any ideas what this problem is cheers,['asp.net'] +165498,appending strings in oracle within a plsql loop like any programming language you can use a simple to append to a variable string but how do you do that within an oracle plsql block examplemy string stringmy string blawhile not greater than 10my string iexpected output bla12345678910,['sql'] +165514,stl remove does not work as expected int main const int size 10 int asize 10 2 35 5 10 26 67 2 5 10 stdostream iterator int outputcout stdvector int va a size stdvector int iterator newlastelement cout contents of the vector stdcopyvbegin vend output newlastelement stdremovevbegin vend 10 cout ncontents of the vector after remove stdcopyvbegin newlastelement output this gives the correct result 2 35 5 26 67 2 5 stdcopyvbegin vend output this gives a 10 which was supposed to be removed 2 35 5 26 67 2 5 2 5 10 cout endl return 0there are three 10 in the array awhy does the array v contains a 10 after we remove the all the 10s with remove functionyou can see the compiled output also here,['c++'] +165522,pre post increment operator behavior in c c java c thisclaimer this is not a realworld example it is just a theoretical question of how these languages workwhat exactly are the differences between cc c and java when it comes to post pre increment operatorsthis is what i get with vc10 java 16 and c 4int a 2int b a aint c a a a c c java c a 7 7 7 7 b 4 4 5 5 c 15 15 16 16,"['c#', 'java', 'c++', 'c']" +165541,compatible sql to test for not null and not empty strings i want to have compatible sql for both oracle database and microsoft sql serveri want a compatible sql expression that will return true for not null and not empty stringsif i usecolumn it will work on microsoft sql server but not on oracle database as is null for oracleif i uselencolumn 0it will work on microsoft sql server but not on oracle database since it uses length,['sql'] +165542,form confirm before submit i am using a simple form and i want to allow the user to confirm before the form submits i know this would be easy using jquery but i am a bit confused about codefunction testformsubmitfunction submitbtntextconfirm i know that the above code is not complete and i would like your help to finish it so it would give an alert using jquery alert that says please confirm if everything is correct and changes the text on the submit button to confirm instead of submit if the user clicks confirm again it would submit the form i hope this makes sense thanks,['jquery'] +165544,truly compiletime string hashing in c basically i need a truly compiletime string hashing in c i do not care about technique specifics can be templates macros anything all other hashing techniques i have seen so far can only generate hashtable like 256 crc32 hashes in compile time not a real hashin other words i need to have thisprintfd somehashstringto be compiled as in pseudoassemblerpush hashvaluepush dcall printfeven in debug builds with no runtime operations on string i am using gcc 42 and visual studio 2008 and i need the solution to be ok for those compilers so no c0x,['c++'] +165560,sun jvm jre jre160 24 segfault net read our jvm crashes with segmentation fault from time to time inproduction with what feels like a race condition of some sortsetups to reproduce jre jre160 24 on linux ubuntu 910 and debian 4x 64 bit multicore amd apache tomcat 6024 6032recompiling java with fastdebug reproduces the problem this gcc g1however it does not yield much more useful information then what wehave hererecompiling java with debug does not reproduce the problem this isgcc g plus possibly some dsomething code debug flagsany help trying to figure this out would be most appreciatedcore file generated using the 160 24 jdk from oracle gdb turns up program terminated with signal 11 segmentation fault 0 0x02ab7b106 in net read from usrlocaljdk160 24jrelibamd64libnetsook so my assembly is really really really rusty keeping that in mind gdb info frame stack level 0 frame at 0x4b3e0040 rip 0x2ab7b106 in net read saved rip 0x2ab7b0d53b called by frame at 0x4b3f0090 arglist at 0x4b3dffc8 args locals at 0x4b3dffc8 previous frames sp is 0x4b3e0040 saved registers rbx at 0x4b3e08 rbp at 0x4b3e0010 r12 at 0x4b3e0018 r13 at 0x4b3e0020 r14 at 0x4b3e0028 r15 at 0x4b3e0030 rip at 0x4b3e0038so gdb tells us that the argument list is at 0x4b3dffc8looking at the data there gdb x8x 0x4b3dffc8 0x4b3dffc8 0x0 0x0 0x0 0x0 0x4b3dffd8 0x0 0x0 0x0 0x0so no dice there again my assembly dates back to 2nd wave ska so ican only think that either the stack is somewhat buggered or the gccoptimization flags generate code which uses registers for argumentsinstead of the stackonto the registers gdb info registers rax 0xf2 242 rbx 0x4 4 rcx 0x2b73aa8bfed3 475782534867 rdx 0x4 4 rsi 0x4b3e0050 1262354512 rdi 0xf2 242 rbp 0x0 0x0 rsp 0x4b3dffd0 0x4b3dffd0 r8 0xffc 4092 r9 0x2b73aa8c61b0 475782560176 r10 0x2b73aa8c9f78 475782575992 r11 0x2b73aa8b20d0 475782478032 r12 0xf2 242 r13 0xf2 242 r14 0x2abad4b9c8 46912767310280 r15 0x4 4 rip 0x2ab7b106 0x2ab7b106 net read22 eflags 0x10202 if rf cs 0x33 51 ss 0x2b 43 ds 0x0 0 es 0x0 0 fs 0x63 99 gs 0x0 0the thisassembly looks to me like it is faulting at read22 0x02ab7b10650 net read0 push r15 0x02ab7b10652 net read2 mov rdxr15 0x02ab7b10655 net read5 push r14 0x02ab7b10657 net read7 push r13 0x02ab7b10659 net read9 mov edir13d 0x02ab7b1065c net read12 push r12 0x02ab7b1065e net read14 push rbp 0x02ab7b1065f net read15 push rbx 0x02ab7b10660 net read16 sub 0x38rsp 0x02ab7b10664 net read20 test ediedi 0x02ab7b106 net read22 mov rsi0x8rsp 0x02ab7b1066b net read27 js 0x2ab7b1067c net read44 0x02ab7b1066d net read29 lea 1073812riprax 0x2ab7c16908 fdcount 0x02ab7b10674 net read36 cmp raxedi 0x02ab7b10676 net read38 jle 0x2ab7b1070b net read187 0x02ab7b1067c net read44 xor ebpebp 0x02ab7b1067e net read46 test rbprbp 0x02ab7b10681 net read49 je 0x2ab7b106f9 net read169 0x02ab7b10683 net read51 lea 0x10rspr14 0x02ab7b10688 net read56 callq 0x2ab7b03dd0 pthread selfplt 0x02ab7b1068d net read61 mov rbprdi 0x02ab7b10690 net read64 movl 0x00x20rsp 0x02ab7b10698 net read72 mov rax0x10rsp 0x02ab7b1069d net read77 callq 0x2ab7b03f80 pthread mutex lockplt 0x02ab7b106a2 net read82 mov rbprdi 0x02ab7b106a5 net read85 mov 0x28rbprax 0x02ab7b106a9 net read89 mov rax0x18rsp 0x02ab7b106ae net read94 mov r140x28rbp 0x02ab7b106b2 net read98 callq 0x2ab7b043b0 pthread mutex unlockplt 0x02ab7b106b7 net read103 mov r13dedi 0x02ab7b106ba net read106 mov 0x8rsprsi 0x02ab7b106bf net read1 xor ecxecx 0x02ab7b106c1 net read113 mov r15rdx 0x02ab7b106c4 net read116 callq 0x2ab7b04160 recvplt 0x02ab7b106c9 net read121 mov rbprdi 0x02ab7b106cc net read124 mov r14rsi 0x02ab7b106cf net read127 mov eaxebx 0x02ab7b106d1 net read129 mov raxr12 0x02ab7b106d4 net read132 callq 0x2ab7b110 endop 0x02ab7b106d9 net read137 inc ebx 0x02ab7b106db net read139 jne 0x2ab7b106e7 net read151 0x02ab7b106dd net read141 callq 0x2ab7b04380 errno locationplt 0x02ab7b106e2 net read146 cmpl 0x4rax 0x02ab7b106e5 net read149 je 0x2ab7b10688 net read56 0x02ab7b106e7 net read151 mov r12deax 0x02ab7b106ea net read154 add 0x38rsp 0x02ab7b106ee net read158 pop rbx 0x02ab7b106ef net read159 pop rbp 0x02ab7b106f0 net read160 pop r12 0x02ab7b106f2 net read162 pop r13 0x02ab7b106f4 net read164 pop r14 0x02ab7b106f6 net read166 pop r15 0x02ab7b106f8 net read168 retq 0x02ab7b106f9 net read169 callq 0x2ab7b04380 errno locationplt 0x02ab7b106fe net read174 movl 0x9rax 0x02ab7b10704 net read180 mov 0xfeax 0x02ab7b10709 net read185 jmp 0x2ab7b106ea net read154 0x02ab7b1070b net read187 movslq edirax 0x02ab7b1070e net read190 lea raxrax2rbp 0x02ab7b10712 net read194 lea 1073639riprax 0x2ab7c16900 fdtable 0x02ab7b10719 net read201 shl 0x4rbp 0x02ab7b1071d net read205 add raxrbp type return to continue or q return to quit 0x02ab7b10720 net read208 jmpq 0x2ab7b1067e net read46 0x02ab7b10725 net read213 data16 0x02ab7b10726 net read214 data16 0x02ab7b10727 net read215 data16 0x02ab7b10728 net read216 nop 0x02ab7b10729 net read217 data16 0x02ab7b1072a net read218 data16 0x02ab7b1072b net read219 data16 0x02ab7b1072c net read220 nop 0x02ab7b1072d net read221 data16 0x02ab7b1072e net read2 data16 0x02ab7b1072f net read223 noplooking at the source code for netread jdksrcsolarisnativejavanetlinux closec snip macro to perform a blocking io operation restarts automatically if interrupted by signal other than our wakeup signal define blocking io return intfd func int ret threadentry t self fdentry t fdentry getfdentryfd if fdentry null errno ebadf return 1 do startopfdentry self ret func endopfdentry self while ret 1 errno eintr return ret int net readint s void buf size t len blocking io return int s recvs buf len 0 thanks,['java'] +165571,on input change event when using jquery change on an input the event will only be fired when the input loses focusin my case i need to make a call to the service check if value is valid as soon as the input value is changed how could i accomplish this,"['javascript', 'jquery', 'html']" +165576,how to format a number 10 as 1 0 i need a way to format numbers i stored some numbers in my db table eg 12500 and would like to print them in this format 12 500 so there is a space every 3 digits is there an elegant way to do this,['ruby'] +165591,how to write settimeout with params by coffeescript please tell me how to write javascript below in coffeescriptsettimeoutfunction somethingparam 10,['javascript'] +165615,using iterator on a treeset situation i have a treeset of custom objects and i have also used a custom comparator i have created an iterator to use on this treeset treesetcustom tsnew treesetcustomiteratorcustom itrtsiteratorwhileitrhasnext custom citrnext code to add a new element to the treeset tsquestion well i want to know that if i add a new element to the treeset within the while loop then will that new element get sorted immediately in other words if i add a new element within the while loop and it is less than the one which i am currently holding in c then in the next iteration will i be getting the same element in c as in the last iterationsince after sorting the newly added element will occupy a place somewhere before the current element,['java'] +165617,eclipse runs debug mode even when i click run eclipse always starts my app on debug mode even though i click the regular run buttonany ideas,"['java', 'android']" +165629,close window automatically after printing dialog closes i have a tab open when the user clicks a button on the onload i have it bring up the print dialog but the user asked me whether it was possible that after it sends to the printer to print if the tab could close itself i am not sure whether this can be done i have tried using settimeout but it is not a defined period of time since the user might get thistracted and have to reopen the tab is there any way to accomplish this,['javascript'] +165635,basic explanation of context in android if you cannot explain it to a six year old you do not understand it yourself a albert einsteinafter reading about a context on the android developer web site and various other places on the web i am still a bit fuzzy in this line of code i am a bit confused what the parameter really means i am not ashamed to get a 6 year old answer textview textview new textviewgetbasecontextthanks,"['java', 'android']" +165643,triggering jquery with css media queries i am using css media queries on my project to create a site that will work with any sized screen i am looking to trigger difference jquery functions just like i would with cssfor example if the browser size is between 10px and 1300px i would like to call the following functionmycarouseljcarousel vertical true scroll 1 auto 2 wrap circularbut when the browser size is below 10px the js would stop its processing so on and so forthi am not sure if this is possible but perhaps there is an existing solution or plugin that creates different js environments based on browser window sizes i suppose i could create conditional statements in some format any thoughts,['jquery'] +165663,how to get object property from each object in an array assuming i have an array of objects in php something likearray 0 stdclass object id 1 name title one 1 stdclass object id 2 name title two 2 stdclass object id 7 name title seven what is the best way ie fastest to get an array of the ids ie array127 i can loop manually but i feel there must be a better methodjust saw this in the similar questions but there is a little debate over whether the accepted answer is really the best way plus it is from 2 years ago i am on php 53,['php'] +165668,is filtering faster than querying in lucene while reading lucene in action 2nd edition i came across the description of filter classes which are could be used for result filtering in lucene lucene has a lot of filters repeating query classes for example numericrangequery and numericrangefilterthe book says that nrf does exactly the same as nrq but without document scoring does this means that if i do not need scoring or sort documents by document field value i should prefer filtering over querying from performance point of view,['java'] +165701,how to print the data in byte array as characters in my byte array i have the hash values of a message which consists of some negative values and also positive values positive values are being printed easily by using the charbytei statement now how can i get the negative value,['java'] +165711,how to play mp3 file in raw folder as notification sound alert in android i am having my own audio file placed in raw folder inside resource folderi want to set it as notification sound alert how should i proceed,['android'] +165713,rest api for java i am preparing an application which is console based and the outcome of the application is a rdfxml file which contains data of all my connections from linkedin now the problem is that my entire application is console based and i need to have a rest api so as to incorporate with my applicationi am not aware of rest apis and how to use it with java but can easily get through the documentation and understand it my applications use the rest api of linkedin so can you please suggest some of the good rest api for java,['java'] +165717,finding the single unknown in an equation i need a library to be able to parse an equation an give me the result giving the inputsfor example something like thisstring equation 5 6 z equationsolver solver new equationsolverequation double result solvergetresult systemoutprintlnresult resultand evaluates to 65is there any kind of library for java that can do that for mebasically i need the program to isolate the single unknown variable in an arbitrary equationthanksthomas,['java'] +165751,how to determine the screen width in terms of dp or dip at runtime in android i need to code the layout of the android widgets using dipdp in java files at runtime if i codeint pixelthisgetwindowmanagergetdefaultthisplaygetwidththis return the screen width in pixels px to convert this to dp i codedint dp pixelintgetresourcesgetthisplaymetricsdensity this does not seem to be returning correct answer i made the emulator of wvga800 whose screen resolution is 480 by 800 when the run the emulator and let the code print the values of pixel and dp it came to 320 in both this emulator is 240 dpi whose scale factor would be 075,['android'] +165754,convert javascript app into windows app is there any solutions except adobe air i have heard that v8 kinda have something therejust do not have time for now to write on another language whole app and then write 2x more code,['javascript'] +165793,php why does not count work like strlen on a string a string is an array of characters correct if so then why does count not produce the same result as strlen on a string,['php'] +165806,how to compare two joda time periods it does not seem straighforwardi am trying thisoverridepublic int compareperiod o1 period o2 return o1tostandarddaysgetdays o2tostandarddaysgetdays 1 o1tostandarddaysgetdays o2tostandarddaysgetdays 0 1but i get this exceptionjavalangunsupportedoperationexception cannot convert to days as this period contains months and months vary in length at orgjodatimeperiodcheckyearsandmonthsperiodjava1455 at orgjodatimeperiodtostandarddaysperiodjava1314i hoped peroid would have an islongerthanperiod p method,['java'] +165827,does a method marshalled on the ui thread need to be threadsafe if i invoke a method onto the ui thread is it searilized by the windows message queue and subsequently does not need to be reentrant private void calledfromworkerthread changed from invokerequired antipattern thisinvokeaction counter is this ok clarification it is only the ui thread that will be accessing counter,['c#'] +165828,converting double to integer in java in java i want to convert a double to an integer i know if you do thisdouble x 15int y intxyou get y1 if you do thisint y intmathroundxyoull likely get 2 however i am wondering since double representations of integers sometimes look like 198 or something is there a possibility that casting a double created via mathround will still result in a truncated down number rather than the rounded number we are looking for ie 1 instead of 2 in the code as represented and yes i do mean it as such is there any value for x where y will show a result that is a truncated rather than a rounded representation of xif so is there a better way to make a double into a rounded int without running the risk of truncationfigured something mathroundx returns a long not a double hence it is impossible for mathround to return a number looking like 398 therefore intmathround will never need to truncate anything and will always work,['java'] +165845,any android market api from google not sure if its a possible duplicate if so please merge to the appropriatei am looking for google market api that can pull the following informationlist of categories in apps books movies in the google marketlist of top free appsbooksmovies by no of downloads ratings etc in a given categorylist of top paid appsbooksmovies by no of downloads ratings etc in a given categoryis there an official google market api availablei came across the below project but the feature set it provides does not support this functionalityany help is highly appreciated,['android'] +165852,setting custom http request headers in an url object does not work i am trying to fetch an image from an ip camera using http the camera requires http basic authentication so i have to add the corresponding request headerurl url new urlhttpmyipcamsnapshotjpgurlconnection uc urlopenconnectionucsetrequestpropertyauthorization basic new stringbase64encodeuserpassgetbytes outputs nullsystemoutprintlnucgetrequestpropertyauthorizationi am later passing the url object to imageioread and as you can guess i am getting an http 401 unauthorized although user and pass are correctwhat am i doing wrongi have also tried new urlhttpuserpassmyipcamsnapshotjpg but that does not work either,['java'] +165873,how do i convert an existing rails 3 application into an engine how can i convert the forum application i have been developing into a rails engine so that it may be embedded inside other applicationswhat should i add keep or remove should i offer a way to integrate the models how do i set up routes and user configuration how do i package it into a gem what should i watch out forafter reading the articles and the documentation i managed to narrow down my questionsshould i namespace the models that is should i keep them in my engines module and in the appmodelsengine folderwhat configuration files in config should i keep aroundwhat about the public folder in rails 31 stylesheets and javascripts were moved to the appassets folder which solved this problem but how do i achieve the same effect in rails 30,"['ruby-on-rails', 'ruby']" +165911,what is unsafe in this code i am learning about managed and unmanaged code in clrso i wrote this example with cstyle pointers in cunsafe static void mainstring args int x int y y x y 50 consolewriteliney consolewritelineintytostringso i am wondering what really is unsafe in il code that i got from the code aboveassembly extern mscorlibassembly unsafepointersmodule unsafepointersexeclass private auto ansi beforefieldinit unsafepointersprogramextends mscorlibsystemobject method private hidebysig static void mainstring args cil managed entrypoint code size 34 0x22 locals init int32 x int32 y il 01 ldloca x il 03 convu il 04 stloc y il 05 ldloc y il 06 ldci4 50 il 08 stindi4 il 09 ldloc y il 0a ldindi4 il 0b call void mscorlibsystemconsolewritelineint32 il 0010 nop il 0011 ldloca y il 0012 convi4 il 0016 call instance string mscorlibsystemint32tostring il 001b call void mscorlibsystemconsolewritelinestring il 0021 ret does clr manages this code and what can go wrong with a code above,['c#'] +165957,code inspection says i need to thispose object which one this is my function i already wrapped both client and message into using clause and still get error when run code inspection error points to first using linepublic static void sendmailitem mail var sender membershipgetusermailcreatedby if sender null return using var msg new mailmessage from new mailaddressconfigurationmanagerappsettingsemailsender configurationmanagerappsettingsemailsendername foreach var recipient in mailmailrecipients var recipientx membershipgetuserrecipientuserkey if recipientx null continue msgtoaddnew mailaddressrecipientxemail recipientxusername msgsubject from senderusername mailsubject msgbody mailbody if httpcontextcurrent null msgbody environmentnewline environmentnewline to reply via web click link below environmentnewline msgbody configurationmanagerappsettingsmailpagepath aid contextmanagercurrentaccountaccountid run senderusername try using var emailclient new smtpclient emailclientsendmsg catch exception ex loggerlogexceptionex this is warning i getwarning 1 ca20 microsoftreliability in method emailsendmailitem object g initlocal0 is not thisposed along all exception paths call systemithisposablethispose on object g initlocal0 before all references to it are out of scope ccodeworkspacecodeutilityemailcs 41,['c#'] +165980,swt trayitemsetimage does not scale properly in mac status bar on my crossplatform swt java application i am using trayitems setimages function to set the dock and status bar icon the icon is a 128x128 transparent png the status and tray icons are appropriately clipped on both windows and linux thistributions but on the mac i have problems that make the status bar icon appear with strange padding on both sides like thisit is strange to me that this is working on all other platforms but the mac for instance here is the same status bar icon without the problem on my linux boxdoes anyone have any idea how to prevent this extra padding on the mac,['java'] +166012,how to set the orientation of jtextarea from right to left inside joptionpane i have jscrollpane with jtextarea inside it and i am trying to set the jtextareas orientation from right to left so the text inside it will start from the right and the scrollbar will be on the lefti have tried the following but they did not affect the direction of the orientationtxtapplycomponentorientationcomponentorientationright to lefttxtsetcomponentorientationcomponentorientationright to lefttxtsetalignmentxjtextarearight alignmenteditthe two answers camickr trashgod provided work fine but not in my program where i use my jtextarea as an object message and pass it to optionpaneedit2i figured out that setcomponentorientationcomponentorientationright to left does not work if i apply it on the joptionpane contents is there an alternative solution to this issuesimilar to my codeimport javaawtimport javautilimport javaxswingpublic class textarea extends jpanel private jtextarea txt new jtextarea public textarea setlayoutnew gridlayout txtsetcomponentorientationcomponentorientationright to left jscrollpane scroll new jscrollpanetxt scrollsetcomponentorientationcomponentorientationright to left setpreferredsizenew dimension200200 thisaddscroll private void thisplay object options this joptionpane pane new joptionpane int option paneshowoptiondialognull null title joptionpanedefault option joptionpaneplain message null options options0 public static void mainstring args new textareathisplay,['java'] +166015,listview with alphabets on the right like the iphone is it possible i would like to know if a listview in android has an option to place alphabets on the right like the paradigm of iphone listview like belowif yes can someone provide me with sample codesi am not looking for the one with an alphabet overlay from apisdemo but an exact one like the iphone paradigm is it possible,['android'] +166019,coding cuda with c i have been looking for some information on coding cuda the nvidia gpu language with c i have seen a few of the libraries but it seems that they would add a bit of overhead because of the pinvokes etc how should i go about using cuda in my c applications would it be better to code it in say c and compile that into a dllwould this overhead of using a wrapper kill any advantages i would get from using cudaand are there any good examples of using cuda with cthanksmax,['c#'] +166049,difference between stringequals and stringcontentequals methods what is the difference between the stringequals method and the stringcontentequals method,['java'] +166096,multi tenancy support in java ee 6 i have an existing java ee 6 application deployed in glassfish v 31 and want to support multiple tenants technologiesapis i am currently using in my app areejb including the ejb timer servicejpa 20 eclipselinkjsf 20 jmsjaxrsi plan to use cdi as wellas far as i know adding multitenancy support affects only the persistence layer my question has anybody done this before what are the steps to convert the application will this affect other layers other than persistencethere will be a high number of tenants therefore all data will reside in the same db schema,['java'] +166114,python stringio replacement that works with bytes instead of strings is there any replacement for python stringio class one that will work with bytes instead of stringsit may not be obvious but if you used stringio for processing binary data you are out of luck with python 27 or newer,['python'] +166146,how do i listen for triple clicks in javascript if this is for double clickwindowaddeventlistenerdblclick functionevent falsehow can i capture a triple click this is for a pinned tab in google chrome,['javascript'] +166156,ctypes pointer into the middle of a numpy array i know how to get a ctypes pointer to the beginning of a numpy arraya nparange10 dtypenpdoublep actypesdata aspointerc doublepcontentsc double00however i need to pass the pointer to let us say element 100 without copying the arraythere must be an easy way to do it but cannot find itany hint appreciated,['python'] +166181,nonvirtual interface design pattern in cc when designing an interface someone recommended to use the nonvirtual interface pattern can someone briefly outline what the benefits of this pattern are,"['c#', 'c++']" +166200,row color and alternate row color for table in rdlc report how do i give row color and alternate row color for a table in rdlc report when i googled i found most of the result says something like iifrownumbernothing mod 2 red white ok but where should i place this stuff any help will be appreciated,['asp.net'] +166238,stream as a return value in wcf who thisposes it let us say i have the following wcf implementationpublic stream downloadstring path filestream stream new filestreampath filemodeopen fileaccessread return streamwhos responsible for thisposing the returned value after all a network failure might occur hence the consumer might not be able to thispose it,['.net'] +166243,python decimal precision for some reason decimal object looses precision when multiplied there is no reason to happen so please check the testcase and enlighten mefrom decimal import getcontextprec 11a decimal508528725881485b 1print getcontextprint a straprint b strbprint a b stra band the outputcontextprec11 roundinground half even emin9 emax9 capitals1 flags trapsdivisionbyzero invalidoperation overflowa 508528725881485b 1a b 50852872588not sure if this is relevant but python26 used,['python'] +166248,uitableview best practices what are the best practices when dealing with uitableviews in order to improve the performance speed up the development and maintenance when dealing with uitableviews,"['iphone', 'objective-c', 'ios']" +166270,c source in w file i found a c source in these files with w extensions it seems like a mix of tex codeand c programming language this is an example of these sourceshow can i compileps excuse me for the silly question but i did not found any documentation,['c'] +166291,how do i split a string into an array of characters var s overpopulationvar ar ar ssplitalertari want to stringsplit a word into array of charactersthe above code does not seem to work it returns overpopulation as objecthow do i split it into array of characters if original string does not contain commas and whitespace,['javascript'] +166295,rounded corners on divs with background color i have got some code that looks like thisdiv idshell div idtitletitle herediv div idcontentarticle content goes heredivdivthe shell div has a grey border that i want rounded corners on the problem i am running into is the title div has a green background and it is overlapping the rounded corners of the shell it either overlaps or does not jut up against the edges to provide a fluid looki am looking for a solution that is backwards compatible with ie 7 and 8 but if there is a solution in html5 that is simple i would be willing to lose those browsersthanks,['css'] +166317,what are the default values for rails 3 for dependent on has many and belongs to in rails 3 i know that i can force deletion of dependent objects on belongs to and has many relations using the dependent delete option however i was wondering what is the default behavior if i do not specify dependent cheers hajo,['ruby-on-rails'] +166327,numpy array to base64 and back to numpy array python i am now trying to figure out how i can recover a numpy array from base64 data this question and answer suggest it is possible reading numpy arrays outside of python but an example is not givenusing the code below as an example how can i get a numpy array from the base64 data if i know the dtype and the shape of the arrayimport base64import numpy as npt nparange25 dtypenpfloat64s base64b64encodetr base64decodestringsq i want a python statement to set q as a numpy array of dtype float64 so the result is an array identical to t this is what the arrays encoded and decoded look like t nparange25dtypenpfloat64 tarray 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 sbase64b64encodet sadwpwabaceaqqabrageacqacbaikakqaczakeaqqacxalkawqadfamkazqadranua2qaddaoea r base64decodestrings rx00x00x00x00x00x00x00x00x00x00x00x00x00x00xf0x00x00x00x00x00x00x00x00x00x00x00x00x00x08x00x00x00x00x00x00x10x00x00x00x00x00x00x14x00x00x00x00x00x00x18x00x00x00x00x00x00x1cx00x00x00x00x00x00 x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x0x00x00x00x00x00x001x00x00x00x00x00x002x00x00x00x00x00x003x00x00x00x00x00x004x00x00x00x00x00x005x00x00x00x00x00x006x00x00x00x00x00x007x00x00x00x00x00x008 q nparray the reason i am asking is because i am working on a project where i would like to store a lot of numpy arrays in a mysql database in an app powered by djangousing this django snippet i can store base64 data in a textfield i want to write the arrays to the database as base64 instead of converting the arrays to a string of unicodethanks for your help,['python'] +166328,cannot compile a simple qt program in mt mode as opposed to md in visual studio 2010 i am trying to compile using mtd in visual studio 2010 instead of mdd so that the dlls are packaged in and i would not need to thistribute them with my exe but i keep getting fatal error lnk1169 one or more multiply defined symbols found during compilation mdd compiles fine but does not work without msvcp100dll on other computersi am using a static build of qt and i am trying to build the default qt program that comes with the vs addinis there another way to force the linker to compile statically all i am trying to do is thistribute a qt program as an exe without dllshere is the build log1clcompile1 all outputs are uptodate1 cooltest1cpp1 moc cooltest1cpp1 maincpp1 generating code1 all outputs are uptodate1 qrc cooltest1cpp1msvcrtlibmsvcr100dll error lnk2005 public thiscall stdexceptionexceptionchar const const 0exceptionstdqaeabqbdz already defined in libcmtlibstdexcptobj1msvcrtlibmsvcr100dll error lnk2005 public virtual thiscall stdexceptionexceptionvoid 1exceptionstduaexz already defined in libcmtlibstdexcptobj1msvcrtlibmsvcr100dll error lnk2005 public thiscall stdexceptionexceptionclass stdexception const 0exceptionstdqaeabv01z already defined in libcmtlibstdexcptobj1msvcrtlibmsvcr100dll error lnk2005 memmove already defined in libcmtlibmemmoveobj1msvcrtlibmsvcr100dll error lnk2005 strncmp already defined in libcmtlibstrncmpobj1msvcrtlibmsvcr100dll error lnk2005 isupper already defined in libcmtlib ctypeobj1msvcrtlibmsvcr100dll error lnk2005 isalpha already defined in libcmtlib ctypeobj1msvcrtlibmsvcr100dll error lnk2005 isdigit already defined in libcmtlib ctypeobj1msvcrtlibmsvcr100dll error lnk2005 isspace already defined in libcmtlib ctypeobj1msvcrtlibmsvcr100dll error lnk2005 malloc already defined in libcmtlibmallocobj1msvcrtlibmsvcr100dll error lnk2005 free already defined in libcmtlibfreeobj1msvcrtlibmsvcr100dll error lnk2005 control87 already defined in libcmtlib ie87 obj1msvcrtlibmsvcr100dll error lnk2005 clearfp already defined in libcmtlib ie87 obj1msvcrtlibmsvcr100dll error lnk2005 strncpy s already defined in libcmtlibstrncpy sobj1msvcrtlibmsvcr100dll error lnk2005 strcpy s already defined in libcmtlibstrcpy sobj1msvcrtlibmsvcr100dll error lnk2005 realloc already defined in libcmtlibreallocobj1msvcrtlibmsvcr100dll error lnk2005 public thiscall stdexceptionexceptionchar const const int 0exceptionstdqaeabqbdhz already defined in libcmtlibstdexcptobj1msvcrtlibmsvcr100dll error lnk2005 exit already defined in libcmtlibcrt0datobj1msvcrtlibmsvcr100dll error lnk2005 errno already defined in libcmtlibdosmapobj1msvcrtlibmsvcr100dll error lnk2005 abort already defined in libcmtlibabortobj1msvcrtlibti instobj error lnk2005 private thiscall type infotype infoclass type info const 0type infoaaeabv0z already defined in libcmtlibtypinfoobj1msvcrtlibti instobj error lnk2005 private class type info thiscall type infooperatorclass type info const 4type infoaaeaav0abv0z already defined in libcmtlibtypinfoobj1link warning lnk4098 defaultlib msvcrt conflicts with use of other libs use nodefaultliblibrary1cusersusernamedocumentsvisual studio 2010projectscooltest1cooltest1exe fatal error lnk1169 one or more multiply defined symbols found11build failed,['c++'] +166331,why whole structure can not be compared in c yet it can be copied why whole structure can not be compared in c yet it can be copiedin other words why comparison in below program does not work it does not print stringinclude stdiohinclude stringhint mainvoid struct emp char n20 int age struct emp e1david23 struct emp e2e1 ife2 e1 printfthe structures are equal return0,['c'] +166339,when does overloaded false operator ever gets executed and what is it good for i have been searching for actual working code where an overloaded false operator actually gets executedthis question whats the false operator in c good for is somewhat the same but the accepted answer links to an url which is returning a 404 error i have also looked at how does operator overloading of true and false work and some other questionswhat i have found in almost all answers is that false only gets executed when you use a short circuited and like x y this is evaluated as tfalsex x tx yok so i have the following code the struct contains an int and considers itself true if the int is greater than zeropublic struct mystruct private int i public mystructint i i i public static bool operator truemystruct ms return ms i 0 public static bool operator falsemystruct ms return ms i 0 public override string tostring return this itostring now i would hope the following program will execute and use the overloaded false operatorclass program private static void main mystruct b1 new mystruct1 to be considered true mystruct b2 new mystruct1 to be considered false consolewritelineb1 b2 consolewritelineb2 b1 however it does not even compile it says it cannot apply operator to operands of type mystruct and mystructi know i can implement an overload of the operator so let us do that the must return a mystruct so i can not make it return a boolpublic static mystruct operator mystruct lhs mystruct rhs return new mystructlhs i rhs inow the code does compile its output is 1 and 1 so the result of b1 b2 is not the same as that of b2 b1if i debug the code i see that b1 b2 first executes the false operator on b1 which returns false then it performs the operator on b1 and b2 which performs a bitwise and on 1 and 1 resulting in 1 so it indeed is first checking if b1 is falsethe second expression b2 b1 first executes the false operator on b2 which returns true combined with the fact i am using short circuiting it does not do anything with b1 and just prints out the value of b2so yes the false operator is executed when you use short circuiting however it does not execute the true or false operator on the second argument but instead executes the overloaded operator on the operandswhen can this ever be useful or how can i make my type so that it can check if the two variables both are true,['c#'] +166344,python compute list difference in python what is the best way to compute the difference between two listsexamplea 1234b 25a b 134b a 5,['python'] +166348,referencing variables from containing scope when using create function as a closure php using true closures we can dofunction fooref infn function use ref ref 42 infnthus modifying the reference without having to pass it in the call to infnif we replace infn function with infn create functionis there any simple and clean way to do the same thing refer to a variable of the containing scope by reference without explicitly passing it into infn,['php'] +166351,unexpected t variable expecting t function i am expecting this to be a basic syntax error i overlooked but i cannot figure it outin a php script i keep getting the following errorparse error syntax error unexpected t variable expecting t function in pathscriptsusersdatabase connectionphp on line 4this occurs when my script to connect to the database is called with an include once i stripped my script down to the most basic code leaving in what is required by other code and it still is calling this errorphp class userdatabaseconnection connection sqlite openpathdatauserssqlite 06 public function lookupuserusername rest of my code udb new userdatabaseconnectioni have struggled with this for a while and just wondered if anyone else could spot somewhere i went wrong,['php'] +166352,executing two java preparedstatements with one connection style choice okay i have realized that i really have asked way too many questions without contributing back to the community but i want your opinions on this say if i haveprivate void closeallresultset rs preparedstatement ps connection con if rs null try rsclose catch sqlexception e if ps null try psclose catch sqlexception e if con null try conclose catch sqlexception e and i wanted to do several operations on my mysql database using a single connection is it better to writeconnection con preparedstatement ps nullresultset rs nulltry ps conpreparestatement rs psexecutequery if rsnext catch sqlexception e systemerrprintlnerror e finally closeallrs ps nulltry ps conpreparestatement rs psexecutequery if rsnext catch sqlexception e systemerrprintlnerror e finally closeallrs ps conorconnection con preparedstatement ps nullresultset rs nulltry ps conpreparestatement rs psexecutequery if rsnext rsclose psclose ps conpreparestatement rs psexecutequery if rsnext catch sqlexception e systemerrprintlnerror e finally closeallrs ps coni consider better to mean either safer clearer more concise or more robust i am not sure whether the latter will always close whichever prepared statements and result sets are open whenever it encounters an exception while i believe it does look more concise but the former looks nicer since it is more consistent yet it puts more overhead since it uses more try finally blocksi realize that java 7s automatic resource management part of project coin will force me to lean to the former since the resources used in the header are implicitly final in the body however i have quite some time before i have to worry about revising my code to adapt it to arm and be able to remove the boilerplate code so the question still stands of the above two styles which would be better practice if they both do the expected behaviors will the latter give me a noticeable performance boost that would excuse the uglier style,['java'] +166369,synthesize musical notes with piano sounds in python i would like to have a python implementation of a musical instrument library for instance a piano object that i can use to convert a list of notes and a duration into sound for instance something likeimport pianopn pianopnplaynote note note durationdoes something like this exist for python 27 i would like to implement it if it does not i currently have something that uses audiere but its just sine waves so it sounds horrible is there any way to hook into a midi piano or something like that i am using windows 7 are there any implementing steps that i might not expect,['python'] +166379,fast checking or limiting of thread memory usage in net i have seen some thiscussions similar to this question but nothing that truly answers the issue i am facingi am working on a c application where the software behavior can be customized through interpreted scripts each script is running on a different child thread of the c app i am using the jint javascript interpreter to run the scripts but my question is equally valid for any other circumstance under which a thread could behave dynamically in a net application so far this is working great but i need to ensure that the application behaves itself in case of a bad script that could cause the application to run out of heap space i need the ability to detect and stop any thread that is eating up too much memory conceptually this could seen as similar to a web browser determining if javascript on a page is taking too long or too much memory to execute the trouble is i have not been able to determine if there is any way to do such in netis there some way i can either place a hard limit on the amount of memory a thread can utilize or quickly check the threads memory utilization from a parent thread i am not concerned with stack overflow within the thread just heap spacethe obvious solution of course would be to split the interpreting into seperate processes rather than seperate threads but that would incur a significant performance hit for my application since these scripts modify the software behavior and thus are intended to be tightly coupled applicationlevel monitoring also wouldnt be ideal since it wouldnt provide information on which script is not behaving itself also a slow method meant for debugging would not work since the scripts are meant to allow for rapid modification of the software rather than having to build test and redeploy i merely need some reasonably fast way to detect a thread that is eating too much memory so i can kill and ignore its scriptthanks,['c#'] +166393,thisable firefoxs autofill is it possible to thisable firefoxs autofill feature without thisabling autocompletei know i can do thisautocompleteoffbut i do not want to thisable autocomplete just the autofillfirefox is populating some of our hidden fields which are meant to be emptythis is mostly a problem when the user refreshes the page the form fields are repopulated with values from prerefresh an example of this being a problem is oldschool placeholder where we populate the field with a value and remove it on submit the value is repopulated on refresh and we do not know if it is the placeholder or use value,['html'] +166406,clear the current content from a frame i was wondering how you are meant to remove the current content from a frame and make it so it is not thisplaying anything also i would like to know how you are supposed to remove all the history from the frame as well,['c#'] +166408,can you layer pictures on top of each other on a webpage i want to build a website that is a dress up game where you can click on different accessories and they will layer on top of each otherbecause it is a little difficult to describe i found these examples which should hopefully highlight what i am trying to dothis is the closest website that i have found but i cannot seem to find the code that is figuring out how the images should lay on top of each othersimilar to this ios princess gamei have hundreds of different accessories as images right now and similar to the game above i need to support being able to choose more than one so i need a solution that does not require me to presave an image of every permeation of accessory combinations on top of the princess as that would be millions of predefined imagesideally i would like a javascriptjquery or css solution but will take any suggestions that people have flash suggestions would be helpful as wellso my questions arehow is the example website above lining up all of the images on top of each other i cannot seem to find any css or javascript code that is doing itare there any suggestions on how to build this type of website links tutorials or code examples would be great,"['jquery', 'html', 'css']" +166431,twotone font coloring in css i really like the look of twotone buttons and fonts i am thinking of when the top half of the font is one color and the bottom half is a variation on the same color for an example see most of the buttons on an iphone or the logo here is it possible to recreate this effect in css alternately is there a free tool i can use to generate fonts that look like this,['css'] +166451,how to hide the horizontal line at the bottom of each item in android listview it seems that there is a horizontal line by default at the bottom of each item in android listview my problem is how to let the line not thisplay,['android'] +166456,determine accurate iphone battery level i am trying to get the battery levelstate as follows void viewwillappear bool animated self viewwillappearanimated battery state self batterystatus nsnotificationcenter defaultcenter addobserverself selectorselectorbatterystatus nameuidevicebatteryleveldidchangenotification objectnil nsnotificationcenter defaultcenter addobserverself selectorselectorbatterystatus nameuidevicebatterystatedidchangenotification objectnil voidbatterystatus nsarray batterystatus nsarray arraywithobjects battery status is unknown battery is in use thischarging battery is charging battery is fully charged nil if uidevice currentdevice batterystate uidevicebatterystateunknown textviewstatus settextbatterystatus objectatindex0 nslog batterystatus objectatindex0 else nsstring msg nsstring stringwithformatbattery charge level 02fn uidevice currentdevice batterylevel 100batterystatus objectatindexuidevice currentdevice batterystate textviewstatus settextmsg nslog msg however i am not getting changes in the battery level and the values are not exact void viewwillappearboolanimated uidevice device uidevice currentdevice devicebatterymonitoringenabled yes textviewstatustext nsstring stringwithformat2f devicebatterylevel device addobserverself forkeypathbatterylevel options0x0 contextnil super viewwillappearanimated void viewdidthisappearboolanimated uidevice device uidevice currentdevice devicebatterymonitoringenabled no device removeobserverself forkeypathbatterylevel super viewdidthisappearanimated voidobservevalueforkeypathnsstring keypath ofobjectidobject changensdictionary change contextvoid context uidevice device uidevice currentdevice if object isequaldevice keypath isequalbatterylevel nslogbattery level fdevicebatterylevel textviewstatustext nsstring stringwithformat2f devicebatterylevel any ideas,"['objective-c', 'iphone']" +166468,how do i move the last item in a list to the front in python i searched thoroughly but cannot find anything relating to this exact specific i have a lista two three onei want to move one to the front so it becomesa one two threethe thing is it could be any amount of numbers in the list assume there is no way of knowing whether there will be 50 items or 3,['python'] +166485,javascript new keyword on function returning array i was experimenting with the new keyword and i cannot find an explanation for this behaviorlet us say we have a function returning an integerin firebug function x return 2 x2 new xx but if the function returns an array function y return 2 y2 new y2why is that,['javascript'] +166490,how to open a pdf stored either in resraw or assets folder i am going to show a pdf in my application and the pdf has to be bundled with the applicationwhat is a good way to do thisi have read that it might be possible to do this by adding the pdf file to a resraw folder and read it from there but i get project errors when i put the pdf file thereso i tried to put the pdf file in the asset folder of the project and it gave no errorsthis is how i have tried to show the pdffile pdffile new fileresrawfilepdfuri path urifromfilepdffileintent intent new intentintentaction viewintentsetdataandtypepath applicationpdfintentsetflagsintentflag activity clear topany ideas or suggestionsthanks in advance,['android'] +166492,fragmentactivity junit testing me used fragment of android compatibility package using the androidsupportv4jar but i cannot do the junit test on this my main fragmentactivity class is declared as follows public class myactivityclass extends fragmentactivitythen in my test project public class myactivityclasstest extends activityinstrumentationtestcase2myactivityclass public myactivityclasstest supercomandroidmyproject myactivityclassclass override protected void setup throws exception supersetup public void testpreconditions public void testnotnull but when i run as android junit test produce failedtocreatetestsrunnerjunit3failure trace javalangruntimeexception exception during suite constructionat androidtestsuitebuildertestsuitebuilderfailedtocreateteststestsuiteconstructionfailedtestsuitebuilderjava239at javalangreflectmethodinvokenativenative methodat androidtestandroidtestrunnerruntestandroidtestrunnerjava169at androidtestandroidtestrunnerruntestandroidtestrunnerjava154at androidtestinstrumentationtestrunneronstartinstrumentationtestrunnerjava430at androidappinstrumentationinstrumentationthreadruninstrumentationjava1447caused by javalangreflectinvocationtargetexceptionat comandroidmyprojecttestmyactivityclasstestinitmyactivityclasstestjava28at javalangreflectconstructorconstructnativenative methodat javalangreflectconstructornewinstanceconstructorjava446at androidtestsuitebuildertestmethodinstantiatetesttestmethodjava87at androidtestsuitebuildertestmethodcreatetesttestmethodjava73at androidtestsuitebuildertestsuitebuilderaddtesttestsuitebuilderjava263at androidtestsuitebuildertestsuitebuilderbuildtestsuitebuilderjava185at androidtestinstrumentationtestrunneroncreateinstrumentationtestrunnerjava336at androidappactivitythreadhandlebindapplicationactivitythreadjava3982at androidappactivitythreadaccess2900activitythreadjava119at androidappactivitythreadhhandlemessageactivitythreadjava1901at androidoshandlerthispatchmessagehandlerjava99at androidoslooperlooplooperjava123at androidappactivitythreadmainactivitythreadjava4363at javalangreflectmethodinvokenativenative methodat comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava860at comandroidinternaloszygoteinitmainzygoteinitjava618at dalviksystemnativestartmainnative methodcaused by javalangnoclassdeffounderror comandroidmyprojectmyactivityclass 19 morewhen i changed myactivityclass to extends activity it worked fine myactivityclass extends activityme used the same androidsupportv4jar in my both test and main project,['android'] +166506,what is aspnet webforms equivalent of aspnet mvcs viewdata what are the conventions used in aspnet webform for passing data to view from code behindin aspnet mvc for example viewdata is a key value collection or a strongly typed class object so what do people do in case of aspnet webformi know we can create a property or member of a class or add stuff to pageitems but what else besides that,['asp.net'] +166527,how to find current base execution directory in groovy or java i have got a little script i am using a paramter to pass in the current execution directory but would like to make it a little more robusthow does one find out the base execution directory,['java'] +166532,assigning string literals to char is the following code legal deprecated or illegal in c0xchar p foobari originally asked this question here as a comment,['c++'] +166574,what is the best way to make a breadcrumb with code igniter i wonder what a best way to make a breadcrumb with code igniter1 retrieve the strings with urlexample thisurisegment22 do you know another way i would really like to have your opinion,['php'] +166577,why does hibernate insert a parent row with a foreign key without inserting the child row i am hoping someone has run into this problem before and can help me out basically hibernate is inserting a parent row with an id pointing to a child row but not inserting that child row with the associated id which leaves the database in a bad state heres an example of the exception that is thrown when hibernate tries to load the improperly saved object27 jun 2011 135531380 error scheduler worker4 job defaultqueryscrubjobdetail threw an unhandled exception orgspringframeworkschedulingquartzjobmethodinvocationfailedexception invocation of method doit on target class x failed nested exception isorgspringframeworkormhibernate3hibernateobjectretrievalfailureexception no row with the given identifier exists xdataprovidertransaction60739703 nested exception is orghibernateobjectnotfoundexception no row with the given identifier exists comidologypersistdataprovidertransaction2this part of the application has three entitiesquery which is a parent of dataprovidertransactionreference and dataprovidertransactiondataprovidertransaction which is a child of query and a parent of dataprovidertransactionreferencedataprovidertransactionreference which has foreign keys pointing to dataprovidertransaction and queryhere are the mappingsfrom queryonetomanymappedby query cascade cascadetypepersist cascadetypemerge fetch fetchtypelazycascadeorghibernateannotationscascadetypesave updatejoincolumnname query idpublic listdataprovidertransactionreference getdataprovidertransactionreferencesfrom dataprovidertransactionmanytoonefetch fetchtypelazyjoincolumnname query idpublic query getqueryfrom dataprovidertransactionreferencemanytoonecascade cascadetypepersist cascadetypemerge fetch fetchtypeeagerjoincolumnname data provider transaction idcascadeorghibernateannotationscascadetypesave updatepublic dataprovidertransaction getdataprovidertransaction return mdataprovidertransactionthe schema looks like this leaving out the queries table since it has no foreign keysdata provider transaction field type null key default extra id bigint20 no pri null auto increment query id bigint20 yes mul null data provider txn refs field type null key default extra id bigint20 no pri null auto increment created at datetime yes null data provider transaction id bigint20 yes mul null query id bigint20 yes mul null so once were done running a query represented by the query object we save it using spring and hibernate using the followinggethibernatetemplatesaveorupdateaquerythe query is saved along with the associated dataprovidertransaction and dataprovidertransactionreference entities except that sometimes it saves a query and a dataprovidertransactionreference without the associated dataprovidertransaction it does put an id in the data provider transaction id but it points to a row that does not exist in the data provider transaction tablethe next step is to add a foreign key constraint to cause the problem to occur when we do the initial save rather than when we try to load the object laterwere using spring 256 hibernate 332 and mysql 50 i have seen the problem occur over the years with earlier versions of spring and hibernate thoughanyone ever seensolved this problem,"['java', 'mysql']" +166592,whats the right way to object orient an android program i have watched many tutorials now about how to program for android i have even started to create some programs myself however i noticed my programs all look like procedural ones while java should be working with object orientation i have been trying to fix this but i have found a problem the primary class of my program the one that is executed at the start of the application under comtestprogramw for example seems to be a mixture of screen and control layers at the same timeon all tutorials i found i see a visual object being recovered from the mainxml view for example a button this recovery indicates to me that this would be the control layer for treatment and just after this the object is registered to a listener of some sort in this case onclicklistener this should be done in the screen not in the control rightis this meant to be this way this main class under the w package is what the screen layer or the control one is this class the right place to do what i mentioned above is this done this way because the xmlbased interface is unable to register java listeners anyone knows a good place for me to go for references on how to oo for android,['android'] +166604,java how expensive is a method call i am a beginner and i have always read that it is bad to repeat code however it seems that in order to not do so you would have to have extra method calls usually let us say i have the following classpublic class binarysearchtre extends comparablee private binarytre root private final binarytre empty new binarytre private int count private comparatore ordering public binarysearchtreecomparatore order ordering order clear public void clear root empty count 0 would it be more optimal for me to just copy and paste the two lines in my clear method into the constructor instead of calling the actual method if so how much of a difference does it make what if my constructor made 10 method calls with each one simply setting an instance variable to a value whats the best programming practice,['java'] +166613,do you quote html5 attributes attribute quotes are optional in html5what are the proscons to quoting themidexample quotes optionalhref quotes optionalclassexample example1 quotes required due to spacehref quotes required due to signupdate added advantages based on the answersadvantages to quoting all attributesall editors can deal with it properlymore consistentbetter portability easier to change doctypeeasier to maintain esp if attributes might become emptyeasier to find and replace changescleaner doc if you think quotes improve readabilityadvantages to omitting optional quotesslightly reduced filesizecleaner doc if you prefer minimal text,['html'] +166641,what does this colon do in an enum declaration i did a search for this question thinking that somebody must have asked it before i did not turn up any results so if it has been please post the link and feel free to close the questioni ran across this code in eastlenum size type size type size t npos size type1 kmaxsize size type2 i have never encountered an enum declaration like that what does the do in this case,['c++'] +166643,android checkbox preference i cannot find any tutorials on checkbox preference i can use a listpreference but i cannot use checkbox preference for now i want that if user sets on the checbox a toast msg says true and if he sets it off the toast msg says false so far i have thispreferencesxml checkboxpreference androidtitleshow call ui androiddefaultvaluetrue androidsummaryshow call interface when clicking call button androidkeycheckboxpref editpreferencesjavapublic class editpreferences extends preferenceactivity string listpreference boolean checkboxpreference override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate addpreferencesfromresourcerxmlpreferences public void onstartintent intent int startid getprefs private void getprefs sharedpreferences prefs preferencemanager getdefaultsharedpreferencesgetbasecontext listpreference prefsgetstringlistpref nr1 checkboxpreference prefsgetbooleancheckboxpref true edit solution thanks to david cauntcheckboxpreference setonpreferencechangelistenernew preferenceonpreferencechangelistener public boolean onpreferencechangepreference preference object newvalue if newvaluetostringequalstrue toastmaketextgetapplicationcontext cb true toastlength shortshow else toastmaketextgetapplicationcontext cb false toastlength shortshow return true,['android'] +166647,where should i put external jar files when developing a web app i am developing a dynamic web application with java servletsjsp in eclipse i am trying to use an external jar i am using stringutils from apache commons and i am confused as to where i should put the jar lib webinflib and how do i need to configure my class path in eclipse i tried putting the jars in both of the aforementioned places and loading them to the classpath by clicking add jar in the project properties and both solution compile fine but give a runtime error like sosevere servletservice for servlet userlist threw exception javalangnoclassdeffounderror orgapachecommonslangstringutils at cs236369hw5dbmysqldbhandlerinsertmysqldbhandlerjava58 at cs236369hw5servletsuserlistdogetuserlistjava50 at javaxservlethttphttpservletservicehttpservletjava617 at javaxservlethttphttpservletservicehttpservletjava717 at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava290 at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava206 at orgapachecatalinacorestandardwrappervalveinvokestandardwrappervalvejava233 at orgapachecatalinacorestandardcontextvalveinvokestandardcontextvalvejava191 at orgapachecatalinacorestandardhostvalveinvokestandardhostvalvejava127 at orgapachecatalinavalveserrorreportvalveinvokeerrorreportvalvejava102 at orgapachecatalinacorestandardenginevalveinvokestandardenginevalvejava109 at orgapachecatalinaconnectorcoyoteadapterservicecoyoteadapterjava298 at orgapachecoyotehttp11http11processorprocesshttp11processorjava859 at orgapachecoyotehttp11http11protocolhttp11connectionhandlerprocesshttp11protocoljava588 at orgapachetomcatutilnetjioendpointworkerrunjioendpointjava489 at javalangthreadrununknown sourceso how do i load external jarsplease take note that i am not that familiar with how external jars are loaded in java the vm or how eclipse manages it all so i would appreciate detailed solutions,['java'] +166657,is there a heroku type hosting solution for pythonweb2py i am interested to know if there are any pythonweb2py hosting platforms similar to heroku for ruby on ralils something that is easily configurable and scalable,['python'] +166664,width of clickable area in listview w onlistitemclick i am trying to get my list items in a listview clickable at the moment they are clickable see my screenshot but they are only clickable within the rectangle the text takes upi am using protected void onlistitemclicklistview l view v int position long id for the clickable list itemshere is my listxmllinearlayout xmlnsandroid androidlayout widthwrap content androidlayout heightwrap contentlistview androidididandroidlist androidlayout widthfill parent androidlayout heightwrap contenttextview androidididandroidempty androidlayout widthwrap content androidlayout heightwrap content androidtextstringno favoritesand my rowxmllinearlayout xmlnsandroid androidlayout widthfill parent androidlayout heightwrap content androidorientationvertical textview androidididartist androidlayout widthfill parent androidlayout heightwrap content textview androidididsongtitle androidlayout widthfill parent androidlayout heightwrap content androidlayout alignparentrighttrue textview androidididalbum androidlayout widthfill parent androidlayout heightwrap content androidlayout alignparentrighttrue textview androidididplaytime androidlayout widthfill parent androidlayout heightwrap content androidlayout alignparentrighttrue textview androidididplaylistnum androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentrighttrue androidvisibilitygone linearlayoutand heres the screenshot examplenew users are not allowed to post images grumble have a hyperlinkin listxml the listview has androidlayout widthfill parent so it should be the full width of the screen all of the items in rowxml are also widthfill parent what am i missing,['android'] +166666,how do i validate that a certificate was created by a particular certification authority i have a windows certification authority that i am using to issue client authentication certificates via net c i have been able to successfully get it to issue certificates programmatically by calling the certification authoritys api through com i issue a new certificate when i set up a clientat runtime these clients attach the certificates to requests to my server how can i verify programmatically that an x509certificate2 was signed by the root certificate of my certificate authority and reject certificates signed by any other source,"['c#', '.net']" +166670,mvcminiprofiler results request giving 404 in aspnet mvc app i am trying to use the mvcminiprofiler in my aspnet mvc application i installed the latest nuget package and added all the code from the wiki page into application beginrequest application authenticaterequest and in my viewupon loading the page all of the mini profilers javascript files are being included and correctly downloaded from the server but when it attempts to get the results chrome showsget httplocalhost59269miniprofilerresultsid59924d7f98ba40fe9c4a6a163f7c9b08popup1 404 not foundi assume this is due to no routes being setup with mvc to allow for the miniprofilerresults however i cannot find a way to do that looking at the google code page their globalasaxcs file of their sample app has gone through several changes with one time using mvcminiprofilerminiprofilerregisterroutes a second using mvcminiprofilerminiprofilerinit and a third style which does nothing of the sort the previously mentioned two functions do not exist so i assume they have been phased outat this point i am unsure of how i can fix this error and use the profiler in my app any ideasmy globalasaxcs file looks likepublic class global systemwebhttpapplication protected void application beginrequest mvcminiprofilerminiprofilerstart protected void application authenticaterequestobject sender eventargs e only show profiling to admins if rolesisuserinroleconstantsadminrole mvcminiprofilerminiprofilerstopthiscardresults true protected void application startobject sender eventargs e arearegistrationregisterallareas registerroutesroutetableroutes public static void registerroutesroutecollection routes routesignorerouteresourceaxdpathinfo routesignorerouteresourceaspxpathinfo routesmaproute default route name controlleractionid url with parameters new controller home action index id parameter defaults,['c#'] +166676,c replacing part of string by start and end position i have a string and i want to replace a part of itthe tricky part is that that i cannot use regexreplace because i only know the start and end positions of the data in the stringfor example if the string looks like thisi love cats some more stuff here we dont know how much moreand i have start8 and end11 and i want to replace that part to whatever i need to this time lets say dogs so the new string will look likei love dogs some more stuff here we dont know how much morehow i could do that,['c#'] +166680,interesting behaviour of type decimal in c if we declare padding as const decimal the padding is not workingmymoney 12 and your money 120 how can this behavior be explainedclass program static void mainstring args decimal balance 12m const decimal constpadding 0m decimal padding 0m decimal mymoney decimalroundbalance constpadding 2 decimal yourmoney decimalroundbalance padding 2 consolewritelinemymoney 12 consolewritelineyourmoney 120,['c#'] +166681,typeoft may return null when using the typeof operator on type created through typebuilder the operator will return nulli am curious why this happens and how to prevent iti am starting to think this is a vs bug in the immediate window but i am not quite sureit is very easy to blame others firstok code to reproduce issue static void main assemblybuilder assemblybuilder appdomaincurrentdomaindefinedynamicassembly new assemblynamemyassembly assemblybuilderaccessrunandsave modulebuilder modulebuilder assemblybuilderdefinedynamicmodulemymodule typebuilder typebuilder modulebuilderdefinetypemytype typeattributespublic typeofarraylist arraylist o arraylistactivatorcreateinstancetypebuildercreatetype consolewritelineogettypename if you put a breakpoint after the variable o and type typeofmytype in the vs immediate windows youll get the issue,['c#'] +166683,calling rngcrypto from coms dotnet class from php i am attempting to call rngcryptoserviceprovidergetbytes from php via the com layer i can get it to connect to the class but every time i call the method i get one of two errors relating to the parameter i think it has something to due with the fact that getbytes takes a fixed size byte array by reference since php does not support fixed sized strings that is where it gets interestingerror 1util new dotnet mscorlib systemsecuritycryptographyrngcryptoserviceproviderdata new variantstr repeatchr46 size vt ui1 vt arrayutilgetbytesdataerror 0x80070057 the parameter is incorrectwhich is thrown by the getbytes lineif i do not use a variant but just use a plain string i still get the same errorhowever if i pass in an array like sodata arrayutilgetbytesdataparameter 0 type mismatchso i think the variantstring approach is the correct one as it passes the parameter type check but i just cannot figure out how to get it working the c interface to the method ispublic override void getbytes byte datathanks,"['php', '.net']" +166715,programming languages that compile into cc source i am using coffeescript to make javascript development easier it is a language with clean syntax that compiles into javascriptso what are the established programming languages that compile into cc source code to simplify syntax andor enhance functionality,"['c++', 'c']" +166723,how do i render nice desktop notifications from java i am writing this very basic j2se application which alerts the user with some info every now and then currently i am using the systemtray and trayicon classes to show notifications but i am not really pleased with that it does not allow me to tweak the notifications nor gives them a good lookso does anyone know an easy to use library to generate nice notificationsbtw i will be porting to linux ubuntu to but will be using notifyosd there which is exactly what i need,['java'] +166735,ruby gemspec dependency is possible have a git branch dependency is possible have a git branch dependency inside mygemgemspeci am thinking something similar to the followinggemadd runtime dependency oauth2 git lgsoauth2git but it does not workany ideasthanks in advance,['ruby'] +166746,webview does not seem to get destroyed after leaving activity i have got an activity with a webview looks like the webview does not get destroyed along with the activity to demonstrate i have created an html page which runs a timer that loads an image resource every few seconds the script continues executing after the activity is destroyedpublic class mywebviewactivity extends activity private webview mwebview override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutthe layout mwebview webviewfindviewbyidridwebview mwebviewgetsettingssetjavascriptenabledtrue mwebviewgetsettingssetbuiltinzoomcontrolstrue mwebviewsetwebviewclientnew embeddedwebviewclient mwebviewloadurltest url private class embeddedwebviewclient extends webviewclient override public void onloadresourcewebview view string url superonloadresourceview url if configdebug logvtag onloadresource url so the above just prints a log statement whenever onloadresource is called heres the javascript in the test html pagehtml head script typetextjavascript function load setintervaldoit 30 function doit image1 new image150 20 image1src abc mathfloormathrandom100 png script head body onloadload bodyhtmlthe above just creates an image resource on the timer interval to trigger the onloadresource method in embeddedwebviewclientso yeah i can see in logcat that the messages keep printing after leaving the activity do we have to shut down the webview somehow maybe this is the issue described hereif it is a known issue should it have been documented in the api docsnote running this on android 234 nexus sthanks,['android'] +166754,how do i convert paypals hhmmss dd m y pstpdt to a c utc datetime i would like to log a payment date in this format in a sql server databaseupdate instinct was right on this one found a solution here verifying of course if paypal ever moves out of the west coast i will be in trouble is there a better way to parse this maybe with timezonepublic static datetime convertpaypaldatetimestring paypaldatetime accept a few different date formats because of pstpdt timezone and slight month difference in sandbox vs prod string dateformats hhmmss m dd y pst hhmmss m dd y pst hhmmss m dd y pdt hhmmss m dd y pdt datetime outputdatetime datetimetryparseexactpaypaldatetime dateformats new cultureinfoenus datetimestylesnone out outputdatetime convert to local timezone outputdatetime outputdatetimeaddhours3 return outputdatetimewait a sec that code above is completely wrong for me i am on the west coast ideally this should be updated to send the date to a proper utc datetime and handle any time zone also the code above does not handle pdt properly if converted to utcupdate2 apparently at least in previous versions the sandbox would return feb while the live returns feb lol someone save meupdate3 link to regex version but debugging could be an issue regex does not seem like the right way to do this there must be a better way summary converts a paypal datestring into a valid net datetime value summary param namedatevaluea string containing a paypal dateparam param namelocalutcoffsetthe number of hours from utcgmt the local time is ie the timezone where the computer isparam returnsvalid datetime value if successful datetimemindate if notreturnsprivate static datetime convertfrompaypaldatestring rawpaypaldate int localutcoffset regex pattern splits paypal date into time hhmmss date m dd y timezone pstpdt const string paypaldateregex timed12d2d2sdatemazaz35sd12syd4stzaz03 important above line broken over two lines for formatting rejoin in code editor example 054956 oct 18 2009 pdt 204822 dec 25 2009 pst match datematch regexmatchrawpaypaldate paypaldateregex regexoptionsignorecase datetime time date datetimeminvalue check to see if the regex pattern matched the supplied string if datematchsuccess extract the relevant parts of the date from regex match groups string rawdate datematchgroupsdatevalue string rawtime datematchgroupstimevalue string tz datematchgroupstzvalue create date and time values if datetimetryparserawtime out time datetimetryparserawdate out date add the time to the date value to get the datetime value date dateaddnew timespantimehour timeminute timesecond adjust for the pdt timezone pass 0 to localutcoffset to get utcgmt int offset localutcoffset 7 pdt utc7 pst utc8 if tz pdtpacific daylight time date dateaddhoursoffset else pacific standard time date dateaddhoursoffset 1 return date,['c#'] +166759,post build event execute powershell is it possible to set up a net project with a post build event to execute a powershell script i am using this script to generate some files also can i pass whether it is a debug or release build to script an example of this would be great,['c#'] +166784,why is pop faster than shift douglas crockford in javascript the good parts states that shift is usually much slower than pop jsperf confirms this does anyone know why this is the case from an unsophisticated point of view they seem to be doing pretty much the same thing,['javascript'] +166842,passing a constructor to arraymap how can i do something like thisvar a 1234amapdateconstructorthis code throws an error on google v8syntaxerror unexpected numberiam also triedamapdateconstructor dateprototypewith the same result,['javascript'] +166858,how expensive is using marshalbyrefobject compared to serialization in my azure web role code i have a customidentity class derived from systemsecurityprincipaliidentity at some point net runtime tries to serialize that class and serialization wouldnt work trying to resolve that i searched a lot and found this answer and tried to inherit my class from marshalbyrefobjectnow once my customidentity class inherits from marshalbyrefobject therere no serialization attempts anymore and my code works however i would like to know the performance implications of using marshalbyrefobject classmy code runs like this first the request comes to iis and is passed to the authentication code that creates an instance of customidentity and attaches that instance to http context then some time later the same http context is passed to the aspnet handler that accesses that customidentity instance at most once the customidentity object lives for the duration of request and is then destroyednow with serialization my customidentity would be serialized into a stream then deserialized from that stream into a new object with marshalbyrefobject there is no serialization but a proxy is created and the access will be marshaled via rpc to where the actual object resideshow expensive will using marshalbyrefobject be in this scenario which marshalbyrefobject or serialization will be more costly,"['c#', '.net']" +166876,why does everyone say dependency injection in aspnet webforms is hard when pagehandlerfactory and ihttphandlerfactory exist so i have a legacy webforms site and am working on making it easier to maintain chucking it away and rewriting it is not an optionioc is obviously one of the first things it got but this leaves me with the servicelocator pattern and a bad taste and the wondering of whether it could be done better various people i have talked to online and off tell me that i could do propertyinjection with an httpmodule that scans a page class for properties decorated with an inject attribute or similar but that sounds like a reflection hit cached but still on every request not appealingso i was looking at other options and came across systemwebihttphandlerfactory which has apparently been in the framework since v2 one can remove the default aspx handler and replace it with one that uses a custom implementation in httphandlers webconfig sectionso the people i have talked to are not dumb i thought i would ask here are there any gotchas with replacing the webforms pagehandlerfactory with an iocbased implementation it looks like it has both a createhandler and releasehandler method so lifestyle related memory leaks from the container keeping a reference to created components should not be a problem,['asp.net'] +166878,how to decode unicode raw literals to readable string if i assign unicode raw literals to a variable i can read its value s uu0421u043eu043eu0431u0449u0435u043du0438u0435 u043eu0442u043fu0440u0430u0432u043bu0435u043du043e suu0421u043eu043eu0431u0449u0435u043du0438u0435 u043eu0442u043fu0440u0430u0432u043bu0435u043du043e print s3434n12 34nn21234but when i have already assigned value to a plain not unicode string i can not s u0421u043eu043eu0431u0449u0435u043du0438u0435 u043eu0442u043fu0440u0430u0432u043bu0435u043du043e su0421u043eu043eu0431u0449u0435u043du0438u0435 u043eu0442u043fu0440u0430u0432u043bu0435u043du043e print su0421u043eu043eu0431u0449u0435u043du0438u0435 u043eu0442u043fu0440u0430u0432u043bu0435u043du043ehow can i decode and read it,['python'] +166884,javascript duplicate code detector i am looking out for a software that identifies duplicateredundant javascript code i found one such tool named clonedr but do not know how good it is i was looking out for similar open source tools please guide,['javascript'] +166902,how to install lxml on ubuntu i am having difficulty installing lxml with easy install on ubuntu 11when i type easy install lxml i getsearching for lxmlreading reading best match lxml 23downloading processing lxml23tgzrunning lxml23setuppy q bthist egg thistdir tmpeasy install7udqozlxml23eggthisttmpgacqgybuilding lxml version 23building without cythonerror binsh xsltconfig not found make sure the development packages of libxml2 and libxslt are installed using build configuration of libxslt in file included from srclxmllxmletreec2270srclxmletree defsh931 fatal error libxmlxmlversionh no such file or directorycompilation terminatedit seems that libxslt or libxml2 is not installed i have tried following the instructions at libxslt on ubuntu linuxphp and libxml on ubuntu linuxphp with no successif i try wget i getsuccessful connection info syst done pwd done type i done cwd 1 libxml2 done size libxml2sources2627targz done pasv done retr libxml2sources2627targz no such file libxml2sources2627targzif i try the other first i will get to configure prefixusrlocallibxslt withlibxmlprefixusrlocallibxml2 and that will fail eventually withchecking for libxml libraries 2627 configure error could not find libxml2 anywhere check i have tried both versions 2627 and 2629 of libxml2 with no differenceleaving no stone unturned i have successfully done sudo aptget install libxml2dev but this changes nothing,['python'] +166918,dynamically create and click a link with jquery i want to dynamically create an a hrefmailto element then click it all without modifying the pagei am trying thisa hrefmailtonbspaclickto no avail,"['javascript', 'jquery']" +166927,writing to a file from my wordpress plugin i have written a custom plugin for my wordpress site that relies on readingwriting from an xml data file within the plugin folder when i test this standard php code for file readingwriting it will let me createwrite to files located at the wpadmin level but not files within the plugin folder although it can read from bothfile testxml can write to this filefile plugins urlmyplugintestxml can read but not write to this file open the file to get existing contentcurrent file get contentsfileecho current append a new person to the filecurrent personjohn smithpersonn write the contents back to the filefile put contentsfile currenti get the following debug errorwarning file put contentshttplocalhostwp mysitewpcontentpluginsmyplugintestxml functionfileputcontents failed to open stream http wrapper does not support writeable connections in applicationsmamphtdocswp mysitewpcontentpluginsmypluginmypluginphp on line 53i am currently running this off a local mamp server but want a solution that will let me package and publish the plugin on any wordpress server what is the right approachthanks,['php'] +166934,how to get the properties of a mp3 file in c ia m programming a little media player with a song librarynow i need to get the properties of a mp3wma file like the artist name or the song durationwhat is the best way to get this information,"['c#', '.net']" +166965,match a hash created in c with sql i have a method used to generate a hashpublic static string getmd5hashstring input systemsecuritycryptographymd5cryptoserviceprovider x new systemsecuritycryptographymd5cryptoserviceprovider byte bs systemtextencodingutf8getbytesinput bs xcomputehashbs systemtextstringbuilder s new systemtextstringbuilder foreach byte b in bs sappendbtostringx2tolower return stostring i then save that hash in a varchar255 column knowing what the original input string was would it be possible to to arrive at the same hash value stored in the varchar255 column using sql 2005i have tried like crazy using different data types conversions and the hashbytes function but have not been able to get close example of my failed attempt select convertvarchar hashbytesmd5 convertvarbinary200 censored0,"['c#', 'sql']" +166966,weird json encoding using json encode i am using wordpress together with the json api plugin to generate responses to our other sitei have hit a really weird problem were using php 536 when i pass the following array to json encode it gives me this with json contenttype so the crap in the beginning in the above example it is 2609 and 0 in the end it changes depending on the size of the response more content higher hex number it also appears only when the amount of response is high enough so it works on small responsesfirst i thought it was the plugin but it works locally on two different machines mac os x and weve updated all packages on the vps debian apache nginx php to the latest versionsit is only thisplayed when sending the contenttype not when outputting the result with plain text instead of applicationjsoncharset get optionblog charsetif headers sent headerhttp11 200 ok true headercontenttype applicationjson charsetcharset trueecho resultcharset is set to utf8the google chrome console says resource interpreted as document but transferred with mime type applicationjsonso does anyone have a clue whats happening here,['php'] +166987,how to copy file from uncshare to local system i am stuck with this questioni have unc share i know account details which has fullaccess but it does not have access to my local systemi can get access to remote unc with var token defaultintptrvar context defaultwindowsimpersonationcontextlogonuser configusername configdomain configpassword 2 0 out tokencontext windowsidentityimpersonatetokentodo systemio operationsfilecopyremoteuncpathlocalpathtrue exception access is deniedcontextundoclosehandletokenbut i cannot access my local system during impersonation because account does not have access to ithow to copy file in this situation do i need to use something like buffer and turn onoff impersonation,"['c#', '.net']" +166993,conditional xor how come c does not have a conditional xor operatorexampletrue xor false truetrue xor true falsefalse xor false false,['c#'] +166999,linq lookahead iteration i am iterating thru a collection using a visitortype pattern and need to access the current and next item in the list at the moment i am doing it via an extension method like thispublic void visittitemthis ienumerabletitem thelist actiontitem titem visitor for i 0 i thelistcount 1 i if i thelistcount 1 visitorthelisti null else visitorthelisti thelisti 1 i was wondering whether there are otherbettermore elegant ways to achieve this at the moment i think i only need to have access to the current and next items in the list but i am wondering whether i may encounter situations where i may need to lookahead the next n items for example,['c#'] +167010,restkit mapping with rails 31 in rails 308 the json contains a root element with your model name for example my location modellocation city san diegoname mission valley ymca krause family skateparkpads required 0country united statesand the mapping provider looked directly for the location objectrkobjectmapping locationmapping rkobjectmapping mappingforclassrklocation class locationmapping mapkeypathid toattributelocationidobjectmanagermappingprovider setmappinglocationmapping forkeypathlocationnow when you upgrade to rails 310 the root node location is now removed by default and i am not sure how to configure the mapping provider without it i tried nil and looked for alternative methods but was unsuccessful do you know how to map this please help city san diego name mission valley ymca krause family skatepark pads required 0 country united states,['ruby-on-rails'] +167049,compilation warning no rule to process file for architecture i386 how can i resolve this warningwarnwarning no rule to process file project dirmyappmessagecellh of type sourcecodeobjjh for architecture i386,['objective-c'] +167072,fillafter and fillenabled not working in android view animation xml i am curious as to this behavior i am currently setting the two values in the anim xml androidfillenabledtrue androidfillaftertruehowever the transformation does not apply after the animation is done it always resets when i set it programmatically via code it does seem to work animationsetfillenabledtrue animationsetfillaftertrueso i am just curious how this should work as i would rather set it on the xml thanks,['android'] +167083,android listview in fragment i am trying to create a list of items which contains an image and some description for the image in each individual after which the list will be place in a fragment inside the application can anyone guide me to create it i am not too sure how can i do it without the listactivity,['android'] +167094,get 2 levels up from dirname file how can i return the pathname from the current file only 2 directories upso if i my current file url is returning themeincludesfunctionsphphow can i return themecurrently i am using return dirname file,['php'] +167103,how do i build a solution programatically in c how do i build a c solution programatically i should be able to pass the path of a solution and get the output messages or just build the solution how do i achieve this in c,['c#'] +167109,can i have gdb break on readwrite from an address possible duplicatecan i set a breakpoint on memory access in gdb i have a specific location in memory that is getting corrupted and i would like to be able to see exactly when things write to that location is there any way that i can make gdb break on memory access to that particular address,"['c++', 'c']" +167118,how to parse a json input stream i am using java to call a url that returns a json objecturl new urlmy urlurlinputstream urlopenconnectiongetinputstreamhow can i convert the response into string form and parse it,"['java', 'android']" +167127,accept a range of numbers in the form of 05 using pythons argparse using argparse is there a way to accept a range of numbers and convert them into a listfor examplepython examplepy range 05is there some way input a command line argument in that form and end up withargsrange 012345and also have the possibility to input range 2 2,['python'] +167135,tls issue when sending to gmail through javamail turns out that javamail is a bit more frustrating than i thought it would be i have looked at several examples online on how to send a simple smtp email through gmails servers but not through ssl after trying several different examples of code i keep concluding to the same example exception when i call transportconnect i keep getting this stack trace exception in thread main comsunmailsmtpsmtpsendfailedexception 530 570 must issue a starttls command first l10sm302158wfk21 at comsunmailsmtpsmtptransportissuesendcommandsmtptransportjava2057 at comsunmailsmtpsmtptransportmailfromsmtptransportjava1580 at comsunmailsmtpsmtptransportsendmessagesmtptransportjava1097 at sendemailmainsendemailjava47can someone please tell me what i should add or do to fix thishere is my code properties props new properties propsputmailtransportprotocol smtp propsputmailhost smtpgmailcom propsputmailuser propsputmailpassword blah propsputmailport 587 session mailsession sessiongetdefaultinstanceprops null transport transport mailsessiongettransport mimemessage message new mimemessagemailsession messagesetsubjectthis is a test messagesetcontentthis is a test textplain messageaddrecipientmessagerecipienttypeto new internetaddress transportconnect transportsendmessagemessage messagegetrecipientsmessagerecipienttypeto transportclose,['java'] +167145,html5 header element not thisplaying background image i am working on a new html5 template i am using the headerheader element on the page with a simple logo background imageheader width100 height100px backgroundurldevacnimgheaderlogobgjpg 45px center norepeat dev page i can see the background image in pc chrome pc ff4 and on mac ff5 however it does not thisplay in ie6 ie7 or ie8and when i open the developer tools in ie8 from some reason there is no opening header element tag in the code inspector just the header closing tag does ie not recognize the header element even if i have properties defined in the stylecss located,"['html', 'css']" +167166,will cursor be still alive after database is closed my code is like belowcursor getresults sqlitedatabase db dbhelpergetreadabledatabase cursor c qbquerydb projection null null null null null dbclose return cmy question is after dbclose is executed is the cursor c still alive and navigablethanks,['android'] +167170,can deriving a class from enable shared from this increase performance make shared is more performant than separately calling new and creating a shared ptr because make shared allocates space for the reference count and weak count in the same memory block as the client object instance effectively giving the shared ptr most of the performance benefits of an intrusive ptrenable shared from this gives a shared pointer without having a reference to any shared pointer therefore things like the reference and weak count have to be somehow accessible from inside the client object therefore it would be sensible for enable shared from this to cause an intrusive count similar to make sharedhowever i have no idea how something like that might be implemented and i am not sure i would follow what was going on in there even if i look at the actual sourcewould it make sense then for performance reasons to tag my class with enable shared from this if i know it is only ever going to be used as a shared ptr and never as a raw object,['c++'] +167173,best practice for storing and updating external api passwords i have a aspnet c application that needs to connect to an external api using webservices every 5 minutes the requirements of the external webservice are as followsusername and password are requiredi must transmit the username and password with each webservice requestpasswords expire every 90 days and must be changed prior to the expiration datepasswords cannot be changed manually by human my application must connect to a separate password change webservice to change the passwordmy application must generate each new password based on a set of rulespasswords can never be reusedssl certificates and firewall ip restrictions are requiredi have built all of the previous but i currently have one issue what is the best practice for storing the current and historical passwords obviously storing the plaintext password is a bad solution i need to be able to have my webservice read the password and transmit it with each request i also need to be able to access all of the historical passwords to make sure that my newly generated password is not a duplicateideally i would like to store each encrypted password in my database and decrypt it whenever i need to call the webservice is there a best practice i should be following should i encrypt each password using microsoftpracticesenterpriselibrarysecuritycryptographycryptographerencryptsymmetricnote unfortunately i have no access to change the way the external api functions i must follow the rules provided,"['c#', 'asp.net']" +167181,alternative to captcha i have a simple reg form name email password on my website and im looking to implement some sort of antibotspam protection captcha seems like a very long winded way plus they really annoy me when i see them on sites has anybody an alternative method to protecting against spam which is lightweight and simply integrated,"['php', 'javascript']" +167186,php string constants overuse i have two particular cases where i thisagree with a coworker whether constants should be used or not we use a homemade framework working roughly like symfony 1xinitial code was in a routing php config file for routing like this oneroutermapsome url arraymodule some module action some actionroutermapsome other url arraymodule some module action some action etcthe coworker changed it toroutermapsome url arraymodule some module action some actionroutermapsome other url arraymodule some module action some action in constantsphp filedefinemodule moduledefineaction actionimo this is constant overuse if the concept of module or action is ever renamed it would have to be renamed in the entire code either written as a string or a constant plus the defined constant names above have no very specific meaning favoring naming collisionsconfusionsinitial code exampleif isset sessionunid isset sessionlogin modified by the coworkerif isset sessionunid isset sessionlogin in a constantsphp filedefineunid uniddefinelogin loginin our application those session vars names unid and login are clearly unlikely to change nonetheless if declaring constants was really a good practice here i would suggest at least more precise names for example fieldname unid and fieldname loginis introducing those constants really relevant that is naming should just be improved or as i guess completely useless thankseditafter a few months here are a few incredible lines from the constantsphp filei definitely find this a completely useless mess similar to this dailywtf post too many constants kills constantsdefinepost postdefineget getdefineproject projectdefineapplication applicationdefinemodule moduledefineaction actiondefineid iddefineslug slugdefinecontroller controllerdefinecontent contentdefineajax ajaxdefineexecute executedefineformat formatdefinebase href constant basehrefdefineunid uniddefineusername usernamedefinepassword passworddefinetemplate templatesdefineunsecure unsecuredefinemode modedefinemessage messagedefinetemporary session temporary sessiondefineerrormessage errormessagedefinestart from startfromdefinecount count and so on,['php'] +167192,ansi c utf8 problem first i develope an independent platform library by using ansi c not c and any non standard libs like ms crt or glibc after a few searchs i found that one of the best way to internationalization in ansi c is using utf8 encodingin utf8strlens always counts the number of bytesmbstowcsnulls0 the number of characters can be countedbut i have some problems when i want to random access of elementscharacters of a utf8 stringin ascii encodingchar get charchar assci str int n it is very fast return assci strnin utf1632 encodingwchar t get charwchar t wstr int n it is very fast return wstrnand here my problem in utf8 encoding what is the return type because sizeofutf8 char is 8 or 16 or 24 or 32 get charchar utf8str int n i can found nth character of string by using for but it is too slow what is the best waythanks,['c'] +167200,gui interface for sqlite data entry in python i am making a simple sqlite database for storing some nonsensitive client information i am very familiar with pythonsqlite and would prefer to stick with this combo on this project i would like to create an simple gui interface for data entry and searching of the database something very similar to what ms access provides i want my wife to be able to entersearch data easily so phpmyadmin style things are out of the questioni understand i could just give in and get ms access but if reasonbly possible would rather just write the code myself so it will run on my computers nix and is flexible so i can later integrate it with a web application and our smart phonescan you developers recommend any interfacespackagesetc preferably pythonic that can accomplish this with reasonable easethanks,['python'] +167210,rails routing root to i know how to set the routes root of my rails app to a controller and an actionbut how to add an idpagesshow1 should be the roothow do i set this,"['ruby-on-rails', 'ruby']" +167244,how does one use delayed job to make an rails 30 actionmailer run asynchronously encountering argumenterrors i am trying to delay a notification email to be sent to users upon signing up to my app the emails are sent using an actionmailer which i call initmailer the way i am trying to delay the jobs is using collectiveideas delayed job job to do this you can see that i specify handle asynchronously after defining the method initial emailclass initmailer actionmailerbase default from def initial emailuser user user url mailto useremail subject welcome to my website end handle asynchronously initial emailendhowever i encounter an argument error in my log file delayed joblogclassinitial email failed with argumenterror wrong number of arguments 1 for 0 5 failed attemptsfor your information the email is sent in a controller using the lineuser initusernewparamsinit userinitmailerdelayinitial emailuseradditionally when i set up my code without the delay the emails were sent out without problem except for the fact that it slowed down my app waiting for gmail serverswhere is causing the errors here how can i get the delayed mail to send properly,['ruby-on-rails'] +167255,datetime datatype in java which data type can i use in java to hold the current date as well as time i want to store the datetime in a db as well as having a field in the java bean to hold thatis it javautildate,['java'] +167258,how to go back to a break point during debugging i am working in aspnet and debugging an applicationsometimes there are scenarios in which i need to go back to a break point that i have passed is there any way to go back to that break point i am debugging using f5 and f10 and press shiftf5 to stop debuggingi searched on google but not finding the required answerplease guide me regarding this i will be thankful,"['c#', 'asp.net']" +167279,when would i want to use aclassa static methods or properties in javascript in javascript why would one want to attach properties directly to the constructor var human function humanspecie homo sapiencei have got this question after looking at coffeescriptas extend helper function which contains among the linesfor var key in parent if haspropcall parent key childkey parentkey which copies properties methods to the subclassed object directly from the constructor object but why would anybody do thatthanks,['javascript'] +167313,how to sum retainedheapsize with oql in the eclipse memory analyzer tool have you used matmemory analyzer tool from eclipseit is really cool15g heap dump file kill jhat ibms heap dump analyzer with oomemat is alive and fast and beautiful and powerfuli wonder how much the ehcahce keys memory size is so write oql belowselect ckeyretainedheapsize from netsfehcachestorecompoundhashentry c unfortunately the group function like sum max min doest existi export total result rowabout 60 to excel file and sum in the excel sheetdo you have the tip or hidden functionfeature about using group functionlike sum,['java'] +167340,how to recover camera preview from sleep i have an application that shows camera preview and i would like the user to be able to put the phone to sleep and then wake it so that my application will recover correctly the problem is that when returning from sleep the camera preview would not restart i have implemented the camera preview as is presented in the api demos but it seems that the api demo example works only through sheer luck in the example the screen orientation is forced to landscape which means that the phone will go through configuration change every time the phone goes to sleep since the lockscreen is in portrait mode if the portrait mode is used in the camera preview application like in mine the bug surfacesi have gathered that the bug is related to recreation of the surfaceview the surface should be destroyed always when going to onpause and then recreated after onresume but this does not happen when going to sleep it seems that i have to destroy the whole activity and then recreate it to get the camera preview to work again i would like to be able to just recreate the surfaceviewis there a way to force the recreation of the surfaceview other than just recreating the whole activity,['android'] +167349,find roots of a function a xn bx c 0 where and isnt an integer with numpy i am writing a program in python and in it i need to find the roots of a function that isaxn bx c 0 where a and b are constants that are calculated earlier in the program but there are several thousand of themi need to repeat this equation twice for all values of a and b once with n 7727 and once with n 3how can i do this in pythoni checked numpyrootsp and that would work for when n 3 i think but for n 7727 how would i be able to do thatthanks for taking the time to read this,['python'] +167366,best way to make one model selected in a backbonejs collection i have a collection of models in my backbonejs applicationit is a list of items that you can hover over with the mouse or navigate around with the keyboardif the mouse is hovering or if the keyboard navigation has the item selected they will both do the same thing set that particular itemmodel to be selectedso in my model i have an attribute basically calledselected falsewhen it is hovered over or selected with the keyboard this will then beselected truebut what is the best way to ensure that when this one model is true the others are all falsei am current doing a basic thing of cycling through each model in the collection and then set the selected model to be true but i wonder if there is a better more efficient way of doing this,['javascript'] +167374,images vs core graphics on ios devices in which occasions is it better to draw graphics using core graphics than using image fileswhat are the advantages of doing so in terms of resources,['iphone'] +167388,can unhandled exceptions in child appdomains be prevented from crashing the main process i am writing a small plugins library which uses app domains to isolate plugins using net framework 40 hence the code that goes in each plugin is out of my control when an unhandled exception is raised in one of the plugins i have observed the results to be kind of a mixed bag they are as followswhen the unhandled exception gets thrown in the plugins main thread the main pluggable app calling the plugins execute method is able to catch and handle it cleanly no problems there howeverif the plugin starts a message loop for a winforms based app in the plugins execute method and an unhandled exception gets thrown in the winform application ie in a form then the pluggable app can only catch the exception if its running from inside visual studio debugger otherwise when invoked outside vs the main pluggable app crashes along with the pluginsif the unhandled exception is thrown in a separate thread spawned by the plugins execute method then the pluggable app has no chance of catching the exception and it crashesi have created a simple vs 2010 project to simulate this behaviour at the link belowin it the main method in the pluggable app looks like thisnamespace pluginexceptiontest class program static void mainstring args consolewritelinepress enter to load plugin consolereadline assembly entryasm assemblygetentryassembly string assemblyfilename pathcombinepathgetdirectorynameentryasmlocation evilpluginexe appdomainsetup domainsetup new appdomainsetup appdomain domain appdomaincreatedomainplugindomain null domainsetup pluginbase plugin pluginbasedomaincreateinstancefromandunwrapassemblyfilename evilpluginplugin consolewritelineplugin loaded scenario 1 winforms based plugin consolewritelinepress enter to execute winforms plugin remember to click on the button in the form to raise exception consolereadline try pluginexecutewinapp catch exception the exception is caught and this gets executed only when running in visual studio debugger else application exits why consolewritelinewinforms plugin exception caught however same does not happen when run out of visual studio debugger why scenario 2 winforms based plugin consolewritelinepress enter to execute threading plugin wait for 3 seconds and the app will exit how to prevent app from exiting due to this consolereadline try pluginexecutethread catch exception this never gets executed as the exception is never caught application exits why consolewritelinewinforms plugin exception caught consolereadline this is the code for the plugin project it inherits from the pluginbase class in the pluggable app project abovenamespace evilplugin public class pluginpluginbase public pluginbase public override void executewinapp applicationrunnew form1 public override void executethread thread t new threadnew threadstartraiseex tstart private void raiseex threadsleep30 throw new exceptionanother evil exception in a seperate thread finally this is the code from the form in the pluginnamespace evilplugin public partial class form1 form public form1 initializecomponent private void btnexception clickobject sender eventargs e throw new exceptionevil exception how can i prevent the main process from exiting due to the two scenarios 1 and 2 mentioned above thanks in advance,['.net'] +167390,html image bottom alignment inside div container i have a div tag with a fixed height most of the images have the same height and widthi want to align the images at the bottom of the div so that they are nicely arranged here is what i have so fardiv idrandomcontainer div idimagecontainer img src1png alt img src2png alt img src3png alt img src4png alt div div idnavigationcontainer navigation stuff divdivthe css looks likedivimagecontainer height 160px verticalalign bottom thisplay tablecelli managed to align the images at the bottom with thisplay tablecell and the verticalalign bottom css attributes is there a cleaner way as thisplaying the div as tablecell and aligning the images at the bottom of the div tag,"['html', 'css']" +167393,fpdf error could not include font metric file i have a app which was done by someone else and now i am asked to look into one issuewhen a pdf report is generated it throws an error this app uses fpdf to generate the pdffpdf error could not include font metric fileearlier it was throwing the following errorwarning fpdfincludehelveticabphp functionfpdfinclude failed to open stream no such file or directory warning fpdfinclude functioninclude failed opening helveticabphp for inclusion fpdf error could not include font metric filethis was resolved by including a font folder with helveticabphp and other php files related to other fontsbut the error fpdf error could not include font metric file is still thereon searching the net the possible reasons werefont directory missingdoesnt have access permissions for the font filesi am not sure what permission need to given to the font folder or files in the folderany help in this regard would be of great help,['php'] +167400,webdriver check if an element exists how to check if an element exist with web driveris using a try catch really the only possible wayboolean presenttry driverfindelementbyidlogoutlink present true catch nosuchelementexception e present false,['java'] +167484,is there a standard pattern to follow when waiting for and number of async methods to complete public class foodatarepository private myservicereferenceclient client get set public void fooclass client new myservicereferenceclient clientsavefoocompleted client savefoocompleted clientsavebarcompleted client savebarcompleted private void client savefoocompletedobject sender eventargs e private void client savebarcompletedobject sender eventargs e public void savefoofoo foo clientsavefooasyncfoo foreach var bar in foobars clientsavebarasyncbar i want to do something within the foodatarepository class once the savefooasync and the all the savebarasync methods have completed is there a standard pattern for trying to do a single thing based upon and number of async calls completing,['c#'] +167489,how does stringbuilder work how does stringbuilder work what does it do internally does it use unsafe code and why is it so fast compared to the operator,"['c#', '.net']" +167500,performance of tables vs views recently started working with a database in which the convention is to create a view for every table if you assume that there is a one to one mapping between tables and views i was wondering if anyone could tell me the performance impacts of doing something like this btw this is on oracle,['sql'] +167520,mysql decimal with accuracy of 10 digits after the comma in mysql i have a decimal field set to 1010 however whenever i enter a new value it shows 09 what would i need to change to accept any number with an accuracy of 10 digits after the comma it does work with 106 for some reasonps i want to insert exchange rates,['mysql'] +167521,how to delete a s3 version from a bucket using boto and python when i try to delete a bucket using the linesconn botoconnect s3aws access key id aws secret access keyprint conndelete bucketbucketnameheremessageit tells me the bucket i tried to delete is not emptythe bucket has no keys in it but it does have versionshow can i delete the versionsi can see the list of versions using bucketlist versionsjava has a deleteversion method on its s3 connection i found that code here he does this line to delete the versions3deleteversionnew deleteversionrequestbucketname keyname versionidis there anything comparable in boto,['python'] +167527,benefits of using reserve in a vector c what is the benefit of using reserve when dealing with vectors when should i use them could not find a clear cut answer on this but i assume it is faster when you reserve in advance before using themwhat say you people smarter than i,['c++'] +167528,replace sequence of bytes in binary file what is the best method to replace sequence of bytes in binary file to the same length of other bytes the binary files will be pretty large about 50 mb and should not be loaded at once in memory update i do not know location of bytes which needs to be replaced i need to find them first,['c#'] +167533,javascript submit is not a function possible duplicatesubmit is not a function in javascript why is the following basic javascript function giving me an error documentgetelementbyidformsubmit is not a function the only thing i have on a page is a form and this javascript function i want he form to auto submit when page is accessedscript windowonload function documentgetelementbyidformsubmitscript,"['javascript', 'jquery']" +167536,why does this c assignment throw an exception public class a private string a string public string astring get return a string set a string value public class b private string b string private a a public a a get return a set a value public string bstring get return b string set b string value this does not work b b new b a astring astring bstring bstring systemnullreferenceexception object reference not set to an instance of an objectthis works b b new b a new a astring astring bstring bstring both compile fine in vs2010,['c#'] +167558,how can i make a span and an input sit next to each other and collectively take up 100 of the width of the containing div i have the following snippethtmlbodydiv stylewidth 700pxspantestspaninput stylewidth 100inputdivbodyhtmlbut this does not do what i want i wanted that span and input together would account for 100 of the div ie that input would start right where the span ends and fill until the width of the div without breaking to the next line how do i do that,"['html', 'css']" +167573,whats the current state of gwt i am currently working on a complex web application and am finding javascriptjquery development for the certain things to be very challenging so i started looking for alternative toolsi think gwt is probably what i have been looking for there has been numerous times during development that i have thought if only i was programming in java the features i am wanting mostly revolve around oop and reusability that i find difficult to obtain in javascripthowever i want to get a feeling of how viable gwt is i have done some searching and have read some opinions of how gwt was a year ago but am curious how things are going now are many developers using it is it growing do you see gwt being used years from now,"['java', 'javascript']" +167588,how to pass this by ref in c in a class classa of mine i want to create a related instance of another class classb providing it with a reference to the object who has initiated it is creation so i have provided classb with a construcror taking a ref classb master argument but in classa i cannot just call var slave new classbref this how to implement this,"['c#', '.net']" +167597,setup default css class for rails form builder helper methods i am looking for a generic way to apply some external css frameworks in a rails application these frameworks typically define a set of class names which should be used for certain html elementsconsider jquery ui to achive a consistent form style you would to something like this in a view form for foo do f ftext field bar class uiwidget uiwidgetcontent uiwidgetcontainer uicornerall or ftext field bar class uiwidget uiwidgetcontent uiwidgetcontainer uicornerall end doing this for each input field is not dry at alleven a helper method like in application helperrbdef jquery ui classes uiwidget uiwidgetcontent uiwidgetcontainer uicornerallend in a view ftext field bar class jquery ui classes or in application helperrbdef jquery text fieldform builder method opts ui uiwidget uiwidgetcontent uiwidgetcontainer uicornerall klass optsdeleteclass uiflattencompact form buildertext field method optsmergeclass klassend in a view jquery text field f bar does not look right or more dry since you still would have to touch the generated form viewalternative ways might now be monkeypatching the instancetag class or hacking into the form for helperhas anyone done this beforeby the way i would avoid using jquery or javascript in general to apply the class attributes since js might be thisabled or blocked or even delivered with delay and cause a flickeringcheersdominik,['css'] +167640,php gmail contacts xml parsing with domdocument and curl what i am trying to get currently is just the attribute of gdemail that is the address only nothing else as of the moment which i can get to the xml portion heck i can even get any given think per say as long as its within tags like but to get the attribute of any given one like in my case i am completely confused on i used to know how to do it but its been so long since i did anything that was not simple for xml useage so i done messed my own self upxml version10 encodingutf8 feed xmlns xmlnsopensearch xmlnsgcontact xmlnsbatch xmlnsgd idid updated20110630t0748706zupdated category scheme term title typetexttaco bellss contactstitle link relalternate typetexthtml href link rel typeapplicationatomxml href link rel typeapplicationatomxml href link rel typeapplicationatomxml href link relself typeapplicationatomxml href link relnext typeapplicationatomxml hrefmaxresults5 author nametaco bellname emailemail author generator version10 uricontactsgenerator opensearchtotalresults90opensearchtotalresults opensearchstartindex1opensearchstartindex opensearchitemsperpage5opensearchitemsperpage entry idid updated20100127t001157430zupdated category scheme term title typetexttaco btitle link rel typeimage href xl joapon1k7snixi2ia link rel typeimage href link relself typeapplicationatomxml href link reledit typeapplicationatomxml href gdemail rel address primarytrue entry entry idid updated20070801t180204410zupdated category scheme term title typetexttitle link rel typeimage href link relself typeapplicationatomxml href link reledit typeapplicationatomxml href gdemail rel address primarytrue entry entry idid updated20100127t001157430zupdated category scheme term title typetextsteve sattlertitle link rel typeimage href link relself typeapplicationatomxml href link reledit typeapplicationatomxml href gdemail rel address primarytrue entry entry idid updated20100127t001157430zupdated category scheme term title typetextmichael montanatitle link rel typeimage href link relself typeapplicationatomxml href link reledit typeapplicationatomxml href gdemail rel address primarytrue entry entry idid updated20070801t180204410zupdated category scheme term title typetexttitle link rel typeimage href link relself typeapplicationatomxml href link reledit typeapplicationatomxml href gdemail rel address primarytrue entry feedwith code that looks like this is the whole script currentlyuser password x ref step 1 loginlogin url fields array email user passwd password service cp contact list service code source testgooglecontactgrabber accounttype googlecurl curl initcurl setoptcurl curlopt urllogin urlcurl setoptcurl curlopt post 1curl setoptcurl curlopt postfieldsfieldscurl setoptcurl curlopt ssl verifypeer 0curl setoptcurl curlopt returntransfer 1 result curl execcurlreturns arrayforeach explodenresult as line line trimline if line continue listkv explodeline2 returnsk vcurl closecurl step 2 grab the contact listfeed url userfullmaxresults5header array authorization googlelogin auth returnsauthcurl curl initcurl setoptcurl curlopt url feed urlcurl setoptcurl curlopt httpheader headercurl setoptcurl curlopt ssl verifypeer 0curl setoptcurl curlopt returntransfer 1 result curl execcurlcurl closecurldoc new domdocumentdocloadresultarrfeeds arrayforeach docgetelementsbytagnameentry as node monkey nodegetattributegdemail itemrss arraymonkeynodevaluearray pusharrfeeds itemrssarray uniquearrfeeds,['php'] +167642,how are lambda expressions bound to a class if i set up a class like below in python as i expect the lambda expressions created should be bound to the class a i do not understand why when i put a lambda inside a list like in g it is not boundclass aobject f lambda xy x y g lambda xy x ya aaf boundprint afbound method alambda of main a object at 0xb743350cag0 not boundprint ag0function lambda at 0xb742d294why is one bound and not the other,['python'] +167646,how to ignore current route values when generating links the question is similar to aspnet mvc htmlactionlink keeping route value i dont want but with a twist that makes it more complexstarting from a default new mvc3 app i change the routes toroutesmaproute r1 route name controlleridactionroutesmaproute r2 route name controlleractionnotice that the id comes before the action in the firstthen in homeindexcshtml i addurlactionindexurlactionindex new id blah urlactionindex new id now i navigate to homefooindex and look at the 3 generated links i gethomefooindexhomeblahindexhomeindexidfoothe first two make sense and are using the first routebut in the third link which hits the second route i do not understand why idfoo is passed on the query string given that i explicitly passed an empty id i would expect it to just generate homeindexcan anyone explain that and suggest how i can get it not to show up,['c#'] +167647,android media controller shows thisplay for a short time this below activity works fine but the mediacontroller thisplay only if i click on the screen and the second problem is the media controller thisplay only for 3 sec what should i do to remove this problem public class playingactivity extends activity private videoview mvideoview private edittext mpath mediacontroller mediacontroller override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutplayingactivity mpath edittext findviewbyidridpath mpathsettextglobalvariablegetstremail mvideoview videoview findviewbyidridsurface view uri uri uriparsesdcarddownloadtestmp3 mediacontroller new mediacontrollerthis mediacontrollerfindfocus mediacontrollersetenabledtrue mediacontrollershow0 mediacontrollersetanchorviewmvideoview mvideoviewsetmediacontrollermediacontroller mvideoviewsetvideouriuri mvideoviewstart,['android'] +167651,querying for all objects of multiple child entity types in core data given the following contrived examplei would like to query my data for all objects that are either cats or dogs i want the result set ordered by name regardless of species so fetching all cats then fetching all dogs would not do i want to do this in a single queryone way to do this would be to add a pettype field to pet give every record a pettype value that identifies the subentity it belongs to then query like sonsentitydescription entity nsentitydescription entityfornamepet inmanagedobjectcontextmymocfetchrequest setentityentity pettype values 1 dog 2 cat 3 goldfish yuknspredicate p nspredicate predicatewithformatpettype 1 or pettype 2fetchrequest setpredicatep etcbut the mere thought of doing it that way makes me shudder is there a better wayupdate thanks to all those whove replied there are some really good wellthought out solutions here and i appreciate all of themto give this some context the real data model is a little more complex than this are not they always but it is pretty well organised i have designed more than my fair share of data schemas in my time and i am happy that the entities and their relationships are well considered this issue has come about because to extend the already shaky contrived example the client originally wanteda view showing a list of all petsa view showing a list of goldfisha view showing a list of catsa view showing a list of dogsso far so good but they also want a view showing a combined list of all cats and dogs because little girls like cats and dogs initially it was cats and goldfish for the same reason there is not really a way to naturally group that subset of the concrete entities it is really rather arbitraryso far dave dribins abstract intermediate entity approach seems like the cleanest solution although in my case i think it would feel somewhat artificial really the only way you could truthfully label the intermediate entity would be as thinglittlegirlslike,['objective-c'] +167661,eclipse see which methods of one class are used in another with eclipse given the following classesclass dao public void one public void two public void three class servicea dao dao public void a daoone daotwo public void b daoone class serviceb dao dao public void z daotwo daothree is it possible to see a list of all dao methods referenced from servicea i am looking for one view that will show that servicea uses one and two do not mind it if one is listed twicei know how to see callers of one specific method i really need a list of all methods referenced within a class think of legacy code orders of magnitude larger dao and services that have tens hundreds of methods i do not feel like going through call hierarchy method by method,['java'] +167689,when will a c11 compiler make rvo and nrvo outperform move semantics and const reference binding consider the case when whole objects with move semantics enabled are returned from functions as with stdbasic stringstdwstring build report const stdwstring report return reportcan i then realistically be expected to make the best choice whether to use the returned string with move semantics as inconst stdwstring reportstdmovebuild reportor if i should rely on nrvo to take place withconst stdwstring reportbuild reportor even bind a const reference to the temporary withconst stdwstring reportbuild reportwhat scheme is there to make a deterministic choice of these options if anyedit 1 note that the usage of stdwstring above is just an example of a move semantics enabled type it just as well be swapped for your arbitrary large structure edit 2 i checked the generated assembly when running a speedoptmized release build in vs 2010 of the followingstdwstring build reportconst stdwstring title const stdwstring content stdwstring report reportappendtitle reportappendcontent return reportconst stdwstring title1ltitle1const stdwstring content1lcontent1const stdwstring title2ltitle2const stdwstring content2lcontent2const stdwstring title3ltitle3const stdwstring content3lcontent3int tmainint argc tchar argv const stdwstring report1stdmovebuild reporttitle1 content1 const stdwstring report2build reporttitle2 content2 const stdwstring report3build reporttitle3 content3 return 0the 2 most interesting outcomesexplicitly calling stdmove for report1 to use the move constructor triples the instruction countas noted by james mcnellis in his answer below report2 and report3 does indeed generate identical assembly with 3 times fewer instructions than explicitly calling stdmove,['c++'] +167699,how to execute async task repeatedly after fixed time intervals how to make async task execute repeatedly after some time interval just like timeractually i am developing an application that will download automatically all the latest unread greeting from the server and for that purpose i have to check for updates from server after some fixed time intervalsi know that can be easily done through timer but i want to use async task which i think is more efficient for android applications,['android'] +167702,code analysis tools for android is there any static code analysis tools for android that would pick up simple things like nullpointerexceptions from trying to access an object that might be null without checking for it firsttools like resharper on c projects do this quite well so i am presuming there is similar tools for androids java,['android'] +167730,avoid hardcoding controller and action names aspnet mvc seems to be encouraging me to use hardcoded strings to refer to controllers and actions for example in a controllerreturn redirecttoactionindex homeor in a viewhtmlrenderpartialindex homei do not want hardcoded strings all over my code what can i do to avoid this,['c#'] +167756,implementation of non local means noise reduction algorithm in image processing i am working over implementation of non local means noise reduction algorithm in c there are papers on this algorithm such as this paper but they are also not very clear on iti know it is using the weighted mean but i do not know what is the use of research window here and how is it related to comparison window being a new user stackoverflow is not allowing me to upload images but you can find formula under the nl means section the link provided above,['c++'] +167762,xml into associative array using php can anyone help with converting data from an xml document into an associative array i am running into issues given that the xml structure is sort of 3d and the array is more of a 2d structure please forgive my lack of correct terminology throughout the xml elements have attributes children and grandchildren but i never know their names so i figured i would try to make the key in the array a concatenation of each childattribute name and the value equal to well the value trouble is i need the attribute name and value as part of the concatenated array key to make it uniquefor examplecomputer id1 os namelinuxname ageolder than meage oscomputercomputer id2 os namewindowsname agenot so muchage oscomputershould ideally give computerid1osname linuxcomputerid1osage older than mecomputerid2osname windowscomputerid2osage not so muchbut i am getting this resultcomputerid 1computerosname linuxcomputerosage older than mecomputerid 2computerosname windowscomputerosage not so muchso that the computerid key is not unique i am using a recursive function to read in the values but i cannot figure how to get the attribute name and attribute value into the name of the subordinate keysby the way there is a good reason for doing this seemingly illogical taskany help would be greatly appreciatedhere is the function which flattens the xml data after it has been read into a multidimensional array i am not sure i am going about this the right wayfunction flattenarray array basename null resetarray while list key value eacharray outkey key if is arrayvalue flattenarrayvalue basename outkey else finalkey basename rtrimoutkey finalvalue value echo finalkey finalvaluen,['php'] +167780,why does pythons itertoolspermutations contain duplicates when the original list has duplicates it is universally agreed that a list of and thistinct symbols has n permutations however when the symbols are not thistinct the most common convention in mathematics and elsewhere seems to be to count only thistinct permutations thus the permutations of the list 1 1 2 are usually considered to be1 1 2 1 2 1 2 1 1 indeed the following c code prints precisely those threeint a 1 1 2do couta0 a1 a2endl whilenext permutationaa3on the other hand pythons itertoolspermutations seems to print something elseimport itertoolsfor a in itertoolspermutations1 1 2 print athis prints1 1 21 2 11 1 21 2 12 1 12 1 1as user artsiom rudzenka pointed out in an answer the python documentation says soelements are treated as unique based on their position not on their valuemy question why was this design decision made it seems that following the usual convention would give results that are more useful and indeed it is usually exactly what i want or is there some application of pythons behaviour that i am missing or is it some implementation issue the algorithm as in next permutation a for instance explained on stackoverflow here by me and shown here to be o1 amortised a seems efficient and implementable in python but is python doing something even more efficient since it does not guarantee lexicographic order based on value and if so was the increase in efficiency considered worth it,['python'] +167781,what happens when you do not follow the practice of argv and argc possible duplicatesmainint argc char argvmains signature in c if i writeint mainint argc char argvi get proper commandline inputwhat would happen if i wrote say int mainint foo double foodouble footype foovaris this osdependent or does it depend on the compiler,"['c++', 'c']" +167793,android listview adapter how to detect an empty list i have a listview in my activity which takes values from an extension class of simpleadapterthis one is correctly working when i add or delete some data in itbut my problem is when my item list is empty i would like to replace the listview by a message like no item inhere or something like thati tried to do it this wayclass favadapter extends simpleadapter activity context arraylisthashmapstringstring data string items int champs int layout favadapteractivity context arraylisthashmapstringstring data int layout string items int champs super context data layout items champs thisdata data thiscontext context thisitems items thislayout layout thischamps champs public view getviewint pos view convertview viewgroup parent recycling view row convertview else get from xml ifrow null layoutinflater infla contextgetlayoutinflater row inflainflatelayout null if there are data ifdatasize 0 here i am correctly constructing row else else textview txt new textviewactivityfavoristhis txtsettextnot data inhere linearlayout ll linearlayout rowfindviewbyidridresult lyt principal lladdviewtxt return row problem is my list has never a size of 0 in fact when the data is empty the adapter is not calledcan someone explain me how i can do it by another waythanks in advanceedit using your answers i succeed on that my solution is setcontentview has to be used with findviewbyidandroidridempty but if like me you have two different listview in your activity which need different empty views you will have to find it inside different layout this way android will automatically call the right view when the listview is empty and nothing have to be done in the adapter when datasize is 0example in activity public void oncreatebundle b superoncreateb lv1 listview findviewbyidridlistviewone lv2 listview findviewbyidridlistviewtwo set listview adater set empty view lv1setemptyviewfindviewbyidridlayoutonefindviewbyidandroidridempty lv2setemptyviewfindviewbyidridlayouttwofindviewbyidandroidridemptywith that xmllinearlayout xmlnsandroid androidorientationvertical androidlayout widthfill parent androidlayout heightfill parent linearlayout androidididlayoutone androidorientationhorizontal androidlayout weight1 androidlayout widthfill parent androidlayout heightfill parent listview androidididlistviewone androidlayout widthfill parent androidlayout heightfill parent textview androididandroididempty androidlayout widthfill parent androidlayout heightwrap content androidtextpas de favoris enregistraes linearlayoutlinearlayout androidididlayouttwo androidorientationhorizontal androidlayout weight1 androidlayout widthfill parent androidlayout heightfill parent listview androidididlistviewtwo androidlayout widthfill parent androidlayout heightfill parent textview androididandroididempty androidlayout widthfill parent androidlayout heightwrap content androidtextpas de favoris enregistraes linearlayout,['android'] +167810,can i animate the uiscrollview contentoffset property via its layer i want to zoom and scroll a uiscrollview with a cgpathref because of that i assume i have to animate the uiscrollviews layer property but which property would i animate that would make it equivalent to doing a uiview animation and setting its contentoffset property and zoomscale these are not properties of a calayerany ideas as to how i would approach this again just want to move the scrollview to a certain contentoffset and zoomscale but not necessarily linearly from point a to point b zoom a to zoom b respectivelyi was thinking a cakeyframeanimation with a cgpathref but i do not know which properties to animate,['ios'] +167816,ruby regex to match grayscale color i want a ruby regex to match a hex greyscale color so it would match 0abababfbut not ccddccafafa0etc,['ruby'] +167847,the roadmap to an android development expert i just started to learn android developmentmy previous experience is majorly net framework in c i have some experience with linux and basically no idea about javaso which is the good way to be an android development expert books study roadmap anything would be appreciated i am all ears to your advisesthanksapologies if this is not the right place to post such a question,['android'] +167863,why not use htmleditorformodel ok i just thiscovered about the editorformodel in mvc and i want to know when i should use this instead of an editorfor on each of my property and why does when i add a strongly typed view it does not use this and build an editorfor on every propertyi am late on this but thanks for the info,['c#'] +167899,jquery deferred waiting for multiple ajax requests to finish i have a three layer deep chain of deferred ajax calls and ideally they are going to kick the promise all the way up when the deepest layer finishes makes me thing of inception we need to go deeper the problem is that i am sending off many ajax requests possibly hundreds at once and need to defer until all of them are done i cannot rely on the last one being done lastfunction updateallnotes return deferredfunctiondfd uan getcount 0 getreturn 0 for i 0 i indexdatalength 1 i getcount whengetnoteindexdataikeydonefunction getnote is another deferred getreturn need help here when getreturn getcount dfd uanresolve promise,['jquery'] +167902,using pageclientscriptregisterclientscriptblock not working i am trying to fire a pop up as shown below but it is not working please helppublic void btnsubmit clickobject o eventargs e if checkfileexistsconverttostringfileinfo pageclientscriptregisterclientscriptblockthisgettype msg script typetextjavascript languagejavascriptfunction showmsgreturn confirmthis image name already exists do you want to replace itscript true btnsubmitonclientclick return showmsg if something else it does whatever is here but never pops the question above and on the button i have aspbutton classbutton idbtnsubmit causesvalidationtrue textsubmit runatserver onclickbtnsubmit clickaspbutton,"['c#', 'asp.net']" +167940,how to retrieve a subset of fields using the c mongodb driver i have searched the world over and cannot seem to find the answer to thishow do i do this in c retrieve ssn field for documents where last name smithdbusersfindlast name smith ssn 1thanks,['c#'] +167955,how can i use mongoid and activerecord in parallel in rails 3 i am using rails 3 and began my application with activerecord now i have many models and the relations are starting to get complicated and some could be more simply expressed with a documentoriented structure so i would like to try migrating to mongodb and use mongoid i have always heard that you did not have to eitheer use all mongodb or nothing but that you could use the two in parallel while migrating i do not see how to go about this from the docs thoughfor example i haveclass user activerecordbase has many items has many products through itemsendclass product activerecordbase has many itemsendclass item activerecordbase belongs to user belongs to product alot of data that fits a hierarchical documentoriented structureendi would like to ideally begin by replacing my item activerecord model with a mongoid document so my items are stored in mongodb and my users and products can stay in my sql dbthing is i do not see how to do this am i going about this the right wayperhaps another alternative is to keep a base ar itemclass item activerecordbase has one mongodb item i know this is wrongendclass mongodbitem include mongoiddocument belongs to ar item i know this is also wrongendthanks,['ruby-on-rails'] +167958,ios cvimagebuffer thistorted from avcapturesessiondataoutput with avcapturesessionpresetphoto at a high level i created an app that lets a user point his or her iphone camera around and see video frames that have been processed with visual effects additionally the user can tap a button to take a freezeframe of the current preview as a highresolution photo that is saved in their iphone libraryto do this the app follows this procedure1 create an avcapturesessioncapturesession avcapturesession alloc initcapturesession setsessionpresetavcapturesessionpreset640x4802 hook up an avcapturedeviceinput using the backfacing cameravideoinput avcapturedeviceinput alloc initwithdevicebackfacingcamera errorerror autoreleasecapturesession addinputvideoinput3 hook up an avcapturestillimageoutput to the session to be able to capture still frames at photo resolutionstilloutput avcapturestillimageoutput alloc initstilloutput setoutputsettingsnsdictionary dictionarywithobjectnsnumber numberwithintkcvpixelformattype 32bgra forkeyidkcvpixelbufferpixelformattypekeycapturesession addoutputstilloutput4 hook up an avcapturevideodataoutput to the session to be able to capture individual video frames cvimagebuffers at a lower resolutionvideooutput avcapturevideodataoutput alloc initvideooutput setvideosettingsnsdictionary dictionarywithobjectnsnumber numberwithintkcvpixelformattype 32bgra forkeyidkcvpixelbufferpixelformattypekeyvideooutput setsamplebufferdelegateself queuethispatch get main queuecapturesession addoutputvideooutput5 as video frames are captured the delegates method is called with each new frame as a cvimagebuffer voidcaptureoutputavcaptureoutput captureoutput didoutputsamplebuffercmsamplebufferrefsamplebuffer fromconnectionavcaptureconnection connection cvimagebufferref pixelbuffer cmsamplebuffergetimagebuffersamplebuffer selfdelegate processnewcameraframepixelbuffer6 then the delegate processesdraws them voidprocessnewcameraframecvimagebufferrefcameraframe cvpixelbufferlockbaseaddresscameraframe 0 int bufferheight cvpixelbuffergetheightcameraframe int bufferwidth cvpixelbuffergetwidthcameraframe glcleargl color buffer bit glgentextures1 videoframetexture glbindtexturegl texture 2d videoframetexture gltexparameterigl texture 2d gl texture min filter gl linear gltexparameterigl texture 2d gl texture mag filter gl linear gltexparameterigl texture 2d gl texture wrap s gl clamp to edge gltexparameterigl texture 2d gl texture wrap t gl clamp to edge glteximage2dgl texture 2d 0 gl rgba bufferwidth bufferheight 0 gl bgra gl unsigned byte cvpixelbuffergetbaseaddresscameraframe glbindbuffergl array buffer self vertexbuffer glbindbuffergl element array buffer self indexbuffer gldrawelementsgl triangle strip 4 gl unsigned short buffer offset0 glbindbuffergl array buffer 0 glbindbuffergl element array buffer 0 self context presentrenderbuffergl renderbuffer gldeletetextures1 videoframetexture cvpixelbufferunlockbaseaddresscameraframe 0this all works and leads to the correct results i can see a video preview of 640x480 processed through opengl it looks like thishowever if i capture a still image from this session its resolution will also be 640x480 i want it to be high resolution so in step one i change the preset line tocapturesession setsessionpresetavcapturesessionpresetphotothis correctly captures still images at the highest resolution for the iphone4 2592x1936however the video preview as received by the delegate in steps 5 and 6 now looks like thisi have confirmed that every other preset high medium low 640x480 and 1280x720 previews as intended however the photo preset seems to send buffer data in a different formati have also confirmed that the data being sent to the buffer at the photo preset is actually valid image data by taking the buffer and creating a uiimage out of it instead of sending it to openglcgcolorspaceref colorspace cgcolorspacecreatedevicergbcgcontextref context cgbitmapcontextcreatecvpixelbuffergetbaseaddresscameraframe bufferwidth bufferheight 8 bytesperrow colorspace kcgbitmapbyteorder32little kcgimagealphapremultipliedfirst cgimageref cgimage cgbitmapcontextcreateimagecontext uiimage animage uiimage imagewithcgimagecgimagethis shows an unthistorted video framei have done a bunch of searching and cannot seem to fix it my hunch is that it is a data format issue that is i believe that the buffer is being set correctly but with a format that this line does not understandglteximage2dgl texture 2d 0 gl rgba bufferwidth bufferheight 0 gl bgra gl unsigned byte cvpixelbuffergetbaseaddresscameraframemy hunch was that changing the external format from gl bgra to something else would help but it does not and through various means it looks like the buffer is actually in gl bgradoes anyone know whats going on here or do you have any tips on how i might go about debugging why this is happening whats super weird is that this happens on an iphone4 but not on an iphone 3gs both running ios43,"['iphone', 'ios']" +167991,whats the point in urbanairship i am looking into push notifications for an app i am creating i have heard lots about urbanairship but i cannot seem to find a definitive reason why i should use it as far as i understand it ua is a middle man this page shows the free version does not have a push composer so a developer will still need a server themselves to create the notification if their own server is needed then i might as well go directly to apnswhat is the point and advantage of ua and if you use it how do you send notifications without your own server,"['iphone', 'objective-c', 'ios']" +168052,c simple cache design for function output i assume it is a quite frequent problem with wellknown solutions which i was notable to find so i am seeking advice hereproblem statementconsider the following settingclass a some classconst a fconst a an expensive functionvoid do stuff a a amodify do stuff1fa compute fa do stuff2fa use cached value of fa amodify do stuff3fa recompute fai would like the return value of fa to be cached between the first andsecond calls but to be thiscarded after the second call to amodifyedit in practice the calls to fa will be in different scopeshere are the pieces of solutions i have explored for what it is worthsolution 1 central cacheusing time stampsi can imagine a simple solution involving adding a time stamp to class a thatfunction f can check and decide if it needs to update its cached resultstored somewhere in a central cache i guess this also implies changing thesignature of f toconst a fconst aproblem 1 with a central cache we need a mechanism to destroy thecached result of fa when a is destroyedusing hash codesaside from problem 1 this seems simple enough but it gets complicated when astands for stdvector i guess dynamic polymorphism should be excludedhere so we forget about adding a time stamp to a subclass of stdvector and allthe overriding that it would imply however we could compute some hash code or uuidbased on the contents of a assuming that it is much cheaper than computingfa and base the central cache on these hash codes but were facing problem 1 againsolution 2 coupled objectsi still have not found how to implement this but the idea is to have a notifythe cache for fa when a is written to or destroyed but not when it ismerely read from i cannot figure how to do that without dynamic polymorphismand without slowing down singleelement accesses using operator oriterators by sending notifications to the cache for each modified elementproblem 2 find a mechanism of delimiting sets of changes to a to invalidate the cache only once for each set of changesi have thought of proxies to enable write access on a inspired by the conceptof mutex but could not come up with any working codeany ideas,['c++'] +168060,reverb effect in iphone app can anyone please give pointers how we can add re verb effect to a recording in an iphone appvocal live free on app store is a pretty good example of how i would want to include reverb effectcore audio overview in ios documentation references reverb as an audio unit any help beyond this will be helpful,['ios'] +168067,jquery mobile phonegap for android error loading indexhtml i am trying to get a basic phonegap jquery mobile program running for android platform 22 but i am getting an application error the connection to the server was unsuccessful fileandroid assetwindexhtml in the android emulator when i try to run the application in android emulator platform 22 on windows xp with eclipse 37 the file loads if i remove all references and syntax of jquery mobile from the html file so i am certain that my project is fine but there is something i am missing with initialization of jquery mobile i am using phonegap 096 with jquery mobile version 10b1 with jquery version 161 i also tried with jqm version 10a2 with jquery 144 but with the same errorif i remove all references to jquery mobile from my html file then i am able to load the program in the emulator without errors i looked at several examples on the web and tried them as they are but all of them show the same error my files are asdoctype htmlhtml head meta nameviewport contentwidth320 userscalableno meta httpequivcontenttype contenttexthtml charsetutf8 titlephonegap with jqmtitle link relstylesheet hrefjquerymobile10b1mincss typetextcss charsetutf8 script srcjquery161minjsscript script typetextjavascript charsetutf8 srcphonegap096jsscript script typetextjavascript charsetutf8 srcmainjsscript script srcjquerymobile10b1minjsscript head body onloadinit div datarolepage datathemee div dataroleheader h1phonegap with jqmh1 div div datarolecontent h1my contenth1 div div datarolefooter h1my footerh1 div bodyhtmlthe mainjs file has onlyfunction init documentaddeventlistenerdeviceready deviceinfo true what am i missing,"['javascript', 'jquery', 'android']" +168075,ios copy a file in documents folder in my project i have two file txt in resources folder how can i copy them inside documents folder,['ios'] +168091,does anyone still use goto in c and if so why i was wondering whether anyone still uses the goto keyword syntax in c and what possible reasons there are for doing so i tend to view any statements that cause the reader to jump around the code as bad practice but wondered whether there were any credible scenarios for using such a syntaxgoto keyword definition,"['c#', '.net']" +168096,concurrent collections eating too much cpu without threadsleep what would be the correct usage of either blockingcollection or concurrentqueue so you can freely dequeue items without burning out half or more of your cpu using a thread i was running some tests using 2 threads and unless i had a threadsleep of at least 50100ms it would always hit at least 50 of my cpuhere is a fictional exampleprivate void dequeueitem object o null whilesocketconnected while listofqueueitemsisempty if listofqueueitemstrydequeueout o use the data with the above example i would have to set a threadsleep so the cpu doesnt blow upnote i have also tried it without the while for isempty check result was the same,['c#'] +168097,rails 3kaminari pagination for an simple array for paginating a common array i got this solutionarr name kaminaripaginate arrayarr namepageparamspageperper page recordsper page records is a variable with value as per needed for paginationany better ideasalso to have an ajax call for using pagination one can use thisin your viewgive id to your div tab div idpaginateand inside it paginate arr name remote true and in js response file putpaginatehtml escape javascriptpaginatearr name remote trueto s so your requests will be ajaxthanks,['ruby-on-rails'] +168098,making a jquery button act as a dropdown take this jquery ui button sample as a referencenow how would you implement that dropdown when click the small buttonmy caution is mainly with the transformation button does to the actual button that messes the offset coordenatesto sum it i need opinions on how to correctly implement a dropdown on the click of a jquery button that integrates with the current themethanksalex,"['javascript', 'jquery', 'css']" +168109,uniform initialization of references i am currently trying to understand the new uniform initialization of c0x unfortunately i stumpled over using uniform initialization of references exampleint main int a int refathis example works fine langc g uniform init of refcpp stdc0x o uni wall wextrauniform init of refcpp in function int mainuniform init of refcpp310 warning unused variable ref wunusedvariableupdate comeau throws an error for that example so maybe gcc should not compile it as wellnow if i use a custom data type instead of an integer it does not work anymoreclass yint main y y y refy langc g initializationcpp stdc0x o initialization wall wextrainitializationcpp in function int maininitializationcpp913 error invalid initialization of nonconst reference of type y from an rvalue of type braceenclosed initializer listinitializationcpp98 warning unused variable ref wunusedvariableunfortunately i did not find the relevant section in the standard draft my guess is that i am misunderstanding the usage of uniform initialization as comeau complains with this messagecomeautestc9 error reference variable ref requires an initializer y refyso can someone of you point me in the right directionin case that you want to know why this question is relevant and why i do not just use y refy i would like to be able to use uniform initialization in the initialization list of a constructorclass x class y const x x public y const x xx x int main x x y yxthis fails with the same error message as abovenote i am using langc to enable english error messagesgcc version 461,['c++'] +168133,in java what is the difference between thismethod and method is there any difference between calling thismethod and method including performance difference,['java'] +168143,on keystroke insert line of code in macvim for pdb i am looking for the way to insert a line of code with a keystroke like leaderp in macvimi want to insert the following line of codeimport pdb pdbset traceprobably not an unheard of line of code in python land,['python'] +168148,save data of logcat in android i want to save all the contents of log cat into specific file in androidi used eclipse ide to develop the android applicationhow i can achieve this thanks,['android'] +168155,checking if an element exists in json using the following feed timelinejsonscreen namemicrosoftinclude rts1count10i am successfully able to loop through this to get the details i want to thisplay on my html pagehowever i need to check if retweeted statususerprofile image url exists and i am not sure how to do thatcurrently i am looping through the data where data is returned by jqueryajaxdatairetweeted statususerprofile image urlif datairetweeted statususerprofile image url does not exist it does not return null or undefined i just get the following errorcannot read property user of undefined,"['javascript', 'jquery']" +168175,function declaration in coffeescript i notice that in coffeescript if i define a function usinga c c1i can only get the function expressionvar aa functionc return c 1but personally i often use function declarationfor examplefunction ac return c 1i do use the first form but i am wondering if there is a way in coffeescript generating a function declaration if there is no such way i would like to know why coffeescript avoid doing this i do not think jslint would holler an error for declaration as long as the function is declared at the top of the scope,['javascript'] +168249,how can i conditionally declare a delegate in an interface declaration i have an xcode 4 project that builds to two different targets i have defined some constants in the build settings so i can run different code for each target like thisifdef version1 do thiselse do thatendifin one version of the app i need the main view controller to open another view controller and become its delegate but the other version does not use that view controller and should not compile its code or try to become its delegate i have set up the main view controller header like thisifdef version2import specialviewcontrollerhendifinterface mainviewcontroller uiviewcontroller mpmediapickercontrollerdelegate specialviewcontrollerdelegate etcthe conditional around the import tag works fine but how can i declare this class to be the specialviewcontrollerdelegate in one version but not the other,"['objective-c', 'ios']" +168276,prevent webview from thisplaying web page not available i have an app that makes extensive use of a webview when the user of this app does not have internet connection a page saying web page not available and various other text appears is there a way to not show this generic text in my webview i would like to provide my own error handling private final activity activity thisprivate class mywebviewclient extends webviewclient public void onreceivederrorwebview view int errorcode string description string failingurl i need to do something like this activitywebviewwipeoutthepage activitymycustomerrorhandling toastmaketextactivity description toastlength longshow i found out webviewclearview does not actually clear the view,"['java', 'android']" +168294,jaxb suppress boolean attribute if false let us say that i have a classxmlrootelementnamethingpublic class thing private string name private boolean awesome xmlvalue public void setnamestring name thisname name public string getname return thisvalue xmlattribute public void setawesomeboolean awesome thisawesome awesome public boolean isawesome return thisawesome if i create some things then marshall them to xml it looks like thisa flying ninjathing awesometrueflying ninjathinga regular old popcorn ballthing awesomefalsepopcorn ballthingbut what i would like to do is change the way that my boolean attributes are marshalled i would rather see the popcorn ball look like this supressing the awesome attributethingpopcorn ballthinghow can i do thisthanks so much,['java'] +168301,mysql matching unicode characters with ascii version i am running mysql 5150 and have a table that looks like thisorganizations create table organizations id int11 not null auto increment name text character set utf8 collate utf8 unicode ci not null url text character set utf8 collate utf8 unicode ci default null phone varchar20 character set utf8 collate utf8 unicode ci default null timestamp timestamp not null default current timestamp on update current timestamp primary key id key id id enginemyisam auto increment25837 default charsetutf8 the problem i am having is that mysql is matching unicode characters with ascii versions for example when i search for a word with that contains an a it will match the same word that has an e instead and vice versamysql set names utf8query ok 0 rows affected 0 secmysql select id name from organizations where name universite de montreal id name 16973 universita de montreal 1 row in set 001 seci get these results both from php and the command line console how can i get accurate matches from my select queriesthanks,['mysql'] +168318,merge pdf files on ios is there a way in ios to merge pdf files that is append the pages of one at the end of another and save it to thisk,"['iphone', 'ios']" +168337,what is the purpose of accessors can somebody help me understand the get setwhy are they needed i can just make a public variable,['c#'] +168366,multiple input in joptionpaneshowinputdialog is there a way to create multiple input in joptionpaneshowinputdialog instead of just one input,['java'] +168389,why is an unsigned int 1 lower than a char y 1 main unsigned x1 char y1 ifxy printfxy else printfxyi expected xybut when i changed unsigned int to signed int i got expected results,['c'] +168408,read input from console in ruby i want to write a simple ab program in ruby but i have no idea how to work with the console,['ruby'] +168423,using php mysqli and prepared statement how i return the id of the inserted row i want retrieve the id of a inserted row in the database but i do not know how to do thisi tried to return using the sql clause returning id but not workshow i can return the id after the insertion of a row,"['php', 'mysql']" +168424,echo string while every long loop iteration flush not working i have a loop that takes very long to execute and i want the script to thisplay something whenever the loop iteration is doneecho helloflushfori 0 i 10 i echo i 510 sec execution time flushthis does not thisplay the echos until the entire script is completed what went wrong,['php'] +168441,defining a percentage width for a linearlayout i want to define a percentage width 70 for a linearlayout that contains some buttons so that i can center it and so that the child buttons can fill parent heres a picture showing what i meanmy current layout looks like thisxml version10 encodingutf8linearlayout xmlnsandroid androidlayout widthfill parent androidlayout heightfill parent androidididlayoutcontainer androidorientationvertical linearlayout androidlayout widthfill parent androidididbarcontainer androidorientationhorizontal androidlayout height40dp androidbackgrounddrawabletitlebackground imageview androidididbarlogo androidsrcdrawabletitlelogo androidlayout gravitycenter vertical androidadjustviewboundstrue androidlayout height25dp androidlayout widthwrap content androidscaletypefitxy androidpaddingleft5dpimageview linearlayout textview androidlayout heightwrap content androidlayout widthfill parent androidgravitycenter horizontal androidididsearchtip androidtextstringsearchtip androidpaddingtop10dp androidpaddingbottom10dptextview linearlayout androidlayout heightwrap content androidididlinearlayout1 androidorientationvertical androidlayout widthwrap content button androidtextbutton androidididbutton1 androidlayout widthwrap content androidlayout heightwrap contentbutton button androidlayout widthwrap content androidididbutton2 androidlayout heightwrap content androidtextbuttonbutton button androidlayout widthwrap content androidididbutton3 androidlayout heightwrap content androidtextbuttonbutton linearlayoutlinearlayoutthe linearlayout im referring to has the id linearlayout1 how do i do this,['android'] +168447,python self convention init vs method class myclassobject def init self selfvar hi def some methodself print selfvarfor the example belowmyclass myclaso i understand that the following statements are equivelentmyclasome methodmyclasome methodmyclassit takes object and passes it as the first argument self to some methodbut when i do myclass myclasshow does this flow work i am assuming its slightly different and some magic happens behind the scenes someone has some memory to allocatehow does that translate to init self what is passed to init myclass,['python'] +168457,java final variables in abstract classes in java i cannot create instances of abstract classes so why does not eclipse scream about the following codepublic abstract class footype private final int myvar public footype myvar 1,['java'] +168468,get position of mouse cursor on mouseover of google maps v3 api marker i am trying to make a div visible at the position of the cursor when the cursor mouseover a marker using jquery its kind of like a tooltip however i cannot seem to figure out how to get the xy coordinates of the point below the cursorcurrent codegooglemapseventaddlistenermarker mouseover functionevent tooltipcss position absolute top eventpagey left eventpagex togglei believe event does not have the properties pagey and pagex like in the event in jquery how do i get the osition of the mouse cursor,"['javascript', 'jquery']" +168482,longest increasing sequence 2d matrix recursion i have been presented with a new homework assignment that has been somewhat frustrating to say the least basically i have a create a 2d array of integers as follows97 47 56 36 60 31 57 54 12 55 35 57 41 13 82 80 71 93 31 62 89 36 98 75 91 46 95 53 37 99 25 45 26 17 15 82 80 73 96 17 75 22 63 96 96 36 64 31 99 86 12 80 42 74 54 14 93 17 14 55 14 15 20 71 34 50 22 60 32 41 90 69 44 52 54 73 20 12 55 52 39 33 25 31 76 45 44 84 90 52 94 35 55 24 41 63 87 93 79 24and i am to write a recursive method or function as you will to calculate the longest increasing sub sequence in this example the longest increasing sub sequence is the following50 with value 1260 with value 1461 with value 1562 with value 2072 with value 4473 with value 5274 with value 5463 with value 7153 with value 7443 with value 96so not only am i to check nsew for values strictly greater but i also have to account for diagonals i have done extensive research in how to solve this recursively however i have not had much luck and recursion is my weakest subject yes i know how powerful it can be in certain situations i have seen something similar posted where someone mentioned an acrylic graph but that is not what i am looking forso far i have basically padded my 2d array with 0s so that i do not have to worry about bounding and i am using nested for loops to traverse the 2d array within those loops i am basically checking if nneesesswwnw have a greater value than the current element sorry if i upset some of you this is my first attempt at a post if you need me to post some code i will do so thank you very much for your time,['java'] +168498,best way to select a row after inserting it i am working on an ios app using the navigation based coredata template i would like to select and scroll to visible a row after it was inserted into the table view ideally i would like to select it deselect it and select it again in order to get a kind of flashing effect as i am using the method that the template provaides namelypragma mark fetched results controller delegate voidcontrollerwillchangecontentnsfetchedresultscontroller controller selftableview beginupdates voidcontrollernsfetchedresultscontroller controller didchangesectionid nsfetchedresultssectioninfosectioninfo atindexnsuintegersectionindex forchangetypensfetchedresultschangetypetype switchtype case nsfetchedresultschangeinsert selftableview insertsectionsnsindexset indexsetwithindexsectionindex withrowanimationuitableviewrowanimationfade break case nsfetchedresultschangedelete selftableview deletesectionsnsindexset indexsetwithindexsectionindex withrowanimationuitableviewrowanimationfade break voidcontrollernsfetchedresultscontroller controller didchangeobjectidanobject atindexpathnsindexpath indexpath forchangetypensfetchedresultschangetypetype newindexpathnsindexpath newindexpath uitableview tableview selftableview switchtype case nsfetchedresultschangeinsert tableview insertrowsatindexpathsnsarray arraywithobjectnewindexpath withrowanimationuitableviewrowanimationtop selftableview selectrowatindexpathnewindexpath animatedyes scrollpositionuitableviewscrollpositionmiddle break case nsfetchedresultschangedelete tableview deleterowsatindexpathsnsarray arraywithobjectindexpath withrowanimationuitableviewrowanimationfade break case nsfetchedresultschangeupdate self configurecelltableview cellforrowatindexpathindexpath atindexpathindexpath break case nsfetchedresultschangemove tableview deleterowsatindexpathsnsarray arraywithobjectindexpath withrowanimationuitableviewrowanimationfade tableview insertrowsatindexpathsnsarray arraywithobjectnewindexpathwithrowanimationuitableviewrowanimationfade break voidcontrollerdidchangecontentnsfetchedresultscontroller controller selftableview endupdates i am a bit confused and do not know where to put that selection codeif i put atableview selectrowatindexpathnsindexpath animatedbool scrollpositionuitableviewscrollposition into voidcontrollerdidchangecontentnsfetchedresultscontroller controllerit selects the row but deselects it immediately and the scrolling does not behave as it should either,['ios'] +168499,cross compiling php i am trying to cross compile php for arm and have good progress but i am totally stuck where it wants to run the php itself have no idea why as it is an arm binary and not intel my building platform it would not runbinsh pathtobuildsapicliphp cannot execute binary filehow can i fix this the configure script understood i am cross compiling but did not do anything about it from configure logchecking whether the c compiler pathtocompilerarmnonelinuxgnueabigcc is a crosscompiler yesi am compiling php536 with configure command lineexport ccpathtoccarmnonelinuxgnueabigconfigure prefixprefixpath hostarmnonelinuxgnueabi thisablelibxml thisabledom thisableopenssl withouticonv withoutopenssl thisablesimplexml thisablexml thisablexmlreader thisablexmlwriter withoutpear withoutsqlite withoutsqlite3 thisablepdo withoutpdosqlite,['php'] +168506,jquery how to check if browser tabwindow the selected is on our page how do check if a the user has the browsers tabwindow currently on our pagefunction userisonourpagedo somethingand when a user switches the tabwindow to our page function tabswitcheddom something here toojust like in many places you switch to the page and the title changes i know the title can be changed with documenttitlebut dont know how to implement those functionsthanks d,"['javascript', 'jquery']" +168512,sql selecting rows where column value changed from previous row let us say i have this mysql database sorted by increasing timestamptimestamp system statusa statusb 20110101 a ok ok 20110102 b ok ok 20110103 a fail fail 20110104 b ok fail 20110105 a fail ok 20110106 a ok ok 20110107 b fail fail how do i select the rows where statusa changed from the previous row for that system statusb does not matter i show it in this question only to illustrate that there may be many consecutive rows for each system where statusa does not change in the example above the query should return the rows 20110103 statusa changed between 20110101 and 20110103 for systema 20110106 20110107the query should execute quickly with the table having tens of thousands of recordsthanks,"['mysql', 'sql']" +168531,is function pointer for there are these in type traitsis pointeris functionis member function pointerbut not thisis function pointerwhy is it so,['c++'] +168540,how to document css for a large site we maintain a fairly large site with a lot pages as the pages grew so did the html and css is there any good way to document these like which page uses a particular selector etc whats the best practice for maintaining css for a large site,"['html', 'css']" +168544,extjs 4 apply defaults to all columns in a grid now that extjs 4 got rid of the columnmodel object how do you apply default config options to all columns in a grid,['javascript'] +168549,rails 3 has and belongs to many migration i have two models restaurant and user that i want to perform a has and belongs to many relationshipi have already gone into the model files and added the has and belongs to many restaurants and has and belongs to many usersi assume at this point i should be able to do something like with rails 3rails generate migration but everything i have tried seems to fail i am sure this is something really simple i am new to rails so i am still learning,['ruby-on-rails'] +168561,getting an exception ora00942 table or view does not exist when inserting into an existing table i am getting below exception when trying to insert a batch of rows to an existing tableora00942 table or view does not exist i can confirm that the table exists in db and i can insert data to that table using oracle sql developer but when i try to insert rows using preparedstatement in java its throwing table does not exist errorplease find the stack trace of error belowjavasqlsqlexception ora00942 table or view does not exist at oraclejdbcdbaccessdberrorthrowsqlexceptiondberrorjava134 at oraclejdbcttc7ttioerprocesserrorttioerjava289 at oraclejdbcttc7oall7receiveoall7java573 at oraclejdbcttc7ttc7protocoldooall7ttc7protocoljava1889 at oraclejdbcttc7ttc7protocolparseexecutefetchttc7protocoljava1093 at oraclejdbcdriveroraclestatementexecutenonqueryoraclestatementjava2047 at oraclejdbcdriveroraclestatementdoexecuteotheroraclestatementjava1940 at oraclejdbcdriveroraclestatementdoexecutewithtimeoutoraclestatementjava2709 at oraclejdbcdriveroraclepreparedstatementexecuteupdateoraclepreparedstatementjava589 at quotecopydbconnectioninsertintodestinationdbdbconnectionjava591 at quotecopyquotecopiermainquotecopierjava72 can anyone suggest the reasons for this error update issue solvedthere was no problem with my database connection properties or with my table or view name the solution to the problem was very strange one of the columns that i was trying insert was of clob type as i had a lot of trouble handling clob data in oracle db before gave a try by replacing the clob setter with a temporary string setter and the same code executed with out any problems and all the rows were correctly insertedie peparedstatementsetclobcolumnindex clobwas replaced withpeparedstatementsetstringcolumnindex stringwhy an error table or view does exist error was throws for error in inserting clob data could anyone of you please explain thanks a lot for your answers and comments,"['java', 'sql']" +168575,translateanimation applied to an imageview leaves trail i have been recently struggling with the translateanimation framework provided by the android ui libraryi have designed a relativelayout which has a gridview taking up the 80 of the screen more or less and an imageview at the bottom of the screen the latter it is supposed to be moving around the botom of the screen constantly with random directionsheres the layoutimageview androidididbottom fish androidlayout alignparentbottomtrue androidadjustviewboundstrue androidcroptopaddingtrue androidscaletypecenterinside androidlayout widthwrap content androidlayout heightwrap content androidlayout marginbottom40dp androidlayout alignparentlefttrue androidlayout weight0 androidsrcdrawablelittle fish rightimageviewgridview androidididgridview androidlayout widthfill parent androidlayout heightwrap content androidlayout alignparenttoptrue androidlayout aboveidmouin bottom androidcolumnwidth90dp androidnumcolumns4 androidverticalspacing10dp androidhorizontalspacing10dp androidstretchmodecolumnwidth androidgravitycenterand heres the translateanimationtranslateanimation slide new translateanimationx0 newx y0 newyslidesetfillaftertrueslidesetinterpolatornew linearinterpolatorslidesetdurationduration slidesetanimationlisteneranimationlistenerivstartanimationslidex0 newxy0 newythe animationlistener assigned to the animation just calls this method on the onanimationend functionthe matter is that when the image is moving from right to left it eventlually leaves bitmap traces on the screen being removed after a whileany idea where the problem could be placed thank you,['android'] +168580,how do i make a dropdown menu like this in the evernote app when you click the middle icon in the action bar a dropdown menu appears how do i make one of these relativelayouts,['android'] +168606,what does posix memalignmemalign do i am trying to understand what functions memalign and posix memalign do reading the available documentation did not help can someone help me understand how it works and what is it used for or perhaps provide a usage examplei am trying to understand how linux memory works i need to write my own simple memory pool lowfragmentation heap,['c'] +168616,can a c method return a method can a method in c return a methoda method could return a lambda expression for example but i do not know what kind of type parameter could i give to such a method because a method is not type such a returned method could be assigned to some delegate consider this concept as an examplepublic unknown type quadraticfunctionmakerfloat a float b float c return x return a x x b x c delegate float functionfloat xfunction quadraticfunction quadraticfunctionmaker1f4f3f,['c#'] +168620,m pi works with mathh but not with cmath in visual studio i am using visual studio 2010 i have read that in c it is better to use cmath rather than mathh but in the program i am trying to write win32 console application empty project if i writedefine use math definesinclude mathhit compiles while if i writedefine use math definesinclude cmathit fails with error c2065 m pi undeclared identifieris it normal does it matter if i use cmath or mathh if yes how can i make it work with cmathupdate if i define use math defines in the gui it works any clue why this is happening,['c++'] +168641,convert hexadecimal unicode character into its visual representation i am trying to make a c program that translates unicode character from its hexadecimal format to a single character and i have a problem this is my codethis workschar e converttocharu0066 however this does not workconsolewritelineenter unicode format character for example u0066string s consolereadlineconsolewritelineyou entered for example fchar c converttochars because converttocharu0066 gives the errorstring must be exactly one character long anyone have an idea how to do this,['c#'] +168649,iphone shine animation i am trying to get my view to do a nice shining animation to catch the users eyes any ideas how to implement thisheres what i have so faruiview beginanimationsviewshine contextselfviewuiview setanimationrepeatautoreversesnouiview setanimationrepeatcount0uiview setanimationduration2uiview setanimationdelegateselfdo nice shining animation hereuiview commitanimationsby shine i mean something like what happens to the slide to unlock text when you open the iphone or anything that is easy to do and looks nice,"['iphone', 'objective-c']" +168664,clarification on why this c code works i am learning c today i have been coding in managed languages java c python etc for some time now i thought i was understanding the details of pointers but then i wrote the following code that worked as expected but generated an incompatible pointer type warningvoid settextchar output code to set output to whatever no problems hereint mainint argc const char argv char output10 settextoutput edited other test code which printfs and further manipulates output return 0so i googled and ended up changing the linesettextoutputtosettextoutputwhich got rid of the warning but now i do not know why the first one was working at all i was sending the address of an address as far as i can tell because char x is essentially the same as char x what am i misunderstanding and why do both of these work,['c'] +168671,why does wrap content fire bindview more than once i am working on an android app with a listview and am in the process of optimizing it it uses a custom cursor adapter in one activity and i noticed that bindview was firing twice for each row of the list while researching the bindview and newview methods here i read in a post that having wrap content for the width of my listview was a bad idea i switched it to fill parent and viola now bindview and newview each only fire once for each itemso that i can better understand the internals of the andorid os i would like to know why wrap content caused bindview to fire multiple timesi have done several searches on google the android developer docs and here with no luckany response is really appreciatedthanksgeorge,['android'] +168697,javascript clientside routingpathing library i am in the need for a routing library to handle my paths for a client side js appi am currently using backbonejs which while great is not fully featured enoughi am looking for a dedicated pathing library that i can replace backbone with only in terms of pathing still want to use that for mvc something with a lot of featuresthanks,['javascript'] +168730,c to musicxml anyone know of any libraries that can be used to write musicxml data from c similar to this although this one is for javai would try to not write it manually but if worse comes to worst i will have no choice but to output and write musicxml manually from my results,['c#'] +168733,mysql making a column unique i have a table that is in production i realize that some of the columns should be unique is it safe to go into phpmyadmin and change those columns to make it uniquealter table foo add unique bar,['mysql'] +168739,firefox and javascript rounding rules i do not know if i am missing something obvious here butin ie opera and chrome i get what i expect from rounding numbers ending in a 5125 toprecision2 130115 toprecision2 12this is what i would expectfirefox though is a little more sophisticated yielding the following125 toprecision2 120 wtf115 toprecision2 12after a bit of head scratching i have come to the conclusion that firefox is using a rounding even rule where if the digit before the 5 is even the number rounds down and if the digit before the 5 is odd the number rounds up05 015 225 235 4 etci am using the rounded results to test student solutions to engineering questions with pseudorandomly generated question inputs a question input in chrome could be h1020 mm but h1030 mm in ff chrome or operai need a function to make rounding consistent ie i want 01235 to round up to 0124 and i want 1234 to round to 1240 so i cannot use a simple num mathfloornum 05 to complicate matters a bit i want input variables and student answers to be correct to 3 sig digs unless the first digit is a 1 in which case i want 4 sig digs2345 2351345 1345i have hacked a solution to the 3 or 4 sig digs depending upon the first digit by converting the number to a string and testing the first nonzero nondecimal point and nonnegative character for 1 not pretty but it works i could do something similar for the rounding problem checking whether the digit to be rounded is a 5 but i am wondering if there is an elegant bitwise solution,['javascript'] +168742,is mysql temporary table a shared resource i have a mysql stored procedure that uses a temporary table assume that my table name is temp and i use it to store some middle data it will create at the beginning of procedure and will drop at the endcreate procedure pbegincreate temporary table tempinsert into temp valuesdrop temporary table tempendthe problem is that this stored procedure may be used by different users concurrently so i want to know if this can cause any problems ie any conflict in inserted data in temp table in other word is temp table a shared resource within different calls to the same sp,['mysql'] +168748,what does swingutilitiesinvokelater do what does swingutilitiesinvokelater do is it just delaying the execution of a block of codes inside its run method what is the difference between calling an action within the invokelater function or simply calling it at the end of the thread we want to be executed can anyone help me with what really does the invokelater function do,['java'] +168762,uilabel background obscured when uitableviewcell is selected i have some uilabel inside a uitableviewcell with opaque background color and white text when this cell is selected the uilabels bg color seems to be obscured by the blue bg color of the selected cell the uilabel text however is showing fine how do i get the background color of the uilabel to show on top of the cell selection color,"['iphone', 'objective-c', 'ios']" +168774,match parent compatibility my application targets the v10 of the android sdk but has the v6 for minsdkversion by default the match parent propertie will be used for the width or height should i change it for fill parent to ensure backwards compatibility of device with android under 22,['android'] +168776,mongodb java how to return restricted fields with find or findone with the driver java mongodb i am looking for a way to return just restricted fields with a find or findonefor example i have a collection people with fields id name surname address city and i just want to return name and surnamei searched on the web and i just found this example of code java mongodb mongodbjava examplehtml,['java'] +168779,how to decompress gzip in stream c this code receives the gzipencoded string how can i decode itstream stream retgetresponsestreamsystemiostreamreader reader new systemiostreamreaderstream encodingdefaultstring answer readerreadtoendanswer is gzip encoded string byte bytes encodingdefaultgetbytesanswergzipstream compstream new gzipstreamstream compressionmodedecompress whats next,['c#'] +168784,resigning an application outside xcode i have some apps i wanna resign with a different apple developer licenseproblem is i dont have source code only the ipa file the app and the archiveinfoplistis it possible for me to resign the app if i dont have the source codethanksompah,['iphone'] +168826,what is the best way to generate a login token is this method of authentication vulnerable to attack i have to implement login tokens in my lithium the php framework based application two reasonsi want to have a remember me functioni also need a way of tracking logins on the server so that i can verify authenticated users on a nodejs socket server like souser requests a pageserver returns a view with a session token somewhere in the htmlthe client side js reads the token and send it to the nodejs server in an attempt to establish a connection via web socketsthe server receives the connect request and verifies the token sent to it with the php serverallows or denies a connection based on the resultso this is a two part question and it is just to verify that i am not being an idiot because the security on this site is of higher priority than usualis this a reasonable way of creating a login tokenphp stringhash generates a sha512 by default hash stringhashtime userusernameis the web socket authentication system i proposed sane can you see any problems arising or any more efficient ways of doing it,['php'] +168841,porting pulse audio on android i am planning to port pulse audio on android i have compiled it on ubuntu after removing the optional parts like x dependency oss support etc and i am able to remote my sound to a network server running windows7 now i want to port this to android any idea on how to start would be appreciated or a link to some page which is doing some thing similar that can get me started with a basic makefile infrastructurethanks,['android'] +168848,how to use mef inherited export metadata i have an interface inheritedexporttypeofimetricpublic interface imetric i have a meta attribute interface public interface imetricattribute and an attribute that implements it metadataattributeattributeusageattributetargetsclass allowmultiple falsepublic class metricattribute exportattribute imetricattribute public string metricname get set public string metricdescription get set public metricattributestring name string description basetypeofmetricattribute thismetricname name thismetricdescription description i then have two classes metricmetricametricapublic class metrica imetric exporttypeofimetric this is importantmetricmetricb metricbpublic class metricb imetric i then try to import the metrics i can see both in the catalogethe following returns be metrica and metricbvar metrics compositioncontainergetexportsimetrichowever the following returns only metricb and not metrica var metrics compositioncontainergetexportsimetric imetricattributeany idea why note the duplicate export on metricb it already has it from implementing imetricthanksdavid,"['c#', '.net']" +168884,check if a given dom element is ready is there a way of checking if the html dom elements for a given selectorelement are ready yet using jquery or javascript looking at the jquery api for the ready function it looks like it can only be used with the document object if ready cannot be used for this purpose is there another way of doing thiseg h1readyfunction do something when all h1 elements are readyobviously i could use documentreadyfunction do something when all h1 elements are readybut if all the h1s load first then the code specific to h1 elements will only execute after the whole document is ready even though it could actually execute earlier,"['javascript', 'jquery']" +168889,order by date and time before group by name in mysql i have a table like thisname date timetom 20110704 010952tom 20110704 010952mad 20110704 021053mad 20090603 0101i want oldest name first select order by date asc time asc group by namedoes not worknow it should give me first madhas earlier date then tombut with group by name order by date asc time asc gives me the newer mad first because it groups before it sortsagain the problem is that i cannot sort by date and time before i group because group by must be before order by,['mysql'] +168896,is it possible to use textoverflowellipsis on multiline text i have a ptag with a specific width and height i want to use textoverflowellipsis to get if the text in the tag is too long is this possible to solve with css on multiline text,"['html', 'css']" +168904,boostproperty tree xml pretty printing i am using boostproperty tree to read and write xml configuration files in my applicationbut when i write the file the output looks kind of ugly with lots of empty lines in the filethe problem is that it is supposed to be edited by humans too so i would like to get a better outputas an example i wrote a small test program include boostproperty treeptreehppinclude boostproperty treexml parserhppint main void using boostproperty treeptree ptree pt reading filexml read xmlfilexml pt writing the unchanged ptree in file2xml boostproperty treexml writer settingschar settingst 1 write xmlfile2xml pt stdlocale settings return 0filexml containsxml version10 config net listenport10420listenport netconfigafter running the program file2xml containsxml version10 encodingutf8config net listenport10420listenport netconfigis there a way to have a better output other than going manually through the output and deleting empty lines,['c++'] +168932,waiting on a task with a onlyonfaulted continuation causes an aggregateexception i have some simple code as a reprovar tasktest taskfactorystartnew systemthreadingthreadsleep50continuewithtask t consolewritelineerr taskcontinuationoptionsonlyonfaultedtry taskwaitalltasktestcatch aggregateexception ex foreach var e in exinnerexceptions consolewritelineemessage environmentnewline estacktracehowever i am getting an unexpected taskcanceledexception being thrown in the try catch block it is in the aggregateexception innerexceptions object a task was canceledwhy am i getting this exception the continuation for the task never fires there was no exception generated by it yet i still get the aggregate exception when waitingi am hoping someone can explain how this makes sense to me,['c#'] +168979,how to pass the id of an element that triggers an onclick event to the event handling function how do i pass the id of an element that triggers an onclick event to the event handling functioni am doing something like thislink onclickdowiththiselementid of this element,"['javascript', 'html']" +168991,are there any examples of ios apps written using pyobjc the only references i can find state that it is theoretically possible to write ios apps using python does anyone know of any examples of apps that were written this way,"['python', 'ios']" +168993,notification to restore a task rather than a specific activity i have a foreground service that keeps a connection open with the server as long as the user is logged into the application this is so that the connection is kept alive and can receive messages directly from the server even when the application has been sent into the background by the user pressing homethe application has a number of activities any of which could be the active one when it is sent into the backgroundi would like to allow the user to click on the notification to restore the current activity i understand how to restore a particular activity but wondered if there is a way to restore the last activity that the user was on of course i could keep track of the the last one and then call that from the notification callback but thought there might be a way at a task levelthanks for any advice you can offer,['android'] +169019,apple push notifications how do i properly export my cert i cannot seem to figure out how to properly export my cert for use in my ios app with push notifications i am using the following cert downloaded from the certificates section of the ios provisioning portali am then following one of the many tutorials i have found all over the web that are all different by the way to get my cert into a pem format for use in rubyapnsfirst i export it from the keychainafter i give it a name and a password i perform the following commands in the terminalopenssl pkcs12 in certp12 out apple push notification devpem nodes clcertsnote this is not the only way i have tried this just the latest i have also tried via the instructions at the following urls the apple push notification servicenot a single one of these solutions work i am sitting here looking at the following error from the console when i try to use rubyapnsread finished a sslv3 alert certificate unknown opensslsslsslerrorand essentially every other server solution i have found has told me my certificate is incorrect or that there is a problem with it as wellam i doing this wrongovernight courtesy bump stealth editso i beat my head against the wall last night and actually came across apples own instructions for doing this it is almost the exact same and i tried it to the same tune nevertheless here is the latest attempt from this linkopenssl pkcs12 in certificatenamep12 out certificatenamepem nodes,['iphone'] +169028,how to stitch several pdf pages into one big canvaslike pdf i have a 32page pdf of my family tree instead of having the family tree all on one really big pdf page which is what i want it is formatted so a group of 8 individual us lettersized pages are supposed to be stitched across the width 4 rows of this completes the tree the margins of each page are all 22pxif you visualize it in table form where the numbers represent pdf page numbersi have tried to whip up some python code to do this but have not gotten very far how can i stitch the pdf so it can be one big page instead of smaller individual pagesthanks for the helpedit heres the code i wrote sorry for not originally posting itfrom pypdf import pdffilewriter pdffilereaderstitchwidth 8currentpage 1output pdffilewriterinput1 pdffilereaderfilefamilytreepdf rbfori0 i4 i outputaddpageinput1getpagecurrentpage currentpage do something to add other pages to widthprint finished with stitchingoutputstream filefamilytreestitchedpdf wboutputwriteoutputstreamoutputstreamclose,['python'] +169045,c glass forms how can i use aero glass to cover my entire forms here is an example of what i mean,['c#'] +169046,connecting actions to buttons in xcode how do i connect a button added in interface builder to an action this is what my instructions for adding a forum component in to my app it says connect the action of that button to your launchsatisfactionremotecomponent method in ib this would need to happen in my supportxib window where is the code where you connect the action to that,['objective-c'] +169085,calling a static method from a class in another namespace in php this code bellow gives me this error class mynamespacedatabase not found how do i reference a class that belongs to no namespace from inside one class database public function request namespace mynamespace class myclass public function myfuction databaserequest,['php'] +169093,sending packets to 255255255255 by java datagramsocket fails i am programming a networking program in java and i want to send some packets to 255255255255 but it fails even when i send them to 1921681255 which according to the output of ifconfig command is the broadcast address but when i send them to my mates ip it works fine heres the code to my program public class stackoverflow public static void mainstring args network net new network scanner input new scannersystemin whileinputhasnext netsendmessageinputnextline i have used datagarmsocket and datagrampacket to do so heres my implementation of the network class network datagramsocket socketpublic network try socket new datagramsocket8027 socketsetbroadcasttrue socketconnectinetaddressgetbyname255255255255 8027 catch exception e systemerrprintlnconnection failed egetmessage listenpublic void listen new thread public void run while true try byte buf new byte10 datagrampacket packet new datagrampacketbuf buflength socketreceivepacket string message new stringbuf systemoutprintlnrecieved message if messageequalsend return catch exception e systemerrprintlnegetmessage startpublic void sendmessagestring message byte buf messagegetbytes datagrampacket packet new datagrampacketbuf buflength try socketsendpacket catchexception e systemerrprintlnsending failed egetmessage no exceptions are being throwni am in an ad hoc networki am using mac os x 106 while my mate is using kubuntu 1104and here is ifconfig outputlo0 flags8049uploopbackrunningmulticast mtu 16384inet6 1 prefixlen 128 inet6 fe801lo0 prefixlen 64 scopeid 0x1 inet 127001 netmask 0xff0 gif0 flags8010pointopointmulticast mtu 1280stf0 flags0 mtu 1280en0 flags8863upbroadcastsmartrunningsimplexmulticast mtu 1500inet6 fe8021ff3fed54779en0 prefixlen 64 scopeid 0x4 inet 19216811 netmask 0xf00 broadcast 1921681255ether 001ff3d54779 media autoselect 100basetx fullduplex status activesupported media autoselect 10basetutp halfduplex 10basetutp fullduplex 10basetutp fullduplexhwloopback 10basetutp fullduplexflowcontrol 100basetx half duplex 100basetx fullduplex 100basetx fullduplexhwloopback 100basetx fullduplexflowcontrol 10baset fullduplex 10baset fullduplexhwloopback 10baset fullduplexflowcontrol noneen1 flags8863upbroadcastsmartrunningsimplexmulticast mtu 1500inet6 fe8021d4feff2b4den1 prefixlen 64 scopeid 0x5 inet 21323317097 netmask 0xfc00 broadcast 213233171255ether 001d4f2b4d media autoselect status activesupported media autoselectfw0 flags8863upbroadcastsmartrunningsimplexmulticast mtu 2030lladdr 0021e9febc79b2 media autoselect fullduplex status inactivesupported media autoselect fullduplexen2 flags8863upbroadcastsmartrunningsimplexmulticast mtu 1500ether 001ff3b62cbe media autoselect status inactivesupported media none autoselect 10basetutp halfduplexvmnet1 flags8863upbroadcastsmartrunningsimplexmulticast mtu 1500inet 1921681491 netmask 0xf00 broadcast 192168149255ether 005056c01 vmnet8 flags8863upbroadcastsmartrunningsimplexmulticast mtu 1500inet 192168731 netmask 0xf00 broadcast 19216873255ether 005056c08 en0 is the device i am using to connect to my mateplease make it simple i am a newbie thanks in advance,['java'] +169095,how to achieve alignparentbottomtrue property in linearlayout if i want to set an image to the bottom of any screen then we can use androidlayout alignparentbottomtrue in relative layout but because of some reason i am bound to use linearlayout there are other views button image button listview in the screen also i want to place image at the bottom of my screen whatever may be the situation user wil be able to see this imageview at the bottom of the screen how to achieve alignparentbottomtrue property in linearlayout see the folowing sample xml i am using example1xml but i want look and file that of example2xmlexample1xml xml version10 encodingutf8linearlayout xmlnsandroid androidlayout widthfill parent androidlayout heightfill parent textview androidididtextview1 androidlayout widthfill parent androidlayout height40dip androidbackgroundf androidtextcolor0 androidtexti am sunil androidgravitybottomlinearlayoutexample2xmlxml version10 encodingutf8 relativelayout xmlnsandroid androidlayout widthfill parent androidlayout heightfill parent textview androidididtextview1 androidlayout widthfill parent androidlayout height40dip androidbackgroundf androidtextcolor0 androidtexti am sunil androidlayout alignparentbottomtrue relativelayoutthanks,['android'] +169096,how to concatenate all strings from a certain column for each group suppose i have this table table1name mark abc 10def 10ghi 10jkl 20mno 20pqr 30what should be my sql statement to retrieve a record that looks like thisgroup by marki have done the 1 and 2 columns but do not know how to accomplish the third column concat the name with the same markmark count names 10 3 abcdefghi20 2 jklmno30 1 pqri am using microsoft sqlplease help thanks,['sql'] +169102,getting locales on ios 5 i have this piece of code that gets a few information current country country name from nslocaleit works without any problem in ios 43 but crashes in ios 5 upon checking it seems that locale localeidentifier and locale thisplaynameforkey value does not work at all but no warnings and errors were detected while building itwhat can i do to get it working in ios 5 create a pool for autoreleased objects nsautoreleasepool pool nsautoreleasepool alloc init get the current country and locale information of the user nslocale locale nslocale currentlocale nsstring currentlocaleid locale localeidentifier returns en us instead of the actual country stored in phone settings nsdictionary localedictionary nslocale componentsfromlocaleidentifiercurrentlocaleid nsstring currentcountry locale thisplaynameforkeynslocalecountrycode valuelocaledictionary objectforkeynslocalecountrycode returns nil get the list of country codes nsarray countrycodearray nslocale isocountrycodes nsmutablearray sortedcountrynamearray nsmutablearray array for nsstring countrycode in countrycodearray nsstring thisplaynamestring locale thisplaynameforkeynslocalecountrycode valuecountrycode thisplaynamestring is nil after executing this line sortedcountrynamearray addobjectthisplaynamestring app crashes here drain the autoreleased pool pool drain,['iphone'] +169121,how to link project in eclipse i have a java project and i want to develop it without replacing the source code from its place i want to link my code to my workspace without replace physically,['java'] +169123,how to delete cookies in aspnet i would like to know can we delete cookie from cookies collection what we have created in aspnet websitei tried find expiration logicit works but it shows in browser cookie responsecookiesuseridexpires datetimenowadays1is there any other way by this we can delete cookies from collection so it will not show in browser cookiesplease help me to solve the issuethanks in advance,"['c#', '.net', 'asp.net']" +169125,serialize form not working in jquery can you please take a look and help me realize where am i going wrong with this here is the jsfiddle link but also here is that code htmlform action idgamesform p input idgname typetext classmedium span classnotification informationgame namespan p p span classnotification informationenabledspan input idgenabled typecheckbox p br additional data for extra type div idextraadditionaldata classhidden p input idrracers typetext classmedium span classnotification informationracersspan p p input idrvideoset typetext classmedium span classnotification informationvideo setspan p div forma href idsaveconfiguration classgraybuttonbigsave everythinga javascriptdocumentreadyfunction saveconfigurationclickfunction alert formserialize all i am getting is an empty string thx for your help,['jquery'] +169132,testsuite setup in junit 4 i have managed to find out how to make a testsuite in junit 4 but i really miss the v3 possibility of wrapping a suite in a testsetupany ideas as to how to get some beforeclassafterclass setup executed for a suite of test cases in junit 4ierunwithsuiteclasuitesuiteclassestest1class test2classpublic class mytestsuite beforeclass public static void setupclass common initialization done once for test1 test2 afterclass public static void teardownclass common cleanup for all tests unfortunately the above code fragment does not work beforeclass only works on a pertestclass basis,['java'] +169147,how to make an application to run in portrait mode only in my application if i want to restrict an activity to work in portrait mode only then i have to write androidscreenorientationportrait in the manifest file against activity tag if i want to force all activity to work in portrait mode then i have to write the same in all activity is there any applicationwise setting so that i need not have to write this in all activities how to make an application to run in portrait mode onlyi am using the following now activity androidscreenorientationportrait androidconfigchangeskeyboardhiddenorientation androidnamemyactivityactivity,['android'] +169148,check if one of variables is set to none i recently had to implement a small check for any variables that might have not been initialized and their default value is none i came up with thisif none in var1 var2 var3 error outwhile in my eyes bordering on beautiful i was wondering is this a good way to do it is this the way to do it are there any cases in which this would produce some unexpected results,['python'] +169157,filtering dropdown values in django admin class foomodelsmodel title modelstextfield userid modelsintegerfield image modelscharfieldmax length100 def unicode self return selftitleclass barmodelsmodel foo modelsforeignkeyfoo related namefoo picks uniquetrue added on modelsdatetimefieldauto now addtruein django admin add viewdef add viewself args kwargs selfexclude added on selfreadonly fields return superbar selfadd viewargs kwargsso field shows in the admin add view is foo which is a drop down list and shows all the titles some title of foo remains empty or so drop down list have lots of empty value because it title is empty i want to filter out those empty values,['python'] +169161,nsintegermax vs nsuintegermax nsuinteger index selfobjects indexofobjectobjif index nsnotfound success note nsnotfound internally uses nsintegermaxif index nsuintegermax failswhy i am suppose to get an unsigned value as a result of indexofobject so naturally i was assuming that if the object is not found it will return nsuintegermax instead of nsintegermax is this a bug or is there a logical explanation for this behavior,['objective-c'] +169162,whats the difference between htmlelement and element whats the difference between htmlelement and element documentcreateelementdiv instanceof element gives truedocumentcreateelementdiv instanceof htmlelement gives truehtmlelement element gives false,['javascript'] +169168,executing show desktop from c i am designing a system where the user makes a gesture then my program captures it using a web cam and my program looks in a rule system based on xml which are the actions that it has to dook once i have explained the background i would like to know how i could make my program execute the show desktop button i would like to provide the user the possibility to do a gesture and show the desktop is it possible i have been looking the program exe that executes the show desktop button and i am afraid that does not exist,['c++'] +169169,registry access with c and build x86 on a 64bit machine i have an application written in c which runs on an windows server 2008 64bit in this application i must check some registry keys regarding the iis among others i want to access the key hkey local machinesoftwaremicrosoftinetstpcomponentswmicompatibilityto check if the iis 6 compatibility mode is enabled or not for this i use registrygetvalue of microsoftwin32for some reasons the solution must be compiled with x86 the consequence is that it is no longer possible to access hkey local machinesoftwaremicrosoftinetstpcomponents but it is still possible to read key from hkey local machinesoftwaremicrosoftinetstp when compiling it with anycpuflag the registryaccess works fineso what is the reason for this behavior is there a solution or workaround for this problem,"['c#', '.net']" +169170,top 1 faster if only selecting one row does the database break the selection loop as fast as it has got one record when using top 1so that select top 1 from customer where cusid 1234is faster thanselect from customer where cusid 1234cusid is unique so does mssql understand to do it faster without top 1,['sql'] +169187,why does firefox not pass all mouse wheel events to my javascript application i am using the protovis library to draw a graph i uploaded the code i am using in case someone wants to take a look at ithere is my problem under firefox when i use the mouse wheel to zoom in or out some mouse wheel events are not captured by my application but by firefox itself the result is that i end up getting a mix of zooms and page scrolls you can test this by shrinking the firefox window until the scroll bar gets visible this problem does not occur under opera why does it happen and how can i solve itthanks a lot in advance,['javascript'] +169206,javascript object get code as string first off i am sorry if this is a duplicate but every time i googled for object and code i got tutorial pagesi want to know if there is any easy way to get the code associated with an object something likefunction a thisname kaiser sauzea new aconsolelogathisplaycodeoutputfunction a thisname kaiser sauzei want to be able to view the code modify it and reload the function all from within the browser i wanted to know if there was some way to do this or if i have to prime the pump by doing something like thisfunction a thisname kaiser sauze thiscode function a thisname kaiser sauzethen every time the user loads up the text editor to view thiscode i connect the onchange to update thiscodeeditturns out yankee suggested a simple solution to thisfunction ax thisx x consolelogatostringoutputfunction ax thisx x but in my implementation the variable x can be a function actually a complicated object with variables functions and sub objects which i mix in via a call to dojomixin so what i really want is to know the code when instantiated something like sofunction ax thisx x var a new afunctiondo somethingconsolelogatostringoutputvar a new afunctiondo somethingbut as most of you already know all that gets output is something like object i have almost found a way around this by putting the initialization in a function like sofunction ax thisx x function a var a new afunctiondo somethingconsolelog atostringoutputfunction a var a new afunctiondo somethingbut that is confusing and then i have to go in and start parsing the string which i do not want to doedit the reason i ask all of this is bc i want to make code that is both dynamically executable and highly modular i am dealing with the canvas i want the user to be able to click on a for example rectangle view its code and modify and then loadexecute it i have a series of rules but basically i have a shape class and everything that defines that shape color transparency fills strokes has to get passed as a parameter to the object cosntructor something likerect new shapecolor rgba01 x 0 y 0 w 100 h 100 draw function ctxfillstyle thiscolor ctxfillrectthisxthisythiswthish this way the code is automatically modular i do not have to worry about the color being defined at the top of the page and then the height being defined half way down the page and so on now the only thing i need is to somehow pass as a parameter the entire above string representation of the initialization i could wrap it in a function and call tostring on that like sofunction wrapper rect new shapecolor rgba01 x 0 y 0 w 100 h 100 draw function ctxfillstyle thiscolor ctxfillrectthisxthisythiswthish code wrappertostring but then there are two problems 1 i have to manually remove the function wrapper and trailing as well as moving every line to the left by one tab 2 there is no guarantee that a user will remember to include the wrapper function as it is totally unecessary for purposes of drawing i am trying to think of a way where the wrapper would seem natural but i cannot think of any but then again i have not slept in over 30 hours,['javascript'] +169211,how can i prevent views from overlapping in relative layout right now i have two textviews one on aligned to the left of the relative layout and one aligned to the right the text on the left is much longer than that on the right on some occasions the text on the left is two lines when this happens this text overlaps the text that is aligned to the right is there anyway to prevent this or is there a way to say if the text on the left is two lines put the text on the right on the second linei am having trouble with name and time down here relativelayout androidlayout widthwrap content androidididrelativelayout androidlayout heightwrap content textview androidtexttextview androidididname androidlayout widthwrap content androidlayout heightwrap content androidlayout marginleft10sp androidtextstylebold androidtextsize16sptextview textview androidlayout widthwrap content androidididaddress androidtextaddress androidlayout heightwrap content androidlayout belowidname androidlayout alignleftidname androidlayout marginleft30sptextview textview androidlayout widthwrap content androidlayout torightofidaddress androidtext androidlayout heightwrap content androidlayout aligntopidaddress androidlayout alignbottomidaddress androidididcrostreettextview textview androidlayout widthwrap content androidididtime androidtexttime androidlayout heightwrap content androidlayout alignparentrighttrue androidlayout marginright10sptextviewrelativelayout,['android'] +169230,how to write a better strlen function i am reading write great code volume 2 and it shows the following strlen impelementationint mystrlen char s char start start s while s 0 s return s startthe book says that this implementation is typical for an inexperienced c programmer i have been coding in c for the past 11 years and i cannot see how to write a function better than this in ci can think of writing better thing in assembly how is it possible to write code better than this in c i looked the standard library implementation of the strlen function in glibc and i could not understand most part of it where can i find better information on how to write highly optimized code,['c'] +169233,json serialization in c what is the best way to generate utf8 json in c i have looked at jansson but it seems extremely bulky is there any other good lowdependency library for creating and reading json objectsstrings in c,['c'] +169240,email anonymization similar to craigslist in c i am developing a site for which i would like to protect buyers by anonymizing their email addressessimilar to craigslists system when a seller needs to contact a buyer they should be able to send an email to an anonymized address such as which will then be routed to the users email address my plan right now is toset up a bucket catchall inboxgenerate a random key for each buyer which will be the user specific 1425415125 above section of the email addressmonitor the bucket inbox and parse out this user specific section once i know the user the email can be forwarded to the correct addressmy questions are as followscan you see any issues with the above solutionare there any open source solutions to the existing problemare there any gotchas that one should be aware of when developing such a systemthanks in advancejp,['c#'] +169269,cannot call a class method with self themethod i am trying to write a class method in objective c the project builds fine when i declare the method but the build fails whenever i try to call the method here is my codeheader fileimport uikituikithinterface loginviewcontroller uiviewcontroller declare vars ibaction login id sender nsstring md5hashnsstring strendsource file nsstring md5hashnsstring str const char cstr str utf8string unsigned char result16 cc md5 cstr strlencstr result return nsstring stringwithformat 02x02x02x02x02x02x02x02x02x02x02x02x02x02x02x02x result0 result1 result2 result3 result4 result5 result6 result7 result8 result9 result10 result11 result12 result13 result14 result15 ibaction login id sender call the class method self md5hashtest,['objective-c'] +169271,why does this code not work on ruby 19 but works on ruby 18 i downloaded the lasted stable ruby source code from the ruby website 192p180 and compiled it on windows with mingw 452tdm and msys to compile i ran sh configure and make i got msvcrtruby191dll and libmsvcrtruby191dlla exactly as expected then i wrote this codeinclude rubyhint main ruby init rb funcall2qnil rb internp 1 valueint2fix0 ruby finalizei compiled with g linking to the rubys dll when i ran the executable i got this error messagemain bug segmentation faultruby 192p180 20110218 revision 30909 i386mingw32 control frame c02 p s04 b04 l03 d03 cfunc pc01 p0 s02 b02 l00120c d00120c top ruby level backtrace information ruby0in pnoteyou may have encountered a bug in the ruby interpreter or extension librariesbug reports are welcomefor details this application has requested the runtime to terminate it in an unusual wayplease contact the applications support team for more informationthe problem is the same code works perfectly when linked with the ruby 187 what is wrong here,"['c', 'ruby']" +169282,horizontal justificationalignment of list items i have the following situationnav idaccess rolenavigation div classmenu ul li classpage itema hrefpricing titlepricingpricingali li classpage itema hrefbooking titlebookingbookingali li classpage itema hrefcontact titlecontactcontactali li classpage itema hrefmap titlemapmapali ul divnavsince the outer container where the nav sits in is like 800px wide the nav container is also 800px wide access menu ul li float lefti am floating all menu elements left so the align side by side i wonder how i can create equal space between all those list items like this this is what i have nowitem item item item item this is what i wantitem item item item itemany idea how to solve this either with pure css or jquery,"['jquery', 'html', 'css']" +169286,printing html tables without splitting a row across two pages i need to print some data in an html table from internet explorer various versions and safari on os x ignoring safari for the momentwhen printing a table that has more rows than can fit on a page the last row on the page is often split with part of the row on the first page and the rest of the row on the next pagethis looks ugly is there a way to avoid iti have been searching around and so far i have found pagebreakbefore always but i am not sure if that is what i am looking for since i would not know up front how many rows will fit on the page eg the rows might be taller or shorter depending on the content and the user might be printing in portrait or landscape mode i am assuming a4 at least but if the user was using us letter or some other paper size it would introduce even more uncertainty also what about printer marginsso is there a way around this or do i just have to guess how many rows will fit and force a page break after that will that even work,"['html', 'css']" +169288,python convert list of keyvalue tuples into dictionary i have a list that looks like thisa 1 b 2 c 3and want to turn it into a dictionary that looks likea 1 b 2 c 3whats the best way to go about this thanksedit it is actually more likea 12937012397 bera 2034927830 ce 2349057340,['python'] +169296,custom view calling startactivityforresult i created custom compound view where i incorporate functionality to take pictures i am calling it like this from viewintent intent new intentandroidprovidermediastoreaction image captureactivitymcontextstartactivityforresultintent indexthis part works good what i do not know how to do is how do i implement onactivityresult inside my custom viewor should i catch this inside activity and than reroute into my view does not look like very nice solution,['android'] +169300,how does javascript vm implements object property access is it hashtable objects in javascript can be used as hashtablethe key must be stringis it perform well as hashtable the data structurei mean does it implemented as hashtable behind the sceneupdate 1 i changed hashmap to hashtable 2 i guess most of the browser implement it the same if not why not is there any requirement how to implement it in the ecmascript specsupdate 2 i understand i just wonder how v8 and the firefox js vm implements the objectproperties getterssetters,['javascript'] +169314,change to database to online and set db to multiuser i have a 2008 sql database that is offline that i would like to take online and set to multiuser using sql server management studio new query window when i execute the following alter database mydb set online alter database mydb set multi useri receive this error messagemsg 5064 level 16 state 1 line 1 changes to the state or options of database mydb cannot be made at this time the database is in singleuser mode and a user is currently connected to it msg 5069 level 16 state 1 line 1 alter database statement failed msg 5064 level 16 state 1 line 3 changes to the state or options of database mydb cannot be made at this time the database is in singleuser mode and a user is currently connected to it msg 5069 level 16 state 1 line 3 alter database statement failedhow would i get the database online and in multiuser mode,['sql'] +169340,client will not catch generic faultexception t only faultexception i have read all there is to read on this but maybe i am missing something well definitely i am missing something otherwise it would be working alreadyi am throwing some exception error inside my server business layerpublic class rfcexception exception public rfcexceptionstring m exception inner base m inner public dictionarystring string extendedproperties get return extendedproperties protected set extendedproperties value private dictionarystring string extendedproperties new dictionarystring stringwhich i leave unhandled in the service but i have an ierrorhandler to catch and create a faultmessagepublic class faulterrorhandler behaviorextensionelement ierrorhandler iservicebehavior public bool handleerrorexception error if loggerisloggingenabled return true var logentry new logentry eventid 100 severity traceeventtypeerror priority 1 title wcf failure message stringformaterror occurred 0 error logentrycategoriesaddmiddletier loggerwritelogentry return true public void providefaultexception error systemservicemodelchannelsmessageversion version ref systemservicemodelchannelsmessage fault if error is rfcexception rfcexception rfcexception error as rfcexception var servicefault new rfcservicefaultrfcexception var faultexception new faultexceptionrfcservicefaultservicefault new faultreasonstringformatsystem error occurred exception 0 error var faultmessage faultexceptioncreatemessagefault fault messagecreatemessageversion faultmessage schemawebservicestandard else var faultexception new faultexceptionexceptionerror new faultreasonstringformatsystem error occurred exception 0 error var faultmessage faultexceptioncreatemessagefault fault messagecreatemessageversion faultmessage schemawebservicestandard public void addbindingparametersservicedescription servicedescription systemservicemodelservicehostbase servicehostbase systemcollectionsobjectmodelcollectionserviceendpoint endpoints systemservicemodelchannelsbindingparametercollection bindingparameters public void applythispatchbehaviorservicedescription servicedescription systemservicemodelservicehostbase servicehostbase foreach channelthispatcher chanthisp in servicehostbasechannelthispatchers chanthisperrorhandlersaddthis public void validateservicedescription servicedescription systemservicemodelservicehostbase servicehostbase public override type behaviortype get return typeoffaulterrorhandler protected override object createbehavior return new faulterrorhandler no need to ask i already confirmed with the debugger its entering in the part if error is rfcexception part i have stepped through that code and it reach til the end without any troublethat errorhandler wraps a faultexceptionrfcservicefault message the rfcservicefault message is thisdatacontractname rfcservicefault namespace servicedatatransferrfcpublic class rfcservicefault public rfcservicefaultrfcexception rfcexception this exceptionrfcexception extendedproperties new dictionarystring stringrfcexceptionextendedproperties public rfcservicefault public rfcservicefaultexception regularexception faultmessage regularexceptionmessage stacktrace regularexceptionstacktrace public dictionarystring string extendedproperties get return extendedproperties protected set extendedproperties value datamember private dictionarystring string extendedproperties new dictionarystring string datamember public string faultmessage get set datamember public string stacktrace get set the service has all the annotations that should have a wcf service with a faultcontractservicecontractname myservice namespace schemawebservicestandard sessionmode sessionmodeallowedpublic interface imyservice operationcontractname getstuff faultcontracttypeofrfcservicefault namerfcservicefault namespaceservicedatatransferrfc lookupresult getstuffnow testing at the client a simple test like thistry var result myservicegetstuff assertistruestringisnulloremptyresultcatch faultexceptionrfcservicefault rfcex omg for the life of the puppies enter herecatch faultexception rr it always falls in herecatch exception ex i have read many many posts about this similar issuecannot handle faultexceptionthrowing generic faultexceptionc wcf catch fault exceptions of base typewcf wsdlfirst approach problems with generating fault typesbut nothing so far seems to help i have tried setting up wcf tracing in the webconfigsystemdiagnostics sources source namesystemservicemodel switchvalueinformation activitytracing listeners add namelog typesystemdiagnosticsxmlwritertracelistener initializedatactracessvclog listeners source sources systemdiagnosticsand i get a svclog file in there i open with wcf trace viewer but i only see a bunch of messages the yellow one show the exception but it only confirms what the client is already seeing a systemservicemodelfaultexception being received rather than the generic oneany ideas how to figure this outedit forgot to mention i enabled my error handler in config like thisbehaviorextensions add namefaulterrorhandlerbehavior typeservicefaulterrorhandlerservice version10 cultureneutral publickeytokennull behaviorextensionsservicebehaviors behavior nameservicebehavior servicethrottling maxconcurrentcalls200 maxconcurrentsessions200 maxconcurrentinstances200 servicemetadata httpgetenabledtrue servicedebug includeexceptiondetailinfaultstrue faulterrorhandlerbehavior behaviorservicebehaviors,['c#'] +169341,where is java home on osx yosemite 1010 mavericks 109 mountain lion 108 or osx lion 107 java is an optional package on the latest versions of osx yet once installed it appears like the java home environment variable is not set properly,['java'] +169347,webkittransition height for a div with a dynamic changing height based on content please see the following jsfiddleyou can click the various buttons which shows different length content which causes the box to growshrinki want the height change to be animated so it is not so jumpy i tried this by addingwebkittransition all 1s linearbut that has no effect in this use case any ideas in terms of a solution that does not require javascriptthanks,['css'] +169350,jquery append text i want to append some simple data in a div likemsgappendsome textin the body i think i will need to place the the html likediv idtest div idmsgdiv show text inside itdivhowever i want to add some css to the msg for example background color now the problem is that since the msg div is present all the time i see the background color even when the text is not appended to it i have tried to add css like thisplaynone but in that case i can not see the text appended to itcan i do it so that the msg div appears inside the test only when the text is appended to it thanks,"['jquery', 'html', 'css']" +169355,change colour of activated list item background on honeycomb for honeycomb i have set my listview items to use the androidattractivatedbackgroundindicator style so they remain highlighted when selectedhow do i change the colour of the highlight,['android'] +169356,prevent network sync loop when syncing from network in android contentprovider i am writing my own contentprovider which will be synced to a web service using a syncadapter problem happens when the sync adapter is modifying the content providers data the provider triggers a network sync when internally calling getcontentresolvernotifychange causing a sync loopthe notifychange with the network sync flag is required for when a client application does the modification but should be avoided when the sync adapter is modifyinghow can one inside a contentprovider easly tell if it is being used by a client application which should trigger network sync upon modification or by a sync adapter which should not trigger network synccurrently i am using different content uris sync adapter accesses the data using a content uri no sync and client apps using a content uri to be able to thistinguish between the two types of access and set the network sync flag accordingly,"['java', 'android']" +169359,how to make a dlna android mobile application i have a task to make a dlna android application as shown in the following videoi have to implement digital media controller and digital media server in my application but i dont know where should i start is there any open source api for thiswhat is the best way to achieve this goalthanks in advance and yes i am a bit lost in this issue p,['android'] +169403,fastest way to subset datatable vs mysql i am an r user and i frequently find that i need to write functions that require subsetting large datasets 10s of millions of rows when i apply such functions over a large number of observations it can get very time consuming if i am not careful about how i implement itto do this i have sometimes used the datatable package and this provides much faster speeds than subsetting using data frames recently i have started experimenting with packages like rmysql pushing some tables to mysql and using the package to run sql queries and return resultsi have found mixed performance improvements for smaller datasets millions it seems that loading up the data into a datatable and setting the right keys makes for faster subsetting for larger datasets 10s to 100s of millions it appears the sending out a query to mysql moves faster was wondering if anyone has any insight into which technique should return simple subsetting or aggregation queries faster and whether or not this should depend on the size of the data i understand that setting keys in datatable is somewhat analogous to creating an index but i do not have much more intuition beyond that,['mysql'] +169408,making sense of where const goes in a declaration i am having trouble finding an intuitive pattern for the way const is used in declarations in the c and c languages here are some examplesconst int a const integerint const a const integerconst int a pointer to constant integerint const a const pointer to an integerint const a const const pointer to a const integerin lines 1 and 2 it seems const can come before or after int which is what it modifiesso how in line 4 does the compiler decide that const is modifying pointer rather than intwhat is the rule that the compiler follows for deciding which thing the const applies todoes it follow the same rule for,"['c++', 'c']" +169414,how can i check that a window is fully visible on the users screen is there a way to check that a winform is fully visible on the screen eg is not out of bounds of the screeni have tried using systeminformationvirtualscreen for this which works great as long as the virtual screen is a rectangle but as soon as it is not eg 3 screens in a l shape systeminformationvirtualscreen returns the smallest rectangle containing all the visible pixels so a window on the upper right corner of the l would not be visible although it is in the virtual screenthe reason i am trying to achieve this is that i would like my program to open its child windows in the last location they were on but i do not want those window to be out of view if the user changes is setup eg unplugs the extra screen from his laptop,['c#'] +169427,checked vs unchecked exceptions in service layer i work on a project with a legacy service layer that returns null in many places if a requested record does not exist or cannot be accessed due to the caller not being authorized i am talking about specific records requested by id for instance something like userservicegetuseridi have recently pushed to have this api changed or supplemented with a new api that throws exceptions instead the debate over checked vs unchecked exceptions has ensuedtaking a note from the designers of jpahibernate et all i have suggested that unchecked exceptions may be most appropriate my argument being that users of the api cannot be reasonably expected to recover from these exceptions and in 99 of the cases we can at best notify the application user that some error has occurred having runtime exceptions propagate up to generic handling mechanisms will obviously reduce a lot of the complexity and required branch handling involved in dealing with edgecase exceptions but there is a lot of concern surrounding such an approach rightly so why have the designers of such projects as jpaejb and hibernate selected to go with an unchecked exception model is there a very good justification for it what are the proscons should developers using these frameworks still handle the runtime exceptions close to where they are thrown with something like adapter wrappersi hope answers to these questions can help us to make the right decision regarding our own service layer,['java'] +169428,is apples push notification service reliable i have an ios app using push notification but once in a while i am not getting a notification on my device when i expect to receive one i would receive all the subsequent notifications i confirmed with my backend to make sure that all the notifications were sent successfullyso my question is is apns nearly 100 reliable or should i just expect to miss some notifications here and there because of intermittent 3gwifi connectioni would think that apns works as a queueing system and retry if it was not successful within the first few times,['iphone'] +169440,why is throw null not creating a compilation error in java class thrownull public static void mainstring args throw null we know that rule for throw is throw throwableinstance where throwableinstance must be an object of type throwable or a subclass of throwablesimple types such as int or char as well as nonthrowable classes such as string and object cannot be used as exceptions null is a special java literal which represents a null valueso why would throw null compile in this code,['java'] +169446,encrypt and decrypt a password in java i want to encrypt and decrypt a password in java and store into database in the form of encryptedit will great if it is open source any suggestions pointers,['java'] +169460,why cannot i assign the wrong enum element but can compare against the wrong enum element with the following c definitionsenum enuma ea element 1enum enumb eb element 10the following code would not compile and that only makes senseenuma variablevariable eb element would not compilebut the following code does compileenuma variable ea elementif variable eb element will compilealthough it cannot make any sense different enums are compared and such code is likely erroneouswhy are these seemingly identical situations handled differently in c,['c++'] +169473,c optional fields in application settings is there a way to create some optional fields in application settings for example for one client we need some client based settings in the settings file something like thisxml version10configuration configsections usersettings setting nameclient 1 out folder serializeasstring valuecvalue setting setting namesome other setting serializeasstring valuetruevalue setting and for the other client we dont need the client 1 out folder at all so to keep the config file clean would be nice to remove it from the config file all together so for client 2 that part of config file would look likexml version10configuration configsections usersettings setting namesome other setting serializeasstring valuetruevalue setting,['c#'] +169476,simple rsa encryptiondecryption in net i would like to generate pair of keys and just type something like rsadecryptdata privatekey rsaencryptdata publickeyis there any easy way to do this i know there is something like rsacryptoserviceprovider but it needs xml to create proper object i would like to store privatepublic key as simple string not xml which i will put in webconfig inappsettings add keymypublickey value add keymyrivatekey valueappsettingsand later i will encrypt webconfig so everything will be safe iis will deal with it is it possible to do that in that way,"['c#', '.net']" +169477,what are some good ways of estimating approximate semantic similarity between sentences i have been looking at the nlp tag on so for the past couple of hours and am confident i did not miss anything but if i did please do point me to the question in the mean time though i will describe what i am trying to do a common notion that i observed on many posts is that semantic similarity is difficult for instance from this post the accepted solution suggests the followingfirst of all neither from the perspective of computational linguistics nor of theoretical linguistics is it clear what the term semantic similarity means exactly consider these examplespete and rob have found a dog near the stationpete and rob have never found a dog near the stationpete and rob both like programming a lotpatricia found a dog near the stationit was a dog who found pete and rob under the snowwhich of the sentences 24 are similar to 1 2 is the exact opposite of 1 still it is about pete and rob not finding a dogmy highlevel requirement is to utilize kmeans clustering and categorize the text based on semantic similarity so all i need to know is whether they are an approximate match for instance in the above example i am ok with classifying 1245 into one category and 3 into another of course 3 will be backed up with some more similar sentences something like find related articles but they do not have to be 100 related i am thinking i need to ultimately construct vector representations of each sentence sort of like its fingerprint but exactly what this vector should contain is still an open question for me is it ngrams or something from the wordnet or just the individual stemmed words or something else altogetherthis thread did a fantastic job of enumerating all related techniques but unfortunately stopped just when the post got to what i wanted any suggestions on what is the latest stateoftheart in this area,['python'] +169491,concurrent access to a utility static method we have a scenario in which several threads call a static method like the following onepublic static boolean isemptyfinal string s return s null slength 1could it cause a problem of inconsistence if 100 threads call it,['java'] +169499,creating a nonthread safe shared ptr i am working on a multthreaded program but have a ui component that makes extensive use of stdshared ptr to manage elements i can guarantee that only one thread will ever use these shared ptrsis there a way to define a shared ptr that does not incur the overhead of thread safe reference countingit could be based on boostshared ptr or stdshared ptredit thanks for answers mentioning intrusive ptr i neglected to mention that i also need weak ptr functionality so that rules it out,['c++'] +169506,reposition scroll bar of listview with padding i have a listview with padding to the right and leftcurrently the list looks something like this row row row row where the rightmost line is the edge of the screen with the s being the scrollbar and the white space to the right of it being the listviews padding to the rightwhat i is for the scroll bar to be to the right of the padding like this row row row row is it possible to move the scrollbar like that or will i have to change the layouts for each row to have an invisible border of the right sizenote currently each row has a separate background set by the adapter since i am making a floating window for my listview and unfortunately one of my screens require me to do this in order to get it to look the way i want,['android'] +169521,image comparison module for php is there any basic free or not but usable not like libpuzzle image fingerprintingsimilaritycompare module for php which works akin to tineye or google image upload search it is basically needed to avoid uploading almost the same but with watermarks resized etc image twice into a set of 50300 images,['php'] +169557,activity lifecycle receiving notification that layout is complete i have an activity in which i have 3 buttons placed alongside each other i have used a subclass of button that will resize the button text to prevent the text from wrapping i would like the 3 buttons to share the same text size in order to do this i intend to detect the button with the smallest text size and set the other 2 buttons to that text sizethe problem i have is knowing when the activity has completed laying out its components so that i can reliably know that the resizing of the text has occurred from the android documentation it would appear that the latest notification in the lifecycle is onresume but it appears that the layout has not completed at this point is there a way of receiving notification that the activity layout has finished,['android'] +169561,how to match begin or end of a line using cs regex i am trying to match this expressioncoma1ta20with this text qualquer linha iniciada por sera ignorada caracteres que nao podem serem usados na nomenclatura das copiadoras ou modelos coma1ta20ta20hdcomb1coma2ta20ta20hdcomb2coma3ta20ta20hdcomb3i can do that using notepad but i cannot with the c regex classcontent srreadtoendstring pattern coma1ta20ifregexismatchcontent patternsystemwindowsformsmessageboxshowtestwhat am i missing,"['c#', '.net']" +169571,sometimes persistent footer also moves during page transition in jquerymobile this is the html code i havedoctype htmlhtml langen head meta nameviewport contentwidthdevicewidth initialscale10 link relstylesheet href script srcscript script srcscript script home page2 page3livepagebeforeshowfunctionevent thisattrid linkaddclassuibtnactive script head body div datarolepage idhome div dataroleheader datathemeb h1testh1 div div datarolecontent datathemeb home page div div datarolefooter datapositionfixed dataidpfooter div datarolenavbar ul lia hrefhome dataiconcustom classuibtnactive idhome linkhomeali lia hrefpage2 dataicongridsecond pageali lia hrefpage3 dataiconstarthird pageali ul div div div div datarolepage idpage2 div dataroleheader datathemeb h1testh1 div div datarolecontent datathemeb second page div div datarolefooter datapositionfixed dataidpfooter div datarolenavbar ul lia hrefhome dataiconcustomhomeali lia hrefpage2 dataicongrid classuibtnactive idpage2 linksecond pageali lia hrefpage3 dataiconstarthird pageali ul div div div div datarolepage idpage3 div dataroleheader datathemeb h1testh1 div div datarolecontent datathemeb third page div div datarolefooter datapositionfixed dataidpfooter div datarolenavbar ul lia hrefhome dataiconcustomhomeali lia hrefpage2 dataicongridsecond pageali lia hrefpage3 dataiconstar classuibtnactive idpage3 linkthird pageali ul div div div bodyhtmlthe problem i am facing is that sometimes when i change selection of navbarthe footer also slides to the left or right along with the pageyou can reproduce the issue by constantly changing the selection of button in the navbaryou can see it here,['jquery'] +169588,how to make a super in javascript function like in this examplevar teste namemarcostesteeachfunction var name thisname i do not want to do that i want to have access to this inside this function sayname var sayname function alertname there is something like super in java or similar way to do saynamehow can i do that,"['javascript', 'jquery']" +169592,algorithm for incrementing a string in a nonobvious manner i want to create randomlooking 5 or 6 character alphanumeric strings something likevg78kycreating pseudorandom strings has been answered but i am wondering if there is an algorithm for incrementing a string in a nonobvious manner a simple increment of the above string might yieldvg78kzbut i do not want this next string to be guessable i want it to look completely different of course successive increments should not yield a previous result as each should be uniqueany thoughts on how to achieve this much appreciatedthanks,['java'] +169599,android apps reverse engineering is there any way to protect an android applications source code from reverse engineering as explain in this post,['android'] +169602,capture output of process synchronously ie when it happens i am trying to start a process and capture the output have come a far way but am not quite at the solution i would wantspecifically i am trying to reset the iis on my development machine from a small utility application that i am writing i have come to the conclusion by experimenting that the safe way to do this is by running iisresetexe in a child processif you run iisresetexe on a command prompt you get feedback during the process running iisreset takes several seconds and several lines of feedback is generated with pauses in between i would like to capture this feedback and present it in my windows forms application in a listbox and i have succeeded with that my remaining concern is that i dont get it until the child process finishes i would like to get the output from the child process line by line immediately when the lines are created i have tried to do my homework readingtesting things from eg thesehow to spawn a process and capture its stdout in netcapturing the console output in net cand several more with similar content most all get the output asynchronously eg with processreadtoend i want the output synchonously which acording to the msdn documentation involves establishing an event handler etc and i have tried that it works but the event handler does not get called until the process exits i get the output from iisresetexe but not until it has finishedto rule out the possibility that this has something to do with iisresetexe in particular i wrote a small console application that generates some output pausing in betweennamespace outputgenerator class program static void mainstring args systemconsolewritelineoutputgenerator starting and pausing for 10 seconds systemthreadingthreadsleep10 systemconsolewritelinepausing for another 10 seconds systemthreadingthreadsleep10 systemconsolewritelineexiting testing with this it turns out that i get captured data diretly when i want so to some extent it seems that the way iisresetexe outputs the data come into play herehere is the code of the program a windows forms application that does the captureusing systemusing systemwindowsformsusing systemdiagnostics namespace outputcapturer public partial class form1 form public form1 initializecomponent private void btnrun clickobject sender eventargs e running this will show all output after the process has exited string path cwindowssystem32iisresetexe running this will show all output when it happens string path coutputgeneratorexe var p new process pstartinfofilename path pstartinfouseshellexecute false shellexecute true not allowed when output is redirected pstartinforedirectstandardoutput true pstartinfocreatenowindow true poutputdatareceived outputdatareceived pstart pbeginoutputreadline private delegate void outputdatatotextboxdelegatestring s void outputdatatotextboxstring s tbxoutputtext s environmentnewline tbxoutputrefresh private void outputdatareceivedobject sender datareceivedeventargs e if edata null edatatostring must run the update of the textbox in the same thread that created it tbxoutputinvoke new outputdatatotextboxdelegateoutputdatatotextbox datetimenowtostring edatatostring thinking it was an eolencoding problem the output of iisresetexe apearing as one line to my app i ran a debug session nope the event handler for standardoutput gets called several times one time for each output line from iisresetexe buth these calls come in one burst after the process exitsi would love if i could get the output from iisresetexe when it happens so that i can show it as a progress indicationi have seen one other thread with the samesimilar problem asynchronous capture from a process output not working properly but wo a solutioni am sort of stumped,"['c#', '.net']" +169607,how to generate ddl for all tables in a database in mysql how to generate the ddl for all tables in a database of mysql at once i know that the following query will output the ddl for a table but i want ddl of all tables at once because i am having hundreds of tables in my databaseshow create table database nametable namefor exampleshow create table projectdbcustomer details the above query will result in ddl of customer details table i am using mysql with mysql workbench on windows os,['mysql'] +169608,dto generator for ef 4 entity model is it possible to write t4 template or if it already exists which will be able to generate dto classes based on the data in the edmx filei have to write dto classes for the current project and this process is kinda tiresomewhat i trying to acquire is to get dto classes which will have scalar properties defined as simple auto properties and navigation parameters as incapsulated instances of other dto classesexample public class someclassdto public byte id get set public string description get set public otherclassdto someproperty getset public ilistanotherclassdto objects getsetthis is a good starting point what is more desirable may look like following sample summary employee details dto summarypublic class employeedetailsdto key public long id get set required public string firstname get set required public string surname get set public long photoid get set home address properties public string homeaddressaddressline1 get set this is just name of field not flattened list public string homeaddressaddressline2 get set public string homeaddressaddressline3 get set public string homeaddresspostcode get set public short homeaddresscountryid get set public long homeaddresscountyid get set public long homeaddresstownid get set public short hometelephonecountryid get set public string hometelephonenumber get set public string hometelephoneextension get set public short personalmobilecountryid get set public string personalmobilenumber get set public string personalmobileextension get set as you can see this is a flatten dto which represent composite structure and may be injected back to entities through valueinjector samenameflatunflat injectionsthis is the ultimate goal though any advices would be appreciated,['c#'] +169664,screen orientation lock is there a reliable way to lock screen orientation on all android devices the code below works for my nexus s and other phones but for some reason rotation 90 corresponds to screen orientation reverse portrait on the xoom is there any way to reliably map rotation to orientationprivate void lockscreenorientation if mscreenorientationlocked final int orientation getresourcesgetconfigurationorientation final int rotation getwindowmanagergetdefaultthisplaygetorientation if rotation surfacerotation 0 rotation surfacerotation 90 if orientation configurationorientation portrait setrequestedorientationactivityinfoscreen orientation portrait else if orientation configurationorientation landscape setrequestedorientationactivityinfoscreen orientation landscape else if rotation surfacerotation 180 rotation surfacerotation 270 if orientation configurationorientation portrait setrequestedorientationactivityinfoscreen orientation reverse portrait else if orientation configurationorientation landscape setrequestedorientationactivityinfoscreen orientation reverse landscape mscreenorientationlocked true private void unlockscreenorientation setrequestedorientationactivityinfoscreen orientation sensor mscreenorientationlocked falseedit this code is meant to get the current orientation and lock it the orientation is locked temporarily and then released to the user,['android'] +169695,what is the difference between webkit is return and jquery return if in a webkit browser like chrome i dospani get a result that looks almost exactly the same as jquerysspanif in the console i look for definition of i getbound function return documentqueryselectorallapplydocument argumentsand for i getfunction abreturn new cfninitabwhat type of functions can i do on a object that i cannot really do with a jquery object,['javascript'] +169704,native html5 drag and drop in mobile safari ipad ipod iphone i have successfully implemented native html5 drag and drop for moving html elements inside a page just say a div from one place to another nothing related to interacting with the host os files whatsoever this works fine in chrome and safari on a pc but i cannot start a drag operation in my ipads safarii have found this so farusing drag and drop from javascriptsafari dashboard and webkitbased applications include support for customizing the behavior of drag and drop operations within your html pagesnote this technology is supported only on desktop versions of safari for iphone os use dom touch described in handling events part of safari web content guide and safari dom additions referencehere but it is outdated 20090608does anyone know if it is possible to use native html5 in mobile safari i do not want javascriptframework like solutions like jquery uithanks,['iphone'] +169730,c11 lambda as member variable can lambdas be defined as class membersfor example would it be possible to rewrite the code sample below using a lambda instead of a function objectstruct foo stdfunctionvoid barthe reason i wonder is because the following lambdas can be passed as argumentstemplatetypename lambdavoid call lambdalambda lambda what is the exact type here lambdaint test foo call lambda stdcout lambda calling stdendl i figured that if a lambda can be passed as a function argument then maybe they can also be stored as a member variableafter more tinkering i found that this works but it is kind of pointlessauto say hello stdcout hello struct foo typedef decltypesay hello bar bar bar foo barsay hello,['c++'] +169749,entity framework 4 with mysql connector 643 autogenerate tables causes column length exception i am working with mysql and the net entityframework 4 using the code first approach the mysql connector version is 643 when i run the project for the first time my initializer attempts to dropcreatedatabasealways the database is created as well as all the tables then the following exception is throwncolumn length too big for column modelhash max 21845 use blob or text insteaddescription an unhandled exception occurred during the execution of the current web request please review the stack trace for more information about the error and where it originated in the codeexception details mysqldatamysqlclientmysqlexception column length too big for column modelhash max 21845 use blob or text insteadsource errorline 38 public virtual list getaline 39 line 40 return dbsettolistline 41 line 42 source file cusersandrewdocumentsvisual studio 2010projectssearchcoreonlineiddalglobalgatewayrepositorycs line 40stack tracemysqlexception 0x804005 column length too big for column modelhash max 21845 use blob or text instead mysqldatamysqlclientmysqlstreamreadpacket 198 mysqldatamysqlclientnativedrivergetresultint32 affectedrow int32 insertedid 73 mysqldatamysqlclientdrivergetresultint32 statementid int32 affectedrows int32 insertedid 20 mysqldatamysqlclientdrivernextresultint32 statementid boolean force 100 mysqldatamysqlclientmysqldatareadernextresult 836 mysqldatamysqlclientmysqlcommandexecutereadercommandbehavior behavior 1399 mysqldatamysqlclientmysqlcommandexecutenonquery 36 mysqldatamysqlclientmysqlscriptexecute 551 mysqldatamysqlclientmysqlproviderservicesdbcreatedatabasedbconnection connection nullable1 commandtimeout storeitemcollection storeitemcollection 260 systemdataobjectsobjectcontextcreatedatabase 84 systemdataentityinternaldatabaseoperationscreateifnotexistsobjectcontext objectcontext 28 systemdataentitydatabasecreateifnotexists 53 systemdataentitydropcreatedatabasealways1initializedatabasetcontext context 233 systemdataentityc thisplayclass21setinitializerinternalb 0dbcontext c 75 systemdataentityinternalc thisplayclass5performdatabaseinitializationb 3 19 systemdataentityinternalinternalcontextperforminitializationactionaction action 72 systemdataentityinternalinternalcontextperformdatabaseinitialization 169 systemdataentityinternallazyinternalcontextinitializedatabaseb 4internalcontext c 7 systemdataentityinternalretryaction1performactiontinput input 118 systemdataentityinternallazyinternalcontextinitializedatabaseactionaction1 action 190 systemdataentityinternallazyinternalcontextinitializedatabase 73 systemdataentityinternalinternalcontextgetentitysetandbasetypefortypetype entitytype 27 systemdataentityinternallinqinternalset1initialize 62 systemdataentityinternallinqinternalset1getenumerator 15 systemdataentityinfrastructuredbquery1systemcollectionsgenericienumerablegetenumerator 40 systemcollectionsgenericlist1ctorienumerable1 collection 315 systemlinqenumerabletolistienumerable1 source 58 onlineiddalglobalgatewayrepository1getall in cusersandrewdocumentsvisual studio 2010projectssearchcoreonlineiddalglobalgatewayrepositorycs40 onlineidbalaccountservicegetaccounts in cusersandrewdocumentsvisual studio 2010projectssearchcoreonlineidbalaccountservicecs32 onlineidwebsitecontrollersaccountmanagementaccountmanagementcontrollerindex in cusersandrewdocumentsvisual studio 2010projectssearchcoreonlineidwebsitecontrollersaccountmanagementaccountmanagementcontrollercs29 lambda methodclosure controllerbase object 62 systemwebmvcactionmethodthispatcherexecutecontrollerbase controller object parameters 17 systemwebmvcreflectedactiondescriptorexecutecontrollercontext controllercontext idictionary2 parameters 208 systemwebmvccontrolleractioninvokerinvokeactionmethodcontrollercontext controllercontext actiondescriptor actiondescriptor idictionary2 parameters 27 systemwebmvcc thisplayclass15b 12 55 systemwebmvccontrolleractioninvokerinvokeactionmethodfilteriactionfilter filter actionexecutingcontext precontext func1 continuation 263 systemwebmvcc thisplayclass17invokeactionmethodwithfiltersb 14 19 systemwebmvccontrolleractioninvokerinvokeactionmethodwithfilterscontrollercontext controllercontext ilist1 filters actiondescriptor actiondescriptor idictionary2 parameters 191 systemwebmvccontrolleractioninvokerinvokeactioncontrollercontext controllercontext string actionname 343 systemwebmvccontrollerexecutecore 116 systemwebmvccontrollerbaseexecuterequestcontext requestcontext 97 systemwebmvccontrollerbasesystemwebmvcicontrollerexecuterequestcontext requestcontext 10 systemwebmvcc thisplayclassbbeginprocessrequestb 5 37 systemwebmvcasyncc thisplayclass1makevoiddelegateb 0 21 systemwebmvcasyncc thisplayclass81b 7iasyncresult 12 systemwebmvcasyncwrappedasyncresult1end 62 systemwebmvcc thisplayclasseb d 50 systemwebmvcsecurityutilb 0action f 7 systemwebmvcsecurityutilprocessinapplicationtrustaction action 22 systemwebmvcmvchandlerendprocessrequestiasyncresult asyncresult 60 systemwebmvcmvchandlersystemwebihttpasynchandlerendprocessrequestiasyncresult result 9 systemwebcallhandlerexecutionstepsystemwebhttpapplicationiexecutionstepexecute 8920029 systemwebhttpapplicationexecutestepiexecutionstep step boolean completedsynchronously 184i am not sure what this modelhash column is as it does not exist in my modelsthanksafriezei have identified the location of this modelhash column it is in the edmmetadata table that is used to track changes the error i am experiencing can be eliminated by adding the following modelbuilderconventionsremove is there a way to use edmmetadata with mysql then,['mysql'] +169768,find an element in a sorted matrix problemgiven a matrix in which each row and each column is sorted write a method to find an element in it it is a classic interview question here is my solutionboolean fint matrix int hs int he int ws int we if hs he ws we return false int m hs he 2 int and ws we 2 if matrixmn t return true else if matrixmn t find the ele in the same row right to mn fm m and 1 we find the ele in the same col upper to mn fm 1 he n n find the ele in the area where imjn fm 1 he and 1 we else if matrixmn t very similar to previous part the running time of the algorithm is logm logn i am looking for an algorithm that is more efficient or with concise codehaving more comments i come up with following code return target recurrence in the matrixint fint m int rs int re int cs int ce int t int r1 rs r2 re int c1 cs c2 ce int r0 c c1 while r1 r2 c1 c2 find the last element that t in column c r flastless r1 r2 c t if r 1 break else find the first ele in the row that is t c ffirstgreater r c1 c2 t if c 1 break else r2 r c1 c else else while fhere is the link to function f1 and f2 find the first element in an array that is greater than the targetvoid flastlessint s int e int t int l s h e while l h int mid lh2 if mid t high mid 1 else if high t low mid 1 else low mid void ffirstgreaterint s int e int t whilel h mid lh2 if mid t low mid1 else high mid,['java'] +169778,how do i call a java method named the same as a scala keyword possible duplicateusing java lib with scala reserved words i am experimenting with scala and a java library i am using has a with method on one of its objects but with is a keyword in scala how do i call this method from my scala code,['java'] +169797,c interface cannot contain operators can anyone please explain why c interfaces are not allowed to contain operatorsthanks,['c#'] +169798,differences between doing ajax using a page method a web service and a custom http handler i am looking to create json objects in the client and then transfer these objects back to the server for processing these are the following options i am consideringa page methoda web servicea custom http handleri am looking to use jquery to send the objects the plan is to convert the json object into c objects that in turn go into queries during the processing i will need access to the users session that is working in sql server session mode the pages where these calls will be running will be on https the return objects will also be json objects i will consider scalability security and performancei was wondering what would be the upsdowns of using each optionthanks for your suggestions,"['c#', 'asp.net']" +169799,write text to notepad with cwin32 i am messing around with win32 api and windows messaging trying to figure out how things work and i found this question very helpfuli would like to improve upon the solution provided there so that it appends the text instead of just replacing the text in notepad via wm settextmy question is how would i use wm gettextlenght followed by wm gettext to get the current text in the notepad window so i could then append new text to it before using wm settextdoes using wm xtext work on both 32 and 64bit machines if there is a lot of text in notepad would the proposed getset algorithm still work or would it hog a bunch of resources if so is there another way to append text to the notepad window without copying everything in it firstthanks for you helpupdatehere is the code i came up with based on david heffernans help and googleso cut and pasting as i am new to the win32api and copied many lines from different sources i would appreciate any and all feedbackdllimportuser32dll charset charsetauto extern static intptr findwindowexintptr hwndparent intptr hwndchildafter in string lpclassname in string lpwindowname dllimportuser32dll entrypoint sendmessage extern static int sendmessagegettextlengthintptr hwnd int msg intptr wparam intptr lparam dllimportuser32dll public static extern int sendmessageintptr hwnd int umsg int wparam string lparam dllimportuser32dll public static extern int sendmessageintptr hwnd int umsg int wparam int lparam const int wm gettextlength 0x0e const int em setsel 0x00b1 const int em replacesel 0x00c2 public void testappendtextstring text process notepads processgetprocessesbynamenotepad if notepadslength 0 return if notepads0 null intptr editbox findwindowexnotepads0mainwindowhandle new intptr0 edit null int length sendmessagegettextlengtheditbox wm gettextlength intptrzero intptrzero sendmessageeditbox em setsel length length sendmessageeditbox em replacesel 1 text,['c#'] +169818,how do i choose the last 2 items in a list with css nthchild is it possible if not is there a way to do it with jquery,['css'] +169824,uiwebview background color i am loading an html string into a uiwebview in order to be able to view rich text so far so good but i have one small problem in my nib file i set the background attribute to greenhowever when it is thisplayed the background is white then in the class file i added the followingmywebview setbackgroundcoloruicolor greencolor mywebview loadhtmlstringmystring baseurlnilhowever the background is still white i even tried reversing the order but still comes out white background there is more text than the size of the uiwebview i noticed that when i scroll down past the end of the text the background is then green how do i get the background for the text itself to be greencould you please advise me as to what i am doing wrongmuchly appreciated,['ios'] +169840,javascript by reference vs by value i am looking for some good comprehensive reading material on when javascript passes something by value and when by reference and when modifying a passed item affects the value outside a function and when not i am also interested in when assigning to another variable is by reference vs by value and whether that follows any different rules than passing as a function parameteri have done a lot of searching and find lots of specific examples many of them here on so from which i can start to piece together pieces of the real rules but i have not yet found a single well written document that describes it allalso are there ways in the language to control whether something is passed by reference or by valuehere are some of the types of questions i want to understand these are just examples i am actually looking to understand the rules the language goes by not just the answers to specific examples but here are some examplesfunction fabc a 3 bpushfoo cfirst falsevar x 4var y eeny miny movar z first truefxyzwhen are the contents of x y and z changed outside the scope of f for all the different typesfunction f var a 1 2 3 var b a1 a1 4 what is the value of b now for all possible data types that the array in a might holdfunction f var a yellow blue red cyan green magenta var b a1 a1red tan what is the value of b now and why bred black did the value of a1red change when i assigned to bredif i want to make a fully independent copy of an object no references whatsoever whats the best practice way to do that,['javascript'] +169872,does java have the static order initialisation fiasco a recent question here had the following code well similar to this to implement a singleton without synchronisationpublic class singleton private singleton private static class singletonholder private static final singleton instance new singleton public static singleton getinstance return singletonholderinstance now i think understand what this is doing since the instance is static final it is built long before any threads will call getinstance so there is no real need for synchronisationsynchronisation would be needed only if two threads tried to call getinstance at the same time and that method did construction on first call rather than at static final timemy question is therefore basically why then would you ever prefer lazy construction of the singleton with something likepublic class singleton private singleton private static singleton instance null public static synchronized singleton getinstance if instance null instance new singleton return instance my only thoughts were that using the static final method may introduce sequencing issue as in the c static initialisation order fiascofirst off does java actually have this problem i know order within a class is fully specified but does it somehow guarantee consistent order between classes such as with a class loadersecondly if the order is consistent why would the lazy construction option ever be advantageous,['java'] +169874,c show dialog box at center of its parent it is been a mess to show a dialogbox at the center of its parent form here is a method to show a dialog i am positioning its parent to center but not able to center the dialogboxprivate void openformobject point object height object width formloading frm new formloading point temp pointpoint point location new pointtempx intintwidth 2 tempy intintheight 2 frmlocation location frmshowdialogprivate void btnview clickobject sender eventargs e try threadstart starter delegate openformcurrentscreenlocation thisheight thiswidth thread t new threadstarter tstart some functionality here tabort catch exception,['c#'] +169875,make ios blocks execute synchronously how can i make a block execute synchronously or make the function wait for the handler before the return statement so the data can be passed back from the blockidperformrequestidargs block nsdata data nil xyzclass requestaccesstoaccountswithtypeaccounttype withcompletionhandlerbool granted nserror error data nsdata datawithdataresponsedata return data,"['iphone', 'ios']" +169889,video callingconference api for iphone currently am doing project on family business in that i need some video calling sort of thingis there any api available for video conference or any open source is availablethanks in advance,['iphone'] +169890,empty array declaration strange compiler behavior i have found a strange looking piece of code in a project i have to maintain there is an empty array member of a class which does not lead to an compiler error i have tested some variations of such a code with msvc 100templateclass t struct a int i warning c4200 nonstandard extension used zerosized array in structuniontemplateclass t struct b static int i templateclass t int btistruct c int i warning c4200 nonstandard extension used zerosized array in structuniontemplateclass t struct d static int i templateclass t int dti4template int dinti 1 int main avoid a bvoid b c c dvoid d0 dint d1 ai0 0 warning c4739 reference to variable a exceeds its storage space bi0 0 warning c4789 destination of memory copy is too small ci0 0 warning c4739 reference to variable c exceeds its storage space int i error c2133 i unknown size d0i0 0 ok d0i1 0 ok return 0the error message at int i is absolutely sensible to me the code which is shown with class d is wellformed standard c but whats about the classes a b and c what kind of types are the member variables int i in this classes,['c++'] +169901,understanding buffer security check gs compiler option in msvc i was recently surprised to note that compiling with gs enable buffer security check in msvc 2010 seems to have a nonnegligible effect on runtime performance in some cases has anyone else had this experiencefor a large scientificstyle application a mesh generation library it seems that compiling with gs can lead to almost 10 improvements in runtime for several of the large benchmarks in my test suite large being 1 second worth of runtime gs is on by default at all levels of optimisation in msvc 2010i must admit that i would never paid too much attention to this option before and i am wanting a bit of clarification as to what it actually does the online documentation seems to talk extensively about string buffers but since i do not use string or char buffers anywhere i must be missing somethingthis paragraph from the online doc seems to indicate that the performance degradation i am seeing is a bit unusuala performance tradeoff for using security checks in an application must be made the visual c compiler team focused on making the performance degradation small in most cases the performance should not degrade more than 2 percent in fact experience has shown that most applications including highperformance server applications have not noticed any performance impactof course i can just turn it off and get faster code but i want to understand the implications before i do that,['c++'] +169905,what does angle brackets mean in java i am currently studying java and have recently been stumped by what does meanspublic class poolt public interface poolfactoryt public t createobjectthisfreeobjects new arraylisttmaxsizewhat does the t mean does it means that i can create an object of type t,['java'] +169925,postgresql virtual columnacolumn does not exist using postgresql 84 i am trying to put together the following queryselect field a field b field c as virtual field from entities where entitiesthing id 9 and virtual field 0 and boolean field t order by virtual field descunfortunately i keep getting the following errorpgerror error column virtual field does not existline 1 ies entitiesthing id 9 and virtual fiel the error message is quite obvious but i will be damned if i can figure out the correct syntax for what i am trying to do field a field b and field c are all real columns in my entities tablefor reference i am using rails 2311 to compose the query heres the anonymised code i am usingthingentitiesboolean scopefindall select field a field b field c as virtual field conditions virtual field value order virtual field descmy brain has failed meacan anyone help me figure it out,['ruby-on-rails'] +169930,how to put a dword in the registry with the highest bit set i have run into a strange problem when setting values of the dword type in the windows registry from my c application i keep getting errors when the highest bit is set apparently there seems to be some kind of conversion problem between signed and unsigned integersexample when i do something like thisregkeysetvaluevalue 0x70u registryvaluekinddwordit works fine but when i add the highest bit which since i am specifically dealing with unsigned integers should be just another value bit like thisregkeysetvaluevalue 0xf0u registryvaluekinddwordi get an exception the type of the value object did not match the specified registryvaluekind or the object could not be properly convertedbut should not it work dword is an unsigned 32bit integer data type and so is the 0xf0u literal c automatically assigns it the uint32 datatype so they should be a perfect match and setting the value manually in the registry editor to 0xf0 works fine too is this a bug in net or am i doing something wrong,['c#'] +169932,how to remove whitespace in a string i have a string say allentown pa how to remove the white space in between and pa using objective c,"['iphone', 'objective-c']" +169959,is it possible to dynamically register bundles in symfony2 i have a loader bundle loaderbundle that should register other bundles in the same directoryacmeloaderbundleacmetobeloadedbundle1acmetobeloadedbundle2i would like to avoid manually registering every new bundle in acme directory in appkernelregisterbundles preferably i would like something in loaderbundle to run on every single request and dynamically register tobeloadedbundle1 and tobeloadedbundle2 is it possible,['php'] +169969,java return the objectmodify the object coding guidelines if a method populatesmodifies an object would it be preferable to return the object or to keep the return type as void and the method would modify the object through its referencepublic obj populateobj oreturn opublic void populateobj oi know this is a trivial question but which one is the most preferred,['java'] +169976,returning an arraylist from a webservice in java i am having a problem returning an arraylist from my web service javai have written a test web service and client which consumes it all appears to work fine that is the client is calling the server and the server receives the operation requesthowever i have written a simple method that i want it to return an arraylisti have my interface definition as followswebservicesoapbindingstyle stylerpcpublic interface isqlserverconnectionws webmethod arraylist getsimplearraylisti have my server side implementation to return the arraylistwebserviceendpointinterfacewebservicesisqlserverconnectionwspublic class sqlconnectionwsserver implements isqlserverconnectionws override public arraylist getsimplearraylist arraylist al new arraylist aladd this aladd is aladd a aladd test return al and finally my client call to itarraylist results servergetsimplearraylistthe server populates the array list fine however back at the client side the arraylist is empty it has a size of 0if i examine the wsdl at my url for the executeselectsql it looks likemessage nameexecuteselectsqlresponse part namereturn typetnsarraylistmessageam i missing something obviousedithowever if i have a web method defines in the interface aswebmethodstring getastringand the server implementationoverridepublic string getastring return hello therethen this works fine hello there is received on the client,['java'] +169997,spring 3 how to handle multilanguage url with same content i want to fully internationalize my web page and have urls translated to different languages for exampleall aforementioned pages should be handled by same controller and show same content translated to desired language of course this i know how to do using message propertiesso my questions are how to achieve this functionality using requestmapping annotationcan i configure such aliases in properties or xml file and then inject them into controller ieproperties filealiaspagepagepaginacontrollerrequestmappingaliaspageor something like thisthanks for answers,['java'] +170010,c ternary operator stdcout how to write the following condition with a ternary operator using cint condition1 condition2 condition3int double result int or doublestdcout condition1 result1 error condition2 result2 error condition3 result3 error,['c++'] +170017,what is the difference between eachselector and selectoreach what is the difference between thiseachmytable inputnamedeleteitemcheckeddo somethingand thismytable inputnamedeleteitemcheckedeachfunction do something the html for the table cell that is being selected and acted upon looks like thistd width20pxinput typecheckbox classchkdeleteitem namedeleteitem value rowitemitemid tdi have gone over the jquery documentation but i still do not understand the difference is it me or is that documentation sometimes slightly nebulous in clarity of contentadded infoapparently my attempt a generic examples is confusing people along with the previously missing parenthesis in the first example the first example comes from a line in my code that removes the tbody for any rows with a checkbox that is checkedeachclassestable inputnamedeleteclassescheckedparentparentparentremovethe second example comes from a situation where i look through the classestable for any checked checkboxes and remove its matching item in a dropdownclassestable inputnamedeleteclassescheckedeachfunction classeslist optionvalue thisattrvalue removei understand that they do two different things but not to the point that i would be able to say i need to use each in this case and eachfunction in another caseare they interchangeable at all only in some cases never,['jquery'] +170021,web deployment project teamcity i am trying to build a web deployment project 2010 project for a solution i have installed the windows sdk and web deployment project 2010 rtw on the build server as well as copied over the missing target files for msbuildwhen attempting to build the project it spits out the following errorcprogram filesmsbuildmicrosoftwebdeploymentv100microsoftwebdeploymenttargets1589 9 error msb6004 the specified task executable location cprogram filesmsbuildmicrosoftwebdeploymentv100aspnet mergeexe is invalidunfortunately searching around google for results about this error do not reveal anything of much value any help to get teamcity successfully building the web deployment project would be appreciated,['asp.net'] +170027,how to run easy install using a particular python version i have 3 python versions i want to easy install orange using the second version how can i do thisunnecessary info21 in usrbinpython26 in libraryframeworkspythonframeworkversions26binpython31 in libraryframeworkspythonframeworkversions31binpythonanswerok found it here also if youre working with python version 24 or higher you can run python with m easy install to run that particular python versions easy install command,['python'] +170030,nfc card emulation android the nexus s device nxp pn544 nfc controller supports not only swp for uicc based se but also the s2c aka nfcwi for the external egmicro sd card se does anybody know how this can be enabled and what it means for the sd card that is not relevant for the google nexus s there is not sd card slot but the nfc version of the samsung galaxy s ii comes already with the sd card slot and here this will be a questioni have tried to search for that and even the s2c standard seems to be relatively old i think ecma 2006 i did not any related materialswhat it means supporting s2c the nxp544 has the builtin support but what about the phone should the device have some hardware support like eg antenna connectors in the slot and on the sd card to be connected directly to the rf interfacethanks a lotregardssten added laterplease visit following link on wstackoverflowcom as wellandroid and symbian nfc mobile development questions and answers faq,['android'] +170032,when i throw something where is it stored in memory i understand that when something is thrown the stack is unwound to the point where it is caught and the destructors of class instances on the stack in each function context are run which is why you should not throw an exception from a destructor you could end up throwing a second onebut i wonder where in memory the object that i have thrown is stored while this happensis it implementation dependent if so is there a particular method used by most popular compilers,['c++'] +170048,calling the original page load function from inline code i like to monkey patch a aspx website so that i can add stuff to the page load method within a compiled assemblymy first thought was to add a script tag containing a second page load method to the aspx file like soscript languagecs runatservervoid page loadobject sender systemeventargs e do some stuff in addition to the original page load methodscriptbut it looks like only the page load method from the inline code will be executed and not the one from the original codebehind file within the compiled assemblyis it possible to call the original method from within my inline code or is there any other way to add stuff that should run directly after the page load method was called from within inline code without modifying the existing assembly,"['.net', 'asp.net']" +170066,what is the best way to deal with the nsdateformatter locale feature it seems that nsdateformatter has a feature that bites you unexpectedly if you do a simple fixed format operation such asnsdateformatter fmt nsdateformatter alloc initfmt setdateformatymmddhhmmssnsstring datestr fmt stringfromdatesomedatefmt releasethen it works fine in the us and most locales until someone with their phone set to a 24hour region sets the 1224 hour switch in settings to 12 then the above starts tacking am or pm onto the end of the resulting stringsee eg nsdateformatter am i doing something wrong or is this a bugand see indexhtmlapparently apple has declared this to be bad broken as designed and they are not going to fix itthe circumvention is apparently to set the locale of the date formatter for a specific region generally the us but this is a bit messynslocale loc nslocale alloc initwithlocaleidentifieren usdf setlocale locloc releasenot too bad in onsiestwosies but i am dealing with about ten different apps and the first one i look at has 43 instances of this scenarioso any clever ideas for a macrooverridden classwhatever to minimize the effort to change everything without making the code to obscure my first instinct is to override nsdateformatter with a version that would set the locale in the init method requires changing two lines the allocinit line and the added importaddedthis is what i have come up with so far seems to work in all scenariosimplementation bnsdateformatteridinit static nslocale en us posix nilnsdateformatter me super initif en us posix nil en us posix nslocale alloc initwithlocaleidentifieren us posixme setlocaleen us posixreturn meendbountyi will award the bounty to the best legitimate suggestioncritique i see by midday tuesday see below deadline extendedupdatere omzs proposal here is what i am finding here is the category version h fileimport foundationfoundationhinterface nsdateformatter locale idinitwithsafelocaleendcategory m fileimport nsdateformatterlocalehimplementation nsdateformatter locale idinitwithsafelocale static nslocale en us posix nilself super initif en us posix nil en us posix nslocale alloc initwithlocaleidentifieren us posixnslogcategorys locale en us posixdescription en us posix localeidentifierself setlocaleen us posixreturn self endthe codensdateformatter fmtnsstring datestringnsdate date1nsdate date2nsdate date3nsdate date4fmt nsdateformatter alloc initwithsafelocalefmt setdateformatymmdd hhmmssdatestring fmt stringfromdatensdate datenslogdatestring datestringdate1 fmt datefromstring20010505 123456nslogdate1 date1descriptiondate2 fmt datefromstring20010505 223456nslogdate2 date2descriptiondate3 fmt datefromstring20010505 123456pm nslogdate3 date3descriptiondate4 fmt datefromstring20010505 123456 pm nslogdate4 date4descriptionfmt releasefmt bnsdateformatter alloc initfmt setdateformatymmdd hhmmssdatestring fmt stringfromdatensdate datenslogdatestring datestringdate1 fmt datefromstring20010505 123456nslogdate1 date1descriptiondate2 fmt datefromstring20010505 223456nslogdate2 date2descriptiondate3 fmt datefromstring20010505 123456pm nslogdate3 date3descriptiondate4 fmt datefromstring20010505 123456 pm nslogdate4 date4descriptionfmt releasethe result20110711 1743243 demoapp160307 categorys locale nscflocale 0x11a820 en us posix20110711 1743257 demoapp160307 datestring 20110711 0543 pm20110711 1743264 demoapp160307 date1 null20110711 1743272 demoapp160307 date2 null20110711 1743280 demoapp160307 date3 null20110711 1743298 demoapp160307 date4 20010505 053456 pm 020110711 1743311 demoapp160307 extended clas locale nscflocale 0x11a820 en us posix20110711 17436 demoapp160307 datestring 20110711 174320110711 1743352 demoapp160307 date1 20010505 053456 pm 020110711 1743369 demoapp160307 date2 20010506 033456 am 020110711 1743380 demoapp160307 date3 null20110711 1743392 demoapp160307 date4 nullthe phone make that an ipod touch is set to great britain with the 1224 switch set to 12 there is a clear difference in the two results and i judge the category version to be wrong note that the log in the category version is getting executed and stops placed in the code are hit so it is not simply a case of the code somehow not getting usedbounty updatesince i have not gotten any applicable replies yet i will extend the bounty deadline for another day or twobounty ends in 21 hours it will go to whoever makes the most effort to help even if the answer is not really useful in my casea curious observationmodified the category implementation slightlyimport nsdateformatterlocalehimplementation nsdateformatter locale idinitwithsafelocale static nslocale en us posix2 nilself super initif en us posix2 nil en us posix2 nslocale alloc initwithlocaleidentifieren us posixnslogcategorys locale en us posix2description en us posix2 localeidentifierself setlocaleen us posix2nslogcategorys object and objects locale selfdescription selflocaledescription selflocale localeidentifierreturn self endbasically just changed the name of the static locale variable in case there was some conflict with the static declared in the subclass and added the extra nslog but look what that nslog prints20110715 163524322 demoapp214307 categorys locale nscflocale 0x160550 en us posix20110715 163524338 demoapp214307 categorys object nsdateformatter 0x160d90 and objects locale nscflocale 0x12be70 en gb20110715 163524345 demoapp214307 datestring 20110715 043524 pm20110715 163524370 demoapp214307 date1 null20110715 163524378 demoapp214307 date2 null20110715 163524390 demoapp214307 date3 null20110715 163524404 demoapp214307 date4 20010505 053456 pm 0as you can see the setlocale simply did not the locale of the formatter is still en gb it appears that there is something strange about an init method in a categoryfinal answersee the accepted answer below,"['ios', 'objective-c', 'iphone']" +170070,how do i correctly profile entity framework what is the minimal amount of code i can write to get a single callback from ef 41 that provides the following onsqlexecuteddbcommand cmd datetime start double durationms string stacktrace at the moment we use a nasty hack that seems to be leaking performance i am curious at how we can achieve this callback with a minimal amount of impact on the app we are able to wire this up in mini profiler by hacking around intially we changed databasedefaultconnectionfactory however mucking with the default factory means you can not have two profiling factories going at the same time so we went the more aggressive route the technique commonly used is pretty straight forward you implement dbproviderfactory idbconnectionfactory dbproviderservices dbconnection dbcommand and dbdatareader in such a way that they intercept the calls and profile so far easy however it gets messy when you try to wire this up try ensure all the factories are loaded dbproviderfactoriesgetfactory catch argumentexception type type typeofdbproviderfactories datatable table super ugly can this be done in another way object setortable typegetfield configtable bindingflagsnonpublic bindingflagsstatic typegetfield providertable bindingflagsnonpublic bindingflagsstaticgetvaluenull if setortable is dataset table datasetsetortabletablesdbproviderfactories table datatablesetortable foreach datarow row in tablerowscastdatarowtolist dbproviderfactory factory try factory dbproviderfactoriesgetfactoryrow catch exception continue var proftype typeofmvcminiprofilerdataefprofileddbproviderfactorymakegenerictypefactorygettype datarow profiled tablenewrow profiledname rowname profileddescription rowdescription profiledinvariantname rowinvariantname profiledassemblyqualifiedname proftypeassemblyqualifiedname tablerowsremoverow tablerowsaddprofiled it requires some reflection hacks and totally bombs on the latest version of ef fileloadexception the given assembly name or codebase was invalid exception from hresult 0x80131047this was documented by both frans and ayendehow do i wire up my profiling factories and family in a robust and elegant wayis there any other way to get my callback,"['c#', '.net']" +170088,gnu gcc g why does it generate multiple dtors developing environment gnu gcc g 412while i am trying to investigate how to increase code coverage particularly function coverage in unit testing i have found that some of class dtor seems to be generated multiple times does some of you have any idea on why pleasei tried and observed what i mentioned the above by using the following codein testhclass baseclasspublic baseclass void somemethodclass derivedclass public baseclasspublic virtual derivedclass virtual void somemethodin testcppinclude iostreaminclude testhbaseclassbaseclass stdcout baseclass dtor invoked stdendlvoid baseclasomemethod stdcout base class method stdendlderivedclassderivedclass stdcout derivedclass dtor invoked stdendlvoid derivedclasomemethod stdcout derived class method stdendlint main baseclass b ptr new baseclass b ptrsomemethod delete b ptrwhen i built the above code g testcpp o test and then see what kind of symbols have been generated as followsnm demangle testi could see the following output following is partial output 08048816 t derivedclasomemethod08048922 t derivedclassderivedclass080489aa t derivedclassderivedclass08048a32 t derivedclassderivedclass08048842 t baseclasomemethod0804886e t baseclassbaseclass080488f6 t baseclassbaseclassmy questions are as follows1 why multiple dtors have been generated baseclass 2 derivedclass 32 what are the difference among these dtors how those multiple dtors will be selectively usedi now have a feeling that in order to achieve 100 function coverage for c project we would need to understand this so that i can invoke all those dtors in my unit testsi would greately appreciate if someone could give me the reply on the above,['c++'] +170105,jdk on osx 107 lion i have instaled the java for developer package provided from apple for 107 and java apps are running finebut eclipse cannot find the jdk root path and i cant eitheranybody any ideas,['java'] +170110,how to partially apply member functions in javascript i currently have a partialapplication function which looks like thisfunctionprototypecurry function var args forvar i 0 i argumentslength i argspushargumentsi return function forvar i 0 i argumentslength i argspushargumentsi thisapplywindow args bindthisthe problem is that it only works for nonmember functions for instancefunction foox y alertx yvar bar foocurry1bar2 alerts 3how can i rephrase the curry function to be applied to member functions as infunction foo thisz 0 thisout functionx y alertx y thisz var bar new foobarz 3var foobar baroutcurry1foobar2 should alert 6,['javascript'] +170144,singletonehcacheregionfactory vs ehcacheregionfactory this link from the creator of ehcache says you should use singletonehcacheregionfactory when you only have one hibernate sessionfactory and ehcacheregionfactory when you have multiplebut wouldnt ehcacheregionfactory be a defacto singleton when you only have one sessionfactoryso whats better about singletonehcacheregionfactory why not use ehcacheregionfactory all the time since it can be used for one sessionfactory or multiplefyi i am using ehcache 242 and hibernate 365,['java'] +170153,whats wrong with my code notification no sound no vibrate i seem to have a problem with my codei have created a test activity just to see whats wrong still i cannotpublic class test extends activity called when the activity is first created overridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain string extra test notificationmanager mynotificationmanager notificationmanager getsystemservicenotification service intent intent new intentthis testclass notification notification new notificationrdrawableicon extra systemcurrenttimemillis pendingintent pendingintent pendingintentgetactivitythis 0 intent pendingintentflag update current notificationsetlatesteventinfogetapplicationcontext title text pendingintent notificationflags notificationdefault sound notificationflags notificationdefault lights notificationflags notificationdefault vibrate notificationflags notificationflag insistent notificationflags notificationflag auto cancel mynotificationmanagernotify33 notificationi get no sound andor vibrate when the notification popsi looked at the settings of my phone and they are ok no silent default sound enabled,['android'] +170156,python right click menu using pygtk so i am still fairly new to python and have been learning for a couple months but one thing i am trying to figure out is say you have a basic windowusrbinenv pythonimport sys osimport pygtk gtk gobjectclass app def init self window gtkwindowgtkwindow toplevel windowset titletestapp windowset default size320 240 windowconnectdestroy gtkmain quit windowshow allappgtkmaini wanna right click inside this window and have a menu pop up like alert copy exit whatever i feel like putting downhow would i accomplish that,['python'] +170184,how does jquerys delay method work underthehood i just saw this and think it is coolconsolelogstartingmy element fadein delay30 fadeoutconsolelogfinishinghow does the delay method work underthehood i mean how does it figure out how to wait 3 seconds but not interrupt the main control flow,"['javascript', 'jquery']" +170194,mysql where in array string username codefriendsarray arrayzac1987 peter micellelimmeizheng1152013142friendsarray2 join friendsarray query120 select picturemedium from users where username in friendsarray2echo query120this is the output select picturemedium from users where username in zac1987 peter micellelimmeizheng1152013142it fail because usernames are not wrapped by single quote like zac1987 peter mice how to wrap each username with single quote,"['php', 'mysql']" +170199,bouncycastle pgp and mcafee ebusiness server 86 incompatibility i have been banging my head against the wall now for a couple of weeks trying to figure out why our bank cannot decrypt a message that has been singlepass signed and encrypted using bouncycastle pgp the bank is using mcafee ebusiness server 86 for decryptionthe data is encrypted with the banks public key and is signed with our private keyusing our own public key for encryption i am successfully able to decrypt and verify the signature on a file generated with the code below gnupg can decrypt and verify the file just finehowever the bank is unable to decrypt the file i have tried first turning compression off and then turning ascii armoring off neither option seems to work and they always get the same error message no matter what options i tryevent 1 initialevent 13 beginlexevent 8 analyzefile is encrypted event 9 recipientssecret key is required to read itkey for user id x xevent 6 passphraseevent 23 decryptionsymmetric cipher used cast5event 3 error 11391event 2 finalerror decrypting file somepathfilenamecorrupt databad packetexitcode 32here is the code i am using to do the single pass sign and encryptpublic class pgpservice private static final logger log loggergetloggerpgpserviceclass static securityaddprovidernew bouncycastleprovider a simple routine that opens a key ring file and loads the first available key suitable for signature generation param input stream to read the secret key ring collection from return a secret key throws ioexception on a problem with using the input stream throws pgpexception if there is an issue parsing the input stream suppresswarningsrawtypes private static pgpsecretkey readsecretkeyinputstream input throws ioexception pgpexception pgpsecretkeyringcollection pgpsec new pgpsecretkeyringcollection pgputilgetdecoderstreaminput we just loop through the collection till we find a key suitable for encryption in the real world you would probably want to be a bit smarter about this iterator keyringiter pgpsecgetkeyrings while keyringiterhasnext pgpsecretkeyring keyring pgpsecretkeyringkeyringiternext iterator keyiter keyringgetsecretkeys while keyiterhasnext pgpsecretkey key pgpsecretkeykeyiternext if keyissigningkey return key throw new illegalargumentexceptioncannot find signing key in key ring single pass signs and encrypts the given file to the given output file using the provided keys param filenamein the name and location of the source input file param filenameout the name and location of the destination output file param privatekeyin the input stream for the private key file param privatekeypassword the password for the private key file param publicencryptionkey the public encryption key param armoredoutput whether or not to ascii armor the output suppresswarningsrawtypes public static void signandencryptstring filenamein string filenameout inputstream privatekeyin string privatekeypassword pgppublickey publicencryptionkey boolean armoredoutput boolean compress int buffersize 116 inputstream input null outputstream finalout null outputstream encout null outputstream compressedout null outputstream literalout null pgpencrypteddatagenerator encrypteddatagenerator null pgpcompresseddatagenerator compresseddatagenerator null pgpsignaturegenerator signaturegenerator null pgpliteraldatagenerator literaldatagenerator null try file output new filefilenameout outputstream out new fileoutputstreamoutput if armoredoutput out new armoredoutputstreamout use bcpgoutputstreams init encrypted data generator encrypteddatagenerator new pgpencrypteddatageneratorpgpencrypteddatageneratorcast5 true new securerandom bc encrypteddatageneratoraddmethodpublicencryptionkey finalout new bufferedoutputstreamout buffersize encout encrypteddatageneratoropenfinalout new bytebuffersize init compression if compress compresseddatagenerator new pgpcompresseddatageneratorpgpcompresseddatazlib compressedout new bufferedoutputstreamcompresseddatageneratoropenencout init signature pgpsecretkey pgpsec readsecretkeyprivatekeyin pgpprivatekey pgpprivkey pgpsecextractprivatekeyprivatekeypasswordtochararray bc signaturegenerator new pgpsignaturegeneratorpgpsecgetpublickeygetalgorithm pgputilsha1 bc signaturegeneratorinitsignpgpsignaturecanonical text document pgpprivkey iterator it pgpsecgetpublickeygetuserids if ithasnext pgpsignaturesubpacketgenerator spgen new pgpsignaturesubpacketgenerator spgensetsigneruseridfalse stringitnext signaturegeneratorsethashedsubpacketsspgengenerate pgponepasignature onepasignature signaturegeneratorgenerateonepassversionfalse if compress onepasignatureencodecompressedout else onepasignatureencodeencout create the literal data generator output stream which writes to the compression stream literaldatagenerator new pgpliteraldatageneratortrue if compress literalout literaldatageneratoropencompressedout pgpliteraldatabinary outputgetname new date new bytebuffersize else literalout literaldatageneratoropenencout pgpliteraldatatext filenamein new date new bytebuffersize update sign and encrypt byte buffer new bytebuffersize int bytesread 0 input new fileinputstreamfilenamein whilebytesread inputreadbuffer 1 literaloutwritebuffer0bytesread signaturegeneratorupdatebuffer0bytesread literaloutflush close literal data stream and add signature literaloutclose literaldatageneratorclose if compress signaturegeneratorgenerateencodecompressedout else signaturegeneratorgenerateencodeencout catch exception e logerrore throw new runtimeexceptione finally close all streams if literalout null try literaloutclose catch ioexception e if literaldatagenerator null try literaldatageneratorclose catch ioexception e if compressedout null try compressedoutclose catch ioexception e if compresseddatagenerator null try compresseddatageneratorclose catch ioexception e if encout null try encoutclose catch ioexception e if encrypteddatagenerator null try encrypteddatageneratorclose catch ioexception e if finalout null try finaloutclose catch ioexception e if input null try inputclose catch ioexception e suppresswarningsrawtypes private static pgppublickey readpublickeyfromcolinputstream in throws exception pgppublickeyring pkring null pgppublickeyringcollection pkcol new pgppublickeyringcollectionin loginfokey ring size pkcolsize iterator it pkcolgetkeyrings while ithasnext pkring pgppublickeyring itnext iterator pkit pkringgetpublickeys while pkithasnext pgppublickey key pgppublickey pkitnext loginfoencryption key keyisencryptionkey master key keyismasterkey if keyisencryptionkey find out a little about the keys in the public key ring loginfokey strength keygetbitstrength loginfoalgorithm keygetalgorithm loginfobit strength keygetbitstrength loginfoversion keygetversion return key return null private static pgpprivatekey findsecretkeyinputstream keyin long keyid char pass throws ioexception pgpexception nosuchproviderexception pgpsecretkeyringcollection pgpsec new pgpsecretkeyringcollectionpgputilgetdecoderstreamkeyin pgpsecretkey pgpseckey pgpsecgetsecretkeykeyid if pgpseckey null return null return pgpseckeyextractprivatekeypass bc any idea what could be causing this i have found numerous reports using google but no resolutions or followups,['java'] +170201,how to call parent constructor let us say i have the following code snippetfunction testid alertid testchildprototype new testfunction testchildvar instance new testchildhiis it possible to get alerthi i get undefined now,['javascript'] +170217,array push with associate array if i am working with an associate array like sucharray username user email email and i want to add an element to the end i would think to doarray pusharray arraypassword passhowever this leaves me witharray username user email email array password pass how can this be avoided so i end up witharray username user email email password pass much appreciated,['php'] +170226,how to make gdb print out all values in hexadecimal mode by default gdb always printsthisplays all variables arguments in base 10 is there any way to ask gdb to always use base 16 while printing anything and turn back to default settings when i do not need that i know that it can be printed by supplying the x argument to printthisplay but i do not want to do it everytime,['c'] +170235,why does gridview not render the header row as thead after postback setting tablesection tablerowsectiontableheader after the grid is bound works initially putting the header row in thead after a postback where the grid is not rebound the header row reverts to the table body i expect the header row to stay in thead can someone explain why this is not the case or what i am doing wrongsampleclick the button to cause a postback the header is not orange after the postback since it is not in thead anymoreaspx page languagec autoeventwireuptrue codebehindgridtestaspxcs inheritsfgridtest doctype html public w3cdtd xhtml 10 transitionalen html xmlnshead runatserver style typetextcss thead th backgroundcolororange styleheadbody form idform1 runatserver divaspbutton idbutton1 runatserver textbutton nbspthis button is here just to trigger a postbackdiv aspgridview idgv1 runatserveraspgridview formbodyhtmlcodeusing systemusing systemwebusing systemwebuiusing systemwebuiwebcontrolsnamespace f public partial class gridtest systemwebuipage protected void page loadobject sender eventargs e gv1databound new eventhandlergv1 databound if ispostback bindgrid void page prerenderobject sender eventargs e if gv1headerrow null systemdiagnosticsdebugwritelinegv1headerrowtablesection still tableheader after postback void gv1 databoundobject sender eventargs e if gv1headerrow null gv1headerrowtablesection tablerowsectiontableheader private void bindgrid gv1datasource thispagecontrols gv1databind,['asp.net'] +170238,how can i define the directory separator for both windows and linux platforms now i create a small php application here i have problem for using file path because in windows use this type location csomelocationindex but in linux wappindex so when i define the path using this but when the application run in window machine it should be problem for this so here i want to define the directory separator both windows and linux platform,['php'] +170247,cannot convert this pointer from const line to line explanation this methodbool pointintersectsconst line line const return linecontainspointthis falsecauses this error cannot convert this pointer from const line to line this changebool pointintersectsconst line line const return const castlinelinecontainspointthis falsefixes the error but does not seem the right way to fix the issue why is the original method considered an errorif it helps containspointconst point point bool isinfinite is nonconst and all methods it calls are nonconst as well,['c++'] +170256,visualvm not showing any methods called for cpu performance profiling i am running a java 16 21 sdk build app its been build in eclipse and i am using the vistualvm eclipse plugin to launch visualvm when the app startswhen i go to the profile tab and click cpu profiling it only shows the threads that are running but it does not show any method calls quite litterally none i have googled a whole bunch of things but nothing seems to fit has anyone seen this problem is there a solution environment windows xp 32bitclassic eclipse sdk 370visualvm from sdk 16 21it does not make any sense to me i can get memory heap information but zero membercalling informationany help is extremely appreciated,['java'] +170306,eclipse takes long time to save webxml well i am using eclipse to build a dynamic web projectin mac os x but there is something confused for me when i start eclipse and click the project explorer to expend the project folder it takes long time to finish it whats more when i change the webxml it takes for at least 5 seconds to save it i want to know why should i change something in the preferencepsi just found thatif i restart eclipse and do not click the project explorer it would be fine to modify and save the webxml but if i click to open the folders in the project explorer it will take a long time to say the changes in webxml now so whyps againwell i just meet with this problem again i am using ubuntu 1104 with 4gb ramthere are some other project similar but with lots of files but it does not happen when i edit their webxml i am confused again nowi just find out that it maybe be related to the xml validation with remote dtd if i close the net connection everything will be okdonei change xsischemalocations attr from 2 4xsd to 2 5xsd,['java'] +170307,how do one use acl to filter a list of domainobjects according to a certain users permissions eg edit when using the acl implementation in symfony2 in a web application we have come across a use case where the suggested way of using the acls checking a users permissions on a single domain object becomes unfeasible thus we wonder if there exists some part of the acl api we can use to solve our problem the use case is in a controller that prepares a list of domain objects to be presented in a template so that the user can choose which of her objects she wants to edit the user does not have permission to edit all of the objects in the database so the list must be filtered accordinglythis could among other solutions be done according to two strategies1 a query filter that appends a given query with the valid object ids from the present users acl for the objector objects iewhere other conditions and uid inlist of legal object ids here2 a postquery filter that removes the objects the user does not have the correct permissions for after the complete list has been retrieved from the database ieobjs query for objectsobjids getting all the permitted obj ids from the aclfor obj in objs if in arrayobjid objids result obj return resultthe first strategy is preferable as the database is doing all the filtering work and both require two database queries one for the acls and one for the actual query but that is probably unavoidableis there any implementation of one of these strategies or something achieving the desired results in symfony2,['php'] +170313,how to embed one layout inside another in my case if i have a layout called bottomxml bottomxmlsimply contain a textview and edit text view linearlayout xmlnsandroid androidlayout widthwrap content androidlayout heightwrap content androidlayout gravitycenter horizontal androidorientationvertical textview androidlayout widthwrap content androidlayout heightwrap content androidlayout gravitycenter horizontal androidgravitycenter horizontal androidtextstringusername edittext androidididname androidlayout width120dip androidlayout height50dip androidlayout gravitycenter horizontal linearlayoutis there any way to embed the above bottomxml layout inside other layouts instead of repeatly writing the same code in several layout files when other layouts have a part which contains the same layout as bottomxmlfor example if my adminxml layout also contain part of the layout which looks exactly the same as bottomxml how to just embed the bottomxml inside adminxml instead of writing the same code againadminxmllinearlayout xmlnsandroid androidlayout widthwrap content androidlayout heightwrap content how to embed bottomxml here linearlayoutif there is no way to do it in android what could be the workaroundupdatelike xevincent suggested i can reuse the bottomxml by use include tag but how to change the id of the elements inside the resued layout for example insdie bottomxml i would like to change the id of edittext androidididname to edittext androidididother name when i reuse the bottomxml layout in other layout how to change the id,['android'] +170323,how to return the index of child in layout i have the following situation horizontalscrollview hsv inside hsv linearlayout and inside it number of buttons the code is herehorizontalscrollview androidididfooter androidorientationhorizontal androidlayout widthfill parent androidlayout height0dp androidlayout weight15 androidbackgrounddrawablefooter bg androidscrollbarsnone androidfadingedgenone linearlayout androidididhsvlinearlayout androidorientationhorizontal androidlayout widthfill parent androidlayout heightfill parent button androidididtoday androidlayout widthwrap content androidlayout heightwrap content androiddrawabletopdrawabletoday androiddrawablepadding0sp androidgravitycenter horizontalbottom androidtextsize8sp androidtextstringtoday androidonclickgetrssnews button androidididlife androidlayout widthwrap content androidlayout heightwrap content androiddrawabletopdrawablelife androiddrawablepadding0sp androidgravitycenter horizontalbottom androidtextsize8sp androidtextstringlife androidonclickgetrssnews button androidididcorner androidlayout widthwrap content androidlayout heightwrap content androiddrawabletopdrawablecorner androiddrawablepadding0sp androidgravitycenter horizontalbottom androidtextsize8sp androidtextstringcorner androidonclickgetrssnews button androidididbanks androidlayout widthwrap content androidlayout heightwrap content androiddrawabletopdrawablebanks androiddrawablepadding0sp androidgravitycenter horizontalbottom androidtextsize8sp androidtextstringbanks androidonclickgetrssnews button androidididit androidlayout widthwrap content androidlayout heightwrap content androiddrawabletopdrawableit androiddrawablepadding0sp androidgravitycenter horizontalbottom androidtextsize8sp androidtextstringit androidonclickgetrssnews button androidididfun androidlayout widthwrap content androidlayout heightwrap content androiddrawabletopdrawablefun androiddrawablepadding0sp androidgravitycenter horizontalbottom androidtextsize8sp androidtextstringfun androidonclickgetrssnews linearlayout horizontalscrollviewis there a way to get the positionindex of the button on which has been clicked,['android'] +170342,ipython no readline available and pip install readline error i installed ipython but it does not have the readline option i first downloaded gnu readline and compiled and installed did not know whether it was a proper solution but was the first thing i thought of it still wouldnt work to no avail with the same error as beforewarning readline services not available on this platformwarning the autoindent feature requires the readline librarythen i tried using pip install readline and i get the error below any help would be appreciatedrunning installrunning buildrunning build extbuilding readline extensioncreating buildcreating buildtemplinuxx86 6426creating buildtemplinuxx86 6426modulescreating buildtemplinuxx86 6426modules2xgcc pthread fnostrictaliasing g o2 dndebug g fwrapv o3 wall wstrictprototypes fpic dhave rl callback dhave rl catch signal dhave rl completion append character dhave rl completion thisplay matches hook dhave rl completion matches dhave rl completion suppress append dhave rl pre input hook i ihomejspenderincludepython26 c modules2xreadlinec o buildtemplinuxx86 6426modules2xreadlineo wnostrictprototypescreating buildliblinuxx86 6426gcc pthread shared buildtemplinuxx86 6426modules2xreadlineo readlinelibreadlinea readlinelibhistorya lhomejspenderlib lncurses lpython26 o buildliblinuxx86 6426readlinesousrbinld cannot find lncursescollect2 ld returned 1 exit statuserror command gcc failed with exit status 1command homejspenderbinpython26 c import setuptools file homejspenderbuildreadlinesetuppyexeccompileopen file readreplacern n file exec install singleversionexternallymanaged record tmppiplbwiomrecordinstallrecordtxt failed with error code 1storing complete log in homejspenderpippiplog,['python'] +170370,input file onchange event not being fired in chrome this is a weird thing i noticed in chrome if the user select a file and then select the same file again bu opening the file dialog again chrome does not fire the onchange event while firefox doesanybody noticed it as well,['javascript'] +170379,iphoneipad save private application settings i am aware of nsuserdefaults for savingrestoring user preferences what is the equivalent class for an application for example a last run field or do not show this prompt again my intention is to keep the applications settings not user settings out of the settings application and not backup those settings in itunes time machine whateveri am getting a lot of noise for java and c but not much for iosiphoneipad,"['iphone', 'ios']" +170393,response is not available in this context i have problem locally everything works fine but in the production server it always throws exception response is not available in this context what can be the problem i have noticed that a lot of people experience this problem due to some changes of globalasax here is the code of globalasax the part related to application start protected void application start arearegistrationregisterallareas registerroutesroutetableroutes applicationsystemuser tusergetuserbyidentifiersystemuid initializesolrinstances searchindexerdoindex startratingtimer solrmanagerrecalculatemostrequested private static void initializesolrinstances solrconfigurationmanagerinitsolrconnectionofferitempresenterresourcesapplicationresourcessolrserviceurl offer solrconfigurationmanagerinitsolrconnectionsavedqueryitempresenterresourcesapplicationresourcessolrserviceurl savedquery solrconfigurationmanagerinitsolrconnectiontopproductspresenterresourcesapplicationresourcessolrserviceurl topproducts solrconfigurationmanagerinitsolrconnectiontopsellerspresenterresourcesapplicationresourcessolrserviceurl topsellers solrconfigurationmanagerinitsolrconnectionmostrequesteditempresenterresourcesapplicationresourcessolrserviceurl mostrequested solrconfigurationmanagerinitsolrconnectionmostrequestedqueryresourcesapplicationresourcessolrserviceurl requestedquery private void startratingtimer lastratingrenewedtime datetimenow datetime currenttime datetimenow datetime starttime new datetime2011 1 1 globalsettingsreindexmainsolrcoresstarttime currenttime timer offeranduserratingrenewertimer new timer timer interval for 24 hours interval 24 60 60 10 enabled true offeranduserratingrenewertimerelapsed new elapsedeventhandlerofferanduserratingrenewertimer elapsed public void offeranduserratingrenewertimer elapsedobject sender elapsedeventargs e globalsettingsreindexmainsolrcores lastratingrenewedtime esignaltime lastratingrenewedtime esignaltime i do not use response or request properties of httpcontext at all neither in global asax itself nor within the methods to be called help methat what it shows server error in applicationresponse is not available in this contextdescription an unhandled exception occurred during the execution of the current web request please review the stack trace for more information about the error and where it originated in the code exception details systemwebhttpexception response is not available in this contextsource error an unhandled exception was generated during the execution of the current web request information regarding the origin and location of the exception can be identified using the exception stack trace belowstack trace httpexception 0x804005 response is not available in this context systemwebutilhttpencoderget current 11406684 systemwebhttputilityurlencodestring str encoding e 137 solrnetimplsolrconnectiongetb 0keyvaluepair2 input 89 solrnetutilsselectd 1a2movenext 612 solrnetutilsfuncreduceienumerable1 source tresult startvalue accumulator2 accumulator 393 solrnetimplsolrconnectiongetstring relativeurl ienumerable1 parameters 908 solrnetimplsolrqueryexecuter1executeisolrquery q queryoptions options 195 solrnetimplsolrbasicserver1queryisolrquery query queryoptions options 176 solrnetimplsolrserver1queryisolrquery query queryoptions options 176 tebecomsearchenginesolrmanagerrecalculatemostrequested in solrmanagercs77 tebecommvcapplicationapplication start in globalasaxcs101httpexception 0x804005 response is not available in this context systemwebhttpapplicationfactoryensureappstartcalledforintegratedmodehttpcontext context httpapplication app 4043621 systemwebhttpapplicationregistereventsubscriptionswithiisintptr appcontext httpcontext context methodinfo handlers 191 systemwebhttpapplicationinitspecialhttpapplicationstate state methodinfo handlers intptr appcontext httpcontext context 352 systemwebhttpapplicationfactorygetspecialapplicationinstanceintptr appcontext httpcontext context 407 systemwebhostingpipelineruntimeinitializeapplicationintptr appcontext 375httpexception 0x804005 response is not available in this context systemwebhttpruntimefirstrequestinithttpcontext context 11612256 systemwebhttpruntimeensurefirstrequestinithttpcontext context 141 systemwebhttpruntimeprocessrequestnotificationprivateiis7workerrequest wr httpcontext context 4842149,"['c#', '.net']" +170403,unable to use lambda in initialization list of template in c i have a class with a stdfunction constructor parameter class clazzapublic clazzafunctionvoid foo clazza clazza if i have an instance of this class as a member of another i have to call constructor in initializer list i can pass a lambda as an argument and it is automatically convertedclass clazzbpublic clazza a clazzb works fine abut if clazzb is a template lambda does not worktemplatetypename t class clazzcpublic clazza a works fine clazzcfunctionvoid foo afoo does not work clazzc syntax error a syntax error unexpected tokens preceding skipping apparent function body the compiler is msvc 2010 i do not understand what i am doing wrong or why this syntax is not supportedat first clazza was a template too and function was a bit more complex so i thought it was the problem with templated lambda or something but after i removed all that code the problem remainsupd tried to compile in mingw g it works looks like a visual studio issue,['c++'] +170404,how to customize the width and height when show an activity as a dialog if i have defined a activitypublic class dialogactivity extends activity override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewdialog activityxml i would like to thisplay the above activity like a dialog so in the androidmanifestxml file i declare this activity like belowactivity androidnamedialogactivity androidthemeandroidstylethemedialogeverything is fine at this point my dialogactivity showed as a dialogthe problem is how to customize the width and height of the dialogactivity to make it more like a small dialog currently it occupies most of the screen by defaultupdatei defined a custom theme like belowstyle namemydialog parentandroidstylethemedialog item nameandroidwindowframenullitem item nameandroidwindownotitletrueitem item nameandroidwindowisfloatingtrueitem item nameandroidwindowcontentoverlaynullitem item nameandroidwidth100dipitem item nameandroidheight100dipitemstylethen declare the dialogactivity in androidmanifestxml asactivity androidnamedialogactivity androidthemestylemydialogmy dialogactivity now even occupies the whole screen the width and height definitionitem nameandroidwidth100dipitemin the theme do not take any effect why,['android'] +170407,logging spring bean creation dependency injection i am looking for a way to set up log4j or any other logger so that i can see in log whenever spring creates a bean or sets a bean property eg something like this10 creating bean foo fooef5c94101 creating bean bar bar147a87e102 setting bean foo fooef5c94 to bar bar147a87eis this easily possible i am using spring 256 no choice there and log4j version does not matter i expect,['java'] +170421,managing webconfig files i have 3 environments dev qa prod on net 4 each has a unique webconfig file we have been having problems managing all three versions its easy to overlook something critical when manually merging webconfig files in tfs more than once we have ended up with a connection string pointing to qa on prodso i read up on webconfig transformations these appear to require msbuild we have no build server so i am not sure how i can attempt to use this solution is there a way to make transformations work with a normal web publishdo you have any alternative suggestions for managing 3 webconfig files,['asp.net'] +170429,c library to populate object with random data i want to populate my object with random data for testing purposes is there a library to do itsome kind of reflection method that will traverse object graph and initialize primitive properties like string int datetime etc but do it the deep way including collections child objects etc,['c#'] +170444,website does not work with javascript turned off so head to wjabsycom with javascript turned offbasically i use some jquery ui dialogs i use javascript for all the bindings on the pagei pretty much use it for everything is that really a bad thing thoughnothing really works without javascript not even the google maps apishould i go out of my way to try and make the entire page work without javascript is that even possible with my site i wouldnt even know where to begin as i use javascript for everything so could i get some points how many users actually turn off their javascript these dayswould it help to let the user know if they have javascript turned off and make them turn it on before accessing it and provide them with directions how,"['javascript', 'html', 'css']" +170453,does java garbage collection log entry full gc system mean some class called systemgc what does full gc system entry in the garbage collection logs mean that some class called systemgc my garbage collection logs has two different entry types for full gc one with the word system the other without whats the differenceupdate i searched on this term and did not find a definitive answer only a few questions so i thought i would post itsystem164638058 full gc system psyounggen 22789k0k992448k psoldgen 1645508k16990k2097152k 1668298k16990k3089600k pspermgen 164914k164914k166720k 57499132 secs times user569 sys006 real575 secsnosystem1687013 full gc psyounggen 126501k0k922048k psoldgen 2063794k1598637k2097152k 2190295k1598637k3019200k pspermgen 165840k164249k166016k 68204928 secs times user680 sys002 real681 secsgc optionsour gcrelated java memory options arexloggcserverpelogjvm gclog xxprintgctimestamps xxprintgcdetailswe do not xxthisableexplicitgc so it is possible some errant class does call systemgc fwiw our full jvm optionsxms3072m xmx3072m xxheapdumponoutofmemoryerror xxusegcoverheadlimit xloggcserverpelogjvm gclog xxprintgctimestamps xxprintgcdetails xxmaxpermsize256m xxusecompressedoopsthanks in advancewill,['java'] +170454,multiple columns index when using the declarative orm extension of sqlalchemy according to the documentation and the comments in the sqlalchemycolumn class we should use the class sqlalchemyschemaindex to specify an index that contain multiple multiple indexhowever the example shows how to do it by directly using the table object like thismeta metadatamytable tablemytable meta an indexed column with index ix mytable col1 columncol1 integer indextrue a uniquely indexed column with index ix mytable col2 columncol2 integer indextrue uniquetrue columncol3 integer columncol4 integer columncol5 integer columncol6 integer place an index on col3 col4indexidx col34 mytableccol3 mytableccol4how should we do it if we use the declarative orm extensionclass abase tablename table a id columninteger primary keytrue a columnstring32 b columnstring32i would like an index on column a and b,['python'] +170487,using facebook javascript sdk to get graph data fixed now but i cannot answer my own question yet see my comment below and thanks for helping i have searched and searched and read the docs and still cannot figure this outi have a web page about an event there is also a public facebook event for my event i am trying to use the fb javascript sdk to get the number of attendees for the facebook event and add it to the number of people whove registered through the websitei have created an app and i have an appid and secret string i can get an access token from tokenclient idxclient secretxgrant typeclient credentialsand i can then use that access token to get the attendees for a public event tokenxthat is all finei am now trying to do this same thing using the javascript sdki have loaded the sdk and done an initfbinit appid x status true check login status cookie true enable cookies to allow the server to access the session xfbml true parse xfbmland i know the sdk is working because i can get an object with the data that does not need an access tokenfbapi 331218348435 function response consolelog response but when i try to get the attendee data that needs the access tokenfbapi 331218348435attending function response consolelog response i get an oauthexception an access token is required to request this resourceall the tutorials and information i can find all refers to using the login method but i do not want a user to login i want to login using my app id without any user interactioni would assumed that the api took the sdks init request and granted me an access token when i called the init method the authentication being done against my websites address the http referrer yes i have set my website url in the facebook app settingsany ideas what might be causing this to not work how can i get the access token using the javascript sdk without doing a login am i missing a step is this even possiblethanks,['javascript'] +170507,best approach to develop wpf application i would like to create a wpf application and would like some advice on the most appropriate approach i want to create an rss reader that automatically refreshes when a new rss entry is added the problem is that i do not want to use traditional controls listboxlistview to thisplay the data i would like the feed items to appear in panels randomly on the screen these panels consist of several textblocks each panel thisplays one feed item it would look something like this conceptthis raises several questions1 generate panels completely from code or use a custom controli would model a class like a panel as described above this class manually adds all controls to the form and drops the panel at a random location on the form when a new rss entry is added an instance of this class gets instantiated and passes the rss information as parameterson the other hand it might be better to create an usercontrol for this is it easy to create this usercontrol by code and pass it the parameters in the constructor 2 can my datapanel automatically update when a new rss entry has been added onlineright now i would refresh everything each x seconds and check against a collection of panels if there has to be created a new one if so create a new panel and drop it randomly on the formis there a better way of doing this i can use a local observablecollection with databinding that automatically updates a control listbox etc when the collection changes can this also be done with an online source like an rss feedthe most ideal way would be that my application gets notified when a new rss entry has been added downloads the last entry and creates a new panel trough code or trough a usercontrolif this is hard thing to accomplish i will use the traditional refresh method3 do i have to use dependencyobjectdependencypropertyi know dependencyobject dependencyproperty expose some powerful functionality for usercontrols but i do not really know how to use them are they necessary for this kind of application4 do i have to use wcf windows communication foundationi am not really experienced with advanced wpf stuff like advanced databindings dependencyobjects and usercontrols but i love to learn,['c#'] +170526,android logcat not showing logs when i switch devices i am trying to use logcat to help diagnose my android issues i frequently have a phone plugged in and an emulator running sometimes i debug on the emulator sometimes i debug on the phone or maybe even a third device logcat does not continue to show messages after a device is switched how can i specify what logcat does or force it to resume logging without restarting eclipseinsight appreciated,['android'] +170589,why cannot nested generic types be inferred given the following classespublic abstract class foobasetbar where tbar barbasepublic abstract class barbasepublic class bar1 barbasepublic class foo1 foobasebar1 and the following methodpublic tbar dosomethingtfoo tbartfoo thefoo where tfoo foobasetbar where tbar barbase return defaulttbarwhy cannot the following line of code imply the return typebar1 mybar dosomethingnew foo1instead i have to specify the generic types like thisbar1 mybar dosomethingfoo1 bar1new foo1,"['c#', '.net']" +170600,java a two dimensional array is stored in columnmajor or rowmajor order in java is a multidimensional array stored in columnmajor or rowmajor order,['java'] +170639,android pixel quality reduction in images loaded in webview i am building javascript application for mobile browsers not wrappedasnative appi noticed that android tested 23 emulator and galaxy s device reduces the quality of loaded images if the image dimensions exceed certain threshold width above 1400 px or so this make it impossible to load big bitmap images 20 x 20 px without the quality going unusablei tested this byloading one big image and drawing it on the i got pixel garbage out if i draw grid lines using lineto on they have perfect quality so the bad must be in the image pixel dataslicing the big image to 100 x 100 slices and drawing them to a canvas this is the only method i found resulting no quality reduction however slicing is cumbersome adds extra step to preprocess images and page loading times suffers i tested tring to load image with new image object tag and css background everything suffers from the reduced quality so i suspect the probelm is the image loader itselfi also tried everything with css imagerendering no luckviewport tag seems to have no effect to the image loading the data is already garbage when you try to touch the loaded pixel data i tried all possible values suggested in androids sdk documentation tested also firefox mobile desktop browsers ios everything is good thereso what is going on android webview simply cannot load big images smiley of hung android robot here,['android'] +170642,place a button right aligned i use this code to right align a button p alignright input typebutton valueclick me pbut p tags wastes some space so looking to do the same with span or div,"['html', 'css']" +170643,how to deploy phonegap app to ipadiphone i am totally new to making ipadiphone application i am totally new to using phonegap i downloaded a helloworld application and opened it up with xcode it works fine in simulator so i tried to deploy it to my ipad when i hit build and run in xcode i get this errorcode sign error the identity iphone developer does not match any valid certificateprivate key pair in the default keychaini have no idea what this means i applied for the apple developer program a few months ago i got back an email saying i successfully enrolled do i need to copy some kind of certificate from my apple account on the website to my ipad to enable xcode to deploy my helloworld program to the ipadi am totally confused on how to test the helloworld application on my ipadadditional notesok i followed some steps on how to sign a certificate and install it in xcode now when i try to build and run to a device i get this errorcode sign error provisioning profile forgelink specifies the application identifier forgelink which does not match the current setting r8t3vn6vr7forgelinkforgelinkdid i type something wrong when creating my certificates bundle identifiers app ids etc,['ios'] +170646,what is the difference between arrow operator and dot operator in objectivec in objectivec what is the difference between accessing a variable in a class by using arrow operator and dot operator is used to access directly vs dot is not direct,['objective-c'] +170684,calculate new coordinate x meters and y degree away from one coordinate i must be missing somthing out in the docs i thought this should be easyif i have one coordinate and want to get a new coordinate x meters away in some direction how do i do thisi am looking for something like cllocationcoordinate2d translatecoordinatecllocationcoordinate2dcoordinate translatemetersintmeters translatedegreesdoubledegreesthanks,"['iphone', 'objective-c']" +170699,are android apps backwards compatible i am doing a bit of iphone android development at the moment and i was curious if i were to build an application that targets android 22 and release it on the android marketplace would it be playable by users who are using older versions of the os such as 16 what would happen if such a user were to attempt to run the app would they be prompted to update their os or just receive an error messagethanks guys,['android'] +170703,thisableturn off inherited css3 transitions so i have the following css transitions attached to the a elementa webkittransitioncolor 01s easein backgroundcolor 01s easein moztransitioncolor 01s easein backgroundcolor 01s easein otransitioncolor 01s easein backgroundcolor 01s easein transitioncolor 01s easein backgroundcolor 01s easein is there a way to thisable these inherited transitions on specific a elementsatags transition none does not seem to be doing the job,['css'] +170709,is a virtual destructor needed for your interface if you always store it in a shared ptr since booststdshared ptr have the advantage of typeerasing their deleter you can do nice things likeinclude memorytypedef stdshared ptrvoid gc ptrint main gc ptr p1 new int42 gc ptr p2 new float314159 gc ptr p3 new charoand this will correctly delete all pointer thanks to the correct deleter being savedif you ensure that every implementation of your interface always gets created with shared ptrinterface or make sharedinterface do you actually need a virtual destructor i would declare it virtual anyways but i just want to know since shared ptr will always delete the type it was initialized with unless another custom deleter is given,['c++'] +170715,websocket problem cannot connect to nodejs server i have got a nodejs server up and running with express and i am trying to establish a websocket connection using socketio serverside and chrome 12 clientside when i try to connect socketio outputs a debug message saying destroying nonsocketio upgrade and the code in my connection handler does not run also on the clientside the readystate of my socket is 2 closingeditreadystate of the socket changed from 0 to 2,['javascript'] +170730,c client library for subscribingpublishing mqtt really small message broker i need to implement the push notification for android but there will not be internet access and only intranet access is availableso i think i cannot use c2dm and third party api like urbanairship so i am thinking of using mqtt rsmbreally small message broker c net as publisher to the broker and wmqttjar for android as subcriber to the brokeri have downloaded the rsmb and found the followings exebrokerexestdinpubexestdoutsubexei have successfully subscribed from android and published messages using stdinpubexe with topici would like to get some advice from you guys on the followings 1is rsmb free is there any other alternatives that suit my case2how will i be able to connect to the rsmb broker using c for publishing and subscribing are there any c client library for rsmb3how is the performance and reliability of the mqtt i might need to push a few hundreds of messages at the same time4if there is no other ways then i am thinking of executing the stdinpubexe inside my c applicationit might sound badi find that there is very little information about mqtt on the web and should i really go that way or are there any other alternatives,"['c#', '.net', 'android']" +170735,uisearchthisplaycontroller with uitableviewcontroller i have a uitableviewcontroller in which i added a uisearchbar as the tableheaderview using interface builder then i added a uisearchthisplaycontroller in the nib and set up all the connections delegate searchresultsdelegate searchcontentscontroller searchresultsdatasource all connected to the uitableviewcontroller i then implemented all the delegate and data source methods in my codeit works like a charm except for a weird bug sometimes the search results table view would not scroll and i can see the flash indicator of the main table view behind it i nslogd the searchresultstableview and apparently it is a subview of the main tableview and i guess that is the reason behind the touch problems i described earlier whats my mistake is it possible to use a uitableviewcontroller with uisearchthisplaycontroller at all if so how do i set up it in such a way that the results table view does not get added as a subview of my main table view update i found this sample which uses uisearchthisplaycontroller with uitableviewcontroller and apparently the search table view gets added to the main table view in there as well so now i do not think that is my problem the thing is that i cannot find any substantial difference between what i am doing and what that sample is doing i am just adding an uisearchbar as a uitableview header in a uitableviewcontroller and adding a uisearchthisplaycontroller to it it is like ios is confused between the main table and the search table when i try to scroll do you have any ideasupdate added a 200 rep bounty please answer only if you know what youre talking about,['iphone'] +170738,how do i put html in a jlabel in java how do i use html tags in a jlabel in java,"['java', 'html']" +170750,rails optional locale route i am trying to setup a routing system for my rails app that allows for an optional route locale to be allowed to the base of the websiteso more or lessenhome would goto the same page as homeenpeople peoplethe only issue i am having is setting this up in the routes config,['ruby-on-rails'] +170773,java why should equals method input parameter be object i am going through a book on data structures currently i am on graphs and the below code is for the vertex part of the graph class vertexe bunch of methods public boolean equalsobject o some code when i try to implement this equals method my compiler complains about not checking the type of the parameter and just allowing any object to be sent it it also does seem a bit strange to me why that parameter should not be a vertex instead of an object is there a reason why the author does this or is this some mistake or antiquated example,['java'] +170780,reentrantreadwritelock vs synchronized when should we use reentrantreadwritelock as compared to synchronized keyword in multithreaded environment in java what are the benefits of using reentrantreadwritelock over synchronized in javacan any one give an example as well in javathanks,['java'] +170783,convert seconds into minutes and seconds how can i convert seconds into minutes and secondsi am aware that you can convert seconds to minutes like so but i do not know how i can get the remainder of secondsint minutes seconds 60,['objective-c'] +170800,responsesendredirect from jspinclude being ignored i have got a jsp file which includes another jsp file to check some values and suchjspinclude pagesetupjsp inside the setupjsp i have got some conditional code which determines if some needed values are set in the session and if not redirects them to a different page or at least it is supposed to but the redirect seems to be getting ignored systemerrprintlnredirectingresponsesendredirectreturni see redirecting get logged to the console but the page continues on and renders normally i had curl dump the headers for me and saw that the response is http11 200 ok so it definitely is not sending a 302 redirectany idea what the problem is and how i can fix thisedit i have verified that my response is not yet committed responseiscommitted returns false meaning the status code and headers have not been sent yetedit 2 i have tried calling responsesendredirect in many other places and find that i can successfully redirect before the the redirect inside the jsp seems to be ignored and if i try to redirect right after the jsp then i get an illegal state exception because the response has already been committed,['java'] +170803,require multiple files i am building a php application that uses a select menu to build email templates the templates are broken into reusable parts each is a separate html file is there an easy way to require multiple files with one expression my php is really rustyessentially i want to do something likefunction require multi require oncefile1 require oncefile2 require oncefile3 require oncefile4,['php'] +170817,1052 column id in field list is ambiguous i have 2 tables tbl names and tbl section which has both the id field in them how do i go about selecting the id field because i always get this error1052 column id in field list is ambiguousheres my queryselect id name section from tbl names tbl section where tbl namesid tbl sectionidi could just select all the fields and avoid the error but that would be a waste in performance what should i do,"['mysql', 'sql']" +170818,how can i sort a list several different ways in a jsp i have a list of player objects getting passed into a jsp from a controller and i want to thisplay them in a couple of different ways on the same page a menu sorted by namea list sorted by winloss percentagei could put separate sorted copies in the model but dealing with different ways to thisplay the same list seems more like a responsibility of the view so i would like to avoid putting the logic in the controller if i can i already have a couple of classes implementing comparator to help with the actual sortingwhats the best way to do that in a jspcan i sort the list before passing it in to the different foreach tags,['java'] +170832,keyvalue store suggestion i need a very basic keyvalue store for java i started with a hashmap but it seems that hashmap is somewhat space inefficient i am storing 20 million records and seems to require 6gb ram the map is mapintegerstring and so i am considering using gnu trove tintobjecthashmapbyte and storing the map value as an ascii byte array rather than string as an alternative to that is there a keyvalue store that only requires adding jar files does not hold the entire map in ram at once and is still reasonably fast,['java'] +170848,how to thisable an anchor link tag convert to span i have a bunch of anchor tags a that i need to convert to span tags i do not need to do this to thisable clicking i know about preventdefault and returning false from the click event handler i just need to do this to enable drag and drop sorting which ie forbids on an anchor tag but permits on a spani have a working solution that is finei am just wondering if any of you wizards have a slicker way of achieving the same end result,"['javascript', 'jquery']" +170852,how do i get the unicodehex representation of a symbol out of the html using javascriptjquery say i have an element like thismath xmlns mo clasymbolimomathis there a way to get the unicodehex value of alpha i x03b1 using javascriptjquery something likesymboltextunicode i know unicode does not existsymboltexthex i know hex does not existi need x03b1 instead of i and it seems like anytime i insert x03b1 into the dom and try to retrieve it right away it gets rendered and i cannot get x03b1 back i just get i,"['javascript', 'jquery', 'html']" +170854,difference bw ab and ab in regex match i knew that denotes a set of allowable characters p rab researchp researchp a sresre match object at 0x1004823d8 researchp b sresre match object at 0x100482370 researchp ab researchp babut today i came across an expression with vertical bars within parenthesis to define mutually exclusive patterns q rab researchq researchq a sresre match object at 0x100498dc8 researchq b sresre match object at 0x100498e40 researchq ab researchq bathis seems to mimic the same functionality as above or am i missing somethingps in python parenthesis themselves are used to define logical groups of matched text if i use the second technique then how do i use parenthesis for both jobs,['python'] +170858,please help me to fix html div width in javascript ok i coded some html pages i integrated a jquery slider there slider name orbit slidermy site use fluid layout if you minimize the page vertically you can see the right corner images moving left side but i have some problem i want to move the right side slider navigation too when the user shrink the page verticallythe problem is i could not apply 100 width in the slider slider automatically create the width based on image size i do not know how to change it to 100 widthyou can check the slider in this page click here to see the pagethis is my javascript file javascript filethis is the place where the javascript uses widthvar b 0p 0h v u f dthisaddclassorbitc fwrapdiv classorbitwrapper parentfaddhwidth1pxheight1pxvar e fchildrenimg a diveeachfunction var a dthis b awidth a aheight b fwidth faddcwidthb h fwidth a fheight faddcheighta v fheight pyou can check it in the javascript file i want the width 100 please give me some idea thanks,"['javascript', 'html', 'css']" +170870,c clear session question 1i want to know when am i supposed to usesessionabandon when i use this during tracing and after calling it i find the session still has a valueand when am i supposed to use sessionclearwhen should i use each specific methodin generalin my specific casei check if session is not equal null in page load if session is equal to null i wanna to clear session and redirect to the login pageshould i use something like thisprivate void initsession sessionclear sessionabandon responseredirectloginpageaspx,"['c#', '.net', 'asp.net']" +170879,check multiple items in aspnet checkboxlist i try to check multiple values in aspnet checkboxlist but i could noti wrote chkapplicationsselectedvalue 2chkapplicationsselectedvalue 6but it just selects item with value 6whats wrong,"['c#', 'asp.net']" +170897,colorsxml resource does not work i created a colorsxml file in my android app under resvaluescolorsxml the contents arexml version10 encodingutf8resources color namegreen00ff00colorresourcesi try to update the background of my a tablerow using tablerow test tablerowfindviewbyidridtablerow2 testsetbackgroundcolorrcolorgreenthis does not set it as green it is gray instead no matter what values i add to the colorsxml file it is always the same gray color however this does work tablerow test tablerowfindviewbyidridtablerow2 testsetbackgroundcolorandroidgraphicscolorgreenis something wrong with my colorsxml,"['java', 'android']" +170936,visual studio tdd setup i am a c developer new to tdd willing to experiment with this development methodologymy current setup is visual studio 2010 resharper very convenient for running unit tests set up a unit test session and there are the run and debug tests buttonsstill i feel like there may be ways to accelerate tdd even more eg when saving a tests file automatically run the tests in itso tdd experts using visual studio can you share any tips about how to make the tdd process more productive,['c#'] +170964,c coming from java and objectivec so i know both java and objectivec quite well but perhaps strangely never really learned c obviously the languages are all related but there are syntactical differences that i do not fully understand is there a nice document that describes the basics of c but still assumes the learner knows a programming language perhaps even a tutorial that aims to describe the differences between the languages this is what i am looking foralso is there a good tutorial on how to use c code inside a mac or ios app the reason i feel the need to learn c is i am trying to port a c program and i heard you can use c code and just wrap it in an objc gui could someone point me to some documentationtutorials on how to do thisthanks,"['java', 'c++', 'objective-c']" +170996,java which of multiple resources on classpath jvm takes if i have multiple files of the same name on classpath eg i have multiple jar with log4jproperties what are the rules jvm follows to chose one,['java'] +171005,airplay mirroring mac to apple tv the new airplay mirroring feature for the ipad 2 in ios 5 is really nice but what if i wanted to use my apple tv as an easy external monitor for my mac i have already googled around and cannot find anything on the topic so i figured i would ask here to see if anyone has any suggestions on how i would go about it before anyone mentions something about jailbreaking the apple tv and using vnc i am not interested i would like a solution that i can use on any apple tvthe airplay work has basically been done for me if i use airplaykit by rothacr what i am concerned with is how i would go about mirroring whats on my macs thisplaythe ideal solution would be a kext of some kind that actually recognizes an apple tv as an external thisplay in system preferences so that i can use my apple tv to mirror my thisplay or if i choose use my apple tv as a second monitori understand that might not be possible so i could settle with an app that mirrors my thisplay but i am not sure of the best way to capture my desktop in a way that is compatible with the apple tv and is the least stressful on processor and network resources transmitting audio from my mac would be totally awesome too do icapture each frame as a still image and transmit each one to the appletvcapture each frame and encode it and transmit it as some sort of video streamam i going about this in the totally wrong directioncan someone give me some insight and get me pointed in the right directionthanks for your help,['objective-c'] +171024,integrating coffeescript with eclipse is there a way to integrate coffeescript and eclipse so that when i write coffeescript in one window the other will show the compiled code as javascripti will wait for answers thanks,['javascript'] +171047,how to copy uiimage data to clipboarduipasteboard and how do i test it i tried to use the following code to copy the image data to uipasteboard on click of the copy item in the menu uipasteboard gpboard uipasteboard generalpasteboardgpboard setdatauiimagejpegrepresentationimgviewimage 10 forpasteboardtypeuipasteboardtypelistimagewhich parameter i have to send for forpasteboardtype and how to test after copying the data,['ios'] +171063,how to import gwt source code into eclipse i am trying to contribute to gwt open source project i am in the very beginning step in importing the project into eclipse and learning how it worksthe gwt source code repository can be found here however there are only ant build files in the source code and there are not any project file there i believe we do not usually edit the source files in notepad and then compile using javac correct me if i am wrong hence i wonder how a normal open source contributor usually do to open the source code in hisher favorite ide,['java'] +171067,bad practice to have two classes of the same name in different packages we have split our application so that package a handles data from one external source and package b from another in both cases we need to create a domain object and have a transformer to do thisso i have comfoobarathingtransformer and comfoobarbthingtransformeri suspect that this is poor practice but want to see what the good people of so think,['java'] +171073,structuring a manytomany relationship between models for rails and backbonejs i am trying to set up an item model and a tag model that have a manytomany relationship items have multiple tags and tags belong to multiple items i am using rails and backbonejs so i need to have them store retrieve and update models seamlessly between each other i would also love it if i could save a new list of tags for a specific item in one go from the clientwhats the correct way to structure the models and controllers on the rails side and the models on the backbone side to keep the system restful and make it easy to share models between them specifically what would the api look like on the server and what would the json representation of the models be in saving and retrieving themi would really appreciate any advice on structure and i do not really need any code or implementation details just a high level setup would be great thanks,['ruby-on-rails'] +171084,adding a whereorder by clause to an iqueryable i have ths function to query a set of records from the dbpublic iqueryablepointtransactionviewmodel getpointtransactionsint userid return from pointtransaction p in entitiespointtransaction join activitylog a in entitiesactivitylog on ptransactionid equals atransactionid where puserid userid select new pointtransactionviewmodel id ptransactionid balance pbalance points pamount relatedactivityid aid when pwhen sender psenderuserinfocompletename i wish to add an additional cause like thisvar entries getpointtransaction1return entriesorderbydescendingwhere x xwhen start wwhen end x xwhenhowever i seem to need to create a new query from the existing one for this to work but i have seem this work before without creating a new query in the code snippet before public paginatedlistiqueryablet source int pageindex int pagesize pageindex pageindex pagesize pagesize totalcount sourcecount totalpages intmathceilingtotalcount doublepagesize thisaddrangesourceskippageindex pagesizetakepagesize does the code above somehow does not need a new query to be created for the iqueryable source object was a temporary object creatededitit is strange but to get it to work i have to do the followingiqueryableactivitylogentry log activityrepogetpointtransactionuserid wherex xpointsearned 50return logtolistthe following will not workvar log activityrepogetpointtransactionuseridlogwhere x xpointsearned 50return logtolistthere is no error message just that the where clause seems to be ignored it is also returning all data which pointsearned is not 50,['c#'] +171122,is not checked out bundle install does not fix help at master is not checked out please run bundle install bundlergiterrorso what do i do bundle install works on development but when i push and deploy to my production server i get this error even after running bundle install on my production server,"['ruby-on-rails', 'ruby']" +171135,mysql php return object value with space in key just come across something i have never came across before i have a value in my table device vendor and i am returning the data os an objectusually i would call obvar name but obviously obdevice vendor will not workhow do i return the valueregards,"['php', 'mysql']" +171159,getting three random dates from each hour the title does not actually fully describes the problem that is i have a table with dates 1 20110701 130148 2 20110701 130936 3 20110701 132124 4 20110701 133512 5 20110701 134923 6 20110701 135747 7 20110701 140512 8 20110701 141245 9 20110701 143148 10 20110701 144731and so on what i need is to get three random dates of each hour for example 1 20110701 130148 2 20110701 132124 3 20110701 134923 4 20110701 140512 5 20110701 141245 6 20110701 144731how can i do it in mysql,['mysql'] +171164,hexencoded string to byte array string str 9b7d2c34a366bf890c730641e6cecf6fi want to convert str into byte array but strgetbytes returns 32 bytes instead of 16,['java'] +171175,interfaceerror 0 i have built a site using django and i am receiving this annoying error when i am trying to execute a queryif i restart the apache server the error will go away for a short timetracebackfile usrlocallibpython27sitepackagesdjangocorehandlersbasepy in get response100 response callbackrequest callback args callback kwargsfile homefrancronviewsset cachespy in set caches24 cursorexecutequery categoryidfile usrlocallibpython27sitepackagesdjangodbbackendsutilpy in execute15 return selfcursorexecutesql paramsfile usrlocallibpython27sitepackagesdjangodbbackendsmysqlbasepy in execute86 return selfcursorexecutequery argsfile buildbthistlinuxi686eggmysqldbcursorspy in execute155 charset dbcharacter set nameexception type interfaceerror at blablablaexception value 0,"['python', 'mysql']" +171196,hostname is undefined in logbackslf4j in production environment i am using logbackslf4j to do logging and it works like a charm on my mac development machinei have the following pattern used for mail appender subjectsubjecterror hostname msgsubjectwhen running the service on my mac i receive a subject like thismacbookprolocalhost error messagewhen i run the service on a debian lenny vps i get the following email subjecthostname is undefiened error messagetyping hostname in command line for both mac and debian machine produces the followingmac macbookprolocalhostdebian s1myservicecomi would like to see the s1myservicecom in email subject,['java'] +171211,fastest way to find string by substring in sql i have huge table with 2 columns id and title id is bigint and i am free to choose type of title column varchar char text whatever column title contains random text strings like abcdefg q allyourbasebelongtous with maximum of 255 charsmy task is to get strings by given substring substrings also have random length and can be start middle or end of strings the most obvious way to perform itselect from t like abci do not care about insert i need only to do fast selects what can i do to perform search as fast as possiblei use ms sql server 2008 r2 full text search will be useless as far as i see,['sql'] +171212,custom iwordbreaker sample for sql server 2008 r2 in any language does anyone have a sample of a custom iwordbreaker for sql server 2008 r2 x64 i am looking for a sample to start building my own iwordbreaker but so far i have found nothing but the really old lrsample from msdn which i do not like it can be in any language i do not care but i prefer it to be in c c or delphi i bet this does not exist,"['c#', 'c++']" +171229,how can i get the canvas size of a custom view outside of the ondraw method i need to be able to access the size of the views canvas to perform some calculations for some reason the size of the view passed to onsizechanged is different than the size of the canvas passed to ondraw my current workaround uses a boolean flag to determine when i need to do the calculationsthe ideal solution would allow me to do these calculations in the onsizechanged method so i am wondering is there any way i can get ahold of the canvas object or at least it is dimensions outside of the ondraw methodmy code is below it is draws the radius of a circle at a given angle when i use canvascenterx to determine the start points and end points for the radius everything works perfectly if i use the parameters passed into onsizechanged it is not even remotely close to correctoverrideprotected void onsizechangedint w int h int oldw int oldh superonsizechangedw h oldw oldh msizechanged trueoverrideprotected void ondrawcanvas canvas superondrawcanvas if msizechanged rectf bounds new rectfcanvasgetclipbounds float centerx boundscenterx float centery boundscentery float radianangle float mathtoradiansmstartangle mradius0 center mradius1 center mradius2 center center floatmathcosradianangle mradius3 center center floatmathsinradianangle msizechanged false mpaintsetcolor0xff330 mpaintsetstrokewidth1 canvasdrawlinesmradius mpaint,['android'] +171234,yui compressor stringindexoutofboundsexception on jboss when minimising yui with 246 i get this problemjavalangstringindexoutofboundsexception string index out of range 232at javalangstringsubstringstringjava1934at comyahooplatformyuicompressorjavascriptcompressorprintsourcestringjavascriptcompressorjava267at comyahooplatformyuicompressorjavascriptcompressorparsejavascriptcompressorjava330at comyahooplatformyuicompressorjavascriptcompressorinitjavascriptcompressorjava533it works when started through my ide but when deployed to jboss it does not this place has some thiscussion of the same problemapparently the issue is around orgmozillajavascriptparser being in the two jars that are pulled in from my maven configdependencygroupidcomyahooplatformyuigroupidartifactidyuicompressorartifactidversion246versiondependencyis there any way i can solve this using maven exclusions etc or by upgrading my version of yui it seems daft that it just does not work and i do not want to have to write a custom classloaderplease help,"['java', 'javascript']" +171244,enforcefipspolicy flag in webconfig does not seem to working for web application i am trying to set up a web application to work in an environment where the fipsalgorithmpolicy is set to 1 in the windows registry specifically hklmsystemcurrentcontrolsetcontrollsa when this flag is enabled any call to the class md5cryptoserviceprovider will cause an invalid operation exception to be thrown with the following stack traceinvalidoperationexception this implementation is not part of the windows platform fips validated cryptographic algorithms systemsecuritycryptographyrijndaelmanagedctor 10480142 systemwebconfigurationmachinekeysectionconfigureencryptionobject 439 systemwebconfigurationmachinekeysectionensureconfig 152 systemwebconfigurationmachinekeysectiongetencodeddatabyte buf byte modifier int32 start int32 length 48 systemwebuiobjectstateformatterserializeobject stategraph 381 systemwebuiutilserializewithassertistateformatter formatter object stategraph 59 systemwebuihiddenfieldpagestatepersistersave 89 systemwebuipagesaveallstate 17 systemwebuipageprocessrequestmainboolean includestagesbeforeasyncpoint boolean includestagesafterasyncpoint 3864based on what i read in this article youre supposed to be able to add the following to your config file to thisable the algorithm checkconfiguration runtime enforcefipspolicy enabledfalse runtimeconfigurationthis works for me in a test console application by modifying its appconfig however it does not seem to work when a modify a net 20 web applications webconfigwhats interesting to me is that even though i am catching all exceptions when i go instantiate an md5cryptoserviceprovider in code it does not seem to even make it to that portion of my code this is the code that is called in my test app protected string printsomething string toprint stringempty try md5cryptoserviceprovider md5 new md5cryptoserviceprovider toprint created algorithm catch exception e toprint etostring return toprint and this is what i see when i visit the pageso this brings up a couple of questionswhy is iis throwing a ysod instead of allowing my app to catch the exceptionwhat do i need to do so that my web app is able to use enforcefipspolicy enabledfalse,"['c#', '.net', 'asp.net']" +171264,how are string constants in objectivec storedretrieved can someone explain where and how string constants are stored by the compiler and how they are accessed by the runtime,['objective-c'] +171270,why do we declare loggers static final in java why is it best practice to declare a logger static finalprivate static final logger s logger,['java'] +171323,why does not zd printf format work in vs2010 following piece of my code does not print the value in visual studioint main intptr t p 10 printftest value is zdp return 0outputtest value is zdi expect the the above code print test value is 10i am using intptr t instead of integer so as to make the code to adjust in both the 32 bit and 64 bit architecture,['c'] +171328,systemargumentexception complex databinding accepts as a data source either an ilist or an ilistsource i am using the c code below to populate a winforms listbox i want to hide all system folders however like the recyclingbin for example but it gives me the following error systemargumentexception complex databinding accepts as a data source either an ilist or an ilistsourcebeing new to linq this is more than confusing to me can anyone tell me where i am going wrongstring dirs directorygetdirectoriescvar dir from d in dirs where dstartswith select dlistboxdatasource dirtostring,['c#'] +171333,cc fastest cmath log operation i am trying to calculate logab and get a floating point back not an integer i was planning to do this as logbloga mathematically speaking i can use any of the cmath log functions base 2 e or 10 to do this calculation however i will be running this calculation a lot during my program so i was wondering if one of them is significantly faster than the others or better yet if there is a faster but still simple way to do this if it matters both a and b are integers,"['c++', 'c']" +171352,boost 1461 property tree how to iterate through ptree receiving sub ptrees first of all i shall say that i think i got how it should be done but my code will not compile any way i try i based my assumption on this official example of empty ptree trick there you can find next line const ptree settings ptget childsettings empty ptreeptreewhich shows that it is or should be possible to get subptree out from ptreeso i assumed we could iterate thru ptree with something like boost foreach in such mannerboost foreachconst boostproperty treeptree v configget childserveciesbut i get next errorerror 1 error c2440 initializing cannot convert from stdpair ty1 ty2 to const boostproperty treeptree or if i try boost foreachboostproperty treeptree v configget childservecies boostproperty trempty ptreeboostproperty treeptreei geterror 1 error c2039 empty ptree is not a member of boostproperty tree so what shall i do how to iterate thru boost ptree and get sub ptreesupdatei also tried such code boost foreachboostproperty treeptreevalue type v configget childpathtoarray of objects stdcout first data vfirstdata stdendl boostproperty treeptree subtree boostproperty treeptree vsecond boost foreachboostproperty treeptreevalue type vs subtree stdcout sub data vsfirstdata stdendl this compiles does not throw any exeptions but does not cout any sub data it just skeeps thru this cycle update 2hm something probably went wrong in my xml now i get correct results with that code,['c++'] +171356,android convert px to dp video aspect ratio possible duplicateconverting pixels to dp in android i am trying to convert pixels to dp what is the formulalets convert 640 and 480 into dp the docs say this the conversion of dp units to screen pixels is simple px dp dpi 160but i do not think that is what i need and i do not know how to use this i guess i just need the forumla i have the code readythisplaymetrics metrics new thisplaymetrics getwindowmanagergetdefaultthisplaygetmetricsmetrics switchmetricsdensitydpi case thisplaymetricsdensity low int sixforty int foureighty break case thisplaymetricsdensity medium int sixforty int foureighty break case thisplaymetricsdensity high int sixforty int foureighty break,['android'] +171369,what is the standard practice for starting a task with multiple parameters right now i have class myparamclass all the parameters i need to pass to the taskmyparamclass myparamobj new myparamclassmyparamobjfirstparam xyzmyparamobjsecondparam abcmytask new taskboolmymethod myparamobj canceltokenmytaskstartbool mymethodobject passedmyparamobj myparamclass myparamobj passedmyparamobj as myparamclass phew finally access to passed parametersis there anyway i can do this without having the need to create class myparamclass how can i pass multiple params to a task without this jugglery is this the standard practice thank you,['c#'] +171388,python getoutput equivalent in subprocess i want to get the output from some shell commands like ls or df in a python script i see that commandsgetoutputls is deprecated but subprocesscals will only get me the return codei will hope there is some simple solution,['python'] +171396,python convert an iterable to a stream if i have got an iterable containing strings is there a simple way to turn it into a stream i want to do something like thisdef make file yield hellon yield worldnoutput tarfiletarfileastream iterable to streammake fileoutputaddfilea stream,['python'] +171401,streamreader is unable to correctly read extended character set utf8 i am having an issue where i am unable to read a file that contains foreign characters the file i have been told is encoded in utf8 formathere is the core of my codeusing filestream filestream fileinfoopenread using streamreader reader new streamreaderfilestream systemtextencodingutf8 string line while stringisnulloremptyline readerreadline hashsetaddline the file contains the word acha cre but when examining it during debugging it is adding it as achi12cre this is a profanity file so i apologize if you speak french i for one have no idea what that means,['c#'] +171403,visual studio 2010 memory consumption i am having problems with my visual studio 2010 where its memory consumption increases quickly while the application is open i unistalled all plug ins and now just have the clean version but while i have the solution open the memory increases from 300k to 1gb to such a point if it hasnt crashed i need to kill the process the version of the vs is professional and it happens for different solutionsi feel it may down to the locking on vs2010 config files eating in to memory but thats a guessanyone have similar issues or how i might go about finding what the issues is,"['c#', 'asp.net']" +171409,get css inset boxshadow to appear on top of inner backgrounds i want a css inset boxshadow to appear on top of the elements inside of the container with the boxshadow specifically background colors of childelementsdemo div classparent foo div classcontentbardivdivstyleparent boxshadow inset 0 0 5px 0 blackcontent background estyleany ideas can do whatever with the html but need to be able to clickthrough so no 100 widthheight divs on top of everything,['css'] +171432,android how to convert int to string and place it in a edittext i have this piece of codeed edittext findviewbyid ridbox int x 10 edsettext xit turns out to be an error i know i have to change it to string but how do i do thisi have tried xtostring but it cannot be compiled,['android'] +171435,how to solve javaxnetsslsslhandshakeexception error i connected with vpn to setup the inventory api to get product list and it works fine once i get the result from the webservice and i bind to ui and also i integrated paypal with my application for make express checkout when i make a call for payment i am facing this error i use servlet for backend process can any one say how to fix this issuejavaxnetsslsslhandshakeexception sunsecurityvalidatorvalidatorexception pkix path building failed sunsecurityprovidercertpathsuncertpathbuilderexceptionunable to find valid certification path to requested target,['java'] +171465,difference between development and thistribution provisioning profile on provisioning portal i am going to activate apns on my app so i am having bit confusion over followingwhat is basic difference between development and thistribution provisioning profile on provisioning portali am going activate apnsapple push notification service to an application which i am going to upload on apple store what should i usethis will be great for me thanks in advance,"['iphone', 'ios']" +171472,how to make jquery ui tabs scroll horizontally if there are too many tabs now the image above is an example of too many tabs it appears as multiple line by default but i want to make it in a single line and horizontally scrollable either adding two arrows before the beginning tab and after the last tab or scroll automatically are ok,"['javascript', 'jquery', 'css']" +171479,efficiently sort an ilist without copying the source list given the test case below how can isort the ilisttestobject based on the index of a matching idin the ilistint listunmatched values are moved to the end of the list and sorted by their original index in this case since 3 and 4 do not exist in the index list we expect to see list3 3 and list4 4whilst i know this can be achieved with linq i need to resort the original list rather than creating a new one due to how the list is storedthe source list must be an ilist i cannot use listtheres the test public class testobject public int id get set test public void can reorder using index list ilisttestobject list new listtestobject new testobject id 1 new testobject id 2 new testobject id 3 new testobject id 4 new testobject id 5 ilistint indexlist new 10 5 1 9 2 todo sort assertthatlist0id isequalto5 assertthatlist1id isequalto1 assertthatlist2id isequalto2 assertthatlist3id isequalto3 assertthatlist4id isequalto4 updateas requested this is what i did try but 1 it only works with listt and 2 i am not sure it is the most efficient way var clone listtolist listsortx y var xindex indexlistindexofxid var yindex indexlistindexofyid if xindex 1 xindex listcount cloneindexofx if yindex 1 yindex listcount cloneindexofy return xindexcomparetoyindex update 2thanks to leppie jamiec mitch wheat this is the working code public class testobjectcomparer comparertestobject private readonly ilistint indexlist private readonly functestobject int currentindexfunc private readonly int listcount public testobjectcomparerilistint indexlist functestobject int currentindexfunc int listcount thisindexlist indexlist thiscurrentindexfunc currentindexfunc thislistcount listcount public override int comparetestobject x testobject y var xindex indexlistindexofxid var yindex indexlistindexofyid if xindex 1 xindex listcount currentindexfuncx if yindex 1 yindex listcount currentindexfuncy return xindexcomparetoyindex test public void can reorder using index list ilisttestobject list new listtestobject new testobject id 1 new testobject id 2 new testobject id 3 new testobject id 4 new testobject id 5 ilistint indexlist new 10 5 1 9 2 4 arraylistadapterilistlistsortnew testobjectcomparerindexlist x listindexofx listcount assertthatlist0id isequalto5 assertthatlist1id isequalto1 assertthatlist2id isequalto2 assertthatlist3id isequalto3 assertthatlist4id isequalto4,"['c#', '.net']" +171500,php multi dimensional array search i have an array where i want to search the uid and get the key of the multidimensional arrayexamplesassume we have the following 2dimensional arrayuserdbarray 0 array uid 100 name sandra shush url urlof100 1 array uid 5465 name stefanie mcmohn pic square urlof100 2 array uid 40489 name michael pic square urlof40489 the function call search by uid100 uid of first user should return 0the function call search by uid40489 should return 2i tried making loops but i want a faster executing code,['php'] +171531,nsnumber vs int if integers cannot be written to a dictionary and then to a plist but nsnumbers can is it better to use nsnumbers throughout the app rather than needing to convert everytime saving or loading a dictionary from a plist,"['iphone', 'objective-c', 'ios']" +171532,how to determine if a table relationship is bidirectional or unidirectional in doctrine 2 i am in the process of upgrading from doctrine 114 to doctrine 206 in my zend applicationcurrently i am working on mapping the associations between entities in doctrine 2s documentation it says relationships maybe bidirectional or unidirectional i am confused as to what these terms mean within the given contexthow do i determine if a relationship is unidirectional or bidirectionalappreciate the help,['php'] +171538,do you need to remove an event handler in the destructor i use some usercontrols which get created and destroyed within my application during runtime by creating and closing subwindows with these controls insideit is a wpf usercontrol and inherits from systemwindowscontrolsusercontrol there is no thispose method i could overrideppmm is a singleton with the same lifetime as my applicationnow in the constructor of my wpf usercontrol i add an event handlerpublic mycontrol initializecomponent hook up to an event ppmmfactorchanged new ppmmeventhandlerppmm factorchangedi got used to removing such event handler in the destructormycontrol hook off of the event ppmmfactorchanged new ppmmeventhandlerppmm factorchangedtoday i stumbled upon this and wondered1 is this neccessary or does the gc take care of it2 does this even work or would i have to store the newly created ppmmeventhandleri am looking forward to your answers,['c#'] +171592,lineheight affects images as you can see in the above example there is extra height of about 6px on the div that extra height is gone if lineheight is changed to 1px link so lineheight affects images too,"['html', 'css']" +171601,android market the only crash reports i get are on platforms other i have an app in the market with a few crash reports of javalangruntimeexception native typeface cannot be made this is covered elsewhere on so and i know where in my code it is that is not my problem the problem is finding out which android version and handset type is causing it i have never seen this on any handsets the app is tested on nor does any version of android on the emulators raise it the only crash errors i see are these and always on platforms other i am assuming if a different crash was reported i would get a better clue regarding the platform i would expect to see 8 11 etcit is a paid app it happens right on first run so the users are cancelling the purchasedoes anyone know what this platform is please,['android'] +171613,getters and setters for arrays i have a few questions about getters and setters for arrays suppose we have a class like this which makes a private copy of an array in its constructorimport javautilarrayspublic class foo private int array public fooint array thisarray arrayscopyofarray arraylength we want the array to only be accessedmutated via the getters and setters if we have a getter that looks like thispublic int getarray return arrayit defeats the purpose of the getter as were returning a reference that allows the user to directly modify the elements of the array egfoo foo new foosomearrayint bar foogetarraybar0 123 now fooarray0 123 and we have not used a setterso presumably we need something like thispublic int getelementint index return arrayindexsimilarly for setters but if were doing things on a perelement basis were also going to need to provide a means of getting the lengthpublic int getarraylength return arraylengththis is already a little messy for a 1dimensional array but say we have a multidimensional array insteadimport javautilarrayspublic class foo private int array public fooint array code for making a deep copy here public int getelementint i int j int k return arrayijk public void setelementint i int j int k int value arrayijk value public int getarraylength return arraylength public int getarraylengthint i return arrayilength public int getarraylengthint i int j return arrayijlength this is a lot of code for such a trivial task and more importantly it is a mess to actually use do we really have to end up with something like this or is there a better way to do it i have looked all over the place and there does not seem to be a standard practice for this,['java'] +171619,sending a raw data postrequest with an html form i need to send raw data in the body of a post request to a webservice can i accomplish this with a html form using a standard html input field seems to unavoidably generate a post body of the form name of input fielddata whereas i would simply like to post data do i need to resort to performing this request with javascript,['html'] +171631,how to change the extraparams config of a proxy at runtime in extjs i have the following storevar store new extdatastore model result proxy type ajax extraparams search term term url findpl how can i change the parameters with which the url is called ex search term at runtime,['javascript'] +171635,java web service client adding http headers having created a java web service client using wsimport on a wsdl i need to set the authorization header for each soap message embedded in an http request having generated a subclass of javaxxmlwsservice how can i append an http header to each outgoing request,['java'] +171655,store file in sql ce 4 using entity framework codefirst approach i am trying to add entity to sql ce 4 which have property of type byte from msdn i have figured out that only image type can hold big filesin my case they not so big but still over limit of binary type 80 byteshere is the modelpublic class tabmodel key public guid id get set public string title get set public string subtitle get set public string artist get set public string album get set public string author get set public string tabauthor get set public datetime dateadded get set columnfiletypenameimage public byte file get set public tabmodel id guidnewguid dateadded datetimenow i also have class that derived from dbcontext and when i use it something like this librarytabsaddtabtab of type tabmodel file is array with length equals 120librarysavechangesthrows exceptionerrorvalidation failed for one or more entities see entityvalidationerrors property for more details entityvalidationerrors0the field file must be a string or array type with a maximum length of 40i have tried to use maxlength attribute on property and error changes to binary clumn with length more 80 not supported it seems like ef maps column to binary type not image how to fix this,['c#'] +171681,tsql select and count from different table i have a table threads containing a field id i would like to select every row from threads as well as the number of rows in the table posts where the field poststhread is the same as threadsidhow can this be done in sqlsomething like this pseudosql select count from posts where postsidthreadsid from threads,"['asp.net', 'sql']" +171709,inverse htmlentities html entity decode basically i want to turn a string like thiscode ltdivgt blabla ltdivgt codeinto thisltcodegt div blabla div ltcodegthow can i do itthe use case bc some people were curiousa page like this with a list of allowed html tags and examples for example code is a allowed tag and this would be the samplecodeltphp echo hello world gtcodei wanted a reverse function because there are many such tags with samples that i store them all into a array which i iterate in one loop instead of handling each one individually,['php'] +171711,why is scaling writes to a relational database virtually impossible from cassandras presentation slides slide 2 link 1 alternate linkscaling writes to a relational database is virtually impossiblei cannot understand this statement because when i shard my database i am scaling writes is not it and they seem to claim against that does anyone know why is not sharding a database scaling writes,['mysql'] +171728,how do i determine the local hostas ipv4 addresses how do i get only internet protocol version 4 addresses from dnsgethostaddresses i have the code below and it gives me ipv4 and ipv6 addressesi have to make it work with boxes that have multiple ipv4 addressesipaddress localips dnsgethostaddressesdnsgethostnameprivate void get ips foreach ipaddress a in localips server ip server ip atostring,['c#'] +171746,programmatically created uibarbuttonitem not launching selector action here is my uibarbuttonselfnavigationitem setleftbarbuttonitemuibarbuttonitem alloc initwithtitle contact styleuibarbuttonitemstyleplain targetnil actionselectorshowpicker animatedyeshere is the code it is supposed to launch voidshowpickeridsender abpeoplepickernavigationcontroller picker abpeoplepickernavigationcontroller alloc init pickerpeoplepickerdelegate self self presentmodalviewcontrollerpicker animatedyes picker releasewhen i launch the app and click on the contact uibarbutton nothing happens no errors nada i put in a breakpoint and it never reaches the method referenced by the selector am i doing something wrong in the way i am calling the selectorthanks,"['objective-c', 'ios']" +171755,sql query that groups different items into buckets i am trying to write a query that returns the count of items whose price falls into certrain bucketsfor example if my table isitem name pricei1 2i2 12i3 4i4 16i5 6outputrange number of item0 10 310 20 2the way i am doing it so far is select countfrom my tablewhere price 0and price 10then select countfrom my tablewhere price 10and price 20and then copy pasting my results each time into excelis there an automatic way to do this in an sql query,['sql'] +171773,split string into different variables instead of array in python possible duplicatepython split string is possible to directly split string into variables in one line instead of using two lines i am sure that split would have two elementstwo lines examplemystring anonym anonymousa mystringsplitfirstnamelastname a0a1,['python'] +171780,mapping multiple tables to a single entity class in entity framework before this is marked as a duplicate i have checked the other related posts and they do not answer my question i am working on a legacy database that has 2 tables that have a 11 relationshipcurrently i have one type1test1result for each of these tables definedi would like to merge these particular tables into a single classthe current types look like this public class result public string id get set public string name get set public string text get set public string units get set public bool outofrange get set public string status get set public string minimum get set public string maximum get set public virtual instrument instrumentused get set public virtual test fortest get set public class test public int id get set public string status get set public string analysis get set public string componentlist get set public virtual sample forsample get set public virtual result testresult get set i would prefer them to look like this public class testresult public int id get set public string status get set public string analysis get set public string componentlist get set public string testname get set public string text get set public string units get set public bool outofrange get set public string status get set public string minimum get set public string maximum get set public virtual instrument instrumentused get set i am currently using the fluent api for mapping these to our legacy oracle database what would be the best method of combining these into a single class please note this is a legacy database changing the tables is not an option and creating views is not a viable solution at this point in the project,['c#'] +171797,what happens when pthreads wait in mutex lockcond wait i have a program that should get the maximum out of my cpuit is multithreaded via pthreads that do their job well apart from the fact that they only get my cores to about 60 load which is not enough in my opinioni am searching for the reason and am asking myself and hereby you if the blocking functions mutex lockcond wait are candidateswhat happens when a thread cannot run on in such a functiondoes pthread switch to another thread it handles ordoes the thread yield its time to the system and if the latter is the case can i change this behaviorregardsnobodymore informationthe setting is one mainthread that fills the taskpool and countless workers that fetch jobs from there and wait on a conditional that is signaled via broadcast when a serialized calculation is done they go on with the values from this calculation until they are done deliver their mail and fetch the next job,['c++'] +171809,direct3d 11 missing getrasterstatus how do i detect the vertical blank period i am updating an application in which measurement of the time of presentation of a stimulus on a screen requires the greatest amount of accuracy it is currently written with directdraw which got put out to pasture a long while ago and there is a need to update our graphics librarythe way which we measure the presentation time utilizes detecting the end of the vertical blank period specifically i need to know with the greatest possible accuracy when whatever was flipped onto the primary surface or presented in the swap chain is actually being drawn by the screen detecting the scan line can increase the certainty of that measurement but i would be able to work with only detecting when the vertical blank period ended immediately after the flip or present was calleddirect 3d 9 has the idirect3ddevice9getrasterstatus method that returns a d3draster status struct which includes a invblank boolean that describes if the device is in a vertical blank as well as the current scan line directdraw has similar functions idirectdrawgetverticalblankstatus also idirectdrawgetscanline which returns dderr verticalblankinprogress during vertical blank can be used to detect the vb however i have not been able to find any similar function in direct3d11 does anyone know if this functionality was moved or removed between direct3d9 and direct3d11 and if the latter why,['c++'] +171814,pvr texturetool build phase i am currently completing an iphone 3d programming bookthe book says to add following python code into a build phase in xcode to run the provided texturetool book quotea leave the shell as binsh b enter this directly into the script boxbinplatform diriphoneosplatformdeveloperusrbin infilesrcroottexturesgrid16png outfilesrcroottexturesgrid16pvr bintexturetool m f pvr e pvrtc infile o outfilec add this to input filessrcroottexturesgrid16pngadd this to output filessrcroottexturesgrid16pvrhowever when doing this i receive the following message failed to load imagefailed to perform encodecommand binsh failed with exit code 1could anyone shed a light on this,"['iphone', 'objective-c', 'ios']" +171818,android external app install on sd card reload alarmmanager alarms on remount through receiver i am developing an android app that i want to allow users to install on their sd card however the app has some alarms created through alarmmanager according to the android developers guide the link i have included if the external media sd card that the app is installed on is unmounted the following will happen your alarms registered with alarmmanager will be cancelled you must manually reregister any alarms when external storage is remountedis there some way i can wake my app up so that i can reschedule the alarms when the sd card is remounted maybe use a receiver with some intent filter i tried adding a receiver for androidintentactionmedia mounted but that did not work maybe because apps installed externally do not get that intent broadcast or because the app binaries are not available immediately after media is mounted and that intent is broadcasted any other intents someone can suggest or some other way to do this the androidintentactionexternal applications available intent external applications unavailable seems like what i would need but the docs say the apps on the external media will not get this intent,['android'] +171821,c loop optimizations with conditionals on looping variable apologies if this is asked in the archives i found some similar questions but none that seemed exactly what i wantedthe thistilled version of the problem i am working on is as follows i have a series of calculations to perform that will store values in 4 very large arrays abc and d these calculations are interdependent for example calculating bi could require using ai1 i am capable of expressing everything in a single loop but that results in edge cases where for certain values of i only some of the calculations should be performed for examplefori0iendi ifi 0 calculate ai1 and bi1 else if i end1 calculate ci1 and di1 else calculate ai1 bi1 ci1 di1for issues of performance i would like to avoid having conditionals within my loop evaluating a conditional would be cheap compared to the calculations but possibly not negligible my question is if a compiler might reliably expand that tocalculate a1 and b1fori1iend1i calculate ai1 bi1 ci1 di1calculate cend2 and dend2i gather from the archives that the compiler would break apart my loop if the conditional expressions were constant but here they depend on i which in principle could be changed by some of my calculations will it detect that i am not tampering with the iteration variable and thus break it apart in the sensible wayextra information in case you decide to answer the question by suggesting a better way to do thingsoriginally the code was written with 4 loops to calculate elements for each of the arrays this was the most intuitive way to write the code but it was inefficient since calculating elements in one array depended on elements in the other arrays this meant i had to read in all 4 arrays from memory during each of the 4 loops since these arrays do not fit in cache this is not optimal and i needed code that would loop through my arrays only oncei am also aware that i can break my loop apart by hand and indeed that is how things are currently done however these calculations involve nontrivial formulas and i cannot afford the performance hit of calling a function during every iteration of this loop so breaking apart the code caused code duplication that is not only very hard to read but almost unmaintainable the next time my formulas get tweaked which they willthanks in advance,['c'] +171825,easiest way to inject code to all methods and properties that do not have a custom attribute there are a a lot of questions and answers around aop in net here on stack overflow often mentioning postsharp and other thirdparty products so there seems to be quite a range of aop optons in the net and c world but each of those has their restrictions and after downloading the promising postsharp i found in their documentation that methods have to be virtual in order to be able to inject code edit see chriswues answer and my comment the virtual constraint must have been on one of the contenders i suppose i have not investigated the accuracy of this statement any further but it is categoricality made me return back to stack overflowso i would like to get an answer to this very specific questioni want to inject simple if somecondition consolewriteline style code to every method and property static sealed internal virtual nonvirtual does not matter in my project that does not have a custom annotation in order to dynamically test my software at runtime this injected code should not remain in the release build it is just meant for dynamic testing threadrelated during developmentwhats the easiest way to do this i stumbled upon monocecil which looks ideal except that you seem to have to write the code that you want to inject in il this is not a huge problem it is easy to use monocecil to get an il version of code written in c but nevertheless if there was something simpler ideally even built into net i am still on net 35 i would like to know update if the suggested tool is not part of the net framework it would be nice if it was opensource like monocecil or freely available,"['c#', '.net']" +171843,easeljs line fuzziness i am using easeljs as an api for html5 canvasi noticed that the following codelinegraphicssetstrokestyle1beginstrokeblackmoveto100100lineto200200stageaddchildlineproduces following linei set the thickness to 1 but the line is still fuzzy if you zoom in with the snapshot you can see it actually occupies 3 pixels i believe i read somewhere canvas draws a point between two pixels so that both pixels will be colored in fact and you need to shift where you draw the point by half the pixel width so it falls on the entire pixeli need sharp image for my applications please advise,['javascript'] +171857,developing android application in separate working modules i have seen applications with addon modules on market these modules addup some new functionalitywhat would be the best way to do that i cannot think of a descent and neat way to do that,['android'] +171869,nullable is not a valuetype if you look at the documentation for the net nullable youll see struct nullabletnote that it is a struct not a classit seems a struct nullablet is not a valuetype which is very unexpected the following code prints false type nullabletype typeofnullableint consolewritelinenullabletype is valuetypeif you look at the generated il youll see that that compiler determined nullabletype to be a valuetype at compile time but how can it be a valuetype if it is a struct all structs are valuetypes right obviously it has something to do with the genericwhat am i missing here is there something in the language spec about thisthanks,['c#'] +171877,how would you parse a url in ruby to get the main domain i want to be able to parse any url with ruby to get the main part of the domain without the w just the xcom,"['ruby-on-rails', 'ruby']" +171883,accessing desktop through android device is there any way of accessing editingdeleting files on the desktop through your android device is it possible through socket connection i dont like to go for internet connection remote access,['android'] +171890,objective c how to fix aspect ratio of image and not change to fit imageview frame i am using the uiimagepickercontroller to select images for my app however i am facing some challenges with regards to maintaining aspect ratio of the selected imagesfor examplei have a raw image on the phone as follows not square imageafter selecting the image on iphone via the move and scale page to crop image the result is as follows aspect ratio is still maintained heremy app will thisplay the selected image in a uiimageview with a square frame 200 x 200 after setting the selected image to the uiimageview uiimageviewimage selectedimage the images aspect ratio is not maintained but instead followed the frame of the uiimageview the image looks skewed now in my uiimageviewis there any way to maintain the aspect ratio of the image in this caseedit update expected resultafter some thinking i realize that the best way to resolve my issue is to ensure that for such images non square i need to convert them into square images ie fill the empty spaces on top and bottom of images to make a square egexpected image with the top and bottom borders addededit update with sample code voidimagepickercontrolleruiimagepickercontroller picker didfinishpickingimageuiimage img editinginfonsdictionary editinfo selfimageviewcontentmode uiviewcontentmodescaleaspectfill selfimageviewimage image picker parentviewcontroller thismissmodalviewcontrolleranimatedyes compress image uiimage image self scaleimageimg tosizecgsizemake61206120 selfimagedata uiimagejpegrepresentationimage 075by adding the code selfimageviewcontentmode uiviewcontentmodescaleaspectfill i was able to obtain the square image in the uiimageviewbut it seems like the original image was still not a square image hence the skewing problem will still occur when i do uiimage image self scaleimageimg tosizecgsizemake61206120 is my assumption correct anyway to mitigate this issue as i will still need to thisplay the compressed image elsewhere in the app,"['objective-c', 'ios']" +171905,is sqlite database instance thread safe i have a database with some tables i want to update the tables using multiple threadsi will use same instance of sqlitedatabase in all threadsplease suggest if this approach is correctis sqlite database threadsafecan two different threads update same table for different set of values at same time,['android'] +171939,first occurrence in a binary search i am tinkering with some code and i realized something i never knew a normal binary search will return a random index in a data set for a key that occurs more than once how can i modify this code below to return the first occurrence is this something people doripped from the jdkpublic static int binarysearchvalueinvertedcontainerinvertedindex a long key return bsearchvala 0 alength keyprivate static int bsearchvalinvertedcontainerinvertedindex a int fromindex int toindex long key int low fromindex int high toindex 1 while low high int mid low high 1 long midval amidval if midval key low mid 1 else if midval key high mid 1 else return mid key found return low key not found return insertion point,['java'] +171965,in entity framework how to call a method on entity before saving below i have created a demo entity to demonstrate what iam looking forpublic class user ivalidatableobject public string namegetset required public datetime creationdategetset public datetime updatedondategetset public ienumerablevalidationresult validatevalidationcontext validationcontext ifnameabc yield return new validationresultplease choose any other name then abc new name i am implementing ivalidatableobject interface to make this entity selfvalidatingnow currently to create new user iam doing this user u new user unamesome name ucreationdatedatetimenow dbcontextusersaddu dbcontextsavechangesiam planning to shift ucreationdatedatetimenow code inside user class and implement an interface that provides a method which will be executed before saving and after validating class structure that iam looking for public class user ivalidatableobjectimycustominterface rest codes as above class public void mymethodwhatever this method gets called after validate and before save ifdatacontextentryuserthisstate systemdataentitystateadded add creation date time thiscreationdatedatetimenow set more defaults ifdatacontextentryuserthisstate systemdataentitystatemodified update updation time thisupdatedondatedatetimenow now to create a new user i just have to do as belownote i didnt added date property this time class does that automatically user u new userunamesome namedbcontextusersaddudbcontextsavechangesto update user updatedondate property will be automatically updated by classuser u getuserfromsomewhereunameupdated namedatacontextentryuserustate systemdataentitystatemodifieddbcontextsavechangesmy question is there any existing interface that provides some method that gets called before save and after validate or some other ways of doing this that i may not be knowingor if i create my custom interface how can i make its method to get executed in the order i am looking for,['c#'] +171975,how to set http proxy in an applet for a java desktop application after we set these properties systemsetpropertyjavanetusesystemproxiestruesystemsetpropertyhttpproxyhost 1systemsetpropertyhttpproxyport 8080every http connection will be done through the defined proxybut for an applet these does not workin an applet viewer it does but in a browser it doesntapplet always uses these settings which are defined in control paneljavanetwork settingsproxy settingshow can i set the proxy in an appletusing proxy class in every opening connection is not a solution for meapplet is signed and compiled with java 16,['java'] +172004,aspectj annotations compiletime weave with ant and netbeans i want to use compiletime aspectj with ant in netbeans i want to run it on google app engine but it is not essential at the moment aspectj is annotation based i prefer compiletime weave modification instrumentation of classes i wouldnt like to use a custom classloader how to achieve thiswhat i already havei tried aspectj annotation tutorial with netbeans i modified buildxml to process aspectj using iajc ant task as described here the problem is that it requires adding javaagentlibaspectjweaverjar it is not possible on gae running my build generates this outputinfo compiling cnetbeansprojectstryaspectjsrcnetandrewewhiteexampleshelloworldjavaweaveinfo join point methodcallvoid javaioprintstreamprintlnjavalangstring in type netandrewewhiteexampleshelloworld helloworldjava9 advised by before advice from netandrewewhiteaspectsbasicaspect basicaspectclass17from basicaspectjavaweaveinfo join point methodcallvoid javaioprintstreamprintlnjavalangstring in type netandrewewhiteexampleshelloworld helloworldjava9 advised by after advice from netandrewewhiteaspectsbasicaspect basicaspectclass23from basicaspectjavainfo woven class netandrewewhiteexampleshelloworld from cnetbeansprojectstryaspectjsrcnetandrewewhiteexampleshelloworldjavainfo compiler took 2547mswhen i run my project with javaagent parameter it works ok in netbeans click on projectpropertiesrunvm options javaagentthistlibaspectjweaverjar otput for code from tutorialrunabout to make call to print hello worldhello worldjust made call to print hello worldbuild successful total time 0 secondswithout agent vm options cleared code runs as if it was without aspectjrunhello worldbuild successful total time 0 secondssourcestryaspectjsrcmetainfaopxmlxml version10 encodingutf8aspectj aspects aspect namenetandrewewhiteaspectsbasicaspect aspectsaspectjtryaspectjsrcnetandrewewhiteaspectsbasicaspectjava package netandrewewhiteaspectsimport orgaspectjlangannotationafterimport orgaspectjlangannotationaspectimport orgaspectjlangannotationbeforeaspectpublic class basicaspect before callvoid javaioprintstreamprintlnjavalangstring withinnetandrewewhiteaspects public void beforeprintlncall systemoutprintlnabout to make call to print hello world after callvoid javaioprintstreamprintlnjavalangstring withinnetandrewewhiteaspects public void afterprintlncall systemoutprintlnjust made call to print hello world tryaspectjsrcnetandrewewhiteexampleshelloworldjavapackage netandrewewhiteexamplespublic class helloworld public static void mainstring argv systemoutprintlnhello world tryaspectjbuildxmlxml version10 encodingutf8project nametryaspectj defaultdefault basedir descriptionbuilds tests and runs the project tryaspectjdescription import filenbprojectbuildimplxml taskdef classpathlibaspectjaspectjtoolsjar resourceorgaspectjtoolsanttaskdefsaspectjtaskdefsproperties target nameaspectj echo levelinfo aspectj start echo iajc destdirbuildclassesdir source16 target16 showweaveinfotrue verbosetrue inpath pathelement locationlibaspectjaspectjrtjar pathelement locationbuildclassesdir inpath sourceroots pathelement locationsrcdir sourceroots classpath pathelement locationjavacclasspath pathelement locationj2eeplatformclasspath classpath iajc a echo levelinfo aspectj finished echo targettarget namepostcompile dependsaspectjtargetprojectwhat do i have to add or change,['java'] +172009,showing that a date is greater than current date how would i show something in sql where the date is greater than the current date i want to pull out data that shows everything greater from today now for the next coming 90 days i was thinking fn now but that doesnt seem to work in my sql view here how can this be done,['sql'] +172014,work out minutes difference between dates i have the following codedatetime pickerdate converttodatetimepickerwakeupdateselecteddatestring enteredstr pickerdatetoshortdatestring textwakeuptimetextstring format ddmy hhmmdatetime entereddate datetimeparseexactenteredstr format nullthe problem i am facing is that i would like to workout the difference between the set date and the date and time now this value will then need to provide me a value of how many minutes there are between the datesi tried usingdatetime todaysdatetime datetimenowtimespan span entereddatesubtracttodaysdatetimeint totalmins spanminutesbut this gave me an incorrect value 0 when the value was set 10 minutes aheadcan anyone help me solve thisthanks,['c#'] +172018,including windowsh causes clashing with local variable name i am including windowsh in one of my h files in order to use capturestackbacktrace in a visualstudio project at first i got some compiler errors because of the use of minmax std methods and the macro with same name in windowsh but this seems to be solved by define nominmax as i read in other so posts i say seems because i cannot be sure till my whole project builds ok againthe problem is that some local variable names now break the build the lineint grp1inside a class method causes the following errorerror c2143 syntax error missing before constantwhile the cpp file compiles ok if i change the variable name to grp1 of course i can just change the variable name but nevertheless i have got a feeling that i am doing something wrong am i or is this a known issue when including windowsh is there any other more elegant solution other than changing the variable name,['c++'] +172023,converting a unix time stamp to twitterfacebook style i am trying to convert a unix time stamp to thisplay like facebook and twitter for example when you see tweets or comments placed on twitterfacebook you see the datetime thisplayed like so2 mins ago or 2 days ago or 2 weeks ago does anyone one know of any function to get it working like this i am guessing it will be a custom one any help is much appreciated,['php'] +172038,how to directly publish only child items of my container type in plone i have a custom folderish dexterity contenttype in plone it can have only documents as children i want these documents to be directly published as they are createdi can achieve this easily by setting an appropriate workflow for the document type but that would affect every document in my site i want only the ones inside my container type to be directly publishedtwo options come to my mindcustom pagecreate basically just a copy of the stock document type and set its workflow to something that has only published stateeventadd iobjectadded event for documents and check if the parent of the new document is my container type and do manual publishing in python codeneither sounds too nice do i have other options,['python'] +172048,amazon app store and android licensing lvl so i have a few little android apps now and am thinking about releasing the in the amazon app store however i have one fundamental question i do not see answered anywhere how is licensing handled if you release the app on the amazon store i am currently using the google lvl licensing in my paid apps to ensure the user is licensed to run them i assume that an app sold on amazon is not going to have any connection to tell google hey this app was purchased they are licensed so send them an ok to run status when they launch it or am i mistakendoes amazon have its own lvl type code or do you just have to forget licensing all together if you want to sell on amazon,['android'] +172058,retrieve values from c code into nlogconfig file is it possible to use variables in the nlogconfig configuration file to get values from some c code the reason i want to use a variable is to retrieve the password that i use to log info in my database previously entered by the user in a windows form,['c#'] +172061,get unique results from json array using jquery i have this block of code that thisplays the categories from my array into a jquery simple listit works fine but if there are 3 items from the category basketball the category will appear 3 timeshow could i make it so they only appear once thank youheres the code function loadcategories consoledebugabout to refresh with sort type sorttype var items eachcatalogproducts functionindex value itemspushli id index a dataidentityproductid hrefproductlistpagecategory valuecategory p stylemarginbottom0pxmargintop0px valuecategory pa li categoryviewhtmlitemsjoin categoryviewlistviewrefreshheres the code for my array var catalog products id 101name mountain bike color greyblacklongdesc 12speed carbon mountain bikedescription size 20 inchescategory outdoors equipment rentalsport cyclingbrand davincitopseller id 102name pro multi basketball color rainbowlongdesc on sale this week only this limited edition basketball is multicoloured and offers pro performance fun and games on the courtdescription limited edition basketballsize nacategory team gearsport basketballbrand niketopseller x,"['javascript', 'jquery']" +172067,android oncreateoptionsmenu item action sorry this is a dumb question but the answer is escaping me right now i have a menu created through override public boolean oncreateoptionsmenumenu menu menuaddemail return superoncreateoptionsmenumenu but i cannot remember how to set a onclicklistener so when its selected i can run my email function thanks,['android'] +172091,entity framework insists on adding new entity in manytomany instead of reusing existing fk i have got a many to many relationship brieflycases casesubjectrelationships casesubjectsmore fullycasesid casetypeid casesubjectsid thisplayname crmspincasesubjectsrelationshipscaseid subjectid primarysubject relationtocase in my manytomany link table are additional properties relating to the subjects association with the specific case such as start date end date freetext relationship to case observer creator etcan entity framework data model has been created aspnet version 40i have a wcf service with a method called createnewcase which accepts as its parameter a case object an entity created by the entity framework its job is to save the case into the databasethe wcf service is invoked by a third party tool here is the soap sentsenvelope xmlnss sbody createnewcase xmlns c xmlnsa acasesubjectsrelationships acasesubjectsrelationship acasesubject acrmspin601acrmspin athisplaynamefred flintstoneathisplayname acasesubject aprimarysubjecttrueaprimarysubject arelationtocaseinterestedarelationtocase astartdate20110712t0astartdate acasesubjectsrelationship acasesubjectsrelationship acasesubject acrmspin602acrmspin athisplaynamebarney rubbleathisplayname acasesubject arelationtocaseobserverarelationtocase astartdate20110712t0astartdate acasesubjectsrelationship acasesubjectsrelationships acasetype aidentifierchange of occupieraidentifier acasetype adescriptioncase descriptionadescription apriority5apriority aqueueidentifierqueue oneaqueueidentifier atitlecase titleatitle c createnewcase sbodysenvelopethe wcf engine deserializes this into a case entity for me correctly and when i look in the debugger everything is set up properlywhat i want to do is only create a new casesubject if there is not already an entry in the database with that crmspin specified crmspin is a reference number from a central customer databaseso in the below example i want to see if i already have an entry in casesubjects for somebody with crmspin 601 and if i do i do not want to create another duplicate entry but instead make the new case link to the existing subject although a new row will need obviously need creating in casesubjectsrelationships with the specific additional information such as relationship etchere is the net code i have tried to do thispublic class camsservice implements icamsservice public function createnewcasec as camsmodelcase as string implements icamsservicecreatenewcase using ctx as new camsentities find the case type dim ct ctxcasetypessingleordefaultfunctionx xidentifiertoupper ccasetypeidentifiertoupper give an error if no such case type if ct is nothing then throw new casetypeinvalidexceptionstringformatthe case type 0 is not valid ccasetypeidentifiertostring end if set the case type based on that found in database ccasetype ct for each csr in ccasesubjectsrelationships dim spin as string csrcasesubjectcrmspin dim s as casesubject ctxcasesubjectssingleordefaultfunctionx xcrmspin spin if not s is nothing then the subject has been found based on crmspin so set the subject in the relationship csrcasesubject s end if next ccreationchannel web service ccreationdate nowdate save it ctxaddtocasesc ctxsavechanges end using return the case reference return cidtostring end functionend classas you can see instead the for each loop i try to get a subject based on the crmspin and if i get something then i update the casesubject entity i have also tried csrsubjectid sid instead of setting the whole entity and also i have tried setting them bothhowever even when putting a breakpoint on the ctxsavechanges line and looking at how the subjects are set up and seeing in the debugger that it looks fine it is always creating a new row in the casesubjects tablei can see in principle this should work youll see i have done exactly the same thing for case type i have picked the identifier sent in the xml found the entity with that identifier via the context then changed the cases casetype to the entity i found when it saves it works perfectly and asexpected and with no duplicated rowsi am just having trouble trying to apply the same theory to one side of a manytomany relationshiphere are some hopefully relevant extracts from the edmxentityset namecases entitytypecamsmodelstorecases storetypetables schemadbo entityset namecasesubjects entitytypecamsmodelstorecasesubjects storetypetables schemadbo entityset namecasesubjectsrelationships entitytypecamsmodelstorecasesubjectsrelationships storetypetables schemadbo associationset namefk casesubjectsrelationships cases associationcamsmodelstorefk casesubjectsrelationships cases end rolecases entitysetcases end rolecasesubjectsrelationships entitysetcasesubjectsrelationships associationset associationset namefk casesubjectsrelationships casesubjects associationcamsmodelstorefk casesubjectsrelationships casesubjects end rolecasesubjects entitysetcasesubjects end rolecasesubjectsrelationships entitysetcasesubjectsrelationships associationsetedit the property setters for the casesubject property of the casesubjectsrelationships object summary no metadata documentation available summaryxmlignoreattributesoapignoreattributedatamemberattributeedmrelationshipnavigationpropertyattributecamsmodel fk casesubjectsrelationships casesubjects casesubjectpublic property casesubject as casesubject get return ctypeme ientitywithrelationshipsrelationshipmanagergetrelatedreferenceof casesubjectcamsmodelfk casesubjectsrelationships casesubjects casesubjectvalue end get set ctypeme ientitywithrelationshipsrelationshipmanagergetrelatedreferenceof casesubjectcamsmodelfk casesubjectsrelationships casesubjects casesubjectvalue value end setend property,['asp.net'] +172100,deleting part of a string in mysql i want to delete part of a string found in a particular field for example the entry in the field could be 01365320aps the aps is what i am looking at deleting my question is should i useselect substring indexfieldnameaps 1,"['mysql', 'sql']" +172113,c datetimes conversion for different time zones i have a bunch of date times that i keep track of for my app they are all in utc time for part of my app i want to send an email with one of these times but edited to be in that specific time zonethere are only two major areas that i will deal with the east coast and texas dallas and hustoni can also make a new datetime when i send out this email to get the eastern time zone datetime timestamp datetimenowmy question is thisif the user is in the texas area how can i convert my time from eastern to that time 1 hour lessi tried something like this convert timestamp to local time timespan ts timezonecurrenttimezonegetutcoffsettimestamp timestampaddts timestampstring timestamptostringbut that did not work i also know that this line is not validtimestamphour timestamphour 1,['c#'] +172132,which javascriptframework can search css stylesheet rules and edit their properties the questionwhich javascript framework prototype scriptaculous mootools mochikit has decent css rule editing supportthis is about changing a style rule i want to have dynamic css classes which change examplestyleanswer reveal thisplay none color blue answer additional stuff stylenow via javascript i want to change the rule that has the athisplay nonea in it a iam convinced that sometimes this is the right way to go iam not looking for alternatives when it is not the right way to do which framework out there makes the following easyselect a rule from all rules eg aanswer revealawhat value does the selected rules have for athisplayadelete the athisplaya property from the rules2 and 3 are easy with dom alone as long as i get a handle to the css rule back from the frameworkthe frameworks which are not good enoughyuias stylesheet for example can only search for rules in one sheet at a time limited but enough for me but it canat show edit or retrieve multiselector rules like my first example too limited for my tasteyui has also no way to get individual properties the underlying dom can but you canat get that structure through yui you could delete the athisplaya property alone though if you get hold of the rule by yui meansdojo has some badly documented and incomplete stuff under dojoxhtmlstylesext js has extutilcss i checked the code and found a bug in getrule it is otherwise pretty sloppy with selectormatching bad ie influence which makes it bad for multiselector rules it also canat delete properties through the api but can give you the cssrule so you can do it yourself a the css tree walking is as primitive as it could be no descending on media rules or importspdrevealcsswhatever is not the answer because it does not touch the css rules at all it touches the css attributes of some elements instead,"['javascript', 'css']" +172141,horizontal ul navigation aligned to the right side i am trying to create a horizontal navigation which is aligned to the right side of the parent element you can see the navigation at where it says espresso my html is ul idmenustandard li idmenuitemaitem 4ali li idmenuitemaitem 3ali li idmenuitemaitem 2ali li idmenuitemaitem 1aliulmy css is menu li float right marginleft 20pxit works like this the only problem is that the order in the list is wrong the first item is the last one in the html code any tips for me thanks a lotyannis,"['html', 'css']" +172143,zipcompress a folder full of files on android i need to zip up a project folder to allow users to share projects via email i found a class for zipping up multiple files into one zip but i need to keep the folder structure in my zip is there any way to achieve this on android thanks in advance,['android'] +172147,making a list of evenly spaced numbers in a certain range in python what is a pythonic way of making list of arbitrary length containing evenly spaced numbers not just whole integers between given bounds for instancemy func0510 lower bound upper bound length 0 05 1 15 2 25 3 35 4 45 note the range function only deals with integers and thisdef my funclowupleng list step up low floatleng for i in rangeleng listappendlow low low step return listseems too complicated any ideas,['python'] +172181,syntax error using parse ini file when files values contain exclamation points and equal signs the function below takes the testbackupini file parses it and inputs the values into the db via the update option methodhowever when the ini files values contain special characters like exlamation points and equal signs and others i would guess its throwing a php syntax error at parse ini filefilesyntax error unexpected etcfor example given this content as the testbackupini filesettingsline1 ascline2 blog ul li marginbottom0 importantline3 trueline4 meta namegooglesiteverification content i get syntax errors on line2 for the and on line 4 for the how should i filter the file before passing it to parse ini file to deal with these characters to that they are preserved when passed to the update option callall i have found thus far is this characters must not be used anywhere in the key and have a special meaning in the valuefile wp plugin dirtesttestbackupiniif file existsfile is readablefile ini array parse ini filefile errors when value contains etc foreach ini array as keyvalue update optionkey value echo the settings have been savedelse echo alternate response here,['php'] +172195,sql current month year question so i have a table that has the month and year broken down for example field called month has the number 7 in it this month and the year field has 2011 theres also additional months years etc how can i query this to show just the current year month,['sql'] +172202,upload resized image to s3 i am trying to upload resized image to s3fp urlliburlopenhttpexamplecomtestpngimg cstringiostringiofpreadim imageopenimgim2 imresize500 100 imagenearest ak xx access key id sk xx secret access keyconn s3connectionaksk b connget bucketexamplek keybkkey examplepngkset contents from filenameim2but i get an error in set contents from filename fp openfilename rbtypeerror coercing to unicode need string or buffer instance found,['python'] +172208,android make view thisappear by clicking outside of it i have some views that i make visible upon a button press i want them to thisappear if i click outside of those viewshow would this be done on android also i realize that the back button can also assist android users with this i might use that as a secondary way to close the views but some of the tablets are not even using a physical back button anymore it has been very deemphasized,['android'] +172240,how to animate a timeordered sequence of matplotlib plots i want to plot a sequence of png images in matplotlib the goal is to plot them rapidly to simulate the effect of a movie but i have additional reasons for wanting to avoid actually creating an avi file or saving matplotlib figures and then viewing them in sequence outside of pythoni am specifically trying to view the image files in sequence inside a forloop in python assuming i have imported matplotlib correctly and i have my own functions new image and new rect heres some example code that fails to work because of the blocking effect of the show functions call to the gui mainloop for index in index list img new imageindex rect new rectindex pltimshowimg pltgcaadd patchrect pltshow i also tried pausing briefly and then closing but this does not get executed due to the gui mainloop from show timesleep025 pltclosethe above code works to show only the first image but then the program just hangs and waits for me to manually close the resultant figure window once i do close it the program then just hangs and does not replot with the new image data what should i be doing also note that i have tried replacing the pltshow command with a pltdraw command and then adding the pltshow outside of the forloop this does not thisplay anything and just hangs,['python'] +172243,iphone how does one read an image from the photo library as nsdata on the iphone i saved an image to the photo library with modifications appending data after the image code using the assest library to save the nsdata directly to the photo library now i want to read the image back from the photo library as an nsdata to read it if i read it as a uiimage it changes the data inside the imagehow can i read the photo from the photo library as nsdata i tried looking into the reference url in 41 but no luckedit i edited to explain why i am saving it as an nsdata the url method in the answers works if you just want pure nsdata but does not help in the context that i am askingedit 2 the answer with the getbytes was the answer that did it for me the code i used wasint8 t bytes mallocrepresentation sizensuinteger length representation getbytesbytes fromoffset0 lengthrepresentation size errorerrorthis was able to get me everything inside the file which gave me the image code plus what i added in nsdata form,['iphone'] +172251,how to install a ipa file into my iphone i need to install an app into my iphone i have the ipa file of that app and also my device is added to the developers account i downloaded the file and open it in itunes and when i am trying to sync my iphone with itunes it gives me an error saying wbw app was not installed on your iphonecould anyone can please provide me with the steps or any link,['iphone'] +172252,activerecord query union i have written a couple of complex queries at least to me with rors query interfacewatched news posts postjoinsnews watchedwherewatched user id idwatched topic posts postjoinspost topic relationships topic watchedwherewatched user id idboth of these queries work fine by themselves both return post objects i would like to combine these posts into a single activerelation since there could be hundreds of thousands of posts at some point this needs to be done at the database level if it were a mysql query i could simply user the union operator does anybody know if i can do something similar with rors query interface,['ruby-on-rails'] +172263,is this code well defined i suspect the following chaining of functions would result in unspecified sequence according to the c standards assume c0x just want a confirmation and if anyone could provide an explanation i would appreciate itinclude iostreamstruct tfoo tfooint stdcouttfoostdendl tfoo foobar1int stdcoutfoobar1stdendl return this tfoo foobar2int stdcoutfoobar2stdendl return this static int bar1 stdcoutbar1stdendl return 0 static int bar2 stdcoutbar2stdendl return 0 static int bar3 stdcoutbar3stdendl return 0 int mainint argc char argv is the sequence well defined for bar1 bar2 and bar3 tfootfoobar1foobar1tfoobar2foobar2tfoobar3 edit removed fastcall specifier for functions not requiredrelevant to the question,['c++'] +172268,header changes as you scroll down jquery techcrunch recently redesigned their site and they have a sweet header that minifies into a thinner version of their branding as you scroll downyou can see what i mean here how would i go about creating something like this is there a tutorial anywhere and if not can one you kind souls give me some tips on where to start,['jquery'] +172271,how to remove unused cc symbols with gcc and ld i need to optimize the size of my executable severely arm development andi noticed that in my current build scheme gcc ld unused symbols are not getting strippedthe usage of the armstrip stripunneeded for the resulting executables libraries does not change the output size of the executable i have no idea why maybe it simply cannotwhat would be the way if it exists to modify my building pipeline so that the unused symbols are stripped from the resulting filei wouldnt even think of this but my current embedded environment is not very powerful and saving even 500k out of 2m results in a very nice loading performance boostupdateunfortunately the current gcc version i use does not have the deadstrip option and the ffunctionsections gcsections for ld does not give any significant difference for the resulting outputi am shocked that this even became a problem because i was sure that gcc ld should automatically strip unused symbols why do they even have to keep them,"['c++', 'c']" +172272,keep persistent variables in memory between runs of python script is there any way of keeping a result variable in memory so i do not have to recalculate it each time i run the beginning of my scripti am doing a long 510 sec series of the exact operations on a data set which i am reading from thisk every time i run my scriptthis wouldnt be too much of a problem since i am pretty good at using the interactive editor to debug my code in between runs however sometimes the interactive capabilities just do not cut iti know i could write my results to a file on thisk but i would like to avoid doing so if at all possible this should be a solution which generates a variable the first time i run the script and keeps it in memory until the shell itself is closed or until i explicitly tell it to fizzle out something like this check if variable already created this sessionin mem var in memory returns pointer to var or false if not in memory yetif not in mem read data set from thisk with openmydata r as in handle mytext in handleread extract relevant results from data set mydata parse datamytext result initial operationsmydata in mem store persistentresulti have an inkling that the shelve module might be what i am looking for here but looks like in order to open a shelve variable i would have to specify a file name for the persistent object and so i am not sure if it is quite what i am looking forany tips on getting shelve to do what i want it to do any alternative ideas,['python'] +172273,what compatibility do i lose when dropping the khtml vendor prefix i have bits and pieces of css that use the webkit vendor prefix for compatibility with older versions of safari i have the same rule with the khtml vendor prefix i am actively uninterested in compatibility with konqueror and other true khtml browsersfor example i may have the following rulesmenuitem khtmluserselect none webkituserselect nonei understand that modern webkit browsers internally rewrite all khtml and apple rules to be webkit rules instead however that leaves me with the following questionin what version of safari did webkit become available that is what is the version before which safari would completely ignore my rulesi plan to use this information to find out whether my individual rules such as khtmluserselect are actually supported by this early version of safari,['css'] +172275,whats the equivalent of has key in javascript if dictionaryhas keyschoolhow would you write this in javascript,"['javascript', 'python']" +172287,how to programmatically add a uisegmentedcontrol to a container view how would i define the frame for a uisegmentedcontrol i would like the segmented control to appear at the bottom of a container view ie uiview,"['iphone', 'objective-c']" +172299,can you use form wizard for model forms in django i have one model and i have created a form out of the model using modelform now i want to spread the form across two pages for example the first three fields will appear on the first page then the user clicks next and the last three fields appear on the second page then he clicks submit and the user submitted data is added to the databasei took a look at the docs for the form wizard and it seems like it would work for model forms as well can someone confirm thisand if it does can someone explain the process of creating a wizardview classthis example is given in the docs and i do not understand what the second two parameters are is form list just a list of form objects that youve instantiated based on your form classes and what is kwargsclass contactwizardsessionwizardview def doneself form list kwargs do something with the form dataform list return httpresponseredirectpagetoredirecttowhendonethanks in advance for your help,['python'] +172313,how do i grant read access for a user to a database in sql server i want to grant access to a user to a specific database with read and write access the user is already available in the domain but not in the dbso how can i give them that access with creating a new user and passwordsomeone told me that it can be done with only specifying the user domain the db that you want to give the user the access to without needing to create a new user and passwordthis is the old way that i was implementing it works but it creates a new login and user rather than using the one that is available in the domainuse dbnamecreate login a 2 with passwordaa123create user a 2 for login a 2grant insert to a 2grant select to a 2,['sql'] +172314,sl4a vs ruboto on android application development i am thinking about creating apps on android using jruby or a suitable variant of ruby for androidaccording to my research there are two current projects that support ruby development on androidrubotosl4afrom the faq of the ruboto wiki on github it seems like ruboto is ready for application development but does not yet support jit compilation and the application has to be packaged with libraries which give it a big footprint for mobile device installationi do not have enough knowledge about sl4a but it seems like sl4a also tries to run jruby scripts on the jvm but the main thing is that sl4a is still in alpha so i do not know if it can be used for app developmentcan someone with a better knowledge of these platforms suggest which one should be used also in the near future which one has the better probability of becoming more mature in terms of jit performance lower footprint and better api access to android,['android'] +172328,how to test if two objects are the same with javascript i need a function function issamea b in which if a and b are the same it returns true i tried return a b but i found that will return falsesome results that i expect this function can gave issame314 314 true issamehello hello true issame true issame1 2 1 2 true issame a 1 b 2 a 1 b 2 true issame1 a1 1 a1 true,['javascript'] +172329,nsfetchrequest predicate with bool check is slow consider the following 2 predicates filtering through a 5k entries storepredicate1 nspredicate predicatewithformathidden no and name beginswithcd searchstringpredicate2 nspredicate predicatewithformatname beginswithcd searchstringi turned on comapplecoredatasqldebug to see the fetch request timespredicate1 04728spredicate2 00867sam i missing something both columns are indexed how come adding a simple boolean check slows down the fetch request that much edit as requested the outputcoredata sql select 0 t0z pk t0z opt t0zhidden t0zid t0zname t0zrank from zartistindex t0 where t0zhidden and nscoredatastringsearch t0zname 393 0 or nscoredatastringsearch t0zname 393 0 order by t0zrank desc limit 14that rank column is also indexed the reason i need this request to be faster than 05s is that it is used for an autocomplete feature that request is made every time the value of some text field gets changed by the useredit 2 adding more contextual info nsarrayautocompletesuggestionsnsstringsearchstring nsfetchrequest request nsfetchrequest alloc init nsentitydescription entity nsentitydescription entityfornameartistindex inmanagedobjectcontextselfindexobjectcontext request setentityentity request setfetchlimit10 nspredicate predicate nspredicate predicatewithformathidden no and name beginswithcd or name beginswithcd searchstring nsstring stringwithformatthe searchstring request setpredicatepredicate nssortdescriptor sortdescriptor nssortdescriptor alloc initwithkeyrank ascendingno request setsortdescriptorsnsarray arraywithobjectsortdescriptor sortdescriptor release nsarray resultsarray selfindexobjectcontext executefetchrequestrequest errornil request release return resultsarraythe artistindex entity has the following attributesid int32 name string indexed rank int32 indexed hidden bool indexededit 3 here are the full sql outputs for the slow query predicate1 and the fast query predicate2 with comapplecoredatasqldebug set to 3 more rigorous testing brought me the following test times which are better but still have a 2x difference and really make a difference in an autocomplete suggestions context or is this a reasonable fetch time difference nowpredicate1 03772spredicate2 01633s,['iphone'] +172360,in mfc carray what are reasons to use different default template type the mfc carray class has two template parameters from msdntemplate class type class arg type const type class carraythe default parameter for arg type is const type and some questions on so ask when to use a type different from the default eg should the arg type for a carray be const or not or whats the difference between carray and carray my questions are now are there reasonable use cases of carray where the arg type is not type or const type eg another class what are the reasons for these usages,['c++'] +172365,how to show one layout on top of the other programmatically in my case my main layout mainxml simply contains two linearlayoutsthe 1st linearlayout hosts a videoview and a buttonthe 2nd linearlayout hosts an edittext and this linearlayout has set the visibility value to gone androidvisibilitygonelike belowlinearlayout xmlnsandroid androidlayout heightfill parent androidlayout widthfill parent androidorientationvertical linearlayout androidididfirst ll androidlayout widthfill parent androidlayout heightwrap content androidorientationhorizontal videoview androidididmy video androidlayout widthwrap content androidlayout heightwrap content androidlayout weight9 button androidididmy btn androidlayout width30dip androidlayout height30dip androidlayout gravityrightbottom androidlayout weight1 linearlayout linearlayout androidididsecond ll androidlayout widthfill parent androidlayout heightwrap content androidpaddingtop2dip androidvisibilitygone edittext androidididedit text field androidlayout height40dip androidlayout widthfill parent androidlayout weight5 androidlayout gravitycenter vertical linearlayoutlinearlayouti successfully implemented the feature that when the button with id my btn is pressed the 2nd linearlayout with edittext field is shown with the following java codelinearlayout secondll linearlayout findviewbyidridsecond llbutton mybtn button findviewbyidridmy btnmybtnsetonclicklistenernew onclicklistener override public void onclickview v int visibility secondllgetvisibility ifvisibilityviewgone secondllsetvisibilityviewvisible with the above java code the 2nd linearlayout with edittext is shown like appending below the 1st linearlayout which makes sense but what i need is when buttonid my btn is pressed the 2nd linearlayout with edittext is shown on top of the 1st linearlayout which looks like the 2nd linearlayout with edittext is rising from the bottom of screen and the 2nd linearlayout with edittext only occupy part of the screen from bottom that is the 1st linearlayout still visible like the image below showedso when buttonid my btn is pressed how to show the 2nd linearlayout with edittext on top of the 1st linearlayout instead of appending 2nd linearlayout below 1st linearlayout programmatically,['android'] +172372,calayer with rotation animation i have masked an image like thisuiview maskimage maskimage uiview alloc initmaskimagebackgroundcolor uicolorfromrgbftrmaskcolormaskimageframe newframecalayer thelayer calayer layerthelayercontents iduiimage imagenamedimagepng cgimagethelayerframe newframemaskimagelayermask thelayerit works fine but the main problem is if i want to rotate the my ipad the rotation animation of the view or the layer i am not very sure does not work it rotates without animation could you help please,"['iphone', 'objective-c', 'ios']" +172394,is htmlunit 28 getfirstbyxpath different from htmlunit 114 getfirstbyxpath i have a site structure that looks something like thisdiv classmain container div classitem container div classbody span classitem nameitem 1span span classitem descdesc 1span div div div classitem container div classbody span classitem nameitem 2span span classitem descdesc 2span div div divend of main container note some divs might not have span classitem nameitem nspan or other elements inside the item containerin htmlunit 114 if i want to get all item namelisthtmldivision divs listhtmldivisionpagegetbyxpathdivclassitem containerforhtmldivision divdivs string name htmlelementdivgetfirstbyxpathspanclassitem nameastext systemoutprintlnnameoutputitem 1item 2but in htmlunit 28 when i do the same i gotitem 1item 1is there a workaround on this in htmlunit 28,['java'] +172425,how to deal with last comma when making comma separated string possible duplicatesdont print space after last numberprinting lists with commas c include vectorinclude iostreaminclude sstreaminclude boostforeachhppusing namespace stdint main vectorint vecints vecintspush back1 vecintspush back2 vecintspush back3 vecintspush back4 vecintspush back5 stringstream ss boost foreachint i vecints ss i cout str return 0this prints out 12345however i want 12345how can i achieve that in an elegant wayi see there is some confusion about what i mean with elegant eg no slowing down ifclause in my loop imagine 10 entries in the vector if that is all you have to offer i would rather remove the last comma after i have gone through the loop,['c++'] +172431,problem using multibytetowidechar i wanted to convert a normal string to a wide string for this i am using the function multibytetowidechar functionbut i have not been at success using this function here is what i have done till nowexamplestring x this is c not javawstring wstringint c multibytetowidechar cp utf8 0 xc str xsize wstring 0 the above line produces error which says multibytetowidechar cannot convert parameter 5 from stdwstring to lpwstrhow can i fix this error and what should be the sixth argument of this function is 0 ok,['c++'] +172454,why are clicks in my expandablelistview ignored i have an alertdialog populated by an expandablelistview the list itself works perfectly but for some reason clicks are ignored apparently my click handler is never calledthis is the codealertdialogbuilder builder new alertdialogbuilderthisbuildersettitleselect somethingexpandablelistview mylist new expandablelistviewthismyexpandablelistadapter myadapter new myexpandablelistadaptermylistsetadaptermyadaptermylistsetonitemclicklistenernew expandablelistviewonitemclicklistener override public void onitemclickadapterview a view v int i long l try toastmaketextexpandablelist1this you clicked me toastlength longshow catchexception e systemoutprintlnsomething wrong here buildersetviewmylistdialog buildercreatedialogshowif i instead try to populate the alertdialog with a plain listview click events are generated without problemsalertdialogbuilder builder new alertdialogbuilderthisbuildersettitleselect color modelistview modelist new listviewthisstring stringarray new string bright mode normal mode arrayadapterstring modeadapter new arrayadapterstringthis androidrlayoutsimple list item 1 androidridtext1 stringarraymodelistsetadaptermodeadaptermodelistsetonitemclicklistenernew onitemclicklistener public void onitemclickadapterview parent view view int position long id when clicked show a toast with the textview text toastmaketextgetapplicationcontext textview viewgettext toastlength shortshow buildersetviewmodelistalertdialog dialog1 buildercreatedialog1showwhat could be the reason why click event fails in my expandablelistview but not in a normal listview i am probably missing something but i have no idea what that could be,['android'] +172469,possible to limit the countries an ios application is released to is it possible to limit the countries an ios application is released to is it possible to limit a version to a certain countryif so where could i find more information i attempted searching the documentation but was unable to locate decisive information regarding this thanks in advance,['ios'] +172472,create table from view i have a view that i want to create a table from in sql enterprise manager but i always get an error when i run this querycreate table a asselect top 10 from dbomyviewso far the error is syntax error at as view is too large is it possible to use a top 10,['sql'] +172484,simple object validation in java i wonder what is the best practice for object validation is there any extra argument against case one or case two is there another wayi do not search for any validation library i just want to do simple validationcase oneclass a public void dosomethingmyobject o try validateo dosomethingusefulo catch validationexception e loggergetloggerwarne private void validatemyobject o throws validationexception if ogetxyz null throw new validationexceptionfield xyz cannot be null private void dosomethingusefulmyobject o some funny stuff case twoclass a public void dosomethingmyobject o if validateo dosomethingusefulo else loggergetloggerwarnobject is invalid private boolean validatemyobject o if ogetxyz null return false return true private void dosomethingusefulmyobject o some funny stuff,['java'] +172502,gdb front end to use with vim what gdb frontends can i use with vim for debugging c and c code currently i use cgdb and am satisfied with it was just wondering what else is out there,"['c++', 'c']" +172506,convert datetime to valid javascript date i have a datetime string being provided to me in the following formatymmdd hhmmss20110714 112300when attempting to parse it into a javascript date object it fails what is the best way to convert this into a format that javascript can understandthe answers below suggest something likevar mydate new date20110714 112300which is what i was using it appears this may be a browser issue i have made a for this it works ok for me in chrome in firefox 501 on os x it returns invalid date,['javascript'] +172540,how can i find out if a user has clicked the facebook like button on my website i want to include content on my website which will only be thisplayed if the user has clicked the facebook like button on the very same page i see in the documentation there is the edgecreate event which i can subscribe to but would not that only fire when the user likes the page the very first time if a user has already liked the page i want him to be able to come back and download again without having to unlike and then like againi also notice that this information can be queried through fql and the likes but it is not clear what the auth requirements are for thisis it possible to do this in some way without extra authentication i want there to only be a single step for the user if he is already logged in,['javascript'] +172572,acts as taggable on and checkbox tags i am using ror 308 and the gem acts as taggable on i want to make it so that a post can have any of the following tags politics sports social science i want them to choose the tags when they create the post and do this using checkboxes is there a way to make it say that if the politics checkbox is check then posttag listpolitics,['ruby-on-rails'] +172576,send a broadcast only to specific activity i have one activity which creates a broadcastreceiver with an intentfilter in the method oncreate intentfilter ifilter new intentfilteractionreceiver new broadcastreceiver override public void onreceivecontext context intent intent registerreceiverreceiver ifilteron the other side is an intentservice which shall send some dataintent intent new intentgetapplicationcontext receiverclassintentsetactionactionsendbroadcastintentbut it seems not to work no broadcast ist receivedmy service class is in an android lib perhaps this makes troublethanks for any advices,['android'] +172589,what does self do possible duplicatepython self keyword forgive me if this is an incredibly noobish question but i never did understand self in python what does it do and when i see things likedef exampleself args return selfsomethingwhat do they do i think i have seen args somewhere in a function too please explain in a simple way p,['python'] +172592,emulator problem after new adt update hi after updating to adt 12 at first seemed ok then i got some problems like theseemulator run improperly and give the problem i report belowi tried to use the quick code from xml windows and it mingle the codeline does anyone has encountered teh same problemsthis is the error i got in the console after trying to run a project20110714 202836 cursomc5leccion6 20110714 202836 cursomc5leccion6 android launch20110714 202836 cursomc5leccion6 adb is running normally20110714 202836 cursomc5leccion6 performing comwocmultimediacursomc5leccion6main activity launch20110714 202836 cursomc5leccion6 automatic target mode launching new emulator with compatible avd avdgooglemarket20110714 202836 cursomc5leccion6 launching a new emulator with virtual device avdgooglemarket20110714 202842 cursomc5leccion6 new emulator found emulator5420110714 202842 cursomc5leccion6 waiting for home androidprocessacore to be launched20110714 202957 cursomc5leccion6 emulator54 thisconnected cancelling comwocmultimediacursomc5leccion6main activity launch20110714 203322 cursomc5leccion6 20110714 203322 cursomc5leccion6 android launch20110714 203322 cursomc5leccion6 adb is running normally20110714 203322 cursomc5leccion6 performing comwocmultimediacursomc5leccion6main activity launch20110714 203322 cursomc5leccion6 automatic target mode launching new emulator with compatible avd avdgooglemarket20110714 203322 cursomc5leccion6 launching a new emulator with virtual device avdgooglemarket20110714 203324 emulator warning data partition already in use changes will not persist20110714 203324 emulator warning sd card image already in use cdocuments and settingsangelo giammarresiandroidavdavdgooglemarketavdsdcardimg20110714 203324 emulator warning cache partition already in use changes will not persist20110714 203324 cursomc5leccion6 new emulator found emulator5620110714 203324 cursomc5leccion6 waiting for home androidprocessacore to be launched,['android'] +172593,android how to set text color for list items in alertdialog properly i have an alertdialog in my application it contains a list of custom views with textview widgets inside everything works fine on android 2x the alertdialog is created with white list and black text in it but when i run my app on android 3x devices all textviews are black and lists background is black too so i cannot see the text until i tap and hold one of the itemsheres a textviews definition from the layout filetextview androidididlabel androidlayout widthfill parent androidlayout heightwrap content androidsinglelinetrue androidellipsizemarquee androidtextappearanceandroidattrtextappearancesmallinverse i thought that using textappearancesmallinverse for the textappearance attribute is a proper way to set text parameters and it must work on all devices but seems i was wrong so what should i do to make alertdialog thisplay list items properly on all platforms thanks in advance,['android'] +172606,java or c equivalents to preon preon is a java library meant for creating binary codecs you simply place annotations in a class data members regarding their correspondence with bit fields eg number of bits to use for certain field and based on such class the library builds a codec object that is able to create instances of the class reading their data from a binary input streamdue to licensing issues it is thistributed under gpl i cannot use itare there any libraries with equivalent or similar functionality either in java or in c,"['java', 'c++']" +172608,php script does not exit on browser exit why this dummy script keeps running event if the client closes the browser so the connection to the serverwhile true sleep 1 file put contents tmpfoo i am alive getmypidn file append it is unexpected to me according to this also this example does not seem to workand set time limit with a nonzero parameter simply does nothingi would like some clarifications,['php'] +172626,how to save photo with exifgps and orientation on iphone i am using writeimagetosavedphotosalbummetadatacompletionblock to save images to the camera roll gps data is in dictionary passed to metadata however pictures are misoriented as i flip the device while taking the pictures there is another function writeimagetosavedphotosalbumorientationcompletionblock but i would not be able to pass exif dataaccording to the documentation there is kcgimagepropertyorientation property to set orientation manually but i am having problems with detecting current orientation of the device while taking the picture and saving ithas anyone achieved saving picture with exif data and proper orientation any help would be very appreciatedheres my code voidimagepickercontrolleruiimagepickercontroller picker didfinishpickingmediawithinfonsdictionary info image info objectforkeyuiimagepickercontrolleroriginalimage self thismissmodalviewcontrolleranimatedyes imageview setimageimage ifsourcecamera exif and gps metadata dictionary saving image alassetslibrary al alassetslibrary alloc init al writeimagetosavedphotosalbumimage cgimage metadatadict completionblocknsurl asseturl nserror error if error nil nslogsaved else nslogerror al release best wishesa,['iphone'] +172627,flasksqlalchemy update a rows information how can i update a rows information for example i would like to alter the name column of the row that has the id 5,['python'] +172631,threadcurrentprincipalidentityname is empty from wpf editthe simple question is how can i get threadcurrentprincipalidentityname to have the current user logon in wpfend editi am trying to call an existing method not in any sort of service just a method in a poco that retrieves the current user withthreadcurrentprincipalidentitynamethis code was written by someone else and presumably works with his aspnet mvc project i am trying to call this same method from wpf and name is now blankis there anything i can do about this,['c#'] +172653,proper way to use linq with cancellationtoken i am trying to write a linq query that would support cancellation using the cancellationtoken mechanism that is provided in the net framework however it is unclear what the proper way to combine cancellation and linq would bewith plinq it is possible to write var resultsequence sourcesequenceasparallel withcancellationcancellationtoken selectmyexpensiveprojectionfunction tolistunfortunately withcancellation only applies to a parallelenumerable so it cannot be used with a plain old linq query it is possible of course to use withdegreeofparallelism1 to turn a parallel query into a sequential one but this is clearly a hack var resultsequence sourcesequenceasparallel withdegreeofparallelism1 withcancellationcancellationtoken selectmyexpensiveprojectionfunction tolisti would also like to avoid creating a separate task for this operation as i need to do this in several places and i need to be able to control which thread this code runs on in some instancesso short of writing my own implementation of withcancellation is there an alternative that would achieve the same thing,"['c#', '.net']" +172663,how to create a stdstring directly from a char array without copying say i have an array of chars which i have allocated on the heap and which i want to convert into an stdstring currently i am doing the followingchar array new charsizewriteintoarrayarray sizestdstring mystringarraydelete arrayreturn mystring or whateverfrom what i read on the internet the string constructor performs a copy of the buffer i pass it leaving me to free the buffer later the string frees its internal buffer what i would like to do is to allocate my buffer transfer control of it to the string and then have it free my buffer when it is destructedthe question initializing stdstring from char without copy looked promising but my code relies on api calls writeintoarray in the above example which have to write into an array of chars so i have to create a cstyle char buffer and cannot convert my code to use only builtin string operations which was the answer suggestedis there some standard way to do this or should i just write my own string class ugh thanks,['c++'] +172679,rails 31 using images under appassetsimagessubdirectory in my rails 31 app i have images stored under appassetsimagesjquery uii do not know how to access these in my css assetsimage namepng and assetsjquery uiimage namepng do not work,['ruby-on-rails'] +172689,android contentprovider and google io rest talk to allif you watch the google io session on building android rest apps they are suggesting in all three design patterns to use content providers regardless if you need to share data or notif you look at the content provider class doc at they say you only need to use a content provider if you plan on sharing your data with other applicationsmy application does not need to share any data with other applications so is using a content provider overkill and if so why does the google io rest video imply that it should be used in all scenarios update talks are here,['android'] +172710,polygon partioning vs triangulation hey so i recently asked this question about how to cut down a concave polygon to convex ones and i was suggested to do triangulation or polygon partioningthe library i am using sfmlbox2d only takes convex shapesthis is what i want to knowis polygon partioning or triangulation of polygons fasterhow does polygon partioning work how do you do itdo not forget triangulation does not require convex shapes to be made either,['c++'] +172720,variable with mongodb dotnotation i want to increase a field inside an object object inside a mongodb document by 1 var stuffid 5 collectionupdate id id inc stuffstuffid 1 functionerr doc resenddone i need to make that stuffid a variable any way to do that thanksthis is using nodemongodbnative if that helpsif youre voting to close can you explain what it is you do not understand,['javascript'] +172744,listview setonitemclicklistener not working by adding button i have a list view with text and button in each row list view setonitemclicklistener is not working is it possible to handle item click and button click events differentlyitem click should call activitya and button click should call activityb does anyone have a solution private arrayliststring useridarr null private arrayliststring usernamearr null private databasehelper dbhelper null private listview userlistviewnull public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutlist view dbhelper new databasehelperthisgetapplicationcontext mapstringarrayliststring thisplaymap dbhelpergetuserlisttothisplay useridarr thisplaymapgetuserid usernamearr thisplaymapgetfirstname1 userlistview listview findviewbyidridlistview2 userlistviewsetadapternew userlistadapterthisuseridarr userlistviewsetonitemclicklistenernew adapterviewonitemclicklistener override public void onitemclickadapterview arg0 view arg1 int position long arg3 toastmaketextuserslistactivitythis item in position position clicked toastlength longshow public class userlistadapter extends arrayadapterstring activity context public userlistadapteractivity context arrayliststring names supercontext rlayoutlist item names thiscontext context private class viewholder public textview usernameandid public textview description public button uploadbtn override public view getviewint position view convertview viewgroup parent viewholder holder view rowview convertview if rowview null layoutinflater inflater contextgetlayoutinflater rowview inflaterinflaterlayoutlist item null true holder new viewholder holderusernameandid textview rowviewfindviewbyidriduser detailstxt holderdescription textview rowviewfindviewbyidriduser status holderuploadbtn button rowviewfindviewbyidriduploadbutton holderuploadbtnsetonclicklistenernew viewonclicklistener public void onclickview v toastmaketextuserslistactivitythis button clickedtoastlength shortshow rowviewsettagholder else holder viewholder rowviewgettag string s usernamearrgetpositionuseridarrgetposition holderusernameandidsettexts holderdescriptionsettextu r in middle return rowview,['android'] +172753,testing c iterator i am writing a c randomaccessiterator for a custom array typesince it does not work with stdsort and a simple int array i would like to make sure that i have implemented it correctlydo you know of any iterator conformance testing framework out therei have implemented every possible function or operator and everything seems correct but i still miss something since sort dereferences arrayend,['c++'] +172767,give a delay of few seconds without using threads how can i give a delay of few seconds without using threadssome function that i can call anywhere for giving delay android builtin function is highly preferred thanks,['android'] +172769,how to reverse the direction of marquee of a textview i want to reverse the direction of marquee in the textview by default the text moves from right to left i want it to move from left to right how can i do this,['android'] +172798,using only g works but not g c and ld i have the following source code in maincppinclude iostreaminclude iomanipint main stdcout hi stdendl return 0using this command works and creates the executable fileg o main maincppbut this commands do not workg c maincppld o main mainothe second one errors withld warning cannot find entry symbol start defaulting to 040e8maino in function mainmaincpptext0xa undefined reference to stdcoutmaincpptext0xf undefined reference to stdbasic ostreamchar stdchar traitschar stdoperator stdchar traitschar stdbasic ostreamchar stdchar traitschar char constmaincpptext0x14 undefined reference to stdbasic ostreamchar stdchar traitschar stdendlchar stdchar traitschar stdbasic ostreamchar stdchar traitschar maincpptext0x1c undefined reference to stdostreamoperatorstdostream stdostreammaino in function static initialization and destruction 0int intmaincpptext0x4a undefined reference to stdios baseinitinitmaincpptext0x4f undefined reference to stdios baseinitinitmaincpptext0x54 undefined reference to dso handlemaincpptext0x61 undefined reference to cxa atexit,['c++'] +172808,must a fluent or chainable method be immutable say i have a class with some properties and some methods for manipulating those propertiespublic class personmodel public string name get set public string primaryphonenumber get set public void loadaccountinfoaccountinfo accountinfo thisname accountinfoname public void loadphoneinfophoneinfo phoneinfo thisprimaryphonenumber phoneinfophonenumber typical usage would bevar model new personmodelmodelloadaccountinfoaccountinfomodelloadphoneinfophoneinfoi think it would be cool to make the methods chainable public personmodel loadaccountinfoaccountinfo accountinfo thisname accountinfoname return this public personmodel loadphoneinfophoneinfo phoneinfo thisprimaryphonenumber phoneinfophonenumber return this then usage would bevar model new personmodel loadaccountinfoaccountinfo loadphoneinfophoneinfobut i am not returning a modified clone of the passedin personmodel object in each of these chainable methods they are just modifying the original object and returning it for convenience to me this creates an ambiguity because someone calling these methods may assume that they are immutable ie they leave the original object intact but return a modified objectdoes that violate any sort of best practice regarding fluentchainable interfaces,['c#'] +172821,java jvm profiling thread status what does monitor status mean i use visualvm connect a multi thread java application thread has 4 status namely running sleeping wait monitor what does this monitoring status mean whats the difference between wait and monitor,['java'] +172824,poor performance of android canvasdrawbitmap switch to opengl i am porting a 2d action game from windows phone 7 developed in xna 40 over to android i am using a lot of canvasdrawbitmap calls around 200300 per frame update with different paints for each call to handle varying transparency and colourisation at drawtime this is managing particle systems and various other overlays and ingame effects as well as a tiled background and ingame sprites i am not doing any ondemand resizing or rotating it is simple srcdest rectangles of the same sizeon wp7 this runs at 30fps but i am struggling to get 12fps on my test droid hardware samsung galaxy s this is making the game unplayable having profiled the code i have confirmed that all my time is being lost in canvasdrawbitmapi seem to be following all the usual performance advice using a surfaceview mindful of gc so not creating loads of throwaway objects and avoiding drawablesam i right in understanding that canvasdrawbitmap is cpubound and if i want to improve performance i have to switch to opengl which will use the gpu i cannot find it stated that baldly anywhere but reading between the lines of some comments i think that might have to be my next step,['android'] +172850,error androidappsupernotcalledexception i am new user of android and i had make one android database connection and create table application but at run time it will generate an erroran error is hear 0715 1625404 errorandroidruntime3308 uncaught handler thread main exiting due to uncaught exception 0715 1625454 errorandroidruntime3308 androidappsupernotcalledexception activity orgexamplesqldemoorgexamplesqldemosqldemo did not call through to superondestroy 0715 1625454 errorandroidruntime3308 at androidappactivitythreadperformdestroyactivityactivitythreadjava3134 0715 1625454 errorandroidruntime3308 enter code here at androidappactivitythreadhandledestroyactivityactivitythreadjava3159 0715 1625454 errorandroidruntime3308 at androidappactivitythreadaccess2400activitythreadjava112 0715 1625454 errorandroidruntime3308 at androidappactivitythreadhhandlemessageactivitythreadjava1724 0715 1625454 errorandroidruntime3308 at androidoshandlerthispatchmessagehandlerjava99 0715 1625454 errorandroidruntime3308 at androidoslooperlooplooperjava123 0715 1625454 errorandroidruntime3308 at androidappactivitythreadmainactivitythreadjava3948 0715 1625454 errorandroidruntime3308 at javalangreflectmethodinvokenativenative method 0715 1625454 errorandroidruntime3308 at javalangreflectmethodinvokemethodjava521 0715 1625454 errorandroidruntime3308 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava782 0715 1625454 errorandroidruntime3308 at comandroidinternaloszygoteinitmainzygoteinitjava540 0715 1625454 errorandroidruntime3308 at dalviksystemnativestartmainnativemethodsqldemojava my code is hear package comdailynote import androidappactivity import androidcontentcontentvalues import androiddatabasecursor import androiddatabasesqlitesqlitedatabase import androidosbundle import androidwidgettextview public class sqldemo extends activity eventdatasqlhelper eventsdata textview output override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutoutput output textview findviewbyidridtextview1 eventsdata new eventdatasqlhelperthis addeventhello android event cursor cursor getevents showeventscursor override public void ondestroy eventsdataclose private void addeventstring title sqlitedatabase db eventsdatagetwritabledatabase contentvalues values new contentvalues valuesputeventdatasqlhelpertime systemcurrenttimemillis valuesputeventdatasqlhelpertitle title dbinserteventdatasqlhelpertable null values private cursor getevents sqlitedatabase db eventsdatagetreadabledatabase cursor cursor dbqueryeventdatasqlhelpertable null null null null null null startmanagingcursorcursor return cursor private void showeventscursor cursor stringbuilder ret new stringbuildersaved eventsnn while cursormovetonext long id cursorgetlong0 long time cursorgetlong1 string title cursorgetstring2 retappendid time title n outputsettextret eventdatasqlhelperjava package comdailynote import androidcontentcontext import androiddatabasesqlitesqlitedatabase import androiddatabasesqlitesqliteopenhelper import androidproviderbasecolumns import androidutillog helper to the database manages versions and creation public class eventdatasqlhelper extends sqliteopenhelper private static final string database name eventsdb private static final int database version 1 table name public static final string table events columns public static final string time time public static final string title title public eventdatasqlhelpercontext context supercontext database name null database version override public void oncreatesqlitedatabase db string sql create table table basecolumns id integer primary key autoincrement time integer title text not null logdeventsdata oncreate sql dbexecsqlsql override public void onupgradesqlitedatabase db int oldversion int newversion if oldversion newversion return string sql null if oldversion 1 sql alter table table add note text if oldversion 2 sql logdeventsdata onupgrade sql if sql null dbexecsqlsql,['android'] +172858,xcode 4 define a preprocessor macro in a dependent target i have an app named myapp which is linked to a static library mylibraryi have added the mylibrary project to xcode and added the mylibrary target to myapps target dependenciesall this works fine i can set breakpoints and i am pretty happythe thing is that i want a conditional log in the library ifdef debug define mydebugmsg nslogndebug nsdnsstring stringwithformatmsg va args pretty function line else define mydebugmsg endifso i have two build configuration for my library debug has debug1 in the targets build settings in preprocessor macros prod has nothingand the mylibrary target is set to build with the debug build configurationthis works fine if i build the static library a and include it in a projectbut if it is built by target dependency it seems that debug is not defined mydebug does not log anythingi have also tried to set debug1 in myapps build settings but it does not workis there something i missed or another way to do it,['objective-c'] +172887,g produces segfault with normal compilation but none with g i am learning c right now using bruce eckels thinking in c and i am in the early chapters i have got a c and java background right now i have got the following problem when i compile the sources below with g acpp bcpp bmaincpp the program outputs a 1 correctly and then a segfault when i compile withg g acpp bcpp bmaincpp the exact same program produces a 1 and no segfault i have got to say i find this astonishing could someone point out what i do wrong my os is linux 263530generic 54ubuntu x86 64 my g is version g ubuntulinaro 414ubuntu5 445edit just because this seems to be an important source of the error thanks evan teran the a constructor in the b struct never gets called i have put a cout blah endl inside and it does not print anythingedit i have included the return 0 at the end of main now but that does not help ahifndef a hdefine a hinclude stringclass a public int i stdstring str void print aendifacppinclude ahinclude iostreaminclude stringusing namespace stdvoid aprint cout str i endlaa str initstr i 0bhifndef b hdefine b hinclude ahclass b private int counterpublic a a b void increase int readendifbcppinclude bhusing namespace stdbb counter 0void bincrease counterint bread return counterbmaincppinclude iostreaminclude bhusing namespace stdint mainint argc char argv b b bincrease cout bread endl return 0edit i have installed g from the packages my ubuntu is also very standard this is what i get when i call gdb aout corewarning cannot read pathname for load map eingabeausgabefehlerreading symbols from usrliblibstdcso6no debugging symbols founddoneloaded symbols for usrliblibstdcso6reading symbols from liblibmso6reading symbols from usrlibdebugliblibm2121sodonedoneloaded symbols for liblibmso6reading symbols from liblibgcc sso1no debugging symbols founddoneloaded symbols for liblibgcc sso1reading symbols from liblibcso6reading symbols from usrlibdebugliblibc2121sodonedoneloaded symbols for liblibcso6reading symbols from lib64ldlinuxx8664so2reading symbols from usrlibdebuglibld2121sodonedoneloaded symbols for lib64ldlinuxx8664so2core was generated by aoutprogram terminated with signal 11 segmentation fault0 0x07fba1049104b in stdbasic stringchar stdchar traitschar stdallocatorchar basic string from usrliblibstdcso6edit 2 btw my hardware is not faulty as far as i know and i treat the os quite welledit 3valgrind reports the following3428 conditional jump or move depends on uninitialised values3428 at 0x4ecb022 stdbasic stringchar stdchar traitschar stdallocatorchar basic string in usrliblibstdcso60143428 by 0x400d73 aa in homexcexercisesch04aout3428 by 0x400d91 bb in homexcexercisesch04aout3428 by 0x400cd7 main in homexcexercisesch04aout3428 3428 use of uninitialised value of size 83428 at 0x4ecb04b stdbasic stringchar stdchar traitschar stdallocatorchar basic string in usrliblibstdcso60143428 by 0x400d73 aa in homexcexercisesch04aout3428 by 0x400d91 bb in homexcexercisesch04aout3428 by 0x400cd7 main in homexcexercisesch04aout3428 3428 invalid read of size 43428 at 0x4ecb04b stdbasic stringchar stdchar traitschar stdallocatorchar basic string in usrliblibstdcso60143428 by 0x400d73 aa in homexcexercisesch04aout3428 by 0x400d91 bb in homexcexercisesch04aout3428 by 0x400cd7 main in homexcexercisesch04aout3428 address 0xf8 is not stackd mallocd or recently freed3428 3428 3428 process terminating with default action of signal 11 sigsegv dumping core3428 access not within mapped region at address 0xf83428 at 0x4ecb04b stdbasic stringchar stdchar traitschar stdallocatorchar basic string in usrliblibstdcso60143428 by 0x400d73 aa in homexcexercisesch04aout3428 by 0x400d91 bb in homexcexercisesch04aout3428 by 0x400cd7 main in homexcexercisesch04aout3428 if you believe this happened as a result of a stack3428 overflow in your programs main thread unlikely but3428 possible you can try to increase the size of the3428 main thread stack using the mainstacksize flag3428 the main thread stack size used in this run was 83886083428 3428 heap summary3428 in use at exit 0 bytes in 0 blocks3428 total heap usage 0 allocs 0 frees 0 bytes allocated3428 3428 all heap blocks were freed no leaks are possible,['c++'] +172891,pass a string from one activity to another activity in android this is my stringprivate final string easypuzzle 6302080102050089109060030 008006050187060500900 090070106810020502003097i want to show this string on the another activity at the 99 sudoku board,['android'] +172901,is it a bad practice to use your appdelegate as your singleton i am sometimes using a singleton to store data that is used by several different classes in my projects and i am thinking why not use my appdeletage since it is already a singleton and easy to access is this a bad practice and if so why,"['iphone', 'objective-c']" +172951,proper usage of spring mvc 3 with hibernate spring orm i am starting a new project trying to do things right this timeso more than one question i might need some help i am not sure what i am doing wrong spring contextcontrollerservice interfaceservice implementationdao interfacedao implementationi want to utilize spring mvc as much as possible how do i make session openingclosing handled by transactionalhow do i catch the exceptionsie non existing record or database failed if any ie my database does not accept duplicate entries like this one commysqljdbcexceptionsjdbc4mysqlintegrityconstraintviolationexception duplicate entryhow can i catch thisand for every next request i make i get this exception orghibernateassertionfailure null id in comtestspringwsserviceimpltestobject entry do not flush the session after an exception occurswhat i am doing wrong can anyone suggest some improvements in my project,['java'] +172954,fuzzy string searching with whoosh in python i have built up a large database of banks in mongodb i can easily take this information and create indexes with it in whoosh for example i would like to be able to match the bank names eagle bank trust co of missouri and eagle bank and trust company of missouri the following code works with simple fuzzy such but cannot achieve a match on the abovefrom whooshindex import create infrom whooshfields import schema schemanametextstoredtrueix create inindexdir schemawriter ixwritertest items ueagle bank and trust company of missouriwriteradd documentnameitemwritercommitfrom whooshqparser import queryparserfrom whooshquery import fuzzytermwith ixsearcher as s qp queryparsername schemaixschema termclassfuzzyterm q qpparseueagle bank trust co of missouri results ssearchq print resultsgives me top 0 results for andfuzzytermname ueagle boost10 minsimilarity050 prefixlength1 fuzzytermname ubank boost10 minsimilarity050 prefixlength1 fuzzytermname utrust boost10 minsimilarity050 prefixlength1 fuzzytermname uco boost10 minsimilarity050 prefixlength1 fuzzytermname umissouri boost10 minsimilarity050 prefixlength1 runtime0166392326355is it possible to achieve what i want with whoosh if not what other python based solutions do i have,['python'] +172967,copying text to the clipboard using java i want to copy text from a jtables cell to the clipboard making it available to be pasted into other programs such as microsoft word i have the text from the jtable but i am unsure how to copy it to the clipboard,['java'] +172976,how do i create a play framework web project with maven is there a maven archetype out there to create a play framework java web applicationthanks,['java'] +172982,c what is the difference between byte and char what is the difference between byte and chardifferentiate more from usage perspective can they be used interchangeably,['c#'] +172998,how can i show a blank option in jquery autocomplete i am using a jquery autocomplete with combobox nabled i want to show an empty option however whenever i set the value of my initial selection to an empty string it is not shown in the combobox the item is present it just contains no height is it possible to have a blank option on an autocomplete combobox,['jquery'] +173011,eclipse google plugin does not start server for web application i want to try the google eclipse plugin for the google app engine but i get stuck in the tutoriali want to start the web application from the google tutorial but when i click on run as web application i only see this message on the consoleusage devappserver options war directoryoptions help h show this help message and exit serverserver the server to use to determine the latest s server sdk version addressaddress the address of the interface on the local machine a address to bind to or 0 for all interfaces portport the port number to bind to on the local machine p port sdk rootroot overrides where the sdk is located thisable update check thisable the check for newer sdk versionswhats the problem it seems like the command to start the server is wrong but i have not edited it can someone help,['java'] +173031,how to debug android application in phone sleep mode without usb connection that is tricky one i guess phone behaves differently when connected with usb for debugging and when unplugged difference is in the sleep mode with usb connection phone seems to be more active and responsive without less for example i have an alarm to wake up the phone and adjust volume while connected works perfectly fine in sleep adjusts volume on every alarm trigger every 10 seconds while not connected works rarely adjusts volume only on random alarm trigger let us say between 20 and 50 secondshow could i debug the phone while unplugged how could i force the phone to behave exactly the same with usb connection and without partial wake lock the one without screen on does not help this is strange and it makes the developing really painful,['android'] +173041,c convert integer to string at compile time i want to do something like thistemplateint nchar foo return a compiletime string containing n equivalent to doing ostringstream ostr ostr n return ostrstrc strit seems like the boost mpl library might allow this but i could not really figure out how to use it to accomplish this is this possible,['c++'] +173053,android how to hide folder from appearing in the gallery i have an application that creates a folder in the sdcard after that i do several operations which may result in storing different media files graphics in my folder the problem is that this folder is then visible in the gallery section which is not appropriate how can i hide the folder or the contents of my folder from appearing in the gallerylooking forward for a responsethanks,['android'] +173058,how can a service listen for touch gesturesevents i am wondering how apps like swipepad and wave launcher are able to detect touch gesturesevents simply through a service these apps are able to detect a touch gestures even though it is not in their own activity i have looked all over the internet and have not found how they can do that my main question is how a service can listen in on touch guesturesevents just as a regular activity may receive motionevents even though it may not be in the original activity or context i am essentially trying a build an app that will recongize a particular touch gesture from a user regardless which activity is on top and do something when that gesture is recongized the touch recongition will be a thread running in the background as a service,['android'] +173061,how do i safely eval user code in a webpage i am working on a webapp to teach programming concepts webpages have some text about a programming concept then let the user type in javascript code into a text editor window to try to answer a programming problem when the user clicks submit i analyse the text they have typed to see if they have solved the problem for example i ask them to write a function named f that adds three to its argumentheres what i am doing to analyse the users textrun jslint on the text with strict settings in particular without assuming browser or console functionsif there are any errors show the errors and stopevalusertextloop through conditions for passing the assignment evalcondition an example condition is f14 conditions come from trusted sourceshow passingfailing conditionsmy questions is this good enough to prevent security problems what else can i do to be paranoid is there a better way to do what i wantin case it is relevant my application is on google app engine with python backend uses jquery has individual user accounts,['javascript'] +173095,jquery select the next item of this in each function i want to select the next element of this in each function check out the code commentsfunction var selects bodyfindspan selectseachfunctionindexel ifindex0 remove the next span of this which is span2 body div span1span div span2span div span3span div body,['jquery'] +173144,iphone replacing rootview in navigation controller i have a project with a navigationcontroller that contains into ib the first viewcontroller to show that is just the default pattern when creating the projectin that first viewcontroller i receive some event that i send to the appdelegate and i want it to replace that rootview with another one not going to a next oneso i do boolapplicationuiapplication application didfinishlaunchingwithoptionsnsdictionary launchoptions override point for customization after application launch add the navigation controllers view to the window and thisplay selfwindowrootviewcontroller selfnavigationcontroller selfwindow makekeyandvisible return yes void gonext selfnavigationcontroller popviewcontrolleranimatedno nextviewcontroller nextwindow nextviewcontroller alloc initwithnibnamenextview bundlenil autorelease selfnavigationcontroller pushviewcontrollernextwindow animatednobut that does not work the first viewcontroller is not popedand the second one is logically thisplayed with a back buttoni just want to replace that first view with the other one as the start of the navigation process,['iphone'] +173155,cwin32 a professional looking application is it really possible i have been looking everywhere to find a good solution tip on how to release an application that has todays topend lookas we all know when coding with windows we normally get windowsstyle colorsbuttonslists etc they just look and feel uglywhen we decide we want to sell an application people want it to look good obviously because they have paid for itso the question ishow is the good application look achieved today owner drawing really customcontrols some good nonfree libraries that do the dirty work and skin your applicationi do not believe programmers do those overdrawn tips and tricks it takes so long to have one control completely done besides i would rather spend that time coding the internal application stuff than playing around with percontrol drawingi have no clue but have a deadline and now after going through all those ownerdrawed controls on google i came up that this is not the thing there has to be something else that comes handy when a programmer needs to make his application look topendplease help any tools any tips anyanything few examples how do they achieve that look openfmjpg,['c++'] +173163,how can i remove a click event from an element in javascript i have a div element that has a click event attached to it using the following codevar id someidvar elem documentgetelementbyidelemidelemaddeventlistenerclick function somefunctionid falseat a later point i copy the element and add it to another part of the dom but need to first remove the click eventvar elem documentgetelementbyidelemidelemremoveeventlistenerclick falsei am not sure how to reference the listener and so far nothing i have tried has removed the event from the element any ideascheersstewart,['javascript'] +173172,initializing variable i do not know their type java class pairuvu firstv secondpublic pair first new u error second new v error public pairu fv s first f second srequired classfound type parameteris it possible to initialize firstsecond with withoutarguments constructor of uv type other way,['java'] +173190,whats the difference between serverphp self and serverscript name i have a php framework and i used serverscript name to optimize portability that way i do not need to manually configure the path anymorethisbase url str replaceindexphp http serverserver name serverscript namebut i noticed that serverscript name and serverphp self returns the exact same string so whats the difference how should i choose between them,['php'] +173203,how to escape a while loop in c i am trying to escape a while loop basically if the if condition is met i would like to be able to exit this loopprivate void checklog while true threadsleep50 if systemiofileexistscommandbat continue using systemiostreamreader sr systemiofileopentextcommandbat string s while s srreadline null if scontainsmp4productioncatchup removeexelog process p new process pstartinfoworkingdirectory dump pstartinfofilename testexe pstartinfoarguments s pstart escape here if the if condition is met escape the loop here,"['c#', '.net']" +173216,foreign key constraints when to use on update and on delete i am designing my database schema using mysql workbench which is pretty cool because you can do diagrams and it converts them panyways i have decided to use innodb because of it is foreign key support one thing i noticed though is that it allows you to set on update and on delete options for foreign keys can someone explain where restrict cascade and set null could be used in a simple examplefor example say i have a user table which includes a userid and say i have a message table message which is a manytomany which has 2 foreign keys which reference the same primary key userid in the user table is setting the on update and on delete options any useful in this case if so which one do i choose if this is not a good example could you please come up with a good example to illustrate how these could be usefulthanks,"['mysql', 'sql']" +173226,how to set selected in select tagoptions from collection for select i have been searching stackoverflow for almost 2 hours now going through similar questions but the answers just do not seem to worki have the following code select tag name dropdown options from collection for selectmodels friendly id name i would like to thisplay the option i have chosen previously as selected instead of going to the first tag by defaultin the other questions they have suggested to add the following none of them work select tag name dropdown options from collection for selectmodels friendly id name 1 or select tag name dropdown options from collection for selectmodels friendly id name modelsfirstid ps i am using rails 31rc4,['ruby-on-rails'] +173242,how to configure teamcity with private files i am setting up teamcity for continuous integration and hopefully continuous deployment some of the build steps will involve private files egsnk files for strong naming net assembliespasswordtoken files for publishing artifacts for example to nuget or codeplexsince these files contain private data i do not want to put them into the publicly accessible source control systemi am setting up for autofixture so i do not have physical access to the server i was hoping for a feature that would let me upload such files but cannot find anything of the kindwhat would be the most appropriate solution,['.net'] +173246,wix bindassemblyfullnamefileid only works on gaced assemblies woe woe and thrice woe why does wix make installing net assemblies so difficulti am installing a com inprocess server which is implemented in net in my wix install i need to create the registry entries for it i do not want to do this i would rather wix had an equivalent of regasm but they make me do this manually i got tired of getting flamed for suggesting this was a tad arcane so i gave up and tried to do it the declarative way like a good boy so heres what my registry stuff looks like nowfile idfildriverassembly sourcevartigraastronomyawrdrivesystemtargetpath keypathyes vitalyes assemblynet class contextinprocserver32 descriptionvarinstallname id vardriverguid threadingmodel both progid descriptionvarinstallname id vardriverid classfileregistrykey roothkcr keyvardriverid actioncreateandremoveonuninstall registryvalue typestring valuevardrivertypename registrykey keyclsid registryvalue typestring valuevardriverguid registrykey keyvardriverguid registryvalue typestring valuevardrivertypename registrykey keyinprocserver32 registryvalue typestring valuemscoreedll registryvalue typestring namethreadingmodel valueboth registryvalue typestring nameclass valuevardrivertypename registryvalue typestring nameassembly valuebindassemblyfullnamefildriverassembly registryvalue typestring nameruntimeversion value2050727 registryvalue typestring namecodebase valuefilefildriverassembly registrykey keybindfileversionfildriverassembly registryvalue typestring nameclass valuevardrivertypename registryvalue typestring nameassembly valuebindassemblyfullnamefildriverassembly registryvalue typestring nameruntimeversion value2050727 registryvalue typestring namecodebase valuefilefildriverassembly registrykey registrykey registrykey keyprogid registryvalue typestring valuevardriverid registrykey registrykey keyimplemented categories registrykey key62c8fe654ebb45e7b4406e39b2cdbf29 registrykey registrykey registrykeyregistrykey wow6432node for x86 compatibility installed only on x64 systems hkey local machinesoftwareclasseswow6432node if varwin64 yes registrykey roothkcr keywow6432node actioncreateandremoveonuninstall registrykey keyclsid registryvalue typestring valuevardriverguid registrykey keyvardriverguid registryvalue typestring valuevardrivertypename registrykey keyinprocserver32 registryvalue typestring valuemscoreedll registryvalue typestring namethreadingmodel valueboth registryvalue typestring nameclass valuevardrivertypename registryvalue typestring nameassembly valuebindassemblyfullnamefildriverassembly registryvalue typestring nameruntimeversion value2050727 registryvalue typestring namecodebase valuefilefildriverassembly registrykey keybindassemblyversionfildriverassembly registryvalue typestring nameclass valuevardrivertypename registryvalue typestring nameassembly valuebindassemblyfullnamefildriverassembly registryvalue typestring nameruntimeversion value2050727 registryvalue typestring namecodebase valuefilefildriverassembly registrykey registrykey registrykey keyprogid registryvalue typestring valuevardriverid registrykey registrykey keyimplemented categories registrykey key62c8fe654ebb45e7b4406e39b2cdbf29 registrykey registrykey registrykeyregistrykeyendif regasm is for wimps eh anyway notice that i need to get the assembly full name to create some of the registry keys i am using binder variables specifically valuebindassemblyfullnamefildriverassemblythis however does not work unless i add the attribute assemblynet to the file entry if i do not add that attribute or if i use assemblyno then i geterror 2 unresolved bindtime variable bindassemblyfullnamefildriverassemblywhen i add assemblynet to the file item then the binder variables work just fine but wix puts my assembly into the global assembly cache which is not what i want oh manis it not possible to query an assemblys full name in a wix project if its not going into the gac why do these two things depend on each other,['.net'] +173274,or die in python is anyone using anything like this in pythondef dieerror message raise exceptionerror messagecheck something or dieincorrect datai think this kind of style is used in php and perldo you find any thisadvantages in this style,['python'] +173282,tfs2010 how to change build definition build priority i want to change the default priority of a build definition the build is triggered each checkinshow do i do that,['c#'] +173285,how to check if the user is already created in the database or not in sql is there is a way that from it i can know if the usernot the login is already created in the database i mean the user not the login since i know how to check for the login i need to check for the user that is created inside a specific db a role assigned to itthis is the code for checking for the loginselect name from sysserver principals where name test userbut how about the user since i need to create the user and assign a role to it if its not created otherwise i will continue without creatingthanks,['sql'] +173322,finding the number of keys in an object possible duplicatehow to efficiently count the number of keysproperties of an object in javascript var values spo2 20 vitalgroupid 1152 temperature 367 datetimetaken date13014943350400 userid 1 height 18288 username null bloodpressurediastolic 80 weight 100909090909091 temperaturemethod oral resprate null heartrate 1 bloodpressureposition standing vitalsite popliteal vitalid 1135 laterality right heartrateregularity regular headcircumference bloodpressuresystolic 120 cuffsize xlfor i0 i valueslength i alertvalueslength gives me 2 how can find how many keys my object has,['javascript'] +173329,publishing nonthread safe object fields in a threadsafe manner i have got a problem with java concurrency yes i looked at questions with almost the exact same title but they all seemed to be asking subtly different things yes i have read java concurrency in practice yes i can see why it is the defacto reference for the topic yes i have read the section specifically on publishing fields in threadsafe classes yes i am still going to ask a concurrency question on java regardless of the fact that i know someone will simply point me to that bookthis has me stumped though i know that you can easily publish mutable primitive fields in a threadsafe manner by ensuring correct readwrite orders with volatility andor synchronized access and that the 64bit primitives needs to have atomic access due to the lack of atomicity in its readwrite operations i know about using locks on chunks of code that need to execute on a specific snapshot of the clas fields i am fully aware of the atomic package with goodies like atomiclong etcbut i am still confused with regards to publishing nonthreadsafe objects as fields in a threadsafe classfrom what i can see as soon as you return the reference to it in the getter youve given unprecedented access to the objects contents to the caller which they can use at any point also if you give a setter youre allowing them to set the object reference to an object they can potentially control outside the object they are using the setter fori cannot work out anyway of composing a threadsafe class out of nonthreadsafe objects without making them all privateprotected and creating threadsafe wrapper methods in the class for all the methods all the nonthread safe objects have that the user of the class may want to use and this just sounds like a boilerplate nightmarei mean if you return an atomicreference to the object in a getter they can just use get to get nonsynchronized access to it againanother way i considered was to have all the getters return new copies of the nonthreadsafe object based on the old one meaning that modifications would be irrelevant with the same applying to setters but java has a hopelessly complicated system for cloning objects shallowcopy vs deepcopy vs specificcopying etc which kinda puts me off doing that also this is so inefficient that it wouldnt be any faster than using a language that is designed for immutability like clojure in fact it would probably be far slower given that such languages allow multiple pieces of immutable data to share the same data behind the scenesso how do i compose thread safe classes of published nonthread safe objects in a viable mannerthanks in advance,['java'] +173338,whats the convention on placing curly braces in objectivec i have seen different conventions for objectivec cocoacocoa touch of placing the curly bracesthe two that i have seen are voiddealloc super deallocvs void dealloc super deallocthis confuses me because i would expect that for such a rather small community there should be only one conventionwhich one of the two is more common,['objective-c'] +173340,how to convert timespan to pm or am time i am storing user time in utc time and when i show it i need to convert it to am pm timehere is example in database i have 170 convert to 500 pmhere is the code what i came up so far but it is not workingvar time datetimeparseexactobjecttimetostring hhmm cultureinfocurrentculturetostringhhmm tt,"['c#', 'asp.net']" +173347,converting a date format in objective c how can i convert the following date sun jul 17 074834 0 2011to the following format 20110717 074834i used nsdateformatter as shown below but it didnt work it gives null as a resultnsdateformatter objdateformatter nsdateformatter alloc initobjdateformatter setdateformatymmdd hhmmssobjdateformatter datefromstringsdate,"['iphone', 'objective-c', 'ios']" +173367,how can i truncate my strings with a if they are too long possible duplicateindicate truncation in tooltipstatuslabel automatically hope somebody has a good idea i have strings like thisabcdefgabcdeabcwhat i need is for them to be trucated to show like this if more than a specified lenghtabc abc abcis there any simple c code i can use for this,['c#'] +173370,linq serialization somewhere i wish i knew where jon skeet and marc gravel were thinking about working on a tool that translated a linq query to xml for transfer over the wire does anyone know if they or someone else has done this and made it publicscenario thistributed cross assembly this is a nice to have feature for me at this stagemaybe this is not possible yet,"['c#', '.net']" +173399,locationhost vs locationhostname and crossbrowser compatibility which one of these is the most effective vs checking if the user agent is accessing via the correct domainwe would like to show a small js based top bar style warning if they are accessing the domain using some sort of web proxy as it tends to break the jswe were thinking about using the followingvar r domaincomif rtestlocationhostname showmessage that would take care of any subdomains we ever usewhich should we use host or hostnamein firefox 5 and chrome 12consoleloglocationhostconsoleloglocationhostname shows the same for bothis that because the port is not actually in the address barw3schools says host contains the portshould locationhosthostname be validated or can we be pretty certain in ie6 and all the others it will exist,"['javascript', 'html']" +173418,is there a way to exit only the php file being included so i have a sidebarphp that is included in the indexphp under a certain condition i want sidebarphp to stop running so i thought of putting exit in sidebarphp but that actually exits all the code beneath it meaning everything beneath includesidebarphp in indexphp all the code would be skipped as well is there a way to have exit only skip the code in the sidebarphp,['php'] +173426,old images show after replacing with new ones in ios app i am dealing with this really really annoying bug in xcode where it seems to save images to some type of memory that seems impossible to cleari have replaced a bunch of images in which i am creating a clock animation however when i try to play the animation it showes all the old images i have tried cleaning the app and still they continue to show even though i have deleted the images so then i tried changing the name of the images along with the code where they were getting called and now i am getting a bunch more errors so i am just woundering if anyone knows how to get around this problem of xcode caching images,['iphone'] +173437,using chrome javascript debugger how to break on page loading events i am using chromes debugger and i am good when it comes to setting break points once a page is running my problem is when i do either f5 or press enter on the url line my break points thisappear how can i set a break point in code that happens when the page first loads,['javascript'] +173464,java documentation on terminal i find myself most often to be on terminal instead of on browser for jdk that i downloaded and in ide eclipsenetbeans the doc usually flips automatically as i type java code hence accessing documentation from terminal is the one and only most convenient way for me i have been searching many so threads archives related to accessing java documentation from terminal but what i found were always for browser or ide environmentis it possible to get java documentation from terminal ex how can i get mathmax documentation on terminal helpin perl i usually do perldoc f thefuncin ruby i usually do ri t thefunc on terminal this usually guides me to any related classesenumerations of the method i am interested in still at the same place terminal without a need to browsesearch at any other separated locations be it browser searchable chm doc or pdf or any other places except the same terminal session if i find there are more than one method that belong to a classenum from ri t max then i type again the complete ri t enumerablemax to get the exact documentation i need i do have to enter rtfm twice but i am still on my terminali use java version 150 28javatm 2 runtime environment standard edition build 150 28b043829m3326java hotspottm client vm build 150 28157 mixed mode sharingmac os x 1058but i downloaded the latest jdk java platform se 6 from oracle site several weeks agothanks for the enlightenment,['java'] +173469,xcode error launching remote program i have seen this all over the place on stack overflow but everyone elses solution does not work for me help pleasei am trying to test my app on my iphone it is run perfectly fine up until i updated xcode and the ios i have also been on v4 though i cannot get it to sync the app over at all i have tried dumping this filefolder dumping caches quitting relaunching xcode rebooting the computer restarting the phone everything i can think of to no avail any ideaserror launching remote program no such file or directoryusersandrewlibrarydeveloperxcodederiveddatabtc exchangedrzeigaqfnjtatglpiwxmscsojbuildproductsdebugiphoneosbtc exchangeappbtc exchangeand the file does exist there are no permissions issues from what i can tell and i ran a whole thisk permissions check too,['iphone'] +173488,pdf viewer apilibrary for android app i want to know is there any api or library for pdf in androidso that we can read any pdf stored on sd cardi have gone through all other questions and their answers but i did not get any satisfied answer please suggest me any proper api or sample code for thisthank you in advance,['android'] +173512,replace only first match using preg replace i have a string with structure similar to aba a cba sbd dga gad a cbz the string can be a bit different each time as it is from an external sourcei would like to replace only first occurrence of a but not the others is it possible,['php'] +173521,which yii user managment modules which module is better has anybody tested either of these modules beforeyiiusermanagementyiiuseryiirightsi tried to install yiiusermanagement but i get lots of errors,['php'] +173524,sparse matrix libraries for ruby i am looking for a sparse matrix library i can use from ruby i am currently using the gnu scientific library bindings provided by the gsl gem but my application would be better optimized if i used a dedicated sparse matrix library i have investigated the linalg and narray libraries none of the these three libraries support sparsematrix optimised storage or operationsis there anything out there i have missed or an existing c library that may be possible to write bindings for i would prefer the former to that latter as i have not written c bindings in ruby before but i would be willing to attempt it,['ruby'] +173528,format price in the current locale and currency i use productgetpriceto get the unformatted price that i can calculate quantity x price with ajax i want to reformat the total in the current locale and currency how can i do that,['php'] +173529,how export jars from library project to referencing projects in eclipse several android projects use a android library project now i added a jar commonslangjar to this library project i want to export this commonslangjar to all projects that use the library project i cannot get it to work without duplicating the jar to all referencing projectswhat i did so farcreated a folder named libs within the library projects folder hierarchycopied the jar to this libs folderadded this jar in the eclipse java build path with add external jars to the library projecton the order and export tab selected the checkbox to the left of the jar to export iton the referencing project on the android page add library projectit seems that the commanslang jar is not exported with the library project i need to create the libs folder on the referencing project as well add the same jars to the build path of the referencing project after that everything works but the apk does contain that external jar twicewhats wrong with my approach what should i do in additionmany thanks in advance,"['java', 'android']" +173536,publishing my first android application in android market i want publish my app in the android market how much time does it take to make an android developer account verified by google also what other things i should do,['android'] +173538,why is nonblocking socket connect so slow when i do 100 nonblock socket connection in 1 threadit is very slowthe number of connection increased one by onebut if i do a blocking socket connection in 100 parallel threadsone connect per thread it is very fastget done immediately sock socketaf inet sock stream ipproto tcpif fcntlsock f setflo nonblock0 perrorfcntl nonblock return 1if setsockoptsock sol socket so reuseaddrreuseaddr sizeofreuseaddr0 perrorreuse addr return 1saddrsin addrs addr inet addrsrv addrsaddrsin port htons1972if nconnectsock const struct sockaddr saddr sizeofsaddr 0 if errno einprogress perrorclient connect error return 1 else if n0 printfd connectednsockreturn sock,['c'] +173543,how to read several resource files with the same name from different jars if there are two jar files in the classpath both containing a resource named configproperties in its root is there a way to retrieve both files similar to getclassgetresourceasstream the order is not relevantan alternative would be to load every property file in the class path that match certain criterias if this is possible at all,['java'] +173563,link to python with mingw i want want to create a crossplattform programm that embedds the python interpreter and compile it with mingw but the python binary thistribution provides no libraries for mingw to link with only python32lib for visual c and the python source package provides no support for compiling with mingwi tried linking to python32lib in mingw with lpython32 but it still generates errors likemaincpp undefined reference to imp py initializemaincpp undefined reference to imp py finalizehow do i link python in mingw i really do not want to switch to using visual c,['python'] +173608,cocoa integrate nsapplication into an existing c mainloop i know that i am not the first one to try to use cocoa on osx together with an existing cc main loop but i am not really liking the solutions i came across so far so i came up with a different idea i would like to thiscuss the most common way i found in glut glfw sdl and also qt i think is to use polling to replace nsapplications run method and process the events yourself with this nexteventmatchingmaskuntildateinmodedequeuethis has the big thisadvantage that the cpu is never really idle since you have to poll the whole time to check if there are any new events furthermore its not the only thing going on inside nsapplications run function so it might break some details if you use this replacementso what i would like to do is to keep the cocoa runloop intact imagine youd have your own timer methods implemented in c which would usually be managed and fired inside your main loop this is just a small part as an example my idea would be to move all my looping portions to a secondary thread since nsapplication run needs to be called from the main thread as far as i know and then post custom events to my derived version of nsapplication that handles them appropriately inside its sendevent method for instance if my timers measured in my c loop fire i would post a custom event to nsapplication that in turn runs loopfunc function of my application residing in the mainthread as well which appropriately sends the events down my c event chain so first of all do you think this would be a good solutionif yes how would you implement that in cocoa i only found this method inside the nsevent reference to post custom nsapplicationdefined eventsothereventwithtypelocationmodifierflagstimestampwindownumbercontextsubtypedata1data2and then use something likensapp posteventatstartto notify nsapplicationi would rather post an event without any information about the window in othereventwithtype can i simply ignore that partthen i would imagine to overwrite nsapplications sendevent function similar to this voidsendeventnsevent event this is my custom event that simply tells nsapplication that my app needs an update if event type nsapplicationdefined mycppaptrloopfunc only iterates once transform cocoa events into my own input events else if event type nsleftmousedown mycppaptrloopfunc also run the loopfunc to propagate input events dont break the cocoa event chain super sendeventeventsorry for the long post but this has been bothering me quite a bit since i am really not happy with what i found about this subject so far is this how i would post and check for a custom event inside nsapplication and do you think this is a valid approach to integrate cocoa into an existing runloop without polling,['c++'] +173611,how do i give write permission to file in linux how can i programmatically give write permission on a file to a particular user in linux like for example its owner everyone has read access to this file,['c'] +173613,resolveurl not working inline i am getting the error on the below code in aspnet 40script typetextjavascript srcresolveurlscriptsjquery141jsscripterror message cs1525 invalid expression term i am using this code in sitemaster in head tag,['asp.net'] +173642,difference between web server and application server as a layman how do i understand the difference between web server and application server if you could give an example using a java based web app in very simple terms that would be really great also when we say weblogic is it a web server only,['java'] +173648,google adsense and adblock i have google adsense ads on my site and adblock blocks them which is fine when they are blocked i would like to thisplay alternate content the problem is that when the ads are blocked there are two things that can happen 1 the ad is complete suppressed by adblock the height and width of the adsense ad are 0 and most of the adsense code is not generated 2 the adsense ad content is blocked but the height and width are set and the adsense code is generatedoption 1 is perfect because it allows me to check the height of the container or for tags that adsense renders and show my alternate content if the height is 0 or if a specific adsense tag does not exist however when option 2 occurs i do not know what i can do to thisplay my alternate content and the adsense ads take up their required height and width but do not thisplay any content making my site look brokenhas anyone else had any experience with this issue my site is in net 40 and i have only tested adblock in chrome v12 so far,"['jquery', '.net']" +173663,is there a way to run mysql inmemory for junit test cases i am just trying to add test cases for services accessing a mysql db and i would like to recreate the whole schema and for some scenarios also just use a mysql dump file with the data needed for each test case i was looking around and found some guys using sqlite h2 and others to do this but i am just wandering if there is any way to run mysql inmemory so i do not need to worry about anything specific to the the mysql dialect i might be using on our services,"['java', 'mysql']" +173684,access modal view controller parent i am presenting a viewcontroller modallyhow can i access the parent view controller my architecture is tabbarcontrollervc1vc2vc3mvc1 and i want to reach vc3 from mvc1in vc3 i have this code void editad askpasswordviewcontroller modalviewcontroller askpasswordviewcontroller alloc initwithnibnameaskpasswordview bundlenil nslogmodalparent class modalviewcontroller parentviewcontroller class self presentmodalviewcontrollermodalviewcontroller animatedyes modalviewcontroller releasei tried this in mvc1 void sendrequest nslogclasse self parentviewcontroller class but it returns my tabbarviewcontroller,"['iphone', 'ios']" +173687,what are jquery hooks and callbacks i am having a tough time conceptualizing what exactly callbacks or hooks are in jquery they seem to be lumped together but i do not know the difference between themfrom what i understand from other posts about callbacks like this a callback is simply a function a that you pass to another function b that calls a once b is done that may be totally wrong correct me if soi really do not have any notion on hooks other than the statement you should use a hookcallback something makes me doubt they are that similar,['jquery'] +173695,get pixel color from canvas on mouseover is it possible to get the rgb value pixel under the mouse is there a complete example of this heres what i have so farscriptfunction draw var ctx documentgetelementbyidcanvasgetcontext2d var img new image imgsrc your url imgonload function ctxdrawimageimg00 canvasonmousemove functione var mousex mousey ifeoffsetx mousex eoffsetx mousey eoffsety else ifelayerx mousex elayerx mousey elayery var c ctxgetimagedatamousex mousey 1 1data ttipcssleftmousex20 topmousey20htmlc0c1c2 script,['javascript'] +173708,how to fire mouse wheel event in firefox with javascript i am trying to do automated testing with webdriver but it currently has no ability to simulate mouse wheel events as a workaround i am trying to fire these events with javascript instead i am doing all my wheel experimenting on a straight html page right now not within the webdriver frameworki am specifically trying to fire a mouse wheel event on a scrolling div elementso far i have been able to do this with chrome and ie9 but i cannot seem to get anything to work in firefox 5xi am using the following crossbrowser code to detect when mouse wheel events are fired which i snagged off the net this code is able to pick up the event in all browsers when i scroll the mouse wheel within the scrolling div i have created idviewscript typetextjavascript function wheelevent var delta 0 if event event viewevent if eventwheeldelta delta eventwheeldelta 120 else if eventdetail delta eventdetail 3 alertdelta var view documentgetelementbyidview if viewaddeventlistener viewaddeventlistenerdommousescroll wheel false viewonmousewheel wheelscriptthe function below when called is able fire the mouse wheel event in chrome and ie9 and gets picked up in the above handler with expected behaviorfunction chromewheel var evt documentcreateeventmouseevents evtiniteventmousewheel true true evtwheeldelta 120 viewthispatcheventevtof course it does not work for firefox i have found existing documentation to be too sparse and confusing to know how ff handles this can anyone show me the bare minimum to fire a mouse wheel event in firefox with a wheel delta placed where ff expects it such that my handler will pick it up,['javascript'] +173727,are php global constants a good modern development practice i am working on a new project with a sizeable php codebase the application uses quite a few php constants definefoo bar particularly for things like database connection parameters these constants are all defined in a single configuration file that is require onced directly by basically every class in the applicationa few years ago this would have made perfect sense but since then i have gotten the unit testing bug and this tight coupling between classes is really bothering me these constants smell like global variables and they are referenced directly throughout the application codeis this still a good idea would it be reasonable to copy these values into an object and use this object ie a bean there i said it to convey them via dependency injection to the the classes that interact with the database am i defeating any of the benefits of php constants say speed or something by doing thisanother approach i am considering would be be to create a separate configuration php script for testing i will still need to figure a way to get the classes under test to use the sandbox configuration script instead of the global configuration script this still feels brittle but it might require less outright modification to the entire application,['php'] +173733,fast check for nan in numpy i am looking for the fastest way to check for the occurrence of nan npnan in a numpy array x npisnanx is out of the question since it builds a boolean array of shape xshape which is potentially gigantici tried npnan in x but that seems not to work because npnan npnan is there a fast and memoryefficient way to do this at allto those who would ask how gigantic i cannot tell this is input validation for library code,['python'] +173739,jquery ui dialog turn off draggable for dialog content i am having a brain fart and cannot seem to get the content of my jquery ui dialog to stop being draggable i turned off the draggable setting on the actual dialog popup however the content inside the box is still able to be dragged out of the boxs view i would like to have a static positioned box and static positioned content within the boxhere is my codelinkbtnclickfunction e epreventdefault var offerid thisattridsubstring8 hiddenlinks offeridshow newdialogofferid function newdialogofferid var divobj hiddenlinks offerid var dialog divobj draggable dialog draggable false autoopen false resizable false modal false title hiddenlinks offeridattrtitle draggablefalse dialogdialogopen return false thanks,['jquery'] +173767,call javascript object method with a variable i am new to object oriented javascript i have a variable whose value i would like to use to call an objects method like thisvar foo bar function barr function now there is a variable whose value can be any of the two methods names bar and barri want to call them with something likevar myvar barfoomyvar,['javascript'] +173800,how to set focus on input field using jquery given the following html structurediv classwrapper div classtop a href classlinkclick herea div div classmiddle some text div div classbottom form input typetext classpost input typesubmit form divdivwhich will be repeated several times on the page how do i set the focus on the input field in the bottom div when a user clicks on the link in the top divi am currently making the bottom div appear successfully on click using the jquery code below but cannot seem to figure out how to set focus on the input field at the same timelinkclickfunction thisparentsiblingsdivbottomshowthanks,"['jquery', 'html']" +173814,css argument for if first child is i need a css selector for inside a div but i want it to only select the element if its the first element of a specific class inside that div css3 of course thank you,['css'] +173838,call c functions from haskell at runtime i am building an interpreter for a dynamic programming language in haskell i would like to add a simple mechanism to call c functions in the past i have used the haskell ffi to call c functions that i had explicitly declared the name and type of this approach would not work here because the interpreter would not know the name or type of the c functions to be called until runtimeis it possible to declare and call c functions at runtime where should i begin,['c'] +173879,confused by javascripts constructor and prototype function myobjectarrayprototypemyobjectprototypevar anew arrayvar bnew myobjectalertaconstructorarraytruealertbconstructormyobjectfalse,['javascript'] +173900,how to open or launch pdf files in cnet how do i launch a pdf programmatically from a c application in it is own processoriginally i want to open pdf file when i click button in cnet,"['c#', '.net']" +173902,malloc function dynamic memory allocation resulting in an error when it is used globally includestdiohincludestringhchar yychar malloc40 gives an error hereint main strcpyyhello worlderror conflicting types for yerror previous declaration of y was herewarning initialization makes integer from pointer without a casterror initializer element is not constantwarning data definition has no type or storage classwarning passing arg 1 of strcpy makes pointer from integer without castnow the real question is cannot we make the dynamic memory allocation globally why does it show an error when i use malloc globally and the code works with no error if i put malloc statement inside the main function or some other function why is this soincludestdiohincludestringhchar yint main ychar malloc40 strcpyyhello world,['c'] +173927,how to find the backgroundposition backgroundimage etc for multiple backgrounds using jquery in safari maybe i am missing something herei am trying to get the current background info for an element div with multiple backgrounds set using the longhand backgroundrepeat backgroundposition and backgroundimageusing jquery i simply do var bpos elementcssbackgroundposition to get the set of current positions which will give me something like 0 0 100px 100px left bottom in firefox and chromium currently versions 5 and 12 respectively but in safari version 5 on osx it just returns the first value pair 0 0 these css values are set in an external stylesheetdoes anyone have any idea as to why this is and how to go about it to get the full set of value pairs in safari using the shorthand background property does not do it eitheredithere is the css that is used in an external style sheetpage backgroundrepeat repeatx repeatx repeatx repeatx repeatx backgroundimage urlimageslinepng urlimageslinepng urlimageslinepng urlimageslinepng urlimageslinepng backgroundposition 0 798px 0 653px 0 125px 0 88px 0 78pxeditok i made a test case for this on jsfiddle and have reported it as a jquery bug since it seems to be reproducible behaviour although i accept that it might be a browser implementation problem rather than actually a jquery bugstill if anyone has any ideaseditthe jquery ticket has been closed i take this to mean that it is a safari bug i am not quite sure how to go further from here but i have posted a bug report with appleeditas pointed out by sindre sorhus this appears to have been corrected in safari 51,"['jquery', 'css']" +173954,how to optimize a simple numeric type wrapper class in c i am trying to implement a fixedpoint class in c but i face problems with performance i have reduced the problem to a simple wrapper of the float type and it is still slow my question is why is the compiler unable optimize it fullythe float version is 50 faster than float whyi use visual c 2008 all possible compilers options tested release configuration of coursesee the code belowinclude cstdioinclude cstdlibinclude clockh just for measuring timedefine real float option 1define real float option 2struct floatprivate float valuepublic floatfloat value valuevalue operator float return value float operatorconst float rhs value rhsvalue return this float operator const float rhs const return float value rhsvalue float operator const float rhs const return float value rhsvalue float operator const float rhs const return float value rhsvalue bool operator const float rhs const return value rhsvalue struct point point x0 y0 pointreal x real y xx yy real x real yint main generate data const int and 30 point pointsn for int i 0 i n i pointsix real6400f rand rand max pointsiy real6400f rand rand max real limit 20 20 check how many pairs of points are closer than 20 clock clk int count 0 for int i 0 i n i for int j i 1 j n j real dx pointsix pointsjx real dy pointsiy pointsjy real d2 dx dx dy dy if d2 limit count double time clktime printfdn count printftime lfn time return 0,['c++'] +173964,how do you make a view fill the space available to it i know it must be an easy question i just do not know how to fix itso just an example xml version10 encodingutf8linearlayout xmlnsandroid androidlayout heightmatch parent androidlayout widthmatch parent androidorientationvertical button androidididfakebutton androidlayout heightmatch parent androidlayout widthmatch parent button androidididsavesearch androidlayout widthwrap content androidlayout heightwrap content androidtextstringsavesearchlinearlayoutthis wouldnt work the first button would make the 2nd invisible weights would make it all a percentage game which is not what i wantam i being thickedit i did not know it but it seems the order is important from answers loading a layout is iterative rather than holistic you can make the first element a fixed height and the rest of the elements will fill whats left but what i need is to make the final element a fixed height,['android'] +173970,what are symbols and how do we use them i do not understand what a symbol table is can someone help me understand symbols from the very basics and explain thoroughly,['ruby'] +173987,converting nsstring to nsdata and vice versa i am having an issue while trying to convert nsstring to nsdata and vice versai am trying to store encrypted string to my database for that i am using aes algorithm now what i am doing is i get encrypted nsdata and i am converting this to nsstring using following not wokingnsstring strtemp nsstring alloc initwithdataencdata encodingnsutf8stringencoding workingnsstring strtemp nsstring alloc initwithdataencdata encodingnsasciistringencodingwhy nsdata is not converting while using nsutf8stringencoding same way when i try to convert the string got by nsasciistringencoding using not workingstrtemp datausingencodingnsasciistringencoding workingstrtemp datausingencodingnsutf8stringencodingwhy nsasciistringencoding is not working while converting the nsstring to nsdata,['iphone'] +174035,can auto using parens mean a function prototype this question arose from being unable to use uniforminitialisation syntax with the auto keyword because it treats it as a stdinitializer listt explanation in the comments heretake the following code exampleclass x int x x function prototype 1auto x x copymove construction of an x function prototype or compiletime errorwhat does the compiler do with auto xreasoning for each possibilitycopymove construction i can see this being the proper behaviour due to 1 being seen as a kind of defectfunction prototype seems unlikely as there is no trailing return typecompiletime error if the compiler does parse this as a function prototype it may cause a compiletime error due to lacking a trailing return typewhat does the c0x standard say this should be interpreted as,['c++'] +174049,authenticate windows authentication using javascript i have to transfer my client from one website to another website this happens in client side in this 2nd website its using windows basic authentication system so it popups the login window i need to omit this popup window and authenticate my client on 2nd website using javascript and then redirect him to 2nd website there is no security issue even i put credentials in javascript file since this whole system is running in intranet so how to authenticate client on 2nd website i found this thread how can i pass windows authentication to webservice using jquerybut it does not work when i look the request header of 2nd url it does not contain the authorization tag,['javascript'] +174054,ios enterprise thistribution warning message i have an ios application that i am thistributing using the enterprise thistribution method posting the ipa file to a website when a user installs the application there is a warning message that reads are you sure you want to open the application application name from developer iphone thistribution certificate name the client is asking if there is any way to change that alert message so that it does not read iphone thistribution i am assuming that at some point in the future apple is going to change the iphone thistributiondevelopment certificate to ios but in the mean time is there anyway to change that warning message,"['iphone', 'ios']" +174085,systemdatasqlite not supporting multiple transactions so i am having an interesting issue with systemdatasqlite and using multiple transactions basically i have the following code which failsusing idbconnection connection1 new sqliteconnectionconnectionstring connection2 new sqliteconnectionconnectionstring connection1open connection2open idbtransaction transaction1 connection1begintransaction idbtransaction transaction2 connection2begintransaction fails usingidbcommand command new sqlitecommand commandtext create table artistartistid int artistname text commandcommandtype commandtypetext commandconnection connection1 commandexecutenonquery using idbcommand command new sqlitecommand commandtext create table tracktrackid int trackname text commandcommandtype commandtypetext commandconnection connection2 commandexecutenonquery transaction1commit transaction2commitfrom what i have read it seems that systemdatasqlite should support nested and by extension sequential transactions the code fails on line 7 where the second transaction is declared with the following exceptionsystemdatasqlitesqliteexception the database file is lockedsystemdatasqlitesqlite3stepsqlitestatement stmtsystemdatasqlitesqlitedatareadernextresultsystemdatasqlitesqlitedatareaderctorsqlitecommand cmd commandbehavior behavesystemdatasqlitesqlitecommandexecutereadercommandbehavior behaviorsystemdatasqlitesqlitecommandexecutenonquerysystemdatasqlitesqlitetransactionctorsqliteconnection connection boolean deferredlocksystemdatasqlitesqliteconnectionbegindbtransactionisolationlevel isolationlevelsystemdatacommondbconnectionsystemdataidbconnectionbegintransactiondoes anyone know what the issue is or how to get around this i feel having concurrent transactions is essential for any database system so there must be some way to do thisthanks,"['c#', 'sql']" +174096,how to access associations in a linq query i am having problems quering this i am new to linq please forgive me and i have spent hours trawling the web in sql i just want to do this select cforname csurname cgtitle ggroupnamefrom contact c inner join contactgroup cg on cgcontactid cid inner join group g on cggroupnameid gidwhere gid1i have attempted it but failed miserably as var result from c in contacts from cg in ccontactgroups from g in cggroup where gid1 select new cforename csurname cgtitle ggroupname can someone please show me what i am doing wrong or direct me to somewhere with further informationmuch thanks,['c#'] +174097,wicket hide comments in html jsps support the comment syntax for comments which is a way to comment markup code such that it does not get included in the emitted htmlis there a way to do this in wicket,['java'] +174112,how to do recompile with a list in python i have a list of strings in which i want to filter for strings that contains keywords i want to do something likefruit recompileapple banana peach plum pinepple kiwiso i can then use researchfruit list of strings to get only the strings containing fruits but i am not sure how to use a list with recompile any suggestions i am not set on using recompile but i think regular expressions would be a good way to do this,['python'] +174120,make the title of the actionbar clickable is it possible to make the title of the actionbar clickable i guess there is some androidridx to identify the title in onoptionsitemselected but i cannot find any,['android'] +174131,javascript how does new work internally probably the least understood part of javascript standing beside the prototype chainso the question is how doesnew dataobjargs actually create an object and define its prototype chainconstructorsetcbest is to show an alternative to fully understand this keyword,['javascript'] +174155,explicit assignment vs implicit assignment i am reading a tutorial for c but it did not actually give me a difference besides syntax between the two here is a quote from the tutorialyou can also assign values to your variables upon declaration when we assign values to a variable using the assignment operator equals sign itas called an explicit assignmentint nvalue 5 explicit assignmentyou can also assign values to variables using an implicit assignmentint nvalue5 implicit assignmenteven though implicit assignments look a lot like function calls the compiler keeps track of which names are variables and which are functions so that they can be resolved properlyis there a difference is one more preferred over the other,['c++'] +174171,gallery space at beginning and end i got the following problem i made a form with a gallery the gallery instead of containing images contains items from one of my classes everything inside each item of the gallery thisplays perfectly i removed the space between images using relativelayout xmlnsandroidandroidlayout widthfill parentandroidlayout heightfill parent gallery androidididgalleryid androidlayout widthwrap content androidlayout heightwrap content androidspacing0dip androidpadding0dip androidlayout weight1 the items of the galleryxml version10 encodingutf8linearlayout androidididlinearlayout01 androidlayout width75dip xmlnsandroid androidlayout heightwrap content androidorientationvertical androidgravitycenter horizontal androidbackgroundf textview androidididframe number androidlayout widthfill parent androidlayout heightwrap content androidtext androidtextsize12dip androidtextcolorf androidbackground0 androidgravitycenter linearlayout androidididlinearlayout01 androidlayout widthfill parent androidlayout heightfill parent androidorientationhorizontal androidgravitycenter horizontal textview androidididframe shot1 androidlayout widthwrap content androidlayout heightwrap content androidtext androidtextsize18dip androidtextcolor0 textview androidididframe shot2 androidlayout widthwrap content androidlayout heightwrap content androidtext androidtextsize18dip androidtextcolor0 linearlayout textview androidididframe total androidlayout widthwrap content androidlayout heightwrap content androidtext androidtextsize38dip androidtextcolor0linearlayoutbut i got a problem there is some blank space at the beginning and end of the gallery with no items the thing is that my gallery has many items on it that you can actually scroll horizontally but i wanna get rid of those spaces so the very first thing on the very left of the gallery is the first item and the very last when you scroll to the very right is the right itemedit 0816 still with the same problem back in the project here i leave an image of exactly what is what i am trying to get rid of that is the black space at the beginning also is at the end of the gallery at the other side,['android'] +174177,codeigniter duplicate session issue i have an application built with codeigniter using the sessions class and storing session data in a database the problem is i am getting extra session records in my database when my webpage loads a css fileup until recently i was running my application on a simple vps host provided by rackspace database and apache were both running on the same vps recently however i have migrated my application to phpfog to allow it to scale more easily i did not have this issue with my former hosting setupthe row with the populated value for user data is my original session the other three blank sessions are the result of simply refreshing the page three times i seem to have tracked it down to including a css file in my header when i comment it out or delete it the issue goes away it is only this particular css file also other cssjsimage files do not cause this issuehere is a link to the css file in questionanyone know what could be causing this thanksupdatei realized the html of the page in question might be helpful commenting out the stylesheet include on line 13 makes the issue go awayupdate2configsess cookie name ci sessionconfigsess expiration 7200configsess expire on close falseconfigsess encrypt cookie falseconfigsess use database trueconfigsess table name ci sessionsconfigsess match ip falseconfigsess match useragent trueconfigsess time to update 300 cookie related variables cookie prefix set a prefix if you need to avoid collisions cookie domain set to yourdomaincom for sitewide cookies cookie path typically will be a forward slash cookie secure cookies will only be set if a secure https connection existsconfigcookie domain caseyphpfogappcom base url partshostconfigcookie path configcookie prefix configcookie secure false,['php'] +174194,nokogiri error failed to build gem native extension i updated to the developer release of lion and noticed i could not start rails apps anymore whenever i try to sudo bundle install i get the following errorinstalling nokogiri 144 with native extensions libraryrubysite18rubygemsinstallerrb551in build extensions error failed to build gem native extension geminstallerextensionbuilderror systemlibraryframeworksrubyframeworkversions18usrbinruby extconfrb mkmfrb cannot find header files for ruby at systemlibraryframeworksrubyframeworkversions18usrlibrubyrubyhgem files will remain installed in usersjamielawrencedocumentswebsitesatgdbvendorbundleruby18gemsnokogiri144 for inspectionresults logged to usersjamielawrencedocumentswebsitesatgdbvendorbundleruby18gemsnokogiri144extnokogirigem makeout from libraryrubysite18rubygemsinstallerrb504in each from libraryrubysite18rubygemsinstallerrb504in build extensions from libraryrubysite18rubygemsinstallerrb180in install from libraryrubygems18gemsbundler1015libbundlersourcerb101in install from libraryrubygems18gemsbundler1015libbundlerrubygems integrationrb78in preserve paths from libraryrubygems18gemsbundler1015libbundlersourcerb91in install from libraryrubygems18gemsbundler1015libbundlerinstallerrb58in run from libraryrubygems18gemsbundler1015libbundlerrubygems integrationrb93in with build args from libraryrubygems18gemsbundler1015libbundlerinstallerrb57in run from libraryrubygems18gemsbundler1015libbundlerspec setrb12in each from libraryrubygems18gemsbundler1015libbundlerspec setrb12in each from libraryrubygems18gemsbundler1015libbundlerinstallerrb49in run from libraryrubygems18gemsbundler1015libbundlerinstallerrb8in install from libraryrubygems18gemsbundler1015libbundlerclirb2in install from libraryrubygems18gemsbundler1015libbundlervendorthortaskrb22in send from libraryrubygems18gemsbundler1015libbundlervendorthortaskrb22in run from libraryrubygems18gemsbundler1015libbundlervendorthorinvocationrb118in invoke task from libraryrubygems18gemsbundler1015libbundlervendorthorrb246in thispatch from libraryrubygems18gemsbundler1015libbundlervendorthorbaserb389in start from libraryrubygems18gemsbundler1015binbundle13 from usrbinbundle19in load from usrbinbundle19,"['ruby-on-rails', 'ruby']" +174199,a hello world tutorial for arduino and android a few days ago arduino just released a start pack for android developers the arduino adk is a microcontroller board based on the atmega2560 datasheet it has a usb host interface to connect with android based phones based on the max3421ei have been searching again and again for tutorials or something in order to begin arduino programming and i am looking for very good tutorials maybe some kind of hello light that would make a light blink on the card with a button on my android devicehave you got some links fan blogs other information about that topici of course know the arduino website and android developer documentation but they are quite overcomplicated,['android'] +174209,iphone development how to thisplay a numeric keyboard i am working on a mobile website which is not a native iphone app but rather a simple msomedomaincom website which is developed in c aspnet objective on clicking one of the text boxes how do i thisplay the numeric keyboard only note the website is not in html5 and is not part of a webview inside a native app but rather a standalone regular websitemy textbox is a regular aspnet text box asptextbox runatserver cssclassreference input text1234567,['iphone'] +174220,popup open position in chrome when i am using firefox and then using windowopenblahcomblahleft30top300 the popup opens in my second thisplay above my first one but in chrome the popup just opens at left0top0 is there a reason why chrome is doing this and how would i fix the problemthanks,"['javascript', 'html']" +174226,how to use relaycommand with the mvvm light framework i have just started learning the mvvm light framework and i cannot find any straightforward examples on how to use a relaycommand for purposes of learning i would just like to have a button in my view which when clicked show does a hello world world message box and which is enabled on every even minute basically if datetimenowminute 2 0how would the button xaml look and how would the relaycommand helloworld be defined in the viewmodelthanks for your help,['c#'] +174229,php replace array value does not stay after foreach loop i am changing the value in a multidimensional array and it is not staying outside of the foreach loop that is being used to traverse itmy array initially looks something like thisarray 0 array name bob age 33 state ca visited 0 my php gets into it by goingforeach people as person echo personname logic for the visited variable personvisited calculated visit valueif i print rpersonat the end but inside of the foreach loop everything looks good the value for visited is set however if i print rpeople outside of the loop personvisited is not set i do not know what i am doing wrong help is appreciated,['php'] +174238,how to do i get object keys by a pattern i have an object with named keysvar names peter pan peter parker tony stark is there a way to get all keys by a pattern eg all keys having peter in itthe case is that i want to have all the filtered keys in an array egvar filterednames peter pan peter parker,['javascript'] +174239,how to include nested and sibling associations in active record to json i have a course model with 2 associations to another model treebelongs to interaction outline class name tree foreign key interaction outline idbelongs to token outline class name tree foreign key token outline idi read this and was able to include sibling associations in my controllercourseto jsoninclude interaction outline token outlinei was also able to get multiply nested associationscourseto jsonincludeinteraction outline include tree node include definition but i cannot get both sibling and multiply nested includescourseto json include interaction outline include tree node include definition token outline include tree node include definition nomethoderror undefined method macro for nilnilclassthe error you get when the syntax or the association is wrongi tried this toocourseto json include interaction outline include tree node include definition token outline include tree node include definition same errorwhat is the right syntax here,['ruby-on-rails'] +174244,java ssl connect add server cert to keystore programatically i am connecting an ssl client to my ssl serverwhen the client fails to verify a certificate due to the root not existing in the clients key store i need the option to add that certificate to the local key store in code and continuethere are examples for always accepting all certificates but i want the user to verify the cert and add it to local key store without leaving the applicationsslsocketfactory sslsocketfactory sslsocketfactory sslsocketfactorygetdefaultsslsocket sslsocket sslsocket sslsocketfactorycreatesocketlocalhost 23467try sslsocketstarthandshake catch ioexception e here i want to get the peers certificate conditionally add to local key store then reauthenticate successfullythere is a whole lot of stuff about custom socketfactory trustmanager sslcontext etc and i do not really understand how they all fit together or which would be the shortest path to my goal,['java'] +174252,proper way to reset csvreader for multiple iterations having an issue with a custom iterator in that it will only iterate over the file once i am calling seek0 on the relevant file object in between iterations but stopiteration is thrown on the first call to next on the 2nd run through i feel i am overlooking something obvious but would appreciate some fresh eyes on thisclass mappediteratorobject given an iterator of dicts or objects and a attribute mapping dict will make the objects accessible via the desired interface currently it will only produce dictionaries with string values can be made to support actual objects later on somehow d def init self objnone mapping args kwargs self obj obj self mapping mapping selfcnt 0 def iter self return self def resetself selfcnt 0 def nextself try try item self objnext except attributeerror item self objselfcnt if no mapping is provided an empty object will be returned mapped obj for mapped attr in self mapping attr mapped attrattribute new attr mapped attrmapped name val itemgetattr val strvalstrip get rid of whitespace todo apply transformers this allows multi attribute mapping or grouping of multiple attributes in to one try mapped objnew attr val except keyerror mapped objnew attr val selfcnt 1 return mapped obj except indexerror stopiteration selfreset raise stopiterationclass csvmappermappediterator def init self reader mapping args kwargs self reader reader self mapping mapping self file kwargspopfile supercsvmapper self init self reader self mapping args kwargs classmethod def from csvcls file mapping args kwargs todo parse kwargs for various dictreader kwargs return clsreaderdictreaderfile mappingmapping filefile def len self return intself readerline num def resetself if self file self fileseek0 supercsvmapper selfresetsample usagefile opensomefilecsv rb say this file has 2 rows a header rowmapping mymappingclass this is not really relevantreader csvmapperfrom csvfile mapping john bobfor r in reader print rname this would not print anythingfor r in reader print rname,['python'] +174260,best way to run robolectric tests on android device i have a robolectric test project setup but i would like to also run these tests on my device to check that i do not get bit by jvm vs dalvik implementation differencesunlike robolectric tests i would not run these tests frequently my concern is that there is little effort to maintain the test suite and that they verify actual device functionalitywhats the best way to do thatwhat i have currently gotmy robolectric test project as a test case testpackage i created an android test project with a test case testroboonandroid it creates a testpackage and has a test for each test in testpackageright now every time i add a test to my robolectric suite i need to manually add it to my device suite is there some way to do that automatically with reflectionalso robolectric uses junit 4 by default and android uses junit 3 so i have to write all of my robolectric tests using junit 3 style importing from junitframework instead of orgjunit,['android'] +174302,does the apple app store reject apps that require usernamepassword access we wish to build an app that would require paid registration on a third party website to access this would be authenticated via the web once allowing access to the content thereafterdoes the apple app store reject apps that require you to be registered with a 3rd party website to access the app ie onetime login screen would appear upon first usedoes anyone have any experience submitting such an appmore info our educational organisation puts together reference guidelines for its members which are updated every 6 months or so we currently use isilo to thistribute these and allowing the content download through our secure website we would rather have a native app to streamline the install and update process for our usersi have read the guidelines and note point 2 apps that arbitrarily restrict which users may use the app such as by location or carrier may be rejected not sure whether this means us,['iphone'] +174328,best dashboard architecture i need to build a dashboard for an application the dashboard will have different dashlets and each dashlet can have any one of the following thingsgraphs jfreecharts and some javascript charttable data from tables data from external sources mapswhat can be a good architecture for such kind of application what i have currently in mind iseach dashlet should have its own lifecycle and when the dashboard loads it should just show the ui of the dashlets initially after the page load each dashlet sends a server call based on its type to fetch its dataafter the data has been fetched each dashlet based on its type renders the data,"['java', 'javascript']" +174348,are private frameworks supported on ios recently i started to modularize my applications much more aggresively than i used to separating pieces of code into frameworks or librariesi like the concept of aprivate frameworksa in desktop cocoa ie the frameworks included in the application bundle from my small experience the frameworks are better suited for code reuse than simple libraries as the frameworks can include their own headers with them this makes adding a new framework to an existing project a whole lot easierthe problem is that these aprivatea frameworks are not supported on ios you have to do with static libraries there and the header management is a pain is there a good technical reason for apple to not support frameworks on iosjust to make sure apple unfortunately uses the term aprivate frameworka for two things the first is acustoma frameworks that ship with an application the second is undocumented and prohibited frameworks that people are not supposed to use on ios iam asking about the formerps did this change in ios 8 thereas a acocoa touch frameworka template in xcode 6,['ios'] +174371,boosttest and mocking framework i am using boosttest and need to use a mocking framework with it does anyone have any recommendations,['c++'] +174377,why does the blowfish output in java and php differ by only 2 chars i have a blowfish encryption script in php and java vice versa that was working fine until today when i came across a problemthe same content is encrypted differently in java vs php by only 2 chars which is really weirdphpwthzxfxlhdmmjmfnoh0hcisjadvffgjavawthzxfxlhdmmjmfnoh0hcisd8dvffgas you see those two positions do not match unfortunately the value is a real email address and i cannot share it also i was not able to reproduce the problem with other few values i have tested i have tried changing base64 encode classes on java and that neither helpedthe source code for php is here and for java is herewhat could i do to resolve this problem,"['java', 'php']" +174387,getting the name of a method parameter in java6 imagine i have the following method signaturepublic void makesandwichbread slice1 bread slice2 listfilling fillings boolean mustardi would like to know at runtime the value that was passed on to slice2 or any other parameter the important bit here is that i want to get the value by parameter namei know how to get the list of parameter types with getparametertypes or getgenericparametertypesideally i would like to get a list of parameter names instead of types is there a way to do so,['java'] +174418,repeated java garbage collection even though there is enough java memory why our java process is eating up lot of cpu and the log shows its doing gc too often even though used memory is 5gb taken from jmx console and the min and max mem is 10gbour jvm args is jvm gcverbosegc xnoclassgc xxprintgcdetails xxuseparnewgc xxnewsize3gb xxparallelgcthreads8 xxmaxtenuringthreshold15 xxuseconcmarksweepgcand minheapmaxheap10gb any idea what might be triggering gc and why is it happening to often and too soon we cant connect any sort of profiling tool as its production box apart from getting some settings via jmx thanks gc log 20110720 021046 full gc system cms 3423k4019122k7340032k 134979250 secs 4876606k4019122k10171200k cms perm 21656k21608k21824k 134980930 secs times user1299 sys050 real1350 secs gc 1 cmsinitialmark 4019122k7340032k 4041525k10171200k 09110 secs times user0 sys0 real0 secs 20110720 0210 cmsconcurrentmark 1032210753 secs times user2155 sys022 real1075 secscmsconcurrentpreclean 00350036 secs times user004 sys0 real004 secs20110720 0215 cms abort preclean due to time cmsconcurrentabortablepreclean 10835063 secs times user108 sys0 real506 secsgcyg occupancy 282204 k 2831168 krescan parallel 00402030 secsweak refs processing 010550 secs 1 cmsremark 4019122k7340032k 4301326k10171200k 00413630 secs times user007 sys001 real004 secs20110720 0216cmsconcurrentsweep 26272627 secs times user263 sys0 real263 secscmsconcurrentreset 00390039 secs times user004 sys0 real004 secs20110720 021120gc 1 cmsinitialmark 4019034k7340032k 4301238k10171200k 00308450 secs times user003 sys0 real003 secs20110720 021130cmsconcurrentmark 1030410307 secs times user2048 sys011 real1031 secscmsconcurrentpreclean 00180019 secs times user002 sys0 real001 secs20110720 021135 cms abort preclean due to time cmsconcurrentabortablepreclean 10435048 secs times user103 sys0 real505 secsgcyg occupancy 282204 k 2831168 krescan parallel 00419560 secsweak refs processing 010880 secs 1 cmsremark 4019034k7340032k 4301238k10171200k 00431480 secs times user007 sys001 real005 secs20110720 021138cmsconcurrentsweep 262622 secs times user263 sys0 real262 secscmsconcurrentreset 00390039 secs times user004 sys0 real004 secs,['java'] +174443,is there any way to change gcc compilation options for a gem i am struggling to install the redcloth gem when i type gem install redclothi get aragelredcloth attributescrl in function aredcloth attribute parseraragelredcloth attributescrl2611 error variable aacta set but not used werrorunusedbutsetvariablecc1 all warnings being treated as errorsmake redcloth attributeso error 1 athe reason is the werror compilation option passed to gcc in the extconfrb of the redcloth gemrequire mkmfconfigwarnflagsgsubwshorten64to32 if configwarnflagscflags o0 wall werror if configcc gccathe problem is that when i remove the werror option from the file it reappears automatically next time i launch the gem install commandhow can i permanently unset the werror optionanother option would be to downgrade to gcc 452 but it is not in the repositories of my fedora 15and i would rather avoid to compile it from sourceaany help much appreciated,['ruby-on-rails'] +174468,how to force subclass to call an abstract implemented method basically what i want to do is force the subclass to call an abstract superclass method implemented in the subclass so i do not have to explicitly write it each time i create a new subclassi wrote it in the superclass constructor once because i want it to force it for every implementationpublic abstract class supahclass public supahclass dostuff it is executed when the subclass constructor is called init not executed even though it is implemented private void dostuff protected abstract void initpublic class somesubclass extends supahclass the problem lies here this is executed after init so it gets null again private textbox mytextbox null public somesubclass super invokes the super constructor so init should be called i could call init here each time i create a new subclass but no override public void init thismytextbox new textbox executed before its declared as null above of course the superclass cannot really call it since its an abstract so undefined method but its an abstract class so it cannot be instanciated it must delegate the task to its subclasses so why cant they call the abstract but now implemented methodedit see the subclass property mytextbox and the init implementationwhich approach do you think i should do remove the null in the property declaration duhor remove the init in the superclass and explicitly calling it in the subclass constructor this is what i wanted to avoid since i will have to write it 100 of the time,['java'] +174470,fast memory access in c what should i take in consideration when developing a game in terms of fast memory access in cthe memory i load is static so i should put in in a continuous block of memory rightalso how should i organize the variables inside structs to improve performance,['c++'] +174502,why java instance initializers what is the sense of instance initializers in java cannot we just put that block of code at the beginning of the constructor instead,['java'] +174516,does applicationenablevisualstyles do anything i am very picky when it comes to understanding a new language and recently i have taken up learning c so i like to know everything that is going on when i create a new application in this case a new windows forms application i created one and was given some generated code from visual studio and one line was applicationenablevisualstyles i did some research on msdn and found this article applicationenablevisualstyles i performed the example that they presented expecting the button not to be visible when i commented out the said line nothing happened it appeared that nothing changed i know this is a very basic example but should not something have changed if this is so critical in the main procedure what exactly is it doing that i am missingthank you,['c#'] +174528,multiple files as input on amazon elastic mapreduce i am trying to run a job on elastic mapreduce emr with a custom jar i am trying to process about a 10 files in a single directory when i submit my job with the parameter s3nbucketnamecompressedxmlgz i get a matched 0 files error if i pass just the absolute path to a file eg s3nbucketnamecompressed01xmlgz it runs fine but only one file gets processed i tried using the name of the directory s3nbucketnamecompressed hoping that the files within will be processed but that just passes the directory to the jobat the same time i have a smaller local hadoop installation in that when i pass my job with wildcards pathtodironhdfsxmlgz it works fine and all 10 files are listed correctlyhow do i get emr to list all my files,['java'] +174540,can i modify an mvc route outside of globalasax is it possible to modify the the routes and thus the routetable outside of the globalasax file maybe in a controller is this even advisablemy reason for asking has to do with iis 6 and integrated mode not allowing for request context calls i am implementing internationalization for a site and keeping track of the culture in the url the culture is originally read from a config file and loaded as a route default this file read is what ends up throwing the error another few steps up the stack i based this off the method described here,['asp.net'] +174546,regex to validate string having only characters not special characters blank spaces and numbers i am using ruby on rails 309 and i would like to validate a string that can have only characters not special characters case insensitive blank spaces and numbersin my validation code i havevalidates name presence true format with regex here i should set the regexhow i should state the regex,"['ruby-on-rails', 'ruby']" +174548,why does not visual studio allow me to step into typegettype i have got the following simple codeclass program static void mainstring args var t typegettypesystemreflectionassembly consolewritelinetfullname i am attempting to debug into the typegettype method but the debugger skips over the method even when using step into i have got debugging enabled for the net framework classes and debugging into other framework methods works fine why does not the debugger allow me to step into this particular method,['.net'] +174551,piping postgres copy in python with psycopg2 i am writing a script to do a copy of some data between two machines on the same network using psycopg2 i am replacing some old ugly bash that does the copy withpsql c h remotehost copy table to stdout psql c copy table from stdinthis seems like both the simplest and most efficient way to do the copy it is easy to replicate in python with a stringio or a tempfile like sobuf stringiofrom curs from conncursorto curs to conncursorfrom curscopy expertcopy table to stdout bufbufseek0 osseek setto curscopy expertcopy table from stdin bufbut that involves saving all the data to thiskin memoryhas anyone figured out a way to mimic the behavior of a unix pipe in a copy like this i cannot seem to find a unixpipe object that does not involve popen maybe the best solution is to just use popen and subprocess after all,"['python', 'sql']" +174552,list to implement iqueryable i am trying to create a mock for my irepository interfacepublic interface irepositoryt icollectiont iqueryabletwith this implementationpublic class repositoryfaket listt irepositoryt public expression expression get return thisasqueryableexpression public type elementtype get return thisasqueryableelementtype public iqueryprovider provider get return thisasqueryableprovider but when i use it i am getting stackoverflow exception how to implement this interface correctly to be able to use just a list as a repositoryusage is very simpletestpublic void test repositoryfakeuser users new repositoryfakeuser usersaddnew user listuser list from user in users where userid 5 select usertolist assertthatlist isemptyhere is screenshot of exception,"['c#', '.net']" +174554,merge image using javascript is it possible to merge pictures using javascriptfor example if you have 2 rectangle jpg or png images files of the same size is it possible that you can align it side by side and produce a merged copy of the two in a new jpg or png image file,['javascript'] +174566,compiletime assertion is there a way i can assert that two constant expressions are equal at compile time eg i want this to cause a compiletime errorenum foo263 bar264 some expressionfoobarbut i want this to not cause an errorenum foo263 bar263 some expressionfoobaredit the above was simplified my situation is more likesome other file i dont controlhclass xpublic enum foo263 my filehenum barsomethingsomethingelse bar should equal xfoosome expressionxfoo bar,['c++'] +174580,long division in java not working as expected class longdivpublic static void mainstring args final long x 2460601010 final long y 24606010 systemoutprintlnxyalthough the expected answer is 10 but the javac gives it as 5 reason,['java'] +174601,unparsed aapt error i was trying to build my android application after adding an image that i planned on using to the drawables folder the project worked perfectly fine before but after running the project an error message showed up saying unparsed aapt error the error shows up on the src folder i have tried to clean my project but the rjava class just thisapearsany suggestions on how to fix this problem,['android'] +174608,what does an expression like arrhi there imply if a3 and b5 what does this implyprintfayahello how is this sn bjunksuperi know that arr4 means arr4 so i need to know what does an expression like hi there implyedit question in probably clearer termswhen a string is used as an array subscript what value does it convey why is output of above hello how is this super,['c'] +174623,change uiimageview mode iphoneipad if i have an uiimageview with the mode set to center for example how can i change it to something else such as aspect fit with code,"['iphone', 'objective-c']" +174648,nginx php5fpm segfaults under high load i have been dealing with this problem all day and it is driving me insane all google results and searches here lead to dead ends i hope someone can work with me to provide a solution for myself and future victims here we goi am running a very popular website with over 3m page views a day on average that is 34 page views per second but more realistically during peak hours it gets to over 300 page views per second think of these as requestsi am running a ubuntu 1004 64bit server with 2 e5620 cpus 12gb ram and a micron p300 6gbs ssd during the peak hours the cpu and memory load is average 2030 cpu and half of memory is usedthe software that powers this site is nginx mysql php5fpm phpapc and memcached ok now finally the meat of the post here are my error logs there a bunch of these errors loggedvarlogphp5fpmjul 20 144947289895 notice fpm is running pid 29373jul 20 144947337092 notice ready to handle connectionsjul 20 145123957504 error pool w unable to retrieve process activity of one or more children will try again laterjul 20 145141846439 warning pool w child 29534 exited with code 1 after 114518174 seconds from startjul 20 145141846797 notice pool w child 29597 startedjul 20 145141896653 warning pool w child 29408 exited on signal 11 sigsegv after 114596706 seconds from startjul 20 145141897178 notice pool w child 29598 startedjul 20 145141903286 warning pool w child 29398 exited with code 1 after 114605761 seconds from startjul 20 145141903719 notice pool w child 29600 startedjul 20 145141907816 warning pool w child 29437 exited with code 1 after 114601417 seconds from startjul 20 145141908253 notice pool w child 29601 startedjul 20 145141916002 warning pool w child 29513 exited with code 1 after 114592514 seconds from startjul 20 145141916501 notice pool w child 29602 startedjul 20 145141916558 warning pool w child 29494 exited on signal 11 sigsegv after 114597355 seconds from startjul 20 145141916873 notice pool w child 29603 startedjul 20 145141921389 warning pool w child 29502 exited with code 1 after 114600405 seconds from startvarlognginxerrorlog20110720 154842 error 295830 569743 readv failed 104 connection reset by peer while reading upstream client 77223197193 server domaincom request get faviconico http11 upstream fastcgi12700190 host wdomaincom20110720 154842 error 295780 571695 readv failed 104 connection reset by peer while reading upstream client 1507064196 server domaincom request get page http10 upstream fastcgi12700190 host wdomaincom20110720 154842 error 295810 571050 readv failed 104 connection reset by peer while reading upstream client 11013615766 server domaincom request get page http11 upstream fastcgi12700190 host wdomaincom20110720 154842 error 295810 564892 readv failed 104 connection reset by peer while reading upstream client 110136161214 server domaincom request get page http11 upstream fastcgi12700190 host wdomaincom20110720 154842 error 295850 456171 readv failed 104 connection reset by peer while reading upstream client 93223135 server domaincom request get faviconico http11 upstream fastcgi12700190 host wdomaincom20110720 154842 error 295850 471192 readv failed 104 connection reset by peer while reading upstream client 749033142 server domaincom request get page http11 upstream fastcgi12700190 host wdomaincom20110720 154842 error 295800 570132 readv failed 104 connection reset by peer while reading upstream client 180246182191 server domaincom request get page http11 upstream fastcgi12700190 host wdomaincomfinally i want to point out that i did try to thisable phpapc to see if it was a bug with the opt cacher but the segfaults still persisted i also have php5suhosin installed and i thisabled it too but the errors still keep happening,['php'] +174677,how do files get into the external dependencies in msvc2010 i wonder why one of my projects has vdserrh listed under external dependencies and another has not and gives me an undefined symbol compiler error about a symbol which is defined in there how can i include this file in the other project as well probably by dragdrop but i would like to know the exact setting here,['c++'] +174679,android workaround for nonworking sensors when screen is off edit removed all mention of android version the issue is present on all versions of androidbackground when the screen is off many android phones do not provide updates to applications of accelerometer readings by calling onsensorchanged when the screen is off this behavior is thiscussed on so and is further documented hereon some phones nexus s droid x2 accelerometer values are only provided when there is a significant change in value sitting still on a table for example there might be one or zero updates per minutein order to produce code that is robust across phone models how am i to thistinguish between a lack of update events per screen off vs lack of updates per nonmovement should i maintain a database of phone models,['android'] +174698,rails update attributes without save is there an alternative to update attributes that does not save the recordso i could do something likecar carnewmake gmcother processingcarupdate attributesmodel sierra year 2012 looks super sexy wanna make love to itother processingcarsavebtw i know i can carmodel sierra but i want to update them all on one line,"['ruby-on-rails', 'ruby']" +174699,aes256 encryption in php i need a php function aes256 encodedatatoecrypt to encrypt the data into aes256 and another one aes256 decodeencrypteddata do the opposite does anyone know what code should this functions have,['php'] +174713,issue with frame size of uiview i am working on an ipad project currently it is on landscape view and i tried doingselfviewframesizeheightwhy is this always returning 960 while as in landscape the height dimension of the view itself should be 768 rightwhat i am trying to do is to allocinitwithframe a uitoolbar that is located at the bottom the uitoolbar has a height of 50 so heres what i did which failedselfbottom bar uitoolbar alloc initwithframecgrectmake0 selfframesizeheight50 selfviewframesizewidth 50why is this and how do i do this,"['ios', 'iphone', 'objective-c']" +174714,pdo pass by reference notice thisstmt dbhprepareselect thing from table where color colorstmtbindparamcolor someclassgetcolorstmtexecuteyields thisruntime notice only variables should be passed by referencethough it still executesthisstmt dbhprepareselect thing from table where color colortempcolor someclassgetcolorstmtbindparamcolortempcolorstmtexecuteruns without complainti do not understand the difference,['php'] +174720,how to effectively transfer real time video between two ios device like facetime skype fring tango i know how to get frame from ios sdk how to capture video frames from the camera as images using av foundation indexhtmlit is pixel and i can transfer it to jpegwhat the way i want to transfer the video is like thisone ios device aget the pixel or jpeg from call functionvoidcaptureoutputavcaptureoutput captureoutput didoutputsamplebuffercmsamplebufferrefsamplebuffer fromconnectionavcaptureconnection connectionusing existed technology encoding to h264 ffmpegencapsulate video with ts streamrun http server and wait for requestthe other ios device bhttp request to ausing http simply instead of rtprtspso my question is do i need to use ffmpeg to get h264 stream or i can get from ios apiif i use ffmpeg to encode to h264libx264 how to do that is there any sample code or guidelinei have read the post whats the best way of live streaming iphone camera to a media serverit is a pretty good thiscussion but i want to know the detail,['iphone'] +174726,jquery text change event i need to fire an event anytime the content of a textbox has changedi cant use keyup nor can i use keypresskeyup and keydown does not work if you hold down on the keykeypress triggers before the text has actually changed it does not recognize backspace or delete eitherso now i am assuming i am going to have to build some custom logic or download a plugin are there any plugins out there or if i should build one what constraints should i look out forfor eg facebook does it with their search at the top you can press and holdanother example is writing a stackoverflow question right below the editor the contents are copied in real time backspace and everythng works how do they do it,"['javascript', 'jquery']" +174738,sql server with clause i am getting this error when using a with clauseincorrect syntax near the keyword with if this statement is a common table expression an xmlnamespaces clause or a change tracking context clause the previous statement must be terminated with a semicolon msg 102 level 15 state 1 procedure viewcomplaintbyprofile line 29 incorrect syntax near here is my procedurealter procedure dboviewcomplaintbyprofile id intasbegin set nocount onwithone as select sno row numberover order by complaint id complaint id complainantnamecomplainttype id complaintprofileidcomplainantprofileiddescription email date complained status admincomments phone evidence plevel case prioritylevel id when 1 then high when 2 then medium when 3 then low end complaint type case complainttype id when 1 then purchased contact has incorrect details when 2 then contacted profile is already married when 3 then suspect the profile has fradudelent contectcredentials when 4 then suspect the profile has fake picture when 5 then profile has obscene or inappropriate content when 6 then report harassment offensive remarks etc by user when 7 then miscellaneous issue end status1 case status when new then 1 when inprogress then 2 when closed then 3 end from complaints two asselect sno row numberover order by complaint id complaintcomplaintprofileid case when castmmbprofilesmmb id as varchar is not null then castmmbprofilesmmb id as varchar when castuppmembershipprofile id as varchar is not null then upp else not found end as mmbid from complaints complaint left join mmbmembership on mmbmembershipprofile id complaintcomplaintprofileid left join mmb businessprofiles mmbprofiles on mmbprofilesmmb id mmbmembershipmmb id left join uppmembership on uppmembershipprofile id complaintcomplaintprofileid select onetwommbid from one join twoon onesno twosnowhere complainttype id idendplease helpthankssun,['sql'] +174754,why a static constructors do not have any parameters as per msdna static constructor does not take access modifiers or have parametersa static constructor is called automatically to initialize the class before the first instance is created or any static members are referenceda static constructor cannot be called directlycan any one please explain why the static constructor can not have parameters,"['c#', '.net']" +174760,c default allocator what should happen if the size does not equal the size passed to the invocation of allocate 2069void deallocatepointer p size type nrequires p shall be a pointer value obtained from allocate and shall equal the value passed as the first argument to the invocation of allocate which returned peffects deallocates the storage referenced by premarks uses operator deletevoid 1861 but it is unspecified when this function is calledwhat should happen if ndoes not equal the value passed as the first agrgument to the invocation of allocate which returned p not deallocate throw stdbad alloc editwhat i actually meant with what should happen was would it be okay to throw or assert in a custom implementation,['c++'] +174761,jsf valuebinding is deprecated facescontext context facescontextgetcurrentinstancevaluebinding vb contextgetapplicationcreatevaluebindingdatabindingcontext bc bindingcontext vbgetvaluecontextdcdatacontrol dc bcfinddatacontrolizpisiamdatacontrolizpisiamimpl izpisiam izpisiamimpldcgetdataproviderwhere valuebinding is deprecated now i found this but not working for me start0tstart0how to cahnge deprecated class,['java'] +174796,get id of div from its class name how can i find an id based on its class just using javascript i know this is easy with jquery what is the solution using getelementsbytagname,['javascript'] +174809,how to thisplay only time in uidatepicker iphone in my app i am thisplaying a uidatetimepicker in action sheet through code it is working finebut i do not want to thisplay date and dayhow this can be doneplease help thanks in advancecodeuiactionsheet actionsheet uiactionsheet alloc initwithtitlenslocalizedstringselect dateselecte datedelegateself cancelbuttontitlenslocalizedstringdonedonedestructivebuttontitlenslocalizedstringcancelcancelotherbuttontitlesnil actionsheetactionsheetstyle uiactionsheetstyleblacktranslucent uidatepicker datepicker uidatepicker alloc initwithframecgrectmake0 50 320 270 datepickershowsselectionindicator yes datepickerdatasource selfdatepickerdelegate self actionsheet addsubviewdatepicker datepicker release actionsheet showinviewselfview actionsheet setboundscgrectmake0 0 320 500 actionsheet release,"['iphone', 'objective-c']" +174874,scrabble word placement c i am currently writing a scrabblelike game in c i can get the computer to find the highest point value word that can be made using the current rack however i have no idea how to check if that word is placeable on the 1515 gameboard2d array string in it is default statewith no letters on the board all elements are set to 0is allowedhefilohow can i check if the word is not for exampleis not allowed h efill f is out of bounds l o is not allowed h ew lo lr foll fill is overlapping with o d,['c#'] +174904,getting only name of the class classgetname how can i get the name of the clastringclassgetname returns javalangstringi am only interested in getting last part ie only stringany api can do that,['java'] +174905,how to join 2 or more wav files together programatically i need the ability to join 2 or more wav files together in to one wav file i must do this programatically using c 3rdparty products are not an option i know of the systemmediasoundplayer class but i am not looking to play the the wav but only to create itthanks in advance,['c#'] +174911,how can i get a uitableviews visible rect i am trying to detect if the user has scrolled to the bottom of a uitableview so that i can do some additional stuff in order to calculate things properly i need to get the uitableviews visible rect how can i achieve this voidscrollviewdidscrolluiscrollview scrollview refreshheaderview egorefreshscrollviewdidscrollscrollview int currentmaxposition cgrectgetmaxyselftableview visiblerect int currentminposition cgrectgetminyselftableview visiblerect int tableviewbottom selftableview boundssizeheight 100 int tableviewtop 0 get older messages once were near the bottom if currentmaxposition tableviewbottom 100 nslogwe at the bottom,"['iphone', 'objective-c']" +174915,abstractmethoderror on calling exceptionprintstacktrace inside a catch clause i want to print the strack trace of the exceptiontry catch exception exc excprintstacktrace but in some cases i do not get a stack trace and instead see something like thisexception in thread pool1thread2 javalangabstractmethoderror javalangexceptionprintstacktracev usually this exception should occur if a library has not the same version at runtime as at compile time but in this case i work with a class from the java library printstacktrace is implemented in throwable so this method cannot be abstract in exception or any derived class further this abstractmethoderror is not always thrown sometimes there are other exceptions at this specific catch clause program flow depends on data from a file and the current time so sometimes other stuff happens like arrayindexoutofboundsexceptions or illegalstateexceptions that are thrown in my own code and that i would expect instead of the strange errorso the question is how is it possible for that particular abstractmethoderror to occurps i am using eclipse helios on linux and use jdk 160 24 as runtime environment to launch my applicationedit there was a typo printstracktrace i corrected it was just written out of my mind and has not anything to do with my problem it is or should be a standalone application no webapplication no eclipse rcp application just a plain old java application more or less the problem does occur on another computer too also with eclipse helios also with fedora linux but with jdk 160 21to my surprise it was indeed possible to call getclassgetname but no other method i tried the exception is of type javalangarrayindexoutofboundsexception i just tried to use openjdk 160 because it is already installed on my system and got different results instead of throwing the abstractmethoderror printstacktrace printed just an empty line and getmessage returned null instead of throwing the error so i do not know where exactly the exception was thrown because a trycatchblock high up in hierarchy catches the exception just to stop a part of the application gracefully i might catch this exception type on some points to get an idea where it comes from but that would not explain the strange behavior of the exception itselfedit 2 finally i tracked the problem down it turned out to be an exception that occurred to me already yesterday at the exact same line but sometimes the exception itself behaves strange i call getint on a list more precisely an arraylist that was wrapped using collectionsunmodifiablelistlist with an index that is 1 that is the initial value inside a loop this index should be changed but it will not for whatever reason at least now i know where to look to fix the arrayindexoutofboundsexception but i still have no clue why the exception itself behaves strangeedit 3 i tried throwableclassgetmethodprintstacktraceinvokeexc instead of excprintstacktrace and got a javalangnosuchmethoderror javalangthrowableprintstacktracev instead of the javalangabstractmethoderror i also tried to compile the java files from the shell using javac and jar only the one library the exception is coming from because it would be tedious to manually compile all jars the result is the same if i throw an indexarrayoutofboundsexception myself at that line the stack trace will be printed just fine maybe i have to hope that this problem is very rare and will never occur anywhere else,['java'] +174917,a datetime equivalent in javasql is there a javasqldatetime so far i have not found a clear answer to this i would like to know what the equivalent is for a sql type datetime and the java type using a preparedstatementi have found but it states that sql type datetime is the same as sqldate but when looking at the sql date docs it says the time is truncated all zeroswhat i want is to be able to specify a preparedstatementsetdatetime or some sortthe only other way i see is using a timestamp but that would require me to change the column type while i cannot imagine someone else never had this problem beforeany hintsedit i am using mysql,"['java', 'mysql', 'sql']" +174921,sql performance on left outer join vs not exists if i want to find a set of entries in table a but not in table b i can use either left outer join or not exists i have heard sql server is geared towards ansi and in some case left outer joins are far more efficient than not exists will ansi join perform better in this case and are join operators more efficient than not exists in general on sql server,['sql'] +174934,whats the difference between shared worker and worker in html5 after reading this blog post i do not get it whats the difference between a worker and a sharedworker,['javascript'] +174952,difference between responseredirect and servertransfer possible duplicatesresponseredirect vs servertransferservertransfer vs responseredirect what is the difference between responseredirect and servertransferonly one difference i know is in responseredirect the browser url changes to targeted page as well as in servertransfer the url remains sameany other difference,"['c#', 'asp.net']" +174955,get url with content after hash how can i get url with content after hash windowlocation return me url without hash for examplewmystorecomprodid1windowlocation return only wmystorecom,"['javascript', 'jquery']" +174962,nameerror undefined local variable or method logger when i run scriptserver everything works fine but when i run my unit tests rake testunits i get the error below and am not sure how to solve thiserrornameerror undefined local variable or method logger for giveawayeligiblemembertest0x10477dff8 userskamilski81sitespevitality mallvendorrailsactionpacklibaction controllertest processrb471in method missing userskamilski81sitespevitality malibupdate giveaway eligible membersrb17in is valid checksum userskamilski81sitespevitality malltestunitgiveaway eligible member testrb26in test that checksum is valid userskamilski81sitespevitality mallvendorrailsactivesupportlibactive supporttestingsetup and teardownrb60in send userskamilski81sitespevitality mallvendorrailsactivesupportlibactive supporttestingsetup and teardownrb60in runi tried putting class testunittestcase rails default logger loggernewstdout rails default loggerlevel loggerwarn logger loggernewstdout loggerlevel loggerwarnendhere is the code that is using my loggerdef is valid checksumcsv arr expected row count csv arr03to i loggerdebug expected record count expected row count actual row count csv arrnitems 1 loggerdebug actual record count actual row count checksum valid false if expected row count actual row count loggerdebug checksum is valid checksum valid true end return checksum validendbut this still does not solve the error,"['ruby-on-rails', 'ruby']" +174972,how to position inside flexbox i am using flex box and want to align button to the bottom i am using position absolute and bottom 0 but browser is ignoring it ul classbox lidivthis has br more br buttononebuttondivli lidivthis has br more br content br buttononebuttondivli liddivbuttononebuttondivliulul basic styling width 100 height 100px border 1px solid 5 flexbox setup thisplay webkitbox webkitboxorient horizontal thisplay mozbox mozboxorient horizontal thisplay box boxorient horizontalbox li webkitboxflex 1 mozboxflex 1 boxflex 1 margin 0 1px paddingbottom 20px borderbottom 20px solid red position relativebutton position absolute bottom 0 our colors box linthchild1 background fcc box linthchild2 background cfc box linthchild3 background ccf i can use float and not use flexbox but i want to see if there is a solution for this using flexboxdemo here,['css'] +175000,installing oursql on mac os lion successes but import in python fails why i followed the installation instructions for installing oursql on mac os x sincesudo pip install oursqltold me that it could not find mysql config i located it with locate mysql config and told it where to find it bysudo mysql configusrlocalmysql5514osx106x86 64binmysql config pip install oursqli added the terminal output at the bottom for readability reasons after that i fired up python in terminal on mac os lion it is python 27 now and did import oursqlbut python keeps telling me import oursqltraceback most recent call last file stdin line 1 in moduleimporterror dlopenlibrarypython27sitepackagesoursqlso 2 library not loaded libmysqlclient18dylib referenced from librarypython27sitepackagesoursqlso reason image not foundwhat do i miss any suggestionsterminal output of pip installationdownloadingunpacking oursql downloading oursql092tarbz2 113kb 113kb downloaded running setuppy egg info for package oursqlinstalling collected packages oursql running setuppy install for oursql skipping oursqlxoursqlc cython extension uptodate building oursql extension usrlocalmysql5514osx106x86 64binmysql config cflags llvmgcc42 fnostrictaliasing fnocommon dynamic g os pipe fnocommon fnostrictaliasing fwrapv mnofusedmadd denable dtrace dmacosx dndebug wall wstrictprototypes wshorten64to32 dndebug g fwrapv os wall wstrictprototypes denable dtrace pipe isystemlibraryframeworkspythonframeworkversions27includepython27 c oursqlxoursqlc o buildtempmacosx107intel27oursqlxoursqlo iusrlocalmysql5514osx106x86 64include os g fnocommon fnostrictaliasing arch x86 64 oursqlxoursqlc in function a pyx pf 6oursql 10connection cinit a oursqlxoursqlc4630 warning implicit conversion shortens 64bit value into a 32bit value oursqlxoursqlc in function a pyx pf 6oursql 10 statement executea oursqlxoursqlc10219 warning implicit conversion shortens 64bit value into a 32bit value oursqlxoursqlc in function a pyx pf 6oursql 16 dbapitypeobject richcmp a oursqlxoursqlc17597 warning implicit conversion shortens 64bit value into a 32bit value llvmgcc42 fnostrictaliasing fnocommon dynamic g os pipe fnocommon fnostrictaliasing fwrapv mnofusedmadd denable dtrace dmacosx dndebug wall wstrictprototypes wshorten64to32 dndebug g fwrapv os wall wstrictprototypes denable dtrace pipe isystemlibraryframeworkspythonframeworkversions27includepython27 c oursqlxcompatc o buildtempmacosx107intel27oursqlxcompato iusrlocalmysql5514osx106x86 64include os g fnocommon fnostrictaliasing arch x86 64 usrlocalmysql5514osx106x86 64binmysql config libs llvmgcc42 wlf bundle undefined dynamic lookup wlf arch i386 arch x86 64 buildtempmacosx107intel27oursqlxoursqlo buildtempmacosx107intel27oursqlxcompato o buildlibmacosx107intel27oursqlso lusrlocalmysql5514osx106x86 64lib lmysqlclient lpthread ld warning ignoring file buildtempmacosx107intel27oursqlxoursqlo file was built for unsupported file format which is not the architecture being linked i386 ld warning ignoring file buildtempmacosx107intel27oursqlxcompato file was built for unsupported file format which is not the architecture being linked i386 ld warning ignoring file usrlocalmysql5514osx106x86 64liblibmysqlclientdylib file was built for unsupported file format which is not the architecture being linked i386successfully installed oursqlcleaning up,['python'] +175011,uitableview contentinset issue i have strange issue with contentinsent i am implementing pull release to refresh on uitableview and everything works fine but in some cases i would like to thisplay loading status without user interaction so i thought i will simply use contentinset in the following wayscrollviewcontentinset uiedgeinsetsmake600f 00f 00f 00feverything works fine for 1 or 2 cells thisplayed out of 3 possible on the view however once the number of cells grows my banner at the top does not get thisplayed at the same time manually scrolling works fine do i have to move the scroll besides moving content,['ios'] +175015,jquery function inside documentready function is it correct to create functions inside ofdocumentreadyfunction like so documentreadyfunction function callme the function inside of the ready does not have to call before dom is ready and event inside of the ready is triggeredjust to clarify a little bit heres the code which would illustrate the problemfunction var ind 0 some event is executed and changes the value of the ind another event which affects the ind variable and another one after this event we call our function there is another event and we call our function againthe function which i need to call needs the updated value of the ind variable which i guess i could pass as a parameter but is there a better way of doing italso another important thing is that the function in question can also change the value of the ind variable for instance incrementing it ind,['jquery'] +175022,how can i hide series from a highcharts legend i have 4 series in my chart 2 are visible when the chart loads 2 are hidden when the user zooms in the visibility switcheshow can i have a legend that only thisplays the 2 visible series,['javascript'] +175025,xcodeinstruments not showing memory leaks i am following the stanford ios development lectures and i have a calculator brain class which has been alloc init in a controller but i have not released it in the dealloc calculatorbrain brain if brain brain calculatorbrain alloc init return braini ran from xcode run with performance tool and the app started and no leaks appeared i then clicked the home button in the ios simulator and nothing i then double clicked the home button and closed the app and still nothingi also did build analyse and it didnt spot anythingcould you let me know why its not picking it up,"['objective-c', 'ios']" +175026,alternatives for pow on windows i love pow for mac however i have a few coworkers that are on windows is there anything that they can use to have the power of pow,['ruby'] +175054,vs nil in objectivec if you have an object like nsstring somestring what is the difference if any betweenif somestringvsif somestring nilthanks,"['iphone', 'objective-c', 'c']" +175061,castle windsor transient thisposables i know this has been thiscussed ad nauseumbut i have an issue with the way windsor is tracking transient ithisposable objectsi understand the benefits of letting windsor manage my idiposablesbut i do not like it what happens if i want to wrap my component in a using block the coder would make the assumption the resource would get cleaned up at the end of the using block right wrong thispose would be called but windsor would hold onto the instance until explicitly released this is all well and fine for me since i know what i am doingbut what about another developer whos coding a class and wants to use an ithisposable the way every other ithisposable is usually used in a using block usingfactorycreateinstance looks much clearer to me thanmythisposable instancetry instance factorygetinstancefinally factoryreleaseinstancein order to truly thispose my instances and have them eligible for gc i need to reference the windsorcontainer or use a typed factory that exposes a release method that means the only acceptable way of using ithisposable components is to use a typed factory this is not good in my opinionwhat if someone adds the ithisposable interface to an existing component every single place that expects the component to be injected will need to change that is really bad in my opinion granted in a non di scenario it would need to change to call thispose alsobut with windsor every place will need to change to use a typed factory which is a much larger changeok fair enough i can use a custom releasepolicy right how about thispublic class customcomponentsreleasepolicy allcomponentsreleasepolicy public override void trackobject instance burden burden if burdenmodellifestyletype lifestyletypepooled basetrackinstance burden ok great my ithisposable transient components will be gcd nowwhat if i want to use a typedfactory so my class can produce many instances of a typepublic interface imyfactory mythisposable getinstance void releasemythisposable instancesingletonpublic class testclass public testclassimyfactory factory ok well for one calling release on factory will do nothing to call thispose on mythisposable since mythisposable is not trackedhow can i overcome these difficultiesthanks,['.net'] +175065,objective c change all attributes in nsattributedstring attributedstring enumerateattributesinrangerange optionsnsattributedstringenumerationreverse usingblock nsdictionary attributes nsrange range bool stop nsmutabledictionary mutableattributes nsmutabledictionary dictionarywithdictionaryattributes mutableattributes setobjectnsnumber numberwithint1 forkeynsunderline attributes mutableattributes i am trying to loop through all attributed and add nsunderline to them when debugging it seems like nsunderline is added to the dictionary but when i loop for the second time they are removedam i doing anything wrong while updating nsdictionaries,"['iphone', 'objective-c']" +175066,htmlagilitypack replace node i want to replace a node with a new node how can i get the exact position of the node and do a complete replacei have tried the following but i cannot figured out how to get the index of the node or which parent node to call replacechild onstring html bbold onebstrongstrongstrongbbold twobhtmldocument document new htmldocumentdocumentloadhtmlhtmlvar bolds documentdocumentnodedescendantswhereitem itemname bforeach var item in bolds string newnodehtml generatenewnodehtml htmlnode newnode new htmlnodehtmlnodetypetext document itemparentnodereplacechild,['c#'] +175071,incorrect lazy initialization findbug told me that i use incorrect lazy initializationpublic static object getinstance if instance null return instance instance new object return instancei do not see anything wrong here is it wrong behaviour of findbug or i missed something,['java'] +175077,what does category in the manifest mean the documentation says you can specify a custom category when why and how would you do it what would be the use of it,['android'] +175080,android async handler or timer every 5 seconds i want to call my webservice and get text not images then thisplay it in my imageadapter what would be the best way to accomplish this,['android'] +175082,which maximum does python pick in the case of a tie when using the max function in python to find the maximum value in a list or tuple dict etc and there is a tie for maximum value which one does python pick is it randomthis is relevant if for instance one has a list of tuples and one selects a maximum using a key based on the first element of the tuple but there are different second elements how does python pick which one to pick as the maximumi am working in python v26,['python'] +175108,entity framework losing sql datetime precision i am querying my edm using entity sql and am losing millsecond precision on my datetime values for example 2011720 1255153 pm gets changed to 2011720 1255150 pmi have confirmed that in sql the milliseconds are recorded preciselythere is a precision attribute i can apply in the edmx xml file but i do not know what sort of values it takes property nametimestamp typedatetime nullablefalse precision does anyone know how to use this precision attribute thanks,['c#'] +175121,how to replace with and with using jquery i have a page that is part of a backend crm admin panel on that page the html output comes from some php functions that i cannot access and that html automatically changes and into html encoded charactersso there is a div that contains html tags like br that is converted into ltb gtso i need to change it back to the html characters using only jquerylt to gt to is there a jquery script i can use to replace those special characters with the corresponding symbols this will mean my html tags will actually work and the html will being thisplayed properly on the screeni have tried removewith but i cannot make it workaddedthe div that im trying to modify is thisdiv stylefontsize 11px width 90 fontfamily tahoma idcotizltstronggtvaluacia3nltstronggt de infoauto 3550ltbr gt cotizacia3n seleccionada ningunaltbr gt allianz responsabilidad civil 20525ltbr gt allianz terceros completos 27885 div,['jquery'] +175129,how to create a uitextview that automatically wraps lines of text i am creating an app that creates a uitextview programmatically the problem is when the user types in text or the app sets the text the words spread across one line and off the screen rather than wrapping to the next line when i create a uitextview with interface builder the text wraps automatically but not when it is created programmaticallycodeuitextview textview uitextview alloc initwithframecgrectmake100 12 210 60self view addsubviewtextviewtextview becomefirstresponder,['iphone'] +175131,spring and passing parameters to factorymethod in runtime the documentation of method contextgetbeanname user saysallows for specifying explicit constructor arguments factory method argumentsbut no matter what i do tried everything with the most logical setting i get this when the beans are being loaded up during initializationorgspringframeworkbeansfactoryunsatisfieddependencyexceptionerror creating bean with name filevalidator defined inportletcontext resourcewebinfclassescontextcustomerformportletxml unsatisfieddependency expressed through constructor argument with index 0 of typecomliferayportalmodeluser ambiguous factory method argumenttypes did you specify the correct bean references as factory methodarguments orgspringframeworkbeansfactoryunsatisfieddependencyexceptionerror creating bean with name filevalidator defined inportletcontext resourcewebinfclassescontextcustomerformportletxml unsatisfieddependency expressed through constructor argument with index 0 of typecomliferayportalmodeluser ambiguous factory method argumenttypes did you specify the correct bean references as factory methodargumentsbean idfilevalidator classczinstancetranslvalidationfilefilevalidator factorymethodcreateinstance private filevalidatoruser user thisuser userpublic static filevalidator createinstanceuser user return new filevalidatoruserthe commentary says you can do it but if you specify constructor arguments in xml definiton of that bean or not it fails,['java'] +175140,should we use constexpr everywhere we can we obviously cannot make everything constexpr and if we do not make anything constexpr well there would not be any big problems lots of code have been written without it so farbut is it a good idea to slap constexpr in anything that can possibly have it is there any potential problem with this,['c++'] +175143,oracle db javasqlsqlexception closed connection reasons for javasqlsqlexception closed connection from oraclejavasqlsqlexception closed connection at oraclejdbcdriverdatabaseerrorthrowsqlexceptiondatabaseerrorjava112 at oraclejdbcdriverdatabaseerrorthrowsqlexceptiondatabaseerrorjava146 at oraclejdbcdriverdatabaseerrorthrowsqlexceptiondatabaseerrorjava208 at oraclejdbcdriverphysicalconnectioncommitphysicalconnectionjava1131 at oraclejdbcoracleconnectionwrappercommitoracleconnectionwrapperjava117we are getting this error from the fail over database connection we use the same code for other databases as well but seeing this issue with only one of the databases is this because the connection might have timeout due to long inactivity period and we are trying to use that pls let me know if you need more detailsabandonedconnectiontimeout set to 15 minsinactivitytimeout set to 30 mins,"['java', 'sql']" +175188,circular function pointer question in c i am trying to figure out how to declare a function that returns a pointer to a function that returns a function it is a circular problem and i do not know if this can be done in c this is an illustrative example of what i am trying to do it does not worktypedef void fpvoidfp funkavoid return funkbfp funkbvoid return funka,['c'] +175198,find out time it took for a python script to complete execution i have the following code in a python scriptdef fun code herefuni want to execute this script and also find out how much time it took to execute in minutes how to find out how much time it took for this script to execute some example would be really appreciatedthank you,['python'] +175209,getting the address of a pointer my apologies i know there are a million questions on pointers arrays etc although as basic as this is i just cannot seem to find anything pointing ha ha to an answeri have got a pointer that is initialised to point to a chunk of memory i understand that i can access this memory similar to how i would an arraychar mmemnew char50coutmmem5endlwhich is actuallychar mmemnew char50coutmmem5endlwhat i do not understand though is how to get the address of an element i am aware that element is not quite the right word considering mmem is not an array that is if my understanding is correct cannot be too sure though because it seems every site uses whatever words it wants when it comes to pointers and arrays so if i havechar mmemnew char50coutmmem5endl orcoutmmem5endlwhy does the address of operator not work correctlycoutmmem5endlinstead of getting the address of the 5th element i get a print out of the memory block contents from that element onwards so why did the address of operator not work as i was expecting and how can i get the address of an element of the memory,['c++'] +175211,c generics class factory question i want to control the creation of a bunch of classes that all share a common interface and all need a bit of logic in the construction also i do not want any other code than the class factory to be able to create objects from these classesmy main stumbling blocks are1 for the generic method to be able to create instances of the classes i need the new constraint which means i must have a public constructor on the classes which means they can be created publicly2 an alternative would be for the classes themselves to have a static method which returns an instance of the class but i cannot call that from my generic class because i need to be dealing in terms of interfacestypes and you cannot have statics via interfacesheres the kind of thing i have currently got but it is using the new constraint which is allowing my classes to be created publiclyinternal static class myclassfactory internal static t createtstring args where t imytype new imytype newthing new t newthinginitialisestring args return tnewthing public interface imytype void initialisestring argspublic class thinga imytypepublic void initialisestring args do something with argsany help greatly appreciated,['c#'] +175263,nhibernate and operator overloading public class version public byte major get set public byte minor get set public short build get set public int revision get set private long numversion get set some logic that make int64 number that represents this verion suppose i want to be able to write queries likewhereproductversion new version1200in product table i store only int64 numversion field so version property is mapped as component and currently i query it like whereproductversionnumversion new version1200numversionin c i can 1 overload comparison operators 2 make it implicitly casted to long likepublic static implicit operator longversion v return vnumversionthis will allow me to compare version objects but how to make nhibernate understand this and generate proper sql,['c#'] +175291,symfony2 how to switch from dev to prod i downloaded symfony2 and i am able to run it starting from app devphpbut when i start from aphp then i get an error page 404aphp though is of course there and it gets executedthe error happens apparently somewhere after the last line of code in aphpkernelhandlerequestcreatefromglobalssendi guess there is a switch somewhere i have to configureeditas suggested by gelo i added the routing for the production version to appconfigroutingyml welcome resource acmedemobundleresourcesconfigroutingyml prefix i created srcacmedemobundleresourcesconfigroutingyml with contentbla pattern defaults controlleracmedemobundledemoindexin democontrollerindexaction i placed a die file nothing i still get 404 from aphp edit regarding the answerappconsole envprod cachecleardid the trick mind the envparameter,['php'] +175297,how to convert latitude longitude into cllocationcoordinate2d i want to convert lat lon to cllocationcoordinate2dselfcurrentlocation latitude 00 longitude 00this gives me error expected expressionwhat am i doing wrong,"['objective-c', 'iphone']" +175300,the type x in xcs conflicts with the imported type x what is causing this build errorthe type arialibraryariablbook in iprogramingmyprogramlibraryarianetdelijancorporationarialibraryariablariablcsconflicts with the imported typearialibraryariablbook iniprogramingmyprogramlibraryarianetdelijancorporationarialibrarybindebugarialibraryexeusing the type defined in iprogramingmyprogramlibraryarianetdelijancorporationarialibraryariablariablcsiprogramingmyprogramlibraryarianetdelijancorporationarialibraryuidocumentbookfrm addnewbookisocs 24 16 arialibrary,['c#'] +175302,parsing objectivec code for static analysis i love static analysis and compiletime checks almost to a fault but most of my day job is in objectivec to resolve this tension i would like to be able to write my own analysis tools that i can run on my objectivec projectsbut googling around the internet suggests that people are having a hard time putting together a complete objectivec grammar one site basically recommends giving upi did find a grammar on the antlr website but when i fired it up i could not get it to parse anything at all for example it responded to the linevoid xwith srcmainresourcessomecodem line 10 no viable alternative at input voidi took a closer look at the grammar and found the following thisheartening thisclaimerit is a work in progress most of the h file can be parsedbut i need something that can parse both interface and implementationis there a complete objectivec 20 grammar out there somewhere i would prefer something that can work with scala so anything java compatible like antlr would be perfect but at this point i would be willing to adapt something designed for another parser toolkit,['objective-c'] +175320,convert php date to mysql format i have a date field in php which is using this code date mysql real escape string postintake datehow do i convert this to mysql format 0 for inclusion in db is it along the lines of dateymd strtotimedate the reason i ask is because i have tried variations of this and i cannot seem to get it to work either thisplays as 1970 or some other variation of that many thanks,"['php', 'mysql']" +175333,delegate covariance and contavariance consider the following code snippetnamespace consoleapplication1public delegate tresult functionin t out tresultt args class program static void mainstring args program pg new program functionobject derivedclass fn1 null functionstring baseclass fn2 null fn1 new functionobject derivedclasspgmycheckfuntion fn2fn1 fn2 calls mycheckfuntionobject a pgmycheckfuntionhello calls mycheckfuntionstring a public derivedclass mycheckfuntionobject a return new derivedclass public derivedclass mycheckfuntionstring a return new derivedclass why the delegate call and normal method invocation call different methods,['c#'] +175337,if cin x why can you use that condition i have been using accelerated c to learn c over the summer and there is a concept which i do not seem to understand properlywhy isint xif cin xequivalent tocin xif cinby looking at the code it seems to me that were using cin as a variable but i thought it was a function why can we use cin in this way when it is x that has whatever value we input into our keyboard,['c++'] +175354,how to get biggest bigdecimal value how can i get the largest possible value of a bigdecimal variable can hold preferably programmatically but hardcoding would be ok tooeditok just realized there is no such thing since bigdecimal is arbitrary precision so i ended up with this which is sufficiently good for my purposebigdecimal my bigdecimalvalueofdoublemax value,['java'] +175361,network device thiscovery for my android app users need to connect to a server that will be hosted somewhere on the same lan there can be multiple servers hosted on the same lan to make it easy for the user i was going to scan the current lan that the android device is connected to and then list all of the network devices that have the server running on it rather than having the user input the ip to the computer manually i am fairly new to networking and after some searching i found out that i would have to use a multicast dns search or udp broadcast to detect the other devices i also found a nice library called jmdns although i have found very few documentation and sample code on it could somebody point me in the right direction for what i am trying to do to save me wasted time mostly if i am on the right track i am assuming that i will have to modify my server a bit to broadcast it is there it works completely as intended if i input the ip manually into the configuration page on my app also this only needs to thiscover windows computers not sure if that matters thanks in advance,['android'] +175379,how do i share a global variable between c files if i define a global variable in a c file how can i use the value of the same variable in another c filefile1cincludestdiohint i10int mainprintfdireturn 0file2cincludestdiohint mainsome data regarding iprintfdireturn 0how can the second file use the value of i from the first file here,['c'] +175381,editing ms office documents from a web application custom webdav implementation or following is our setup requirementthere is a public web application accessible via ssl basic authentication most of these applications are in aspnet couple of legacy ones are in classic asp server is win 2003 iis 60this application needs to support online editing of mostly ms office documents 2007 2010 the documents themselves are stored in the database along with the content of the applicationthe users should be able to open the document via html links the corresponding external office application say ms word should open the document in edit mode with exclusive lock and when the user presses save button the document should be posted back to the applicationpreferably no external pluginsactivex controls need to be deployed on the client sideis a custom webdav implementation the best possible approach note that we might not need all the features of webdav for supporting above requirements are you aware of any alternativesif custom webdav implementation is the way to go can you please recommend some good resources commercialopen source iis plugins samples in net docs etc apart from btw i do not prefer installing a bulky cms like sharepoint to support such a small requirementi found a thread on so about custom webdav implementation what are your experiences implementingusing webdav it sounds so thiscouraging avialable only on iis root requires windows authentication etcthanks in advance,['asp.net'] +175388,horizontally centre a ul inside a div i have a div with a ul inside i want to center the ul horizontally of the screen the full code of the project can be found here jsfiddlei have tried usingmargin 0 auto after setting the width of course textalign center ran out of ideas i also tried relative positioning and setting instead of px but this doesnt give me exact centre of the screen and also if i added more items to the menu it wouldnt be center after including them items using a my full code is in jsfiddle for all you to tinker withi have pasted some of the what i think is relevant code below for your convenience css mainulnav thisplay inlineblockpadding 0px liststyletype none whitespace nowrapposition relativetop 10pxleft 10 this is what im currently using but as thought it doesnt work as needed border 2px solid chocolatemozborderradius 10px border radius for mozilla firefox borderradius 10px border radius for everything elseulnav li float left fontfamily myraid pro arial helvetica sansserif use available font for menu fontweight bold margin 0 padding 5px 0 4px 0 backgroundcolor ee8043 background colour for the lipadding 5px padding for the li mozborderradius 8px border radius for mozilla firefox borderradius 8px border radius for everything else html div idheader a hrefindexhtmlimg idlogo srcimagesdafne logopnga div idnavbar ul idnav lia hrefindexhtml relhomehomeali li classmenu separatorli lia hrefindexhtmlnewsali li classmenu separatorli lia hrefforumshtmlforumsali li classmenu separatorli lia hrefsignup4327htmlto252fsignupali li classmenu separatorli lia hreflogin4327htmlto252floginali li classmenu separatorli ul div div div idcoloured bardivso basically i want to center the nav which is contained within the navbar which is contained within the header,"['css', 'html']" +175406,fixed position but relative to container i am trying to fix a div so it always sticks to the top of the screen usingposition fixedtop 0pxright 0pxhowever the div is inside a centered container when i use positionfixed it fixes the div relative to the browser window such as it is up against the right side of the browser instead it should be fixed relative to the containeri know that positionabsolute can be used to fix an element relative to the div but when you scroll down the page the element vanishes and does not stick to the top as with positionfixedis there a hack or workaround to achieve this,['css'] +175422,how does file encoding affect c11 string literals you can write utf81632 string literals in c11 by prefixing the string literal with u8uu respectively how must the compiler interpret a utf8 file that has nonascii characters inside of these new types of string literals i understand the standard does not specify file encodings and that fact alone would make the interpretation of nonascii characters inside source code completely undefined behavior making the feature just a tad less usefuli understand you can still escape single unicode characters with un but that is not very readable for say a full russian or french sentence which typically contain more than one unicode characterwhat i understand from various sources is that u should become equivalent to l on current windows implementations and u on eg linux implementations so with that in mind i am also wondering what the required behavior is for the old string literal modifiersfor the codesample monkeysstring utf8string a u8lha tel de ville doit aatre la bas aa cest un faitstring utf16string b ulha tel de ville doit aatre la bas aa cest un faitstring utf32string c ulha tel de ville doit aatre la bas aa cest un faitin an ideal world all of these strings produce the same content as in characters after conversion but my experience with c has taught me that this is most definitely implementation defined and probably only the first will do what i want,['c++'] +175441,nginx 403 forbidden for all files i have nginx installed with phpfpm on a centos 5 box but am struggling to get it to serve any of my files whether php or notnginx is running as wdatawdata and the default welcome to nginx on epel site owned by rootroot with 644 permissions loads finethe nginx configuration file has an include directive for etcnginxsitesenabledconf and i have a configuration file examplecomconf thusserver listen 80 virtual host name server name wexamplecom examplecom location root homedemositesexamplecompublic html index indexphp indexhtm indexhtml location php fastcgi pass 12700190 fastcgi index indexphp fastcgi param path info fastcgi script name fastcgi param script filename homedemositesexamplecompublic htmlfastcgi script name include fastcgi params despite public html being owned by wdatawdata with 27 file permissions this site fails to serve any content error 41670 4 open homedemositesexamplecompublic htmlindexhtml failed 13 permission denied client x server wexamplecom request get indexhtml http11 host wexamplecomi have found numerous other posts with users getting 403s from nginx but most that i have seen involve either more complex setups with rubypassenger which in the past i have actually succeeded with or are only receiving errors when the upstream phpfpm is involved so they seem to be of little helphave i done something silly here,['php'] +175442,html templating solution for both aspnet mvc and browser i am trying to find an html templating solution that will work both on my aspnet mvc application net 4 iis 75 and in the browser the reason is to the the same code to render html both on the server performance outputting to mobile etc or on the browser refreshing data via ajax this is not a new problem but i am wondering if current technology trends have changed the answera couple of ideas i am consideringuse mustache templates with are available in bothjavascript and netuse a port of the razor view engine tojavascript like considered in javascript razor jazortake a position like micro templates are dead forget about it andjust use javascript ironjs and the dom jsdomaspnet mvc view engine comparison looked relavent but there is no mention of mustacheupdate the clientside templating throwdown mustache handlebars dustjs and more from linkedin engineering rates mustache in it is top four with it being the only one with native net rendering vs requiring serverside javascript to render on the server,['javascript'] +175450,why use ikernel over iwindsorcontainer i have seen in several code examples where people have used ikernel rather than use iwindsorcontainer why is this here is one example skwaa14uzdj55gv55dzgf0vuiwindsorwindsortutorialparttwopluggingwindsorinashxin the above example it came to bite me because i added a subresolver containerkernelresolveraddsubresolver new collectionresolvercontainerkernel truethat will allow me to inject collections but yet it wasnt working i figured out that because just the ikernel was being used it couldnt use the full features of windsor why would someone ever want to use the kernel over the full container i think if you are going to implement windsor use the full container am i wrong why,['c#'] +175459,weird use of in typeid code in one of the projects i am working on i am seeing this codestruct base virtual base struct classx bool isholdingderivedobj const return typeid1 m baseptr m baseptr typeidderived base m baseptri have never seen typeid used like that why does it do that weird dance with instead of just doing typeidm baseptr could there be any reason base is a polymorphic class with a virtual destructor edit at another place of this code i am seeing this and it appears to be equivalently superfluoustemplatetypename t t nonnullt t return t struct classy bool isholdingderivedobj const return typeidnonnullm baseptr typeidderived base m baseptr,['c++'] +175479,polymorphism c in some books there is written that class that declares or inherits a virtual function is called a polymorphic classclass b does not have any virtual functions but passes more than one isa testclass c has one virtual function but does not inheritclass a class b public a class cpublic virtual void f is class b or c polymorphic,['c++'] +175500,aspnet mvc cookie implementation i try to implement a basic cookie helper in my applicationmainly i check in base controller everytime whether or not if cookie is setif cookie public class mycookie public static string cookiename getset public virtual user user get set public virtual application app get set public mycookieapplication app cookiename mycookie app app app public void setcookieuser user httpcookie mycookie httpcontextcurrentrequestcookiescookiename new httpcookiecookiename mycookievaluesuserid useruseridtostring mycookievalueslastvisit datetimenowtostring mycookieexpires datetimenowadays365 httpcontextcurrentresponsecookiesaddmycookie public httpcookie getcookie httpcookie mycookie httpcontextcurrentrequestcookiescookiename ifmycookie null int userid converttoint32mycookievaluesuserid user user sessiongetuseruserid return user return null if session is null i try to get from cookie or if session initialize i set cookie but i never see my cookie in browser what is wrongi always start session but with userid0to get cookie and set session from cookieif userid 0 mycookie mycookie new mycookie app user user cookiehelpergetcookie if user null sessionhelpersetsessionuser,"['c#', 'asp.net']" +175516,javascript clear dom i am wanting to completely clear the dom with javascripti have tried a few things like thisdocumentgetelementsbytagnamehtml0innerhtml documentbodyinnerhtml interestingly clearing the head like this will generate an error invalid target element for this operation in ie but will successfully clear the head in chrome however clearing the body like this works in ie but fails silently in chromei have also trieddocumentchildnodeslength 0but this is apparently a readonly property and would not do anythingis there a good crossbrowser way to clear the dom,"['javascript', 'html']" +175551,script all data from sql server database i have two databases with equivalent structure and i need to extract data from one of them in form of insert statements generate script to apply it on the other database how can i do it using management studio,['sql'] +175560,can a pointer to a string be used in a printf i am thinking of something likeinclude stdiohinclude coniohinclude stdlibhint mainvoid test pointer to string char s50 char ptrs printfnenter string s fgetss 50 stdin printfs snptr sn s ptr systempause return 0or should i use a for loop with si and the format specifier cis that the only possible way to print a string through a pointer and a simple printfupdate the printf operates with the adress of the first element of the array so when i use ptr i actually operate with the first element and not it is adress thanks,['c'] +175579,python string concatenation concatenating n i am new to python and need help trying to understand two problems i am getting relating to concatenating strings i am aware that strings can be added to concatenate each other using symbol like so a babhowever i just recently found out you do not even need to use the symbol to concatenate strings by accidentfiddling around which leads to my first problem to understand howwhy is this possible print a babfurthermore i also understand that the n string produces a newline but when used in conjunction with my first problem i get the following print n a7aso my second problem arises why do i get 7 new lines of the letter a in other words should not the repeater symbol repeat the letter a 7 times as follows print a7aplease help me clarify what is going on,['python'] +175595,what are the rules for evaluation order in java i am reading some java text and got the following codeint a 44int b 1ab b 0in the text the author did not give a clear explanation and the effect of the last line is a1 0i am not so sure that i understand how did the evaluation happen,['java'] +175600,smooth transition between two class and classhover is there a scriptway that makes normal css hover more smoothidea would be that you got two classes maybe with gradient backgrounds and the script would smoothly swap the classes so the gradients would look like your pressing a button should be automatic so you call the trigger someclasmoothtransition and it would automatically use the someclasshover as the second classbounty editthis is actually a very interesting question that got a partial answer by me the problem with my answer is that it works only for solid background color and does not work with css gradients or any other more specific parameterthis script should be a musthave in any jquery developers library so i am offering 150 rep to anyone who can think of a way or find good resource that can do thisif your method single jquery plugin works for all these examples then you have wonexamples modern days editsince this question was asked in 2011 when css transition is commercial game was not an option then understand why everything is focused on js and not css in this question from these answers i developed a js script that was at the time perfect its not anymore css transitions are the ultimate solution now so the proper answer got reaccepted,['jquery'] +175604,how does jquery live work i was thinking about performance regardingclick vs liveclickand that left me wondering about how live does workdoes it monitor dom changes and when it detects a change in the dom it just attaches the event then does it use some sort of timer i wouldnt think so but if it did this is very important timers make me a sad person,['jquery'] +175614,why do constructors in java not have a return type possible duplicatewhy constructor not returns value why do not constructors have a return type not even void whats the reason for that,['java'] +175632,why use services iserviceprovider i am coming to this question from exploring the xna framework but i would like a general understandingisomeservice someservice isomeservicegamegetservicestypeofisomeserviceand then we do something with whatever functionsproperties are in the interfacesomeservicedosomething let us say not a static method but does not matteri am trying to figure out why this kind of implementation is any better thanmyobject instancefromcomponentthatwouldprovidetheservicemyobjectdosomethingwhen you use the services way to get your interface youre really just getting an instance of the component that provides the service anyway right you cannot have an interface instance and there is only one class that can be the provider of a service so all you really have is an instance of your component class with the only difference being that you only have access to a subset of the component object whatever subset is in the interfacehow is this any different from just having public and private methods and properties in other words the public methodsproperties of the component is the interface and we can stop with all this roundaboutness you can still change how you implement that interface without breaking anything until you change the method signature but that would break the services implementation tooand there is going to be a 1to1 relationship between the component and the service anyway more than one class cannot register to be a provider of the service and i cannot see a class being a provider of more than one service srp and all thatso i guess i am trying to figure out what problem this kind of framework is meant to solve what am i missing,['c#'] +175636,sql server how to get current date time in ymmddhhmissmss i need the current date time in the format ymmddhhmissmis example 20110723233747607by using the current timestamp or getdate functions we can retrieve the current datetime into 20110723 233747607 format if i use replace and convert functions to remove the and characters then i get the value into jul 23 2011 1137pmformat but i need the current date time as 20110723233747607 to use it for my another purposemy sql query is select replaceconvertvarchar20 current timestampoutput jul 23 2011 1137pmso how can i get the current date time in my required format pls help,['sql'] +175644,mac user and getting warning nokogiri was built against libxml version 278 but has dynamically loaded 273 i have done all kinds of research and tried many different things i know this question has been answered many times but none of the suggested solutions are working for meafter upgrading to lion i am getting segmentation faults in ruby i am fairly confident it is nokogiri so i installed libxml2 via homebrew i ran brew link libxml2 then i reinstalled nokogiri using that version of the libraryfor proof nokogiri v nokogiri 150warnings nokogiri 150ruby version 192 platform x86 64darwin1100 description ruby 192p290 20110709 revision 32553 x86 64darwin1100 engine rubylibxml binding extension compiled 278 loaded 278i have already included nokogiri at the top of my gemfile and i have also required it in my environment file i have no idea why i am still getting that warningany suggestions or ideas to make sure it is loading the right version libxml2,['ruby'] +175648,autotest problem i just installed zentest 446 which includes autotest 446 and when i run autotest i get the following errorgemszentest460libautotestrb226in autothiscover undefined method any for gemspecificationclass nomethoderrorhuh it is like it reverted back to ruby without rails,['ruby-on-rails'] +175652,what view component does the google plus app stream use if you use the google plus app on android and switch to the stream you get a view where you can swipe to the left and right between the all circlesincomingnearbystream what view component is used for this is this a standard android component or where can i find democode how i can build such a view component,['android'] +175660,content vs content none i was reading through eric meyers css reset and saw thisblockquotebefore blockquoteafterqbefore qafter content content nonei assume that some browsers support content and some content none is this the case and which browsers support which,['css'] +175667,net directoryexists denies existence of mapped network drive when running as admin i am writing a small net program on windows 7 one thing it needs to do is to create symbolic links which seems to require me to have administrator privileges it also needs to be able to work with mapped network drives for example r which on my system maps to titaniumprivatei am using directoryexistspath to verify that a path existswhen running the program as a regular user administrator account but not as administrator this works fine on the mapped network drivewhen running the program as an administrator with uac it fails to find directories that exist as a result the program refuses to acknowledge that rsteam games is a directory that actually existsi am a bit baffled as to why this is happening using the full unc path titaniumprivatesteam games also does not workhas anyone run into this before is there any good workaround do i have to format the paths different note most of them are currently formatted with pathcombine so they should be correctthanks for your helpas an example directoryexistsrsteam games returns false when running as an admin but that folder exists the function call correctly returns true when running regularlyedit the issue indeed appears to be that an administrator is technically a different user account i could not even use unc paths because i was only logged in to my fileserver under my regular user not under administrator as a relatively hackish workaround i just run my program with regular privileges and then use procestart to invoke an instance of cmdexe with the arguments to create a symbolic link and verb runas to get the uac prompt,['.net'] +175684,how do i repeat a avaudioplayer i am just wondering how you repeat a avaudioplayer,['iphone'] +175688,how best to inherit from native javascript object especially string i am a longtime browser but a first time participator if i am missing any etiquette details please just let me knowalso i have searched high and low including this site but i have not found a clear and succinct explanation of exactly what i am looking to do if i just missed it please point me in the right directionalright i want to extend some native javascript objects such as array and string however i do not want to actually extend them but create new objects that inherit from them then modify thosefor array this worksvar myarray function n thispushn thisa function alertthis0 myarrayprototype arrayprototypevar x new myarrayfooxahowever for string the same does not workvar mystring function n this n thisa function alertthis mystringprototype stringprototypevar x new mystringfooxai have also triedmystringprototype new stringnow in trying to research this i have found that this does workvar mystring function n var s new stringn sa function alertthis return svar x mystringfooxahowever this almost feels like cheating to me like i should be using the real inheritance model and not this shortcutso my questions1 can you tell me what i am doing wrong as regards inheriting from string preferably with a working example2 between the real inheritance example and the shortcut example can you name any clear benefits or detriments to one way over the other or perhaps just some differences in how one would operate over the other functionally because they look ultimately the same to methanks alleditthank you to everyone who commentedanswered i think cmss information is the best because1 he answered my string inheritance issue by pointing out that by partially redefining a string in my own string object i could make it work eg overriding tostring and tovalue2 that creating a new object that inherits from array has limitations of its own that werent immediately visible and cannot be worked around even by partially redefining arrayfrom the above 2 things i conclude that javascripts claim of inheritablity extends only to objects you create yourself and that when it comes to native objects the whole model breaks down which is probably why 90 of the examples you find are petdog or humanstudent and not stringsuperstring which could be explained by chjjs answer that these objects are really meant to be primitive values even though everything in js seems to be an object and should therefore be 100 inheritableif that conclusion is totally off please correct me and if it is accurate then i am sure this is not news to anyone but myself but thank you all again for commenting i suppose i now have a choice to makeeither go forward with parasitic inheritance my second example that i now know the name for and try to reduce its memoryusage impact if possible or do something like davin jeff or chjj suggested and either psudoredefine or totally redefine these objects for myself which seems a wastecms compile your information into an answer and i will choose it,['javascript'] +175695,ios devices as web server i saw there are several apps on app store that allow other computers to make a http connection to the iphoneipad devices to transfer files it seemed like a web service is running on the ios device just curious how is it done what class was usedthanks,"['iphone', 'objective-c', 'ios']" +175710,possible bug in mkmapview if i create a viewcontroller with a map view and this is the only code i add to viewdidloadmkpointannotation annotation mkpointannotation alloc initannotationcoordinate cllocationcoordinate2dmake90 180selfmapview addannotationannotationselfmapview removeannotationannotationannotation releasei get the erroran instance 0xa126fa0 of class mkpointannotation was deallocated while key value observers were still registered with it observation info was leaked and may even become mistakenly attached to some other object set a breakpoint on nskvodeallocatebreak to stop here in the debugger heres the current observation infonskeyvalueobservationinfo 0xa127df0 nskeyvalueobservance 0xa127c90 observer 0xa11c530 key path coordinate options new no old no prior yes context 0x0 property 0xa127640if i change the code to this then i do not get any errorsmkpointannotation annotation mkpointannotation alloc initannotationcoordinate cllocationcoordinate2dmake0 0selfmapview addannotationannotationselfmapview removeannotationannotationannotation releasethe only difference is that 00 is visible in the map where as 90 180 is out of view that is i need to pan the map to bring coordinate 90 180 into viewanyone experienced this error before or even better know how to fix it,"['iphone', 'ios']" +175720,populate drop down in mfc i am trying populate a combo box in mfc application with no luck i have tried all the methods available on internet but none seems to work for me if i try to enter the values using data option in property windows like value 1 value 2 only value 2 thisplays in combo box if i try to add it using comboxboxaddstringvalue 1i get left side of addstring must have classunionstructi am using visual studio 2008,['c++'] +175730,how do i access php rest api put data on the server side answer after help and homework i am new so i cannot answer my own question until after 8 hours odd okay after working with the great people here i have to say we ran into the answer i am kicking myself for it being so easy at the same time it was confusingcurl setopthandle curlopt customrequest putcurl setopthandle curlopt postfields http build querydatathe first change above i had to add http build query around data this took my data from an array to a url friendly stringnext up i had to addparse strfile get contentsphpinput putnow i can do things like putdatathe answer paulpro gave above does work to get the data the same way file get contents did with less lines we got stuck trying to figure out how to parse the data which was where my lack of http build query i had seen on another site kicked into playso this is how it all worksdata is put into a normal arrayhttp build query converts it into a nice almost get like stringfile get contents transports it from the client to the serverparse str then turns it back into an arrayi am seeing a lot of messages about using put to send files i can see how this would work but from what i read in this entire rest process was that put is to update data as post is to create data maybe i am mistaken am i missing something question i am just starting out with the rest api and am getting pretty confusedthis is what my php crul clientside looks like for a putcase put curl setopthandle curlopt customrequest put curl setopthandle curlopt postfields data breaknow when i look at the server my serverrequest method shows put but my question is how do i get the data i sent with curlopt postfieldsall i need to do is get the data sent with a put request into the next line likevalue datacurl datai have seen so much clutter on this topic that it is giving me a headache it seems so easy on the php client side but no one has answers that are working for the php server sidethanks for any help,['php'] +175731,redirecting standard output in c then resetting standard output i am trying to use redirects in c to redirect input to one file and then set standard output back to print to the screen could someone tell me whats wrong with this codeinclude stdiohinclude fcntlhinclude unistdhint mainint argc char argv create file test if it does not exist and open for writing setting permissions to 7 int file opentest o creat o wronly 07 create another file handle for output int current out dup1 printfthis will be printed to the screenn ifdup2file 1 0 fprintfstderr could not redirect outputn return 1 printfthis will be printed to the filen ifdup2current out file 0 fprintfstderr could not reset outputn return 1 printfand this will be printed to the screen againn return 0,['c'] +175742,how to install tomcat plugin in eclipse i am using eclipse as my sdk for web project and i need tomcat integration with eclipse i am on my ubuntu machine how can i do the integration stuff how and from where i can download and install tomcat plugin,['java'] +175775,how to create a ui like the new market or google plus i was wondering if there is an official way to create apps for android that will have the same design as the new android market or google app by that i mean having the possibility to slide to the leftright to change the view have the list on the top etc any android user probably get what i meanif there is no official way do you have any tips on how to reproduce these effets,['android'] +175776,operation priority in java an object instantiates and runs before the gui is updated i want the gui to change the title of a button from go to working before an object is instantiated and actually does the work when finished i want the title of the button to switch back to goheres the code private class convert implements actionlistener public void actionperformedactionevent e jbutton button jbuttonegetsource buttonsettextworking buttonsetenabledfalse anobject name new anobject boolean result namemethodnamechoosergetselectedfileencoding a bunch of stuff was here but irrelevant to the question so it was removed to save room buttonsetenabledtrue buttonsettextgo what actually happens in practise is name is instantiated methodname gets called and then the button gets updated on the screen despite the fact that i have told the vm to change the button title firstmy working theory is given i have not made this program threaded this has something to do with operational priority or internal threading of the jvm or somethingany suggestions,['java'] +175777,when to use nsenumerationconcurrent every now and then i notice that i am using a block to iterate over a collection without writing to any shared data or causing any side effects i consider adding in an nsenumerationconcurrent option then decide against it as i do not really understand when it is worth usingso i have got a specific question and a more general onefirst question heres a maybe slightly contrived example of using a block to do something trivial concurrentlycgfloat getaverageheightnsarray people nsuinteger count people count cgfloat heights mallocsizeofcgfloat count people enumerateobjectswithoptions nsenumerationconcurrent usingblock id person nsuinteger idx bool stop heightsidx person height cgfloat total 00 for size t i 0 i count i total heightsi freeheights return total countignoring the fact that a nonconcurrent enumeration could have just summed the height directly without the need for calling malloc or the second half of the function is there any point using nsenumerationconcurrent here does the overhead of using gcd or whatever nsenumerationconcurrent does in the background negate the gain of getting a trivial property concurrently how much less trivial does the blocks work need to get before it is worth using nsenumerationconcurrentsecond question more generally should i consider concurrency to be something i should use when i see an opportunity to do so rationale presumably the point of these apis is that they make concurrency less of a special case and more part of the general makeup of a program or just an optimisation that i should only use if i have found a specific performance issue and believe that concurrency is the answer rationale bugs in concurrent code are a nightmare to track down,['objective-c'] +175781,how to escape a json string to have it in a url using javascript i want to generate a link to a page the parameters to the page are in a javascript array that i serialize in jsonso i would like to generate a url like that my json array herehow do i need to escape my json string array serialized to include it as a parameter in a url if there is a solution using jquery i would love itnote yes the parameters to the page need to be in an array because there are a lot of them i think i will use bitly to shorten the links afterwards,"['javascript', 'jquery']" +175782,what syntax for including subpackages in i am using spring and i have a long list of subpackages do i have to specify them one by one in the contextcomponentscan tagcontextcomponentscan basepackagecomfooappmainpackage comfooappmainpackagesubpackage1 comfooappmainpackagesubpackage2 comfooappmainpackagesubpackage3,['java'] +175787,how to write a class that like array can be indexed with arrkey like we do sessionaddloginuserid 123and then we can access sessionloginuserid like an array how do we implement it,"['c#', '.net']" +175811,how bind datatable to datagrid this is my datatable datatable simpledatatable new atatable var person new datacolumnperson datatype typeof person simpledatatablecolumnsaddpersonvar student new datacolumnstudent datatype typeof student simpledatatablecolumnsaddstudent var dr1 simpledatatablenewrowdr10 new person personid 1 personname tonydr11 new student studentid 1 studentname tony simpledatatablerowsadr1var dr2 simpledatatablenewrowdr20 new person personid 2 personname mal dr21 new student studentid 2 studentname mal simpledatatablerowsadr2plaase tell me how to bind above type of datatable,['c#'] +175824,prevent losing form data by navigating away from page i am creating a datagrid with hundreds of rows which contain a checkbox on each row so that the user can select an item from the gridnow the user may spend a great deal of time going filteringsearching through the grid and ticking the required checkboxes only to accidentally press the backspace key on their keyboard or click on a hyperlink on the page and they would lose all their checkbox selectionsso i want to introduce some functionality whereby if at least one checkbox has been ticked then if the user unintentionally does an action that would navigate them away from the page then a javascript confirm message is thisplayed to notify the user of thisthe checkboxes would all belong to the same group for instance it would be called productsis this possible to do at all,"['javascript', 'jquery']" +175827,what is the best resourceguide for understanding new storyboard feature in xcode 42 i can see completely new feature called storyboard in new xcode 42 inteface builderwhere can i find good guide helping to deeply understand this feature,['iphone'] +175858,merging a python scripts subprocess stdout and stderr while keeping them thistinguishable i would like to direct a python scripts subprocess stdout and stdin into the same file what i do not know is how to make the lines from the two sources thistinguishable for example prefix the lines from stderr with an exclamation markin my particular case there is no need for live monitoring of the subprocess the executing python script can wait for the end of its execution,['python'] +175871,c not all code paths return a value try catch i am having a hard time figuring out how to get around the error with the below code in this case below i want to return the datatable inside the catch as null public static datatable dttablestring mysqlquery out datatable dttabletable try mysqldataadapter datadttables new mysqldataadaptermysqlquery connection datadttablesselectcommandcommandtimeout 240 datatable datadttablesdt new datatable datadttablesfilldatadttablesdt dttabletable datadttablesdt eventlogwriteentrystaticstringclasscrawlerid returning sucessful datatable query mysqlquery return dttabletable catch exception ex string messagestring could not fill database for query mysqlquery because of error exmessagetostring loggingclassgenericloggingmessagestring,['c#'] +175950,samsung smart tv app can we create apps for samsung smart tv in dot netif no which languages can we use to create them i guess adobe air is one,['.net'] +175954,changing a sql column title via query i have the following queryselect product descriptionname productquantityproductpriceproduct option value descriptionnameproduct option valuequantityfrom productinner join product descriptionon productproduct idproduct descriptionproduct idinner join product option value descriptionon productproduct idproduct option value descriptionproduct idinner join product option valueon productproduct idproduct option valueproduct idorder by product descriptionname how could i change the title for product option value descriptionname as i would like to name this option,"['mysql', 'sql']" +175972,uiscrollview custom paging size paging in uiscrollview is a great feature what i need here is to set the paging to a smaller thistance for example i want my uiscrollview to page less size that the uiscrollview frame widththanks,"['iphone', 'objective-c']" +175973,setting attributes of a property in partial classes i have an employee class generated by entity framework efpublic partial class employee private string name public string name getreturn name set name value now i want to put a required attribute in the name property to use in for mvc3 validation in another employee partial class which is written by me in order to extend the one which is generated by ef so that i do not have to rewrite my code if i refresh the model generated by efmy written partial class is in the same assembly and name spacepublic partial class employee what should i write here to add required attribute in the name property,['c#'] +175985,ruby markdown parser with wikiword support i am using gitwiki for my personal note storage it works very well except that wikiwords are converted to links before the markdown parsing stage using a regular expression this messes up scores of things for instance links that point to outside wiki pages or block quotes if i am quoting something i do not want a wikiword to be changed into a linkare there rubybased markdown parsers that understand wikilinks,['ruby'] +176011,does proguard remove unused code on android i was just wondering i am designing a library to use with my android projects now i am starting to include things like the apache ftp jar to support some debug file uploadsi know that not all projects will use all parts of the library eg some project will not have an ftp upload at all but wants to use the ui tools from the librarynow i got three questionsdoes proguard remove unsused sources own code like eg my ui tool classes if they are never references from the main project meaning not used in the applicationdoes proguard remove external libraries eg apache ftp jar if never used if not i may include the source if option 1 applieshow about resource files not really proguards job more intellij or eclipse example i write a google map extension using default markers stored in the library project if i do not need the maps anyway do the files get included in each android project and is there an easy way to prevent thatsome more backround i try to keep all my library stuff in one project as long as possible i do not know a good point to split the library yet so i do not want to overkill to create seperate libs for everything did that in the past and most of the time it was way to much modularizationthanks for any insightschris,"['java', 'android']" +176029,using apple id as for iphone application authentication can i use users itunes accounts as authentication mechanism for an iphone applicationis there any reference material for that,['iphone'] +176052,cannot use object of type stdclass as array i get a strange error using json decode it decode correctly the data i saw it using print r but when i try to access to info inside the array i getfatal error cannot use object of type stdclass as array incusersdailsoftwareabsphp on line 108i only tried to do resultcontext where result has the data returned by json decodehow can i read values inside this array,['php'] +176071,how to thisable highlight on a image i am trying to thisable highlight on image when i move with my mouse on image and dragtake a look thanks alot,"['html', 'css']" +176087,is it better to encapsulate functionality in a jquery plugin or vanilla javascript function let us say i have some bit of javascript which will modify the dom perhaps hideshow a form field or something like that and let us assume i want to execute this task on multiple pages but only once or twice per pageis it better to encapsulate this functionality into a jquery plugin or a vanilla javascript functionessentially is thisjqueryfntoggleforminput function stunning javascriptjquery magic herebetter or worse than thisfunction toggleforminput stunning javascriptjquery magic here,"['javascript', 'jquery']" +176099,how to inverse type parameters in java i have a class ax y and i want to refactor it to ay x in a way that all the references to it would be modified as well,['java'] +176112,escape forward slash in jackson i use jackson to generate json objects and write them directly into htmls tag like this script var data somejacksonwrappertojsondata scriptthis code breaks if some string contains script in it escaping forward slash would solve the problem and it is alowed by jsons spechow do i enable it in jackson,['java'] +176116,catch any error in python is it possible to catch any error in python i do not care what the specific exceptions will be because all of them will have the same fallback,['python'] +176124,aspnet strange compilation error i do not know whats wrong with my machine but it is a while that i am getting the following strange error from aspnet for all my applicationscompilation errordescription an error occurred during the compilation of a resource required to service this request please review the following specific error details and modify your source code appropriately compiler error message the compiler failed with error code 1073741502show detailed compiler outputcwindowssyswow64inetsrv cwindowsmicrosoftnetframeworkv4030319cscexe tlibrary utf8output rcwindowsmicrosoftnetframeworkv4030319temporary aspnet filesroot75855fbd1e953b27assemblydl32689d6b5f0791420 961fcc01wnvhtmlconvertdll rcwindowsmicrosoftnetassemblygac msilsystemv40 40 b77a5c561934e089systemdll rcwindowsmicrosoftnetassemblygac msilsystemdrawingv40 40 b03f5f7f11d50a3asystemdrawingdll rcwindowsmicrosoftnetassemblygac 32systemwebv40 40 b03f5f7f11d50a3asystemwebdll rcwindowsmicrosoftnetassemblygac msilsystemwebentityv40 40 b77a5c561934e089systemwebentitydll rcwindowsmicrosoftnetassemblygac msilsystemservicemodelwebv40 40 31bf3856ad364e35systemservicemodelwebdll rcwindowsmicrosoftnetassemblygac msilsystemidentitymodelv40 40 b77a5c561934e089systemidentitymodeldll rcwindowsmicrosoftnetframeworkv4030319temporary aspnet filesroot75855fbd1e953b27assemblydl3d08c81cd4d77c01f 961fcc01ajaxcontroltoolkitdll rcwindowsmicrosoftnetassemblygac msilsystemservicemodelactivationv40 40 31bf3856ad364e35systemservicemodelactivationdll rcwindowsmicrosoftnetassemblygac msilsystemwebapplicationservicesv40 40 31bf3856ad364e35systemwebapplicationservicesdll and so onfactskilling worker process fixes the problem temporarilyi even reinstalled my net framework did not workrestarting iis does not helpany idea what can cause this problem this is really wasting lots of my timethanks,"['.net', 'asp.net']" +176131,place datagridviews row indicator for manually selected row i have the following code in a winforms datagridview for handling rightmouseclicks to select the underlying rowprivate void datagridviewteststeps mousedownobject sender mouseeventargs e if ebutton mousebuttonsright return var hittestinfo datagridviewteststepshittestex ey datagridviewteststepsclearselection datagridviewteststepsrowshittestinforowindexselected true now this works fine but it does not place the small indicator in the correct row see image below so basically i was wondering whats missing in the method above,['.net'] +176146,css how can i center text despite a floating element beside it basically i want to center text ignoring any floating sibling elementsat first i thought this wouldnt be a problem as i was under the impression that a floating element did not take from the width of any sibling elementsexample i want the red text to be at the center of the blue box despite the green texthow is this best achieved,['css'] +176195,merge cell values with phpexcel php i have a simple table like id first name last name email phonei am using phpexcel to export my data in xls format rownumber 1 while row mysql fetch rowresult col a foreachrow as cell objphpexcelgetactivesheetsetcellvaluecolrownumbercell col rownumber the full codenow i want to merge the two fields first name last name in one celli triedrownumber 1 while row mysql fetch rowresult objphpexcelgetactivesheetsetcellvaluearownumberrowid setcellvaluebrownumberrowfirst name setcellvaluecrownumberrowlast name rownumberbut i get errors and do not works any help,['php'] +176199,ctags multiline c function prototypes is there a way for ctags to handle multiline function prototypes in ci have searched around and the fieldss is supposed to do multiline prototypes but i cannot get it to workctags x ckindspf fieldss filefileint fooint x int y ctags only returnsfoointnote that the return type is also missingultimately i would like to get an output similar toint fooint x int yor int fooint x int yis fieldss not the correct wayare there part of the ctags fields that i am missingany pointers in generalif there is not a way to do it in ctags any recommended programs i am currently looking at uncrustify,['c'] +176203,could not load a xcode project because it is already opened from another project or workspace i have a project that has one target dependency the target dependency is dependent on a framework called three20 the dependency tree looks like thismyproject mycustomframework three20when i tried to build and run i get the following error message workspace integrity could not load three20xcodeproj because it is already opened from another projet or workspacei have only one project open any suggestions on why i am getting this message,"['objective-c', 'ios']" +176226,c global extern c friend cannot reach private member on namespaced class please consider the codeinclude iostreamusing namespace stdextern cvoid foo void namespace a template int no class bar private friend void foo void static void private func int and template int no void bar no private func int and cout abar no private func and endl extern cvoid foo void abar 0 private func 1 int main cout endl foo g gives g wall o extern c extern ccppextern ccpp in function avoid fooaextern ccpp207 error astatic void abarnoprivate funcint with int no 0a is privateextern ccpp2931 error within this contextif i comment the namspace a it will compile and run correctlywhat am i missingi looked related topics but could not find any that fits in my problemc namespace conflict between extern c and class memberwhy this friend function cant access a private member of the classthanks peopleediti am now convinced that extern c has nothing to do with the problemplease ignore it,['c++'] +176241,can i store an object inside a button in c i am creating buttons dynamically in my code is there a way i can store a custom object in my button so i can use it when i press this button,['c#'] +176242,determine if two java objects are of the same class i am attempting to do the equivalent of if object1class object2class do something which of course does not work what method am i overlooking,"['java', 'android']" +176243,how to know when a user has left the page and refreshed the page i want to make an ajax call before the user leaves the page so basically before leaving the page and before refreshing the pagehow can this be done i was trying to search something with jquery but didnt get anything i tried to use the following code windowonbeforeunloadfunctionalertbefore unloadbut the alert box never appears when leaving the pageclosing the browser tab or refreshing the page how can this be accomplished,"['javascript', 'jquery']" +176276,garbage collection overhead help needed i am looking for a little bit of guidance in trying to diagnose a gc related issue we are testing on solaris with websphere portal and my current environment has a garbage collection overhead of 7 this was calculated with verbose gc and running the log through pmat i am supposed to compare this value with another environment which is running at an avg of 45 the env are on the exact same version of websphere portal same jvm sizesparameterscustom variblesetc my jvms had 20 more allocation failures 2 more full gcs a 2 sec higher mean pause time during gcs than their environment during a 1 hr performance testing period can you give me any advice on what could be causing this issue with all the same configuration values and the same exact 1 hr performance test or anything else to review thanks,['java'] +176289,css sprites how to leave hover button in depressed state css sprites button with three different statesstandardhoverpressed activecurrently standard hover and pressed work the issue is pressed only stays pressed as the mouse is held down i would like the pressed or active state to stay active until it is clicked again any ideas css solution javascript solutionthanks for your helpdheres the codehtmlstyle typetextcss abutton backgroundimage urlbutton sprites image width 86px height 130px thisplay block textindent 9px amicbuttonhover backgroundposition 0 130px amicbuttonactive backgroundposition 0 260px stylea classbutton href ahtml,"['javascript', 'html', 'css']" +176347,python best module to write into xls files i want to read a text file write into an windows xls file ie create a xls file and later do some modifications to the created xls file i have googled as to what are all the available packageswin32 com client xlrd only for reading from xls files i guess xlwt only for writing into xls filespyexceleratorwhat is the best module to perform these actions any suggestions,['python'] +176352,string or binary data would be truncated sql error i have a sql stored procedure that accepts a parameter of type varcharmaxas far as i know and according to all i read about the max size for such strings is 2gbmsdnfor some reason when passing a string larger than 8kb i getstring or binary data would be truncatedwhy do i get this error message and how can i resolve it,['sql'] +176355,how to hide the grid lines of a datagridview winforms c how to hide the grid lines of a datagridview i have searched the internet but found no solutions on thisplease help thanks,['c#'] +176373,how does plus equal work i am a bit confused with the sign how does it work1 2 equals and thisvar data 12345var sum 0dataforeachfunctionvalue sum value sum,['javascript'] +176379,how to convert image to data uri for html with c i need convert image to data url embedding image in the winapplication for html and i need data url embedding image to image,"['c#', 'html']" +176395,null values in where clause i have got a table bla like thisid name fk1 test 42 foo 53 bar nullif i do the sql query select from bla where fk 4i only get the record with the id 2 i do not get the record with id 3 where fk is nulli thought null 4 seems that this is wrongwhy is this so,"['mysql', 'sql']" +176411,when declaring a reference to an array of ints why must it be a reference to a constpointer note i am using the g compiler which is i hear is pretty good and supposed to be pretty close to the standardlet us say you have declared an array of intsint a3 4 5 6 now let us say you really want to declare a reference to that array nevermind why other than the bjarne says the language supports itcase 1 if you tryint ra athen the compiler balks and saysinvalid initialization of nonconst reference of type int from a temporary of type int first things first why is a a temporary variable ie does not it have a place in memory anyway fine whenever i see a nonconst error i try to throw in a const case 2 if you tryintconstrca a wish i knew where the spaces should go but my other post asking about this sort of protocol got a negative rank while many of the answers got ranked highly aha there are stupid questions then everything is cool it compiles and you get a reference to the arraycase 3 now here is another thing that will compileint justsomeintpointer a line 1int rpa justsomeintpointer line 2this also gives you a reference to the original arrayso here is my question at what point does the name of a statically declared array become a constpointer i seem to remember that the name of an array of ints is also a pointertoint but i do not remember it ever being a constpointertointit seems like case 1 fails because the reference declared ra is not to a constpointer which may mean that a was already a constpointertoint to begin withit seems like case 2 works because the reference declared rca is already a constpointertointcase 3 also works which is neat but why at what point does the assumed pointertoint ie the array name a become a constpointer does it happen when you assign it to an int line 1 or does it happen when you assign that int to a int line 2hope this makes sense thanks,['c++'] +176417,unable to set data attribute using jquery data api i have got the following field on an mvc viewhtmltextboxformodel modelcoursetitle new data helptext old text spanin a seperate js file i want to set the datahelptext attribute to a string value heres my codealerttargetfielddatahelptexttargetfielddatahelptext testing 123the alert call works fine it shows the text old text in an alert dialog however the call to set the datahelptext attribute to testing 123 does not work old text is still the attributes current valueam i using the call to data incorrectly i have looked this up on the web and i cannot see what i am doing wrongheres the html markupinput datahelptextold text idcourse title namecoursetitle typetext value,['jquery'] +176433,should a validate method throw an exception i have implemented a little validation library which is used like thisdomain objectvalidate handle validation errors in some way if domain objecterrors for error in domain objecterrors printerrorvalidate performs the checks and populates a list called errorsi know from other validation libraries that they throw exception when validation is performed unsuccessfully error messages would be passed as an exception propertywhat approach is better is it advantageous to throw validation exceptions,['python'] +176458,propertychanged is always null in viewmodelbase i made a simple example to better understan the mvvm patternhere is a link to the sample solution because its difficult to explain the whole problemthere is employee model with age property and employeeviewmodel which contains employee object and changes its age property in the following codepublic int age get return employeeage set if value employeeage return employeeage value notifypropertychangedage employeeviewmodel is inherited from viewmodelbase class with standard inotifypropertychanged codeif propertychanged null propertychangedthis new propertychangedeventargspi am trying to change employees age using icommandpublic void increase thisselectedemployeeage notifypropertychangedagethe property is changed but the binded textblock does not change its valuei checked and saw that notifypropertychanged is called but propertychanged is nulli also ensured that i have only one peopleviewmodel in my appso why is the propertychanged is nulledithere is full code for viewmodelbasepublic class viewmodelbase public string thisplayname get set region inotifypropertychanged members public event propertychangedeventhandler propertychanged protected void notifypropertychangedstring p if propertychanged null propertychangedthis new propertychangedeventargsp endregionthere is peopleviewmodel which contains observalblecollection with employeeviewmodels and set as datacontextthe values of properties are changed but the changes are not shown without reloading objectshere is the peopleviewerxaml that shows the bindingusercontrol xclassmvvmtestmycopyviewpeopleviewer xmlns xmlnsx xmlnsmc xmlnsd xmlnsvmclrnamespacemvvmtestmycopyviewmodel mcignorabled ddesignheight316 ddesignwidth410 usercontrolresources vmpeopleviewmodel xkeyviewmodel usercontrolresources grid datacontextbinding sourcestaticresource viewmodel gridcolumndefinitions columndefinition width150 columndefinition width gridcolumndefinitions listbox itemssourcebinding people gridcolumn0 margin5545 selecteditembinding selectedemployee modetwoway listboxitemtemplate datatemplate stackpanel orientationhorizontal textblock margin2 textbinding firstname textblock margin2 textbinding lastname textblock margin0 2 text textblock margin2 textbinding age textblock margin0 2 text stackpanel datatemplate listboxitemtemplate listbox grid gridcolumn1 gridrowdefinitions rowdefinition height075 rowdefinition height025 gridrowdefinitions grid xnameemployeedetails gridrow0 datacontextbinding selectedemployee margin5 gridrowdefinitions rowdefinition height1 rowdefinition height1 rowdefinition height1 gridrowdefinitions textblock textbinding firstname verticalalignmentcenter horizontalalignmentcenter gridcolumn0 textblock textbinding lastname verticalalignmentcenter horizontalalignmentcenter gridrow1 textblock textbinding age verticalalignmentcenter horizontalalignmentcenter gridrow2 grid stackpanel orientationvertical horizontalalignmentcenter gridrow1 button xnamebutton content width32 height32 commandbinding decreasecommand button button xnamebutton1 content width32 height32 commandbinding increasecommand button stackpanel grid gridusercontrol,['c#'] +176468,set columns width in a datagrid using compact framework i am trying to set the width of the columns in my datagrid i use compact framework 20 and ci tried this but it gives me an out of bonds error messageforeach datagridcolumnstyle vcolumnstyle in datagrid1tablestyles0gridcolumnstyles vcolumnstylewidth 100here is the code for filling my datagrid with the datatable only fails when i try to set the columns widthvoid filldata 1 open connection string constring data sourceprogram filessmartdeviceproject2repartocracksdf using sqlceconnection c new sqlceconnectionconstring copen 2 create new dataadapter using sqlcedataadapter a new sqlcedataadapter select codbultocomp nombre estado from envios inner join tiendas on envioscodigodestino tiendascodigodestino c 3 use dataadapter to fill datatable datatable t new datatable afillt 4 render data onto the screen foreach datagridcolumnstyle vcolumnstyle in datagrid1tablestyles0gridcolumnstyles vcolumnstylewidth 100 datagrid1datasource t,['c#'] +176491,how to enable igbinary with memcached installed first i have memcached installed with libmemcached also i have installed igbinarythis is my phpini directory in which the loadable extensions modules resideextension dir extension dir usrlocallibphpextensionsnodebugnonzts20060613extensionapcsoapcenabled1apcshm size128mextensionmemcachedsosessionsave handlermemcachedsessionsave path127001211extensionigbinarysosessionserialize handlerigbinaryigbinarycompact stringsonwhen i run phpinfo i see that igbinary is enabled but not for memcachedapcserialization support php igbinary igbinaryigbinary support enabledigbinary version 1igbinary apc serializer abi 0directive local value master valueigbinarycompact strings on onphpinfo about memcachedmemcachedmemcached support enabledversion 102libmemcached version 051session support yesigbinary support no that last line igbinary support thats the question oddly enough as you can see under the heading apc there is stated serialization support php igbinary so do someone know why i cannot enable igbinary for memcachedthanks,['php'] +176510,how to prevent xss attacks when i need to render html from a wysiwyg editor nontechnical background info i am working for a school and we are building a new website using django the teachers that work for the school are not technologically competent enough to use another markup language such as markdown we eventually decided that we should use a wysiwyg editor which poses security flaws we are not too worried about the teachers themselves but more malicious students that might get the teachers credentialstechnical background info we are running using django 13 and have not chosen a specific editor yet we are leaning towards a javascript one such as tinymce but can be persuaded to use anything that allows security and ease of use because the wysiwyg editor will output html to be rendered into the document we cannot simply escape itwhat is the best way to prevent malicious code while still making it easy for nontechnical teachers to write posts,['html'] +176520,backbonejs global error handling i am writing website with usage of backbonejs for web front end and own restful server for api back end my api restful server requires manual authorization and expects security token in authorization header if security token is deprecated or broken api server will return response with 401 status code i override backbonesync to send additional headers with requests and returning optionserrorjqxhrstatus on ajax errorhow can i add global error events listener to handle optionserror events on failed resources loading i need it to make navigation redirect to signin page on 401 unauthorized response,"['javascript', 'jquery']" +176538,meaning of in javascript what does assigning a variable to mean is that initializing it to a function i have code in a javascript file that says thisglgewavefront functionuid glgeassetsregisterassetthisuid thismultimaterials thismaterials thisinstances thisrendercaches thisqueue how is that assignment different from an array is it a type of array,['javascript'] +176545,how can i check a pdo mysql connection for errors before i run a query my scripts are getting quite riddled with forked processes in a lot of different functions whenever pcntl fork is called all mysql connections are lost if i run a query on a pdo mysql connection i get the error mysql server has gone awaythe problem is that this error only shows up in pdoerrorinfo after a failed query execution i would like to be able to detect if the mysql server has gone away before i try to run a query that way i could create a pdo wrapper that makes a new connection for me in such situationsany ideas,"['php', 'mysql']" +176568,c how to define an extension method as with in f f has a convenient feature with exampletype product namestring priceint let p nametest price42 let p2 p with nametest2 f created keyword with as the record types are by default immutablenow is it possible to define a similar extension in cseems it is a bit tricky as in c i am not sure how to convert a string nametest2to a delegate or expression,['c#'] +176580,dealing with boost header files is there a way to drastically reduce the number of header files needed for boost ideally i am asking the boost folks to find a way to make their product smaller but in the mean time is there a way to include boost but not have several thousand header files to deal with is there a c mechanism to bundle thousands of header files into a single package and just check that single file into source controli guess the problem here is source control doing a diff svn st and check out is so slow with all these files to deal with,['c++'] +176633,css venn diagram mouse hover i am trying to create a pure css venn diagram like this where the circle gets highlighted on mouse hover but the problem is using the borderradius property if i mouse over the corner of the circle outside the circle it triggers hover as wellfor a demo see this jsfiddle link and hover over the red areais there any css solution to avoid this or am i ganna have to calculate it using javascriptedit thanks to all for the responsesi should have posted the browser information as well i am using chrome 12so far it seems this bug exists in chrome i will update this page with any further findingsupdate aug 2013 just tested this again on chrome 28 and the issue no longer exists,"['html', 'css']" +176634,how do i determine whether data on a form has been input by the user or the browser i have a checkout form that will thisplay a popup survey to ask why they have not started filling out the form after 5 seconds however i need to be able to check whether the user has actually entered data as opposed to data entered by the browsers autofill feature any prepopulated data set in the markup i specifically ignore in the javascript or jqueryright now my solution is to have the settimeout run a function which checks a variable true or false that is set to false on a jquery focus or change event on the input types input select textarea however since the javascript may load after the user is able to use the form elements i have to check whether the user has entered data before the survey pops upis it possible to differentiate between userinputted data and browserinputted data if the javascript loads after the user has done anything to the form fields,"['javascript', 'jquery']" +176638,regular expression capturing all repeating groups i have strings like belowpropertyonesome text another optional text here etcwhich contains strings inside i would like to capture all these variables into groups via one regexp matching but it seems like it is not possible as regexp returns only last captured group while repeating,['java'] +176639,android converting string to int i am simply trying to convert a string that is generated from a barcode scanner to an int so that i can manipulate it by taking getting the remainder to generate a set number of integers so far i have tried int mynum 0try mynum integerparseintmystringgettexttostring catchnumberformatexception nfe andintegervalueofmystrand int value integerparseintstring the first one gives me the error the method gettext is undefined for the type stringwhile the last two do not have any compile errors but the app crashes immediately when those are called i thought it had to do with my barcode scanning intent method but i put it into the oncreate and still got the error,['android'] +176653,upgraded to xcode 41 and sqlite3h is causing compilation errors where it did not before the upgrade i recently opened an existing project from a time before i installed xcode 41at first there were many errors and i corrected the problem by chosing llvm 21 as the option for the compilerall of the errors but one have been cleared up in sqlite3h this line is causing a problemsqlite api int sqlite3 enable shared cacheint osx available but deprecated mac 10 0 mac 10 7 iphone 2 0 iphone 5 0the error message readsexpected function body after function declaratorany help is greatly appreciatedthanks,"['objective-c', 'ios']" +176665,how to get complete current url for cakephp how do you echo out current url in cakes view,['php'] +176666,convert datetime from english to spanish does anybody know how to convert a datetime from english to spanisheg convertmonday january 01 2011intolunes enero 01 2011 thanks in advance,"['c#', '.net']" +176667,replacing stdlist object given an iterator given an iterator into a stdlist how do you replace the object at the position that the iterator references currently all i can think of is calling insert with the new object and iterator to insert the new object before the element referenced by the iterator and then calling erase to remove the object to be replaced is there a less roundabout way of accomplishing a replace,['c++'] +176700,algorithm to loop over an array from the middle outwards i am working on a divideandconquer algorithm in fact one that does curve fitting to a number of input points for the divide part i need to calculate an error term for each point and if the error exceeds a given threshold i wish to split the curve at that point and process the left and right sections of the input separately a simple loop does the trick but it would be advantageous for me to start at the middle of the current section and work outwards to clarify if i do find a point whose error is too large i recursively call and generate separate curves for the left and right sections if all the points are within the threshold then my curve fits and i returnafter a bit of headscratching i came up with this the points are in an array and the current section is from startindex to endindex inclusiveint steps endindex1startindexint i startindexendindex1int stepdir 1forint q0 qsteps q istepdirq stepdirstepdir test point i here and return early if error exceeds thresholdin other words beginning near the middle go one index forward two back three forward four back it works and i am sure it is efficient but it strikes me that there should be a cleaner way to do it in particular i ended up having to check the java language spec to make sure that the statements in the for update expression did evaluate in sequence even though is not a sequence operator as it is in ccany ideas gratefully appreciated is there a cleaner way,"['java', 'c++', 'c']" +176714,c detecting ctrlv with registerhotkey but not intercepting it i need to detect when a user presses ctrlv regardless of window focus my app will likely be minimised but i must not stop the actual paste operationi have tried a few things i am successfully binding to keystrokes with registerhotkeyi haveprotected override void wndprocref message m if mmsg 0x312 hotkey basewndprocref mand i have tried the followingvoid hotkey sendkeyssendwaitv just puts v instead of clipboard contentsandvoid hotkey sendkeyssendwaitclipboardgettext this works but since ctrl is still down it triggers all the shortcut keys for the app eg if the keyboard contains s then instead of putting s in the app it calls ctrls which makes the app think the user wants to save currently the only working solution i have is to bind to something different eg ctrlb and then call sendkeyssendwaitv however this is not idealan ideal solution would be if my window did not intercept the keystroke in the first place just reacted,['c#'] +176715,how do i get escape javascript and other helpers in my sprockets preprocessed js file not a view i am using rails 31 and the sprockets stuffi want to use erb to preprocess a js file that will then be included using javascript include tag it is generated from code and so i am preprocessing it with erb but i cannot get to the helpers like escape javascript from actionviewhelpersjavascripthelpersay my file is called dynamicjserb and it containsobj name test tag escape javascript image tag logopng how do i stop it from producing the errorthrow errornomethoderror undefined method escape javascript for class0x1067da9400x116b2be18in usersmesiteappassetsjavascriptsdynamicjserbwhen i hit my local server and ask for assetsdynamicjs,['javascript'] +176743,how to run a batch script after installation is finished i am working for a custom installer developed in visual studio 2008 setup deployment setup project for a c project i would like to run a batch file bat after installation is finished how can i do that,"['c#', '.net']" +176748,need sql query to find parent records without child records i am not at all conversant in sql so was hoping someone could help me with a query that will find all the records in a parent table for which there are no records in a child table the following works for me to find parent records for specific child field valuesselect parenttableparentid from parenttable inner join parenttable on parenttableparentid childtablechildid where childtablechildfield 2131 group by parenttableparentid having countthistinct childtablechildfield 0can i change the where clause some how to find parents with a count of zero child recordsthanks,['sql'] +176776,python rewrite multiple lines in the console i know it is possible to consistently rewrite the last line thisplayed in the terminal with r but i am having trouble figuring out if there is a way to go back and edit previous lines printed in the consolewhat i would like to do is reprint multiple lines for a textbased rpg however a friend was also wondering about this for an application which had one line dedicated to a progress bar and another describing the downloadie the console would printmoving file nameoffiletxttotal progress 40and then update appropriately to both lines as the program was running,['python'] +176781,javamongodb query by date i stored a value as a javautildate in my collection but when i query to get values between two specific dates i end up getting values outside of the range heres my codeto insertbasicdbobject object new basicdbobjectobjectputdateadded new javautildatecollectioninsertobjectto querybasicdbobject query new basicdbobjectqueryputdateadded new basicdbobjectgte fromdatequeryputdateadded new basicdbobjectlte todatecollectionfindquerysortnew basicdbobjectdateadded 1when i query between wed jul 27 165449 est 2011 and wed jul 27 165449 est 2011 basically fromdate todate i get objects with dates like tue jul 26 094337 est 2011 which should definitely not be possible what am i missing here,['java'] +176793,is there any java flyweight pattern implementation out there i have been looking for a flyweight pattern implementation and gave up after reaching page 20 of google search while there are countless stupid examples out there it seems no one has ever published are reusable implementation in javafor me flyweight really only makes sense if you have to keep many such instances so it has to be implemented as a collection what i would like is a factory that takes a byteshortintlong mapper implementation and returns either a list set or map that looks like a normal object collection but stores it is data internally as an array of primitive thereby saving lots of ram the mapper would take an object of type x and map it to a primitive or do it the other way aroundis there something like that available somewhereedit i am looking for a collection library that support this pattern not just any example of which there are hundreds,['java'] +176795,ordering of using namespace std and includes i recently saw this code being used in a source file in a c projectusing namespace stdinclude iostreamignoring all issues of whether it is a good idea to have using namespace std at all is the above code even legal there is no code in the file before these two linesi would have thought that this wouldnt compile since namespace std has not been declared in scope until the include iostream directive includes it into the file but using the build system for the project this was compiling just fine if someone has a link to a relevant part of the spec that would be most appreciated,['c++'] +176799,get all unique years from a date column using sql mysql i have a mysql table with a datetime column named created which contains the date and time the record was inserted this table has about 30 records right now i want to get all occuring years unique not per record from this table is there a way to do this using a mysql query,['mysql'] +176805,how can i make vim align the ternary operator nicely i like to write code using the ternary operator like thisstdstring result inputempty createnewitem processinput input how can i configure vim so that when pressing return after having typed createnewitem indents the next line so that the cursor is in the same column as the last so that i can just continue typing processinput input i tried looking at the cinoptionsvalues setting but i did not see anything relevant,['c++'] +176813,how to create temp dir in ruby how do i create a temporary directory in ruby in a nice way i would also like to delete it automatically on process exit thanks,['ruby'] +176828,fastest way to sort an array in descending order why is the following codearraysortvaluesarrayreversevaluesmuch faster at sorting an array in descending order compared toarraysortvalues abacomparetobcode was run in release mode outside of the debuggerwhat is the most efficient way to produce a descending sort for arrays preferably in a one liner,['c#'] +176856,why reimplement strlen as loopsubtraction inspired by this question about the following code from sqlite3 static int strlen30const char z const char z2 z while z2 z2 return 0x3f intz2 z that is accompanied by a commit message saying this function helps with int overflowsi am particularly interested in this part const char z2 z while z2 z2 to me this loop advances z2 until z2 points onto null terminator then z2z yields the string lengthwhy not use strlen for this part and rewrite like thisreturn 0x3f intstrlenzwhy use loopsubtraction instead of strlen what can loopsubtraction do what strlen cannot,"['c++', 'c']" +176861,why does php consider 0 to be equal to a string i have the following piece of codeitemprice 0code to get item information goes in hereifitemprice e itemprice 1it is intended to initialize the item price to 0 and then get information about it if the price is informed as e it means an exchange instead of a sell which is indicated with a negative value because it is to be stored in a database which requires a numeric valuethere is also the possibility to leave the price as 0 either because the item is a bonus or because the price will be set in a later momentbut always when the price is not set which leaves it with the initial value of 0 the if loop indicated above evaluates as true and the price is set to 1 that is it considers 0 as equal to ehow can this be explainededitwhen the price is provided as 0 after initialization the behavior is erratic sometimes the if evaluates as true sometimes it evaluates as false,['php'] +176873,memory problems with thisplaying large images in uitableview i have a system which loads alot of large images from the web and thisplays them in custom table cells on older devices the memory warnings happen pretty quickly so i implemented a system of deleting some from the table to try to combat this but it did not work well enough lots of images were deleted affecting the ui so i thought i could load all the images into the devices cache and then load them from there i have implemented sdwebimage this is great but i still havent solved the problem of memory allocation as the images are still being thisplayed all the time and therefore kept in memory causing crashes i think i need to implement a system which shows the images from the cache if the cell is being thisplayed and hide it if the cell is not showing i am just stuck at how to build such a system or is this not going to work can you really keep the apps memory low and stop it having memory warnings crashing by removing images from its table cells or do i just need to carry on with my earlier solution and just delete imagescells until the memory warnings stopupdated with codetableviewcontrollerm uitableviewcell tableviewuitableview tableview cellforrowatindexpathnsindexpath indexpath if indexpathsection 0 currentindexpath indexpath imagetablecell cell imagetablecell tableview dequeuereusablecellwithidentifiercellidentifier imagedownloader download totaldownloads objectatindexindexpath row if cell nil cell imagetablecell alloc initwithstyle uitableviewcellstyledefault reuseidentifier cellidentifier autorelease cellimageviewimage downloadimage return cellreturn nil nsintegertableviewuitableview tableview numberofrowsinsectionnsintegersection int t totaldownloads count return timagetablecellm custom cell idinitwithstyleuitableviewcellstylestyle reuseidentifiernsstring reuseidentifierself super initwithstylestyle reuseidentifierreuseidentifierif self selfframe cgrectmake00f 00f 3200f 00f selfcontentviewframe cgrectmake00f 00f 3200f 00f selfautoresizingmask uiviewautoresizingflexibleheight uiviewautoresizingflexiblewidth selfcontentmode uiviewcontentmodescaletofill selfautoresizessubviews yes selfcontentviewautoresizingmask uiviewautoresizingflexibleheight uiviewautoresizingflexiblewidth selfcontentviewcontentmode uiviewcontentmodescaletofill selfcontentviewautoresizessubviews yes selfimageview drawrectcgrectmake00f 00f 3200f 00f selfimageviewcontentmode uiviewcontentmodescaleaspectfill selfimageviewautoresizingmask uiviewautoresizingflexibleheight uiviewautoresizingflexiblewidth selfimageviewopaque yesreturn selfimagedownloader implements sdwebimagemanagerdelegate void downloadimage comes from model class if image nil nsurl url nsurl urlwithstringselfurlstring sdwebimagemanager manager sdwebimagemanager sharedmanager remove in progress downloader from queue manager cancelfordelegateself if url manager downloadwithurlurl delegateself retryfailedyes voidcancelcurrentimageload sdwebimagemanager sharedmanager cancelfordelegateself voidwebimagemanagersdwebimagemanager imagemanager didfinishwithimageuiimage image selfimage image if selfdelegate respondstoselectorselectoraddimagetomodel selfdelegate addimagetomodelself voidwebimagemanagersdwebimagemanager imagemanager didfailwitherrornserror error if selfdelegate respondstoselectorselectorbadimage selfdelegate badimage,"['ios', 'objective-c']" +176874,counting method calls in rhino mocks so i would like to count method calls in rhino mocks with something more specific than any once or atleastonce is there any mechanism for doing this,['c#'] +176883,how does marshalreadint32 etc differ from unsafe context and pointers particularly is marshal safer are pointers fasterint pixel marshalreadint32bitmapdatascan0 x 4 y bitmapdatastrideint pixel intbitmapdatascan0x y bitmapdatastride 4,"['c#', '.net']" +176896,handling illegal xml values while reading emails with ews we have an application that uses a streamingsubscriptionconnection to read every email that gets sent to a particular mailbox the issue i am running into several times a day during development i get the exception square character hexadecimal value 0x1f is an invalid character line 1 position 1 here is the stack trace at systemxmlxmltextreaderimplthrowexception e at systemxmlxmltextreaderimplthrowstring res string args at systemxmlxmltextreaderimplthrowint32 pos string res string args at systemxmlxmltextreaderimplthrowinvalidcharint32 pos char invchar at systemxmlxmltextreaderimplparsetextint32 startpos int32 endpos int32 outorchars at systemxmlxmltextreaderimplparsetext at systemxmlxmltextreaderimplparsedocumentcontent at systemxmlxmltextreaderimplread at microsoftexchangewebservicesdataewsxmlreaderread at microsoftexchangewebservicesdataewsxmlreaderreadxmlnodetype nodetype at microsoftexchangewebservicesdataewsxmlreaderinternalreadelementxmlnamespace xmlnamespace string localname xmlnodetype nodetype at microsoftexchangewebservicesdataewsxmlreaderreadstartelementxmlnamespace xmlnamespace string localname at microsoftexchangewebservicesdataservicerequestbasereadresponseewsservicexmlreader ewsxmlreaderhow can i safely read emails with ews that contain illegal charactersafter much searching it appears it was possible to fix this issue with older versions of the ews api however with the newest version of the managed api no one seems to have a fixthis is a cross post from i have managed to get the exception again and here is the full stacktrace and what exchange is turning as a notificationi am using exchange 2010 sp1edit i am reviving this question as it is causing me serious problems and the original question states the problem clearly i am looking for clientside solutions that modify the behavior of the managed ews api to filter invalid characters from the xml and avoid exceptions exchange server fixes are unlikely to be an option unless they are simple configuration changes my software will be run against customer exchange servers i do not control,['c#'] +176914,simulate variadic templates in c is there a well known way for simulating the variadic template feature in cfor instance i would like to write a method that takes a lambda with an arbitrary set of parameters here is in pseudo code what i would like to havevoid mymethodt1t2treturnfunt1t2 treturn fthank you,['c#'] +176942,how to save pictureboximage to file i use the following to write jpgimage to a pictureboximagevar jpgimage new bytejpgimagesizepictureboximage new bitmapnew memorystreamjpgimageand i can use the following to write a byte array to a fileusing var bw new binarywriterfileopenfilename filemodecreate fileaccesswrite filesharenone bwwritejpgimagebut how can i get the jpgimage byte array from the pictureboximage so i can write it to the fileiow how do i reverse the following to get the byte array from the pictureboximagepictureboximage new bitmapnew memorystreamjpgimage,['c#'] +176954,coordinates of selected text in browser page i need the coordinates in pixels of the beginning of the text selection anywhere on the page not in a textareai tried using the cursor coordinates but this did not work quite well because the cursor coordinates and the beginning of the selection are not always the same for example when a user drags over a texti hope someone has the solution,"['javascript', 'html']" +176970,how to bottom align two elements in a div element i am currently doing this with a table with 2 bottomaligned cells i am okay with the table solution but just wondering if this is possible with just css and html no javascriptrequirement the sizes of the text and image are unknown but the combined width of the two will not exceed the width of the containing element eg if i later want to change the image or the text i do not want to dive into the ccs file image is aligned to the left and the text actually a horizontal list is aligned to the right thanksedit in response to kos the sizes of the text and images are dynamic be it height or width but the combined width of the two elements will not exceed the width of the containing element the image and text should be bottom aligned the containing element should fit tightly the tallest element,"['css', 'html']" +176985,error lnk2019 unresolved external symbol main referenced in function tmaincrtstartup but this time it is not a windowsconsole problem so the infamous error is back the project is complaining that it cannot find the main method that is what the error means righthowever i do have a main and my project is a console project as it should be it worked before so i know it is not thatalso the project has too many classes and files for me to post them all so i will post any classes you need by request it is a c opengl and sdl game on visual studio 2010 it is not a problem of any of the libraries as it was working fine before it suddenly and inexplicably showed this linker erroredit the main methodint mainint argc char argv glutinitargc argv glutinitthisplaymodeglut double glut rgb glut depth glut alpha glutcreatewindowgame glenablegl depth test glenablegl normalize glenablegl color material glenablegl blend glblendfuncgl src alpha gl one minus src alpha g game glutinitwindowsizeggetscreenwidth ggetscreenheight glutpositionwindow1280 50 callbacks glutthisplayfunchandleredraw glutreshapefunchandleresize glutmousefunchandlemouseclicks glutpassivemotionfunchandlemouseovers glutkeyboardfunchandlekeyboardevents gluttimerfunc50 moveitemtoinventory 0 glutmainloop return 0,['c++'] +176989,fragments within fragments i am wondering if this is actually a bug in the android apii have a setup like soa 1 2 aa 3 aa a a ais a menu which loads fragment 2 a search screen in the right paneis a search screen which contains fragment 3 which is a result listthe result list is used in several places including as a functioning high level fragment in it is own rightthis functionality works perfectly well on a phone where 1 2 and 3 are activityfragments however when i used this code fragmenttransaction transaction getsupportfragmentmanagerbegintransaction fragment frag new fragmentnumber2 iftoload null fragsetargumentstoload transactionreplaceridrightpane frag transactioncommitwhere ridleftpane and ridrightpane are fragments in a horizontal linear layoutit is my understanding that the above code removes the fragment which is resident and then replaces it with a new fragment brilliant obviously that is not what happens because when this code runs the second time you get the following exception0727 152255940 errorandroidruntime8105 caused by javalangillegalargumentexception binary xml file line 57 duplicate id 0x7f080024 tag null or parent id 0x0 with another fragment for fragmentnumber3this is caused because the the container for fragmentnumber3 has been duplicated and it no longer has a unique id the initial fragment has not been destroyed before the new one is added in my mind that means it has not been replacedcan someone tell me if this is possible this answer suggests it is not or is it a bug,['android'] +176992,i need help finding my memory leak using mat i am using the mat to compare two heap dumps i have been taking a heap dump each day and it is growing by about 200 megs each day i think the leak is associated with javautilzip because of what the table shows and also because we added a new process recently that zips and unzips a lot of files see imageat this point i open the dominator and filtered for inflater that produced a large list of javautilzipinflater now i want to see whats holding these open so i picked one and ran the path to gc root excluding weak and soft references see image it looks like this has to do with the jar inflation and nothing to do with my process at this point i am stuck and need some suggestionsedit 1sean asked about the threadlocals if you look at the dominator tree with no filter you see that javalangapplicationshutdownhooks is 58 of the heap if i expand some of those entries you can see that they seem to be in the threadlocalmap how would i find what put them thereedit 2seans comment put me on the correct track i am using glassfish v 20 and it has a memory leak it continually creates new logmanagers and adds them to the applicationshutdownhooks collectioni worked around the issue by cracking open the applicationshutdownhooks and manually removing the objects from the collection,['java'] +177000,return string from a callback java does anyone know how i can solve the following problem i want to return a string from a callback but i get only the final local variable s cannot be assigned since it is defined in an enclosing type because of final public string getconstraintint indexfdg final string s asynccallbackstring callback new asynccallbackstring public void onfailurethrowable caught caughtprintstacktrace public void onsuccestring result s result speicherserviceutilgetinstancegetconstraintindexfdg callback return s,['java'] +177026,embed a function from a matlab mex file directly in python i am using a proprietary matlab mex file to import some simulation results in matlab no source code available of course the interface with matlab is actually really simple as there is a single function returning a matlab struct i would like to know if there is any way to call this function in the mex file directly from python without having to use matlabwhat i have in mind is for example using something like swig to import the c function into python by providing a custom matlabwrapper around itby the way i know that with scipyioloadmat it is already possible to read matlab binary mat data files but i do not know if the data representation in a mat file is the same as the internal representation in matlab in which case it might be useful for the mex wrapperthe idea would be of course to be able to use the function provided in the mex with no matlab installation present on the systemthanks,['python'] +177076,are whiletrue loops so bad i have been programming in java for several years now but i just recently returned to school to get a formal degree i was quite surprised to learn that on my last assignment i lost points for using a loop like the one belowdo get some input if the input meets my conditions break otherwise ask again whiletruenow for my test i am just scanning for some console input but i was told that this kind of loop is thiscouraged because using break is akin to goto we just do not do iti understand fully the pitfalls of goto and its java cousin breaklabel and i have the good sense not to use them i also realize that a more complete program would provide some other means of escape say for instance to just end the program but that was not a reason my professor cited sowhats wrong with dowhiletrue,['java'] +177092,jquery error jqxhrresponsetext is empty i have a java spring mvc controller that can throw an exception i have an exceptionhandler setup to handle these errors and i would like to use it to return the exceptions message to the callerthe server code is exceptionhandlerdeviceexceptionclass responsestatushttpstatusmethod failure responsebody public string handleexceptiondeviceexception ex return exgetmessage i have tested throwing a deviceexception and getting the result using curl from the cli the exceptions message is being returned in the response body i cannot get the jquery error handler to thisplay it however my handler code is error functionjqxhr textstatus errorthrown problem the data is always blank alertjqxhrresponsetext jqxhrresponsetext all i ever get for the responsetext is an empty string how do i get the string returned by the exceptionhandler to thisplay in the jquery error handler,['jquery'] +177095,reading file content to string in net compact framework i am developing an application for mobile devices with the net compact framework 20 i am trying to load a files content to a string object but somehow i cannot get it done there is no readtoend method in the systemiostreamreader class is there another class that provides this functionality,"['c#', '.net']" +177115,version vs build in xcode i have an app that i developed with xcode 3 and recently started editing with xcode 4 in the target summary i have the ios application target form with fields identifier version build devices and deployment target the version field is blank and the build field is 340 which matches the version of the app from when i was still editing with xcode 3my questions are what is the difference between the version and build fieldswhy was the version field blank after i upgraded to xcode 4thanks,['ios'] +177136,what does rtlinitializeexceptionchain do and how can i reduce its execution overhead i am trying to find bottlenecks in my program currently in the lowhanging fruit stage and using a profiler i get something like the followingthe thing i see in this is that rtlinitializeexceptionchain takes up the far majority of the time and functions from my actual program do not even make it onto this top list i would like to know if anyone knows what rtlinitializeexceptionchain does how it is called and how i can reorganize my program to not call it so muchsome other information about my project it is a com api using atl and the program being profiled is a testing c program which consumes this apithanks,['c++'] +177142,how to write fast low level code i would like to learn more about low level code optimization and how to take advantage of the underlying machine architecture i am looking for good pointers on where to read about this topicmore detailsi am interested in optimization in the context of scientific computing which is a lot of number crunching but not only in low level languages such as cc i am in particular interested in optimization methods that are not obvious unless one has a good understanding of how the machine works which i do notyetfor example it is clear that a better algorithm is faster without knowing anything about the machine it is run on it is not at all obvious that it matters if one loops through the columns or the rows of a matrix first it is better to loop through the matrix so that elements that are stored at adjacent locations are read successivelybasic advice on the topic or pointers to articles are most welcomeanswersgot answers with lots of great pointers a lot more than i will ever have time to read heres a list of all of themthe software optimization cookbook from intel bookwhat every programmer should know about memory pdf bookwrite great code volume 2 thinking lowlevel writing highlevel booksoftware optimization resources by agner fog five detailed pdf manualsi will need a bit of skim time to decide which one to use not having time for all,"['c++', 'c']" +177150,how do i turn a macro into a string using cpp gnus cpp allows you to turn macro parameters into strings like sodefine strx xthen strhi is substituted with hibut how do you turn a macro not a macro parameter into a stringsay i have a macro constant with some value egdefine constant 42this does not work strconstant this yields constant which is not what we want,['c++'] +177157,how do i make a patch request in python is there a way to make a request using patch http method in pythoni tried using httplib but it does not accept patch as method param,['python'] +177162,php mysql update if exist or insert if not i have no idea if this is even remotely correct i have a class where i would like to update the database if the fields currently exist or insert if they do not the complication is that i am doing a joining 3 tables set colors school art baseimage any help would be really greathere is what i have public function set layer colorsvalue global dbresult array mysql queryif existsselect from set colors where school art id value update set colors school art id baseimage id sub folder layer select school artid baseimageid baseimagesub folder baseimagelayer from school art join baseimage on baseimagebase folder school artseries code where baseimageimage type b order by school artid else insert into set colors school art id baseimage id sub folder layer select school artid baseimageid baseimagesub folder baseimagelayer from school art join baseimage on baseimagebase folder school artseries code where baseimageimage type b order by school artid return result arraythanks in advance,"['php', 'mysql']" +177179,geodjango thistance queries returning incorrect results i just got geodjango up and running on my development machine problem is that i cannot get a thistance query to work correctly no matter what srid i use the thistance results are totally off heres an example from djangocontribgismeasure import d from appmodels import place from djangocontribgisgeos import point qs placeobjectsall point point118 34 qsfiltercoordinates thistance ltepoint dm1place 7eleven place arthur murray dance studio place costco place amc century city 15 place 24 hour fitness place ralphs place houstons restaurant place cvspharmacy place shaky alibi place sephora place trader joesthe problem is that these places are much further than 1m away from pointi tried playing around with it but have not had much luck heres an example with another srid qs placeobjectsalltransform3786 point point118 34 srid3786 qsfiltercoordinates thistance ltepoint dm1place 7eleven place arthur murray dance studio place costco place amc century city 15 place 24 hour fitness place ralphs place houstons restaurant place cvspharmacy place shaky alibi place sephora place trader joesi have a feeling i am just choosing the wrong srids but not a single one that i have run into online has worked or given any response that is even moderately usefulany help is greatly appreciated,['python'] +177187,is it necessary to include init as the first function everytime in a class in python i am new to python and i want to know that whether it is necessary to include init as the first method while creating a class as in the example belowclass exampleclass def init self some message selfmessage some message print new class instance created with message print selfmessage also why do we use self to call methodscan someone explain the use of self in detailalso why do we use pass statement in python,['python'] +177193,ffmpeg integration on iphone ipad project can any one tell me how do i integrate ffmpeg in my iphone ipad projecti m using xcode 4i searched a lot but did not find any useful link please tell me step by step procedure to integrate ffmpeg in my projectthanks,['iphone'] +177217,are most php frameworks actually mva instead of mvc many php frameworks claim that they implement mvc design pattern however in their implementation the model and view do not know each other and each communication in between must be done through controller as i read in wikipedia this is mva model view adapter instead of mvc design pattern approach because in mvc model and view communicates directlythose frameworks claim are wrong or did i miss something,['php'] +177234,attach to application using eclipse can you attach to a running application using eclipse similar to how you attach using visual studio,['java'] +177238,whats the equivalent of get in javascript d helloabcdgethellodefault valabove is python how to do this in javascript i want to be able to set a default value if no key found,"['javascript', 'python']" +177242,how to have logarithmic bins in a python histogram as far as i know the option logtrue in the histogram function only refers to the yaxisphistdbins50logtruealpha05colorbhisttypestepi need the bins to be equally spaced in log10 is there something that can do this,['python'] +177253,submit html5 form using javascript and validate its inputs i am writing form and adding html5 validation attributes to its input like required autofocus i use javascript to submit the form using documentmyformsubmit but it does not validate the form against the html5 validation attributes as they are not thereany suggestions,['javascript'] +177258,alternatives to cheffabricpuppet for simple lamp development i have finally committed to really learning the software design process correctly in order to advance my skills and grow my business this means embracing version control git setting up a developmentstagingproduction environment and keeping these environments as similarly configured as possiblei am getting really caught up with the last step in picking a solution to automate and sync my server settings i have looked into chef puppet fabric but for my purposes they all seem overly complex i amdeveloping a small web app on a single serverwill be developing in a lamp environment with intermediate php unix skillswould not be heavily modifying environmental variables primarily phpini apache configsi would appreciate any recommendations on solutions that would be easier to implement than mastering the complex chef environment or learning python to use fabric i can do this if necessary but am hoping there is a more basic elegant solution given my very simplistic needs,['php'] +177262,android fastest way to draw a bitmap to canvas just wondering what the fastest way is to draw a bitmap to canvascurrently i have a bitmap and canvas for drawing which i use to double buffer drawing calls and then when i draw to canvas have a scrolling effect by applying a 1px canvas translation this alone will reduce the framerate from 60 fps to 40 quite a hit im not using surfaceview or glsurfaceview at the moment but just wondering if im missing anything that would improve the speed ondraw code belowoverride public void ondrawcanvas canvas update fps text mfpstrackerframetouch ifmbufferedbitmap null mbufferedbitmap bitmapcreatebitmapgetwidth getheight bitmapconfigargb 4 mbufferedcanvas new canvasmbufferedbitmap paintsetcolorcolorblue mbufferedcanvasdrawline0 getheight getwidth getheight paint mbufferedcanvastranslate0 1 canvasdrawbitmapmbufferedbitmap 0 0 null draw fps mtextpaintsetcolorcolorwhite canvasdrawtextmfpstrackergetfpsstring 40 40 mtextpaint invalidate,['android'] +177266,what is the purpose of pure virtual destructor possible duplicatesunder what circumstances is it advantageous to give an implementation of a pure virtual functionwhy do we need a pure virtual destructor in c compiler does not force the child class to implement a destructor when its base has pure virtual destructorstruct base virtual void foo 0 virtual base 0basebase necessarystruct child base void foo ok no destructor needed to create objects of childfunny part is that compiler rather forces the base to define a destructor body which is understood demo for referencethen what is the purpose of having pure virtual destructor in base class is it just to thisallow base creating objects,['c++'] +177275,em vs px and cross browser compatibility i am a css newbie and was wondering if there is a benefit using em instead of px when it comes the cross browser compatibility of my css,['css'] +177297,how to hide wpf datagrid columns depending on a property i have the following wpf sample programxamlwindow xclassancestorariemainwindow xmlns xmlnsx titlemainwindow height350 width525 windowresources booleantovisibilityconverter xkeybooltovis windowresources grid datagrid autogeneratecolumnsfalse nameblumen itemssourcebinding leaves datagridcolumns datagridtextcolumn bindingbinding color headerfarbe width160 datagridtextcolumn bindingbinding size headergraae width60 visibilitybinding pathdatacontextflag relativesourcerelativesource findancestor ancestortypextype window converterstaticresource booltovis datagridcolumns datagrid gridwindowcode behindpublic partial class mainwindow window public mainwindow initializecomponent flowers rose new flowers roseleaves new observablecollectionleaf roseflag false leaf l1 new leaf l1color rot l1size 3 roseleavesaddl1 leaf l2 new leaf l2color gelb l2size 2 roseleavesaddl2 thisdatacontext rose and the model classes arepublic class leaf public string color get set public int size get set public class flowers public bool flag get set public observablecollectionleaf leaves get set as you can see i want to hide the 2nd datagrid column if the flag property is set to false but it does not work i get the following binding error in the visual studio output windowsystemwindowsdata error 4 cannot find source for binding with reference relativesource findancestor ancestortypesystemwindowswindow ancestorlevel1 bindingexpressionpathdatacontextflag dataitemnull target element is datagridtextcolumn hashcode44856655 target property is visibility type visibilitywhat is wrong in my code concerning the visibility attribute,['c#'] +177312,no suitable application records were found i created an app store archive file during validation it raises an error with the following message please make sure that you have set up a record for this application on itunes connect,['ios'] +177342,adding custom attribute html5 support to jsf 20 uiinput component i am trying to write a renderer which would process the placeholder attribute on an hinputtext componenti headed to this path after reading jsf 20 strips out needed html5 attributes and it seems correct heres my custom rendererpublic class inputrenderer extends comsunfacesrenderkithtml basictextrenderer override public void encodebeginfacescontext context uicomponent component throws ioexception systemoutprintlnrendering componentgetclientid string placeholder stringcomponentgetattributesgetplaceholder ifplaceholder null responsewriter writer contextgetresponsewriter writerwriteattributeplaceholder placeholder placeholder superencodebegincontext component override public void decodefacescontext context uicomponent component superdecodecontext component override public void encodeendfacescontext context uicomponent component throws ioexception superencodeendcontext component and this renderer is registered in faces config as renderkit renderer componentfamilyjavaxfacesinputcomponentfamily renderertypejavaxfacestextrenderertype rendererclasscomexamplerendererinputrendererrendererclass rendererrenderkitthis gets registered fine no issues theremy intention is to process the placeholder attribute insert it and then delegate the processing to super my above code does not work because i am inserting the attribute at a wrong place it must be inserted after writerstartelementinput has executed however the startelement must be happening somewhere in the supers encodebegin method so how do i insert a custom attribute placeholder in this case and then continue the execution flownb the above code does add a placeholder attribute but not to the input component that i intend to it writes it to the parent of the input since i am trying to write an attribute before the component itself is actually written in the stream it applies the attribute to the current component,['html'] +177386,how can you read a file line by line in javascript i am writing a webapp for the ipad that will be loading data from a text file a sample data set is around 400 kb i have everything set up except the file reading the way i have set up my code you pass an object which reads a file line by linehow can i read a file line by lineif there is no direct way to read a file line by line can someone please show me an example of how to read a file into a string object so that i can use the split method p,['javascript'] +177392,how to thistinguish between a method and an attribute in python by name sometimes i find it hard to thistinguish between a method and an attribute by it is name without appending parenthesesfor exampletherere keys method and text attribute in xmletrelementtrelement classtextthe text attribute can be used to hold additional data associated with the element keysreturns the elements attribute names as a listis there some basic rulesconventions to make text an attribute but keys a methodif i make text a method and keys an attribute it still seems ok,['python'] +177394,is it possible to let mouse events pass through a canvas layer i have a grid of images and a canvas layer on top of it i would like to do some animations on the canvas tag once the user rolls over a thumbnail image from the grid so i wonder if is possible to let mouse events pass through the canvas layer,['javascript'] +177424,change a django form field to a hidden field i have a django form with a regexfield which is very similar to a normal text input field in my view under certain conditions i want to hide this from the user and trying to keep the form as similar as possiblewhats the best way to turn this field into a hiddeninput field i know i can set attributes on the field with formfieldnamefieldwidgetattrreadonly readonly and i can set the desired initial value with forminitialfieldname mydesiredvalue however that would not change the form of the widgetwhats the bestmost djangoyleast hacky way to make this field a input typehidden field,"['python', 'html']" +177443,how can i put square brackets in regexp javascript i am trying thisstr bla blastr strreplacegconsolelogstrand the replace does not work what am i doing wrongupdate i am trying to remove any square brackets in the stringwhats weird is that if i do replaceg replaceg it works butreplaceg does not,['javascript'] +177471,ruby on rails drop down box on change event i have two drop down boxes in my applicationbased on the value selected in 1st combobox the values in 2nd drop down box should be populatedand these values should come from databaseplease help me,"['ruby-on-rails', 'ruby']" +177477,cc optimizations i have been raised in a very oo manner when it comes to programming which has unfortunately meant that highly optimized code is not my forte i am fairly good at c now and can usually do things in reasonably intelligent ways but i still have trouble thinking of the most optimized way to handle situationsone example would beint strlenconst char str char s for sstr s s return sstri would never have thought of that myselfso what are some good resources that expose you to optimized code like this i would like to find a place where i could read up on the theory behind it what the compiler does in the background which makes it worthwhile etcit would also be nice if some resources were noted for studying optimized data structures with application to reallife scenarios but that is probably too much to ask,"['c++', 'c']" +177488,c inheritance via dominance warning i am trying to implement a rather large object that implements many interfaces some of these interfaces are pure virtual i may have a problem in diamond inheritance visual studio is reporting a warning of c4250 class1 inherits class2member via dominance first of all these classes are inherited virtually as it should be the following is the partial class design that causes this problema b c ab bc bc2 d implementation of b c bc bc2 bigin this entire tree only d implements virtual methods there is no other definition of the method in question and all virtual methods of b is listed in warnings if important d is a complete classi read this happens with boost serialization and it is safe to thisregard the warning is this method i am trying to achieve valid is it safe to thisregard this warningnote 1 this is not a duplicate of visual studio compiler warning c4250 class1 inherits class2member via dominance i have tried the solution proposed therenote 2 i can also send class diagram but its a little more complicated than thiseditfull warning is as follows warning c4250 ggeresourceimageresource inherits ggegraphicsimagetextureggegraphicsimagetexturedrawin via dominanceggeresourceimageresource is big in the drawing ggegraphicsimagetexture is d drawin is one of the six methods i get warning for,['c++'] +177493,stdforward vs stdmove while binding lvalue to rvalue reference is there a difference between move and forward herevoid testint val val4void main int nb teststdforwardintnb teststdmovenb stdcinignore,['c++'] +177500,how do i convert a document made in jsoup the java html parser into a string i have a document that was made in jsoup that looks like thisdocument doc jsoupconnectgethow do i convert that doc into a string,['java'] +177509,will ignoring ithisposable cause memory leaks in the comments to an answer i wrote we had a thiscussion about memory leaks and ithisposable where we did not come to any real conclusiona class that handles unmanaged resources likely implements ithisposable if ignore that and neither call thispose nor wraps the object in a using will that lead to the unmanaged resource being leaked or will it be properly cleaned up when the gc collects the objectwe can assume that the class handling the unmanaged resource has a correct implementation of ithisposable including finalizer etc,"['c#', '.net']" +177518,selector color on linearlayout i am trying to assing a color selector to an extended class of linearlayout so i think its like if we speak about linearlayouti followed the instructions on this post the answer talking about shapesnow i have 3 xml on drawables foldersnormalxml fileshape xmlnsandroid androidshaperectangle solid androidcolorf shapepressedxml fileshape xmlnsandroidandroidshaperectangle solid androidcolor0 shapeand finally bgxml filexml version10 encodingutf8selector xmlnsandroid item androidstate pressedtrue androiddrawabledrawablepressed item androidstate focusedtrue androiddrawabledrawablepressed item androidstate selectedtrue androiddrawabledrawablepressed item androiddrawabledrawablenormal selectori am accessing this in the following way drawable d getresourcesgetdrawablecontextgetresourcesgetidentifiermypackageuritprojectdrawablebg null null viewsetbackgrounddrawabledthe normal state its fine with the color set at normalxml but no way with the other ones i press my view and nothing happens it is not changing color in any wayi cannot see what i am doing wrongthank you,['android'] +177522,how can i readstream a file without loading the entire file into memory how can i read an arbitrary file and process it piece by piece meaning byte by byte or some other chunk size that would give the best read performance without loading the entire file into memory an example of processing would be to generate an md5 hash of the file although the answer could apply to any operationi would like to have or write this but if i can get existing code that would be great tooc,['c#'] +177523,what does a space in a jquery selector mean i ran into a reaction i could not explain today while working with some very basic jquery today and i was hoping one of you could explain to me what is occurring to lead to these resultsso i have a dom model simplified herediv classobjectcontainer div classobject divstuffdiv div classobject divstuffdivthe idea was to set an attribute on the last object using this codedivobjectcontainerfinddivobject lastattrindex 1i understand now the code here was incorrect and the proper find selector should be divobjectlast but it is the results i do not understand when i executed the first code this occurreddiv classobjectcontainer div classobject div index1stuffdiv div classobject divstuffdivcould someone explain to me how my initial selector managed to set an attribute on a child node,['jquery'] +177524,activerecord custom type naming scheme i am dealing with a table that already has a column with natural type names eg there already exists a column called provider that has values of either foo or bar i want to use sti on this table using the existing type names as it seems silly to have to add an additional column called type for active record to use problem is these type names do not match up exactly the the ruby classes i was hoping to be able to set up a custom mapping eg class1 foo class2 bari tried the following in the base claset inheritance column provider in class1def selfsti name fooend in class2def selfsti name barendbut this does not seem to cut it i getthe singletable inheritance mechanism failed to locate the subclass fooactiverecord 308 libactive recordbaserb923in find sti classit looks like activerecord is only equipped to handle full class names and demodularized class names i am not sure what the purpose of having a protected sti name method is at alli am about to dig deeper into the framework and override activerecordbasecompute type before i do that has anyone done this before is this a wild goose chasecan rails handle custom type names or am i stuck with having the ruby class namesupdatei got this to work with in the base classdef selffind sti classtype name do mapping from foobar to class1class2 endi am still wary of hitting some more issues down the road is this the right way to do this,"['ruby-on-rails', 'ruby']" +177534,digitally sign a pdf document in ios recently i was assigned an ios project where i need to digitally sign a pdf document using a key that the application will download from a serveri do not yet have a clear idea of the process involved in signing documents what i know until now is that i will be signing my pdf using a private key file provided to me and then the verification will be done using the public key version of the same filei have seen that digital sign can be achieved using libraries like itext for java or itextsharp for c that is why i would like to know if there is something similar for ios and if not what would be the process to achieve this using quartz abilities to manage pdf documents any idea would be a great starting point thanks a lotwelli have been checking the apple docs and i found thisi think this is supossed to support the x509 format wich i could use to sign the pdf as an instance os cfdata i guess also i have been checking the cryptoexercise sample code but i am not 100 sure if this is what i am looking for other suggestions have told me to check adobe documentation but have not found yet a c api to sign documents using certificatesif somebody has used the certificate services provided by apple it would be great any suggestion or more sample codes to understand the process thanks a lot,"['iphone', 'ios', 'objective-c']" +177538,ruby on rails 3 to json not including all attributes i am using the to json method on my model object that i created by doing something likeuser userfind1when i do userto json a lot of attributes are missing including userid from the encoded json string it appears that all of the attributes that i have added as attr accessible from the user model are there but none of the others perhaps that is what to json is doing but i think that adding id to attr accessible is a no go what is the right way of solving this problemupdate this looks to be a specific issue with devise if i comment out the following from userrb everything works as expecteddevise rememberable trackable token authenticatable omniauthable,['ruby-on-rails'] +177542,yaml parsing and python what is the best way to parse a yaml file into a python objectfor example this yamlperson name xyzto this python classclass personyamlyamlobject yaml tag person def init self name selfname namei am using pyyaml by the way,['python'] +177557,trouble with negating core data nspredicate relationships i am scratching my head on this one i have a work around but i do not understand it so that does not count what i want to do is for the entity in this case a photo lets say i want to find all the photos reviewed by anyone other than the specified user the relationship here is photoreviewuser where a photo can have multiple reviews and each review is owned by exactly one user the first two examples were my logical first attempts but does not work i found some similar code that shows the subquery which works but can anyone explain why the first two examples do not work this does not worknspredicate predicatewithformatnot any reviewsuser selfuser this does not worknspredicate predicatewithformatnone reviewsuser selfuser this worksnspredicate predicatewithformatsubqueryreviews x xuser count 0 selfuser,['ios'] +177562,get jquery version from inspecting the jquery object is there a way to find out what version of jquery is being used by inspecting the jquery object jquery is dynamically getting added to my page and i cannot see any reference to it in my markup if i inspect it in my browsers console its there,"['javascript', 'jquery']" +177564,how many rows with data in excel sheet i am trying to count the number of rows in a spreadsheet which contain at least one non blank value over a few columns ierow 1 has a text value in column arow 2 has a text value in column brow 3 has a text value in column crow 4 has no values in a b or cthe formula would equate to 3 because rows 1 2 3 have a text value in at least one column similarly if row 1 had a text value in each column a b c this would be counted as 1,['.net'] +177590,implicit conversion of an objectivec pointer to void is thisallowed with arc what does this mean and what alternative do i haveimplicit conversion of an objectivec pointer to void is thisallowed with arci am porting an xcode3 project to ios5 wich uses audiosessioninitialize like thisaudiosessioninitializenull null null selfwhere self here is a viewcontroller,['objective-c'] +177625,how to use view flipper with three layouts i am currently using viewflipper for my main activity with two different layouts i want to use a third layout but i can only find the shownext and showprevious commands can someone show me how to implement a third layout using viewflipper,['android'] +177651,nsimageview background color i have requirement like this have one nsimageview and which will be changing frequently on the timer basis on resizing it needs to maintain the aspect ratio so image may not occupy the entire frame of the image in such case i need to thisplay the background color black can anyone help me how can i achieve that on googling got one approach is to have subclass of nsimageview but no idea what will impact on the performance as image is changing frequently,['objective-c'] +177653,thistributing a thirdparty developed application via app store i am newbie in ios development and thistribution so may be my question is too basicconsider the following i suppose very common situationour company a asked a software company b to develop an iphone application for us naturally we want to thistribute this application via app store under our company brand ahowever they say a strange thing like the application can be thistributed only under the developer name company b and that is unacceptable for uswhat is a possible solution here,['iphone'] +177656,why are there multiple total time for which application threads were stopped logs between two minor gcs i am running a java application with the following settings xms1g xmx2g xdebug xloggcusrlocalresinloggclog xxprintgcdetails xxpermsize150m xxprintgctimestamps xxprinttenuringthistribution xxprintgcapplicationstoppedtime xxprintgcapplicationconcurrenttime xxprintheapatgc xxuseconcmarksweepgci thought turning on xxprintgcapplicationstoppedtime switch would output how much time the application is stopped each time a gc occurs but a got multiple lines of logs telling how much time the application is stopped between two minor gcs like the following logstotal time for which application threads were stopped 0430 secondsapplication time 14104236260 secondsheap before gc invocations636 full 2 par new generation total 38336k used 34123k 0x02ab1a60 0x02ab43f0 0x02ab43f0 eden space 34112k 100 used 0x02ab1a60 0x02ab3bb0 0x02ab3bb0 from space 4224k 0 used 0x02ab3bb0 0x02ab3bb2de0 0x02ab3fd0 to space 4224k 0 used 0x02ab3fd0 0x02ab3fd0 0x02ab43f0 concurrent marksweep generation total 1006016k used 208278k 0x02ab43f0 0x02af1a60 0x02aab31a60 concurrentmarksweep perm gen total 153600k used 90763k 0x02aab31a60 0x02aab3b060 0x02aab3b060122682024 gc 122682024 parnewdesired survivor size 2162688 bytes new threshold 4 max 4 age 1 4896 bytes 4896 total age 2 2272 bytes 7168 total 34123k10k38336k 037720 secs 242402k208291k1044352k 038540 secs times user0 sys0 real0 secs heap after gc invocations637 full 2 par new generation total 38336k used 10k 0x02ab1a60 0x02ab43f0 0x02ab43f0 eden space 34112k 0 used 0x02ab1a60 0x02ab1a60 0x02ab3bb0 from space 4224k 0 used 0x02ab3fd0 0x02ab3fd2bf8 0x02ab43f0 to space 4224k 0 used 0x02ab3bb0 0x02ab3bb0 0x02ab3fd0 concurrent marksweep generation total 1006016k used 208280k 0x02ab43f0 0x02af1a60 0x02aab31a60 concurrentmarksweep perm gen total 153600k used 90763k 0x02aab31a60 0x02aab3b060 0x02aab3b060total time for which application threads were stopped 044760 secondsapplication time 3176313600 secondstotal time for which application threads were stopped 04960 secondsapplication time 865483550 secondstotal time for which application threads were stopped 05090 secondsapplication time 01400 secondstotal time for which application threads were stopped 01360 secondsapplication time 466827150 secondstotal time for which application threads were stopped 04430 secondsapplication time 742952540 secondstotal time for which application threads were stopped 04940 secondsapplication time 01300 secondstotal time for which application threads were stopped 01130 secondsapplication time 01290 secondstotal time for which application threads were stopped 01290 secondsapplication time 511991810 secondstotal time for which application threads were stopped 04860 secondsapplication time 1907426760 secondstotal time for which application threads were stopped 04930 secondsapplication time 0750 secondstotal time for which application threads were stopped 010 secondsapplication time 554635280 secondstotal time for which application threads were stopped 04900 secondsapplication time 1807308270 secondstotal time for which application threads were stopped 05060 secondsapplication time 609953830 secondstotal time for which application threads were stopped 05490 secondsapplication time 609591480 secondstotal time for which application threads were stopped 06410 secondsapplication time 29205720 secondsheap before gc invocations637 full 2 par new generation total 38336k used 34122k 0x02ab1a60 0x02ab43f0 0x02ab43f0 eden space 34112k 100 used 0x02ab1a60 0x02ab3bb0 0x02ab3bb0 from space 4224k 0 used 0x02ab3fd0 0x02ab3fd2bf8 0x02ab43f0 to space 4224k 0 used 0x02ab3bb0 0x02ab3bb0 0x02ab3fd0 concurrent marksweep generation total 1006016k used 208280k 0x02ab43f0 0x02af1a60 0x02aab31a60 concurrentmarksweep perm gen total 153600k used 90763k 0x02aab31a60 0x02aab3b060 0x02aab3b060124099341 gc 124099341 parnewdesired survivor size 2162688 bytes new threshold 4 max 4 age 1 20680 bytes 20680 total age 3 808 bytes 21488 total 34122k25k38336k 036900 secs 242403k208305k1044352k 037700 secs times user0 sys0 real001 secs heap after gc invocations638 full 2 par new generation total 38336k used 25k 0x02ab1a60 0x02ab43f0 0x02ab43f0 eden space 34112k 0 used 0x02ab1a60 0x02ab1a60 0x02ab3bb0 from space 4224k 0 used 0x02ab3bb0 0x02ab3bb6488 0x02ab3fd0 to space 4224k 0 used 0x02ab3fd0 0x02ab3fd0 0x02ab43f0 concurrent marksweep generation total 1006016k used 208280k 0x02ab43f0 0x02af1a60 0x02aab31a60 concurrentmarksweep perm gen total 153600k used 90763k 0x02aab31a60 0x02aab3b060 0x02aab3b060why are there multiple consecutive lines of total time for which the application threads were stopped and application time logs between two minor gcs what is each line of them related to a gc that is not outputted in detail or are they not caused by gcif i want to know the total time my application stopped for during gcs should i sum the time in all these logs,['java'] +177658,the execute permission is denied on the userdefined table types i have a question about userdefined table types in sql server 2008for the need of one of the aspnet application we defined our own tabletypes on sql server 2008 to use them as parameters in the stored procedures when executing sql command in aspnet application we pass datatable object as parameter for stored procedure see here for an examplethe problem is that when we run sql command execute stored procedure from aspnet we get an errorthe execute permission was denied on the object ourtabletype database ourdatabase schema ourschemawhy is that so why do we need to set permission on userdefined table types why is not enough to have permission set just on stored procedure that uses it and if we have to set it no matter what why there is no execute permission type to set in properties window whatsoever i can see only control references take ownership view definitionwhat i also do not understand is that setting permission to control in properties window solves the problem and the stored procedure runs without problems,['asp.net'] +177669,is it inefficient to pass large objects as parameters in java let us say for example i have a class a that creates an instance of a fairly big object b is passing b as a parameter to a method in a class c inefficient that is does it just pass a reference or does it shift the objects memory around as wellthanks,['java'] +177693,securityexception permission denial error i have just upgraded to the new version of gmail v235 and i have got an app that queries the content provider to get details about the contacts that messages are received forwith the latest version i am getting the below errorjavalangsecurityexception permission denial opening provider comgoogleandroidgmprovidermailprovider from processrecord40adef58 3576comrageconsultingandroidlightflow10056 pid3576 uid10056 requires comgoogleandroidgmpermissionread gmail or comgoogleandroidgmpermissionwrite gmailfor gmail in my manifest i am declaring the followingpermissions for gmailusespermission androidnamecomgoogleandroidgoogleappspermissiongoogle authusespermission androidnameandroidpermissionget accountsusespermission androidnamecomgoogleandroidprovidersgmailpermissionread gmailusespermission androidnamecomgoogleandroidgmpermissionread gmailusespermission androidnamecomgoogleandroidgmpermissionwrite gmailso as far as i can tell i have got the permissions correctmy gmail receiver looks like the following receiver androidnamereceivergmailreceiver intentfilter action androidnameandroidintentactionprovider changed androidpriority10 action data androidschemecontent androidhostgmaills androidpathpatternunread data intentfilter intentfilter action androidnameandroidintentactionprovider changed androidpriority10 action data androidmimetype androidschemecontent androidhostgmaills androidpathunreadi data intentfilter receivercan anyone think of something that i may have missed out on,['android'] +177711,condition variable in windows wont compile i am trying to make a windowsversion of a program written for linux in c for the program to be threadsafe i use pthread cond t and pthread cond wait in the linux version these functions use a mutex to help make sure that the waiting thread is actually waiting i found that condition variable may do the trick in windows however i cannot figure out why it wont compile i get the error error condition variable does not name a type even though all relevant headers are included as far as i can tell i tried copypasting the code on which wont compile either i am using gccany ideas on how to compile this or any alternate approaches which does not involve condition variables,['c++'] +177721,whats the best column type for google user id google has very long user ids10456012440368899812321 characters which is not possible to input into bigint field not unsignedwhat column type would you use for such ids i do not think that varchar is good idea,['mysql'] +177728,split an array into two based on a index in javascript i have an array with a list of objects i want to split this array at one particular index say 4 this in real is a variable i want to store the second part of the split array into another array might be simple but i am unable to think of a nice way to do this,['javascript'] +177741,gson date format i am trying to have a custom date format in gson output but setdateformatdateformatfull does not seem to work and it the same with registertypeadapterdateclass new dateserializerit is like gson does not care about the object date and print it in its wayhow can i change thatthanksedit entitypublic class advicesheet public date lastmodifpublic void method gson gson new gsonbuildersetdateformatdateformatlongcreate systemoutprintlngsontojsonadvicesheeti always use javautildate setdateformat does not work,['java'] +177761,is javascript size a performance concern after it is cached i am writing a project which will use some fairly large js libraries including jquery ui the project will be run within an intranet though so download time is not really an issue for me and most people should only have to download the libraries once since i assume they will remain in the browsers cachemy question is about how modern browsers ie9ff5etc handle the processing of the javascript code i imagine at some point it is compiled but is this done on each page load or is the compiled code cached too if so is it cached even after the browser is closedthis web app may run on some low powered portable devices so i wanted to be reasonably efficient i wanted to combine all the javascript files into one large one that is linked to on every page of the appbut depending on how much work the browser must do to process all the js i am wondering if i should split them up so not all pages must load all the js obviously that is more work thoughany thoughts or info would be appreciated thank you,"['javascript', 'jquery']" +177790,how to do inheritance of resource files resx imagine youre working on a net 40 project that is made up of hundreds of assemblies each having its own resource file resx for localization the localized strings are accessed from c through classes autogenerated with resxfilecodegenerator which creates a resourcefiledesignercs file string test resourcefileteststringeach assembly has localized strings which are particular to it but there are strings which are common to all assemblies you tell yourself that it would be nice to have those common strings in a parent resource file on which the code would fall back if the resource key is not available in the local resource file you then say hey inheritance could work here and indeed doing something like this in the autogenerated designer file does work internal class resourcefile parentresourcefilethat is strings not defined in resourcefile but defined in parentresourcefile can still be accessed with resourcefilestringinparentfilebut something in the designer files header troubles you changes to this file may cause incorrect behavior and will be lost if the code is regenerated plus you know playing in the autogenerated designer files is frowned upon so you come here and you askwhen does resxfilecodegenerator generateregenerate the designerclass is there a way to turn off that autogeneration will we haveto forego the advantages of resxfilecodegenerator and implement ourown handling of resourcemanagerand you say thank you,['c#'] +177816,how to integrate my app with google is there any way to integrate google with my app so that from my app i can read the posts post something on my wallaccess different circles at least post somethingdid google provide any api or sdk for this,['android'] +177833,how does django handle multiple memcached servers in the django documentation it says thisone excellent feature of memcached is its ability to share cache over multiple servers this means you can run memcached daemons on multiple machines and the program will treat the group of machines as a single cache without the need to duplicate cache values on each machine to take advantage of this feature include all server addresses in location either separated by semicolons or as a listdjangos cache framework memcachedhow exactly does this work i have read some answers on this site that suggest this is accomplished by sharding across the servers based on hashes of the keys multiple memcached servers questionhow does the memcachestore really work with multiple serversthat is fine but i need a much more specific and detailed answer than that using django with pylibmc or pythonmemcached how is this sharding actually performed does the order of ip addresses in the configuration setting matter what if two different web servers running the same django app have two different settings files with the ip addresses of the memcached servers in a different order will that result in each machine using a different sharding strategy that causes duplicate keys and other inefficiencieswhat if a particular machine shows up in the list twice for example what if i were to do something like this where 127001 is actually the same machine as 1721926240caches default backend djangocorecachebackendsmemcachedmemcachedcache location 127001211 172192624011211 172192624211211 what if one of the memcached servers has more capacity than the others if machine one has as 64mb memcached and machine 2 has a 128mb will the sharding algorithm take that into account and give machine 2 a greater proportion of the keysi have also read that if a memcached server is lost then those keys are lost that is obvious when sharding is involved whats more important is what will happen if a memcached server goes down and i leave its ip address in the settings file will djangomemcached simply fail to get any keys that would have been sharded to that failed server or will it realize that server has failed and come up with a new sharding strategy if there is a new sharding strategy does it intelligently take the keys that were originally intended for the failed server and divide them among the remaining servers or does it come up with a brand new strategy as if the first server did not exist and result in keys being duplicatedi tried reading the source code of pythonmemcached and could not figure this out at all i plan to try reading the code of libmemcached and pylibmc but i figured asking here would be easier if someone already knew,['python'] +177861,is documentready necessary if i put all my javascript at the bottom of the page possible duplicatejquery is documentready necessary putting the js just above the body tag improves perceived load time because the browser does not have to read and parse through all the js before it can start rendering the pagebut it has another benefit does not it we do not need to wrap the js in documentreadyfunction because all the elements are already above the js and thus are ready for manipulationis documentready necessary to ensure the dom has fully loaded and is ready for manipulationis there any difference between the execution times would one method fire faster than the othercould we link our external js files script src at the bottom of the page too then or does that need to be in the header,"['javascript', 'jquery']" +177877,java sort based on two columns lets say i have table like this string int1 int2 foo 5 0 faa 4 1 zaa 0 1 zoo 4 2 laa 4 3 loo 1 4what i would like to get is table like this string int1 int2 foo 5 0 laa 4 3 zoo 4 2 faa 4 1 loo 1 4 zaa 0 1first thing that happens is sort based on column int1second thing that happens is sort of based on column int2 but only on rows that have same numbers in column int1how should i approach this problem without using any database engine,['java'] +177883,unable to run nodejs on android phone i have been trying to port nodejs on android phone by following the link below js on androidi created the nodetar on qemu environment and sent it to the ubuntu machine i have put all so files in systemlib and node bin file in systembin when i try to run it it gives node not found even though it is present note i have manually pushed the files since tar command does not work on android i am using a rooted device is there any way to create the binary file in android directly without the arm environment am i missing something thanks for the help thanks for the response i have installed debian on android using your suggested linkafter that when i run the following commands on chroot to be able to make and install node js refgit clone nvmnvmsh export jobs1 nvm install v0411i get the following errornvmsrcnodev0411depsv8srcarmmacroassemblerarmcc613 error error for thumb interworking we require an architecture which supports blxscons objreleasearmmacroassemblerarmo error 1scons building terminated because of errorswaf leaving directory nvmsrcnodev0411buildbuild failed task failed err 2 task libv8a sconstruct libv8aalternately if i try the following mkdir tmp cd tmp wget tar xvzf nodev0411targzadded marcharmv5t to ccflagsin nodev0411depsv8sconstruct and the cd nodev0411 configure make make installthe installation runs without errors node version reports v0411 and when i try to run any node commands i get pure virtual method called terminate called without an active exception abortedcan you please let me know what i am doing wrong here,['android'] +177884,what is the best standard data structure to build a graph at first i am a beginner at c and i am self learning it so please be quite simple in answers i need to program a graph that contains nodes each node has id and list of edges each edge has the other node id and the thistance what i am looking for is what should i use to build this graph considering that i wants to use dijkstra algorithm to get the shortest path form one point to the other so searching performance should be the most important i think i have searched a lot and i am so confused now thank you in advance for the help,['c++'] +177891,ax error when using accessibility inspector for ios app i am testing an iphone app with the simulator whenever i click on certain elements i receive this error in consoleax error could not find my mock parent most likely i am stalethis error does not seem to cause any sideeffects i can use the app and examine the elements freely any idea what it may be caused by,"['iphone', 'ios']" +177894,aspnet refuses to respect my authority i have managed to impersonate a user successfully using the logonuser interop eg dllimportadvapi32dll setlasterror true static extern bool logonuser string principal string authority string password logonsessiontype logontype logonprovider logonprovider out intptr tokenthis works fine when i go to my immediate window and enter windowsidentitygetcurrentname the impersonated user shows as my currentuser when i release this user it goes back to my real user no problems here i am am impersonatinghowever when i attempt to write a file to a share that the user has access to i getaccess to the path path name deniedi have been able to log into windows manually as the user i am impersonating navigated and written a file to the share the user definately has administrative privlidges to the directory i am targetingi am allowing the end user to upload a file and using the httppostedfilebase object write a file to this share essentially i am restricting the impersonation to the block of code to upload the file once it is finished it goes back to the original authenticated ldap user eg imp impersonationimpersonateusersomeusersomepassword httppostedfilebase hpf requestfilesfile as httppostedfilebase hpfsaveaspath impersonationstopimpersonatingimpthe path is correctwhen i save the file using the saveas method is it respecting my impersonationis it attempting to write the file under another account i am not aware of and if so how can i change thisthere does not seem to be a whole lot of control using the saveas method not a single overload are there any other alternatives to using this object that would give me greater control over my credentials,['asp.net'] +177924,java regex split string i am kind of stuck trying to come up with regular expression to break up strings with the following propertiesdelimited by the pipe characterif an individual value contains a pipe escaped with backslashif an individual value ends with backslash escaped with backslashso for example here are some strings that i want to break uponetwothree should yield one two threeonetwothree should yield onetwothreeonetwothree should yield one twothreenow how could i split this up with a single regexupdate as many of you already suggested this is not a good application of regex also the regex solution is orders of magnitude slower than just iterating over the characters i ended up iterating over the characterspublic static liststring splitvaluesstring val final liststring list new arrayliststring boolean esc false final stringbuilder sb new stringbuilder1024 final characteriterator it new stringcharacteriteratorval forchar c itfirst c characteriteratordone c itnext ifesc sbappendc esc false else ifc esc true else ifc listaddsbtostring sbdelete0 sblength else sbappendc ifsblength 0 listaddsbtostring return list,['java'] +177926,how to configure pylint to check all things pep8 checks searching for an answer on pylints mailing list brings no interesting resultspylint is known to be very customizable so i guess this should be possible the reason i would like pylint to check compliance with pep8 is becausepydev has much better support for pylint than it has for pep8it is easier to have one tool doing all checks than having to use twoi also asked this question on pylints mailing list at example of diagnostic messages from pep8 which i do not get from pylinte203 whitespace before e225 missing whitespace around operatore251 no spaces around keyword parameter equalse301 expected 1 blank line found 0e303 too many blank linese501 line too long 90 charactersw291 trailing whitespacew292 no newline at end of filew293 blank line contains whitespace,['python'] +177931,when are files from nscachesdirectory removed in what circumstances would files in the ios nscachesdirectory get removed obviously delete and reinstall an application what about application upgrade what about low thisk space conditions anything else,"['iphone', 'ios']" +177938,alternatives to python popencommunicate memory limitations i have the following chunk of python code running v27 that results in memoryerror exceptions being thrown when i work with large several gb filesmyprocess popenmycmd shelltrue stdoutpipe stderrpipemystdout mystderr myprocesscommunicatesysstdoutwritemystdoutif mystderr sysstderrwritemystderrin reading the documentation to popencommunicate there appears to be some buffering going onnote the data read is buffered in memory so do not use this method if the data size is large or unlimitedis there a way to thisable this buffering or force the cache to be cleared periodically while the process runswhat alternative approach should i use in python for running a command that streams gigabytes of data to stdouti should note that i need to handle output and error streams,['python'] +177957,scrollbar in a listviewcustomizing it is there a way to customize the standard scrollbar that listview provides in android i have not got a definitive answer on this yet,['android'] +177960,ruby module given arguments calls a method i am confused about whats going on in the nokogiri docsas far as i can tell ifrequire nokogirisome html htmlbodyh1mr belvedere fan clubh1bodyhtmlthen these three lines do the same thinghtml doc nokogirihtmldocumentparsesome htmlhtml doc nokogirihtmlparsesome htmlhtml doc nokogirihtmlsome htmlthe second is just a convenience method for the first but to my nonruby eyes the third looks like it is passing an argument to a module not a method i realize that ruby has constructors but i thought they took the form classnew not moduleargs whats going on here,['ruby'] +177972,is there a way to autogenerate valid arithmetic expressions i am currently trying to create a python script that will autogenerate spacedelimited arithmetic expressions which are valid however i get sample output that looks like this 32 42 95 24 53 21while the empty parentheses are perfectly ok by me i cannot use this autogenerated expression in calculations since there is no operator between the 24 and the 53 and the before the 21 at the end has no second argumentwhat i want to know is is there a way to account forfix these errors using a pythonic solution and before anyone points it out i will be the first to acknowledge that the code i posted below is probably the worst code i have pushed and conforms towell very few of pythons core tenetsimport randomparentheses ops parentheseslines 0while lines 10 fname opentesttxta expr numexpr lines if numexpr 2 0 numexpr 1 isdiv false boolean var makes sure there is no div by 0 isnumber isparentheses isop determine whether next element is a number parentheses or operator respectively isnumber randomrandint01 0 determines whether to start sequence with number or parentheses isparentheses not isnumber isop false counts parentheses to ensure parentheses are matching numparentheses 0 while numexpr 0 or numparentheses 0 if numexpr 0 and numparentheses 0 isdiv false exprappend numparentheses 1 elif isop and numparentheses 0 rand randomrandint05 exprappendopsrand isdiv rand 3 true if div op was just appended checks to see if was appended if rand 5 isnumber false isop true numparentheses 1 checks to see if was appended elif rand 4 isnumber true isop false numparentheses 1 all other operations go here else isnumber true isop false did not add parentheses possibility here in case expression in parentheses somehow reaches 0 elif isnumber and isdiv exprappendstrrandomrandint1100 isdiv false isnumber false isop true if a numbers up decides whether to append parentheses or a number elif isnumber rand randomrandint01 if rand 0 exprappendstrrandomrandint0100 isnumber false isop true elif rand 1 if numparentheses 0 exprappend numparentheses 1 else rand randomrandint01 exprappendparenthesesrand if rand 0 numparentheses 1 else numparentheses 1 isdiv false numexpr 1 fnamewrite joinexpr n fnameclose lines 1,['python'] +177990,multiline inlineblock becomes a block and ruins my nifty quote effect i am trying to create a block quote that has huge quotation marks on it is sides the text content of the block quote is dynamic and so the marks should align according to it is sizei have used an inlineblock element so it will shrinktofit and contain it is text and i am 90 there but my only problem is that an inlineblock element becomes a block element when it has multiple linesto illustrate why this is a problem i have made jsfiddle snippetas you can see most of the blocks look rightsingle line no problem the closing mark attaches itself to thelast wordmultiple lines the blockquote takes full availablewidth still not much of a problemsame as 2 just shorter wordshere is where it gets tricky since the inlineblock elementbecomes a block element it takes full available width and ruins the effect by putting the closing mark really fari have no control on the contents length of words sometimes example 4 will occurdoes anyone have an idea how to solve thisi am also willing to throw away all of this code if you have a completely different approach to get the same effectthanks,"['html', 'css']" +177996,how to check if a number is included in a range in one statement i am using ruby on rails 309 and i would like to check if a number is included in a range that is if i have a variable number 5 i would like to check 1 number 10 and retrieve a boolean value if the number value is included in that rangei can do that like thisnumber 1 number 10but i would like to do that in one statement how can i do that,"['ruby-on-rails', 'ruby']" +178019,help for solving drop column default value of a table error i have a table and i want to drop or set the default value of one of columns i use below scripts alter table accaccountgroup alter column name drop defaultalter table accaccountgroup alter column name set default default valuewhen i run the scripts below errors appears incorrect syntax near the keyword default for drop scriptincorrect syntax near the keyword set for add scriptthese scripts are from msdnwhat is the problem i use sql server 2008 r2,['sql'] +178021,windows phone 7 call history mango api am i able to get the current call history with the call number and datetime details from the phone with the mango api i think it is not possible with the current one,['c#'] +178022,if i am already using modernizr will i then even need html5 shiv 1 if i am already using modernizr will i then even need html5 shiv to enable html5 tag support for ie2 is html5 shiv only for ie or for all browser who do not have native html 5 support like older versions of firefox safari chrome etc,['javascript'] +178061,how to allow a stdstring parameter to be null i have a function fooconst stdstring str that it does crash if you call it using foonullwhat can i do to prevent it from crashing,['c++'] +178075,android how to create fadeinfadeout sound effects for any music file that my app plays the application that i am working on plays music files if a timer expires i want the music to fade out how do i do that i am using mediaplayer to play music and music files are present in raw folder of my application,['android'] +178080,use of prototype constructor in js can someone explain to me use of meprototypeconstructor me and why is needed when this code is working and without itin code prototype object is created on me object and it is instantiated and replaced old prototype object why do i need to point to me constructor in a given up code function me thisname dejanfunction you thisname ivanmeprototype new yousomebody new memeprototypeconstructor me whymeprototypefoo function alertproto me it always fire up this alert ether constructor is pointing to me or not youprototypefoo function alertproto yousomebodyfooalertsomebodyname alert dejan,['javascript'] +178119,rails params explained could anyone explain params in rails controller where they come from and what they are referencing def create vote votenewparamsvote item paramsvoteitem id uid paramsvoteuser id extant votefindlast conditions item id and user id item uid last vote time extantcreated at unless extantblank curr time timenow endi would like to be able to read this code linebyline and understand whats going on,"['ruby-on-rails', 'ruby']" +178122,how to create the required certificates for ios development i have registered for the apple developer program and i am now able to login into the portal i am a very newbie to app development for iphone however i have read a few tutorials and blogsmy question is how can i generate the certificate for my ipod touch 43 vios device i could not find any easy to follow links so came here to know the steps from someone experienced and someone who has already done similar taskalso i have installed iphone sdk on my machine i tried to create a hello world example but when i do build go it gives some error about sdk like no sdk foundcan somebody help me with a easy to follow steps links for creating the certificates and hopefully how to set up the ios development environment on my macthanks in advance,['iphone'] +178146,declaring a reference to object and the assignment operator i feel like this question is basic enough to be out there somewhere but i cannot seem to be able to find an answer for itsuppose i have this codeclass member functionstdmap stdstring stdstring mymapconst stdmap stdstring stdstring bar return mymapvoid myfunc stdmap stdstring stdstring foo1 foo1 bar stdmap stdstring stdstring foo2 barmy understanding is that if i start using foo2 since foo2 is a reference to the same instance as what bar returns anything i do with foo2 will be reflected in mymap but what about foo1 does foo1 get a copy of mymap or does it also point to the same instance as what bar returns the c standard library says that the assignment operator for stdmap will copy the elements over but then does that mean the assignment operator is not really invoked in the declaration of foo2thanks,['c++'] +178147,idiomatic ruby execute a function until it returns a nil collecting its values into a list i stole my title from this post executes a function until it returns a nil collecting its values into a listthat question refers to lisp and is frankly over my head however i think that his questiontranslated into rubyis exactly my ownwhats the best way to create a conditional loop in ruby that executes a function until it returns nil at which time it collects the returned values into a listmy current clunky approach is thisdef foo ret arraynew x func parenthesis for clarity i am not a native ruby coder until xnil ret x x func end retendthis code snippet will do what i wantbut i know there is a cleaner more idiomatically ruby approachright,['ruby'] +178148,unexpected error creating debug information file ggpdb when i try to build my project it returns the following errorerror 1 unexpected error creating debug information file ddocumentslancedocumentsschoolcapstonegobjdebugpdb ggi have recently had the misfortune of having my pc restart on me due to sudden power supply problems maybe this is while the project was building before this problem startedwhen the pc came back online i have noticed that the changes i have made to the program prior to the sudden power down was not saved and it would not build anymore,"['c#', '.net']" +178160,django design pattern for web analytics screens that take a really long time to calculate i have an analytics dashboard screen that is visible to my django web applications users that takes a really long time to calculate it is one of these screens that goes through every single transaction in the database for a user and gives them metrics on iti would love for this to be a realtime operation but calculation times can be 2030 seconds for an active user no paging allowed it is giving averages on transactions the solution that comes to mind is to calculate this in the backend via a managepy batch command and then just thisplay cached values to the user is there a django design pattern to help facilitate these types of modelsthisplays,['python'] +178194,declaring variables without var keyword at w3schools there is writtenif you declare a variable without using var the variable always becomes globalis it useful to declare global variable inside the function i can imagine to declare some global variables in some event handler but what is it good for better usage of ram,['javascript'] +178201,pyqt or pyside which one to use i started learning a bit of python and would now like to toy around a bit with guibuilding qt seems to be a good choice because of its crossplatformishnessnow there seem to be two bindings available pyqt by riverbank computing and pyside originally developed by nokiaso which one should i choose all i can find are two year old feature comparisons but what differences are there nowadayswhich one is easier to use has morebetter documentation are both still in active developmentlicensing is not of much concern to me since i do not intend to write commercial applications,['python'] +178204,boostasioio service why use post function i would like for someone to tell me the pros and cons for using the post function why and when should i prefer using post and whywhen should i not want to use it,['c++'] +178219,java 7 precise rethrow with a final exception in previous versions of java rethrowing an exception was treated as throwing the type of the catch parameterfor examplepublic static void test throws exception dateformat df new simpledateformatymmdd try dfparsex20110731 new filereaderfiletxtread catch exception e systemoutprintlncaught exception egetmessage throw e in java 7 you can be more precise about the exception being thrown if you declare the exception finaldoes not compile in java7public static void test2 throws parseexception ioexception dateformat df new simpledateformatymmdd try dfparsex20110731 new filereaderfiletxtread catch final exception e systemoutprintlncaught exception egetmessage throw e my question the docs say that i need to declare the exception final but if i do not the code above still compiles and works am i missing something referencesproject coin multicatch and final rethrow add more flexible checking for rethrown exceptions,['java'] +178248,howto run together multiple instance of selenium browser is it possible to run together multiple instance of selenium browsers and each one will work for themselve which will increase speedi can run one likeiselenium selenium new defaultseleniumlocalhost 4 chrome httplocalhostseleniumstartbut how to open more of them and open page inside each one,['c#'] +178252,how to find the last occurrence of an item in a python list say i have this listli a b a c x d a 6as far as help showed me there is not a builtin function that returns the last occurrence of a string like the reverse of index so basically how can i find the last occurrence of a in the given list,['python'] +178254,what is a front controller and how is it implemented in php first of all i am a beginner to php and have posted a question here refactoring require once file in a project i have tried to read about front controller as much as i can but cannot get how it works or even whats all aboutcan somebody explain in brief how it works and whats all about thanks,['php'] +178297,multiple onclick on widget for the same intent my widget starts a service and the service update a list of 3 linearlayoutsi want to set on each linearlayout a setonclickpeningintent with different extrabut when i start the widget and want to click on the linearlayouts only the last one is onclickable i dont know whats wrong hope you can help meremoteviews remoteviews new remoteviewsgetpackagename rlayoutwidget layoutfor int widgetid appwidgetids int lls ridll con 1 ridll con 2 ridll con 3 for int i 0 i jraylength i try jsonobject o jraygetjsonobjecti onclick ifi 0 intent msg intent new intentgetapplicationcontext msgsopenmsgclass msg intentputextramessageid ogetstringid pendingintent msg pendingintent pendingintentgetactivity getapplicationcontext 0 msg intent intentflag activity new task remoteviewssetonclickpendingintentridll con 1 msg pendingintent else ifi 1 intent msg intent1 new intentgetapplicationcontext msgsopenmsgclass msg intent1putextramessageid ogetstringid pendingintent msg1 pendingintent pendingintentgetactivity getapplicationcontext 0 msg intent1 intentflag activity new task remoteviewssetonclickpendingintentridll con 2 msg1 pendingintent else ifi 2 intent msg intent new intentgetapplicationcontext msgsopenmsgclass msg intentputextramessageid ogetstringid pendingintent msg2 pendingintent pendingintentgetactivity getapplicationcontext 0 msg intent intentflag activity new task remoteviewssetonclickpendingintentridll con 3 msg2 pendingintent catch jsonexception e,['android'] +178300,initializereset struct to zeronull struct x char a10 char b20 int i char c char d10i am filling this struct and then using the values on the next iteration i want to reset all the fields to 0 or null before i start reusing it how can i do that can i use memset or i have to go through all the members and then do it individually,['c'] +178302,non static const data members how do i define a nonstatic const data member of a class in c if i try compiling the following codeclass apublic void print coutyendl private const int y2int main a obj objprinti get an erroriso c forbids initialization of member aya,['c++'] +178308,root url javascript i am working on an net asp mvc razor applicationthe root url on the server being mywebsitecommyapp i need to find dynamically this url to have the right url to make some ajax call to action like this ajax type post url root controlleraction data i read a few things here and there but what i found does not workdocumentlocationhostname mywebsitecomlocationhost mywebsitecomwindowlocationpathname myapplast one sounded promissing but if i navigate in the website for an url mywebsitecommyappcontrolleraction1 windowlocationpathname myappcontrolleraction,"['javascript', 'asp.net']" +178313,code koans for c is there a code koans set for c or lispi have found koans in this languages but no one in c or lispruby javascript clojure scala,['c'] +178327,arrayfind with delegate what does it return if not found i have an arrayperson myarray and i am using the following codemyarrayfindo onameequalsjohnthis article in msdn statesreturn valuetype tthe first element that matches the conditions defined by the specified predicate if found otherwise the default value for type tif i had an arrayint the default value would be zerobut in my case i am using a class let us say arraypersonwhat would be the default for my class and how can i handle the not found case using a delegate,['c#'] +178328,python byte buffer object is there a byte buffer object in python to which i can append values of specific types preferably with specifiable endianessfor examplebufadd int4 should add a 4 byte integerbufadd short10 should add a 2 byte shortbufadd byte24 should add a bytei know that i could just use structpack but this approach just seems easier ideally it should be like the dataoutputstream and datainputstream objects in java which do this exact task,['python'] +178365,how to construct stdarray object with initializer list possible duplicatehow do i initialize a member array with an initializer list you can construct an stdarray just fine with an initializer list stdarrayint 3 a 1 2 3 works finehowever when i try to construct it from an stdinitializer list as a data member or base object in a class it does not workinclude arrayinclude initializer listtemplate typename t stdsize t size typename enumtstruct enum addressable array public stdarrayt size typedef stdarrayt size base t typedef typename base treference reference typedef typename base tconst reference const reference typedef typename base tsize type size type enum addressable arraystdinitializer listt il base til reference operatorenumt n return base toperatorstatic castsize typen const reference operatorenumt n const return base toperatorstatic castsize typen enum class e a b cenum addressable arraychar 3 e ea a b cerrors with gcc 46testcpp in constructor enum addressable arrayt size enumtenum addressable arraystdinitializer listt with t char unsigned int size 3u enumt etestcpp2655 instantiated from heretestcpp1268 error no matching function for call to stdarraychar 3uarraybraceenclosed initializer listtestcpp1268 note candidates areincludec461array6012 note stdarraychar 3uarrayincludec461array6012 note candidate expects 0 arguments 1 providedincludec461array6012 note constexpr stdarraychar 3uarrayconst stdarraychar 3uincludec461array6012 note no known conversion for argument 1 from stdinitializer listchar to const stdarraychar 3uincludec461array6012 note constexpr stdarraychar 3uarraystdarraychar 3uincludec461array6012 note no known conversion for argument 1 from stdinitializer listchar to stdarraychar 3uhow can i get it to work so that my wrapper class can be initialized with an initializerlist as suchenum addressable arraychar 3 e ea a b c,['c++'] +178407,how to convert uiview to uiimage without background i have uiview that contain a pin image and a label as we know uiview is rectangle so if i convert uiview to uiimageuiimage is also rectangle i want make uiimage like the a pin image because if user click a background uiimages event will be called too i want to convert uiview to uiimage without it is background how can it bei use this method to change uiview to uiimageuiimage changeviewtoimage uiview viewuigraphicsbeginimagecontextviewboundssizeviewlayer renderincontextuigraphicsgetcurrentcontext uiimage img uigraphicsgetimagefromcurrentimagecontext uigraphicsendimagecontext return imghmm example like this i have a rectangle as a uiview and a triangle as a shape in uiview and then i want to make this uiview become a uiimage but i just want the triangle without background so the image just a triangle how can i do it,['iphone'] +178480,prevent windowopen from focusing i want to open a page in a new tab in google chrome with windowopen but i do not want that window to gain focus after it is opened but to stay in the backgroundis this possible it only has to work on google chrome it can also use the google chrome extension apithanks,['javascript'] +178490,how to override a field in the parent class i have parent and child classes in django model and i want to fill a field in parent class when initialize child class or override this field in child class class parentmodelsmodel type modelscharfield class childparent type modelscharfield does not workalso trying override init method but it does not work too how can i accomplish this,['python'] +178491,how to know the position of items in a pythons ordered dictionary can we know the position of items in pythons ordered dictionary for exampleif i have dictionary ordered dict is ordereddictionary ordered dict fruit banana drinks water animal catnow how to know in which position cat belongs tois it possible to get answer likeposition ordered dictanimal 2 or in some other way,['python'] +178497,video recording using avfoundation i am trying to record video using avfoundation when i add video input only to the session everything works fine but when i add an audio input to it it stops recording the videodelegate method is called immediately after recording starts here is my codevoid recordvideo selfsession avcapturesession alloc initifsession cansetsessionpresetavcapturesessionpresetmedium sessionsessionpreset avcapturesessionpresetmediumcalayer viewlayer selfcameraview layeravcapturevideopreviewlayer capturevideopreviewlayer avcapturevideopreviewlayer alloc initwithsessionsessioncapturevideopreviewlayerframe viewlayerboundsviewlayer addsublayercapturevideopreviewlayerselfvideoinput avcapturedeviceinput deviceinputwithdeviceself frontfacingcameraifavailable errornilselfaudioinput avcapturedeviceinput deviceinputwithdeviceself audiodevice errornilifvideoinput nslogcould not create inputelse selfoutput avcapturemoviefileoutput alloc init nsstring pathstring self outputpathstringbyaddingpercentescapesusingencodingnsutf8stringencoding nsurl fileurl nsurl fileurlwithpathpathstring session beginconfiguration session removeinputself videoinput ifsession canaddinputvideoinput session addinputvideoinput videoinput release session removeinputself audioinput ifsession canaddinputaudioinput session addinputaudioinput audioinput release ifsession canaddoutputoutput session addoutputoutput output release session commitconfiguration session startrunning output startrecordingtooutputfileurlfileurl recordingdelegateself void captureoutputavcapturefileoutput captureoutput didstartrecordingtooutputfileaturlnsurl fileurl fromconnectionsnsarray connections nslogrecording started at fileurl voidcaptureoutputavcapturefileoutput captureoutput didfinishrecordingtooutputfileaturlnsurl outputfileurl fromconnectionsnsarray connections errornserror error nslogrecording to file ended session stoprunning session release avcapturedevice frontfacingcameraifavailable nsarray videodevices avcapturedevice deviceswithmediatypeavmediatypevideo avcapturedevice capturedevice nilfor avcapturedevice device in videodevices if deviceposition avcapturedevicepositionback capturedevice device break return capturedevice avcapturedevice audiodevice nsarray devices avcapturedevice deviceswithmediatypeavmediatypeaudio if devices count 0 return devices objectatindex0 return nili call output stoprecording after some fixed time but when i add an audio input it records a single frame and didfinishrecroding delegate method is called immediatelycan anybody tell me whats wrong with this codethanks,['iphone'] +178503,how to clear cache android i need to find a way how to clear the data which my application stores in cachebasically i am using fedors android how do i do a lazy load of images in listview lazy list implementation and i want to clear the cache automatically when i have for example 100 images loadedany ideas how to do thateditcode public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain listlistviewfindviewbyidridlist adapternew lazyadapterthis mstrings listsetadapteradapter deletecachethis adapternotifydatasetchangedpublic static void deletecachecontext context try file dir contextgetcachedir if dir null dirisdirectory deletedirdir catch exception e public static boolean deletedirfile dir if dir null dirisdirectory string children dirlist for int i 0 i childrenlength i boolean success deletedirnew filedir childreni if success return false return dirdelete,['android'] +178513,postgresql insert from another table i am trying to insert data to a table from another table and the tables have only one column in common the problem is that the table1 has columns that would not accept null values so i cannot leave them empty and i cannot get them from the table2i have table1id col 1 not null col 2not null col 3 not nulland table2id col a col b col cso how could i insert id from table2 to table1 and fill the col 13 with hard coded strings like data1 data2 data3insert into table1 id select id from table2 where col a somethingwill result in error null value in column col 1 violates notnull constraint,['sql'] +178556,what is the difference between the android constructor and oncreate i am a little confused by the difference between java and android java let us say i have an activity class androidx there is no main function and there is no androidx constructor as we know it i realize that oncreate most probably initializes the androidx activity but why is there no main whats the difference,"['java', 'android']" +178569,which one should i use ossep or ospathsep they are same but which one should i useossepthe character used by the operating system to separate pathname components this is for posix and for windows note that knowing this is not sufficient to be able to parse or concatenate pathnames a use ospathsplit and ospathjoin a but it is occasionally useful also available via ospath,['python'] +178576,how to convert a vector to a vectorstring we have a legacy method that returns a vector of char pointers ie vectorchar now i need to process only strings stdstring how can i do thisthis question may sound simple but i run into couple of websites which depicted that these sort of considerations might lead to memory leaksnow i either want to get a vectorstring or even a string without any memory leaks how can i do this,['c++'] +178583,getting selected value of a combobox public class comboboxitem public string text get set public string value get set public override string tostring return text private void combobox1 selectedindexchangedobject sender eventargs e int selectedindex combobox1selectedindex int selecteval intcombobox1selectedvalue comboboxitem selectedcar comboboxitemcombobox1selecteditem messageboxshowstringformatindex 0 carname1 value2 selectedindex selectedcartext selecteval i am adding them likecomboboxitem item new comboboxitem itemtext cdname itemvalue cdid thiscombobox1itemsadditemi keep getting a nullreferenceexeption and not sure why the text seems to show up just fine,['c#'] +178585,c why is strcpy necessary can someone please explain to me why strcpy is necessary to assign strings to character arrays such as in the following code snippetint mainvoid char s4s abc failsstrcpys abc succeedsreturn 0what is the reason that s abc fails and why is strcpy the only way to assign strings to char arrays after they have been declared it seems strange to me that you have to use a function to carry out a basic assignment,['c'] +178591,debug a script that sits in a partial view why i cannot debug scripts that reside in a partial view that gets created in runtime to see the script in the list of scripts in chrome for example and debug it i have to move it to the regular view on the upper level or i have to move it to a separate js file but what if the script so small that i do not want to move it anywhere and still want to be able to debug it,['javascript'] +178610,making csr certificates in windows 7 closely related to how to generate csr when iis is not installed i also do not have this installed i am developing a mobile application for ios and i am trying to obtain a provisioning file so i can test my app locally in the process of acquiring this i am asked for a csr file and it instructs me on how to build this on my mac except i do not have a mac i have a pc and my company exclusively uses pcs i need this certificate without having access to a mac i have seen and used this csr generator but it gives me the key and request in long strings of characters and i need a csr file to upload to apple pasting it in notepad and changing the extension to csr did not work either does anyone have any insights on this,['ios'] +178620,cross browser dom ready i inherited this piece of code and it seems suboptimal and possibly incorrect since it is adding event listeners on both the window and document objects however it is working properly except for blackberry 50 can someone explain if all this is set up correctly or if there are any recommendations to make it better andor more streamlined if documentreadystate complete callback else if documentaddeventlistener documentaddeventlistenerdomcontentloadedcallbackfalse windowaddeventlistenerloadcallbackfalse else ifwindowattachevent documentattacheventonreadystatechange callback windowattacheventonloadcallback else settimeoutcallback20,['javascript'] +178675,jquery each faulty in bb os5 i have been working on debugging some jquery on a blackberry os5 device the 8530 there are a number of problems but one that i have narrowed down is related to jquerys eachthe logic is as suchobjectarrayeachfunction alerttest ifsome logic thisaddclasstestclass in any normal browser i get the alert click ok and then see that particular item in this case a td get an updated class if the logic statement is true it then repeats through the rest of the items each getting an alert me oking it and me seeing that particular tds class get updatedon the blackbery 8530 however i get each alert but the tds are not updated onebyone instead they all get updated at once after the last alert based on the if logic of the last td onlyodds are that there are serious js issues with this particular browser but i am wondering if there is a way to get around this are there alternatives to using each in jquery updatea more detailed code exampletrseachfunction var tr this var checkboxtd trfindtdtd3 var checkbox checkboxtdfindinput alertcheckboxischecked if checkboxischeckedtrue checkboxtdaddclassnotselected i am looping through each tr of a table within each tr is a td td3 that contains a checkbox i need to check each one if it is not checked i need to add a class to the tdin good browsers the alert will show a true or false and based on that particular alert you will see the class being applied appropriately to that row as you thismiss the alert it then repeats for every rowin bb os5s browser each alert pops up with the proper value but the classes are not updated until after the very last alertloop so every td class then used the logic of the last loop only update 2 fixthanks to alex i did some more playing with this and found a way to get this to work in the stubborn browsertrseachfunctionidx var tr this var checkboxtd trfindtdtd3 var checkbox checkboxtdfindinput alertcheckboxischecked if checkboxischeckedtrue trseqidxfindtdtd3addclassnotselected the fix the difference is that i am going back to the main jquery object trs and specifically grabbing one of the elements from it based on its index so based on that my final question is does the above solution have any downsides for the good browsers is there a performance hit,['jquery'] +178701,visual studio 2010 javascript highlighting i am using visualstudio 2010 with vsphp when i write or open a javascript file it is not higlighted and intellisense is not working all i see is plain text it seems that vs does not identify the javascript file when i manually order js files to open in script editor in tools options text editor file extension nothing changes highlighter in in tools options environment tools and colors is set properly do you have any ideas how can i run highlighting google says nothing,['javascript'] +178728,add line breaks or spaces between elements when using jquery append i have a jquery set of elements that i get from my dom by callingsomeselectorall my elements are divs each in its own line my divs are set css among other thingsthisplay inlineblockwhich prevents them from rendering as block elements each in its own linethe problem is that when these div are rendered they have spaces between them because there is line break in the document between each element i am comfortable with that i could of course use floatleft that would get rid of these spaces but that is not what i want because i would have other problems with container sizing etcso the problem is that i manipulate the order of these elements in my jquery set an then rerender them what i essentially do issomeselectordetachmanipulateappendtocontainer or equivalentcontainerappendsomeselectordetachmanipulatethe problem is that they get reinserted into the dom but without line breaks or spaceshow do i get these line breaks back in when appending my elements into dom,"['jquery', 'css']" +178734,multiprocessing useless with urllib2 i recently tried to speed up a little tool which uses urllib2 to send a request to the unofficialtwitterbuttoncounturl 20 urls and parses ita s results with the multiprocessing module and ita s worker pools i read several thiscussion here about multithreading which slowed the whole thing down compared to a standard nonthreaded version and multiprocessing but i coulda t find an answer to a probably very simple question can you speed up urlcalls with multiprocessing or aina t the bottleneck something like the networkadapter i dona t see which part of for example the urllib2openmethod could be parallelized and how that should workedit this is the request i want to speed up and the current multiprocessingsetup urlswfoobar wbarfoo tw url def gettweetsselfurls for i in urls try selftw queurllib2urlopentw url i selfjsonsjsonloadsselftw queread selftweetsappendurlidatetodaytweetsselfjsonscount except valueerror print continue return selftweets if name main pool multiprocessingpoolprocesses4 result poolapply asyncgettweetsi for i in urls iget for i in result,['python'] +178763,avoiding boxing by passing in single element primitive array i am working with an interface that takes type object as its input this is unfortunate for me as i have primitive data that i sometimes need to pass in through the interface this of course forces me to boxprofiling has shown this area to be a hotspot in the code i am thus exploring alternatives to make this area fasteran idea i had today for this is to preallocate a static primitive array and to store the primitive value in this and then pass the array through and then in the implementation of the interface grab the double out of the arrayi have written some code in effort to test this for reasonably high values 10 million i am seeing that the array method is significantly faster as i increase the number of iterations of my test the two convergei am wondering if anyone has thought about this approach before and if there are any suggestions on how to benchmark this wellexample codedouble data doublevalueofvalueinstinterfacedatainside interfaceobject objectdouble data double objectdouble d datavaluevsdoublearray0 valueinstinterfacedatainside interfaceobject objectdouble data double objectdouble d data0thanksrb,['java'] +178765,avaudiorecorder throws erros i use avaudiorecorder to record it worked fine on ios 4 devices but yesterday we found out recording is broken on ios5 using the iphone 5 simulator i got following error20110802 110903586 moodle783210103 error loading systemlibraryextensionsaudioipcdriverkextcontentsresourcesaudioipcpluginbundlecontentsmacosaudioipcplugin dlopensystemlibraryextensionsaudioipcdriverkextcontentsresourcesaudioipcpluginbundlecontentsmacosaudioipcplugin 262 symbol not found cfobjciscollectabledo you know where this error came from and how to fix this,"['iphone', 'ios']" +178790,need to perform wildcard etc search on a string using regex i need to perform wildcard etc search on a stringthis is what i have donestring input messagestring pattern dregex regex new regexpattern regexoptionsignorecaseif regexismatchinput messageboxshowfoundelse messageboxshownot foundwith the above code found block is hitting but actually it should notif my pattern is e then only found should hitmy understanding or requirement is d search should find the text containing d followed by any charactersshould i change my pattern as d and e is there any support in net for wild card which internally does it while using regex class,"['c#', '.net']" +178798,android viewpager and fragmentstatepageadapter i am designing an app that allows users to flip between multiple pages in a viewpager i have been struggling trying to figure out how it is possible to remove a fragment instance from a page when it is no longer visible on screen cache it to say a hashmap and then restore it so that when the user flips back to that page the views and everything else in it will be in the same state it was before removal for example my first page is a login screen that makes certain layout elements on that particular page visibleinvisible on a successful login when i flip forward enough pages then flip back to the first page the layout is reset this becomes more of a problem for another one of my pages which contains a huge horizontalvertical scrolling grid of data that i use a thread in the background to draw when it initializes i use a progress dialog to notify the user of loading progress and that becomes really annoying everytime i have to load itso i did some researchi browsed through the source code for fragmentstatepageadapter and in the destroyitem callback the state of the fragment instance being removed is saved to an arraylist when a new instance of the fragment is being created in the instantiateitem callback if an instance of an item does not already exist they keep track of this by using an arraylist a new fragment instance is created and its saved state is initialized with the corresponding fragmentsavedstate data unfortunately this data does not include the state that the views were in although i noticed that for pages with a gridviewlistview the state of the views were somehow restored if i scrolled to some random position flipped a few pages and came back it would not be resetaccording to the apithe saved state can not contain dependencies on other fragments that is it cannot use putfragmentbundle string fragment to store a fragment reference because that reference may not be valid when this saved state is later used likewise the fragments target and result code are not included in this statebeing a noob to android i am not quite sure i understand the last statementthat being said is there any way to cache view state if not i think i will just go ahead and go with leaving all the fragment pages in memory,['android'] +178811,java inheritance issue while exploring for scjp questions i came across this behaviour which i found strangei have declared two classes item and bolt as followsclass item int cost 20 public int getcost return cost class bolt extends item int cost 10 public int getcost return cost and tried to access the value of cost twicepublic class test public static void mainstring args item obj new bolt systemoutprintlnobjcost systemoutprintlnobjgetcost the output i get is 20 10i cannot understand how this happens,['java'] +178832,how often is the gc executed java how often is the gc executed in jvm every second every minute or is it random depending on the memory size i just want to have an ideathank you,['java'] +178904,mongodb c driver and memory issue i am using mongodb 182 debian and mongocsharpdriver 1104184 iis 75net 40 x64multiple items are inserted every second in a existing collection with 30 objects 19 gbthe webserver memory is increasing by 1 mb after every insert which leads very fast to 2 gb memory usagethe memory is never released anymore and only an application pool recycle can free the memoryany ideas mongoserver server mongoservercreatemongodbconnectionstringmongodatabase database servergetdatabasedbname mongocollectionresult resultcollection databasegetcollectionresultresultresultcollectioninsertresultresult looks likeprivate class result public objectid id get set public datetime timestamp get set public int location get set public string content get set updatemy problem is not the insert it is the select sorry weird codebase to investigate i reproduced it with this sample codeconsolewritelinestart gcgettotalmemoryfalsetostring0 bytesfor int i 0 i 10 i mongoserver server mongoservercreatemongodbconnectionstring mongodatabase database servergetdatabasedbname mongocollectionresult resultcollection databasegetcollectionresultresult var query queryand queryeqlocation 1 querygtetimestamp datetimenowadays90 mongocursorresult cursor resultcollectionfindasresultquery foreach result result in cursor noop consolewritelinei gcgettotalmemoryfalsetostring0 bytesoutput from a net 40 console application with 10 results in the cursorstart 193060 bytes0 12736588 bytes1 24331600 bytes2 16180484 bytes3 13223036 bytes4 30974892 bytes5 135236 bytes6 13439448 bytes7 13942436 bytes8 14026108 bytes9 14113352 bytesoutput from a net 40 web application with the same 10 results in the cursorstart 5258376 bytes 0 20677816 bytes1 29893880 bytes2 43783016 bytes3 20921280 bytes4 34814088 bytes5 48698704 bytes6 62576480 bytes7 76453728 bytes8 90347360 bytes9 104232800 bytesresultbug was reported to 10gen and they will fix it in version 14 they are working currently on 12,['c#'] +178915,android remove gravity from accelerometer readings i am developing an application for android where i need to remove gravity from accelerometer readings i have read multiple thiscussions on this problem i have also found an algorithm here but i did not really understand iti want to filter gravity from each axis not from the total accelerationcould you please help me out my code should be something likepublic void onsensorchangedsensorevent sensorevent float vals sensoreventvalues float accelerationx filtergravityvals0 float accelerationy filtergravityvals1 float accelerationz filtergravityvals2what code should i place in the filtergravity method,['android'] +178921,cannot get component to be inherited in spring in my project there is a common base class that all client classes extend this has an autowired field that needs to be injected by hibernate these are all grouped together in another class that has an autowired collection of the base class in order to reduce boilerplate for client code i am trying to get component inherited with component not doing this by default apparently it used to though i created this workaround annotationtargetelementtypetyperetentionretentionpolicyruntimecomponentinheritedpublic interface inheritedcomponent and annotated the base class with it its not pretty but i hoped it would work unfortunately it did not which really confuses me as inherited should make it workis there any other way to get component inherited or do i just have to say that any class that extends the base class needs this boilerplate,['java'] +178937,projectspackage naming convention i just know only naming convention of variable constant method but i do not know naming convention of project and package anybody can help me addition name of project should have white space thanks very much,"['java', 'c++']" +178942,encoding mail subject smtp in python with nonascii characters i am using python module mimewriter to construct a message and smtplib to send a mail constructed message isfile msgtxtcontenttype multipartmixedfrom meto subject a econtenttype textplaincharsetutf8a ei use the code below to send a mailimport smtplibssmtplibsmtpsmtpabccomtolist fopenmsgtxt above msg in msgtxt filemsgfreadfclosessendmailtolistmsgi get mail body correctly but subject is not propersubject some junk charactersa e body is correctplease suggest is there any way to specify the decoding to be used for the subject alsoas being specified for the body how can i get the subject decoded correctly,['python'] +178944,install failed dexopt error when trying to install application i have a similar problem to the ones listed here and herei am getting an install failed dexopt error every time i try to install my app on my motorola xoomhere is the error message from the console20110802 093443 blade installation error install failed dexopt20110802 093443 blade please check logcat output for more details20110802 093443 blade launch canceledand here is the corresponding logcat0802 094748910 errorpackagemanager142 package comtheisenpblade has mismatched uid 10023 on thisk 10073 in settings0802 094748910 infopackagemanager142 linking native library dir for dataappcomtheisenpblade1apk0802 094749110 errordalvikvm2094 duplicate interface lgnutrovetintintprocedure0802 094749110 errordalvikvm2094 trouble with item 1108 offset 0x5d49c0802 094749110 errordalvikvm2094 crossitem verify of section type 06 failed0802 094749110 errordalvikvm2094 error byte swap verify failed0802 094750140 errordalvikvm2094 optimization failed0802 094750150 warninstalld91 dexinv end dataappcomtheisenpblade1apk status0xff00 process failed0802 094750150 errorinstalld91 dexopt failed on datadalvikcachedataclassesdex res 652800802 094750160 warnpackagemanager142 package could not be installed in dataappcomtheisenpblade1apkheres what i have tried so farselecting the wipe user data option in the run configurations target menu though i can only see emulators and not my physical device in this tab perhaps i am not actually wiping user data from the xoomuninstalling the app from my device before trying to reinstallrestarting the device multiple timesany suggestions you can offer are very much appreciated,['android'] +178958,does dapper support sql 2008 tablevalued parameters 2 i know that dapper can support tvf but how do you send extra parameters along with tvf without adding it to the intdynamicparam class see the below example from testscs i have modified to add the extra parameterconnectionexecutecreate type int list type as table n int not null primary keyconnectionexecutecreate proc get ints x int ints int list type readonly as select from intsi tried the following but got errors no mapping exists from object type sqlmappertestsintdynamicparam to a known managed provider native typevar p new dynamicparameterspaddx 4paddintsnew intdynamicparamnew int 1 2 3 var nums connectionqueryintget ints ptolistthank you for the reply sam but the question was a little different i want to know how to pass in another variable along with the tuple see the modified sp belowcreate type int tuple list type as table n int not null primary key n2 intcreate proc get int tuples somevar varchar10 ints int tuple list type readonlyas select from ints,['c#'] +178975,using 31s usb host mode with arduino is there a good tutorial for using an arduino with an android where the android device is the usb host the android device has os version 31 honeycomb or later the only host program on the developer site is the missile launcher which seems far simpler than interfacing with an arduino would bespecifics i am trying to make an asus transformer host an arduino uno but since there is very little information on how the android host mode works i am lost on where to start i just need the android to be able to read data values out of the arduinos memory the arduino is being used to count the frequency of a signal that value then needs to be passed to the android if i have missed some simple way of doing this feel free to let me know there is a lot of information floating around about using the adk to make the arduino the host but with the transformer that is not an option see stack overflow question is it possible to get the android adk working on an asus e pad transformer running 31the information does not really need to be transformer or uno specific i just cannot seem to find examples of people using the new host mode on their tablets,['android'] +178982,how to scroll through a div by dragging and not by using the scroll bars i am working on a project that uses a touchscreen interface i have a div inside of a smaller div so the smaller div has scroll bars to access the rest of the first div here is the basic code for itdiv1 height 100px width 100pxdiv2 height 50px width 50pxand the html isdiv id div2 classdiv2 div iddiv1 classdiv1divdivusing javascript i would like to be able to scroll through div2 by pressing since it is a touch screen an unoccupied part of the screen and dragging along the div basically the scroll feature would behave the way google maps does when you click and drag in it can anybody help me with this thanks in advancenotein terms of mouse actions pressing is equivalent to clicking here just to be clear i am also working in firefox only so crossbrowser compatibility is not an issue,['javascript'] +179009,what css is used by browsers for styling invalid s ok so in html5 browsers you can haveinput classtxtbox typeemail nameemail relrequired when the email is not in the proper format it puts a red box around itmy question is what is the css that determines that style,['css'] +179027,gdal install on mac os x lion i am trying to install gdal 171 on mac os x lion usingpython setuppy buildpython setuppy installand get the errorrunning buildrunning build pyrunning build extbuilding osgeo gdal extensionllvmgcc42 fnostrictaliasing fnocommon dynamic g os pipe fnocommon fnostrictaliasing fwrapv mnofusedmadd denable dtrace dmacosx dndebug wall wstrictprototypes wshorten64to32 dndebug g fwrapv os wall wstrictprototypes denable dtrace pipe arch i386 arch x86 64 iport igcore ialg iogr isystemlibraryframeworkspythonframeworkversions27includepython27 ilibrarypython27sitepackagesnumpy200dev e2af7b7 20110721py27macosx107x86 64eggnumpycoreinclude ilibraryframeworksgdalframeworkversions17include c extensionsgdal wrapcpp o buildtempmacosx107intel27extensionsgdal wrapounable to execute llvmgcc42 no such file or directoryerror command llvmgcc42 failed with exit status 1is this the right compiler how can i get this workingupdatei get a little further with xcode installedrunning buildrunning build pyrunning build extbuilding osgeo gdal extensionllvmgcc42 fnostrictaliasing fnocommon dynamic g os pipe fnocommon fnostrictaliasing fwrapv mnofusedmadd denable dtrace dmacosx dndebug wall wstrictprototypes wshorten64to32 dndebug g fwrapv os wall wstrictprototypes denable dtrace arch i386 arch x86 64 pipe iport igcore ialg iogr isystemlibraryframeworkspythonframeworkversions27includepython27 ilibrarypython27sitepackagesnumpy200dev e2af7b7 20110721py27macosx107x86 64eggnumpycoreinclude ilibraryframeworksgdalframeworkversions17include c extensionsgdal wrapcpp o buildtempmacosx107intel27extensionsgdal wrapocc1plus warning command line option wstrictprototypes is valid for adacobjc but not for cextensionsgdal wrapcpp281322 error cpl porth no such file or directoryextensionsgdal wrapcpp281424 error cpl stringh no such file or directoryextensionsgdal wrapcpp281527 error cpl multiproch no such file or directoryextensionsgdal wrapcpp281718 error gdalh no such file or directoryextensionsgdal wrapcpp281823 error gdal privh no such file or directoryextensionsgdal wrapcpp281922 error gdal algh no such file or directoryextensionsgdal wrapcpp282024 error gdalwarperh no such file or directoryextensionsgdal wrapcpp2837 error expected initializer before averyquieterrorhandleraextensionsgdal wrapcpp2713 warning aswig modulea defined but not usedcc1plus warning command line option wstrictprototypes is valid for adacobjc but not for cextensionsgdal wrapcpp281322 error cpl porth no such file or directoryextensionsgdal wrapcpp281424 error cpl stringh no such file or directoryextensionsgdal wrapcpp281527 error cpl multiproch no such file or directoryextensionsgdal wrapcpp281718 error gdalh no such file or directoryextensionsgdal wrapcpp281823 error gdal privh no such file or directoryextensionsgdal wrapcpp281922 error gdal algh no such file or directoryextensionsgdal wrapcpp282024 error gdalwarperh no such file or directoryextensionsgdal wrapcpp2837 error expected initializer before averyquieterrorhandleraextensionsgdal wrapcpp2713 warning aswig modulea defined but not usedlipo cannot open input file vartmpccgnlepxout no such file or directoryerror command llvmgcc42 failed with exit status 1,['python'] +179042,what type of linq to sql queries should be compiled i am using linq to sql on a project and have read articles about how inefficient the framework is i have read that one way to drastically increase the performance is to create compiled queries would all queries perform better compiled or are there certain instances where it may not make much of a difference i assume this is critical on large scale applications that get a high volume of trafficthanks,['c#'] +179079,how to find all references of a particular clas overloaded operator in visual studio if i have a class that contains an overloaded operator function how do i find out where this overloaded operator is being used throughout the code other than placing a break point inside the overloaded method and seeing if the code ever hits it i tried going to the class view in visual studio right clicking on the method and selecting find all references but it claims there are no references when i know there is at least one that i added,['c++'] +179085,android youtube api available is there a youtube api available for android if not how would one go about getting videos from youtube other than through the web browser,['android'] +179107,how to thisable qlpreviewcontroller print button can anyone tell me how to remove the qlpreviewcontroller print button also would like to thisable cutpastecopy,['ios'] +179108,how should closures be formatted i ran a script through jslint and it picked out a specific issue with parenthesis placementi had writtenfunctionand it was suggested to usefunctioni am curious as to what bugs or issues this particular change fixes i would assume that because jslint picked it out as an issue there must be an issue for someoneexpanded forms function p code param parameters after the parensvs function p code param parameters within the parens,['javascript'] +179115,splash screenhow to show an image in full screen i want to make a splash screen in my application for that i need to know how to show an image in full screen this could me made by xml or java code and howfor now i just made thispublic class splashscreen extends activity private static final int stopsplash 0 private static final long splashtime 50 private handler splashhandler new handler override public void handlemessagemessage msg switch msgwhat case stopsplash remove splashscreen from view intent intent new intentsplashscreenthis jetpackclass startactivityintent break superhandlemessagemsg override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutsplash screen message msg new message msgwhat stopsplash splashhandlersendmessagedelayedmsg splashtime how can be this splash screenxml thank you for your help,['android'] +179119,linux kernel aio functionality i am testing kernel asynchronous io functions not posix aio and am trying to figure out how it works the code below is a complete program where i simply write an array repeatedly to a file opened using o direct i get an error in the callback function write missed bytes expect 1024 got 0 see the fprintf statement in work donefor those not familiar with kernel aio the code below does the followinginit some structsprepare aio io prep pwritesubmit io requests io submitcheck for event completion io geteventscall a callback function to see if everything went oki get an error at step 5 if i do not open the file using o direct things work fine but it beats the purpose of having async writescan someone tell me what i am doing wrong is this the correct usage of kernel aio for example is my use of callbacks correct are there any restrictions on the usage of o directi compile using gcc wall testc laiothanks in advance file myaiocpc author kmehta created on july 11 2011 1250 pm testing kernel aio program creates a 2d matrix and writes it multiple times to create a file of desired size writes are performed using kernel aio functions io prep pwrite io submit etc define gnu sourcedefine xopen source 600include stdiohinclude stdlibhinclude getopthinclude pthreadhinclude fcntlhinclude stringhinclude sysuiohinclude systimehinclude omphinclude unistdhinclude systypeshinclude sysstathinclude errnohinclude libaiohchar buflong seg sizeint seg rowsdouble total sizechar filenamestatic int wait count 0void io taskvoid cleanupvoid allocate 2d matrixintint file openchar void wr doneio context t ctx struct iocb iocb long res long res2int mainint argc char argv total size 1048576 1mb seg size 1024 1kb seg rows 1024 filename aioout int dims seg rows seg size allocate 2d matrixdims creates 2d matrix io task cleanup return 0 create a 2d matrix void allocate 2d matrixint dims2 int i char data create the matrix data char calloc1 dims0 dims1 sizeof char if data null printfncould not allocate memory for matrixn exit1 buf char mallocdims0 sizeof char if buf null printfncould not allocate memory for matrixn exit1 for i 0 i dims0 i bufi datai dims1 static void io errorconst char func int rc if rc enosys fprintfstderr aio not in this kerneln else if rc 0 fprintfstderr s sn func strerrorrc else fprintfstderr s error dn func rc exit1 callback function static void work doneio context t ctx struct iocb iocb long res long res2 if res2 0 io erroraio write res2 if res iocbucnbytes fprintfstderr write missed bytes expect lu got ldn iocbucnbytes res2 exit1 wait count printfd wait count wait routine get events and call the callback function work done int io wait runio context t ctx long iter struct io event eventsiter struct io event ep int ret n get up to aio maxio events at a time ret and io geteventsctx iter iter events null printfgot d eventsn n call the callback functions for each event for ep events n 0 ep io callback t cb io callback tepdata struct iocb iocb epobj cbctx iocb epres epres2 return retvoid io task long offset 0 int bufindex 0 open file int fd file openfilename initialize structures long i long iter total size seg size no of iterations to reach desired file size total size io context t myctx if0 io queue inititer myctx perrorcould not initialize io queue exitexit failure struct iocb ioqiter loop through iter times to reach desired file size for i 0 i iter i struct iocb io struct iocb mallocsizeof struct iocb io prep pwriteio fd bufbufindex seg size offset io set callbackio work done ioqi io offset seg size bufindex if bufindex seg rows 1 if entire matrix written start again from index 0 bufindex 0 printfdone preparing now submittingn ifiter io submitmyctx iter ioq perrorfailure on submit exitexit failure printfnow awaiting completionn wait count iter int res while wait count res io wait runmyctx iter if res 0 io errorio wait run res closefdvoid cleanup freebuf0 freebufint file openchar filename int fd if 1 fd openfilename o direct o creat o wronly o trunc 06 printfnerror opening file n exit1 return fd,['c'] +179125,nsurlconnectiondelegate getting http status codes in ios how can i receive the http status code 404500 200 etc for a response from a web server i am assuming it is in the nsurlconnectiondelegateobjectivec or monotouch net answer ok,"['iphone', 'ios']" +179132,impersonate tag in webconfig in aspnet i am using impersonate tag in my webconfig in aspnet 40 websitebelow is my webconfig codesystemweb authentication modewindows identity impersonatetrue usernameadministrator passwordlalla26526 authenticationsystemwebwhen i run app in visual studio i get this errorparser error message unrecognized element identitysource errorline 50 systemwebline 51 authentication modewindowsline 52 identity impersonatetrue line 53 usernameadministratorline 54 passwordlalla26526where am i going wrong,['asp.net'] +179141,can i name a c namespace starting with a number i am on a mac and cannot try it for myself right nowfor example will this compilenamespace 2somethingsomethingelse,['c#'] +179145,return this in c in java you can simply return this to get the current object how do you do this in cjavaclass myclass myclass example return this,['c++'] +179146,how do i restrict my edittext input to numerical possibly decimal and signed input i have read android limiting edittext to numbers and how do i show the number keyboard on an edittext in android unfortunately none of them seems to fit my needsi want to restrict my edittext input to only numbers however i also want to allow signed andor decimal inputhere is my current code i need to do this programmaticallyedittext edit new edittextthiseditsethorizontallyscrollingtrueeditsetinputtypeinputtypetype class numberwith this my edittext merrily restricts all input to numerical digits unfortunately it does not allow anything else like the decimal pointif i change that line to editsetinputtypeinputtypetype number flag decimal the edittext accepts all input which is not what i wanti have tried combining flags in desperation to see if it would workeditsetinputtypeinputtypetype class numbereditsetinputtypeinputtypetype number flag decimaleditsetinputtypeinputtypetype number flag signedthat did not work either the edittext accepted all input as usualso how do i do this,['android'] +179147,pointer vs variable speed in c at a job interview i was asked the question in c how do you access a variable faster though the normal variable identifier or though a pointer i must say i did not have a good technical answer to the question so i took a wild guessi said that access time will probably be that same as normal variableidentifier is a pointer to the memory address where the value is stored just like a pointer in other words that in terms of speed they both have the same performance and that pointers are only different because we can specify the memory address we want them to point tothe interviewer did not seem very convincedsatisfied with my answer although he did not say anything just carried on asking something else therefore i though to come and ask soers wether my answer was accurate and if not why from a theory and technical pov,['c++'] +179149,appconfig how do i make a nested customsection called appsettings be the configurationmanagerappsettings my desired appconfig would be like thisconfigsections sectiongroup nameqa environment section namedatabases typesystemconfigurationnamevaluesectionhandler section namestoragesystems typesystemconfigurationnamevaluesectionhandler sectiongroup sectiongroup nameproduction environment section namedatabases typesystemconfigurationnamevaluesectionhandler section namestoragesystems typesystemconfigurationnamevaluesectionhandler sectiongroup configsectionsand then i have got the actual groups and sections right below that but i would be happy with whatever works or better suggestions though i have now lowered my wishes to this configsections sectiongroup nameqa environment section nameappsettings typesystemconfigurationnamevaluesectionhandler sectiongroup sectiongroup nameproduction environment section nameappsettings typesystemconfigurationnamevaluesectionhandler sectiongroupconfigsectionsand i guess that is finethe main thing i am wondering about is if i can substitute one of these sections as the root level appsettingswithout iterating through them and programmatically adding or creating the config and saving it i just want the user to be able to select an environment the select event will change the appsettingsone constraint that i am facing is that the data layer i am referencing needs to remain the same as it isso i basically need to get my appconfig to be accessible exactly like it is currently from these other projectsthat is configurationmanagerappsettingsafdasdflet me know if this needs any clarificationthanks,['c#'] +179186,embedding dlls into exe in in visual c 2010 i am working on a c program that uses itextsharpdll and webcam capturedll when i build the program it creates executable in the debug folder and it also copies these two dlls to the debug folder as expected i want to merge them into a single executable however i failed these two libraries are visible in the references normally in the solution explorer i also add them as resources executable size got bigger which equals the sum of three files nevertheless the executable still requires these libraries in its directory i played with build action property of the resource files but no change i also tried ilmerge but it gave me an error so what should i doupdate this is what i get from ilmergean exception occurred during mergingunresolved assembly reference not allowed systemcoreat systemcompilerir2mdgetassemblyrefindexassemblynode assembly at systemcompilerir2mdgettyperefindextypenode typeit is just a windows application by the way a form to be filled and printed as pdf with a photo taken via webcam if available thanks all,['c#'] +179206,how to set text color in android app for all text i want to define a default text color for my android appi have a base activity class that all activities are extended from it and i thought this might be a good place to define the colors if not what is a better solution maybe stylestrouble is this all is new to me so feel free to advise me and provide code snippets and explanations as wellthis is what my base class looks like as you can see it is pretty emptypackage comccslocalmobilequizjlsimport androidappactivityimport androidosbundlepublic class baseactivity extends activity set up app preferences here,['android'] +179220,creating data model class for database handling i was just starting to work on an database application when i realized i should implement mvc pattern as the application is quite complex and involves a number of database operationsin regards to this i have decided to create a separate model class for handling database operations this class will have all methods which will return me the data after executing sqlite commandselect for instance or will simply execute the sqlite commanddelete for instance but what i want is to separate this class from database adapter class where i open create and close my databaselet me put my concept into code public class datamodelprivate members method to select data from student tablepublic arrayliststring fetchstudents parameter 1private arrayliststring arrstudentdatabaseadapter objdb new databaseadapterobjdbopen some codeobjdbclosereturn arrstudentmethod to delete record from student tablepublic deletestudentparameter 1databaseadapter objdb new databaseadapterobjdbopensome codeobjdbcloserest of methods databaseadapterclass private static class databasehelper extends sqliteopenhelper databasehelpercontext context supercontext database name null database version oncreate method is called for the 1st time when database does not existsoverridepublic void oncreatesqlitedatabase db logitag creating database create student tabledbexecsqlcreate student table onupgrade method is called when database version changesoverridepublic void onupgradesqlitedatabase db int oldversion int newversion logwtag upgrading database from version oldversion to newversion questionwhat i want to ask is this the correct approach of implementation is it fine if create separate class for database methods what limitations or issues you guys think might trouble me later on also is there a better way to implement the above concept thanksstone,['android'] +179225,in mvvm model should the model implement inotifypropertychanged interface i have clear idea about view and viewmodel in mvvm pattern i am planning to implement mvvm pattern in my application i am facing an issue regarding the model i have xml file which parsed and showed the information on the viewi need to be notified about the changes in the model for the first time only from onwards on demand i need to be notifiedso how to implement the model should i implement inotifypropertychanged interface in model class also i read that model should not implement inotifypropertychanged interface since it is wpf specific,['.net'] +179238,how to get a reliable unicode character count in python google app engine uses python 252 apparently with ucs4 enabled but the gae datastore uses utf8 internally so if you store uud834udd0c length 2 to the datastore when you retrieve it you get u01d10c length 1 i am trying to count of the number of unicode characters in the string in a way that gives the same result before and after storing it so i am trying to normalize the string from uud834udd0c to u01d10c as soon as i receive it before calculating its length and putting it in the datastore i know i can just encode it to utf8 and then decode again but is there a more straightforwardefficient way,['python'] +179275,python checksum of a dict i am thinking to create a checksum of a dict to know if it was modified or notfor the moment i have that import hashlib import pickle d k v k2 v2 z pickledumpsd hashlibmd5zhexdigest8521955ed8c63c554744058c98dc30perhaps a better solution existsnote i want to create an unique id of a dict to create a good etagedit i can have abstract data in the dict,['python'] +179290,error in accessor property cannot redefine nonconfigurable property status i am trying to define an object and create an accessor property for ithtmlinput typehidden idcrudmode valuecreate javascriptcrudmode create create read read update update delete delete current function return crudmodeval objectdefinepropertycrudmode mode get function return thiscurrent set functionvalue crudmodevalvalue but when i use it it throws the mentioned error in the question titleconsolelogcrudmodemodethrowstypeerror cannot redefine nonconfigurable property modewhats wrong here,['javascript'] +179308,opencv create mat from camera data in my programm i have function that takes the image from camera and should pack all data in opencv mat structure from the camera i get width height and unsigned char to the image buffer my question is how i can create mat from this data if i have global mat variable the type for mat structure i took cv 8uc1mat image function takephoto unsigned int width getwidthofphoto unsinged int height getheightofphoto unsinged char databuffer getbufferofphoto mat imagesizewidth height cv 8uc1 databuffer matauto step printfwidth un imagesizewidth printfheight un imagesizeheight image createsizeimagesizewidth imagesizeheight cv 8uc1 image imageclone printfwidth un image sizewidth printfheight un image sizeheightwhen i test my program i get right width and height of image but width and height of my global mat image is 0 how i can put the data in my global mat varible correctlythank you,['c++'] +179312,how do i import a module from a parent directory unittest purposes i have just finished writing the core section of a project i am working on and i want to write test for it using unittest before i continue i am aware that i should have done this before but when i started i did not know python so whateverwhat i would like to achieve i have a subpackage of the main package which contains all the modules i want to test inside it i want to put a subsubpackage inside that called tests or something which then contains all of my test cases which i would like to be able to aggregate into a test suite from outside the package so eventually i can run all the test for the entire project in one gothe structure is something like thisprojectpackageprojectpackagepackageprojectpackagepackage init py emptyprojectpackagepackagesomemodulepyprojectpackagepackage more modulesprojectpackagepackagetestingpy runs all the tests in testsprojectpackagepackagetestsprojectpackagepackagetests init py emptyprojectpackagepackagetestssomemoduletestspyproblem i am havingsomemoduletests has to import somemodule from the parent package so it can test its methods this does not seem to work i get various errors likeattempted relative import beyond toplevel packageanyway i expect it is just because i am a python noob i have my own ideas on how i am going to do it for this project because of course each is different but any general advice on the structuring of mediumlarge python projects is also appreciated,['python'] +179346,bidirectional hash table in ruby i need a bidirectional hash table in ruby for exampleh abc 123 xyz 789 qaz 789 wsx 8 9hfetchxyz 789hrfetch123 abchrfetch789 xyz qazhrfetch8 wsxmethod rfetch means reversed fetch and is only my proposalnote three thingsif multiple keys map at the same value then rfetch returns all of them packed in arrayif value is an array then rfetch looks for its param among elements of the arraybidirectional hash means that both fetch and rfetch should execute in constant timedoes such structure exists in ruby including external librariesi thought about implementing it using two onedirectional hashes synchronized when one of them is modified and packing it into class to avoid synchronization problems but maybe i could use an already existing solution,['ruby'] +179347,file system listener i would like to know if it is possible to have a listener in my application for notifying events when a file is added to the file system can someone kindly guide me with thisthanks in advance,['android'] +179351,is there an idiomatic rubyrails way of returning the first truthy mapped value i have an array of objects some of which respond to description and i want to get the description from the first one with a truthy description i could do thisobjectsdetecto otrydescriptiondescriptionor thisobjectsmapo otrydescriptiondetecto obut the first is not dry description is in there twice and the second iterates through the whole array before finding the value is there anything in the ruby standard library or in rails extensions to it which would let me do something like thisobjectsdetect and returno otrydescriptioni know i could write it easily enough but the standard libraries are big enough that i might not need to is there a function which works like my detect and return,"['ruby-on-rails', 'ruby']" +179374,it or it when iterating over a map examples showing how to iterate over a stdmap are often like thatmaptypeconst iterator end dataend for maptypeconst iterator it databegin it end itie it uses it instead of it is there any reason why could there be any problem if i use it instead,['c++'] +179405,how may i override the compiler gcc flags that setuppy uses by default i understand that setuppy uses the same cflags that were used to build python i have a single c extension of ours that is segfaulting i need to build it without o2 because o2 is optimizing out some values and code so that the core files are not sufficient to pin down the problemi just need to modify setuppy so that o2 is not usedi have read thistutils documentation in particular thistutilsccompiler and thistutilsunixcompiler and see how to add flags and libs and includes but not how to modify the default gcc flagsspecifically this is for a legacy product on python 251 with a bunch of backports fedora 8 yes i know no i cannot change the os or python version and i cannot without great problems recompile python i just need to build a one off of the c extension for one customer whose environment is the only one segfaulting,['python'] +179418,iframe versus div jquery i would like to know what is the more appropriate for what i want to achieveon my main page mainphp i have links to different forms form1php form2php form3php i need the pages of the links to open in a portion of mainphp ie in a div or in a iframe on mainphp without refreshing mainphp the form pages enables to populate delete update a database when i do those actions i do not want mainphp to refresh but only the appropriate form pagemy first option is to open form1php for example in a iframe of mainphp when i submit a form only form1php in the iframe is refreshedmy second option is to use jquery open the link form1php in a div of mainphpsubmit the form within the div and refresh the div onlythe second option is more demanding since i do not have much experience with ajax and jquery the first option is more straight forward for mei am wondering if there is any advantages to use the second option with a div refresh compared to iframe ie compatibility with different browsers and elsethanks,"['jquery', 'html']" +179433,rest and soap webservice in android i found tutorial to use ksoap api to use soap webservice can anyone provide me sample programs tutorial on getting rest webservice and soap webservice in android i have googled lot but did not find such type of tutorial,['android'] +179461,file exists returns false but the file does exist i am having a very weird issue with file exists i am using this function to check if 2 different files in the same folders do exist i have doublechecked they both do existecho relative urlpath pathfilename jpgresult imagesexample001001jpgecho relative urlpath pathfilename pathextensionresult imagesexample001001pngnow let us use file exists on thesevar dumpfile existsrelative urlpath pathfilename jpgresult boolfalsevar dumpfile existsrelative urlpath pathfilename pathextensionresult booltruei do not get it both of these files do exist i am running windows so it is not related to a casesensitive issue safe mode is offwhat might be worth mentioning though is that the png one is uploaded by a user via ftp while the jpg one is created using a script but as far as i know that should not make a differenceany tipsthanks,['php'] +179477,javascript clicking a wrapper element but not a child element i am writing some javascript jquery that enables a div wrapped around a checkbox when clicked will toggle the checkbox element however the problem i am running into is that when you click on the checkbox it does not work because it is being toggled twice at least i think that is whats happening heres a demoheres the codecheckboxwrapperclickfunction var checkbox thisfindinputtypecheckbox if checkboxischecked checkboxattrchecked false else checkboxattrchecked true how can i make it so that clicking the checkbox works as normal but if you click in the surrounding area it toggles the checkboxsolutionthanks to jandys comment for showing how this can be done by checking the eventtarget propertycheckboxwrapperclickfunctione if etargetnodename input estoppropagation return var checkbox thisfindinputtypecheckbox if checkboxischecked checkboxattrchecked false else checkboxattrchecked true and as others have pointed out this may not be the best example since you get the same functionality without needing javascript by wrapping the checkbox with a label tag instead of a div tag demo,"['javascript', 'jquery']" +179478,jquery getjson doesnt send cookies i am including js on domain1 form domain2script typetextjavascript srcscriptthat script doesn onload and on button click a jsonp request to domain2getjson functiondata if data processdata data and then thisplaying the data on domain1so here is my problemthe getjson request doesnt send cookies to the domain2the weirdest thing is that it does send the cookies half a day and the other half not this is how the request looks like when it doesnt workrequest detailsget ajaxembeduserlibrarydetail98callbackjsonp1312398534998 http11 useragent opera980 windows nt 61 u en presto29168 version1150host wfloowiecomaccept texthtml applicationxmlq09 applicationxhtmlxml imagepng imagewebp imagejpeg imagegif imagexxbitmap q01acceptlanguage enskskq09skq08acceptencoding gzip deflatereferer connection keepaliveresponse detailshttp11 200 ok date wed 03 aug 2011 190651 gmtserver apache2216 debianxpoweredby php5350dotdeb1setcookie sessid64292b70dc28d7c6c9f13f70070353d8 path domainfloowiecomexpires mon 26 jul 1997 050 gmtcachecontrol nocache mustrevalidatepragma nocachecontentlength 34keepalive timeout15 max100connection keepalivecontenttype applicationjsonand this when it worksnothing changed in the scriptsrequest detailsget ajaxembeduserlibrarydetail99test1callbackjsonp13123985349 http11 useragent opera980 windows nt 61 u en presto29168 version1150host test1floowiecomaccept texthtml applicationxmlq09 applicationxhtmlxml imagepng imagewebp imagejpeg imagegif imagexxbitmap q01acceptlanguage enskskq09skq08acceptencoding gzip deflatereferer cookie utma254918925148979683213017253171312260335131229803344 utmz25491892513122980334411utmcsrsokkerczutmccnreferralutmcmdreferralutmcctentest2 langen flwsessid1bc696f83f5a70b5f0f3ae30b4691 utma1219556761030804516128259515313123906561312397285194 utmb1219556768101312397285 utmc121955676 utmz121955676131239728519421utmcsrfloowiecrmserverczutmccnreferralutmcmdreferralutmcctindexphpconnection keepaliveresponse detailshttp11 200 ok date wed 03 aug 2011 190745 gmtserver apache2216 debianxpoweredby php5350dotdeb1expires mon 26 jul 1997 050 gmtcachecontrol nocache mustrevalidatepragma nocachecontentlength 20keepalive timeout15 max100connection keepalivecontenttype applicationjsondid someone see such a behaviouris it solvablethank you,"['javascript', 'jquery']" +179491,garbage collection modes if 2 apps exist on a server does server mode rob peter to pay paul a 2parter if necessary i can seperate questions to award seperate right answerswere in a situation where running in server mode is likely appropriate we have 2 enterprise level apps running on the same farm if i put the app config collection modes of both apps in server mode am i risking hurting one app every time the other gcs will the network load balancer shift traffic away from a machine in the middle of gc again in server modeediti broke the load balancing part of this question over to here is the network load balancer of a web farm affected by gc strain,['c#'] +179502,how do i save filter values in wpf toolkit datagrid filter extension i am using the code vs2008 i found under the article automatic wpf toolkit datagrid filtering which works very well it is implemented as a new style for a datagrids header not as an extension of the datagrid itself my question is how can i save the values entered into those filter boxes and later use them to reenter those values if not possible as is how would i go about modifying the source code available from link above to the filter wpf newbiethanksenrico,['c#'] +179509,how can a nonassigned string in python have an address in memory can someone explain this to me so i have been playing with the id command in python and came across this idcat5181152 a cat b cat ida5181152 idb5181152this makes some sense to me except for one part the string cat has an address in memory before i assign it to a variable i probably just do not understand how memory addressing works but can someone explain this to me or at least tell me that i should read up on memory addressingso that is all well and good but this confused me further a a02t acat ida39964224 idcat5181152this struck me as weird because cat is a string with an address of 5181152 but the new a has a different address so if there are two cat strings in memory why are not two addresses printed for idcat my last thought was that the concatenation had something to do with the change in address so i tried this idb02t39921024 b b02t bcat idb40896i would have predicted the ids to be the same but that was not the case thoughts,['python'] +179510,programatically set left drawable in a textview i have a textview in xml here textview androidididbooktitle androidlayout widthmatch parent androidlayout heightwrap content androidlayout weight1 androiddrawableleftdrawablecheckmark androidgravitycenter vertical androidtextstylebold androidtextsize24dip androidmaxlines1 androidellipsizeendas you can see i set the drawableleft in xmli would like to change the drawable in code is there anyway to go about doing this or setting the drawableleft in code for the text view,['android'] +179518,resume ftp download after timeout i am downloading files from a flaky ftp server that often times out during file transfer and i was wondering if there was a way to reconnect and resume the download i am using pythons ftplib here is the code that i am using usrbinpythonimport ftplibimport osimport socketimport sys define parameters for ftp site site areallyunstableserveruser anonymouspassword root ftp dir directory1root local dir directory2 tuple of order numbers to download each web request generates an order numbersorder num 1234 loop through each order connect to server on each loop there might be a time out for the connection therefore reconnect for every new ordernumber first change local directoryoschdirroot local dir begin loop through for order in order num print begin proccessing order number s order connect to ftp site try ftp ftplibftp hostsite timeout1200 except socketerror socketgaierror e print error unable to reach s site sysexit login try ftploginuserpassword except ftpliberror perm print error unable to login ftpquit sysexit change remote directory to location of order try ftpcwdroot ftp dirorder except ftpliberror perm print unable to cd to s root ftp dirorder sysexit get a list of files try filelist ftpnlst except ftpliberror perm print unable to get file list from s order sysexit loop through files and download for each file in filelist file local openeach filewb try ftpretrbinaryretr s each file file localwrite file localclose except ftpliberror perm print error cannot read file s each file osunlinkeach file ftpquit print finished proccessing order number s ordersysexitthe error that i get socketerror errno 110 connection timed outany help is greatly appreciated,['python'] +179527,what are zygoteinit calls periodically i get exceptions reported on android market that are not reproducible the stack traces always begin like thisat at androidoshandlerhandlecallbackhandlerjava587at androidoshandlerthispatchmessagehandlerjava92at androidoslooperlooplooperjava143at androidappactivitythreadmainactivitythreadjava4306at javalangreflectmethodinvokenativenative methodat javalangreflectmethodinvokemethodjava507at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava839at comandroidinternaloszygoteinitmainzygoteinitjava597at dalviksystemnativestartmainnative methodzygoteinitmethodandargscaller appears to be calling app methods directly instead of through code how is this happeningfinally reproduced one of these exceptions as follows touch app icon touch text field to bring up dialog press home kill app pid touch app icon and press back added saving and restoring of app instances variables in onsaveinstancestate and onrestoreinstancestate to fix problemwould still like to find description of zygoteinit calls somewhere,['android'] +179530,in java memory management what does ps stand for whenever i see reference to memory in java the various spaces are always prefixed with ps what does ps mean it is starting to bother me my only guess so far is pool space but that would be redundantexamplesps eden spaceps survivor spaceps tenured space old generationps perm gen permanent generation,['java'] +179537,why is selfnavigationitembackbarbuttonitem always nil i push a view controller onto a navigation controller like thisselfnavigationcontroller pushviewcontrolleranotherviewcontroller animatedyesand then inside anotherviewcontroller i check selfnavigationitembackbarbuttonitem and leftbarbuttonitem but they are always nili can see the backbarbuttonitem and it seems to work fine,['objective-c'] +179553,high performance event log so i have been trying various ways to get event log data in bulk 10 recordssecondi need something that can filter out old logs right now i store the last recorded event record id and retrieve all records where the event id is greater than thati have tried eventlogqueryeventlogreader this works fast except when i want to pull message data in order to get a formatted message for security logs i need to call eventlogrecordformattedmessage this brings my log speed to about 150second with easy to format logs even worse with complicated onesi have tried systemdiagnoisticseventlog this does not allow me to build filters so every time i run this it must load all event logs then i can parse off any duplicates from the last scan i have a sever that has 200k event logs over the past two days memory usage gets terrible due to this so that is a nogoi have tried wmi using systemmanagementmanagementobjectcollection this has filtering and can pull message data from the security event log fast approaching 10second however it will go to about 5060k and start to drag it is feet down to doing about 12second eventually i will get a quota violation error so eitheris there a way to avoid the quota violation error or do i want to use some other method for pulling event logs at this speedediti wrote a blog post detailing what i have learned about thismostly winapi is your best bet either write cclr or use pinvoke,['c#'] +179589,thisadvantages to using css wordwrap globally are there any thisadvantages to using wordwrapbreakword in the following waybody wordwrap breakwordthe descriptions of the values for this property are as followsnormal break words only at allowed break pointsbreakword allows unbreakable words to be brokennow this only makes a difference in the breaking of unbreakable words ie continuous strings that are longer than their containers otherwise it will make no difference for 99 of text anywhereso are there any thisadvantages to using this globally it can certainly solve a lot of layout issues without at least as far as i can see having any adverse effects it seems better to do this once than to have to apply it everywhere you could possibly have overflowing text that would mess up your layout,['css'] +179593,where is the assisted class in the guice jar i have download guice 20 and 30 via maven and cannot find the entire comgoogleinjectassistedinject package in the jar all the other components of guice seem to be there but assisted and its brethren are simply not thereany idea where they went,['java'] +179623,combining di with constructor parameters how do i combine constructor injection with manual constructor parameters iepublic class someobject public someobjectiservice service float somevalue where iservice should be resolvedinjected by my di container and somevalue should be specified how do i mix the two,['c#'] +179625,efficient stopwatch hi i am programming a stopwatch utility in javascript and i have a question about efficiency and overhead there are two ways i have considered making the stopwatch1store a start date and constantly measure the number of milliseconds it has been since that date2create an integer and increment its value at a set intervali want to know which is most efficient also i am not sure if option 2 would be very accurate if anyone has any input about this that would be awesome as well,['javascript'] +179630,do we really need enum class in c11 when we havestruct e enum e hello e is inheritablethen why do we needenum class e hello e is not inheritableimo 2nd version does not offer more features than the 1st i do not think that enum class is introduced just to save 2 curly braces am i missing any important aspect as a minor question is there any difference between enum class and enum struct other than syntax because both have public access specifier,['c++'] +179635,android emulator error20110802 1401 emulator panic could not open cusershalloandroidavdmyemuini i am beginner android application developer i have done lot of apps in eclipse on emulator and device also but now it is giving error at the time of running project on emulator it is working on device phone but on emulator it is giving following error20110802 1400 hello1 20110802 1400 hello1 android launch20110802 1400 hello1 adb is running normally20110802 1400 hello1 performing commahiwayshello1hello1activity activity launch20110802 1400 hello1 automatic target mode launching new emulator with compatible avd myemu20110802 1400 hello1 launching a new emulator with virtual device myemu20110802 1401 emulator panic could not open cusershalloandroidavdmyemuinihow can i solve this problem,['android'] +179641,how to convert utf8 combined characters into single utf8 characters in ruby some characters such as the unicode character latin small letter c with caron can be encoded as 0xc4 0x8d but can also be represented with the two code points for latin small letter c and combining caron which is 0x63 0xcc 0x8cmore info here i wonder if there is a library which can convert a latin small letter c combining caron into latin small letter c with caron or is there a table containing these conversions,['ruby'] +179648,why lifetime of temporary does not extend till lifetime of enclosing object i know that a temporary cannot be bound to a nonconst reference but it can be bound to const reference that is a x a error const a y a oki also know that in the second case above the lifetime of the temporary created out of a extends till the lifetime of const reference ie ybut my question iscan the const reference which is bound to a temporary be further bound to yet another const reference extending the lifetime of the temporary till the lifetime of second object i tried this and it did not work i do not exactly understand this i wrote this codestruct a a stdcout a stdendl a stdcout a stdendl struct b const a a bconst a a aa stdcout b stdendl b stdcout b stdendl int main a a b ba stdcout stdendl b ba extra braces are needed output ideone a bba a babdifference in output why the temporary object a is destructed before the object b in the second case does the standard c03 talks about this behavior,['c++'] +179651,android change strings resource programmatically is there a way to do this for instance i have a setting in my preferences that can convert between metric and standard units of measurement and when the user changes this i would like to update a few strings to change some labels around within my app,['android'] +179678,gwt equivalent for net i enjoy gwt because i can have compiletime type safe code that runs in the browser however i like c a lot better than java is there some good way to have c compile to javascript,"['c#', 'javascript']" +179683,java getting input from midi keyboard i have designed my own synthesizer in java and i now want to connect it with a midi keyboard my class below searches through all the midi devices that have transmitters it successfully finds my midi keyboard i add my own receivers to each transmitter for each device so that it should pick up everything possible from reading all the help documents and java doc i know that a transmitter sends midievents to a receiver which then handles them with the send method so i wrote my own inner class implementing receiver and just used a println statement to check if there was anything detected at all in the send method however nothing is picked up at all there seems to be very little help to do such a simple thing and i have looked at every help file javadoc and forum i am sure it must be something really obvious i have somehow missedmy synthesizer should not be confused with the interface synthesizer and it is not a midi instrument it uses a synthesis algorithm and has a playback method basically i just need to get the midi keyboard sending a note on event which will invoke the playback methodimport javaxsoundmidiimport javautilarraylistimport javautillistimport javaiopublic class midihandler arraylist of mididevices private arraylistmididevice devices new arraylistmididevice public midihandler mididevice device midideviceinfo infos mithisystemgetmidideviceinfo for int i 0 i infoslength i try device mithisystemgetmidideviceinfosi does the device have any transmitters if devicegettransmitterssize 0 if it does add it to the device list systemoutprintlninfosi devicegettransmitterssize devicesadevice catch midiunavailableexception e if any transmitting devices were found ifdevicessize0 for each device forint i 0 idevicessize i try get all transmitters listtransmitter transmitters devicesgetigettransmitters and for each transmitter forint j 0 jtransmitterssizej create a new receiver transmittersgetisetreceiver using my own midiinputreceiver new midiinputreceiverdevicesgetigetdeviceinfotostring open each device devicesgetiopen if code gets this far without throwing an exception print a success message systemoutprintlndevicesgetigetdeviceinfo was opened catch midiunavailableexception e tried to write my own class i thought the send method handles an midievents sent to it public class midiinputreceiver implements receiver public string name public midiinputreceiverstring name thisname name public void sendmidimessage msg long timestamp systemoutprintlnmidi received public void close notei have already seen this java midi getting data from pianoand this interface sequencer looked way to complicated for what i want also,['java'] +179685,springmvc 3 and tiles 2 localization of page title i have a project setup using spring 3 apache tiles 2 and mavenbefore i implement tiles i was using the messagesproperties file to dynamically populate the titles for a webpage the part that appears between the head and title tags the reason for this was to allow localization in the future however since i have integrated tiles the tilesxml file seems to control the titles for my pageis there a way to change this so the page title comes from messagesproperties for each jsp i use as the body of a pagetilesxml is definition namebasedefinition templatewebinfviewslayoutslayoutjsp putattribute nametitle value putattribute nameheader valuewebinfviewsincludesheaderjsp putattribute namemenu valuewebinfviewsincludesmenujsp putattribute namebody value putattribute namefooter valuewebinfviewsincludesfooterjsp definitiondefinition namehome extendsbasedefinition putattribute nametitle valuewelcome from tile putattribute namebody valuewebinfviewshomejsp definitiondefinition namenewdealinput extendsbasedefinition putattribute nametitle valuenew deal putattribute namebody valuewebinfviewsnewdealinputjsp definitionwhere you see welcome from tile or new deal as the title i would rather that this message comes from a messagesproperties i have tried putting the message in the title tags on the body page to no availthe project is setup on github you can take a look at this url groupdealclone,['java'] +179691,common table expression why semicolon usually in sql server common table expression clause there is semicolon in front of the statement like thiswith orderedorders as semicolon here select salesorderid orderdate row number over order by orderdate as rownumber from salessalesorderheader select from orderedorders where rownumber between 50 and 60why,['sql'] +179705,android fragments setcontentview alternative i am trying to rewrite an existing project using fragments to port my application on tableti am replacing activities with fragmentsthe problem is that i do not know what is the equivalent to setcontentview method is there any way to create fragments view except rewriting oncreateview,['android'] +179715,how can i put an input element on the same line as its label i would like to put a label and an inputtypetext on the same line and i would like for the inputs width to fill the remaining width of the containing element regardless of the length of the labels text see first imagei tried to use width auto for the input but it seems to have a static width i also tried width 100 but that moves the input to a new line see second imagehow can i achieve this using css,"['html', 'css']" +179721,rabbitmq on ec2 performance challenges what could be performance expectations of rabbitmq on ec2 would appreciate sharing experience herei am trying to do some performance test of rabbitmq on aws ec2 i have 3 separate ec2 instance running for rabbitmq publisher and consumerworkerthe scenario i have is that publisher pushes json string approx 165200 bytes to exchange type direct with durable set to true and bind queue with durable set to true ie both in persistent mode consumerworker is running on separate box keeps pulling messages moving forward these messages at worker are expected to be persisted in mongodb and publisher would be replaced with restful service using rest easyto keep things simple i have simulated this scenario by using multicast sample code i had split multicast code in to two separate java file namely aproducera and aworkera to run each on separate box i have used ac1mediama ec2 with ubuntu server v114 32 bit for running producer and consumer and am1largea with ubuntu server v114 64 bit for rabbitmqi am able to achieve a throughput of 35k messages per second ie keeping study message push rate to 5k this concur with further when i increase the push rate to 1012k messages per second consumeras ability to consume messages drops to 12k messages per second and it generates backlog many time it goes below 800 messages per second toowith above scenario i have following questions and would appreciate thoughtssuggestion to improve throughput of consumer as well note all the messages in my scenario are expected to similar type giving no opportunity to group them for setting routing therefore may need some kind of loadbalancer approach1 this performance is observed with one rabbitmq server one exchange and one queue is anything further can be configured finetuned to improvise throughput to more than 5k with persistent mode2 i do understand clustering could be another option however i need to set cluster based on incoming load and i may not get message grouping identity to define routing since messages are expected to be just log description can i have clustering following load balancing option for workerconsumer3 i am expected to process several hundred thousand requests per second i would appreciate sharing some experience and approach to achieve this,['java'] +179738,glassfish 31 credential error in eclipse i cannot start glassfish 31 on eclipse indigo with oracle glassfish server tools plugin on windows 7 after installing the plugin i have chosen new server in the server view and clicked on glassfish 31 and downloaded the installation through eclipseevery time i try to start it i have the following messagethe eclipse plugin cannot communicate with the glassfish server status is credential errori have found out that the initial password is changeit and i have changed it to my own on the command linebinasadmin changemasterpassword domain1enter the current master passwordenter the new master passwordenter the new master password againcommand changemasterpassword executed successfullyi have changed it accordingly in glasshfish 31 configuration screen within eclipse in the section application server admin passwordthe ports listed 8080 4848 seems compatible with domainxml configurationnetworklisteners networklistener port8080 protocolhttplistener1 transporttcp namehttplistener1 threadpoolhttpthreadpoolnetworklistener networklistener port8181 protocolhttplistener2 transporttcp namehttplistener2 threadpoolhttpthreadpoolnetworklistener networklistener port4848 protocoladminlistener transporttcp nameadminlistener threadpooladminthreadpoolnetworklistenernetworklistenershowever in my log i find the followingentry oracleeclipsetoolsglassfish 4 1 20110804 113843925message glassfish error stack 0javanetconnectexception connection refused connect at javanetplainsocketimplsocketconnectnative method at javanetplainsocketimpldoconnectplainsocketimpljava3 at javanetplainsocketimplconnecttoaddressplainsocketimpljava195 at javanetplainsocketimplconnectplainsocketimpljava182 at javanetsockssocketimplconnectsockssocketimpljava366 at javanetsocketconnectsocketjava525 at javanetsocketconnectsocketjava475 at sunnetnetworkclientdoconnectnetworkclientjava163 at sunnetwhttphttpclientopenserverhttpclientjava394 at sunnetwhttphttpclientopenserverhttpclientjava529 at sunnetwhttphttpclientinithttpclientjava233 at sunnetwhttphttpclientnewhttpclientjava306 at sunnetwhttphttpclientnewhttpclientjava323 at sunnetwprotocolhttphttpurlconnectiongetnewhttpclienthttpurlconnectionjava860 at sunnetwprotocolhttphttpurlconnectionplainconnecthttpurlconnectionjava801 at sunnetwprotocolhttphttpurlconnectionconnecthttpurlconnectionjava726 at comsunenterprisejstserversunappsrvcommandscommandrunnercallcommandrunnerjava607 at comsunenterprisejstserversunappsrvcommandscommandrunnercallcommandrunnerjava1 at javautilconcurrentfuturetasksyncinnerrunfuturetaskjava303 at javautilconcurrentfuturetaskrunfuturetaskjava138 at javautilconcurrentthreadpoolexecutorworkerruntaskthreadpoolexecutorjava886 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava908 at javalangthreadrunthreadjava619entry oracleeclipsetoolsglassfish 4 150 20110804 113843928message the eclipse plugin cannot communicate with the glassfish server status is credential errorstack 0javalangruntimeexception the eclipse plugin cannot communicate with the glassfish serverstatus is credential error at comsunenterprisejstserversunappsrvsunappserverlaunchlaunchsunappserverlaunchjava163 at orgeclipsedebuginternalcorelaunchconfigurationlaunchlaunchconfigurationjava854 at orgeclipsedebuginternalcorelaunchconfigurationlaunchlaunchconfigurationjava703 at orgeclipsedebuginternalcorelaunchconfigurationlaunchlaunchconfigurationjava696 at orgeclipsewstservercoreinternalserverstartimpl2serverjava3404 at orgeclipsewstservercoreinternalserverstartimplserverjava3342 at orgeclipsewstservercoreinternalserverstartjobrunserverjava363 at orgeclipsecoreinternaljobsworkerrunworkerjava54so it seems that the error message shown in the interface is misleading it should be a connection problem not password problem as far as i understand anyone knows how to solve this problem,['java'] +179745,class implementation in multiple files i am trying to implement a class in different cpp files i understand it is a legitimate thing to do in c if the member functions are independent however one of the member function uses another member function such as in this casein function1cppinclude myclasshvoid myclassfunction1 function2in function2cppinclude myclasshvoid myclassfunction2i will get an error of undefined reference to function2 it does not work by adding this pointer either do i need to declare it in some way in function1cpp thanksthe header file includes declaration of both functions it works when function1 and function 2 are in the same file but not when i separate them i also believe i have added both cpp in the project i am using qt creater btw,['c++'] +179756,how do i duplicate item when using jquery sortable i am using this method to connect two lists that i have i want to be able to drag from list a to list b but when the item is dropped i need to keep the original one still in list a i checked the options and events but i believe there is nothing like that any approaches,['jquery'] +179779,db unit testing framework in my project i have used spring jpa with postgresql dbi have lots of table in db and i need to have unit testing of all of themis there any framework which just rollback all the transactions after each test finished so every test will have freshsame db data to test and this way after all test executions data of db schema would be as it isany suggestion for thisi have some idea of dbunit but in that i need to write xml files for every input data for every test and need to insert data in setup and clearremove data in teardown but does not seems better strategy to meany suggestion is appreciatedthanks,['java'] +179786,difference between intentsetclass and intentsetcomponent i am looking at a tutorial and see the author using intentsetclass to get the to the next activity and then on the same page he uses intentsetcomponent to get to the next activityso what is the difference and what is the advantage in using any of them,['android'] +179793,css dotted border issue in adjacent columns in a table rendered as dash in chrome when i run this code in chrome and firefox both thisplay border differently i see a dash in between adjacent cells in chrome while in firefox it is rendered without any dashes how can i fix this,"['html', 'css']" +179794,unable to open log device devlogmain no such file or directory i am new to android development and bought a cheap huawei sonic u8650 apparently so i could test my first attempts at making an app on an actual devicehowever whenever i try to use adb logcat or adb shell then logcat on the device i getunable to open log device devlogmain no such file or directoryi have already enabled usb debugging in settings developeri just do not know enough about android to know if this is something i can even fixi have found two other questions with similar problemsdevlogmain not found infounknownunknown unable to open log device devlogmain no such file or directorybut they both turned out to be using some kind of non standard kernel that had logging thisabled mine is a stock phone out of the boxit is a very cheap but snappy android 23 phone so hopefully it was not a total waste of moneyany help would be greatly appreciated,['android'] +179800,complete code in trycatch block i want to know is it a good practice to place complete code inside a try block or i should place only the code which i feel it will cause a specific exceptionand should i catch basic exception always code 1 complete code in try block myfunction try code with chance of oneexception catchoneexception e catchexception e code 2 only the code with chance of exception in try blockmyfunction try code with chance of oneexception catchoneexception e code 3should i catch exception always myfunction try code chance of oneexception catchoneexception e catchexception e out of this code1 code2 and code3 which one is the besti am mainly concern with java and c coding,"['c++', 'java']" +179801,why folderbrowserdialog dialog does not scroll to selected folder as show in this screen shot the selected folder is not in the view it needs to be scrolled down to view the selected foldersame dialog shows selected folder visible on different computeri ran it on two computers both having windows 7 it works correctly on one but does not on 2nd it looks something with windows environment instead some code issue can anyone suggest any fixthere is no change in code i used longer paths from different drives but results are sameprivate void testdialog click object sender eventargs e last path store the selected path to show the same directory as selected on next application launch propertiessettingsdefaultlastpath folderbrowserdialog dlgfolder new folderbrowserdialog dlgfolderrootfolder environmentspecialfolderdesktopdirectory dlgfolderselectedpath propertiessettingsdefaultlastpath if dlgfoldershowdialog systemwindowsformsdialogresultok propertiessettingsdefaultlastpath dlgfolderselectedpath propertiessettingsdefaultsave,['c#'] +179816,android ndk how to include androidmk into another androidmk hierarchical project structure looks like it is possible but my script produces odd resultslocal path call mydirinclude clear varsinclude local pathlibosandroidmkinclude local pathlibbaseandroidmkinclude local pathutilsandroidmklocal module nativeinclude build shared libraryonly the first include is being parsed fine other androidmk files are being seacrhed at odd pathssuggestionsupdate i have broken my building environment it was ok in the office but at home local path call mydir defines local path to ndk dir instead of project dir this is my batch for building set bashpathkcygwinbinbashset projectdircygdrivehalexalexworkandroidremoteandroidset ndkdircygdrivehalexprogramming docsandroidandroidndkr6ndkbuildset app build scriptcygdrivehalexalexworkandroidprojectjniandroidmkset dev roothalexalexworkandroidprojectbashpath login c cd projectdir ndkdirupdate i absolutely do not understand how does this thing compose paths i am getting errors with paths like cygdrivedprojectjnicygdrivedsoftprojectjnilibossrcliboscpp this is after i decided to specify all files in the root androidmk instead of including submodulesupdate 2 no luck this does not work eitherlocal path call mydir include makefiles hereinclude local pathlibosandroidmkinclude local pathlibbaseandroidmkinclude local pathutilsandroidmk clear variables here include clear vars,['android'] +179836,how to properly use insertrowsatindexpaths i went through all the examples online and could not figure out how to properly add a cell to a tableview with animation let us say i have one section with one cell and i want to add another cell once the user clicks on the first cells accessorymy add method does this ibaction toggleenabledtextforswitch1onsomelabel id sender if switch1on nsarray applecomputers nsarray arraywithobjectsw x y z nil nsdictionary applecomputersdict nsdictionary dictionarywithobjectapplecomputers forkeycomputers listofitems replaceobjectatindex0 withobjectapplecomputersdict tblsimpletable reloaddatawhich is working but there is no animation i understand that in order to add animation i need to use insertrowsatindexpathswithrowanimation so i tried tons of options but it always crashes when executing the insertrowsatindexpathswithrowanimation method my recent try was by doing this ibaction toggleenabledtextforswitch1onsomelabel id sender if switch1on nsindexpath path1 nsindexpath indexpathforrow1 insection0 also tried with indexpathrow0 nsarray indexarray nsarray arraywithobjectspath1nil tblsimpletable insertrowsatindexpathsindexarray withrowanimationuitableviewrowanimationright what am i doing wrong how can i make this happen easily i dont understand this whole indexpathforrow thingi also dont understand how with this method i can add a label name to the new cell please helpthanks,"['iphone', 'objective-c']" +179858,does the order of rules in a css stylesheet affect rendering speed while this could possibly result in a simple yes or no answer i will go for it anywayconsider the following examplehtmlhtml head head body div classfoo span classbarhello worldspan psome really interesting textp div bodyhtmlcsshtml some css body some css divfoo some css divfoo spanbar some css divfoo p some css will the order in which css rules appear have any effect on how fast the browser can render the page in this example it would not really matter but consider a real website with loads of html and css so the above css script will render faster or easier for the browser than divfoo p some css divfoo spanbar some css divfoo some css body some css html some css do browsers careshould weread before askingis this how you would structure your css stylesheetwhats the best way to organize css ruleshow do browsers read and interpret css,"['html', 'css']" +179861,mybitmaprawformat is something different than any known imageformat i am working with gdi and i create a new bitmap like thisvar bmp new bitmapwidth heightnow when i observe its rawformatguid i see that it is different from all predefined imageformats while i expect it to be jpegimageformatjpegguid b96b3cae072811d39d7b0f81ef32eformatguid b96b3caa072811d39d7b0f81ef32einteresting part is that as you can see they are identical except one character which makes me even more confusedany idea why which parts of code determines what is the rawformat of the bitmap i create how can we ensure it is a valid imageformatthanks,['c#'] +179862,can php return a resource with id 0 i am wondering if it is possible for a valid php resource to have an id of 0 i am getting database connection resources and so far they have all been nonzero positive integers just curious what the range of potential ids is for resources,['php'] +179865,how to thiscover new mef parts while the application is running i am using mef to load plugins in my app everything works but i want new parts to be thiscovered when they are dropped into my app folder is this possible directorycatalog has a changed event but i am not sure how it worksthis is my code right nowpublic sealed class revealerfactory private static readonly lazyrevealerfactory lazy new lazyrevealerfactory new revealerfactory public static revealerfactory instance get return lazyvalue private filesystemwatcher watcher private revealerfactory initialize importmanyrequiredcreationpolicy creationpolicyshared private ienumerablelazyirevealer irevealercapabilities revealers get set public irevealer getrevealeruri uri return from revealer in revealers where urihostequalsrevealermetadatahost stringcomparisonordinalignorecase revealervalueisrevelableuri select revealervaluefirstordefault private void initialize var catalog new directorycatalog environmentgetfolderpathenvironmentspecialfolderapplicationdata sdownloaderrevealers var container new compositioncontainercatalog containercomposepartsthis,['c#'] +179876,multiple characters in a character constant some c compilers permit multiple characters in a character constant this means that writing yes instead of yes may well go undetected source c traps and pitfallscan anyone give an example of this where multiple characters are allowed in a character constant,['c'] +179877,which way is better setinterval or windowsetinterval ok so there is a couple things to this questionfirst of all i am asking this for settimeout and for setintervali have seen a couple different ways to call them and i am wondering which way is the best for this circumstancei am making a jscanvas game and i am just looking over my draw interval where it loops the draw methodanyways here are the different ways i have seen part ausing windowdrawinterval windowsetintervaldraw 60not using windowdrawinterval setintervaldraw 60part b not using quotes and brackets around the function namedrawinterval setintervaldraw 60using quotes and brackets around the function namedrawinterval setintervaldraw 60so for part a should i use window or notand what about windowclearinterval vs clearinterval by itselfand for part b should i use quotes and brackets or not i was told before that it was a bad idea to use quotes and brackets for this situation,['javascript'] +179878,using bonecp handling connections from the pool i have just started using bonecp and this is my first time using a connection pool i am somewhat confused as to how i am supposed to use it currently i am saving the bonecpobject as a static variable and thus i can use it between different connectionswhen i am done with the connection i close it with connectioncloseshould i do this or should i not close it to enable it to be reused by the poolthis is my current implementation to get a connectionprivate static bonecp connectionpoolpublic connection getconnection throws sqlexception if connectionpool null initpool return connectionpoolgetconnectionprivate void initpool throws sqlexception bonecpconfig config new bonecpconfig configsetjdbcurldb url configsetusernamedb username configsetpassworddb password configsetminconnectionsperpartition5 configsetmaxconnectionsperpartition10 configsetpartitioncount1 connectionpool new bonecpconfigdoes this seem correct or have i misunderstood how i am supposed to use bonecp,['java'] +179906,set python recursion limit for a function i have 2 solutions to a recursion problem that i need for a function actually a method i want it to be recursive but i want to set the recursion limit to 10 and reset it after the function is called or not mess with recursion limit at all can anyone think of a better way to do this or recommend using one over the others i am leaning towards the context manager because it keeps my code cleaner and no setting the tracebacklimit but there might be caveatsimport sysdef funci1 print i if i 10 import sys systracebacklimit 1 raise valueerrorrecursion limit i 1 funciclass recursion limitobject def init self val selfval val selfold val sysgetrecursionlimit def enter self syssetrecursionlimitselfval def exit self args syssetrecursionlimitselfold val raise valueerrorrecursion limitdef func2i1 call as with recursion limit12 func2 print i i 1 func2iif name main print running func1 func with recursion limit12 func2i do see some odd behavior though with the context manager if i put in mainwith recursion limit12 func2it prints 1 to 10 if i do the same from the interpreter it prints 1 to 11 i assume there is something going on under the hood when i import thingsedit for posterity this is what i have come up with for a function that knows its call depth i doubt i would use it in any production code but it gets the job doneimport sysimport inspectclass keeptrackobject def init self selfcalldepth sysmaxint def funcself zero leninspectstack if zero selfcalldepth selfcalldepth zero i leninspectstack print i selfcalldepth if i selfcalldepth 9 selffunckeeping track keeptrackkeeping trackfunc,['python'] +179913,iphone indoor location based app i am researching how to create an app for my work that allows clients to download the app preferably via the app store and using some sort of wifi triangulationfingerprints be able to determine their location for essentially an interactive tour now my question specifically is what is the best route to take for the iphone none of the clients will be expected to have jail broken iphones to my understanding this requires the use of the wifi data which is a private api therefore not meeting the app store requirements the biggest question i have is how does american museum of natural history get away with using the same technology but still available on the app store if youre unfamiliar with american museum of natural history interactive tour app see herethank you for any clarification you can provide,"['iphone', 'ios']" +179916,how to debug jstl i am using springsource tool suite with roo and have some successwhat bothers me though is that i do not know how to debug tag librarystuffi may add breakpoints but it never stops at themwhat i am looking for is a dump of all current variables in the contextup until now i did something likecforeach itemsdata varitem cout valueitemcoutbr cforeachsadly that is difficult to read and also not pretty straightforwardwhat can i do to improve this,['java'] +179926,integrate google yahoo and openid in android application i want to integrate google yahoo and openid in my android application i have successfully done with facebook twitter i had used facebook android sdk for facebook integration and twitter4jcoreandroid223jar for twitter integration now i am looking for yahoo google and openid integration i searched for yahoo integration also registered to get consumer key consumer secrete key and application id but i did not find any jar or sdk for yahoo integration there is for iphone but not any thing for androidi want my user to able to login in my application using any off the yahoo gmail openid accountplz guide me to if any jars or sdk is available for these integrationthanks in advance,['android'] +179935,installing a remote tomcat server in eclipse i want to deploy and debug a local web application using a remote instance of eclipse i went through the normal create a server wizard and specified my hostname as show belowhowever the next step requires i specify a local tomcat directory how can i specify a remote location instead,['java'] +179948,need the height of an invalidated swing component the basic setup is this i have a vertical jsplitpane that i want to have a fixedsize bottom component and a resizing top component which i accomplished by calling setresizeweight10 in this application there is a button to restore the default window configuration the default height of the window is the desktop height and the default divider location is 100 pixels from the bottom of the split paneto set the divider location to 100px i take the jsplitpane height 100 the problem is just before this i resize the jframe and since the code is in a button callback the jsplitpane has been invalidated but not yet resized so the divider location is set incorrectlyhere is a sscce click the button twice to see the problem the first click will resize the window but the divider location remains the same relative to the bottom of the window the second click properly moves the divider since the window size did not changeimport javaawtborderlayoutimport javaawtdimensionimport javaawtgraphicsconfigurationimport javaawtinsetsimport javaawtrectangleimport javaawttoolkitimport javaawteventactioneventimport javaxswingabstractactionimport javaxswingjbuttonimport javaxswingjframeimport javaxswingjlabelimport javaxswingjsplitpanepublic class sscce param args unused public static void mainstring args new sscce private final jframe f new jframejsplitpane ssce private final jsplitpane sp new jsplitpanejsplitpanevertical splittrue public sscce fsetdefaultcloseoperationjframeexit on close spaddnew jlabeltop spaddnew jlabelbottom spsetresizeweight10 fgetcontentpaneaddsp fgetcontentpaneaddnew jbuttonnew abstractactionresize to default override public void actionperformedactionevent e restoredefaults borderlayoutpage end fsetsize400300 fsetvisibletrue void restoredefaults fsetsizefgetwidth getdesktoprectfgetgraphicsconfigurationheight spsetdividerlocationspgetsizeheight 100 does not work on first button press rectangle getdesktoprectgraphicsconfiguration gc toolkit toolkit toolkitgetdefaulttoolkit dimension size toolkitgetscreensize insets insets toolkitgetscreeninsetsgc return new rectangleinsetsleft insetstop sizewidth insetsleft insetsright sizeheight insetstop insetsbottom i have thought of a few ways i might get around this but they all seem sort of hackish so far the best idea i have had has been to call fvalidate in between setting the frame size and setting the divider location but i am concerned there might be side effects to forcing validation earlythe other option i thought of is to use eventqueueinvokelater to put the call to set the divider location at the end of the event queue but that seems risky to me i am assuming the jsplitpane will have been validated at that point and i am concerned that may be a faulty assumption to makeis there a better way,['java'] +179966,chow to use empty list as optional parameter can somebody provide a example of thisi have tried nullstringempty and object initialization but they do not work since default value has to be constant at compile time,['c#'] +179981,python logging reverse effects of thisable the logging docs say that calling the loggingthisablelvl method can temporarily throttle logging output down across the whole application but i am having trouble finding the temporarily take for example the following scriptimport loggingloggingthisableloggingcriticalloggingwarningtest something hereloggingwarningtestso far i have not been able to find the something here that will reenable the logging system as a whole and allow the second warning to get through is there a reverse to thisable,['python'] +179984,determining execution time of queries in sqlite i am creating a program for analyzing and generating queries i was curious if there currently exists a method within sqlite such that i could query the time taken for a query to process i am unable to modify my install in any way so this method needs to work out of the box i am writing my tool in python and although i guess i could use the timer class to time execution this method will not work when i am connecting to remote machines and return a consistent timing,"['python', 'sql']" +179995,what is the best javascript compressionobfuscation tool what kind of a tool would you recommend for javascript compression andor obfuscation a google search comes back with a lot of online tools but i am not sure how to gauge their effectivenessusefulnessis there a tool that you would recommend for thisthanks,['javascript'] +180017,view helper methods not included for devise views in rspec integrationrequest tests when i visit my sign in page in a browser everything works finewhen i visit my sign in page in an rspec integrationrequest test i get the following erroractionviewtemplateerror undefined method title for class0x07af91800x07af32a8the title method is used by the view and defined in applicationhelper which devise seems to find when using the browser however during rspec integration tests devise is unable to find the helper methodis there anything i should be stubbing it seems wrong to be stubbing in integration tests any other ideasthis question is not about how to include devise helpers in integration tests i am manually filling in the sign in forms to authenticate,['ruby-on-rails'] +180046,calling stored procedures with parameters in petapoco i want to be able to call a stored proc with named parameters in petapoco in order to call a stored proc that does a searchfetchcan i do something like thisreturn dbfetchcustomerexec sp findcustnew sqlparameterfirst name fnamenew sqlparameterlast name lnamenew sqlparameterdob dobalso how can i call a stored proc that does an insertreturn dbexecuteexec insertcust custid 1 custname athanksnac,['sql'] +180052,c analogue for wpf so i have fooled around with wpf a bit recently and i must say that i really like the idea i love the framework as a whole from the gui to the plumbinghowever as much as i love managed land i love my native code just as much so i am wondering what sort of libraries exists for c which capture the essence of various parts of wpf i am not looking for interop solution nor do i want managed c or ccli solutions but pure c solutionsnow i am not expecting to find a copy of wpf for c i wouldnt expect that to exist nor would i need it to instead i would expect that different libraries might capture a subset of the desired concepts my particular interests arehardware accelerated graphics for widget based guis via directx or opengl preferably the latterdeclarative language for gui design preferably an xml dialectdata bindingresolution independence less importantto say a little about my reasoning i would like to implement such a library myself which captures a specific model that i have begun working out i am in the process of finding some more inspiration and helpful resources before locking down my design the library is intended to be crossplatform so references to crossplatform ideas would be great but not strictly necessary as i am usually capable of translating things into crossplatform solutionslastly although i am writing a c library and c ideas would be great i am open to ideas from any native languagethanks in advance for any help,['c++'] +180063,how to set the jdk netbeans runs on i have older nb67 nb69 nb70 which used to run on jdk160 21 and jdk160 25 now i have removed those jdks and only have jdk160 26 and jdk170 left but i still want to keep the older nbs but now when i run them i get this messagecannot locate java installation in specified jdkhome cprogram files x86javajdk160 25 do you want to try to use default version i tried to find where it is looking for the jdk160 25 and updated a few config files in cprogram files x86netbeans 67 and cusersusernbiregistryxml and yet the message keeps coming my question is where and what do i need to change to point it to cprogram files x86javajdk160 26,['java'] +180070,fixed header to uitableview i have got a uitableview that i would like to stick a 44px subview on top of i tried tableviewheader but that scrolls with the rest of the tablei tried searching and have found many people saying i need to add a uiview superview and then add my header and the uitableview to it however i cannot find an example on exactly how to do this i tried making a new uiview subclass and laying out the subviews in ib but i ran into trouble getting the table controller to link w the uitable because i do not know enough about ibhow can i do this with xibs can someone provide an examplethanks for any help you guys can provide,['ios'] +180083,2 column html layout with stretchtofit column i am in search of a 2 column nontable layout that behaves like a table and works in ie7this works but it is a table and as we all know tables are not the ideal option of layouts i will use it if i have to but i would like to find a more semantically appropriate way to do this note how the left column stretches to fit the containing content and the right column takes up the rest of the available spacetable trtd classleft12345tdtd classrighttdtr trtd classleft123456tdtd classrighttdtr trtd classleft1234567tdtd classrighttdtr trtd classleft12345678tdtd classrighttdtr trtd classleft123456789tdtd classrighttdtr trtd classleft1234567890tdtd classrighttdtrtabletable width100left width1px backgroundcolorblue colorwhiteright backgroundcolorgrayi tried to change this to use ullidiv but i can either set a fixed width or percentage left column there is no widthstretchtofithtmlul lidiv classleft12345divdiv classrightdivli lidiv classleft123456divdiv classrightdivli lidiv classleft1234567divdiv classrightdivli lidiv classleft12345678divdiv classrightdivli lidiv classleft123456789divdiv classrightdivli lidiv classleft1234567890divdiv classrightdivliulcssul liststylenone width100li clearboth positionrelative overflowhiddenli div padding5pxleft floatleft width20 backgroundcolorblue colorwhiteright backgroundcolorgraysuggestions,"['html', 'css']" +180104,where does visual studio look for assemblies i have got a framework which consists of many base classes that can be derived to develop many apps among these classes there is a subclass of systemwindowsformspanel for which i wrote its own designer everything is working fine with visual studio 2005 but something goes wrong when i try to move to vs2010 this is a much simplified version of what i am doingi have a project called coreclasse which contains an interface and two classespublic interface iconf string foo get set void initfoopublic class simpleclass public string foopublic class confloader public static iconf loadconf assemblyname anassemblyname new assemblynameconfclasses assembly anassembly assemblyloadanassemblyname iconf result iconfanassemblycreateinstanceconfclassesconfclass resultinitfoo return result then there is a project confclasses which references coreclasses and contains just one class implementing iconfpublic class confclass iconf public simpleclass confval public string foo get return confvalfoo set confvalfoo value public void initfoo confval new simpleclass confvalfoo bar and finally there is a project for the controls which references only coreclasses and contains a subclass of panel and the associated designerdesignermycontrolsdesignsimplepaneldesigner typeofirootdesignerpublic class simplepanel panel public simpleclass dummy new simpleclasspublic class simplepaneldesigner documentdesigner public iconf designerconf public simplepaneldesigner base designerconf confloaderloadconf now i create another solution which references all these dlls and contains an empty subclass of simplepanel when i double click on this class in solutionexplorer the constructor of simplepaneldesigner is executed and the method loadconf of confloader is called this means that confclassesdll is loaded dinamically and an instance of confclass is created everything is fine up to this moment but when initfoo is called this exception is raisedcould not load file or assembly coreclasses version10 cultureneutral publickeytokennull or one of its dependencies the system cannot find the file specifiedto make things harder the exception is not actually raisedin this example but this is exactly the kind of istructions my real app is executing and the exception i am getting i have not got a clue of whats happening here vs is executing a method which is in coreclasses why is it trying to load it again and where is it looking for it i checked the current appdomain too but it has coreclasses among its loaded assemblies and it does not seem to changejust to add some more details every project is build in a common folder not the usual objdebug folder inside the project folder and there is no other copy of my dlls on the pc at the moment i start my test then a copy of all the referenced dlls is done in a series of folders in the appdatalocalmicrosoftvisualstudio100projectassemblies folder of my userprofile and this seems to be the place vs is looking for the assemblies when assemblyload is executed and i can find a copy of coreclasses there i tried to clean all the folders to rebuild everything and to keep the different solutions openedclosed in every combination but without any improvement editas granmasterflush suggested this is the fusionlog generated by the exception prebind state information log user fcdbfc0107log thisplayname xenginecore version1001 cultureneutral publickeytokennull fullyspecifiedlog appbase filecprogram files x86microsoft visual studio 100common7idelog initial privatepath nullcalling assembly unknownlog this bind starts in default load contextlog using application configuration file cprogram files x86microsoft visual studio 100common7idedevenvexeconfiglog using host configuration file log using machine configuration file from cwindowsmicrosoftnetframeworkv4030319configmachineconfiglog policy not being applied to reference at this time private custom partial or locationbased assembly bindlog the same bind was seen before and was failed with hr 0x800702err unrecoverable error occurred during predownload check hr 0x800702edit 2just to add some info i took a look at the fusion logs generated by my simple example and found out that exactly the same log has been generated while trying to load coreclasses but someway visualstudio finds a way to cope with it,['c#'] +180110,java priority queue reordering when editing elements i am trying to implement dijkstras algorithm for finding shortest paths using a priority queue in each step of the algorithm i remove the vertex with the shortest thistance from the priority queue and then update the thistances for each of its neighbors in the priority queue now i read that a priority queue in java would not reorder when you edit the elements in it the elements that determine the ordering so i tried to force it to reorder by inserting and removing a dummy vertex but this does not seem to be working and i am stuck trying to figure it out this is the code for the vertex object and the comparatorclass vertex int v d public vertexint num int this vnum dthis class vertexcomparator implements comparator public int compare object a object b vertex v1 vertexa vertex v2 vertexb return v1dv2d here is then where i run the algorithm int thistancesnew intp comparatorvertex comparator new vertexcomparator priorityqueuevertex queue new priorityqueuevertexp comparator forint i0 ip i ifiv thistancesimax else thistancesi0 queueaddnew vertexi thistancesi run dijkstra forint i0 ip i vertex curqueuepoll iterator itr queueiterator whileitrhasnext vertex test vertexitrnext ifgraphcurvtestv1 testdmathmintestd curdgraphcurvtestv thistancestestvtestd force the pq to resort by adding and then removing a dummy vertex vertex resort new vertex1 1 queueaddresort queueremoveresort i have run several text cases and i know that the priority queue is not reordering correctly each time i go through and update the thistances for vertices but i do not know why did i make an error somewhere,['java'] +180142,how do i add my own javascript libs to clojurescript i want to write a google chrome extension using clojurescript with clojurescript i can use all the google closure libs but afaik access to the chrome browser is not included in those libs so i want to wrap all the chrome stuff in my own javascript libso far i tried creating my own jar that has a single javascript file that just creates a foo object and exports the constructor iv added this jar to the lib directory of the clojurescript compiler which also has for example googjar but so far without luckexception in thread main javalangillegalargumentexception no implementation of method compile of protocol cljsclosurecompilable found for class nilat clojurecore cache protocol fninvokecore deftypeclj494at cljsclosureeval1056fn 1057g 1047 1064invokeclosureclj187at cljsclosureget compiled cljsinvokeclosureclj422at cljsclosurecljs dependenciesinvokeclosureclj440at cljsclosureadd dependenciesdoinvokeclosureclj462at clojurelangrestfnapplytorestfnjava139at clojurecoreapplyinvokecoreclj602at cljsclosurebuildinvokeclosureclj701at usereval1246invokecljscclj21at clojurelangcompilerevalcompilerjava6406at clojurelangcompilerloadcompilerjava6843at clojurelangcompilerloadfilecompilerjava6804at clojuremainload scriptinvokemainclj282at clojuremainscript optinvokemainclj342at clojuremainmaindoinvokemainclj426at clojurelangrestfninvokerestfnjava421at clojurelangvarinvokevarjava405at clojurelangafnapplytohelperafnjava163at clojurelangvarapplytovarjava518at clojuremainmainmainjava37has anyone tried this before,['javascript'] +180154,a referral was returned from the server exception when accessing ad from c directoryentry ode new directoryentryldapdctest1dctest2dcgovdclkusing directorysearcher ds new directorysearcherode dspropertiestoloadaddname dspropertiestoloadadduserprincipalname dsfilter objectclassuser searchresultcollection results dsfindall foreach searchresult result in results consolewriteline0 1 resultpropertiesname0tostring resultpropertiesuserprincipalname0tostring on the searchresultcollection results dsfindall line i get an exceptiona referral was returned from the serverwhy do i get that exception and what does it mean,['c#'] +180160,how to specify binary data in jquery post function i have screenshot as binary stringi would like to post some data to server using post functionmy codevar filename screenshotjpgvar filedataurl string like dataimagejpegbase649j4a postserverurl title titlename namehere must be my file functionresponse alertokhow can i specify parameter as attached file,['jquery'] +180163,jquery ui trigger vs trigger i have developed a jquery uiplugin and cannot really understand which of these methods to useaccording to the jquery ui documentation i should use trigger to trigger the events this allows the handlers to be initialized with the plugin likeidpluginname click function called when clicked but if i later want to attach more listeners to this event i cannot find any way to do thati am trying to use jquery bind but that does not workexampleidbindclick function this does not get fired on click if using triggerthe only solution i have so far is to fire of both but it feels kind of strangemy code must do the following to workidpluginname click function called when my plugin uses this triggerclick bindfunction called when my plugin uses thiselementtriggerclicki am using custom events but did not think that was relevant for asking this questionanyone have an idea on how to use event chaining when using trigger,['jquery'] +180165,how often should i call srand in a c application i have a c application which calls rand in various places do i need to initialize srand regularly to ensure that rand is reasonably random or is it enough to call it once when the app starts,['c++'] +180195,change url on ajax request i want to add some get parameters to the page url i am loading content like thiscontentloadshoppl content product paramcateg1how can i change the url to have the same parameter categ1,"['javascript', 'jquery']" +180207,filename of downloaded file in dataapplicationoctetstream i am trying to download a file using data uri in following manner input typebutton onclickwindowlocationhrefdataapplicationoctetstreamcontentthispositionattachmentfilenamefiletxtdetails valuedownloadthe problem is that the downloaded file is always named unknown whatever i try to use as filename is this the correct way to give the file a name or something else needs to bedone,['html'] +180209,retrieve filename and contenttype from base64 encoded image ruby on rails i am trying to retrieve the contenttype and filename of an image which i am receiving in base64 encoded format here is the code which is doing a post request with the base64 encoded imagerequire nethttprequire rubygemsrequire active supporturl uriparsehttplocalhost30image activesupportbase64encode64openpublicimagesrailspngto ajoinpost params image image nethttppost formurl post paramsin the controller i need to get the contenttype and filename of this image so first i am decoding it image activesupportbase64decode64paramsimageimage data stringionewimageand then i am stuck i basically want to save this image using paperclip need some serious help update i cannot send params for contenttype and filename i was just mimicking the client which is sending this and i have no control on adding extra params,"['ruby-on-rails', 'ruby']" +180238,best practice for reusing python code i have write a python library appwhich contains several py files and several of my python projects need to reuse the code in the library app whats the recommended best practice for reusing python code currently i have thought out three optionscopy and paste this is far away from best practice it violates thedry principledo not repeat yourself add the folder of the library app to the environment variable pythonpath export pythonpathpathtolibraryapp then every projects on the same computer can reference the code in the library appand the folder of the library app to syspath in python code syspathappendpathtolibraryappamong the three options above which one do you prefer what advantage does it have compared to the other two options do you have any other better options it is much appreciated that if some one with years of python development experiences could answer this question,['python'] +180246,how to make a caseinsensitiveconcurrentmap how can i implementclass caseinsensitiveconcurrentmapv implements concurrentmapstring vwhich works just like concurrenthashmapstring v except that the keys are compared caseinsensitively the keys should not be converted to lowercase or uppercasenote that collectionssynchronizedmapnew treemapstring new mycaseinsensitivecomparator is no solution as it allows no concurrency and misses the additional methodscreating a stringlike class with caseinsensitive equals and hashcode is no option either since the map has to be passed to methods expecting strings as keys,['java'] +180255,is there anything more important than important in css it seems like my wordpress theme is adding a font color by default with important condition and it appears as inline style it targets not exactly what i need so is there anything i can do about it i already tried important important,['css'] +180261,alter table adding autoincrement in mysql i created a table in mysql with on column itemid after creating the table now i want to change this column to autoincrement how can this be done using alter statements table definition allitems itemid int10 unsigned itemname varchar50i am using the following code but it is throwing error syntax incorrectalter table allitemsmodify itemid int10 unsigned autoincrement,"['mysql', 'sql']" +180273,is it possible to create element on the fly with jquery mobile i have an app built using jquery and using various jqueryui toolsfor some reason i have to port it to smartphonestablet computer and decided to use jquery mobile for that in order to minimize the number of changesin my vanilla app i created some elements of the page on the fly depending of user interactionsfor example a slider could be created like that p is an object with a bunch of paramsfunction createsliderp return div idpid classpdivclass slider orientation palign minpconstraintmin maxpconstraintmax steppstep valuepcurval animatenormal and some event handling here but it does not matter and it will produce a nice looking slider now it looks likefunction createsliderp return range idpid classpdivclass minpconstraintmin maxpconstraintmax steppstep valuepcurval but as it is created on the fly all the stuff done by jquery mobile on the page load is not done on itis there a way to force that initialization without writing the slider in the htmlthanksedit i found in the doc that it could be achieved using containertriggercreatehowever this does not work yetedit2 ok create was the solution,"['javascript', 'jquery']" +180280,accessing private member variables from a templated class assignment operator i have a container class that is templatized i am overloading the assignment operator such that derived types can also be assignedmy problem is when the type is not the same i cannot access the private members of the container class what is the best approach to gaining access the member variables cannot be made accessible through public getters thanksexample code note var is privatetemplate class tcontainert containertoperatorconst containert rhs ifthis rhs var rhsvar works for same type return thistemplate class ttemplate typename ucontainert containertoperatorconst containeru rhs ifthis rhs var rhsvar does not work for different types return this,['c++'] +180289,android can i increase the textsize for the numberpicker widget we got a numberpicker widget in 30 but it seems that the textsize for this widget cannot be modified am i missing something or is this the case i would really like to increase the font size it is quite small with the default value but i cannot see a textsize property for it,['android'] +180291,difference between similarobject and similarobject are they not same can someone please explain this to medynamic castsomeobject similarobject what is the point of doing the address of a dereferenced pointer wouldnat the pointer itself just be the address of it,['c++'] +180319,goto in python i must use goto in python i read this but my python implementation cpython 271 on mac does not have this module so it does not seem to be portable it should at least work in all python implementations which support cpython bytecode esp i care about cpython and pypyi could go and build up the bytecode manually ie write my own python compiler because there is such an instruction jump absolute and friends but i wonder if there is an easier way is it possible via inspect or so to call a single bytecode instruction i also thought about compiling via python and then automatically patching the generated python bytecodeof course people will ask why and will not give me any helpful answer if i do not explain why i really really need this so in short my use case i am translating a c ast to python ast and compiling this i can map every logical flow all the loops and other stuff in some way to equivalent python code everything except goto related projects pycparser see interpreterpy pycpython pylua,['python'] +180322,best way of basically doing a where clause in javascript i am trying to parse some json that is sent to me and it is all in the format ofkeyvaluekey2value2 what would be the best way to get the value of key2 in this is there a way to do it without doing a for loop,['javascript'] +180327,python command line editing mistake on previous line when using python via the command line if i see a mistake on a previous line of a nested statement is there any way to remove or edit that line once it has already been enteredeg file openfile1 w for line in file parts linesplit example i meant to type instead print parts01 print print parts1so rather than retyping the entire thing all over to fix one char can i go back and edit something in hindsighti know i could just code it up in vim or something and have a persistent copy i can do anything i want with but i was hoping for a handydandy trick with the command line thanks,['python'] +180338,android need to record mic input is there a way to record mic input in android while it is being process for playbackpreview in real time i tried to use audiorecord and audiotrack to do this but the problem is that my device cannot play the recorded audio file actually any android player application cannot play the recorded audio fileon the other hand using mediarecorder to record generates a good recorded audio file that can be played by any player application but the thing is that i cannot make a previewpalyback while recording the mic input in real timeany feedback is very much appreciatedthanks in advance,['android'] +180354,swig module object has no attribute decklist i am having one hell of a time with swig due in part to the lack of good c examples to learn from i finally got my first program to compile with swig but am having troubles running it let me just get right to the codesetuppyusrbinenv pythonsetuppy file for swig examplefrom thistutilscore import setup extensiondecklist module extension decklist sourcesdecklist wrapcxx decklistcpp setup name decklist version 01 author me description testing ext modules decklist module py modules decklist decklisthppinclude boostunordered maphppclass decklist private boostunordered mapstdstring int mainboard boostunordered mapstdstring int sideboard public void addcardstdstring name int cardcount int getcountstdstring cardname decklist decklistdecklistcppifndef decklist hdefine decklist hinclude decklisthppinclude stdiohdecklistdecklistvoid decklistaddcardstdstring cardname int cardcount mainboardcardname cardcountint decklistgetcountstdstring cardname return mainboardcardnameendif decklistidecklistimodule decklist include decklisthppinclude decklisthppnow on the terminal i am on ubuntu natty narwhal i run the following two commandsswig python c decklistipython setuppy build ext inplacethe second gives me the following responserunning build extbuilding decklist extensiongcc pthread fnostrictaliasing dndebug g fwrapv o2 wall wstrictprototypes fpic iusrincludepython27 c decklist wrapcxx o buildtemplinuxx86 6427decklist wrapocc1plus warning command line option wstrictprototypes is valid for adacobjc but not for cgcc pthread fnostrictaliasing dndebug g fwrapv o2 wall wstrictprototypes fpic iusrincludepython27 c decklistcpp o buildtemplinuxx86 6427decklistocc1plus warning command line option wstrictprototypes is valid for adacobjc but not for cg pthread shared wlo1 wlbsymbolicfunctions wlbsymbolicfunctions buildtemplinuxx86 6427decklist wrapo buildtemplinuxx86 6427decklisto o homeaespiel1deck decklistsobut i wind up withdecklistcppdecklisthppdecklistidecklistpydecklistpyc decklistsodecklist wrapcxxsetuppyand a build folder with o files for both the decklist wrap and decklist filesif i run python in idle and switch into this directory andimport decklisti gettraceback most recent call last file pyshell2 line 1 in module import decklistimporterror no module named deckliststrangely if i run it from the terminal i can import decklist but then a command likedl decklistdecklist givestraceback most recent call last file stdin line 1 in moduleattributeerror module object has no attribute decklistwhat am i doing wrong i am so frustrated,"['c++', 'python']" +180357,when to thispose cancellationtokensource the class cancellationtokensource is thisposable and quick look in reflector proves usage of very probably unmanaged resource kernelevent it has no finalizer so if we do not thispose gc wont do thaton the other hand if you look at samples on msdn cancelation article all code snippets do not do that except oneit seems to be difficult to find correct place and time to do that in code you can not wrap code starting your parallel task with using if you do not wait for it and it makes sense to have cancelation only if you do not waitof course you can add continuewith on task with a thispose call but it that the way to gowhat about cancelable plinq queries which do not synchronize back but just do somenthing at the end let us say foraallx consolewritexis it reusable can reuse the same token for several calls and then thispose it together with host component let us say ui control because it has not something like reset method to cleanup iscancelrequested and token filed i would suppose it is nor reusable thus every time you start a task or a plinq query you should create a new one is it true if yes my question is what is the correct and recommended strategy to deal with thispose on those many cancelationtokensource instances,['c#'] +180368,adding two linked lists efficiently in c i have two linked lists representing the digits of decimal numbers in order from most to leastsignificant for eg 4796 and 57the answer should be 4853 without reversing the lists because reversing the lists would result in decrease of efficiencyi am thinking of solving the problem using stacki will traverse both the lists and push the data elements into two separate stacksone for each linked listthen i pop both the stacks together and add both the elements and if the result is a two digit no i 10 modulo it and store the carry in a temp variablethe remainder is stored in the node and the carry is added to the next sum and so onif the two stacks are s1 and s2 and the result linked list is restemp 0res nodemallocsizeofnodewhiles1top1 s2top1 temp 0 sum pops1 pops2 n1 nodemallocsizeofnode temp sum10 sum sum10 sum sumtemp n1data sum n1next res res n1 free n1 temp0ifs1top1s2top1 return reselse ifs1top1 whiles2top1 temp 0 sum pops2 sum sum temp temp sum10 sum sum10 n1 nodemallocsizeofnode n1data sum n1next res res n1 free n1 else whiles2top1 temp 0 sum pops2 sum sumtemp temp sum10 sum sum10 n1nodemallocsizeofnode n1data sum n1next res res n1 free n1 return res i have come across this problem many times in interview questions but this is the best solution that i could think ofif anyone can come with something more efficient in c i will be very glad,['c'] +180370,what does the c coclass attribute do i found code something like the following in a 3rd party library were usingcoclasstypeofblahclasspublic interface blah iblahwhat is this doing exactly the msdn documentation did not illuminate the subject sufficiently for me to follow,['c#'] +180377,choosing the right api level for my android application i currently have a application targeted at android 23 api level 10 but went thinking that probably people using android 2122 or older would not even be able to see the application in the market so i thought that using api level 3 would be the best to use but i do not know if this will maybe make certain elements in my app work less good and probably buggier since it actually uses old android code is there a good way to find out which api level i should use and also how do i convert my application to that level,['android'] +180383,css float align at top what is the best way without js to make all cells align ie have three cells per row in this casehtmlul idlist liline1 this is a very long line that will break the layoutli liline2li liline3li liline4 this is a very long line that will break the layoutli liline5li liline6li liline7 this is a very long line that will break the layoutli liline8li liline9liulcsslist li float left width 33 border 1px 0 solidresultit can all be seen in this fiddlethe number of items per line may change ie i do not know where the new line will start and the height of each is variable ie cannot force height,['css'] +180399,locating the line number where an exception occurs in python code i have a code similar to thistry if x statement1 statement2 statement3 elif y statement4 statement5 statement6 else raiseexcept statement7here i am sure that the exception occurs in if x block but i would like to know in which statement of if x block the exception occurs is there a way to get the line number where the exception occursregards,['python'] +180400,what exactly are the rules for avoiding the mixed content warning in ie due to background images this is related to ssl and mixed content due to css background images but that question had no accepted answer and the one i am asking is a little more specificunder some circumstances when accessing an https website ie will throw the mixed content warning if an element is given a style with a background image i found one forum reference that said the warning can be avoided if you put the reference in a stylesheet for examplesomeelement a width11px height11px thisplayblock overflowhidden backgroundurlimagessprites listpng norepeat cursorhand cursorpointer backgroundposition0px 72pxbut not if you try to create the element inline a lasomeelementappenda titlesomething stylebackground urlimagessprites listpng norepeat etcand indeed this works for me i have seen others that say you have to use an absolute https url to refer to the image rather than a relative onewhat is the real story here is there some official explanation or at least a reference to what the rules are or failing that is there a standard set of guidelines which if followed makes it extremely unlikely to trigger the warning,"['javascript', 'jquery', 'html']" +180405,how to check if sharedpreferences file exists or not i am looking an android shared preferences and i am wondering is there a way to just check if the preferences file exists sharedpreferences mysharedpreferences mysharedpreferencesgetsharedpreferencesaname of your preferenceamodethis above code leads me to believe that name of your preferene is stored as a file or some sort of container that will contain your preferencesi am wondering is there away to check if this exists or not when a user loads up an activity i want to save all the settings into this file with some default valuesoff for all settings however i only want to do this if they are going to the page for the first timeotherwise if i would do something like this every time the page loads upsharedpreferenceseditor editor mysharedpreferencesedit now store your primitive type values in this case it is true 1f and hello world editorputboleanamybooleanatrueeditorputfloatamyfloata1feditorputstringamystringaa hello worldai am guessing it would override all settings even ones they set,['android'] +180429,what is the difference between mysql server and mysql client in ubuntu i normally install both but what are the differences between the client and server for mysql,['mysql'] +180453,the method getsystemservicestring is undefined for the type listen i am trying to check if comandroidmusic is running and i am getting the following error on this line thisgetsystemservicecontextactivity serviceerrorthe method getsystemservicestring is undefined for the type listencode public boolean ismusicrunning activitymanager activitymanager activitymanager thisgetsystemservicecontextactivity service listrunningaprocessinfo procinfos activitymanagergetrunningaprocesses for int i 0 i procinfossize i if procinfosgetiprocessnameequalscomandroidmusic toastmaketextnull music is running toastlength longshow if you could let me know what i am doing wrong here that would be great,['android'] +180476,which objects can i use in a finalizer method i have a class that should delete some file when thisposed or finalized inside finalizers i cannot use other objects because they could have been garbagecollected alreadyam i missing some point regarding finalizers and strings could be usedupd something like thatpublic class tempfilestream filestream private string filename public tempfilestreamstring filename basefilename filemodeopen fileaccessread fileshareread filename filename protected override void thisposebool thisposing basethisposethisposing if filename null return try filedelete filename oops filename could be gced already filename null catch exception e,"['c#', '.net']" +180487,xcode project how to detect target programatically or how to use env vars i want to do an application test that parses some json stores to core data and reads out some objectshow can my code know if it is being run as part of a test or normal run just some way to know are we in test target because the app when it fires up now kicks off a bunch of requests to populate my coredata with info from the server i do not want it to do this during my tests i want to fire up the app read hardcoded json from a file and store this using the same methods as otherwise into coredata and verify the resultsif someone could explain how to pass specific keyvalue pairs on a per target basis that can be read from within the app i would be even more delightedthis has been the most frustrating part of an otherwise positive experience in xcodecocoa dev so far,['objective-c'] +180498,how to add builtin functions i am new to python programming how can i add new builtin functions and keywords to python interpreter using c or c,['python'] +180499,update height with viewflipper i want to be able to update height on every child of the viewflipper is this possible as i could never find any api documentation for viewflipper and updating the height or width,['android'] +180522,objectivec arc error fobjcarc is not supported with fragile abi i am having a problem trying to migrate my iphone app to the new arc technology when i try to convert the code the following error shows up 29 times apple llvm compiler 30 error fobjcarc is not supported with fragile abiwhat does this mean and more importantly how can i fix itthanks in advance,"['iphone', 'objective-c']" +180529,jquery multiselect set a value as selected in the multiselect dropdown i am having a multiselect dropdown as belowselect iddata namedata classdata multiplemultiple option value100foption option value101baroption option value102batoption option value103bazoptionselecton load of page i will get an array of value like 101102i should iterate through the array and make the values selectedcheck boxes corresponding to the ids should be checkedplease help,['jquery'] +180539,why declare a struct that only contains an array in c i came across some code containing the followingstruct abc unsigned long arraymax abcwhen does it make sense to use a declaration like this,['c'] +180540,convert unsigned byte to signed byte is there an easy and elegant way to convert an unsigned byte value to a signed byte value in java for example if all i have is the int value 240 in binary 24 bits 10 32bits how can i get the signed value for this int,['java'] +180542,max return value if empty query i have this queryint maxshoesizeworkerswherexxcompanyid8maxshoesizewhat will be in maxshoesize if company 8 has no workers at allupdatehow can i change the query in order to get 0 and not an exception,"['c#', '.net']" +180548,mvc 3 reuse of partial views and jquery without conflicting the dom as i am still new to mvc 3 and jquery i would like to know a best practice solution to how the following can be solved i have a view where i use jquery ajax to fetch and thisplay a partial view with some product details for product a the loaded partial view consist of a bunch of html and jquery code which is tied to the defined ids within the partial viewthus i would like to reuse the same partial view to show details from other products on the same view eg show product b details in a popup dialog whenever the popup is shown the newly fetched partial view will conflict with the partial view for product a as the same ids are used in the html is there a way to encapsulate the html and javascript in the partial view and reuse it several pages without worry about any conflicts with ids and stuff i hope my question makes sense thanksnima updatedhere is some pseudo code outlining my issue viewscript typetextjavascriptdocumentreadyfunction productitemsclickfunction var input productid thisattrdataproductid var url url urlcontentproductdetailsshowproductdetails show the modal box with product details dialogboxdialog title thisattrdataproducttitle fetch content in the background geturl input function result response dialogboxhtmlresult scriptdiv iddetailsarea htmlrenderpartialproductdetails modelproduct divdiv idproductlinks span classproductitems dataproductid123product badivdiv iddialogbox stylethisplay nonedivcontroller action showproductdetailspublic actionresult showproductdetailsint productid get product from db and return the partial view return partialviewproductdetails ppartial view productdetailsscript typetextjavascript function setproducttabcontentselectedtab productdescriptioncontent divcssthisplay none switch selectedtab case tab1 productdescriptiontextcssthisplay block break case tab2 productspecificationtextcssthisplay block break documentreadyfunction get all the menu items var menuitems productmenu a select the first tab as default menuitemsfirstaddclassmenuitemactive handle the look of the tabs when user selects one menuitemsclickfunction var item this get content for the selected tab setproducttabcontentitemattrhref menuitemsremoveclassmenuitemactive itemaddclassmenuitemactive return false scriptdiv idproductmenu style a hreftab1 div classmenuitemheadermenu1div a a hreftab2 div classmenuitemheadermenu2 div adivdiv idproductdescriptioncontent div idproductdescriptiontext stylethisplay none modelproductdescription div div idproductspecificationtext stylethisplay none modelproductdescription2 divdivissuewhen the partial view gets loaded twice in the dom the divs conflicts,['jquery'] +180570,why int cannot be null how does nullable int int work in c i am new to c and just learned that objects can be null in c but int cannotalso how does nullable int int work in c,['c#'] +180595,is there a tts engine with a natural voice i was looking for a decent text to speech software and could not find any with a natural voice i hate listening to the microsoft robotic voices and although anna does away with it in windows 7 and probably vista she is still far from naturalwhat i needa free text to speech librarypreferred language c javai plan to create a decent tts software or better still an ms wordoffice plugin if things go smoothly i am working on windows 7 obviously,"['c#', 'java']" +180598,making a jframe and observable object i have a class let us say myjframe which represent the gui of my application it implements the interface observer and override the method updatepublic class myjframe extends jframe implements observer public void updateobservable arg0 object arg1 now i want to make also my jfram an observable object but i cannot because it already extend the class jframe i tried to create a variable of type observable in my classpublic class myjframe extends jframe implements observer observable observable new observablethe problem here is that i can add observer to this observable field and i can also notify the observer but i cannot invoke the method setchanghed because it is declared as protected which has to be called before the notificationdo you have any idea about i can implement itthanks,['java'] +180599,which c compiler is my program using i am not very expert in cpp programming rather a beginner in the enormous world of programming as these days we just install any ide and start with our programs in it i started using codeblocks ide but just out of curiosity wanted to know which compiler is my program using as it can be 432 or 408 or maybe something elsei tried reading through the build logs it was not there a small google did not help eitheris there any simple command which i can run in my cpp progam and check which compiler my ide is usingthanks in advance,['c++'] +180612,c property grid string editor what is the easiest way to have visual studiolike editor for string in propertygrid for example in autoslocalswatches you can previewedit string values inline but you can also click on magnifying glass and see string in external window,['c#'] +180636,propertychangesupport for spinnernumbermodel i want to listen to the changes of the value of the spinnernumbermodel for a jspinneri create a propertychangesupport and put the model into iti need the propertychangelistener because it shows me the old and new value of the property the snippet does not work the propertychange method prints nothing when i click on the jspinnera simple changelistener give only the new value but i need also the old value how can i get itpackage deunikasseljungimport javabeanspropertychangeeventimport javabeanspropertychangelistenerimport javabeanspropertychangesupportimport javaxswingjframeimport javaxswingjspinnerimport javaxswingspinnernumbermodelpublic class propertychangetest implements propertychangelistener public static void mainstring args new propertychangetest public propertychangetest jframe frame new jframe framesetbounds100 100 450 300 framesetdefaultcloseoperationjframeexit on close int value 1 int min 0 int max 10 int step 1 spinnernumbermodel spinnermodel new spinnernumbermodelvalue min max step propertychangesupport pcs new propertychangesupportspinnermodel pcsaddpropertychangelistenervalue this jspinner spinner new jspinnerspinnermodel framegetcontentpaneaddspinner framesetvisibletrue override public void propertychangepropertychangeevent evt systemoutprintlnevt systemoutprintlnevtgetsource,['java'] +180640,input width defined at css level and at the element level styleinputtypetext width 200px border 1px solid cstylebodyinput typetext nametest valuetest size5 bodywhen this is viewed on browser firefox 5 the size it appears is a fixed 200px it seems the size i specified is completely ignored this is from a mvc project and that is the default style css that comes with it for the time being i took off the width 200px but is there a way to keep it there and override it at the input leveli also triedinput typetext nametest valuetest width50px it did not override at all,"['html', 'css']" +180649,linq lambda group by with sum hi i can do this in method syntax but i am trying to improve my lambda skills how can i doselect sumjob group quota as sumfrom dbotbl job sessionwhere job group job number jobnumand job group id like sessgroup by job group job numberi have been messing around with it but cannot get it rightlnqtbl job sessionsgroupbya ajob group job number jnum selectb new bjob group quotasum,['c#'] +180654,how does nsproxy transform itself into another object the nsproxy class reference says thistypically a message to a proxy is forwarded to the real object or causes the proxy to load or transform itself into the real objecthow exactly would the transform itself into the real object work to make things a little more specific suppose class foo has a method newfoowithstring that takes a string and returns a new instance of foo would it be possible to setup an nsproxy that sits around and if a pleasebecomeafoousingstring bar message is received transforms itself into foo newfoowithstring bar occupying the same memory without messing with other references to itself that may exist,['objective-c'] +180657,how do i use the scancrop property of a zbar reader i am using the zbar sdk for iphone in order to scan a barcode i want the reader to scan only a specific rectangle instead of the whole view for doing that it is needed to set the scancrop property of the reader to the desired rectanglei am having hard time with understanding the rectangle parameter that has to be setcan someone please tell me what rect should i give as an argument if on portrait view its coordinates would be cgrectmake a b c d,"['objective-c', 'iphone']" +180677,c problem on casting why cast a char to char when allocating a buffer in the code sample below and what is happening herefirst reinterpret castchar first code sample public char allocate if first return 0 char result first first reinterpret castchar first why available return result private char buffers char first stdsize t available stdsize t maxnum stdsize t buffersize whole class is here class chunk public chunkstdsize t buffersize stdsize t buffernum buffers 0 first 0 available 0 maxnum 0 buffersize 0 assertbuffersize sizeofchar buffernum 0 stdsize t len buffersize buffernum buffers new charlen first buffers available buffernum maxnum buffernum buffersize buffersize char begin buffers char end buffers len buffersize reinterpret castchar end 0 for begin end begin buffersize char next reinterpret castchar begin next begin buffersize chunk delete buffers char allocate if first return 0 char result first first reinterpret castchar first available return result void deallocatechar buffer reinterpret castchar buffer first first buffer available bool isfull const return available 0 the buffer is one of this chunk bool ischunkbufferchar buffer const assertbuffer return buffer buffers buffer buffers maxnum buffersize private char buffers char first stdsize t available stdsize t maxnum stdsize t buffersize,['c++'] +180680,running bundle install fails and asks me to run bundle install in fact all gemrelated commands result in the same error message when run from inside the existing rails app i cloned from a git repo bundle installcould not find tzinfo0327 in any of the sourcesrun bundle install to install missing gems gem listcould not find tzinfo0327 in any of the sourcesrun bundle install to install missing gems bundle updatecould not find tzinfo0327 in any of the sourcesrun bundle install to install missing gems rails vcould not find tzinfo0327 in any of the sourcesrun bundle install to install missing gemsi thought i already had rails installed following commands were run from outside the app directory rails vrails 303 ruby vruby 192p290 20110709 revision 32553 x86 64darwin1100any idea whats up with bundle install telling me to run bundle installi exited my app directory and manually didsudo gem install tzinfo v 0327but upon entering my app directory again and trying bundle install bundle installcould not find polyglot031 in any of the sourcesrun bundle install to install missing gemsso i went back out of the app directory did sudo gem install polyglot v 031bundle install now yielded bundle installcould not find treetop149 in any of the sourcesrun bundle install to install missing gemswhy am i having to manually install all these random gems that i did not have to in the past new dev env anyone know what i could have set up wrong in my environment,"['ruby-on-rails', 'ruby']" +180687,sequence iterator is not there one in boost from time to time i am feeling the need for a certain kind of iterator for which i cannot make up a good name except the one prefixed to the title of this question suppose we have a function or function object that maps an integer to type t that is we have a definition of a mathematical sequence but we do not actually have it stored in memory i want to make an iterator out of it the iterator class would look something like thistemplate class f class tclass sequence iterator public stditerator int i f f public sequence iterator f f int i 0ff ii operators etc will compare increment etc the value of i t operator const return fi template class t class fsequence iteratorf t make sequence iteratorf f int i return sequence iteratorf tf imaybe i am being naive but i personally feel that this iterator would be very useful for example suppose i have a function that checks whether a number is prime or not and i want to count the number of primes in the interval ab i would do thisint identityint i return icount ifmake sequence iteratorintidentity a make sequence iteratorintidentity b isprimesince i have thiscovered something that would be useful at least imho i am definitely positive that it exists in boost or the standard library i just cannot find it so is there anything like this in boost in the very unlikely event that there actually is not then i am going to write one and in this case i would like to know your opinion whether or not should i make the iterator category random access iterator tag my concern is that this is not a real rai because operator does not return a referencethanks in advance for any help,['c++'] +180703,android email sqlite database i am hoping to be able to email the sqlite database i use within my app as a form of backup that the user can perform my current code is below the database shows up as an attachment in the email intent and the email will send but the attachment is not sent file file new fileenvironmentgetdatadirectory datacomappdatabasesdatabasenameintent intent new intentintentaction sendintentputextraintentextra email new stringintentputextraintentextra subject backupintentputextraintentextra text intentsettypeapplicationoctetstreamintentputextraintentextra stream filetouristartactivityintentcreatechooserintent send email,['android'] +180708,icon already includes gloss effects i have a problem with the gloss effect in app icon at ios 5 beta 5 in ios 4 it is show the effect not gloss but ios5 shows the glos effect i put the option icon already includes gloss effects yes but simply does not work and it appears that the application google also has the same problemthanks,['ios'] +180713,object copy versus clone in php consider the followingobject1 new stdclassobject2 object1object3 clone object1object1content ciaovar dumpobject1 outputs objectstdclass1 1 content string4 ciao var dumpobject2 outputs objectstdclass1 1 content string4 ciao var dumpobject3 outputs objectstdclass2 0 is it a normal php behavior that object2 has a content identical to object1 to me it sound like object2 is a reference to object1 instead of a copycloning the object before changing the content does act like a copythis behavior is different than what happens with variables and seems unintuitive to me,['php'] +180725,why does my console application have command history i have written a console application which is essentially a consolereadlineloop when the application is waiting for input pressing the up arrow key iterates through all previous lines of input my application does not contain any code for this feature what part of windows provides this how can i thisable iti can only image that it is either a feature of the console subsystem or implemented in consolereadlinehere is some sample code that exhibits the described behaviornamespace consoleapplication class program static void mainstring args string input do input systemconsolereadline while input exit i would like to thisable the history feature for now and reimplement it later using my own code the current behavior is too limited,"['c#', '.net']" +180739,why does bitmap cause rule ca20 but image does not there are a lot of questions on so lamenting the fact that code analysis rule ca20 is being applied possibly too rigorously by vs2010 but i seem to have run into a case where it should be applied but is notconsider the following codeimage srcimage imagefromfilesourcebitmap newimage new bitmapnewwidth newheightusing graphics gr graphicsfromimagenewimage grdrawimagesrcimage new rectangle0 0 newwidth newheightnewimagesavedestination imageformatjpegnow if i run code analysis in visual studio 2010 on this it will complain about newimage not being thisposed easy fix put it in another using block but it does not complain about srcimage which also has a thispose method that i am never calling does anyone know why code analysis does not complain here,['c#'] +180757,iterate through unicode strings and compare with unicode in python dictionary i have two python dictionaries containing information about japanese words and characters vocabdic contains vocabulary key word value dictionary with information about itkanjidic contains kanji single japanese character key kanji value dictionary with information about itnow i would like to iterate through each character of each word in the vocabdic and look up this character in the kanji dictionary my goal is to create a csv file which i can then import into a database as join table for vocabulary and kanjimy python version is 26my code is as followingkanjivocabjoinwriter csvwriteropenkanjivocabjoincsv wb delimiter quotechar quotingcsvquote minimalkanjivocabjoincount 1loop through dictionaryfor key val in vocabdiciteritems if vallang is jpn only check japanese words vocab valtext print vocab loop through vocab string for v in vocab test kanjidicgetv print v print test if test is not none print strkanjivocabjoincountstrtestidstrvalid kanjivocabjoinwriterstrkanjivocabjoincountstrtestidstrvalid kanjivocabjoincount kanjivocabjoincount1if i print the variables to the command line i getvocab works prints in japanesev one character of the vocab in the for loop i12test character looked up in the kanjidic noneto me it seems like the for loop messes the encoding upi tried various functions decode encode but no luck so farany ideas on how i could get this workinghelp would be very much appreciated,['python'] +180762,how do you add prototype functions to canvas context i want to add some methods to the context retrieved from a canvas object for example i would like to have this prototype method added to any 2d drawing context which resets the transform to an identity matrixcontextprototypeidentity function thissettransform1 0 0 1 0 0and then whenever i request a 2d context like sovar canvas documentgetelementbyidcanvasvar context canvasgetcontext2dthe context object automatically has an identity method available for me to reset any transform back to the default state i know i can attach my prototype method by sayingcontextidentity function contextsettransform1 0 0 1 0 0 but i have to do this explicitly every time and i would prefer the contextprototypeidentity function syntax as it would attach the method for me automaticallycurious,['javascript'] +180814,rails always include the milliseconds with created at for every model how do i modify my rails app to always include the milliseconds information with the created at field of my modelsthis question has the answer for how to do it for an individual model but i want to do it globallyfor example when i retrieve all my item models by hitting items with a get i get the following jsoncreated at20110807t234215zupdated at20110807t234215zid180user id6contenttestbut note that the created at field does not have any information about the millisecond that it was created how do i include that for all my models,['ruby-on-rails'] +180861,evaluate c expression inside another expression i want to use an expression in another oneexpressionfuncdouble double f x x x 27 blah expression with xexpressionfuncdouble double g y 3 8 fcompiley y blah expression with y and fythis will not work when sent to linq to sql because fcompile is unknown to sqlhow do you evaluate the expression f on the variable y without compiling it but still using normal syntax to define gi do not want to have to define all of g with some unreadable expressionaddexpressionmultiply etc statementsthanks,['c#'] +180905,how can i intercept an incoming sms with a specific text i want to know about intercepting an incoming sms for a specific key word exhi so that i can read that sms containing hi in it delete it after reading the msg if that msg does not contain any such text then it wouldnt be deleted and instead saved in the inbox guys please help me i am finding it very difficult to perform this functionality,['android'] +180906,compiling functional languages to c suppose youre compiling a functional language to portable c and suppose also that for various reasons you want precise rather than conservative garbage collection there is no portable way perhaps no way at all in the general case for the garbage collector to figure out what is and is not a pointer on the c stack it seems to me there are two solutions to this problemshadow stack make each c function maintain bookkeeping information about what is and is not a pointer this is the approach recommended by eg llvmtake advantage of the fact that you are compiling a functional language which means mainline code has no side effects when the allocator detects out of memory instead of calling the garbage collector itself it aborts the current operation with a longjmp back to the main loop which calls the garbage collector in a context where the set of variables that may contain pointers is known in advance then restarts the operationit seems to me that if you are dealing with a pure functional language where the second approach is applicable it must be more efficient than the first approach as well as easier to mix with handwritten care there any problems i am overlooking any references to existing thiscussion or implementations of this technique,['c'] +180917,difference of hashmap in altrtjar and rtjar what is the difference between hashmap in altrtjarand rtjar i think i see a considerable speed upin one of my applications what would be the explanationbest regardsps i found the two different jar in jdk 160 25 64bit eventually thespeed up is also related to altstringjarthis alt could eventually be related to a command line optionbut i am more interested in understanding altrtjar and i do not see from theabove article that there is a command lineoption related to it,['java'] +180973,new datelong gives different results when i run this codesystemoutprintln x date new date 1311781583373l i get this result in eclipses junit runnerx datewed jul 27 164623 gmt0100 2011and this result in maven from the command linex datewed jul 27 174623 cest 2011as you can see the hour is differentsame computer same java version maybe 30s apart whyedit also the time zone is different why is java using cest when it is started from maven and gmt0100 when started from eclipseor to put it another way how can i force java to use either,['java'] +180990,whats a floodcolor and lightingcolor definition in css way cool i would just realised there is something called floodcolor and lightingcolor in css does anyone know what is a floodcolor and lightingcolor and what do they dowhat exactly do these meanthe afloodcolora property indicates what color to use to flood the current filter primitive subregion the keyword currentcolor and icc colors can be specified in the same manner as within a specification for the afilla and astrokea properties the alightingcolora property defines the color of the light source for filter primitives afediffuselightinga and afespecularlightingahow do we apply these socalled svg effects i have tried setting the lightingcolor to red but there does not seem to be any effect whatsoever,"['html', 'css']" +181016,how to wait in objectivec i want to change my uilabels text after 2 secondsi tried setting my uilabels text to a text and use sleep2 and finally changing the text to another textbut sleep2 only freezes the app and another text is set without thisplaying a text for 2 secondshow may i thisplay a text for 2 seconds and then show another text,"['ios', 'objective-c']" +181040,java sockets dataoutputstream or outputstream i am still relatively new to sockets and i have not seen any information regarding this subjectto write to a connected socket you can either usesocketgetoutputstreamwriteor create a new dataoutputstream from the socket outputstream and write to thatwhat is considered good practice using a dataoutputstream or outputstreammost of the examples i find on the internet use dataoutputstream to send strings such as in a two way chat are there any advantages or thisadvantages from using dataoutputstream over outputstreamis there any difference in performance that is noticeable between these two when for example sending files,['java'] +181054,a super strange bug of ospathabspath on my python 26 64bit win7 activepython when i callospathabspathdprojectssuishoubeiwssbstaticvoicesenmp3conmp3it returnsconi have no problem with other paths so faranyone has the same issuecan someone please tell me why,['python'] +181055,how to emulate destruct in a static class i have coded a simple configuration class for my own frameworkthere are simple functions like get set or loadfilebut all functions and variables are staticand now i want to implement an autosave mechanism i had the idea to create an instance in my init function whose destruct will call the static destruct functionphpclass config static private autosave static public function get set save load etc static public function initautosave selfautosave autosave new config static public function destruct if selfautosave selfsave public function destruct configdestruct are there any better solutions or is my design pattern completely wrong in this case,['php'] +181072,how to use automapper formember i am trying to set up automapper to convert from entity to dto i know i am supposed to be using formember after mappercreatemapentity dto to set up custom mappings but this does not seem to be an available methodedit for clarificationi am not looking for a link to the documentation which i have read or an explanation of the basic syntax i am using the correct syntax as described in answers and the documentation for example mappercreatemapefaddress addressformemberdest destcode opt optmapfromsrc srcnameif i have an invalid type name within createmap i can see formember as a valid method mousing over shows the method signature as i would normally expect but as soon as i give it two valid types formember says it cannot resolve the symbol as if the method is not availableis there some kind of constraint on the generic classes which i am not meeting thanks,['.net'] +181086,problem installing ruby 192 on mac os lion i am running lion utilizing xcode 4 have rvm and homebrew installed but am only able to run ruby 187 spurvis rogue ruby v ruby 187 20100110 patchlevel 249 universaldarwin110 spurvis rogue i have read through several threads related to this topic but nothing seems to work for my problem spurvis rogue rvm install 192 installing ruby from source to usersroguervmrubiesruby192p290 this may take a while depending on your cpus ruby192p290 fetching ruby192p290 extracted to usersroguervmsrcruby192p290 already extracted fetching yaml014targz to usersroguervmarchives extracting yaml014targz to usersroguervmsrc configuring yaml in usersroguervmsrcyaml014 compiling yaml in usersroguervmsrcyaml014 installing yaml to usersroguervmusr ruby192p290 configuring ruby192p290 compiling error error running make please read usersroguervmlogruby192p290makelog error there has been an error while running make halting the installationthe makelog gives me the following info 20110808 115052 make usrbingcc42 o3 ggdb wextra wnounusedparameter wnoparentheses wpointerarith wwritestrings wnomissingfieldinitial rbconfigrb unchanged miniruby ilib iextcommon i rextpurelibrb encmake encmakerb builtinencsasciio us asciio unicodeo utf 8 miniruby ilib iextcommon i rextpurelibrb i toolcompile preluderb preluderb encpreluderb gem prelude usrbingcc42 o3 ggdb wextra wnounusedparameter wnoparentheses wpointerarith wwritestrings wnomissingfieldinitial ar rcu libruby191statica dlno encodingo versiono arrayo bignumo classo comparo complexo diro dln findo enumo enumera usrbingcc42 dynamiclib wlundefineddynamic lookup wlmultiply definedsuppress wlflat namespace install name usersr w l init l threadptr libruby191dylib miniruby ilib iextcommon i rextpurelibrb toolgeneric erbrb c o encdbh templateencdbhtmpl enc enc encdbh unchanged make f encmk rubyminiruby ilib iextcommon i rextpurelibrb minirubyminiruby ilib iextcommon i r make1 nothing to be done for enc make f encmk rubyminiruby ilib iextcommon i rextpurelibrb minirubyminiruby ilib iextcommon i r make1 nothing to be done for srcsminiruby ilib iextcommon i rextpurelibrb toolgeneric erbrb c o transdbh templatetransdbhtmpl enctra transdbh unchanged make f encmk rubyminiruby ilib iextcommon i rextpurelibrb minirubyminiruby ilib iextcommon i r make1 nothing to be done for enctransmake f encmk rubyminiruby ilib iextcommon i rextpurelibrb minirubyminiruby ilib iextcommon i r mkdir p extx86 64darwin1100enc extx86 64darwin1100enctrans enc enctrans compiling testbug3662 make1 nothing to be done for all compiling teststring make1 nothing to be done for all compiling bigdecimal make1 nothing to be done for all compiling continuation make1 nothing to be done for all compiling coverage make1 nothing to be done for all compiling curses compiling openssl usrbingcc42 i iextincludex86 64darwin1100 iinclude iextopenssl druby extconf hextconfh ossl bioc in function aossl obj2bioa ossl bioc26 error called object arnda is not a function ossl bioc42 warning implicit conversion shortens 64bit value into a 32bit value make1 ossl bioo error 1 make mkmainsh error 1per other suggestions i tried adding export ccusrbingcc42 to my bashrc but that did not solve the problem eitherplease help,['ruby'] +181104,generating wsdl with nusoap return struct with various types int string array of structs i would like to query some stuffs via soap by generating wsdl with nusoapi know there are lots of questions related to the topic but i did not have success to adapt the codes to my particular problemi was successful in generating wsdl code which returns just an array of structs associative array but i would rather like to return an object struct which contains an integer variable a string variable and an array of structsso this is the code that works for returning an array of structsphp function getstuffs user pass here we can check user and pass and do whatever if it is not alright we can throw exception or return null or sg similar stuff array array stuff array array id122 nameone stuff stuff array array id213 nameanother stuff stuff array array id435 namewhatever stuff stuff array array id65 namecool stuff stuff array array id92 namewow what a stuff return stuff array require once nusoaplibnusoapphp server new soap server mynamespace serverscript uri mynamespace http serverhttp host serverscript name serverconfigurewsdlmystuffservice urn mynamespace serverwsdlschematargetnamespace serverwsdladdcomplextype name stuffs typeclass complextypesimpletypeattribute complextype phptype currently supported are array and struct php assoc array struct compositor allsequencechoice all restrictionbase namespacename elements array name arraynametype array id array name id type xsdint name array name name type xsdstring serverwsdladdcomplextype name stuffsarray typeclass complextypesimpletypeattribute complextype phptype currently supported are array and struct php assoc array array compositor allsequencechoice restrictionbase namespacename soapencarray elements array name arraynametype array attrs array array ref soapencarraytype wsdlarraytype tnsstuffs arraytype namespacename tnsstuffs serverregister string name the name of the php function classmethod or classmethod getstuffs array in assoc array of input values key param name value param type array user xsdstring pass xsdstring array out assoc array of output values key param name value param type array return tnsstuffsarray mixed namespace the element namespace for the method or false urn mynamespace mixed soapaction the soapaction for the method or false urn mynamespace getstuffs mixed style optional rpcdocument or false note when document is specified parameter and return wrappers are created for you automatically rpc mixed use optional encodedliteral or false encoded string documentation optional description to include in wsdl fetch array of stuffs id name documentation serverwsdlschematargetnamespace mynamespace serverserviceissethttp raw post data http raw post data exitin a c console application after adding a web reference called stuffservice with the wsdl appended to the appropriate url where this phpfile can be found this code works i can perfectly query the stuff array values like thisusing systemusing systemcollectionsgenericusing systemlinqusing systemtextnamespace webservicetest class program static void mainstring args stuffservicemystuffservice myservice new stuffservicemystuffservice stuffservicestuffs stuffs myservicegetstuffssomeone 1234 foreach var stuff in stuffs consolewritelinestuffid stuffname consolewriteline consolewritelinepress a key consolereadkey that is cool but i would like to develop this code to give back an object like thisclass responseobject public responsecode 0 public responsemessage public stuffarray null responseobject nullfunction getstuffs user pass global responseobject responseobject new responseobject check stuffs in a simple way now ifuser someone pass 1234 responseobjectresponsecode 2 responseobjectresponsemessage authentication failed return responseobject responseobjectstuffarray array responseobjectstuffarray array id122 nameone stuff responseobjectstuffarray array id213 nameanother stuff responseobjectstuffarray array id435 namewhatever stuff responseobjectstuffarray array id65 namecool stuff responseobjectstuffarray array id92 namewow what a stuff responseobjectresponsecode 1 responseobjectresponsemessage successful return responseobject whats the appropriate nusoap code for thatthanks i hope i could clarify what i would like to achieve returning a struct which contains an int a string and an array of structs but do not know how to write the appropriate nusoapcode for that this way i could firstly check the responsecode and handle it with the appropriate error messages or outputting the stuffarray etc,['php'] +181133,invoking windows task manager with performance tab selected i am currently invoking the windows task manager using a click event in wpf the event simply executes procestarttaskmgr my question is is there a way to choose which tab inside task manager is selected when the process starts is thisplayed i am looking to have the performance tab selected automatically whenever the click event is raisedthanks for the help,['c#'] +181161,select from nested select tsql i wish to modify data by selecting them in a inner query and count one of them modified it gives error select countcvs from select cvs case citycode when 123 then test else other end as cityname case productcode when 0 then test3 when ss then xtr else d end as cardname from applications,['sql'] +181164,avvideocompositioncoreanimationtool and calayer in portrait mode i am trying to backe a calayer into portraitmode video on export using an avmutablecomposition an avmutablevideocomposition and a avvideocompositioncoreanimationtool on ios 43 this all works in landscape if i capture video in portrait however the avvideocompositioncoreanimationtool is ignoring the transform on the video track that is for portraitmode video i am setting avmutablecompositiontrackpreferredtransform to the preferredtransform value from the original asset video track as long as i do not use a avvideocompositioncoreanimationtool this works and the video comes out in portrait mode as soon as i add a avvideocompositioncoreanimationtool and calayer however the file comes out in landscape the calayer appears correctly but the video behind it is on its side and the aspect ratio of the file is off i have tried applying the transform to the calayer and setting a transform in the acvideocomposition neither of these change the orientation of the file produced it is still 480x369 not 360x480 is there a way to render portraitmode video with avvideocompositioncoreanimationtoolfirst i set up a avmutablecomposition and avmutablevideocompositionavmutablecomposition composition avmutablecomposition compositionavmutablecompositiontrack compositionvideotrack composition addmutabletrackwithmediatypeavmediatypevideo preferredtrackidkcmpersistenttrackid invalidavurlasset videoasset avurlasset urlassetwithurlurl optionsnilcmtimerange timerange cmtimerangemakekcmtimezero videoasset durationavassettrack clipvideotrack videoasset trackswithmediatypeavmediatypevideo objectatindex0cgsize videosize cgsizeapplyaffinetransformclipvideotracknaturalsize clipvideotrackpreferredtransformvideosizewidth fabsvideosizewidthvideosizeheight fabsvideosizeheightcmtime titleduration cmtimemakewithseconds5 600cmtimerange titlerange cmtimerangemakekcmtimezero titledurationcompositionvideotrack inserttimerangetitlerange oftracknil attimekcmtimezero errornilcompositionvideotrack inserttimerangetimerange oftrackclipvideotrack attimetitleduration errornilcompositionvideotrackpreferredtransform clipvideotrackpreferredtransformavmutablevideocomposition videocomposition avmutablevideocomposition videocompositionavmutablevideocompositioninstruction passthroughinstruction avmutablevideocompositioninstruction videocompositioninstructionpassthroughinstructiontimerange cmtimerangemakekcmtimezero composition durationavassettrack videotrack composition trackswithmediatypeavmediatypevideo objectatindex0avmutablevideocompositionlayerinstruction passthroughlayer avmutablevideocompositionlayerinstruction videocompositionlayerinstructionwithassettrackvideotrack passthroughinstructionlayerinstructions nsarray arraywithobjectpassthroughlayervideocompositioninstructions nsarray arraywithobjectpassthroughinstruction videocompositionframeduration cmtimemake1 30 videocompositionrendersize videosizevideocompositionrenderscale 10and a calayer with a titlecalayer animationlayer calayer layeranimationlayerbounds cgrectmake0 0 videosizewidth videosizeheightcatextlayer titlelayer catextlayer layertitlelayerstring effect valueforkeytitletitlelayerfont effect valueforkeyfonttitlelayerfontsize 30titlelayeralignmentmode kcaalignmentcentertitlelayerbounds cgrectmake0 0 videosizewidth videosizeheight 6animationlayer addsublayertitlelayertitlelayeranchorpoint cgpointmake05 05titlelayerposition cgpointmakecgrectgetmidxlayerbounds cgrectgetmidylayerbounds cabasicanimation fadeanimation cabasicanimation animationwithkeypathopacityfadeanimationfromvalue nsnumber numberwithfloat10fadeanimationtovalue nsnumber numberwithfloat00fadeanimationadditive nofadeanimationremovedoncompletion nofadeanimationbegintime 35fadeanimationduration 10fadeanimationfillmode kcafillmodebothtitlelayer addanimationfadeanimation forkeynilfinally i add the calayer to the avmutablevideocomposition calayer parentlayer calayer layercalayer videolayer calayer layerparentlayerbounds cgrectmake0 0 videosizewidth videosizeheightparentlayeranchorpoint cgpointmake0 0parentlayerposition cgpointmake0 0videolayerbounds cgrectmake0 0 videosizewidth videosizeheightparentlayer addsublayervideolayervideolayeranchorpoint cgpointmake05 05videolayerposition cgpointmakecgrectgetmidxparentlayerbounds cgrectgetmidyparentlayerboundsparentlayer addsublayerlayer animationlayeranchorpoint cgpointmake05 05animationlayerposition cgpointmakecgrectgetmidxparentlayerbounds cgrectgetmidyparentlayerboundsvideocompositionanimationtool avvideocompositioncoreanimationtool videocompositioncoreanimationtoolwithpostprocessingasvideolayervideolayer inlayerparentlayerand exportavassetexportsession exportsession avassetexportsession alloc initwithassetcomposition presetnameavassetexportpresetmediumquality autoreleaseexportsessionvideocomposition videocomposition nsurl segmentfileurl some local urlexportsessionoutputfiletype comapplequicktimemovieexportsessionoutputurl segmentfileurlexportsession exportasynchronouslywithcompletionhandler switch exportsession status case avassetexportsessionstatusfailed logexport failed exportsession error break case avassetexportsessionstatuscancelled logexport canceled break case avassetexportsessionstatuscompleted logexport done break this code works in landscape mode and also in portrait if i remove the line videocompositionanimationtool avvideocompositioncoreanimationtool videocompositioncoreanimationtoolwithpostprocessingasvideolayervideolayer inlayerparentlayer,['ios'] +181174,convert to method group resharper i have written a method below like this internal static ilistempowertaxview getempowertaxviewsbylongagencyandagencytaxtypes ilistempowercompanytaxdata validempowercompanytaxdatas ilistempowertaxview empowertaxviews ilistempowertaxview result new listempowertaxview foreach empowercompanytaxdata empowercompanytaxdata in validempowercompanytaxdatas ilistempowertaxview validempowertaxviews getempowertaxviewsbylongagencyandtaxtype empowercompanytaxdata empowertaxviews validempowertaxviewstolistforeachdelegateempowertaxview etv resultaddetv return resultand for this method the resharper saysvalidempowertaxviewstolistforeachdelegateempowertaxview etv resultaddetv convert to method group what does this mean and what should be done to get rid of this,['c#'] +181196,how do i quit a mac application programmatically i need to add a quitbutton to my application that runs from the menubar in machow do i programmatically quit an application in mac,['objective-c'] +181204,how to pass a tablevalue parameter i am trying to pass a tablevalue parameter to a stored procedure but i keep getting an exception see belowsqlcommand c new sqlcommandgetpermittedusers myconn commandtype commandtypestoredprocedure cparametersaddwithvalueintnotifyinguserid notifyinguseridcparametersaddwithvaluetselectedpdfids sharedpdfssqldbtype sqldbtypestructuredsqldatareader dr cexecutereaderthe type is defined on the server like thiscreate type dboidlist as table id int not nulli have tried passing sharedpdfs as a listint and iqueryableint but keep getting the following exceptionobject must implement iconvertibleanyone know what i am doing wrong the documentation implies that i should be able to pass a list as a tvp but does not give any examplesthank you,"['c#', '.net']" +181216,using openmax il for audiovideo decoding on android many of the newer hardware platforms running android in particular nvidias tegra 2 support openmax for media acceleration it is effectively impossible on todays devices to decode 720p video without this support but the number of demuxers supported on android are quite slim the only public api i have been able to find has been through the mediaplayer class in the android sdk there are multiple places in the android source tree with openmax related tidbits howeveron my device samsung galaxy tab 101 i have got access to hardware decoders through a multitude of openmax libs in systemlib and it would be great to interface my video application with these can anyone point me to information on implementing a decoder powered by openmax i have found the documentation from khronos but nothing in the way of example code or tutorials i have already got demuxing and even software decoding taken care of via libavcodeclibavformat i would just like to put hooks in to enable hardware encoding i am also assuming here it would be necessary to link directly to the ones available on the device which makes it pretty lackluster in terms of portability but it worksalternatively i am interested in anything anyone knows about private apis for accessing the video decoding available on tegra 2 devices especially if there is a vdpau interface like what nvidia implements for desktop linux thistributions since there is plenty available for that but i was not able to find shared libraries that indicate that support,['android'] +181219,mobile redirect using screen resolution i advertise a company basicaly i am an affiliate i want to redirect my mobile viewers to the mobile version of my affiliate website i am thinking of doing this with screen resolution basicaly if the screen resolution is unde 800 x 600 chances are big the guest is using a mobile phoneis this a good ideeahere is the codeif screenwidth 800 screenheight 600 windowlocation mobilesite ty,"['javascript', 'jquery']" +181227,how do i get vim to autocomplete my jquery code i am using vim to write my jquery code is there a plugin that i can use to autocomplete parts of the codeediti fond this snippet for jquery javascriptjquery snippet,['jquery'] +181230,automatic sql query formulation from natural language input i am looking for an example application and a good research paper on automatic sql query formulation form natural language input for example i have a database on the population of various cities and the names of their states so is there a way through which if the user enters a question like city with highest population and automatically a sql query select maxpopulation from data is fired or if someone asks a more complex question like state with minimum population or is this not something that has been achieved already and is still being researched,['sql'] +181260,http to https redirection we have a website that can be accessed with both http and httpswe need all the pages to be accessed with http which is working fine but when users logged into the site we need all the pages that had authenticated need to thisplay with httpsplease let us know what is the easiest way to achieve thisthankssrinivas,['java'] +181282,debugging ios how do i break on property value change i am trying to find out how a uiviews transformation matrix is being modified thus using the gdb console i would like to watch for anyall changes of the uiviews transform property how would i go about doing so,"['objective-c', 'ios']" +181286,using rtti to determine inheritance graph in c what if any c constructs are there for listing the ancestors of a class at runtime basically i have a class which stores a pointer to any object including possibly a primitive type somewhat like boostany which i do not want to use because i need to retain ownership of my objects internally this pointer is a void but the goal of this class is to wrap the void with runtime typesafety the assignment operator is templated so at assignment time i take the typeid of the incoming pointer and store it then when i cast back later i can check the typeid of the cast type against the stored type info if it mismatches the cast will throw an exceptionbut there is a problem it seems i lose polymorphism let us say b is a base of d if i store a pointer to d in my class then the stored type info will also be of d then later on i might want to retrieve a b pointer if i use my clas method to cast to b then typeidb typeidd fails and the cast raises an exception even though db conversion is safe dynamic cast does not apply here since i am operating on a void and not an ancestor of b or d what i would like to be able to do is check is ancestortypeidb typeidd is this possible and is not this what dynamic cast is doing behind the scenesif not then i am thinking of taking a second approach anyway implement a a class typeinfo whose derived classes are templated singletons i can then store whatever information i like in these classes and then keep pointers to them in my anypointer class this would allow me to generatestore the ancestor information at compile time in a more accessible way so failing option 1 a builtin way of listing ancestors given only information available at runtime is there a constructprocedure i can use which will allow the ancestor information to be generated and stored automatically at compiletime preferably without having to explicitly input that class a derives from b and c c derives from d etc once i have this is there a safe way to actually perform that cast,['c++'] +181296,how to write text on image in objectivec ios i want to make an image like this programmaticallyi have the upper image and text with me should i write text on imagei want to make it a complete png imageimage label and set it as the background of the buttonplease provide any sample code or any suggestion for it,"['ios', 'iphone']" +181311,how to enable gzip compression in xampp server i am using xampp sever latest version to improve my web page performancei have to enable gzip in xampp how can it be done,['php'] +181324,iphone how to build an ipa file from selfmade app i programmed a small app for ios and i used mac os x 1066 xcode 325 and ios sdk 42 all running in a virtual box machine 40now i want the app to run on my iphone and to thistribute it to some beta testers because i am not a registered apple developer and i do not want to pay 99 to apple i need to find some other waythe first thing i found on the net is the tutorial of alex whittemorealexwhittemorecomi followed the instructions by creating a self sign root certificatebinary patching the xcode program and adding some scripts to the build process afterwards i switched to from debug to release mode and from simulator to device the buildprocess ends with a warningmessageapplication failed codesign verification the signature was invalid or it was not signed with an apple submission certificate 19011but i still have a appnameapp folder in the releaseiphoneosfolder which i can transfer via ssh or scp in the applicationsfolder of my jailbroken iphone afterwards i call uicache on the iphone and the app is shown in springboard i can also start the app and everything works finenow is the problem that i want an ipa file of my app as i read on the net an ipa file is nothing more than the appnameapp folder in a folder called payload zipped together with two files called itunesartwork and itunesmetadataplist i created the itunesartworks file out of an 512x512 jpeg image and the plist file from some preset i found on the net afterwards the appnamezip file has to be renamed to appnameipa i did this process manually and transfered the ipa file via scp to the downloadfolder of my installousapp on my iphone then i started installous and tried to install my app there comes the error messageinstallation failed invalid ipai did a search on the net for this error message and found something about updating my appsync and installousinstallation i updated both programs from the hackulousrepository but this did not helpso i thought that i did something wrong during the ipacreationprocess i did some research and found out that it is possible to drag and drop the appnameappfolder to itunes which automatically makes an ipa file of it then you can find the ipa file in some folder of itunes i copied this file to the download folder of installous on my iphone and tried to install this file again but the same error message is shownmy questionhow can i make a valid ipa file for installous if i have a selfsigned app does installous check the signaturemaybe someone has a hint for meediti found a solution for my problembecause i wanted more information on the installouserrormessage i installed syslog toggle and syslogd to varlogsyslog via cydia on my iphone to log detailed information to varlogsyslog then i tried to install the ipa file again and i got a message in the syslog from the installd daemon that the ipa file has a minimumiosversion requirement of 42 while my iphone is running under ios 40 installd163 005030 verify bundle metadata the system version is lower than the minimum os versioninteressingly there was no problem to install the app as system application by copying the appnameappfolder via ssh to applications but with the wrong minimumiosversionparameter build in so i rebuild my app with the right minimumiosversion for my iphonei tried to install again but again i got an error message about an invalid ipa this time the installd daemon tells me in the syslog of my iphone that it could not install an system applicationinstalld193 005030 preflight application install cannot install system or internal appsthis problem was easy to solve because i still had the app installed as system application in applications i just needed to delete the applicationsappnameapp folder and call uicache twice with the user mobile via ssh then i startet installous again and tried to install my ipa file et voila it workedmaybe i was able to help someone with a similar problem it seems to be a good idea to install the syslogapps via cydia to have a closer look for the error messages of installous if some generic error message like invalid ipa appearsps i was really irritated that my question was closed by the moderator just because someone thinks that my question is not generally applicable to the worldwide audience of the internet it is so stupid to close questions now you see i got a solution and i posted it here maybe it will help someone in the future you should not make the same fault as wikipedia by overcontrolling the user content,['iphone'] +181331,how can i allow django admin to set a field to null i have set my model field to nulltrue which allows null in mysql but i cannot seem to assign null to the field through django admin i have tried also setting blanktrue but that just sets the field to an empty string following this did not work either as the field value was set to none the stringany ideas,"['python', 'mysql', 'sql']" +181344,jquery mouseout on ipad i have a jquery code which works perfect on desktop browsersspancheckbox errmouseoutfunction spancheckbox errfadeoutslow but the same does not trigger on the ipad as a result the checkbox err is thisplayed on screen but never hideshow do i trigger the mouseout event on the ipad also i will want to avoid using any additional library just to fix this small issuei have a follow up questioni am testing a page on ipad and am facing some issues implementing an equivalent of mouseout behaviorso the issue is very simple to understand 1 on my page there is a checkbox on click or rather touch i want to show an errormsg 2 on clicktouch on anything other than the errormsg i want to hide the errormsgbelow is the code i have writtendocumentbindtouchstartfunctione ifetargetid checkbox err spancheckbox errfadeoutslow inputcheckboxbindtouchstartfunctionspancheckbox errfadeinfastnow the issue is when i clicktouch on the checkbox the errormsg shows for a while and then it also hides it immediately since target is not the errormsghow do i fix this issue,"['javascript', 'jquery', 'iphone']" +181346,aspnet mvc 3 how to do themes right i am looking for input on how to do themes in mvc 3 in the best way i guess a custom view engine is needed to take care of locating the view files etci also would like the theme system to be extensible so that if it is only one of the views i would like to change the others still use the default kind of like the orchard project doesa imagine a folder structure like themesdefaultviews etci have found a few mvc 10 and 20 examples but nothing that fits my needs exactly i need something that takes advantage of all the aspnet mvc 30 features and goodies of the razor view engine any input and ideas will really be appreciated christian,['asp.net'] +181353,scroll to tableviewheader using tableviewsectionforsectionindextitleatindex help i added a search bar into my tableviewcontrollers header and i have also added a search to the sectionindextitlesfortableview array now on the right side i got the letters of the alphabet the search symbol on the top to scroll to the sections of the letters not the search field i used this nsintegertableviewuitableview tableview sectionforsectionindextitlensstring title atindexnsintegerindex return index 1now when i click the letter a it scrolls to the section a and so on only i cannot make the search symbol scroll to the search bar in the tableviews headerhow can i do thisthank you in advance,"['iphone', 'ios']" +181377,is volatile bool for thread control considered wrong as a result of my answer to this question i started reading about the keyword volatile and what the consensus is regarding it i see there is a lot of information about it some old which seems wrong now and a lot new which says it has almost no place in multithreaded programming hence i would like to clarify a specific usage could not find an exact answer here on soi also want to point out i do understand the requirements for writing multithreaded code in general and why volatile is not solving things still i see code using volatile for thread control in code bases i work in further this is the only case i use the volatile keyword as all other shared resources are properly synchronizedsay we have a class likeclass someworkerpublic someworker isrunning false void start isrunning true spawns thread and calls run void stop isrunning false private void run while isrunning do something volatile bool isrunning for simplicity some things are left out but the essential thing is that an object is created which does something in a newly spawned thread checking a volatile boolean to know if it should stop this boolean value is set from another thread whenever it wants the worker to stopmy understanding has been that the reason to use volatile in this specific case is simply to avoid any optimization which would cache it in a register for the loop hence resulting in an infinite loop there is no need to properly synchronize things because the worker thread will eventually get the new valuei would like to understand if this is considered completely wrong and if the right approach is to use a synchronized variable is there a difference between compilerarchitecturecores maybe it is just a sloppy approach worth avoidingi would be happy if someone would clarify this thanksediti would be interested to see in code how you choose to solve this,['c++'] +181380,gradle how to configure multiproject setup with sidebyside projects we have an old project that is set up like thisa customizationprojectaa a a ejbaa a a servicesa projecta a a ejbaa a a shareda projectbaa a a ejba projectc a ejb a servicesthe idea is that the customizationproject is where the final assembly of the delivered application happends there might in fact be multiple customizationprojects and they might include multiple configurations that however is not the problem i am tyring to solvei want to make the customizationproject the logical root project of the gradle projectshow do i configure the individual projects so that theya know they are part of a multiproject buildb can be properly executed with different scopes eg just running the tests of one subproject while also allowing all tests to be executed accross all the projects,['java'] +181398,a example in gotw 67 there is a example in int main double x 1e8 float x 1e8 while x 0 x when you change the double to float it is a infinite loop in vs2008according to the gotw explanationwhat if float cannot exactly represent all integer values from 0 to 1e8 then the modified program will start counting down but will eventually reach a value and which cannot be represented and for which n1 and due to insufficient floatingpoint precision and then the loop will stay stuck on that value until the machine on which the program is running runs out of powerfrom what i understand the ie754 float is a single precision32 bits and the range of float should be 34e 38 and it should have a 7 digits significant but i still do not understand how exactly this happens eventually reach a value and which cannot be represented and for which n1 and due to insufficient floatingpoint precision can someone try to explan this bit a bit of extra info when i use double x 1e8 it finished in about 1 sec when i change it to float x 1e8 it runs much longerstill running after 5 min also if i change it to float x 1e7 it finished in about 1 secondmy testing environment is vs2008btw i am not asking the basic ie 754 format explanation as i already understand thatthanks,['c++'] +181407,could not render the url could not get image from urlnavigation timeout i have got a aspnet web application which contains the winnovative html to pdf converterthis has been running for over a year successfully generating pdfshowever this is no longer working and the error being returned iscould not render the url could not get image from urlnavigation timeouti have checked the winnovative faq and they suggest adding a navigationtimeout to the instance of the pdfconverter i have added the followingpdfconverternavigationtimeout 500however this has not fixed the error furthermore the page being converted only takes a fraction of a second to load when loading directly in the browser so i do not believe its a performance issue with the page being renderedhas anyone experienced this problem before are there any known solutionscauses for this,['asp.net'] +181417,generic interface with inverse relationship i want to create two interfaces with inverse relationships public interface item d extends description c extends categoryditemdc public c getcategory public void setcategoryc categoryi am not sure if expression c extends categoryditemdc is correct but at least there are no compiler errorspublic interface categoryd extends description i extends item public listi getitems public void setitemslisti itemsi extends item gives the warning item is a raw type references to itemdc should be parametrized i triedi extends itemdcategorydibut this results in the error bound mismatch the type categorydi is not a valid substitute for the bounded parameter c extends categoryditemdc of the type itemdc how to i parametrize the interface category correctly with generics,['java'] +181438,what the difference between eclipse 37 38 and 42 eclipse indigo is 37 and eclipse juno is 42 but 38m1 has just been released whats 38 and how is this different from 37 i am eagerly awaiting java 7 support and am confused whether i should use 38m1 or wait for 371,['java'] +181443,busy application leads to false not responding state on windows 7 wm update during long term operations our c win32 application shows a modal status dialog with a process bar which is updated irregular every few seconds or so starting with windows 7 we realized that windows quite soon shows a message seems to hang andor appends not responding to our window title bar we figured out that the process dialog must handle messages to avoid this more specifically it seems that windows 7 is constantly sending wm update messages to check if our program is alive we formerly had thisabled all unneeded message handling in this dialog as profile runs shows that they were a major slow downbut although we thought to have fixed that problem users are reporting such problems again windows shows seems to hang andor appends not responding to our window title bar although we handle all events every few secondsquestions is there any documentation about this change of behavior in windows 7 or windows vista we have not found any we also found a number of other changes of messaging behavioris there possibly a way to thisable all such is alive checks from windows our application is pretty well alive and processes can take quite longedit to be more specific what we only do each few seconds is calling the message pump peekmessagetranslatemessagethispatchmessage as this is a quite old legacy program using a separate worker thread is not possible in the near future we of course do that for new code please note also that my main point is that this behavior definitely changed with windows vista windows 7 i have not found any documentation thereabout,['c++'] +181465,jquery referencing outer scope within callback i have an issue with oo javascript and a jquery callbackif you look at the sample below it should explain everythinghow do i call functiontocall deep within this functceptionfunction outerclass thisfunctiontocall function do something thissomeotherfunction function thisacoupleofvariables1 2 thisacoupleofvariables2 stuff ajax success function how do i call functiontocall right here tried functiontocall thisfunctiontocall thatfunctiontocall,"['javascript', 'jquery']" +181468,iphoneios how do i tell what localization the phone is using at runtime i am having a difficult time localizing an app it needs to be localized into farsi iranian persian not only that it needs to use the solar calendar when fa ir is selected as a localizationthe os has a persian calendar it is no problem for me to use it but i need to know that the fa ir localization has been selected to add insult to injury i cannot test this locale in the us as it seems that att does not allow it as a localization i have to send it to iran which is a royal pitai am having the devil of a time finding out the localization at runtime there is a bunch of stuff for accessing the bundle flags but i cannot find anything for getting runtime infoi am pretty damn green at ios programming so i still need to determine which m to rtfm i have been searching the docs with many keywords to no availcan anyone help with what seems to be an absurdly easy question,"['iphone', 'ios']" +181472,how to do threading in javascript so i have a large json object i am returning from the server then building a datatable from it and thisplaying it on the form this usually takes a few seconds so i was thinking of a loading bar i have the logic behind the loading bar however the loop that builds the hmtl data is locking down the browser and i cannot call out to the element i need to update here is my function to do thisfunction builddatatabledb table container id var pb div idprogressbardiv container idhtmlpb pbprogressbar value 0 postpost location view all function data var headers var contents var jsonobject parsejsondata var tik mathroundjsonobjectlength 100 for key in jsonobject0 headers th keyreplace nbsp th for i in jsonobject contents tr for j in jsonobjecti contents td classborderright jsonobjectij td contents tr ifmathrounditik itik if i run the alert between popups i can see the progressbar update otherwise i see no update the progressbar appears empty then the container id element is updated with the table i have generated alert pbprogressbarvalueitik var html table cellpadding5 cellspacing0theadtr headers trtheadtbody contents tbodytable container idhtmlhtml container idchildrentablefirstdatatable bjqueryui true sscrollx 100,"['javascript', 'jquery']" +181486,are there cases where a typedef is absolutely necessary consider the following excerpt from the safe bool idiomtypedef void testablebool type constoperator bool type constis it possible to declare the conversion function without the typedef the following does not compileoperator void testable const const,['c++'] +181508,java source code parsersgenerators i need tools toconveniently parse java source code and easily access given elementseasily generate source code files to easily transform data structures into codeany good tips libraries frameworks tools thank you for help,['java'] +181537,detect all firefox versions in js hello how to detect firefox in javascriptthe problem is that i want to detect all versions of firefox,"['javascript', 'jquery']" +181560,uiwebview scrollto should behave smoothly i do not know if i asked correctly in question title but here i am going to describe in briefi have an uiwebview and loading the content based on div and each div has unique id on loadrequest as though my content was too large so i break down into pieces and loading the remaining content once you tap on read morethis read more event fire on autoscroll which i am handling through javascript so once that event is fired it just append data for which i have another method by using windowlocationhref div1div2its just an examplenow the main problem is when i scrolldown and wherver i get the read more message and it auto fire then it adds the data to the current div and show user feel its an continue reading but wheni scroll towards to up it behaves weired because it just append the data to the div and scroll to setyscrollupdatedlocationupdatedlocation is used for when we are adding the content to the div and it should scroll to the same position where the user wasso lets start with an example assume currently i am reading the div2 and when i scroll upread more events fired and add div1 to div2 and then web view delegate shouldstartloadwithrequest calledso every time its update the content to div2 when you are scrolling up but first it takes me the previous s location of div1 and then take me to div2 location where i was currently readingso it feel like really weired suddenly it takes me to somewhere for a while and take me to my current position within friction of second i tried with this solutioni thought to take the screen shot and create an imageview with that screenshot image of the current uiwebview and put on webview whenever read more event is happening once the web view loading is done remove the imageview and thisplay the webviewbut this is happening in the same way the problem is every thing is happening under the webview delegate i still could not figure out whats happening the solution of this problem am i on right trackj or is there any better solution for that,"['javascript', 'iphone', 'html']" +181600,trigger standard html5 validation form without using submit button anyone who know how i can trigger the standard html5 validation in a form without using a submit button javascript or jqueryi do not want to send postget request only do the validation,"['javascript', 'jquery']" +181605,css html5 position a at the bottom of the page no wrapper the ageold problem i need to position a footer element at the bottom of the page however i do not have a wrapper divi am do have the following stuctureabodyheadersection idcontentfooterbodyis there an easy way to push the footer to the bottom if the content is not high enough,"['html', 'css']" +181606,can multiple threads see writes on a direct mapped bytebuffer in java i am working on something that uses bytebuffers built from memorymapped files via filechannelmap as well as inmemory direct bytebuffers i am trying to understand the concurrency and memory model constraintsi have read all of the relevant javadoc and source for things like filechannel bytebuffer mappedbytebuffer etc it seems clear that a particular bytebuffer and relevant subclasses has a bunch of fields and the state is not protected from a memory model point of view so you must synchronize when modifying state of a particular bytebuffer if that buffer is used across threads common tricks include using a threadlocal to wrap the bytebuffer duplicate while synchronized to get a new instance pointing to the same mapped bytes etcgiven this scenariomanager has a mapped byte buffer b all for the entire file say it is 2gbmanager calls duplicate position limit and slice on b all to create a new smaller bytebuffer b 1 that a chunk of the file and gives this to thread t1manager does all the same stuff to create a bytebuffer b 2 pointing to the same mapped bytes and gives this to thread t2my question is can t1 write to b 1 and t2 write to b 2 concurrently and be guaranteed to see each others changes could t3 use b all to read those bytes and be guaranteed to see the changes from both t1 and t2i am aware that writes in a mapped file are not necessarily seen across processes unless you use force to instruct the os to write the pages down to thisk i do not care about that assume for this question that this jvm is the only process writing a single mapped filenote i am not looking for guesses i can make those quite well myself i would like references to something definitive about what is or is not guaranteed for memorymapped direct buffers or if you have actual experiences or negative test cases that could also serve as sufficient evidenceupdate i have done some tests with having multiple threads write to the same file in parallel and so far it seems those writes are immediately visible from other threads i am not sure if i can rely on that though,['java'] +181639,how to convert namevaluecollection to json string i tried namevaluecollection data new namevaluecollection dataaddfoobaa string json new javascriptserializerserializedatait returns foo i expected foo baa how do i to do this,"['c#', '.net', 'asp.net']" +181703,php json encode class private members i am trying to json encode some objects in php but i am facing a problem i want to encode data which is kept by a class private membersi found this piece of code to encode this object by calling an encode function likepublic function encodejson foreach this as key value jsonkey value return json encodejson however this only works if the object i want to encode does not contain other objects inside which is the case how can i do to encode not only the outer object but encode as well any members that are objects toothanks in advance,['php'] +181731,making ajax request in portlets for liferay 6 i want to make an ajax call inside my jsp file which calls processaction method of a portlet based on the success message from processaction method i need to make another call to serveresource method of portletplease provide some examples,['jquery'] +181737,how to show the android emulator without a keyboard i am using a virtual device whose target is 231 if i run any of my android applications the keyboard will show the right side on the emulator see the image below but i want to show my emulator without a keyboard how can i do this,['android'] +181745,how to find out if the current application is an aspnet web app from a managed class library i would like to find out whether the currently executing application is an aspnet web application web forms or mvc or noti have seen different approaches to do so eg by checking one of the followingsystemwebhostinghostingenvironmentishosted truesystemwebhttpcontextcurrent nullsystemwebhttpruntimeappdomainappid nullsystemwebhttpruntimecache nullchecking for a webconfig file note i do not think this is reliablethe question is which approach should i be using are some of them invalid ie might they return true even when running in a windows app or are all of them equalupdate clarification sorry if my question was not clear enoughi have a managed class library net code which is run by a net application obviouslythis host application can either be an aspnet application eg web forms or mvc or a windows application eg console or win formsmy question is is there a way to reliably determine from within my class library at runtime whether it is running as part of an aspnet applicationnote i know i could implement a different solution eg see comments below or tomas lyckens answer but that is not the point of this question the class library is already existing and i would like to change as little code as possible,"['.net', 'asp.net']" +181754,nsmanagedobjectcontext save does not crash but breaks on objc exception throw i am having the same issue described at this address i am debugging an application that uses core data with multithreading and i have a breakpoint on objc exception throw and it hits this breakpoint in the call to save line 2 in code nserror error nil selfmanagedobjectcontext saveerror if error nslogerror error i do not have any thing that is loggedi am using xcode 4 with ios 40 43 i think this is not related to xcodeios version,"['iphone', 'objective-c']" +181763,seelog which javascript function is being executed by the browser is there a wayaddon that i can use so everytime any javascript function is executed in firefox for example the function name will be printed to the console or where everthis is because i cannot find it is very hard to find which function is executed when i click on a drop downso i want firefoxaddon to tell me the name of every javascript function that is being executed,['javascript'] +181802,detecting full screen mode in windows i need detect if some application currently running in full screen mode if yes then i must stop my application so how i can detect that ps win32 c,['c++'] +181806,what is the optimal data structure for a pool container at the moment i use the stl vector container template to put back and get the connections1 on get a connection is returned and erased from pool vector2 on release the connection is handed back to the pool via push backthis might be very heavy if the pool is frequently used so my question is is there any way to improve the performance here by switching to an other data structure,['c++'] +181853,c keypress getch cinget i have a win32 program that runs on a loop i would like to be able to pause that program while awaiting a keypress it does not matter whether i use any key or a specific key but i need to have the program freeze until i press somethingi am wondering which command i should use i am working with visual c and the compiler does not recognise any of the following commandscingetstdcingetgetchi am relatively new to c i understand that in a console app this is a fairly simple action to take cinget but that it can be more difficult in win32 any simple solution or workaround would be appreciated the program is bespoke to be used in a single scientific experiment so for now i am not fussed if the solution is a little botchyapologies if i have missed any important info from my question,['c++'] +181866,android multiple option menus in one activity i have an activity containing a viewflipper and would like to show a different option menu for each view in that viewflipper that is the type of menu thisplayed when the menu button is pressed would depend on the type of the current view however oncreateoptionsmenu is called only once when showing the option menu for the first time so creating the different menus cannot be implemented there how could i solve thisany suggestions appreciated,['android'] +181882,code first entity framework change connection string how do i change the connection string in a code first entity frameworkmvc application i am trying to transfer it to a live site but it overlooks web config values and still references my local version of the databasehere is the connection string section of my webconfigadd namemembershipconnectionstring connectionstringdata source192168143initial catalogwebsitemodelsintranetapplicationuser idusernamepasswordpasswordtimeout30 add namewebsiteconnectionstring connectionstringdata source192168143initial catalogwebsitemodelsintranetapplicationuser idusernamepasswordpasswordtimeout30 add nameentities connectionstringmetadataresmodelsintranetmodelcsdlresmodelsintranetmodelssdlresmodelsintranetmodelmslprovidersystemdatasqlclientprovider connection stringquotdata source192168143initial catalogwebsitemodelsintranetapplicationuser idusernamepasswordpasswordmultipleactiveresultsetstruequot providernamesystemdataentityclient i am not sure if the entities string has any relevance as i used code first entity framework and i think that only appeared when i tried to create an edmx file although i ended up just deleting it the entities connection string has sat commented out so i do not think it is usedi want entity framework to read the websiteconnectionstring but it seems to want to use the local connection string but i cannot even see where that is set how do i change it,['c#'] +181895,thistributed celery scheduler i am looking for a thistributed cronlike framework for python and found celery however the docs says you have to ensure only a single scheduler is running for a schedule at a time otherwise you would end up with duplicate tasks celery is using celerybeatpersistentscheduler which store the schedule to a local fileso my question is there another implementation than the default that can put the schedule into the cluster and coordinate task execution so that each task is only run oncemy goal is to be able to run celerybeat with identical schedules on all hosts in the clusterthanks,['python'] +181898,apache stringutils vs java implementation of replace what would be the difference between java 142s implementation of replace and apache 23s implementation is there a performance gain one over anotherjava 142 replaceapache 23 replace,['java'] +181909,it puts strings together instead of adding them javascript var x epagexvar myx thishtmlvar difference myx xvar ex myx differenceeverything workes until the last row it doesna t make an addition it puts together the variables into one string if myx is 10 and difference is 20 it will be 1020 when i want it to be 30how do i solve this,['javascript'] +181926,please define define could someone give me some examples of how to use define in cdefine preprocessor directivewhat is the purpose of it here example from microsoft which i still do not get preprocessor ifcsdefine debugdefine mytestusing systempublic class myclass static void main if debug mytest consolewritelinedebug is definedelif debug mytest consolewritelinemytest is definedelif debug mytest consolewritelinedebug and mytest are definedelse consolewritelinedebug and mytest are not definedendif,['c#'] +181928,objective c categories and inheritance if a method is defined in both a class and a category on that class it is undefined which implementation will be calledbut how does this interact with inheritance specificallygiven a superclass category method and a regular method in the subclass is it guaranteed that the subclass implementation will win when called on a member of the subclassgiven a superclass regular method and a subclass category method trying to override it is it guaranteed that the subclass category implementation will win when called on a member of the subclassgiven a superclass category method and a subclass category method is it guaranteed that the subclass category method will win when called on a member of the subclass,"['iphone', 'objective-c', 'ios']" +181966,why is enumchildwindows skipping children i am getting strange behavior when it comes to using the windows api method enumchildwindows it seems to not be picking up a section of children windows when i drill down using spy i can see the children but when i execute my code it does not return the ones i see in spywhat i see in spyhere is my codepublic delegate bool enumwindowprocintptr hwnd intptr parameter dllimportuser32 return marshalasunmanagedtypebool public static extern bool enumchildwindowsintptr window enumwindowproc callback intptr i public static listintptr getchildwindowsintptr parent listintptr result new listintptr gchandle listhandle gchandleallocresult try enumwindowproc childproc new enumwindowprocenumwindow enumchildwindowsparent childproc gchandletointptrlisthandle finally if listhandleisallocated listhandlefree return result private static bool enumwindowintptr handle intptr pointer gchandle gch gchandlefromintptrpointer listintptr list gchtarget as listintptr if list null throw new invalidcastexceptiongchandle target could not be cast as listintptr listaddhandle return true is there a reason as to why the highlighted red section in the screenshot above would not get populated into my collection listintptr when calling enumchildwindows,['c#'] +181968,performance implications when hiding a div by rendering it offscreen what are the performance implications of hiding a complex portion of an html document within an offscreen div likediv stylepositionabsolutetop10pxleft10px lots of html heredivas compared to using thisplay none or visiblity hidden is there a performancememoryusage penalty how bad is itcan this be advisable if the targets are mobile browsers iphoneandroid,['html'] +181971,getting python to print in utf8 on windows xp with the console i would like to configure my console on windows xp to support utf8 and to have python detect that and work with itso far my attemptscdocuments and settingsphilippecpython25pythonexepython 252 r25260911 feb 21 2008 131145 msc v1310 32 bit intel on win32type help copyright credits or license for more information print uaa import sys sysstdoutencodingcp437 quitso by default i am in cp437 and python detects that just finecdocuments and settingsphilippechcp 65001active code page 65001cdocuments and settingsphilippepythonpython 252 r25260911 feb 21 2008 131145 msc v1310 32 bit intel on win32type help copyright credits or license for more information import sys sysstdoutencodingcp65001 print uacdocuments and settingsphilippeit seems like printing in utf8 makes python crash now,['python'] +181974,how to get parent product id in magento in ver 1420 i know you need to get parent ids like solist parentid magegetmodelcatalogproduct type configurable getparentidsbychild productgetid my question isif i do not know what the parent ishow do i know to use the catalogproduct type configurable vs catalogproduct type grouped model to get the id,['php'] +181978,nscachesdirectory not a directory in my file system i am trying to store something in my caches folder on my ipad app nsarray cachepatharray nssearchpathfordirectoriesindomainsnscachesdirectory nsuserdomainmask yes nsstring cachepath cachepatharray lastobjectand when i print out the returned filepath i get usersgelalibraryapplication supportiphone simulator50applications3ff7eb1a49a94b13adc4df0662ba724blibrarycacheshowever when i navigate to that folder on my hard drive caches is not a folder but a vague document file any ideas why it is not a folder and how i can write to my cache,"['iphone', 'ios', 'objective-c']" +181989,how to securely submit a high score in a front end game to prevent post hijacking given a client side game lets call it game x and a server side database that stores the high scores how can after the end condition of the game securely sumbit a high score to the server in a way that can only be done if the game was actually played thus to prevent post hijackinggiven this problem set here are a few ideas i have been thinking about upon the game start send a session id that expires after a given amount of time to be sent to the server for verification the problem is that this could be easily exploited by requesting the start id then just forging the score checkpoints within the game that post to the server to verify the person is actually playing the gameagain this could be synthesized with some crafty scripting,['javascript'] +181996,statistics and cardinality estimation why am i seeing this result i came across this little issue when trying to solve a more complex problem and have gotten to the end of my rope with trying to figure the optimizer out so let us say i have a table called mytable that can be defined like thiscreate table mytable groupclosuresid int identity11 not null siteid int not null deletedatetime datetime null constraint pk mytable primary key groupclosuresid siteidthis table has 286685 rows in it and running dbcc show statisticsmytablepk mytable will yieldname updated rows rows sampled steps density average key length string index filter expression unfiltered rows pk mytable aug 10 2011 100pm 286685 286685 18 0931986 8 no null 2866851 rows affectedall density average length columns 3743145e06 4 groupclosuresid3488149e06 8 groupclosuresid siteid2 rows affectedrange hi key range rows eq rows thistinct range rows avg range rows 1 0 8 0 1129 1002 7 127 7889764242 826 6 112 7375531 2010 6 288 6979167717 1108 5 185 5989189889 822 4 171 48070171401 2044 4 511 41763 1101 3 361 304986114207 24780 1 12443 199148181759 67071 1 67071 14457 31743 1 31743 17209 2047 1 2047 1179109 61439 1 61439 1181169 1535 1 1535 1229410 47615 1 47615 1235846 2047 1 2047 1275456 39442 1 39442 1275457 0 1 0 1now i run a query on this table with no additional indexes or statistics having been createdselect groupclosuresid from mytable where siteid 1397 and deletedatetime is nulltwo new statistics objects now appear one for the siteid column and the other for deletedatetime column here they are respectively note some nonrelevant information has been excludedname updated rows rows sampled steps density average key length string index filter expression unfiltered rows wa sys 02 7b0c223c aug 10 2011 115pm 286685 216605 200 003384706 4 no null 2866851 rows affectedall density average length columns 07380074 4 siteid1 rows affectedrange hi key range rows eq rows thistinct range rows avg range rows 1397 5942782 1600502 5 1183174name updated rows rows sampled steps density average key length string index filter expression unfiltered rows wa sys 06 7b0c223c aug 10 2011 115pm 286685 216605 201 07447883 08335911 no null 2866851 rows affectedall density average length columns 01065871 08335911 deletedatetime1 rows affectedrange hi key range rows eq rows thistinct range rows avg range rows null 0 255827 0 1the execution plan generated for the query i ran above gives me no surprises it consists of a simple clustered index scan with 142823 estimated rows and 15676 actual rows from what i have learned about statistics and cost estimation using the two histograms above we can multiply the selectivity of siteid 1600502 286685 times the selectivity of deletedatetime 255827 286685 to get a composite selectivity of 00498187307480119 multiplying that times the total number of rows 286685 gives us the exact same thing the optimizer did 142823but here is where i get confused i create an index with create index ix mytable on mytable siteid deletedatetime which creates its own statistics objectname updated rows rows sampled steps density average key length string index filter expression unfiltered rows ix mytable aug 10 2011 141pm 286685 286685 200 002749305 8822645 no null 2866851 rows affectedall density average length columns 07107321 4 siteid742611e05 4822645 siteid deletedatetime3488149e06 8822645 siteid deletedatetime groupclosuresid3 rows affectedrange hi key range rows eq rows thistinct range rows avg range rows 1397 504 15686 12 42when i run the same query as before select groupclosuresid from mytable where siteid 1397 and deletedatetime is null i still get 15676 rows returned but my estimated row count is now 18182 i have tried manipulating numbers to try and figure out where this estimation is coming from but i just cannot get it i have to assume it is related to the density values for ix mytableany help would be greatly appreciated thanksedit here is the execution plan for that last query execution,['sql'] +182021,excluding fields from embedded properties on case by case basis with hibernatejpa i am migrating some classes in a hibernate hbmxml file to jpa annotationswe have an embeddable class address that is used in several places each place uses a different subset of the properties in addressgetterssetters omitted for brevityembeddablepublic class address string email string address string city string state string zip string countryentitytablenamecustomerpublic class customer embedded attributeoverrides attributeoverridenameaddress columncolumnnameship addr attributeoverridenamecity columncolumnnameship city attributeoverridenamestate columncolumnnameship state attributeoverridenamezip columncolumnnameship zip attributeoverridenamecountry columncolumnnameship country address shippingaddress embedded attributeoverrides attributeoverridenameaddress columncolumnnamebill addr attributeoverridenamecity columncolumnnamebill city attributeoverridenamestate columncolumnnamebill state attributeoverridenamezip columncolumnnamebill zip address billingaddressnote that in this contrived example shippingaddress uses addresscountry but billingaddress does not and neither of them use addressemailthe problem is that hibernate is inferring column tags for any column where i have not explicitly provided onei tried adding transient to all the address fields but it appears that attributeoverride does not trump transientis there any workaround for this,['java'] +182030,compiling with clang using libc undefined references the first couple are too long to reference i get this error when i try to compile clang stdliblibc maincc with clang and libc from the svnerror undefined reference to typeinfo for char consterror undefined reference to cxa allocate exceptionerror undefined reference to cxa throwtmpccpbn00yomainccfunction std 1dequedouble std 1allocatordouble add back capacity error undefined reference to cxa begin catchtmpccpbn00yomainccfunction std 1dequedouble std 1allocatordouble add back capacity error undefined reference to cxa rethrowtmpccpbn00yomainccfunction std 1dequedouble std 1allocatordouble add back capacity error undefined reference to cxa end catchtmpccpbn00yoeh frame0xbd3 error undefined reference to gxx personality v0solution thanks to one of the answers i know the solution libc cannot be used by itself like libstdc it has to be linked along with libcabi however libcabi is not complete yet so using libc seems to be a little incomplete for the moment but it is still my first choice when it completesupdate 5262012 libcabi is now complete for c and i have been using clang as follows successfully clang stdc11 stdliblibc lcabi,['c++'] +182041,aspnet mvc validation using qtip jquery plugin i am using the solution found here to show client side validation errors in a tooltip using the qtip jquery plugin this solution works great for client side validation but i would love to able to thisplay server side validation errors in the same way does anyone know how to show server side validation errors in tooltips utilizing qtipthanks,['jquery'] +182062,php and codeigniter how do you check if a model exists andor not throw an error example 1bschaeffersanswer to this question in his last examplethisloadmodeltabledata thistablesome functhisloadviewview datahow do you handle this when table does not existexample 2 try thisloadmodelserve model name my model thismy modelmy fcnprams model exists catch exception e model does not exist but still after running this obvously the model does not exist but sometimes will it fails with the following erroran error was encounteredunable to locate the model you have specified serve formsi am getting this function call by1 getting some jsonmodel 1function namepram 11 pram 212 and turning it into the function callthisloadmodelserve model 1 my model3 where i callthismy modelfunction namepram 11 pram 21solutionthe problem lies in the fact that codeigniters show error function thisplays the error then exit not cool so i overrode model my model youll get errors if you just override it and removed the show error because for some reason you cannot override it weird for codeigniter then in my model made it throw an exceptionmy personal opinion the calling function should return show errormessage where show error returns false that or you could take out the exit and make show error overridable,['php'] +182067,get variables from a settingspy file in a jinja template with flask say i have settingspy file with a bunch of constants maybe more in the future how do i access those variables in a jinja template,['python'] +182157,how can i extract only the main textual content from an html page updateboilerpipe appears to work really well but i realized that i do not need only the main content because many pages do not have an article but only links with some short description to the entire texts this is common in news portals and i do not want to thiscard these shorts textso if an api does this get the different textual partsthe blocks splitting each one in some manner that differ from a single text all in only one text is not useful please reportthe questioni download some pages from random sites and now i want to analyze the textual content of the pagethe problem is that a web page have a lot of content like menus publicity banners etci want to try to exclude all that is not related with the content of the pagetaking this page as example i do not want the menus above neither the links in the footerimportant all pages are html and are pages from various differents sites i need suggestion of how to exclude these contents at moment i think in excluding content inside menu and banner classes from the html and consecutive words that looks like a proper name first capital letterthe solutions can be based in the the text contentwithout html tags or in the html content with the html tagsedit i want to do this inside my java code not an external application if this can be possiblei tried a way parsing the html content described in this question,"['java', 'html']" +182159,what is consuming over 65 of time in an aspnet application i have an net framework 40 aspnet aspnet mvc 3 web application hosted on a windows 7 iis 75 iis logging is enabled on this machine and set to log in w3c modethe application is compiled by using the release configuration and has been deployed to iis with compilation debugfalse attribute set explicitly the webconfig specifies the use of sql server based session statei have added the following statements in globalasax in beginrequest and endrequest events respectively the results ie swelapsedtotalmilliseconds are getting stored in an application level list of values i dump these values out via a debug page and get an average of the same in beginrequesthttpcontextcurrentitemsaddrequeststartend systemdiagnosticsstopwatchstartnew in endrequestvar sw systemdiagnosticsstopwatchhttpcontextcurrentitemsrequeststartendswstopi have created a load test which runs a single request against this application with a concurrent user load of 20 users the test is run in visual studio 2010 ultimate editionafter running the load test i am getting an average timetaken as recorded by the stopwatch as 681 millisecondsthe average timetaken as per iis for these requests i cleaned out all logs before running the load test is 2121 milliseconds the average timetaken as per iis tallys with the value shown in visual studio load test reportthe stopwatch timetaken only accounts for 32 of timetaken as reported by iis logs visual studio where does the other 68 time go update 1i set the session state to inproc and reran the load test in this scenario the difference between the average time reported by stopwatch and average timetaken reported by iis logs grew to more than 70 where is all that time going update 2peter i tried out the failed request tracing by putting a trace rule to log on status code of 200 next i ran the load test with 20 concurrent users for approx 15 minutes went through last 50 trace files and found that the time taken field in that report had range of 750ms to 1300ms the visual studio report showed avg time taken as 2300ms in the report using the compact view i see that the time taken changes between the following transitions 1 aspnetstart aspnetappdomainenter 2 managedpipelinehandlerstart managedpipelinehandlerend the 2 item is probably my applications code still there is a big difference between max of timetaken as per failed request logs ie 1300ms and the avg timetaken as shown by visual studio 2300ms how to find accounting for that thanks for this great tip though,['asp.net'] +182167,migration to change default value for a field and change all existing records value to new default value only if it has old default value i need to change the default value of a field from 0 to 3 but the catch is i have thousands of records already and want those records to change the value to 3 from 0 only if the record has default value 0 but for other values like 1 2 it should remain the same how can i do it,"['mysql', 'ruby-on-rails']" +182176,gmagick extension for php install how and where downloaded phppear and tried installing gmagick extension by following the steps given in link the pecl gave an error gmagick109b1 pecl install gmagickfailed to download peclgmagick within preferred state stable latest release is version 109b1 stability beta use channelpeclphpnetgmagick109b1 to installinstall failedtried adding the channel no result gmagick109b1 pecl channeladd error no version number found in tagchanneladd invalid channelxml filefound the link to download the php extension untard it to find the following files gmagick109b1 lsconfigm4 gmagickdraw methodsc gmagick methodsc license php gmagick helpersh readmegmagickc gmagick helpersc gmagickpixel methodsc php gmagickh php gmagick macroshtried configm4 only to find more errorsgmagick109b1 configm4 configm4 line 1 syntax error near unexpected token gmagickconfigm4 line 1 php arg withgmagick whether to enable the gmagick extensionbeen at this since a day with no resultread that gmagick is a swiss knife of image processingsad that there isnt much documentation done on it or at least a proper how to install link anywherebadly need helpthanks in advance,['php'] +182183,how to know when uitextview became first responder how to handle when uitextview became first responder i have text in text view and i want when the view became active want to clear the text how can i do that thanks in advance,['ios'] +182209,change android logcat font in eclipse i cannot seem to find the preference for changing the androids logcat debug output font in eclipse can it be changed at all how i do not mind editing some preference file somewhere by hand as long as it works,['android'] +182236,const field or get property whats the difference between the first and second definitions1private static string mask get return some text 2 private const string mask some text which benefits has the first and the second approach,['c#'] +182239,sqlcommand object what length of time for commandtimeout how do i decide what length of time to use as a timeout when using an sqlcommand objecton parts of the code i am working on written by somebody else i havecmdcommandtimeout 60which i think is quite short however i have seen some people in forums talking about setting it to 30 which seems too longhow do i know what is best for my application,['c#'] +182251,jquery open page in a tab and pass some post values how can i open in a new window a php page and pass in some post variablei am using jquerythank you,"['javascript', 'jquery']" +182265,uiview animation blocks vs caanimation ios animation experts what are the pros and cons of each method i know apple recommends blocks instead of the old uiview animation methods uiview beginanimations etc but what about caanimation when would you use one method vs the other is there a tradeoff in terms of performance,"['objective-c', 'ios']" +182300,using selenium2 how do i check if certain text exists on the page i am using the c selenium webdriver and i would like to confirm that certain text exists on the pagehow do i do this all the selectors seem to use ids classes etc i do not care where the text is on the page i just want to make sure it exists somewhere on the pageany thoughtsps i can do this using jquery and javascript but apparently that is not supported in all browser driversprotected bool textisonthepagestring texttofind var javascriptexecutor ijavascriptexecutor driver bool textfound converttobooleanjavascriptexecutorexecutescriptstringformatreturn contains0length 0 texttofind return textfound,['c#'] +182308,why is not getselecteditem on jcombobox generic jcombobox in java 7 has been updated to use generics i always thought it was a bit of an oversight that it did not already so i was pleased to see this changehowever when attempting to use jcombobox in this way i realised that the methods i expected to use these generic types still just return objectwhy on earth is this it seems like a silly design decision to me i realise the underlying listmodel has a generic getelementat method so i will use that instead but it is a bit of a roundabout way of doing something that appears like it could have been changed on jcombobox itself,['java'] +182312,whats char const argv i am studying linux c programing when i seeint execveconst char path char const argv char const envpi do not understand what is char const argv i know char const foo is a const pointer to char and const char foo is a pointer to a const char but whats char const argvis it an array of const pointers to char or an array of pointers to const charand i have a vectorstring now how to convert it to char const argv,['c++'] +182323,reconstructget code of php function can i programmatically get a code of function by it is namelikefunction blaha b return ab echo getfunctioncodeblahis it possible are there any php selfdescriptive functions to reconstruct functionclass code mean instead of getting source code right from sources filein java there exists in phpget class methodstypeofreflectionfunction thanks alin purcaru,['php'] +182324,jquery detect no action for x minutes and run function on that event no event in x minutes how to detect that user have done nothing for x minute and run function on this eventegif no action from user for x minutes do stuff any suggestion much appreciated,['jquery'] +182330,what is the difference between long long and long int i know the difference between long and int but what is the difference between long long and long int,"['c++', 'c']" +182340,how to do a like considering two columns i have a customer table with two columns first name and last namehow can i use like in a query being able to get data from both columns at same tamefor instanceselect concatfirst name last name as full name from customer where full name like john di have tried this and it tells me full name column does not exist,"['mysql', 'sql']" +182357,android 30 calendarview i am trying to implement a calendarview it takes an absurd amount of time about 10 seconds to appear on screen and it only loads the month and weekday headers it does not thisplay any calendar contentusing the same code from this video but not seeing the same result i am trying to launch it in a dialogcalendarview calendarview new calendarviewthisdialogsetcontentviewcalendarviewbut when i tried to embed it in an activity it took the screen the same amount of time to load and similarly failed to thisplay correctly,['android'] +182381,why a procedure is so much faster when put into a function here is what i did i created 2 procedures one in a function and one in the python file itself the one on the python file itself run almost 2 times slower even if it is exactly the same why bellow is an example with 2 procedures that are just loops on p elementi have the following python file from time import p10 range of the 2 loopsdef loopn for k in rangen continuestarttimelooppstop1timefor k in rangep continuestop2timeprint time with function stop1startprint time without function stop2stop1here is what i get i tried it with one thousand samples and the result is the following time with function 00950286102time without function 015706485with xrange instead of range i get time with function 0046038147time without function 01079843597so it is like 005 second in used to build the list i know it is may be a useless question but if someone know why is this going so much faster i would be happy to know,['python'] +182384,ios get location of a view in a window i have a uiview that thisplays a popup after it is been clickedthe popup needs to be added to the main uiwindow to make sure that it goes on top of everything elsei want the position of this popup to be relative to my uiview so i need to know the relative location of my uiview in the windowquestion how can i find the location of a uiview in a uiwindow when the uiview is not directly in the uiwindow it is inside the view of my viewcontroller,"['iphone', 'objective-c', 'ios']" +182387,ignore milliseconds when comparing two datetimes this is probably a dumb question but i cannot seem to figure it out i am comparing the lastwritetime of two files however it is always failing because the file i downloaded off the net always has milliseconds set at 0 and my original file has an actual value is there a simple way to ignore the milliseconds when comparingheres my functioncompare files datespublic bool comparebymodifieddatestring strorigfile string strdownloadedfile datetime dtorig filegetlastwritetimestrorigfile datetime dtnew filegetlastwritetimestrdownloadedfile if dtorig dtnew return true else return falsethanks in advance,['c#'] +182394,valid lists inside lists ul inside ul i need lists inside listswhats the most valid wayul li ul lih2titleh2li lielementli lielementli ul li li ul lih2titleh2li lielementli lielementli ul liwould that be valid and semantic,['html'] +182396,redirecting to ftp url with username and password in safari i have got a problem with safari i have not been able to solvephp headerlocation ftpusernamesomefilezipthis codesnippet works in every browser fx chrome ie79 but not in the latest safari which tells me that i do not have permission to view the page that is it redirects to the correct page somedomainorg with the correct protocol but does not process the authentication datainterestingly it works when i copy it directly to the address bar or when i put in in an atag an click on it is this a safari bug or am i missing something here which the other browsers ignore and if it is a safari bug is there some kind of workaround,['php'] +182432,datatables with json ajax and php not thisplaying any data i have been trying to get datatables to work with my existing ajax search function which works by itselfi have the following code searchresultsdatatable bprocessing true bserverside true bretrieve true sajaxsource processphpactionsearchartifact fnserverdata function ssource aodata fncallback aodatapush name searchname value artifactsearchattrvalue ajax datatype json type post url ssource data aodata success fncallback the php is returning a valid json object using json force object0artifact id4e2fe3bce356cartifact name123artifact typeuiartifact labeltest int eas 123artifact locationintartifact domainabcartifact authornullregistered emailregistered date27072011registered time110900i can see this all fine in firebug but my empty table is not being populated with this dataany ideaskyle er thats it i guess i do not have one this is my first attempt struggle with datatables and i am just copying from the documentation marcb added that but still no data thisplayed thanks for the help,['php'] +182447,linux perf how to interpret and find hotspots i tried out linux perf utility today and am having trouble in interpreting its results i am used to valgrinds callgrind which is of course a totally different approach to the sampling based method of perfwhat i didperf record g p pidof someaperf report g nnow i see something like this 1692 kdevelop libsqlite3so086 0x3fe57 a 1061 kdevelop libqtguiso473 0x81e344 a 709 kdevelop libc214so 0x85804 a 496 kdevelop libqtguiso473 0x265b69 a 350 kdevelop libqtcoreso473 0x18608d a 268 kdevelop libc214so memcpy a 115 kdevelop kernelkallsyms k copy user generic string a 090 kdevelop libqtguiso473 qtransformtranslatedouble double a 088 kdevelop libc214so libc malloc a 085 kdevelop libc214so memcpy ok these functions might be slow but how do i find out where they are getting called from as all these hotspots lie in external libraries i see no way to optimize my code basically i am looking for some kind of callgraph annotated with accumulated cost where my functions have a higher inclusive sampling cost than the library functions i callis this possible with perf if so hownote i found out that e unwraps the callgraph and gives somewhat more information but the callgraph is often not deep enough andor terminates randomly without giving information about how much info was spent where example 1026 kate libkatepartinterfacesso460 katetextloaderreadlineint katetextloaderreadlineint int katetextbufferloadqstring const bool bool katebufferopenfileqstring const katedocumentopenfile 0x7fe37a81121ccould it be an issue that i am running on 64 bit see also i am not using fedora but seems to apply to all 64bit systems,['c++'] +182460,architectural question as a result of a previous post architecture simple cqs i have been thinking how i could build a simple system that is flexible enough to be extended later in other words i do not see the need for a fullblown cqrs now but i want it to be easy to evolve to it later if neededso i was thinking to separate commanding from querying but both based on the same database the query part would be easy a wcf data service based on views to that it is easy to query for data nothing special therethe command part is something more difficult and heres an idea commands are of course executed in an asynchronous way so they do not return a result but my aspnet mvc sites controllers often need feedback from a command for example if a registration of a member succeeded or not so if the controller sends a command it also generates a transaction id a guid that is passed together with the command properties the command service receives this command puts it into a transactions table in the database with state processing and is executed using d principles after execution the transactions table is updated so that state becomes completed or failed and other more detailed information like the primary key that was generatedmeanwhile the site is using the queryservice to poll for the state of this transaction until it receives completed or failed and then it can continue its work based on this result if the transactions table is polled and the result was completed or failed the entry is deleteda side effect is that i do not need guids as keys for my entities which is a good thing for performance and sizein most cases this polling mechanism is probably not needed but is possible if needed and the interfaces are designed with cqs in mind so open for the futuredo you think of any flaws in this approach other ideas or suggestionsthankslud,"['c#', '.net']" +182468,is it better to use classisenum or instanceof enum i have an object i want to check to see if it is of type enum there are two ways to do thisobjectgetclassisenumorobject instanceof enumis one better,['java'] +182474,what is the difference between arraylistclear and arraylistremoveall assuming that arraylist is defined as arrayliststring arraylist is arraylistremoveallarraylist equivalent to arraylistclearif so can i assume that the clear method is more efficient for emptying the array listare there any caveats in using arraylistremoveallarraylist instead of arraylistclear,['java'] +182480,what happens to an awaiting thread in c async ctp i have been reading about the new async await keyword and it sounds awesome but there is one key question i have not been able to find the answer for in any of the intro videos i have watched so far i also read the whitepaper a while backsuppose i have a call to await in a nested function on the main ui thread what happens to the thread at this point does control go back to the message loop and the ui thread is free to process other inputswhen the awaited task completes does the entire stack get pushed onto a message queue such that control will return through each of those nested functions or is something else entirely happening hereand secondly while i have your attention i do not really understand why asynchronous methods need to be labeled with async cannot any method be executed asynchronously what if i want to execute a method asynchronously but it does not have an async keywordis there a way to do that simplycheers editadmittedly if i could get the sample code compiling i could probably just figure that out myself but for one reason or another i am running into a block there what i really want to know is to what extent does a continuation continue does it freeze the entire call stack to resume it when the task completes or does it only go back so far does a function itself need to be marked as async in order to support continuation or as i asked originally does it continue the entire call stackif it does not freeze the entire call stack what happens when the async await hits a nonasync calling function does it block there wouldnt that defeat the point of await i hope you can see that i am missing some understanding here that i hope someone can fill in so i can continue to learn this,"['c#', '.net']" +182485,how to do mobile analytics using jquery mobile i am looking for a good solution to do mobile analytics for jquery mobile i did check this question flurry analytics vs google analytics on the mobile platformbut these are all solutions for a platform specific phone manufacturer specific but jquery mobile works on all platforms irrespective of the manufacturer or operating system essentially i am looking for a analytics solution for webapps additional infobango seems expensive at 49month admob wont work since we dont need it for advertising and not for placing ads,['jquery'] +182489,javascript insert an array inside another array what is the more efficient way to insert an array inside another array a1 12345a2 2122newarray a1insertat2a2 12 2122 345iterating a2 using splice looks a bit awfull from a performance point of view if a2 array is largethanks,['javascript'] +182493,onclick blocks copypaste on mobile safari background i have a dropdown menu that basically works the same as the one described on this other mobile safari event issue question click a menu item to thisplay the dropdown either click the menu item again or click anywhere else on the page to hide the menu the jquery that hides the dropdown is bound to the click event of a parent div spanning the entire window this dropdown works aok in all browsers including mobile safari and i am only describing it here for the sake of contextthe problem this onclick event prevents users on mobile safari tested on an ipod touch 421 and ipad 435 from getting the normal touchandhold copy paste popup anywhere on our site doh based on my research it seems that if an html element has a click handler defined its contained content would not be copyablei have set up a strippeddown demo here update i am using straight javascript in this demo to illustrate that it is not a jquery issue but this fails to work with jquerys click as well if you open that link in mobile safari you should not be able to copy the lorem ipsum text but you will get a message via consolelog when you click on the text to prove that the click handler is firingheres the gist of it in case that link goes downdiv idcontentimagine a large block of text heredivscript documentgetelementbyidcontentonclick function consolelogyou just clicked me scriptthings i have tried webkituserselect text as described hereusing onmouseup and other events instead of onclick nope moving the onclick to the body tag or to the window objectfigure 64 in the ios handling events documentation is relevant but did not lead me to any great revelations about what to doany thoughts is this the way it is supposed to work or am i missing something is there a way to make this text selectable yet still fire the click handler or maybe i should go back to the drawing board for how to best hide the dropdown menu so that i avoid this issue entirely,"['javascript', 'jquery', 'iphone', 'ios']" +182500,why does pythons urllib2urlopen raise an httperror for successful status codes according to the urllib2 documentation because the default handlers handle redirects codes in the 300 range and codes in the 100299 range indicate success you will usually only see error codes in the 400599 rangeand yet the following coderequest urllib2requesturl data headersresponse urllib2urlopenrequestraises an httperror with code 201 createderror 20110811 204017318 init py463 http error 201 createdso why is urllib2 throwing httperrors on this successful requestit is not too much of a pain i can easily extend the code totry request urllib2requesturl data headers response urllib2urlopenrequestexcept httperror e if ecode 201 success else fail else when will this happenbut this does not seem like the intended behavior based on the documentation and the fact that i cannot find similar questions about this odd behavior also what should the else block be expecting if successful status codes are all interpreted as httperrors then when does urllib2urlopen just return a normal filelike response object like all the urllib2 documentation refers to,['python'] +182518,jquery date picker zindex issue i have a slideshow div and i have a datepicker field above that divwhen i click in the datepicker field the datepicker panel show behind slideshow divand i have put the script asso i cannot change the zindex of datepicker in css the zindex of datepicker which the script is generating is 1 and my slideshow divalso calling thru googleajaxapi zindex is 5 so i guess i have to increase the zindex of date picker greater than 5 so is there any way to increase it someone can help me,['jquery'] +182520,why does not jquery expose its uuid functionality underneath the hood jquery uses a map of uuids just a counter it maintains as jqueryuuid to work around the wellknown memory leak issues browsers have when you attach a property to a tag in the dom from javascript in lieu of doing so jquery uses the datatag name value to store data in a map keyed off of the uuid a key that can be determined by checking tagjqueryexpandowhile data is very useful there are times you want to map data to tags without dumping that data into one global bucket you want your own smaller bucket of data that you can for example check the length of or loop throughas a contrived example suppose you have icons that rotate through one of 4 states when clicked when one is in state 2 you want to add it to an array of icons in state 2 the most obvious way to do so is to add the tag to an array however doing so would create a memory leak you could call data on the checkbox but that does not quite accomplish what youre trying to do youd have to loop through all the checkboxes checking data against them to figure out which are and are not in the listyou need to store some abstraction of the tags in an array and that is jquerys uuids you could write your own uuid functionality but ideally you just leverage the uuid functionality already builtin to jquery for both codesize and quality reasons you could ask jquery to attach a uuid to the tag implicitly by calling datatag irrelevant 1 and then check tagjqueryexpando to get its uuid and finally use that in the list but that is a bit of a hack really what would be ideal is to have the following exposed in the public apigetuuidtag checks for and creates a uuid if none exists ideally the method is factored out of data and creates or fetches the uuid for the tag passed inso is there a reason this is not factored out into its own method in jquery is this harmful in some way was it just never something that seemed usefuli should note that i have actually factored it out in the version of jquery were using and it is very helpful but perhaps there is an underlying risk i am not hitting in my usage i am also aware of a plugin that sortof accomplishes this but it is a bit broken and having 2 codepaths to perform the same uuid functionality is both a bit wasteful and a bit brittle,['jquery'] +182527,lightweight java socket library i have used mina and netty but now i am in the market for a lightweight library that may also be used in android i prefer nio or asyncio over standard io implementations update 1the lack of responses really makes me think i should write my own library right now i am using raw nio and its not a lot of fun,['java'] +182543,how can i determine if a uisearchthisplaycontrollers searchresultstableview is visible i have a uisearchthisplaycontroller that is in the headerview for my uitableview i want to know when the uisearchthisplaycontrollers searchresultstableview is shown so i can do some other operationifselftableview selfsearchthisplaycontrollersearchresultstableviewreturns true all the time even when the searchresultstableview is shown how can i figure this out,"['iphone', 'objective-c']" +182560,how to generate gaussian pseudo random numbers in c for a given mean and variance i have a code here which generates random numbers having a mean 0f 1 and std deviation of 05 but how do i modify this code so that i can denerate gaussian random numbers of any given mean and varianceinclude stdlibhinclude mathhifndef m pidefine m pi 314159265358979323846endifdouble drand uniform thistribution 01 return rand10rand max10double random normal normal thistribution centered on 0 std dev 1 return sqrt2logdrand cos2m pidrandint main int i double rands10 for i0 i10 i randsi 10 05random normal return 0,['c'] +182566,does br tag posseses height i know that br is used to create linebreaks i am just wondering if it also creates space between lines please consider these examplephello br stackoverflow brbrbr pthe output looks likehellostackoverflowby putting more and more br i found thistance between lines increase is it because of br but when i try to control br height in css it does not follow it seems like it has no height at all just a linebreak if br is not the cause of the space between line then which is which and how to control it in css also i usually use br to create large thistance between lines i do that to replace nr or the like when the data is from the database is that okay,['html'] +182567,what does a correct call to cgimagecreate look like if the data provider for it uses an array created by the app i am trying to create a bitmap in memory as part of a pattern function that a drawlayerincontext method this method is part of the calayer delegate protocol will call the pattern function looks similar to thisstatic const size t kcomponentsperpixel 4static const size t kbitspercomponent sizeofunsigned char 8nsinteger layerheight 160nsinteger layerwidth 160cgcontextsavegstatecontext cgcolorspaceref rgb cgcolorspacecreatedevicergbsize t bufferlength layerwidth layerheight kcomponentsperpixelunsigned char buffer mallocbufferlength the real function does something more interesting with the buffer but i cut it to reduce the complexity while i figure out the crashfor nsinteger i 0 i bufferlength i bufferi 255memsetbuffer 255 bufferlengthcgdataproviderref provider cgdataprovidercreatewithdatanull buffer bufferlength nullfreebitmapbuffercgimageref imageref cgimagecreatelayerwidth layerheight kbitspercomponent kbitspercomponent kcomponentsperpixel kcomponentsperpixel layerwidth rgb kcgbitmapbyteorderdefault kcgimagealphalast provider null false kcgrenderingintentdefaultcgcontextdrawimagecontext cgrectmake0 0 160 160 imagerefcgimagereleaseimagerefcgdataproviderreleaseprovidercgcolorspacereleasergb cgcontextrestoregstatecontextlater when drawlayerincontext calls cgcontextfillrect to thisplay the pattern created by this function i get exc bad access the top of the stack is cgsconvertalphabyte i looked at the buffers memory at that point and it seemed fine set to exactly what it was set to when the pattern function was calledi think that maybe i messed up some parameter of cgimagecreate quite possibly the flags or the buffer is not populated in the right order but i am not sure how i can go wrong if i fill every byte with the same valueany ideas or examples of similar code that is noncrashing,"['objective-c', 'ios']" +182570,get itunes artwork for current song with scriptingbridge i have been trying to figure out how to get the itunes artwork for the currently playing song with scripting bridge i have gotten to a point where it works for some songs but for others i get a sigabrt i am not sure what the issue could be so any help would be greatly appreciated here is what i have so faritunesapplication itunes sbapplication applicationwithbundleidentifiercomappleitunesnsimage songartworkitunestrack current itunes currenttrackitunesartwork artwork itunesartwork current artworks get lastobjectifartwork nil songartwork artwork dataelse songartwork nsimage imagenamedimagetiffnsmenuitem artworkmenuitem nsmenuitem alloc initwithtitle actionnull keyequivalentsongartwork setsizensmakesize128 128artworkmenuitem setimagesongartworkmenu insertitemartworkmenuitem atindex0i for some songs it works and thisplays the artwork nicely in the menu item but for others i get a sigabrt on the linesongartwork setsizensmakesize128 128the output of the console is as follows20110812 231320094 songviewer2146707 nsappleeventdescriptor setsize unrecognized selector sent to instance 0x102827f7020110812 231320095 songviewer2146707 an uncaught exception was raised20110812 231320096 songviewer2146707 nsappleeventdescriptor setsize unrecognized selector sent to instance 0x102827f7020110812 231320097 songviewer2146707 0 corefoundation 0x07f86f11986 exceptionpreprocess 1981 libobjcadylib 0x07f8b04cd5e objc exception throw 432 corefoundation 0x07f86f9d5ae nsobject doesnotrecognizeselector 1903 corefoundation 0x07f86efe803 forwarding 3714 corefoundation 0x07f86efe618 cf forwarding prep 0 2325 songviewer 0x0102a83 ipmenulet awakefromnib 44836 corefoundation 0x07f86f089e1 nsobject performselector 497 corefoundation 0x07f86f08962 nsset makeobjectsperformselector 2748 appkit 0x07f8d9d9c27 nsibobjectdata nibinstantiatewithownertoplevelobjects 12459 appkit 0x07f8d9d01b9 loadnib 32210 appkit 0x07f8d9cf6b6 nsbundlensnibloading loadnibfilenametablewithzoneownerbundle 21711 appkit 0x07f8d9cf5d1 nsbundlensnibloading loadnibfileexternalnametablewithzone 14112 appkit 0x07f8d9cf514 nsbundlensnibloading loadnibnamedowner 36413 appkit 0x07f8dc42355 nsapplicationmain 39814 songviewer 0x0101882 main 3415 songviewer 0x0101854 start 5220110812 231320098 songviewer2146707 terminating app due to uncaught exception nsinvalidargumentexception reason nsappleeventdescriptor setsize unrecognized selector sent to instance 0x102827f70 first throw call stack0 corefoundation 0x07f86f11986 exceptionpreprocess 1981 libobjcadylib 0x07f8b04cd5e objc exception throw 432 corefoundation 0x07f86f9d5ae nsobject doesnotrecognizeselector 1903 corefoundation 0x07f86efe803 forwarding 3714 corefoundation 0x07f86efe618 cf forwarding prep 0 2325 songviewer 0x0102a83 ipmenulet awakefromnib 44836 corefoundation 0x07f86f089e1 nsobject performselector 497 corefoundation 0x07f86f08962 nsset makeobjectsperformselector 2748 appkit 0x07f8d9d9c27 nsibobjectdata nibinstantiatewithownertoplevelobjects 12459 appkit 0x07f8d9d01b9 loadnib 32210 appkit 0x07f8d9cf6b6 nsbundlensnibloading loadnibfilenametablewithzoneownerbundle 21711 appkit 0x07f8d9cf5d1 nsbundlensnibloading loadnibfileexternalnametablewithzone 14112 appkit 0x07f8d9cf514 nsbundlensnibloading loadnibnamedowner 36413 appkit 0x07f8dc42355 nsapplicationmain 39814 songviewer 0x0101882 main 3415 songviewer 0x0101854 start 52terminate called throwing an exceptiongdb if anyone has any idea what could be wrong please let me know,['objective-c'] +182574,how can i verify image uri is valid in android i am building my own contact picker because i needed multiselect support everything is working fine except for one small problem with the contact images for contacts who do not have images i am showing a no image image this works fine for contacts in the phones address book i am having a problem however when it comes to images from my google contactsmost of my google contacts do not have photos however when i query the contacts database for photos it still returns a uri for them of the form of contentcomandroidcontactscontacts657photo which is the same format as for contacts who do have a photo then when i try to assign the photo to a quickcontactbadge using bdgsetimageuripic it sets it to essentially a blank picture and logs a silent info message stating infosystemout3968 resolveuri failed on bad bitmap uri contentcomandroidcontactscontacts657photoi need to know how i can eithera validate the uri orb catch the info message abovec query the imageviewbadge to see if it found a valid imageso that i can assign these contacts my no image imagehow can i go about doing thisedit 201108120044i have tried adding this to my code as per laurences suggestion which he is since removed rv is my uri variableifrv null drawable d drawablecreatefrompathrvtostring if d null rv nullwhile the google contacts now get my no image image so do all the other contacts including ones that do in fact have images,['android'] +182589,i want to fetch and view sms conversations contentresolver cr getcontentresolvercursor cur crqueryuriparsecontentsmsconversations nullnullnull null is not working whyusespermission androidnameandroidpermissionread sms permissions have been added0812 105639188 errorandroidruntime377 caused by androiddatabasesqlitesqliteexception near syntax error while compiling select body as snippet from sms select thread id as group thread id maxdateas group datecount as msg count from sms group by thread id as groups where smsthread id groupsgroup thread id and smsdate groupsgroup date0812 105639188 errorandroidruntime377 at androiddatabasedatabaseutilsreadexceptionfromparceldatabaseutilsjava1430812 105639188 errorandroidruntime377 at androiddatabasedatabaseutilsreadexceptionfromparceldatabaseutilsjava10812 105639188 errorandroidruntime377 at androidcontentcontentproviderproxybulkquerycontentprovidernativejava2790812 105639188 errorandroidruntime377 at androidcontentcontentproviderproxyquerycontentprovidernativejava2980812 105639188 errorandroidruntime377 at androidcontentcontentresolverquerycontentresolverjava1520812 105639188 errorandroidruntime377 at comgetmessagesgetconversationsfetchdatadoinbackgroundgetconversationsjava330812 105639188 errorandroidruntime377 at comgetmessagesgetconversationsfetchdatadoinbackgroundgetconversationsjava10812 105639188 errorandroidruntime377 at androidosasynctask2callasynctaskjava1850812 105639188 errorandroidruntime377 at javautilconcurrentfuturetasksyncinnerrunfuturetaskjava256,['android'] +182590,python passing flags to functions for a long time i have been trying to figure out what is the best way to pass flags to python functions the most straightforward way is something likedef funcdata flag1 flag2 flag3 funcmy data true false truethis is really nice and concise but incredibly hard to read since the word true or false tells you nothing about what flag is being set and you have to carefully count the arguments starting from the left you can make them keyword argumentsdef funcdata flag1false flag2false flag3false funcmy data flag1true flag3truebut this is kind of redundant since the true does not carry any meaning at all i could pass it as a listfuncmydata flag1 flag3or funcmydata funcflag1 funcflag3but the first feels rather dirty using strings as flags and the second is still somewhat repetitive ideally i want to say something likefuncmy data flag1 flag3to pass flags to a function with minimal verbosity and redundancy is there any way to do something like this in pythonediti ended up going withfuncmydata flaga1 flagb1mostly for the reasons mentioned compiletime checking versus passing in strings no namespace pollution as opposed to using global enums and minimal boilerplate 1 or 0 is only 2 characters vs 5 or 6 for true or false it also makes setting default values for the flags very easydef funcdata flaga1 flagb0 flagc1 which is far more clear and far more easy than jumping through hoops to extract and assign defaults to kwargstyle flags the flags are basically statically checked and very clearclean to write now if only i could shave off the last two characters,['python'] +182602,arc and bridged cast with arc i can no longer cast cgcolorref to id i learned that i need to do a bridged cast according clang docsa bridged cast is a cstyle cast annotated with one of three keywords bridge t op casts the operand to the destination type t if t is a retainable object pointer type then op must have a nonretainable pointer type if t is a nonretainable pointer type then op must have a retainable object pointer type otherwise the cast is illformed there is no transfer of ownership and arc inserts no retain operations bridge retained t op casts the operand which must have retainable object pointer type to the destination type which must be a nonretainable pointer type arc retains the value subject to the usual optimizations on local values and the recipient is responsible for balancing that 1 bridge transfer t op casts the operand which must have nonretainable pointer type to the destination type which must be a retainable object pointer type arc will release the value at the end of the enclosing fullexpression subject to the usual optimizations on local valuesthese casts are required in order to transfer objects in and out of arc control see the rationale in the section on conversion of retainable object pointersusing a bridge retained or bridge transfer cast purely to convince arc to emit an unbalanced retain or release respectively is poor formin what kind of situations would i use eachfor example cagradientlayer has a colors property which accepts an array of cgcolorrefs my guess is that i should use brige here but exactly why i should or should not is unclear,['objective-c'] +182615,difference between querynum rows and thisdbcount all results in codeigniter which one is recommended in a scenario i need to know the count of recordset a query will return which in codeigniter can be done by querynum rows or thisdbcount all results which one is better and what is the difference between these two,['php'] +182617,thoughts on using expressjs instead of ruby on sinatra i am working on a social app and considering using expressjsnodejs instead of my original choice sinatrarubyi am mostly worried about the of open source projects available in ruby to help get things done quickly the second major concern is the stabilitymaturity and completeness of expressjsany feedback comments are welcome,"['javascript', 'ruby']" +182635,how to create a video preview in android i have a video file in my sdcard i would like to show a preview of this video in my imageview please let me know how to do this in android thank you for your help and time,['android'] +182645,how to write a generic method for adding numbers i want to define a method to make sums betweendifferent type numberst void add t one t two t res one two the above method not work because type erasure convert t into objectand thus the operator is not defined on objecthow can do thatthanks,['java'] +182648,stop video in uiwebview in my ipad app i have a modal view uiviewcontroller with modal presentation style uimodalpresentationpagesheetinside the view is a uiwebview with a html page and an embedded youtubevideo if i start the video and close the view the video does not stop the audio continues and you can see a small play icon next to the battery icon in the status barhow can i stop the videothanks,"['iphone', 'objective-c']" +182657,how to find city temperature by longitude and latitude in android how to find city temperature by longitude and latitudedoes anyone know of a service with an api or a widget that i could use to thisplay weather based on geographical coordinates,['android'] +182661,tools and techniques for effective use of feature toggles in net i have read a lot about feature toggles but have no practical experience of using them what tools and techniques do people recommend for effective management of feature togglesi imagine the simplest way would be to store toggles as truefalse values in the webconfig file as appsettings but this does not sound a particularly good methodideally i would like any method of managing feature toggles toflag any uses of the toggle on removal eg a compilation errorhighlight any old toggles ie a toggle that is still in place after the feature has been released,['.net'] +182673,how to make alignment on console in php i am trying to run a script through command prompt in php and trying to show the result in tabular form but due to different character length of words i am not able to show the result properly aligni want result like thisbook isbn departmentoperating system 101 csc 102 csjava 103 cscan anyone please help me to get this output like this in php on consolethanks in advance,['php'] +182681,this application does not exist app idx i was unable to upload to an appengine as appcfg was telling me this application does not exist app iduxi was only a developer on the appengine so as i was just testing i created a new appengine where i was the owner but i still get the same message on a newly created appengine,['python'] +182693,multiple fileextensions searchpattern for systemiodirectorygetfiles what is the syntax for setting multiple fileextensions as searchpattern on directorygetfiles for example filtering out files with aspx and ascx extensions todo set the string searchpattern to only get files with the extension aspx and ascxvar filteredfiles directorygetfilespath searchpatternupdate linq is not an option it has to be a searchpattern passed into getfiles as specified in the question,"['c#', '.net']" +182697,meaning of path attribute on handlers in webconfig i am looking at iis75 configuration systemwebserverhandlersdo you know what is the diference between and in the path argument for handlerscould you use file to match filetxt and filexml or abcac to match abcabc and abcasc can the path argument make reference to the folder like f4txtgiven a http request like get f1f2f3f4abcarg1arg2arg33arg4txt14what is the part the path argument tries to match,['asp.net'] +182716,sql insert into with select and inner join hey guys i hope you can help me with this little problemi am not quite sure of how to explain the situation to you so ill just give it a trywhat i am trying to do is the followingi want to insert some specific values and parameters which i type in myself into the table rfc risks so basically every time i find a specific reason inside the table rcf risks i want to write a new row that updates the priority of the rfc every time that happens the position shall be increased by 1my problem is now that when i run this statement i just get the select part not inserting is done neither do i get a sql statement error or anything like that i just type in the parameters and then i get a select table thats alli am using ms access 2010 and i hope you can help me out with my little problem insert into rfc risks rfc no riskpos datum comments riskprio reasonselect rfc risksrfc no rfc risksriskpos 1 as riskpos aktuelles datum as datum kommentartext as comments neue prio as riskprio rfc risksreason from rfc risks inner join risk reasons on rfc risksreason risk reasonsreasontext where rfc risksreason risk reasonsreasontext,['sql'] +182726,reload specific uitableview cell in ios i have a uitableview i want to update the table data based on selection made right now i use mytable reloaddata i want to know if there is any way where i can just update the particular cell which is selected can i modify by using nsindexpath or others any suggestionsthanks,"['iphone', 'ios']" +182733,get the current url of cocoas webview im new to cocoai am trying to extract the url of the currently loaded webpage in my webview objecti use this webview to show a login screen and after logging in i have to get some parts of the urli have already triedframe provisionaldatasource request url absolutestringbut this one only works one time when called while loading if the loading is complete it returns null the problem is that it seems like the url changes while loading the page so i get the wrong urldoes anybody know how to get the url at any time i wantthanks,['objective-c'] +182770,linq except with custom iequalitycomparer i am trying to find the difference between two generic lists as in the example below even though t1 and t2 contain the same properties they are not the same object so i have need to implement an iequalitycomparerthis appears to be working with this example but the real class has several other properties and i also need to do the same with a few other claso i was wondering if i am reinventing the wheelis there an easier method of comparing all the properties of two objects at the moment i really only need to cope with class containing simple types but it would be nice i have a comparer that worked with classes that contains instances of other classesvoid main var t1 new sizes name test size 1 var t2 new sizes name test size 1 var list1 new listsizes var list2 new listsizes list1addt1 list2addt2 var differences list2exceptlist1 new sizescomparer differences should be emptypublic class sizes public string name get set public int size get set public class sizescomparer iequalitycomparersizes bool iequalitycomparersizesequalssizes x sizes y return xnameequalsyname xsizeequalsysize int iequalitycomparersizesgethashcodesizes obj if objectreferenceequalsobj null return 0 return objnamegethashcode objsize,['c#'] +182774,plotting directly to movie with numpy and mencoder so this should be a comment to this thread but it is apparently closed so here it goes i have been playing around quite successfully with matplotlib and numpy and mencoder as has been suggested around here i have since adopted voki codder buffer to stdin solution which speeds the whole process up considerably the thing is i could not find any documentation on the formatbgra part of the command this means that the bytes are from right to left blue green red alpha right do they have to be uint32 or something else the problem is i am plotting colormaps of floats so i am trying to convert them to grayscale but i am getting lots of weird patterns which make me strongly believe i am doing something wrong i wrote this function to convert from floats to uint32 within a range but the result is not why i expected am i doing something terribly stupiddef grayscalex min max return npuint32xminmaxmin0xf,['python'] +182780,nodejs error cannot set headers after they are sent i am fairly new to nodejs and i am having some issuesi am using nodejs 410 and express 243when i try to access i will be redirected to callbacki than received the following errorerror cannot render headers after they are sent to the client at serverresponseanonymous httpjs57311 at serverresponse renderheaders homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectlibpatchjs6425 at serverresponsewritehead httpjs81320 at homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectauthlibauthstrategiesfacebookjs2815 at homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectauthlibindexjs11313 at next homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectauthlibstrategyexecutorjs4539 at object objectpass homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectauthlibauthexecutionscopejs323 at object objecthalt homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectauthlibauthexecutionscopejs298 at object objectredirect homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectauthlibauthexecutionscopejs168 at object objectanonymous homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectauthlibauthstrategiesfacebookjs7715error cannot set headers after they are sent at serverresponseanonymous httpjs52711 at serverresponsesetheader homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectlibpatchjs5020 at next homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectlibhttpjs16213 at next homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectlibhttpjs19511 at next homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectlibhttpjs15023 at param homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectlibmiddlewarerouterjs18913 at pass homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectlibmiddlewarerouterjs19110 at objectrouter as handle homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectlibmiddlewarerouterjs1976 at next homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectlibhttpjs19815 at objectauth as handle homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectauthlibindexjs1537error cannot set headers after they are sent at serverresponseanonymous httpjs52711 at serverresponsesetheader homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectlibpatchjs5020 at next homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectlibhttpjs16213 at next homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectlibhttpjs2079 at next homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectlibhttpjs15023 at param homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectlibmiddlewarerouterjs18913 at pass homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectlibmiddlewarerouterjs19110 at objectrouter as handle homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectlibmiddlewarerouterjs1976 at next homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectlibhttpjs19815 at objectauth as handle homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectauthlibindexjs1537error cannot set headers after they are sent at serverresponseanonymous httpjs52711 at serverresponsesetheader homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectlibpatchjs5020 at next homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectlibhttpjs16213 at next homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectlibhttpjs15023 at next homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectlibhttpjs2079 at objectauth as handle homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectauthlibindexjs1537 at next homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectlibhttpjs19815 at httpserverhandle homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectlibhttpjs2113 at objecthandle homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectlibhttpjs10514 at next homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectlibhttpjs19815error cannot set headers after they are sent at serverresponseanonymous httpjs52711 at serverresponsesetheader homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectlibpatchjs5020 at next homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectlibhttpjs16213 at next homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectlibhttpjs15023 at next homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectlibhttpjs2079 at httpserverhandle homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectlibhttpjs2113 at objecthandle homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectlibhttpjs10514 at next homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectlibhttpjs19815 at homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectlibmiddlewaresessionjs3239 at homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectlibmiddlewaresessionjs3389nodejs134 throw e processnexttick error or error event on first tick error cannot set headers after they are sent at serverresponseanonymous httpjs52711 at serverresponsesetheader homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectlibpatchjs5020 at next homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectlibhttpjs16213 at next homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectlibhttpjs2079 at homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectlibmiddlewaresessionjs3239 at homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectlibmiddlewaresessionjs3389 at arrayanonymous homeeugenepublic htmlall things nodeprojectsfb2node modulesconnectlibmiddlewaresessionmemoryjs577 at eventemitter tickcallback nodejs12626the following is my codevar fbid xvar fbsecret xvar fbcallbackaddress callbackvar cookiesecret node enter a random hash for securityvar express requireexpressvar auth requireconnectauthvar app expresscreateserverappconfigurefunction appuseexpressbodyparser appuseexpressmethodoverride appuseexpresscookieparser appuseexpresessionsecret cookiesecret appuseauth authfacebook appid fbid appsecret fbsecret callback fbcallbackaddress scope offline accessemailuser about meuser activitiesmanage pagespublish stream faileduri noauth appuseapprouterappgetauthfacebook functionreq res reqauthenticatefacebook functionerror authenticated if authenticated resredirectgreat consolelogok cool consolelogresreqsession appgetnoauth functionreq res consolelogauthentication failed ressendauthentication failedappgetgreat function req res ressendsupercoolstuffapplisten8may i know what is wrong with my codei am really new to this so sorry for just putting up the code herethank you all in advance,['javascript'] +182784,rails using cached applicationcss despite changes i have a rails 31 application that uses sass the applicationcscss file looks likeimport resetcssimport 960cssimport pagesmastercscssi have a watchr script that touches applicationcscss whenever one of the imported files is changedfor a while this setup worked fine ever since last week and i am not sure why rails has been pulling a cached version of applicationcss for the webpages despite all my attempts at restarting the app retouching applicationcscss etc i have also deleted sasscache to no effectany ideas,['ruby-on-rails'] +182807,sql table inheritance causing duplicate records in base table even though primary key constraint is set i have a problem where lets say i have a people table that is inherited by a student table and a teacher table if i do an insert into student and an insert into teacher and specify the primary key of the people table p id for exampleinsert into studentp id lastname firstname studentnumbervalues 1 jones casey sid01insert into teacherp id lastname firstname facultynumbervalues 1 jones casey jones01i wind up with two duplicate records in my people table p id is my primary key on the people table it appears that the subtables are doing the inserts into the people table without considering the constraints on that table should not the primary key constraint on the people table prevent duplicate records from being createdi have thought about resolving this issue using a trigger that will fire before an insert is made on the people table witch would check for a p id that already exists but i would like for it to either prevent me from doing such things or i would like it to intelligently create a record in the subtable onlyafter doing this would there be an issue with changing the lastname for example in the student table and having the changes reflect onto the teacher tablehere are the create statements the above insert statements were only to give an example i understand they will not work with these tables that are createdcreate table peoplepeople id integer not nulast name character varying not nullfirst name character varying not nullmiddle name character varyinggender character varying not nulldate of birth datessn character varyingpref language character varyingconstraint people pkey primary key people idcreate table student inherited from table people people id integer not null inherited from table people last name character varying not null inherited from table people first name character varying not null inherited from table people middle name character varying inherited from table people gender character varying not null inherited from table people date of birth date inherited from table people ssn character varying inherited from table people pref language character varyingstudent id integer not nullrace character varying80ethnicity character varying80employer character varying80school character varying80pref location character varying80constraint student pkey primary key student idinherits peoplecreate table teacher inherited from table people people id integer not null inherited from table people last name character varying not null inherited from table people first name character varying not null inherited from table people middle name character varying inherited from table people gender character varying not null inherited from table people date of birth date inherited from table people ssn character varying inherited from table people pref language character varyingteacher id integer not nulluser name character varying not nullpassword character varying not nulltitle character varyingconstraint teacher pkey primary key teacher idinherits people,['sql'] +182824,simple thread problem i started learning java and i am now at the concurrency chapter after reading some stuff about concurrency i tried an example of my ownpublic class task implements runnablepublic void run whilethreadinterrupted try systemoutprintlntask timeunitsecondssleep2 catch interruptedexception e systemoutprintlninterrupted public static void mainstring args throws exception executorservice exec executorsnewcachedthreadpool execexecutenew task timeunitsecondssleep10 execshutdownnowthe problem is that i was expecting to see the following outputtasktasktasktasktaskinterruptedbut after i get this the program continues printing until i close itso my question is what am i doing wrong why does the program continues printing,['java'] +182832,jsf 2 how show different ajax status in same input i would like to validate every field in my form when each field lose the focus when this happens i would like these actions happen1 in the right side of the field appears an image a gif to represent that the system is checking the user input2 when finished appears another gif which depends of the input sucessgif or errorgif for example and a message on the right sidei do not want to use popup or something like the user is gonna lose usability and i do not want thisi am trying to do something like this this is what i have done so farhform idform hpanelgrid columns3 houtputlabel forfirst name valuefirst name hinputtext idfirst name valueregisterbeanfirstname fajax eventblur renderm first name hinputtext a4jstatus nameajaxstatus ffacet namestart hgraphicimage nameloadergif libraryimages houtputtext valueprocessing ffacet a4jstatus a4jcommandbutton valueregister actionregistervalidatename statusajaxstatus hpanelgridhformi was searching for some solution on google and i think aa4j is my best option because of the onbegin and oncomplete attributesthere is some attribute as these in some native tag in jsf 2 updatebalusc approachdoctype htmlhtml langptbr xmlns xmlnsf xmlnsh xmlnsui hhead titleinsert title heretitle script typetextjavascript function showprogressdata var inputelement datasource the html dom input element var ajaxstatus datastatus can be begin success and complete var messageforinputelement documentgetelementbyidinputelementid message switch ajaxstatus case begin this is called right before ajax request is been sent messageforinputelementinnerhtml validating break case complete this is called right after ajax response is received messageforinputelementinnerhtml break case success this is called when ajax response is successfully processed if messageforinputelementinnerhtmllength 0 so no message has been set messageforinputelementinnerhtml valid break script hhead hbody hform idform hpanelgrid columns3 houtputlabel forfirst name valuefirst name hinputtext idfirst name valuebeanfirstname requiredtrue fajax eventblur renderfirst name message oneventshowprogress hinputtext hmessage idfirst name message forfirst name hpanelgroup hcommandbutton valuesubmit actionregisterdosomething fajax executeform renderform hcommandbutton hmessages globalonlytrue layouttable hpanelgrid hform hbodyhtmland this is my beanmanagebeanviewscopepublic void dosomething try threadsleep20 catch interruptedexception e eprintstacktrace,['java'] +182833,if delegates are immutable why can i do things like x y reading c in depth 2nd edition section 212 on combining and removing delegatesthe subsection title states that delegates are immutable and that nothing about them can be changed in the next paragraph though it talks about using constructs likex ywhere x and y are variables of compatible delegate typesdid not i just change x or does the immutability part deal with when x is thisposed of when i do this ie immediately,['c#'] +182852,error with rounding extension on decimal cannot be accessed with an instance reference qualify it with a type name instead i have used extension methods numerous times and have not run into this issue anyone have any ideas why this is throwing an error summary rounds the specified value summary param namevaluethe valueparam param namedecimalsthe decimalsparam returnsreturns public static decimal round this decimal value int decimals return mathroundvalue decimals usagedecimal newamount decimalparse3434343434thisrtbamounttext newamountround3tostringnewamountround3 is throwing the compiler errorerror 1 member decimalrounddecimal cannot be accessed with an instance reference qualify it with a type name instead,"['c#', '.net']" +182860,drawable vs single reusable bitmap better with memory as i understand it not that i am correct drawables are generally correctly removed from memory when the application is finished with them bitmaps however need to be manually recycled and sometimes even have a special class written to handle them properly my question is in regards to memory and leaks is it more beneficial to simply stick with drawables like suchmyviewsetbackgrounddrawablegetresourcesgetdrawablerdrawablemy imagemyview1setbackgrounddrawablegetresourcesgetdrawablerdrawablemy image1myview2setbackgrounddrawablegetresourcesgetdrawablerdrawablemy image2rather than something like so with bitmapsbitmap tmpbitmap bitmapfactorydecoderesourcegetresources rdrawablemy imagemyviewsetimagebitmaptmpbitmaptmpbitmaprecycletmpbitmap bitmapfactorydecoderesourcegetresources rdrawablemy image1myview1setimagebitmaptmpbitmaptmpbitmaprecycletmpbitmap bitmapfactorydecoderesourcegetresources rdrawablemy image2myview2setimagebitmaptmpbitmaptmpbitmaprecyclei have also read of course that you have to be careful about recycle method on bitmaps because they can be removed while still in use it seems like these issues keep popping up in different forms but i cannot really get a straight answer from anyone on the matter one person says to reuse a bitmap and recycle after every use and others say use drawables and an unbinddrawables method this is what i have been using private void unbinddrawablesview view if viewgetbackground null viewgetbackgroundsetcallbacknull if view instanceof viewgroup for int i 0 i viewgroup viewgetchildcount i unbinddrawablesviewgroup viewgetchildati viewgroup viewremoveallviews any applicable insight would be much appreciated though thanks,['android'] +182863,android new thread runnable executes in main thread i am trying to create a new thread in the oncreate of an activity but instead of creating a new thread and executing the runnables code in it the runnable code is executing in the main thread of my program a new thread never seems to be createdthe oncreate codeoverrideprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmonster layout runningmonsterviewactivity this threadcurrentthreadsetnamemain thread logvtag oncreate has run thread genthread new threadnew testrunnable genthreadrunthe runnable code import androidoshandlerimport androidutillogpublic class testrunnable implements runnablestring tag testrunnable public testrunnable mainthreadhandler h override public void run forint i0 i 10 i logvtag new integeritostring try threadsleep10 catch interruptedexception e todo autogenerated catch block eprintstacktrace the stack trace i got when i paused the code when it was executingdalvikvmlocalhost8621 suspended thread 1 main thread suspended vmthreadsleeplong int line not available native method threadsleeplong int line 1306 threadsleeplong line 1286 testrunnablerun line 18 threadrun line 1096 monsterviewactivityoncreatebundle line 49 instrumentationcallactivityoncreateactivity bundle line 1047 activitythreadperformlaunchactivityactivitythreadactivityrecord intent line 2627 activitythreadhandlelaunchactivityactivitythreadactivityrecord intent line 2679 activitythreadaccess2300activitythread activitythreadactivityrecord intent line 125 activitythreadhhandlemessagemessage line 2033 activitythreadhhandlerthispatchmessagemessage line 99 looperloop line 123 activitythreadmainstring line 4627 methodinvokenativeobject object class class class int boolean line not available native method methodinvokeobject object line 521 zygoteinitmethodandargscallerrun line 868 zygoteinitmainstring line 626 nativestartmainstring line not available native method thread 6 binder thread 2 suspended thread 5 binder thread 1 suspended daemon system thread 3 signal catcher suspended daemon system thread 2 heapworker suspended,"['java', 'android']" +182869,prevent children from inheriting transformation css3 i have a div that i am tranforming scale and translate but inside that div i have another div now i would to see that the inner div isnt affected by the transformation of its parent in other words i would like for the inner div to not scale like his parent does here is the htmldiv idrightsection div classtopdiv div classmiddle div classlarge img srcassetsimagesrightpanel expandedpng altmap titlemap div div div classbottom pcheck if your friends are goingp divdivhere is my cssrightsectionhover moztransformscale21628 translate80px53px webkittransformscale21628 translate80px53px otransformscale21628 translate80px53px mstransformscale21628 translate80px53px transformscale21628 translate80px53pxso the problem is when i scale rightsection the img gets scaled to but i would like to keep the image on its original sizeany help is appreciated,['css'] +182872,when an object is returned from a method is a new instance or a reference created possible duplicatedo methods which return reference types return references or cloned copy a coworker of mine stated that when a method returns an object like the following a new instancecopy of the object is created as opposed to passing back a reference public customerentity customer get set public customerentity getcustomer customer new customerentity return customer is that correct my tests seem to indicate otherwise but i am not certain how to confirm this he is concerned about the overhead in copying data to the new object for good measure in which of the following methodsscenarios are new objects created in which situations does the calling class access a reference to or a copy of the to the original object assume the customerentity is a very large objectpublic class custman public customerentity getcustomer customer new customerentity return customerpublic void fillcustomercustomerentity customer customer new customerentity calling class customerentity ce new customerentity l custmanfillcustomerce writelinecename public void loadcustomer customer new customerentity calling class access customerentity via l custmancustomerentityclarification my coworker believes it would be better to use a load method than a get methodl custmanloadcustomerentity l custmancustomervs customerentity l custmangetcustomer,"['c#', '.net']" +182892,nodejs or envjs dynamic jquery tmpl my current task is to generate and provide centralized templates for a particular dom for this example let us just say it is a form basically i would like to take each form element from the labels to the inputs to the div wrappers and save them as individual templates from there we will have a ui where our producers can piece together these forms once they decide how they want their form to be layed out dom order and structure is actually critical for this project it can not be a cssonly solution a script on our platform side will save a json object which will determine the structure of the dom based on template names which i can reference on page load later on i am thinking that an ideal solution here would be to send that json object to a node server or use envjs somehow to build this dom and then assign it to a php variable to be included in the codeigniter view so it can be indexed by google i know jquery works natively with envjs and i know there is a jquery plugin for node but alas this is my first serverside js project and it happens to be pretty major i was able to get envjs working on my local machine through the command line but it takes a good 1030 seconds to complete a simple task if envjs is the way to go how can i keep it running in the background and have scripts reference it php curl to an envjs servlet on tomcat maybeone caveat is my local dev is wamp it would not let us have local unix machines but our test and production environments are both lamp i do have a personal lamp server i can test on if that is the absoluteonly way to go here but coding company stuff on my personal server can get me in some heatunfortunately i do not have time to research all the possibilities and tryfail as i normally would with new technologies on my own time ideas guidance code examples anything that can help me decide how to approach this would be greatly appreciated,['jquery'] +182917,https request with boostasio and openssl i am trying to read the ticker symbol at from my c application i use boostasio and openssl because the service requires httpsboost version 1470openssl 100d 8 feb 2011 win32for the application i took the example from 47 0dochtmlboost asioexamplesslclientcppto get started and modified it as followsthis is where i want to connect toboostasioiptcpresolverquery querymtgoxcom 443i set verification to none because the handshake fails otherwise i am not sure if this is a problem with mtgox or that this implementation is really strict because when i print the certificate to the screen it looks legit and chrome has no problem with it when visiting the ticker pagesocket set verify modeboostasiosslcontextverify nonethis is the request i sendstdstringstream request request get api0datatickerphp http11rnrequest host mtgoxcomrnrequest acceptencoding rnrequest rnboostasioasync writesocket boostasiobufferrequest str boostbindclienthandle write this boostasioplaceholderserror boostasioplaceholdersbytes transferredfull code i run into the following errorconnection okverifyingcilostartcom ltdousecure digital certificate signingcnstartcom certification authoritysending request get api0datatickerphp http 11host mtgoxcomacceptencoding sending request okread failed an existing connection was forcibly closed by the remote hostam i going in the right direction with this the error message is not really descriptive of the problem and i do not know which step i did wrongthanks in advanceupdate i used curl to see what went wrongcurl traceascii outtxt full output it fails during verificationwhen i connect with the unsafe parametercurl traceascii outtxt k full output everything works fine fixi fixed the typo in the http headers i added a root certificate andturned ssl verification back on,['c++'] +182939,building a serverclient application in cocoa i built a fairly simple program that watches a folder manipulates files as they are added and gives a simple progress view of whats going on the folder is watched via a subclass of nsoperation that passes information in an nsdictionary to my progress view via the nsnotificationcenter now i need to break things up and run the watched folderprocessing part on my server and build a client to monitor the progress from multiple workstations my problem is i do not know how to accomplish this and my searches are not really helping me it seems i am getting a lot of out dated solutions webobjects portable thistributed objects or incomplete information it seems like i would want to use nsstream to pass data back and forth but everything i find on nsstream looks like it is set up for client side because it is looking for an ip address what would be the best way to go about setting up both a server and a client to connect to it,['objective-c'] +182940,could not load file or assembly antlr3runtimedll we were using teamcity for our build server net framework 4 and aspnet mvc2 and nhibernateour build server recently went offline thanks to amazon ec2 issue recently we are setting a new build server uphowever even though nothing changed recently in our codebase teamcity gives following errorresgen error rg0 could not load referenced assembly cteamcitybuildagentwork1e7706dcd512f467xlibantlr3runtimedll caught a fileloadexception saying could not load file or assembly cteamcitybuildagentwork1e7706dcd512f467xlibantlr3runtimedll or one of its dependencies provider dll failed to initialize correctly exception from hresult 0x8009001dgiven dll file exists along with other required dlls any solution,['asp.net'] +182953,bad text rendering with core animation first of all i know this topic has been brought up several times before but i am posting this question because none of the solutions i have used in the past have worked in this specific case i am drawing some text to a calayer that is hosted by a view inside my nstoolbar heres what the text look likesi tried using a suggestion from this stackoverflow post which is to call cgcontextsetshouldsmoothfontsctx false to turn off subpixel antialiasing before drawing into the context this is a solution that has given me acceptable results in the past but in this case it seems to have made the text look even worsethe other solution mentioned in that post is to fill the rect with an opaque background color before drawing which simply is not possible in this case because the toolbar background is a gradient is there anything i can do to make this text look as nice as text drawn into a plain nsview,['objective-c'] +182959,issue reading http request body from a json post in php i am writing a script that is registered as an endpoint for a webhook i know that it is successfully registered because i am writing the header of every request to my server logs heres a samplecontenttype textxml charsetutf8useragent jakarta commonshttpclient31host obfuscated contentlength 1918the api that i have registered with is posting a json object to my script and i would like to parse that object using php as you can see from the request header there is a nice big fat json object waiting to be parsed it seems straightforward but it has not been at first i tried using postjson or just post but since the data is not in an array i was not really sure how to access it like thati have tried using file get contentsphpinput and fopenphpinput r with and without json decode but no luck i cannot use http get request body since the server i am on does not have pecl and that is out of my controlare there any other ways to interact with the posted json object that i am missing thanks,['php'] +182966,ignore specific warnings with php codesniffer i am working on a password tools module and part of it is using base64 encodingdecoding as a result i have a number of variables which include the term base64 for obvious reasons the problem is that when i run the php codesniffer tool it throws warnings variable 64 contains numbers but this is thiscouragedis there any way to tell php codesniffer to ignore these warnings for this specific file i am sure there is a good reason to avoid numbers but in this case i would rather use base64 than basesixtyfourthis is how i am running php codesniffervaloringandalfworkspacelibrary phpcs standardzend toolsfile homevalorinworkspacelibrarytoolspasswordphpfound 0 errors and 6 warnings affecting 5 lines 38 warning variable bencryptionbase64 contains numbers but this is thiscouraged 94 warning variable bencryptionbase64 contains numbers but this is thiscouraged 94 warning variable base64 contains numbers but this is thiscouraged 95 warning variable base64 contains numbers but this is thiscouraged 210 warning variable bencryptionbase64 contains numbers but this is thiscouraged 251 warning variable bencryptionbase64 contains numbers but this is thiscouragedtime 1 second memory 750mb,['php'] +182973,using an alternate rails layout but same view on mobile devices i have been using the same tactics in the mobile devices railscast to provide an alternate layout for my site in a mobile browserwhen a mobile browser is detected the requestformat is set to mobile which i have defined as a mime typei have created a new layout for mobile devicesif i provide a mobile view eg showmobilehaml both the mobile view and layout are used on mobile devices and everything works greatthe problem is i do not want to create entirely new views it is just the layout i want to change if i do not create an appropriately named view the mobile layout is never used so asis i can only manage to change both or neither on mobile deviceswhat am i missing here how can i get rails to swap out just the layout when i have got a mobile user,['ruby-on-rails'] +182984,are lambda functions faster than delegatesanonymous functions i assumed lambda functions delegates and anonymous functions with the same body would have the same speed however running the following simple programstatic void mainstring args listint items new listint random random new random for int i 0 i 10 i itemsaddrandomnext stopwatch watch ienumerableint result funcint bool delegate delegateint i return i 500 watch stopwatchstartnew result itemswheredelegate watchstop consolewritelinedelegate 0 watchelapsedtotalmilliseconds funcint bool lambda i i 500 watch stopwatchstartnew result itemswherelambda watchstop consolewritelinelambda 0 watchelapsedtotalmilliseconds watch stopwatchstartnew result itemswherei i 500 watchstop consolewritelineinline 0 watchelapsedtotalmilliseconds consolereadlinei getdelegate 42948 mslambda 019 msanonymous 034 msalthough negligible why are these three apparently identical methods running at different speeds whats happening under the hoodupdateas suggested by the comments the following forces the where by calling tolist on it in addition a loop is added to offer more run datawhile true listint items new listint random random new random for int i 0 i 10 i itemsaddrandomnext stopwatch watch ienumerableint result funcint bool delegate delegateint i return i 500 watch stopwatchstartnew result itemswheredelegatetolist watchstop consolewritelinedelegate 0 watchelapsedtotalmilliseconds funcint bool lambda i i 500 watch stopwatchstartnew result itemswherelambdatolist watchstop consolewritelinelambda 0 watchelapsedtotalmilliseconds watch stopwatchstartnew result itemswherei i 500tolist watchstop consolewritelineinline 0 watchelapsedtotalmilliseconds consolewritelinenew string 12the above code results in 120 ms for each function,['c#'] +183009,how to view all javascript functions called in real time i want to figure out how a website reloads it is content using ajax therefore i would like to see what js functions are called in real time because i cannot figure out what function is responsible for reloading the page dynamically how to see all executed functions js in real time in ff chrome opera or ie,['javascript'] +183040,finding unused django code to remove i have started working on a project with loads of unused legacy code in it i was wondering if it might be possible to use a tool like coverage in combination with a crawler like the djangotestutils one to help me locate code which is not getting hit which we can mark with deprecation warnings i realise that something like this would not be foolproof but thought it might helpi have tried running coveragepy with the django debug server but it does not work correctly it seems to just profile the runserver machinery rather than my views etcwere improving our test coverage all the time but there is a way to go and i thought there might be a quicker wayany thoughtsthanks,['python'] +183046,building executable using pythonvtk and py2exe is it possible to create a binary executable with py2exe for vtkcould someone provide a minimum working example or at least some hints py2exe is not necessary if there is a working solution on other similar programs bbfreeze etc i am intrested too,['python'] +183047,codeigniter email attachment of last emails not cleared while sending multiple emails in loop my code sends multiple emails in loop with attachmentproblem is attachments of lastprevious all emails get attached to next emailex suppose 3 emails in database with 1 attachment in eacha1pdf a2pdf a3pdfthen it sends email with attachment asemail 1attachment a1pdfemail 2attachment a1pdf a2pdfemail 3attachment a1pdf a2pdf a3pdfi am using codeigniter frameworkmy code is this code is called in loopthisemailsubjectitemsubject thisemailmessagemessage attachments ifstrlenitemattachment 5 attachments explode itemattachment foreachattachments as attachment ifstrlenattachment5 thisemailattachfcpath attachments attachment thisemailsend,['php'] +183053,ruby c extensions api questions so recently i had the unfortunate need to make a c extension for ruby because of performance since i was having problems with understanding value and still do so i looked into the ruby source and found typedef unsigned long value link to source but you will notice that there are a few other ways it is done but i think it is essentially a long correct me if i am wrong so while investigating this further i found an interesting blog post which saysin some cases the value object could be the data instead of pointing to the datawhat confuses me is that when i attempt to pass a string to c from ruby and use rstring ptr on the value passed to the cfunction from ruby and try to debug it with strlen it returns 4 always 4example codevalue testvalue inp unsigned char c rstring ptrinp return rb str new2c this returns some random gibberish return int2fixstrlencthis example returns always 1 as the string lengthvalue testvalue inp unsigned char c unsigned char inp return rb str new2c always x03 in ruby return int2fixstrlencsometimes in ruby i see an exception saying cannot convert module to string or something along those lines however i was messing with the code so much trying to figure this out that i am unable to reproduce the error now the error would happen when i tried stringvalueptr i am a bit unclear what this exactly does documentation says it changes the passed paramater to char on inpvalue testvalue inp stringvalueptrinp return rb str new2charinp without the cast i would get compiler warnings so the ruby code in question is mymodtestblahblablahedit fixed a few typos and updated the post a littlethe questionswhat exactly does value imp hold a pointer to the objectvaluethe value itselfif it holds the value itself when does it do that and is there a way to check for ithow do i actually access the value since i seem to accessing almost everything butthe valueps my understanding of c is not really the best but it is a work in progress also read the comments in the code snippets for some additional description if it helpsthanks,"['c', 'ruby']" +183055,switch statements in c variable in case include stdiohint mainint argc char argv char a c switchc case a printfhin return 0the above would not compile for this errorcase label does not reduce to an integer constantwhy is this not allowed,['c'] +183057,why does not coveragepy properly measure djangos runserver command i should know the answer to this but i do not if you try to measure the coverage of a django project like thiscoverage run managepy runserver you get coverage measurement that misses all of your actual code something early on in the process is stopping the measurement or all the real work happens in a new context that does not get measured at allcan someone point me to the specific point in the process where the measurement breaks down so that i can try to fix coveragepy so that it will measure it properly the way people expect,['python'] +183082,how does the firebug network monitor work in the firebug addon for firefox how is firebug able to get the connecting waiting and receiving time also how is it that firebug can know the file size before the file is even finished loadingis javascript used in these calculations or does firebug use another method altogether,['javascript'] +183107,how does contractensures work i am starting to use code contracts and whilst contractrequires is pretty straight forward i am having trouble seeing what ensures actually doesi have tried creating a simple method like thisstatic void main dosomethingprivate static void dosomething contractensuresfalse wrong consolewritelinesomethingi never see the message wrong though nor does it throw exceptions or anything elseso what does it actually do,['c#'] +183108,link to and remote true jquery how help im trying to make an users link on the index of my rails website so that it shows the registered users userall but i want that to appear on the right part of the website as a partial in a div without loading the whole page from the starti knew that this was possible with old prototype and remote true but with rails 31 and jquery and assets i have no idea how to do itcan anyone help or show me the way to a tutorial,"['jquery', 'ruby-on-rails']" +183109,using within good idea or bad idea i noticed facebook does this where they have a meta refresh enclosed in a noscript enclosed in the head tag they use this to detect if the user agent has javascript enabled or notwe were thinking of using this method for 2 reasonsto auto redirect to a nonjs optimized version of the site as facebook doesto include a nonjs stylesheet to hopefully thisable the finger pointer over javascript only anchors as well as for css3 complaint browsers fading those buttons out to make it more obvious they are thisabled not working ratherwill using this method for the above reasons cause any adverse effects that will affect a large percentage of user agents,"['javascript', 'html', 'css']" +183114,how to makesimulate persistent tcp connection it looks like wcf tcp connections are not persistent first ping reply takes a while but subsequent processes take less time after a while it takes long again another reconnectionserver started on nettcp09 client connection created to nettcplocalhost9 not a real connection ready to connectclient ping reply in 1s163ms first connectionclient ping reply in 22ms already connectedclient ping reply in 26msclient ping reply in 24msclient ping reply in 325ms reconnectedclient ping reply in 19msclient ping reply in 767ms reconnectedif it is true what is the idle time value for a tcp connection before it will be thisconnected i need to keep the connection aliveupdate modified codenettcpbinding tcpbind new nettcpbindingtcpbindreliablesessionenabled truetcpbindreliablesessionordered truetcpbindreliablesessioninactivitytimeout timespanfromminutes10servicehost svh new servicehosttypeofserviceimplementationsvhaddserviceendpoint typeofwcfsimplecontractiservice new nettcpbinding tcpbind stringformatnettcp01 ip portsvhopennow i got another errorthe action is not supported by this endpoint only wsreliablemessaging february 2005 messages are processed by this endpointupdate i modified only server side and it caused the error then i modified client sides tcp as reliable messaging,"['c#', '.net']" +183123,how can i break the law of noncontradiction in javascript the law of noncontradiction dictates that two contradictory statements cannot both be true at the same time that means that the expressionsa aa aa ashould always evaluate to a falsy value anda ashould always evaluate to a truthy valuefortunately though javascript is a fun language that allows you to do all sorts of sick things i bet someone a small fortune that it is possible to convince javascript to break the law of noncontradiction or at least convincingly make it look like it is breaking the law of noncontradiction now i am trying to make all four of the above code examples give the unexpected resultwhat would be a good way to go about this,['javascript'] +183124,why do all backgrounds thisappear on uitableviewcell select my current projects uitableviewcell behavior is baffling me i have a fairly straightforward subclass of uitableviewcell it adds a few extra elements to the base view via selfcontentview addsubview and sets background colors on the elements to have them look like black and grey rectangular boxes because the background of the entire table has this concretelike texture image each cells background needs to be transparent even when selected but in that case it should darken a bit i have set a custom semitransparent selected background to achieve this effectuiview background uiview alloc initwithframeselfbounds autoreleasebackgroundbackgroundcolor uicolor blackcolor colorwithalphacomponent06backgroundopaque noself setselectedbackgroundviewbackgroundand although that yields the right look for the background a weird side effect happens when i select the cell all other backgrounds are somehow turnt off heres a screenshot the bottom cell looks like it should and is not selected the top cell is selected but it should thisplay the black and grey rectangular areas yet they are gonewho knows whats going on here and even more important how can i correct this,['objective-c'] +183166,youtube iframes sitting on top of fixed position element in chrome in chrome youtube iframes float on top of my fixed position header i have tried setting zindexes for both and its not happening anybody know a fix for this,"['html', 'css']" +183180,anchor option in link to rails i have a link to method in railslink tofeedback meetings urlanchor sometext the above code gives an output ofa hrefpmeetingscroll tosometextfeedbackai thought anchor was supposed to prepend a hash paramter something like thispmeetingsometext,['ruby-on-rails'] +183197,animate list items in listview i try to animate new items in my listview i have stable ids so i know exactly which element to animate the problem comes from the recycle mechanism of listview i call startanimation on the view when i know i got a recently inserted element but then the view got recycled filled with different data it results on the ui animating the wrong row at some point the view was holding the right data but then got recycled i confirmed this via logcatis there any way to solve thiseditpublic expenscursoradaptercontext context cursor c boolean autorequery copyonwritearraysetstring fadeanimatetags supercontext c autorequery thismfadeanimtags fadeanimatetagsoverridepublic boolean hasstableids return trueoverridepublic void bindviewview view context context cursor cursor setupview context cursorprivate void setupview view context context cursor cursor final string id cursorgetstring4 if local logv logvtag stringformatcreate item for s received view s id viewtostring viewsettagid final textview datetext textview viewfindviewbyidriddate final textview timetext textview viewfindviewbyidridtime final textview title textview viewfindviewbyidridtitle final textview amount textview viewfindviewbyidridamount final date date new datecursorgetlong0 titlesettextcursorgetstring1 datetextsettextdformatformatdate timetextsettexttformatformatdate amountsettextstringformatd ft cursorgetint2 if cursorgetint3 1 timetextsettextcolorcolorltgray titlesettextcolorcolorltgray datetextsettextcolorcolorltgray amountsettextcolorcolorltgray else timetextsettextcolorcolorblack titlesettextcolorcolorblack datetextsettextcolorcolorblack amountsettextcolorcolorblack if mfadeanimtagscontainsid viewsetanimationanimationutilsloadanimationcontext ranimfade mfadeanimtagsremoveid overridepublic view newviewcontext context cursor cursor viewgroup parent final layoutinflater inflater layoutinflaterfromcontext view view inflaterinflaterlayoutexpense list item parent false setupview context cursor return view,['android'] +183200,u200b zero width space characters in my js code where did they came from i am developing a front end of a web app using netbeans ide 701 recently i had a very nasty bug which i finally fixedsay i have codevar element input size3 idfoo nameelementsfoo0 barappendelementi noticed that something gone wrong when i saw that size attribute does not work in chrome did not checked in other browsers when i opened that element in inspector it was interpreted as something likeinput idquot3quot namequotelementsfoo0quot sizequotfooquot which was rather strange after manually retyping the element string characterincharacter the bug was gone when i undoed that change i noticed that netbeans alerted me about some unicode characters in my old code it was u200b a zero width spaces after each between and in the end of the string so the string appeared normal because zero width spaces was not thisplayed but after escaping them my string wasinput sizeu200b3 idu200bfoo nameu200belementsfoou200b0 u200bnow where the hell did i get themi am not sure where did i copied the code of element from but it is definitely one of the followingother pane of netbeans editor with html template filegoogle chrome inspector copy as html actiongoogle chrome source view page very doubtfullybut i cannot reproduce the bug with neither of thati use netbeans 701 and google chrome 130 under windows 7 no keyboard switchers or anything like it is running also i am using git for version control but i did not pulled that code so it is very unlikely that git is to blame it cannot be a stupid joke of my colleagues because they are quite wellmanneredany suggestions who messed up my code,"['javascript', 'html']" +183227,mysql update an entire column i wanted to ask if there is a way to update an entire column with the same valuei want to run 0 down a column or 1i can use a php loop to do it but it will involve multiple db calls etchopeing for a sql statement that can run the same value down an entire mysql columncheers,['mysql'] +183234,triangle fit inside another triangle given the lengths of the sides of 2 triangles determine if the second triangle can fit inside the first trianglefor more detailed info read the full problem statement belownum1566localeenmy implementation below tries all the 32 possible combinations of aligning the bases of the triangles it then tries to shift the second triangle inside the first triangle while checking that the base of the second triangle does not exceed the base of the first trianglebut i keep getting wrong answerwa 16 the case i gave is the second image it is obvious that if you rotate pqr to align the sides of length 277 and 30 the third vertex will not be inside triangle abc the side of length 42 can only be aligned along the side of len 5 thus this case is satisfied only in the configuration show in the second imagecan you help me find the bug suggest some test cases where my algorithm breaks down alternative algorithms are also welcomeinclude cmathinclude iostreamusing namespace stdconst double pi atan10 4 traingle abc envelopedouble xa ya xb yb xc yc traingle pqr postcarddouble xp yp xq yq xr yr angle between sides ab and acdouble thetadouble signwrtlinedouble x1 double y1 double x2 double y2 double x double y double a y2 y1 double b x1 x2 double c a x1 b y1 return a x b y cbool fit if xr xc yq yb return false if signwrtlinexa ya xb yb xq yq 0 double d yq tantheta xq return xr d xc return signwrtlinexa ya xb yb xq yq 0 signwrtlinexb yb xc yc xq yq 0 signwrtlinexc yc xa ya xq yq 0bool fitdouble a double b generate the 3 permutations of the envelope loops ik for int i 0 i 3 i double angle double you ai v ai 1 3 w ai 2 3 for int k 0 k 2 k switch k case 0 xa 0 ya 0 angle theta acosu you v v w w 2 you v xb v cosangle yb v sinangle xc u yc 0 break case 1 reflect envelope swapv w angle theta acosu you v v w w 2 you v xb v cosangle yb v sinangle break generate the 3 permutations of the postcard loops jk for int j 0 j 3 j double angle double you bj v bj 1 3 w bj 2 3 for int k 0 k 2 k switch k case 0 xp 0 yp 0 angle acosu you v v w w 2 you v xq v cosangle yq v sinangle xr u yr 0 break case 1 reflect postcard swapv w angle acosu you v v w w 2 you v xq v cosangle yq v sinangle break if fit return true return falseint main double a3 b3 for int i 0 i 3 i cin ai for int i 0 i 3 i cin bi iffita b cout yes endl else cout no endl return 0,['c++'] +183235,changing the way a javascript alert or prompt looks is there any way to change the looks of an alert or prompt in javascript things like adding an image changing the font color or size and whatever will make it look different,['javascript'] +183252,treemap or hashmap faster i am writing an dictionary that make heavily use of string as key in mapstring index what i concern is which one of hashmap and treemap will result in better faster performance in searching a key in the map,['java'] +183253,specific reason why python uses triplequotation marks for comments why did not python just use the traditional style of comments like ccjava uses comment lines more comment lines line comments line commentsis there a specific reason for this or is it just arbitrary,['python'] +183270,whats the best way to format a phone number in python if all i have is a string of 10 or more digits how can i format this as a phone numbersome trivial examples518005i know those are not the only ways to format them and it is very likely i will leave things outif i do it myself is there a python library or a standard way of formatting phone numbers,['python'] +183277,how to pass variables to layout i know how to pass variable from controller into a viewthisrenderview name arrayvariable namevariable valuehowever i would like to pass some variables to layout the only connection between controller and layout seems to be the public layout attribute in controller class like thispublic layoutlayoutscolumn2however i do not see a way to pass a variable to it,['php'] +183289,why does the datagrid not update when the itemssource is changed i have a datagrid in my wpf application and i have a simple problem i have a generic list and i want to bind this collection to my datagrid data source every time an object is being added to the collection and i am not interested to use observable collectionthe point is i am using the same method somewhere else and that works fine but this time when i press add button an object is added and datagrid updates correctly but from the second item added to collection datagrid does not update anymorehere is the code private void btnadditem clickobject sender routedeventargs e orderdetailobjectsaddnew orderdetailobject price currentitempricevalue quantity intparsetxtquantitytext title currentitemthisplayname totalprice currentitempricevalue intparsetxtquantitytext dgorderdetailitemssource orderdetailobjects dgorderdetailupdatelayout any idea,['c#'] +183301,unable to set margin of item in listview using custom adapter i am attempting to set variable left margins for items in my listview the problem occurs in my custom adapter in the getview method public view getviewint position view convertview viewgroup parent ifconvertview null comment c commentsgetposition convertview inflaterinflaterlayoutlist item null textviewconvertviewfindviewbyidridstorysettextcmessage relativelayoutlayoutparams lp new relativelayoutlayoutparamsviewgrouplayoutparamsfill parent viewgrouplayoutparamsfill parent lpsetmargins0 cgetdepth 5 0 0 convertviewsetlayoutparamslp return convertview we inflate the list item layout which is a relativelayout with some textviews inside i then attempt to set the margins using a relativelayoutlayoutparams i get a class cast exception on this but the normal layoutparams type has no method for setting the marginswhat is the best way to go about setting the marginhere is the errorjavalangclasscastexception androidwidgetrelativelayoutlayoutparamsat androidwidgetlistviewsetupchildlistviewjava1779at androidwidgetlistviewmakeandaddviewlistviewjava1748at androidwidgetlistviewfilldownlistviewjava670at androidwidgetlistviewfillfromtoplistviewjava727at androidwidgetlistviewlayoutchildrenlistviewjava1598at androidwidgetabslistviewonlayoutabslistviewjava1273at androidviewviewlayoutviewjava7192at androidwidgetframelayoutonlayoutframelayoutjava338at androidviewviewlayoutviewjava7192at androidwidgetlinearlayoutsetchildframelinearlayoutjava1254at androidwidgetlinearlayoutlayoutverticallinearlayoutjava1130at androidwidgetlinearlayoutonlayoutlinearlayoutjava1047at androidviewviewlayoutviewjava7192at androidwidgetframelayoutonlayoutframelayoutjava338at androidviewviewlayoutviewjava7192at androidviewviewrootperformtraversalsviewrootjava1145at androidviewviewroothandlemessageviewrootjava1865at androidoshandlerthispatchmessagehandlerjava99at androidoslooperlooplooperjava130at androidappactivitythreadmainactivitythreadjava3835at javalangreflectmethodinvokenativenative methodat javalangreflectmethodinvokemethodjava507at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava847at comandroidinternaloszygoteinitmainzygoteinitjava605at dalviksystemnativestartmainnative method,['android'] +183306,tricky median question given and points choose a point in the given list such that the sum of thistances to this point is minimum compared to all othersthistance is measured in the following mannerfor a point xy all 8 adjacent points have thistance 1x1yx1y1x1y1xy1xy1x1yx1y1x1y1editmore clearer explanationa function foo is defined as foopoint apoint b maxabspoint ax point bxabspoint ay point byfind a point x such that sumfooxy for y in list of points is minimumexampleinput12 143 314 714 32 121 6output1 6egthistance between 45 and 67 is 2this can be done in on2 time by checking the sum of each pairis there any better algorithm to do it,['python'] +183321,instantiation of recursive generic types slows down exponentially the deeper they are nested why note i may have chosen the wrong word in the title perhaps i am really talking about polynomial growth here see the benchmark result at the end of this questionlet us start with these three recursive generic interfaces that represent immutable stacksinterface istackt inonemptystackt istackt pusht xinterface iemptystackt istackt new inonemptystackt iemptystackt pusht xinterface inonemptystackt out tstackbeneath istackt where tstackbeneath istackt t top get tstackbeneath pop new inonemptystackt inonemptystackt tstackbeneath pusht xi have created straightforward implementations emptystackt nonemptystackttstackbeneathupdate 1 see the code belowi have noticed the following things about their runtime performance pushing 10 items onto an emptystackint for the first time takes more than 7 secondspushing 10 items onto an emptystackint takes virtually no time at all afterwardsperformance gets exponentially worse the more items i push onto the stackupdate 2i have finally performed a more precise measurement see the benchmark code and results belowi have only thiscovered during these tests that net 35 does not seem to allow generic types with a recursion depth 100 net 4 does not seem to have this restrictionthe first two facts make me suspect that the slow performance is not due to my implementation but rather to the type system net has to instantiate 10 thistinct closed generic types ieemptystackintnonemptystackint emptystackintnonemptystackint nonemptystackint emptystackintnonemptystackint nonemptystackint nonemptystackint emptystackintetcquestionsis my above assessment correctif so why does instantiation of generic types such as tu ttu tu and so on get exponentially slower the deeper they are nested are clr implementations other than net mono silverlight net compact etc known to exhibit the same characteristics offtopic footnote these types are quite interesting btw because they allow the compiler to catch certain errors such asstackpushitempoppop causes compiletime error if stack is not known to be nonemptyor you can express requirements for certain stack operationststackbeneath poptwoitemst tstackbeneath inonemptystackt inonemptystackt tstackbeneath stackupdate 1 implementation of the above interfacesinternal class emptystackt iemptystackt public inonemptystackt iemptystackt pusht x return new nonemptystackt iemptystacktx this inonemptystackt istackt istacktpusht x return pushx this could be made into a singleton per type tinternal class nonemptystackt tstackbeneath inonemptystackt tstackbeneath where tstackbeneath istackt private readonly t top private readonly tstackbeneath stackbeneathtop public nonemptystackt top tstackbeneath stackbeneathtop thistop top thisstackbeneathtop stackbeneathtop public t top get return top public tstackbeneath pop return stackbeneathtop public inonemptystackt inonemptystackt tstackbeneath pusht x return new nonemptystackt inonemptystackt tstackbeneathx this inonemptystackt istackt istacktpusht x return pushx update 2 benchmark code and resultsi used the following code to measure recursive generic type instantiation times for net 4 on a windows 7 sp 1 x64 intel u4100 13 ghz 4 gb ram notebook this is a different faster machine than the one i originally used so the results do not match with the statements aboveconsolewritelinen t msint outern 0while true outern var appdomain appdomaincreatedomainouterntostring appdomainsetdatan outern appdomaindocallbackdelegate int and intappdomaincurrentdomaingetdatan var stopwatch new stopwatch stopwatchstart istackint s new emptystackint for int i 0 i n i s spushi this creates a new type stopwatchstop long ms stopwatchelapsedmilliseconds consolewriteline0 1 n ms appdomainunloadappdomaineach measurement is taken in a separate app domain because this ensures that all runtime types will have to be recreated in each loop iterationheres a xy plot of the outputhorizontal axis n denotes the depth of type recursion ien 1 indicates a nonemptystackemptystacktn 2 indicates a nonemptystacknonemptystackemptystacktetcvertical axis t is the time in milliseconds required to push n integers onto a stack the time needed to create runtime types if that actually happens is included in this measurement,['.net'] +183326,how to unhide view with animations say i have a hidden view in xcode for ios now when i set the view to not hidden viewhiddenno how can i make it so that it now appears but with animations,['iphone'] +183328,do c collections always enforce order ie if i want to select from an array is the resultant ienumerableobject object necessarily in orderpublic class student public string fullname public class school public string name public student students public void studentlistworkschool thisschool ienumerablestring studentnames thisschoolstudentsselectstudent studentfullname is studentnames guaranteed to be in the same order as thisschoolstudentsthanks,"['c#', '.net']" +183332,using php constants in pdo calls php nettuts tutorial using php data objects pdothis file contains the database access information this file also establishes a connection to mysql and selects the database set the database access information as constants print rpdogetavailabledriversdefinedb user rootdefinedb password rootdefinedb host localhostdefinedb name sitenamephp htmlspecialcharstry mysql with pdo mysql dbh new pdomysqlhostphpdb host dbnamephpdb name root root dbh new pdomysqlhostlocalhost dbname sitename root root dbhsetattributepdoattr errmode pdoerrmode exception uhoh typed delect instead of select dbhpreparedelect name from people catch pdoexception e echo i am sorry dave i am afraid i cannot do that file put contentspdoerrorstxt egetmessage file appendthe console in os x returns 14aug2011 155959 php notice use of undefined constant root assumed root in applicationsmamphtdocs3nettutsphppdo for database accessmysql pdo connectphp on line 20i have googled and found a partial answer here so i was hoping for completion heretia,['php'] +183336,touch through uiimageview i have a transparent uiimageview with a button behind it how can i touch through it and press the button underneath itthanks,['iphone'] +183347,detect the enter key in a text input field i am trying to do a function if enter is pressed while on specific inputwhat i am i doing wrongdocumentkeyupfunction e if input1isfocus ekeycode 13 do something is there a better way of doing this which would say if enter pressed on input1 do function,"['javascript', 'jquery']" +183356,tower of hanoi javascript the good parts i have seen the other questions on so about the recursive function and i have read the responses but i still cannot get the algorithm to click in my headvar hanoi function thisc src aux dst if thisc 0 hanoithisc 1 src dst aux documentwritemove thisc thisc from src to dst hanoithisc 1 aux src dst hanoi3 src aux dsthow does the documentwrite ever run my logic is first time we run the function thisc is 3 then we recursively call the function again skipping everything below so how does the documentwrite get a chance to runi understand recursion done the basic examples but i still cannot see how you get an output if there is a way i can run it visually and see it in action that would help alot,['javascript'] +183367,how do i animate a glowing effect on text i have not really been able to find any good simple tutorials an animating a glow effecthere is something i found but it does not work so i do not even know if it will have the look that i want,"['jquery', 'css']" +183391,given two python lists of same length how to return the best matches of similar values given are two python lists with strings in them names of personslist 1 j payne george bush billy idol m stuart luc van den bergenlist 2 john payne george w bush billy idol m stuart luc bergeni want a mapping of the names that are most similarj payne john paynegeorge bush george w bushbilly idol billy idolm stuart m stuartluc van den bergen luc bergenis there a neat way to do this in python the lists contain in average 5 or 6 names sometimes more but this is seldom sometimes it is just one name in every list which could be spelled slightly different,['python'] +183400,html link that bypasses cache i have a file that i link to from my website likea hrefviewahowever this file changes very frequently and when the link is clicked the browser loads the cached version of the file not the actual fileis there a way so that clicking on that link will bypass the cache for that pagesomething nice like a bypasscache href would be wishful thinking,['html'] +183408,error when trying to delete foreign key aerror 1025 hy0a i am running into some trouble trying to delete a foreign key could someone please helphereas my show create table catgroup catgroup create table catgroup catgroupid int11 not null auto increment category id int11 not null group id int11 not null primary key catgroupid key category id category id key group id group id constraint catgroup ibfk 1 foreign key category id references cats cid on update cascade constraint catgroup ibfk 2 foreign key group id references groupsd on update cascade engineinnodb auto increment21 default charsetutf8 this is how i am trying to drop the foreign keyalter table catgroup drop foreign key group id ibfk 2and hereas the error message error 1025 hy0 error on rename of asset basecatgroup to asset basesql216b44 errno 152what am i doing wrong,['mysql'] +183417,store additional data in android account manager i would like to use the android accountmanger to sync my webservice and application standard sync of contacts and calander however accountmanager only appears to store a username and password my web service takes three credentials a username a password and an account what is the best practice for storing the third piece of information,['android'] +183425,perl compatible regular expression pcre in python i have to parse some strings based on pcre in python and i have no idea how to do thatstrings i want to parse looks like match mysql m0n4w00s pmysql i1in this example i have to get this different items m0n4w00s pmysql i1the only thing i have found relating to pcre manipulation in python is this module but it is written it is a so do you know if some python module exist to parse this kind of string,['python'] +183453,iphone sdk xcode how to get all the filenames in the documents dir i want to get all the filenames in my applications documents folder and place them in an nsmutablearray nothing more nothing less,['ios'] +183470,php function how to set default value as object a functionactually constructor of another class needs an object of class temp as argument so i define interface itemp and include itemp obj as function argument this is fine i must pass class temp objects to my function but now i want to set default value to this itemp obj argument how to accomplish this or is it not possiblei will put the test code to clarifyinterface itemp public function get class temp implements itemp private var public function constructvar null this var var public function get return this var defaulttempobj new tempdefaultfunction func1itemp obj print got objget as argumentnfunction func2itemp obj defaulttempobj error unexpected t variable print got objget as argumentntempobj new tempfoofunc1defaulttempobj got default as argumentfunc1tempobj got foo as argumentfunc1 error argument 1 must implement interface itemp should print defaultfunc2 could not test as i cannot define it,['php'] +183473,aspnet error the page yascx cannot use the user control xascx i am getting the error below when trying to build the web site project in visual studio 2010the page websitecontrolsc2ascx cannot use the user control websitecontrolsc1ascx because it is registered in webconfig and lives in the same directory as the pagei have 2 web user controlscontrolsc1ascxcontrolsc2ascxthe controls have been registered in webconfigconfiguration systemweb pages controls add srccontrolsc1ascx tagprefixmy tagnamec1 add srccontrolsc2ascx tagprefixmy tagnamec2 controls pages systemwebconfigurationc1ascx contains just a static html c2ascx is trying to include c1c1ascx contains just some plain static simple html c2ascx is trying to include c1ascx control languagevb myc1 runatserver phello from c2pwhen trying to build the project i am getting the error message at the top i realise this issue can be fixed by adding another register directive to c2ascx register srccontrolsc1ascx tagprefixctl tagnamec1 but i am wondering if there is a cleaner solution and why am i getting the error in the first placethanks,['asp.net'] +183476,calling a javascript function recursively i can create a recursive function in a variable like so count down to 0 recursively var functionholder function counter outputcounter if counter 0 functionholdercounter1 with this functionholder3 would output 3 2 1 0 let us say i did the followingvar copyfunction functionholdercopyfunction3 would output 3 2 1 0 as above if i then changed functionholder as followsfunctionholder functionwhatever outputstop countingthen functionholder3 would give stop counting as expectedcopyfunction3 now gives 3 stop counting as it refers to functionholder not the function which it itself points to this could be desirable in some circumstances but is there a way to write the function so that it calls itself rather than the variable that holds itthat is is it possible to change only the line functionholdercounter1 so that going through all these steps still gives 3 2 1 0 when we call copyfunction3 i tried thiscounter1 but that gives me the error this is not a function,['javascript'] +183478,constexpr question why do these two different programs run in such a different amount of time with g i am using gcc 461 and am getting some interesting behavior involving calling a constexpr function this program runs just fine and straight away prints out 12200160415121876738include iostreamextern const unsigned long joeconstexpr unsigned long fibunsigned long int x return x 1 1 fibx 1 fibx 2const unsigned long joe fib92int main stdcout here i amn stdcout joe n return 0this program takes forever to run and i have never had the patience to wait for it to print out a valueinclude iostreamconstexpr unsigned long fibunsigned long int x return x 1 1 fibx 1 fibx 2int main stdcout here i amn stdcout fib92 n return 0why is there such a huge difference am i doing something wrong in the second programedit i am compiling this with g stdc0x o3 on a 64bit platform,['c++'] +183483,the ruby way mixins and class reopening vs dependency injection in studying mixins vs dependency injection i often hear the phrase the ruby way often developers say something along the lines ofruby lets you reopen classes and redefine methods means that you can easily inject new references into your code at testtimesee 6 at but testing is not my main concern my concern is class reuse i want classes i can reuse in multiple enterprisescale rails applicationsso what happened to reusing classes using mixins and reopening classes does not seem to provide a way to write classes in such a way that they are decoupled from applicationspecific details without a bunch of extra work but perhaps i am wrong if i am can someone provide a link to an article containing sample code that clearly explains how to accomplish this properly using mixins and reopening of classesas an example the class foo here is coupled to the class loggerclass foo def initialize logger new logger end def new logger loggernew endendyes i can reopen foo and redefine new logger but i just cannot believe this is considered a realistic standard approach to writing reusable classes usable by multiple rails applications,"['ruby-on-rails', 'ruby']" +183502,can devise omniauth have several types of login i have used devise as a standard authentication gem for other projects in another project i have used devise omniauth for twitter authenticationin a new project i need my end users to be able to login via twitter and facebook or to be able to register via the app in the future the user could link his accounts together for example his twitter and facebook account or his twitter and native account native being the account he registered with directly with the web appis devise capable of such if so how do we link the accounts of users together what is the concept behind this how does the app know which facebook and twitter account belong to which userideas and suggestions welcomeediti have been following and what i dont get is if user is signed out of appuser has an account registered with appuser signs in with a different service provider facebook twitteretchow does the app know how to link his new service provider with his already existing accountsstackoverflowcom has this feature but one service provider they are not including in their multisign on feature is twitter i am guessing it is because twitter does not expose the users email through their api while the other service providers facebook yahoo gmail does,['ruby-on-rails'] +183591,how to fix the overhead and effective problem on innodb table questions 1 what is mean by overhead when i click optimize table button on myisam table overhead and effective data are gone i wonder what it does to my table2 do i need to care of overhead and effective value actually how to fix the overhead and effective problem on innodb table,['mysql'] +183596,is there a way for mysql to wait for rows matching a condition to be inserted let us say i was writing an aplication whered i would need to get notifications in real time from a server and let us say those notifications are stored on a mysql database for me to get them i would have to keep polling the mysql server keep repeating the same selectquery till i actually get results but i figure that is very unefficient way of doing it since most of the time the select would turn up empty if i do it often it is unreasonable strain on the server if i do it rarely the notifications would come in very lateso i was wondering if there is a way for say a mysql query to block until a result matching a condition becomes availablelist query select from notifications where unread1 instead of returning an empty list if there is no unread notifications it would instead wait till there actually are unread notifications to return,['mysql'] +183598,are javascript arrays actually linked lists i am new to javascript and notice that you do not need to specify an arrays size and often see people dynamically creating arrays one element at time this would be a huge performance problem in other languages as you would constantly need to reallocate memory for the array as it increases in sizeis this not a problem in javascript if so then is there a list structure available,['javascript'] +183600,reliably forcing guava map eviction to take place edit i have reorganized this question to reflect the new information that since became availablethis question is based on the responses to a question by viliam concerning guava maps use of lazy eviction laziness of eviction in guavas mapsplease read this question and its response first but essentially the conclusion is that guava maps do not asynchronously calculate and enforce eviction given the following mapconcurrentmapstring myobject cache new mapmaker expireafteraccess10 timeunitminutes makemaponce ten minutes has passed following access to an entry it will still not be evicted until the map is touched again known ways to do this include the usual accessors get and put and containskeythe first part of my question solved what other calls cause the map to be touched specifically does anyone know if size falls into this categorythe reason for wondering this is that i have implemented a scheduled task to occasionally nudge the guava map i am using for caching using this simple methodpublic static void nudgeeviction cachecontainskeyhowever i am also using cachesize to programmatically report the number of objects contained in the map as a way to confirm this strategy is working but i have not been able to see a difference from these reports and now i am wondering if size also causes eviction to take placeanswer so mark has pointed out that in release 9 eviction is invoked only by the get put and replace methods which would explain why i was not seeing an effect for containskey this will apparently change with the next version of guava which is set for release soon but unfortunately my projects release is set soonerthis puts me in an interesting predicament normally i could still touch the map by calling get but i am actually using a computing mapconcurrentmapstring myobject cache new mapmaker expireafteraccess10 timeunitminutes makecomputingmaploadfunctionwhere loadfunction loads the myobject corresponding to the key from a database it is starting to look like i have no easy way of forcing eviction until r10 but even being able to reliably force eviction is put into doubt by the second part of my questionthe second part of my question solved in reaction to one of the responses to the linked question does touching the map reliably evict all expired entries in the linked answer niraj tolia indicates otherwise saying eviction is potentially only processed in batches which would mean multiple calls to touch the map might be needed to ensure all expired objects were evicted he did not elaborate however this seems related to the map being split into segments based on concurrency level assuming i used r10 in which a containskey does invoke eviction would this then be for the entire map or only for one of the segmentsanswer martinus has addressed this part of the questionbeware that containskey and other reading methods only run postreadcleanup which does nothing but on each 64th invocation see drain threshold moreover it looks like all cleanup methods work with single segment onlyso it looks like calling containskey wouldnt be a viable fix even in r10 this reduces my question to the title how can i reliably force eviction to occurnote part of the reason my web app is noticeably affected by this issue is that when i implemented caching i decided to use multiple maps one for each class of my data objects so with this issue there is the possibility that one area of code is executed causing a bunch of foo objects to be cached and then the foo cache is not touched again for a long time so it does not evict anything meanwhile bar and baz objects are being cached from other areas of code and memory is being eaten i am setting a maximum size on these maps but this is a flimsy safeguard at best i am assuming its effect is immediate still need to confirm thisupdate 1 thanks to darren for linking the relevant issues they now have my votes so it looks like a resolution is in the pipeline but seems unlikely to be in r10 in the meantime my question remainsupdate 2 at this point i am just waiting for a guava team member to give feedback on the hack martinus and i put together see answers belowlast update feedback received,['java'] +183602,ios app how to make main window rotate i have a background image in my main window so that when i flip views it is not a blank white screen behind but an image my problem is that this image does not rotate when the device rotatesedit as far as i can tell brett was correct when he pointed out that i would have to rotate the background image manually in this instance in case it helps anyone else out in the future heres how i rotated itinside myappdelegate void applicationuiapplication application willchangestatusbarorientationuiinterfaceorientationnewstatusbarorientation durationnstimeintervalduration if newstatusbarorientation uiinterfaceorientationportrait selfbgimagetransform cgaffinetransformidentity else if newstatusbarorientation uiinterfaceorientationportraitupsidedown selfbgimagetransform cgaffinetransformmakerotationm pi else if uiinterfaceorientationislandscapenewstatusbarorientation float rotate newstatusbarorientation uiinterfaceorientationlandscapeleft 11 m pi 20 selfbgimagetransform cgaffinetransformmakerotationrotate selfbgimagetransform cgaffinetransformtranslateselfbgimagetransform 0 selfbgimageframeoriginy,"['iphone', 'ios']" +183628,flash vs html5 game development for web mobile i am an experienced as3 programmer and i have done flash apps and games on the browser and on mobile via adobe air eg on androidi am about to start developing a game basic 2d platformer with pixelart graphics think about super mario world targeted to both web and mobile platforms thus i am searching for easy deployment to these two kinds of platforms having basically the same source codei am divided between choosing actionscript 30 flash or html5javascript for developing this gamemy main question is for those whove experienced the same situation beforewhat is the safest way to goin other words are there serious thisadvantages with one of these frameworks that thisallows me to develop multiplatform 2d gamesor am i just dreaming and practical multiplatform web and mobile game development is not so possible does someone know how rovio did it with angry birdshere are some pros and cons that i already knowpros for as3flashthe stateofart for web gamesi am experienced with italmost concealed source codeon the web it is browserindependentcan run as a native app on ios and android through adobe air it is not the best performance experience ever but i know that you can get playable performances with itcons for as3 flashperformance on air for mobile is not optimal so i might end up having to abandon a really cool but expensive feature or even several featurespeople are saying html5javascript will substitute itpros for html5javascriptit is possible to do flashquality games using eg engines like impactjs or akihabaraseems to be more stable and well supported on mobile in the futuredeployment as native app is possible through phonegap appmobi etccons for html5javascripti have some basic knowledge of this technologysource code is wide open exposedperformancebehaviour is browserdependentlacks a solid framework or engine which is free of cot,['javascript'] +183645,can a program depend on a library during compilation but not runtime i understand the difference between runtime and compiletime and how to differentiate between the two but i just do not see the need to make a thistinction between compiletime and runtime dependencieswhat i am choking on is this how can a program not depend on something at runtime that it depended on during compilation if my java app uses log4j then it needs the log4jjar file in order to compile my code integrating with and invoking member methods from inside log4j as well as runtime my code has absolutely no control over what happens once code inside log4jjar is rani am reading up on dependency resolution tools such as ivy and maven and these tools clearly make the thistinction between these two types of dependencies i just do not understand the need for itcan anyone give a simple kings englishtype explanation preferably with an actual example that even a poor sap like me could understand,['java'] +183664,testing for 400 errors with paste on a webpy app i am using paste to do some functional testing on my controllers in my webpy app in one case i am trying to test for a 400 response when a malformed post is made to an api endpoint here is what my test looks likedef test api users index post malformedself r selftestapostapiusers params assert rheadercontenttype applicationjson assert rstatus 400but i am getting the following exceptionapperror bad response 400 bad request not 200 ok or 3xx redirect for apiusersi see paste has httpexception middleware but i cannot find any examples on how to use it or if its even the right way to go any suggestions or am i just going about this wrong,['python'] +183697,in what ways are subtypes different from subclasses in usage a subtype is established when a class is linked by means of extending or implementing subtypes are also used for genericshow can i differentiate subtyping from subclasses,['java'] +183708,using mongodb objectid as a document id i am trying to make a board with mongodbi want to assign document id with objectidif a user can access to a document page by where 4easdf123123 is a mongodb objectidis there any possible security threat if i use and show mongo objectid in url and using it as a document idand any suggestion with assigning document id with mongodb,['php'] +183711,how can i detect basic 2d geometric shapes eg square triangle circle on a jpeg image after taking a picture i am trying to detect the shape of the object that is shot what i am looking for is similar to face detection except i want the app to detect shapes instead of faces i am creating an android app using java and the android sdk any ideas on what libraries or resources i can access to do this sort of thing,"['java', 'android']" +183730,multiple functions as arguments in coffeescript i cannot for the life of me figure this out or find a solution online i am trying to figure out how to write a script in coffeescript from jquery based javascriptthe script is thisjquerypostthumb ahover function jquerythisfindoverlayfadein150 function jquerythisfindoverlayfadeout150i initially tried rewriting that like thisthumb overlay postthumb ahover thisfindoverlayfadein150 thisfindoverlayfadeout150but that did not work so i thought i would post here so how do i write that javascript in coffeescript,['jquery'] +183732,ios how to catch unhandled exception we are writing static library we have done exception handling for the exposed apis but still there are few unhandled exceptions or os exceptions can you please let me know how to catch these unhandled exceptionsthanks,"['ios', 'objective-c']" +183743,find maximum of three number in c without using conditional statement and ternary operator i have to find maximum of three number provided by user but with some restrictions its not allowed to use any conditional statement i tried using ternary operator like belowmaxababcababcbut again its restricted to use ternary operatornow i am not getting any idea how to do this,['c'] +183745,maven failing to download jar dependencies i have a very simple default application that i have created to test my eclipse indigomaven v301 setup on my windows 7 machine the hello world app runs fine from eclipsenow from the command line i am trying to test with mvn installat which point i see maven download a large series of dependencies for some reason though it will get stuck downloading one and will just stop part way through it is not at the same point each time but it is currently consistently the same jar file egif i download this file from a browser it works perfectly quite fast in fact now if i manually copy that downloaded file to the appropriate directory in my m2 repository directory the install continues to download dependencies until it hits another one at random which it stops atheres my pom although i am not sure it will help as it is so basic and seems to work fine with a mvn compileproject xmlns xmlnsxsi xsischemalocation modelversion400modelversion groupidcomkyeemagroupid artifactidqserverartifactid version001snapshotversion packagingjarpackaging nameqservername urlurl properties projectbuildsourceencodingutf8projectbuildsourceencoding properties dependencies dependency groupidjunitgroupid artifactidjunitartifactid version381version scopetestscope dependency dependenciesprojectheres some debug output referencing some dummy jar fileinfo surefire report directory cworkspaceqservertargetsurefirereportsdebug setting system property userdircworkspaceqserverdebug setting system property localrepositorycusersandrem2repositorydebug setting system property basedircworkspaceqserverdebug using jvm cprogram filesjavajdk170jrebinjavadebug dummydummyjar10 selected for nulldebug orgapachemavensurefiresurefirebooterjar272compile selected for compiledebug orgapachemavensurefiresurefireapijar272compile selected for compiledebug adding to surefire booter test classpath cusersandrem2repositoryorgapachemavensurefiresurefirebooter272surefirebooter272jar scope compiledebug adding to surefire booter test classpath cusersandrem2repositoryorgapachemavensurefiresurefireapi272surefireapi272jar scope compiledebug dummydummyjar10 selected for nullwarning missing pom for orgapachemavensurefiresurefirejunit3jar272 error resolving project artifact failure to find orgapachemavensurefiresurefirejunit3pom272 in was cached in the local repository resolution will not be reattempted until the update interval of ibiblioorg has elapsed or updates are forced for project orgapachemavensurefiresurefirejunit3pom272debug orgapachemavensurefiresurefirejunit3jar272test selected for testinfo info build failureinfo info total time 0626sinfo finished at tue aug 16 131842 pdt 2011info final memory 8m154minfo error failed to execute goal orgapachemavenpluginsmavensurefireplugin272test defaulttest on project qserver error to resolving surefire provider dependency missingerror error 1 orgapachemavensurefiresurefirejunit3jar272error error try downloading the file manually from the project websiteerror error then install it using the commanderror mvn installinstallfile dgroupidorgapachemavensurefire dartifactidsurefirejunit3 dversion272 dpackagingjar dfilepathtofileerror error alternatively if you host your own repository you can deploy the file thereerror mvn deploydeployfile dgroupidorgapachemavensurefire dartifactidsurefirejunit3 dversion272 dpackagingjar dfilepathtofile durlurl drepositoryididerror error path to dependencyerror 1 dummydummyjar10error 2 orgapachemavensurefiresurefirejunit3jar272error error error 1 required artifact is missingerror error for artifacterror dummydummyjar10error error from the specified remote repositorieserror ibiblioorg releasestrue snapshotsfalse,['java'] +183746,how to send a pdf file directly to the printer using javascript how to send a pdf file directly to the printer using javascripti found two answers in a forumembed srcvehinvcpdf id pdf1 namepdf1 hiddena onclickdocumentgetelementbyidpdf1printwithdialog stylecursorhandprint fileaandobject id pdf2 namepdf2 classidclsidca8a9780280d11cfa24d4553540 width364 height290 param namesrc valuefilepdfobjecta onclickdocumentpdf2printwithdialogprint filea but my problem is that it just works on ie and doesnt work in firefox or chromeis there any solution for this,"['javascript', 'html']" +183754,how to access webcam from html5 i want access webcam from html5 for register and save a video file for playing later is this possible,['javascript'] +183763,how can you thisplay the maven dependency tree for the plugins in your project a common maven debugging technique is to use mvn dependencytree to view the graph of project dependencies however this list shows the project dependencies not the plugin dependency tree for each plugin is there some way to do this from a project,['java'] +183772,converting exception to a string in python 3 does anyone have an idea why this python 32 code try raise exceptionxexcept exception as e printerror 0formatstreworks without problem apart of unicode encoding in windows shell but this try raise exceptionxexcept exception as e printerror 0formatstre encoding utf8throws typeerror coercing to str need bytes bytearray or bufferlike object exception found how to convert an error to a string with custom encodingeditit does not works either if there is u2019 in messagetry raise exceptionmsgexcept exception as e b bytesstre encoding utf8 printerror 0formatstrb encoding utf8but why cannot str convert an exception internally to bytes,['python'] +183782,iphone performselector with bool parameter is there any way to send bool in selector self performselectorselectordosomething withobjectyes afterdelay15or i should use nsinvocation could somebody write a sample please,['iphone'] +183799,gearman with multiple servers and php workers i am having a problem with gearman workers running on multiple servers which i cannot seem to solvethe problem occurs when a worker server is taken offline rather than the worker process being cancelled and causes all other worker processes to error and failexample with just 1 client and 2 workers clientclient new gearmanclient clientaddserver 1921681200clientaddserver 1921681201job clientdo generate tile serialize arrdataworkerworker new gearmanworker workeraddserver 1921681200workeraddserver 1921681201workeraddfunction generate tile generate tilewhile 1 if workerwork switch workerreturncode default echo error workerreturncode workererror n break function generate tile job the worker code is being run on 2 separate servers when every server is up and running both workers execute jobs as expected when one of the worker processes is cancelled the other worker executes all jobs as expectedhowever when the server with the cancelled worker process is shutdown and taken completely offline requests to the client script hang and the remaining worker process does not pick up any jobsi get the following set of errors from the remaining worker processerror 46 gearman con waittimeout reachederror 46 gearman con waittimeout reachederror 4 gearman con flushwrite110error 46 gearman con waittimeout reachederror 4 gearman con flushwrite113error 4 gearman con flushwrite113error 4 gearman con flushwrite113when i startup the other server not starting the worker process on it the remaining worker process immediately jumps into life and executes any remaining jobsit seems clear to me that i need some code in the worker process to cope with any servers that may be offline however i cannot see how to do thismany thanksandy,['php'] +183800,install an apk file from command prompt i want to install a file using the windows command line first i want to build after compiling all the jar files to create an apk file for an android application without using eclipsedoes anyone know how this can be done without the use of eclipse only by making use of command line,['android'] +183808,over populating logcat causes windows to freeze until hard reboot is performed the title speak for itself but i would add some pointers i have noticed along the wayi would like anyone which also experience the end result while developing for android to try to reproduce this and see if this scenario is really the case and if someone have a solution that would make me very happy it is extremely frustrating that i need to hard reboot my computer while developingthe crash happens when logcat is over populated by over populated i mean that from a point in time if you would leave a device connected in debug mode for a while and you would look at the logcat view it would thisplay only the new delta lines added to the log in the past short interval of about 2 secif you would pay attention while the logcat is over populated the device which is been debugged response slowly to user interactionthis can be your indication that the logcat is over populated while testing your application and perform other actions ridiculously slow if you would leave the device connected and more logs would be added there is a short interval 510 sec where eclipse starts to behave weird and after that there is nothing you can do windows 7 freezes and only hard reboot allows you to get back to worki can reproduce this every time if i would just leave a device connected in debug mode with an application runningi have googled this and came up with nothing i assume that if me and my colleagues encounter thiswe have the same eclipse setup then other should also experience this so before posting a bug i would like to confirm thisdetailswindows 7eclipse 36adt 10v201102162101104271 latest for todaythanksadam,['android'] +183818,indenting multiline labels i have the following automaticallygenerated htmlwhat is the advised way using css to indent the label so that there is some white space under the radio button,['css'] +183822,wia scanning via feeder wia scanning via feederhere is my device propertiesdocument handling select 1 2 is for flatbed and 1 is for the feederhere is my item page propertieshorizontal resolution 150vertical resolution 150horizontal extent 500 i want to get it first to work then i will play with the extentsvertical extent 500bits per pixel 8current intent 4i got everything running smoothly if i set the document handling select to 2 when i set it to 1 and ran it just before i say itemtransfer or itemtransferbmpjpegpngguid i get the exception value does not fall within the expected rangethis is so annoying what value i have googled the web and i could only find a little information but it is not much of help,['c#'] +183832,show android notification every five minutes i want to know how to set time for notification i want to set notification every five minutesso help me do thatpublic class firstactivity extends activity private static final int hello id 1 public static final int flag auto cancel 0enter code here override protected void oncreatebundle savedinstancestate todo autogenerated method stub superoncreatesavedinstancestate setcontentviewrlayoutfirstactivity string ns contextnotification service notificationmanager mnotificationmanager notificationmanager getsystemservicens int icon rdrawableicon charsequence tickertext hello long when systemcurrenttimemillis notification notification new notificationicon tickertext when remoteviews contentview new remoteviewsgetpackagename rlayoutstatusbarnotification contentviewsetimageviewresourceridimage rdrawableicon contentviewsettextviewtextridtext hello this message is in a custom expanded view notificationcontentview contentview notificationflags notificationdefault lights notificationflag auto cancel intent notificationintent new intentgetapplicationcontext secondactivityclass pendingintent contentintent pendingintentgetactivitythis 0 notificationintent 0 pendingintent contentintent pendingintentgetactivitythis 0 notificationintent 0 notificationcontentintent contentintent mnotificationmanagernotifyhello id notification,['android'] +183842,windowlocationhref and windowopen methods in javascript what is the difference between windowlocationhref and windowopen methods in javascript,['javascript'] +183856,cfg peg used for code completion i am wondering if it is possible to use a cfg or peg grammar as a basis for code completion directly without modification i have heard that code completion is in ides is sometimes manipulated and massaged or even hard coded so that it performs betteri want to code complete on a small dsl so i fully understand that a grammar cannot help a code completion system with knowledge of library functions etcas far as i am aware the parser itself needs to at least provide a system for querying what it expects nextin particular i am interested in a javascript code completion solution using pegjsor jison,['javascript'] +183870,jquery location href possible duplicatehow can i make a redirect page in jqueryjavascript i remember there is a redirect function in jqueryit was likelocationhrefbut what was it exactly i could not remember and cannot find on google,"['javascript', 'jquery']" +183871,how to convert number of week into date given a year and calendar week how can i get the tuesday of that week as a date,"['mysql', 'sql']" +183875,cardlayouts how can i tell which card is visible i have been looking through the documentation for the swing cardlayout and there does not appear to be any way to determine which card is currently showing backed in to the class yet there must be a way to ask the layout which card it is currently showing rightdue to project constraints i cannot simply extend it and add this functionality to a subclass so if there is not such a function does that mean i am stuck tracking the components state external to the component yuck or is there some other option buried somewhere deep in swing,['java'] +183879,in python when you pass internally defined functions into other functions how does it keep the variables for example why does this workdef func1func1var def innerfuncinnerfuncvar if func1var 1 print innerfuncvar else print 5 func2innerfuncdef func2function function9when innerfunc is called in func2 how does it know the values of func1var,['python'] +183882,django static structure i am trying to understand the static structure django 13 tries to pursuei have a project with this structureproject someapp static someapp css etcetera modelspy viewspy urlspy urlspy managepy settingspynow i wish to overwrite the django admin so i have to set these settings in settingspy which i did like below basepath is the shortcut path to the current directory absolute path to the directory static files should be collected to do not put anything in this directory yourself store your static files in apps static subdirectories and in staticfiles dirs example homemediamedialawrencecomstaticstatic root base pathstatic url prefix for static files example static url static url prefix for admin static files css javascript and images make sure to use a trailing slash examples staticadminadmin media prefix staticadmin additional locations of static filesstaticfiles dirs put strings here like homehtmlstatic or cwdjangostatic always use forward slashes even on windows do not forget to use absolute paths not relative pathsif i use the managepy command collectstatic it collects all static files including the admin files in a directory static as expected within the main project dirhowever it is content is not served yet until i add that directory to the staticfiles dirs tuple however then i have to change the static root directory setting because otherwise i will get the error they cannot be the samei think i am overlooking the obvious because what i have to do to make it work seems redundant,['python'] +183893,bad use of templates i understand that templates kinda get blamed for binary bloat i also understand that a template is just a pattern i dont really understand the nuts and bolts as it wherealot of time i see code like the following where it returns a base class pointer class gameobjectpublic component getcomponentstdstring keystatic castcompobjgetcomponentcomprather than making the method a template methodclass gameobjectpublic templatetypename t t getcomponentstdstring keyobjgetcomponentcompcompis this stylistic or is there a performance loss associated with the templates,['c++'] +183902,java how to call super method from inner inplace class i have base class foo with method spam and class bar which overrides spam i need to call spam of base class in method of some callback object which is defined inplacepublic class foo public void spam public class bar extends foo override public void spam objectwhichrequirecallbacknew callback override public void oncallback superspam this code is not working because super is related to callback not bar class is it possible to call super method from object defined inplace,['java'] +183909,how to change text encoding of localizablestrings file in xcode 4 i am learning how to localize the strings in my project and i am using xcode 4 i have generated the base localizablestrings file and i want to import this file changing its encoding from utf16 to unicode utf16 so that the text in the file is readable within xcode if i strate import this file when i select it within xcode the text shows up as gibberish in xcode 3 when you drag the localizablestrings into your project the dialog box which appears gives you the option to change the text encoding but this is not the case in xcode 4 does anyone know a way around this,"['iphone', 'ios']" +183911,tools to detect false sharing in a cc application are there any tools that detect and report false sharing for applications written in c or c,"['c++', 'c']" +183944,convert raw grayscale binary to jpeg i have c language source code for an embedded system containing arrays of data for an 8bit per pixel grayscale image i am in charge of documenting the software and i would like to convert this source code to a jpeg image filehere is a code sampleconst unsigned char grayscale image 0 0 0 0 0 0 0 74 106 159 159 159 159 159 159 159 159 159 159 159 159 159 159 159 159 159 159 159 159 159 159 159 146 93 39 0 0 0 0 0 0 0 0 0 0 0 const unsigned int height 41const unsigned int width 20here are my questions yes plural what applications do you recommend for converting this source file to jpegcan gimp or paint import a csv file of dataif i write this custom application what java libraries exist forjpegwhat libraries exist in c for accomplishing this taski have the following resources at my thisposal ms visio 2010 gimp paint java eclipse ms visual studio 2010 professional wxwidgets wxframebuilder cygwini can write the custom application in c java c or cthanks for your advice,"['c#', 'java']" +183955,webapp2 jinja2 how can i get uri for working in jinja2views how can i add pass modelspecific urls to the templatelet us say i want to build an editlinki would guess using the uri for function would be an easy approachbut the following gives me undefinederror webapp2 is undefined webapp2uri foreditgreeting greetingkeyid or should i prepare these in the mainpagerequesthandlerif so i do not know how to add them to each greetingthe following codeexample is taken fromcontrollerhandlerclass mainpagewebapp2requesthandler def getself guestbook nameselfrequestgetguestbook name greetings query greetingallancestor guestbook keyguestbook nameorderdate greetings greetings queryfetch10 if usersget current user url userscreate logout urlselfrequesturi url linktext logout else url userscreate login urlselfrequesturi url linktext login template values greetings greetings url url url linktext url linktext path ospathjoinospathdirname file indexhtml selfresponseoutwritetemplaterenderpath template valuestemplateviewhtml body for greeting in greetings if greetingauthor b greetingauthornickname b wrote else an anonymous person wrote endif blockquote greetingcontentescape blockquote endfor form actionsign methodpost divtextarea namecontent rows3 cols60textareadiv divinput typesubmit valuesign guestbookdiv form a href url url linktext a bodyhtmlthe class basehandler is the class all handlers inherit fromi tried the following as moraes suggestedi still get value selffuncobjfile cuserstimme04pythonhellowebapphandlersbasehandlerpy line 23 in jinja2return jinja2get jinja2factoryselfjinja2 factoryfile cuserstimme04pythonhellowebappwebapp2 extrasjinja2py line 212 in get jinja2jinja2 appregistrykey factoryapptypeerror jinja2 factory takes exactly 1 argument 2 givenimport webapp2from webapp2 extras import jinja2class basehandlerwebapp2requesthandler def jinja2 factoryapp j jinja2jinja2app jenvironmentfiltersupdate set filters jenvironmentglobalsupdate set global variables uri for webapp2uri for return j webapp2cached property def jinja2self returns a jinja2 renderer cached in the app registry return jinja2get jinja2factoryselfjinja2 factory def render responseself template context renders a template and writes the result to the response rv selfjinja2render template template context selfresponsewriterv,['python'] +183959,what is the proper term for nonfunctionpointers in c in c you can pass in function types which are like function pointers but they are just the type of the function and not a pointer to it for exampletemplate typename t class mytemplateclass and latermytemplateclassvoid int int mtcwhat is the proper name for this form is this a function typeupdatei edited my example to be a little more clear however keep in mind the main part of the sample i am trying to point out is the void int int part,['c++'] +183960,can jquerydata cause a memory leak would the following piece of code create a memory leakaccording to the jquery documentation use of the data function avoids memory leaks it would be useful to confirm whether the following is safevar myclass functionel store reference of element in object thiselement el store reference of object in elementsomethingdataobj new myclasomething,"['javascript', 'jquery']" +183976,setting default compiler in cmake i am using cmake version 28 on winxp sp3 whenever i run my cmakelists script by default cmake use visual studio 10 compiler i have tried to doset cmake cxx compiler cmingwbing without success how can i set mingw as my default compiler so that i do not have to worry about setting compiler in the cmakelists,['c++'] +183985,how do you duplicate freeze pane functionality on an html table i have a widget in an aspnet project that i am developing for my job it has to be 300 pixels wide and cannot be any wider unfortunately what they want has proven to be fairly complicated for such a small widget here is what i have right nowas you can see this is a jquery ui accordion control as each accordion pane expands an ajax call is made to load its contents asynchronously right now it spits out an html table containing the desired data the table is within a div with style overflow auto so that we get scroll bars on the bottom and the rightmy problem is that i want some pretty custom functionality like the freeze pane ability in excel when scrolling left and right i want all rows including header to scroll left and right except for the far left column product name like thiswhen scrolling up and down i want all columns including the left column to scroll up and down except for the header row like thiswhat is the best way to achieve this functionality or is there a way,"['c#', 'javascript', 'jquery', 'asp.net', 'html']" +183993,clickonce setupexe fails but the application file works fine when using a windows share for deployment i am getting the error of systemdeploymentapplicationdeploymentdownloadexception when i try to run setupexe for my clickonce application if run it over the network from its original location it works fine but if i copy setupexe from the path on the server i get the errorcan not download application the application is missing required filesi need the setup as it installs some prerequisites net 4 that the end user may not haveclicking the details button from the error window gives the following informationplatform version info windows 61760165536 win32nt common language runtime 4030319237 systemdeploymentdll 40303191 rtmrel0303190100 clrdll 4030319237 rtmgdr0303192300 dfdlldll 40303191 rtmrel0303190100 dfshimdll 40311060 main0311060sources deployment url filecuserssrchamberlaindownloadscontractflowtoolapplicationerror summary below is a summary of the errors details of these errors are listed later in the log activation of cuserssrchamberlaindownloadscontractflowtoolapplication resulted in exception following failure messages were detected downloading filecuserssrchamberlaindownloadscontractflowtoolapplication did not succeed could not find file cuserssrchamberlaindownloadscontractflowtoolapplication could not find file cuserssrchamberlaindownloadscontractflowtoolapplication could not find file cuserssrchamberlaindownloadscontractflowtoolapplicationcomponent store transaction failure summary no transaction error was detectedwarnings there were no warnings during this operationoperation progress status 8162011 122326 pm activation of cuserssrchamberlaindownloadscontractflowtoolapplication has startederror details following errors were detected during this operation 8162011 122326 pm systemdeploymentapplicationdeploymentdownloadexception unknown subtype downloading filecuserssrchamberlaindownloadscontractflowtoolapplication did not succeed source systemdeployment stack trace at systemdeploymentapplicationsystemnetdownloaderdownloadsinglefiledownloadqueueitem next at systemdeploymentapplicationsystemnetdownloaderdownloadallfiles at systemdeploymentapplicationfiledownloaderdownloadsubscriptionstate substate at systemdeploymentapplicationdownloadmanagerdownloadmanifestasrawfileuri sourceuri string targetpath idownloadnotification notification downloadoptions options serverinformation serverinformation at systemdeploymentapplicationdownloadmanagerdownloaddeploymentmanifestdirectbypasubscriptionstore substore uri sourceuri tempfile tempfile subscriptionstate substate idownloadnotification notification downloadoptions options serverinformation serverinformation at systemdeploymentapplicationdownloadmanagerdownloaddeploymentmanifestbypasubscriptionstore substore uri sourceuri tempfile tempfile subscriptionstate substate idownloadnotification notification downloadoptions options at systemdeploymentapplicationapplicationactivatorperformdeploymentactivationuri activationuri boolean isshortcut string textualsubid string deploymentproviderurlfromextension browsersettings browsersettings string errorpageurl at systemdeploymentapplicationapplicationactivatoractivatedeploymentworkerobject state inner exception systemnetwebexception could not find file cuserssrchamberlaindownloadscontractflowtoolapplication source system stack trace at systemnetfilewebrequestendgetresponseiasyncresult asyncresult at systemnetfilewebrequestgetresponse at systemdeploymentapplicationsystemnetdownloaderdownloadsinglefiledownloadqueueitem next inner exception systemnetwebexception could not find file cuserssrchamberlaindownloadscontractflowtoolapplication source system stack trace at systemnetfilewebresponsectorfilewebrequest request uri uri fileaccess access boolean asynchint at systemnetfilewebrequestgetresponsecallbackobject state inner exception systemiofilenotfoundexception could not find file cuserssrchamberlaindownloadscontractflowtoolapplication source mscorlib stack trace at systemio errorwinioerrorint32 errorcode string maybefullpath at systemiofilestreaminitstring path filemode mode fileaccess access int32 rights boolean userights fileshare share int32 buffersize fileoptions options security attributes secattrs string msgpath boolean bfromproxy boolean uselongpath at systemiofilestreamctorstring path filemode mode fileaccess access fileshare share int32 buffersize fileoptions options string msgpath boolean bfromproxy at systemiofilestreamctorstring path filemode mode fileaccess access fileshare share int32 buffersize boolean useasync at systemnetfilewebstreamctorfilewebrequest request string path filemode mode fileaccess access fileshare sharing int32 length boolean async at systemnetfilewebresponsectorfilewebrequest request uri uri fileaccess access boolean asynchintcomponent store transaction details no transaction information is availablethe root of the problem is it is trying to download its files from the same path as setupexe is run from filecuserssrchamberlaindownloads in this case instead of the actual deployment url fs1contractflowtooli have seen a few solutions but all of them tell me the solution is to change the mime type on iis iis is not installed on the server that is hosting the fileswhat else can be done to fix this besides change the mime typesupdatesee the second post in this thread for some test cases i ran the summary is it appears that the setupexe file uses the working directory to download its files as it works fine when i run the exe file over the network however it fails if i copy the exe to my local thiskhow do i resolve this issue other than tell people to just run it from the network pathupdate2looking at the setupexe file with a hex editor i could not find my install path anywhere in it when i changed the install path to i was able to find it easilyis it a visual studio bug that it does not save the publishing locationinstall path if you are using a unc path,['.net'] +184024,how can i decrypt an encrypted mcrypt rijndael 256 value in c that was encrypted by mcrypt in php i am trying to read a base64encoded value from a database table managed on the linux side in that table there is a column called first name on the linux side i can decrypt this easily by using the following command in phpdata mcrypt decryptmcrypt rijndael 256 patient fn salt base64 decodeh6xmkhvwvdd88thclikjjlisgzibk3ctnvyqmlnhpo mcrypt mode ecbhowever i try as much as i can to duplicate this logic on the c side and all i get is gibberishmy c code is below i hope you have some suggestions because i ran out of ideas byte ciphertext convertfrombase64stringh6xmkhvwvdd88thclikjjlisgzibk3ctnvyqmlnhpobyte key encodingutf8getbytespatient fn saltarrayresizeref key 32byte iv new byte32string fname utilitiesdecryptciphertext key ivpublic static string decryptbyte ciphertext byte key byte iv check arguments if ciphertext null ciphertextlength 0 throw new argumentnullexceptionciphertext if key null keylength 0 throw new argumentnullexceptionkey if iv null ivlength 0 throw new argumentnullexceptionkey tdeclare the streams used to decrypt to an in memory array of bytes memorystream msdecrypt null cryptostream csdecrypt null streamreader srdecrypt null declare the aesmanaged object used to decrypt the data rijndaelmanaged rj new rijndaelmanaged declare the string used to hold the decrypted text string plaintext null try create an aesmanaged object with the specified key and iv rjmode ciphermodeecb rjblocksize 256 rjkeysize 256 rjpadding paddingmodezeros rjkey key rjgenerateiv rjiv iv create a decrytor to perform the stream transform icryptotransform decryptor rjcreatedecryptorrjkey rjiv create the streams used for decryption msdecrypt new memorystreamciphertext csdecrypt new cryptostreammsdecrypt decryptor cryptostreammoderead srdecrypt new streamreadercsdecrypt read the decrypted bytes from the decrypting stream and place them in a string plaintext srdecryptreadtoend finally clean things up close the streams if srdecrypt null srdecryptclose if csdecrypt null csdecryptclose if msdecrypt null msdecryptclose clear the aesmanaged object if rj null rjclear return plaintext,"['c#', 'php']" +184028,jquery getscript i am currently stuck using several javascript libraries that must load in a very specific order since jquerys getscript is asynchronous it starts downloading all of the scripts very quickly and as they finish executes them since they do not execute in order i get multiple errors coming from the librariesunfortunately i cannot change or modify any of these libraries what i am attempting to do is use a method that downloads a javascript library and in the callback have it call itself until it is finished loading all of the librariesthis works for the first file when the second file comes around it loses context inside of the callback and i cannot call my recursive method anymoreany ideasa paireddown version of the codefunction loadfiles completedcallback var files getfiles this is an array of js files to load var currentfileindex 0 function processfile file getscriptfilecurrentfileindex proxyfunction currentfileindex if currentfileindex fileslength completedcallback else processfilefilescurrentfileindex this processfilefilescurrentfileindex,"['javascript', 'jquery']" +184040,css vertically align text in header i am trying to vertically align text in my header and am having some trouble attached is an image of my starting pointthe header has a set height of 141px and everything in that header should be right in the middle even the name of website here so if that name changes and only takes up 1 line or maybe 3 lines it will all be in the same placenote this is for multiple websites which are being generated dynamically so that is why i cannot just position it with a margintop because the names will be different some might take up a few lines and some might take up multiple linesi took out my attempts to vertically align it from what i searched online because nothing is working so this is the code from my starting point htmldiv idheader h1name of website hereh1 h3call todaybr spanx xspanh3 p123 main stbr city state zippdivcssheaderheight141pxheader h1floatleftfontsize17emwidth200pxtextaligncenterlineheight26pxheader h3floatlefttextaligncentercolore62520fontsize17emlineheight26pxfontstyleitalicmargin0 0 0 95pxheader h3 spanfontsize12emheader pfloatrightcolor2a5091fontsize13emfontstyleitalicfontweightboldlineheight20pxtextalignrightthank you,['css'] +184044,fill your tables with junk data i am lazy sometimes excruciatingly lazy but hey ironically this is how we get stuff done righthad a simple idea that may or not be out there if it is i would like to know and if not perhaps i will make it when working with my mssql database sometimes i want to test the performance of various transactions over tables and view and procedures etc does anyone know if there is a way to fill a table up with x rows of junk data mearly to experiment withone could simple enoughinsert into tableselect columns from source tableor do some kind ofdeclare count int set count 0while count xbegininsert into tablecolumn listvaluesvalues could include the count here as a primary keyset count count 1endbut it seems like there is or should already be something out there any ideas,['sql'] +184045,ms word automation in c unable to cast object of type systemstring to type systemstring i use this code to get a string array of headings used in a ms word 2007 document docxdynamic arr documentgetcrossreferenceitemswdreferencetypewdreftypeheadingusing the debugger i see that arr is dynamically assigned a string array with titles of all my headings in the document about 40 entries so far so goodthen i want to access the strings but no matter how i do it i get the following exceptioninvalidcastexception unable to cast object of type systemstring to type systemstringi have tried different ways of accessing the stringsby indexstring arr elem arr1by casting to an ienumerableienumerable list ienumerablearrby using a simple foreach loopforeach string str in arr consolewritelinestrhowever no matter what i try i always end up with the same exception as shown abovecan anyone explain what i am missing here what i am doing wrong and especially string what does it mean,"['c#', '.net']" +184055,how to detect rails environment inside whenever this question will probably only make sense if you know about the whenever gem for creating cron jobs for my app i want to use whenever in all the environments including testing and developmentmy schedulerb looks like thisset output error pathlogerrorlog standard pathlogcronlogset environment railsenvto symevery 5minutes do rake dbactivitysynchronizeendbut it fails on railsenvto sym and the same stands for rails envhomemariusrvmgemsruby192p290uxologemswhenever068libwheneverjob listrb21in eval uninitialized constant wheneverjoblistrails nameerror from homemariusrvmgemsruby192p290uxologemswhenever068libwheneverjob listrb21in eval from homemariusrvmgemsruby192p290uxologemswhenever068libwheneverjob listrb21in initialize from homemariusrvmgemsruby192p290uxologemswhenever068libwheneverrb15in new from homemariusrvmgemsruby192p290uxologemswhenever068libwheneverrb15in cron from homemariusrvmgemsruby192p290uxologemswhenever068libwhenevercommand linerb41in run from homemariusrvmgemsruby192p290uxologemswhenever068libwhenevercommand linerb8in execute from homemariusrvmgemsruby192p290uxologemswhenever068binwhenever38in top required from homemariusrvmgemsruby192p290uxolobinwhenever19in load from homemariusrvmgemsruby192p290uxolobinwhenever19in mainso my question basically boils down to how do i access the current environment orwhat should i do to use whenever in all the environments,['ruby-on-rails'] +184064,safari and chrome ignore minwidth css propery why do safari and chrome ignore minwidth css property example this works in ie and firefox but not in safari and chrome,['css'] +184069,should i subclass ccsprite ccnode or nsobject i see that certain texts always seem to subclass ccsprite i read somewhere that it is not good to do that and that it is better to start with something basic i wanted to find out what the pro game developers do in terms of game structure that is subclass ccsprite or add ccsprite in a nsobject class etci hope my question makes sense,['ios'] +184071,what is the difference between a readwrite property and a nonatomic assign property i have seen readwrite on int bool etc same as nonatomic assign i am some what confused on this i do know that on non native objects we typically do nonatomic retain,"['iphone', 'ios', 'objective-c']" +184095,java enumeration from set i have a simple collections question i have a setstring object i want an enumeration of the strings in that set what is the cleanestbest way to go about it,['java'] +184100,indexeddb fuzzy search ok first of all sorry for my englishi am working in a web project that show suggests when i type something in the inputbox but i want to use indexeddb to improve the query speed in firefoxwith websql i have this sentencedbtransactionfunction tx var sql select column1 column2 from table where column1 like order by sortcolumn desc limit 6 txexecutesqlsql searchterm functiontx rs process code here i want to do same thing with indexeddb and i have this codedbtransactiontable readonly objectstoretable indexsortcolumn opencursornull prev onsuccess function e e e event var cursor etargetresult if cursor if cursorvaluecolumn1substr0 searchtermlength searchterm process code here else cursorcontinue but there is too slow and my code is buggy i want to know is there a better way to do thisthank for reply,['javascript'] +184122,convert rgb to ycbcr c code i need to convert rgb to ycbcr for my final project and i trying to do this way i am programming in c autor vinicius garcia data 09ago2011 funaao que converte um pixel rgb em ycbcr param int r valor do pixel no canal red param int g valor do pixel no canal green param int b valor do pixel no canal blue return int vetor de inteiros com os valores h s e v calculados nesta ordem int converter rgb para ycbcrint r int g int b int ycbcr int malloc3 sizeofint double delta 1280 constante necessaria para o calculo da conversao de cor double y 0299 r 0587 g 0114 b double cb b y 0564 delta double cr r y 0713 delta ycbcr0 int y ycbcr1 int cb ycbcr2 int cr return ycbcrbut it does not work for mei was comparing with cvcvtcolor from opencv library and the results does not match r 88 g 76 b 78cvcvtcolor y 80 cb 127 cr 134myfunction y 382 cb 132 cr 132 cr and cr are always equali really need help with this i trying do this for a long time and i could not find any answer for my doubtdo you guys think i am getting the rgb values wrong i am doing this wayuchar b cv image elemimg rgb uchar linha coluna 3uchar g cv image elemimg rgb uchar linha coluna 3 1uchar r cv image elemimg rgb uchar linha coluna 3 2then i am calling my conversion function this wayconverter rgb para ycbcrr g bmy function expects int r int g int b but i am passing uchar b uchar g uchar r its that ok,['c'] +184127,removing logging with proguard does not remove the strings being logged possible duplicateremoving unused strings during proguard optimisation i have an android application with dozens of logging statements i would prefer they wouldnt appear in the release version so i used proguard with something like this in the proguardcfg fileassumenosideeffects class androidutillog public static dbut the problem is that there are a lot of logdsomething is something and although the logd statement is being removed from the bytecode the strings are still thereso following this answer i created a simple wrapper class something along the lines ofpublic class mylogger public static void dobject msgs stringbuilder log new stringbuilder forobject msg msgs logappendmsgtostring logdtag logtostring then i edited my proguardcfgassumenosideeffects class mypackagemylogger public static dbut the strings are still found in the generated bytecodeother than this i am using the standard proguardcfg provided by the android sdk am i doing something wrongedit after examining the generated bytecode i saw that the strings were there but they were not being appended one to another as i thought they were being stored in an array why to pass them as variable parameters to my method it looks like proguard does not like that so i modified my logger class like thispublic static void dobject a logapublic static void dobject a object b loga b i had to put like seven d methods private static void logobject msgs same as beforeit is ugly but now the strings are nowhere in the bytecodeis this some kind of buglimitation of proguard or is it just me not understanding how it works,['android'] +184131,how to know if a variable is a tuple a string or an integer i am trying to figure out a type mismatch while adding a string to another string in a concatenate operationbasically the error returned is a type error cannot concatenate string and tuple so i would like to figure out where did i assigned a value as tuple instead than stringall the values that i assign are strings so i gotta figure out where the tuple is coming from so i was hoping that there is a way in python to find out what is contained inside a variable and what type is itso far using pdb i was able to check the content of the variables and i get correctly the values that i would expect but i would like to know also the type of the variable by logic if the compiler is able to raise a type error it means that somehow is able to know what is inside a variable and if it is compatible with the operation to performso there must be a way to get that valueflag outis there any way to print out the type of a variable in pythonbtw i tried to change all my variables to be explicitly strings but is not feasible to force str myvar so i cannot just cast strings types everywhere i use stringsthanks,['python'] +184147,why does this javascript block in nodejs i have the following simple http server using nodejsvar http requirehttpvar server httpcreateserverfunctionreq res var counter 0 forvar i 1 i 30 i httpget host wgooglecom functionr counter reswriteresponse counter rstatuscode n ifcounter 30 resend serverlisten80when i curl into my local host on port 80 i do get the expected result ofresponse 1 200response 2 200response 3 200response 30 200but when i try to curl in from another terminal while the first process is running i see the console hang and wait for the first process to finish entirely before it starts receiving the same outputmy understanding was that since this is async code using callbacks that node could handle multiple requests in sync by processing them on the next tick of the event loop and in fact i even watched a video of ryan dahl doing something similar with a hello world example whats in my code that is making the server block,['javascript'] +184214,how to call an aspnet c method using javascript does anyone know how to call a serverside c method using javascript what i need to do is to stop imports if cancel is chosen or to continue importing if ok is chosen i am using visual studio 2010 and c as my programming lanaguagethis is my codeprivate void alertwithconfirmation responsewrite script typetextjavascript if windowconfirmimport is currently in progress do you want to continue with importation if yes choose ok if no choose cancel windowalertimports have been cancelled else windowalertimports are still in progress script,"['c#', 'javascript', 'asp.net']" +184224,enum in a namespace is there a point of doing somthing like thisnamespace status enum status ok error and use it like that statusokor should i do thisenum status status ok status errorand use it like this status okupdate with c11 you now should do thisenum class status ok errorand use like this statusok,['c++'] +184236,get right position of element jquery or javascript i wish to get the right position of an element in jquery i have tried attrright and i have read the api document regarding positionright which is non existent i believeis an example i wish to alert the right value for,"['javascript', 'jquery']" +184281,xmlhttprequest cannot load origin null is not allowed by accesscontrolalloworigin i have a codehtml file containing the following code ajax type post datatype jsonp url path success functionmsg var e documentcreateelementdiv eid ads documentbodyappendchilde adshtmlmsg when i open the codehtml file in the browser it gives an errorxmlhttprequest cannot load file origin null is not allowed by accesscontrolalloworiginplease help me how to avoid this problem,"['php', 'javascript']" +184315,c enum of long values i was wondering why this declarationpublic enum ecountry long none canada unitedstatesrequires a cast for any of its valueslong id ecountrycanada error cannot implicitly convert type ecountry to long an explicit conversion exists are you missing a castand is there any way to get a long value directly from the enum besides castingthis would not work either for examplepublic enum ecountry long none 0l canada 1l unitedstates2l,['c#'] +184320,default values for array arguments just playing around a little with c what i really want to do is to be able to setup a function with default values defined for an array or pointer argument to keep things simple let us just use an array like sovoid experimentachar a3 a b cthe compiler llvm gcc 42 with gnu99 complains expected expression that is quite obtuse but i was told by colleagues that this is happening because the value i am trying to assign is statically allocated whereas the variable i am trying to assign it to a3 is autobut i am not completely sure if that is the case since i am able to do thisvoid experimentbchar a3 abc and the compiler merely warns me that stringliteral to char conversion is deprecated i do not understand how abc differs fundamentally from abc in order to cause this thiscrepancy any insight is much appreciated,['c++'] +184327,php shell exec vs exec i am struggling to understand the difference between shell exec and execi have always used exec to execute server side commands when would i use shell execis shell exec just a shorthand for exec it seems to be the same thing with fewer parameters,['php'] +184346,how do a read a xdebug profile in webgrind i have setup xdebug and webgrind and i have generated a profile so i can start improving the speed of my code execution i have thisplayed the profile in webgrind but i have not got a clue what any of it means all the googling i have done does not really explain any of it eithercould someone please explain the basics of reading a webgrind reportinvocation counttotal self costtotal inclusive costwhat the different colours meanwhat the coloured bar meanscallstotal call costcount,['php'] +184358,linq to objects predicate builder what is the best way to do a conditional query using linq to objectsnot linq to sqlcurrently i am using the predicate builder found here and passing the compiled predicate to the ienumerablewhere and it seems to work nicelyexample code of what i want to solve eg i have this string keyword1 test1 string keyword2 test3 ienumerabletestobject tests new listtestobject new testobject name1 test1 name2 test1 new testobject name1 test2 name2 test2 new testobject name1 test3 name2 test3 if stringisnulloremptykeyword1 stringisnulloremptykeyword2 tests testswheree ename1containskeyword1 else if stringisnulloremptykeyword2 stringisnulloremptykeyword1 tests testswheree ename2containskeyword2 ename1containskeyword1 return teststolist,['c#'] +184369,android readsend text messages on ubuntu as an android programmer i spend an awful lot of time with my test device phone plugged into my computer and being as lazy as i am i would like to be able to send texts via my computer through my phonefor example i get a text the text is pushed to the active adb connection from which i can send it to a running script that will allow me to see the text on my computer i can then type the response hit enter which will push the text through the active adb connection to the phone and be sent to the targetis there any way i do this maybe there is an adb command that i can route through a python script or something,['android'] +184377,what is the best way to store pairs of strings make an object or use a class in net do not know whether i am having a thick day but i just wondered what is the best route herecontexti have a list of fields and i want to store alias names with them i am using net 20 btw egso its essentially a pair of stringsreference refcommunity communitypost code zip code and i am thinking it seems overboard all the time to keep creating objects for things like this so should i create a stringdictionary and store the values that way even though i would not use any of the functionality of the stringdictionary class and i am not bothered about a key value pair association etc i just want to keep a pair of strings essentiallyany helppointers would be great,['c#'] +184386,how to determine where focus went this has been asked here before but several years ago and there was no crossplatform solution at the time other than the settimeout solution which is really not very handyi would like to do onblurfooparm and have foo be able to determine which element now has focusi am using regular javascript no jquery for this one pleaseis that possible these days,"['javascript', 'html']" +184398,stop backbone from adding surrounding divs to a view i am using handlebarsjs as a templating tool for my backbonejs app my render functions in my views usually look like the following var source roundhtml var template handlebarscompilesource var context jsonparsejsonstringifythismodel var html templatecontext thiselhtmlhtml return thisthe above is appended to the main app view through the following codethis is the code that calls the above codedivroundcontainer thiselappendroundviewrenderelmy handlebars template handles all of the styling and layout so i leave the el element of a view blank backbonejs automatically adds surrounding div tags around the handlebars template i assume this is because the el element is blank is there a way to prevent the addition of the surrounding div tags thanks,['javascript'] +184419,checkout of git repository in pure php i need to to a git checkout in pure phpi already tried this with http and sasl but i did not really workthen i took a look at glip but that does not seem to have any functionality like thisbasically i need toreplicateclone a remote git repositoryextract master branch files into a specified directorythe main problem with php git is that it just did not supported all possible changes you could do in a commit only new files no moving around of files and it was also unable to extract fileseditgit is not installed and i also cannot install git,['php'] +184425,how to handle the xcode warning no previous prototype for function this warning is popping up a bunch in some third party librariesis there a way to handle it without modifying the code eg ignore the warningif i have to modify the code to fix it how do i do itheres one of the code blocks that is causing a warningbool fbisdeviceipad if iphone os version max allowed 30200 if ui user interface idiom uiuserinterfaceidiompad return yes endif return no,['objective-c'] +184447,using pil to fill empty image space with nearby colors aka inpainting i create an image with pili need to fill in the empty space depicted as black i could easily fill it with a static color but what i would like to do is fill the pixels in with nearby colors for example the first pixel after the border might be a gaussian blur of the filledin pixels or perhaps a pushpull type algorithm described in the lumigraph gortler et ali need something that is not too slow because i have to run this on many images i have access to other libraries like numpy and you can assume that i know the borders or a mask of the outside region or inside region any suggestions on how to approach thisupdateas suggested by belisarius opencvs inpaint method is perfect for this heres some python code that uses opencv to achieve what i wantedimport image imagedraw cvim imageopenu7xvlpngpix imloadcreate a mask of the background colors this is slow but easy for example purposesmask imagenewl imsizemaskdraw imagedrawdrawmaskfor x in rangeimsize0 for y in rangeimsize1 if pixxy 0 maskdrawpointxy 255convert image and mask to opencv formatcv im cvcreateimageheaderimsize cvipl depth 8u 3cvsetdatacv im imtostringcv mask cvcreateimageheadermasksize cvipl depth 8u 1cvsetdatacv mask masktostringdo the inpaintingcv painted im cvcloneimagecv imcvinpaintcv im cv mask cv painted im 3 cvcv inpaint nsconvert back to pilpainted im imagefromstringrgb cvgetsizecv painted im cv painted imtostringpainted imshowand the resulting image,['python'] +184450,repeatedly extract a line between two delimiters in a text file python i have a text file in the following formatdelimiter1extract meextract meextract medelimiter2i would like to extract every block of extract mes between delimiter1 and delimiter2 in the txt filethis is my current nonperforming codeimport redef getthesentencesfile filecontents openfile start rx recompiledelimiter end rx recompiledelimiter2 line iterator iterfilecontents start false for line in line iterator if refindallstart rx line start true break while start next line nextline iterator if refindallend rx next line break print next line continue line iteratornextany ideas,['python'] +184474,how to use activeadmin on models using has many through association i am using activeadmin gem in my projecti have 2 models using has many through association the database schema looks exactly the same as the example in railsguide basicshtmlthehas manythroughassociationhow can i use activeadmin to show appointment date of each patient in physicians pageedit appointment date of each patient in physicians pagethanks all,['ruby-on-rails'] +184476,invoking mbunit test runner programmatically i am currently building a test suite using mbunit so far so good but instead of using the included icarus gui i want to have my own test runner not knowing much about what to do i go on gallios google group and copied the code posted by a user threadthreadafab404a14674cd2and i got the following exception insteadgallioruntimeruntimeexception was unhandled messagecould not resolve component for service type galliorunnerprojectsitestprojectmanager because there do not appear to be any components registered and enabled for that service type sourcegallio stacktrace at gallioruntimeextensibilityregistryservicelocatorresolvenonthisableddescriptortype servicetype at gallioruntimeextensibilityregistryservicelocatorresolveimpltype servicetype at gallioruntimeextensibilityregistryservicelocatorresolvetservice at galliorunnertestlauncherrunwithruntime at galliorunnertestlauncherrun at dundasdashboardtestsystemtestprogramsdriverruntests in cusersedmondcdocumentsvisual studio 2010projectsautomatedtestsystemtestprogramsimagecomparisontestdrivercsline 49 at dundasdashboardtestsystemprogrammainstring args in cusersedmondcdocumentsvisual studio 2010projectsautomatedtestsystemtestconsoleprogramcsline 13 at systemappdomain nexecuteassemblyruntimeassembly assembly string args at systemappdomainexecuteassemblystring assemblyfile evidence assemblysecurity string args at microsoftvisualstudiohostingprocesshostprocrunusersassembly at systemthreadingthreadhelperthreadstart contextobject state at systemthreadingexecutioncontextrunexecutioncontext executioncontext contextcallback callback object state boolean ignoresyncctx at systemthreadingexecutioncontextrunexecutioncontext executioncontext contextcallback callback object state at systemthreadingthreadhelperthreadstart innerexception what am i doing wrong there,['c#'] +184480,replace element html faster in jquery i am populating a list with about 250 items using code like thisvar html forvar i 0 i reallylongarraylength i html lia hrefhialilist olhtmlhtmlsomewhat to my surprise i used a profiler and found out that the bottleneck in my code was not the loop that iterated thousands of times but setting the html of the list to the string this usually takes about 510 seconds on my computer which is an order of magnitude too slowis there a way to do this that is significantly faster ie at least 10 times faster,"['javascript', 'jquery']" +184483,how to ignore hidden files using oslistdir my python script executes an oslistdirpath where the path is a queue containing archives that i need to treat one by one the problem is that i am getting the list in an array and then i just do a simple arraypop0 it was working fine until i put the project in subversion now i get the svn folder in my array and of course it makes my application crashso here is my question is there an existing function that ignore hidden files when executing an oslistdir and if not what would be the best waythank you,['python'] +184496,hresult 0x800a03ec on worksheetrange i am getting hresult 0x800a03ec on worksheetrange method number of rows are more than 70k office 2007codemicrosoftofficeinteropexcelrange neededrange currentwsrangecellcells1 1 cellcellsnrowcount ncolumncounthere my rowcount is more than 65530 breaks on this function i have observed that it breaks only when row count goes more than 65530,['c#'] +184552,can i check modelstate without modelbinding i am getting my feet wet with the entity framework and am wondering if there is a way for me to check model state without model binding happeningsay i create a user primarily from code is there a way for me to check to make sure it is valid according to my predefined data annotations before i update public actionresult index user you new user uusername test upassword test uemail test defaultcontext db new defaultcontext if modelstateisvalid dbusersaddu dbsavechanges responsewriteuid else model is not valid return view the above code does not work because there is no binding happening or maybe i am confused of the processthanks,['c#'] +184557,query speed with limit and milion records hi i have a 7milion records db table for testing query speedi tested up my 2 queries which are the same query with different limit parametresquery 1 select from table limit 20 50query 2 select from table limit 60 6030query exec times arequery 1 06 secquery 2 5500 secin both of these queries i am fetching same number of records but in the second case it is taking more time can someone please explain the reasons behind this,"['php', 'mysql', 'sql']" +184564,how can i get a python generator to return none rather than stopiteration i am using generators to perform searches in lists like this simple example a 1234 i for i v in enumeratea if v 4next3just to frame the example a bit i am using very much longer lists compared to the one above and the entries are a little bit more complicated than int i do it this way so the entire lists would not be traversed each time i search themnow if i would instead change that to i 6 it would return a stopiteration because it cannot find any 6 entry in ahow can i make it return none instead i could of course wrap it in a try except clause but is there a more pythonic way to do it,['python'] +184572,does c do tail recursion possible duplicatewhy doesnt netc eliminate tail recursion does c do tail recusioni cannot find any documentation telling me if it does or not,['c#'] +184594,how to avoid many database round trips and a lot of irrelevant data i have worked with various applications and encountered this situation many times until now i have not figured out what is the best approachheres the scenarioi have an application either desktop or webi need to retrieve simple documents from the database the document has a general details and item details so the databasegeneraldetails table documentid datecreated owner 1 070707 naruto 2 080808 goku 3 090909 taguro itemdetails table documentid item quantity 1 marbles 20 1 cards 56 2 yoyo 1 2 chess board 3 2 gi joe 12 3 rubber duck 1 as you can see the tables have a onetomany relationship now in order to retrieve all the documents and their respective items i always do either of the twomethod 1 many round trips pseudocode documents getfromdbselect documentid owner from generaldetails for each document in documents thisplaydocumentcreatedby documentitems getfromdbselect item quantity from itemdetails where documentid documentdocumentid for each documentitem in documentitems thisplaydocumentitemitem documentitemquantity method 2 much irrelevant data pseudocodedocumentsanditems getfromdbselect gdocumentid gowner iitem iquantity from generaldetails as g inner join itemdetails as i on gdocumentid idocumentidthisplayi used the first method when i was in college for desktop applications the performance was not bad so i realized it was okay until one day i saw an article make the web faster it says that many round trips to the database is bad so ever since then i have used the second methodon the second method i avoided round trips by using inner join to retrieve the first and the second table at once but it produces unecessary or redundant data see the result set documentid owner item quantity 1 naruto marbles 20 1 naruto cards 56 2 goku yoyo 1 2 goku chess board 3 2 goku gi joe 12 3 taguro rubber duck 1 the result set has redundant documentid and owner it looks like an unnormalized databasenow the question is how do i avoid round trips and at the same time avoid redundant data,['sql'] +184599,how to get pressed char from systemwindowsinputkeyeventargs i have systemwindowsinputkeyeventargs e variable i want to get real char for example i press button on keyboard and normally it returns string like oem but i want to get char how to do edit i use this in textbox,['c#'] +184602,learning web development django vs node vs rails vs others i know java and pythonwith some django and little bit of rubyno rails and no nodejs and probably there are more that i am not aware of i am planing to start learning web development and its complete stack but when i see around i see loads of options and this confuses me i need suggestions based on the following params ease to learn ease to build and iterate ease to deploy like free and cheap hosting solutions popular please throw some advice thank you,"['java', 'ruby-on-rails']" +184645,windows running py directly vs running python blahpy behaves differently i have a python script that uses subprocessimport subprocessprint running stuffsubprocesscheck calldo stuffbatprint stuff runif this was named blahpy and i run from a command promptpython blahpyi will get the output from do stuffbat or whatever i runif this is run asblahpythen i do not get output from do stuffbat only the print statementsso far seen on windows server 2003 python version 252 stuck there for various reasonslooking at the associated file type action i seepythonfilecpython25pythonexe 1 so can anyone explain the difference,['python'] +184655,how to access the files in bindebug within the project folder in visual studio 2010 i have my docxxsl file in my projectbindebug foldernow i want to access this file whenever i neededbut i could not able to access this file wordprocessingdocument worddoc wordprocessingdocumentopeninputfile true maindocumentpart maindocpart worddocmaindocumentpart xpathdocument xpathdoc new xpathdocumentmaindocpartgetstream xslcompiledtransform xslt new xslcompiledtransform string xsltfile docxxsl or docxxsl xsltloadxsltfile xmltextwriter writer new xmltextwriteroutputfile null xslttransformxpathdoc null writer writerclose worddoccloseplease guide me to put correct valid path to access docxxsl file,"['c#', '.net']" +184671,span backgroundcolor padding problems i have a design i want to implement that involves title text appearing with its own background color padded by 10px over an image par examplethe first example in this picture works well and is simplegreenbox width520px height261px positionrelativegreenbox span padding0 10px background0 positionabsolute left0 bottom40px trouble arises when the text overflows onto another line then the span elements padding does not effect the text on the line breaks it renders like soanyone know of an alternative or how they would set this design out so that the background color padding was consistentthanks in advanceedit i had simplified the code to make it concise but had missed a vital part actually it is like thisgreenbox width520px height261px positionrelativegreenbox a positionabsolute left0 bottom40px greenbox span padding0 10px background0 with the html asdiv classgreenbox a hreflinkspanthe title goes herespanadivthus the span remains inline wrapped in a absolute position anchor,['css'] +184681,set variable text column width in printf in order to determine the size of the column in c language we use numberdfor instance i can type 3d and it will give me a column of width3my problem is that my number after the is a variable that i receive so i need something like xd where x is the integer variable i received sometime before in my programbut it is not workingis there any other way to do this,['c'] +184697,looping through arrays of arrays i have an arrays of arrays some thing like graph how to iterate all arraysvar parentarray 123456789 1012131415161718 1920212324262728its just an example array actual can contains any number of array and then arrays how to print all those numbers its similar to html objects dom,['javascript'] +184709,where are mac osx http live streaming tools i am trying to install mediastreamvalidator mediastreamsegmenter mediafilesegmenter tools for my mac machine version 1068as mentioned in below link about downloading required tools for development of apple specified http live serveras above article saysthe tools are frequently updated so you should download the current version of the http live streaming tools from the apple developer website you can access them if you are a member of the iphone developer program one way to navigate to the tools is to log onto connectapplecom then click iphone under the downloads headingafter logging in to site connectapplecom with mac osx developer credentialsunder download heading there is no tab named iphone i am unable to find this linkif these tools are stored else where can some one please provide me the updated link i need these command lines for developing hls serveras i read on apple web site mac osx version 106 and above have these applications prinstalled and we do not need to install them using dgm files but on my max machine i have only mediastreamsegmenter command line tools not all of themcan some one please provide me a link to download these command line tools or provide information on how to get these applications installed on my macthanks,['ios'] +184710,rails 31 actioncontrollerroutingerror no route matches get assetsrailspng standard new rails app has issue showing the railspngactioncontrollerroutingerror no route matches get assetsrailspngi have tried moving the png file around to various places in assets and assetsimages and also the older place public or publicimages and changing the page but nothing has helped please answer if you have seen and resolved this i have tried about 20 different combos myselfversionrails 310rc4,"['ruby-on-rails', 'ruby']" +184720,android creating custom launcher i am intending to develop custom launcher for android phone i have searched web but i have not found any valuable information regarding creating launcher project what does an android app needs for being at the top of the gui aka launcher,['android'] +184722,beautify html output i was wondering whether there is class or something similar which i can include into my php pages to beautify the html outputsuch as putting new lines in after tags and correctly indenting so that my source code is not only one line i know that to the browser it does not matter but i wish to do thisi have heard of but am not clear on what it does and how to implement it ie i do not understand what the manual says about it,['php'] +184731,python method as argument so i know in python everything is an object meaning that it can be passed as an argument to a method but i am trying to understand how exactly does this work so i was trying out the following exampleclass a def init self selfvalue a def my methodself print selfvalueclass b def init self selfvalues b def my methodself method methoda ab bbmy methodamy methodnow first this was written just to see how things work i know i should for example check if my method s argument is callable now my question ishow exactly is the method passed here i mean the output i am recieving is a so i am guessing that when a object method is passed as parameter so is the actual object in this case when i pass amy method the instance a is also passed,['python'] +184742,why should we use sp for font sizes in android possible duplicatedifference of px dp dip and sp in android i am new to android and i was trying out this tutorialin that tutorial they used the unit sp for textsize attribute and dp for other attributesplease tell me how sp differs from dp,['android'] +184749,python get the first character of a the first string in a list how would i get the first character from the first string in a list in python it seems that i could use mylist01 but that does not give me the first character mylist mylistappendasdf mylistappendjkl mylist01sdf,['python'] +184766,how to choose between jaxrs and jaxws web services implementation in what contexts is it better to use one over the other and whythanks,['java'] +184771,variable decimal places in net string formatters fixed decimal places is easystringformat0f1 654321gives 6543how do i feed the number of decimal places in as a parameter like you can in c sostringformat0f 654321 2gives65432i cannot find what should replace the,['.net'] +184778,add blank option to top of select and make it the selected option in ie htmlselect iddropdown option valuevolvovolvooption option valuesaabsaaboption option valuemercedesmercedesoption option valueaudiaudioptionselectjquerydropdownprependoption value selectedselectedoptionwhen i run this in firefox or chrome the drop down has the newly inserted blank option selected when i run it in ie8 it still has volvo selected any ideas,"['jquery', 'html']" +184780,deleting mail permanently using java mail i have been using java mail to automate gmail operationsone of the operation is to delete mail and i use following for it messagesetflagflagsflagdeleted truebut doing so only pushes my mails to spam folderi am wondering if there is a straight way to delete mail permanently instead of deleting mail from inbox first and then searching mails in spam folder and deleting them,['java'] +184782,service not available geocoder android i have a little problem with the geocoder to get latitude and lontitude from an address this is my codefor garage g xmlgarage listaddress addressaddress codergetfromlocationnameggetaddress 5if address null address location addressget0 gsetlatitudelocationgetlatitudegsetlongitudelocationgetlongitudethe error is 0818 142856026 warnsystemerr359 javaioioexception service not available0818 142856026 warnsystemerr359 at androidlocationgeocodergetfromlocationnamegeocoderjava1780818 142856026 warnsystemerr359 at comamtandroidgaragegaragepostdatagaragejava2690818 142856026 warnsystemerr359 atcomamtandroidgaragegarageform2onclickgarageformjava860818 142856026 warnsystemerr359 at androidviewviewperformclickviewjava24850818 142856026 warnsystemerr359 atandroidviewviewperformclickrunviewjava90800818 142856036 warnsystemerr359 at androidoshandlerhandlecallbackhandlerjava5870818 142856036 warnsystemerr359 atandroidoshandlerthispatchmessagehandlerjava920818 142856036 warnsystemerr359 atandroidoslooperlooplooperjava1300818 142856036 warnsystemerr359 at androidappactivitythreadmainactivitythreadjava36830818 142856036 warnsystemerr359 atjavalangreflectmethodinvokenativenative method0818 142856036 warnsystemerr359 atjavalangreflectmethodinvokemethodjava5070818 142856036 warnsystemerr359 atcomandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava8390818 142856046 warnsystemerr359 atcomandroidinternaloszygoteinitmainzygoteinitjava5970818 142856046 warnsystemerr359 at dalviksystemnativestartmainnative methodthanks and regards anass,['android'] +184784,what does a new b mean in php although i get it that a new bwould be initializing an object for the class b but what woulda new bmean because i came across some code that happens to work otherwise,['php'] +184804,core data unresolved error on save i am getting an error when saving my core data context here is the logunresolved error error domainnscocoaerrordomain code134030 the operation couldnat be completed cocoa error 134030 userinfo0x1937a0 nsaffectedstoreserrorkey nssqlcore 0x156410 nsunderlyingerror0x181a60 the operation couldnat be completed cocoa error 4 nsfilepathvarmobileapplicationsappiddocumentsappnamesqlite nsaffectedstoreserrorkey nssqlcore 0x156410 nsfilepath varmobileapplicationsappiddocumentsappnamesqlite nsunderlyingerror error domainnscocoaerrordomain code4 the operation couldnu2019t be completed cocoa error 4 userinfo0x181a30 nsunderlyingerror0x108ab0 the operation couldnu2019t be completed no such file or directoryi receive this error after removing and deleting an objectproductlist removemproductobjectproductdelegate managedobjectcontext deleteobjectproductdelegate savecontexti also noted that i also receive the error for the following scenariosdebugging1 productlist removemproductobjectproduct delegate savecontext2 delegate managedobjectcontext deleteobjectproduct delegate savecontext3 delegate managedobjectcontext deleteobjectproduct productlist removemproductobjectproduct delegate savecontext4 delegate managedobjectcontext deleteobjectproduct delegate savecontexterror productlist removemproductobjectproduct delegate savecontext5 productlist removemproductobjectproduct delegate savecontexterror delegate managedobjectcontext deleteobjectproduct delegate savecontextat times i may pass around either the productlist or a product object both of type nsmanagedobject to other controllers always using assign in the property and never retain productlist is an object which may contain many product objectsi am able to create new objectsnsmanagedobject but when it comes to deleting them i get the error mentioned above when running the application in the simulator i keep a close eye on the sqlite file after attempting to delete an objectcode above i notice the sqlite file is removedi have created a few core data iphone applications with no problem but i seem to be having an issue here i do not believe i am doing anything out of the ordinary but perhaps i am missing a small detail but i do not know whatwhy is my sqlite file being deleted and resulting in this error message on savehow can i find a more useful error message so i can determine the cause of this error,['iphone'] +184819,mysql high cpu usage and persistent links i am having very high cpu spikes on mysqld process greater than 100 and even saw a 300 at one point my load average is around 25 34 28i read this great post about this issue mysql high cpu usageone of the main things to do is thisable persistent connections so i checked my phpini and mysqlallow persistent on and mysqlmax persistent 1 which means no limitthis raises a few questions for me before changing anything just to be sureif my mysqld process is spiking over 100 every couple seconds should not my load average be higher then they arewhat will thisabling persistent links do will my scripts continue to function as isif i turn this off and reload php what does this mean for my current users as there will be many active userseditcpu info core2quad q9400 26 ghz,"['php', 'mysql']" +184820,is there a tree structure or algorithm to shuffle around levels in a tree i have what i think is an interesting problembasically i have a list of items where each item has a fixed set of metadata of different valuesfor exampleitem 1 type text author user a edited date 03032003item 2 type table author user a edited date 04052006item 3 type image author user b edited date 05052005item 4 type text author user b edited date 05072007now as it stands that list of items is flattened and presented in a tablehowever we would like to find a way to allow the users to browse it in a tree but with the added flexibility that they can pivot the order each of the metadata tags appears in the treeso initially it might look likeitems table user a 04052006 item 2 item 2 item 2 text user a 03032003 item 1 item 1 user b 05072007 item 4 item 4 item 1 item 4 image however suppose instead a user wants to flip it round and view all items related to a particular useritems user a text table item 1 item 2 user b image text item 3 item 4and so oni hope that makes senseso what i am wondering therefore is if there is a best practice approach to achieving this at low cost the result of each flipshufflepivot is nicely represented in a tree so obviously the first thought is that when a user requests to change the representation a new tree could be generated of the list of items as required however i was hoping perhaps there may be a better way simply rotating a single tree etcalso is this something that could be done computationally cheaply in javascript on the users browser if the backend were to just simply return a flat list of itemsmany thanks kind regardsjamie,['javascript'] +184826,easy install and pip does not work easy install and pip does not work anymore on python 27 when i try to dosudo easy install pipi gettraceback most recent call last file usrbineasy install line 5 in module from pkg resources import load entry point file usrbinlibpython27sitepackagesthistribute0619py27eggpkg resourcespy line 2713 in module parse requirements requires environment file usrbinlibpython27sitepackagesthistribute0619py27eggpkg resourcespy line 584 in resolve raise thistributionnotfoundreqpkg resourcesthistributionnotfound thistribute0615and when i trysudo pip install packagei gettraceback most recent call last file usrbinpip line 5 in module from pkg resources import load entry point file usrbinlibpython27sitepackagesthistribute0619py27eggpkg resourcespy line 2713 in module parse requirements requires environment file usrbinlibpython27sitepackagesthistribute0619py27eggpkg resourcespy line 584 in resolve raise thistributionnotfoundreqpkg resourcesthistributionnotfound pip082i have already install both of them and yes first deleted them but no resultthanksi tried already this post,['python'] +184843,strange entity updating in entity framework codefirst i am solving the problem with updating entity before saving to database and got strange behaviori am using entity framework 41 codefirst in aspnet mvc 3 web application here is modelpublic class order public int orderid get set public int carid get set public datetime beginrentdate get set public datetime endrentdate get set public decimal rentprice get set public virtual car car get set public class car public int carid get set public string brand get set public string model get set public string numberplate get set public decimal rentprice get set each car has a rentprice this price should be copied to orders rentprice when creating one the car is selecting by user so initially orderrentprice is 0here i want to copy price valuehttppostpublic actionresult createorder order orderrentprice contextcarsfindordercaridrentprice if modelstateisvalid contextordersaddorder contextsavechanges return redirecttoactionindex return vieworderit is not working because of an error on the savechanges that entity has validation errors ok i found that need first to call updatemodelorder and then change valuesso what i have working code contextordersaddorderupdatemodelorderorderrentprice 7 contextsavechangesnot working code contextordersaddorderupdatemodelorderorderrentprice contextcarsfindordercaridrentprice contextsavechangesworking code contextordersaddorderupdatemodelordervar t double contextcarsfindordercaridrentpriceorderrentprice decimalt contextsavechangescan someone explain please what is going on here especially magic on the 3nd and 4th lines in the last block of codeupdatei am getting dbentityvalidationexception validation failed for one or more entities see entityvalidationerrors property for more detailsfrom the inner exception originalvalues cannot be used for entities in the added state,['c#'] +184866,building multi java project using gradle i am tearing my hair out over this i have stripped my scripts right back to code provided in the gradle tutorial pages as i think i am either doing something fundamentally wrong or have misunderstood how a multi project application is supposed to be structured using gradle i have got three java projects within eclipse with all three containing a buildgradle script and only one containing a settingsgradle script structure is as followsscripts buildgradle settingsgradledatabase buildgradleservices buildgradlei am attempting to build the database and services project using the build script in the scripts project to create the project tree i have the following code in settingsgradleinclude services databaseproject servicesprojectdir new filesettingsdir servicesproject databaseprojectdir new filesettingsdir databasereplicating the code in the multiproject tutorial gradle docs i am trying to get each of the build scripts to print out some text to ensure everything is set up correctly my end goal is to have the dependencies correctly built when eclipseclasspath is executed so that all projects correctly compile within eclipse however the text is not being printed out as i expectedbelow are what is contained within the three build scriptsscripts buildgradleallprojects task hello task println i am taskprojectname subprojects hello println i depend on scriptsdatabase buildgradlehellodolast println i am inside database services buildgradlehellodolast println i am inside services within the scripts project when i run gradle q hello i get the following resultsi am scriptsi am anprdatabase i depend on scriptsi am database i depend on scriptswhy is the text i am inside database and i am inside services not appearing i am a bit baffled by it i can only surmise it has something to do with my project structure can someone confirm this is the case if not what is the problem as mentioned i have stripped my scripts back to this simple example as i could not get the dependencies to run within each projects build script using the same structuregreatly appreciate any help offered,['java'] +184899,partial template specialization i have a scenario in which there is a template classtemplatetypename x typename yclass foo typedef ynestedtype bar int a bar thing void b int cx that other stuffand then i would like the a method to have a different behavior when x is a given type but b and c can stay the same and the actual code actually has about 10 other methods a few of which are quite lengthy and subject to frequent tweaking so i would rather avoid making a fullclass specialization and copypaste the full class implementationi went on and wrotetemplatetypename tint foomytype tabar thingbut my compiler clang 16371 refused to even consider this as a template specialization of any sortis there some syntax error hidden in the way i wrote the code or is this coding style invalid c unfortunately even if other compilers do support the idiom my company is stuck with clangthanks for any help on this,['c++'] +184924,textdecorationnone does not remove text decoration consider the following codehtmlspan classc1homesup idid12supspancssc1 textdecorationunderlineid1 textdecorationnone importantnow i expected home to have an underline while the superscript 2 does not have the underline but it so happens that the superscript is also getting the underline what am i missing here,"['javascript', 'jquery', 'css']" +184926,can a pdf be converted to a vector image format that can be printed from net we have a net app which prints to both real printers and pdf currently using pdfsharp although that part can be changed if there is a better option most of the output is generated text or images but there can be one or more pages that get appended to the end that pages are provided by the enduser in pdf formatwhen printing to paper our users use preprinted paper but in the case of an exported pdf we concatenate those pages to the end since they are already in pdf formatwe want to be able to embed those pdfs directly into the print stream so they do not need preprinted paper however there are not really any good options for rendering a pdf to a gdi page systemdrawinggraphicsis there a vector format the pdf could be converted to by some external program that could rendered to a gdi page without being degraded by conversion to a bitmap first,['c#'] +184934,what does tty mean in the unix ps command when i run ps one of the columns output is tty what does this mean in particular how does as value of compare with ttys0i ask because i have a java program execute sort via processbuilder and when this program is run via my ide intillij the process takes 5x shorter than when run as an executable jar outside the ide in each case i run ps when the sort is running and the only difference is the ide creats a process with a tty of whereas the jar creates a process with tty of ttys0,['java'] +184964,convert jquery element to html element i have a jquery element but i have to send it to a function that only accepts html elements how can i convert the jquery element to an html element,"['javascript', 'jquery']" +184970,httprequesthttpresponse memory leak cfnet 35 win ce 60 i have tried everything possible to get rid of what i think is a memory leak with the httprequest or httpresponse classes in the cfnet 35 running on a win ce 60 device i am using them to communucate with an ip camerabelow is the current code i am using the code is running in a custom control on a thread with its priority set to below normal and backgroundworker set to true there are two of these control objects on one of my formsi say current because i have tried async requests and other permutations of the below code with no reduction in memory consumption protected void camrefreshthread while true if false camenabled httpwebrequest httpreq null try lock lockobject create request httpreq httpwebrequestwebrequestcreatehttp thisipv4address axiscgijpgimagecgi httpreqtimeout 50 httpreqreadwritetimeout 50 httpreqcredentials new networkcredentialthiscamusername thiscampassword indicate waiting for reponse responserxed false get response using httpwebresponse httpresp httpwebresponsehttpreqgetresponse get response streamimagefromstream using stream imgstream httprespgetresponsestream get bitmap using bitmap imgfrmstream new bitmapimgstream if false camenabled indicate response has not timed out responsetimedout false responsefirst true marshall bitmap thisinvokegetbitmapdelegate imgfrmstream indicate response rxed responserxed true catch webexception e if false responsetimedout responsetimedout true responsefirst false thisinvokerefreshthisplaydelegate catch exception finally if null httpreq httpreqabort threadsleep1 i have profiled it with the rpm and as the memory grows so do a butch of rooted objects for the systemnet namespace and systemthreading namespace which includes a bunch of thread and sync objects that i am not creatingi have attached an image of the heap comparison of the first and last heap snapshotsi have made sure to use using and call thispose on all the ojects that allow it also i make sure to abort the request when done i have seen this in other examples and it is supposed to release connection resources etchere is the strange part the leak only occurs when a timeout webexception is thrown if i do not have cameras connected with cameras connected the devices runs for days without increase in memory also both the managed number of bytes and the total number of bytes grows in rpm so i do not think it is an unmanged leak lastly i am attempting to get images from the camera as fast as i can i am starting to wonder if i am just not giving the gc time to collect but when a collection occurs i see the collection count go up in rpm the managed byte count does not go down it just keeps growing hopefully i am doing something very stupid and this is an easy fix as always any help or suggestions are appreciatedadditional infothe two delegates invoked from the camera thread are as follows if it might help to knowgetbitmapdelegate new voiddelegatebitmapupdatecamimagerefreshthisplaydelegate new voiddelegatevoidrefreshcamimageprotected void updatecamimagebitmap frame if null bmpoffscreen bmpoffscreenthispose bmpoffscreen bitmapframeclone refreshprotected void refreshcamimage refreshadditional info2just to complete the information below i have included the onpaint etc that i used to paint the bitmap to the screen for the cameraprotected override void onpaintpainteventargs e string thisplaystring null if false camenabled thisplaystring stringempty else if false responsetimedout thisplaystring communication timeout else if null bmpoffscreen false responsefirst egraphicsdrawimagebmpoffscreen 0 0 else thisplaystring loading if null thisplaystring egraphicsclearthisbackcolor using solidbrush stringbrush new solidbrushthisforecolor using stringformat format new stringformat formatlinealignment stringalignmentcenter formatalignment stringalignmentcenter egraphicsdrawstringthisplaystring thisfont stringbrush thisclientrectangle format protected override void onpaintbackgroundpainteventargs eupdatehere is what i do not get since httprequest is just an object that hold information and cannot be closedthisposed and since when a timeout webexception is thrown the httpresponse is still null cannot be closed what is referencing the resources that were used to attempt the request the only explaination is that there is some reference held by the httprequest object that when abort is called should release the resources used to make the request the ones that i am seeing not recovered in rpm since i call abort and since the httprequest object is only in the scope during the request i do not see how any resources referenced cannot be collectedupdate2well i let it run with the cameras enabled and allowed the timeouts to continue then i thisabled the cameras eliminating the httprequest attempts and the timeouts and let it run the rest of the day at the end of the day the gc was stuck at the same value based on past test it should have grown by about 6mb proving that is has nothing to do with giving the gc time to collect at least i think so the resources are still off in limbo and i need to figure out exactly what is keeping them rooted hopefully i can figure thatout and give another update until thenside notehas anyone ever used httprequesthttpresponse to get images from an ip camera on a win ce device using cfnet 35 if so was there a test case for loss of comm from the camera for an indefinite amount of time that should have been the first thing i asked since i have not found a lot of examples out there showing how to communicate to ip cameras from embedded devicesupdate3well i think i have stumbled onto a fix for my specific issue i made a few changes to the servicepointmanager static class members with respect to the number of default connections and the max idle timeservicepointmanagerdefaultconnectionlimit 4servicepointmanagermaxservicepointidletime 10since i will have a maximum of 4 cameras connected at any time and since my timeout for the httprequest is set to 50ms i figured i would try a 10ms max idle time to see what would happend i let two units run overnight with no cameras connected timing out every 50ms what normally would happen is i would come in the morning and the devices would be sitting there with an oom message and the gc memory and physical memory would be maxed out for my system well both devices were at the same memory levels that they were at when i left last night so i am hoping this is the fix for my issue based on msdn documentationthe connectionlimit property sets the maximum number of connections that the servicepoint can make to an internet resource the value of the connectionlimit property is set to the value of the servicepointmanagerdefaultconnectionlimit property when the servicepoint is created subsequent changes to defaultconnectionlimit have no effect on existing servicepoint instancesthe maxidletime property contains the length of time in milliseconds that the servicepoint is allowed to maintain an idle connection to an internet resource before it is recycled for use in another connection you can set maxidletime to timeoutinfinite to indicate that the servicepoint should never timeout the default value of the maxidletime property is the value of the servicepointmanagermaxservicepointidletime property when the servicepoint is created subsequent changes to the maxservicepointidletime property have no effect on existing servicepoint instancesthe maxservicepointidletime property sets the maximum idle time that the servicepointmanager assigns to the maxidletime property when creating servicepoint instances changes to this value will affect only servicepoint instances that are initialized after the value is changed after a servicepoint has been idle for the time specified in maxidletime it is eligible for garbage collection a servicepoint is idle when the list of connections associated with the servicepoint is emptythe key to all of this for me is that is specifically states that after the service point is idle for the max idle time it is eligible for garbage collection i have seen anywhere from 100 secs to 900 secs as the default for this value depending on the framework version the description was pertaining to i am going to do some more testing before i consider this a fix i would love to here from anyone who has played with these properties to fix their specific issues and whether or not this makes sense as the root cause of the problem i have been seeing all responses are appreciated thanks in advance,['c#'] +184998,why is googles infowindow css not exposed customization is too hard this really bugs me a lotafter wading through google maps v3 generated client side code in firebug i am about ready to drive down the street and give some of these engineers a piece of my mind argh pthe infowwindow class produces html that personally i would think is simply nuts maybe someone can help me make sense of itthe infowwindow html structure is like thismap canvas div div div div div 5 levels of elements no big deal here ok div top left cornerdiv top right cornerdiv bottom left cornerdiv bottom right corner now comes fun stuff for the speech bubble arrowdivdivdivdivdivdivdivdivdivdiv the 10 divs above are stacked diagonally with odd sizes to make this arrow i am sorry but why is it done like that i suppose they wanted the user to be able to grab the map even right next to the arrow think about this do users really need to be able to not grab the arrow if grabbing the arrow causes map pan as is the case for the shadow images would that really be a problemdiv bottom middle for image background border or somethingdiv top middlediv middlediv bottom middle againdiv entire block of the infowindow probably the container img close boxdiv center block with the contents of the infowindowdiv text content containerwow thats nutsnotice there is no real semantic structure and gosh dare i have such an assumption no class names anywhere nothing i figured maybe they have some kind of 9slice box going on and then produce the arrow separately i mean the image sprite in iw3png sure is not going to be the problem herei dearly hope someone who has an effect on this api comes across this and hopefully google will eventually find a way to solve this such that custom infowindow visuals are as straightforward as markersthanks for tuning in happy commentingmeanwhile i shall use a hack to get to these crazy divs and make them do my biddingearlier i commented on some other post and i think it should not be too much to ask for a method in the api that lets you use custom ui without resorting to a nearduplication of the whole window object as is currently necessary see google extension classes v3googlemapsinfowindowsetstyle topleft background urlimageswindowspritepng 0 0 norepeat width 10px height 10px topright etc etc,['css'] +184999,withobject block trick there is a common idiom of using substitutions likedef with clazz block yield clazz clazzendwith hashnew hash hashmergea 1endis there a way to go further and define with to have a possibility of doingwith hashnew hash mergea 1 endor evenwith hashnew do mergea 1endupdatelater accidentally i found exactly what i was looking for solution similar to the accepted oneupdate 2it was added to sugarhighdsl in update 3docille project on github exploits this idea very nicely,['ruby'] +185014,avoiding duplication of function definitions in template specializations the class widget has some functions that apply for all parameter types common functions and other functions that need to be specialized for given types the uncommon functionsg insists that the specialization for widget should also define common fn and not just uncommon fn but that defeats the purpose of using specialization in the first place how can one avoid repeating common fninclude casserttemplatetypename type struct widget widget char common fn return a int uncommon fn return 1 template struct widgetchar widget int uncommon fn return 2 int main widgetchar widgetchar assert widgetcharcommon fn a error assert widgetcharuncommon fn 2 begineditto alfi am unable to usetemplate int widgetcharuncommon fn return 2 because some of the uncommon functions need to return a trait type and so it was excessive to simplify by making the actual type primitiveor is there in fact a way to make the compiler recognize typename foobar when writingstruct foo typedef foobar bar template typename foobar widgetfoouncommon fn return endeditbeginedit2to iammilindthat is interesting but i am unable to use derivation from widget or the possibly clearer solution of refactoring the common parts into a parent class generalwidget for the same reason the common parts are not entirely common their declarations and their definitions look the same but because they use traits they are at the end quite differentendedit2,['c++'] +185025,devise for twitter cookie overflow error i am trying to integrate twitter into devise using this guide i basically take all occurence of facebook and substitue it with twitter however when i sign in with twitter i am getting the following erroractionthispatchcookiescookieoverflow actionthispatchcookiescookieoverflowat the following urlhttplocalhost30usersauthtwittercallbackoauth tokensomethingoauth verifierblahis there any nice way to get around fixing this problem thanks,['ruby-on-rails'] +185029,whats the advantage of message queue over shared data in thread communication i read a article about multithread program design it says it is a best practice that replacing shared data with asynchronous messages as much as possible prefer to keep each threadas data isolated unshared and let threads instead communicate via asynchronous messages that pass copies of datawhat confuse me is that i do not see the difference between using shared data and message queues i am now working on a nongui project on windows so let us use windowss message queues and take a tradition producerconsumer problem as a exampleusing shared data there would be a shared container and a lock guarding the container between the producer thread and the consumer thread when producer output product it first wait for the lock and then write something to the container then release the lockusing message queue the producer could simply postthreadmessage without block and this is the async messages advantage but i think there must exist some lock guarding the message queue between the two threads otherwise the data will definitely corrupt the postthreadmessage call just hide the details i do not know whether my guess is right but if it is true the advantage seems no longer existsince both two method do the same thing and the only difference is that the system hide the details when using message queuesps maybe the message queue use a nonblocking containner but i could use a concurrent container in the former way too i want to know how the message queue is implemented and is there any performance difference bwtween the two waysupdatedi still do not get the concept of async message if the message queue operations are still blocked somewhere else correct me if my guess was wrong when we use shared containers and locks we will block in our own thread but when using message queues myselfs thread returned immediately and left the blocking work to some system thread,['c++'] +185040,whats the difference between finish and finishactivityint requestcode in android can anyone explain me the difference between finish and finishactivityint requestcode and the situation of where to use them aptlythanks in advance,['android'] +185048,detecting button pressed when there are multiple alert views i have multiple alert views in one view and i use this code to detect which button was pressedvoidalertviewuialertview alertview clickedbuttonatindexnsintegerbuttonindex nsstring title alertview buttontitleatindexbuttonindex if title isequaltostringok for one alert view passcode becomefirstresponder else if title isequaltostring ok for another alert view had to change ok to ok passcodeconfirm becomefirstresponder now since there are multiple alert views in one view that do different things i have to trick the user into thinking ok and ok are the same thing it works and looks fine but it feels kind of messy surely there is another way to do this such as making this specific to an alert view and then making it specific to another do you know how i would do this thanks,"['iphone', 'ios']" +185068,error an expression tree may not contain a dynamic operation i use aspnet 4 and c i use ef 4i have this query i receive an error an expression tree may not contain a dynamic operationdynamic o eitemdataitemvar imagescontent contextcmsimagescontentsfirstordefaultimg imgcontentid ocontentidit seems is imposible to cast a dynamic type using a lamba expressionhow i can fix the problem and able to use my object o in my lamba thankspseitemdataitem is of type cmscontentand ocontentid is of type int,['c#'] +185070,index on multiple bit fields in sql server we currently have a scenario where one table effectively has several 10 to 15 boolean flags not nullable bit fields unfortunately it is not really possible to simplify this too much on a logical level because any combination of the boolean values is permissiblethe table in question is a transactional table which may end up having tens of millions of rows and both insert and select performance is fairly critical although we are not quite sure of the thistribution of the data at this time the combination of all flags should provide relative good cardinality ie make it a worthwhile index for sql server to make use oftypical select query scenarios might be to select records based on 3 or 4 of the flags only eg where flag31 and flag70 and flag91 it would not be practical to create separate indexes for all combinations of the flags used by these select queries as there will be many of them given this situation what would be the recommended approach to effectively index these fields the table is new so there is no existing data to worry about yet and we have a fair amount of flexibility in the actual implementation of the tablethere are two main options that we are considering at the momentcreate a single index which includes all the bit fields this would probably include 1 or 2 other int fields which would always used my concern is that given the typical usage of only including a few of the fields this approach would skip the index and resort to a table scan let us call this option a having read some of the replies it seems that this approach would not work well since the order of the fields in the index would make a difference making it impossible to index effectively on all the fieldseffectively do what i believe sql server is doing internally and encode the bit fields into a single int field using binary operators anding and oring numbers together 1 2 4 8 etc my concern here is that wed need to do some kind of calculation to query on this encoded field which would skip the index again maintenance and the complexity of this solution is also a concern let us call this option b additional info the argument for this approach is that we could have a relatively simple and short index which includes one or two other fields from the table and this field the other fields would narrow down the number of records needing to be evaluated and since the encoded field would contain all of our bit fields sql server would be able to perform the calculation using the data retrieved from the index directly ie an index scan as opposed to the table ie a table scan at the moment we are heavily leaning towards option b for completeness this would be running on sql server 2008any advice would be greatly appreciatededit spelling clarity query example additional info on option b,['sql'] +185079,download html page in c i am writing an app in cis there a way to download a html page by giving my program its url onlyfoe example my program will get the url wgooglecom and download the html page,"['c#', 'html']" +185082,what are some good web apps for learning flask i am looking for apps source code with user registration login session oauth and sqlalchemy for learning flask i have looked at the source for flaskpocorg website and also some repos at github i believe there are more out there appreciate any pointer thanks,['python'] +185100,int c getchar ok so im reading this book the c programming language by kernighan and ritchie second edition and one of the examples im having trouble understanding how things are workinginclude stdiohdefine maxline 10int getlinechar line int maxlinevoid copychar to char fromint mainint argc char argv int len int max char linemaxline char longestmaxline max 0 whilelen getlineline maxline 1 iflen max max len copylongest line ifmax 0 printfs longest getchar getchar return 0 int getlinechar s int lim int c i fori 0 i lim 1 c getchar eof c n i si c ifc n si c i si 0 return ivoid copychar to char from int i i 0 whiletoi fromi 0 ithe line fori 0 i lim 1 c getchar eof c n iwhere it says c getchar how can an integer characters input from the command line integers yes but how are the characters i type being stored thanks in advance,['c'] +185110,need to capture video stream from camera in c application i need to build an application that meets the requirements below it can be a windows client silverlight client or wpf clientscreen will show video stream from 2 separate cameras in 2 separate windowsneed to have pvr type functionality that is21 show live stream22 pause and playback previous 30 seconds of videoi am trying to use resources i have that is c application development however i do not have any experience with video captureany help in terms of libraries i can look at or the best way to do thisthankscronline,['c#'] +185148,why did microsoft abandon long double data type a while ago i wrote a program which used some factorial functions i used the long double data type to support relative big numbers now i changed from codeblocks to visualstudio 2010 i was wondering why my program did not work any more till i realized after some research that ms has abandonded the long double data typeis there any special reason for this to me it looks very like step backwards in terms of technology is there any alternative to use i would also be happy with an alternative out of the boost library,['c++'] +185158,output newline char in regexp under java or ant i have ant target that invokes replaceregexp tasktarget nameregexpreplace replaceregexp filefiletemp match replacefirst operation on 1 second operation on 1 bylinetruetargetfiletemp is a1a2desired output is first operation on a1second operation on a1first operation on a2second operation on a2what to insert as new line char for producing desired output in ant replaceregexp parameter replacefirst operation on 1 new line second operation on 1,['java'] +185160,beautify nslog of nsarray nsdictionary i am dealing with deeply nested nsarrays and nsdictionarys and it is very time consuming to say the least data objectatindex0 valueforkeyblah etc etcdoes anyone know of a nice ios category to recursively log the structure highlight the type and show the valuesmight be asking a bit much but you never know,['ios'] +185178,calculate voronoi around polygon i need to generate a voronoi diagram around a concave nonconvex inside polygon i have looked for methods online but i have not been able to figure out how to do this basically i generate the convex hull of the points calculate the dual points and build an edge network between these points however when meeting the edges of the inside polygon it has to look like the edge of the shape just like the convex hull so by doing this and clipping all the edges at the borders i should end up with a voronoi diagram that has nice edges to the borders of the inside polygon and no cells that are on both sides of the inside polygonlet me give you an examplethe problem with this is that the cells cross the inside polygon edges and there is no visual relation between the cell structure and the polygon shapedoes anybody know how to approach this problem is there some algorithm that already does this or gets close to what i am trying to achievethank you so much for any kind of input,['java'] +185187,get overall sum of all databases size in a sql server i want to calculate how much space my databases are using in a server i could use sp spacefiles or query sysdatabases table but that would give me separate results for each database and i would have to copy that into an excel sheet and calculate the sum from thereis there a direct way of doing it in tsqlthanks,['sql'] +185191,creating an instance of an interface i have the following interfaces definedpublic interface iaudit datetime datecreated get set public interface iauditable iaudit audit get set the iauditable interface says which classes i will have an audit for the iaudit interface is the actual audit for that class for example say i have the following implementationspublic class user iauditable public string username get set public useraudit audit get set public class useraudit iaudit public string username get set public datetime datecreated get set public useradituser user username userusername now given an object which is iauditable user from above i would like to be able to create an intance of iaudit useradit from above by feeding in the iauditable object into the constructor ideally i would have something likeif myobject is iauditable var audit new iauditmyobject datecreated datetimeutcnow this would create a useraudit using the above examplehowever i have a bunch of problemsyou cannot create an instance of an interfaceno where in the code does it define which iaudit applies to which iauditablei cannot specify that the iaudit interface must have a constructor which takes an iauditablei am sure this is a design pattern many have had before but i cannot get my head around it i would really appreciate if someone could show me how this can be achieved,['c#'] +185193,pressing the enter key instead of clicking button with shoes ruby as the title suggests i am just looking for a way of pressing a button in shoes without clicking it i have searched the forum but unfortunately cannot find anythingthanks,['ruby'] +185236,python help function printing docstrings is there an option to print the output of helpmyfun the behaviour i am seeing is that output is printed to stdout and the script waits for user input ie type q to continuethere must be a setting to set this to just dump docstringsalternatively if i could just dump the docstring plus the def fargs line that would be fine toosearching for python help function is comical maybe i am missing some nice pydoc page somewhere out there that explains it all,['python'] +185245,core plot 04 tutorial ios does anyone have a good tutorialbook recommendation for using core plot 04 in ios i have never used it before and from looking at the tutorials that they have linked to it does not make sense i cannot even run the switch on the code tutorial where do i start,"['iphone', 'objective-c', 'ios']" +185258,doctrine coregettablefindall how to specify order when using a doctrine table object is it possible to specify the order of the returned collection when using findall or findbywhateverin the docs i see some stuff about getorderbystatement and processorderby but it is not clear on how to use them,['php'] +185286,facebook login without popup i am trying to make a simple facebook app but for the authorization it seems that it is always blocked by a popupblocker my code is thusfbinit appid theapid status true cookie true xfbml true fbloginfunctionresponse if responseauthresponse fbapime functionresponse fblogoutfunctionresponse consoleloglogged out else consoleloguser did not authorize any help would be greatly appreciated thanks,['javascript'] +185301,matplotlib errors result in a memory leak how can i free up that memory i am running a django app that includes matplotlib and allows the user to specify the axes of the graph this can result in overflow error agg complexity exceededwhen that happens up to 100mb of ram get tied up normally i free that memory up using figgcf plotclose and gccollect but the memory associated with the error does not seem to be associated with the plot objectdoes anyone know how i can release that memorythankshere is some code that gives me the agg complexity errorimport matplotlibmatplotlibuseaggimport matplotlibpyplot as pltimport numpy as np import gca nparange10b nprandomrandn10fig pltfigurenum1 dpi100 facecolorw edgecolorwfigset size inches107ax figadd subplot1axplota bfigsavefigyourdesktoprandompng code gives me an error herefigclf normally i use these lines to release the memorypltclosedel a bgccollect,['python'] +185307,python unpack ibm 32bit float point i was reading a binary file in python like thisfrom struct import unpackns 10f openbinary file rbwhile true data freadns 4 if data break unpacked unpacksf ns data print strunpackedwhen i realized unpackf str is for unpacking ie floating point my data is ibm 32bit float point numbersmy question ishow can i impliment my unpack to unpack ibm 32bit float point type numbersi do not mind using like ctypes to extend python to get better performanceedit i did some searchingthis looks very promising but i want to get more efficient there are potential tens of thousands of loopsedit posted answer below thanks for the tip,['python'] +185315,standard error in nonlinear regression i have been doing some monte carlo physics simulations with python and i am in unable to determine the standard error for the coefficients of a nonlinear least square fitinitially i was using scipys scipystatslinregress for my model since i thought it would be a linear model but noticed it is actually some sort of power function i then used numpys polyfit with the degrees of freedom being 2 but i cannot find anyway to determine the standard error of the coefficientsi know gnuplot can determine the errors for me but i need to do fits for over 30 different cases i was wondering if anyone knows of anyway for python to read the standard error from gnuplot or is there some other library i can use,['python'] +185325,java wait and notify illegalmonitorstateexception i do not completely understand how wait and notify of object work and as a result i am forced to slim down my attempts into the following section of codemainjavaimport javautilarraylistclass main public static main main null public static int numrunners 4 public static arraylistrunner runners null public static void mainstring args main new main main runners new arraylistrunnernumrunners for int i 0 i numrunners i runner r new runner runnersaddr new threadrstart systemoutprintlnrunners ready notifyall runnerjavaclass runner implements runnable public void run try mainmainwait catch interruptedexception e systemoutprintlnrunner away currently i get an illegalmonitorstateexception when calling mainmainwait but i do not understand why from what i can see i need to synchronize runnerrun but in doing so i assume it would only notify one thread when the idea is to notify them alli have looked at javautilconcurrent but i cannot find a suitable replacement maybe i am just missing something,['java'] +185354,does array changes in method when i write like thispublic class test void mainx int fyeah 2 3 4 smthfyeah systemoutprintlnxfyeah0 void smthint fyeah fyeah0 22 it prints x22when i write like thispublic class test void mainx int fyeah 5 smthfyeah systemoutprintlnxfyeah void smthint fyeah fyeah 22 it does not print x22 but prints x5why in the second version function does not change the value or it changes values only for arrays,['java'] +185356,which jquery plugin design pattern should i use i need to build a jquery plugin that would return a single instance per selector id the plugin should and will only be used on elements with id not possible to use selector that matches many elements so it should be used like thiselementidmypluginoptionsi need to be able to have few private methods for the plugin as well as few public methods i can achieve that but my main issue is that i want to get the very same instance every time i call elementidmyplugin and i want to have some code that should be executed only the first time the plugin is initialized for a given id constructthe options parameter should be supplied the first time for the construct after that i do not want the construct to be executed so that i can access the plugin just like elementidmypluginthe plugin should be able to work with multiple elements usually up to 2 on the same page but each and every one of them will need own config again they will be initialized by id not common class selector for example the above syntax is just for example i am open for any suggestions on how to achieve that patterni have quite some oop experience with other language but limited knowledge of javascript and i am really confused on how do it righteditto elaborate this plugin is a googlemaps v3 api wrapper helper to help me get rid of code duplication as i use google maps on many places usually with markers this is the current library lots of code removed just most important methods are left to seefunction csgooglemapshelper set function param options map settings for the google maps helper available options are as follows maptypeid constant maptypecontrolposition constant maptypecontrolstyle constant mapcenterlatitude decimal 180 to 180 latitude of the map initial center mapcenterlongitude decimal 90 to 90 latitude of the map initial center mapdefaultzoomlevel integer map zoom level clusterenabled bool clustermaxzoom integer beyond this zoom level there will be no clustering fncsgooglemapshelper functionoptions var id thisattrid var settings extendtrue fncsgooglemapshelperdefaults options fncsgooglemapshelpersettingsid settings var mapoptions maptypeid settingsmaptypeid center new googlemapslatlngsettingsmapcenterlatitude settingsmapcenterlongitude zoom settingsmapdefaultzoomlevel maptypecontroloptions position settingsmaptypecontrolposition style settingsmaptypecontrolstyle fncsgooglemapshelpermapid new googlemapsmapdocumentgetelementbyidid mapoptions param options settings object for the marker available settings venueid int venuelatitude decimal venuelongitude decimal venuemapiconimg optional url to icon img venuemapiconwidth int icon img width in pixels venuemapiconheight int icon img height in pixels title string marker title draggable bool fncsgooglemapshelpercreatemarker functionid options pushtomarkersarray var settings fncsgooglemapshelpersettingsid markeroptions map fncsgooglemapshelpermapid position optionsposition new googlemapslatlngoptionsvenuelatitude optionsvenuelongitude title optionstitle venueid optionsvenueid draggable optionsdraggable if optionsvenuemapiconimg markeroptionsicon new googlemapsmarkerimageoptionsvenuemapiconimg new googlemapssizeoptionsvenuemapiconwidth optionsvenuemapiconheight var marker new googlemapsmarkermarkeroptions lets have the venueid as marker property if markervenueid markervenueid null googlemapseventaddlistenermarker click function fncsgooglemapshelperloadmarkerinfowindowcontentid this if pushtomarkersarray let us collect the markers as array in order to be loop them and set event handlers and other common stuff fncsgooglemapshelpermarkerspushmarker return marker this loads the marker info window content with ajax fncsgooglemapshelperloadmarkerinfowindowcontent functionid marker var settings fncsgooglemapshelpersettingsid var infowindowcontent null if markerinfowindow ajax async false type get url settingsmapmarkersinfowindowajaxurl data venueid markervenueid success functiondata var infowindowcontent data infowindowoptions content infowindowcontent markerinfowindow new googlemapsinfowindowinfowindowoptions close the existing opened info window on the map if such if fncsgooglemapshelperinfowindow fncsgooglemapshelperinfowindowclose if markerinfowindow fncsgooglemapshelperinfowindow markerinfowindow markerinfowindowopenmarkermap marker fncsgooglemapshelperfinalize functionid var settings fncsgooglemapshelpersettingsid if settingsclusterenabled var clusteroptions cluster true maxzoom settingsclustermaxzoom fncsgooglemapshelpershowclusteredid clusteroptions var venue fncsgooglemapshelperfindmarkerbyvenueidsettingsselectedvenueid if venue googlemapseventtriggervenue click fncsgooglemapshelpersetvenueeventsid set the common click event to all the venues fncsgooglemapshelpersetvenueevents functionid for var i in fncsgooglemapshelpermarkers googlemapseventaddlistenerfncsgooglemapshelpermarkersi click functionevent fncsgooglemapshelpersetvenueinputid this show the clustering grouping of markers fncsgooglemapshelpershowclustered functionid options show clustered var clustered new markerclustererfncsgooglemapshelpermapid fncsgooglemapshelpermarkers options return clustered fncsgooglemapshelpersettings fncsgooglemapshelpermap fncsgooglemapshelperinfowindow null fncsgooglemapshelpermarkers jqueryit is usage looks like this not actually exactly like this because there is a php wrapper to automate it with one call but basicallyjs idcsgooglemapshelperjsoptionsnif thisvenues null foreach thisvenues as row data googlemapshelpergetvenuemarkeroptionsjsrow js fncsgooglemapshelpercreatemarkerid data truen js fncsgooglemapshelperfinalizeidnecho jsthe problems of the above implementation are that i do not like to keep a hashmap for settings and maps the id is the div element id where the map is initialized it is used as a key in the map and settings has maps where i hold the settings and googlemaps mapobject instance for each initialized such googlemaps on the page the jsoptions and data from the php code are json objectsnow i need to be able to create a googlemapshelper instance that holds its own settings and googlemaps map object so that after i initialize it on certain element by its id i can reuse that instance but if i initialize it on and elements on the page each and every of them should have own configuration map object etci do not insist that this is implemented as a jquery plugin i insist that it is flexible and extendable because i will be using it in a large project with over dozen currently planned different screens where it will be used so in few months changing it is usage interface would be a nightmare to refactor on the whole projecti will add a bounty for this,"['javascript', 'jquery']" +185363,wpf listview with buttons on each line i have a list of games which just has an id a date and a timei am setting this list as the datacontexti then have a datatemplate for these games that is datatemplate datatypextype locgame grid gridrowdefinitions rowdefinition heightautorowdefinition gridrowdefinitions gridcolumndefinitions columndefinition width100columndefinition columndefinition width100columndefinition columndefinition width100columndefinition gridcolumndefinitions textblock namedateblock gridcolumn0 gridrow1 textbinding date stringformatdtextblock textblock nametimeblock gridcolumn1 gridrow1 textbinding timetextblock need to but a button here for each row grid datatemplateto use the template i am simply just doing this listbox itemssourcebindinglistbox i need to add a button to each line in this list view that have the same click event but will somehow pass the id of the game for which button is being clickedhow can i do this i am stuckif it does not make sense let me know and i will try to explain better,['c#'] +185374,net object explorer control does anyone know of an object explorer control for net winforms or webformsby object explorer i mean something like the visual studio object explorer that i can use it in my own programi found these links on the net1 httpwcodeprojectcomkbtraceoeaspx it is pretty old and i do not know if relevant today2 httpwpcreviewcoukforumscanembedvsnetsobjectexplorerprogramt1342274html nobody answers him,"['c#', '.net', 'asp.net']" +185386,best practice asynctask during orientation change asynctask is a great thing to run complex tasks in another threadbut when there is an orientation change or another configuration change while the asynctask is still running the current activity is destroyed and restarted and as the instance of asynctask is connected to that activity it fails and causes a force close message windowso i am looking for some kind of bestpractice to avoid these errors and prevent asynctask from failingwhat i have seen so far isthisable orientation changes for sure not the way you should handle thisletting the task survive and updating it with the new activity instance via onretainnonconfigurationinstancejust canceling the task when the activity is destroyed and restarting it when the activity is created againbinding the task to the application class instead of the activity instancesome method used in the shelves project via onrestoreinstancestatesome code examplesandroid asynctasks during a screen rotation part i and part iishelvesactivityjavacan you help me to find the best approach which solves the problem best and is easy to implement as well the code itself is also important as i do not know how to solve this correctly thanks for helping,['android'] +185410,var x y foo can this be accomplished since it is possible to dovar x foo y foowould this also be possiblevar x y fooi tried it however x becomes undefinedi know this may seem like a silly or redundant question but if i am curious about something why not ask also you will probably wonder why i would need two variables equal to the same thing in scope that is not the point of the question i am just curious,"['javascript', 'jquery']" +185412,how to produce exception error while transformation processing between xml and xslt i am having a doubt when we are doing any process in cnet on going if some thing error would may come at that time we are trapping in error log similarly when suppose we are doing any process between xml and xslt on processing error would may come at that how we can trap that exceptions can any one have an idea because it will use for validations for me so kindly let me know any possibilities for that,['c#'] +185422,rails 310 assets folder not rendering sprocketsenvironmentstatic root is deprecated when trying to update my rails 310rc4 app to rc6 i must have messed something up because my assets js and css files stopped rendering i tried to revert to rc4 but was still having this problem so i transferred all my files over to a new 310rc6 app and everything appears to work fine but i get the following messagessprocketsenvironmentstatic root is deprecated sprocketsenvironmentpath is deprecatedfollowed by a long list of files i can attach the extended msg if needed i am guessing i inadvertently fooled around with the sprockets configuration and that is whats been messing up my app from the beginning how do i dedeprecatereconfigure sprockets i guess is my question i have tried some different sprockets gem versions but nothing has worked yet thanks,['ruby-on-rails'] +185457,swt browser no more handles error i wrote a simple program just a ctabfolder and a welcomtab inherent from ctabitem i want to fill my welcometab by a browser which render my htmls at the init method of welcometab i create a browser but when program want to construct it i get this errorexception in thread main orgeclipseswtswterror no more handles unknown mozilla path mozilla five home not setat orgeclipseswtswterrorunknown sourceat orgeclipseswtbrowsermozillainitmozillaunknown sourceat orgeclipseswtbrowsermozillacreateunknown sourceat orgeclipseswtbrowserbrowserinitunknown sourceat orghekmatofhbookuiwelcometabinitwelcometabjava55at orghekmatofhbookuiwelcometabinitwelcometabjava30in addition i use eclipse 37 on kde based on archlinuxas i searched for this error everywhere tells about handle limited on threads but this is simple program with no font or image to thispose i think it should be a problem about gain handle from operation system,['java'] +185485,get the file size in android sdk i have a problem getting the size of a file i have the following codefile file new filesdcardlalatxtlong length filelengthand always length is zero yes zeroi am using android sdk not sure what version the code is running inside an activity i have created an sdcard perhaps it is a permission issue is there anything i am missing,"['java', 'android']" +185490,android gridview draw dividers i would like to know the simplest way to draw dividers between items currently textviews within a gridview the only way i can think of is to draw borders around those textviews so when combined they look like continuous horizontal and vertical dividersthere is a setdivider for listviews but not gridviewsthanks,['android'] +185498,jtable row hightlighter based on value from tablecell as i read that not possible to encode my navajo language finging the way how to only alternatestriped color into jtable example camickr import javaawtimport javaxswingimport javaxswingtablepublic class tablerowrenderingtip extends jpanel private static final long serialversionuid 1l public tablerowrenderingtip object columnnames type company shares price boolean object data buy ibm new integer10 new double805 booleantrue sell dell new integer20 new double625 booleanfalse short sell apple new integer30 new double735 booleantrue buy microsoft new integer40 new double2750 booleanfalse short sell cisco new integer50 new double20 booleantrue defaulttablemodel model new defaulttablemodeldata columnnames private static final long serialversionuid 1l override public class getcolumnclassint column return getvalueat0 columngetclass jtabbedpane tabbedpane new jtabbedpane tabbedpaneaddtabalternating createalternatingmodel addtabbedpane private jcomponent createalternatingdefaulttablemodel model jtable table new jtablemodel private static final long serialversionuid 1l override public component preparerenderertablecellrenderer renderer int row int column component c superpreparerendererrenderer row column if isrowselectedrow alternate row color csetbackgroundrow 2 0 getbackground colorlight gray return c tablesetpreferredscrollableviewportsizetablegetpreferredsize return new jscrollpanetable public static void mainstring args swingutilitiesinvokelaternew runnable override public void run createandshowgui public static void createandshowgui jframesetdefaultlookandfeeldecoratedfalse jframe frame new jframetable row rendering framesetdefaultcloseoperationjframeexit on close frameaddnew tablerowrenderingtip framepack framesetlocationrelativetonull framesetvisibletrue i have a jtable which contains some market trades better for understanding by reason my poor english skills but some of deals has only one leg but another for example vanilla cross currency swap could have two legs how is possible to hightlighting tablerows based on value from specifics tablecolumn for example last column with name dealid i tried to check row with row 1 row 1 but my empty head generated lots of codesrow to much for idea how to stop complicated simple simple things how to check if there exist duplicate value in another row always with strict ordering as captured in the pictures no idea how to implements simple formula for thatpictures demonstratedgenerated from codeimport javaawtimport javaxswingimport javaxswingtablepublic class tablepreparerenderer extends jframe private static final long serialversionuid 1l private object columnnames buysell type subtype ccy1 amount1 ccy2 amount2 dealid private object data buysell ccy swap a1 eur new double10 usd new double14390 50 buysell ccy swap a3 usd new double143890 eur new double10 50 buysell ccy swap a1 eur new double50 chf new double550 350 buysell ccy swap a1 chf new double54980 eur new double50 350 sellbuy ccy swap a3 usd new double10 eur new double7490 2250 sellbuy ccy swap a1 eur new double74890 usd new double10 2250 buysell ccy swap a1 gbp new double10 usd new double163810 400 buysell ccy swap a3 usd new double163820 gbp new double10 400 sell ccy spot a1 aud new double3435750 eur new double250 11990 buy ccy spot a1 eur new double10 jpy new double10990 259 sell ccy fwd a3 dkk new double7488900 eur new double10 115439 private jtable table public tablepreparerenderer defaulttablemodel model new defaulttablemodeldata columnnames table new jtablemodel private static final long serialversionuid 1l override public component preparerenderertablecellrenderer renderer int row int column component c superpreparerendererrenderer row column jcomponent jc jcomponent c if isrowselectedrow csetbackgroundgetbackground int modelrow convertrowindextomodelrow string type string getmodelgetvalueatmodelrow 0 if buyequalstype buysellequalstype csetbackgroundcolororange else if sellequalstype sellbuyequalstype csetbackgroundcolororange else if buysellequalstype csetbackgroundcoloryellow else if sellbuyequalstype csetbackgroundcoloryellow if isrowselectedrow if row 0 row 1row 4row 6row 7row 9row 10 jcomponent csetbackgroundcolororange else jcomponent csetbackgroundcoloryellow if isrowselectedrow if row 0 row 1 row 4 row 5 row 8 row 10 jcomponent csetbackgroundcolororange else jcomponent csetbackgroundcoloryellow if column 0 column 1 column 2 column 3 column 5 sethorizontalalignmentjavaxswingswingconstantscenter csethorizontalalignmentjavaxswingswingconstantscenter jcomponent csethorizontalalignmentjavaxswingswingconstantscenter return c override public class getcolumnclassint column switch column case 0 return stringclass case 1 return stringclass case 2 return stringclass case 3 return stringclass case 4 return doubleclass case 5 return stringclass case 6 return doubleclass case 7 return integerclass return null tablesetpreferredscrollableviewportsizetablegetpreferredsize jscrollpane scrollpane new jscrollpanetable getcontentpaneaddscrollpane public static void mainstring args tablepreparerenderer frame new tablepreparerenderer framesetdefaultcloseoperationexit on close framepack framesetlocationrelativetonull framesetvisibletrue edithow to set alignment for tablecell into preparerenderer,['java'] +185503,whats the benefit of cast over select i have a type with implicit conversion operators to most base types and tried to use caststring on a collection of this type which failed as i dug into it i noticed that casting via as does not use implicit or explicit conversion and just would not compile so i guess that is where cast falls down so this failsvar enumerable sourcecaststringbut this worksvar enumerable sourceselectx stringxso whats the benefit of cast sure it is a couple of characters shorter but seems a lot more limited if it can be used for conversion is there some benefit other than the more compact syntax,['c#'] +185521,create a picasa album and upload images to it with php and curl all of the tutorials i have found for creating picasa albums and uploading pictures use the zend framework which i have not studiedis it possible to upload images and create albums using php and curlmy images are stored in the directory eimages and the image information is stored in a mysql table like thisset sql modeno auto value on zerocreate table if not exists picasaimage id bigint1 unsigned not null auto increment title varchar255 collate utf8 unicode ci not null content varchar255 collate utf8 unicode ci not null tags varchar255 collate utf8 unicode ci not null license varchar50 collate utf8 unicode ci not null image path varchar150 collate utf8 unicode ci not null width int4 collate utf8 unicode ci not null height int4 collate utf8 unicode ci not null primary key id engineinnodb default charsetutf8 collateutf8 unicode ci auto increment0 i am getting the google client authentication code using the following codephp ch curl init curl setoptch curlopt url curl setoptch curlopt followlocation true data arrayaccounttype google email passwd yourpassword sourcephicurlexample servicelh2 curl setoptch curlopt ssl verifypeer 0 curl setoptch curlopt post true curl setoptch curlopt returntransfer true curl setoptch curlopt postfields data hasil curl execch echo hasil siddqaoue lsiddqabbo authdqasxq can anyone give some guidance on creating an album named test and uploading the images to itedit1how to add photo license when i upload photos with php scriptsreference on web albums filescreative commons attribution 30 unported ccbycreative commons attributionshare alike 30 unportedunlicensedcreative commons attributionnoncommercial 30 unportedcreative commons attributionno derivative works 30 unportedcreative commons attributionnoncommercialno derivative works 30 unportedcheck the response data from api get album photo there should be have something like gphotolicense tattribution non commercial no derivatives id3 nameattributionnoncommercialno derivative url,['php'] +185536,i want to create a minifilter driver to transparently redirect thisk io but i am having trouble getting started a project i am working on at the moment requires the implementation of a copyonwm mechanism which will be used to redirect thisk io in a similar manner to deep freeze or sandboxie on windows xp if i could i would also like to be able to mount the users modified files similar to how virtualclonedrive simulates thisk drives and transparently mounts iso images on themit is my understanding that such programs make use of minifilter drivers to redirect io requests the standard process copies any modified data to a secondary location and then readsmodifies that storage for subsequent access to that data so i think i understand what i would need to do there when it comes to simulating a cddvd drive and mounting an image on it though i am completely losti have been looking online google msdn the code project etc and in books such as developing drivers with the windows driver foundation and windows nt file system internals a developers guide but finding specific information and examples on monitoring intercepting and redirecting requests and creating loopback devices is proving difficult i am still quite new to the technologies involved so maybe i am having trouble seeing the forest for the treesi was wondering if anyone has been in a similar situation and had thiscovered any useful resources or could point me in the right direction so i could implement similar functionalityedit i found this question which seems like a useful resource though not for my specific use case so i have linked it here to add to any forthcoming responsessome clarificationi am trying to create a program which will allow users to install and use applications without needing administrative privileges the program will work by saving any filesystemregistry modifications to a seperate storage area a file on a pen drive or network store for example then allowing these to be integrated into any desktop on which the host program is runing on the fly carry your desktop around on a usb pen plug it in and your settings are appliedto redirect the io i couldpatch a process import address table iat to insert customised code at the application levelwrite a usermode filter driver to modify the requests on the flyfor enhanced any at all really security implement a kernelmode driver to patch the system service descriptor tables ssdts in a similar manner to av software there are upsides and downsides to each of these approaches for example approach three is much more difficult than approach one it provides more security but even then it can be beaten theoretical attacks have been around since 96 practical attacks since 07i was initally considering specific security features as opposed to just io redirection similar to wow64 compatibility settings but since starting to look at this i have remembered that you cannot protect the user from himself forever and that no matter how much work i was to put into defending a host system from a malicious process or foolish user it could be beaten or more likely i would make a mistake i also decided to avoid reinventing the sandboxing and antivirus wheels and simply concentrate on creating some useful functionality the philosophy of a tool should do one job and do it well won the dayin a nutshell all i want to do is implement functionality similar to that of vm snapshots and redirect changes to my own storage area the diagram below is a little out of date but it might be better at communicating my intentions than i am at the moment,['c++'] +185584,office addin ribbons same tab with 2 addins i am trying to make two word addins groups to appear in the same tab tools but they both create unique tabs there is two tools tabs i saw this video but i am using the visual designer not xml can i edit the designer code in some way to make this work,"['c#', '.net']" +185590,integrating r with rsruby i was wondering if anyone possibly had any experience integrating r into rails specifically on heroku i am familiar with the rsruby gem which is the de facto perhaps only binding that ruby has with r but documentation on integrating r with rails is sparse if not nonexistent would it be feasible to let us say install r into the lib folder of a rails application and use rsruby to access it through rails,"['ruby-on-rails', 'ruby']" +185591,android battery usage report for developers on gingerbread users can report apps for their battery usage by going to settings about phone battery use and then tap on a specific appmy question is as a developer where can i see these reportsthey seem very useful because they contain information on what type of wake locks you might be leaking,['android'] +185600,sending keyboard events to another application in c that does not handle windows events here is my situation we are writing an application that must transform microsoft kinect coordinates into keyboard and mouse eventswhen we need to take control of the mouse everything works as we intended in any kind of application the problem arises when we need to send keyboard events like key down or key up to applications that does not handle windows events like games for examplewe tried the sendkeys class of the net framework and it only works with windows applications when the application is a game like halflife or doom we cannot get the same effect so here is my question how can we effectively send keyboard events to these other applications,['c#'] +185606,python for loop slowing with time so i am having a little trouble dealing with for loops in python as far as i can tell they are getting slower with time i am looping over a range inside of a range and as time passes the loop noticeably slows this is done inside of a game engine if it matters could anyone tell me what the issue isheres a quick examplefor x in rangexs xs ys and zs are all predetermined size values for z in rangezs for y in rangeys vp x vs y vs z vs v cubevpthe initial speed of this process is fine but with time the loop slows i know it is not anything else like the rasterizer of the game engine because when the loop is done the rest of the engine runs at 60 fps so what could be the problemedit i am using python 3 so there is no xrangeedit 2 for this example vs is 10 and the predetermined size values of xs ys and zs are all 20,['python'] +185612,is there a way to inherit only one element of css shorthand a quick question from a css newbie here i am trying to reduce the size of my css files by using shorthand for certain properties such as paddingmarginsetc in certain cases i want to for example specify margintop marginleft and marginbottom but inherit marginright i tried margin 10px inherit 11px 12pxbut that does not work because the css inherit keyword inherits all or nothing is there a way to mark that one as skipped and do something like margin 10px 11px 12pxmarginright inheritand have css know that i am skipping one value in a 4value shorthand and not interpret it as a 3value shorthanddoes anyone know an easy way to get this to work or should i just use longhand in cases where i do not specify all four valuesthanks,['css'] +185616,using dll in visual studio 2010 c i have a problem i place my dll and lib file in the same directory as my project go to properties common properties framework and references add new reference but the list comes up emptyis there something else i should be doing,['c++'] +185661,uitableview cell just thisappeared callback i have a uitableview with heavy images content so the scrolling is not fluid anymorei want to add a timer to load the images while you scroll i create the timer for each row if the cell quits the view i cancel the timer if not i fade in the imagesmy question is is there a callback for a cell going out of view i am reading the doc but i am not sure there is anything for my needsthanks for the help edit the code i am using this is the three20 library i am using a custom tableitemcell the tabbar1tabitems itemphotos is the line hoging resources on the first load it is okay because the photos are being loaded asynchronously from the server but when i scroll back or reload the view they are all loaded synchronously and the scrolling is not smooth anymore especially on an iphone 3g voidsetobjectidobject if item object super setobjectobject mission item object selftextlabeltext itemname tabbar1tabitems nil timerfeats nstimer scheduledtimerwithtimeinterval05f targetself selectorselectorupdatefeats userinfonil repeats no tabbar1tabitems itemphotos voidupdatefeats dlogtimer ended mission item selfobject self tabbar1tabitems itemphotos,['ios'] +185663,is it possible to clean memory after filereader filereader seems to consume all the memory as it is repeatedly used to preload multiple blobs and never frees it any known way to force it to release consumed memory setting filereader object and it is result property to null does not seem to workupdatehere is a sample code test it on a big files like movie or you would not notice the effect in task managerinput idfile typefile onchangesliceme scriptfunction sliceme var file documentgetelementbyidfilefiles0 fr chunksize 2097152 chunks mathceilfilesize chunksize chunk 0 function loadnext var start end blobslice fileprototypemozslice fileprototypewebkitslice start chunk chunksize end start chunksize filesize filesize start chunksize fr new filereader fronload function if chunk chunks shortcut in production upload happens and then loadnext is called loadnext frreadasbinarystringblobslicecallfile start end loadnextscripti tried to create fresh filereader instance every time but the problem still stays i suspect that it could be caused by a circular nature of the pattern but i am not sure what other pattern can be used in this casei checked this code in both firefox and chrome and chrome seems to handle it more gracefully it purges memory after each cycle and is very fast but the irony of the situation is that chrome does not need to use this code at all it is just an experiment to overcome gecko 6 formdata blob bug bug 649150 blobs do not have a filename if sent via formdata,['javascript'] +185669,javascript namespace declaration with functionprototype i know this is often thiscussed but after searching around like someone out of the 19th century i need some advice i have no problem by declaring a namespace but when it comes to a prototypefoo function i stuck i found a way but i do not like itnamespace namespaceobj function thisfoobarnamespaceobjprototypestart function thisfoofubarblah new namespaceobjblahstartnow since i am a little neurotic in case of scripting i would like to have something like thisnamespace obj function thisfoobar objprototypestart functiontabinst thisfoofubar but then it throws an error uncaught syntaxerror unexpected token i know this is cosmetic but i think that there has to be a better method of declaring a namespace containing a class and prototype functions,['javascript'] +185673,quartz scheduler how to pass custom objects as jobparameter i am planning to write a aspnet page to trigger the job on demand currently i am using simpletrigger class to trigger the job but none of the trigger class supports object type as value in jobparameters and it has come to my knowledge that wcf tcp binding is used under the hook to pass the parameters to job scheduling engine i would like to know how to pass custom object serializable as job parametersthanks for your advice,"['c#', 'asp.net']" +185705,nested multiline comments in java while writing experimental code i find it very useful to comment out entire blocks of code at a time however i cannot find a reasonable way to do this in java because i frequently end up with nested blocks being commented outin c or c this is easily achieved using if 0 or if falsei cannot seem to find any such equivalent in java any help would be appreciated thanks,['java'] +185719,convert existing project to a maven project when i started my project i was not aware of maven i realized the importance of it after the project had already grown to a pretty large size at that time i was really into rapid development hence i did not really want to break the flow so i deferred plugging maven into the project now i have a little breathing space so i would like to add maven into the project what do your suggest i do or should i even do it i have spring struts log4j hibernate and jaxrs in the project,['java'] +185728,difference between clojures multimethod and cs extension methods i just watched a video on protocols in clojure and it explained how multimethods work it seems to me that they look very similar to how extension methods in c work are they basically the same thing with the exception that you do not need to create a static class in clojure or is there a fundamental difference is there an advantage or thisadvantage in using either,['c#'] +185759,detecting if nsnumber is between 0 and 255 i am trying to detect whether a nsnumber is between 0 and 255 or not whenever i run the app i receive the alert view that my number is greater than 255 even when it is not i do not have this problem with 0if redvalue 0 nslogred value is less than 0 uialertview alert uialertview alloc initwithtitleyour number must be greater than 0 messagenil delegateself cancelbuttontitleok otherbuttontitlesnil alert show alert release else if redvalue 255 nslogred value is greater than 255 uialertview alert uialertview alloc initwithtitleyour number must be less than 255 messagenil delegateself cancelbuttontitleok otherbuttontitlesnil alert show alert releaseadditionally i receive this warning on the else if redvalue 255 line ordered comparison between pointed and integer nsnumber and int so i am assuming i have to convert this nsnumber to an integer,"['iphone', 'objective-c', 'ios']" +185760,how do i undo a objectdefineproperty call fiddlevar assertion function return dummy data objectdefinepropertyobjectprototype should set function get function return new assertionthis insert magic here this needs to be falseconsolelogshould undefinedwhat options do i have in es5 to undo a defineproperty call no silly suggestions like objectdefineproperty function pleasethe following objectdefinepropertyobjectprototype should does not workand objectdefinepropertyobjectprototype should value undefined throws a uncaught typeerror cannot redefine property defineproperty in v8objectdefinepropertyobjectprototype should set function get function return undefined throws the same errordelete objectprototypeshould also does not work,['javascript'] +185784,use of python super function in django model heres some code in a django tutorial that i am going through i have never come across the super function in python before and the way it is used here is different from the examples i have seen online ie usually when you use super do not you have multiple classes it is in the last line supersnippet selfsaveforce insert force updatecould you explain exactly whats going on there and what would be an alternative way to write that it just seems like the save method is calling itself hereclass snippetmodelsmodel title modelscharfieldmax length255 language modelsforeignkeylanguage author modelsforeignkeyuser description modelstextfield description html modelstextfieldeditablefalse code modelstextfield highlighted code modelstextfieldeditablefalse tags tagfield pub date modelsdatetimefieldeditablefalse updated date modelsdatetimefieldeditablefalse class meta ordering pub date def unicode self return selftitle def saveself force insertfalse force updatefalse if not selfid selfpub date datetimedatetimenow selfupdated date datetimedatetimenow selfdescription html markdownselfdescription selfhighlighted code selfhighlight supersnippet selfsaveforce insert force update,['python'] +185786,how to iterate through a strings characters nsstring mystrings nsstring stringwithstringabcdefghijklmnopqrstuvwxyzhow could i iterate each of the letters abcde in an objectivec for loop,['objective-c'] +185809,marginbottom not working i am having a frustrating problem where i am trying to set a style on a link so that it always appears 10px from the bottom of the box it is in for some reason the marginbottom style i have applied to it is not workingthe weird thing is that margintop marginright and marginleft all work but when i put marginbottom it does not registeri am sure it is likely something stupid i am missing but i have spent far too long trying to figure out it and trying different combos but cannot seem to get it to worki have tried applying the class style directly to the link tag and also wrapping a paragraph day around the link and applying the class to it the paragraph method works in that it positions it to the right like i want but again it is not applying my marginbottom 10px any ideas as to what i am doing wrongbelow are snippets of the html for the boxes as well as the css i am using any thoughtssuggestions would be greatly appreciatedthankshtml div idboxes classcontainer div classbox idbox1 h2headingh2 plorem ipsum dolor sit amet consectetur adipiscing elit duis ac viverra orci etiam volutpat lectus vitae tellus blandit volutpat maecenas ante quam scelerisque et tempor ac varius id eros integer hendrerit pretium feugiat p a href classc2actionlinka divbox1 div classbox idbox2 h2headingh2 plorem ipsum dolor sit amet consectetur adipiscing elit duis ac viverra orci etiam volutpat lectus vitae tellus blandit volutpat maecenas ante quam scelerisque et tempor ac varius id eros integer hendrerit pretium feugiat lorem ipsum dolor sit amet consectetur adipiscing elit lorem ipsum dolor sit amet consectetur adipiscing elit p p classc2aa hreflinkap divbox2css html body div span applet object iframe h1 h2 h3 h4 h5 h6 p blockquote pre a abbr acronym address big cite code del dfn em font img ins kbd q s samp small strike strong sub sup tt var b u i center dl dt dd ol ul li fieldset form label legend table caption tbody tfoot thead tr th td margin 0 padding 0 border 0 outline 0 fontsize 100 verticalalign baseline background transparent body background f fontfamily arial verdana sansserif container margin 0 auto width 940px box width296px height270px floatleft backgroundcolorebe1bf margintop 20px borderstyle solid borderwidth 2px bordercolor e0d6b2 box h2 fontsize 16px margintop 18px marginleft 24px color 353535 box p margintop 10px marginleft 24px width 252px fontsize13px color525151 pc2a textalignright marginbottom10px fontsize 14px color00ff00 c2action a textalignright marginbottom10px fontsize 14px colorff0 box1 marginright 20px box2 marginright 20px,['css'] +185818,problems when trying to run fparsec in f interactive i am trying to run some fparsec code in f interactive but with no success i am able to build and run this tutorialfs file but the same is not happening with fsi as it did not recognize fparsecdlli have already tried running the r parsec command in fsi but it was of no availanyone has a clue on what might be the problem here,['.net'] +185822,javascript remove an array item by value my situationvar id tag 123785678473490i would like to delete where id tag 90 and to returnvar id tag 1237856784734how can i do that,['javascript'] +185829,convert string to variable name or variable type is it possible to convert strings into variablesand vise versa by doing something likemakevariableint countor string fruitcin fruit user inputs applemakevariablefruit a green round objectand then be able to just access it by doing something likecout apple a green round objectthanks in advance,['c++'] +185835,access xml element by attribute value probably this question repeated but i am not satiesfied with existing answers i want to get xml element from dynamically generated xml file by attribute value we do not know how many nodes and its herarchy but each element its sub element its subsub elements subsubsub elementsso on will contain unique guid as id attribute element id subelement idsubelement subelement id subsubelement id subsubsubelement id subsubsubsubelement idother sub inside this subsubsubsubelement subsubsubelement subsubelement subelementelementi want to find the element by only passing the guid value nonethless of its xpath its node location position how can i do this in c is i need to use linqedited xdocument xmldoc xdocumentloadxmlfilepathxelement selectedelement xmldocdescendantswherex string xattributeid myidvaluefirstordefault exception expression cannot contain lambda expressionsi have added using systemlinq namspaces,['c#'] +185862,reading properties file from maven pom file i have maven pom file with some configuration and in section plugins i have maven tomcat plugin with some configuration like thisconfiguration urlhttplocalhost8080managerhtmlurl servertomcatserverconfigurationi would like to export url setting to some property file for example tomcatproperties with that keyurlhttplocalhost8080managerhtmland how can i read this key back in my pom file,['java'] +185870,recognize numbers using gestures i want to recognize numbers using gestures through coding i have recognized using gesture library is there any possibility to recognize numbers perfectlyplease suggest any sample code,['android'] +185900,pycairo how to resize and position an image based on the question create pdf with resized png images using pycairo rescaling surface issue i have attempted to create code that rescales and places an image at a specific position as shown in the code below in this case for example the images should appear over the underlying rectangles however i cannot seem to get the image to appear at the correct locations i would appreciate knowing what i must change in order to both scale and position an image correctlyimport cairoif not cairohas pdf surface raise systemexitcairo was not compiled with pdf supportdef draw imagectx image top left height width draw a scaled image on a given context image surface cairoimagesurfacecreate from pngimage calculate proportional scaling img height image surfaceget height img width image surfaceget width width ratio floatwidth floatimg width height ratio floatheight floatimg height scale xy minheight ratio width ratio scale image and add it ctxsave ctxscalescale xy scale xy ctxtranslateleft top ctxset source surfaceimage surface ctxpaint ctxrestoredef draw boxctx left top width height draw a box on a given context ctxrectangleleft top width height ctxset source rgb1 1 1 ctxfill ctxrectangleleft top width height ctxset source rgb0 0 0 ctxstroke a4 page in pointssurface cairopdfsurfaceboxpdf 595 842context cairocontextsurface sizes in pointsheight 250width 180margin 20 draw boxesdraw boxcontext margin margin width heightdraw boxcontext margin width margin height width height draw images should be superimposed over rectangles but are notimage hellopngdraw imagecontext image margin margin height widthdraw imagecontext image margin height margin width height width,['python'] +185902,determining the version of an msi without installing it i have an msi file built from my c visual studio 2010 the version is set through the version property i wanted to know if there is a way to determine the version without having to install the file currently when right click and view the properties it is not thisplayed,['c#'] +185911,closing applications what is best practice when closing a c applicationi have read that you can useenvironmentexit0 or applicationexitbut what is the differencefurthermore with regards to environmentexit0 i have used exit codes before when working with java but have never fully understood their purpose what role do they play when exiting an application in c,['c#'] +185925,error in the push heroku json and ruby aa192 i have a problem at the time of the push heroku follow the below error gemfile detected running bundler version 107 unresolved dependencies detected installing using without developmenttest fetching source index for installing rake 092 installing abstract 100 installing activesupport 309 installing builder 212 installing i18n 050 installing activemodel 309 installing erubis 266 installing rack 123 installing rackmount 0614 installing racktest 057 installing tzinfo 0329 installing actionpack 309 installing mimetypes 116 installing polyglot 032 installing treetop 1410 installing mail 2219 installing actionmailer 309 installing arel 2010 installing activerecord 309 installing activeresource 309 installing difflcs 112 installing json 153 with native extensions usrruby192libruby191rubygemsspecificationrb519in normalize yaml input invalid byte sequence in usascii argumenterror from usrruby192libruby191rubygemsspecificationrb479in from yaml from usrruby192libruby191rubygemspackagetar inputrb183in load gemspec from usrruby192libruby191rubygemspackagetar inputrb51in block in initialize from usrruby192libruby191rubygemspackagetar readerrb64in block in each from usrruby192libruby191rubygemspackagetar readerrb55in loop from usrruby192libruby191rubygemspackagetar readerrb55in each from usrruby192libruby191rubygemspackagetar inputrb32in initialize from usrruby192libruby191rubygemspackagetar inputrb17in new from usrruby192libruby191rubygemspackagetar inputrb17in open from usrruby192libruby191rubygemspackagerb58in open from usrruby192libruby191rubygemsformatrb63in from io from usrruby192libruby191rubygemsformatrb51in block in from file by path from usrruby192libruby191openurirb35in open from usrruby192libruby191openurirb35in open from usrruby192libruby191rubygemsformatrb50in from file by path from usrruby192librubygems191gemsbundler107libbundlersourcerb72in fetch from usrruby192librubygems191gemsbundler107libbundlerinstallerrb45in block in run from usrruby192librubygems191gemsbundler107libbundlerspec setrb12in block in each from usrruby192librubygems191gemsbundler107libbundlerspec setrb12in each from usrruby192librubygems191gemsbundler107libbundlerspec setrb12in each from usrruby192librubygems191gemsbundler107libbundlerinstallerrb44in run from usrruby192librubygems191gemsbundler107libbundlerinstallerrb8in install from usrruby192librubygems191gemsbundler107libbundlerclirb225in install from usrruby192librubygems191gemsbundler107libbundlervendorthortaskrb22in run from usrruby192librubygems191gemsbundler107libbundlervendorthorinvocationrb118in invoke task from usrruby192librubygems191gemsbundler107libbundlervendorthorrb246in thispatch from usrruby192librubygems191gemsbundler107libbundlervendorthorbaserb389in start from usrruby192librubygems191gemsbundler107binbundle13in top required from usrruby192binbundle19in load from usrruby192binbundle19in main failed heroku push rejected failed to install gems via bundleri am using ruby 192,['ruby-on-rails'] +185938,java invert map i need create inverse map select unique values and for them find keysseems that only way is to iterate all keyvalue pairs because entryset returns set of so value not uniquethanks,['java'] +185969,how to unit test callback logic more complete question is given a dependency that expects a callback as a parameter how do i write a unit test that covers the callback logic and still manage to mock up the dependencypublic class dostuff public void runthisrunnable callback call callback public class classundertest private dostuff stufftodo public void methodundertest thisstufftodorunthisa runnable with some logic in the example above i would mock stufftodo since i should verify calls and mock outputs of method calls however mocking runthis results in the callback logic not being tested furthermore callback logic seems like it should be private so i wouldnt expect to test it directly perhaps that is a misconception on my partsince callbacks are used rather extensivly i would expect there to be a common method for testing them but i have not found it,['java'] +185977,how to foldunfold html tags with vim is there some plugin to fold html tags in vim or there is another way to setup a shortcut to fold or unfold html tags i would like to foldunfold html tags just like i do with indentation folding,['html'] +185981,add 0 before number if 10 this is my codestring unreadz 0while true unreadz checkmail if unreadzequals0 portwritem else portwritenif unreadz is less than 10 i want to add a 0 before it before portwritethis is what i have triedif unreadz 10 portwrite0 unreadzelse portwrite unreadzbut it does not work because unreadz is a string,['c#'] +185992,regex to match letters numbers and some specific characters i am trying to match a django url bit that can contain 09 az az spacehow can i do it so it is picked up by djangos url matcher in form of a parameterrpcharargwit needs to be herepintargd dest,['python'] +185997,php return 500 error but no error log i am having an issue when i have a php application that is returning an internal server error 500 however nothing is showing up in the error lognow i know there are error with what i am trying to run i know i have missing some files and what not but something should show in the apache error log otherwise how are i supposed to know exactly what i am missingi created a test script is errors it in under the same vhost configuration and those error show up fine so everything seems configured right as far as phpapache are there certain php errors that does show up in the error log php is configure to thisplay any type of notice warning error fatal error etcthis is running on ubunut 1004 with the standard apache and php from the ubuntu repo with aptget,['php'] +185999,redefine springnet object in multiple configuration files i am setting up my xml configuration files for my aspnet web application using springnet ioc dependency injection i referenced each of my config files in the webconfig a sample of setting in springnet configuration file settingsxml isobject idobj1 typenscommoncacheclass nscommon singletontrue initmethodinitialize destroymethodthispose property namename valuemy name objectthis all works finenow i install my web application in multiple environments so i am creating a springnet config file for environment eg dev qa prodso when installing the application the applicable environment spring file is referenced in the webconfig this is part of an automated installerwithin the qa environment file i want to redefine the object above obj1 toobject idobj1 typenscommoncacheclass2 nscommon singletontrue initmethodinitialize destroymethodthispose property namename valuemy new name objecthowever as this is automated adding the reference to the environment file the settingsxml file is not changed and now referencing 2 files with a defined object with the same id this causes major problems as run time errors will occuris there any way that i can include in the qaxml and flag or the like to highlight this object definition overrides any other defined objects in any other xml file with the same object id,['c#'] +186021,mapkit polylinewithcoordinates interconnects all points i was just curious what the correct way to draw a simple route line between a set of points was i currently have an array of coordinates and when i pass it to polylinewithcoordinates and do all the other necessary things it draws a big web of lines that interconnect all of the points to one another i have looked at a few samples but none of them seem to do anything special to account for this even when they use more than two points voidviewdidload super viewdidload add drawing of route line cllocationcoordinate2d coordinatesmycheckpoints count int i 0 for checkpoint ckpt in mycheckpoints coordinatesi cllocationcoordinate2dmakeckptlat floatvalue ckptlon floatvalue i mkpolyline route mkpolyline polylinewithcoordinates coordinates count mycheckpoints count mapview addoverlayroute mkoverlayview mapviewmkmapview mapview viewforoverlayid mkoverlayoverlay mkpolylineview polylineview mkpolylineview alloc initwithpolylineoverlay autorelease polylineviewstrokecolor uicolor greencolor polylineviewlinewidth 50 return polylineviewthis is the code in my mapviewcontroller that is responsible for the drawing just in case somebody sees what i am doing or not doingnow that i look at everything much closer is actually not connecting adjacent coordinates to each other each point only has 2 lines stemming from it connecting that point to 2 more points but i cant figure out the pattern its connecting them in,"['iphone', 'objective-c', 'ios']" +186022,what does mongodb not being acid compliant really mean i am not a database expert and have no formal computer science background so bear with me i want to know the kinds of real world negative things that can happen if you use mongodb which is not acid compliant this applies to any acid noncompliant databasei understand that mongodb can perform atomic operations but that they do not support traditional locking and complex transactions mostly for performance reasons i also understand the importance of database transactions and the example of when your database is for a bank and youre updating several records that all need to be in sync you want the transaction to revert back to the initial state if there is a power outage so credit equals purchase etcbut when i get into conversations about mongodb those of us that do not know the technical details of how databases are actually implemented start throwing around statements likemongodb is way faster than mysql and postgres but there is a tiny chance like 1 in a million that it would not save correctlythat would not save correctly part is referring to this understanding if there is a power outage right at the instant youre writing to mongodb there is a chance for a particular record say youre tracking pageviews in documents with 10 attributes each that one of the documents only saved 5 of the attributesa which means over time your pageview counters are going to be slightly off youll never know by how much you know they will be 9 correct but not 100 this is because unless you specifically made this a mongodb atomic operation the operation is not guaranteed to have been atomicso my question is what is the correct interpretation of when and why mongodb may not save correctly what parts of acid does it not satisfy and under what circumstances and how do you know when that 01 of your data is off cannot this be fixed somehow if not this seems to mean that you should not store things like your users table in mongodb because a record might not save but then again that 110 user might just need to try signing up again noi am just looking for maybe a list of whenwhy negative things happen with an acid noncompliant database like mongodb and ideally if there is a standard workaround like run a background job to cleanup data or only use sql for this etc,['sql'] +186029,what caused this invalidoperationexception using linq to sql we experienced a number of errors on our live application a week or two ago that have so far escaped explanation we saw these errors internally and they were also experienced by clients as it manifested in a set of web servicesi have included the inner exception below the project uses the csla framework and the error occured when retrieving an object from the databaseno known changes were made to the system at the time we started experiencing the errors the infrastructure consists of a number of load balances web serversthe errors seemed to be isolated to one of our servers we experienced them using a console application connecting to the web services the server in question was using a local dmz ip to resolve the web services in its hosts file and by forcing this to go externally it seemed to resolve the issuesit seems to be a very fine line between application and infrastructure to isolate this so i am wondering if anyone has any ideas or theories that could possibly explain thisinnerexception exceptiontypesysteminvalidoperationexception mscorlib version40 cultureneutral publickeytokenb77a5c561934e089exceptiontype messageexception of type systeminvalidoperationexception was thrownmessage sourcemscorlibsource helplink property namedatasystemcollectionslistdictionaryinternalproperty property nametargetsitevoid verifyintegrityproperty stacktrace at systemruntimecompilerservicesconditionalweaktable2verifyintegrity at systemruntimecompilerservicesconditionalweaktable2addtkey key tvalue value at systemlinqexpressionsexpressionctorexpressiontype nodetype type type at systemdatalinqsqlclienttranslatortranslatelinksqllink link list1 keyexpressions boolean asexpression at systemdatalinqsqlclientsqlbindervisitorconverttofetchedexpressionsqlnode node at systemdatalinqsqlclientsqlbindervisitorconvertlinkssqlexpression node at systemdatalinqsqlclientsqlbindervisitorfetchexpressionsqlexpression expr at systemdatalinqsqlclientsqlbindervisitorvisitmembersqlmember m at systemdatalinqsqlclientsqlvisitorvisitsqlnode node at systemdatalinqsqlclientsqlbindervisitorvisitexpressionsqlexpression expr at systemdatalinqsqlclientsqlbindervisitorvisitnewsqlnew sox at systemdatalinqsqlclientsqlvisitorvisitsqlnode node at systemdatalinqsqlclientsqlbindervisitorvisitexpressionsqlexpression expr at systemdatalinqsqlclientsqlbindervisitorvisitselectsqlselect select at systemdatalinqsqlclientsqlvisitorvisitsqlnode node at systemdatalinqsqlclientsqlbindervisitorvisitaliassqlalias a at systemdatalinqsqlclientsqlvisitorvisitsqlnode node at systemdatalinqsqlclientsqlvisitorvisitsourcesqlsource source at systemdatalinqsqlclientsqlbindervisitorvisitselectsqlselect select at systemdatalinqsqlclientsqlvisitorvisitsqlnode node at systemdatalinqsqlclientsqlbindervisitorvisitincludescopesqlincludescope scope at systemdatalinqsqlclientsqlvisitorvisitsqlnode node at systemdatalinqsqlclientsqlbinderbindsqlnode node at systemdatalinqsqlclientsqlproviderbuildqueryresultshape resultshape type resulttype sqlnode node readonlycollection1 parentparameters sqlnodeannotations annotations at systemdatalinqsqlclientsqlproviderbuildqueryexpression query sqlnodeannotations annotations at systemdatalinqsqlclientsqlprovidersystemdatalinqprovideriproviderexecuteexpression query at systemdatalinqdataquery1systemlinqiqueryproviderexecutesexpression expression at systemlinqqueryablesingleordefaulttsourceiqueryable1 source at namespaceadasqlnamespacebnamespacebcontextnamespaceadanamespacebinamespacebcontextgetclassaint32 objectid at namespaceanamespacebclassadataportal fetchsinglecriteria2 criteria at dmobject object at cslareflectionmethodcallercallmethodobject obj dynamicmethodhandle methodhandle object parametersstacktrace innerexceptionthank you in advance for any help or theoriesedit full exception is herelinq to sql below nothing to it and objecta is simply a wrapper class with a properties nothing more than a simple select and populate of one object bases on an id ctx is a csla contextmanagervar data from d in ctxdatacontextobjectas where dobjectid objectid select new objecta id dthispatchid clientid dclientid datecreated ddatecreated return datasingleordefault,['c#'] +186061,use html tidy to just indent html code is it possible to use html tidy to just indent html codesample codeform action methodget acceptcharsetutf8ullilabel clascreenreader forqkeywordslabelinput typetext nameq value idq liliinput clasubmit typesubmit valuesearch liulformdesired resultform action methodget acceptcharsetutf8 ul li label clascreenreader forqkeywordslabelinput typetext nameq value idq li liinput clasubmit typesubmit valuesearchli ulformif i run it with the standard command tidy f errstxt m indexhtml then i get thisdoctype html public w3cdtd html 401enhtmlheadmeta namegenerator contenthtml tidy for mac os x vers 31 october 2006 apple inc build 1536 see w3orgtitletitleheadbodyform action methodget acceptcharsetutf8ullilabel clascreenreader forqkeywordslabelinput typetext nameq value idqliliinput clasubmit typesubmit valuesearchliulformbodyhtmlhow can i omit all the extra stuff and actually get it to indent the codeforgive me if that is not a feature that it is supposed to support what library tool am i looking for,['html'] +186100,using python subprocess call to invoke python script i have a python script that needs to invoke another python script in the same directoryi did this from subprocess import call callsomescriptpyi get the following error callsomescriptpy file usrlibpython26subprocesspy line 480 in call return popenpopenargs kwargswait file usrlibpython26subprocesspy line 633 in init eread errwrite file usrlibpython26subprocesspy line 1139 in execute childraise child exceptionoserror errno 2 no such file or directoryi have the script somescriptpy in the same folder though am i missing something here thanks,['python'] +186108,rails 3 activerecord api build method i am fairly new to rubyror outside of a year and i have noticed that there are several different methods inside of ror or ruby that basically do the same thing the one method i am wanting to get some sort of clarification on is the build method when it is effective to use or how to use it in its best light sorta thingthanks,['ruby-on-rails'] +186110,how to move an entire div element up x pixels i want to reposition an entire div and its contents up about 1015 pixelshow can i do thisnote this is slider element so when i click a button the slider slides down once it is finished i want to reposition it up about 15 pixels,"['javascript', 'jquery']" +186126,get class name from file i have a php file which contains only one class how can i know what class is there by knowing the filename i know i can do something with regexp matching but is there a standard php way the file is already included in the page that is trying to figure out the class name,['php'] +186131,backbonejs with aspnet mvc in the last few days i have been reading about backbonejs and how it simplifies js code interaction with view elements basically within html i have also read about the differences between knockoutjs and backbonejs now i am thinking whether using one or the other inevitably leads to duplicating the code that we already have in our mvc app mostly viewmodels and routes in globalasax inside our views essentially requiring us to code another set of models in backbone or knockout as i understand with knockoutjs this is even more prevalent that is why i thought i will choose backbone but now i think it is not that different after a few examples i saw that same duplication is becoming evidentalso how do we maintain such an application if for instance we already have a bunch of mvc partial views and now we are supposed to recreate them in backbone using some templating engine like jquery templates,['jquery'] +186133,can javascript detect if the users browser supports gzip can i use javascript to detect if the users browser supports gzipped content client side not nodejs or similari am trying to support the following edge casethere are a lot of possible files that can load on a particular web app and it would be better to load them on demand as necessary as the application runs rather than load them all initially i want to serve these files off of s3 with a farfuture cache expiration date since s3 does not support gzipping files to clients that support it i want to host two versions of each file one normal and one gzipped with contenttype set to applicationgzip the browser of course needs to know which files to request if javascript is able to detect if the browser supports gzipped content then the browser will be able to request the correct filesis this possible,['javascript'] +186140,javascript to capitalize the next char after mc given a string like marty mcfly is there a regex or other one line solution to capitalize the f so i get marty mcfly i can always count on the space between first and last and the first letter of the last name ie the m will always be capsi am pretty open to just about any javascript jquery regex solution i just need it to be short and sweeti have got a method that takes the string apart using indexof and substring but i am hoping theres a regex or something similar,"['javascript', 'jquery']" +186144,why would not filter work in internet explorer 8 this is the linesongs songsfilterfunction el return elalbumalbum this is the errorobject does not support this property or methodthis works 100 fine in chrome whats going on,"['javascript', 'jquery']" +186151,is this c0x optimization legal is it legal for a c0x compiler to optimizeint funcint a a 3 return atoint funcint a return 3or for another pod,['c++'] +186154,existing php tool for feature toggle recently i have read a number of articles talking about the idea of using feature toggles or gatekeepers to keep features hidden from users until the development is done facebook and flickr both also talk about how they use this to test new features with a subset of users before unleashing them on everyonea bit of googling did not turn up any existing php packagestools that can be added to a web app to handle this type of thing it seems straight forward enough to roll our own but no reason to reinvent that wheel if we do not need to are there any existing php tools to do thisarticlesfeature toggle by martin fowlerflipping out on flickr devblogclarification the part of this that i am looking to see if it exists is the admin panel that controls which users can see the new features in flickrs example they can turn it on based on the host in the facebook example they add functionality such as limiting a feature to 5 of users only techcrunch users or only east coast usersthe admin panel seems crucial when you have 200 turned on features 10 features that are not quite done yet and 3 more that youre demoing for some users,['php'] +186167,how to get uilabel to respond to tap i have thiscovered that i can create uilabel much faster than uitextfield and i plan to use uilabel most of the time for my data thisplay appto make a long story short though i wish to let the user tap on a uilabel and have my callback respond to that is that possiblethanks,['ios'] +186189,is memory released when a destructor is called or when delete is called assume you have an object of class foolclass fool int abc double array fool destroys the array delete array fool fool new fool now i know you should not but some fool calls the destructor on fool anyway foolfooldoes that mean fools memory is freed ie abc are invalid or does that mean only whatever deallocations in fool function occur ie the array is deleted onlyso i guess my question is is a destructor just another function that gets called when delete is called on an object or does it do more,['c++'] +186201,example of waitpid wnohang and sigchld i need an example of waitpid wnohang and sigchld combined in c and how i can use them all with forebackground signal sigchld sig ign waitpidchild status 0,['c'] +186203,why unicode character for hearts symbol fails with html according to my understanding the following html markup should thisplay a heart symbol but it is not what i am missingi got the data about unicode characters here special characterscharacter entity references in htmlxml version10 encodingutf8 doctype html public w3cdtd xhtml 10 stricten html xmlnsheadmeta httpequivcontenttype contenttexthtml charsetutf8 titleheartstitleheadbody2665bodyhtml,['html'] +186211,creating breakpoint in xcode for unrecognized selector is it possible to set the breakpoint in xcode to have the debugger stop only on unrecognized selectori have other exceptions that are triggering and i only want to trigger on the unrecognized selector exception nothing else,['objective-c'] +186230,why does responseredirect not redirect external url context user is currently in the following page issuewhen user clicks on a button in the above page the mvc controller method that handles this click should do some processing and redirect the user to an external domain say googlecom i tried the 2 statements below separately but both calls append the external url to the current internal page that the user is onsystemwebhttpcontextcurrentresponseredirectwgooglecom plain old httpresponse objectreturn controllerresponseredirectwgooglecom mvc controllers response objectboth of the above statements result in user getting redirected to instead of just redirecting the user to wgooglecomwhat am i missing here,"['c#', 'asp.net']" +186237,dijkstra shortest path with vertexlist lists in boost graph i am quite new to boost graph i am trying to adapt an example for finding dijkstra shortest path algorithm which used vertexlist vecs i changed the vertex container to lists i learned that we have to provide our own vertex index for the algorithm to work if we use listsint mainint char typedef float weight typedef boostpropertyboostedge weight t weight weightproperty typedef boostpropertyboostvertex name t stdstring nameproperty typedef boostpropertyboostvertex index t int indexproperty typedef boostadjacency list boostlists boostlists boostdirecteds nameproperty weightproperty graph typedef boostgraph traits graph vertex descriptor vertex typedef boostgraph traits graphvertex iterator viter typedef boostproperty map graph boostvertex index t type indexmap typedef boostproperty map graph boostvertex name t type namemap typedef boostiterator property map vertex indexmap vertex vertex predecessormap typedef boostiterator property map weight indexmap weight weight thistancemap graph g vertex v0 boostadd vertexstdstringv0 g vertex v1 boostadd vertexstdstringv1 g vertex v2 boostadd vertexstdstringv2 g vertex v3 boostadd vertexstdstringv3 g weight weight0 5 weight weight1 3 weight weight2 2 weight weight3 4 boostadd edgev0 v1 weight0 g boostadd edgev1 v3 weight1 g boostadd edgev0 v2 weight2 g boostadd edgev2 v3 weight3 g stdvectorvertex predecessorsboostnum verticesg to store parents stdvectorweight thistancesboostnum verticesg to store thistances indexmap indexmap boostgetboostvertex index g namemap name viter i iend create our own vertex index this is what i changed in the original code int c 0 for boosttiei iend verticesg i iend i c indexmapi c error points to this line namei a c predecessormap predecessormappredecessors0 indexmapthistancemap thistancemapthistances0 indexmapboostdijkstra shortest pathsg v0 boostthistance mapthistancemappredecessor mappredecessormap extract a shortest path stdcout stdendl typedef stdvectorgraphedge descriptor pathtype pathtype path vertex v v3 forvertex you predecessormapv you v keep tracking the path until we get to the source v u you predecessormapv set the current vertex to the current predecessor and the predecessor to one level up stdpairgraphedge descriptor bool edgepair boostedgeu v g graphedge descriptor edge edgepairfirst pathpush back edge write shortest path stdcout shortest path from v0 to v3 stdendl float totalthistance 0 forpathtypereverse iterator pathiterator pathrbegin pathiterator pathrend pathiterator stdcout nameboostsourcepathiterator g nameboosttargetpathiterator g boostget boostedge weight g pathiterator stdendl stdcout stdendl stdcout thistance thistancemapv3 stdendl return exit successi get the following errorspveccpp6220 error no match for aoperatora in aindexboostadj list vertex property mapoperator with graph boostadjacency list boostproperty valuetype boostdetailerror property not found reference boostdetailerror property not found tag boostvertex index t boostadj list vertex property mapkey type voidistd list iterator tpoperator with tp void tp void cai am sure i made a mistake in creating my own vertex index but couldna t find out exactly whata s the issue does anyone have some suggestions on what i am doing wrong,['c++'] +186255,how to understand and learn instrument package of java recently i found there is a javalanginstrument package in jdk which is used by many frameworks to reload classes or profilei do not find many articles of using them is there any resourcebook article project to help to understand it,['java'] +186260,javascript sort custom comparator function sorting a sorted array i have an array of objects of the following formarr0 item1 1234 item2 a string i sort it first by item1 which is straightforward now i want to sort arr which is sorted by item1 again but this time by item2 but only for the elements where item1 is the same the final array would look likearr item1 1234 item2 apple item1 1234 item2 banana item1 1234 item2 custard item1 2156 item2 melon item1 4345 item2 asparagus i tried to write a sorting function for the second case like soarrsortfunctionab ifaitem1 bitem1 return aitem2 bitem2 1 aitem2 bitem2 1 0 i could combine the two sorts in one function to get the final sorted array but there will be cases where i will have to sort by just item1 or just item2,['javascript'] +186263,what does loadermanager do i am trying to understand that what does loadermanager do can anyone share an example with it must i use them when i create a cursor if not how should i use a simple example is very appreciated,['android'] +186265,heroku devise getting nomethoderror undefined method to key for usersymbol i do not know when it happened but i am getting this error nomethoderror undefined method to key for usersymbolthis behavior only happens on heroku cedar stack i use devise 142 for authentication via facebook on rails 310rc6 and ruby 192p290 it happens on the line with sign in and redirectuser authenticationuser heres my methoddef create omniauth requestenvomniauthauth authentication authenticationfind by provider and uidomniauthprovider omniauthuid if authenticationnil flashnotice i18ntdeviseomniauth callbackssuccess kind omniauthprovider sign in and redirectuser authenticationuser elsif current user current userauthenticationscreateprovider omniauthprovider uid omniauthuid redirect to profile path notice i18ntdeviseomniauth callbackssuccess kind omniauthprovider else user usernew userapply omniauthomniauth if usersave flashnotice i18ntdeviseomniauth callbackssuccess kind omniauthprovider sign in and redirectuser user else sessionomniauth omniauthexceptextra redirect to new user registration url end endend,['ruby'] +186270,android layout equivalent of html hr tag is there any android layout equivalent for html hr tag,['android'] +186285,unity3d xmlrpc and c i am actually answering my own question herei must be the only person in the world who tried to do this but given that it has taken me about a week to work this out i figured that if there is ever another person who wants to use xmlrpc in unity i will save them a weeks hasslewhat i wanted to do is talk to one of our game servers for things like leaderboards this server talks xmlrpc and i soon figured out that that is not easy in unity,['c#'] +186296,phpunit how do i create a function to be called once for all my tests i have a phpunit test case class consisting of some test functions i would like to write a onetimesetup function to be called once for all my tests in the class unlike the standard setup function which is called once for each test in the class in other words i am looking for a phpunit equivalent to the junit beforeclass annotationsame question with a onetimeteardown functionis it possible to do so in phpunit,['php'] +186301,how to interrupt or stop currently running quartz job i have some tasks that are executed with the help of java quartz jobs but i need to stop some tasks by some condition in my code i read that this can be done via interruptablejob but i did not understand in what way i should do it,['java'] +186345,javascript prototype explanation needed i normally in my project create my class in this way object literal var objectname global variables a somevalue func1 function func2 function if i have to turn this into prototype format how would i do thatwhat would be my advantage of using prototype than this one when the job is getting done with this formatwhy do people speak so much on prototype,['javascript'] +186360,create a file using javascript in chrome on client side i would like to know if i can create a text file and save the file in the users downloads section in hisher computer using javascript the way my feature should work is when the user clicks the submit button i populate the users info in the text file and then save it in his machine i would like this to work in google chromeis this possible i have seen posts that specifically tell me that it is a serious security issue,['javascript'] +186369,how to implement an interface with an enum where the interface extends comparable consider this codepublic interface foo extends comparablefoo public enum fooimpl implements foo due to the restrictions of type erasure i receive the following errorjavalangcomparable cannot be inherited with different arguments foo and fooimpli have the following requirementsfooimpl needs to be an enum because i need to use it as a default value in annotationsthe contract of my interface is that it needs to be comparablei already tried using generic bounds in the interface but this is not supported in java,['java'] +186377,why are interfaces not allowed as annotation members consider this coderetentionretentionpolicyruntimetargetelementtypemethodpublic interface bar foo foo default fooimplfooconstantcompiler errorannotation value not of an allowable typeif i replace foo with fooimpl the code is acceptedwhats the reason for this behavior,['java'] +186384,creating animation on imageview while changing image resource i have only one imageview in my layout and i am changing its resource when a gasture event detected i just want to show an animation while changing resource of imageview can i use viewflipper with one imageview,['android'] +186401,what is mojarra how is mojarra different from suns jsf reference implemenationis it just a later version is it simply a rename,['java'] +186404,how can i detect when the user is leaving my site not just going to a different page i have a handler for onbeforeunloadwindowonbeforeunload unloadmessfunction unloadmess var conf confirmwait before you go please share your stories or experiences on the message forum ifconf windowlocationhref but i am not sure how to know if the url they clicked on the page is within the sitei just want them to alert them if they will leave the site,"['javascript', 'jquery']" +186405,best way to validate a string against many patterns this is a question more about best practicesdesign patterns than regexpsin short i have 3 values from to and the value i want to change from has to match one of several patternsxwhereas to has to be a decimal number depending on what value is given in from i have to check whether a value i want to change satisfies the from condition for example the user inputs from 10 to 150 means that every value greater than 10 should be changedthe regexp itself is not a problem the thing is if i match the whole from against one regexp and it passes i still need to check which option was inputted this will generate at least 5 ifs in my code and every time i want to add another option i will need to add another if not cool same thing if i were to create 5 patternsnow i have a hashmap which holds a pattern as the key and a valuematcher as the value when a user inputs a from value then i match it in a loop against every key in that map and if it matches then i use the corresponding valuematcher to actually check if the value that i want to change satisfies the from valuethis aproach on the other hand requires me to have a hashmap with all the possibilities a valuematcher interface and 5 implementations each with only 1 short matches methode i think it sure is better than the ifs but still looks like an exaggerated solutionis there any other way to do it or is this how i actually should do it i really regret that we cannot hold methods in a hashmappass them as arguments because then i would only have 1 class with all the matching methodes and store them in a hashmap,['java'] +186417,pass session cookies in http header with python urllib2 i am trying to write a simple script to log into wikipedia and perform some actions on my user page using the mediawiki api however i never seem to get past the first login request from this page a botlogging in i do not think the session cookie that i set is being sent this is my code so farimport cookie urllib urllib2 xmletrelementtreeurl formatxmlusername userpassword passworduser data lgname username lgpassword passwordlogin step 1make the post requestrequest urllib2requesturldata urlliburlencodeuser datalogin raw data1 urllib2urlopenrequest datareadparse the xml for the login informationlogin data1 xmletrelementtreefromstringlogin raw data1login tag login data1findlogintoken login tagattribtokencookieprefix login tagattribcookieprefixsessionid login tagattribsessionidset the cookiescookie cookiesimplecookiecookiecookieprefix session sessionidlogin step 2request urllib2requesturlsession cookie header cookieprefix sessionsessionid path domainwikipediaorg httponlyrequestadd headersetcookie session cookie headeruser dataappendlgtoken tokendata urlliburlencodeuser datalogin raw data2 urllib2urlopenrequest datareadi think the problem is somewhere in the requestadd headersetcookie session cookie header line but i do not know for sure how do i use these python libraries to send cookies in the header with every request which is necessary for a lot of api functions,['python'] +186419,loading a custom yii component i am trying to use a custom class i have created to send out mail so i can keep the controller files thin i created my custom class and put it in the components folder i then addedsendmail array classapplicationcomponentssendmail underneath main components in my main config filethis should allow me to access the class directly correct i try using yiiappsendmailmailerconfirmationandyiiappmailerconfirmationand all i end up with is errorscan anyone tell me how i include a custom component maybe i am doing this all wrong,['php'] +186427,multiple aspects on one method in my application i previously used regular c attributes to annotate a method egfoosomekeya somevalue3foosomekeyb somevalue4public void themethod specialattributelogicherewhat specialattributelogichere did was to reflectively look at all the fooattributes that annotated this particular method it would then on its own create its own dictionary for all the keys and valuesi am now trying to move to postsharp because the specialattributelogic could be put into an aspect and removed from the method body which is much cleaner within onentry foo will be replaced by an aspect that extends onmethodboundaryaspecti would still like to use it the following wayfoosomekeya somevalue3foosomekeyb somevalue4but if foo has an onentry that means that the specialattributelogic will be executed twice i basically need to gather all the keys and values from each foo into a dictionary which i then apply some logic tohow to do this or best practices with postsharp thanks,['c#'] +186441,persistent work queue in c imagine i want to have a small network of worker drones possibly on separate threads and possibly on separate processes or even on different pcs the work items are created by a central programi am looking for an existing product or service that will do this all for me i know that there is msmq and also mqseries mqseries is too expensive msmq is notoriously unreliable a database backed system would be fine but i do not want to ownmanagewrite it i want to use someone elses work queue systemrelated articleshere is a similar question but it is advocating building a custom queue mechanismthe queue that i like a lot is this one from google app engine,"['c#', '.net']" +186444,what is the default order of a list returned from a django filter call short questionwhat is the default order of a list returned from a django filter call when connected to a postgresql database backgroundby my own admission i had made a poor assumption at the application layer in that the order in which a list is returned will be constant that is without using order by the list of items i was querying is not in alphabetic order or any other deliberate order it was thought to remain in the same order as which they were added to the database this assumption held true for hundreds of queries but a failure was reported by my application when the order changed unknowingly to my knowledge none of these records were touched during this time as i am the only person who maintains the db to add to the confusion when running the django app on mac os x it still worked as expected but on win xp it changed the order note that the mentioned hundreds of queries was on win xp any insight to this would be helpful as i could not find anything in the django or postgresql documentation that explained the differences in operating systems example call required tests card testobjectsusingget databasefiltername icontainskeyeditafter speaking with some colleagues of mine today i had come up with the same answer as bjarn lindqvist looking back i definitely understand why this is done wrong so often one of the benefits to using an orm django sqlalchemy or whatever is that you can write commands without having to know or understand in detail the database it is connected to admittedly i happen to have been one of these users however on the flipside of this is that without knowing the database in detail debugging errors like this are quite troublesome and potentially catastrophic,['python'] +186481,how to change shape color dynamically i have xml version10 encodingutf8shape xmlnsandroid androidshaperectangle solid androidcolorf00 padding androidleft7dp androidtop7dp androidright7dp androidbottom7dp shapetextview androidbackgrounddrawabletest androidlayout height45dp androidlayout width100dp androidtextmoderateso now i want this shape to change colors based on information i get back from a web service call so it could be maybe yellow or green or red or whatever depending on the color i receive from the web serivce callhow can i change the color of the shape based on this information,['android'] +186506,is clear a reserved word in javascript i just spent a long time figuring out that i should not use clear as the name of a function in javascripthead script typetextjavascript srcarrayjsscriptheadbody hellobr button typebutton onclickclear idpshoobuttonbr button typebutton onclickadd idaddadd a few elementsbuttonbr button typebutton onclickcheck idcheckcheck the arraybuttonbr p idresultsresults will appear herep script typetextjavascriptinitialize scriptbodyheres arrayjsvar resultsfunction initialize results documentgetelementbyidresultsfunction add resultsfirstchilddataadd function clear resultsfirstchilddata hellofunction check resultsfirstchilddata checksymptoms clicking the add and check buttons gives me the result i expect but clicking the clear button does nothingif i rename clear to clearxyz it works fine my questionsis clear a reserved word i do not see it on the list wordsis there a debugging trick i should be using to figure this kind ofthing out in the future it took me a long time i am a noob tofigure out that the name of the function was my problemmany thanksedit i am using firefox 60 and i added a line break to show where arrayjs starts,['javascript'] +186510,google maps api for android getting sha1 cert instead of md5 when i try to get the md5 fingerprint using keytool i get a sha1 fingerprint instead and the google maps doesnt recognize it how do i get the md5 fingerprint,['android'] +186515,debugging an ipad device crash with little info i am getting the following stack trace from an ipad crash pulled from the device this was pulled from a users ipad and i do not know what they were doing when it crashed how would i get more info on whywhere the app is crashing and fix ituncaught c exceptionstack trace 0 0 myapp 0x05ac1 z16terminatehandlerv 24 1 1 libstdc6dylib 0x33814e3d zn10 cxxabiv1 terminateepfvve 52 2 2 libstdc6dylib 0x33814e91 zst9terminatev 16 3 3 libstdc6dylib 0x33814f61 cxa throw 84 4 4 libobjcadylib 0x3441dc8b objc exception throw 70 5 5 foundation 0x3645192b nsthreadperformperform 654 6 6 corefoundation 0x34e16a79 cfrunloop is calling out to a source0 perform function 12 7 7 corefoundation 0x34e1875f cfrunloopdosources0 382 8 8 corefoundation 0x34e194eb cfrunlooprun 230 9 9 corefoundation 0x34da9ec3 cfrunlooprunspecific 230 10 10 corefoundation 0x34da9dcb cfrunloopruninmode 58 11 11 graphicsservices 0x339d041f gseventrunmodal 114 12 12 graphicsservices 0x339d04cb gseventrun 62 13 13 uikit 0x33a07d69 uiapplication run 404 14 14 uikit 0x33a05807 uiapplicationmain 670 15 15 myapp 0x036af main 70 16 16 myapp 0x03664 start 40,['objective-c'] +186518,what is the size of actionbar in pixels i need to know the exact size of actionbar in pixels so to apply correct background image,['android'] +186531,how to make anonymous functions with local parameters how do i make this javascript alert 0 1 and 2 instead of 3 3svar vals 1 2 3forvar i 0 i valslength i windowsettimeoutfunction alerti 10i know the reason why it does this but i cannot figure out how to pass i to the anonymous function,['javascript'] +186544,clearing users facebook session in webview i have a webview which allows a user to share an image to facebook this process involves them logging into fb after they are done i destroy the webview and the app resets and a different user is offered the same functionality the intention is for the webview to not to remain logged in from one session to the next however i am unclear on how to either manually log the user out at the end of their session calling no longer works apparently and grabbing new instances of webview and webchromeclient does not do it eitherhowever i notice that when i reinstall the application as i modify it the log in is cleared so i am assuming that somehow webkit can tell that this is a different app as it is uninstalled and reinstalled and i am hoping i can leverage this or any other mechanism to clear whatever it is that holds the users login info i am guessing it is a cookie but i am not entirely certain that it is i am sure i am not the first person to need to log the user out of fb manually but not via my own oauth since i am not the one logging them in,['android'] +186563,thiscarding data with boostasio i am using boostasio in asynchronous mode and i would like to skipthiscarddrop a message that has been sent to me over tcp i want to do this because i have already read the header for the message and i know that it is of no interest to me the message may be large so it i would prefer not to allocate space for it and even better not to transfer it into user space at alli see boostasionull buffers but it does not appear to be applicable here see,['c++'] +186566,wpf input typedialog box hi i am trying to take a single input from the user and delete some information form the grid which i thispalyso for this i want to raise a input boxdialog box which accepts the text and when i hit the button on the dialog box i want to save the datais it possible with out creating a new window or usecontrol,['c#'] +186577,what is the progid or clsid for ie9s javascript engine codenamed chakra using net i can write an app that hosts a scripting engine that complies with microsofts iactivescript conventions this includes jscript and vbscript from microsoft and also perlscript rubyscript and i do not know what else from thirdparties the way to do it in code is something like this type engine typegettypefromprogidprogid true engine activatorcreateinstanceengine as iactivescriptwhere the progid can take the value javascript jscript ecmascript vbscript and others you can do something similar when running cscriptexe specifying the progid on the command line with the e option for example this command cscriptexe file ejscriptwill run the specified file regardless of its extension through the jscript engine on my machine if i look in hklmswclasses the three progids javascript jscript ecmascript all point to the same clsid which i guess is the jscript 58 script engine f414c2606ac011cfb6d100aa00b58is there a progid or clsid i can specify to run ie9s javascript engine aka chakra does ie9s engine still get loaded by iactivescriptmicrosofts documentation suggests that it does but does not specify a progid or clsid,"['javascript', '.net']" +186578,net date without time is there one or should i not need one i am doing some domain modelling and coming across a property which to my mind would be best exposed as a date rather than a datetime without a time component is there a good reason why there is no such type in the framework it was deemed a good enough idea to add a date type to sql server also if someone knows of a handy implementation of a date class please let me know,['.net'] +186580,running ios application on simulator without building app i was wondering if it was possible to run an xcode project on the simulator without having it build the source firstwhen i click the run button in xcode 402 it builds first then runs it is it possible to run without building if it is possible how do you do itedit this may sound like a strange question but i have acquired an xcode project from a third party who is telling me to run the code without building it to get it running on the simulator not sure how to do that,['ios'] +186582,jquery timeago timestamps how to choose language i am sure this is a dumb question but i really do not know how to do iti am using timeago jquery plugin and it has locale support for multiple languagesi am translating my site from english to spanish i am using php to do this so i would like to use timeago in both languages tooi found this strings for multiple languages but how do i use them thanks,['jquery'] +186585,compiling php with gd and libjpeg support i compile my own php partly to learn more about how php is put together and partly because i am always finding i need modules that are not available by default and this way i have control over thatmy problem is that i cannot get jpeg support in php using centos 56 here are my configuration options when compiling php 538 configure enablefpm enablembstring withmysql withmysqli withgd withcurl withmcrypt withzlib withpear withgmp withxsl enablezip thisablefileinfo withjpegdirusrlibthe configure output sayschecking for gd support yeschecking for the location of libjpeg nochecking for the location of libpng nochecking for the location of libxpm noand then we can see that gd is installed but that jpeg support is not there php r print rgd infoarray gd version bundled 2034 compatible freetype support t1lib support gif read support 1 gif create support 1 jpeg support png support 1 wbmp support 1 xpm support xbm support 1 jismapped japanese font support i know that php needs to be able to find libjpeg and it obviously cannot find a version it is happy with i would have thought usrliblibjpegso or usrliblibjpegso62 would be what it needs but i supplied it with the correct lib directory withjpegdirusrlib and it does not pick them up so i guess they cannot be the right versionsrpm says libjpeg is installed should i yum remove and reinstall it and all it is dependent packages might that fix the problemheres a paste bin with a collection of hopefully useful system informationapologies for crossposting with server fault although i tried to thiscover what stack exchanges position on crossposting was and it was not clear,['php'] +186613,suppress newline in python logging module i am trying to replace an adhoc logging system with pythons logging module i am using the logging system to output progress information for a long task on a single line so you can tail the log or watch it in a console i have done this by having a flag on my logging function which suppresses the newline for that log message and build the line piece by pieceall the logging is done from a single thread so there is no serialisation issuesis it possible to do this with pythons logging module is it a good idea,['python'] +186624,determining if uilocalnotification fired with app in foreground or background when receiving a uilocalnotification the method applicationdidreceivelocalnotification is called when the app is in foregroundwhen the app is in the background it opens the application and then calls applicationdidreceivelocalnotification how can i determine which one of these scenarios are taking place i would like to treat them differently if the app was in the background then the user indicated they want to look at the event so in applicationdidreceivelocalnotification i do not want to ask them again i just want to take them to the eventbut if the application is in the foreground when the notification fires and calls applicationdidreceivelocalnotification i want to ask the user if they want to view the event in essence i would have voidapplicationuiapplication application didreceivelocalnotificationuilocalnotification notification if applauncedfrombackground go to eventelse ask if user wants to view eventi have thought of writing a bool value to an nsuserdefault inside applicationwillenterforegroundapplication and then reading and resetting it inside applicationdidreceivelocalnotification but i thought if there was a way to test that would be a much better routethanks markedit thanks xuzhe but that is not going to work in this situation here is a little more detail that may explain why it wont work and maybe help someone in answering this for methe uilocalnotification that i am setting here is an event like a calendar event that is scheduled to fire at a user selected time so when scheduling the notification i will have no idea what the user is going to be doing when the notification fires i am using the userinfo of the notification to store data about the event that is scheduled but setting a value like inbackground as suggested wont work i do know it will be one of two situations if the user decides they want to view the event this all will assume the app is either in the background or foreground and not quit1 if it fires while the app is not being used the app is in the background and not quit ios will notify the user that an event has occurred and provide an option for going to the responsible app which is mine in this case at that point assuming the user says yes take me to this cool app it will open the app from the background and call the applicationdidreceivelocalnotification where i can get all the notification userinfo2 the user by chance happens to be in my application when the scheduled event takes place at that point the applicationdidreceivelocalnotification method is called again where i can then get all the notification userinfobut it is at this point that i want to know which of the two scenarios just took place 1 or 2hope this additional detail about my use of the uilocalnotification will help in answering this question thanks in advance markend edit,"['iphone', 'objective-c']" +186631,jsonp and backbonejs i would like to use backbonejs with a rest api i control i was hoping to have the rest api and the backbone scripts live on a different domain but unfortunately this will be blocked as it is a cross domain requestdoes backbonejs have an built in functionality to support jsonp requests or alternatively does anyone have any experience with manually adding jsonp support to backbonejs sync system,['javascript'] +186636,d3js and documentonready i am just getting started with d3js and there is one detail which is completely eluding me how do i have my code execute only after the dom is ready to receive inputi could of course use something like jquery but that seems excessivein every d3js example i have encountered there seems to be no special documentonready type of routine yet all the examples work flawlessly when testing code on my end however the code totally fails if executed before the dom is ready throwing my code into a windowonload confirms thiswhat gives,['javascript'] +186653,why virtual keyword is used in c masterdetail model refer to the entityframework article and other asp mvc webinars from microsoft such as1 2 they use virtual keyword to reference between master and detail modelscould you explain 1 why they use virtual keyword and 2 what drawbacks occur without the keywordregards,['c#'] +186663,viewing excel files in my android app i am working on an android app in which i have to open close excel files on button click these excel files will be readonly after closing the excel file it should direct me to the app please suggest me a way to do this,['android'] +186667,check if an object is nsinteger i hope to check the type of an object for nsstringtheobject iskindofclassnsstring classit works but for nsintegertheobject iskindofclassnsinteger classwill report errorwelcome any comment,"['iphone', 'objective-c']" +186679,inheritance confusion alright so i have been working on a game engine and i am running into a problem currently i have a hierarchy of classes imageanimationobject all of which have a method get type and i am having this problemif i declare a derived class using the new keyword or statically i get the desired results object instancecout instanceget type returns an int value object pointer newobjectcout pointerget typefrom the above code the console outputs 3 the method is declared as such in objectimage classclass imagepublic virtual int get typeint objectget type return 1animation classclass animation public imagepublic virtual int get typeint animationget type return 2object classclass object public animationpublic virtual int get typeint objectget type return 3now the problem arises when i do something like thisobject t objectcout tget type the result is now 1if i remove the virtual keyword from the class declaration of the object class it works as i expect the last bit of code returns 3question how can i utilize my virtual methods from the object pointer without using the new keyword reason being i am filling a vector with pointers to these objects and creating them as i am adding them so i hope to be able to do something like the followingvectorobject objects not imgs or animationsfor int a 0 a 20 a objectspush backobjectand have any objectxget type return the correct class type the reason for this is an event system that i am using in my game that needs the origination class typetldr i really stink at inheritance can you help,['c++'] +186694,using python iterparse for large xml files i need to write a parser in python that can process some extremely large files 2 gb on a computer without much memory only 2 gb i wanted to use iterparse in lxml to do itmy file is of the formatitem titleitem 1title descdescription 1descitemitem titleitem 2title descdescription 2descitemand so far my solution isfrom lxml import etreecontext etreeiterparse myfile tagitem for event elem in context print elemxpath descriptiontext del contextunfortunately though this solution is still eating up a lot of memory i think the problem is that after dealing with each item i need to do something to cleanup empty children can anyone offer some suggestions on what i might do after processing my data to properly cleanup,['python'] +186703,using mysql database to authenticate users in spring security i want to use spring security to authenticate users in my web applicationsince am not a matured user to spring framework i cannot get a clear idea about how we can do the configuration settings to use jdbcuserservice i had done the following configurationsbut its not workingauthenticationmanager authenticationprovider jdbcuserservice datasourcerefmydatasource authenticationprovider authenticationmanagerbeansbean idmydatasource classorgapachecommonsdbcpbasicdatasource destroymethodclose beansproperty namedriverclassname valuecommysqljdbcdriver beansproperty nameurl valuejdbcmysqllocalhost3306testdb beansproperty nameusername valueadmin beansproperty namepassword valueadminbeansbeancan anyone please help me to solve the issue with a sample config filethanks in advance,['mysql'] +186704,stubbing a property twice with rhino mocks for some objects i want to create default stubs so that common properties contains values but in some cases i want to override my default behaviour my question is can i somehow overwrite an already stubbed valuefirst i create the default stub with a default valuevar foo mockrepositorygeneratestubifoofoostubx xthevaluereturn1somewhere else in the code i override the stubbed valuefoostubx xthevaluereturn2assertareequal2 foothevalue fails since thevalue is 1,['c#'] +186705,gridview thisable edit on 1 column aspnet i am using a gridview edit to edit the values i have in my gridview when i press edit all columns can be edited i would like that one of the columns is not allowed to be editedis there any way i can do thisthiss is my aspx codeaspgridview idgridview1 runatserver allowsortingtrue onrowcommandgridview1 selectedindexchanged1 autogenerateeditbuttontrue onrowcancelingeditgridview1 rowcancelingedit cellspacing10onrowupdatinggridview1 rowupdating showfootertrue onselectedindexchangedgridview1 selectedindexchangedonroweditinggridview1 roweditingaspgridviewthanks,"['c#', 'asp.net']" +186727,how to access xnameproperty in code for non frameworkelement objects similar to another question i would like to access the xname property of an object through code tough in this case the object in question is not a frameworkelement and thus does not have a name property i do not have access to the member variable either in my situation i have a listview with named columns and would like to extend the listview class so that it persists the column layout for this functionality i need named columns and it would make sense to me to reuse the xname property i need to set anyway for other reasons instead of adding an attached columnname property for examplemy current solutiongridviewcolumn headerx localcontrolsextendedlistviewcolumnnameiconcolumn desiredgridviewcolumn headerx xnameiconcolumn so is it possible to get the xname value somehow,"['c#', '.net']" +186739,prerendered icon flag true in submitted iphone app binary details but icon shown with glossy effect in store icon already includes gloss effects is set to yes in plist file it worked for iphone app 10 version the same plist file without any modifications 11 version is submitted for revision and got it approved but the icon is shown in store with glossy effect checked the plist filename in target and is referring to correct file opened plist file in textedit and can see uiprerenderedicon as true version 12 binary uploaded again and i can now see prerendered icon set to true in binary details but the app icon in app details page is still shown with gloss effect what am i missing here i am using xcode 402 version and 43 sdk,['iphone'] +186754,why can i use constants as statements in c why does this program below not show any error int main void angus 1 314 return 0,['c'] +186756,checking session if empty or not qwhen checking session if empty or notshould i use some thing like thatifsessionemp num null if stringisnulloremptysessionemp numtostring the code or just ifsessionemp num null the code because sometimes when i check only with if stringisnulloremptysessionemp numtostring the code i face the following exceptionnull reference exception,"['c#', 'asp.net']" +186760,slash and backslash in ruby i want to write a application that works in windows and linux but i have a path problem because windows use and linux use how can i solve this problemthanks,['ruby'] +186772,showing tool tip for every item in datagridview row when mouse is above it how can you show the tooltip for datagridview for every item in datagridview when you hover mouse over the item in that particular rowi have table product with columnsproduct name product price product descriptionproduct image i have a requirement that i have a datagridview with columns and i am getting these from databaseproduct name product price product image now i want to show the tooltip like this if i have mouse over the product image the product description will be thisplayed for that product i want to do this for every row would anyone please help on this one,"['c#', '.net']" +186802,change colors for jprogressbar with nimbus does anyone know how to change the colors for jprogressbar when you use nimbus lookandfeel,['java'] +186809,why does creating a video element dynamically using jquery not work in ie9 i am trying to recreate the following with jqueryvideo width640 height264 autoplay source src typevideomp4 source src typevideowebm source src typevideoogg videoi have come up with the following but in ie9 the video element is empty can anyone tell me why and what i would need to change to be able to dynamically add videos in ie9 it works fine in firefox chrome and safarihtmldiv idvideoholderdivjqueryvar video video width640 height264 autoplayvideo appendsource src typevideomp4 appendsource src typevideowebm appendsource src typevideoogg appendtovideoholderupdated closed the video tag above and aded new link,"['jquery', 'html']" +186827,get part of the map view as an image in ios i am creating an app where in i have to show just the part of the area where on my place will be plotted similar like the one belowclicking on this will image will take my app further but here it is just an static image generated depending upon my longitude and latitudeany help would be really appreciatedthanks,['iphone'] +186835,use stringcontains with switch i am doing an c app where i use if messagecontainstest consolewritelineyes else if messagecontainstest2 consolewritelineyes for test2there would be any way to change to switch the if statements,['c#'] +186839,my listview does not fill parent relativelayout androidlayout widthfill parent androidlayout heightfill parent textview androidididtv test androidtexttest androidlayout widthwrap content androidlayout heightwrap content listview androidididlist test androidlayout widthfill parent androidlayout heightfill parent androidlayout belowidtv test listviewrelativelayoutand everything is in a scrollview i do not know why but the relative layout seems to set a wrap content and it makes the listview small and not taking the whole placei do not know if it is useful but heres my java code public class showview extends activitylistview lvarrayadapterstring adapterstring mylist one two three four five six seven height nine tenoverrideprotected void oncreatebundle savedinstancestate todo autogenerated method stub superoncreatesavedinstancestate setcontentviewrlayoutshow lv listview findviewbyidridlist test adapter new arrayadapterstringgetapplicationcontext androidrlayoutsimple list item 1 mylist adaptersetdropdownviewresourceandroidrlayoutsimple list item 1 lvsetadapteradapter,"['java', 'android']" +186843,how can i store an integer array in sharedpreferences i want to saverecall an integer array using sharedpreferences is this possible,['android'] +186864,generating python cli man page i am developing a python cli tool using optparse in python26 but hope to switch soon to python27 and i am about to write the man pagei have some experience on generating dynamic man pages bycreating a dedicated method that composes a string in pod format and writes it to a fileexecuting the pod2man command to generate data in groff format to be passed to the man commandi would also like to generate wiki pages with the same content as the man page with pod i can generate html through pod2html and probably the html can be easily translated into wiki formathas someone a better ideaflow on how to do thisone thing i have found as interesting is on this link creating man pages using optparse and thistutils,['python'] +186873,how to specify image size in pixels quick question about specifying the size of images in pixelsimg srclogojpg altlogo width200px height120px orimg srclogojpg altlogo width200 height120 i have been always putting in the px but recently noticed that very few people do this am i better off leaving that out does it matter one way or the other,['html'] +186881,how do i load an url in iframe with jquery i want to load an iframe on click this is what i have so farframeclickfunction thisload it does not work this is the complete code js bin,['jquery'] +186927,what is the advantage of using reachability what is the advantage of the using reachability over the code below i feel that reachability has a huge amount of code but if it is better in any way then i would use that insteadnsstring connectionstring nsstring alloc initwithcontentsofurlnsurl urlwithstringif connectionstring length 0 no connectionnow granted if google ever went down then this wouldnt work but there is literally no chance of that happening what do you think thanks,"['iphone', 'objective-c', 'ios']" +186955,sql how to select a single id row that meets multiple criteria from a single column i have a very narrow table user id ancestrythe user id column is self explanatorythe ancestry column contains the country from where the users ancestors haila user can have multiple rows on the table as a user can have ancestors from multiple countriesmy question is this how do i select users whose ancestors hail from multiple specified countriesfor instance show me all users who have ancestors from england france and germany and return 1 row per user that met that criteriawhat is that sql user id ancestry 1 england 1 ireland 2 france 3 germany 3 poland 4 england 4 france 4 germany 5 france 5 germanyin the case of the data above i would expect the result to be 4 as user id 4 has ancestors from england france and germanythanks in advanceps to clarify yes the user id ancestry columns make a unique pair so a country would not be repeated for a given userpps i am looking for users who hail from all 3 countries england france and germany and the countries are arbitraryps i am not looking for answers specific to a certain rdbms i am looking to answer this problem in generali am content w regenerating the where clause for each query provided generating the where clause can be done programmatically eg that i can build a function to build the where from where clause,['sql'] +186966,how can i check a input field exists in the form when i submit it to the server how can i check a input field exists in the form when i submit it to the serverfor instance i want to check whether a check box named mem follow exists or not in the formor do i have to use javascript jquery,"['php', 'jquery']" +186986,how to set system properties in c how can i set system properties in c in java i can usesystemsetpropertywebdriverchromedriverpathtowhereyouveputchromedriverexehow to do this in c,['c#'] +186989,managing scope and object lifetime within stl vectors coming from a c world i am struggling to make sure i do not introduce memory leaks and errors in a c project i have been assigned to i am writing code that uses structs to parse information from a buffer of data because the number of data structures that appear in the buffer can vary at runtime an stl vector is used to store the processed data i came across the following block of code in the existing software and am struggling to understand why it worksmyvectorofobjectsclearfor unsigned int8 i 0 i numberofobjects i myparserobject parserobject declaring without new parserobjectdecodebuffer offset size a method on the struct myvectorofobjectspush backparserobject does this keep parserobject in scopemy questions are specificallyaccording to this question wouldnt parserobject go out of scope each iteration since the new keyword is not used evidently this code has been workingin this case does placing the object in a vector keep the parserobject in scopeaccording to this question the parserobject is copied if this is the case what are the performance implications eg memory consumption memory allocation etc of this also do the copied parserobjects then assume the same scope as the vectorthanks for any help,['c++'] +186993,how to get a photos original filename in ios i am currently developing an ipad app where a user will enter a photo filename in a text field as part of field notes then later they will import their photos to the ipads photo library the app will access the library using alassetslibrary and enumerate over the photos looking for ones with the filename they entered in their field notes this would be the filename given to the photo by the camera that took it for example dsc 0019jpg is this not possiblei noticed that if i import photos from my camera to ipad then open iphoto on my mac and look at the ipad as a camera i can get info on the images held on the ipad and see the original filename i am looking for however this is not contained in the metadata on the ipadany help would be greatly appreciated here is my codein working with the cfdictionary pretty much everything is null except the exif keys which do not have what i am looking for voidviewdidload super viewdidload start activity animation selfactivity sethiddenno selfactivity startanimating init our arrays autoassignedassets nsmutablearray alloc init unassignedrecords nsmutablearray alloc init unassignedassets nsmutablearray alloc init setup the library alassetslibrary library alassetslibrary alloc init block assetenumerator void assetenumeratoralasset nsuinteger bool alasset result nsuinteger index bool stop if result nil if result valueforpropertyalassetpropertytype isequaltostringalassettypephoto alassetrepresentation representation result defaultrepresentation create a buffer to hold the data for the assets image uint8 t buffer bytemallocrepresentationsize copy the data from the asset into the buffer nsuinteger length representation getbytesbuffer fromoffset 00 lengthrepresentationsize errornil convert the buffer into a nsdata object free the buffer after nsdata adata nsdata alloc initwithbytesnocopybuffer lengthrepresentationsize freewhendoneyes setup a dictionary with a uti hint the uti hint identifies the type of image we are dealing with ie a jpeg png or a possible raw file specify the source hint nsdictionary sourceoptionsdict nsdictionary dictionarywithobjectsandkeys idrepresentation uti kcgimagesourcetypeidentifierhint nil create a cgimagesource with the nsdata a image source can contain x number of thumbnails and full images cgimagesourceref sourceref cgimagesourcecreatewithdatacfdataref adata cfdictionaryref sourceoptionsdict adata release cfdictionaryref imagepropertiesdictionary get a copy of the image properties from the cgimagesourceref imagepropertiesdictionary cgimagesourcecopypropertiesatindexsourceref0 null nsstring imagefilename nsstringcfdictionarygetvalueimagepropertiesdictionary kcgimagepropertyciffimagefilename nslog nsdictionary cfdictionarygetvalueimagepropertiesdictionary kcgimagepropertyexifdictionary cfnumberref imagewidth cfnumberrefcfdictionarygetvalueimagepropertiesdictionary kcgimagepropertypixelwidth cfnumberref imageheight cfnumberrefcfdictionarygetvalueimagepropertiesdictionary kcgimagepropertypixelheight int w 0 int h 0 cfnumbergetvalueimagewidth kcfnumberinttype w cfnumbergetvalueimageheight kcfnumberinttype h cleanup memory cfreleaseimagepropertiesdictionary cfreleasesourceref nslogwidth d height d w h nslog imagefilename nsdictionary metadata result defaultrepresentation metadata nslognnasset info result nslognmetadata metadata autoassignedassets addobjectresult end if photo end if end assetenumerator block block assetgroupenumerator void assetgroupenumeratoralassetsgroup bool alassetsgroup group bool stop ifgroup nil group enumerateassetsusingblockassetenumerator end if now were done reload and stop animations selftableview reloaddata selfactivity stopanimating selfactivity sethiddenyes end assetgroupenumerator block block failureblock void failureblocknserror nserror error nsstring errortitle error localizeddescription nsstring errormessage error localizedrecoverysuggestion nsstring errorfailuredesc error localizedfailurereason nslogerror suggestion failure desc errortitle errormessage errorfailuredesc end failureblock loop over all the albums and process the pictures with the blocks above library enumerategroupswithtypesalassetsgroupall usingblockassetgroupenumerator failureblock failureblockend viewdidload,"['objective-c', 'ios']" +187023,fft on iphone to ignore background noise and find lower pitches i have implemented demetris pitch detector project for the iphone and hitting up against two problems 1 any sort of background noise sends the frequency reading bananas and 2 lower frequency sounds are not being pitched correctly i tried to tune my guitar and while the higher strings worked the tuner could not correctly thiscern the low ethe pitch detection code is located in riointerfacemm and goes something like this get the dataaudiounitrender convert int16 to floatconvert divide the signal into evenodd configurationvdsp ctozcomplexoutputbuffer 2 a 1 nover2 apply the fftvdsp fft zripfftsetup a stride log2n fft forward convert split real form to split vectorvdsp ztoca 1 complex outputbuffer 2 nover2demetri then goes on to determine the dominant frequency as followsfloat dominantfrequency 0int bin 1for int i0 in i2 float curfreq magnitudesquaredoutputbufferi outputbufferi1 if curfreq dominantfrequency dominantfrequency curfreq bin i12 memsetoutputbuffer 0 nsizeofsint16 update the ui with our newly acquired frequency valuethislistener frequencychangedwithvaluebinthissampleratebuffercapacityto start with i believe i need to apply a low pass filter but i am not an fft expert and not sure exactly where or how to do that against the data returned from the vdsp functions i am also not sure how to improve the accuracy of the code in the lower frequencies there seem to be other algorithms to determine the dominant frequency but again looking for a kick in the right direction when using the data returned by apples accelerate frameworkupdatethe accelerate framework actually has some windowing functions i setup a basic window like thiswindowsize maxframestransferbuffer floatmallocsizeoffloatwindowsizewindow floatmallocsizeoffloatwindowsizememsetwindow 0 sizeoffloatwindowsizevdsp hann windowwindow windowsize vdsp hann norm which i then apply by inserting vdsp vmuloutputbuffer 1 window 1 transferbuffer 1 windowsize before the vdsp ctoz function i then change the rest of the code to use transferbuffer instead of outputbuffer but so far have not noticed any dramatic changes in the final pitch guess,['iphone'] +187046,rspec route testing and hosts i see i can test routes with rspec like thisgetshould route towelcomeindexbut i have constraints based on the hostname or parts of hostnames and redirects between several ones how do i specify a hostname when testinghow do i run the tests with proper configuration i tried printing root url and i gotmissing host to link to please provide the host parameter set default url optionshost or set only path to true,"['ruby-on-rails', 'ruby']" +187051,how can i remove a shadow in iphone i am using the standard way of making shadows from a button programmatically but i would like to shadow to no longer exist after i am done with the button i could set opacity to 0 but would the shadow still exist and if so would it still tax the system thanksthis gives an errortempbuttonsuperviewlayershadowoffset nil tempbuttonsuperviewlayershadowradius nil tempbuttonsuperviewlayershadowopacity nil,['iphone'] +187056,what are the benefits of cursorloaders i use cursors extensively in my app to load and occasionally write information from and to a database i have seen that honeycomb and the compatibility package have new loader classes designed to help with loading data in a good way essentially are these new classes in particular cursorloader considerably better than previous methods of managing data what is the benefit of a cursorloader over managed cursors for exampleand i use a contentprovider to deal with data which obviously takes uris but how does this mesh with the initloader method must i set up each of my fragments to use loaders individually and how unique does the id need to be for each loader is it over the scope of my app or just a fragment is there any simple way of simply passing a uri to a cursorloader to query my dataall i can see at the moment is that loaders add an unnecessary extra step to getting my data into my app so can someone explain them to me better,['android'] +187075,ruby methods that either yield or return enumerator in recent versions of ruby many methods in enumerable return an enumerator when they are called without a block1234map enumerator 1 2 3 4map 1234map x x2 2 4 6 8 i want do do the same thing in my own methods like soclass array def doubleblock endendarr 1234puts with block yielding directlyarrdouble x p x puts without block returning enumeratorenum arrdoubleenumeach x p x,['ruby'] +187092,collections and stream classes equivalences between smalltalk perl python and ruby i have few experience with languages like python perl and ruby but i have developed in smalltalk from some time there are some pretty basic smalltalk classes which are very popular and crosmalltalk implementationfilestreamreadwritestreamsetdictionaryorderedcollectionsortedcollectionbagintervalarraywhich classes would be the equivalent or valid semantic replacements in python perl and ruby i have found several language comparison pages comparing syntax however it seems there is little help when comes to the translation of core and base librariesi also wonder if there is a base or core class in python perl or ruby which is not present in smalltalk or viceversa,"['python', 'ruby']" +187109,copyprotection traps just about to release a free version of my app and i am looking towards the freemium model to give extra options to users however i am definitely worried about it being pirated too quickly for me to make any anythingdoes anybody have some quality copyprotection techniques for android and i am not talking about the pos lvl that is provided i am looking for some sneaky traps to detect if my code has been tampered with any ideas welcome gotta make it hard enough on them that its just not worth it,['android'] +187118,unbound class path variable java android eclipse what does the meaning of unbound class path variable on eclipse i got the error and do not know how to fix it,"['java', 'android']" +187126,how to change the font size in uipickerview i have one uipickerview this is having nearly 200 items each items has long texts so i want to resize the uipickerviews font size how can i change it it is possiblecan any one help me thanks yuvam,['iphone'] +187158,what is this character a and how do i remove it with php it is a capital a with a on top ait is showing up in strings pulled from webpages it shows up where there was previously an empty space in the original string on the original site this is the actual character that is stored in my database it is also what thisplays on my website when i echo a string that contains iti realize it is a character encoding problem when i originally process the webpage but i am now stuck with these characters in my database i have to convert this character when it is thisplayed or somewhere else in the php before outputting html that contains it i cannot reprocess the original documentsi have tried str replace and html entity decode and neither do anythingwhat else should i try,['php'] +187195,debugging of image processing code what kind of debugging is available for image processingcomputer visioncomputer graphics applications in c what do you use to track errorspartial results of your methodwhat i have found so far is just one tool for online and one for offline debuggingbmd attaches to a running process and enables you to view a block of memory as an imageimdebug enables printfstyle of debuggingboth are quite outdated and not really what i would expectwhat would seem useful for offline debugging would be some style of image logging lets say a set of commands which enable you to write images together with text probably in the form of html maybe hierarchical easy to switch off at both compile and run time and the least obtrusive it can get the output could look like this output from our simple tool aclinear dbhtmlare you aware of some code that goes in this directioni would be grateful for any hints,['c++'] +187205,is realloc safe in embedded system while developing a piece of software for embedded system i used realloc function many times now i have been said that i should not use realloc in embedded without any explanationis realloc dangerous for embedded system and why,['c'] +187207,ways to define a global method in ruby i am writing a small gem and i want to define a dsllike method pretty much the same as the desc and task methods in rakerake defines them as private methods in the rakedsl module and then selfextend rakedslto mix the module into the main object i am a newbie and go ahead laugh if i am wrongwhat are the benefits by doing so is it because making these methods private can prevent any other objects to use them that is to prevent something like some objdesc what if i define the methods in kernelmodule kernel private include rakedslendis there any difference,['ruby'] +187248,one vs2010 bug allowing binding nonconst reference to rvalue without even a warning string foo return hello int main below should be illegal for binding a nonconst lvalue reference to a rvalue string tem foo below should be the correct one as only const reference can be bind to rvaluemost important const const string consttem foo gcc is the good one to give a compile error invalid initialization of nonconst reference of type stdstring from a temporary of type stdstringvs2008 is not too bad as at least it gives a compile warningwarning c4239 nonstandard extension used initializing conversion from stdstring to stdstring a nonconstreference may only be bound to an lvaluehere comes the problematic one vs2010sp1 comples fine without anyerror or warning why i know rvalue reference in vs2010 can be used to bind with rvalue but i am not using instead in the demo code i was just using nonconst lvalue reference can somone help me explain the behavior of vs2010 here is it a bug thanks,['c++'] +187251,trueway solution in java parse 2 numbers from 2 strings and then return their sum quite a stupid question given the codepublic static int sumstring a string b throws what int x integerparseinta throws numberformatexception int y integerparseintb throws numberformatexception return x ycould you tell if it is good java or not what i am talking about is numberformatexception is an unchecked exception you do not have to specify it as part of sum signature moreover as far as i understand the idea of unchecked exceptions is just to signal that programs implementation is incorrect and even more catching unchecked exceptions is a bad idea since it is like fixing bad program at runtimewould somebody please clarify whetheri should specify numberformatexception as a part of methods signaturei should define my own checked exception baddataexception handle numberformatexception inside the method and rethrow it as baddataexceptioni should define my own checked exception baddataexception validate both strings some way like regular expressions and throw my baddataexception if it does not matchyour ideaupdateimagine it is not an opensource framework that you should use for some reason you look at methods signature and think ok it never throws then some day you got an exception is it normalupdate 2there are some comments saying my sumstring string is a bad design i do absolutely agree but for those who believe that original problem would just never appear if we had good design heres an extra questionthe problem definition is like this you have a data source where numbers are stored as strings this source may be xml file web page desktop window with 2 edit boxes whatever your goal is to implement the logic that takes these 2 strings converts them to ints and thisplays message box saying the sum is xno matter whats the approach you use to designimplement this youll have these 2 points of inner functionalitya place where you convert string to inta place where you add 2 intsthe primary question of my original post isintegerparseint expects correct string to be passed whenever you pass a bad string it means that your program is incorrect not your user is an idiot you need to implement the piece of code where on one hand you have integerparseint with must semantics and on the other hand you need to be ok with the cases when input is incorrect should semanticsso briefly how do i implement should semantics if i only have must libraries,['java'] +187266,how do i compile the asm generated by gcc i am playing around with some asm code and something is bothering mei compile thisinclude stdiohint mainint argc char argv printfhello worldn return 0with gcc filec s o files this generates a nice little piece of asm code cstringlc0 ascii hello world0 textglobl main mainlfb3 pushq rbplcfi0 movq rsp rbplcfi1 subq 16 rsplcfi2 movl edi 4rbp movq rsi 16rbp leaq lc0rip rdi call puts movl 0 eax leave retlfe3 section text eh framecoalescedno tocstrip static symslive supporteh frame1 set lset0lecie1lscie1 long lset0lscie1 long 0x0 byte 0x1 ascii zr0 byte 0x1 byte 0x78 byte 0x10 byte 0x1 byte 0x10 byte 0xc byte 0x7 byte 0x8 byte 0x90 byte 0x1 align 3lecie1globl maineh mainehlsfde1 set lset1lefde1lasfde1 long lset1lasfde1 long lasfde1eh frame1 quad lfb3 set lset2lfe3lfb3 quad lset2 byte 0x0 byte 0x4 set lset3lcfi0lfb3 long lset3 byte 0xe byte 0x10 byte 0x86 byte 0x2 byte 0x4 set lset4lcfi1lcfi0 long lset4 byte 0xd byte 0x6 align 3lefde1 subsections via symbolsmy next problem is really how do i compile this output and can i make gcc do it for me,['c'] +187276,find the query from query id in mysql can i find the exact query from mysql query idthis is a part of show engine innodb status in mysqlmysql thread id 1106 query id 1360 localhost 127001 test2transaction 0 19491 not started os thread id 2960035840is there a way by which i can find what was the query with id 1360,['mysql'] +187281,table cells fixed height regardless the content of the cell i have a dynamic table that i generate after getting some inputs from the user to present some tabular data i need to know if there is away to assign a fixed height for the cells even if some of them have some content text i would like all the cells to have 30px height regardless if they have content or if they are emptythis is the css i have table width 90 height100 table th table td border 1px solid gray height30px important padding 9px important width 16 the table is generated by this code foreach thisrows as i row tbody tr nhtmlel tr classdatarow i foreach thisfields as field tbody traddnhtmlel tdclassfieldnamesethtmlrowfieldname but when i have a cell that has some text the cell height expands anyway any ideas,['css'] +187299,how reliable is the filesystemwatcher in netframwork 4 has anyone used the filesystemwatcher in framework 4 and have you encountered any problemsi am using it in a windows service and i cant afford for it to faili have heard from a friend that it is not very reliable but i have been testing for a few hours now and i havent had any problems but i am still doubting using iti would appreciate any advice on this matter i dont want to deliver the app to the the client and then realise that this thing is going to crashthanksthanks for the advice guysi think for my purposes it should be ok it will be checking a folder on the local drive of the server and all its checking for is if a file have been modified so i think it should be fine,['.net'] +187321,linq to entities vs linq to objects are they the same i usually use the term entity to represent a business data object and in my mind the linq to entities and linq to objects were the same is that not correct,['c#'] +187333,why is the culture name for english caribbean en029 why is the culture name for english caribbean en029i know enca is used for english canada but why 029 what does it signify why was it chosen,"['c#', '.net']" +187366,check length of multidimensional arrays with javascript possible duplicatelength of javascript associative array i want to check the length of a multidimensional array but i get undefined as the return i am assuming that i am doing something wrong with my code but i cannot see anything odd about italertpatientsdatalength undefinedalertpatientsdataxlength undefinedalertpatientsdataxfirstname a namefruits banana orange apple mangoalertfruitslength 4thoughts could this have something to do with scope the array is declared and set outside of the function could this have something to do with json i created the array from an eval statement why does the dummy array work just fine,['javascript'] +187379,jquery load doesnt work at all in ie8 google is full of this question but none of the other pages help me i have tried changing jquery versions tried doing the whole var j jquerynoconflict tried rearranging jsjquery scripts tried the no caching thing suggested by jquery website but still my load does not worka onclickloadcontcanyouphpcan you help usafunction loadcontfilejmaincontloadfilealertfilereturn falseas always it loads on every other browser except ie8 the alart is there for ie8 debugging and the file is passed successfully its just not loaded into maincontany help aboutthe code or replies appreciatedthanks,['jquery'] +187402,xcode 4 transfering package pathologically slow after deleting app i have noticed that when performing native debugging on xcode 4 if i have my app installed then delete the app then attempt to debug again from xcode 4 the time it takes to perform the step transferring package is pathologically slow has anyone else experienced this i dread deleting the app as it will take 2030 minutes to load the appour app has lots of user files that get deleted when app is deleted perhaps some sort of synclike process is running at same time killing xcode 4 does not fix the issue,['iphone'] +187415,c enum array accepting a wrong value i was working on a web service method that will receive an array of ints as parameter and then inside the method i converted the values in the array into enum values and stored them in a enum list however when a value that is not in the enum is passed it is added to the enum list with no problems no invalidcastexception nothing i made a test project that looks like thisstatic class program static void mainstring args listtestvalues values new listtestvalues testvaluesvalue1 testvaluesvalue2 testvalues15 foreach var val in values consolewritelineval consoleread enum testvalues value1 2 value2 4 value3 8 when i run it the output isvalue1value215for my web service i will implement a validation so this will never hapen at all but this is weird should not the runtime throw a invalidcastexception or argumentoutofrangeexception or something similar since i got a list of enums and not int values i want the values to be limitted to the values of the enum that is what an enum is foram i missing something is this a net bug a c bug or is there something i do not know with enums,"['c#', '.net']" +187472,measuring performance of clients i am currently researching any ways to gather some analyticsmetrics on the performance of client machines to our webapp the app is heavily ajax and we are hoping to gather some stats about how well the clients machines are running itwe do not necessarily want to put performance monitoring code all through the application for a great number of reasons this may not be feasible anyways rather we would like to be able to run some kind of test or something when a user submits feedback that could give us an idea of how well their browsercomputer performsthis has been a slightly tricky thing to research as it keeps bringing up thiscussions about profiling etc this is obviously useful but only to a point as our development machines are massively overpowered we are hoping to get some metrics on the kinds of machines our clients are connecting withdoes any kind of libraryframework or best practice exist for this so far my best though is to run some kind of cpu intensive process through js for a few seconds and measure the performance that way thoughts or suggestions may be an interesting thiscussion,['javascript'] +187482,how to simply check if servers php version is 5 or above i am creating a preinstallation checklist for a program the program requires php5 so i need the checklistscript to check for php5s availabilitythere is a function as phpversion that will return in the format of 536 or similar however i want the checklist to be very straight forward and simply tell you yes or no so thisplaying the current version is not helping me that much okay one way is to use the phpversion and remove the comas etc but is not there a neater way weirdly enough there is no information on this anywhereso how to simply check if servers php version is 5 or aboveif echo server has php5 or above else echo servers php version is lower then php5,['php'] +187494,hasattrobj iter vs collections i have seen a couple posts recommending isinstanceobj collectionssequence instead of hasattrobj iter to determine if something is a listlenobject or hasattrobject iter python is not sequenceat first i was excited because testing if an object has iter always seemed dirty to me but after further review this still seems to be the best solution because none of the isinstance tests on collection yield the same results collectionssequence is close but it returns true for stringshasattrobj iter set true true true str false 1 falseisinstanceobj collectionsiterable set true true true str true 1 falseisinstanceobj collectionsiterator set false false false str false 1 falseisinstanceobj collectionssequence set false false true str true 1 falsehere is the code i used to generate thisimport collectionstestobjs set dict list str 1print hasattrobj iter for obj in testobjs print r r obj hasattrobj iter printprint isinstanceobj collectionsiterablefor obj in testobjs print r r obj isinstanceobj collectionsiterableprintprint isinstanceobj collectionsiteratorfor obj in testobjs print r r obj isinstanceobj collectionsiteratorprintprint isinstanceobj collectionssequencefor obj in testobjs print r r obj isinstanceobj collectionssequenceprintam i missing something or is hasattrobj iter still the best option for testing if something is iterableedit i am only interested in detecting the builtin types dict list and setedit this is foolish edit i should have included the use case that got me looking into this i have a function that takes an arg that can be a single value or a sequence so i want to detect what it is and turn it into a sequence if it is a single value so i can deal with it as a sequence after thatif hasattrarg iter arg setargelse arg setargone solution to this is just to let it throw an exception if the object cannot be iterated but that does not work in my use case another solution is to use something likeimport collectionsdef issequenceformeobj if isinstanceobj basestring return false return isinstanceobj collectionssequencefrom python is not sequencebut this requires this function to be defined which makes me not want to use itit looks like hasattrarg iter is still the best option,['python'] +187495,cannot convert string to guid in cnet why would the cast to a systemguid type statement be invalid second line in try block for example suppose i have a string with a value of 5dd5290834ff44f899b90038afefdb81 i would like to convert that to a guid is that not possible guid owneridguid guidempty try string ownerid callcontextdatacurrentprincipalidentityuseridtostring owneridguid guidownerid catch implement catch,['c#'] +187510,cross platform string encryption i am looking for a method of encrypting a string on an iphone passing that to a web server aspnet c and decrypting it there for processing and return a responsei think that i know how to send the encrypted string and then return the result but i do not know what encryption will work on iphone and aspnetany suggestions sample code would be helpful especially on the iphone side if at all possible,"['asp.net', 'objective-c']" +187522,error building android project with maven i am trying to build my android project with maven so i could automate my tests but i am getting the following errordprojectsmtprojectmvn installinfo scanning for projectsinfoinfo info building appscience 100info infoinfo mavenandroidplugin284generatesources defaultgeneratesources appscience info android904002 found aidl files count 3info android904002 found aidl files count 0info copying local resource files to combined resource directoryinfo cprogram files x86androidandroidsdkplatformtoolsaaptexe package m j dprojectsmtprojecttargetgeneratedsourcesr m dprojectsmtprojectandroidmanifestxml s dprojectsmtprojecttargetgeneratedsourcescombinedresourcesres a dprojectsmtprojectassets i cprogram files x86androidandroidsdkplatformsandroid4androidjarinfo dprojectsmtprojecttargetgeneratedsourcescombinedresourcesreslayoutmainxml2 error error string types not allowed at layout height with value match parentinfo dprojectsmtprojecttargetgeneratedsourcescombinedresourcesreslayoutmainxml2 error error string types not allowed at layout width with value match parentinfo dprojectsmtprojecttargetgeneratedsourcescombinedresourcesreslayoutmainxml5 error error string types not allowed at layout width with value match parentinfo dprojectsmtprojecttargetgeneratedsourcescombinedresourcesreslayoutmainxml11 error error string types not allowed at layout width with value match parentinfo dprojectsmtprojecttargetgeneratedsourcescombinedresourcesreslayoutsplashxml2 error error string types not allowed at layout width with value match parentinfo dprojectsmtprojecttargetgeneratedsourcescombinedresourcesreslayoutsplashxml2 error error string types not allowed at layout height with value match parenterror error when generating sourcesorgapachemavenpluginmojoexecutionexception at comjaywaymavenpluginsandroidphase01generatesourcesgeneratesourcesmojogeneratergeneratesourcesmojojava313 at comjaywaymavenpluginsandroidphase01generatesourcesgeneratesourcesmojoexecutegeneratesourcesmojojava1 at orgapachemavenplugindefaultbuildpluginmanagerexecutemojodefaultbuildpluginmanagerjava101 at orgapachemavenlifecycleinternalmojoexecutorexecutemojoexecutorjava209 at orgapachemavenlifecycleinternalmojoexecutorexecutemojoexecutorjava153 at orgapachemavenlifecycleinternalmojoexecutorexecutemojoexecutorjava145 at orgapachemavenlifecycleinternallifecyclemodulebuilderbuildprojectlifecyclemodulebuilderjava84 at orgapachemavenlifecycleinternallifecyclemodulebuilderbuildprojectlifecyclemodulebuilderjava59 at orgapachemavenlifecycleinternallifecyclestartersinglethreadedbuildlifecyclestarterjava183 at orgapachemavenlifecycleinternallifecyclestarterexecutelifecyclestarterjava161 at orgapachemavendefaultmavendoexecutedefaultmavenjava319 at orgapachemavendefaultmavenexecutedefaultmavenjava156 at orgapachemavenclimavencliexecutemavenclijava537 at orgapachemavenclimavenclidomainmavenclijava196 at orgapachemavenclimavenclimainmavenclijava141 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava39 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava25 at javalangreflectmethodinvokemethodjava597 at orgcodehausplexusclassworldslauncherlauncherlaunchenhancedlauncherjava290 at orgcodehausplexusclassworldslauncherlauncherlaunchlauncherjava230 at orgcodehausplexusclassworldslauncherlaunchermainwithexitcodelauncherjava409 at orgcodehausplexusclassworldslauncherlaunchermainlauncherjava352caused by comjaywaymavenpluginsandroidexecutionexception android0401 could not execute command cmdexe x c cprogram files x86androidandroidsdkplatformtoolsaaptexe package m j dprojectsmtprojecttargetgeneratedsourcesr m dprojectsmtprojectandroidmanifestxml s dprojectsmtprojecttargetgeneratedsourcescombinedresourcesres a dprojectsmtprojectassets i cprogram files x86androidandroidsdkplatformsandroid4androidjar result 1 at comjaywaymavenpluginsandroidcommandexecutorfactory1executecommandcommandexecutorjava186 at comjaywaymavenpluginsandroidphase01generatesourcesgeneratesourcesmojogeneratergeneratesourcesmojojava311 22 moreinfo info build failureinfo info total time 19558sinfo finished at fri aug 26 040016 cest 2011info final memory 7m45minfo error failed to execute goal comjaywaymavenpluginsandroidgeneration2mavenandroidplugin284generatesources defaultgeneratesources on project appscience mojoexecutionexception android0401 could not execute command cmdexe x c cprogram files x86androidandroidsdkplatformtoolsaaptexe package m j dprojectsmtprojecttargetgeneratedsourcesr m dprojectsmtprojectandroidmanifestxml s dprojectsmtprojecttargetgeneratedsourcescombinedresourcesres a dprojectsmtprojectassets icprogram files x86androidandroidsdkplatformsandroid4androidjar result 1 help 1errorerror to see the full stack trace of the errors rerun maven with the e switcherror rerun maven using the x switch to enable full debug loggingerrorerror for more information about the errors and possible solutions please read the following articleserror help 1 i cannot figure out what the error isthanks a lot everybody in advance,['android'] +187523,what is the branch in the destructor reported by gcov when i use gcov to measure test coverage of c code it reports branches in destructors struct foo virtual foo int main int argc char argv foo fwhen i run gcov with branch probabilities enabled b i get the following output gcov homeepronksrclcov19exampleexamplegcda o homeepronksrclcov19example bfile examplecpplines executed10 of 6branches executed10 of 2taken at least once50 of 2calls executed40 of 5examplecppcreating examplecppgcovthe part that bothers me is the taken at least once50 of 2the generated gcov file gives more detail cat examplecppgcov cfilt 0sourceexamplecpp 0graphhomeepronksrclcov19exampleexamplegcno 0datahomeepronksrclcov19exampleexamplegcda 0runs1 0programs1 1struct foofunction foofoo called 1 returned 100 blocks executed 100 1 2function foofoo called 1 returned 100 blocks executed 75function foofoo called 0 returned 0 blocks executed 0 1 3 virtual foo 1 4 1 5 branch 0 taken 0 fallthroughbranch 1 taken 100call 2 never executedcall 3 never executedcall 4 never executed 6 7function main called 1 returned 100 blocks executed 100 1 8int main int argc char argv 9 1 10 foo fcall 0 returned 100call 1 returned 100 11notice the line branch 0 taken 0 fallthroughwhat causes this branch and what do i need to do in the code to get a 100 hereg ubuntulinaro 4528ubuntu4 452gcov ubuntulinaro 4528ubuntu4 452,['c++'] +187534,uitableview headings shown on top of mbprogresshud so i have a subclass of uitableviewcontroller that loads some data from the internet and uses mbprogresshud during the loading process i use the standard mbprogresshud initialization hud mbprogresshud alloc initwithviewselfview selfview addsubviewhud huddelegate self hudlabeltext loading hud showyesthis is the result is there any way to resolve this issue or should i just abandon mbprogresshudthanks,"['iphone', 'ios']" +187540,android app name not being thisplayed my android app is not thisplaying the application name app name instead its thisplaying the activity name title this is from my manifest file application androidicondrawableicon androidlabelstringapp name activity androidnamemain androidlabelstringtitle intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activitywhy is the application getting its name from the main activity and ignoring the application labelthis is the full manifest xml version10 encodingutf8 manifest xmlnsandroid packagecomextemporcheetah androidversioncode1 androidversionname10 application androidicondrawableicon androidlabelstringapp name activity androidnamemain androidlabelstringtitle intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity activity androidnameinfohelp androidlabelstringtitleinfo intentfilter action androidnameandroidintentactionhelpinfo category androidnameandroidintentcategorydefault intentfilter activity application usessdk androidminsdkversion10 usespermission androidnameandroidpermissioninternet manifest,['android'] +187548,what is the difference between eclipse 37 and eclipse 41 i see there are two main thistributions of eclipse going on one is on 36 37 38 path and the other is 40 41 path i do not have clarity on what is the difference between these two thistributions,['java'] +187572,how to clear mkmapview cache i am trying load map region and mkmapview delegate methods are not being called on second or subsequent load none of the delegate methods viz voidmapviewwillstartloadingmapmkmapview mapview voidmapviewdidfinishloadingmapmkmapview mapview voidmapviewdidfailloadingmapmkmapview mapview witherrornserror errorare ever called the only methods called are voidmapviewmkmapview mapview regionwillchangeanimatedboolanimated voidmapviewmkmapview mapview regiondidchangeanimatedboolanimatedit seems that ios4 is caching mapview tiles imagesi found these lines in mkmapviewdelegate protocol reference documentation highlighted line is my problemthis method is called when the map tiles associated with the current request have been loaded map tiles are requested when a new visible area is scrolled into view and tiles are not already available map tiles may also be requested for portions of the map that are not currently visible for example the map view may load tiles immediately surrounding the currently visible area as needed to handle small pans by the useri need to perform certain operations after the map is loaded but since none of the above mentioned delegate methods are getting called i am not able to perform desired functionality can anyone suggest a fix to either clear the cache or provide an alternative solution for this i have already tried using the methods described here and this but i am still not been able to get the code working,['objective-c'] +187598,landscape printing with css i have added an css file this waylink relstylesheet hrefstylecss typetextcss mediascreen printthe css contains amongst other the followinglandscape width 100height 100margin 0 0 0 0filter progid dximagetransformmicrosoftbasicimage rotation 3 the body tag of my html page is set with classlandscape then the question while viewing the page in ie9 it is rotated 90 degrees landscape but when i print the page is still in portrait everything else is ok with the page so it loads the css for prints but it seems like ie9 ignores the landscape for printing anyone know why and how i can print it in landscapei have also tried the following which seems like it only works in chromemedia print page size a4 portrait marginleft00cm marginright00cm i have found several answers on google but most of them sums up to the two alternatives i have presented which does not really work for meedit as presented belowmstransform rotate90deg does not work either i have a big table which i just want to print in landscape because of the big nr of columns how hard can it be,"['html', 'css']" +187627,jaxws always sends mtom attachments inline basically i want to create a web services client to send a mtom soap message via the proxy method i have created my service artifacts fine from the web service wsdl the message is created correctly however when i enable mtom and add an attachment the attachment is always sent inline and not in a separate mime part its like mtom is enabled but for some reason it decides not to optimize the message and so sends it inline running the same code through soapui gives the correct result so i know the service itself will accept ithere is my basic code for creating a soap request and sending it i enable mtomfeature but have also tried doing it with soapbindingsetmtomenabledtruefor both methods i have debugged it with soapbinding bindingismtomenabled to check that it is set to being enabled initiate services create service and enable mtomwebserviceblah service new webserviceblahnew urlwsdlurl service namewebserviceblahport port servicegetwebserviceblahportnew mtomfeaturetrue 3072 load filefile file new filehomemypdfpdffileinputstream fileinputstream new fileinputstreamfileint numberbytes fileinputstreamavailablebyte bytearray new bytenumberbytesfileinputstreamreadbytearrayfileinputstreamclose create uploadresultuploadresult request new uploadresult create attachmentattachmenttype attachment new attachmenttypeattachmentsetcontenttypeapplicationdocattachmentsetvaluebytearray create result and add attachment to itrenderedresult result new renderedresultresultsetresultattachmentresultsetresultcontenttypepdfresultsetresultnamea pdf file add result to requestrequestgetresultaddresult send requestportuploadresultsrequestwhat i get is my attachment is sent inline as seen below captured with wiresharkpost blahws http11contenttype multipartrelatedstartltrootparttypeapplicationxopxmlboundaryuuid15c3ee3b60c74726a52c8080965e4536startinfotextxmlsoapaction accept textxml multipartrelated texthtml imagegif imagejpeg q2 q2useragent jaxws ri 216 in jdk 6host 123123123123connection keepalivecontentlength 12372uuid15c3ee3b60c74726a52c8080965e4536 contentid rootpart contenttype applicationxopxmlcharsetutf8typetextxml contenttransferencoding binarysenvelope xmlnsheadersheadersbodyns2uploadresult xmlnsxmime renderedresult result xmimecontenttypeapplicationdocjvberi0xljqkjaqrrk0kncawig9iago8result resultcontenttypepdfresultcontenttype resultnamea pdf fileresultname renderedresultns2uploadresultsbodysenvelopeuuid15c3ee3b60c74726a52c8080965e4536what i want is for the attachment in the result tag to be replaced with the inline tag and the attachment added to the soap message in a different mime part egresult xmimecontenttypeapplicationdoc incinclude hrefcidmyid3 xmlnsincresultand then the following added to the soap message part 10 280272051314348995670contenttype applicationpdfcontenttransferencoding binarycontentid cidmyid3contentthisposition attachment namemypdfpdfjvberi0xljqkjaqrrk0kncawig9iago8,['java'] +187636,fastest way of reading bytes in d2 i want to read single bytes as fast as possible from a file into a d2 application the application need byte per byte so reading larger blocks of data is not an option for the interface to the readerfor this i created some trivial implementations in c java d2 at as you can see i tried plain reads buffers in the application code and memory mapped filesfor my usecase the memory mapped solution worked best but the strange thing is that d2 is slower than java i would have hoped for d2 to land between c and java c code is compiled with o3 g d2 code is compiled with o releaseso please tell me what i am doing wrong here and how to speed up the d2 implementationto give you an idea of the use case here is a c implementationclass stdiofilereader private file ffile static const size t buffer size 1024 unsigned char fbufferbuffer size unsigned char fbufferptr unsigned char fbufferendpublic stdiofilereaderstdstring s ffilefopensc str rb fbufferptrfbuffer fbufferendfbuffer assertffile stdiofilereader fcloseffile int read bool finished fbufferptr fbufferend if finished finished fillbuffer if finished return 1 return fbufferptr private bool fillbuffer size t l freadfbuffer 1 buffer size ffile fbufferptr fbuffer fbufferend fbufferptrl return l 0 size t readbytes size t res 0 for int i0 i10 i stdiofilereader rtmpshop with idspb int read rread while read 1 res read rread return reswhich is much faster compared to the same solution in dstruct filereader private file ffile private static const buffer size 8192 private ubyte fbufferbuffer size private ubyte fbufferptr private ubyte fbufferend public thisstring fn ffile stdcstdiofopentmpshop with idspb rb fbufferptr fbufferptr fbufferend fbufferptr public int readubyte targetbuffer auto finished fbufferptr fbufferend if finished finished fillbuffer if finished return 0 targetbuffer fbufferptr return 1 private bool fillbuffer fbufferptr fbufferptr auto l stdcstdiofreadfbufferptr 1 buffer size ffile fbufferend fbufferptr l return l 0 size t readbytes size t count 0 for int i0 i10 i auto reader filereadertmpshop with idspb ubyte buffer1 ubyte p bufferptr auto c readerreadp while 1 c count c readerreadp return count,['c++'] +187655,php gd use one image to mask another image including transparency i am trying to create a php script that takes an image and then applies a png imageas a maskthe end result needs to maintain transparencyif at all possible i want to do this in gd imagemagick is not really an option right nowhow would i go about this phalacees post in phpgd how to copy a circle from one image to another seems to be along the right lines but i specifically need to use an image as a mask not a shape,['php'] +187668,array of polymorphic base class objects initialized with child class objects sorry for the complicated title i have something like thisclass basepublic int somemember base somemember42 virtual int get return somemember class childa public basepublic virtual int get return somemember2 class childb public basepublic virtual int get return somemember2 class childc public basepublic virtual int get return somemember2 base ar childa childb childc for int i0 isizeofarsizeofbase i base ptr ari printfel i in i ptrgetwhich outputsel 0 42el 1 42el 2 42is this correct behavior in vc 2005 to be perfectly honest i expected this code not to compile but it did however it does not give me the results i need is this at all possible,['c++'] +187672,retrieve the x y coordinates of a button in android i have been working on android for a while and would like to know if it is possible to retrieve the position of a button in androidmy target is to get the x y coordinates and print them on the logcatsome example to show me how would be appreciatedthanks,['android'] +187674,how to deserialize json in aspnet i have follow code which request from webstringbuilder sb new stringbuilderbyte buf new byte8192httpwebrequest request httpwebrequestwebrequestcreatepartnerid17uniqueid54325345435timestamp131286916367digestbf53cae8f364cfc1d796489d09e4cfdnbspnbspbrhttpwebresponse responce httpwebresponserequestgetresponsestream resstream responcegetresponsestreamstring tempstring nullint count 0do count resstreamreadbuf 0 buflength if count 0 tempstring encodingasciigetstringbuf 0 count sbappendtempstring while count 0 responsewritesbtostring brbr string val sbtostringsplitafter the run this code i will get this type of json id 23 name video clips id 15 name deleted scenes id 9 name music albums id 7 name trailers id 18 name short films id 21 name movie clips id 1 name movies id 4 name plays id 22 name scenes id 2 name tv show id 5 name kids id 16 name interviews id 11 name film songs id 14 name making of movie now i want deserialize this in aspnetci tried to get a proper answer but did not getplease advice,"['c#', 'asp.net']" +187700,multiple activities identical oncreateoptionsmenu onoptionsitemselected and onkeydown can i somehow reuse the code multiple activities have identical oncreateoptionsmenu onoptionsitemselected and onkeydown when i implement a change i have to do it in every activity work time activity count is there a way to reuse the code for example write all of the three methods in one place and put down a reference to it in every activity,['android'] +187722,how to write if condition in ifdef for staging in objectivec i need to add one more condition inside this call staginghow to do it in this condition ifdef myapp production buildmode production else ifdef myapp release buildmode release else myapp debug buildmode debug endif endifanother is myapp staging need to include in this if condition how to do this,['objective-c'] +187740,iphone watermark on recorded video in my application i need to capture a video and put a watermark on that video the watermark should be texttime and notes i saw a code using qtkit frame work however i read that the framework is not available for iphone thanks in advance,['iphone'] +187746,how to check if an image was found on a web site i am using ruby on rails v309 and i would like to check if an image in my case a faviconico icon image is successfully retrieved from a web site and if not i would like to thisplay a custom imagein order to retrieve the faviconico image related to a web site in my view file i haveimage tag web sitelinkfaviconico size 16x16where web sitelink values are something like the followingshow to check if an image was found on a web site maybe using an if else end statement or performing some http request before to handle favicon images and how to handle the above scenario,"['ruby-on-rails', 'ruby']" +187759,method missing in java or php i have been looking at different languages to get started i found method missing in ruby very interesting but was not able to find the same in java and php is there something like method missing in java or php,"['java', 'php', 'ruby']" +187762,combine two images into one new image i have two jpeg files with different dimensionsimage1 width1height1image2 width2height2i want to create image3 width3 height3 with image1 on the left side and image2 on the right,"['c#', '.net']" +187767,css vertically align div when no fixed size of the div is known how do i align a div which contains an image or flash vertically with css height and width are dynamic,"['html', 'css']" +187772,searchingfiltering a custom class array with a nspredicate i have a array that contains objects of a custom class and i would like to filter the array based on if one of the classes attributes contains a custom string i have a method that is passed the attribute that i want to be searched column and the string that it will search for searchstring here is the code i havenspredicate query nspredicate predicatewithformatk contains k column searchstringnsmutablearray temp thisplayproviders mutablecopythisplayproviders releasethisplayproviders temp filteredarrayusingpredicatequery mutablecopytemp releasehowever it always throws an exception on thisplayproviders temp filteredarrayusingpredicatequery mutablecopysaying this class is not key value codingcompliant for the key whatever searchstring isany ideas what i am doing wrong,['ios'] +187812,creating a custom mysql function i have just started using mysql with php and i would like to know if it is possible to create a custom function this code snippet should illustrate what i am trying to do a somewhat complicated formula not suitable to embed into the queryfunction thistancelata lona latb lonb earths radius radius 3956 lata deg2radlata lona deg2radlona latb deg2radlatb lonb deg2radlonb calculate deltas deltalat latb lata deltalon lonb lona calculate great circle thistance result powsindeltalatitude 20 2 coslata coslatb powsindeltalon 20 2 thistance radius 2 atan2sqrtresult sqrt1 result return thistance how can i call thistance in my queryquery select lat lon from zipcodes where thistancelat lon 0 0 20mysql queryquerythanks in advance for any help,"['php', 'mysql']" +187823,javautilnosuchelementexception no line found i got an run time exception in my program while i am reading a file through a scanner javautilnosuchelementexception no line found at javautilscannernextlineunknown source at day1readfilereadreadfilejava49 at day1parsetreemainparsetreejava17 my code iswhilestrscnextlinenull i0 ifstrequalslocations size4 t3 strscnextline strscnextline ifstrequalsprofessions size3 t2 strscnextline strscnextline ifstrequalsindividuals size4 t4 strscnextline strscnextline int j0string locnew stringsizewhilejsize beg0 endstrindexof ifend1 tmpstrsubstringbeg end begend2 ifend1 tmpstrsubstringbeg ifbegstrlength strstrsubstringbeg locitmp i ifisize ift3 locationaddloc ift2 professionaddloc ift4 individualaddloc i0 j systemoutprintn,['java'] +187841,create new contact view i have been told to do the followingimplement contact add view like below and let him store in sql tablecontacts will have name phone no of mobile work fax email viewshould look like belowmy questioncan you clarify me should i use addressbook or simply a custom view and a sql database to save data from that custom view i mean both the options are open here,['iphone'] +187849,customizing aspnet mvc routing to service json xml style urls i have a search api i am working on that needs to return search results in a block of html using styles the client has defined on their end i would also like to return results in json for future api stuff well eventually be using currently the routes look like thisapi1searchjsonparam1blahparam2blahetcapi1searchhtmlparam1blahparam2blahetcfor reference the pattern here is area1controlleractioni like the look of some apis i have seen that return results in different formats depending on the extension they have in the url a laapi1searchjsonparam1blahparam2blahetchowever i have not figured out how to configure aspnets mvc routing to support this style the general routing in apiarearegistrationcs iscontextmaproute api default api1controlleractionid new action index id urlparameteroptional i have tried the following defined above the general one which does not worksearch apicontextmaproute searchjson api1controlleraction new controller searchcontroller how would i configure routing to enable the formatstyle urls,['c#'] +187858,memory model guarantees in doublechecked locking i recently came across the following post on the resharper website it was a thiscussion of doublechecked locking and had the following codepublic class foo private static volatile foo instance private static readonly object padlock new object public static foo getvalue if instance null lock padlock if instance null instance new foo instanceinit return instance private void init the post then makes the claim thatif we assume that init is a method used to intialize the state of foo then the above code may not function as expected due to the memory model not guaranteeing the order of reads and writes as a result the call to init may actually occur before the variable instance is in a consistent statehere are my questionsit was my understanding that net memory model at least since 20 has not required that instance be declared as volatile since lock would provide a full memory fence is that not the case or was i misinformedis not readwrite reordering only observable with respect to multiple threads it was my understanding that on a single thread the side effects would be in a consistent order and that the lock in place would prevent any other thread from observing something to be amiss am i offbase here as well,['.net'] +187864,dominance in virtual inheritance what are the c98c03 standards and the c0x future standards exact rules for dominance in virtual inheritancei am not asking for just the specific paragraphs although i am asking also for that somewhere in section 10 i would guessi am asking also for the consequences of the standardese the standardese explained clearly,['c++'] +187888,good web serverservlet container for clojure web apps i am looking for a good production web serverservlet container for my compojure web appliction what are the pros and cons of using jetty or tomcat or other server for a clojure web app using compojure is there any good documentation for using a web server with clojure for production or toolsi would prefer a web server that is flexible easy to configure and has good documentation on how to configure and use it,['java'] +187911,spork would not reload file in lib i am running rspec with spork and i cannot get a file in lib to reload on consecutive rspec runs i have tried requireing the file in sporkeach runi am not getting any responses so i will try to explain further i have the following files in my rails applibcarrbspeclibcar specrbto run tests first i start spork then run rspec speclibcar specrbrspec is not seeing my changes to my car class unless i restart sporkany helpi am onrails 310rc6rspec 260spork 090rc9,"['ruby-on-rails', 'ruby']" +187916,spanning columns with tablelayout possible duplicatewhat is the equivalent of colspan in an android tablelayout it says in the documentation for tablelayout cells can span columns as they can in html however i cannot find any way to do sospecifically i have one row with two columns and another with one column i want the one column row to span the entire table seems easy but i do not see it,['android'] +187977,using both cameras on android fail to connect to camera service i am having troubles in accessing both front and rear cameras at the same time when turn on one camera it works when i turn off first and turn on second it worksit gives following exception when i am trying to turn on second camera while the first one is still showing the imageeandroidruntime32325 fatal exception maineandroidruntime32325 javalangruntimeexception fail to connect to camera serviceeandroidruntime32325 at androidhardwarecameranative setupnative methodeandroidruntime32325 at androidhardwarecamerainitcamerajava265eandroidruntime32325 at androidhardwarecameraopencamerajava226eandroidruntime32325 at comexamplevideostreamermainactivitycamerahandlerstartmainactivityjava116eandroidruntime32325 at comexamplevideostreamermainactivity2onclickmainactivityjava74eandroidruntime32325 at androidviewviewperformclickviewjava2532eandroidruntime32325 at androidwidgetcompoundbuttonperformclickcompoundbuttonjava99in the documentaion i found a phrase that sayspublic static camera open int cameraidsince api level 9 creates a new camera object to access a particular hardware camera you must call release when you are done using the camera otherwise it will remain locked and be unavailable to other applications your application should only have one camera object active at a time for a particular hardware camera but i am having only one camera object for one hardware camera and i wanted to create second object for second devicedoes anybody know if this is possible i am using android 233the place androidhardwarecameranative setupnative method can suggest that probably it is hardwaredriver limitation i am using htc sensation,['android'] +187980,python createimport custom module in same directory i am trying to create a simple python script and import a couple of custom classes i would like to do this as one module here is what i havepointpointpyclass point etcpointpointlistpyclass pointlist etcpoint init pyfrom import point pointlistscriptpyimport sys pointverbose falsepointlist pointlistwhen i run scriptpy i get nameerror name pointlist is not definedwhats weird is that in point all three of the module files init pointlist point have a pyc version created that was not there before so it seems like it is finding the files the class files themselves also compile without any errorsi feel like i am probably missing something very simple so please bear with me,['python'] +188065,why is 08 not a valid integer literal in java why is 08 considered an out of range int but 07 and below are not,['java'] +188066,problem with entry set of javautilmap i am having a strange problem with the following code worksmapstring object map new hashmapstring objectforentrystring object entry mapentryset while the code below does not compilemap map new hashmapforentry entry mapentryset compile error here any clues,['java'] +188084,what bad things may happen without calling to releasedc programming with c once we get the context device by getdc to use what bad things may happen if we exit the program without calling to releasedc,['c++'] +188095,backbonejs how to handle login hi i am trying to wrap my head around backbonejs for some days now but since this is my first mvc framework it is pretty hardi can easily get my collections to work fetching data from the server etc but it all depends on first logging in per apikey i just do not know how to model this with a good mvc approach btw i cannot use the routercontroller because it is a chrome extensionthe flow looks like thisstart extensionis there an apikey in localstorageno thisplay a input field and a save button which saves the key to localstorage yes proceed with the applicationappthe only way i could think of it is putting it all together in a big view but i guess since i am fairly new to this there are surely some better approaches,['javascript'] +188099,getting an el in a javascript file loaded by resourcedependency i am using resourcedependency annotation in a jsf component to add javascript and css files into my jsf pagein my javascript file i need to reference another resource file a swf file which located in metainfresources as jsf requires i tried to put a resourceswffileswf el expression in my javascript code but it would not get resolved for exapmle for the following js file in the server var instance new jsclassinstancesetresourceurlresourceswffileswfthe browser getsvar instance new jsclassinstancesetresourceurlresourceswffileswfwhich is wrongwhile when i put the same el in the css file it get resolved properly for the following css file in the serverinstancecssclass background urlresourceswffileswfthe browser getsinstancecssclass background urlwebappjavaxfacesresourcefileswfjsflnswfwhich is exactly what i need but in the js fileobviously i can use the css as a workaround for the issue create a dom element attach the css class to it and then read and parse the required style property but is there a more elegant way to achive it is it a bug in the jsf library i am using mojarra 203 with jboss 61 or there is a reason for that behaviorplease mind that the code above is part of a tag library so workarounds such as those cannot be usededit seems that the css workaround is not feasible since i cannot see a way to get css attribute from a css file so any working workaround would be gladly accepted as well,"['java', 'javascript']" +188122,why do we sometimes separate behaviour from classes in java its a pretty basic question but i am new to java designing to please excuse me i want to know in which scenarios we need to separate the class behavior from the class itself for eg if i have an class employee i will have some data in it like name age etc also this class will have some behavior like dowork etc now in what scenario we can have data and the behavior inside once class employee only and in which scenario we need to have 2 different classes for employee data employeedto and behavior employeeservice very subjective question but am looking for some inputs on a design of a small application where i am taking data from a text file should i put the data and behavior in different classes or same what will be your reason to justify this decision ps any links to information on this will also be very useful thankyou,['java'] +188134,android jdbc not working classnotfoundexception on driver i am trying to use jdbc in my android application to connect to a remote database to do inserts queries etc i have successfully connected and done these things in a different java project so i figured since android is java i could just port over the relevant code add the same build path for the driver etc but it gives me the error javalangclassnotfoundexception commysqljdbcdriveri really do not think it is a code issue since the same code works in a java project which i just execute in main but for reference here it is string url jdbcmysqllocalhost3306eventhub test string user root string pass sqlutils sqlu new sqlutilsurl user passthe sqlutils class i made public class sqlutils private string connection urlprivate string userprivate string passprivate javasqlstatement stmt private javasqlconnection connpublic sqlutilsstring conn url string user string pass thisconnection url conn url thisuser user thispass pass public void init throws illegalaccessexception instantiationexception classnotfoundexception sqlexception classforname commysqljdbcdrivernewinstance conn drivermanagergetconnectionconnection url user pass stmt conncreatestatementso i am really confused here does jdbc not work with android if so tell me what alternatives i should look into for remote mysql database access thanks,"['java', 'android', 'mysql']" +188145,change text color of one word in a textview i am looking for a way to change the color of a text of a single word in a textview from within an activityfor example with thisstring first this word is string next redtextview t textview findviewbyidridtextboxtsettextfirst nexthow would i change the color of the next text to red,['android'] +188190,how can i properly center a jpanel fixed size inside a jframe hi alli am trying to solve an apparently simple problem but i cannot fix iti am working on a sample application with javaswing libraries i have a jframe and a jpaneli just want to achieve the following objectivesjpanel must be centered inside the jframejpanel must have always the size that is specified withsetpreferredsize method it must not be resized under this sizei tried by using a gridbaglayout it is the only way i can do itsee the sample below file stacksample01java import javaawtimport javaxswingpublic class stacksample01 public static void mainstring args jframe frame new jframe jpanel panel new jpanel panelsetpreferredsizenew dimension100 100 panelsetbackgroundcolorred framesetlayoutnew gridbaglayout frameaddpanel new gridbagconstraints framesetsizenew dimension200 200 framesetdefaultcloseoperationjframeexit on close framesetvisibletrue here a screenshot i would not use a gridbaglayout to do a thing too simplei tried a simplest solution by using a box but this does not worksample code file stacksample02java import javaawtimport javaxswingpublic class stacksample02 public static void mainstring args jframe frame new jframe jpanel panel new jpanel panelsetpreferredsizenew dimension100 100 panelsetbackgroundcolorred for debug panelsetalignmentxjcomponentcenter alignment have no effect box box new boxboxlayouty axis boxaddboxcreateverticalglue boxaddpanel boxaddboxcreateverticalglue causes a deformation frameaddbox framesetsizenew dimension200 200 framesetdefaultcloseoperationjframeexit on close framesetvisibletrue here a screenshot any ideas thanks to all,['java'] +188197,how to create custom texttospeech engine as i know tts needs tts engine to speak one language in android emulator 22 pico tts engine is default it has only some popular languages i can see some engines on market which must be purchased to install my question is there any way to create a custom engine which support other languagesby programming or using software i do not know if i should post this question in stackoverflow or superuser if wrong place please migrate it,['android'] +188203,generic inference in constructors if i have a class foopublic class foot public foot t do something public static e void bare e do something why does foobarstring infer that e is a string and therefore not throw a compiler warning but new foostring not infer that t is a string,['java'] +188225,threads within threads in java i am currently thinking about how to design a multithreading system in java that needs to do some heavy network processing and database storage the program will launch three basic threads at first along these basic threads i would like to launch other threads not from the main program but from two of the threads is it possible for a thread to launch another thread leading to some sort of a hierarchy like parent t0 thread1 t1 tread11 t0 thread2 t0 thread3 t2 thread31t0 inital timet1t2 time at a point in the running threadt1 t2 if not could somebody provide a theoretical solution with references,['java'] +188234,get size of file in windows i have found this function getfilesizeex which returns the size of file in plarge integer that is formed by the union of structurestypedef union large integer struct dword lowpart long highpart struct dword lowpart long highpart u longlong quadpart large integer plarge integeris it same as if i would call it structure of structures how can i figure the file size that it has returned and how large information can it handle,['c++'] +188241,php array delete by value not key i have a php array as followsmessages 312 401 1599 3 i want to delete the element containing the value del val for example del val401 but i do not know its key this might help each value can only be there oncei am looking for the simplest function to perform this task please,['php'] +188242,how to run ussd commands on android has anyone know how to runs ussd command for checking phones credit balance the number is 123 and get the result the credit balance for further processing thankss,"['java', 'android']" +188244,forward traffic from port x to computer b with c udp punch hole into firewall i need to establish a tcp connection from my house computer to my office computeron the office there is a router where several computers are connected to that router has internet therefore all the computers connected to that router have internet as well on my house i have a computer with internet access i need my office computer to act as the server and my home computer to connect to it before i used to be able to connect by port forwarding traffic on the server as natupnplibupnpnatclass upnpnat natupnplibistaticportmappingcollection mappings public serverexample initializecomponent upnpnat new natupnplibupnpnatclass mappings upnpnatstaticportmappingcollection server local ip address mappingsadd1300 tcp 1300 192168150146 true plsease work this code tels the router to forward all tcp traffic comming from port 1300 to the server computer it is lan ip address happens to be 192168150146 and i was able to connect from my house i know that the simple way will be to open the ports on the office router and forward them to my computer the problem is that i do not have access to the office routernow they replaced the router on my office with a newer one and i am not able to use my codenow with the new router when i execute the privious code i getnote that mappings returns null therefore i am not able to add a mapping i am sure there should be a way to establish a connection because some people in the office use limewire for example or bit torrent i think my problem has to do with permissions maybe how can i resolve this editso from researching i found that what i am trying to do is udp punch hole into firewall i actually want to do it over a tcp connection i do not know what is will be the difference between tcp and upd puch holing i mean the purpose of that is for a client to be able to find a pear without having to do configurations on the routerupdateok so i believe i have tried doing what you guys posted on this question with c ok let me show you what i didnote you may need to refer to this diagram in order to understand what i will be explainas you know i want to establish a tcp connection between computer a and computer b the way i manage to do this is by doing what is called tcp punch holingstep 1the first thing that i do is to start listening for new connections on the server s tcplistener server new tcplistenersystemnetipaddressparsea192168109a 50 serverstart var client serveracceptsocket wait here until someone connectsstep 2 now connect to the server with computer a as tcpclient tcpclient new tcpclient192168109 50step 3after executing step 2 code on computer a the server s debug should look likestep 4now our goal is to connect from computer b to computer a server s has the information that b needs in order to establish the connection in reality i will have to establish a connection between computer b and server s so that server s can give b the appropriate parameters in order for b to connect to a step 5 since i am debuging i am able to see the parameters so i will make computer a a server now by listening on port 3313 i want computer a to be listening now on that port 3313 because all the packages sent to router x with port 3313 should be sent to computer a computer a tcplistener server new tcplistenersystemnetipaddressparse1921680120 3313 serverstart var newclient serveracceptsocket wait here until a client gets connectedstep 6so computer a should now be listening for new connections on port 3313 again port 3313 is important because router x should forward all packages received from that port to computer a computer a is waiting for new connectionsstep 7so now quickly we want to establish that connection from computer b in reality server s will pass the parameters but since i am just trying to make this work i will write the program really quick on computer b tcpclient tcpclient new tcpclienta192168108a 3313 192168108 is the address of router xfinallyfor some reason computer b is not able to connect to computer athe reason why it is not able to connect is because router x did not forwarded the packages to computer a i know this because i have enabled port forwarding on port 54540 on router x and when i use that port it works i mean i donat understand why router x did not forward traffic coming from port 3313 to computer a computer a already established a connection to server s and all the things that server s sent to router x through port 3313 got sent to computer a why is it that if i send packages to router x through port 3313 they donat get received by computer a psnote that everything that i showed here i actually have the three routers x y and z and also i have server s computer a and computer b,['c#'] +188266,how to pip install packages according to requirementstxt from a local directory here is the problemi have a requirementstxt that looks likebeautifulsoup320django13fabric120jinja2255pyyaml309pygments14sqlalchemy071south073amqplib061anyjson03i have a local archive directory containing all the packages othersi have created a new virtualenv withbinvirtualenv testingupon activating it i tried to install the packages according to requirementstxt from the local archive directorysource binactivatepip install r pathtorequirementstxt f filepathtoarchivei got some output that seems to indicate that the installation is finedownloadingunpacking fabric120 from r testingrequirementstxt line 3 running setuppy egg info for package fabric warning no previouslyincluded files matching found under directory docs build warning no files found matching fabfilepydownloadingunpacking south073 from r testingrequirementstxt line 8 running setuppy egg info for package southbut later check revealed none of the package is installed properly i cannot import the package and none is found in the sitepackages directory of my virtualenv so what went wrong,['python'] +188316,what is the right way to populate a dropdownlist from a database i am populating a dropdownlist from a sql server database as shown below it works fine but i am not sure it is a good way can someone shed some light on this method and give some improvementsprivate void loadsubjects ddlsubjectsitemsclear string selectsql select subjectidsubjectname from studentsdbosubjects sqlconnection con new sqlconnectionconnectionstring sqlcommand cmd new sqlcommandselectsql con sqldatareader reader try listitem newitem new listitem newitemtext select subject newitemvalue 0 ddlsubjectsitemsaddnewitem conopen reader cmdexecutereader while readerread newitem new listitem newitemtext readersubjectnametostring newitemvalue readersubjectidtostring ddlsubjectsitemsaddnewitem readerclose catch exception err todo finally conclose,"['c#', 'asp.net']" +188321,java thistributed system i am starting my final year computer science project and i am trying to figure out my first steps for more details you can go to the project pagebackgroundbecause i have very little experience in thistributed systems i basically though how should i face such a challenge what i came up with is that the system should work as following the client sends out a file or a set of files that contains code to be processed that code will implement a thistributed algorithm interface written by me a specific class the server will create an object from the classthat object will be responsible for the algorithm to be run the server will return the results to the client i actually read about rmi later and found it very similarsending out files is basic common network iothe real problem is object creation and using it as the predefined interface in runtime questionsthe challenge that i have presented sounds like a reflection challenge is this correct do you have any first tips on how to implement it looking for some thistributed systems java technologies i have encountered rmi trmi linda corba jini and many others rmi sounds the most appealing because it is very similar to what i have gathered to be the solution but it is also oldwhat set of libraries do you think will help me complete this task remember i am a computer science student so complete out of the box solutions will not stick with my professors rmi is old any better solutions out there any comprehensive tutorial on trmiif you find my logic some how faulty please correct itif you have some more tips on the subject that you think that should be thiscussed feel free to contact me,['java'] +188324,what does the orange triangle in the target column of android device chooser window mean when i launch my android app with eclipse the usual window android device chooser appears i can here choose on which device i want to run my appin the target column appears next to my target an orange triangle with an exclamation mark kind of warning see the image belowdoes somebody know what it means,['android'] +188326,pythontornado vs scalalift i am looking to start a google maps based web application my initial thoughts are that in the first phase the focus should be on the frontend and the backend should be easy to write and to prototype and should aid as much as possible the development of the frontendthere will be no classic pages just a meebocom style interface javascript jquery meaning very few if none at all static pagesmy eye has caught the cometstyle server push paradigm and i am really interested in doing some proof of concepts with thisdo you have any recommendations or advantages and thisadvantages or any experiences in working with python tornado vs scala lift what other advantages or thisadvantages in other areas of a web application might a choice bringnote this is for max 2 developers not a big thistributed and changing teamthanks,['python'] +188331,expecting anything as parameter to mock using easymock using easymock i want to be able to say that i expect a specific method called on my mock but i do not care about the parameter which are used to call the mocksomeinterface mock easymockcreatemocksomeinterfaceclassmocksendanythingreplaymock perform actions that will eventually invoke mock verifymockis this possible and howadditionally if i want to accept any object that derives from a specific base class how do i specify that,['java'] +188350,how to check if a parameter of the current method has an annotation and retrieve that parameter value in java consider this codepublic examplestring s int i foo bar bar i want to check if the method has an annotation foo and get the argument or throw an exception if no foo annotation is foundmy current approach is to first get the current method and then iterate through the parameter annotationsimport javalangannotationannotationimport javalangreflectmethodclass util private method getcurrentmethod try final stacktraceelement stes threadcurrentthreadgetstacktrace final stacktraceelement ste stessteslength 1 final string methodname stegetmethodname final string classname stegetclassname final class currentclass classfornameclassname return currentclassgetdeclaredmethodmethodname catch exception cause throw new unsupportedoperationexceptioncause private object getargumentfrommethodwithannotationmethod method class annotation final annotation paramannotations methodgetparameterannotations for annotation annotations paramannotations for annotation an annotations is this the right approach or is there a better onehow would the code inside the forach loop look like i am not sure if i have understood the what getparameterannotations actually returns,['java'] +188355,how to select first and last td in a row how can you select the first and the last td in a rowtr td0tr td1 styles,['css'] +188366,most respected language and free compiler for creating hobby operating systems hopefully this is a nice quick question to answerwhich language is considered to be the defacto language for writing hobbyish operating systems from scratch that also supports the creation of 512 byte boot sectors i am assuming plain c is the answer although i have this vague concept in my head that c can also be used do any of you have any opinions about alternative but potentially superior languages given the passage of time would others highly suggest plain old assemblerand following on from your answer what free and perhaps even open source compiler would you recommend for compiling the source code into binaryps i am fully aware that writing an os is a very challenging task and i am sure i will never finish i am conducting a personalinterest research task and would like to at least create a mbr and very basic kernel with simple console io,"['c++', 'c']" +188392,java configurationparameter passing design often i find the need to engineer objects with configurable functionality to exemplify assume i am creating a dateiterator the configurable options might be whether to iterate the closed interval start end or the openend interval start end1 the in my opinion ungraceful solution limited to only one truefalse configuration optionnew dateiteratorboolean openinterval2 the typesafe enum way typically a bit bulkynew dateiteratorintervalopen end3 the unconventional attempt nice but not too straight forwardnew dateiteratoropenend4 the inheritance approach often overengineeringnew openendeddateiteratorto this comes a few alternatives which i consider inferior like integerbased configuration new dateiteratorintervalopen end or property based configuration are there any other approaches which approach you do you prefer,['java'] +188395,create a radial gradient for internet explorer 678 to create a linear gradient in internet explorer i used to adopt this terrible code filter progiddximagetransformmicrosoftgradientstartcolorstr282828 endcolorstr185976i wonder wether exists a way to create a radial gradient using filter and dximagetransoform,['css'] +188399,sign csr using bouncy castle i cannot find any codedoc describing how to sign a csr using bc as input i have a csr as a byte array and would like to get the cert in pem andor der formati have gotten this fardef signcsrcsrdataarraybyte cacacertificate capasswordstring val csr new pkcs10certificationrequestholdercsrdata val spi csrgetsubjectpublickeyinfo val ks new javasecurityspecx509encodedkeyspecspigetderencoded val kf javasecuritykeyfactorygetinstancersa val pk kfgeneratepublicks val cacert capriv parsepkcs12capkcs12data capassword val fromdate javautildate new javautildate fixme val todate fromdate fixme val issuer principalutilgetissuerx509principalcacert val contentsigner new jcacontentsignerbuildersha256withrsaencryptionsetproviderbcbuildcapriv val serial bigintcertserialnumbernextserialnumber val certgen new jcax509v3certificatebuildernew x500nameissuergetname serialbiginteger fromdate todate csrgetsubject pki have trouble figuring out get from a certificate generator to store this in pem or der formator am i going down the wrong path all together,['java'] +188406,how to use if statements in underscorejs templates i am using the underscorejs templating function and have done a template like this script typetexttemplate idgriditem div classgriditem gridtype gridsize img src image div classcontent span clasubheading categoryname span if date span classdate date span h2 title h2 div divscriptas you can see i have an if statement in there because all of my models would not have the date parameter however this way of doing it gives me an error date is not defined so how can i do if statements within a template,['javascript'] +188420,finite state machine with guards in php does anybody know a finite state machine that has guard feature in php,['php'] +188438,make div as wide as it needs to be to explain my problem i am trying to make a div wide enough to accommodate a dynamically generated title without wrapping it but the div also has other content which i want to wrapin other wordscssbox minwidth170pxbox spantitle fontsize24px whitespace nowrapbox spantext fontsize10px whitespace normalhtmldiv classbox span classtitletitle on one linespanbr span classtextthis is the main body of text which i want to wrap as required and have no effect on the width of the divspandivhowever this is causing the div to expand to be wide enough to contain the main body of text on one line which i want to wrap i have tried various arrangements for css and the putting them all inside container divs and the like but i cannot seem to get the box to be exactly wide enough to contain only the title without wrapping but not less than the min widthis there any way to do this just in css note i do not want to set a max width as this just causes it to become a static size again as the main body of text is always going to be enough to hit the max width i also cannot line break the body manually as it is dynamically generated,['css'] +188441,how do i specify which network interface the android emulator should use on my development machine my development machine is simultaneously connected to two different networks one is through ethernet eth0 and the other is wifi en1 in this situation the android emulator appears to always want to reach out to the network on eth0 when starting the emulator from the command line is there an option where i can tell it to use a specific network interface on the development machine en1 in my caseit seems like this should be possible through args you can pass to the qemu flag however the current version of the emulator will not start when you use this flag,['android'] +188458,how to design a dao class what should be the best way to design a dao class approach1 design dao class as an objectclass customer customer classclass customerdao public void savecustomercustomer customer code public customer getcustomerint id code client codeclass client public static void mainstring args customerdao customerdao new customerdao customer customer new customer customerdaosavecustomercustomer approach2 design dao class with static methods aka static classclass customer customer classclass customerdao public static void savecustomercustomer customer code public static customer getcustomerint id code client codeclass client public static void mainstring args customer customer new customer customerdaosavecustomercustomer in approach1 i have to create an object of dao class in all the client code other option is to pass the reference of dao all around while in approach2 i do not have to create the object and the static methods can be designed with no state trackingso which approach is the best in design of dao classes,['java'] +188471,how to use http authentication in devise with an optional omniauth token as the authentication token we have a rails app setup that uses devise omniauth to allow logging in via facebook authentication we also have a mobile app that is currently using http authentication to login to the rails app either by passing username password or by passing in the http authentication token this all works great so farthe mobile app also has the ability to authenticate with facebook itself and receive the user facebook token directly between itself and facebooki would like to bridge this gap so that if the user has logged in from the mobile app via facebook and has their facebook token allow that facebook token to be used as the authentication on the rails app as if they had received it from facebook via the browserthe end result would be that the mobile app can log a user in via1 usernamepasswordor2 http authentication tokenor3 omniauth facebook token also in the case of 3 if the user does not yet exist on the rails app would need to create the user doing that now already with browser side authentication so there may be nothing more to dohow can i best accomplish this within the devise construct,['ruby-on-rails'] +188477,convert between string u16string u32string i have been looking for a way to convert between the unicode string types and came across this method not only do i not completely understand the method there are no comments but also the article implies that in future there will be better methodsif this is the best method could you please point out what makes it work and if not i would like to hear suggestions for better methods,['c++'] +188512,programmatically set androidlayout centerhorizontal in xml you can do the followingtextview androidlayout centerhorizontaltrue how would i when i have the instance of textview do this programmatically,['android'] +188514,how to give focus after an alert i have something likeinput typetextbox idpartnumber onchangevalidatepartthisinput typetextbox idquantity onfocussaveoldquantitythisthe onchange event is properly firing after a change is made and the textbox loses focus when quantity gains focus the onfocus event is properly firing to save the old value of quantity before changes are madeif validatepart detects an invalid partnumber value it alerts the user to that fact after the alert has cleared i would like to return focus to the partnumber input but doing a focus on the input node is not giving it focus debugging is tricky here because the ie debug window interaction is of course changing the focushow can i ensure focus returns to partnumber if an error is detected in validatepartedita simple version of validatepartfunction validatepartnode if nodevalue alertplease enter a part number nodefocus why is not this having any effect,"['javascript', 'html']" +188521,php namespaced function best practices i have a few general use functions that do not really make sense in any class as static methods i would like to encapsulate them under a namespace so there are no conflicts with functions defined in the global scope for my namespaced classes i follow the widelyadopted pattern where a class such as mynamespacedmyclass exists in mynamespacedmyclassphp on the include pathis there a best practice for where namespaced functions should be placed right now i am putting them in functionsphp within the directory holding classes under the same namespace for example mynamespacedmyfunction exists in mynamespacedfunctionsphpalso is there any way to autoload these functions in the same way that classes are autoloaded,['php'] +188590,adding man pages to a python egg possible duplicatepython installing man pages in thistutils based project i have a python package which is a collection of scripts each script comes with its own commandline syntax and i have created separate man pages for each script how can i add man pages to my setuptools project,['python'] +188622,json parsing of google maps api in android app i am trying to use the google maps api to fetch direction times i am hoping to create a url get the json response and then examine that response for travel duration after i create the json object i have trouble navigating it to me this indicates that i have either messed up getting the response or navigating the json object i would appreciate it if you could peek at the bits and pieces of code i have stitched together from tutorials around the webthis code is intended to get the response it is surrounded by a trycatch and it has not triggered any errors string stringurl url goes here url url new urlstringurl httpurlconnection httpconn httpurlconnectionurlopenconnection if httpconngetresponsecode httpurlconnectionhttp ok bufferedreader input new bufferedreadernew inputstreamreaderhttpconngetinputstream8192 string strline null while strline inputreadline null responseappendstrline inputclose string jsonoutput responsetostringthis code is intended to take that output and parse it into the final string duration as inspired by this stackoverflow answer for a similar question jsonobject jsonobject new jsonobjectjsonoutput jsonobject routeobject jsonobjectgetjsonobjectroutes jsonobject legsobject routeobjectgetjsonobjectlegs jsonobject durationobject legsobjectgetjsonobjectduration string duration durationobjectgetstringtexti am catching a json exception on the second line of the second block can anyone help to fix this or perhaps suggest a simpler way to get the same dataedit thanks to the first helpful answer here from aromero the latter half now looks like jsonobject jsonobject new jsonobjectresponsetext jsonarray routeobject jsonobjectgetjsonarrayroutes jsonarray legsobject routeobjectgetjsonarray2 error jsonobject durationobject legsobjectgetjsonobject1 string duration durationobjectgetstringtextbut it is still throwing a json exception only now it is after the third line i am sure this is embarrassingly easy to fix but i would really appreciate some helpthe relevant part of an example json file is shown below routes bounds northeast lat 34092810 lng 118328860 southwest lat 33995590 lng 118446040 copyrights map data a2011 google legs thistance text 129 mi value 20807 duration text 27 mins value 1619,['android'] +188627,how to use shared memory to communicate between two processes i am trying to communicate between two processes i am trying to save datalike name phone number address to shared memory in one process and trying to print that data through other processprocess1cinclude stdiohinclude sysshmhinclude sysstathint main int segment id char shared memory3 int segment size key t shm key int i0 const int shared segment size 0x6400 allocate a shared memory segment segment id shmget shm key shared segment size ipc creat ipc excl s irusr s iwusr attach the shared memory segment shared memory3 char shmat segment id 0 0 printf shared memory attached at address pn shared memory write a string to the shared memory segment sprintfshared memoryi maddy n sprintfshared memoryi1 73453916n sprintfshared memoryi2 american calling the other process systemprocess2 detach the shared memory segment shmdt shared memory deallocate the shared memory segment shmctl segment id ipc rmid 0 return 0process2cinclude stdiohinclude sysshmhinclude sysstathint main int segment id char shared memory3 int segment size int i0 key t shm key const int shared segment size 0x6400 allocate a shared memory segment segment id shmget shm key shared segment size s irusr s iwusr attach the shared memory segment shared memory3 char shmat segment id 0 0 printf shared memory22 attached at address pn shared memory printf namesn shared memoryi printf sn shared memoryi1 printf sn shared memoryi2 detach the shared memory segment shmdt shared memory return 0but i am not getting the desired outputthe output which i got isshared memory attached at address 0x7f0fd2d460segmentation faultanyone can please help me with this is this the correct way of initializing shared memory3thank you,['c'] +188629,generating counter code for database entry i am using phpmysql to generate a counter code for the each entry while opening the entry screenhere is the code i am usingqresult dbqueryselect count from ap aurora projectsrow qresultfetch row slno row0 1today dateymdcode today slnothis code is generating correctly and showing to user before he creates the record the issue is when multiple users open same time the code is duplicating in their screenswhat is the method to avoid the duplicatesi tried to create a separate table to store the latest number and incremented for each request but the issue is if user cancel the entry that number is missingeditthe code is working properly when one user generate the code and insert the record but the issue is if multiple users opens simultaneously it generates same number to them in their screen if all of them try to save the record it is getting duplicatedplease note that i generate this number and show in the entry screen initially not while saving the record,"['php', 'mysql']" +188635,jquery post to rails my setup rails 309 ruby 192 jquery 162i have a form that shows multiple photos and comments for a user and i wish to implement inline commentingdiv idnewsfeed div div classphoto titlesummer 2011div div classnewsfeed photo a href a div textarea classcomment boxwrite a commenttextarea div div div classcomment titleseeing a moviediv textarea classcomment boxwrite a commenttextarea div i want to submit an ajax post upon the user hitting the enter key in the textarea field heres the javascript incomplete that i have so far newsfeeddelegatecomment box keydown function event eventpreventdefault postsub comments i am using the delegate method because div idnewsfeed contents could be replaced with another ajax call what i need is the syntax for jquery post method assuming i need to pass some form params like say photo id etc assume that i have a way to access the values for the params whats the syntax for the post call to creating params the way rails expect themheres the standard rails bitssub comments controllerrb def new sub comment subcommentnew respond to do format formathtml newhtmlerb formatjs end endalso i do not want to use the usual form forsub comment remote true do f for each and every inline comment i could add i have also taken a look at ryan batess railscast but the code looks outdated,"['ruby-on-rails', 'jquery']" +188639,how to implement rs optimize function in c thisclaimer i have searched for an answer using the keywords r optimize c c optima maxima minima local maximum optimization newtons method gradient descent etc and have not found any satisfactory answers rs optimize man page gives the original fortran code but not the c translation of it please let me know if i should have searched for other keywords or if you can quickly find a website that clearly answers this questionquestion i am new to c and want to convert one of my r programs into c i use the optimize function in r and want to know if there are any librariesheader filesfunctions in c that will easily give me the same results please give an example if possiblehere is a simple example of rs optimize maximizing fp p1p over 01 where the maximum is at p 05 and f05 025 optimizefunctionp p1pc01maximumtmaximum1 05objective1 025thank you for your help,['c++'] +188649,switching videos in avplayer creates flash when changing i am using avfoundations avplayer to play 2 video clips made from 1 longer video so the end of the first matches the beginning of the secondwhen the first video ends and the user taps i create a new avplayer and assign it to my playerview and start playing the second clipthis all works however there is a prominent screen flickermy assumption is that this is caused by the player view removing the first clip and then showing the second clipwhat i need is for this flicker to no appear so that going between the two clips is seamlessdo anyone know if there is a way to stop this flickr either via the avplayer classes or a way to fake it by doing something to make it so this is not visiblethanksbelow is the code of my load and play method voidloadassetfromfile nsurl fileurl nil switch playingclip case 1 fileurl nsbundle mainbundle urlforresourcewh 3a withextensionmp4 break case 2 fileurl nsbundle mainbundle urlforresourcewh 3b withextensionmp4 break case 3 fileurl nsbundle mainbundle urlforresourcewh 3c withextensionmp4 break case 4 fileurl nsbundle mainbundle urlforresourcewh 3d withextensionmp4 break default return break avurlasset asset avurlasset urlassetwithurlfileurl optionsnil nsstring trackskey tracks asset loadvaluesasynchronouslyforkeysnsarray arraywithobjecttrackskey completionhandler the completion block goes here nserror error nil avkeyvaluestatus status asset statusofvalueforkeytrackskey errorerror if status avkeyvaluestatusloaded selfplayeritem avplayeritem playeritemwithassetasset nsnotificationcenter defaultcenter addobserverself selectorselectorplayeritemdidreachend nameavplayeritemdidplaytoendtimenotification objectplayeritem selfplayer avplayer playerwithplayeritemplayeritem playerview setplayerplayer selfplayer seektotimekcmtimezero self play else deal with the error appropriately nslogthe assets tracks were not loadedn error localizeddescription,['ios'] +188658,set edittext cursor color i am having this issue where i am using the androids holo theme on a tablet project however i have a fragment on screen which has a white background i am adding an edittext component on this fragment i have tried to override the theme by setting the background of the hololight theme resources however my text cursor carat remains white and hence invisible on screen i can spot it faintly in the edittext fielddoes anyone know how i can get edittext to use a darker cursor color i have tried setting the style of the edittext to androidstylewidgethololightedittext with no positive result,['android'] +188688,returning multiple tables from a stored procedure in my winform application i have the following scenario i want to get multiple tables on a single event returning all tables as dataset in single server cycle or getting one table at time and using separate server cycle for each table which one is better what are the advantages one over another,"['c#', '.net']" +188703,set the same value to multiple properties css this seems like such a stupid question but i cannot find the answer anywhereis there a way to set multiple css properties to one valueborderleft borderright 1px solid e2e2e2the way that you can do with selectorswrapper maindiv,['css'] +188706,is the destruct method necessary for php the manual said that the destructor method will be called as soon as all references to a particular object are removed or when the object is explicitly destroyed or in any order in shutdown sequencedoes not the php gc enough could someone give an example that destruct method is necessary,['php'] +188714,can you use html entities in the css acontenta property i would like to use html entities in css but it shows me the bull insteaddownbefore contentbull colorf00also why does the above code not work in ie it does not show the before part at all,"['html', 'css']" +188715,how would i call a function which returns a table and accepts a varchar i have a function i need to use i am passing in a var char and i insert records into a table called using valuelist however i am not sure how to call use this function alter function dbogetlistfromcsvstring csvstring varchar500returns valuelist table listvalue varchar50asbegin bodyend,['sql'] +188735,how to convert current date to epoch timestamp how to convert current date to epoch timestamp format current date29082011 110502,['python'] +188808,download file from web in python 3 i am creating a program that will download a jar java file from a web server by reading the url that is specified in the jad file of the same gameapplication i am using python 321i have managed to extract the url of the jar file from the jad file every jad file contains the url to the jar file but as you may imagine the extracted value is type string heres the relevant functiondef downloadfileurlnone import httplib2 h httplib2httpcache resp content hrequesturl get return contentdownloadfileurl from filehowever i always get an error saying that the type in the function above has to be bytes and not string i have tried using the urlencodeutf8 and also bytesurlencodingutf8 but i would always get the same or similar errorso basically my question is how to download a file from a server when the url is stored in a string type,['python'] +188817,access a window by window name if i open a window using windowopenmyurlhtml windowname width100height100how do i refer to the new window from the same page that opened it using windowname this question is specifically about this i am aware that i could save a reference to the handle by using var mywin windowopen but i do not care about that in this situationthanks dave,['javascript'] +188820,advice on implementing a shopping cart using playframework i am learning to use playframework by writing code to implement a webstore for selling itemsi have implemented the admin area using the crud and secure modulesnow i want to create a shopping cart to which a user can add items and proceed to checkout my knowledge of ecommerce is minimalbut i had gone through some textbooks which implement shopping carts and some webshop functionality using servletsin the books the cart used to keep a set of cartitems each of which contained an instance of the product and quantityafterthe user added items to cartthe cart was stored in user sessionsoanytime the user went to the cart details pageit showed all the added itemsonly when the session was clearedeither due to session timeout as defined in the serveror when the order was placedthe cartitems were removed from the shoppingcarti guess i can use the cache in playframework to do the aboveafter adding a cartitem to shoppingcart instance i can shopcartaddmycartitemcachesetsessiongetid shopcartand laterin another page i can retrievethe cart and its contentsprocess them and clear the cartshopcart cart cachegetsessiongetidshopcartclasetcartitem items cartgetcartitemsprocessorderitemsuserinfocartclearitemsis this the right way to go about thisif the way i am thinking is not correctplease help me with suggestions,['java'] +188822,java can a hashmap have 4 generic parameters instead of 2 this may be difficult to explain but here goesi want to store 3 integers and a string to a hashmap so i can retrieve data from the map but it turns out that hashmaps only allow 2 generic parameters instead of 4for example hashmap string integer integer integer what i want to dobut you can only use 2 parameters as it seems hashmap string integermy best guess is that my idea cannot be done if so please list the alternatives to handling something like this,['java'] +188837,proceed with variable arguments with aspectj i am trying to normalize uris across an application using aspectj i am catching every call that is made to a method passing in a javaneturi parameter using this codeobject around execution javaneturi for object arg thisjoinpointgetargs if arg instanceof uri normalize return proceedhowever since uri is immutable i cannot swap in the normalized value into the existing object what i need is to call proceed with the new normalized uri objects and possibly passing along the other arguments unchanged however the proceed call only lets me pass along arguments that were collected by the join point is there any way to accomplish this for a variable number of arguments mostly being interested in any uri arguments but willing to collect and pass along all arguments,['java'] +188841,ios custom button with a depressed state i realize that there has to be a a ton of guides to do this but i cannot find itwhat i am trying to do is use a button with a custom image in it and when you press the button have the image change to another pressed version of the button,"['ios', 'objective-c']" +188849,yield return from a trycatch block as eric lippert described in this article yield return is not allowed within trycatch clausesis there a nice way i could get something like this without having to write my own ienumerator by handpublic ienumerabledata getdata var transaction sessionbegintransaction try iquery q createquerysession foreach var result in qenumerable yield return projectresultresult does not work sessioncommit catch exception ex transactionrollback throw finally transactionthispose,['c#'] +188852,edittext hint shows extra spaces when inputtypetextpassword just wondered am i the only one to encounter this strange behavior when placing an edittext inside my activity and setting its inputtypetextpassword as follow edittext androidtext androidididedittext01 androidhintthis is a hint androidinputtypetextpassword androidlayout widthwrap content androidlayout heightwrap contentedittextthe hint is thisplayed with biggerdouble spaces between the words if i remove the inputtype attribute it all goes back to normal i could not find a known issue regarding this behavior btw if you wonder why this is important it is not that much try putting two edittext widgets one below the other and set the inputtype of one of them to textpassword it does not look good any idea on how to change the password or the other edittexts to use the same format thanks ps the question was added here first threadthread88738bb8d8046f6f but i did not find an answer,['android'] +188862,android app restarts automatically after a crash my app is partly written in native app using cc the problem is that whenever cc part crashes for some reason the app dies and then restarts automatically this causes all kinds of messy problemsnow of course it should not crash in the native part and i am trying to weed out all reasons why it would happen however if it does happen i would like toquit gracefullyif it does die at least not try to restart automaticallyi am curious as to why this behaviour happens after some search i tried putting the following line in the main activity element of the androidmanifestxmlandroidfinishontasklaunchtruebut the automatic restore still happensanyone knows why this is happening and how to change it updatei think a more fundamental question isis there something similar to a callback if there is a native crashone of the answers suggested handling crash signals i would be grateful for any links on how it can be done at an application or module levelas it stands currently if there is a crash the app just thisappears there is nothing in logcat so no debugging is possible,['android'] +188864,phpgd better gaussian blur i want to blur an image with gd library unfortunately the gaussian blur effect that gd gives is not enough and i want something being more blurrishphp im imagecreatefrompng getimageifim imagefilterim img filter gaussian blur headercontenttype imagepng imagepngimelse echo failimagedestroyimi want something like this or at least near it,['php'] +188866,bodysettransform does not work inside contact listener andengine and box2d i am trying to move player body while contact with teleport but settransform is not executedthis is my contact listenermphysicsworldsetcontactlistenernew contactlistener override public void begincontactcontact contact final fixture fixturea contactgetfixturea final body bodya fixtureagetbody final fixture fixtureb contactgetfixtureb final body bodyb fixturebgetbody ifbodyagetuserdataequalsplayer bodybgetuserdataequalsplayer forint i 0 i tellistsize i ifbodyagetuserdata tellistgeti teleport tl tellistgeti iftllookgetx pllookgetx plmoveto150 320 plsetlinearvelocitynew vector245f0 else plmoveto150 320 plsetlinearvelocitynew vector245f0 break else ifbodybgetuserdata tellistgeti teleport tl tellistgeti iftllookgetx pllookgetx plmoveto150 320 plsetlinearvelocitynew vector245f0 else plmoveto150 320 plsetlinearvelocitynew vector245f0 break override public void endcontactcontact contact player class has method public void movetoint x int y bodysettransformnew vector2x32y32 0and it works fine but is not executed inside contact listener and i am sure contact is occured because it enters the if block and plsetlinearvelocitynew vector245f0 is executed thanks in advance,"['java', 'android']" +188906,jquery validation not waiting for remote validation to return true considers form valid new component formvalidate errorclass inputerror rules comp dataaccount name required true remote url validate data provider twitter onsubmit true onfocusout false onkeyup false onclick false new component formsubmitfunction consolelogthisvalidthis outputs true even if the value is invalid i see the validation eventually fail and show the error message but the form is still submitted,['jquery'] +188930,android lock apps i am new here and i have searched for questions to help me but i have no clear answersi need to make an application to block other applications on the phonei have seen several on the market but i want to make oneis there any way of knowing when a user tries to open an application and bring forward an activity to put the password i tried with fileobserver but only works with files and directories obviouslycould i make a listener that captures the intent of the other applications before startingi apologize for my english and i appreciate your help,['android'] +188937,jackson jettison usage in jersey jersey framework uses both jackson and jettison libraries for json unmarshallingmarshalling afaik jettison is for for mapping json to xml with different mechanism support like mapped notation and jackson is for json generationparsing i am using this without jersey alsowill jersey using these two for two different functionalities or both for same json generationparsing functionalityi only want support json format at my first thought it seems i can remove either of the dependencies and i think i can remove jettison as jacksone seems more natural choice for json generationparsing,['java'] +188957,how crossplatform is googles protocol buffers handling of floatingpoint types in practice googles protocol buffers allows you to store floats and doubles in messages i looked through the implementation source code wondering how they managed to do this in a crossplatform manner and what i stumbled upon wasinline uint32 wireformatliteencodefloatfloat value union float f uint32 i f value return iinline float wireformatlitedecodefloatuint32 value union float f uint32 i i value return finline uint64 wireformatliteencodedoubledouble value union double f uint64 i f value return iinline double wireformatlitedecodedoubleuint64 value union double f uint64 i i value return fnow an important additional piece of information is that these routines are not the end of the process but rather the result of them is postprocessed to put the bytes in littleendian orderinline void wireformatlitewritefloatnotagfloat value iocodedoutputstream output outputwritelittleendian32encodefloatvalueinline void wireformatlitewritedoublenotagdouble value iocodedoutputstream output outputwritelittleendian64encodedoublevaluetemplate inline bool wireformatlitereadprimitivefloat wireformatlitetype float iocodedinputstream input float value uint32 temp if inputreadlittleendian32temp return false value decodefloattemp return truetemplate inline bool wireformatlitereadprimitivedouble wireformatlitetype double iocodedinputstream input double value uint64 temp if inputreadlittleendian64temp return false value decodedoubletemp return trueso my question is is this really good enough in practice to ensure that the serialization of floats and doubles in c will be transportable across platformsi am explicitly inserting the words in practice in my question because i am aware that in theory one cannot make any assumptions about how floats and doubles are actually formatted in c but i do not have a sense of whether this theoretical danger is actually something i should be very worried about in practiceupdateit now looks to me like the approach pb takes might be broken on sparc if i understand this page by oracle describing the format used for number on sparc correctly the sparc uses the opposite endian as x86 for integers but the same endian as x86 for floats and doubles however pb encodes floatsdoubles by first casting them directly to an integer type of the appropriate size via means of a union see the snippets of code quoted in my question above and then reversing the order of the bytes on platforms with bigendian integersvoid codedoutputstreamwritelittleendian64uint64 value uint8 bytessizeofvalue bool use fast buffer size sizeofvalue uint8 ptr use fast buffer bytes writelittleendian64toarrayvalue ptr if use fast advancesizeofvalue else writerawbytes sizeofvalue inline uint8 codedoutputstreamwritelittleendian64toarrayuint64 value uint8 target if definedprotobuf little endian memcpytarget value sizeofvalueelse uint32 part0 static castuint32value uint32 part1 static castuint32value 32 target0 static castuint8part0 target1 static castuint8part0 8 target2 static castuint8part0 16 target3 static castuint8part0 24 target4 static castuint8part1 target5 static castuint8part1 8 target6 static castuint8part1 16 target7 static castuint8part1 24endif return target sizeofvaluethis however is exactly the wrong thing for it to be doing in the case of floatsdoubles on sparc since the bytes are already in the correct orderso in conclusion if my understanding is correct then floating point numbers are not transportable between sparc and x86 using pb because essentially pb assumes that all numbers are stored with the same endianess relative to other platforms as the integers on a given platform which is an incorrect assumption to make on sparcupdate 2as lyke pointed out ie 64bit floating points are stored in bigendian order on sparc in contrast to x86 however only the two 32bit words are in reverse order not all 8 of the bytes and in particular ie 32bit floating points look like they are stored in the same order as on x86,['c++'] +188963,app ready for sale i can view it but no one else can apple just approved my app and it says ready for sale i know that there is usually a delay with it actually showing up on the app store but when i press view in itunes in the app details it is able to take me to my app now if i search for the app nothing comes upis this normal that i can view it using the direct link and no one else can by just searching it,['iphone'] +188972,how to build debian package with cpack to execute setuppy until now my project had only cpp files that were compiled into different binaries and i managed to configure cpack to build a proper debian package without any problemsrecently i wrote a couple of python applications and added them to the project as well as some custom modules that i would also like to incorporate to the package after writing a setuppy script i am wondering how to add these files to the cpack configuration in a way that setuppy gets executed automatically when the user installs the package on the system with dpkg i packagedebi am struggling to find relevant information on how to configure cpack to install custom python applicationsmodules has anyone tried this,['python'] +188992,which default argument is evaluated first and why i have three functions funt1 funt2 and funt3int funt1 coutfunt1 calledendl return 10int funt2 coutfunt2 calledendl return 20void funt3int xfunt1 int yfunt2 cout x y endlmy main functionint main funt3 return 0when i am calling funt3 in my main method why is funt1 is called first and then funt2,['c++'] +188997,uialertview without cancel button i am trying to create a uialertview that has 3 options and no cancel button but when i do this it always styles button 3 as a cancel button is there any way to avoid thisuialertview alertview uialertview alloc initwithtitleselect one messagenil delegateself cancelbuttontitlenil otherbuttontitlesbutton 1button 2 button3 nil,['iphone'] +189027,fbgetloginstatus not working i am trying to write a code that checks whether the user is logged in or not and found that there is a builtin method in fbjs api which is called getloginstatusi have implemented it inside of html but for some how alert inside of the getloginstatus is not firedi have also tried to add channelurl at initbut it still does the same below is the code that i have writtencan anyone help me with itthanks in advance initialize fb api for use div idfbrootdiv script typetextjavascript var curloc windowlocation var chanurl curlocprotocol curlochostname curlocport channelhtml windowfbasyncinit function fbinitappid status true cookie true xfbml true fbgetloginstatusfunctionresponse if responsesession logged in and connected user someone you know alertlogged in else no user session available someone you dont know alertnot logged in function var e documentcreateelementscript etype textjavascript esrc documentlocationprotocol connectfacebookneten usalljs easync true documentgetelementbyidfbrootappendchilde script,['javascript'] +189071,loadable bash builtin i am writing a strcmp bash builtin it compiles fine but when i try to enable it i get enable f strcmp strcmpbash enable cannot open shared object strcmp strcmp only et dyn and et exec can be loadedthe big parts of my builtinstrcmp builtin listword list listchar strcmp doc char nullstruct builtin strcmp struct strcmp builtin name strcmp builtin function implementing the builtin builtin enabled initial flags for builtin strcmp doc array of long documentation strings strcmp string 1 string 2 usage synopsis becomes short doc 0 reserved for internal use the compile line from the expanded make filebash42examplesloadables gcc fpic dhave config h dshell g o2 i i i ilib ibuiltins iinclude ibash42 ibash42lib ibash42builtins c o strcmp strcmpci have googled et dyn and et exec and only found links to questions like this,['c'] +189094,unknown build error cannot resolve dependency to systemwindows i just downloaded poshconsoles source code and was trying to build the solution i initially had two problem the systeminteractivitydll could not be resolved i installed blend 4 sdk and that issue was fixedunknown build error cannot resolve dependency to systemwindowsright now whenever i try to build the project i get the following error in two projects in the solution and i have not been able to find a solution after some googling aroundcannot resolve dependency to assembly systemwindows version2050 cultureneutral publickeytoken7cec85d7bea7798e because it has not been preloaded when using the reflectiononly apis dependent assemblies must be preloaded or loaded on demand through the reflectiononlyassemblyresolve event,['c#'] +189096,in php what happens in memory when we use mysql query i used to fetch large amount of data using mysql query then iterating through the result one by one to process the data exmysql result mysql queryselect from userwhilerow mysql fetch arraymysql result echo rowemail nrecently i looked at a few framework and realized that they fetched all data to an array in memory and returning the arraylarge array dbfetchallselect from userforeachlarge array as user echo useremail ni would like to know the proscons of each method it appears to me that loading everything in memory is a recipe for thisaster if you have a very long list of items but then again a coworker told me that the mysql driver would have to put the result set in memory anyway i would like to get the opinion of someone who understand that the question is about performance please do not comment on the code i just made it up as an example for the postthanks,"['php', 'mysql']" +189111,how to measure execution time of a cucumber step i am looking for a way to measure the execution time of my cucumber steps using the junit format i managed to get some data about the execution time of the features and scenarios but i would like to see the times of the steps inside the scenarios as well,['ruby'] +189113,passing context with bind in backbonejs i want my panels to rerender themselves when they are clicked however when i perform a click i get the followinguncaught typeerror cannot call method get of undefinedit appears that the this that i am logging is in fact the model itself callbacks object changed true escapedattributes object previousattributes objectattributes objectcid c0collection rdid f5589ba4a0aadd86969730e532e0f975 proto ni am having trouble figuring out why the appropriate this is not preserved by passing my context into modelbindheres my code modelswindowpanel backbonemodelextend defaults function return flipped false toggle function thissaveflipped thisgetflipped collectionswindowpanellist backbonecollectionextend modelpanel localstorage new storepanels flipped function return thisfilterfunctionpanel return panelgetflipped global collection of panelswindowpanels new panellist panel viewwindowpanelview backboneviewextend tagname div template templatepaneltemplatehtml events click toggle initialize function thismodelbindchange thisrender this thiselhtmlthistemplatethismodeltojson render function consolelogthis var flipped thismodelgetflipped if flipped thiseladdclassflip else thiselremoveclassflip return this toggle function thismodeltoggle,['javascript'] +189143,regular expressions c behaves differently than perl python under pythonttsiodelrond python import re athis is a test resubr george ageorgeunder perlttsiodelrond perlathis is a testasgeorgeprint actrldgeorgeunder cusing systemusing systemcollectionsgenericusing systemtextusing systemthreadingusing systemtextregularexpressionsnamespace isthisacsharpbug class program static void mainstring args var matchpattern var replacepattern george var newvalue regexreplacethis is nice matchpattern replacepattern consolewritelinenewvalue unfortunately c prints csc regexpcsmicrosoft r visual c 2008 compiler version 35307295420for microsoft r net framework version 35copyright c microsoft corporation all rights reserved regexpexe georgegeorgeis this a bug in the regular expression library of c why does it print george two times when perl and python just print it once,['c#'] +189147,object marshalled and unmarshalled what is meant by object marshaling and unmarshaling what is the impact on object state when the above operation happening i mean like serialization impact on hash code value of the object etcthank you,['java'] +189148,how do i find a unicode characters bidirectional character type in c is there any way i can find a unicode characters bidirectional character type in ci want to look through the characters in a string and decide if they are all strong ltr strong rtl a mixture of strong ltr and neutral etc,['c#'] +189152,cython install problem i got cython 015 and tried to install it like thispython setuppy installi get thisrunning installrunning buildrunning build pyrunning build extbuilding cythonplexscanners extensionerror unable to find vcvarsallbatwhat does this mean i have micorsoft visual studio 2008 and windows sdk using windows 7 python 26,['python'] +189177,what is wrong with the current way of developingpackaingthistributing a large java web application there are lots of applications are moving towards osgi and there are lots of material on the internet talk about benefits of using osgi but i fail to see the problems the current way of buildingthistributing a large java web application using nonosgiold way could someone first outline the nonosgi and osgi way of developingpackingthistributing a large java web application secondly point out the the problem associated with nonosgi way thirdly how moving to osgi would solve these problems maybe also give concrete examples and reference resources,['java'] +189192,singleton protected vs private constructor when designing singletons why is the constructor made protected and not private this is based on what i have seen over the webwe want to control the number of instances made of that class fair enough but why protected wouldnt private do the trick as well,['c++'] +189200,drupal how to get sum of rows i want to do a simple select with a sum of several rows in drupal but i cannot seem to figure out how to do that i know there are more ways to do a query in drupal one of them is writing the actual query but i do not want thathere is the code i havequery db selectnodenqueryfieldsn arraynidlikes sumlikesbut apparently drupal strips my brackets and i get the following error1054 unknown column nsumlikes in field listcould anyone help me is there something like querysum,"['php', 'mysql']" +189214,background gradients in ie7 with css i am using the following bit of css to create a linear background gradient it seems to work just fine in ie89 ff safari and chrome but not in ie7 ie7 shows a solid green background here is my codemenu body a thisplayblock color006699 background 008800 mozilla background mozlineargradienttop 0b71a4 025f8e chrome safari background webkitgradientlinear left top left bottom from0b71a4 to025f8e msie filter progiddximagetransformmicrosoftgradient startcolorstr0b71a4 endcolorstr025f8e gradienttype0 padding 1px 18px,['css'] +189243,catch block variable warning in java i try to get my code to compile with no errors and no warnings as standard practice there is one annoying warning though that i know how to deal with in net but not in java say i have a code block like this try fileinputstream in new fileinputstreamfilename return new scannerinusedelimiteranext catch filenotfoundexception ex logloglevelsevere unable to load file 0 filename return null i get a warning that variable ex is not used now i do not really have a use for ex i do not want ex but i do not know what to do about it in net i could just docatch filenotfoundexceptionwithout the variable and it will compile and run with no error how would one handle this situation in java i know i could make a local variable and set it to ex but that seems like a silly and wasteful workaround to fix a warning that is not really neededthoughts,['java'] +189261,nsurl returns nil value here below is my code nsstring string nsstring stringwithformat demoviewphpdrinkidnamecommentdaterating reqesttypesubmitcommentdrinkidnamecommentdateratingnsurl url nsurl alloc initwithstringstringhere in string there is value but url returns nilcan anyone tell why this happenedthanks this would not work so heres what i did insteadnsstring string nsstring stringwithformatnamecommentdateratingreqesttypesubmitcommentdrinkidnamecommentdateratingnsurl url nsurl alloc initwithstringstring,['objective-c'] +189272,does enumerablewhere in linqtoobjects preserve order var source new liststring a1 a2 b1 b2 var filtered sourcewheres sstartswithaforeach var s in filtered consolewritelines outputs first a1 and then a2it seems like enumerablewhere keeps the original order of elements when used on an ordered ienumerable such as a listt or t is this always the case if yes where is this documented,"['c#', '.net']" +189280,why and when to use static structures in c programming i have seen static structure declarations quite often in a driver code i have been asked to modifyi tried looking for information as to why structs are declared static and the motivation of doing socan anyone of you please help me understand this,['c'] +189298,image and text inside of tag this is the html aspnet generated with some clientidentifying details removedin windows xp ie 7 clicking on the image does nothing click on the text executes the hyperlink rightclicking anywhere and then selecting open in new window or open also works in other browsers it all works as expectedis there anything simple anyone can see that i could do to this to get it to work correctly in ie7div idhdrx a idctl00 x titlex classhdrx href target blank div stylefloatleftthisplay block img idctl00 x srcimagesxpng styleborderwidth0px div div stylefloatleft thisplay block padding15px 0 0 0 span idxsome text right herespan div a div,"['html', 'css']" +189306,better solution than else if with ranged data i have a simple java method that returns colors based on the hsb value converted from an rgb it works needs some tweaking but i use a series of else if and nested if statements to return the data i want i had heard that hashmaps and string factories were better but i could not see how these worked with ranged data is there a better solution that works with ranged data like thissnippetpublic static string getcolorname gethsbrgb ifhsbh 45 hsbh 75 ifhsbs 0 hsbs 45 hsbb 70 return whiteoff white else ifhsbs 0 hsbs 45 hsbb 10 return dark yellow else return yellow else ifhsbh 15 hsbh 45 ifhsbs 0 hsbs 45 hsbb 70 return whiteoff white else ifhsbs 0 hsbs 45 hsbb 10 return dark orange else return orange,['java'] +189328,coffeescript this inside jquery each i have some coffeescript like the followingclass foo bar bob loblaw processrows mytabletreach id thisattrid processrow id processrow id consolelog bar idso my problem is i need this to reference the each context inside the loop to get at id but i also would like this to reference the class instance inside fooprocessrowwhich it does not currently do using something like this this outside the each function and passing it around is not a great solution either since i reference many class variables inside processrowany thoughts am i missing something obvious thanks,['javascript'] +189336,what makes a jquery object show up as an array in chromes developer tools i am wondering how it is possible that jquery objects show up as an array in the console log of developer tools in chromeeg if i execute a what i see in the console log isabut the following statements are falsevar a aarrayisarraya falsea instanceof array falsei tried to modify jquery and see what happens and one thing that was surprising is that removing length from the jquery function removes the array notationlength 0 commenting this line removes array notationinstead it then shows up as arrow is that solid one to expand jqueryjqueryfnjqueryinitbut if i try to make my own constructor which is supposed to be thisplayed in array notation it does not workvar test function thislength 0 new test logged arrow is same one as before testso i am wondering what in the jquery code makes developer tools show instances as an array what propertyfunctionthing is added to jquery that makes developer tools handle it as an array when thisplaying an instance,['jquery'] +189337,set background image for font color say i have the following codespanhello worldspanand the following cspancolorredis there any way i can change the red to an image like urlimagestextbgpng i want to put a texture on my text and decided that i would just make the text color an image but i am not sure if this can be done with css,"['html', 'css']" +189353,struts html option selected in struts it seems there is no selected option the html option tag has a selected attribute such that you can dooption selectedselectedsome optionoptionand that option will be automatically selected is there a way to do this in struts it seems that in struts its randomly autoselected one my options for a reason i do not understand and i would like to be able to specify which option should be auto selected,['html'] +189362,how to round up to decimal place like money i need to round money values up to the nearest cent then do some operations on that rounded value i cannot use round because this will also round down these are all money values1234567 1234611349 114is there any way to do this in sql if i need a udf please provide suggestion on how to accomplish code for that udfedit data is stored as float,['sql'] +189366,custom implementation of a domainservice using linq to sql can anyone point me to an example of or briefly describe how one would go about creating a custom implementation of a wcf ria services domainservice using linq to sql as the data access layer but without the use of the dbml file this is because the linq to sql model is generated by a custom tool is heavily cutomized and is of a fairly large database with 50 tables and without the vs2010 wizard for creating a domainservice the wizard is dependant on the dbml file being availableheres a really simple shell of what i tried myself so farenableclientaccesspublic class subscriptionservice domainservice queryisdefault true public iqueryablesubscription getsubscriptionlist subscriptiondatacontext dc new subscriptiondatacontext var subs dcsubscriptionwherex xstatus statusactive selectx new subscription id xid name xname tolist return subsasqueryable public void insertsubscriptionsubscription sub if subidisempty subscriptiondatacontext dc new subscriptiondatacontext subscription tmpsub dcgetbyidsubscriptionsubid if tmpsub null tmpsubname subname dcsavetmpsub else tmpsub new subscription tmpsubname subname dcsavetmpsub public void updatesubscriptionsubscription sub if subidisempty subscriptiondatacontext dc new subscriptiondatacontext subscription tmpsub dcgetbyidsubscriptionsubid if tmpsub null tmpsubname subname dcsavetmpsub public void deletesubscriptionsubscription sub if subidisempty subscriptiondatacontext dc new subscriptiondatacontext subscription tmpsub dcgetbyidsubscriptionsubid if tmpsub null dcdeletetmpsub this seems to work so far does anyone see any problem with this approach that i might be missing i do not want to go too far down the wrong road with this if someone has already tried this way and found some major problems with itthanks for everyones input,['c#'] +189382,random color generation using php i am trying to generate random html colors in php but i am having trouble getting them to look similar or in the same family is there some function i can use to generate colors that are similar to another color besides just generating and concatenating 6 random hex digits,"['php', 'html']" +189387,why use string constants vs enum constants i have a design related questioni have seen that the uiapplication class has this kind of flagsuikit extern nsstring const uiapplicationdidenterbackgroundnotificationuikit extern nsstring const uiapplicationwillenterforegroundnotificationuikit extern nsstring const uiapplicationdidfinishlaunchingnotificationuikit extern nsstring const uiapplicationdidbecomeactivenotificationuikit extern nsstring const uiapplicationwillresignactivenotificationuikit extern nsstring const uiapplicationdidreceivememorywarningnotificationand on the other side the class uitableview declares structs liketypedef enum uitableviewscrollpositionnone uitableviewscrollpositiontop uitableviewscrollpositionmiddle uitableviewscrollpositionbottom uitableviewscrollposition one is for notifications an the other defines types of objects i believe that those two are design choices to tag some related objects and make decitions at runtime based on that flaglet us say that i want to create a factory of objects that need to be tagged in the image bellow i want enumerations or ids for every section and widget how would any widget communicate or invoke another oneej containter sharedinstance presentwidget forsection withinfoidinfo is there a deeper or more accurate reason to choose one of themthanks for your help,"['objective-c', 'ios']" +189395,check in js whether a css property is supported i want to check whether the css property pointerevents see documentation is supported by the users browser currently for example it is not supported by opera and i believe some versions of ie i would like to run a check in javascript and thisplay appropriate bits of html depending on whether or not it is supported is there a better way to do this than checking the useragent string,"['javascript', 'css']" +189396,program stopped working problem event nameclr20r3 i am starting my program from release folder on my windows 7 64bit machine it is workingin virtual machine windows 7 32bit it is workingon third machine with windows 7 64bit it is not workingon every machine i have installed net framework 4 my project use net framework 35 because i use sqlite database and sqlite dll as i understand need for project to be net framework 35i am using visual studio 2010 express edition sqlite databasehere is error from third computerdescriptionstopped workingproblem signatureproblem event name clr20r3problem signature 01 geotestexeproblem signature 02 10problem signature 03 4e58f462problem signature 04 geotestproblem signature 05 10problem signature 06 4e58f462problem signature 07 fproblem signature 08 12problem signature 09 systembadimageformatexceptionos version 6176002002561locale id 1033,['c#'] +189440,show spinner while loading an iframe in a facebox i am using jquery facebox to open a new window for authenticating facebook users with deviseomniauth in my rails app at first i wanted to simply load this in a div like sofacebookauthlive click facebox div idfoodiv fooload thisattr href falsebut the problem is that this will not work because there are multiple redirects the first link opens authfacebook which redirects to graphfacebookcom which redirects back to my callback url which finally redirects to a confirmation page i need to thisplay the confirmation page to the user the way i have it working right now is by opening an external window like thisfacebookauthlive click width 600 height 400 left screenwidth 2 width 2 top screenheight 2 height 2 windowopen thisattrhref authpopup menubarnotoolbarnostatusnowidthwidthheightheighttoolbarnoleftlefttoptop false is there a way for me to open a new window and load its contents in the facebox or is there a better approacheditthanks to jareds suggestion i was able to do this using an iframe mod from here see this jsfiddle however i would like to show the loading spinner while the iframe content is loading is this possible according to the documentation the way to do it normally is like thisbadgelive click facebox get pagehtml data facebox data falsebut i am not sure how to do this with the iframe mod,"['javascript', 'jquery']" +189476,how to zoom specific area of image on canvas in swing i want to zoom specific area on image which is selected by the user image thisplay on canvas using swing i already done full image zoom on canvas but cannot implement specific area zoomplease help,['java'] +189481,when does an iphone application receive didchangeauthorizationstatus delegate call i have a question about cllocationmanagerdelegate the documentation says if the user changes the settings for your location services in the iphones settingsapp then your app is supposed to receive an didchangeauthorizationstatus message to the delegate my question is when would this happenif the user changed the setting it means they are in the settings app and your app is either backgrounded or not running at all so in the former case when would your apps cllocationmanager delegate get the didchangeauthorizationstatus call,['iphone'] +189495,how to select one of and objects at random without knowing and at first for concreteness how would you read text line and select and print one random line when you do not know the number of lines in advanceyes this is a problem from the programming pearl which i get confusedthe solution choose the 1st element then select the second with probability 12 the third with 13 and so forthan algorithmi 0while more input lines with probability 10i choice this input line print choicesuppose the final choice is the 3rd element the probability is 1 x 12 x 13 x 34 x x n2n1 x n1n 12n but 1n should be correct,['c'] +189496,start with python and tornado i am new to tornado and python i need to develop web application usingpython so i came to know that tornado is good one but there isno one to guide me through if any one could help me out how to startthanksamar,['python'] +189504,does monocecil take care of branches etc location well this question may seem odd but its simple my point is if i have a goto brtrue etc in the decompiled code like examplebr il 03call il 03 retand i add a command after that call will the br at the top point to ret like it should or to that codedoes cecil do it by itself or i have to take care of all those branches it wouldnt be very hard to fix them but if cecil doesnt then i simply wont start this project ive no time or knowledge for advanced il magic pps sorry if im confusing things but im a begginer in net stuff i was allways repulsed by it same as java or anything that has a vm tbhyes i know it wont be il 03 its just for example,"['c#', '.net']" +189513,does junit execute test cases sequentially in this post i asked a small question as part of a bigger problem since i did not get responses yet i put my question hereis it reasonable to suppose that junit executes test cases sequentially a test case ends befores the next one starts does it differ between junit versions my priority is on junit4 and if not is there a simple way to force junit to execute tests sequentiallythank you,['java'] +189532,how to implement an http server on android i have two android applications on same lan provided by wifi app a that open a listening socket on port 8033 app b that use httpclient to access a on port 8033how to make it possible that a may do post and get requests on bwhat the url used by a to access b looks like thanks to all,['android'] +189536,calling java class member from native cc code i am writing an opengl cc application which i am porting to android through android ndk jni support i am having difficulties executing code from java callback signaled from nativehere is the codeclass openglsurfaceview extends glsurfaceview a public openglsurfaceviewcontext context int devicewidth int deviceheight supercontext nativeobj new nativelib mrenderer new openglrenderercontext nativeobj devicewidth deviceheight setrenderermrenderer setrendermoderendermode when dirty a private void callback force redraw requestrender class openglrenderer implements glsurfaceviewrenderer apublic void onsurfacecreatedgl10 gl eglconfig config nativeobjinita nativeobjcachejavaobjectjnienv env jobject obj for caching obj on native side public void onsurfacechangedgl10 gl int w int h public void ondrawframegl10 gl nativeobjdrawa and in native code i have a function texturesloaded that is signaled when some textures are loaded completely on another thread and i need to force a refresh from nativelibdrawa on the java side here is how i do it i cache the javavm jclass jmethodid on jni onload and gjobjectcachedjniexport jint jnicall jni onloadjavavm jvm void reservedgjvm jvm cache the javavm pointerlognativetoandroidextjniloadjnienv envint status gjvmgetenvvoid env jni version 1 6ifstatus 0 lognativetoandroidextfailed to get jni environment assuming native thread status gjvmattachcurrentthreadenv null ifstatus 0 lognativetoandroidextcallback handler failed to attach current thread return jni err gjclass envfindclasscomandroidnewlineactivitynewlineglsurfaceviewifgjclass null lognativetoandroidextcannot find java class return jni errgjmethodid envgetmethodidgjclass callback vifgjmethodid null lognativetoandroidextcannot find java method void callback return jni ereturn jni version 1 6jniexport void java com android opengl nativelib cachejavaobjectjnienv env jobject obj cache the java object gjobjectcached objand then on texturesloaded i do void texturesloaded cannot share a jnienv between threads you should share the javavm and use javavmgetenv to thiscover the threads jnienv jnienv env null int status gjvmgetenvvoid env jni version 1 6 ifstatus 0 lognativetoandroidextcallback handler failed to get jni environment assuming native thread status gjvmattachcurrentthreadenv null ifstatus 0 lognativetoandroidextcallback handler failed to attach current thread return lognativetoandroidextcalling java method from native cc envcallvoidmethodgjobjectcached gjmethodid lognativetoandroidextdoneresulta from native side i get the class i get the method method gets called but when it reachescalls requestrender insideor trying to access any other member method of glsurfaceview it crashesi cannot try with callstaticvoidmethodgjclass gjmethodid because then i do not have access to requestrenderany ideas or opinions maybe i am doing something wrong herethanks,['android'] +189548,sse microoptimization instruction order i have noticed that sometimes msvc 2010 does not reorder sse instructions at all i thought i did not have to care about instruction order inside my loop since the compiler handles that best which does not seem to be the casehow should i think about this what determines the best instruction order i know some instruction have higher latency than others and that some instructions can run in parallelasync on cpu level what metrics are relevant in the context where can i find themi know that i could avoid this question by profiling however such profilers are expensive vtune xe and i would like to know the theory behind it not just emperical resultsalso should i care about software prefetching mm prefetch or can i assume that the cpu will do a better job than melets say i have the following function should i interleave some of the instructions should i do the stores before the streams do all the loads in order and then do calculations etc do i need to consider uswc vs nonuswc and temporal vs nontemporal auto cur128 reinterpret cast m128icur auto prev128 reinterpret castconst m128iprev auto dest128 reinterpret cast m128idest auto end cur128 count16 whilecur128 end auto xmm0 mm add epi8 mm load si128cur1280 mm load si128prev1280 auto xmm1 mm add epi8 mm load si128cur1281 mm load si128prev1281 auto xmm2 mm add epi8 mm load si128cur1282 mm load si128prev1282 auto xmm3 mm add epi8 mm load si128cur1283 mm load si128prev1283 dest128 is uswc memory mm stream si128dest1280 xmm0 mm stream si128dest1281 xmm1 mm stream si128dest1282 xmm2 mm stream si128dest1283 xmm3 cur128 is temporal and will be used next time which is why i choose store over stream mm store si128 cur1280 xmm0 mm store si128 cur1281 xmm1 mm store si128 cur1282 xmm2 mm store si128 cur1283 xmm3 cur128 4 dest128 4 prev128 4 stdswapcur prev,['c++'] +189564,get text from character and after using jquery i want to get the text from a string after the occurrence of a specific characterlets say texttexttextabcand i want to get abchow is this done in jquerythis might be trivial to somebody but i have little exp in jquery,"['javascript', 'jquery']" +189585,classcastexception when casting lookedup ejb view in as7 i have am deploying 2 ears onto jboss as 710alpha1snapshot post 701final version both deploy finei have an ejb singleton class packaged within a jar within one of the ears startupsingleton one of localstoreclass remotestoreclass localbeantransactionattributetransactionattributetypenot supportedtransactionaltransactionpropagationsupportspublic class storefront implements store public interface store when it deploys it says the ejb is bound tojavaappstorecore2012snapshotstorefrontjavaappstorecore2012snapshotstorefrontukcomagusjamstorecorestorejavamodulestorefrontjavamodulestorefrontukcomagusjamstorecorestorejavaglobalstoreear2012snapshotstorecore2012snapshotstorefrontukcomagusjamstorecorestorejavaglobalstoreear2012snapshotstorecore2012snapshotstorefrontso far so good when i try to look it up via jndi from a noncdi nonejb class within a jar within the other deployed ear it can only be found on the jndi names under global again expected however when i try to cast the resulting object to the actual interface classobject lookupobject new initialcontextlookupjndinamestore store storefrontlookupobjecti get the following exception1752402 error jamcorelinklinklistener thread45 exception when casting to store after lookup with javaglobalstoreear2012snapshotstorecore2012snapshotstorefront javalangclasscastexception jamstorecorestoreview1 cannot be cast to jamstorecorestore at jamcorelinklinklistenergetstorelinklistenerjava108 corejar2012snapshotjar at jamcorelinklinklistenerpostloadlinklistenerjava27 corejar2012snapshotjar at sunreflectnativemethodaccessorimplinvoke0native method 160 07 at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava39 160 07 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava25 160 07 at javalangreflectmethodinvokemethodjava597 160 07 at orghibernateejbeventlistenercallbackinvokelistenercallbackjava48 at orghibernateejbevententitycallbackhandlercallbackentitycallbackhandlerjava96 at orghibernateejbevententitycallbackhandlerpostloadentitycallbackhandlerjava89 at orghibernateejbeventejb3postloadeventlisteneronpostloadejb3postloadeventlistenerjava49 at orghibernateengineinternaltwophaseloadinitializeentitytwophaseloadjava264 at orghibernateloaderloaderinitializeentitiesandcollectionsloaderjava1012 at orghibernateloaderloaderdoqueryloaderjava889 at orghibernateloaderloaderdoqueryandinitializenonlazycollectionsloaderjava289 at orghibernateloaderloaderdoqueryandinitializenonlazycollectionsloaderjava259 at orghibernateloaderloaderloadentityloaderjava2058 at orghibernateloaderentityabstractentityloaderloadabstractentityloaderjava81 at orghibernateloaderentityabstractentityloaderloadabstractentityloaderjava71 at orghibernatepersisterentityabstractentitypersisterloadabstractentitypersisterjava3686 at orghibernateeventinternaldefaultloadeventlistenerloadfromdatasourcedefaultloadeventlistenerjava446 at orghibernateeventinternaldefaultloadeventlistenerdoloaddefaultloadeventlistenerjava427 at orghibernateeventinternaldefaultloadeventlistenerloaddefaultloadeventlistenerjava204 at orghibernateeventinternaldefaultloadeventlistenerproxyorloaddefaultloadeventlistenerjava251 at orghibernateeventinternaldefaultloadeventlisteneronloaddefaultloadeventlistenerjava148 at orghibernateinternalsessionimplfireloadsessionimpljava947 at orghibernateinternalsessionimplgetsessionimpljava863 at orghibernateinternalsessionimplgetsessionimpljava856 at orghibernateejbabstractentitymanagerimplfindabstractentitymanagerimpljava787 at orghibernateejbabstractentitymanagerimplfindabstractentitymanagerimpljava762 at orgjbossasjpacontainerabstractentitymanagerfindabstractentitymanagerjava220 jbossasjpa710alpha1snapshotjar710alpha1snapshot at jamcoredaogenericdaofindbyidgenericdaojava87 corejar2012snapshotjar at harvestserviceharvesterdaoutilloadlinkharvesterdaoutiljava251 harvestsar2012snapshotjar at harvestservice1779224926proxy weldsubclassloadlink1779224926proxy weldsubclassjava harvestsar2012snapshotjar at sunreflectnativemethodaccessorimplinvoke0native method 160 07 at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava39 160 07 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava25 160 07 at javalangreflectmethodinvokemethodjava597 160 07 at orgjbossinterceptorproxysimpleinterceptionchaininvokenextinterceptorsimpleinterceptionchainjava112 jbossinterceptorcore200alpha3jar200alpha3 at orgjbossinterceptorproxyinterceptorinvocationcontextproceedinterceptorinvocationcontextjava119 jbossinterceptorcore200alpha3jar200alpha3 at orgjboseamtransactiontransactioninterceptor1worktransactioninterceptorjava194 seampersistence300finaljar at orgjboseamtransactionworkworkintransactionworkjava54 seampersistence300finaljar at orgjboseamtransactiontransactioninterceptoraroundinvoketransactioninterceptorjava188 seampersistence300finaljar at sunreflectnativemethodaccessorimplinvoke0native method 160 07 at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava39 160 07 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava25 160 07 at javalangreflectmethodinvokemethodjava597 160 07 at orgjbossinterceptorproxyinterceptorinvocationinterceptormethodinvocationinvokeinterceptorinvocationjava72 jbossinterceptorcore200alpha3jar200alpha3 at orgjbossinterceptorproxysimpleinterceptionchaininvokenextinterceptorsimpleinterceptionchainjava82 jbossinterceptorcore200alpha3jar200alpha3 at orgjbossinterceptorproxyinterceptormethodhandlerexecuteinterceptioninterceptormethodhandlerjava133 jbossinterceptorcore200alpha3jar200alpha3 at orgjbossinterceptorproxyinterceptormethodhandlerinvokeinterceptormethodhandlerjava112 jbossinterceptorcore200alpha3jar200alpha3 at orgjbossweldbeanproxycombinedinterceptoranddecoratorstackmethodhandlerinvokecombinedinterceptoranddecoratorstackmethodhandlerjava65 weldcore112finaljar20110726 1502 at harvestservice1779224926proxy weldsubclassloadlink1779224926proxy weldsubclassjava harvestsar2012snapshotjar at harvestservicecombineharvesterworkonlinkidcombineharvesterjava259 harvestsar2012snapshotjar at harvestservicecombineharvesterharvestcachecombineharvesterjava223 harvestsar2012snapshotjar at harvestservicecombineharvesterperformharvestcombineharvesterjava136 harvestsar2012snapshotjar at harvestservicecombineharvesterruncombineharvesterjava107 harvestsar2012snapshotjar at javalangthreadrunthreadjava619 160 07whether the ejb is annotated with one from any oflocalstoreclassremotestoreclasslocalbean makes no difference as i understand it the fact it is returning a proxy view is normal however should not i be able to cast that view to the interface the combination of which global jndi name i use and whether i cast to store or storefront also appears to make no difference unable to cast whatever the combination even when the exception is like jamstorecorestoreview1 cannot be cast to jamstorecorestore with matching base class namescan anyone point out what i am doing wrong,['java'] +189603,changing keyboard type for html textarea on ipad i am writing a web application for ipadi know it is possible to change the type of keyboard thisplayed when an html input field is selected usingtext input typetext telephone input typetel url input typeurl email input typeemail zip code input typetext pattern09 the problem is that i have to use textarea instead of input is it possible to obtain the same resultif not is there any way to change the keyboard label for the enter key at the moment the default label is return and i would like to have send since it is a chat appthanks a lot,['ios'] +189604,no such file to load bundlersetup ruby on rails i am attempting to get a rails 305 app up and running at you can see the errors there backtraceany ideas,"['ruby-on-rails', 'ruby']" +189632,memcache and eventual consistency i am working on a small project to learn about google app engine the project is in java and has customer objectsinstances of customer can have a policy each customer is in its own entity group so that transactions can be used tomodify the customer the main page of the site is a list of customers when a new customer is added the customer list is thisplayed again since each customer is in their own entity group there are times when the newly added customer does not appear in thenew customer list refreshing the customer list after a few seconds and the customer will appear a similar problemexists when deleting customers you delete the customer but it appears in the overall list for a few seconds i understandthat this is to be expected in google app engine because of the eventual consistency that the datastore providesso i have tried to get around this problem by using memcache to store the customers that have been recently added or recentlydeleted the code i am using is belowpublic listcustomer getcustomers listcustomer cachedcustomers mycachegetcached listcustomer recentlydeleted mycachegetdeleted calls the real datastore listcustomer dbcustomers customerdaogetcustomerlist setcustomer allcustomers new hashsetcustomer add cached first as these are most the most up todate allcustomersaddallcachedcustomers allcustomersaddalldbcustomers allcustomersremoveallrecentlydeleted listcustomer alist new arraylistcustomer alistaddallallcustomers collectionssortalist return alisti am asking here because i think that the way i am going about this does not feel the right way to do it and would liketo hear from those who know better ways to get around the issues that eventual consistency creates,['java'] +189642,delete all rows in an html table how can i delete all rows of an html table except the ths using javascript and without looping through all the rows in the table i have a very huge table and i do not want to freeze the ui while i am looping through the rows to delete them,"['javascript', 'html']" +189661,deferring javascript loading i have heard and read a few articles about deferring javascript loading and am very interested it seems to be very promising for web apps that may be useful on mobile platforms where the amount of javascript that can be loaded and executed is limitedunfortunately most of the articles talk about this at an extremely high level how would one approach thiseditnormally all javascript is loaded on page load however there may be functions that are not necessary until a certain action occurs at which time the javascript should be loaded this helps ease the burden of the browser on page loadspecifically i have a page that very heavily uses javascript when i load the page on my phone it would not load properly as i debugged the page i eliminated some of the js functions once enough was eliminated the page suddenly workedi want to be able to load the js as needed and possibly even eliminate the functions simply used for start up,['javascript'] +189728,python using exceptions for control flow considered bad all righti have seen this multiple times in the past but most recently with my question here so i am curious why this is the case in python because generators use exceptions to indicate the end of the dataif this is so bad for everyone using python why does the language include it in what are considered fundamental control structures for those who want to read the relevant pep go here,['python'] +189730,how objectivec singleton should implement init method i read a couple of amazing resources on singletons in objcso question what does your objectivec singleton look likefriday qa care and feeding of singletonsapple docs creating a singleton instance but none of these resources addressed init method concept explicitly and while still being a novice to objc i am confused how should i implement it so far i know that having init private is not possible in objc as it does not offer true private methods so it is possible that user can call myclass alloc init instead of using my myclass sharedinstancewhat are my other options i believe i should also handle subclassing scenarios of my singleton,['objective-c'] +189735,will the count limit expression of a forloop be evaluated only once or on each iteration if i invoke a method within a loops conditional statement will it be called with each loop iterationfor examplefor int i 0 i expensivecomputation i do somethingwill i be performing expensivecomputation on each iteration or will the result of expensivecomputation be stored and used in each iteration at the same time the loop variable is initialisedshould i instead rewrite it to thatint max expensivecomputationfor int i 0 i max i do something,['java'] +189756,check if an nsstring is just made out of spaces i want to check if a particular string is just made up of spaces it could be any number of spaces including zero what is the best way to determine that,['objective-c'] +189758,the microsoft jet database cannot open the file it is already opened exclusively by another user or you need permission to view its data i have a winforms application that i have taken over support for and it was build using visual studio 2005 with vbnet the application makes use of an access database it runs fine when it is installed as a standalone application but the install cd for the application also allows for a network install and this is where i am currently encountering issues to test the network install i created a folder on my server windows server 2003 sp2 and copied the access database to this folder i created a share for this folder and gave everyone full permissions to the share then on the workstation i installed the application and gave the path to the database as followsmyservermysharemydbmdbthe install steps here are as per the instructions given on the installation cdthe workstation that i installed it on is windows 7 ultimate when i run the application i get the error message given in the title when the application tries to read the database file i have confirmed that i am able to write to the shared folder on the server so i do not think this is a permissions issue also the database file is not in use at all so it is definitely not opened exclusively anyone have any idea what could be causing this and what i could try do to get it workingupdatei have tested the workstation installation on a computer with a fresh install of windows xp sp3 and it is able to access the database file without a problem so it seems that this error that i am getting is somehow specific to windows 7 is there maybe a known issue with oledb drivers on windows 7 my version of windows 7 btw is 32 bit,['.net'] +189761,eclipse debugging hashmap logical structure using key and values tostring method i have recently started to use eclipse after using intellij for a few years when debugging map using intellij if the key or object implements tostring a nice list of string representation of keyvalue is thisplayedin eclipse when i select show logical structure i see something like the followingthe problem with this view is that you will need to expand each entry to see the actual key and value if you need to find something in a map of more than 10 elements it becomes very tediousi understand that you can make custom logical structure and the default for map look the thisreturn entrysettoarrayis there any way either through custom logical structure or plugin to view map entries more useful thanconcurrenthashmapwritethroughentry id193,['java'] +189764,mutagen how to detect and embed album art in mp3 flac and mp4 i would like to be able to detect whether an audio file has embedded album art and if not add album art to that file i am using mutagen1 detecting album art is there a simpler method than this pseudo codefrom mutagen import fileaudio filemusicexttest each of audiopictures audiocovr and audioapic if does not raise an exception and is not none we found album art2 i found this for embedding album art into an mp3 filehow do you embed album art into an mp3 using pythonhow do i embed album art into other formatsedit embed mp4audio mp4filenamedata openalbumart rbreadcovr if albumartendswithpng covrappendmp4coverdata mp4coverformat pngelse covrappendmp4coverdata mp4coverformat jpegaudiotagscovr covraudiosave,['python'] +189765,what is the best way to make shared libraries available to multiple applications like most shops weve got a team of people working on various projects that all need to access the same core information and functions that relate to our business usually in c were currently just copying common classes from project to project but everyone is starting to have their own flavors and we want to consolidatewe use tortoise svn and have decided to maintain a separate project to contain our common classes but are not sure the best way to deploy this common code to our various applications we work for an internal it shop that can dictate everything about how the users access the applications we do not have to worry about releasing our products into the real worldsome of our thoughts have beencompile the classes into a single dll and load it into the global assembly cache gaccompile the classes into a single dll and save it to a centrally located shared drive to be referenced by all other projectscompile the classes into a single dll and include it in each projectjust fetch the most recent classes when starting a project but do not have a central shared library our interpretation of this svn externals i know this is a common problem and if you spend any time looking into these or other options you invariably find people explaining the pitfalls of each method versioning regression testing dll hell the gac sucks etc i can hardly find anyone talking about what works and why is there a preferred method,['c#'] +189805,rspecconfigure and the request object i have a rails 31 application that is being built out as a restful api the plan is to handle authentication based on an api key that is passed on each request via the authorization http header in order to test this in rspec i wanted to set the requestenvhttp authorization attribute in the configbefore blockrspecconfigure do config configmock with rspec configuse transactional fixtures true configbeforeeach do set api key in authorization header requestenvhttp authorization 6db13cc8815f42ceaa9e446556fe3d72 endendunfortunately this throws an exception because the request object does not exist in the configbefore blockis there another approach to setting this header outside of includingit in the before block of each controller test file,"['ruby-on-rails', 'ruby']" +189808,match http parameters in url with android intent filters i am trying to put together an intent filter to start my application when a certain html url is accessed in the browser i have no problems doing so when it is a standard url like wstonyxcom for example however i need to match an url with http parameters like wstonyxcompagename and it is the part after the that i am having trouble matching i have tried using androidpath androidpathprefix and androidpathpattern and none of them seem to do it for me not sure if it is cause i am doing something wrong or if it is just because it is a php path with a question mark any help is highly appreciatedps heres what my intent filter looks like at the momentintentfilter action androidnameandroidintentactionviewaction category androidnameandroidintentcategorydefaultcategory category androidnameandroidintentcategorybrowsablecategory data androidhostwmegauploadcom androidschemehttpdataintentfilter,['android'] +189840,nosuchelementexception is occurred during implementation of internetexplorerdriver in selenium webdriver currently i am working on webdriver to invoke ie browser to run the testing but i received a nosuchelementexception when i tried to run the simple example belowhowever the code just worked fine if i used chrome driver or firefox driverany idea or thought would be appreciatedjar seleniumserverstandalone250jarcodeimport orgopenqaseleniumbyimport orgopenqaseleniumwebdriverimport orgopenqaseleniumieinternetexplorerdriverimport orgopenqaseleniumremotedesiredcapabilitiespublic static void mainstring args throws interruptedexception desiredcapabilities iecapabilities desiredcapabilitiesinternetexplorer iecapabilitiessetcapabilityinternetexplorerdriverintroduce flakiness by ignoring security domains true webdriver driver new internetexplorerdriveriecapabilities drivergetwgooglecom driverfindelementbynameqerror messageexception in thread main orgopenqaseleniumnosuchelementexception unable to find element with name q warning the server did not provide any stacktrace informationfor documentation on this error please visit such elementhtmlbuild info version 250 revision 13516 time 20110823 182957system info osname windows 7 osarch x86 osversion 61 javaversion 160 25driver info driverversion remotewebdriver at sunreflectnativeconstructoraccessorimplnewinstance0native method at sunreflectnativeconstructoraccessorimplnewinstanceunknown source at sunreflectdelegatingconstructoraccessorimplnewinstanceunknown source at javalangreflectconstructornewinstanceunknown source at orgopenqaseleniumremoteerrorhandlercreatethrowableerrorhandlerjava131 at orgopenqaseleniumremoteerrorhandlerthrowifresponsefailederrorhandlerjava105 at orgopenqaseleniumremoteremotewebdriverexecuteremotewebdriverjava409 at orgopenqaseleniumremoteremotewebdriverfindelementremotewebdriverjava197 at orgopenqaseleniumremoteremotewebdriverfindelementbynameremotewebdriverjava246 at orgopenqaseleniumbybynamefindelementbyjava298 at orgopenqaseleniumremoteremotewebdriverfindelementremotewebdriverjava189 at libwebdriver2mainwebdriver2java14,['java'] +189856,lisp syntax highlighting for icsharpcodetexteditor is there a common lisp syntax highlighting xshd file for use with icsharpcodetexteditor i have not been able to find one on google and the format for writing syntax highlighting specification files is so wretchedly documented that i cannot make a very good one myself i can highlight basic keywords but not much moreit needs to have the followinghighlight common lisp keywords such as list dolist readline lambda etcsyntax highlighting for the words after defun defmacro defvar etc such that in the text defun a a is highlighted it does not have to be complete because i can add more just one or two is fine to show how it is donehighlight symbols like ahighlight quoted lists in both backquote and single quote form and unhighlight escaped forms within quoted lists escaped by etchighlight the name of a function being called for example in the text a b c a needs to be highlightedoptional anything else that i missed that would be helpful i am new to lisp so i do not know everything that can be highlighteddoes anyone know where to get a common lisp syntax highlighting file for icsharpcodetexteditor that has these features,['c#'] +189859,is there an r equivalent of strtotime php has this wonderful function strtotime that takes any string containing just about any date format and returns a time secssince1970 it is more futureproof than strptime for instance because if the date format changes my script does not break does r have anything similari do not need the timerelative feature of strtotime as of today but i am sure at some point i will need strtotimenext thursday or strtotimefirst day of last month so if you know r extensions that do that too then i would love to hear about itupdate if anyone possibly me at some point in the future want to try implementing this in r or any other language i tracked down the source code for it the relevant files are timelibh timelibre and timelib structsh it appears to all be standard c and standalone no php headers to bring in however the compile process compiles the re file into real c so you will need to install and compile php at least oncethe code that calls it is also quite straightforward see lines 1428 to 1433 at the time of writing the longer code above it in the same function is just to get the current time for use in relative times,['php'] +189864,assignment of fieldsproperties in a struct possible duplicatemodify struct variable in a dictionary why is it that mystruct test new mystruct testclosed trueworks great butmydictionarykeyclosed trueshows a cannot modify the expression because it is not a variable error at compile timewhy is different about the assignment in these two casesnote mydictionary is of type int mystructcode for the structpublic struct mystruct other variables public bool isclosed public bool closed get return isclosed set isclosed value constructors,['c#'] +189871,is object created without new operator deleted in a specific case in c if we have the following code snippetmyobject my object myobject0my object myobject1what happens to myobject0 is it deleted looking at what i have read about it it should only be deleted when we leave the scope of creation so the anwser is probably no if this is the case is there any way to explicitly delete it other than using pointers,['c++'] +189880,what does a in an import statement in python mean i am looking over the code for pythons multiprocessing module and it contains this linefrom multiprocessing import win32 connection pipeconnectioninstead offrom multiprocessing import win32 connection pipeconnectionthe subtle difference being the period before multiprocessing what does that mean why the period,['python'] +189915,difference between colorred and colorred whats the real difference between definitions for setxcolorred and setxcolorredi have found the following explanation on the web is it all about naming conventionsjava originally defined a few color constant names in lowercase which violated the naming rule of using uppercase for constants they are available in all versions of java colorblack colordarkgray colorgray colorlightgray colorwhite colormagenta colorred colorpink colororange coloryellow colorgreen colorcyan colorbluejava 14 added the proper uppercase names for constants colorblack colordark gray colorgray colorlight gray colorwhite colormagenta colorred colorpink colororange coloryellow colorgreen colorcyan colorblue,['java'] +189934,in python how do you find the index of the first value greater than a threshold in a sorted list in python how do you find the index of the first value greater than a threshold in a sorted listi can think of several ways of doing this linear search handwritten dichotomy but i am looking for a clean an reasonably efficient way of doing it since it is probably a pretty common problem i am sure experienced soers can helpthanks,['python'] +189950,how to unit test deliberate compilation errors please note that this is not a duplicate of how write a unit test for verifying compiling error as i am not concerded about testing the correctness of external libraries or the compiler itselfit is typical in c particularly when dealing with templates to employ techniques that prevent some particular piece of code from being compiled as these can get convoluted what is the best way to ensure that particular pieces of code do indeed generate compiler errorsas the test should not even get compiled you cannot rely on things such as boosttest so i guess it should be integrated in the build system how are these issues usually approached,['c++'] +189953,is it safe to share local variable between threads via a callback closure i want to do something like the following basically i am calling an async operation which will call a callback in another thread and i want to wait for it to complete inline my worry is that that changes variables shared across threads bar event may not be synchronized due to being stored in registers for example if they were member variables i could mark them volatile but volatile canat be used on local variables created on the stack i could use member variables but i think its cleaner not clutter my class by keeping it all localbar bar nullmanualresetevent event new manualreseteventfalsefooasyncoperationnew action this delegate will be called in another thread bar eventseteventwaitonetimeout use bar,"['c#', '.net']" +189971,looking for a unsigned 128bit integer datatype for the net framework possible duplicateint128 in net as i am working on a tool which manages ip devices and i would like to add ipv6 support to it i am searching for a 128bit unsigned integer net datatype to do basic ip related calculations subnetting list all hosts for a subnet it should support the standard arithmeticlogic methodsthank you,"['c#', '.net']" +189977,activitygroup switch view with animation so i have this activitygroup in which i show 2 activities when i am switching i want to have this transition effect the current view sliding to the left out of the screen the new view coming in from the rightthis is my code for switching assuming current view is viewaintent i new intentthis viewaclassviewb getlocalactivitymanagerstartactivityviewb iaddflagsintentflag activity clear topgetdecorviewsetcontentviewviewbnow when i do the following the background of viewb gets shown and the contents of viewb slide in this is not what i wantanimation animin animationutilsloadanimationthis ranimrighttoleftinviewbstartanimationaniminanimation animout animationutilsloadanimationthis ranimrighttoleftoutviewastartanimationanimoutsetcontentviewviewbhow can i achieve thisactually the above does work i had a problem where i thought viewa was shown while it was not,['android'] +189982,update and insert queries creating a deadlock i will try to explain my problem as detailed as possible and i would appreciate any helpsuggestion my problem is regarding a deadlock being caused by two queries one insert and one update i am using mssql server 2008i have two applications using the same databaseweb app on every request multiple records are inserted in the impressions table by calling a stored procedurewindows service calculates all the impressions done in one minute every minute for the previous minute and sets a flag on each of the impressions calculated via a stored procedure as wellthe web app inserts the impressions records without using a transaction while the windows service application calculates the impressions while using a isolationlevelreaduncommitted transaction the stored procedure in the windows service app does something like thiswindows service stored procedureloops trough all the impressions that have the iscalculated flag set to false and date now increments a counter and other data in another table connected to the impressions table and sets the iscalculated flag to true on impressions that have date now because this stored procedure is pretty big no point in pasting it here is a shortened code snippet of what the proc doesdeclare nowtime datetime convertdatetime now 21 declare dailycursor cursor forselect dailydailyid dailyspentdaily dailyimpressionscountcache sumimpressionsamountcharged as sumcharged countimpressionsimpressionid as countimpressionsfrom daily inner join impressions on impressionsdailyid dailydailyidwhere impressionsischarged0 and impressionsshowtime nowtime and dailyisactive 1group by dailydailyid dailyspentdaily dailyimpressionscountcacheopen dailycursordeclare dailyid int spentdaily decimal186 impressionscountcache int sumcharged decimal186 countimpressions intfetch next from dailycursor into dailyidspentdaily impressionscountcache sumcharged countimpressionswhile fetch status 0 begin update daily set spentdaily spentdaily sumcharged impressionscountcache impressionscountcache countimpressions where dailyid dailyid fetch next from dailycursor into dailyidspentdaily impressionscountcache sumcharged countimpressions endclose dailycursordeallocate dailycursorupdate impressions set ischarged1 where showtime nowtime and ischarged0web app stored procedurethis procedure is pretty simple it just inserts the record in the table here is a shortened code snippetinsert into impressions dailyid date pageurliscalculated values dailyid date pageurl 0the codethe code that calls these stored procedures is pretty simple it just creates the sql commands passing the needed parameters and executes themi send the date like thisstring date datetimenowtostringymmdd hhmmssf cultureinfoinvariantculturesqlcommand comm sqlstoredprocedurecommandstoredprocname parameters valuesi am experiencing deadlocks very often the exceptions occur in the web app not the windows service and after using the sqlprofiler i found out that the deadlocks are probably happening because of these two queries i do not have much experience in analyzing profiler datathe latest trace data collected from the sql server profiler can be found on the bottom of this questionin theory these two stored procedures should be able to work together because the first one inserts the records one by one with datedatetimenow and the second one calculates the impressions that have date datetimenowedithere is the code run in the windows service appsql sql new sqldatetime endtime datetimenowour custom dal class that opens a connectionsqlstarttransactionisolationlevelreaduncommittedtry liststring properties new liststring now liststring values new liststring endtimetostringymmdd hhmmssf cultureinfoinvariantculture sqlcommand comm sqlstoredprocedurecommanndchargeimpressions properties values commtransaction sqltransaction ok sqlcheckexecutecommcatch exception up ok false throw upfinally if ok sqlcommittransaction else sqlrollbacktransactions closeconnediti added the indexes on both of the tables as suggested by martin smith like thiscreate nonclustered index idx daily dailyid on dbodaily daily ascwith pad index off statistics norecompute off sort in tempdb off ignore dup key off drop existing off online off allow row locks on allow page locks on on primarygoandcreate nonclustered index idx impressions ischarged showtime on dboimpressions ischarged asc showtime ascwith pad index off statistics norecompute off sort in tempdb off ignore dup key off drop existing off online off allow row locks on allow page locks on on primarygofor now no exceptions will report back latereditunfortunately this did not solve the deadlock issue i will start a deadlock trace in profiler to see if the deadlocks are the same as beforeedit pasted the new trace to me it looks the same as the previous one could not capture a screen of the execution plan its too big but here is the xml from the execution planand here is a screenshot of the execution plan of the insert query deadlock victimprocess14e29e748 processlist process idprocess14e29e748 taskpriority0 logused952 waitresourcekey 672057594045071360 f473d6a70892 waittime4549 ownerid2507482845 transactionnameinsert lasttranstarted20110905t115916587 xdes0x15bef83b0 lockmodes schedulerid1 kpid2116 statussuspended spid65 sbid0 ecid0 priority0 trancount2 lastbatchstarted20110905t115916587 lastbatchcompleted20110905t115916587 clientappnet sqlclient data provider hostpid2200 isolationlevelsnapshot 5 xactid2507482845 currentdb6 locktimeout4294967295 clientoption1671088672 clientoption2128056 executionstack frame procnamedboinsertimpression line27 stmtstart2002 stmtend2560 sqlhandle0x030600550e30512609e200529f010insert into impressions dailyid languageid showtime pageurl amountcharged age ipaddress useragent portalid ischargediscalculated values dailyid languageid showtime pageurl amountcharged age ip useragent portalid 0 0 frame executionstack inputbufproc database id 6 object id 1362103893 inputbuf process process idprocess6c9dc8 taskpriority0 logused335684 waitresourcekey 672057594045464576 5fcc21780b69 waittime4475 ownerid2507482712 transactionnametransaction name lasttranstarted20110905t115915737 xdes0x1772119b0 lockmodeu schedulerid2 kpid3364 statussuspended spid88 sbid0 ecid0 priority0 trancount2 lastbatchstarted20110905t115915737 lastbatchcompleted20110905t115915737 clientappnet sqlclient data provider hostpid1436 isolationlevelread uncommitted 1 xactid2507482712 currentdb6 locktimeout4294967295 clientoption1671088672 clientoption2128056 executionstack frame procnamedbochargeimpressions line60 stmtstart4906 stmtend5178 sqlhandle0x030600e3c5474f0609e200529f010update impressions set ischarged1 where showtime amplt nowtime and ischarged0 frame executionstack inputbufproc database id 6 object id 1330103779 inputbuf process processlist resourcelist keylock hobtid72057594045071360 dbid6 objectnamedbodaily indexnamepk daily idlock14c6aab00 modex associatedobjectid72057594045071360 ownerlist owner idprocess6c9dc8 modex ownerlist waiterlist waiter idprocess14e29e748 modes requesttypewait waiterlist keylock keylock hobtid72057594045464576 dbid6 objectnamedboimpressions indexnameidx impressions ischarged showtime idlock14c901200 modex associatedobjectid72057594045464576 ownerlist owner idprocess14e29e748 modex ownerlist waiterlist waiter idprocess6c9dc8 modeu requesttypewait waiterlist keylock resourcelist deadlockedit after suggestions from jonathan dickinson i changed the stored procedure removed the cursor i changed the idx impressions ischarged showtime to not allow page locks andi added 1 second to the now property in the windows service application to avoid borderline deadlock cases updatethe query execution time was decreased after the last changes but the number of exceptions has nothopefully last updatethe changes proposed by martin smith are now live the insert query now uses the nonclustered index and in theory this should fix the issue for now no exceptions have been reported keeping my fingers crossed,"['c#', '.net']" +189983,rails 3 best way to create a comment system for posts my first entry herei am trying to add a comment system to our posts model however i am not sure of the best way to go about it for a number of reasons i would like the comment system to be similar to that on forrstcom but i would rather have visitors who comment not need an account as the site is our company site not a large communityoutline of features arevisitor can comment on post entering name email and commentour team members can comment i would like these to be styled differently so would like the system to know it was from one of our team they will be logged into the system when leaving a commentvisitors and team members can reply to a comment the system needs to know which comment it was in reply tolastly i would like the system to know if the comment was written by the post authori have looked and been trying out acts as commentable with threading which seems perfect except everyone needs a user account to leave a comment something i am trying to avoid unless anyone has other thoughts on thati have also implemented this myself by creating a comments model and using awesome nested set for the threading within the comments model i have a user id which is only populated if the user is logged in meaning they must be a team member this seems a little messy thoughdoes anyone have any thoughts on thisoh and i would love each person to be notified of a reply to their comment if posthanks in advance,"['ruby-on-rails', 'ruby']" +190003,precompile mustache templates or load externally it would be useful to have a coffeescript include function so it could load the external mustache templates when compiling in javascript and not clutter the coffee filesactually you can load mustache files at runtime but you need to call them with an ajax request with some performance penalities involvedi would like to precompile some static mustache templates and include them in generated javascript function that could be stitched and compressed in a single fileis there a project or a script for that,['javascript'] +190012,resharper find and fix all issues at once egalt enter context menu find all redundant name qualifier issues but now in the new window that lists all those issues in my project is there a way to fix them all rather than go through them individualyta,['c#'] +190022,css how to break long words in a table td this is what i havetd stylewidth500px whitespace prewrap whitespace mozprewrap whitespace prewrap whitespace oprewrap wordwrap breakword,['css'] +190044,how can i show a viewbag as html ok quite new to aspnet mvc so i am sorry if this is a silly question but how do i go about showing the values of a viewbag as html for example if viewbagsomemessage contains the following texth3testh3ptestpptestpptestpptestpptestphow would i go about actually having the page render that as normal html or is there a much easier way of achieving this that i am totally missingcheers,"['c#', 'asp.net']" +190086,run migrations from rails console is there a way to run rake commands for dbmigrate and dbrollback on the console it sucks to wait for the rails environment to load,['ruby-on-rails'] +190097,different return values the first and second time with moq i have a test like this testcasepagemyaction public void page with custom actionstring path arrange var pathdata new mockipathdata var pagemodel new mockipagemodel var repository new mockipagerepository var mapper new mockicontrollermapper var container new mockicontainer containersetupx xgetinstanceipagerepositoryreturnsrepositoryobject repositorysetupx xgetpagebyurlipagemodelpathreturns pagemodelobject pathdatasetupx xactionreturnsmyaction pathdatasetupx xcontrollerreturnspage var resolver new dashboardpathresolverpathdataobject repositoryobject mapperobject containerobject act var data resolverresolvepathpath assert assertnotnulldata assertareequalmyaction dataaction assertareequalpage datacontroller getpagebyurl runs twice in my dashboardpathresolver how can i tell moq to return null the first time and pagemodelojbect the second,['c#'] +190132,aspnet mvc alongside web forms in the same web app has anyone successfully deployed aspnet mvc alongside web forms in the same application in a production environment were there any conflicts or gotchas you faced while doing sois it really as easy as shown here in practice what about if you run a mvc using the razor view engine alongside web forms,['asp.net'] +190133,ruby on rails super simple signup page how would i be able to make a signup page with ruby on railslike i have a beta page and a user enters their email address and then i can add it to the databasealso i could send them an email confirming their signupedit i want something real simple like just plain adding a row in a database simple i do not need a password box and a username box because that just further complicates things i am a beginner so i like to have things simple,['ruby-on-rails'] +190148,activatorcreateinstance works inside vside but not externally i have a bunch of com objects which all implement the same interface and need to create one of them as chosen at runtime from a list of options since i know the clsid for each of the implementing com servers this should be easy however for a certain subset of com libraries i can only make this work if i am running inside of the vs2010 idehere is the entire program i am using to test withusing systemnamespace comtest class program static void mainstring args var clsid e8978da6047f4e3d9c78cdbe46041603 var type typegettypefromclsidnew guidclsid var obj activatorcreateinstancetype true consolewritelineobj is 0 obj i can make this work for every com clsid i have tried so far as long as i run through vs2010 with or without the debugger attached and with or without the hosting process attached i get a system comobject back from createinstancewhen i compile and run this code from a console window for certain clsid values i instead getunhandled exception systemruntimeinteropservicescomexception creating an instance of the com component with clsid e8978da6047f4e3d9c78cdbe46041603 from the iclassfactory failed due to the following error 804005 at systemruntimetypehandlecreateinstanceruntimetype type boolean publiconly boolean nocheck boolean canbecached runtimemethodhandleinternal ctor boolean bneedsecuritycheck at systemruntimetypecreateinstanceslowboolean publiconly boolean skipcheckthis boolean fillcache at systemruntimetypecreateinstancedefaultctorboolean publiconly boolean skipvisibilitychecks boolean skipcheckthis boolean fillcache at systemactivatorcreateinstancetype type boolean nonpublic at comtestprogrammainstring args in this only happens with particular clsids for example c1243ca0bf9611cdb57908002b30bfeb the builtin text ifilter works but e8978da6047f4e3d9c78cdbe46041603 acrobat reader xs ifilter does not what i cannot figure out is how being run via the ide makes any different on wether a com interop call will succeed any ideasediti am not running vs2010 as an administrator but i have tried running the output binary through an elevated powershell console and it still does not workedit 2thus far the only com server i have used that reproduces this bug is acrobat reader xs arordifdll prior versions work fine i am not worried about getting acrobats specific ifilter working anymore but i am very concerned that i have code that runs in my ide but not outside of it and as an aside the windows sdk filtdump tool has no problem loading this com server so i know it is possible i just do not know how,['c#'] +190149,how to get utc offset in seconds in android i am trying to get the utc offset in seconds in android since the emulator keeps returning 0 i cannot tell if i am doing this correctly or not calendar ccalendargetinstance timezone tzcgettimezone int offsetfromutctzgetoffset010when i put 0 in the tzgetoffset it means i just want the number of seconds from gmtlet me know if what im doing is correct thanks,['android'] +190156,aes string encryption in objectivec my objectivec app requires text string encryption specifically nsstring i know aes is the most secure encryption method available for consumer use i also understand how to convert strings to data and back just a beginner many webpages and qas about encryption with aes are unclear and none of them state how to use the code given for example a webpage might say here is the code here is what it does but no explanation for how to use it i have found this code through lots of researchimport commoncryptocommoncryptorhimplementation nsmutabledataaesfor encryption nsmutabledata encryptaesnsstring key char keyptrkcckeysizeaes2561 bzero keyptr sizeofkeyptr key getcstring keyptr maxlength sizeofkeyptr encoding nsutf16stringencoding size t numbytesencrypted 0 nsuinteger datalength self length size t buffersize datalength kccblocksizeaes128 void buffer mallocbuffersize nsmutabledata output nsdata alloc init cryptorstatus result cryptkccencrypt kccalgorithmaes128 kccoptionpkcs7padding keyptr kcckeysizeaes256 null self mutablebytes self length buffer buffersize numbytesencrypted output nsmutabledata datawithbytesnocopybuffer lengthnumbytesencrypted ifresult kccsuccess return output return null for decryption nsmutabledatadecryptaes nsstringkey andfordatansmutabledataobjencrypteddata char keyptrkcckeysizeaes2561 bzero keyptr sizeofkeyptr key getcstringkeyptr maxlengthsizeofkeyptr encodingnsutf16stringencoding size t numbytesencrypted 0 nsuinteger datalength self length size t buffersize datalength kccblocksizeaes128 void buffer decrypt mallocbuffersize nsmutabledata output decrypt nsdata alloc init cryptorstatus result cryptkccdecrypt kccalgorithmaes128 kccoptionpkcs7padding keyptr kcckeysizeaes256 null self mutablebytes self length buffer decrypt buffersize numbytesencrypted output decrypt nsmutabledata datawithbytesnocopybuffer decrypt lengthnumbytesencrypted ifresult kccsuccess return output decrypt return null this is the code i made that i would like to correspond with the above code voidencrypt convert nsstring to nsdata so that it can be used to encrypt the input nsstring input inputbox text nsdata inputdata input datausingencodingnsutf8stringencoding what to do herehow do i use this code these methods where does it go in my implementation file,['objective-c'] +190157,passing ithisposable as a parameter is it a good practice to pass ithisposable as a parameter to a method and thispose it inside that method this is sort of inevitable when you have to use several threads well the best practices says the ownercaller should thispose it eg public void mymethodmyclass reader usingreader some code what if the owner creating thread no longer exist eg interface ireader ithisposable string readpublic class myreader ireader public string read return hellow world public void thispose thispose code here you find the problempublic void start myreader readerset new myreader5 for int i 0 i readersetlength i readerseti new myreader foreach ireader reader in readerset threadpoolqueueuserworkitemnew waitcallbackrun reader exit after creating threadspublic void runobject objreader ireader reader ireaderobjreader using reader use the reader,['.net'] +190169,store and reload matplotlibpyplot object i work in an psudooperational environment where we make new imagery on receipt of data sometimes when new data comes in we need to reopen an image and update that image in order to create composites add overlays etc in addition to adding to the image this requires modification of titles legends etc is there something built into matplotlib that would let me store and reload my matplotlibpyplot object for later use it would need to maintain access to all associated objects including figures lines legends etc maybe pickle is what i am looking for but i doubt it,['python'] +190177,aspnet mobile application development i have an existing website for schools and colleges management which is developed in aspnetc and sql servernow i am planning to support for the mobile applications like basic models from nokiasamsung and for opera mobiles i know the normal site we can access through some of the devices without any change but needs to be optimizedi am preparing another version which will be only few required fields and easy navigation for mobile for that which method i need to usenormal aspx files with optimized html codeor using wap controlsshould i use html 5please help me to decide,['asp.net'] +190180,kill background php script shared hosting i created a script that runs in the background using the ignore user abort function however i was foolish enough not to insert any sort of code to make the script stop and now it is sending emails every 30 seconds is there any way to stop the script i am in a shared hosting so i do not have access to the command prompt and i do not know the pid,['php'] +190187,jquery select option elements by value i have a select element wrapped by a span element i am not allowed to use the select id but i am allowed to use the span idi am trying to write a javascriptjquery function in which the input is a number i which is one of the values of the selects options the function will turn the relevant option to selectedspan idspan id select idh273yrjdfhgsfyiruwyiywer multiplemultiple option value1cleaningoption option value2food2option option value3toiletoption option value4babyoption option value6knickknacksoption option value9junk2option option value10cosmeticsoption selectspani wrote something as follows this does not completely work which is why i am posting this questionfunction select optioni options span idchildrenselectchildrenoption alertoptionslength 7 alertoptions0 object htmloptionelement alertoptions0val not a jquery element alertoptions0value 1 the following does not seem to work since the elements of options are dom ones not jquerys option optionsfindvalue i alertoptionattrvalue undefined optionattrselected selectedthanks,"['javascript', 'jquery']" +190192,python and unicode code point extraction in python api is there a way to extract the unicode code point of a single characteredit in case it matters i am using python 27,['python'] +190204,sql injection how to sanitize program generated sql clause in standard ajax where and order by sql clauses are provided by the program not user egvar url selectddempwhereescapeemp tpabc and hire dtcurrent date2 years and super emp id is thistinct from emp idanswered on the server bywhere isset getwhere pureclause getwhere nullorder isset getorder pureclause getorder nullquery querywhere where whereorder order by orderthe question is what should function pureclause look likeright now pureclause simply raises error if any of the following exist select insert update delete drop create truncateif other injection causes query failure that is fine as long as data undamagedto me this seems adequate but in my heart i know i am wrongclarificationsprepared statements in postgres although very fast are a pain to set up and maintain they are ok for well used queries but not custom queriescreating a prepared statement for each transaction is a huge db hit much preferred if security can be attained in at the app levellastly consider the where clauseemp tpabc and hire dtcurrent dt2 years and super emp id is thistinct from emp idhow many placeholders here this needs to be parsed correctly before being fed into a prepared statement with placeholders right or am i completely missing the boatprimary factsnot practical to write a sql clause parser for parameterized prepared statementsnot practical to write a sql clause sanitizer that guarantees no harmsolutionfor selects where the random sql can be a problem since it is too hard to protect the database let the database protect itself have different users have different roles permissions use a readonly user for selects for normal sql this guarantees no dml from these statementsbest practices four db user accessesdeveloper do everything never use as connection in web appdml can select dml on almost everything must use for dmlread can select use for all selects whether prepared or textlogin can only execute loginpassword functions used in login processpassword protectiondml and read may not access password data either through select or dmllogin should access password data only through protected functions eg function login username password returns user id function set password usr id password sets passwordonly login may run the login and set password functionsdepending on your database login may need sql access to password columnsdepending on your database the password column may be protected itself if not then should be moved out of the user table into its own secure tablesetting this up in mysql using the administrator tool took about 30 minutes including time to write the login functions and split out the password column,"['javascript', 'sql']" +190206,how do i return from a function inside a lambda consider the following toy code to determine whether a range contains an elementtemplatetypename iter typename tbool contains1iter begin iter end const t x for begin end begin if begin x return true return falseyes i know there are already perfectly fine algorithms in the standard library that is not the pointhow would i write the same thing with for each and a lambda the following does not worktemplatetypename iter typename tbool contains2iter begin iter end const t x stdfor eachbegin end xconst t y if x y return true return falsebecause that would only return from the lambda not from the functiondo i have to throw an exception to get out of the lambda again there are probably a dozen better solutions to this specific problem that do not involve lambdas at all but that is not what i am asking for,['c++'] +190218,how to integrate facebook login with your website i made some research and i cannot seem to completely undestand how to integrate facebook login with your websitei am trying to do this for an old fashioned php shop that up till now does not use any type of login but only a session that allows users to browse across pages and add items to carti read here on stackoverflow that you need a table in your database to keep the users email address and facebook id so after that i can hook up with other tables in my db in order to provide info and much more to each userare there other ways to easily integrate your website with facebookgoogle accounts i read something about openid but did not really understand whats its use so that is why i am asking you guys to put me on track i am really new with this and any advice best practices etcwill be greatly appreciatedthanks,['php'] +190243,adding jquery mobile swipe event i have a listview and what i am trying to do is add a swipe event on the links for example if a user swipes the first link it goes to that page is this possible with listview elements i have tried divhrefaliul but still no alert it works with body thanksdiv ul datarolelistview datainsettrue li classrqstpagea hrefrequestsphprequestsali lia hrefspeakersphp datatransitionpopcontrol panelali lia hrefschedulehtmlscheduleali lia hrefinformationhtmlinformationali uldivscriptdiv ul lirqstpagebindswipefunctionevent ui mobilechangepagerequestsphp slidescript,['jquery'] +190256,python regex how to replace each instance of an occurrence with a different value suppose i have this strings blah blah blahusing python regex how can i replace each instance of blah with a different value eg i have a list of values v 1 2 3,['python'] +190259,how to open already opened activity instead of creating new one i have two activities with navigation menu which has items for launching activity1 and activity2for example we starts activity2 from activity1 and then we want open activity1 by tap on navigation menu but when we do this we get new instance of activity1 instead of open xisting instancehow can i open instance of activity1 if it already exists and create new instance if not,['android'] +190265,multiple threads calling the same objects function simultaneously can it cause problems suppose i have the following c classclass myclass private int i private object locker new object public void dosomething var b 2 some work that depends on b being 2 lock locker i 3 some more work b 1 some more work and i use it this wayusagevar myobject new myclassnew threadnew threadstart myobjectdosomethingstartnew threadnew threadstart myobjectdosomethingstartcan the following sequence happen thread 1 is halfway through its workthread 2 just starts sets b 2 thread 1 sets b 1 thread 2 is confused because it expected b to be 2 but its 1the important point is that b is a local variable will the two threads get access to the same instance of b i understand that for the instance variable i this will happen hence the lock construct for that but am not sure whether i need to do locking for local variables as well,['c#'] +190290,sending encoding response in json am using alot of jquery in a project am working oni have a javascript function that makes an ajax request to a controller which returns data in jsoni would like to thisplay a user friendly message informing the user that heshe has no information stored yet but i confused as to how to send a response in json so my javascript function can determine whether not the user has information to be thisplayhere is my javascript functionfunction latest pheeds var action urlpheedslatest pheeds pheedstreamhtmldiv classloadingdiv loadingappendimg srcpheed loader src ajax urlaction typeget datatypejson error function successfunctiondata loadingfadeoutslow eachdatafunctionindexitem pheedstreamappend div classpheed iditempheed id pa classuser trigger hrefusersinfoitemuser id itemuser idap pitempheedp div classpheed meta spanitemdatetime agospan span classcmitemcomments img classcomment trigger srcpheedbackassetsimgcommentpng titleclick to comment on pheed onclickretrieve commentsitempheed id span spanitemrepheeds repheeds img classrepheed trigger srcpheedbackassetsimgcommunicationpng titleclick to repheed onclickrepheeditempheed id span span favourite img classfavourite trigger srcpheedbackassetsimgstarpng titleclick to make this a favourite onclickfavourite pheeditempheed id span div div and heres the controller function the ajax request is made tofunction latest pheeds confirm if a user is logged before allowing access ifthisislogged true load the pheed model for database interaction thisloadmodelpheed model load user model thisloadmodeluser model load comment model thisloadmodelcomment model store the pheeds to a the data variable data thispheed modelget latest pheeds load the date helper to calculate time difference between post time and current time thisloadhelperdate current timeunix timetamp time time pheeds pheeds array ifcountdata 0 foreachdata as pheed rowpheed id pheedpheed id rowuser id thisuser modelreturn usernamepheeduser id rowpheed pheedpheed rowdatetime timespanpheeddatetimetime rowcomments thiscomment modelcount commentspheedpheed id rowrepheeds pheedrepheeds pheeds row echo json encodepheeds responseresponse ok res response echo json encoderesn else it generates the json outputbut the syntax is broken so i cant read it with javascriptbut once i get rid of the following code from the above method it works normally responseresponse ok res response echo json encoderesn,"['php', 'javascript', 'jquery']" +190344,proper assert raise unit testing and use of exception class i am working on exercise 49 of learn ruby the hard waythe exercise asks to write a unit test for each function provided one of the items i am testing is if a proper exception is raised it is suggested that we use assert raise for this purposehere is the code i am testingclass parsererror exceptionendpair structnewtoken worddef peekword list begin word listfirsttoken rescue nil end enddef matchword list expecting word word listshift if wordtoken expecting word else nil endenddef skip wordword list token while peekword list token matchword list token endenddef parse verbword list skip wordword list stop if peekword list verb return matchword list verb else raise parsererrornewexpected a verb next endendand here is the test for the function parse verbdef test parse verb list one pairnewverb go pairnewnoun king assert equalparse verblist one pairnewverb go list two pairnewnoun player pairnewverb go pairnewnoun king assert raiseparsererrornewexpected a verb next parse verblist twoendwhen i run the test it fails and here is the message i getlarson2test larson ruby test sentencerbloaded suite test sentencestartedffinished in 01204 seconds 1 failuretest parse verbsentencetests test sentencerb36parsererror expected a noun or direction next exception expected notclass parsererrormessage expected a verb nextbacktraceuserslarsonrubyprojectsex48libsentencerb45in parse verbtest sentencerb36in block in test parse verb4 tests 7 assertions 1 failures 0 errors 0 skipstest run options seed 40627based on my understanding of the assert raise function this test should pass is there something wrong with the way i am using itif anybody would like a full source code of all the files i am working with i it is available here,['ruby'] +190381,does an analog of the nhibernatetofuture extension method exist in the entity framework so the question is in the headerwhat nhibernate users can dovar q1 sourcecompaniestofuturevar q2 sourceitemstofuturevar q3 sourceuserstofuturevar compoundmodel new compoundmodelq1 q2 q3 all data obtained in single database roundtrip when the first to future statement is touchedhow to mimic such behavior in ef 4,['c#'] +190415,how to combine defensive programming techniques together the question i want to ask you is quite wide but in the same time it is very concrete first i have to say that i mostly interested in answers which are applicable in the net environmentwell i want to increase the level of the code i produce now i mostly use the tdd and the static code analysis to ensure that my code is correct recently i have listened to dino espositos speech about code contracts and now i want to use it in conjunction with other techniques while listening to dino i have also recalled the debugassert and traceassertto be concrete i will ask several questionshow should i write the contracts and unit tests to complement each othershould i use code contracts in every method or in public methods onlyshould i prevent the usage of debugassert when it is ok to use them for example notice that invariants in net are checked only on public methodproperty exit so is it ok to make some checks in the middle of the method by simple assertcould you please recommend me the open source project where all these techniques are properly used because a picture paints a thousand words,['c#'] +190416,how do you pass a single quote through a url i am using nodejsvar s whos that girlvar url encodeuricomponentsrequest url post this does not work and facebook cuts off my textfull codefunction posttofacebookfbid access token data next var uri stringfbidfeedaccess tokenaccess token var uri querystringstringifydata request methodpost uri uri functioneresponsebody next appgettestfunctionreqres var d namewhos that girl link caption some caption description some description picture posttofacebookrequserfbid requserfbaccesstoken d ressenddonefacebook gets a blank post on the wall no text shows nothingwhen i log my uri it is this token2067022539347370d7ae6f314515c918732eab3611230602668gtojpi3zbatd41tpvrhb0oiyyknamewhos20that20girl3flinkhttp3a2f2fexamplecomcaptionsome20captiondescriptionsome20descriptionpicturehttp3a2f2fiimgurcom2fcmlrmpngobviously if you take a look at that url you see that the single quote is not being encoded correctly,['javascript'] +190420,why is string concatenation faster than array join today i read this thread about speed of string concatenation surprisingly string concatenation was the winnerthe result was opposite from what i thought besides there are many articles about this which explains oppositely like this or this i can guess that browsers are optimized to string concat on latest version but how do they do that can we say that it is better to use when concatenating strings,['javascript'] +190428,of macro in iowin32h i cannot understand the following line from minizips iowin32hvoid fill win32 filefunc ofzlib filefunc def pzlib filefunc defsource outdated but still relevantwhat does the of macro do,['c'] +190454,mongodb and mongoid in production i am deploying my first little app with mongodb and mongoid as a driverwhat is the right secure way to use mongodb in productioni mean in the development i have just started mongod and that is it no username or password needed and that looks unsecurealso mongoid sets default configurationsproduction host envmongoid host port envmongoid port username envmongoid username password envmongoid password database envmongoid database how should i configure this options and entire mongodb on my production server,"['ruby-on-rails', 'ruby']" +190457,how does c code call assembly code eg optimized strlen i always read things about how certain functions within the c programming language are optimized by being written in assembly let me apologize if that sentence sounds a little misguidedso i will put it clearly how is it that when you call some functions like strlen on unixc systems the actual function youre calling is written in assembly can you write assembly right into c programs somehow or is it an external call situation is it part of the c standard to be able to do this or is it an operating system specific thing,['c'] +190459,using list as a data type in a column sqlalchemy i want to store a list of rss feed urls in an sqlite db i am using sqlalchemy and was wondering how to store these i cannot seem to find any documentation about lists and was wondering if this was legal for a column columnrss feed urls listor is there an array type that i could use,['python'] +190466,set edittext digits programmatically i am essentially trying to set the digits value of an edittext programmatically so far i haveweightinputsetinputtypeinputtypetype class phoneweightinputsetkeylistenerdigitskeylistenergetinstancewhich is fine but i also want to be able to include a decimal place any ideas,['android'] +190475,how to get the domain name from the request in a java servlet if a single servlet serves data from two domains example1com and example2com how do you retrieve the domain information from the request in a java servletthe purpose is to perform different actions depending on the domain,['java'] +190478,prevent linebreak of span element i have a span element which i want to thisplay without any line break how can i do that,"['html', 'css']" +190480,c compiler error while assigning int to object namespace consoleapplication1 class program static void mainstring args object obj new object3 obj0 new object obj1 some string obj2 10 string strings new string one two three obj strings no error here why int ints new int 1 2 3 obj ints compiler error cannot implicitly convert type int to object why i get a compiler error while doing the step as shown above but in the preceding step there is no error can somebody explain me this behavior i am using vs 2010edit for sake of completeness again this would not compile variance support in net 40 has been cleaned up now one can use new keywords in and out with generic type parameters listobject objectlist new listobject liststring stringlist new liststring objectlist stringlist,['c#'] +190492,why does return listsort return none not the list purposeaccept a file nameprint out the unique words alphabeticallyproblemthe file runs and i have been able to verify that the finduniquewords does result in a sorted list however it does not return the list to the main methodi cannot seem to find out why this is any ideasthanksleedef finduniquewordsthelist newlist words read a line at a time for item in thelist remove any punctuation from the line cleaned cleanupitem split the line into separate words words cleanedsplit evaluate each word for word in words count each unique word if word not in newlist newlistappendword answer newlistsort return answerdef cleanupphrase item strphrasereplace item stritemreplace item stritemreplace item stritemreplace item stritemreplacen return itemdef main filename raw inputenter a filename list openfilenamer finallist finduniquewordslist print finallistmain,['python'] +190508,align div at bottom on main div i have two divs one inside the other and i would like the small div to be aligned at the buttom of the main divheres my code so far currently the button is at the top of main div instead i want it positioned at the bottom any help would be appreciatedvertical banner border 1px solid e9e3dd float left height 210px margin 2px padding 4px 2px 10px 10px textalign left width 117pxbottom link verticalalign bottomheres how i have been trying to use it but as you can see i am still new to css div classvertical banner div idbottom link input typesubmit valuecontinue divdiv,"['html', 'css']" +190514,spring standard logging aspect interceptor i have found a lot of examples on how to create a custom aspect for logging using the spring framework like this or this but did not find standardcommon spring implementation for this situation and question are there any standard implementations of logging aspect from spring or not,['java'] +190541,is javastyle groovy as fast as java if i understand correctly groovy is dynamically typed but since it is almost a superset of java static type information may optionally be provided this could be useful if writing something where only a few parts are performance critical while avoiding the friction of using multiple languages type annotations could be provided only for the performance critical parts what is the performance penalty for using groovy instead of java in functionsclasses where the javalike subset is used and static type annotations are provided,['java'] +190560,understanding the etcgmt time zone what is the rationale behind apple using etcgmt timezone when they return the receipt from the app store for autorenewable subscriptionswhat exactly is the etcgmt time zone does the java sdk understand this time zone or do i have to use other thirdparty libraries like jodatime,"['java', 'iphone']" +190563,splitting routes file into multiple files i am working w a rails 3 application and i want to split up the routes into separate files depending on the subdomain right now i have this in my routesrb fileskateparksapplicationroutesdraw do constraintssubdomain api do load routesapirb endendand in my routesapirb file i haveresources skateparksthis does not seem to work though because if i run rake routes i get undefined method resources for mainobjectalso if i try to navigate to i getrouting errorno route matches,"['ruby-on-rails', 'ruby']" +190615,nullpointerexception in windowmanagerimpl on android os 32 i got an null pointer exception on android 32 emulator on a simple android project created by wizerd with a service in separated process when i switch between stretch to fill screen to zoom to fill screen this crash will not happen if the service is put into the same process with main activity namely androidprocess attribute not specified while it only happens when i add androidprocess to manifest file for my test servicethe exception isfatal exception main javalangnullpointerexception at androidviewwindowmanagerimplreportnewconfigurationwindowmanagerimpljava427 at androidappactivitythreadhandleupdatepackagecompatibilityinfoactivitythreadjava2801 at androidappactivitythreadaccess2700activitythreadjava122 at androidappactivitythreadhhandlemessageactivitythreadjava1151 at androidoshandlerthispatchmessagehandlerjava99 at androidoslooperlooplooperjava132 at androidappactivitythreadmainactivitythreadjava4123 at javalangreflectmethodinvokenativenative method at javalangreflectmethodinvokemethodjava491 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava841 at comandroidinternaloszygoteinitmainzygoteinitjava599 at dalviksystemnativestartmainnative methodmy test codetestactivityjava generated by wizerdpackage comtestimport androidappactivitypublic class testactivity extends activity override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain intent intent new intentthis testserviceclass startserviceintent testservicejava most of the functions are emptypackage comtestimport androidcontentcomponentnamepublic class testservice extends service private boolean m connected false private serviceconnection m conninitservice new serviceconnection public void onserviceconnectioncomponentname classname ibinder service m connected true public void onservicethisconnectedcomponentname classname public static class testservicebinder extends binder public ibinder onbindintent intent return new testservicebinder public void ondestroy superondestroy public int onstartcommandintent intent int flags int startid return 1 if i run the test app without service or with service in the same process the screen compatibility switch will not cause any problem however i do not understand why service can cause system exception during screen compatibility switch is this because service process is a nonui process which could potentially triggers a bug inside the android core code,['android'] +190643,does forcedirected layout of d3js support image as node d3 has a demo of a forcedirected graph layoutinstead of circles i want all nodes in the graph to be imagesso i changed appendsvgcircle attrclass node attrcx functiond return dx attrcy functiond return dy attrr 5 stylefill functiond return filldgroup callforcedragto appendxhtmlimg attrsrc callforcedragbut i can not see any images what am i doing wrong,['javascript'] +190667,generating ssh keys for apache user how do i add ssh keys for apache user in linux background i am trying to add a service hook to github to notify a url once i push to my repo i have the following php page set upphp git pull origin master however i get the following outputsh git permission deniedthis is because the keys i generated for github access were generated by my root user however when i exectue a command from php it is the apache user that runs itthe keys therefore do not correspond and permission is denied to pullas i cannot switch user from the terminal to generate keys as apache i am not too sure what to do can anyone suggest a solution,['php'] +190670,servicestacktext how to serialize class to json just downloaded servicestacktext to use it in my aspnet i have class with many properties and would like to serialize five of themstring integer binary to json could anyone post simple example how to create json object from my class,['c#'] +190674,can i access a base classes protected members from a static function in a derived class i have a program where i need to make a base class which is shared between a dll and some application code then i have two different derived classes one in the dll one in the main application each of these have some static member functions which operate on the data in the nase class they need to be static as are used as function pointers elsewhere in its simplest form my issue is shown belowclass base protected int var class derived public base static bool process base pbase pbasevar 2 return true my compiler complains that i cannot access protected members of pbase even though derived has protected access to base is there any way around this or am i misunderstanding somethingi can make the base variables public but this would be bad as in my real instance these are a lump of allocated memory and the semaphores to protect it for multithreadinghelp,['c++'] +190681,what is the canonical implementation of markdown the problem with writing my own markdown parser in clojure is that markdown is not a wellspecified language there is no official grammar just an informal heres how it works description and a really ugly reference implementation in perl i can see grubers specification here and the implementation here this is an implementation that wins the google ranking test here then there is pegmarkdown which appears to solve the there is no grammar problem but is not the canonical implementationmy question is what is the canonical implementation of markdown the one that everybody says defines the standard editi acknowledge that there is no canonical standard i am looking for the next best thing the answer seems to be showdownjs but there are problems with it using the definition of canonical being the one that everybody says defines the standardit gets referenced here and on github here i will throw in pagedown as well as aluded to by deceze because it appears to fix the bugs in showdown and be a little closer to grubers original,['javascript'] +190683,thistributing state across many machines i am trying to write up a tool that requires knowledge of the state of other machines in a cluster local lan this is for a network failoverhigh availability system similar to vrrp and corosyncopenais but i wish to contain more information such as near realtime speedperformance characteristics so devices can make more intelligent choices this means using a protocol more complicated than a predetermine weightbased mechanism by allowing all clustered machines to see the state of each other they can communally agree on which is the most suitable to be the master devicefrom my searches i have not found any c c or javame libraries that offer a thistributed state mechanism ideally i am looking for something that broadcastsmulticasts each individual machines state periodically so participating machines can build up a global state table and all can see who the master should be state in this case is arbitrary keyvalue pairsi would rather not reinvent any wheels so am curious to know if anyone here can point me in the right direction,"['c++', 'c']" +190688,how to do cucumber android integration testing i am trying to set up continuous integration with an android project and cucumberthe idea is to write tests in cucumber and run the tests on my android build via cuke4duke and nativedriver for androidwhen i have this running i plan to use maven and a jenkins server to automate the testing so it is run every time i commit to the subversion repohas this been done before is there a good guide somewhere or is it a bad idea to do it this way,['android'] +190692,error void value not ignored as it ought to be template typename z z mytemplate z popfromvector if myvectorempty false return myvectorpop back return 0int main mytemplate int obj std cout objpopfromvector return 0errorerror void value not ignored as it ought to beafai can see the return type of popfromvector is not void whats the point that i am missingthe error thisappears when i comment out this call in main,['c++'] +190716,do you have to implement multiple iterators in a stllike class i am quite familiar with the stl and how to use it my question isif i were to implement my own stl container type how are the internal iterators defined stl classes tend to have sequential or randomaccess iterators const versions of these and stream iteratorsare these iterators all fullydefined in every stl class or is there some sort of base class that you inherit from to gain most of the iterator functionality does anyone know a good reference for how to implement a class that supports these different kinds of iterators,['c++'] +190725,changing metatags dynamic with jquery these are my metatagsmeta propertyogimage contentassetscssgfxskoldpngmeta propertyogtitle contentden historie hjemmesiden for norges golfforbundmeta propertyogdescription contenther finner du alle de historie tingene som har skjedd i norges golfhistorie gjennom tidene meta propertyogurl contenthttpmeta propertyogsite name contentnorges golfklubbmeta propertyogtype contentsportand i am trying to change them dynamic with the following codemetapropertyogtitleattrcontent resulttitlebut i am keep getting syntax error unrecognized expression propertyogtitle in firebugusing the latest version of jquery does anyone know what i am doing wrong,"['jquery', 'html']" +190729,how to select only one sibling with jquery i have this code ul li classfoofoo textli li classfoo2foo2 textli more li here li classbarbar textli li classbar2bar2 textli more li here li classbazclickmeliulandbazclickfunction alerttest thissiblingsbar0text does not worksiblingsbar0 does not work no alert box pops up and no javascript errorwhat is the proper way to select one sibling only jsfiddle tryedit i do not want to use prev or next,['jquery'] +190741,jlist selected item to string could someone tell me how to get the selected item of jlist to a string it is a single selection jlist,['java'] +190766,assign custom navigation bar to uinavigationcontroller possible duplicatecustom uinavigationbar background i am creating my uinavigation controller programatically in the application delegate i have a class that subclasses uinavigationbar and would like to assign that as the controllers navigation bar in ib i would just select the controller its bar and change the class from the default to my custom class however i do not know how to do this in code any help would be greatly appreciated,"['iphone', 'ios']" +190770,backbone routes without hashes i am using backbone for a current project i was wondering if it is possible to do routing without hashes like davisjs does thanks,['javascript'] +190822,xmlschema inferred from an xml file how to iterate through all the elements in the xsd i have an xml file and i am inferring its xsd schema in runtime using the xmlschemainference clasample fileproducts product id1 nametshirt size namemedium size namelarge price net10net gross25gross price product product id2 namecomputer mouse price net50net price productproductsit does work it infers the schema nicelyxml version10xsschema attributeformdefaultunqualified elementformdefaultqualified xmlnsxs xselement nameproducts xscomplextype xssequence xselement maxoccursunbounded nameproduct xscomplextype xssequence xselement minoccurs0 maxoccursunbounded namesize xscomplextype xsattribute namename typexsstring userequired xscomplextype xselement xselement nameprice xscomplextype xssequence xselement namenet typexsunsignedbyte xselement minoccurs0 namegross typexsunsignedbyte xssequence xscomplextype xselement xssequence xsattribute nameid typexsunsignedbyte userequired xsattribute namename typexsstring userequired xscomplextype xselement xssequence xscomplextype xselementxsschemathe question ishow can i iterate recursively through all the elements from this schema how are they stored by the xmlschemaset class i need to present them to the user so they can do some mapping i am retrieving an xmlschema from xmlschemasetschemas property and then what xmlschemaelements only contains one item products and i cannot find any way to look up what its subelements are,['c#'] +190830,why would not regroups give me anything when i run this codeprint researchr1 1groups i get a result of however group0 gives me the matchshould not groups give me something containing the matchupdate thanks for the answers so that means if i do research with no subgroups i have to use groups0 to get a match,['python'] +190865,there is no xib file when i create a new empty application in xcode i am working through the big nerd ranch guide 2nd ed for ios programming using xcode version 42for the very first project i am asked to create a new project which is a windowbased application the description for which reads this template provides a starting point for any application it provides just an application delegate and a window the windowbased application option was not available to me in xcode 42 but i did see the option to create a new empty application which has the same description this template provides a starting point for any application it provides just an application delegate and a windowwhen i create the project i am supposed to have a mainwindowxib file but that does not show up at all in my project help please,"['objective-c', 'ios']" +190866,union iterator for maps preface the associative c containers like stdmap are a bit like microdatabases with just one key column boosts bimap elevates this to a twocolumn table with lookup in both columns but that that is as far as the analogy goes there is no polymap that generalizes the ideain any event i want to keep thinking of maps as databases and i now wonder if there is an iterator or some other solution that allows me to do a union of several constituent maps that is all maps have the same type or value type and comparator at least and i want a single iterator that treats the entire collection as a big multimap repeated keys are ok and lets me traverse it in the correct unioned orderdoes such a thing exist perhaps within boost or is it easy to rig one up in pseudo codestdmapk m m1 m2union iteratork m um1 m2forauto it ubegin it uend it for example if we hadm1 900 check in 1200 break 1600 check out m2 1030 coffee 1215 backed beans 1500 lies then i want the iterator to produce900 check in 1030 coffee 1200 break 1215 backed beans,['c++'] +190882,why do people use i i 1 instead of i i have seen that in a number of loops and increments instead of doing i they do i 1 why is this,['javascript'] +190887,how to check if an nsarray contains an object of a particular class what is the best way to test if an nsarray contains an object of a certain type of class containsobject seems to test for equality whereas i am looking for iskindofclass equality checking,['objective-c'] +190929,convert speech to text in iphone i want to convert speech to text in iphoneis there any way i had used vocalkit but it is not giving the true outputeditand i had also tried to use openears for speech to text openearsbut then also it is not working properlythe problem with open ears is i had tried to implement open ears through but i cantt able to understand how to use the openears in our appstep 4i had successfully configured itif you have any demo our detail link with sample code then please send itexamplei had found the code from githubcode linknot i this application when i speak anything it does not recognize properlyi had edited my questionplease check itand i had also tried to use openears for speech to text openearsbut then also it is not working properlythe problem with open ears is i had tried to implement open ears through but i cantt able to understand how to use the openears in our appstep 4i had successfully configured itif you have any demo our detail link with sample code then please send itwhat i want to do iswhatever i speak it recognize the proper words with any language and want to do the particular action on the recognized text of the speechplease help methanks in advance,['iphone'] +190950,convert polygon to triangles in order to create a vbo in opengl i need to convert polygons to trianglesis there an example of scriptcode somewhere that would describe this i would need something robust for convex and concave polygons,['c'] +190967,simple gae java json rest server i am a newbie at gae json rest and the web in general i have a very simple gwtgae datastore i would like to use to update data in an android application i wrote after some research it seems a good way to do this is to create a restful web service my android app will access through an http request that sends back json formatted data i have been looking for a way to do this and there seems to be many ways mostly using 3rd party libraries there are so many it is hard to choose wisely as a beginner also my problem is so simple that this would be a good chance to learn the basics of creating a restful web service and json on gae all it needs to do is return json data from a url no creates no updates no deletes i imagine a simple example or tutorial of java code would make more sense to achieve my goal than learning a complicated library does anyone know of a simple example or tutorial to send me in the right direction thanksno snark pleaseupdatein the doget override of greetingserviceimpl that comes from the wizard i added superdogetreq respprintwriter out respgetwriteroutprintlnhello worldthis seems to work could it be this simple can i just modify this code to generate my json output in place of the hello world string and i am done,['java'] +190976,process has died in my app i am downloading images from the web sometimes i am getting the following error in stack trace and then app crashed what is meaning of the process has died how to handle thiserror0906 110346127 iactivitymanager 98 process comibkrelgifto pid 7684 has died0906 110346157 iwindowmanager 98 win death window44b0e778 comibkrelgiftocomibkrelgiftoelgiftosplash pausedfalse0906 110346167 iwindowmanager 98 win death window44b4e400 comibkrelgiftocomibkrelgiftoehome pausedfalse0906 110346207 iactivitymanager 98 start proc comibkrelgifto for activity comibkrelgiftoelgiftosplash pid8011 uid10060 gids3003 10150906 110346487 iusagestats 98 unexpected resume of comibkrelgifto while already resumed in comibkrelgifto0906 110416687 winputmanagerservice 98 got remoteexception sending screen onoff notification to pid 7684 uid 10060,['android'] +190980,ora00936 missing expression when reading from database with dotconnect driver and oracle database i am using dotconnect driver for connecting to oracle database but i always get this error when i want to use parameters ora00936 missing expressioncodeusing var cmd conncreatecommand connopen cmdcommandtext select stevilka dokumenta from zmpt dokumenti po where status status cmdparametersaddstatus oracledbtypevarchar 1 using var reader cmdexecutereader while readerread string stevilkadokumenta readergetstringstevilka dokumenta error is hereusing var reader cmdexecutereaderwhy i get ora00936 missing expression how must i declare input parameters,['c#'] +190989,cannot get zclip to work i know it works even on this site but only when i trigger it via the h1 element and i need to trigger it via an image representing copy but when i try it simply would not work heres my javascriptcopytxtclickfunction alerttxt2copytext thiszclip path scriptsjszeroclipboardswf copy txt2copytext aftercopy function alerttxt2copytext was copied to clipboard the alert was just for me to make sure it reaches and it does it just would not copy if i add the beforecopy i do get a message there but it moves no furtherthe id copytxt has been moved to a span an img tr td and the table itself but it just would not work unless i fire the event from the h1 the html in which the image istr tdlabel fornavurlnavigation url nbspimg idcopytxt srcimagescopypnglabeltd td idtxt2copy thisorderordernavigationurl td tr,"['javascript', 'jquery']" +190997,other way to prohibit a certain c class construction except than declaring the constructor private say i have a class with some const reference member variable and i would like to forbid a certain type of construction so i would declare the according constructor private of course a constructor must initialise all const reference member variables of the class doing so however results in odd looking codeclass a class b bconst a a hosta private bhosta this is ugly and not needed const a hostis there another way to prohibit a certain construction type except than declaring the constructor private i do not want to let the compiler write a constructor for me,['c++'] +191002,send data from android to pc via usb how to send a simple data with java programming from android to pc connected via usb i am using android 233 also can someone tell me what apis should i look for doing this thanks,['android'] +191008,converting hex nsstring to nsdata i am trying to convert a hex nsstring to nsdata i am using the below attached code the following is the output0 0 0 0 0 0 0 0which looks totally irrelevant to me any idea suggestions on where its going wrong nsstring strdata 72ff63cea198b3edba8f7e0c23acc345050187a0cde5a9872cbab091ab73e553nslogstring data length is dstrdata lengthnsmutabledata commandtosend nsmutabledata alloc initunsigned char whole bytechar byte chars2int ifor i0 i strdata length2 i byte chars0 strdata characteratindexi2 byte chars1 strdata characteratindexi21 whole byte strtolbyte chars null strdata length commandtosend appendbyteswhole byte length1 nslog commandtosend,"['iphone', 'objective-c', 'ios']" +191009,how do i stop visual studio inserting a space between function definition and immediate call i am using the visual studio jslint plugin to keep my javascript in order which seems to work really well apart from this one problem if i type inx function and then put the semicolon on the end visual studio corrects it tox function and then jslint complains js lint unexpected space between and obviously this is fixable by removing the space but visual studio is very persistent in putting the space back putting a semicolon anywhere inside the function which is most of the file will cause vs to put the space back this is starting to get annoyingi have tried mucking about with the visual studio javascript editor settings insert space after but cannot seem to stop it doing thisanother way this could be expressed is x function which vs leaves alone but jslint says js lint move the invocation into the parens that contain the function so no dice thereany suggestions i know i can turn bits of jslint off even just around this last line of the file but that is going to look messy i would like to do a bit better,['javascript'] +191026,c net 40 wcf messagesecurityexception security header is empty when consuming a service when using wcf and c in a project i get an exception mesagesecurityexception with the message security header is empty here follows the response according to ms service trace viewer soapenvenvelope xmlnssoapenv xmlnswsa soapenvheader wssesecurity xmlnswsse soapenvmustunderstandtruewssesecurity wsaaction what i did wsaaction wsarelatesto msg id of request wsarelatesto soapenvheader soapenvbody correct body soapenvbody soapenvenvelopeindeed the security header is empty but it is still correct accprding to the security header definition as far as i can telli have also tried editing the bindings but that does not seem to help as well i also found a similar problem where enabling enableunsecuredresponse would help but it does not herehere is the response according to soapuisoapenvenvelope xmlnssoapenv xmlnswsa soapenvheader wssesecurity soapenvmustunderstandtrue xmlnswsse wsaaction what i did wsaaction wsarelatesto req msg id wsarelatesto soapenvheader soapenvbody correct body soapenvbodysoapenvenvelopethey are almost identical except for how they close the security header which is interesting but should not raise the exceptioni also found a similar problem where the solution was to create a custom message encoder and strip the entire security header although this would work it is an extra unneeded step is that the only way to do it with net and wcf cannot wcf handle security headers without contenteditclarification of the issue is writing an encoder which drops the security header the only way to recieve and parse soapmessages with empty security headers using wcfedit2 adding part of conf binding nameninjabinding security allowserializedsigningtokenonreplytrue enableunsecuredresponsetrue authenticationmodeusernameovertransport requirederivedkeysfalse securityheaderlayoutlax includetimestampfalse allowinsecuretransporttrue keyentropymodecliententropy messageprotectionordersignbeforeencryptandencryptsignature messagesecurityversionwssecurity10wstrustfebruary2005wssecureconversationfebruary2005wssecuritypolicy11basicsecurityprofile10 requiresecuritycontextcancellationfalse localservicesettings detectreplaysfalse secureconversationbootstrap identical to above secureconversationbootstrap security textmessageencoding httpstransport bindingas far as i know its configure to allow practically everything,"['c#', '.net']" +191037,how to thisplay pdf on php website without flashadobe i am not satisfied with the browsers internal behaviour of thisplaying pdfs i would like to provide my users with an easy yet stylish pdf viewing experience on my sites something like scribd but managable and unter full security and control on my serveri could provide inline links to googledocsviewer or zohoviewer or convert the pdf right after its upload with swftools and show the swf with native php or html5anyway somehow after hours of reading and thinking i am just not happy with any of the above approachesany suggestions,['php'] +191041,doctrine 2 saving entity in complex relationship i have the following relationships within my doctrine entitiesfavoriterecipe manytoonetargetentityuser inversedbyfavoriterecipes private user manytoonetargetentityrecipe inversedbyfavoriterecipes private reciperecipe onetomanytargetentityfavoriterecipe mappedbyuser private favoriterecipesuser onetomanytargetentityfavoriterecipe mappedbyuser private favoriterecipesin one of my controllers i have the following codefavoriterecipe new entitiesfavoriterecipefavoriterecipesetreciperecipefavoriterecipesetuseruserthis empersistfavoriterecipethis emflushbut this throws an exception with the following messagea new entity was found through a relationship that was not configured to cascade persist operations entitiesuser0408bd0107cb1380e explicitly persist the new entity or configure cascading persist operations on the relationshiphow can i correctly create and save a favoriterecipe entity,['php'] +191053,should you report the message text of exceptions consider some code that can throw a checked exception an exception of type exception your code catches the exception of course you do not just swallow the exception either your code reports it in some way to the user through your user interface in a log file perhaps or using a gui popupshould the text you report to the user include the message text of the exception that is the text provided by throwablegetmessage or throwablegetlocalizedmessagei think not but it seems many thisagree with me so what have i got wrong my argument is as followsthe message was created when the exception was thrown it therefore at best can provide only very low level information which can be inappropriate for reporting to a userphilosophically using the message seems to me against the whole point of exceptions which is to separate the detection and initiation of error handling the throw part from completion of handling and reporting the catch part using the message means the message must be good for reporting which moves responsibility for reporting to the location that should be responsible for only detection and initiation that is i would argue that the getmessage part of the design of throwable was a mistakethe message is not localised despite its name getlocalizedmessage is not much good because you might not know what locale you want to use until you catch the exception is the report to go to a system log read by your english system administrators or is it to pop up in a window for the french user of the guii hear that java 7 has a much improved exception hierarchy for ioexception enabling you to handle different kinds of io erors in diferent catch clauses making the getmessage text less important that implies even the java designers are somewhat uncomfortable with getmessagei am not asking whether reporting the stacktrace is useful a stacktrace is only ever going to be useful for an exception that suggests a bug that is for an unchecked exception i think in such circumstances providing the lowlevel detail of the exception message is not just useful but mandatory but my question deals with checked exceptions such as filenotfound,['java'] +191055,taking photo every 66 milliseconds on android phone for colour analysis heart rate monitor i am doing a final year project at university which involves making a medical application for android as a practice i have to make a heart rate monitor appi have worked out that the best way to do this is to look for colour changes in your blood when holding the camera against your finger with the flash switched onthis is where the problems come into play is it possible to take a photo every 66 milliseconds on the camera then compare each pair of photos for any intensity changes in order to count a heart beat or am i better off recording a video and analysing each frame looking for a changeheck is it even possible to just look at the video preview and compare each framethe questions i need answering for this problem are neatly listed belowwhat is the best method for this taking photos recording video or looking at the live previewis there any posts or pages i can visit on the internet where people have attempted similar thingsanyone got a basic method i should do to get two images that i can compare within the time framelastly if i do take the basic take a picture every 66 milliseconds approach what can i do to ensure the picture is taken at the correct time intervals,['android'] +191066,optimizing the number of constructor calls at work we have a class with an expensive constructor so we would like it to be called as few times as possible we looked through the uses of it and tried to make the code more rvo friendly so to sayhowever we found a quirk in the g compiler where we did not understand what happenedplease consider the two implementations of operatorconst imaginary imaginaryoperatorconst imaginary rhs const imaginary tmpthis tmpappendrhs return tmpandconst imaginary imaginaryoperatorconst imaginary rhs const return imaginarythisappendrhsi have put printouts in the the various constructors and with the following little programint mainint argc char argv imaginary x1 1 imaginary y2 1 imaginary c x y return 0i get this print out with the first implementation of operatorintint ctorintint ctorcopy ctorand i get the following when the second variant of operator is in useintint ctorintint ctorcopy ctorcopy ctorhere we see that g is able to optimize away one call to the copy constructor in one case but not the latter and to my surprise it managed to do it with the more clumsy implementation where i saved it to a temporarynow i could have understood it more if it was the other way around but appearantly it is notand now i am hoping that maybe one you could enlighten me on this subjecti should probably add that when we add noelideconstructors as a flag to gi get the following print outintint ctorintint ctorcopy ctorcopy ctorcopy ctorregards mattias,['c++'] +191069,jquery mobile date picker is there someone out there that has a good date picker for jquery mobilei am going to let the user select a from date and a to date and i have not found anything good for this situationany ideas,['jquery'] +191071,compile boost 147 for windows ce there is actually a bit of information out there about people trying to build the boost libraries for windows ce but no one has reported success or even given the steps required to do so with the two latest releases 146 and 147 the release notes have mentioned that one of their test compilers was visual c windows mobile 5 with stlport 90 which seems to imply that success has been achieved as a side note the compiler given is interesting since the latest stlport i have been able to download is 521 am i missing somethingthe posts i have found seem to revolve around the file contained here the thing is i honestly do not know how to use it i was able to build stlport for windows ce but following the boost getting started guide 47 0moregetting startedwindowshtml i get stuck at the boostbuild stage do i need to configure at this point to compile for ce i just do not know what steps to take and would appreciate some guidancethese are the steps i have followed so farcompile stlport for windows ce documentation was pretty decent this did not prove too difficultinstall boostbuild according to getting started guide i am a little shaky on this step since the bootstrapbat file seems to be specific to ntx86 and ntx86 64 have i already screwed upat this point assuming i have done things correctly i need to run b2 with something likeb2 builddirbuilddirectory toolsettoolsetname buildtypecomplete stagei assume my build directory is the prefix i used for boostbuild the build type and stage will remain as given but i do not know what toolset name to use the veecoftc file has multiple entries for msvc and stlport i removed the two entries that did not relate to wm5 but when i compile with the following commandb2 builddircboostbuild toolsetmsvc buildtypecomplete stagei get a bunch of errors likecompilecc cboostbuildboostbinv2libsregexbuildmsvc90wm5stlport52debugthreadingmultihas icu testobjthe system cannot find the path specifiedindeed that file does not exist but has icu testobjrsp exists there am i missing something am i even on the right trackupdatesince i cannot get boostbuild to work and am getting no love on the boostbuild mailing list i have moved on to trying the cmake build system for boost i am using this in conjunction with cegcc i am much more familiar with linux than windows and i am running into the following errorboostconfigrequires threadshpp475 error error compiler threading support is not turned on please set the correct command line options for threading pthread linux pthreads solaris or mthreads mingw32mthreads is part of the c and cxx flags the problem is that boost platform config is not defined by boostconfigselect platform confighpp what should this be defined to for windows ce i figured it should be boostconfigplatformwin32hpp which would then define boost has winthreads which would solve the above error how can the release notes claim this works when select platform confighpp does not seem to handle windows ce cases if boost platform config does indeed need to be boostconfigplatformwin32hpp then i need to define either win32 win32 or win32 my first reaction is that none of these should be used for compiling for ce also the veecoftc file does not contain any of these how does it work,['c++'] +191076,testing sqlite database in robolectric i am trying to test a simple sqlite database using robolectric in my android application i am putting in some values but when reading them back 0 rows are returnedi am using the sqliteopenhelper class to access the database requestcache extends sqliteopenhelperrequestcache cache new requestcacheactivity sqlitedatabase db cachegetwritabledatabase write to dbcontentvalues values new contentvaluesvaluesputrequest timestamp test time valuesputrequest url test urldbinsertorthrowtable name null values read from db and compare values vectorrequest matchingrequests new vectorrequestdb cachegetreadabledatabasecursor cursor dbquerytable name search url return columns search url where new string url null null order by nullint id 0whilecursormovetonext long timestamp cursorgetlong0 request request new requestid requestseturlurl requestsetcreationtimestampnew datetimestamp matchingrequestsaddrequest assert that one row is returnedassertthatmatchingrequestssize equalto1 fails size returns 0when debugging the code outside robolectric this works as expected am i doing anything wrong or is it not possible to test sqlite databases using robolectric,['android'] +191096,datetime 25 years back from today in c how do you calculate date 25 years ago from today,['c#'] +191123,removing an object when collision happens iam still new to java and android programming and i am having so much trouble removing an object when collision happensi looked around the web and found that i should never handle removing box2d bodies during collision detection a contact listener and i should add my objects to an arraylist and set a variable in the user data section of the body to delete or not and handle the removing action in an update handlerso i did thisfirst i define two arraylists one for the faces and one for the bodiesarraylistsprite myfaces new arraylistspritearraylistbody mybodies new arraylistbodythen when i create a face and connect that face to its body i add them to their arraylists like thisface new animatedspritepx py pwidth pheight thismboxfacetextureregionbody boxbody physicsfactorycreateboxbodymphysicsworld face bodytypedynamicbody objectfixturedefmphysicsworldregisterphysicsconnectornew physicsconnectorface boxbody true truemyfacesaddfacemybodiesaddboxbodynow i add a contact listener and an update handler in the onloadscene like thisthismphysicsworldsetcontactlistenernew contactlistener private animatedsprite face2overridepublic void begincontactfinal contact pcontact overridepublic void endcontactfinal contact pcontact overridepublic void presolvecontact contactmanifold oldmanifold overridepublic void postsolvecontact contactcontactimpulse impulse sceneregisterupdatehandlernew iupdatehandler overridepublic void reset overridepublic void onupdatefinal float psecondselapsed my plan is to detect which two bodies collided in the contact listener by checking a variable from the user data section of the body get their numbers in the array list and finally use the update handler to remove these bodiesthe questions aream i using the arraylist correctly and in the collision listener how to retrieve the object that collided from the array listhow to add a variable to the user data the code pleasei tried removing a body in this update handler but it still throws me a nullpointerexception so what is the right way to add an update handler and where should i add itany other advices to do this would be greatthanks in advance,['android'] +191128,calling javascript object method using webbrowserdocumentinvokescript in my winforms application i need to call javascript function from my webbrowser control i used documentinvokescript and it works perfect with functions alone eg documentinvokescriptfunctionbut when i want to call javascript object method egdocumentinvokescriptobjmethodit does not work is there a way to make it work or different solution to this problem without changing anything in the javascript codethanks in advance,"['c#', 'javascript', '.net']" +191132,finding element nearest to clicked point need some help here i am a ui designer who is not good at numbers doing an experimental web form design and i need to know which input element is closest to a clicked point on a web page i know how to do nearest neighbor with points but the input elements are rectangles not points so i am stucki am using jquery i just need help with this little algo once i am done with my experiment i will show you guys what i am doingupdatei thought about how it can work look at this diagrameach rectangle has 8 points or rather 4 points and 4 lines which are significant only the x value is significant for horizontal points red dot and only the y value is significant for vertical points green dot both x and y are significant for the cornersorange crosses are the points to be measured against a mouse clicks in my use case the light purple lines are the thistances between the orange cross and it is possible nearest pointsoa for any given orange cross loop through each of the 8 points and every rectangle to find the nearest edge or corner closest of each rectangle to the orange cross the rectangle with the lowest value is the nearest onei can conceptualize and visualize it but cannot put it into code help,"['javascript', 'jquery']" +191148,whats the correct way to use stubs and mocks heres my exampletestmethodpublic void newaction should return indexaction newviewmodel viewmodel new newviewmodel name josa inacio santos silva email username joseinacio isuserregistered is used to validate username username is unique mockauthenticationservicesetupx xisuserregisteredviewmodelusername returnsfalse isuserregistered is used to validate email email is unique mockusuariorepositorysetupx xgetuserbyemailviewmodelemail mockdbcontextsetupx xsavechanges mockusuariorepositorysetupx xadditisanyuser usercontroller new usercontroller mockusuariorepositoryobject mockdbcontextobject mockauthenticationserviceobject actionresult result usercontrollernewviewmodel resultassertactionredirecttoactionindex mockauthenticationserviceverifyall mockusuariorepositoryverifyall mockdbcontextverifyalli have read some tutorials and they say that we should use only one mock per testbut look at my test it use 3 mocks to check if my action is working the right way i need to check these 3 mocks do not agreehow do i make this test in the correct way,"['c#', '.net']" +191189,c compiling for 3264 bit or for any cpu puzzler this question relates to these previous question on so any cpu question 1 and any cpu question 2i have a application which was originally built on win xp using visual studio 2005 do not laugh this app calls into our win32 c dll the c components which call the c dlls were built with the any cpu configuration and have been happily working on win xp without any issue we are now moving to win 7 and the release version of our app which was built on win xp with vc 2005 works fine however with the roll out of win 7 to our users we have now taken the opputunity to move to vs 2010 and i have built the c components on win 7 with vc 2010 but now when running this version i get lots unable to load abcdll where abcdll is our win32 c components i understand that recompiling the c assemblies with x86 config will solve the problem but what i do not understand is how the release version c assemblies built with winxpvisual studio 2005 any cpu config are able to run on win 7 without any issues surely these c assemblies built with any cpu should jit to 64 bit code when loaded in win 7 and cause badimageformatexception or other errors because they call win32 c dlls update i have some more information that have been requested in the comments belowon my windows 7 box i right click on my computer and look at the properties the system information says system type 64 bit operating system confirming this is a win64 osopening up the solution in vc2005 on windows xp when viewing the configuration manager for the solution i can confirm all the c projects are platform type any cpuwhen running the release build which was done on vc2005win xp on 64bit win 7 machine i task manager shows the image name as testexe 32 this confirms it is jit would and loaded into 32bit process,['c#'] +191208,using void in c i am confused about why we need to pass void into c functionsint fvoid return 0 versusint f return 0 what is the proper thing to do and why,['c'] +191212,whats the point of having hidden input in html what are common uses for this i do not see the benefit of having hidden input if you set the value of the hidden input why not just use that value at the point where you reference this hidden inputthere are reasons for this but i just do not know them,['html'] +191216,mysql database size estimation i have an application database with a table for users 1kbyte of data per user based on counting fields typelength and about 100 things of the same size belonging to a user 05 kbyte per thing and it is in a user table and a thing table that would seem to lead to about 51kbytes of data per user however i have heard that for mysql i should double it to cover index tables which would get me to 102kbytesuser is that true are there any other data expansion factors to consider for mysql or is 102 kbytes a good estimatebesides the indexing factor which i think is 2 and the storage efficiency which i also think is 2 are there any other multipliers for data storage in mysql,['mysql'] +191236,debugging template instantiations when doing metaprogramming using c templates is there a method that can be used sort of like a debugger to step through how the templates are being instantiated and complied it seems right now when creating a complicated network of templates there really is not a very good way of debugging them other than looking at the complier error messages to see how the templates are being instantiated if there are any compiler errors and the attempt to work backwards from the error messages if something unexpected is being generated i am not really sure if what i am looking for even exists as it would have to be something that is done at compile time but basically it would be a method sort of like stepping through code and examining the stack frame in gdb at runtime where the compiler could be stopped and the environment examined for the sequence by which a template or set of nested templates is being instantiatedfor instance let us say i created some simple code like the followingtemplatetypename t typename r voidstruct int return type templatetypename rstruct int return typeint r typedef r typetemplatetypename t typename r voidstruct float return type templatetypename rstruct float return typefloat r typedef r typetemplatetypename ttypename int return typettype test cout t type is int endltemplatetypename ttypename float return typettype test cout t type is float endlint main testint testfloat return 0i know this is relatively easy code to follow but templates can get quite a bit more involved especially when doing metaprogramming recursion etc i understand that the complier will issue error messages that can be used to deduce how templates are being instantiated but i am also wondering what can be done when the actual template code is correct in a syntactic sense but the runtime results are still incorrect it would be nice for instance to have a method to stop the compiler and see what test as well as int return type and float return type was being instantiated with or what instantiations were failingare the only options available right now for debugging templates with this level of granularity 1 the compiler error messages when the code is incorrect and 2 a combination of thisassemblers and debuggers to see what instantiated code was generated if the runtime results are incorrect or are there some other utilities out there that help with watching how templates are instantiated and seeinspect what code is generated by the compiler to investigate and debug template errors,['c++'] +191259,how define the variable type in pdostatementbindvalue the pdostatementbindvalue method offers a way to specify the type of the variable boundpdostatementbindvalue parameter value data type pdoparam str i am wondering whats the purpose of specifying the data type whereas when leaved as default param str eventually the database will anyway cast the value to the proper type before using itfor example if you have these queries over an integer fieldinsert into table integerfield values select from table where integerfield and you bind an integer in php pdo will by default bind it as a string which is equivalent asinsert into table integerfield values 1 select from table where integerfield 1 that will work flawlessly because the sql database at least mysql i am not really aware of how that would work on other rdbms knows how to convert the string back to an integer before using itwhat are the use cases where it would make a difference to bound typed parameters vs strings,"['php', 'sql']" +191269,android mobile user agent i am currently making an android application for a forum basically it just loads the website in a webview and that works fine and all but i am trying to add an option to view the full site or the mobile site i got it working by just making a boolean browsertype which when set to true loads the mobile site in the webview and when set to false loads the full page i already have it working and everything the full site loads and i jsut have the user agent as chrome and i set the mobile user agent to mobile but that does not work what am i supposed to use as the user agent for mobile just for reference this is the method i am usingmywebviewgetsettingssetuseragentstringchromethen for the mobile one instead of chrome i used mobile what is the correct user agent for mobile,['android'] +191318,groovy date parsing x is an illegal pattern character i have the following date string 20110906t2202570400 the problem is the timezone 0400 the java7 docs say i can use x to magically match this timezone string the problem is that groovy does not support the x character presumably because it is not using jdk7 yet the z character does not work because it is not gmt0700 only 0700 what is the easiest way to parse this timezonetjw,['java'] +191369,how do i get the name of a day of the week in the users locale i have a number between 1 and 7 which i want to turn into the users locales equivalent of monday to sunday can i do that and if so how,"['objective-c', 'ios']" +191408,how to store image as blob in sqlite how to retrieve it i want to store an imagefrom url into a sqlite databasefor that i use db new databasegetapplicationcontexturl url new url teampngurlconnection ucon urlopenconnectioninputstream is ucongetinputstreambufferedinputstream bis new bufferedinputstreamis128bytearraybuffer barb new bytearraybuffer128int current 0while current bisread 1 barbappendbyte currentcontentvalues filedata new contentvaluesfiledataputdatabaseimg srcbarbtobytearraydbinsertdatabasetable img null filedatain the insertpublic void insertstring tableimg object object contentvalues datatoinsert todo autogenerated method stub string sql insert into tableimg idimg src values 1datatoinsert dbexecsqlsqlfor the retrieval of imagecursor cursor dbselectdatatoshowdatabasetable img databaseimg srcbyte imagebytearraycursorgetblobcursorgetcolumnindexdatabaseimg src cursorclosebytearrayinputstream imagestream new bytearrayinputstreamimagebytearraybitmap theimage bitmapfactorydecodestreamimagestreamsystemoutprintln theimageso here i got nulland in my database the value of image stored as imageb43e5ac48,['android'] +191452,maven deploys to snapshot instead of release i am trying to release a project using maven but instead of releasing to the releases repository it puts it in our snapshots repomy pom looks likeproject xmlns xmlnsxsi xsischemalocation 0 0xsdmodelversion400modelversiongroupidcomexamplemyprofilergroupidartifactidprofilerlibartifactidnameprofiler libnameversion102snapshotversiondescriptionprofiler librarydescriptionscm connectionscmsvn connection developerconnectionscmsvn developerconnectionscmthistributionmanagement publish the versioned releases here repository idnexusid namenexusname url url repository publish the versioned releases here snapshotrepository idnexusid namenexusname url url snapshotrepositorythistributionmanagement download artifacts from this repo repositories repository idnexusid nameexample public repositoryname urlurl releases enabledtrueenabled releases snapshots enabledtrueenabled snapshots repositoryrepositoriesdependencies dependenciesbuild finalnameprojectartifactidfinalname plugins plugin artifactidmavenreleasepluginartifactid configuration tagbase tagbase configuration plugin plugin artifactidmavencompilerpluginartifactid configuration source16source target16target configuration plugin pluginsbuildproperties projectbuildsourceencodingutf8projectbuildsourceencoding powermockversion146powermockversionpropertiesproject,['java'] +191484,how can i monitorlog tomcats thread pool i have a tomcat installation where i suspect the thread pool may be decreasing over time due to threads not being properly released i get an error in catalinaout when maxthreads is reached but i would like to log the number of threads in use to a file every five minutes so i can verify this hypothesis would anyone please be able to advise how this can be be donealso in this installation there is no tomcat manager it appears whoever did the original installation deleted the manager webapp for some reason i am not sure if manager would be able to do the above or if i can reinstall it without damaging the existing installation all i really want to do is keep track of the thread poolalso i noticed that maxthreads for tomcat is 200 but the max number of concurrent connections for apache is lower apache is using mod proxy and mod proxy ajp ajp 13 to feed tomcat that seems wrong too what is the correct relationship between these numbersany help much appreciated dupdate just a quick update to say the direct jmx access worked however i also had to set dcomsunmanagementjmxremotehost i set it to localhost and it worked however without it no dice if anyone else has a similar problem trying to enable jmx i recommend you set this value also even if you are connecting from the local machine seems it is required with some versions of tomcatjust a quick update to say the direct jmx access worked however i also had to set dcomsunmanagementjmxremotehost i set it to localhost and it worked however without it no dice if anyone else has a similar problem trying to enable jmx i recommend you set this value also even if you are connecting from the local machine seems it is required with some versions of tomcat,['java'] +191499,is there any 3d visualization library or toolkit for c no c please basically i am interested in knowing if there exists any opengl 3d visualization toolkit for c for scientific uses,['c'] +191501,bad design decision to throw an exception from an accessor i have read some answers re the pros and cons of throwing an exception within an accessor but i thought i would broach my specific question with an examplepublic class app static class test private liststring strings public test public liststring getstrings throws exception if thisstrings null throw new exception return strings public void setstringsliststring strings thisstrings strings public static void mainstring args test t new test liststring s null try s tgetstrings catch exception e todo do something more specific getstrings is throwing an exception when strings has not been set would this situation be better handled by a method,['java'] +191507,get path to subdirectory in resources folder i am trying to get an array of all png files in a subdirectory of the resources folderin my apps resources folder i have created a folder named images this folder holds all the pngfiles i need to thisplaythis is the way i tried to get the path nsstring imagepath nsstring stringwithformatnsbundle mainbundle bundlepathimagesnslogpath to images imagepathnsarray paths nsbundle pathsforresourcesoftype png indirectoryimagepathnsmutablearray allimagenames nsmutablearray alloc initfor nsstring path in paths if path lastpathcomponent hasprefix aq continue allimagenames addobject path lastpathcomponentthis way i get a path like aappnameappimagesbut if i try to do it that way the array is always empty what am i doing wronggreetzzarak,['ios'] +191544,how to post a django form with ajax jquery i have checked out tons of tutorials for django ajax forms but each one of them tells you one way of doing it none of them is simple and i am a bit confused since i have never worked with ajaxi have a model called note a modelform for it and inside the template i need that everytime a note element sends the stop signal from jquery sortables django updates the objectmy current codeviewspydef save noterequest space name saves the note content and position within the table place get object or 404space urlspace name note form noteformrequestpost or none if requestmethod post and requestis ajax msg the operation has been received correctly print requestpost else msg get petitions are not allowed for this view return httpresponsemsgjavascriptfunction savenotenoteobj savenotenoteobj saves the notes making an ajax call to django this function is meant to be used with a sortable stop event arguments noteobj note object var noteid noteobjattrid postsave note noteid noteid phase example phase parent noteidparenttdattrid title noteid textareaval message blablbla the current code gets the data from the template and prints it in the terminal i do not know how i can manipulate this data i have seen some people manages the data through jqueryforms to send the data to djangohow can i access the data sent by ajax and update the note object,"['javascript', 'jquery']" +191553,missing table when running django unittest with sqlite3 i am trying to run a unittest with django 13 normally i use mysql as my database backend but since this is painfully slow to spinup for a single unittest i am using sqlite3so to switch to sqlite3 just for my unittests in my settingspy i haveimport sysif test in sysargv databases default engine djangodbbackendssqlite3 nametmpdatabasedb user password host when i run my unittest with python managepy test myapptesttest myfunc i get the errordatabaseerror no such table django content typegoogling shows there are a few of possible reasons for this error none of which seem applicable to me i am not running apache so i do not see how permissions would be an issue the file tmpdatabasedb is being created so tmp is writable the app djangocontribcontenttypes is included in my installed appswhat am i missingedit i ran into this problem again in django 15 but none of the proposed solutions work,['python'] +191573,abstract classes and spring mvc modelattributerequestparam i have a hierarchy of model classes in my springhibernate applicationwhen submitting a post form to a spring mvc controller is there any standard way of specifying the type of the object being submitted so spring can instantiate the correct subclass of the type declared in the receiving methods modelattribute or requestparamfor examplepublic abstract class product public class album extends product public class single extends product meanwhile in the controllerrequestmappingsubmithtmlpublic modelandview addproductmodelattributeproduct valid product product bindingresult bindingresult model modeldo stuff and get either an album or singlejackson can deserialize json as a specific subtype using the jsontypeinfo annotation i am hoping spring can do the same,['java'] +191575,apache is stringutilsisblankstr vs guavas stringsisnulloremptystr should you routinely check for whitespace is there any advantage in using stringutilsisblankstr from apache commonslangvs stringsisnulloremptystring stringfrom google guavai want to replace hundreds of cases of they following usage in a java projectifstr null strisemptyguavas isnullorempty seems to be a direct replacement for the usage above in my projectbut more people seem to use apache is isblank method based on my reading of so questionsthe only difference seems to be that stringutilsisblankstr also checks for whitespace in addition to checking whether the string is null or emptynormally is it a good idea to check a string for whitespace or could that produce a different result in your code than guavas simpler check,['java'] +191576,horizontal scroll mobile swipe can anyone please recommend the best way to trigger a horizontal jquery scroller using swipe gesturewe have a working web version which we would like to implement onto our android site but dont know the best way to approach thiswe basically want to use a scrolling list similar to these examples triggered via swipe gestureany advice or alternate versions gratefully receivedcheerspaul,['jquery'] +191590,how to detect focusin support thanks to perfection kills we can use the following javascript to detect event supportfunction haseventev var elem documentcreateelementa type on ev supported elemtype undefined if supported elemsetattributetype return supported typeof elemtype function elem null return supportedthis works for about the only time i need it detecting mouseenter support haseventmouseenter will return false in chrome firefox etc as it shouldbut now i am trying to fix browsers that do not support the focusin and focusout events according to ppk that is basically just firefox unfortunately chrome and safari are listed as having incomplete support for the following reasonsafari and chrome fire these events only with addeventlistener not with traditional registrationin general that is fine i would only be using addeventlistener anyway it does mean however that detecting support via elemonfocusin undefined would not work i tested it out and it is truepdo i support a hreffocusinapscriptvar elem documentgetelementsbytagnamep0 hasevent method defined herefunction listener var response haseventfocusin yes no alertresponseelemaddeventlistenerfocusin listener falsescriptthe above alerts no in chrome is there any way to detect whether the browser supports focusin without using browser sniffing,['javascript'] +191602,why is ilist not deferred execution as i understand it ienumerable and iqueryable are deferred execution why wouldnt it be of benefit for ilist to also support deferred execution,['c#'] +191622,how to filter out iframes in an addon sdk extension the main problem is that my extension is loading into every iframes on a target webpage it puts buttons that appear inside the iframes as well i want them to thisappear the window and document objects are shown as the parents window and document objects so it is impossible to check the document location for example because it shows the parents location instead of the iframes location,['javascript'] +191641,object file format unrecognized invalid or unsuitable xcode error i do not see any reasons why this message should come at the end of the logusersvallibrarydeveloperxcodederiveddatamathematicsdzakmzlewrmgvibasvuixiwmkwwpbuildproductsdebugiphoneosmathematicsapp object file format unrecognized invalid or unsuitablecommand usrbincodesign failed with exit code 1 how can i fix this errori am desperate all my certificates and profiles are valid the app itself has no bugs at all,"['iphone', 'objective-c', 'ios']" +191666,a tag as a submit button hi i am trying to get a tag as a submit button i found a code somewhere in the web but it did not worka href onclickthisformsubmitsubmitais there any code for to achieve my need,['html'] +191688,email processing with nodejs i am writing a node application which among other things needs to receive email and process it so that it can be rendered in a web page as happens in web mail list archives etc i have got the receiving part covered with haraka from there to storing the received emails in mongo is easy and so long as they are plain text i can thisplay themthe part i am missing is handling the rather involved varieties of ways in which email content can come including alternatives html attachments inlined images and much more that is a rather steep amount of functionality to have to put together and i cannot seem to find a js library that will do it for me given the number of libraries out there and the speed at which new ones are added it might just be that i have missed it a so pointers welcomeand failing that if i were to port an existing library for this over from another language which ones would you recommend i look atthanks,['javascript'] +191708,putting hypertext link to external internet site inside javadoc i want my javadoc to reference a dev manual that is on my intranet i would like to know how to do this i tried using see link but this just produced and not a hypertext link let us say i wanted to point to some wiki page inside the javadoc how can i do this i am just trying to have link to external website so i want something like example as hypertext link and it points to a full url to website,['java'] +191717,using the task parallel library on an eventbased asynchronous pattern i am writing a networked applicationmessages are sent over the transport as suchnetworksendmessage new firstmessage i can register an event handler to be called when this message type arrives like sonetworkregistermessagehandlerfirstmessage onfirstmessagereceivedand the event gets firedpublic void onfirstmessagereceivedeventargsfirstmessageeventargs ei am writing a custom authentication procedure for my networked application which requires around five messages to completewithout using the task parallel library i would be forced to code the next step of each procedure in the preceding event handler like sopublic void onfirstmessagereceivedeventargsfirstmessageeventargs e networksendmessage new secondmessage public void onsecondmessagereceivedeventargssecondmessageeventargs e networksendmessage new thirdmessage public void onthirdmessagereceivedeventargsthirdmessageeventargs e networksendmessage new fourthmessage public void onfourthmessagereceivedeventargsfourthmessageeventargs e authentication is completei do not like the idea of jumping around the source code to code a portion of this and a portion of that it is hard to understand and editi hear the task parallel library substantially simplifies this solutionhowever many of the examples i read using the task parallel library were related to starting a chain of active tasks what i mean by active is that each task could start when called explicitly like sopublic void drink public void eat public void sleep taskfactorystartnew drink continuewith eat continuewith sleep this is opposite from my eventbased async pattern in which each event handler method is called only when the message is receivedin other words i cannot do something like this but i want totaskfactorystartnew onfirstmessagereceived continuewith onsecondmessagereceived continuewith onthirdmessagereceived continuewith onfourthmessagereceived i have read this article but i do not quite understand it it seems like what i need has to do with taskcompletionsource if i wanted to make a task from my eventbased async pattern like the code block above what would it look like,['c#'] +191720,how can i use linq to project this parent and children object model into a flat single object i am trying to flatten out a simple class that has a parent child array into a single classfrompublic class foo public int id get set public string name get set public icollectionpewpew pewpews get set public class pewpew public string name get set public string whatever get set 1 fred a x b y 2 bill c z topublic class fooprojection public int id get set public string name get set public pewpewname get set public pewpewwhatever get set 1 fred a x 1 fred b y 2 bill c z,"['c#', '.net']" +191772,detecting if filemove will require copy delete or just alter location in the file system table thisclaimeri will admit straight away i have a fair amount of ignorance regarding the details on how file systems function i have been using ntfs for so long that i can extrapolate what is going on based on behaviors i have witnessed as well as whatever i have learned from dorking on the internet howeveri was hoping that there is a way to detect if when moving a file from location a to location b whether the operation will require the equivalent of filecopy filedelete or if it will not copy the actual file data but just update the location in the master file table or the likefor various purposes i sometimes move large numbers of large files i like to report progress in the ui i realize that when i call filemove and move a file from a location on one thiskpartition to another that the function will effectively have to copy file data delete between the thisks partitions when it encounters this situation i want to be able to detect that this will happen so i can use code i have authored that will copy the file and give detailed progress reporting as bytes are transferred so i can update progress bars in the ui frequently when it is on the same thiskpartition as updating the location in the master file table is so fast i simply update the progress bar when the filemove function completes for each file i am batch movingusing net 4 c is it possible to detect through other means whether calling the filemove will require an equivalent copy delete operation or will simply update a file table and not copy the file dataeditas i note in comments below possibilities on how i thought this might be done would be to detect if a given source file location and destination file location are located on the same physical thisk partition and if so would this mean i could accurately anticipate the behavior and decide what functions to call the built in filemove function for the near instant update file system table that i believe occurs when moving to same thiskpart or my more detailed report progress every x bytes copied custom file copy code file transfer speeds can vary greatly on the machines my programs will run on so i like to be able to report detailed progress present transfer speed when possiblenote the program may be using network unc paths which can be using different physical thisks with the same root path ie somenamesharesworkfolderproject may be on a different physical thisk then somenamesharesworkfoldderotherproject so i would need a method for detecting the partition id or physical thisk id to see if a source and destination folder on on the same thiskpartitionthank you,['c#'] +191783,maximum length of formsauthenticationticketuserdata property i am implementing a custom identity class for an aspnet 40 site with forms authentication based on this tutorialforms authentication configuration and advanced topicsi would like to store extra user information firstlast name gender geographic region profile picture thumbnail filename etc in the authcookie there is a warning on msdnmicrosoftcom about limiting the size of the userdata propertyi have not been able to find a definitive character limit for the userdata property only that the entire encrypted cookie should be under 4096 bytesanybody know a maximum character limit i should assume in my code or have a better idea about how to store these frequently needed pieces of user informationthanks,"['c#', 'asp.net']" +191788,jquery selector contains to equals i have the folowing selector var likecomperssionoption selectidcomparisiontypeeq0 findoptioncontainslikethis checks for an option which contains the word like righthow do i find an option which is exactly with the word likesomthing like this var likecomperssionoption selectidcomparisiontypeeq0 findoptionequalslike,"['javascript', 'jquery']" +191836,c default implementation for and operators for objects i would like to know what is default implementation for equality operatort and is itpublic static bool operator object obj1 object obj2 return obj1equalsobj2public static bool operator object obj1 object obj2 return obj1equalsobj2so i only need to override equals method or do i need to override euality operators as well,"['c#', '.net']" +191854,problem using opencv231 with android native activity i am developing a computer vision application for android that work involves getting camera frames as fast as possible so i am trying to build a android application directly in c using android native app glue and libnative camera to get camera framesit seems to be incompatiblei tested out 2 options i tried to use opencv on the android ndk sample nativeactivity just make the few necessary changes convert sample to c modify androidmk y applicationmk and including using namespaces and includes it gives the following errorsharedlibrary libnativeactivitysocdevelopmentandroidopencvwspsamplesnativeactivityobjlocalarmeabiv7aobjsnativeactivitymaino in function matcdevelopmentandroidopencvwspsamplesnativeactivityopencv231shareopencvincludeopencv2coremathpp297 undefined reference tocvfastfreevoidand so oni tried to import the necessary libraries to make a native activity on the opencv231 tutorial 3 sample i simply modified the androidmk and addedlocal static libraries android native app glueimmediately when i add this line i get the following errorsharedlibrary libnative samplesocdevelopmentandroidopencvwspsamplestutorial3nativeobjlocalarmeabiv7aobjsnative samplejni parto in function matcdevelopmentandroidopencvwspsamplestutorial3nativeopencv231shareopencvincludeopencv2coremathpp297 undefined reference tocvfastfreevoidand so onplease has anyone tested a purely native activity with opencv231 and libnative camera to get camera framesthanks in advance,['android'] +191862,difference between preferences oncreateview and onbindview methods what is the difference between oncreateview and onbindview methods in preferencein documentation it says that onbindviewbinds the created view to the data for this preference this is a good place to grab references to custom views in the layout and set properties on themwhy is it such a good place to set properties on views in my layout currently i am setting properties in oncreateview method and everything seems to work finefrom my experience it looks like both methods are always called together maybe there are some situations when only onbindview is called,['android'] +191866,how to delete a file such that the delete is irreversable i want to delete a sensitive file using c in a way that the file will not be recoverablei was thinking of simply rewriting over the file and then delete it is it enough or do i have to perform more actions,['c++'] +191868,strategy advice for advanced rails debugging i have been coding in rubyrails for almost 9 months now having spent years before that in pythonwhile i am really enjoying rails there is one area where i often find myself frustrated chasing down stubborn bugs in other languages i can almost always track down difficulties without too much trouble but when i hit a wall debugging rails i tend to really hit a wall i guess what i am asking is what strategies do advanced rails users employ to track down more stubborn errors at the moment my approach is usuallyexamine the stack trace most simple bugs solved hererun debuggerpryconsole examine the environment pace through each step if necessarygoogle itpost on stack overflowgithub issuesprocrastinate andor swear profuselyif any advanced railsers would share their strategy for chasing down more stubborn bugs i would be really appreciative in short what do yo do when tracedebugger do not offer any clues,['ruby-on-rails'] +191891,bind json properties to a form i have a json object and a form if the json object has a property whose name matches the name of a form input i want the input to dsiplay the value of this property is there a simple way to do this with jqueryvar json foo foo bar bardef form myform something magical that assigns json property values to form inputs with matching namesthe form in question looks something likeform id myform actionfoobar input namefoo input namebarform,"['javascript', 'jquery']" +191908,android why setvisibilityviewgone or setvisibilityviewinvisible do not work i want my datepicker and the button to be invisible in the begining and when i press my magic button i want to setvisibilityviewvisiblethe problem here is when i setvisibilityviewgone or setvisibilityviewinvisible nothing changes and the component is still visiblefinal datepicker dp2 datepicker findviewbyidriddatepick2final button btn2 button findviewbyidridbtndate2dp2setvisibilityviewgonedp2setvisibilityviewinvisiblebtn2setvisibilityviewgonebtn2setvisibilityviewinvisiblebtn2setonclicklistenernew viewonclicklistener public void onclickview arg0 textview txt2 textview findviewbyidridtxt2 txt2settextyou selected dp2getdayofmonth dp2getmonth 1 dp2getyear,['android'] +191955,orghibernateannotationexception onetoone or manytoone on references an unknown entity i am receiving the following hibernate exceptionorghibernateannotationexception onetoone or manytoone on czrohanduspsmodelswitchportkonfiguracnitemplateaccess references an unknown entity czrohanduspsmodelkonfiguracnitemplate orghibernatecfgtoonefksecondpassdosecondpasstoonefksecondpassjava103 orghibernatecfgannotationconfigurationprocessendofqueueannotationconfigurationjava541 orghibernatecfgannotationconfigurationprocessfksecondpassinorderannotationconfigurationjava523 orghibernatecfgannotationconfigurationsecondpasscompileannotationconfigurationjava380 orghibernatecfgconfigurationbuildsessionfactoryconfigurationjava1377 orghibernatecfgannotationconfigurationbuildsessionfactoryannotationconfigurationjava954 czrohanduspshelpersessionfactoryhelperinitfactorysessionfactoryhelperjava122 czrohanduspshelpersessionfactoryhelpergetsessionfactorysessionfactoryhelperjava134 czrohanduspsfilterhistoriezmenfilterdofilterhistoriezmenfilterjava102 czrohanduspsfiltercharsetfilterdofiltercharsetfilterjava41after 20 hours spent on the problem with various people having read every possible blog or forum i am really getting desperate herethis is a midsized project i should mention the database is postgres 91 and we generate the db using a modelling tool hibernate connects to the database but does not generate iti have created a new entity in the database it is called konfiguracnitemplate configuration template i have created the model controller form validators jsps all basically copied 11 from an existing entity of a similar nature i can now work with konfiguracnitemplate crud is fully workingthe problem comes when i reference this konfiguracnitemplate from the entity called switchport in the db there is a relation between the twoswitchport 11 0n konfiguracnitemplate switchport always references a konfiguracnitemplate a konfiguracnitemplate may be referenced zero or more timesswitchport has fk konfiguracnitemplateaccess id for this relationin modelswitchportjava the relation is mapped just like all other relations that are workingmanytoonejoincolumnnullable falseprivate konfiguracnitemplate konfiguracnitemplateaccessi have tried various formsmanytoonejoincolumnnamekonfiguracnitemplateaccess id nullable falseprivate konfiguracnitemplate konfiguracnitemplateaccessormanytoonetargetentitykonfiguracnitemplateclassjoincolumnnamekonfiguracnitemplateaccess id nullable falseprivate konfiguracnitemplate konfiguracnitemplateaccessi have also checkedboth entities are in the same packagethey are both annotated entity using import javaxpersistenceentitythe build produces no errorwarning messagesas long as the reference in switchport is commented out everything is fineno matter what i try i cannot get rid of the references an unknown entity exception can somebody please share an idea what is happening or maybe how to debug the issue the stacktrace at the top of the post is all i get in the logsall input is greatly appreciated,['java'] +191981,how to pass parameter to click event in jquery i want to change the following js to jquery but i do not know how to pass parameter to click event in jquery can anyone help me thanksscript typetextjavascriptfunction thisplayid alertthe id is id scriptinput idbtn typebutton valueclick onclickthisplaythisid,['jquery'] +191989,control a print format when printing a list in python i have a list with floating point number named a when i print the list with print a i get the result as follows8364 037 009303 70849 0469 0303 9469 028603 022901 9414 098601 0534 215305can i tell the list printer to print the format of 53f to get better result8364 037 0093 7084 0469 0303 9469 0286 0229 9414 0986 0534 2153,['python'] +192002,what does return thiseach do in jquery i am looking at a jquery plugin which has a single function after setting up the appropriate defaults though a constructor argument the function defines a couple of helper functions and then as the last part returns a call to thiseach like soreturn thiseachfunction long method defined herei understand the use of thiseach in modifying matching dom elements and such but what does the return statement accomplish some sort of array of modified dom elements which can then be chained in other calls i have read about thiseach on this site but i cannot quite figure what the return does here thanks for helping clear this up,['jquery'] +192016,list of const int instead of enum i started working on a large c code base and found the use of a static class with several const ints fields this class is acting exactly like an enum wouldi would like to convert the class to an actual enum but the powers that be said no the main reason i would like to convert it is so that i could have the enum as the data type instead of int this would help a lot with readabilityis there any reason to not use enums and to use const ints insteadthis is currently how the code ispublic int fielda get set public int fieldb get set public static class ids public const int itema 1 public const int itemb 2 public const int itemc 3 public const int itemd 4 public const int iteme 5 public const int itemf 6however i think it should be the following insteadpublic ids fielda get set public ids fieldb get set,['c#'] +192020,how to plot 1d data at given yvalue with pylab i want to plot the data points that are in a 1d array just along the horizontal axis edit at a given yvalue like in this plothow can i do this with pylab,['python'] +192039,how do extract text layer and background layer from pdf in my project i have to do a pdf viewer in html5css3 and the application has to allow user to add comments and annotation actually i have to do something very similar to crocodoccomat the beginning i was thinking to create images from the pdf and allow user create area and post comments associates to this area unfortunately the client wants also navigate in this pdf and add only comments on allowed sections for example paragraphs or selected textand now i am in front of one problem that is to get the text and the best way to do it if any body has some clues how i can reach it i would appreciatei tried pdftohtml but output does not look like the original document whom is really complex example of document even this one does not reflect really the output but is much better than pdftohtmli am open to any solutions with preference for command line under linux,['php'] +192053,synchronous rpc calls in gwt that title alone should cause people to come out of the woodwork to bash me with clubs but hear me outi have a use case where i need to return a value from a asynchronous call i am using gwtplatform but the concepts are the same i declared a final javascriptobject array then assigned the value within the asynccallback however i need to return the value and the method returns before the asynccallback completes therefore i need to block somehow until the asynccallback completes i need the returned value in another method or i would just do what i need to in onsuccessi have tried loops timers and a few other methods with no luck can anyone helpoverridepublic javascriptobject dogetwhereamimarkerfinal double lng final double lat final javascriptobject markerarray new javascriptobject1 ugly hack i know thispatchexecutenew getlocationdescriptionsactionlng lat new asynccallbackgetlocationdescriptionsresult override public void onfailurethrowable caught caughtprintstacktrace override public void onsuccessgetlocationdescriptionsresult result mapstring location resultmap resultgetresult stringbuffer message new stringbuffer for string key resultmapkeyset messageappendkeyappend appendresultmapgetkeyappendn map tempmap new hashmap tempmapputtitlelocation information tempmapputlat lat tempmapputlng lng tempmapputcontents messagetostring javascriptobject marker googlemaputilcreatemarkertempmap markerarray0 marker if markerarray0 null gwtlogmarker array updated return markerarray0update as requested here is the code that calls dogetwhereiammarker i have tried having a separate native method with the google map object as a javascriptobject as a parameter but it appears that passing that object between native methods kills the ability to update said objectpublic native void initmapjavascriptobject mapoptions javascriptobject bounds javascriptobject border jsarray markerarray element e create the map and fit it within the given bounds map new wndgooglemapsmape mapoptions if bounds null mapfitboundsbounds set the polygon for the borders if border null bordersetmapmap set up the info windows if markerarray null markerarraylength 0 var infowindow new wndgooglemapsinfowindow contentinfowindow content goes here for var i 0 i markerarraylength i var marker markerarrayi markersetmapmap wndgooglemapseventaddlistenermarker click function infowindowsetcontentmarkercontent infowindowopenmap this need to reference the calling class inside the function so set a reference to this var that this wndwhereamifunctionlng lat whereamiddlnglat wndgooglemapseventaddlistenermap click functionevent var lat eventlatlnglat var lng eventlatlnglng wndwhereamilng lat,['java'] +192055,css google fonts italics getting stretched in ie i have a question about google fonts i am using the font lato from google fonts and it appears to be working perfect in firefox chrome ie9 but in ie 7 and 8 the italic version looks real stretchedi am not doing anything too crazy just using fontstyleitalic fontweight700and including the font usinglink href relstylesheet typetextcssis this a known problem with google fonts or is it something i am doing wrongthanks,['css'] +192063,wcf named pipe minimal example i am looking for minimal example of wcf named pipes i expect two minimal applications server and client which can communicate via a named pipemicrosoft has the briliant article getting started tutorial that describes wcf via http and i am looking for something similar about wcf and named pipesi have found several posts in the internet but they are a little bit advanced i need something minimal only mandatory functionality so i can add my code and get the application workinghow do i replace that to use a named pipeendpoint addresshttplocalhost80servicemodelsamplesservicecalculatorservice bindingwshttpbinding bindingconfigurationwshttpbinding icalculator contracticalculator namewshttpbinding icalculator identity userprincipalname valueolegpcoleg identityendpointhow do i replace that to use a named pipe step 1 of the address configuration procedure create a uri to serve as the base addressuri baseaddress new urihttplocalhost80servicemodelsamplesservice step 2 of the hosting procedure create servicehostservicehost selfhost new servicehosttypeofcalculatorservice baseaddresstry step 3 of the hosting procedure add a service endpoint selfhostaddserviceendpoint typeoficalculator new wshttpbinding calculatorservice step 4 of the hosting procedure enable metadata exchange servicemetadatabehavior smb new servicemetadatabehavior smbhttpgetenabled true selfhostdescriptionbehaviorsaddsmb step 5 of the hosting procedure start and then stop the service selfhostopen consolewritelinethe service is ready consolewritelinepress enter to terminate service consolewriteline consolereadline close the servicehostbase to shutdown the service selfhostclosecatch communicationexception ce consolewritelinean exception occurred 0 cemessage selfhostaborthow do i generate a client to use a named pipe,['c#'] +192090,is there a way to refer to the current type with a type variable suppose i am trying to write a function to return an instance of the current type is there a way to make t refer to the exact subtype so t should refer to b in class bclass a t extends a fooclass b extends a override t foo,['java'] +192119,php fopen fails on files even with wideopen permissions i am currently migrating my lamp from my windows server to a vps running debian 6 most everything is working however one of the php scripts was failing to write to its configured log file i could not determine why so i wrote a new simple contrived php script to test the problemphp ini setthisplay errors 1 error reportinge all echo execwhoami log fopenvarlogapache2writetestwritetestlog a if log null fflushlog fcloselog log null however it fails with the resultwdata warning fopenvarlogapache2writetestwritetestlog failed to open stream permission denied in varw adminphpwritetestphp on line 5 while i would never do it normally to help diagnose i set varlogapache2writetestwritetestlog to chmod 7 both the directory and the file are owned by wdatawdata the file was created with touchi ran strace to verify which process was performing the openpid 21931 lstatvarlogapache2writetestwritetestlog 0x7f81677d30 1 eacces permission deniedpid 21931 lstatvarlogapache2writetest 0x7f81677b90 1 eacces permission deniedpid 21931 openvarlogapache2writetestwritetestlog o rdwro creato trunc 06 1 eacces permission deniedi checked and pid 21931 was indeed one of the apache2 child processes running under wdata as you can see i also included echo execwhoami in the script which confirmed the script was being run by wdataother notesphp is not running in safe modephp open basedir is not setversion info apache2216 debian php5337squeeze3 with suhosinpatch mod ssl2216 openssl098ouname a 2632238191el5028stab0922 1 smp thu jul 21 192322 msd 2011 x86 64 gnulinuxthis is on a vps running under openvzls l file rwxrwxrwx 1 wdata wdata 0 sep 8 1813 writetestlogls l directory drwxrxrx 2 wdata wdata 4096 sep 8 1813 writetestapache2s parent process runs under root and the child processes under wdataselinux is not installed thanks to fabio for reminding me to mention thisi have restarted apache many times and rebooted the server as well,['php'] +192257,sms sending through free gateway please guide me with sample code for sending sms through website how to include sms gateway please tell me can i use way2smscom as gatewayis it the right way to use please suggest me only this much of code worksphperror reportinge allob implicit flushtrueinclude once classcurlphpinclude once clasmsphpsmsappnew smssmsappsetgatewayway2sms echo logging in smsapplogin10 digit numberway2sms passwordecho sending sms resultsmsappsendreceipient numbertext messageifresulttrue echo message sentelse echo error encountered smsappgetlasterrorhere is my classcurlphpphpclass sms var username var password var curl var server var logindone var debugmode var data var error public function construct thiscurlnew curl thiscurlsetproxy thislogindonefalse thisdebugmodefalse thisdataarray public function setgatewayservername switchservername case 160by2 thisserver160by2 break case way2sms thisserverway2sms break case airtel thisserverairtel break default thisserverway2sms public function loginusernamepassword serverthisserver call user funcarraythislogin serverusernamepassword thislogindonetrue public function sendnumbermsg serverthisserver ifthislogindone return call user funcarraythissend servernumbermsg else echo h2please login first before sending smsh2 private function login way2smsusernamepassword outthiscurlpost11 patternlocationn preg matchpatternoutmatches domaintrimmatches1 thisdatadomaindomain out thiscurlpostdomainauthclusernameusernamepasswordpasswordsubmitsignin patternlocationn preg matchpatternoutmatches referertrimmatches1 thisdatarefererreferer private function send way2smsnumbermsg domainthisdatadomain htmlthiscurlpostdomainjspinstantsmsjspval011thisdatareferer ifthisdebugmode echo h2after logging in the html returned by server ish2 echo html pattern nameactionvalue preg matchpattern html matches custfrommatches1 msgurlencodemsg htmlthiscurlpostdomainfirstservletsmscustidcustidundefinedhiddenactioninstantsmsactioncustfromloginpassmobnonumbertextareamsg pattern clastyle1span preg matchpattern html matches outmatches1 ifpreg matchsuccessfullyout thisseterrorout return false else return true thisseterrorno errors public function getlasterror return thiserror private function seterrorerror thiserrorerror private function login 160by2usernamepassword out2thiscurlget outthiscurlposttxt msgmnotxtusernameusernametxtpasswdpasswordremembermeyescmdsubmitlogin patternmymenuaspmsg preg matchpatternoutmatches idtrimmatches1 thisdataidid private function send 160by2numbermsg msgurlencodemsg idthisdataid out1thiscurlposttxt mobilenonumbertxt msgmsgcmdsendsendsmstidt msgidmsgid echo out1 pattern tabletables preg matchpattern out1 matches outstrip tagsmatches1 ifcountmatches1 patterndivbackgroundyellowdivs preg matchpatternout1matches outstrip tagsmatches1 echo out is out ifpreg matchsuccessfullyiout thisseterrorout return false else return true thisseterrorno errors private function login airtelusernamepassword thisdatausernameusername thisdatapasswordpassword private function send airtelnumbermsg in the place of username and password which username and password i should use,['php'] +192272,what are the differences between redrawwindow and updatewindow in win32 what are the differences between redrawwindow and updatewindow in win32since they seem to have the same purpose to refresh a window what are the differences,['c++'] +192274,connectiontimeout versus sockettimeout im having a problem with a library i am using it might be the library or it might be me using it wrongbasically when i do this timeout in milliseconds ignitedhttpsetconnectiontimeout1 v short ignitedhttpsetsockettimeout60 60 secondsno timeout exception is generated works ok however when i do this ignitedhttpsetconnectiontimeout60 60 seconds ignitedhttpsetsockettimeout1 v shorti get a socket exceptionso my question is why can i not simulate a connection exception am i misunderstanding the difference between a socket and a connection timeout the library is here not officially realsed yet,"['java', 'android']" +192280,c datetime how to check time part is null is there any easy way to check to see if the time part of the datetime value is null other than checking hour is 0 min is 0 and sec is 0thanks,['c#'] +192294,error running mysql server have following errorskydosskydoslaptop service mysql startstart rejected send message 1 matched rules typemethod call sender141 uid10 pid1827 commstart mysql interfacecomubuntuupstart0 6job memberstart error nameunset requested reply0 destinationcomubuntuupstart uid0 pid1 commsbininitskydosskydoslaptop how to solve this problemmore info skydosskydoslaptop sudo service mysql start start job is already running mysql skydosskydoslaptop pidof mysql skydosskydoslaptop pidof mysqld skydosskydoslaptop htop skydosskydoslaptop sudo service mysql start start job is already running mysql,['mysql'] +192316,what is the difference between jframegetcontentpane and jframegetrootpane what is the difference between java frame functions getcontentpane and getrootpanealso what wil happen when we set a jbutton as default,['java'] +192339,simple javascript dropdown menu i would like to make clickable icon image which will thisplay dropdown menu i need only simple menu without submenus and i do not want to use libraries like jquery or mootoolscan anyone help me with this,['javascript'] +192347,behaviour of pythons yield i am reading about the yield keyword in python and trying to understand running this sampledef countfromn while true print before yield yield n and 1 print after yieldfor i in countfrom10 print enter for loop if i 20 print i else breakthe output isbefore yieldenter for loop10after yieldbefore yieldenter for loop11after yieldbefore yieldenter for loop12after yieldbefore yieldenter for loop13after yieldbefore yieldenter for loop14after yieldbefore yieldenter for loop15after yieldbefore yieldenter for loop16after yieldbefore yieldenter for loop17after yieldbefore yieldenter for loop18after yieldbefore yieldenter for loop19after yieldbefore yieldenter for loop20after yieldbefore yieldenter for loopit looks like the yield will return the specified value and will continue runing the function till the end in a parallel thread maybe is my understand correctif you could answer this without mentioning generators i would be thankful because i am trying to understand one at a time,['python'] +192348,tinymce outer wrap selected elements i am having a problem getting tinymce to wrap the contents of the selectionthe first style format simple adds the class to the selected element this works finethe problem is with the second style format i want it to wrap the selected elements inside of the egbeforeptest textpptest textpptest textpptest textpafterp classaccordion toptest textpdiv classaccordion middlediv classaccordion middlewrapper ptest textp ptest textp ptest textpdivdivusing the jquery version i have below the code in question is the bottom style formatstinymcetinymce script url homewebappsharedjavascripttiny mcetiny mcejs mode textareas theme advanced skin cirkuit width 726 plugins advlistinsertdatetimepasteprintsearchreplacespellcheckertablewordcountvisualcharsxhtmlxtrastemplatecodemagic theme advanced buttons1 cutcopypastepastetextpastewordselectallundoredohracronymcharmapblockquotereplaceinsertdateinserttimecleanupremoveformatcodemagic theme advanced buttons2 wrap divstyleselectformatselectbolditalicunderlinebullistnumlisttablelinkunlinkinsertimagespellcheckermybutton theme advanced buttons3 theme advanced buttons4 theme advanced buttons1 tablepasteword theme advanced blockformats ph2h3h4h5h6 theme advanced toolbar location top theme advanced toolbar align left theme advanced statusbar location bottom theme advanced resizing true forced root block p force br newlines false force p newlines true valid elements spanclassidbrclassidahreftargettitleimgsrcidwidthheightclassalti liclassidulclassidolclassidpclassid tableclassidthclassidtrclassidtdclassidtheadtbody h1classidh2classidh3classidh4classidh5classidh6classidstrongclassid divclassid content css template homecsstinymcecss new dategettime plugin insertdate dateformat dmy plugin insertdate timeformat hm paste auto cleanup on paste true convert urls false relative urls false style formats style formats title accorion top selector ph2h3h4h5h6 classes accordion top title accorion middle block div classes accordion middle setup function ed create an wrap div button edaddbutton wrap div title wrap accordion image homewebappsharedjavascripttiny mcethemesadvancedimgcreatelinkgif onclick function var text edselectiongetcontent format text if text tinyinsertdiv classaccordion middlediv classaccordion middlewrapper text divdiv,"['javascript', 'jquery']" +192351,oracle sql getting the nth element regexp i am trying to get the nth element in a comma separated string using sql in oraclei have the following so farselect regexp substr10161545101884lt0110108921012655lsei5101884lt011sl359503002nngn17from dualbut it does not work when the element is empty ie can anyone help,['sql'] +192377,linq on a nested list select all ids i have a nested list something like this listhotel hotelspublic class hotel listroomtype roomtypepublic class roomtype room roompublic class room int roomidit is a little convoluted sorry could not think of a better mockup model the idea is that i have many hotels each hotels has many room types and assume each room type has exactly one room object now from hotels list i just want to select all roomids i am stuck here while trying to nest all listright now i am trying this cant do this some invalid errorint allroomids hotelsselectmanyx xrooms selectmanyy yroomtyperoomidthistincttoarraycant do this z doesnt have anythingint allroomids hotelsselectmanyx xrooms selectmanyy yroomtype selectz z how do i do this please accessing all ids of all items in a nested list occasionally it complains of cannot convert int to boolean and i do not know what it means thanks hope the question was understanble,['c#'] +192381,unary minus overload member or nonmember given that prefix unary operators can be implemented by a nonstatic member function with no parameters or a nonmember function with one parameter a1351overunary1 is there a difference besides the usual encapsulationcode reuse design rationales that apply to any membernonmember function choicesfor binary operators there is a semantic difference because nonmembers allow implicit conversions of their lefthand operands there does not seem to be anything like that for the unary operators yet the standard defines stdcomplexs unary negation operator as a nonmember a2646complexops while stdvalarrays and stddurations unary negation operators are members a26626valarrayunary a201153timedurationarithmetic is there a nuance,['c++'] +192385,how to select a single record in a left join i need to select a specific model from the models table using its key modelid i also need to add a blurb of content from the model content table the models content table however has several blurbs of content for each model i need to select just the first blurbmy tables look like this models table modelid pk model varchar models content table contentid pk modelid fk content varchar select mmodelid mmodel ccontent from models m left join models content c on mmodelid cmodelid where mmodelid 5how do i adjust my query to select just the very first blurb of content for a specific model,['sql'] +192389,find object by id in an array of javascript objects i have got an arraymyarray id73foobarid45foobar etci am unable to change the structure of the array i am being passed an id of 45 and i want to get bar for that object in the array how do i do this in javascript or using jquery,"['javascript', 'jquery']" +192402,new wpf window only shows underneath originating window in my wpf application i have a listview on the main form that thisplays bound data from a dataset when a user doubleclicks a row in the listview it opens a detail windowin my xaml i used a style to create a double click handler on the listviewstyle xkeylistviewdoubleclick targettypextype listviewitem eventsetter eventmousedoubleclick handlerhandledoubleclick stylelistview namesearchresults itemcontainerstylestaticresource listviewdoubleclickin the codebehind i have a dictionary that keeps track of the open details windows multiple can be open at a time so that if a detail window is already open it is brought to the front i handle the doubleclick like soprivate void handledoubleclickobject sender mouseeventargs e datarowview clickedrow listviewitemsendercontent as datarowview int row intclickedrowrowid if thisplayedcardscontainskeyrow detailwindow window new detailwindowretrievedatarow windowowner this thisplayedcardsaddrow window windowshow else thisplayedcardsrowactivate my problem is that with the code like it is above the detail windows are opened behind the main form if i set the owner information windowowner this the detail windows are opened on top of the main form but the main form is never able to come in front of the detail windows the thisplayedcardsrowactivate works as i expected bringing that detail window to the front of all other detail windows but it falls victim to the same problem as above it does not come in front of the main windowwhat i want to accomplish is to have the detail windows on the same levellayer z order as the main window so that both can appear on top of one another and to have the detail windows show up on top of the main form when they are openededit if it is important the detail window has no windowstyle and allowstransparency is set to true i also do not have a window title and the window does not appear in the taskbar when trying to figure this out i tried setting the windowstyle to singleborderwindow and the same problem occurs except that the border of the detail window is shown on top of the main form as the detail window is being drawn and then it is pushed behind the main form could my doubleclick handler essentially be pulling the main form to the front after the detail window is shown,['c#'] +192435,how to ignore rails 3 assets from log possible duplicatehow to thisable logging of asset pipeline sprockets messages in rails 31 is possible to hack logger in rails3 to ignore requests for assetsit is maddness to find something in log when it is full ofstarted get assetstiscalipng for 127001 at 20110909 195945 0200served asset tiscalipng 304 not modified 0msthanks,['ruby-on-rails'] +192440,how can floating point calculations be made deterministic floating point calculation is neither associative nor thistributive on processors soa b c is not equal to a b cand a b c is not equal to a b a cis there any way to perform deterministic floating point calculation that do not give different results it would be deterministic on uniprocessor ofcourse but it would not be deterministic in multithreaded programs if threads add to a sum for example as there might be different interleavings of the threadsso my question is how can one achieve deterministic results for floating point calculations in multithreaded programs,['c'] +192449,spring 30 forwarding request to different controller what is the proper way to forward a request in spring to a different controllerrequestmappingsomeurlpublic modelandview executemodel model if somecondition forward to controller a else forward to controller b all of the controller have dependencies injected by spring so i cannot just create them and call them myself but i want the request attributes to be passed on to the other controllers,['java'] +192459,introspective code completion with vim or other lightweight editor with this feature i have been all over the web trying to find a way to get vim to have code completion similar to pydev it does not seem like it is possible i have tried to use the omnicompletion suggested at this link i have tried several addons to alleviate the problem none workthe omnicomplete functionality is not what i am looking for it just takes all the words in the file you are working on and uses those to try and complete what i am doing for example if i wroteimport numpya single array range100npathen i hit cntrln to code completeit would spit out a single array as a possible completion but that is absurd that is not a valid completion for numpya what is the issue here all the addon would have to do is run a dirwork you want to find from the folder you are in and then filter the output this cannot be that difficult i suppose you would also have to read the file you are currently editing and filter that as well to take note of name changes but that is pretty much itspeaking of how easy it would be if there is not anything already made i was thinking of writing the script myself any guides on how to do that,['python'] +192466,testing memoization i have an expensive method called calculate total i need a method called total that will return the result of calculate total subsequent calls to total should return the previous result of calculate totali want to do this in a test driven way here are my tests i am using rspecdescribe item do describe total do before do item itemnew itemstubcalculate total 123 end it returns the calculated total do itemtotalshould 123 end it subsequent calls return the original result do previous total itemtotal itemtotalshould equalprevious total end endendthis is not a good test because the following method makes the tests pass but i was expecting the second test to faildef total calculate totalendthe reason is calculate total returns a fixnum so ruby does not see the result as 2 different objects i was expecting the second test to fail so then i could do the following to make it passdef total total calculate totalendanyone know a better way to test thisi do not think this is the bestcorrect way to test it but i have settled on this,['ruby'] +192475,mysql select count by value i have this mysql tabledate valueand i wish to become a select which shows me this information asdate count total count val1 count val2any ideas how i can achieve thisthanks,['mysql'] +192481,redirect subprocess to a variable as a string possible duplicateparsing a stdout in python with the following command it prints 640x360 command subprocesscallmediainfo informvideowidthxheight usersdaviddesktop1videomp4640x360how would i set a variable equal to the string of the output so i can get x640x360 thank youupdate answers can be found here parsing a stdout in python this worked for me p1 subprocesspopenmediainfo informvideowidthxheight usersdaviddesktop10stest720pmovstdoutpipe outputp1communicate0stripn output1280x688,['python'] +192482,cc casting away volatile considered harmful related to this question is it safe to cast away volatile but not quite the same as that question relates to a specific instanceis there ever a case where casting away volatile is not considered a dangerous practiceone particular example if there is a function declaredvoid foolong pland i have to implementvoid barvolatile long plwith part of my implementation requiring bar to call foopl then it seems like i cannot get this to work as is because the assumptions made by the compilation of foo and the compilation of the caller of bar are incompatibleas a corollary if i have a volatile variable v and i want to call foov with someone elses function void foolong pl and that person tells me it is safe i can just cast the pointer before the call my instinct is to tell them they are wrong because there is no way to guarantee that and that they should change the declaration to void foovolatile long pl if they want to support the use of volatile variables which one of us is correct,"['c++', 'c']" +192486,average of multiple columns i have a table called request and the data looks likereq id r1 r2 r3 r4 r5r12673 2 5 3 7 10r34721 3 5 2 1 8r27835 1 3 8 5 6now i want to thisplay the average of r1r2r3r4 and r5so i wrote a query likeselect req id avgr1r2r3r4r5 as averagefrom requestgroup by req idbut i just get the sum of r1r2r3r4 and r5 not the average where am i doing wrong,['sql'] +192488,how to flatten or index 3darray in 1d array i am trying to flatten 3d array into 1d array for chunk system in my game it is a 3dblock game and basically i want the chunk system to be almost identical to minecrafts system however this is not minecraft clone by any measure in my previous 2dgames i have accessed the flattened array with following algorithmtilesx y widthhowever this obviously does not work with 3d since it is missing the zaxis i have no idea how to implement this sort of algorithm in 3dspace width height and depth are all constants and width is just as large as heightis it just x ywidth zdepth i am pretty bad with math and i am just beginning 3dprogramming so i am pretty lost ps the reason for this is that i am looping and getting stuff by index from it quite a lot i know that 1d arrays are faster than multidimensional arrays for reasons i cant remember p even though this may not be necessary i want as good performance as possible,"['c#', '.net']" +192492,nodejs require function and parameters when i dolib requirelibjsappis app actually geting passed inin libjsexports moduleexports functionappseems like no since when i try to do more than just app and instead dolib requirelibjsapp param2andexports moduleexports functionapp param2i do not get params2i have tried to debug by doingparams paramsapp aparamsparam2 testlib requirelibjsparamsbut in libjs when i try to jsonstringify i get this errordebug typeerror converting circular structure to json,['javascript'] +192511,nsset allobjects does random ordering i have the following codeselftemporaryimagearray nsset array objectatindex0 images allobjectsarray holds an band object from my coredata model it has an nsset as a property called imagesnow i use this temporaryimagearray to determine via timestamps whether or not the images need to be updated i have come across some very random behavior and my question now isdoes nsset allobjects return the objects from the set randomly in no order is there any way to prevent this or to have it return it in order it would lessen the complexity of my code a lot,"['objective-c', 'ios']" +192518,a simpler singleton all the singleton patterns i have seen use a reference to the object to determine if the object has been instantiated however if i am using a singleton to guarantee only one db connection why not use the db connection resource link to do this here is the code i am using ps it works fine i use the comment to be able to search for my classes easily oneclass one public static db private function construct selfdbnew mysqlidb host db user db pass db database public static function get ifselfdbnull new self return selfdb,['php'] +192520,uibutton keep text black when touched i have an iphone uibutton custom which has a background image and textwhen touched the image darkens good but the text goes from the set black to whitehow do i keep the text the same black so that when the button is touched only the image changes color,"['iphone', 'ios']" +192535,why do i have to type ctrld twice for my own amusement i have cooked up a python script that allows me to use python for bash oneliners supply a python generator expression and the script iterates over it heres the scriptdefault modules os re sys g for m in default modules gm import mimport syssysstdoutwritelinesevalsysargv1 gand heres how you might use it groups python pypepy lupper for l in sysstdindbornside for the intended use it works perfectlybut when i do not feed it with pipe and just invoke it directly for instance emphasis added to show what i type python pypepy rn l for l in sysstdinfooenterbarenterbazenterctrl dctrl dfoonbarnbazn in order to stop accepting input and produce any output i have to type either enter ctrl d ctrl d or ctrl d ctrl d ctrl d this violates my expectations that each line should be processed as entered and that typing ctrl d at any time will end the script where is the gap in my understandingedit i have updated the interactive example to show that i am not seeing the quoting wim describes in his answer and some more examples too python pypepy rn l for l in sysstdinfooctrl dctrl dbarenterctrl dctrl dfoobarn python pypepy rn l for l in sysstdinfooctrl vctrl ddbarenterctrl dctrl dfoox04barn,['python'] +192541,nspredicate to test for null and blank strings i have an nsarray and need to filter out any strings that are null or rather have empty string how do i do that i have tried doingnspredicate predicatename nspredicate predicatewithformatnamenil but that does not seem to work or maybe it does but there are different kinds of null,"['objective-c', 'ios']" +192543,help with understanding a function object or functor in java can someone explain what a functor is and provide a simple example,['java'] +192578,is it possible to generate reports dynamically using jasper reports without generating a jasper for each report i have to generate reports based on various parameters which would be provided dynamically in certain contexts the parameters may be nullfor example from the table person with id name age sex and maritalstatus as fields i would have to generate reports on married male persons of age 30 some other times it may be required to get married female without considering age if i use the same jasper for both these cases the age constraint will be null in second case is there any way to manage this conditionalso is it possible to dynamically specify which all fields should be produced in the report,['java'] +192604,logging http requestsresponses with fiddler on android emulator fiddler manages to log all my pc http traffic but when i run android emulator and start browsing web though emulator nothing gets loggedwhy is not fiddler logging android emulator browser http traffic,['android'] +192637,android scrollbar length with different item sizes i have a listview with a comments comments has different lengthfrom 1 line to 20 for example and while i am scrolling this listview standard scrollbar increases and decreases depending of what the comment i am scrolling in this momentwhy is it happening,['android'] +192647,creating a ping uptime service with php i have a server that i can use php on and a router that can be pinged from the internet i want to write a php script that sends a ping to the router every 5 minutes with the following resultsif the ping succeeds then nothing would happenif the ping fails then it waits a few minutes and if it still fails it sends a warning to my email address onceafter the router is pingable again it sends an email that it is okcould this be done with php how does anybody has a small php file that does this,['php'] +192652,return type vararg i have a method likevoid fooint x grok groksthere is no way to define a method that returns a type of varargs right ideally i want an additional util methodfoo25 new grok new grok generatemoregrokspublic grok generatemoregroks return new grok new grok new grok new grok right more info the issue with the above is that we cannot mix a few grok instances allocated there with an array of groks new grok new grok generatemoregroksand i do not think that is legal unless you could define a method to return a type of vararg i guessthanks,['java'] +192676,how to check the retain count while debugging does anybody know how can i check the retain count of an object while in debug mode i have tried to add an expression objinstance retaincount but it did not work i have also tried the print object po objinstance retaincount in the console but again it did not work,"['iphone', 'objective-c', 'ios']" +192696,how to prevent cracker getting a login access via stealing cookies i am trying to find a solution for securing remember me functionality cookies will be usedfunction encstring slat 32x can be autogenerated hash sha1md5slatstringmd5stringsha1md5md5string return hashecho encpassword store users password in dbi started thinking what if a cracker steals my members cookie in this case the hacker will have access until hacker or original user logs out there will be no evidence other than last login that account is hacked in this case hacker will always have access every time the original user logs in with remember me until original user changes the passwordassuming hacker could not have the passwordsolutions how to prevent hacker get an access if heshe stole the users cookie1 in db user table i put token field which will carry salt value2 everytime user logs in via the form or via the cookie autologin update the token with auto generated value also update the password field with the new hash3 now set the cookie with the new values4 the previous cookie is not valid anymore5 assume hacker got access his access will be temporary until original user access his account and would not be able to do major changes such as changing passwordemailhacker and user will share step 2 everytime hacker logs in user is kicked out from access due to multiple account access and vice versa this will indicate account being stolen so it would not be so long till the original user simply go and change the passwordthis not a 100 solution but reduces chances of risks and warns the user that there is another person using the same accounti am trying to keeping it as simple as it canis the solution good enough are there major flaws in the solution,['php'] +192711,why is arr faster than arr new array i ran this code and got the below result i curious to know why is fasterconsoletimeusingforvar i0 i20 ivar arr consoletimeendusingconsoletimeusing newforvar i0 i20 ivar arr new arrayconsoletimeendusing newusing 299msusing new 363msthanks to raynos here is a benchmark of this code and some more possible way to define a variable,['javascript'] +192712,what are some python libraries that use finite elements to solve structural two and three dimensional frames using numpyscipy or any other library i am interested in solving 2d and 3d frame analysis problems so far i came across sfepy although it is a fully functioning fem package i was wondering if there are any alternatives,['python'] +192719,magento unit testing i have been having some problems with a magento site recently and am looking for a way to check the integrity of a magento site at any given pointunit testing jumps out as one method of doing this but i would assume it would be a very big job to write a whole lot of tests to check everything in the site is working as it shouldcan anyone involved in unit testing and magento advise on the followingis it possible to test the whole site and not just custom modules is so some examples of tests would be amazinggiven that the site is heavily linked to the database how would itbe possible to fully test the site without thisturbing the databaseare there any better ways to automaticlly check the integrity of a magento sitewhen i say integrity i really mean that there are no faults on the site shipping payment etc are all working correctly,['php'] +192748,gujarati font rendering i am having sqlite database containing gujarati wordsthe sql query for the database isbegin transactioncreate table eng guj id integer primary key eng word guj word insert into eng guj values1aardvarka a34aa aa34a a34aa a a aa a34a aa aa a a34acommiti want to thisplay the text in textview but its not rendering properly meant its thisplaying the word in gujarati like a34 will be thisplayed as a34i already have used typeface and different ttf fonts,['android'] +192771,is ios developer able to view file system i wonder if developer has some sort of ways to be able to view file system on ios device like ifile but without jailbreak the deviceneed it for devlopement purposeeditthanks for your answers i know there is a place inside app folder and can be read and write tobut i was looking for a way to view the data quickly without coding like ifile so i can check if my write functions suceed or not,"['iphone', 'ios', 'objective-c']" +192797,generate all subsets of size k containing k elements in python i have a set of values and would like to create list of all subsets containing 2 elements for example a source set 123 has the following 2element subsets set12 set13 set23is there a way to do this in python,['python'] +192820,android mediarecorder native code playing with the mediarecorder java code i have found the mediarecorder class to be quite limited there is no way to control the media before it is encodedcompressed and there is no way to control the result file socket transportmpeg2ts mp4 moof position with windows enviroment directshowmediafoundation provide fine access and control of the media pipelinei wonder is there any lowlevel ndk api for the mediarecorder that enable some of the above mentioned functionalityi would really like to avoid implementing a native c mediarecorder myselfany help will b appreciatednadav,['android'] +192833,singleton release method produces warning in my singleton release method i have it doing nothingvoid release a whole lot of nothingbut it produces this warningwarning conflicting thistributed object modifiers on return type in implementation of releasei googled and saw others have the same error but no explanation of the warning anyone know what the warning is about,['objective-c'] +192867,byte array in python how can i represent a byte array like in java with byte in python i will need to send it over the wire with geventbyte key 0x13 0x00 0x00 0x00 0x08 0x00,['python'] +192871,help with php array filter function please see the following function to scan the files in a directory taken from herefunction scandir only filesdir return array filterscandirdir function item return is filedirdirectory separatoritem this does not work because the dir is not in scope in the anonymous function and shows up empty causing the filter to return false every time how would i rewrite this,['php'] +192877,php interfaces how are they usable in practice i will start by saying that i know how php interfaces work and how to use themmy question is rather how do they become useful in real life applicationsi have been writing php for over 3 years now and have never felt the need for an interface i am writing interfaces more for good practice than for a particular purpose,['php'] +192882,why does gcc show duplicate warnings for bad printf format specifier i am curious why gcc shows me two identical warnings when compiling this file cat testc include stdioh int main int argc char const argv long foo 0l printfin foo return 0 gcc42 wall testc testc in function amainatestc6 warning format aia expects type ainta but argument 2 has type along intatestc6 warning format aia expects type ainta but argument 2 has type along intainterestingly clang also gives two warnings clang testc testc614 warning conversion specifies type int but the argument has type long wformat printfin foo ldtestc614 warning conversion specifies type int but the argument has type long wformat printfin foo ld2 warnings generatedany ideasfor info gcc42 vusing builtin specstarget i686appledarwin11configured with privatevartmpgccgcc563278srcconfigurethisablechecking enablewerror prefixusr mandirsharemanenablelanguagescobjccobjcprogramtransformnamecgs42 withslibdirusrlibbuildi686appledarwin11 programprefixi686appledarwin11hostx86 64appledarwin11 targeti686appledarwin11withgxxincludedirincludec421thread model posixgcc version 421 apple inc build 56 dot 3 clang vapple clang version 21 tagsappleclang16371 based on llvm 30svntarget x86 64appledarwin10thread model posixedit the multiarchitecture hypothesis a few have suggested sounded good but i am not sure it is right if i force a single architecture with arch i get two warnings if i specify arch x86 64 arch i386 i get two sets of duplicate warnings gcc42 wall arch x86 64 testc testc in function amainatestc6 warning format aia expects type ainta but argument 2 has type along intatestc6 warning format aia expects type ainta but argument 2 has type along inta gcc42 wall arch x86 64 arch i386 testc testc in function amainatestc6 warning format aia expects type ainta but argument 2 has type along intatestc6 warning format aia expects type ainta but argument 2 has type along intatestc in function amainatestc6 warning format aia expects type ainta but argument 2 has type along intatestc6 warning format aia expects type ainta but argument 2 has type along intaedit i do not get dupes for all warning types wformat is the only one i have come across so far for example if i throw in an unused variable i only get one warning for that cat testc include stdioh int main int argc char const argv long foo 0l long bar printfin foo return 0 gcc42 wall testc testc in function amainatestc7 warning format aia expects type ainta but argument 2 has type along intatestc7 warning format aia expects type ainta but argument 2 has type along intatestc6 warning unused variable abara,['c'] +192894,how to send an email from javascript i want my website to have the ability to send an email without refreshing the page so i want to use javascriptform actionjavascriptsendmail namepmform idpmform methodpostenter friends emailinput namepmsubject idpmsubject typetext maxlength64 stylewidth98 input namepmsubmit typesubmit valueinvite here is how i want to call the function but i am not sure what to put into the javascript function from the research i have done i found an example that uses the mailto method but my understanding is that does not actually send directly from the site so my question is where can i find what to put inside the javascript function to send an email directly from the websitefunction sendmail code here,['javascript'] +192900,in mysql how can i deleteflushclear all the logs that are not necessary i have tried several commands flush logs purge master but none deletes the log files when previously activated or the log tables mysqlslow logcsv and mysqlgeneral logcsv and their frm and csm counterpartsshow binary logs returns you are not using binary loggingedit i found this simple solution to clear the table logs but not yet the file logs using a mysql commandtruncate mysqlgeneral logtruncate mysqlslow log,['mysql'] +192902,is it possible to have a viewpager inside of a scrollview i am trying to use a viewpager inside of a scrollview but the viewpager does not appear if i remove the scrollview the viewpager appears finei have created a simple test project with the followingmainxml layoutxml version10 encodingutf8linearlayout xmlnsandroidandroidorientationvertical androidlayout widthfill parentandroidlayout heightfill parent scrollview androidlayout widthfill parent androidlayout heightfill parent androidsupportv4viewviewpager androidlayout widthfill parent androidlayout heightfill parent androidididviewpager scrollviewlinearlayoutactivity classpublic class scrollviewwithviewpageractivity extends activity override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain viewpager vp viewpager findviewbyidridviewpager vpsetadapternew mypageradapterthis class mypageradapter extends pageradapter private context ctx public mypageradaptercontext context ctx context override public int getcount return 2 override public object instantiateitemview collection int position textview tv new textviewctx tvsettextsize50 tvsettextcolorcolorwhite tvsettextsmile dude smile dude smile dude smile dude smile dude smile dude smile dude smile dude smile dude smile dude smile dude smile dude smile dude smile dude smile dude smile dude smile dude smile dude viewpager collectionaddviewtv return tv override public void destroyitemview collection int position object view viewpager collectionremoveviewview view override public boolean isviewfromobjectview view object object return view object override public parcelable savestate return null override public void restorestateparcelable arg0 classloader arg1 override public void startupdateview arg0 override public void finishupdateview arg0 thanks for your time,['android'] +192915,is there a more concise way to write this java code this foo that is returned by lookup could be nullthat is why i am trying to avoid calling foogetfoostr on a null value by first returning null if foo is nullbut is there a better more concise way to write thispublic static string getfoostrstring input foo foo lookupinput iffoonull return null return foogetfoostr,['java'] +192916,php decoding and encoding json with unicode characters i have some json i need to decode alter and then encode without messing up any charactersif i have a unicode character in a json string it will not decode i am not sure why since jsonorg says a string can contain anyunicodecharacter exceptoror controlcharacter but it does not work in python eithertagoda3metroi can use utf8 encode which will allow the string to be decoded with json decode however the character gets mangled into something else this is the result from a print r of the result array two characterstag odaa3metrowhen i encode the array again i the character escaped to ascii which is correct according to the json spectagodu00f3metrois there some way i can unescape this json encode gives no such option utf8 encode does not seem to work eitheredit i see there is an unescaped unicode option for json encode however it is not working as expected oh damn it is only on php 54 i will have to use some regex as i only have 53json json encodearray json unescaped unicodewarning json encode expects parameter 2 to be long string,['php'] +192922,c vector push back what is the proper way of pushing a new object element onto a stdvector i want the data to be allocated in the vector will this copy the object newradio into the vector and then get rid of newradio when it goes out of scope eg out of the stackvectorradio m radiosradio newradioradionumm radiospush backnewradioand then when i free the object containing m radios will this free all the memory allocated by the vector,['c++'] +192955,business webapp in net which technology to pick working on porting a winforms application to the web this is a business application but control over endusers browser is not available mostly everyone will be using either ie chrome firefox on desktops and safari on ipadsapplication is making heavy use of listviews treeviews grids charts and has an overall dockstyle interface navigation bar on the left detail pages open up on the right and are tabbed similar to visual studio ui have no need for any seohtmlfriendly framework as the app is hidden from search engineslooking for recommendations on webtechnology need either native or 3rd party support for listviews treeviews grids charts and docking ui speed to market and simplicity are very important hate screwing around with javascript or nonserver technologiessilverlight mvc with html5 plain mvc webforms with html5 plan webforms3rd party controls have license to teleriks and would prefer to stick to them unless there are freeopensource packagesi think a year ago silverlight would have been an easy answer but now i am no longer sure about it due to the ultimate rise of android devices that lack silverlight support and it seems that microsoft is switching its focus from silverlight to html5so what is there left instead of silverlight for business apps thank you,['asp.net'] +192967,how does the compiler internally solve the diamond problem in c we know that we can solve the diamond problem using virtual inheritancefor example class animal base class int weight public int getweight return weight class tiger public animal class lion public animal class liger public tiger public lion int main liger lg compile error the code below will not get past any c compiler int weight lggetweight when we compile this code we will get an ambiguity errornow my question is how compiler internally detects this ambiguity problem diamond problem,['c++'] +192981,jquerycss how do i select all the li thisplay none in the document jquerycss how do i select all the li stylethisplay none in the document,"['jquery', 'css']" +193055,the conversion of a datetime2 data type to a datetime data type resulted in an outofrange i am working on application contains a datepicker and if i set the time in that picker to a very old value or far in the future when i try to save this value in the database the server throw this exception what is the cause of itthe conversion of a datetime2 data type to a datetime data type resulted in an outofrange value the statement has been terminated,['sql'] +193063,does mongodb have a native rest interface i am currently evaluating mongo and couchdb for storing data points analyticsduring my earlier interaction with couchdb i loved its jsonp based interface i could perform all crud operations from purely javascriptjust run couchdb and write some javascript no server side component neededwhen comparing this to mongo is there any rest interface availableis it possible to do crud purely from javascript in mongothanks,['javascript'] +193064,turning an integer into random string and back again what i am wanting is to convert an integer into a string for example 123456789 may become 8gfsah93r you know like youtube pastebin and what not i then want to convert it backi am working with large integers for example 131569877435989900take a look at this link this is my attempt using a function i found on the web obviously it is not correctly converting back to integer i am needing something that does this realiablythanks,['php'] +193077,how to find particular class exists on a page using jquery i want to write jquery which will find whether classmandatory exists on the page and if any element is having this class then only perform certain actionthanks,['jquery'] +193092,does local variable in thread function have separe copy according to thread i have declared some local variable in one function like thisvoid thread function void parameter struct parameter thread data struct parameter parameter char buffer20 int temphere if i have created two threads then in one thread if buffer temp is updated so will it effect other thread i mean if there are two thread then does there will be two copy of all local variableedit then in which case i need to used thread specific data i mean pthread setspecific all such stuff,['c'] +193115,combining two constructors that copy and move currently one of my toy class templates has two constructors that look very similaroptionalconst t x constructxoptionalt x constructstdmovexcan i combine them into a single constructor template or will this change the semantics somehowtemplatetypename uoptionalu x constructstdforwardux,['c++'] +193121,error fatal not a git repository or any of the parent directories git when i try to put images into the resources folder of my project i got this message fatal not a git repository or any of the parent directories githow can i fix that,['ios'] +193122,how to bind dropdownlist which is inside repeater i want to bind dropdownlist which is inside a repeatermy code is asprepeater idrep unassigncomps runatserver itemtemplateaspdropdownlist iddrp comppropaddress runatserver aspdropdownlistitemtemplateasprepeater,['asp.net'] +193152,parsing crontabstyle lines i need to parse a crontablike schedule definition in python eg 00 3 and get where this should have last runis there a good preferably small library that parses these strings and translates them to dates,['python'] +193183,rotating video taken in portrait mode my app lets the user capture videointent cameraintent new intentandroidprovidermediastoreaction video capturestartactivityforresultcameraintent camera video request or picsintent cameraintent new intentandroidprovidermediastoreaction image capturestartactivityforresultcameraintent camera pic request in the case of the pics i can tell whether they were taken in any mode other than landscape and then rotate them before i upload them to the webexifinterface exif new exifinterfacefilenameint exiforientation integerparseintexifgetattributeexifinterfacetag orientationfloat rotate 0switch exiforientationcase exifinterfaceorientation rotate 90 rotate 90 breakcase exifinterfaceorientation rotate 180 rotate 180 breakcase exifinterfaceorientation rotate 270 rotate 270 breakifrotate 0 bitmap bitmap bitmapfactorydecodefilefilename matrix matrix new matrix matrixpostrotaterotate bitmap bitmapcreatebitmapbitmap 0 0 bitmapgetwidth bitmapgetheight matrix true outputstream outstream contextgetcontentresolveropenoutputstreamurifromfilefile bitmapcompressbitmapcompressformatjpeg 100 outstreamhow do i accomplish the same with video,"['java', 'android']" +193184,is it linq or lambda i know that this is linqvar results from item in list where itemvalue 1 select itemand i know this is lambdavar results listwherex xvalue 1editors note the above is not merely lambda it is linq using the method syntax whose predicate is a lambda to be clear both of the above samples are linq my original post was incorrect but i left the error to illustrate the confusion prompting the questionbut is linq a subset of lambda or whatwhy are there two seemingly identical techsis there a technical reason to choose one over the other,['c#'] +193192,why is the amount of visibility on methods and attributes important why should not one leave all methods and attributes accessible from anywhere ie publiccan you give me an example of a problem i can run into if i declared an attribute as public,['php'] +193217,is it possible to deprecate some of the values of a java enum and if so how i want to deprecate some but not all possible enumeration values,['java'] +193223,what does sql clause group by 1 mean someone sent me a sql query where the group by clause consisted of the statement group by 1this must be a typo right no column is given the alias 1 what could this mean am i right to assume that this must be a typo,"['mysql', 'sql']" +193227,why should yinnerhtml xinnerhtml be avoided let us say that we have a div x on the page and we want to duplicate copypaste the contents of that div into another div y we could do this like soyinnerhtml xinnerhtmlor with jqueryyhtml xhtml however it appears that this method is not a good idea and that it should be avoided 1 why should this method be avoided2 how should this be done insteadupdatefor the sake of this question let us assume that there are no elements with ids inside the div xsorry i forgot to cover this case in my original questionconclusioni have posted my own answer to this question below as i originally intended now i also planed to accept my own answer p but lonesomedays answer is so amazing that i have to accept it instead,"['javascript', 'jquery', 'html']" +193247,why should the getinstance method in factory pattern be static in most of the factory pattern implementations the getinstance method is usually declared as static the main advantage of factory pattern is to hide the implementation details but why does getinstance method needs to be static is instantiating a new factory object a bad practicexyzfactory factory new xyzfactory xyzobj obj factorygetinstancetypevsxyzobj obj xyzfactorygetinstancetype,['java'] +193258,map bitwise enum to sql column value i have a bitwise enum with flagsattribute set over it like this flagsattributepublic enum myenum none 0 first 1 second 2 third 4 five 8 six 16 seven 32 eight 64 nine 128now in c i am storing this value in a property say myproperty and on save i write this property in my sql database in integer column suppose if i select firstsecondfive from code then in database it will be saved as 11i know i can fetch value from db and just need to typecast int value to myenum and it will give me the values but i want some manipulation to be done on sql data in some stored procedure where obviously i cannot typecast it to enum value so is there a way out which can let me know about the individual valueslike in example if 11 is stored any way that i can get it as 128,"['c#', 'sql']" +193263,passing function template specializations to a variadic template function i have no problem passing the address of a function template specialization to a regular template functiontemplate typename tvoid ft template typename a typename bvoid fooa b int main foofint ffloathowever when i try to pass the same specializations to a variadic templatetemplate typename tvoid ft template typename avoid bara int main barfint ffloati get the following compiler errors with gcc i tried 461 and 470testcpp in function int maintestcpp927 error no matching function for call to barunresolved overloaded function type unresolved overloaded function typetestcpp927 note candidate istestcpp56 note templateclass a void bara testcpp56 note template argument deductionsubstitution failedwhy am i getting these errors,['c++'] +193280,check if a key is down with qt i am playing around with some graphics and i have implemented simple camera movement with the arrow keys my first approach was to override keypressevent to do something like thisswitchkey case up movecameraforwardstep break case left movecameraleftstep break this does not work as i wish it would when i press and hold for example the forward key the camera moves forward step units then halts for a while and then continues moving i am guessing that this is how the event is generated in order to avoid multiple events in case of a little bit long keypreso i need to poll the keyboard in my paint routine i have not found how to do it with qt i thought of having a mapkey bool which would be updated in keypressevent and keyreleaseevent and poll that map in paint any better ideas thanks for any insights,['c++'] +193284,numpy modify ndarray diagonal is there any way in numpy to get a reference to the array diagonali want my array diagonal to be divided by a certain factorthanks,['python'] +193311,thisable dragging of a file system image into a browser i am experimenting with the html5 file api i notice however that browsers have a default behaviour where they thisplay an image if you drag the image into the browser this can however be annoying if your aim is to upload the image rather than to view it i am wondering if there is a way of preventing this behaviour i have tried stoppropagation preventdefault on an ondrop event which works somewhat however leaves the drop cursor in place giving the impression that the image can be dropped anywhere on the page ideally you would only see the drop cursor on the designated area where images are meant to be dropped,['javascript'] +193315,reason for using nontype template parameter instead of regular parameter in c you can create templates using a nontype template parameter like thistemplate int i void add int value value iint main int argc char argv int i 10 add 5 i stdcout i stdendlwhich prints 15 to cout what is the use for this is there any reason for using a nontype template parameter instead of something more conventional likevoid add int value int amount value amountsorry if this has already been asked i looked but could not find anything,['c++'] +193340,instagram api and importing photos without server side authentication i am a bit confused on a certain functionality i would like to implement into a website using the instagram api i would like to access my own feed based on my user id from the instagram api and thisplay them on my site it is saying that there is a way to do client side oauth authentication but i am a bit confused on how i would go about this i am fairly okay with javascript and if someone could point me in the right direction i am sure i could figure it outany best practices would be greatthank you in advancejn,['javascript'] +193374,post increment operator coutx fails coutx passeswhy does the post increment fail i see it happen but not sure of the technical reason,['c++'] +193385,unable to understand usecapture attribute in addeventlistener i have read article at but unable to understand usecapture attribute definition there isif true usecapture indicates that the user wishes to initiate capture after initiating capture all events of the specified type will be thispatched to the registered listener before being thispatched to any eventtargets beneath it in the dom tree events which are bubbling upward through the tree will not trigger a listener designated to use capture in this code parent event triggers before childso i am not able to understand its behaviordocument object has usecapture true and child div has usecapture set false and document usecapture is followedso why document property is preferred over childhtmlheadscriptfunction loaddocumentaddeventlistenerclickfunctionalertparent eventtruedocumentgetelementbyiddiv1addeventlistenerclickfunctionalertchild eventfalsescriptheadbody onloadloaddiv iddiv1click medivbodyhtml,['javascript'] +193396,static abstract class i need a way to create a static class where some constants can be case specific but hardcodedwhat i really want to do is have a class where several constants are provided when the class is extended i want the constants hardcoded i figured i will make the some abstract properties and define the get return constant when extending the classi know that is not possible so now i am facing two options and am wondering what would be best and why if there are options i am missing please let me knowcreate a static class with nullable fields and throw an exception if the fields are null when the static method is calledgive up the static class have a nonstatic class with abstract properties and create an instance of the object wherever i need it even though all the functionality really is statici know this might be subjective and casedependant however i am going around in circles when thinking about this and could really do with some external input that plus i hope there might be away of doing what i want and i am just thinking about this wrongupdate code i will try to write some code that describes what i would like to accomplish i know this code cannot workimagine that the abstract class calculation is in a dll used by many projects the functionality is the same for all of them just the constant varies from project to projectpublic abstract static class calculation private abstract int constant get the constant is unknown at this time public static int calculateint inputvalue return inputvalue constant the class calc is defined in a separate project where the functionality is needed and the constant is knownpublic static class calc calculation private override int constant get return 2 static class program stathread static void main at some point int result calccalculate6 i suppose the simplest way would be to create a nonstatic class and create an instance however i fear having several instances of the class could be expensive and would like to prevent that if possiblei cannot see how i could write this as a singleton pattern without writing it again in each project having only the nested class in the dll that does not prevent the implementor to just create an ordinary class and is likely to restart the debate for every project where the code is usedupdate 2 what i ment with option one is thisclass in a dllpublic static class calculation public int constant get set public static int calculateint inputvalue if constant null throw new argumentnullexception return inputvalue intconstant usage of the function in a seperate projectstatic class program stathread static void main at some point calculationconstant 2 int result calccalculate6 option one is very simple and elegant what bothers me about it that nothing forces the implementor to set the constant i fear an admittedly unlikely scenario where an obscure corner case will cause the property to not be set and for the code to fail and constant beeing the last suspect,['c#'] +193398,a library to convert svg to images i am looking for a library written either in c or c which can convert the svg to image formatsi came across inkscape which converts svg to images but to use this i must run inkscape as a process and this not the solution i am afteri need the library to run on both windows and linux as welli am after a c or c library if it was with java i would have used apache is batik rasterizer,"['c++', 'c']" +193426,null literal parameter type overload resolution possible duplicatehow does the method overload resolution system decide which method to call when a null value is passed this is a question about why the compiler chooses a certain overload when passed a null literal as a parameter demonstrated by stringformat overloads stringformat throws an argumentnullexception when using null literal for args parameterstringformatfoo 0 nullthe format method has some overloads stringformatstring objectstringformatstring objectstringformatiformatprovider string objectrunning through the decompiled code the exception for the null literal args is thrown from the second method however the following examples call the first method above as expected and then that calls the second which calls the third eventually returning just foo string x nullstringformatfoo 0 xstring ystringformatfoo 0 y nullbut stringformatfoo 0 null calls the second method above and results in a null exception why does the compiler decide that the null literal matches the second method signature instead of the first in this case,"['c#', '.net']" +193434,providing datetime values in odata i am currently writing a special client application to allow our unit tests to work with an odata interface using the xml structure for atom feedsall seems to be working properly but i am running into trouble when i need to pass a datetime value as propertyi have written the following code that extracts the datetime value from the property of the object and stores it in a specific formatprivate static void generatepropertytstringbuilder xml t obj propertyinfo info extract the information about the property if it contains a value if infogetvalueobj null null return string type infogetgetmethodreturntypetostringsplitlast string value infogetvalueobj nulltostring if type datetime value datetimeinfogetvalueobj nulltostringymmddthhmmss if type boolean value valuetolower append the property to the generated xml xmlappendtypetolowerequalsstring stringformatd01d0 infoname value stringformatd0 mtypeedm12d0 infoname type value the code is heavy on reflection but that is beside the point the values returned by this code for a datetime are in the following format 20114913t114941zhowever i am receiving the following error from my odata service error processing request stream error encountered in converting the value from request payload for property created to type systemdatetime which is the propertys expected type see inner exception for more detail the string 20114913t114941z is not a valid allxsd value systemformatexception at systemxmlxmlconverttodatetimestring s xmldatetimeserializationmode datetimeoption at systemdataservicesparsingwebconvertstringtoprimitivestring text type targettype at systemdataservicesserializersplainxmldeserializerconvertvaluesforxmlobject value string propertyname type typetobeconvertedso apparently it does not understand the datetime format but when i look at the documentation that is posted here i would expect it to be valid anyone have any experience with this,"['c#', '.net']" +193437,jquery serialize not processing value of dropdown list i think this should be a simple thing but for some reason all my form values are being serialized fine except for the selected value of the dropdown list the form is belowform idcontactform label fornamenamelabel input typetext idname namename placeholderfirst and last name tabindex1 label forphonenumberphone numberlabel input typetext idphonenumber namephonenumber placeholderplease enter your phone number tabindex2 label foremailemaillabel input typetext idemail nameemail placeholder tabindex3 label fordropdownplease confirmlabel select option valuequestion selectedselectedi have a questionoption option valueattendingi am attendingoption option valuenotattendingi am not attendingoption select label forcommentyour messagelabel textarea namecomment idcomment namecomment placeholderenter something here cannot think tabindex5textarea input namesubmit typesubmit idsubmit tabindex6 valuesend messageformand this is how i am serializing itcontactformsubmitfunction var query thisserialize ajax type post url sendphp data query success functiondata rest of functionand finally the bit of php i am using to set the value as a variable isdropdown postdropdownan example header is namesgrggrphonenumber5emailme40mecomcommentquicktest so i am stuck as to why the dropdown value is not being picked upthanks for your help,"['php', 'jquery', 'html']" +193445,defining settergetter for an unparented local variable impossible there is a few previous questions on stackoverflow questioning how one goes about accessing local variables via the scope chain like if you wanted to reference a local variables using bracket notation and a string youd need something like local varname thus far i have not found even the hackiest method for accomplishing this and have not come up with a method after hours of exploiting every trick i knowthe purpose for it is to implement getterssetters on arbitrary unparented variables objectdefineproperties or definegetsetter require a context to be called on for properties in the global or window contexts you can accomplish the goal of having a settergetter for direct references to the objectobjectdefinepropertythis glob get functionreturn direct accessconsolelogglob direct accesseven in my tests with a custom extension i compiled into a modified chromium that runs prior to any window creation where the context is the actual global context and even trying to call this directly in the global context crashes my program i can pull this off without a hitchobjectdefinepropertyobjectprototype define value functionname descriptor objectdefinepropertythis name descriptor definereallyglobal get function return above window context and it is then available in all frames created later as a global routed through the specified gettersetter the old definegetsetter also works in that context without specifying what to call it on does not work in firefox though the method above doesso basically it is possible to define getset guards for any variable on an object including the windowglobal context with direct call to the object you do not need windowpropname just propname this is the issue with being unable to reference unparented scoped variables being the only type that can be in an accessible scope but have no addressable container of course they are also the most commonly used too so it is not an edge case this problem also transcends the current implementation of proxies in es6harmony since it is a problem specifically with being unable to address a local objects container with the languages syntaxthe reason i want to be able to do this is that it is the only barrier to allow overloading of most math operators for use in complex objects like arrays and hashes and deriving a complex resulting value i need to be able to hook into the setter in cases where a value is being set on an object type i have set up for overloading no problem if the object can be global or can be a contained in a parent object which is probably what i will just go with it is still useful with amyobject but the goal is to make it as transparently usable as possiblenot only that but it would just be really useful to be able to accomplish something like thisvar point3d function var x y z return get function return x y z set functionvals xvals0 yvals1 zvals2 that is similar to es6s destructuring but has more general applications for implementing functionality attached to gettingsetting and not just transporting complex values even this basic code will completely failvar x myname intercept valueof and set to overload math ops index 5x x is now nan if you do not implement a setter somehowi do not care how hacky the solution is at this point it is just an intense curiosity for me as to whether it can be accomplished even if it requires breaking every best practice that exists i have crashed firefox and chrome a few hundred times in pursuit of this so far by doing things like redefininginterceptingmodifying objectprototypevalueoftostring functionprototype functionprototypeconstructor functionprototypecallapply argumentscalleecaller etc with infinite recursion errors and whatnot in attempts to jury rig contexts retroactively the only thing that i have been able to make work is wrapping basically the whole thing with eval and dynamically building code chunks which is a bridge too far for me to ever actually use the only other remotely successful route was in using with combined with predefining all local variables on a container but that is obviously very intrusive on top of the issues with using with,['javascript'] +193446,general c question following class has two method wherein m1 complain anot all code path return a valuea and m2 doesnat question how does the compiler resolve m2 in context of return value how notimplementedexception instance is implicitly casted as int if there is any internal compile time resolution class a int m1 int m2 throw new notimplementedexception,['c#'] +193450,how to get private key from pem file i have a pem file that includes public key and a private key for ssl data transfer like thisbegin rsa private key private key dataend rsa private keybegin certificate public key dataend certificatewhen i want to load the pem file by the following codex509certificate2 xx new x509certificate2cmykeypemi get an exception that says cannot find the requested object with full stacksystemsecuritycryptographycryptographicexception was unhandled messagecannot find the requested object sourcemscorlib stacktrace at systemsecuritycryptographycryptographicexceptionthrowcryptographicexceptionint32 hr at systemsecuritycryptographyx509certificatesx509utils querycertfiletypestring filename at systemsecuritycryptographyx509certificatesx509certificateloadcertificatefromfilestring filename object password x509keystorageflags keystorageflags at systemsecuritycryptographyx509certificatesx509certificatectorstring filename at systemsecuritycryptographyx509certificatesx509certificate2ctorstring filename at dlltestssl testtest in eprojectsdlltestdlltestssl testcsline 165 at dlltestssl testrun in eprojectsdlltestdlltestssl testcsline 21 at dlltestprogrammainstring args in eprojectsdlltestdlltestprogramcsline 21 at systemappdomain nexecuteassemblyruntimeassembly assembly string args at systemappdomainexecuteassemblystring assemblyfile evidence assemblysecurity string args at microsoftvisualstudiohostingprocesshostprocrunusersassembly at systemthreadingthreadhelperthreadstart contextobject state at systemthreadingexecutioncontextrunexecutioncontext executioncontext contextcallback callback object state boolean ignoresyncctx at systemthreadingexecutioncontextrunexecutioncontext executioncontext contextcallback callback object state at systemthreadingthreadhelperthreadstart innerexception if i swap place of private key section and public key section the code works and load data and i can get just public key info from the object eg issuernameand its hasprivatekey is false why am i misunderstood and doing wrong something,['.net'] +193453,c infer generic type based on passing a delegate i have the following codepublic static class x public static c testabcthis a a funcbc f where cclass return null public class bar public bar thistestfoo this does not compile thistestfuncint stringfoo thistestint q x string fooint a return why does not the marked line compile does it have something to do with return type not being part of the signaturebut the third line does compile which makes me guess the compiler turns it into something similiar to the second line,['c#'] +193465,why absolutelayout is deprecated why absolutelayout is deprecated i know that it may cause problems in supporting multiple screens but was better for showing view at particular position,['android'] +193474,exchange web services ews finditems within all folders i am using the following code to find all the emails sent from a user however this only searches the main inbox folder and does not check any subfolders i would like to search all the mail items including any subfoldersi have tried the wellknownfoldernameroot and wellknownfoldernameinbox and these only search those folders not the subfolders private static void searchitemsstring email itemview iv new itemview10 finditemsresultsitem fiitems servicefinditemswellknownfoldernameinbox from iv foreach item item in fiitems consolewritelinesubjectt itemsubject consolewritelinereceived at itemdatetimereceivedtostringdd m y consolewriteline consolewritelinepress enter to continue consolereadline,['c#'] +193483,how to convert int to unsigned byte and back i need to convert a number into an unsigned byte the number is always less than or equal to 255 and so it will fit in one bytei also need to convert that byte back into that number how would i do that in java i have tried several ways and none work heres what i am trying to do nowint size 5 convert size int to binarystring sizestr integertostringsizebyte binarybyte bytevalueofsizestrand now to convert that byte back into the numberbyte test new bytebinarybyteint msgsize testintvalueclearly this does not work for some reason it always converts the number into 65 any suggestions,['java'] +193487,expandablelistview inside expandablelistview i would like to know if it is possible to put an expandablelistview as one child of one element of another expandablelistview thanks,['android'] +193536,hashing floating point values recently i was curious how hash algorithms for floating points worked so i looked at the source code for boosthash value it turns out to be fairly complicated the actual implementation loops over each digit in the radix and accumulates a hash value compared to the integer hash functions it is much more involved my question is why should a floatingpoint hash algorithm be any more complicated why not just hash the binary representation of the floating point value as if it was an integerlikestdsize t hash valuefloat f return hash valuereinterpret castintfi realize that float is not guaranteed to be the same size as int on all systems but that sort of thing could be handled with a few template metaprograms to deduce an integral type that is the same size as float so what is the advantage of introducing an entirely different hash function that specifically operates on floating point types,['c++'] +193540,tricks to make app more efficient on battery consumptionios are there any tricksmethods to optimize the battery usage that you app usesi have an app that can play streaming audio in the background quiet well it does the basics like put the app in the background after a little time of no interfacing with the screen by the userare there any other tricks to be done to stop it eating the battery like a fat man at an all you can eat buffetthankscode,"['iphone', 'objective-c', 'ios']" +193542,iphone apps on visual studio possible duplicatehow can i develop for iphone using a windows development machine i want to develop an iphone application as my final year project and i cannot buy a mac i heard that iphone apps can be built on visual studio from this web site is this true,"['iphone', 'ios']" +193551,bulk insert rowterminator issue i have this csv named testcsv with the content below1test user4075619900aldelo for restaurantsthis is my deallocation42joe johnson32 bit44519restaurant pro expresmoe one is watching usome locationhere is my sql file to do the bulk insertuse somedbgocreate table csvtempid intname varchar255department varchar255architecture varchar255phone varchar255email varchar255download varchar255comments textcompany varchar255location varchar255gobulkinsert csvtempfrom ctesttestcsvwithfieldterminator rowterminator char124char10gocheck the content of the tableselect from csvtempgobut whats happening is its only inserting one record and all the info from the second record is getting inserted in the location field on the first record idnamedepartmentarchitecturephoneemaildownloadcommentscompanylocation 1test usernullnull4075619900aldelo for restaurantsthis is my dealnulocation42joe johnson32 bit44519restaurant pro expresmoe one is watching usome locationi assume the problem is the rowterminator but i tried all theserowterminator nrowterminator rnrowterminator rand all the same results any ideas on how to fix thisi am creating the csv like this via php,"['php', 'sql']" +193557,whats the preferred way of exiting a command line program this should be straightforward i just need to simply exit my commandline c program no fancy stuffshould i use environmentexitorthiscloseor something else,"['c#', '.net']" +193563,how to fix seekbarbarthumbcenteringissues i have set thumb image of a seek bar but my thumb looks little below of seek bar how to set thumb at proper position of a seekbar have a look on the attached imageseekbar androidididpp player seekbar androidthumbdrawablemusic player playerhead androidpaddingleft8dip androidpaddingright8dip androidprogressdrawabledrawableseekbar drawable xml background androidlayout width236dip androidlayout centerhorizontaltrue androidlayout heightwrap content androidlayout margintop47dipseekbarthankssunil kumar saoo,['android'] +193577,nltk fails to find the java executable i am using nltks nltktagstanford which needs to call the java executablei set javahome to cprogram filesjavajdk160 25 where my jdk is installed but when run the program i get the errornltk was unable to find the java executable use the config java or set the javahome variablethen i spent 3 hours on debugging it and tried config javacprogram filesjavajdk160 25config javacprogram filesjavajdk160 25binand those without the ending however the nltk still cannot find itanyone has idea about whats going wrong thanks a lot,"['java', 'python']" +193584,extjs how to use proxy model how are they related i have been trying to learn to work with models and stores but the proxy bit is confusing me a lot so i am going to list out my understanding here please point out the gaps in my understandingmy understandingmodels are used to represent domain objectsmodels can be created by modelmanager or by simply using the constructormodels are saved in storesstores may be in memory stores or can be server stores this is configured using proxyproxy tells the store how to talk to a backing store be that a json array or a rest resource or a simply configured url via ajaxstores are responsible for storing models and proxies are responsible for controllinghelping with that taskwhen a models values are changed its dirty flag gets set it gets automatically cleared when the model is saved more in this laterthe part that confuses mewhy is there a proxy config and save method on model i understand that models can only be stored on to storeswhy is the dirty flag not cleared simply when i add a model object to a storewhen i add a model object to a store why does the model not acquire the proxy configured with that storeproxy is a static configuration for a model does that mean that we cannot use objects of a particular model with multiple data sources by extension does this mean having multiple stores for a single model essentially uselesswhen we define a store are we defining a class storetype if we may call it that or is it an instance of a store reason i ask is when we declare a grid we simply pass it a store config as store myappstoremystore does the grid instantiate a grid of that type or is it simply using the store weve already instantiatedthanksps 50 bounty to the person who explains all this will offer bounty after those 48 hours are over,['javascript'] +193586,c equivalent to java resource is there an online resource or database that allows looking up the c equivalent to a java class and vice versai have been porting code and have been googling individual classes one at a time it gets a little tedious 8jcheers,"['c#', 'java']" +193604,hide microphone button android virtual keyboard i wanted to know if is it possible to hide the microphone button speechtotext in android virtual keyboard programaticallyi know i can thisable this option through device settings but i do not want the user to use this feature in my application independently of hisher settings i mean i want to force this behaviour inside my appthanks in advancedemian,['android'] +193612,how can i initialize base class member variables in derived class constructor why cannot i do thisclass apublic int a bclass b public a b a a0 b0 edit i meant for the a member variables to be public,['c++'] +193614,is it possible to view the contents of files in the ios application sandbox while debugging title more or less says it alli would like to check the contents of an xml file at a specific point of execution while debugging in xcode is it possible to view the contents of the file either through the organizer i am debugging using actual hardware devices not the simulator or by typing in some sort of command into the outputconsolei am using xcode 4,['ios'] +193649,const reference to nonconst object in the following would there be a temporary object created before const reference is used to a nonconst objectconst int y 20const int s y ok const reference to const objectint x 10const int r x any temporary copy hereif no then how does this work const int z 30 int t z ok why cannot you do this,['c++'] +193651,is there an app that removes unused classes from frameworks so to give you an idea of what it is i am trying to do oocss framework uses a ton of classes i am about to package up a mobile site that is about 25 megs and would like to remove all unused classes from the files sure i could do it by hand but it would be much easier if something like this existed for the future,['css'] +193674,warning parameters parameters invalid chunk ignored when posting from a managed bean i am opening a httpurlconnection from within a managed bean to post to an external service when i make the call to httpurlconnectiongetinputstream i am getting the following warning warn parameters parameters invalid chunk ignoredeverything processes just fine but i would like to keep a bunch of those warnings out of our logs what is causing this warning and how might i stop it from occurringhere is the relevant codemanagedbeansessionscopedpublic class mycontroller private void dostuff url url new urlexternalserviceurl httpurlconnection conn httpurlconnection urlopenconnection connsetdooutputtrue connsetdoinputtrue wr new outputstreamwriterconngetoutputstream wrwritepostdata wrflush inputstream is conngetinputstream warning logged after this line,['java'] +193677,can i change the scroll speed using css or jquery in this jsfiddle example i would like to reduce the scroll speed of the divs content especially when using the mouse wheel as one one wheel scrolls approxilately the divs heightis it possible to control that with css and if not javascript perhaps using jquery note i realize that the scroll speed might differ between osbrowers and browser settings but i think that in the majority of the cases the scroll speed when using the mouse wheel is too fast so i would like to slow it down,"['jquery', 'css']" +193693,given a vector of points possibly out of order find polygon not convex hull i currently have a vector of pointsvectorpoint cornerswhere i have previously stored the corner points of a given polygon given that i know for sure that the points form a simple polygon that does not contain any selfintersecting edges however in the process of storing these vertices the order in which they connect to each other was not preservedi now have a function that given a vector of points connects them and draws me a closed figure however i need to give this function the sequence of points in the order they need to be connected can anyone suggest a way that i could sort these points in the correct order they form a very simple concave polygon not a convex hull an algorithm to find the center point among all the 7 points would also be helpful,['c++'] +193711,how can i deprecate an entire protocol is it possible to deprecate an entire protocol i am using the gcc compiler that is shipped with ios sdk 50 beta 7deprecated attribute does not seem to workfor example the following two statements do not compileprotocol deprecated attribute myprotocolprotocol myprotocol deprecated attribute,['objective-c'] +193724,add elements to a list while iterating over it java possible duplicatejava adding elements to a collection during iteration my problem is that i want to expand a list with new elements while iterating over it and i want the iterator to continue with the elements that i just addedfrom my understanding the listiteratoradd adds a element before the current element in the list not after it is it possible to achieve this in some other waythx in advance,['java'] +193725,reading entire file in python if you read an entire file with content openpathtofile rread is the file handle left open until the script exits is there a more concise method to read a whole file,['python'] +193728,detect unused css rules possible duplicatehow can i find unused images and css styles in a website i am developing a websitei use ready templatethis template contains many css files with many css rulesbut i have few pages and i am sure i did not use all selectorsis there any tool exist for scanning project html files and finding unused css rules and remove them i found this question that says dustme selectors is a firefox plugin that finds unused selectorsbut its not compatible with ff6 and seems it just review current viewing page and not scans whole website files,['css'] +193729,how to limit ios keyboard to numeric input the question pretty much says it all is there any way to have the iosiphone keyboard default to numeric input,['ios'] +193732,what differentiates a rest web service from a rpclike one i have a web application that uses ajax to grab json data from the server it requires that the user first log in with their browser so that a cookie can be set only the get and post verbs are used where get is for retrieving data and post is for any operation that modifies datafrom what i understand rest differs from the above method in that the user authentication information is sent with every request and the put and delete verbs are used as wellmy question is what benefits does a rest web service have over the rpclike method if the end point is only meant to be a users browser i can understand how rest is beneficial when the client is unknown but when i am only using jquery ajax calls are the benefits still worth it over an rpclike method,['jquery'] +193737,ios programming on windows system i am interested in learning ios programming but at the moment i do not have access to a macintosh system just wondering if there is an equivalent of ios sdk for windows i do have an iphone though,['ios'] +193791,check an int variable is null or is empty from the database i am having a variable which isnocustomers rsgetintcust tran counti would like to perform if it is null or noti tried if nocustomers nullit showed an errorhow do i solve thismy new modified code istry query select from ss summary where txn date to date asatdateymmdd st conncreatestatement rs stexecutequeryquery if rsnext nocustomers rsgetintcust tran count nocheques rsgetintcheq delivered main if rswasnull outprintlnno data found,['java'] +193797,statelistdrawable and tiled bitmap this is my custom selector statelistdrawableselector xmlnsandroid item androiddrawabledrawablecommon cell background item androidstate pressedtrue androiddrawabledrawablecommon cell background highlight item androidstate focusedtrue androiddrawabledrawablecommon cell background highlight item androidstate selectedtrue androiddrawabledrawablecommon cell background highlight selectorboth common cell background and common cell background highlight are xml code belowcommon cell backgroundxmlbitmap xmlnsandroid androidsrcdrawablecommon cell background bitmap androidtilemoderepeat androiddithertruebitmapcommon cell background highlightxmlbitmap xmlnsandroid androidsrcdrawablecommon cell background bitmap highlight androidtilemoderepeat androiddithertruebitmapbitmaps are also exactly the same highlight is just a little bit lighter and there is no other differences both bitmaps are png filesnow i setconvertviewsetbackgroundresourcerdrawablelist item backgroundand here is the problem my common cell background does not repeat it is stretched but what is suprising when i touch on cell of my list background changes to common cell background highlight and guess what everything is fine it is repeated like it should be i have no idea where is the problem why my background does not repeat while highlight does any thoughts,['android'] +193821,magento login as customer from admin i have extended the mage adminhtml customercontroller with a new action loginaction in order to be able to login as a customer from the admin interface i call the loginbyid on the customersession but the customers session is not modified after the redirectcan someone explain why it should be a simple operationheres a gist containing the loginactioni appreciate any help thanksupdatei created a githubrepo containing all the code for the module once this issue is solved it might be useful for someone else as well,['php'] +193837,iad refusing to thisplay iad framework is doing my nut againplease someone help me towards sanityyesterday was working on the simulator today it is not after an hour of raging at it i actually plug in my brain and log the error iirc this is on the simulatorerror domainaderrordomain code3 the operation couldnat be completed ad inventory unavailable userinfo0x5a5bb50 adinternalerrorcode3 nslocalizedfailurereasonad inventory unavailable then i try a rebooton the simulatorerror domainaderrordomain code4 the operation couldnat be completed application has iad network configuration error userinfo0x5839510 adinternalerrorcode4 nslocalizedfailurereasonapplication has iad network configuration error now try on the deviceerr domainaderrordomain code1 the operation couldnat be completed aderrordomain error 1 userinfo0x19c8c0 finally i find something on googlethis guy is saying it seems to be an issue with ios 42so i try again using ios 40 iphone simulatoryay i get yet another error codeerror domainaderrordomain code0 invalid data,"['ios', 'objective-c']" +193839,android how can i rotate an arrow image around a fixed point i have an arrow image that i want to rotate from 0 to 180 degree like the needle in a meter one point of the arrow is fixed in middle and at bottom of the screen and head of arrow should move length of arrow is fix it is image also i have two buttons and i want arrow to turn left when button left is touched and turn right when right button is touchedwhat is the logic of this process,['android'] +193846,java read line from file my program must read text files line by linefiles in utf8i am not sure that files are correct can contain unprintable charactersis possible check for it without going to byte levelthanks,['java'] +193872,to if if if or to if else if else if else i am writing some code for data analysis and have to exclude samples based on some criteria in practice i end up writing code such asbool testsampletype sample if subtest1sample return false if subtest2sample return false if subtest3sample return false return truethe following seems equivalent to mebool testsampletype sample if subtest1sample return false else if subtest2sample return false else if subtest3sample return false else return trueis there a difference in terms of computing cost is there a arguable preferential one in terms of extendibilitymaintainability aesthetics etci know this is probably an inconsequential issue but once i get these questions stuck in my head i need to find the answerps in case anyone cares my actual code as of 1509 can be found at the following,"['c++', 'c']" +193896,java integer flag and bitwise operations for memory reduction is using an integer flag and bitwise operations an effective way of reducing the memory footprint of high volume objectsmemory footprintit is my understanding that commonly a boolean is stored as an int in a jvm implementation is this correct in which case surely the 32 flags represent a large memory footprint reductionalthough of course the jvm implementations vary so this may not always be the caseperformanceit is my understanding that cpus are very number driven and bitwise operations are about as efficient as things come in computingis there a performance penalty or even gain to using bitwise operations over boolean operationsalternativesis there a better way of accomplishing the same thing does an enum allow the combination of flags ie flagx flag1 flag2example codenote the last method propogatemove is recursive and may be called many hundreds of times per second and has a direct effect on the responsiveness of our application hence the usage of flags to avoid logic bits and calling other methods flags helper functionsprivate final void setclearint mask boolean set if set setmask else clearmask private final void setint mask flags mask private final void clearint mask flags mask private final boolean testint mask return flags mask mask flags private static final boolean horizontal trueprivate static final boolean vertical falseprivate static final int orient 0x01private static final int thisplay 0x02private static final int hshrink 0x04private static final int vshrink 0x08private static final int shrink hshrink vshrinkprivate static final int tile image 0x010private static final int cursor 0x020private static final int mouseinside 0x040private static final int mouseinside blocked 0x080private static final int constrain 0x0100private static final int constrain descendent 0x0200private static final int place 0x0400private static final int place descendent 0x0800private static final int reflow constrain constrain descendent place place descendentprivate static final int pack 0x010private static final int clip 0x020private static final int has width slack 0x040private static final int has height slack 0x080private static final int align top 0x010private static final int align bottom 0x020private static final int align left 0x040private static final int align right 0x080private static final int aligns align top align bottom align left align rightprivate static final int align topleft align top align leftprivate static final int align topright align top align rightprivate static final int align bottomleft align bottom align leftprivate static final int align bottomright align bottom align rightprivate static final int enter trap 0x0010private static final int leave trap 0x0020private static final int move trap 0x0040private static final int move trap 0x0080private static final int children read trap 0x010private static final int children trap 0x020private static final int place clean 0x030private static final int shrink trap 0x040private static final int hshrink trap 0x10private static final int vshrink trap 0x20private static final int unused 0x40private static final int unused 0x80 flags in switch get align value as a string from align flags private js aligntojs switchflags aligns case align topleft return sc align topleft case align bottomleft return sc align bottomleft case align topright return sc align topright case align bottomright return sc align bottomright case align top return sc align top case align bottom return sc align bottom case align left return sc align left case align right return sc align right case 0 center return sc align center default throw new errorthis should never happen invalid alignment flags flags aligns flags in logic private final boolean propagatemoveint mousex int mousey throws jsexn start with preevent move which preceeds enterleave if test move trap if interpretercascade prevented justtriggertrapssc move jsut move cascade prevention induces leave propagateleave propagate cascade prevention return true remark anything from here on in is a partial interruption relative to this box so we can not call propagateleave directly upon it int i boolean interrupted false if testpack absolute layout allows for interruption by overlaying siblings for box b getchilditreesize1 b null b getchildi if btestthisplay continue if interrupted bpropagateleave continue int b mx mousexgetxinparentb int b my mouseygetyinparentb if binsideb mx b my if bpropagatemoveb mx b my interrupted true else bpropagateleave else packed layout interrupted still applies plus packedhit shortcut boolean packedhit false for box b getchilditreesize1 b null b getchildi if btestthisplay continue if packedhit bpropagateleave continue int b mx mousexgetxinparentb int b my mouseygetyinparentb if binsideb mx b my packedhit true if bpropagatemoveb mx b my interrupted true else bpropagateleave child prevented cascade during movemove which blocks enter on this box invoking leave if necessary if interrupted if testmouseinside if testmouseinside blocked mouse previously inside now blocked so invoke leave setmouseinside blocked if testleave trap justtriggertrapssc leave jsut else mouse not previously inside enter not yet triggered so do not invoke leave setmouseinside setmouseinside blocked propagate cascade prevention return true set cursor if applicable to this box if testcursor surface s getsurface if snull scursorset scursor jsutostringgetandtriggertrapssc cursor scursorset true fire enter traps if testmouseinside setmouseinside if testenter trap justtriggertrapssc enter jsut finish postevent move which follows enterleave if testmove trap if interpretercascade prevented justtriggertrapssc move jsut propagate cascade prevention return true propagation uninterrupted return false,['java'] +193902,mysqlwriting file error errcode 28 i have the following error with one of our web applications query3 failed error writing file tmpmy1fnqpm errcode 28 insert maillist removed the rest of the query for security reasonsany ideas is this some hard thisk space issue on my server,['mysql'] +193911,close spinner on click outside of spinner i want to close an android spinner once i click outside of the spinner is that even possible,['android'] +193917,numpy reverse multidimensional array what is the simplest way in numpy to reverse the most inner values of an array like thisarray1 1 1 2 2 2 2 3 3 3 3 4 1 1 1 2 2 2 2 3 3 3 3 4so that i get the following resultarray2 1 1 1 3 2 2 2 4 3 3 3 2 1 1 1 3 2 2 2 4 3 3 3thank you very much,['python'] +193939,why does formatting a datetime as a string truncate and not round the milliseconds when a double is formatted as a string rounding is used egconsolewriteline123456tostringf0outputs12346however when a datetime is formatted as a string truncation is used egvar ci cultureinfoinvariantculturevar datetime datetimeparse20110914t1518429 ciconsolewritelinedatetimetostringo ciconsolewritelinedatetimetostrings ciconsolewritelinedatetimetostringymmhhthhmmssf cioutputs20110914t1518429020110914t15184220110914t1518429what is the reasoning if any behind this behaviorrounding to nearest second can be achieved by adding half a second before formatting as a stringvar ci cultureinfoinvariantculturevar datetime datetimeparse20101231t235959 ciconsolewritelinedatetimetostrings civar roundeddatetime datetimeaddmilliseconds500consolewritelineroundeddatetimetostrings cioutputs20101231t23595920110101t0,"['c#', '.net']" +193951,javascript closures vs php closures whats the difference what are the differences between closures in js and closures in php do they pretty much work the same way are there any caveats to be aware of when writing closures in php,"['php', 'javascript']" +193957,why response expectedcontentlength always return 1 void connectionnsurlconnection connection didreceiveresponsensurlresponse response uiapplication sharedapplicationnetworkactivityindicatorvisible yes ifrecieveddata length recieveddata setlength0 download size response expectedcontentlengthi have this code download size is nsintegerexpectedcontentlenght always return 1maybe someone know why i tried use long but effect was the samethanks for help,"['iphone', 'ios']" +193981,windows 8 c and metro gui samples so i look at this windows build keynote 14256 and i just do not get it what i can use to create gui from c andor gui language that will be capable to call functions from my c code html xaml or what and where to see code sample of doing markup call code and code create gui sample with c for windows 8 metro apps,['c++'] +193994,is there any fully generic version of mapget ie v getk key since mapget is not fully generic we often find cases where a developer passed a different type of object and hence bugs frequency of such cases went up when we started using artifactsservices from other teams what are the reasons why mapgetobject key is not fully generic explains why get is not fully genericsince we do not really have use cases of two objects belonging to different types but semantically being equal having a version of mapget would really help us identify such bugs at compile time any apis that can be used in production exist,['java'] +194028,access ios dictionary programmatically i am looking for a way to access ios dictionary programmatically what i need is to retrieve the list of the words of a particular language from inside a custom app is it possible are there any api that provide this or similar functionality i have checked apple documentation but did not find anything usefulmay someone point me to the right direction,"['objective-c', 'ios']" +194039,showhide tables with jquery i have a series of tables similar to the following html codetable idfilmtr th class1head content 1th tr tr td class1body content 1td trtabletable idfilmtr th class2head content 2th tr tr td class2body content 2td trtablei want the tables to expand individually when the respective head th is clicked moreover the tables should start unexpanded i use the following jquery scriptdocumentreadyfunction film tdhidedocumentreadyfunctionvar n1 0 film th1clickfunction ifn1 0 film td1show n1 1 else film td1hide n1 0 var n2 0 film th2clickfunction ifn2 0 film td2show n2 1 else film td2hide n2 0 however when i execute only the top table is able to showhide not the second onecan anyone see where i am going wrong,"['javascript', 'jquery']" +194040,django one view multiple urls i am fairly new to both python and django and would like to follow best practices where possible i would like to tidy up the following code to make it easier to work withi am trying to set up a view which can be accessed through multiple urls which provide different parameters for which a queryset will be returned and thisplayedi have set up the following urls urlrmyrecords login requiredrecordlistviewas view filter all namemyrecords urlrmyrecordspageppage09 login requiredrecordlistviewas view filter all namemyrecords urlrmyrecordspyeard4 login requiredrecordlistviewas view filter year namemyrecords urlrmyrecordslastpmonths0912months login requiredrecordlistviewas view filter month namemyrecordsthen in my view i have something like this there are actually several other parameters but these should remain the same regardless of the url entereddef get querysetself if selfkwargsfilter month x months ago datetimedatetoday datetimetimedeltaintselfkwargsmonths 365 12 queryset recordobjectsfilteruserselfrequestuser date gte x months agoisoformat elif selfkwargsfilter year queryset recordobjectsfilteruserselfrequestuser date yearselfkwargsyear else queryset recordobjectsfilteruserselfrequestuserthis seems very messy to me is there anyway i can make it cleaner is it possible to put the filter parameters in some sort of data structure and then just pass them to the recordobjectsfilter line rather than writing the whole thing out multiple timesany advice would be greatly appreciatedthanks,['python'] +194049,what is a constant reference not a reference to a constant a pretty theoretical questionwhy constant references do not behave the same way as constant pointers and i can actually change the object they are pointing to they really seem like another plain variable declaration why would i ever use them this is a short example that i run which compiles and runs with no errorsint main int i0 int y1 intconst icri icry can change the object it is pointing to so it is not like a const pointer icr99 can assign another value but the value is not assigned to y int x9 icrx couticr icr yyendl,['c++'] +194067,constexpr undefined behaviour i have been experimenting with constexpr on my test compiler g 46 this fails to compile with an error about out of bounds access is a compiler required to spot this at compile timeinclude iostreamconstexpr const char str hiconstexpr int fail return str10 way past the endtemplate int nstruct foo static void print stdcout and stdendl int main foofailprint,['c++'] +194091,why does sendkeysend only work once in a while i am making a windows application that captures keyboard input globally when a user uses the ctrl alt g shortcut combo the application uses sendkeysendguidnewguidtostringto type a generaged guid into whatever text field is in focus and it should do this regardless of the application taking the inputit works exactly as i intended the first time you type ctrl alt g but subsequent attempts result in nothing or just very infrequent successesi mean it all should be very simple and consistent i have a working global keyboard hook which works all the time i have tested it but the sendkeysend method does not work every timei have looked all over google at anything related to my issue but nothing has worked so far anyone have any insightedit 1i have tried using sendkeysendwait as well does the same thing i really want a more responsive way to generate new guid using this keyboard shortcut approach edit 2below is the essential parts of the code initialization code here register the event that is fired after the key presshookkeypressed new eventhandlerkeypressedeventargshook keypressed register the control alt f12 combination as hot keyhookregisterhotkeyuinthotkeymodifierscontrol hotkeymodifiersalt keysgthe event code is quite simplevoid hook keypressedobject sender keypressedeventargs e sendkeyssendwaitguidnewguidtostringeverything else in my project is just fluffupdate 1 i do have more questions about this subject but i am out of time to continue working on this for today i have implemented jon raynors suggestion of using the appconfig approach to some degree of success once i isolate my new problems i will post an edit and possibly close this question if i get my application functioning as intended,"['c#', '.net']" +194111,why does 006 001 007 in coldfusion why do not math operations in coldfusion seem to be affected by floating point math issues take the coderesult 006 001writedumpresultwritedumpresultgetclassgetnamewhich outputs007 javalangdoublehowever the equivlant java code produces what id expect when adding two doublespublic static void mainstring args double a 001d double b 006d systemoutprintlna b 0069this is what i would expect to see from coldfusion because of the realities of floating math goldberghtml does coldfusion do some magic behind the scenes or am i looking at an isolated anomaly here,['java'] +194129,python rpm i built would not install because i have to install multiple versions of python on multiple oracle linux servers which are built via a kickstart process i wanted to build a python rpm for our yum repository i was able to build python manually using make altinstall which does not install over your default system python installation so i thought that would be the way to goafter much trial and error i managed to build an rpm starting with a bz2 python 27 package but now when i try to install it i get an error error failed dependencies usrlocalbinpython is needed by python2721i386what the python is what i am trying to install and system default python 24 is in usrbinpython and my prototyping location for the python directory is tmppython27 and the executable was tmppython27binpython27 so why is it looking in usrlocalbinhere is the core of my rpm specprepsetup qbuildconfigure prefixtmppython27makeinstallmake altinstalli take a closer look at the rpm build log and i seerequires binsh tmppython27binpython27 usrbinenv usrlocalbinpython libcso6 libcso6glibc 20a lot moreok so there is where usrlocalbin comes in now the question is how is it determining these requirements did i specify something wrong do i need to override somethinglike many rpm newbies i get the build part but i do not really grok what happens at the end of rpmbuild and what actually gets put into the rpm file other than the files you specify in files and then what actually happens when you do the rpm installcan anyone suggest why my install is failing or what i might read to understand why my rpm build is requiring what i am trying to build,['python'] +194131,android webview web page not available when using a webview view in my app no matter what page i force it to visit it says web page not found here is my codemainactivityjavapackage comtestingwebviewimport androidappactivityimport androidosbundleimport androidwebkitwebsettingsimport androidwebkitwebviewpublic class mainactivity extends activity override public void oncreate bundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain webview webview webview findviewbyidridwebview1 websettings websettings webviewgetsettings websettingssetbuiltinzoomcontrolstrue webviewloadurl mainxmlxml version10 encodingutf8linearlayout xmlnsandroid androidlayout widthfill parent androidlayout heightfill parent androidorientationvertical webview androidididwebview1 androidlayout widthfill parent androidlayout heightfill parent linearlayoutit is very basic code as you can see there is indeed an internet connection as i can open the normal browser app and visit any webpage like normal,['android'] +194150,what text editor for windows or linux supports objectivec syntax this question might look like a duplicate but it is noti am not looking for a full ide to program iphone apps on i am looking for a text editor for windows or linux that recognizes objectivec syntax i know notepad does but it really is painfulwhat i need is an editor thatautocompletes braces not possible with notepadautomatically inserts a new line at the end of the file not possible with notepadhighlights syntax possible with notepadautocompletes directives class names andor method names not possible with notepadthanks,['objective-c'] +194167,uncaught typeerror when using a javascriptinterface i am currently thisplaying a bunch of data to the user as html in a webview i have some links below each entry that should call a method in my app when clicked the android webviews javascript interface seems to be the best only way of handling these things however whenever i click the link i get this error message errorweb console6112 uncaught typeerror object my namespace4075ff10 has no method edit at base url55i have the following interface declaredpublic class javascriptinterface context context javascriptinterfacecontext c context c public void editstring postid logdmyapp edit do stuff i then add it to my webviewfinal webview threadview webview findviewbyidridwebviewthreadthreadviewgetsettingssetjavascriptenabledtruethreadviewaddjavascriptinterfacenew javascriptinterfacethis androidand finally i call this within my html as followsdiv classpostactions div classright a onclickandroidedit4312244edita divdivthe real kicker is this all works when i am debugging my app via the emulator or adb connection to my phone when i build and publish the app it breaksi am at my wits end any help or advice would be greatly appreciated,"['javascript', 'android']" +194170,threadingcondition vs threadingevent i have yet to find a clear explanation of the differences between condition and event classes in the threading module is there a clear use case where one would be more helpful than the other all the examples i can find use a producerconsumer model as an example where queuequeue would be the more straightforward solution,['python'] +194182,rodbc queries returning zero rows issue rodbc falsely returning zero rowssituationi am using rodbc to connect to a dsn i created using a commercial dbs odbc driver osi softs pi historian time series db if youre curious libraryrodbc piconn odbcconnectpirv uid pidemo sqlstr select tag time status value from piinterp where tag pw1plant1production rate and time date4h and timestep 2mnow if i query i get zero rows sqlquerypiconn sqlstr1 tag time status value 0 rows or 0length rownameswith believenrows false these all still show zero results even though it should return 120 rows sqlquerypiconn sqlstr believenrows false sqlquerypiconn sqlstr believenrows false max 0 sqlquerypiconn sqlstr believenrows false max 0 buffsize 120what else can i tryproof that there should be many rowsin excel or command promptselect tag time status value from piinterp where tag pw1plant1production rate and time date4h and timestep 2mwith resultstag time status valuepw1plant1production rate 15092011 933 448 0pw1plant1production rate 15092011 931 452 0pw1plant1production rate 15092011 929 390 0pw1plant1production rate 15092011 927 419 0pw1plant1production rate 15092011 925 413 0pw1plant1production rate 15092011 923 393 0pw1plant1production rate 15092011 921 427 0etcboth in r and in excel if i query for a tag that does not exist say tag ae11 it correctly returns zero rowsadditional infosql tables sqltablespiconn table qualifier table owner table name table type remarks1 na na pialias table pialias2 na na piavg table piavg3 na na pibatch table pibatch4 na na picomp table picomp5 na na piinterp table piinterpodbc info odbcgetinfopiconn dbms name dbms ver driver odbc ver data source name driver name driver ver odbc ver server name pi 03040370 0201 pirv piodbc32dll 01030100 03520 aurvyzpis1 my session info sessioninfor version 2122 20110225platform i386pcmingw32i386 32bitlocale1 lc collateenglish australia1252 lc ctypeenglish australia1252 lc monetaryenglish australia1252 lc numericc 5 lc timeenglish australia1252 attached base packages1 grid stats graphics grdevices utils datasets methods base other attached packages1 ggplot2 089 proto 0392 reshape 084 plyr 16 rodbc 133 loaded via a namespace and not attached1 tools 2122,['sql'] +194190,design a system supporting massive data storage and query i was asked by the interviewer to design a system to store gigabytes of data and the system also has to support some kind of querydescriptionthere are massive amount of records generated in an idc each record is composed of a url an ip which visits the url and the time when the visit occurs the record can probably be stated as a struct like this but i am not sure which data type should i pick to represent them struct record url char ip int visit time time t or simply a numberrequirementsdesign a system to store 100 billion records and also the system gotta support 2 kinds of query at leastfirst given a time period t1 t2 and a ip query how many urls this ip has visited in the given periodsecond given a time period t1 t2 and a url query how many times this url has been visitedi was stumbled and here is my stupid solutionanalysisbecause every query is performed upon a given period of time so1create a set put all visit time into the set and keep the set ordered according to the times value from older to latest2create a hash table using hashvisit time as the key this hash table is called timehashtable then each node in a specific bucket has 2 pointers pointing to another 2 hashtables respectively3the another 2 hashtables would be a iphashtable and a urlhashtableiphashtable uses haship as the key and all the ips in the same iphashtable have the same visittime urlhashtable uses hashurl as the key and all the urls in the same urlhashtable have the same visittimegive a drawing as followstime hastbl visit time ivisit time jvisit time pnil ip hastbl url hastbl so when doing the query upon t1 t2find the closest match from the time set let us say the match is t1 t2 then all the valid visit time will fall into the part of set starting from t1 to t2for each visittime t in the time sett1t2 do hasht and find ts ip hastbl or url hastbl then count and log how many times the given ip or url appearsquestions1my solution is stupid hope you can give me another solution2with respect to how to store the massive records on thisk any advice i thought of btree but how to use it or is btree applicable in this system,['c'] +194199,that codesign returned 1 object ifile format invalid or unsuitable problem again i am working with xcode 41 build 4b110f trying to get my ios app ready for upload it passes the productarchive step with no errors asking twice for permission to sign something but when i try a validate of the archive from the organizer it fails codesigning usersuqrchernlibrarymobiledeviceprovisioning profiles70d2381d37334f5d88b24729572c2864mobileprovision with iphone thistribution ron chernich usrbincodesign force preservemetadata sign iphone thistribution ron chernich resourcerulesvarfoldersulula1ahkngpqq9ftdnulltmtmprybczu3ebdpayloadabradappresourcerulesplist entitlements varfoldersulula1ahkngpqq9ftdnulltmtmprybczu3ebdentitlements plistrz1vwko6 varfoldersulula1ahkngpqq9ftdnulltmtmprybczu3ebdpayloadabradaprogram usrbincodesign returned 1 varfoldersulula1ahkngpqq9ftdnulltmtmprybczu3ebdpayloadabradapp replacing existing signaturevarfoldersulula1ahkngpqq9ftdnulltmtmprybczu3ebdpayloadabradapp object file format invalid or unsuitableerror codesign failed with error 1i have looked at all the similar problems and solutions some of which make no sense whatever or apply to really old versions of the tools none have made the slightest differencei have also checked 3 times that verify is using the production certificate as is the codesign step that produces the archive i have even turned the above output into a schell script so i could try all certificates manually same result every timei have been stuck on this for 3 days now with no joyany suggestions most welcome maybe the app file being signed really is unsuitablebtw codesign has no version flag but the man page is dated june 1 2006 the binary has a file date of nov 20 2010update next dayresearching the problem further found an obscure reference saying that codesign needs the following environment var setcodesign allocatedeveloperplatformsiphoneosplatformdeveloperusrbincodesign allocateusing the output from a failed validate run i created a shell script which exported this var just before the failing codesign force step and viola the codesign worksbut this does not really help me prepare my code for upload is there a way to include this into the script run by the organizer validate buttona little later still the solution under the theory there is a script someplace which generates all the commands run during an organizer validate run i did some digging with grep and find the script indeed exists and it is name isdeveloperplatformsiphoneosplatformdeveloperusrbinpackageapplicationit is just perl and the fix is to add the required environment var to the associative array env right at the start say at line 72envcodesign allocate developerplatformsiphoneosplatformdeveloperusrbincodesign allocatethis totally fixes the problem i have no idea where all the other posters on the web who think they fixed it by combinations of deleting certificates building clean shutting down and restarting xcode etc etc are coming from i will just quietly assert that this fix favors science over superstition and works for me under xcode 41 build 4b110f and its associated packageapplication script running under snow leopard 1068 with perl 5100,['ios'] +194230,how to find the thistance between two zipcodes using java code my requirements are similar to this question except the fact that i am prohibited to use the latitude and longitude values i want to caluclate the walking thistance between two zipcodes later i would also require to query who is within x kms i am not sure whether it is achievable or not is it really possible to find the thistance between two given zipcodes i do not want the answers which will work only for usuk zip codes i need a generic solution which will work for any two zipcodes of the world if the calculation of thistance without using langitude longitude is not possible than can i get the langitude longitude values of a given zipcode amazing but how any tutorial example will be of great helpsince i am working on a commercial project cant use the google maps api so please do not suggest any other licensed servicesthanks in advanceupdateone of the answers of this question suggests the use of mysql or postgress will that work for me,['java'] +194300,nonpointer typedef of member functions not allowed after getting an answer to this question i thiscovered there are two valid ways to typedef a function pointertypedef void function typedef void pfunction void foo function p foopfunction q fooi now prefer function p to pfunction q but apparently this does not work for pointertomember functions consider this contrived exampleinclude iostreamstruct base typedef void base callback remove this and put it below ie cb callback cb void go thiscb virtual void x 0 base cb basex struct d1 public base void x std cout d1n struct d2 public base void x std cout d2n int main d1 d1 d2 d2 d1 go d2 go but if i change it to the new preferred style typedef void base callback and callback cb i get a compiler error at the point of typedefextra qualification base on member callbackdemo for errorwhy is this not allowed is it simply an oversight or would it cause problems,['c++'] +194323,objectivec and uml modelling we all know objectivec method headers carry more information than standard java method headersthis poses an issue when modelling using umlsome method names are uncontrollably quite longwhat is the best way to model these methods clearly in a uml class diagramcan you condense the method names or write some java style header for themi am doing a report for a software system and i am stuck,"['iphone', 'objective-c']" +194328,how to check if cursor exists open status how do i check if a cursor is open or not because many times i am encountering the error cursor already exists please let me know how can i check whether a cursor is already in open statusin fact i have closed as well as deallocated it at the end close ppm cursor deallocate ppm cursor but still i am getting the same error what could be the reason,['sql'] +194333,how object objects return strings java if object is the mother of all classes in the hierarchy how can he implement a method returning an object of a child class eg tostring returns a string object,['java'] +194338,sqlite how to get all table names in database what do you think would be the right way to get all table names from a database and add them to a listright now got that farfinal arrayliststring dirarray new arrayliststringsqlhelper sqlhelper new sqlhelperthis tkdb null 1sqlitedatabase db sqlhelpergetwritabledatabasecursor c dbrawqueryselect name from sqlite master where typetable nullcmovetofirstwhile cisafterlast false dirarrayaddn cgetcolumnindexname cmovetonext cclosebut it outputs some android metadata instead of my table names so guess there is something wrong with the querythanks,"['java', 'android']" +194342,difference between sqrt and sqrtf i want to consider to code first it isinclude iostreaminclude cmathinclude mathhusing namespace stdint main int s 25 cout sqrts endl return 0it gave me this mistakecusersdatuashvilidocumentsvisual studio 2010projectstrainingtrainingtrainingcpp9 error c2668 sqrt ambiguous call to overloaded function1 cprogram filesmicrosoft visual studio 100vcincludemathh589 could be long double sqrtlong double1 cprogram filesmicrosoft visual studio 100vcincludemathh541 or float sqrtfloat1 cprogram filesmicrosoft visual studio 100vcincludemathh127 or double sqrtdouble1 while trying to match the argument list int build 0 succeeded 1 failed 0 uptodate 0 skipped if i add type float in brackets in front of s like thisinclude iostreaminclude cmathinclude mathhusing namespace stdint main int s 25 cout sqrtfloats endl return 0i got as i would guess 5 and another variant is that instead of sqrt if i write sqrtfinclude iostreaminclude cmathinclude mathhusing namespace stdint main int s25 cout sqrtffloats endl return 0i also got 5what is the difference between them does it means that sqrtf is same as sqrt for the float type,['c++'] +194363,delayed jobs save completed jobs is there a parameter i can pass to delayed job that will prevent it from deleting completed jobs from the delayed jobs tablekind of like the destroy failed jobs but for completed jobsany ideas,['ruby-on-rails'] +194365,how to get integer thread id in c11 c11 has a possibility of getting current thread id but it is not castable to integer typecoutstdthis threadget idendloutput 139918771783456coutuint64 tstdthis threadget idendlerror invalid cast from type astdthreadida to type auint64 tasame for other typesinvalid cast from type astdthreadida to type auint32 tai really dont want to do pointer casting to get the integer thread id is there some reasonable waystandard because i want it to be portable to do it,['c++'] +194369,what are parametric and inclusion polymorphism in c i am reading some c text at the address in the section universal polymorphism the author mentioned about parametric and inclusion polymorphisms i am not quite sure that i understand the point especially why parametric polymorphism is implemented at compile time while inclusion polymorphism is implemented at run timecan anyone give me a clear explanation or an example please,['c++'] +194380,backbonejs in a view whats the difference between el and tagname i am trying to wrap my head around this concept can you dumb this down for me and maybe provide a simple example of the difference between the el attribute and the tagname attributein some examples different views use el sometimes and others use tagnamei am specifically messing around with my own implementation of this example,['javascript'] +194389,is this safe to unsubscribe dowork after calling runworkerasync but before the function exits i have many methods they only run one at a time though they all use the same runworkercompleated and progresschanged methods but they all have different dowork methods is it safe to do the followingprivate void button process clickobject sender eventargs e bgwork processdowork scrub dowork bgwork processrunworkerasync bgwork processdowork scrub doworkor can i hit a edge case doing this i did not see anything on the msdn on it saying it was not allowed and it as so far run fine in my program but i wanted to check here to see if anyone has run in to trouble doing this,"['c#', '.net']" +194403,how to include text file into javascript is there any way to load some text from another file into javascript without server side codei was thinking to use another element to hold the text inside some comments but i do not know how to read it is source code with javascriptsomething likescript srcmyfilejsscriptscript function readmytext scriptin myfilejs some text,['javascript'] +194407,embeddable wysiwyg equation editor do you know of a wysiwyg equation editor like dragmath implemented in javascriptmathml or flash i could embed dragmath as well but i was wondering if there is a way to have a good wysiwyg formula editor without requiring the users to run a java appletthanks,['javascript'] +194410,how do i extract the property name and value being passed into an expression let us assume i have a method like thispublic static listt gethis someobjectt expressionsfunctbool eget the property name and value they want to check is true falsetheobjectgetx xpropertyname somevaluehow do i get propertyname and somevalue when i pass it into the get extension method,['c#'] +194412,using fiddler with java and eclipse i am trying to hook up fiddler to a java unit test in eclipse so i can see the soap request when our web service is being calledit works automatically in our net harness but is there some setting that needs to be applied for java thanks,['java'] +194426,how to prevent an iframe from reloading when moving it in the dom i have an iframe loaded with some content i would like to move it inside the dom without causing a refresh i like the content inside it i want to keep iti am doing some basic nodeappendchildiframe to do the jobis that possiblethanks in advance for your help,['javascript'] +194440,printf thisplays something weird there is such codeinclude stdiohint main float d 10 int i 2 printfd d d i getchar return 0and the output is 0 1072693248i know that there is error in printf and first d should be replaced with f but why variable i is printed wrong 1072693248 instead of 2,['c'] +194443,creating segments in video i am using python 27 pygtk 224 and pygst gstreamerto ensure smooth playback from one clip to another without a blink i combined all the clips i needed into one larger video this lets me seek to the exact place i need in code one of the clips is like a fillin which should loop whenever one of the other clips is not playinghowever to make my code easier and more streamlined i want to use segments to define the various clips within the larger video then at the end of each segment i know there is a segment end event i seek to the fillin clip when i need another clip i just seek to that segmentmy question is how exactly do i create these segments i am guessing that would be the event new new segment but i am not sure can i create multiple clips to seek with using this function is there another i should use are there any gotchas to this method of seeking in my video that i should be aware ofsecond how do i seek to that segementthank you,['python'] +194449,c cannot declare delegate within a method i am really blanking out here i am wondering why i cannot declare a delegate type within a method but rather i have to do it at a class level namespace delegate learning class program works fine public delegate void anon delgateint i static void mainstring args havefun consoleread public static void havefun throws an error delegate void anon delgateint i anon delgate ad delegateint i consolewritelineitostring edit i am researching lambda expressions and backing up into how it was before lambdas for my own personal knowledge,"['c#', '.net']" +194477,protect string constant against reverseengineering i have android application that has hard coded static string constants credentials userpass for sending emails via smtpthe problem is that dex file in apk can be easily reverseengineered and everybody can see my passwordis there a way how to secure these credentials while i will still be able to use them in my classes,"['java', 'android']" +194480,linq get values not shared across multiple lists whats the most efficient way to write a method that will compare and lists and return all the values that do not appear in all lists so thatvar lists new listlistint new listint 1 2 3 4 new listint 2 3 4 5 8 new listint 2 3 4 5 9 9 new listint 2 3 3 4 9 10 public ienumerablet getnonsharedthis ienumerableienumerablet lists fast algorithm hereso that listsgetnonsharedreturns 1 5 8 9 10i had public ienumerablet getnonsharedthis ienumerableienumerablet lists return listselectmanyitem item exceptlistsaggregatea b aintersectbbut i was not sure if that was efficient order does not matter thanks,['c#'] +194524,is it possible to register for preshutdown service events using net i have run into a situation where i deployed a net c service on a win 2008r2 server the service has a dependency on msmq at shutdown it needs to send a couple of quick messages before terminating this works fine with manually triggered onstop events but when the server is shutting down and the scm calls onshutdown i am finding that msmq has already shutdown and my service cannot properly cleanup my service only needs 25 seconds to do it is worki understand now that service dependencies only apply to startup so that is not helping i spent some time today trying to figure out how to register my service to accept the newly since vista available service accept preshutdown events and work with the preshutdownorder feature but this is not supported in the servicebase as implemented in the framework as far as i can telli went down the path of trying to manually set it using the setservicestatus function but it does not appear to work servicehandle thisservicehandleservice status servicestatus new service statusservicestatuscurrentstate intstateservice runningservicestatuscontrolsaccepted intcontrolsacceptedservice accept preshutdown controlsacceptedservice accept stopservicestatuswaithint 0servicestatuscheckpoint 0bool setstatus setservicestatus servicehandle ref servicestatusint error marshalgetlastwin32errorthis returns an error status of 13 when you call getlasterrorany ideas for how to hook into the preshutdown service events,['c#'] +194534,how to query code first entities based on rowversiontimestamp value i have run into a case where something that worked fairly well with linq to sql seems to be very obtuse or maybe impossible with the entity framework specifically i have got an entity that includes a rowversion property both for versioning and concurrency control something likepublic class foo key maxlength50 public string fooid get set timestamp concurrencycheck public byte version get set i would like to be able to take a entity as input and find all of the other entities that are more recently updated something likefoo lastfoo getsomefoovar recent mycontextfooswheref fversion lastfooversionnow in the database this would work two rowversion values can be compared to one another without any problems and i have done a similar thing before using linq to sql which maps the rowversion to systemdatalinqbinary which can be compared at least to the extent that the expression tree can be mapped back to the databasebut in code first the type of the property must be byte and two arrays cannot be compared with the regular comparison operators is there some other way to write the comparison of the arrays that linq to entities will understand or to coerce the arrays into other types so that the comparison can get past the compiler,['c#'] +194535,unsafe javascript attempt to access frame with url i have incorporated vimeo into a wordpress theme i am building and i get these errorsunsafe javascript attempt to access frame with url from frame with url domains protocols and ports must matchunsafe javascript attempt to access frame with url from frame with url byline0portrait0 domains protocols and ports must matchit also i think is the reason for the page still loading,['javascript'] +194543,popupwindow animation not working i has a nice popupwindow which i want to appear with an animation i do it like thispopupsetanimationstyleranimappearpopupshowatlocationpopupmenulayout gravity offsetx offsetyi then set up a listener for changing the animationpopupsetonthismisslistenernew popupwindowonthismisslistener override public void onthismiss popupsetanimationstyleranimthisappear but hey it would not work neither for resanimappeartranslate xmlnsandroid androidfromydelta100 androidtoydelta0 androidduration10 nor for resanimthisappeartranslate xmlnsandroid androidfromydelta0 androidtoydelta100 androidduration10any clues,['android'] +194560,jquery callback on image load when changing the src i am changing the img src once i have loaded a json file all this works fine but i want to make sure the image is completely loaded which i can do using oneloadfunction alertimage has load yay but after reading various posts that not all browsers fire the load if the image is in cache i do not seem to be getting this problem in the browser that are meant to cause this issue but i have only test ff602 chrome1307 and safari505 on a mac now i am sure ie must have a problem and is it only pc related i am running pretty recent versions of the browsers so has something changed in these to now fire load or my other thought is i am running the latest version of jquery 163 has load been changedi am hoping it is all to do with running the latest jquery but if not and it is an older browser issue then i need to put in a fix i have tried a couple of solution on this site for examplejquery loading images with complete callbackand also some of the comments on the load api page but i cannot seem to get them to work the first one does not work at all and the second one seems to fall over with the eachthis is the code i have so far which seems to work ok but cannot be sure as maybe an older browser issuesgetjsonjsonurl functionjson aimgzoom imgattrsrc jsonimageidlargeimageoneloadfunction alertthe image has loaded do something here aimgzoomattrhref jsonimageidlargeimage thanks in advance for any helpb,['jquery'] +194565,is there a way to find leaked memory using a core file i have a core dump from an application with a memory leak i have used the strings command and xdd to examine the file and i have got a few ideas of which part of the program might be responsible for the leak i am able to run up the core file in gdb with the application but i cannot do a lot of testing with it because it is an embedded application with lots of complex time based io which i cannot simulate in the officei have also heard that running with various memory leak detection utilities will slow down the app which we cannot afford because it is running at near cpu capacity alreadyso for now all i have is this core file example of what i am looking for is there a pointer table i can examine to find memory that is been allocated which i can then use to try and find stuff that should have been freed but has not been,['c++'] +194567,remove styles from text when copying cutting using css or javascript yoalright been noodling on this one for a while how copycut styled text without bringing along any style baggage backgroundcolor color etccouple of routes of attacks that have been foiledstyle the text differently using select does not work style is not copiedstyle the selected text using jquerys select binding this only works for inputs not p divsintercept and remove style by binding an event to copypaste using jquery cannot access the copied object to remove stuff tried using epreventdefault then returning the event object but that did not work eithermodify the clipboard data once it is been saved also no dice most browsers wont let you into this without flash and some sort confirmationanyway thoughts seems like it would be very useful for sites that have white background colors,"['javascript', 'jquery', 'css']" +194569,documenting div sections use title attribute i am looking for the most terse way to document sections of my page eg div sectionsanything wrong with using the title attribute egdiv titlepayment area classform div ps in case relevant i am using the intellij ide but new to its various capabilities eg automatic formatting control and other ways to be able to easily understand sections of my pages,['html'] +194578,how to have same font for the text that is copied from wordpad into textarea i have a text area in my web application my users can copy text from wordpadand paste it in textarea they want the same text font of the wordpad document to be appear in textarea too how can we achieve this,"['javascript', 'html', 'css']" +194580,how do you log all events fired by an element in jquery i would like to see all the events fired by an input field as a user interacts with it this includes stuff likeclicking on itclicking off ittabbing into ittabbing away from itctrlc and ctrlv on the keyboardright click pasteright click cutright click copydragging and dropping text from another applicationmodifying it with javascriptmodifying it with a debug tool like firebugi would like to thisplay it using consolelog is this possible in javascriptjquery and if so how do i do it,"['javascript', 'jquery']" +194586,why is my background color not showing if i have thisplay inline html body div stylethisplay inline backgroundcolor 5 h3testh3 div bodyhtmlhere is my code i am wondering why my background color is not showing if i change css thisplay from inline to block then it show up why is it not showing up if thisplay is inline i am trying to understand the reason of the problem other than looking for a solution,"['html', 'css']" +194633,weird c template const problem i do not understand why the output of this program is second method instead of first methodinclude iostreamtemplate class tvoid assignt t1t t2 stdcout first method stdendltemplate class tvoid assignt t1const t t2 stdcout second method stdendlclass apublic aint a aaprivate int a friend a operatorconst a l const a ra operatorconst a l const a r friend a operatorconst a l const a rreturn al ar aint main a a1 const a b2 assignaabhowever when i change my main function to thisint main a a1 const a b2 a cab assignacthe output is first methodany ideas,['c++'] +194656,adding elements to jlist in swing java i have a function that executes when a button is clicked suppose there is a loop to add 1 to 10 to a jlist i add that data to defaultlistmodel it works perfectly and the numbers get added then i added a threadsleep10 within the loop but the output is different i wanted to add 1 element every second but now it waits for 10secs and the add all 1 to 10 together at the end of 10th second am i wrong anywherelist processlist listnumbersgetselectedvalueslistdefaultlistmodel resultlist new defaultlistmodellistresultsetmodelresultlistfor int i 0 i processlistsize i resultlistaddelementstringvalueofi try threadsleep10 catch interruptedexception ex,['java'] +194671,android how to show notification on screen i have been working on push notifications and i am able to implement it and thisplay it on status bar the problem i am facing is that i want to thisplay it even if the phone is lock under the lock screen where it says drag to unlock i have seen notifications like that but cant find any example to thatexamplejust like when you received a missed call it will show it under the lock button on your screencodestring ns contextnotification servicenotificationmanager mnotificationmanager notificationmanager getsystemservicensint icon rdrawableicon launchercharsequence tickertext myapplicationlong when systemcurrenttimemillisnotification notification new notificationicon tickertext whennotificationdefaults notificationdefault soundnotificationdefault vibratenotificationdefault lightscharsequence contenttitle thistitlecharsequence contenttext thismessageintent notificationintent new intentthis mainactivityclasspendingintent contentintent pendingintentgetactivitythis 0 notificationintent 0notificationsetlatesteventinfocontext contenttitle contenttext contentintentmnotificationmanagernotifynotice id notification,['android'] +194673,how are live tiles made in windows 8 i have searched the samples the developer site the getting started and the enhancing bla bla bla pageseven using some search queries on google i cannot seem any information on live tiles in windows 8how do i create a live tile in windows 8 what languages can be used for that c xaml,['c#'] +194686,how do i do dependency parsing in nltk going through the nltk book it is not clear how to generate a dependency tree from a given sentencethe relevant section of the booksubchapter on dependency grammar gives an example figure but it does not show how to parse a sentence to come up with those relationships or maybe i am missing something fundamental in nlpediti want something similar to what the stanford parser doesgiven a sentence i shot an elephant in my sleep it should return something likensubjshot2 i1detelephant4 an3dobjshot2 elephant4prepshot2 in5posleep7 my6pobjin5 sleep7,['python'] +194706,separate test cases across multiple files in google test i am new in google test c framework it is quite easy to use but i am wondering how to separate the cases into multiple test files what is the best wayinclude the cpp files directly is an option using a header seems that does nothingany help is welcome,['c++'] +194711,updating changed attributes with backbonejs so i am setting a model with updated attributesthen in my view i am listening for a change event for this model when that fires i think i should use modelchangedattributes do i pass it a callbackit should return a hash of all the attributes that are updated or new is there anyway to know which are updated and which are newhow should i go about updating once i have this hash of changed attributes parse the object to type of attribute or should i just use higher resolution listeners from the get gothanks,['javascript'] +194712,ormlite query for date i am trying to query for a date between low and hign valuecar car new car1 octaviacarsetmanufacturedcalendargetinstancegettimedaocar integer cardao gethelpergetcardaocardaocreatecarquerybuildercar integer carqb cardaoquerybuildercalendar yesteday calendargetinstanceyestedayaddcalendardate 1calendar tommorrow calendargetinstanceyestedayaddcalendardate 1carqbwherebetweenmanufactured yestedaygettime tommorrowgettimepreparedquerycar query carqbpreparelistcar cars cardaoqueryquerylogdtag carsget0tostringcar object looks this waypublic class car databasefieldid true private int id databasefield string name databasefieldforeign true foreignautorefresh true user user databasefieldforeign true foreignautorefresh true private brand brand databasefieldcolumnnamemanufactured private date manufacturedunfortunaly i am getting no results where could be a problem,['android'] +194723,classvalue in java 7 while browsing the java 7 api documentation i stumbled upon the new class javalangclassvalue with the following rather minimal documentationlazily associate a computed value with potentially every type for example if a dynamic language needs to construct a message thispatch table for each class encountered at a message send call site it can use a classvalue to cache information needed to perform the message send quickly for each class encounteredcan anyone give a better explanation of what problem this class solves and perhaps some sample code or open source project that already uses this classupdate i am still interested in some actual source code or examples using this new classi also found this mail on the mlvmdev mailing list concerning some implementation improvements it was apparently changed from using a weakhashmap to a new private field on javalangclass to make it more scalable,['java'] +194757,ie9 link hover css color change vertical shift ie 9 on hover over a link pushes some of the html down the pagewhen i remove the color from tdsubarea h2 ahover color aa051a textdecoration none the problem does not occuri cannot paste all the code here and fairly sure its a unique problem to this pagebut maybe someone out there has seen something similarits not moving the linka tag down the page its the whole containing table that moves,"['html', 'css']" +194760,androidhow to close progress dialog when back button is pressed how to close progress dialog when back button is pressed,['android'] +194779,how to round up integer division and have int result in java i just wrote a tiny method to count the number of pages for cell phone sms i did not have the option to round up using mathceil and honestly it seems to be very uglyhere is my codepublic class main param args the command line arguments public static void mainstring args string message today we stumbled upon a huge performance leak while optimizing a raycasting algorithm much to our surprise the mathfloor method took almost half of the calculation time 3 floor operations took the same amount of time as one trilinear interpolation since we could not belive that the floormethod could produce such a enourmous overhead we wrote a small test program that reproduce systemoutprintfcount is d intmessagepagecountmessagepublic static double messagepagecountstring message ifmessagetrimisempty messagetrimlength 0 return 0 else ifmessagelength 160 return 1 else return mathceildoublemessagelength153 i do not really like this piece of code and i am looking for a more elegant way of doing this with this i am expecting 3 and not 30 any ideas,['java'] +194797,android maps point clustering is there any code for point clustering in android how can i load thousand pinpoint without having performance issues,['android'] +194820,detect if time format is in 12hr or 24hr format is there any way to detect if the current device of the app uses 12h our 24h format so that i can use one nsdateformatter for 12h and one for 24h depending on the users languageloaction setting just like the uidatepicker detects and shows the ampm picker if it is 12h format,"['objective-c', 'ios']" +194858,how to call stdmin when min has been defined as a macro how do i call stdmin when min has already been defined as a macro,['c++'] +194879,thisable select options based on value through the html only i need to thisable a select option based on the value of a variable the value is similar to one of the select option value and it needs to be thisabledfor exselectoptionvalue aoptionoptionvalue boptionselectvariable some select option valueso if variable is equal to value a then it needs to be thisabled in select optionthanks,"['jquery', 'html']" +194889,how often does a database view get updated in mysql assume i have a view in mysqlcreate view blah as select columna from tableahow often does this view get updated from the underlying table tablea,['mysql'] +194907,how to icmp ping on android i need to do a icmp ping to a host from my android device i need to measure the round trip time i am proficient with android and java just dont know what library to usehow do i do itis it possible via 3g edge,['android'] +194916,jsonobject how to get a value i am using a java class on the following is my code snippetstring jsonresult utilmethodsgetjsonthisjsonurl nulljson new jsonobjectjsonresultgetjson returns the following stringlabeldatasloganawaken your sensesjobsearchjob searchcontactcontactvideoenchanting beachscapescreateprofilecreate profilenowhow do i get the value of slogan i tried all the methods listed on the page but none of them worked,['java'] +194926,crossbrowser resize browser window in javascript i would like to be able to resize the browser window with javascript i do not want to use jquery and the smaller the code the better but it has to work in all of the major browsers including chromeany solutionsthanks for the helpps the tags that this question was tagged with should be combined but i do not know howbrowser same as webbrowsercrossbrowsersame as browser compatibility,['javascript'] +194932,what is the difference between condensed arrays and literal arrays as the title says what is the difference between condensed arrays and literal arraysnew arrayjohn bob sue condensed arrayjohn bob sue literal arrayare there things i can do with one that i cannot do with the other or is it the way it is kept in the memory,['javascript'] +194943,will an empty sqlite cursor return true for isbeforefirst isafterlast both or neither it is a pretty straightforward question i am hoping the answer is both but i am worried it is neither i have scrutinized the android developer docs for sqlitedatabase and cursor but cannot find any definitive answer to this questionthe case i am asking about is where i get a cursor call movetofirst then loop until isafterlast returns true it would be really convenient for a pattern i am coding a few times if that would just work and execute the loop 0 times if the cursor has 0 recordsor do i need to explicitly test for an empty cursor firstedit some of the responses indicate that people are not quite getting what i am asking basically i would like to write thiscursor mydbquerycursormovetofirstwhile cursorisafterlast processrowbut i am not 100 certain that i can isafterlast cannot return anything useful but true for this case but that does not mean it actually does return true for an empty query the docs do not seem to specify what the return value of most of the cursor methods are if the cursor is empty the android docs seem to be unspecific on a lot of corner cases actually other than getcount so i am worried that i need to do thiscursor mydbqueryif cusrorgetcount 0 cursormovetofirst while cursorisafterlast processrow which is messier and logically redundant bear in mind that in the real implementation there is more code and this is spread across multiple methods and one of the answers is now suggesting that i need to check the cursor for null as well which is completely undocumentedi simply want to know whether anyone else knows the actual behaviour of isafterlast when called on an empty cursor,['android'] +194947,how to get rid of this circular dependency i am currently writing a few classes to deal with localization in a php web applicationthe classes arelocale deals with setting and getting the users locale timezone languagelocaleformat deals with formatting dates collations currency formats etctimezone deals with compiling a list of time zones for countries and other functions related to timezoneslocaledata fetches locale data for example address formats and things like post code regexesthe whole application works properly but i need to add a few more things to timezonethis results in this problemlocale requires timezones methods which requires localedatas methods which requires locales methodshow can i break this circular dependency should i break my classes down into smaller pieces are there any patterns for dealing with thischeers,['php'] +194962,how to set stdtuple element by index one can get an element from stdtuple by index using stdgetanalogically how to set tuples element by index,['c++'] +194969,c double to decimal precision loss i have a double 13863078380386264 and i want to convert it to a decimal however when i do so i either by casting or by using converttodecimal i loose precision whats going on both decimal and double can hold this number double doub doubleparse13863078380386264 decimal dec decimalparse13863078380386264 string decs dectostringf17 string doubse doubleconvertertoexactstringdoub string doubs doubtostringf17 decimal decc decimal doub string doudeccs decctostringf17 decimal decconv converttodecimaldoub string doudecs decconvtostringf17also how can i get the tostring on double to print out the same result as the debugger shows eg 13863078380386264,['c#'] +194974,put css and javascript in files or main html although it is always recommended to put javascript and css code into appropriate files as js and css most of major websites like amazon facebook etc put a significant part of their javascript and css code directly within the main html pagewhere is the best choice,"['javascript', 'html', 'css']" +194982,how to remove newlines from beginning and end of a string java i have a string that contains some text followed by a blank line whats the best way to keep the part with text but remove the whitespace newline from the end,['java'] +194998,google api how can i use refreshtokens to avoid requesting access every time my app launches i am trying to use the google api to access info for the authenticated user i have copied some code from one of the samples which works fine below however i am having trouble making it work in a way i can reuse the token across applaunchesi tried capturing the refreshtoken property and using providerrefreshtoken amongst other things and always get a 400 bad request responsedoes anyone know how to make this work or know where i can find some samples the google code site does not seem to cover this class program private const string scope static void mainstring args var provider new nativeapplicationclientgoogleauthenticationserverdescription providerclientidentifier blah providerclientsecret blah var auth new oauth2authenticatornativeapplicationclientprovider getauthentication var plus new plusserviceauth pluskey blah var me pluspeoplegetmefetch consolewritelinemethisplayname private static iauthorizationstate getauthenticationnativeapplicationclient arg get the auth url iauthorizationstate state new authorizationstatenew scope statecallback new urinativeapplicationclientoutofbandcallbackurl uri authuri argrequestuserauthorizationstate request authorization from the user by opening a browser window procestartauthuritostring consolewrite authorization code string authcode consolereadline consolewriteline retrieve the access token by using the authorization code return argprocessuserauthorizationauthcode state,"['c#', '.net']" +195001,why cannot we pass arrays to function by value apparently we can pass complex class instances to functions but why cannot we pass arrays to functions,['c++'] +195016,how to pass serial object by reference to my class in arduino i have been reading up a couple of days now about pointers references and dereferences in cc targeted for the arduino and cannot fully udnerstand what i am missingi have my sketch which has a setup of serialbegin9600 just for loggingserial1begin9600 arduino mega other devicei use a wrapper class to send bytes over serial1 by calling a simple function like getstatusthe issue i am having is i would like to make my class more dynamic so i would like my class to use serial1 serial2 serial3 or even the base serial but i do not know how to build my h and cpp files to use these as referencesat the moment my class has a static serial1 but if somebody would like to use my class they would have to rename everything to serial if they use arduino unoin myclassh i have something likemyclasshardwareserial serialand in myclasscpp constructormyclassmyclasshardwareserial serial hardserial serial but the compiler keeps on moaning about expected before or i have tried various ways and always get the same error except when i reference my class to the serial object but it says serial was not definedi cannot find any tutorials except pointer resource for arduinodeclaration and creationinclude printhdatatype variablename targetprint printer serial usageusagethis is the equivalent of serialprintprinterprintprint using the serial object notice the as opposed to change target address or which address to point toprinter serial2this is the equivalent of serial2printprinterprintprint using the serial2 objectwhich is exactly what i want but it seems i do not understand it i did what they did there and it does not work for meedit 1thanks i did it the reference way because it is better yet i still get these errors though88 error hardwareserial has not been declaredline 88 from huint8 t initlong baudrate hardwareserial serialh136 error iso c forbids declaration of hardwareserial with no typeh136 error expected before tokenline 136 from h this keeps on happening i do not know what to use serialwrite serialprivatehardwareserial hardserialedit 2so basically because i import the hardwareserialh file in file myclassh which is imported in my sketch to use all myclasses stuff it kills the references in the sketch and wants me to redefine the serial instances it seems like the inheritance is the wrong way aroundaannoying whats the default constructor used in the sketchit is like it is asking me to do thishardwareserial serial1rx buffer1 ubrr1h ubrr1l ucsr1a ucsr1b udr1 rxen1 txen1 rxcie1 udre1 u2x1really again i do not understand,"['c++', 'c']" +195020,is it necessary to have getters and setters in pojos i have been going through clean code book which states that the class should not expose the internal state of its data and only should be exposing the behavior in case of a very simpl and dumb java bean exposing the internal state which getters and setters is it not worth just removing them and make the private members public or just treat the class as a data structure,['java'] +195025,integrating facebook twitter google into android app using phonegap i want to integrate facebook like twitter google bubble button into my android app which is developed using jquery mobile within phonegap so that users can post content from the page on their walls nothing is working for me,['android'] +195037,getting the context inside a custom view i have made a small custom view componentpublic class actionbar extends relativelayout public actionbarcontext context attributeset attrs supercontext attrs custom logic here private class homebuttonlistener implements onclicklistener override public void onclickview v how do i get the context here every actionbar component comes with a homebutton so i thought it would be appropriate to put it is onclicklistener inside the view definition itself the button should return the user to the main activity when clicked but i need a context in order to start activities can i create a local reference to the context passed in the constructor without running into a mess of memory leaks,"['java', 'android']" +195061,rails question belongs to with sti how do i do this correctly i have been playing around with sti and belongs to has many relationships and i am a bit confusedi have a few questions based on a model configuration similar toclass parental activerecordbaseendclass mother parental has many babiesendclass father parental has many babiesendclass baby activerecordbase belongs to endwhat should baby belong toin terms of a migration what should i nameadd for foreign key onthe babies tablei have had a hard time researching this is there a definitive sourcethat explains this the api docs did not seem to hit it on the heador i missed it which is totally possiblemy first thought is add parental id to babies along with a method like babyowner that does the followinghits selfparental determines the parentals typereturns the correct type of parental could be a mother could be a fatherthank you,['ruby-on-rails'] +195066,how are threads allocated to handle servlet request can someone please explain what is thread per request and thread per connection which model do servlets work on how threads are allocated to handle http requests is it threadrequest or connectionand let us say if i want to perform a time consuming task in my servlets doget method asynchronously i start a new thread using java executors so that lengthy calculations are done in a separate thread and response is sent right awaynow does that ensure that i have freed the thread which had been processing my httpservletrequest or is it still being used because a child thread is still running,['java'] +195067,eventtarget not working on firefox var x eventtargeteventsrcelement documentgetelementbyidxidstyleleft 200 px documentgetelementbyidxidstyletop 100 px works fine on google chrome and ie but not on firefox tried it on google google says eventsrcelementworks on ie but not on firefox so i have added eventtarget but still not working is there anymore changes i need to do to work on firefox by the way im using 35 version of firefox function up dragok false documentonmousemove null var x eventtargeteventsrcelement documentgetelementbyidxidstyleleft 200 px documentgetelementbyidxidstyletop 100 px please help me to make it work on firefox,['javascript'] +195084,preventing status bar expansion is there anyway to prevent users from sliding the status bar expand or collapsing back i am trying out a lockscreen replacement and seems like it is a musthave feature is there any possible way to do it without requiring root privileges,['android'] +195089,set any applications volume i was wondering how i could set a specific application as in any running application not just my owns volume level in c i know i would probably have to use pinvoke this is fine i am just not sure on how the sound apis work and how i would go about gettingsetting the volume of specific applications like the volume mixer in vista7 cani know it is possible to do programattically because nircmd has a feature that can do itany help would be appriciated thanks,"['c#', '.net']" +195090,object undefined error at var chat connectionchat while using signalr i tried installing signalr library to create a sample chat application i believe i have followed all steps given in documentation i am not sure what could be a reason of failingit is failing when it creates a chat object i am using vs2010 and i downloaded signalr using vs2010 package download utilityis anyone had an issue with thisthankssamirthanks hurricanepkt for helping me outyes i did get all signalr via nuget using vs2010 add library package dialog box i was getting object undefined error at var chat connectionchati just made it work but it was aspnet web application project i could not make it work with aspnet website project i do not know whyi believe it due to dynamic dll creation in website project vs fixed dll in aspnet web application project have you encounter such issue,['asp.net'] +195099,c unified assignment operator movesemantics edit solved see commentsdo not know how to mark as solved with out an answerafter watching a channel 9 video on perfect forwarding move semantics in c0x i was some what led into believing this was a good way to write the new assignment operatorsinclude stringinclude vectorinclude iostreamstruct my type my typestdstring name namename my typeconst my typedefault my typemy type other thisswapother my type operatormy type other swapother return this void swapmy type other nameswapothername private stdstring name void operatorconst my typedelete void operatormy typedeleteint main my type thello world my type t1foo bar tt1 tstdmovet1this should allow both rvalues and const s to assigned to it by constructing a new object with the appropriate constructor and then swapping the contents with this this seems sound to me as no data is copied more than it need to be and pointer arithmetic is cheaphowever my compiler thisagrees g 46 and i get these errorcopyconsttestcpp in function aint mainacopyconsttestcpp404 error ambiguous overload for aoperatora in at t1acopyconsttestcpp404 note candidates arecopyconsttestcpp1811 note my type my typeoperatormy typecopyconsttestcpp3011 note my type my typeoperatorconst my type deletedcopyconsttestcpp31 note my type my typeoperatormy type near matchcopyconsttestcpp31 note no known conversion for argument 1 from amy typea to amy typeacopyconsttestcpp4116 error ambiguous overload for aoperatora in at stdmove with tp my type typename stdremove reference templateparameter11 type my type t1acopyconsttestcpp4116 note candidates arecopyconsttestcpp1811 note my type my typeoperatormy typecopyconsttestcpp3011 note my type my typeoperatorconst my type deletedcopyconsttestcpp31 note my type my typeoperatormy type deletedam i doing something wrong is this bad practice i do not think there is way of testing whether you are self assigning is the compiler just not ready yetthanks,['c++'] +195103,ninject binding with wheninjectedinto extension method i feel i am missing something obvious i have read several related questions on here and i have read the updated contextual bindings page on ninjects wiki but alas it still does not worki am trying to retrofit a legacy application that used a factory pattern to use ninjecti have 1 interface iinterface implemented by 2 classes classb and classc iinterface has a load method in classbs load method it instantiates classc and then executes it is load methodbasically the program flow is classa creates classb and executes the load method in the load method classb creates classc that does some workmy bindings are setup as sobindiinterfacetoclasscwheninjectedintoclassbbindiinterfacetoclassbwheninjectedintoclassawhen this runs it fails in classbs load method with this errorerror activating iinterface no matching bindings are available and the type is not selfbindableif i try the followingbindiinterfacetoclasscwheninjectedintoclassbbindiinterfacetoclassbit does an endless loop and never creates classcediti have simplified this into a unit test that passes but does not give me the results i wanttestclasspublic class ninjecttestfixture private interface idosomething void saysomething private class classa idosomething public void saysomething consolewritelinehello from class a private class classb idosomething private ikernel kernel public classbikernel kernel kernel kernel public void saysomething consolewritelinehello from class b var x kernelgetidosomething xsaysomething private class classc private ikernel kernel public classcikernel kernel kernel kernel public void saysomething consolewritelinehello from class c var x kernelgetidosomething xsaysomething testmethod public void testmethod1 var kernel new standardkernel kernelbindidosomethingtoclassa kernelbindidosomethingtoclassbwheninjectedintoclassc kernelbindclassctoself var x kernelgetclassc xsaysomething the output ishello from class chello from class abut i wanthello from class chello from class bhello from class athanks,['c#'] +195130,windows azure access control wpf anyone has worked with windows azure access control wpf client i like authentication of zune client with live idi need authenticate with windows live id in my wpf appi have a website that works with windows azure acces control i use claims for roles in my website but i need know if its possible use this claims with wpf appi cana t find anything about wpf windows azure access control only for aspnetthank you so much,['asp.net'] +195143,how can a formatstring vulnerability be exploited i was reading about vulnerabilities in code and came across this formatstring vulnerability wikipedia saysformat string bugs most commonly appear when a programmer wishes to print a string containing user supplied data the programmer may mistakenly write printfbuffer instead of printfs buffer the first version interprets buffer as a format string and parses any formatting instructions it may contain the second version simply prints a string to the screen as the programmer intendedi got the problem with printfbuffer version but i still did not get how this vulnerability can be used by attacker to execute harmful code can someone please tell me how this vulnerability can be exploited by an example,['c'] +195180,registering com referenced dlls on a build server were developing a c application that references a few com libraries autoit for examplei am including all referenced components under source control in a 3rd party libs folderthe problem is that com dlls do not have a hintpath property in the csproj file and i assume these must be manually registered using regsvr32 or using a script of some sorti am currently looking into creating an msbuild script that will run before every build however i could not figure out if i should be manually calling regsvr32exe or use some predefined msbuild taskcurrently this is what i have attmpted as a test xml version10 encodingutf8project xmlns defaulttargetsbuild itemgroup myassemblies includeddll itemgroup target namebuild registerassembly assembliesmyassemblies registerassembly targetprojectthis generates errors that the dlls i have placed in the given folder are not valid dllswhat is a good solution for this problemeditprojects that reference com dlls have something similar to this in the csproj filecomreference includeautoitx3lib guidf8937e53d4e71927535b64210cc3bguid versionmajor1versionmajor versionminor0versionminor lcid0lcid wrappertooltlbimpwrappertool isolatedfalseisolated comreferencethis does not include any hint path as other managed assemblies so on a build server the referenced com dll is not foundwhen registering the com dll on the build server using regsvr32 the build succeeds,['c#'] +195183,handling header files dependencies with cmake i am using cmake on a small c project and so far it works great with one twist xwhen i change a header file it typically requires recompiling a number of sources files those which include it directly or indirectly however it seems that cmake only detects some of the source files to be recompiled leading to a corrupted state i can work around this by wiping out the project and rebuilding from scratch but this circumvents the goal of using a make utility only recompiling what is neededtherefore i suppose i am doing something wrongmy project is very simply organizeda top directory where all resources sit the main cmakeliststxt sits therea include directory where all public headers lies in various subdirectoriesa src directory where all the subdirectories for sources files are the src cmakeliststxt sits therea cmakeliststxt per subdirectory in the src directorythe main directory hascmake minimum requiredversion 28projectfoosetexecutable output path cmake binary dirbin compiler optionssetcmake cxx flags cmake cxx flags g stdc0x wall wextra werrorinclude directoriesfoo source dirincludeadd subdirectorysrcthe src directoryadd subdirectorysub1add subdirectorysub2add subdirectorysub3add subdirectorysub4add executablefoo maincpptarget link librariesfoo sub1 sub2 sub3 sub4where sub4 depends on sub3 which depends on sub2 which depends on sub1and an example of a subdirectory sub3setsub3 srcs file1cpp file2cpp file3cpp file4cpp file5cpp file6cpp add librarysub3 sub3 srcstarget link librariessub3 sub1 sub2i would be glad if anyone could point my mistake to me searching here or on cmake did not yield anything so i guess it is very easy or should work out of the boxfor reference i am using cmake version 282 on msyseditthanks to bills suggestion i have checked the dependmake file generated by cmake and it is indeed lacking severely here is an examplesrcsub3cmakefilessub3dirfile1cppobj srcsub3file1cppyep that is all non of the includes were referenced at all x,['c++'] +195185,fastest way to check if string contains only digits i know a few ways how to check thisregexintparsetryparseloopingcan anyone tell me what is the fastest way to checkthe need is to only check no need to actually parsethis is not the same question as how do i identify if a string is a numberthe question is not only about how identifybut about what is the fastest method,['c#'] +195187,metro tile notifications in c i am trying to put together a simple windows 8 metro style app in c with tile notifications but i cannot seem to get them workingwhat i cannot quite figure out yet is where the code to update the tile notifications should reside i have had a look at the javascript sample but i am not seeing how that works in a c app has anyone got some sample code or a quick tip on where tile updates should happen in a c metro app,['c#'] +195193,how to center text in tabhost i have a basic question in many tabhost examples we find tabs with image and textin my case i would like to only thisplay a text but the issue is that my text is horizontally centered but not vertically the text is at the bottom of my tabi tried androidlayout gravitycenter in the framelayout but it does not workdo you have any idea please my xmltabhostxmlnsandroidandroididandroididtabhostandroidlayout widthfill parentandroidlayout heightfill parentandroidlayout gravitycenter linearlayout androidorientationvertical androidlayout widthfill parent androidlayout heightfill parent androidlayout gravitycenter tabwidget androididandroididtabs androidlayout widthfill parent androidlayout heightwrap content androidlayout gravitycenter framelayout androididandroididtabcontent androidlayout widthfill parent androidlayout heightwrap content androidlayout gravitycenter framelayout linearlayouttabhostsolved i customized my tabs thanks to the following tutorial thank you,['android'] +195213,am i really forced to readtoend a streamreader reading an ioniczlibgzipstream i am using the following code to uncompress a gzipstream using dotnetzip library where fs is a filestream pointing to a gz file with filemodeopen fileaccessread filesharereadwriteusing var gz new gzipstreamfs compressionmodedecompress using var sr new streamreadergz header srreadline but if the file is not read till the end which i prefer to do when not needed as the file can be huge it throws zlibexceptionbad crc32 in gzip trailer actualec084966expected8fc3ef16on the first closing bracket actually when trying to close the streamreadernow if call readtoend before closing the streamreader or i read all lines using a whilesrendofstream loop it worksi have observed the same behaviour with a 500 mb and 200 kb compressed file so it seems it is not related to the file sizeyour insight is very welcomehere is a link to a simple dedicated test project it works with the systemiogzipstream library so this is very strange,"['c#', '.net']" +195224,trycatch is this acceptable practice we have received java code from a software supplier it contains a lot of trycatch blocks with nothing in the catch part they are all over the place example try spaceblockenablelindsaymodel catch exception e my questions are is the above acceptable practice if so when or should i just go ahead and remove all of these bogus try and catch statements to me this looks like terrible practice but i am not experienced enough in java to tell for sure why catch errors if youre not going to do anything with them seems to me you would only do that if you were confident that an exception would be of absolutely no consequence and you do not care if one occurs however this is not really the case in our particular application edit to give some context we bought a javascriptable product from the supplier alongside the product they provided a large proofofconcept script tailored to our needs this script came free of charge though we wouldnt have bought the product if it had not come with the script and it works but the script is a real pain to build upon due to many things that even i as a java novice recognise as awful practice one instance being this bogus trycatch business,['java'] +195241,is iosin needed for ifstreams opened in binary mode whats the difference between these two is not the in flag object thing redundant thanksstdifstream file1onebin stdifstreamin stdifstreambinarystdifstream file2twobin stdifstreambinary,['c++'] +195242,why do we need classmethods and instancemethods i read the api for activesupportconcern there are classmethods and instancemethods we can put class methods in classmethodsbut the ms host can use the methods defined in m cannot it why cannot i just writemodule m def selfx end def y endendrather thanmodule m module classmethods def x end end module instancemethods def y end endend,"['ruby-on-rails', 'ruby']" +195246,how to deal with linuxpython dependencies due to lack of support for some libraries i want to use i moved some python development from windows to linux development i have spent most of the day messing about getting nowhere with dependenciesthe questionwhenever i pick up linux i usually run into some kind of dependency issue usually with development libraries whether they are installed via aptget easy install or pip i can waste days on what should be simple tasks spending longer on getting libraries to work than writing code where can i learn about strategy for dealing with these kind of issues rather than aimlessly googling for someone whos come across the same problem beforean examplejust one example i wanted to generate some qr codes so i thought i would use githubcombitlypyqrencode which is based on pyqrcodesourceforgenet but supposedly without the java dependencies there are others pyqrnative githubcomarachnidpyqrencode but that one seemed like the best bet for my needsso i found the package on pypi and thought using that would make life easieri have perhaps made life more difficult for myself by using virtualenv to keep things neat and tidymyenv3matubuntumyenv3 binpip install pyqrencodedownloadingunpacking pyqrencode downloading pyqrencode02targz running setuppy egg info for package pyqrencodeinstalling collected packages pyqrencode running setuppy install for pyqrencode building qrencode extension gcc pthread fnostrictaliasing dndebug g fwrapv o2 wall wstrictprototypes fpic iusrincludepython27 c qrencodec o buildtemplinuxi68627qrencodeo gcc pthread shared wlo1 wlbsymbolicfunctions wlbsymbolicfunctions buildtemplinuxi68627qrencodeo lqrencode o buildliblinuxi68627qrencodesosuccessfully installed pyqrencodecleaning upi guess i probably sudo aptget install libqrencodedev at some point prior to that tooso then i tried to run the test scriptmyenv3matubuntumyenv3 python test qrpy traceback most recent call last file test qrpy line 1 in module from qrencode import encoder file qrencodepyx line 1 in init qrencode qrencodec1520importerror no module named imageopswell investigations revealed that imageops appears to be part of pilmyenv3matubuntumyenv3 pip install pildownloadingunpacking pil downloading pil117targz 506kb 122kb downloadedoperation cancelled by userstoring complete log in homematpippiplogmyenv3matubuntumyenv3 binpip install pildownloadingunpacking pil downloading pil117targz 506kb 506kb downloaded running setuppy egg info for package pil warning not a valid package name please use onlyseparated package names in setuppyinstalling collected packages pil running setuppy install for pil warning not a valid package name please use onlyseparated package names in setuppy building imaging extension gcc building imagingmath extension gcc pil 117 setup summary version 117 platform linux2 271 r27186832 apr 11 2011 180524 gcc 452 tkinter support not available jpeg support not available zlib pngzip support not available freetype2 support not available littlecms support not available to add a missing option make sure you have the required library and set the corresponding root variable in the setuppy script to check the build run the selftestpy script successfully installed pilcleaning uphmm pils installed but has not picked up the libraries i installed with sudo aptget install libjpeg62 libjpeg62dev libpng12dev zlib1g zlib1gdev earlier i am not sure how to tell pip to feed the library locations to setuppy googling suggests a variety of ideas which i have tried but none of them seem to help much other than to send me round in circlesubuntu 1104 installing pil into a virtualenv with pip suggests using the pillow package instead so let us try thatmyenv3matubuntumyenv3 pip install pillowdownloadingunpacking pillow downloading pillow175zip 637kb 637kb downloaded running setuppy egg info for package pillow installing collected packages pillow running setuppy install for pillow building imaging extension gcc setup summary pillow 175 pil 117 version 175 platform linux2 271 r27186832 apr 11 2011 180524 gcc 452 tkinter support not available jpeg support available zlib pngzip support available freetype2 support available littlecms support not available to add a missing option make sure you have the required library and set the corresponding root variable in the setuppy script to check the build run the selftestpy script successfully installed pillowcleaning upwell we seem to have the jpeg and png support this time yaymyenv3matubuntumyenv3 python test qrpy traceback most recent call last file test qrpy line 1 in module from qrencode import encoder file qrencodepyx line 1 in init qrencode qrencodec1520importerror no module named imageopsstill no imageops though now i am stumped is imageops missing from pillow or is it a different problem that was also there with pil,['python'] +195286,pdo connection to db issues i need to know if pdo extension i wrote is valid both syntactically and semantically i have been var dumping my connection variables and while the variables are being passed to the constructor with correct values i am not able to actually fetch anything from my database i have researched the pdo class on the php manual and from what i have uncovered the class i am using is nearly identical to the extension class given in the examples section of the wiki page heres my codeclass dbconnector extends pdo private host private username private password private db private dns public function constructhost username password db thishost host thisusername username thispassword password thisdb db thisdns mysqldbnamethisdbhosthost connection parent constructthisdns thisusername thispassword and heres a test query which returns an array withnothing inside of it there is data within the database so obviously something is not correctfunction testquery global connection query select from users stmt connectionpreparequery result stmtfetchallam i doing something wrong,"['php', 'mysql']" +195288,how to set current value in collection in simple form here is a piece of code in edithtmlerb which does not work the purpose of the code is to fill a form for editing collection is used with option of yes and no how can i set the collection to the current active value with selected option simple form for category do f finput name thisabled true required false finput description finput active collection yes no selected factive fbutton submit end the error saying the active is not a method in finput active collection,['ruby-on-rails'] +195309,how to get different height html divs to float up i have got a series of dynamically created divs of varying heights in a container div div idcontainer div idd1varying textdiv div idd2varying textdiv div idd3varying textdiv div idd4varying textdiv div idd5varying textdiv div idd6varying textdiv div idd7varying textdivdivwhen i float left the divs wrap as expected leaving white space between the shorter divs and the next row of divs how would i get the divs to effectively float up wrapping veritcally rather than horizonatally using only cssideally item 2 would be under item 1 but any improvement would helpso it would end up looking like this,"['html', 'css']" +195311,nameerror name re is not defined i am very new to python very new i copied the following from a tutorialusrbinpythonimport refrom urllib import urlopenfrom beautifulsoup import beautifulsoupwebpage urlopenreadpatfindertitle recompiletitletitlepatfinderlink recompilelink relhreffindpattitle refindallpatfindertitlewebpagefindpatlink refindallpatfinderlinkwebpagelistiterator listiterator range216for i in listiterator print findpattitlei print findpatlinki print ni get the error traceback most recent call last file testpy line 8 in module patfindertitle recompiletitletitlenameerror name re is not definedwhat am i doing wrongedit i added import re but now get the followingfile scripts prodtestpy line 13 in module findpattitle refindallpatfindertitlewebpage file usrlib64python26repy line 177 in findall return compilepattern flagsfindallstringtypeerror expected string or buffer,['python'] +195313,converting timezoneaware date string to utc and back in python i am parsing the national weather service alerts feed into a web application i would like to purge the alerts when they hit their expiration time i would also like to thisplay the expiration time in the local time format for the geographic area they pertain to the alerts cover the whole us so i think the best approach is to store and compare the times in utc timestamps the expiration time arrives in the feed as a string like this 20110909t22120400i am using the labix dateutils package to parse the string in a timezoneaware manner from dateutilparser import parse d parse20110918t15520400 ddatetimedatetime2011 9 18 15 52 tzinfotzoffsetnone 14400i am also able to capture the utc offset in hours offset hours dutcoffsetdays 86400 dutcoffsetseconds 3600 offset hours4using the datetimeutctimetuple and timemktime methods i am able to convert the parsed date to a utc timestamp import time expiration utc ts timemktimedutctimetuple expiration utc ts13163935200at this point i feel pretty good that i am able to convert the raw strings into a timestamp representing the expiration time in utc i am able to compare the current time as a utc timestamp to the expiration and determine if it needs to be purged now utc ts timemktimetimegmtime now utc ts13163987440 now utc ts expiration tc tstruethe difficulty i am having is trying to convert my stored utc timestamp back to the original localized format i have the offset hours stored from the original conversion and a string i parsed to store the timezone label print offset hours4 print timezoneedti would like to convert the utc timestamp back to a locally formatted time but converting it back to a datetime does not seem to be working import datetime datetimedatetimefromtimestampexpiration utc ts datetimetimedeltahoursoffset hoursdatetimedatetime2011 9 18 16 52 the hour is 16 but it should be 15it looks like it is off by an hour i am not sure where the error was introduced i put together another test and got similar results running this at 2129pm edt utc now datetimedatetimeutcnow utc now ts timemktimeright nowutctimetuple datetimedatetimefromtimestamputc now tsdatetimedatetime2011 9 18 22 29 47 off by 1 hourcan someone help me find my mistake i am not sure if it is a daylight savings issue i came across some stuff that leads me to believe it might be trying to localize my dates and times but at this point i am pretty stumped i was hoping to do all of these calculationscomparisons in a timezoneagnostic manner,['python'] +195322,how can i achieve a slot machine spinning effect with css3 jquery i am creating a demo application that randomly selects a venue when a button is clicked once the button is clicked i want to have the venues scroll through with a slot machine spinning animation using css3 and jquery before a venue is selected i thought about using webkitkeyframes and changing the background position but it is not the ideal animation i would like webkitkeyframes spin 0 backgroundposition 0 0 0 webkittransform rotatex0deg 100 backgroundposition 0 0 640px webkittransform rotatex360deg rotating webkitanimation spin 5s infinite linear webkittransition backgroundposition 7scan anyone give any insight on how this can be achieved here is what i have so far any help is appreciated thank you,"['jquery', 'html', 'css']" +195328,issue iterating through arraylists i have two questions i have an object here that is of type arraylist and for this case let us call it cari have made 2 of themcar car1 new carcar car2 new cari have a function to add items to those car objects car1addpartfront wheelscar1addpartrear wheelscar1addpartrear view mirrorcar2addpartrimscar2addpartsteering wheelcar2addpartbumperi need to have a function called samecontents that i can call on car1 car1samecontentscar2which passes in an object of type arraylist and checks it with car1 to see if they have the same contents and in the same orderpublic boolean samecontentscar c arrayliststring other car c error type mismatch cannot convert from car to arrayliststring for string c thisparts systemoutprintlnc forstring oc other car stuff i seem to be having all sorts of issues with this one i cannot get the other car variable to be used in a foreach loopthe second one that needs to be done is transfercontents it is called like car1transfercontentscar2 which transfers the items in car2 into car1 and then leaves car2 empty i cannot seem to get the arraylist to work again in a foreach loop which is what i think i need public void transfercar c code for transfer method thisparts is the arraylist of car parts for car c c thispartsaddc not sure how to set car2 to empty,['java'] +195348,onsaveinstancestateonpause wait until state is fully saved before allowing process to be killed i am working on my first android app it has a model that is persisted to a database as the user makes updateswhen onsaveinsancestate is called i want to save an id that can be used to load the document the user was working on from the database but this can only happen once the document has fully hit the database in some cases persisting a complex document can take several seconds i am hoping this will speed up once i take all the verbose logging out and in actual use a complex document will be built up by the user in stages each of which will be persisted to the database so it is not very likely for a complex document to have to all be saved in one gonow the 1 rule of threading on android is do not block the ui thread so of course the db interactions happen on a separate thread but my understanding of the android lifecycle is that in many cases onsaveinstancestate is being called because the android system wants to kill the process that suggests i cannot allow this method to return until the db thread finishes saving the document and in fact with my current design i do not actually know what the id number of the document is until it is been saved to the db so i cannot even put that in the bundle of saved stateis it appropriate under these circumstances to block the ui thread waiting for the persist task to be done when onsaveinstancestate is called because the process is being killed the app is no longer visible in the foreground so there is no interface to become unresponsivebut onsaveinstancestate is also called when the activity instance is being trashed by a config update which happens when the screen orientation changes it is very unfortunate when rotating the screen sideways fails to do anything for several seconds in this case the process and therefore memory space is still around so i do not strictly need to ensure the document hits the database if i can just store a reference to it in the bundle instead of its id but i am not aware of a way to tell the difference between these two casesis there an accepted practice for these situations should i just block the thread to be safe can i just use normal java thread primitives to block and wait is there something i can do that does not block the thread but ensures the persist task will be finished before android closes the processall this also applies to onpause as onsaveinstancestate is not necessarily going to be called,['android'] +195351,how to use relativelayoutsetbackgrounddrawable with a bitmap i have a relativelayout object and want to dynamically change the background image with a dynamically created bitmap object it changes its color dynamicallyi saw that when i wanted to update the background image of the relativelayout object that i can only choose setbackgrounddrawable which requires a drawable object as a parametermy question is how can i convert the dynamically created bitmap object into a drawable object,['android'] +195363,php headerlocation force url change in address bar i am currently working on a mobile site with authentication using php sessions with a databasei have a login page with a form that goes to server loginphp on submit the php file then creates some session data store in session and redirects the user back to the index pageheaderlocationindexphpthe new web page indexphp loads correctly however when the header redirects the page the url at the address bar is not changed it stays at httplocalhostphpserverserver loginphp instead of httplocalhostindexphp and thus all my other resources that makes use of relative pathing could not be loaded it is as if the web page still thinks that it resides at phpserver instead of strangely my other use of headerlocation at logoutphp works and redirects the page successfully with a url changei have made sure that there are no outputs in my server loginphp before the header redirect above it are just mysql calls to check and i have used ob start and ob end flush tooare there any methods of forcing the url on the address bar to change and thus hopefully fix the relative path problem or am i doing something wrongps i am using jquery mobileedit heres my code for the redirection that does not change the url some other stuff not shownsql select from user table where email myemail and password mypasswordlogin result mysql querysql connectioncount mysql num rowslogin resultif count 1 successfully verified login information session start if isset sessionis logged in sessionis logged in 1 if isset sessionemail sessionemail myemail if isset sessionpassword sessionpassword mypassword register users name and id if isset sessionname isset sessionuser id row mysql fetch assoclogin result sessionname rowname sessionuser id rowuser id headerlocation httplocalhost8080meet2eatindexphp else not logged in redirect back to login page headerlocation httplocalhost8080meet2eatphploginphperr1,['php'] +195378,nl2br equivalent in javascript possible duplicatejquery convert line breaks to br nl2br equivalent currently i add br for each evtwhich 13 is there a nl2br for javascript so i can do away with this evtwhich 13how different is this from phpjstextareakeypressfunctionevt if evtwhich 13 var range textareagetselection var image selection rangetext textareareplaceselectionbr textarea1htmltextareaval,"['php', 'javascript', 'jquery']" +195422,cannot drop database because it is currently in use i want to drop a database i have used the following code but to no availpublic void dropdatabasestring dbnamesqlconnection scon try sqlconnectionclearallpools sqlcommand cmd new sqlcommandalter database dbname set single user with rollback immediate scon cmdcommandtype commandtypetext sconopen cmdexecutenonquery sconclose sqlcommand cmddrpdb new sqlcommanddrop database dbname scon cmddrpdbcommandtype commandtypetext sconopen cmddrpdbexecutenonquery sconclose catch exception ex messageboxshowdropdatabase exmessage i am getting error as cannot drop database because it is currently in useplease help me out in the above mentioned issue,"['c#', 'asp.net']" +195446,is there something like tuple in net 35 i need some data type like listint int int string int of course i can implement but is there something built in net 35thanks,"['c#', '.net']" +195458,javascript intelligent rounding i currently need to round numbers up to their nearest major number not sure what the right term is herebut see an example of what i am trying to achieveie 13 20 349 400 5645 60 9892 10 13988 20 93456 10 231516 30etc etci have implemented a way of doing this but its so painful and only handles numbers up to a million and if i want it to go higher i need to add more if statements yeah see how i implmented it p im not very proud but brain is stuckthere must be something out there already but google is not helping me very much probably due to me not knowing the correct term for the kind of rounding i want to do,['javascript'] +195472,how should user agents handle unrecognized html elements i have tried to find an answer to this in the w3c html specifications but have not had any luck so farfor example if i have the following html codebody p foobarfoo pbodydoes w3c specify how a user agent should handle this eg should the foo element be completely ignored should the foo element be ignored but the content bar parsedalso is it even legal to do thisedit some excellent answers from all of you i totally agree that it would be bad practice to embed generic xml unless possibly if you have complete control over which browser your users will use i was mostly curious about what actually would or should happen if such markup were to be produced,['html'] +195490,secure contents in documents directory can anyone help me to make the contents of my documents directory secure,['ios'] +195495,add enable and thisable nlog loggers programmatically how can i add edit delete enable and thisable loggers from code for nlog,['c#'] +195536,where should you start coding a web browser say i want to create a web browsernot the windows form high level toolkit kind where there is already a webbrowser control widget which you just add into your application say i want to create one like mozilla firefox and google chrome with its own html css parser though chrome uses webkit etc where should i start coding it how much should i codei do not obviously intend to create one from scratch eg beginning with a low level gfx api writing my own widgets then handcoding all the parsers and the entire client side and every other thing i just do not want simply to embed a prebuilt webbrowser control and call it my own web browser therefore i do intend to use all the thirdparty libraries that help so how much should i code and where do i start what libraries and apis may be helpful,['c++'] +195547,transparent border expands background colorimage i need to modify a website to make the clickable zone of all links bigger for the ipadfirst i was thinking this was a easy task i gave all links a transparent border and a negative margin so that this change would not affect the textflow now this works like a charm but not on links that have a background image nor color the background colorimage seams to spread out to the transparent border it seams that all browser behave the same in this case here a other example why is this i was always thinking that the border is outside of the element and do you have any idea how i could fix this or maybe a other solution that does not require to modify the html ps it only has to work in webkit,['css'] +195596,can i load an entire html document into a document fragment in internet explorer heres something i have been having a little bit of difficulty with i have a local clientside script that needs to allow a user to fetch a remote web page and search that resulting page for forms in order to do this without regex i need to parse the document into a fully traversable dom objectsome limitations i would like to stressi do not want to use libraries like jquery there is too much bloat for what i need to do hereunder no circumstances should scripts from the remote page be executed for security reasonsdom apis such as getelementsbytagname need to be availableit only needs to work in internet explorer but in 7 at the very leastlet us pretend i do not have access to a server i do but i cannot use it for thiswhat i have triedassuming i have a complete html document string including doctype declaration in the variable html heres what i have tried so farvar frag documentcreatedocumentfragmentdiv fragappendchilddocumentcreateelementdivdivouterhtml html results in an empty fragmentdivinsertadjacenthtmlafterend html html is not added to the fragmentdivinnerhtml html error expected but i tried it anywayvar doc new activexobjecthtmlfiledocwritehtmldocclose javascript executesi have also tried extracting the head and bodynodes from the html and adding them to a html element inside the fragment still no luckdoes anyone have any ideas,"['javascript', 'html']" +195600,eclipse plugin autocomplete as it should be i have a problem with multiple possible solutionsi am doing a computer sience study and i am working as an intern at the moment my assignment is to make a business application for android ios i have been working for 2 years with visual studio 2010 now xcode is rather simular so that is no biggy eclipse on the other hand is not as what i am used to i am not saying it is bad i have enjoyed eclipse so far but now i am constantly using xcode and eclipsenow hold on there before you answer i know there is an autocomplete in eclipse but it will only pop after you push ctrl space or after one of the maximum of four auto activition triggers is well triggeredso my question isis there any tool that does trigger auto complete after every keystroke or somethingi tried looking at making my own eclipse plugin but it was way to hard with zero knowlegde about the eclipse api although tutorials considering the auto complete features are welcome they should cover classes like contentassistcommandadapterthanks in advance,['java'] +195614,how can the pseudo element detect the height of the nonpseudo element please see ptext text text text text text textpp backgroundcolor bluepbefore content position absolute width 10px height 100 backgroundcolor redessentially the height of the pseudo element is too big i want it to have the same height as the p element how can i do that,['css'] +195641,image source completion for sublime text 2 first of all i am not entirely sure if this fits into stackoverflow or should rather be placed into programmers or superuser if i posted into the wrong page i am sorryto the questionin aptana studio for example there is a very nice feature for the srcattribute for imgtags when typing into the srcattribute a directorylisting is shown in the autocompletecontextmenu so you can directly select image files and the path is inserted into the attributehere is what i meanis there any way a plugin or something alike so i can get this behaviour into sublime text 2 preferably working for htmlmarkup and css backgroundimageseditmeanwhile i posted this on the sublime userecho maybe something will come up trough this i will keep this question updatedsublime userecho,['html'] +195658,why does windowopenonunload function not work as i expect i want to be able to tell when a window that i open is closed by the user this is the code of my attempt at monitoring thishtml head script typetextjavascript srcscript script typetextjavascript windowdocumentonready function documentgetelementbyidopenwindowonclick function var windowref windowopentests2html windowrefonunload function windowalerthola scriptheadbody button idopenwindowopen windowbuttonbodyhtmli would expect this to alert hola in the original window after the window that was opened with windowopen was closed instead it alerts hola in the original window immediately after opening the new window with windowopen why does it work like this is there a way of doing what i want to do,['javascript'] +195675,why cannot i create a vector of lambda in c11 i was trying to create a vector of lambda but failedauto ignore return 10 1stdvectordecltypeignore v 2vpush back return 100 3up to line 2 it compiles fine but the line3 gives compilation errorerror no matching function for call to stdvectormainlambdapush backmainlambdai do not want a vector of function pointers or vector of function objects however vector of function objects which encapsulate real lambda expressions would work for me is this possible,['c++'] +195691,circular buffer implementation in c i have found pseudo code on how to implement a circular buffer producerwhile true produce item v while in1n out wait bin v in in 1 n consumerwhile true while in out wait w bout out out 1 n consume item w what i do not understand is the consume item w comment because i think that with w bout we are consuming w are not we,['c'] +195703,how do i eliminate line break from fgets function in php i am attempting to make a gallery that calls the image names from a flat file database using the php fgets function there are different sections in the gallery each with it is own default image and a small list of images that the users can select from everything is working fine except for one buttoni have one button on the page that is supposed to reset all the galleries to their default images using javascript onclick it works exactly as i want it to with one small hitch it copies the line break at the end of the line allong with the characters on the line breaking the javascriptthe offending codefunction backdocumentgetelementbyidbackclassnamebackdocumentgetelementbyidoneclassnamecellcontthis should output the proper javascript but does notphpa fopenctxtrif a echo error unable to open file exitb fgetsaecho documentgetelementbyidi1srcbfcloseahow it outputsfunction backdocumentgetelementbyidbackclassnamebackdocumentgetelementbyidoneclassnamecellcontdocumentgetelementbyidi1src00jpgas you can see the ending quotation mark and the semicolon falls on the next line and this breaks the buttonwith the files i am using now i can get around this problem by changing fgetsa to fgetsa 7 but i need to have it grab the entire line so that if the client decides to enter a file with a longer name it does not break the gallery on them,"['php', 'javascript', 'html']" +195705,how do i print a multidimensional array in ruby whats the preferred method of printing a multidimensional array in rubyfor example suppose i have this 2d arrayx 1 2 3 4 5 6i try to print it print x123456also what does not work puts x123456,['ruby'] +195728,objectivec is there an invoke on blocks that takes parameters as you may be aware blocks take invokevoidfoo nslogdo stufoo invoke logs do stuffi would like to do the followingvoidbarint int k nslogd kbar invokewithparameters7 want it to log 7 but no such instance methodthe ordinary argumentless invoke works on bar but it prints a nonsense valuei cannot find a direct message of this kind i can send to a block nor can i find the original documentation that would describe how blocks take invokeis there a list of messages accepted by blocksyes i have tried to use class copymethodlist to extract a list of methods from the runtime there appear to be noneedit yes i am also aware of invoking the block the usual way bar7 what i am really after is a selector for a method i can feed into library code that does not take blocks perse,['objective-c'] +195732,options for rpc in mono wcf alternatives i have had the opportunity to spend a great number of hours trying to use wcf in mono it is simply too poorly implemented at this point to be put into a production environment for anything beyond toy applications it does not survive a 247 loadi do currently have wcf on mono running in a production environment but i need to move away from it at least in the near term to bring stability to my software currently i am surviving by restarting processes every few hours and often times that is not enoughi am looking for potential alternatives all of my communicating entities are net based with some being mono on linux and others being msnet on windows server i am very tempted to roll my own rpc layer with protobufnet as the serialization layer but i would prefer not to do this the big plus with protobufnet is that it has good c support which is something that i valuehas anyone out there achieved stability with rpc on mono if so what did you doupdated i did not mention that i am looking for stateful duplex messaging this is a considerably important piece of information i am not stuck with it but i very much want it wcf provides this with nettcp duplex channels,['.net'] +195745,javascript cannot set property of undefined my code var a 1 b hello c 100 some important data d dagreeting b dadata c consoledebug di get the following error uncaught typeerror cannot set property greeting of undefinedi am trying to do something similar to an associative array why is not this working,['javascript'] +195752,removing the first 16 bytes from a byte array in java how do i take a byte array and remove the first 16 bytes from the array i know i might have to do this by copying the array into a new array any examples or help would be appreciated,['java'] +195760,for in loop with string array outputs indices when i write some javascript such as thisvar words word1 word2 word3for word in words consolelogwordthe resulting output is the numeric indices of the respective word i did some searching on google and i could not find the exact reason for this behavior i am guessing that this is completely expected behavior but i would like to know the reason whythanks,['javascript'] +195763,how can i combine multiple signup options facebook twitter openid i want to build a login system with javascript and php that will let users use existing accounts to login to my site they should be able to use at least these accountsfacebook twitter google yahoo openid plus option to create an account on my site if they do not have a login abovei have seen all these services below which offer what i am wanting to do i would like to build this myself or use some open source project in other words i do not want a 3rd party to handle this like the sites aboveso does anyone know if an open source project exists that can handle this or point me in the direction on how i should create this i can do php and javascript so asking more about the design theoryproject flow more than how to code iti am aware that there might be similar questions but i have not found what i am looking for,"['javascript', 'php']" +195819,h2 database gui tool i trying to use the h2 database in my application and i need to backup only two tables i also need a way to import and export blobs through a gui tool to make it easy is there a gui tool for doing this,['java'] +195829,replace with in a string in c i still do not get how to do this i saw many posts regarding this but none of the solutions worked for mei have a string called ab the result i need is ab how is this donei have a text file which has a database connection string pointing to an instance called serverdbinstancemy aim is to do a string replace in the text file replace serverdbinstance with another value say 101213 1200so i havestringtobereplaced serverdbinstancenewstring 101213 1200this is where the problem starts my stringtobereplaced will always be serverdbinstance and when i search for this string in my text file the search fails as the text file does not have a string serverdbinstance instead it has only serverdbinstance so how do change serverdbinstance to serverdbinstance,['c#'] +195836,how to fix screen orientation to potrait for my whole phonegap app how to configure the phonegap app to be fixed to only portrait mode i there any possibility to do it with css or javascript so that i should be able to get the consistent behaviour across the platformsi found this useful post detectingthisplaysorientationchangeonmobiledeviceswithaccelerometeraplatformindipendentapproachhere it is explained how to detect the orientation but i need to configure itis it possible through css3 media queries,"['iphone', 'android']" +195853,why use many subprojects and dependencies over packages iave mostly in my career worked in small or midsized java projects i recently saw a huge project comprising of 30 projects in eclipse i donat really get concept of creating many small projects and then maintain interproject dependencies when do we prefer this over simply organizing stuff in packagesi guessed itas a maven thing have mostly been using ant iave been reading up on mavenas concept of modules as well a i saw some links on net recommending creation of different modules for web dao and service layers under a parent module is it really a commonbest practicewith or without maven a does such division really makes life easier isnat it more compact to have everything in a single project with welldefined packages structure for different layers,['java'] +195854,how can i run an app automatic after restart how can i run an app automatic after restartby c code i create a new string in runonce key in registry with the path of the appthe os run this app before it load the osmy problem is my app loads but explorer does not load after i close my app explorer loadsi restart the computer in app and after restart i want that my app reopen,['c#'] +195862,thread safety with template tags after reading this document about thread safety i am left feeling that there is something missing in the documentation or my reading of it or my reasoninglet us give a simple exampleclass helloworldnodetemplatenode def renderself context return o hai lolregistertagnamehello worlddef hello worldparser tokens greets the world with wideeyed awe return helloworldnodei understood this code to construct a new instance of the helloworldnode class whenever the hello world tag is used other examples involve passing arguments to the constructor like thisclass helloworldnodetemplatenode def init self message selfmessage message def renderself context return o hai lol messageregistertagnamehello worlddef hello worldparser tokens greets the world with wideeyed awe message tokenssplit contents1 return helloworldnodemessagethus when hello world is executed a new instance of helloworldnode is created and the instance dictionary has an attribute message this instance surely must be used only for the rendering of only the given instance of the tag as using it for other renderings would mean that the data bound to it would be incorrect if this were not the case the arguments would get mixed up between different uses of the taglooking at other examples from the docs heres a simplified example from heredef do current timeparser token tag name format string tokensplit contents return currenttimenodeformat string11as this takes data from the tokens passed to the function the only way that currenttimenode can work is that a new one is instantiated each time do current time is invoked back to the documentation page where the thissonance sets in this is badclass cyclenodenode def init self cyclevars selfcycle iter itertoolscyclecyclevars def renderself context return selfcycle iternextthe doc says that two pages using the same tag might then experience race conditions if they both use the same node i do not understand how two templates rendering could end up sharing the same instance if they both independently instantiate their ownthe way to solve this says the docs is like this class cyclenodenode def init self cyclevars selfcyclevars cyclevars def renderself context if self not in contextrender context contextrender contextself itertoolscycleselfcyclevars cycle iter contextrender contextself return cycle iternextthis appears to index contextrender context with self the implication of that must be that self is used to identify the instance in one of two waysself references one specific instance of the class in the whole systemself references that class only and in order to reference the instance a render context is requiredif 1 is true why not just associate data with selfif 2 is true and the render context is associated with the context of the template that is currently being rendered how is it possible to thistinguish between two instance of the template tag on the same pageis the node instantiated individually each time the tag is invoked if so why the concurrency problems if not why not,['python'] +195883,what is the meaning of in a variable name recently i read that the sign is allowed in java variable names but has a special meaning unfortunately it is not mentioned what this special meaning istherefore i ask here what is the special meaning of in variable names in javahere is the exact quote from java an introduction to problem solving and programmingfrom walter savitchjava does allow the dollar sign symbol to appear in an identifier but these identifiers have a special meaning so you should not use the symbol in your identifiers,['java'] +195885,templates instantiation in c i am confused by how c instantiate template i have a piece of codetemplate class t int arraysizevoid test1t arrayarraysize cout typeidtname endltemplateclass tvoid test2t array cout typeidtname endlint main int abc5 test1abc test2abc return 0here are my questions1 how does the size of array abc is passed to test1 the parameter arraysize 2 how does c compiler determine the type of t in the two templates,['c++'] +195887,is it possible to use rsync inside of ios app is it possible to use rsync lib inside of an iphone or ipad app or maybe there are any alternatives suitable for remote file sync over sftp,"['iphone', 'ios']" +195892,jumping from one case to the default case in switch statement switchch case a do something condition does not match so go to default case do not break in here and do not allow fall through to other cases case b case c case default breakin a switch statement like above one i enter case a i break only if the condition inside it occurs otherwise i want to jump to default case is there any other way of doing this rather than labels or gotos,['c'] +195906,advanced how to optimize my complex ona2 algorithm i have people and places data asperson entity hasilistdaterangeplaces each havingilistplace of possible places schedule day pattern as ie 10 days available 4 unavailablewithin a particular daterangeplaces date range one has to obey to schedule pattern whether person can go to a particular place or notplace entity hasilistdaterangetiming each defining openingclosing times within each date rangeoverlapping date ranges work as lifo so for each day that has already been defined previously new timing definition takes preferencethe problemnow i need to do something like this in pseudo codefor each place for each day between minimum and maximum date in ilistdaterangetiming get a set of people applicable for place and on day this means that number of steps to execute my task is approxplaces days a people this to my understanding isox a yx a zand likely approximates to this algorithm complexityon3i am not an expert in theory so you can freely correct my assumptions what is true is that this kind of complexity is definitely not acceptable especially given the fact that i will be operating over long date ranges with many places and peoplefrom the formula approximation we can see that people set would be iterated lots of times hence i would like to optimize at least this part to ease things a bit i changedpersonilistdaterangeplacesilistplacetopersonilistdaterangeplacesidictionaryint placewhich would give me a faster result whether a person can go to some place on particular date because i would only check whether placeid is present in the dictionary versus ilistwhere linq clause that would have to scan the whole list each and every timequestioncan you suggest any additional optimizations i could implement into my algorithm to make it faster or even make it less complex in terms of the big o notationwhich memory structure types would you use where and why lists dictionaries stacks queues to improve performanceaddendum the whole problem is even more complextherere also additional complexities that i did not mention since i wanted to simplify my question to make it more clear so there is alsoplaceilistpermissionpersonilistdaterangepermissionso places require particular permissions and people have a limited time permission grants that expireadditional to that there is alsopersonilistdaterangetimingrestrictionwhich tells only particular times that person can go somewhere during particular date range andpersonilistdaterangeplaceprioritieswhich defines place prioritization for a particular date rangeand during this process of getting applicable people i also have to calculate certain factor per every person per every place that is related to thenumber of places that a person can visit on particular daypersons place priority factor on that particular dayall these are the reasons why i decided to rather manipulate this data in memory than using a very complex stored procedure that would also be doing multiple table scans to get factors per person and place and dayi think such stored procedure would be way to complex to handle and maintain so i rather get all the data first put it appropriate memory structures to aid performance and then mangle with it in memory,['c#'] +195921,error could not find or load main class i am having trouble compiling and running my java code intended to allow me to interface java with a shared object for vensim a simulation modeling packagethe following code compiles without errorjavac d cp apachelog4j1216log4j1216jarvensimjar spatialmodeljava vensimhelperjava vensimexceptionjava vensimcontextrepositoryjavahowever when i try to run the followingjava cp apachelog4j1216log4j1216jarvensimjar spatialmodel varsi get the following error error could not find or load main class spatialmodel my spatialmodeljava code does contain a main method below so i am not sure what the problem is can anyone please help me out thanksimport javaiofileimport javatextnumberformatimport javautilarraylistimport javautilarraysimport javautillistimport orgapachelog4jloggerpublic class spatialmodel private vensimhelper vh public static final string dll libname param vensim lib nam public static final string model path param vensim model path private final static int vensim context creation max failure count 10 public spatialmodel throws spatialexception string libname systemgetpropertydll libname param string modelpath systemgetpropertymodel path param iflibname null libnametrimequals logerrorvensim library name has to be set with d dll libname param throw new spatialexceptionvensim library name has to be set with d dll libname param ifmodelpath null modelpathtrimequals logerrormodel path has to set with d model path param throw new spatialexceptionmodel path ahs to be set with d model path param for int i 0 i vensim context creation max failure count vh null i try loginfocreating new vensim helperntdll lib libname ntmodel path modelpath vh new vensimhelperlibname modelpath catch throwable e logerroran exception was thrown when initializing vensim try i e if vh null throw new spatialexceptioncannot initialize vensim public static void mainstring args throws vensimexception long before systemcurrenttimemillis string libname systemgetpropertydll libname param string modelpath systemgetpropertymodel path param if libname null libname libvensim ifmodelpath null modelpath bassmodelvmf systemsetpropertydll libname param libname systemsetpropertymodel path param modelpath if argslength 0 args0equalsinfo systemoutprintlnnew vensimhelperlibname modelpathgetvensiminfo else if argslength 0 args0equalsvars vensimhelper helper new vensimhelperlibname modelpath string vars helpergetvariables for string var vars systemoutprintlnhelpergetvariableinfovar else file f new file systemoutprintlnfgetabsolutepath spatialmodel sm new spatialmodel systemoutprintlnexecution time systemcurrenttimemillis before,['java'] +195923,sending messages or datas with bluetooth via python how can i send messages over bluetooth via python without key authentification like type numbers i used pybluezbut i got this errorfile send line 12 in module connectfile send line 8 in connect sockconnectbd addr portfile string line 5 in connect bluetoothbtcommonbluetootherror 1 connection refusedhere is the codeusrbinpythonimport bluetoothdef connect bd addr x port 1 sockbluetoothbluetoothsocketbluetoothrfcomm sockconnectbd addr port socksendhello sockcloseconnect,['python'] +195930,linq operating on lists of lists i have a list of class a class a contains a list of class b i want to operate on all instances of b within all instances of class a var mylistofa new listaclass a public listb listofbhow can i iterate over all b ie foreachvar b in mylistofalistofb,['c#'] +195968,removing cookies with the same name but different paths i need to delete clientside cookies with the same name but with different paths what is the best way to do this in javascript,['javascript'] +195974,java convert long to date i have list with long values for example 1220227200 12208320 1221436800 which i downloaded from web service i must convert it to dates unfortunately this way for exampledate d new date1220227200returns 1 jan 1970 anyone know another way to convert it correctly,['java'] +195999,linqtosql context database connection handling what are the rules for how a linqtosql datacontext keeps the database connection openthe question came up when we made a few tests on performance for one submitchanges per updated entity instead of one submitchanges for the entire batch of entities resultsinserting 30 items in one submitchanges call duration 1318msinserting 30 items in one submitchanges call within transactionscope duration 1280msinserting 30 items in individual submitchanges calls duration 4377msinserting 30 items in individual submitchanges calls within a transaction duration 2901msnote that when doing individual submitchanges for each changed entity putting everything within a transaction improves performance which was quite unexpected to us in the sql server profiler we can see that the individual submitchanges calls within the transaction do not reset the db connection for each call as opposed to the one without the transactionin what cases does the data context keep the connection open is there any detailed documentation available on how linqtosql handles connections,"['c#', '.net']" +196001,how to get website root path in c in c code i need to write src for an image does anyone know how to get website root path in c my folder structure is uiimagei found that when i usestring rootpathpagerequestapplicationpathif run the application in debug model it works but if run it by typing url directly it would not show image the property of the image is httpimageturnonbmp which should be httplocalhostimageturnonbmpany idea,['c#'] +196037,hiding email address with jquery i know there are plugins that do this but i need something pretty specific and i cannot find anythingi need a jquery script that only change the mailto link and not the text of the link for examplea hrefpersonatexammplecompersons emailai need to thisplay something else inside the link besides the actual email address the script i was trying to use is from this siteheres the script jqueryfnmailto function return thiseachfunction var email thishtmlreplacess thisbeforea hrefmailto email relnofollow titleemail email email aremove i think i need to replace the email variable with something else in between the a tags but i am not sure with what i am still pretty new to jquerythanks,['jquery'] +196066,in rails how to add a new method to string class i want to build an index for different objects in my rails project and would like to add a count occurences method that i can call on string objectsi saw i could do something likeclass string def selfcount occurences do something here endendwhats the exact way to define this method and where to put the code in my rails projectthanks,['ruby'] +196074,virtualabstract fields in c is it possible to have a virtualabstract field in a c class if so how is it done,"['c#', '.net']" +196090,how to time expire rails fragment caches how would i go about expiring a fragment cache after a period of time i came across references to a timed fragment cache gem but it seems outdated,"['ruby-on-rails', 'ruby']" +196105,how to change color of a column in datagridview i have a datagridview and i am setting some of the columns to readonly for data entry purposes when i do that the column stays the normal white although it does not allow entry how can i color the column gray i have seen lots of samples on how to color rows but not columnshow can i make the readonly columns look gray,['c#'] +196109,stupefyingly weird ie 9 javascript bug altering doc title makes subsequent code execute i do not understand this at all here is some javascript code that works in every browser but ie 9 it is called from a flash movie using externalinterface and is meant to dynamically resize the movie in the dom if the size of the movie changes internallyfunction vresizeflashswfid ht documentgetelementbyidswfidheight 100 documentgetelementbyidflashcontainerstyleheight ht pxbut it works fine if i alter the documenttitlefunction vresizeflashswfid ht ie 9 would not run the rest of this function unless we go through the charade of changing the document title if navigatorappnameindexofmicrosoft 1 var doctitle documenttitlereplaces1 documenttitle doctitle wellcoded browsers begin here documentgetelementbyidswfidheight 100 documentgetelementbyidflashcontainerstyleheight ht pxhere i simply trim any whitespace from the right side of the documenttitle then add a single whitespace character to it suddenly the following lines get executed note there are other externalinterface calls on the page and all of them work fine even in ie 9 so it is not a flashie 9 problemi stumbled on the fix because i was altering the title to show the function arguments as a quick debugging test just to make sure the function was getting run and suddenly the code worked take it out does not work 100 reproducibleanybody know why this absolutely stupefying behavior takes placeupdatec69 has posed the question maybe its ie9s dead code removeri did not know about this so i went and googled and found this article on the topic as well as some thiscussion of it elsewhere i do not know enough about it to evaluate how this would affect a twoline javascript function however especially since one of the lines does have a referent on the page although it is lateloading through the swfobject code still it would be a pretty bad bug for a code optimizer to remove lines of code it deemed unnecessary because it does not understand how they are called and if it did fail to understand how the lines are called how does inserting a line making a bogus change to the documenttitle render that code suddenly necessaryupdate 2another piece of the puzzle this may have something to do with ie 9s compatibility mode the page starts out in ie 9s standards modenow if i turn on ies compatibility mode the problem goes away without using the above hack turn it off and the problem returns if no hack presentbut when i tried to make a simple test using the exact same html minus a couple of jsp tags and a stripped down swf that only contains the resize code and the tools to test everything works fine in that case however no compatibility icon is thisplayed at allwere using tomcat 6032 i am not aware that we are using any special headers and there are no meta tags regarding ie compatibility mode in either the main app or in my test app,['javascript'] +196124,c abi issues list i have seen a lot of thiscussion about how c does not have a standard abi quite in the same way that c does i am curious as to what exactly the issues are so far i have come up withname manglingexception handlingrttiare there any other abi issues pertaining to c,['c++'] +196147,python dst time zone detection after addition so i currently have a line of code which looks like this t1 datetimeselfyear selfmonth selfday selfhour selfminute selfsecond t2 timedeltadaysdaynum hourstime2hour minutestime2minute secondstime2second sumval t1 t2i would like for the result to take into account any dst affects that might occur such as if i am at 1142012 0030 am and add 3 hours i would get 0230 am due to a fall back for dst i have looked at using pytz and pythondateutil and neither of them seem to support this or at least not support it without a separate file which contains all of the time zones the kicker is that the times may not necessarily be in the same time zone as the current system or even be in the past i am sure there is a simple way to do this or i would expect so out of python but nothing seems to be what i need right now any ideas,['python'] +196169,inhibit default library paths with gcc is there a way to inhibit the default library path search with gcc nostdinc does this for the include path search but nostdlib either by omission or by design only inhibits the lc lgcc etc but not the library search paths,['c'] +196213,what does sysmaxunicode mean cpython stores unicode strings as either utf16 or utf32 internally depending on compile options in utf16 builds of python string slicing iteration and len seem to work on code units not code points so that multibyte characters behave strangelyeg on cpython 26 with sysmaxunicode 65535 char uu01d49e lenchar2 char01u835 char12uudc9eaccording to the python documentation sysmaxunicode is an integer giving the largest supported code point for a unicode characterdoes this mean that unicode operations are not guranteed to work on code points beyond sysmaxunicode if i want to work with characters outside the bmp i either have to use a utf32 build or write my own portable unicode operationsi came across this problem in how to iterate over unicode characters in python 3,['python'] +196240,any good examples of inheriting from a concrete class background as a java programmer i extensively inherit rather implement from interfaces and sometimes i design abstract base classes however i have never really felt the need to subclass a concrete nonabstract class in the cases where i did it it later turned out that another solution such as delegation would have been betterso now i am beginning to feel that there is almost no situation where inheriting from a concrete class is appropriate for one thing the liskov substitution principle lsp seems almost impossible to satisfy for nontrivial classes also many other questions here seem to echo a similar opinionso my question in which situation if any does it actually make sense to inherit from a concrete classcan you give a concrete realworld example of a class that inherits from another concrete class where you feel this is the best design given the constraints ib be particularly interested in examples that satisfy the lsp or examples where satisfying lsp seems unimportanti mainly have a java background but i am interested in examples from any language,['java'] +196262,problem on starting cassandra i download apachecassandra085 for ubuntu and extract iti read the readme filei try bellow command in shellbincassandra fbut it saiderror exception thrown by the agent javanetmalformedurlexception local host name unknown javanetunknownhostexception node24niselocal node24niselocalwhat should i do,['java'] +196266,get android shared preferences value in activitynormal class i have made a shared preference activity that store the user settings now i want to get values in a activity or normal java classplease provide a solution or example i have already tried this code but failedpublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate sharedpreferences channelthisgetsharedpreferencesstrfile contextmode private strchannelchannelgetstringkeychanneldefaulttostring toastmaketextgetapplicationcontext strchannel toastlength longshow in this code strfile for eg comandroidpackclassname is sharedpreference activity from values to be fetched and keychannel is key that is same in sharedpreference activitykindly provide the solution,['android'] +196287,how to measure the time that a piece of code takes to execute suppose i want to measure the time that a certain piece of code takes for that i would normally do something like thisclock t starttime clockdo stuffdo stuffdo stuffdo stufloat secselapsed floatclock starttimeclocks per secwhat if the program is multithreaded and context switches occur within the part which i want to measure how would i measure the time that my code takes to execute excluding time spent on other threads even if there are tools that do it i would very much like to know how they are doing it,['c++'] +196299,need aidl tutorials i am working on aidl and consider the apidemo for it but if some one has more knowledge please share it,"['java', 'android']" +196302,append relative url to javaneturl provided i have a javaneturl object pointing to let us say or is there some helper somewhere to append some relative url to thisfor instance append myitemid or myitemid to get,['java'] +196311,jquery documentready not firing when content loaded with ajax i have a simple custom tabbing module that loads tabs with an ajax request via elemload on each page that is loaded with ajax i have some javascript the first time the page loads via direct input of url not ajax the javascript fires up perfectly when i navigate away from the page via the ajax tabs the javascripts from the pages are not loading anymoreis there any way i can force them to executethe javascript that is not firing is placed in a documentready function if that helps,"['javascript', 'jquery']" +196315,osgi java modularity and jigsaw so as of yesterday morning i had not a clue as to what osgi even was osgi was just some buzzword that i kept seeing cropping up over and over again and so i finally set aside some time to brush up on itit actually seems like pretty cool stuff so i would like to start off by stating for the record that i am not antiosgi in any respect nor is this is some osgibashing questionat the end of the day it seems that osgi has essentially addressed jsr 277 on java modularity which recognized that there are shortcomings with the jar file specification that can lead to namespace resolution and classloading issues in certain corner cases osgi also does a lot of other really cool stuff but from what i can ascertain that is its biggest draw or one of themto me as a fairly new a few years now java ee developer it is absolutely mindboggling that we are in the year 2011 and currently living in the era of java 7 and that these classloading issues are still present particularly in enterprise environments where one app server could have hundreds of jars on it with many of them depending on different versions of one another and all running more or less concurrentlymy questionas interested as i am in osgi and as much as i want to start learning about it to see whereif it could be of use to my projects i just do not have the time to sit down and learn something that large at least nowso what are nonosgi developers to do when these problems arise what java oraclesunjcp solutions currently exist if any why was jigsaw cut from j7 how sure is the community that jigsaw will get implemented next year in j8 is it possible to get jigsaw for your project even though its not a part of the java platform yeti guess what i am asking here is a combination of panic intrigue and a facepalm now that i finally understand what osgi is i just do not get how something like jigsaw has taken 20 years to come to fruition and then how that could have been canned from a release it just seems fundamental and as a developer i am also curious as to what my solutions are sans osgialso note i know this is not a pure programmingtype question but before some of you get your noses bent out of shape i wanted to state again for the record that i deliberately put this question on so that is because i have nothing but the utmost respect for my fellow soers and i am looking for an architecturallevel answer from some of the gods of it that i see lurking around here every daybut for those of you who absolutely insist that a so question be backed with some code segmentint x 9thanks to anybody who can weighin on this osgijigsawclassloadernamespacejar hell stuff,['java'] +196340,chromes firebugs technic to track ajax requests i am trying to make my google chrome extension to track ajax requests while browsing web only way i found is to listen for domsubtreemodified event event is fired on every single ajax event but there is no additional information about the request but in firebug google chrome extension there is ajax requests tracking with many details i tried to check how they do it in the source code but it is hard for me to understand do you know how to track those events to get some details about requestmaybe someone could take a look at this firebugs technic or maybe someone knows it and could tell me how they do it,['javascript'] +196343,ternary conditional and assignment operator precedence i am confused about direct assignment and ternary conditional operators precedenceincludestdiohint mainvoid int j k j k 0 1 j k 1 first printfd dn j k j k 0 1 j k 1 second printfd dn j k return 0i would expect the output to be1 01 0but it happens to be1 00 0plus i get this warningmaincpp20 warning statement has no effectwhich is about the line i commented as secondsince the direct assignment operator has less precedence than the ternary conditional operator i was expecting lines commented as first and second to be equivalent but alas it is not the casei tried this with g version ubuntu 4434ubuntu5 443,['c++'] +196359,applying style resource programatically i did not find a way to do that programatically so i am posting this question here also i did not find any question related to this onei have a resource style defined in the resvaluesstylesxml what i am trying to do is apply this style inside my activity using java to a view object that i am manipulating is it possible to achieve this in android or the style can only be applied to an object using the androidstyle attribute,['android'] +196365,make a jpanel border with title like in firefox i would like to make an option dialog in my application in this dialog i want to make kind of areas surrounded with a border and with a title an example of what i want is in firefox how can i do something like that in java,['java'] +196398,mongodb not that faster than mysql i thiscovered mongodb some months agoand after reading this post i thought mongodb was really faster than mysql so i decided to build my own bench the problem is that i do not have the same result than the above posts author especially for quering the database mongodb seems to be slower than myisam tables could you have a look to my python code may be there is something wrong in it from datetime import datetimeimport randomimport mysqldbimport pymongomysql dbmysqldbconnectusermepasswdmypasswddbtest kvcmysql dbcursorconnection pymongoconnectionmongo db connectiontestkvtab mongo dbkvtabnb10thelistfor i in xrangenb thelistappendstrrandomrandomstrrandomrandomt1datetimenowfor kv in thelist cexecuteinsert into key val tab kv values k v dtdatetimenow t1print mysql insert elapse dtt1datetimenowfor i in xrangenb cexecuteselect from key val tab where k randomchoicethelist0 resultcfetchonedtdatetimenow t1print mysql select elapse dtt1datetimenowfor kv in thelist kvtabinsertkeykvaluevdtdatetimenow t1print mongodb insert elapse dtkvtabensure indexkeyt1datetimenowfor i in xrangenb resultkvtabfind onekeyrandomchoicethelist0dtdatetimenow t1print mongodb select elapse dtnotesboth mysql and mongodb are on locahostboth mysql and mongodb has the key column indexedmysql tablecreate table if not exists key val tab k varchar24 not null v varchar24 not null key kindex k enginemyisam default charsetlatin1versions aremysql 5141mongodb 183python 265pymongo 201linux ubuntu 2632 32bits with paehardware desktop core i7 293 ghzresults for 1 million insertsselects mysql insert elapse 00252143803mysql select elapse 00443675914mongodb insert elapse 049038416 mongodb much faster for insertmongodb select elapse 00510409025 but slower for quering thought was the opposite,"['python', 'mysql']" +196410,how do browsers parse and interpret javascript code how does a browser go about parsing javascript it loads from files or inline i am trying to get at the core of what a browser does what happens when a page loads and it has script references to external files and actual javascript on the page too any good articles out there,['javascript'] +196437,how do task killers work the usefullness of task killer apps is debated but i am wondering how do they actually work how is it possible to kill particular process is there an api for this and if so what does it actually do editworth adding i saw task killer apps kill processes on not rooted devices so i wonder how is it possible to kill process which you do not own in android,['android'] +196440,converting csv to array i have this array with airport codes and city names around 3500 linescodecityabilene tx abiadak island ak adkakiachak ak kkiakiak ak akiakroncanton oh cakakuton ak kqaalakanuk ak aukalamogordo nm almi need to convert that file into a php array this is my code so farifhandle fopentestcsv r false while data fgetcsvhandle 10 false echo pre print rdata echo pre fclosehandlealthough i am setting the delimiter and enclousure characters for the fgetcsv function im getting this as a resultarray 0 code 1 cityabilene 2 tx 3 abiadak island 4 ak 5 adkakiachak 6 ak 7 kkiakiak 8 ak 9 akiakroncanton 10 oh 11 cakakuton 12 ak 13 kqaalakanuk 14 ak 15 aukalamogordo 16 nm 17 alm,['php'] +196447,how to use signal and slot without deriving from qobject or other way to formulate my question though it did not solve my problem qobjectqobject cannot access private member declared in class qobjecti need signals and slots functionality in my class but i assume it is not possible without to derive from qobjectclass myclasignals importantsignalpublic slots importantslotthe problem seems to be that i need to derive from qobject to use signals and slots but i need the default contructor of myclass but i cannot construct them because of the following feature of qobjectno copy constructor or assignment operatori tried a lot so my shoul class look like thatinclude qobjectclass myclass public qobject q objectpublic explicit myclassqobject parent 0 autogenerated by qtcreator for qobject derived class myclassconst myclass othersignals importantsignalpublic slots importantsloti need the default contructor of myclaso is there any possibility do avoid the qobjectqobject cannot access private member declared in class qobject erroror as an alternative is there any possibility to use signals and slots without qobjecti am glad for any advice,['c++'] +196456,why is spring container destroying beans immediately after creating them immediately after creating all the beans declared in the various context files of my application spring notifies see below that it is destroying singletons and that context initialization failedinfo destroying singletons in orgspringframeworkbeansfactorysupportdefaultlistablebeanfactory orgspringframeworkwebcontextcontextloader error context initialization faileddoes anyone know why the spring container is destroying all the beans right after creating themnote there are no warnings or errors in the log output aside from the above context initialization failure error see belowdebug eagerly caching bean uploadservice to allow for resolving potential circular references 20110921 151908 orgspringframeworkbeansfactoryannotationinjectionmetadata debug processing injected method of bean uploadservice autowiredfieldelement for private orgapachecommonsfileuploadthiskthiskfileitemfactory comfacilerwsservicesuploadservicethiskfilefactory 20110921 151908 orgspringframeworkbeansfactorysupportdefaultlistablebeanfactory debug creating shared instance of singleton bean thiskfileitemfactory 20110921 151908 orgspringframeworkbeansfactorysupportdefaultlistablebeanfactory debug creating instance of bean thiskfileitemfactory 20110921 151908 orgspringframeworkbeansfactorysupportdefaultlistablebeanfactory info destroying singletons in orgspringframeworkbeansfactorysupportdefaultlistablebeanfactoryb0ede6 defining beans orgspringframeworkbeans,['java'] +196459,offline web application html5 on android i want to develop a html5 web appi read that in html5 you can use the new feature offline web applicationswith the manifest filei read an article from november 2010 that this feature only works on the ios platformdoes it work on android now,"['android', 'ios']" +196478,where do i put my credentials when using ivy and a private company repository i am using ant ivy and my company has recently set up a nexus server for our own private libraries ivy can get dependencies from the nexus server by using a ibilio resolver and m2compatibletrue but i have to put my credentials in a ivysettingsxml filehow are different developers supposed to store their credentials is the ivysettingsxml file not supposed to be commited in vcs i really do not want to store my password in plain text,['java'] +196491,uidatepicker with 15m interval but always exact time as return value i have got a uidatepicker in time mode with an interval of 15 minuteslet us say it is 722pm the value that the date picker shows per default is the current time rounded to the next higherlower value in this case it is 715pm if the user interacts with the date picker the value that is shown is also the value returned however if there has not been any user interaction and i get the time with uidatepicker date the return value is the exact current time ie 722 to stick with the example is there any way to always get the value that is actually shown on the date picker instead of the current unrounded time even if the user has not explicitly picked a value i have already tried to set the picker manually with uidatepicker setdatensdate date but that does not change the behaviorany hints thanks in advance,"['objective-c', 'ios']" +196498,virtual function that is const in the base class and not const in the derived can anyone explain the output of the following codeinclude iostreaminclude stringclass animalpublic animalconst stdstring name namename animal virtual void printmessage const stdcout hello i am name stdendl private stdstring name other operators and stuffclass cow public animalpublic cowconst stdstring name animalname cow virtual void printmessage animalprintmessage stdcout and moo stdendl int main cow cowbill animal animal cow cowprintmessage animalprintmessagethe output ishello i am bill and moo hello i am billi do not understand why the pointer animal points at an object of type cow printmessage is a virtual function why is not the implementation of the cow class the one that is called,['c++'] +196507,doctrine 2 how to write a dql select statement to search some but not all the entities in a single table inheritance table so i have 3 entities within one table i need to be able to search 2 out of the 3 entities in one select statement but i am not sure how to do this any advice would be greatly appreciated cheers,['php'] +196516,where is vmware vsphere sdk c samples required references for vimapi namespaced classes i cannot compile the c samples from the vmware vsphere sdk 50 using visual studio 2010 the error is missing references for namespaces apputil and vimapithe references in the vs2010 solution file point to these filesapputilbindebugapputildllvim25service2010dllvim25service2010xmlserializersdllvimservice2010dllvimservice2010xmlserializersdllvmwaresecuritycredentialstorebindebugvmwaresecuritycredentialstoredllwhere are these files in the sdk or how do i get them if not in the sdktwo of the references are from other projects in the solution including the apputil namespace i can update each project to reference the project instead of the debug outputis there a build step i am missing to generate the other dlls is vimapi part of a different download the release notes do not mention additional downloads to get the projects to compile,['c#'] +196520,oracle how to create a materialized view with fast refresh and joins so i am pretty sure oracle supports this so i have no idea what i am doing wrong this code workscreate materialized view mv test nologging cache build immediate refresh fast on commit as select v from tpm projectversion vif i add in a join it breakscreate materialized view mv test nologging cache build immediate refresh fast on commit as select v p from tpm projectversion v inner join tpm project p on pprojectid vprojectidnow i get the errorora12054 cannot set the on commit refresh attribute for the materialized viewi have created materialized view logs on both tpm project and tpm projectversion tpm project has a primary key of projectid and tpm projectversion has a compound primary key of projectidversionid whats the trick to this i have been digging through oracle manuals to no avail thanks,['sql'] +196521,how to tell pex not to stub an abstract class that has concrete implementations i am trying to use pex to test some code i have an abstract class with four concrete implementations i have created factory methods for each of the four concrete types i had also created one for the abstract type except as this nice thread explains pex will not use the abstract factory method nor should itthe problem is that some of my code depends on the four concrete types being all there are since it is very very unlikely that any more subclasses will be created but pex is breaking the code by using moles to create a stubhow can i force pex to use one of the factory methods any one i do not care to create instances of the abstract class without ever creating moles stubs for that abstract class is there a pexassume directive that will accomplish this note that some of the concrete types form a type of tree structure so say concreteimplementation derives from abstractclass and concreteimplementation has two properties of type abstractclass i need to ensure that no stubs are used anywhere in the tree at all not all the concrete implementations have abstractclass propertieseditit appears that i need to add some more information on how the class structure itself works though remember that the goal is still how to get pex not to stub classeshere are simplified versions of the abstract base class and the four concrete implementations thereofpublic abstract class abstractclass public abstract abstractclass thistill public static bool operator abstractclass left abstractclass right some logic that returns a bool public static bool operator abstractclass left abstractclass right some logic that basically returns operator public static implementation1 implementation1 get return implementation1getinstance public class implementation1 abstractclass iequatableimplementation1 private static implementation1 implementation1 new implementation1 private implementation1 public override abstractclass thistill return this internal static implementation1 getinstance get return implementation1 public bool equalsimplementation1 other return true public class implementation2 abstractclass iequatableimplementation2 public string name get private set public string nameplural get private set public implementation2string name initializes including name name and sets nameplural to a default public implementation2string name string plural initializes including name name nameplural plural public override abstractclass thistill if stringisnulloremptyname return abstractclassimplementation1 return this public bool equalsimplementation2 other if other null return false return othername thisname public class implementation3 abstractclass iequatableimplementation3 public ienumerableabstractclass instances get private set public implementation3 base instances new listabstractclass public implementation3ienumerableabstractclass instances base if instances null throw new argumentnullexceptioninstances error msg if instancesanyabstractclassc c null thrown new argumentnullexceptioninstances some other error msg instances instances public override abstractclass thistill ienumerableabstractclass newinstances new listabstractclassinstances flatten the collection by removing nested implementation3 instances while newinstancesoftypeimplementation3anyimplementation3 newinstances newinstanceswhereabstractclassc cgettype typeofimplementation3 concatabstractclassnewinstancesoftypeimplementation3selectmanyimplementation3 abstractuniti iinstances if newinstancesoftypeimplementation4anyimplementation4 listabstractclass denominator new listabstractclass while newinstancesoftypeimplementation4anyimplementation4 denominatoraddrangenewinstancesoftypeimplementation4selectimplementation4 abstractclassc cdenominator newinstances newinstanceswhereabstractclassc cgettype typeofimplementation4 concatabstractclassnewinstancesoftypeimplementation4selectimplementation4 abstractclassc cnumerator return new implementation4new implementation3newinstances new implementation3denominatorthistill there should only be implementation1 andor implementation2 instances left return only the implementation2 instances if there are any ienumerableimplementation2 i2s newinstancesselectabstractclass abstractclassc cthistilloftypeimplementation2 switch i2scountimplementation2 case 0 return abstractclassimplementation1 case 1 return i2sfirstimplementation2 default return new implementation3i2sorderbyimplementation2 stringc cnameselectimplementation2 abstractclassc c public bool equalsimplementation3 other omitted for brevity return false public class implementation4 abstractclass iequatableimplementation4 private abstractclass numerator private abstractclass denominator public abstractclass numerator get return numerator set if value null throw new argumentnullexceptionvalue error msg numerator value public abstractclass denominator get return denominator set if value null throw new argumentnullexceptionvalue error msg denominator value public implementation4abstractclass numerator abstractclass denominator base if numerator null denominator null throw new argumentnullexceptionwhichever error msg numerator numerator denominator denominator public override abstractclass thistill abstractclass numthistilled numeratorthistill abstractclass denthistilled denominatorthistill if denthistilledgettype typeofimplementation1 return numthistilled if denthistilledgettype typeofimplementation4 implementation3 newinstance new implementation3new listabstractclass2 numthistilled new implementation4implementation4denthistilleddenominator implementation4denthistillednumerator return newinstancethistill if numthistilledgettype typeofimplementation4 implementation4 newimp4 new implementation4implementation4numreducednumerator new implementation3new listabstractclass2 implementation4numthistilleddenominator denthistilled return newimp4thistill if numthistilledgettype typeofimplementation1 return new implementation4numthistilled denthistilled if numthistilledgettype typeofimplementation2 denthistilledgettype typeofimplementation2 if implementation2numthistilledname implementation2denthistilledname return abstractclassimplementation1 return new implementation4numthistilled denthistilled at this point one or both of numerator and denominator are implementation3 instances and the other if any is implementation2 because both numerator and denominator are thistilled all the instances within either implementation3 are going to be implementation2 so the following should work listimplementation2 numlist numthistilledgettype typeofimplementation2 new listimplementation21 implementation2numthistilled new listimplementation2implementation3numthistilledinstancesoftypeimplementation2 listimplementation2 denlist denthistilledgettype typeofimplementation2 new listimplementation21 implementation2denthistilled new listimplementation2implementation3denthistilledinstancesoftypeimplementation2 stackint numindexestoremove new stackint for int i 0 i numlistcount i if denlistremovenumlisti numindexestoremovepushi while numindexestoremovecount 0 numlistremoveatnumindexestoremovepop switch denlistcount case 0 switch numlistcount case 0 return abstractclassimplementation1 case 1 return numlistfirstimplementation2 default return new implementation3numlistoftypeabstractclass case 1 switch numlistcount case 0 return new implementation4abstractclassimplementation1 denlistfirstimplementation2 case 1 return new implementation4numlistfirstimplementation2 denlistfirstimplementation2 default return new implementation4new implementation3numlistoftypeabstractclass denlistfirstimplementation2 default switch numlistcount case 0 return new implementation4abstractclassimplementation1 new implementation3denlistoftypeabstractclass case 1 return new implementation4numlistfirstimplementation2 new implementation3denlistoftypeabstractclass default return new implementation4new implementation3numlistoftypeabstractclass new implementation3denlistoftypeabstractclass public bool equalsimplementation4 other return numeratorequalsothernumerator denominatorequalsotherdenominator the heart of what i am trying to test is the thistill method which as you can see has the potential to run recursively because a stubbed abstractclass is meaningless in this paradigm it breaks the algorithm logic even trying to test for a stubbed class is somewhat useless since there is little i can do about it other than throw an exception or pretend that it is an instance of implementation1 i would prefer not to have to rewrite the code under test to accommodate a specific testing framework in that way but writing the test itself in such a way as never to stub abstractclass is what i am trying to do herei hope it is apparent how what i am doing differs from a typesafe enum construct for instance also i anonymized objects for posting here as you can tell and i did not include all methods so if youre going to comment to tell me that implementation4equalsimplementation4 is broken do not worry i am aware that it is broken here but my actual code takes care of the issueanother edithere is an example of one of the factory classes it is in the factories directory of the pexgenerated test projectpublic static partial class implementation3factory pexfactorymethodtypeofimplementation3 public static implementation3 createienumerableabstractclass instances bool useemptyconstructor implementation3 i3 null if useemptyconstructor i3 new implementation3 else i3 new implementation3instances return i3 in my factory methods for these concrete implementations it is possible to use any constructor to create the concrete implementation in the example the useemptyconstructor parameter controls which constructor to use the other factory methods have similar features i recall reading though i cannot immediately find the link that these factory methods should allow the object to be created in every possible configuration,['c#'] +196524,high performance simple java regular expressions part of the code i am working on uses a bunch of regular expressions to search for some simple string patterns eg patterns like foo0934 bar currently we use staticallycompiled java patterns and then call patternmatcher to check whether a string has contains a match to the pattern i do not need the match just a boolean indicating whether there is a match this is causing a noticeable amount of memory allocation that is affecting performanceis there a better option for java regex matching that is faster or at least does not allocate memory every time it searches a string for a pattern,['java'] +196529,why is it a bad thing to have multiple html elements with the same id attribute why is it bad practice to have more than one html element with the same id attribute on the same page i am looking for a way to explain this to someone who is not very familiar with htmli know that the html spec requires ids to be unique but that does not sound like a convincing reason why should i care what someone wrote in some documentthe main reason i can think of is that multiple elements with the same id can cause strange and undefined behavior with javascript functions such as documentgetelementbyid i also know that it can cause unexpected behavior with fragment identifiers in urls can anyone think of any other reasons that would make sense to html newbies,['html'] +196536,snprintf and sprintf explanation can someone explain to me the output of this simple program include stdiohint mainint argc char argv char chararray1024 char chararrayagain1024 int number number 2 sprintfchararray d number printfchararray sn chararray snprintfchararrayagain 1 d number printfchararrayagain sn chararrayagain return 0and the output is aout chararray 2chararrayagain why i do not have 2 herethanks,['c'] +196552,java parse json objects that i know are null i have an array of json objects to parse these arrays and store the simply data type values i have to make assumptions of the key names and store them accordinglyi also know that sometimes the keys values will be null example promotionnull how would i parse thisif i try to access a key whose value is null i get a jsonexception now this makes sense but even if i do ifmyjsobjectgetstringpromotionnull then i will still get json exception when it checks how would i do a conditional check in my code for null objects so that i can avoid the json exception,['java'] +196556,whats the difference between mixin and extend in javascript libraries i am looking through various libraries and seeing extend pop up a lot but i am also seeing mixin show up yui has both mixins and extensionswhats the difference between these two concepts when would i decide between a mixin and extending an objectthanksmatt,['javascript'] +196558,set position size of ui element as percentage of screen size i am trying to work out if it is possible to use percentage positionssizes when creating a layout what i want is something like this 68vgallery height equivalent of 16 total screen size 16vi am testing on a device which in landscape has a thisplay of 800x480 actual pixels and i am currently forcing it with the followingxml version10 encodingutf8relativelayout xmlnsandroid androidlayout widthfill parent androidlayout heightfill parent gallery androidididgallery androidlayout widthfill parent androidlayout height80px androidlayout margintop 320px relativelayoutobviously i do not want to hardcode fixed px units but i cannot use 68 or 068 for layout margintop for example i have looked at dp units but i am not sure if i can do it that way eitheri have to admit ui design is a weak point of mine so any advice would be gratefully receivededit for future reference if anyone is looking for a similar answer following alan moores suggestion i have the following working exactly how i want itxml version10 encodingutf8linearlayout xmlnsandroid androidorientationvertical androidbackgrounddrawablebground androidlayout widthfill parent androidlayout heightfill parent textview androidlayout widthfill parent androidlayout height0dp androidlayout weight068 androidbackgroundandroidcolortransparent gallery androidididgallery androidlayout widthfill parent androidlayout heightwrap content androidlayout weight016 textview androidlayout widthfill parent androidlayout height0dp androidlayout weight016 androidbackgroundandroidcolortransparent linearlayouti managed to find some other examples of using layout weight and decided to set the textview heights to 0dp and also used floats for the weights working great,['android'] +196568,accessing a class constant using a simple variable which contains the name of the constant i am trying to access a class constant in one of my classesconst my const valueif i have a variable which holds the name of this constant like thismyvar my constcan i access the value of my const somehowselfmyvardoes not work obviously because it is for static propertiesvariable variables does not work either,['php'] +196573,multiple group concat on different fields using mysql i have a query like thisselect productid group concatimageid as images id group concatimagetitle as images title group concatfacetid as facets idgroup by productidand the query works but not as expected because if i have a product with 5 facets and 1 image suppose an image with id7 then i get something like this in images id7if i have 2 images 7 and 3 then i get something like73and in facets i get something like8765487654i think mysql is making some type of union of the differents rows returned by the query and then concatenating everythingmy expected result is for the last exampleimages id 73facets id 87654i can obtain that using thistinct in the group concat but then i have another problemif i have two images with the same title one of them is ommited and then i get something likeimages id 735images title title7and3title5so i miss the relation between images id and images titledoes somebody know if it is possible to make this query in mysqlmaybe i am complicating everything without any real benefitsi am trying to execute only one query because performance but now i am not so sure if it is even faster to execute two queries one for selecting the facets and another for the images for exampleplease explain what do you think is the best solution for this and whythanks,['mysql'] +196590,add a method to a list instance in python i want to add a method to a single instance of the list class examplea 12afirst lambda self return self0i know this do not work but i want something like that works like that i know its not a good practice and i know i should do a whole new class but i think this is possible in python and have not figured out howi am aware ofdynamically add member function to an instance of a class in pythonand dynamically binding python methods to an instance correctly binds the method names but not the methodbut none of those work with a native listthanks,['python'] +196608,how do you query by date and date range in mongo this would be the equivalent of this sql statementselect from example where date 20110921the record is stored with a mongodate field i would also like to know the syntax of the between query,['php'] +196609,how to apply jquery ui theme to my regular html i use jquery ui for the various widgets like dialogs buttons etc i want to continue using the theme for my other webpage elements like erroralert notices and highlight styles so i went to the themeroller page to view what they use for the css around for example an alert noticediv classuiwidget div stylepadding 0 7em classuistateerror uicornerall pspan stylefloat left marginright 3em classuiicon uiiconalertspan strongalertstrong sample uistateerror stylep divdivthere is a wrapper div span with background icon etc do i just copy these or does the jquery ui javascript create some for me whats the proper way to apply themes to nonwidget html,['jquery'] +196612,webkittaphighlightcolor in windows phone is there an equivalent to webkittaphighlightcolor for windows phone 7 mango i am writing a mobile site and i would like it to thisplay the same way across all browsers if possiblei have tried taphighlightcolor and mstaphighlightcolor neither worked,"['html', 'css']" +196615,rails 31 how to run an initializer only for the web app rails serverunicornetc my webapp needs to encrypt its session data what i setup isconfiginitializersencryptorrbrequire opensslrequire myappencryptormyappencryptorconfig random key opensslrandomrandom bytes 128 sessiondelete allappmodelssessionrbrequire attr encryptedclass session activerecordbase attr accessible session id data attr encryptor data key proc myappencryptorconfig random key marshal true rest of model stuffendthat all works great and keeps the session data secured heres the problem when i run my custom rake tasks it loads the initializer and clears all the sessions not goodwhat can i put in my initializer to make sure it only runs for the webapp initialization or what can i put in my initializer to make it not run for rake tasksupdate ok what i have done for the moment is add myapp in rake true unless defined myapp in rake to my rake file and then in my initializer i dounless defined myapp in rake myapp in rake web only initializationendseems to work but i am open to other suggestions,"['ruby-on-rails', 'ruby']" +196618,backbonemodelextend is not a function what have i done wrong i am having a crack at backbone and decided to open a jsfiddle to play aroundunfortunately i keep getting this error being thrownbackbonemodelextend is not a functionmy code var model backbonemodelextendi got this piece of code from a backbone tutorialthe fiddlewhat have i done wrong,['javascript'] +196635,cakephp 200rc2 console backing error i originally thought this error had to do with my path setup i hadseparated the core from the app so i could work more easily with gitsubmodules so i ignored it i just did a fresh checkout from the gitrepo a download of the rc2 source and a cakeinit install of the20 package also uses git and all 3 installs have the same issue ihad beforemy code seems to work fine via the browserthe output of a cake backe model from inside the local copy of thecore in the libcakeconsole folder is herethis totally prevents me from using backe backing a project does notwork backing a new database config does not work it also does notmatter which of the datasources i trycan someone point me in the right direction here i want to use someof the backe tools and work on converting some shells for 20i am using xampp latest version for os x i reinstalled it 20minutes ago as a last ditch attemptosx 1058the databasephp i am working with is here with the passwords removedbut otherwise workingi have tested it with and without the unix socket setting and encodingsettings all works fine from the browser but again not via the cli,"['php', 'mysql']" +196681,submit tag with javascript function i am new to railsi want to call a javascript function when click the submit buttoni used submit tag but the function did not get triggeredi want some thing like the following submit tag onsubmit return validateform i googled the problem but i could not find a solutionplease any one give a solution,['ruby-on-rails'] +196696,how do formtastic and simple form compare how do formtastic and simple form comparewhat the benefits of each,['ruby-on-rails'] +196700,css direct descendant operator not working and it is not ie6 i am trying to do something very simple select the tags which are direct descendants of a tagthe css i am using is as followstabledata tr backgroundcolor red my html looks like thistable classdata tr trtablebut no red background is forthcoming if i remove the character from the css it works i have tried this in firefox ie 8 chrome and safari and all the browsers do exactly the same thinghopefully someone can help me after so many frustrating hours i know i am doing something extremely stupid but i cannot figure out what it is,"['html', 'css']" +196726,how do i get the php uploads directory i have uploaded a file using html php and following is the print r of the filesfile arrayarray name chrysanthemumjpg type applicationoctetstream tmp name gxampptmpphp82dbtmp error 0 size 879394as you can see above the temp file is stored in the tmp name directory i need to get that directory path using php how do i get it tried using sys get temp dir but this is what it returns mei do not want to get the directory from the array or from the file upload data i want to dynamically get the php file uploads directory using a functioncusersadminappdatalocaltemp,['php'] +196743,simple way for removing all non word characters i would like to remove all characters from string using most simple wayfor examplefrom asd3 31ds to asdds i cad do it something like thisasd3 31dsgsubw gsubd asddsbut it looks a little bit awkward maybe it is possible to merge these rexegs in one,['ruby'] +196807,how to create a restful web service with input parameters i am creating restful web service and i wanted to know how do we create a service with input parameters and also how to invoke it from a web browserfor examplepathtodopublic class todoresource this method is called if xmlis request put produces mediatypeapplication xmlmediatypeapplication json public todo getxml todo todo new todo todosetsummarythis is my first todo todosetdescriptionthis is my first todo return todo and i can invoke it using httplocalhost8088jerseyjaxbresttodoand i want to create a method like pathtodo public class todoresource this method is called if xmlis request put produces mediatypeapplication xmlmediatypeapplication json public todo getxmlstring x string y todo todo new todo todosetsummaryx todosetdescriptiony return todo in case of soap based web services i would invoke it like thishttplocalhost8088jerseyjaxbresttodoxabcypqrbut i want to know how to invoke it using rest and also can i pass the parameters as i am doing in the above example when i use rest and jersey,['java'] +196810,html5 javascript api intellisense support in visual studio i started playing with html5css3 and the new javascript apisomething i noticed in vs 2010 is it does not have any support for the new javascript api i was wondering if there is anything i can do about itso in vs2010 if i type var canvas documentgetelementbyiddiagonal var context canvasgetcontext2di do not get any intellisense for the getcontext method etci dont wanna write the code and compile and pray it worksany idea how can i enable intellisense for new javascript,['javascript'] +196811,how to remove items from activerecord query resultset i get a resultset from a rails find query i want to iterate over that resultset and depending on certain criteria drop records from that resultset before passing it on for further processing the additional criteria are external to the data held in the database and hence i cannot include them in the original find querynote i do not want to delete any records from the database just remove them from the resultsetplease can someone give me the code to do thatall help gratefully receivedpurvez,['ruby-on-rails'] +196823,create sql insert script with values gathered from table i need to create a insert script in order to insert in another database the same data if in sql server i select script table as insert to i can easily recreate the skeleton for the insert statement however since i have several records to migrate i would prefer to avoid having to insert the values manuallytherefore is there any way to automatically get the insert script with also the values coming from the target table filled in i know this could be done with ssis but i am wondering whether it would be possible as well with a quicker solution,['sql'] +196832,bindings not applied to dynamicallyloaded xaml i am using xamlreader successfully to load a xaml file and create a frameworkelement to work withthe xaml i am loading has binding expressions in it such astextblock textbinding datacontexttextproperty if i place the frameworkelement i get back from xamlreaderload into a wpf window the binding all works finehowever in this case i am using laurent bugnions excellent article on creating pngs from wpfxaml since the result of xamlreaderload is written directly to a png via a visualbrush it seems the necessary mechanics of wpf to invoke binding expressions are bypassedthis leads me to believe that the actual bindings are not really being invoked just by calling xamlreaderload or that they are not working because of something i do not know about to do with there not being a visual tree until you add the frameworkelement to an existing visual tree or somethingis there something i can do to ensure these bindings are invokedmany thanks in advance,['c#'] +196837,can i assume that the order i send values over post will be model bound to an array in the same order in aspnet mvc i am am working on having a screen that allows the user to change the order of items and when the user clicks on the save button my javascript will look at the order of li items and in the order it finds them it will form an array with an id value and send it back to my application i expect the post data to look likestepids5stepids2stepids1this means that the steps are in the order of 5 then 2 and lastly 1 in my aspnet mvc application i plan to catch it withpublic virtual actionresult reordershort stepids my question is will aspnet mvc always form the stepids array in the same order that values are specified in the post string or do i need to do a more complicated post in order to ensure the order the user picks is the order the server sees,['c#'] +196843,listview onclick event does not fire with linkified email address i have a straight forward listview with a listadapter and custom onitemclick method for the listmy listview items are clickable to perform other functions however some of my listview elements contain an email address that should be clickable tooi found linkify and added it to the email address textview per the docsafter doing so the listview item containing such a clickable textview is now no longer clickable to perform the other functionsi have tried adding the onitemclicklistener after i create the entire view to no avail any ideas on how to have my listview items clickable eventhough they contain a linkified textviewmy deepest appologies for not searching further before asking the question to begin withi have found the answer to my question and posted it as an answer,['android'] +196891,question about optimization in c i have read that the c standard allows optimization to a point where it can actually hinder with expected functionality when i say this i am talking about return value optimization where you might actually have some logic in the copy constructor yet the compiler optimizes the call outi find this to be somewhat bad as in someone who does not know this might spend quite some time fixing a bug resulting from thiswhat i want to know is whether there are any other situations where overoptimization from the compiler can change functionalityfor example something likeint x 1x 1x 1x 1might be optimized to a single x1suppose i haveclass aa a ba ba bcould this possibly also be optimized probably not the best example but i hope you know what i mean,['c++'] +196913,do onmeasure in android returns size including padding and margin i am working on a custom component and would like to know if onmeasure called on children would return width and height of the child including padding and margin of it,['android'] +196915,how to force visual studio debugger to skip specific exceptions i have clientserver silverlight appsome server code throws exceptions that i handle on client when i debug visual studion breaks on those exceptions and i have to hit continue it really slows down developmentis there any way to skip specific exceptions or deal with this somehow,['c#'] +196949,android overlay a view ontop of everything can you overlay a view on top of everything in androidin iphone i would get the new view set its frameorigin to 00 and its width and height to the width and height of selfview adding it to selfview would then cause it to act as an overlay covering the content behind or if it had a transparent background then showing the view behindis there a similar technique in android i realise that the views are slightly different there are three types or more relativelayout linearlayout and framelayout but is there any way to just overlay a view on top of everything inthiscriminately,['android'] +196989,spring mvc ui components i am in the technologies selection phase of a small singlepage web application that will be heavilybased in ajax and which will report to a java backendin a previous question i posted several weeks ago the so community at large felt strongly that i would be better off going with a spring mvcbased web app than with something in jsf since spring is requestoriented and jsf is componentoriented it would only make sense to use spring for something that is going to be getting a lot of asynchronous requestsif i were going the jsf route then my next set of decisions would be whether or not to use socalled ui component libraries for the view technology such as primefaces icefaces or myfacesso i am wondering does spring mvc have anything similar to say primefaces or its likes for creating the view component for my pages i know its not componentbased but i am not all that familiar with spring mvcs web platform and was wondering what are some de facto standards if any or typical technology stacks that spring web developers use for constructing nice web pagesand if spring just uses runothemill template engines would something like freemarker sufficei guess this is a best practicestype question for a budding spring web developerthanks in advance,['java'] +196995,provisioning profiles push notifications production vs development i am building an ios app that uses push notifications and i am finally ready to submit it before i do i would like to test out push notifications off the production server to make sure everything is working correctly thus far the sandbox environment has been working fineafter doing quite a bit of searching i learned that switching the servers over from sslgatewaysandboxpushapplecom2195 to sslgatewaypushapplecom2195 was not enough and that production push tokens are different from sandbox push tokens instead apparently i need a new provisioning profile with production entitlements new certs installed on my server and to rebuild my app with said profile so that it knows to create the correct push tokens sweetso after going through all the steps i cannot even make a build run on my phone xcode says this profile cannot be installed on devices hmhere are the steps i have taken if i am missing something please let me knowin my ios developer center i have made sure that my appid is enabled for production under the apple push notification servicealso in my ios developer center i have created my production push ssl certificate gone through the necessary conversion steps and installed the resulting pem on my serverper the instructions i have create a new provisioning profile containing the app id you wish to use for notifications i have done this by going to provisioning and clicking on the thistribution tab and making a new profile i have confirmed that production is set under the entitlements section of this profilei have selected the provisioning profile in my project settings i get the message this profile cannot be installed on devices and i am stuckany help is greatly appreciated thanks in advance,"['iphone', 'ios']" +196997,syntax error with keyerror in python 32 i am a beginner using python 32 and i have a book whos code is all in python 26 i wrote part of a program and keep gettingsyntax error invalid syntaxthen pythons idle highlights the comma after keyerror in my codefrom tank import tanktanks atankalice btankbob ctankcarolalive tanks lentankswhile alive tanks 1 print for tank name in sorted tankskeys print tank name tankstank name first raw inputwho fires lower second raw inputwho at lower try first tank tanksfirst second tank tankssecond except keyerror name print no such tank exists name continue,['python'] +196999,are values stored in nsuserdefaults removed when the app that put them there is uninstalled if i put a token a string into nsuserdefaults lets say as a paramter passed to a rest api that is used by the app and the app is uninstalled will the string remain on the device,"['iphone', 'ios']" +197026,unruly css pseudo element box shadow i am working on a new layout for a website and i am extremely close to achieving the result i want however there is one problem i am using an adaptation of the technique described here see the 3 column example just below the gorillas basically my version uses an absolutely positioned css pseudo element as the backgrounds for the left columnmy problem arises when i attempt to apply a boxshadow to the pseudo element the element and its shadow always appear on top of my main columnto make all of this clearer i have created a simple example page here my fear is that since i am using a pseudo element based on the parent of my main column it will never be able to sit under it but i am hoping there is some way this can be worked around any ideas,"['html', 'css']" +197041,how to include package data with setuptoolsthistribute when using setuptoolsthistribute i can not get the installer to pull in any package data files everything i have read says that the following is the correct way to do it can someone please advisesetup namemyapp packagesfind packages package data myapp datatxt include package datatrue zip safefalse install requiresthistributewhere myappdata is the location of the data files,['python'] +197078,posting on tumblr using oauth and c i am trying to develop a simple application to interact with tumblr using v2 apis i am able to go past every step in the oauth flow thanks to the documentation found on twitter and obtain an authorized and authenticated token and secret but when it comes to posting i get a 401 unauthorized error this is the relevant code snippet private void post clickobject sender systemwindowsroutedeventargs e url new urimyblogtumblrcompost random random new random nonce randomnext12340 9tostring timespan ts datetimeutcnow new datetime1970 1 1 0 0 0 0 timestamp converttoint64tstotalsecondstostring string method post stringbuilder sb new stringbuilder sbappendformat0 method sbappendformat0 uppercaseurlhttputilityurlencodeurltostring sbappendformatbody3d026 uppercaseurlhttputilityurlencodetextboxtext sbappendformatoauth consumer key3d026 consumerkey sbappendformatoauth nonce3d026 nonce sbappendformatoauth signature method3d026 hmacsha1 sbappendformatoauth timestamp3d026 timestamp sbappendformatoauth token3d026 token sbappendformatoauth version3d026 10 sbappendformattype3d0 text systemdiagnosticsdebugwritelinesbtostring string signingkey consumersecret secret hmacsha1 signing new hmacsha1encodingasciigetbytessigningkey byte bytearray encodingasciigetbytessbtostring memorystream stream new memorystreambytearray signature converttobase64stringsigningcomputehashstream servicepointmanagersecurityprotocol securityprotocoltypessl3 stringbuilder header new stringbuilder headerappendoauth headerappendformatoauth consumer key0 consumerkey headerappendformatoauth token0 token headerappendformatoauth nonce0 nonce headerappendformatoauth timestamp0 timestamp headerappendformatoauth signature method0 hmacsha1 headerappendformatoauth version0 10 headerappendformatoauth signature0 uppercaseurlhttputilityurlencodesignature systemdiagnosticsdebugwritelineheadertostring httpwebrequest request httpwebrequestwebrequestcreateurl requestmethod webrequestmethodshttppost requestheadersaddauthorization headertostring try httpwebresponse response requestgetresponse as httpwebresponse streamreader reader new streamreaderresponsegetresponsestream if readerreadtoend 201 created controlinvokemethodinvokerdelegate statustexttext post successfully sent catch exception ex systemdiagnosticsdebugwritelineexmessage the function is called upon clicking on a button and get the body text from a text box the signing part is correct because it has been tested with other services twitter etc and it still provides valid signatures for tumblr itself the authorization header is pretty much the same i have used to request a token and to authorize it and the base string only contains the type of the content text in this case and the body apart from the oauth standard parameters i also checked the code with the tools available on hueniversecom but still nothingprobably i am missing some http header or i am posting the wrong request any ideas thanks,['c#'] +197079,setting button text color with a style i have not been able to set the text color of a button using a predefined style i must be missing something simple for example i have a button button androidididcalculate button androidlayout widthfill parent androidlayout heightwrap content androidtextstringcalculate androidbackgrounddrawablerounded bottom shape androidpadding5dp androidtextappearancestylecalcresultstyle buttonand the corresponding style isstyle namecalcresultstyle item nameandroidtextsize12spitem item nameandroidtextcolorfitemstylethe size portion works fine but the color does not the only workaround i have found is to set the textcolor on the actual button which means changing colors on a number of buttons becomes a pain i also prefer to set the textcolor attribute in my styles using a color reference such as colorbrown for example but setting the color using a reference or explicitly seems to make no difference,['android'] +197090,c char differs in levels of indirection from char 6 can someone please explain to me whats wrong with the following and more importantly whyint main int argc char argv char array array char test test array test0 z printf sn array return 0editmy example above was based on a function like this that was crashingvoid apple char pp pp malloc 123 pp0 a technically this is correct but in bad form pp1 b incorrect but no crash pp2 0 incorrect and crashas pointed out to me by vaughn cato although pp0 a does not crash it is in bad form the correct form is the parenthesisvoid apple char pp pp malloc 123 pp0 a correct pp1 b correct pp2 0 correctalso as another poster mk pointed out the faq covers the difference between arrays and pointers,['c'] +197141,list and linq to sql performance issue i have one table my sql with 2 millions records and one list with 100 records i have list except lamda expression for finding all those urls that is in list but not in tablenow issue is that it is taking lot of time around 5 mins i am working in powerful vps and code and database in same serverplease suggest me all possible way to increase the performance of linq to sql and linq to entitymy code isreturn urlsexceptdbcontextpostedurllistsselectcrawl crawlpostedurltolisttolistwhere urls is list which contain 100 urls and postedurllists is a table that contains 2 millions recordthanks,"['mysql', 'sql']" +197156,instrumenting cc codes using llvm i just read about the llvm project and that it could be used to do static analysis on cc codes using the analyzer clang which the front end of llvm i wanted to know if it is possible to extract all the accesses to memoryvariables local as well as global in the source code using llvmis there any inbuilt library present in llvm which i could use to extract this informationif not please suggest me how to write functions to do the sameexisting source code reference tutorial exampleof what i have thought is i would first convert the source code into llvm bc and then instrument it to do the analysis but do not know exactly how to do iti tried to figure out myself which ir should i use for my purpose clangs abstract syntax tree ast or llvms ssa intermediate representation ir but could not really figure out which one to usehere is what i m trying to dogiven any cc program like the one given below i am trying to insert calls to some function before and after every instruction that readswrites tofrom memory for example consider the below c program accountcppinclude stdiohclass account int balancepublic accountint b balance b int read int r r balance return r void depositint n balance balance n void withdrawint n int r read balance r n int main account a new account10 adeposit1 awithdraw2 delete aso after the instrumentation my program should look likeinclude stdiohclass account int balancepublic accountint b balance b int read int r foo r balance foo return r void depositint n foo balance balance n foo void withdrawint n foo int r read foo foo balance r n foo int main account a new account10 adeposit1 awithdraw2 delete awhere foo may be any function like get the current system time or increment a counter so on i understand that to insert function like above i will have to first get the ir and then run an instrumentation pass on the ir which will insert such calls into the ir but i do not really know how to achieve it please suggest me with examples how to go about italso i understand that once i compile the program into the ir it would be really difficult to get 11 mapping between my original program and the instrumented ir so is it possible to reflect the changes made in the ir because of instrumentation into the original programin order to get started with llvm pass and how to make one on my own i looked at an example of a pass that adds runtime checks to llvm ir loads and stores the safecodes loadstore instrumentation pass and but i could not figure out how to run this pass please give me steps how to run this pass on some program say the above accountcpp,['c++'] +197198,any way to get json data of a google doc spreadsheet using jquery without make the doc public i am trying to get data from a google doc spreadsheet using javascript and jquery in order to do some math with the numberswith the next code i got it for public spreadsheetsfunction getdata key wid f return getjson spreadsheetsgooglecomfeedscells key wid publicbasicaltjsoninscriptcallback function data the content of this function is not important to the question var entryidrc rdcd var retdata retdatamat for var l in datafeedentry var entry datafeedentry l var id entryidt var m entryidrcexec id var rc if m null r new number m 1 c new number m 2 var row retdatamat r if typeof row undefined retdatamat r retdatamat r c entrycontent if typeof f undefined f retdata else consolelog retdata when tried for private ones i got the data in xml using the urlspreadsheetsgooglecomfeedscells key wid privatebasic this test checks also for the availability the firewall the permission setup and the login state of the current userbut adding the last part altjsoninscriptcallbackf to get the data in json throws an not found error 404 also got if only altjson is addedsummary of situation public privatexml yes yesjson yes questionthe use of json against google is described in the use of google spreadsheet api is described inany way to get json data of a gdoc spreadsheet using javascript without make the doc publicly availablethanks in advance,"['javascript', 'jquery']" +197210,embed pythondsl for scripting in an php web application i am developing an web based application written in php5 which basically is an ui on top of a database to give users a more flexible tool i want to embed a scripting language so they can do more complex things like fire sql queries do loops and store data in variables and so on in my business domain python is widely used for scripting but i am also thinking of making a simple domain specific language the script has to wrap my existing php classesi am seeking advise on how to approach this development task update i will try scripting in the database using plpgsql in postgresql this will do for now but i cannot use my php classes this way lua approach is appealing and seems what is what i want besides its not python,"['php', 'python']" +197255,set table row height my lacking skills of css is giving me a headache as presented in this picture below captured from firebugusing a gwt like framework called vaadin i have given a table component the class name m2mmodaltable and i want set a minheight to the four rows in that table however i cannot seem to get it to work and as you see from the image the table does not even seem to have the class name m2mmodaltable but vtabletable instead styles are being added outside my involvement since i am using an already setup framework libraryso can anyone who has good knowledge of css class referring tell me what i should write in the style sheet to set the row height of the tablethank youedit thank you avall for the help and i found that writing the css asm2mmodaltable vtabletable thm2mmodaltable vtabletable td height 55px minheight 55pxwill only set the style on the table in question and not all tables in the application,['css'] +197274,trigger a button click inside a jquery ui dialog it is a very simple question that i am not finding an answer for it i have a dialog and in some events happening inside the dialog i want to click one of the dialog buttons the code which defines the dialog isvar dialog divdialog autoopen false title title resizable false buttons cancel text messagescancel click functionthisdialogclose ok text messagesok click okbuttoncallback and in my event i can get the dialog find the buttons but i can not trigger the click event with right reference passed as this i do thisbuttons dialogdialogoption buttonsand i have the buttons each of them has the click function if called directly or through triggerclick they call the click event of button but with the button itself as this not the dialog objecti saw somewhere to callbuttonsokapplydialogbut my buttons have absolutely no apply functioni am not sure what can i do,['jquery'] +197288,is there any way to get around name collisions in nested structures in my mustachejs templates i am really having problems with name collisions in my mustache templates using mustachejs this example illustrates those two problemsi am passing this datarecs code foo id 1 childrecs id 2 code bar id 3 into this template recs record id id childrecs this child code is code and its parent id is id childrecsrecsexpectedrecord id 1this child code is and its parent id is 1this child code is bar and its parent id is 1actualrecord id 1this child code is foo and its parent id is 2this child code is bar and its parent id is 3there is no way in the nested childrecs block to access the parent recsidrecs field it is overwritten by the childrecsidchildrecsif a variable in childrecs is missing and a parent variable of the same name exists there is no way to prevent it from printing the parent variablemy nested structures are very deep and there are many name collisions so renaming them in such a way that they do not collide is not a viable option is there any other way to solve my problems,['javascript'] +197296,can i use a settimer api in a console c application i have a console application that is using a dll file that uses a settimer call to create a timer and fire a function within itself the call is belowsettimerhwndnull 0 timer num timerprocunsyncmsgtimer 0 it is expecting to receive timer messages but this never happens i assume because mine is a console application and not a standard windows gui application like where the dll file was originally used this stops a key part of the dll files functionality from workingmy application needs to stay a console application and i cannot change the dllis there a work around to make this work,['c++'] +197306,why does concurrent gc sometimes cause executionengineexception per msdn according to msdn there is a tip stating that a net application running under heavy load with concurrent garbage collection either gcconcurrent enabledtrue or unspecified since it is the default behavior may throw an executionengineexception is anyone aware of a microsoft kb article or other source that provides additional background on thiswe have experienced this directly with an nhibernate 32based windows service application which will invariably crash after at most a few hours of operation we were able to track down the exception to the isessionflush callthere is a thread on nhusers reporting what appears to be the same problem his suggested workaround which was to thisable concurrent gc has worked for us so far although switching to servermode gc gcserver enabletrue which implicitly thisables concurrent gc also did the trick before submitting this to ms as a bug i would like to find out if anyone out there has additional information on the concurrent gc instablity that the tip mentions,['.net'] +197311,what does a single splatasterisk in a ruby argument list mean i was poking through the rails 3 activerecord source code today and found a method where the entire parameter list was a single asteriskdef savei could not find a good description of what this does though i have some ideas based on what i know about splat arguments what does it do and why would you use it,['ruby'] +197322,one button firing another buttons click event i would like two submit buttons on a form i have my team building one above the fold and one below i am getting complaints from my tech team about adding it because it requires some server side coding to make sure the user does not click it more than once apparently they have it one button but to add that validation to two would be a problemcan you not just call the button the same thing with the same id and wouldnt the form treat it as one button another option i thought would be for new button to fire a click even on the other button then they still have one click even for the form but i get my two buttons how would i write thatthanksadma,['javascript'] +197326,is there a good simplesamlphp slo example one of our clients is requesting that we implement single logout slo through saml their side of the saml service is the identity provider while ours is the service provider singlesignon sso works by validating the users credentials with the clients idp then redirecting the user to a login page on yet another platform with a token that lets them log straight in that platform knows absolutely nothing about saml and in particular does not share the simplesamlphp session statelogout needs to happen two ways thoughif the user hits the logout button on our platform need to log them out of our site and hit the idps slo serviceif the user hits the logout button on the clients side or on another service providers side the client idp will hit our sps slo service which then needs to log them out of our real platform before redirecting the user back to the sps logout response pagei am able to convince our platform to redirect the user to an arbitrary page on logout so i think the first part can be achieved by a page that uses simplesaml auth simplegetlogouturlsuch a page might also work when hit from the idp side but the saml specs are complicated enough that i cannot be sure until we try it however the sp configuration in configauthsourcesphp does not accept a singlelogoutservice parameter the metadata as produced by wmodulephpsamlspmetadataphpentityid still lists wmodulephpsamlspsaml2logoutphpentityid as the singlelogoutservice location if that page is necessary for clearing the simplesamlphp session that is fine but i need to know how to slip in the extra redirects required for logging the user out of our platformi have tried searching for examples but all i get is api references it would also be nice to know how i can test logout without attempting to set up my own idp is there a service like the openidpfeideno that handles slo as well as sso,['php'] +197346,java dateformat parse does not respect the timezone calendar cal calendargetinstancetimezonegettimezoneamericanew yorkdateformat df new simpledateformatymmdd hhmmss zdfsettimezonetimezonegettimezoneamericanew yorktry systemoutprintlndfformatcalgettime systemoutprintlndfparsedfformatcalgettime catch parseexception e eprintstacktracehere is the result20110924 141051 0400sat sep 24 201051 cest 2011why when i parse a date i get from format it does not respect the timezone,['java'] +197351,why is init py not being called i am using python 27 and have the following files init pyaoeupy init py has the following contentsaoeu aoeuaoeu aoeuaoeuaoeuso i would expect running aoeupy to error when python tries to load init py but it does not the behavior is the same whether pythonpath is set to or unsetwhats going on,['python'] +197362,findbyidentity performance differences the following code works fine from a variety of machines on our domainvar context new principalcontextcontexttypedomainvar principal userprincipalfindbyidentitycontext domainusernamehowever if i run this similar code on a machine that is not on a domain it works but the findbyidentity line takes 2 secondsvar context new principalcontextcontexttypemachinevar principal userprincipalfindbyidentitycontext machinenameusernamecan this performance difference be addressed by supplying special parameters to the principalcontext constructor andor the findbyidentity method is there a setting in iis or windows that could be tweakedat the very least can anybody tell me why it might be slower in the second scenariothe code is running from an aspnet mvc 3 app hosted in iis 75 integrated pipeline on windows server 2008 r2,['.net'] +197371,must template parameters be types in the bjarne stroustrup c book chapter 13 page 331 it said that a template parameter can be used in the definition of subsequent template parameter and it gives the following codetemplateclass t t def val class cont can anyone provide an example of how to use this template for example how to initialize an object of cont it look to me that def val is not a type argument and should not be placed in am i wrongthanks a lot,['c++'] +197374,only count a download once it is served we have this code which serves a downloadpublic class downloadrelease ihttphandler public void processrequest httpcontext context snip contextresponseclear contextresponsecontenttype applicationoctetstream contextresponseaddheadercontentthisposition attachment filename originalfilename contextresponsewritefilesettingsreleasefilelocation actualfilename log download constructorversionreleasedownloadnewreleasedownloadactualfilenameit works fine except that the log download code runs as soon as the download starts seemingly not when the download has fully completed as we expectcan someone explain why this is and how to change it so it only logs when it is completed we do not want to count partial downloads,"['c#', 'asp.net']" +197397,gcc c compile error void value not ignored as it ought to be i am having trouble compiling some c codewhen i compile il get this error playerc in function alogina playerc5417 error void value not ignored as it ought to bethis is the code for the errorstatic bool loginconst char username const char password sp error err sp session loging sess username password remember me printfsigning inn if sp error ok err printfcould not signinn return 0 return 1any way to bypass this kind of errorthankseditall sp functions are from libspotify,['c'] +197398,can jquery check whether input content has changed is it possible to bind javascript jquery is best event to change form input value somehow i know about change method but it does not trigger until you the cursor leaves the input field i have also considered using keyup method but it reacts also on arrow keys and so on i need just trigger an action every time the text in the input changes even if it is only one letter change,"['javascript', 'jquery']" +197409,how to thisable just vertical scrolling in a uiscrollview uiscrollview has a property scrollenabled to thisable all scrolling but i want to thisable only the vertical scrollingis that possible thanks,['ios'] +197411,writing formatted xml with xmlwriter i am trying to write to an xml file to the isolated storage but i would like to format it like thissampledata item property1aliquaxx item property1integer item property1quisque item property1aenean item property1mauris item property1vivamus item property1nullam item property1nam item property1sed item property1class sampledatabut i am buggered if i can work it out can anyone helpthanksstruggling newbie,['c#'] +197418,android convert first letter of string to lower case i am looking for a way to convert the first letter of a string to a lower case letter the code i am using pulls a random string from an array thisplays the string in a text view and then uses it to thisplay an image all of the strings in the array have their first letter capitalized but image files stored in the app cannot have capital letters of coursestring source drawablemonb is randomly selected from an array not hardcoded as it is herestring monb picturei need code here that will take monb and convert it from picture to picturestring uri source monb int imageresource getresourcesgetidentifieruri null getpackagename imageview imageview imageview findviewbyidridmonpic drawable image getresourcesgetdrawableimageresource imageviewsetimagedrawableimagethanks,['android'] +197432,white pure css triangle bug on firefox 6 windows notice the gray border on the white triangle this only happens on ff 6 windows i did not test on older ff versionis there a fix to this it looks like bad antialiasing or something,"['html', 'css']" +197463,how to pass argument to delegate method in rails i would like to have a dashboard to thisplay summary of multiple models and i implemented it using presenter without its own data i use an activemodel class without data tableclass dashboard attr accessor user id def initializeid selfuser id id end delegate username password to user delegate address to account delegate friends to friendshipend by delegate i want to be able to call dashboardaddress and get back accountfind by user iddashboarduser idaddress if dashboard was an activerecord class then i could have declared dashboardbelongs to account and delegate would work automatically ie account would know it should return address attribute from account with user id equals to user id in dashboard instance but dashboard is not an activerecord class so i cannot declare belongs to i need another way to tell account to lookup the right recordis there a way to overcome this problem i know i can fake dashboard to have an empty table or i can rewrite users instance methods to class methods that take argument but these solutions are all hacksthank you,['ruby-on-rails'] +197472,jetty classpath issues i am currently running solr out of a jetty container that it ships with it runs correctly when run from the command line via java jar startjarwhen i am in the same directory as startjar unfortunately i need to be able to launch jetty from any directory not just the one that contains startjar i have tried many options such asjava dsolrsolrhomesolr djettyhomesolr djettylogssolrlogs cp solrstartjarsolrlibjettyutil6126patchedjetty1340jarsolrlibjetty6126patchedjetty1340jarsolrlibservletapi2520081211jar jar solrstartjar solretcjettyxml every time i get this backtracejavalangclassnotfoundexception orgmortbayxmlxmlconfigurationat javaneturlclassloader1runurlclassloaderjava217at javasecurityaccesscontrollerdoprivilegednative methodat javaneturlclassloaderfindclassurlclassloaderjava205at javalangclassloaderloadclassclassloaderjava321at javalangclassloaderloadclassclassloaderjava266at orgmortbaystartmaininvokemainmainjava179at orgmortbaystartmainstartmainjava534at orgmortbaystartmainstartmainjava441at orgmortbaystartmainmainmainjava119,['java'] +197474,what does wrong number of arguments 1 for 0 mean in ruby what does argument error wrong number of arguments 1 for 0 mean,['ruby'] +197476,eliminating initial keypress delay when you type into a textbox and hold a key you get a depending on the initial key press delayaddkeylistenernew keyadapter public void keypressedkeyevent e handle key press here i am creating a game in which the users reflexes are very important how can i eliminate this delay completely the above code does not work i have also tried overriding processkeyevent with no luck,['java'] +197478,conditional injection of bean i want to have inject a bean based on a string parameter passed from clientpublic interface report generatefilepublic class excelreport extends report implementation for generatefilepublic class csvreport extends report implementation for generatefileclass mycontroller report report public httpresponse getreport i want report instance to be injected based on the parameter passed any help would be greatly appretiated thanks in advance,['java'] +197480,what could this generic class declaration could mean i know this is not a good question to ask and i might get cursed to ask it but i cannot find any place to get help on this questionbelow is a generic class that appeared in my interview question which i have already failed the question was to tell what this class declaration is doing and in what circumstances this could be used for i have very limited understanding of generic programming but i understand that t is type and extends here means that the type should have inherited simplegenericclass but i do not understand the at the end and in what circumstances this class could be potentially used for public abstract class simplegenericclasst extends simplegenericclass,['java'] +197513,how does the compiler benefit from cs new final keyword c11 will allow to mark classes and virtual method to be final to prohibit deriving from them or overriding themclass driver virtual void print constclass keyboarddriver public driver void printint const finalclass mousedriver final public driver void printint constclass data final int values this is very useful because it tells the reader of the interface something about the intent of the use of this classmethod that the user gets diagnostics if he tries to override might be useful toobut is there an advantage from the compilers point of view can the compiler do anything different when he knows this class will never be derived from or this virtual function will never be overriddenfor final i mainly found only n2751 referring to it sifting through some of the thiscussions i found arguments coming from the ccli side but no clear hint why final may be useful for the compiler i am thinking about this because i also see some thisadvantages of marking a class final to unittest protected member functions one can derive a class and insert testcode sometimes these classes are good candidates to be marked with final this technique would be impossible in these cases,['c++'] +197530,is it possible to stub a method in a parent class so that all subclass instances are stubbed in rspec given a parent class fruit and its subclasses apple and banana is it possible to stub the method foo defined in fruit so that any calls to method foo on any instances of apple and banana are stubbedclass fruit def foo puts some magic in fruit endendclass banana fruit endclass apple fruit endfruitany instancestubsfoo did not work and it looks like it only stubs for instances of fruit is there a simple way to achieve this other than calling stubs for every subclassesfound this link raising the similar question but it looks like it has not been answered yet threadthread981af7c86dad5e,"['ruby-on-rails', 'ruby']" +197542,jquery tokeninput add if not exists i am in the process of writing a script that builds upon user input i have some fields that its values need to be quired from the database and if no entry found i want to add a new value so the next user will find it through autocompletei found this great looking easy to implement jquery plugin called tokeninput but it does not seem to accept entries that are not available in my database queryheres the link for the plugin is there a workaround for this or do you suggest another plugin that already has this featureand i am a little bit concerned about the security aspect of this sort of websites is there something special i need to take care of when doing this sort of implementation,"['php', 'jquery']" +197576,debugging c code involving use of vector string stl i am c beginner when i try to debug c code using following constructs like string vector of certain native types stl etc debugging gets tedious i use ms visual studio 2010 visual c 2010 express eg while using string as belowstring strgetlinecin strfori0 istrsizeiwatch window does not show values for stri it says overloaded operator not found i have to manually collapse the whole string variable str and see the char elem at that particular index which gets cumbersome while using vector as below same issue if i set variable v1k in watch window same errorvectorint v1100forint k0k100k v1push backk tried using simple stl iterators like itbegin itend and algorithms like sort reverse i could not debug inside those functions by stepping or could not set break point into thosei know they being inside stl or some such standard library they would be assured to be bugfree but one can still use them incorrectly by passing something invalidincorrectcoming from c language usage of many years to c i find this lack of debug ability or some restrictions in that painful while i am trying to understand large chunks of c code written by someone else at work my questions what are effective ways to debug working code to understand its functionality while using idioms like step in breakpoints watch point watch windows is any particular debugger betterworse than otherlike say gdb being better or are there any specific trickstips to aid debuggingin general how to analyze a c code to understand its working,['c++'] +197577,detecting circular references in sql i have the following tablecreate table x a sometype not null b sometype not null c sometype null primary key ab foreign key ac references x abthe entities stored in x are hierarchically organized if a row a1b1c1 exists and c1 is not null then it is considered to be a child of a1c1c2 whatever c2 is since an item cannot descend from itself i would like to make it illegal that circular hierarchical sequences exist legalinsert into x a1b1nullinsert into x a1b2b1insert into x a1b3b2insert into x a1b4b2 currently legal but i want to make it illegalupdate x set c b1 where b b1 b1b1 update x set c b2 where b b1 b1b2b1 update x set c b3 where b b1 b1b2b3b1 update x set c b4 where b b1 b1b2b4b1 update x set c b2 where b b2 b2b2 update x set c b3 where b b2 b2b3b2 update x set c b4 where b b2 b2b4b2 update x set c b3 where b b3 b3b3 update x set c b4 where b b4 b4b4 how do i do thisalternatively i could add a field representing the level in the hierarchy to the tablecreate table x a sometype not null b sometype not null c sometype null level int not null primary key ab foreign key ac references x abthen i would like to require that level be 0 when c is null and parents level 1 otherwisei am using sql server 2008 r2,['sql'] +197602,remove the extension of a file given a filename like packagezip imagejpeg videoavi etci would like to remove the extension if exists how can i make this in java thanks,['java'] +197604,my sub query is adding 20 seconds to the execution time how can i speed it up i have a table of sent sms text messages which must join to a delivery receipt table to get the latest status of a messagethere are 997148 sent text messagesi am running this queryselect mid muser id mapi key mto mmessage msender id mroute msubmission reference munique submission reference mreason code mtimestamp did as dlrid ddlr statusfrom messages sent mleft join delivery receipts don dmessage id midand did select maxid from delivery receipts where message id midwhich returns 997148 results including the latest status of each messagethis takes 228688 seconds to executehere is the sql for messages sentcreate table if not exists messages sent id int10 unsigned not null auto incrementuser id int10 unsigned not nullapi key varchar40 not nullto varchar15 not nullmessage text not nulltype enumsmsmms not null default smssender id varchar15 not nullroute tinyint1 unsigned not nullsupplier tinyint1 unsigned not nullsubmission reference varchar40 not nullunique submission reference varchar40 not nullreason code tinyint1 unsigned not nullreason text not nulltimestamp timestamp not null default current timestamp on update current timestampprimary key idkey user id user idkey api key api keykey sender id sender idkey route routekey submission reference submission referencekey reason code reason codekey timestamp timestampkey to tokey unique submission reference unique submission reference enginemyisam default charsetutf8 auto increment10342 and for delivery receiptscreate table if not exists delivery receipts id int10 unsigned not null auto incrementmessage id int10 unsigned not nulldlr id bigint20 unsigned not nulldlr status tinyint2 unsigned not nulldlr substatus tinyint2 unsigned not nulldlr final tinyint1 unsigned not nulldlr refid varchar40 not nulldlr phone varchar12 not nulldlr charge tinyint3 unsigned not nullprimary key idkey message id message idkey dlr status dlr status enginemyisam default charsetutf8 auto increment1468592 here is an explain of the sql,"['php', 'mysql', 'sql']" +197607,large php session slowing down web application i have a web application where complex permissions determine whether or not a user has access to each of thousands of different files a user can see all files but there is an indicator to open files that they have access to a user has access to a file if someone else in their organization has access to it or if someone that they are in a collaboration with has shared access to that file right now i have a complex php function that generates a large php session by building arrays of the files a user has access to either in their organization or their collaborations and merging these access arrays when these files are thisplayed to the user php checks this array to see if they have access and if they do it adds the button to open the file i am doing it this way because running the query to check for access for each individual file ended up taking way too long when thisplaying long file lists and phps in array was substantially fasterthe problem isthe php session has gotten so large that it seems to be slowing down simple website functions to a crawl and i need to think of a new way to do this my question iswhat would be the best way to replace php sessions for storing file permissions and file locations for thousands of files a user has access to so that when lists of files are being thisplayed php can rapidly retrieve this information without needing to run a query for each individual file,"['php', 'mysql']" +197617,facebook userbundle authentication with symfony2 i am trying to authenticate my users via facebook or userbundle on symfony2heres what i did so far and it works although not as i wantfirewalls main pattern fos facebook app url server url httplocalhostfacebookapp login path fblogin check path fblogin check default target path provider my fos facebook provider form login check path login check anonymous true logout handlers fos facebooklogout handlerthe problem with that config is that when the user is not logged in he is redirected to login form login while i would like him to be redirected to facebook authentication by defaulti already tried simply removing the form login but then if i access login which is how i want users to login outside facebook it does not know the login check route to submit the login formmaybe chain provider would be a solution i did not get it working either,['php'] +197623,user permissions based mef components i did my first steps toward mef few month ago and everything seemed to be okay till now what i want to do is to use mef in now of my real applications and load or we can say thisplay ui components based on authenticated users permissions i am developing patient management system for clinic and i want to implement scenario where mef composed ui components are thisplayed based on user type for example if authenticated user is doctor i want to show particular components and hid otherswhat i am trying to achieve is something likeisystemcomponent which has some properties and methods so administration can control each user access level and based on db records mef composed controls will be thisplayed to the enduser i also think of using metadata interface while exporting components so using this how can i get the desired result any right direction will be appreciated,['c#'] +197635,what are the common use cases for iphone os version max allowed what are the situations in which you would use the iphone os version max allowed check what about iphone os version min required,['ios'] +197639,thisadvantages of using basic4android i am currently researching the pros and cons about basic4android i have a good list of pros but what are some thisadvantages to using this what limitations does this tool havethankyou for the help,['android'] +197651,how do you change uibutton image alpha on thisabled state i have a uibutton with an image and on its thisabled state this image should have 3 alphauibutton button uibutton buttonwithtypeuibuttontypecustomuiimage arrowimage uiimage imagenamedarrowpngbutton setimagearrowimage forstateuicontrolstatenormal the arrow should be half transparent herebutton setimagearrowimage forstateuicontrolstatethisabledhow do i accomplish thisupdate i noticed by default uibutton does reduce the alpha of the image on thisabled state probably at 5 but i would like to know how to finetune this value,"['ios', 'iphone', 'objective-c']" +197654,rails controller method or instance variable inside a helper i am using the bitly gem and would like to have access to the bitly api inside my helper methods which get called by views and mailers to generate urlsi initiate an api connection in this method in my applicationcontrolleris there a more appropriate place to do this btwclass applicationcontroller actioncontrollerbase before filter bitly connect def bitly connect bitlyuse api version 3 bitly bitlynewapp configbitly username app configbitly api key endendby default i do not have access to bitly in my helpers can you suggest a way to accomplish thatthe only related thread i found was not helpfulrails 3 and controller instance variables inside a helperthanks,['ruby-on-rails'] +197675,android run bash command in app hi i am developing an application which requires me to run some bash code is there a way i can hard code the script into my app and then run it for instance this is a very simplified examplesystembinshif f sdcardhellotxt thenecho hello world sdcardhellotxtelseecho goodbye world sdcardgoodbyetxtfii have the following method for running one line bash commands but need to run something like that that is on multiple lines again that above code is a very simplified example what i am actually doing must be run through a script and cannot be done through java i also want to have it hard coded i know could have the script stored on the phone and run it with the following but do not want the script just out there would rather it hard coded in the apublic boolean execcommandstring command try runtime rt runtimegetruntime process process rtexecsu dataoutputstream os new dataoutputstreamprocessgetoutputstream oswritebytescommand n osflush oswritebytesexitn osflush processwaitfor catch ioexception e return false catch interruptedexception e return false return true thank you for any help with my issue,"['java', 'android']" +197682,when to use navigator or package explorer view i have imported an existing project built using maven into my eclipse workspace should we use navigator or package explorer to view our projects in eclipse,['java'] +197690,how to send parameters with jquery get i am trying to do a jquery get and i want to send a parameter heres my function function var availableproductnames getmanageproductsdooption1 functiondata availableproductnames datasplit alertavailableproductnames nameinputautocomplete source availableproductnames this does not seem to work i get a null in my servlet when i use requestgetparameteroptionif i type the link into the browser it works perfectlyi also triedget manageproductsdo option 1 functiondatawhich does not work eithercan you please help meeditalso tried ajax type get url manageproductsdo data option1 success functionmsg availableproductnames msgsplit alertavailableproductnames nameinputautocomplete source availableproductnames still getting the same result,['jquery'] +197699,javascript regex to change all relative urls to absolute i am currently creating a nodejs webscraperproxy but i am having trouble parsing relative urls found in the scripting part of the source i figured regex would do the trick although it is unknown how i would achieve this is there anyway i can go about this also i am open to an easier way of doing this as i am quite baffle about how other proxies parse websites i figured that most are just glorified site scrapers that can read a sites source a relay all linksforms back to the proxy,['javascript'] +197716,any reason to favor mathml syntax over tex in mathjax mathjax opensource javascript library to render maths support multiple syntaxes including mathml and latex are there any reason to favor the use of the mathml syntax for inpage equations vs the tex syntax it only looks to me that mathml is vastly more verbose,"['javascript', 'html']" +197718,how can class be of the class class and not have class instance methods i was studying how the ruby interpreter is implemented and one question occurred that did not get an answer yet for me that is the one in the title since class r cclass has super set to itself ignoring metaclasses since actually super is the metaclass of r cclass if i send one method to the class object this will be looked in the method table of class class but class class is class so should not i end up looking the instance methods of class but that is not the case since in the documentation class class methods and class instance methods are separated in the search method in evalc of ruby i did not find any special check for the class class can anyone shed some light on this,['ruby'] +197730,has the webkitselection selector ever been supported there are a few references on the internet to webkitselection a webkitspecific version of the selection selectorsee eg edit ppk has since removed webkitselection from that pagehowever i havenat been able to get the example in the page above or my own examples to work in any webkitbased browser iave triedsafari10122030405051chrome2614the unprefixed selection selector works in all of these browsers anyway so itas not really a problem but i was wondering where the references to the webkitspecific version of this selector had come fromhas anyone ever used it,['css'] +197736,total number of row resultset getrow method read the following codepublic class selecttable public static resultset rsetpublic static int total0public static resultset onload opetationsconnection conn int rownumstring sqlint rownumrownumint totalrec0try connconnectionodbcgetconnection statement stmt conncreatestatementresultsettype scroll insensitive resultsetconcur read only string sqlstmt sql rset stmtexecutequerysqlstmt total rsetgetrow catchexception e systemoutprintlnegetmessage systemoutprintlntotal number of recordstotalrec return rset the folowing code dost show actual totaltotal rsetgetrowmy jtable thisplay 4 record in jtable but total 0 when i evaluate through debug it showstotalint0 rather than totalint4and if i use rsetlast above from the code total rsetgetrowthen total shows accurate value 4 but rset return nothing then jtable is emptyupdate me,['java'] +197744,switch between two frames in tkinter i have built my first few scripts with a nice little gui on them as the tutorials have shown me but none of them address what to do for a more complex program if you have something with a start menu for your opening screen and upon user selection you move to a different section of the program and redraw the screen appropriately what is the elegant way of doing this does one just destroy the start menu frame and then create a new one filled with the widgets for another part and reverse this process when they press the back button,['python'] +197760,operator new initializes memory to zero there is such codeinclude iostreamint main unsigned int wsk2 new unsigned int5 stdcout wsk2 wsk2 wsk2 stdendl delete wsk2 wsk2 new unsigned int stdcout wsk2 wsk2 wsk2 stdendl return 0resultwsk2 0x928e008 5wsk2 0x928e008 0i have read that new does not initialize memory with zeroes but here it seems that it does how does it work,['c++'] +197780,why does msdn recommend including object sender in delegate declarations i was reading this page and i noticed how it said this is standard guidelinesthe net framework guidelines indicate that the delegate type used for an event should take two parameters an object source parameter indicating the source of the event and an e parameter that encapsulates any additional information about the eventi can understand how having an object sender could be useful in some circumstances but i could see the exact opposite in others for examplewhat if a class handling the event should not have any knowledge about who fired it coupling cohesion and all of thatin my case i already have a reference to the object as a member variable that is how i subscribe to the event there will only ever be one instance of it so there is no reason to cast the sender object rather than just using the member variablein my program the sender object should not be known at all to the clients it is hard to explain what i am doing but basically i have a class with an internal constructor within a library that is used by two other classes also within that library my client classes are subscribing to events from those two classes but the events are originally invoked from this internal class that clients should not have any knowledge ofit is confusing to clients of the event handler libraries should be simple to understand and in my case there is no reason to ever use the sender variable none then why include itthat being said why does microsoft indicate that event handlers should follow these guidelines is not it not always the best choiceedit thanks for the replies everyone i have decided to go with the majority and use eventhandlert for all my events in this library,['c#'] +197802,how do i create a packaged task with parameters following this excellent tutorial for futures promises and packaged tasks i got to the the point where i wanted to prepare my own taskinclude iostreaminclude futureusing namespace stdint ackermannint m int n might take a while ifm0 return n1 ifn0 return ackermannm11 return ackermannm1 ackermannm n1int main packaged taskintintint task1 ackermann 3 11 error auto f1 task1get future thread th1 movetask1 call cout ack311 f1get endl th1joinas far as i can decipher the gcc470 error message it expects the arguments differently but how i try to shorten the error messageerror no matching function for call to stdpackaged taskintint intpackaged taskbraceenclosed initializer listnote candidates are stdpackaged task res argtypes res argtypes note candidate expects 1 argument 3 provided note cannot convert ackermann type int int int to type stdallocator arg tis my variant how i provide the parameters for ackermann wrong or is it the wrong template parameter i do not give the parameters 311 to the creation of thread rightupdate other unsuccessful variantspackaged taskint task1 return ackermann311 thread th1 movetask1 packaged taskint task1 bindackermann311 thread th1 movetask1 packaged taskintintint task1 ackermann thread th1 movetask1 311 hmm is it me or is it the betagcc,['c++'] +197809,cron job not working in whenever gem i have an application that contains a bunch of tasks and every day i want to run a cron job that creates a daytask for each task in the database a task has many daytasks and these daytasks are what users will be checking off every day i am using the whenever gem but it does not seem to be running at all any ideasconfigschedulerbevery 1day at 1201am do runner taskgenerate tasks for day endtaskrb def generate tasks for day taskalleach do task taskday taskscreatetarget date datetoday end end result of running the whenever command1 0 binbash l c cd homegrantrails projectsgoaltwist scriptrails runner e production taskgenerate tasks for daynote i have been changing the times in configschedulerb every time i want to test run it,"['ruby-on-rails', 'ruby']" +197811,systemwindowsinteractivity could not load file or assembly systemwindows version2050 i am trying to reference systemwindowsinteractivity in order to support isexpanded behavior commandbut as soon as i add a reference to this assembly i get the error loading systemwindows 20 this appears to be a known bug and solution appears to be to just reference that assemblyi downloaded silverlight sdk and referenced assembly in question in my project however now i am getting lots of conflicts between systemwindows and windowsbasedll classes such as routedeventhandler exist in both must be a way to fix this since i see people being successful in using that interactivity dll with wpf 40,"['c#', '.net']" +197826,is 0 guaranteed to be 0 i wrote this function in c which is meant to iterate through a string to the next nonwhitespace characterchar iterate through whitespaceunsigned char i whilei i 32 return i1it seems to work quite well but i am wondering if it is safe to assume that the i will be evaluated to false in the situation that i 0 and it would not iterate beyond the end of a string it works well on my computer but i am wondering if it will behave the same when compiled on other machines,['c'] +197830,c char arrays use in cingetline i have the following codechar mytext256cingetlinemytext256why exactly do i have to pass a character array to cingetline and not a stringi have read that in general it is better to use strings than character arrays should i then convert a character array to a string after retrieving input with cingetline if that is possible,['c++'] +197854,how to prevent floating content in two divs from overlapping in a faq page i am trying to make i have a page with this structuresection idcontainer div idfaq primarydiv div idfaq sidebardivsectionfooter div iddirectory div idcol adiv div idcol bdiv div idcol cdiv divfooterhere is the relevant csscontainer width960px margin 0px auto positionrelativefaq primary width720px margin20px 40px 0 0 positionrelative floatleft thisplayinline faq sidebar left760px positionabsolutefooter width1px height250px margin90px auto 0px positionrelative backgroundimageurlimagesfooterbgpng color7d7d7ddirectory width960px margin0px auto paddingtop25px fontsize13pxdirectory ul li paddingbottom4pxdircola dircolb dircolc dircold dircole width174px height140px floatleftdircola width150pxdircole width143pxmy page content is found in the section container and the footer is directly below the faq sidebar is much shorter than faq primary and because the columns in the footer are all floating left they end up to the right of the faq primary below the faq sidebar heres a screenshot any advice so i can prevent the content in the footer and container from overlapping,"['css', 'html']" +197860,how do i flush a randomaccessfile java i am using randomaccessfile in javafile new randomaccessfilefilename rwfilewritebyteshow can i ensure that this data is flushed to the operating system there is no fileflush method note that i do not actually expect it to be physically written i am content with it being flushed to the operating system so that the data will survive a tomcat crash but not necessarily an unexpected server power lossi am using tomcat6 on linux,['java'] +197868,can css alter an input elements src attribute is it possible via css to remove or change the src reference in the markup belowthe easy thing to do would be to change the markup however this code is in the wild and i need to deal with it as it is so i am trying to remove the image and use a background image insteadinput typeimage srcwpcontentuploadsimagepng namesubmit clasubmit valuesubmit,['css'] +197883,python binding to imagemagick i am looking for a good python binding to imagemagick but there seem a lot of bindings already i am not sure that which of these is the right tool for my job can you guys recommend me onehere is the list of my requirements and preferences in order of importancemust be available on pypi to simplify our deploymentprefer ctypes over c api extension a we will go pypy soonpythonic api design and naming conventionsgood documentation especially api references,['python'] +197908,how to access resdrawablefolder on my application i have many pictures which i have grouped in folder under resdrawable but android dosent let me access them trough r is there a way to access those foldersthis is the code im using for imageview iv new imageviewconext ivsetimageresourcerdrawablesmiley6i marked the part which i cannot accessthx in advancesafari,['android'] +197928,renaming a temporary table into a physical one can i do something like thiscreate table tbl tmp col1 intinsert into tbl tmp select 3exec sp rename tbl tmptbl new,['sql'] +197929,what are those java threads starting with pool i have a problem with a tomcat server that is unable to shutdown gracefully i have taken a thread dump after i issued the shutdown command and it looks like thisthe thread which i believe is the suspect that does not allow the vm to shut down is the one named pool4thread1 the rest of them are either daemon threads or internal vm threads while trying to find out what this thread is for i noticed that there are other java programs out there that create threads with similar names for example jvisualvm creates such threadsso i am wondering if someone else knows what this thread is and how it can be created,['java'] +197933,java convert float to string and string to float how could i convert from float to string or string to floatin my case i need to make the assertion between 2 values string value that i have got from table and float value that i have calculatedstring valuefromtable 25float valuecalculated 250i tried from float to stringstring sselectivityrate stringvalueofvaluecalculated but the assertion fails,['java'] +197945,javalangillegalstateexception the specified child already has a parent you must call removeview on the childs parent first this is my codeframegamecontrollertestsetcontentviewframeworldgetscreenframeworldsetrunningtrueon the second line i am getting the following errorerrorandroidruntime15229 caused by javalangillegalstateexception the specified child already has a parent you must call removeview on the childs parent firstcan anyone help me solve it previously it was working just fine the problem starts when i take it in another activityi am using android 22,"['java', 'android']" +197962,javascript textarea undo redo i am making a small javascript editor for a chrome extension somewhat like the one on sothere is a toolbar for manipulation of the text in the textarea eg surround the selected text with some templatei was wondering if there is a easy way to achieve this currently when using the system undoredo it messes the text up i think the system is only keeping track of deltas between edits,['javascript'] +197968,set maven property from plugin i have read some questions here about how to set a property most of them talked about the version number for an application from a maven plugin it seems there is no easy way of doing this and the best solution i found is to have a filterproperties file which is updated from the plugin and used by the main pom file to filter the desired resourcesi tried another solution after i read this from the maven documentation maven filter pluginvariables can be included in your resources these variables denoted by the delimiters can come from the system properties your project properties from your filter resources and from the command linei found interesting that variabled can be read from system properties so i modified my plugin to set a system property like thissystemsetpropertycurrentversion appcurrentversionhowever filtered resources do not seem to read this value could anybody tell me whats wrong with this approachupdate i am running my plugin in the validate phasethanks a lot,['java'] +197976,what is an opaque pointer in c possible duplicatewhat is an opaque value may i know the usage and logic behind the opaque pointer concept in c,['c'] +198025,create db connection and maintain on multiple processes multiprocessing similar to another post i made this answers that post and creates a new questionrecap i need to update every record in a spatial database in which i have a data set of points that overlay data set of polygons for each point feature i want to assign a key to relate it to the polygon feature that it lies within so if my point new york city lies within polygon usa and for the usa polygon gid 1 i will assign gid fkey 1 for my point new york city okay so this has been achieved using multiprocessing i have noticed a 150 increase in speed using this so it does work but i think there is a bunch of unecessary overhead as one db connection is required for each recordso here is the codeimport multiprocessing time psycopg2class consumermultiprocessingprocess def init self task queue result queue multiprocessingprocess init self selftask queue task queue selfresult queue result queue def runself proc name selfname while true next task selftask queueget if next task is none print tasks complete selftask queuetask done break answer next task selftask queuetask done selfresult queueputanswer returnclass taskobject def init self a selfa a def call self pyconn psycopg2connectdbnamegeobase 1 host localhost pyconnset isolation level0 pycursor1 pyconncursor procquery update city set gid fkey gid from country where st withinselect the geom from city where city id s countrythe geom and city id s selfa selfa pycursor1executeprocquery print what is self print selfa return selfa def str self return arc def runself print inif name main tasks multiprocessingjoinablequeue results multiprocessingqueue num consumers multiprocessingcpu count 2 consumers consumertasks results for i in xrangenum consumers for w in consumers wstart pyconnx psycopg2connectdbnamegeobase 1 host localhost pyconnxset isolation level0 pycursorx pyconnxcursor pycursorxexecuteselect count from cities where gid fkey is null temp pycursorxfetchall num job temp0 num jobs num job0 pycursorxexecuteselect city id from city where gid fkey is null cityidlisttuple pycursorxfetchall cityidlistlist for x in cityidlisttuple cityidlistappendx0 for i in xrangenum jobs tasksputtaskcityidlisti 1 for i in xrangenum consumers tasksputnone while num jobs result resultsget print result num jobs 1it looks to be between 03 and 15 seconds per connection as i have measure it with time moduleis there a way to make a db connection per process and then just use the city id info as a variable that i can feed into a query for the cursor in this open this way i make say four processes each with a db connection and then drop me city id in somehow to process,['python'] +198026,how to get dictionary values as a generic list i just want get a list from dictionary values but it is not so simple as it appears here the code dictionarystring listmytype mydico getdictionarylistmytype items i try listmytype items new listmytypemydicovaluesbut it does not work,['c#'] +198048,injecting content into specific sections from a partial view aspnet mvc 3 with razor view engine i have following section defined on my layoutcshtmlrendersectionscripts falsei can easily use it from a view as follows section scripts stuff comes herewhat i am struggling is how to get some content injected inside this section from a partial viewlet us assume following is my view page section scripts script code comes here scriptdiv poo bar poodivdiv htmlpartial mypartialdivi need to inject some content inside scripts section from mypartial partial viewdo you have any idea how,['asp.net'] +198051,selenium export test cases as phpphpunit is missing in my selenium ide 120 i really in need of convertingexporting my test cases to php but phpphpunit formatter in selenium ide 120 is missing can you please tell me how can i get it its really urgent please,['php'] +198079,nskeyedunarchiver how to prevent a crash i guess this is very obvious but i have a question about loading data if have a file called librarydat which stores all kind of information about objects in the app it is set up all nicely in terms of the initwithcoder and encodewithcoder methods etc but i was just wondering what happens if the librarydat ever gets corrupted i corrupted it a bit myself and the app will then crash is there any way to prevent a crash can i test a file before loading it here is the bit which can potentially be very fatal voidloadlibrarydat nslogloadlibrarydat nsstring filepath self documentsdirectory stringbyappendingpathcomponentlibrarydat if the app crashes here there is no way for the user to get the app running except by deleting and reinstalling it selflibrarydat nskeyedunarchiver unarchiveobjectwithfilefilepathi had a look at nsinvalidunarchiveoperationexception but have no idea how i should implement this in my code i would be grateful for any examples thanks in advance,"['iphone', 'objective-c', 'ios']" +198087,c method name as template parameter how do i make the method name here some method a template parametertemplatetypename tvoid sv set helpert d bpnarray const v to svv dsome method,['c++'] +198103,how to represent a binary tree with tables html here is a brainteaser for the brave i have been at it for days and just cannot come with the solutioni wanted to come out with something like thisusing html css and php onlyi got near but not quite what i expected here is the code in php and here is the outputtable border0thead tr thcientoveintiochavosth thseseintaicuatravosth thtreintaidosavosth thdieciseisavosth thoctavosth thcuartosth thsemifinalesth thfinalth trtheadtbodyphp fori0i256i tr php forn0c2n8nc2 php iffalsei 0 rwspn c21 iter 0 else rwspn c iter cc21 class ic2parimpar winner ific0 td rowspanc classclaspanphp echo genrandomstringspantd php endif php endfor tr php endfor tbodytableif someone knows how to represent a binary tree or a dendrogram or comes up with a smarter code please let me know,['php'] +198134,determine if statically named javascript function exists to prevent errors i have a script on my website that calls a statically named function when calledchildloadthe childload function is not always defined though it is always called how can i prevent the script from calling this function if it does not exist,['javascript'] +198154,how to stop multiprocess pythonprogram cleanly after exception i have a python program that has several processes for now only 2 and threads 2 per process i would like to catch every exception and especially shut down my program cleanly on ctrlc but i cannot get it to work everytime an exception occurs the program stops but does not shut down correctly leaving me with an unusable commandlinewhat i have tried so far in pseudocode istry for process in processes processjoinexcept pass just to suppress errormessages will be removed laterfinally for process in processes processterminatebut as i already said with no luck also note that i get the exception error message for both processes so they are both halted i believemaybe i should also mention that most of the threads are blocked in listening on a pipeeditso i nearly got it working i needed to try every thread and make sure the threads are joined correctly there is just one flaw exception keyboardinterrupt in module threading from usrlib64python27threadingpyc ignored when shutting down this is raised in the mainthread of the mainprocess this thread is already finished meaning it has passed the last line of code,['python'] +198176,are tables created with create temporary table in memory or on thisk in mysql when you create a temporary table for example create temporary table is that table created and held in memory or on the thiski have read through the docs and googled it and have not come up with an answer,['mysql'] +198181,difference between soap webservice and restful webservice i am new to javai know that there are two types of web servicesoap webservicerestful webservicecan any one please tell me what is the basic difference between both of themand in which situation the soap webservice is created and in which situation restful webservice is createdthank you,['java'] +198189,spring transaction not starting transactions i am using spring 3 with hibernate 3 i am trying to configure spring declarative transaction but no matter what i try spring transaction is not getting started here is my configurationfile applicationcontexthibernatexmltxannotationdriven transactionmanagertxmanager bean idtxmanager classorgspringframeworkormhibernate3hibernatetransactionmanagerproperty namesessionfactory refsessionfactory beanbean idmdbdatasource classorgapachecommonsdbcpbasicdatasourcebeanbean idsessionfactory classorgspringframeworkormhibernate3annotationannotationsessionfactorybean property namedatasource refmdbdatasource property nameannotatedclassesbeani have a class servicelocatorimpl which implements servicelocator interfaceserviceservicelocatortransactionalpublic class servicelocatorimpl implements applicationcontextaware serializable servletcontextaware servicelocator public resultobject executeservice map objargs iftransactionsynchronizationmanagerisactualtransactionactive loggerdebugservicelocatorexecuteservice active transaction found else loggererrorno active transaction found it seems to me that all my configuration is correct but when executeservice method is called transactionsynchronizationmanagerisactualtransactionactive is always returning false please help me solving this problem let me know if any more information requiredupdate i have wired the servicelocator into one of the other classes as followsautowiredprivate servicelocator servicelocator servicelocator is interfacei am using spring 300 versionexecuteservice is one the method defined in the servicelocator interface i updated the code to throw exception instead of just logging an error following is the stack trace i do not see any proxy creation in this trace please help javalangruntimeexception no active transaction foundat comnihilentvenicecommonserviceservicelocatorimpllogtransactionstatusservicelocatorimpljava102at comnihilentvenicecommonserviceservicelocatorimplexecuteserviceservicelocatorimpljava47at comnihilentvenicewebcontrollercommoncontrollerhandlerequestcommoncontrollerjava184at sunreflectnativemethodaccessorimplinvoke0native methodat sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava39at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava25at javalangreflectmethodinvokemethodjava597at orgspringframeworkwebbindannotationsupporthandlermethodinvokerdoinvokemethodhandlermethodinvokerjava710at orgspringframeworkwebbindannotationsupporthandlermethodinvokerinvokehandlermethodhandlermethodinvokerjava167at orgspringframeworkwebservletmvcannotationannotationmethodhandleradapterinvokehandlermethodannotationmethodhandleradapterjava414at orgspringframeworkwebservletmvcannotationannotationmethodhandleradapterhandleannotationmethodhandleradapterjava402at orgspringframeworkwebservletthispatcherservletdothispatchthispatcherservletjava771at orgspringframeworkwebservletthispatcherservletdoservicethispatcherservletjava716at orgspringframeworkwebservletframeworkservletprocessrequestframeworkservletjava647at orgspringframeworkwebservletframeworkservletdogetframeworkservletjava552at javaxservlethttphttpservletservicehttpservletjava617at javaxservlethttphttpservletservicehttpservletjava717at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava290at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava206at orgtuckeywebfiltersurlrewriterulechainhandlerewriterulechainjava176at orgtuckeywebfiltersurlrewriterulechaindorulesrulechainjava145at orgtuckeywebfiltersurlrewriteurlrewriterprocessrequesturlrewriterjava92at orgtuckeywebfiltersurlrewriteurlrewritefilterdofilterurlrewritefilterjava381at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava235at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava206at orgapachecatalinacoreapplicationthispatcherinvokeapplicationthispatcherjava646at orgapachecatalinacoreapplicationthispatcherprocessrequestapplicationthispatcherjava436at orgapachecatalinacoreapplicationthispatcherdoforwardapplicationthispatcherjava374at orgapachecatalinacoreapplicationthispatcherforwardapplicationthispatcherjava302at orgapachejasperruntimepagecontextimpldoforwardpagecontextimpljava709at orgapachejasperruntimepagecontextimplforwardpagecontextimpljava680at orgapachejspindex jsp jspserviceindex jspjava57at orgapachejasperruntimehttpjspbaseservicehttpjspbasejava70at javaxservlethttphttpservletservicehttpservletjava717at orgapachejasperservletjspservletwrapperservicejspservletwrapperjava386at orgapachejasperservletjspservletservicejspfilejspservletjava313at orgapachejasperservletjspservletservicejspservletjava260at javaxservlethttphttpservletservicehttpservletjava717at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava290at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava206at orgtuckeywebfiltersurlrewriterulechainhandlerewriterulechainjava176at orgtuckeywebfiltersurlrewriterulechaindorulesrulechainjava145at orgtuckeywebfiltersurlrewriteurlrewriterprocessrequesturlrewriterjava92at orgtuckeywebfiltersurlrewriteurlrewritefilterdofilterurlrewritefilterjava381at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava235at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava206at comnihilentvenicewebfilterdyanamicresponseheaderfilterdofilterdyanamicresponseheaderfilterjava33at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava235at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava206at comopensymphonymodulesitemeshfilterpagefilterparsepagepagefilterjava118at comopensymphonymodulesitemeshfilterpagefilterdofilterpagefilterjava52at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava235at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava206at orgspringframeworksecuritywebfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava343at orgspringframeworksecuritywebaccessinterceptfiltersecurityinterceptorinvokefiltersecurityinterceptorjava109at orgspringframeworksecuritywebaccessinterceptfiltersecurityinterceptordofilterfiltersecurityinterceptorjava83at orgspringframeworksecuritywebfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava355at orgspringframeworksecuritywebaccessexceptiontranslationfilterdofilterexceptiontranslationfilterjava97at orgspringframeworksecuritywebfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava355at orgspringframeworksecuritywebsessionsessionmanagementfilterdofiltersessionmanagementfilterjava100at orgspringframeworksecuritywebfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava355at orgspringframeworksecuritywebauthenticationanonymousauthenticationfilterdofilteranonymousauthenticationfilterjava78at orgspringframeworksecuritywebfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava355at orgspringframeworksecuritywebservletapisecuritycontextholderawarerequestfilterdofiltersecuritycontextholderawarerequestfilterjava54at orgspringframeworksecuritywebfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava355at orgspringframeworksecuritywebsavedrequestrequestcacheawarefilterdofilterrequestcacheawarefilterjava35at orgspringframeworksecuritywebfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava355at orgspringframeworksecuritywebauthenticationabstractauthenticationprocessingfilterdofilterabstractauthenticationprocessingfilterjava188at orgspringframeworksecuritywebfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava355at orgspringframeworksecuritywebauthenticationabstractauthenticationprocessingfilterdofilterabstractauthenticationprocessingfilterjava188at orgspringframeworksecuritywebfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava355at orgspringframeworksecuritywebcontextsecuritycontextpersistencefilterdofiltersecuritycontextpersistencefilterjava79at orgspringframeworksecuritywebfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava355at orgspringframeworksecuritywebfilterchainproxydofilterfilterchainproxyjava149at orgspringframeworkwebfilterdelegatingfilterproxyinvokedelegatedelegatingfilterproxyjava237at orgspringframeworkwebfilterdelegatingfilterproxydofilterdelegatingfilterproxyjava167at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava235at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava206at comnihilentvenicewebfilterrequestfilterdofilterrequestfilterjava44at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava235at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava206at orgspringframeworkwebfiltercharacterencodingfilterdofilterinternalcharacterencodingfilterjava88at orgspringframeworkwebfilteronceperrequestfilterdofilteronceperrequestfilterjava76at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava235at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava206at orgapachecatalinacorestandardwrappervalveinvokestandardwrappervalvejava233at orgapachecatalinacorestandardcontextvalveinvokestandardcontextvalvejava191at orgapachecatalinacorestandardhostvalveinvokestandardhostvalvejava127at orgapachecatalinavalveserrorreportvalveinvokeerrorreportvalvejava102at orgapachecatalinacorestandardenginevalveinvokestandardenginevalvejava109at orgapachecatalinaconnectorcoyoteadapterservicecoyoteadapterjava298at orgapachecoyotehttp11http11processorprocesshttp11processorjava859at orgapachecoyotehttp11http11protocolhttp11connectionhandlerprocesshttp11protocoljava588at orgapachetomcatutilnetjioendpointworkerrunjioendpointjava489at javalangthreadrunthreadjava619update solvedi got the issue fixed before giving the answer as how it was fixed i need to provide some more information i am using spring mvc in my project the control thispatchservlet is configured in the webxml this front controller has a configuration xml file abcservletxml abc being the servlet name in webxml i have other spring configuration files too which are defined as contextparam in webxml one of the file is applicationcontexthibernatexml filei defined the txmanager and txannotationdriven in the applicationcontexthibernatexml file today i was wondering whether autowired and transactional work with together so i google the information and found this threadthe thread talk about similar problem and this solves the problemi implemented one of the suggestion and added txannotationdriven to my servlet us application context xml and it fixes the problemthinking that i also moved my txannotationdriven into abcservletxml file and it worked my logs are now shoulding the required messagesvenice debug http80801 27 sep 2011 142406312 servicelocatorimpllogtransactionstatus100 servicelocatorexecuteservice active transaction foundthanks to everyone for helping may be this information will be helpful to someone i would still like to hear about the explanation as why it was not working earlier,['java'] +198192,use ruby array for a javascript array in erb escaping quotes i have found numerous things online for this but they dont work for me am i missing something in my controller i havet abcin the erb file that is callback the t renders like soquotaquot quotbquot quotcquot i have done hacks to replace the to proper symbols i have read that to json should work but it doesnt the following does not work abcto json the results are the same,['ruby'] +198209,simple javascripthtml slideshow new to javascript but after some research it loks like this would be the best method in implementing my desired output i am trying to produce a slideshow of images 5 preselected images that automatically change between 5 second intervals can anyone point towards a tutorial or guide me along in this process any help is very much appreciated,"['javascript', 'html']" +198239,c linq to xml get parents when a child satisfy condition i need some help i have this xml documentxml version10 encodingutf8myitems parent upca01 sku archivopantalon1jpg child upc101 sku archivoimagejpg grandchild archivoimagejpg child child upc102 sku archivoimagejpg grandchild archivoimagejpg child parent parent upca02 sku archivoimagejpg child upc101 sku archivoimagejpg grandchild archivoimagejpg child child upc102 sku archivoimagejpg grandchild archivoimagejpg child parent parent upc200 sku archivoimagejpg child upc201 sku archivoimagejpg grandchild archivoimagejpg child child upc202 sku archivoimagejpg grandchild archivoimagejpg child parentmyitemsthen i am trying to select all the parents where a child fullfil a condition example all the parents wich contains a child where child attribute upc is equal to 101i was studying this article select nodes based on properties of descendant nodesbut i just cant get what i wantthanks and have a nice day,['c#'] +198251,clear explanation of the theta join in relational algebra i am looking for a clear basic explanation of the concept of theta join in relational algebra and perhaps an example using sql perhaps to illustrate its usage if i understand it correctly the theta join is a natural join with a condition added in so whereas the natural join enforces equality between attributes of the same name and removes the duplicate the theta join does the same thing but adds in a condition do i have this right any clear explanation in simple terms for a nonmathmetician would be greatly appreciated also sorry to just throw this in at the end but its sort of related could someone explain the importance or idea of cartesian product i think i am missing something with regard to the basic concept because to me it just seems like a restating of a basic fact ie that a set of 13 x a set of 4 52,['sql'] +198281,importing resources from osgi bundle with the import mechanism in osgi it is straightforward to import packages from another bundle however i have been unsuccessful in importing resources that exist in the root of the bundleis it at all possible to import resources that are not package scoped in to another bundlewhat i would like to achieve is thisbundle a has a file resource in the root bundle b imports bundle as packages and resourcesthrough bundle bs classloader i would like to be able to load the resource in bundle a as if it existed in bundle b,['java'] +198333,why int mainanything you type doesnt produce any error here i have written my name in main argument declaration but still this program works and did not give any warning include stdiohint mainmr32 printfwhy this works return 0whenever i write anything in place of mr32 the code still works i really do not know why this is happening as per c programming standard this is wrong right edit i have tried wall but it does not give any warningi think here it should be error because i am not doing as standard c function definition declaration in c every function definition must follow this format returntype function name arg type arg1 arg type argn this should also appy to main right okay wextra shows warning that mr32 is by default intthen why is the default type of any argument in main an int,['c'] +198339,testing battery usage i want to test how my application effects the battery of a phonetablet are there any testing tools which will allow me to do sofor example i want to test which modules of my application are consuming the most amount of battery etc,['android'] +198356,findbugs rv absolute value of random int warning i am trying to do a code review for our project using findbugswe have a method to generate unique id randomly public static string generateuuidint base return stringvalueofgetcurrenttimeinnanoslongbase stringvalueofmathabsrandomnextint and findbugs indicates rv absolute value of random int warning rv bad attempt to compute absolute value of signed 32bit random integer i guess the problem is in stringvalueofmathabsrandomnextintso if you have an explanation for why is this and how to fix it thanks,['java'] +198362,benefit from generated getters and setters in play framework the play framework generates getters and setters for each public field of a model class at runtimepublic class product public string name public integer pricewill be transformed topublic class product public string name public integer price public string getname return name public void setnamestring name thisname name public integer getprice return price public void setpriceinteger price thisprice price the manual explains furtherthen when you want to access a property you can just writeproductname my productproductprice 58which is translated at load time toproductsetnamemy productproductsetprice58 and warnsyou canat directly use getter and setter methods to access properties if you rely on automatic generation these methods are generated at runtime so if you reference them in code you write the compiler wonat find the methods and will generate an errorsince i cannot use these getters and setters from outside of the play project i see no benefit in generating them what is the benefit compared to public fields refactorings encapsulate a field and change the callers of all modern ides taken into account,['java'] +198389,how to perform ios app validation from the command line is it possible to perform the local validation for ios applications which can be see in the organizer under archives function via the command lineupdate just to clarify the goal here is to eventually make this validation a part of the continuous integration process for my ios applications,"['iphone', 'ios']" +198398,xcode 4 external build project and debugging i have got a makefile based project set up that builds my code on multiple platforms on my mac i want to use xcode for debugging though i have set up an xcode as an external build project i can run the application from within xcode the output is shown in xcode and if the app crashes it drops in to the debugger but when running the debugger cannot locate the source files so i just see assembly output how can i tell xcode where to locate the source i also cannot set breakpoints but i think that this is all the same problem,['c++'] +198433,how to force layoutsubviews of uiview i have a custom uiview which has a dedicated manually set frame for portrait and landscape orientation because autoresizingmasks just do not work in my case i set this frame in voidviewwillappearboolanimatedand it works as expectedmy problem is now that my uiview furthermore has subviews that also have a dedicated position for portraitlandscape i position these subviews in voidlayoutsubviewsif i now leave my viewcontroller in eg portrait orientation rotate to landscape on another viewcontroller and then come back to this viewcontroller i see that my view got resized correctly but the subviews of my view which get positioned in layoutsubviews are not repositioned yet but are resized in an animated fashion after the view already appearedi do nothing in viewdidappear and i already tried calling voidlayoutifneededas well as voidsetneedslayoutin viewwillappear but it does not seem to change anythingany ideas what i am doing wrongthanks,"['ios', 'iphone']" +198450,pyramid and ini configuration each pyramid application has an associated ini file that contains its settings for example a default might look likeappmainuse eggmyprojectpyramidreload templates truepyramiddebug authorization falsepyramiddebug notfound falsepyramiddebug routematch falsei am wondering if it is possible to add your own configuration values in there and read them at runtime mostly from a view callable for instance i might want to haveappmainblogtitle custom blog nameblogcomments enabled trueor is it better to have a separate ini file and parse it during startup,['python'] +198465,jquery thisable scroll when mouse over an absolute div i am trying to thisable the window mouse scroll functionality when the mouse is hovering over the div so that only div scrolling is enabled and when mouse moves away from the div scrolling to the window is applied again the div is positioned absolutelyi have seen this post use jquery to thisable mouse scroll wheel function when the mouse cursor is inside a div but it does not seem to provide any answer hence my questioni am assuming it would be something like this if only these methods existedcontainerhoverfunction windowscrollthisable thisscrollenable function windowscrollenable,['jquery'] +198485,netdbh not linking properly i am trying to compile this program as referenced in beejs guide to network programming on page 19include stdiohinclude netdbhinclude systypeshinclude syssockethint main int status struct addrinfo hints struct addrinfo servinfo will point to the results memsethints 0 sizeof hints make sure the struct is empty hintsai family af unspec do not care ipv4 or ipv6 hintsai socktype sock stream hintsai flags ai passive if status getaddrinfonull 3490 hints servinfo 0 fprintfstderr getaddrinfo error sn gai strerrorstatus exit1 servinfo now points to a linked list of 1 or more struct addrinfos do everything until you do not need servinfo anymore freeaddrinfoservinfo free the linkedlist return 0 among other errors i seemainc818 error storage size of ahintsa isnat knownmainc1319 error aai passivea undeclared first use in this functionmainc163 warning implicit declaration of function agai strerrorait appears that gcc is not linking with netdbh eclipse the ide that i am using to build this has no trouble finding the file heres the compiler commandgcc o0 g3 pedantic wall c fmessagelength0 ansi mmd mp mfmaind mtmaind omaino maincadding lnetdb does not resolve the issue also find usrinclude name netdbhusrincludebitsnetdbhusrincludegssrpcnetdbhusrincludenetdbhusrincluderpcnetdbhi think these files came preinstalled on my opensuse host why does not gcc detect netdbh or am i drawing the wrong conclusion,['c'] +198499,how to change progressbar style in listfragment under compatibility library the progress bar is large one by default in listfragmentprogressbar progress new progressbarcontext null androidrattrprogressbarstylelargeis the only way to change it using reflection,['android'] +198538,can a foreign key be null andor duplicate please clarify two things for mecan a foreign key be nullcan a foreign key be duplicateplease in support of your answer provide some authentic references or links as fair as i know null should not be used in foreign keys but in some application of mine i am able to input null in both oracle and sql server and i do not know why,['sql'] +198548,animation when changing textview i currently use a major workaround and have two activities switching each time i change the text on a textview i am using this codeweeklytextthisoverridependingtransition ranimslide in left ranimslide out right is it possible to do this in one activity it is kind of annoying having two activities with the exact same content just so that i can use animations thanksplease ask if you do not understand my question,['android'] +198555,php connection reset on large file upload regardless correct setting i am having a very common problem which it seems that all the available solutions found are not workingwe have a lamp server which is receiving high amount of traffic using this server we perform a regular file submission upload on small file uploads it works perfectly on files of around 45mb this submission upload failed intermittently sometimes it works but many times it failed we have the following configuration on our phpmax input time 600max execution time 600max upload size 10mpost max size 10mapache settingtimeout 600keepalive timeout 15keepalive onper child 10max conn 100thus i wonder if anyone can help me with this we have found the issues and solutions online but none of them work in our casethank you so much any input feedback is much appreciated,['php'] +198564,c member function pointers in class and subclass i have one base class which holds a map for function pointers like thistypedef void baseclassevent tclass baseclass protected stdmapstdstring event t events public example event void onfoo can be added easily to the map handling this works prefect but now i want to make baseclass an abstract base class to derive from like this class specificclass public baseclass public void onbar this is gonna be difficult although i can access the map from specificclass i am not able to add onbar because the event t type is only defined for the baseclass is there any possibility maybe with templates which does not lead to define the event t for each class i will useit is not neccessary to use templates any goodsuitable approach would be nicemore background informationthis whole thing is for a text based rpg my base class could be called location and the specifc one any location eg civiccenter each location object subscribes to my eventsystem which notifies all neccessary objects when i fire an event therefore i want to store in a map some pointers to private functions holding the actions with their name like onsetonfire xd as the key,['c++'] +198591,prevent temporary from extending its lifetime this may be impossible but i was wondering if it was possible to keep a temporary from ever lasting past its original expression i have a chain of objects which point to parent objects and a member function which will create a child object a simplified example is hereclass person string name person mommypublic personconst string nam person m 0 namenam mommym person babyconst string nam return personnam this void talk const if mommy mommytalk cout name endl int main personannbabysusanbabywendytalk fine const person babygirl personjuliebabylaura not fine babygirltalk segfault return 0the way i want to use person is to pass it to a function and something like thisvoid useconst person p ptalkusepersonannababylisais finethis will work fine as long as none of the temporaries survive past the original expression but if i bind one of the final temporaries to a const reference its parents do not survive and i get a segfault i can hide persons copy constructor and assignment operator but is there any way i can prevent this kind of error from happening i would like to avoid dynamic allocation if possible,['c++'] +198606,private and public variables to a backbone view in a backbone view where would you put your private variables and your publicright now i have something like thismyview backboneviewextend initialize functionoptions thismypublic i am public i tried adding a var myprivate before the initialize method but it threw an error where would private variables that are only used within the view go,['javascript'] +198628,validation in html5 invalid classe after submit i am building a form and i want to use the invalid selector to give the required input fields a red border if the user presses submit without filling them but using this makes them appear highlighted right when the page loads it seems unfriendly to give this kind of warning to the user before even giving him the chance to fill them at least onceis there a way that these fields appear highlighted only after trying to submit the form said in another way is there a way to run the validation only after clicking submit or at least losing focus on the required input fields,['css'] +198663,boostpython select between overloaded methods assume exist some class foo with two overloaded methodsclass foo void m1a a void m1b bi need expose one of these methods over boostpythonboostpythonclass foofoo defm1 foom1how should i specify that signature of m1aa should be used over m1bb,"['c++', 'python']" +198681,heap memory problems there is a wcf self hosted service that must work 99 of time sometimes we got some memory troubles like thisbut service is working as usual after that issues how can we manage this any tips and points to make robust services that will survive in different except situations are very very welcome,"['c#', '.net']" +198688,ruby on rails flash messages alert error notice and success in several of my controllers i have redirectsflash messagesredirect to products url notice message here redirect to states url error oops etc in my sessions controller however upon successful authentication i have flashsuccess welcome redirect to useri would like to be able in my other controllers to do something like success yaythis is mostly for cosmeticconsistency purposes but are notice alert and error the only flashtypes available can i add additional types am i making sensethanks,['ruby-on-rails'] +198707,why margintop of the top div would apply to here i posted a demo as you can see body gets margintop10px from the top div and therefor htmls black background leaks out does it mean that i cannot give the top div a positive margintopxml version10 encodingutf8doctype html public w3cdtd xhtml 11en html xmlns head style htmlcolor0backgroundfbodydivdldtddulollih1h2h3h4h5h6precodeformfieldsetlegendinputbuttontextareaselectpblockquotethtdmargin0padding0tablebordercollapsecollapseborderspacing0fieldsetimgborder0addressbuttoncaptioncitecodedfneminputoptgroupoptionselectstrongtextareathvarfontinheritdelinstextdecorationnoneliliststylenonecaptionthtextalignlefth1h2h3h4h5h6fontsize100fontweightnormalqbeforeqaftercontentabbracronymborder0fontvariantnormalsupverticalalignbaselinesubverticalalignbaselinelegendcolor0 htmlbackgroundblack bodybackgroundwhite style head body div stylemargintop10pxbackgroundredheight100pxhere the top div beginsdiv div styleheight800pxa long long divdiv bodyhtml,"['html', 'css']" +198746,is it considered bad practice to use internalsvisibleto for unit test code sample code in frameworks assemblyinfocsassembly systemruntimecompilerservicesinternalsvisibleto testcompanydepartmentcoreis this a bad practice,"['c#', '.net']" +198747,how to use variables in python regular expression i am in need to use a variable in python regular expressionfor line in refindall330842 datai am using above code to match a line with 330842 some times this values changes so i need to use a variable likefor line in refindallvar name dataplease help me how to use a variable in python regular expressionthanks in advance,['python'] +198771,cs0030unable to generate a temporary class i have a web service when i try to generate the object of it i am getting below errorunable to generate a temporary class result1error cs0030 cannot convert type shortsellshortsellrqorigindestinationinformationflightsegment to shortsellshortsellrqorigindestinationinformationflightsegmenterror cs0030 cannot convert type shortsellshortsellrsorigindestinationoptionflightsegment to shortsellshortsellrsorigindestinationoptionflightsegmenterror cs0030 cannot convert type shortsellshortsellrqorigindestinationinformationflightsegment to shortsellshortsellrqorigindestinationinformationflightsegmenterror cs0029 cannot implicitly convert type shortsellshortsellrqorigindestinationinformationflightsegment to shortsellshortsellrqorigindestinationinformationflightsegmenterror cs0029 cannot implicitly convert type shortsellshortsellrsorigindestinationoptionflightsegment to shortsellshortsellrsorigindestinationoptionflightsegmenterror cs0029 cannot implicitly convert type shortsellshortsellrsorigindestinationoptionflightsegment to shortsellshortsellrsorigindestinationoptionflightsegmenti tried changing the temp folder properties to writable but i am still getting this error why am i getting this error and how can i fix it,['c#'] +198777,how to send post form with java i would like to send a post form with java on a website i came up with this but i dont what to do next or if this is even the right wayurl url new urlurlconnection connurlopenconnectionconnsetdooutputtrueoutputstreamwriter wr new outputstreamwriterconngetoutputstreamwrwritedatathe post form looks like thisform actionprikaz4php methodpost select nameigralec option valuekobe bryantkobe bryantoption option valuedwayne wadedwayne wadeoption input typesubmit form,"['java', 'html']" +198835,unable to update the entityset because it has a definingquery and no element exist i am using entity framework 1 with net 35i am doing something simple like thisvar roomdetails contextroomstolistforeach var room in rooms roomlastupdated datetimenowi am getting this error when i try to do contextsavechangesi get the errorunable to update the entityset because it has a definingquery and no updatefunction element exists in the modificationfunctionmapping element to support the current operationi am doing lots of updates on the context and not having any issues it is only when i try to update this particular entityall my searching shows up the same thing that there is no primary key declared on the entity that i am trying to update but alas i do have a primary key declared,"['c#', 'asp.net', '.net']" +198840,resharper 6 create auto property by default when i write code and need new property i simply write propery name as it would exist already and choose action from menuproblem is that it generates code like this protected int somenewproperty get throw new systemnotimplementedexception set throw new systemnotimplementedexception so i need to go there and manually adjust that actually i prefer to choose create field from menu and change it to auto property anyway i thought may be there is a way to change default behavior of create property that it would create auto property instantlyupdate in resharper 8 auto properties are available and may be set by default,['c#'] +198871,exception stack trace difference between debug and release mode the code below generates different exception stack trace in both debug and release modestatic class et public static void e1 throw new exceptione1 public static void e2 try e1 catch exception e throw public static void entry try e2 catch exception e consolewritelineestacktrace result in debug modeat ete1 in dmystudiocsharpcsharp40mycsharpexceptionhandlingcsline 47at ete2 in dmystudiocsharpcsharp40mycsharpexceptionhandlingcsline 58at etentry in dmystudiocsharpcsharp40mycsharpexceptionhandlingcsline 68result in release modeat ete2 in dmystudiocsharpcsharp40mycsharpexceptionhandlingcsline 55at etentry in dmystudiocsharpcsharp40mycsharpexceptionhandlingcsline 68please note that the first line from the result in release mode is missing how to return the offending line in release mode,['c#'] +198880,webview add local css file to an html page in android i am using webview to thisplay a part of a webpage wich i fetched from the internet using httpclient from apache to only have the part i want from the html i use jsoup string htmlstring entityutilstostringentity4 full html as a string document htmldoc jsoupparsehtmlstring as a jsoup documentelements tables htmldocgetelementsbytagtable important partnow i can just loadtablestostring in the webview and it thisplays now i want to link a css file wich i store inside my assets folder with this page i know i can have something like link hrefstylesfilecss typetextcss relstylesheet in my html but how do i link it so it uses the one i have stored locallyediti have now changed to thisstringbuilder sb new stringbuilder sbappendhtmlheadlink hreffileandroid assethtmlstyles defaultcss typetextcss relstylesheetheadbody sbappendtablestostring sbappendbodyhtml return sbtostringsomehow i do not get the styles applied to the page is it the location path i used that is wrong please help me,"['android', 'html', 'css']" +198929,in javascript what is the advantage of function over function possible duplicatewhat does the exclamation mark do before the function i have long used the following for selfexecuting anonymous functions in javascriptfunction magic happens lately i have started seeing more instances of the following pattern eg in bootstrapfunction presumably the same magic happens anyone know what the advantage is of the second pattern or is it just a stylistic preference,['javascript'] +198932,strstr faster than algorithms i have a file that is 21056 bytesi have written a program in c that reads the entire file into a buffer and then uses multiple search algorithms to search the file for a token that is 82 charsi have used all the implementations of the algorithms from the aexact string matching algorithmsa page i have used kmp bm tbm and horspool and then i used strstr and benchmarked each onewhat i am wondering is each time the strstr outperforms all the other algorithms the only one that is faster sometimes is bmshould not strstr be the slowestheres my benchmark code with an example of benchmarking bmdouble get time large integer t f queryperformancecountert queryperformancefrequencyf return doubletquadpartdoublefquadpartbefore get timebmtoken strlentoken buffer lenafter get timeprintftime fnn after beforecould someone explain to me why strstr is outperforming the other search algorithms i will post more code on request if needed,['c'] +198936,basic userinput string validation i have been writing a check in a name property of my person abstract class the problem that i have is that i am trying to implement a piece of code that will not allow the user to leave the field empty or to exceed the name limit with 35characters or input a digit but i am stuck with it if any one can help or suggest me public string name get return name set while true if value valuelength 35 consolewriteplease enter correct name value consolereadline continue foreach char item in value if charisdigititem consolewritedigits are notallowedn consolewriteplease enter correct name value consolereadline break break name value,['c#'] +198940,warning unchecked unchecked call to putkv as a member of the raw type javautilhashtable localparamsputname values i have got 2 warning the first is helpdeskgestion2srcjavaglpifilterloginfilterjava289 warning unchecked unchecked call to putkv as a member of the raw type javautilhashtable localparamsputkey value the second is helpdeskgestion2srcjavaglpifilterloginfilterjava292 warning unchecked unchecked call to putkv as a member of the raw type javautilhashtable localparamsputname values the code ho generate this warnings is public void setparameterstring name string values if debug systemoutprintlnloginfiltersetparameter name values localparams localparams if localparams null localparams new hashtable copy the parameters from the underlying request map wrappedparams getrequestgetparametermap set keyset wrappedparamskeyset for iterator it keysetiterator ithasnext object key itnext object value wrappedparamsgetkey localparamsputkey value localparamsputname values,['java'] +198942,cannot create external files dir in android write external storage is present i tried using both my applicationcontext and my calling services context to access the external directory unfortunately it keeps returning null and logcat reports it was unable to create the external directory i am sure i have the write storage permission present but it still would not work my device is running api 10 233 vanilla android any ideasheres my manifestxml version10 encodingutf8manifest xmlnsandroidpackagedroidsignboard androidversioncode1androidversionname10usessdk androidminsdkversion10 androidtargetsdkversion10 usespermission androidnameandroidpermissionaccess network state usespermission androidnameandroidpermissionaccess wifi state usespermission androidnameandroidpermissionchange wifi state usespermission androidnameandroidpermissioninternet usespermission androidnameandroidpermissionwrite external storage application androidicondrawableicon androidlabelstringapp name androidnamesignboardapp receiver androidnameapplicationstarter intentfilter action androidnameandroidintentactionboot completedaction action androidnamedroidsignboardlauncher startaction intentfilter receiver activity androidlabelstringapp name androidscreenorientationlandscape androidlaunchmodesingletop androidnameviewsignboard intentfilter action androidnameandroidintentactionmainaction category androidnameandroidintentcategorylaunchercategory intentfilter activity service androidnamecontrollermastercontrollerservice intentfilter action androidnamedroidsignboardlaunch service from activityaction intentfilter serviceapplicationmanifestand heres where the code messes upprivate boolean canwriteex string state environmentgetexternalstoragestate if stateequals environmentmedia mounted logi tag can write to external directory contextgetexternalfilesdir nullgetabsolutepath return true else logi tag cannot write to external directory contextgetexternalfilesdir nullgetabsolutepath return false the code is a method of a runnable that is called by a service the constructor of the runnable takes a context as its parameter that is the context used by the code the code throws an exception at the log call that succeeds implying that external storage is present and availableupdates of attempted fixesa clean install does not workreverting down to api 9 does not work though it worked earlier,['android'] +198951,converting numpy array to opencv array i am trying to convert a 2d numpy array representing a blackandwhite image into a 3channel opencv array ie an rgb imagebased on code samples and the docs i am attempting to do this via python likeimport numpy as np cvvis npzeros384 836 npuint32hw visshapevis2 cvcreatemath w cvcv 32fc3cvcvtcolorvis vis2 cvcv gray2bgrhowever the call to cvtcolor is throwing the following cpplevel exceptionopencv error image step is wrong in cvsetdata file buildbuilddopencv210srccxcorecxarraycpp line 902terminate called after throwing an instance of cvexception what buildbuilddopencv210srccxcorecxarraycpp902 error 13 in function cvsetdataabortedwhat am i doing wrong,['python'] +198976,tool to convert an xpath to a jquery selector firebug is able to thisplay the xpath for any dom element in the html view i was wondering if there is a way to convert the xpath to a jquery selector i prefer not to do this manuallythis will greatly save me time to find the correct selector for elements which do not have an id are way deep in the dom hierarchy for example the fifth td in the 20th trafaik xpath support in jquery is dropped so i cannot use the xpath straight in jquery,['jquery'] +198984,oswalk multiple directories at once possible duplicatehow to join two generators in python is there a way in python to use oswalk to traverse multiple directories at oncemy paths path1 pathtodirectoryonepath2 pathtodirectorytwofor path dirs files in oswalkpath1 path2 my pathsappenddirsthe above example does not work as oswalk only accepts one directory but i was hoping for a more elegant solution rather than calling oswalk twice plus then i can sort it all at once thanks,['python'] +198985,how does mongoid criteria work i am trying to do something straight forward such asuserallcriteria project id 2this returns an instance of mongoidcriteriawhat can i do with this criteria what if i just want the array of documents returned for further evaluation,['ruby-on-rails'] +199009,sharing aspnet cookies across subdomains i have two sites both on the same domain but with different subdomainssite1mydomaincomsite2mydomaincomonce i am authenticated on each i look at the cookies included in subsequent request and they are identical for each site however if i log into the first site and then navigate to the other i expect my cookie from site 1 to be sent with the request to site2 but this is not the case here are the properties of my cookieslogging into site1 this cookie then existsname mysite domain has keys false httponly false path value 1c41854066b03d8cc5679ea92de1ef427dac65d1ba0e672899e27c57245c1f0b7e93ab01b5563363ab4815a8f4bde9d293fd261e03f8e60b8497abba964d8d315cce1c8dd220c7176e21dc361935cf6 expires 1101 120 am logging into site2 these cookies then exists name mysite domain has keys false httponly false path value c8c69f87f993166c4d044d33f21ed96463d5e4eb41e1d986bf508da0cbd5c2ca7d782f59f3bc96871108997e899ff7401c0d8615705bdb353b56c7e164d2302ee6731f41705016105ad99f4e0578ecd2 expires 1101 120 am i have set the domain on each does not show up in a request cookie as it is only needed on the clienti have made sure my forms setting for each are identicali have made sure my machine key settings are the same in both web configsi am at a loss on why this is not working what is it that a cookie contains that the client will send it for one subdomain and not the other when they are both using the same auth cookies so far as i can tellplease comment if there is more info youd like to see i have been struggling with this for two days now according to this article this should be workingupdate code addedhere is my config file setting for my authentication this is used in both sitesauthentication modeforms forms loginurlaccountlogon defaulturlhomeindex namemysite protectionall path domainmydomaincom enablecrossappredirectstrue timeout2880 and here is my code to create the cookie in site1 add a cookie that the site2 will use for authenticationvar cookie formsauthenticationgetauthcookieusername truecookiename mysitecookiehttponly falsecookieexpires datetimenowaddhours24cookiedomain mydomaincom httpcontextresponsecookiesaddcookiehttpcontextresponseredirectsite2urltrueupdate 2i noticed something strange while testing when i add a cookie to the response for site1 it gets added to this directory cusersjreddyappdataroamingmicrosoftwindowscookieswhen i add a cookie to the response for site it gets added to this directory cusersjreddyappdataroamingmicrosoftwindowscookieslowthat could be my problem could it be that one of my sites is included in the local intranet zoneupdate 3 problem found solution unknownit seems that my problem has to do with my second site being part of the local intranet zone if i go to site1 using firefox it works but i have to enter my windows credentials if i go thru ie my credentials are picked up automatically but the cookies cannot be read by site2 i may ask this in another question,['asp.net'] +199029,where to put core resources in symfony2 i started to build a website with symfony2 and i had a little bit of a quandary about resourcesthe symfony2 book says that every resource file have to be in a bundle but what about the most essential images js and css files that i use in the basehtmltwig file on every pageshould i make a corebundle or something similiar just for these files or should i put these in the appresources folder or directly in the web folder maybeif i can use the appresources folder for these how can i reference these files from the templatemaking a bundle just for this seems a little unnecesary and the asset urls for these files are ugly too eg bundlesprojectcoreimageslogojpg in my opinionwhats the best practice here,['php'] +199040,find all subfolders of the inbox folder using ews i have the following inbox folder structureinboxabcabc 2abc 3xyzxyz 2123123 a123 b123 ci am using exchange web services and the following code to find the child folders of the inbox folderexchangeservice service new exchangeserviceexchangeversionexchange2010serviceautothiscoverurlmailbox mb new mailboxfindfoldersresults findresults servicefindfolders wellknownfoldernameinbox new folderviewintmaxvalueforeach folder folder in findresultsfolders consolewritelinefolderthisplaynamethis partly works because it returns the abc xyz and 123 folders unfortunately it does not return the folders inside each of those folders abc 2 abc 3 xyz 2 123 a 123 b 123 calso it is possible that a folder could have more than one level of subfolders inside ithow can i write this code so that it will return all subfolders regardless of how deeply nested they may be,['c#'] +199065,what does dot slash refer to in terms of an html file path location i know means go up a path but what does mean exactlyi was recently going through a tutorial and it seems to be referring to just a file in the same location so is it necessary at all can i just not use it if that is all it is doing,"['javascript', 'html']" +199068,is the correct type required for the delete operator in c void intptr new intdelete int intptris the int type cast required,['c++'] +199069,skip before filter with active admin i am using devise and recently added active admin which created a separate table of admin users to keep adminsall works fine with active admin when i try to log in and browse around however my application controller has this for general usersbefore filter authenticate user except show indexbecause of this when inside the active admin interface whenever i try to edit or delete anything it asks me to log in i learned that a skip before filter can be used inside the controller in which the before filter needs to be excluded however active admin does not have a controller file in the controllers folder or anywhere in my project i could lookcan anyone suggest how to make active admin ignore the application beofre filter which i want to apply on all of the clientuser facing,['ruby-on-rails'] +199097,where should i start investigating sockettimeoutexception read timed out every now and then i see following stacktrace in the log in which httpclient socket times out trying to access textscript content from another server my question is what config settings should i check for my j2ee app running on weblogic on linux i am specifically looking for the followingjvm timeout paramshttpclient paramsweblogic timeout params or any other config like number of threads etcj2ee application settings like servlet config etcoperating system resources like threads file handlers and cpuany other config settings that might influence the socket connectionwould thread dumps helpheres my codehttpresponse httpclientresponsedo some stuffhttpclientresponsegetstatuscode this is where it failsand this is the stacktracejavanetsockettimeoutexception read timed outat jrockitnetsocketnativeioreadbytespinnednative methodat jrockitnetsocketnativeiosocketreadsocketnativeiojava32at javanetsocketinputstreamsocketread0socketinputstreamjavaat javanetsocketinputstreamreadsocketinputstreamjava129at httpclientbufferedinputstreamfillbuffbufferedinputstreamjava206at httpclientbufferedinputstreamreadbufferedinputstreamjava126at httpclientstreamdemultiplexorreadstreamdemultiplexorjava356at httpclientrespinputstreamreadrespinputstreamjava147at httpclientrespinputstreamreadrespinputstreamjava108at httpclientresponsereadresponseheadersresponsejava1123at httpclientresponsegetheadersresponsejava846at httpclientresponsegetstatuscoderesponsejava331at httpclientretrymoduleresponsephase1handlerretrymodulejava92at httpclienthttpresponsehandleresponseimplhttpresponsejava872at httpclienthttpresponseaccess0httpresponsejava62at httpclienthttpresponse2runhttpresponsejava839at httpclienthttpresponse2runhttpresponsejava837athttpclienthttpclientconfigurationdoactionhttpclientconfigurationjava6at httpclienthttpresponsehandleresponsehttpresponsejava837at httpclienthttpresponsegetstatuscodehttpresponsejava242 thanksi will be updating my question with the findings belowthere is no explicit timeout set on httpclient which means that httpsession timeout of the server might be taking an effectso timeout for httpclient is 0 which means that it should wait indefinitely,['java'] +199106,is passbyvalue a reasonable default in c11 in traditional c passing by value into functions and methods is slow for large objects and is generally frowned upon instead c programmers tend to pass references around which is faster but which introduces all sorts of complicated questions around ownership and especially around memory management in the event that the object is heapallocatednow in c11 we have rvalue references and move constructors which mean that it is possible to implement a large object like an stdvector that is cheap to pass by value into and out of a functionso does this mean that the default should be to pass by value for instances of types such as stdvector and stdstring what about for custom objects whats the new best practice,['c++'] +199114,how can i get image file size which selected by uiimagepickercontroller i want to know that the image file size in iphone photoalbum which selected by uiimagepickercontrolleri have tried this code with 1571299 byte jpeg image uiiamge selectedimage info objectforkeyuiimagepickercontrolleroriginalimagensdata imagedata if png image imagedata uiimagepngreprensentationselectedimageelse imagedata uiimagejpegreprensentationselectedimagensuinteger filelength imagedata lengthnslogfile length u filelengthbut when i run the code it print 362788 byteis there anybody who know this,"['iphone', 'objective-c']" +199115,creating statecharts in visio using c can anyone point me to an example of how to programatically create a statechart in visioi can create blank pages drop shapes open template etc but when i try to add transitions it complains that the page is not the right typecannot find a sample anywherealternatively i can save the user actions to create the chart as a macro can i run that programaticallythanks edit step away from the pc for 2 minutes and you realise you should have put the code snippet in the question and not try to put it in comments forest meet trees visiodocument umlstencil visioappdocumentsopenexumlsta mvss shortvisopensaveargsvisopendocked visiopage page visiodocpagesadd visioshape s1 pagedropumlstencilstate 50 50 visioshape s2 pagedropumlstencilstate 50 50 visioshape transition pagedropumlstenciltransition 10 10 as you can see pretty similar to the snippet in the answer below edit,['c#'] +199124,how can i turn the output of aspsitemappath into a list i am extremely unfamiliar with both net and vbnet and cannot quite figure out how to do this say i have code like thisdiv classbreadcrumb aspsitemappath idsitemappath1 runatserveraspsitemappathdivit outputs a bunch of spans with as separators something like thisdiv classbreadcrumb span idctl00 sitemappath1 a hrefctl00 sitemappath1 skiplink img altskip navigation links height0 width0 srcbonfieldwebresourceaxddpepmmiw6qvhaec3hewxgjgvjklzc3domu ezwn6pfl6yriyjwmlvrypb689eslkxysa7aoh x aljls5qxiz7ng41ampt634245478914809245 styleborderwidth0px a span a hrefbonfielddefaultaspxhomea span span 187 span spanshowcasespana idctl00 sitemappath1 skiplinkaspandivhow can i turn that into a list likeul lihomeli lishowcaseliul,['.net'] +199125,zoom effect on android surfaceview i am developing a car race game i am able to move stop accelerate but i want that when i press screen then carbitmap of car image should look like it had jumped on its placei am using surfaceviewto draw viewi do not want to use 3d opengl any help is much appreciated,['android'] +199140,how to detect array equality in javascript there are two arrays in javascript they are both in the following formatdrinkalcohol soft hot fruitapple peari need to detect if the two arrays are equal or not they are considered equal if they contain the same elements in a different order how can i make that,['javascript'] +199150,android fast pixel access and manipulation i am trying to port an emulator that i have written in java to android things have been going nicely i was able to port most of my codes with minor changes however due to how emulation works i need to render image at pixel levelas for desktop java i use int pixelsa databufferint srcgetrastergetdatabuffergetdata which allow me to get the reference to the pixel buffer and update it on the flyminimize object creationscurrently this is what my emulator for android does for every frameoverridepublic void ondrawcanvas canvas buffer bitmapcreatebitmappixelsa 256 192 bitmapconfigrgb 565 canvasdrawbitmapbuffer 0 0 null pixelsa is an array int pixelsa contains all the colour informations so every frame it will have to create a bitmap object by doingbuffer bitmapcreatebitmappixelsa 256 192 bitmapconfigrgb 565which i believe is quite expensive and slowis there any way to draw pixels efficiently with canvas,['android'] +199163,how do i align a view in relativelayout to topright corner im trying to figure out how to align a view in relative layout to its top right cornercurrently it is aligned in top left cornera simple problem yet i dont know how to do ithere is the code relativelayoutlayoutparams gpsviewlayoutparams new relativelayoutlayoutparamsrelativelayoutlayoutparamswrap content relativelayoutlayoutparamswrap content gpsviewlayoutparamsaddrulerelativelayoutalign parent top gpsviewlayoutparamsaddrulerelativelayoutalign right thisrelativelayoutaddviewgpsviewgpsviewlayoutparams,['android'] +199176,ruby why is 1025round2 rounded to 102 as far as i understand the roundfunctionality in ruby rounds decimals upwards where the last significant number is 5for example 15round0 2 okbut why does 1025round2 102 and not 103 as i would expectirbmain0370 1025round2 102what can i do to go around this,['ruby'] +199235,use coffee instead of node command in production i have an appjs that is running expressjsi wanna convert the code to coffeescript and thought about to create a appcoffee that i compile to appjs so i can run it with node appjsbut then it hit me that i could just write that file in appcoffee and run it with coffee appcoffeeis this a better way can i run the server with coffee in production,['javascript'] +199238,wget not working to download jar file from maven repo i am trying to download a single jar file from the maven repository from the url belowdownloading in a browser works fine and i get the file as expectedwget downloads something but the file i get does not appear to be valid running jar tf on the downloaded file gives zipexception error in opening zip filedownloading the file programmatically from java inputstream from the url writing to a fileoutputstream downloads something and creates the file opening that with winzip7zip it appears to contain one file named guavatestlib100 which looks like the jar archive i was expecting to getwget another jar does work as expected at least sometimes with u user agent stringis this some dodgy interaction between wgetmaven or javamaven is it a malformed jar file that my browser understands and downloads correctly both of those seem slightly implausible to me,['java'] +199240,what is the difference between androids invalidate and postinvalidate methods what is the difference between androids invalidate and postinvalidate methods when does each one get called must the methods be called only in classes which extend view,['android'] +199259,iphone simulator simulate 3g connection i am testing the reachability api but my physical device only has wifi access as i do not have a phone contract my code needs to thistinguish between being connected to 3g2g or wifi is it possible to simulate a 3g connection on the iphone simulatorclarifications i am using snow leopard limiting the bandwidth is not what i need i need for the actual interface to be identified as the 3g or 2g radio as opposed to wifi,['iphone'] +199268,how to get the tail of a stdstring how to retrieve the tail of a stdstringif wishes could come true it would work like thatstring tailstring sourcestringright6but this seems to be too easy and does not workany nice solution availableoptional question how to do it with the boost string algorithm libraryaddedthe method should be save even if the original string is smaller than 6 chars,['c++'] +199273,can xdebug track separately the time spent for profiler calls i am using xdebug as a profiler for a php application i have run into a situation where xdebug changes severely the results in such a degree that they are uselesshere a simplified example to demonstrate the problemfunction foo x 1 function bar foo test at0 microtimetruefor i 0 i 10 i fooecho microtimetrue t0test bt0 microtimetruefor i 0 i 10 i barecho microtimetrue t0so these are the results i am getting in seconds profiler profiler profiler thisabled enabled results output output total time time in foo time in bartest a 0159 12199 12245 0110 not calledtest b 0233 25399 25578 0104 11068the increased execution time is expected because of the extra calls to the profiler the slight variation between the microtimebased output and the profiler results is also expected i have repeated the tests several times and the results are always similarfrom the results taken from test b with the profiler thisabled we can say that the script spends about 0159 seconds in foo and 0074 seconds in bar it is evident that time spent in bar is less than the time spent in foohowever when i analyze the results of the profiler with qcachegrind the time shown as spent in bar 11068 seconds is ridiculously higher than the time in foo 0104 seconds there is a possible explanation for this each time a function call is made the profiler runs some extra code to keep track of the time spent in the call i believed that it excluded this extra time from the results but apparently it does noteditas a result the profiler says that bar takes more time than foo in this program which is not the case as we have measured with the profiler thisabled it is not even close the relative results the percentage of time taken by each function are totally wrong this should not be expected because if this is the case the profiler can not indicate which function takes most of the time although the absolute times are expected to have big differences the relative times should not haveeditthis renders the results unusable any code that is more modular with more function calls wrappers objects etc is severely penalized although it is not that slowerso the question is is there any way to tell xdebug to ignore or track separately the extra time spent for the profiler calls,['php'] +199310,how to target net 40 under mono i have mono 210 installed which is said to support 40i have a site running a simple hello world that is built i develop in on a windows box with vs 2010 and then upload to a linux box with 35i want to put the site under 40i changed it on visual studio and on the windows box it works on linux i have the error unrecognized attribute targetframeworkso which steps are needed to change the target from 35 to 40edit am not using monodevelopam creating the site on a windows machine with visual studio and then copying the entire website folder to the linux box after that i open the site url and thats itwhen should i run the dmcs compiler afaik the site is compiled automatically when it runs for the first time,['.net'] +199313,precisely measure execution time of code in thread c i am trying to measure the execution time of some bits of code as accurately as possible on a number of threads taking context switching and thread downtime into account the application is implemented in c vs 2008 examplepublic void threadfunc some code here critical block 1 begins here long ltimestamp1 stopwatchgettimestamp callcomplex3rdpartyfunc a long ltimestamp2 stopwatchgettimestamp critical block 1 ends here some code here critical block 2 begins here long ltimestamp3 stopwatchgettimestamp callothercomplex3rdpartyfunc b long ltimestamp4 stopwatchgettimestamp critical block 2 ends here save timestamps for future analysispublic int main string sargs some code here int ncount somefunc for int i 0 i ncount i thread othread new thread threadfunc othreadstart some code here return 0 i would like to measure the execution time of the above two critical code blocks as accurately as possible the two calls marked as a and b are potentially long function calls that may sometimes take several seconds to execute but in some cases they may complete in a few millisecondsi am running the above code on a number of threads somewhere between 1 to 200 threads depending on user input the computers running this code have 216 cores users use lower thread counts on the weaker machinesthe problem is that a and b are both potenitally long functions so it is very likely that at least one context switch will happen during their execution possibly more than one so the code gets ltimestamp1 then another thread starts executing and the current thread waits eventually the current thread gets back control and retrieves ltimestamp2this means that the duration between ltimestamp1 and ltimestamp2 includes time when the thread was not actually running it was waiting to be scheduled again while other threads executed the tick count however increases anyway so the duration is now reallycode block time a b some time spent in other threadswhile i want it to be onlycode block time a bthis is especially an issue with a larger number of threads since they will all get a chance to run so the above timings will be higher while all other threads run before the thread in question gets another chance to runso my question is is it possible to somehow calculate the time when the thread is not running and then adjust the above timings accordingly i would like to eliminate subtract that 3rd term entirely or at least as much of it as possible the code runs millions of times so final timings are calculated from a lot of samples and then averaged outi am not looking for profiler products etc the application needs to time these the marked parts as accurately as possible the functions a and b are 3rd party functions i cannot change them in any way i am also aware of the possible fluctuations when measuring time with nanosecond precision and possible overhead inside those 3rdparty functions but i still need to do this measurementany advice would be greatly appreciated c or x86 assembly code would work as welledit seems to be impossible to implement this scotts idea below using getthreadtimes is good but unfortunately getthreadtimes is a flawed api and it almost never returns correct data thanks for all the replies,['c#'] +199314,correct singleton pattern objective c ios i found some information in the net to create a singleton class using gcd thats cool because it is threadsafe with very low overhead sadly i could not find complete solutions but only snippets of the sharedinstance method so i made my own class using the trial and error method and et voila the following came outimplementation mysingleton mark mark singleton pattern using gcd idallocwithzonenszone zone return self sharedinstance retain idcopywithzonenszone zone return self idautorelease return self oneway voidrelease singletons cannot be released voiddealloc super dealloc should never be called idretain return self nsuintegerretaincount return nsuintegermax that is so nonzero mysingleton sharedinstance static mysingleton instance nil static thispatch once t predicate thispatch oncepredicate call to super avoids a deadlock with the above allocwithzone instance super allocwithzonenil init return instance mark mark initialization idinit self super init if self initialization code here return selfendplease feel free to comment and tell me if i have missing something or doing something completely wrong cheersstefan,"['ios', 'objective-c']" +199365,winrt start an application on windows boot i am working on a metro style application in the new winrt net 45 framework for windows 8 and i was wondering if it would be possible somehow for an application through the registry or some other means to register itself to start up when windows starts as welli have not been able to find anything about this anywhere else only for windows 7 or below with normalstyle applications,"['c#', '.net']" +199393,where does it come from in this example of objectsetselectvalue productquery1selectvalueint32itproductidhow would i know what it means herewhole example from msdn docsusing adventureworksentities context new adventureworksentities string querystring select value product from adventureworksentitiesproducts as product objectqueryproduct productquery1 new objectqueryproductquerystring context mergeoptionnotracking objectqueryint32 productquery2 productquery1selectvalueint32itproductid foreach int32 result in productquery2 consolewriteline0 result,['c#'] +199419,how do i find elements that contain a data attribute matching a prefix using jquery i am want to create a selector to find elements which have attributes starting with a string at this point i am assuming this selector does not existdo i need to extend the selector capabilities extending jqueryas selector capabilities by james padolseyi need to express something like the attribute contains prefix selector namevalue but instead of matching value i need to match against the name of the attribute and not the value of the attributetag datapluginoption1val1 datapluginoption2val2 i would like to end up with a syntax like thistagattrdataplugin which should find the element tag because it has at least one element that starts with dataplugin,"['javascript', 'jquery']" +199432,create tooltip at cursor position in text area with jquery i am trying to create a tooltip above the input caret in a text area this would be easy if i could get the xy coordinates of the caret in the text area however i have been searching for a little while and cannot figure out how to do thatsay a user is typing in a text area and then presses some key symbol for instance i am trying to show a little tooltip above the text area caretany ideas,['jquery'] +199456,how to make a rounded corner image in java i want to make a image with rounded corners a image will come from input and i will make it rounded corner then save it i use pure java how can i do that i need a function likepublic void makeroundedcornerimage image file outputfileedit added an image for information,['java'] +199477,how can an interface include a method that references the concrete implementation type of the interface in its signature or return type suppose i am designing something like the following interfacepublic interface myinterface public myinterface method1 public void method2myinterface mihowever there is the caveat that the return type for method1 and the parameter for method2 match the concrete implementation and not just myinterface that is if i have myinterfaceimpl that implements myinterface it needs to have the followingpublic class myinterfaceimpl implements myinterface override public myinterfaceimpl method1 override public void method2myinterfaceimpl mias written above method1 would not cause any compile errors but there is nothing guaranteeing that the return type matches in all implementations of course method2 would not even compile because the signature does not match the interfaceone candidate solution is to use selfreferential or recursive bounds in genericspublic interface myinterfacet extends myinterfacet public t method1 public void method2t mipublic class myinterfaceimpl implements myinterfacemyinterfaceimpl override public myinterfaceimpl method1 override public void method2myinterfaceimpl mithis would get me what i want with one exception other implementations might pass the wrong generic type nothing forces t to match the concrete type so potentially someone else could implement the followingpublic class notmyinterfaceimpl implements myinterfacemyinterfaceimpl override public myinterfaceimpl method1 override public void method2myinterfaceimpl mi that would compile just fine even though notmyinterfaceimpl should implement myinterfacenotmyinterfaceimpl that makes me think i need something elsenote that i do not think i am trying to violate lsp i am ok with the return typeparameter being subclasses of notmyinterfaceimplso i do not know of a clean way to do this that leads me to believe that i might be focusing too much on implementation details in the interface but it does not seem that way to me is there any way to do the type of thing i described or is this some kind of smell that i am putting something in an interface that does not belong there,['java'] +199484,check for operator how do i check whether an object supports operation in python i think of something like the followingif supportsobj printsupports,['python'] +199496,how to hide a text after 5 sec using jquery how can i hide the results after 5 secs i tried this but it does not workresultshidehtmldatafadeinslowdelay50hidewhat i had is this oneresultshidehtmldatafadeinslow,"['javascript', 'jquery']" +199497,sorting gigantic binary files with c i have a large file of roughly 400 gb of size generated daily by an external closed system it is a binary file with the following formatbyte8byte4bytenwhere and is equal to the int32 value of byte4this file has no delimiters and to read the whole file you would just repeat until eof with each item represented as byte8byte4bytenthe file looks like byte8byte4bytenbyte8byte4byteneofbyte8 is a 64bit number representing a period of time represented by net ticks i need to sort this file but cannot seem to figure out the quickest way to do sopresently i load the ticks into a struct and the byten start and end positions and read to the end of the file after this i sort the list in memory by the ticks property and then open a binaryreader and seek to each position in ticks order read the byten value and write to an external fileat the end of the process i end up with a sorted binary file but it takes forever i am using c net and a pretty beefy server but thisk io seems to be an issueserver specs2x 26 ghz intel xeon hexcore with ht 24threads32gb ram500gb raid 102tb raid 5i have looked all over the internet and can only find examples where a huge file is 1gb makes me chuckledoes anyone have any advice,['c#'] +199499,trying to use jquery tooltip plugin object has no method tooltip i am using this tooltip i have the following lines in my html filescript srcjavascriptshomejs typetextjavascriptscriptscript src typetextjavascriptscriptscript typetextjavascript srcscriptsjqueryminjsscriptdiv idbooimg srcimage1jpg titlethis thing is a toolimg srcimage2jpg titlethis thing is also tooldivi have the following line in my homejs fileboo imgtitletooltipi have the following line in my css filetooltip thisplaynone backgroundtransparent urltoolsimgtooltipblack arrowpng fontsize12px height70px width160px padding25px colorf i get this erroruncaught typeerror object object object has no method tooltipi am at my wits end i feel like i have followed the example on the site exactly but no idea whats going on,['jquery'] +199510,str replace for multiple items i remember doing this before but cannot find the code i use str replace to replace one character like this str replace string but i want to replace all the following characters without doing a str replace for each,['php'] +199547,how to correctly create a tablayout now that the tabactivity is deprecated since the introduction of fragments the tabactivity is deprecated the hello views tablayout tutorial however still uses the tabactivity and the apidocumentation has no clear answer on how to create a tab layout with fragments instead of a tabactivity how are you building tablayouts now that the tabactivity is deprecated,['android'] +199565,magento easy way to remove paypalexpressreview step when ordering using paypal in magento it takes you to paypal paypal already thisplays a confirmation you confirm you get redirected to another confirmation page paypalexpressreview it is an extra step that is unnecessary for user experience i would like to remove it and make the order automatically placed when user confirm on paypal page once leave paypal if order successful the customer should see the success page is there any easy solution to this i might have overlooked or at least if you can point me to the right direction to remove that step,['php'] +199570,java regular expression optimization tips i am new to java regular expression we are using a pattern for matching a string we are using this for validating a text field and it meets our requirements but there is a performance issue in the matchingpattern azaz09 azaz09 input text should start with azaz09spacesingle is allowed between words and are allowed but cannot be consecutiveour problem is for certain input strings the cpu time goes high and causes hanging the threads also we get exceptions can anyone please help me to optimize the pattern or suggest a new pattern to solve my issueexception details hung thread details all the same92811 114007320 cdt 03 threadmonitor w wsvr0605w thread webcontainer 26 04f has been active for 709755 milliseconds and may be hung there isare 1 threads in total in the server that may be hung at javautilregexpatterngroupcurlymatchpatternjava3938 at javautilregexpatterngroupheadmatchpatternjava4180 at javautilregexpatternbranchmatchpatternjava4124 at javautilregexpatternquesmatchpatternjava3703 at javautilregexpatterncurlymatch0patternjava3801 at javautilregexpatterncurlymatchpatternjava3756 at javautilregexpatterngroupheadmatchpatternjava4180 at javautilregexpatternloopmatchpatternjava4307 at javautilregexpatterngrouptailmatchpatternjava4239 at javautilregexpatternquesmatchpatternjava3703 at javautilregexpatternbranchconnmatchpatternjava4090 at javautilregexpatterngrouptailmatchpatternjava4239 at javautilregexpatterngroupcurlymatch0patternjava4006 at javautilregexpatterngroupcurlymatchpatternjava3928 at javautilregexpatterngroupheadmatchpatternjava4180 at javautilregexpatternbranchmatchpatternjava4124 at javautilregexpatternquesmatchpatternjava3703 at javautilregexpatterncurlymatch0patternjava3794 at javautilregexpatterncurlymatchpatternjava3756 at javautilregexpatterngroupheadmatchpatternjava4180 at javautilregexpatternloopmatchpatternjava4307 at javautilregexpatterngrouptailmatchpatternjava4239 at javautilregexpatternquesmatchpatternjava3703 at javautilregexpatternbranchmatchpatternjava4124 at javautilregexpatternquesmatchpatternjava3703 at javautilregexpatterncurlymatch0patternjava3794 at javautilregexpatterncurlymatchpatternjava3756 at javautilregexpatterngroupheadmatchpatternjava4180 at javautilregexpatternloopmatchpatternjava4307 at javautilregexpatterngrouptailmatchpatternjava4239 at javautilregexpatternquesmatchpatternjava3703 at javautilregexpatternbranchconnmatchpatternjava4090 at javautilregexpatterngrouptailmatchpatternjava4239 at javautilregexpatterngroupcurlymatch0patternjava4006 at javautilregexpatterngroupcurlymatchpatternjava3928 at javautilregexpatterngroupheadmatchpatternjava4180 at javautilregexpatternbranchmatchpatternjava4124 at javautilregexpatternquesmatchpatternjava3703 at javautilregexpatterncurlymatch0patternjava3794 at javautilregexpatterncurlymatchpatternjava3756 at javautilregexpatterngroupheadmatchpatternjava4180 at javautilregexpatternloopmatchpatternjava4307 at javautilregexpatterngrouptailmatchpatternjava4239 at javautilregexpatternquesmatchpatternjava3703 at javautilregexpatternbranchconnmatchpatternjava4090 at javautilregexpatterngrouptailmatchpatternjava4239 at javautilregexpatterngroupcurlymatch0patternjava4006 at javautilregexpatterngroupcurlymatchpatternjava3928 at javautilregexpatterngroupheadmatchpatternjava4180 at javautilregexpatternbranchmatchpatternjava4124 at javautilregexpatternquesmatchpatternjava3703 at javautilregexpatterncurlymatch0patternjava3794 at javautilregexpatterncurlymatchpatternjava3756 at javautilregexpatterngroupheadmatchpatternjava4180 at javautilregexpatternloopmatchpatternjava4307 at javautilregexpatterngrouptailmatchpatternjava4239 at javautilregexpatternquesmatchpatternjava3703 at javautilregexpatternbranchmatchpatternjava4124 at javautilregexpatternquesmatchpatternjava3703 at javautilregexpatterncurlymatch0patternjava3794 at javautilregexpatterncurlymatchpatternjava3756 at javautilregexpatterngroupheadmatchpatternjava4180 at javautilregexpatternloopmatchpatternjava4307 at javautilregexpatterngrouptailmatchpatternjava4239 at javautilregexpatternquesmatchpatternjava3703 at javautilregexpatternbranchmatchpatternjava4124 at javautilregexpatternquesmatchpatternjava3703 at javautilregexpatterncurlymatch0patternjava3801 at javautilregexpatterncurlymatchpatternjava3756 at javautilregexpatterngroupheadmatchpatternjava4180 at javautilregexpatternloopmatchpatternjava4307 at javautilregexpatterngrouptailmatchpatternjava4239 at javautilregexpatternquesmatchpatternjava3703 at javautilregexpatternbranchconnmatchpatternjava4090 at javautilregexpatterngrouptailmatchpatternjava4239 at javautilregexpatterngroupcurlymatch0patternjava4006 at javautilregexpatterngroupcurlymatchpatternjava3928 at javautilregexpatterngroupheadmatchpatternjava4180 at javautilregexpatternbranchmatchpatternjava4124 at javautilregexpatternquesmatchpatternjava3703 at javautilregexpatterncurlymatch0patternjava3794 at javautilregexpatterncurlymatchpatternjava3756 at javautilregexpatterngroupheadmatchpatternjava4180 at javautilregexpatternloopmatchpatternjava4307 at javautilregexpatterngrouptailmatchpatternjava4239 at javautilregexpatternquesmatchpatternjava3703 at javautilregexpatternbranchmatchpatternjava4124 at javautilregexpatternquesmatchpatternjava3703 at javautilregexpatterncurlymatch0patternjava3794 at javautilregexpatterncurlymatchpatternjava3756 at javautilregexpatterngroupheadmatchpatternjava4180 at javautilregexpatternloopmatchpatternjava4307 at javautilregexpatterngrouptailmatchpatternjava4239 at javautilregexpatternquesmatchpatternjava3703 at javautilregexpatternbranchconnmatchpatternjava4090 at javautilregexpatterngrouptailmatchpatternjava4239 at javautilregexpatterngroupcurlymatch0patternjava4006 at javautilregexpatterngroupcurlymatchpatternjava3928 at javautilregexpatterngroupheadmatchpatternjava4180 at javautilregexpatternbranchmatchpatternjava4124 at javautilregexpatternquesmatchpatternjava3703 at javautilregexpatterncurlymatch0patternjava3794 at javautilregexpatterncurlymatchpatternjava3756 at javautilregexpatterngroupheadmatchpatternjava4180 at javautilregexpatternloopmatchpatternjava4307 at javautilregexpatterngrouptailmatchpatternjava4239 at javautilregexpatternquesmatchpatternjava3703 at javautilregexpatternbranchmatchpatternjava4124 at javautilregexpatternquesmatchpatternjava3703 at javautilregexpatterncurlymatch0patternjava3794 at javautilregexpatterncurlymatchpatternjava3756 at javautilregexpatterngroupheadmatchpatternjava4180 at javautilregexpatternloopmatchpatternjava4307 at javautilregexpatterngrouptailmatchpatternjava4239 at javautilregexpatternquesmatchpatternjava3703 at javautilregexpatternbranchmatchpatternjava4124 at javautilregexpatternquesmatchpatternjava3703 at javautilregexpatterncurlymatch0patternjava3794 at javautilregexpatterncurlymatchpatternjava3756 at javautilregexpatterngroupheadmatchpatternjava4180 at javautilregexpatternloopmatchpatternjava4307 at javautilregexpatterngrouptailmatchpatternjava4239 at javautilregexpatternquesmatchpatternjava3703 at javautilregexpatternbranchconnmatchpatternjava4090 at javautilregexpatterngrouptailmatchpatternjava4239 at javautilregexpatterngroupcurlymatch0patternjava4006 at javautilregexpatterngroupcurlymatchpatternjava3928 at javautilregexpatterngroupheadmatchpatternjava4180 at javautilregexpatternbranchmatchpatternjava4124 at javautilregexpatternquesmatchpatternjava3703 at javautilregexpatterncurlymatch0patternjava3794 at javautilregexpatterncurlymatchpatternjava3756 at javautilregexpatterngroupheadmatchpatternjava4180 at javautilregexpatternloopmatchpatternjava4307 at javautilregexpatterngrouptailmatchpatternjava4239 at javautilregexpatternquesmatchpatternjava3703 at javautilregexpatternbranchconnmatchpatternjava4090 at javautilregexpatterngrouptailmatchpatternjava4239 at javautilregexpatterngroupcurlymatch0patternjava4006 at javautilregexpatterngroupcurlymatchpatternjava3928 at javautilregexpatterngroupheadmatchpatternjava4180 at javautilregexpatternbranchmatchpatternjava4124 at javautilregexpatternquesmatchpatternjava3703 at javautilregexpatterncurlymatch0patternjava3794 at javautilregexpatterncurlymatchpatternjava3756 at javautilregexpatterngroupheadmatchpatternjava4180 at javautilregexpatternloopmatchinitpatternjava4323 at javautilregexpatternprologmatchpatternjava4263 at javautilregexmatchermatchmatcherjava1139 at javautilregexmatchermatchesmatcherjava514,['java'] +199577,finish activity after toast message thisappears does anybody know if there is a possibility to do something in my case finish activity on toast message will be closed,['android'] +199601,are there any perfomance test results for usage of likelyunlikely hints gcc features likelyunlikely hints that help the compiler to generate machine code with better branch predictionis there any data on how proper usage or failure to use those hints affects performance of real code on some real systems,"['c++', 'c']" +199616,implement ithispatchinvoke to be called by a webbrowser control i am trying to do what they explain on this article in the controlling download and execution section i understand the web browser control in that context is not nets webbrowserwhat i am trying to do is to gain control over what the webbrowser control downloads i have been searching for this a lot and always en up in the csexwb which has a huge code that i just cannot decipher what i have done so far is inherit nets webbrowser make my inherited class com visible by using the comvisibletrue attribute add this method to my class taken from csexwb thispidhtmlthispidsthispid ambient dlcontrol public int ithispatch ambiantdlcontrol invoke handler return intm dlctlflags and then call this line of code where browser is an instance of my derived classifacesenumsstructsclassesiolecontrol olecontrol browseractivexinstance as ifacesenumsstructsclassesiolecontrololecontrolonambientpropertychangeifacesenumsstructsclasseshtmlthispidsthispid ambient dlcontrolso what i am hoping is that the olecontrol will call my ithispatch ambiantdlcontrol invoke handler method which it does not i do not know how and this is probably what my code is missing is the olecontrol supposed to know on which object to call my ithispatch ambiantdlcontrol invoke handler method what the article i linked above says is it will call your ithispatchinvoke what does it mean by your how do i tell olecontrol which object is my ithispatch hope i am making any sense,['c#'] +199631,set the value of a input field with javascript how would you set the default value of a form input text field in javascript,['javascript'] +199633,opencv random forest example do anyone have some example using random forests with the 231 api mat and not the cvmat basicly i have a matrix mat data that consist of 10 rows with 16x16x3 elements and a matrix mat responses a 10x1 matrix that hold which class each row belong to i would like to run the random forest algorithm on this,['c++'] +199637,not able to access adb in os x through terminal command not found i have installed android sdk and eclipse on mya mac system i am able to program using eclipse and have created few sample applications but i am still not able to access adb through the terminal window i have tried following command in terminal pwdusersespireinfolabsdesktopsoftandroidsdkmac x86platformtools lsnoticetxt dexdump llvmrscc2aapt dx llvmrscctxtadb lib sourcepropertiesaidl llvmrscc adb helpbash adb command not foundi have also added the ls output so that you know in which window i am,['android'] +199655,how to subclass uiapplication in monotouch edita couple of years later things are easier it is now possible to omit theregister attributes both on the application and the app delegate and instead useuiapplicationmainargs typeofcustomapp typeofcustomappdelegatein order to be able to override uiapplicationsendevent i want to subclass uiapplicationpublic class uiapplicationmain uiapplication public uiapplicationmain base public override void sendevent uievent uievent basesendevent uievent in the maincs i use this codepublic class application static void main string args uiapplicationmain args uiapplicationmain appdelegatebase but it fails withobjectivec exception thrown namensinternalinconsistencyexception reason unable to instantiate the uiapplication subclass instance no class named uiapplicationmain is loadedso i am missing some attributes i guess but what and where,"['c#', 'ios']" +199681,add custom headers to webview resource requests android i need to add custom headers to every request coming from the webview i know loadurl has the parameter for extraheaders but those are only applied to the initial request all subsequent requests do not contain the headers i have looked at all overrides in webviewclient but nothing allows for adding headers to resource requests onloadresourcewebview view string url any help would be wonderfulthanksray,"['java', 'android']" +199688,css thisplay inlineblock does not accept margintop i have an element with thisplay inlineblock but it does not seem to accept margintop is this because the element is still treated as an inline elementif yes does anyone have a workaroundedit 1my css is quite simplelabel background f thisplay inlineblock margintop 2px padding 7px 7px 5pxi ended up wrapping the content in another div and giving that a margintop but that causes a lot of extra markup and makes my code less clearedit 2margintop marginbottom on inlineblock elements only seems to work with positive values,['css'] +199693,getting year and week of year from php date when week spans two years i have run into an interesting issue using phps date function have not had any luck locating a thiscussion of this on so or using google but maybe someone else has run into the same issue beforei am trying to get the year and the week of the year for a given timestamp this is the code i am usingdateywhich as of today correctly outputs 2011w39the problem is when supplying a timestamp if the timestamp in question is for example on january 3rd 2011 which was actually part of the 52nd week of 2010 php correctly returns w52 but it also returns 2011 as the year instead of 2010 dateyww 1294016400outputs 2011w52any idea on how to solve this problem i should note that although in this case it would be easy to just compare that the strtotime of the output is greater than the current time and adjust but i need a solution that will work for previous years as well eg if the same thing happened for january 3rd 2010,['php'] +199697,supress console output from chrome extensions when troubleshooting my own javascript i see console messages from my installed chrome extensions is there any way to supress these messages i would prefer to not see them as they clutter up the console output,['javascript'] +199740,phonegap and retina thisplay i am creating an app for iphone using phonegap but i am sure it is not working using retina thisplay instead of that it is using the old iphone3 resolutionis there any way to have 2 versions for iphone when developing using phonegap this is one version using retina and another version with worst resolution for the older devicesthanks,['iphone'] +199759,iequatables implementation only called if the base equals is overridden i have the following class class product iequatableproduct public guid id get set public bool equalsproduct other return idequalsotherid if i try and create a unique list of the items of a list as follows guid a guidnewguid listproduct lista new listproduct listaaddnew productid a listproduct listb new listproduct listbaddnew product id a debugassertlistaunionlistbcount1two items are returned this occurs until i override the objectequals method once i do this and my code is as follows class product iequatableproduct public guid id get set public bool equalsproduct other if referenceequalsnull other return false if referenceequalsthis other return true return otheridequalsid public override bool equalsobject obj if referenceequalsnull obj return false if referenceequalsthis obj return true if objgettype typeof product return false return equalsproduct obj public override int gethashcode return idgethashcode my iequatable equals method is now called but only if i override the base method furthermore if i put a breakpoint on the object equals method it is never called why is thisupdateso with the product class class product iequatableproduct public guid id get set public bool equalsproduct other return idequalsotherid public override int gethashcode return idgethashcode if gethashcode is removed the iequatable implementation of equals is never hit i understand you should generally implement equals and gethashcode together is this why,"['c#', '.net']" +199779,what is this technique to resize the images proportionally used by google chrome new tab i saw this code in google chrome beta versions new tab where it show the icon if installed tabsthey are using any technique to resize the imagesthis is html of a icondiv classappimgcontainer launchclicktarget titlebox office styleheight 9756981132075472px width 9756981132075472px img class srcchromeextensionicondhbbohlkjglcppclgngklojecglglinl1280 divand it is css of related classesappimgcontainer marginleft automarginright autowebkitmasksize 100 100appimgcontainer height 100width 100can anyone tell me which method they are using is it based on javascript to check this you can install google chrome beta and install some apps from chrome store then open a new tab in chrome you will se the iconsnote it is only works in beta versionthis is the whole source of tab page which i took from view sourceand this is rendred source which i copied from chrome developer tools html tabi want to know the method which is being used to resize the icons,"['javascript', 'css']" +199783,does cascadealldeleteorphan have any meaning in a hibernate unidirectional manytomany association with a join table i have two objects which form a parentchild relationship which have a manytomany relationship following the recommendations in the hibernate reference manual i have mapped this using a join tableclass nameconference tableconferences set namespeakers tableconference speakers cascadeall key columnconference id manytomany claspeaker columnspeaker id setclassclass namespeaker tablespeakers id nameid columnid generator classnative id property namefirstname property namelastnameclassmy wish is that a single speaker can be associated with many different conferences but also that any speaker which is no longer referenced by any conference is removed from the speakers table as a speaker with no associated conferences does not have much meaning in my projecthowever i have found that if i use cascadealldeleteorphan then if a speaker which is associated with multiple conferences is removed from just one of them hibernate attempts to delete the speaker instance itselfbelow is a unit test which shows this behaviortestpublic void testremovesharedspeaker int initialcount countrowsintablespeakers conference c1 new conferencec1 conference c2 new conferencec2 speaker s new speakerjohn doe c1getspeakersadds c2getspeakersadds conferencedaosaveorupdatec1 conferencedaosaveorupdatec2 flushhibernate assertequalsinitialcount 1 countrowsintablespeakers assertequals2 countrowsintableconference speakers the remove c1 conferencedaogetc1getid c1getspeakersremoves flushhibernate assertequalscount should stay the same initialcount 1 countrowsintablespeakers assertequals1 countrowsintableconference speakers c1 conferencedaogetc1getid c2 conferencedaogetc2getid assertequals0 c1getspeakerssize assertequals1 c2getspeakerssizean error is thrown when ss removal from c1speakers is processed because hibernate is deleting both the row in the join table and the speakers table row as welldebug orghibernatesql delete from conference speakers where conference id and speaker id debug orghibernatesql delete from speakers where idif i change cascadealldeleteorphan to just cascadeall then this test works as expected although it leads to the undesired behavior where i will end up with orphaned rows in my speakers tablethis leads me to wonder is it even possible for hibernate to know when to delete orphaned objects from the childside of the relationship but only when the child is not referenced by any other parents whether or not those parents are in the current session perhaps i am misusing cascadealldeleteorphani get the same exact behavior if i use jpa annotations instead of xml mapping such asmanytomanycascade cascadetypealljointablename conference speakers joincolumns joincolumnname conference id inversejoincolumns joincolumnname speaker idorghibernateannotationscascadeorghibernateannotationscascadetypedelete orphanprivate setspeaker speakers new hashsetspeakerthis is with hibernate 367final by the way,['java'] +199794,listen to multiple keydowns i am trying to let a user move an element on the page using the arrow keys so far i have movement working for updownleftright but not for diagonal two arrow keys pressed simultaneouslymy listener looks like thisaddeventlistenerkeydown functione move false x false y false var keycode if windowevent keycode windoweventkeycode else if e keycode ewhich switchkeycode case 37 move true x negative prevent page scroll epreventdefault break case 38 move true y negative prevent page scroll epreventdefault break case 39 move true x positive prevent page scroll epreventdefault break case 40 move true y positive prevent page scroll epreventdefault break ifmove animationmovexy return falsethe idea was that if the user presses an arrow key it sets x and y to either negative or positive and fires off the move function which will move the element a preset number of pixels in the desired direction and that if two keys were pressed a second event would fire i also hope to be able to have the user seemlessly change directions by releasing and pressing keys rapidly neither of these are happening however if the user presses another direction key they seem to need to wait a momment for movement to happen unless they completely release the key and then press another one and it would not respond to the second key at all until the first is released,['javascript'] +199800,strange bug in usage of abs i encountered recently i have cc mixed code which i build ona visual c 2010 expressfree version on win7 x32b cygwingcc environment installed on a windows7 home premium edition x32 the gcc version 344 cygming special gdc 012 using dmd 0125c ubuntu 1004 linux gcc version 443 ubuntu 4434ubuntu5i have a code as belowits a member function for my user defined class which computes absolute value of the passed object myhalfmyhalfmyhalfabsmyhalf a float tmp tmp absavalue this abs is from mathh float absfloat return tmpthis is working perfectly as desired in ms visual c 2010 abs of ve nos were returned correctly as ve nos having same valuestrangely when i built this code on b cygwingcc environment c linuxgcc 443 mentioned above i was getting junk output so fired up gdb and after lot of sweat and binarysearch approach on the code to decide where it started going wrong i hit this piece of code as shown above tmp absavaluewhich was behaving strangely under cygwingccfor ve numbers abs was returning 0zero wtfthen as a work around avoided calling abs from stdlib and coded my own abs as belowmyhalfmyhalfabsmyhalf a float tmp unsigned int tmp dbg tmp absavalue tmp dbg unsigned intavalue tmp dbg tmp dbg 0x7f tmp floattmp dbg return tmpthis worked fine on cygwingcc linuxgcc and output was as desired and of course it worked fine on msvisual c 2010this is the whole makefile for the cygwingcc and linuxgcc builds i use just if anyone supspects something fishy thereobjs all my obj files listed here explicitlyheaders my header files herecflags walibs lmldflags libsmdebug1ifdef mdebugcflags fmudflapldflags fmudflap lmudflapendifmyexe objs g objs ldflags o myexeo cpp headers makefile g cflags c clean rm f myexe objs1 what is going on here what is the root cause of this strange bug2 am i using some old version of gcc on cygwin which has this issue as known bug or something3 is this function float absfloat known to be deprecated or something with a newer version superseding itany pointers are useful,['c++'] +199814,difference between classloadergetsystemresourceasstream and getclassgetresourceasstream given this code 1 inputstream in1 classloadergetsystemresourceasstreamfoobartxt 2 inputstream in2 thisgetclassgetresourceasstreamfoobartxtdo both return the same resource i think the answers yesdo they both access the same classpath why is the method name in 1 get system resourceasstream but for 2 it is just getresourceasstreamthanks,['java'] +199820,browscapini throwing an error when loading php command line php cli i have a cronjob that summarize browser statistics this cronjob loads data and then use the get browser php function to parse the browser informationheres what i didcd etcphp5cliconfdmeubutnuetcphp5cliconfd sudo wget php browscapini o browscapini20110930 151418 890 kbs browscapini saved 185384185384then the cronjob runphp usrlocalcronsummarizestatsphp optionbrowserstats dateyesterdayand i get this errorphp syntax error unexpected end expecting in etcphp5cliconfdbrowscapini on line 51what am i doing wrong thanks,['php'] +199824,autofull screen for a youtube embed i have a youtube video embeded on a webpage is it possible to have the video go full screen when the user presses play using the html5 iframe with youtubes apiusing the chromeless player is not an option as the website is intended for ipads,['javascript'] +199862,combining nsarrays through intersection and union i have two nsarrays a and b that share some common elements ega 12345 b 4567i would like to create a new nsarray consisting of the contents common between the two nsarrays joined with the contents of the second nsarray while maintaining the order of the elements and removing duplicates that is i would like a a b aa b the operation on the previous nsarrays would yielda a b 45a a b aa b 4567how do i accomplish this in objectivec,['objective-c'] +199864,how do execute a sql script from bash basically i need to setup a database from a bash script i have a script dbsql that does all this now how do i run this script from bashdatabase system is mysql,['mysql'] +199876,elementtrees iter equivalent in python26 i have this code with elementtree that works well with python 27i needed to get all the nodes with the name a under xy node from xmletrelementtree import elementtreeverbosenode topnodefindxynodes listverbosenodeiterahowever when i tried to run it with python 26 i got this error ioncalculateskewconstraintpy line 303 in getnodeswithattribute nodes liststartnodeiternodenameattributeerror elementinterface instance has no attribute iterit looks like that python 26 elementtrees node does not have the iterhow can i implement the iter with python 26,['python'] +199877,amazon s3 upload with public permissions i am using the amazon c sdk and trying to upload a file but by default it has restricted permissions i would like to make it publicly available but i cannot seem to find out how to do it as part of the upload my bucket is public but when i upload a new file using the code below the file i upload is not publichas anyone had to do this beforepublic class s3uploader private string awsaccesskeyid private string awssecretaccesskey private string bucketname private amazons3transfertransferutility transferutility public s3uploaderstring bucketname thisbucketname bucketname thistransferutility new amazons3transfertransferutilityx x public void uploadfilestring filepath string topath asynccallback callback new asynccallbackuploadcomplete transferutilitybeginuploadfilepath bucketname topath callback null private void uploadcompleteiasyncresult result var x result,['c#'] +199881,gprof command is not creating proper outtxt first of all i am running macosx 1071 i have installed all properly xcode 4 and all the libraries to work with c lenguagei am having troubles running gprof command in shell i will explain step by step what i am doing and the output i am receivingstep 1 roger cd pathtomyworkspace roger lsoutput step 1queuec queueh testqueuecstep 2 roger gcc c g pg queuec roger lsoutput step 2queuec queueh queueo testqueuecstep 3 roger gcc o testqueue g pg queueo testqueuec roger lsoutput step 3queuec queueh queueo testqueue testqueuecstep 4 roger testqueue roger lsoutput step 4enqueue element 16807head0tail1enqueue element 282475249head0tail2enqueue element 1622650073head0tail3enqueue element 984943658head0tail4enqueue element 1144108930head0tail5enqueue element 470211272head0tail6enqueue element 101027544head0tail7enqueue element 1457850878head0tail8enqueue element 14587923head0tail9enqueue element 2007237709head0tail10queue is fulldequeue element 16807dequeue element 282475249dequeue element 1622650073dequeue element 984943658dequeue element 1144108930dequeue element 470211272dequeue element 101027544dequeue element 1457850878dequeue element 14587923dequeue element 2007237709queue is emptygmonout queueh testqueuequeuec queueo testqueuecstep 5 roger gprof b testqueue gmonout outtxt roger nano outtxtoutput step 5 gnu nano 206 file outtxtgranularity each sample hit covers 4 bytes no time propagatedcalledtotal parentsindex time self descendents calledself name indexcalledtotal childrenlgranularity each sample hit covers 4 bytes no time accumulated cumulative self self totaltime seconds seconds calls mscall mscall namelindex by function namefinally the output file should show something like this cumulative self self total time seconds seconds calls mscall mscall name 34 002 002 7208 0 0 open 1667 003 001 244 004 012 offtime 1667 004 001 8 125 125 memccpy 1667 005 001 7 143 143 write 1667 006 001 mcount 0 006 0 236 0 0 tzset 0 006 0 192 0 0 tolower 0 006 0 47 0 0 strlen 0 006 0 45 0 0 strchr 0 006 0 1 0 50 main 0 006 0 1 0 0 memcpy 0 006 0 1 0 1011 print 0 006 0 1 0 0 profil 0 006 0 1 0 50 reportand it shows blank fieldi searched here and i found nothing helpfully at all i google it but the same thingi would be very grateful if anyone could help me please,['c'] +199896,why do not i see my todos for my php files in eclipse why do not i see my todos for my php files in eclipsei ran into this issue in pdt i just wanted to put the answer up in case someone else did too,['php'] +199897,when probing for assemblies why does the searched for publickeytoken differ when running as admin vs as a normal user i am following instructions from a 2006 microsoft net course workbook going through one of the exercises specifically this course is ms2349b and i am doing module 4 exercise 2 these exercises seem to built for the pre vista days when everyone has full admin privileges all the time i am using net 40this exercise involves building a strong name assembly installing it in the gac building a local executable against the strong named assembly verifying that the executable runsas per the tutorial i sign my assembly using a if blockif strongassembly systemreflectionassemblyversion20assembly systemreflectionassemblykeyfileorgverkeysnkendifi build my executable as a local usercpathtolabcsc definestrong targetlibrary outareverser v20areverserdll areverser v20areversercscpathtolabcsc referencemystringerstringerdll referenceareverser v20areverserdll clientcsi install it into the gac via a visual studio command prompt run as administrator cpathtolabgacutil i areverser v20areverserdllwhen i run my exe in the administrator prompt i get the output i expect the application runs fine and appears to load the dll correctly from the gac when i run under the nonadmin command prompt i get the following errorunhandled exception systemiofileloadexception could not load file or assembly areverser version20 cultureneutral publickeytokenb5fcbdcff229fabb or one of its dependencies the located assemblys manifest definition does not match the assembly reference exception from hresult 0x80131040 at mainappmainwhats odd to me is that the publickeytoken is not the same as whats in the gacareverser version20 cultureneutral publickeytokenf0548c0027634b66but if i uninstall areverser from the gac and attempt to run my exe as admin prompt i get the following error which indicates its looking for the expected public key token f0548c0027634b66cpathtolabgacutil u areverserversion20cultureneutralpublickeytokenf0548c0027634b66microsoft r net global assembly cache utility version 40303191copyright c microsoft corporation all rights reservedassembly areverser version20 cultureneutral publickeytokenf0548c0027634b66uninstalled areverser version20 cultureneutral publickeytokenf0548c0027634b66number of assemblies uninstalled 1number of failures 0cpathtolabclientexeunhandled exception systemiofileloadexception could not load file or assembly areverser version20 cultureneutral publickeytokenf0548c0027634b66 or one of its dependencies the located assemblys manifest definition does not match the assembly reference exception from hresult 0x80131040 at mainappmainnotice under admin its actually searching for the correct publickeytokenwhat gives why would the searched for publickkeytokens differ what could i have done wrongeditthe app config were told to use may be the culprit i am wondering if you have to be admin to apply some of these settings getting rid of it seems to cause running as admin to fail although in that case publickeytoken is listed as null heres my app configconfiguration runtime assemblybinding xmlnsurnschemasmicrosoftcomasmv1 probing privatepathmystringer publisherpolicy applyno dependentassembly assemblyidentity nameareverser publickeytokenf0548c0027634b66 culture publisherpolicy applyno bindingredirect oldversion20 newversion20 dependentassembly assemblybinding runtimeconfiguration,"['c#', '.net']" +199903,activerecordstatementinvalid could not find table i am trying to run users testrb file which just hastest the truth do assert true endi do have a likes table still i am getting this error why soyour bundle is complete use bundle show gemname to see where a bundled gem is installeda channelappnew rake dbtestclonea channelappnew rake dbtestclone structurea channelappnew rake dbmigratea channelappnew rake dbtestloada channelappnew rake dbtestpreparea channelappnew rake dbtestpurgea channelappnew ruby itest testunituser testrbloaded suite testunituser teststartedeerrortest the truthusertestactiverecordstatementinvalid could not find table likesfinished in 0058371 seconds1 tests 0 assertions 0 failures 1 errors 0 pendings 0 omissions 0 notifications0 passed1713 testss 0 assertionssthanks,['ruby-on-rails'] +199906,how to share objects between different classloaders i need different classloaders to be able to unload classes but i need to share objects between them actually i am getting classcastexception so what are the solutions to deal with this thanks,['java'] +199932,adding uisearchbar as tableheaderview in xib not works i added uisearchbar as tableheaderview for uitableview in xib by just dropping uisearchbar onto uitableview it is working fine when the table has more than 6 rows but when there is less than 6 rows it uitableview does not scroll at the same time if i add the uisearchbar as tableheaderview for uitableview programatically in m file using the following statement everything works fine tableviewtemptableheaderview searchbarfriends seems very strange to me what might be the problem please advice thank you,"['iphone', 'objective-c']" +199935,generating one texture2d from multiple texture2ds my problem is the i need to represent a lengthchanging floor using a texture2d which means a floor that the sides has the image of the sides and in the middle it repeats the same middle image like soto achieve this i get the left edge the middle and the right edge textures problem is i do not know how to merge them into one single texture2dit is important to do that at runtime because the floor length is changing horizontallyi read you can do that using setdata but i have no idea howit is very important for me that it will act as one texture and not multiple texture parts because i am using farseer physics engine to move the floor and use iti am using c and xna with visual studio 2010 i am an almostexperienced c programmerthank you,['c#'] +199969,can i automatically send sms without the user need to approve i am rather new to android im trying to send sms from android application when using the sms intent the sms window opens and the user needs to approve the sms and send itis there a way to automatically send the sms without the user confirming it thankslior,['android'] +199981,generate random coordinates around a location i would like to have a function that accepts a geo location latitude longitude and generates random sets of coordinates around it but also takes these parameters as a part of the calculationnumber of random coordinates to makeradius to generate inmin thistance between the random coordinates in metersthe root coordinates to generate the locations around itexample of how the generation would bewhats a good approach to achieve this,['php'] +199992,where is the thread going when a future leaves scope with threads i know that terminate is called when the threadvariable leaves scopesize t fibrecsize t n return n2 1 fibrecn2fibrecn1int main stdthread th fibrec 35 no join here th will call terminateths destructor will call terminate when it leaves scopebut what about futures where is the thread they run going is it detached how is it endedinclude iostreaminclude future asyncusing namespace stdsize t fibrecsize t n return n2 1 fibrecn2fibrecn1struct fibrec size t operatorsize t n return fibrecn const size t name fibrecsize t name name name fibrec cerr name endl void execit auto f1 async fibrec33 33 auto f2 async fibrec34 34 no fxget here f1 f2 but no terminate where do the threads goint main auto f0 async fibrec35 35 execit cerr fib35 f0get endlwhen execit is left the futures f1 and f2 are destroyed but their threads should still be running the destructor of fibrec is called of course but where are the threads going the program does not crash so i guess the become joined or maybe detached or are they stopped or canceled i believe that is not trivially done in c11,['c++'] +199993,regexp in preg match function returning browser error the following function breaks with the regexp i have provided in the pattern variable if i change the regexp i am fine so i think that is the problem i am not seeing the problem though and i am not receiving a standard php error even though they are turned onfunction parseapiresultsresultstakes results from getapiresults returns array pattern n resultsarray preg matchpattern results matchesfirefox 6 the connection was resetchrome 14 error 101 neterr connection reset the connection was resetie 8 internet explorer cannot thisplay the webpageupdateapachephp may be crashing heres the apache error log from when i run the scriptsat oct 01 114140 2011 notice parent child process exited with status 255 restarting sat oct 01 114140 2011 notice apache2211 win32 php530 configured resuming normal operations running wamp 20 on windows 7,['php'] +199997,cannot add an intptr and an int i have this lines in c visual studio 2010intptr a new intptr10intptr b a 10and it says operator cannot be applied to operands of type systemintptr and intmsdn says that this operation should work,['c#'] +200009,elementwise vectorvector multiplication in blas is there a means to do elementwise vectorvector multiplication with blas gsl or any other high performance library,['c++'] +200041,libsqlite in simulator and ios compiling i am having some issues when compiling my app to iosi am using sqlite3 and imported asimport sqlite3hwell i only found a file named libsqlite30dylib in my mac and i copied it to my projectwhen i compile it for ios simulator it works just fine however when i try to compile the app for ios device it throws an error apple matcho linker error in every call i do in my implementation to sqlites function such as sqlite3 open etchow can i compile it to ios devicethank you,['ios'] +200045,why are instance variables in java are always private i am newbie to java and i am learning about encapsulation and saw an example where instance variables are declared as private in a class encapsulationhtm i have 2 querieswhy are instance variables private why not publicwhat if instance variables are made public and accessed directly do we see any constraintscan you explain with an example as to what will go wrong in case the instance variables are declared as public in a class in java,['java'] +200070,resetting a stringstream how do i reset the state of a stringstream to what it was when i created itint firstvalue 1int secondvalue 2stdwstringstream s hello firstvaluestdwstring firsttextstrprint the value of firsttext herehow do i reset the stringstream herei would like it behave as if i had created stringstream ss2 and used it belowss bye secondvaluestdwstring secondtextstrprint the value of secondtext here,['c++'] +200071,security between rails and nodejs i have an app that is mostly in rails but also uses nodejs for some realtime features for example chat users log in via rails and get assigned a session etc as usual however whats the best way to authenticate with nodejs as that same user for example i would like to prevent users from impersonating one another but login is done on rails right now and messaging is done on nodejs rails and nodejs both have access to the same databasei am using devise and socketio if that matters,['ruby-on-rails'] +200107,how can i use boto to stream a file out of amazon s3 to rackspace cloudfiles i am copying a file from s3 to cloudfiles and i would like to avoid writing the file to thisk the pythoncloudfiles library has an objectstream call that looks to be what i need but i cannot find an equivalent call in boto i am hoping that i would be able to do something likeshutilcopyfileobjs3objectstreamrsobjectstreamis this possible with boto or i suppose any other s3 library,['python'] +200108,numbersign in javascript wonder if there are any nontrivial ways of finding numbers sign signum functionmay be shorter faster more elegant solutions than the obvious onevar sign number 0 1 number 0 1 0short excerptuse this and youll be safe and fastfunction signx return typeof x number x x 0 1 1 x x 0 nan nanresultsfor now we have these solutions1 obvious and fastfunction signx return x 0 1 x 0 1 0 11 modification from kbec one type cast less more performant shorter fastestfunction signx return x x 0 1 1 0 caution sign0 12 elegant short not so fast slowestfunction signx return x x mathabsx caution signinfinity nan sign0 nanas of infinity is a legal number in js this solution does not seem fully correct3 the art but very slow slowestfunction signx return x 0 x 0 4 using bitshiftfast but signinfinity 0function signx return x 31 x 0 1 0 5 typesafe megafast seems like browsers especially chromes v8 make some magic optimizations and this solution turns out to be much more performant than others even than 11 despite it contains 2 extra operations and logically never cannot be fasterfunction signx return typeof x number x x 0 1 1 x x 0 nan nantoolsjsperf preformance testsfiddle typecast testsimprovements are welcomeofftopic accepted answerandrey tarantsov 100 for the art but sadly it is about 5 times slower than the obvious approachfradaric hamidi somehow the most upvoted answer for the time writing and it is kinda cool but it is definitely not how things should be done imho also it does not correctly handle infinity numbers which are also numbers you knowkbec is an improvement of the obvious solution not that revolutionary but taking all together i consider this approach the best vote for him,['javascript'] +200126,how to create map tiles from openstreetmap offline thisplay it on android what i want is to thisplay a simple offline map using openstreetmap i cannot find in the web the right tools to create map tiles and use it to thisplay a map in android i have downloaded different resources but it seems that i do not have any idea where to start i want to integrate images from openstreetmap using josm but i do not know if i can use it on android can i use mapnik your help will a great thank you,"['java', 'android']" +200134,prevent urls from appearing as links in mail clients i am sending an html mail from my app this mail contains urls is there a way to prevents from mail clients to show these urls as linksfor example tabletbodytrtdtdtrtbodytablewill generate instead i want it to generate a static textany thoughts,['html'] +200149,web config clear what is the use of the clear in the webconfig filei have it under connectionstringsconnectionstrings clear connectionstrings,['asp.net'] +200166,javascript convert string to safe class name for css i am sure this must of been asked before but cannot find any in the search what is the fastest way to ensure all non safe characters are removed from a string allowing it to be used in a css class name,"['javascript', 'jquery']" +200193,how to draw a transparent circle i am trying to draw a transparent circle but it just does not workwhen i am drawing a bitmap it works but a circle does not become transparentheres my code in shortpaint paint new paintpaintsetalpha125canvasdrawbitmapbitmap sourcerect destrect paint this works finecanvasdrawcirclex y radius paint the circle is drawn but not transparent,['android'] +200200,remove past dates and next months dates from the current month is it possible to remove the past dates and next months dates from the fullcalendar so for the current month it should thisplay only current dates and days,['jquery'] +200211,remove all whitespaces from nsstring i have been trying to get rid of the white spaces in an nsstring but none of the methods i have tried worked i have this is a test and i want to get thisisatesti have used whitespacecharacterset which is supposed to eliminate the white spacesnsstring search searchbartext stringbytrimmingcharactersinset nscharacterset whitespacecharactersetbut i kept getting the same string with spaces any ideas,['objective-c'] +200237,how does stdstring allocate memory in gcc with fwholeprogram update the following problem appears to depend on the fwholeprogram optioni have been playing around a bit with memory allocation and i encountered a small mystery in gcc 46 how does stdstring allocate its memory editwhen i compile with fwholeprogramhave this following test programinclude newinclude stringinclude iostreaminclude cstdlibvoid operator newstdsize t n throwstdbad alloc void const p stdmallocn if p null throw stdbad alloc stdcerr new requests and bytes allocated at p n return pvoid operator deletevoid p noexcept stdcerr delete at p n stdfreepint main stdstring s hello worldwhen i use any other dynamic container which uses stdallocatort the allocator uses operator new and so i see the debug messages happily however with stdstring i see nothing at all i am sure that dynamic allocation happens though as i can confirm with valgrind 13 plus string length bytes are allocated i went through several source files and the standard and i am pretty sure that the template is stdbasic stringt stdchar traitst stdallocatort so i am at a loss why i do not see the messages from my replaced allocation functionscan anyone shed any light on this conundrum what do i do to track string allocations also could anyone run this through some other compiler and see if it produces any outputfor example if i add stdmapint int m 0 1 i have output new requests 24 bytes allocated at 0x8d53028 etc,['c++'] +200257,chrome not loading stylesheet seems like google chrome is not thisplaying my site according to the stylesheetwhen the page first load it loads finebut then it changes to raw html format towards the end of the page loadit ends up looking like this you can see web address at the top barclick for full sizei have 2 style sheets one is an alternative that a user can switch between by clicking the lightdark buttons at top right of the site why is this happening i never had a problem beforemy specs mac os x with google chrome 140835186,['css'] +200261,dereferencing typepunned pointer will break strictaliasing rules i have a unsigned char pointer which contains a structurenow i want to do the followingunsigned char buffer24code to fill the buffer with the relevant informationint len ntohsrecord tbufferlenwhere record t structure contains a field called leni am not able to do so and am getting the errorerror request for member alena in something not a structure or unionthen i triedint len ntohsrecord tbufferlenso as to get the operator precedence rightthat gave me the warningdereferencing typepunned pointer will break strictaliasing rulesdthen i declared record t rec nullrec record twhat am i doing wrong here,['c'] +200276,any good example projects for the kiwi testing library offering more complexity than 22 i am looking for a good example projecttutorial that show the kiwi testing framework in action i do not need any more examples of testing classes with the only purpose of adding 2 numbers together or something mundane like that there are plenty of those examples already i am particularly interested in strategies for testing uiviewcontroller subclasses and classes that are in charge of data fetching what are the strategies that exist for testing against a web service is it to stub out the return methods from the fetch calls,"['ios', 'objective-c']" +200277,backbone events not firing i know other posts have been made regarding this but so far the answers i have seen have not been helpful and slightly different from my situationwindowbotview backboneviewextend initialize bindall alert render el by calling this here it initializes the jquery object el submit model chatbot events click submit alert alert consolelogalert called alertevent observed render alertrenderedjquery windowapp new botview consolelog appelall i want is when i click on the submit button with the id of submit for it to fire the alert function however i cannot even get this to workwhat is going on with the events that my simple click handler on submit is not workingi have double checked that my el is properly initialized but even so it should not matter because the click handler is not using elcould anyone shed some light on why this simple event is not firingthanks in advance,['javascript'] +200279,jquery datatables slow initiation normal html table shown in the beginning i am using jquery datatable plugin but i got a concern where the scripts loading seems to take some time so my web page is always thisplaying the ordinary html table first and after all script done the table will then become datatablei do not think this kind of appearance is acceptable so i hope can get some advices here whether i can make the scripts faster or do not thisplay the plain table aheadbtw i am calling my script from a scripts partial view at my layoutcshtml head tag htmlpartial scripts updatei tried to hide the table and show it after the datatable initialize however i get a datatable without the table header any idea why this is happeningstocktablehide initialize data table var mytable stocktabledatatable try styling sscrollx 100 sscrollxinner 100 bscrollcollapse true to use themeroller theme bjqueryui true to use tabletool plugin sdom tclearlfrtip allow single row to be selected otabletools srowselect single fninitcomplete function stocktableshow,['jquery'] +200344,asynchronous adonet i am trying to write an asynchronous server that queries a sql server database and am concerned that my db side is too synchronous specifically i can call executereader asynchronously but cannot then call readeritem asynchronously and is where 57 of the time is spent blocking my precious threadis this the most asynchronous i can do with adonet or is there an asynchronous way to do readeritem as well,['c#'] +200356,typedelegator equality inconsistency consider the following code class mytype typedelegator public mytypetype parent baseparent class program static void mainstring args type t1 typeofstring type t2 new mytypetypeofstring consolewritelineequalitycomparertypedefaultequalst1 t2 false consolewritelineequalitycomparertypedefaultequalst2 t1 true consolewritelinet1equalst2 true consolewritelinet2equalst1 true consolewritelineobjectequalst1 t2 false consolewritelineobjectequalst2 t1 true how come the various versions of equals return different results the equalitycomparerdefault probably calls objectequals so these results match although inconsistent in themselves and the normal instance version of equals both return true this obviously creates problems when having a method return a type that actually inherits from typedelegator imagine for example placing these types as keys in a dictionary which by default use the equalitycomparerdefault for comparisons is there any way to resolve this problem i would like all the methods in the code above return true,"['c#', '.net']" +200377,how to remove the title in dialog i created an activity as a dialog using the code below which i put in my manifest but the problem is it has title bar how can i remove itandroidthemeandroidstylethemedialog,['android'] +200400,how to deminify javascript possible duplicateonline tool to unminify decompress javascripttool to reverse javascript minify is there a way to convert minified javascript code into normal,['javascript'] +200401,combining consecutive dates in ilist into ranges i have a series of objects with from and to datesusing something likeilistdatetime dates thisdateranges selectmanyr new rfrom rto thistinct orderbyd d tolisti can get all dates without any of them being duplicated ranges may fully overlap partially overlap upper or lower overlapping touch or they may not overlap at allnow i need to convert this list to a different one so that each consecutive date pair forms a new generated datetime instance right in the middle of paird1 d2 d3 d4 d5 g1 g2 g3 g4where dn are my thistinct dates from the list and gm dates are ones i would like to generate in the middle of themquestionhow do i convert an ordered list of individual dates to pairs so that i get pairs as shown in the following example i would like to form these using linq instead of for loop which can accomplish the same thing using linq may result in and more efficient code due to delayed expression tree executionadditional explanation using a realworld examplesuppose this is my example of such rangesd1 d2 d3 d4 d5 d6 d11 d12 d7 d8 d9 d10first step of getting thistinct dates would result in these datesd1 d7 d2 d3 d4 d5 d6 d10 d11 d12d9 and d8 would fall off because they are duplicatesnext step is to form pairs i do not know how to do this using linqd1d7 d7d2 d2d3 d3d4 d4d5 d5d6 d6d10 d10d11 d11d12last step has to calculate a date for each pair usingdnew dfrom dto dfrom2empty ranges issuerange d10d11 should preferably be omitted but if omitting it results in overcomplicates code it can be kept and excluded with a separate check afterwards but if it can be excluded initially then that is what should be done so if you also provide information of how to form pairs that exclude empty ranges youre welcome to add that info as well,['c#'] +200404,php abstract properties is there any way to define abstract class properties in phpabstract class foo abstract abstract public tablenameclass foo extends foo abstract foo must implement property public tablename users,['php'] +200422,how can i check if a generic method parameter is a value type is there a way to check if a variable is value type of reference typeimagineprivate object getsomethingtparams t values foreach var value in values bool is valuetype check if value is a value type or reference type,"['c#', '.net']" +200438,c interview vtable for a class with a pure virtual function i was asked this interview question today it was a really awkward telephonic interviewwhat is the difference between the vtable for a class with virtual functions and a class with pure virtual functionsnow i know the c standard does not specify anything about vtables or even the existence of a vtable however theoretically speaking what would the answer be i blurted out that the class with a pure virtual function could have a vtable and its vtable entry for the pure virtual function will point to the derived class implementation is this assumption correct i did not get a positive answer from the interviewerwill a hypothetical compiler create a vtable for a class with only pure virtual functions what if the class contains pure virtual functions with definitions as shown in,['c++'] +200465,tablet not appearing in adb i have just got a lenovo thinkpad slate tablet running android and cannot for the life of me get adb to recognise it in either win7 or kubuntuusb debugging is on in the tablet settings and when i connect the tablet to the computer the usb debugging connected message appears so all good from the tablet side of things the computer side of things is not so greatkubuntu my main dev machinei have added the vendor id to the etcudevrulesd51androidrules file as directed here have tried each of the below one at a time with no succesubsystemusb sysfsidvendor17ef mode06subsystemusb attridvendor17ef mode06 groupplugdevsubsystemusb attridvendor17ef mode06subsystemusb attridvendor17ef mode06for reference i have subsystemusb attridvendor18d1 mode06 groupplugdevfor my nexus s and it works finelsusb prints outrootubuntuetcudevrulesd lsusbbus 002 device 008 id 17ef741b lenovo windows have followed these instructions and still not getting any response from adb devicesi have restarted both machines and the tablet several times to no avail can anyone help,['android'] +200469,getting activepython to work with wsh i have installed activepython 272 and i am trying to execute a pys script via the console with wscriptcscript ie activepython pythonscript with pys extension in microsofts wshwindows scripting host and when trying with wscript i get two errors the program cannot start because msvcr90dll is missing from your computer try reinstalling the program to fix this problemcannot find script engine python for script i did some googling and have also downloaded and installed the microsoft visual c rethistributable package x86 from here to no availi have tried pythonw cpython27libsitepackageswin32comextaxscriptclientpyscriptpy to register pythonany help would be greatly appreciatedi am running on win7 x86,['python'] +200471,get command prompt output to string in java i need a java method that will read command prompt output and store it into a string to be read into javathis is what i have so far but is not working rightpublic void testgetoutput systemoutprintlnthis is the testgetoutput method string s null string query dir thisdesktop try runtime runtime runtimegetruntime inputstream input runtimeexeccmd c querygetinputstream bufferedinputstream buffer new bufferedinputstreaminput bufferedreader commandresult new bufferedreadernew inputstreamreaderbuffer string line try while line commandresultreadline null s line n catch exception e eprintstacktrace systemoutprintlns catch exception e eprintstacktrace end testgetoutputi think the problem is when i try to change the query to be a command which will execute handbrakecliexe looking at my system when the program is running but seems to have paused it shows me that handbrakecliexe is running under a cmd window which is being run under my ide all that makes sense but the handbrakecliexe does not exit so i am guessing that is why i cannot read the output as input to my programso after that background my big question is this how do i get handbrakecliexe to close after it is finished with my query so i can get its outputjust for extra info the only difference between the method above and the scan dvd method i have for handbrakecli is the query variable is different like this examplestring query cuserskentdesktophbclihandbrakecli t scan i cuserskentdesktopgeneral conference dvdssources174th october 2004dvd 1 this is actually a variable in the dvd object but heres an exampleoh and by the way when i run that query in a regular command prompt it does exactly what i want it to giving me all the output i desperately desireheres the original problem i am not sure how to resubmit a questioni have been looking everywhere and cannot figure this out i am not sure what i have found is even relevant to what i want to do i do not have a whole lot of code for it yet so it wont do much to put code here and i think this should be pretty simple so i am going to give some screenshots here so heres my taskscan folder which is full of ripped dvd folders video ts folders with vob files etc and store these folder names as the title of the dvdscan each folder using the handbrakecli and store the output to a stringregex the string to identify each title chapter and languagegenerate queries to give back to handbrakecli to bulk encode each language in each chapter in each title for each dvd you can see why i want to automate thisstore these queries in a bat filethe only part i am not sure about is step 2 i can do everything else pretty easily i have read a lot about outputstreams but i just cannot seem to understand how it works i really just need to get the output to a string which i can regex to get the stuff i need here are the screenshots of what i need to input and what i need to strip from the outputinput to handbrakeclioutput to scan,['java'] +200488,in extjs how to add a custom css class to data grid rows how do i add custom css classes to rows in a data grid extgridpaneli am using extjs 40,['javascript'] +200501,load data local infile forbidden in php i am trying to use load data infile to insert some records into a table unfortunately it is not workinghere are some detailsif i use this instructionload data infile filetxtinto table table exfields terminated by lines terminated by nfield1 field2 field3 field4it works using the mysql client program and a php application in this way it will look for the file in the data directory of my mysql installationnow if i try to execute the instructions using the local option it only works if i use the mysql client but not from phpload data local infile pathtofilefiletxtinto table table exfields terminated by lines terminated by nfield1 field2 field3 field4again it works with mysql client but not from the php application i get this errorload data local infile forbidden in pathtomyapplicationi read that the problem is related to the compilation of php and using mysqlnd i am using php 538 and mysql 5515 but i have not found a solutionadditional information until now the only help i have found was an open php bug,"['php', 'mysql']" +200532,redirect after sign in with devise is it possible to redirect users to different pages based on role after signing in with devise it only seems to redirect to the root to page defined in routesrbthanks,['ruby-on-rails'] +200535,indent wrapped text so i am simulating a table layout with a div and a couple spans inside it i would like the span on the right to indent any text that wraps i have tried a few things and cannot get it to work any help would be appreciatedjsfiddle htmldiv classthisplayelement span classthisplaylabelfield 1span span classthisplayfieldthis is my string of data some times it is pretty long sometimes it is not this one isspandivdiv classthisplayelement span classthisplaylabelfield 2span span classthisplayfieldthis is another string of dataspandivcssthisplayelement thisplaylabel thisplay inlineblock width 100px paddingleft 5pxthisplayfield thisplay inline,['css'] +200544,how to create a link inside a cell using epplus i am trying to figure out how to write a hyperlink inside a cell using epplus instead of the cell containing the link text i need it to be recognized as a link and be clickableany help is appreciated,['c#'] +200556,inducing activitymanager to no longer want for testing i am trying to test how my application handles getting destroyed by the android activitymanager and later restarted by alarm eventsin other words i want to force the messageiactivitymanager 3 no longer want commynamemyapp pid 4 hidden 22is there a way to reliably induce the activitymanager to no longer want my applicationa few tricks i know for ending processes however the purpose of this question is to find something to induce the activitymanager method of no longer wantusing manage applications touch the button force stop the problem with this is it does not always seem to behave quite the same as the activitymanager no longer want methodrun many memory hogging applications the problem with this is it is unreliable and timeconsuming sometimes i can run lots of applications and i do not see a peep from activitymanageros api killbackgroundprocesses the problem with this is it was not clear if calling killbackgroundprocesses explicitly would behave exactly the same as the activitymanager no longer want method,['android'] +200562,jquery flot bar chart multiple series in order to make things easy to undertand i am providing the code what we have here is a data set like this look the source for more label scott data 131742720 17017 131751360 77260where the first value is a date in utc format and second should be scorenow what i am trying to do is to have for each date in the y axis the bars representing the score side by side like below 3 2 1 0 1 oct 2 oct 3 octinstead now as you can see the bars are staked each one over the otherany help would be really appreaciated thanks,['jquery'] +200582,file default icon in wpf possible duplicatehow do i thisplay a windows file icon in wpf i am building email client using wpf i thisplay first the mail content with list of the attachments of the mail i need a way to thisplay thumbnail of the file so user can see what is the file about for example if it is an image then user can see the thumbnail like windows explorer if its word then word default icon in summary to thisplay the list like windows explorer with the thumbnails any ideas,"['c#', '.net']" +200596,webapp2 for authentication and login i would like to roll my own login system for my python google app engine application rather than using googles users apii am using webapp2 and i noticed that there is a webapp2 extrasauth module and an incomplete auth tutorialdoes anyone know how i can use this api to createuser registration take an email and password and perhaps verify emailuser login with email and passwordonce i have the email and password where do i store it in the authstoreand how do i authenticate against the authstore,['python'] +200597,center text in table cell i cannot seem to find the answer to my issue i have a table with two rows and two columns like the code shown below how do i center align the text in specific cells i would like to center align the text in one or two of the cells not all the cells many thanksdiv styletextalign center table stylemargin 0px auto border0 tbody tr tdcell 1td tdcell 2td tr tr tdcell 3td tdcell 4td tr tbody tablediv,['html'] +200655,which java based workflow engine should i use i am looking for a off the shelf workflow engine to be used in my java based web application following are my initial requirements the engine should have a nice ui to createmanage workflowsshould work with oracle databaseprovides java api or web service api to interact with workflow from my application so that i can build logic on the workflowability to define custom business rulesas of now i am looking at jboss jbpm and drools together do let me know if you have experience of this or other contenders which i should consider for evaluation,['java'] +200692,how to show and edit existing pdf files in ios application i do not want to create new pdf filethat i had already done but want to show and edit existing pdf file in ios through codeis this possible or not and if possible than how can i do thisupdatesuppose there will be text document pdf and we want to enter some other text in that file and save itso how to do this by programming please help me to solve this problemthanks in advance,"['iphone', 'objective-c', 'ios']" +200711,c convert one enum to an other i have 2 enumspublic enum persontitle mr0ms1mrs2public enum systempersontitles mr0ms1mrs2how do i convert one to an other no switch cases or if statementspublic void systempersontitles tellwhatyouarepersontitle persontitlehereusagesystempersontitles systempersontitles tellwhatyouarepersontitlems,['c#'] +200743,listview with onitemclicklistener android i am using a custom listview with ratingbar and imagebutton here is my problem when i click on my listview my onitemclicklistener is not working please can any one help mecodelistview lv getlistviewsetcontentviewlvlvsetonitemclicklistenernew onitemclicklistener override public void onitemclickadapterview arg0 view arg1int position long arg3 toastmaketextsuggestionactivitythis position toastlength shortshow thanks in advance,['android'] +200755,how to use wickets downloadlink with a file generated on the fly downloadlink is nice and handy for creating a buttonlink for downloading a file along these linesaddnew downloadlinkdownloadbutton getreportfile reportpdfandinput typebutton wicketiddownloadbutton valuedownload however i would like to trigger the generation of the file to download only when the buttonlink is clicked in other words upon click i would call a method that generates the file a pentaho report in our case puts it in a temp place and returns a file pointing to it then i would tell the downloadlink to use that file question is is this possible somehow currently we have something like the code below which works but i am interested in whether downloadlink could be used insteadaddnew linkvoiddownloadbutton override public void onclick iresourcestream resourcestream new abstractresourcestreamwriter override public void writeoutputstream output try reportservicegeneratereportoutput report catch ioexception e override public string getcontenttype return content type pdf getrequestcycle setrequesttargetnew resourcestreamrequesttargetresourcestream setfilenamereportpdf wicket 1418 if it makes a difference,['java'] +200765,is this an appropriate use of pythons builtin hash function i need to compare large chunks of data for equality and i need to compare many per second fast every object is guaranteed to be the same size and it is possiblelikely they may only be slightly different in unknown positions i have seen from the interactive session below using operator for byte strings can be slower if the differences are towards the end of the string and it can be very fast if there is a difference near the start i thought there might be some way to speed things up using some sort of hash of course computing the md5 hash and comparing is a fair whack slower but pythons inbuilt hash does seem to speed things up significantly however i have no idea about the implementation details of this hash is it really hashlike in that i can be comfortable that when hasha hashb then a b is very likely i am happy to have a few incorrect results if a hash collision is reasonably rare rare in the sense of needing an array of 200 ps3s several hours to make a collisionin 1 import hashlibin 2 with opendevurandom as f spam fread220 1 in 3 spama spam ain 4 aspam a spamin 5 spamb spam bin 6 timeit spama spamb10 loops best of 3 159 ms per loopin 7 timeit spama aspam10 loops best of 3 664 ns per loopin 8 timeit hashlibmd5spama hashlibmd5spamb100 loops best of 3 442 ms per loopin 9 timeit hashlibmd5spama hashlibmd5aspam100 loops best of 3 439 ms per loopin 10 timeit hashspama hashspamb10 loops best of 3 157 ns per loopin 11 timeit hashspama hashaspam10 loops best of 3 160 ns per loop,['python'] +200770,jquery autocomplete working with older versions of the browsers but not new ones here is the json data for my auto complete list genericindicatorid 100 isactive false maxvalue null minvalue null modificationdate 12839040 monotone 1 nameabbau old name abbau change delete imac position 2 systemgraphics 0 unitid 1 valuetype 1 description abbau weight 1and the code which i wrote is portletnamespace ginameautocomplete source enter code here function request response post ajaxgetgis constantsindicator name requestterm constantsservice id serviceid function data response map datalist function item alertitemname itemgenericindicatorid itemvalue itemname return item json minlength 2i am using jqueryui1814autocompleteminjs plugin for auto completethe problem i am getting is it is not showing all the matched results in new browsersfor example if i type an in which should matches to the anzahl keyword the fire bug is showing error like bad control character literal in a string results are showing for the letters assa any help would be appriciatedthank you,"['php', 'javascript', 'jquery']" +200793,how to secure intent data while sending it across applications i am working on the security aspects of my android applicationi would like to know about the ways to secure the intent data and extras while sending it from one application to another so that no other application other than these two can snoop itone of the bruteforce approaches would be to use androids encryptiondecryption to encode intent data is there a better way to achieve the same thanks in advance,['android'] +200794,how i can set gap in vertical boxsizer how can i set gap in vertical boxsizer whats in the vertival boxsizer the similar or alternative method of setvgap which sets the vertical gap in pixels between the cells in the sizer in gridsizer,['python'] +200804,pip install pil e tickets1 no jpegpng support i am using ubuntu and vitualenv for my django projecti have pil library installed using synaptic package manager and it is working fine but when i create an vitrualenv and try to install pil using pip it installes but i get this strange behaviourpil 117 setup summaryversion 117platform linux2 271 r27186832 apr 11 2011 181353 gcc 452 tkinter support not available jpeg support not available zlib pngzip support not available freetype2 support not available littlecms support not availableto add a missing option make sure you have the requiredlibrary and set the corresponding root variable in thesetuppy scripti was hoping that i can use requirementstxt for all my dependencies but may be pil have to be somehow manually installed but howedit thank you john keyes you are right i runsudo ln s usrlibx86 64linuxgnulibfreetypeso usrlibsudo ln s usrlibx86 64linuxgnulibzso usrlibsudo ln s usrlibx86 64linuxgnulibjpegso usrliband after another try for pil install i getpil 117 setup summaryversion 117platform linux2 271 r27186832 apr 11 2011 181353 gcc 452 tkinter support not available jpeg support available zlib pngzip support available freetype2 support available littlecms support not available to add a missing option make sure you have the requiredlibrary and set the corresponding root variable in thesetuppy scriptedit you may need to install libfreetype6dev libjpeg8devedit another good option is to use pillow instead of pil,['python'] +200824,consequences of drawablesetcallbacknull while trying to implement small inmemory cache of drawables i learned that to avoid memory leaks after closing activity i need to unbind those drawables set their callback to nullbecause maintaining drawables cached in each activity would require extra code i tried to unbind them immediately after setimagedrawabledrawable and i do not see any consequences so farthis is code from myimageview class extends imageviewsetimagedrawabledrawabledsetcallbacknullin debugger i can clearly see that before first line callback is null after first line it is set to this imageview and after that i set it to null again it is normally shown after thatdocumentation for setcallback drawablecallback cb statesbind a drawablecallback object to this drawable required for clients that want to support animated drawablessince i do not need animated drawable i do not see why i should not do this but it bothers me that in several blogs about memory leakage in android concerning drawables this is done only after activity is done question is why is callback always automatically set when binding to imagevieware there some border conditions where those drawables with callback set to null will cause a problem not thisplaying or npe,['android'] +200830,why c does not support basebase i tested code like thisclass a public a public virtual void test consolewritelinei am a class b a public b public override void test consolewritelinei am b basetest class c b public c public override void test consolewritelinei am c basebasetest i want to thisplay here i am a and tried to call from c method test of a class grandparents method but it does not work please tell me a way to call a grandparent virtual method,"['c#', '.net']" +200861,how to test json login in devise with rspec i am trying to build a rails login process with devise that will allow the user to signinsignout through a mobile applicationi created a sessionscontroller like that class sessionscontroller devisesessionscontroller def create resource wardenauthenticatescope resource name recall controller pathnew set flash messagenotice signed in if is navigational format sign inresource name resource respond to do format formathtml super formatjson render status 200 json error success user resourceto json end end def destroy super endendmy routes devise for users controllers sessions sessionsresources usersthen i have the following spec to test the process require spec helperdescribe sessionscontroller do describe post signin do before each do user factoryuser end it should login with json request do expected userto json post create user email password please content type applicationjson format json responsebodyshould expected end endendand i get the following error failureerror post create user email password please content type applicationjson format json abstractcontrolleractionnotfound could not find devise mapping for path userssign injsoncontent typeapplication2fjsonuser5bemail5duser40testcomuser5bpassword5dplease maybe you forgot to wrap your route inside the scope blockeditit seems like the functionality is ok but only the test is broken because if i run this small script require rest clientrequire active supportcore extrestclientpost httplocalhost30userssign in user email password pleaseto json content type json accept jsoni get the following result errorsuccessuseremailnamefirst userwhich is the expected one,['ruby-on-rails'] +200883,pop to root view when tab is selected i have been having some trouble with something i thought might be easy i have a table in my root view controller when a row is selected i push a new view and from there i go to another tab my question is how do i make sure that as soon as the user taps the first tab the navigation controller will pop to root,"['iphone', 'ios']" +200891,putting the current thread to sleep i have a unit of work i am doing in a thread not the main thread under certain circumstances i would like to put this thread to sleep for 10 seconds is threadsleep10 the most resource efficient way to do this,['c#'] +200930,docstring tag for yield keyword there are some tags for docstrings in python like param and return for exampledef my methoda param param a param description of this param return the return value of the method return inta param other or 1what can i use for documenting generators specially the yield keyword likedef my generatorfrom0 param from the initial value yield a lot of values yield a valuei understand that return an iterator can be used here but i do not know if it is correct because a generator can return values alsothanks,['python'] +200948,import sqlite3 with python27 on heroku i am trying heroku with python i ran the hello word example with flask successfullyi now want to deploy a very basic application using sqlite3 and flask and i know the application was working but i have trouble getting it to work and i suspect the problem is with sqlitewhen i started the python shell that heroku provides here the import error log heroku run python running python attached to terminal up run2python 271 r27186832 jun 26 2011 010811 gcc 443 on linux2type help copyright credits or license for more information import sqlite3traceback most recent call last file stdin line 1 in module file usrlocallibpython27sqlite3 init py line 24 in module from dbapi2 import file usrlocallibpython27sqlite3dbapi2py line 27 in module from sqlite3 import importerror no module named sqlite3do i need to add something to the requirementstxt the file used for dependencies it only contains flask08 so far import datetime in examples works as expected i looked with heroku logs and this message appears as well without any other important messagesdo i have any way to use some sqlite3 on herokuthanks for help,['python'] +200971,android are logcat calls visible to end users if phone is in debug mode i have been using logwhatever calls to log various bits of information as i have been developing my android app as i prepare to publish my app to the android marketplace i am trying to figure out what i need to removeaccording to the android developer dev guide before publishing they suggestdeactivate any calls to log methods in the source codehow does one deactivate the log methods obviously i could go through and erase them all which is a bit of a pain but is there some other way to deactivate log calls that i am unaware ofalso what danger is there to having log calls in a published application can anyone install eclipse plugin in their phone and enable debug mode and see all the same logcat information that i see as i am developingalso the dev guide suggestsremove the androiddebuggabletrue attribute from the application element of the manifesti was unaware of this flag until now what does it do exactly i have been developing and debugging my app just fine up to this point and this flag is not set to true or false for in my manifest,['android'] +200999,creating a graph or a plot from a c console app using matlab if i have a two dimensional array in c how would i plot the contents of this array in matlab as a 2d graph i am after an extension method iemy2darrayplotinmatlab,"['c#', '.net']" +201006,how do you make an anchor link nonclickable or thisabled i have an anchor link that i want to thisable once the user clicks on it or remove the anchor tag from around the text but definitely keep the texta href idthislinksome textai can do this easily with a button by adding attrthisabled thisabledi successfully added the thisabled property but the link was still clickablei do not really care if the text is underlined or not any clueyou can try it here when you click on the wrong musician it should just add wrong and then become unclickablewhen you click and you are correct it should add awesome and then thisable all a tags,['jquery'] +201016,contentnotrenderederror after a django upgrade heres a middleware that i useclass statsmiddlewareobject def process viewself request view func view args view kwargs get number of db queries before we do anything and lenconnectionqueries time the view start timetime response view funcrequest view args view kwargs tottime timetime start compute the db time for the queries just run queries lenconnectionqueries n if queries dbtime reduceadd floatqtime for q in connectionqueriesn else dbtime 00 and backout python time pytime tottime dbtime stats tottime tottime pytime pytime dbtime dbtime queries queries sql br join div clastats sql querysdivdiv clastats sql times sdiv qsql qtime for q in connectionqueriesn clean query cache dbreset queries replace the comment if found if response and responsecontent s responsecontent regexp recompilerpcmtsstatspfmt match regexpsearchs if match s smatchstartcmt matchgroupfmt stats smatchendcmt responsecontent s return responseit has been working perfectly for me up to django 13 but this broke when i upgraded to django trunk 14 today with the exceptiontracebackfile djangotrunkdjangocorehandlersbasepy in get response 105 response middleware methodrequest callback callback args callback kwargsfile miscmiddlewarepy in process view 63 if response and responsecontentfile djangotrunkdjangotemplateresponsepy in get content 123 raise contentnotrenderederrorthe response content must be exception type contentnotrenderederror at exception value the response content must be rendered before it can be accessedwould appreciate it if some one using django trunk points me in the right direction thanks,['python'] +201049,how do i check whether an object is an arguments object in javascript i am in es5 strict mode so the solutionfunction isargumentsitem return itemcallee undefinedunfortunately does not work,['javascript'] +201073,how to get the ast of a regular expression string how can i get the abstract syntax tree ast of a regular expression in c for example xyz123should yield a tree of z 3 x y 1 2is there a boostspirit grammar to parse regular expression patterns the boostregex library should have it but i did not find it are there any other opensource tools available that would give me the abstract representation of a regex,['c++'] +201076,highlight search resuls with string part i am using the code below to highlight the search resultstext preg replacebwordbi span classhighlight word1span textand its working finebut the preg replace return the whole string and highlight the words that matchi need to get a part of the string and only the whole stringa scenario is to get 100 chars before and 100 chars after the first match any help will be appreciated,['php'] +201086,what are the differences between typedef and using what are the differences between usingtypedef somenestednamespacetypename typenameorusing somenestednamespacetypenameto provide the shorthand typename in the local scope,['c++'] +201093,arrays initialization body as function parameter carray is it possible i am searching for some help in next situationi have some class and some method in it syntax is like this class someclass public void dosomethingint a so i want to call this method like someclassdosomething 0 1 2 3 4 is it possible in any languageany c c objc objc implementation is welcome i know that this initialization block is a body of array likeint a 0 1 2 3 4 someclassdosomethingabut interface will look great i think if there will be no temp variables before function calls as we do not need to know the type of parameter in classclient so is there any chance to make this,['c++'] +201094,how can i elide a call if an edge condition is known at compile time i have the following situation there is a huge set of templates like stdvector that will call memmove to move parts of array sometimes they will want to move parts of length zero for example if the array tail is removed like stdvectorerase they will want to move the remainder of the array which will happen to have length zero and that zero will be known at compile time i saw the thisassembly the compiler is aware yet the compiler will still emit a memmove callso basically i could have a wrapperinline void callmemmove void dest const void source size t count if count 0 memmove dest source count but this would introduce an extra runtime check in cases count is not known in compile time that i do not wantis it somehow possible to use assume hint to indicate to the compiler that if it knows for sure that count is zero it should eliminate the memmove,['c++'] +201112,understanding the reference handler thread i am continuing my path to deep understanding of java thread unfortunately my java certification did not cover that part so the only way of learning is to post a series of dumb questions with so many years of java development i am sometimes wondering how much i still have to learn in particular my attention is now with the reference handler threadreference handler daemon prio10 tid0x02da3400 nid0xb98 in objectwait 0x0302f0 javalangthreadstate waiting on object monitor at javalangobjectwaitnative method waiting on 0x1aac0320 a javalangrefreferencelock at javalangobjectwaitobjectjava485 at javalangrefreferencereferencehandlerrununknown source locked 0x1aac0320 a javalangrefreferencelocknow some questions are following for some of them i know the answer but i am not posting it because i would like to hear someone else opinionswhat is the reference handler thread supposed to do a thread dump should be considered bottom up why does the stack trace start with locked should not the lock statement appears at least after the thread has run what does native method means why unknown source in which case the thread dump cannot recall the source code lastly the waiting on and locked has the same why as usual i kindly ask to answer all the questions so that i can mark answered,['java'] +201120,twoline text button in compact framework i want to create a twoline text button in compact framework i have used every idea in this thread but without successif i use n or rn or environmentnewline i get squaresi am using compact framework 35any idea on how to make a twoline text box,['c#'] +201124,how to get only the file name without the file path i have this codeopenfiledialog1filter csv files dbfdbfopenfiledialog1filterindex 1openfiledialog1restoredirectory trueopenfiledialog1filename if openfiledialog1showdialog dialogresultok dbf file openfiledialog1filenamein dbf file i get all the file path and name cmydirmyfiledbfi need only the name myfiledbf,['c#'] +201132,how to add assemblyreferences on a perconfigurationbasis i am currently looking to add some debug only code to a windows phone project this debug code will drag in some debug class library references nunit helpers and some wcf service client references and i would really like to not have these referenced in the release buildcan anyone suggest any way that i can add an assemblyreference to debug but not have it appear in releasei have seen this on connect but it is marked as postponed,"['c#', '.net']" +201136,android oneditoractionlistener actionid give 0 when i click done key i have created one keyboardwhen user enter numbers its entering particular edittextbut when user click on done key it did not go to setoneditoractionlistener but its closing the keyboardthis is my code final edittext txtqty new edittextthis txtqtysetheight1 txtqtysetlayoutparamsnew layoutparamslayoutparamswrap content 42 txtqtysetinputtypeinputtypetype class phone txtqtysetimeoptionseditorinfoime action done txtqtysetselectallonfocustrue txtqtysettextsize9 txtqtysetvisibilityviewvisible txtqtysethint00 txtqtysethighlightcolorrcolorgreen traddviewtxtqty txtqtysetoneditoractionlistener new oneditoractionlistener public boolean oneditoractiontextview v int actionid keyevent event logikeyboard inside the edit text if actionid editorinfoime action done actionid editorinfoime action next here its give actionid 0and editorinfoime action next 5when i run through the android softkeyboard its working fine txtqtysetoneditoractionlistener new oneditoractionlistener public boolean oneditoractiontextview v int actionid keyevent event logikeyboard inside the edit text logieditorinfoime action next editorinfoime action next logiactionid actionid logievent event logieditorinfoime action done editorinfoime action donehere giving editorinfoime action next 5 actionid 5 editorinfoime action done 6 actionid6but when i run through my soft keyboard gave editorinfoime action next 5 actionid 0 editorinfoime action done 6 actionid0this is the problemwhere its wrong why it did not take actionid valuethis is kind of scenario i am doingeditedupdated public class softkeyboard extends inputmethodservice implements keyboardviewonkeyboardactionlistener static final boolean debug false static final boolean process hard keys true private keyboardview minputview private candidateview mcandidateview private completioninfo mcompletions private stringbuilder mcomposing new stringbuilder private boolean mpredictionon private boolean mcompletionon private int mlastthisplaywidth private boolean mcapslock private long mlastshifttime private long mmetastate private latinkeyboard msymbolskeyboard private latinkeyboard msymbolsshiftedkeyboard private latinkeyboard mqwertykeyboard private latinkeyboard mcurkeyboard private string mwordseparators override public void oncreate superoncreate mwordseparators getresourcesgetstringrstringword separators override public void oninitializeinterface if mqwertykeyboard null int thisplaywidth getmaxwidth if thisplaywidth mlastthisplaywidth return mlastthisplaywidth thisplaywidth mqwertykeyboard new latinkeyboardthis rxmlqwerty msymbolskeyboard new latinkeyboardthis rxmlsymbols msymbolsshiftedkeyboard new latinkeyboardthis rxmlsymbols shift override public view oncreateinputview minputview keyboardview getlayoutinflaterinflate rlayoutinput null minputviewsetonkeyboardactionlistenerthis minputviewsetkeyboardmqwertykeyboard return minputview override public view oncreatecandidatesview mcandidateview new candidateviewthis mcandidateviewsetservicethis return mcandidateview override public void onstartinputeditorinfo attribute boolean restarting superonstartinputattribute restarting mcomposingsetlength0 updatecandidates if restarting mmetastate 0 mpredictionon false mcompletionon false mcompletions null switch attributeinputtypeeditorinfotype mask class case editorinfotype class number case editorinfotype class datetime mcurkeyboard msymbolskeyboard break case editorinfotype class phone mcurkeyboard msymbolskeyboard break case editorinfotype class text mcurkeyboard mqwertykeyboard mpredictionon true int variation attributeinputtype editorinfotype mask variation if variation editorinfotype text variation password variation editorinfotype text variation visible password mpredictionon false if variation editorinfotype text variation email address variation editorinfotype text variation uri variation editorinfotype text variation filter mpredictionon false if attributeinputtypeeditorinfotype text flag auto complete 0 mpredictionon false mcompletionon isfullscreenmode updateshiftkeystateattribute break default mcurkeyboard mqwertykeyboard updateshiftkeystateattribute mcurkeyboardsetimeoptionsgetresources attributeimeoptions override public void onfinishinput superonfinishinput clear current composing text and candidates mcomposingsetlength0 updatecandidates setcandidatesviewshownfalse mcurkeyboard mqwertykeyboard if minputview null minputviewclosing override public void onstartinputvieweditorinfo attribute boolean restarting superonstartinputviewattribute restarting minputviewsetkeyboardmcurkeyboard minputviewclosing override public void onupdateselectionint oldselstart int oldselend int newselstart int newselend int candidatesstart int candidatesend superonupdateselectionoldselstart oldselend newselstart newselend candidatesstart candidatesend if mcomposinglength 0 newselstart candidatesend newselend candidatesend mcomposingsetlength0 updatecandidates inputconnection ic getcurrentinputconnection if ic null icfinishcomposingtext override public void onthisplaycompletionscompletioninfo completions if mcompletionon mcompletions completions if completions null setsuggestionsnull false false return liststring stringlist new arrayliststring for int i0 icompletions null completionslength 0 i completioninfo ci completionsi if ci null stringlistaddcigettexttostring setsuggestionsstringlist true true private boolean translatekeydownint keycode keyevent event mmetastate metakeykeylistenerhandlekeydownmmetastate keycode event int c eventgetunicodecharmetakeykeylistenergetmetastatemmetastate mmetastate metakeykeylisteneradjustmetaafterkeypressmmetastate inputconnection ic getcurrentinputconnection if c 0 ic null return false boolean dead false if c keycharactermapcombining accent 0 dead true c c keycharactermapcombining accent mask if mcomposinglength 0 char accent mcomposingcharatmcomposinglength 1 int composed keyeventgetdeadcharaccent c if composed 0 c composed mcomposingsetlengthmcomposinglength1 onkeyc null return true override public boolean onkeydownint keycode keyevent event switch keycode case keyeventkeycode back if eventgetrepeatcount 0 minputview null if minputviewhandleback return true break case keyeventkeycode del if mcomposinglength 0 onkeykeyboardkeycode delete null return true break case keyeventkeycode enter return false default if process hard keys if keycode keyeventkeycode space eventgetmetastatekeyeventmeta alt on 0 inputconnection ic getcurrentinputconnection if ic null icclearmetakeystateskeyeventmeta alt on keydownupkeyeventkeycode a keydownupkeyeventkeycode n keydownupkeyeventkeycode d keydownupkeyeventkeycode r keydownupkeyeventkeycode o keydownupkeyeventkeycode i keydownupkeyeventkeycode d return true if mpredictionon translatekeydownkeycode event return true return superonkeydownkeycode event override public boolean onkeyupint keycode keyevent event if process hard keys if mpredictionon mmetastate metakeykeylistenerhandlekeyupmmetastate keycode event return superonkeyupkeycode event private void committypedinputconnection inputconnection if mcomposinglength 0 inputconnectioncommittextmcomposing mcomposinglength mcomposingsetlength0 updatecandidates private void updateshiftkeystateeditorinfo attr if attr null minputview null mqwertykeyboard minputviewgetkeyboard int caps 0 editorinfo ei getcurrentinputeditorinfo if ei null eiinputtype editorinfotype null caps getcurrentinputconnectiongetcursorcapsmodeattrinputtype minputviewsetshiftedmcapslock caps 0 private boolean isalphabetint code if characterislettercode return true else return false private void keydownupint keyeventcode getcurrentinputconnectionsendkeyevent new keyeventkeyeventaction down keyeventcode getcurrentinputconnectionsendkeyevent new keyeventkeyeventaction up keyeventcode private void sendkeyint keycode switch keycode case n keydownupkeyeventkeycode enter break default if keycode 0 keycode 9 keydownupkeycode 0 keyeventkeycode 0 else getcurrentinputconnectioncommittextstringvalueofchar keycode 1 break public void onkeyint primarycode int keycodes if iswordseparatorprimarycode handle separator if mcomposinglength 0 committypedgetcurrentinputconnection sendkeyprimarycode updateshiftkeystategetcurrentinputeditorinfo else if primarycode keyboardkeycode delete handlebackspace else if primarycode keyboardkeycode shift handleshift else if primarycode keyboardkeycode cancel handleclose return else if primarycode latinkeyboardviewkeycode options show a menu or somethin else if primarycode keyboardkeycode mode change minputview null keyboard current minputviewgetkeyboard if current msymbolskeyboard current msymbolsshiftedkeyboard current mqwertykeyboard else current msymbolskeyboard minputviewsetkeyboardcurrent if current msymbolskeyboard currentsetshiftedfalse else handlecharacterprimarycode keycodes public void ontextcharsequence text inputconnection ic getcurrentinputconnection if ic null return icbeginbatchedit if mcomposinglength 0 committypedic iccommittexttext 0 icendbatchedit updateshiftkeystategetcurrentinputeditorinfo private void updatecandidates if mcompletionon if mcomposinglength 0 arrayliststring list new arrayliststring listaddmcomposingtostring setsuggestionslist true true else setsuggestionsnull false false public void setsuggestionsliststring suggestions boolean completions boolean typedwordvalid if suggestions null suggestionssize 0 setcandidatesviewshowntrue else if isextractviewshown setcandidatesviewshowntrue if mcandidateview null mcandidateviewsetsuggestionssuggestions completions typedwordvalid private void handlebackspace final int length mcomposinglength if length 1 mcomposingdeletelength 1 length getcurrentinputconnectionsetcomposingtextmcomposing 1 updatecandidates else if length 0 mcomposingsetlength0 getcurrentinputconnectioncommittext 0 updatecandidates else keydownupkeyeventkeycode del updateshiftkeystategetcurrentinputeditorinfo private void handleshift if minputview null return keyboard currentkeyboard minputviewgetkeyboard if mqwertykeyboard currentkeyboard alphabet keyboard checktogglecapslock minputviewsetshiftedmcapslock minputviewisshifted else if currentkeyboard msymbolskeyboard msymbolskeyboardsetshiftedtrue minputviewsetkeyboardmsymbolsshiftedkeyboard msymbolsshiftedkeyboardsetshiftedtrue else if currentkeyboard msymbolsshiftedkeyboard msymbolsshiftedkeyboardsetshiftedfalse minputviewsetkeyboardmsymbolskeyboard msymbolskeyboardsetshiftedfalse private void handlecharacterint primarycode int keycodes if isinputviewshown if minputviewisshifted primarycode charactertouppercaseprimarycode if isalphabetprimarycode mpredictionon mcomposingappendchar primarycode getcurrentinputconnectionsetcomposingtextmcomposing 1 updateshiftkeystategetcurrentinputeditorinfo updatecandidates else getcurrentinputconnectioncommittext stringvalueofchar primarycode 1 private void handleclose committypedgetcurrentinputconnection requesthideself0 minputviewclosing private void checktogglecapslock long now systemcurrenttimemillis if mlastshifttime 800 now mcapslock mcapslock mlastshifttime 0 else mlastshifttime now private string getwordseparators return mwordseparators public boolean iswordseparatorint code string separators getwordseparators return separatorscontainsstringvalueofcharcode public void pickdefaultcandidate picksuggestionmanually0 public void picksuggestionmanuallyint index if mcompletionon mcompletions null index 0 index mcompletionslength completioninfo ci mcompletionsindex getcurrentinputconnectioncommitcompletionci if mcandidateview null mcandidateviewclear updateshiftkeystategetcurrentinputeditorinfo else if mcomposinglength 0 committypedgetcurrentinputconnection public void swiperight if mcompletionon pickdefaultcandidate public void swipeleft handlebackspace public void swipedown handleclose public void swipeup public void onpressint primarycode public void onreleaseint primarycode and symbolsxml file key androidcodes3 androidkeyicondrawablesym keyboard done androidkeywidth20p androidkeyedgeflagsleft when i click done key also i did not go to oneditoractionlistener method please help meplease help me this i have tried like this but not proper solution anyhow i want to take actionid according to actionid i want put switch statement want to know why it did not take actionid when we use other than the android keyboard txtqtysetoneditoractionlistener new oneditoractionlistener public boolean oneditoractiontextview v int actionid keyevent event ifeventgetkeycode keyeventkeycode enter,['android'] +201153,what is happening here in this c code can anyone please explain what is going in this c code it compiles and executes fine on linuxinclude iostreamusing namespace stdint main cout hello worldn 195,['c++'] +201160,does phps date default timezone set adjust to daylight saving does phps date default timezone set adjust to daylight savingi have this code and wonder if it will always result in the correct stockholm time date default timezone seteuropestockholm timestamp dateymd his,['php'] +201163,try to change bin log directory mysqlbinindex not found errcode 13 mysql 5154ubuntu 1104iam try to change bin log directory in myconf asmysqldlog binhomedeveloperlogsmysqlmysqlbinlogafter this changes mysql server cannot start with errorusrsbinmysqld file homedeveloperlogsmysqlmysqlbinindex not found errcode 131005 124758 error abortingpermission for directory homedeveloperlogsmysql is 07whats going on,['mysql'] +201172,match strings with regular expression in ignore case i need to match strings in my array which are not starting with kb stringi have tried thisstring ar kb akb b k c kbd kb e fpattern p patterncompilekbforstring str ar matcher m pmatcherstr ifmmatches systemoutprintlnstrbut it still not matches k cthanks,['java'] +201188,iphone qrcode generator and decoder i have to create an app in iphone which can generate qrcode for textmailmapphotos etc and can also decode the qrcode has anyboday have idea about its api or examplethanks in advance,"['iphone', 'ios']" +201190,replace multiple substrings at once say i have a file that contains some text there are substrings like substr1 substr2 substr3 etc in it i need to replace all of those substrings with some other text like repl1 repl2 repl3 in python i would create a dictionary like this substr1 repl1 substr2 repl2 substr3 repl3and create the pattern joining the keys with then replace with resub functionis there a similar simple way to do this in java,['java'] +201208,compiling java 7 to java 6 i am aware that the runtime features of java 7 are not available with java 6 but since no new byte code has been added the new byte code invokedynamic is only relevant for nonjava languages i was wondering how hard it would be to convert java 7 source code new switch statement diamond operator to pure java 6 ie to be able to start to convert the source to java 7 without losing java 6 compatibilityany pointers,['java'] +201210,how can i fix vims line breaking behavior for long lines in python so heres my problems let us say i have a python file and i am typing a really long line like the last one hereclass someclassobject def some methodself some variable someotherclasome other methodsome parametersome valuewhen i type this in vim this happensclass someclassobject def some methodself some variable someotherclasome other methodsome parametersome valuethat is not just bad style it breaks pep8 what i would like to happen isclass someclassobject def some methodself some variable someotherclasome other method some parametersome valuewhich is in keeping with pep8 for the purposes of this thiscussion i am only interested in the line breaking behavior not the indentation behavioredit breakat only works in conjunction with linebreak to govern how lines are thisplayed it does not apparently work in conjunction with textwidth to determine where hard line breaks are inserted so my idea below will not worksurprisingly i have found nothing out there indicating others share this problem which leads me to think i am doing something wrong nevertheless my idea was to add the character to the breakat setting along with and while i was at iti have tried this heres the output of set breakatbreakat ihowever it is to no avail no matter what i do vim insists on breaking after the above i have this same problem with long function names as well where it will break right after defhere are the complete contents of my vimrcset nobackupset nowritebackupset noswapfileset columns80set tabstop4set shiftwidth4set softtabstop4set autoindentset smarttabset smartindentset textwidth80set wrapset breakat ifiletype indent onfiletype onfiletype plugin oni have no plugins etc installed for the purpose of trying to figure this outdoes anyone have any idea how i can get vim to obey my breakat setting or any other thoughts about the best way to deal with this behavior,['python'] +201225,best way to find out if response is json during ajaxsuccess in my ajaxsucess function i need to find out if the response is json currently i am doing thisbodyajaxsuccessfunctionevt xhr settings var conttype xhrgetallresponseheadersmatchcontenttype ifconttype conttypelength 2 conttype1tolowercase applicationjson is there a better way,"['javascript', 'jquery']" +201231,how do you select top x but still get a count of the whole query i am writing a webpage to interactively filter results based on filter criteria as it is specified by the user i only want to return from sql the top 20 rows but i want to know how many rows met the criteria count i want to be able to tell the user here are the top 20 rows matching your criteria and btw there were 20 additional rows i am not showing herei know i could simply run the query twice but ew that is expensive and wasteful how can i achieve what i want without over taxing the database,['sql'] +201246,why does sql keep creating a df constraint i am trying to create upgrade and backout scripts in sql the upgrade script adds a column like soif not exists select from syscolumns where name ncolumnname and object id object idndbotablenamealter table tablename add columnname bit not null default0 the backout script removes the column like soif exists select from syscolumns where name ncolumnname and object id object idndbotablenamealter table tablename drop column columnnamehowever the backout script throws this errormsg 5074 level 16 state 1 line 5 the object df tablename columnname 1bf3d5bd is dependent on column columnnamemsg 4922 level 16 state 9 line 5 alter table drop column columnname failed because one or more objects access this columni know how to drop the constraint but the constraints name changes everytime the suffix changes i either need sql to stop creating this randomlynamed constraint or i need to be able to remove the constraint in my script using wildcard characters since the name changes,['sql'] +201274,stored procedures and unit testing does anybody know of a framework or methodology to unit test stored procedures just using sql and be able to produce a reasonable report as to what has passed and what has failed something similar to cppunit,['mysql'] +201280,interactively using mutexes et al in powershell while debugging an application that uses semaphores for crossprocess synchronization i stumbled upon the idea of using powershell to take the place of the other process doing something like this in powershell works fine in c applicationvar sem new semaphore0 1 crossprocsemsemwaitone in powershell session1 cprojects sem newobject systemthreadingsemaphore0 1 crossprocsem2 cprojects semreleaseand i can call waitone and release repeatedly on that same instance of a semaphore as often as i need tobut when i try to do the same thing with a mutex powershell keeps claiming that the mutex was abandoned1 cprojects mtx newobject systemthreadingmutexfalse crossprocmtx2 cprojects mtxwaitonetrue3 cprojects mtxreleasemutex4 cprojects mtxwaitoneexception calling waitone with 0 arguments the wait completed due to an abandoned mutexat line1 char13 mtxwaitone categoryinfo notspecified parentcontainserrorrecordexception fullyqualifiederrorid dotnetmethodexceptionthe error seems to happen any time i call waitone after having acquired the mutex once before either a previous waitone call or asking for it to be initially owned in the constructor5 cprojects mtx2 newobject systemthreadingmutextrue6 cprojects mtx2waitoneexception calling waitone with 0 arguments the wait completed due to an abandoned mutexat line1 char14 mtx2waitone categoryinfo notspecified parentcontainserrorrecordexception fullyqualifiederrorid dotnetmethodexception7 cprojects mtx3 newobject systemthreadingmutex8 cprojects mtx3waitonetrue9 cprojects mtx3waitoneexception calling waitone with 0 arguments the wait completed due to an abandoned mutexat line1 char14 mtx3waitone categoryinfo notspecified parentcontainserrorrecordexception fullyqualifiederrorid dotnetmethodexceptionis powershell doing some wierd thread shenanigans in the background or am i just completely forgetting how mutexes work,['.net'] +201287,railscachefetch exception typeerror cannot be referred to i am implementing some caching by using the nifty railscachefetch however in one particular instance sometimes i encounter an exceptiontypeerror in emlocontrollerindexemlo cannot be referred toappcontrollersemlo controllerrb320in get employeesappcontrollersemlo controllerrb356in prepare json responseappcontrollersemlo controllerrb23in block 2 levels in indexappcontrollersemlo controllerrb15in indexit seems the fetch will always explode with the above on the first try and then work fine as long as the fetch is within the expiration i know i am missing something so a fresh pair of eyes would be niceheres the method which invokes the cache fetchdef get employees this is for a ajax refresh loop so a 5second cache actually helps quite a bit railscachefetchemlo all expires in 5seconds race condition ttl 1 do conditions paramsid user id paramsid nil selections employee locationsid as emlo id employee locationsstatus id employee locationsnotes employee locationsuntil employee locationsupdated at employee locationsuser id location statesid as state id location statestitle as status string location statesfont color location statesbg color usersthisplayname usersemail usersmobile usersdepartment usersextension usersguid usersdn join emloall select selections joins left join users on employee locationsuser idusersid left join location states on employee locationsstatus idlocation statesid conditions conditions order usersthisplayname asc endend,['ruby-on-rails'] +201290,why does the c compiler complain that types may unify when they derive from different base classes my current noncompiling code is similar to thispublic abstract class a public class b public class c a public interface ifoot void handlet itempublic class myfoota ifoota ifoob where ta a public void handleta a public void handleb b the c compiler refuses to compile this citing the following ruleerrormyprojectmyfoota cannot implement both myprojectifoota and myprojectifoomyprojectb because they may unify for some type parameter substitutionsi understand what this error means if ta could be anything at all then it could technically also be a b which would introduce ambiguity over the two different handle implementationsbut ta cannot be anything based on the type hierarchy ta cannot be a b at least i do not think it can ta must derive from a which does not derive from b and obviously there is no multiple class inheritance in cnetif i remove the generic parameter and replace ta with c or even a it compilesso why do i get this error is it a bug in or general unintelligence of the compiler or is there something else i am missingis there any workaround or am i just going to have to reimplement the myfoo generic class as a separate nongeneric class for every single possible ta derived type,['c#'] +201301,thisplaying chess pieces with unicode in eclipse using java im just trying to thisplay some unicode chess symbols in eclipse using java however it just prints out the random rectangles and unless chess pieces have taken a radical change in style lately i dont think its what i want help is much appreciatedmy codeimport javaioprintstreamimport javaiounsupportedencodingexceptionpublic class chesymbols public static void main string argsthrowsunsupportedencodingexception string unicodemessage u2654 white king u2655 white queen u2656 white rook u2657 white bishop u2658 white knight u2659 white pawn n u265a black queen u265b black queen u265c black rook u265d black bishop u265e black knight u265f black pawn n printstream out new printstream systemout true utf8 outprintlnunicodemessage,['java'] +201303,undefined reference to vtable for x takeawayo in function takeawayproject145 undefined reference to vtable for takeawayproject145 undefined reference to vtable for takeawaytakeawayo in function takeawayproject151 undefined reference to vtable for takeawayproject151 undefined reference to vtable for takeawaytakeawayo in function gamecoreprojecth109 undefined reference to gamecoreintinitialdataintcollect2 ld returned 1 exit statusmake takeaway error 1i keep getting this error from the linker i know it has something to do with inline functions getting a vtable temporarily stored but what that entails i am not quite sure i would assume it has something to do with how i call gamecores constructor in the initilization list of takeawaycppi have a templated class gamecoreh and a class takeawaycpp that is inheriting from gamecorethe vtable error is called 3 times1in takeaways constructor2 takeaways destructor3in gamecores constructori am using ghere is the codei know it may seem hard to read but i have marked off exatcly where the erros occur takeawayhifndef takeaway h define takeaway h includemapincludecctypeincludestackincludemapincludeiostreamincludestringincludecstdlibincludegamecorehincludevectorusing namespace stdclass takeaway public gamecoreint private public templateclass penny void textualgame bool isnumstring str templateclass penny stackint initialdataint initial templateclass position int score int position templateclass position stackint addstackint currentpos stackint possiblepositions templateclass penny takeaway int initial templateclass position takeawaybool isnumstring strint chartointchar thecharendiftakeawaycppdescription this game communicates with the gamecore class to determine the results of a game of takeaway played between two computers or a computer and human include takeawayh descriptioncreates a stack represening initial data notechange to a vector eventually return stack of int stackint takeaway initialdataint initial stackint returnstack int thescore scoreinitial int final ifinitial 0 final 1 else final 0 returnstackpushthescore returnstackpushfinal return returnstack description a textual representation of the game note this is still terribly wrong void textualgame cout this is the best i could do for a graphical representation description deetermines if a number is even note helper function for determining win or loss positions returns 1 if it is and 0 if it is not int takeawayscoreint position ifposition 2 0 return 1 return 0 description will return a stack withouth the given postion in it will contain all positions possible after the given position along with anyother that wehre in the given stackthis function must also update the map to represent updated positions takes a position to check and a stack to return returns a stack of possible positions stackint takeawayaddstackint currentpos stackint possiblepositions ifcurrentpos 0 if even if currentpos 2 0 create a data aray with score of the new positon and mark it as not final int data scorecurrentpos20 vectorint thedatadata datasizeofdata int pos currentpos2 add it to the map this gamesmapcurrentpos2 dataarray this gamesmapinsertstdpairint vectorint pos thedata add it to the possible positions possiblepositionspushpos ifcurrentpos 3 0 int data scorecurrentpos30 vectorint thedatadatadatasizeofdata int pos currentpos3 this gamesmapcurrentpos3 dataarray this gamesmapinsertstdpairint vectorint pos thedata possiblepositionspushpos work for the position that represents taking one penny int minusfinal 0 ifcurrentpos 1 0 minusfinal 1 int data scorecurrentpos 1minusfinal vectorint thedatadatadatasizeofdata int pos currentpos 1 this gamesmapcurrentpos 1 dataarary thisgamesmapinsertstdpairintvectorint pos thedata possiblepositionspushpos return possiblepositions description constructor for the takeaway gameoa takes a initial position and initial data for it takeawaytakeawayint initialgamecoreintgamecoreinitial error here constructor description destuctor takeawaytakeaway error here destructor checks input and creates gameint mainint argc char argv int numberpennies string game argv0 ifargc 2 isnumargv1 int pennies chartointargv1 takeaway gameinstancepennies creates a instance of else ifargc 3 argv1 play isnumargv2 int pennies chartointargv2 takeawayint gameinstancepennies craete a human playab else cerr errorusage game play numberofpennies n exit 1 return 0 converts a char to a integerint chartointchar thechar int theint atoithechar return theint determines if a string is numericbool isnumstring str forint i 0i strlength i ifisdigitstri 1 cerr errorinput number must be a positive integer the charecter stri invalidated your input n exit1 return false return truegamecorehgamecorehdescription this class created gamemap that are written as a template they will communicate with the specific game and the algorithm to keep track of positions ans there valuesifndef gamecore hdefine gamecore hinclude mapinclude stackinclude stringinclude vectorusing namespace stdtemplate class positionclass gamecore protected best move used by algorithim position bestmove the current highest score used by the algorithim int highestscore stack to be used to remmeber what move created the score stackposition movedfrom stack used for the algorithim stackposition curworkingpos the actual map that the data will be held in mappositionvectorint gamesmap public description finds the data array for a poisition takes a position returns a array of integers virtual stackint initialdataposition pos 0 description game must implement a way to determine a positions score virtual int scoreposition pos 0 description a graphical representation of the game virtual void textualgame 0 description a virtual function implemented by the child class it will return a stack without the given position in itthis stack will contain all positions available from the given postion as well as all position already in the given stack also it will update the map with all generated positions takes a postion to check and a stack of currently working positons virtual stackposition addstackposition currentpos stackposition possiblepositions 0 descriptionconstructor that creates a map with positions as the key and an array of two integers that represent the positions value and if we have moved here in the past takes a initial position and a array of integers gamecoreposition initial error here determine the initial data and add it to the map and queue stackint thedata initialdatainitial int first thedatatop thedatapop int second thedatatop thedatapop int initialdata firstsecond vectorint posdatainitialdatainitialdatasizeofinitialdata gamesmapinitial posdata curworkingpospushinitial description a destructor for the class gamecore i do nothing but this class needs a destructor description takes the current position and returns that positions score takes a position returnsa integer that is a positions score int getposscoreposition thepos const return this gamesmapfindthepossecond0 description adds values to a stack based on the current position takes a poistion void updatestackposition curpos this curworkingpos addstackcurposthis curworkingpos get a stack from the game the game has a function that takes a position and a stack and based on the positions returns a stack identical to the last but with added values that represent valid moves from the postion description takes a positions and returns a integer that depends on if the position is a final pos or not takes a position returns a bool that represents if the position is a final1 or not 0 possible change bool isfinalposition thepos typename mappositionvectorint iterator iter this gamesmapfindthepos return itersecond1 1 description based on the given position determine if a move needs to be made if not this is a end game position and it will return itself if a move needs to be made it will return the position to move to that is ideal note because all positions can be represented as integers for any game the return type is a integer int evaluatepositionposition possibleposition ifisfinalpossibleposition if this is a final position return getposscorepossibleposition return the score else updatestackpossibleposition put all possible positions from this in thte stack whilethis curworkingpossize 0 this movedfrompushthiscurworkingposfront take the top of the possible positions stack and set it the the moved from stack this curworkingpospop int curscore evaluatepositionthis movedfromtop recursive call for school curscore curscore 1 negate the score ifcurscore this highestscore if the score resulting from this position is biggest seen highestscore curscore this movedfrompop do this first to get rid of the the lowest point this bestmove this movedfromtop mark where the lowest point came from else this movedfrompop return this bestmove a structure to determine if a position has a lower value than the second struct poscompare bool operator position pos1position pos2 const return pos1getposscore pos2getposscore endif,['c++'] +201318,tcpdf error image unable to get image i am using tcpdf with drupals print module to generate pdf of articles ending up with following error message when i click the link to generate pdftcpdf error image unable to get image httplocalhostpathtodrupalthemesbartiklogopngthe image exists in the location specifiedi tried applyingallow url fopen onallow url include onin phpini but that could not resolve the problem please care to help,['php'] +201384,why does aspnet access the state server even when the pages enablesessionstatefalse but only for a vbnet site not a c site our website uses our own custombuilt session state management separate from aspnet session state but because a handful of special pages use sql server reporting services we also need to enable aspnet session state since we are in a loadbalanced environment we enabled the aspnet state server aspnet stateexe or outofprocess mode on a separate backend machinetoday i noticed that when we temporarily brought down the machine running the state service in our dev environment the dev website stopped working unable to make the session state request to the session state server this despite having enablesessionstatefalse on the page being loadedwhy would aspnet need to connect to the state service when serving a request for a page that does not use session state this seems to happen even if the page does not use a master page base page or any user controls i searched through all our codebehind to ensure that we never programmatically reenable session state or attempt to access it edit after more troubleshooting as suggested by a user below i tried creating a web site from scratch to retest this without any complications from httphandlers httpmodules or other custom logici used visual studio 2008 to create a new aspnet web site using vbneti ran the site through vs allowing it to enable debug mode and generate a standard webconfig filei added sessionstate modestateserver stateconnectionstringtcpiplocalhost42424 under the systemweb element and started my local aspnet state servicei changed the defaultaspx pages enablesessionstate to false and reloaded the page oki stopped the aspnet state service and reloaded the page unable to make the session state request to the session state serverat this point i was puzzled because other users claimed that they had tried something similar and did not experience the same issue so i wondered if it had anything to do with using vbnet silly though that sounds more people use c for aspnet so i redid my test above with a c web site and lo and behold no exception when accessing the page i only got an exception if i set enablesessionstate to true and actually accessed the session collection in codethis proves that vbnet sites in aspnet behave slightly differently in that they access session state on each page even if the page does not need to unfortunately this does not answer my original question whyi am going to crosspost this to the official aspnet forums and see if any gurus there can shed some light,"['.net', 'asp.net']" +201388,error lnk2038 mismatch detected for iterator debug level value 0 does not match value 2 in mainobj i have read a lot of solutions to my problem but none helped i tried clean rebuild reinstalled visual 2010 and change from professional to ultimate but still i dont know why i have this error my project look like this1 exe solution to test my static library1 dll solution static librarycode which is converted to dll is using function from 1 lib called classificationframework i provided this lib as headers and cpp so basically source code in exe solution i linked my generated library some other libs to run it classificationframeworkdll everything works fine when i use release but when i change to debug because i want to debug some stuff i am tired of skipping debugger in release mode i get this 2link 2 classificationframeworklibsampleclassobj msil netmodule or module compiled with gl found restarting link with ltcg add ltcg to the link command line to improve linker performance 2classificationframeworklibsampleclassobj error lnk2038 mismatch detected for iterator debug level value 0 does not match value 2 in mainobj 2classificationframeworklibsamplenamessetobj error lnk2038 mismatch detected for iterator debug level value 0 does not match value 2 in mainobj 2classificationframeworklibsamplesetobj error lnk2038 mismatch detected for iterator debug level value 0 does not match value 2 in mainobj 2classificationframeworklibdirectoryreaderobj error lnk2038 mismatch detected for iterator debug level value 0 does not match value 2 in mainobj 2link warning lnk4098 defaultlib msvcrt conflicts with use of other libs use nodefaultliblibrary 2cdocuments and settingsadministratormy documentsvisual studio 2010projectstransformerdebugtesterexe fatal error lnk1319 4 mismatches detectedwhen i build in release i also got these warnings 1link 1 generating code 1cprogram files x86microsoft visual studio 100vcincludeutility101 warning c4748 gs can not protect parameters and local variables from local buffer overrun because ptimizations are thisabled in function 1cuserskasiadocumentsvisual studio 2010projectsclassificationframeworkclassificationframeworkdirectoryreadercpp30 warning c4748 gs can not protect parameters and local variables from local buffer overrun because optimizations are thisabled in function 1cprogram files x86microsoft visual studio 100vcincludexstring1589 warning c4748 gs can not protect parameters and local variables from local buffer overrun because optimizations are thisabled in function 1cuserskasiadocumentsvisual studio 2010projectsclassificationframeworkclassificationframeworksamplenamessetcpp226 warning c4748 gs can not protect parameters and local variables from local buffer overrun because optimizations are thisabled in function 1cuserskasiadocumentsvisual studio 2010projectsclassificationframeworkclassificationframeworkdirectoryreadercpp60 warning c4748 gs can not protect parameters and local variables from local buffer overrun because optimizations are thisabled in function 1cuserskasiadocumentsvisual studio 2010projectsclassificationframeworkclassificationframeworksamplenamessetcpp199 warning c4748 gs can not protect parameters and local variables from local buffer overrun because optimizations are thisabled in function 1cuserskasiadocumentsvisual studio 2010projectsclassificationframeworkclassificationframeworksamplesetcpp27 warning c4748 gs can not protect parameters and local variables from local buffer overrun because optimizations are thisabled in function 1cuserskasiadocumentsvisual studio 2010projectsclassificationframeworkclassificationframeworksamplenamessetcpp59 warning c4748 gs can not protect parameters and local variables from local buffer overrun because optimizations are thisabled in function 1 finished generating code 1classificationframeworklibsamplesetobj warning lnk4099 pdb vc100pdb was not found with classificationframeworklibsamplesetobj or at cdocuments and settingsadministratormy documentsvisual studio 2010projectstransformerreleasevc100pdb linking object as if no debug info 1classificationframeworklibsamplenamessetobj warning lnk4099 pdb vc100pdb was not found with classificationframeworklibsamplenamessetobj or at cdocuments and settingsadministratormy documentsvisual studio 2010projectstransformerreleasevc100pdb linking object as if no debug info 1classificationframeworklibsampleclassobj warning lnk4099 pdb vc100pdb was not found with classificationframeworklibsampleclassobj or at cdocuments and settingsadministratormy documentsvisual studio 2010projectstransformerreleasevc100pdb linking object as if no debug info 1classificationframeworklibdirectoryreaderobj warning lnk4099 pdb vc100pdb was not found with classificationframeworklibdirectoryreaderobj or at cdocuments and settingsadministratormy documentsvisual studio 2010projectstransformerreleasevc100pdb linking object as if no debug info 1 testervcxproj cdocuments and settingsadministratormy documentsvisual studio 2010projectstransformerreleasetesterexei found that debugger skips because of wrong path to pdb filestesterexe loaded cdocuments and settingsadministratormy documentsvisual studio 2010projectsworkreleasetesterexe symbols loadedtesterexe loaded cwindowssyswow64kernel32dll cannot find or open the pdb filetesterexe unloaded cwindowssyswow64kernel32dlltesterexe loaded cwindowssyswow64ntdlldll cannot find or open the pdb filetesterexe loaded cwindowssyswow64kernel32dll cannot find or open the pdb filetesterexe loaded copencv22binopencv core220dll binary was not built with debug informationtesterexe loaded cwindowssyswow64msvcp100dll symbols loadedtesterexe loaded cwindowssyswow64msvcr100dll symbols loadedtesterexe loaded copencv22binopencv highgui220dll binary was not built with debug informationtesterexe loaded cwindowssyswow64user32dll cannot find or open the pdb filetesterexe loaded cwindowssyswow64gdi32dll cannot find or open the pdb filetesterexe loaded cwindowssyswow64advapi32dll cannot find or open the pdb filetesterexe loaded cwindowssyswow64rpcrt4dll cannot find or open the pdb filetesterexe loaded cwindowssyswow64secur32dll cannot find or open the pdb filetesterexe loaded cwindowssyswow64ole32dll cannot find or open the pdb filetesterexe loaded cwindowssyswow64msvcrtdll cannot find or open the pdb filetesterexe loaded cwindowswinsxsx86 microsoftwindowscommoncontrols 6595b64144ccf1df 58237904770 xww a689ab02comctl32dll cannot find or open the pdb filetesterexe loaded cwindowssyswow64avifil32dll cannot find or open the pdb filetesterexe loaded cwindowssyswow64winmmdll cannot find or open the pdb filetesterexe loaded cwindowssyswow64msacm32dll cannot find or open the pdb filetesterexe loaded cwindowssyswow64msvfw32dll cannot find or open the pdb filetesterexe loaded cwindowssyswow64shell32dll cannot find or open the pdb filetesterexe loaded cwindowssyswow64shlwapidll cannot find or open the pdb filetesterexe loaded cwindowssyswow64avicap32dll cannot find or open the pdb filetesterexe loaded cwindowssyswow64versiondll cannot find or open the pdb filetesterexe loaded copencv22binopencv imgproc220dll binary was not built with debug informationtesterexe loaded cwindowssyswow64imm32dll cannot find or open the pdb filetesterexe loaded cwindowssyswow64lpkdll cannot find or open the pdb filetesterexe loaded cwindowssyswow64usp10dll cannot find or open the pdb filetesterexe loaded cwindowswinsxswow64 microsoftwindowscommon controls 6595b64144ccf1df 6037904770 xww 8d2e3180comctl32dll cannot find or open the pdb filethe program 4984 testerexe native has exited with code 0 0x0when i go to debugwindowsmodules i see that he cannot find those pdb files or something how i can say him that those files are here here and here i tried to run msvisual as administrator but that too didnt help i used microsoft server to load pdb files but also didnt help,['c++'] +201394,jsstringformat and apostrophe with json so i am having an interesting problem with jsstringformat when trying to escape special characters for json i am using the jquery datatables plugin and doing an ajax call to coldfusion what appears to be happening is that jsstringformat is escaping the apostrophe character and putting in my json according to json spec the single apostrophe does not need escaping thus it breakshere is a sample of my json return secho 2 itotalrecords 659 itotalthisplayrecords 201 aadata 516 54d 7h 12m 02 revenue assist in validating error in jca provided thiscount commission report received work request jan 1 2012 616 16d 7h 12m 02 revenue orderinstall new pos terminal at katies workstation in progress work request oct 31 2011 617 15d 7h 12m 02 revenue replace 6081 pos printer at kims desk received work request oct 31 2011 you can clearly see the inserted in the descriptions i really need to find a way to prevent jsstringformat from escaping the apostrophe updateso far have this code for attempting to populate the aadata array right now i am getting nothing but commas so i know its looping properly but not populating the data in the right placesall of this is based off of datatables coldfusion datasource code cfcontent resetyes cfset aadata cfset datasetrecords cfloop queryqfiltered startrowvalurlithisplaystart1 endrowvalurlithisplaylengthcfif currentrow gt urlithisplaystart1cfif cfloop listlistcolumns indexthiscolumn cfif thiscolumn neq listfirstlistcolumnscfif cfif thiscolumn is version cfif version eq 0 cfelsecfset datasetdataversion cfif cfelsecfset datasetdata qfilteredthiscolumnqfilteredcurrentrow cfif cfset arrayappenddatasetrecords datasetdata cfloopcfset arrayappenddatasetrecords aadata cfloopcfset record cfset recordsecho valurlsecho cfset recorditotalrecords qcounttotal cfset recorditotalthisplayrecords qfilteredrecordcount cfset recordaadata aadata cfoutputcfdump varrecordcfoutputcfoutputserializejsonrecordcfoutput,['javascript'] +201401,nesting views within views in backbone js i am working with backbonejs building some complex view relationships and i am wondering if there are any problems from a javascript performance standpoint of doing something that looks like thisvar viewone backboneviewextend tagname li initialize function thisv2 new viewtwoparentthis clickhideone function thiselremoveclaselected var viewtwo backboneviewextend tagname a initialize function thisbindclick thisclickhide this clickhide thiselremoveclaselected thisoptionsparentclickhideone where this is a very simple example of a circular reference between two views in order to have events in one view easily propagate up a chain of views or maintain any references to objects in the parent views are there any situations where this would be a problem specifically in relation to the potential leaks with dom element references in ie7 or is there another recommended best practice for referencing parent viewsalso i understand that i could just do thiselparentliremoveclaselected in viewtwo that is not the point this just a very simple example of the question i have about the circular reference,"['javascript', 'jquery']" +201407,how to rspec a shared activerecord module without associated database table using rspec 26 rails 31 postgres i am writing a supporting module in my lib that any ar model can include i would like to write spec for this module it needs to be included by an arbase model because it loads associations when included and relies on some ar methods but i do not want to use my existing model when writing rspec for this module i would just like to create an arbitrary ar model but obviously it would not have a table associated in the database and ar is dying heres kindda what i want to doclass somerandommodel activerecordbase include mymodule simulate db attributes that mymodule would be using attr accessor foo bar baz enddescribe somerandommodel do it some method in my module do srm somerandommodelnewfoo 1 srmsome method in my moduleshould eqsomething endendof course i get some error in postgres about the relation not existing thanks for your help,['ruby-on-rails'] +201423,how to change routes in ruby on rails i just installed ruby on rails and created a scaffold called posts ror generated controllers and other required files for mei created a new method in posts controller but i cannot access it i looked at other methods that are in the controller and looks like i need to access them by postsmy post idmy method nameassuming i created my custom method hello in the controller how do i access iti looked at routesrb but there is no configuration for itupdatedi understand that i can manually configure it in routesrb but how do all the other methods work for example i have edit and update methods in the posts controllerrb controller how do those two methods work without configuring routes get posts1edit def edit post postfindparamsid endi cannot find a configuration that matches posts09edit pattern,['ruby-on-rails'] +201446,why do cell renderers often extend jlabel i noticed this is common for example defaultlistcellrenderer defaulttablecellrenderer and defaulttreecellrenderer all use it also a lot of the custom cell renderers i see online use this as well i want to use a custom tablecellrenderer in my code but i am confused about whether i really need to subclass jlabel whats the benefit of subclassing jlabel,['java'] +201447,addresses of identical function template instantiations across compilation units why does this worki see similar so questions stating that it does but could someone explain it in more detail particularly is this behavior protected by a standardihifndef i h define i h typedef void funcptrtemplatetypename tvoid functemplate class c endifaccinclude ihfuncptr a return functemplatecbccinclude ihfuncptr b return functemplatecmccinclude iostreaminclude ihfuncptr afuncptr bint main stdcout a b equal not equal stdendl return 0then g c o ao acc g c o bo bcc g c o mo mcc g ao bo mo o prog progequaltossing wall wextra werror ansi onto all the g calls produces the samemy naive understanding is that functemplate is instantiated once in each of the ao and bo compilation units and so the addresses should each point to one copy how do these end up the same after all and is this behavior portable or protectededit the shared library case g shared o libaso acc g shared o libbso bcc g c o mo mcc g l la lb mo o prog progequal,['c++'] +201450,strange gcc behaviour given the following c codestruct vertex type float x y z vertex type vertex typefloat x float y float z xx yy zz typedef struct vertex type vertex10 obj typeobj type cube 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 int main return 0when i added the currently commented out constructors into the vertex type struct it abruptly 1015 second rise in compilation timestumped i looked to the assembly generated by gcc using s and noticed that codegen size was several hundred times bigger than beforemovl 0x3f80 cube84ripmovl 0x3f80 cube88ripmovl 0x3f80 cube92ripmovl 0x0 cube96ripmovl 0x0 cube1196ripby leaving out the constructor definition the generated assembly was completely differentglobl cube data align 32 type cube object size cube 120cube long 3212836864 long 3212836864 long 3212836864 long 1065353216 long 3212836864 long 3212836864 long 3212836864 long 1065353216 long 3212836864 long 1065353216 long 1065353216 long 3212836864 long 3212836864 long 3212836864 long 1065353216 long 1065353216 long 3212836864 long 1065353216 long 3212836864 long 1065353216 long 1065353216 long 1065353216 long 1065353216 long 1065353216 zero 24 textobviously there is a significant difference in the code generated by the compiler why is thatalso why does gcc zero all the elements in one situation and not the otherediti am using the following compiler flags stdc0x with g 452,['c++'] +201456,tree plotting in python i want to plot trees using python decision trees organizational charts etc any library that helps me with that,['python'] +201476,automatically implemented property in struct can not be assigned i have a next codestruct t public tint u thisu 10 errors are here public int you get private set c compiler give me a pair of errors in stated line 1 backing field for automatically implemented property testconsoleaprogramtu must be fully assigned before control is returned to the caller consider calling the default constructor from a constructor initializer2 the this object cannot be used before all of its fields are assigned towhat i do wrong help me understand,"['c#', '.net']" +201495,creating method dynamically and executing it backgroundi want to define few static methods in c and generate il code as byte array from one of these methods selected at runtime on client and send the byte array over network to another machine server where it should be executed after regenerating the il code from the byte array my attempt pocpublic static class experiment public static int multiplyint a int b consolewritelinearguments 0 1 a b return a b and then i get the il code of the method body asbindingflags flags bindingflagspublic bindingflagsstaticmethodinfo meth typeofexperimentgetmethodmultiply flagsbyte il methgetmethodbodygetilasbytearrayso far i did not create anything dynamically but i have il code as byte array and i want to create an assembly then a module in it then a type then a method all dynamically when creating the method body of the dynamically created method i use the il code which i got using reflection in the above codethe codegeneration code is as followsappdomain domain appdomaincurrentdomainassemblyname aname new assemblynamemydllassemblybuilder assembuilder domaindefinedynamicassembly aname assemblybuilderaccessrunmodulebuilder modbuilder assembuilderdefinedynamicmodulemainmoduletypebuilder tb modbuilderdefinetypemytype typeattributespublic typeattributesclassmethodbuilder mb tbdefinemethodmymethod methodattributesstatic methodattributespublic callingconventionsstandard typeofint return type new typeofint typeofint parameter typesmbdefineparameter1 parameterattributesnone value1 assign name mbdefineparameter2 parameterattributesnone value2 assign name using the il code to generate the method bodymbcreatemethodbodyil ilcount type realtype tbcreatetypevar meth realtypegetmethodmymethodtry object result methinvokenull new object 10 9878 consolewritelineresult should print 98780 ie 10 9878catch exception e consolewritelineetostringbut instead of printing 98780 on the output window it throws an exception sayingsystemreflectiontargetinvocationexception exception has been thrown by the target of an invocation systemtypeloadexception could not load type invalid token0x0101e from assembly mydll version0 cultureneutral publickeytokennull at mytypemymethodint32 value1 int32 value2 please help me figuring out the cause of the error and how to fix it,['c#'] +201506,is there a more efficient way to convert double to float i have a need to convert a multidimensional double array to a jagged float array the sizes will var from 25 up to around 61024i was curious how just looping and casting the double to the float would perform and it is not too bad about 225as for a 25 array heres the codeconst int count 5const int numch 2double dbl new doublenumch countfloat flt new floatnumchfor int i 0 i numch i flti new floatcount for int j 0 j count j fltij floatdbli j however if there are more efficient techniques i would like to use them i should mention that i only timed the two nested loops not the allocations before itafter experimenting a little more i think 99 of the time is burned on the loops even without the assignment,['c#'] +201537,is there an eclipse shortcut behaves just like double click using mouse i notice the eclipse has a very handy feature of double click it can select text block or select contents between surrounding quotes so is there a shortcut available to do just thisthanks by the way i would like to know if there is shortcut to go to the next todofixme position,['java'] +201541,winapi create resizable window without title bar but with minimizemaximizeclose buttons as firefoxchromeopera if you look at the windows of the browsers firefox chrome or opera youll notice that their windowshave minimizemaximizeclose buttonsare resizablebut have no title bari am interested how can i create such a windowwhat i have already triedi looked around on stackoverflow and googled too and found this opening a window that has no title bar with win32unluckily this did not help completelythe first step was to extend the solution proposed on opening a window that has no title bar with win32hwnd createwindowszwindowclass sztitle ws border cw usedefault cw usedefault cw usedefault cw usedefault null null hinstance nullsetwindowlonghwnd gwl style ws sizebox see remarks on setwindowposhwnd 0 0 0 0 0 position size swp nomove swp nosize swp nozorder swp framechangedof course this delivers no minimizemaximize buttons but on the other hand if i want minimizemaximize buttons i have to dosetwindowlonghwnd gwl style ws sizebox ws maximizebox ws minimizebox ws sysmenu ws captionwhy does this combination seem to be necessary first i probably want ws maximizebox ws minimizebox since i want these buttonsbut says that if i set one of ws maximizebox and ws minimizebox i also have to set ws sysmenu and when i set ws sysmenu i also have to set ws caption but this is not what i want because i wanted to avoid the title bar indeed if ws caption is not set no minimizemaximize buttons are shownso what is to do,['c++'] +201579,save object while orientation change how to save object while orientation change since onretainnonconfigurationinstance and getlastnonconfigurationinstance are deprecated and which cannot me used with compatibility package androidsupportv4jar fragmentactivity where it shows cannot override the final method from fragmentactivitydeveloper site say use the new fragment api setretaininstanceboolean insteadbut i do not know how to save a custom object using setretaininstance my scenario in my activity i have a asynctask with progress dialog here i need to handle orientation changefor that i got a very good answer from mark murphy commonswarebackgroundtaskprogressdialogorientationchangeisthereany100workingwith sample project since i am using compatibility package androidsupportv4jar fragmentactivity i cannot override onretainnonconfigurationinstancecannot override the final method from fragmentactivityis there any alternative method for saving my custom objectediti cannot make my asynctask task parcelable if i am not wrong since it use interface context etcmy asynctask public class commonasynctask extends asynctaskobject object object context context asynctaskservices callerobject progressdialog progressdialog string dialogmessag i am looking is there any alternatives for onretainnonconfigurationinstance method which save an object completely while orientation change and later can be retrieve using getlastnonconfigurationinstance,['android'] +201600,bundling data files with pyinstaller onefile i am trying to build a onefile exe with pyinstaller which is to include an image and an icon i cannot for the life of me get it to work with onefileif i do onedir it works all works very wellwhen i use onefile it cannot find the referenced additional files when running the compiled exe it finds the dlls and everything else fine just not the two imagesi have looked in the tempdir generated when running the exe temp mei95642 for example and the files are indeed in there when i drop the exe in that tempdirectory it finds them very perplexingthis is what i have added to the spec fileadatas imagesiconico dworkspaceappsrcimagesiconico dataimagesloaderanigifdworkspaceappsrcimagesloaderanigifdata i should add that i have tried not putting them in subfolders as well did not make a differenceedit marked newer answer as correct due to pyinstaller update,['python'] +201603,get original url without nonstandard port c first questionenvironmentmvc c appharborproblemi am calling an openid provider and generating an absolute callback url based on the domain on my local machine this works fine if i hit httplocalhost12345loginrequesturl gives me httplocalhost12345callbackhowever on appharbor where i am deploying because they are using nonstandard ports even if i am hitting it at requesturl gives me and this screws up my callback because the port number was not in the original source urli have triedrequesturlrequesturloriginalstringrequestrawurlall gives me also to clear up that this is not a realm issue the error message i am getting from dotnetopenauth is not under realm httpexamplecom i do not think i have stuffed that upnow i am about to consider some hacky stuff like preprocessor commands if debug then put portstring replace requesturlcontainslocalhostall of these are not 100 solutions but i am sick of mulling over what could be a simple property that i am missing i have also read this but that does not seem to have an accepted answer and is more about the path rather than the authority so i am putting it towards you guyssummaryso if i had httplocalhost12345login i need to get httplocalhost12345callback from the request contextand if i had i should get regardless of what port it is onthanks sleep time will answer any questions in the morning,['c#'] +201616,how to thisable text selection via jquery i know this question have been already asked here but all the answers i have found dealt with cselector selection that is not yet too widely supported by browsersso how can i thisable text selection on my html page via jquery not relying on css tricks,"['javascript', 'jquery', 'html']" +201659,priority of kernel modules and sched rr threads i have an embedded linux platform the beagleboard running angstrom linux with two devices connecteda laser range finder hokuyo utm 30 connected via usba custom external board connected via spi we have a written a linux kernel module which is responsible for the spi data transfer it has an irq handler in which spi async is called which in turn causes an async callback method to be calledmy c application consists of three threadsa main thread for data processinga laser polling threadan spi polling threadi am experiencing problems which seem to be caused by how the modules described above interactwhen i switch off the usb device laser range finder i receive all spi messages correctly 1 message every 3ms message length divided by data rate is 1ms independent from thread schedulingwhen i switch on the usb device and i run my program with normal thread scheduling sched other priority 0 no nice level set about 1 of the messages is lost because the callback method of spi async is running when the next irq occurs i could handle this case differently in order not to loose the messages so this is not a big issuewith the usb device turned on and i run the program with sched rr andpriority 10 for main threadpriority 10 for spi reading thread priority 4 for usblaser polling threadthen i am loosing 40 of the messages because the irq is triggered again before the spicallback method is called i could still maybe find a workaround but the problem is that i need fast response times which can no longer be reached in this case i need to use the thread scheduling and the laser device so i am looking for a way to solve this casequestion 1my assumption was that irq handlers and the callbacks triggered by spi async in kernel space have higher priority than any thread running in user space no matter if sched rr or sched other this would mean that turning to sched rr in my application should not slow down spi transfer but this seems very wrong is itquestion 2how can i determine what happens here which debugging aids exist or maybe you do not need any further information the main question for me is why do i experience the problems only when the laser device is turned on could the usb driver consume so much time editi have made the following observationthe spi asyncs callback calls wake up interruptiblemydatareadq with wait queue head t readq from the user space my app i call a function which results in poll waitfile mydatareadq wait when the poll returns the user space calls read when my application runs with sched other i can see that the callback method first finishes before the read method in my kernel module is entered when my application runs with sched rr read is entered before exiting the callbackthis seems to proof that the priority of the user space threads is higher than the callback methods contexts priority is there any way to change this behaviour and still have sched rr for my applications threads,"['c++', 'c']" +201661,debugging java application deployed in tomcat i have an application that i deployed in tomcat later i configured the code as a project in eclipse i want to connect to the tomcat via eclipse and debug the applicationtrying to setup a remote debug connection is throwing up errors is there any entry that i need to add somewhere in tomcat,['java'] +201662,htaccess rewrite get variables i have a indexphp which handle all the routing indexphppagecontroller simplified just to split up the logic with the viewoptions followsymlinksrewriteengine onrewritecond request filename frewritecond request filename drewriterule wd indexphppage1 ncwhich basicallyhttplocalhostindexphppagecontrollertohttplocalhostcontrollercan anyone help me add the rewrite forhttplocalhostcontrollerparamvalueparamvalue and soforththat would behttplocalhostcontrollerparamvalueparamvaluei cannot get it to work with the rewriterulea controller could look like this phpif isset getaction if getaction delete do delete stuff hereand also phpif isset getaction isset getx if getaction delete do delete stuff here,['php'] +201668,how do i get a listing of only files using dirglob how can i return a list of only the files not directories in a specified directoryi have my list dirglobscript pathjointhis returns everything in the directoryincluding subdirectories i searched but have not been able to find the answer,['ruby'] +201676,make sure that my code is thread safe i am doing an android service that gives content to other apps that can register as callbacki am not 100 sure about how the android handler class works so can someone confirm me that this code is thread safepublic class myservice extends service private static final string message message private final remotecallbacklistimycallback readercallbacks new remotecallbacklistimycallback private static final int report msg 1 private thread readerthread override public void oncreate readerthread new threadreaderrunnable readerthreadsetdaemontrue readerthreadstart private runnable readerrunnable new runnable override public void run while threadinterrupted blocking call byte message jnicommunicatorreadmessage if message null messagelength 0 continue bundle b new bundle bputbytearraymessage message message m readhandlerobtainmessagereport msg msetdatab readhandlersendmessagem private final handler readhandler new handler override public void handlemessagemessage msg switch msgwhat case report msg byte message msggetdatagetbytearraymessage broadcast the new message to all clients final int and readercallbacksbeginbroadcast for int i 0 i n i try readercallbacksgetbroadcastiteminewmessagemessage catch remoteexception e the remotecallbacklist will take care of removing the dead object for us readercallbacksfinishbroadcast break override public ibinder onbindintent intent return mbinder private final iservicestub mbinder new iservicestub public void registercallbackimycallback cb if cb null readercallbacksregistercb public void unregistercallbackimycallback cb if cb null readercallbacksunregistercb in particular if someone calls unregistercallback while the handler is in the for loop will it crashfrom my understanding the handler run in the same thread so it is thread safe but i am not surethanks,['android'] +201686,using createattribute vs just setting the attribute directly in javascript we can create a new dom element in the following waysby using the createattribute setattributenode dom methodsvar input documentcreateelementinput type documentcreateattributetypetypenodevalue textinputsetattributenodetypecontainerappendchildinputor by just setting the attributes directlyvar input documentcreateelementinputinputtype textcontainerappendchildinputthe latter can end up being quite lot less code even when there are only a couple attributes per element the question has anyone run across any drawbacks of the latter method setting attributes directlyi tested this on several browsers the latest ff ie safari opera old ies even ie6 worked and on a basic test inserting a text input with type name and maxlength attributes they all passed heres the fiddle if anybody needs it,['javascript'] +201701,generating sound of a particular frequency using gcc in ubuntu how can i generate sound of a particular frequency in cc i run ubuntu 1004 and use gcc there is a void soundint frequency function on turboc for windows is there an equivalent for gcc,['c'] +201708,php date to ical date format for dtstart is there an easy way to get the correct format for an ical dtstart using php datei need the format to look like 201008t110 or 201008 that one is easy if i do not have any timedoes php date have a quick way to do this specifically one that adds the time or removes it when needed,['php'] +201710,uitableviewcontroller last row cut off i am experiencing a problem where in my uitableviewcontroller the last row is always cutoff by halfif i have 20 rows the 20th will be cut off if i have 30 the 30th will be cut offi tried to resize the contentsize and the frame of the uitableviewcontroller but it does not workis there a way to resize the uitableviewcontroller to the correct sizethanks in advancesome codeinitialize it in another class settingstable settingtableviewcontroller alloc init settingstableviewframe cgrectmake0 0 320 480 selfview addsubviewsettingstableviewin the uitableviewcontroller nsintegernumberofsectionsintableviewuitableview tableviewreturn settingsdata count nsstring tableviewuitableview tableview titleforheaderinsectionnsintegersectionreturn settingsdata objectforkeynsstring stringwithformatd section objectatindex0 nsintegertableviewuitableview tableview numberofrowsinsectionnsintegersectionreturn settingsdata objectforkeynsstring stringwithformatd section objectatindex1 intvaluei did not resize the frame anywhere in the uitableviewcontroller,"['iphone', 'objective-c', 'ios']" +201764,how to copy a file with the ability to cancel the copy iam trying to have the program be able to cancel the copy therefore i canat use microsoftvisualbasicfileiofilesystemcopyfile there are some wrappers for copyfileex on the web such as here however i rather not use something i donat understand not wanting any unexpected results or bugs is there a managed way to do this or perhaps a wrapper by ms in something like windows api codepackthanks,['c#'] +201801,how to measure memory usage for a live aspnet mvc web application so right off the bat not sure if this question is better suited for another stackexchange sitei have got an aspnet mvc 3 web application running on windows server 2008 and iis 75site runs fine initially but i can see the memory usage gradually growing after about 12 hours it is nearly out of memory and the site chokesi am using a lot of caching so i am thinking this combined with some possibly memory leaks is the cause of the issueso my question whats the best way tools for example to monitor memory usage on a web server running aspnet mvc in the past i have used good old perfmon and put the iis counters on to measure these thingsit this still the best way and if so can someone recommend a good perfmon counter template for my scenario,['asp.net'] +201812,use xlintdeprecation with android so i almost always get some message like this when i am compiling my android appjavac note homekurtissandboxudjandroidappsrcorgklnusbaumudjplaylistfragmentjava uses or overrides a deprecated apijavac note recompile with xlintdeprecation for detailshow do i recompile with this option do i have to edit something in my buildxml,"['java', 'android']" +201821,objective c if syntax i am a little confused by the pound if or if syntax i see when i look at some classesfor exampleif someconstant somenumber do somethingelif etcversusif someconstant somenumber do somethingelse if do more stuffwhats the difference and why use if,['objective-c'] +201823,how do you put a border around a uitableviewcells contentview for testing whats the code to put a border around a uitableviewcells contentview for testingif not possible why is this for my learning,"['iphone', 'ios']" +201825,printing a comma after each item in an array lets say i have an array or list of itemsa abcdeif i want to print them out so each item is separated by a comma or any other delimiter i generally have to do thisforint i0 i acount i consolewriteai if i acount1 consolewriteso my output looks likeabcdeis there a better or neater way to achieve thisi like to use a foreach loop but that prints a comma after the last element as well which is undesirable,['c#'] +201846,how to support amazon and android market google play links in same apk possible duplicatesupporting amazon and android market links inside application i was wondering if and how you could differentiate between an amazon app store installed app and one installed from the marketfor example say i have my app called example app and i want to develop for amazon and the market in the app i have links to rate example app i also have a link to buy example app pro this poses a problem because amazon will not release my app if it links to a different app storethis requires me to make 2 apk files which is a pain it only takes about 30 seconds extra to export both but it creates extra clutter and testing timeso has anyone found a way to make a single apk that can be uploaded to both amazon and android market without making any changes between the two so that at run time i can check whether it is the amazon or the market that installed it and change the links accordingly,['android'] +201851,how to select data from table which recorded today use php and mysql in my table there is date field datetime recorded by now sql function example value of data in this field is 20101007 105736 how can i select all data which daymonthyear is today i try to use code as below select from table where date,['sql'] +201877,how to iterate arraylist i have an arraylist object like thisarraylisthashmapstring string data new arraylisthashmapstring stringhow to iterate through the listi want to thisplay the value in a textview which comes from the data of arraylist object,"['java', 'android']" +201913,edittext how to enablethisable input i have a 7x6 grid of edittext views i want all of them thisabled when the application starts ie they should behave like normal textviews and not to be editable then the user taps one cell in the grid it changes its background and performs something visual if the user clicks on the cell one more time it should allow editing i am struggling with onclick and onfocuschange listeners but i cannot accomplish such a basic interactionplaying with setenabled and setfocusable does not help i wonder why even a simple task like this has been made so difficult on android,['android'] +201918,handlebarsjs and seo i have read a great deal of thiscussions about javascript templating and search engine optimization still i have not found a satisfying answer to the question either poorlydocumented or outdatedcurrently i am looking into handlebarsjs as a clientside template solution because i love the possibility to create helper functions but what about indexing for search engines does the bot index the generated content as intended or only the source with the ugly javascript pseudovariables i know that there are lots of threads going on about this matter but i feel that nobody does exactly know the answerif engines like google would not index these templates properly why would one bother using this for public websitesanother question within this context is it possible to render handlebarjs templates on server side and then present them onto the client side obviously to avoid all this seo thiscussion,['javascript'] +201919,log4j warning while initializing i am trying to learn about log4j so i just tried to do something which is very simplelogger logger loggergetloggerclientapplicationlogloggerinfologger testbut after making this i gotlog4jwarn no appenders could be found for logger clientapplicationloglog4jwarn please initialize the log4j system properlydo you know where i am wrong thank you all,['java'] +201946,a const member function returning a pointer to a non const member variable why would it be good i work in a large collaboration of mostly nonprofessional programmers i being one of them i regularly see examples of the followingvoid tdochangesi i will make changes to internal structure of t nonconstv tgetvalueclass aprivate t fmemberpublic a t getmember const return fmember where a usecase would bea ai iagetmemberdochangesiv v agetmembergetvaluethis practice violates a tenant drilled into me when i took programming courses ie that const refers not only to the bitwise structure of the class instance but the internal logical structure under this philosophy the member function should take the following formst getmember return fmemberconst t getmember const return fmemberi have heard that some people think that const should only refer to members speaking strictly using the c terminology howwhy would someone argue for this type of practice,['c++'] +201948,how do i access a file from xcodeas supporting files group in app i have an app that i have almost finish now that emails at the end of a data entry flow two pdf files one of these is generated from the entered data the other is a static file that will be the same in every instancethe first pdf is generating fine it is saved to the apps documents folder and i have successfully attached to to an email for sending it is the second pdf one that i made externally to the app and am trying to add that is causing me griefi have added it to the supporting files folder within my xcode project but after much searching on here and elsewhere online i cannot work out how to access that file to be able to add it as an attachment in the emailhaving downloaded the apps data from the organizer in xcode i can see that the file is not there anywhere presumably because xcode can see that the file is not being used anywhere it is not adding it at build time very much an assumption on my part but i do not know how to reference it anywhere because i do not know where it will be to reference it,['ios'] +201962,proper way to generate html dynamically with jquery i found some different and conflicting answers on this topici am building an application which works mostly with html dynamically generated by jquery based on results acquired from underlying api in form of json datai was told by some of my collegues personally that the best way would be to do something like thisvar ul uladdclasomeuleachresults functionindex ulappendlihtmlthisattrid indexbodyappenddivattrid dividaddclasomedivappenduletcthe reason i was told it was that updates the dom directly instead of parsing html to achieve ithowever i see lots of code like this same examplevar toappend div clasomediv iddividuleachresults functionindex toappend li id index this litoappend uldivwhich i personally consider as not as elegant but is it better i googled the issue for a couple of minutes and found this article basically it is about increasing performance drastically by using string concatenation my second waythe main issue of this article is that it has been released in 2009 and thiscussed jquery version is 13 today the current release is version 164 which can behave quite differently and this is the issue of most articles on the subject i have already found and i am also somehow suspicious about their credibilitythat is why i have decided to post the question here and ask which method of generating dom is actually the proper one based on performanceimportant editi have written a little benchmark to test which approach is better considering performancejsfiddle concatenation versionjsfiddle array join versioncodevar text lorem ipsumvar strings stringsvar objects objectsvar results results string concatenationvar start new dategettimevar toappend div classdivclass iddivid1ul classulclass idulid1for var i 1 i 20 i toappendi li classliclass idliid1 i text litoappendi uldivresultsappendtoappendjoinstringshtmlnew dategettime start jquery objectsvar start new dategettimevar ul ulattrid ulid2addclassulclassfor var i 0 i 20 i ulappendliattrid liid2 iaddclassliclassresultsappenddivattrid divid2addclassdivclassappendulobjectshtmlnew dategettime startit seems that operating on strings is faster in firefox 7 about 7 times than using jquery objects and methods but i can be wrong especially if there are any mistakes or performancedecreasing bugs in this benchmarks code feel free to make any changesnote i used array join because of the article mentioned earlier instead of actual concatenationedit based on suggestion by hradac i used actual string concatenation in the benchmark and it did in fact improve the times,"['jquery', 'html']" +201975,how to cache in a blackberry browserfield i am creating a blackberry application to thisplay a full screen web view of a certain site i have a working browserfield that thisplays properly but navigation from page to page is slower than that of the native browser the browserfield does not seem to have a built in cache causing the load time to be slow when i add the following code to manage the cache the site no longer thisplays properlybrowserfieldscreenjavaimport netrimdeviceapibrowserfield2import netrimdeviceapiscriptscriptengineimport netrimdeviceapisystemimport netrimdeviceapiuiimport netrimdeviceapiuicomponentimport netrimdeviceapiuicontainerimport orgw3cdomdocumentclass browserfieldscreen extends mainscreen browserfield browserfield loadingscreen load new loadingscreen public browserfieldscreen browserfield new browserfield browserfieldgetconfigsetproperty browserfieldconfigjavascript enabled booleantrue browserfieldgetconfigsetproperty browserfieldconfignavigation mode browserfieldconfignavigation mode pointer browserfieldgetconfigsetproperty browserfieldconfigcontroller new cacheprotocolcontrollerbrowserfield browserfieldrequestcontent addbrowserfield cacheprotocolcontrollerjavaimport javaxmicroeditioniohttpconnectionimport javaxmicroeditionioinputconnectionimport netrimdeviceapibrowserfield2browserfieldimport netrimdeviceapibrowserfield2browserfieldrequestimport netrimdeviceapibrowserfield2protocolcontrollerpublic class cacheprotocolcontroller extends protocolcontroller the browserfield instance private browserfield browserfield cachemanager will take care of cached resources private cachemanager cachemanager public cacheprotocolcontrollerbrowserfield browserfield superbrowserfield thisbrowserfield browserfield private cachemanager getcachemanager if cachemanager null cachemanager new cachemanagerimpl return cachemanager handle navigation requests eg link clicks public void handlenavigationrequestbrowserfieldrequest request throws exception inputconnection ic handleresourcerequestrequest browserfieldthisplaycontentic requestgeturl handle resource request eg images external cssjavascript resources public inputconnection handleresourcerequestbrowserfieldrequest request throws exception if requested resource is cacheable eg an http resource use the cache if getcachemanager null getcachemanagerisrequestcacheablerequest inputconnection ic null if requested resource is cached retrieve it from cache if getcachemanagerhascacherequestgeturl getcachemanagerhascacheexpiredrequestgeturl ic getcachemanagergetcacherequestgeturl if requested resource is not cached yet cache it else ic superhandleresourcerequestrequest if ic instanceof httpconnection httpconnection response httpconnection ic if getcachemanagerisresponsecacheableresponse ic getcachemanagercreatecacherequestgeturl response return ic if requested resource is not cacheable load it as usual return superhandleresourcerequestrequest cachemanagerjavaimport javaxmicroeditioniohttpconnectionimport javaxmicroeditionioinputconnectionimport netrimdeviceapibrowserfield2browserfieldrequestpublic interface cachemanager public boolean isrequestcacheablebrowserfieldrequest request public boolean isresponsecacheablehttpconnection response public boolean hascachestring url public boolean hascacheexpiredstring url public inputconnection getcachestring url public inputconnection createcachestring url httpconnection response public void clearcachestring urlcachemanagerimpljavaimport javaioioexceptionimport javaioinputstreamimport javautildateimport javautilhashtableimport javaxmicroeditioniohttpconnectionimport javaxmicroeditionioinputconnectionimport netrimdeviceapibrowserfield2browserfieldrequestimport netrimdeviceapibrowserfield2browserfieldresponseimport netrimdeviceapiiohttphttpheaderspublic class cachemanagerimpl implements cachemanager private static final int max standard cache age 25920 private hashtable cachetable public cachemanagerimpl cachetable new hashtable public boolean isrequestcacheablebrowserfieldrequest request only http requests are cacheable if requestgetprotocolequalshttp return false do not cache the request whose method is not get if request instanceof httpconnection if httpconnection requestgetrequestmethodequalsget return false do not cache the request with post data if requestgetpostdata null return false do not cache authentication request if requestgetheadersgetpropertyvalueauthorization null return false return true public boolean isresponsecacheablehttpconnection response try if responsegetresponsecode 200 return false catch ioexception ioe return false if responsegetrequestmethodequalsget return false if containspragmanocacheresponse return false if isexpiredresponse return false if containscachecontrolnocacheresponse return false if responsegetlength 0 return false additional checks can be implemented here to inspect the http cacherelated headers of the response object return true private boolean isexpiredhttpconnection response try getexpiration returns 0 if not known long expires responsegetexpiration if expires 0 expires new dategettime return true return false catch ioexception ioe return true private boolean containspragmanocachehttpconnection response try if responsegetheaderfieldpragma null responsegetheaderfieldpragma tolowercase indexofnocache 0 return true return false catch ioexception ioe return true private boolean containscachecontrolnocachehttpconnection response try string cachecontrol responsegetheaderfieldcachecontrol if cachecontrol null cachecontrol removespacecachecontroltolowercase if cachecontrolindexofnocache 0 cachecontrolindexofnostore 0 cachecontrolindexofprivate 0 cachecontrolindexofmaxage0 0 return true long maxage parsemaxagecachecontrol if maxage 0 responsegetdate 0 long date responsegetdate long now new dategettime if now date maxage already expired return true return false catch ioexception ioe return true public inputconnection createcachestring url httpconnection response byte data null inputstream is null try read data int len int responsegetlength if len 0 is responseopeninputstream int actual 0 int bytesread 0 data new bytelen while bytesread len actual 1 actual isreaddata bytesread len bytesread bytesread actual catch ioexception ioe data null finally if is null try isclose catch ioexception ioe if response null try responseclose catch ioexception ioe if data null return null calculate expires long expires calculatecacheexpiresresponse copy headers httpheaders headers copyresponseheadersresponse add item to cache cachetableputurl new cacheitemurl expires data headers return new browserfieldresponseurl data headers private long calculatecacheexpireshttpconnection response long date 0 try date responsegetdate catch ioexception ioe if date 0 date new dategettime long expires getresponseexpiresresponse if an expire date has not been specified assumes the maximum time if expires 0 return date max standard cache age 10l return expires private long getresponseexpireshttpconnection response try calculate expires from expires long expires responsegetexpiration if expires 0 return expires calculate expires from maxage and date if responsegetheaderfieldcachecontrol null string cachecontrol removespaceresponse getheaderfieldcachecontrol tolowercase long maxage parsemaxagecachecontrol long date responsegetdate if maxage 0 date 0 return date maxage catch ioexception ioe return 0 private long parsemaxagestring cachecontrol if cachecontrol null return 0 long maxage 0 if cachecontrolindexofmaxage 0 int maxagestart cachecontrolindexofmaxage 8 int maxageend cachecontrolindexof maxagestart if maxageend 0 maxageend cachecontrollength try maxage longparselongcachecontrolsubstringmaxagestart maxageend catch numberformatexception nfe multiply maxage by 10 to convert seconds to milliseconds maxage 10l return maxage private static string removespacestring s stringbuffer result new stringbuffer int count slength for int i 0 i count i char c scharati if c resultappendc return resulttostring private httpheaders copyresponseheadershttpconnection response httpheaders headers new httpheaders try int index 0 while responsegetheaderfieldkeyindex null headersaddpropertyresponsegetheaderfieldkeyindex responsegetheaderfieldindex index catch ioexception ioe return headers public boolean hascachestring url return cachetablecontainskeyurl public boolean hascacheexpiredstring url object o cachetablegeturl if o instanceof cacheitem cacheitem ci cacheitem o long date new dategettime if cigetexpires date return false else remove the expired cache item clearcacheurl return true public void clearcachestring url cachetableremoveurl public inputconnection getcachestring url object o cachetablegeturl if o instanceof cacheitem cacheitem ci cacheitem o return new browserfieldresponseurl cigetdata cigethttpheaders return null cacheitemjavaimport netrimdeviceapiiohttphttpheaderspublic class cacheitem private string url private long expires private byte data private httpheaders httpheaders public cacheitemstring url long expires byte data httpheaders httpheaders thisurl url thisexpires expires thisdata data thishttpheaders httpheaders public string geturl return url public long getexpires return expires public byte getdata return data public httpheaders gethttpheaders return httpheaders any help that can be giving towards this will be greatly appreciated this really has me stumped thanksupdate it looks like the caching only works at a certain level of the blackberry libraries i have added logic to check the current software level and turn on the caching if it is supported by the devices current software level this provides me with a good work around but i would still like to know if there is a better way for the caching to work with all devicesupdate 2 based on comments the site no longer thisplaying properly pertains to site not thisplaying the proper layout images and text it basically give a white background with links and text thisplaying as a bulleted list all formatting removed,['java'] +201980,java array with loop i need to create an array with 100 numbers 1100 and then calculate how much it all will be 1234100 sumi do not want to enter these numbers into the arrays manually 100 spots would take a while and cost more codei am thinking something like using variable till 100 and then calculate the sum of it all not sure how exactly it would be written but it is in important that it is in arrays so i can also say later how much is array 55 and i can could easily see it,['java'] +201982,extjs 4 naming conventions i was thiscussing with my colleagues the correct naming conventions for classes variables and objects etc within extjs 4 but we all had differing viewsis there an official stance on this,['javascript'] +201985,jquery ui toggle button checkbox clickdrag bug i am posting this along with the best answer i have come up with i have not found any similar questions so here goeswhen a input of type checkbox is converted to a jquery ui button i have observed as have others that it only registers a click if the mouse is kept completely still while clicking any movement whatsoever and nothing happens to the user this can only be perceived as flaky and unreliable behaviorhow do others work around this behavior observed with jquery 163jquery ui 1816 in chrome 14 and ie 8 is there something obvious i am missing since i have to go to such lengths to get the expected behavior,['jquery'] +201987,tuple object does not support item assignment i am using the pil libraryi am trying to make an image look reder this is what i have gotfrom pil import imageimage imageopenballoonjpgpixels listimagegetdatafor pixel in pixels pixel0 pixel0 20 imageputdatapixelsimagesavenewbmphowever i get this error typeerror tuple object does not support item assignment,['python'] +202000,db connection string in webconfig to use attached mdf database would not work the file neodbmdf is in my app data folder and i can browse the database in the server explorer in visual studio using built in sqlexpresscurrently trying to no avail connectionstrings add nameefdbcontext connectionstringsqlexpressattachdbfilenamedatadirectoryneodbmdf databaseneodbtrusted connectionyes providernamesystemdatasqlclient connectionstringsand connectionstrings add nameefdbcontext connectionstringdata sourcesqlexpressdatabaseneodbmdfintegrated securitytrue providernamesystemdatasqlclient connectionstringsalso as i understand the mdf is an sql server database file type and dbo is owner of file when it is included in the initial catalog whats the initial catalog anywhere,['asp.net'] +202017,c how to make a http call i wanted to make an http call to a website i just need to hit the url and dont want to upload or download any data what is the easiest and fastest way to do iti tried below code but its slow and after 2nd repetitive request it just goes into timeout for 59 secounds and than resumewebrequest webrequest webrequestcreatehttpussbazesspre0049002dreadd filenamewebrequestmethod postwebrequestcontenttype applicationxwformurlencodedwebrequestcontentlength filenamelengthstream os webrequestgetrequeststreamoswritebuffer 0 bufferlengthoscloseis using the webclient more efficientwebclient web new webclientwebuploadstringaddressi am using net ver 35,['c#'] +202037,can i format null values in stringformat i was wondering if there is a syntax for formatting null values in stringformat such as what excel usesfor example using excel i could specify a format value of 0null which means thisplay the numeric value as number format if positive number format in parenthesis if negative or null if the value is nullstringformat0null somenumericvalueediti am looking for formatting nullnothing values for all data types not just numeric ones my example is actually incorrect because i mistakenly thought excel used the 3rd parameter if the value was null but it is actually used when the value is 0 i am leaving it in there because it is the closest thing i can think of to what i was hoping to doi am hoping to avoid the null coalescing operator because i am writing log records and the data is not usually a stringit would be much easier to write something likelogstringformatvalue1 changes from 0null to 1null new object oldobjectsomevalue newobjectsomevalue than to writevar old oldobjectsomevalue null null oldobjectsomevaluetostringvar new newobjectsomevalue null null newobjectsomevaluetostringlogstringformatvalue1 changes from 0 to 1 new object old new,['c#'] +202043,forcing footer stay at the bottom i have no containers no wrappersi simply have a layout like sobodydiv idheaderdivdiv idleftdivdiv idrightdivdiv classcleardivdiv idfooterdivwhat i am wanting to do is to make sure the footer always stays at the bottom of the screen whether i have content that goes pretty far down and or even not enough content to go all the way to the bottom of the screenas of right now i can get either two of the ways listed above to work but i want both to workhere is the css i have setup for thishtml height 100body height 100position relativefooter position absolutebottom 0i am aware that if i apply a minheight 100 to the html element within the css document that will go as the content goes but if i do not have any content per se it will not stick at the bottom of the screen resolution regardlessi have ran into this problem multiple times and never am quite sure how to figure it out so some help would be much appreciated along with some explanationthank you so much everyone for your help,"['html', 'css']" +202052,code working fine on jsfiddle but not on local system this code is working fine on jsfiddle but not on my systemjsfiddlei have checked from the draft pressing ctrl shift enter on jsfiddle added this code to head section modified like belowwindowaddeventload function windowwebkitrequestfilesystemwindowtemporary 210241024 functionfs fsrootgetfiletest create true functionfileentry alertfileentrytourl fileentrycreatewriterfunctionfilewriter var builder new webkitblobbuilder builderappendsaurabh builderappendn builderappendsaxena var blob buildergetblobtextplain filewriteronwriteend function navigate to file will download locationhref fileentrytourl filewriterwriteblob function function function,['javascript'] +202077,how to document python function parameter types i know that the parameters can be any object but for the documentation it is quite important to specify what you would expectfirst is how to specify a parameter types like these belowstr or use string or stringintlistdictfunctiontupleobject instance of class myclasecond how to specify params that can be of multiple types like a function that can handle a single parameter than can be int or strplease use the below example to demonstrate the syntax needed for documenting this with your proposed solution mind that it is desired to be able to hyperlink reference to the image class from inside the documentation def mymethodself name image does something name string name of the image image image instance of image class or a string indicating the filename return true if operation succeeded or false return truenote you are welcome to suggest the usage of any documentation tool sphinx oxygen as long it is able to deal with the requirements updateit seams that there is some kind of support for documenting parameter types in doxygen in general the code below works but adds an annoying to the param name because it was initially made for php param str arg description param strint arg description,['python'] +202084,android start service on boot from everything i have seen on stack exchange and elsewhere i have everything set up correctly to start an intentservice when android os boots unfortunately it is not starting on boot and i am not getting any errors maybe the experts can helpmanifestxml version10 encodingutf8manifest xmlnsandroid packagecomphxbatterylogger androidversioncode1 androidversionname10 androidinstalocationinternalonlyusessdk androidminsdkversion8 usespermission androidnameandroidpermissionreceive boot completed usespermission androidnameandroidpermissionwrite external storage usespermission androidnameandroidpermissionbattery stats application androidicondrawableicon androidlabelstringapp name service androidnamebatterylogger receiver androidnamestartupintentreceiver intentfilter action androidnameandroidintentactionboot completed intentfilter receiverapplicationmanifestbroadcastreceiver for startuppackage comphxbatteryloggerimport androidcontentbroadcastreceiverimport androidcontentcontextimport androidcontentintentpublic class startupintentreceiver extends broadcastreceiver override public void onreceivecontext context intent intent intent serviceintent new intentcontext batteryloggerclass contextstartserviceserviceintent update i tried just about all of the suggestions below and i added logging such as logvbatterylogger got to onreceive about to start service to the onreceive handler of the startupintentreceiver and nothing is ever logged so it is not even making it to the broadcastreceiveri think i am deploying the apk and testing correctly just running debug in eclipse and the console says it successfully installs it to my xoom tablet at batteryloggerbinbatteryloggerapk then to test i reboot the tablet and then look at the logs in ddms and check the running services in the os settings does this all sound correct or am i missing something again any help is much appreciated,"['java', 'android']" +202085,regular expression to match all comments in a tsql script i need a regular expression to capture all comments in a block of tsql the expression will need to work with the net regex classlet us say i have the following tsql this is comment 1select foo from bargo this is comment 2update bar set foo foogo this is comment 3 delete from bar where foo foo this is amultiline comment drop table bari need to capture all of the comments including the multiline ones so that i can strip them outedit it would serve the same purpose to have an expression that takes everything but the comments,['sql'] +202100,dialog click listener not triggering in ie8 or firefox with jquery i have this click listener and for some reason it is not triggering in ie8 or firefoxconsoleloglistener attachedjqueryuibuttontextclickfunction consolelogthis should have triggered var ajaxurl ajaxphppopuptrue var datastring paramparamparam2param2 contruct the ajax request jqueryajax url ajaxurl datatype json data datastring beforesend function jqueryuibuttontexthtmlsaving complete function jqueryuidialogcontentdialogclose successfunctionresponse so i can see the listener attached in the console but i do not see the click trigger this works in chrome what am i doing wrong herethanksupdate i have tried using liveclick function instead but it is not triggeringupdate so another update i should mention that the content of this dialog is acquired through a separate page it is loaded with ajax this dynamically loaded content contains this click listenerupdate here is the code that loads the content please be aware i did not actually write this piece of code so i do not fully understand why its done the way it is done here start of new window popup jqueryoption windowclickfunction var url jquerythisattrhref var title jquerythisattrtitle jquerydiv dialog autoopen false width 720 title manage code modal true buttons save and returnfunction var self this var popupform jqueryformsubmit on close if jqueryformsubmit on closeattraction jqueryformsubmit on closeattraction ifpopupformattraction popupformattraction jqueryajax url jqueryformsubmit on closeattraction datatype json data jqueryformsubmit on closeserialize success functiondata data evaldata ifdataresp success var obj jqueryrepl activation row objunbindmouseover if dataproperty code 0 if objhasclasscodeoff objremoveclasscodeoffaddclasscodeon else if objhasclasscodeon objremoveclasscodeonaddclasscodeoff jqueryselfdialogclose else jqueryselfdialogclose titletitle open functionevent ui jqueryuidialogdelay600queuefunctionn var toppos jqueryuidialogoffsettop var finalpos toppos jqueryuidialogheight 3 jqueryuidialogcsstop finalpos n var self this jquerygetjsonurl functiondata jqueryselfhtmldata close functionevent ui jquerythisdialog destroy jquerythisremove dialogopen return false end of new window popup and here is the linka hrefpopupmanagerphpcode3212client4432 classactions option window menulinkmanagea,['jquery'] +202125,filtering django admin by nullis not null i have a simple django model likeclass personmodelsmodel referrer modelsforeignkeyself nulltrue in this models modeladmin how would i allow it to be filtered by whether or not referrer is null by default adding referrer to list filter causes a dropdown to be shown that lists every person record which may be in the hundreds of thousands effectively preventing the page from loading even if it loads i still cannot filter by the criteria i wantie how would i modify this so that the dropdown only lists all null or not null choicesi have seen some posts that claim to accomplish something similar using custom filterspec subclasses but none of them explain how to use them the few i have seen appear to apply to all fields in all models which i wouldnt want moreover there is zero documentation for filterspec which makes me nervous because i do not want to invest in a lot of custom code tied to some transient internal class that might thisappear by the next release,['python'] +202137,possible states for native threads on android what are all the possible thread states during execution for native cc threads on an android device are they the same as the java thread states are they linux threads posix threadsnot required but bonus points for providing examples of what can cause a thread to enter each stateedit as requested heres the motivationi am designing the interface for a sampling profiler that works with native cc code on android the profiler reports will show thread states over time i need to know what all the states are in order to a know how many thistinct states i will need to possibly visually differentiate and b design a color scheme that visually differentiates and groups the desirable states versus the undesirable states,"['android', 'c++', 'c']" +202147,dom mutation event in jquery or vanilla javascript are there any dom mutation events in jquery or in vanilla javascript that fire cross browserto clarify say i have a script on my page which inserts a div into the body i do not have access to the script and i do not know when the div has been inserted i was wondering if there is a dom mutation event that i can add a listener for to know when an element has been inserted i know i can use a timer to periodically check for the insertion but i do not really like the overhead that this would impose,"['javascript', 'jquery']" +202154,how to translate model in namespace i have a model productscar how can i translate its attributesi have already tried thisactiverecord models products car 2n341434 n attributes products car owner nand thisactiverecord models products car 2n341434 n attributes products car owner nbut if i try to use productscarmodel namehuman it still says car my other translations work well and the language is set to ru,['ruby-on-rails'] +202160,javascript convert from epoch string to date object var mydate new datevar epoch mydategettime 1318023197289 number of ms since epochvar unixepoch mathroundepoch10how do you convert epoch back to a date objectcan you also convert unixepoch back to a date object,['javascript'] +202170,strategy for parsing natural language descriptions into structured data i have a set of requirements and i am looking for the best javabased strategy algorthm software to use basically i want to take a set of recipe ingredients entered by real people in natural english and parse out the metadata into a structured format see requirements below to see what i am trying to doi have looked around here and other places but have found nothing that gives a highlevel advice on what direction follow so i will put it to the smart people whats the best simplest way to solve this problem should i use a natural language parser dsl lucenesolr or some other tooltechnology nlp seems like it may work but it looks really complex i would rather not spend a whole lot of time doing a deep dive just to find out it cannot do what i am looking for or that there is a simpler solutionrequirementsgiven these recipe ingredient descriptions8 cups of mixed greens about 5 ounceseight skinless chicken thighs about 1a14 lbs65 tablespoons extravirgin olive oilapproximately 6 oz thinly sliced smoked salmon cut into strips2 whole chickens 3 5 pounds each20 oz each frozen chopped spinach thawed5 cup parmesan cheese gratedabout 5 cup pecans toasted and finely ground5 cup dixie diner bread crumb mix plain8 garlic cloves minced 4 tsp8 green onions cut into 2 piecesi want to turn it into this measure weight weight value measure ingredient value measure preparation brand name 1 8 cups mixed greens 5 ounces 2 8 skinless chicken thigh 15 pounds 3 65 tablespoons extravirgin olive oil 4 6 ounces smoked salmon thinly sliced cut into strips 5 2 whole chicken 35 pounds 6 20 ounces forzen chopped spinach thawed 7 5 cup parmesean cheese grated 8 5 cup pecans toasted finely ground 9 5 cup bread crumb mix plain dixie diner 10 8 garlic clove 4 teaspoons minced 11 8 green onions cut into 2 pieces note the diversity of the descriptions some things are abbreviated some are not some numbers are numbers some are spelled out i would love something that does a perfect parsetranslation but would settle for something that does reasonably well to startbonus question after suggesting a strategy tool how would you go about itthanksjoe,['java'] +202204,systemweb assembly is not found on net 40 version i updated net from 35 to 40 version but after updating the assembly systemweb does not work any more i am getting the following errorwarning 1 could not resolve assembly systemweb the assembly is not in the currently targeted framework netframeworkversionv40profileclient please remove references to assemblies not in the targeted framework or consider retargeting your projectusing the 35 version it works fine how can i fix this,"['c#', '.net']" +202227,drawrect on top of subviews i have subclassed uiview and added a drawrect method to it then i define a view using this custom class and add subviews to it the problem is that drawrect seem to draw stuff under the subviews hence not visiblei want stuff that drawrect draws appear above the subviews of my custom uiviewis this possible,['ios'] +202234,how to program hex2bin in javascript i need to communicate between javascript and php i use jquery for ajax but the output of php script may contain binary data that is why i use function bin2hex in php then json encode is applied on php side what i do not know is how to convert hexadecimal string to binary data on javascript sidethanks,['javascript'] +202240,mongodb c id serialization best pattern i have a class user and i need to work with them in web servicesthen problem is that if i try to serialize id that is type of bsonobjectid i seethat have an empty property that have an empty property and so on i have write this workaround in order it is is a good solutionpublic partial class i user bsonididgenerator typeofbsonobjectidgenerator nonserialized public bsonobjectid id public string id get return this idtostring in this way i can keep id as bsonobjectid but i send an string representation over the web in the property idanother solution is to work with stringobjectidgeneratorpublic partial class i user bsonididgenerator typeofstringobjectidgenerator public string idbut is see that mongodb will store a string into database instead of objectidwhat is the best approach in order to work in a serialization environmental like web services andor an clientserver flashc,['c#'] +202247,how to fire js event in selenium i am using selenium webdriver syntax i know that in selenium serverbased syntax you can fire an javascript event by doingselenium selenium new defaultseleniumlocalhost servergetport iexplore seleniumfireeventlteq30 blurhow do i do the same in an application created with webdriver for example firefoxdriver,['java'] +202250,functions as template parameters issue i have this problem bothering me i have the fsm class which associate keys to callbacksclass fsmpublictypedef bool fsmincallback t int typedef stdmap stdstring incallback t table since i would like to allow the user to register both functors and class member functionstemplate typename callback t bool callback tcallbackfunct tint bool callback int x return callback tcallbackfunct t x void addcallback const stdstring ikey incallback t icallback tableinsert stdmake pair ikey icallback private table tableand some callbacks classesclass callbackbasepublic bool operator int x return docall x private virtual bool docall int x return true class callback public callbackbaseprivate bool docall int x stdcout callbackn return true now if into the main i dofsm afsm okafsmaddcallback one fsmcallback callbackbase callbackbaseoperator koafsmaddcallback two fsmcallback callback callbackoperator the first call is fine in the second one compiler complainstestcpp in function aint mainint charatestcpp10477 error no matching function for call to afsmaddcallbackconst char 4 unresolved overloaded function typeatestcpp10477 note candidate istestcpp247 note void fsmaddcallbackconst string fsmincallback ttestcpp247 note no known conversion for argument 2 from aunresolved overloaded function typea to afsmincallback taalso notice that the following is finetypedef bool callbackfunction t int function t afunction callbackoperatorcallbackafunction 5 any ideathanks in advance for your helpsimone,['c++'] +202254,how to make the datagridview line text in bold when i pick a row how do i make the datagridview line text in bold when i pick a row,['c#'] +202258,why javascript implementation of bubble sort much faster than others sorting algorithms i have done some research about javascript sorting algorithms performance comparison and found unexpected results bubble sort provided much better performance than others such as shell sort quick sort and a native javascript functionality why does this happen maybe i am wrong in my performance testing methodyou can find my research results herehere are some algorithm implementation examples bubble sortoptimized arrayprototypebubblesort function var and thislength do var swapped false for var i 1 i n i if thisi 1 thisi var tmp thisi1 thisi1 thisi thisi tmp swapped true while swapped quick sort arrayprototypequicksort function if thislength 1 return this var pivot thismathroundthislength 2 return thisfilterfunction x return x pivot quicksortconcat thisfilterfunction x return x pivot concat thisfilterfunction x return x pivot quicksort,['javascript'] +202262,how i can do facebook batch fql in java in facebook fql theres this codecurl f access tokena f batch method get relative url me method get relative url mefriendslimit50 it suppose to to be sent with jsonbut i really dont understand how to do this any help thanks,['java'] +202289,check if file exists on sd card on android i want to check if a text file exists on the sd card the file name is mytextfiletxt below is the codefileoutputstream fos openfileoutputsdcardmytextfiletxt mode world writeablehow can i check whether this file exists,['android'] +202291,python running out of memory parsing xml using celementtreeiterparse a simplified version of my xml parsing function is hereimport xmletreecelementtree as etdef analyzexml it etiterparsefilexml count 0 for ev el in it count 1 printcount 0formatcountthis causes python to run out of memory which does not make a whole lot of sense the only thing i am actually storing is the count an integer why is it doing thissee that sudden drop in memory and cpu usage at the end that is python crashing spectacularly at least it gives me a memoryerror depending on what else i am doing in the loop it gives me more random errors like an indexerror and a stack trace instead of a segfault but why is it crashing,['python'] +202302,what happened with my text shadows in google chrome so i have some simple style here previosly chrome rendered it same way as ff like thisand all over sudden i look on my document in chrome and see this not transparent at all shadows what to do with tham how to fixmy css codebodypadding 5pxbackgroundcolor font 101 trebuchet msverdanaarialsansserifh1h2pmargin 0 10pxh1h2fontsize 250color f textshadow 0px 1px 1px 0h2fontsize 120divnifty margin 0 1background 9bd1fabrtop brbottomthisplayblockbackground fbrtop b brbottom bthisplayblockheight 1pxoverflow hidden background 9bd1fabr1margin 0 5pxbr2margin 0 3pxbr3margin 0 2pxbrtop br4 brbottom br4margin 0 1pxheight 2pxpcolor 0textshadow 0px 1px 1px fpaddingbottom03eminputtypebutton ebutton width 150pxpadding 5px 10pxwordwrap breakwordheight automozselection backgroundcolor fbfdfe color ff6c24 textshadow 0px 1px 1px 258ffdselection backgroundcolor fbfdfe color f textshadow 0px 1px 1px 258ffd,"['html', 'css']" +202312,is jqueryready useful on anything other than document i was thinking about the jquery documentready event and it occurs to me that i have never seen anyone apply it on anything other than document is there any other legitimate use for it,['jquery'] +202327,what makes jni calls slow i know that crossing boundaries when making a jni call in java is slowhowever i want to know what is it that makes it slowwhat does the underlying jvm implementation do when making a jni call that makes it so slow,['java'] +202355,getpath and spaces in java i encountered a problem with getpath recently my code looks something like thisfile path new filemainclassgetresourceworldsgetpathfile files pathlistfilesthe problem now is that if there is a space somewhere in the path to the main class pathlistfiles will return null if there is no space everything works fineif i print the path to the cmd i see that every space is replaced by an 20,['java'] +202366,whats a good hash function for english words i have a long list of english words and i would like to hash them what would be a good hashing function so far my hashing function sums the ascii values of the letters then modulo the table size i am looking for something efficient and simple,"['c++', 'c']" +202370,how to add an entry in the android calendar from an html5 mobile web page i am looking for an example or documentation on how to create a hyperlink to the android calendar apps add event screenfor example in the same way that one can create a call hyperlink witha hreftel565callai am looking for info on whether it is possible to link to the android calendars add event screen with something likea hrefcalendarymmddthhmmtzdendymmddthhmmtzdnameappointmentadd calendar entryai am willing to use the google calendar web api specifically but have not found any working solutionheres a forum post with someone looking for a webbased call that works on androidhlen,['android'] +202386,css about two column layout i have never thought that writing a simple two column layout is so complicated using csshahawhat i want to do is the followingwhen the height of the content div exceed the height of screen size scroll bar exist only in the content div the users can only scroll the content div but the sidebar keeps staticthe two columns should have the same heightmy layout iscontainerheadersidebarcontentfooterend of containerhere is my css filethank you,['css'] +202406,failed to register input channel what is this caused by and how to fix this i have been getting the following error reported via market developer console by the users of my appjavalangruntimeexception failed to register input channel check logs for details at androidviewinputqueuenativeregisterinputchannelnative method at androidviewinputqueueregisterinputchannelinputqueuejava92 at androidviewviewrootsetviewviewrootjava568 at androidviewwindowmanagerimpladdviewwindowmanagerimpljava177 at androidviewwindowmanagerimpladdviewwindowmanagerimpljava91 at androidviewwindowlocalwindowmanageraddviewwindowjava465 at androidappdialogshowdialogjava241 at myprogrammyactivityhandlefailureunknown source at myprogrammyactivityrunfailedrununknown source at androidoshandlerhandlecallbackhandlerjava587 at androidoshandlerthispatchmessagehandlerjava92 at androidoslooperlooplooperjava130 at androidappactivitythreadmainactivitythreadjava3835 at javalangreflectmethodinvokenativenative method at javalangreflectmethodinvokemethodjava507 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava847 at comandroidinternaloszygoteinitmainzygoteinitjava605 at dalviksystemnativestartmainnative methoditalicized lines are part of my code the code in question just creates and shows a dialog it is run from a runnable posted to a handler everything should be happening in the gui thread that is why handler is usedi do not know how to debug this i have not experienced this problem myself and all i have is just a bunch of automated reports google shows up a couple of threads on this exact problem but no answers except a hint of this being an android 233specific problem,['android'] +202441,rack error loaderror cannot load such file trying to go through the tekpub rack tutorial but run into this error boot errorsomething went wrong while loading appruloaderror cannot load such file haikuthere is a file named haikurb in the same directory as the app i am trying to run but i get the above error while trying to run the program here is the codeclass environmentoutput def initializeappnil app app end def callenv out unlessappnil response appcallenv2 outresponseendenvkeyseach key outlikeyenvkeyli200contenttype texthtmlout endendrequire hamlrequire haikuclass myapp def callenv poem haikunewrandom template fileopenviewsindexhamlread engine hamlenginenewtemplate out enginerenderobjectnew poem poem 200contenttype texthtml out endenduse environmentoutputrun myappnewi am sure its a small error as the code is the same as in the tutorial and it works for him thanks,"['ruby-on-rails', 'ruby']" +202447,jquery how to check if two elements are the same i need to pass an element to a function and then match that specific element while traversing parent the catch for someone clueless like me is that this element does not have an id in the following example i want every element to turn pink except the one clicked on that should turn yellowfunction colorizeelement elementparentfindspaneachfunction if thiselement the problem is this is always false thiscssbackgroundyellow else thiscssbackgroundpink spanclickfunction colorizethis,"['javascript', 'jquery']" +202465,adding light to scene has no effect i was just starting to play around with threejs but i am stuck at the beginning when i add a light to the scene it has no effectrenderer new threewebglrenderercamera new threeperspectivecamera 45 view angle 800 640 aspect 01 near 10 farcamerapositionz 300scene new threescenerenderersetsize 800 640documentbodyappendchildrendererdomelementcreatesphere radius 50 segments 16 rings 16 sphere new threespheregeometryradius segments rings material new threemeshbasicmaterial color 0xcc0f shading threesmoothshading ambient 0x5 specular 0xf new threemesh sphere material light new threepointlight0x0040fflightpositionx 10lightpositiony 50lightpositionz 300lightintensity 01object createspheresceneadd new threeambientlight0x0f0sceneadd lightsceneadd objectdraw time new dategettime 05 lightpositionx mathsintime 07 30 objectrotationx 002 rendererrender scene camera requestanimationframe drawdrawi also created a js fiddle with the parsed js,['javascript'] +202475,renaming columns in a mysql select statement with r package rjdbc i am using the rjdbc package to connect to a mysql maria db database in r on a windows 7 machine and i am trying a statement likeselect a as bfrom tablebut the column will always continue to be named a in the data framethis works normally with rodbc and rmysql but does not work with rjdbc unfortunately i have to use rjdbc as this is the only package that has no problem with the encoding of chinese hebrew and so on letters set names and so on do not seem to work with rodbc and rmysqlhas anybody experienced this problem,['mysql'] +202477,how to resume a broken upload in html5 i am trying to add resume functionality to html5 file uploaderi need to be able to resume after browser was closed and reopened and i lost the file object i do not want the user to dragopen the file againuntil now i used java applet to do it but i was hoping to find an html5 solution for this problemi thought about saving the files in local storage but they are too bigis there a way to save only the file object the path or any other information that might help me reopen the file without asking the user to reopen the file,['javascript'] +202512,how to integrate the inappsettingskit i have just downloaded the inappsettingskit and i am trying to integrate it with my app however i am having some issues with it since i cannot find any documentation to help me out so far i have done the following stepsi added the inappsettingskit directory to my xcode projecti created a new uiviewcontroller class for my settings which i named settingviewcontrollerat this point i have become a bit stuck as i am not sure what needs to be done if someone could offer some steps on how to integrate this it would be really really helpful as i cannot find any up to date documentation online,"['ios', 'iphone']" +202518,error trying to install npm for nodejs i am having a stab at learning nodejs and i am having a few issues when installing npm node package manager i am pretty sure it is either a permissions thing or folder thing please note that i have just purchased a mac i have used windows all my life and i am pretty unfamiliar with the mac terminalokay i went to use the one line install for npm curl sh and i got an errorall clean d git git submodule update init recursivenode clijs rm npm g fnode clijs install g fnpm err could not create usrlocallibnode modules npmnpmnpm err error installing error eaccess undefined error 0 usrlocallibnode modulesnpm err error eaccess undefined error 0 usrlocallibnode modulesnpm err report this entire log atnpm err npm err or email it tonpm err npm err npm err system darwin 1100npm err command node privatevarfoldersz2f05c8hx105g79drh6r7hr01w0gntnpm1219packageclijs install g fnpm err cwd privatevarfoldersz2f05c8hx105g79drh6r7hr01w0gntnpm1219packagenpm err node v v059prenpm err npm v 1094npm err path usrlocallibnode modulesnpm err code eaccessnpm err npm err additional logging details can be found innpm err privatevarfoldersz2f05c8hx105g79drh6r7hr01w0gntnpm1219packagenpmdebuglognpm not okmake install error 1npm err could not create usrlocallibnode modules npmnpmnpm err error installing error eaccess undefined error 0 usrlocallibnode modulesnpm err error eaccess undefined error 0 usrlocallibnode modulesnpm err report this entire log atnpm err npm err or email it tonpm err npm err npm err system darwin 1100npm err command usrlocalbinnode privatevarfoldersz2f05c8hx105g79drh6r7hr01w0gntnpm1219packageclijs install gfnpm err cwd privatevarfoldersz2f05c8hx105g79drh6r7hr01w0gntnpm1219packagenpm err node v v059prenpm err npm v 1094npm err path usrlocallibnode modulesnpm err code eaccessnpm err npm err additional logging details can be found innpm err privatevarfoldersz2f05c8hx105g79drh6r7hr01w0gntnpm1219packagenpmdebuglognpm not okit failedthere is obviously a folder issue here perhaps i am installing in the wrong place my node folder is at usersmikenode when i try and find out my node path variable using node path i get the following errormichaelsmacbookpro mike node nodenode path nodejs203 throw e processnexttick error or error event on first tick error cannot find module usersmikenodenode path at function resolvefilename modulejs33411 at function load modulejs27925 at arrayanonymous modulejs47010 at eventemitter tickcallback nodejs19526can someone please tell me what i am doing wrong do i need to add the node path like such export pathpathtonode0nybinpath curl shor am i confusing myself,['javascript'] +202525,gridview and excess space padding i have a problem with grid view layout on android i cannot find solution to eliminate extra space in grid view i tried a lot of things numcolumns columnwidth stretchmode gravity and advices from stackoverflow but nothing works correctly i spent almost 8 hours with this problem here is a code of grid viewgridview androidididlookbook gridview androidlayout widthfill parent androidlayout heightwrap content androidlistselectornull androidpadding0dip androidlayout margin0dip androidverticalspacing0px androidhorizontalspacing0px androidnumcolumnsauto fit androidcolumnwidth160px androidstretchmodecolumnwidth androidgravitycenter androidlayout gravitycenter androidbackground0 androidcachecolorhint0 androiddescendantfocusabilityafterdescendants androidlayout alignparenttoptrue androidlayout aboveidbuttons gridview i also tried to reduce extra space programicallyprivate void setgridview gridview gridview gridview findviewbyidridlookbook gridview thisplay thisplay windowmanager getsystemservicewindow servicegetdefaultthisplay int gridsize thisplaygetwidth int count gridsize 160 image has 160x160 px int colwidth gridsize count padding gridviewsetcolumnwidthcolwidth gridviewsetnumcolumnscountbut it works only on my htc desire right but on emulator left with the same thisplay resolution and the same api version it is not workingdoes somebody know how to set images in gridview without any special padding or space to work successfully with all resolutions and devices,['android'] +202562,the essential difference among html tags the b tag make texts bold but if assigned with css fontweightnormal then it is absolutely like a normal tag on the other hand the i tag can be styled to thisplay the text inside like a b tagi stylefontstylenormal fontweightboldyeah i am talking about the interchangeability of html tags so we can have fewer tagsand 2 of the most famous tags turn out to be div and span which are thiscussed in this so question what is the difference between html tags div and spani want to know what is the essence of the div tag that makes a span tag like thisspan stylethisplayblockspancannot be a replacement for div by another respect whats the deep reason behind make these code become invalid xhtmlspan stylethisplay blockpstill wrongpspanthanksfor the scenario i am building a socalled htmlcssgenerator which requires deep knowledge of html tags i want to filter the sets of all valid html tags to make a set of major tags then i am asking for the interchangeability of the tagsupdate the ultimate goal of this questioni wonder if the difference was that the tag is natively blocklevel like divp or inlinelevel like span is there any other kind of native property that css or js cannot change like blockinlinelevel for the html tags,['html'] +202566,mysql accent insensitive and dotted insensitive search the problem i am trying to implement a search algorithm that shows the results even when dotted chars are provided in other words select a14ber uber or select mas maa these results will return true this would apply for every single char in the following arrayarr arraya s a c a o a14 u and so on the solution in my mind along with the original column i can have a particular column that stores the english names so before storing a14ber to database i will also convert it to uber in php and then will store both a14ber as the original and uber as the searchable to the databasebut then even though i have searched for this the whole day i still believe that there should be a simplier and cleaner way to accomplish the task since this would mean more or less to store the same data twice in the database so guys what do you think is the solution the only way to go or you know a better approach editfor accent insensitive i have seen the posts on so they are working but since i am also considering the dotted chars i had to ask this questionedit2i cannot post the whole table structure and code exactly for some reasons but i will provide a close example myusers create table myusers id int auto increment not null primary keyemail varchar100 collate latin1 general ci not nullfullname varchar75 collate latin1 general ci not nullprimary keyid enginemyisam auto incremenet2 default charsetlatin1 collate latin1 general ci the above is the structure of the table here comes the inserts and selectsinsert into myusers fullname values aga14edainsert into myusers fullname values aguedaselect from myusers where fullname aga14eda collate latin1 general ci id email fullname 1 aga14eda 1 row in set 0 secselect from myusers where fullname agueda collate latin1 general ci id email fullname 2 agueda 1 row in set 0 secwell the desired result is obviously when agueda is searched both agueda and aga14eda will return but that is not the case as i mentioned above i have created a new column and store the whole name in english characters and make the search from there as well but still it costs me a two times search because i am also searching from the original columns which rank higher in the search result there should be a better way,"['php', 'mysql']" +202571,how do user annotations work i am still fairly new to java programming and i was looking over a open source project and came across thispublic tilenetworkdata int progresspart 0 i have seen the use of before but only to do things like override before a member to my surprise looking up the definition it brought me to user codeimport javalangannotationinheritedimport javalangannotationretentionimport javalangannotationretentionpolicyretentionretentionpolicyruntimeinheritedpublic interface tilenetworkdata int staticsize default 1 what is this code doing and what is it useful for it looks like it is adding some form of metadata to the field how is something like this useddoing some googleing i found this is called annotations but everything attached to it went over my head any kind of example where something like this would be used would be appreciated,['java'] +202597,apple push notification connection issue key value mismatch check private key message i am trying to test push notifications for my app but cannot connect to the apple sandbox with my certificate and private key i am following this tutoriali set up a new certificate and app id per the tutorial set up a private key and generated the pem files for the certificate and the private keyopenssl x509 in aps developer identitycer inform der out pushtestcertpemopenssl pkcs12 nocerts out pushtestkeypem in pushtestkeyp12 for the private key it asks me to enter the original password the key as well as a new one i used the same passwordthen i test the connection to apple and am prompted for my password and i enter the new password for the key pem file which is the same as the old passwordopenssl s client connect gatewaysandboxpushapplecom2195 cert pushtestcertpem key pushtestkeypementer pass phrase for pushtestkeypemerror setting private key59244error0b080074x509 certificate routinesx509 check private keykey values mismatchsourcecacheopenssl098openssl098351srccryptox509x509 cmpc406is there something i am missing on the ios provisioning portal my app id says it is enabled for development push i have tried redownloading the openssl certificate no cigar,"['iphone', 'ios']" +202633,get gps location in a broadcast receiveror service to broadcast receiver data transfer i am new to androidi want to get gps location in a broadcast receiver but it shows an errormy code is public void onreceivecontext context intent intent locationmanager locmanager locationmanager getsystemservicecontextlocation service errors in getsystemservice method locationlistener loclistener new mylocationlistener locmanagerrequestlocationupdateslocationmanagergps provider 0 0 loclistener location loc locmanager getlastknownlocationlocationmanagergps provider logd location location locgetlatitudequestions is it possible to get gps location data in broadcast receiver another alternative way i tried so far was to use a service which is invoked by the broadcast receiver the service can get gps data but how can i get it in the broadcast receiver,['android'] +202644,jquery ui datepicker enable only specific days in array i am trying to thisable all dates in a datepicker and only enable dates which are in an array this is the code i have so far the problem is only may 14th shows up as enabled the others are all thisabled any ideas var availabledates 9520145201552011function availabledate dmy dategetdate dategetmonth1 dategetfullyear if inarraydmy availabledates 1 return true available else return falseunavailable datedatepicker beforeshowday available,['jquery'] +202649,uitextfield format in x i am using uitextfield and i want that should take character in the format of x only numbersany help,"['iphone', 'objective-c', 'ios']" +202674,wcf performance latency and scalability i am trying to port a simple async tcp server in f to c 4 the server receives a connection reads a single request and streams back a sequence of responses before closing the connectionasync in c 4 looks tedious and error prone so i thought i would try using wcf instead this server is not unlikely to see 10 simultaneous requests in the wild so i think both throughput and latency are of interesti have written a minimal duplex wcf web service and console client in c although i am using wcf instead of raw sockets this is already 175 lines of code compared to 80 lines for the original but i am more concerned about the performance and scalabilitylatency is 154 worse with wcfthroughput is 54 worse with wcftcp handles 10 simultaneous connections easily but wcf chokes on just 20firstly i am using the default settings for everything so i am wondering if there is anything i can tweak to improve these performance figuressecondly i am wondering if anyone is using wcf for this kind of thing or if it is the wrong tool for the jobheres my wcf server in ciservice1csdatacontractpublic class stock datamember public datetime firstdealdate get set datamember public datetime lastdealdate get set datamember public datetime startdate get set datamember public datetime enddate get set datamember public decimal open get set datamember public decimal high get set datamember public decimal low get set datamember public decimal close get set datamember public decimal volumeweightedprice get set datamember public decimal totalquantity get set servicecontractcallbackcontract typeofiputstockpublic interface istock operationcontract void getstockspublic interface iputstock operationcontract void putstockstock stockservice1svc servicehost languagec debugtrue serviceduplexwcfservice2stocks codebehindservice1svccs service1svccs servicebehaviorconcurrencymode concurrencymodemultiple public class stocks istock iputstock callback region istock members public void getstocks callback operationcontextcurrentgetcallbackchanneliputstock stock st null st new stock firstdealdate systemdatetimenow lastdealdate systemdatetimenow startdate systemdatetimenow enddate systemdatetimenow open 495 high 495 low 495 close 495 volumeweightedprice 495 totalquantity 495 for int i0 i10 i callbackputstockst endregion webconfigxml version10configuration systemweb compilation debugtrue targetframework40 systemweb systemservicemodel services service nameduplexwcfservice2stocks endpoint address bindingwsdualhttpbinding contractduplexwcfservice2istock identity dns valuelocalhost identity endpoint endpoint addressmex bindingmexhttpbinding contractimetadataexchange service services behaviors servicebehaviors behavior servicemetadata httpgetenabledtrue servicedebug includeexceptiondetailinfaultstrue behavior servicebehaviors behaviors servicehostingenvironment multiplesitebindingsenabledtrue systemservicemodel systemwebserver modules runallmanagedmodulesforallrequeststrue systemwebserverconfigurationheres the c wcf clientprogramcs callbackbehaviorconcurrencymode concurrencymodemultiple usesynchronizationcontext false class callback duplexwcfservice2istockcallback systemdiagnosticsstopwatch timer int n public callbacksystemdiagnosticsstopwatch t timer t and 0 public void putstockduplexwcfservice2stock st n if n 1 consolewritelinefirst result in thistimerelapsedtotalseconds s if n 10 consolewriteline10 results in thistimerelapsedtotalseconds s class program static void testint i var timer systemdiagnosticsstopwatchstartnew var ctx new instancecontextnew callbacktimer var proxy new duplexwcfservice2stockclientctx proxygetstocks consolewritelinei connected static void mainstring args for int i0 i10 i int j i new systemthreadingthread testjstart heres my async tcp client and server code in ftype aggregateddeals firstdealtime systemdatetime lastdealtime systemdatetime starttime systemdatetime endtime systemdatetime open decimal high decimal low decimal close decimal volumeweightedprice decimal totalquantity decimal let read stream systemiostream async let header streamasyncread 4 let length systembitconvertertoint32header 0 let body streamasyncread length let fmt systemruntimeserializationformattersbinarybinaryformatter use stream new systemiomemorystreambody return fmtdeserializestreamlet write stream systemiostream value async let body let fmt systemruntimeserializationformattersbinarybinaryformatter use stream new systemiomemorystream fmtserializestream value streamtoarray let header systembitconvertergetbytes bodylength do streamasyncwrite header do streamasyncwrite bodylet endpoint systemnetipendpointsystemnetipaddressloopback 4502let server async let listener systemnetsocketstcplistenerendpoint listenerstart while true do let client listeneraccepttcpclient async use stream clientgetstream let streamasyncread 1 for i in 110 do let aggregateddeals firstdealtime systemdatetimenow lastdealtime systemdatetimenow starttime systemdatetimenow endtime systemdatetimenow open 1m high 1m low 1m close 1m volumeweightedprice 1m totalquantity 1m do write stream aggregateddeals asyncstartlet client async let timer systemdiagnosticsstopwatchstartnew use client new systemnetsocketstcpclient clientconnect endpoint use stream clientgetstream do streamasyncwrite 0uy for i in 110 do let read stream if i1 then lock stdout fun printfn first result in fs timerelapsedtotalseconds lock stdout fun printfn 10 results in fs timerelapsedtotalsecondsdo server asyncstart seq for i in 1100 client asyncparallel asyncrunsynchronously ignore,['c#'] +202679,how to declare an immutable property backed by a mutable type iad like to declare a public immutable propertyinterface foopropertystrong readonly nsset itemsendabacked with a mutable type in the implementation fileinterface foo private interfacepropertystrong nsmutableset itemsendimplementationsynthesize itemsendwhat i want is a mutable collection in the implementation that gets cast into an immutable one when accessed from the outside i donat care that the caller can cast the instance back to nsmutableset and break the encapsulation i live in a quiet decent town where such things donat happenright now my compiler treats the property as nsset inside the implementation i know there are many ways to get it working for example with custom getters but is there a way to do it simply with declared properties,['objective-c'] +202698,getting height and width of a text using canvas i am developing an android 22 applicationi am using this method to draw a text in a view public void drawcanvas c psetcolorcolorwhite ifname null cdrawtextname getleft gettop p how can i get height and width of name textif i do this p is a paint objectpgettextboundsname 0 namelength boundsi get with name loading bounds rect1 10 42 3i do not know why i get this strange rectangleany cluethis is my possible solutionpublic class myview extends arsphericalview public string name public myviewcontext ctx superctx inclination 0 public void drawcanvas c psetcolorcolorwhite ifname null cdrawtextname getleft gettop p psetcolorcolorblack ifname null rect bounds new rect cdrawtextname getleft gettop p setbackgroundcolorcolorwhite pgettextboundsname 0 namelength bounds cdrawrectbounds p but it does not work i get that strange rectangle,['android'] +202707,prevent text from overflowing a padded container in html i have this situationdiv stylewidth 100px padding 5px 15px 5pxsome text longer than 100pxdivif i set overflow hidden on the div the text will still go outside the 15px padded area on the rightthis text should stop here but ican this be done without putting an extra element inside to hold the text any solution in any browser will do i just want to know if it is possible,"['html', 'css']" +202715,how to reference a bean of another xml file in spring i have a spring bean defined in an xml file i want to reference it from another xml file how can i go about it,['java'] +202746,opening and creating password protected zip files with php i have found the following two commands to respecively create and open password protected zip files i was however wondering if it is possible to do this in pure phpecho systemzip p password filezip filetxt echo shell execunzip p password filezip,['php'] +202757,run as android application is missing sdk and adt are installed and working but when i run some android code the run as panel is empty i need to go to run configuration click on android application make a copy put the name of my project on the copy and the run it then it run properly on the emulator how can i add the android application item menu inside the run as menu,"['java', 'android']" +202801,custom monolog logging channel in symfony2 command in this cookbook article we can see how to use a custom channel in a service but how can i use a custom login channel in a command i created a symfony2 command to perform something i would like to use monolog to log things done by my command actually i want to write log for my command in another file than the logs of the application,['php'] +202820,is zero ever a valid handle there is a safehandlezeroorminusoneisinvalid class in the net framework as well as a safehandleminusoneisinvalid classwhy is this in which situations is zero ever a valid handle,['.net'] +202856,why is a 1 character net string 32 bytes in x64 i have been trying to figure out the overhead of a string in net 4 x64 this is what i have got so far16 byte object header for x644 bytes for the stringlength field arraylength is gone in net 4length 1 2 bytes for the string content utf16 null terminatedso youd expect a 1 character string to be 16 4 4 24 bytes it is divisible by 8 so it should not need any paddingbut when i look at the sizes in windbg i see them taking 32 bytes when i dumpobject them they say their size is 28 bytes which is what i assume is getting rounded up to 32 whats going on is there another round of memory alignment happening,['.net'] +202871,how to convert 2d list to 2d numpy array i have a 2d list something like a 1 2 3 4 5 6 7 8 9 and i want to convert it to a 2d numpy array can we do it without allocating memory like numpyzeros33and then storing values to it,['python'] +202897,why i cannot use code files from app code in my code aspnet c i am working on an aspnet web app and i have few classes in my app code but for some reason i cannot use any of them in my code i tried using the same namespace i tried without any namespace in both files but nothing helps this is my page codeusing systemusing systemcollectionsgenericusing systemlinqusing systemwebusing systemwebuiusing systemwebuiwebcontrolsusing linkedinusing linkedinserviceentitiesnamespace authentication public partial class linkedinmoreinfo linkedinbasepage protected void page loadobject sender eventargs e and my code in the classusing systemusing systemdatausing systemconfigurationusing systemlinqusing systemwebusing systemwebsecurityusing systemwebuiusing systemwebuihtmlcontrolsusing systemwebuiwebcontrolsusing systemxmllinqusing linkedinnamespace authorisation public class linkedinbasepage systemwebuipage private string accesstoken get return stringsessionaccesstoken set sessionaccesstoken value private inmemorytokenmanager tokenmanager get var tokenmanager inmemorytokenmanagerapplicationtokenmanager if tokenmanager null string consumerkey configurationmanagerappsettingslinkedinconsumerkey string consumersecret configurationmanagerappsettingslinkedinconsumersecret if stringisnulloremptyconsumerkey false tokenmanager new inmemorytokenmanagerconsumerkey consumersecret applicationtokenmanager tokenmanager return tokenmanager protected weboauthauthorization authorization get private set protected override void onloadeventargs e thisauthorization new weboauthauthorizationthistokenmanager thisaccesstoken if ispostback string accesstoken thisauthorizationcompleteauthorize if accesstoken null thisaccesstoken accesstoken responseredirectrequestpath if accesstoken null thisauthorizationbeginauthorize baseonloade any idea what can be the problemthanks in advance,"['c#', 'asp.net']" +202920,python setuppy sthist error operation not permitted i am trying to create a python source package but it fails when creating hard links for files python setuppy sthistrunning sthistrunning checkreading manifest template manifestinwriting manifest file manifestmaking hard links in foo01hard linking readmetxt foo01error operation not permittedi have tried running the command with sudo but it produces the same errorthis also produces the same errorln foo bari am using vbox to run a virtual instance of ubuntu which is probably where the problem comes from is there a way round using hard links when creating source thistributionssystem informationubuntu server 1104virtualbox 414osx 1066python 271,['python'] +202930,designing a rails application single table inheritance i have been researching this for a few days now and i know there is an abundance of articles that talk about single table inheritance and polymorphic associations with rails a lot of helpful material is from 2009 or before and i am wondering if there is a better approach to this problem nowthe situationthe application has a couple of different user types ie buyer and seller each of which have a profile the profile for each user type is really different so i am currently ruling out the idea of one generic profile tablemy current approachwhich is the same as this solutionclass user activerecordbase authentication stuffendclass usertype1 user has one user type 1 profileendclass usertype2 user has one user type 2 profileendclass usertypen user has one user type and profileendbased on my research this is kind of a mixed model designhonestly at this point i do not know of any other solution that would work every time i have seen similar questions asked i see the idea of polymorphic associations brought up could someone elaborate how a polymorphic association would work in this casedoes anyone have any other design suggestions,['ruby-on-rails'] +202943,nsdate independent of timezone i have an app that thisplays a timetable of certain ferry tripsif i travel to a different timezone say 4 hours behind a 10am ferry trip now shows up as 6ami know this has got to do with how dates are treated based on their timezones but i cannot work out how to change that behaviourat the moment heres how i am getting the date and thisplaying it on a uilabelnsdateformatter dateformatter nsdateformatter alloc initdateformatter setdateformathhmmselfdeparturetime settextdateformatter stringfromdateselfroute objectforkeydeparturetimeselfarrivaltime settextdateformatter stringfromdateselfroute objectforkeyarrivaltimedateformatter releasethanks in advance for your help,"['iphone', 'objective-c', 'ios']" +202965,how to align the absolute position to center i am trying to stack two canvas together and make it a double layers canvasi have saw an example herediv styleposition relative canvas idlayer1 width100 height100 styleposition absolute left 0 top 0 zindex 0canvas canvas idlayer2 width100 height100 styleposition absolute left 0 top 0 zindex 1canvasdivbut i would like to set both of the canvas align at the center of the screen if i set the value of left as a constant while i change the orientation of the screen as i am doing aps on ipad the canvas would not remain at the middle of the screen like how it act in div aligncentercan anyone please help,['css'] +202982,using javascript closures in settimeout i am using settimeout to emulate rendering and i came to the structure like thisvar renderer new class implements events initialize thisonrender onrender function some rendering actions settimeoutthisonrenderbindthis 20 does that code have potential memory leaks because of infinite nesting of closures or everything is ok the only solution i came so far is to rewrite it to usualfunction renderer var onrender function rendering settimeoutonrender 20 onrenderbut i do not want to lose mootools events and classesfor some reasons i cannot use a singleton like windowrenderer new renderer too,['javascript'] +203004,when do you use self in python are you supposed to use self when referencing a member function in python within the same module more generally i was wondering when it is required to use self not just for methods but for variables as well,['python'] +203012,ruby on rails why do i get message for javascript and css after rails s rails sstarted get assetsapplicationcssbody1 for 127001 at 201011 033703 0900served asset applicationcss 304 not modified 0msstarted get assetshomecssbody1 for 127001 at 201011 033703 0900served asset homecss 304 not modified 0msstarted get assetsjquery ujsjsbody1 for 127001 at 201011 033703 0900served asset jquery ujsjs 304 not modified 0msstarted get assetsjqueryjsbody1 for 127001 at 201011 033703 0900served asset jqueryjs 304 not modified 0msstarted get assetshomejsbody1 for 127001 at 201011 033703 0900served asset homejs 304 not modified 0msstarted get assetsapplicationjsbody1 for 127001 at 201011 033703 0900served asset applicationjs 304 not modified 0msi get these message every time when page reloadshow can i get rid of this message,"['ruby-on-rails', 'ruby']" +203068,max size of url parameters in get i am accessing a php server using rest all data is passed in a get request as url parameters one of the parameters arrives at the server in the query string but it is not in the get global but shortening the parameter the cutoff seems to be around 512 characters lets it throughassuming i have diagnosed the problem correctly is there a way to change this maximum size i have not found any explanation in the documentation not even a mention of this limit this is on debian squeeze apache 2216 php 533,['php'] +203098,how to use convertchangetype when conversiontype is decimal and input is 40 i mean i want to convert thisstring a 40convertchangetypea typeofdecimalthe result is a decimal value of 40the problem is that the convert call is in a very abstract generic method in a xmltoobject converter i do not want to add programmatically lots of different exceptions to convert correctlyregards chris,"['c#', '.net']" +203100,double dotted border while using colspan i have what seems like a simple problem but searching the net has not yielded any resultsi have a tabletable tr td colspan3 img srcsomethingpng td tr tr td hello td td world td td td trtablethe tr elements all have bordertop dotted 1px black this works fine apart from the central td element in the second trthis element has a double border and so appears as a solid line removing the colspan fixes the issue i have tried applying bordercollapse collapse to the the table and this has not worked i have tried adding content in the form of nbsp inside the first td instead of an image and this has not worked eitherany ideas anyonethanksjake,"['html', 'css']" +203109,c winforms difference between doubleclick event and mousedoubleclick event quick question hereas the title says whats the difference between the two eventsas far as i can tell mousedoubleclick is inherited from control while doubleclick is inherited from component but is there any functional difference between the twothanks,['c#'] +203117,rotating a layout and after placing in relativelayout prblem i need to rotate a layout has a textview and imageview and it should be placed align right and top in relativelayout i create my layout this layout is placed righttop but if i rotate it i cant align right what should i domy relative layout relativelayout xmlnsandroid androidlayout widthwrap content androidbackgrounddrawablebackground androidlayout heightwrap content androidididtestrl relativelayout androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentrighttrue androidlayout alignparenttoptrue androidididtestrotatell imageview androidlayout heightwrap content androidlayout widthwrap content androidbackgrounddrawablepicture border offer first page textview androidlayout heightwrap content androidlayout widthwrap content androidtext70tl androidtextsize15sp androidlayout centerinparenttrue androidtextcolorandroidcolorwhite androidididamountlayouttv relativelayoutrelativelayoutand i rotate this linearlayout with animation this rotates good rotate xmlnsandroid androidfromdegrees0 androidtodegrees45 androidpivotx50 androidpivoty50 androidfillenabledtrue androiddetachwallpapertrue androidduration0 androidfillaftertruerotateafter rotate new visial is,['android'] +203149,store int in arraylist and get it back to primitive variable int java i am getting an error and cannot find out how to solve iti add a int to an arraylistint and 1arraylist list new arraylistlistadd and further down i try to put it back in another intgrid y x listget0i also tried thisgrid y x int listget0but it does not work i get this errorfound javalangobjectrequired intgrid y x intlistget0 i hope someone can help me,['java'] +203159,c linq where clause according to property name let us say i have the following class public class person public string firstname get set public string surname get set public int age get set public string gender get set also i have the following method and i am reaching out to person data via a repositorypublic ienumerableperson getpeoplestring searchfield string searchterm repogetall returns ienumerableperson var model repogetall need the logic here for filtering return modelas you can see i am getting two parameter for the method searchfield and searchterm searchfield is for the field name whose value will be used for filtering searchterm is the value which will be used to compare with retrived value sorry if i am not clear here but this is the most i can come up withwhat i would normally do is as follows public ienumerableperson getpeoplestring searchfield string searchterm repogetall returns ienumerableperson var model repogetall switchsearchfield case firstname model modelwherex xfirstname searchterm break case surname model modelwherex xsurname searchterm break keeps going return modelwhich will work just fine but if i make a change on my class this code will have a change to break or be in lack of some functions if i add new properties this classwhat i am looking for is something like below note this below code completely belongs to my imagination and there is no such a thing existsmodel modelwherex xgetpropertybynamesearchfield searchtermam i flying too high here if it is impossible or being complete idiot if there is already a built in way for this,"['c#', 'asp.net']" +203177,how can i enforce a void method to return void from a stub object how can i enforce a stub object in rhinomocks to return void for a void method on ittake this examplepublic interface icar string model getset void hornicar stubcar mockrepositorygeneratestubicarstubcarexpectcchornreturn now what so that it returns nothing as the meth returns void,['c#'] +203183,configure spring security to use custom usernamepasswordauthenticationfilter i have implemented my own lowercaseusernamepasswordauthenticationfilter that is just a subclass of usernamepasswordauthenticationfilterbut now my problem is how to configure spring security to use this filterup to now i usedsecurityhttp autoconfigtrue useexpressionstrue securityformlogin loginprocessingurlresourcesj spring security check loginpagelogin authenticationfailureurlloginlogin errort securitylogout logouturlresourcesj spring security logout securityintercepturl pattern accessisauthenticated requireschannelcfmasecuritychannel securityhttpdo i really to turn of autoconfig and need to configure all the filters by hand if this is true does anybody can provide an example pleasethe way to add simply a securitycustomfiltersecurityhttp securityformlogin loginprocessingurlresourcesj spring security check loginpagelogin authenticationfailureurlloginlogin errort securitycustomfilter reflowercaseusernamepasswordauthenticationfilter positionform login filter securityhttpdoes result in an exception with that messageconfiguration problem filter beans lowercaseusernamepasswordauthenticationfilter and root bean class orgspringframeworksecuritywebauthenticationusernamepasswordauthenticationfilter scope abstractfalse lazyinitfalse autowiremode0 dependencycheck0 autowirecandidatetrue primaryfalse factorybeannamenull factorymethodnamenull initmethodnamenull destroymethodnamenull have the same order value when using custom filters please make sure the positions do not conflict with default filters alternatively you can thisable the default filters by removing the corresponding child elements from and avoiding the use of,['java'] +203188,drawing custom lines on highchart graph i have recently been working with the highchart api to plot some data on a website and i have need to be able to add a custom vertical line to symbolise something happening for example a press releasei have thought about adding a column element to the chart as a seperate series but this is less than idealif anyone has any ideas that would be awesomethanks,"['javascript', 'jquery']" +203203,camel routes and endpoints i have been pouring over the apache camel docs trying to get a concrete understanding of two of its most basic concepts endpoints and routes and although these terms are used everywhere throughout the docs i can find no reference that actually defines what they are and what they are used for and although their names are fairly obvioussounding and i think i understand what they are i have now been assigned to a task that has landed me neckdeep in apache camel land and its absolutely vital that i understand what these mechanisms aremy guess is that an endpoint is just a bean one that can be configured in a config file like any other that maps a name to a uriport combo this taken from the w3c docs in the context of apache camel my guess is that endpoints are used to connect components together so that routes connectionsmaps can be formed between them so when component a living at endpoint 1 wants to communicate with component b living at endpoint 2 so long as there is a mapping from 1 to 2 camel will be able to transmit messages between these twoplease stop me and correct me if i am wrong hereso now i have seen examples where it looks like routes can be configured in javafromendpointarouteidsomemessagetoendpointband i have seen examples where it looks like routes can be configured in xmlroute id from to routeare these two methods for configuring routes or are they different concepts altogetherfinally what is the format of the messages that can be routed between endpoints if it has to be xml for example what is the xsdschema of these routed messages if it has to be a java object what boundsrestrictions apply to the objects that camel can sendthanks in advance for any clarity on these simple terms that i truly cannot find simple explanations for,['java'] +203209,how to sign an android app for the market i have recently released my first app on the market i tried to install the app on my phone immediately after it was released but when installing it i got an error saying that the app was wrongly signed i also got lots of bad ratings for my app because other people could not install it as wellso my question is how can i sign my app correctly is there any way to test the result before releasing the app on the marketbtw i used the built in function of eclipse to export the signed apk file,['android'] +203223,java best practices in matrixvector library i have to write a simple vectormatrix library for a small geometry related project i am working on heres what i am wonderingwhen doing mathematical operations on vectors in a java environment is it better practice to return a new instance of a vector or modify the state of the originali have seen it back and forth and would just like to get a majority input certain people say that the vectors should be immutable and static methods should be used to create new ones others say that they should be mutable and normal methods should be used to modify their state i have seen it in some cases where the object is immutable and normal methods are called which returns a new vector from the object without changing the state this seems a little off to mei would just like to get a feel for if there is any best practice for this i imagine it is something that is been done a million times and am really just wondering if there is a standard way to do thisi noticed the apache commons math library returns a new vector every time from the original,['java'] +203245,data structure with efficient manipulation and retrieval by both key and index i am looking for a data structure with the functionality of eg the ordereddictionary in net that is to say an associative collection ie one that associates a key with a value that maintains element order just like a normal list does it must have fast lookup by both index and key it should also have a fast append operation inserting a new item at the end and fast removal of items with any index based on either index or keythe ordereddictionary in net uses both a hash table and an array to store its items if i am not mistaken retreiving an index based on a key or vice versa is therefore on and of course removal of an item from the middle of an array is on to start with plus the added lookup of the index from the key if removing by keymy question is if there exists a more efficient data structure that satisfies my conditions or if this is indeed my best option here,['.net'] +203256,how can i use urls in a singlepage application this article makes a pretty convincing argument that because urls are longlived they get bookmarked and passed around they should be meaningful and that using the hash for real routing determining what data is shown on the page andor the state of the application is thus improper when i try to actually do that in my singlepage application though i run up against a problem how do i render my links so that all browsers can use the application as i see it there are three optionsall hrefs have a prefix this works great in html4 browsers in html5 browsers i can add a sammy route that redirects to the hashless version which also works great there might be a problem with browsers marking links as visited when they are not or not marking them visited when they are the other problem is that it is wrong anyone who shares a link by rightclicking it and selecting copy link url will be sending a working but kludgy url aroundno hrefs have a prefix as far as i can tell html4 browsers will have no way of intercepting these link clicks which means that every one will cause a page refresh though the application would probably still function since i could use sammy routes to rewrite the hashless versions to hashy ones on page load the page loads would kill the performance of the singlepage applicationi dynamically determine whether to prefix with or not this means that all of my links have to have dynamic markup and dramatically complicates the application,['javascript'] +203308,text in border css html i would like to have a div that looks like thisis this possible to do with html css i will also be animating this div with jquery when the div is hidden i would like the title and the top line to show,"['html', 'css']" +203358,python suds return type other than xml i am working with a somewhat nonstandard soap webservice most of the calls to the webservice return the standard soap xml as you would expect but one call in particular returns a json string instead this fouls up the xml parser on the client sidemy question is is there a way to designate the return type on a particular webmethod in suds so that it does not try to run it through the xml parser i just want the raw json response,['python'] +203372,how to determine in applicationdidbecomeactive whether it is the initial iphone app launch how to determine in how to determine in uiapplicationdidbecomeactivenotification whether it is the initial app launchwhether it is the initial app launchthat is the initial start up of the application as opposed to subsequent didbecomeactives due to the application being put in background and then to foreground eg user goes to calendar then back to your app,"['iphone', 'ios']" +203387,what to use instead of filereader for safari am new to web programming so apologies for any lack of rudimentary knowledgemy page allows a user to select a file that is then read clientside thisplayed in a textbox on the page the easiest way i found to do this was to use a filereader object which works fine in firefox and chromethis does not work in safari yet so what should i do insteadwhen the eventlistener detects a change in the input filevar file evttargetfiles0var reader new filereaderreaderonload function edocumentgetelementbyiddatavalue etargetresultreaderreadastextfilerelevant notesi am working with safari for windowsright now the page is local as is the file to read chrome had issues with this until i used the flag allowfileaccessfromfiles,['javascript'] +203392,how can i do member registration confirmation how can i register with cakephp after registering it will send email for confirmationif i click the link for confirmation then the account will be confirmedhow can i do thisis there any function with auth to do thator do i have to send mail manually to confirm registration if i have to send email manually to confirm registration then how can i generate the registration token and how can i set time to be a valid token can anyone show an example of this,['php'] +203412,tried to register widget with idvalores0 but that id is already registered i get this error and i do not know how can be solved i read this link beforeedit1indexphp script typetextjavascriptdocumentreadyfunction customformsubmitfunction var formdata customformserializearray ajax url sentphp type post datatype json data formdata success functiondata switch datalivre case tags msgbox2fadeto200 01 function thishtmlempty tagsfadeto900 1 break default msgbox2fadeto200 01 function thishtmlupdatefadeto900 1 function conteudoloaddojotest sliderphp break return false scripttest sliderphpscript typetextjavascriptvar slider for i 0 i 5 i slideri functioni return function var node dojobyidinputi var and dojobyidvaloresi var rulesnode documentcreateelementdivi nodeappendchildrulesnode var sliderrules new dijitformhorizontalrule count11 styleheight4px rulesnode var labels new dijitformhorizontalrulelabels styleheight1emfontsize75 n var theslider new dijitformhorizontalslider value5 onchange function consolelogarguments nameinputi onchangefunctionval dojobyidvalueivalue dojonumberformat1valplaces4 styleheight165px minimum1 maximum9 node thesliderstartup sliderrulesstartup i dojoaddonloadslideriscriptproblem first click in submit btn all works well 5 sliders are imported second click an update is supposed but i get this messagetried to register widget with idvalores0 but that id is already registereddemo video2,['javascript'] +203447,marshalgetactiveobject throws mk e unavailable exception in c the following vbscript code works prefectly finedim app set app getobjectquicktestapplicationappquitbut when i translate it into c code as belowclass program stathread static void mainstring args object qtapp marshalgetactiveobjectquicktestapplication qtapp as quicktestapplicationquit i get the exceptionan unhandled exception of type systemruntimeinteropservicescomexception occurred in mscorlibdlladditional information exception from hresult 0x800401e3 mk e unavailablei do not think the problem is related to rot because the vbscript code works so what is wrong with the c code,['c#'] +203461,raphael paper zoom animation i manage to do some hack in order to zoom raphael paper as setviewbox was not working for me here is the function i wrote function setctmelement matrix var s matrix matrixa matrixb matrixc matrixd matrixe matrixf elementsetattributetransform sraphaelfnzoomandmove functioncoordxcoordyzoom var svg documentgetelementsbytagnamesvg0 var z zoom var g documentgetelementbyidviewport1 var p svgcreatesvgpoint px coordx py coordy p pmatrixtransformggetctminverse var k svgcreatesvgmatrixscaleztranslatepx py setctmg ggetctmmultiplyk where the viewport1 element was defined as var gelem documentcreateelementns g gelemid viewport1 papercanvasappendchildgelem papercanvas gelemthen i can call paperzoomandmoveminxminyzoomratiois it possible to transform the function to make it zoom smoothly thx by advance,['jquery'] +203472,prevent memory leaks in wpf working with winforms you have to free memory after using gdi objects event handlers objects from native code etcin winforms i used to remove for example event handlers in the thispose methodwhat is the best workaround to prevent memory leaks in wpf is it the same as in winforms using thispose pattern at all do i have to care about event handlers gdi objects in wpf what about the runtime created resourcesbrushes etc,['c#'] +203490,maven plugin not using eclipses proxy settings i am using springsource tool suite 272 based on eclipse 37 the maven plugin comes now out of the box with eclipse which is great and this problem occured even with previous version of eclipseso here is my issuei have set the proxy information in my settingsxml file and in command line maven works just fine i have also set the same proxy details in the eclipse configuration itself and i know that it is correct as well as the updates work with it and not withoutof course the maven plugin in my eclipse is set to use the proper settingsxml filebut maven from within eclipse just does not use the proxy settings from either of those places which is very annoying every time i change the pom filedoes anyone have a solution for this issue settingsxmlhere is my settingsxml filexml version10 encodingutf8 settings xmlns xmlnsxsi xsischemalocation profiles profile idgeneralid repositories repository snapshotsenabledfalseenabledsnapshots idibiblioid namemaven ibiblioname urlurl repository repository snapshotsenabledtrueenabledsnapshots idibiblio2id namemaven ibiblio2name urlurl repository repository snapshotsenabledtrueenabledsnapshots idmavenid namemaven sunsitename urlurl repository repository snapshotsenabledtrueenabledsnapshots idjbossid namemaven jbossname urlurl repository repositories profile profiles activeprofiles activeprofilegeneralactiveprofile activeprofiles proxies proxy idproxyid activetrueactive protocolhttpprotocol hostmyproxyserverhost port80port usernamemyusernameusername passwordmypasswordpassword proxy proxiessettingsthanks a lot in advance,['java'] +203495,in js which is faster objects in operator or arrays indexof i want to keep a list of strings that i will only ever check for the presence of egcorporateplan candeauthorize hasgmailsupport cansharereports cansummonkraken etcso when the user tries to summon the kraken i will do corporateplanindexofcansummonkraken 1 to see if he cana coworker suggests that it would be faster to store it as an objectcorporate plan candeauthorize null hasgmailsupport null cansharereports null cansummonkraken null etc nulland just do something like cansummonkraken in corporateplan to check if the plan contains that key this makes sense in a classic cs sense since of course contains is constant time on a map and linear on an array does this check out against how arrays and objects are implemented under the hood in js thoughin our particular case with less than 100 elements the speed does not matter much but for a larger array which way would be faster on access,['javascript'] +203503,what does restore purchases in inapp purchases mean i do not really understand this ideado i have to provide a restore button for the userwhat method should this method invokewhat will restore will do,['iphone'] +203524,c function template specialisation given this codeclass xpublic template typename t void func const t v templatevoid xfunc int const int v templatevoid xfunc char const char v 16when i compile it i get the following errortestcpp16 error templateid funcchar for void xfuncconst char does not match any template declarationcan anyone shed any light on this,['c++'] +203544,jquery and ajax or server sent events it seems in both cases client sends a request to server and server answers unless in server sent event you can set retry time in your server side code so is there any benefit in using sse rather than jquery post or get method,['jquery'] +203546,wsgi vs uwsgi with nginx could anyone please explain proscons when using wsgi vs uwsgi with nginxcurrently i am building up a production server for the django website which i have prepared but unable to decide whether should i go with wsgi or uwsgi could you please explain in detail what differentiates each configuration which configuration should scale the bestthanks in advance,['python'] +203549,increase max execution time for php i have added set time limit0 function to increase execution time but its executing only 23 minutes maximumerror reportinge allerror reporting1set time limit0i want to search links from a site wich taking a long lime any help would be greatly appreciated thanks a lot,['php'] +203550,how to create a numpy record array this gives me an errorimport numpy as npx nparray1 o 1 dtypenpdtypestep int32 symbol s1 index int32typeerror expected a readable buffer objecti do not know why this should failalternatlively how can i force something like this statement to workx nparray1 o 1thenxdtype npdtypestep int32symbol s1index int32or xviewdtypenpdtypestep int32symbol s1index int32both give mevalueerror new type not compatible with arrayeditif i try to enter each record as a tuple it will think that the triple is a single value rather than three separate fields for instanceimport numpy as npx nparray1 o 1 dtypenpdtypestep int32 symbol s1 index int32seems fine until i do thisimport numpylibrecfunctions as recrecappend fieldsxindex1gives metypeerror object of type numpyint32 has no lenpresumably because xshape is 1 rather than 13,['python'] +203597,creating rails 31 app with postgresql database osx lion i cant seem to find an uptodate guide to creating a new rails 31 app with a postgresql database i would greatly appreciate a guide through that process,['ruby-on-rails'] +203600,iphone compass presents the wrong heading pitch angle is about 45a this might be hard to explain the geometry so i will be careful in spelling it out this is visible in the standard compas app and from the data in cllocationmanager1 when holding the phone in portrait orientation consider the pitch angle to be 0a2 when pointing the camera up into the sky such as taking a picture of a cloud the pitch angle goes from 0a 90a where 90 degrees is straight up3 when the phone is tilted upward 0 degrees and rotating on the x magnetometer axis and when the phone is at about but not exactly 45 degrees the compass heading rotates 180 degrees so while the camera is still point n the compass will report s4 for the next roughly 90 degrees the compass heading is rotated 180 degreesthis rotation of the heading is destructive for me and it does not align perfectly with the accelerometers is there a good tutorial i did not find one off the bat on using the the raw data x y z from the clheading data to calculate heading datathe end result is i want the heading of the compass to always match the heading of the camera,"['iphone', 'ios']" +203605,swt java how to change colour of text in label control i know how to change size style but how can i set colour of text in label control here is my code so farlabel mylabel new labelshell swtnonemylabelsettextsome text that needs to be for example greenfontdata fd mylabelgetfontgetfontdatafd0setheight16fd0setstyleswtboldmylabelsetfont new fontthisplayfd0i see there is no colour property in fontdata class,['java'] +203655,dompdf save download i need to do 2 things together at the same time with dompdfi need to do the following together is this possibleprint the pdf file to the screen for savingdompdfstreampdf filename rand1010pdf arrayattachment falsesave the pdf file on the serverfile put contentshomestsnewpublic htmlpdffilepdf dompdfoutput the above works fine if dompdfstream and dompdfoutput are done separatelyindividually but when i try to run them together as shown above it just crashesany helpadvice would be really appreciatedthanks,['php'] +203667,apply webkit scrollbar style to specified element i am new to pseudoelements that are prefixed with a double colon i came across a blog article thiscussing styling of scrollbars using some webkit only css can the pseudoelement css be applied to individual elements this works by applying style to all scroll bars in window webkitscrollbar width 12px this does not apply the scrollbar to anything div webkitscrollbar width 12pxin this fiddle i would like to make the divs scrollbar customized but the main windows scrollbar stay at the default,['css'] +203689,jsfiddle works in firefox chrome but not ie8 here is my jsfiddle it works fine in chrome and firefox but i get this error when running it in ie8message object does not support this property or methodline 244char 9code 0uri i added the code from this jsfiddle to my site and i am seeing the same issue with ie8 do i have to add something specific to get it working in ie8thanks,['jquery'] +203706,thisable rating on ratingbar iam using a ratingbar und a onratingbarchangelistener in my codethe user can rate once and after this i set ratingbarsetenabledfalse i want to show the user an advice why he cannot rate anymorehow can i achieve to set a toast after the user touch the thisabled ratingbaranybody an ideagreetings,['android'] +203713,iterate through words of a file in python i need to iterate through the words of a large file which consists of a single long long line i am aware of methods iterating through the file line by line however they are not applicable in my case because of its single line structureany alternatives,['python'] +203736,android problems using fragmentactivity loader to update fragmentstatepageradapter i am trying to use fragmentactivity with viewpager to thisplay dynamic list of fragments there are plenty of examples on how to do a static version of it my problem is that the list i thisplay needs to be loaded dynamically and also can change based on user input adelete i am trying to use customized androidsupportv4contentloader to load set of data that i can use to build my list everything goes fine in my setup until i get to the point when i want to update the adapter and issue fragmentstatepageradapternotifydatasetchanged call at which point this code is executed from fragmentstatepageradapterpublic void finishupdateview container ifmcurtransaction null mcurtransactioncommit bang the exception is thrown mcurtransaction null mfragmentmanagerexecutependingtransactions the transaction commit fails with this messagejavalangillegalstateexception can not perform this action inside of onloadfinishedbecause within fragmentmanagerimpl this code is executedprivate void checkstateloss if mstatesaved throw new illegalstateexception can not perform this action after onsaveinstancestate if mnotransactionsbecause null throw new illegalstateexception can not perform this action inside of mnotransactionsbecause it turns out that mnotransactionsbecause value is not null and it is set in loadermanagerimplloaderinfo when the result is returned back to onloadfinishedi was looking at the various variables trying to somehow change tramsactioncommit to transactioncommitallowingstateloss but everything related to transaction seems to be private or at least packageprotectedcan someone give me a general idea if i can do what i need to do and how just to note that my code works fine if instead of using loader i run the loading ops in asynctask,['android'] +203741,in bash which gives an incorrect path python versions can anyone explain how python 26 could be getting run by default on my machine it looks like python points to 27 so it seems like which is not giving me correct information python versionpython 265 which pythonoptlocalbinpython optlocalbinpython versionpython 272 ls l optlocalbinpythonlrwxrxrx 1 root admin 24 12 oct 1602 optlocalbinpython optlocalbinpython27when i generate an error i see whats really getting run why could this be python errormakingargumentunknown option eusage libraryframeworkspythonframeworkversions26resourcespythonappcontentsmacospython option c cmd m mod file arg try python h for more informationand how can i correct iteditfrom suggestions in comments aliasalias cpcp ialias gccgcc wall type pythonpython is optlocalbinpython,['python'] +203757,inserting a multidimensional php array into a mysql database i have an array from a csv with a similar structure to thisarray 0 array 0 name 1 age 2 gender 1 array 0 ian 1 24 2 male 2 array 0 janice 1 21 2 female etci would like to insert insert it into a mysql table where the items of the first array name age gender are the column titles and each subsequent array is a row in the tablecould anyone advise as to the best way to do this as i have hit a wall and it has left me with a hurting head,"['php', 'mysql']" +203767,parsing very large xml files and marshalling to java objects i have the following issue i have very large xml files like 300 megs and i need to parse them in order to add some of their values to the db the structure of these files is also very complex i want to use stax parser as it offers the nice possibility of pullparsing and thus processing only parts of the xml file at a time and thus not loading the whole thing in memory but on the other hand getting the values with stax at least on these xml files is cumbersome i need to write a ton of code from this latter point of view it will immensly help me if i could marshall the xml file to java objects like jaxb does however this would load the whole file plus a ton of object instances in memory all at oncemy question is is there some way to pullparse or just partially parse the file sequentially and then marshall only those parts to java objects so i can deal with them easily without bogging down on memory,['java'] +203769,how should i time highlighting of text with audio for a karaoke like application on iphone say for example i had an application that would show chunks of lyrics 3 or 4 lines at a time now i want to trigger an audio file to start playing and then time the highlighting of the lyrics with the audio itself kind of like the bouncing ball that bounces from one word to anotherthe only thing i can think of is that i will need to create metadata to go along with each audio file so that i can start a timer that runs alongside the audio file or perhaps the audio player in ios can expose its own running timer and i could trigger the highlighted word to change at certain pointsany idea the best way to do this i would think that it could be taxing on the processor if i had to check every second if the word should change but i do not know how i could trigger it otherwise,"['objective-c', 'ios']" +203773,determining codesigning identities from the command line i am trying to set up an automated way to sign my ios apps before using codesign is there a way to programmatically determine from the command line what my valid signing identities arefor example for the command codesign v sign iphone thistribution joe developer pathtoapphow could i figure out that iphone thistribution joe developer is a valid identity how would i figure other valid identitiesi would prefer a way to do this from within a command line but from within cocoa would work as well,"['iphone', 'ios']" +203777,how to replace apostrophe with double apostrophe in string i have a stringgood overview of esps in more detail than you probably needwhile inserting into sql table it is giving error so i want replace apostrophe in the string with double apostrophe like good overview of esps in more detail than you probably needhow to manipulate this in c,"['c#', 'sql']" +203790,c formatting current time in c how can i get the current datetime in the following format 20110810t2136016327538z,['c#'] +203797,fontface eot not loading over https summaryi am running into an issue using fontface over https in ie 789 it simply is not loading it does not matter whether the containing html page is hosted on https or not when i try to load the eot font over http it works https it does not has anyone seen this behavior the server hosting the font is sending the proper contenttypeapplicationvndmsfontobjecti have tried multiple fonts so it is not specific to the fontthe fonts were generated over at font squirrelcss syntaxfontface fontfamily gothamcondensedboldsrcurlpathtofontgothmbcdwebfonteotsrcurlpathtofontgothmbcdwebfonteotiefix formatembeddedopentype urlpathtofontgothmbcdwebfontwoff formatwoff urlpathtofontgothmbcdwebfontf formattruetype urlpathtofontgothmbcdwebfontsvggothamcondensedbold formatsvgfontweight normalfontstyle normalsample page,['css'] +203800,create a direct link to a magento product via product id i would like to place a direct link to a magento product without using to pretty urls instead of something like this i would like it to be or something similaris that possible,['php'] +203823,nscfdictionary setobjectforkey mutating method sent to immutable object idinit if selfsuper init nsmutablearray listname nsmutablearray allocinitwithobjectscualznaurufurbpbwr nil nsmutablearray listvolumn nsmutablearray arraywithcapacitylistname count for int i0 ilistname count i listvolumn addobjectnsnumber numberwithlong0 nsmutabledictionary nsdictionary alloc initwithobjectslistvolumn forkeyslistname return selfin my init methodi defined two nsmutablearrayand added to nsmutabledictionary nsmutabledictionaryin my other methodnsmutabledictionary setobjectnsnumber numberwithlong100 forkeycubut it crash at above line,['iphone'] +203824,how to use setinterval function within for loop i am trying to run multiple timers given a variable list of items the code looks something like thisvar list arrayforvar x in list setintervalfunction listx 10 consolelogx listx n 5 10the problem with the above code is that the only value being updated is the item at the end of the list multiplied by the number of items in the list can anyone offer a solution and some explanation so i know why it is behaving this way,['javascript'] +203830,illegalstateexception not supported on asynccontextstartasyncreq res i have created a servlet 30 to explore asynchronous request processingwebservletnamemytest urlpatternsmytest asyncsupportedtruepublic class mytest extends httpservlet override public void dogethttpservletrequest req httpservletresponse res throws servletexception ioexception asynccontext tmp reqstartasyncreq res but i get an illegalstateexception when startasync is called i know the javadoc mentions that exception but i did explicitly enable async cf webservlet annotation i am using tomcat 70110 delivered with netbeansi could confirm that reqisasyncsupported is returning false what am i doing wrong what more do i need to do to enable async processingediti tried to implement the following example and got the same issue,['java'] +203847,thisable airplay with mpmovieplayercontroller i have an instance of a mpmovieplayercontroller which is being used to thisplay some live streaming video on an iphone app this is working fine however i wish to remove all airplay functionalityto be sure i specifically thisable airplay like soifselfmovieplayercontroller respondstoselectorselectorsetallowsairplay selfmovieplayercontrollerallowsairplay nohowever even with this code i still see the airplay icon on the video controls if i select this and select my appletv only the audio is sent over airplay the video continues to play within the app if i set allowsairplay to yes both the video audio are sent over airplaydoes anyone know why this happens is this a feature of the os to allows allow the audio to be sent over airplay,"['iphone', 'objective-c']" +203861,how does virtual destructor work in c i will type an example class apublicvirtual aclass b public apublicbint mainvoida a new bdelete areturn 0now in above example destructors will be called recursively bottom to up my question is how compiler do this magic,['c++'] +203869,uitableviewcontroller select header for section i have a uitableview with multiple sections each section has a section header a custom view is there an easy way to detect when someone selects the section header just like didselectrowatindexpath but for the headerthanks in advance,['ios'] +203880,why we need the iequalitycompareriequalitycomparer interface the equal and gethashcode method are exist in the object class and our type inherit the object base class whats the different between implement the two methods of the object directly and using the icomparer interfaceif we overriding objects equal and gethashcode and push to a hashtable it will use the overring s equal methodwhat the differents of new a hashtable with the iequalitycomparer constructor,['.net'] +203893,undefined reference to gxx personality sj0 with gcc 46 when trying to execute this code include iostreamusing namespace stdinclude bitsetint main int a long long min stdnumeric limitsintmin unsigned long long max stdnumeric limitsintmax cout min min n cout max max n cout min max stdbitset64 minimalmin cout minimal minimal return 0i am getting the following error1 undefined reference to gxx personality sj02 undefined reference to unwind sjlj register3 undefined reference to unwind sjlj unregister4 undefined reference to unwind sjlj resume what on hell is going on,['c++'] +203895,public const string is it ok to use a class like this design guideline specific i am using mvvm patternpublic static class pages public const string home homexaml public const string view2 view2xaml a few more,['c#'] +203900,how do i include a dependencys test jar into a maven projects deployment i have two projects foo and fooweb under the comexample group fooweb depends on footo be able to develop the ui part of the application without depending on external services dummy daos were implemented in foo they return static data so we do not have to connect to databases etc we were required to move the dummy classes to srctestjava this means that they do not get deployed with foojar to the war built from the web project i found these instructions on the maven site but they do not seem to work for mein foos pomxml i have plugin artifactidmavenjarpluginartifactid executions execution idtestjarid phasetestcompilephase goals goaltestjargoal goals execution executions pluginwhen running mvn install on fooweb in the target of foo i would get two jars foo100snapshotjar and foo100snapshottestsjar they both get installed fine in the local maven repositorybefore the fooweb dependency looked like thisdependency groupidcomexamplegroupid artifactidfooartifactid version100snapshotversiondependencyand that would trigger the deployment of foo100snapshotjar in the war now i want to also deploy the tests jar preferably only for a local profilei tried in various ways to do thisprofile idlocalid dependencies dependency groupidcomexamplegroupid artifactidfooartifactid version100snapshotversion typetestjartype dependency dependenciesprofilethis causes the source jar to be deployed with a different name comexamplefoojar and does not deploy the test jar i also tried using classifier instead of type in the dependency but it still does the same i tried using the above dependency outside of the profile alongside the others but it still behaves the sameif i add the type to the main dependency without adding the other dependency i get the test jar deployed with the same name as above but the source naturally does not get deployedthe only difference from whats written in the documentation is the fact that the scope is not specified for the test dependency does it only work for the test scope can i somehow deploy the test classes differentlyi know the questions a bit convoluted please let me know if there is something i can clarifythanksupdatei tried it in several more ways but it still would not worki added another execution to the mavenjarplugin in the foo project the dependency not the main web project in which i hoped to force maven to compile the test classes in the same jar as the main ones and reference the big bundle by a different classifier i could not get it to workexecution idlocalbuildid phasepackagephase goals goaljargoal goals configuration classifierbatmanclassifier directorybasedirsrctestjavadirectory tried several variations here includes includeinclude includes configurationexecutionthe jar was generated with the batman classifier but i could not find any way to get it to include test classes in the jar goaldoing this i realized that this does not depend on the testjar typetests classifiertest scope relationship when i tried to specify the new jar i am building besides the main one i got the same behavior as when trying to include the tests jar i checked the local maven repository and both all jars from the dependent project are getting installed fine so the problem is the main projects dependency resolutiontldreverything boils down to the question if you can include the same dependency with multiple classifiers from what i saw until now the answer is no i always get the comexamplefoo jar when specifying the same dependency multiple times with different classifiers,['java'] +203916,creating a softkeyboard with multiplealternate characters per key i have followed the examples on developerandroidcom regarding input methods and played with the softkeyboard sample application these together give more than enough information regarding the creation of simple keyboardwhat i cannot see in the api is the ability to create alternate multiple characters per key which is available on the standard keyboard latinime keyboardthe above image is the result of a long press on the a key when you long press a key it is possible to populate a popup with alternate charactersit is also possible to give a popup hint on some keys which will prompt the user to press and hold a key in order to get the popup menuso far i have not found a single source of information on how this is achieved hopefully someone will be able to give me a head start until then i will follow the source code of the inbuilt keyboard and see if i can reverse engineer itedit would help if developerandroidcom s link to the latinime keyboard did not link to a picture of a sheep actual source code for latinimejavaedit 2 more as a reference than anything else this is the sequence i believe a usual longpress action goes through in order to show the popup keyboard in keyboardviewjavaontoucheventonmodifiedtoucheventmhandklerhandlemessage with msg longpressopenpopupifrequired onlongpressedit 3 i still have not figured this out how do you add label suggestions to keys an answer suggests it is not built into the api and indeed i have not found the codeto do this however the keyboard on 234 api 10 shows this functionality being implementedwould very much like to figure out how it does it but it is not anywhere in the ondraw method that i can see which makes me believe it is being written outside of the keyboardview element i cannot however find the layout file used to thisplay the keyboardview element on the inbuilt keyboard if anyone knows where to find this perhaps that will give me the clue i neededit 4 moved key preview question here as it is slightly off topichow do you thisable customise the soft keyboard key preview window,['android'] +203933,route for custom action in controller inheriting from devisesessionscontroller i have a session controller which inherits from devisesessionscontrollerclass sessionscontroller devisesessionscontroller skip before filter authenticate user only get token def create end def destroy end def get token responseheadersappkey form authenticity token render texttoken set endendas you can see above i am overwriting create and destroy action and i have added another action named get token i added routes for it as shown belowroutesrbapplicationroutesdraw do devise for users controllers sessions sessions path users path names sign in login sign out logoutconfirmation verification match get token to sessionsget tokenbut i am getting the following eror when i am trying to access get token methoddevise could not find devise mapping for path get token how to add route for the get token actionthanks in advance,['ruby-on-rails'] +203934,any open source java decompiler for windows 7 i am looking for free open source java decompilers any suggestionswe are using windows 7 i found out that dcompiler is open source and downloadeded it it has come as a rar file nothing is there in it except its class files could you please suggest one which is a open source,['java'] +203960,mssql2008 pyodbc previous sql was not a query i cannot figure out whats wrong with the following codethe syntax is ok checked with sql management studio i have access as i should so that works too but for some reason as soon as i try to create a table via pyodbc then it stops workingimport pyodbcdef sqlquery target db cnxn pyodbcconnectdriversql serverserver target dbuiduserpwdpass cursor cnxncursor cursorexecutequery cpn for row in cursor cpnappendrow return cpnprint sqlcreate table dboapprovals id smallint not null identity primary key hostname char120it fails withtraceback most recent call last file test sqlpy line 25 in module print sqlcreate table dboapprovals id smallint not null identity primary key hostname char120 file test sqlpy line 20 in sql for row in cursorpyodbcprogrammingerror no results previous sql was not a queryanyone have any idea to why this isi got a sql server driver installed it is default running windows 7 against a windows 2008 sql server environment not a express database,['python'] +203968,cannot install sqlite3 with jruby i am brand new to ruby and using windows 7 it is a different environment to what i am normally used to so i am having problems getting a simple project goingafter reading several tutorials it appears that jruby is the simplest way to go on windows which i have done i am now trying to create a web application from scratch but i am confused about this shell style method of workingi have downloaded sqliste3def sqlite3dll and sqlite3 which i have put in the cjruby164bindirectory however i am now trying to install sqlite but with no avail firstly what i would like to know is which console environment does one use to do this is this cmd or the irb consolewhenever i use cmd the default line is cusersme and i do not know if this is affecting how things should workwhenever i try to install sqlite3 i am assuming that i need to go cusersmegem install sqlite3rubyhowever i am not getting anywhere and receiving the following errorwarningjruby does not support native extensions or the mkmf library very welli have heard a lot of good things about ruby and i am simply trying to build a basic webpage with a contact form but i seem to be running into all sorts of issues with the project installation and simply getting ruby up and running are there any tutorials that explain how to start a web project with jruby and sqlite3 from scratch,['ruby-on-rails'] +203973,is there a tool to generate a json schema from an xml schema through java is anyone aware of a tool or approach from which we can generate a json schema from xml schema or xml schema from json schema by java,['java'] +203984,nsurlconnectiondownloaddelegate file issue now that 50 is launched and we can thiscuss it without breaching apples nda i have an issue with the new version of nsurlconnection this has a new delegate nsurlconnectiondownloaddelegate with two key methodsconnectiondidwritedatatotalbyteswrittenexpectedtotalbytes is invoked repeatedly while the file download is progressingconnectiondidfinishdownloadingdestinationurl is called once when the download is complete the downloaded file should then be at destinationurl at least for the life of this method the intent is that you get it and move it somewhere permanent the issue is it is not there that directory is empty i have reported this as a bug to apple and they tell me it is a duplicate of an issue that they are already aware ofif anyone has a workaround for this or finds they can use this delegate successfully please let me knowupdate 10172011 i have given up on this and gone back to the old delegate which still works fine in 50 even though the documentation says the delegate methods are only available thru 43,['ios'] +203998,storekit catch failed restore i am implementing inapp purchase feature with restore buttoni have a brand new test user set up without any payments madewhen i hit the restore button and log in with the new test user i cannot catch any delegated methods that tell me that the restoring transaction has failed since there is nothing to restorethe only method that get invoked is voidpaymentqueuerestorecompletedtransactionsfinishedskpaymentqueuequeue but this method gets called in the case when restoring was successful toowhat can i do now how can i catch such a caseaddition i have a progress indicator that says contacting app store and i need an invocation where i can hide it in failed cases too,['iphone'] +204011,how to extend config of different bundle in symfony2 i know i can overwrite templates or extend classes of other bundles but can i extend also configs i was hoping to be able to load other namespaces from config in dependenyinjectionacmeextensionphps load method but i have not found anything about it anywhereexamplei have acmebundle which defines following in configacme a 1i want to extend this bundle in new bundle called awesomeacmebundle and be able to define another variables either by adding them to original namespaceacme a 1 b 2or by wrapping original namespace to new one and adding new variables thereawesome acme a 1 b 2,['php'] +204041,safariwebkit is consolelog dom node as object this is something that is been driving me nuts for a while when i consolelog a dom node returned by example from documentgetelementbyid it appears as an interactive html element as it would appear on the elements tabthis can be handy for sure but there are times when i just want to be able to expand the object and see all of its properties like i can do for every other kind of object i log to the consoleis there any way i can get a dom node to thisplay in the console as a regular object,['javascript'] +204090,difference between executor and executorcompletionservice in java as the question title itself says what is the difference between executors and executorcompletionservice classes in javai am new to the threadingso if any one can explain with a piece of code that would help a lot,['java'] +204106,writing your own stl container are there guidelines on how one should write new container which will behave like any stl container,['c++'] +204125,mysql table does not exist but it does or it should i did change the datadir of a mysql installation and following some steps it worked fine every base i had was moved correctly but onei can connect and use the database even show tables returns me all the tables correctly and the files of each table exists on the mysql data directory but when i try to select something there it says the table does not exists but the table does exists it even shows at show tables statementmy guess is that the show tables lists the files existence somehow that the files are corrupt or something like that but it does not check it so i can list them but not access thembut that is just a guess i have never seen this before cannot restart the database now for testing every other application which uses it is running finedoes anyone knows what is itexamplemysql show tables tables in database table one table two table three mysql select from table oneerror 1146 42s02 table databasetable one does not exist,['mysql'] +204126,is there any possibility to have jsonstringify preserve functions take this objectx key1 x key2 functionreturn thiskey1if i do thisy jsonparse jsonstringifyx then y will return key1 x is there anything one could do to transfer functions via stringify creating an object with attached functions is possible with the ye goode olde eval but whats with packing it,['javascript'] +204127,nsfilemanager unique file names i need a quick and easy way to store files with unique file names on ios i need to prefix the file with a string and then append the generated unique identifier to the end i was hoping nsfilemanager had some convenient method to do this but i cannot seem to find iti was looking at createfileatpathcontentsattributes but am unsure if the attributes will give me that unique file name,"['objective-c', 'ios']" +204128,mongoid random document lets say i have a collection of users is there a way of using mongoid to find and random users in the collection where it does not return the same user twice for now lets say the user collection looks like thisclass user include mongoiddocument field nameendsimple huhthanks,"['ruby-on-rails', 'ruby']" +204156,how do i create and persist a sqlite db from scratch in code using systemdatasqlite and c i have a database creation tool and am creating a database from scratch this is done the same way as mentioned here it creates a temporary db and i can add data to itwhen i close the database it is deleted which is the expected behavior but i do not want it deletedi cannot find a save or create method in systemdatasqlite and creating one with systemiofilecreatemydbfilename creates a file that sqlite cannot connect tohow do i create and persist a database in code from scratch,['c#'] +204175,how do i remove the and country code from a phone number i am using following api to get a phone number however some of the device will return the number in following format countrycode phone number ex 12062436969telephonymanager tm telephonymanager getsystemservicetelephony servicestring phonenumber tmgetline1numberi would like to find out a wayalgorithm to remove this sign and the country code so i will get only the last ten digits ex 12062436969 2062436969i believe i only need the last ten digits could anyone please suggest any idea,"['java', 'android']" +204178,mysql query restarting every 60 seconds i have a strange problem i am running a mysql query against a very large table from php the query time is over a minute but that is not my problem it looks like php is resending the query every 66 secondsshow processlist id user host db command time state info 150018 root localhost amrs query 32 sending data derekselect ctlno count as count from omitteda few minutes later i checked again id user host db command time state info 150018 root localhost amrs query 188 sending data derekselect ctlno count as count from omitted 150021 root localhost amrs query 122 sending data derekselect ctlno count as count from omitted 150023 root localhost amrs query 56 sending data derekselect ctlno count as count from omittedi have not reloaded the page or anything set time limit0 is called near the beginning of the script the annoying part is the page seems to be linked to the most recently run one so if i kill 150018 nothing bad happens but if i kill 150023 before another one is spawned the page comes up with a query execution interrupted error 150018 will eventually finish running on its own but it does not do any good because the scriptpage would not receive itanyone have any ideasedit show full processlist gives the following with some lines removed for brevity and confidentiality id user host db command time state info 147385 root localhost44560 amrs sleep 14021 null 150248 root localhost null query 0 null show full processlist 150251 root localhost amrs query 1 statistics derekselect ctlno count as count from snip,"['php', 'mysql']" +204195,encoding issues in javascript files using rails asset pipeline i am using rails 31 and the asset pipeline ruby 192i get the following error when trying to serve a javascript jserb file that has utf8 encoded stringsinvalid byte sequence in usasci have set encodingdefault external utf8 in my environmentrb file how do i get the asset pipeline to serve with a different encodingeditthe error only shows up when i am generating the utf8 character outside of the file in this case by querying from the db the error goes away if i add to the top of the file i am guessing there is some kind of encoding guessing going on here but how do i avoid it without that hacky solution,"['ruby-on-rails', 'ruby']" +204204,gcc optimization trick does it really work while looking at some questions on optimization this accepted answer for the question on coding practices for most effective use of the optimizer piqued my curiosity the assertion is that local variables should be used for computations in a function not output arguments it was suggested this would allow the compiler to make additional optimizations otherwise not possibleso writing a simple bit of code for the example foo class and compiling the code fragments with g v44 and o2 gave some assembler output use s the parts of the assembler listing with just the loop portion shown below on examination of the output it seems the loop is nearly identical for both with just a difference in one address that address being a pointer to the output argument for the first example or the local variable for the second there seems to no change in the actual effect whether the local variable is used or not so the question breaks down to 3 partsa is gcc not doing additional optimization even given the hint suggestedb is gcc successfully optimizing in both cases but should not bec is gcc successfully optimizing in both cases and is producing compliant output as defined by the c standardhere is the unoptimized functionvoid dosomethingconst foo foo1 const foo foo2 int numfoo foo barout for int i0 inumfoo i baroutmungefoo1 foo2i and corresponding assemblyl3 movl esi eax addl 1 ebx addl 4 esi movl eax 8esp movl edi eax movl eax 4esp movl 20ebp eax note address is that of the output argument movl eax esp call zn3foo5mungees s cmpl ebx 16ebp jg l3here is the rewritten functionvoid dosomethingfasterconst foo foo1 const foo foo2 int numfoo foo barout foo bartemp barout for int i0 inumfoo i bartempmungefoo1 foo2i barout bartempand here is the compiler output for the function using a local variablel3 movl esi eax load foo2i pointer into eax addl 1 ebx increment i addl 4 esi increment foo2i 32bit system 8 on 64bit systems movl eax 8esp push foo2i onto stack careful from eax not esi movl edi eax load foo1 pointer into eax movl eax 4esp push foo1 leal 28ebp eax load bartemp pointer into eax movl eax esp push the this pointer for bartemp call zn3foo5mungees s munge cmpl ebx 16ebp i numfoo jg l3 recall incrementing i by one coming into the loop so test if greater,['c++'] +204294,i cannot get the string value of a token i try to implement a lexer for a little programming language with boost spirit i have to get the value of a token and i get a bad get exception terminate called after throwing an instance of boostbad get what boostbad get failed value get using boostget abortedi obtain this exception when doing stdstring contents voidbase iterator type first contentsbeginbase iterator type last contentsendsimplelexerlexer type lexeriter lexerbeginfirst lastend lexerendstdcout value boostgetstdstringitervalue stdendlmy lexer is defined like that typedef stdstringiterator base iterator typetypedef boostspiritlexlexertltokenbase iterator type boostmplvectorunsigned int stdstring toktypedef lexlexertlactor lexertok lexer typetemplatetypename lclass simplelexer public lexlexerl private public simplelexer keyword for for keyword while while keyword if if keyword else else keyword false false keyword true true keyword from from keyword to to keyword foreach foreach word azaz integer 09 litteral left parenth right parenth left brace right brace stop comma swap assign addition subtraction multiplication division modulo equals not equals greater less greater equals less equals whitespaces tn comments add keywords thisself keyword for keyword while keyword true keyword false keyword if keyword else keyword from keyword to keyword foreach thisself integer litteral word thisself equals not equals greater equals less equals greater less thisself left parenth right parenth left brace right brace thisself comma stop thisself assign swap addition subtraction multiplication division modulo ignore whitespaces and comments thisself whitespaces lex pass lexpass flagspass ignore thisself comments lex pass lexpass flagspass ignore lextoken defstdstring word litteral integer lextoken deflexomit left parenth right parenth left brace right brace lextoken deflexomit stop comma lextoken deflexomit assign swap addition subtraction multiplication division modulo lextoken deflexomit equals not equals greater less greater equals less equals keywords lextoken deflexomit keyword if keyword else keyword for keyword while keyword from keyword to keyword foreach lextoken deflexomit keyword true keyword false ignored tokens lextoken deflexomit whitespaces lextoken deflexomit commentsis there an other way to get the value of a token,['c++'] +204296,redbean orm performance i would like to know can redbean orm be used for performance oriented scenarios like social networking web apps and is it stable even if thousands of data is pulled by multiple users at same time also i would like to know whether redbean consumes more memory spacecan anyone offer a comparison study of doctrinepropelredbean,['php'] +204303,how to make a angled arrow like this with gradient and transparent how to make a angled arrow like this with gradient and transparent i made a block with gradient here need help to convert into arrowi need a compatible with ie8 compatibility,['css'] +204310,can you avoid using temporary buffers when using stdstring to interact with c style apis i should preface this question by saying i think the answer is probably no but i would like to see what other people think about the issue i spend most of my time writing c that interacts with the win32 api which like most c style apis wants to eithertake buffers which i have provided and operate on themor return pointers to buffers which i need to later free both of these scenarios essentially mean that if you want to use stdstring in your code youve got to accept the fact that youre going to be doing a lot of string copying every time you construct a stdstring from a temporary bufferwhat would be nice would beto be able to allow c style apis to safely directly mutate a stdstring and prereserve its allocation and set its size in advance to mitigate scenario 1to be able to wrap a stdstring around an existing char to mitigate scenario 2is there a nice way to do either of these or should i just accept that there is an inherent cost in using stdstring with old school apis it looks like scenario 1 would be particularly tricky because stdstring has a short string optimisation whereby its buffer could either be on the stack or the heap depending on its size,"['c++', 'c']" +204338,changing viewpager to enable infinite page scrolling jon willis has posted on how to enable an infinite scrolling with his codein there he said that he made some changes in the viewpager class int the android support library which changes have been made and how is it possible to recompile the library with the viewpager changethanks,['android'] +204346,how to find stored procedures execution time in sql server i have 10 stored procedures as followssp1sp2sp10these stored procedures do some stuffi need to run these procedures as followsexecute sp1execute sp2execute sp10when sql server finshes to complete execution of these procedures it gives ten lines showing any row changes caused by all these stored procedures what i want to do is that after execution of all stored procedures sql server also gives in output window the execution time for each stored procedurescan i do this i am sure that for achieving this task i need to modify stored procedures but i do not have any idea how to do itplease help methanks,['sql'] +204354,change strength of antialiasing in matplotlib is it possible to increase the antialiasing in matplotlibi can still see some aliasing in my data i tried several backends and it is still there the antialiasing flag of the lines is sethere you can see what i mean it is a sample taken from a screenshot it is probably not the best example but i guess one can see the stairs in the line it was taken with the wxagg backendi am using matplotlib version 101 with windows 7updatei do not have the code which produced the previous picture anymore but i still have the problem below is a simple code example which shows the aliasingimport numpy as npimport matplotlibmatplotlibusewxaggimport matplotlibpyplot as plprint backend plget backendx nplinspace06100y npsinxfor a in range10 plplot x a10x linewidth1plshowit prints backend wxaggand the resulting plot looks like the followingespecially the lower red curve shows clear aliasing,['python'] +204360,how to customize mkpolylineview to draw different style lines i want to customize the lines drawn on mkmapview to show a route so that the lines have a border color and a fill color similar to this where it has a black border and is filled with another colori am currently just returning mkpolylineview objects from mapviewviewforoverlay which works fine for plain lines the docs says the mkpolylineview is not to be subclassed so should i subclass mkoverlayview and implement my own drawmaprect or should i subclass mkoverlaypathview or create a replacement for mkpolylineview edit what i am asking is where is the place to put your own quartz drawing code in order to draw your own annotationsoverlays currently i have created a subclass of mkoverlayview and implement my own drawmaprectzoomscaleincontext it is pretty easy to draw the overlay that way but is that the best solution,"['iphone', 'ios']" +204363,java nio and windows thisk access does java nio need special permissions on windowswhen i run the following java code on windows server 2003 it fails with an access denied error that is the whole message in the cygwin terminal windownew fileoutputstreamoutputfilegetchannel transferfromnew fileinputstreaminputfilegetchannel 0 longmax valuebut if i use apache commonsio which i assume does not use nio it works with the same input and output filesfinal fileinputstream inputstream new fileinputstreaminputfilefinal fileoutputstream outputstream new fileoutputstreamoutputstreamioutilscopyinputstream outputstreami am running in java 5 with an administrator account is there some special file permission that must set,['java'] +204367,viewonmeasure not called i have a very simple custom view with onmeasure overriden my onmeasure decides the size according to the background drawable when the view is first created from xml everything works normally but then i set a different background programatically so the view should resize the view has now a different background but it does not resize and onmeasure is not calledi tried everything requestlayout forcelayout invalidate setlayoutparams without any effect what am i doing wrong i just want my view to resize,['android'] +204431,algorithm for calculating probabilities of a number being drawn opening a book i have a book with n10 pages and a number xin the range 1x40i want to calculate the probability that opening that book at random the combination of the digits of the opened pages of the book are equals to the numberthe level of combinations may vary from simple sum of digits the event p234 is true for x 9 to combination of sums and subtractions up to pairs of digitsthe event p124 is true for x 1 2 341 4 541 624 7124 8124 12 14 16142 23241 24 25241 a starting note is that if you open a book youll always get page and and page n1 so the probability should be calculated on the 2n12n couple for each n 1here what i am doingstatic protected int sommacifrenumeroint numero int retnum0 for char c integervalueofnumerotostringtochararray retnum c 48 return retnumstatic public float calcolaprobabilita sempliceint da interrogare int ne interroga return floatne interrogafloatda interrogare100f questo sistema calcola le probabilita che aprendo un libro a caso la somma delle cifre delle pagine diano il tuo numero nellelenco del registro se il tuo numero non pua2 essere raggiunto avrai sempre probabilita 0 static public float calcolaprobabilita librosempliceint npagine int nregistro int maxnumberinterrogabile 0 float retprob maxnumberinterrogabile sommacifrenumero npagine maxnumberinterrogabile integervalueofnpaginetostringlength 2 integervalueofnpaginetostringtochararray1 48 1 91maxnumberinterrogabile integervalueofnpaginetostringtochararray1 48 1 91 maxnumberinterrogabile maxnumberinterrogabile integervalueofnpaginetostringlength 3 integervalueofnpaginetostringtochararray2 48 1 92maxnumberinterrogabile integervalueofnpaginetostringtochararray1 48 1 92 maxnumberinterrogabile maxnumberinterrogabile integervalueofnpaginetostringlength 4 integervalueofnpaginetostringtochararray3 48 1 93maxnumberinterrogabile integervalueofnpaginetostringtochararray1 48 1 93 maxnumberinterrogabile ifnregistromaxnumberinterrogabile retprob 0f return 0f il numero massimo raggiungibile a inferiore al numero in registro non puoi essere chiamato int favorevoli 0 forint i1 inpagine i ifsommacifrenumeroinregistro inregistro favorevoli retprob float favorevoli float npagine 100f return retprob questo sistema a unestensione del precedente somma le cifre di una pagina aperta a caso ma anche a coppiees p124 pua2 dare 12 16 24 25 static public float calcolaprobabilita librocomplessaint npagine int nregistro string pagstring float retprob int nreglength stringvalueofnregistrolength int favorevoli 0 int totali 0 vectorinteger possibili int number to add int number added forint i 1inpagine i possibili new vectorinteger pagstring integervalueofitostring forint a0 anreglengthpagstringlength a string numero selezionato pagstringsubstringaanreglength if integerparseintnumero selezionato31 possibiliaddintegerparseintnumero selezionato somma le parti prima forint b0 ba b b a lindice iniziale della sottostringa che verra sommata forint c1 cnreglength c c a lindice 1 finale della sottostringa che verra sommata ifbca number to add integerparseintpagstringsubstringbbc if number to add0 number added integerparseintnumero selezionato number to add if number added 31 possibiliaddnumber added somma le parti dopo forint banreglength bpagstringlength b forint c1 cnreglength c ifbcpagstringlength number to add integerparseintpagstringsubstringbbc if number to add0 number added integerparseintnumero selezionato number to add if number added 31 possibiliaddnumber added totali possibilisize forint numero possibili favorevoli numeronregistro 10 retprob floatfavorevolifloattotali 100f return retprobthe first method calculates the sum of the digits of a number the second the probability that the opened page number are equal to the x or their digits sum isthe third check also couples of digits1 i am not taking in count the note i made before2 i will run this on a mobile device3 right now i really feel the results are wrongi was wondering if a table of precalculated results would fit better i know that and is 10 so i can use an array4010 for storing the results to load at runtime but i am not to keen in file manipulations in java in addition i will need to store this for say 4 different methods of calculating the probability so how much memory would it consume and is it a problem to calculate this at runtime insteadis there a better approachor maybe an already written algorithm for doing this,['java'] +204468,numpy array with dtype decimal are decimal dtypes available in numpy import decimal numpy d decimaldecimal11 s 12312323232321212312321312 ss numpyarrays dtypenumpydtypedecimaldecimal a numpyarrays dtypefloat typedclass decimaldecimal typess11class str typea11class numpyfloat64i suppose numpyarray does not support every dtype but i sort of thought that it would at least let a dtype propagate as far as it could as long as the right operations were defined am i missing something is there some way for this to work,['python'] +204478,android issue with showing dialog from themelight activity i am trying to show a dialog from a preferenceactivity which is set to themelight the dialog shows with dark text on a dark backgroundi assume it uses dark text because it is inheriting the text color from the parent activity or something similar i would like the dialog to either use white text on the dark background or use a white background with dark text as the preferenceactivity does when set to themelightthis seems to be a known problem the workarounds i have found involve creating and using a custom style that extends themedialog and using it to instantiate the dialog something like style namecustomdialog parentandroidstylethemedialogitem nameandroidtextcolorandroidattrtextcolorprimaryinversethisableonlyitemstyledialog dialog new dialogcontext rstylecustomdialogi tried this but it made no difference i also tried a number of different values for textcolor none of which modified the dialogs text color as a sanity check i added item nameandroidbackgroundf0itemto the style which resulted in a dialog with a red background so i am sure that i am instantiating the dialog properlythe closest i have come to a solution is just setting the dialogs background color to white which gives the below dialog but this is not a good solution because some version or some device might not use the same behavior i am seeing when inverting text colorso is there a good way to set text color on a dialog thisplayed from a themelight activity,['android'] +204487,converting array of objects to xml in c i know there is no built in converter to convert an array of objects to xml is there a quick rudimentary way to create a xml out of the array to help me do a linq to xml join between this one and another xml i have,['c#'] +204492,jaxb objects hashcode and equals we have a huge java application that entirely works based on jaxb serializationthe middleware server does all db access and sends all the data objects in jaxb objects and serializes to xml and sends the data to ui cnetmost of the times after the data is populated from db access into the jaxb java objects i will have to some processing like sort the collection of objects based on attribute find the avg do some calculation on the list of objects in the collection etcmy major problem is jaxb objects do not have equals and hashcode so what i am doing is moving all the data to some user defined data objects where i have hashcode equals compareto defined so i can do all operations in the collections and then copy to the jaxb objects i think this is a extra overheadquestions1 does jaxb objects support equals hashcode compareto can i specifiy these in schema2 any other better alternativesthanks,['java'] +204520,main color detection in python i have about 30 images and 13 different colors the background of the majority of these images is white if the main color of an image is one of those 13 different colors i would like them to be associatedi have seen similar questions like image color detection using python that ask for an average color algorithm i have pretty much copied that code using the python image library and histograms and gotten it to work but i find that it is not too reliable for determining main colorsany ideas or libraries that could address thisthanks in advanceeditthanks guys you all pretty much said the same thing to create buckets and increase the bucket count with each nearest pixel of the image i seem to be getting a lot of images returning white or beige which is also the background on most of these images is there a way to work around or ignore the backgroundthanks again,['python'] +204521,removing drive or network name from path in c whats the most concise but safe way to remove a drive name network path etc from an absolute path in cfor example convertingnetworkmachinefoobarorcfoobarto foobarthere seem to be a good number of questions already answered with regards to path matters but i could not quite find what i was looking for my own first thought that came to mind was to use pathgetfullpath to ensure i am indeed working with an absolute path and then to just use a regular expression to find the first slash that is not next to another one however using a regular expression to do path manipulation seems slightly dangerouswould it perhaps be wiser to get the drive lettertarget network machineetc convert the strings to uri and ask for the path relative to the drivemachine and then convert back to strings or is there an even better approachthank you for your time,"['c#', '.net']" +204550,what exactly happens when i install an android application my guess is that the contents of apk package are extracted somewhere and the application is registered at some directory so that the application launcher or whatever can find it but is that all if that is the case is the original manifestxml read every time the app is launched or it gets preprocessed into some other form,['android'] +204560,how to load image with relative path in bitmap i want to upload image int the bitmap object from aspnet the image is location under uploadedimagessampleimagejpgwhenever i use below code to load image in bitmap i gets error saying parameter not validbitmap b new bitmapuploadedimagessampleimagejpg this path is coming from database holded in variablei tried to replace the slashes in path to still that does not workcan anyone tell me what could be the reason for the error and the possible resolution,['asp.net'] +204561,highlight exception throwers in intellij idea i recently moved from eclipse to intellij idea and there is a feature that i am missing in eclipse when you placed the caret on a checked exception in throws declaration or catch block it would highlight which methodconstructor calls throw that exception is there any way to do this in intellij idea community edition,['java'] +204566,iphone and webapp sync through icloud just checking if its possible to sync ios devices and a web app through icloud currently weve got an ios app built are looking at using icloud for synching between all the devices and also want a web app component icloud would be great to use as the module to sync everything togetheranyone know if it is possible,"['iphone', 'objective-c']" +204583,how winrt events are interoperate with net in the latest video by rx team bart de smet rx update net 45 async winrt i saw that winrt events exposed to net by some really strange metadata more preciesly add remove pair methods signatureeventregistrationtoken add myeventeventhandlermyeventargs handler a void remove myeventeventregistrationtoken registrationtoken a it looks really great allowing unsubscribing from event by thisposing the registration token rx does the same kind of thing returning ithisposable instance from subscribe method so it is became possible to easily unsubscribe lambaexpressions from events butso how does c allows for working with this kind of events in net it is possible to subscribe an method static and instance with one instance on delegate and unsubscribe with completely another delegate instance pointed to the same method so if i using an winrt event and just do unsubscribing of some delegate type instance in c where did compiler get the correct eventregistrationtoken how all this magic works update actually eventregistrationtoken does not allows to unsubscribe simply by calling some kind of thispose method that is really sadlypublic struct eventregistrationtoken internal ulong value get internal eventregistrationtokenulong value public static bool operator eventregistrationtoken left eventregistrationtoken right public static bool operator eventregistrationtoken left eventregistrationtoken right public override bool equalsobject obj public override int gethashcode update2 winrt interoperability actually uses global table of registration tokens when subscribing winrt events with managed objets for example interop code for removing handlers looks like thisinternal static void removeeventhandlertactioneventregistrationtoken removemethod t handler object target removemethodtarget var eventregistrationtokentable windowsruntimemarshalmanagedeventregistrationimplgeteventregistrationtokentabletarget removemethod eventregistrationtoken obj2 lock eventregistrationtokentable listeventregistrationtoken list if eventregistrationtokentabletrygetvaluehandler out list return if list null listcount 0 return int index listcount 1 obj2 listindex listremoveatindex removemethodobj2that is really sadly,['c#'] +204598,swing html drawstring i am trying to create some special component for a specific purpose on that component i need to draw a html string heres a sample code public class mycomponent extends jcomponent public mycomponent super protected void paintcomponentgraphics g some drawing operations gdrawstringhtmlutext to renderuhtml1010 unfortunately the drawstring method seems to be not recognizing the html format it foolishly draws the string just as it isis there any way to make that work,"['java', 'html']" +204600,play avmutablecomposition with avplayer i am trying to get two videos to play sequentially i have tried avqueueplayer but there is a huge burp between the two clips i need to them to play without interruption so i am trying to use avmutablecomposition and an avplayer but cannot get it rightheres my code ignore memory leaks just testing in an empty projectcomposition avmutablecomposition alloc initnsstring path nsbundle mainbundle pathforresourcetest oftypemp4nsurl url nsurl fileurlwithpathpathavurlasset asset avurlasset alloc initwithurlurl optionsnilnserror error nullcomposition inserttimerangecmtimerangemakecmtimemake010cmtimemake410 ofassetasset attimecmtimemake010 errorerroriferror nslogerror errorpath nsbundle mainbundle pathforresourcechug1 oftypemp4url nsurl fileurlwithpathpathasset avurlasset alloc initwithurlurl optionsnilerror nullcomposition inserttimerangecmtimerangemakecmtimemake010cmtimemake310 ofassetasset attimecmtimemake4110 errorerroriferror nslogerror erroravplayeritem item avplayeritem alloc initwithassetcompositionavplayer player avplayer playerwithplayeritemitemavplayerlayer layer avplayerlayer playerlayerwithplayerplayerlayer setframecgrectmake0 0 320 480self view layer addsublayerlayerplayer playthe code seems right to me the first frame of each video is actually rendered to the screen but the video does not play at all i am i missing something do i need to figure out how to use the mutabletrack stuff,['ios'] +204647,convert vector to jobject in cjni i am using java native function public native arrayliststring parsexmlin c my native function vectorstring resultlistjniexport jobject jnicall java sample1 parsexmljnienv env jobject obj logic return resultlist here getting errormy problem is that how to convert resultlist vector type to jobject type,"['java', 'c++']" +204653,svg dragging for group i am trying to achieve group and individual dragging inside the group in the group there are 3 circles blue and grey circles has to drag individually by onmousedown and orange one is for group moving by onclick the problem is that after dragging whole group but you have to try at and see codeany help would be appreciate thanks,['javascript'] +204654,get website ip using php i need to fetch the given website ip address using php that is ip address of server in which website is hosted for that i have used gethostbynameexamplecom it works fine when the site is not redirected for example if i used this function to get googlecom it gives 7412523520 when i tried it for lappusacom it gives lappusacom then i tried this in browser it is redirecting to i checked the http status code it shows 200but i need to get ip address even if site was redirected like if lappusacom is redirected to lappusalappgroupcom then i need to get ip for redirected url how should i get this any help greatly appreciated thanks,['php'] +204673,best practice for setting jframe locations i have a somewhat philosophical question relatively to swing or to gui programming in general are there recognized best practices on where to locate the jframe instances used in the application where should the first and main frame be located always at the center setlocationrelativetonullwhere should a child jframe be located relatively to its parent jframe at the center of the screen wherever we want i have always assumed there were some best practices kind of a gui bible about this am i wrong and should i gasp arbitrarily decide what to do,['java'] +204679,what is the best place for business logic in aspnet mvc when using repositories when implementing repository for database in aspnet mvc project is it correct to place business logic into it or may be better to place logic in controller class or use additional service and helper classes for manipulating data,"['c#', '.net', 'asp.net']" +204696,how to find the vertical thistance from top in px of an element using jquery how do i find the vertical thistance from the top of the page to where the element exist in the dom using javascriptjqueryi have something likeul lioneli lioneli lioneli lioneli li classtestoneli lioneliulfor example here i want to find the vertical thistance from top of the page to the litest elementi tried scrolltop but it always comes as 0,"['javascript', 'jquery']" +204736,why is template argument deduction thisabled with stdforward in vs2010 stdforward is defined as suchtemplateclass ty inline ty forwardtypename identity tytype arg forward arg given explicitly specified type parameter return ty argidentity appears to be used solely to thisable template argument deduction whats the point of purposefully thisabling it in this case,['c++'] +204757,how to get out of full screen mode in android emulator sometimes i accidentally hit a key combination to make the android avd emulator go into full screen and i could not figure out how to get out of it without restarting the emulator all i could do to escape was alttab to toggle applications,['android'] +204772,how to use aliases with mysql left join my original query is doing joins using the where clause rather than join i realized that this was not returning movies that did not have any stars or genres did not show up so i think i have to do a left join in order to show every movie here is my original sqlselect from movies m stars s stars in movies sm genres g genres in movies gmwhere mid smmovie idand smstar id sidand gmgenre id gidand gmmovie id midand mtitle like theand sfirst name like benorder by mtitle asclimit 5i tried to do a left join on movies i am definitely doing something wrongselect from movies m stars s stars in movies sm genres g genres in movies gmleft join movies m1 on m1id smmovie idleft join movies m2 on m2id gmmovie idand smstar id sidand gmgenre id gidorder by mtitle asclimit 5i get error 1054 42s22 unknown column smmovie id in on clause so clearly i am doing the join wrong i just do not see what it is,"['mysql', 'sql']" +204773,can descriptors for sockets be converted to file pointers i got a descriptor for a tcp socket in the following manner int desc acceptsocket descriptor client address lennow from this descriptor desc i want to get a file pointer can fdopen be used here the reason i want to get a file pointer is because i am making changes to an existing code that writes data to a local file now i want to extend its functionality so that it can alternatively write to a tcp client i dont want to rewrite all functions and was thinking of somehow being able to use the existing infrastructure the existing functions use the file pointer to write to the file i was wondering if it was possible to make the same function write to a tcp stream without making any changes,['c'] +204784,how can i represent an infinite number in python in python when you want to give to a set of elements an associated value and you use this value for comparisons between them i would want this value as infinite no matter which number you enter in the program no number will be greater than this representation of infinity,['python'] +204805,when to use android or android i am a newbie and trying to understand the following xml codelooking at the documentation at developerandroidcom it says starstyle is a constant in rattr and public static final int starstylesince api level 1default star stylemust be a reference to another resource in the form packagetypename or to a theme attribute in the form packagetypenameit seems to say that there are 2 syntax i can declare 1 packagetypename 2 packagetypenameif there are 2 syntax what is the correct one for packagetypename i tried androidattrstarstyle but i did not get a star checkbox even though the application compiled ok,['android'] +204809,override browsers ctrlwheelscroll with javascript in most browsers on linux ctrlwheelscroll allows the user to zoom in and out of the page by enlarging or shrinking the size of all elements now i want to override this behaviour and get ctrlwheel to zoom into an svg element i have by applying affine transformationsis this possible specifically is it possible to catch this keyboardmouse event as well as suppressing the browsers default behaviour,['javascript'] +204810,java printing two dimensional array i have a 2020 two dimensional array that i have manipulated in a few words i am doing a turtle project with user inputting instructions like pen up 0 and pen down 1 when the pen is down the individual array location for instance 34 is marked with a 1the last step of my program is to print out the 2020 arrayi cannot figure out how to print it and i need to replace the 1 with an xthe print command is actually a method inside a class that a parent program will calli know i have to use a loopany help would be appreciatedpublic void printgrid systemoutprintln,['java'] +204831,when to move from container managed security to alternatives like apache shiro spring security i am trying to secure my application which is built using jsf20i am confused about when do people choose to go with security alternatives like shiro spring security or owasps esapi leaving behind container managed security having seen some of related questions on stack overflow where i realized that container based security was more preferred by jsf developers in past but i have also been strongly recommended to use apache shiro i am novice in terms of the security issues and have no idea what may be the relevant issues how to deal with them therefore i am looking for something that handles most of the security issues through its default settings on its ownin terms of my application requirements i have a social application where users with different roles have access to different set of pages and can use different levels of functionality on those pages based on their rolesin that case what do you think could be a good option for me to go with i personally have been convinced to opt shiro since it is easy to use and takes care of most of the things for the novice,['java'] +204834,icloud makes it possible for users to steal inapp consumables in my app users purchase consumables let us say suitcases that are stored in core data when the user first installs the app i give them a freebie to get started the app cannot function without at least one suitcase set upbut if the user installs the app on their iphone and then their ipad and syncs the two they now have 2 suitcases and if they uninstall the app on either device then reinstall and sync it they have just gained an extra one and they can do that indefinitelyi can see two solutions but none of them seem rightadd a value to nsubiquitykeyvaluestore when the user first syncs with icloud check this value on first launch if it is nil create the freebie if it is not sync data but this creates a problem what if the user thisables icloud or has no internet connection on first launch the app would create the freebie then when icloud is available sync the duplicate and they could do this as many times as they likesomehow match the default items on each app i had the idea of matching objectids or timestamps but these would vary and i am not sure how to handle itdoes anyone know anything i could do about thiseditusing a prepackaged database plus migratepersistentstoretourloptionswithtypeerror seems to be the way to go will post an answer with code if it works for me,"['iphone', 'objective-c']" +204835,error unknown table engine innodb on query after restarting mysql i have mysql db on server s1 mysql version 51413ubuntu127log i have created masterslave for this db on server s2 mysql version 51541ubuntu4logthe db on s1 was using one data file ibdata after dumping the db to s2 i set innodb file per table1 this made every table to have its own ibd file now everything went fine and smoothlybut after restarting mysql on s2 i faced a problem with getting this errorerror unknown table engine innodb on query default database mydband when i try to show enginesshow engines engine support comment transactions xa savepoints myisam default default engine as of mysql 323 with great performance no no no mrg myisam yes collection of identical myisam tables no no no blackhole yes devnull storage engine anything you write to it thisappears no no no csv yes csv storage engine no no no memory yes hash based stored in memory useful for temporary tables no no no federated no federated mysql storage engine null null null archive yes archive storage engine no no no innodb is not listedin error log i can see thisinnodb database physically writes the file full waitinnodb cannot initialize created log files becauseinnodb data files are corrupt or new data files wereinnodb created when the database was started previousinnodb time but the database was not shut downinnodb normally after that1016 82411 error plugin innodb init function returned error1016 82411 error plugin innodb registration as a storage engine failed1016 82411 warning neither relaylog nor relaylogindex were used so replication may break when this mysql server acts as a slave and has his hostname changed please use relaylogs2relaybin to avoid this problemi have tried to delete ib logfiles but this did not work as wellanybody faced such issue before any idea is highly appreciatedthanks,['mysql'] +204848,embeds many and embeds one from same model with mongoid i have two models blog and theme a blog embeds many themes and theme embedded in blog i also have blog embeds one theme for the activated theme this does not work when creating a theme with blogthemescreate it is not stored if i change the collections so they are not embedded everything works this does not workclass blog embeds many themes embeds one themeendclass theme embedded in blogendbut this does workclass blog has many themes has one themeendclass theme belongs to blogendanyone know why this isupdatealso there is a problem with assigning one of themes to selected themeblogthemes theme 1 theme 2blogsaveblogtheme blogthemesfirstblogsaveblogreloadblogtheme returns nil,"['ruby-on-rails', 'ruby']" +204873,should i set max pool size in database connection string what happens if i do not this is my database connection string i did not set max pool size until nowpublic static string srconnectionstring serverlocalhostdatabasemydbuidsapwdmypwso currently how many connections does my application support what is the correct syntax for increasing the connection pool sizethe application is written in c 40,['sql'] +204885,javascript number split into individual digits hi i am trying to solve a math problem where i take a number eg 45 or 1 and then split the number into separate digits eg 4 5 or 1 1 1 i will then save each number to a var to run a method on does anyone no how to split a number into indivdual digitals for example i have a loop that runs on an array for var i 0 i rangelength i var and rangei for each number i would like to split its digits and add them together,['javascript'] +204912,ruby array limit method i want to limit an array object how is this possible with rubyonetwothreelimit2 onetwothanks for your quick help,['ruby'] +204917,androidjava determining if text color will blend in with the background i am introducing tagging functionality in my application and one of the ways i allow tags to be thisplayed is to set the text to the color the user has selected for each my application has three themes with backgrounds that are white black and a notepadlike brown these could changegrow in the future i want to be able to thisplay the tag in its native color if it easily contrasts the background and just use the default text color for each theme otherwisei have written a helper function to help me determine if the text will be masked but its not 100 correct i want it to determine if colors will be masked based on all three of the hsv components and right now the saturation comparison is not valid the code is below public static boolean colorwillbemaskedint color application app float hsv new float3 colorcolortohsvcolor hsv note 0 black 1 white 2 int theme appapigetthemeview systemoutprintlnh hsv0 s hsv1 v hsv2 themetheme ifandroidrcolortransparent color return true color is dark ifhsv2 2 iftheme 1 return true color is light else ifhsv2 8 iftheme 2 return true return false when calling this function with blue red transparent black yellow and green the output is as follows respectivelyh00 s10 v10 theme1h22941177 s10 v10 theme1h2676923 s10 v0050980393 theme1h00 s00 v00 theme1h5952941 s10 v10 theme1h129411 s10 v10 theme1my question is based on hue saturation and value how can you determine if text that is colored a certain way will show up on a white background vs a black background or if it will be masked please take my algorithm and improve it or help me create a new onethanks in advance,"['java', 'android']" +204934,lua equivalent for numpy and scipy i am thinking of learning lua i learned that it is a smaller language compared to python and has an efficient jit compiler implementation in the form luajiti would like to know is it possible to use lua the way i use python with numpyscipyfurther if lua has numpyscipy equivalent does it have a matplotlib equivalent,['python'] +204948,php foreach why using pass by reference of a array is fast below is a test of php foreach loop of a big array i thought that if the v do not change the real copy will not happen because of copy on write but why it is fast when pass by referencecode 1function test1a c 0 foreacha as v ifvx c function test2a c 0 foreacha as v ifvx c x array fill0 10 xbegin microtimetruetest1xend1 microtimetruetest2xend2 microtimetrueecho end1 begin n 00332025847echo end2 end1 002147388458252but this time using pass by reference is slowcode 2function test1a cnt counta c 0 fori0 icnt i ifaix cfunction test2a cnt counta c 0 fori0 icnt i ifaix cx array fill0 10 xbegin microtimetruetest1xend1 microtimetruetest2xend2 microtimetrueecho end1 begin n 00243268013049echo end2 end1 0037616014480591can someone explain why passing by reference is fast in code1 but slow in code2editwith code 2 the counta makes the main difference so the time of the loop took is almost the same,['php'] +204963,python check if a process is running or not i am trying to create a python script which i will later run as a service now i want to run a particular part of the code only when itunes is running i understand from some research that polling the entire command list and then searching for the application for that list is expensive i found out that programs in unix based operating systems create a lock file to notify that a program is currently running so we can use osstatlocation of file to check if the file exists to determine if a program is running or notis there a similar lock file created in windows if not what are the various ways in python by which we can determine if a process is running or not i am using python 27 and itunes com interface,['python'] +204972,how to get all amazon category products what is the way to get all amazon products from existing category with the api i can just can browse 10 pages and get for each page 10 prodcutson the category it shows there is 502348 products i want to be able to get them allthank you for your helpamazon product advertising api php params array operation itemsearch searchindexelectronics browsenode281052 responsegroupsmall merchantid all conditionnew itempage1471,['php'] +204977,how to write a function that takes a functor as an argument basically i want to do thiscan i use a lambda function or stdfunction object in place of a function pointerclearly that is impossible for now for functions that expect a function pointer however it will work for a function that expects a functor i have done it before with stls sort functionhowever i do not know how to write a function that takes a functor as an argumentanyone,['c++'] +204979,css class selector to select text inside a div i have a div with a classname test the class test has a cursor pointer assigns to it the class also has a fixed width of 200px inside the div is text of length that is shorter than the width of the div i do not want the point to appear when the mouse is placed in the blank part of the div is there a way that i can assign the css pointer to the text inside the div without wrapping the text inside another span tag i just do not want to go back and add the span tag to every single div and rewrite the javascripti am thinking of something like this pseudo css codetesttext cursorpointer,"['html', 'css']" +204988,rails 31 simple form submit style css hello did anybody know how to add a class to a simple form submit button for css styleheres what i try to do formhtmlerb simple form fordrink do f fsubmit add drinkinput html class create enddrinkscscsscreate backgroundcolor2fd62f mozborderradius4px webkitborderradius4px borderradius4px border1px solid dcdcdc thisplayinlineblock colorfafafa fontfamilyarial fontsize12px fontweightbold padding7px 24px textdecorationnone textshadow0px 0px 0px 70706fcreatehover backgroundcolor2fbf0fcreateactive positionrelative top1px,"['ruby-on-rails', 'css']" +205007,memory leak when redeploying application in tomcat when i redeploy my application in tomcat i get the following issue the web application created a threadlocal with key of type javalangthreadlocal value javalangthreadlocal10d16b and a value of type comsunxmlbindv2runtimepropertysingleelementleafpropertyvalue comsunxmlbindv2runtimepropertysingleelementleafproperty1a183d2 but failed to remove it when the web application was stopped this is very likely to create a memory leakalso am using ehcache in my application this also seems to result in the following exception severe the web application created a threadlocal with key of type null value comsunxmlbindv2classfactory124cdc7 and a value of type java utilweakhashmap the ehcache seems to create a weak hash map and i get the message that this is very likely to create a memory leaki searched over the net and found this but i dont have access to the server as suchplease let me know if these warnings have any functional impact or can they be ignored i used the find memory leaks option in tomcat manager and it says no memory leaks found,['java'] +205015,using jquery to access a new windows dom i am creating a new window that will contain text that user will printi would like to do something similar to thisvar new win windowopennew windocumenthtmltest,"['javascript', 'jquery']" +205021,uipageviewcontroller gesture recognizers i have been working on an application for a while now but i could not ask this question due to the nda i have a uipageviewcontroller load with my viewcontroller the view controllers have buttons which are overridden by the pageviewcontrollers gesture recognizers for example i have a button on the right side of the viewcontroller and when you press the button the pageviewcontroller takes over and changes the pagehow can i make the button receive the touch and cancel the gesture recognizer in the pageviewcontrolleri think the pageviewcontroller makes my viewcontroller a subview of its viewi know i could turn off all of the gestures but this is not the effect i am looking fori would prefer not to subclass the pageviewcontroller as apple says this class is not meant to be subclassed,['ios'] +205090,unable to configure notepad dbgp plugin xdebug already installed i have installed xdebug on php but now i cannot make the notepad dbgp plugin worki have latest wamp version on win7 and the w folder is on partition dwi have coded a test file testphp php test 3 echo testand i have tried opening it in web browser using this link httplocalhosttestphpxdebug session starttestbut the dbgp would not connect i tried with and without ide keyi have gone through the documentation many times but was unable to findsolve the issue hopefully someone could know the reasonbelow are some screen shotsthanks,['php'] +205097,constant arrays this is a good old c arrayint a10and this is a good old c array that is constconst int b10in c there seem to be two ways to define stdarrays that are conststdarrayconst int 10 cconst stdarrayint 10 dare these two definitions equivalent if so what is the idiomatic one if not what are the differences,['c++'] +205112,convert hex code to color name how can i convert this hexa code 2088c1 into colour name like blue or redmy aim is i want to get the colour name like blue for the given hexa codei have tried the below code but it was not giving any colour name systemdrawingcolor col systemdrawingcolortranslatorfromhtml2088c1color col colorconverterconvertfromstring2088c1 as colorbut it does not giving the colour name like this aquabluei am using winforms applications with c,['c#'] +205126,css link and visited pseudoclasses are web browsers adhering to the spec the w3org css specification states the following emphasis minethe link pseudoclass applies for links that have not yet been visitedthe visited pseudoclass applies once the link has been visited by the userthe two states are mutually exclusivethis means that any style applied to the link selector should only be applied to unvisited links however the only property for which this is true appears to be color applying font sizes backgrounds and so on to the link selector targets all linksthere is a note further down the page that statesnote it is possible for style sheet authors to abuse the link and visited pseudoclasses to determine which sites a user has visited without the users consentuas may therefore treat all links as unvisited links or implement other measures to preserve the users privacy while rendering visited and unvisited links differentlyhowever as far as i am aware this only applies to the styles returned by javascript not to the thisplay of the styles themselvesheres a js fiddle showing the issue are the browsers deviating from the spec here or is there something i am missing,['css'] +205132,most efficient way to scale an array in java apologies if this has been asked before i cannot believe it has not but i could not find one perhaps my searchfu is weakfor years i have known that java has no native function to scale an array ie multiply each element by a constant so i have been doing thisfor int i0 iarraylength i arrayi arrayi scalefactoris this actually the most efficient way in this application for example it is an array of around 10 doubles or is there a better way,['java'] +205141,jquery clearing form inputs i have tried to different ways to clear a formform actionservicephp idaddrunner nameaddrunner methodpostfirst name input typetext nametxtfirstname idtxtfirstname br last name input typetext nametxtlastname idtxtlastname br gender select idlgender nameddlgenderoption valueplease selectoptionoption valueffemaleoptionoption valuemmaleoptionselectbr finish timeinput typetext nametxtminutes idtxtminutes size10 maxlength2minutesinput typetext nametxtseconds idtxtseconds size10 maxlength2secondsbr button typesubmit namebtnsave idbtnsaveadd runnerbuttoninput typehidden nameaction valueaddrunner idactionformjquery 1function clearinputstxtfirstnamevaltxtlastnamevalddlgendervaltxtminutesvaltxtsecondsvalthis works perfectlyjquery 2function clearinputsdataaddrunner inputeachfunctionthisvalthis clears the form but does not let me submit any more any information to it i try and click the button again and it does nothingheres the button click handlerbtnsaveclickfunction var data addrunner inputserializearray postaddrunnerattraction data functionjson if jsonstatus fail alertjsonmessage if jsonstatus success alertjsonmessage clearinputs jsonphp post codephpif post if postaction addrunner fname htmlspecialchars posttxtfirstname lname htmlspecialchars posttxtlastname gender htmlspecialchars postddlgender minutes htmlspecialchars posttxtminutes seconds htmlspecialchars posttxtseconds ifpreg matchwsi fname preg matchwsi lname failinvalid name provided if emptyfname emptylname failplease enter a first and last name if emptygender failplease select a gender if emptyminutes emptyseconds failplease enter minutes and seconds time minutesseconds query insert into runners set first namefname last namelname gendergender finish timetime result db connectionquery if result msg runner fname lname added successfully successmsg else failinsert failed exit if i use jquery method 2 i get this error in the consoleuncaught typeerror cannot read property status of nullwhy does this happeni forgot to include this key informationfunction fail message diejson encodearraystatusfail messagemessagefunction success message diejson encodearraystatussuccess messagemessagethis sends the message back to the ajax function in jquery it looks like after i submit the form once using method 2 the successfail messages are blanked out,['jquery'] +205147,user access token for search via facebook graph according to the instruction given here searching public information as typeobject type needs to have a valid access token as i know access token is when a user authorized an apps to access his information but this is searing the public information how to get an apps access token to search public informationin that page facebook automatically add my access token to the link astypepostaccess tokenmy access tokeni created an access token by my apps as tokenclient idapp idclient secretsecret idgrant typeclient credentialswhen i use the generated access token in url typepostaccess tokengenerated access token it gives an error error message a user access token is required to request this resource type oauthexception how can i generate access token by my appsor do i need to generate access token by own user account if yes howsince it is searching public profile facebook should not need authorization on every search can i generate a permanent access token to perform different searches,['php'] +205150,ways to combine css i have multiple css files the designer made several bad iterations that i need to combine to a single file however i do not want to just cat them together i want to merge the properties for like selectors iefile 1mainmenu width100 background01568b textdecoration none file 2mainmenu width100 background01568bwhere the output would bemainmenu width100 background01568b textdecoration noneobviously this is a simple example but should explain what i am looking to do are there any tools available or am i going to have to do this the hard way,['css'] +205198,how to version dynamic business objectsdata we are developing a large applications which are related to business you can find these applications similar to some erp crm etcnow we have a requirement that we need all the data which are entered by the user to be versionedfor example at some point of time the user would need to see whats the change history of a particular purchase orderi am looking for a very generic versioning handler not rigid which could handle even cases if some some business data attributes gets changed this single versioning handler should be able to work with almost any type of business objectsdatawhat would be the best programmingdatabase design to handle theseany ideas or opinionsps i have added some programming tags as i want programmers to entertain this thread and give their ideasediti am looking for a very optimized way somewhat similar to having diffs beings stored rather than storing the objects in a serializeddumping way,"['php', '.net']" +205199,how do i apply jquery ui styles to normal form elements like input and select tags maybe i am missing something but after reading the jquery ui docs i do not see anything about applying theme styles to normal widgets like input and select tags after calling button on buttons and datepicker on input tags that will pick dates am i supposed to wrap normal textareas and inputs in a div classuiwidget to give a consistentlooking style or give them a certain css class or call a function on document load that styles everything else,['css'] +205213,algorithm used in ruby for stringinclude is anyone able to pinpoint which algorithm is used for the include method in ruby for example helloworldincludehello,['ruby'] +205216,how to set up autotest to rerun only failing rspec examples my impression of how autotest is intended to work based on the cucumber github wiki and other stuff online is that it should rerun red examples until they pass my problem is that it reruns all examples in the spec file where a failing example is found including passing ones i would rather not waste time rerunning passing examples while fixing a failing one can autotest be configured so only the failing examples are run,['ruby'] +205219,validation failed for one or more entities see entityvalidationerrors property for more details i am having this error when seeding my database with code first approachvalidation failed for one or more entities see entityvalidationerrors property for more detailsto be honest i do not know how to check the content of the validation errors visual studio shows me that its an array with 8 objects so 8 validation errorsthis was working with my previous model but i made a few changes that i explain belowi had an enum called status i changed it to a class called statusi changed the class applicantspositionhistory to have 2 foreign key to the same tableexcuse me for the long code but i have to paste it all the exception is thrown in the last line of the following codenamespace datamodel public class position databasegeneratedsystemcomponentmodeldataannotationsdatabasegeneratedoptionidentity public int positionid get set requirederrormessage position name is required stringlength20 minimumlength 3 errormessage name should not be longer than 20 characters thisplayname position name public string name get set requirederrormessage number of years is required thisplayname number of years public int yearsexperiencerequired get set public virtual icollectionapplicantposition applicantposition get set public class applicant databasegeneratedsystemcomponentmodeldataannotationsdatabasegeneratedoptionidentity public int applicantid get set requirederrormessage name is required stringlength20 minimumlength 3 errormessagename should not be longer than 20 characters thisplayname first and lastname public string name get set requirederrormessage telephone number is required stringlength10 minimumlength 3 errormessage telephone should not be longer than 20 characters thisplayname telephone number public string telephone get set requirederrormessage skype username is required stringlength10 minimumlength 3 errormessage skype user should not be longer than 20 characters thisplayname skype username public string skypeuser get set public byte photo get set public virtual icollectionapplicantposition applicantposition get set public class applicantposition key columnapplicantid order 0 public int applicantid get set key columnpositionid order 1 public int positionid get set public virtual position position get set public virtual applicant applicant get set requirederrormessage applied date is required thisplayformatdataformatstring 0d applyformatineditmode true thisplayname date applied public datetime applieddate get set columnstatusid order 0 public int statusid get set public status currentstatus get set notmapped public int numberofapplicantsapplied get int query from ap in position where apstatus intstatusapplied select ap count return query public class address stringlength20 minimumlength 3 errormessage country should not be longer than 20 characters public string country get set stringlength20 minimumlength 3 errormessage city should not be longer than 20 characters public string city get set stringlength50 minimumlength 3 errormessage address should not be longer than 50 characters thisplayname address line 1 public string addressline1 get set thisplayname address line 2 public string addressline2 get set public class applicationpositionhistory databasegeneratedsystemcomponentmodeldataannotationsdatabasegeneratedoptionidentity public int applicationpositionhistoryid get set public applicantposition applicantposition get set columnoldstatusid public int oldstatusid get set columnnewstatusid public int newstatusid get set public status oldstatus get set public status newstatus get set stringlength500 minimumlength 3 errormessage comments should not be longer than 500 characters thisplayname comments public string comments get set thisplayformatdataformatstring 0d applyformatineditmode true thisplayname date public datetime datemodified get set public class status databasegeneratedsystemcomponentmodeldataannotationsdatabasegeneratedoptionidentity public int statusid get set stringlength20 minimumlength 3 errormessage status should not be longer than 20 characters thisplayname status public string status get set using systemusing systemcollectionsgenericusing systemlinqusing systemtextusing systemdataentityusing systemionamespace datamodel public class hrcontextinitializer dropcreatedatabasealwayshrcontext protected override void seedhrcontext context region status status applied new status status applied status reviewedbyhr new status status reviewed by hr status approvedbyhr new status status approved by hr status rejectedbyhr new status status rejected by hr status assignedtotechnicaldepartment new status status assigned to technical department status approvedbytechnicaldepartment new status status approved by technical department status rejectedbytechnicaldepartment new status status rejected by technical department status assignedtogeneralmanager new status status assigned to general manager status approvedbygeneralmanager new status status approved by general manager status rejectedbygeneralmanager new status status rejected by general manager contextstatusaddapplied contextstatusaddreviewedbyhr contextstatusaddapprovedbyhr contextstatusaddrejectedbyhr contextstatusaddassignedtotechnicaldepartment contextstatusaddapprovedbytechnicaldepartment contextstatusaddrejectedbytechnicaldepartment contextstatusaddassignedtogeneralmanager contextstatusaddapprovedbygeneralmanager contextstatusaddrejectedbygeneralmanager endregion region position position netdeveloper new position name net developer yearsexperiencerequired 5 position javadeveloper new position name java developer yearsexperiencerequired 5 contextpositionsaddnetdeveloper contextpositionsaddjavadeveloper endregion region applicants applicant luis new applicant name luis skypeuser levalencia telephone 0491732825 photo filereadallbytescusersluissimbiosdocumentsvisual studio 2010projectsslnhrhrrazorformscontentpictures1jpg applicant john new applicant name john skypeuser jovalencia telephone 3435343543 photo filereadallbytescusersluissimbiosdocumentsvisual studio 2010projectsslnhrhrrazorformscontentpictures2jpg contextapplicantsaddluis contextapplicantsaddjohn endregion region applicantspositions applicantposition appicantposition new applicantposition applicant luis position netdeveloper applieddate datetimetoday statusid 1 applicantposition appicantposition2 new applicantposition applicant john position javadeveloper applieddate datetimetoday statusid 1 contextapplicantspositionsaddappicantposition contextapplicantspositionsaddappicantposition2 endregion contextsavechanges error here,['c#'] +205231,how do i get urlaction to use the right port number i am creating a website using mvc3 i am using the razor syntax to create the views and it is all running under azurecurrently i am running under the azure emulator locallyi have a view at the url httplocalhost81blahfooin that view i want to get the url for another actionto achieve this i use urlactionsomeaction somecontroller null thisrequesturlschemehowever because of the load balancing the azure emulator does the port number the request is made on changesie whilst it is running on port 81 the request might come from port 82this leads to to create an incorrect url httplocalhost82blahbar and i get a 400 bad hostname errorfollowing the info in this post i found that i could get the correct host and port number using httpcontextrequestheadershostbut i can only pass a hostname to urlaction if i try passing the hostname and port then it still appends what it thinks is the right port so i end up with localhost8182edit i found someone with the same problem they seem to have gathered the same information i have except they have included a reproduction too but they do not have a useful fix as i cannot specify the port number manuallyi suppose one fix would be to make my own urlaction overload that lets me specify the port,['asp.net'] +205246,pattern to avoid nested try catch blocks consider a situation where i have three or more ways of performing a calculation each of which can fail with an exception in order to attempt each calculation until we find one that succeeds i have been doing the followingdouble valtry val calc1 catch calc1exception e1 try val calc2 catch calc2exception e2 try val calc3 catch calc3exception e3 throw new nocalcsworkedexception is there any accepted pattern which achieves this in a nicer way of course i could wrap each calculation in a helper method which returns null on failure and then just use the operator but is there a way of doing this more generally ie without having to write a helper method for each method i want to use i have thought about writing a static method using generics which wraps any given method in a trycatch and returns null on failure but i am not sure how i would go about this any ideas,['c#'] +205248,are there any working examples of zolera soap infrastructure zsi i have looked at examples and googled but could not find a single usable example,['python'] +205274,how to save a timezone correctly with ruby and mongoid please excuse me if this is a bit of a noob issuei have an app where users can set their own timezones in their profilewhen someone adds a lineup app specific terminology i do the followingtime activesupporttimezonenewusertimezoneparse wednesday 26 october 2011 1330 this outputs 201026 1330 0200 valid according to the user selected tzi then save the lineuplineupcreate date timegmtime uid user id pid product idthis should in theory save the date as gmtime but i get the following when viewing the record id objectid4e9c6613e673454f9302 date wed 26 oct 2011 13 30 00 0200 uid 4e9b81f6e673454c8a01 pid 4e9c6613e673454f9301 created at mon 17 oct 2011 19 29 55 0200as you can see the date field is wrong it still maintaining the user timezone it should be gmt not timezone specificif i output timegmtime i get the right time that should be saved201026 1130 utc correctany ideas how to save the gmt date so that it actually saves the gmt date,['ruby'] +205303,transitioning from xib files to storyboard possible duplicateiphone ios5 storyboard how to load a uiviewcontroller with a custom xib file i currently have an xcode project that uses xibs and would like to start using storyboards is there a good way to move my xib files into the storyboard,"['iphone', 'ios']" +205311,add duration to js settimeout after the timer is running i am trying to figure out a way to emulate as3s timer classif youre not familiar one of the cool things you can do is add duration to the timer even if it is already running this functionality has a lot of very nice uses anyone have any thoughts on doing this in js,['javascript'] +205316,unresolved inclusion error while using ndk i am using android ndk but the c file in the jni folder is showing the error of unresolved inclusion as shown in the image kindly help me in solving this issue i have tried almost everything i could find on internet but unable to solve it for a cc project i can use the build pathpaths and symbols option to solve the inclusion but for an android project this option is not available in project properties,['android'] +205318,permission denied to access property href i try to reload parent web page from iframe here is my code scriptdocumentreadyfunction windowparentlocationhref windowparentlocationhref scriptbut it doesna t work firebug says permission denied to access property hrefia m on same domain so whata s the problem i try to do it in wordpress theme,['javascript'] +205331,exceptions signaling endofiterator why is it bad in java and normal in python i am really confused the standard approach in java is to throw exceptions only in abnormal conditions and not to use them to signal endofiteratorexamples effective java item 57 use exceptions only for exceptional conditions and javaspecialists newsletter 162flow controlwe should never cause an exception that is otherwise preventable i have seen code where instead of checking bounds it is assumed that the data will be correct and then runtimeexceptions are caughthere is an example of bad code please do not code like thispublic class antipattern1 public static void mainstring args try int i 0 while true systemoutprintlnargsi catch arrayindexoutofboundsexception e we are done whereas it is standard to use this idiom in python eg stopiterationexception stopiterationraised by an iteratoras next method to signal that there are no further values this is derived from exception rather than standarderror since this is not considered an error in its normal applicationwhy is it bad for java but good for python,"['java', 'python']" +205333,python need to close file from mkstemp if i use fdopen which of the following is more correctfi path tempfilemkstempf osfdopenfi wfwriteresfcloseosclosefiorfi path tempfilemkstempf osfdopenfi wfwriteresfclose,['python'] +205336,ios how to set a uiswitch programmatically i want to set my uiswitch to on or off programmatically how would i do that i am an ios newbie,"['objective-c', 'ios']" +205343,jframe exit on close java i do not get how can i employ this codeframesetdefaultcloseoperationjframeexit on closeto close the program with the x button,['java'] +205392,ios uitableview refresh table properly i have lots of data and lots of rows in my tableviewwhen data changes i want to update my visible cells on the screen i really do not want to use reloaddata because it is an expensive callis it possible to somehow update the visible cells onlyi tried calling beginupdate endupdate on the table but that does not work all the timeany suggestions,"['iphone', 'ios']" +205403,annoying invalid credentials with oauth 20 google api i am trying to use oauth 20 for the google api on my site and i keep getting error errors domain global reason autherror message invalid credentials locationtype header location authorization code 401 message invalid credentials the thing is i do not know why this is happening i have a valid access token from google but google tells be it is invalid i know that the token has not expired because the json data is request from google within 10 seconds of getting the access token here is the process that i am usingget user to authorize the request gets request code from googleuses curl to request access token with the request code from googleputs the access code into a php sessionredirects back to the main pagemain page detects session variable is set and does not thisplay login linkphp on main page uses readfile to get the json response from googlegoogle returns invalid credentialshere is a example uri generated by php that is inserted into readfileaccess tokenya29ahes6zqrgovda5fhsoju3qcm1denymjpywz1muue4cwgh5n70ocakwhelp please,['php'] +205428,email an attachment in r with gmail i am desiring to send an email in r with an attachment using gmail i have found that sendmailr does not work with gmail because it requires authentication i could not get it to work with gmail so i assume this to be true unless someone tells me i am wrong in which case i will post the r output and error message for that i found a code snippet found here link as the site suggests the code is not formatted to send attachments but i have got it to send an email i would like to extend this code to send attachments in an email correspondence the author of this code was unable to extend the code to send attachmentsi want to send emails with r using gmail i am a windows 7 user with the 214 beta version of r the code that sends emails but not attachmentsrequirerjython rjython rjython rjythonexec import smtplib rjythonexecfrom emailmimetext import mimetext rjythonexecimport emailutils mailc email settings fromaddr toaddrs msg mimetextthis is the body of the message msgfrom emailutilsformataddrsender name fromaddr msgto emailutilsformataddrrecipient name toaddrs msgsubject simple test message smtp server credentials username password pw set smtp server and send email eg google mail smtp server server smtplibsmtpsmtpgmailcom587 serverehlo serverstarttls serverehlo serverloginusernamepassword serversendmailfromaddr toaddrs msgas string serverquit jythonexecrjythonmail note this message is cross posted at talkstatscom i did not receive a reply there just members telling me they wish they could help if i receive a workable solution i will also post it there as well,['python'] +205434,setting focus on a button is not working i am trying to set the focus to a button while the user presses the enter key in the text box but it is not working i am using the internet explorer 8 browser am i missing somethinginputboxlivekeydown functione if ekeycode 13 epreventdefault buttonfocus not working,['jquery'] +205466,how to change background image of button when clickedfocused i want to change the background image of a button when clicked or focusedthis is my codebutton tiny buttonfindviewbyidridtinytinysetonclicklistenernew onclicklistener override public void onclickview v todo autogenerated method stub button tiny buttonfindviewbyidridtiny tinysetbackgroundresourcerdrawablea9p 09 11 00754 textview txt textviewfindviewbyidridtxt txtsettext on click is this code right does it calls a button on its event,['android'] +205468,what python accessible tools can you use to generate xsd from an xml document i am looking for a tool that will play nicely with python except for my python requirement my question is the same as this one i am looking for a tool which will take an xml instance document and output a corresponding xsd schema,['python'] +205537,how to change android seekbar track start position i would like to set the seekbarss track start position so it does not start from the left side of the seekbar but form an arbitrary position here is a photoshop image how it should look likeit should be just a graphical effect the seekbars underlying logic is not changedi tried to change the seekbargetprogressdrawablesetbounds to change the track image position but no luck,['android'] +205544,using mac book built in camera with ios simulator i am new to ios application development and i am using xcode4 i am trying to develop an application which uses the camera for testing is there a way to integrate the built in camera of mac book to ios simulatorthanks,"['iphone', 'ios']" +205549,css3 transformscale in ie i would like to use the css3 property transformscalediv transform scale0505is there a way to imitate this in internet explorer 8 and lowermay be something with filter or a javascript solutioni have searched the web without any resultthanks a lot vincent,['css'] +205575,how to set the buttons label text color for state uicontrolstatehighlighted i am creating an iphone application in which i have a custom button i have set the buttons title by creating a label and adding it as subview now when the button is highlighted i want to change the labels text color here is my codeuibutton button1 uibutton buttonwithtypeuibuttontypecustom button1 setframecgrectmake68162 635 101 button1 setimageuiimage imagenamedstartwithouttextpng forstateuicontrolstatenormal button1 setimageuiimage imagenamedstartactivewithouttextpng forstateuicontrolstatehighlighted uilabel buttonlabel uilabel alloc initwithframecgrectmakebutton1boundsoriginx50 button1boundsoriginy20 button1boundssizewidth100 button1boundssizeheight40 buttonlabel setfontuifont fontwithnamehelvetica size28 buttonlabelbackgroundcoloruicolor clearcolor buttonlabeltextcoloruicolor colorwithred8302550 green8302550 blue8302550 alpha10 buttonlabelhighlightedtextcoloruicolor whitecolor buttonlabeltext long text string button1 addsubviewbuttonlabel button1 bringsubviewtofrontbuttonlabel button1 setcontentverticalalignmentuicontrolcontentverticalalignmentcenter button1 setcontenthorizontalalignmentuicontrolcontenthorizontalalignmentcenter button1 addtargetself actionselectorbutton1clicked forcontroleventsmainview button1 can any body help me to change the text color when the button is highlighted,"['iphone', 'objective-c']" +205582,drawing with glkit i am trying to write a game using opengl but i am having a lot of trouble with the new glkit classes and the default template from ios voidviewdidload super viewdidload selfcontext eaglcontext alloc initwithapikeaglrenderingapiopengles2 if selfcontext nslogfailed to create es context ifrenderer renderer rendermanager sharedmanager tiles tileset allocinit glkview view glkview selfview viewcontext selfcontext viewdrawabledepthformat glkviewdrawabledepthformat24 self setupgl voidsetupgl int width self view boundssizewidth int height self view boundssizeheight eaglcontext setcurrentcontextselfcontext selfeffect glkbaseeffect alloc init selfeffectlight0enabled gl true selfeffectlight0diffusecolor glkvector4make04f 04f 04f 10f configure buffers glgenframebuffers1 framebuffer glbindframebuffergl framebuffer framebuffer glgenrenderbuffers2 colourrenderbuffer glbindrenderbuffergl renderbuffer colourrenderbuffer glrenderbufferstoragegl renderbuffer gl rgba8 oes width height glframebufferrenderbuffergl framebuffer gl color attachment0 gl renderbuffer colourrenderbuffer glgenrenderbuffers3 depthrenderbuffer glbindrenderbuffergl renderbuffer depthrenderbuffer glrenderbufferstoragegl renderbuffer gl depth component16 width height glframebufferrenderbuffergl framebuffer gl depth attachment gl renderbuffer depthrenderbuffer confirm everything happened awesomely glenum status glcheckframebufferstatusgl framebuffer ifstatus gl framebuffer complete nslogfailed to make complete framebuffer object x status glenablegl depth test enable the opengl states we are going to be using when rendering glenableclientstategl vertex array voidglkviewglkview view drawinrectcgrectrect glclearcolor04f 04f 04f 10f glcleargl color buffer bit gl depth buffer bit glbindframebuffergl framebuffer framebuffer float iva 0 0010 1010 10 glvertexpointer3 gl float sizeoffloat 3 iva gldrawarraysgl points 0 4endwith this the buffer clearsto a grey colour but nothing from the vertex array renders i have no idea what to do from here and due to the age of the technology there is not much information available on how to properly use glkit,['ios'] +205593,how to get pixel colour in android i am using intent to call and show an image from gallery and now i made it enable to get me the coordinates of the image in a textview using thesefinal textview textview textviewfindviewbyidridtextview final textview textviewcol textviewfindviewbyidridtextviewcolortargetimagesetontouchlistenernew imageviewontouchlistener override public boolean ontouchview v motionevent event todo autogenerated method stub int x0 int y0 textviewsettexttouch coordinates stringvalueofeventgetx x stringvalueofeventgety imageview imageview imageviewv bitmap bitmap bitmapdrawableimageviewgetdrawablegetbitmap int pixel bitmapgetpixelxy int redvalue colorredpixel int bluevalue colorbluepixel int greenvalue colorgreenpixel ifpixel colorred textviewcolsettextit is red ifredvalue 255 ifbluevalue 0 ifgreenvalue0 textviewcolsettextit is red return true now what i need to do is to get the colour rgb value of the exact coordinates the user selects and later on assign each to ff0 00ff00 and 0ff but for now please help to get the pixel colour based on what i havecheers,['android'] +205602,apache mod proxy configuring proxypass proxypassreverse for crossdomain ajax calls i am creating an html5 javascript app for mobile devices using phonegap i have to interact with a rest servicethe service is now running on httplocalhost8080backendmvci am developing my app on an wamp server apache2 httplocalhoststagei am using chrome for browserwhen preforming an ajax call the browser responds xmlhttprequest cannot load httplocalhost8080backendmvcevent origin httplocalhost is not allowed by accesscontrolalloworiginso i find several ways to circumvent this crossdomain ajax call problem1 starting chrome chromeexe thisablewebsecurity no difference2 configuring apache using mod proxy to redirect the traffici enabled in the httpdconf proxy moduleproxy connect moduleproxy http modulei put a htaccess file in the w root with the following content start mod rewriterewriteengine onproxyrequests offproxy order denyallow allow from allproxyproxypass embackend httplocalhost8080backendmvcproxypassreverse embackend httplocalhost8080backendmvcrewriterule embackend backendmvc1 ri restarted all services apachephpresulting in error 500apache error log tue oct 18 143011 2011 alert client 127001 cwampwhtaccess proxyrequests not allowed hereany clues on how to resolve this,['javascript'] +205604,check if array is not empty updatevar dump string0 i am trying to check if part of an array is not empty then thisplay code but the code gets thisplayed anywayi have tried is null empty i am not really sure which should be correct or should i go with if sizeofbookbookingcomments0codephp if emptybookbookingcomments table width100 border0 tbody tr td stylefontfamilylucida grande sansseriffontsize12pxfontweightnormalcolor6 bookbookingcomments td tr tbody table arrayarraybooking array id 109 user id 1 corporate account id 0 id ref res0109 price 17800 arrival 201018 0 departure 201019 0 rate title adult guests 4 child guests 0 company gravitate titlename firstname seon surname gleeson address1 8 crow st address2 city dublin state co dublin postcode 2 country ireland phone 0863269087 mobile fax email comments created 201018 134047 updated 201018 134047 status 1 cancelled 0 request src website request token 0 token ayzrgnx survey sent 0 0 survey returned 0 0 send sms 0 payment time 0 0 fullname seon gleeson,['php'] +205625,casting pointertofunction with ellipsis consider the following programinclude iostreamtypedef void fptrvoid foofptr func func12void barint x stdcout bar x stdendlint main foofptrbarthis compiles runs and prints bar 12 on at least one compiler i found this in some legacy code i am supposed to maintain and i wonder if this is safedefinedbar does not match the type fptr so the only way to get this to work is by using an unsafe cast i guess it depends on how the ellipsismagic works internally so is that defined in some way,['c++'] +205626,jpa 20 using hibernate as provider exception no persistence provider for entitymanager i am trying to set up a simple jpa 20 project by following the information in the hibernate entitymanager documentation i have been on this for hours now but no matter what i do i always get this exception when i try to create a entitymanagerfactoryexception in thread main javaxpersistencepersistenceexception no persistence provider for entitymanager named manager1 at javaxpersistencepersistencecreateentitymanagerfactorypersistencejava54 at javaxpersistencepersistencecreateentitymanagerfactorypersistencejava32 at semycompusertestmainusertestjava9i have found quite a few similar questions regarding this exception but no solutions that i am able to get to work what am i doing wrong heredirectory structurea pomxmla src a main aa a a java aa a aa a a se aa a aa a a mycomp aa a aa a a usertestjava aa a aa a a domain aa a aa a a userjava aa a a resources aa a a metainf aa a aa a a persistencexml aa a a log4jproperties a test a javamy persistencexmlpersistence xmlns xmlnsxsi xsischemalocation 2 0xsd version20 persistenceunit namemanager1 transactiontyperesource local providerorghibernateejbhibernatepersistenceprovider clasemycompdomainuserclass properties property namehibernatedialect valueorghibernatedialectmysql5innodbdialect property namehibernatehbm2ddlauto valuecreatedrop property namejavaxpersistencejdbcdriver valuecommysqljdbcdriver property namejavaxpersistencejdbcurl valuejdbcmysqllocalhosttest property namejavaxpersistencejdbcuser valuetest property namejavaxpersistencejdbcpassword value1234 properties persistenceunitpersistencemy pomxmlproject xmlns xmlnsxsixsischemalocation modelversion400modelversiongroupidseliltryjpagroupidartifactidtryjpaartifactidversion10snapshotversionpackagingjarpackagingproperties projectbuildsourceencodingutf8projectbuildsourceencoding hibernatecoreversion364finalhibernatecoreversion mysqlconnectorjavaversion5116mysqlconnectorjavaversion slf4jversion161slf4jversion log4jversion161log4jversionpropertiesdependencies hibernate dependencies dependency groupidorghibernategroupid artifactidhibernatecoreartifactid versionhibernatecoreversionversion dependency mysql dependencies dependency groupidmysqlgroupid artifactidmysqlconnectorjavaartifactid versionmysqlconnectorjavaversionversion dependency logging dependencies dependency groupidorgslf4jgroupid artifactidslf4japiartifactid versionslf4jversionversion dependency dependency groupidorgslf4jgroupid artifactidslf4jlog4j12artifactid versionlog4jversionversion dependencydependenciesbuild plugins plugin groupidorgapachemavenpluginsgroupid artifactidmavencompilerpluginartifactid version232version configuration source16source target16target optimizetrueoptimize debugtruedebug configuration plugin plugin groupidorgapachemavenpluginsgroupid artifactidmaveneclipsepluginartifactid version28version configuration downloadsourcestruedownloadsources configuration plugin pluginsbuildusertestjavapublic class usertest public static void mainstring args entitymanagerfactory emf persistencecreateentitymanagerfactorymanager1 entitymanager em emfcreateentitymanager,['java'] +205632,what does the hash mean after a js file what is the significance of the hash here how does it relate to the js filescript srcfoojsbar1script,"['javascript', 'html']" +205698,specify generics class where t should be subclass of other type here is what i am trying to do not even sure if possiblei am creating baseviewmodelt and i want it to accept types inherited from entityconsider this codepublic abstract class baseviewmodelt notificationobject inavigationawarepublic t myentitypublic somemethodmyentitysomeentityproperty somevalueso i want to say that my t inherited from entity and therefore i know that it will have someentityproperty is this possible,['c#'] +205715,sql server backup restore issues ok so i am having a bit of an issue i executed some code on my sql server and did not realize that i did not have the where bit selected of course when i saw the 608 rows affected rather than 1 row affected i freaked a bit luckily i have a backup saved but for some reason i am getting a couple issues now i took the server down so i know that it is not being used by anyone but it is giving me the following errorrestore failed for server myserversystemdatasqlclientsqlerror exclusive access could not be obtained because the database is in use microsoftsqlserversmoi saw something that stated i should be using alter database databasesset single user with rollback immediaterestore database productfrom thisk but i am having three reservations about this code first i am completely unsure of how to turn multi user back on second i do not know where the program stores its backups third this sql is a bit above my head i am relatively new to the language honestly so i am not sure how this will affect thingsanyone have any answers to my troubles,['sql'] +205728,whats the best way to swap xcode contents for projects intended for many clients i have got a relatively large xcode project that produces a single app however i have many clientscustomers who require deep customization and branding of said app these configurations include different graphics a few different interfaces and implementations and perhaps most importantly xcconfig filesmy xcode project has a dedicated group that points to a particular clients customization folder on thisk so by opening the xcode project and building you get a build of the single app with the current clients customizations to switch to another client i change where that group points to on thisk i also change and switchback the xcconfig based on settings in the projects info pane to reload the full xcconfig inheritance simply changing the group containing one or more xcconfig files does not reload this this has worked great for 100 clients it is a little tedious to switch this folder every time you need to build the app for a different client and ensure the xcconfig is correct but it worksnow i am in the process of automating builds via the command line and running into troubles the quick and dirty solution to pointing the aforementioned xcode group at a different customization folder was to copy the projectnamexcodeprojprojectpbxproj file to projectnamexcodeprojprojecttemplatepbxproj and put placeholders inside this file that can be grepped and replaced with the name and path of the desired customization folder then temporarily overwrite projectpbxproj with the modified projecttemplatepbxproj and build to get the correct appas youve probably observed the projectpbxproj was duplicated and modified and will therefore get out of sync as developers modify the original and forget to also update the template and besides i should not really be messing with pbxproj files in this fashion anyway that is xcodes private stuffso is there a better way to tell xcode about a folder full of resources code and config files perhaps during the build phase with a script or environment variable rather than at the project group level the most complicated bit seems to be the xcconfig chain since each client has their own xcconfig file that inherits from the single apps debug development and thistribution xcconfig filessorry for the longwindedness of this question but it is a little complicated any suggestions would be greatly appreciated,['ios'] +205729,how to return a compound literal struct i have a function that will always return a struct with known values what is the syntaxstruct mystruct functionvoid return struct mystruct123i am getting a compiler error on the return lineerror syntax errorany ideas i am using a crosscompiler to an embedded target so it could be my compilereditit is my compiler as cnicutar commented it is valid c99 codesome people pointed out that i could create a variable my goal was to avoid creating a variable just to return it,['c'] +205744,jquery ajax global settings is it possible to know what eventelement trigger the ajax call this is easy enough to work around but it would be nice if it was wrapped up in the global ajax setupwhen i run an ajax call i would like to know which elementevent trigger the ajax call in the beforesend optionis there a concise way of doing this,['jquery'] +205779,how do i position the cursor on the right in edittext my application uses rtl language right to leftwhen the edittext field gets focus the cursor appears on the left and only when the user starts to type the cursor and the rtl text moves rightwhen the user clicks enter to start a new line the cursor moves to the left againwhen i use androidgravityright the cursor is ok on the right but as the user starts to type the text always moves to the the other side rtl text moves leftany ideas how i can align text to the right and keep the text direction,['android'] +205801,c naming conventions for a recursive inner functions c has a few naming conventions for commonlyseen method typesbeginfoo endfoo for async methodstryget tryparse that return false instead of throwing an exceptionfordefault for methods that return defaultt instead of throwing an exceptionisfoo for boolean flagsi was wondering is there one for recursive inner methods eg in this example from another stack overflow questionpublic int calculatesomethingrecursivelyint somenumber return dosomethingrecursivelysomenumber 0 what to call this private int dosomethingrecursivelyint somenumber int level if level max level shouldkeepcalculatingsomenumber return somenumber return dosomethingrecursivelysomenumber level 1in c i have seen people use foo foo r as a convention but how about in net,"['c#', '.net']" +205822,b tree split bug i want to be up front so i will say this homework that i am about to talk about we are suppose to do a b tree i have got it most of the way there but i am having a problem when i have a node split specifically when the node is a nonleaf excluding the root and it splits i am losing my far right pointerfor example if the tree was 3 5 1 2 4 5 6i lose the pointer to 5 6 so when i search for those values i cannot find them or when i go to add a value that would follow that path i get a null pointer exceptionanyway i normally would just paste my code here but unfortunately we have developed a problem with cheating in my school and since the program is due soon i am sure a lot of my classmates are scouring the internet for the code the last thing i want to happen is some jerk rip off my code if anyone wouldnt mind looking at the code i will gladly send it to you to check out once again it is in java and is pretty lengthythanks in advance here is the code on a side node when i clear offsets and keys i use int and long max value so when i sort i know those cleared values will go to the end of the node the split class is just a dumb idea from earlier i need to fix it consists of a node offset and key originally i was thinking that i may need to return an offset and key that was not in the split node i then realized that was dumb and all i would ever need to return was the new node itself public void add int key long offset throws ioexception if root null start search of where to add the book splitbucket split addroot key offset recursive call if split null root has split long newrootoffset make new root and have it point to old root and the split node booknode newroot new booknode newrootchangecurrentchildren1 newrootsetchildkey0 splitkey newrootsetchildoffset0 rootgetmyoffset newrootsetchildoffset1 splitoffset newrootsetchildoffset2 rootgetchildoffsetconstantschildsize 1 newrootsetnode0 root newrootsetnode1 splitnode newrootsetnode2 rootgetnodeconstantschildsize 1 iosetbooknoderootgetmyoffset root newrootoffset ioinsertnewnodenewroot iosetrootnewrootoffset root newroot else empty tree so create root and add long rootoffset longmax value root new booknode rootsetchildkey0 key rootsetchildoffset0 offset rootchangecurrentchildren1 rootswitchleaftrue rootoffset ioinsertnewnoderoot iosetrootrootoffset rootsetmyoffsetrootoffset param current current booknode param key isbn to add param offset offset of book to add return booknode if a split occurs throws ioexception private splitbucket add booknode current int key long offset throws ioexception if currentisleaf at the bottom level room to add if currentgetcurrentchildren constantschildsize 1 add the offset and key to the end of the node sort the node and rewrite to file currentsetchildoffsetcurrentgetcurrentchildren offset currentsetchildkeycurrentgetcurrentchildren key currentchangecurrentchildren1 currentsortkeysandoffsets iosetbooknodecurrentgetmyoffset current return null else not enough room must split add offset and key to end of node and sort currentsetchildkeycurrentgetcurrentchildren key currentsetchildoffsetcurrentgetcurrentchildren offset currentchangecurrentchildren1 currentsortkeysandoffsets int start currentgetcurrentchildren 2 long newnodeoffset longmax value splitbucket bucket new splitbucket booknode newnode new booknode newnodeswitchleaftrue forint i start i constantschildsize i new node will hold the larger split values newnodesetchildkeyi start currentgetchildkeyi newnodesetchildoffseti start currentgetchildoffseti newnodesetnodei start currentgetnodei newnodechangecurrentchildren1 currentsetchildkeyi integermax value currentsetchildoffseti longmax value currentsetnodei null currentchangecurrentchildren1 since sorted prior to for loop all data needs not to be sorted again newnodesortkeysandoffsets currentsortkeysandoffsets transferring presplit nodes next pointer to new node newnodesetchildoffsetconstantschildsize currentgetchildoffsetconstantschildsize newnodesetnodeconstantschildsize currentgetnodeconstantschildsize newnodeoffset ioinsertnewnodenewnode newnodesetmyoffsetnewnodeoffset currentsetchildoffsetconstantschildsize newnodeoffset currentsetnodeconstantschildsize newnode iosetbooknodecurrentgetmyoffset current bucketkey newnodegetchildkey0 bucketoffset newnodegetmyoffset bucketnode newnode return bucket else not at a leaf int index 0 find pointer index to follow while index currentgetcurrentchildren key currentgetchildkeyindex index recursive call splitbucket bucket addcurrentgetnodeindex key offset ifbucket null split occurred bucket not full so add here ifcurrentgetcurrentchildren constantschildsize currentsetchildkeycurrentgetcurrentchildren bucketkey currentsetchildoffsetcurrentgetcurrentchildren bucketoffset currentsetnodecurrentgetcurrentchildren bucketnode currentchangecurrentchildren1 currentsortkeysandoffsets iosetbooknodecurrentgetmyoffset current bucket null else bucket is full so split int start currentgetcurrentchildren 2 long newnodeoffset longmax value booknode newnode new booknode forint i start i constantschildsize i larger keys go to the new node newnodesetchildkeyi start currentgetchildkeyi newnodesetchildoffseti start currentgetchildoffseti newnodesetnodei start currentgetnodei newnodechangecurrentchildren1 currentsetchildkeyi integermax value currentsetchildoffseti longmax value currentsetnodei null currentchangecurrentchildren1 ifbucketkey newnodegetchildkey0 goes in new bucket newnodesetchildkeynewnodegetcurrentchildren bucketkey newnodesetchildoffsetnewnodegetcurrentchildren bucketoffset newnodesetnodenewnodegetcurrentchildren bucketnode newnodechangecurrentchildren1 newnodesortkeysandoffsets else goes in old bucket currentsetchildkeycurrentgetcurrentchildren bucketkey currentsetchildoffsetcurrentgetcurrentchildren bucketoffset currentsetnodecurrentgetcurrentchildren bucketnode currentchangecurrentchildren1 currentsortkeysandoffsets may not need this line and next newnodesetchildoffsetnewnodegetcurrentchildren currentgetchildoffsetconstantschildsize newnodesetnodenewnodegetcurrentchildren currentgetnodeconstantschildsize newnodeoffset ioinsertnewnodenewnode newnodesetmyoffsetnewnodeoffset iosetbooknodecurrentgetmyoffset current bucket new splitbucket return middle key value of split node bucketkey newnodegetchildkey newnodegetcurrentchildren 2 bucketoffset newnodegetmyoffset bucketnode newnode return bucket return null,['java'] +205834,how do i make makefile to recompile only changed files i have been struggling a bit to get make to compile only the files that have been edited however i did not have much success and all the files get recompiled can someone explain me whymy files aremainca functionscwhere mainc includes mainh and a functionsc includes ahhere is my makefileccgcflagswall i cexec fileprogram1all programa functionso a functionsca functionsc ahmaino maincmainc mainhobjects a functionsc mainc cc a functionsc mainc cflagsprogram a functionso maino cc a functionso maino o exec filechanging the makefile as per suggestions seems to have the same problemall programa functionso a functionsc ah gcc a functionsc cmaino mainc mainh gcc mainc cprogram a functionso maino gcc a functionso maino o program1,['c'] +205847,sortedlist desc order i am using sortedlist to arrange arraylist records dynamically in sort order by datecolumn but by default it is sorting in asc order then i have been trying to get order in desc order but not able to get it,"['c#', 'asp.net']" +205862,wpf program startup crash how to debug i have a wpf program that runs fine on the development pc and on the client pc 1 but on client pc 2 it crashes immediately on startup with the send report to microsoft window i would appreciate some advice on how to trace what is wrong heres what i have triedinserted trycatch in my main window classpublic mainwindow try messageboxshowbefore initcomp initializecomponent messageboxshowbefore sub1 subroutine1 messageboxshowbefore sub2 subroutine2 etc catch exception ex code for messagebox thisplay error here the idea is to try to isolate which part of the startup sequence is crashing but the first debug message before initcomp does not even show up so it seems the app is crashing even before starting my codeone possibility is to install the entire vs2008 in the client pc 2 load in the source and use the ide debugger to trace the problem this is likely the most effective in finding the problem but i do not want to do this because a the client pc 2 does not belong to me b it does not scale i must do likewise for client pc 345 and c it violates my firms vs2008 licensehow should i go about debugging this problem,['c#'] +205878,jsonnet conditional type deserialization i am consuming some arcgis web services and they have some unfortunate json design for example they might give something like thisgeometrytype esrigeometrypolygongeometry rings blah now depending on the geometrytype value passed in the geometry object may be one of several different object types in the case above the geometry node is of type polygonso question is in jsonnet is there any way to notate this conditional typing if not which i doubt there is is there a way to build a provider for deserializing that geometry node based on the object info above if not are there any recommended ways for solving thisedit i looked pretty extensively into building a custom converter but the problem with the converter is that they have this abstract methodpublic override t create type objecttypehowever i have no way of knowing what type to create here i need to know what kind of object was specified in the json abovethanks,['c#'] +205914,python which is faster to parse json or xml from my observations overall json is faster to parse than xml i have found two good question regarding this one is asked for php and other is asked for javascript i want to know about python how python is efficient with them and which is more efficient to parsealso please help in choosing the best python parser for xml eg xmlparser library lxml or and json simplejson jsonlib or,['python'] +205965,strange log entry related to webcoreglue in android since 2 days i get the following error when i run my app on the devicehowever it runs fine on the emulatorcan any 1 help me in solving this error e 3762 webcoreglue the real object has been deleted e 3762 webcoreglue the real object has been deleted e 3762 webcoreglue the real object has been deleted e 3762 webcoreglue the real object has been deletedit occurs when i m loggin in to facebook login webview through my appthe login dialog appears fr a tenth of a second and then thisappearsany suggestionsthanks,['android'] +205976,linq to sql creating duplicate designer files i have a strange bug with my linq to sql dbml files when ever i save it instead of saving to the existing designer file a duplicate file is createdthis is causing errors all over the place as there is ambiguity between the data context constructor inside of filedesignercs and file1designercsis there any way to fix this error that doesnt involve deleting and recreating the dmbl files as this error is happening on all of my dbml files some of which are rather largethe above image shows the issue that i am having,['c#'] +206012,dilemma cascade delete or join delete it is not a specific question more a general wondering when you have to make a delete on multiple tables in a 1m relationship is it better to make a fk constraint with a cascade delete or join the tables in the delete statementi had an old project that had separate delete statements for related tables and a few times some of the statements were not executed and data integrity was compromised i had to make a decision between the two so i was thinking a bit what would be a better solutionthere is also an option to make a stored procedure or a transactionso i am looking for an opinion or advice,"['mysql', 'sql']" +206013,what is the most efficient way to do comparisons involving manymany relationships with linq in ef 41 in my database i have the following tablespersonpostinteresttagmanymany relationships exist between personinteresttag and postinteresttagi need to perform a linq query in ef 41 to pull back any post that contains at least one interest tag that matches at least one interest tag related to the given userexample a person has the following interestscarssportsfitnessi need to return any post that is related to either cars sports or fitnesswhat is the most efficient way to write this query in terms of performanceeditrunning into an error based on the answer given belowthis compiles fine but throws an error at runtimevar matchingposts postswherepost posttopicsanyposttopic personinterestscontainsposttopicthe error is unable to create a constant value of type systemcollectionsgenericicollection1 only primitive types such as int32 string and guid are supported in this contextany ideas how to fix thisedit 2so my classes are structured as suchpublic class person public int personid get set public string firstname get set public string lastname get set other properties of types string int datetime etc public icollectioninteresttag interesttags get set public class post public int postid get set public string titleget set public string content get set other properties of types string int datetime etc public icollectioninteresttag interesttags get setpublic class interesttag public int interesttagid get set public string interestdescription get set public bool active get set public icollectionperson persons get set public icollectionpost posts get set in my context class i am overriding onmodelcreating to define my db table namesmodelbuilderentitypersonhasmanyu uinteresttagswithmanyt tpersons mapm mmapleftkeypersonid mmaprightkeyinteresttagid mtotablepersoninteresttags modelbuilderentityposthasmanyu uinteresttagswithmanyt tposts mapm mmapleftkeypostid mmaprightkeyinteresttagid mtotablepostinteresttags in my query method i am bring back an iqueryable of post and applying some filters including the clause in which i am trying to accomplish in this question var person personrepositorygetx xpersonid 5 var posts postrepositorygetqueryable i have tried this and get the error above posts postswherex xinteresttagsanytag personinteresttagscontainstag,"['c#', 'asp.net']" +206026,what is the best way to check iqueryable result set is null i just want to know what is the best way to check if an iqueryable result has no valueseg if we have a method likepublic static iqueryabletable thisplayall var db new datacontext var list from data in dbtable select data return listand then we do something like thisvar list thisplayalliflist null do something in here even if the result set has no values it will go to this line it just say enumeration yielded no resultsany possible way to check the result set has content or notthanks,"['c#', 'asp.net']" +206034,default parameter specifiers are not permitted i have the following code that gives the error default parameter specifiers are not permittedhow can this be fixedbool listsubscribestring apikey string id string email address string merge vars string email typehtml bool double optinfalse bool replace intereststrue bool send welcomefalsebool listunsubscribestring apikey string id string email address bool delete menberfalse bool send goodbyetrue bool send notifytrue,"['c#', '.net']" +206044,tracking uninitialized static variables i need to debug an ugly and huge math c library probably once produced by f2c the code is abusing local static variables and unfortunately somewhere it seems to exploit the fact that these are automatically initialized to 0 if its entry function is called with the same input twice it is giving different results if i unload the library and reload it again it works correctly it needs to be fast so i would like to get rid of the loadunloadmy question is that how to uncover these errors with valgrind or by any other tool without manually walking through the entire codei am hunting places where a local static variable is declared read first and written only later the problem is even further complicated by the fact that the static variables are sometimes passed further via pointers yep it is so uglyi understand that one can argue that mistakes like this should not be necessary detected by an automatic tool as in some scenarios this is exactly the intended behaviour still is there a way to make the autoinitialized local static variables dirty,['c'] +206062,ld warning unexpected srelocation type 9 while building in xcode hi i get around 70 such warnings in the link stage of building my app for thistributionld warning unexpected srelocation type 9any idea what this is and how i can fix iteditthese warnings come during the link stage of armv7 only when building for thistribution and i also get the following warningwarning all apps should include an armv7 architecture current archs armv6i have checked that armv7 is included in valid architectures for both debug and thistribution configuration,['iphone'] +206088,what are the advantages of boostnoncopyable to prevent copying a class you can very easily declare a private copy constructor assignment operators but you can also inherit boostnoncopyablewhat are the advantages thisadvantages of using boost in this case,['c++'] +206106,heroku conflict between gzipping assets and precompiling assets i have been running a rails 31 app on heroku cedar stack for a couple of months now i am using rackdeflater middleware to gzip my content and achieve this by configmiddlewareinsert before actionthispatchstatic rackdeflaterin my stagingrb filehowever since last week i get the following error when deploying to herokurunning rake assetsprecompile rake aborted no such middleware to insert before actionthispatchstatichowever running rake middleware still returnsuse rackcacheuse rackdeflateruse actionthispatchstaticuse racklockand content served were still gzipped however assets were not compiledminified as precompilation failed a manual rake precompileasets also does not helpso i am assuming actionthispatchstatic is not available during precompilation of assets so i tried to insert rackdeflater before racklock and now my assets are compiled without any error message but content served is not gzippedso what do i need to do to both gzip and compile my assets what am i missing thanks,['ruby-on-rails'] +206108,logback set log file name programatically i am using logback and i am trying to set the log file name programatically within my java program similar to setting logback appender path programmatically and i tried to adapt that solution as followsin logbacktestxmlappender namefile classchqoslogbackcorefileappender fileloglog file namelogfile and then again in my java programstring logfilename systemcurrenttimemillis just for examplesystemsetpropertylog file name logfilenameloggercontext lc loggercontext loggerfactorygetiloggerfactorycontextinitializer ci new contextinitializerlclcresettry i prefer autoconfig over joranconfiguratordoconfigure so i wouldnt need to find the file myself ciautoconfigcatch joranexception e statusprinter will try to log this eprintstacktracestatusprinterprintincaseoferrorsorwarningslchowever the result is two logs one full and named as i wanted eg 1319041145343log and the other is empty and named log file name is undefinedlog how do i stop this other empty log file from being created,['java'] +206111,r cannot be resolved to a variable in eclipse i have created a project from a source and now it shows errors r cannot be resolved to a variable from what i found here i had cleared and rebuilt the project but still the r file does not appear in the gen folderany ideas,['android'] +206132,draw text in circle overlay i am trying to draw some circle overlays containing text on mkmapviewi have subclassed the mkcircleview in which i put the following based on this but the text does not appear the circles show up correctly also tried the first responses solution same resultvoiddrawmaprectmkmaprectmaprect zoomscalemkzoomscalezoomscale incontextcgcontextrefcontext super drawmaprectmaprect zoomscalezoomscale incontextcontext nsstring t xnx uigraphicspushcontextcontext cgcontextsavegstatecontext uicolor redcolor set cgrect overallcgrect self rectformaprectselfoverlay boundingmaprect nslogmkc lf lf lf lf maprectoriginx maprectoriginy overallcgrectoriginx overallcgrectoriginy t drawinrectoverallcgrect withfontuifont fontwithnamearial size100 linebreakmodeuilinebreakmodeclip alignmentuitextalignmentcenter cgcontextrestoregstatecontext uigraphicspopcontextwhen debugging i get values like thesemkc 43253760 1040711680 1776503 19245 mkc 43253760 1040711680 1562442 2043090are they normal what am i missing thanks,"['iphone', 'objective-c']" +206197,setting mac osx application menu menu bar item to other than python in my python qt application i am writing a gui application using python and qt when i launch my application on mac the first menu item in the mac menu bar at the top of the screen is python i would prefer the application name there to be the name of my application how can i get my program name up therethe following demo program creates a window with two menus python and foo i do not like that because it makes no difference to my users whether i wrote the app in python or cobol instead i want menus myapp and foousrbinpython this example demonstrates unwanted python application menu name on mac makes no difference whether we use pyside or pyqt4from pysideqtgui import from pyqt4qtgui import import sysapp qapplicationsysargv mac menubar application menu is always python i want desiredapptitle instead setapplicationname does not affect mac menu barappsetapplicationnamedesiredapptitlewin qmainwindow need none parent for menubar on mac to get custom menus at allmbar qmenubar add a custom menu to menubarfoomenu qmenumbarfoomenusettitlefoombaraddactionfoomenumenuactionwinsetmenubarmbarwinshowsysexitappexec how can i change that application menu name on mac edit i would prefer to continue to use the system python or whatever python is on the user path if possible,['python'] +206205,iphone fetch data dictionary from keychain so i am trying to convert an old project to automatic reference counting i am trying to use the conversion tool that xcode has but it says to fix a couple things before it can convert i have no idea how to fix this error it is in the implementation of the keychain file this method is the one that returns the error specifically the line with the secitemcopymatching the error i am getting says cast of an indirect pointer to an objectivec pointer to cftyperef aka const void is thisallowed with arc i have been looking all over google apple docs and a bunch of other crap and cannot find a better way to fetch an existing data dictionary in the keychain any help appreciated thanksnsmutabledictionaryfetchdictionary nsmutabledictionary genericpasswordquery self buildsearchquerynsmutabledictionary outdictionary nilosstatus status secitemcopymatching bridge retained cfdictionaryrefgenericpasswordquery cftyperefoutdictionaryif debug printffetch sn self fetchstatusstatus utf8stringif status errsecitemnotfound return nullreturn outdictionary,['iphone'] +206216,how do i import a sql data file into sql server i have a sql file and i am trying to import it into sql server 2008 what is the proper way to do this,['sql'] +206227,mysql alter table modify column failing at rows with null values i have a table with about 10k rows which i am trying to alter so that the field fielddelimiter is never null i am attempting to do an alter statement expecting any null values to be changed to the default value but i get an error back from the sql statementalter table merchant ftp account modify column fielddelimiter char1 not null default t170848 alter 0 rows 0 secs error code 1265 sql state 010 data truncated for column fielddelimiter at row 3987 1 statements executed 0 rows affected execfetch time 0 sec 0 successful 0 warnings 1 errorsas i understand it this means that the data exceeds the field size at this row but a the data in the field is null at that row and b i am able to update that row directly with the value t and i do not get a truncation error if i update that row with a nonnull value and try to rerun the alter statement it fails at the next row where fielddelimiter is null eta i get that mysql could update in any direction but i can actually track its progress as i change rowsthere is a warning in the mysql docswarning this conversion may result in alteration of data for example if you shorten astring column values may be truncated to prevent the operation from succeeding ifconversions to the new data type would result in loss of data enable strict sql modebefore using alter table see section 516 aserver sql modesabut the values that it is supposedly truncating are nulls can anybody explain to me what is going on here and how to resolve iteta the existing fielddelimiter field definition is char1 allows nulls no default value so it should not have values 1 char and a select confirms that it does not the thistinct values in the field are null empty string p t and y,['mysql'] +206241,every array of enum implements ienumerable how do i work around this it appears that in net array of enum is not a stronglytyped concept myenum is considered to implement not just ienumerablemyenum but also ienumerableyourenum i did not believe it at first either returns truetypeofienumerabledayofweekisassignablefromtypeofattributetargets outputs 3var listoflists new listobject new attributetargetsall new consolecolorblue new platformidxbox platformidmacosx consolewritelinelistoflistsoftypeienumerabledayofweekcountso when i go looking through a list for everything that implements ienumerablet i am getting the ts and the listts and the iteratorgenerated ienumerablets but i am also getting the somethingelses that i do not wantwhats the easiest way to find out whether a given type as with isassignablefrom above or a given instance as with oftypet above really and truly implements say ienumerabledayofweeki gave mr skeet the green checkmark but once i got his code into visual studio resharper suggested a more concise version use whichever version you preferpublic static ienumerableienumerablet ofsequencetypet this ienumerable source where t struct return from sequence in sourceoftypeienumerablet let type sequencegettype where typeisarray typegetelementtype typeof t select sequence,"['c#', '.net']" +206257,no route matches get assets i have a rails app that i am trying to test in the production environment i ran rails envproduction rake assetsprecompile which generated all of my assets in publicassets the problem is that when i start my app w rails envproduction rails s thin i getactioncontrollerroutingerror no route matches get assetsapplicationeff78fd67423795a7be3aa21512f0bd2cssthis file does exist though at publicassetsapplicationeff78fd67423795a7be3aa21512f0bd2css any thoughts as to why i am getting this routingerror,['ruby-on-rails'] +206302,ios load uiwebview content synchronously i have a uitableview with many rows each row contains a uiwebview the content of this webview is stored in my database on the app and the height of each cell in tableview is calculated based on the scroll height of my uiwebviewhere is the problem the loadhtmlstring method works asynchronously so when heighforrowatindexpath method of uitableview gets called the data has not been loaded in the uiwebview because it works asynchronously so i cannot calculate the required height for the cellso here is the question is it possible to load the content of a uiwebview synchronously my html text is very short so it should not take that long to load it synchronouslyeditis it possible to calculate the expected height of an html string without placing it inside a uiwebview i know that this is possible using plain text i do not know about html,"['iphone', 'ios']" +206306,ios different addsubview behavior between ios 43 and 50 while coding in ios 43 before i found while add a view controllers view to another view with superview addsubviewcontrollerview the controller instance will not receive the viewwillappearviewdidappear message than i found same issue in some thread in stack overflow after that i manually call viewwillappearviewdidappear as needed but after upgrade to ios 50 some frisky uiview behavior happened finally i found that in ios 5 the superview addsubviewcontrollerview will send a viewwillappearviewdidappear message to the controller instance automatically plus my manually calls there are two duplicated message each time the controller action its behaviorand i also found a similar issue ios 5 viewwillappear is not called after thismissing the modal in ipadnow the problem is after search apples documents i did not find any explicitly doc for diff about these issues i even wonder if this is a guaranteed view life cycle behavior in ios 50 does anyone fix similar issues or find some guidelines about these difference cause i want to run my app both in 4x 5x ios,"['iphone', 'ios']" +206317,android statusbar notification launches new app though it running already how to synchronize launching app from app icon and staus bar notification i have implemented notification within service notification works fine but in the case when app is running already and i clicked on android status bar notification it launches new copy of my app which is obviously wrong it should be if user click on status bar notification should start app if app is not running already otherwise it should opens other activity message activity in my case i tried many suggestions provided in similar type of problem posted here but i did not get solution in my case,['android'] +206346,jquery change backgroundimage i am trying to swap two images with jquery using the hover event i triedwltdealview buybutton newmouseoverfunctione buybutton newcssbackgroundimageurlimagescompra mouseoverpngwltdealview buybutton newmouseoutfunctione buybutton newcssbackgroundimageurlimagescompra normalpngbut the image is not showing and after i get the mouse from it it triggers the second event it should update with the first image but it does notyou can have a look here hover the buy button,"['javascript', 'jquery', 'html', 'css']" +206352,kvo can i remove all observers from concrete object iam using keyvalue observing i have object 1 nsmanagedobject and few other objectsobservers when i remove object 1 from managed object context my program crashescoredata error serious application error exception was caught during core data change processing this is usually a bug within an observer of nsmanagedobjectcontextobjectsdidchangenotificationcan i put something to dealloc method or somewhere else to remove all observers of object 1 or the only appropriate decision is to send notification right when i am about to remove object 1 from managed object context and listen to this notification by other objects to remove themselves from observers of object 1,['objective-c'] +206356,is hashalgorithmcomputehash stateful i need to compute hashes of multiple blocks of data independently something like thisusing hashalgorithm hasher new actualhashalgorithm for int i 0 i numberofblocks i byte block getblock i byte hash hashercomputehash block use hash can i reuse the same hashalgorithm object between blocks will hashalgorithm reset state between calls to computehash or do i need to thispose the hashalgorithm object and create new one for each new block of data,"['c#', '.net']" +206436,selecting multiples choices in django admin filter list filter currently i filter by some option in djangos admin interface for instance lets say i filter by by status is it possible to select multiple statuses to filter results from here is the screenshot of the filtercan i select multiple items from this list,['python'] +206437,obtaining client ip address from a wsgi app using eventlet i am currently writing a basic thispatch model server based on the python eventlet library having looked at the wsgi docs on eventlet i can see that the eventletwsgiserver function logs the xforwardedfor header in addition to the client ip address however the way to obtain this is to attach a filelike object the default which is sysstderr and then have the server pipe that to that objecti would like to be able to obtain the client ip from within the application itself ie the function that has start response and environ as parameters indeed an environ key would be perfect for this is there a way to obtain the ip address simply ie through the environ dictionary or similar without having to resort to redirecting the log object somehow,['python'] +206471,stop color hilighting of selected item in combobox i am using combo box in winform but when i was selected any item in combo box then selected item background color is blue i want to remove this blue background color particularly on form load tried to set focus to other control in the form but combo highlight not removed but item should be selected can anybody help out on this,"['c#', '.net']" +206474,load aspnet mvc jsonresult jquery datatables i am trying to get the datatables to work with a jsonresult returned by an aspnet mvc controller i keep getting a datatables warning table id example requested unknown parameter 0 from the data source for row 0 error which according to the docs means it cant find the columns the code in controller that returns the jsonresult looks like public jsonresult loadphonenumbers listphonenumber phonenumbers new listphonenumber phonenumber num1 new phonenumber number 5 123 4567 description george phonenumber num2 new phonenumber number 5 765 4321 description kevin phonenumber num3 new phonenumber number 5 5 4781 description sam phonenumbersaddnum1 phonenumbersaddnum2 phonenumbersaddnum3 return jsonphonenumbers jsonrequestbehaviorallowget phonenumber is just a plain c class with 2 properties number and descriptionthe javascript that retrieves and loads the data looks likescriptdocumentreadyfunction exampledatatable bprocessing true sajaxsource accountloadphonenumbers sajaxdataprop scriptand the html looks liketable cellpadding0 cellspacing0 border0 classthisplay idexamplethead tr th number th th description th trtheadtbodytbodytfoottfoottablei have deliberately set sajaxdataprop to an empty string so that datatables does not look for aadata even when i explicitly set aadata like so in the controllerreturn jsonnew aadata phonenumbers i still get the error any advice pleasethanks,['jquery'] +206483,saving ui on orientation change onsaveinstancestate not working as expected if retaining fragment using compat lib v1 not using v23 because of certain bugs a variation of this questioni have a fragment whose ui has various controls whose state i want to maintain on an orientation changethe parent activity is being destroyed on orientation change please do not tell me about manifest changes to avoid activity recreation the fragment calls setretaininstancetrue1 now my understanding is that views with unique ids should retain some state on say an orientation change given this i would expect a nonnull bundle into oncreateviewonactivitycreated but it is null2 in any case if i save state in onsaveinstancestate ensuring i call super i still get a null bundle in oncreateviewonactivitycreated3 if i do not call setretaininstancetrue then i do get a nonnull bundle in oncreateviewonactivitycreated even if i do not have an onsaveinstancestate methodthe questions i have is is this working as expected and my understanding of the lifecycle is broken regardless i am guessing that the best way forward for me would be to retain the fragment and then maintain the state of the controls myself within the fragmentthanks in advance peter,['android'] +206495,latex on python alpha and beta do not work i am using matplotlib to produce some graphics and i am using latex for the legendsmore specifically i am trying to use something like thisloglogxx rlabel alpha legendshowhowever this code does not present a legend on the figure and gets error after i close the imagei am using the enthought package for mac but the error comes from the pylabscipythe error the appears is exactly lpha at char 0 line1 col1however if use the mu or gamma it works well i only found about this problem on beta and alphadoes anyone knows what this can be i believe python is interpreting a as some character but i do not know how should i debug avoid it,['python'] +206502,where do css and javascript files go in a maven web app project i am switching to use maven for my spring web app projects and i am running into a simple issue i am not sure where to put the css and js files in the new project structuretraditional web app structurein a traditional java web app structure in eclipse created as a dynamic web project i put the css javascript and images files under the following structurewebcontent cssmystylescss jsmyjsjs imagesmyimagegif webinfthen in my jsp if i want to reference a css file i do as followslink relstylesheet hrefrequestgetcontextpathcssmystylescssthis works fine maven web app structurein a maven project i have put the css files in these locationsfirst attemptunder the webapp folder at the same level as webinf just like in a traditional dynamic web project but when i do the followingmvn clean tomcatruni get the following error from the spring frameworkorgspringframeworkwebservletpagenotfound no mapping found for http request with uri appnamecssmystylescss in thispatcherservletsecond attemptplaced my css folder under srcmainresources but when i do the followingmvn clean tomcatruni get the following error from the spring frameworkorgspringframeworkwebservletpagenotfound no mapping found for http request with uri appnamecssmystylescss in thispatcherservletthird attemptplaced my css folder srcmainresourcesresults same as abovei am sure it is something simple but i am stuck maybe i am overlooking something thanks in advanceupdate adding pomxml to see if it can help troubleshoot the issuexml version10 encodingutf8project xmlns xmlnsxsixsischemalocation 0 0xsdmodelversion400modelversiongroupidcomdariopardogroupidartifactidjfreechartdemoartifactidnameabcnamepackagingwarpackagingversion100buildsnapshotversionproperties javaversion16javaversion orgspringframeworkversion306releaseorgspringframeworkversion orgaspectjversion169orgaspectjversion orgslf4jversion1510orgslf4jversionpropertiesrepositories repository idspringmavenreleaseid namespring maven release repositoryname urlurl repository repository idspringmavenmilestoneid namespring maven milestone repositoryname urlurl repository repository idspringroorepositoryid namespring roo repositoryname urlurl repository repository idjboss repoid urlurl namejboss reponame repositoryrepositoriespluginrepositories pluginrepository idspringmavenreleaseid namespring maven release repositoryname urlurl pluginrepository pluginrepository idspringmavenmilestoneid namespring maven milestone repositoryname urlurl pluginrepository pluginrepository idspringroorepositoryid namespring roo repositoryname urlurl pluginrepositorypluginrepositoriesdependencies spring dependency groupidorgspringframeworkgroupid artifactidspringcontextartifactid versionorgspringframeworkversionversion exclusions exclude commons logging in favor of slf4j exclusion groupidcommonslogginggroupid artifactidcommonsloggingartifactid exclusion exclusions dependency dependency groupidorgspringframeworkgroupid artifactidspringcoreartifactid versionorgspringframeworkversionversion exclusions exclusion groupidcommonslogginggroupid artifactidcommonsloggingartifactid exclusion exclusions dependency dependency groupidorgspringframeworkgroupid artifactidspringtestartifactid versionorgspringframeworkversionversion scopetestscope exclusions exclusion groupidcommonslogginggroupid artifactidcommonsloggingartifactid exclusion exclusions dependency dependency groupidorgspringframeworkgroupid artifactidspringaopartifactid versionorgspringframeworkversionversion dependency dependency groupidorgspringframeworkgroupid artifactidspringaspectsartifactid versionorgspringframeworkversionversion dependency dependency groupidorgspringframeworkgroupid artifactidspringtxartifactid versionorgspringframeworkversionversion dependency dependency groupidorgspringframeworkgroupid artifactidspringjdbcartifactid versionorgspringframeworkversionversion classifier dependency dependency groupidorgspringframeworkgroupid artifactidspringormartifactid versionorgspringframeworkversionversion classifier dependency dependency groupidcommonspoolgroupid artifactidcommonspoolartifactid version154version classifier exclusions exclusion groupidcommonslogginggroupid artifactidcommonsloggingartifactid exclusion exclusions dependency dependency groupidcommonsdbcpgroupid artifactidcommonsdbcpartifactid version13version classifier exclusions exclusion groupidcommonslogginggroupid artifactidcommonsloggingartifactid exclusion exclusion groupidcommonspoolgroupid artifactidcommonspoolartifactid exclusion exclusion groupidxercesgroupid artifactidxercesartifactid exclusion exclusion groupidxercesgroupid artifactidxercesimplartifactid exclusion exclusion groupidxmlapisgroupid artifactidxmlapisartifactid exclusion exclusions dependency dependency groupidorgspringframeworkgroupid artifactidspringwebartifactid versionorgspringframeworkversionversion classifier exclusions exclusion groupidcommonslogginggroupid artifactidcommonsloggingartifactid exclusion exclusions dependency dependency groupidorgspringframeworkgroupid artifactidspringwebmvcartifactid versionorgspringframeworkversionversion dependency aspectj dependency groupidorgaspectjgroupid artifactidaspectjrtartifactid versionorgaspectjversionversion dependency hibernate dependency groupidorghibernategroupid artifactidhibernatecoreartifactid version364finalversion classifier dependency dependency groupidorghibernategroupid artifactidhibernateentitymanagerartifactid version364finalversion classifier exclusions exclusion groupidcglibgroupid artifactidcglibartifactid exclusion exclusion groupiddom4jgroupid artifactiddom4jartifactid exclusion exclusions dependency dependency groupidorghibernatejavaxpersistencegroupid artifactidhibernatejpa20apiartifactid version100finalversion classifier dependency dependency groupidorghibernategroupid artifactidhibernatevalidatorartifactid version410finalversion classifier exclusions exclusion groupidjavaxxmlbindgroupid artifactidjaxbapiartifactid exclusion exclusion groupidcomsunxmlbindgroupid artifactidjaxbimplartifactid exclusion exclusions dependency dependency groupidjavaxvalidationgroupid artifactidvalidationapiartifactid version100gaversion classifier dependency dependency groupidcglibgroupid artifactidcglibnodepartifactid version22version classifier dependency dependency groupidjavaxtransactiongroupid artifactidjtaartifactid version11version classifier dependency logging dependency groupidorgslf4jgroupid artifactidslf4japiartifactid versionorgslf4jversionversion dependency dependency groupidorgslf4jgroupid artifactidjcloverslf4jartifactid versionorgslf4jversionversion scoperuntimescope dependency dependency groupidorgslf4jgroupid artifactidslf4jlog4j12artifactid versionorgslf4jversionversion scoperuntimescope dependency dependency groupidlog4jgroupid artifactidlog4jartifactid version1215version exclusions exclusion groupidjavaxmailgroupid artifactidmailartifactid exclusion exclusion groupidjavaxjmsgroupid artifactidjmsartifactid exclusion exclusion groupidcomsunjdmkgroupid artifactidjmxtoolsartifactid exclusion exclusion groupidcomsunjmxgroupid artifactidjmxriartifactid exclusion exclusions scoperuntimescope dependency inject dependency groupidjavaxinjectgroupid artifactidjavaxinjectartifactid version1version dependency servlet dependency groupidjavaxservletgroupid artifactidservletapiartifactid version25version scopeprovidedscope dependency dependency groupidjavaxservletjspgroupid artifactidjspapiartifactid version21version scopeprovidedscope dependency dependency groupidjavaxservletgroupid artifactidjstlartifactid version12version dependency test dependency groupidjunitgroupid artifactidjunitartifactid version47version scopetestscope dependency to bring jfree chart in itext apache poi dependency groupidnetsfjasperreportsgroupid artifactidjasperreportsartifactid version412version dependency dependency groupidorgcodehausgroovygroupid artifactidgroovyallartifactid version155version dependency oracle jdbc drivers dependency groupidcomoraclegroupid artifactidoracleartifactid version102010version dependencydependenciesbuild plugins plugin groupidorgapachemavenpluginsgroupid artifactidmavencompilerpluginartifactid configuration sourcejavaversionsource targetjavaversiontarget configuration plugin plugin groupidorgapachemavenpluginsgroupid artifactidmavenwarpluginartifactid configuration warnameabcwarname configuration plugin plugin groupidorgapachemavenpluginsgroupid artifactidmavendependencypluginartifactid executions execution idinstallid phaseinstallphase goals goalsourcesgoal goals execution executions plugin pluginsbuildupdate adding webxmlxml version10 encodingutf8webapp version25 xmlnsxmlnsxsixsischemalocation 2 5xsd the definition of the root spring container shared by all servlets and filters contextparam paramnamecontextconfiglocationparamname paramvaluewebinfspringrootcontextxml classpathmetainfspringapplicationcontextxml paramvaluecontextparam creates the spring container shared by all servlets and filters listener listenerclassorgspringframeworkwebcontextcontextloaderlistenerlistenerclasslistener processes application requests servlet servletnameappservletservletname servletclassorgspringframeworkwebservletthispatcherservletservletclass initparam paramnamecontextconfiglocationparamname paramvaluewebinfspringappservletservletcontextxmlparamvalue initparam loadonstartup1loadonstartupservletservletmapping servletnameappservletservletname urlpatternurlpatternservletmapping,['css'] +206507,replacing comgoogleinject with javaxinject is it true that javaxinject annotations can function as direct replacements for comgoogleinjectso that if i replaced all my current guicegin annotations with those from javaxinject my app would compile and run just finefirst does javaxinject cover all the bases that googleinject cover,['java'] +206513,cc global vs static global possible duplicatestatic vs global i am confused about the differences between global and static global variables if static means that this variable is global only for the same file then why in two different files same name cause name collisionscan someone explain this,"['c++', 'c']" +206519,generic onetoone relation in django i need to set up onetoone relation which must also be generic may be you can advice me a better design so far i came up to the following modelsclass eventmodelsmodel skip event related fields content type modelsforeignkeycontenttype object id modelspositiveintegerfield content object genericgenericforeignkeycontent type object id class meta unique together content type object idclass action1modelsmodel skip action1 related fields events genericgenericrelationevent content type fieldcontent type object id fieldobject id property def eventself return selfeventsget is this reasonableclass action2modelsmodelin django admin in event list i want to collect all actions and from there i want go to admin pages for actions is it possible to avoid creating event property in the action models is there a better solution it would be nice to combine the field events and the property event in a single definition the project i am working with uses django 11,['python'] +206554,detecting that the browser has no mouse and is touchonly i am developing a webapp not a website with pages of interesting text with a very different interface for touch your finger hides the screen when you click and mouse relies heavily on hover previewhow can i detect that my user has no mouse to present him the right interface i plan to leave a switch for people with both mouse and touch like some notebooks the touch event capability in the browser does not actually mean the user is using a touch device for example modernizr does not cut it the code that correctly answers the question should return false if the device has a mouse true otherwise for devices with mouse and touch it should return false not touch onlyas a side note my touch interface might also be suitable for keyboardonly devices so it is more the lack of mouse i am looking to detectto make the need more clear here is the api that i am looking to implement level 1 the current answers provide a way to do thathastouch returns true if a mouse is expected note as explained by the op this is not hastouch i do not think we have this in the answers already that why i offer a bountyhasmouse level 2 i do not think it is possible but maybe i am wrong so why not asking callback is called when the result of hastouch changeslistenhastouchchangescallback callback is called when the result of hasmouse changeslistenhasmousechangescallback,['javascript'] +206577,oracle using a database link in a stored procedure table or view does not exist i currently have an issue whereby i cannot reference a table in a linked database within a stored procedure i get the error messageora00942 table or view does not existhere are the steps i took on the host machine running oracle 10g to set up the database link to the remote database running oracle 11g the steps are accurate but some some names have been changed though they have been kept consistentupdate tnsnamesora adding a new entryremote db description address protocol tcp host 10101010 queuesize 20 port 1521 connect data service name remote service create database link as the user who will later be creating and executing the stored procedurecreate database link remote linkconnect to remote useridentified by remote passusing remote dbprove database link is working by selecting from itselect id from remote tableremote linkid8ac6eb9bfcc145748604c9fd4412b917c9e7ee5123144002a6847817b181267bcc395a8156dd4d689bbafa926dad4fc7d6b450e03f36411aba142acc18b9c008create stored procedure that depends on working database linkcreate or replaceprocedure test remote db linkasv id varchar50begin select id into v id from remote tableremote link where id c9e7ee5123144002a6847817b181267b dbms outputput linev id v idend test remote db linkexplode own head after staring at the following error message for over an entire working dayerror1027 plsql ora00942 table or view does not existi have tried many things to try to sort this issue out includingwhen creating the database link not using quotes around the username and password link creates fine but selecting from it gives me this errorerror at line 1ora01017 invalid usernamepassword logon deniedora02063 preceding line from tws linktried various combinations of username and password in upperlowercase received same error as 1tried single quotes instead of double quotes around username and password recieved this errorerror at line 1ora00987 missing or invalid usernamesproved i have full access to the remote db by connecting into it with sqlplusoracle sqlplus remote userremote passremote dbsqlplus release 102010 production on thu oct 20 2312 2011copyright c 1982 2005 oracle all rights reservedconnected tooracle database 11g enterprise edition release 112020 64bit productionwith the partitioning olap data mining and real application testing optionssql i am not sure what to do next the possible next step is to start looking at issues on the remote database and perhaps see if other databases can connect to it another would be to look at incompatibilities going from host 10g to remote 11g any suggestions for what to look for would be very much appreciatedif any more information would be of help to anyone please let me know and i will update the question asap i am starting to go nutsgc,['sql'] +206584,how can i create a selectlist with multiple selected values i am trying to set multiple values in a select listselectlist list new selectlistmylistitems valfield datafield selected valueswhat objectvalues do i use for to select multiple items,['c#'] +206622,ios how do you prevent the screen from greying out immediately when reenabling the idletimer i am working on an ios game that primarily uses accelerometer input previous programmers set idletimerthisabledyes on startup and left it that way i recently made a change such that the idle timer is only thisabled during gameplay and is reenabled when a level ends the problem is if the play time of the level is longer than the users idletimer setting the screen will grey out the moment i set idletimerthisabledno is there a way to reset the timer upon reenabling so that the full time increment will occur before the idletimer dims the screen,['ios'] +206636,xcode 42 debug does not symbolicate stack call i have a problem with xcode 42 debugging in an ios 5 simulatordevice the following code crashes as expectednsarray arrnsarray arrayarr objectatindex100in ios 4 i get a useful stack trace of hex numbers but in ios 5 it just gives me first throw call stack0x16b4052 0x1845d0a 0x16a0674 0x294c 0x6f89d6 0x6f98a6 0x708743 0x7091f8 0x7fcaa9 0x2257fa9 0x16881c5 0x15ed022 0x15eb90a 0x15eadb4 0x15eaccb 0x6f02a7 0x6faa93 0x2889 0x2805thanks,['ios'] +206638,validate json in php is there any way to check that a variable is a valid json string in php without using json last error i do not have php 533,['php'] +206642,optional path variables in springmvc requestmapping uritemplate i have the following mappingrequestmappingvalue firstlast method requestmethodgetpublic string testpathvariablefirst string first pathvariablelast string last which for the following urisfooabcdefghbarfooabarfoobarmaps foo to first and bar to last and works finewhat i would like is something that maps everything between foo and bar into a single path param or null if there is no middle as in the last uri examplerequestmappingvalue firstmiddlesome regex herelast method requestmethodgetpublic string testpathvariablefirst string first pathvariablemiddle string middle pathvariablelast string last pretty stuck on the regex since i was hoping that something simple like middle which only maps to fooabar or middle which seems to map to nothingdoes the antpathstringmatcher tokenize upon prior to applying regex patterns making patterns that cross a impossible or is there a solutionfyi this is in spring 31m2this seem similar to requestmapping controlers and dynamic urls but i did not see a solution there,['java'] +206646,how do static libraries do linking to dependencies say i have liba it depends on for example libsomething for the simple fact that a non inline method of liba makes a call to a method in libsomethingh how does the dependency link up in this case does liba have to statically link to libsomething when it is compiled or will a user of liba an application using liba need to link to both liba and libsomethingthanks,"['c++', 'c']" +206652,python return statement error return outside function when running the following code in python 271 on a mac with mac os x 107while true return falsei get the following errorsyntaxerror return outside functioni have carefully checked for errant tabs andor spaces i can confirm that the code fails with the above error when i use the recommended 4 spaces of indentation this behavior also happens when the return is placed inside of other control statements eg if for etcany help would be appreciated thanks,['python'] +206654,asynchronous call in synchronous method here is the simple examplepublic event eventhandler cookindone delegatepublic void coockinrequest var indicator new activityindicator activityindicatorshowo coockin something cool var bw new backgroundworker bwdowork sender e cockinservicecook bwrunworkercompleted sender e indicatorhide cookindoneinvokethisnull bwrunworkerasyncnow everytime i use that method i have to intercept cookindone event and move onvar cook new cookcookcookindone sender e messageboxshowyay smells goodcookcoockinrequestbut how can i simplify that by making return type of the method as boolean and return result upon the cookin completionif coockinrequest messageboxshowyay smells even betterif i put there something like while bwisbusy it will screw my activityindicator freeze the main thread and i feel it would be the lousiest thing to do there are also some monitorwait stuff and some other stuff like taskfactory but all that stuff seems to be too complicated to use in simple scenarios it might be also different in different environments like some approach is good for wpf apps some for something else and whatnot but there should be a general pattern is not that righthow do you do that guys,['c#'] +206667,thread unsafe decrementingincrementing why mostly positive i am wondering about result of unsafe decrementingincrementing in java threads so there is my programmain classpublic class start public static void mainstring args int count 10 pos 0 neg 0 zero 0 for int x0 x10 x magiccounter 0 thread dec new threadnew magicfalse count thread inc new threadnew magictrue count decstart incstart try incjoin decjoin catch interruptedexception e systemoutprintlnerror if magiccounter 0 zero else if magiccounter 0 pos else neg systemoutprintlnintegertostringneg t integertostringpos t integertostringzero threads classpublic class magic implements runnable public static int counter 0 private boolean inc private int countto public magicboolean inc int countto thisinc inc thiscountto countto override public void run for int i0ithiscounttoi if thisinc magiccounter else magiccounter i have run program few times and always getting much more positive result then negative i have also tried to change order of which threads starts but this changed nothing some resultsnumber of results 0 number of results 0 number of results 01103 8893 43159 6838 32639 7359 23240 6755 53264 6728 82883 7112 52973 7021 63123 6873 42882 7113 53098 6896 6,['java'] +206678,determine if activerecord object is new or created how can i introspect an activerecord object to determine whether it is new or already created,['ruby-on-rails'] +206713,how can i define nullable entityset for each entity that has a one to many relation with other entity when i trying to add a new item it seems like i have to define these list of items that relates to this entityfor example lets say that i have a producttype entity that has a list of products as followingtablepublic class producttype columnisprimarykey true isdbgenerated true public int id get private set column public string name get set private entitysetproduct products associationstorage products thiskey id otherkey producttypeid public entitysetproduct products get return products set productsassignvalue when i try to add a new producttype like thatproducttype newtype new producttype name newtype productrepositoryaddnewtype insertonsubmit and savechangesit gives me an exception that products is nullobject reference not set to an instance of an objectthe same problem with all the entities that has a one to many relation with other entities so how can i allow null for the entityset that represents a one to many relation,['c#'] +206724,css animation works in chrome but not in firefox in rotate animation works in chrome but not in firefox whymozkeyframes rotate from moztransform rotate0deg to moztransform rotate360deg webkitkeyframes rotate from webkittransform rotate0deg to webkittransform rotate360deg example background red width 100px height 100px mozanimation rotate 20s linear 0 infinite webkitanimation rotate 20s linear 0 infinite,"['html', 'css']" +206749,phone gap implementation of application settings i wanted to store some settings like username and password for my application such that at the start of the application i would be able to do user authenticationcan anyone guide me how to achieve this using phonegap,['android'] +206760,how to run a service every day at noon and on every boot in my app i have sqlite database that has one table with date rows in milliseconds i would like to have a notification shown every day if 30 days has passed since the last date value stored in my database a service seems to be a good way to accomplish this check upi ran into commonswares wakefulintentservice and thought it could be the answer but i really do not know how should i implement it in the demo it starts a service after 5 minutes since boot is complete which is just fine but what do i need to add to get it also start at every noon but only to show one notification day not both as from boot and regular daily check upi know this could be solved using alarmmanager but really do not know how so the help i need is to give me some samples key points to get the service start on every boot andor every day without app runningthanks,['android'] +206773,difference between onkey onkeydown and thispatchkeyevent methods provided by android what is the difference between onkey onkeydown and thispatchkeyevent methods provided by androidi would like to know when and where each of these can be usedplease shed some light into this,['android'] +206801,how do i switch my css stylesheet using jquery what i am working on is simpleyou click on a button idthemes and it opens up a div idthemedrop that slides down and lists the themes i only have two at this pointbutton idoriginaloriginalbuttonbr button idgrayscalegrayscalebuttonnow when the site is loaded it loads with style1css mainoriginal themelink relstylesheet typetextcss hrefstyle1cssnow what i am trying to figure out ishow can i have it that when the grayscale button is clicked to change the stylesheet from style1css to style2css note files are in the same directoryany help would be much appreciated,"['jquery', 'css']" +206810,isodate and datetime in mongodb using c let us suppose that i want to query mongo on the datetime i have two c variables representing the start and the end date1 20102011 02 22102011 0now the bsondatetimecreatedatetime transformed them to a bson datetime well too1 201020t0 mongodbbsonbsondatetime2 201022t0 mongodbbsonbsondatetimethis is the code creating the datetimes value is a string datetime datetimebool parsed datetimetryparse value out datetimeif parsed throw new formatexceptionwrong format for a query paramreturn bsondatetimecreatedatetimethen the next code builds the queryprivate querycomplete makequerystring key bsonvalue value if separatortype return querygtekey value if separatortype return queryltekey value return queryeqkey valueand i do get such a strange value in a querysessionsend gte isodate201019t210z lte isodate201021t210z well i google isodate but have not found any reason why it should be shifted is it ok,['c#'] +206818,unable to override oncreateoptionsmenu in listfragment i created an app that supports both phone and tablet version so i use the androidsupportv4jar library my activity extends the listfragment and i tried to override the oncreateoptionsmenumenu menu menuinflater inflater as in the following link i previously called sethasoptionsmenuunfortunately it seems that i cannot override oncreateoptionsmenuthis is the error messagethe method oncreateoptionsmenumenu menu menuinflater inflater of type myfragment must override or implements a supertype methodand i did that withpublic class myfragment extends listfragment,['android'] +206830,how to set multiple smtp server in android my question is how to set multiple smtp server for sending mails in android like yahoohotmailgmailrediff any type of domain will worked while sending mailcan anyone suggest any site or any idea please help methank you in advance,['android'] +206831,thisable openmp in nice way i have c code with openmp pragmas inside i want to test this code both for multithread mode with openmp and in single thread mode no openmp for now to switch between modes i need to comment pragma omp or at least parallelwhat is the cleanest or default way to enable thisable openmp,"['c++', 'c']" +206833,rails newbie about yield i saw some code in a rails v23 app in layoutcar generalhtmlerb this view is called by a method in cars controller i saw the code body yield javascript include tag jquery142min javascript tag do yield jstemplates var some car new object yield some car end bodytwo questions to askwhere can i find the yield content of the first yield under body is it a rails specific way to include js code in a view by using yield jstemplates and what about yield some car is it point to a view or just to show the value of some car,['ruby-on-rails'] +206844,why c11 and php closures require declaring the closedover variables function literals in both c and php require programmer to specify which variables they are using from the current lexical context whats the reason behind this requirementi guess it is not meant for the compilerinterpreter because one can statically infer this information from function literals body is it only for drawing the readers attention,"['php', 'c++']" +206863,detecting clicks outside of uiscrollview i have implemented a paged scroll according to this technique ios develop how to extend uiscrollviews scroll event responding area and it works just as intendedthe view that i am scrolling is containing a couple of buttons and i want to be able to click not only those that are centeredpaged into the scrollview but also those to the left and to the right of it i cannot find any way to solve this but i am not really an iosjedi yet hoping one of you are though so as you can see from the screenie the uiscrollview is about a third of the width of the window the contentsize of the uiscrollview is much larger about 1500px and contains a lot of buttons added programmatically the cool thing with this solution and the part that actually works is that the buttons 1 are paged into the scrollview 2 are visible outside the scrollview since clip subviews is unchecked for the scrollview 3 the buttons are clickable when visible inside the uiscrollview but what does not work is simply this the buttons currently being outside of the window does not receive their clicks when clicking on them the events are instead forwarded to the underlaying the white part of the window view,['ios'] +206888,what is the best way to protect sensitive data in the code i was examining the ways of protecting my code from decompilingthere are several good threads here describing obfuscation and code packing as the possible ways of protecting the code however none of them is ideal obfuscation does not work with reflection when the string methodproperty names are used many people do not recommend to use obfuscation at allso i currently decided not to go with any of the above however i have parts of the code where i need a sort of encryption for example a database connection string with an ip login and password is stored inside the code as simple const string same as email account datain aspnet there is an option to move the sensitive data to a config file and encrypt it but that requires the server key ie linked to a single computer i did not read much about it but i suppose something similar is available for desktop applications but i need this to work on any computer where the application is installedand here is the question are there ways to encodeprotect such data so that it cannot be read along with decompiled code,"['c#', '.net']" +206914,writing async cpp nodejs 053 modules ia m searching for a way to build c modules for nodejs with the current release 059 by using the following tutorial and abstracting from nodes node filecc i was able to build a module by my self for node 053but with node 054 some of the apia s must have changed because because ia m no longer able to warp functions with eio anymorelooking at node filecc i thiscovered that the eio wrapping is replaced by new reqwrap classesfor example in this macro no i wonder whats the best way of writing async extensions,"['javascript', 'c++']" +206917,making two requests to the same controller in rails integrations specs i am having problem making two requests to the same url in a rails integration test with rspecit does something do get something statusany other header this line couses problem get something statusok header doc nokogirihtmlresponsebody lis doccssthe id lissizeshould 1 lis0textshould includeanythingendif i make two requests to the same controller the test seems to maintain the old responsein the above example if i uncomment that line the test breaks beacause it maintains the result of the first queryis it a limitation of the test stack or am i doing something wrong,['ruby-on-rails'] +206925,why is the datetimepickers maxdatetime 123198 235959 this value seems arbitrary when no explanation is provided why is not this just datetimemaxvalue,['c#'] +206947,how to upload an image given in form of dataurl from html canvas to facebook in my web page i have an html canvas i want to upload the canvas image to facebook i think the first step may be a canvascontexttodataurl function call whats next if the user is logged in to facebook i want himher to be able to upload the image automatically with his facebook account from my page i want the user will be able to either post the image in hisher wall or one of hisher friends what should be the code and where should i add the code a detail answer in javascript or jquery will be highly appreciated thank you,"['javascript', 'html']" +206948,array set value using dot notation looking into kohana documentation i found this really usefull function that they use to get values from a multidimensional array using a dot notation for examplefoo arraybar arraycolor green size mvalue pathfoo barcolor null value now is greenim wondering if there is a way to set the an array value in the same wayset valuefoo barcolor blackthe only way i found to do that is rebuilding the array notation arraybarcolor and then set the value using evalany idea to avoid eval,['php'] +206958,what is the color code for transparency in css can anyone tell me what is the color code for transparency in css like white f as i am using following code to convert the color codes into intcolor color colortranslatorfromhtmlhexreturn intcolorr 16 colorg 8 colorb 0,"['html', 'css']" +206959,how can i set properties on all items from a linq query with values from another object that is also pulled from a query i have a query pulling from a databaselistmyclass items new listmyclassfrom i in context select new myclass a ia b i does not know this this comes from elsewhere c ic i also have another query doing a similar thinglistmyclass2 otheritems new listmyclass2from j in context select new myclass2 a ja a is the intersection there will only be 1 a here but many as in items b jb in reality these classes are much larger and query data that is separated not only by database but by server as well is it possible to use a linq query to populate the property b for all items where itemsa intersect all of the built in linq predicates appear only to do aggregates selections or bool expressionsin my brain i had something like this but this is all offitemswherex xb otheritemswherez za xasinglebor am i being ridiculous with trying to make this work in linq and should just abandon it in favor of a for loop where the actual setting becomes trivial because of deadlines i will be resorting to the for loop and it is probably going to end up being a lot more readable in the long run anyway but is it possible to do this would an extension method be necessary to add a special predicate to allow this,['c#'] +206987,php empty post and files when uploading larger files i have a following problem i have html form that uploads a file with some extra information but it allows to upload files that only less then 10mb but when user tries to upload something bigger both post and files array are empty i expected that post will have some values and files will have some values but will indicate that there is an upload errorthere is a few questions empty post files like that but i did not find any solution or explanation for ithtml formform enctypemultipartformdata methodpost actionuploadphp p input typehidden namemax file size value10 input typefile nameimage p p input typetext nameother field pformuploadphpprint r post arrayprint r files arrayexitit works fine if file size is under 10mb file size limit is 10mb and i do not want to increase it i just want to capture an error in phpupdated explanationsolution from php sitefrom php site i missed this sectionsets max size of post data allowed this setting also affects file upload to upload large files this value must be larger than upload max filesize if memory limit is enabled by your configure script memory limit also affects file uploading generally speaking memory limit should be larger than post max size when an integer is used the value is measured in bytes shorthand notation as described in this faq may also be used if the size of post data is greater than post max size the post and files superglobals are empty this can be tracked in various ways eg by passing the get variable to the script processing the data ie and then checking if getprocessed is set,"['php', 'html']" +206988,how to write unit tests with tpl and taskscheduler imagine a function like thisprivate static concurrentlistobject list new concurrentlistobjectpublic void addobject x taskfactorystartnew listaddx i do not care when exactly the fentry is added to the list but i need it to be added in the end obviously i do not see a way to properly unittest stuff like this without returning any callbackhandler or sth and therefor adding logic that is not required for the programhow would you do it,['c#'] +206996,how to change the style of alert box i need to change the style of the ok button in an alert boxhead script typetextjavascript function show alert alerthello i am an alert box scriptheadbody input typebutton onclickshow alert valueshow alert box body,"['javascript', 'css']" +207004,multiple dex files error when compiling with ant or eclipse i am unable to build my applicationi am running the latest build tools downloaded today this started happening after the updatedex dex converting compiled files and external libraries into usersrobreposmy appbinclassesdex dx dx unexpected toplevel exception dx comandroiddxutildexexception multiple dex files define lcomrobaldredmyappabout1i have tried cleaning and rebuilding i have also tried in eclipse but it gives the same erroranyone got any ideas i am at a brick wall here now,['android'] +207005,set a symbol marker with highchart highchart has an option which will let me set a marker to certain valuehighchart doc data 70 69 95 145 182 215 252 y 265 marker symbol urldemogfxsunpng 233 183 139 96as you can see the position 265 gains a png image as its markermy question is how can i set it to a certain value from my arraygetjsonajaxlinechartajaxphp functiondata eachdata functionkey value var series data y 0 marker symbol urlimgfailpng data array for new series name key marker symbol square seriesdata value optionsseriespushseries pushing series object var chart new highchartschartoptions i tried this but nothing appeared the chart ran without the marker,"['javascript', 'jquery']" +207024,configuring objectmapper in spring my goal is to configure the objectmapper in the way that it only serialises element which are annotated with jsonpropertyin order to do so i followed this explanation which says how to configurate the objectmapperi included the custom objectmapper as described herehowever when the class numbersofnewevents is serialized it still contains all attributes in the jsondoes anybody have a hintthanks in advancejackson 180spring 305customobjectmapperpublic class companyobjectmapper extends objectmapper public companyobjectmapper super setvisibilitycheckergetserializationconfig getdefaultvisibilitychecker withcreatorvisibilityjsonautodetectvisibilitynone withfieldvisibilityjsonautodetectvisibilitynone withgettervisibilityjsonautodetectvisibilitynone withisgettervisibilityjsonautodetectvisibilitynone withsettervisibilityjsonautodetectvisibilitydefault servletxmlxml version10 encodingutf8beans xmlns xmlnsxsi xmlnscontext xmlnsmvc xsischemalocation contextcomponentscan basepackagedecompanybackendweb mvcannotationdriven bean classorgspringframeworkwebservletmvcannotationannotationmethodhandleradapter property namemessageconverters list bean classorgspringframeworkhttpconverterjsonmappingjacksonhttpmessageconverter property nameobjectmapper refjacksonobjectmapper bean list property bean bean idjacksonobjectmapper classdecompanybackendwebcompanyobjectmapper beansnumbersofneweventspublic class numbersofnewevents implements statusattribute public integer newaccepts public integer openrequests public numbersofnewevents super,['java'] +207028,cashapelayer as a mask for calayer rounded corners are stretched i want to mask a calayer with cashapelayer because changes to the shape can be animated when i use the cashapelayer as a mask the rounded corners are stretched however if i take the same shape create an nsimage with it and use the image to mask my calayer the rounded corners are perfectly fineheres the code i am using to mask the layers you can also download the whole example projectcgcolorref backgroundcolor cgcolorcreategenericrgb00 00 00 10fselfwindowcontentview setlayercalayer layerselfwindowcontentview setwantslayeryesselfwindowcontentview layer setframeselfwindowcontentview framecalayer imagebasedmasklayer calayer layerimagebasedmasklayer setcontentsidself maskwithsizensmakesize50 50 cgimageforproposedrectnull contextnil hintsnilimagebasedmasklayer setframecgrectmake0 0 50 50calayer layerwithimagebasedmasklayer calayer layerlayerwithimagebasedmasklayer setbackgroundcolorbackgroundcolorlayerwithimagebasedmasklayer setmaskimagebasedmasklayercashapelayer shapebasedmasklayer cashapelayer layercgpathref maskshape self newmaskpathwithframensmakerect0 0 50 50shapebasedmasklayer setpathmaskshapeshapebasedmasklayer setfillrulekcafillruleevenoddcgpathreleasemaskshapeshapebasedmasklayer setframecgrectmake0 0 50 50calayer layerwithshapebasedmasklayer calayer layerlayerwithshapebasedmasklayer setbackgroundcolorbackgroundcolorlayerwithshapebasedmasklayer setmasknillayerwithshapebasedmasklayer setmaskshapebasedmasklayerlayerwithimagebasedmasklayer setframecgrectmake50 50 50 50layerwithshapebasedmasklayer setframecgrectmake120 50 50 50selfwindowcontentview layer addsublayerlayerwithimagebasedmasklayerselfwindowcontentview layer addsublayerlayerwithshapebasedmasklayercgcolorreleasebackgroundcolorand the two methods i am using to create nsimage and cgpathref nsimage maskwithsizecgsizesize nsimage maskimage nsimage alloc initwithsizesize maskimage lockfocus nscolor blackcolor setfill cgpathref mask self newmaskpathwithframecgrectmake0 0 sizewidth sizeheight cgcontextref context nsgraphicscontext currentcontext graphicsport cgcontextaddpathcontext mask cgcontextfillpathcontext cgpathreleasemask maskimage unlockfocus return maskimage autorelease cgpathrefnewmaskpathwithframecgrectframe cgfloat cornerradius 3 cgfloat height cgrectgetmaxyframe cgfloat width cgrectgetmaxxframe cgmutablepathref maskpath cgpathcreatemutable cgpathmovetopointmaskpath null 0 heightcornerradius cgpathaddarctopointmaskpath null 0 height cornerradius height cornerradius cgpathaddlinetopointmaskpath null widthcornerradius height cgpathaddarctopointmaskpath null width height width heightcornerradius cornerradius cgpathaddlinetopointmaskpath null width cornerradius cgpathaddarctopointmaskpath null width 0 widthcornerradius 0 cornerradius cgpathaddlinetopointmaskpath null cornerradius 0 cgpathaddarctopointmaskpath null 0 0 0 cornerradius cornerradius cgpathclosesubpathmaskpath return maskpathplease note that the actual mask i want to create is more complicated than a rounded rect otherwise i wouldve used some of the simpler drawing techniques i have tried various cgpath drawing functions the problem did not thisappearwhat am i missing here,['objective-c'] +207036,htaccess rule to tidy up rest api requests i have an api server that i am working on it currently accepts requests through get variables like belowhttplocalhostrequestphpmethodgetactionquery usersid1138ab9bce298fe353827792794394time1319225314signatured2325dedc41bd3bb7dc3f7c4fd6f081d95af10i need help creating a htaccess rule that can read urls that replace the with and also the and with to create a clean url likehttplocalhostrequestmethodgetactionquery usersid1138ab9bce298fe353827792794394time1319225314signatured2325dedc41bd3bb7dc3f7c4fd6f081d95af10is there any way of doing this whilst still keeping the get parameters intact for the api to work fromalso this is not the only request there are different requests that will be madestackoverflow is always the place to go for expert advice so thanks in advance,['php'] +207049,join two identical table structures with different data editafter attempting the coalesce method i am now seeing an issue where the data is repeating itself with the same data for each wattage category column 2 is wattagei have created two temp tables both with the exact same table structure in these tables there are multiple columns that could have the same values and then a few value columns that will have different numbers some of these will be null in one column and not null in another i want to get all the values together and on rows with the same site and plant i would like the values joinedhere is an example of what the two tables could look like and the result i would expecttable1 site plant value 1 value 2s1 p1 54 66s1 p2 43 43table 2site plant value 1 value 2s1 p1 33 43s2 p1 34 22resultsite plant t1 value 1 t1 value 2 t2 value 1 t2 value2s1 p1 54 66 33 43s1 p2 43 43 null nulls2 p1 null null 34 22my original thoughts would be a full join however this does not work because in your select statement you must specify where to grab the columns from like site and plant but to select both t1site and t2site would generate two columns the closest thing i got was the query below however anytime there is a result in s2 that has a site and plant not in s1 you receive null values for s1 and s2select t1site t1plant t1value 1 t1value 2 t2value 1 t2value 2 from table1 t1 full join table2 t2 on t1site t2siteand t1plant t2plant,['sql'] +207051,sleeppausewait in javascript possible duplicatejavascript sleep is there a javascript function that simulates the operation of function sleep in phpa function sleep to pause code execution on x milliseconds and then resume where it left offthere is something in javascripti found some things here on stackoverflow but nothing useful,['javascript'] +207052,how can i trim just the left and right side of an image using imagemagick in php i am trying to trim a variable amount of whitespace in an image only the left and right side using imagemagick and php does anyone know how to do this perhaps using something other than imagemagickheres an examplei have these two imageseach has a variable amount of text that is dynamically created in a fixed width imagewhat i need to do is trim the background off the right and left side so the images come out like thisif imagemagick cannot do it i am willing to use something else but i will need help on how exactly because i am not much of a programmer thanksheres my current code that trims all sides of an imagephp create the object and read the image in i 3im new imagicktestipng trim the image imtrimimage0 ouput the image headercontenttype image imgetimageformatecho im write the trimmed image to thisk imwriteimagedirname file testipngthisplay imageecho img img srctestipng,['php'] +207078,how can i prevent scroll bars from being hidden for os x trackpad users in webkitblink webkitblinks safarichrome default behaviour on on mac os x since 107 lion is to hide scroll bars from trackpad users when they are not in use this can be confusing the scroll bar is often the only visual cue that an element is scrollableexample jsfiddlehtmldiv classframe foobr barbr bazbr help i am trapped in an html factory divcssframe overflowy auto border 1px solid black height 3em width 10em lineheight 1emawebkit chrome screenshotpresto opera screenshot how can i force a scroll bar to always be thisplayed on a scrollable element in webkit,['css'] +207081,why is volatile used in this example of double checked locking from head first design patterns book the singleton pattern with double checked locking has been implemented as below public class singleton private volatile static singleton instance private singleton public static singleton getinstance if instance null synchronized singletonclass if instance null instance new singleton return instance i do not understand why volatile is being used does not volatile usage defeat the purpose of using double checked locking ie performance,['java'] +207085,gmail on heroku with rails 3 i am trying to send emails from heroku up and running at the moment i can send emails from heroku via the tutorial at sending email with gmail so that is finemy current problem is that when i got it to work at heroku i cannot get it to work in development i had that up and running with settings in either environmentrb or developmentrb but after the stuff in the tutorial kicked in and i removed the settings in envdevrb it does not workin the browser i get the error msg530551 authentication required learn more at it cuts after learn more atin the server console i get the error msgnetsmtpauthenticationerror 530551 authentication required learn more ati have set heroku configadd gmail smtp user and heroku configadd gmail smtp passwordyourpassword with my info but it does not helpany ideas what i am doing wrongcan i do it the old way in development and skip the heroku script in some waycheers carl,['ruby-on-rails'] +207089,linq queries with dynamic order by i have a query where i need to have ordeby based on a querystring parameter for example if sortby parameter is price query needs to change with price if its rating than change query to sort by rating i know predicatebuilder can do and and or stuff but how do i make a dynamic ordeby linq query,"['c#', '.net']" +207178,introspection on pygtk3 possible one of the great things of python is the ability to have introspection on methods and functions as an example to get the function signature of mathlog you can in ipython run thisin 1 mathlogtype builtin function or methodbase class type builtin function or methodstring form builtin function lognamespace interactivedocstring logx base return the logarithm of x to the given base if the base not specified returns the natural logarithm base e of xand see that x and optionally base are the parameters of this functionwith the new gtk3 and the automaticall generated pygobject bindings i can in all examples i tried only ever get args kwargs as the parameters of every gtk method example labelset text which requires a stringin 1 from girepository import gtkin 2 mylabel gtklabelhelloin 3 mylabelset texttype instancemethodbase class type instancemethodstring form bound method labelset text of label object at 0x275b230 gtklabel at 0x28cd040namespace interactivefile usrlibpython27thistpackagesgitypespydefinition lset textargs kwargsdocstring no docstringnow the question is this the loss of method introspection for python bindings something that will change once more documentation effort has gone into pygobjects or is this something that is here to stay due to the way pygobjects works,['python'] +207215,optimzing ccode with sseintrinsics i have been struggling for a while with the performance of the network coding in an application i am developing see optimzing ssecode improving performance of network codingencoding and opencl thistribution now i am quite close to achieve acceptable performance this is the current state of the innermost loop which is where 99 of the execution time is being spent whileelementiterations 0 unsigned int firstmessagefield currentmessagegaloisfieldsarray unsigned int secondmessagefield currentmessagegaloisfieldsarray m128i valuestomultiply mm set epi320 secondmessagefield 0 firstmessagefield m128i mulitpliedhalves mm mul epu32valuestomultiply fragmentcoefficentvector do you have any suggestions on how to further optimize this i understand that it is hard to do without more context but any help is appreciated,['c'] +207222,popstate returns eventstate is undefined i am learning about history in html5 in this example open the javascript browser console to see error the eventstateurl returnsuncaught typeerror cannot read property url of undefinedlook and help,['jquery'] +207275,best practice to get entitymanagerfactory what is the best approach to get entitymanagerfactory in web appjspservletsis this a good way when should entitymanagerfactory instance be createdopenedor it is better get it from jndi or something else,['java'] +207286,java swing how do i properly instantiate gui and pass domain objects i have a gui with nested panelstabbed with nested panels and etc i need to pass domain object to deeply nested panel i can think of two waysinstantiate all gui objects in one place like frame class thatwould make passing domain objects dead simple but frame class willbe huge and hardly maintanableeach panel has its own class where we instantiate and layout itscomponents now its easy to maintain and classes are clean but howdo i pass down the chain my domain objects i dont want to chainpassthem through constructors of panels that should not even know theirexistance and top level panels would have a ton of these objects to start withniether way seems like a soulution how do you usually aproach this,['java'] +207289,capistrano deploy host key verification failed i have followed several suggestions from other sites but to no avail when i try cap deploycold i consistently get host key verification failedi have tried everything i have sshd from my computer to the remote removed and readded both keys from knownhosts cloned from github set up my public key from both the server and local on githubwhat am i missing herecapfileerrors,['ruby-on-rails'] +207299,nsdata isequaltodata i really do not understand whats going on herei have a function that is getting the first 3 bytes from an nsdata object receivedstream and putting them into another nsdata object temp via a char array then comparing that to an nsdata object created from a char array buffer both new nsdata objects are created and have the correct contents however when isequaltodata is called i get an errornsconcretedata isequaltodata unrecognized selector sent to instance instance refers to tmp2i also get the warninginstance method isequaltodata not found return type defaults to idwhich i do not understand as it is clear that this is a valid method in the docs do i need to declare nsdatah somewhereboolcheckheader char tmp3 receivedstream getbytestmp length3 nsdata temp nsdata datawithbytestmp length3 nsdata tmp2 nsdata datawithbytesheader length3 bool test tmp2 isequaltodatatemp return test,['objective-c'] +207312,rails and postgresql role postgres does not exist i have installed postgresql on my mac os lion and am working on a rails app i use rvm to keep everything separate from my other rails appsfor some reason when i try to migrate the db for the first time rake cannot find the postgres user i get the error fatal role postgres does not existi have pgadmin so i can clearly see there is a postgres user in the db the admin account in fact so i am not sure what else to doi read somewhere about people having issues with postgresql because of which path it was installed in but then i do not think i would have gotten that far if it could not find the db,['ruby-on-rails'] +207313,error building stanford corenlp when i build corenlp on my own i get the following messageincompatible types no instances of type variables value exist so that value conforms to mapintegerstringthe offending linemapintegerstring rolemap corelabelt1labelgetcoreannotationsconllsrlannotationclassthe offending function suppresswarningsunchecked public value key extends keycoremap value value getclasskey key for int i size i 0 if keysi key return valuevaluesi return nulli really have no clue how to fix this i am trying to build corenlp with maven so i can use it easily in my project ideas,['java'] +207334,why cannot i override layout properties of included layouts in my android project i am attempting to create some modular ui elements as described at android developers creating reusable ui components unfortunately i am not getting the desired result the article states you can override all the layout parameters this means that any androidlayout attribute can be used with the tagmy xml code looks like this relevant partsxml version10 encodingutf8relativelayout xmlnsandroid androidorientationvertical androidlayout widthfill parent androidlayout heightfill parentinclude androidididradio group layoutlayoutradio buttons androidlayout margintop75dp include androidididplayer group layoutlayoutplayer buttons androidlayout alignparentbottomtrue edittext androidididtext field androidsinglelinetrue androidlayout widthfill parent androidlayout heightwrap content androidhintenter your login id androidlayout belowidplayer group here is the first of the included layouts radiogroup xmlnsandroid androidididradio group androidlayout widthfill parent androidlayout heightfill parent androidorientationvertical androidlayout margintop20dp androidlayout marginleft20dp androidlayout marginbottom20dp radiobutton androidididradio01 androidlayout widthwrap content androidlayout heightwrap content androidtextsong 1 androidpaddingleft45dp two more identical buttonstextview androidididchoice androidlayout widthfill parent androidlayout heightwrap content androidtextyou have selectedradiogroupand the otherxml version10 encodingutf8linearlayout xmlnsandroid androidlayout widthfill parent androidlayout heightwrap contentbutton androidtextbtn01 androidididbutton01 androidlayout widthwrap content androidlayout heightwrap content androidgravitycenter horizontal button androidtextidbutton02 androidididbutton02 androidlayout widthwrap content androidlayout heightwrap content androidgravitycenter horizontal button androidtextstart playing androidididstartplayerbtn androidlayout widthwrap content androidlayout heightwrap content androidgravitycenter horizontal androidonclickdoclick linearlayoutunfortunately this results in all the included ui elements bunched together on top of each other at the top of the screen the edittext element aligns correctly but none of the included elements will respond to any overrided attributes i have tried a number of different ones with the same nonresults note i also tried putting an androidlayout alignparentbottomtrue parameter into the included layouts thinking that it might need to be in there for it to be overridden but got the same nonresultalso the margintop param does not do anything eitherso any idea what i am doing wrong this is driving me crazynote there was a question asked a little while ago about how to style included layouts the answer was a reference to the page on reusable ui components just want to say that i have read that question and the answer and it has not helped,['android'] +207364,multiprocessingpool picklingerror cannot pickle attribute lookup threadlock failed multiprocessingpool is driving me crazyi want to upgrade many packages and for every one of them i have to check whether there is a greater version or not this is done by the check one functionthe main code is in the updaterupdate method there i create the pool object and call the map method here is the codedef check oneargs res total package version args i resqsize loggerinfor01 1 2 3 i floattotal package i total addnfalse try json pypijsonpackageretrieve new version versionjsoninfoversion except exception as e loggererrorerror failed to fetch data for 0 1 package e return if new version version resput nowaitpackage version new version jsonclass updaterfilemanager init and other methods def updateself loggerinfosearching for updates packages queuequeue data packages selfset len thistproject name versionthistversion for thist in selfworking set pool multiprocessingpool poolmapcheck one data poolclose pooljoin while true try package version new version json packagesget nowait except queueempty break txt a new release is avaiable for 0 1s old 2 updateformatpackage new version version you loggerasktxt boolupgrade version keep working version dont askselfyes if u selfupgradepackage json new version else loggerinfo0 has not been upgraded package self clean loggersuccessupdating finished successfullywhen i run it i get this weird errorsearching for updatesexception in thread thread1traceback most recent call last file usrlibpython27threadingpy line 552 in bootstrap inner selfrun file usrlibpython27threadingpy line 505 in run self targetself args self kwargs file usrlocallibpython27thistpackagesmultiprocessingpoolpy line 225 in handle tasks puttaskpicklingerror cannot pickle type threadlock attribute lookup threadlock failed,['python'] +207386,how to close browser with capybara i have a situation when i am using using selenium driver multiple browsers with capybara to test my frontend how can i close some of them using capybara when they are not needed,['ruby'] +207389,how to match letters only using java regex matches method import javautilregexpatternclass howeasy public boolean matchesstring regex systemoutprintlnpatternmatchesregex abcabc return patternmatchesregex abcabc public static void mainstring args howeasy words new howeasy wordsmatchesazaz the output is false where am i going wrong also i want to check if a word contains only letters and may or maynot end with a single period what is the regex for thatie abc abc is valid but abc is not valid i can use indexof method to solve it but i want to know if it is possible to use a single regex,['java'] +207410,stdmake tuple does not make references i have been experimenting with stdtuple in combination with referencesinclude iostreaminclude tupleint main int ab stdtupleintint testab stdget0test 1 stdget1test 2 stdcout a b stdendl does not make ref not expected auto test2 stdmake tupleab stdget0test2 1 stdget1test2 2 stdcout a b stdendl int ara int brb why does this not make a tuple of int references can we force it to notice auto test3 stdmake tuplearbr stdget0test3 1 stdget1test3 2 stdcout a b stdendlof the three examples here the first two work as expected the third one however does not i was expecting the auto type test3 to be the same as the type of test ie stdtupleintint it seems that stdmake tuple cannot automatically make tuples of references why not what can i do to make this the case other than explicitly constructing something of that type myself compiler was g 445 using 45 does not change it,['c++'] +207414,remove duplicates from array array unic by key array 0 array file varwebsitesexamplecomassetsimages200px1419050406e6648e1c766551a0ffc91380fd6ff3406002010233750jpg md5 42479bee7a304d2318250de2ef1962a9 url 1 array file varwebsitesexamplecomassetsimages200px212792606e6648e1c766551a0ffc91380fd6ff3406002010233750jpg md5 42479bee7a304d2318250de2ef1962a9 url how can i remove md5 key duplicates from above array,['php'] +207419,does bugsense crash handler need to be called in each activities of an android application my app has 3 activities ab and cfrom a the home i can start b and from b i can start cdo i have to call bugsensehandlersetupthis my api key only in a or also in b and c,['android'] +207445,implicit intent to uninstall application i am trying to have an onclicklistener call an intent to uninstall an app by having the intent call the default uninstall app activity from the applications settings i have found herethat i can uninstall an app using action uninstall package compackagexyxy which seems to be what i am looking forhowever i am unsure how to call this i have tried the following public void onclickdialoginterface dialog int which uri packageuri uriparsepackagecompackagename intent uninstallintent new intentintentaction uninstall package packageuri startactivityuninstallintentbut the syntax is wrong have tried a number of different ways of calling this and am kind of stuck not sure how to call this thanks for your help,['android'] +207464,java comparing arrays i have two arrays of unknown typeis there a way to check the elements are the samepublic static boolean equalsobject a object b if a instanceof int return arraysequalsint a intb if a instanceof double etci want to do this without all the instanceof checks,['java'] +207493,radgrid get selected row index from item template button i am working on a project using telerik controls i am trying to figure out how to get the selected row index on an itemtemplate button click event like in the markup belowtelerikradgrid idradgrid1 runatserver allowfilteringbycolumntrue datasourceidcusgrid gridlinesnone skindefault allowpagingtrue datakeyvaluecustomerid pagesize500 allowmultirowselectiontrue showstatusbartrue mastertableview autogeneratecolumnsfalse datakeynamescustomerid datasourceidcusgrid rowindicatorcolumn headerstyle width20pxheaderstyle rowindicatorcolumn expandcollapsecolumn headerstyle width20pxheaderstyle expandcollapsecolumn columns telerikgridtemplatecolumn uniquenamecheckboxtemplatecolumn itemtemplate aspbutton runatserver textselect onclickselrecord itemtemplate telerikgridtemplatecolumn normally with a gridview i would just do something likeprotected void selrecordobject sender eventargs e var grow gridviewrowsender as controlparentparent var key stringempty if grow null key growcells0text what is the equivalent with the telerik control,"['c#', 'asp.net']" +207527,updating a yaml file in ruby my class isclass mycfg options def init options yamlload filedirpwd path end def setkey val optionskey val end def getkey optionskey end def save endendusing this classoj mycfgnewojinitif ojget name tom ojset changed datanowendojsaveyaml filename tompawd 123456version 001created 201024changed 201024how to i finish the method save to update the yaml file if something has changed,['ruby'] +207533,apache camel alternative in net apache camel provided the sort of configurable architecture which allows web service messages to be determined dynamically during run time for web services that are hosted in java environment i was wondering whether there is a similarequivalent framework for applications written in c and hosted in netsharepoint environment,"['c#', '.net']" +207539,increase the grid spacing in android i have a gridview in which i have a lot of items in three colums i want to increase the spacing between them how can i do that in android,['android'] +207574,what is the best python editor which editor do you find best for python development temporarily i use notepad it is fine except for debuggingthanks,['python'] +207577,convert date from long time postgres i want to select datereadable string from epoch time from one column that have time in long milliseconds in postgres likeselect to datetime in milli sec from mytablehow to do,['sql'] +207582,how do i schedule a conditional continuewith i have some gui on a bunch of linq queries the queries take some time to execute so i would like for the gui to be responsive and show busyindicators and progress bars many of the queries are to check for certain conditions existing in the data if the query returns an empty result the app shall continue with the next query if it returns a result the return set will either be of severity warnings or errors if it is warnings execution shall continue if it is errors it shall stopmuch code plays ping pong with the threadpool and gui quasi codetaskfactorystartnew run in background continueingui update something continueinbackground do more work continueingui etc etcthis is tidy and nice however i do not see how i can insert conditions to go different continuation routes or break off the continuation chain if errors are found in the datathere is no method for continuewithif predicate delegatetaskschedulerdo i use taskcancellation do i throw an exception or is there some simple branching mechanism that i am not thinking of,['c#'] +207602,android one onclick method for multiple buttons i started program little bit in android i have 3 buttons in a single activityi saw some example codes that assign the same onclick event to all the buttons even if they perform completely different action and in the method switchid case case casewhat is the better approach one onclick method and switching or a lot of methods one for each buttonthanks,"['java', 'android']" +207630,updating the value of data attribute using jquery i have the following html codea classtoggle hreftoggle img srcappcssimagestockpng altno dataid4 datablock1ai want to update the value of src and datablock attribute using jquery how do i do itupdate as i have many image elements i want to update the value of specific image by using dataidthanks,['jquery'] +207631,rake aborted table users already exists i have created a database with devise and the nifty generator i am trying to make a new database with the nifty generator rails g niftyscaffold asset user idinteger but when i try to migrate the database rake dbmigrate i get the following errorcharlottedatorshowdown holgersindbaek rake dbmigrate devisecreateusers migrating create tableusersrake abortedan error has occurred all later migrations canceledmysql2error table users already exists create table users id int11 default null auto increment primary key email varchar255 default not null encrypted password varchar128 default not null reset password token varchar255 reset password sent at datetime remember created at datetime sign in count int11 default 0 current sign in at datetime last sign in at datetime current sign in ip varchar255 last sign in ip varchar255 name varchar255 created at datetime updated at datetime engineinnodbtasks top dbmigratesee full trace by running task with tracei am following a tutorial and have quite a hard time understanding why this happens can anyone explain what is going on,"['ruby-on-rails', 'ruby']" +207643,how to flatten array in jquery how to simply flatten array in jquery i have 1 2 3 4 5 6 7and i want 1 2 3 4 5 6 7,['jquery'] +207649,recursive fibonacci memoization i need some help with a program i am writing for my programming ii class at universtiy the question asks that one calculates the fibonacci sequence using recursion one must store the calculated fibonacci numbers in an array to stop unnecessary repeated calculations and to cut down to the calculation timei managed to get the program working without the array and memorization now i am trying to implement that and i am stuck i am not sure how to structure it i have googled and skimmed through some books but have not found much to help me solve how to implement a solutionimport javaxswingjoptionpanepublic class question2static int count 0static int dictionarypublic static void mainstring argsint answerint num integerparseintjavaxswingjoptionpaneshowinputdialogenter njavaxswingjoptionpaneshowmessagedialognull about to calculate fibonacci num giving the array n elementsdictionary new int numif dictionarylength0dictionary0 0if dictionarylength1dictionary0 0dictionary1 1method callanswer fibonaccinumoutputjoptionpaneshowmessagedialognullfibonaccinum is answer took count calls static int fibonacciint n count only defined for and 0if n 0 systemoutprintlnerror fibonacci sequence not defined for negative numbers systemexit1 base cases f0 is 0 f1 is 1 other cases fn fn1 fn2if n 0 return dictionary0else if n 1 return dictionary1elsereturn dictionaryn fibonaccin1 fibonaccin2the above is incorrect the end of my fib method is the main problem i have no idea how to get it to add the numbers recursively to the correctly parts of the array,['java'] +207657,why do we use virtual and override why do we use override and virtual if it gives the same effect when we dont use override and virtualexample 1class baseclass public virtual string call return a class derivedclass baseclass public override string call return b output bexample 2class baseclass public string call return a class derivedclass baseclass public string call return b and the output is still the sameoutput bto run the testclass program static void mainstring args derivedclass dc new derivedclass consolewritelinedccall consolereadkey does the compiler add virtual and override automatically at compile timei would be pleased if someone would explain to me the reason for using virtual and override,['c#'] +207688,how to turn off buffering of stdout in c i want to turn off the buffering for the stdout for getting the exact result for the following codewhile1 printfsleep1the code printf bunch of only when buffer gets filled,['c'] +207698,contenttypetextplain forces to download the file if i call headercontenttypetextplain charsetiso885915 the browser will download the file instead of showing it using texthtml works instead the downloaded file is processed anyway it is not downloading the source codei have tried to add headercontentthispositioninline but it was just ignoredi am pretty clueless about what could cause this problem any tipthe server is mamp 196 php 535 apache2064edit this only happens on chrome it works on firefox camino and safari,['php'] +207702,ror precompiling assets fail while rake assetsprecompile on basically empty applicationjs runningbundle exec rake assetsprecompile rails envproduction trace execute assetsprecompileprimaryrake abortedtypeerror object does not support this property or method in csitesmyappappassetsjavascriptsapplicationjshere is the entire content of applicationjs require jquery require jquery ujs require tree nothing else there i tried to remove the three require lines from applicationjs the precompilation then runs with no problems,['ruby-on-rails'] +207704,standard 401 response when using http auth in flask in flask i am using the following snippet to enable http authdef authenticate return responsewhy access is denied string goes here 401 wauthenticatebasic realmlogin requirednow in my past experience with flask if someones credentials are incorrect and i want to let them know i can just callabort401this gives you the basic apache 401 response does anyone know how i can implement that with the snippet abovethanks,['python'] +207712,typeerror adoesnotexista object is not callable it is not always this code chunk but this is the most recent it seems to be random any thoughtstry you userobjectsgetemail iexactuseremailexcept userdoesnotexist throws this error randomlyfile srvmyappregistrationmodelspy line 23 in get or create user you userobjectsgetemail iexactuseremailfile usrlocallibpython26thistpackagesdjangodbmodelsmanagerpy line 132 in get return selfget query setgetargs kwargsfile usrlocallibpython26thistpackagesdjangodbmodelsquerypy line 349 in get selfmodel metaobject nametypeerror adoesnotexista object is not callable,['python'] +207735,is it possible to reference an anonymous function from within itself in php i am trying to do something like the following assume f is an arg to the wrapping functionself thisfunc function usef ctx self selfremovefunc ctx i want func to be a reference to this anon function args func get args call user func arrayf argsis it possible to reference the function assigned to func from with the same function,['php'] +207744,why would you use custom attributes in your code net could anyone explain the benefits or reasons to use custom attributes in your code of course i use and understand the purpose of defined attributes in certain scenarios wcf serialization etc but i cannot imagine any algorithms where i would need to create and use my own custom attributes could someone provide a realworld case where usages of custom defined attributes bring something to a project,"['c#', '.net']" +207755,ttk treeview alternate row colors how can i set a style for treeview widgets so that alternate rows have different background colors for example rows 135 have white backgrounds and rows 246 have light bluegrey backgroundsi would also like to set gridlines,['python'] +207782,mysql query performance dilemma enum vs tables i currently have this schemacreate table users users id int11 not null auto increment users name varchar50 users lastname varchar50 users dob date users type int11 not null default 0 users access int11 not null default 0 users level int11 not null default 0 etc primary key users id enginemyisam default charsetlatin1create table users types types id int11 not null auto increment types name varchar50 primary key types id enginemyisam default charsetlatin1 etcqueryselect types name as user type all other fields users from users inner join users types on usersusers typetypes id inner join for all other tables rest of query my new solutioncreate table users users id int11 not null auto increment users name varchar50 users lastname varchar50 users dob date users type enumtype1 type2 type3 users access enumaccess1 access2 access3 users level enumlevel1 level2 level3 etc primary key users id enginemyisam default charsetlatin1queryselect from usersfrom what i see is using enum is very simple and can be very fast to executeam i right would it be faster for the mysql engine to process an enum type field rather than having left joinsis using enum a good practicethanks,['mysql'] +207785,using anchors in python regex to get exact match i need to validate a version number consisting of v plus positive int and nothing elseeg v4 v1004i have import repattern avdwm rematchpattern v303if m is none print nomatchelse print matchbut this does not work removing the a and w will match for v303 but will also match for v30g for example thanks,['python'] +207786,how to unit test file uploads with mockhttpservletrequest i have a spring 30 controller with a method which has httpservletrequest as one of the parameters since it is handling multiple file uploadsrequestmappingvalue classifiedidclassifieddealeridpersonupload method requestmethodpostresponsebodypublic final string uploadclassifiedpicture pathvariable int idclassified pathvariable int idperson requestparam string token httpservletrequest requesthow to unit test it i know i can create a mockhttpservletrequest but i do not know how to pass one or more files to itmockhttpservletrequest request new mockhttpservletrequestpost classified38001dealer54uploadtokendfak241adf,['java'] +207787,using c0x in xcode 42 project via cmake i am using cmake to generate a project file for xcode 42 on osx lion and i am using some of the c0x features in llvm like nullptr and auto in order to use these xcode requires that 2 project settings be setc language dialect set to c0x stdc0xc standard library set to libc llvm c standard library with c0x supportcurrently every time i generate an xcode project i have to go in and manually adjust these settings is there a way to specify these settings in cmakethanks,['c++'] +207793,make a cookie expire in 30 seconds could someone update the following code to make the cookie expire in 30 secondsfunction setcookiec name value exdays var exdate new date exdatesetdateexdategetdate exdays var c value escapevalue exdays null expires exdatetoutcstring documentcookie c name c value,['javascript'] +207806,a variable that is readonly after assignment at runtime fairly new programmer here and an advance apology for silly questionsi have an int variable in a program that i use to determine what the lengths of my arrays should be in some of my structures i used to put it in my header as a const int now i want to fork my program to give the variable different values depending on the arguments given in but keep it readonly after i assign it at runtimea few ideas i have had to do this is there a preferred waydeclare a const int in my header and assigning it to a const int in my main function but that seems clunkymake it a plain int in my main functionpass the variable as an argument when the function is calledsomething else i have not thought of yet,['c++'] +207807,excluding south migrations from pylint i am using south for migration in my django project when i run pylint on my project i get a bunch of errors from the migration files how can i exclude migration files from pylinti am on a windows system so i cannot use filename exclusions in the pylint options i have tried to resort to adding pylint thisablemsgcatwcrefi to the top of each of my migration files it seems very kludgy and seems to be the last resort but this documented directive does not work and i get the error e unrecognized file option thisablemsgcatany helpthanks,['python'] +207827,how do i make an event in the usercontrol and have it handeled in the main form i have a custom usercontrol and i want to do something relatively simplewhen ever a numeric up down in that usercontrols value changes have the main form update a thisplay windowthis is not a problem if the nud was not in a usercontrol but i cannot seem to figure out how to have the event handled by the mainform and not the usercontrol,['c#'] +207832,are net opencv wrappers worth using so we have this image processing course at the university and well be using opencv extensively problem is opencv uses c but i am much more fluent in c than c i know that there are wrappers for opencv opencvdotnet sharpercv emgucv but i do not know which to choosemy questions are which one wraps mostall of opencv functionality are they even worth using may not be updated often lack functionality or speedor should i be better off brushing my c skillsnote i know that my question is a possible duplicate of this one but it is old from 2008 and things may have changed,"['c#', '.net', 'c++']" +207844,syswebformspagerequestmanagerservererrorexception an unknown error occurred while processing the request on the server i have couple of update panels and jquery tabs on page and also i am loading couple user controls on update panels after user waited for couple of minutes not checked the time approx 40 mins when user send request from submit button it is giving below error syswebformspagerequestmanagerservererrorexceptionsyswebformspagerequestmanagerservererrorexception an unknown error occurred while processing the request on the server the status code returned from the server was 0 when calling method nsidomeventlistenerhandleeventi am not able trace this issue to fix but i am sure this is causing by ajax gurus if you knows solution please let me know,"['c#', 'javascript', 'jquery', 'asp.net']" +207849,the enum as immutable richobject is this an antipattern i have often seen and used enums with attached attributes to do some basic things such as providing a thisplay name or descriptionpublic enum movement thisplaynameturned right turnedright thisplaynameturned left descriptionexecute 90 degree turn to the left turnedleft and have had a set of extension methods to support the attributespublic static string getthisplaynamethis movement movement public static movement getnextturnthis movement movement following this pattern additional existing or custom attributes could be applied to the fields to do other things it is almost as if the enum can work as the simple enumerated value type it is and as a more rich immutable value object with a number of fieldspublic class movement public int value get set ie the type backing the enum public string thisplayname get set public string description get set public movement getnextturn in this way it can travel as a simple field during serialization be quickly compared etc yet behavior can be internalized ala oopthat said i recognize this may be considered an antipattern at the same time part of me considers this useful enough that the anti might be too strict,"['c#', '.net']" +207881,how can i pass mains argv to a function i have a program that can accept commandline arguments and i want to access the arguments entered by the user from a function how can i pass the argv from int main int argc char argv to that function i am kind of new to the concept of pointers and argv looks a bit too complex for me to work this out on my ownthe idea is to leave my main as clean as possible by moving all the work that i want to do with the arguments to a library file i already know what i have to do with those arguments when i manage to get hold of them outside the main i just do not know how to get them therei am using gccthanks in advance,['c'] +207915,what programming language features are well suited for developing a live coding framework i would like to build a live coding frameworki should explain what is meant by live coding framework i will do so by comparing live coding to traditional codinggenerally put in traditional programming you write code sometimes compile it then launch an executable or open a script in some sort of interpreter if you want to modify your application you must repeat this process a live coding framework enables code to be updated while the application is running and reloaded on demand perhaps this reloading happens each time a file containing code is changed or by some other action changes in the code are then reflected in the application as it is running there is no need to close the program and to recompile and relaunch it in this case the application is a windowed app that has an updatedraw loop is most likely using opengl for graphics an audio library for sound processing supercollider and ideally a networking libof course i have preferred languages though i am not certain that any of them would be well suited for this kind of architecture ideally i would use python lua ruby or another higher level language however a friend recently suggested clojure as a possibility so i am considering it as welli would like to know not only what languages would be suitable for this kind of framework but generally what language features would make a framework such as this possible,"['python', 'ruby']" +207939,is it true that java implicitly defines references to the objects used in classes after reading the books surfing the nets regarding the type of references in java i still have some doubts or i may have interpreted the concept wrongit would be a great help for me if anyone clear my doubts let me take an example of a class containing class variables instance variables and local variables public class test public static arrayliststring listcommon new arrayliststring private hashmapstring string mapinstance public test mapinstance new hashmapstring string public void dosomethingstring key arrayliststring local new arrayliststring ifkey null localaddmapinstancegetkey systemoutprintlnvalue is added in instance map mapinstancegetkey my question are1 are listcommon static variable and mapinstance instance variable strong reference towards garbage collector2 is variable local defined and used in method a weak reference3 how the phantom reference and soft reference came in picture4 or above 3 concepts are invalid means that java defines the references only if you explicitly used the type defined in javalangref package any help would be great for me,['java'] +207963,password gets thisplayed as in ie for placeholder i am using htlm5 placeholder and added modernizrjs to make it work in ie the code segment is input typepassword placeholderpasswordfunction hasplaceholdersupport var input documentcreateelementinput return placeholder in inputdocumentreadyfunction ifmodernizrinputplaceholder placeholderfocusfunction var input this if inputval inputattrplaceholder inputval inputremoveclassplaceholder blurfunction var input this if inputval inputval inputattrplaceholder inputaddclassplaceholder inputvalinputattrplaceholder blur placeholderparentsformsubmitfunction thisfindplaceholdereachfunction var input this if inputval inputattrplaceholder inputval it is working fine for other browser and i want to thisplay the text for input type password in ie but instead it puts the placeholder in the masking characters how can the password text be thisplyed,"['javascript', 'jquery']" +207966,java difference between list and list what is the difference between list and listobject in java,['java'] +207975,removing routes rendered on a google map i am trying to do something that i gather has been done quite a few times before although i am having some difficulty accomplishing iti have a webpage that thisplays three google mapsfor each of these google maps i have a text box that accepts a post code zip code and a get directions buttonclicking on each of these buttons uses the googlemapsdirectionsservice object to thisplay one set of directions in one panel centered at the bottom of the pagemy issue arises when i try to find a new route by searching again as you can see in the image below both routes are renderedi have one marker at the end which is in a markers collectioni have read a few times now about how you can loop through this array and use markersetmapnull to clear this marker however i cannot seem to clear the actual routes after each specific search has anybody had any problems with clearing markers from multiple maps do you have to totally reset the map in some wayif you have to clear markers at what point in the lifecycle of the process should you do it so that your new journey appears after the search but the old one is removed,['javascript'] +207991,center align span text inside a div i have a html code asdiv classleftspan classpaneltitletxttitle textspandivmy css is as followsleft backgroundcolor 9 height 50px width 245spanpaneltitletxt thisplay block width 100 height 100now how do i center align the span text inside the div assume that the left div after the conversion gets a px width of 100pxi tried the standard way of using marginauto but that is not workingalso i want to avoid using textaligncenteris there some other way of fixing this,"['html', 'css']" +207992,query the mongodb for the documents whose ids are contained inside a list suppose you have a list of ids which can contain up to thousands ids for the documents inside the database what is the best way to get those documents back should i invoke a query for each of them or should i specify a giant or query may be there is something way better i do not know of,['c#'] +208006,how to run multiple videos with different videoviews in one activity in android 22 i am using 3 videoviews for 3 diff videos in one activity now if i am run the program in android 233 emulator then it runs perfectly but it can run only 1 video in android 22 emulator or deviceso how each video can run in android 22i am using following code to run each videovideoview vd videoviewthisfindviewbyidridvideoviewshow string uri1 androidresource getpackagename rrawdoor 175 210 vdsetvideouriuriparseuri1 vdstart,['android'] +208010,stringbuilder append vs what is the difference between these two linesstringbuilderappendtext counter more textstringbuilderappendtext appendcounterappend more textassuming that counter is an incrementing int does the first line create a string text 0 more text text 1 more text etc each time it is called while the second line creates only these two strings once text and more text is this correct,['java'] +208031,how to check whether a particular device supports 4g networks in android i want to check if a particular device has hardware support for 4g networks i will elaborate the issuein the application we have a settings page where user can make selection and allow application to run only in selected networks eg user can select that app will run only in wifi network or only in 3g network etc there are checkbox preferences for all networks wifi 2g 3g 4g etcnow if the device does not have the support for 4g network i want to hide the 4g selection checkboxall the remaining functionality is complete i am struck on just this issue that how to detect if device support 4g or notplease note that i want to detect hardware support for 4g on the device and not the 4g connection is connected or soany help is greatly appreciated,['android'] +208032,how to get code coverage in android using maven androidmavenplugin i have an android maven project let us call it parent project that contains various submodules my library project app using my library project test project and extra libso the structure would be like thisparent project my library project android library project app using my library project demo app that uses the android library project test project project containing the tests instrumented against app using my library project extra libwhat i would like is to generate test coverage for my android project using maven and not ant i am already able to generate code coverage reports using ant following these instructions i have no strong preference for the code coverage tool used but i would prefer emma since seems the most common in the android development worldi am using androidmavenplugin in its 300alpha12 version and i have already tried to put in the configuration of my parents pomxml the nexttest coveragetruecoverage createreporttruecreatereporttestbut that does not produce the desired code coverage reportsois there any difference between the pom configuration for getting code coverage for a standard java project and an android projectdo you know any example android project using maven that has code coverageany hints on how to do this,['android'] +208051,java method to save current state of a program is it possible to save the current state of a java program and then reload it the program is fairly complicated i just need to be able to save the current state to a file and then reload it could you please refer me to a java library or a place to read more about that from,['java'] +208053,how can i detect screen lockunlock events on the iphone how can i detect screen lockunlock events on the iphone when the user unlocks it i want to show a notification alert from my iphone app for just like broadcast receiver for screen unlock in android,"['ios', 'objective-c']" +208068,how to remove all items from manytomany collection in sqlalchemy when i need to remove an object from declarative orm manytomany relationship i am supposed to do thisblogposttagsremovetagwell what am i supposed to do if i need to purge all these relations not only one typical situation i would like to set a new list of tags to my blogpost so i need toremove all existing relations between that blogpost and tagsset new relations and create new tags if they do not existof course there could be a better way of doing this in that case please let me know,['python'] +208078,ios 5 storyboard programmatically determine path i am having trouble to achieve the following using a storyboardwhen setup is not donerun app show settings view controller show main navigation controllerwhen setup is donerun app show main navigation controllerso basically i want the app to programmatically start with the settings view in certain cases and otherwise skip right ahead to the main navigation controlleri did manage to show the settings view with a modal style segue from the main navigation controller but i do not know how to thisplay it before the main navigation controller is thisplayed any ideas,['objective-c'] +208088,python list last index list1 1 2 33 51i need to check is 4 the last index of the list just like list1lastindex 3how can i do it in python,['python'] +208111,why does the maven assembly plugin append the descriptor ref to the finalname value this is plugin configuration i am usingplugin artifactidmavenassemblypluginartifactid configuration archive manifest mainclasscommycompanychangepasswdmainclass manifest archive finalnamechangepasswdfinalname descriptorrefs descriptorrefjarwithdependenciesdescriptorref descriptorrefs configurationpluginwhen i run mvn clean install assemblysingle what i get is changepasswdjarwithdependenciesjar how do i tell the assembly plugin to just name it changepasswdjar or is that something which is handled outside of the assembly plugin,['java'] +208112,uiwebview does not work like native iphone browser when interacting with aspx page i am fairly new to iphone development and i have been trying to create a wrapper app that points to a aspx webpage the webpage loads without any issues in my uiwebview and the user can select items from two dropdown boxesthe issue here is that once the user selects an item from the dropdown menu the page should refresh to reflect the selected value this does not happen in my webview but works correctly in safari on my iphoneheres the link to the webpage so you can see what i am talking about heremy question is what are the differences between a uiwebview and the native browser which affect running js or aspx or other webpage contents and how do i fix this issuethanks for any help,"['iphone', 'asp.net', 'ios']" +208135,how to add hash clicking to an element when i open my page at where i have this jquery code locslidebutton2clickfunction i would like clicking on the locslidebutton2 element add an hash such as example to the url without make any redirecthow can i do it,"['javascript', 'jquery']" +208147,log4j abbreviateshorten package names how would i abbreviateshorten package names in log generated using log4j ie instead of comlongpackageanotherpackagelastpackagemyclass i want clalmyclass i have seen this in artifactory logs but cannot figure how to achieve this using log4j,['java'] +208151,how does eclipse actually run junit tests i am running into a thiscrepancy when running junit tests in eclipse and ant here is the scenarioeverything ran as intended in eclipse however i could not get an accurate junit report when running through an ant build script i whipped up i made a couple of changes to our test runner and test cases in a nutshell i added the test suite method to all of my test cases which returns a new junit4testadapter and had our custom runner execute runnotifierfiretestassumptionfailedfailure instead of firetestassumption now everything runs fine in ant but failures are marked as passed when run in eclipseis there any documentation for eclipse that explains exactly how it runs junit tests i am basically looking to know exactly how eclipse executes junit tests whether it is run directly through ant if it uses java to interface with junit etc if anyone knows an actual solution to the issue i welcome that as well but i would really like to try solving this one on my own i just need a point in the right direction,['java'] +208158,why does drawstring look so crappy i am trying to add a text scale to a color imagethe agcscalejpg image below is 2 winform labels on the top and bottom and 2 winform pictureboxes on the left and rightthe exact same code was used to produce the strings in the right and left pictureboxes the only difference is that pictureboxagcvscale contains only the strings why does drawstring in pictureboxagc look fine but drawstring in pictureboxagcvscale look so bad i can probably fix pictureboxagcvscale by doing a bmpsetpixel for each pixel but that seems like the wrong way to fix thisprivate void thisplayagcvscaledouble min double max var bmp new bitmappictureboxagcvscalewidth pictureboxagcvscaleheight var c max min bmpheight using var g graphicsfromimagebmp var font new fontmicrosoft sans serif 825f var y1 bmpheight 10 for var y y1 y bmpheight y y1 var agc y c min var text agctostring0v var h bmpheight y fontheight 2 gdrawstringtext font brushesblack 0 h pictureboxagcvscaleimage bmp,['c#'] +208188,how is const implemented how does a compiler c or c for example gcc honors the const declarationfor example in the following code how does the compiler keeps track that the variable ci is const and cannot be modifiedintget foo return 42voidtest int i get foo i 5 const int ci get foo ci 7 compile error assignment of readonly variable ci,"['c++', 'c']" +208203,long compile times in visual c 2010 with large static arrays we have a c project in which there are several large static data tables arrays of structs generated by an preprocessing tool and compiled into our project weve been using vc 2008 up to now but are preparing to move to 2010 and these data tables are suddenly taking a very long time to compileas an example one such table has about 30 entries each of which is a struct containing several ints and pointers all initialized statically this one file took 15 seconds to compile in vc 2008 but is taking 30 minutes in vc 2010as an experiment i tried splitting this table evenly into 8 tables each in its own cpp file and they compile in 2030 seconds each this makes me think that something inside the compiler is on2 in the length of these tablesmemory usage for clexe plateaus at around 400 mb my machine has 12 gb of ram and i do not see any io activity once it plateaus so i believe this is not a thisk caching issuedoes anyone have an idea what could be going on here is there some compiler feature i can turn off to get back to sane compile timeshere is a sample of the data in the table cid 0 0x0 oid cid otyp cid 0 fopti getfn null 0 null pfnget void static castpfnget cidcbasiccid null cid basic cid oid identity 0 null is derived from 1 0x1 oid is derived from otyp bool 0 fopti fn coptthunkmgrthunkoptbasicis derived from false null null null cid basic is derived from oid nil 0 coptioninfomgrs afnsig0 fire trigger event 2 0x2 oid fire trigger event otyp void 0 fopti fn coptthunkmgrthunkoptbasicfire trigger event false null null null cid basic fire trigger event oid nil 0 null fire untrigger event 3 0x3 oid fire untrigger event otyp void 0 fopti fn coptthunkmgrthunkoptbasicfire untrigger event false null null null cid basic fire untrigger event oid nil 0 nullas you can see it includes various ints and enums as well as a few literal strings function pointers and pointers into other static data tables,['c++'] +208208,accessing physical memory from linux kernel can we access any physical memory via some kernel code because i wrote a device driver which only had init module and exit module the code is followingint init modulevoid unsigned char p unsigned char0x10 printk kern info i got u n p return 0and a dummy exit module the problem is the computer gets hung when i do lsmod what happens should i get some kinda permission to access the mem location kindly explain i am a beginner,['c'] +208232,online c compiler with input stream i kinda like codepad online editor supports c but i would like to use some scanfs which is not possible with codepad is there some online c compiler that supports input streams is that even possible,['c++'] +208236,create an a search with php i have a map stored as a multidimensional array maprowcol and i would wish to create a path from point a to point bsince i can have some obstacles with turns corners etc etc i would wish to use the a search to calculate the fastest pathso the general function isfx gx hxand i have all of these values gx is cost of the move and it is saved on the map hx is the linear thistance between a and bso i have everything i need but i have a question how can i organize everythingi have no need to test for alternative paths since a square on the map can be passable or not so when i reach the target it should be the shortest onehow can i organize everythingi tried with multidimensional array but i get lost editi worked out some code it is pretty a wall of text start array28 19 end array14 19thismapmap is a multidimensional array everything has a cost of 1 except for blocking squares that cost 99thismapmap thisradarblocking square at 2317 2218 2219 20 2321 1917 2018201920201921they are like 2 specular mustache pfunction createpathstart end found false temp thiscoststart end foreachtemp as t iftcost thismapmapend0end1 found true thiscoststacktcost arraygrid tgrid dir tdir ksortthiscoststack iffound foreachthiscoststack as k stack foreachstack as kn node curnode nodegrid unsetthiscoststackn break ifcountthiscoststackk unsetthiscoststackk break thiscreatepathcurnode end function costcurrent target return array aim arrayn array1 0e array 0 1s array 1 0w array 0 1 foreachthisaim as direction offset position0 current0 offset0 position1 current1 offset1 radar is a copy of the map if thisradarposition0position1 v continue else thisradarposition0position1 v h int thisthistanceposition target g thismapmapposition0position1 return arraygrid position dir direction cost h g return returni hope you can understand everything i tried to be clear as much as possiblefinally i can get to my destination expanding only cheaper nodes but now i have a problemhow can i turn it into directions i have to store a stack of orders ie n n e etc etc how can i identify a path inside these values,['php'] +208248,javascript dom setting custom dom element properties is it ok to set custom properties on dom elements and rely on them persistingfor example given htmlbodydiv idfoodivbodyhtmlwould it be fair to do documentgetelementbyidfoobar baz and expect documentgetelementsbytagnamediv0bar to equal baznote that i am talking about properties as in normal javascript object properties here not element attributesi am interested both in how crossbrowser it is and whether its supported in any specdoes the dom api guarantee that the same javascript object will be returned for the same dom element every time,['javascript'] +208269,converting from hsv hsb in java to rgb without using javaawtcolor thisallowed on google app engine i figured i should post this question even if i have already found a solution as a java implementation was not readily available when i searched for itusing hsv instead of rgb allows the generation of colors with the same saturation and brightness something i wantedgoogle app engine does not allow use of javaawtcolor so doing the following to convert between hsv and rgb is not an optioncolor c colorgethsbcolorhue saturation valuestring rgb integertohexstringcgetrgbedit i moved my answer as described in the comment by nick johnsonex animo alexander,['java'] +208274,objectivec header file not recognizing custom object as a type i am working on a game for ipad using cocos2d which involves a board filled with different types of tiles i have created a custom class called tile as a general template for tiles and a few subclasses of tile which have different properties and methods i have also created a class called board which among other things keeps track of the locations of all the tiles using a special coordinate system for some reason in the board class the compiler does not seem to be recognizing tile as a type of object even though i have added import tileh at the top of the file heres the relevant code just ask if there is other parts of the code you want to seetilehimport foundationfoundationhimport cocos2dhimport boardhinterface tile nsobjectvoid updateneighborsproperty nonatomic retain ccsprite spriteproperty assign cgpoint coordsproperty assign cgpoint positioninpointsproperty nonatomic retain nsmutablearray neighborsendboardhimport foundationfoundationhimport cocos2dhimport tilehinterface board nsobjectboardsharedboard void puttile tile tile atindex cgpoint index error here void replacetileatindex cgpoint index1 withtileatindex cgpoint index2 tile tileatindex cgpoint index error here void populateproperty nonatomic retain nsmutablearray tilesproperty nonatomic retain nsstring typeproperty assign cgpoint sizeendthis code will not even build and i am getting the following error where indicatedexpected before tileif i change the type from tile to nsobject it fixes the error which leads me to believe that tile is not being recognized as a type of objecti have searched via google and this site and cannot figure out why this is happeningupdatedumb mistake easy to fix as you all have pointed out the problem is that the two header files are importing each other which is not allowed for now i have fixed the problem by moving the import boardh statement to tilem since it is not needed in the header file later on if i decide to use board in the tileh file i will use forward referencing class board as a few of you suggestedthanks again,['objective-c'] +208286,debugger stops when there is no breakpoint vs2010 i recently changed one of the options in the debugger and i think that is what is causing this problem but i cannot seem to undo iti google and all hits come back with the opposite why does the debugger not stop on a breakpointanyway can someone shed some lightedit when i press f5 in debug mode everytime it goes into the programcs and stops on applicationsetcompatibletextrenderingdefaultfalsein the main,"['c#', '.net']" +208293,adding to a vector of pair i have a vector of pair like suchvectorpairstringdouble revenuei want to add a string and a double from a map like thisrevenueifirst stringrevenueisecond mapisecondbut since revenue is not initialized it comes up with an out of bounds error so i tried using vectorpush back like thisrevenuepush backstringmapisecondbut that says cannot take two arguments so how can i add to this vector of pair,['c++'] +208314,is it possible to configure paperclip to produce https urls i am using paperclip to manage useruploaded images on a site that is served entirely under https in order to avoid the silly security warnings on ie7ie8 i need to also serve these images over ssl i typically render my images using something like the following image tag productimageurllarge whereclass product activerecordbase has attached file image styles large geometry 616x450 storage s3 s3 credentials access key id x secret access key x path attachmentidstylebasenameextension bucket configs3 media bucket default url assetsimage missingpngand the image url produced is something likeis there a magic paperclip option to change this to,['ruby-on-rails'] +208317,jquery chosen reset i have a bunch of select elements in a form with which i am using the jquery chosen plugin how can i reset the form the following does not workinput typereset,['jquery'] +208332,using regex to balance match parenthesis i am trying to create a net regex expression that will properly balance out my parenthesis i have the following regex expressionfuncazaz azaz09 the string i am trying to match is thistest funcpow32 91what should happen is regex should match everything from funcpow until the second closing parenthesis it should stop after the second closing parenthesis instead it is matching all the way to the very last closing parenthesis regex is returning thisfuncpow32 91it should return thisfuncpow32any help on this would be appreciated,"['c#', '.net']" +208361,is there a naming convention for mysql heres how i do ittable names are lower case uses underscores to separate words and are singular eg foo foo bar etci generally not always have a auto increment pk i use the following convention tablename id eg foo id foo bar id etcwhen a table contains a column that is a foreign key i just copy the column name of that key from whatever table it came from for example say table foo bar has the fk foo id where foo id is the pk of foowhen defining fks to enforce referencial integrity i use the following tablename fk columnname eg furthering example 3 it would be foo bar foo id since this is a table namecolumn name combination it is guaranteed to be unique within the databasei order the columns like this pks fks then the rest of columns alphabeticallyis there a better more standard way to do this,['mysql'] +208373,is the use of storyboards in xcode 42 production ready and recommended cf previous xib methods is the use of storyboards in xcode 42 production ready and recommended that is would iphoneipad developers that have used storyboards recommend for native iphoneipad apps to definitely use storyboards or are there some gotchas and issues still with the conceptps also do storyboards assist in getting a universal application designedworking,"['iphone', 'ios']" +208378,what is the use of basecolumns in android what is the use of implementing a class from basecolumns in android,"['java', 'android']" +208379,android ndk tutorialguide for beginners i am starting with the android ndk is there some nice placeebook for guiding methanks,"['java', 'android']" +208385,how much space do string constants occupy in a compiled dll i am trying to work out what is affecting the compiled size of my silverlight application assembly clearly i want to reduce the size of my application and the most obvious way of doing that is to get rid of some of my constant strings eg error strings there are no images in the application or other resource intensive entities i will subsequently pull strings from the server on demand before i undergo this work i want to work out what the approximate space savings would be how much memory does a compiled constant take up in the compiled dll i am assuming it is is stored as a unicode utf16 array of characters and so will be 2bytes per character is this correct is there a rule of thumb or more rigorous rule for calculating how much compression can be made on a string for the zip compression that is used to create the final xap fileedit there is clearly some confusion being caused by the way i have asked this question i am not talking about the memory footprint as the amount of memory consumed by the application but the size of the dll and consequently the xap file that is created,['c#'] +208395,how to hide some phing targets from xml i have about 25 phing targets when i list them in the consolebut 5 of them are just needed by other targets and i will never trigger them aloneis there a possibility to hide themfor example there are the targets cmscc config content ccservicethe all pop up in my list but cctarget is the only one i will triggerthank you,['php'] +208397,why would i use javalangclasscast possible duplicatewhen should i use the java 5 method cast of class i recently stumbled upon a piece of code that went like thisobject o foo foo fooclasscastoi was actually not even aware that javalangclass had a cast method so i looked into the docs and from what i gather this does simply do a cast to the class that the class object represents so the code above would be roughly equivalent to object o foo foo foso i wondered why i would want to use the cast method instead of simply doing a cast the old way has anyone a good example where the usage of the cast method is beneficial over doing the simple cast,['java'] +208399,difference between these two nsstring methods so i just got asked this at an interview today and after some googling am still unable to figure out the answer in fact i could not even find any code at all which used the nsstring string methodwhat is the difference betweennsstring somestring nsstring stringnsstring somestring nsstring alloc initnow my initial thoughts were that nsstring string would return an object which would be autoreleased whereas using alloc and init would return an object which has been retained however it seems that this answer was incorrecti have looked at the nsstring class reference in the apple docs but all it says is returns an empty string idstring return valuean empty stringcould somebody explain to me exactly what the difference between these two are,"['iphone', 'objective-c', 'ios']" +208401,is accessing c member class through thismember fasterslower than implicit call to member after some searching on our friend google i could not get a clear view on the following pointi am used to call class members with this even if not needed i find it more explicit as it helps when maintaining some heavy piece of algorithm with loads of varsas i am working on a supposedtobeoptimised algorithm i was wondering whether using this would alter runtime performance or notdoes it,['c++'] +208413,viewpager in a listview how to lock the scrolling axis i have a viewpager widget in every row of a listview this provides a shelflike ui so the user can scroll around searching for a shelf vertically and then scroll horizontally amongst the contents of a shelf this worksbut the scrolling experience is terrible if i start to drag a shelfs viewpager scroll it horizontally and accidentally drag a bit upwardsdownwards then the listview traps this dragging action and start to scroll vertically ending my horizontal drag in this state the drag action would not return to the viewpager the listview has it and that is it i have to start another drag action to affect the viewpager again so i guess the listview has precedence in these caseshow can this be fixed i would like to achieve the exact opposite if the viewpager inside a list row starts reacting to a horizontal drag then it should trap that action and this drag should stop affecting the listview no matter how the user moves hisher finger vertically can this be done,['android'] +208415,readline errors prevent me running rails console my environment is rails 31 ruby 192 rvm xubuntu 10when i try to run the rails console within an app i am getting require errors pointing at readlineso i am trying to install readline as a package within rvm but this is the error i am gettingapplying patch homerobrvmpatchesreadline62patchshobjconfdifferror error running patch p0 f homerobrvmpatchesreadline62patchshobj confdiff please read homerobrvmlogreadlinepatchlogerror patch homerobrvmpatchesreadline62patchshobjconfdiff did not apply cleanly back to the patching board the log contains201026 101630 patch p0 f homerobrvmpatchesreadline62patchshobjconfdiffpatching file supportshobjconfhunk 1 failed at 1571 out of 2 hunks failed saving rejects to file supportshobjconfreji have tried rvm pkg install readline rvm remove 192 rvm install 192 withreadlinedirrvm pathusrand cd homervmsrcruby192p0extreadline ruby extconfrb make installthe latter gives mechecking for tgetnum in lncurses yeschecking for readlinereadlineh yeschecking for readlinehistoryh yeschecking for readline in lreadline nochecking for readline in ledit nochecking for editlinereadlineh norunning rails server works so i think the problem is just with readlinecan anyone point me in the right direction,['ruby-on-rails'] +208417,can i set accessibility identifier in interface builder xcode42 i can only set accessibility label in interface builder but in ui automationi need accessibility identifier to get the ui elementsany way to do this,['ios'] +208423,nodejs memory consumption in an infinite loop i do not know if this is a bug with node or v8 but if i run the following code the node process leaks memory the gc never seems to kick in and in a few seconds it is consuming 1gb of memory this is unexpected behavior am i missing somethingheres the codefor consolelog11 obviously this is a little bit of a contrived situation but i can see an issue with a longrunning process that would never free memoryedit i tried both with v0510 unstable and v0412 stable and the unstable version performs a little bit betterthe stable version just stops outputting to the console but continues to consume memory whereas the stable version continues executing and consuming memory without pause,['javascript'] +208426,how to force line break in firefox contenteditable i have a javascript wysiwyg editor not unlike ckeditor running on a site it has a setting that makes ie create br line breaks when you press enter in the editorthat works great but unfortunately firefox i have tested with 5 and 7 will still generate p elements and generate br s only if you use shift enter is there a way to make firefox always generate br elements in a contenteditable,['html'] +208427,delete last char of string i am retrieving a lot of informations in a list linked to a database i want to create a string of groups for someone who is connected to the websitei use this to test but this is not dynamic so really bad string strgroupids 6i want to use this now but the string returned is something like 12345 groupidsforeachg strgroupids strgroupids gtostring strgroupidstrimend strgroupidstrimendnew char i want to delete the after the 5 but it is definitely not working can someone help methank you very much,['c#'] +208431,c error attempted to read or write protected memory or external component has thrown an exception i have a c program target framework net 40 which makes calls to com objects unmanaged code all objects managed properly destroyed when no longer required etci have also few exceptions handler trycatch blocks without custom exceptions however some times this program crashed works most of the times random behaviour stack traces also vary example systemaccessviolationexception was unhandled messageattempted to read or write protected memory this is often an indication that other memory is corrupt sourcesystemwindowsforms stacktrace at systemwindowsformsunsafenativemethodsthispatchmessagewmsg msg at systemwindowsformsapplicationcomponentmanagersystemwindowsformsunsafenativemethodsimsocomponentmanagerfpushmessageloopintptr dwcomponentid int32 reason int32 pvloopdata at systemwindowsformsapplicationthreadcontextrunmessageloopinnerint32 reason applicationcontext context at systemwindowsformsapplicationthreadcontextrunmessageloopint32 reason applicationcontext context at systemwindowsformsapplicationrunform mainform at indexertesterprogrammain in dtesterprogramcsline 17 innerexceptionin programcs line 17 applicationrunnew form1systemruntimeinteropservicessehexception was unhandled messageexternal component has thrown an exception sourcesystemwindowsforms errorcode2147467259 stacktrace at systemwindowsformsunsafenativemethodsthispatchmessagewmsg msg at systemwindowsformsapplicationcomponentmanagersystemwindowsformsunsafenativemethodsimsocomponentmanagerfpushmessageloopintptr dwcomponentid int32 reason int32 pvloopdata at systemwindowsformsapplicationthreadcontextrunmessageloopinnerint32 reason applicationcontext context at systemwindowsformsapplicationthreadcontextrunmessageloopint32 reason applicationcontext context at systemwindowsformsapplicationrunform mainform at indexertesterprogrammain in dtesterprogramcsline 17 at systemappdomain nexecuteassemblyruntimeassembly assembly string args at systemappdomainexecuteassemblystring assemblyfile evidence assemblysecurity string args at microsoftvisualstudiohostingprocesshostprocrunusersassembly at systemthreadingthreadhelperthreadstart contextobject state at systemthreadingexecutioncontextrunexecutioncontext executioncontext contextcallback callback object state boolean ignoresyncctx at systemthreadingexecutioncontextrunexecutioncontext executioncontext contextcallback callback object state at systemthreadingthreadhelperthreadstart innerexceptioni am in isolation stage to find out root of this error do you have any suggestions of this errorany suggestions about catch these exceptions and exit gracefullythanks for your help,['c#'] +208434,watch console output panel in visual studio while running a xna game i am a visual studio newbie currently developing a game using vs 2010 express c and xna 40 i am trying to debug a little game i am developing using a consolewriteline call when a certain event occur unfortunately when i execute the program the visual studio layout changes and the output panel thisappear until the program exits so i can analyze the output only after the program endsi would like to know if it possible and how to keep the output panel visible,['c#'] +208438,how can i get the title of a webpage given the url an external url using jqueryjs i am a newbie so excuse me if this is a silly question so what i was trying is to get the title of a url using jqueryjs i dont want to load the content of the url and then parse tags in itlet me be more clear i have a set of urls say 20 for which i want to thisplay the titles the urls i am referring to are not the current urls so i cant use js documenttitle so i want to do something of the form somefunctitleurl and get its title is there any such function,"['javascript', 'jquery']" +208466,creating a full screen iframe i am currently looking into xss attacks with the aim of using them in client demonstrations i am a pen tester i have written a tool that will host a malicious version of a websites login page that harvests usernames and passwords and then redirects the victim back to the original website however i have been trying to get it to work using iframes instead as it would look far more convincing as the url would not changei have googled about and this seems to be the appropriate codeiframe src styleborder 0 width 100 height 100but the iframe created is by no means full screen on internet explorer and firefox here is a screenshot as you can see the iframe login page is beneath the what is your name area thus no where near full screen i have tried editing the css file of the malicious login page to include full screen parameters but this has no effect eitherdoes anyone have any solutions thanks,['html'] +208469,add padding to a uitextview as the title says i am trying to add paddinglike behavior to a uitextview the textview is generated when the view is pushed inside my navigation controller and the following code occurs selftextviewlayercornerradius 7 pretty stuff is pretty nsstring description appdelegateproductinthisplaydescription selftextview settextdescription pretty stuff has content now cgrect frame textviewframe framesizeheight textviewcontentsizeheight textviewframe frame set the uitextview to the size of it is containing text selftextvieweditable no selfthescrollviewcontentsize cgsizemake320 250 textviewframesizeheight set the parent scrollviews height to fit some other elements with fixed size 250 and the prementioned uitextviewso it all works and it is ok but i want to add some padding on all 4 sides of the uitextview and i have been unable to do this with 3 hours of googling for something that seems rather easy any suggestions,['ios'] +208472,can uilocalnotification fire a custom method when app is in background mode well the title is self explained i want to create an app that can manage programmed local notifications when app is in background mode notifications works smoothly but i want to fire a custom method when the alert is firedis it possiblethank you,"['iphone', 'objective-c']" +208490,are there any guidelines for writing net apis using the new asyncawait features i am currently designing some internal apis where i use the async ctp and its new awaitasync keywords are there any guidelines or best practices on how these apis should be designed specificallyshould i provide both a synchronous and an asynchronous version of methods ie task dostuffasync and void dostuffshould all async methods i expose be in the form async taskt getstuffasync ie method name end with async or is it ok to to have something named getstuff be awaitablei do understand that it is not all black or white here and that it depends on the method in question but i am looking for general guidelines,"['c#', '.net']" +208494,facebook apps iframes and third party cookies i have a rails app that runs inside of fabebook as an iframe i use koala gem for fb communication also the js sdk for some parts and devise as authentication basefor some time i have been seen some problems with the issue that the app runs inside an iframe so third party cookies cannot be set for ie i use a p3p header which as mitigated the problem somehow but the whole thing is very confusing i am on snow leopardfor examplewith safari 511 i have set block cookies from third parties and advertisersthe application works ok and it can be used with no problemswith chrome 50874 very recent update the option block thirdparty cookies from being set was checked so the two main cookies that my app sets app cookie and fbs x cookie cannot be set so the app does not work since the user needs to authenticate all the timewith opera 1152 there is no reference to third party cookies and the browser is set to accept cookies only from the sites i visit my app works ok with that settingwith firefox 701 my app works but i just could not find any setting that deal with cookies just to delete themso apparently my problem is with chrome but the same setting works with safari so i am really confusedis asking the user to allow third party cookies the only solution to this problemthanksupdate on my current working solutioni did some extra research and tests i did try to use rails alternative methods of session storage by default they are stored in a cookie but you can store session data in memory db etc but it is not enough because it still uses a cookie with a pointer to the alternative storage you selectin the end i set some info the the url that allows me find the identity of the current logged in user get the user and manually sign in that user with devises sign in method i do not like it too much but now i can block third party cookies and still works i will later on make a change and instead of having the real info there i will have a key to a memcached entry from where i will get the user previously set after all only my app should have access to that memcached serverthanks,['ruby-on-rails'] +208512,jquery modify html string could someone tell me how i can modify the html before i insert it into the documentthis is an ajax callurl httplocalhostcartpublicadminalbumsuccess functionhtml this is the result of the ajax calldiv classmaincontent slidein h1create albumh1 div classinner divdivall i want to do is change the color of the h1 tag i have added this codeurl httplocalhostcartpublicadminalbumsuccess functionhtml htmlfindh1csscolorred asideafterhtmlhowever this has no effect the jquery selector does seem to be working thoughurl httplocalhostcartpublicadminalbumsuccess functionhtml htmlfindh1csscolorred consoleloghtmlfindh1length asideafterhtmlusing consolelog correct outputs 1 so it is finding the h1 for some reason though the css style is not being appliedi am bit stuck am i missing a step,"['jquery', 'html']" +208530,logging aspect oriented programming and dependency injection trying to make sense of it all i know that logging is a prime use case for aop additionally logging wrappers are also exemplified as cases when you want to use di so that classes are not coupled with a specific logging implementation however some consider logging wrappers an antipattern primarily such a view is because in most cases the wrapper tends to be simplistic and removes many of the features specific of the logging framework if you implement those specific features why not just use the framework directly i am aware of the commonlogging facade that attempts to abstract a good amount of the features of log4net entlib nlog for you however even here we still have a dependency of sorts on commonlogging not in a codeunit testing way regarding interfaces and such but if the project dies it is been over a year since the last release or you want to latter switch to a logger not supported that can cause problemsthat said if logging is achieved via aop is it even necessary to use di for the logging dependency ie why not just directly reference say nlog yes that aop portion of code would be tightly coupled but the logic of the classes that one wants to unit test is devoid of logging dependencies at least before the weaving happens it is at this point that i am a bit lost i have not tried aop yet after weaving would having not used di for the aop code cause problems for unit testing the method under test or can one unit test without weaving the aop code unless logging is a requirement of the user of the software i am not sure how useful it is to test that logging has occured with mocks i would think that the business logic of the method under test is what most would be interested in testing lastly if one wants to use tddbdd wouldnt one have to use di for the logging dependencies in the aop code or would one just not test drive the aop side of things as you can see i am trying to get a feel for what the most practical approach is for developing an application that would be using both aop for crosscuttingconcerns and di for designtesting since aop is relatively new and logging is the most common example what is the recommended approach,['.net'] +208541,testing equivalence of xmletrelementtree i am interested in equivalence of two xml elements and i have found that testing the tostring of the elements works however that seems hacky is there a better way to test equivalence of two etree elements exampleimport xmletrelementtree as etreeh1 etrelementhatcolorredh2 etrelementhatcolorredh1 h2falseetreetostringh1 etreetostringh2true,['python'] +208555,matrix multiplication small difference in matrix size large difference in timings i have a matrix multiply code that looks like thisfori 0 i dimension i forj 0 j dimension j fork 0 k dimension k cdimensionij adimensionik bdimensionkjhere the size of the matrix is represented by dimensionnow if the size of the matrices is 20 it takes 147 seconds to run this piece of code whereas if the size of the matrices is 2048 it takes 447 seconds so while the difference in no of multiplications is 204820482048202020 1073 the difference in the timings is 447147 3 can someone explain why this happens i expected it to scale linearly which does not happen i am not trying to make the fastest matrix multiply code simply trying to understand why it happens specs amd opteron dual core node 22ghz 2g ram gcc v 450program compiled as gcc o3 simpleci have run this on intels icc compiler as well and seen similar resultseditas suggested in the commentsanswers i ran the code with dimension2060 and it takes 145 secondsheres the complete programinclude stdlibhinclude stdiohinclude systimeh change dimension size as needed const int dimension 2048struct timeval tv double timestamp double t gettimeofdaytv null t tvtv sec tvtv usec10 return tint mainint argc char argv int i j k double a b c start end a doublemallocdimensiondimensionsizeofdouble b doublemallocdimensiondimensionsizeofdouble c doublemallocdimensiondimensionsizeofdouble srand292 fori 0 i dimension i forj 0 j dimension j adimensionij randrand max 10 bdimensionij randrand max 10 cdimensionij 00 start timestamp fori 0 i dimension i forj 0 j dimension j fork 0 k dimension k cdimensionij adimensionik bdimensionkj end timestamp printfnsecsfn endstart freea freeb freec return 0,['c'] +208605,stdatomic decrement and comparison on the following codestdatomicint myint shared variableif myint 0 code block bis it possible that more than one thread access the block i named code block bplease consider that overflow will not happen that the if is being executed concurrently by more than one thread that the only modification to myint in the whole program is the myint inside the if and that myint is initialized with a positive value,['c++'] +208612,why the font size would not change with browser zoom in in most of websites while i change the zoom level of browsers the font size will also increase and help user to see them for some reasons that just would not work on my new website while i change the zoom level of the browser everything changes but all font size keep the same is there a css or html property that i can use to control this behavior thankshere is an example,"['html', 'css']" +208616,finishing current activity from a fragment i have a fragment in an activity that i am using as a navigation drawer it contains buttons that when clicked start new activities startactivity from a fragment simply calls startactivity on the current activityfor the life of me i cannot seem to figure out how i would finish the current activity after starting a new onei am looking to achieve something like this in the fragmentoverridepublic void onclickview view todo autogenerated method stub if view mbuttonshows intent intent new intentviewgetcontext mynewactivityclass intentaddflagsintentflag activity clear top startactivityintent finish but it seems fragmentclass does not implement finish like it implements startactivityi would like the activity backstack cleared when they launch the 2nd activity so pressing back from the new activity would technically drop them back to the launcher,['android'] +208635,programmatically adding controls to tablelayoutpanel behaves differently based on originating thread i am creating a winform project that thisplays messages from a server and a client client messages are added via standard ui events like click and keypress server messages are added via a background thread that is listening for messages and alerts the ui when they arrive the alert happens through an eventhandler that then makes use of the invoke method since we are requesting to modify the ui from a thread that did not create itwhen messages are added from the client they appear as desired ie correctly sized wrapping and resizing performs correctly when messages are added from the background thread via invoke only the first message thisplays correctly and even then only initially once the form is resized the wrapping stops working and the first message is clipped based on how much space is available messages after the first get sized completely incorrectly in that it appears that their height gets set to 1 pixel or something very small so that only the tops of the characters from the first line can be seen since i am new to winforms i am suspicious that i am doing something wrong as far as the correct way to programmatically add controls to the uiboth the client and the background thread call the same method to add the controls to the form only the background calls it via invoke i am at a loss as to why the added controls behave differently based on the event they originated from because either way they are being added the exact same way my only thought is that i am missing something obvious because i am new to winformsanyway enough of the explanation here is the relevant codeprivate void addmessagestring message tablelayoutpanel1suspendlayout richtextbox rtb new richtextbox rtbappendtextmessage rtbmultiline true rtbwordwrap true rtbdock dockstyletop rtbreadonly true rtbborderstyle borderstylenone rtbscrollbars richtextboxscrollbarsnone rtbbackcolor colorlightblue rtbfont new fonttahoma 8 fontstyleitalic rtbresize rtb resize rtbminimumsize new size150 15 rtbmargin new padding1 0 0 5 rtbpadding new padding3 3 3 3 rtbheight rtbgetpositionfromcharindexrtbtextlengthy tablelayoutpanel1rowstylesaddnew rowstylesizetypeautosize tablelayoutpanel1rowcount tablelayoutpanel1rowstylescount tablelayoutpanel1controlsaddrtb tablelayoutpanel1setcolumnspanrtb 2 tablelayoutpanel1resumelayouttrue tablelayoutpanel1autoscrollposition new point0 tablelayoutpanel1verticalscrollmaximumprivate void richtextbox1 keypressobject sender keypresseventargs e if ekeychar 13 stringisnulloremptyrichtextbox1text addmessagerichtextbox1text richtextbox1clear public void postmessageobject sender messageeventargs e begininvokenew addmsgaddmessage new object emessage public delegate void addmsgstring mprivate void rtb resizeobject sender eventargs e var rtb richtextbox sender rtbheight rtbgetpositionfromcharindexrtbtextlengthyok now some more explanation client messages originate from richtextbox1 keypress and server messages originate from postmessage postmessage is assigned to the eventhandler for the background thread when it gets a message both as you can see call addmessage which adds a richtextbox with the message to the tablelayoutpanel the rtb resize method contains logic for a way i found online to get a ricktextbox to auto size since apparently it does not support this maybe this a possible source to my problemi will also provide the designer code below for the tablelayoutpanel since this seems to be helpful and relevant from other posts i have seen on here tablelayoutpanel1 thistablelayoutpanel1autoscroll truethistablelayoutpanel1autosize truethistablelayoutpanel1autosizemode systemwindowsformsautosizemodegrowandshrinkthistablelayoutpanel1backcolor systemdrawingcolorwhitethistablelayoutpanel1columncount 2thistablelayoutpanel1columnstylesaddnew systemwindowsformscolumnstylesystemwindowsformssizetypepercent 100fthistablelayoutpanel1columnstylesaddnew systemwindowsformscolumnstylesystemwindowsformssizetypeabsolute 50fthistablelayoutpanel1dock systemwindowsformsdockstylefillthistablelayoutpanel1location new systemdrawingpoint1 10thistablelayoutpanel1name tablelayoutpanel1thistablelayoutpanel1padding new systemwindowsformspadding5 5 12 5thistablelayoutpanel1rowcount 1thistablelayoutpanel1rowstylesaddnew systemwindowsformsrowstylethistablelayoutpanel1size new systemdrawingsize272 276thistablelayoutpanel1tabindex 0the tablelayoutpanel does contain an initial row since the designer does not allow you to have one with no rows but i clear all the rows out in the forms constructor after the standard call to initializecomponenthopefully i have provided enough here to give people the information they need but please let me know if you have any questions or need to see other parts of the code and i will provide them as quickly as possible also if it matters i am using visual studio 2008 and net 35thank you,"['c#', '.net']" +208647,generating random numbers under very specific constraints i am faced with the following programming problem i need to generate n a b tuples for which the sum of all as is a given a and sum of all bs is a given b and for each tuple the ratio of a b is in the range c min c max a b is within the same range too i am also trying to make sure there is no bias in the result other than what is introduced by the constraints and the a b values are moreorless uniformly thistributed in the given rangesome clarifications and metaconstraintsa b c min and c max are given the ratio a b is in the c min c max range this has to be so if the problem is to have a solution given the other constraintsa and b are 0 and nonintegeri am trying to implement this in python but ideas in any language english included are much appreciated,['python'] +208673,filter on parent object attribute in activeadmin i would like to be able to filter an object based on an attribute of it is parentclass call activerecordbase belongs to userendclass user activerecordbase has many callsendi would like to be able to do thisactiveadminregister call do filter userendand have it filter on username rather than present a select of all users can this be done,['ruby-on-rails'] +208699,ios cropping a cmsamplebufferref before appending to avassetwriterinput i am currently experimenting with coreimage learning how to apply cifilters to a camera feed presently i am succeeded in taking a camera feed applying a filter and writing the feed to an avassetwriter in the form of a video but one issue i am having with it is that during the filtering process i actually crop the image data so that it always has square dimensions needed for other aspects of the projectmy process is as followscapture feed using avcapturesessiontake the cmsamplebufferref from the capture output and acquire the cvpixelbufferrefget the base address of the cvpixelbufferref and create a cgbitmapcontext using the base address as its data so we can overwrite itconvert the cvpixelbufferref to ciimage using one of the ciimage constructorsapply the filters to the ciimageconvert the ciimage to cgimagerefdraw the cgimageref to the cgbitmapcontext resulting in the sample buffers content to be overwrittenappend the cmsamplebufferref to the avassetwriterinputwithout drawing the cgimageref to the context this is what i getafter drawing the cgimageref to the context this is what i getideally i just want to be able to tell the cmsamplebufferref that it has new dimensions so that the additional information is omitted but i am wondering if i will have to create a new cmsamplebufferref altogetherany help would be greatly appreciated,['ios'] +208710,implementing autocomplete with listview in android i was following this exampleand i want to know how i can implement this with a listview instead of the dropdown window that is supplied with this textviewfor instance as the user types into the textview there is a listview directly below the textview that will be constantly changing as the user types in the textview fieldedit here is the solution that i coded with thanks to josephuspackage comjayleflercontactsimport javautilarraylistimport androidappactivityimport androidosbundleimport androidtexteditableimport androidtexttextwatcherimport androidwidgetarrayadapterimport androidwidgetedittextimport androidwidgetlistviewpublic class contactprojectactivity extends activity called when the activity is first created list of all contacts private arrayliststring searchnames new arrayliststring filtered list of contacts after user begins typing in search field private arrayliststring partialnames new arrayliststring list of names matching criteria are listed here private listview mylist field where user enters his search criteria private edittext namecapture adapter for mylist private arrayadapterstring adapter override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain set list adapter mylist listview findviewbyidridnames adapter new arrayadapterstringthis androidrlayoutsimple list item 1 partialnames mylistsetadapteradapter searchnamesaddtom arnold searchnamesaddzeb arnold searchnamesadan bateman searchnamesaddtommy canders searchnamesaddelijah arnman searchnamesaddtomas muster searchnamesaddstefan edberg searchnamesaddivan lendl namecapture edittext findviewbyidridname namecapturesettexttom alteradapter namecaptureaddtextchangedlistenernew textwatcher as the user types in the search field the list is override public void ontextchangedcharsequence arg0 int arg1 int arg2 int arg3 alteradapter not used for this program override public void aftertextchangededitable arg0 not uses for this program override public void beforetextchangedcharsequence arg0 int arg1 int arg2 int arg3 todo autogenerated method stub filters list of contacts based on user search criteria if no information is filled in contact list will be blank private void alteradapter if namecapturegettexttostringisempty partialnamesclear adapternotifydatasetchanged else partialnamesclear for int i 0 i searchnamessize i if searchnamesgetitostringtouppercasecontainsnamecapturegettexttostringtouppercase partialnamesaddsearchnamesgetitostring adapternotifydatasetchanged,"['java', 'android']" +208712,android startactivityforresult immediately triggering onactivityresult i am launching activities from the main activity in my app using the call startactivityforresultintent activity type and they are all working but one this one when called launches the activity as desired but in the log i can see that onactivityresult is immediately being triggered the activity shows up but result canceled is immediately returned to onactivityresult i then interact with the activity press a button which calls finish and onactivityresult is not called the time because apparently a result has already been returneddoes this make sense to anyone has anyone seen this behavior before,['android'] +208736,seeing too many lsof cannot identify protocol i have a java processapp when i run usrsbinlsof p on that java process i see a lot of cannot identify protocol also interestingly file descriptorsfds are increasing at a very steady rate and those fds that are being created are having description as cannot identify protocolso is there any way to instrumentprofile the java process so as to nail down who is creating that many fds any detailed explanation on any tool would be really really helpfula quick google search tells me strace is one way but iiuc that will show linux system calls coming out of the java process i am more interested in which part of my java code is behaving badly than what system calls are being generatedagain any ideassuggestions would be simply great,['java'] +208762,removeobjectatindex causes message sent to deallocated instance i am converting some code to arc the code searches for an element in an nsmutablearray then finds removes and returns that element the problem is that the element gets deallocated immediately upon removeobjectatindex uiview viewwithtaginttag uiview view nil for int i 0 i self count i uiview aview self objectatindexi if aviewtag tag view aview nslogview 1 view is good self removeobjectatindexi break nslogview 2 view has been deallocated return viewwhen i run it i get uiview respondstoselector message sent to deallocated instance 0x87882f0at the second log statementprearc i was careful to retain the object before calling removeobjectatindex and then to autorelease it how do i tell arc to do the same thing,"['objective-c', 'ios']" +208766,list interface from java to c i am a java programmer learning c these daysusually in java when using lists it should be preferrable programming against its interface in order to switch between implementationslistobject list new arraylistobjectorlist new linkedlistobject what about c does exist a similar approach can someone show me an example since now i am building a list this way but i do not think list is an interfacelistint list new listintlistadd2,"['c#', 'java']" +208768,can i pass constant pointers thisguised as arrays void fooconst char sis equivalent tovoid fooconst char sare there similar equivalents to the following twovoid foochar const svoid fooconst char const s,"['c++', 'c']" +208769,how do i change a value while debugging python with pdb i want to run pdb step through the code and at some point change the value pointed at by some name so i might want to change the value pointed at by the name stationlat but it seems i cannot heres the example import extractpercentiles import pdb pdbrun extractpercentilesextractonestation string1modulenonepdb scall scratchextractpercentilespy96extractonestation def extractonestation pdb tbreak 132breakpoint 3 at scratchextractpercentilespy132pdb cdeleted breakpoint 3 scratchextractpercentilespy132extractonestation stationlon floatstationloc3so now i am at a place where i would like to change the value of stationlat pdb appears to allow me to set stationlat to a new value but when i inspect the value it is unchangedpdb stationlat34171103pdb stationlat 40pdb stationlat 34171103pdb stationlat 40pdb stationlat34171103pdb you can see i tried using as well without successthe pdb manual says i should be able to change variablescommands that the debugger doesnat recognize are assumed to be python statements and are executed in the context of the program being debugged python statements can also be prefixed with an exclamation point this is a powerful way to inspect the program being debugged it is even possible to change a variable or call a functionis this a question of scope is it to do with the way i have started pdb i tried the embedded pdbset trace idiom and i got the same result thanks for reading,['python'] +208780,cannot install python module pycrypto on debian lenny i tried to install pycrypto module by downloading the source code and executing the following command python setuppy install then an error came running installrunning buildrunning build pyrunning build extwarning gmp library not found not building cryptopublickey fastmathbuilding cryptohashmd2 extensiongcc pthread fnostrictaliasing fwrapv wall wstrictprototypes fpic stdc99 o3 fomitframepointer isrc iusrincludepython25 c srcmd2c o buildtemplinuxx86 6425srcmd2osrcmd2c3120 error pythonh no such file or directorysrcmd2c118 error expected asm or attribute before tokenin file included from srcmd2c134srchash templatec42 error expected specifierqualifierlist before pyobject headsrchash templatec46 error expected asm or attribute before pytypeobjectsrchash templatec in function newalgobjectsrchash templatec55 warning implicit declaration of function pyobject newsrchash templatec55 error expected expression before algobjectsrchash templatec55 warning assignment makes pointer from integer without a castsrchash templatec at top levelsrchash templatec62 error expected before tokensrchash templatec77 error expected asm or attribute before tokensrchash templatec96 error expected asm or attribute before tokensrchash templatec108 error expected asm or attribute before tokensrchash templatec143 error expected asm or attribute before tokensrchash templatec160 error expected asm or attribute before alg methodssrchash templatec169 error expected asm or attribute before tokensrchash templatec178 error expected asm or attribute before algtypesrchash templatec203 error expected asm or attribute before tokensrchash templatec237 error array type has incomplete element typesrchash templatec238 error pycfunction undeclared here not in a functionsrchash templatec238 error expected before alg newsrchash templatec in function initmd2srchash templatec254 error pyobject undeclared first use in this functionsrchash templatec254 error each undeclared identifier is reported only oncesrchash templatec254 error for each function it appears insrchash templatec254 error m undeclared first use in this functionsrchash templatec256 error algtype undeclared first use in this functionsrchash templatec256 error pytype type undeclared first use in this functionsrchash templatec257 warning implicit declaration of function py initmodulesrchash templatec260 error o undeclared first use in this functionsrchash templatec260 warning implicit declaration of function pyint fromlongsrchash templatec260 warning implicit declaration of function pydict setitemstringsrchash templatec260 warning implicit declaration of function pymodule getdictsrchash templatec260 warning implicit declaration of function py decrefsrchash templatec263 warning implicit declaration of function pyerr occurredsrchash templatec264 warning implicit declaration of function py fatalerrorerror command gcc failed with exit status 1which means that he did not find the pythonh i searched online for this error and it seems that by installing the python header file the problem will be solved but my debian lenny came with anther erroraptget install python26devand error reading package lists donebuilding dependency treereading state information donee could not find package python26dev,['python'] +208782,ioexception when opening jfilechooser ok this one is really weird every first time my application opens a jfilechooser it throws a ioexception then some icons do not show properlyjavaioioexception at sunawtimagegifimagedecoderreadheadergifimagedecoderjava265 at sunawtimagegifimagedecoderproduceimagegifimagedecoderjava102 at sunawtimageinputstreamimagesourcedofetchinputstreamimagesourcejava246 at sunawtimageimagefetcherfetchloopimagefetcherjava172 at sunawtimageimagefetcherrunimagefetcherjava136now when i dig into the error it seems like on one icon when it tries to read the header it retrieve only the first 8 bytes which is not enough i have have checked the icons files and they all seem oki have tried to override the icon file with another one that loads properly before this error but same thinghere is my stack when breaking on this error daemon thread image fetcher 0 suspended exception ioexception gifimagedecoderreadheader line 265 local variables unavailable gifimagedecoderproduceimage line 102 local variables unavailable bytearrayimagesourceinputstreamimagesourcedofetch line 246 imagefetcherfetchloop line 172 imagefetcherrun line 136 local variables unavailablehere is my variable value when digging into gifimagedecoder instancesource bytearrayimagesource id272 awaitingfetch false consumers null decoder gifimagedecoder id271 decoders gifimagedecoder id271 imagedata id307 0 71 1 73 2 70 3 56 4 57 5 97 6 16 7 13 8 10 imagelength 9 imageoffset 0 normally this imagedata should be way bigger first 10 bytes is header but it only retrieve 8 bytes as you can see after this exception every other icon from jfilechooser does not load properlythis is a proper call to readheader source bytearrayimagesource id208 awaitingfetch false consumers null decoder gifimagedecoder id207 decoders gifimagedecoder id207 imagedata id223 099 100199 200299 300399 400499 500599 600699 700799 800899 900979 imagelength 980 imageoffset 0 the buffer is fully loaded with an icon right before the icon that throws an errorhere is an exemple of where it could crash it happens in several part of my code whenever i first load my system icons public class directorybrowser extends jfilechooserprivate string suffixaccepted nullpublic directorybrowserfile file string choosertitle string approveopenbtntext string suffixaccepted superfile thissuffixaccepted suffixaccepted initchoosertitle approveopenbtntextwhen it enters in superfile it goes there thread awteventqueue0 suspended objectwaitlong line not available native method mediatrackerwaitforidint long line 651 imageiconloadimageimage line 234 imageiconinitbyte line 215 swingutilities22createvalueuidefaults line 1105 uidefaultsgetfromhashtableobject line 185 uidefaultsgetobject line 130 multiuidefaultsgetobject line 44 multiuidefaultsuidefaultsgeticonobject line 411 uimanagergeticonobject line 613 ironfilechooseruibasicfilechooseruiinstalliconsjfilechooser line 233 ironfilechooseruibasicfilechooseruiinstalldefaultsjfilechooser line 219 ironfilechooseruibasicfilechooseruiinstalluijcomponent line 135 ironfilechooseruimetalfilechooseruiinstalluijcomponent line 139 directorybrowserjcomponentsetuicomponentui line 653 directorybrowserjfilechooserupdateui line 1757 directorybrowserjfilechoosersetupfilesystemview line 366 directorybrowserjfilechooserinitfile filesystemview line 332 directorybrowserjfilechooserinitfile line 315 directorybrowserinitfile string string string line 33 packtointegratepanelchoosepackpathtointegratefile line 522 packtointegratepanel1actionperformedactionevent line 104 jbuttonabstractbuttonfireactionperformedactionevent line 1849 abstractbuttonhandleractionperformedactionevent line 2169 defaultbuttonmodelfireactionperformedactionevent line 420 defaultbuttonmodelsetpressedboolean line 258 basicbuttonlistenermousereleasedmouseevent line 236 jbuttoncomponentprocessmouseeventmouseevent line 5517 jbuttonjcomponentprocessmouseeventmouseevent line 3135 jbuttoncomponentprocesseventawtevent line 5282 jbuttoncontainerprocesseventawtevent line 1966 jbuttoncomponentthispatcheventimplawtevent line 3984 jbuttoncontainerthispatcheventimplawtevent line 2024 jbuttoncomponentthispatcheventawtevent line 3819 lightweightthispatcherretargetmouseeventcomponent int mouseevent line 4212 lightweightthispatcherprocessmouseeventmouseevent line 3892 lightweightthispatcherthispatcheventawtevent line 3822 workbenchframecontainerthispatcheventimplawtevent line 2010 workbenchframewindowthispatcheventimplawtevent line 1791 workbenchframecomponentthispatcheventawtevent line 3819 eventqueuethispatcheventawtevent line 463 eventthispatchthreadpumponeeventforhierarchyint component line 242 eventthispatchthreadpumpeventsforhierarchyint conditional component line 163 eventthispatchthreadpumpeventsint conditional line 157 eventthispatchthreadpumpeventsconditional line 149 eventthispatchthreadrun line 110 then other thread mentioned above retrieves the icons cf 2nd stack of this post,['java'] +208791,binding redirect fails different publickeytoken i have an application that references this assembly in development environmentsnamemicrosoftdatasqlxml cultureneutral publickeytoken89845dcd8080cc91 version902420however live server contains old version of this librarynamemicrosoftdatasqlxml cultureneutral publickeytokenb77a5c561934e089 version3229170as you see publickeytoken is different i have added bindingredirect to appconfigruntime assemblybinding xmlnsurnschemasmicrosoftcomasmv1 dependentassembly assemblyidentity namemicrosoftdatasqlxml cultureneutral publickeytoken89845dcd8080cc91 bindingredirect oldversion902420 newversion3229170 dependentassembly assemblybindingruntimebut i still get the errorunhandled exception systemiofilenotfoundexception could not load file or ass embly microsoftdatasqlxml version3229170 cultureneutral publickeytoke n89845dcd8080cc91 or one of its dependencies the system cannot find the file specified file name microsoftdatasqlxml version3229170 cultureneutral publicke ytoken89845dcd8080cc91 systemiofilenotfoundexception could not load fi le or assembly microsoftdatasqlxml version902420 cultureneutral publi ckeytoken89845dcd8080cc91 or one of its dependencies the system cannot find t he file specified file name microsoftdatasqlxml version902420 cultureneutral publickey token89845dcd8080cc91is there any way to redirect to older version of library in that case,"['c#', '.net']" +208798,is iis performing an illegal character substitution if so how to stop it context aspnet mvc running in iis with a a utf8 encoded urlusing the standard project template and a testaction in homecontroller likepublic actionresult teststring id return contentid textplainthis works fine for most encoded utf8 routes such ashttpmydevserverhometeste4baace983bde5bc81with the expected result aoe12a14however using the routehttpmydevserverhometestee93bbthe url is not received correctlyaside ee93bb is encoded codepoint 0xe4fb basicmultilingualplane privateuse area but ultimately a valid unicode codepoint you can verify this manually or viastring value char 0xe4fbtostringstring encoded httputilityurlencodevalue ee93bbnow what happens next depends on the webserver on the visual studio development server aka cassini the correct id is received a string of length one containing codepoint 0xe4fbif however i do this in iis or iis express i get a different id specifically a codepoints 0xee 0x201c 0xbb you will immediately recognise the first and last as the start and end of our percentencoded string so what happened in the middlewellcodepoint 0x93 is a sourcecodepoint 0x201c is a sourceit looks to me very much like iis has performed some kind of quotetranslation when processing my url now maybe this might have uses in a few scenarios i do not know but it is certainly a bad thing when it happens in the middle of a encoded utf8 blocknote that httpcontextcurrentrequestraw also shows this translation has occurred so this does not look like an mvc bug note also darins comment highlighting that it works differently in the path vs query portion of the urlso twoparteris my analysis missing some important subtlety of unicode url processinghow do i fix it ie make it so that i receive the expected character,['asp.net'] +208821,best practices for mvc viewmodel binding using interfaces example i am new to aspnet mvc 30 and trying to build an application using the mvc viewmodel design i was wondering what the best practices are regrading controllers for viewmodels and have a few questions below this is my understanding so far which might be wrongwe create modelscreate viewmodels by making a new class and declairing attributes with the same name and type as the base model classes including id fields of the base models you want to update later and the classes are not linked in any waycreate a repository for each of the base models to find and save data ectcreate a controller action for each of the viewmodels which access the repositories of the base classes to retrieve values and put these values into the viewmodel then pass the viewmodel to the viewmodels viewcreate views from the viewmodels viewmodel viewsin the viewmodel controller update post method recieve the updated viewmodel object and convert it into base model objects maybe use automapper and next save the base model objects back using their repositories and apply binding like this tryupdateipersonperson tryupdateiplaceplace this looks wrong the aim is to put the values back into the base classes from the viewmodel apply binding save base models back using the repositories this doesnt appear to use the repositories instead of tryupdateipersonperson i would expect to see something like this personsaveiperson where person contains the values save is the repository and iperson contains the binding attributes to use for binding not sure if this is rightso far i have created viewmodels by making a new class and adding attributes from different base models using the same names at this point i have the following questionsq1 does each viewmodel have its own controller and access each of the base models repository classes to get its valuesq2 in the viewmodel should you include the id field of all of the base models that you are using attributes from considering that you might want to post an update back through the viewmodels controller to the base models repository needing the id valuesq3 how would you bind attributes using an interface for binding the model in the controller using the repository to savei have been unable to find a tutorial or resource that explains everything in a step by step example a complete answer would be the following example2x simple models 1x simple viewmodel 1x interface for binding 1x simple controller using an interface class for binding on update 1x repository iemodel1public class person int personid getset string firstname getset string lastname getset datetime dob getsetmodel2public class place int placeid getset string description getset string areatype getset string postcode getsetviewmodel containing attributes from modelspublc class viewmodel person attributes int personid getset string firstname getset string lastname getset place attributes int placeid getset string description getset string areatype getset other attributes string someotherattributeforthisplay getsetmodel1 interface for binding on modelpublic interface iperson string firstname getsetmodel2 interface for binding on modelpublic interface iplace string description getset string areatype getsetviewmodelcontroller what goes hererepository what goes here,['asp.net'] +208825,what is the difference between list and dictionary in c i have a strange doubt regarding list and dictionary in cin a list we add items to list by using the following methodusing systemcollectionsgenericclass program static void main listint list new listint listadd2 listadd3 listadd5 listadd7 in a dictionary we add items like this using systemusing systemcollectionsgenericclass program static void main dictionarystring int d new dictionarystring int daddcat 2 dadog 1 daddllama 0 daddiguana 1 i do not know exactly what is the difference but in a dictionary we add items like a keyvalue pair and in a list we just add items without specifying any key would anyone clarify this,"['c#', '.net']" +208830,xcode 4 warning expression result unuseda for nsurlconnection i am just trying to do my usual data transfert i define my nsmutableurlrequest then callnsurlconnection alloc initwithrequestrequest delegateselfthis used to be ok with xcode 3 but xcode 4 warns me about expression result unused on that linethe request does work but i would like to find a way to get rid of the warningi suppose i could store the connection in a variable but i do not really need it and i cannot see the point of setting it to nil the next line although this would remove the warningplease note i am not 100 sure if it is xcode 4 or the fact arc is enabledmany thanks for your help,"['iphone', 'objective-c', 'ios']" +208833,cursorloader not updating after data change i have created a small application trying to understand the functionality of the loadermanager and cursorloaderclassesi have implemented loadercallbackscursor on my fragmentactivityclass and everything works fine except the fact that when i update my data via contentresolverupdate or contentresolverinsertmethods onloadfinished is not called and as a result my data does not updatei have a custom contentprovider and i am wondering if the problem is in my contentprovider not notifying that the data changed or something else,['android'] +208834,convert value from string to generic type that is either guid or int i have got a generic method which converts an id from a string eg retrieved from the value of a hiddenfield on an aspnet form to a target type and does something with itprivate void mymethodtstring rawid actiont dosomethingwithid t id tconvertchangetyperawid typeoft dosomethingwithididt will be either guid or int32 and the above code falls over at runtime when it is guid saying that the cast from string to guid is invalid then i thought i might try to check the type and if guid instantiate a new guidvar id defaulttif id is guid id new guidrawidelse id tconvertchangetyperawid typeoftnow this gives an error at compile time that guid cannot be converted to type tnot too sure how to work around this any suggestions,"['c#', 'asp.net']" +208835,callback to delay i have an image that i fadein and fadeout and then remove after fadeout completes this is my codeimage fadein fadeoutfunction thisremove i want to add a delay after fadeout and remove the image only once delay has completed i have triedimage fadein fadeout delay10 function thisremove the problem is that delay doest not accept a callback function how can i remove the picture as a callback to delay,['jquery'] +208841,ajaxcontroltoolkit nobotstate is always invalidbadresponse i am trying to implement ajaxcontroltoolkit nobot but i always get false from isvalid method the state value is always invalidbadresponse am i missing something hereascx code buttons textboxes etcaspnobot idnobot1 runatserver cutoffmaximuminstances5 cutoffwindowseconds60 responseminimumdelayseconds2 code behind protected void button1 clickobject sender eventargs e ajaxcontroltoolkitnobotstate state if nobot1isvalidout state page page httpcontextcurrenthandler as page scriptmanagerregisterstartupscriptpage pagegettype err msg alert bot true else far more weird is this i enter data for login and click on asp button nobot state is invalidbadresponse and it fails but then i click on browsers refresh button it asks me to resend request i say ok and now state is valid why,"['c#', 'asp.net']" +208845,ios how to capture a particular portion of screen i want to capture a particular portion of iphone screen i used uigraphicsbeginimagecontextwithoptions but could not capture a portion of screen with thisplease help me,"['iphone', 'ios']" +208853,scala xml performance vs java xml i would appreciate if anyone could point me in the direction or inform me of some benchmarks which is comparing how scalas xml library does compared to the typical solution in javai am thinking on measurements of parsing and selecting xml elementsthanks in advanceregards stefan,['java'] +208885,merge wpf app with c and vbnet code i have an application written in c which needs some functionality from vbnet better said something valid in cil but not provided in cso i have an executable and a library fileproblemit has to be published in one file and may not be split to different assembliesbutit is a wpf application ilmerge will not work what could i dois it possible to generate performant il on the fly,"['c#', '.net']" +208892,making and receiving an http request in c i want to make my c application to be able to send an http request and receive the answer at runtimean explanation from the website i want to request from is herei do not have any experience with that before so i am a little confused about the json xml stuff i know i will need an xml parser or something like this to understand the request,"['c#', '.net']" +208908,how do i save cookies from a response to a curl request using php im using curl through php to fetch a url i am successfully able to download the page headers and all however the cookies returned by any page do not get saved to the specified file i have checked permissions etc and nothing seems out of the ordinary i am beginning to think something is off in my codeget cookie page echo curl downloadget cookie pagefunction curl downloadurl ch curl init curl setoptch curlopt url url curl setoptch curlopt nobody true curl setoptch curlopt cookiejar cookietxt http headers array host wgoogleca useragent mozilla50 windows nt 61 wow64 rv602 gecko20100101 firefox602 accept acceptlanguage enusenq05 acceptcharset iso88591utf8q07q07 connection keepalive curl setoptch curlopt header true curl setoptch curlopt httpheader http headers curl setoptch curlopt returntransfer true curl setoptch curlopt timeout 10 output curl execch curl closech return outputany help appreciated,['php'] +208911,how do i sort very large files i have some files that should be sorted according to id at the beginning of each linethe files are about 23 gb i tried to read all data into an arraylist and sort them but memory is not enough to keep them all it does not worklines look like0052304 04041 john teddy 0230022024 04041 george clan 013how can i sort the files,['java'] +208916,how to purge all tasks of a specific queue with celery in python how to purge all scheduled and running tasks of a specific que with celery in python the questions seems pretty straigtforward but to add i am not looking for the command line codei have the following line which defines the que and would like to purge that que to manage taskscelery routes socialreporttaskstwitter save queue twitter saveat 1 point in time i wanna purge all tasks in the que twitter save with python code maybe with a broadcast function i could not find the documentation about this is this possible,['python'] +208923,what legal code could trigger c4523 multiple destructors specified visual c warning according to msdn visual c can emit c4523 warning class multiple destructors specified how is such situation even possiblei tried the followingclass class class classintwhich yields a destructor must have a void parameter list error and c4523 warning and the followingclass class class classwhich yields member function already defined or declared error and the followingclass class int class classwhich yields a destructor cannot have a return type errorso how do i have c4523 warning and no error,['c++'] +208931,whats mysqls sql specific programming language name you have tsql on sql server plsql on oracle whats the programming language on mysql,"['mysql', 'sql']" +208935,fb url scheme official or not some dev blogs have published information about the fb url scheme for opening various views in the facebook iphone app no matter how much i have searched i have not found one word from any official facebook source about thissince the information is public anyways i am sure i am not the only one whod like to know whether using this url scheme is officially approved am i allowed to use it does it work correctly and if it is not approved will it be and whats the approximate schedule for thatthanks in advance for any info on this subject,['ios'] +208977,jquery mobile css3 page transitions without jquery mobile library i have a mobile app created using htmljsjquerycss and i am looking to include page transitions that mimic those found in jquery mobile in specific the flip transition without the need to include the whole jquery mobile frameworkthese animations appear to be css3 transitions tied to jquery triggers but i have no idea where to start does anyone have any ideasany help would be greatly appreciated,['jquery'] +208982,how to generate large random numbers c i am looking for a way to generate large random numbers on the order of 264 in c 10 9 to use in a public key encryption algorithm as p and qi do not want to generate a number smaller than 264 that is smaller than 10is there anything that could help me to do this,['c'] +208999,why are not class template constructor arguments automatically determined consider the following classtemplatetypename t1 typename t2class pair public t1 first t2 second pairconst t1 first const t2 second firstfirst secondsecond the following is not allowed in cauto p pair10 10why is not that allowed the types can be completely determined from the constructor calli know there are workaround for that liketemplatetypename t1 typename t2pairt1 t2 makepairconst t1 first const t2 second return pairt1 t2first secondbut why is that needed why does not the compiler just determine the type from the arguments just like it does from function template you might say its because the standard does not allow it so why does not the standard allow iteditfor those who say this is an example why this should not be allowedtemplatetypename t1 typename t2class pair public t1 first t2 second pairconst t1 first const t2 second firstfirst secondsecond pairconst t2 second const t1 first firstfirst secondsecond auto p pair1010i can do exactly this with function templates overloadingtemplatetypename t1 typename t2pairt1 t2 makepairconst t1 first const t2 second return pairt1 t2first secondtemplatetypename t1 typename t2pairt1 t2 makepairconst t2 second const t1 first return pairt1 t2first secondwhy is this allowed for functions but not for classes,['c++'] +209014,same fb app multiple ios bundle ids with different suffixes i have two versions of my iphone app one is for the appstore and the other an adhoc version for internal testing they have same fb app id for both they both communicate with same backend two different bundle ids so they can both be installed on device different url suffixes empty and adhocthey both worked properly with login but when i changed the ios bundle id on the app page on fb admin tool it obviously stopped working i got fb app id suffixauthorizeerrorunknown5ferror as the url before it called to fbdidnotlogin on the test appif i do not put the ios bundle id it works do i have any option to still protect the bundle id and have the other app working,['ios'] +209026,audiosessionsetactive fails after interruption i was trying to figure out what actually happens for weeks and i have no idea why i cannot continue playback after interruption so probably you guys know an answer audiosessionsetactivetrue always returns cat which is kaudiosessionincompatiblecategory while reactivation if my app plays in background and i am in different app although it works fine and continues playback if i caught interruption while being in my app original code actually has all audiosession and audioqueue calls wrapped in macros which prints osstatus if it means error but i removed it for better readability also self pause just toggles pause so basically it calls audioqueuestartaudioqueue null on upause but it does not work ofcourse if audiosession failsaudio session initialization codeaudiosessioninitializenull null audiosessioninterruptionlistener selfuint32 sessioncategory kaudiosessioncategory mediaplaybackaudiosessionsetpropertykaudiosessionproperty audiocategory sizeofsessioncategory sessioncategoryaudiosessionaddpropertylistenerkaudiosessionproperty audioroutechange audiosessionpropertylistener selfaudiosessionsetactivetrueinterruption handler code voidhandleinterruptionchangetostateaudioqueuepropertyidininterruptionstate ifininterruptionstate kaudiosessionbegininterruption nsloginterruption ifselfstate nx state play self pause audiosessionsetactivefalse ispausedbyinterruption yes else ifininterruptionstate kaudiosessionendinterruption ifispausedbyinterruption audiosessionsetactivetrue self pause ispausedbyinterruption false nsloginterruption this streamer source code can be found here if it is gonna help somehow to resolve an issue,"['iphone', 'objective-c']" +209028,private cookie for only my app why is it influencing the browsers cookie when i log into my app my browsers cookie for the same site is lost why is this cookie being shared between apps loggingin in chrome does not affect safaris cookies how can i emulate that behavior in my app store appi am logging into a websites api and setting a cookie via nshttpcookiestorage setcookieusing the docs i see two ways to get the cookie storage locationa initwithstoragelocation deprecated available in mac os x v106 through mac os x v106and sharedhttpcookiestorageit seems like the first one is similar to what i want using a unique storage loaction that is only usable by my app but that method is deprecated in lion how then do you use a private myapponly cookie,['objective-c'] +209037,google webpage thumbnails absolute uri how can i get a list of either the absolute uris or base64 encodings for page urls in googles search resultsgoaliterate through url arraypagespinelakedesigncompagespinelakedesigncomaboutpagespinelakedesigncomcontactoutputgoogle thumbnail 1google thumbnail 2google thumbnail ngoogle is using base64 string encoding of thumbnail jpg images for their visual search results in 2011 this thumbnail service changed from the previous system with the magnifying glass and absolute uri construction described in this questiongoogle web thumbnailsi just want to tile out a list of the the pages in a website as google thumbnails so i know which pages have been indexed and thumbnailed at a glance and what those thumbs all look likeedit nov 5 2011i identified that a call to this url returns jsonp with the base64 encoding google search result title description and url f3s400585querypinelakedesignhlenglusc29dhttp3a2f2fwpinelakedesigncom2fb1jgooglenyccj pvk1tu gabodsakh0ztuaw 3787232970 3expi172912761528936300493031631215320353227132410329403310433194336273378833854339073397534103a2ntthe query parameter is what was searched in google d is the destination of the link and possibly the source of the thumbnail s400585 is the height and width i am not sure what r4 and f3 do modifying any of these variables results in a 404 error my hunch is that the expi is some sort of checksum expiration algorithm based on the different parameter values but i do not knowreturned jsonpgooglenyccj pvk1tu gabodsakh0ztuaw 3787232970 3sbb1quality100shardsheights300131imgsdataimagejpegbase649j4aaqskz this is the long base64 enconding pa5r61f9ktbtsboxh15l0t39w224txtempine lakeem specializes in small business website emdesignem redesign and hosting we have developed the sungem content management system which allows our bbtxtboxh57l0t58w400urlupdate nov 8 2011i am looking for some solution like emedlys preview for viewing google thumbnailsupdate feb 9 2012using phantom js looks like a good way to achieve serverside remote snapshots but it does not help identify how to get at googles imagesupdate mar 26 2012i believe googles search spider is a headless version of desktop chrome running 1024px wide resolution a chrome spider would allow the spider to execute javascript use fontface css3 selectors view flash even waiting for preloader to reaches 100 and take accurate snapshots of the rendered pages after loading all assets and dom manipulation would anybody from google please weigh in to confirm or deny anything,"['javascript', 'jquery']" +209067,thispatch queue create multiple invocations with same label i have a requirement to execute a small set of related tasks on a custom thread created for them the tasks will be scheduled from different classesi am planning to use gcds thispatch queue create to create the custom thread and schedule the task on it note that all the related tasks must execute only on that one thread in orderso my question is if i call thispatch queue createmy custom thread label null with the same label from many classes in my codebase would it all eventually map to just one thread or do i need to create it in one place and get a reference to it whenever needed thanks,"['iphone', 'ios']" +209072,jetty 7 configuring jndi for startjava following wicket 15s lead i am converting a project from jetty 6125 to 750v20110901 my existing startjava contains the following setup which i use to configure jndi envconfiguration envconfiguration new envconfiguration url url new filesrcmainwebappwebinfjettyenvxmltouritourl envconfigurationsetjettyenvxmlurl bbsetconfigurationsnew configurationnew webinfconfiguration envconfiguration new orgmortbayjettypluswebappconfiguration new jettywebxmlconfiguration new taglibconfigurationthen my jettyenvxml has the followingconfigure classorgmortbayjettywebappwebappcontext new classorgmortbayjettyplusnamingresource argjdbcmyapparg arg new classorgspringframeworkjdbcdatasourcedrivermanagerdatasource set namedriverclassnamecommysqljdbcdriverset set nameurljdbcmysqllocalhostmyappcharacterencodingutf8set set nameusernameusernameset set namepasswordpasswordset new arg newconfigurethis has worked great in jetty 6 but in 7 orgmortbayjettypluswebappconfiguration does not seem to exist or perhaps i am missing a jar can someone give me some guidance on how to configure jndi with jetty 7,['java'] +209074,returning abstract type in base class in a design of a class hierarchy i am using an abstract base class that declares various methods that the derived classes would implement in a sense the base class is as close to an interface as you can get in c however there is an specific issue consider the code below which declares our interface classclass interface public virtual interface method 0class implementation public interface public virtual implementation method of course this wouldnt compile because you cannot return an abstract class in c to get around this problem i am using the following solutiontemplate class tclass interface public virtual t method 0class implementation public interfaceimplementation public virtual implementation method this solution works and is all fine and dandy however to me it does not look very elegant because of the redundant bit of text which would be the parameter for interface i would be happy if you guys could point our any other technical issues with this design but that is my only concern at this pointis there any way to get rid of that redundant template parameter possibly using macrosnote the method in question has to return an instance i am aware that if method returned a pointer or a reference there would be no issue,['c++'] +209082,can i suspend iscroll functionality i want to thisable the scroll sometimes so i can do multitouch events in the same area something likeif eventoriginaleventtoucheslength is 2 then myscrollthisableis something like this possible,"['javascript', 'jquery']" +209099,storing uiimage in core data with the new external storage flag i know that the storing of uiimages in core data has been thiscussed a lot such as here but that was preios5 now that we have the external storage flag do you guys think it would be a fine idea to store uiimages directly in the entity as a separate entity or still on the thiskhere is a source explaining the external storage option,['iphone'] +209152,css center content inside div i need to center html content inside a div classpartners top div with 2 images as you can see from the image below it floats left instead of center of the divthis is my html codediv idpartners div classwrap clearfix h2partnertnerzy serwisuh2 ul lia hrefimg width56 height16 altparnter bar wika srcaspartnerswikapngali lia hrefimg width65 height15 altparnter bar siemens srcaspartnerssiemenspngali ul a classlinkclose hreffirmyclbp1zamknij a div divimagecsspartners top position relative zindex 100partners margin 12px 0 3px textalign centerclearfixafter rowafter clear both content thisplay block height 0 visibility hiddenpartners wrap width 655pxwrap margin 0 auto position relative width 990pxpartners h2 color a6a5a5 float left fontweight normal margin 2px 15px 0 0partners ul float leftul liststyleposition outside liststyletype none,"['html', 'css']" +209167,how to include prebuilt shared libraries in apk with eclipse i have a shared library libfooso and need to use it in my android appmy first try was to have in androidmkinclude clear varslocal module testlocal src files testcpplocal ldlibs lpath to foo lfooinclude build shared libraryin my activity i havestatis systemloadlibraryfoothis builds correctly however i noticed that created apk doesnt include libfooso also i see it is not copied to libsarmeabi i guess for that reason i have unsatisfiedlinkerror when executing my appi saw in some other posts that i need to add prebuild shared library so i add the following to my androidmkinclude clear varslocal module foolocal src files foo pathlibfoosoinclude prebuild shared librarybut now i am getting the build errorfoo local src files points to a missing filei am sure that the path is correct note that the libfooso was having origionally the version number at the end though i had to remove it and leave only so since ndkbuild complainedwhat am i doing wrong,['android'] +209186,java list that contains unique elements in order is there a list type in java that stores objects in ascending order and not adds if this object is previously added i know java maps can do that but i wonder if there is a list type that does what i want otherwise i have to override contains equalsto and add methodsright,['java'] +209191,const reference public member to private class member why does it work recently i found an interesting thiscussion on how to allow readonly access to private members without obfuscating the design with multiple getters and one of the suggestions was to do it this wayinclude iostreamclass a public a ro val val void dosomethingint some val val 10some val const int ro valprivate int valint main a a instance stdcout a instance ro val stdendl a instancedosomething13 stdcout a instance ro val stdendloutput aout 0130gotw66 clearly states that objects lifetime starts when its constructor completes successfully and returns normally that is control reaches the end of the constructor body or an earlier return statementif so we have no guarantee that the val memeber will have been properly created by the time we execute ro val val so how come the above code works is it undefined behaviour or are primitive types granted some exception to the objects lifetimecan anyone point me to some reference which would explain those things,['c++'] +209196,why should i put trycatch block out of loop here is codereview guideline by practicepatterns team topic7the link navigate to the exception section automaticlythey said you should put trycatch block out of loop when you handle exception i want to know why,['c#'] +209206,custom database type in activerecord i am using rails 311 with postgresql 91 and the earththistance moduleto be able to calculate the thistance between different locations properly i have setup a column with the earth type in my branches tablethe problem i am experiencing now is that my rails application that uses this table does not understand the earth type and thus i am getting this in my dbschemarb could not dump table branches because of following standarderror unknown type earth for column locationthis is problematic since now i cannot create my test database from the schemarbhow can i add this type to ar or make it ignore that column,['ruby-on-rails'] +209220,wait unitl listviews smoothscrolltoposition finishes scopeneed to scroll to certain position smoothly and then jump to another positoin with setselectionanotherposition this is done to create an illusion of smooth scrolling of eg 100 items in listview smoothscrolltoposition100 lasts too much you knowproblemsetselection does not wait till smoothscrolltoposition finishes it is work so setselection is called immediately and user see quick jumping onlycodeprivate final int scrollableitems 20int firstvisibleposition mlistviewgetfirstvisiblepositionif firstvisibleposition scrollableitems mlistviewsmoothscrolltoposition0 else mlistviewsmoothscrolltopositionfirstvisibleposition scrollableitems mlistviewsetselection0mlistviewclearfocusideaok we could change logic of smoothness illusion first setselection then scroll smoothly were scrolling to very first item on top of the list int firstvisibleposition mlistviewgetfirstvisibleposition if firstvisibleposition scrollableitems mlistviewsmoothscrolltoposition0 else mlistviewsetselectionscrollableitems mlistviewsmoothscrolltoposition0 mlistviewclearfocus,['android'] +209244,iscroll preserving native vertical scroll works in ios not android i am using iscrolljs to scroll through a carousel of items on a mobile page i found the following fix that listens for vertical movement and stops the iscroll script taking control letting the native vertical scroll happen onbeforescrollstart functione try point etouches0 pointstartx pointpagex pointstarty pointpagey catche null onbeforescrollmove functione try deltax mathabspointpagex pointstartx deltay mathabspointpagey pointstarty if deltax deltay epreventdefault else null catche i am using trycatch as it had some issues when testing in a browser complained about point not being definedthe issue i am having is that it works well on ios tested on several idevices but on android it is not so good if a user tries to scroll the page vertically starting by placing the finger on the carousel the page does not scroll as the iscroll still has controlany idea how i can get it to work on android or any pointers toward where it might be going wrongeditsome debugging and i have thiscovered possibly why this is not working the coordinates are being updated while the user touches the screen on ios but on android only the first set of coordinates are being caught any idea why this would be,"['jquery', 'android']" +209250,get relative x and y div after rotation so heres one which i wished i paid more attention in maths class fori have a big container div and inside of this i have a few content divs which are rotatedwhat i am trying to do is animate between the child divs by moving the main div around in the viewport this would be really easy if i was just doing it based upon simple xy topleft calculations however when there is rotation involved my maths just breaks downi have tried a few things and have not really cracked itheres a simplified version of my results sort far please feel free to fiddlei really cannot figure this outediti am going with this solution as a preference simply because i have already worked a way of making the rotate plugin work with msie6howver i have to say that although i follow all the math functions and they seem clean the results are not pixel perfect is this something to do with a pi calculation it seems that the bigger and more spaced out i make the boxes the less likely they are to match up to the top left oddnessalso can anyone remind me of what trig thing i need to do if the angle is more than 45 degress i cannot find a reference i remember this from maths class years ago when there were 4 quadrants or something rr how i wish i paid more attention thank you hugely for all the help so far,"['javascript', 'jquery', 'css']" +209259,ruby code to get the date of next monday or any day of the week given an input of for exampleday mondayhow can i calculate the date of daydef date of nextday end,['ruby'] +209292,controlling your phone from laptop idea create a remote control for your android phonewhy i like listening music on my phone in a dock station with speakers connected now sometimes i want to turn the volume updown change the song etc so i need to unlock the phone locate app that is playing music music player internet radio app etc sometimes i manage to undock the phone or just mess something up and generally this scksso i would like to control my phone on a data connection not wifi from the laptop on wifii had investigated couple of approaches and would like to get some recommendations on themuse xmpp this is nice as there a lots of free xmpp services i can use two libraries both based on smack that i tried work just fine flow asmack port and beem smack port i could automatically create new user on device and present some idpassword combination that i user would enter on a desktop side to link both devicesuse jxta should be the next real deal but could be an overkill i would imagine running a rendezvousrelay server somewhere need to get hosting to work around firewallnat and creating a peer group protected with password use device unique id and password withing group to link to the desktop application a great ebook explaining p2p and jxta can be downloaded from hereuse c2dm could be the answer but notification delivery sometimes can take more then couple of seconds to deliver and there would be no feedback mechanismso far first solutions looks like a lot easier choice create custom extension or just create chat between both endpoints and use that for relaying commandsmessages but i wonder if i would be abusing xmpp system jxta sounds great but from all the reading i done it is apparent that it is designed for group communication and service sharing and not a solution for connecting two endpointswhat do you guys think i welcome all suggestions tooupdate i do not want to remote to a phone and interactively control it i want to establish a connection socket connection between laptop and phone even if both of them are on different networks secured behind firewalls routers with this i could define a protocol to issue commands to the phone lower volume mute start app etcupdate 2 i am giving jxta a shot it is a nice solution but lack of documentation is a bit of a downer got vps freebsd server to test rdvrelay side of things i keep updating this question further as it may be helpful for othersupdate 3 some more readinghow to make two android devices to communicate through tcpconnection between two computers without opening ports using a third computerupdate 4 so far i did not have enough time to further continue my project i did find an interesting project at the moment project owners are rewriting their library you can track their progress here,"['java', 'android']" +209298,adding elements to an xml file in c i have an xml file formatted like thissnippets snippet nameabc snippetcode testcode1 snippetcode snippet snippet namexyz snippetcode testcode2 snippetcode snippet snippetsi can successfully load the elements using xdocument but i have trouble adding new elements there are many functions and most of which i tried did not work well for me how would this be done the new element would contain the snippet name tag and the snippet code tag my previous approach was to open the file and manually create the element using a string which although works is a very bad ideawhat i have tried xdocument doc xdocumentloadspath xelement root new xelementsnippet rootaddnew xelementname name goes here rootaddnew xelementsnippetcode snippetcode docelementsnippetsaddroot docsavespathand the result is thissnippet namename goes herename snippetcode code goes here snippetcode snippetit works fine except that the name tag is generated incorrectly it should be snippet nameabc but i cannot generate that properly,['c#'] +209317,android sqlite cursor contentvalues is there any way to get the contentvalues object from the sqlite it is very useful that we can insert contentvalues in db and it should be more useful to get the cv from there,['android'] +209321,using c generics in a nested class consider the following class structurepublic class foot public virtual void dosomething public class baru where you foot new public void test var blah new u blahdosomething public class bazpublic class foobaz foobaz public override void dosomething when i go to use the nested class i have something like the followingvar x new foobazbarfoobazit seems redundant to have to specify it twice how would i create my class structure such that i can do this insteadvar x new foobazbarshould not there be some way on the where clause of the nested class to say that you is always the parent howupdate added methods for dosomething above to address some of the comments it is important that when i call dosomething it addresses the overridden version if i just use foo instead of u then the base implementation is called instead,['c#'] +209343,convert python to r i know there exists a module rpy and rpy2 to convert r code to pythonis there any easy way to do the reverse,['python'] +209350,c static class why use possible duplicatewhen to use static classes in c i set my classes as static a lot but i am not sure when use static or not or whats the difference it makes to use it or notcan anybody explain please,['c#'] +209357,aspnet charting control not working on production server i have an application that relies heavily on charting and currently the charts will work in the aspnet development server but when i try to publish out to my server win 2008 server r2 iis 7 the charts do not show up using firebug i can see that the call to chartimgaxd returns a 404 and all i get is a blank image holder in ie or nothing in firefox i have searched for about 3 or 4 hours so far and have tried just about everything recommended but nothing seems to be workingi would like to use memoryhttpimagehandler instead of the imagelocation configurationmy webconfig appsettings add keychartimagehandler valuestoragefiletimeout20dirctempimagefiles add keychartimagehandler valuestoragememorytimeout20deleteafterservicingfalse appsettings systemwebserver handlers remove namechartimagehandler add namechartimagehandler preconditionintegratedmode verbgetheadpost pathchartimgaxd typesystemwebuidatavisualizationchartingcharthttphandler systemwebdatavisualization version40 cultureneutral publickeytoken31bf3856ad364e35 handlers systemwebserver systemweb httphandlers add pathchartimgaxd verbgetheadpost typesystemwebuidatavisualizationchartingcharthttphandler systemwebdatavisualization version40 cultureneutral publickeytoken31bf3856ad364e35 validatefalse httphandlers pages controls add tagprefixasp namespacesystemwebuidatavisualizationcharting assemblysystemwebdatavisualization version40 cultureneutral publickeytoken31bf3856ad364e35 controls pages compilation debugtrue targetframework40 assemblies add assemblysystemwebdatavisualization version40 cultureneutral publickeytoken31bf3856ad364e35 assemblies compilation customerrors modeoff systemwebdoes anyone have any ideas where i am going wrong to keep this from working on my server,['asp.net'] +209366,aspnet syntax i am trying to make the switch from java to neti have noticed a number of aspnet pages have sometext in them can someone explain what this does in a couple of sentences or point me to a reference on the syntax,['asp.net'] +209376,when exactly does the virtual table pointer in c gets set for an object i know that for any class that has a virtual function or a class that is derived from a class that has a virtual function the compiler does two things first it creates a virtual table for that class and secondly it puts a virtual pointer vptr in the base portion for the object during runtime this vptr gets assigned and starts pointing to the correct vtable when the object gets instantiatedmy question is that where exactly in the instantiation process does this vptr gets set does this assignment of vptr happens inside the constructor of the object of beforeafter the constructor,['c++'] +209378,python dots in the name of variable in a format string say i have got a dictionary with dots in the name of fields like personname joe if i wanted to use this in strformat is it possiblemy first instinct was name personnameformatpersonname joebut this would only work if my dict were shaped likepersonnamejoethe relevant manual docs section does not mention anyway of escaping the dotsidenote i thought that generally def funckw printkwfuncab joewould cause an error but the expanded function call seems to work even if they are not valid identifiers it does error out on nonstrings though o o,['python'] +209394,uipopovercontroller dealloc getting calledaarc environment while thisplaying a popover controller for a second time after thismissing it and then rethisplaying it i get the following errorterminating app due to uncaught exception nsgenericexception reason uipopovercontroller dealloc reached while popover is still visiblethe stack trace is only a bunch of hex and the sigabrt happens at uiapplicationmain every time heres the code that the button triggers ibactioncreatenewscoreidsender if selfpc if selfpcpopovervisible return else breakpoint is hit hereacrashes after this line selfpc presentpopoverfrombarbuttonitemuibarbuttonitem sender permittedarrowdirectionsuipopoverarrowdirectionup animatedyes ngdocumentinfoviewcontroller documentinfovc ngdocumentinfoviewcontroller alloc initwithblankdocumenttargetinmanagedobjectcontextselfcontext uinavigationcontroller navc uinavigationcontroller alloc initwithrootviewcontrollerdocumentinfovc uibarbuttonitem donebutton uibarbuttonitem alloc initwithbarbuttonsystemitemuibarbuttonsystemitemdone targetself actionselectordonecreatingnewscore uibarbuttonitem cancelbutton uibarbuttonitem alloc initwithbarbuttonsystemitemuibarbuttonsystemitemcancel targetself actionselectorcancelcreatingnewscore navcnavigationbartopitemleftbarbuttonitem donebutton navcnavigationbartopitemrightbarbuttonitem cancelbutton cgsize popoversize cgsizemakedocumentinfovcviewboundssizewidth documentinfovcviewboundssizeheight documentinfovccontentsizeforviewinpopover popoversize uipopovercontroller popover uipopovercontroller alloc initwithcontentviewcontrollernavc popoverdelegate self selfpc popover popover presentpopoverfrombarbuttonitemuibarbuttonitem sender permittedarrowdirectionsuipopoverarrowdirectionup animatedyesi would like to just retain the popover which would fix the issue but this is an arc environment so i do not have retain is there a way for me to fix the error without turning off arc for the file and having to manually do the memory for the entire fileedit the popover is stored as an ivarproperty strong uipopovercontroller pcdoes anyone have a solution for this problem maybe an arc override i will file a br as codafi suggests but a solution would still be nice as this is a roadblock in a major project if this is not possible then i suppose i will roll my own,['ios'] +209404,rails not rendering a partial on webpage total newbie trying to work through the rails tutorial on lyndacomthe code is really short and exactly the way it is on the video yet i cannot get my page to render the partial when i pull run it on the server it does not render the partial at all but just skips it no error messages thanks in advancethis is edithtmlerb link to back to list action list class backlinkdiv clasubject edit h2edit subjecth2 form forsubject url action update idsubjectid do f render partial form locals f f div classformbuttons submit tagupdate subject div end divand this is formhtmlerbtable summarysubject form fields tr thnameth td ftext fieldname td tr tr thpositionth td ftext fieldposition td tr tr thvisibleth td ftext fieldvisible td trtable,['ruby-on-rails'] +209428,jquery infinite scroll reset i am using the infinite scroll jquery plugin for a website everything is fine except that my page is a search sowhat happen is1 you go on the page browser autolocates you and give you back a list of items eg bars around youinfinite scroll is needed to avoid pagination for this list everything works until hereexcept the fact that i could reache the endoftheinfinitepage and the plugin unbinds itself from the scroll2 nowwhen you want to manually insert an address in the input text you are free to do ityou write your address and press enterand with ajax no page refreshi will look for latlon locate the address change the navigation link for the infinite scrollandi feel dumb but i cannot figure out a way to reactivate or rebind the plugin to the eventso my new search results do not have a fresh infinite scroll instancepage split correctly and correctly returns a json trying changing pagenumberthis is what happens in the consolemath 0 468jqueryinfinitescrollminjs20heading into ajax array2 0 ajaxgetcoworkingspage 1 latitude525234051longitude1341139thistance12 length 2 proto array0jqueryinfinitescrollminjs20using json via ajax methodjqueryinfinitescrollminjs20error endjqueryinfinitescrollminjs20binding unbindafter the unbind i am not able to bind it again and therefore have the infinit scroll on my next search results,['jquery'] +209434,loss of precision converting float to nsnumber back to float i seem to be encountering a strange issue in objectivec converting a float to an nsnumber wrapping it for convenience and then converting it back to a floatin a nutshell a class of mine has a property red which is a float from 00 to 10property nonatomic assign float redthis object is comparing itself to a value that is loaded from thisk for synchronization purposes the file can change outside the application so it checks periodically for file changes loads the alternate version into memory and does a comparison merging differencesheres an interesting snippet where the two values are comparedif localobjectred remoteobjectred nsloglocal red f remote red f localobjectred remoteobjectredheres what i see in the logs201028 210702356 myapp12826aa63 local red 0205837 remote red 0205837weird right how is this piece of code being executedthe actual value as stored in the filered0205837is converted to a float usingcurrentobjectred attributedict valueforkeyred floatvalueat another point in the code i was able to snag a screenshot from gdb it was printed to nslog as this is also the precision with which it appears in the file on thisk201028 212119894 myapp132141c03 local red 0707199 remote red 0707199but appears in the debugger ashow is this level of precision being obtained at the property level but not stored in the file or printed properly in nslog and why does it seem to be varying,['objective-c'] +209438,objectivec pass block as parameter how can i pass a block to a functionmethodi tried voidsomefunc blocksomeblock with no availie what is the type for a block,['objective-c'] +209440,json uncaught syntaxerror unexpected token trying to make a call and retrieve a very simple one line json filedocumentreadyfunction jqueryajax type get url datatype jsonp success functiondata alertsuccess end documentreadyheres the raw requestget 1319854793396 1319854793399 http11host wncrunnerscomconnection keepalivecachecontrol maxage0useragent mozilla50 windows nt 61 applewebkit5352 khtml like gecko chrome150874106 safari5352accept referer httplocalhost8jquerytesthtmlacceptencoding gzipdeflatesdchacceptlanguage enusenq08acceptcharset iso88591utf8q07q03heres the raw responsehttp11 200 okdate sat 29 oct 2011 022124 gmtserver apache13 unix mod ssl2822 openssl097d se053lastmodified fri 28 oct 2011 174847 gmtetag 166a2402104eaaeaffacceptranges bytescontentlength 16contenttype textplainconnection closered f00the json is coming back in the response red f00 but chrome reports uncaught syntaxerror unexpected token colorsjson1if i navigate directly to url itself the json is returned and is thisplayed in the browserif i paste the contents of colorsjson into jslint the json validatesany ideas why i cannot get this error and i never make it to the success callbackedit the jqueryajax call above runs perfect at jsfiddlenet and returns the alert success as expected edit 2 this url works fine rapidsjson i noticed that it returned as type textjavascript and chrome did not throw the unexpected token i have tested several other urls and the only one that does not throw the unexptected token is the wunderground that is returned as type textjavascript streams returned as textplain and applicationjson are not being parsed correctly,['jquery'] +209449,css width and maxwidth combined i have the following codetable stylewidth 100 maxwidth 800px tablelayout fixed table stuff here tablei think it is obvious i intend for the table to take the full width available with a capped maximum size of 800pxthis works in internet explorer and firefox however in chrome it appears that the maxwidth is being ignored when width is presenti have tried using maxwidth 100 width 800px which again works in ie and ff but the maxwidth is ignored in chrome i have tried using just maxwidth 800px but in chrome the table comes out 1159 pixels wide instead wtfif anyone can help with this it would be much appreciated thank you,['css'] +209457,djangomptt order in my project i am using djangomptt for categoriesmy modelclass categorymodelsmodel name modelscharfield parent modelsforeignkeyself blanktrue nulltrue related namesub category nav order modelsintegerfieldnullfalse blankfalse default0 unsure need nav order column in db class meta verbose name plural categoriesmpttregistercategoryand i need to have ability get order for current category like thiscategory navigation orderone columncata 0subcat11 0 sub11a 0 sub11b 1 sub11c 2subcat12 1catb 1 subcat21 0subcat22 1subcat23 2 sub23a 0catc 2how can i quickly fillrecalculate order column on creatingmoving elementsor calculate it by categorys method categoryobjectsgetnamesub11bget order should return 1,['python'] +209489,what will the the order in which filters will be called suppose i have following in my webxmlfiltermapping filternamef1filtername urlpatternxyzurlpatternfiltermappingfiltermapping filternamef2filtername urlpatternxyzabcdourlpatternfiltermappingfiltermapping filternamef3filtername urlpatternurlpatternfiltermappingwhat will be the order in which the filters will be called if a request comes as xyzabcdoand why,['java'] +209496,why does bsearch return a void void bsearch const void key const void base size t num size t size int comparator const void const void if i pass in a const void base should not bsearch also return a const void result,['c'] +209510,ios detect 3g or wifi i am not sure if this is possible but i have this scenarioi have a website thisplayed in my uiwebview which has the link set in a uisegmentedcontrollerthey website can detect if you are on wifi or on the 3g networknow the segmented controller points to 2 different pages 1 an iphone friendly login screen2 the home page once you are logged innow this is the questioncan i program my application to detect if it is on wifi or 3g i know you can do this but then based on the answer go to segment 1 or 2kind like thisifiphone device is on 3g go to segment 1 else go to segment 0,"['ios', 'objective-c']" +209550,active admin autocomplete with rails3jqueryautocomplete gem i am having an issue using the rails3jqueryautocomplete gem with active admini am using the most recent version of active admin from git which now relies on formtastic 2 and i am using 104 of rails3jqueryautocompleteundefined local variable or method autocomplete artist name records path for activeadmindsl0x007fde797140d0it does not like the url route i am providing any ideas what i could be doing wronggemsgem activeadmin git gitgithubcomgregbellactive admingitgem rails3jqueryautocomplete 104recordsrb active adminactiveadminregister record do controller do autocomplete artist name full true end form do f finput artist name as autocomplete url autocomplete artist name records path endendroutesrb resources records do get autocomplete artist name on collection endi also tried this fix which i found somewhere but it did not change anything including the error,['ruby-on-rails'] +209601,any alternatives to cachinghttpclient for android i want to enable httpcaching for my android app so i am looking for a library project to depend upon cachinghttpclient looks nice but uses apache httpclient 41 and android only includes 40so are there any other good httpcache projects for java that are usable on android,['android'] +209630,is it possible to make rails i18n locales fallback to each other i am using rails 3 with globalize3 020beta4ideally i need fr to fallback to en and vice versathere are cases when only a french translation is available and i need to show it even if the locale is eni triedconfigi18nfallbacks fr en en fr but somewhat unsurprisingly it causes a stack level too deep error,['ruby-on-rails'] +209634,relationship between catalog schema user and database instance to compare databases of different vendors oracle sql server db2 mysql and postgresql how can i identify any object uniquely and do i need a catalog for instance in javas databasemetadata i should specify catalog and schema foopattern at least is it true that catalog is just an abstraction of data storage,['mysql'] +209641,close a socket and then reopen it from the same port in net well i wonder if some one can help with a problem that i encounteri want to close a socket and then rerun from the same port this is what i am doingopening udpserver new socketaddressfamilyinternetwork sockettypedgram protocoltypeudp udpserveripendpoint new ipendpointipaddressany 9050 udpendpoint endpointudpserveripendpoint udpserverbindudpserveripendpointcloseing udpservershutdownsocketshutdownboth udpserverthisconnecttrue udpservercloseafter i close it and the i try to reconnect it with the same code as above i get erroradditional information only one usage of each socket address protocolnetwork addressport is normally permittedi checked for exception during closing but i didnt get any i guessed they were closed properly so actually what is causing this problem please help,"['c#', '.net']" +209650,sharekit modal view controller would not go away i am using sharekit 021 on xcode 42 ios sdk 5 to share text on twitter it shares fine but the modal view controller wont go away after successfully sharing on after clicking on the cancel button see belowand this is my codeibactionshareontwitteridsender item to share nsstring text go away modal view controller shktwitter sharetexttextwhat am i doing wrong,['objective-c'] +209652,posting json as the body of a post request using afhttpclient i am trying to find a way using afnetworking to set the contenttype header to be applicationjson and to post with json in the body the methods that i am seeing in the documentation postpath and requestwithmethod both take a dictionary of parameters which i assume is encoded in the standard form syntax does anyone know of a way to instruct afhttpclient to use json for the body or do i need to write the request on my own,"['objective-c', 'ios']" +209694,detect safari browser how to detect safari browser using javascript i have tried code below and it detects not only safari but also chrome browserfunction issafari var is safari navigatoruseragenttolowercaseindexofsafari 1 return is safari,['javascript'] +209711,js confusion about inheritance i am familiar with oop concepts through the languages like c java right now i am trying to learn javascript as a hobby mainly due to the interest in webgl but i am having troubles with prototype based inheritancelet us say i have a base class which accepts a parameter in constructor and i need to extend this the way i am doing this is shown belowfunction basen this and nbaseprototypeprint function consolelogthis nfunction derivedn basecallthis nderivedprototype new basederivedprototypeconstructor derivednow this is what i understand a single base object is serving as the prototype of derived so all instances of derived will inherit properties from this base object eg the print method when i call new derived10 then a new object is created function derived is called in the context of this newly created object ie this points to newly created object and function base is called from function derived and then n is created and assigned the value 10 so if i create 5 derived objects all of them will have their own n property so far this is okaybut i do not like this linederivedprototype new basefunction base expects an argument but i am passing nothing here there is no point of passing a parameter here as this object will act as prototype of derived and i do not need any value of n for this prototype object but what if the function base depends on the argument say base loads a resource and the path is passed as parameter what to do then to summarize my questions arewhat to do with data members in prototype object n in this example derivedprototype new base is creating an instance of base and this will remain in memory always assuming derived is defined in global space what to do if base class is very costly and i do not want an extra object,['javascript'] +209775,dequeuereusablecellwithidentifier behavior changed for prototype cells in ios5 using arc and prototype cells for tableview on storyboard can i replace the code belowstatic nsstring cellidentifier celluitableviewcell cell tableview dequeuereusablecellwithidentifiercellidentifierif cell nil cell uitableviewcell alloc initwithstyleuitableviewcellstyledefault reuseidentifiercellidentifier configure the cellreturn cellwith this simple codeuitableviewcell cell tableview dequeuereusablecellwithidentifiercellreturn celli saw this on this linkthanks in advancearildo,['iphone'] +209799,iphone simulator cannot be lauched when i press run on xcode with other tasks already running the following message appearssimulator in use the simulator cannot be launched because it is already in usei checked with some friends and when they press run xcode automatically stop the tasks running and run the app you want how can i configure this herethanks in advance,"['iphone', 'ios']" +209809,target numeric keys only in array i have an array with 2 kinds of keys strings and integers i want to do foreach on this array and want to do it for numeric keys only what is the most elegant way of doing it,['php'] +209829,best unit for fontsizes in css what are the advantages thisadvantages of each em px and pt my current choice are percentages the only reason is because i can globally change the fontsize of all elements just by modifying the font size on the root element body,['css'] +209844,restoring content when clicking back button with historyjs i have implemented historyjs on a local test application everything seems to work however if i press the back button in the browser the previous content does not get restoreddo i actually have to load the content manually again ie make another ajax call when user presses the back button then how does github do it i see they do not make another ajax call when clicking back button in the code treehere is my codehistoryadapterbindwindowstatechangefunction var state historygetstate historylogstatedata statetitle stateurl aeachfunctionindex link if linkattrdataajaxthisabled true linkclickfunctionevent var clips thisattrdataajaxclips ajaxthisattrhref data clipsclips success functiondata var data parsejsondata historypushstatestate1 datatitle documenttitle eachdataclips functionkey val keyreplacewithval return false dataclips is a json array which contains ids of html objects as key and the actual html content as value for exampleheader content in header divas noted the replacement works fine i output a random number in the header every click on a link spits out another random number in the header however if i push the back button the number stays the same only the title will be restored also random number,['javascript'] +209847,how do i convert a uiimage to nsdata or cfdataref how do i convert a uiimage to nsdata or cfdataref i need to pass a cfdataref to abpersonsetimagedata,"['iphone', 'ios']" +209851,which method is called when back button clicked in navigation controller i want to save db when the back button clicked in navigation controllerso i would insert code in methodwhat method is called when back button clicked in navigation controller,['ios'] +209856,what are the new type qualifiers introduced with arc automatic reference counting arc introduces some new type qualifiers i have seen strong and weak but what do they do,"['objective-c', 'ios']" +209875,can i remove just the popup bubbles of pois in google maps api v3 so i am working on a new web app that has a big focus on maps using google maps api v3 and really happy with it but noticed that the points of interest pois have automatically bubbles with more details and a link to the google places page i do not want these here is my codemap new googlemapsmapdocumentgetelementbyidmap centernew googlemapslatlngdefault latitudedefault longitude zoom11 maptypeidgooglemapsmaptypeidroadmap maptypecontrolfalse pancontrolfalsei know you can remove the pois entirely here is my code for thatmap new googlemapsmapdocumentgetelementbyidmap centernew googlemapslatlngdefault latitudedefault longitude zoom11 maptypeidgooglemapsmaptypeidroadmap maptypecontrolfalse pancontrolfalse styles featuretypepoi elementtypelabels stylers visibilityoff this removes everything entirely and i still would like to see the labels as i think they bring value but just think the bubbles are too much of a thistractionfor reference here is the bubble i want to removeand here is the same map with pois removed entirely,['javascript'] +209886,styling bullets and numbers in and how can i get access to the actual bullet andor number in css selectors for ul and ol i would specifically like to increase the fontsize and fontweight of the numbersbullets to make my items stand out more,"['html', 'css']" +209916,sql not empty instead of not null i am using postgresql i have a column thatnot nullhowever when i want to insert a row with an empty string as likeit does not give me an error and accepts how can i check insert value should be not empty neither empty nor nullps my column defined asads character varying60 not null,['sql'] +209920,resizing an image without losing quality i made this code to resize images with two factors it works but the quality of image is very bad after it is resized can you help methis is the codepublic class imagetest private static final int factor1 3private static final int factor2 4public static void mainstring args jfilechooser cs new jfilechooser cssetfileselectionmodecsdirectories only int i csshowopendialognull ificsapprove option file f csgetselectedfile file ff flistfiles forint j0jfflengthj string end ffjgetnamesubstringffjgetnameindexof1 systemoutprintlnend try bufferedimage originalimage imageioreadffj int type originalimagegettype 0 bufferedimagetype int argb originalimagegettype bufferedimage resizeimagejpg resizeimagewithhintoriginalimage type imageiowriteresizeimagejpg end new fileprffjgetname catchioexception e eprintstacktrace private static bufferedimage resizeimagewithhintbufferedimage originalimage int type int img width originalimagegetwidthfactor1factor2 int img height originalimagegetheightfactor1factor2 bufferedimage resizedimage new bufferedimageimg width img height type graphics2d g resizedimagecreategraphics gdrawimageoriginalimage 0 0 img width img height null gthispose gsetcompositealphacompositesrc gsetrenderinghintrenderinghintskey interpolation renderinghintsvalue interpolation bilinear gsetrenderinghintrenderinghintskey rendering renderinghintsvalue render quality gsetrenderinghintrenderinghintskey antialiasing renderinghintsvalue antialias on return resizedimage i see on web that resizeimagewithhint is done with the scope to do not lose quality but it do why can you help me about,['java'] +209930,how do i exit a while loop in java what is the best way to exitterminate a while loop in javafor example my code is currently as followswhiletrueifobj null i need to exit here,['java'] +209932,viewpager and fragments a whats the right way to store fragments state fragments seem to be very nice for separation of ui logic into some modules but along with viewpager its lifecycle is still misty to me so guru thoughts are badly needed editsee dumb solution below scopemain activity has a viewpager with fragments those fragments could implement a little bit different logic for other submain activities so the fragments data is filled via a callback interface inside the activity and everything works fine on first launch butproblemwhen the activity gets recreated eg on orientation change so do the viewpagers fragments the code youll find below says that every time the activity is created i try to create a new viewpager fragments adapter the same as fragments maybe this is the problem but fragmentmanager already has all these fragments stored somewhere where and starts the recreation mechanism for those so the recreation mechanism calls the old fragments onattach oncreateview etc with my callback interface call for initiating data via the activitys implemented method but this method points to the newly created fragment which is created via the activitys oncreate methodissuemaybe i am using wrong patterns but even android 3 pro book does not have much about it so please give me onetwo punch and point out how to do it the right way many thankscodemain activitypublic class dashboardactivity extends basepageractivity implements onmessagelistactionlistener private messagesfragment mmessagesfragmentoverrideprotected void oncreatebundle savedinstancestate loggerddash oncreate superoncreatesavedinstancestate setcontentviewrlayoutviewpager container new defaulttoolbarthis create fragments to use mmessagesfragment new messagesfragment mstreamsfragment new streamsfragment set titles and fragments for view pager mapstring fragment screens new linkedhashmapstring fragment screensputgetapplicationcontextgetstringrstringdashboard title dumb new dumbfragment screensputgetapplicationcontextgetstringrstringdashboard title messages mmessagesfragment instantiate view pager via adapter mpager viewpager findviewbyidridviewpager pager mpageradapter new basepageradapterscreens getsupportfragmentmanager mpagersetadaptermpageradapter set title indicator titlepageindicator indicator titlepageindicator findviewbyidridviewpager titles indicatorsetviewpagermpager 1 set of fragments callback interface implementations overridepublic void onmessageinitialisation loggerddash onmessageinitialisation if mmessagesfragment null mmessagesfragmentloadlastmessagesoverridepublic void onmessageselectedmessage selectedmessage intent intent new intentthis streamactivityclass intentputextramessageclassgetname selectedmessage startactivityintentbasepageractivity aka helperpublic class basepageractivity extends fragmentactivity basepageradapter mpageradapterviewpager mpageradapterpublic class basepageradapter extends fragmentpageradapter implements titleprovider private mapstring fragment mscreenspublic basepageradaptermapstring fragment screenmap fragmentmanager fm superfm thismscreens screenmapoverridepublic fragment getitemint position return mscreensvaluestoarraynew fragmentmscreenssizepositionoverridepublic int getcount return mscreenssizeoverridepublic string gettitleint position return mscreenskeysettoarraynew stringmscreenssizeposition hack we do not want to destroy our fragments and reinitiate them afteroverridepublic void destroyitemview container int position object object todo autogenerated method stubfragmentpublic class messagesfragment extends listfragment private boolean mislastmessagesprivate listmessage mmessageslistprivate messagearrayadapter madapterprivate loadmessagestask mloadmessagestaskprivate onmessagelistactionlistener mlistener define callback interfacepublic interface onmessagelistactionlistener public void onmessageinitialisation public void onmessageselectedmessage selectedmessageoverridepublic void onattachactivity activity superonattachactivity setting callback mlistener onmessagelistactionlistener activity mislastmessages activity instanceof dashboardactivityoverridepublic view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate inflaterinflaterlayoutfragment listview container mprogressview inflaterinflaterlayoutlistrow progress null memptyview inflaterinflaterlayoutfragment nodata null return superoncreateviewinflater container savedinstancestateoverridepublic void onactivitycreatedbundle savedinstancestate superonactivitycreatedsavedinstancestate instantiate loading task mloadmessagestask new loadmessagestask instantiate list of messages mmessageslist new arraylistmessage madapter new messagearrayadaptergetactivity mmessageslist setlistadaptermadapteroverridepublic void onresume mlisteneronmessageinitialisation superonresumepublic void onlistitemclicklistview l view v int position long id message selectedmessage message getlistadaptergetitemposition mlisteneronmessageselectedselectedmessage superonlistitemclickl v position id public methods to load messages from host acitivity etc solutionthe dumb solution is to save the fragments inside onsaveinstancestate of host activity with putfragment and get them inside oncreate via getfragment but i still have a strange feeling that things should not work like that see code below overrideprotected void onsaveinstancestatebundle outstate superonsaveinstancestateoutstate getsupportfragmentmanager putfragmentoutstate messagesfragmentclassgetname mmessagesfragmentprotected void oncreatebundle savedinstancestate loggerddash oncreate superoncreatesavedinstancestate create fragments to use if savedinstancestate null mmessagesfragment messagesfragment getsupportfragmentmanagergetfragment savedinstancestate messagesfragmentclassgetname streamsfragmentclassgetname if mmessagesfragment null mmessagesfragment new messagesfragment,['android'] +209936,rabbitmq queue with no subscribers durable and persistent mode appear to relate to reboots rather than relating to there being no subscribers to receive the messagei would like rabbitmq to keep messages on the queue when there are no subscribers when a subscriber does come online the message should be recieved by that subscriber is this possible with rabbitmqcode sampleservernamespace rabbiteg class program private const string exchange name helloworld static void mainstring args connectionfactory cnfactory new rabbitmqclientconnectionfactory hostname localhost using iconnection cn cnfactorycreateconnection using imodel channel cncreatemodel channelexchangedeleteexchange name channelexchangedeclareexchange name direct true channelbasicreturn new basicreturneventhandlerchannel basicreturn for int i 0 i 100 i byte payload encodingasciigetbyteshello world i ibasicproperties channelprops channelcreatebasicproperties channelpropssetpersistenttrue channelbasicpublishexchange name routekey helloworld false false channelprops payload consolewritelinesent message i systemthreadingthreadsleep25 consolereadline clientnamespace rabbitlistener class program private const string exchange name helloworld static void mainstring args connectionfactory cnfactory new connectionfactory hostname localhost using iconnection cn cnfactorycreateconnection using imodel channel cncreatemodel channelexchangedeclareexchange name direct true string queuename channelqueuedeclaremyqueue true false false null channelqueuebindqueuename exchange name routekey helloworld consolewritelinewaiting for messages queueingbasicconsumer consumer new queueingbasicconsumerchannel channelbasicconsumequeuename true consumer while true basicdelivereventargs e basicdelivereventargsconsumerqueuedequeue consolewritelineencodingasciigetstringebody,['c#'] +209949,javaioioexception unable to parse response from server at getfromlocationname i know the question has been asked frequently before but i am unable to get the solution from any answer or search resultsi have to solve this issue asap i am trying to get the latitude and the longitude from the address enter by the user but i am continue getting javaioioexception unable to parse response from server i am using this code geocoder geocoder new geocoderthis localegetdefault string newaddress stringsaveasgettexttostring listaddress addresses geocodergetfromlocationnamenewaddress 1i tried a lot with different possible ways but nothing worksthe default map application works well when the user enter the address it shows sucessfully that address in the maphow can i do the samei have added all the required permissions and i am testing it on the real deviceversion 23,['android'] +209985,list of resources in a folder of jar file as usually i read resources from jar file as followinggetclassloadergetresourceptextpath plang xmli need to read all resources with certain name from known folder in jar file eg read xml from addonresourcestextscould i somehow get from jar files list of resources according to path and name templateupdate exact duplication of get a list of resources from classpath directory please close the question,['java'] +209990,android bluetooth connecting error im getting the follow messages in my stack trace i can find bluetooth devices but when i try to open the socket this happens1030 2308901 errorbtl cfg8633 warning servicebrcmbtinq filter bda property get failed 01030 2324585 errorbtld8633 search uuid 14541030 2324600 errorbluetootheventloopcpp2502 oncreatedeviceresult dbus error orgbluezerroralreadyexists device already exists1030 2324616 errordtun hcid48659 no device pointer found for peer ignore error true ignoring error1030 2326093 errordtun hcid48659 thiscovery unsuccessful1030 2330628 errorcachedbluetoothdevice18609 onuuidchanged time since last connect 1440232 minitiatedpairing false1030 2330632 errorcachedbluetoothdevice18609 onuuidchanged time since last connect1440236minitiatedpairingfalseeditthe socket attempts to open but doesnt an exception is thrown service thiscovery failed and then the socket is closed correctly,['android'] +210062,how to cast list to list when classb inherits from classa i deserialized json string to listclassb and now i want to cast it to listclassa before i return it from bindmodel method i need casting because the methods expects to get listclassawhy i get error while casting after all classb inherits from classa what should i dops this question is extended from this post in line new datacontractjsonserializertypeoflistclassb instead of listclassb the type will be constructed at runtime public override object bindmodel var serializer new datacontractjsonserializertypeoflistclassb memorystream ms new memorystreamencodingutf8getbytesid1namename var list serializerreadobjectms return listclassalist knowntypetypeofclassa datacontract public class classa public classa knowntypetypeofclassb datacontract public class classb classa datamembername id public int id get set datamembername name public string categoryname get set,['c#'] +210067,how do i get the value from objectstdclass using php i have to parse a string coming to my code in a format like thisobjectstdclass4 title string5 fruit color string6 yellow name string6 banana id int3 i am sure there is a simple solution but i cannot seem to find it how to get the color and namethanks so much,['php'] +210080,is there a name for this pattern of using generics this class or interface if you like is set up as genericpublic abstract class genericbaset public t performbasictaskt in but is intended to be inherited by objects that close the genericpublic class concretefordatesgenericbasedatetime public datetime performspecifictaskdatetime in so that consuming code never knows that a generic is involvedvar mydateconcrete new concretefordates look ma no gtpthese two methods look alike and there is no generic type inferenceeven with performbasictaskvar basicresult mydateconcreteperformbasictaskdatetimenowvar specificresult mydateconcreteperformspecifictaskdatetimetodaydoes not compile because t is understood by inheritance to be a datetimeeven though performbasictasks implementation may well handle an intvar anotherbasicresult mydateconcreteperformbasictask1i have seen and used this pattern several times and it is very useful for providing common functionality across a series of typespecific subclasses for instance this could be a model for controllerspresenters specific to a type of domain object that is central to the pages the class is used to control basic operations like retrievalpersistence may use 100 common functionality but bindingunbinding may be very specific is there a name for this pattern of generic declaration without exposing the generic to the end user,['c#'] +210086,how can i change the font open xml how can i change the font family of the document via openxml i tried some ways but when i open the document it is always in calibrifollow my code and what i triedthe header builder i think is useless to postprivate static void builddocumentstring filename liststring lista string tipo using wordprocessingdocument w wordprocessingdocumentcreatefilename wordprocessingdocumenttypedocument maindocumentpart mp waddmaindocumentpart documentformatopenxmlwordprocessingdocument d new documentformatopenxmlwordprocessingdocument body b new body documentformatopenxmlwordprocessingparagraph p new documentformatopenxmlwordprocessingparagraph run r new run get and format the text for int i 0 i listacount i text t new text ttext listai if ttext rappendnew carriagereturn else rappendt rappendnew carriagereturn what i tried runproperties rpr new runproperties new runfonts ascii arial listaclear pappendr bappendp headerpart hp mpaddnewpartheaderpart string headerrelationshipid mpgetidofparthp sectionproperties sectpr new sectionproperties headerreference headerreference new headerreference headerreferenceid headerrelationshipid headerreferencetype headerfootervaluesdefault sectprappendheaderreference bappendsectpr dappendb customize the header if tipo alugar hpheader buildheaderhp anaoncio aluguel de ima3vel else if tipo vender hpheader buildheaderhp anaoncio venda de ima3vel else hpheader buildheaderhp aluguelvenda de ima3vel hpheadersave mpdocument d mpdocumentsave wclose,['c#'] +210107,plupload restrict to only one file i do not see an option in the plupload api docs on restricting the number of files uploaded to any number even 1doc fail or feature fail if it does not exist i will be working on making that happen if anyone needs it,['javascript'] +210108,ruby 193 breaks rake test i have an existing rails 3 project that works just fine on ruby 192p290 however upgrading to ruby 193p0 causes rake test to spit out the following erroruserszmanjirbenvversions193p0libruby191testunitrb167in block in non options file not found testunit testrb argumenterrorfrom userszmanjirbenvversions193p0libruby191testunitrb146in mapfrom userszmanjirbenvversions193p0libruby191testunitrb146in non optionsfrom userszmanjirbenvversions193p0libruby191testunitrb207in non optionsfrom userszmanjirbenvversions193p0libruby191testunitrb52in process argsfrom userszmanjirbenvversions193p0libruby191minitestunitrb891in runfrom userszmanjirbenvversions193p0libruby191minitestunitrb884in runfrom userszmanjirbenvversions193p0libruby191testunitrb21in runfrom userszmanjirbenvversions193p0libruby191testunitrb326in block 2 levels in autorunfrom userszmanjirbenvversions193p0libruby191testunitrb27in run oncefrom userszmanjirbenvversions193p0libruby191testunitrb325in block in autorunuserszmanjirbenvversions193p0libruby191testunitrb167in block in non options file not found testfunctional testrb argumenterrorfrom userszmanjirbenvversions193p0libruby191testunitrb146in mapfrom userszmanjirbenvversions193p0libruby191testunitrb146in non optionsfrom userszmanjirbenvversions193p0libruby191testunitrb207in non optionsfrom userszmanjirbenvversions193p0libruby191testunitrb52in process argsfrom userszmanjirbenvversions193p0libruby191minitestunitrb891in runfrom userszmanjirbenvversions193p0libruby191minitestunitrb884in runfrom userszmanjirbenvversions193p0libruby191testunitrb21in runfrom userszmanjirbenvversions193p0libruby191testunitrb326in block 2 levels in autorunfrom userszmanjirbenvversions193p0libruby191testunitrb27in run oncefrom userszmanjirbenvversions193p0libruby191testunitrb325in block in autorunit seems to be a consequence of this rake issue however when i create a simple rails project on ruby 193 so such error occurs what can i do to get my rails project to run on ruby 193,['ruby'] +210141,adding author name in eclipse automatically to existing files is there a real easy to use tool no monster tool that i can plug into eclipse and press a generate header button and then the authors name appears in every file in that project,['java'] +210151,restkit returning 0 objects in objectloader didloadobjects so i am trying to get back an array of leaderboard objects from a database using rest calls didloadobjects returns 0 objects even though the mapping seems correct rkobjectmanager svc rkobjectmanager sharedmanager nsstring resourcepath leaderboardresourcepath rkobjectmapping mapping svcmappingprovider objectmappingforclassleaderboard class rkobjectloader loader rkobjectmanager sharedmanager loadobjectsatresourcepathresourcepath objectmappingmapping delegateselfhere is the didloadobjects method voidobjectloaderrkobjectloaderobjectloader didloadobjectsnsarrayobjects if objectloaderresourcepath isequaltostringleaderboardresourcepath synchronizedstandings standings objects here is the mapping code voidsetmappings standings mapping rkobjectmapping leaderboardmapping rkobjectmapping mappingforclassleaderboard class leaderboardmapping mapkeypathuname toattributeuname leaderboardmapping mapkeypathgeo toattributegeo leaderboardmapping mapkeypathweek toattributeweek leaderboardmapping mapkeypathyear toattributeyear leaderboardmapping mapkeypathpts toattributepts rkobjectmanager sharedmanagermappingprovider addobjectmappingleaderboardmapping rkobjectrouter router rkobjectmanager sharedmanagerrouter define a default resource path for all unspecified http verbs router routeclassleaderboard class toresourcepathleaderboardresourcepath updatei found out that the problem is with the geo object in the mappings the geo object consists of three fields each of which also need to be mapped here is the mapping for the geo object voidsetmappings standings mapping rkobjectmapping geomapping rkobjectmapping mappingforclassgeo class geomapping mapkeypathlat toattributelat geomapping mapkeypathlng toattributelng geomapping mapkeypathplace toattributeplace rkobjectmanager sharedmanagermappingprovider addobjectmappinggeomapping rkobjectmanager sharedmanagermappingprovider setmappinggeomapping forkeypathgeo voidinitialize super initialize if self class geo class self setmappings this causes the didloadobjects to correctly pass back the objects but the geo object of the leaderboard object still comes back null thoughts,"['iphone', 'ios']" +210154,cookie page counter in php i am implementing a php page counter that will keep track of each time the user visits this page until the browser is closed i am checking to see if the cookie is set if it is then i am increment it and reset its value but the problem i am having is that the counter is always at two why is thishtml head titlecount page accesstitle head body php if isset cookiecount welcome this is the first time you have viewed this page php cookie 1 setcookiecount cookie else cookie cookiecount setcookiecount cookie you have viewed this page cookiecount times php end else body htmledit thanks everyone i did the pre increment thing and got it to work,['php'] +210180,how can i print all unicode characters i want to print some unicode characters but uu10 up to uu1099 this does not workfor i in range101100 sunicodeustri print is,['python'] +210188,how to increment a referenced variable by 1 i am new to c and i am trying to increase cars starting with value 50 but only increase by one if the youdamage is greaters than cardamage i want cars to hold its value for the next time it does through the loop i hope this makes senseint power int carint main int car 50 int cardamage 0 int yourdamage 0 pick a random number between 1 to 50 yourdamage 0 rand 50 0 1 cardamage 0 rand 50 0 1 cout you hit the car and cause damage of cardamage endl cout the car hits you and causes damage of yourdamage endl cout endl ifcardamage yourdamage cout you win endl cout you gain strength endl cout endl int car car 1 else,['c++'] +210215,writing to event log in c do i need to use eventlogcreateeventsource when writing to application log when i use the following code to write to application event log everything works fineeventlog log new eventloglogsource applicationlogwriteentrytest message eventlogentrytypeerrorwhen i use the code that is from msdn and all other blogs i get the security error i am guessing because createeventsource raises itstring ssource mywebservicestring slog myapplicationstring smsg errormessageif eventlogsourceexistsource eventlogcreateeventsourcessource slog eventlogwriteentryssource smsg eventlogentrytypeerror so do i need to check whether the source exists if all i need is to write to application log which is there by default what is the proper way to write to eventviewer,['c#'] +210227,objectivec create text file on device and easily retrieve the file i am wanting to write my own logs to a text file on my iphone i wrote up a quick method that writes a string to a file right now it saves it into the documents directory which if on the device is going to be a pain to get off since i cannot just browse to it is there a better way to quickly get this file off the device after i have written to it logs a string to file version revision 01 voidlogwithstringnsstring string create the file nserror error directory nsstring documentsdirectory nshomedirectory stringbyappendingpathcomponentdocuments nsstring filepath documentsdirectory stringbyappendingpathcomponentlogtxt get the file contents nsdata localdata nsdata datawithcontentsoffilefilepath if localdata nsstring logstring nsstring alloc initwithdatalocaldata encodingnsutf8stringencoding string logstring stringbyappendingformatn string logstring release write to the file string writetofilefilepath atomicallyyes encodingnsutf8stringencoding errorerrorend,"['iphone', 'objective-c', 'ios']" +210230,how to organize code for a flask application with multiple set of templates i am writing an application with flask and i would like to generate different code for desktop and mobile browsers imho it should be a good idea to keep the application code identical and push the problem of serving different content down the stack at the template level so it essentially becomes a matter of writing two sets of templates for the two use cases and finding a way to choose the correct one to use at every single requesti am using the default jinja2 template engine with flaski should mention that i have no experience with flask and i am learning my way through it while i write code i am taking this as an exercise too what mechanism would you use to address this problem and keep source code as clean as possible,['python'] +210232,parsing of a string containing an array i would like to convert string containing recursive array of strings to an array of depth oneexamplestringtoarraya b c d e f g h i a b c d e f g h iseems quite simple but i come from functional background and i am not that familiar with net framework standard libraries so every time i started from scratch like 3 times i end up just plain ugly code my latest implementation is here as you see it is ugly as hellso whats the c way to do this,['c#'] +210236,ios delete button objective c i was wondering where does one get access to ios delete button this is the button that apple uses to close the iad window and for deleting iphone apps from the home screen and also the twitter app uses it to delete the photo that you add to a tweet do they just download this image somewhere or is there an option for it somewhere like for the info button and the detail thisclosurethanksi also found that growl uses this icon along with lions mission control,"['iphone', 'objective-c', 'ios']" +210238,i18n with jinja2 gae i googled for a gae jinja i18n example but could not find it can anyone provide a link or working examplemy effort uses the django translations and i do not know if this is the recommend way of doing itimport jinja2from djangoutils import translationfrom djangoutilstranslation import gettext ngettext ugettext ungettext get language activateclass djangotranslatorobject def init self selfgettext gettext selfngettext ngettext selfugettext ugettext selfungettext ungettextfrom jinja2 import environment filesystemloaderclass djangoenvironmentjinja2environment def get translatorself context return djangotranslatorjinja environment djangoenvironment loaderjinja2filesystemloaderospathdirname file extensionsjinja2exti18njinja environmentinstall gettext translationstranslationthanks for any hint or advice i also use a custom request handler for i18nfrom djangoutils import translationclass i18nhandlerwebapp2requesthandler def render templateself file template args path ospathjoinospathdirname file templates file selfresponseoutwritetemplaterenderpath template args def initializeself request response webapp2requesthandlerinitializeself request response selfrequestcookies cookiesself selfrequestmeta osenviron selfreset language def reset languageself decide the language from cookiesheaders language translationget language from requestselfrequest translationactivatelanguage selfrequestlanguage code translationget language set headers in response selfresponseheaderscontentlanguage strtranslationget language,['python'] +210239,what does this gdb output mean i have got a button that plays a sound and it seems to work perfectly fine on the simulator but i am getting this messageerror loading systemlibraryextensionsaudioipcdriverkextcontentsresourcesaudioipcpluginbundlecontentsmacosaudioipcplugin dlopensystemlibraryextensionsaudioipcdriverkextcontentsresourcesaudioipcpluginbundlecontentsmacosaudioipcplugin 262 symbol not found cfobjciscollectable referenced from systemlibraryframeworkssecurityframeworkversionsasecurity expected in developerplatformsiphonesimulatorplatformdevelopersdksiphonesimulator50sdksystemlibraryframeworkscorefoundationframeworkcorefoundation in systemlibraryframeworkssecurityframeworkversionsasecurity20101 021302605 halloween fx3348410703 error loading systemlibraryextensionsaudioipcdriverkextcontentsresourcesaudioipcpluginbundlecontentsmacosaudioipcplugin dlopensystemlibraryextensionsaudioipcdriverkextcontentsresourcesaudioipcpluginbundlecontentsmacosaudioipcplugin 262 symbol not found cfobjciscollectable referenced from systemlibraryframeworkssecurityframeworkversionsasecurity expected in developerplatformsiphonesimulatorplatformdevelopersdksiphonesimulator50sdksystemlibraryframeworkscorefoundationframeworkcorefoundation in systemlibraryframeworkssecurityframeworkversionsasecurity20101 021302657 halloween fx3348410703 error loading systemlibraryextensionsapplehdakextcontentspluginsapplehdahalpluginbundlecontentsmacosapplehdahalplugin dlopensystemlibraryextensionsapplehdakextcontentspluginsapplehdahalpluginbundlecontentsmacosapplehdahalplugin 262 symbol not found cfobjciscollectable referenced from systemlibraryframeworkssecurityframeworkversionsasecurity expected in developerplatformsiphonesimulatorplatformdevelopersdksiphonesimulator50sdksystemlibraryframeworkscorefoundationframeworkcorefoundation in systemlibraryframeworkssecurityframeworkversionsasecurity20101 021302671 halloween fx3348410703 error loading systemlibraryextensionsapplehdakextcontentspluginsapplehdahalpluginbundlecontentsmacosapplehdahalplugin dlopensystemlibraryextensionsapplehdakextcontentspluginsapplehdahalpluginbundlecontentsmacosapplehdahalplugin 262 symbol not found cfobjciscollectable referenced from systemlibraryframeworkssecurityframeworkversionsasecurity expected in developerplatformsiphonesimulatorplatformdevelopersdksiphonesimulator50sdksystemlibraryframeworkscorefoundationframeworkcorefoundation in systemlibraryframeworkssecurityframeworkversionsasecurity20101 021302706 halloween fx3348410703 error loading systemlibraryextensionsapplehdakextcontentspluginsapplehdahalpluginbundlecontentsmacosapplehdahalplugin dlopensystemlibraryextensionsapplehdakextcontentspluginsapplehdahalpluginbundlecontentsmacosapplehdahalplugin 262 symbol not found cfobjciscollectable referenced from systemlibraryframeworkssecurityframeworkversionsasecurity expected in developerplatformsiphonesimulatorplatformdevelopersdksiphonesimulator50sdksystemlibraryframeworkscorefoundationframeworkcorefoundation in systemlibraryframeworkssecurityframeworkversionsasecurity20101 021302715 halloween fx3348410703 error loading systemlibraryextensionsapplehdakextcontentspluginsapplehdahalpluginbundlecontentsmacosapplehdahalplugin dlopensystemlibraryextensionsapplehdakextcontentspluginsapplehdahalpluginbundlecontentsmacosapplehdahalplugin 262 symbol not found cfobjciscollectable referenced from systemlibraryframeworkssecurityframeworkversionsasecurity expected in developerplatformsiphonesimulatorplatformdevelopersdksiphonesimulator50sdksystemlibraryframeworkscorefoundationframeworkcorefoundation in systemlibraryframeworkssecurityframeworkversionsasecurity20101 021302732 halloween fx3348410703 error loading systemlibraryextensionsapplehdakextcontentspluginsapplehdahalpluginbundlecontentsmacosapplehdahalplugin dlopensystemlibraryextensionsapplehdakextcontentspluginsapplehdahalpluginbundlecontentsmacosapplehdahalplugin 262 symbol not found cfobjciscollectable referenced from systemlibraryframeworkssecurityframeworkversionsasecurity expected in developerplatformsiphonesimulatorplatformdevelopersdksiphonesimulator50sdksystemlibraryframeworkscorefoundationframeworkcorefoundation in systemlibraryframeworkssecurityframeworkversionsasecurity20101 021302741 halloween fx3348410703 error loading systemlibraryextensionsapplehdakextcontentspluginsapplehdahalpluginbundlecontentsmacosapplehdahalplugin dlopensystemlibraryextensionsapplehdakextcontentspluginsapplehdahalpluginbundlecontentsmacosapplehdahalplugin 262 symbol not found cfobjciscollectable referenced from systemlibraryframeworkssecurityframeworkversionsasecurity expected in developerplatformsiphonesimulatorplatformdevelopersdksiphonesimulator50sdksystemlibraryframeworkscorefoundationframeworkcorefoundation in systemlibraryframeworkssecurityframeworkversionsasecurityand i have had reports saying on some devices it is not playing at all,"['objective-c', 'ios']" +210241,jquery clone table row i have a table with an add button on the end when you click this button i want a new table row to be created underneath the current one i also want the input fields on this row to be blank i am trying to do this using clone but it clones all the rows on the page please help thanksscriptinputtr clone add liveclick function thisclosesttr clone clone insertaftertr clone htmltable width100 border0 cellspacing0 cellpadding0 idtabledatatrtdnametdtdlocationtdtdfromtdtdtotdtdaddtdtrtr classtr clonetdinput typetext autofocus placeholderwho namewho tdtdinput typetext autofocus placeholderlocation namelocation tdtdinput typetext placeholderstart date namedatepicker start classdatepickertdtdinput typetext placeholderend date namedatepicker end classdatepickertdtdinput typebutton nameadd valueadd classtr clone addtdtrtable tabletabledata,['jquery'] +210322,c serialize generic list to file i got a class which holds info about pictures like filepath hashvalue bytesin another class i got a generic list where i put objects from the class that holds picture infothat class looks like thisserializable class picinfo iserializable public string filename get set public string completefilename get set public string filepath get set public byte hashvalue get set public picinfo public picinfoserializationinfo info streamingcontext ctxt thisfilename stringinfogetvaluefilename typeofstring thiscompletefilename stringinfogetvaluecompletefilename typeofstring thisfilepath stringinfogetvaluefilepath typeofstring thishashvalue byteinfogetvaluehashvalue typeofbyte public void getobjectdataserializationinfo info streamingcontext ctxt infoaddvaluefilename thisfilename infoaddvaluecompletefilename thiscompletefilename infoaddvaluefilepath thisfilepath infoaddvaluehashvalue thishashvalue my list is just listpicinfo pi new listpicinfowhat would be the eaziest way to serialize this list,['c#'] +210326,using stdshared ptr with clang and libstdc i am trying to use the stdshared ptr in clangclang version 31 trunk 143100 using libstdc461 i have a little demo programinclude memoryint main stdshared ptrint somenew int stdshared ptrint othersome return 0which can be build usingclang stdc0x o main maincppand gives the following error outputmaincpp623 error call to deleted constructor of stdshared ptrint stdshared ptrint othersome usrincludec46bitsshared ptrh9311 note function has been explicitly markeddeleted hereclass shared ptr public shared ptr tpfor some reason it needs the constructor which is deleted because a move constructor is provided which is correct behaviourbut why does it work compile with g ubuntulinaro 4619ubuntu3 461 somebody any ideas on how to fix this,['c++'] +210336,projectproperties file instead of defaultproperties file i stumbled across something i cannot figure out myself i have an android project with a reference to a library project now the weird thing is that it seems like my defaultproperties file is no longer needed android creates a projectproperties file so my questions is what is the difference between the two is not a projectproperties file standard java and defaultproperties android specific what do they do exactly,['android'] +210346,how to audit a java ee project i have to audit the codearchitecture quality and maintainability in the end to be sure we have what we paid for a java ee web project based on jsfcdiejb30jpa just to name some of the technologies involvedthis may not be the right place to ask but how do you deal with this kind of taskbasically i would proceed from coarsegrained to finegrained ie from the whole architecture to the java code is it better to deal with each layer completelyshould i spend more time on the lowlevel layersdo you assess the whole thing build deployment test,['java'] +210361,put and get string array from shared preferences i need to save on shared preferences some array of strings and after that to get them i tried this prefseditorputstringplaylists playliststostring where playlists is a stringand to get playlist myprefsgetstringplaylists playlists where playlist is a string but it is not workinghow can i do this can anyone help methanks in advance,['android'] +210376,ie9 text input with padding issue in ie9 i do not know about older versions but first i need a solution for the scenario in ie9 the last letters in an input typetext thisappear behind the right padding if so existsplease take a look at this fiddle in ie9 does anyone have a solution to this problemthanks,['css'] +210377,is the textual order across partial classes formally defined specifically in relation to field initializers in this case static a1711 in ecma 334if a class contains any static fields with initializers those initializers are executed in textual order immediately prior to executing the static constructornow if we have multiple partial classes in separate files is that order determined anywhere my gut says not formally defined but probably relates to the order included in the csproj or the order noted to csc is this correctand yes i realise it would be better to avoid the ambiguity completely probably by moving all the initialization to a static constructorfor example if i have acsusing systempartial class program private static int foo writefoo static int writestring name consolewritelinename return 0 static void main consolewritelinepress any key consolereadline and bcspartial class program private static int bar writebarandcompile includeacs compile includebcs then this is foo then bar if however this iscompile includebcs compile includeacs then it is bar then foo this supports the observation but does not state it strongly a8713 partial type declarations makes no comment on the order when combining partial classes so is there anything stronger we can say here either from the c language spec or from the tooling documentationadditionally it behaves similarly with csc acs bcs vs csc bcs acs,['c#'] +210403,how to set the default value to the drop down list control i have a drop down list control on my web page i have bind the datatable to the dropdownlist control as follows lstdepartmentdatatextfield departmentname lstdepartmentdatavaluefield departmentid lstdepartmentdatasource dtdept lstdepartmentdatabindin the page load event i want to set the default value to the drop down list control from my other table fieldhow to do this,"['c#', 'asp.net']" +210412,jslint and bookmarklets i am running jslint checks in rhino using jslintantjs i found something a bit strange and was wondering if i could gets some input from other programmers basically the following line gets a jslint script url errorvar a a hrefjavascriptalerti am a bookmarklet drag me to your toolbaraerrorlint at line 124 character 35 script urli have gone into the code that douglas crockford wrote in fulljslintjs and found that indeed he is testing for this as follows javascript urljx javascriptjscriptecmascriptvbscriptmochalivescriptsiso given this constraint and the fact that drag and drop bookmarklets only use the href attribute of the a tag how are we meant to dynamically create bookmarklets that pass a jslint testthanks for your input,['javascript'] +210432,how to apply dynamic alpha mask to a text on android i want to make a dynamic alpha mask with drawable shapes as circles or whatever and apply it to a drawed text on androidhere is an example of what i want i am trying to make it with setxfermodenew porterduffxfermodemodesrc in but i cannot get it workhere is the code i have in ondrawcanvas canvas method paint paint new paintpaintsetantialiastruecanvasdrawargb0 0 0 0paintsetcolorcolorwhitecanvasdrawcircle50 50 50 paintpaintsetxfermodenew porterduffxfermodemodesrc inpaintsetcolorcolorredcanvasdrawtexthello 0 50 paintthanks in advance for your help,['android'] +210444,how to register an android developer account for a company i am trying to register an android developer account for our company that well use to publish our companys apps to the market so we do not want a account which is bound to a single developer but this statement which is thisplayed before paying the fee of 25 let me wonder if a developer account can be associated with a company at all your registration fee enables you to publish software in the market the name and billing address used to register will bind you to the android market developer thistribution agreement so make sure you double checkif i understand this correctly then this means that the person whose credit card is used to pay the fee will be the person how accept the developer agreement and therefore will be legal responsible for the apps that are published under this account if this is correct then this is not exactly what we want as we cannot make one of our developer personal legal responsible for the companys product so what are our options to avoid this how could the account be legally bound to the company instead or did we miss understand the whole statement,['android'] +210456,attributesaddclass classname but preserve existing class simple thing well i think it isi need to add a class to an element within an asprepeater under certain conditions using vbso i can doitemidattributesaddclass classtoaddbut this removes the existing classes and therefore screws up my css itemidattributesclass classtoaddseems to do the same thinghow do i add a class to an element whilst preserving it is existing class values,['css'] +210464,outsidein bdd with specflow i am new to bdd but i found it very interesting and want to develop my next project using bdd after googling and watching screencasts i still have lots of questions about bdd in real life1 declarative or imperative scenariosmost of givenwhenthen scenarios i saw were written in terms of ui imperativescenario login given i am on the loginpage when i enter auser in the textbox username and i enter apassword in the textbox password and i click the login button then i should see the following text you are logged ini found those tests extremely brittle and they tell nothing about business value of clicking on buttons i think its nightmare to maintain why most of examples use imperative scenarios scenario login declarative given i am not logged in when i log in using valid credentials then i should be logged inif you prefer declarative style how do you describe such stuff like home page or products pagetips for writing good specifications2 exercise ui or notmost of steps implementations i saw used watin white or something like that to implement scenarios from user point of view starting browser clicking buttons i think its extremely slow and brittle well i can use something like page object to make tests less brittle but thats another amount of work especially for desktop applications with complex uihow do you implement scenarios in reallife projects exercising ui or via testing controllerspresenters best way to apply bdd3 real database or notwhen given part of scenario is implemented often it needs some data to be in the system eg some products for shop application how do you implement that part adding data to real database full endtoend testing or providing repository stubs to controllerswaiting for experienced answersupdate added useful links on questions,['c#'] +210471,apache mod wsgi interaction before posting this i have read quite a few resources online including the mod wsgi wiki but i am confused about how exactly apache processesthreads interact with mod wsgi this is my current understanding apache can be configured to run such that one or more child processes can handle incoming requests and each of these child processes can be configured to in turn use one or more threads to service requests after that things start getting hazy for me my doubts arewhat is a wsgidaemonprocess and who actually calls my django app using the python sub interpreterif i have my django app running under a mode where multiple threads are allowed in a single apache child process does that mean that multiple requests could be simultaneously accessing my app at the same time if so would doing something like setting a module level variable say that of an users id could be overwritten by other parallel requests and lead to nonthread safe behaviorfor the case above with pythons global interpreter lock would the threads actually be executing in parallel,['python'] +210491,pythonpath not working for sudo on gnulinux works for root edit works for root sudo is the problem read belowi have a directory with my own libraries eg my python libraries are located at homenamelibpyi have added this directory to pythons path for all users including root by adding the following line to etcbashbashrcexport pythonpathpythonpathhomenamelibpyit works for all users including root but it does not work for sudo is there any way i can make sudo use etcbashbashrcedit more informationi have added pythonpath to sudoers file like so defaults env keep home pythonpath it sitll does not workenv grep python pythondontwritebytecode1 pythonpathhomenamelibpysudo env grep python pythondontwritebytecode1sudo echo pythonpath homenamelibpy,['python'] +210505,in python how can i ensure that one of my clas methods is always called even if a subclass overrides it for example i have aclass basehandlerobject def prepareself selfprepped 1i do not want everyone that subclasses basehandler and also wants to implement prepare to have to remember to callsupersubbasehandler selfprepareis there a way to ensure the superclass method is run even if the subclass also implements prepare,['python'] +210516,jquery selector for attributes that does not begin with a string selector starting with namevalue selects elements that have the specified attribute with a value beginning exactly with a given stringis there a negative of this like sonamevaluewhich selects elements that have the specified attribute with a value not beginning with a given string,['jquery'] +210518,c countdown timer i am trying to make a countdown using c and show the time in format hourminutessecondsi have tried this var minutes 3 countdown time var start datetimenow var end datetimenowaddminutesminutes threadsleep1800 if i tried datetimenow end not works show time label1text else done label1text done different ways to solve this problem also appeared thanks in advance,"['c#', '.net']" +210530,switch android profiles programmatically is is possible somehow programmatically switch built in android profiles i was planning to write yet another profile app but actually built in profiles are more than enough for my needs i just would need to switch them automated way,['android'] +210536,shorthand byte notation in cc it is been awhile since i programmed in cc for the life of me i cannot remember or find in google how to make this work i thought there was a shorthand way of writing a repeating string of bytes like this0x00 0x0xff 0xf0xcd 0xcdcdcdcdso for example if i declareint x 0xcdprintfd x prints 3452816845 not 205without using bitshifts ie the preprocessor handles it am i going crazy ps i am using microsoft visual c 2010,"['c++', 'c']" +210552,dynamic parameters in abstract methods in php if i have a classabstract class parent abstract function fooclass child extends parent function fooparam stuff i get an error because the abstract declaration does not have any parameters but the childs implementation of it does i am making an adapter parent class with abstract functions that when implemented could have a variable amount of parameters depending on the context of the child class is there any structured way i can overcome this or do i have to use func get args,['php'] +210565,jquery mobile change theme on click i have got a basic list with the theme a i am trying to find a way to change the theme when clicking on a button have tried a liattrdatathemea combined with list refresh with no luck an success out there,['jquery'] +210566,guid is all 0s zeros i am testing out some wcf services that send objects with guids back and forth in my web app test code i am doing the followingvar responseobject proxycallservicenew requestobject data misc data guid new guidfor some reason the call to new guid is generating guids with all 0s zeros like this0what could be causing this,"['c#', '.net']" +210576,how do i find all the points in a path in android awhile back i asked a question to see if i was able to find a pair of specific points in a path however this time i want to know if there is a way to know all points in a path i could not find a method that did so which is unfortunate because java provides a way to do this just not androidthe reason i ask this is because i have multiple geometric graphs and i want to compare the points to see where they intersecti appreciate any helpful responses,"['java', 'android']" +210589,android can sqlite cursors be used after closing the database first of all correct me if i am wrong but if you close a database connection you cannot use the cursor you got from it correctdbopencursor c dbquerytrue mytable columns null null null null null nulldbclose the cursor is empty now because the db was closedcmovetonextlogvtag ctostring0so is it there any way to use the cursor after closing the database like is there any way to pass it elsewhere and use it kinda like an object or do you always have to leave the database connection open until you are done with the cursor,"['java', 'android']" +210596,does android work with jre 7 does android work with jre 7 i cannot find any documentation on it,"['java', 'android']" +210611,urlencode only the directory and file names of a url i need to url encode just the directory path and file name of a url using phpso i want to encode something like name and have it result in of course if i do urlencode name then i end up with http3a2f2fexamplecom2ffilenamethe obvious to me anyway solution is to use parse url to split the url into scheme host etc and then just urlencode the parts that need it like the path then i would reassemble the url using http build url is there a more elegant solution than that or is that basically the way to go,['php'] +210615,jquery find nearest i needed to find the nearest element relative to another elementi wanted a generic function not locked to a spesific tree structuremaybe it already exists within jquery and if so please show mehere is what i came up with and it works for what i neededfnnearest functions var o var p thisparent whileplength ifpfindslength o pfindsfirst break else p pparent return ochris,['jquery'] +210621,safe cross platform coroutines all coroutine implementations i have encountered use assembly or inspect the contents of jmp buf the problem with this is it inherently not cross platformi think the following implementation does not go off into undefined behavior or rely on implementation details but i have never encountered a coroutine written like thisis there some inherent flaw is using long jump with threadsis there some hidden gotcha in this codeinclude setjmphinclude threadclass coroutinepublic coroutine void m done false m thread thisstart coroutine void stdlock guardstdmutex lock m mutex m done true m conditionnotify one m threadjoin void start void if setjmp m resume 0 stdunique lockstdmutex lock m mutex m conditionwait lock return m done else routine longjmp m yield 1 void resume void if setjmp m yield 0 longjmp m resume 1 void yield void if setjmp m resume 0 longjmp m yield 1 private virtual void routine void 0 jmp buf m resume jmp buf m yield bool m done stdmutex m mutex stdcondition variable m condition stdthread m thread,['c++'] +210633,how do i open a users twitter profile using the twitter app using a link in mobile safari it looks like twitter registers the uri scheme of twitter but after playing around with it i cannot get it to directly open a users profile i have triedtwitterusernametwitteruserusernametwitterprofileusernamewith no luck i will need it to work on android as wellthoughts,"['iphone', 'ios']" +210711,deleting embedded documents with mongoid i am building my first app with mongoid and am having trouble deleting an embedded resource i have these modelsclass article include mongoiddocument field body embeds many commentsetcclass comment include mongoiddocument field body embedded in article inverse of commentsendi do not understand why i cannot delete a comment from an article ruby192p290 043 articlecomments comment id 4eb0e991a27d201ded038 type nil body foo score nil ruby192p290 045 articlecommentsfirstdestroy true ruby192p290 046 articlecomments ruby192p290 047 articlesave true ruby192p290 049 articlereload article id 4eb0e991a27d201ded037 type nil body foo title ruby192p290 050 articlecomments comment id 4eb0e991a27d201ded038 type nil body foo score nil calling destroy or delete on the embedded document appears to delete it in memory but not from the db any insight would be very much appreciated,['ruby-on-rails'] +210718,should i always finish one activity before going to another do you always call finish on some activity before going to another activityfor example in order to prevent user going to the previous activity via mobile back button some people suggest that you should finish all activities except the main one this way the back button always returns you to the main activity or any other activity you think a user should be navigated this is done by overriding back button behaviour bad thing of this is when there is a dialog run from the handler which try to runs after the activity finished what is your rule of thumb on this issue call finish in some smarter way or overriding back button to direct user to page of your choice,['android'] +210747,why i already installed pywin32 lib but still got importerror no module named win32comclient i already installed the python for windows extensions library from herebut when i import the win32comclient in my program i still got the error message of importerror no module named win32comclientmy python version is 32thx in advance,['python'] +210748,whats a portable way to implement noop statement in c one in a while there is a need for a noop statement in c for example when implementing assert which is thisabled in nondebug configuration also see this questionifdef debugdefine assertx if x throwexcepion file line else noop here elsedefine assertx noop hereendifso far i am under impression that the right way is to use void0 for a noopvoid0however i suspect that it might trigger warnings on some compilers something like c45 expression has no effect expected expression with sideeffect visual c warning that is not emitted for this particular case but is emitted when there is no cast to voidis it universally portable is there a better way,['c++'] +210758,what scalability issues are associated with networkx i am interested in network analysis on large networks with millions of nodes and tens of millions of edges i want to be able to do things like parse networks from many formats find connected components detect communities and run centrality measures like pageranki am attracted to networkx because it has a nice api good documentation and has been under active development for years plus because it is in python it should be quick to develop within a recent presentation the slides are available on github here it was claimed thatunlike many other tools nx is designed to handle data on a scale relevant to modern problemsmost of the core algorithms in nx rely on extremely fast legacy codethe presentation also states that the base algorithms of networkx are implemented in cfortranhowever looking at the source code it looks like networkx is mostly written in python i am not too familiar with the source code but i am aware of a couple of examples where networkx uses numpy to do heavy lifting which in turn uses cfortran to do linear algebra for example the file networkxnetworkxalgorithmscentralityeigenvectorpy uses numpy to calculate eigenvectorsdoes anyone know if this strategy of calling an optimized library like numpy is really prevalent throughout networkx or if just a few algorithms do it also can anyone describe other scalability issues associated with networkxreply from networkx lead programmeri posed this question on the networkx mailing list and aric hagberg repliedthe data structures used in networkx are appropriate for scaling to large problems eg the data structure is an adjacency list the algorithms have various scaling properties but some of the ones you mention are usable eg pagerank connected components are linear complexity in the number of edgesat this point networkx is pure python code the adjacency structure is encoded with python dictionaries which provides great flexibility at the expense of memory and computational speed large graphs will take a lot of memory and you will eventually run outnetworkx does use numpy and scipy for algorithms that are primarily based on linear algebra in that case the graph is represented copied as an adjacency matrix using either numpy matrices or scipy sparse matrices those algorithms can benefit from the legacy c and fortran code that is used under the hood in numpy and scipy,['python'] +210767,how to read location only once with locationmanager gps and network provider and not any more looking for updates of location how to read location only once with locationmanager gps and network provider and not any more looking for updates of location to save battery,['android'] +210774,is there a way to get address book contact ids from sync services contact ids when getting the modified contacts from sync services through the applychangeforentitynameremappedrecordidentifierformattedrecorderror method the ids in the address book are of the form 2c13e20e6b24409081fa7a1e8b28119b and even though some ids of this kind are present in the isyncchange object those are not actual contact ids that can be found in the address bookis there a way to find out from sync services what a certain contacts id is in the address bookthe reason for asking is that when saving large pictures for contacts in the address book sync services does not save those pictures in their internal data storage therefore contacts that have been modified or added with a large picture will be returned by sync services without the picture basically offering incomplete informationi need to get the address book id so that i can look up the contacts picture in libraryapplication supportaddress bookimagesthanks,['objective-c'] +210775,android cloning a drawable in order to make a statelistdrawable with filters i am trying to make a general framework function that makes any drawable become highlighted when pressedfocusedselectedetcmy function takes a drawable and returns a statelistdrawable where the default state is the drawable itself and the state for androidrattrstate pressed is the same drawable just with a filter applied using setcolorfiltermy problem is that i cannot clone the drawable and make a separate instance of it with the filter applied here is what i am trying to achievestatelistdrawable makehighlightabledrawable drawable statelistdrawable res new statelistdrawable drawable clone drawableclone how do i do this clonesetcolorfilter0xf0 porterduffmodemultiply resaddstatenew int androidrattrstate pressed clone resaddstatenew int drawable return resif i do not clone then the filter is obviously applied to both states i tried playing with mutate but it does not helpany ideasupdatethe accepted answer indeed clones a drawable it did not help me though because my general function fails on a different problem it seems that when you add a drawable to a statelist it loses all its filters,['android'] +210826,how do i dynamically insert an svg image into html i have some code that retrieves a scripted svg image from a server via ajax i can get the image text back into the browser but i cannot find a way to insert it into the dom that will actually thisplay it can anyone help with thisthe svg looks likes thissvg idchart xmlns xmlnsxlink onloadinitevtscript typeapplicationecmascriptcdatalots of code changes on each ajax requestscriptscript typeapplicationecmascript xlinkhrefjsonserver1jsscript typeapplicationecmascript xlinkhrefjsonserver2jssvgi have tried various things if i do this xmlhttponreadystatechangeaddimagexmlhttpresponsexml somewherefunction addimagetxt dst id var scr documentcreateelementdiv iftextcontent in scr scrtextcontent txt everybody else else scrtext txt ie documentgetelementbyiddst idappendchildscrthen opera and chrome do nothing and ff complains object xmldocument if i change responsexml to responsetext then operachrome correctly thisplay the entire svg text not image in the right place and ff still gives the same warningi have also tried assigning the response to an innerhtml but that does nothingany ideas thankseditin response to phrogzz answer below i have added two simple svg files the first is a standard simple svg thisplaying a circle the second is a scripted svg thisplaying a rectangle you should be able to view both directly in any browser except ie8if i edit phrogzz code to use the circle file replace stirling4svg with the name of this file then it works but if i want the scripted rectangle instead it does not tested on ff opera chromium but does not work anyway on my chromiumfile 1 circlesvg xmlns version11 circle cx100 cy50 r40 strokeblack strokewidth2 fillred svgfile 2 rectanglesvg xmlns xmlnsxlink onloadinitevtscript typeapplicationecmascriptcdatavar svgdocumentvar svgns function initevt ifwindowsvgdocument null svgdocument evttargetownerdocument var lbox svgdocumentcreateelementnssvgns rect lboxsetattributensnull x 10 lboxsetattributensnull y 10 lboxsetattributensnull width 30 lboxsetattributensnull height 30 lboxsetattributensnull stroke 8080ff lboxsetattributensnull strokewidth 2 lboxsetattributensnull fillopacity 0 lboxsetattributensnull strokeopacity 1 lboxsetattributensnull strokedasharray 0 svgdocumentdocumentelementappendchildlboxscriptsvgpresumably the answer is to get the script into the header,"['javascript', 'html']" +210828,jquery sortable drag and drop not showing move cursor im using this sortable function on my list my problem is that i want it to show the move cursor when the drag and drop is being used and the pointer cursor only on hover i have my css calling the cursorpointer on hover but it does not seem to show the move cursor at all everything else works fine code belowdoctype html public w3cdtd xhtml 10 transitionalen html xmlns head script typetextjavascript srcscript script typetextjavascript srcscript link relstylesheet href typetextcss link relstylesheet hrefblahcss typetextcss script typetextjavascript charsetutf8 documentreadyfunction sortablesortable helper clone tried this thistance 5 delay 300 opacity 06 cursor move update function script head body ul idsortable li classuistatedefaultitem 1li li classuistatedefaultitem 2li li classuistatedefaultitem 3li ul body htmlseperate css doc containssortable liststyletype none margin 0 padding 0 width 60 sortable li margin 0 3px 3px 3px padding 04em paddingleft 15em fontsize 11em lineheight 18px height 18px sortable li span position absolute marginleft 13em heres the important stuff sortable lihover cursor pointersortable liuisortablehelper cursor moveany help would be greatly appreciated thanks in advance perhaps a little more information its a db populated list from a while statement each list item is a link so i want it to thisplay the cursor pointer option but when it is dragged i need it to thisplay the cursor move i would have thought that the code above would do it but its not working i confused myself with the first post so thought i would clarify this a little better,"['jquery', 'css']" +210856,how to remove an element in lxml i need to completely remove elements based on the contents of an attribute using pythons lxml exampleimport lxmletree as etxmlgroceries fruit staterottenapplefruit fruit statefreshpearfruit fruit statefreshstarfruitfruit fruit staterottenmangofruit fruit statefreshpeachfruitgroceriestretfromstringxmlfor bad in treexpathfruitstaterotten remove this element from the treeprint ettostringtree pretty printtruei would like this to printgroceries fruit statefreshpearfruit fruit statefreshstarfruitfruit fruit statefreshpeachfruitgroceriesis there a way to do this without storing a temporary variable and printing to it manually asnewxmlgroceriesnfor elt in treexpathfruitstatefresh newxmlettostringeltnewxmlgroceries,['python'] +210878,could not get connection factory client fighting with google maps another day another problem i finally managed to set up correctly google maps on my android application or at least i thought i have done it the whole progam starts it even call the class which should print a map but the only thing i can see is a grid with google label on it in the corner i have checked the dalvik monitor and the error emapactivity394 could not get connection factory client occurs i have find out on stackoverflow website that i should sent a gps signal or sth like this from dalvik monitor and i have done it nothing happend also i got the api key one more time but nothing changedhere is mapxmlxml version10 encodingutf8 this file is reslayoutmapviewxml linearlayout xmlnsandroidandroidorientationvertical androidlayout widthfill parentandroidlayout heightfill parentlinearlayout xmlnsandroidandroidorientationhorizontal androidlayout widthfill parentandroidlayout heightwrap contentbutton androidididzoomin androidlayout widthwrap contentandroidlayout heightwrap contentandroidtextandroidonclickmyclickhandlerandroidpadding12px button androidididzoomout androidlayout widthwrap contentandroidlayout heightwrap content androidtextandroidonclickmyclickhandler androidpadding12px button androidididsat androidlayout widthwrap contentandroidlayout heightwrap content androidtextsatelliteandroidonclickmyclickhandler androidpadding8px button androidididstreet androidlayout widthwrap contentandroidlayout heightwrap content androidtextstreetandroidonclickmyclickhandler androidpadding8px button androidididtraffic androidlayout widthwrap contentandroidlayout heightwrap content androidtexttrafficandroidonclickmyclickhandler androidpadding8px button androidididnormal androidlayout widthwrap contentandroidlayout heightwrap content androidtextnormalandroidonclickmyclickhandler androidpadding8px linearlayoutcomgoogleandroidmapsmapviewandroidididmapview androidlayout widthfill parentandroidlayout heightwrap content androidclickabletrueandroidapikey0zpcz1vyrsplusufj2jol0ffl2uxdmovgpw319w linearlayouthere is a mapmapajavapublic class mapmapa extends mapactivityprivate mapview mapviewoverrideprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestatesetcontentviewrlayoutmapmapview mapviewfindviewbyidridmapviewpublic void myclickhandlerview target switchtargetgetid case ridzoominmapviewgetcontrollerzoominbreakcase ridzoomoutmapviewgetcontrollerzoomoutbreakcase ridsatmapviewsetsatellitetruebreakcase ridstreetmapviewsetstreetviewtruebreakcase ridtrafficmapviewsettraffictruebreakcase ridnormalmapviewsetsatellitefalsemapviewsetstreetviewfalsemapviewsettrafficfalsebreakoverrideprotected boolean islocationthisplayed return falseoverrideprotected boolean isroutethisplayed return falsemanifestxmlxml version10 encodingutf8manifest xmlnsandroidpackagemenudot androidversioncode1 ndroidversionname10application androidlabelstringapp name androidicondrawableiconuseslibrary androidnamecomgoogleandroidmaps activity androidnamemainactivityandroidlabelstringapp nameintentfilteraction androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilteractivityactivity androidnameaboutandroidlabelstringabout title androidthemeandroidstylethemedialog activityactivity androidnameexitandoridlabelstringexit title activityactivity androidnameoptionsactivityactivity androidnamestartactivityactivity androidnamecreateactivityactivity androidnamewhereactivityactivity androidnameproceedactivityactivity androidnamefinishactivityactivity androidnameloginactivityactivity androidnameokactivityactivity androidnameuserpanelactivityactivity androidnamemanageroactivityactivity androidnameeditionactivityactivity androidnamedoneactivityactivity androidnamedeleteactivityactivity androidnamemapmapaactivityapplicationusespermission androidnameandroidpermissionaccess fine locationusespermission androidnameandroidpermissionaccess coarse locationusespermission androidnameandroidpermissioninternetusessdk androidminsdkversion3 manifest,['android'] +210880,bluetoothwifi between mac app and ios app how can i make a bluetooth mac app that connects with an ios app and sends messages or an ios app that connects with a mac app via a local wifi network,['ios'] +210882,gearman sending data from a background worker to the client is it possible to send back data from a gearman worker that runs in the background with phpi know that i can pass a status numeratordenominator to the client but i need to return datathe background is that i need to call workers on different servers and if they do not respond the main script should continue so i think i have to run the workers in the background but i need some data from themupdateit seems not to be possible i think i have either to store the data in a shared database or to write it from the remote server to the local server or to read it from the remote server or to make something like thisshell execgearman f getdata1921682001 mypath 21 echo,['php'] +210890,where is a mac applications nsuserdefaults data stored i am using nsuserdefaults to store some data in my applicationnsuserdefaults prefs nsuserdefaults standarduserdefaultsprefs setobjectdummy string forkeylastvalueprefs synchronizefor testing purposes i need to see the system preferences plist file where my nsuserdefaults data is saving on the maci know where the ios application user defaults are stored but i do not know about mac application where is a mac applications nsuserdefaults data stored,['objective-c'] +210903,is there any way to bookmark or link to a section of a page without an anchor is there any way to bookmark or link to an html page which i am not author of without having an anchor in the html code i want the page to get scrolled down to a particular section when accessed from a bookmark or hyperlink even if there is no anchor tag in the destination pagenote the destination page has an anchor tag as foo then bookmark like httphellohtmlfoo will not only take the user to hellohtml but also automatically scroll down to the section of the page so that the anchore tag foo is at the top of the screen,['html'] +210926,get the last 4 characters of a string i have the following string abhow can i get the last four characters and store them in a string using python,['python'] +210939,android sqlite what does sqlitedatabasereplace actually do i need to do a insert or update if exist type of procedure with my database i read that replace was the way to go it inserts new records just fine but if the record already exists it does not appear to update iti have something like thiscontentvalues values new contentvaluesvaluesputid 1valuesputname bobvaluesputvisible truedbreplacepeopletable null valuesif i run this code when this record is not in the database it appears to create the record just fine as if i did an insert but if i change name to john or something like that and run the replace again it does not appear to update the recordaccording to the docs here is the syntaxpublic long replace string table string nullcolumnhack contentvalues initialvalueswhy is it called initalvalues does that mean those values are only used when the record does not exist and it is going to be inserted if so how do you use the method to update a record where do you specify the new valuesif i am misunderstanding what replace does altogether can someone explain what it is purpose is,"['java', 'android']" +210946,html5 canvas method ispointinpath determines only the last object an example herevar contextdocumentgetelementbyidcanvasgetcontext2dred boxcontextbeginpathcontextfillstyleredcontextrect10105050contextfillpink circlecontextbeginpathcontextlinewidth3contextfillstylepinkcontextarc250250500mathpi2falsecontextfillcontextstrokecontextfont12em verdanacontextfillstyleblackcontextfilltextcontextispointinpath35353535contextfilltextcontextispointinpath250250250250if you write without beginpath all objects detectedhow to identify objects on the canvas or to omit beginpath,['javascript'] +210950,how to make custom buttons in ios the default ios ui is nice but if i wanted to use images for buttons instead how would i do that is it opengl,['ios'] +210964,passing bootstrapped variables and json to requirejs what is the best practice for passing bootstrapped variables within the rendered page ie json data or config variables to requirejs so they can be checked for an used by dependanciesit looks like this could be done by checking the window object ie windowbootstrapped models but that does not seem very optimalapphtml example data within the html documentscriptvar config isadmin true userid 1var bootstrapped models groups id 1 name foo id 2 name bar scriptappjs example app using requirerequirejquery groupcollection function groupcollection extend default config if config extenddefaults config use bootstrapped json here var collection new groupcollection if bootstrapped modelsgroupslength 0 collectionaddbootstrapped modelsgroups,['javascript'] +210976,eval unexpected token error i tried this simple javascript codeevaltopicstototatatitiin the chrome console for example this returnssyntaxerror unexpected token i tried the json on jsonlint and it is validdo you see the bug,['javascript'] +210985,autocomplete contains instead of starting with in winform textbox in designer textboxincontextautocompletemode suggest in designer textboxincontextautocompletesource customsourceautocompletestringcollection autocomplete new autocompletestringcollectionautocompleteaddrangemyarrayofstringstextboxincontextautocompletecustomsource autocompletei have this code which works well as documented in msdn problem if user types ps it shows all the string starting with ps i would like to thisplay all the strings containing psany pointers,['c#'] +210992,is form submit synchronous or async i am just wondering if the documentmyformsubmit is a synchronous call that will block until finished or if it is async and will continue to execute without waiting for the submit to return thanks for any help,['javascript'] +210994,orghibernateannotationsentity deprecated in hibernate 4 i am attempting to update to hibernate 4 and i am getting that orghibernateannotationsentity is deprecated none of the documentation however seems to indicate that this is the case anyone have any insight into thisorghibernateannotationsentitydynamicupdate true,['java'] +211003,uibutton settitle forstate not working i am trying to set the text of a uibutton on a new view when a next button is pressed from a previous view i have set the iboutlet correctly and i have looked all over for answers to this but it just is not working at allhere is a sample of what i am trying to do ibactioncomputequizidsender fivefootuniversalresults settitletest forstateuicontrolstatenormal ibactionjumpt10resultsviewidsender nsstring nibfiletoload jumpt10results uidevice device uidevice currentdevice ifdevice userinterfaceidiom uiuserinterfaceidiompad nibfiletoload nibfiletoload stringbyappendingstringipad jumpmasterpathfinderviewcontroller nextview jumpmasterpathfinderviewcontroller alloc initwithnibnamenibfiletoload bundlenil modal view controller nextviewmodaltransitionstyle uimodaltransitionstylecrossthissolve self presentmodalviewcontrollernextview animatedyes nextview release scrollview setcontentsizecgsizemakeimageviewwidth imageviewheight 440these actions are both connected to a button on a previous view the view loads fine and everything the only problem is the text will not change on the button i am 100 sure i have the iboutlets set correctly i just do not know what i am doing wrong any ideas,['iphone'] +211021,create session factory in hibernate 4 i am having trouble generating a session factory in hibernate 4 in hibernate 3 i simple didorghibernatecfgconfiguration conf hibernateutil getlimsinitializedconfigurationsystemconfigurationgethibernateconffilesessionfactory sf confconfigurebuildsessionfactorynow i need to pass a serviceregistry class to buildsessionfactory but the javadocs are extremely vague on how to go about this any tips,['java'] +211026,error detached entity passed to persist try to persist complex data playframework i have a problem with persisting data via playframework maybe it is not possible to achive that result but it would be really nice if it would work simple i have a complex model shop with addresses and i want to change the shop with addresses at once and store them in the same way shopsave but the error detached entity passed to persistoccurs udate history0511 0511update model shop with attribute mappedbyshopupdate link to google user group0911find a workaround but it is ot generic1611update example html form thanks to pavelupdate workaround update 0911 to a generic method thanks to mericano121i gave up trying to find a solution and waiting for play 20dateil i try to cut down the problem to a minimum model entitypublic class shop extends model requiredmessage shopname is required public string shopname onetomanycascadecascadetypeall fetchfetchtypeeager mappedbyshop public listaddress addressesentitypublic class address extends model required public string location manytoone public shop shopnow my frontendcode extends mainhtml form saveshopid input typehidden nameshopid valueshopid field shopshopname label forshopnameshop namelabel input typetext namefieldname valueshopshopname classfielderrorclass field legendaddressenlegend list items shopaddresses as address input typehidden nameshopaddressesaddress index 1id valueaddressid labellocationlabel input nameshopaddressesaddress index 1location typetext valueaddresslocation list input typesubmit classbtn primary valuesave changes formi have just the id from the shop itself and the shopname to deliver via post like shopshopnamefoo the interssting part is the list of addresses and there i have the id and the location from the address and the result would be somthin like shopshopnamefooshopaddresses0id1shopaddresses0locationbar now the controller part for the data public class shops extends crud public static void formlong id if id null shop shop shopfindbyidid rendershop renderpublic static void savelong id shop shop set owner manually dont edit from fe user user userfindbyemail securityconnectedfirst shopowner user validate validationvalidshop if validationhaserrors renderform shop shopsave indexnow the problem when i change the address data the code reaches the shopsave the object shop is filled with all data and everything looks fine but when hibernate tryes to persist the data the error detached entity passed to persist occurs i tried to change the fetch mode the cascadetype and i also tried shop shop1 shopmergeshop1saveunfortunately nothing worked either the error occurs or no address data will be stored is there a way to store the data in that way if there is somthing not clear please write to me i would be glad to give as much information as possible update 1i also put the problem on the google user groupupdate 2 3 with the help of the user group thanks to bryan w and an answer from mericano1 here i found a generic workaround first you have to remove cascadecascadetypeall from attribute addresses in shopclass then you have to change the method save within shopsclass public static void savelong id shop shop set owner manually dont edit from fe user user userfindbyemail securityconnectedfirst shopowner user store complex data within shop storedatashopaddresses shopaddresses storedatashoplinks shoplinks validate validationvalidshop if validationhaserrors renderform shop shopsave indexthe generic method to store the data looks like that private static t extends model void storedatalistt list string parametername forint i0 ilistsize i t relation listgeti if relation null continue if relationid null relation tmodelmanagerfactoryforrelationgetclassfindbyidrelationid stringbuffer buf new stringbufferparametername bufappendappendiappend binderbindrelation buftostring requestparamsall try to set bidiritional relation you need an interface or smth relationshop shop relationsave i added in shopclass a list of links but i would not update the other code snippets so be warned if compiling errors occur,['java'] +211033,what is the meaning of id i am trying to learn objectivec and i keep coming across a phrase likeid initand i understand id is an objective c language keyword but what does it mean to say the compiler specifically treats id in terms of the pointer type conversion rulesdoes id automatically designate the object to its right as a pointer,['objective-c'] +211042,sizeof in visual c makes me unhappy i was writing a piece of code where i use sizeofsomestring as a parameter of a function then i noticed the function was not returning the expected value so i went to see the corresponding asm code and i found an unpleasant surprise does anyone have an explanation for this see the picturei know there are 10 different ways of doing this i already implemented another one of them but i do want to know the reason behind this behaviour for the curious this is visual studio 2008 sp1,['c++'] +211069,attr accessor strongly typed ruby on rails just wondering if anyone can shed some light on the basics of getter setters in ruby on rails with a view on strongly typed i am very new to ruby on rails and predominately have a good understanding of netfor example let us consider we have a net class called personclass person public string firstnamegetset public string lastnamegetset public address homeaddressgetsetclass address public string addressline1getset public string citygetset public string countrygetsetin ruby i would write this asclass person attr accessor firstname attr accessor lastname attr accessor homeaddressendclass address attr accessor addressline1 attr accessor city attr accessor countryendlooking at the ruby version of the person class how do i specify the types for the accessor methods firstname lastname and homeaddress if i were to consume this class i could feed any type into homeaddress but i want this accessor method to accept only the type address any suggestions thanks,"['ruby-on-rails', 'ruby']" +211084,whats the best way to develop a sideswipe menu like the one in facebooks new ios app it appears that sideswipe menus are becoming a more common interface element as more information gets crammed into each iphone app facebook has included it in their latest version and the new gmail app appears to include it as well i was wondering if anybody had thoughts on the most efficient way of developing something like this as it is becoming a more common interface element while i have my own thoughts on how to build this i am curious to hear what other people think,"['objective-c', 'ios']" +211091,what happens to an nsarray object when encoding i am building an application that utilises nscoding to save nsobjects to a documentpathi am having no issues doing this i am just curious about somethingi have macompany which implements nscoding delegate methods void encodewithcodernscoder encoder encoder encodeobjectaddress 1 forkeykaddress 1 encoder encodeobjectaddress 2 forkeykaddress 2 encoder encodeobjectcity town forkeykcity town encoder encodeobjectcompany name forkeykcompany name encoder encodeobjectcountry forkeykcountry encoder encodeobjectdate added forkeykdate added encoder encodeobjectfax forkeykfax encoder encodeobjectparent company website forkeykwebsite encoder encodeobjectpostal code forkeykpostal code encoder encodeobjectstate province forkeykstate province encoder encodeobjecttype forkeyktype encoder encodeobjectstores forkeykstores nsarray of custom nsobjectsas you can see i have a nsarray of custom nsobjects mastore each one of these objects also implements the same nscoding what nothowever my question is when i call encodewithcodernscoder encoder method in mastore and it gets to the encoder encodeobjectstores forkeykstores will all the objects stored within the stores nsarray have the encoderwithcodernscoder encoder method called if implementededitthe reason i am asking this is that i want to know whether or not it will work before i invest time in doing such a thing i have multiple custom nsobjects with nsarrays that hold more custom nsobjects it would be a long process to find that it does not work,"['iphone', 'objective-c']" +211171,inputstreamreader vs filereader i cannot seem to determine any difference between inputstreamreader and filereader besides the way the two are initialized is there any benefit to using one or the other most other articles cover fileinputstream vs inputstreamreader but i am contrasting with filereader instead seems to me they both have the same purpose,['java'] +211190,how to judge an overflow when adding signed to unsigned i am trying to detect the overflow when adding a signed offset to an unsigned positionuint32 positionint32 offset it could be negativeuint32 position positionoffsethow can i check whether the result is overflow or underflowi have thought of an ugly way but not sure of its correctnessunderflow offset 0 position offset positionoverflow offset 0 position offset positionand i am also wondering if there is a more elegant way to do itupdatewhats the best solution if offset is longuint32 positionlong offset it could be negativeuint32 position positionoffset,['c'] +211194,syntax guidelines for taking ownership and releasing objects in c i want to know are there any guidelines about syntax of c nonmember functions that allows me to understand without comments if possible the ownership policy of its arguments and return value by ownership i mean that the owner is responsible for the destruction of the owned objecti thistinguish the following rules about argumentstake ownershipdo not take ownershipshareand about return valuerelease return by value is in this groupdo not releasesharefor example passing object by reference does not take it is ownershipvoid funcobject obj such guidelines may use standard constructions like unique ptr shared ptr etc if there are no such guidelines then the examples of possible syntax misunderstandings are welcome too,['c++'] +211223,why is java prohibiting inheritance of inner interfaces ie why is the following cyclic dependency not possiblepublic class something implements behavior public interface behavior since interfaces do not reference the outer class this should be allowed however the compiler is forcing me to define those interfaces outside the class is there any logical explanation for this behavior,['java'] +211227,running scrapy tasks in python my scrapy script seems to work just fine when i run it in one off scenarios from the command line but if i try running the code twice in the same python session i get this errorreactornotrestartablewhythe offending code last line throws the errorcrawler crawlerprocesettingscrawlerinstallcrawlerconfigure schedule spidercrawlercrawlmyspiderspider myspidercrawlerqueueappend spiderspider start engine scrapytwistedcrawlerstart,['python'] +211233,how does bitconvertertoint32 work here is a method using systemclass program static void mainstring args create an array of four bytes then convert it into an integer and unsigned integer byte array new byte4 array0 1 lowest array1 64 array2 0 array3 0 sign bit use bitconverter to convert the bytes to an int and a uint the int and uint can have different values if the sign bit differs int result1 bitconvertertoint32array 0 start at first index uint result2 bitconvertertouint32array 0 first index consolewritelineresult1 consolewritelineresult2 consolereadline output1638516385i just want to know how this is happening,['c#'] +211269,html if image is not found i have an image in a html pageif the image is not found on the server it shows an ugly blank squarei want to make it so that if an image is not found it will thisplay nothing or some other default image that i know is definitely on the serverhow can this be done,['html'] +211286,sse2 code optimization i am using sse2 intrinsics to optimize the bottlenecks of my application and have the following questionddata mm xor si128 mm xor si128 mm sll epi32xdata 0x7u mm srl epi32tdata 0x19u xdataon microsoft c compiler this would not compile because types m128i and unsigned int passed to mm sll epi32 instruction are not interchangeablewhy is this so and how should i pass the arbitrary unsigned int value to mm sll epi32 m128i istypedef union declspecintrin type crt align16 m128i int8 m128i i816 int16 m128i i168 int32 m128i i324 int64 m128i i642 unsigned int8 m128i u816 unsigned int16 m128i u168 unsigned int32 m128i u324 unsigned int64 m128i u642 m128i,['c++'] +211287,docked multiline textbox is covered by statusstrip i am having a form in which i have multiple line textbox and status strip both docked to the bottom of the formtextbox must be docked so it can be resizable while the whole form is resizablethe problem is that the status strip is covering the textbox on the bottom of the from covering scroll bars down arrowis there any way to make textbox docked to the bottom while still thisplaying above the status stripregards,['c#'] +211293,specify nunit test to run i have an nunit project creating a console application for running tests the entry point looks like thisclass program stathread static void mainstring args string my args assemblygetexecutingassemblylocation int returncode nunitconsolerunnerrunnermainmy args if returncode 0 consolebeep what can i pass in as an argument if i wanted to run this one test onlytestfixturepublic class emailnotificationtest test public void mailerdefaulttest assertistruefalse clearly this is supported and just as clearly i have no idea how to do it,['c#'] +211321,what is the best way to sort list with custom sorting parameters in python i have a series of lists that looks like thisli1 a1 b9 c8 d1 e2li2 a4 b1 c2 d2 e4how can i rearrange the items in each list so that the first item is bsomething for the example aboveli1 b9 a1 c8 d1 e2li2 b1 a4 c2 d2 e4maintaining the order after the first item is not important thanks for the help,['python'] +211328,what more can i do to improve performance on this class i am currently developing a 2d game with cxna the games core feature are bullets with vastly different behaviors it will be kind of a bullet hell gameupdating all the bullets can take quite some time since they can be infinitely complex with their behaviors and all of them have to do 1 collision checkoriginally i just stored them in a list and updated and drew all of them removing inactive bullets from the list each framethis however quickly proved to slow the game down when there where 8k bullets on the screen so i decided to implement multithreading and using linq to help performancething is it is still slowing down at around 16k bullets i was told i could achieve up to 7 million active bullets if i did it right so i am not satisfied with 16kis there anything else i could do to improve performance hereadditional information before code my bullets have fields for velocity direction angular velocity acceleration a speedlimit and a behaviorthe only special thing as mentioned is the behavior it can modify any of the bullets fields at any time or spawn more bullets and even plant itself in them therefore i am having a hard time applying a datadriven solution and just storing all these fields in arrays instead of having a list of bulletsinternal class bulletmanager gamecomponent public static float currentdrawdepth 82f private readonly listbullet bullets new listbullet private readonly int processorcount private int counter private readonly task tasks public bulletmanagergame game basegame processorcount variableproviderprocessorcount tasks new task processorcount public void clearallbullets bulletsclear public void addbulletbullet bullet bulletsaddbullet public override void updategametime gametime if statemanagergamestate gamestatesingame statemanagergamestate gamestateseditor enginestatesgamestates eenginestatesrunning return var bulletcount bulletscount var bulletstoprocess bulletcount processorcount split up the bullets to update among all available cores using tasks and a lambda expression for var i 0 i processorcount i var x i tasksi taskfactorystartnew forvar j bulletstoprocess x j bulletstoprocess x bulletstoprocess j if bulletsjactive bulletsjupdate update the remaining bullets if any for var i bulletstoprocess processorcount i bulletcount i if bulletsiactive bulletsiupdate wait for all tasks to finish taskwaitall tasks this is an attempt to reduce the load per frame originally bulletsremovealls sactive ran every frame counter if counter 300 return counter 0 bulletsremovealls sactive public void drawspritebatch spritebatch if statemanagergamestate gamestatesingame statemanagergamestate gamestateseditor return spritebatchdrawstringfontprovidergetfontmono14 bulletscounttostring new vector2100 20 colorwhite using some linq to only draw bullets in the viewport foreach var bullet in bulletswherebullet cameraviewportcontainsbulletcirclecollisioncentertopoint bulletdrawspritebatch currentdrawdepth 82e5f currentdrawdepth 82f,['c#'] +211340,how to create a sidebar similar to the facebook app for ios possible duplicatewhats the best way to develop a sideswipe menu like the one in facebooks new ios app how can i create a sidebar similar to the facebook app for ios iphoneipad that sidebar that appears when you slide your finger horizontally there is a component for this or is it just a uiview,"['iphone', 'objective-c', 'ios']" +211348,how to load image from users computer is it possible to load image to xna game from user computer for example i want to load cimagesboxpng to sprite texture is it possible if yes how,['c#'] +211360,does gcc define anything when g is specified shortly i want to know if gcc or g i need it in c but also am curious about c defines any special symbols if g is enabled does it if so what symbolsin the search process i found out that debug is defined manually by manually i mean d debug and is a habit taken from visual c programmers because vc defines debug when compiling in debug modendebug is defined if not in debug mode although i found a few places saying this i tried with my gcc and g in c and cpp files and in none of them with or without g no such symbol was definededit let me demonstrate why i do not want to use a nonstandard symbolimagine a kernel module that does something and also provides header files to be included in other kernel modules so that they can connect to this onenow as a facility in one of the header files i haveifdef debug this is what i needdefine logx printksome extra infox va args elsedefine logx printkwithout extra infox va args endifnote that the name is not really log that is an examplenow i can use any symbol for debug myself but then if someone includes my header they may not define that symbol of course i can tell them by the way to get the headers in debug mode define this other symbol but that just does not sound right to mei could define the symbol in a header and include it in all header files this way if they include one of my headers they get the debug symbol too the problem now is that if they do not want to compile in debug mode my headers still think they are in debug modeso what i thought would be best was to use a symbol that is defined when g is used if there are anyupdateso far i came to the conclusion that i could do something like thishow to buildhif definedndebugdefine my debugendifusageinclude how to buildhifdef my debug rest of the storythis way the common option of ndebug removes my definition also it still requires me to tell them to define it if they do not want to get the headers in debug mode,['c'] +211367,massive ie7 memory leaks when destroying a jquery ui dialog on close i have searched all over for an answer or even a reference to this particular issue to no avail i am using jquery ui 187 and jquery 151 i have a dialog that i want to not only destroy on close but also remove from the dom on close this works fine in firefox however when i do the same thing in ie7 i see a 6mb spike in memory usage for the browser and this memory never gets reclaimed until i shut down the browser completely so my first thought was something in my dialog is causing memory leaks i stripped out everything that i was adding and made a simple dialog using the following codediv idtestmehellodivdialog modal true autoopen true close function thisdialogdestroy when i open this dialog close it and then refresh the browser i always end up with 6mb more memory than i had before if i open this dialog but then refresh the browser before closing it then i do not see any memory spike at all i have no idea what could be causing this i have found a bunch of threads about general jquery ui memory leaks but none of the fixes have done anything to remedy my situation i also thought that maybe some other code in my project was getting in the way this is not the case if i do the same thing using this jsfiddle example i get a memory spike as well at this point i have no idea where else to turn or what else to do i need to destroy these dialogs and remove them from the dom there are already quite a few instances of the dialogs throughout our very large application that bank on the fact that the dialog div is no longer in the dom after closing edit changing the value of the modal flag has no effect also i realize that my example does not remove the element from the dom whether i do that or not the memory leak remains the code in my actual project is just removing the element from the dom using thisremove i simplified the example because the real issue is the destroy call leaving some sort of circular reference or something that is causing the 6mb memory spike i mentionededit after looking into this more it does not seem to matter what jquery ui widget i am using i tried dialog my own custom widget and button as long as i remove the element that the widget is referencing from the dom i see the huge memory leak in ie7 the memory leak also happens if i move the elements to somewhere else in the dom i tried creating a garbage bin div that i moved all the contents of my dialog to instead of removing them completely and the same spike happenedany help or direction would be greatly appreciated thanks in advance guys,"['javascript', 'jquery']" +211370,how do i set a 40x error with a custom message on jaxrs exception i am working on a web service on jaxrs that is already working now i am looking for the way to catch some exceptions in order to send an 40x error with a custom message to the useri have a web service and an exceptionmapperthis is my web servicepath value testpublic interface servicetest pathvalue rrf get producesmediatypetext xml public objectdto getdealerpathparamrrf string rrf objectdto objectdto new objectdto if verifyrrfsintaxrrf get the objet this part works fine else throw new illegalargumentexceptioncustom message return dwsdto private boolean verifyrrfsintaxstring rrf return rrfmatches098 this is my exceptionmapperproviderproducesmediatypetext xmlpublic class illegalargumentexceptionmapper implements exceptionmapperillegalargumentexception override public response toresponseillegalargumentexception e return responsestatusresponsestatusbad requestbuild and this is how it is registed on the applicationcontextxml filebean idservicetest claservicetestjaxrsserver idserver addressws jaxrsservicebeans ref beanservicetest jaxrsservicebeans jaxrsproviders bean idrfferrorexception classillegalargumentexceptionmapper jaxrsprovidersjaxrsserverwhen i debug the illegalargumentexceptionmapper catches the exception i throw but i do not see the message on a yellow web page that is shown on the browser i always have a erreur danalyse xml aucun alament trouva xml parsing error no element found in englishhow i can make to show this custom message on the browserwhy even if i change the kind of response status not found bad request forbidden this yellow page is always the samepd on the console i have in a message outhandlemessage that is printed when the mapper catch the exceptionthanks,['java'] +211412,why does not jquery use requestanimationframe some browsers support requestanimationframe so why not use it after all it is been supported since google chrome 10 despite that jquery does not seem to be using it i have found a bug report about it but no real explanation was given i am sure the jquery people have their reasons thoughwhy wouldnt they use this awesome api,['jquery'] +211416,how to query a mysql table to thisplay the root and its subchild userid username parentid topid 1 abc null null 2 edf 1 1 3 gef 1 1 4 huj 3 1 5 jdi 4 1 6 das 2 1 7 new null null 8 gka 7 7topid and parentid is from the useridi want to get a user record and its child and subchild record here userid1 is the root and its child are userid2 and userid 3 so if the user id is 1 i have to thisplay all the records from userid 1 to userid 6 since all are child and subchild of the root similarly for userid3 i have to thisplay userid3 and its child userid 4 and child of userid 4 userid5if the userid is 3 output should be userid username3 gef4 huj5 jdii will know the userid and the topid so how can i do the query to acheive the above resultselect userid username from tbl user where parentid3 or userid3 and topid1by the above query i am able to thisplay userid 3 and userid 4 i am not able to thisplay userid 5 kind of struck in it need help thanks,"['mysql', 'sql']" +211422,android xml layout file is not being added to rjava xml version10 encodingutf8linearlayout xmlnsandroid androidlayout widthfill parent androidlayout heightwrap contentimageview androidididimagenew androidlayout width50dip androidlayout height50dip androidsrcdrawableicon androidscaletypecentercroplinearlayoutthis is my new layout file and it is not being detected by eclipse nor is it in the r file i cannot create any new layout files or perhaps i am doing it all wrong all my older layouts are seen fineeditalso a layout i had created previously i have edited with a new id however that new id is not detected either,['android'] +211439,does overloading get you if i manually overload the operator for a structure do i get the operator for free presumably defined to be the boolean opposite or do i have to overload it manually even if to just return this rhseditthe question is not whether or not i can overload both operators but whether i must overload inequality if i have already overloaded the equality operator regardless good answers have been given,['c++'] +211465,is there a java library that can diff two objects is there a java utility library that is analogous to the unix program diff but for objects i am looking for something that can compare two objects of the same type and generate a data structure that represents the differences between them and can recursively compare differences in instance variables i am not looking for a java implementation of a text diff i am also not looking for help with how to use reflection to do thisthe application i am maintaining has a fragile implementation of this functionality that had some poor design choices and that needs to be rewritten but it would be even better if we could use something off the shelfheres an example of the kind of thing i am looking forsomeclass a new someclasomeclass b new someclassasetprop1aasetprop2xbsetprop1bbsetprop2xdiffdatastructure diff offtheshelfutilitydiffa b magical recursive comparison happens hereafter comparison the utility would tell me that prop1 is different between the two objects and prop2 is the same i think it is most natural for diffdatastructure to be a tree but i am not going to be picky if the code is reliable,['java'] +211466,c wait for user to finish typing in a text box is there a way in c to wait till the user finished typing in a textbox before taking in values they have typed without hitting enterrevised this question a littleokay i have a simple calculator that multiplies by 2 here is what i want it to do the user inputs a value like 10 into a textbox and it automatically thisplays 20 here is what happens as soon as the user enters in 1 its multiplies by 2 and outputs 2,['c#'] +211502,best way to convert dictionary into single aggregate string representation how would i convert a dictionary of key value pairs into a single string can you do this using linq aggregates i have seen examples on doing this using a list of strings but not a dictionaryinputdictionarystring string map new dictionarystring string a alpha b beta g gammaoutput string result aalpha bbeta ggamma,['c#'] +211508,returning the differences between two enumerables i am trying to determine the differences between two collectionsprivate observablecollectionsomeobject objectlist nullprivate observablecollectionsomeobject cachedobjectlist nullsomeobject implements iequatablesomeobjecti am using the following to determine if my two collections have any differencesthis objectlisttolistorderbyx xidsequenceequalthis cachedobjectlisttolistorderbyx xidthe cachedobjectlist collection will not change you are able to add remove or modify an object in the objectlist collectionhow can i return a new list that contains any newly added deleted or otherwise modified object from the two collectionsany help would be greatly appreciated iequatable implementation for someobjectpublic class someobject iequatablesomeobject public int gethashcodesomeobject object return basegethashcode public bool equalssomeobject other bool result true if objectreferenceequalsother null result false check whether the compared objects reference the same data if objectreferenceequalsthis other result true else if the reference is not the same we can check the properties for equality if thisidequalsotherid result false if thisotherlistorderbyx xidtolistsequenceequalotherotherlistorderbyx xidtolist result false return result editi only want the changes if the objectlist contains a modified object based on the iequatableequals then i would like it returned otherwise return new objects or removed objects in the list,['c#'] +211509,what is the fastest fft library for iosandroid arm devices what is the fastest fft library for iosandroid arm devices and what library to people typically use on iosandroid platforms i am guessing vdsp is the library most frequently used on ios edit my code is at and uses the bsd license it runs on android and ios and it is faster than libav fftw and vdsp edit2 if anyone can provide access to a power7 machine or other machines please email me it would be much appreciatedcheers,"['android', 'ios']" +211516,why would i combine mathfloor with mathrandom why would anybody call mathfloor on a mathrandom result i have seen it used likemathfloormathrandom numcan someone explain please,['javascript'] +211546,running c in browser i have written some basic c programs in one of my classes for school i was wondering if it was possible to somehow virtually run the program in a broswer i would like to post the program to my website once its posted a person could access the program run the program and interact with the program i am not trying to write c for my website it would be more for an interactive portfoliois this possible,"['c++', 'html']" +211603,difference between a static and a final static variable in java generally final static members especially variables or static final of course they can be used in either order without overlapping the meaning are extensively used with interfaces in java to define a protocol behavior for the implementing class which implies that the class that implements inherits an interface must incorporate all of the members of that interface i am unable to differentiate between a final and a final static member the final static member is the one which is a static member declared as final or something else in which particular situations should they be used specificallya static variable or a final static variable can never be declared inside a method neither inside a static method nor inside an instance method whythe following segment of code accordingly will not be compiled and an compiletime error will be issued by the compiler if an attempt is made to compile itpublic static void mainstring args final int a0 ok int b1 ok static int c2 wrong final static int x0 wrong,['java'] +211618,redirect to registration page if user not signedin in devise from reading the devise code and wiki it seems there is no option to redirect user to registration page if a user is not logged in in libdevisefailure apprb it appear that the redirect url is hardcoded def redirect url opts route new scope session path optsformat request format unless skip format if respond toroute sendroute opts else root pathopts end endi want to ask that is the best practice in getting the work done i am thinking of manually setting user return to session value then make a call to registration page is that a good practice,['ruby-on-rails'] +211632,how to change uisearchbar from round to rectangle i will like to know how do i need to change a uisearchbar from the default round curve to a rectangle,"['iphone', 'ios']" +211639,what is and i was going through some vc code in a large codebase and came across this if nstate tool tips visible nstate tool tips visible else nstate tool tips visible breakis there any such operator as or in c what is it foris it the equivalent of nstate nstate tool tips visible,['c++'] +211666,code generation for ios and android i am searching for a framework to create apps for both android and ios from one codebase i am aware of appcelarator and phonegap etc however i need a different kind of product i am not sure if it exists i cannot find it here or on googlewe are a team of android and ios developers and are not afraid to build natively what i want is a tool to help me jumpstart development preferably a tool where i can create the basic ui and models and generate native code to use as basis for further development does such a tool exist,"['android', 'ios']" +211667,how are textual data files parsed in modern c i am too often confronted with the task of having to parse textual data files the kind of textual structured data representation you used before everyone used xml that are some kind of industry standard there are too many of theseanyways the basic task is always taking a text file and stuffing whats in there in some kind of datastructure so that our c code can do something with the infonow i have implemented a few simple and oh so buggy parsers by hand and there is little i despise more so i was wondering what the current state of the art is when i want to parse structured textual data into a inmemory representation think xml data binding for an arbitrary languagewhat i found so far was what parser generator do you recommend but i am not so sure i am after a parser generator like antlrobvious candidates seem to be pegtl and boostspirit but they both seem rather complicated but at least they are inlanguage and last time i tried spirit the compiler errors drove me nuts and pegtl needs a c11 compatible compiler which is still a problem here vc 2005so am i missing a simpler solution for just getting something likebegin compu method dec decimal value rat func 30 dec coeffs 0 10 0 0 0 10end compu methodinto a c datastructure this is just an arbitrary example of how part of such a file may look for this format i could and probably should buy a library to parse it as it is widespread enough which is not the case for all formats i encounter or should i just go for the complexity of say boostspirit,['c++'] +211677,any way to circumvent dialogs must be userinitiated exception my app has a open file button before launching the openfiledialog it asks whether the user wants to save the current file and if they do it launches a savefiledialog it then launches the openfiledialog pretty standard stuffmy problem is that silverlight then sees the openfiledialogshowdialog method as not userinitiated and i get a securityexception is there any known reasonable way to avoid this exception surely this is a pretty standard scenariothe app is within a browserany ideas welcomeeditsorry not allowed to release actual code the logic is pretty simple though in psuedocode the openfile button press event calls a method something likelaunch a new sl message asking whether to save firston message window yesno clickedif no go to loadif yes launch savefiledialogshowdialog go to loadloadlaunch an open file dialogedit 2mini programmexml content for the main pagegrid xnamelayoutroot backgroundwhite button contentopen clickbutton clickgridcodeusing systemwindowsusing systemwindowscontrolsnamespace silverlightapplication15public partial class mainpage usercontrol askwindow aw new askwindow public mainpage initializecomponent awclosed new systemeventhandleraw closed private void button clickobject sender routedeventargs e awshow private void aw closedobject sender systemeventargs e if awdialogresult true savefiledialog svd new savefiledialog svdshowdialog openfiledialog ofd new openfiledialog ofdshowdialogcauses security exception public class askwindow childwindow public askwindow button b new systemwindowscontrolsbutton bclick new systemwindowsroutedeventhandlerb click bcontent yes save it thiscontent b private void b clickobject sender systemwindowsroutedeventargs e thisdialogresult true,['c#'] +211694,assigning classes to elements through css i would like to tell the browser to assign certain css classes to elements matching a particular selector can i do it with pure css and if yes howexample i want all the h5 elements inside a div with id sidebar to have the class uicornersall,"['html', 'css']" +211759,ruby on rails after validation if valid right now from what i know after validation will be called even if the model fails the validations is there a way to only call it if the model is valid i tried adding return false unless selfvalid in the after validation method but that triggers validation again and it creates an infinite loop,"['ruby-on-rails', 'ruby']" +211760,specifying exact percentage widths in relation to parent div in css i am attempting to create a visual element using div elements and css which should thisplay data in the format demonstrated below502525when using the code and css i have specified below my final element always spills onto the next line and the css percentage values i am specifying do not seem to create the layout properlycould anybody suggest a better way to do thismy htmldiv classvisualindicatortitleall itemsdivdiv classvisualindicatorholderdiv classviinternalelement stylewidth 25 backgroundcolor 5e9bd1 25divdiv classviinternalelement stylewidth 25 backgroundcolor ab884d 25divdiv classviinternalelement stylewidth 50 50divdivdiv classvisuallegendul classinlineblock li div classlegendblue div salesli lispan classlegendtanspanprocessedli lispan classlegendgreyspanpending processingliulmy cssvisualindicatortitlefontsize12pxfontweightboldcolor7visualindicatorholderwidth100backgroundcolor6height28pxborderradius 8pxvisualindicatorholder viinternalelementfontsize11pxtextaligncentercolorfbackgroundcolor7borderradius 6pxthisplayinlineblock,['css'] +211771,position jquery ui dialog how can i position the jquery ui dialog specifically so that it goes to a position not defined by center top etcthanks i have tried to be as specific as posible,['jquery'] +211786,optimising java switch statement with many cases i am currently using a switch statement to handle types of incoming messages of which there are 20 or so different cases some of these cases are orders of magnitude more likely to occur than othersis the hotspot compiler able to optimise the order of examining cases to find the correct case to execute or should i structure my code so that the most common cases appear firstswitchmessagetype case most common handle it break case least common handle it breakall cases are mutually exclusivewould i be better off using the strategy pattern and a map lookup on message typeperformance is the key concern as i am handling thousands of messages per second and am trying to cut down on object creation and method call overheadmany thankschriseditthanks for the pointersmessagetype is an int with a tight range of values so it looks like it will compile to the tableswitch bytecode so no need to reorder the casesrelevant part of jvm spec is here editionhtmlcompilingdochtml14942,['java'] +211787,inaccessible type due to private inheritance g is denying me access to a type just because it happens to be a private grandfather does this make sensestruct a struct b private a struct c b void fooa const a compiling this yields110 error astruct a a is inaccessible612 error within this contextmy point is i never wanted to access a as an ancestor in fact if a is a private ancestor of b should not this be completely invisible to anybody but b ie cof course i could use protected inheritance but in my case it does not really make sense,['c++'] +211789,how can i generate java objects with bean validation annotations from an xsd i am writing an ejb as a contract first soap service and i generate the java classes and sei from the wsdl the wsdl specifies several types with constraints max length pattern etc the generated java classes are jaxb annotated but lack the contraints metadata because the jaxb annotations do not support those this means that input validation only occurs when the service is called through the soap endpointthe problem is that when the ejb is called by another ejb the validation is bypassed since it is located in the xml stack i would like to thisable xml schemavalidation and use bean validation instead so validation works for both ways soap and rmi of calling the ejbquestion how can i generate not only jaxb annotations but also bean validation annotations on the java classes,['java'] +211799,how do i extract specific n bits of a 32bit unsigned integer in c could anyone tell me as to how to extract n specific bits from a 32bit unsigned integer in c for example say i want the first 17 bits of the 32bit value what is it that i should doi presume i am supposed to use the modulus operator and i tried it and was able to get the last 8 bits and last 16 bits asunsigned last8bitsvalue32 bit integer 16unsigned last16bitsvalue32 bit integer 32is this correct is there a better and more efficient way to do this,['c'] +211816,why is graphicsdrawline drawing a wedge shape i am trying to draw a bus route as a simple sequence of lines nothing fancy but instead of lines i am getting wedges initially i was fine with this because the wedges sortof look like arrows and always face towards the second point but now i want to improve the look and the wedges are becoming a big problemmy suspicion is some sort of floatingpoint issue due to the graphics transform latlons are fed in and the transform turns them into xy on the bitmap assuming latlon is euclidean is accurate enough for my purposes so the scaling is several orders of magnitudescreenshotit actually kind of looks like the line was split into two triangles but only one of them was drawnrelevant code note drawing is done asynchronously which is why i am creating a bitmap creating the transform dim bitmap new bitmapmathmax1 picturebox1width mathmax1 picturebox1heightdim g graphicsfromimagebitmapgtranslatetransform0 bitmapheightgscaletransform1 1gscaletransformcsngbitmapwidth maxlon minlon csngbitmapheight maxlat minlatgtranslatetransformminlon minlat drawing the lines in a method called asynchronously using pen new penbrushesblack 01dim shapes busdatatripsingrouptripgroupvalue selectfunctione eshape thistinctfor each shape in shapes for i 0 to shapepointscount 2 dim e1 shapepointsi dim e2 shapepointsi 1 dim p1 new pointfcsnge1longitude csnge1latitude dim p2 new pointfcsnge2longitude csnge2latitude gdrawlinepen p1 p2 nextnextexample valuescenlat 44657176cenlon 63549471spnlat 0071921spnlon 0179729minlat cenlat spnlat 2maxlat cenlat spnlat 2minlon cenlon spnlon 2maxlon cenlon spnlon 2shpts lat 446518683235 lon 635930836628 lat 446512537117 lon 635927528307 lat 446508013753 lon 635924572976 lat 446503312812 lon 635921923044 lat 446503312812 lon 635921923044 lat 446502137576 lon 635921260568 lat 446495810455 lon 635917829189 lat 44648893839 lon 635913776026 lat 446485468163 lon 635911976944 lat 446485468163 lon 635911976944 lat 446475084762 lon 635906617219 lat 446475084762 lon 635906617219notes and thiscoveriesusing drawlines instead of drawline solves the issue but whyincreasing the pen thickness makes the issue go away but the lines are too thickzooming out increasing latlon view window makes the issue go away eventually but i want to zoom in,['.net'] +211817,jni converting unsigned int to jint how do i convert an unsigned int to jint do i have to convert it at all or can i just return it without any special treatment this is basically my code right now but i cannot test it as i have not setup jni locally jniexport jint jnicalljava test testjnienv env jobject obj jlong ptr myobject m myobject ptr unsigned int i mget return i,"['java', 'c++']" +211868,odd number list for hash i am trying to get a rails website up and running from github and i am encountering these errorswarning task t arg needs deps is deprecated please use task t args deps instead at libraryrubygems18gemssunspot rails121libsunspotrailstasksrb41 rake aborted usersrobertgrzesikdocumentsrubyonrailsindieoptionapphelpersadvertisements helperrb15 odd number list for hash user id current userid usersrobertgrzesikdocumentsrubyonrailsindieoptionapphelpersadvertisements helperrb15 syntax error unexpected expecting user id current userid usersrobertgrzesikdocumentsrubyonrailsindieoptionapphelpersadvertisements helperrb16 syntax error unexpected expecting page requesturl usersrobertgrzesikdocumentsrubyonrailsindieoptionapphelpersadvertisements helperrb17 syntax error unexpected expecting kend usersrobertgrzesikdocumentsrubyonrailsindieoptionapphelpersadvertisements helperrb20 odd number list for hash page requesturl usersrobertgrzesikdocumentsrubyonrailsindieoptionapphelpersadvertisements helperrb20 syntax error unexpected expecting page requesturl usersrobertgrzesikdocumentsrubyonrailsindieoptionapphelpersadvertisements helperrb21 syntax error unexpected expecting kend for this codeif ad if current user adimpressionscreate user id current userid page requesturl else adimpressionscreate page requesturl end link to external redirect advertisement urlad do image tag adimageurlformat endelse nilendendany ideas,"['ruby-on-rails', 'ruby']" +211878,autostart mysql on boot from terminal i just installed mysql in terminal through homebrewnow when i try to connect to mysql it fails but after i run mysqld it works so what i need to do now is run mysqld when i boot my maci have searched google for mysqld autoload at startup etc but could not find the right answerhope someone can point me in the right direction thanks,['mysql'] +211892,scala 29 bridgemethod i am using scala 291i have defined a logging trait as such trait logging def debugmsg string throwables throwable and i have a jmspublisher class which mixesin the logging trait class jmspublisher extends publisher with logging def publishproductslist list product def publishlist seqproduct this all compiles fine my issue is that i have a user who wants to load my jmspublisher into spring he is using spring 256when the applicationcontext is loaded during startup the app crashes with an illegalstateexception complaining that it cannot find a bridgedmethod related to my logging traitinitialization of bean failed nested exception is javalangillegalstateexception unable to locate bridged method for bridge method public void comappmessagingjmspublisherdebugjavalangstring scalacollectionseq at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorydocreatebeanabstractautowirecapablebeanfactoryjava480 stack trace followsthis code worked under scala28 and i heard that scala is marking trait that have some methods as bridged in 29 i think this is what is causing spring to fail i cannot upgrade to scala29 if my class cannot be loaded by springhas anyone run into this issue is there any fix or workaround,['java'] +211903,put delegate methods into a category i developed some application till now now i am writing a new one and in this project i want to keep the code very clean so it is very easy to find the methodsi want to start with the uiviewcontrollers whose view have a uitableview as subview i wish to have a file with the name detailviewcontroller for all functions which belong directly to it another file with the name detailviewcontrollerprotocols should contain a category of the class above and all these delegate methods of uitableviewis it possible to do something like this i want to keep my code clean and split it into multiple fileseditdetailviewcontrollerhinterface detailviewcontroller uiviewcontroller some properties some methodsenddetailviewcontrollermimport detailviewcontrollerhimplementation detailviewcontroller some synthesizes some methodsenddetailviewcontrollerprotocolshinterface detailviewcontroller protocols uitableviewdelegate uitableviewdatasourceenddetailviewcontrollerprotocolsmimplementation detailviewcontroller protocols nsintegernumberofsections return nsintegernumberofrowsinsectionnsintegersection if section 0 return return endbut then xcode shows a warning that some of the delegate methods are not implemented in detailviewcontroller i also tried it with importing the detailviewcontrollerprotocolsh in the detailviewcontrollerh no changingthen i tried it with ignoring the warnings and see it worked but why should not it work without these warnings,"['objective-c', 'ios']" +211914,why does javas treeset removeobject not take an e from the java 6 treesete documentationboolean removeobject o removes the specified element from this set if it is presentwhy does this accept an object instead of the generic type e the only objects that can be added are of type e so it follows that the only removable type should be of type e,['java'] +211919,java is it possible to output the stacktrace with method signatures is it possible to output the current stacktrace with method signatures i am trying to debug some obfuscated code that has a ton of methods with the same name that just differ in arguments and return typesome things that will not workthreadcurrentthreadgetstacktracenew throwablegetstacktrace etc,['java'] +211920,does nsobject autocontentaccessingproxy work at all i am trying to make use of nsobject autocontentaccessingproxy as described at classreferencereferencehtmlapple refoccinstmnsobjectautocontentaccessingproxythe object i am trying to proxy implements the nsthiscardablecontent protocol and autocontentaccessingproxy successfully returns a nonnil valueif however i try to send a message to the proxy i always get an nsinvalidargumentexception with a reason of nsproxy methodsignatureforselector calledi understand that if i was writing my own nsproxybased class i would have to implement the methodsignatureforselector method but in this case i am not writing the proxy just trying to use the proxy provided by the documented method for what it is worth i can see that the proxy is actually of type nsautocontentaccessingproxy so i would expect that that class would indeed have an implementation for methodsignatureforselectorhere is a small block of code using an nspurgeabledata instance instead of my custom class this small block has exactly the same issuenspurgeabledata data nspurgeabledata datawithbytes123 length3nslogdatalength u datalengthid proxydata data autocontentaccessingproxynslogproxydatalength u proxydata length throws nsinvalidargumentexceptiondata endcontentaccessdata releasedo i have some misunderstanding of the autocontentaccessingproxy method here or is it just completely broken,"['objective-c', 'ios']" +211933,what is the most simple lightestweight wsgi framework which of the wsgi frameworks are super lightweight and minimal if you are familar with ruby then i am looking for something similar to rails metalwsgi rackrails djangosinatra flaskrails metal,['python'] +211936,prevent buttons from hiding soft keyboard on android i have a webview and some buttons in my layout there is a large tag in my webview this app is used to edit text files the buttons are used to effect the textarea inside my webview when the user presses a button such as an arrow button to move the text view it closes the keyboard i have used togglesoftinput but that just toggles the keyboard to show or not i want the buttons to stop hiding the soft keyboard when the button is pressed i have found nothing about my specific problem i have searched for weeks anybody have any idea on how i can stop my buttons from hiding the soft keyboard on android,['android'] +211947,undefined reference to static constexpr char i want to have a static const char array in my class gcc complained and told me i should use constexpr although now it is telling me it is an undefined reference if i make the array a nonmember then it compiles what is going on hppstruct foo void bar static constexpr char baz quz cppvoid foobar stdstring strbaz undefined reference to baz,['c++'] +211951,c less operator overload which way to use for example in a c header file if i defined a struct record and i would like to use it for possible sorting so that i want to overload the less operator here are three ways i noticed in various code i roughly noticed that if i am going to put record into a stdset map priority queue a containers the version 2 works probably version 3 as well if i am going to save record into a vectorrecord v and then call make heapvbegin vend etc then only version 1 works struct record char c int num version 1 bool operator const record rhs return thisnumrhsnum version 2 friend bool operator const record lhs const record rhs friend claim has to be here return lhsnumrhsnum in the same header file for example version 3 inline bool operator const record lhs const record rhs return lhsnumrhsnum basically i would like to throw the questions here to see if someone could come up with some summary whats the differences among these three methods and what are the right places for each version,['c++'] +211955,how does codeigniter sanitize inputs i am building a codeigniter application and i am trying my hardest to prevent sql injections i am using the active record method to construct all my queries i know active record automatically sanitizes the input but i am wondering exactly to what extent does it simply escape all the quotes or does it do more what about preventing obfuscated sql injections or other more advanced kindsbasically i am looking for an indepth explanation of how ci sanitizes data anyone know,"['php', 'sql']" +211975,specifying memory limits with hadoop i am trying to run a highmemory job on a hadoop cluster 020203 i modified the mapredsitexml to enforce some memory limits property namemapredclustermaxmapmemorymbname value4096value property property namemapredclustermaxreducememorymbname value4096value property property namemapredclustermapmemorymbname value2048value property property namemapredclusterreducememorymbname value2048value propertyin my job i am specifying how much memory i will need unfortunately even though i am running my process with xmx2g the job will run just fine with this much memory as a console application i need to request much more memory for my mapper as a subquestion why is this or it is killedval conf new configurationconfsetmapredchildjavaopts xms256m xmx2g xxuseserialgcconfsetmapredjobmapmemorymb 4096confsetmapredjobreducememorymb 1024the reducer needs hardly any memory since i am performing an identity reducer class identityreducerk v extends reducerk v k v override def reducekey k values javalangiterablev contextreducerkvkvcontext for v values context write key v however the reducer is still using a lot of memory is it possible to give the reducer different jvm arguments than the mapper hadoop kills the reducer and claims it is using 3960 mb of memory and the reducers end up failing the job how is this possibletasktree pid10282tipidattempt 201041418 05 r 0 0 is running beyond memorylimitscurrent usage 4152717312byteslimit 1073741824byteskilling taskupdate even when i specify a streaming job with cat as the mapper and uniq as the reducer and xms512m xmx1g xxuseserialgc my tasks take over 2g of virtual memory this seems extravagant at 4x the max heap sizetasktree pid3101tipidattempt 201041418 0112 m 0 0 is running beyond memorylimitscurrent usage 2186784768byteslimit 2147483648byteskilling taskupdate the original jira for changing the configuration format for memory usage specifically mentions that java users are mostly interested in physical memory to prevent thrashing i think this is exactly what i want i do not want a node to spin up a mapper if there is inadequate physical memory available however these options all seem to have been implemented as virtual memory constraints which are difficult to manage,['java'] +211982,invoking a javaaxis web service from net the areturn nulla issue i have been seeking for this problem through all google stackoverflow and more and i found a lot of related answers to it but not a real solutioni am consuming an axis service from a net client but the return is always null no matter what parameters i send always is nullso i started to look and i tried to consume it from the soapui and it workedso my first thought was net is doing something wrong and i searched and searched and i found that there are some problems with the namespacesrelated post hereso after this i tried to consume the service via service reference web reference creating a proxy with wsdlexe it was created pretty well and looked for all the namespaces but all lokked good i made some changes to it to the namespace but nothingthen i found that not just the namespaces are problematics also the arrays and in fact the service returns something like thissoapenvenvelope xmlnssoapenv xmlnsxsd xmlnsxsi soapenvbody informacionpolizaresponse xmlns ns1poliza xmlnsns1 ns1numero0036887ns1numero ns1seriens1serie ns1ramo00110ns1ramo ns1subramo00110ns1subramo ns1incisons1inciso ns1claveagente0270ns1claveagente ns1nombreagentenombre pendientens1nombreagente ns1numerooficinans1numerooficina ns1fechaemision20110215ns1fechaemision ns1fechainiciovigencia20110215ns1fechainiciovigencia ns1fechafinvigencia20120215ns1fechafinvigencia ns1estatus03ns1estatus ns1nombrecontratantecarlos zarate jimenezns1nombrecontratante ns1rfccontratantezajc720213k98ns1rfccontratante ns1telefono0449626251463ns1telefono ns1moneda1ns1moneda ns1formapago003ns1formapago ns1primaprimerpago23784ns1primaprimerpago ns1primapagosubsecuente23784ns1primapagosubsecuente ns1primaneta95136ns1primaneta ns1financpagofraccionadons1financpagofraccionado ns1gastosexpedicion00ns1gastosexpedicion ns1ivans1iva ns1primatotalns1primatotal ns1polizaorigen0036887ns1polizaorigen ns1polizarenueva0ns1polizarenueva ns1productons1producto ns1planns1plan ns1asegurados ns1item ns1nombrecarlos zarate jimenezns1nombre ns1clavens1clave ns1direccion ns1callens1calle ns1colonians1colonia ns1poblacionns1poblacion ns1estadons1estado ns1cpns1cp ns1textons1texto ns1direccion ns1fechanacimiento19720213ns1fechanacimiento ns1sexo1ns1sexo ns1fumador1ns1fumador ns1parentesco0ns1parentesco ns1antiguedaddesdens1antiguedaddesde ns1coberturas ns1item ns1clave00150ns1clave ns1seccionns1seccion ns1nombrecoberturaseguro de muerte accidentalns1nombrecobertura ns1limitemaximo250ns1limitemaximo ns1deducible00ns1deducible ns1prima820ns1prima ns1edadcalculo039ns1edadcalculo ns1plazosegurons1plazoseguro ns1plazopagons1plazopago ns1sumaasegurada250ns1sumaasegurada ns1coaseguro00ns1coaseguro ns1item ns1item ns1clave00150ns1clave ns1seccionns1seccion ns1nombrecoberturaseguro de muerte accidentalns1nombrecobertura ns1limitemaximo250ns1limitemaximo ns1deducible00ns1deducible ns1prima9500ns1prima ns1edadcalculo039ns1edadcalculo ns1plazosegurons1plazoseguro ns1plazopagons1plazopago ns1sumaasegurada250ns1sumaasegurada ns1coaseguro00ns1coaseguro ns1item ns1item ns1clave00150ns1clave ns1seccionns1seccion ns1nombrecoberturaseguro de muerte accidentalns1nombrecobertura ns1limitemaximo500ns1limitemaximo ns1deducible00ns1deducible ns1prima3636ns1prima ns1edadcalculo039ns1edadcalculo ns1plazosegurons1plazoseguro ns1plazopagons1plazopago ns1sumaasegurada500ns1sumaasegurada ns1coaseguro00ns1coaseguro ns1item ns1coberturas ns1beneficiarios ns1item ns1asegurados ns1incisos ns1recibos ns1item ns1numerorecibo5183648ns1numerorecibo ns1fechaemision20110215ns1fechaemision ns1fechaestatus20110226ns1fechaestatus ns1fechapago20110226ns1fechapago ns1estatus00ns1estatus ns1descripcionestatusgeneradons1descripcionestatus ns1importe027589ns1importe ns1recargos00ns1recargos ns1derechopoliza00ns1derechopoliza ns1fechainiciovigencia20110215ns1fechainiciovigencia ns1fechafinvigencia20110515ns1fechafinvigencia ns1primatotal xsiniltrue ns1primapagada xsiniltrue ns1primapendiente xsiniltrue ns1item ns1item ns1numerorecibo5183649ns1numerorecibo ns1fechaemision20110215ns1fechaemision ns1fechaestatus20110215ns1fechaestatus ns1fechapago190ns1fechapago ns1estatus00ns1estatus ns1descripcionestatusgeneradons1descripcionestatus ns1importe027589ns1importe ns1recargos00ns1recargos ns1derechopoliza00ns1derechopoliza ns1fechainiciovigencia20110515ns1fechainiciovigencia ns1fechafinvigencia20110815ns1fechafinvigencia ns1primatotal xsiniltrue ns1primapagada xsiniltrue ns1primapendiente xsiniltrue ns1item ns1item ns1numerorecibo5183650ns1numerorecibo ns1fechaemision20110215ns1fechaemision ns1fechaestatus20110215ns1fechaestatus ns1fechapago190ns1fechapago ns1estatus00ns1estatus ns1descripcionestatusgeneradons1descripcionestatus ns1importe027589ns1importe ns1recargos00ns1recargos ns1derechopoliza00ns1derechopoliza ns1fechainiciovigencia20110815ns1fechainiciovigencia ns1fechafinvigencia2015ns1fechafinvigencia ns1primatotal xsiniltrue ns1primapagada xsiniltrue ns1primapendiente xsiniltrue ns1item ns1item ns1numerorecibo5183651ns1numerorecibo ns1fechaemision20110215ns1fechaemision ns1fechaestatus20110215ns1fechaestatus ns1fechapago190ns1fechapago ns1estatus00ns1estatus ns1descripcionestatusgeneradons1descripcionestatus ns1importe027589ns1importe ns1recargos00ns1recargos ns1derechopoliza00ns1derechopoliza ns1fechainiciovigencia2015ns1fechainiciovigencia ns1fechafinvigencia20120215ns1fechafinvigencia ns1primatotal xsiniltrue ns1primapagada xsiniltrue ns1primapendiente xsiniltrue ns1item ns1recibos ns1endosos ns1siniestros ns1poliza informacionpolizaresponse soapenvbodysoapenvenvelopei got this example from the soapuithe related post is here i tried also thisand got another possible trouble from here with the listed items of an array named as item as you can see in the webserviceresponse mentioned above they are listed like that so everything seemed to me that is a deserialization problem from c and looking i found a halfsolution to all of thisthe reality was that actually net get the response pretty good all that it has is problem with the deserializing step maybe for all the posibles causes mentioned abovemultiple namespaces arrays array items named like item ws netaspx i overrided the method in my proxy like thisprotected override systemnetwebresponse getwebresponsesystemnetwebrequest request webresponse wr basegetwebresponserequest streamreader sr new streamreaderwrgetresponsestream throw new exceptionsrreadtoend return wr i thrown the exception to see if the result of the service was catched and in fact is right there so after all os this i dont know if there is a fix a service pack someone found a solution or anything of how i can deserealize correctly the webresponse or how to consume correctly that axis service i think the best aproach to this is just serialize the response correctly overriding the method because it seems like a bug of net i think it has troubles with the because everything array has an item on itthanks in advance for read this posti would really really apreciate any helpthanks again,"['c#', 'asp.net']" +212007,mysql join with multiple conditions i have a problem with an sql query actually a simple query but i cannot figure up what am i missing so i came to ask your helpso what i have to doi have two tables rooms and rooms facilitiesand i have to select the rooms with desired facilitiesif i select a room with one facility facility with id4 id fu using the following queryselect u from rooms you join facilities r fu on fuid uc uid uc and fuid fu 4 where 1 and vizibility1 group by id uc order by you premium desc id uc desc everything it is okbut if i want to select the room with more facilities let us say facilities with id4 and id3 using the following queryselect u from room you join facilities r fu on fuid ucuid uc and fuid fu 4 and fuid fu 3 where 1 and vizibility 1 group by id uc order by you premium desc id uc desc it does not worki cannot understand why it does not work but i cannot figure up how to put the conditionthanks mihai,"['mysql', 'sql']" +212011,jquery difference between click and onclick i usually useselectorclickbut some people recommend me to use this instead selectoronclick functionor selectorliveclick deprecatedi read the manual but my begginers mind could not understand it i got confused with all the terminology they used i still do not know the difference nor why to use on,"['javascript', 'jquery']" +212035,using handlebarsjs helpers to create active elements with jquery is it possible to within a handlebarsjs helper to create elements using jquery and attach event handler to them i would like to be able to create active elements using helpersexamplehandlebarsregisterhelperbutton functiontitle var button buttontexttitle buttonclickfunction alertbutton title clicked return divappendbuttonhtmlin the handlebars template i instantiate the button like thisbutton click mei understand that this can not work since the jquerys html function removes the event handler but simply returning button obviously does not work eitherhandlebars helpers should be able to return dom nodes but this is not possible right i tried to return buttonget but without success any ideas,"['javascript', 'jquery']" +212049,techniques for smoother image animation with jscss i am using the following code to glide an image across the top layer of a webpage but its a little jittery giving streaky vertical lines down the image especially when over content with many nested elements this is the case even when the border is set to zero any suggestions for a smoother method for gliding an image with jscssborder4pps250 speed of glide pixels per secondskip2 eg if set to 10 will skip 9 in 10 pixelsrefresh3 how often looks to see if move needed in millisecondselem documentcreateelementimgelemid img idelemstylezindex20elemstylepositionfixedelemstyletop0elemstyleleft0elemsrc 69e6d9eb5c mjpgelemstyleborderborderpx solid blackelemstylecursorpointerdocumentbodyinsertbeforeelemnullpos start 250pos current pos startpos finish 20var timer new dategettimemovefunction move var elapsed new dategettime timer var pos new mathfloorpos startppselapsed10skipskip if pos new pos current if pos newpos finish pos newpos finish img idcssleft pos new if pos newpos finish return pos current pos new t settimeoutmove refresh,"['javascript', 'css']" +212053,regex stringbuilder and large object heap fragmentation how can i run lots of regexes to find matches in big strings without causing loh fragmentationit is net framework 40 so i am using stringbuilder so it is not in the loh however as soon as i need to run a regex on it i have to call stringbuildertostring which means it will be in the lohis there any solution to this problem it is virtually impossible to have a long running application that deals with big strings and regexes like this an idea to solve this problemwhile thinking about this problem i think i found a dirty solution at a given time i only have 5 strings and these 5 strings bigger than 85kb will be passed to regexmatchsince the fragmentation occurs because new objects would not fit to empty spaces in loh this should solve the problempadright all strings to a max accepted size let us say 1024kb i might need to do this with stringbuiderby doing so all new strings will fit to already emptied memory as previous string is already out of scope there would not be any fragmentation because object size is always same hence i will only allocate 10245 at a given time and these space in loh will be shared between these stringsi suppose the biggest problem with this design what happens if other big objects allocate this location in loh which would cause application to allocate lots of 1024 kb strings maybe with an even worse fragmentation fixed statement might help however how can i send a fixed string to regex without actually create a new string which is not located in a fixed memory address any ideas about this theory unfortunately i cannot reproduce the problem easily i am generally trying to use a memory profiler to observe the changes and not sure what kind of isolated test case i can write for this,['c#'] +212055,libcurl output to variable instead of textfile in failing to get curlpp for c working i have decided to start using libcurl with c instead for now being completely new to both c and c this is getting a little confusing i am not even sure if i can keep c and c functions apart but as far as i know this is pure cwith the help of a friend i have managed to write the output page contents that curl picked up to a textfile but i want to put it in a string variable instead so i can use the output in other parts of the code i could just reopen the textfile and read its contents but that is silly i want to stop writing to a file and just save to a string variable immediatelythe write function the function to invoke as the data received size t write datavoid ptr size t size size t nmemb file stream size t written written fwriteptr size nmemb stream return writtenthe entire codeinclude iostreaminclude curlcurlhinclude stdiohinclude stdlibhinclude iostreamusing namespace std the function to invoke as the data recieved size t write datavoid ptr size t size size t nmemb file stream size t written written fwriteptr size nmemb stream return writtenint mainint argc char argv curl curl file fp curlcode res curl curl easy initchar outfilenamefilename max cusersadmindownloadsbtxt ifcurl char response null fp fopenoutfilenamewb curl easy setoptcurl curlopt url httpwhiddenorgwptestlalalatxt curl easy setoptcurl curlopt writefunction write data curl easy setoptcurl curlopt writedata fp res curl easy performcurl curl easy cleanupcurl fclosefp return 0i was also hoping someone could elaborate on how this function is used exactly i am used from php and vbnet to a function like thisfunction1thisisavariablethisisavariabletoo if thisisavariable something print gogopowerangers append thisisavariabletoo which would then be used likefunction1passthisasvariable1passthisasvariable2but in the code above the functionsize t write datavoid ptr size t size size t nmemb file streamis simply called like thiswrite dataas you can see herecurl easy setoptcurl curlopt writefunction write dataso whats all this forvoid ptr size t size size t nmemb file streamdoes curl automatically fill those in or does cc work differently with functions than most other languages,"['c++', 'c']" +212080,how to optimize size of shared library say we have huge static libraries with lots of unneeded features in the example below we have libraries lib1a and lib2a with unneeded functions g1 and f2we want to build shared library with a few exported methods which use only a few functionsclasses from that huge libraries see example below we want to export function fooquestionscan we tell linker ld which functionsmethods we want to export like we do it for dll in windowscan linker resolve dependecies and remove unneeded functionsmethods or is there any other way to solve the problemif you have a solution please write the fixes for the example belowexamplefile 1hint f1 int and int g1 int and file 2hint f2 int and file foocppinclude 1hinclude 2hint foo int and return f1 and file 1cppint f1 int and return n int g1 int and return n file 2cppint f2 int and return n file makefilecxxflags g i wall wnosigncompareall prepare libfoosoclean rm f obja objo ressoprepare mkdir p src mkdir p obj mkdir p reslib1a lib2a liba o ar r obj objo1o 2o fo o g cxxflags c o obj srccpplibfooso lib1a lib2a fo ld shared o reslibfooso objfo lobj l1 l2and after making target all we have nm reslibfooso01d8 t z2f1i020e t z2g1i01c4 t z3fooiso ld has removed 2o object file according to dependencies between object files but did not remove function g1 from 1o,['c++'] +212104,python check for valid email address is there a good way to check a form input using regex to make sure it is a proper style email address been searching since last night and everybody that has answered peoples questions regarding this topic also seems to have problems with it if it is a subdomained email address,['python'] +212112,problems doing ajaxrequests with a phonegap application i am trying to create a simple rss reader with phonegap and jqueryi am following this tutorial i have managed to get this working just fine when i try out the code in my browser the phpfile fetches the feed and outputs it just like i expect it to but when i run the same file from within my compiled phonegap application the ajaxrequest just returns the contents of the phpfile the phpcode not the executed resulti have spent hours googling this and tried numerous tutorials and tweaks i found no solutions in the offical phonegap forums either what am i doing wrong the problem seems to be php not responding to the request i have tried to move the phpfile to a different domain but the result is the same it works in my browser but not in the compiled appheres the jquery code that initiates the ajaxcodefunction get rss feed clear the content in the div for the next feed feed contentemptyhtmlimg classloader srcjsimagesajaxloadergif alt ajax url success function parserssd find each item in the file and parse it dfinditemeachfunction name the current found item this for this particular loop run var item this grab the post title var title itemfindtitletext grab the posts url var link itemfindlinktext next the description var description itemfinddescriptiontext do not forget the pubdate var pubdate itemfindpubdatetext now create a var html to store the markup were using to output the feed to the browser window var html div classentryh2 classposttitle title h2 html em classdate pubdate em html p classdescription description p html a href link target blankread more adiv put that feed content on the screen feed contentappendhtml feed content imgloaderfadeout heres the rssproxyphp that loads the xml from the url and outputs itphp php proxy loads a xml from any location used with flashflex apps to bypass security restrictions author paulo fierro january 29 2006 usage proxyphpurl session curl init geturl open the curl session curl setoptsession curlopt header false do not return http headers curl setoptsession curlopt returntransfer true do return the contents of the call xml curl execsession make the call headercontenttype textxml set the content type appropriately echo xml spit out the xml curl closesession and close the session,"['php', 'jquery']" +212124,call user func array passing arguments to a constructor i have searched many a page of google results as well as here on stackoverflow but cannot find a solution that seems to fit my situation i appear to have but one last snag in the function i am trying to build which uses call user func array to dynamically create objectsthe catchable fatal error i am getting is object of class product could not be converted to string when the error occurs in the log i get five of these one for each argument php warning missing argument 1 for product construct before the catchable fatal errorthis is the code of the functionpublic static function selectallclass table sort field sort order asc first the function performs a mysql query using the provided arguments query select from table order by sort field sort orderresult mysql queryquery next the function dynamically gathers the appropriate number and names of properties num fields mysql num fieldsresultfori0 i num fields i fetch mysql fetch fieldresult i propertiesi fetchname finally the function produces and returns an array of constructed objectswhilerow mysql fetch assocresult fori0 i num fields i argsi rowpropertiesi array call user func array new class argsreturn arraynow if i comment out the call user func array line and replace it with thisarray new classargs0args1args2args3args4the page loads as it should and populates the table i am building so everything is absolutely functional until i try to actually use my args array within call user func array is there some subtle detail about calling that array that i am missing i read the php manual for call user func array once and then some and examples on that page seemed to show people just building an array and calling it for the second argument what could i be doing wrong,"['php', 'mysql']" +212158,what causes the error undefined reference to some function i get the errormainotext0x1ed in function main undefined reference to avergecolumnscollect2 ld returned 1 exit statuswhen i gcc o i am not quite sure what causes this error other posters have explained it as the function is not found or the function is empty if someone could clarify or refine it would be greaty appreciatedhere is my functions codei am trying to calculate the average of the column in 2d arraysinclude myhvoid averagecolumns int x int y int a int i int j float sum float colavg sum 0 colavg 0 printfi the column averages are n fori 0 i x i forj 0 j y j sum aij colavg sum floatx printfcolumn 3d average 62f j colavg sum 0 colavg 0 the relavent parts of main areinclude myhint main int argc char argv int a float colavg int rows int cols int i int j int table file fpmyfile int closeresult printme rows cols a call functions a j oddvalues rows cols a oddlocations rows cols a countoddrows rows cols a addrows rows cols a findfirstsmall rows cols a findlastlarge rowscols a addcolumns rows cols a avergecolumns rows cols aalso is this a linker or a compile error i was not sure which tag to add,['c'] +212174,understanding the exact meaning of the void keyword in cc as explained for example here we all know of 3 main uses for the void keyword more experienced cc programmers can skip to the 4th use1 as a return type for function that does not return anything this will cause a code sample like thisvoid fooint i footo generate a compiler error2 as the only parameter in a functions parameter list afaik an empty functions parameter list is exactly the same to the compiler and therefore the following 2 lines are identical in meaningedit it is only true in c the comments show the difference in cint fooint foovoid3 void is a special type of generic pointer it can point to any variable that is not declared with the const or volatile keyword convert tofrom any type of data pointer and point to all nonmember functions in addition it cannot be dereferenced i will not give examplesthere is also a 4th use that i do not fully understand4 in conditional compilation it is often used in the expression void0 as following procedure that actually prints error message void assertchar file int line char test ifdef ndebug define asserte void0 elsedefine asserte e void0 assert file line e endifi try to understand the behavior of this expression through experiments all the following are legal compile well int foo some function declarationint fooptr function pointervoidfoovoidfooptrvoid0void0voidavoidblablaexampleclass e some class named exampleclass with a default ctorvoidestatic castvoidebut these are notvoid0 no semicolonint i void0can i conclude from this that void in the context of the 4th use is simply a special type that any type can cast to it whether it is cstyle or cppstyle and it can never be used as an lvalue or rvalue,"['c++', 'c']" +212182,android is there an easy way to find all the strings in my project i want to scan my android project for all hardcoded strings so i can localize the project putting the strings in stringsxml i see an option in eclipse to externalize strings but it is not specific to android i know you can refactor individual strings but i would like to refactor all the strings at once i have got a ton of files and i am trying to avoid going through each one manually,['android'] +212204,is there a quadratic programming library in c the only google search result i found is quadprog but it can not solve the quadratic programming problem whose matrix is not applicable for cholesky decompositionso can anyone give me some suggestion on other library thanks,['c++'] +212209,is there a much better way to create deep and shallow clones in c i have been creating object for a project and there are some instances that i have to create a deep copy for this objects i have come up with the use of a built in function for c which is memberwiseclone the problem that bothers me is whenever there is a new class that i created i would have to write a function like the code below for a shallow copycan someone please help me improve this part and give me a shallow copy that is better than the second line of code thanks shallow copypublic static roomtype createtwinroomtype roomtype return roomtypememberwiseclone as roomtypedeep copypublic static t createdeepclonett source if typeoftisserializable throw new argumentexceptionthe type must be serializable source if objectreferenceequalssource null return defaultt iformatter formatter new binaryformatter stream stream new memorystream using stream formatterserializestream source streamseek0 seekoriginbegin return tformatterdeserializestream,"['c#', '.net']" +212212,why is browser showing tds larger than my specified width property td width is 162px even though stylewidth25px for td and thi have put this in my css filetable td th border 1px solid blacktable bordercollapsecollapsetablenarrow th td width50pxit does not work the last one there is supposed to take a table with classnarrow and make all its descendent th and td elements 50px wide and chrome shows matched css rulesnarrow th td width 50px so chrome is reading it and ignoring it or css is just idiotic or i am why cannot css just do what you tell it like a normal programming languageso i tried putting stylewidth25px right in the 1st column td and th tags and still does not work chrome shows elementstyle width25px but it would not tell me why the hell it is thisplaying it at 162pxanyone have any cluesthank youedit kolink gave me the clue i needed form text fields inside the tags were causing a large minimum width i added this style to shrink the tablenarrow input width80pxit reduced the width of all the inputs inside the classnarrow table and hence reduced the width of the table,['css'] +212214,conversion from derived to base i was reading this and unfortunately could not understand in depth why the compiler does not allow conversion from derived to base also i have seen this which gives no more info than the parashiftcoms link editlet us analyze this code line by line car car car carptr car car carptrptr carptr mycomment until now there is no problem vehicle vehicleptrptr carptrptr this is an error in c mycomment here compiler gives me an error and i try to understand why mycomment let us consider that it was allowed so what let us go ahead nuclearsubmarine sub nuclearsubmarine subptr sub mycomment this two line are ok too vehicleptrptr subptr mycomment the important part comes here vehicleptrptr is a pointer to mycomment a vehicle particularly in our case it points to a car object mycomment now when i assign to the pointer to the car object vehicleptrptr mycomment a pointer to nuclearsubmarine then it should just point to the mycomment nuclearsubmarine object as it is indeed a pointer to a vehicle mycomment is not it where is my fault where i am wrong this last line would have caused carptr to point to sub carptropengascap this might call firenuclearmissle,['c++'] +212215,subprocess completes but still does not terminate causing deadlock ok since there are currently no answers i do not feel too bad doing thiswhile i am still interested in what is actually happening behind the scenes to cause this problem my most urgent questions are those specified in update 2 those beingwhat are the differences between a joinablequeue and a managerqueue and when should you use one over the other and importantly is it safe to replace one for the other in this examplein the following code i have a simple process pool each process is passed the process queue pq to pull data to be processed from and a returnvalue queue rq to pass the returned values of the processing back to the main thread if i do not append to the returnvalue queue it works but as soon as i do for some reason the processes are blocked from stopping in both cases the processes run methods return so it is not put on the returnqueue blocking but in the second case the processes themselves do not terminate so the program deadlocks when i join on the processes why would this beupdatesit seems to have something to with the number of items in the queueon my machine at least i can have up to 6570 items in the queue and it actually works but any more than this and it deadlocksit seems to work with managerqueuewhether it is a limitation of joinablequeue or just me misunderstanding the differences between the two objects i have found that if i replace the return queue with a managerqueue it works as expected what are the differences between them and when should you use one over the otherthe error does not occur if i am consuming from rqoop there was an answer here for a moment and as i was commenting on it it thisappeared anyway one of the things it said was questioning whether if i add a consumer this error still occurs i have tried this and the answer is no it does notthe other thing it mentioned was this quote from the multiprocessing docs as a possible key to the problem referring to joinablequeues it says the semaphore used to count the number of unfinished tasks may eventually overflow raising an exceptionimport multiprocessingclass procstop passclass procmultiprocessingprocess def init self pq rq self pq pq self rq rq super init print selfname def runself dat self pqget while not dat is procstop self rqputdat uncomment me for deadlock self pqtask done dat self pqget self pqtask done print selfname def del self print selfnameif name main pq multiprocessingjoinablequeue rq multiprocessingjoinablequeue pool for i in range4 p procpq rq pstart poolappendp for i in range10 pqputi pqjoin for i in range4 pqput procstop pqjoin while lenpool 0 print pool poolpopjoin hangs here if using rq print completesample output not using returnqueue proc1 proc2 proc3 proc4 proc4 proc3 proc1 procproc1 started procproc2 started procproc3 started procproc4 started proc2 procproc1 stopped procproc2 started procproc3 stopped proc3 procproc1 stopped procproc2 started proc2 procproc1 stopped proc1 complete proc4sample output using return queue proc1 proc2 proc3 proc4 proc2 proc4 proc1 procproc1 started procproc2 started procproc3 started procproc4 started proc3 here it hangs,['python'] +212219,lifetime of lambda objects in relation to function pointer conversion following this answer i am now wondering what the rules are for the lifetime of lambdas and how the relate to the lifetime of function pointers which are created by automatic conversion there are several questions about the lifetime of lambdas eg here and here in which case the answers are they behave exactly like you wrote the full functor object yourself however neither address the conversion to function pointer which could quite sensibly be a special casei put together this small working example that illustrates my concerninclude iostreamtypedef int func tint first casefunc t retfun1 static auto lambda int return 1 automatically converted to func t return lambda second casefunc t retfun2 no static auto lambda int return 2 automatically converted to func t and the local variable lambda reaches the end of its life return lambdaint main const int a retfun10 const int b retfun20 stdcout a b stdendl return 0is this well defined for both cases or only for retfun1 the question is is the function that the function pointer points required to be calling the functor object itself or reimplementing the body in a separate function either one would make sense but the fact that the conversion to function pointer specifically requires a captureless lambda suggests that it may actually be the latterput another way i can see at least two sensible ways a compiler might want to implement such lambdas one possible legal implementation might be for a compiler to synthesize code likefunc t retfun3 struct voodoo magic lambda implementation int operatorint const return 3 static int plainfunctionint return 3 operator func t const return plainfunction lambda return lambdain which case both the static and nonstatic variants of retfun would be fine if however it is also legal for a compiler to implement the lambda likestatic int voodoo impl functionint xstatic struct voodoo maigc impl2 int operatorint const return 4 operator func t const return voodoo impl function magic functor ptrstatic int voodoo impl functionint x return magic functor ptrxfunc t retfun4 voodoo maigc impl2 lambda nonstatic local lifetime magic functor ptr lambda or do the equivalent of this in the ctor return lambdathen retfun2 is undefined behaviour,['c++'] +212223,check for multiple items in array using include ruby beginner is there a better way to write thisif myarrayinclude val1 myarrayinclude val2 myarrayinclude val3 myarrayinclude val4,"['ruby-on-rails', 'ruby']" +212231,an abstract class in java need not implement any methods from it is implementing interface why let us look at the following simple code snippet in javainterface sum abstract public void showsuminterface mul abstract public void showmulabstract class super implements sum protected int x protected int y public superint x int y thisxx thisyy no error though the method showsum of the implementing iterface sum is commented why public void showsum systemoutprintlnsum xy final class calculation extends super implements mul public calculationint x int y superxy public void showsum systemoutprintlnsummation xy if showmul is commented it would issue a compiletime error why public void showmul systemoutprintlnmultiplication xy final public class main public static void mainstring args throws ioexception scanner snew scannersystemin systemoutprintnenter a number int xsnextint systemoutprintnenter another number int ysnextint calculation cnew calculationxy cshowsum cshowmul since the interface sum containing only one method showsum is being implemented by the abstract class super there should be necessary for the abstract class super to implement that method showsum the compiler however does not complain at all and the program is working well with no problem at all whysimilarly the nonabstract final class calculation is implementing the mul interface and contains the actual implementation of the method showmul presented in it is implementing interface in case if this method showmul in the class calculation is commented it issues a compiletime error why is the same thing not applicable to that abstract class super,['java'] +212232,split double into two int one int before decimal point and one after i need to split an double value into two int value one before the decimal point and one after the int after the decimal point should have two digitsexample 1050 10 and 50 1045 10 and 45 105 10 and 50,['c#'] +212239,c how to insert array into hash set i need to insert a 1d array into the hashsetbut i got error while compilinginclude stdiohinclude stdlibhinclude hash sethusing namespace stdint hash compconst int state1const int state2 int result 0 for i 0 i 16 i if state1i state2i result 1 return resultstruct eqarray bool operatorconst int a1const int a2 const return hash compa1a2 0 hash setinthashinteqarray closelistint mainint argc char argv const int sn16 12345608910121314715 closelistinsertsn return 0usrincludec421exthashtableh in member function size t gnu cxxhashtable val key hashfcn extractkey equalkey alloc m bkt num keyconst key size t const with val int key int hashfcn gnu cxxhashint extractkey std identityint equalkey stdequal toint alloc stdallocatorintusrincludec421exthashtableh599 instantiated from size t gnu cxxhashtable val key hashfcn extractkey equalkey alloc m bkt numconst val size t const with val int key int hashfcn gnu cxxhashint extractkey std identityint equalkey stdequal toint alloc stdallocatorintusrincludec421exthashtableh1006 instantiated from void gnu cxxhashtable val key hashfcn extractkey equalkey allocresizesize t with val int key int hashfcn gnu cxxhashint extractkey std identityint equalkey stdequal toint alloc stdallocatorintusrincludec421exthashtableh437 instantiated from stdpair gnu cxx hashtable iterator val key hashfcn extractkey equalkey alloc bool gnu cxxhashtable val key hashfcn extractkey equalkey allocinsert uniqueconst val with val int key int hashfcn gnu cxxhashint extractkey std identityint equalkey stdequal toint alloc stdallocatorintusrincludec421exthash set197 instantiated from stdpairtypename gnu cxxhashtable value value hashfcn std identity tp equalkey allocconst iterator bool gnu cxxhash set value hashfcn equalkey allocinsertconst typename gnu cxxhashtable value value hashfcn std identity tp equalkey allocvalue type with value int hashfcn gnu cxxhashint equalkey stdequal toint alloc stdallocatorintsrcods2cpp677 instantiated from here,['c++'] +212240,jquery animate top from bottom to top i am trying to animate a div a top275i tried animate margintop 820 but on each screen it ends up to a different position so i changed the margintop to animate top 275 but the div comes from the top to down slidedown note that so i can use the animatetop i had to set the div to positionabsolute during the animation is there any hackyway to make the top come from the bottom up or make the margintop have the same thistance from the top on each screen resolution i assume margintop cannot be solved since im setting margin top to 820 in order to get at a point of top275 therefore screens smaller than 1200px height the div will go much higherhere is my codefeaturesfadein css position absolute animate top 275 function callback,"['javascript', 'jquery', 'css']" +212241,google maps html5 click to get lat long i am trying to build a mobile html5 webapp in which user can click on the map to get latlong from google maps is there a code example i tried googling but only found some website that does that but no soucecode examplethis is because i am going to use html5 geolocation to thisplay the current location first but if it is not accurate then users can specify that by themselves thanks a lot,['javascript'] +212264,compiling four java files within one package using javac i have four java files in my folder they are all in the same package heres the package declarationpackage comosamaghide all of these classes are in the same package i want to know how can i compile them using javac i mean i do not know how to compile multiple files that are using each other and once that is done how do i launch then using java command in the cli here are the file namesenteringpointjavahidingprocessjavalistfilesjava,['java'] +212304,performance of java enums i am implementing a 2player game that will be run in a tight loop literally hundreds of thousands of times being then performance paramountmy code actually looks something like thispublic class table private final int white player 1 private final int black player 1 private final int currentplayer private final int otherplayer i was wondering if i would get any performance hit would i choose to replaceprivate final int white player 1private final int black player 1to an enum defined aspublic enum players whiteplayer blackplayeri had the idea that enums were just syntactic sugar over integer constants and taking a glaze look over the bytecode generated for a test enum as well as the code calling it seems to indicate that using them is indeed the same as making a static method call but for some enum infrastructure that is set up when it is first runis my assumption that it is indeed the same to use enums as static constants correct or am i missing something here,['java'] +212346,what http useragent does my ios program advertise itself as i have written an app for my podcast otaku no podcast in various parts of the app i use nsurlconnection fetch rss feeds uiwebview thisplay website content avplayer play mp3 audio files off our cdn and mpmovieplayerviewcontroller play video files off our cdn now since all of these make http requests of some sort i am assuming that they will advertise themselves with the standard iphone useragent string if my assumption is incorrect please let me know this means that based on reading my log files i have no way of telling which of my visitors is coming in via plain old mobile safari vs using my appis there a way of changing the useragent to one of my own i found this question on so that describes how to do this with nsurl but i cannot find any information about any of the above classes that i am using,['ios'] +212349,java compare dates to check if in range ok not as simple as title may make it sound i tried this in a very primal way with c and it worked but i have a feeling a better job could be achieved with java and oracle as database so the thing isi have a reservation system multiple bookings could be made on the same day for period between date x and date y as long as each day in the range can accommodate the requested number maximum number of clusters to reserve is 46 hence logically you would look at each day as a holder of 46 cluster reservation and deduce from that now what i have difficulty working out iswhen there are and number of bookings stored and valid in database then i want to make new booking so how do i check if this new date range falls within any of the previously booked days or not not talking simply here about x falling in y as ranges more like x y x y x y x yas you can see the overlap is happeningplease let me know how could i do this as it will affect early design of objectsregards,['java'] +212389,rails use livereload with asset pipeline quick question for rails pros out therewhen working with rails 30x apps i was a heavy user of guard and livereload however it seems that when using the asset pipeline in rails 31 the livereload guard does not know that changes to a sass file should trigger sending new css to the browseris anyone using livereload with the asset pipeline if so how are you making it workthanks,['ruby-on-rails'] +212396,how to convert char to wchar t i have tried implementing a function like this but unfortunately it does not workconst wchar t getwcconst char c const size t csize strlenc1 wchar t wccsize mbstowcs wc c csize return wcmy main goal here is to be able to integrate normal char strings in a unicode application any advice you guys can offer is greatly appreciated,['c++'] +212398,implementing log in alongside suphp how can a log in like feature be designed to use suphps file permissions for example if i have a website at wexamplecom and the following two users with their own home directories each with a php script testphp and a validateuserphp script that belongs to another user root wdata apache in the home directoryhomea validateuserphpa user1aa a a testphpa user2 a testphpuser1 can access user2s script by visiting wexamplecomuser2testphp and vice versa instead what i want is to channel all incoming requests using something like mod rewrite to validateuserphp however doing so will have the consequence of executing all scripts as the owner of validateuserphp not the target testphp scriptis there anyway to call a php script before suphp kicks in and then either allow suphp to continue or abort entirelyedit this is the second bounty i am putting up the first i gave to gustav bc he gave a good partial answer i will mention what i have attempted so far and why none of them work for me1i have tried using mod rewrite to redirect the url to validateuserphp to either log the user in or call whatever script they wanted to call the problem is that i have set my virtual hosts such that each user has their own virtual site ie wuser1examplecom wuser2examplecomif this is a bad design approach feel free to rudely point it out therefore although the os sees the file structure as above online the root directories are set up as suchvirtualhost wuser1examplecoma validateuserphpa testphpvirtualhost wuser2examplecoma validateuserphpa testphpnaturally i just moved a copy of validateuserphp into every users directory the problem is that now the user can delete that file and put whatever they want in there like not require a log in at all a way around this is to make the home folder sticky not something i would ever recommend doing to a home folder and make the validateuserphp owned by root but now it will executed as root since this is suphp that is where i gave up2i could use gustavs mod auth suggestion but i do not like that it demands the password up front like the old school web sites3 i have considered a variant to 1 if i could redirect between virtual hosts for example restructure the virtual hosts like so virtualhost wuser1examplecoma testphpvirtualhost wuser2examplecoma testphpvirtualhost wadminexamplecoma validateuserphpthen use mod rewrite to redirect all traffic from users to wadminexamplecomvalidateuserphp and if the user is logged in or if the login is successful the user is redirected back to the site they initially tried to log in to the benefit of this if it even is possible is that suphp would not kick in until the user is directed back to their own virtual host,['php'] +212409,how do i use regex to search ignoring certain characters with nspredicate in hebrew there are certain vowels that nspredicate fails to ignore even when using the d diacritic insensitive modifier in the predicate i was told that the solution is to use regular expressions to do the search how do i take a search string and use regex to search hebrew text that contains vowels ignoring those vowelseditin other words if i wanted to search the following text thisregarding dashes and asterisks how would i do so using regexexample texti went to the store yessterday edit 2essentially i want totake an input string from a usertake a string to searchuse a regex based on the users search string to search for contains matches in the larger block of text the regex should ignore vowels as shown aboveedit 3heres how i am implementing my search the user updated the search text boolsearchthisplaycontrolleruisearchthisplaycontroller controller shouldreloadtableforsearchstringnsstring searchstring nsmutablearray unfilteredresults selffetchedresultscontroller sections objectatindex0 objects mutablecopy if selffilteredarray nil selffilteredarray nsmutablearray alloc init autorelease filteredarray removeallobjects nspredicate predicate if controllersearchbarselectedscopebuttonindex 0 predicate nspredicate predicatewithformatarticletitle containscd searchstring else if controllersearchbarselectedscopebuttonindex 1 predicate nspredicate predicatewithformatarticlecontent containscd searchstring else if controllersearchbarselectedscopebuttonindex 2 predicate nspredicate predicatewithformatany tagstagtext containscd searchstring else predicate nspredicate predicatewithformatany tagstagtext containscd or dvartorahtitle containscd or dvartorahcontent containscd searchstringsearchstringsearchstring for article article in unfilteredresults if predicate evaluatewithobjectarticle selffilteredarray addobjectarticle unfilteredresults release return yesedit 4i am not required to use regex for this was just advised to do so if you have another way that works go for itedit 5i have modified my search to look like thisnsinteger length searchstring lengthnsstring vowelsasregex u5b0u55c4nsmutablestring modifiedsearchstring searchstring mutablecopyfor int i length i 0 i modifiedsearchstring insertstringvowelsasregex atindexiif controllersearchbarselectedscopebuttonindex 0 predicate nspredicate predicatewithformatarticletitle containscd modifiedsearchstring else if controllersearchbarselectedscopebuttonindex 1 predicate nspredicate predicatewithformatarticlecontent containscd modifiedsearchstring else if controllersearchbarselectedscopebuttonindex 2 predicate nspredicate predicatewithformatany tagstagtext containscd modifiedsearchstring else predicate nspredicate predicatewithformatany tagstagtext containscd or dvartorahtitle containscd or dvartorahcontent containscd modifiedsearchstringmodifiedsearchstringmodifiedsearchstring for article article in unfilteredresults if predicate evaluatewithobjectarticle selffilteredarray addobjectarticle i am still missing something here what do i need to do to make this workedit 6okay almost there i need to make two more changes to be finished with thisi need to be able to add other ranges of characters to the regex which might appear instead of or in addition to the character in the other set i have trie changing the first range to thisu05b0u05c u0591u05afsomething tells me that this is incorrect also i need the rest of the regex to be case insensitive what modifier do i need to use with the regex to make it case insensitive,"['objective-c', 'ios']" +212413,remove backgroundimage from style how can i remove backgroundimage from element style i do not want to set it to none or 0 i want to remove it completely it is conflicting with mozlineargradient which is defined in another class div stylebackgroundimageurl width100px classmozgradientdiv,"['javascript', 'jquery', 'css']" +212420,how can i get keydown events on a div in chrome i would like to get keydown events on a div i use jquery keydown pretty simplehowever it does not work on chrome for this to work on chrome i have to set tabindex 0if i do this chrome puts an ugly orange border around my divis there a way to make this work on chrome without the ugly orange border,['jquery'] +212440,convert integer to array of digits i try to convert an integer to array for example 1234 to int arr 1234 i have written a function public static void convertint2arrayint guess string temp integertostringguess string temp2 int temp3 int newguess new inttemplength forint i0itemplengthi if itemplength temp2 tempsubstringi i1 else temp2 tempsubstringi systemoutprintlni temp3 integerparseinttemp2 newguessi temp3 forint i0inewguesslengthi systemoutprintlnnewguessi but an exception is thrownexception in thread main javalangnumberformatexception for input string at javalangnumberformatexceptionforinputstringnumberformatexceptionjava65 at javalangintegerparseintintegerjava504 at javalangintegerparseintintegerjava527 at q4testconvertint2arraytestjava28 at q4testmaintestjava14java result 1have any ideas,['java'] +212442,push notification from urbanairship not working with live server ie with production key in android in one of my android app i am using push notification from urban airship the problem with the app is that when i am using the development key for the push notification its working perfect the app get registered apid generated but when i am using the production key it does not work at allthe apid not generatedhowever i have configured the app for production key properly like in airshipconfigproperties 1 set key for production key 2 making inproduction truestill its not working i am getting the error app name ualib stop conecting in a holding patternon logcat everytime i am trying to connect it with the live server production keyany idea or help on this will be highly appreciated,['android'] +212452,crossplatform newline confusion for some reason my writetotextfile function stopped working all of a suddenvoid write datachar filename char writethis ofstream myfile myfileopen filename stdios baseapp myfile endl writethis myfileclosethe function was called from a loop so basically it started with an empty line and appended all the following writethis lines on a new linethen all of a sudden no more newlines all text was appended on one single line so i did some digging and i came across thiswindows cr lflinux lfmac 0sx crso i changed the line tomyfile rn writethisand it worked again but now i am confused i am coding on linux but i am reading the textfiles created with the program out on windows after transferring them with filezilla now which part of this caused the lines in the textfile to appear as one linei was pretty sure endl worked just fine for linux so now i am thinking windows messed the file up after transferring them with filezilla messing up the way the text file is written to and read out will guarantee my program to break so if someone can explain this i would appreciate iti also do not recall what i changed in my program to cause this to break because it was working just fine earlier the only thing i added was threadingediti have tried swapping the transfer mode from ascii binary even removed the forceasciifortxtextension but it makes no differences the newlines appear in linux but not on windowshow odd,"['c++', 'c']" +212465,aspnet ajaxbeginform onsuccess call back with params i want to add more params to my onsuccess call back but keep the ajax context variablewhat i did is using ajaxbeginformregister new ajaxoptions onsuccess new functionarghandlebasicformarg mycustomvariable the js functionfunction handlebasicformajaxcontext mycustomvariable var content ajaxcontextget responseget object but ajaxcontext is nullhow do i do that,"['c#', '.net']" +212478,how to write html field on aspnet mvc3 razor i have a string field on my model that contains an html value my problem is that when i place the code to render this field on my view it will be entirely reconverted to html and the final result is a big string with html characters escapedfield divrenders lt divgt how can i override this behavior and force it to write the html unescaped on my field,['html'] +212507,how to get filename from contentthisposition in headers i am downloading a file with mechanize and in response headers there is a stringcontentthisposition attachment filenamemyfilenametxtis there a quick standard way to get that filename valuewhat i have in mind now is thisfilename f1contentthispositionsplit 1replacefilename but it looks like a quickndirty solution,['python'] +212511,why does second function declaration win even though i return before it i have the following javascript codefunction function f alert1 return f function f alert2 can you explain why the alert pops up with 2 and not 1thanks,['javascript'] +212536,whats the fastest way to read a text file linebyline i want to read a text file line by line i wanted to know if i am doing it as efficiently as possible within the net c scope of thingsthis is what i am trying so farvar filestream new systemiofilestreamtextfilepath systemiofilemodeopen systemiofileaccessread systemiofilesharereadwritevar file new systemiostreamreaderfilestream systemtextencodingutf8 true 128while lineoftext filereadline null do something with the lineoftext,"['c#', '.net']" +212548,calling setvolumecontrolstream from a service i need to call setvolumecontrolstream from a service that plays some sound via stream systemobviously in an activity that is no problem but how can i do this with a service,['android'] +212558,ios verify if a point is inside a rect is there a way to verify if a cgpoint is inside a specific cgrectat example i am dragging an uiimageview and i want to verify if its central point cgpoint is inside another uiimageview how can i do,['ios'] +212565,tomcat memory consumption is more than heap permgen space i am observing a mismatch in tomcat ram consumption between what the os says and what jvisualvm saysfrom htop the tomcat jvm is has 993 mb of resident memoryfrom jvisualvm the tomcat jvm is usingheap max 1070399488 bheap size 298438656 bheap used variable between 170mb and and 270mbpermgen max 268435456 bpermgen size 248872960 bpermgen used slightly variable around 150mbfrom my understanding the os memory consumption should be heap size permgen size 522 mb but that is 471 mb less than what i am observing anyone got an idea what am i missing here ps i know that my max heap is much higher than what is used but i am assuming that should have no effect if the jvm does not use it ie heap size is lowerthanksmarc,['java'] +212566,cleanup of audionodes in web audio the web audio api docs do not really explain what do with an audionode once youre done with it for example if i am done with an audiobuffersourcenode and i want to get rid of it is it enough to just call noteoff or do i need to thisconnect it,['javascript'] +212572,find out whether property setter is called in deserialization process is there a way to find out whether an object property is called as part of the deserialization process eg by the xmlserializationreaderxbackground a typical scenario is to thisable events and complex operations in that case until the initialization is completeone approach i have found is to interpret the stack and look up whether the call is triggered by xmlserializationreaderx which is not so elegant imho is there anything betterpublic someclass someproperty get set this somepropertyvalue value thisdosomemorestuff do not do this during deserialization update as salvatore has mentioned somehow similar to how do you find out when youve been loaded via xml serialization,['c#'] +212621,net how to convert exception to string when an exception is thrown while debugging in the ide i have the opportunity to view details of the exceptionbut in code if i call exceptiontostring i do not get to see those useful detailssystemdatasqlclientsqlexception 0x80131904 could not find stored procedure fetchactiveusers snip stack tracebut visual studio has some magic where it can copy the exception to the clipboardwhich gives the useful detailssystemdatasqlclientsqlexception was unhandled by user code messagecould not find stored procedure fetchactiveusers sourcenet sqlclient data provider errorcode2146232060 class16 linenumber1 number2812 procedure servervader state62 stacktrace snip stack trace innerexceptionwell i want thatwhat would be the contents ofstring exceptiontostringexception ex todo write useful routine return extostringthat can accomplish the same magic is there a net function built in somewhere does exception have a secret method somewhere to convert it to a string,"['c#', '.net']" +212639,how to handle handler messages when activityfragment is paused slight variation on my other postingbasically i have a message handler in my fragment which receives a bunch of messages that can result in dialogs being thismissed or shown when the app is put into the background i get an onpause but then still get my messages coming through as one would expect however because i am using fragments i cannot just thismiss and show dialogs as that will result in an illegalstateexceptioni cannot just thismiss or cancel allowing state lossgiven that i have a handler i am wondering whether there is a recommended approach as to how i should handle messages while in a paused stateone possible solution i am considering is to record the messages coming through while paused and play them back on an onresume this is somewhat unsatisfactory and i am thinking that there must be something in the framework to handle this more elegantlythanks in advance peter,['android'] +212679,tinymce default font size how can i set the default font size of tinymce i have a tinymce editor and i tried all the things to change the textsize to 14px and it always shows 10px i am using rails 31 and tinymce major version 3 and minor version 44i changed tinymcethemesadvancedskinsdefaultcontentcss fontsize to 14pxi even add tinymceinit theme advanced font sizes 10px12px13px14px16px18px20px font size style values 12px13px14px16px18px20pxandbody td pre color 0 fontfamily verdana arial helvetica sansserif fontsize 14px margin 8px,"['javascript', 'html', 'css']" +212693,nsdata and uploading images via post in ios i have been combing through the many many posts about uploading images via post in ios despite the wealth of information on this topic i cannot manage to correctly upload jpeg data taken from my iphone simulator photo librarythe data once on the server is just a huge string of hexidecimal should not nsdata just be a byte stream i do not get whats going on with all the hex or why this code seems to work for everyone elsehere is the code in questionvoiduploadwithuserlocationstringnsstringuserlocationnsstring urlstring set up the form keys and values revise using 1 nsdictionary at some point neater than 2 arraysnsarray keys nsarray alloc initwithobjectsauthtextlocationnilnsarray vals nsarray alloc initwithobjectsselfauthtokenselftextboxtextuserlocationnil set up the request objectnsmutableurlrequest request nsmutableurlrequest alloc init autoreleaserequest seturlnsurl urlwithstringurlstringrequest sethttpmethodpostadd contenttype to header need to use a string boundary for data uploadingnsstring boundary nsstring stringwithstring0xkhtmlboundarynsstring contenttype nsstring stringwithformatmultipartformdata boundaryboundaryrequest addvaluecontenttype forhttpheaderfield contenttypecreate the post bodynsmutabledata body nsmutabledata databody appenddatansstring stringwithformatrnboundary datausingencodingnsasciistringencodingadd keyvalue pairs no idea why all the rs and ns are necessary but everyone seems to have themfor int i0 ikeys count i body appenddatansstring stringwithformatcontentthisposition formdata namernrnkeys objectatindexi datausingencodingnsasciistringencoding body appenddatansstring stringwithformatvals objectatindexi datausingencodingnsasciistringencoding body appenddatansstring stringwithformatrnrnboundary datausingencodingnsasciistringencodingbody appenddatansstring stringwithstringcontentthisposition formdata nameimagern datausingencodingnsasciistringencodingbody appenddatansstring stringwithstringcontenttype applicationoctetstreamrnrn datausingencodingnsasciistringencodingbody appenddatansdata datawithdataselfimagedatabody appenddatansstring stringwithformatrnrnboundary datausingencodingnsasciistringencoding set the body of the post to the reqeustrequest sethttpbodybody make the connection to the webnsdata returndata nsurlconnection sendsynchronousrequestrequest returningresponsenil errornilnsstring returnstring nsstring alloc initwithdatareturndata encodingnsutf8stringencodingnslogreturnstringkeys releasevals releasethanks for your time,"['iphone', 'ios']" +212736,ios line graphing what would be the easiest way to graph a line graph on a ios app i am building a ios app that needs a line graph i do not need anything complex just something that will graph a int i have seen core graph but not sure if thats the way to go,"['iphone', 'objective-c']" +212758,storing hierarchical data in mysql with high write load i am building web application that should have high write load and thousands even millions of hierarchical records representing user definedconstructed trees i am not trying to build forum with threads but huge database with thousands of smallsized hierarchies trees with up to 1020 descendantsi am aware of many models for storing hierarchies currently i am using nested sets but performance with huge data and load is issue i am also doubtful that adjacency lists or something similar may resolve thisi have been experimenting with mongo database which is superfast keyvalue storage but i can use only mysqli would like to hear about other people experiences with similar issues,['mysql'] +212760,why does the use of random with a hardcoded seed always produce the same results the following simple program in java uses the javautilrandom class such that it always thisplays hello world the code snippet can be seen belowpackage nomainimport javautilrandomfinal public class j public static string randomstringint seed random rand new randomseed stringbuilder sb new stringbuilder forint i0i int nrandnextint27 if n0 break sbappendchar n return sbtostring public static void mainstring args systemoutprintlnrandomstring229985452 randomstring147909649 there is some surprise in that it always thisplays hello world even if the random class is used that causes the random numbers to generate hence the numbers should be changed on each run and the corresponding characters should be changed accordingly but it always thisplays only one stable string which is as mentioned above hello world why does it happen,['java'] +212767,javascript performance difference between double equals and triple equals in javascript is there a performance difference between using a double equals vs using a triple equals example if foo bar vs if foo bar,['javascript'] +212779,post json data to simple rails application with curl i set up a simple new rails application with model entry with attributes title and content using scaffolding now i am trying to use curl to post the json data rather than using the browser the following seems to work ie successfully posted with null datacurl verbose header accept applicationjson header contenttype applicationjson request post data httplocalhost30entriesthe following does not workcurl verbose header accept applicationjson header contenttype applicationjson request post data contenti belong to atitlea httplocalhost30entriesi have tried many variations the errors i get are mostly host not found or unexpected token at the json data,"['ruby-on-rails', 'ruby']" +212791,alternatives to php for inline web programming i first learned web programming with php a while back it has some features that i find very helpful but the overall language is not something i enjoy just as a matter of personal preference i am wondering what alternatives i could use to provide similar functionality using a different underlying programming language python rubywhat i am looking forgeneral purpose programming capabilityinline serverside code embedded in html ie i want to be able to make my documents pure html if desired rather than demanding special syntax even where i do not want dynamic contentaccess to request parametersability to send headers set cookies etcpreferablydoes not require a separate server processeasy to connect with apachedoes anyone have any suggestionsone thing i tried to do was embedded ruby erb through cgi this looked like a good fit on paper unfortunately i was not able to get it to work because i was following a few different guides and the result of combining them did not work out at any rate it seems this would not allow me to set arbitrary headers and more importantly use sessions and cookiesnote i am not looking for a full web framework at the moment just relatively small amounts of dynamic content among otherwise html pagesthanks,"['php', 'python', 'ruby']" +212803,how to do copypaste function programmatically in iphone i have a textview with some text and a copy button in that viewwhen the user enter some text and press the copy button it needs to copy that text and paste that text wherever he wantsi know there is a default copypaste menucontroller in iosbut i want to do this functionality in a button clicki think there is uipasteboard to do this functionalitybut i do not know how to use itso please help me to do this,['iphone'] +212806,list all sequences in hsqldb 18 how can i list all sequences in a specific schema in hsqldb 18note hsqldb 18 does not support the information schema tables introduced in 20,"['java', 'sql']" +212826,how to stop flickering c winforms i have a program that is essentially like a paint application however my program has some flickering issues i have the following line in my code which should get rid of flickering but does not thissetstylecontrolstylesallpaintinginwmpaint controlstylesuserpaint controlstylesdoublebuffer truemy codeminus the super and sub classes for the shapes is as followsusing systemusing systemcollectionsgenericusing systemcomponentmodelusing systemdatausing systemdrawingusing systemlinqusing systemtextusing systemwindowsformsnamespace paint public partial class paint form private point startpoint private point endpoint private rectangle rect new rectangle private int32 brushthickness 0 private boolean drawspaint false private listshapes listofshapes new listshapes private color currentcolor private color currentboardercolor private boolean isshaperectangle false private boolean isshapecircle false private boolean isshapeline false public spaint initializecomponent thissetstylecontrolstylesallpaintinginwmpaint controlstylesuserpaint controlstylesdoublebuffer true currentcolor colorred currentboardercolor colordodgerblue isshaperectangle true private void panelarea paintobject sender painteventargs e graphics g panelareacreategraphics if drawspaint true pen p new pencolorblue pdashstyle systemdrawingdrawing2ddashstyledash if isshaperectangle true gdrawrectanglep rect else if isshapecircle true gdrawellipsep rect else if isshapeline true gdrawlinep startpoint endpoint foreach shapes shape in listofshapes shapedrawg private void panelarea mousedownobject sender mouseeventargs e startpointx ex startpointy ey drawspaint true private void panelarea mousemoveobject sender mouseeventargs e if ebutton systemwindowsformsmousebuttonsleft if ex startpointx rectx startpointx rectwidth ex startpointx else rectx ex rectwidth startpointx ex if ey startpointy recty startpointy rectheight ey startpointy else recty ey rectheight startpointy ey panelareainvalidate private void panelarea mouseupobject sender mouseeventargs e endpointx ex endpointy ey drawspaint false if rectwidth 0 rectheight 0 if isshaperectangle true listofshapesaddnew therectanglesrect currentcolor currentboardercolor brushthickness else if isshapecircle true listofshapesaddnew thecirclesrect currentcolor currentboardercolor brushthickness else if isshapeline true listofshapesaddnew thelinesstartpoint endpoint currentcolor currentboardercolor brushthickness panelareainvalidate private void rectangletoolstripmenuitem clickobject sender eventargs e isshaperectangle true isshapecircle false isshapeline false private void ellipsetoolstripmenuitem clickobject sender eventargs e isshaperectangle false isshapecircle true isshapeline false private void linetoolstripmenuitem clickobject sender eventargs e isshapecircle false isshaperectangle false isshapeline true private void thicknesslevel0 clickobject sender eventargs e brushthickness 0 private void thicknesslevel2 clickobject sender eventargs e brushthickness 2 private void thicknesslevel4 clickobject sender eventargs e brushthickness 4 private void thicknesslevel6 clickobject sender eventargs e brushthickness 6 private void thicknesslevel8 clickobject sender eventargs e brushthickness 8 private void thicknesslevel10 clickobject sender eventargs e brushthickness 10 private void thicknesslevel12 clickobject sender eventargs e brushthickness 12 private void thicknesslevel14 clickobject sender eventargs e brushthickness 14 private void fillcolour clickobject sender eventargs e colordialog fillcolourdialog new colordialog fillcolourdialogshowdialog currentcolor fillcolourdialogcolor panelareainvalidate private void button1 clickobject sender eventargs e colordialog fillcolourdialog new colordialog fillcolourdialogshowdialog currentboardercolor fillcolourdialogcolor panelareainvalidate how do i stop the flickeringupdatethis code actually works great when i am drawing directly on the form however when i try to draw on the panel flickering becomes an issue,['c#'] +212836,what is a good combination of tools currently for implementing restj2eedatabase custom auth was just wondering at the current point in time what is a good combination of toolsframeworkslibraries for implementing a rest api on top of j2ee that integrates to a backend rdb and using openid for authenticationwhat i am looking to implement is a server component that provides a set of services all of which will utilise openid authentication and the services will retrieve or update information tofrom a backend relational database environment what i am interested in are application server options available eg tomcat glassfish etc ides eg eclipse netbeans intellij etc additional components useful for implementing rest and json payloads what is best practicegood techniqueoptions available for database integration from the services hibernate via spring hibernate directly raw jdbc connections for integrating authentication via openid what is an appropriate integration point for any custom authentication mechanism within the j2ee environment are there any commonly used solutionsplugins available for openid etcalso any pointers to good current tutorials books etceditunfortunately i have not had as much time to research the results to this question as i would have liked at this stage i have found that installingsetting up rest with jersey was very quick and i believe i can use a containerrequestfilter to provide the openid support as per the article here i intend on using openid4java for the openid support with the pape extensions to get users email address returned i do not need oauth as i do not need to access any of the users other openid details or info on their openid site from my server appi have had a look at the latest spring it looks very good and if i were needing to build a web client with my solution or had more time to look at both i could easily have ended up leaning that way thanks for the good answers and replies hard to pick a single correct answer i have accepted yves answer because it is correct and the way i am going at the moment with minimal time to research properly but awarded the bounty to cfontes answer as it is also correct and he is replied with additional information and justification,['java'] +212837,enable list item to clickable area in jquery mobile descriptionfollowing code piece is used in androidiphone for roundabout carousal each li is 100px x 100px in width and height and link is top of the li div datarolecontent datathemeaa ul classroundaboutholder li classroundaboutmoveableitem a href url for action graph label forlink ali li classroundaboutmoveableitem a href url for action graph label forlink ali li classroundaboutmoveableitem a href url for action graph label forlink ali li classroundaboutmoveableitem a href url for action graph label forlink ali li classroundaboutmoveableitem a href url for action graph label forlink ali ul divcssroundaboutholder liststyle none width 75 height 10em margin 1em autoroundaboutmoveableitem height 100px width 100px border 1px dotted 9 backgroundcolor f3f3f3 fontsize 2em cursor pointercurrent behaviorin the items anchor only behave as link jump to the given referenceexpected behaviorwhen user clicked on li it should jump to given reference relative resource from stackoverflowhow do i make the whole area of a list item in my navigation bar clickable as a linkmake a list item clickable htmlcsseventhough solution come to near my issue i need to find generic solution because i cant set padding for all at onece or one by one because link label may change time to timeadded and tested asfollowsthisplayinlineblock and padding then issue is sorted but time to time padding should be change,"['jquery', 'css']" +212859,reopen wpf window from a console application i want to open a wpf window from a console application after referring to this post it works finethe problem is when the user closed the wpf window manually it can no long be reopened from the console throwing the exception message cannot create more than one systemwindowsapplication instance in the same appdomainhere is the codeclass program static void mainstring args string inputnull while input consolereadline y works fine at the first iteration but failed at the second iteration startwpfthread private static void openwindow exceptioncannot create more than one systemwindowsapplication instance in the same appdomain is thrown at the second iteration var app new systemwindowsapplication var window new systemwindowswindow apprunwindow user closes the opened window manually private static void startwpfthread var thread new thread openwindow threadsetapartmentstateapartmentstatesta threadisbackground false threadstart how can i reopen the wpf window,"['c#', '.net']" +212887,sizeof structures not known why why cannot i use sizeof on simple structsegprivate struct floatshortpair public float myfloat public short myshortint size sizeoffloatshortpair cs0233error cs0233 floatshortpair does not have a predefined size therefore sizeof can only be used in an unsafe context consider using systemruntimeinteropservicesmarshalsizeofmsdn states the sizeof operator can only be used for types that are compiletime constants if you are getting this error make sure that the size of the identifier can be determined at compile time if it cannot then use sizeof instead of sizeofhow are float and short not compile time constants 8,['c#'] +212897,boostgeometry union simplification how it works there is great library for geometry in boost it allows also to draw svg images i want to use it in some project of mine but it works really strange for me see image belowso we have 3 pixel points represented as square poligons in 2d space 1 1 0 1pic 1we want to get from them a union and simplify it so that when we scale it wed get a triangle like1 1 1 1 1 11 1 1 1 1 1 1 1 1 1 1 10 1 1 1 1 1 0 0 1 1 1 1 0 0 0 1 1 1pic 2but we get thiswhere yellow doted line is union and green is simplificationsourcecodeinclude iostreaminclude fstreaminclude boostassignhppinclude boostalgorithmstringhppinclude boostgeometrygeometryhppinclude boostgeometrygeometriesgeometrieshppinclude boostgeometrymultigeometriesmulti polygonhppinclude boostgeometryalgorithmsenvelopehppinclude boostgeometryextensionsiosvgsvg mapperhpptemplate typename geometry1 typename geometry2void create svgstdstring const filename geometry1 const a geometry2 const b typedef typename boostgeometrypoint typegeometry1type point type stdofstream svgfilenamec str boostgeometrysvg mapperpoint type mappersvg 400 400 mapperadda mapperaddb mappermapa fillopacity05fillrgb1532040strokergb1532040strokewidth2 mappermapb opacity08fillnonestrokergb2551280strokewidth4strokedasharray17strokelinecaproundint main create points each point square poligon boostgeometrymodelpolygonboostgeometrymodeld2point xydouble one two three boostgeometryread wkt polygon1 1 1 0 0 0 0 1 one boostgeometryread wkt polygon2 2 2 1 1 1 1 2 two boostgeometryread wkt polygon1 1 1 2 0 2 0 1 three create a container for joined points structure boostgeometrymodelmulti polygon boostgeometrymodelpolygonboostgeometrymodeld2point xydouble output simpl join points one by one because one day we would have many boostgeometryunion one two output boostgeometryunion output three output simplify joined structure boostgeometrysimplifyoutput simpl 05 create an svg image create svgmake envelopesvg simpl output requires at least boost 1470 and 3 files from boostgeometryextensionsiosvgso how to make it simplify like i want meaning to get shape like pic 2updatecreated new code works correctly quite testedinclude iostreaminclude fstreaminclude boostassignhppboostinclude boostalgorithmstringhppinclude boostgeometrygeometryhppinclude boostgeometrygeometriesgeometrieshppinclude boostgeometrymultigeometriesmulti polygonhppinclude boostgeometrygeometriesadaptedboost tuplehppinclude boostforeachhppand this is why we use boost geometry from boost trunk include boostgeometryextensionsiosvgsvg mapperhppboost geometry register boost tuple cscscartesiantemplate typename geometry1 typename geometry2void create svgstdstring const filename geometry1 const a geometry2 const b typedef typename boostgeometrypoint typegeometry1type point type stdofstream svgfilenamec str boostgeometrysvg mapperpoint type mappersvg 400 400 mapperadda mapperaddb mappermapa fillrulenonzerofillopacity05fillrgb1532040strokergb1532040strokewidth2 mappermapb opacity08fillnonestrokergb2551280strokewidth4strokedasharray17strokelinecaproundvoid make pointint x int y boostgeometrymodelpolygonboostgeometrymodeld2point xydouble ring using namespace boostassign boostgeometryappend ring boostgeometrymodeld2point xydoublex1 y1 boostgeometryappend ring boostgeometrymodeld2point xydoublex y1 boostgeometryappend ring boostgeometrymodeld2point xydoublex y boostgeometryappend ring boostgeometrymodeld2point xydoublex1 y boostgeometryappend ring boostgeometrymodeld2point xydoublex1 y1 boostgeometrycorrectringvoid create pointint x int y boostgeometrymodelmulti polygon boostgeometrymodelpolygonboostgeometrymodeld2point xydouble mp boostgeometrymodelmulti polygon boostgeometrymodelpolygonboostgeometrymodeld2point xydouble temp boostgeometrymodelpolygonboostgeometrymodeld2point xydouble ring make pointx y ring boostgeometryunion mp ring temp boostgeometrycorrecttemp mptempint main using namespace boostassign typedef boostgeometrymodelpolygon boostgeometrymodeld2point xydouble polygon typedef boostgeometrymodelmulti polygonpolygon mp polygon ring mp pol simpl polygon exring create point11 pol create point2 1 pol create point3 1 pol create point41 pol create point5 1 pol create point12 pol create point2 2 pol create point3 2 pol create point42 pol create point5 2 pol create point2 3 pol create point3 3 pol create point5 3 pol create point3 4 pol create point5 3 pol create point5 5 pol boostgeometrythissolvering pol baad boostgeometrysimplifypol simpl 05 good create svgmake envelopesvgpol simpl and this code creates such imageand for 3 points it returns images alike j calleja answer,['c++'] +212899,using keyword takes less space is it true that if i use the following it will take less resources and the cleanup will be faster using textreader readlogs fileopentextcflashautotemplogtxt my stuff as compared to textreader readlogs new streamreadercflashautotemplogtxt my stuffreadlogsclosereadlogsthispose,['c#'] +212911,which image caching library for ios i am building a photo album app and find a few image caching libraries namelyjmimagecachehjcachesdwebimagewhat one youd recommend or other libs not on the list i am looking forefficiencyminimum effort in terms of garbage collectionsupport for blocks preferredthanks,"['iphone', 'ios']" +212927,webscraping javascript page with python i am trying to develop a simple web scraper i want to extract text without the html code in fact i achieve this goal but i have seen that in some pages where javascript is loaded i did not obtain good resultsfor example if some javascript code adds some text i cannot see it because when i call response urllib2urlopenrequesti get the original text without the added one because javascript is executed in the clientso i am looking for some ideas to solve this problem,['python'] +212931,how to set layout gravity programmatically my question is simplehow to set my buttons layout gravity programmaticallyi found this on internet but it simply throws me a nullpointer exception button mybutton new buttonthis linearlayoutlayoutparams lplinearlayoutlayoutparamsmybuttongetlayoutparams lpgravitygravityright mybuttonsetlayoutparamslp mylinearlayoutaddviewmybuttonany solution,['android'] +212961,how does iefix solve web fonts loading in ie6ie8 lots of articles in the web like this suggest to add a iefixto the eot url i was curious to know how is this going to solve the problem thanks,['css'] +212964,viewflipper receiver not registered in my app sometimes i receive this error javalangillegalargumentexception receiver not registered androidwidgetviewflipper14806a4a8 at androidappactivitythreadpackageinfoforgetreceiverthispatcheractivitythreadjava667at androidappapplicationcontextunregisterreceiverapplicationcontextjava840at androidcontentcontextwrapperunregisterreceivercontextwrapperjava321at androidwidgetviewflipperondetachedfromwindowviewflipperjava104at androidviewviewthispatchdetachedfromwindowviewjava5891at androidviewviewgroupthispatchdetachedfromwindowviewgroupjava1076at androidviewviewgroupthispatchdetachedfromwindowviewgroupjava1074at androidviewviewgroupthispatchdetachedfromwindowviewgroupjava1074at androidviewviewgroupthispatchdetachedfromwindowviewgroupjava1074at androidviewviewrootthispatchdetachedfromwindowviewrootjava1570at androidviewviewrootdodieviewrootjava2565at androidviewviewrootdieviewrootjava2535at androidviewwindowmanagerimplremoveviewimmediatewindowmanagerimpljava218at androidviewwindowlocalwindowmanagerremoveviewimmediatewindowjava436at androidappactivitythreadhandledestroyactivityactivitythreadjava3498at androidappactivitythreadhandlerelaunchactivityactivitythreadjava3599at androidappactivitythreadaccess2300activitythreadjava119at androidappactivitythreadhhandlemessageactivitythreadjava1867 at androidoshandlerthispatchmessagehandlerjava99at androidoslooperlooplooperjava123at androidappactivitythreadmainactivitythreadjava4363at javalangreflectmethodinvokenativenative methodat javalangreflectmethodinvokemethodjava521at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava862at comandroidinternaloszygoteinitmainzygoteinitjava620at dalviksystemnativestartmainnative methodwhats this what should i do need some help pleasehere is some code on oncreate method i have this vf viewflipper findviewbyidriddetails vfsetflipinterval30 vfstartflipping populatewhere populate method is this private void populate for int i 0 i jarraylength i systemoutprintlnlungime jarraylength linearlayout l new linearlayoutthis lsetlayoutparamsnew layoutparamslayoutparamsfill parent layoutparamsfill parent lsetbackgroundcolor0x0 lsetorientationlinearlayoutvertical vfaddviewl file f new fileenvironmentgetexternalstoragedirectory downloads file files flistfiles bitmap bitmap bitmapfactorydecodefilefilesigetpath img new imageviewthis imgsetlayoutparamsnew layoutparamslayoutparamsfill parent layoutparamsfill parent imgsetimagebitmapbitmap systemoutprintlntarget targeti imgsetontouchlistenerthis imgsetidi laddviewimg img null,['android'] +212984,how to do advanced i18n with mustachejs it seems twitter is using a fork of mustachejs to provide i18n to its templatescould someone give a brief example of how this is done and perhaps also outline what semantics is necessary to crowdsource these translationsthere is of course this simple examplevar template iname is using mustachejsivar view name mattvar translationtable welsh according to google translate name is using mustachejs mae name yn defnyddio mustachejsfunction text return translationtabletext textalertmustacheto htmltemplate view alerts mae matt yn defnyddio mustachejsbut i would like some more insight on how to structure the text function and translationtable to provide conditionals singular plural etc examples of solving more advanced use cases would be much appreciated,['javascript'] +213002,sort a list in ascending order by date from sqlite i am having a code for retrieving data like this i wanted to get records with the dates in the ascending orderi tried using key date time asc but it didnt workpublic cursor fetchallreminders return mdbquerydatabase table new string key rowid key title key body key phonekey date time null null null null null,['android'] +213023,recursively iterate over all the files in a directory and its subdirectories in qt i want to recursively scan a directory and all its subdirectories for files with a given extension for example all jpg files how can you do that in qt,['c++'] +213031,how do you get matlab to write the bom byte order markers for utf16 text files i am creating utf16 text files with matlab which i am later reading in using java in matlab i open a file called filename and write to it as followsfid fopenfilename wnutf16lefprintffidsome stuffin java i can read the text file using the following codefileinputstream fileinputstream new fileinputstreamfilenamescanner scanner new scannerfileinputstream utf16le string s scannernextlinehere is the hex outputoffseth 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 130 73 00 6f 00 6d 00 65 00 20 00 73 00 74 00 75 00 66 00 66 00 some stuffthe above approach works fine but i want to be able to write out the file using utf16 with a bom to give me more flexibility so that i do not have to worry about big or little endian in matlab i have codedfid fopenfilename wnutf16fprintffidsome stuffin java i change the code tofileinputstream fileinputstream new fileinputstreamfilenamescanner scanner new scannerfileinputstream utf16string s scannernextlinein this case the string s is garbled because matlab is not writing the bom i can get the java code to work just fine if i add the bom manually with the added bom the following file works fineoffseth 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 150 ff fe 73 00 6f 00 6d 00 65 00 20 00 73 00 74 00 75 00 66 00 66 00 aa34some stuffhow can i get matlab to write out the bom i know i could write the bom out separately but i would rather have matlab do it automaticallyaddendumi selected the answer below from amro because it exactly solves the question i posedone key thiscovery for me was the difference between the unicode standard and a utf unicode transformation format see bomhtml the unicode standard provides unique identifiers code points for characters utfs provide mappings of every code point to a unique byte sequence since all but a handful of the characters i am using are in the first 128 code points i am going to switch to using utf8 as romeo suggests utf8 is supported by matlab the warning shown below would not need to be suppressed and java and for my application will generate smaller text filesi suppress the matlab warningwarning the encoding utf16le is not supportedwithwarning off matlabiofununsupportedencoding,['java'] +213032,paramiko piping blocks forever on read i have a problem with getting piping to work with paramikothis worksh paramikosshclientstdin stdout stderr sshexec commandfind tmpstdoutreadthis does not work blocks forever on stdoutreadstdin stdout stderr sshexec commandbash stdinwritefind tmpnstdinclosestdoutreadany ideasediti looked at the source code for paramiko and channelfileclose does not really do anything in terms of communication so i looked at the channel api and this seems to workstdinwritefind tmpnstdinflushstdinchannelshutdown writestdoutread,['python'] +213103,using parent constructor in a child class in java i have a class childclass that extends the class parentclass rather than completely replace the constructor for the parent class i want to call the parent clas constructor first and then do some extra worki believe that by default the parent clas 0 arguments constructor is called this is not what i want i need the constructor to be called with an argument is this possiblei triedthis childclass new parentclasomeargumentbut that does not work because you cannot modify this,['java'] +213116,immutable vs mutable types i am confused on what an immutable type is i know the float object is considered to be immutable with this type of example from my bookclass roundfloatfloat def new cls val return float new cls roundval 2is this considered to be immutable because of the class structure hierarchy meaning float is at the top of the class and is its own method call similar to this type of example even though my book says dict is mutableclass sortedkeydictdict def new cls val return dict new cls valclearwhereas something mutable has methods inside the class with this type of exampleclass sortedkeydict adict def exampleself return selfkeysalso for the last clasortedkeydict a if i pass this type of set to itd zhengcai 67 huijun 68xinyi 2without calling the example method it returns a dictionary the sortedkeydict with new flags it as an error i tried passing integers to the roundfloat class with new and it flagged no errors,['python'] +213146,resource interpreted as image but transferred with mime type texthtml magento i am getting below error when uploading a new product image for my magento shopresource interpreted as image but transferred with mime type texthtmlis there a reason why this is happening,['php'] +213149,java database connection pool bonecp vs dbpool vs c3p0 for a java app outside of a j2ee container which connection pool library is the besti heard c3p0 is getting outdatedjakartas common pool library is no longer under developmenttherefore i am left with bonecp and dbpool from what i can tell both have limited activity the main difference i can see is performance which bonecp seems to win out with however the documentation is pretty weakwhich database pool library have you used in the real world and why what was the good and bad,['java'] +213161,java starting a new thread in a constructor why is starting a new thread in a constructor frowned upon in java or anywhere for that matter i am getting warnings from netbeans for doing so but it is not giving me any refactoring suggestions i am writing a clientserver swing application and the thread i am starting is in the servers jframe constructor in order to continuously listen for client datagramswhy is this not good practice and how should i avoid it,['java'] +213182,property with type sel in objectivec i would like to declare a property with type sel like thisproperty nonatomic assign sel myselectoris assign correct here perhaps assign can be omitted,['objective-c'] +213187,nested type parameters in java this is an example which i made up to be a simplification of my real code so i apologize if it is a little contrived what i would like to do is to effectively get two type parameters out of a single nested type argument i am pretty sure this is impossible but i thought i would give it a shotnot legal java codepublic class fooc extends collectiont where t is another type parameter private c coll public fooc coll thiscoll coll public void addt elem thiscolladdelem updated to add getter i may need to retrieve the collection again or pass it on to another function that needs the specific c type public c getcoll return coll liststring strings new arrayliststringfooliststring foo new fooliststringstringsfooaddhelloi know that i could do it by adding another type parameterpublic class fooc extends collectionttbut then i have to add the redundantfooliststringstring foo new fooliststringstringstringsand in my real world case my generics can sometimes be specified in the implements clause likepublic class bar implements bazstringhaving to specify that second type parameter is even more painful then because it feels like it throws the implementation details in my face having to sayfoobarstringwhen there is a relationship between string and bar already just seems inelegant i get that its java so that goes with the territory but just curious if there was a solution for this,['java'] +213211,javascript regex for alphabetic characters and spaces i need a regex for javascript that includes az az and spacesfor example the string bob says hi would be accepted but not there were 4 clownsthe closest i have gotten is azaz which includes az and az but not spaces,['javascript'] +213222,how to specify ruby regex when using active record in rails to get all jobs which invoice number is a pure number i dojobwhereinvoice number regexp digitis it possible to do the same by specifying the regex in ruby rather than mysql,"['mysql', 'ruby-on-rails']" +213233,printing hexadecimal characters in c i am trying to read in a line of characters then print out the hexadecimal equivalent of the charactersfor example if i have a string that is 0xc0 0xc0 abc123 where the first 2 characters are c0 in hex and the remaining characters are abc123 in ascii then i should get c0 c0 61 62 63 31 32 33however printf using x gives mefc0 fc0 61 62 63 31 32 33how do i get the output i want without the f and why is it that only c0 and 80 has the f but not the other characters,['c'] +213247,stop eclipse switch to debug tab my problem is somewhat like the question here and here but none of those answer can apply to my situationi am running tomcat inside eclipse and my project has some quartz job that run by schedule those quartz job meets null pointer exception very often since they must parse documents from an untrusted source and surely the team who are working with those jobs cannot fix them right awaythe result is that eclipse pop up debug tab every now and then usually take up focus so that i cannot look what happen in console moreover when eclipse meet the exception it pop out to take focus out of the program i currently work in browser email it is very annoyingcan i simply skip all the null pointer exceptions since the fail of the jobs does not affect my program anyway or is there a way to keep the focus on the console tab and keep eclipse does not complain everytime an exception pop outi am very thankful for any possible solutionupdate i am using eclipse helios with few plugins,['java'] +213299,python threading module import failure i am trying to import the threading module however i just seem to get errors for no good reason here is my codeimport threadingclass thethread threadingthread def run self print insert some thread stuff here print i will be executedyeah print there is not much to itthethreadstartand the errorstraceback most recent call last file threadingpy line 1 in module import threading file cuserstrentdocumentsscriptingpythonthreadingthreadingpy line3 in module class thethread threadingthread attributeerror module object has no attribute threadpress any key to continue python statspython 272 default jun 12 2011 150859 msc v1500 32 bit intel on win 32,['python'] +213317,java drawing a circle when mouse clicked i am writing a program that when the mouse is clicked a circle will be drawn the below code i have wrote so far import javaawtimport javaxswingimport javaawteventactioneventimport javaawteventactionlistenerimport javaawteventmouseeventimport javaawteventmouselistenerimport javaxswingeventimport javaawtgeompublic class test extends jframe implements actionlistener mouselistener shape circle new ellipse2dfloat10 10 10 10 public test setsize250150 addmouselistenerthis public static void mainstring args todo code application logic here javaawteventqueueinvokelaternew runnable public void run test frame new test framesetvisibletrue public void actionperformedactionevent ae public void drawcircleint x int y graphics g thisgetgraphics gdrawovalx y x y gsetcolorcolorblack gfillovalx y 2 2 public void mouseclickedmouseevent e drawcircleegetx egety repaint public void mouseexitedmouseevent e public void mousepressedmouseevent e public void mousereleasedmouseevent e public void mouseenteredmouseevent e the code is a 400x400 jframe when clicked open thisplay a circle at a half seconds the problem is that when i release the mouse the circle thisappear why,['java'] +213332,elasticsearch server thiscovery configuration i have installed elasticsearch server that i am running by elasticsearch f 018211698 initializing loaded sites 018211698 initialized 018211698 starting bound address inet09300 publish address inet19216811069300 new master stingrayocw4qpdmsfwud9puxhon1qinet19216811069300 reason zenthiscojoin elected as master elasticsearchocw4qpdmsfwud9puxhon1q recovered 0 indices into cluster state bound address inet09200 publish address inet19216811069200 018211698 startedhow i can configure java client to connect to this serveri have justnodeclienttruebut after trying to connect i am receivingorgelasticsearchthiscoverymasternotthiscoveredexception at orgelasticsearchactionsupportmastertransportmasternodeoperationaction3ontimeouttransportmasternodeoperationactionjava162if i am configuring java client asnodedatafalsei am getting following logsinfo main nodeinternalinfo93 stark tony 018213008 starting info main transportinternalinfo93 stark tony bound address inet09301 publish address inet19216811069301info elasticsearchstark tonyclusterserviceupdatetaskpool13thread1 serviceinternalinfo93 stark tony new master stark tonywknn96hgtkwxrnsr0eozjainet19216811069301datafalse reason zenthiscojoin elected as masteras i understood it means that this new node supposed to be client node made itself a new master node and i do not from log that it is found and connect to any other nodeboth server and client are started on same machine 19216811069200 are accessible from browserand i cannot find any good documentation about thiscovery config where i can read more about elasticsearch configurations and how to configure java client,['java'] +213334,eclipse maven to manage only dependencies and nothing more is it possible for maven plugin to manage only dependencies and nothing morei work with strange maven project and want eclipsemaven plugin only to read dependencies from pomxml and add it to project classpath and nothing morei do not want it to set exclusion filters source folders and output folders or to overwrite other dependenciesalso pomxml is not located in the source folder of eclipse project i know i could use mvn eclipseeclipse task manually but it mess with my classpath and project files which i do not want to merge manuallyto summary i want that all dependencies from pomxml are automatically managed by plugin but for plugin not to touch anything elseedit the problem is that whenever something in pomxml changes maven plugin changes my project configurationedit it has to be maven since there is already pomxml which i can replace with sbt or ivy or lein or anything eles,['java'] +213343,is there a way to close the ios simulator from the command line is there any way to quit the ios simulator via a command line scriptbackgroundi am setting up a continous integration environment to enable ios builds to compile and be tested automatically as part of this i am running scripts using apples ui automation tool within instrumentsi have managed to automate the execution of the scripts on the ios simulator by running instruments from the command line but now i now want to automate quitting of the simulatori have tried some apple script similar to this post how can i reset the ios simulator from the command line but get the error access for assistive devices is thisabled hopefully there is a simpler way,['ios'] +213344,java volatile implied order guarantees my question is an extension to this one java volatile guarantees and outoforder executionto make it more concrete let us say we have a simple class which can be in two states after it is initializedclass a private volatile boolean state private volatile boolean initialized false boolean getstate if initialized throw new illegalstateexception return state void setstateboolean newstate state newstate initialized true the field initialized is declared volatile so it introduces happenbefore barrier which ensures that reordering cannot take place since the state field is written only before initialized field is written and read only after the initialized field is read i can remove the volatile keyword from declaration of the state and still never see a stale value questions areis this reasoning correctis it guaranteed that the write to initialized field would not be optimized away since it changes only the first time and the barrier would not be lostsuppose instead of the flag a countdownlatch was used as an initializer like this class a private volatile boolean state private final countdownlatch initialized new countdownlatch1 boolean getstate throws interruptedexception initializedawait return state void setstateboolean newstate state newstate initializedcountdown would it still be alright,['java'] +213352,what is the best way get the symmetric difference between two sets in java i am wondering if there is a quickclean way to get the difference between two sets i havesetstring s1 new hashsetstrings1addas1addbs1addcsetstring s2 new hashsetstrings2addbi need something likesetstring diff somethingdiffs1 s2 diff would contain a cjust to clarify i need the symmetric difference,['java'] +213359,google maps v3 circle circle that i created do not match i created a circle using the google maps v3 api and also tried to make a circle of markers with the same radius problem the one i created is oblique while the one by google maps is a nice round circle what went wronggoogle maps v3 circle code draw search circlesearch circle new googlemapscirclesearch circlesetcentertarget latlngsearch circlesetradiustravel time average speedsearch circlesetmapmap,"['javascript', 'jquery']" +213392,should i close the filechannel i came across an issue with one of our utility classes today it is a helper for files and contains some static file copy routines below are the relevant methods extracted along with a test methodthe problem is that sometimes the setlastmodified call fails returning falseon my pc windows 7 latest java i sometimes get the setlastmodified failed message about 25 times out of 10i have worked around the problem right now by removing the filechannelclose calls but i would much prefer to understand why this is happening even if that is the correct solutiondoes anyone else get the same problemprivate void testcopy throws filenotfoundexception ioexception file src new filecpublictestsrctxt file dst new filecpublictestdsttxt for int i 0 i 10 i copyfilesrc dst public static void copyfilefinal file from final file to throws filenotfoundexception ioexception final string tmpname togetabsolutepath tmp copy to a tmp file final file tmp new filetmpname do the transfer transferfrom tmp preserve time if tmpsetlastmodifiedfromlastmodified systemerrprintlnsetlastmodified failed in case there is one there already todelete rename it in tmprenametotopublic static void transferfinal file from final file to throws ioexception fileinputstream in null fileoutputstream out null try in new fileinputstreamfrom out new fileoutputstreamto transferin out finally if null in inclose if null out outclose public static void transferfinal fileinputstream from final fileoutputstream to throws ioexception filechannel srcchannel null filechannel dstchannel null try srcchannel fromgetchannel dstchannel togetchannel srcchanneltransferto0 srcchannelsize dstchannel finally if null dstchannel dstchannelclose if null srcchannel srcchannelclose edit i have changed the code to only close the streamss and not the filechannels because research suggests closing the filechannel also closes the stream,['java'] +213434,onclick javascript to make browser go back to previous page is there a function i can attach as a click event of a button to make the browser go back to previous pageinput nameaction typesubmit valuecancel,"['javascript', 'html']" +213435,associative array versus object in javascript in my script there is a need to create a hash table i searched in google for this most of the folks are recommending javascript object for this purpose problem is some of the keys in the hash table have in them i am able to create these keys easily with the associative arraysi do not understand why associative arrays are bad first thing that is mentioned in the sites that i looked at is the length property i am coming from the perl background where i used hashes most common uses were to get the value from a key check if a key exists delete a keyvalue pair add a keyvalue pair if these are my common uses can i safely use associative array,['javascript'] +213437,context manager for pythons mysqldb i am used to spoiled by pythons sqlite interface to deal with sql databases one nice feature in pythons sqlites api the context manager ie pythons with statement i usually execute queries in the following wayimport as sqlitewith sqliteconnectdb filename as conn query insert or ignore into shapes values results connexecutequery id1trianglewith the code above if my query modifies the database and i forget to run conncommitthe context manager runs it for me automatically upon exiting the with statement it also handles exceptions nicely if an exception occurs before i commit anything then the database is rolled backi am now using the mysqldb interface which does not seem to support a similar context manager out of the box how do i create my own there is a related question here but it does not offer a complete solution,"['python', 'mysql']" +213445,objectivec getter decorator for boolean values i was reviewing the objectivec programming language documentation to get a better understanding of property declaration and implementation i came across this line and thought it might be important to the way i codetypically you should specify accessor method names that are keyvalue coding compliant see keyvalue coding programming guideaa common reason for using the getter decorator is to adhere to the ispropertyname convention for boolean valuesuntil now i have simply used thisproperty nonatomic assign bool abooleanpropertybut i have always had a sense that this may not be quite righti do not understand that last part highlighted in the documentation how does that suggest that i should provide a getter decorator and what would that do for me,['objective-c'] +213447,resources for working with machine learning in f i have learned a machine learning course using matlab as a prototyping tool since i got addicted to f i would like to continue my machine learning study in f i may want to use f for both prototyping and production so a machine learning framework would be a great start otherwise i can start with a collection of librarieshighlyoptimized linear algebra librarystatistics packagevisualization library which allows to draw and interact with charts diagramsparallel computing toolbox similar to matlab parallel computing toolboxand the most important resources to me are books blog posts and online courses regarding machine learning in a functional programming language focamlhaskell can anyone suggest these kinds of resource thankseditthis is a summary based on the answers belowmachine learning frameworksinfernet an net framework for bayesian inference in graphical models with good f supportwekasharper a f wrapper around the popular data mining framework wekamicrosoft sho a continuous environment development for data analysis including matrix operations optimization and visualization on net platformrelated librariesmathnet numerics internally using intel mkl and amd acml for matrix operations and supporting statistics functions too microsoft solver foundation a good framework for linear programming and optimization tasksfsharpchart a nice data visualization library in freading listnumerical computing it is great for starting with machine learning in f and introduces various tools and tipstricks for working with these math libraries in ff and data mining blog it is also from yin zhu the author of numerical computing chapter highly recommendedf as a octavematlab replacement for machine learning gustavo has just started a series of blog posts using f as the development tool it is great to see many libraries are plugged in togethermachine learning in action s samples in f mathias has translated some samples from python to f they are available in githubhal daumes homepage hal has written a number of machine learning libraries in ocaml you would feel relieved if you were in doubt that functional programming was not suitable for machine learningany other pointers or suggestions are also welcome,['.net'] +213452,check if array is null or not in php i have an array like below which is generated by parsing a xml urlthe array is array tags simplexmlelement object 0 the array name is result now i want to check that if the array received like above i want to print a message of failure but how to check this array in if condition,['php'] +213458,better way to check for elements in list if i want to perform actions such as where or max i need to make sure the list is not null and has a count greater than zero besides doing something such as the following everytime i want to use the listifmylist null mylistcount 0is there something more inline or lambda like technique that i can use or another more compressed technique,"['c#', '.net']" +213459,java initialize an int array in a constructor i have a class and in that class i have this some code private int data new int3 some codethen in my constructorpublic date data0 0 data1 0 data2 0if i do this everything is ok default data values are initialized but if i instead do thispublic date int data 0it sayslocal variable hides a fieldwhywhats the best way to initialize an array inside the constructorthanks,['java'] +213485,is an arraylist or a linkedlist better for sorting i want to use data structure that needs to be sorted every now and again the size of the data structure will hardly exceed 10 itemswhich one is better arraylist or linkedlistwhich sorting algorithm is better to use,['java'] +213486,mongodb what is the most efficient way to query a single random document i need to pick a document from a collection at random alternatively a small number of successive documents from a randomlypositioned windowi have found two solutions 1 and 2 the first is unacceptable since i anticipate large collection size and wish to minimize the document size the second seems ineffective i am not sure about the complexity of skip operation and here one can find a mention of querying a document with a specified index but i do not know how to do it i am using c driverare there other solutions to the problem which is the most efficient,['c++'] +213494,whitelist security constraint in webxml i am using tomcat for my struts2 application the webxml has certain entries as shown belowsecurityconstraint webresourcecollection webresourcenamerestricted methodswebresourcename urlpatternurlpattern httpmethodputhttpmethod httpmethoddeletehttpmethod httpmethodtracehttpmethod webresourcecollection authconstraint securityconstraintsecurityconstraint webresourcecollection webresourcenameno accesswebresourcename urlpatternjspurlpattern webresourcecollection authconstraintsecurityconstraint securityconstraint webresourcecollection webresourcenameno accesswebresourcename urlpatternmyrrunnerurlpattern webresourcecollection authconstraintsecurityconstrainthow can i change above blacklisted parts to use only whitelisting part for example instead of blacklisting put delte http methods i need to whitelist other methods but i am not sure the syntax of whitelisting them what methods to whitelist them for my above webxml snippet i will appreciate if some one can provide me whitelisitng counter part for above xmledit also how would i really verify whether the solution works or notthanks,['java'] +213515,rails 3 override devise sessions controller i need to override devise sessions controller during the login process rails 309 ruby 192 devise 134 i tried this without any effectclass sessionscontroller devisesessionscontroller get resourcesign in def new resource build resource clean up passwordsresource respond with navigationalresource stub optionsresource render with scope new endendideaseditas indicated in the answer i also need to change the route in addition i also need to copy the views it is better explained heremy custom strategydeviserbconfigwarden do manager managerstrategiesaddcustom strategy do def authenticate authenticate against 3rd party api if resbody success you userfind or initialize by emailparamsuseremail if unew record usave end successu end endend,['ruby-on-rails'] +213584,number of seconds since the beginning of the day utc timezone how do i find number of seconds since the beginning of the day utc timezone in python i looked at the docs and did not understand how to get this using datetimetimedelta,['python'] +213607,jquery check if string starts with 1234 thanks for taking the time to answer my questioni want to check if a string has exactly 7 characters and starts with 1234 how do i do thati know of stringsubstring but am not sure if i shouold use regex or are there any other alternative thanks in advance,"['javascript', 'jquery']" +213622,importing csv quoting error is driving me nuts i have been having an unbelievable time trying to import a csv file in ruby192the file i am trying to parse hascommas within columnsquotes within columnsuses an as the col sepcsvtxt representative input real one is 101k linesa34a34jiaseal radical in chinese characters kangxi radical 26my coderequire csvcsvforeachusersadamdesktopcsvtesttxt col sep do row puts rowto s endmy desired outputa34 a34 jia seal radical in chinese characters kangxi radical 26what i get for outputcsvmalformedcsverror unclosed quoted field on line 1from usersadamrvmrubiesruby192p290libruby191csvrb1910in block in shiftfrom usersadamrvmrubiesruby192p290libruby191csvrb1825in loopfrom usersadamrvmrubiesruby192p290libruby191csvrb1825in shiftfrom usersadamrvmrubiesruby192p290libruby191csvrb1767in eachfrom usersadamrvmrubiesruby192p290libruby191csvrb1202in block in foreachfrom usersadamrvmrubiesruby192p290libruby191csvrb1340in openfrom usersadamrvmrubiesruby192p290libruby191csvrb1201in foreachfrom irb31from usersadamrvmrubiesruby192p290binirb16in mainit says there are unclosed quoted feilds but i can see that the quotes open and closeescaping the quotes does nothing i get the same error seal rchanging them to single quotes makes it work seal rthe problem is i need them to be in double quotesany ideas,['ruby'] +213626,line breaks in alert messages a noob questioni have an alertalertmessage this is my message 1 2 3 and another one 5 6 7which i am thisplaying withnsstring asd nslocalizedstring alertmessage nsstring alerttitle nslocalizedstring alerttitle uialertview alert uialertview alloc initwithtitlealerttitle messageasd delegateself cancelbuttontitleok otherbuttontitlesnil nilhow do i implement line breaks so and another one starts on the second linethank you,"['objective-c', 'ios']" +213627,private nested static class good or bad practice would it be considered a bad practice to nest a private static class inside of a nonstatic classpublic class outer private static class inner the idea here is that all instances of outer would share access to the static state another way to do it might be to just let the inner class be nonstatic and use a static instance of itpublic class outer private static innerinstance new inner private class inner similar effect what are the pros cons or other considerations with this approach i must admit that i almost never use nested classes whether static or not but i am interested in this particular concept,"['c#', '.net']" +213632,built in method to merge two sorted lists in ruby i have two lists of foo objects each foo object has a timestamp footimestamp both lists are initially sorted by timestamp in descending orderi want to merge both the lists of foo objects in a way where the final list is also sorted by timestamp in descending orderimplementing this is not hard but i was wondering whether there are there any builtin ruby methods that can do this as i assume the builtin methods will yield the best performancethanks,['ruby'] +213633,how could an instance of the base class hold an instance of the derived class i have been a net coder can not say i am a programmer for 2 years there is one question that i can not understand for years that is how could an instance of the base class hold an instance of the derived clasuppose we have two classesclass baseclass public a propertya public b propertybclass derivedclass i14baseclass public c propertychow could this happenbaseclass obj new derivedclass i mean the memory model of baseclass has no space for the newly added propertyc so how could it still hold the value of propertycon the other side how could this can not happenderivedclass obj new baseclassi thought this is the correct way since the memory model of derivedclass has all the spaces for the baseclass and even more but this is not true whyi know i am asking a really stupid question but could someone give me a more detail answer of this it would be better from the perspective of the memory or compiler,['.net'] +213679,how to register spring configuration annotated class instead of applicationcontextxml file in webxml i am using jsf and spring together in web application i have configured datasource and session factory in one configuration class which uses annotations like configuration componentscan etc i do not have any applicationcontextxml file in my project as i am handling every entry of context xml in configuration class the test case works successfully but when i deploy my web application it gives me error javalangillegalstateexception no webapplicationcontext found no contextloaderlistener registerednow if i give listener class in webxmllistener listenerclassorgspringframeworkwebcontextcontextloaderlistenerlistenerclasslistenerit gives me error webinfapplicationcontextxml not foundas per the document of contextloaderlistener it is true that if i do not give contextconfiglocation param in webxml explicitly it will search for the default spring context file named applicationcontextxml in webxml now what should i do if i do not want to use spring context file and do all the configuration with annotations how should i register listener class contextloaderlistener so that without use of xml file and using annotations only i be able to run my web application with spring and jsf,['java'] +213685,how to create 7 tablet 1280 800 screen resolution emulator in android i need to test my application on android springboard tableti need to create emulator for 1280 800 screen resolution and 7 tablet for android 30 31 or abovewhen i create emulator for 1280 800 screen resolution its consider by default 10 tabletany one please suggest me how to create for specified screen and specified 7 tabletthanks,['android'] +213686,filenotfound access is denied exception on javaio why do i get this error when i run this program this occurs after random iterations usually after the 80th iterationpublic static void mainstring args filewriter writer null try forint i 0 i 10 i file file new filecusersvarunachardesktoptodotxt iffileexists systemoutprintlnfile exists writer new filewriterfile true writerwritei systemoutprintlni writerclose iffiledelete systemoutprintlnunable to delete threadsleep10 writer null systemgc catchioexception e eprintstacktrace finally ifwriter null try writerclose catchioexception e eprintstacktrace after the exception occurs the file is not present that means the it is deleting but filewriter tries to acquire the lock before that even though it is not a multi threaded program is it because the windows is not deleting the file fast enough and hence the filewriter does not get a lock if so then filedelete method returns before windows actually deletes ithow do i resolve it since i am getting a similar issue during load testing my applicationedit 1 stacktracejavaiofilenotfoundexception cusersvarunachardesktoptodotxt access is denied at javaiofileoutputstreamopenappendnative method at javaiofileoutputstreaminitfileoutputstreamjava192 at javaiofileoutputstreaminitfileoutputstreamjava116 at javaiofilewriterinitfilewriterjava61edit 2 added fileexists and filedelete conditions in the program and the new stacktrace7452javaiofilenotfoundexception cusersvarunachardesktoptodotxt access is denied at javaiofileoutputstreamopenappendnative method at javaiofileoutputstreaminitfileoutputstreamjava192 at javaiofilewriterinitfilewriterjava90 at comtestclassmaintestclassjava25edit 3 thread dumptestclass java application comtestclass at localhost57843 thread main suspended exception filenotfoundexception fileoutputstreaminitfile boolean line 192 filewriterinitfile boolean line 90 testclassmainstring line 24 cusersvarunachardocumentssoftwaresjava jdkjdk 626jdkjrebinjavawexe 09nov2011 115734 pm edit 4 program runs successfully on different machine with same os now how do i ensure that the app with run successfully in the machine it is deployed in,['java'] +213735,finding out which control has focus is there a way to figure out which control in my visualtree has focusthis is mostly for debugging,['c#'] +213736,android get current timestamp i want to get the current timestamp like that 1320917972int time int systemcurrenttimemillistimestamp tstemp new timestamptimestring ts tstemptostring,['android'] +213739,how to merge multiple assemblies into one i consuming my service stack using exe project startup task for azure application in that i have copied following service stacks dll some azures dlls in to exe projectwhen i build this exe project then azure dlls will be bundled with my exe but service stacks dll will not be bundled with exe because to run my exe on any machine i need to copy all service stacks dll manuallyi have used this service stacks dll to use jsonserviceclient client new jsonserviceclientservicepathwhat should i have to do to bundled all these dlls in to my exe,['c#'] +213744,how to fill background image of an uiview i have an uiview and i set a background image in this wayselfviewbackgroundcolor uicolor colorwithpatternimageuiimage imagenamedsfondappzpngmy problem is that backimage is not centered inside the view but it is replayed some times to fill all the view is there a way to center image inside uiview and scretch to have screen size note i cannot use uiimageview for background cause i have a scrollview,"['iphone', 'objective-c']" +213763,why use rolap instead of plain mysql are there any performance advantages in using a rolap server such as mondrian on top of a mysql database as opposed to simply querying the mysql databasei am asking this in the context in which most of my queries will be relatively simple such as finding all the sales in a certain period but the size of the database is rather large hundreds of thousands of entries my idea was to use olap to speed up queries but now i am confused as to whether or not this is actually the purpose of this technology especially in its rolap form while trying the olap4j api i realized that i can use it to make mdx queries without even having an actual olap server just having a relational database and an olap schema for it how could that be of any use in terms of performancethanks,['mysql'] +213783,how to stop uipangesturerecognizer when object moved to certain frame i have an object of image type which i am moving using uipangesturerecognizer and i need to stop recognizing the uipangesturerecognizer when the object reaches a certain frame uipangesturerecognizer panrecognizer uipangesturerecognizer alloc initwithtargetself actionselectormove panrecognizer setminimumnumberoftouches1 panrecognizer setmaximumnumberoftouches1 panrecognizer setdelegateself templatephotoplaceholderview addgesturerecognizerpanrecognizervoidmoveuipangesturerecognizer gesturerecognizer cgpoint translatedpoint gesturerecognizer translationinviewtemplatephotoplaceholderview ifgesturerecognizer state uigesturerecognizerstatebegan firstx imageview centerx firsty imageview centery translatedpoint cgpointmake firstxtranslatedpointx firstytranslatedpointy nslog move center point nsstringfromcgpointtranslatedpoint imageview setcentertranslatedpoint how may i do this,"['iphone', 'objective-c']" +213791,how to remove the bold from a headline i have a headlineh1this is a headlineh1how do i make the phrase this is not to be bold and the rest without a changecould not find any relevent tag in textdecoration,['css'] +213797,adding constructor or function to enum i am not sure if a constructor is exactly what i am looking for but if i explain what i am trying to do hopefully someone can tell me if i am trying to do is a silly idea or whether there are ways to do itso i have an enumpublic enum messagetype normal error chat groupchat headlinethis enum is basically a wrapper for the jabbernet messagetype so i want to create my enum from this so at the moment i have a function like thisprivate messagetype convertmessagetypejabbermessagetype jabbertype messagetype type messagetypeerror switch jabbertype case jabbermessagetypenormal type messagetypenormal break etc return typeso i have to use enum messagetype type convertmessagetypejabbermessagetypegroupchatwhat i would like though is to be able to do something likeenum messagetype type messagetypejabbermessagetypegroupchat or enum messagetype type messagetypefromjabberjidjabbermessagetypegroupchatso that the conversion belongs with the enum rather than being a method outtside of,['c#'] +213819,how can we hide the tableheaderview and tablefooterview i have two buttons which i add it in one in tablefooter and other one in tableheaderi know how to hide the headerview of the table using this codetabletableheaderviewhidden yesbut the problem is there is still space in the top portion of the tablethat space is equal to the headerview sizebut the view is hidden it still has the spacehow can we thisable the tableheader by removing this spacei hope you genius developers understand my questionplease help methanks in advance,"['iphone', 'objective-c', 'ios']" +213820,how do i run groovy scripts as java from the command line i am trying to use groovyc but something is not rightecho printlnhello world testgroovygroovy testgroovyhello worldgroovyc testgroovyjava cp cutilsgroovy181embeddablegroovyall181jar testerror could not find or load main class testdir testclass102011 0254 pm 7104 testclasswhat am i missing,['java'] +213843,javascript console log in magento i have a custom phtml pages in magento as far i know magento uses jquery and prototype librariesfor example if i need external jqueryjqueryui i need to use noconflict but if i want to use consoleloghello worldin chrome 15 console i got no response nothing also tried with firebugobviously there is some conflict with magento javascript code is there any solution,['javascript'] +213850,initialize dict with keysvalues from two list i have read this linkbut how do i initialize the dictionary as well say two list keys abcd values 1234 dict i want initialize dict with keys values,['python'] +213851,how to convert stringbuffer to inputstream in java me i am new in java and learning java me development i got stuck in this conversion please help me to convert stringbuffer to inputstream thanks,['java'] +213863,restrict attribute usage to be mutually exclusive at design time i am developing a serialization class that uses attributes on custom classes to decorate whether a property is a fixed length format or a delimited format these two attributes should be mutually exclusive meaning that the developer can either specify fixedlength or delimited with appropriate constructors on a property but not both in order to reduce complexity and increase cleanliness i do not want to combine the attributes and set a flag based on the format type eg formattedformatterformattingdelimited is it possible to restrict these attributes to be mutually exclusive to one another at design time i am aware how i can check for this scenerio at runtime,['c#'] +213877,overloading operator for a nested private class possible how one can overload an operator for a nested private class like this oneclass outer private class nested friend ostream operatorostream os const nested a when trying outside of outer class compiler complains about privacyerror aclass outernesteda is private,['c++'] +213878,pyqt4 names showing as undefined in eclipse but it runs fine i am using eclipse 371 with the latest pydev addin for python coding i am using pyqt4 at the top of my file i havefrom pyqt4qtcore import from pyqt4qtgui import in addition i have the pyqt4 tree included in the project explorer listing however eclipse still thinks the names like qmainwindow are undefined the code runs fine how may i get eclipse to recognize those namesthanks,['python'] +213895,django user passes test decorator how do i implement the user passes testlambda u uis superuser decorator for class based views i have used this before for function based views and i have a work around but it feels unnaturallyshould not this be covered by the thispatch method,['python'] +213896,stdbind and stdfunction questions int funcint xreturn xstdfunctionintint x stdbindfunc stdplaceholders 1x123does x123 actually call the operator of the functor which stdfunction generated which in turn calls the operator of the functor which stdbind generated which finally calls func does this get optimized into something as optimal as calling func123where does the functor live which stdbind generates in what scope and how does stdbind name it can there be name collisionscan lambdas replace all uses of stdbindis stdbind as optimal as implementing it as a lambda insteadwhats up with the syntax of the template argument of stdfunction how does that get parsed and how can i use that template argument syntax elsewhere,['c++'] +213907,inserting image into docx using openxml and setting the size i am using openxml to insert an image into my document the code provided by microsoft works but makes the image much smallerpublic static void insertapicturestring document string filename using wordprocessingdocument wordprocessingdocument wordprocessingdocumentopendocument true maindocumentpart mainpart wordprocessingdocumentmaindocumentpart imagepart imagepart mainpartaddimagepartimageparttypejpeg using filestream stream new filestreamfilename filemodeopen imagepartfeeddatastream addimagetobodywordprocessingdocument mainpartgetidofpartimagepart private static void addimagetobodywordprocessingdocument worddoc string relationshipid define the reference of the image var element new drawing new dwinline new dwextent cx 990l cy 7920l new dweffectextent leftedge 0l topedge 0l rightedge 0l bottomedge 0l new dwdocproperties id uint32value1u name picture 1 new dwnonvisualgraphicframedrawingproperties new agraphicframelocks nochangeaspect true new agraphic new agraphicdata new picpicture new picnonvisualpictureproperties new picnonvisualdrawingproperties id uint32value0u name new bitmap imagejpg new picnonvisualpicturedrawingproperties new picblipfill new ablip new ablipextensionlist new ablipextension uri 28a0092bc50c407ea94770e740481c1c embed relationshipid compressionstate ablipcompressionvaluesprint new astretch new afillrectangle new picshapeproperties new atransform2d new aoffset x 0l y 0l new aextents cx 990l cy 7920l new apresetgeometry new aadjustvaluelist preset ashapetypevaluesrectangle uri thistancefromtop uint32value0u thistancefrombottom uint32value0u thistancefromleft uint32value0u thistancefromright uint32value0u editid 50d07946 append the reference to body the element should be in a run worddocmaindocumentpartdocumentbodyappendchildnew paragraphnew runelement i need to make the image its original size how can i do this i have googled how to do this outside of this process but that is not what i am looking for i have to assume that there are some sort of size properties inside of the given codeedit updated code still not workingpublic static void insertapicturestring document string filename using wordprocessingdocument wordprocessingdocument wordprocessingdocumentopendocument true maindocumentpart mainpart wordprocessingdocumentmaindocumentpart imagepart imagepart mainpartaddimagepartimageparttypejpeg using filestream stream new filestreamfilename filemodeopen imagepartfeeddatastream addimagetobodywordprocessingdocument mainpartgetidofpartimagepart filename private static void addimagetobodywordprocessingdocument worddoc string relationshipid string filename var img new bitmapimagenew urifilename urikindrelativeorabsolute var widthpx imgpixelwidth var heightpx imgpixelheight var horzrezdpi imgdpix var vertrezdpi imgdpiy const int emusperinch 914400 const int emuspercm 360 var maxwidthcm 1651 var widthemus longwidthpx horzrezdpi emusperinch var heightemus longheightpx vertrezdpi emusperinch var maxwidthemus longmaxwidthcm emuspercm if widthemus maxwidthemus var ratio heightemus 10m widthemus widthemus maxwidthemus heightemus longwidthemus ratio define the reference of the image var element new drawing new dwinline new dwextent cx 990l cy 7920l new dweffectextent leftedge 0l topedge 0l rightedge 0l bottomedge 0l new dwdocproperties id uint32value1u name picture 1 new dwnonvisualgraphicframedrawingproperties new agraphicframelocks nochangeaspect true new agraphic new agraphicdata new picpicture new picnonvisualpictureproperties new picnonvisualdrawingproperties id uint32value0u name new bitmap imagejpg new picnonvisualpicturedrawingproperties new picblipfill new ablip new ablipextensionlist new ablipextension uri 28a0092bc50c407ea94770e740481c1c embed relationshipid compressionstate ablipcompressionvaluesprint new astretch new afillrectangle new picshapeproperties new atransform2d new aoffset x 0l y 0l new aextents cx widthemus cy heightemus new apresetgeometry new aadjustvaluelist preset ashapetypevaluesrectangle uri thistancefromtop uint32value0u thistancefrombottom uint32value0u thistancefromleft uint32value0u thistancefromright uint32value0u editid 50d07946 append the reference to body the element should be in a run worddocmaindocumentpartdocumentbodyappendchildnew paragraphnew runelement,['c#'] +213916,how to change the font and font size of an html input tag input idtxtcomputerhow do i make my text inside the input tag bigger i want to make it 24 size font it would also be good if i can change the font from the default,"['html', 'css']" +213939,when to use addchildviewcontroller vs pushviewcontroller i just watched a 2011 wwdc presentation on implementing uiviewcontroller containment heres a link to the videothey mentioned both of these ways of adding viewcontrollers to the screen and i would appreciate some clarification on best practicesaddchildviewcontroller removefromparentviewcontrollerused with an property nonatomic readonly nsarray childviewcontrollers and self transitionfromviewcontrollercurrentview toviewcontrollernextview duration options animations completionpushviewcontroller animated popviewcontrolleranimatedthey really quickly skimmed past this in the presentationin my apps i use all custom viewcontrollers and until today i have always managed them withnextcontroller performselectorselectorsetdelegate withobjectselfcurrentpagecontrollerview removefromsuperviewselfview addsubviewnextcontrollerviewbut i understand now that this is bad practice and i am wondering what is the correct way to use addchildviewcontroller and what is the correct way to use pushviewcontrolleri really appreciate your thoughts on the matter,['iphone'] +213946,python printing a file to stdout i have searched and i can only find questions about the other way around writing stdin to a file is there a quick and easy way to dump the contents of a file to stdout,['python'] +213956,how to load image from sql server into picture box i have tried a lot to find that how can i load an image from sql server to picture box but i could not find very much helpful materialfirst i saved image into the database with the help of following queryinsert into imagetest pic id picvalues1 d11jpgnow i want to load the image into a picture box,['c#'] +213968,how to add an icon image as hint to editbox in android i need to put the search image lens as hint in edittext is it possible to do it in androidbest regards,['android'] +213981,polymorphic associations in net how do i effectivelyefficiently create polymorphic associations in netthat being said i have a few more granular questions that i would love to see as part of the broader answertechnologiesnet 40aspnet mvc 3ms sql 2008c latestadonet entity frameworklinqtoentitiescontexti am developing a consumerfacing application consisting of a dal business object layer a service broker layer for rest services and ultimately web tablet mobile and desktop front endsthis application involves hundreds of products that adhere to various classifications also the products consist of various attributions that may also be an attribute of their broader classificationsexamplewidget a and widget b both are red so they may be grouped in a view under things that are red however widget a is a toy car whereas widget b is a red bicycle so although they are both red objects they are objects of different types as such they may be grouped differently in other views eg bicycles which would show red bikes blue bikes etcgoalcreate an efficient core and service layer that is both responsive to the caller and easily maintainedwhat i am thinking of doingto easily manage all of these various attributes and relationships i thought of building a global attribute table where attributes could be logged for objects of various typesglobal attributes tableid intobjecttype int fk to objecttypes table which contains a list of types eg bicycle toy car etcobjectid int the id of the object in it is own table eg bicycles tableattributetype int fk to attributetypes table which contains various types of attributes eg color material age groupattributeid int the id of the attribute in it is own table eg colors tableso columns 3 5 objectid and attributeid would ideally have a dynamic foreign key to the table that corresponds to their typesmy thinking is that this would make searching fast model construction easy and less verbose codewise adding of future attributes and object types easier maintenance easier etcquestionsis this an acceptable or good method to follow as opposed to creating say a product table series table etc with a mile long list of columnsis there a way to accomplish dynamic foreign keyspolymorphic associations in net with out simply making a query building a model with the results querying that model etcare there any other suggestions for a better data architecture,"['.net', 'sql']" +213984,generating pdflatex with python script i am a college guy and in my college to present any kind of homework it has to have a standard coverpage with the college logo course name professors name my name and bla bla blaso i have a tex document which generate my standard coverpages pdfs it goes something likebegindocument college logovspace5cmbegincentertextbfhuge school and program name vspace1cmtextbflarge homework title vspace1cmtextbflarge course name endcentervspace25cmbeginflushrightlarge my name endflushrightso i was wondering if there is a way to make a python script that asks me for the title of my homework the course name and the rest of the strings and use them to generate the coverpage after that it should compile the tex and generate the pdf with the information givenany opinions advice snippet library is accepted,['python'] +213988,how to go into maintainance mode to safely update a production application in symfony 2 i need to update source files pull and update from the repository in my production server run migrations and regenerate cached assetsis there any mechanism in symfony 2 to do this safely like putting the site into maintainance mode which should throw a 503 or something,['php'] +213994,javascript confirm inside a jquery click function i have the followingelementclickfunction var foobar if foo bar confirmdialogue but i would like to bool the confirm function i have already triedelementclickfunction var foobar if foo bar var confirmconfirmdialogue if confirmtrue alerttrue else alertfalse but no confirmation box is generated how can i accomplish this,"['javascript', 'jquery']" +213995,highlight line in flot chart is it possible to highlight a line chart with flot i only see highlighting of the datapoints but not the lines between the pointsi use the code from the following exampleplaceholderbindplothover function event pos item xtextposxtofixed2 ytextposytofixed2 if enabletooltipcheckedlength 0 if item if previouspoint itemdataindex previouspoint itemdataindex tooltipremove var x itemdatapoint0tofixed2 y itemdatapoint1tofixed2 showtooltipitempagex itempagey itemserieslabel of x y else tooltipremove previouspoint null,"['javascript', 'jquery']" +213998,how to orderby an integer in a string field in a linq query i have some data coming out of an db that i cannot readily change the schema of i want to sort it and bind it to a control based on a numerical id the problem is that the api stores the number in a string field instead of as an int and linq barfs on the conversion attemptmycontroldatasource datafromdborderbyo intparseostringholdinganintlinq to entities does not recognize the method int32 parsesystemstring method and this method cannot be translated into a store expressionconverttoint32 does not work eitherlinq to entities does not recognize the method int32 toint32systemstring method and this method cannot be translated into a store expressionsorting as a string is not suitable because the values are not all the same length and it would order them like this 1 10 11 2 3,['c#'] +214005,killing zombie children in parent processes so i want to do the followingset up a daemon that forks a bunch of processesso the daemon forks a bunch of processesthen forks another bunch of processesthe problem is the child processes might take a long time to exit how do i prevent zombie children if the parent process has other work to do despite forking children the parent process the daemon does something like thiswhiletruesql query executed whilemysql fetch array fork children the problem is how can i wait for the children processes to exit if the parent process has to do other work besides forking children and if the children take a long time to exiti am using the system daemon pear function to create the daemon and the pcntl fork function to create the processes,"['php', 'mysql']" +214016,when a user launches new window in a home screen app when a user launches new window link in a home screen appin mobile safari this type of action would open a new tab what happens if the app is on the home screen and has nameapplemobilewebappcapable contentyes active will the window still technically be in another tab although you cant get back to the original one or will it just navigate within the current tab,['iphone'] +214031,nonblocking socket writes in java versus blocking socket writes why would someone prefer blocking writes over nonblocking writes my understanding is that you would only want blocking write if you want to make sure the other side got the tcp packet once the write method returned but i am not even sure that is possible you would have to flush and flush would have to flush the underlying operating system write socket buffer so is there any thisadvantage of nonblocking socket writes does having a large underlying write socket buffer a bad idea in terms of performance my understanding is that the smaller the underlying socket write buffer the more likely you will hit slowbuggy client and have to dropqueue packets in the application level while the underlying socket buffer is full and iswritable is returning false,['java'] +214040,headers for c posix functions where or how can i find the correct c headers to include in a c program to obtain the declaration of c functions declared in a posix compliant environmenti am asking this because i needed to use the open system call in my c program for my purposes so i initially tried to include the headers mentioned in the online documentation about open in the synopsis section which are sysstath and fcntlh however when trying to compile the compiler complained that open was not declared after a search on google i found that another possibility was unistdh i tried using that header and the program compiled so i went back to the posix documentation to read more about unistdh to check if open was mentioned there but i could not find anything about itwhat am i doing wrong why is there this thiscrepancy between the posix documentation and my gcc environment,['c++'] +214042,if i override windowonerror in javascript should i return true or false i want to log javascript errors so i am overriding windowonerror like thiswindowonerror functionmessage file linenumber var browser encodeurinavigatorappversion var error encodeurimsg message ntfilefilentlnlinenumber var user encodeuri return falsei have seen some people return true and some return false which is right and why one post mentioned something about have you have to return true or firefox will handle the error it is own way what,['javascript'] +214059,rubydebug with ruby 193 i just updated to ruby 193p0 and rails 311 now when i try to launch the server it complains that i should install rubydebug even though it is already installed rails server environmentdevelopment debug booting webrick rails 310 application starting in development on call with d to detach ctrlc to shutdown serveryou need to install rubydebug to run the server in debugging mode with gems use gem install rubydebugexitingin my gemfile i have see gem rubydebugbase19 01124gem rubydebug19 0116is it possible to run debug with the latest version of ruby,"['ruby-on-rails', 'ruby']" +214070,cannot create a managed object context on ios i created a non core data project i now want to use core data in the build phases i linked my binary with coredataframework in my application delegate method i want to manually create a managed object context like sonsmanagedobjectcontext acontext nsmanagedobjectcontext alloc initwhen i do the above i get the following errorreceiver nsmanagedobjectcontext for class message is a forward declarationany suggestions on what i might be doing wrong,['ios'] +214071,how to get the network traffic stat for video streaming applications on android i am trying to write a network traffic monitor application myself i have been using the trafficstat to get per app network traffic stat but for video applications like youtube the streamed data cannot be captured by trafficstat instead the streamed data is captured in androidprocessmedia sometimes it is captured by the total network traffic api in trafficstat instead of the per app api if there is just one video application say youtube i can always assign the data usage captured by androidprocessmedia part back to youtube but some people have multiple different video applications on the phone and those applications usually use the same method to stream video thus i cannot thistinguish how much data each video app consumesfrom android market i found my data manager which seems to correctly capture each video applications data usage so i assume there must be a way to do it but i have spent a lot of time searching the solutions not successful yet does anyone know how to do it update on 02052014 i happened to talk to the guy who implements android trafficstat in a google event he told me that earlier versions gingerbread and eariler of trafficstat is buggy the new ones in ics or later should be correct i did not test the new versions so use it with caution,['android'] +214077,what is the javascript equivalent of preg match possible duplicatehow can i use preg match in jquery what is the jquery equivalent of the php preg match feature in php it would be preg matchazaz09 strwhich checks if the string has anything other than letters and numbersi would like to add some client sided validation to my site but i have looked and looked and cannot quite find the jquery equivalent of this thanks,"['javascript', 'jquery']" +214082,using regex for switchstatement in java void menu print scanner input new scanner systemin whiletrue string s inputnext switch s case m print continue case s stat break case az1az2d1 filminfo s break case jur1 filminfos break for debugging this worked fine case q return it seems like either my regex is off or that i am not using it right in the casestatement what i want is a string that begins with exactly one uppercase letter and is followed by exactly two lowercase letters which are followed by at least one digit i have checked out the regex api and tried the three variants greedy reluctant and possessive quantifiers without knowing their proper use also checked the methods for string without finding a method that seemed pertinent to my needs,['java'] +214088,how to insert a bool into nsmutabledictionary i am trying to save a boolean database value into a map as follows recenttags setvaluensnumber numberwithboolamessage isset forkeyamessage tagnameit gives me an error saying incompatible pointer to integer conversion sending bool aka signed char to bool aka signed char how would i insert a bool into the dictionary,['ios'] +214126,how do i float two divs sidebyside without specifying a width i have two divs the first does not have much content and the second has a lot of content i want them to float sidebyside such that the first div is only as wide as the text and the second div fills the remaining amount of horizontal space and i do not want to specify fixed widthshere is the desired appearance using tablescan this easily be done with css floats or is a table layout the only way to achieve this look,['css'] +214139,applying string operations to numpy arrays are there better ways to apply string operations to ndarrays rather than iterating over them i would like to use a vectorized operation but i can only think of using map example shown or list comprehensionsarr numpyrecfromrecordsziprange5as far as i knowsplit namesname stringsprint joinmaplambda x x0upperarrstrings afaikfor instance in the r language string operations are also vectorized string unliststrsplitas far as i know 1 as far as i know pastesprintfstouppersubstrstring11collapse1 afaik,['python'] +214143,ror new command hangs i am just starting ruby on rails in terminal i entered rails new testapp and this is what happens at terminal create create readme create rakefile create configru create gitignore create gemfile create app create appassetsimagesrailspng create appassetsjavascriptsapplicationjs create appassetsstylesheetsapplicationcss create appcontrollersapplication controllerrb create apphelpersapplication helperrb create appmailers create appmodels create appviewslayoutsapplicationhtmlerb create appmailersgitkeep create appmodelsgitkeep create config create configroutesrb create configapplicationrb create configenvironmentrb create configenvironments create configenvironmentsdevelopmentrb create configenvironmentsproductionrb create configenvironmentstestrb create configinitializers create configinitializersbacktrace silencersrb create configinitializersinflectionsrb create configinitializersmime typesrb create configinitializerssecret tokenrb create configinitializerssession storerb create configinitializerswrap parametersrb create configlocales create configlocalesenyml create configbootrb create configdatabaseyml create db create dbseedsrb create doc create docreadme for app create lib create libtasks create libtasksgitkeep create libassets create libassetsgitkeep create log create loggitkeep create public create public404html create public422html create public500html create publicfaviconico create publicindexhtml create publicrobotstxt create script create scriptrails create testfixtures create testfixturesgitkeep create testfunctional create testfunctionalgitkeep create testintegration create testintegrationgitkeep create testunit create testunitgitkeep create testperformancebrowsing testrb create testtest helperrb create tmpcache create tmpcacheassets create vendorassetsstylesheets create vendorassetsstylesheetsgitkeep create vendorplugins create vendorpluginsgitkeep run bundle installand it hangs there should i just exit it and continue with the app why does not it give me back the control to terminalthanksupdate it asked me for my password and installed some gems but it does that every time i create a new rails project is this normalthanks,"['ruby-on-rails', 'ruby']" +214179,how to find the currently running applications programatically in android i am very new to android i am working on application that must get the information about the applications currently running on foreground it means if user launches any applications my application should capture the launched application information by the time my application should not interrupt launched applicationexample if user launches browser application my application should print browser application information on log how can i do this,"['java', 'android']" +214191,const char and char const are they the same from my understanding const modifiers should be read from right to left from that i get thatconst charis a pointer whose char elements cannot be modified but the pointer itself can andchar constis a constant pointer to mutable charsbut i get the following errors for the following codeconst char x new char20x new char30 this works as expectedx0 a gives an error as expectedchar const y new char20y new char20 this works although the pointer should be const righty0 a this does not although i expect it to workso which one is it is my understanding or my compilervs 2005 wrong,['c++'] +214201,deploying new relic on heroku cedar php has anyone succesfully deployed the new relic addon to a php app running on heroku cedar stack i am running a fairly high traffic facebook app on a few dynos and cannot get it to workthe best info i can find details a python deployment thanks,['php'] +214203,how to use sftp in c possible duplicatehow do i upload a file to an sftp server in c net does net support sftp i cannot find any sample onlinethanks in advance,"['c#', '.net']" +214213,comma separated list of selectors i am refactoring some code at the moment and have come across a selectorjquerytrctl00 maincontent myusercontroleachfunctionirow it looks like it is selecting trs from the user control on the page ignore the fact that the instance is fully named but it is not a syntax i am familiar with and cannot find anything in the documentation i would expect it to be writtenctl00 maincontent myusercontrol treachfunctionirow can anyone tell me if there is a difference subtle or otherwise that i am missing here,['jquery'] +214216,uninitialized const this compiles perfectly fine with the current msvc compilerstruct foo const foohowever it fails to compile with the current g compilererror uninitialized const foo fpermissivenote const struct foo has no userprovided default constructorif i provide a default constructor myself it worksstruct foo foo const foois this another case of msvc being too permissive or is g too strict here,['c++'] +214221,i want to show list items as 2 or more columns dynamic alignment i am able to do the list using floatleft like thisbut i would like to show it like this as 2 or more columnshow can i do thatsandeep gave good solution unfortunately does not work in ieneed ie7 and aboveany help,"['javascript', 'jquery', 'html', 'css']" +214226,sort eigenvalues and associated eigenvectors after using numpylinalgeig in python i am using numpylinalgeig to obtain a list of eigenvalues and eigenvectorsa somematrixarrayfrom numpylinalg import eig as eigenvaluesandvectorssolution eigenvaluesandvectorsaeigenvalues solution0eigenvectors solution1i would like to sort my eigenvalues eg from lowest to highest in a way i know what is the associated eigenvector after the sortingi am not finding any way of doing that with python functions is there any simple way or do i have to code my sort version,['python'] +214242,why are java constants declared static why are java constants declared static class foo static final int fii 2 in this i understand the use of final buy why does it have to be static why should it be a class variable and not an instance variable,['java'] +214287,how to get hash code of a string in c following java code returns hash code of a string string uri some uripublic int hashcode return urihashcodei want to translate this code to c is there any function availabe in c or an easy way to translate this,['c++'] +214291,result of calling iequatableequalst obj when this null and obj null what should iequatabletequalst obj do when this null and obj null1 this code is generated by f compiler when implementing iequatablet you can see that it returns true when both objects are null public sealed override bool equalst obj if this null return obj null if obj null return false code when both this and obj are not null 2 similar code can be found in the question in iequatable implementation is reference check necessary or in the question is there a complete iequatable implementation reference this code returns false when both objects are null public sealed override bool equalst obj if obj null return false code when obj is not null 3 the last option is to say that the behaviour of the method is not defined when this null,"['c#', '.net']" +214292,background service needs to send gps location on server i have problem with my android application i need an application that will send in background gps location every 10 minutes to the server here i have wcf service that work application needs to send data even if it is closed so i created a service for test purposes that sends to me time on server but when i insert my code for getting gps location in my service everything fails stopped unexpectedly i have reed that you need to put some receiver or something but nothing so far works so i will be very pleased if someone can help me xml version10 encodingutf8manifest xmlnsandroid packagecombiromatikgps androidversioncode1 androidversionname10 usessdk androidminsdkversion4 application androidicondrawableic launcher androidlabelstringapp name activity androidlabelstringapp name androidnameetmgpsserviceactivity intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity application application androidicondrawableic launcher androidlabelstringapp name androidnamemyapplication service androidenabledtrue androidnamemonitorservice service receiver androidenabledtrue androidnamelocationreceiver intentfilter action androidnamecombiromatikintentactionlocation intentfilter receiverapplication usespermission androidnameandroidpermissioninternetusespermission usespermission androidnameandroidpermissionread phone stateusespermission androidnameandroidpermissionsend smsusespermissionusespermission androidnameandroidpermissionaccess network state usespermission androidnameandroidpermissionaccess coarse location usespermission androidnameandroidpermissionaccess fine location manifest,['android'] +214294,how to integrate zxing without installing barcode scanner application i added zying android application to my application as library then edited manifestxml and tried to use intent integrator no luckdownloading scanner app is totally unreasonableby the wayintent scanintent new intentcomgooglezxingclientandroidscanscanintentsetpackagecomgooglezxingclientandroid1 151527793 warnsystemerr15384 androidcontentactivitynotfoundexception no activity found to handle intent actcomgooglezxingclientandroidscan catandroidintentcategorydefault pkgcomgooglezxingclientandroid has extras,['android'] +214295,c unsafe code fixed pointer passed as parameter i came across the following code on msdn unsafe static void squareptrparam int p p p unsafe static void main point pt new point ptx 5 pty 6 pin pt in place fixed int p ptx squareptrparam p pt now unpinned consolewriteline 0 1 ptx pty i am just wondering we are directly accessing pointer in squareptrparam function does it inherit information that array is fixed from calling methodwhy do not we need to explicitly set it to fixed locally in squareptrparami guess i could use some elaborations about this fixed statement,['c#'] +214339,mysql determine which database is selected after calling mysql select db to grab a database is there any way to later output the name of the database that is currently selected this seems very basic but i could not find anything on phpnet or stackoverflow all results are for no database selected,['mysql'] +214347,django reverse relation with select related i have 4 models and i want to retrieve a join between themmodelaclass modelamodelsmodel product modelsforeignkeymodelb group modelsforeignkeygroupmodelbclass modelbmodelsmodel title modelscharfieldmodelcclass modelcmodelsmodel product modelsforeignkeymodelb group modelsforeignkeymodeldmodeldclass modeldmodelsmodel name modelscharfieldnow i want all my modela objects joined with modelb modelc and modeldin sql this is pretty easy thing to do just make joins between tableswith django orm i am stuck because i only can do forward relationi am doing thismodelaobjectsallselect relatedproductbut i cannot join modelc i already have read this article but i do not want to loop over my big list to do a simple thing and i want to hit database only oncei am using the last version of django and i hope there is already a solution to this that i am not aware ofthank you,['sql'] +214370,how to read from input until newline is found using scanf i was asked to do a work in c when i am supposed to read from input until there is a space and then until the user presses enterif i do thisscanf20s 20s a bit will follow the 1st rule but not the 2ndif i writei am smartwhat i get is equivalent toa ib ambut it should bea ib am smarti already triedscanf20s 20nn a bandscanf20s 20 a bin the 1st one it waits for the user to press ctrld to send eof and that is not what i wantin the 2nd one it would not compile according to the compilerwarning no closing aa for aa formatany good way to solve this,['c'] +214374,array attribute for ruby model is it possible to create an attribute for a class that is an array i tried reading this but i did not get much out of it i want to do something like thisclass createarches activerecordmigration def change create table arches do t tstring name tarray thearray ttimestamps end endendsuch that when i call thearray on an instance of arch i get an array that i can add new elements toruby192p290 006 arc archnewruby192p290 007 arcthearray,['ruby'] +214380,how can i tint a uiimage with gradient i searched everywhere but did not find the solution i have image 1 how can i programatically tint them with gradient to get images 2 and 3 here are those imagestints that i applied to them via photoshop are simple 2color linear gradientsand my question is how can i achieve this effect programaticallysolution jrtc27 gave me almost working example i fixed it for arc and made it reusable using uiimages category here is it uiimage tintedwithlineargradientcolorsnsarray colorsarr cgfloat scale selfscale uigraphicsbeginimagecontextcgsizemakeselfsizewidth scale selfsizeheight scale cgcontextref context uigraphicsgetcurrentcontext cgcontexttranslatectmcontext 0 selfsizeheight cgcontextscalectmcontext 10 10 cgcontextsetblendmodecontext kcgblendmodenormal cgrect rect cgrectmake0 0 selfsizewidth scale selfsizeheight scale cgcontextdrawimagecontext rect selfcgimage create gradient uicolor colorone colorsarr objectatindex1 top color uicolor colortwo colorsarr objectatindex0 bottom color nsarray colors nsarray arraywithobjectsidcoloronecgcolor idcolortwocgcolor nil cgcolorspaceref space cgcolorspacecreatedevicergb cggradientref gradient cggradientcreatewithcolorsspace bridge cfarrayrefcolors null apply gradient cgcontextcliptomaskcontext rect selfcgimage cgcontextdrawlineargradientcontext gradient cgpointmake00 cgpointmake0selfsizeheight scale 0 uiimage gradientimage uigraphicsgetimagefromcurrentimagecontext uigraphicsendimagecontext return gradientimage,['iphone'] +214422,why is pydev giving a syntax error for builtin keywords why is pydev giving me syntax errors for builtin python functions like strundefined variable strundefined variable falseundefined variable float,['python'] +214427,when and how to use constants in php i am currently programming a website in php4 i plan to save values which do not change during runtime in constants those are for example the version number of logindata for the databasequestion 1 are there any security relevant problems that can arise from saving data in constantsat the moment i do the following to define and call the constantdefineversion 10echo current version version result current version 10there is one thing that annoys me in case a constant is not defined the wrong variable name is returned instead of eg nulldefineversion 10echo current version versionx result current version versionxone solution i found to get an error message and the return value null when i accidently entered a wrong constant name is using the function constantdefineversion 10echo current version constantversionx result current version question 2 can i prevent in a different way that php returns the name of the nonexisting variablequestion 3 should the value of a constant in php always be returned using the function constant,['php'] +214458,crashsigabrt when i try to present a uipopovercontroller hi i am at my wits end with what i am doing wrong here i am using ios5 and nothing crashes if i do not call presentpopoverfrombarbuttonitem has anyone experienced anything similar i checked the apple developer forums google stack overflow and could not find anythingrunning bt on gdb did not reveal any hints eitheruiviewcontroller viewtwoviewtwo viewtwo alloc initwithnibnameviewtwo bundleniluipopovercontroller popoverpopover uipopovercontroller alloc initwithcontentviewcontrollerviewtwo popover presentpopoverfromrectthebutton bounds inviewthebutton permittedarrowdirectionsuipopoverarrowdirectionleft animatedno,['ios'] +214460,memorystream cannot access a closed stream with the sharppdf library i generate a pdf memory stream and i want to send it directly via email but the line msseek gives an objectthisposedexception cannot access a closed streamthe pdfcreatepdf method takes either an output filename string or an outstream but i guess it also closes the stream i am not used to work much with streams so if you could please advise how it should be done the sharppdf source code of the createpdf method can be found here public sub sendpdf dim pdf as new sharppdfpdfdocumenttitle author generate pdf content dim ms as new iomemorystream pdfcreatepdfms dim email as new emailservice emailsendmsend subpublic class emailservice public sub sendbyval ms as stream msseek0 ioseekoriginbegin dim atc as new attachmentms reportpdf mailattachmentsaddatc set other email parameters clientsendasyncmail mailsubject end sub end class,['.net'] +214467,autoscaling inputtypetext to width of value is there a way to scale the width of an input typetext to the width of the actual valueinput thisplay block margin 20px width autoinput typetext valuei have had enough of these damn snakes on this damn plane input typetext valueme too,"['jquery', 'html', 'css']" +214469,iphone cannot run apps from xcode on ios 501 device since ios update from 50 i have just updated my iphone to ios 501 and xcode does not recognize it anymore as a valid device to run applicationsi have gone to the organizer reset the device as a development device updated my components and library but still nothing the device does not appear in the available destinations into the main window popuphow can i do to test again on the device,"['iphone', 'ios']" +214470,are rems replacing ems in css i was reading about rem units in css3 and was a little confused if you use rem do you still use em or does that replace itfor exampleselector marginbottom24px marginbottom24rem fontsize16px fontsize16remorselector marginbottom24px marginbottom24em marginbottom24remjust trying to figure out if rem takes the place of em or if it is just another unit,['css'] +214488,using swingeventmonitor to monitor other applications how do i use swingeventmonitor to monitor mouse events in applications running in other jvms the demo code i have can monitor mouse clicks in applications running within its own jvm but applications started seperately or via jnlp are ignored how do i make sure java loads my swingeventmonitor app with every application regardless of how its started desktop or jnlp,['java'] +214491,jquery validation custom validation adding no space validation i have a form where the user can update his name and last name i use jquery validation to validate the form how can i validate if the user put spacesheres what i havescriptdocumentreadyfunction submitclickfunction var valid myformvalid ifvalid return false ajax type post url save data myformserialize datatype json cache false success functionresult redirect to another page scriptheadbodyform idmyform methodpost actionfieldsetlegendupdate namelegendp label forfnamenamelabel ememinput idfname namefname size25 classrequired minlength2 pp label forlnamelast namelabel ememinput idlname namelname size25 classrequired minlength2 pp input idsubmit typesubmit valuesubmitpfieldsetformthanks,['jquery'] +214556,move uploaded file gives failed to open stream permission denied error after all configurations i did i keep getting this error when trying to configure the upload directory with apache 22 and php 53 on centosin phpiniupload tmp dir varwhtmlmysitetmp file uploadin httpdconfdirectory varwhtmlmysitetmp file upload options indexes allowoverride none order allowdeny allow from alldirectorydirectory varwhtmlmysiteimages options indexesdirectorycentos directory permissionsdrwxrwxrx 2 root root 4096 nov 11 1001 imagesdrwxrxrx 2 root root 4096 nov 12 0454 tmp file uploadno matter what i do i keep getting this error from php when i upload the file warning move uploaded fileimagesrobotjpg failed to open stream permission denied in varwhtmlmysiteprocessphp on line 78warning move uploaded file unable to move tmpphpskd2qm to imagesrobotjpg in varwhtmlmysiteprocessphp on line 78 as you can see it never did take the configuration from the phpini file regarding the upload filewhat am i doing wrong here,['php'] +214571,how do i change my code to avoid warning should trim empty in aptana studio i use class when i need css function for example when i want to use clear lefti make a class clear clear left and use it in html filebut there is always the warningshould trim empty luckily it is not error so i do not care greatly but it bother me sometimesis there any solution sticking my habit,"['css', 'html']" +214580,what does it mean bundle thisable shared gems 1 i found bundle thisable shared gems 1 in bundleconfig what does it mean,"['ruby-on-rails', 'ruby']" +214606,checking if server port is open from android i am trying to connect to a my remote server from my android device how do i check if a specific port on my server is open eg how to check if port 80 is open on my server 1currently i am using inetaddress to ping if the host is reachable but this does not tell me if the port 80 is opencurrent codeboolean isavailable falsetry isavailable inetaddressgetbyname1isreachable20 if isavailable true host is reachable dosomething catch exception e,['android'] +214655,new and init in python i am learning python and so far i can tell the things below about new and init new is for object creation init is for object initialization new is invoked before init as new returns a new instance and init invoked afterwards to initialize inner state new is good for immutable object as they cannot be changed once they are assigned so we can return new instance which has new statewe can use new and init for both mutable object as its inner state can be changedbut i have another questions now when i create a new instance such as a myclasshelloworld how these arguments are passed i mean how i should structure the class using init and new as they are different and both accepts arbitrary arguments besides default first argumentself keyword is in terms of name can be changed to something else but i am wondering cls is in terms of name is subject to change to something else as it is just a parameter namei made a little experiments as such below class myclasstuple def new tuple return 123and i did below a myclass a1 2 3albeit i said i want to return tuple this code works fine and returned me 123 i knew we were passing the first parameters as the type we wanted to receive once the new function is invoked we are talking about new function right i do not know other languages return type other than bound typeand i did anther things as well issubclassmyclasslistfalse issubclassmyclasstupletrue isinstanceamyclassfalse isinstanceatuplefalse isinstancealisttruei did not do more experiment because the further was not bright and i decided to stop there and decided to ask stackoverflowthe so posts i readpython object creationpythons use of new and init,['python'] +214658,jshintcom requires use strict what does this mean jshintcom is giving the errorline 36 var signin found missing use strict statement,['javascript'] +214673,cannot open excel file generated with excellibrary i am using excellibrary to programatically create excel files but i get a file format error when i try to open the generated files in microsoft office exceli have seen this has been reported but there is still no answer about iti use office 2010 and i am able to open any other xls 972003 file format but the ones generated with excellibrary i have also tried open office and still cannot open the generated file i have not tried to open them in office 972003just try the sample code to reproduce the errorhave anybody found how to use the library and not run into this problem,['c#'] +214700,general approach to developing an image classification algorithm for dilbert cartoons as a selfdevelopment exercise i want to develop a simple classification algorithm that given a particular cell of a dilbert cartoon is able to identify which characters are present in the cartoon dilbert phb ratbert etc i assume the best way to do this is to 1 apply some algorithm to the image which converts it into a set of features and 2 use a training set and one of many possible machine learning algorithms to correlate the presenceabsence of certain features with a particular character being present in the cellso my questions are a is this the correct approach b since there is a number of classification algorithms and ml algorithms to test what is a good methodology for finding the right one and c which algorithms would you start with given that were essentially conducting a classification exercise on a cartoon,['python'] +214713,why is it okay that this struct is mutable when are mutable structs acceptable eric lippert told me i should try to always make value types immutable so i figured i should try to always make value types immutable but i just found this internal mutable struct systemwebutilsimplebitvector32 in the systemweb assembly which makes me think that there must be a good reason for having a mutable struct i am guessing the reason that they did it this way is because it performed better under testing and they kept it internal to thiscourage its misuse however that is speculation i have cpd the source of this struct what is it that justifies the design decision to use a mutable struct in general what sort of benefits can be gained by the approach and when are these benefits significant enough to justify the potential detrimentsserializable structlayoutlayoutkindsequentialinternal struct simplebitvector32 private int data internal simplebitvector32int data thisdata data internal int integervalue get return thisdata set thisdata value internal bool thisint bit get return thisdata bit bit set int data thisdata if value thisdata data bit else thisdata data bit internal int thisint mask int offset get return thisdata mask offset set thisdata thisdata mask value offset internal void setint bit thisdata bit internal void clearint bit thisdata bit,"['c#', '.net']" +214714,java using enum with switch statement i have looked at various qas on so similar to this question but have not found a solutionwhat i have is an enum which represents different ways to view a tv guidein the ndroid application clastatic enum guideview guide view seven day guide view now showing guide view all timeslotswhen the user changes the view an event handler receives an int from 02 and i would like to do something like thisin an android activity onclickdialoginterface dialog int which event handler which is an int from 02switch which case ndroidguideviewguide view seven day breaki am used to c enums and selectcase statements which would allow something like the above and i know java does things differently but i just cannot make sense of what i need to doam i going to have to resort to if statements there will likely only ever be 3 choices so i could do it but i wondered how it could be done with switchcase in javaedit sorry i did not completely expand on the issue as i was looking at it as being a generic java issue i have added to the question to explain a bit furtherthere is not anything that is android specific which is why i did not tag it as android but the enum is defined in the application class and the code where i want the switch is in an activity the enum is static as i need to access it from multiple activities,['java'] +214749,simple way to query connected usb devices info in python how can we query connected usb devices info in pythoni want to get uid device name ex sonyericsson w660 path to device ex devttyacm0and also what would be the best parameter out of above info to be used as identifying the device whenever it is connected again uidi am working on ubuntu 1104atm i have this code using pyusbbusses usbbussesfor bus in busses devices busdevices for dev in devices print reprdev print device devfilename print idvendor d 0x04x devidvendor devidvendor print idproduct d 0x04x devidproduct devidproduct print manufacturer devimanufacturer print serial deviserialnumber print product deviproductthe problem is i do not get desired output will paste one exampleusblegacydevice object at 0x1653990device idvendor 4046 0x0fce idproduct 53411 0xd0a3manufacturer 1serial 3product 2first i do not get filename it is most important to me i am assuming it is the devttyacm0 etc part second i guess there was some uid of every usb device or i should use both vendor or product idedit apparently i have some setup issues i think i am using wrong usb library using libusb01 atm that is why i get device devfilename string empty if someone can please just tell that on what operating system he is using what usb library and what version of pyusb i think it will solve my problems,['python'] +214760,ios5 images thisappear when scrolling with webkitoverflowscrolling touch i had previously been using iscroll plugin but wanted to drop it for the native behaviour the initial implementation was usingwebkitoverflowscrolling autohowever i updated this to webkitoverflowscrolling touch to enable the motioninertia on the touch scrollthe issue with this is the list items contained within the navigation thisappear completely when scrolling and only return once the momentum has come to a restan example of this can be seen here,['ios'] +214782,java 7 jdk 7 garbage collection and documentation on g1 java 7 has been out for a while now but i cannot find any good resources on the configuration of the garbage collectors specifically the new g1 collectormy questionsis g1 the default collector in java 7 and if not how do i activate g1what optional settings does g1 have in java7were there any changes made to other collectors like cms or the parallel collector in java 7where can i find good documentation on garbage collection in java 7,['java'] +214815,access model attribute in scriptlet i am using spring mvc and in my controller i am setting a standard model attribute usingmodeladdattributeparam valuenow i wish to access this in a scriptlet within a jsp for example object value getparam more java codehow can i do thisnote i understand it is a bad idea to use scriptlets but please bear with it for now,['html'] +214821,cannot create django project using windows command prompt if i run djangoadminpy startproject mysitedjangoadminpy which is located in cpython27scriptsdjangoadminpy will open in a file editor now it opens in python ide but in the past i had pype so it would open in pype so the file openscpython27pythonexefrom djangocore import managementif name main managementexecute from command linei see no output in the command prompt at all so lets say i typedcabcdjangoadminpy startproject mysitewhen i hit enter i see cabcand the project will not be created using the command promptthis issue is not new for me i am creating my python projects using pydev i would love to fix this issue with the command prompt though slugonamissionwhen i runpyhon djangoadminpy startproject mysitethe output of the command prompt ispython cannot open djangoadminpy file errno 2 no such file or directory,['python'] +214835,cannot load ia 32bit dll on a amd 64bit platform i am trying to use svmlight from java using the jni wrapper on this page static systemloadlibrarylibjni svmlight601libsvmlight i get the following error libjni svmlight601libsvmlightdll cannot load ia 32bit dll on a amd 64bit platformcan i solve this by recompiling the dll for 64 bit how would i go about doing this is there some other workaround i can use svmlight makes the c source code available,['java'] +214840,scalaandroid is anybody successfully building and debugging in eclipse so far the only way i have been able to debug within eclipse is to use treeshaker with scala ides buggy 28 branch if i try to build with scala ide without treeshaker i get classnotfound errors per this long thread on scalaonandroidideally i would build with sbtandroid and debug within eclipse but i have been unable to do so successfully the closest to debugging an sbtandroid project i was able to achieve was to build the sbtandroid project with the androidpackagedebug command start the executable with the androidstartemulator command and then connect ddms to the applications threadhowever i had breakpoints set that only would have executed after i connected the debugger to the thread and none of them caused the thread to stop when reached has anyone been able to debug scala android code in eclipse using any other tools besides treeshaker with scala ide based on scala 28update i am successfully debugging not building in eclipse after building from the command line with sbt sbteclipse and androidpluginwhat i did was to use eclipses new android project menu connect to existing source and point it to the srcmain directory then eclipse recognized the android settings and ddms recognized the task as belonging to the eclipse android projecti also had to reconfigure the eclipse projects java build path source folders by removing the src folder from the build path and adding the scala folder then i had to restart eclipse to add breakpoints to the scala fileheres some interesting thiscussion about the difficulties building and debugging android applications using eclipse,['android'] +214843,gae not recognizing cookie i am playing around with gae and android trying to get an app made for a webservice i am going through the steps to get the auth token from accountmanager on android getting the cookie as required then attaching that cookie to a get request that the gae python application handles for some reason the gae application does not seem to recognize the cookie or something sorry for the huge post i figured i would get as much code in here as possible to help explaini have this basic class in gae to test if the user is recognizedclass testuserwebapprequesthandler def getself if usersget current user selfresponseoutwriteusersget current usernickname else selfresponseoutwriteno userapplication webappwsgiapplication mainpage testuser testuser debugtruedef main run wsgi appapplicationif name main mainfrom a browser this works great i see the user when executing on android i get no user heres a bunch of android code oncreate override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain cookielength textviewfindviewbyidridcookielength cookie accountmanager manager accountmanagergetgetapplicationcontext account accounts managergetaccountsbytypecomgoogle new getauthtokentaskexecuteaccounts get the auth token invalidate it and get it again to avoid expired tokensprivate class getauthtokentask extends asynctaskaccount object string override protected string doinbackgroundaccount accounts accountmanager manager accountmanagergetgetapplicationcontext account account accounts0 string token thisbuildtokenmanager account logdtag first token token managerinvalidateauthtokenaccounttype token return thisbuildtokenmanager account private string buildtokenaccountmanager manager account account try accountmanagerfuturebundle future managergetauthtoken account ah false null null bundle bundle futuregetresult return bundlegetstringaccountmanagerkey authtoken catch operationcanceledexception e logwtag egetmessage catch authenticatorexception e logwtag egetmessage catch ioexception e logwtag egetmessage return null protected void onpostexecutestring authtoken logdtag second token authtoken getcookieauthtoken get the users cookie stored in global cookie stringprivate void getcookiefinal string authtoken new threadnew runnable public void run string href ahlogincontinuehttplocalhostauthauthtoken logdtag href href defaulthttpclient httpclient new defaulthttpclient final httpparams params new basichttpparams httpclientparamssetredirectingparams false httpclientsetparamsparams httpget httpget new httpgethref try httpresponse response httpclientexecutehttpget httpentity entity responsegetentity if entity null entityconsumecontent listcookie cookies httpclientgetcookiestoregetcookies logdtag cookies if cookiesisempty logdtag none else for int i 0 i cookiessize i logdtag cookiesgetitostring cookie c cookiesgeti logdtag cookiegetname cgetname if cgetnamecontentequalssacsid logdtag found sacsid cookie cookie cgetvalue logdtag cookie now set to cookie catch clientprotocolexception e todo autogenerated catch block eprintstacktrace catch ioexception e todo autogenerated catch block eprintstacktrace startwe now have a cookie stored user pressed test user button in interface this is executedpublic void testuserview view logdtag testuserstring href defaulthttpclient httpclient new defaulthttpclient final httpparams params new basichttpparams httpclientparamssetredirectingparams false httpclientsetparamsparams httpget httpget new httpgethref httpgetsetheadercookie cookie try httpresponse response httpclientexecutehttpget statusline status responsegetstatusline if statusgetstatuscode 200 throw new ioexceptioninvalid response from server statustostring httpentity entity responsegetentity if entity null entityconsumecontent inputstream inputstream entitygetcontent bytearrayoutputstream content new bytearrayoutputstream read response into a buffered stream int readbytes 0 byte sbuffer new byte512 while readbytes inputstreamreadsbuffer 1 contentwritesbuffer 0 readbytes string dataasstring new stringcontenttobytearray logdtag response dataasstring catch clientprotocolexception e todo autogenerated catch block eprintstacktrace catch ioexception e todo autogenerated catch block eprintstacktrace heres a sniff of the connection from wiresharkget testuser http11cookie ajkiycecp6zzhfuonu5kvleii wcwzlborqpokq0t 4lwoo0znxn6t7okpmpa7ctavy58go5bmwxksz4yze7eouwtzxegaukwi2yrisqjnnuqb36wuzlybfdy6c7eccvxuu7bnylyjtdob7zjducesxfbmgzrfsh3fhmvo56c540armwzkoftrb0ejkdlb6phugrxcbi2rbfdvkwunkjqb0xir8w zceo9aumjbqqxkdqduiagn ehkfw9c99kzw8cjnhx1ekxvl5tc2qiyjxwnztjayscitcq6iittnsdfzwrkbk6ys9zobynqooaaoxhm5urx7cgg0jo2nwqtnykshfa9ur7ixbkp137hw7ar5pimjyb8jd8ozgwb4uznhv5v5yzs9akcqxcaqoz0wgmt5fjtzqcgzjfmpgteubgpgtqjsvhwpb6mbaxwsooyuyzpxneffdh51wev53wqs 5fdtwgq7rq7ztefobpznajnfo3ecy54dqmmhflml izge pntobi02wlerfm0lclpxtkm4ssdxftfmpwave2w1wpmpbwb4pljc6np98wlpwgizrw7g2nwq y0iwiogiq9aghost someawesomeappappspotcomconnection keepalivehttp11 200 okcontenttype texthtml charsetutf8cachecontrol nocacheexpires fri 01 jan 1990 0 gmtvary acceptencodingdate sun 13 nov 2011 174234 gmtserver google frontendtransferencoding chunked7no user0the response here is no user from gae any thoughts on how to get gae to accept and act on the cookie as the user 27 seconds later i think i found an issue heres a sniff from the browser i do not have that acsid partcookie acsidajkiycfeuhzup56athanks for your helpstatefuledit i got it fixed i need to wait a while to answer my own question though not enough reputation basically since i am getting the cookie with ssl the cookie needs to be prefixed with sacsid rather than acsid and the testuser url needs to be https as well since that is the cookie were using,['android'] +214865,swigpython array inside structure i have got a structure defined inside headerh that looks like typedef struct int icntl40 double cntl15 int irn jcnwhen i init an object with this structure i have access to integersdoubles but not arrays sticntlswig object of type int at 0x103ce37e0 sticntl0traceback most recent call last file test mumpspy line 19 in module print sicntl0typeerror swigpyobject object is not subscriptablehow to have access to the values in readwrite,['python'] +214878,jsoup select with specific id i am making a small android application for a class where i find cancerrelated events from the american cancer societys website i have been using jsoup to get basic information about the events and to get specific information from the website i have tried to use the select method however the current method that i am using grabs way more html nodes than i would like and i could not figure out why the table that i am trying to grab looks like thisedit i realized that the where id pnlresults does not end at that table it ends after about 3 more tables all with information that i would like to grab here is the table again div idpnlresults h2span idlbleventnameamerican cancer society 44th annual walter hagen golf tournamentspanh2 general information box div classtextbox boxed wide h3 classhead stylewidth97 general information h3 div classcontent p labelevent timeslabelspan idlblstartdatemonday july 30 2012spanspan idlblenddatespanbr labelnbsplabelspan idlblstarttime10 amspan span idlblendtime900 pmspan p p labeltime zonelabelspan idlbltimezoneeasternspan p p labeldescriptionlabelspan idlbldesc classfielddata longthe american cancer society walter hagen golf tournament highlights the societyas role in supporting research and patient care here in rochester funds raised through this event help us make a difference in patentsa lives every day though programs including road to recovery and patient navigation as well as support grants to our research institutions 144 golfers will play a round of golf and then enjoy cocktails dinner and silent auction following the tournament span p p labelagendalabelspan idlblagenda classfielddata long10am checkin 1100am lunch 1215pm shot gun start 600 cocktails and silent auction 700pm dinner and programspan p div div div idpnlstandardthisplay event location box div classtextbox boxed wide line h3 classhead stylewidth97 event location h3 div classcontent stylethisplayinlineblock width97 div div idmapoutsidecontainer classresourcemap div idmap canvas classresourcemap div div script typetextjavascript var mapdatapoints lat431075545lng775164518 titlegolf eventcontentbamerican cancer society 44th annual walter hagen golf tournamentbbrbr4045 east avenuebr brrochester new york 14618br br phone br fax buildmapmapdatapoints 5 script div h4span idlbllocationnameirondequoit country clubspanh4 p labeladdresslabelspan idlbladdress classfielddata stylewidth150px4045 east avenuebr rochester new york 14618span p p label nowrapnowraphandicap accessiblelabelspan idlblhandicapaccesibleyesspan p div div primary contact box div class line div ideventprimarycontact divcontact classtextbox boxed wide h3 classhead stylewidth97 primary contact h3 div classcontent p labelcontactlabelspan ideventprimarycontact lblcontactkaterina kormas a hrefmailtosubjectamerican cancer society 44th annual walter hagen golf tournamentcontact acs for detailsaspan p p labelcontact typelabelspan ideventprimarycontact lblcontacttypeacs staffspan p p labelphonelabelspan ideventprimarycontact lblcontactphone585 2881950span p p labeladditional informationlabelspan ideventprimarycontact lblcontactaddlinfo classfielddata longdirect line is 5852244919 or cell 5856458912span p div div div registration information box div classtextbox boxed wide line h3 classhead stylewidth97 registration information h3 div classcontent p label nowrapnowrapregistration required labelspan idlblregrequiredyesspan p div div event cost box div class line div ideventcost divcost classtextbox boxed wide h3 classhead stylewidth97 event cost h3 div classcontent p labelcostregistration fee labelspan ideventcost lblcostregfee classfielddata long350 per golferspan p p labelpayment type labelspan ideventcost lblpaymenttypes classfielddatacash check american express mastercard visa thiscoverspan p p labelcheck payable to labelspan ideventcost lblcheckpayable classfielddataamerican cancer societyspan p p labelmemo line labelspan ideventcost lblcheckmemo classfielddataamerican cancer society 44th annual walter hagen golf tournaspan p p labelmail check tolabelspan ideventcost lblcheckmailto classfielddataamerican cancer societybr 1120 south goodman stbr rochester new york 14620span p div div div tax deduction information box div classline div classtextbox boxed wide h3 classhead stylewidth97 tax deduction information h3 div classcontent p 210 per golfer is tax deductible p div div divdiv end standard thisplay end daffodil thisplay edit given these new tables i would like to extract the general information and event location how would i go about doing that maybe using the subset of select i just got to select again where the headers are what i wantthe code where i am using the select is shown below as i said before i tried to useselectdividpnlresultsbut the returned data is much more than just the div where the id is pnlresultspublic arraylistevent results arraylistevent results new arraylistevent document doc jsoupparsepage elements links docselectahrefeventdetails forelement e links string title etext string link eattrhref try document eventinfo jsoupconnectlinkget elements info eventinfoselectdividpnlresults catchmalformedurlexception exception exceptionprintstacktrace catchioexception exception exceptionprintstacktrace return resultsany help would be greatly appreciated,"['java', 'android']" +214886,how better check requestquerystring string parameter for null i need explanations i using cnet to web applications i always write string val requestquerystringfooand then ifstringisnulloremptyval whats the differencestring val requestquerystringfooi was advised to dostring val requestquerystringfoo as stringifstringisnulloremptyval whats the difference,"['c#', 'asp.net', '.net']" +214895,how can boostserialization be used with stdshared ptr from c11 i know that there is a boost module for serialization of boostshared ptr but i cannot find anything for stdshared ptralso i do not know how to implement it easily i am afraid that the following codenamespace boostnamespace serializationtemplateclass archive class tinline void serializearchive ar stdshared ptrt t const unsigned int version ifarchiveis loadingvalue trarrtr else artgetnamespacesdoes not work indeed if some object was referred multiple times it would be loaded with first run of arr and after that just a pointer will be copied however we would create multiple shared ptr objects pointing to it and therefore would destruct it more than one timeany ideas on thatsome technical details about the system i am usingos ubuntu 10 x64compiler g ubuntulinaro 4619ubuntu3 461boost version 1461 installed with sudo aptget install libboostdev,['c++'] +214898,importerror no module named bz2 for python 272 i am using python 272 on ubuntu 10 i got this error when importing the bz2 moduleimporterror no module named bz2i thought the bz2 module is supposed to come with python 27 how can i fix this problemedit i think i previously installed python 272 by compiling from source probably at that point i did not have libbz2dev and so the bz2 module is not installed now i am hoping to install python27 throughsudo aptget install python27but it will say it is already installed is there a way to uninstall the previous python27 installation and reinstall,['python'] +214912,what is the size of an enum type data in c this is a c interview test question not homework include iostreamusing namespace stdenum months t january february march april may june july august september october november december y2k int main cout sizeof months t is sizeofmonths t endl cout sizeof y2k is sizeofy2k endl enum months t1 january february march april may june july august september october november december y2k1 cout sizeof months t1 is sizeofmonths t1 endl cout sizeof y2k1 is sizeofy2k1 endl why the all size is 4 bytes not 12 x 4 48 bytes i know union elements occupy the same memory location but this is enum,['c++'] +214920,android handling many edittext fields in a listview just a basic question if i have several dozen edittext fields that are part of a listadapter how can the individual edittext fields know to which row they belongcurrently i am using textwatcher to listen for text input i have tried extending textwatcher so that i can pass in the position of the edittext to textwatchers constructorhowever when the soft keyboard pops up the positions that correspond to the various edittext fields shufflehow can i track the edittext fields to their proper positioni am using a gridview to lay things out the layout of each item is an imageview with a textview and edittext field below itthe text for each edittext is held in a global string array called strings it is initially empty and is updated by my textwatcher classpublic void initlist arrayadapterstring listadapter new arrayadapterstringthis rlayoutshape strings override public view getviewfinal int position view convertview viewgroup parent if convertview null convertview layoutinflaterfromgetcontextinflaterlayoutshape null final string thedata getitemposition final edittext edittext edittext convertviewfindviewbyidridshape edittext edittextsettextthedata edittextaddtextchangedlistener new mytextwatcherposition edittext imageview image imageview convertviewfindviewbyidridshape image imagesetbackgroundresourceimagesposition textview text textview convertviewfindviewbyidridshape text if gametype shapes abstract textsettextseq else textsetvisibilityviewgone return convertview override public string getitemint position return stringsposition gridsetadapterlistadapter private class mytextwatcher implements textwatcher private int index private edittext edittext public mytextwatcherint index edittext edittext thisindex index thisedittext edittext public void beforetextchangedcharsequence s int start int count int after public void ontextchangedcharsequence s int start int before int count public void aftertextchangededitable s stringsindex stostring public void setindexint newindex index newindex when i click into the first edittext see picture the edittext shifts to the one under the smiley face,['android'] +214933,rails 31 unicorn and apache static files i have rails 31 unicorn and apache setup my apache settings are below and productionrb looks like this i like using h264 streaming but since rails is serving these video files the apache mod would not workdocumentroot blablacurrentpublicrewriteengine onoptions followsymlinksproxy balancerunicornservers balancermember proxy redirect all nonstatic requests to railsrewritecond document rootrequest filename frewriterule balancerunicornserversrequest uri pqsalproxypass balancerunicornserversproxypassreverse balancerunicornserversproxypreservehost onproxy order denyallow allow from allproxyxsendfile onxsendfileallowabove oni have to enable serve static assets or i cannot download any static stuff i have precompiled assets too but it would not make any difference as no file is available from public directory unless rails rack i guess is doing the servingshould i use configaction controllerasset host or is there something wrong with my apache config,['ruby-on-rails'] +214939,how to determine if three ints are all equal hi say i have three ints value1 value2 and value3how do i best determine if they are all the samei triedreturn value1 value2 value3but this saidoperator cannot be applied to operands of type bool and intso i guess it compares the first two which returns a boolean which it tries to compare to the thirdi could goreturn value1 value2 value2 value3but this seems to be getting untidyanybody have a good suggestion,['c#'] +214942,generic methods explanation i learned java generics some time ago but now i am learning collections and found some code that i do not understand here is the codestatic e liste ncopiesint n e valueit is from class javautilcollectionsmy question is why there ise listeand not onlylisteobviously i am missing something can someone clarify this for me,['java'] +214945,what return value should you use for a failed function call in c possible duplicateerror handling in c code let us say you have a functionint mightwork if it works return x if it fails return ywhat should x and y bebecause i have another functionif mightwork do stuff 1else do stuff 2i know for this particular example using a return value of 1 will take the second code block to do stuff 1 and using a return value of 0 will take the second code block to do stuff 2my question is what is preferred style in c to do this does a return value of 0 for a function indicate success and any other value indicates failure or vice versa or values under 0i would like to make sure i am writing my c code with the current style thanks,['c'] +214961,looking for best barcode scanner library besides zxing i am looking for some best barcode libraries on all platforms i know zxing but wondering more libraries besides it any help is appreciated,"['android', 'iphone']" +215007,are assignment operators required to return according to the c standard can i be sure that assignment operators for builtin variables return the original valueor is this implementation dependent yet simply have most popular compilers implemented this,['c++'] +215015,howto debug winsock api calls i have a very large c server application on windows win7 it compiles fine and runs mostly well but sometimes ip connections failmy suspicion is that some calls to the winsock api get bad parameters and not all result codes are checked properlyis there a way to trace all calls to the winsock api including parameters so i can can check them for the failing connection something similar to strace on linux maybe,['c++'] +215040,how to add one month to an nsdate how to add month to nsdate objectnsdate somedate nsdate date 30days,"['ios', 'iphone', 'objective-c']" +215042,get bitmap from layout i am trying to inflate a layout and use that to set a bitmap on an image view then i am adding that imageview to a linear layout and thisplaying the linear layout heres what i have triedpublic class testactivity extends activity private static bitmap bitmap called when the activity is first created override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate linearlayout l new linearlayoutthis bitmap bitmapcreatebitmapgetwindowmanagergetdefaultthisplaygetwidth getwindowmanagergetdefaultthisplaygetheight bitmapconfigargb 8 canvas canvas new canvasbitmap layoutinflater inflater layoutinflaterfromthis view v1 inflaterinflaterlayoutmain null v1layout0 0 getwindowmanagergetdefaultthisplaygetwidth getwindowmanagergetdefaultthisplaygetheight v1drawcanvas imageview i1 new imageviewthis i1setimagebitmapbitmap i1setadjustviewboundstrue i1setlayoutparamsnew framelayoutlayoutparamsgetwindowmanagergetdefaultthisplaygetwidth getwindowmanagergetdefaultthisplaygetheight laddviewi1 setcontentviewl unfortunately the bitmap is not being created properly is there anything i am doing wrong,['android'] +215044,string true and false to boolean i have a rails application and i am using jquery to query my search view in the background there are fields q search term start date end date and internal the internal field is a checkbox and i am using the ischecked method to build the url that is queriedgetscriptdocumenturl q search qval start date search start dateval end date search end dateval internal search internalischeckednow my problem is in paramsinternal because there is a string either containing true or false and i need to cast it to boolean of course i can do it like thisdef to booleanstr return true if strtrue return false if strfalse return nilendbut i think there must be a more rubyish way to deal with this problem is not there,"['jquery', 'ruby-on-rails', 'ruby']" +215046,error vsp1712 invalid vsp file i have generated a vsp file that is around 4gb and i get this error when i try to open it does anyone know why this might be the same thing works when i profile a smaller amount of code,['c++'] +215052,how to use parameters with httppost i am using a restfull webservice with this methodepostconsumesapplicationjsonpathcreatepublic void createstring str1 string str2systemoutprintlnvalue 1 str1systemoutprintlnvalue 2 str2in my android app i want to call this method how do i give the correct values to the parameters using orgapachehttpclientmethodshttpposti have noticed that i can use the annotation headerparam and simply add headers to the httppost object is this the correct way doing it likehttppostsetheaderaccept applicationjsonhttppostsetheaderstr1 a valuehttppostsetheaderstr2 another valueusing the setentity methode on httppost would not work it only sets the parameter str1 with the json string when using it likejsonobject json new jsonobjectjsonputstr1 a valuejsonputstr2 another valuehttpentity e new stringentityjsontostringhttppostsetentityeserver output value 1 str1a valuestr2another value,"['java', 'android']" +215061,enlarge image and move it with the pointer on mouse over sorry if this might seem trivial for me to ask buti have some images and i need them to enlarge when i hover my mouse over them but i want for the enlarged image to stick next to the pointer as i move it across the image i do not know what to call it i am pretty sure it is only done with javascript just css would not work heresomething like this but you know it has to move with the pointer in motionwhats the most effective way to do this,"['javascript', 'html', 'css']" +215082,get memory address of member function how do i get the absolute address of a member function in c i need this for thunkingmember function pointers do not work because i cannot convert them to absolute addresses void i need to know the address of the actual function in memory not simply the address relative to the type,['c++'] +215088,use windows built in mp3 decoder to play audio how do i from c or c use the mp3 decoder supposedly built in with windows since windows media player 61i want to play an mp3 file without having to depend on any other third party library such as for instance lamedlli updated the question to better fit the answers i got since i liked them a lot related question,"['c++', 'c']" +215106,how do i know whether my iphoneipad is connected to 2g or 3g i was trying to check wether the device is connected via 2g gprs edge or 3g umts hsdpai only found the reachability example class from here apple dev examplethis example only check wether its wifi or wwan i wanna use it to decide wether i download the small data or the huge files as it is big different between grps and umtsis it possible to thistinguish 2g and 3g,"['iphone', 'ios']" +215120,viewpager intercepts all xaxis ontouch events how to thisable scopethere is a viewpager of two fragments one of those fragments has a layout witch listens to ontouch changes at xaxisproblemlayout does not get almost all actionmove events when touching and sliding along xaxisit seems that viewpager has a onintercepttouchevent which returns truequestionis it real to override viewpagers behavior to make it and my layout work together so the perfect situation is layout intercepts all ontouch events on it and viewpager manages the rest of ontouch events thanks,['android'] +215173,handle dblclick in fullcalendar jquery plugin i know that this question has been asked before but several new versions have been released since then is it possible to handle a dblclick event for creating a new appointment in the calendar without having to modify the fullcalendarjs file it would be great to handle this extension in a separate file together with my other tweaksthanks in advanceadam,['jquery'] +215179,ioc with value type and object type dependencies i am looking for suggestions as to the best way to design objects for iocsuppose i have an object service that has a dependency to a datacontext which is registered with iocbut it also requires a name property i could design the object like thisclass service public serviceidatacontext datacontext string name this datacontext datacontext this name name public string name get return name the problem is it becomes very complicated to use with ioc containers as a string object such as name is not easy to register and the usage becomes complicated with the ioc containerso resolution becomes confusingvar service iocresolveservice another approach is to design it as followsclass service public serviceidatacontext datacontext this datacontext datacontext public string name get set the resolution is now easiervar service iocresolveserviceservicename some namethe only downsite is specifying the name is no longer requiredi would like to hear from di or ioc experts how they would go about designing this and still stay fairly agnostic to the concrete ioc container technologyi know that a lot depends on how you want to use this option 2 would be perfect if name really was optional but in the case where name is required you could add the validation step at another point in code but rather go for the design to make ioc simplerthoughts,['c#'] +215206,objectivec arc nsnumber segmentation fault i have an objectivec program and i am using arc automatic reference counting it throws a segmentation fault in line 23 see program belowquestion1 why does the segmentation fault occur given below is the programimportfoundationfoundationhinterface car nsobjectproperty weak nsnumber doorsendimplementation car synthesize doorsendint main systemclear autoreleasepool car car1 car alloc init printf1n nsnumber d1 nsnumber alloc initwithinteger 4 printf2n car1doors d1 segmentation fault why printf3n printf endn return0output12segmentation fault 11,['objective-c'] +215250,boost asio multithreaded tcp synchronous server i am trying to create a tcp synchronous server my main thread would create listen to a port and an incoming connection would be handled by a threadmy codevoid workerthreadboostshared ptr boostasioio service io service io servicerunvoid applicationserver boostshared ptr boostasioio service io new boostasioio service boostshared ptr boostasioio servicework work new boostasioio serviceworkio open the acceptor with the option to reuse the address ie so reuseaddr boostasioiptcpacceptor acceptorio boostasioiptcpendpoint endpointboostasioiptcpv4 2198 acceptoropenendpointprotocol acceptorset optionboostasioiptcpacceptorreuse addresstrue acceptorbindendpoint acceptorlisten pool of threads boostthread group worker threads forint x 0 x 5 x worker threadscreate threadboostbindworkerthread io whiletrue boostshared ptr boostasioiptcpsocket socket new boostasioiptcpsocket io acceptoracceptsocket processconnectionsocket socketclose iostop worker threadsjoin allvoid applicationprocessconnectionboostasioiptcpsocket socket boostasiostreambuf request buffer stdistream request streamrequest buffer repsonse buffer boostasiostreambuf response buffer stdostream response streamresponse buffer boostasioread untilsocket request buffer message process request buffer into response buffer boostasiowritesocket response bufferthe following is working with more than one client connecting to the server however it also work if i remove the pool of thread can anyone explain me why that is do i even need a pool of threads,['c++'] +215254,transitioning between multiple storyboards in xcode 4 i have not yet seen this question answeredwhat is the best way to implement multiple storyboards in xcode 4 an example of when you would want to do this might be in a team environment where multiple people are working on subsections of the same uiany ideas i might guess it has to be done manually in code but it would be neat if there were a way to do it graphically within the storyboard editing view,"['iphone', 'ios']" +215257,iphone ios how to detect when in roaming not for jailbreaked phones i am coding an app with heavy network usage i have been told to warn users for costs but only when in roaming mode i know theres some way to know when the phone is roaming comparing two undocumented files on jailbreaked iphones but i need to find out how to for non jailbreaked phonesbtw found nothing at scnetworkreachability apity,"['iphone', 'ios']" +215261,linq to objects join two collections to set values in the first collection i have the following entity framework queryvar results from r in dbresults select ri am using automapper to map to another typevar mapped mappermapienumerabledatabaseresult ienumerableobjectsresultresultsin my objectsresult type i have a property called reason that is not coming from the database it is coming from another source that i need to basically populate back into my mapped typevar reasons new listreason new reason id 1 reason asdf i need to join the reasons with my mapped collection and set the reason property in my mapped collection using the value from my reasons collection is this possible need something like this mapped from m in mapped join r in reasons on mid equals rid update mreason rreason select mobviously the above code does not compile but is there code i can write that does what i want,"['c#', '.net']" +215292,can i define php int size to 4 bytes on 64bit system running php i am using php 53on my 32bit system the size of an intprint php int max php int max nprint php int size php int size bytes php int size 8 bitsnphp int max 2147483647php int size 4 bytes 32 bitshowever part of an an encoding algorithm i am using relies on the fact that an int is the above size 4 bytes when i run the code on my web hosts server it is a 64bit system and the int size is twice as largeis there a way to force int cast to use the 32bit sizefor example assume the following codetest 4170266799print test print int teston my 32bit system the output is4170266799124700497on my 64bit system the output is41702667994170266799is it possible to force the value of an int to be 4 bytes even when the architecture changes from 32bit to 64bit,['php'] +215299,proguard missing type parameter i try obfuscate my code of android app with proguard but after this my app give exception at running 15 014626818 wsystemerr21810 javalangruntimeexception missing type parameter15 014626828 wsystemerr21810 at dainitunknown source15 014626828 wsystemerr21810 at gcinitunknown source15 014626828 wsystemerr21810 at fxfunknown source15 014626828 wsystemerr21810 at comyourshowsactivityunwatchedactivityonresumeunknown sourcei checked a mapping file and found this comgooglegsonreflecttypetoken dai think it is lines in my app like type maptype new typetokenmapinteger watchedepisodesgettype define generic type jsdata gsonfromjsonr maptypei can not understand what conclusions should i do do not use variable name less then three characters or whatupd answer,['android'] +215307,man in the middle mitm proxy with https support we seem to be going round in circles a bit at the moment we are looking for simple light weight preferably ruby based proxy that enables us to do the followingproxy https requests between a browser and a web app eg gmailintercept and modify the requestresponses man in the middle modificationgenerate on the fly ssl certs or maybe us preconfigured for use between the proxy and the browserusing ruby weve experimented with emproxy and goliath but i do not think these are quite the right fitany suggestions would be very much appreciatedbest regardscarlskii,['ruby'] +215326,release management releasing to a subset of users how would it work for a public facing website i read somewhere sorry do not exactly remember the source that facebook has release tuesdays they release the new features to their internal employees first then to a small set of external users and then to the whole world i believe google also does something similari work primarily with microsoft stack tfs for source control iis aspnet sql server with huge data public facing sites of course so they have to be up 24x7x365 though i can envision releasing my apidll only on one of the servers in the webfarm and testing it out how would i do this if there are db stored proc signatures table schema changes presently we are versioning sps the new ones will be myspnamev2 where as the old one will be myspnamev1 both taking different set of parameters hence the renaming and the new apis would use spv2 where as the old api would continue with spv1i see some design smell but is there a better way to do itedit we release the new code to only one server and test it what is difficult is how would you abstract may be abstract is not the right word but you get the idea db schema changes from multiple concurrent versions of the application,"['asp.net', '.net']" +215332,static classes in javasomething is being shadowed following is the simplest example of static inner class in java let us look at itpackage staticclassfinal class outer final public static class inner static string s black static extra inner new extra the inner class name and the object name of the class extra are same and it is responsible for shadowinghiding innersfinal class extra string s whitefinal public class main public static void mainstring args systemoutprintlnouterinners within the outer class there is a static class named inner and a static object with the same name inner of type extra the program thisplays whilte on the console a string in the extra class through outerinners in main which is intended to thisplay the string contained in the inner class within the outer classwhy is there no name collision between a static inner class and a static object of type extra how does the extra class enjoys the higher priority than the inner class and thisplays the string contained in the extra class,['java'] +215339,how does lazy get around needing new constraint example 1 does not compilevoid main var c new cd cmfclass ct t m null public t m get if m null m new t return m class d public void f consolewriteline i was created resultcannot create an instance of the variable type t because it does not have the new constraintexample 2 worksvoid main var c new cd cmfclass ct lazyt m new lazyt public t m get return mvalue class d public void f consolewriteline i was created resulti was created,['c#'] +215341,get text above table ms word this one is probably a little stupid but i really need it i have document with 5 tables each table has a heading heading is a regular text with no special styling nothing i need to extract data from those tables plus header currently using ms interop i was able to iterate through each cell of each table using something like this apptables1cell2 2rangetextbut now i am struggling on trying to figure out how to get the text right above the table heres a screenshot for the first table i need to get i need this text and for secnd table i need to get and this one also pleaseso basically i need last paragraph before each table any suggestions on how to do this,"['c#', '.net']" +215349,use didselectrowatindexpath or prepareforsegue method for uitableview i am using storyboards and i have a uitableview i have a segue setup that pushes from my table to the detail vc but which method should i use to handle this i will have to pass a couple objects to the detail view but do i use didselectrowatindex or voidprepareforsegueuistoryboardsegue segue senderidsender,"['iphone', 'objective-c']" +215360,how to redirect to the same page in php how can i redirect to the same page using php for example in local my web address ishttplocalhostmywebindexphphow can i redirect within my website to another page sayheaderlocation clientsphpi know this might be wrong but do i really need to put the whole thing what if later it is not httplocalhost is there any way to do something like this also i have a lot of code and then at the end after it is done processing some code i am attempting to redirect using that is that ok,['php'] +215440,spliting the first character of the words i have a requirement where i have to take the first letter of two words alone like i get the response from the webservice as john cooper and i have to take jc from this i tried sbstr02 but this takes jo is there any way we can form like above,['javascript'] +215460,recommended way to implement push notifications i am building an app for android and iphone this app needs to receive notification for new messages in users inbox being a total noob in app dev i was wondering if any of you guys could suggest the best way to implement what i need herei have read up more on android than iphone so my understanding of latter may be wanting based on what i have read and understood i believe that i will need to start a service when my app launches for the first time or instruct the device to start the service every time the device starts or something this service will then interface with a server to receive notifications and thisplay them clicking on the notification will launch the appmy options are c2dm or apnsurban airshipmy own server using mostly idle tcp connection with clientdepending upon the option i choose my client side implementation as well as server side implementation changeswhat will you guys recommend is there any other way to do what i need doneany help is greatly appreciatedupdatebuilding on jbat100 answer the fact that apple does not allow me to write my own server to communicate directly with my app for notifications means that apns must be used so option 3 is out altogether this means we are left with either urban airship or interfacing directly with apns and c2dm based on my research the effort involved in both cases is comparable so it does not make sense to shell out 45k mo extra just to support notification so i plan to implement option 1 if any of you think otherwise please leave comments belowthanks,"['android', 'iphone', 'ios']" +215461,loading hasmany data in extjs i am trying to load nested data in a hasmany relation in extjs4my model looks like thisextdefineentrypagemodelentrypage extend extdatamodel fields idtitleurlkeytextpicturekeywords searchtermsdescriptioncritriamodus hasmany model entrypagecriteriumnamebrands proxy type ajax url adminextjsonentrypages reader typejson rootentrypages and entrypagecriteriumextdefineentrypagemodelentrypagecriterium extend extdatamodel fields idtypetitlei load my data like soentrypageloadnikoncoolpixsuccessfunctionrecordoptionssuccessconsolelogrecordit loads fine json returns this success true entrypages id1 urlkeynikoncoolpix titlenikon coolpix textsome blahblah about nikon keywordsnikoncoolpixdigitalecamera descriptionnikon coolpix cameras picturenikon coolpix cameras searchtermsnikon coolpix languagenl brands id27038titlenikontypebrand but when i try recordbrands or anything like that it says no such method existsi think something is going wrong in mapping the data in the modelany helpy would be very much appreciated,['javascript'] +215480,method within a method i am creating a c library with some reusable code and was trying to create a method inside a method i have a method like thispublic static void method1 codewhat i would like to do is thispublic static void method1 public static void method2 public static void method3 then i could choose either method1method2 or method1method3 obviously the compiler is not happy about this any help is much appreciated thanks,['c#'] +215504,how can i print error stack trace in jsp page i have set my error page like this in webxml errorpage exceptiontypejavalangexceptionexceptiontype locationerrorserrorjsplocation errorpagenow i would like to print stack trace of error on jsp of course in development mode only how can i print stack trace of error on my jsp page i do not use any frameworks for this application so only default servlet apis are available for my program,['java'] +215518,is it possible to get an object property name string without creating the object instance a string representation of an object instance property can be taken with expressionfunctstring propertyname memberexpression propertybodymembernamebut what if i do not have do not want to create the instance how do i get the property name in this caseexplainedi need a string representation of a property name of some objectlet us say there is an entitypublic class customer public int id public string namenow i want to pass the key expression of this entity to some other function thus i need the string id but i do not want to hardcode the string like someotherfunctionid instead i use the expression someotherfunctionexpressionreadergetstring customerinstanceid for this to work i need to supply the entity instancenow i want to do the same without creating the instance,['c#'] +215528,insert image to excel file using jxl without stretching it i can insert image to my excel file using jxl usingsheetaddimagewritableimage obj my problem is that it stretches based on the args of writableimage i am wondering if there is a way so that the image that i insert will not stretch like if i insert a 200x200 sized image it will appear to the sheet as 200x200,['java'] +215535,how to set linecolor for linechart using coreplot i am using coreplot 09 i had tried setting linecolor property for cptlinestyle bycptlinestyle linestyle cptlinestyle linestylelinestylelinecoloruicolor graycolorbut it is giving error that linecolor is readonly property please give me some solution for this,"['iphone', 'objective-c']" +215538,jackson deserialize variable as json string i have a model like thatprivate string messageprivate integer errorcode private string datai get a json string from remote and message errorcode variables gets the correct value however i do not want to deserialize to my data variable i want it to be a json string as likecat 1234 ner 80 name pinta after that i will deserialize it to object myself how can i do thatps to clarify questioni get a json string like that datacat 1234 ner 80 name pinta message m errorcode 12 after deserialization my variables should have that valuesmessage merrorcode 12data cat 1234 ner 80 name pinta,['java'] +215539,force application close on system shutdown i have a windows forms application that when the main window is closing it thisplays a basic dialog box confirming the action if the user decides to cancel the application exit is cancelledhowever when the application is running minimized and the user wants to shut down the pc the shutdown sequence stops because my application is waiting on the user to confirm the application close the dialog box is thisplayedi thought of adding a timer for making a timeout and if no answer comes in a certain amount of time close the application automatically but even if this is a way to do it it is certainly not how every other app does itso what would there be an optimal solution to confirm the application shutdown in every other case unless the system is shutting downthank you,['c#'] +215550,library not found for lcommoncrypto i need to link my ios 5 app with commoncrypto the problem is that i cannot compile due to this error library not found for lcommoncrypto how can i solve,"['iphone', 'ios']" +215564,storing a dictionary with polymorphic values in mongodb using c let us say we have a key with values which are polymorphic in their sense consider the next sample projectpublic class tobeserialized bsonid public objectid mongoid public idictionarystring basetype dictionarypublic abstract class basetypepublic class type1 basetype public string value1public class type2basetype public string value1 public string value2internal class program public static void main var objecttosave new tobeserialized mongoid objectidgeneratenewid dictionary new dictionarystring basetype oded1 new type1 value1value1 oded2 new type1 value1value1 string connectionstring mongodblocalhostserialization var mgsb new mongourlbuilderconnectionstring var mongoserver mongodbdrivermongoservercreatemgsbtomongourl var mongodatabase mongoservergetdatabasemgsbdatabasename mongocollectiontobeserialized mongocollection mongodatabasegetcollectiontobeserializeddictionary mongocollectionsaveobjecttosave tobeserialized received mongocollectionfindone sometimes when i try to deserialize it i get deserialization errors like unknown thiscriminator value the name of concrete type what am i doing wrong if every value stores a t why cannot it map it correctly,['c#'] +215585,php generate image curly arrow is it possible to create this image in php using gd i know i need to use gd and imagecreate imagecolorallocate imagedestroy etc but i have no idea how to do the curvei need to create multiple arrows with these patternsdifferent type of arrowsdifferent inclination of the curvedifferent colorsdifferent lengthedit this way i do not have to look on the internet for arrows based on a userclient specs and then later i will add text to the image for example click next or follow the arrow since im not a graphic designer creating these iamges using gd will be easier for meeg arrow curvejpg images13664curved inlinepngthanks,['php'] +215594,how to do left join in linq to entities i have spent the last 2 days trying to find out how to do a real left join in linq and i have not been successfuli have a user table that has a primary2address column in it that could and is often nullso i have to do a left join here in addition in the address table i have more relationship that could be null so i have to do multiple left joinsevery linq attempt i do outputs some seriously crazy sql statements with unions nested select statements and more wacky thingsall i need isselect uusername from users you left join addresses a on aaddressid uprimary2addressleft join states s on sstateid aaddress2stateleft join countries c on ccountryid acountryidplease help so far my workaround was to create a stored procedure that uses my sql statement above but i would really like to try to do this with linq l2ethanks guys,['.net'] +215634,how should i get my inputaccessoryview to resize when rotating device i am attaching a uitoolbar to my uitextview as its inputaccessoryview in order to add a button to thismiss the keyboard this works great and it looks correct when the device is in portrait mode but i am having trouble figuring out how to resize the toolbar to the lower height used for toolbars when the device is in landscape modei am adding the toolbar in my text views delegates textviewshouldbeginediting methodif textviewinputaccessoryview uitoolbar keyboardbar uitoolbar alloc init keyboardbarautoresizingmask uiviewautoresizingflexiblewidth uiviewautoresizingflexibleheight uiviewautoresizingflexiblebottommargin uiviewautoresizingflexibletopmargin keyboardbarbarstyle uibarstyleblacktranslucent uibarbuttonitem spaceitem uibarbuttonitem alloc initwithbarbuttonsystemitemuibarbuttonsystemitemflexiblespace targetnil actionnil uibarbuttonitem donebutton uibarbuttonitem alloc initwithbarbuttonsystemitemuibarbuttonsystemitemdone targetself actionselectorthismisskeyboard keyboardbar setitemsnsarray arraywithobjectsspaceitem donebutton nil spaceitem release donebutton release keyboardbar sizetofit textviewinputaccessoryview keyboardbar keyboardbar releasei get strange behavior from this code in landscape mode though if i start editing in landscape mode the toolbar has the landscape height but the done button is drawn half off the screen if i then rotate to portrait mode the done button is drawn in the correct location and it remains in the correct location when i rotate back to landscape modeif i start editing in portrait mode the toolbar is drawn with portrait height but the done button is drawn in the correct location if i then rotate to landscape mode the toolbar remains portrait height but the done button is still drawn in the correct position at leastany suggestions for how to get this to resize when the device rotates i am really hoping there is a more automatic way than manually plugging in the height magic numbers in one of the view controllers rotation events,['ios'] +215642,current url in safari extension safariapplicationactivebrowserwindowactivetaburl is always undefinedany idea why this might be,['javascript'] +215652,differences in query algorithms between xpath and css i am wondering why someone would want to use css selectors rather than xpath selectors or viceversa if he could use either one i think that understanding the algorithms that process the languages will resolve my wonderthere is a lot of documentation on xpath and css selectors individually but i have found very few comparisons also i do not use css selectors that muchheres what i have read about the differences these three references thiscuss the use of xpath and css selectors in selenium to query html but my wonder is generalxpath allows traversal from child to parentcss selectors have features specific to htmlcss selectors are faster when youre using internet explorer in seleniumit looks like css selection algorithms are somehow optimized for html but i do not know howis there a paper on how css and xpath query algorithms work and how they differare there other abstract differences between the languages that i am missing,['html'] +215655,adjusting for the default timezone setting on rds we recently switched to an rds instance and noticed that bunch of our database tasks were getting triggered 4 hours earlier than needed on investigating further the problem is caused by the default timezone setting utc on the rds instance since this setting can not be altered we would like to fix the issue on the code level globally across all our applications using this database instance i tried to set the timezone on the db instance i create to useastern by usingset global time zone useastern orset time zone useasternbut that generates an error database error unknown or incorrect time zone useasternwhat do you think i am doing wrong here does anyone has used any other solutions,['mysql'] +215667,javascript replace only replaces the first match i have the following script in javascriptvar string this is a testvar result idtextreplace alertresultwhen i show the variable result i was expecting it to remove all of the underscores and give me the text this is a test but instead i get this is a testany idea on how to fix this,['javascript'] +215676,how are constructors called during serialization and deserialization how are the constructors called during serialization and deserializationwhen there is one class implementing serializablewhen there is parentchild relationship and only child implements serializablewhen there is parentchild relationship and both parent and child implements serializable,['java'] +215697,c throw syntax i have a general question regarding the syntax of throwing an object considerinclude stdiohstruct bad void func throw badint mainint char try func catchbad printfcaughtn return 0this code does not compile g 443 as the throw line must be replaced withthrow badwhy is this if i am creating a stackallocated bad i construct it like sobad b i cannot use bad b as it is mistaken for a function prototypei have consulted stroustrups book and this website but was unable to find any explanation for what seems to be an inconsistency to me,['c++'] +215700,why do we need parentheses around block macro in linux container of macro is enclosed in seemingly extra parentheses define container ofptr type member const typeof type 0member mptr ptr type char mptr offsetoftypemember instead of it can we just use define container ofptr type member const typeof type 0member mptr ptr type char mptr offsetoftypemember are the parentheses mandatory or are they just for precaution,['c'] +215722,extending phpunit adding a decorator contexti recently inherited the development and maintenance of a wellprogrammed php application sarcasm the application is based on a commercial software which i will not name and there is a layer of customization ours that is built on top of it unfortunately this application uses a ton of globals and singletons punintended i have built test cases for all the things weve overridden however a lot of things relies on some global state of something which can cause race conditions and all sorts of weird stuffrandomizing the testsin order to catch most of these weirdotons i like to call them that i have built a phpunit testdecorator as documented in the manual1 this oneclass phpunit extensions randomizer extends phpunit extensions testdecorator public function constructphpunit framework test test tests testtests shuffle array foreach tests as t if t instanceof phpunit framework testsuite shuffle array mergeshuffle ttests else shuffle t shuffleshuffle suite new phpunit framework testsuite foreach shuffle as t suiteaddtestt parent constructsuite it basically randomizes the tests order to make sure a test does not depend on a global state that may or may not be correctthe questionthe problem arose when came the time to test my custom decorator i have not found anywhere in the manual google or stack overflow how to load it when analyzing the code i saw that phpunit itself was instantiating the repeatedtest decorator in the textui testrunnerdorun method i know i can subclass the testrunner override dorun arrange for my decorator to be created and then just call the parentdorun with my decorator instance as the argument override textui command and create a new cli script to use my stuff instead of the builtin stuffbefore i reinvent the wheel i was just wondering is it possible do load a custom decorator without subclassing the testrunnerthanks,['php'] +215724,loading csv files into mysql workbench i have a lot of excel csv files that i need to load into my db in mysql workbench i am on mac os x i have searched around for a good walkthrough or tutorial but i have not seen anything that clearly explains how to load csvs into mysql workbenchcan anyone help,['mysql'] +215727,how to get array of bits in a structure i was pondering and therefore am looking for a way to learn this and not a better solution if it is possible to get an array of bits in a structurelet me demonstrate by an example imagine such a codeinclude stdiohstruct a unsigned int bit01 unsigned int bit11 unsigned int bit21 unsigned int bit31int main struct a a 1 0 1 1 printfun abit0 printfun abit1 printfun abit2 printfun abit3 return 0in this code we have 4 individual bits packed in a struct they can be accessed individually leaving the job of bit manipulation to the compiler what i was wondering is if such a thing is possibleinclude stdiohtypedef unsigned int bit1struct b bit bits4int main struct b b 1 0 1 1 for i 0 i 4 i printfun bbitsi return 0i tried declaring bits in struct b as unsigned int bits41 or unsigned int bits14 or similar things to no avail my best guess was to typedef unsigned int bit1 and use bit as the type yet still does not workmy question is is such a thing possible if yes how if not why not the 1 bit unsigned int is a valid type so why should not you be able to get an array of itagain i do not want a replacement for this i am just wondering how such a thing is possibleps i am tagging this as c although the code is written in c because i assume the method would be existent in both languages if there is a c specific way to do it by using the language constructs not the libraries i would also be interested to knowupdate i am completely aware that i can do the bit operations myself i have done it a thousand times in the past i am not interested in an answer that says use an arrayvector instead and do bit manipulation i am only thinking if this construct is possible or not not an alternativeupdate answer for the impatient thanks to neagoegabinstead oftypedef unsigned int bit1i could usetypedef struct unsigned int value1 bitproperly using pragma pack,"['c++', 'c']" +215730,mapactivity cannot be resolved to a type i am busy trying to get the mapview included in my android project i am following the mapview tutorial on the android developer website but i am getting an errormapactivity cannot be resolved to a typei tried pressing ctrlshifto to auto import all classes but it is not helping when i try to include the maps libary manually it gives this errorthe import comgoogleandroid cannot be resolvedi have added the following line see below to the manifest and my target is api 7 platform 21useslibrary androidnamecomgoogleandroidmaps what am i doing wrongthanks,['android'] +215732,different browsers different ips i am saving the users ip addresses by saving the value of serverremote addr in a mysql database problem is that for both firefox and chrome serverremote addr is 1 that means localhost in ipv6 and for ie and opera is 127001 ipv4so my questions areare ip versions browserdependant i used to think it depended onthe computershould i create two fields in the database one for ipv4 addresses and one for ipv6 onesshould i unify all ips to ipv6 and how can i do this in php if it is even possible,['php'] +215766,variable declaration placement guidelines in java there seems to be two accepted variable declaration placements for java variables each with different raison daatrefrom the suns code conventions we can seeput declarations only at the beginning of blocks a block is any code surrounded by curly braces and do not wait to declare variables until their first use it can confuse the unwary programmer and hamper code portability within the scopehowever in the highly praised code complete and some other authors advocate for reducing the scope of a variable to a minimum that is basically waiting to declare variables until their first usethese two approaches are clearly contradictory although i can see the point for both of themwhich should i follow is there any consensus on the matter,['java'] +215770,zeromq in javascript client have anyone used zmqsocketjs successfully i would like to know how can it be used to establish a safe channel between the browser and a zeromq server app is there otherbetter options for such use case,['javascript'] +215796,jstack not working on server we use jstack on servers to detect if java apps are getting deadlocked it is not working on one of our linux servers i think os version iscat etcissuenetred hat enterprise linux server release 56 tikangakernel r on an mjava version running on server java version 160 24javatm se runtime environment build 160 24b07java hotspottm 64bit server vm build 191b02 mixed modewhen i tryjstack 19114i get19114 unable to open socket file target process not responding or hotspot vm not loadedthe f option can be used when the target process is not respondingwhen i tryjstack f 19114i getattaching to process id 19114 please waitdebugger attached successfullydeadlock detectionno deadlocks foundthread 19180 state blockederror occurred during stack walkingsunjvmhotspotdebuggerdebuggerexception sunjvmhotspotdebuggerdebuggerexception get thread regs failed for a lwp at sunjvmhotspotdebuggerlinuxlinuxdebuggerlocallinuxdebuggerlocalworkerthreadexecutelinuxdebuggerlocaljava152 at sunjvmhotspotdebuggerlinuxlinuxdebuggerlocalgetthreadintegerregistersetlinuxdebuggerlocaljava466 at sunjvmhotspotdebuggerlinuxlinuxthreadgetcontextlinuxthreadjava65 at sunjvmhotspotruntimelinux amd64linuxamd64javathreadpdaccessgetcurrentframeguesslinuxamd64javathreadpdaccessjava92 at sunjvmhotspotruntimejavathreadgetcurrentframeguessjavathreadjava256 at sunjvmhotspotruntimejavathreadgetlastjavavframedbgjavathreadjava218 at sunjvmhotspottoolsstacktracerunstacktracejava76 at sunjvmhotspottoolsstacktracerunstacktracejava45 at sunjvmhotspottoolsjstackrunjstackjava60 at sunjvmhotspottoolstoolstarttooljava221 at sunjvmhotspottoolsjstackmainjstackjava86 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava39 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava25 at javalangreflectmethodinvokemethodjava597 at suntoolsjstackjstackrunjstacktooljstackjava118 at suntoolsjstackjstackmainjstackjava84caused by sunjvmhotspotdebuggerdebuggerexception get thread regs failed for a lwp at sunjvmhotspotdebuggerlinuxlinuxdebuggerlocalgetthreadintegerregisterset0native method at sunjvmhotspotdebuggerlinuxlinuxdebuggerlocalaccess800linuxdebuggerlocaljava51 at sunjvmhotspotdebuggerlinuxlinuxdebuggerlocal1getthreadintegerregistersettaskdoitlinuxdebuggerlocaljava460 at sunjvmhotspotdebuggerlinuxlinuxdebuggerlocallinuxdebuggerlocalworkerthreadrunlinuxdebuggerlocaljava127anyone know what is causing this,['java'] +215816,servlet filtering using java ee 6 annotation is it possible to simulate a servlet filter chain using applicationpath and path annotations in ee 6exampleapplicationpathapiclass filter extends application path public void filter loginforequest to api pathfooclass foo get pathbar producestextplain public string bar return hello world where the url would be but the filter method would be invoked as if it were a servlet filter chain i know the approach above wont work but is there an annotated approach in this ilk that would achieve the same as if the filter was configured from webxml file,['java'] +215828,barcode scanner implementation on java good sirs i have a question the school java project i am currently working on requires me to have a usb barcode scanner as an external input to be connected to my laptop i have not actually bought the usb scanner since it is quite expensive for a student so i have to gather evidence that this scanner would work with my program would the scanner be able to read from a barcode presumably printed off online and store it into a variable if so is it true that the action event for the press of the scanner would be read exactly like a keyboard keypress if so what would the line of code look like also if you could post your experiences with barcode scanners or give any advice such as which scanner to buy that would help alot cheers,['java'] +215840,how to read appsettings section in the webconfig file my xml looks like this and the name is webconfigxml version10configuration appsettings add keyconfigfile valueiisconfig add keyrialtodomain valueasnc auditors appsettings systemservicemodel systemservicemodelconfigurationin the code when i read like this string path configurationsettingsappsettingsconfigfilehere i am getting a null value no exception thrown hereis this right way to do or is there any other methodthanks in advancewaiting for the response,['.net'] +215841,androidadd helvetica neue font in application i am making an app in which i have to use helvetica neue font for text but problem is thid that i do not know that how to use helvetica font in android my question is that do android support helvetica font and it yes then how to use that that font because i was not able to find helvetica font in windowspreferencegeneralappreancecolor and fonts any help will be appreciatedthanks,['android'] +215848,android database transaction i have created database i want to do the transaction savecustomer contain more than one statement to insert records to customer customercontrol profilepayment table at that timewhen user call savecustomer method then that data will go to these 4 tableso how can i do the transaction if one table insert failer then need to rollback everything for example when 3rd table insert the record i got error then need to rollback previous two tables insert records alsosee my code public void savecustomer dbadapter dbadapter dbadaptergetdbadapterinstanceretailerorderkeyactivitythis dbadapteropendatabase contentvalues initialvalues new contentvalues initialvaluesputcustomernamecustomergetname initialvaluesputaddresscustomergetaddress initialvaluesputcustomerpidstrpid initialvaluesputdatestrdateonly long and dbadapterinsertrecordsindbcustomer null initialvalues likewise other statement also theredbadpter code is public long insertrecordsindbstring tablename string nullcolumnhackcontentvalues initialvalues long and 1 try mydatabasebegintransaction and mydatabaseinserttablename nullcolumnhack initialvalues mydatabaseendtransaction mydatabasesettransactionsuccessful catch exception e how to do the rollback eprintstacktrace return nthis is the full code public class dbadapter extends sqliteopenhelper private static string db path datadatacommycontrollerdatabases private static final string db name customer private sqlitedatabase mydatabase private final context mycontext private static dbadapter mdbconnection private dbadaptercontext context supercontext db name null 1 thismycontext context db path datadata contextgetapplicationcontextgetpackagename databases the androids default system path of your application database is datadatamypackagenamedatabases public static synchronized dbadapter getdbadapterinstancecontext context if mdbconnection null mdbconnection new dbadaptercontext return mdbconnection public void createdatabase throws ioexception boolean dbexist checkdatabase if dbexist do nothing database already exist else by calling following method 1 an empty database will be created into the default system path of your application 2 than we overwrite that database with our database thisgetreadabledatabase try copydatabase catch ioexception e throw new errorerror copying database private boolean checkdatabase sqlitedatabase checkdb null try string mypath db path db name checkdb sqlitedatabaseopendatabasemypath nullsqlitedatabaseopen readonly catch sqliteexception e database doest exist yet if checkdb null checkdbclose return checkdb null true false private void copydatabase throws ioexception inputstream myinput mycontextgetassetsopendb name string outfilename db path db name outputstream myoutput new fileoutputstreamoutfilename byte buffer new byte1024 int length while length myinputreadbuffer 0 myoutputwritebuffer 0 length close the streams myoutputflush myoutputclose myinputclose open the database throws sqlexception public void opendatabase throws sqlexception string mypath db path db name mydatabase sqlitedatabaseopendatabasemypath null sqlitedatabaseopen readwrite override public synchronized void close if mydatabase null mydatabaseclose superclose call on creating data base for example for creating tables at run time override public void oncreatesqlitedatabase db override public void onupgradesqlitedatabase db int oldversion int newversion dbexecsqlalter table wmpalmuploadcontrol add testing int public void upgradedb onupgrademydatabase 1 2 public cursor selectrecordsfromdbstring tablename string tablecolumns string whereclase string whereargs string groupby string having string orderby return mydatabasequerytablename tablecolumns whereclase whereargs groupby having orderby public arraylistarrayliststring selectrecordsfromdbliststring tablename string tablecolumns string whereclase string whereargs string groupby string having string orderby arraylistarrayliststring retlist new arraylistarrayliststring arrayliststring list new arrayliststring cursor cursor mydatabasequerytablename tablecolumns whereclase whereargs groupby having orderby if cursormovetofirst do list new arrayliststring forint i0 icursorgetcolumncount i listadd cursorgetstringi retlistaddlist while cursormovetonext if cursor null cursorisclosed cursorclose return retlist public long insertrecordsindbstring tablename string nullcolumnhackcontentvalues initialvalues long and 1 try mydatabasebegintransaction and mydatabaseinserttablename nullcolumnhack initialvalues mydatabaseendtransaction mydatabasesettransactionsuccessful catch exception e how to do the rollback eprintstacktrace return n public boolean updaterecordindbstring tablename contentvalues initialvalues string whereclause string whereargs return mydatabaseupdatetablename initialvalues whereclause whereargs 0 public int updaterecordsindbstring tablename contentvalues initialvalues string whereclause string whereargs return mydatabaseupdatetablename initialvalues whereclause whereargs public int deleterecordindbstring tablename string whereclause string whereargs return mydatabasedeletetablename whereclause whereargs public cursor selectrecordsfromdbstring query string selectionargs return mydatabaserawqueryquery selectionargs public arraylistarrayliststring selectrecordsfromdbliststring query string selectionargs arraylistarrayliststring retlist new arraylistarrayliststring arrayliststring list new arrayliststring cursor cursor mydatabaserawqueryquery selectionargs if cursormovetofirst do list new arrayliststring forint i0 icursorgetcolumncount i listadd cursorgetstringi retlistaddlist while cursormovetonext if cursor null cursorisclosed cursorclose return retlist database lock problem in htc desirei want to rollback if there any issues occurred when insert the table dataplease help methanksi looked this same related question,['android'] +215858,why does basic iosswap only do a partial swap c11 a2754221void swapbasic ios rhseffects the states of this and rhs shall be exchanged except that rdbuf shall return the same value as it returned before the function call and rhsrdbuf shall return the same value as it returned before the function callwhat is this partial swapping useful forcan it cause trouble,['c++'] +215873,jquery if scroll is a certain amount of pixels is there a built in jquery function to determine the length of a scrolli am trying to write a function that will add a class to a div if the user has scrolled 50 pixels from the topso the code will look like thisifuserhasscrolled mydivaddclasshasscrolled,['jquery'] +215877,difference between running task and running process in android can any one please tell me what is the difference between task and process in androidif i use this code snippetactivitymanager appmgrprotected listactivitymanagerrunningtaskinfo appsprotected listactivitymanagerrunningaprocessinfo applicationsapplications appmgrgetrunningaprocessesapps appmgrgetrunningtasks30whats the difference between applications appmgrgetrunningaprocesses and apps appmgrgetrunningtasks30please help meregards,['android'] +215897,how do i find duplicates across multiple columns so i want to do something like this sql code belowselect sid snamescity from stuff sgroup by sname having countwhere city and name are identical 1to produce the following but ignore where only name or only city match it has to be on both columnsid name city 904834 jim london 904835 jim london 90145 fred paris 90132 fred paris90133 fred paris,['sql'] +215929,appending timestamp in log file name of java util logger currently i am using using java util for logging logs into the file which can be configured from javautilloggingfilehandlerpattern i want to append a timestamp in the log file name i also have to take the log file path from javautilloggingfilehandlerpattern property,['java'] +215933,double foreach break with a if statement possible duplicatebreaking out of a nested loop i got somthing like to simplifyforeach foreach some code if statement break the thing is that i want my statement to leave for the doubleforeach loop i am thinking about a sort of break flag as a boolean but is there any way to avoid that,['c#'] +215951,ignore case in glob on linux i am writing a script which will have to work on directories which are modified by hand by windows and linux users alike the windows users tend to not care at all about case in assigning filenamesis there a way to handle this on the linux side in python ie can i get a caseinsensitive globlike behaviour,['python'] +215961,how to correctly compare host names i have a few host names that i need to compare and tell if they represent the same host for examplelocalhost127001machinenamewhat is the most reliable way to do it in c for now i am doing that like private bool comparehostsstring host1 string host2 uribuilder builder1 new uribuilder builder1host dnsgethostaddresseshost10tostring var uri1 builder1uri uribuilder builder2 new uribuilder builder2host dnsgethostaddresseshost20tostring var uri2 builder2uri return uricompareuri1 uri2 uricomponentshost uriformatunescaped stringcomparisonordinalignorecase 0 i have not included error handling for host addresses array but i am not sure what to do if it will return more then one address does it mean that they will represent different machines is there any better way to compare them i need to check that those hosts refer to the same machine,['c#'] +215969,google maps v3 map tile caching on client i am using google maps js api v3 for a project is there a way to ask the map to cache tiles on the clients machine so that when they refresh the browser the tiles do not have to all download againmany of my clients are on cellular connections where redownloading the map takes a considerable amount of timethanks,['javascript'] +215970,how does facebook ticker work most of facebook is written in php but there are a few front end features that use other scripting languagesticker the small box at the top right of the news feed page thisplaying recent posts etc etci am guessing ajax is involved in this but i was wondering how it all works i have developed something similar but more basic in flash where flash checks every millisecond as good as real time for updates but facebook clearly does not use flash for thisi know data can be passed back and forth with ajax but how would they make it instant constantly checkingjust wondering,['php'] +215989,correct way to inherit from stdexception i have just created exception hierarchy and wanted to pass char to constructor of one of my derived classes with a message telling whats wrong but apparently stdexception does not have constructor which would allow me to do so yet there is a class member called what which would suggest that some information can be passedhow can i can i pass text to derived class of a stdexception in order to pass info with my exception class so i can say somewhere in the codethrow my exceptionsomething bad happend,['c++'] +216025,how to target the net 4 client profile for ccli under visual studio 2010 this article describes selecting it for net 35 under vs2008how does one select the net 40 client profile for ccli under vs2010,['.net'] +216030,using an in c i was wondering how using an to access a certain memory location changed the nature of a function call for example if i had written a function to set the radius of a circletrue if success false if radius is offscreenbool setradiuscirclecircle b int rthis was an example given in the assignment my professor gave me i just wanted to know how the he included in the sample function call differed from simply using circle b,['c++'] +216071,css jquery unable to perform toggle and repeated jquerytemplate item i must warn you this is a bit overwhelming okay here we gostreamhtml template filediv clastreamitem clearfix input typebutton div classclientstrip img src altsender div div classclientview a href classclientnamesendera pvaluep pdatetimep div classitemgadgets ul li classtoggleinputvalueli lili ul div div classinputcontainer input typetext value div divdivdiv claspacer defaultaspx jquerytoggleinputliveclick function thisparentparent findinputcontainertoggle thisparentparentfindinputcontainer findinputtypetextfocusupdate the above has been changed to toggleinputliveclick function thisclosestclientviewfindinputcontainertoggle thisclosestclientviewfindinputcontainer findinputtypetextfocus issues with jqueryi have comments that belong to each streamitem my previous solution was to use listview control as followsitemtemplate asppanel idstreamitem cssclastreamitem runatserver insert another nested listview control here to load the comments for the parent stream so as you can see this is not a solution since i started using jquery templates and i am fetching the data using the following jquery ajax methodajax type post url servicesasmxgetstream data contenttype applicationjson success function stream gettemplatesstreamhtml function template tmpltemplate streamdappendtostream how can i resolve this without using the old listview solution but by using jquery templates to load the comments whenever i am getting data for a specific stream i am using a simple webmethod to return my data as followswebmethodpublic liststream getstream liststream streams streamgetrangex x httpcontextcurrentuseridentityname return streamsi am looking for a way to handle the toggleinput click event i need check if comments a main container for the to be comments container div has children or more than one commentitem if so then i need to show that inputcontainer and hide all the other inputcontainer divs with comments size 0 if they are visible please see the image belowupdate css issue below is resolved i had a conflictglobalcontainer div float right position relative thisplay inlineblock thank you firebug defaultaspx partial cssdivstreamitem divclientview float left width 542pxdivstreamitem divclientview p margin 5px 0 0 0 fontsize 10pt divstreamitem divclientviewdivinputcontainer thisplay none does not hide inputcontainer padding 2px backgroundcolor f1f1f1issues with csson page load thisplay none has no effectthat is it if youre reading this i would like to thank you for your time and thoughts,"['c#', 'javascript', 'jquery', 'asp.net', 'css']" +216082,resourcenotfoundexception how to debug i have got couple reports on market about this exception there is no reference to where it happens in my app and majority of users do not have thit issue how do i debug something like that this is not exception i get from all devices just one specific device might report itandroidcontentresresourcesnotfoundexception resource id 0x109005d at androidcontentresresourcesgetvalueresourcesjava892 at androidcontentresresourcesloadxmlresourceparserresourcesjava1869 at androidcontentresresourcesgetlayoutresourcesjava731 at androidviewlayoutinflaterinflatelayoutinflaterjava318 at androidviewlayoutinflaterinflatelayoutinflaterjava276 at comandroidinternalpolicyimplphonewindowgeneratelayoutphonewindowjava2451 at comandroidinternalpolicyimplphonewindowinstalldecorphonewindowjava2506 at comandroidinternalpolicyimplphonewindowgetdecorviewphonewindowjava1626 at androidappactivitythreadhandleresumeactivityactivitythreadjava2165 at androidappactivitythreadhandlelaunchactivityactivitythreadjava1672 at androidappactivitythreadaccess1500activitythreadjava117 at androidappactivitythreadhhandlemessageactivitythreadjava935 at androidoshandlerthispatchmessagehandlerjava99 at androidoslooperlooplooperjava130 at androidappactivitythreadmainactivitythreadjava3687 at javalangreflectmethodinvokenativenative method at javalangreflectmethodinvokemethodjava507 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava842 at comandroidinternaloszygoteinitmainzygoteinitjava600 at dalviksystemnativestartmainnative method,['android'] +216099,how to run own daemon processes with django in my django project i have to do repeatedly some processing in the backgroundthis processing needs access to django stuff so i put it into djangos commands and run it as cronjobright now i realize that i have to do some of them more frequently cronjob has limitation to invoke command at most every 1 minute another problem is that i do not have enough control to protect running the same command in one time it is happen when one processing takes longer than one minutei think that i should run them like daemons but i am looking for pure way to do it with djangohave you ever faced with this problem or know any clean solution for it,['python'] +216115,is it possible with upload a file and submit text in a single form i am writing a plugin for wordpress where certain information like a name and emailaddress and some info is stored in an sql database table i have got that working perfectly but this information also needs a picture to go with it so when wordpress admin fills in the form has the file selected and clicks submit i want the file to be uploaded into a directory and its location stored in a database along with the name and emailaddressall this preferably needs to be done in just one formis this possible or is there another way that would make the end user click only once on a sumbit button,"['php', 'sql']" +216125,java rmi cannot bind server i am working on java rmi application and having problem binding a server to the registry i am working on eclipse using rmi plugin and everything worked fine before i had to format my pc also i am sure the code is ok since it is the one given to me as a solution so there must be something wrong with my configuration heres the codepublic static void main string args try rmichatserver myobject new rmichatserverimpl systemsetsecuritymanagernew rmisecuritymanager namingrebindhello myobject systemoutprintlnremote object bound to registry catch exception e systemoutprintlnfailed to register object e eprintstacktrace systemexit1 exceptions it givesfailed to register object javarmiserverexception remoteexception occurred in server thread nested exception is javarmiunmarshalexception error unmarshalling arguments nested exception is javalangclassnotfoundexception access to class loader deniedjavarmiserverexception remoteexception occurred in server thread nested exception is javarmiunmarshalexception error unmarshalling arguments nested exception is javalangclassnotfoundexception access to class loader denied at sunrmiserverunicastserverrefoldthispatchunicastserverrefjava419 at sunrmiserverunicastserverrefthispatchunicastserverrefjava267 at sunrmitransporttransport1runtransportjava177 at sunrmitransporttransport1runtransportjava174 at javasecurityaccesscontrollerdoprivilegednative method at sunrmitransporttransportservicecalltransportjava173 at sunrmitransporttcptcptransporthandlemessagestcptransportjava553 at sunrmitransporttcptcptransportconnectionhandlerrun0tcptransportjava808 at sunrmitransporttcptcptransportconnectionhandlerruntcptransportjava667 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava10 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava603 at javalangthreadrunthreadjava722 at sunrmitransportstreamremotecallexceptionreceivedfromserverstreamremotecalljava273 at sunrmitransportstreamremotecallexecutecallstreamremotecalljava251 at sunrmiserverunicastrefinvokeunicastrefjava377 at sunrmiregistryregistryimpl stubrebindunknown source at javarminamingrebindnamingjava177 at rmichatserverimplmainrmichatserverimpljava175caused by javarmiunmarshalexception error unmarshalling arguments nested exception is javalangclassnotfoundexception access to class loader denied at sunrmiregistryregistryimpl skelthispatchunknown source at sunrmiserverunicastserverrefoldthispatchunicastserverrefjava409 at sunrmiserverunicastserverrefthispatchunicastserverrefjava267 at sunrmitransporttransport1runtransportjava177 at sunrmitransporttransport1runtransportjava174 at javasecurityaccesscontrollerdoprivilegednative method at sunrmitransporttransportservicecalltransportjava173 at sunrmitransporttcptcptransporthandlemessagestcptransportjava553 at sunrmitransporttcptcptransportconnectionhandlerrun0tcptransportjava808 at sunrmitransporttcptcptransportconnectionhandlerruntcptransportjava667 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava10 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava603 at javalangthreadrunthreadjava722caused by javalangclassnotfoundexception access to class loader denied at sunrmiserverloaderhandlerloadclassloaderhandlerjava447 at sunrmiserverloaderhandlerloadclassloaderhandlerjava184 at javarmiserverrmiclassloader2loadclassrmiclassloaderjava637 at javarmiserverrmiclassloaderloadclassrmiclassloaderjava264 at sunrmiservermarshalinputstreamresolveclassmarshalinputstreamjava216 at javaioobjectinputstreamreadnonproxydescobjectinputstreamjava1593 at javaioobjectinputstreamreadclassdescobjectinputstreamjava1514 at javaioobjectinputstreamreadordinaryobjectobjectinputstreamjava1750 at javaioobjectinputstreamreadobject0objectinputstreamjava1347 at javaioobjectinputstreamreadobjectobjectinputstreamjava369 13 morecaused by javasecurityaccesscontrolexception access denied javaiofilepermission duniyear 3enterprise programmingjavaczat solution 2bin read at javasecurityaccesscontrolcontextcheckpermissionaccesscontrolcontextjava366 at javasecurityaccesscontrollercheckpermissionaccesscontrollerjava5 at javalangsecuritymanagercheckpermissionsecuritymanagerjava549 at sunrmiserverloaderhandlerloadercheckpermissionsloaderhandlerjava1176 at sunrmiserverloaderhandlerloaderaccess0loaderhandlerjava1130 at sunrmiserverloaderhandlerloadclassloaderhandlerjava411 22 morei researched the problem and most say that it is because of codebase settings i also use security policy i have tried different settings and currently using compute from classpath option provided by rmi plugin which worked before but fails now please advice,['java'] +216141,object has no hasownproperty method ie it is undefined ie8 this seems quite bizarreheres my experiment in the ie8 consoletypeof obj1 objectobj1hasownproperty typeof obj2 objectobj2hasownproperty undefinedany ideas as to what could cause this,['javascript'] +216154,thisable resharper warnings that are dependent on build type i am using belt and suspenders type checking for potential null object problems resharper is not playing nicely though in a debug build it marks the if button null check as always true and puts a warning marker in the sidebar in a release build it shades the debugassert as never used code although at least it is smart enough not to clutter the sidebar this timei do not want to thisable the always truefalse resharper warning globally because it can indicate a problem in the code at the same time having to clutter my code up with resharper thisablerestore conditionisalwaystrueorfalse comments every time i do a check is ugly is there an option somewhere in resharper 51 to thisable build type contingent behavior so that the if is not marked in debug builds without preventing the warning from being shown if an assert is not presentthis should always work unless the columns are fiddled withlinkbutton button erowcells5findcontrol linkbuttonname as linkbuttonif this is not the case in a debug build have vs throw an error in the devs facedebugassertbutton nulldo not let anything go boom in production if an error is not caught in devif button null buttonvisible schedulecreatedby authentificationgetloggedinuser,['c#'] +216168,with a java executorservice how do i complete actively executing tasks but halt the processing of waiting tasks i am using an executorservice a threadpoolexecutor to run and queue a lot of tasks i am attempting to write some shut down code that is as graceful as possibleexecutorservice has two ways of shutting downi can call executorserviceshutdown and then executorserviceawaitterminationi can call executorserviceshutdownnowaccording to the javadoc the shutdown commandinitiates an orderly shutdown in which previously submittedtasks are executed but no new tasks will be acceptedand the shutdownnow commandattempts to stop all actively executing tasks halts theprocessing of waiting tasks and returns a list of the tasks that wereawaiting executioni want something in between these two optionsi want to call a command that a completes the currently active task or tasks like shutdown b halts the processing of waiting tasks like shutdownnowfor example suppose i have a threadpoolexecutor with 3 threads it currently has 50 tasks in the queue with the first 3 actively running i want to allow those 3 active tasks to complete but i do not want the remaining 47 tasks to starti believe i can shutdown the executorservice this way by keeping a list of future objects around and then calling cancel on all of them but since tasks are being submitted to this executorservice from multiple threads there would not be a clean way to do thisi am really hoping i am missing something obvious or that there is a way to do it cleanlythanks for any help,['java'] +216202,node cannot be inserted at the specified point in the hierarchy so i am trying to load plain text from an outside file into my page and i keep getting the error in the title what am i doing wrong i followed the tutorial exactly thankshtmlhtmlheadscript srcscriptscript srcajaxjsscriptheadbodyinput idbutton typebutton valueload div idcontentdivbodyhtmljquerybuttonclickfunction ajax urlajaxrequesthtml successfunctiondata contenthtmldata edit it is apparently no successful not sure why the file is there right next to it,['jquery'] +216226,immediate window behavior differences in c and vbnet i have noticed that the immediate window in vs 2010 behaves differently when debugging a c project and a vbnet project although i have not been able to find any specific documentation of this differencefor c projects i can simply type in any expression and it will be evaluated and thisplayed ie typing infoobar bazwill outputfalsein vbnet however doing the same thing outputs nothingi have to put a question mark in front of the expression for it to workfoobar bazfalseedit for clarity and my bad example aboveall other expressions exhibit the same behavior including simple math such as 1 2 sometimes the error message is different though as 1 2 results in the error labels that are numbers must be followed by colonsis there a way to fix this behavior and make the vbnet immediate window behave more like the c one having to type a in front of every statement can be a pain when using it frequently,['c#'] +216240,code cleanup tool to move all using statements inside namespace in all cs files in my solution after writing a whole bunch of code i am finally waking up to adding ca and stylecop to my solutionby default all files a lot of them in my solution have using statements at the top of the file before the namespacei have resharper 60 and powertools in visual studiois there a way using these or any other tool that will go through all my cs file in the solution and put the using statements inside the namespace for each file,"['c#', '.net']" +216243,nginxphp downloading instead of executing i have an nginx server with fastcgiphp running on it i need to add userdirs to it but i cannot get php to execute the files it just asks me if i want to download it it does work without the userdir eg it works on physibotsinfohugsphp but not physibotsinfokisseshugsphpconfigserver listen 80 server name physibotsinfo access log homevirtualphysibotsinfologsaccesslog root homevirtualphysibotsinfopublic html location php fastcgi param script filename home1public htmlfastcgi script name fastcgi pass unixtmpphpsocket location alias home1public html2 autoindex on location php try files uri errorhtmlurinull fastcgi pass unixtmpphpsocket,['php'] +216269,php templating vs echoing i would like to know which one is the best for performance1 use smarty template or any other betterphpsmarty new smarty set all the default variables and other configsmartyassignvar1 hellosmartyassignvar2 worldsmartythisplaypagehtml2 use this codephpvar1 hellovar2 worldecho var1 var23 use this codephpvar1 hellovar2 worldecho var1 var2based on these 3 examples i cant think about a new one which one is best to use when performance note of course i have more variables than this example thanks,['php'] +216283,perl dbi reconnect on thisconnect i have search google but could not find answer to what i think is an easy quiestioni have a perl code example below that gets data every 3 seconds and updates the received data into mysql database but sometimes mysql database is not available and the script dies how can i make mysql connection again if it fails use dbdmysqlsub updatemysqldbmy connect dbiconnectdbimysqldatabasehost user pw raiseerror 1 myquery my sql query to insrt data into columnsquery handleconnectpreparemyqueryquery handleexecuteconnectthisconnectwhile 1 if data received call updatemysqldb else wait for data sleep 3,['mysql'] +216285,running rake dbdrop dbcreate dbmigrate on heroku cedar stack when i try to runheroku run rake dbdrop dbcreate dbmigratei get the errorrunning rake dbdrop attached to terminal up run5could not drop adsfsadfas activerecordstatementinvalid pgerror error must be owner of database adsfsadfas drop database if exists adsfsadfasi am on the heroku cedar stack am i allowed to drop databases on herokuthanksjohn,['ruby-on-rails'] +216286,eclipse for android how to automate export android application to apk i am working an android project using eclipse i cannot test it out in emulator because of the sensor and so i have to export to apk file quite frequently the problem is that it takes more than 10 mouse clicks and entering the same password two times which i often type wrong to generate the apk filei am wondering if there is a way to automate these steps or is there a command line equivalent for those steps,['android'] +216327,how to dynamically allocate memory space for a string and get that string from user i want to read input from user using c program i do not want to use array likechar names50because if the user gives string of length 10 then the remaining spaces are wastedif i use character pointer likechar namesthen i need to allocate memory for that in such a way ofnames char malloc20 sizeofcharin this case also there is a possibility of memory wastageso what i need is to dynamically allocate memory for a string which is of exactly same as the length of the stringlets assumeif the user input is stackoverflow then the memory allocated should be of 14 ie length of the string 13 and 1 additional space for 0how could i achieve this,['c'] +216339,local sequence cannot be used in linq to sql implementation of query operators except the contains operator i use linq in my project and my code is var se from c in shopsections join c1 in objsectionobjects on csectionid equals c1sectionid select c datagridview1datasource sebut i face this error in line datagridview1datasource seerror message is local sequence cannot be used in linq to sql implementation of query operators except the contains operatorthanks for help,"['c#', 'sql']" +216342,how do we achieve substringmatch under on time i have an assignment that requires reading a huge file of random inputs for exampleadana izmir adnan menderes aptadthis ababaadenadiyamanaldanamman marka intl airportadak islandadelaide airportanuradhapurakodiak aptdallasadthisonardabil andrews afbetcif i specify a search term the program is supposed to find the lines whereby a substring occurs for example if the search term is uradha the program is supposed to show anuradhapura if the search term is airport the program is supposed to show amman marka intl airport adelaide airporta quote from the assignment specs you are to program this application taking efficiency into account as though large amounts of data and processing is involvedi could easily achieve this functionality using a loop but the performance would be on i was thinking of using a trie but it seems to only work if the substring starts from index 0i was wondering what solutions are there which gives a performance better than on,['java'] +216361,running fabric with python script together i see most of the fabric api are use together with functionexample of file samplepyfrom fabricapi import print hellodef deploy with settingshosts stringremote user ubuntu key filenamehomeubuntukeypem puthomelocalusersamplesh homeubuntu runbash homeubuntusampleshi run the command to executefab deployis it possible to running fabric in main method so when i run it as a python script the fabric will be executedpython samplepythanks,['python'] +216363,efficiently sanitize user entered text i have a html form that accepts user entered text of size about 10 and is submitted to a php page where it will be stored in mysql database i use pdo with prepared statements to prevent sql injection but to sanitize the text entered by user what are the best efforts needed to do i want to prevent any script injection xss attacks etc,"['php', 'mysql']" +216443,ternary operator and unexpected nullpointerexception i am getting nullpointerexception from the below line sometimes systemoutprintlndate row null rowgetlegmaturitydate nullafter adding brackets it is fine systemoutprintlndate row null rowgetlegmaturitydate nullplease clarify me the behavior thanks in advance,['java'] +216446,can vim highlight matching html tags like notepad vim has support for matching pairs of curly brackets parentheses and square brackets this is great for editing cstyle languages like php and javascript but what about matching html tagsnotepad has had this feature for as long as i have been using it being able to spot where blocks of html begin and end is very useful what i am looking for is something like this for vim see the green div tagsa bonus feature highlighting unclosed html tags like the red tag in this screenshotmatchit has been proposed as a nextbestthing but it requires an extra keystroke to use its functionality i would like be able to see where the blocks of html begin and end without an extra keypressi have trawled the internet to find something like this for vim apparently i am not the only one according to 2 other stackoverflow questions and nabblei have almost resigned myself to vim not being able to visually match html tags is it possible for vim to do thisaddendum if it is not currently possible to do this with any existing plugins does any vimscript wizard out there have any pointers on how to approach writing a suitable plugin,['html'] +216466,cross compiling c project relocations in generic elf em 3 i have been working on a c project for a while now but would like to port it over to my arm processor i already have all of my crosscompile tools i am using codesourcery and thought i could just change my makefile to point to that compiler it compiles fine using the default g but when try a make pointing to the crosscompiler i get relocation errors homeoryancodesourcerybinlibgccarmnonelinuxgnueabi452armnonelinuxgnueabibinld serversocketo relocations in generic elf em 3 serversocketo could not read symbols file in wrong format collect2 ld returned 1 exit status make simple server error 1 it seems like i do not have a proper link set up or it is pointing to a wrong location i am not that familiar with makefiles and am probably missing something obvious the makefile i have been using is from with the client side removed makefile for the socket programming examplesimple server objects serversocketo socketo simple server mainoall simple serversimple server simple server objects homemattcodesourcerybinarmnonelinuxgnueabig o simple server simple server objectssocket socketcppserversocket serversocketcppsimple server main simple server maincppclean rm f o simple serverright now i am manually compiling each file and it works great but i would like to further my understanding herethanks,['c++'] +216511,combine static libraries i tried the approach in this question but it seems the linux version of ar is not the same as the mac version since i failed to combine the object files againwhat i basically want to do is is merge another static library into my xcode static library build product via a runscript build phaseunfortunately i cannot compile the other library directly into my project because it has it is own build system therefore i use the compiled libsi think it should be possible to merge the other library via ar into the xcode generated library without decompiling the build product how do i accomplish this,"['objective-c', 'c']" +216537,how to select all text in jtable cell when editing but not when typing the default behavior of a jtable is to append to the contents when you start typing and to place the caret at the clicked location when clicking i want the behavior of both these things to change so the contents is replaced when i edit a cell either by typing or by clicking and then typing when i click a cell and then change the caret position however i want the contents to stay so i can change iti know how to select all when the cell becomes editing by replacing the cell editor with one that selects all inside a swingutilitiesinvokelater see elsewhere but that causes the typing behavior to break when i do this and start typing in a cell first the typed character is appended to the string then it is selected but the selection is invisible and when typing another character the contents gets replaced by thatis there a way to replace the contents immediately when typing in a highlighted but not editing cell but select all when clicking a cellhere is the code i use for the celleditorpublic class textfieldcelleditor extends jtextfield implements tablecelleditor private celleditorlistener celleditorlistener null private boolean isinteger false private object oldvalue start editing override public component gettablecelleditorcomponentjtable table object obj boolean isselected int row int column color color2 defaultlookupgetcolorthis ui tablealternaterowcolor supersetbackgroundcolor2 null row 1 1 color2 tablegetbackground supersetforegroundtablegetforeground supersetborderdefaultlookupgetborderthis ui tablefocuscellhighlightborder supersettextobjtostring isinteger obj instanceof integer if isinteger supersethorizontalalignmentswingconstantsright oldvalue obj swingutilitiesinvokelaternew runnable public void run textfieldcelleditorthisselectall return this retrieve e dited value override public object getcelleditorvalue if isinteger try to convert to integer if input is invalid revert try return new integersupergettext catch numberformatexception e return oldvalue return supergettext override public boolean iscelleditableeventobject e return true override public boolean shouldselectcelleventobject e return true override public boolean stopcellediting celleditorlistenereditingstoppednew changeeventthis return true override public void cancelcellediting celleditorlistenereditingcancelednew changeeventthis override public void addcelleditorlistenercelleditorlistener celleditorlistener celleditorlistener celleditorlistener override public void removecelleditorlistenercelleditorlistener celleditorlistener if celleditorlistener celleditorlistener celleditorlistener null,['java'] +216538,remove jquery tablesorter from table i am using the jquery tablesorter after being applied to a table by mytabletablesorter how can i remove it again from the table,['jquery'] +216565,how to convert a char to a string in java i have a char and i need a string how do i convert from one to the other,['java'] +216570,change column name without recreating the mysql table is there a way to rename a column on an innodb table without a major alterthe table is pretty big and i want to avoid major downtime,['mysql'] +216576,in android how to concatenate base64 encoded strings please help me to solve thisi have two strings for emailid and password likestring name string pass abci encode these two into base64 string likestring encoded name new stringbase64encodenamegetbytes 0string encoded pass new stringbase64encodepassgetbytes 0and i need to concatenate these two encoded strings with space like string merge encoded name encoded passi checked this string in console by systemoutprintconcatenate string mergebut in console i am getting result in two lines like this18 002529898 infosystemout1244 merge ehl6qgdtywlslmnvbq18 002529908 infosystemout1244 ywjjwhy is this happing the result is unexpected for me why it is not printing in a single line please help me to solve thisthanks,['android'] +216585,towards the true definition of java home as a java developer who switches between nix systems os x ubuntu although i can always get my jdk up and running it seems that there is no clear definition of java home in many packages which require java home to be set for example maven java home refers to your jdk directoryhadoop java home which specifies the path to the java 15x installationsun java home is the directory that contains the jrei thus have 2 questions regarding this matter any insights would be welcome also but concretely i have these two questions 1 does mac os x java installation copy the target from the javavmframeworks directory into usrbin 2 what is the definition of java home clearly we cannot define java home as simply the place where java is installed because this definition is ambiguous since java can exist both in a home location ie in systemlibraryfraemworks or alternatively it may also be directly in the usrbin directory my thoughts i believe that java home is actually meant to refer to more than just a binary java program java home probably is meant to refer to the location of a set of java related directories and binaries but still i am not really clear what this comprises and wether or not this definition which i am proposing is precise enough to be useful,['java'] +216588,android app market update propagation i uploaded a new version of my apk to the android market and activated then saved it my publisherhome reports that it is my desired version but the apps download page in the app market is still showing the previous version is there a propagation period,['android'] +216589,delete vs splice on associative array if i have a js associative array which is from what i gather is really an object and i wish to remove an element using delete myarrsomeid will set the element to undefined whilst splice would not work at all so what is the alternative for an associative array if i wish to delete an element rather than setting it to undefined,['javascript'] +216597,setinterval timing slowly drifts away from staying accurate it seems that when i setinterval for 10ms it actually fires the function every 1001ms or so this results in a slow temporal drift the longer its runningvar startvar f function if start start new dategettime var diff new dategettime start var drift diff 10 litextdrift msappendtoresultssetintervalf 10when run this shows the inaccuracy immediately0ms1ms2ms3ms4ms5ms5ms7ms8ms9ms9ms10mssee it for yourself so is there a more accurate way to keep time or a way to make setinterval behave with more accuracy,['javascript'] +216599,c boost 148 type traits and cocoa inclusion weirdness i just updated boost to version 1480 on a project i am developing on osx lion that also includes the cocoa headers after doing so i got a load of errors all pointing to has prefix operatorhpp and has binary operatorhpp which all point to lines like ie boost static constantbool value sizeofcheckmakelhs boost tt trait op makerhsmakehas operatorsizeofboosttype traitsyes typeboost 1 48 0boosttype traitsdetailhas binary operatorhpp1574 error expected expression 1after trying around since i could not really read any sense into these errors i noticed that if i switch the inclusion order fromimport cocoacocoahinclude boosttype traitshpptoinclude boosttype traitshppimport cocoacocoahthings magically work i am very confused about that since it worked just fine with the previous boost release and i have no clue why this is happening any ideas about what might be going onthanks,['c++'] +216609,android memory leak i think my android app is leaking memory i am not absolutely sure that this is the problem though every so often the app crashes when opening and logcat shows an out of memory exception trying to load a bitmap image after crashing i reopen the app and it works fine logcat shows lots of gcs and every once in a while the jit table is resized upwards never downwards until the app crashes with the out of memory errordoes this sound like a memory leak if so how do i go about locating and closing the leak here is my adb shell meminfo for my app meminfo in pid 2691 comexampledeepcliff native dalvik other total size 23264 8839 na 32103 allocated 12503 3826 na 16329 free 168 5013 na 5181 pss 2512 1395 13815 17722 shared dirty 2088 1844 5008 8940 priv dirty 2412 224 11316 13952 objects views 0 viewroots 0 appcontexts 0 activities 0 assets 2 assetmanagers 2 local binders 55 proxy binders 13death recipients 1 openssl sockets 0 sql heap 129 memory used 129 pagecache overflow 9 malloc size 50 databases pgsz dbsz lookasideb dbname 1 14 10 webviewdb 1 6 18 webviewcachedb asset allocations zipdataappcomexampledeepcliff2apkresourcesarsc 17k,"['java', 'android']" +216643,popular open source libraries and reference conflicts we use log4net in all of our many inhouse applications we typically do what amounts to xcopy deployment for developer convenience we compiled the log4net source into one of our core librariesthis is now coming back to bite us other opensource libraries such as topshelf reference log4net still others nservicebus for example merge log4net into their assemblies usually the versions differthis is a general question the specific libraries are just examplesthere are several similar questionsthe located assemblys manifest definition does not match the assembly referencenet picking wrong referenced assembly versionhow do i resolve ambiguity between my project dll and a dll in the gacnet compiled thirdparty dll reference conflictof the various solutions gac assemblybinding bindingredirect etc what is likely to cause us the least pain in the future we can modify our core library we just cannot do anything that would break an existing deployed version in the field updating all of our project references will be painful so we only want to do this onceupdate the current version of topshelf abstracted logging so this is no longer an issue with that framework,['c#'] +216648,when using presentationframeworkaero do i need to set copy local to true and include it in my setup project my wpf project uses net 4 client profile when i addresourcedictionary sourcepresentationframeworkaerocomponentthemesaeronormalcolorxaml to applicationresources i get this exception when starting the program in debug mode in release mode the program silently crashesa first chance exception of type systemwindowsmarkupxamlparseexception occurred in presentationframeworkdlladditional information set property systemwindowsresourcedictionarysource threw an exception line number 14 and line position 14when i set the property copy local of presentationframeworkaero to true everything works and the exception is gonecopy local places a copy of presentationframeworkaero in my output directory and i therefore need to include it in my setup project why is that necessary according to msdn presentationframeworkaero is included in the net framework 40 client profile and therefore in the gac i do not feel comfortable deploying a framework file with my applicationudateas hans passant suggested i verified that the directory presentationframeworkaero exists in cwindowsmicrosoftnetassemblygac msil then i used fuslogvwexe to generate the following log created when starting my application setacl studioexe without presentationframeworkaerodll being present in the application directory interestingly the loader does not even check the gac why assembly binder log entry 18112011 171327 the operation failedbind result hr 0x800702 the system cannot find the file specifiedassembly manager loaded from cwindowsmicrosoftnetframework64v4030319clrdllrunning under executable ddatenhelgeprogrammierungsetacl studiosourcebindebugsetacl studioexe a detailed error log follows prebind state information log user hkt520helgelog thisplayname presentationframeworkaero cultureneutral partialwrn partial binding information was supplied for an assemblywrn assembly name presentationframeworkaero cultureneutral domain id 1wrn a partial bind occurs when only part of the assembly thisplay name is providedwrn this might result in the binder loading an incorrect assemblywrn it is recommended to provide a fully specified textual identity for the assemblywrn that consists of the simple name version culture and public key tokenwrn see whitepaper for more information and common solutions to this issuelog appbase fileddatenhelgeprogrammierungsetacl studiosourcebindebuglog initial privatepath nulog dynamic base nulog cache base nulog appname setacl studioexecalling assembly presentationcore version40 cultureneutral publickeytoken31bf3856ad364e35log this bind starts in default load contextlog using application configuration file ddatenhelgeprogrammierungsetacl studiosourcebindebugsetacl studioexeconfiglog using host configuration file log using machine configuration file from cwindowsmicrosoftnetframework64v4030319configmachineconfiglog policy not being applied to reference at this time private custom partial or locationbased assembly bindlog attempting download of new url fileddatenhelgeprogrammierungsetacl studiosourcebindebugpresentationframeworkaerodlog attempting download of new url fileddatenhelgeprogrammierungsetacl studiosourcebindebugpresentationframeworkaeropresentationframeworkaerodlog attempting download of new url fileddatenhelgeprogrammierungsetacl studiosourcebindebugpresentationframeworkaeroexelog attempting download of new url fileddatenhelgeprogrammierungsetacl studiosourcebindebugpresentationframeworkaeropresentationframeworkaeroexelog all probing urls attempted and failedupdate 2this is the output from gacutilcprogram filesmicrosoft sdkswindowsv71bingacutilexe l presentationframeworkaeromicrosoft r net global assembly cache utility version 35307291copyright c microsoft corporation all rights reservedthe global assembly cache contains the following assemblies presentationframeworkaero version30 cultureneutral publickeytoken31bf3856ad364e35 processorarchitecturemsilnumber of items 1,['.net'] +216664,compute the different ways to make money change from 16737 this was an interview questiongiven an amount say 16737 find all the possible ways of generating the change for this amount using the denominations available in the currencyanyone who could think of a space and time efficient algorithm and supporting code please sharehere is the code that i wrote working i am trying to find the running time of this any help is appreciated import javautilhashmapimport javautiliteratorimport javautillinkedlistimport javautilmappublic class change generation param args public static void generatechangefloat amountlinkedlistfloat denominationshashmapfloatinteger useddenominations ifamount0 return ifamount0 iteratorfloat it useddenominationskeysetiterator whileithasnext float val itnext systemoutprintlnval useddenominationsgetval systemoutprintln return forfloat denom denominations ifamountdenom 0 continue ifuseddenominationsgetdenom null useddenominationsputdenom 0 useddenominationsputdenom useddenominationsgetdenom1 generatechangeamountdenom denominations useddenominations useddenominationsputdenom useddenominationsgetdenom1 public static void mainstring args todo autogenerated method stub float amount 20f float nikle05f float dollar10f float ddollar20f linkedlistfloat denominations new linkedlistfloat denominationsadollar denominationsadollar denominationsaddnikle hashmapfloatinteger useddenominations new hashmapfloatinteger generatechangeamount denominations useddenominations,"['java', 'c']" +216669,using fopen in objectivec i am puzzled by a crash i keep getting due to an error at this section of code file fid200 fid200 fopen length200vectortxt w if fid200 null perrorerror opening length200vectortxt for int and 0 n200 n if n 0 fprintf fid200 f selfavgfeaturevect0n else fprintf fid200 f selfavgfeaturevect0n fprintf fid200 n fclosefid200the error is error opening length200vectortxt operation not permittedthe file is residing in my resources folder for my project and this line is being executed in a mm file within the same project in cpp files i am using practically the same exact code which runs without a problem cannot seem to figure this one outthanks,"['c++', 'objective-c', 'ios']" +216674,whats the consolelog of java i am working on building an android app and i am wondering what the best approach is to debugging like that of consolelog in javascript,"['java', 'android']" +216678,switchcase statement and range of numbers is there a way to use switch statement with ranges in objective c in xcode hypothetically something like this nsstring evaluatensintegersamplesize nsstring returnstr switch samplesize case samplesize 10 returnstr too small break case samplesize 11 samplesize 50 returnstr appropriate break case samplesize 50 returnstr too big break return returnstr,['objective-c'] +216700,what exactly is a byte and what does it have to do with binary i am just learning about binary and bytes i understand that 8 bits make up a byte and that a byte can have 256 possibilities the thing i am confused about is thisbyte b new byte 85 85 67 75 what does 85 or any of the numbers above have to do with binary there is simply something not fully clicking in my mind,['c#'] +216701,clearing inlineblocks i havecenteredholder marginleft auto marginright auto clear left thisplay inlineblockthen div classcenteredholdermisc content 1divdiv classcenteredholdermisc content 2divdiv classcenteredholdermisc content 3divi only want one max per line is this actually possible somehow it is an iphone html5 app so older browser restrictions are not an issue,"['html', 'css']" +216719,hide a layout after 10 seconds in android i have a layout thisplayed on a button clicki want to hide that layout after 10 secondsprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestatemvolhandler new handler mvolrunnable new runnable public void run mvollayoutsetvisibilityviewgone private ontouchlistener mvolplusontouchlistener new ontouchlistener override public boolean ontouchview v motionevent event mvollayoutsetvisibilityviewvisible mvolhandlerpostdelayedmvolrunnable 10,['android'] +216730,capybara with js true causes test to fail i am new to capybara and testing on rails in general so please forgive me if this is a simple answeri have got this testit should be able to edit an assignment do visit dashboard path selectprojectclient projectname from assignment project id selectteam memberfirst name team memberlast name from assignment person id click button create assignment pageshould have contentteam memberfirst nameendit passes as is but if i add js true it fails withcannot select option no option with text test client test project in select box assignment project idi am using factorygirl to create the data and as the test passes without js i know that part is working i have tried with the default js driver and with the webkit driver with capybarawebkit installedi guess i do not understand enough what turning on js for capybara is doingwhy would the test fail with js on,['javascript'] +216771,is there a way to set drawables alpha using xml easy like itself i wanna make an alpha button which would have a selected drawable this wayxml version10 encodingutf8selector xmlnsandroid playpause item androidstate selectedfalse androiddrawabledrawableitem item androidstate selectedtrue androiddrawabledrawableitem selectori would wanna make something like thisxml version10 encodingutf8selector xmlnsandroid playpause item androidalpha125 androidstate selectedfalse androiddrawabledrawableitem item androidalpha255 androidstate selectedtrue androiddrawabledrawableitem selectorthanks for all,['android'] +216780,ios android designing app allnative or phonegap in the company i work for i am part of a team which will have to focus on mobile apps development ios and androidwe are committed to realize our first commercial app for both ios and android and since the first meetings the team is thiscussing about which is the better development approach for it if the native languages and development environments for the targeting platforms or html5 through phonegapwe already know about the technical differences between the two worlds but one aspect we are debating on is about the appearancealso please notice that the only networking features the app will have are related to http requestsin fact the app were talking about is required to have a quite customized ui with particular button and listview appearance for instance to be more precise were not only talking about colors but also circular buttonsthis kind of canvas lets some of us to think that html5phonegap could be a faster and more flexible solution due to the obvious design power you have on your hands paired with development speed and targeting 2 apps with 1 code basewould someone suggest which approach between allnative and html5phonegap could be preferable when a customized appearance is required,"['android', 'ios']" +216784,sql query execution with single quotation mark value i have a simple problem with sql query executioni know the reason but do not know how to get rid of iti am using mysql database suppose i have a table named companies and the companies table has two columns named name and addressi need to execute sql query in rails in the following waymy name my company namemy address abcquery insert into companies nameaddress values my namemy addressactiverecordbaseconnectionexecutequeryby running the above code the new data inserted into the table successfullybut if i change my name value from my company name to johns company i will get errormysql2error you have an error in your sql syntaxi know the reasonwhich is because of the single quotation mark in my name value which yield the query to beinsert into companies nameaddress values johns companyabcyou see the johns company part which have 3 single quotation mark and it cause the sql syntax errorhow to get rid of this error if i have a single quotation mark in my value and i have already used double quotation mark for the query string definition i mean i have already used query,"['sql', 'ruby-on-rails']" +216795,android can somebody please explain what is activitycontextintent in android android can somebody please explain what is activitycontextintent in androidi read android documentation but could not understand these conceptsthanking you in advance,['android'] +216796,ie9 hangs local flask instance a web app i am working on works fine under firefox and ie8 from virtual box but when i try to load it with ie9 it tries to load the page but after a while stops loading then i try to load the same url with firefox again and it does not load at all then i restart flask and the same happens i can work normally with the app through ff but not ie9looks like a kind of a bug does not ithere is the exception python throwsexception happened during processing of request from 127001 6924traceback most recent call last file cpython27libsocketserverpy line 284 in handle request noblock selfprocess requestrequest client address file cpython27libsocketserverpy line 310 in process request selffinish requestrequest client address file cpython27libsocketserverpy line 323 in finish request selfrequesthandlerclassrequest client address self file cpython27libsocketserverpy line 639 in init selfhandle file cuserscosmoappdataroamingpythonpython27sitepackageswerkzeugservingpy line 189 in handle return rvunboundlocalerror local variable rv referenced before assignmenti have uploaded code to my hosting and it works fine therei think the issue from this thread is similar to my one,['python'] +216801,how to find nth parent of an element using jquery i want to find the nth parent element of an given element and access the attributes of parentdiv idparent1br div idparent2br spanp idelement1testpspanbr divbr div idparent3br spanp idelement2testpspanbr divbrdivi want to access the 3rd parent element of element1 without using element1parentparentparentany help would be appreciated,['jquery'] +216803,how to override equals method in java i am trying to override equals method in java i have a class people which basically has 2 data fields name and age now i want to override equals method so that i can check between 2 people objects my code is as followspublic boolean equalspeople other boolean result ifother null getclass othergetclass result false end if else people otherpeople peopleother result nameequalsothername ageequalsotherage end else return result end equalsbut when i write ageequalsotherage it gives me error as equals method can only compare string and age is integer please help me fix this thanks is advancei used operator as suggested and my problem is solved thanks a lot everyon for putting an effort to help me,['java'] +216804,does anyone know of code that wraps joptionpane using the builder pattern good ol joptionpane contains a plethora of static methods there are many combinations yet to change certain options like buttons you still must specify other optional arguments often defaults like a null icon this does not lead to easy to read codemoreover the methods are not particularly consistent does an int return correspond to a option constant or a button index so it requires a slew of documentation to thisambiguate it is not quick easy to learn remember or writeit would seem natural to me to create a builder wrapper it might look something like thisstring buttontext looks good it sucks object selection new optionpanebuilderwhat do you think question messagemessagecomponent resizabletrue showoptiondialogparent buttontextreturn buttontext0equalsselectionthe final method call could be returns int or enumshowconfirmdialogparent joptionpaneyes no cancel option returns joptionpanebuild etc i am happy to go write it but my failure to find anything existing makes me wonder am i crazy it is a bad idea there are better ways or just inept at using google so does anyone know of anything that achieves something like thismy feeling is to stick with joptionpane dialogs so that the ui delegates gets things like fonts and system icons correct for any look and feel but i guess if alternatives succeed at this they would be fine too,['java'] +216833,how to act differently on first iteration in a ruby loop i always use a counter to check for the first item i0 in a loopi 0my arrayeach do item if i0 do something with the first item end common stuff i 1endis there a more elegant way to do this perhaps a method,['ruby'] +216848,html table with width 100 does not work with long text i have the following structuretable cellspacing0 cellpadding0 width100tr td stylewidth60px td td div stylewidth100overflowxhidden problems are here div tdtrtablethe first td takes 60px the second one takes the rest of the 100 but when i have some long text with no spaces and no dashes the table becomes larger then the 100how to thisplay the nonbreakable text in one line or on multiple lines both ways are acceptable and keep the table on 100 of the screeni have tried to fix this with overflowhidden but it has no effectheres a screenshot of the problemlink,"['html', 'css']" +216862,cakephp selective ssl how do i force https for certain parts of a site eg a login page or register page and use http for the rest of the site,['php'] +216863,difference between dropdownlist or dropdownlistfor html helper it seems weird that i could not find an explanation of the difference between those two helpers so i would assume that is something obvious but i missedbasically i am trying to decide which one i should use for my case with the following simple modelpublic class booking public int id get set public room room get set public datetime starttime get set public datetime endtime get set public icollectionequipment equipments get set public string who get set and i want thisplay a simple room dropdownlist for adding and editing booking recordafter doing a lots of google around it seems that i probably need a dropdopwlistfor but not sure why and how,['asp.net'] +216879,why are not typedefs strongly typed whats the reason for typedefs not being strongly typed is there any benefit i cannot see or is it due to backward compatibility see this exampletypedef int velocityvoid foovelocity v do anythingint main int i4 fooi should result in compile error if strongly typed return 0i am not asking for workarounds to get a strong typed datatype but only want to know why the standard is not requiring typedefs to be strongly typedthank you,['c'] +216902,probability in java i was curious to know how do i implement probability in java for example if the chances of a variable showing is 125 then how would i implement that or any other probability please point me in the general direction,['java'] +216935,is there an insertion order preserving set that also implements list i am trying to find an implementation of javautillist and javautilset at the same time in java i want this class to allow only unique elements as set and preserve their order like list does it exist in jdk 6it is important to have listtaddint t so i can insert into a specific position,['java'] +216957,strange behavior using braces in java when i run the following codepublic class test test systemoutprintln1 systemoutprintln2 static systemoutprintln3 public static void mainstring args new test i expect to get the output in this order123but what i got is in reverse order321can anyone explain why it is output in reverse orderalso when i create more than one instance of testnew testnew testnew testnew teststatic block is executed only at first time,['java'] +216961,using boosttuple in tr1hash i want to define stdtr1hashboosttupleabc but i get an error that does not appear when i give a complete instantation heres the codenamespace stdnamespace tr1templatetypename a typename b typename cstruct hashboosttupleabc size t operatorconst boosttupleabc t const size t seed 0 boosthash combineseed tget0 boosthash combineseed tget1 boosthash combineseed tget2 return seed templatestruct hashboosttupleintintint size t operatorconst boosttupleintintint t const size t seed 0 boosthash combineseed tget0 boosthash combineseed tget1 boosthash combineseed tget2 return seed the first piece gives this errorunorderedhpp in member function size t stdtr1hashboosttuplestuplea b c boosttuplesnull type boosttuplesnull type boosttuplesnull type boosttuplesnull type boosttuplesnull type boosttuplesnull type boosttuplesnull type operatorconst boosttuplestuplea b c boosttuplesnull type boosttuplesnull type boosttuplesnull type boosttuplesnull type boosttuplesnull type boosttuplesnull type boosttuplesnull type constunorderedhpp12 error expected primaryexpression before tokenunorderedhpp13 error expected primaryexpression before tokenunorderedhpp14 error expected primaryexpression before tokenand the second compiles just fine whats wrong with the first template i am using gcc 434,['c++'] +217007,how to expose the text property of a usercontrol possible duplicatetext property in a usercontrol in c how do i mark the text property of a usercontrol as browsablea net usercontrol class has a text propertyunfortunately the text property of a usercontrol is not browsable returns the text associated with this controlbindablefalseeditorbrowsableeditorbrowsablestateneverbrowsablefalsedesignerserializationvisibilitydesignerserializationvisibilityhiddenpublic override string text get set in my usercontrol i want to expose the text property ie make it browsable in the properties window i tried blindly declaring it browsablebrowsabletruepublic override string text get set and now it appears in the properties window except now it does nothingi tried blindly calling basetext to bring back the functionalitybrowsabletruepublic override string text get return basetext set basetext value thisinvalidate and now the property does function at designtime but the property value is not persisted to the formdesignercs and it is initalizecomponent codewhat is the proper way to expose the usercontrol text property so that it is browsable in the properties windowis functionalis persisted in the form designerand as a bonusknow when it changes,['c#'] +217015,how to make link not change color after visited i have this cssavisited textdecoration none decoration none after a link is visited it changes color it is happening to the browse all problems link on the bottom of the right side of this page thanks,"['html', 'css']" +217059,androidsupportv4 error generated with rjava being erased ok steps im following1create new project from existing source2select androidandroidsdkextrasandroidcompatibilityv4samplessupport4demos3finishso my beautiful eclipse creates the project but he erase the rjava class from gen so i get errors from every class of the package i thing also stylexml give me some errorthis is killing me because i can learn nothing from this for 3 days and i my friend google is not helping with this thx in advance,['android'] +217063,get mouse wheel events in jquery is there a way to get the mouse wheel events not talking about scroll events in jquery,"['javascript', 'jquery']" +217074,using ruby on rails link to to link to controller action i would just started toying around with ruby on rails and had come across an issue with linking to another action in a controller from a particular view i am almost certain it is an issue or lack of code in my routesrb file but i think i am misunderstanding exactly how this file works what i have to do i have got a solution but pretty sure it is not the best way to do iti have one controller called home with two actions index which is the default and newbill inside indexhtmlerb i haveh1home viewh1 link to new controller home action newbill however i was getting a routing errorno route matches controllerhome actionnewbilldoing rake routes gives me the followingroot controllerhome actionindexi then following some googling added this code to routesrbmatch homenewbill homenewbill as newbilland then in my indexhtmlerb i have got this link to name newbill path and now this works as expected my questions however arewhy does this work what exactly is going on behind the scenes surely this is not the best way to do it adding another match homenewbill for every controller action i want to link to seems a rubbish way of doing thingsi really like ruby but struggling a bit with this aspect of railsrouting in general is messing up my head a bit i thinkany help is much appreciated dthanks jack,"['ruby-on-rails', 'ruby']" +217075,use javascript to find parameter in url and then apply if then logic i am trying to make my page perform an action only if it sees that a particular parameter is present in the urli essentially want the javascript code to do thisconsider an example page such as if a page loads that contains the parameter track within the url print track exists else if the track paramater does not exist print track does not existthanks in advance for your help,"['javascript', 'jquery']" +217080,how to pass multiple expressions to orderby for ef i am using ef 42 but i expect this would apply to ef 4 and 41 as welli would like to pass an iqueryablet and multiple expressionfunctsource tkey to a method and have the method apply orderby and thenby to the iqueryablet as appropriatei found this answer and wrote the method below based on thatpublic iqueryableuser applyorderbyiqueryableuser query ienumerableexpressionfuncuser icomparable orderby if orderby null return query iorderedqueryableuser output null foreachvar expression in orderby if output null output queryorderbyexpression else output outputthenbyexpression return output querythis works fine as long as the properties i order by are strings but when i try to order by an int property i get an exceptionunable to cast the type systemint32 to type systemicomparable linq to entities only supports casting entity data model primitive typesany suggestions to work around this or for a different approach altogether i considered passing in an ienumerableexpression but then would need to figure out how to cast back to the specific type eg expressionfuncuser int to call orderby,['c#'] +217081,does objectivec support generics i wonder whether objectivec offers any support for genericsfor instance consider a methodvoid sort nsmutablearray deck is there any way for me to make it only deal with deck of cardsis something like this possible to enforcevoid sort nsmutablearray card deck,['objective-c'] +217093,detect a paste event in a contenteditable given a content editable div how can i detect a paste event prevent the paste from being inserted so can i can intercept and sanitize the paste to include text onlyi also do not want to lose focus after the paste sanitize is completeideas thanks,"['javascript', 'jquery', 'html']" +217098,may stdvector make use of small buffer optimization i was wondering with my colleague today whether stdvector can be implemented to make use of small buffer optimization by looking into the c11 draft i read at 2331p8 the expression aswapb for containers a and b of a standard container type other than array shall exchange the values of a and b without invoking any move copy or swap operations on the individual container elements that at first seems to outlaw small buffer optimization but under the asif rule we would be allowed to still do small buffer optimization for nonclass types since we cannot observe the copy being done the next text appears to be harder to foolevery iterator referring to an element in one container before the swap shall refer to the same element in the other container after the swap is this sufficient to prevent implementing the small buffer optimization for stdvector are there any other roadblocks or is it eventually possible to have a stdvector with sbo,['c++'] +217099,ios make segue wait for login success i am designing an ios app using xcode 42s storyboard feature the app has a login screen that takes a username and password and has a button to log in pushing the login button triggers a push seque to another view controller however i want the seque to wait until the login comes back successful before proceeding to the next view controlleri know about prepareforseguesender but heres my issue the login call is asynchronous i therefore cannot perform the login thereis there someway around this can i create a seque in the storyboard that is only triggered when i want it to be as opposed to when a button is clicked,['ios'] +217108,svg animate paths d attribute is it possible to use svg to animate the d attribute of pathi can draw both a diamond and a circle as a path made of eight bezier curveshtml head script srcscript script jqueryfunction var a 50 var draw functionb c d e f return m a 0 c b c d e f f c e d c b 0 a c c b e d f f c d e b c a 0 c b c d e f f c e d c b 0 a c c b e d f f c d e b c a 0 join diamondattr d draw 5a6 a6 2a3 a3 a2 circle attr d draw a amathpi12 2 1mathsqrt2a3 amathpi6 amathsqrt2 script head body svg width200 height200 g transformtranslate100100 path iddiamond fillblue strokeblack g svg svg width200 height200 g transformtranslate100100 path idcircle fillred strokeblack g bodyhtmli would like to animate the transformation from one to the otheri could simulate this in javascript just by linearly interpolating the bezier curve parameters at certain times but i want to know if there is a way to do it with svgthe circle and diamond are just an example in reality i would like to transition between two arbitrary solids made of the same number of bezier curves,['javascript'] +217112,why is an empty function call in python around 15 slower for dynamically compiled python code this is pretty bad microoptimizing but i am just curious it usually does not make a difference in the real worldso i am compiling a function that does nothing using compile then calling exec on that code and getting a reference to the function i compiled then i am executing it a couple million times and timing it then repeating it with a local function why is the dynamically compiled function around 15 slower on python 272 for just the callimport datetimedef getcompiledfunc cc compiledef aapass string exec dd exec cc in dd return ddgetaacompiledfunc getcompiledfunc def localfuncpassdef testcallf st datetimedatetimenow for x in xrange10 f et datetimedatetimenow return etsttotal secondsfor x in xrange10 lt testcalocalfunc ct testcallcompiledfunc print s s s slower lt ct int10ctltltthe output i am getting is something like1139 1319 15 slower,['python'] +217121,video encoding using avassetwriter crashes i have a function that is supposed to reencode a video to a manageable bitrate on iphoneipad here it is updated working code now with audio voidresizevideonsstringpathy nsstring newname pathy stringbyappendingstringdownmov nsurl fullpath nsurl fileurlwithpathnewname nsurl path nsurl fileurlwithpathpathy nslogwrite started nserror error nil avassetwriter videowriter avassetwriter alloc initwithurlfullpath filetypeavfiletypequicktimemovie errorerror nsparameterassertvideowriter avasset avasset avurlasset alloc initwithurlpath optionsnil autorelease nsdictionary videosettings nsdictionary dictionarywithobjectsandkeys avvideocodech264 avvideocodeckey nsnumber numberwithint1280 avvideowidthkey nsnumber numberwithint720 avvideoheightkey nil avassetwriterinput videowriterinput avassetwriterinput assetwriterinputwithmediatypeavmediatypevideo outputsettingsvideosettings retain nsparameterassertvideowriterinput nsparameterassertvideowriter canaddinputvideowriterinput videowriterinputexpectsmediadatainrealtime yes videowriter addinputvideowriterinput nserror aerror nil avassetreader reader avassetreader alloc initwithassetavasset erroraerror avassettrack videotrack avasset trackswithmediatypeavmediatypevideoobjectatindex0 videowriterinputtransform videotrackpreferredtransform nsdictionary videooptions nsdictionary dictionarywithobjectnsnumber numberwithintkcvpixelformattype 420ypcbcr8biplanarvideorange forkeyidkcvpixelbufferpixelformattypekey avassetreadertrackoutput asset reader output avassetreadertrackoutput alloc initwithtrackvideotrack outputsettingsvideooptions reader addoutputasset reader output audio setup avassetwriterinput audiowriterinput avassetwriterinput assetwriterinputwithmediatypeavmediatypeaudio outputsettingsnil retain avassetreader audioreader avassetreader assetreaderwithassetavasset errorerror retain avassettrack audiotrack avasset trackswithmediatypeavmediatypeaudio objectatindex0 avassetreaderoutput readeroutput avassetreadertrackoutput assetreadertrackoutputwithtrackaudiotrack outputsettingsnil audioreader addoutputreaderoutput nsparameterassertaudiowriterinput nsparameterassertvideowriter canaddinputaudiowriterinput audiowriterinputexpectsmediadatainrealtime no videowriter addinputaudiowriterinput videowriter startwriting videowriter startsessionatsourcetimekcmtimezero reader startreading thispatch queue t processingqueue thispatch queue createassetaudiowriterqueue null videowriterinput requestmediadatawhenreadyonqueue processingqueue usingblock self retain while videowriterinput isreadyformoremediadata cmsamplebufferref samplebuffer if reader status avassetreaderstatusreading samplebuffer asset reader output copynextsamplebuffer bool result videowriterinput appendsamplebuffersamplebuffer cfreleasesamplebuffer if result reader cancelreading break else videowriterinput markasfinished switch reader status case avassetreaderstatusreading the reader has more for other tracks even if this one is done break case avassetreaderstatuscompleted your method for when the conversion is done should call finishwriting on the writer hook up audio track audioreader startreading videowriter startsessionatsourcetimekcmtimezero thispatch queue t mediainputqueue thispatch queue createmediainputqueue null audiowriterinput requestmediadatawhenreadyonqueuemediainputqueue usingblock nslogrequest nslogasset writer ready daudiowriterinputreadyformoremediadata while audiowriterinputreadyformoremediadata cmsamplebufferref nextbuffer if audioreader status avassetreaderstatusreading nextbuffer readeroutput copynextsamplebuffer nslogready if nextbuffer nslognextbuffer audiowriterinput appendsamplebuffernextbuffer else audiowriterinput markasfinished switch audioreader status case avassetreaderstatuscompleted videowriter finishwriting self hookupvideonewname break break case avassetreaderstatusfailed videowriter cancelwriting break break nslogwrite endedunfortunately if i pass in a video any longer than 2 seconds the app sucks up memory like crazy and crashes the code seems fairly simple but i cannot seem to get it to workam i supposed to release the buffer in there somewhere after it is written i would be most greatful to anyone that has any input,"['iphone', 'objective-c']" +217142,uitapgesturerecognizer breaks uitableview didselectrowatindexpath i have written my own function to scroll text fields up when the keyboard shows up in order to thismiss the keyboard by tapping away from the text field i have created a uitapgesturerecognizer that takes care of resigning first responder on the text field when tapping awaynow i have also created an autocomplete for the textfield that creates a uitableview just below the text field and populates it with items as the user enters texthowever when selecting one of the entries in the auto completed table didselectrowatindexpath does not get called instead it seems that the tap gesture recognizer is getting called and just resigns first responderi am guessing there is some way to tell the tap gesture recognizer to keep passing the tap message on down to the uitableview but i cannot figure out what it is any help would be very appreciated,['ios'] +217144,any difference between datetimeparse and converttodatetime is there any difference betweenconverttodatetimeanddatetimeparsewhich one is faster or which is more secure to use,"['c#', 'asp.net']" +217145,use of list inside map c can i use following syntax stdmapintstdlistint malldatawhere key valueint will be id of data and said data could have multiple types so storing all them against said key value i am trying to use it,['c++'] +217192,converting a bufferedimage to another type the most convenient method to read an image from a source files inputstreams urls isbufferedimage myimage imageioread source but then how to convert myimage to a bufferedimagetype ushort 565 rgb format,['java'] +217222,why is this min template of cppnext at fault i was reading cppnext where this min template is presented as an example of how verbose c code can be compared to python codetemplate class t class uauto mint x you ydecltypex y x y return x y x y at first this looks innocent but daveed vandevoorde made this remarkthe min template that uses decltype in its return type specification doesnat work it returns a reference because the argument is an lvalue that ends up referring to a local variable in most common usesi figured it may not be clear to everyone how the problem manifests can you please give a detailed explanation and possible fixes,['c++'] +217237,best strongest method of encryption for databases i am storing paswords and personal data in a database what is the strongest method for encrypting these values for protectionalso what is the best method for encryption for credit card info in a database or should i use something else to store credit card info not a mysql databasethanks,['mysql'] +217239,confused about resources and getmanifestresourcenames i have been learning about resources in c and the visual c ide i am confused now i have read some pages on stackoverflow like this one howtogetthepathofanembebbedresource and the documentation of microsoft but it confused memy first question what are resources is it the resources file or is it the files that are inside it like iconssecond when i use the getmanifestresourcenames method do i get the resources files names or the the names of the files inside it when i use it in my program i only get the resources files but reading topics like this loopthroughalltheresourcesinaresxfile i get the impression i should get the names of the files inside the resources fileis it me or is this terminology really a bit confusing can anyone make it a little clearer thanks for all help,['c#'] +217248,create a flask public url decorator i would like to create a decorator for flask routes to flag certain routes as public so i can do things like thispublicapproutewelcomedef welcome return render templatewelcomehtmlelsewhere heres what i was thinking the decorator and check would look like public urls setdef publicroute function add route functions url to public urls public urlsaddroute function url rule def decoratorf return fdef requested url is public from flask import request return requesturl rule in public urlsthen when a request is made i have a context function that checks requested url is publici am a bit stumped because i do not know how to get the url rule for a given function in the public decoratorperhaps this is not the best design choice for flask but i would expect there is another simple elegant way to achieve this i have seen this patterns like this before and would like to mimic it for example this is something of a counterpart to djangos login required decoratori would enjoy reading thoughts on this,['python'] +217260,how to use gimp inside a python script gimp enables you to make plugin in in python what i would like to do is to call gimp function like i would do inside one of this plugin but this return the following error since gimp does not find any running gimp core to uselibgimpbaseerror gimp wire write msg the wire protocol has not been initialized abortingi would like to know if it is possible and if yes how thanks,['python'] +217261,setting innerhtml why would not it update the dom wondering why i cannot get documentgetelementbyidmy divinnerhtml to update the dom when i reassign the variable for examplediv idmy div onclickclicky byedivscript typetextjavascript charsetutf8 function clicky var mydivvalue documentgetelementbyidmy divinnerhtml mydivvalue hello consolelogmydivvalue scriptin the log i can see the variable get reassigned when i click but the innerhtml of my div remains unchanged why is this,['javascript'] +217265,hibernatecfgxml not found i am new to hibernate reading this book java persistence with hibernate and i am trying to implement the example from there so far my ant build is successful but when i try to execute the class containing the main method i am getting this error message19nov2011 184009 orghibernatecfgenvironment clinitinfo hibernate 32319nov2011 184009 orghibernatecfgenvironment clinitinfo hibernateproperties not found19nov2011 184009 orghibernatecfgenvironment buildbytecodeproviderinfo bytecode provider name cglib19nov2011 184009 orghibernatecfgenvironment clinitinfo using jdk 14 javasqltimestamp handling19nov2011 184009 orghibernatecfgconfiguration configureinfo configuring from resource hibernatecfgxml19nov2011 184009 orghibernatecfgconfiguration getconfigurationinputstreaminfo configuration resource hibernatecfgxmlexception in thread main javalangexceptionininitializererror at persistencehibernateutilclinitunknown source at hellodrivermainunknown sourcecaused by orghibernatehibernateexception hibernatecfgxml not found at orghibernateutilconfighelpergetresourceasstreamconfighelperjava147 at orghibernatecfgconfigurationgetconfigurationinputstreamconfigurationjava1405 at orghibernatecfgconfigurationconfigureconfigurationjava1427 at orghibernatecfgconfigurationconfigureconfigurationjava1414 2 moreit is clear that hibernate cannot find my config file which is located in the root dirprojectliball required librariessrc hello helloworldjava messagejava messagehbmxml persistence hibernateutiljavabuildxmlhibernatecfgxmlmy the complete source code can be found here i have a running mysql server with a database hibernateapp and table messagesthanks,['java'] +217272,java vertical flowlayout with horizontal scrolling as described in the title i have been trying to set up sort of a vertical flow layout with horizontal scrolling the components within the layout will be jlabels let me draw a picture windowlabel1 label4 label7label2 label5 label8 labelslabel3 label6 label9 scrollbarsame window expanded vertically windowlabel1 label5 label9 label2 label6 label10 labelslabel3 label7 label11label4 label8 label12 scrollbarso the labels would fill the available vertical space and then create a new column once the available horizontal space is exhausted a horizontal scrollbar would appeara vertical scrollbar should not typically appear however it would be nice to have a vertical scrollbar if the vertical height of the window is unusually smallany help is greatly appreciated i am new to java so any additional explanation would be wonderful thankseditbased on the responses below i am now working with andi have the wraplayout extending verticalflowlayout as suchpackage logicsimimport javaawtimport javaxswingjscrollpaneimport javaxswingswingutilities flowlayout subclass that fully supports wrapping of components public class verticalwraplayout extends verticalflowlayoutprivate dimension preferredlayoutsize constructs a new codewraplayoutcode with a left alignment and a default 5unit horizontal and vertical gappublic verticalwraplayout super constructs a new codeflowlayoutcode with the specified alignment and a default 5unit horizontal and vertical gap the value of the alignment argument must be one of codewraplayoutcode codewraplayoutcode or codewraplayoutcode param align the alignment valuepublic verticalwraplayoutint align superalign creates a new flow layout manager with the indicated alignment and the indicated horizontal and vertical gaps p the value of the alignment argument must be one of codewraplayoutcode codewraplayoutcode or codewraplayoutcode param align the alignment value param hgap the horizontal gap between components param vgap the vertical gap between componentspublic verticalwraplayoutint align int hgap int vgap superalign hgap vgap returns the preferred dimensions for this layout given the ivisiblei components in the specified target container param target the component which needs to be laid out return the preferred dimensions to lay out the subcomponents of the specified containeroverridepublic dimension preferredlayoutsizecontainer target return layoutsizetarget true returns the minimum dimensions needed to layout the ivisiblei components contained in the specified target container param target the component which needs to be laid out return the minimum dimensions to lay out the subcomponents of the specified containeroverridepublic dimension minimumlayoutsizecontainer target dimension minimum layoutsizetarget false minimumwidth gethgap 1 return minimum returns the minimum or preferred dimension needed to layout the target container param target target to get layout size for param preferred should preferred size be calculated return the dimension to layout the target containerprivate dimension layoutsizecontainer target boolean preferred synchronized targetgettreelock each row must fit with the width allocated to the containter when the container width 0 the preferred width of the container has not yet been calculated so lets ask for the maximum int targetwidth targetgetsizewidth if targetwidth 0 targetwidth integermax value int hgap gethgap int vgap getvgap insets insets targetgetinsets int horizontalinsetsandgap insetsleft insetsright hgap 2 int maxwidth targetwidth horizontalinsetsandgap fit components into the allowed width dimension dim new dimension0 0 int rowwidth 0 int rowheight 0 int nmembers targetgetcomponentcount for int i 0 i nmembers i component m targetgetcomponenti if misvisible dimension d preferred mgetpreferredsize mgetminimumsize cannot add the component to current row start a new row if rowwidth dwidth maxwidth addrowdim rowwidth rowheight rowwidth 0 rowheight 0 add a horizontal gap for all components after the first if rowwidth 0 rowwidth hgap rowwidth dwidth rowheight mathmaxrowheight dheight addrowdim rowwidth rowheight dimwidth horizontalinsetsandgap dimheight insetstop insetsbottom vgap 2 when using a scroll pane or the decoratedlookandfeel we need to make sure the preferred size is less than the size of the target containter so shrinking the container size works correctly removing the horizontal gap is an easy way to do this container scrollpane swingutilitiesgetancestorofclassjscrollpaneclass target if scrollpane null dimwidth hgap 1 return dim a new row has been completed use the dimensions of this row to update the preferred size for the container param dim update the width and height when appropriate param rowwidth the width of the row to add param rowheight the height of the row to add private void addrowdimension dim int rowwidth int rowheight dimwidth mathmaxdimwidth rowwidth if dimheight 0 dimheight getvgap dimheight rowheighthere is my frame setup jframe frame new jframe framesetdefaultcloseoperationjframeexit on close framesetsize300 300 framesetvisibletrue jpanel panel new jpanel panelsetlayout new verticalwraplayout0 jscrollpane pane new jscrollpanepanel frameadd pane borderlayoutcenter for int i0 i 80 i paneladd new jlabel label i now this sets up the labels in vertical columns in the way that i am after but it still creates the vertical scroll bar i am pretty shaky when it comes to modifying the verticalwraplayout class also i really do not understand how the jscrollpane interacts will these classes any suggestions on how to proceedsolved please see the answers below as well as my answer,['java'] +217281,write unicode string in a file using streamwriter does not work i have this codestring s streamwriter writer new streamwriteratxt false encodingutf8writerwritelinesbut when i run it i cannot see any in atxt there is not any string in atxt it is empty what is problem can anyone help me,"['c#', '.net']" +217283,linker error when using qt and boost when i am using qt v474 and boost tried v147 and v148 together in my c project i get a linker error caused by a class that includes boostfilesystemhpp i just set up qt and before the code was working without any problems this is error message obj error lnk2001 unresolved external symbol private static class stdcodecvt const cdecl boostfilesystem3pathwchar t codecvt facetvoid wchar t codecvt facetpathfilesystem3boostcapbvcodecvtgdhstdxzobj error lnk2001 unresolved external symbol void cdecl boostfilesystem3path traitsconvertchar const char const class stdbasic stringclass stdallocator class stdcodecvt const convertpath traitsfilesystem3boostyaxpbd0aavbasic stringguchar traitsgstdvallocatorg2stdabvcodecvtgdh5zobj error lnk2001 unresolved external symbol void cdecl boostfilesystem3path traitsthispatchclass boostfilesystem3directory entry const class stdbasic stringclass stdallocator class stdcodecvt const thispatchpath traitsfilesystem3boostyaxabvdirectory entry23aavbasic stringguchar traitsgstdvallocatorg2stdabvcodecvtgdh6zobj error lnk2001 unresolved external symbol void cdecl boostfilesystem3path traitsconvertunsigned short const unsigned short const class stdbasic stringclass stdallocator class stdcodecvt const convertpath traitsfilesystem3boostyaxpbg0aavbasic stringduchar traitsdstdvallocatord2stdabvcodecvtgdh5zexe fatal error lnk1120 4 unresolved externalsedithere i found someone having this problem coming to this conclusion this really is a qt issue using wchar t as a native type you have to recompile qt using the same compiler switch there even is a bug in the tracker in general you will have to be very careful and do not mix wchar t compiler settings in your projects as they will become incompatibleso i recompiled qt setting zcwchar t but it did not show any effect i still get the same error,['c++'] +217284,php custom postcard i am creating a new feature on my site that allow people to send postcard to friends in this section they can choose the image they want to send they already uplaoded the image to their profile my pictures sectioni am using the php function to create the text that goes on the right but how can i add another image to this image with the texti use imagettftext to create the text imagecreatefromjpeg to open the main image see below and imagedestroy when im donethanksi am using this postcard,['php'] +217325,iterable property i have a library djangopiston which is expecting some parameters of the class as class properties i would like to define this value dynamically in a method so i wanted to do something likeclass myhandlerbasehandler property def fieldsself fields selfmodel metafields selfmodel metavirtual fields do something more with fields return fieldsbut it fails withproperty object is not iterableso i wanted to do something likeclass iterable propertyproperty def iter self what herebut i got stuck here how could i get a property which can also be iterated over,['python'] +217328,roll back all rails migrations or drop tables and modify migrations start from scratch i am new to rails and have started a project that i am unhappy with my models and db schemai would like to start again from scratch but keep all my views controllerswhats the best way to go about doing thisi want to remove all my migrations and all my models there should be no irrelevant files left after this process like migrations that are no longer in useif it helps i am using rails 31thanks,"['ruby-on-rails', 'ruby']" +217331,check if page tab app is still installed what is the best way to check if a tab app is still installed on a specific fan page using the graph api the only way i can come up with is using idtabsapp id and this will return the data for the given tab if it is installed but it appears a access token is required to use this method i think i would need to ask the user for not only the manage pages permissions but also for the offline access then i could store the page access token and be able to use it later for sole purpose of checking if the app has been removed it seems odd that this wouldnt just be public information considering without being logged into facebook you can see all the tabs installed on a fan pagehere is a similar question asking about the deauthorize callbackdeauthorize page tab notificationthanks,['php'] +217350,unit test an android fragment i want to unit test an android fragment classcan i set up a test using androidtestcase or do i need to use applicationtestcaseare there any useful examples of how these two testcases can be used the testing examples on the developer site are minimal and just seem to focus on testing activitiesall i have found elsewhere are examples where the androidtestcase class is extended but then all that is tested is adding two numbers together or if the context is used it just does a simple get and tests that something is not nullas i understand it a fragment has to live within an activity so could i create a mock activity or get the application or context to provide an activity within which i can test my fragmentdo i need to create my own activity and then use activityunittestcasethanks for your assistancetrev,['android'] +217373,c directed graph generating library i noticed that visual studio can generate graphs using something called dgmli would like to generate a graph like the following one in my c applicationit does not have to be interactive like the vs i just want to generate a static such image and save it as a general graphics file such as pngis there any free net library for this,['c#'] +217375,do build warnings affect the ios app store approval process when an app is undergoing the app store approval process do the people at apple check the warnings in your project or do they only check for errorseg i have this warning on a lot of my nib filesunsupported configuration title set but using a system identifier these attributes are mutually exclusive the title will be ignoredwill this be a reason for apple to reject my app for the app store,['iphone'] +217378,how to get the browser language using javascript possible duplicatejavascript for detecting browser language preference i want to detect the language of the browser that is entering my site is it en or frso i can redirect to the en page or the other pageand can i detect mobile language also,['javascript'] +217425,serving files with pyramid i am serving quite large files from a pyramid application i have writtenmy only problem is download managers do not want to play nicei cannot get resume downloading or segmenting to work with download manager like downthemallsize ospathgetsizepath dfileresponse responsecontent typeapplicationforcedownload content thispositionattachment filename dfileresponseapp iter openpath dfile rbresponsecontent length sizei think the problem may lie with pastehttpserver but i am not sure,['python'] +217429,create unique doubles and triplets from collection i have a collection list of items string number of items in this collection will always be between 0 to 9i need to create all combinations of pairs and triples from this collectionposition of item in double or triplet does not matter so 12 is equal to 21how can i achieve this maybe there is some nice way to do this via linq,"['c#', '.net']" +217444,how to macports select python when i enter port select list pythonthis is the resultavailable versions for python none python25 active python25apple python26apple python27 python27applei thought when i use python i would be using version 25 instead when i enter python version 27 seems to be active how do i change that to version 25python 271 r27186832 jun 16 2011 165905 gcc 421 based on apple inc build 5658 llvm build 23351500 on darwintype help copyright credits or license for more information,['python'] +217473,mmap and locking files consider the following snippet error handling missing on purposevoid fooconst char path off t size int fd void ret fd openpath o rdwr lockffd f lock 0 ret mmapnull size prot readprot write map shared fd 0 closefd return retso the idea is to open a file mmap it and return just the data pointer it would be great if the file could be locked for mmaptime tooper mmap3pthe mmap function shall add an extra reference to the file associated with the file descriptor fildes which is not removed by a subsequent close on that file descriptor this reference shall be removed when there are no more mappings to the filebut per lockf3pfile locks shall be released on first close by the locking process of any file descriptor for the fileso using lockf i would have to keep the fd open and carry its reference for an awfully long time is there a better portable method to ensure the file is locked till munmap is called,['c'] +217480,directory listener in c is there any library for listening a directory i mean i have a directory and i want to be informed of any changes in itfor example when some files are deleted or created in the directory i want to be informed i do not want to use a timer and check the directory manually to detect any changes,['c#'] +217487,boostpython and seterase weird behaviour i am trying to store objects in a stdset those objects are boostshared ptr coming from the python environment adding values to the set would not cause any troubles but when i try to erase a value even though i am passing the very same reference it would not work here is an example include setinclude iostreaminclude boostshared ptrhppinclude boostpythonhppusing namespace stdusing namespace boostusing namespace boostpythonstruct bar bar struct foo set shared ptrbar v set shared ptrbar v ptr foo void add shared ptrbar v param cout storing v param in v set and v ptr endl v setinsertv param v ptr v param void del shared ptrbar v param cout deleting v param endl if v param v ptr cout v param v ptr endl else cout v param v ptr endl cout erasing from v set using v param endl if v seterasev param 0 cout did not erase anything endl else cout erased endl cout erasing from v set using v ptr endl if v seterasev ptr 0 cout did not erase anything endl else cout erased endl boost python module test class foo shared ptrfoo foo defaddfooadd defremovefoodel class bar shared ptrbar bar compiling gcc pthread fnostrictaliasing marchi686 mtunegeneric o2 pipe dndebug marchi686 mtunegeneric o2 pipe fpic iusrincludepython27 c testcpp o testo g pthread shared wlhashstylegnu wlasneeded buildtemplinuxi68627testo lusrlib lboost python lpython27 o testsoand now a small python script from test import f foob barfaddbfremovebhere is the result storing 0x8c8bc58in v set and v ptrdeleting 0x8c8bc58v param v ptrerasing from v set using v paramdid not erase anythingerasing from v set using v ptrerased i store 0x8e89c58 inside the set and outside just in casei am passing the same reference to both calls 0x8e89c58just to make sure i check if v vali try to erase by using v it does not worki try to erase by using val it works i am completely lost there cannot see what is causing this any input,['c++'] +217498,how can i concatenate static strings with xml string resources i am trying to combine a static hard coded string with one referenced from stringsxml for string array itemsthe goal is to have a dynamic metrics list where the number is the same for all languages but the metrics text value may change by language something like thisstringarray nameinterval labels item30 stringseconditem item1 stringminuteitem item5 stringminuteitem item10 stringminuteitem item15 stringminuteitem item30 stringminuteitem item60 stringminuteitemstringarrayright now if i remove the numbers before the string references it works well as mentioned here but i was wondering whether there is a way to retrieve the referenced string and concatenate it to the hard coded one,['android'] +217503,conversion of 2d array to pointertopointer activity solutionabactivity mother solutioni want to convert 2d array of objects to pointertopointer how can i do thisi searched it on google however i found only one dimension array example,['c++'] +217505,local classes c03 vs c11 is there any change in the usage of local class in c11it seems in c03 local classes cannot be used as template argument i recall thatconsider this codetemplatetypename t void fconst t note s is a local class defined inside mainint main struct s fs i want template argument to be deducedbut it gives compilation error c03 mode saying ideoneprogcpp4 error no matching function for call to afmainsahowever it compiles fine when compiling it in c11 mode ideone which makes sense to me otherwise lambda wouldnt work so i guess that there is at least this change in the usage of local classes am i right what are other changes concerning local classesplease quote the relevant text from the standards c03 and c11 both so readers can compare themselves and for future reference,['c++'] +217508,how to create an paypal button with overwritable variables hello i would like to create a paypal buy button which has a dynamic set amount i would like to pass the amount by a text input field within the form and the item number by a hidden field the issue is that what ever i do i get a encrypted sxclick button from the paypal website this button does not allow hidden variables being placed in the form i think what i need is a xclick button my goal is to allow users to increase their internally credit of my website edit moving the addition to the question from the answer to the questionfrom here tokamto add this to the thiscussion i would like to show my current solution for the problemhere we have some javascript validation which helps the user with the input recognize that it opens a lightbox on successfunction validatepaypalform var val paypalpaymentamountvalreplaces replace replacea var errormsg var ret amountfield if val isnan parsefloatval isfiniteval errormsg bitte geben sie einen guumlltigen betrag anelse if parsefloat val php echo thisminimum errormsg das einzahlungsminimum betraumlgt php echo thisminimumeuroret errormsg amountfield paypalamountfield if ret amountfieldremoveclass error paypalamounterrormessagehtml nbsp paypalpaymentamountval val fbstart pstrongsie werden in ka14rze zur seite von paypal weitergeleitetstrongp width700 showprintfalse modaltrue showclosefalse showouterclosetrue showitemnumberfalse closeonnewwindowfalse outsideclickclosestrue innerborder0 imageclickclosesfalse scrolling no else amountfieldaddclass error paypalamounterrormessagehtml errormsg return rethere comes my button now the issues i am having with are eg that it is easy for the user to set an other currency code i could handle this in my ipn listener by refunding the payment are there other issues which come with an unencrypted changeable buttonform onsubmitreturn validatepaypalform clastnform action methodpostfieldset idfieldsetplegendspan2spanmyproject guthaben aufladen per paypal zahlunglegenddiv idpaypalamountfield classfieldlabel forpaypalpaymentamount betrag eurolabelinput idpaypalpaymentamount typetext nameamount value span stylethisplayblock idpaypalamounterrormessage classerrortextnbspspandivinput typehidden namecmd value xclickinput typehidden namebusiness valuethe id of my clientinput typehidden namelc valuedeinput typehidden nameitem name valuemyproject advertiser vorkasseinput typehidden nameitem number value11500input typehidden namecurrency code valueeurinput typehidden namebutton subtype valueservicesinput typehidden nameno note value1input typehidden nameno shipping value1input typehidden namebn valueppbuynowbfbtn paynowcc lggifnonhostedinput typehidden namerm value1input typehidden namecbt valuezu myprojectde zuruumlckkehreninput typehidden namecurrency code valueeurinput typehidden namereturn value input typehidden namecancel return value div classactionrowinput typeimage src dedeibtnbtn paynowcc lggif border0 namesubmit altjetzt einfach schnell und sicher online bezahlen a mit paypalimg alt border0 src deiscrpixelgif width1 height1divfieldsetform,"['php', 'html']" +217511,how get yesterday and tomorrow datetime in c i have a codeint monthnow systemdatetimenowmonthint yearnow systemdatetimenowyearint daynow systemdatetimenowdayhow can i get yesterday and tomorrow day month and year in c of course i can just writedaytommorow daynow 1but it may happen that tomorrow is other month or year are there in c builtin tools to find out yesterday and today,['c#'] +217528,deserializing a simple json array with datacontractjsonserializer i am sure this question has been asked over and over again but for some reason i still cannot manage to get this to worki want to deserialize a json object that contains a single member a string arrayresults a bthis is the class that i am trying to deserialize intopublic class whatever datamembername results public string results get protected set and this is the deserialize methodprivate static t deserializetstring json var instance activatorcreateinstancet using var ms new memorystreamencodingunicodegetbytesjson var serializer new datacontractjsonserializerinstancegettype return tserializerreadobjectms a call like deserializewhateverresults a b is returning an initialized instance of whatever but the results array is staying nullis there something wrong with the structure of whatever,"['c#', '.net']" +217540,what are the changes to sun scjpscjascea tracks since oracle took over the context it appears that the simple scjp scja tracks for sun certification have been merged with other oracle style certifications as a developer i have spent some time lately trying to figure out the new pathways for certificationexisting resources there is a very dense but also informative page here certified professional the oracle website is also of course full of links and diagrams with different certification factoids my problemit is not clear that there is a new paradigm or pathway for java certifications is emerging and thus whether or not the old scjp style certifications are still in existence albeit with a different title nor is it clear what the entire certification pipeline looks like for example this diagram from the older sun certifications clearly related the myriad of certification and training initiatives in a lucid and easily interpreted diagram but i do not see any such resource for explaining and comparing the modern oracle java certificationsthe questionswhat is the relationship between the new oracle certifications and how do they relate to the original scjp scjd and scea exams,['java'] +217544,java regex email first of all i know that using regex for email is not recommended but i gotta test this outi have this regexbaz09 az09az24bin java i did thispattern p patterncompilebaz09 az09az24bmatcher m pmatcherif mfind systemoutprintlncorrecthowever the regex fails regardless of whether the email is welformed or not a find and replace inside eclipse works fine with the same regexany ideathanks,['java'] +217548,finding all children for multiple parents in single sql query suppose i have a table with parentchild relationshipsparent child1 41 52 63 74 86 97 108 11now i have a query that returns a list of people eg 1 and 2 and i want to find all their children grandchildren etc in this case 4 5 6 8 9 11 i know i can use common table expressions to search recursively but i wondered if i could create a sql statement to find all descendents at once without having to iterate over the input setedit sorry for not being clear enough i am looking for something likeselect hierarchical relation from table where parent in 12which should result in a single output column with rows for 4 5 6 8 9 11i am no longer interested in the relationship in the output just the complete set of family members for multiple families,['sql'] +217580,remove a value from an array in coffeescript i have a an arrayarray hello world again how could i check if world is in the arraythen remove it if it existsand have a reference to worldsometimes maybe i wanna match a word with a regexp and in that case i would not know the exact string so i need to have a reference to the matched string but in this case i know for sure it is world which makes it simplerthanks for the suggestions i found a cool way to do it,['javascript'] +217591,jackson equivalent for iphone i have used jackson extensively on the server side to convert from pojos to json and was wondering if there is a similar library for objective ciphone sdk and vice versa objective c does provide reflection so it should be possible to make something similar to jackson,['iphone'] +217611,object reference not set to an instance of an object i keep getting this error when i run the programobject reference not set to an instance of an object description an unhandled exception occurred during the execution of the current web request please review the stack trace for more information about the error and where it originated in the code exception details systemnullreferenceexception object reference not set to an instance of an objectsource errorline with errorline 156 if strsearch strsearchtrimlength 0what is the correct way it should be written,['c#'] +217614,do i need to call suspendlayout for every child control cannot find any information about this my controls are rendering extremely slow and i noticed i am not calling suspendlayout when doing major updates what i am in doubt is since the top level control contains controls which contain other controls and so on will calling suspendlayout on my top control also suspend layout for every nested control or do i need to call it for each of them,['c#'] +217633,how does rundll32 work how exactly does rundll32 call a function without knowing the numbertypes of arguments that the function can takedoes it have a builtin compiler or something of the sort,['c'] +217638,c how do i split a string into evenlysized smaller strings in c how do i split a string into evenlysized smaller stringfor example i have a string 012345678 and want it to split it into 5 smaller strings and this should return me something like 01 23 45 67 8 i am having trouble of determining the length of the smaller strings in the previous example the original string is size 9 and i want to split it into 5 smaller string so each smaller string except the last one should be length 9 5 1 but then the last one will be length 9 1 4 5 which is unacceptableso the formal definition of this problem the original string is split into exactly and substrings and no two of the substrings should differ by greater than 1 in length my focus is not on c syntax or library it is how to design an algorithm so that the returned string can be nearlyequal in size,['c++'] +217697,how to importinclude in closure stylesheet reading this page i cannot seem to find any documentation explaining how to include or import another gss files is this possible,['css'] +217703,how to set different frame rate for each animation in jquery i know the frame rate in jquery could be set through jqueryfxinterval however it applies to all the jquery internal animate function such as slidedown fadein and animateetci want to set frame rate for each animate how could i archieve that,['jquery'] +217717,css transitions do not work when assigned trough javascript i am having some major headache trying to apply css3 transitions to a slideshow trough javascriptbasically the javascript gets all of the slides in the slideshow and applies css classes to the correct elements to give a nice animated effect if there is no css3 transitions support it will just apply the styles without a transitionnow my little problem all works as expected all slides get the correct styles the code runs without bugs so far but the specified transitions do not work even though the correct styles where applied also styles and transitions work when i apply them myself trough the inspectorsince i could not find a logical explanation myself i thought someone here could answer it pretty pleasei have put together a little example of what the code is right now or use jsfiddle no images,"['javascript', 'css']" +217720,how to search a particular node in jtree and make that node expanded i am having a jtree with 100 nodes now i want to search particular node from that tree and make that node expandedhow can i solve this problem,['java'] +217743,xmlelement annotation thissallowed with webparam i have a method inside a webservice with the following signaturewebresultnamepurchaseid public int createpurchase xmlelementrequiredtrue webparamname item string item it seems to me based on what information i have found that this should work unfortunately i get the following error message on compilationthe annotation xmlelement is thisallowed for this locationdoes anyone know how to resolve the issue,['java'] +217755,do i need to close files i perform filegetname on i will be having lot of files in a directory i will be just getting the file names using filegetname and log them to a log file i presume i do not need to close the file since i am not doing any readwrite operation in itis this correct,['java'] +217759,servicestack rest api and cors anyone know if the servicestack framework can be used to create cors rest servicesi have been banging my haed against the wcf rest stuff for days now utterly uselessthanks,['c#'] +217765,is a django session thread safe i am storing a dictionary in a django session which is accessible by multiple threads all threads can update that dictionary threads also get values from dictionary in order to run the process i want to know does the django session is thread safe or i have to use locks or semaphorestypical examplethread1threaddict requestsessiongetthreaddict noneif threaddictstop break the for loop exit the threadelse do some processing and update some values in thread dictionary threaddictabc 0 requestsessionthreaddict threaddict point1def somefunction this function is used to send stop signal to thread threaddict requestsessiongetthreaddict none threaddictstop true requestsessionthreaddict threaddict point2does there is a chance that when point2 update thread dictionary in session just after it updates point1 also update it then my stop to quit thread is lostmore infoan ajax request start four threads which download samples from the 4 different urls why i used threads because i want to show the user which samples are currently being downloaded and which are left all threads will update its state in dictionary within session after threads started i make ajax request after every two seconds and take the dictionary from session and read the current state of threads but this idea failed because threads are independent of request and their session each ajax request definately have its session but i can not pass that session to threads because when they once begin they are independent of rest of world may be i can pass it but i may not pass it as fast the procesing is being done by the threads so to tackle this problem i choose cache framework instead of session as cache is accessable from any where threads store their state in dictionary and put back in to cache and after every two seconds i take dictionary from cache and read the state and one more thing according to my experience cache is not thread safe so for four threads i used four dictionaries sepratelly,['python'] +217805,why would a c compiler not eliminate null check of pointer returned by new recently i ran the following code on ideonecom gcc434include stddefhinclude stdiohinclude stdlibhinclude newusing namespace stdvoid operator new size t size throwstdbad alloc void ptr malloc 2 1024 1024 1024 printf pn ptr return ptrvoid operator delete void ptr free ptr int main char ptr new char if ptr 0 printf unreachablen delete ptrand got this outputnilunreachablealthough new should never return a null pointer and so the caller can count on that and the compiler could have eliminated the ptr 0 check and treat dependent code as unreachablewhy would the compiler not eliminate that code is it just a missed optimization or is there some other reason for that,['c++'] +217867,why no autoreseteventslim in bcl why is not there an autoreseteventslim class in bclcan it be simulated using manualreseteventslim,"['c#', '.net']" +217868,how to change the schema name ia m developing an aspnet mvc app that uses ef 41 code firsti have to change the default schema name dbo to another namei tried thispublic string schemanamepublic void mycontext schemaname getschemanameprotected override void onmodelcreatingdbmodelbuilder modelbuilder modelbuilderentityaccounttotabletb acc holders schemanamebut ita s not working when i get a new instance of my context and call some of my tables the generated query still with dbo schema nameanyone have some idea to solve that,['c#'] +217875,iteratively traverse through tree to find size i need to find the number of elements in a tree using an iterative algorithm but i am finding the code conceptually very difficult to writemy approach is to start at the root node and visit the child nodes then the children of these child nodes and so onthis is the code i have written which works for a small tree but is not a real solution because i would need to add an additional block for each level of depth start the counter at 1 because the root node countsint size 1foritree child1 root size foritree child2 child1 size foritree child3 child2 size foritree child4 child3 size foritree child5 child4 size return size,['java'] +217917,is set nocount off necessary in a stored procedure i have many procedures that has set nocount onis it necessary to turn it off at the end of stored procedureegcreate procedure dummyprocasbegin set nocount on set nocount offend,['sql'] +217918,every project says error after android adt update i updated to the newest android adt and now every project in my workspace says error though there is not any in the actual files even a clean android project says error even though i have double checked all the preferences and i have not found any fixes though i have investigated every possible help forum many timesi have gotten many random error messages and here are just a few current file is not a match for the given config conversion to dalvik format failed with error 1 not anymore invalid preference page path xml syntax failed to load properties file for project etcall my projects worked before updatingnone of the following workscleaning the project deleting the project and importing again deleting libraries and temporary files and fixing project properties unchecking the is library updating the progruad updating the eclipse moving eclipse to ceclipse changing api levels and supported android versions and so oni have fought with this problem for some time noweditthe following things do not work either removing libraryname src files my project has noneediti unchecked a checkbox in the general preferences which made eclipse to delay the packing i will check the name of that checkbox later and the current errors went away but now it says that could not find apk,['android'] +217919,changing a foreach loop to a parallelforeach loop okay so here is the basic background this program connects to outlookexchange and parses through all the mail messages to see which are encrypted one of the things i would like to do is to use multithreading to decrease the time it takes to scan through the messagescurrently the code looks like thisforeach object item in folderitems checks for encryption and gets needed info and updates countand i would like to utilize the parallelforeach function instead i was wondering how i could set it up i tried setting up the expression to how it is now but i get an error stating that the object type is being used as a variable any help with this would be greatly appreciatedokay the layout i have been given seems to be correct the code looks like this right nowparallelforeachfolderitems item does stuffi am now getting the following error error 15 the type arguments for method systemthreadingtasksparallelforeachsystemcollectionsconcurrentorderablepartitioner systemaction cannot be inferred from the usage try specifying the type arguments explicitlyany ideas thanks for your help guys it is appreciatedokay i found this site and it gave me the answer i needed to the error i just needed to change the collection to a generic one by making a casting functionstatic ienumerableobject castienumerable source foreach object o in source yield return oand then tweak the original toparallelforeachcastfolderitems item does stuffnow it runs without errors hurray,['c#'] +217925,how to print stacktrace for an exception android i want to print the stack trace because at the moment i have this running catch ioexception e throw new errorcopying failedand i have been told to print estacktracehow do i do this,['android'] +217943,php domdocument loadhtml not encoding utf8 correctly i am trying to parse some html using domdocument but when i do i suddenly lose my encoding at least that is how it appears to meprofile divpvarious japanese characterspdivdom new domdocumentdomloadhtmlprofile divs domgetelementsbytagnamedivforeach divs as div echo domsavehtmldivthe result of this code is that i get a bunch of characters that are not japanese however if i doecho profileit thisplays correctly i have tried savehtml and savexml and neither thisplay correctly i am using php 53what i seea a3a3aoa9aaoaoa14aa5a a34a12a14a4aaoaoa3a a aa a14a1a3a a a a34a a a a a2a a3a aa3a a aa2awhat should be showna a3ac3aoaa9aooaa14a5caca aaca34a1214a4aooaa3aceaa a14aa1aa3aa eaa ea34a ae aa ae2e3ea c3ae a e2aedit i have simplified the code down to five lines so you can test it yourselfprofile div langjapa a3ac3aoaapdivdom new domdocumentdomloadhtmlprofileecho domsavehtmlecho profilehere is the html that is returneddiv langjapa12a34a a3a3aoapdivdiv langjapa a3ac3aoaapdiv,['php'] +217963,how can i change the cursor shape with pyqt i have a simple application that runs a process that can last for several minutes before completing so i am trying to provide an indicator to the user that it is processing the request such as changing the cursor to an hourglassbut i cannot quite get it to work right all of my attempts have resulted in either an error or had no effect and i seem to calling the cursorshapes incorrectly pyqt4qtwaitcursor returns an error that the module does not contain itwhat is the correct way to indicate to the user that the process is running,['python'] +217994,smloginitemsetenabled get counterpart for sandboxed apps to create a launch item apple suggest you use lsregisterurl and smloginitemsetenabled along with a helper tool i have set up everything how i want it but i would like a way not storing a preference value to get the status of if it is registered basically a way to perform the same action as smloginitemgetenabled wouldedit here is my final code thanks to rob kenigers answer boolstartatlogin nsdictionary dict nsdictionarysmjobcopydictionaryksmdomainuserlaunchd cfstrcomyourcompanyapp bool contains dictnull dict release return contains,['objective-c'] +218003,converting c class to json i would like to create a json string containing the instance variables of my classfor exampleclass example stdstring string stdmapstdstring stdstring map stdvectorint vector would become stringthestringvalue map key1val1 key2val2 vector1234i have looked into several c libraries for creating json and they all seem incredibly complex i would like something similar to javascripts jsonstringifyobject in other words just pass a stdmap to it and receive a string the map could contain other maps vectors lists strings numbers and boolswhats the nicest way to do thisthanks for your helpediti have looked into the followingjson spirit jsoncpp zoolib jost cajun libjson nosjob jsonbox jsonmewhich i understand i can construct a separate json object as in an answer below and convert to json i would like to be able to store my stuff in standard collections and convertedit 2okay scrap the idea of serializing a class since it appears that is impossible with cs lack of reflectionis there a nice way to convert a stdmap containing stdmaps stdvectors stdlists numbers strings and bools to json without having to change datatypes or copying data to a new datatypethanks,['c++'] +218011,how to track lists of nodes in a jquery plugin if clients may remove those dom nodes i am writing a jquery plugin that points at a certain number of nodes in the dom yet if i try something like having my plugin hold references to a set of nodes i worry about them going stalewhile i realize that javascript is garbage collected and would not crash i would like to be able to keep my lists up to date and not hold on to things that should be gcdthe first thing that occurred to me was that there might be some sort of hook but there does not seem to be a standard that looks trustworthywith jquery is it possible to have a function run when a dom element calls removecallback on the removal of an element from the dom treejquery remove callbackthis made me wonder about maintaining lists of nodes by putting a class attribute on them that way their membership in the list would travel with them but as one might fear this can be pathologically slow to enumerate and is why you are supposed to formulate your query as tags before classesin addition to potential performance concerns i wonder if it is considered poor form for a plugin to poke classes onto dom nodes for this kind of purpose which is not related to styling one of the better things about data is that it is relatively outofband and with the exception of this list issue that is what i am usingthis seems like a common enough problem to have been addressed by other plugins i am tempted to use the class solution for it is correctness properties even though it is slower but is there a faster and more canonical way that gives the best of both worlds,['jquery'] +218025,how to prevent session timeout i know this is probably an easy question for most of you guys but my problem is that my server host empty their session pools every minute so how do i get my users to stay logged in longer than one minutei have heard that i could use sessionstates but i have not found any guides on the net that is easy to use for a newbie like mealso i have heard about doing it with cookies howi am working with c and net,"['c#', 'asp.net']" +218026,how to post value to php in the same page using jquery i do not know if i am just dumb i have been trying to figure this out for the past 1hour please help doctype html public w3cdtd xhtml 10 transitionalen html xmlnsheadmeta httpequivcontenttype contenttexthtml charsetutf8 titleuntitled documenttitlescript srcjqueryjs typetextjavascriptscriptheadbodydiv idbox divdiv idbox2divscript typetextjavascript function boxhtmltest boxattrnameindy var a boxattrname postwindowlocation name johnscriptbodyhtmlphpprint r posthow do i pass the value i know this works if the php is in a different file but this is not the case here,"['php', 'jquery']" +218028,how to make a breakpoint on class member function of pythoni14 i used b classnamefunction or b classnamefunction and those did not work now i use b linenum as a workaroundbut as i modifiy my code frequently linenum changesso how to make a breakpoint on class member function in pythoni google it read the python manual and there is no direct answerthanks,['python'] +218032,symfony and mechanize i am trying to access to a local website designed with the symfony frameworkit works perfectly with the web browser and with curl but when i use mechanize i always got the 401 unauthorized answer for the server import mechanize browserbr mechanizebrowserbrset debug httptruebrset debug redirectstruebrset debug responsestrue does not change anything even if we change thosbraddheaders useragent mozilla50 x11 u linux i686 enus rv1901 gecko2008071615 fedora3011fc9 firefox301 here is my websiter bropenhttplocalhost8080frontend devphphomehtml rread show the html source print htmldo you have any idea why it behaves like thisthanks,['python'] +218065,python how to force a print to use unicode instead of str or otherwise naturally print the message without explicitly calling unicode basically i just want to be able to create instances using a class called bottle eg class bottleobject and then in another module be able to simply print any instance without having to hack code to explicitly call a character encoding routinein summary when i tryobjbottleua3c234print objor to an in place printprint bottleua3c234i getunicodeencodeerror ascii codec cannot encode characterssimilar stackoverflow questionsunicode class in pythonhow to print chinese word in my code using pythonpython string decoding issuepython 30 how to make print output unicodea it is currently not feasible to switch to python3 aa solution or hint and explanation on how to do an in place utf8 print just like class you does successfully below would be muchly appreciated thanx nsample code 8 cut here usrbinenv python coding utf8 def setdefaultencodingencodingutf8 import sys codecs org encoding sysgetdefaultencoding if org encoding ascii not good enough print encoding set to encoding sysstdout codecsgetwriterencodingsysstdout sysstderr codecsgetwriterencodingsysstderrsetdefaultencodingmsgua3c234 the messageclass uunicode passm1umsgprint a m1 works fine even with unicode butclass bottleobject def init selfmsg selfmsgmsg def repr self print debug repr selfmsg return selfmsg def unicode self print debug unicode selfmsg return selfmsg def str self print debug str selfmsg return selfmsg def decodeselfarg print debug decodeselfmsg def encodeselfarg print debug encodeselfmsg def translateselfarg print debug translateselfmsgm2bottlemsgprint b strm2print c reprx reprm2print d unicodex unicodem2print em2 gives unicodeencodeerror ascii codec cannot encode characters 8 cut here python 24 outputencoding set to utf8a a3c234c reprx debug repr a3c234u5473u7cbed unicodex debug unicode a3c234a3c234e debug str a3c234traceback most recent call last file ucpy line 43 in print em2 gives unicodeencodeerror ascii codec cannot encode charactersunicodeencodeerror ascii codec cannot encode characters in position 34 ordinal not in range128 8 cut here python 26 outputencoding set to utf8a a3c234c reprx debug repr a3c234traceback most recent call last file ucpy line 41 in module print c reprx reprm2unicodeencodeerror ascii codec cannot encode characters in position 34 ordinal not in range128,['python'] +218107,how to find the size of any object in ios i was optimizing my app and wanted to know that how much is the size of the object so that i can also show it in logsuppose i have nsdictionary tempnsdictionarydata objectatindexi data is defined in the h file now how will i know that how much is the size of the object tempi tried using the variable view and in the temp section i found the instance sizelong int30498656is the instance size is the exact size of my temp objecti also tried sizeoftempbut it crashed on that pointany help,"['iphone', 'objective-c']" +218128,empty directory delete all files what would be a safe and efficient way to delete all files in a directory in pure ruby i wrotedirforeachdir path f filedeletef if f f but it gives me a no such file or directory errorthank you,['ruby'] +218129,regular expression to get all characters before how can i get the string before the character using regular expressionsfor example i have text1 and i want to return text,['c#'] +218135,calculating manhattan thistance i am implementing nxn puzzels in java 2d array int state am required to use the manhattan heureustic in the following way the sum of the vertical and horizontal thistances from the current node to the goal nodetile plus the number of moves to reach the goal node from the initial positionat the moment i do not know how to go further am a beginner in puzzle game programming with 2d arrays so am sweating hard to understand certain conceptsam asking if someone can help by explaining to me the step by step the procedure i must follow to write this code in javathank you,['java'] +218144,how can i check a c variable is an empty string or null possible duplicateeasier way of writing null or empty i am looking for the simplest way to do a check i have a variable that can be equal to or null is there just one function that can check if it is not or null,['c#'] +218164,getting matplotlib plots to refresh on mouse focus i am using matplotlib with interactive mode on and am performing a computation say an optimization with many steps where i plot the intermediate results at each step for debugging purposes these plots often fill the screen and overlap to a large extentmy problem is that during the calculation figures that are partially or fully occluded do not refresh when i click on them they are just a blank grey i would like to force a redraw if necessary when i click on a figure otherwise it is not useful to thisplay it currently i insert pdbset traces in the code so i can stop and click on all the figures to see what is going onis there a way to force matplotlib to redraw a figure whenever it gains mouse focus or is resized even while it is busy doing something else,['python'] +218171,manifest and supported devices showed in android market is there a tool out there which could test my android manifest to see which devices are supported by the android market with given settings i hope that there is some way other than uploading every test to android marketi need to find out why some small screen devices are not supported but i have not yet found the reason i currently support the following screens and i suppose that androidsmallscreens should let samsung galaxy mini with android 23 install my app but it does not supportsscreens androidlargescreenstrue androidnormalscreenstrue androidsmallscreenstrue androidanydensitytrue edit current permissions and features usespermission androidnameandroidpermissionaccess network state usespermission androidnameandroidpermissioninternetusespermissionusespermission androidnameandroidpermissionaccess fine locationusespermissionusespermission androidnameandroidpermissionaccess coarse locationusespermissionusespermission androidnameandroidpermissionaccess location extra commandsusespermissionusespermission androidnameandroidpermissioncamerausespermissionusespermission androidnameandroidpermissionvibrateusespermissionusespermission androidnameandroidpermissionflashlightusespermissionusespermission androidnameandroidpermissionwrite external storageusespermissionusesfeature androidnameandroidhardwarecamera usesfeature androidnameandroidhardwarecameraautofocus usesfeature nameandroidhardwarescreenportrait requiredfalse i think i have to remove some of these i have garbage here which is not needed anymore will digg into it tonighttomorrow,['android'] +218203,cakephp using multilevel containable behaviour i have been quite some time trying to use the containable behavior in cakephp but i cannot get to make it work as i expectedmy application is different but to simplify i will put this example let us say i have a forum with threads and activities and the activities can be rated the general relations would beforum hasmany threadthread belongsto forum hasmany activityactivity belongsto thread hasmany ratingrating belongsto activitywhat i want to achieve is using the find method get all the ratings performed on a certain forum what i suppose should be done is the following thisratingfindcount array contain array activity array thread conditions array threadforum id 1 but the result query is select count as count from ratings as rating left join activities as activity on ratingactivity id activityid where threadforum id 1i have accomplished this using the joins option but it is more complex and i have to use this kinda action in many situationsall the files related with the example can be found here thanksupdate 23112011after investigating the framework and thanks to the answers of moz morris and api55 i found the source of the problemthe basic problem was that as i understood cakephp i thought it was querying using joins each time the thing it that it does not do that the real operation it would perform to obtain the result i was looking for would be something like thisselect from rating join activityselect from activity join threadselect from activity join threadmeaning that it would do a query to get all the activities and then for each activity perform a query to get the threads my approach was failing not because of the containable behaviour being used wrong but because the conditions option was applied to all queries and on the first one it crashed because of the absence of the thread table after finding this out there are two possible solutionsas api55 said using the conditions inside the contain array it would apply them only to the queries using the thread table but doing this the problem persists because we have way too many queriesas moz morris said binding the thread model to rating would also work and it would perform a single query which is what we want the problem is that i see that as a patch that skips the relations betweem models and does not follow cakephp philosophyi marked api55 solution as the correct because it solves the concrete problem i had but both give a solution to the problem,['php'] +218208,motivations and demotivation for migrating applications to java 7 java 7 has been around for a while now now if an application is to be migrated to java 7 without any changes codeconfiguration are there any inherent advantages or drawbacks i was curious to know what the problems are faced during such migrationedit by migration i mean the code will remain the same but the runtime will change to java 7 as i mentioned no codeconfiguration changes so thing which i think should impact the application is new compilervm level default optimizations so i was looking for anything which would impact the overall application behavior,['java'] +218220,saving entities in djangononrel with google appengine update i have noticed that entities are saved and available at the datastore viewer when i save them using views and the create object function but when i use shell managepy shell to create and save new entity it is not commited to the storage but still can be seen in tesobjectsalli started playing with the djangononrel with google appengine and i am getting frustrated by thing as simple as saving entitiesi have set up my environment as described in instruction i managed to run sample application and it runs ok i would like to extend it so it saves my entity to the storage to do soi added new django module with modelspyfrom djangodb import modelsclass tesmodelsmodel name modelscharfieldmax length150i created a script to save some dataimport osimport syssyspathappenddworkspaceprojectosenvirondjango settings module settingsfrom testmodulemodels import test tesnametesttsave tes tesobjectsallfor t in tes print tnamethe script runs without erors when i run it few times one after another it prints more and more test strings but when i try running it after a minute break the tesobjectsall returns nothing during that time the datastore file changes it size but maybe that is just some kind of logs when i look at the httplocalhost80 ahadmindatastore i can select only ahadminxrsftoken from select fieldanyway what am i missing where i can find some kind of logs which would tell me whats wrong,['python'] +218231,strange local folder inside virtualenv folder after i create my virtualenv environment ve inside it there is a symbolic link named local it points to the ve folder which means that if you open it you end up in the same folder that you started ini wouldnt care about that but it makes some autocompletion wizards in pycharm unusable they show the same item over and over again each time with a deeper nesting levelsomehow i cannot find any hint about this problem i am using virtualenv 164 the question is whats that local symlink used for,['python'] +218242,c vector accumulates i was trying to use the accumulate function for vectorsvector double adouble b 0areserve100foritr 0 itr 210 itr term1 powritr 12 term1 1term1 term2 powritr 6 term2 2term2 apush backterm1 term2b accumulateabegin aend 0however i always got b 0 while a had nonzero values,['c++'] +218247,alert dialog two buttons hello all i have a simple problem i have a alertdialog and i want it to show two buttons i have searched here but it seems the options before do not work anymore and are deprecatedanyone know the new way of doing this you can see my code below that does not work button share button findviewbyidridbtn share sharesetonclicklistenernew onclicklistener public void onclickview v call some other methods before that i guess alertdialog alertdialog new alertdialogbuilderpasswactivitythiscreate read update alertdialogsettitleuprgade alertdialogsetmessageupgrade text here alertdialogsetbuttonupgrade new dialoginterfaceonclicklistener public void onclickdialoginterface dialog int which alertdialogsetbuttoncancel new dialoginterfaceonclicklistener public void onclickdialoginterface dialog int which alertdialogshow see this,['android'] +218251,getting filesystemexception a required privilege is not held by the client using filescreatesymboliclink in play framework i am trying to use the new java 7 filescreatesymboliclink method within play framework and i got the following exceptionruntimeexception occured javaniofilefilesystemexception cworkfoobara required privilege is not held by the clientthis is my first encounter with javas permission model so i understand whats going on but do not yet know how to fix it i would like to give the controllers more permissionsif anyone can answer here faster than i will find the answer me and future readers will be grateful,['java'] +218267,compressing text before storing it in the database i need to store a very big amount of text in mysql database it will be millions of records with field type longtext and database size will be hugeso i want ask if there is a safe way to compress text before storing it into text field to save space with ability to extract it back if neededsomething likearchived text compress texthuge text saving archived text to database here getting compressed text from databasearchived text get text from dbhuge text uncompress textarchived textis there a way to do this with php or mysql all the texts are utf8 encodedupdatemy application is a large literature website where users can add their texts here is the table i havecreate table book parts id int11 not null auto increment book id int11 not null title varchar200 default null content longtext order num int11 default null views int10 unsigned default 0 add date datetime default null is public tinyint3 unsigned not null default 1 published as draft tinyint3 unsigned not null default 0 primary key id key key order num order num key add date add date key key book id book idis publicorder num constraint foreign key book id references books id on delete cascade engineinnodb default charsetutf8 currently it has about 800k records and weights 4 gb 99 of queries are select i have all reasons to think that numbers increase diagrammatically i wouldnt like to store texts in the files because there is quite heavy logic around and my website has quite a few hits,"['php', 'mysql']" +218268,reset css thisplay property to default value is it possible to override the thisplay property with its default value for example if i have set it to none in one style and i want to override it in a different with its defaultor is the only way to find out what the default of that element is and then set it to that would like to not have to know if the element is usually block inline or whichever,['css'] +218269,where the heck is the android apps lib folder i have been trying to find the socalled lib folder to install some 3rdparty tools this there they tell you to place it downloaded jar file in your android appas libs folder but in eclipse i could not find the lib folder even after expanding all of the directories shown in the navigator area will someone tell me where this lib folder is thanks,"['java', 'android']" +218274,ios add a parameter to selector when i have this line of codeuilongpressgesturerecognizer downwardgesture uilongpressgesturerecognizer alloc initwithtargetself actionselectordraggesturechangedand this voiddraggesturechangeduilongpressgesturerecognizergesturei want to add at selectordraggesturechanged a parameter that is uiscrollviewscrollview how can i do,['ios'] +218283,why does the c boost package only contain hpp files i am new to c i just downloaded the boost libraries to study i wanted to look into some implementation details so i looked for cpp files to my surprise i have not found any so farthere seem only hpp files out there where are the cpp files this question may sound pretty naive to you but please bear with me for a moment,['c++'] +218295,jquery ajax image upload as the title describes i would like to create an image upload with ajax with jquery as far as i know right now there is no image ajax uploading workarounds are iframes and flash since i do not like flash i am fine with the iframe hack i hope like they do it here i have an element i want to make it possible to double click on the element then a file browser appears you choose your image it gets uploaded and the images src you just clicked gets changed to the new uploaded images path does not really sound that hardactually that is what the link i posted above does i do not know what it does in detail how it handels everything since there is no documentationso can me anyone explain what that plugin does in the backend so i understand it i do not know what i should do with the phpphp file what i should pass as an action of the formthanks,['jquery'] +218304,unit testing and assert case for void method i am trying to create some unit testing for a void method basically the method is intended to show the role of a system user and implement it within the software this is the method public void setpersonobjperson typeobj thistypeobj typeobj createmainhow would i create an assert case in a separate class that uses unit testing to check this methodmany thanks,['java'] +218311,settimeout not working on safari mobile i have a function that shows a menu when clicking on it and i want it to thisappear after 5 seconds this is my javascript it works properly on desktop browser but it does not thisappear on the mobile onesfunction prod btnclickfunction thisaddclaselectednextulcssthisplay block settimeouthidemenu 50 function hidemenu prod btnremoveclaselectednextulcssthisplay nonewhere is the problemthanks,"['javascript', 'jquery']" +218340,cucumber capybara search for text within table row i am trying to search within a single table row for my cucumber testi have each row formatted like thistr td title td complete td goaland i am looking to search within a row with a given title and check the goalis there a simple way to accomplish this,['ruby'] +218344,replace substring of nsattributedstring with another nsattributedstring i want to replace a substring eg replace of an nsattributedstring with another nsattributedstringi am looking for an equivalent method to nsstrings stringbyreplacingoccurrencesofstringwithstring for nsattributedstring,"['iphone', 'ios']" +218356,jquery mobile static headers i have a jqm application that uses the header as a navigation bar the problem i am having is that the page transitions specifically slide move the header along with the content as one page i am looking for a way to keep the header static during page transitionsi have checked the api and cannot seem to find anything has anyone figured out a way to accomplish this is it even possible with jqmany help would be appreciated,['jquery'] +218358,closures in auto executing functions vs objects let us say i have the followingvar foo function var bar 0 return getbar function return bar addone function bar addrandom functionrand bar rand and i have the followingvar foo2 function var bar 0 thisgetbar function return bar thisaddone function bar thisaddrandom functionrand bar rand is the only difference in executing the functions a newalertfoogetbar 0fooaddonefooaddrandom32alertfoogetbar 33var foo2 obj new foo2alertfoo2 objgetbar0foo2 objaddonefoo2 objaddrandom32alertfoo2 objgetbar33they both out put the exact same thingso what is the difference in the long runwhat can one do that the other cannotfiddle demo of the above,['javascript'] +218376,twostep method resolution with inheritance and generic constraints i have encountered something quite surprising when using generic constraints with inheritance i have an overloaded methods foo that differ with parameter either base or derived class instance in both cases it is generally just passing the instance to the second pair of overloaded methods barwhen i call foo with base class instance bar overload for the base class is called when i call foo with derived class instance bar overload for the derived class is called this is clear and expectedbut when i tried to merge foo methods into single one genericfoo that use generics and constraints methods are resolved differently t is resolved correctly but only baseclass overload of bar is calledpublic class animal public class cat animal public class animalprocessor public static void fooanimal obj consolewritelinefooanimal barobj public static void foocat obj consolewritelinefoocat barobj new generic method to replace the two above public static void genericfoott obj where t animal consolewritelinefoogeneric barobj public static void baranimal obj consolewritelinebaranimal public static void barcat obj consolewritelinebarcat testing code two first cases for nongeneric old methods two last for new generic methodconsolewritelineanimalanimalprocessorfoonew animalconsolewritelineconsolewritelinecat animalprocessorfoonew catconsolewritelineconsolewritelineanimalanimalprocessorgenericfoonew animalconsolewritelineconsolewritelinecat animalprocessorgenericfoonew catconsolereadlineand the result note the difference in type resolved in baranimalfooanimalbaranimalcatfoocatbarcatanimalfoogenericbaranimalcatfoogenericbaranimalit looks like the compiler binds all calls from genericfoo to the least specific overload even if all more specifictyped calls are known at compile time why is that what is the reason for such behaviour which part of specs defines this,['c#'] +218390,extra whitespace in html values rendered with jade every time i write my html in jade i am getting extra whitespace added after each elements valuefor example i will have a line like this in my jade templatelabelforkeyword keywordand when it is rendered the source will look like thislabel forkeyword 1keyword labelran into some problems with that extra whitespace messing w my css plus it just does not look as tidy anyone know how i can prevent it from being inserted,['html'] +218397,which project is more mature scalaquery or squeryl for me both of them looks quite similar if it is going to features but it is hard to say without using them yet so i have few questions1 are they really feature comparable more or less 2 is there any example of enterprise or big open source system using any of them 3 i have impression that squeryl have better documentation is lack of documentation in case of scalaquery real problem 4 which of them is growing faster andor is faster on fixing the bugs 5 is any of them easier to use more productive,['sql'] +218420,right way to have aspnet iis not cache pdf files i have the following scenario and i wanted suggestions on what is the best way to handle this my web app aspnet 20 iis 6 generates pdf files and i have a results page with links to those pdfs now i noticed that if i visit the results page click on a pdf file it opens in a new window then regenerate the pdf file and click on the same link in the results page the old pdf is shown instead of the new one i had to delete the temporary internet files in order to see the new oneso since i am not serving an aspx that actually writes the pdf and i do not want the save dialog to show but straight linking to the pdf file i want to know what the best way to make sure the user always sees the latest file in the server not a cached versioni am guessing adding nocache headers is out of the question but the pdf request would still go through an http handler so i would like to know if i should create a specific http handler to intercept requests for pdfs or if i should do this at the iis levelhowever i dont necessarily want to avoid caching all pdfs on that site any suggestions thanks in advance for the help,['asp.net'] +218449,fragments dialogfragment and screen rotation i have an activity that calls setcontentview with this xmllinearlayout xmlnsandroid androidlayout widthfill parent androidlayout heightfill parent androidorientationhorizontal fragment androidnameorgvtindiatabgroupfragment androidididhome groups androidlayout widthfill parent androidlayout heightfill parent androidlayout weight1 some other fragments linearlayoutthe groupfragment extends fragment and all is well there however i show a dialogfragment from within groupfragment this shows correctly however when the screen rotates i get a force closewhats the proper way to thisplay a dialogfragment from within another fragment other than dialogfragmentshowfragmentmanager string,['android'] +218472,can a function pointer with a const argument be used as a function pointer with a nonconst argument perhaps the title is not clear in itselfi have a function f provided by some library that takes as an argument a function pointer of signature void gint ievoid fvoid ginthowever i would like to use it using a function g that i defined with signature void gconst int a priori i cannot see how this can violate any constcorrectness as all the signature of f says is that g will only ever be called with a nonconst int nonconst and indeed i can call a void const int function with a nonconst int argumentbut gcc complains and saysexpected void int but argument is of type void const int i cannot see how this complaint can be legitimate so does anyone know whether my understanding of that is wrong or if there is a way around that,['c'] +218478,dictionary keyscontains vs containskey are they functionally equivalent i am curious to know if these two are functionally equivalent in all casesis it possible that by changing the dictionarys default comparator that these two would be functionally differentalso is not keyscontains almost guaranteed to be slower,['c#'] +218479,no linkage at block scope do all variables declared in a block have no linkagefor example1if i declare a static variablevoid foo static int iwould it have an internal linkage or no linkage if no linkage then why make it static2what happens if i use externglobal scopestatic int ivoid foo extern int iin this case what will be the linkage of i,['c++'] +218483,how to get nsarray of localised dayofweek names in ios how to get nsarray of localised dayofweek names in iosie do not want to have to hardcode them in myself is there an easy way to get this from an ios class all i can think of is to write a method that steps through 7 days and then using the formatter output the day of week and collect these up,"['iphone', 'ios']" +218502,why is semicolon allowed in this python snippet python does not warrant the use of semicolons to end statementsso why is this below allowedimport pdb pdbset trace,['python'] +218514,in android 40 navigation bar hijack first touch event in android 40 on devices without hardware navigation keys android will render navigation baryou can hide it if you want by using setsystemuivisibilityif that is done lets say if you want to get as much screen as possible for playback when you first touch screen and yes on view you implement viewontouchevent first touch will be hijacked by android and your api will not be called only once navigation bar is visible it will be callednow that can be avoided by also listening toand when navigation bar is visible just do what you will do on first touchis there any other way to do the same that will say android 40 to propagate touch event to my app once navigation bar is done with it,['android'] +218517,how do i pop two views at once from a navigation controller i want to pop to the third view on the navigation stack back to the first viewi know how to pop one view at onceselfnavigationcontroller popviewcontrolleranimatedyesbut how do i do two at oncethanks,"['iphone', 'ios']" +218523,exceptiongetmessage is null inside my java code it is checking for null condition and throwing an exceptionfor example try if studgetcall null acall studgetcalltostring else throw new exceptiondata is nullcatch exception e loggererrorsome error egetmessage throw new exceptionplease check the manatadatory field is missing egetmessagebut in the logs i am gettingsome error nullwhy is the egetmessage null,['java'] +218538,spanned columns collapsing on android webbrowser when using autofit pages update i have logged a bug report with google can4colspecid20type20status20owner20summary20starsupdate benni mac b points out that the problem goes away if you thisable autofit pages this solution works on 21 and 22 turns out that the 23 phone i was testing on had thisabled autofit to start with and when enabled the table breaks againguess i am now looking for a way to tell android not to autofit the table and override the browser setting not liking my chances judging by my google searches so fari have encountered an odd issue with the android webbrowser and spanned columns for example if i have this structuretable classamhtable col width1672 col width1662 col width16 col width16 col width3467 thead tr classheading tdmodifying circumstancetd tdcommon pathogenstd tdfirst choicetd tdalternativetd tdadditional informationtd tr thead tr classheading2 td colspan5 width100section titletd tr tr classbody tdcolumn 1td tdcolumn 2td tdcolumn 3td tdcolumn 4td tdcolumn 5td trtablethe spanned row will reduce to fit the size of the screen even if the table itself is still wider this means that the heading2 rows background is missing across most of the table in some cases making it look quite oddthis is not happening on iphone or any desktop browser chrome ie ff safari that were aware of just on android multiple devices and versionsthe cssamhtable borderwidth1px borderstylesolid bordercolor0 bordercollapse collapse borderspacing 0 padding 5px fontweight normal color 0amhtable td borderwidth1px borderstylesolid bordercolorblack padding 3pxamhtable th borderwidth1px borderstylesolid bordercolor7 backgroundcolor0084d6amhtable heading borderwidth1px borderstylesolid bordercolor0 backgroundcolor567ac4 fontweight bold fontstyle italic fontfamily verdana arial helvetica dejavu sans bitstream vera sans sansserif amhtable heading2 borderwidth1px borderstylesolid bordercolor0 backgroundcolor82a3e7 fontweight bold fontfamily verdana arial helvetica dejavu sans bitstream vera sans sansserif so far i have tried the followingremoving the col elementsadding a sixth column and empty td elements into each rowremoving the bordercollapse style after reading webkit browsers rendering problem for table depending on colspan setting the width of the spanned column to 100 along with the changes abovesetting a fixed width on the table and setting the spanned column to 100replaced the based widths of the columns with fixed pixel widthsset the position to be relative for the spanned cell and then the row and set left and right to 0set the position to be relative for the row with left as 0 and width as 10pxwrapped the table in a 100 wide divone thing that we noticed yesterday is that the table should have a 1px black border but there is a gap on the 2122 devices were testing on where the row does not complete it really does seem to be a rendering problem on these devices,"['android', 'html', 'css']" +218565,how to save traceback sysexc info values in a variable i want to save name of the error and the traceback details into a variableimport systry try print x except exception ex raise nameerrorexcept exception er print 0 sysexc info0 print 1 sysexc info1 print 2 sysexc info2output getting0 type exceptionsnameerror1 2 traceback object at 0xbd5fc8output wanted0 nameerror12 traceback most recent call last file exceptionpy line 6 in module raise nameerrorhelpps i know this can be done easily using traceback module but i want to know usage of sysexc info2 object here,['python'] +218590,unable to get click event in d3 javascript library i am using d3 javascript library to thisplay data as a force directed marker it works fine but i am unable to add click event to the circle so when i click on the circle i get detailed analysis of the circle and thisplay it in a modal boxvar links source x targety type paidvar nodes compute the thistinct nodes from the linkslinksforeachfunctionlink linksource nodeslinksource nodeslinksource name linksource linktarget nodeslinktarget nodeslinktarget name linktargetvar w 950 h 500var force d3layoutforce nodesd3valuesnodes linkslinks sizew h linkthistance60 charge300 ontick tick startvar svg d3selectgraphappendsvgsvg attrwidth w attrheight h pertype markers as they do not inherit stylessvgappendsvgdefsselectallmarker datasuit licensing resolved enterappendsvgmarker attrid string attrviewbox 0 5 10 10 attrrefx 15 attrrefy 15 attrmarkerwidth 6 attrmarkerheight 6 attrorient auto appendsvgpath attrd m05l100l05var path svgappendsvggselectallpath dataforcelinks enterappendsvgpath attrclass functiond return link dtype attrmarkerend functiond return url dtype var circle svgappendsvggselectallcircle dataforcenodes enterappendsvgcircle attrr 6 callforcedragvar text svgappendsvggselectallg dataforcenodes enterappendsvgg a copy of the text with a thick white stroke for legibilitytextappendsvgtext attrx 8 attry 31em attrclass shadow textfunctiond return dname textappendsvgtext attrx 8 attry 31em textfunctiond return dname use elliptical arc path segments to doublyencode directionalityfunction tick pathattrd functiond var dx dtargetx dsourcex dy dtargety dsourcey dr mathsqrtdx dx dy dy return m dsourcex dsourcey a dr dr 0 01 dtargetx dtargety circleattrtransform functiond return translate dx dy textattrtransform functiond return translate dx dy i tried adding onclick alerthello world to var circle it does not work as expected it alerts on load instead on clicki appreciate any help,['javascript'] +218599,how does linkedlist work internally in java as far as i know the concept of a linked list is a bunch of object connected to each other by having a next and sometimes previous attribute to traverse the objectsi noticed in java you can create a linkedlist objectbut treat it like an arraylistsequence by using the same methods such as add get etcso is linkedlist internally an arraylike sequence,['java'] +218606,array filter in the context of an object with private callback i want to filter an array using the array filter function it hints at using call user func under water but does not mention anything about how to use within the context of a classobject some pseudocode to explain my goal class relatedsearchblock private function get filtered docs return array filterthisget docs filter item private filter item return docsomevalue 123 would i need to change filter item into arraythis filter item is what i want possible at all,['php'] +218610,rounding up to the second decimal place possible duplicatephp round function round up to 2 dp what my problem iswhen i useceil36451895227869i get like4but i want365can you help me outupdateplease rememberthis should always round to ceil like while rounding363it must not be 363 but should be 364,['php'] +218655,how to get little endian data from big endian in c using bitconvertertoint32 method i am making application in cin that application i have byte array containing hex valueshere i am getting data as a big endian but i want it as a little endianhere i am using bitconvertertoint32 method for converting that value to integerbut my problem is that before converting valuei have to copy that 4 byte data into temporary array from source byte array and then reverse that temporary byte arrayi cant reverse source array because it contains other data alsobecause of that my application becomes slowcode here i have one source array of byte as wavedatait contains lot much of databyte tempfortimestampnew byte4tempfortimestamp0 wavedata290tempfortimestamp1 wavedata289tempfortimestamp2 wavedata288tempfortimestamp3 wavedata287int number bitconvertertoint32tempfortimestamp 0is there any other method for that conversion,['c#'] +218692,increasing the size of checkbox in html is there any way to increase the size of checkbox in html,['html'] +218749,rails devise mail im trying to override devise in order to send mail to activate a user in the create method in the registrations controller i have thisurlemail resourceemailsubponymail to resourceemail from subject confirm account headers contenttype texthtml body h1welcome to my awesome siteh1 pfollow this link to create your accountp phttplocalhost30confirmmestuff resourceconfirmhashto s urlemailto s p this url leads to a method to activate the user whether this is a good way to confirm an account is beside the point the problem is that when the ponymail runs i get this error uninitialized constant registrationscontrollerponyi have installed pony and ponymail works in the console i also tried using require pony in the top of the controller file but i get no such file to load ponywhat do i need to do to make this work,['ruby-on-rails'] +218761,getting the root element that a delegated event is bound to jquery taking the following code bind the click event to the thumbnails ulhplistonclick ahpthumb function event eventpreventdefault var this this surely there has to be a smarter way to do this hplist thisparentsulhplist changeitemthis hplist how do i better identify the root ancestor element that the event is bound to i feel awful searching the dom for this,['jquery'] +218764,windows forms application visual style i will try to keep this as simple as possiblea button created in a windows forms application looks like thisif i create a form manually buttons i create will look like thisi looked thoroughly through the windows forms application and found no code that changes the visual style of buttonsis there any simple explanation as to why this is happeningthanks in advance,['c#'] +218786,jquerymobile loading message theme i have a question about the loading message on jquery mobileby default the loading message theme is a according to jquery mobile code div classuiloader uibodya uicornerall styletop 2045px divi would like to know how i can change the default theme of this div i cannot figure it outthanks in advance,['jquery'] +218796,python urllib2 using different network interface i have the following codef urllib2urlopenurldata freadfcloseit is running on a machine with two network interfaces i would like to specify which interface i want the code to use specifically i want it to use the one other than the one it is using by default but i can figure out which is which if i can just pick the interfacewhats the easiestbestmost pythonic way to do this,['python'] +218801,ios launching settings restrictions url scheme i have recently thiscovered the awesome ios5 custom settings url scheme which can be explained in detail at this great websitei have found this to work directing the user to the settings app from my applicationuiapplication sharedapplication openurl nsurl urlwithstringprefsrootgeneralbut cannot seem to route directly to the restrictions path via the path parameteruiapplication sharedapplication openurl nsurl urlwithstringprefsrootgeneralpathrestrictionshas anyone found documentation on this or been able to make this work any insight would be greatly appreciated i am trying to take the user to enable inapp purchasing and would rather not have the user manually click on restrictions not very obvious,"['ios', 'iphone']" +218805,new ios5 uiswitch does not look thisabled in a uitableviewcell i am placing a uiswitches in uitableviewcells and i try to thisable it initially uitableviewcell tableviewuitableview tableview cellforrowatindexpathnsindexpath indexpath selfswitch uiswitch alloc init selfswitchenabled no cellaccessoryview selfswitch in ios versions prior to ios5 the oldlooking switch is thisabled and also looks thisabled dimmed when the view appearsin ios5 the newlooking switch is thisabled alright i cannot flip it but it does not look thisabled at this stage it has the same brightness as an enabled switchif i enable and rethisable it later in the code not in the cellforrowatindexpath callback it does look thisabled dimmedam i doing something wrong or is this a bug in ios5,"['iphone', 'ios']" +218807,smoothscrolltopositionfromtop for froyo listview i want to tap a control on the screen and have the listview scroll until a given row is at the top of the screen a feature that appears to be very easy in iosi did find such a method in the api int inthowever this is for api level 11 honeycomb that means phones cannot use it until ice cream sandwich and it will be a long long time until it is practical to set ice cream sandwich as a minimum requirement to run appsis there a way to get this same functionality in froyo,['android'] +218816,does pythons ossystem wait for an end of the process the python manual says nothing about whether ossystemcmd waits or not for a process to endto quote the manualexecute the command a string in a subshellit looks like it does wait same behaviour as perls system is this correct,['python'] +218823,what is the reason for this strange php behaviour i have the following codedata array prep arraydatardvark trueprint rdata output arrayecho nvar dumpin arrayzebra datathe output is as followsarray aardvark 1booltruedespite the fact that zebra is clearly not in the array it looks like it is to do with phps loose type system bool zebra is true and there is a true in the array so the in array returns truei think i can see the logic but it is flawed is this a php bugcheers,['php'] +218850,changing packaging based on active profile in pom i have a project which i compile with maven i have different profiles declared in pomxmlfor some of these profiles i prefer building a war and for other profiles i prefer a jar i use to manually edit the pomxml file and change packaging variable to eitherpackagingwarpackagingorpackagingjarpackagingbefore doing a mvn clean package pchosenprofilehow can i tell mvn the packaging corresponding to each profile so i do not need to edit pomxml,['java'] +218857,using like wildcard in prepared statement i am using prepared statements to execute mysql database queries and i want to implement a search functionality based on a keyword of sorts for that i need to use like keyword that much i know and i have also used prepared statements before but i do not know how to use it with like because from the following code where would i add the keyword can i directly use it in the pstmtsetstring1 notes as 1 notes or something like that i see a lot of posts on this on the web but no good answer anywherepreparedstatement pstmt conpreparestatement select from analysis where notes like pstmtsetstring1 notesresultset rs pstmtexecutequery,"['java', 'mysql']" +218877,right way to incorporate superclass into a guava objectshashcode implementation possibly a dumb question but i do not want to screw this up let us say i have two java classes class1 and class2 where class2 extends class1 i want to override objecthashcode using guava for both classes for the superclass i have got overridepublic int hashcode return objectshashcodemfield1 mfield2for class2 whats the right way to implement hashcode that takes the members of class1 into consideration is it like thisoverridepublic int hashcode return objectshashcodesuperhashcode mfield3 mfield4 that seems right to me but i am looking for some validation joshua bloch does not address this situation in effective java and the guava docs do not either,['java'] +218882,java instantiate class at runtime with parameters i am using an abstract factory to return instances of concrete subclassesi would like to instantiate the subclasses at runtime given a string of the concrete class name i also need to pass a parameter to the constructors the class structure is as followsabstract class parent private static hashmapstring child instances new hashmapstringchild private object constructorparameter public static child factorystring childname object constructorparam ifinstanceskeyexistschildname return instancesgetchildname some code here to instantiate the child using constructorparam then save child into the hashmap and then return the child currently i am doing child instance child classfornamechildclassgetconstructornewinstancenew object constructorparam instancesputchildname instance return instance constructor is protected so unrelated classes cannot instantiate protected parentobject param constructorparameter param end parentclass child extends parent protected childobject constructorparameter superconstructorparameter my attmept above is throwing the following exception javalangnosuchmethodexception childinit followed by the stack trace any help is appreciated thanks,['java'] +218888,sleep is a bad design but appears to be my only option i am writing an io class to uploaddownload files to a controller over rs232 serial unfortunately i cannot send a whole file all at once i have to break it into packets and send it a little bit at a time heres the basic approach ifstream file pathtofileext iosin iosbinarywhile fileeof zero buffer and add packet header 8 bytes size t nresult fileread buffer8 129 serialwrite buffer nresult8 see if controller wrote anything to the serial port and process it is command sleep 600 i know that using sleep is not a good design practice but if i remove the sleep statement or even shorten the amount time the loop sleeps then the controller throws errors about it is buffer being full and the transfer fails is there a better way to do thisbefore you say it no i cannot send a message to the controller to determine if it is ready for the next packet it does not have that functionality editi forgot to mention that the interval at which i am having to sleep is somewhat blind the protocol specification provided by the manufacturer does not detail any length of time needed between packets so i had to determine that value by trial and error i am afraid that it may not work on every pc and more so that it may not work on every controller this development is being done for windows xpvista7edit 2also the amount of data per packet is actually a trial and error guess as well the protocol specification allows for packets of 65535 bytes including the header but if you send more than 129 bytes at a time you start seeing issues where sometimes it works and sometimes it does not there also seems to be a relationship between the time you have to sleep and the amount of bytes you can send if i drop the packet size down to 20 bytes per packet i can drop the sleep time down to 400 milliseconds i believe the reason for these issues stem from the time it takes to the controller to move data from its buffer to the file,['c++'] +218913,argparse identify which subparser was used i think this must be easy but i do not get itassume i have the following arparse parserimport argparseparser argparseargumentparser versionpyargparsetest 10 subparsers parseradd subparsershelpcommands allall parser subparsersadd parserall helpprocess all apps appapp parser subparsersadd parserapp helpprocess a single appapp parseradd argumentappname actionstore helpname of app to processhow can i identify which subparser was usedcallingprint parserparse argsallgives me an empty namespacenamespace,['python'] +218924,how do i compare two files in ruby 19 in ruby 18 i would call filecompare from the ftools library to easily compare the contents of two fileshowever in ruby 19 ftools is replaced by fileutils which does not have a compare method whats the equivalent call,['ruby'] +218936,a slider for curses based ui as a learning project i would like to setout to make an ncursesbased ui for a program i had in mind written in pythonafter looking at urwid documentation i cannot see anyway to create a simple slider i need it to make a volume slider that can be adjusted with the mouseam i missing something in urwid or is there a more convenient curses module to make such a slider,['python'] +218944,uncaught exception permission denied to proxyinstalltrigger i have searched high and low for this and can easily reproduce it running absolute latest php sdk and the js is coming directly from facebook over an https connection my myappid and domain have been changed in the code that follows substitute your own to reproducethis is with firefox 8 and firebugcode to reproduce bodydiv idfbrootdivscript typetextjavascriptwindowfbasyncinit function fbinit appid myappid status true oauth true cookie true channelurl fbcanvassetautoresize fbcanvasscrollto00 function var e documentcreateelementscript easync trueesrc documentlocationprotocol connectfacebookneten usalljsdocumentgetelementbyidfbrootappendchildescripttestbodyhtmlit is most definitely the calls to fbcanvas that are generating the error if i comment both out no error if i uncomment one or the other or both errorthe code was working fine until a few days ago targeting the top of the page and scaling the iframe properly i believe this is a fb js error,['javascript'] +218951,how to removeuninstall item templates in visual studio 2010 i have an item template that i did wrong and want to delete i deleted the zip file from the output location and ran devenv installvstemplates and devenv setup and when i opened vs and tried to add a new item it was still there stranger still i can still use it and create copies of the file so it must exist somewhere is there somewhere that visual studio stores the files after being installed that i need to delete i also cant change the template it stays the same no matter what i doedit if it makes a difference i am using xna gs 40,['c#'] +218958,invalid byte sequence error in normalize yaml input being thrown i am getting the error below when trying to push my project to heroku googling found a few people with similar issues turning up but with a different gem as the last gem before the error so i do not think it is got to do with warden a few of the similar errorsgithub issues i found had solutions pointing back to a rubygems error which was apparently to be fixed in 1810 which i have got already so i am doubtful that it is that issue eitherany suggestions would be appreciatedai am sure it is something simple i have missedcobychapple at shiva in codez on mastera git push heroku mastercounting objects 201 donedelta compression using up to 2 threadscompressing objects 100 181181 donewriting objects 100 201201 9214 kib donetotal 201 delta 38 reused 0 delta 0 heroku receiving push rubyrails app detected detected rails is not set to serve static assets installing rails3 serve static assets done configure rails 3 to thisable xsendfile installing rails3 thisable x sendfile done configure rails to log to stdout installing rails log stdout done gemfile detected running bundler version 107 unresolved dependencies detected installing using without developmenttest fetching source index for installing rake 0922 installing multi json 103 installing activesupport 312 installing builder 300 installing i18n 060 installing activemodel 312 installing erubis 270 installing rack 135 installing rackcache 11 installing rackmount 083 installing racktest 061 installing hike 121 installing tilt 133 installing sprockets 212 installing actionpack 312 installing mimetypes 1172 installing polyglot 033 installing treetop 1410 installing mail 230 installing actionmailer 312 installing arel 221 installing tzinfo 0331 installing activerecord 312 installing activeresource 312 installing addressable 226 installing bcryptruby 301 with native extensions installing coffeescriptsource 113 installing execjs 129 installing coffeescript 220 installing rackssl 132 installing json 161 with native extensions installing rdoc 311 installing thor 0146 installing railties 312 installing coffeerails 311 installing orm adapter 005 installing warden 110 usrruby192libruby191rubygemsspecificationrb519in normalize yaml input invalid byte sequence in usascii argumenterror from usrruby192libruby191rubygemsspecificationrb479in from yaml from usrruby192libruby191rubygemspackagetar inputrb183in load gemspec from usrruby192libruby191rubygemspackagetar inputrb51in block in initialize from usrruby192libruby191rubygemspackagetar readerrb64in block in each from usrruby192libruby191rubygemspackagetar readerrb55in loop from usrruby192libruby191rubygemspackagetar readerrb55in each from usrruby192libruby191rubygemspackagetar inputrb32in initialize from usrruby192libruby191rubygemspackagetar inputrb17in new from usrruby192libruby191rubygemspackagetar inputrb17in open from usrruby192libruby191rubygemspackagerb58in open from usrruby192libruby191rubygemsformatrb63in from io from usrruby192libruby191rubygemsformatrb51in block in from file by path from usrruby192libruby191openurirb35in open from usrruby192libruby191openurirb35in open from usrruby192libruby191rubygemsformatrb50in from file by path from usrruby192librubygems191gemsbundler107libbundlersourcerb72in fetch from usrruby192librubygems191gemsbundler107libbundlerinstallerrb45in block in run from usrruby192librubygems191gemsbundler107libbundlerspec setrb12in block in each from usrruby192librubygems191gemsbundler107libbundlerspec setrb12in each from usrruby192librubygems191gemsbundler107libbundlerspec setrb12in each from usrruby192librubygems191gemsbundler107libbundlerinstallerrb44in run from usrruby192librubygems191gemsbundler107libbundlerinstallerrb8in install from usrruby192librubygems191gemsbundler107libbundlerclirb225in install from usrruby192librubygems191gemsbundler107libbundlervendorthortaskrb22in run from usrruby192librubygems191gemsbundler107libbundlervendorthorinvocationrb118in invoke task from usrruby192librubygems191gemsbundler107libbundlervendorthorrb246in thispatch from usrruby192librubygems191gemsbundler107libbundlervendorthorbaserb389in start from usrruby192librubygems191gemsbundler107binbundle13in top required from usrruby192binbundle19in load from usrruby192binbundle19in main failed heroku push rejected failed to install gems via bundlerto zgit remote rejected master master prereceive hook declinederror failed to push some refs to zgitheres the output of bundle install too in case it helpscobychapple at shiva in codez on mastera bundle installusing rake 0922 using multi json 103 using activesupport 312 using builder 300 using i18n 060 using activemodel 312 using erubis 270 using rack 135 using rackcache 11 using rackmount 083 using racktest 061 using hike 121 using tilt 133 using sprockets 212 using actionpack 312 using mimetypes 1172 using polyglot 033 using treetop 1410 using mail 230 using actionmailer 312 using arel 221 using tzinfo 0331 using activerecord 312 using activeresource 312 using addressable 226 using ansi 141 using bcryptruby 301 using bundler 1018 using coffeescriptsource 113 using execjs 129 using coffeescript 220 using rackssl 132 using json 161 using rdoc 311 using thor 0146 using railties 312 using coffeerails 311 using orm adapter 005 using warden 110 using devise 151 using faker 101 using rails 312 using formtastic 202 using formtasticbootstrap 101 using haml 313 using launchy 205 using restclient 167 using rubyzip 094 using termansicolor 107 using heroku 2140 using jqueryrails 1018 using kaminari 0124 using populator 100 using sass 3110 using sassrails 315 using sequel 3200 using sinatra 10 using sqlite3 134 using sqlite3ruby 133 using taps 0323 using turn 082 using uglifier 110 your bundle is complete use bundle show gemname to see where a bundled gem is installedrubygems versioncobychapple at shiva in codez on mastera gem v1810,"['ruby-on-rails', 'ruby']" +218970,libraryservice for extracting information for microsoft onenote documents does there exist a phpruby library or a webservice that enables programmatic extraction of information from microsoft onenote documentsthe solution is to be implemented in a web application backendi am not looking for windows specific solutions also i am not looking for solutions that require users to download application extensions or installable softwares,"['php', 'ruby']" +218972,adding items to a jlist from arraylist using defaultlistmodel i am trying to add items that are in an arraylist to a jlist which is working when i use the following codeprivate void updatejlist defaultlistmodelstring model new defaultlistmodelstring forperson p personlist modeladdelementptostring clientjlistsetmodelmodel clientjlistsetselectedindex0however if i declare the defaultlistmodel outside of the method the adding increments each item ie instead of adding one of each item it adds multiple items i was just wondering why this happens,['java'] +218976,finding by object key in underscorejs i have the following object join i would like to find it is default object from the array below login label login url login join label join url join theme a home label none icon home url theme a i would like to loop through the array and match the key in this case jointhis is what i have so far var butt to find join var all buttons array above var matching findall buttons functiondefault button return if default butt key 1 is the same as butt to find key 1 this is the first time i have used underscore after hearing so much about itany help more than welcome,['javascript'] +219040,deselecting all elements from a multiselect dropdown in jquery i have a multiselect drop down as following where i have selected the options test 2 and test 3select ideditrec classformselect multiplemultiple namerecoption value6012test 1optionoption value8436test 2optionoption value4689test 3optionoption value6784test 4optionselecti have a button called deselect all when this button is clicked all selected items should be deselected in this case the items i previously selected test 2 and test 3 should now become deselectedhow can i accomplish this using jquery,['jquery'] +219056,how to match surf interest points to a database of images i am using the surf algorithm in c opensurf to get a list of interest points from an image each of these interest points contains a vector of descriptors an x coordinate int an y coordinate int the scale float and the orientation floatnow i want to compare the interest points from one image to a list of images in a database which also have a list of interest points to find the most similar image that is imageip compareto list of imagesip best match comparing the images on an individual basis yields unsatisfactory resultswhen searching stackoverflow or other sites the best solution i have found is to build an flann index while at the same time keeping track of where the interest points comes from but before implementation i have some questions which puzzle me1 when matching images based on their surf interest points an algorithm i have found does the matching by comparing their thistance x1y1x2y2 with each other and finding the image with the lowest total thistance are the descriptors or orientation never used when comparing interest points2 if the descriptors are used than how do i compare them i cannot figure out how to compare x vectors of 64 points 1 image with y vectors of 64 points several images using a indexed treei would really appreciate some help all the places i have searched or api i found only support matching one picture to another but not to match one picture effectively to a list of pictures,['c#'] +219068,connecting to mongodb using pdo driver will i be able to connect to this database using phps php mongodll driverif so could you please provide some sample code as i was not able to get it in any forum,['php'] +219087,change div height on button click what i do wrong why div height did not change thanks in advancehtml head headbody button typebutton onclick documentgetelementbyidchartdivstyleheight 200pxclick mebutton div idchartdiv stylewidth 100 height 50px backgroundcolore8edf2divbodyhtml,"['javascript', 'html']" +219090,xmltextwriter incorrectly writing control characters nets xmltextwriter creates invalid xml filesin xml some control characters are allowed like horizontal tab x9 but others are not like vertical tab xb see speci have a string which contains a utf8 control character that is not allowed in xmlalthough xmltextwriter escapes the character the resulting xml is ofcourse still invalidhow can i make sure that xmltextwriter never produces an illegal xml fileor if it is not possible to do this with xmltextwriter how can i strip the specific control characters that are not allowed in xml from a stringexample codeusing xmltextwriter writer new xmltextwritertestxml encodingutf8 writerwritestartdocument writerwritestartelementtest writerwritevaluehello xb world writerwriteendelement writerwriteenddocumentoutputxml version10 encodingutf8testhello xb worldtest,"['c#', '.net']" +219097,removing whitespaces inside a string i have a string lotst ofnwhitespacern which i have simplified but i still need to get rid of the other spaces in the stringqstring str lotst ofnwhitespacern str strsimplifiedi can do this erase allstr in boost but i want to remain in qt,['c++'] +219114,cannot retry request with a nonrepeatable request entity i am using javahttpclient library and apache transport with it on client side and rails on server side from time to time a get error like this1124 173702469 warnbaseactivity5925 orgapachehttpclientclientprotocolexception at orgapachehttpimplclientabstracthttpclientexecuteabstracthttpclientjava557 at orgapachehttpimplclientabstracthttpclientexecuteabstracthttpclientjava487 at orgapachehttpimplclientabstracthttpclientexecuteabstracthttpclientjava465 at comgoogleapiclienthttpapacheapachehttprequestexecuteapachehttprequestjava58 at comgoogleapiclienthttphttprequestexecutehttprequestjava639 at comskapiskclientupdateuserskclientjava157 at comskapiskclient3callskclientjava76 at comskapiskclient3callskclientjava71 at javautilconcurrentfuturetasksyncinnerrunfuturetaskjava306 at javautilconcurrentfuturetaskrunfuturetaskjava138 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava1088 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava581 at javalangthreadrunthreadjava1019 caused by orgapachehttpclientnonrepeatablerequestexception cannot retry request with a nonrepeatable request entity at orgapachehttpimplclientdefaultrequestdirectorexecutedefaultrequestdirectorjava413 at orgapachehttpimplclientabstracthttpclientexecuteabstracthttpclientjava5 12 morewhat should i do to avoid this,"['java', 'android']" +219122,regex expression to match whole word with special characters not working i was going through this question regexmatch whole wordsit says for match whole word use bpatternbthis works fine for match whole word without any special characters since it is meant for word characters only i need an expression to match words with special characters also my code is as follows class program static void mainstring args string str regexescapehi temp dkfsfdf hi string pattern regexescapetemp var matches regexmatchesstr b pattern b regexoptionsignorecase int count matchescount but it fails because of do we have any workaround for thisthere can be other special characters like space etc,"['c#', '.net']" +219135,are there any tools to convert cc source code to html i want to a tool which can convert cc source code files to html files so far all tools i have found like srchighlite highlight can only do syntax highlighting the critical feature i want is to navigate over code and when my mouse moves over a classname i can click the hyperlink and it takes me to the definition file of the classthen i can package these html files into a mobi file so i can read source code on my kindledoes anybody know,['c++'] +219172,type of character generated by uuid does javautiluuid generates special characters what are the type of each character eg uppercase lower case digits generated by uuid,['java'] +219176,is it possible to change the value of a string added in resstringsxml on android at run time or by code i know we can use resource strings to store values but is it possible to change those values at run time for example i added two new resource elements username and password and i want to change these values at run time or is there an alternate way to store values,['android'] +219200,castconvert bigint to varchar in mysql how might i castconvert bigint to varchar in mysql,['mysql'] +219204,boost spirit semantic actions are evil reading and watching this presentationi have thiscovered this statement basically we are suggested not to use semantic actionsi must admit that i have already felt something like that grammars with semantic actions actually look kinda ugly and when i needed to extendchange them it took a lot of micromanagement exactly with semantic actions the approach with attribute grammar demonstrated in the presentation seems to be much more elegant and promising so i would like to ask is this is an official point should i learn how to work with attribute grammar and avoid semantic actions in more detail if so i would like to ask for some basic maybe even trivial examples demonstrating such an approach the lisp interpreter is too complex for me to chew,['c++'] +219233,how to check if number is divisible by a certain number i am using andengine to add sprites to the screen and come across using the movemodifier methodi have two integers maxduration and mindurationwhat i want to do is when the user gets to a score of a certain incrementlike for example when the user gets to 20the integer changes when the user gets to 40the integer changes so basically count by 20 and every time the score meets a number divisible by 20 the integers change i hope this makes senseis there any method or way to do this i have an updatetime handler that can check the score just about every secondany ideas,['java'] +219243,googles speech recognition api in objectivec i would like to use this google api for testing onlyclientchromiumlangenusmy question is how should i send a post request to this url i am using nsarray paths nssearchpathfordirectoriesindomainsnsdocumentdirectory nsuserdomainmask yesnsstring recdir paths objectatindex0nsurl url nsurl fileurlwithpathnsstring stringwithformatrecordtestflac recdirnsdata mydata nsdata datawithcontentsoffilensstring stringwithformatrecordtestflac recdirnsstring audio nsstring stringwithcontentsoffilensstring stringwithformatrecordtestflac recdirnsmutableurlrequest request nsmutableurlrequest alloc initwithurlnsurl urlwithstringclientchromiumlangenusrequest sethttpmethodpostset headersrequest addvaluecontenttype forhttpheaderfieldaudioxflac rate160request addvalueaudioxflac rate160 forhttpheaderfieldcontenttypensstring requestbody nsstring alloc initwithformatcontent mydatarequest sethttpbodyrequestbody datausingencodingnsasciistringencodingrequest setvaluensstring stringwithformatdmydata length forhttpheaderfieldcontentlengthnshttpurlresponse urlresponse nil nserror error nserror alloc init nsdata responsedata nsurlconnection sendsynchronousrequestrequest returningresponseurlresponse errorerror nsstring result nsstring alloc initwithdataresponsedata encodingnsutf8stringencodingnslogthe answer is resultbut i get only status5idfe6ba68a593f9919f5fd33e819d493a01hypotheses here should be the text whats wrong what should i do,['objective-c'] +219246,how to properly use modal view controller with the xcode 42 storyboard i was wondering how to properly use the storyboard to put up a view controller modally personally i prefer working with xibs but it seems that the storyboard is gaining popularity and will be the way to go in the futurethe way i would normally put up a view controller modally would be like this let us say we have viewcontrollera a for short and viewcontrollerb b for shorti would then normally put a protocol in bh specifying the delegate method when b wants to be thismissed and add the idtheprotocol delegate field as an assign property assuming i am busy in a and i want to present b modally i would writeb b b alloc initwithnibnameb bundlenilbdelegate selfself presentmodalviewcontrollerb animatedyesusing the storyboard i know it is possible to put up a different view controller in a modal way by ctrldragging from a button to a viewcontroller and selecting modal as transition type i am just wondering though where do i set the delegate of the new view controller whats the correct practice of passing things to your modal view controller i do not really know what the whole deal with segues is,['ios'] +219269,how to remove a static cell from a uitableview designed in storyboard the solution is probably very simple but i could not just find it working with storyboard ios 5 i have a tableviewcontroller and a designed static tableview with 5 sections with differents static cell inside each sectionmy question is how to delete a cell programatically in the viewwillappearfor example i have a cell designed for a dateiboutlet uitableviewcell cellfordateand if there is not date i want to remove my cellcellfordatehidden true hide the cell but leave a blank spaceive tried tableview deleterowsatindexpaths did not workanyone got an idea,['iphone'] +219270,any reason to use private instead of private final static on the logback logger when instantiating logger in a spring controller is there any reason to declare it as a static final the logger is not used outside mycontrollerclass i have seen both examples in use but cannot see why i should use one or the other private logger logger loggerfactorygetloggermycontrollerclassvsprivate static final logger logger loggerfactorygetloggermycontrollerclass,['java'] +219282,entity framework code first fluent api adding indexes to columns i am running ef 42 cf and want to create indexes on certain columns in my poco objectsas an example lets say we have this employee classpublic class employee public int employeeid get set public string employeecode get set public string firstname get set public string lastname get set public datetime hiredate get set we often do searches for employees by their employeecode and since there are a lot of employees it would be nice to have that indexed for performance reasonscan we do this with fluent api somehow or perhaps data annotationsi know it is possible to execute sql commands something like thiscontextdatabaseexecutesqlcommandcreate index ix name on i would very much like to avoid raw sql like thati know this does not exist but looking for something along those linesclass employeeconfiguration entitytypeconfigurationemployee internal employeeconfiguration thishasindexe eemployeecode hasindexe efirstname hasindexe elastname or maybe using systemcomponentmodeldataannotations the poco could look like this again i know this does not existpublic class employee public int employeeid get set indexed public string employeecode get set indexed public string firstname get set indexed public string lastname get set public datetime hiredate get set anyone have any ideas on how to do this or if there are any plans to implement a way to do this the code first wayupdate as mentioned in the answer by robba this feature is implemented in ef version 61,['c#'] +219307,microsoftofficeinteropexcel does not work on 64 bit i have encountered a problem when developing on ms visual web developer 2008 express eddeveloping aspnet c on windows7 64 bit osi am trying to open an excel document but it gives me old format or invalid type library exception from hresult 0x80028018 type e invdatareadi did configured the build to all processors any cpu x64 x86 but it does not work i searched the answer on the internet but could not find out how to handle itthe weird thing is the same code worked on the same system when i developed on microsoft visual c 2010 express how come is not it the same dll working behinddo i need to change that com dll so it will work on x64 systemplease help me what can i domy code isusing excel microsoftofficeinteropexcelxlapp new excelapplication logopenning excelfilenamexlworkbook xlappworkbooksopenexcelfilename 0 true 5 true microsoftofficeinteropexcelxlplatformxlwindows t false false 0 true 1 0xlworksheet excelworksheetxlworkbookworksheetsget item2,['asp.net'] +219312,calendar set year issue i tried the following piece of codecalendar c1 calendargetinstancec1setcalendaryear 0c1setcalendarday of year 1date d1 c1gettimecalendar c2 calendargetinstancec2settimed1c2setcalendaryear 2001c2setcalendarday of year 1systemoutprintlnc2gettimetostringcalendar c3 calendargetinstancec3setcalendaryear 20c3setcalendarday of year 1date d2 c3gettimecalendar c4 calendargetinstancec4settimed2c4setcalendaryear 2001c4setcalendarday of year 1systemoutprintlnc4gettimetostringthe result iswed jan 01 234700 cet 2001mon jan 01 234700 cet 2001what is wrong should not i use calendar in this way for setting year,['java'] +219317,send ioctl to windows device driver createfile fails i want to send an ioctl command to a pcsc reader connected to my computer win7 64 bitin order to send an ioctl command i need a handle to the device which i am unable to createthe device is listed as omnikey 1021 in the device manager the physical device object name is deviceusbpdo15 using the winobj tool i can detect 2 symlinksusbvid 076bpid 10215291f69900150dd5230ba8a11d1bf5d0f805f530usbvid 076bpid 10215291f699001a5dcbf10653011d2901f00c04fb951edmy problem i cannot create a valid handle to this device with the createfile functioni found several possible formats on msdngoogle to use as the lpfilename param of the createfile function but none of them seem to workdeviceusbpdo15deviceusbpdo15globaldeviceusbpdo15globaldeviceusbpdo15usbpdo15usbvid 076bpid 10215291f69900150dd5230ba8a11d1bf5d0f805f530usbvid 076bpid 10215291f69900150dd5230ba8a11d1bf5d0f805f530globalusbvid 076bpid 10215291f69900150dd5230ba8a11d1bf5d0f805f530globalusbvid 076bpid 10215291f69900150dd5230ba8a11d1bf5d0f805f530usbvid 076bpid 10215291f699001a5dcbf10653011d2901f00c04fb951edusbvid 076bpid 10215291f699001a5dcbf10653011d2901f00c04fb951edglobalusbvid 076bpid 10215291f699001a5dcbf10653011d2901f00c04fb951edglobalusbvid 076bpid 10215291f699001a5dcbf10653011d2901f00c04fb951edcode sampleinclude iostreaminclude windowshint main int argc char argv handle handle createfile ldeviceusbpdo15 0 file share read file share write null open existing 0 file flag overlapped null if handle invalid handle value stdcout invalid handle stdendl else stdcout handle stdhex handle stdendlnotesthe returned handle is always invalidalways running as administrator so the privileges should not be a problemeditsolutionthe pcsc service takes exclusive ownership of the devices so any attempt to call createfile will always failthe solution is a kernel space driver this allows you to pass irps to the driver i was able to implement a kmdf filter driver to alter data sentreceived tofrom the device,['c++'] +219327,does scalajava has something like stringio from python i would like to know that if javascala has the string object that could act as file as stringio in python i figure that it would be better than writing and reading alot of temporary file i prefer scala but java one should be fine too,['java'] +219337,what is the best process for fetching new content using json what would be the best way to fetch new content on a website with json i got the following system in my mind loopedclient do i have new content server client nope server client do i have new content server client yes contentid x server client get content with id x serverclient jim morrison serveris this the best way the application will be used for over 10 users how does facebook do this and still keep everyone super fast upto date,['php'] +219385,burst memory usage in java i am trying to get a handle on proper memory usage and garbage collection in java i am not a novice programmer by any means but it always seems to me that once java touches some memory it will never be released for other applications to use in that case you have to make sure your peak memory is never too high or your application will continually use whatever the peak memory usage wasi wrote a small sample program trying to demonstrate this it basically has 4 buttonsfill class scope variable biglist new arrayliststring with about 250 long string itemscall biglistclearreallocate the list biglist new arrayliststring again to shrink the list sizea call to systemgc yes i know this does not mean that gc will really run but it is what we haveso next i did some testing on windows linux and mac os while using the default task monitors to check on the processes reported memory usage here is what i foundwindows pumping the list calling clear and then calling gc several times will not reduce memory usage at all however reallocating the list using new and then calling gc several times will reduce the memory usage back to starting levels imo this is acceptablelinux i used mint 11 thistro with sun jvm same results as windowsmac os i followed the sames steps as above but even when reinitializing the list calls to gc seemingly have no effect the program will sit using hundreds of mb of ram even though i have nothing in memorycan anyone explain this to me some people have told me some stuff about heap memory but i still do not fully understand it and i am not sure it applies here from what i have heard about it i should not be seeing the behavior i am on windows and linux anywaysis this just a difference in the way mac oss activity monitor measures memory usage or is there something else going on i would prefer to not have my program idling with tons of ram usage thanks for your insight,['java'] +219422,aspnet setting width of databound column in gridview i have a gridview which uses boundfield for columns i am trying to set a maxwidth for my userinfo columni have tried many many ways but non of them work below is the code for my gridview aspgridview idgridview1 autogenerateeditbuttontrue ondataboundgv databound runatserver datasourceidsqldatasource1autogeneratecolumnsfalsecolumns aspboundfield headertextuserid datafielduserid sortexpressionuseridaspboundfield aspboundfield headertextusername datafieldusername sortexpressionusernameaspboundfield aspboundfield headertextuserinfo datafielduserinfo sortexpressionuserinfoaspboundfield columnsaspgridviewlooking for suggestions on how i can set the width of a specific column which is my userinfo column,"['c#', 'asp.net']" +219424,javascript dateparse difference in chrome and other browsers i have a date string 20124t0900270 fetched from the graphfacebook apiwhen i run var timestamp dateparsefacebookdatein chrome i get a timestamp that relates to the date perfectbut in every other major browser i get nan surely all these browsers use the same javascript parse function rightcan anybody explain why the same javascript function give different resultsand can anybody also tell me how to fix this issuethanks in advancealex,['javascript'] +219429,update statement geography column sql server is it different to update geography column in sql server than a regular field varchar can you please provide a sample statement to do this thanks,['sql'] +219432,debugging crash in coregraphicsmapkit i am getting an intermittent crash when my application runs on an iphone all the crashes are identical and involve mkmapview overlays mkcircleviews in some wayfrom a typical iphone 4s crash reportreport headerhardware model iphone41process elgps01 1021path varmobileapplications61288e1574b545b9a9e0b58c767816elgps01appelgps01identifier elgps01version code type arm nativeparent process launchd 1datetime 20122 155941065 0os version iphone os 501 9a405report version 104exception type exc bad access sigsegvexception codes kern invalid address at 0x0crashed thread 6and the crashed threadthread 6 name thispatch queue comapplerootdefaultprioritythread 6 crashed0 0 0 01 coregraphics 0x319a87c2 0x319670 2682262 coregraphics 0x3199a9e6 0x319670 2114303 mapkit 0x37ec3564 0x37e6f0 3454 mapkit 0x37ec3652 0x37e6f0 3456825 mapkit 0x37ecc0a4 0x37e6f0 3810926 quartzcore 0x3341be18 0x33410 486647 quartzcore 0x334d77e0 0x33410 8171208 quartzcore 0x3346af24 0x33410 3725169 libthispatchdylib 0x3797e892 0x3797b0 1448210 libsystem cdylib 0x360e31ca 0x360d90 4141811 libsystem cdylib 0x360e30a0 0x360d90 41120when the application crashes whilst my iphone is connected to my laptop i get the following in my output panelwarning check safe call could not restore current framewarning unable to restore previously selected framethe debugger gives me nothing at all and the issue navigator shows a crashed thread with nothing on the stackthere is a very simple project highlighting the problem here1ndivisiblemkoverlaybuggiti am not sure how to approach this is there any information here that i can use it seems the crash is originating deep in the framework,"['iphone', 'objective-c', 'ios']" +219436,android how to use adapter for listview without extending listactivity i have an application with tabs in one tab i need to put data strings in rows to do so i chose tablelayout but when i wanted to use a contextmenu on its rows it does not work i can show the contextmenu onlongclick but the problem is that i cannot get the info about the selected row to edit or delete the selected row then i read in a thiscussion that using listview is better than tablelayout if we have many rows but the examples i saw extend listactivity but i do not want to do this so when i try working on a listview without extending listactivity i do not know how to do it what i mean is that i have never used listview before so i try different examples i found on the internet to understand it but it is not working heres what i did so far for the listviewstring itemsgetressourcesgetstringarrayrarraresolution resolution is an array of stringslistview lvlisteview findviewbyidridlistviewvsetadapternew arrayadapterstringthis androidrlayoutsimple list item 1 itemswhen i compile it i get a list with elements of my array in it but first i want to change the color of text which i cannot and secondly i want to add rows dynamically to the list which i do not know how to do either i think i have to use an adapter to do it but i do not know how can someone please guide me through this i just want to know how to attach my list to an adapter whichll allow me to dynamically add rows add contextmenu etc,['android'] +219446,gradual engagement persistent guest user with devise i am trying to set up gradual engagement in my utility app which people can use without registering eg notepadcc and jsfiddlenet and i plan to create a guest user with devise for the user when he writes to the appi found this guide on the devise wiki which shows how to create a guest user for the duration of the browser session what i want is for the user to continue using the same guest account in subsequent visits until he signs up maybe when i introduce subscription plans for more featureshow can i modify whats in the guide to make this possiblecode in the guide linked above file appcontrollersapplication controllerrbclass applicationcontroller actioncontrollerbase protect from forgery if user is logged in return current user else return guest user def current or guest user if current user if sessionguest user id logging in guest userdestroy sessionguest user id nil end current user else guest user end end find guest user object associated with the current session creating one as needed def guest user userfindsessionguest user idnil sessionguest user id create guest userid sessionguest user id end called once when the user logs in insert any code your application needs to hand off from guest user to current user def logging in end private def create guest user you usercreatename guest email guest timenowto irand99email addresscom usavefalse u endendand using it in the controllerthinguser current or guest userthingsave,"['ruby-on-rails', 'ruby']" +219475,why is this code not thread safe in code snippet below declaring the dothings method as static would make the class threadsafe is the reason for this that if multiple testseven threads are started and since x is a static variable a race condition could occur public class testseven extends thread private static int x public synchronized void dothings int current x current x current public void run dothings public static void mainstring args testseven t new testseven thread thread new threadt threadstart,['java'] +219495,coffeescript and haml with unobtrusive javascript dataremote in rails 31 i searched le interwebs but i have not found someone experiencing the same problem as me so i propose my question herei just started using rails 31 with compass haml and coffeescript and ran into a problem when i rename my controllerspecific javascript file located in appassetsjavascriptindexjs to indexjscoffee and translate the javascript code to coffeescript everything works as expected the file is requested by the browser and compiled on the fly into javascript changes in the coffeescript file do also trigger recompilationhowever when i try to do this with unobtrusive javascript remote true and rename the already working javascript file located in the view folder appviewsindexindexjshaml to indexjscoffeehaml and translate the included code rails does not recognize it as a coffeescript that needs to be compiledwhat am i doing wrong do i actively have to enable coffeescript evaluation for the view where,['ruby-on-rails'] +219499,why cannot i convert attribute to nested element i am reading settings from appconfig i just figured out how to work with configurationsection configurationelementcollection and configurationelelementappconfigxml version10 encodingutf8 configuration configsections sectiongroup namenotificationsettingsgroup section namemailtemplates typeprojectlibconfigurationmailtemplatesection projectlib allowdefinitioneverywhere allowexedefinitionmachinetoapplication requirepermissionfalse sectiongroup configsections notificationsettingsgroup mailtemplates items mailtemplate nameactionchain subjectsubject blabla bodybody blablabody mailtemplate items mailtemplates notificationsettingsgroup startup supportedruntime versionv40 skunetframeworkversionv40 startup configurationmy c codepublic class mailtemplatesection configurationsection configurationpropertyitems isdefaultcollection false public mailtemplatecollection mailtemplates get return mailtemplatecollectionthisitems set thisitems value configurationcollectiontypeofmailtemplateelement additemname mailtemplate collectiontype configurationelementcollectiontypeaddremoveclearmappublic class mailtemplatecollection configurationelementcollection protected override configurationelement createnewelement return new mailtemplateelement protected override object getelementkeyconfigurationelement element return mailtemplateelement elementname public class mailtemplateelement configurationelement configurationpropertyname defaultvalue action iskey true isrequired true public string name get return stringthisname set thisname value configurationpropertysubject defaultvalue subject iskey false isrequired true public string subject get return stringthissubject set thissubject value configurationpropertybody defaultvalue body iskey false isrequired true public string body get return stringthisbody set thisbody value and working codeclass program static void mainstring args configuration config configurationmanageropenexeconfiguration configurationuserlevelnone var mailtemplatessection configgetsectionnotificationsettingsgroupmailtemplates as mailtemplatesection all works when i am declaring fields as attributes in xml but when i try to convert attributes into nested element property body is not a configurationelement error occurswhat am i doing wrong,"['c#', '.net']" +219531,play m3u8 video in android i want to live streaming the video and it is in m3u8 format so i tried the below codepublic class streamingplayer extends activity implementsonbufferingupdatelistener oncompletionlisteneronpreparedlistener onvideosizechangedlistener surfaceholdercallback private static final string tag streamingplayerclassgetsimplename private int mvideowidth private int mvideoheight private mediaplayer mmediaplayer private surfaceview mpreview private surfaceholder holder private string path private boolean misvideosizeknown false private boolean misvideoreadytobeplayed false override protected void oncreatebundle savedinstancestate todo autogenerated method stub superoncreatesavedinstancestate setcontentviewrlayoutmediaplayer 2 mpreview surfaceview findviewbyidridsurface holder mpreviewgetholder holderaddcallbackthis holdersettypesurfaceholdersurface type push buffers private void playvideo docleanup try todo set path variable to progressive streamable mp4 or 3gpp format url http protocol should be used mediaplayer can only play progressive streamable contents which basically means 1 the movie atom has to precede all the media data atoms 2 the clip has to be reasonably interleaved path httplivexboodangxapichannellivestreamcom30playlistm3u8 if path tell the user to provide a media file url toast maketext this please edit mediaplayerdemo video activity and set the path variable to your media file url toastlength longshow logepath path path create a new media player and set the listeners mmediaplayer new mediaplayer mmediaplayersetdatasourcepath mmediaplayersetthisplayholder mmediaplayersetonbufferingupdatelistenerthis mmediaplayersetonpreparedlistenerthis mmediaplayerprepare mmediaplayersetoncompletionlistenerthis mmediaplayersetonvideosizechangedlistenerthis mmediaplayersetaudiostreamtypeaudiomanagerstream music catch exception e logetag error egetmessage e public void onbufferingupdatemediaplayer arg0 int percent logdtag onbufferingupdate percent percent public void oncompletionmediaplayer arg0 logdtag oncompletion called public void onvideosizechangedmediaplayer mp int width int height logvtag onvideosizechanged called if width 0 height 0 logetag invalid video width width or height height return misvideosizeknown true mvideowidth width mvideoheight height if misvideoreadytobeplayed misvideosizeknown startvideoplayback public void onpreparedmediaplayer mediaplayer logdtag onprepared called misvideoreadytobeplayed true if misvideoreadytobeplayed misvideosizeknown startvideoplayback public void surfacechangedsurfaceholder surfaceholder int i int j int k logdtag surfacechanged called public void surfacedestroyedsurfaceholder surfaceholder logdtag surfacedestroyed called public void surfacecreatedsurfaceholder holder logdtag surfacecreated called playvideo override protected void onpause superonpause releasemediaplayer docleanup override protected void ondestroy superondestroy releasemediaplayer docleanup private void releasemediaplayer if mmediaplayer null mmediaplayerrelease mmediaplayer null private void docleanup mvideowidth 0 mvideoheight 0 misvideoreadytobeplayed false misvideosizeknown false private void startvideoplayback logvtag startvideoplayback holdersetfixedsizemvideowidth mvideoheight mmediaplayerstart in logcat it shows onbufferingupdate percent100 but i cannot see the videoaudio is working but suddenly it was struck and i tried this video link indexm3u8 it is working but my video link is not working and i changed httplive instead of http but no useand i saw this answer also android video stream mms and m3u8in above link it shows the video cannot be played message,['android'] +219536,component with parent is there any way to use bean parentsomeparent with component annotation creating spring beans using annotationi would like to create spring bean that has spring parent using component annotationis it possible,['java'] +219537,prohibit the call to systemexit i am trying to prohibit the call to systemexitint in some jarsthese jars will be developed by external teams and loaded by our container application my first reflex is to use the java security managerdjavasecuritymanagerdjavasecuritydebugallwith the simplest userhomejavapolicy file grant although i can no longer call such as systemgetproperties since i do not have javautilpropertypermission i can do a systemexit 0 the option javasecuritydebugall gives the following consolescl getperms protectiondomain file mybinpath no sign certificatessunmisclauncher appclassloader 10385c1no principalsjavasecuritypermissions 15b7986 javalangruntimepermission exitvmjavaiofilepermission mybinpath readwhy do all classes in mybinpath have javalangruntimepermission exitvm granted thanks,['java'] +219539,when focusing on an input field with a 3px border all the other input fields keep moving i added a css focus on input field which has a default style which contains border and shadow when i focus on the input field the input field below moves down slightly i tried adding a height to the li but that did not work css inputtypetext inputtypepassword border 1px solid c boxshadow 0 1px 3px rgba0 0 0 02 minheight 22px padding 3px checkout inputfocus border3px solid 6b991c padding2px ul classclearfix li label fortitle classcheckoutlabeltitle strong classrequiredinfostronglabel select nametitle idtitle classrequired option selectedselectedplease selectoption option valuemrmroption option valuemrsmrsoption option valuemissmissoption option valuedrdroption select li li classactive label classcheckoutlabel forfirstnamefirst name strong classrequiredinfostronglabel div classcheckoutinputlarge input typetext namefirstname idfirstname classrequired div li li label forlastname classcheckoutlabellast name strong classrequiredinfostrong label div classcheckoutinputlarge active input typetext namelastname idlastname classcheckoutinput1 required div li li label foremail classcheckoutlabelemail strong classrequiredinfostronglabel div classcheckoutinputlarge input typetext nameemail idemail classrequired div li li label forphonenumber classcheckoutlabelphone number strong classrequiredinfostronglabel div classcheckoutinputlarge input typetext namephonenumber idphonenumber classcheckoutinput1 required div li li input typecheckbox namesmsalert idsmsalert label forsmsalert clasmsalertlabeli wish to receive sms alerts on my order statuslabel li li label classcheckoutlabelare you a br business customer strong classrequiredinfostronglabel input typeradio namebusinesscustomer idbusinesscustyes valueyes classradio required label classbusinesscustomerlabels forbusinesscustyesyeslabel input typeradio namebusinesscustomer idbusinesscustno valueno classradio required checkedchecked label classbusinesscustomerlabels forbusinesscustnonolabel li ul,"['html', 'css']" +219553,what is the most maintained newest framework in net for writing acceptance tests i am practicing tdd for some time now i want to advance my skills and start doing atddi read about frameworks for ruby and java but did not hear much about netwhat is the most maintained newest framework in net for writing acceptance testsedit after reading more i want to note that i was relating acceptance testing for websites and web appliation any maybe it has to be considered gui testing as well,['.net'] +219563,jquery ui slider with control buttons i am trying to add control buttons on to the jquery ui slider but cannot get it to workcan anyone see what im doing wrong herefunction var gmin 1 var gmax 500 slider slider value5 min gmin max gmax step 1 slide function event ui donate amount label span html a uivalue donate amount label span html a slider slider value val slider slider value downclickfunction var s slider sslidervalue sslidervalue sslider step the slider works fine and the values get updated but when you click the down link nothing happens to the scrollbar i would like it to move up one step when the down link is clickedthankspete,['jquery'] +219568,using null as a key value in a map i would like to know if using null as a key in a map object is considered good style and if not what are the alternatives,['java'] +219615,unix c compilers that do not understand c o autoconfautomake are at pains to support ancient c compilers that did not understand the simultaneous use of the c and o options create an object file with this name there is am prog cc c o and a special wrapper script and the automake manual warns you to use them if you want to use subdirobjects modethere is not an am prog cxx c o it is not hard to modify am prog cc c o to test the c compiler instead but i wonder if it is necessary was there ever a unix c compiler cfront maybe that did not support simultaneous use of c and o come to that just how old are the c compilers that do not support it was there ever a c89supporting compiler with this problem for instance,['c++'] +219632,converting nsarray contents to a varargs with arc for use with nsstring initwithformat we have some code today that takes an nsarray and passes it as a argument list to nsstring initwithformatarguments and were trying to get this to work with arc heres the code were usingnsstring format item s and item s retrieved elsewherensarray args nsarray arraywithobjects1 2 nil retrieved elsewhere char argslist char mallocsizeofnsstring argscountargs getobjectsid argslistnsstring message nsstring alloc initwithformatformat argumentsargslist autoreleasefreeargslistany recommendations on how to make this arc compliant or were even open to a better way of doing it,['objective-c'] +219633,how to add class to an image tag rails helper i have the following code image tag iteratorimageurlsmall class img preview but the rendered html showsimg srcactiveshotels13smallclean wavejpg1317675452 altclean wavewhy the class attribute is not therethank you,['ruby-on-rails'] +219650,automatically precompile assets before pushing to heroku is it possible to automatically precompile my assets in a rails app before pushing out to heroku i always forget to do it so it would be nice if when i typed git push heroku master it would first run rake assetsprecompile git commit add git commit a m precompile or something to that effecthas anyone achieved such a solution possibly without hooks though i suspect that is the only way,"['ruby-on-rails', 'ruby']" +219673,why is the comma optional in c variadic function declarations is there a difference in these two declarationsint foo int a andint foo int a if there is no difference what was the point of making the second syntactically valid,['c++'] +219700,modernizr vs html shiv if i only need older browsers to recognize html5 tags which should i use modernizr or the popular html5 shivand also if i do not need to style this html5 tags do i need the browsers to recognize them anyways or is it only necessary when adding css to these tagsthanks,['javascript'] +219704,proper way to close a usb accessory connection what is the proper way to close a connection to a usbaccessory in androidit seems the even in the stock google example if i connect and accessory exit the app and then go back to it the connection is not reestablishedlooking closely it seems that after calling close on the filedescriptor it would not open again and a could not open devusb accessory log is emittednot calling close is a bad option as a thread blocking on read will not be released upon physical thisconnection reconnection of the device everything is okit seems really surprising that the simple usecase of exiting the app and then opening it again does not work in the reference application and even more surprising if it is not feasiblei am using a nexus s running stock android 236,['android'] +219740,optimizing stdvector operator vector access when it becomes a bottleneck gprof says that my high computing app spends 53 of its time inside stdvector operator unsigned long 32 of which goes to one heavily used vector worse i suspect that my parallel code failing to scale beyond 36 cores is due to a related memory bottleneck while my app does spend a lot of time accessing and writing memory it seems like i should be able or at least try to do better than 52 should i try using dynamic arrays instead size remains constant in most cases would that be likely to help with possible bottlenecks actually my preferred solution would be to solve the bottleneck and leave the vectors as is for convenience based on the above are there any likely culprits or solutions tcmalloc is out,['c++'] +219749,reading whats available from socket without blocking i am working on a server which reads data sent by the client but the size is not known neither can i change the client to send the sizei want to read the data from client till it blocks and waits for servers response i tried using available it works sometimes but sometimes it just returns zero even when there is some data in stream whilelen inavailable 0 inreadb0lenis there any way to do this in java i am aware of asynchronous methods but have never tried that so if someone can provide a short example,['java'] +219750,does filecopy prevent another app from writing to the file i want to copy some text files that are written by another app but i do not want to do anything to prevent the other app from writing to these filesi am using filecopy from the systemio namespace c net framework 20i checked msdns documentation but nothing is specifically stated about the method that filecopy uses is it a wrapper to an unmanaged api calldoes filecopy lock or block the file being copied in any waythanks in advance for any info about this,['c#'] +219780,how can i make iframe respect zindex in ie i have a youtube iframe element in my website but it is next to my menu items when i hover over a menu item a submenu opens that partially covers the iframe because of it is position that is not it is specific function obviously this works fine in firefox but as usual it does not in ie here the iframe covers the menu making it basically unreadable is there an option i need to add to the iframe to make it work or is it just plain impossibletesting with ie9 at the moment,['css'] +219791,how to check if a html5 input is supported i want to check in my website if the visitors browser support a html5 input type how should i do it,['javascript'] +219807,is there any way to enable or thisable the spring bean definition in applicationcontextxml file is there any way to enable or thisable a java bean definition in application contextbean idenbean clascomenbeanbeanname property nameprop1beanor is there any way to load the bean conditionally defined in application context,['java'] +219817,how do i implement asynchrounous caching were using the following pattern to handle caching of universal objects for our aspnet applicationprivate object systemconfigurationcachelock new objectpublic systemconfiguration systemconfiguration get if httpcontextcurrentcachesystemconfiguration null lock systemconfigurationcachelock if httpcontextcurrentcachesystemconfiguration null httpcontextcurrentcacheinsertsystemconfiguration getsystemconfiguration null datetimenowaddminutes1 cachenoslidingexpiration new cacheitemupdatecallbacksystemconfigurationcacheitemupdatecallback return httpcontextcurrentcachesystemconfiguration as systemconfiguration private void systemconfigurationcacheitemupdatecallbackstring key cacheitemupdatereason reason out object expensiveobject out cachedependency dependency out datetime absoluteexpiration out timespan slidingexpiration dependency null absoluteexpiration datetimenowaddminutes1 slidingexpiration cachenoslidingexpiration expensiveobject getsystemconfigurationprivate systemconfiguration getsystemconfiguration load system configuration the problem is that when under load 10 users we see a huge jump in ttfb as the cacheitemupdatecallback blocks all the other threads from executing until it has finished refreshing the cache from the databaseso what i figured we needed is solution that when the first thread after an expiry of the cache attempts to access it an asynchronous thread is fired off to update the cache but still allows all other executing threads to read from the old cache until it has sucessfully updatedis there anything built into the net framework that can natively handle what i am asking or will i have to write it from scratch your thoughts pleasea couple of thingsthe use of the httpcontextcurrentcache is incidental and not necessarily essential as weve got no problem using private members on a singleton to hold the cached dataplease do not comment on the cache times sproc effeciency why were caching in the first place etc as it is not relevent thanks,"['c#', 'asp.net']" +219829,how to open files given as command line arguments in python i want my py file to accept file i give as input in command line i used the sysargv and also fileinput but i am not getting the output,['python'] +219833,formatting an array value inside a heredoc i was wondering why i cannot do something like number formatrowmy number inside a heredoc is there any way around this without having to resort to defining a variable like mynumber below looked at but found nothingcodeforeach dbh querysql as row mynumber number formatrowmy number table eot tr tdrowmy numbertd works tdmynumbertd works tdnumber formatrowmy numbertd does not work treotendforeach,['php'] +219850,how can i run android tests with sbt i developed for my application a small suite of android tests written in scala that uses the robotium library the suite is for all intents and purposes a standard android junit test project and runs successfully if launched from eclipsei have already successfully built and run my main android application with sbt androidplugin the main application is located in projectdirsrcmain i was also able to successfully build my android test application that is located in the projectdirtestssrcmain directory i checked the emulator and the test application appears to have been correctly installed with androidplugins testsandroidinstallemulator command however when i try to run the test project via sbt testsandroidtestemulator i gettest results for instrumentationtestrunnertime 01ok 0 testshow i can get sbt androidplugin to recognize that the project contains junit tests and run them,['android'] +219860,ajax loading for complex projects my problem is actually not the ajax loading itself more the capability to load it without javascript i mean i cope easily when i code my whole project just based on ajaxavailability or just without the use of ajaxedit although arend already had a more or less valid answer at the same time there is no direct answer to this question however i would like to see some other approaches of developers for scenarios like mine though even just a few links can helpbasically i just get frustrated coding everything twice on the same page to make sure that both users without and with javascript enabled have the same experience it is annoying and i was always wondering how others solve this problemwhen i update for example two divs with dependency on the same variables it gets messy heres an examplenonjsversionrequire classobjectclassphpanother var somethingclass new classobject postvariable just an example to show that this is dynamic i am aware of injectionfunction classreturnsth returns 1ifisset post echo div idonemodule 1 says require module onephp echo div echo br br echo div idtwomodule 2 says require module twophp echo divnow in module twophp and module twophp i have code that executes differently depending on the return variable of functionlikeiffunction 1 another var something do stuffelse do other stuff now as this works easily with a reload when i want to load the two modules on keyupentersubmit or whatever i have basically a few problemsi have to send the post variables manually to the modules to use themi have to reexecute the class it is methods and make a link require once to them in each of the modulefilesas another var is not existent in the modules i would have to send this variable to each modules too with post for example and then before it can be used i would have to change it like another var postanother vari find this mildly annoying and i wonder how you guys do that i hope my way of coding is not too silly but i cannot think of another way it is probably hard to relate to my very basic example but to bring a whole project with the code would be too much to sum it up i am looking for a better way to code and clean this mess up there must be a way i thought about sessions but for compatability i do not want to rely on them either if someone does not allow cookiesin case you cannot relate to what i am trying to accomplish with that way of having my code assembled i will explain a scenario i am facing quite a lot not important if you already understand my miserybasically i have my indexphp page where everything gets executed with the html body and css styling and so on this page expects some variables that get set from the page that requires the index like another var in my example now other variables can get set too from a form for example depending on that different classes and methods load new variables arrays that get used in whileloops in my modules to echo everything out hope that is not too abstract think of a booking system where some variables are set from the page you are coming from the event you want to book and then a few more things get set by the user a timespan some preferences in the end it is supposed to show results from the database all the way to the endresult you can say the user narrows the results from step to step,"['php', 'jquery']" +219862,android 40 api level 14 vs google apis google inc api level 14 what is the difference when i want to create a android virtual machine on my computer there is two options to select a target device both of them are for same api level so which one should i select what is the differences between them,['android'] +219925,putting a clplacemark on map in ios 5 in ios 5 there is a new way to forward geocode address converting address like 1 infinite loop ca usa to latlang address more info on this is here has anybody tried to put the forward geocoded clplacemark object on a mkmapview i have a clplacemark object after geocoding but have no clue how to put it on a mapi would appreciate any type of help google is of no help so far,['ios'] +219935,is there a gem to test rethis logic in rails like database cleaner or the default clearing of the data store after a test run i searched and could not find one it could be either a separate test data store or just something simple that namespaces all rethis commands into a test namespaceif anyone knows of any lemme know otherwise i will write one and os it,['ruby-on-rails'] +219944,fast repeat takewhile causes infinite loop how can i make the following observable repeat until streamdataavailable is falsecurrently it looks like it never stopsasyncreadchunk and observablereturn inside the defer section make onnext call then oncompleted callwhen repeat receives the onnext call it passes it to takewhile when takewhiles is not satisfied it completes the observable but i think the oncompleted that comes right after the onnext is so fast that it makes repeat to resubscribes to the observable and causes the infinite loophow can i correct this behaviourpublic static iobservablebyte asyncreadthis networkstream stream int buffersize return observabledefer try return streamdataavailable asyncreadchunkstream buffersize observablereturnnew byte0 catch exception return observablereturnnew byte0 repeat takewhiledatachunk index datachunklength 0,['c#'] +219946,it appears i have run out of 32bit address space what are my options i am trying to take the covariance of a large matrix using numpycov i get the following errorpython224980xa02e3720 malloc mmapsize1340379136 failed error code12 error cannot allocate region set a breakpoint in malloc error break to debugprocess python bus errorit seems that this is not uncommon for 32bit machinesbuilds i have a 64bit mac os x 105 but using a 32bit python and numpy build as i had trouble building numpyscipymatplotlib on a 64bit installationso at this point what would be the recommended course of action that will allow me to proceed with the analysis if not switching machines none others are available to me at the moment export to fortranc is there a simpler solution thanks for your suggestions,['python'] +219961,simplify javascript code how can i simplify this code if needed i can rename the php files to be the same exact name as the id element so locus can be used jszipid elementphp or whatever thats only if that helps out script typetextjavascript readyfunction locusautocompletejszipusphp matchcontains true matchfirst true mustmatch false selectfirst false cachelength 10 minchars 1 autofill false scrollheight 150 width 185 max 20 scroll true loccaautocompletejszipcaphp matchcontains true matchfirst true mustmatch false selectfirst false cachelength 10 minchars 1 autofill false scrollheight 150 width 185 max 20 scroll true locukautocompletejszipukphp matchcontains true matchfirst true mustmatch false selectfirst false cachelength 10 minchars 1 autofill false scrollheight 150 width 185 max 20 scroll true locauautocompletejszipauphp matchcontains true matchfirst true mustmatch false selectfirst false cachelength 10 minchars 1 autofill false scrollheight 150 width 185 max 20 scroll true locieautocompletejszipiephp matchcontains true matchfirst true mustmatch false selectfirst false cachelength 10 minchars 1 autofill false scrollheight 150 width 185 max 20 scroll true locotautocompletejszipotphp matchcontains true matchfirst true mustmatch false selectfirst false cachelength 10 minchars 1 autofill false scrollheight 150 width 185 max 20 scroll true script,"['javascript', 'jquery']" +219966,single line comments in ansic i am used to to mark a single line comment from java and visual studio and was surprised that this does not exist for ansic using my comment is quite annoying is there any other way to mark a single line comment when using ansic,['c'] +219967,clear text area in onselect event i have scriptvinanghinguyen images bbocdevalvinanghinguyen images bbocdevalvinanghinguyen final bbcodei want clear text area idvinanghinguyen images bbocde before add value to it but textarea add add add add and value and not clear i want clear it before add valuei use uploadify here is my functionscript typetextjavascriptdocumentreadyfunction vinanghinguyen bbcodevinanghinguyen final bbcodevinanghinguyen linkvinanghinguyen final derect linkresponse file uploaduploadify uploader site full urluploadifyuploadifyswf script site full urluploadifyuploadifyphp cancelimg site full urluploadifycancelpng folder datapicture upload2011 auto false multi true buttontext oncomplete functioneventidfileobjresponsedata vinanghinguyen bbcodeimgresponseimgn vinanghinguyen final bbcodevinanghinguyen final bbcodevinanghinguyen bbcode vinanghinguyen derect linkresponsen vinanghinguyen final derect linkvinanghinguyen final derect linkvinanghinguyen derect link vinanghinguyen images bbocdevalvalvinanghinguyen final bbcode vinanghinguyen images derect linkvalvinanghinguyen final derect link vinanghinguyen resultshow uploadifyqueueheight5 onselect functioneventidfileobj vinanghinguyen images bbocdeval vinanghinguyen resulthide uploadifyqueueheight315 script,['jquery'] +219970,reference as class member initialization i want to initialize a property of a class that holds a reference to another class by passing such a reference as a parameter to the constructor however i receive an error ataxsquarebank must be initialized in constructor basemember initializer listawhat is wrong in the following code of the classes ifndef taxsquare hdefine taxsquare hinclude squarehclass bankclass taxsquare public square public taxsquareint int bank virtual void process private int taxamount bank bankendifinclude iostreaminclude taxsquarehinclude playerhinclude bankhusing namespace stdtaxsquaretaxsquareint anid int amount bank thebank squareanid taxamount amount bank thebankifndef bank hdefine bank hclass bankpublic bankint int int void getmoneyint void givemoneyint void granthouse void granthotelprivate int summoney int numofhouses int numofhotelsendif,['c++'] +219985,ios bubble popup menu similar to itunes could anyone provide some guidance on how to implement that speechbubble like popup menu when you click more in the iphone ipod application toolbar,"['iphone', 'objective-c', 'ios']" +219994,is func appropriate to use as a ctor arg when applying dependency injection examplepublic class businesstransactionfactoryt where t ibusinesstransaction readonly functype ibusinesstransaction createtransaction public businesstransactionfactoryfunctype ibusinesstransaction createtransaction createtransaction createtransaction public t create return t createtransactiontypeoft container setup code utilising samepublic class dependencyregistration registry public dependencyregistration scanx xassembliesfromapplicationbasedirectory xwithdefaultconventions xaddalltypesoftypeofrepository xconnectimplementationstotypesclosingtypeofirepository scanx xassembliesfromapplicationbasedirectory xaddalltypesofibusinesstransaction fortypeofbusinesstransactionfactoryusetypeofbusinesstransactionfactory forfunctype ibusinesstransactionusetype ibusinesstransactionobjectfactorygetinstancetype forobjectcontextuse new managemententities what do you think,['c#'] +220000,aspnet the specified network password is not correct i have in my dev machine a wcf client which requires certificate and it is working fineafter the deployment to production server i get the following error cryptographicexception the specified network password is not correctdev win7 32bit iis 75production win server 64bit 2008 iis 75 even though there is no password between the networks and there is not certificate password i know because the dev works with no passwordthe only password that i have is the wcf one that is the same as the dev crmserviceclient crm new crmserviceclientcrmserviceendpointcrmclientcredentialsusernameusername crmconfigrepositorycrmusernamefinecrmclientcredentialsusernamepassword crmconfigrepositorycrmpasswordfinecrmclientcredentialsclientcertificatecertificate new x509certificate2paththis wont work as wellcrmclientcredentialsclientcertificatecertificate new x509certificate2path x509keystorageflagsexportable this is the full stackcryptographicexception the specified network password is not correct systemsecuritycryptographycryptographicexceptionthrowcryptographicexceptionint32 hr 41 systemsecuritycryptographyx509certificatesx509utils loadcertfromfilestring filename intptr password uint32 dwflags boolean persistkeyset safecertcontexthandle pcertctx 0 systemsecuritycryptographyx509certificatesx509certificateloadcertificatefromfilestring filename object password x509keystorageflags keystorageflags 372 systemsecuritycryptographyx509certificatesx509certificate2ctorstring filename 101 externalscrmconnectionget in cusersavidocumentsvisual studio 2010projectsexpressbrokerexternalscrmconnectioncs31 expressbrokermodelsactionsmetadatahandlersleadaccounthandlerhandlebrokeraction brokeraction actionstep step dictionary2 httppostdatacollection in cusersavidocumentsvisual studio 2010projectsexpressbrokerexpressbrokermodelsactionsmetadatahandlersleadaccounthandlercs45 expressbrokermodelsactionsmetadatahandlersbasestephandlersecuredhandlebrokeraction brokeraction actionstep step dictionary2 httppostdatacollection in cusersavidocumentsvisual studio 2010projectsexpressbrokerexpressbrokermodelsactionsmetadatahandlersbasestephandlercs49 expressbrokermodelsactionsmetadatahandlershandlerinvokerinvokebrokeraction brokeraction actionstep actionstep dictionary2 stepvalues in cusersavidocumentsvisual studio 2010projectsexpressbrokerexpressbrokermodelsactionsmetadatahandlersstepserverinokercs29 expressbrokercontrollersleadaccountcontrollerregisterstring step in cusersavidocumentsvisual studio 2010projectsexpressbrokerexpressbrokercontrollersleadaccountcontrollercs28 lambda methodclosure controllerbase object 127 systemwebmvcreflectedactiondescriptorexecutecontrollercontext controllercontext idictionary2 parameters 264 systemwebmvccontrolleractioninvokerinvokeactionmethodcontrollercontext controllercontext actiondescriptor actiondescriptor idictionary2 parameters 39 systemwebmvcc thisplayclass15invokeactionmethodwithfiltersb 12 129 systemwebmvccontrolleractioninvokerinvokeactionmethodfilteriactionfilter filter actionexecutingcontext precontext func1 continuation 784922 systemwebmvccontrolleractioninvokerinvokeactionmethodwithfilterscontrollercontext controllercontext ilist1 filters actiondescriptor actiondescriptor idictionary2 parameters 314 systemwebmvccontrolleractioninvokerinvokeactioncontrollercontext controllercontext string actionname 784976 systemwebmvccontrollerexecutecore 159 systemwebmvccontrollerbaseexecuterequestcontext requestcontext 335 systemwebmvcc thisplayclassbbeginprocessrequestb 5 62 systemwebmvcasyncc thisplayclass1makevoiddelegateb 0 20 systemwebmvcc thisplayclasseendprocessrequestb d 54 systemwebcallhandlerexecutionstepsystemwebhttpapplicationiexecutionstepexecute 453 systemwebhttpapplicationexecutestepiexecutionstep step boolean completedsynchronously 371thanks,"['c#', '.net']" +220001,where are ios 5 simulator screenshots stored i have saved some screenshots in the iphone simulator running ios 5 but i cannot find them i had this problem before and it took me frickin ages to find them in the file system is this so simple that i am just a dullard or does noone use this feature or whati know i can get the screenshots off my real phone but i do not want retina screenshots i want normal screenshots,['iphone'] +220004,is there any need to sanitize a post value before using it in a php header for redirecting can i use a posted value in a php redirect header safetly without checking itheader location base postreturn base is set to the base of the siteif the user would somehow manipulate return to a file that does not exist it would simply return a nice 404 messageis there any danger in doing this is there anything the user can set it to that can compromise the system or in any way do damage,['php'] +220012,transparent circle using only css is it possible using only cssthis we can all dobut can we do thiscondition transparency must be preserved thus the problem is not solved by putting a circle in a solid color div box,['css'] +220039,scala equivalent of javautilarraylist i am doing a project in scala but am fairly new to the language and have a java background i see that scala does not have arraylist so i am wondering what scalas equivalent of javas arraylist is called and if there are any important differences between the java and scala versionsedit i am not looking for a specific behavior so much as an internal representation data stored in an array but the whole array is not visible only the part you use,['java'] +220041,anonymous functionclosure and using self or static i am working with anonymous functions where i am creating anonymous function outside of the object and then adding it to an object later in which it will be used with callstatic magic function the closures that are being added to contain methods from the parent class i am wondering if i would be able to call those methods from the closureright now i get this erroremptyobjectaddmethodopen function if static hasadapterget class function return self calladapterget class function details echo pyou have mailpthrows this errorfatal error cannot access static when no class scope is active in andadd the functionsemptyobjectaddmethodopen function if emptyobject hasadapteremptyobject function return emptyobject calladapteremptyobject function details echo pyou have mailpthrow this error because the method is protectedfatal error uncaught exception badmethodcallexception with message method hasadapter was not found in class emptyobject,['php'] +220043,section article or div and smaller text in a section and article tag recently i went to w3schools new html5 elements and thiscovered the section and article tag my question is when should you use a section article or div tag and why does the text gets smaller when i use a section and article tag like sosectionh1h1 tag in a section tagh1sectionarticleh1h1 tag in an article tagh1articleh1h1 tag in nothingh1copy and paste in to here just putting it there for convenience,"['html', 'css']" +220086,efficient strings containing each other i have two sets of strings a and b and i want to know all pairs of strings a in a and b in b where a is a substring of bthe first step of coding this was the followingfor a in a for b in b if a in b print abhowever i wanted to know is there a more efficient way to do this with regular expressions eg instead of checking if a in b check if the regexp a matches b i thought that maybe using something like this would let me cache the knuthmorrispratt failure function for all a also using a list comprehension for the inner for b in b loop will likely give a pretty big speedup and a nested list comprehension may be even betteri am not very interested in making a giant leap in the asymptotic runtime of the algorithm eg using a suffix tree or anything else complex and clever i am more concerned with the constant i just need to do this for several pairs of a and b sets and i do not want it to run all weekdo you know any tricks or have any generic advice to do this more quickly thanks a lot for any insight you can shareeditusing the advice of ninjagecko and sven marnach i built a quick prefix table of 10mers import collections prefix table collectionsdefaultdictset for k b in enumerateb for i in xrangelenprot seq10 j i101 prefix tablebijaddk for a in a if lena 10 for k in prefix tablea10 check if a is in b missing edges is necessary but not sufficient if a in bk print ab else for k in xrangelenprots and seqs a is too small to use the table check if a is in any b if a in bk print a b,['python'] +220089,create unique constraint with null columns i have a table with this layoutcreate table favorites favoriteid uuid not null primary key userid uuid not null recipeid uuid not null menuid uuidi want to create a unique constraint similar to thisalter table favoritesadd constraint favorites uniquefavorite uniqueuserid menuid recipeidhowever this will allow multiple rows with the same userid recipeid if menuid is null i want to allow null in menuid to store a favorite that has no associated menu but i only want at most one of these rows per userrecipe pairthe ideas i have so far areuse some hardcoded uuid such as all zeros instead of nullhowever menuid has a fk constraint on each users menus so i would then have to create a special null menu for every user which is a hasslecheck for existence of a null entry using a trigger insteadi think this is a hassle and i like avoiding triggers wherever possible plus i do not trust them to guarantee my data is never in a bad statejust forget about it and check for the previous existence of a null entry in the middleware or in a insert function and do not have this constrainti am using postgres 90is there any method i am overlooking,['sql'] +220099,creating a fuzzy border in css 3 heres my source imageand my source image zoomed inany thoughts on how to accomplish this with only css3 notice the slight bleed upwards into the element,['css'] +220105,drawing in air with android phone i am working on an application to draw in the air with an android phoneas my phone is moving thanks to the acceletometer i retrieve the acceleration on each axis ax ay az what i am interested in is xyzfrom what i read in forums and in some tutorials integrating the accelaration twice gives huge errorsso what is the best solution for me to get information on the deplacement of the phonethanks for your help,['android'] +220106,any simple examples using roboguice with fragments in android i am having issues finding a working example of using fragments roboguice the problem happens when you attempt to addremove fragments with the android fragment transaction manager once you tell the fragment to inherit from robofragment the transaction manager no longer thinks the class is a fragment because it extends robofragment you can however use roboguices own fragment manager but it also crashes is there any examples out there of addingremoving roboguice fragments dynamically,['android'] +220128,send post with webclientdownloadstring in c i know there are a lot of questions about sending http post requests with c but i am looking for a method that uses webclient rather than httpwebrequest is this possible it would be nice because the webclient class is so easy to usei know i can set the headers property to have certain headers set but i do not know if it is possible to actually do a post from webclient,['c#'] +220143,best way to delete millions of rows by id i need to delete about 2 million rows from my pg database i have a list of ids that i need to delete however any way i try to do this is taking days i tried putting them in a table and doing it in batches of 100 4 days later this is still running with only 297268 rows deleted i had to select 100 ids from an id table delete where in that list delete from ids table the 100 i selectedi trieddelete from tbl where id in select from idsthat is taking forever too hard to gauge how long since i cannot see it is progress till done but the query was still running after 2 daysjust kind of looking for the most effective way to delete from a table when i know the specific ids to delete and there are millions of ids,['sql'] +220148,php regular expression for video swf iwant to get the video url from a objectembed html source i read i can use regular expression to get it but me and regular expression are no friendsso heres what i havephp function srctext text str replace text text str replacesrc text temporary explodeembed text temporary temporary1 temporary explode trimtemporary return temporary0 html object width180 height220 param namemovie valueparam embed src typeapplicationxshockwaveflash width180 height220embedobject echo srchtmlthis works but is it better in regular expressioni am using lamp,['php'] +220162,how to get fabric to automatically instead of userinteractively interact with shell commands combine with pexpect seeking means to get fabric to automatically instead of userinteractively interact with shell commands and not just requests for passwords but also requested user input when no stdininteractive override like aptget install y is availablethis question along with these fabric docs suggest that fabric can only push the interactivity back to the human user that is running the fabric program seeking to instead fully automate without any human presence do not yet have a real current problem to solve just preparing for possible future obstaclepossibly useful to combine with pexpect or similar alternative mechanism if fabric cannot exclusively handle all stdinprompts automatically hoping it does not need to be an eitheror kind of thing why not leverage both pexpect and fabric where appropriate if applicable in same programautomation,['python'] +220163,videoview does not start when invisible i have an asynctask where i hide a video view start the video playback and show the video view when the video is playing but the video would just not start when the video view is set to invisible the async task keeps hanging in onbackground if i comment out this line the video starts playingwhy does the video view require a visible surfacepublic void walkfinal view v new asynctask override protected void onpreexecute superonpreexecute mvideoviewsetvisibilityviewinvisible this line causes video not to start mvideoviewstart override protected object doinbackgroundobject objects while mvideoviewisplaying return null override protected void onpostexecuteobject o superonpostexecuteo mvideoviewsetvisibilityviewvisible executea bit of background why i am doing this i try to avoid the wellknown issue of the black flash that you usually have when starting a video,['android'] +220172,parse json string to json object in cnet i have a json string returned by my soap web service in net it is as followscheckrecordrollnoabc2percentage40attended12missed34table1now i want to parse this string to a json object i also read this where they have used this line of codejobject jsonobj jobjectparsejsonso can i do the same by replacing json with my string name also do i need to reference any other dll except the newtonsoftdll btw here is the full webservice code,"['c#', '.net']" +220186,is there any publically accessible json data source to test with real world data i am working on a javascript dynamically loaded tree view user control i would like to test it with real world datadoes anybody know any public service with an api that provides access to hierarchical data in json format,['javascript'] +220187,arc equivalent of autorelease if i have this code mycustomclass mycustomclass return mycustomclass alloc init autoreleasethis code guarantees the returning object is autoreleasedwhats the equivalent of this in arc,['objective-c'] +220215,how to set session attribute in java i am able to set session attribute in scriptlet but when i am trying to set session attribute inside java class it shows error like session cannot be resolvedso how to set session in javastring username stringrequestgetattributeunsessionsetattributeusername username,['java'] +220225,initialize all string members with an empty string i want to set all string members of an object to an empty string if they are nullpseudocodeforeach member in object if member instanceof string and member null member what is the simplest way to achieve thatany framework tool that i can usewrite my own solution via reflection,['java'] +220246,taking screenshot i am developing an application for taking screenshots in the device in this application we can draw anything on the screen for this i am using canvas paint and path to do thisi am using this code to take screenshots public void savescreenshot if ensuresdcardaccess bitmap bitmap bitmapcreatebitmapgetwidth getheight bitmapconfigargb 8 canvas canvas new canvasbitmap ondrawcanvas file file new filemscreenshotpath systemcurrenttimemillis jpg fileoutputstream fos try fos new fileoutputstreamfile bitmapcompressbitmapcompressformatjpeg 100 fos fosclose catch filenotfoundexception e logepanel filenotfoundexception e catch ioexception e logepanel ioeception e helper method to ensure that the given path exists todo check external storage state private boolean ensuresdcardaccess file file new filemscreenshotpath if fileexists return true else if filemkdirs return true return false however when the following line is run bitmap bitmap bitmapcreatebitmapgetwidth getheight bitmapconfigargb 8my application closes with the following exception1128 150546291 eandroidruntime8209 javalangillegalargumentexception width and height must be 0if i change the height and width the screenshot is taken but it is emptywhy is that happening what am i doing wrong,['android'] +220251,css animations with delay for each child element i am trying to create a cascading effect by applying an animation to each child element i was wondering if there is a better way to do it than thismyclass imgnthchild1 webkitanimation myanimation 09s linear forwardsmyclass imgnthchild2 webkitanimation myanimation 09s linear 01s forwardsmyclass imgnthchild3 webkitanimation myanimation 09s linear 02s forwardsmyclass imgnthchild4 webkitanimation myanimation 09s linear 03s forwardsmyclass imgnthchild5 webkitanimation myanimation 09s linear 04s forwardsand so onso basically i would like to have an animation starting for each child but with a delay thanks for any inputaddition maybe i did not properly explain what was my concern it is about how to do this no matter how many children i have how to do this without having to write down the properties for every child for example when i do not know how many children there are going to be,['css'] +220257,how can i monitor and get http traffic in an android application i am wondering is there a way to interceptmonitor http traffic in android one way which i could think of is to install custom module in androids browser source code such that all traffic goes through it please steer me to the pertinent choice else how can we implement custom module any guidelines,['android'] +220277,how to rerun failed junit tests immediately is there a way to have an junit rule or something similar that gives every failing test a second chance just by trying to run it once againbackground i have a large set of selenium2webdriver tests written with junit due to a very aggressive timing only short wait periods after the clicks some tests 1 out of 100 and always a different one can fail because the server sometimes responds a bit slower but i can not make the wait period so long that it is definitely long enough because then the tests will take for ever so i think it is acceptable for this use case that a test is green even if it needs a second tryof course it would be better to have a 2 out of 3 majority repeat a failing test 3 times and take them as correct if two of the tests are correct but this would be a future improvement,['java'] +220297,firefox warning message i have a weird issue with firebug with my current javascript codei have a web page with javascript and and jqeury and i get this messageuse of getattributenodens is deprecated use getattributens insteadi use jquery 152 and firefox 8 i get this error also on windws 7 and xp i tried mac alsoi dont use getattributenodens in my codewho can i fix this error thanks,"['javascript', 'jquery']" +220319,use sbt to build pure java project historically i have used antivy or maven for building my java projectsi am now looking at nonxml based solutionsgradle can compile jar and publish my project with few issuescan i do the same with sbtif so can you provide a simple example of using sbt to build a java only project,['java'] +220346,twitter share button i want my own image for a twitter share button and want to also open in a popbox it is happening on facebook but in twitter i am able to find out is there a link or solution,"['javascript', 'css']" +220356,how to uninstall rubymine how do you uninstall rubymine from mac osx or other systemsit does not come with an uninstaller from what i can tell there are no options to uninstall in the application itself there is no documentation except a thank you for trying to uninstall on their sitei can drag the app to the trash but i assume there are preferences etc to also uninstall i hate to lose files,['ruby'] +220370,handling code which relies on jquery before jquery is loaded i would like to follow the general guideline of putting all javascript at the very bottom of the page to speed up loading time and also to take care of some pesky issues with conflicting jquery versions in a web app djangohowever every so often i have some code code which depends on jquery but which must be further up on the page basically the code cannot be moved to the bottomi am wondering if there is an easy way to code this so that even though jquery is not yet defined the code works when jquery is definedthe following seems i have to say like overkill but i do not know of another way to do itfunction run my code jquerydependent code here foodatabar truevar t nullfunction jquery ready if windowjquery windowjqueryui run my codewindowjquery else t windowsettimeoutjquery ready 100 t windowsettimeoutjquery ready 100actually i might need to use code more than once in a page code that does not know about other code so even this probably would not work unless i rename each jquery ready to something like jquery ready guid jquery ready otherguid and so onclarificationjust so this is clear i am putting the include to javascript script typetextjavascript srcjqueryminjs at the very bottom of the page just before the body so i cannot use the,"['javascript', 'jquery']" +220375,waveform on ios i am looking for how to draw the sound amplitudei found but i have some problems how get a list of floatingpoint values representing the audio,"['objective-c', 'ios']" +220399,ultimate answer to relative python imports i know that there are lots of questions about the same import issues in python but it seems that nobody managed to provide a clear example of correct usagelet us say that we have a package mypackage with two modules foo and bar inside foo we need to be able to access barbecause we are still developing it mypackage is not in syspath we want to be able toimport mypackagefoorun foopy as a script and execute the sample usage or tests from the main sectionuse python 25how do we have to do the import in foopy in order to be sure it will work in all these cases mypackage init py mypackagefoo init py mypackagebarpy def dobar printdobar mypackagefoofoopyimport bar fails with module not foundimport bar fails due to valueerror attempted relative import in nonpackagedef dofoo printdobarif name main dofoo,['python'] +220462,how do you easily create empty matrices javascript in python you can do thisnone 9 for x in range9and youll get thisnone none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none nonehow can i do the equivalent in javascript,['javascript'] +220478,detect long click on two item list view let me start by saying i am new to android development but have a strong background in c vbi have read a ton of posts on similar issues and tried the solutions but it never seems to work i am certain it is something i am doing and it is based on my ignorance of the programming languageso i got some code for a listadapter to populate the two item list view import javautilarraylistpublic class listadapter extends baseadapter private activity activity private arraylistinteger image private arrayliststring list1 private arrayliststring list2 private static layoutinflater inflaternull public listadapteractivity a arraylistinteger image arrayliststring list1 arrayliststring list2 thisactivity a thisimage image thislist1 list1 thislist2 list2 listadapterinflater layoutinflateractivitygetsystemservicecontextlayout inflater service public int getcount return imagesize public object getitemint position return position public long getitemidint position return position public static class viewholder public textview text1 public textview text2 public imageview image public view getviewint position view convertview viewgroup parent view viconvertview viewholder holder ifconvertviewnull vi inflaterinflaterlayoutgrid list layout null holdernew viewholder holdertext1textviewvifindviewbyidriditem1 holdertext2textviewvifindviewbyidriditem2 holderimage imageviewvifindviewbyidridicon visettagholder else holderviewholdervigettag holdertext1settextthislist1getposition holdertext2settextthislist2getposition holderimagesetimageresourcethisimagegetposition return vi i have modified the above to use arraylist instead of array in the original article it works fine what i want to do is detect the long click and prompt the user to delete or notthe mainxml has this partial code which is the list viewlistview androidididlvresult androidlayout widthfill parent androidlayout height296dp androidpaddingleft10px androidpaddingright10px listviewthere is another grid list layoutxml file which containslinearlayout xmlnsandroidandroidlayout widthfill parentandroidlayout heightwrap content imageview androidididicon androidlayout width72px androidlayout heightwrap content androidlayout margintop5px twolinelistitem xmlnsandroid androidididtwolinelist androidlayout widthfill parent androidlayout heightwrap content androidonclickonclick androidorientationvertical androidpaddingbottom5px androidpaddingtop5px textview androidididitem1 androidlayout widthmatch parent androidlayout heightwrap content androidtextappearanceandroidattrtextappearancemedium textview androidididitem2 androidlayout widthmatch parent androidlayout heightwrap content androidpaddingtop30px androidtextappearanceandroidattrtextappearancesmall twolinelistitemin the main activity it is instantiated withlistview lv listview findviewbyidridlvresultlistadapter is declared further uplistadapter new listadapterhomesteractivitythis arricon arrssid arrmac lvsetadapterlistadapterso what i would like to know is how do i intercept a long click where do i put the various bits ie there must be something in the xml file but which one i have tried lvsetonitemclicklistenernew adapterviewonitemclicklistener public void onlistitemclicklistview l view v int positionlong id superonlistitemclick l v position id toastmaketextthis position toastlength longshow and various versions but nothing seems to please the compilerif you have time and feel so inclined i would appreciate some education so i can get my mind around it,['android'] +220480,onetomany relationship is not working my tablesproduct id nameoffer id value product identitiesentitytablenameproductpublic class product implements serializable onetomanymappedbyproduct private setoffer offers entitytablenameofferpublic class offer implements serializable manytoone joincolumnnameproduct id private product product when i try to get some data from table product i get a javalangnullpointerexception and this code productgetoffers returnsindirectset not instantiatedhow to fix this,['java'] +220496,why does char cause undefined behaviour while char does not attempting to modify a string literal causes undefined behaviorchar p wikipedia p0 w undefined behaviourone way to prevent this is defining it as an array instead of a pointerchar p wikipedia p0 w okwhy does char cause undefined behaviour while char does not,['c'] +220511,undefined symbol in c when loading a python shared library i have been trying to get a project of mine to run but i have run into trouble after much debugging i have narrowed down the problem but have no idea how to proceedsome background i am using a python script inside c code this is somewhat documented on python and i managed to get it running very well in my basic executable include and a lpython26 and everything was grandhowever difficulty has arisen when running this python script from a shared libraryso this shared library is loaded as a module by a simulation system openrave the system interacts with this module using a virtual method for modules called sendcommand the module then starts a boostthread giving python its own thread and returns to the simulation system however when python begins importing its modules and thus loading its dynamic libraries it fails i assume due to the following error importerror usrlibpython26thistpackagesnumpycoremultiarrayso undefined symbol py zerostruct i have run ldd on my executable and the shared library there does not some to be a difference i have also run nm d on the file above the py zerostruct is indeed undefined if you guys would like print outs of the commands i would be glad to supply them any advice would be greatly appreciated thank youhere is the full python errortraceback most recent call last file usrlibpython26thistpackagesnumpy init py line 130 in import add newdocs file usrlibpython26thistpackagesnumpyadd newdocspy line 9 in from lib import add newdoc file usrlibpython26thistpackagesnumpylib init py line 4 in from type check import file usrlibpython26thistpackagesnumpylibtype checkpy line 8 in import numpycorenumeric as nx file usrlibpython26thistpackagesnumpycore init py line 5 in import multiarrayimporterror usrlibpython26thistpackagesnumpycoremultiarrayso undefined symbol py zerostructtraceback most recent call last file homeconstantinworkspaceopenravesrcgrasp behavior 2py line 3 in from openravepy import file homeconstantinworkspacerospackagesopenravelibpython26sitepackagesopenravepy init py line 35 in openravepy currentversion loadlatest file homeconstantinworkspacerospackagesopenravelibpython26sitepackagesopenravepy init py line 16 in loadlatest return loadversion openravepy file homeconstantinworkspacerospackagesopenravelibpython26sitepackagesopenravepy init py line 19 in loadversion mainpackage import openravepy globals locals targetname file homeconstantinworkspacerospackagesopenravelibpython26sitepackagesopenravepy openravepy init py line 29 in from openravepy int import importerror numpycoremultiarray failed to import,['python'] +220521,including js files jquery in jspx files i am creating a dynamic web project in eclipse almost from scratch and i created a jspx file where i putheadscript typetextjavascript srcroutetoscriptsjqueryjsscriptscript typetextjavascript srcroutetoscriptsjqueryuijsscriptscript typetextjavascript srcroutetoscriptssomethingjsscriptheadi intend to use jquery ui sortable and i found out that using jspx only the first script loads in firefox and ie while in opera it works if i use plain jsp whether html of xhtml it loads all the js filesis there any way to include all the js files successfully without usingscriptjspinclude scriptthat i must be aware of because this one loads the script into the final xhtmledit just thinking why does opera read the xhtml right while ff and ie failed at reading the script tags could it be a bug,"['javascript', 'jquery']" +220540,xforms rendered via xslt and xml error i know this question will sound like a from the past thing but i need to do this for a homework and i cannot make it workthe problem the followingi have xml data called from a database i used xslt to render an xforms document on the browser by the way its the old firefox 36 that was installed only to use the xforms extensionit renders the xforms document correctly but the controls doesnt work as expected i cant submit a form and also the instance data is not filling in the inputsmy xsl stylesheet is the followingxslstylesheet version10 xmlns xmlnsxsl xmlnsxfxsloutput methodxmlindentyesomitxmldeclarationyesmediatypeapplicationxhtmlxmldoctypepublicw3cdtd xhtml 10 strictendoctypesystem xsltemplate match html xmlns xmlnsxf dirltr langes head xfmodel xfinstance data xmlns icargo id1icargo id scargo desclalalascargo desc iconcurrencia id1iconcurrencia id data xfinstance xfsubmission idprueba actioneditarcargosaspx methodpost xfmodel link hrefcstylecss relstylesheet typetextcss titlecdataadicionar cargostitle head body div classheaderdiv div classmenu a hrefempleadoseditarempleadosaspxcdataempleadosa a hrefhorarioseditarhorariosaspxcdatahorariosa a hrefjornadaseditarjornadasaspxcdatajornadasa a hrefcargoseditarcargosaspxcdatacargosa a hrefusuarioseditarusuariosaspxcdatausuariosa a hrefprofesioneseditarprofesionesaspxcdataprofesionesa a hrefreportesreportemarcacionesaspxcdatarep de marcacionesa a hrefcerrarsesionaspxcdatacerrar sesia3na div div idmain div classmaintitle cdataadicionar cargos div div xfinput refscargo desc xflabelcdatacargoxflabel xfinput div xfsubmit submissionprueba xflabelcdataguardar cambiosxflabel xfsubmit div div div a classcmdsecond hrefeditarcargosaspxcdatavolvera div div body htmlxsltemplatexsltemplate matchcargoicargo id icargo id xslvalueof selecticargo id icargo id scargo desc xslvalueof selectscargo desc scargo desc iconcurrencia id xslvalueof selecticoncurrencia id iconcurrencia idxsltemplatexsltemplate matchcargonoticargo id icargo idicargo id scargo descscargo desc iconcurrencia idiconcurrencia idxsltemplatexslstylesheetand my xml code look like thiscargo icargo id1icargo id scargo descjefe de sistemasscargo desc iconcurrencia id1iconcurrencia idcargoi think the problem is the xsloutput methodxml attribute because xforms requires xhtml to render but firefox throws an xslt exception when i make itplease help i have searched everywhere and ive found it has something to be with a bug in firefox but i expect there is another way to make this work your help will be very appreciated and sorry about my english i am currently learning d,['html'] +220557,cmake with include and source paths basic setup i am trying to set up a test project looking like my own project just to get things working first and it looks like thismainprojectincmainhmainprojectsrcmaincpplibprojectinctesthlibprojectsrctestcppi have found some tutorials but i cant find out how to set up this when i have the inc and src folder how would the cmakeliststxt files look would i have one in one in each of the project folders it seems like i dont need to have one in the inc and src folders,['c++'] +220562,how do you check if the current page is using ssl in aspnet i have a site that by design and client preference can be served using http or https the client company simply chooses whether or not to link to our site using the http or https and iis does the rest a feature is being added to a page which deals with sensitive information that should only ever be viewed over ssl clients have agreed that this additional feature should be thisabled on this page when not using an https connectionin the page load event i would like to add an if statement that checks to see if the page is currently being viewed over https in order to show or thisable this optional feature i can probably read the url to see if it begins with https but worry that the approach is insecureis there a property that can be checked to test for https during the page load event,['asp.net'] +220567,how to set a timeout with afnetworking my project is using afnetworkinghow do i dial down the timeout atm with no internet connection the fail block is not triggered for what feels like about 2 mins waay to long,"['objective-c', 'ios']" +220585,use both account and user tables with devise i am working with rails 310 and devise 148 and am new to bothi want to allow multiple users for an account the first user to sign up creates the account probably for their company then that user can add more users a user is always linked to exactly one accounti have users and accounts tables abbreviated modelsclass user activerecordbase belongs to account devise database authenticatable registerable recoverable rememberable trackable validatable confirmable lockable timeoutable attr accessible email password password confirmation remember meendclass account activerecordbase has many users dependent destroy attr accessible name account typeendthe question is when the first user signs up how do i create both the account and userdo i need to modifyoverride the devise registrations controllersomething like the answer here i could not figure out how tocreate the account then pass it to devise for creating the useraccount id is already in the user model should i add account nameand account type to the user model and create a new the accountrecord if account id is not passed in in this case i am trying to hide account creation from devise but not sure that will work since i still need to prompt for account name and account type on the registration page,['ruby-on-rails'] +220586,how to make width of a column fit to its contents in html table i have the following table in my htmldiv stylemaxwidth700px table border1 trtd colspan2this is a long texttdtr trtd width1pxatdtd btdtr trtd width1pxctdtd dtdtr tabledivi want the first column width in the second and third row to just fit the content length that is why i put width1px there in the mean while i want to table width to just fit the length of the longest content in the table which is the first row instead of spanning to the maxwidth of its bounding divit works in firefox as shown belowhowever in ie 9 it does not work as expected as showni tried to replace width1px with width1 but then the table width will span to the maxwidth of the parent divdoes anyone know how to fix it in iethanks in advance,"['html', 'css']" +220621,devise password reset from rails console while running an app how do you select a user by email address and then set the password manually within rails console for devisealso where would i go to review documentation to cover more details in this regard to manipulation of accounts while using devise,"['ruby-on-rails', 'ruby']" +220630,cucumber vs rspec i want to start diving into bdd i have never used tdd before and amnot sure if i should start by learning rspec and then jump to cucumberor just go straight to using cucumberi have been reading on the internet about both and it seems to me thatcucumber could be a replacement for rspec am i right or should beone used for certain things and the other one for others,['ruby-on-rails'] +220642,flagging cookies as secure in forms auth when the website is behind a load balancer serving the tls cert recently i had a bit of a problem with a site on appharbor which i wrote about on their support forums requestissecureconnection always returns falsein short because the load balancer is decrypting the https traffic before it hits the web app attributes such as requestissecureconnection and configuration like requiressl on forms auth is not behaving as expected in fact in the latter case you cannot even authenticate as the app thinks the request is not coming over httpsit is the forms auth which is especially problematic because without it cookies are not set to secure and are sent back over http if the site is accessed by domain name only and implicitly serves up the insecure url schemewhat would be the best workaround for this i would prefer to leverage the native security configuration can anyone see a way to override the implementation which checks if the connection is secure it is easy enough to detect whether the request was served over https either based on requesturlscheme or the x forwarded for header it is just a question of neatly tying this in,['asp.net'] +220655,communication between ioss native app and webpages javascript i have a webpage loaded in a uiwebview and a javascript function of the page needs to data from native ios app a nsstring how can a js function access the data in native app thanks lvreiny,"['javascript', 'ios']" +220671,how to thisable redirection after login check in symfony 2 i need to thisable redirection after login check because i need to get only that the login was success or not after submission login check url give me the right data but keep redirecting to login on failurelogin is blank after thati am trying to set up login form using extjs 4 so i need to validate trough an ajax post requestlogin check should authenticate create user session and return whether it was success or failure but no forwarding anywheremy loginhtmltwig looks like if is grantedis authenticated remembered successtrue else success false endif and in securityymlfirewalls main form login provider fos userbundle failure path null failure forward false,['php'] +220711,how do i linq order a collection i have a collection of class objectsteststhis collection contains many test instancespublic class test public string column1 get set i would like to use linq to order the contents of tests and put into a new collection called testsordered i want to order by the contents of column1 i would like to do this with linq as later i want to add more to the orderinghow can i do this with linq,['c#'] +220715,how to test an ios library which is using uikit i would like to create a library for ios applications which uses uikit furthermore i would like to create unit tests for this library unfortunately my tests do not work because of uikit uifont systemfontofsize120 to be precise according to apples unit testing guide there are two types of test cases logic tests and application tests application tests seem to be the correct type for tests involving uikit related stuff but i did not find out about how to set up application tests for libraries has anybody ever had the same problem and was able to solve itthanks a lot,['ios'] +220730,ios 5 storyboards returning to initial view controller i am working on an application that uses the new storyboard functionality in xcode 42is there a way of programatically sending a user back to the initial view controller from any point within the applicationfor example when a session expires and they need to login again initial view controller is my login screen,['ios'] +220733,how to count steps using an accelerometer i have to develop the same functionality as of this pedometer appi have observed this pedometer app in very high detailit is not a perfect pedometer app for example if you staysit at one place and shake your hand it also detects steps counts and thistanceignore this ideal and gravity behavior because in the instructions of this app it is already been mentioned that you should tie up your iphone or you should place it in your pocket to count stepsthis way i have found this app working very well it detects almost all stepsmy problem is i have developed one sample according to the above logic but it is not working up to that level for example sometimes it detects 23 steps at the same time and sometimes it works finemy codein viewdidloaduiaccelerometer sharedaccelerometer setupdateinterval02 voidaccelerometeruiaccelerometer accelerometer didaccelerateuiacceleration acceleration const float violence 12 static bool beenhere bool shake false if beenhere return beenhere true if accelerationx violence accelerationx 1 violence shake true if accelerationy violence accelerationy 1 violence shake true if accelerationz violence accelerationz 1 violence shake true if shake stepssteps1 beenhere falsewhat am i doing wrong i am not able to determine the threshold if i make it high it would not detect minor steps if i make it small it registers 34 steps simultaneouslyis there any other implementation required to do this or some tweaks in this codei have seen all other similar stack overflow links nothing i have found performs up to this levelplease help,"['iphone', 'ios']" +220736,open native maps app from phonegap is there phonegap solution for opening the native maps app centred on a location or with a route thisplayed,['iphone'] +220744,video plays only once in webview of android i am succeeded to play streamed youtube video from html5 content in webview in android but now problem is that video plays only first time after that videoview only goes to end of the video file i tried clearing cache as suggested here but no luckwhat could be the possible solution for this problemplease try following code to run video this has been using some suggestions given on stackoverflowcomwebview webview webview findviewbyidridproduct details webviewwebsettings websettings webviewgetsettingswebsettingssetpluginstatewebsettingspluginstateonwebsettingssetjavascriptenabledtruewebsettingssetusewideviewporttruewebsettingssetloadwithoverviewmodetruewebviewsetwebchromeclientnew chromeclientwebviewsetwebviewclientnew webviewclientwebviewloadurlurlpublic class chromeclient extends webchromeclient implements oncompletionlistener onerrorlistener private webview wv private videoview mvideoview private linearlayout mcontentview private framelayout mcustomviewcontainer private webchromeclientcustomviewcallback mcustomviewcallback framelayoutlayoutparams cover screen gravity center new framelayoutlayoutparams viewgrouplayoutparamswrap content viewgrouplayoutparamswrap content gravitycenter override public void onshowcustomviewview view customviewcallback callback if view instanceof framelayout wv webviewfindviewbyidridproduct details webview mcustomviewcontainer framelayout view mcustomviewcallback callback mcontentview linearlayoutfindviewbyidridlinearlayout1 if mcustomviewcontainergetfocusedchild instanceof videoview mvideoview videoview mcustomviewcontainergetfocusedchild frameremoveviewvideo mcontentviewsetvisibilityviewgone mcustomviewcontainersetvisibilityviewvisible setcontentviewmcustomviewcontainer mvideoviewsetoncompletionlistenerthis mvideoviewsetonerrorlistenerthis mvideoviewstart public void onhidecustomview if mvideoview null return else hide the custom view mvideoviewsetvisibilityviewgone remove the custom view from its container mcustomviewcontainerremoveviewmvideoview mvideoview null mcustomviewcontainersetvisibilityviewgone mcustomviewcallbackoncustomviewhidden show the content view mcontentviewsetvisibilityviewvisible public void oncompletionmediaplayer mp mpstop mcustomviewcontainersetvisibilityviewgone onhidecustomview setcontentviewmcontentview public boolean onerrormediaplayer arg0 int arg1 int arg2 setcontentviewmcontentview return true,['android'] +220761,how can i find out why my app is getting sigkilled inside uipasteboard very infrequently our app is crashing because it receives sigkill the circumstances are different but the backtrace is always the same0 0x94a00afa in mach msg trap 1 0x94a01267 in mach msg 2 0x00fa9d5c in uipasteboardservercontainstypesatindex 3 0x00faa9ae in uipasteboardservercontainstypesatindex 4 0x00fa5417 in uipasteboard containspasteboardtypes 5 0x00de4054 in uitextfield canperformactionwithsender 6 0x087038a8 in uiresponderuitextaccessibilityutilities accessibilityhastextoperations 7 0x08704df5 in uiaccessibilitytextfieldelement accessibilityhastextoperations 8 0x08791dcf in nsobjectaxprivcategory accessibilityattributevalue 9 0x0878a3b4 in copymultipleattributevaluescallback 10 0x087c5c95 in axxmigcopymultipleattributevalues 11 0x087c0a6c in xcopymultipleattributevalues 12 0x087c8e66 in mshmigperform 13 0x020cf1c5 in cfrunloop is calling out to a source1 perform function 14 0x02034022 in cfrunloopdosource1 15 0x0203290a in cfrunlooprun 16 0x02031db4 in cfrunlooprunspecific 17 0x02031ccb in cfrunloopruninmode 18 0x02a43879 in gseventrunmodal 19 0x02a4393e in gseventrun 20 0x00d2ba9b in uiapplicationmain 21 0x0284d in main argc1 argv0xbfed44 at myappmainm1422 0x027c5 in start how would i go about finding out what is causing this crash,"['iphone', 'objective-c']" +220762,how to change the session timeout in php i would like to extend the session timeout in phpi know that it is possible to do so by modifying the phpini filebut i do not have access to itso is it possible to do it only with php code,['php'] +220773,read csv file with comma within fields in python i need to read a csv file which has fields that have a comma so i have double quoted the fields which contains commas such as1 text1text2 text3 text4 a b cbut when i try to read the file in python i get the fields separated by the commas as followingrow0 1row1 text1row2 text2row3 text3row4 text4row5 arow6 brow7 ci am reading the csv file with the following codeinfo csvreaderopeninfocsv for row in info print row0 row1 is it possible to read double quoted fields which contains a comma,['python'] +220785,how to render html element without using web browser is there a way how to draw specific html element content on a canvas without using any web browser control with this code i am rendering the element to the forms canvas just as an exampleit works though but this code is not a good practice see below whyuses shdocvw mshtmlprocedure tform1button1clicksender tobjectvar webbrowser twebbrowser htmlelement ihtmlelement htmlrenderer ihtmlelementrenderbegin webbrowser twebbrowsercreatenil try webbrowserparentwindow applicationhandle webbrowsernavigate while webbrowserreadystate readystate complete do applicationprocessmessages htmlelement webbrowserdocument as ihtmldocument3getelementbyidquestion htmlrenderer htmlelement as ihtmlelementrender htmlrendererdrawtodccanvashandle finally htmlelement nil htmlrenderer nil webbrowserfree endendit is bad becauseit uses the hidden twebbrowser control but i would like to load the html document directly through the ihtmldocument interface and render certain element on my own canvasif i create and load the ihtmldocument manually eg this way then the renderer method ihtmlelementrenderdrawtodc does not paint anything maybe because there is no canvas for rendering of the documenteven worse is that ihtmlelementrenderdrawtodc is deprecated at this time so i am looking for an alternative method for rendering elements on my own canvasis there a clean way to solve this using mshtml,['html'] +220788,reset css styles for only div well i have a big html document and i want to embend control to this document but css styles of this control overlap by styles of big html document how can i reset all styles for only div and all nested divs,"['html', 'css']" +220803,jquery val vs attrvalue i had thought these two were the same but they appear to not be i have generally been using objattrvalue to work with form fields but on the page i am currently building objattrvalue does not return the text i enter in my field however objval does on a different page i have built both objattrvalue and objval return the text entered in the form field what could account for objattrvalue working as expected in one case but not in anotherwhat is the proper way to set and retrieve a form fields value using jquery,['jquery'] +220809,passing true false to slidetoggle in jquery i know that we can pass true or false value to the function to toggle visibility of an element i cannot get slidetoggle to do the same thing any help pleasefor example instead of if true somethingslidedownelse somethingslideupi would really like to do something similar to somethingtogglemyboolvaluebut i want to do it with slidetogglelook at my example of jsfiddle to know what i am trying to dois that possible,['jquery'] +220811,how to see log file transfer progress using paramiko i am using paramikos sftpclient to transfer file between hosts i want my script to print the file transfer progress similar to the output seen using scp scp my file userhostuserhost password my file 100 816kb 8158kbs 0any ideathanks in advance,['python'] +220812,mysql table structure proposal is this table any good for mysql i wanted to make it flexible in the future for this type of data storage with this table structure you cannot use a primary key but an index should i change the format of the table to have headers primary key width length space coupling id num param value1 width 5e0811 length 121 space 5e0841 coupling 151 metal layer m302 width 5e0822 length 138e0612 space 5e0812 coupling 152 metal layer m310,['mysql'] +220821,javascript indexof on an array of objects if i have an array likevar myarray colorred name redname colorblue name bluename colorgreen name greenname coloryellow name yellowname how do i get the index of say blue,['javascript'] +220823,pass std algos predicates by reference in c i am trying to remove elements from a stdlist and keep some stats of deleted elementsin order to do so i use the remove if function from the list and i have a predicate i would like to use this predicate to gather statistics here is the code for the predicate class testpredicate private int limit public int sum int count testpredicateint limit limit limit sum0 count0 bool operator int value if value limit sum value count part where i gather the stats return true else return false and here is the code for the algostdlist int containercontainerpush back11testpredicate pred10containerremove ifpredassertpredcount 1unfortunately the assertion is false because the predicate is passed by value is there a way to force it to be passed by reference,['c++'] +220825,could a malicious hacker alter a hidden post variable i know that a post can be spoofed in terms of originating domain but what about being able to change the variables of the hidden post variables in my html i am concerned that someone could alter the amount value in my paypal form from this input typehidden nameamount value100to thisinput typehidden nameamount value001or something similar thanks,"['php', 'html']" +220852,nuget add reference error while installing packages i am not able to install any package by nuget for example when i want install entity framework i receive following errorinstallpackage entityframeworksuccessfully installed entityframework 4200successfully uninstalled entityframework 4200install failed rolling backinstallpackage failed to add reference to entityframeworkat line1 char16 installpackage entityframework categoryinfo notspecified installpackage invalidoperationexception fullyqualifiederroridnugetcmdletunhandledexceptionnugetpowershellcommandsinstallpackagecommandi receive same error while installing every package from console or gui reinstalling nuget thisabling other extentions and running vs as admin did not help me regards,['.net'] +220861,how does the jquery animate function work internally here is small codediv idclickmeclick heredivimg idbook srcbookpng alt width100 height123styleposition relative left 10px clickmeclickfunction bookanimate opacity 025 left 50 height toggle 50 function animation complete it is clear from the code left is increasing and opacity will be 25 how jquery manage to do sodoes jquery internally execute a loop to increase the left and change the opacity until it becomes 25 need guidance thanks,['jquery'] +220866,android alternative to metrogridhelper i am a newbie for android development and i came from wp7 world so i found many familiar tools missing one of my favorite is which is really helpful for me to find out whats wrong with ui layout or alignment during debugging so i am wondering if there is an alternative in android world or can anyone please give me some hints on how to implement similar things in android,['android'] +220877,view mysql temporary table not in session i currently have a script running and did not think it would take so long to run the script is modifying a temporary tablei know that temporary tables only exist for the current session but is there anyway to see the data they hold from outside the sessionreason is that i want to know how long my script is going to keep running for if i could see the temporary data then i would be able to figure it out,['mysql'] +220881,can i stop hover from being applied to an element let us say i have some cssbuttonhover fontweight bold how can i prevent the hover styles from being applied at will my target use case is when the element is thisabled for example with this htmlbutton thisabledclick mebuttonthe hover css is still applied the button gets faded out but the hover effect can still be seen how can this be stopped,"['html', 'css']" +220892,jquery onclick func function not doing its job how to create the issueclick on existing trigger links something happens passclick on the add trigger button which appends a new trigger link w same classclick on the newly created link and it does not do the same thing as the 1st 2 links that existed from the start failhere is my example i thought the onclick func function was good for adding events to current elements in the dom but also for future elements that get added to the domhere is my current javascript documentreadyfunction linkonclick functione epreventdefault outappendclickedbr b1onclick function p1appenda href classlinknew triggera here is the htmlbutton typebutton idb1add triggerbutton p idp1 a href classlinktrigger 1a a href classlinktrigger 2a p div idoutdivnote im using jquery 17 thanks,['jquery'] +220893,junit ignore all other tests ignoreother i am testing extensively with junit and sometimes while debugging my code i want temporary only run a single test of my runwitharquillianclass test class currently i am adding a ignore to all other tests and wondering if something like ignoreother does existare there better solutions to ignore all other tests,['java'] +220901,best choice for in memory data structure for ip address filter in java i have file that is cidr format like this 1921681024 and it is converted into this two column strucutre3232236030 32322357each string ip address convertion happens with this codestring subnet 1921681024subnetutils utils new subnetutilssubnetinet4address a inet4address inetaddressgetbynameutilsgetinfogethighaddresslong high bytestolongagetaddressinet4address b inet4address inetaddressgetbynameutilsgetinfogetlowaddresslong low bytestolongbgetaddressprivate static long bytestolongbyte address long ipnum 0 for int i 0 i 4 i long y addressi if y 0 y 256 ipnum y 3 i 8 return ipnumconsider that there are over 5 million entries of low high 3232236030 32322357also there will be intersects so the ip can originate from multiple ranges just the first one is more than okthe data is read onlywhat would be the fastest way to find the range the iptobefiltered belongs to the structure will be entirely in memory so no database lookups updatei found this peerblock project it has over million download so i am thinking it must have some fast algorithms wfpcdoes anyone know what technique is the project using for creating the list of ranges and than searching them,['java'] +220905,move a calayer add animation well i have a calayer layer and i would like to move it with a cathisplaylink like layercentercgpointmakelayercenterx 10 layercentery 10but i cannot use center or position for the layerhere is my problem i want to make it move like it was a uiimageview,['iphone'] +220923,how to declare and define global variables in order to access them from all headerssource files properly well i am learning c and never really learned how to do stuff that is not ooi am trying to get a bit more experience coding in c stylegobalinformationhpragma onceifndef globalinformation hdefine globalinformation hinclude mapinformationhnamespace gi mapinformation mapinfendifi would like to be able to access gimapinf from every header and cpp in my project right now i am including globalinformationh in every header so i am getting linker errors with multiple definitionshow can i work around the problem,"['c++', 'c']" +220924,use only wifi connection not cellular network in app my app has been rejected in the apple appstoreto fix this it must use only wifi and not cellular network connection when the user is using the application the application uses uiwebview how can we go about implementing this restrictionany help will be appreciatedthanks,['ios'] +220949,efficient structure for element wise access to very large sparse matrix pythoncython i am looking for an efficient data structure to represent a very large matrix of integers in pythoncython with focus on elementwise operationsi am currently building a model that requires a lot of elementwise operations on a large highly sparse matrix ca 50bn readwrites on a 2mmx500k matrix previously i have run experiments on smaller data and used python with cython and numpy arrays and would ideally like to continue using some parts of the existing infrastructurea number of options i have looked at implemented so far they may not be fully optimised but all implementations should be good enough to give a realistic idea of the potential of each approach i have tested by creating a 2mmx500k matrix adding 25mm elements and then again removing them this reflects the kind of operations i would need29 minutes cython lists to fill scipysparsecoo sparsedok 10 minutes cython lists to fill scipysparsecoo sparselil 3 minutes dict st ad d ij contains mij 3 minutes dict st aij contains mij1 minute dict st ainj contains mij1 minute stdmap using cythonhacking a dict together performs best so far but is still fairly slow also it feels like too much of a hack so i am assuming there must be a more efficient method out there particularly considering the dict solution does not really use any of the potential cython could provide is there a more cythonic solution around for this google was not very helpful unfortunately or i was lacking the correct keywords to search withany suggestions on how to do this would be greatly appreciatededit 1the difference between the two dictionary solutions is that the ad d ij variant is faster for access whereas the aij variant is faster for setup setup executiondict st ad d ij contains mij 180s 30sdict st aij contains mij 66s 104sdict st dict st ainj contains mij 40s 8swhile the ad d ij is marginally slower in the current test it would be preferable in the long run as the setup cost will only increase by a factor 10x the execution cost by a factor 10x for my actual experimentsedit 2i could speed up the dictionary version further by removing the string operations and instead using a large integer representation by concatenating the two indices using a suitably large multiplier on the first to avoid collision the multiplication is typed using a cdefcdef unsigned int keyint a int b return a 10 bit might still be possible to further improve speed by optimising the dict or moving the data structure to c but this should be fast enough for my purposes any other suggestions would still be very welcome though will report back if i find a more efficient solution using stl map or similar data structuresedit 3following suggestions of a colleague i have also implemented the system using stdmap via it is cython interface to store data in an intint map the implementation is actually mildly slower than the dict implementation once we have large amounts of data with the key difference being in access speed small data 25mm elements large data 250mm elements time total setup readwrite total setup readwritedictint keys 40s 25s 8s 369s 269s 72sstdmap 26s 11s 12s 376s 169s 177s,['python'] +220959,convert flat array of objects into nested array of objects original json data flat table id1first namejasonlast namemartinstart date19960725end date20060725salary123456citytorontodescriptionprogrammerdepartmentfinanceactive1 id2first namealisonlast namemathewsstart date19760321end date19860221salary6178cityvancouverdescriptiontesterdepartmentfinanceactive1 id3first namejameslast namesmithstart date19781212end date19900315salary654478cityvancouverdescriptiontesterdepartmentqaactive1 id4first namecelialast namericestart date19821024end date190421salary234478cityvancouverdescriptionmanagerdepartmenthractive1 id5first namerobertlast nameblackstart date19840115end date19980808salary233478cityvancouverdescriptiontesterdepartmentitactive1 id6first namelindalast namegreenstart date19870730end date19960104salary432278citynew yorkdescriptiontesterdepartmentqaactive1 id7first namedavidlast namelarrystart date19901231end date19980212salary789778citynew yorkdescriptionmanagerdepartmenthractive1i need to call the function like thisnestdatacitydescriptiondepartmentthe first parameter is the entire dataset the second is an array of columns which define the nesting levelexpected json outputkey city value toronto count 1 children key description value programmer count 1 children key department value finance count 1 key city value vancouver count 2 children key description value tester count 3 children key department value finance count 1 key department value qa count 1 key department value it count 1 key description value manager count 1 key city value new york count 2 children key description value tester count 1 children key department value qa count 1 key description value manager count 1 children key department value hr count 1 i have tried writing a few recursive functions but keep getting stuck when i have to dynamically search the tree to avoid duplication,['javascript'] +220965,rjava not generated i have downloaded code from google codes but when i import that project in my eclipse ideit does not generate rjava filei searched many blogs and forums and tried many things like cleaning rebuilding creating project from existing source etc but still facing the problemsome people mentioned that it is sometimes caused by the svn client softwarebut none of them mentioned any solution for thati will be very thankful to you guys if you download it yourself and find what is the exact problem,['android'] +220999,loading json from string into jsonarray on android i have been experiencing some problems for quite some time trying to load a json string into a jsonarray i was hoping a post here would help me solve the problem the file is located in the assets folder and contain objects of the class kabelskap the json string is formatted like this excerptdriftsmerking1420 10 04objektnummer565690adressekanebogasen 4fabrikatnebbtypebetegnelseko500spenning023posisjonokkompnr1420kommune1901 harstadlatitude687786964342854longitude165598512563035driftsmerking4416 01 04objektnummer2463490adressenonsasenfabrikatabbtypebetegnelseko300spenning023posisjonokkompnr4416kommune1911 kvafjordlatitude687367985627796longitude162694481350258driftsmerking4080 05 02objektnummer2759330adressekvafjord planteskole veksthusfabrikatabbtypebetegnelseko700spenning023posisjonokkompnr4080kommune1911 kvafjordlatitude687712454761326longitude161901046355049driftsmerking1383 01 02objektnummer1509510adresseskillevn 13fabrikatabbtypebetegnelsespenning04posisjonokkompnr1383kommune1901 harstadlatitude687781436806564longitude165643438120601driftsmerking4085 07 02objektnummer2751220adressemathusetfabrikatnebbtypebetegnelse70spenning023posisjonokkompnr4085kommune1911 kvafjordlatitude687721426826508longitude161785193494225this string is read into a string variable which is then passed on into this code segmenttry jsonobject jsonobj new jsonobjectfinalstring forint i 0 i jsonlength i kabelskap ks kabelskap jsongeti skapputksobjektnummer ks catch jsonexception e eprintstacktracethis should according to what i expected return an json array which i then could iterate through and cast into objects of my class 1130 003133568 infosystemout389 driftsmerking1420 10 04objektnummer565690adressekanebogi12sen 4fabrikatnebbtypebetegnelseko500spenning023posisjonokkompnr1420kommune1901 harstadlatitude687786964342854longitude165598512563035driftsmerking4416 01 04objektnummer2463490adressenonsi12senfabrikatabbtypebetegnelseko300spenning023posisjonokkompnr4416kommune1911 kvi12fjordlatitude687367985627796longitude162694481350258driftsmerking4080 05 02objektnummer2759330adressekvi12fjord planteskole veksthusfabrikatabbtypebetegnelseko700spenning023posisjonokkompnr4080kommune1911 kvi12fjordlatitude687712454761326longitude161901046355049driftsmerking1383 01 02objektnummer1509510adresseskillevn 13 of type orgjsonjsonobject cannot be converted to jsonarray1130 003133588 warnsystemerr389 at orgjsonjsontypemismatchjsonjava1071130 003133588 warnsystemerr389 at orgjsonjsonarrayinitjsonarrayjava9130 003133588 warnsystemerr389 at orgjsonjsonarrayinitjsonarrayjava1031130 003133588 warnsystemerr389 at netlovholmkraftwerkkraftwerkoncreatekraftwerkjava68this error message indicates that there should be a problem with the formatting but to check this i have tested the json structure against some online validators and it seems to be valid the string as it is returned from the log seems to use a different encoding than that of the file utf8 i am not sure whether this may be a part of the problem or if this is just the character encoding of the log console any suggestion to this problem is very welcome update update update update i have now updated the code with the suggestions from ajesler which corrects some of the mistakes i did in the code excerpt above here is a longer excerpt from my code and i still experience problem with the error message above it seems this line jsonarray json new jsonarrayfinalstringcauses something malicious to happen in the jsonarray constructor the string passed in should accomodate the requirements of the api with valid json syntax and opening square brackets try assetmanager assetmanager getassets fis assetmanageropensourcepath bufferedreader bw new bufferedreadernew inputstreamreaderfis utf8 while str bwreadline null finalstring str catch filenotfoundexception e eprintstacktrace catch ioexception e eprintstacktracesystemoutprintlnfinalstringtry jsonarray json new jsonarrayfinalstring forint i 0 i jsonlength i jsonobject jsonobj jsongetjsonobjecti try kabelskap ks getkabelskapfromjsonjsonobj skapputksobjektnummer ks catch jsonexception e eprintstacktrace catch jsonexception e eprintstacktrace update 20 the systemoutprintlnfinalstring not sure whether the reader or the systemoutprintln skips long parts of the text i would presume that the ddms logcat is using a charset not supporting norwegian special letters1130 1102278 infosystemout4304 driftsmerking1420 10 04objektnummer565690adressekanebogi12sen 4fabrikatnebbtypebetegnelseko500spenning023posisjonokkompnr1420kommune1901 harstadlatitude687786964342854longitude165598512563035driftsmerking4416 01 04objektnummer2463490adressenonsi12senfabrikatabbtypebetegnelseko300spenning023posisjonokkompnr4416kommune1911 kvi12fjordlatitude687367985627796longitude162694481350258driftsmerking4080 05 02objektnummer2759330adressekvi12fjord planteskole veksthusfabrikatabbtypebetegnelseko700spenning023posisjonokkompnr4080kommune1911 kvi12fjordlatitude687712454761326longitude161901046355049driftsmerking1383 01 02objektnummer1509510adresseskillevn 13fabrikatabbtypebetegnelsespenning04posisjonokkompnr1383kommune1901 harstadlatitude687781436806564longitude165643438120601driftsmerking4085 07 02objektnummer2751220adressemathusetfabrikatnebbtypebetegnelse70spenning023posisjonokkompnr4085kommune1911 kvi12fjordlatitude687721426826508longitude161785193494225driftsmerking3410 05 12objektnummer351840adressehans egedesgt 20 eriksgatefabrikatnebbtypebetegnelsespenning023posisjonokkompnr3410kommune1901 harstadlatitude687980203542316longitude16538182961594driftsmerking0800 06 10objektnummer2669280adressegamnes vmagne harald olsenfabrikatabbtypebetegnelseko35spenning023posisjonokkompnrkommune1901 harstadlatitude688206299498345longitude164915959572276driftsmerking2580 02 02objektnummer1863790adresseressanfabrikatelmektypebetegnelse50 cmspenning023posisjonokkompnr2580kommune1913 ski12nlandlatitude686729130202412longitude17127746958547driftsmerking1500 10 06objektnummer1938750adressetuvslettvn 9fabrikatabbtypebetegnelseko500spenning023posisjonokkompnr1500kommune1901 harstadlatitude6874741783798longitude165517037722856driftsmerking3282 02 02objektnummer355470adressetegebi12rvn 12bfabrikatnebbtypebetegnelsespenning023posisjonokkompnr3282kommune1901 harstadlatitude687991934883357longitude165033927383319driftsmerking1430 05 02objektnummer1163750adressei12verland 2fabrikatabbtypebetegnelseko700spenning023posisjonokkompnr1430kommune1901 harstadlatitude687759663213591longitude165611455110691driftsmerking4150 05 06objektnummer2754960adresse nyvn 21fabrikatabbtypebetegnelseko500spenning04posisjonokkompnr4150kommune1911 kvi12fjordlatitude6877419257284longitude161726621696438driftsmerking1486 07 02objektnummer1621920adresseroholtvn 7fabrikatabbtypebetegnelseko 700spenning023posisjonokkompnr1486kommune1901 harstadlatitude687550368601091longitude165679658964195driftsmerking3025 02 06 3060 objektnummer351740adressehans egedesgt 6 hvedingsgatefabrikatnebbtypebetegnelsespenning023posisjonokkompnr3025kommune1901 harstadlatitude687994885383443longitude1654148173716driftsmerking7045 03 06objektnummer2514100adressekongsvikdalenfabrikattypebetegnelsespenning023posisjonokkompnr7045kommune1852 tjeldsundlatitude685682671357longitude162428412985428driftsmerking3010 03 02objektnummer351430adresse6divisjonsgt 10fabrikatabbtypebetegnelseko500 new update the full error trace from the jsonarraystring json constructor1203 1514290 warnsystemerr412 orgjsonjsonexception value posisjonokspenning023driftsmerking1420 10 04adressekanebogi12sen 4kompnr1420objektnummer565690typebetegnelseko500longitude165598512563035latitude687786964342854kommune1901 harstadfabrikatnebb of type orgjsonjsonobject cannot be converted to jsonarray1203 1514290 warnsystemerr412 at orgjsonjsontypemismatchjsonjava107 1203 1514290 warnsystemerr412 at orgjsonjsonarrayinitjsonarrayjava911203 1514290 warnsystemerr412 at orgjsonjsonarrayinitjsonarrayjava1031203 1514290 warnsystemerr412 at netlovholmkraftwerkkraftwerkoncreatekraftwerkjava661203 1514290 warnsystemerr412 at androidappinstrumentationcallactivityoncreateinstrumentationjava10471203 1514290 warnsystemerr412 at androidappactivitythreadperformlaunchactivityactivitythreadjava161203 1514290 warnsystemerr412 at androidappactivitythreadhandlelaunchactivityactivitythreadjava16631203 1514290 warnsystemerr412 at androidappactivitythreadaccess1500activitythreadjava1171203 1514290 warnsystemerr412 at androidappactivitythreadhhandlemessageactivitythreadjava9311203 1514290 warnsystemerr412 at androidoshandlerthispatchmessagehandlerjava991203 1514290 warnsystemerr412 at androidoslooperlooplooperjava1301203 1514290 warnsystemerr412 at androidappactivitythreadmainactivitythreadjava36831203 1514290 warnsystemerr412 at javalangreflectmethodinvokenativenative method1203 1514290 warnsystemerr412 at javalangreflectmethodinvokemethodjava5071203 1514290 warnsystemerr412 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava8391203 1514290 warnsystemerr412 at comandroidinternaloszygoteinitmainzygoteinitjava5971203 1514290 warnsystemerr412 at dalviksystemnativestartmainnative methodthe implementation of the jsonarray initialisation and the getkabelskapfromjson methodjson array initialisation excerpttry jsonarray json new jsonarrayfinalstringforint i 0 i jsonlength i jsonobject jsonobj jsongetjsonobjecti try kabelskap ks getkabelskapfromjsonjsonobj skapputksobjektnummer ks catch jsonexception e eprintstacktrace catch jsonexception e eprintstacktracegetkabelselskapfromjson methodprivate kabelskap getkabelskapfromjsonjsonobject jsonobj throws jsonexception string driftsmerking jsonobjgetstringdriftsmerkingstring adresse jsonobjgetstringaddressestring objektnummer jsonobjgetstringobjektnummerstring spenning jsonobjgetstringspenningstring fabrikat jsonobjgetstringfabrikatstring typebetegnelse jsonobjgetstringtypebetegnelsestring posisjon jsonobjgetstringposisjonstring kompnr jsonobjgetstringkompnrstring kommune jsonobjgetstringkommunestring latitude jsonobjgetstringlatitudestring longitude jsonobjgetstringlongitudekabelskap k new kabelskapdriftsmerking objektnummer adresse fabrikat typebetegnelse spenning posisjon kompnr kommune latitude longitudereturn k,['android'] +221035,page waits for all ajax calls to complete before updating sometimes on my page i do a lot of ajax calls at once concurrently the idea is that every element gets updated as its data becomes available i do not want to queue the calls sometimes however the webpage will not update any elements until all the ajax calls are complete for example i have four pictures in a row that i am updating each image has its own ajax callback that will update its source once that data is available the code looks something like thisfor var i 0 i numpictures i dajaxiceimagesload picturecallback function pictureid ithe callback function puts the image into its ui element once its readyimgsnippet img src dataimg source datacontainer idhtmlimgsnippetdata is the objects this function received from the serveri am using as you can see in the example dajax plugin for django for the ajax functionality on the server side i have an apache 22 running django 13 via mod wsgiwhen executed even though some ajax calls finish earlier i can see it on my server the page will not update any elements until the last call comes backany suggestionsthanks,"['javascript', 'jquery', 'html']" +221038,webkit bug with hover and multiple adjacentsibling selectors safari and chrome as well as opera and firefox can handle the hover pseudoclass and adjacentsibling selectorsahover div this workshowever when another adjacentsibling is addeddivhover a div webkit falls aparthowever if you first hover over a and then hover over the div the style is applied as it ought toi am further confounded because if you add divhover div with or without a style declared it starts working as it ought todemoi see this problem ingoogle chrome 150874121safari 511for os xany ideas,['css'] +221047,how to get the name of the running application in ios if the application name under the icon on the home screen is my awesome app how do you get that string within the application at runtime,['ios'] +221069,array unique vs array flip if i had an array of signed integers egarray 0 3 1 1 2 2 3 3 4 3to get unique values i would instinctively use array unique but after consideration i could perform array flip twice which would have the same effect and i think it would be quickerarray unique on log n because of the sort operation it usesarray flip on am i correct in my assumptionsupdate exampleintarray1 array4123print rintarray1intarray1 array flipintarray1print rintarray1intarray1 array flipintarray1print rintarray1array 0 3 1 1 2 2 3 3 4 3array 3 0 1 1 2 2 3 4array 0 3 1 1 2 2 4 3,['php'] +221084,gui architecture and design in java swing i have spent the last several hours scouring the internet looking for examples and ideas on how to write a medium sized gui in java i know a little about swing but that is all i do not know of any other way to develop a gui in java besides swing if you know of a different way that would be good too i also want to handwrite the gui myself to allow for easier integration with our game and future refactoringwe have written the entire business logic to a tic tac toe game that has several features the gui needs to have several windows which can be navigated using simple buttons on the interface a very crude and waterdowned version of what i am looking to do can be seen below the heart of my question is thishow do i architect the gui using swing and what general design is usedand some followup questionsis there a class for every window do i just use setvisible to make my windows appear and thisappear after the buttons are pressedre there any examples you all know of github repos would be excellent happy forking that could show me a good gui architecturedesign,['java'] +221123,c templates specialization syntax in c primer plus 2001 czech translation i have found these different template specialization syntaxfunction templatetemplate typename t void footspecialization syntaxvoid fooint param 1void foointint param 2template void foointint param 3template void fooint param 4template void fooint param 5googling a bit i have found only no3 examples is there any difference in call compiling usage among them are some of them obsoletedeprecated why not just use no1,['c++'] +221127,java get uri from filepath i have little knowledge of java i need to construct a string representation of an uri from filepathstring on windows sometimes the inputfilepath i get is filecatxt and sometimes it is catxt right now what i am doing isnew fileinputfilepathtouritourltoexternalformthe above works fine for paths which are not prefixed with file but for paths prefixed with file the touri method is converting it to a invalid uri by appending value of current dir and hence the path becomes invalidplease help me out by suggesting a correct way to get the proper uri for both kind of paths,['java'] +221153,pythonic way to assign default values consider this linesome value lstattridxthere are two possible errors here the attr might not exist and the idx might be out of rangeis there any elegant way to reduce this statement ideally to something like thissome value lstattridx or default valuedo not try that at home that only works for properly defined expressions that evaluate to somethingsure i can dotry some value lstattridxexcept some value default valuebut what if i am in the context of an assignment for exampleprint xattridx for x in ywhats the pythonic way to handle errors and assign default values in this case,['python'] +221163,creating xdocument with xsischemalocation namespace i need to create the following xml and i am trying to do this using xdocument however i am having trouble specifying the name spacesassessmentorderrequest xsischemalocation 5hrxml2 5standaloneassessmentorderrequestxsd xmlns xmlnsxsiassessmentorderrequestthis is the sort of code that i am looking for however i cannot create attributes with a colon in the name for the xsischemalocationreturn new xdocument new xelementassessmentorderrequest new xattributexsischemalocation xnamespaceget 5hrxml2 5standaloneassessmentorderrequestxsd new xattributexmlns xnamespaceget new xattributexnamespacexmlns xsi xnamespaceget,['c#'] +221180,how to call a nonconst method from a const method i have got a const method in my class which cannot be changed to nonconst in this method i need to call a nonconst method but the compiler does not let me do thatis there any way around it here is a simplified sample of my codeint someclasomemethod const qcolor savecolor color setcolorqcolor255255255 calling nonconst method setcolorsavecolor restore color return 1,['c++'] +221243,what are the fastest gdi rendering settings there is quite a lot of post about rendering high quality graphics like this onehigh quality image scaling ci need to render about 6k object line and ellipse in a graphics with gdi at a framerate of around 10fps so i need the lowest quality property possible for my graphicshere is what i have done public static class graphicsextensions public static void tohighqualitythis graphics graphics graphicsinterpolationmode interpolationmodehighqualitybicubic graphicscompositingquality compositingqualityhighquality graphicssmoothingmode smoothingmodehighquality graphicstextrenderinghint textrenderinghintcleartypegridfit graphicspixeloffsetmode pixeloffsetmodehighquality public static void tolowqualitythis graphics graphics graphicsinterpolationmode interpolationmodelow graphicscompositingquality compositingqualityhighspeed graphicssmoothingmode smoothingmodehighspeed graphicstextrenderinghint textrenderinghintsystemdefault graphicspixeloffsetmode pixeloffsetmodehighspeed did i forgot something or is this the best possible extremum for the property of graphicsi am drawing at 5fps 202msimage with the lower mode and 3fps 330msimage with higher modei do not feel there is a big difference but i have reduce my performance problem to drawing onlysome numbers 1650 call to drawline6600 call to fillellipse,"['c#', '.net']" +221254,order of condition execution in mysql suppose i have a mysql query with two conditionsselect from table where field 1 1 and field 2 like termthe first condition is obviously going to be a lot cheaper than the second so i would like to be sure that it runs first limiting the pool of rows which will be compared with the like clause do mysql query conditions run in the order they are listed or if not is there a way to specify order,['mysql'] +221283,xsd gen classes that reference a common type i am using xsds to define my dto types in c i am using xsdexe to gen the classes from the xsdsi have a commonxsd that defines an address type and i want to use this in more than one class xscomplextype nameaddress xssequence xselement namestreet1 typexsstring xselement namestreet2 typexsstring xselement namecity typexsstring xselement namestate typexsstring xselement namezip typexsstring xssequence xscomplextype xselement nameaddress typemhmaddressi am referencing this in a company xsd xsinclude schemalocationcommonxsd xscomplextype namecompany xssequence xselement nameadmcode typexsstring xselement namecompanycode typexsstring xselement namename typexsstring xselement refmhmaddress xssequence xscomplextype xselement namecompany typemhmcompanyand an employee xsd xsinclude schemalocationcommonxsd xscomplextype nameemployee xssequence xselement nameemployeenumber typexsint xselement namefirstname typexsstring xselement namelastname typexsstring xselement nameaddress typemhmaddress xssequence xscomplextype xselement nameemployee typemhmemployeei gen the classes using this command linexsd xsdcommonxsd c o ndomainmodelxsd xsdemployeexsd c o ndomainmodelxsd xsdcompanyxsd c o ndomainmodelwhen i go to compile the project i find that the address type has been generated in both the companycs class file and the employeecs class filehow can i get the address type generated just once in the commoncs class file and the employee and company types use this single address type,['c#'] +221308,convert derived class to base class i am trying to refresh my memory but cannot find answers with googlepublic class baseclass public virtual void dosomething tracewritebase class public class derivedclass baseclass public override void dosomething tracewritederived class if i create an instance of derived class how do i convert it to it is base class so that when dosomething is called it uses the base clas method onlya dynamic cast still calls the derived clas overridden methodderivedclass dc new derivedclassdcdosomethingdc as baseclassdosomethingoutput derived class,['c#'] +221339,generic or instead of and is it possible to generically parameterize a method accepting either classa or interfaceb does not compile due to pseudocodepublic t extends number charsequence void ordoert somedata ie instead of writing multiple method signatures i would like this one method to accept either a number or charsequence as an argumentshould pass with a number or charsequence argumentordoernew integer6int someprimitive 4ordoersomeprimitiveordoera string of chars,"['java', 'android']" +221342,how to thisable textbox from editing i want to use a text box to thisplay some text i can not thisable it because then the scroll bar will not workhow can i prevent editing within the multiline textbox yet make it appear as if it is enabled so that the scroll bar works correctly,['c#'] +221358,how does google analytics real time work i am wondering how google analytics real time user interface works whats the technique do they use longpolling from the client to keep the ui statistics instantly up to date by delivering realtime information from the server to the clienti just open chrome dev tool on network tab and there is a infinite request on does anybody know the trick it works flawless,['javascript'] +221371,center fluid grid of elements without setting hard width on parent i would like to center a grid of elements thatawhen resizedaadjusts to center itselflike this i have tried setting a maxwidth but that leads to this problem when resized i do not consider using media queries and setting hard widths or even maxwidths for every configuration a real solutioni am open to css3 as long as it degrades gracefully and would like to avoid javascriptedit adding nonsemantic elements is also a deal breaker a container div or something would be passable but not idealthe markup should be as follows ul lili lili lili ulhere is a demo to get you startedthank you,"['html', 'css']" +221374,is it possible to make oauth secure on ios is it possible to make oauth secure on iosi am investigating oauth 20 as a means to implement single signon authorization for a suite of ios apps to explain my concerns i will simplify and use facebook a 3rd party app that uses facebook for authentication let us say wordswords with friendsfor the purpose of example i will assume that facebook registers to support schemeprotocol facebook and that words registers to support wordsi also make the assumption that it is not possible to secure the clientsecret or the protocol in an ios application because you can decompile the application any ways that i have come up with to secure this results in security by obscurityanother assumption is that there is no way to prevent two applications from registering to handle the same protocol the behavior when two apps both register for the same protocol is indeterminate although it appears that the first app to launch on the device gets registered while the second apps registration is ignoredif i understand the workflow between facebook useragent and words client on the ios deviceuser launches wordsuser chooses to logon via facebook credentialswords invokes openurlfacebook which contains among other things an identifier for words as an application and a redirect uri ie wordsios launches facebook applicationuser enteres credentials which facebook application validates against facebook authorization serveruser prompted to authorize words to access facebook data ie words can access my friends listfacebook invokes callback uri provided by words along with access token ie wordsaccess tokentoken herewords uses this token to access my friends list ie protected resource dataassuming the above is correct if i want to be malicious and access random peoples friends list i could create an application that also registers to handle the protocol words and get it on the app store if someone has my app and words installed and my app is the one that successfully registered ie launched on the device before words thenlaunch words choose to logon launches facebookuser authenticates authorizesfacebook attempts to redirect back to words by invoking openurl on the redirect urlmy app not words is launchedmy app now has access to the auth code which with the secret learned by decompiling can be exchanged for an access token with rights to access your friends listi am hoping that my reasoning is flawed above or i would have to conclude specifically that facebook ios authentication for 3rd party apps is insecuremore generically is it possible to implement oauth 20 authorizationimplicit grant workflows securely on ios application,['ios'] +221400,how can i get a listview gridviewcolumn to fill the remaining space in my grid i want to create a listview that has two columns with a fixed width and a third column to fill in the remaining space so something like thislistview listviewview gridview gridviewcolumn headername width gridviewcolumn headerage width50 gridviewcolumn headergender width50 gridview listviewviewlistviewthe problem is i cannot find a way to get the name column to fill in the remaining space as setting the width to does not work it looks like there is a way to do this with a value converter but it seems like there should be a simpler way like with a datagrid control you can specify the widths of columns with s,['.net'] +221406,frp on a game engine is it worth it today i have read about frp functional reactive programming however i do not know how much this fits in the engine itself after reading gerold meisingers article my question is if it is worth it to use frp instead of a componentbased architecture is this the near future of game engine architecture design it is just a simple approach on solving small problems componentbased architectures do i would appreciate any article explanation personal opinion etcthink about an engine for a commercial game specially shooters or racing genres 3d games do not think about a 2d platformer or other simpler talking about engine complexity ones i would use cc i noticed people using frp rely on haskell due to its nature however i saw this document and prefer to stand on c as the industry standard,['c++'] +221407,pythons urllib2urlopen hanging with local connection to a java restlet server i am trying to connect to a local running restlet server from python but the connection hangs infinitely or times out if i set a timeoutimport urllib2handle urllib2urlopenhttplocalhost8182contact123 hangsif i use curl from a shell to open the above url the results return quickly if i use urllib2 to open a different local service eg a django web server on port 80 urllib2 works fine i have tried thisabling firewall i am doing this on os x i have tried changing localhost to 127001 the logs from restlet for both the curl and urllib2 connection appear the same aside from the useragent my workaround would be to just call curl via subprocess but i would rather understand why this is failingheres how my restlet resource lookspublic class contactresource extends serverresource get public string represent throws exception return contact details let me know if you want more infocode,"['java', 'python']" +221409,how to get around sysexit in python nosetest it seems that python nosetest will quit when encountered sysexit and mocking of this builtin does not work thanks for suggestions,['python'] +221426,unordered collection for unhashable objects i have got a dict where some of the values are not hashable i need some way to compare two unordered groups of these to ensure they contain equal elements i cannot use lists because list equality takes the order into account but sets would not work because dicts are not hashable i had a look through the python docs and the only thing that looks useful is a dicts view which is hashable under some circumstances but in this case this does not help either as one of the values is an object which contains lists itself meaning the dicts view would not be hashable eitheris there a standard container for situations like this or should i just use lists and loop through every element in both lists and ensure an equal element is somewhere in the other list,['python'] +221428,fill an array using a foreach loop i am trying to fill an array with my foreach loop but i do not get it to work what am i doing wronga arrayactivities projectgetprojectnames db projectnaamifemptyactivities foreachactivities as k v a array fillvname all i get back is the string array,['php'] +221446,checking java files for errors not limited to strings many of the standard source code checking tools pmd findbugs checkstyles all implement a string equality rule where the usage of or when comparing strings can be detected and reported as an errori am looking to write or configure a similar rule that works on a set of other object types in my apiwant to detect things likeinstance a instance b if a b error here not using aequalsblooking at pmd findbugs there is no obvious or easy way to do this has anyone come across something like this cheersro,['java'] +221452,zmq pubsub program failure when losing network connectivity i have a simple pubsub setup on a midsized network using zmq 21 although some subscribers are using c bindings others are using python bindings and the issue i am having is the same for eitherif i pull the network cable from a machine running a subscriber i get an uncatchable error that immediately terminates that subscriber heres a very simple example of a subscriber in python not actual production code but enough to reproduce the problemimport zmqdef mainserver address port context zmqcontext sub socket contextsocketzmqsub sub socketconnecttcp server address strport sub socketsetsockoptzmqsubscribe kith1s2 while true msg sub socketrecv print msg if name main maincompanyintranet 40in c the program simply terminates silently in python i at least get thisassertion failed rc 0 srczmq connectorcpp48this application has requested the runtime to terminate it in an unusual way please contact the applications support team for more informationi have tried nonblocking versions and poller versions but in either case this instant termination problem persists is there something obvious i should be doing but i am not that is obvious to someone else editfound the following seems as though it iswas a known issue that link further links to github where a change log for 2110 has this notefixed issue 207 assertion failure in zmq connectercpp48 when an invalid zmq connect string was used or the hostname could not be resolved the zmq connect call now returns 1 in both those casesalthough connect does indeed throw an invalid argument exception in python not c apparently recv still fails if the subscriber machine suddenly loses the network that subscriber will simply stop functioning so i am going to try using ip addresses instead of named addresses to see if this will bypass the issue not ideal but better than instacrash,"['c#', 'python']" +221480,generating ipa from xcode commandline whats the best approach for generating an ipa file from commandlinei am on xcode 42 and generating the archive usingxcodebuild scheme appstore clean archivethis generates the dsym and app files in the build output directory after codesigning how should i proceed to generate the ipa file in other words i am looking for the commandline equivalent of doing the following in guiorganizer archivesshareios app store packagedo not resignthanks,['ios'] +221500,complexity requirements for stddequepush backfront as a result of this question from a few days ago there are a few things that have been bugging me about the complexity requirements for stddequepush backpush front vs the actual stddeque implementations out in the wildthe upshot of the previous question was that these operations are required to have o1 worst case complexity i verified that this was indeed the case in c11from 234 deque modifiers refering to insert pushemplace frontbackcomplexity the complexity is linear in the number of elements inserted plus the lesser of the thistances to the beginning and end of the deque inserting a single element either at the beginning or end of a deque always takes constant time and causes a single call to a constructor of tthis is combined with the o1 complexity requirement for indexing via operator etcthe issue is that implementations do not strictly satisfy these requirements in terms of both msvc and gcc the stddeque implementation is a blocked data structure consisting of a dynamic array of pointers to fixed size blocks where each block stores a number of data elementsin the worst case push backfront etc could require an extra block to be allocated which is fine fixed size allocation is o1 but it could also require that the dynamic array of block pointers be resized this is not fine since this is om where m is the number of blocks which at the end of the day is onobviously this is still amortised o1 complexity and since generally m n it is going to be pretty fast in practice but it seems there is an issue with conformanceas a further point i do not see how you can design a data structure that strictly satisfies both the o1 complexity for both push backfront etc and operator you could have a linkedlist of block pointers but this does not give you the desired operator behaviour can it actually be done,['c++'] +221508,how to crawl a websiteextract data into database with python i would like to build a webapp to help other students at my university create their schedules to do that i need to crawl the master schedules one huge html page as well as a link to a detailed description for each course into a database preferably in python also i need to log in to access the datahow would that workwhat toolslibraries canshould i useare there good tutorials on thathow do i best deal with binary data eg pretty pdfare there already good solutions for that,['python'] +221526,wait to return from a javascript function until condition met this is an odd problem i have a client object that i am building up using crockfordesque publicprivate membersvar client function var that remote data other data add public interface thatdostuff function wait for remote resources to load remote data jsonrequest1 other data jsonrequest2 return thatthe problem i am having is that i need to load some remote json resources prior to returning the new that object which signals a ready client data is returned asynchronously obviously and i am setting boolean variables to indicate when each remote resource has returnedi have thought about doing something like the followingreturn wheninitializedfunction return that the wheninitialized function returns whether or not both of the boolean flags are true i would use this with a combination of setinterval but i am sure this would not workwould appreciate your suggestions,['javascript'] +221528,unity3d integration with uiview please correct me if this question is duplicatedi just came across unity3d and i just want to ask if it is possible to integrate unity3d on top of other uiview,"['iphone', 'ios']" +221532,get a checkbox in word using openxml how does one get a handle to a checkbox control that is embedded in a word document using openxmlyou would think that either paragraphcontrolpropertiespart or paragraphdescendents would achieve something but in every single case i get a null type returnedi can traverse down the document tree using the actual xml structure but this seems cumbersomesuggestions welcome,['c#'] +221548,deny direct url access to action method i am trying to find a way to deny any direct access to my action methods basically what i want my users to click on links to navigate instead of typing the url directly into the address bar in their browsersnow i know this can be done by checking the urlreferrer in the request object but this is kind of unreliable and weak because the urlreferrer can easily be modified and some of the security suites actually remove it from the requestso does any of you know of a way to do this in aspnet mvc3,['c#'] +221561,custom single choice listview i urgently want to make a custom list view having two textviews and a radio button in a single row and on listitem click the radio button state should be toggle i cannot use simple adapter herei have already asked that question single choice listview custom row layout but dont find any satisfactory solution so this time i am asking with some more detailswhat i am currently doing is i am using simple list item single choice and putting data of both textviews in a single one separated by some white spaces but here it is getting worseshown in the image from link belowwhat i want is to fix the location of size and price and make list view as single choicexml layout for the list can be something like xml version10 encodingutf8linearlayout xmlnsandroid androidididlayout androidlayout widthfill parent androidlayout heightwrap content androidgravitycenter horizontal androidorientationhorizontal textview androidididtv size androidlayout widthwrap content androidlayout heightwrap content androidtexttextview androidtextsize15sp androidwidth200dp textview androidididtv price androidlayout widthwrap content androidlayout heightwrap content androidtexttextview androidtextsize15sp androidwidth70dp radiobutton androidididradiobutton androidlayout widthwrap content androidlayout heightwrap content linearlayoutany help for making custom adapter for that will be highly appreciated,['android'] +221564,c11 how do i implement convenient logging without a singleton my current implementation simplifiedinclude stringinclude memoryclass log public log closing filedescriptors etc static void logmsg const stdstring msg static stdunique ptrlog g singleton if g singletonget g singletonreset new log g singletonlogmsg msg private log void logmsg const stdstring msg do work in general i am satisfied with this implementation becauselazy instantiation means i do not pay unless i use ituse of unique ptr means automatic cleanup so valgrind is happyrelatively simple easytounderstand implementationhowever the negatives aresingletons are not conducive to unittestingthissonance in the back of my mind for introducing a pseudoglobal a bit of a code smellso here are my questions directed towards those developers who are successful in exorcising all singletons from their c code what kind of nonsingleton implementation do you use for applicationwide loggingis the interface as simple and accessible as a loglogmsg call abovei want to avoid passing a log instance all over my code if at all possible note i am asking because i too want to exorcise all singletons from my code if there is a good reasonable alternative,['c++'] +221577,androideclipse moved workspace from one computer to another computer i followed these instruction but did not know what file to select after checking in my project propertiesproperties libraries unable to get system library for the project access rules no rules defined native library location none add external jars program file java jre6 is it lib or bin then what do i select after thaterrors description resource path location type the project was not built since its build path is incomplete cannot find the class file for javalangobject fix the build path then try building this project unknown java problem the project was not built since its build path is incomplete cannot find the class file for javalangobject fix the build path then try building this project unknown java problem the type javalangobject cannot be resolved it is indirectly referenced from required class files the type javalangobject cannot be resolved it is indirectly referenced from required class files unable to resolve target android8 unknown android target problem unable to resolve target android8 until the sdk is loaded unknown android target problem unable to resolve target google incgoogle apis8 unknown android target problem unable to resolve target google incgoogle apis8 until the sdk is loaded unknown android target problem,['android'] +221606,c11 replace all nonowning raw pointers with stdshared ptr with the advent of stdunique ptr the blemished stdauto ptr can finally be put to rest so for the last several days i have been changing my code to use smart pointers and to eliminate all delete from my codealthough valgrind says my code is memoryclean the semantic richness of smart pointers will make for cleaner and easiertounderstand codein most of the code the translation is simple use stdunique ptr for in place of the raw pointers held by the owning objects throw out delete and carefully sprinkle get reset and move calls as needed to interface well with the rest of the codei am at the point where i am translating nonowning raw pointers to smart pointers nowsince i was careful with the lifetimes of my objects i ensure my modules only depend in one direction valgrind tells me that i do not have any uninitialized reads dangling pointers or leaks so technically i could just leave those nonowning raw pointers alone nowhowever one option is to change those nonowning raw pointers to stdshared ptr because i know they are acyclic or would it be better to leave them as raw pointersi need some advice from veteran users of smart pointers as to what rules of thumb you use to decide whether to keep nonowning raw pointers asis or to translate them into stdshared ptr keeping in mind that i constantly unittest and valgrind my codeedit i might be misunderstanding the use of stdshared ptr can they be used in conjunction with stdunique ptr or is it the case that if i use stdshared ptr all handles should also be stdshared ptr,['c++'] +221619,animating headers of a listview giving classcastexception i have listview that stores the communication history of a person i have one header inside a listview that acts as a message editor with a edit text and a send buttonwhen a user types something and press send button the messages adds to the communication list and editor gets empty what i want is when user press the send button the editor should become invisible and item should be added to the listview after that the editor should come gradually from the top giving the feel that its moving the items belowi have implemented a translate animation on the header but what it does is it makes the space for it by pushing the items down and then gradually fills the space which i dont wanti used the negative margin trick which is explained in this question but it did not work for me as we cant use layout params other that abslistviewlayoutparam for the headers i tried setting other params but while animating it gives me classcastexception i tracked the exception and its due to code written inside listview they are trying to cast these params with abslistviewlayoutparams inside clearrecycledstate method or is there a way to apply layout params that supports margin on a listviewheaderthe codepublic class pagelistview extends listview private application app private commlistadapter listadapter private messageeditorheader messageeditorheader private messageitemlongclick minterface private handler handlerpublic profilepagelistviewapplication app messageitemlongclick minterface superapp thisapp app thisminterface minterface thishandler new handler setupviewpublic void applydataprofiledata data listadapterapplydatadatagetuser some other business logic private void setupview messageeditorheader new messageeditorheaderapp addheaderviewmessageeditorheader listadapter new commlistadapterapp minterface setadapterlistadapter setdividernull setscrollingcacheenabledfalse tanimation new translateanimation00f 00f 900f 00f tanimationsetzadjustment1 tanimationsetduration1500 this gets called whenever the communication gets added to the listviewpublic void onnewcommunicationcommunication lc listadapteronnewcommunication iflc null lcisoutgoing lcgettypeiscall getmessageeditorstartnewmessage messageeditorheadersetvisibilityvisible this is overriden method here i m toggling the height 1px and wrap content messageeditorheaderstartanimationtanimation few more methods are thereheres the code of message editorpublic class messageeditorheader extends relativelayout private messageeditor msgeditorpublic messageeditorheaderappteraapplication context supercontext msgeditor new messageeditorcontext its a relative layout containing edit text and the send button addviewmsgeditorpublic messageeditor getmsgeditor return msgeditorpublic void setprogressint progress msgeditorsetprogressprogress overridepublic void setvisibilityint visibility thisvisibility visibility if visibility viewvisible listviewlayoutparams params new listviewlayoutparamslistviewlayoutparamsfill parent listviewlayoutparamswrap content setlayoutparamsparams else listviewlayoutparams params new listviewlayoutparamslistviewlayoutparamsfill parent 1 setlayoutparamsparams,['android'] +221625,how can i use certificate authentication with httpsurlconnection i am trying to connect to an https url but i need to use client authentication with a certificate placed on my system by third party softwarei have not the slightest idea how i am supposed to either find or use it and all i have to go on is c sample code which differs significantly with all the java answers i have found about this for instance the keystore needs some sort of password apparentlythis is the c sample code i havesystemsecuritycryptographyx509certificatesx509certificatecollection ssc certs new systemsecuritycryptographyx509certificatesx509certificatecollectionmicrosoftwebservices2securityx509x509certificatestore ws2 store microsoftwebservices2securityx509x509certificatestorecurrentuserstore microsoftwebservices2securityx509x509certificatestoremystorews2 storeopenreadmicrosoftwebservices2securityx509x509certificatecollection ws2 store certs ws2 storecertificatesand then it just iterates over the ws2 store certs certificatecollection and checks them all that waya bit further on it sets the certificates like thishttpwebrequest httpwebrequest httpwebrequestwebrequestcreateurl stringhttpwebrequestclientcertificates ssc certsthis all looks fairly logical even if i have no idea how it finds the certificates but i still have not been able to find the java equivalent of thisupdatethe connection i am making is part of a larger application that depends on jdk 5 but i have managed to just use the sunmscapi jar to find the certificate i am looking for it errors when i try to connect using the windows keystore though so i thought i got around the problem by getting the certificate i need from the windows store and inserting it in the default java one now i am getting an eofexception followed by an sslhandshakeexception saying remote host closed connection during handshake the ssl debug trace does not reveal an immediate problem to me since the certificate i need is thisplayed in the certificate chain here it does the whole clientkeyexchange thing says it is finished and then the last messages i get from the debug log right after that arewrite md5 and sha1 hashes len 160 14 00 00 0c d3 e1 e7 3d c2 37 2f 41 f9 38 26 cc 7a8padded plaintext before encryption len 320 14 00 00 0c d3 e1 e7 3d c2 37 2f 41 f9 38 26 cc 7a80010 cb 10 05 a1 3d c3 13 1c ec 39 ed 93 79 9e 4d b0 9ymawteventqueue1 write tlsv1 handshake length 32raw write length 370 16 03 01 00 20 06 b1 d8 8f 9b 70 92 f4 ad 0d 91 p0010 25 9c 7d 3e 65 c1 8c a7 f7 da 09 c0 84 ff f4 4a ej0020 ce fd 4d 65 8d meawteventqueue1 received eofexception errorand the code i am using to set up the connection iskeystore jks keystoregetinstancekeystoregetdefaulttypejksloadnull nullkeymanagerfactory kmf keymanagerfactorygetinstancesunx509jkssetcertificateentryalias cert1 x509certificate obtained from windows keystorekmfinitjks new char0sslcontext sslcontext sslcontextgetinstancesslsslcontextinitkmfgetkeymanagers new trustmanagertm nullsslsocketfactory sslcontextgetsocketfactorysystemsetpropertyhttpsproxyhost proxyurlsystemsetpropertyhttpsproxyport proxyportauthenticatorsetdefaultnew myauthenticatorproxyid proxypasswordurl url new urlnull urlstr new sunnetwprotocolhttpshandlerhttpsurlconnection uc httpsurlconnection urlopenconnectionucsetsslsocketfactorysslsocketfactoryucsetallowuserinteractiontrueucsetrequestmethodpostucconnecti have not tried httpclient yet because i have no idea how to find the certificate file and i am also not sure if this will always be the same on every client systemanother updatei have found the cas for the certificate i need in the windowsroot keystore and checked with verify to see that they all check out i have added them to the java keystore as well but still nothing changes i guess they are supposed to go in the truststore but i have yet to find a way to do that programatically would prefer not to rely on end users to do this kind of thing as all i can guarantee from them is that the certificate and cas will be present due to the third party software mentioned at the start of this ridiculously long question yet more updatesadding on the previous update i have come to the conclusion that my problem must lie in the fact that my cas are not in javas cacerts file so it gets the list of trusted cas from the server but does not recognise them and subsequently does not send a single certificate back causing the connection failureso the problem remains how do i get java to either use it is keystore as truststore or add certificates to cacerts programmatically without the need for file paths because if those are not possible that just leaves me with secret option c voodoo i will start stabbing a duke doll with needles just in case,['java'] +221630,start rails development environment on android is it possible to run the ruby on rails development environment on android like we do on macubuntuwindows if not then please post comments to why is not possible,"['android', 'ruby-on-rails', 'ruby']" +221758,boost variant how to get currently held type as i understood all types of boostvariant are parsed into real types meaning as if boost variantint string a ablabla would after compilation turn into string a ablabla and so i wonder how to get what type was put into boost variant what have i triedinclude boostvarianthppinclude boostfunctionhppinclude boostshared ptrhppinclude iostreamint main typedef boostfunctiondouble double x func0 typedef boostfunctiondouble double x double y func1 typedef boostvariantint func0 func1 variant func func1 fn stdplusdouble variant func vfn stdcout boostgetfunc1v10 10 stdendl this works stdcout boostgetvtypev10 10 stdendl this does not compile with many errors stdcout v10 10 stdendl this fails with error 1 error c2064 term does not evaluate to a function taking 2 arguments stdcinget return 0,['c++'] +221762,why does nsmutablestring stringwithstring work just wonderingin nsstring there is a static method called stringwithstringthis is not redeclaredoverridden in nsmutablestring so we cannot assume that this will return an nsmutablestring in fact even in the nsstring class the return type is defined as id and the doc statesreturn value a string created by copying the characters from astringwhat part of objective c am i missing in my knowledge to understand why this works and returns an nsmutablestring especially because the base class nsstring is not aware that we want a mutable string in return one could say that internally class alloc is called which will generate an object of type nsmutablestring but even this is pure guesswork as we do not have the source code and stringwithstring could do whatever it wants internallyare all those class methods reimplemented in the subclass and if yes why is not this documented,['objective-c'] +221773,css transform that looks like a hardcover book being opened i am trying to create a css transform on a div that makes it look like the cover of a book opening this means the left side is bound and the right side flys towards the user getting largercan anyone offer some direction if it works in webkit that is all i neededit i am looking for the effect you would find with a hardcover book i do not want the pages to bend or fold just the right side comes out at the useri have done this it is pretty close but i cannot get the left side to lock in place webkitkeyframes bookcover 0 webkittransform perspective400px rotatey0deg opacity 1 100 webkittransform perspective400px rotatey90deg opacity 0got it you need to change the orgin webkittransformorigin top left,"['javascript', 'html', 'css']" +221778,codeigniter making my controllers more dry in my codeigniter controller function i am using the following code to generate my view and insert all the necessary content left column thisloadviewwidgetssub navigation subnav data true left column thisloadviewwidgetssearch box true set data to be loaded into columns left column base thisloadviewwidgetsassist navigation true center column this is center column right column thisloadviewwidgetsask us a question true right column thisloadviewwidgetsnewsletter true right column thisloadviewwidgetslatest news true thistemplateinject partialleft column left column inject data into the partial columns thistemplateinject partialleft column base left column base thistemplateinject partialcenter column center column thistemplateinject partialright column right column thistemplatebuildtemplatedata i am using a three column layout and the code above dictates what is shown in each of the columns it works in a very modular way allowing me to customize each page quicklyis there a way of simplifying the above code using arrays maybe to cut down on repetetive code making things more dry,['php'] +221781,make the backgroundcolor of a fill the enclosing i have an html table whose cells contain divs with thisplayinlineblock containing text of varying sizesi need the text to align on the baseline and i need the background colors of the divs to fill the height of the cells for the largest font the background color does fill the cell but it does not for the smaller fontsis this possible obvious solutions like div height100 seem to be scuppered by the varying font sizesheres the code so fardoctype htmlhtml langenhead meta charsetutf8 style typetextcss table td verticalalign baseline padding 0 td div thisplay inlineblock styleheadbody table tr td stylebackgroundcolorcyan div stylebackgroundcolorpinkpinkdiv div stylebackgroundcolorgreengreendiv td td stylebackgroundcolorcyan div stylefontsize 40pt backgroundcoloryellow big yellow text div td tr tablebodyhtmlit is also on jsfiddle here,"['html', 'css']" +221790,java difference between classforname and classloaderloadclass recently came across some code that got me thinking whats the difference betweenclass theclass classfornamesomeimplsomeimpl impl someimpltheclassnewinstanceandclass theclass classloaderloadclasomeimplsomeimpl impl someimpltheclassnewinstanceare they synonymous is one preferable to the other in certain circumstances what are the dos and donts to using these two methodsthanks in advance,['java'] +221815,uibutton cannot be touched while animated with uiview animatewithduration i have the following codeuiview animatewithduration03 delay00 optionsuiviewanimationcurveeaseout uiviewanimationoptionallowuserinteraction animations cgrect r btn frame roriginy 40 btn setframe r completionbool done ifdone uiview animatewithduration03 delay1 optionsuiviewanimationoptioncurveeasein uiviewanimationoptionallowuserinteraction animations cgrect r btn frame roriginy 40 btn setframe r completionbool doneifdone zombiepopping 0 the problem is it seems the button doesnt respond to touches while being animated even though i am using uiviewanimationoptionallowinteraction which is a bit weird to me maybe this most be done with core animation to work and if so how would i go about that,"['iphone', 'objective-c', 'ios']" +221826,database of all countries with all cities in respective country can i get database of all countries with all respective cities for mysql,['mysql'] +221832,is there a way to do a put with webclient with the webclient class in net 40 is there a way to do a puti know you can do a get with downloadstring and a post with uploadstring but is there a method or property that lets you do a putthanks,['c#'] +221862,is that is a bug with checkbox in android i am using 21 android version i was creating a check box and i saw something strange with checkbox when i put androidpadding5dp the check box shown asbut the text should be shown next to checkbox when i remove padding its looks fine is that mean it is a bug or i am taking it in a wrong sense checkbox androidididcheckbox androidlayout widthwrap content androidlayout heightwrap content androidlayout gravityleft androidlayout marginleft10dp androidpadding5dp androidtextselect the checkbox androidtextcolorcolorblack,['android'] +221863,entity framework is too slow what are my options i have followed the do not optimize prematurely mantra and coded up my wcf service using entity frameworkhowever i profiled the performance and entity framework is too slow my app processes 2 messages in about 12 seconds where the legacy app that i am rewriting does 56 messages in the same time the legacy app calls sprocs for its db accessmy profiling points to entity framework taking the bulk of the time per messageso what are my options are there better orms out theresomething that just supports normal reading and writing of objects and does it fast is there a way to make entity framework fasternote when i say faster i mean over the long run not the first call the first call is slow 15 seconds for a message but that is not a problem i just need it to be fast for the rest of the messagessome mysterious 3rd option that will help me get more speed out of my servicenote most of my db interactions or create and update i do very very little selecting and deleting,['.net'] +221868,how do i avoid infinite recursion with a custom enumerator i made an extension method to find the number of consecutive values in a collection because it is generic i allow the caller to define the incrementor which is a func that is supposed to increment the value in order to check for the existence of a next valuehowever if the caller passes an improper incrementor ie x x it will cause an infinite recursive loop any suggestions on a clean way to prevent thispublic static int countconsecutivetthis ienumerablet values t startvalue funct t incrementor if values null throw new argumentnullexceptionvalues if incrementor null throw new argumentnullexceptionincrementor var nextvalue incrementorstartvalue return valuescontainsnextvalue valuescountconsecutivenextvalue incrementor 1 1,['c#'] +221931,connecting a mysql database to glassfish classpath is not set or classname is wrong i am swapping out a derby database for a mysql one i had everything working before but after what i thought was the proper configuration i am getting the errorcaused by javaxresourceresourceexception class name is wrong or classpath is not set for commysqljdbcjdbc2optionalmysqldatasourcefull error output from consolecaused by javaxresourceresourceexception class name is wrong or classpath is not set for commysqljdbcjdbc2optionalmysqldatasourceat comsungjccommondatasourceobjectbuildergetdatasourceobjectdatasourceobjectbuilderjava292at comsungjccommondatasourceobjectbuilderconstructdatasourceobjectdatasourceobjectbuilderjava114at comsungjcspimanagedconnectionfactorygetdatasourcemanagedconnectionfactoryjava1292at comsungjcspidsmanagedconnectionfactorygetdatasourcedsmanagedconnectionfactoryjava148at comsungjcspidsmanagedconnectionfactorycreatemanagedconnectiondsmanagedconnectionfactoryjava101at comsunenterpriseresourceallocatorlocaltxconnectorallocatorcreateresourcelocaltxconnectorallocatorjava87i have double checked some of the names the connection pool and other resourcesi have also added the mysql driver jars to the library of glassfish in both projects the database was definitely working correctly through eclipse because i was able to view tables and thisplay the resources inside the database context of eclipse so i know that at least those drivers are working correcly also the persistencexml file looks good it references the jdbcmydatabase jndi reference like it should and default jta is selected as the manament type does anyone have another suggestion thank you,['mysql'] +221937,android how to thisplay camera preview with callback first i have been working on this for some time and tried several solutions so do not send me the first link that you find on googlewhat i need to do is quite simple i want to manually thisplay preview from camera using camera callback and i want to get at least 15fps on a real device i do not even need the colors i just need to preview grayscale imageimages from camera are in yuv format and you have to process it somehow which is the main performance problem i am using api 8in all cases i am using camerasetpreviewcallbackwithbuffer that is faster than camerasetpreviewcallback it seems that i cant get about 24 fps here if i am not thisplaying the preview so there is not the problemi have tried these solutions1 thisplay camera preview on a surfaceview as a bitmap it works but the performance is about 6fpsbaos new byteoutputstreamyuvimagenew yuvimagecameraframe imageformatnv21 prevx prevy nullyuvimagecompresstojpegnew rect0 0 prevx prevy 80 baosjdata baostobytearraybmp bitmapfactorydecodebytearrayjdata 0 jdatalength convert to bitmap this is the main issue it takes a lot of timecanvasdrawbitmapbmp 0 0 paint2 thisplay camera preview on a glsurfaceview as a texture here i was thisplaying only luminance data greyscale image which is quite easy it requires only one arraycopy on each frame i can get about 12fps but i need to apply some filters to the preview and it seems that it cannot be done fast in opengl es 1 so i cannot use this solution some details of this in another question3 thisplay camera preview on a glsurfaceview using ndk to process the yuv data i find a solution here that uses some c function and ndk but i did not manage to use it here some more details but anyway this solution is done to return bytebuffer to thisplay it as a texture in opengl and it would not be faster than the previous attempt so i would have to modify it to return int array that can be drawn with canvasdrawbitmap but i do not understand c enough to do thisso is there any other way that i am missing or some improvement to the attempts i triedthanks for any reply,"['java', 'android']" +221976,how can i prevent a form from being submitted more than once within 5 minutes i recently found a huge security problem with my pm system that allows users to send a message as much as they want with a for loop in the address bar someone put this into the address barjavascriptforx0x10x compose formsubmit and the message was sent 10 times to me and my inbox was full of the same message and my database was so full that phpmyadmin was being very laggy my question is how can i prevent this this is a major issue also the form is submitted with ajaxediti use php so how can i prevent this like how could i make it to where a message can only be sent every 5 minutes or so and if they submit more than one within 5 minutes it will thisplay an error or not show any user feedback at all and just stop it from being submitted,['php'] +221999,why does the sqlparameter namevalue constructor treat 0 as null i observed a strange problem in a piece of code where an adhoc sql query was not producing the expected output even though its parameters matched records in the data source i decided to enter the following test expression into the immediate windownew sqlparametertest 0valuethis gave a result of null which leaves me scratching my head it seems that the sqlparameter constructor treats zeroes as nulls the following code produces the correct resultsqlparameter testparam new sqlparametertestparamparametername testtestparamvalue 0 subsequent inspection shows that the value property is still 0can anyone explain this behaviour is it somehow intentional if so it is potentially rather dangerous,['c#'] +222071,java how to transform from list to map without iterating i have a list of objects that i need to transform to a map where the keys are a function of each element and the values are lists of another function of each element effectively this is grouping the elements by a function of themfor example suppose a simple element classclass element int f1 string f2 and a list of these f1100 f2alice f1200 f2bob f1100 f2charles f1300 f2dave then i would like a map as follows key100 value alice charles key200 value bob key300 value dave can anyone suggest a succinct way of doing this in java without iterating a combination of lambdajs group method with guavas mapstransform nearly gets there but group does not generate a map,['java'] +222076,can android support zeroconfbonjour over bluetooth how about tcpip on iphone if i create custom service for example test tcplocal in bonjour i can seekbroadcast this service through wifi orand bluetoothit is possible on android i know that there is jmdns but from what i understand it works only through wifinetworknot bluetooththanksedit by seva alekseyev who offered the bounty i am not after workarounds like zeroconf sans bluetooth or bluetooth sans zeroconf i am after the real thing,"['java', 'android']" +222116,how to thisable uitextfields edit property possible duplicateeasy way to thisable a uitextfield i have a uitextfield i want to thisable its edit property i just want to thisplay a text in ithow can i achieve it,['ios'] +222142,guice how to share the same singleton instance through multiple injectorsmodules in guice the singleton scope does not refer to the singleton patternaccording to the dependency injection book of dhanji very simply a singletonas context is the injector itself the life of a singleton is tied to the life of the injector as in figure 58 therefore only one instance of a singleton is ever created per injector it is important to emphasize this last point since it is possible for multiple injectors to exist in the same application in such a scenario each injector will hold a different instance of the singletonscoped objectis it possible to share the same singleton instance through multiple modules and multiple injectors,['java'] +222162,how we can use onnewintent in any activity what is the real use of onnewintent in the activity life cycle and how do we use this method,['android'] +222165,how to automatically convert strongly typed enum into int include iostreamstruct a enum local a a1 a2 enum class b b1 b2int foo int input return inputint mainvoid stdcoutfooaa1stdendl stdcoutfoostatic castintbb2stdendlthe alocal a is what the strongly typed enum is trying to achieve but there is a small difference normal enums can be converted into integer type while strongly typed enums can not do it without a castso is there a way to convert a strongly typed enum value into an integer type without a cast if yes how,['c++'] +222172,thisplaying a mediawiki within a iframe first off i do not really want to use iframes but i do not think i have a choice in this situationi am integrating some help docs into an already built system the easiest thing for me to let other people write the help is to provide them with a mediawiki with a custom style then to integrate this into the system i wanted to put a direct link to the mediawiki in a help tabthe problem is my mediawiki appears to block iframes from loading it maybe this is a default setting but i was wondering how to turn it off i know my code is fine as it loads other sitesalso can you do what i am attempting to do with a div tagthanks,"['css', 'html']" +222178,parsing puppetapi yaml with python i am creating a script which need to parse the yaml output that the puppet outputswhen i does a request agains example httpspuppet8140productioncatalogmytestserverno i will get some yaml back that looks something like id001 rubyobjectpuppetresourcecatalog aliases applying false classes s baseconfig edges id1 rubyobjectpuppetrelationship source id047 rubyobjectpuppetresource catalog id001 exported and so on the problem is when i do an yamlloadyamlstream i will get an error likeyamlconstructorconstructorerror could not determine a constructor for the tag rubyobjectpuppetresourcecatalog in string line 1 column 5 id001 rubyobjectpuppetreso as far as i know this id001 part is supported in yamlis there any way around this can i tell the yaml parser to ignore themi only need a couple of lines from the yaml stream maybe regex is my friend hereanyone done any yaml cleanup regexes beforeyou can get the yaml output with curl likecurl cert varlibpuppetsslcertshostnamepem key varlibpuppetsslprivate keyshostnamepem cacert varlibpuppetsslcertscapem h accept yaml httpspuppet8140productioncataloghostnamei also found some info about this in the puppet mailinglist but i cant get it to work correctly,['python'] +222181,declare functions or method in a view since there is no more code behind in aspx pages in net mvc it seems impossible to declare a function or method direclty in the aspx page the view in classic asp i could add a script tag with runatserver to declare a local functioneach client has its own view the method in the controller send the right view to the right client what i would like to do is to change some method logic depending of the client since this is highly dynamici do not want to add a class or a method in the controller then rebuild and upload in production each time we have a new clientso i thought of adding some logic directly in the view is this possible,"['c#', '.net']" +222196,how to create a shared library in android i have a library say lib which exposes the quite a few apis and classes for use by application developersif there are more than one applications that use lib on the phone i want only one instance of lib to be created and running it is somewhat similar to what android platform services like locationmanager sensormanager packagemanager etcspecifically there are two problems that are to be addressedhow to make sure that there is only one instance of lib how to deploy libseparate apk bundled with every application that uses it but only one of them creating the library instance at any point of time etcis there any other wayother than serviceaidl to make sure that only one instance of lib runs irrespective of the number of applications using it,['android'] +222204,string reverse in python write a simple program that reads a line from the keyboard and outputs the same line whereevery word is reversed a word is defined as a continuous sequence of alphanumeric charactersor hyphen aa for instance if the input isacan you help meathe output should beanac uoy pleh emai just tryed with the following code but there are some problem with it printenter the stringstr1raw inputprint joinstr11split 2it prints nac uoy pleh em just look the exclamation it is the problem here anybody can help me,['python'] +222205,a good small example to demonstrate wait and notify method in java can anybody please provide me a good small example demonstrate wait and notify functionality in java i have tried with the below piece of code but it is not showing what i expected public class waitdemo int i 10 int thisplay systemoutprintlnlexmark i return i public class classdemo1 extends thread private waitdemo wd new waitdemo public static void mainstring args classdemo1 cd1 new classdemo1 classdemo1 cd2 new classdemo1 cd1setnameeurope cd2setnameamerica cd1start cd2start synchronized void thisplay systemoutprintlnhello notifyall public void run synchronized this try notify systemoutprintlnthe thread is currentthreadgetname wait systemoutprintlnthe value is wdthisplay catch interruptedexception e the issue is that the method in the class waitdemo is not getting executed and as per my idea the sop after wait should execute please help me out on this,['java'] +222210,jquery isotope sort data by group using the isotope plugin i am trying to achieve a sorting system where by clicking an item groups are formed by positioning items of the same type after the clicked item isotopes sortfilter functions do not seem designed for this purpose so my initial approach was to rearrange the dom using insertafter and then firing relayout however it seems that after initialization the dom order is not relevant and nothing short of destroying and reinitializing isotope works but that causes undesirable scroll position jumpssee is there are way to update isotope based on dom structure without a reinitor is it conceivable to interface with the sortfilter functions to achieve this aimthanks in advanceowen,['jquery'] +222256,is it bad to use important in css property not know much about css and purely a javaj2ee developer but some how got strucked in some css puzzle which i am unable to solvei was using a form with some jquery light box effect which has a div with id and classdiv idcontactcontainer classmyclass stylezindex 1002 height 386px width 450px position fixed left 4065px top 15 in my css file i saw the following entrycontactcontainer font 16px22px trebuchet ms verdana arial textalignleft width450pxbut when this form was thisplayed as jquery popup it getting thisplayed properly in mozilla but on google chrome and ie the box was not coming properly like only some part of it and rest as a scroll barwhen i saw it through firebug used first time it showing me something like div idcontactcontainer classmyclass styleposition fixed zindex 1002 height 67px width 450px left 4065px top 15and for same settings it was not coming properly for ie and mozilla so after lots of goggling i did following changes to csscontactcontainer font 16px22px trebuchet ms verdana arial textalignleft width450px height380px importanti fixed the height by height380px importantthough this fixed my issue but being no idea about css i am not sure if this was the right approach as i searched about height but it was not defined anywhereplease suggest if i have adopted a wrong approach,"['html', 'css']" +222260,is there any straightforward way to output text files or csv from sql server i have done a fair amount of tinkering and searching and the best option seems to be eithersending output to text and copypasting into a text file or excel or outputting to a somewhat unorthodox rpt file which i am not sure what youd do withopening it in excel does not preserve formatting present in the original output for what seems like a pretty common task i am surprised there is not a simpler way to do this can anyone suggest an easier way to go about this than the two methods i outlinedoh and for what it is worth i am working on sql server 2008,['sql'] +222304,regex matches in c but not in java i have the following regex long i knowmixmixmixmixmixmixmixthat i am using to split a string it matches correctly in c but when i moved the code to java it does not match is there any particular feature of this regex that is conlythe source is produced asstring source patternquote assign foo values foo0 while in c it isstring source assign foo values foo0 the c version is like thisstring split regexsplitsource regexin java i tried bothstring split sourcesplitregexand alsopattern p patterncompileregexstring split psplitsource,"['c#', 'java']" +222305,multiple routers vs single router in backbonejs all examples on backbone i have seen use one router for the whole application but wouldnt it make sense to have a router for each single part of your app header footer stage sidebar has anyone built apps with more than one router and what are your experienceslet us think about a complex app with nested views wouldnt it be better when a view has its own router that handles the thisplay of the subviews than having one big router that has to inform the main view to change its subviewsthe background of this question i have see a lot of parallels of the router in backbone and the activitymapper in gwt the activitymapper is only responsible to get the right presenter for a given route and a given container in the dom,['javascript'] +222306,marshalling c struct containing arrays to c with great help of the stackoverflow community i have managed to call a native dll function however i cannot modify the values of id or intersects array no matter what i do with it on the dll side the old value remains it seems readonlyhere are some code fragmentsc structtypedef struct face int id int intersects625 facec mappingstructlayoutlayoutkindsequential public struct face public int id marshalasunmanagedtypebyvalarray sizeconst 625 public int intersects c method type set to dll in vs2010extern c int declspecdllexport stdcall solveface faces int nforint i 0 in i forint r0 r625 r facesiintersectsr 3 facesiid 6 c method signaturedllimportlibdll charset charsetansi callingconvention callingconventionstdcallpublic static extern int solveface faces int lenc method invocationface faces new face10faces0intersects new int625faces0id 1 and add 9 more solvefaces faceslength faces0id still equals 1 and not 6kindest regardse,['c#'] +222363,timestamp for row creation and last modification i need to keep track of the time a row was inserted into the database and the time it was last modifiedi tried to create two separate columns and use current timestampcreate table def id int creation timestamp default current timestamp modification timestamp on update current timestamphowever this produced an errorerror 1293 hy0 incorrect table definition there can be only one timestamp column with current timestamp in default or on update clausewhat is the best way to do thisi am thinking stored procedure but looking for a standard solution i am also concerned with access privileges as few programsthings should be able to touch the timestamps as possiblealthough i would prefer mysql answers solutions for other rdbmss are also appreciated,"['mysql', 'sql']" +222367,undefined symbol when trying to load a library with dlopen i am trying to load a shared library plugin i was provided closed source with dlopen under a linux arm platform i am trying to load this wayvoid handle dlopenlibrary pathlibrary name rtld nowthe result is a failure with this messagefailed to load library pathlibrary name undefined symbol symbol namei tried to look inside the library with nm but it seems the lib was stripped no symbol could be found i also tried using readelf s and in fact i got this result12663 0 0 notype global default und symbol nameby reading around i get that readelf s returns all the symbols including those symbols defined in libraries referenced by itthe answers to this question are not completely clear to me is this a symbol which is supposed to be in the library and which is not there because it was compiled the wrong way or is this a symbol i am supposed find somewhere else the output of readelf d seems to suggest i am providing all the needed shared libraries may this error be related to a mistake in the way i am compiling my executable or is this something not related to the loaderalso i read about the meaning of each column but those values are quite strange how do you interpret that symbol description why is address 0 why is type notype,['c++'] +222395,how can i express that two values are not equal to eachother is there a method similar to equals that expresses not equal toan example of what i am trying to accomplish is belowif secondarypasswordequalsinitialpassword joptionpaneshowmessagedialognull youve successfully completed the program else secondarypassword joptionpaneshowinputdialognull your passwords do not match please enter you password again i am trying to find something that will not require me to use if a c,['java'] +222396,python mysql unicode and encoding i am parsing json data and trying to store some of the json data into mysql database i am currently getting following unicode error my question is how should i handle this should i handle it from the database side and if so how can i modify my table to do soshould i handle it from python sidehere is my table structurecreate table yahoo questions question id varchar40 not null question subj varbinary255 question content varbinary255 question userid varchar40 not null question timestamp varchar40 category id varbinary20 not null category name varchar40 not null choosen answer varbinary255 choosen userid varchar40 choosen usernick varchar40 choosen ans timestamp varchar40 unique question iderror while inserting via python code traceback most recent call last file yahooquerydatapy line 78 in module values s s s s s s s s s s s row2 row5 row6 quserid questiontime categoryid categoryname qchosenanswer choosenuserid choosennickname choosentimestamp file optlocallibraryframeworkspythonframeworkversions26libpython26sitepackagesmysqldbcursorspy line 159 in execute query query dbliteralargs file optlocallibraryframeworkspythonframeworkversions26libpython26sitepackagesmysqldbconnectionspy line 264 in literal return selfescapeo selfencoders file optlocallibraryframeworkspythonframeworkversions26libpython26sitepackagesmysqldbconnectionspy line 202 in unicode literal return dbliteraluencodeunicode literalcharsetunicodeencodeerror latin1 codec cannot encode characters in position 204230 ordinal not in range256python code segment pushing user id to the url to get full json stack urlobject urlliburlopenbase urlformatrow2 qnadatajson urlobjectread data jsonloadsqnadatajsoncurexecuteinsert into yahoo questions question id question subj question content question userid question timestamp category id category name choosen answer choosen userid choosen usernick choosen ans timestamp values s s s s s s s s s s s row2 row5 row6 quserid questiontime categoryid categoryname qchosenanswer choosenuserid choosennickname choosentimestampjson structurequestions id 201201185322aa5htdcsubject what are the new pokemon callcontent i used to know them i stop at dialga and palkia version and i heard there is new ones whats it calldate 201201 185322timestamp 1322794402what i also did prior to running the query i execute the following on mysql set character set client utf8and this how the mysql variables looks likemysql show variables like character set variable name value character set client utf8 character set connection utf8 character set database latin1 character set filesystem binary character set results utf8 character set server latin1 character set system utf8 character sets dir usrlocalmysql5510osx106x86 64sharecharsets 8 rows in set 0 sec,"['python', 'mysql']" +222473,cannot define a private static final variable because it throws an exception i have a class likepublic class someclassimpl implements someclass private static final somelib somelib new somelibi cannot do this because somelib throws a unknownhostexceptioni know i could move the instantiation to the constructor but is there a way for me to do it the way i have it above somehow that way i can keep the var marked as finali tried to look for how to throw exceptions at the class level but cannot find anything on it,['java'] +222482,live video streaming between server and client using java this is part of a project i am working on i have two desktop java application one runs on the server which has real ip and the other is the client i just want to stream a live video from a webcam connected to the server application and play it on the client application i want to do this streaming from more than one camerai have been looking searching for days between xuggler jmf red5 vlcj i just cannot figure from where i should start as i am new to dealing with media in programming any ideas from where i should start with this thanks in advance,['java'] +222485,reading outlook mail with c i am using the following code as i attempt to connect to my outlook mail now i must be doing something wrong because i try to get the inbox mails and i always get 0 mails when this is not the case this is my code microsoftofficeinteropoutlooknamespace namespace applicationgetnamespacemapi namespacelogon missingvalue missingvalue inboxfolder namespacegetdefaultfoldermicrosoftofficeinteropoutlookoldefaultfoldersolfolderinbox consolewritelinefolders 0 inboxfolderfolderscounti have several email accounts in my outlook profile when i write the followingconsolewritelineaccounts 0namespaceaccountscountconsolewritelinename 0 namespaceaccounts1thisplaynamethe total number of accounts is thisplayed correctly and so is the name of the account i really want to access index 1 now the problem is that i need to access a specific folder within that account how do i do this,['c#'] +222490,making child wider than its parent without width div idparent div idchild content divdivis it possible to make child as wide as the content is making it wider than parent wich has a fixed width if neededin my case content is an unkown text string that i dont want to line break,['css'] +222496,do i need to buy the qt framework i want to develop a c application that will work on all operating systems this application will be free until version 15 to make sure it is of high quality i do not want this application to be open source the public will only have access to the installer exe and that is it all source code will be kept and maintained by me and not under a legal company for now at leastso with the information above do i need to buy the qt framework or can i use the free version i am always confused with these free license agreements like lgpl and gpl i can read it a million times and still not know if i can use it or notif i can use the qt for free in regular non legal terms what must i do or how will be restricted so that i can see qt for free i really hope i can use the qt for free for when this application does cost money i still want to have a free version with less feature and the paid version will still be very cheap not enough to make me rich just enough so i do not go broke haha we are talking like 5 for the paid version or something,['c++'] +222509,how to check if google street view image api returns no image i am using google street view image api to show an image of a locationit works fine however when no picture is available i get a black image instead of a location picture is there any way i can check if no image is returned and show another image instead,['javascript'] +222512,jackson throws jsonmappingexception on deserialize demands singlestring constructor another question but it relates to this onedeserializing json with jackson why jsonmappingexception no suitable constructorthis time i am getting a different error namely that the jackson deserializer complains that i do not have a singlestring constructorfactory method in my class protocolcontainerhowever if i add a singstring constructor like thispublic protocolcontainerstring json the exception does indeed thisappear but the protocolcontainer that i expected to be there is all empty ie all its properties are in their initial state and not populated according to the jsonstringwhy is thatim pretty sure you should not need a string constructor and if you do that you shouldnt have to populate the properties in that constructor right,['java'] +222524,listview setitemchecked only works with standard arrayadapter does not work when using customized arrayadapter this is really weirdwhen i use the standard arrayadapter for a listview calling setitemchecked works okbut when using a custom made arrayadapter it does notwhat would be the reason is this a bug or am i missing somethingpublic class test activity extends activity called when the activity is first created private listmodel list private listview lview public void oncreatebundle icicle superoncreateicicle create an array of strings that will be put to our listactivity setcontentviewrlayoutmain lview listview findviewbyidridlistview01 lviewsetchoicemodelistviewchoice mode multiple list getmodel with this adapter setitemchecked works ok lviewsetadapternew arrayadaptermodelthis androidrlayoutsimple list item multiple choice list problem with this adapter it does not check any items on the screen arrayadaptermodel adapter new test class1this list lviewsetadapteradapter private listmodel getmodel listmodel list new arraylistmodel listaddget0 listaddget1 listaddget2 listget1setselectedtrue model m listget1 listaddget3 listaddget4 listaddget5 listaddget6 listaddget7 initially select one of the items return list private model getstring s return new models override public boolean oncreateoptionsmenumenu menu menuinflater inflater getmenuinflater inflaterinflatermenuresults screen option menu menu return true category optionsmenu override public boolean onoptionsitemselectedmenuitem item switch itemgetitemid case ridselect all int size lviewgetadaptergetcount for int i 0 i size i problem lviewsetitemcheckedi true selects the item only for standard arrayadapter logix looping i return true case ridselect none return true return false public class test class1 extends arrayadaptermodel private final listmodel list private final activity context public test class1activity context listmodel list supercontext rlayoutrowbuttonlayout2 list thiscontext context thislist list static class viewholder protected textview text protected checkbox checkbox override public view getviewint position view convertview viewgroup parent view view null logix getview position if convertview null layoutinflater inflator contextgetlayoutinflater view inflatorinflaterlayoutrowbuttonlayout null final viewholder viewholder new viewholder viewholdertext textview viewfindviewbyidridlabel viewholdercheckbox checkbox viewfindviewbyidridcheck viewholdercheckbox setoncheckedchangelistenernew compoundbuttononcheckedchangelistener override public void oncheckedchangedcompoundbutton buttonview boolean ischecked model element model viewholdercheckbox gettag logix oncheckedchanged elementsetselectedbuttonviewischecked logix oncheckedchanged viewsettagviewholder viewholdercheckboxsettaglistgetposition else view convertview viewholder viewgettagcheckboxsettaglistgetposition viewholder holder viewholder viewgettag holdertextsettextlistgetpositiongetname logix holdercheckboxsetchecked position holdercheckboxsetcheckedlistgetpositionisselected logix getview position return view,['android'] +222538,starting android project with phonegap i am trying to start an android app with phonegap i follow youtube video and when i hit the run button it shows me the following errors1203 184552704 eandroidruntime27214 javalangruntimeexception unable to start activity componentinfotplappsuktrainstplappsuktrainsmain androidcontentresresourcesnotfoundexception resource id 0x01203 184552704 eandroidruntime27214 at androidappactivitythreadperformlaunchactivityactivitythreadjava27051203 184552704 eandroidruntime27214 at androidappactivitythreadhandlelaunchactivityactivitythreadjava27211203 184552704 eandroidruntime27214 at androidappactivitythreadaccess2300activitythreadjava1321203 184552704 eandroidruntime27214 at androidappactivitythreadhhandlemessageactivitythreadjava20711203 184552704 eandroidruntime27214 at androidoshandlerthispatchmessagehandlerjava991203 184552704 eandroidruntime27214 at androidoslooperlooplooperjava123then i tried to run their example app the one with the phone informations and stuffs it is working fine and i made some other changes according to sample app but it is still not workingdo you have any idea what it could bethanks,['android'] +222543,generating pi to nth digit java i wanted to know how i can generate pi to the nth digit i have a couple of basic ideasuse mathpi and increase the precision if that is possibleuse eulers formula to generate pi but even here i would need to increase the precision i thinkthere is also srinivasa ramanujans formula for generating pi which is known for it is rapid convergence this formula seems difficult to implement i believe i would have to also increase deicmal precision hereso in short either way i would need to increase the precision of bigdecimal depending on what the nth digit is how would i go about increasing the precision of bigdecimal to nth digit also if there is a better and faster of doing this can you please point me in the correct directionedit i just want to generate pi i do not want to use for calculations and this is a question about how i can use bigdecimal to implement my ideas of generating pi,['java'] +222552,touch event handled by multiple views i have a subclass of uiview on top of a uitableview i am using the uitableview to thisplay some data and at the same time i would like to overlay an animation that follows the finger for instance leaving a trailif i get it right i need the touch events to be handled both by the uiview subclass and the uitableview how can i do thatis it possible to have ie touchesmoved being triggered on the uiview subclass and then on uitableviewthank you so much for any help,['ios'] +222556,proper use libdl and dynamically linked libraries i need to dynamically link a library that i have created i am not exactly sure what the issue is it all compiles properly but i always catch handle as the null pointervoid handlechar errorhandle dlopen hw11libmichaelschillingso rtld lazysame error comes up with full path as well as hw11ifhandle error dlerror printfsn error printferror loading libraryn exit1i cant get passed this error and i am not sure what could possibly be wrong i am pretty sure i have compiled everything correctly here are the compilation steps i usedgcc rdynamic c hw11libmichaelschillingc o hw11libmichaelschillingsogcc hw11michaelschilling4c ldl o hw11michaelschilling4i am getting an error that reads hw11libmichaelschillingso only et dyn and et exec can be loaded what does this meanthanks,['c'] +222561,android developer console takes ages to update i released an application yesterday to the android market however i have hit a few issues when updating my app and tracking information via the developers console first of all when i update my app either the apk or just information about it the information seemingly takes a very long time to actually hit the market is this normal or is it just because my app is newthe other issue i am having is that the developer console is telling me i have 0 downloads when i know for a fact that is not true furthermore a friend told me he had ratedcommented but the console is only showing 1 ratingcomment which is from someone else,['android'] +222564,xcode 42 app loader unable to verify icon dimensions no icon found i have never had this problems until i began to use xcode 42 i am getting the following error trying to upload my appunable to verify icon dimensions no icon found your minimum os version is below 32 so you must define cfbundleiconfile or provide a default iconpng that is 57x57i have an iconpng image and is 57x57 i tried add it and remove it from infoplist no success i do not know what to dohere is my infoplist fileinfoplist edited againsolutionthanks for your comments the problem was that i was not following the right steps to prepare the app for submission in xcode 4 it is very different to xcode 32 if you follow the steps of this guide you will not have the issues i had,"['iphone', 'ios']" +222579,how do i suppress c vtable generation for pure virtual classes using g supressing c vtable generation can be done in msvc using the declspecnovtable attribute however it seems that there is no equivalent attribute for the gnu c compiler the fact is that leaving the vtables for pure virtual classes unnecessarily links in cxa abort and many others and i want to avoid this happening because i am programming for an embedded system so what should i dostruct isomeinterface virtual void func 0class csomeclass public isomeinterface virtual void funcvoid csomeclassfunc,['c++'] +222598,what does on update restrict do user id integer not null constraint fk user meta foreign key user id references users id on delete cascade on update restricti know from here that on delete cascade means that if i delete a row from the users table then the associated row from the user meta table will be removed too but what does on update restrict do,['mysql'] +222600,how can i fire a traits static event notification on a list i am working through the traits presentation from pycon 2010 at about 23045 the presenter starts covering trait event notifications which allow among other things the ability to automatically call a subroutine any time a trait has changedi am running a modified copy of the example he gave in this trial i am trying to see whether i can fire a static event whenever i make a change to volume or inputsfrom traitsapi import hastraits range list floatimport traitsclass amplifierhastraits define an amplifier a la spinal tap with enthoughts traits use traits to enforce values boundaries on the amplifiers objects use events to notify via the console when the volume trait is changed and when new volume traits are added to inputs volume rangevalue50 traitfloat low00 high110 inputs listvolume i want to fire a static trait event notification when another volume element is added def init self volume50 superamplifier self init selfvolume volume selfinputsappendvolume def volume changedself old new static event listener for selfvolume if not new in selfinputs selfinputsappendselfvolume if new 110 print this one goes to eleven so far we have seen selfinputs def inputs changedself old new static event listener for selfinputs print check it outif name main spinal tap amplifier spinal tapvolume 110 print directly adding a new volume input spinal tapinputsappend40 try print negative test adding 120 spinal tapinputsappend120 except traitstrait errorstraiterror print test passedwhen i run this script i can see this one goes to eleven so far we have seen 50 110 in the console output so i know that volume changed gets fired when i assign 110 to spinal tapvolumehowever i never see any events from inputs changed no matter what example i cook up i cannot get a list to fire an eventthis is the output i am seeing note that there is no evidence that inputs changed ever firesmpenningbucksnort python spinaltappythis one goes to eleven so far we have seen 50 110directly adding a new volume inputnegative test adding 120test passedmpenningbucksnort i have run this both under python26 cygwin windows 7 and python 25 linux all using traits version 400 that i easy install directly off enthoughts site the results are the same no matter what i have tried so farshould a list be able to fire a static event when using traits if so am i doing something wrong,['python'] +222624,code first causing required relation to be optional public class client public int32 clientid get set public virtual icollectioninquiry inquirymanufacturers get set public virtual icollectionproduct products get set public virtual icollectioninquiry inquiryretailers get set public class product public int32 productid get set public int32 clientid get set public virtual client client get set public virtual icollectioninquiry inquiries get set public class inquiry public int32 inquiryid get set public int32 productid get set public int32 manufacturerid get set public int32 retailerid get set public virtual product product get set public virtual client manufacturer get set public virtual client retailer get set the fluent api is ashasrequiredi iproduct withmanyp pinquirieshasrequiredi imanufacturer withmanyp pinquirymanufacturers hasforeignkeyp pmanufactureridhasrequiredi iretailer withmanyp pinquiryretailers hasforeignkeyp pretaileridso here are some classes that i have defined they have relationships as follows client product have one to many client inquiry have one to many and product inquiry have one to many i am using code first here now using fluent api i have defined the relationships these relationships are supposed to be required ones meaning client product relationship can not be null as well as client and inquiry cannot be null eitherhowever the relationship between client inquiry is being forced to be an optional one with the code first when i try to make them required the ef does not generate the databasecan someone tell me what is wrong with my model that it is causing the ef to not create a required relationsship between client inruiry is this due to cascade delete as i read some where the mssql can only have one cascade delete path between client product and inquiry any help explaination would be nice,['c#'] +222634,c must friend functions be defined in the header file i want to overload the operator in one of my classesthe signature goes like thisfriend stdostream operatorstdostream os const annuaire objwhen i try to define it in the cpp file it says that the operator exactly takes 1 argument however when i define it in the h it compiledworks finethis is how i define it in the cpp file stdostream annuaireoperatorstdostream os const annuaire obj does it have anything to do with friend functions needing to be defined in header files,['c++'] +222636,using libcurl to upload files to dropbox i am trying to use the libcurl in a cc application to post files to dropbox i would like to use the files post api as documented herei am having problems with properly authenticating oauth this call it is unclear to me how to properly create the authentication signaturefrom some a sample i saw it looked like they were reading in the whole file to create the hmacsha1 encoding on this seems problematic on large filesdoes anyone have experience or insight using this api or something similar,"['c++', 'c']" +222646,nsfetchedresultscontroller always returns no rows i am trying to get a nsfetchedresultscontroller working with my tableview but despite my best efforts to get it setup correctly it is always returning no rows i have opened up my data store through finder and validated through a sqlite editor that there are in fact plenty of records but it always returns zero what am i missingcustom getter for the controller nsfetchedresultscontroller fetchedresultscontroller if fetchedresultscontroller nil return fetchedresultscontroller rbgameitemcontroller itemcontroller rbgameitemcontroller sharedinstance nsfetchrequest fetchrequest nsfetchrequest alloc init nsentitydescription entity nsentitydescription entityfornamegameitem inmanagedobjectcontextitemcontrollermanagedobjectcontext fetchrequest setentityentity nssortdescriptor sort nssortdescriptor alloc initwithkeyname ascendingno fetchrequest setsortdescriptorsnsarray arraywithobjectsort fetchrequest setfetchbatchsize20 nsfetchedresultscontroller thefetchedresultscontroller nsfetchedresultscontroller alloc initwithfetchrequestfetchrequest managedobjectcontextitemcontrollermanagedobjectcontext sectionnamekeypathnil cachenameroot selffetchedresultscontroller thefetchedresultscontroller selffetchedresultscontrollerdelegate self sort release fetchrequest release thefetchedresultscontroller release return selffetchedresultscontrolleri am fetching the data in viewdidload voidviewdidload super viewdidload nserror error nil if selffetchedresultscontroller performfetcherror nslogunresolved error error error userinfo fetched results delegate voidcontrollerwillchangecontentnsfetchedresultscontroller controller the fetch controller is about to start sending change notifications so prepare the table view for updates selftableview beginupdates nslogcontrollerwillchangecontent voidcontrollernsfetchedresultscontroller controller didchangeobjectidanobject atindexpathnsindexpath indexpath forchangetypensfetchedresultschangetypetype newindexpathnsindexpath newindexpath nslogcontrollerdidchangeobject uitableview tableview selftableview switchtype case nsfetchedresultschangeinsert tableview insertrowsatindexpathsnsarray arraywithobjectnewindexpath withrowanimationuitableviewrowanimationfade break case nsfetchedresultschangedelete tableview deleterowsatindexpathsnsarray arraywithobjectindexpath withrowanimationuitableviewrowanimationfade break case nsfetchedresultschangeupdate self configurecellselftableview cellforrowatindexpathindexpath atindexpathindexpath break case nsfetchedresultschangemove tableview deleterowsatindexpathsnsarray arraywithobjectindexpath withrowanimationuitableviewrowanimationfade reloading the section inserts a new row and ensures that titles are updated appropriately tableview reloadsectionsnsindexset indexsetwithindexnewindexpathsection withrowanimationuitableviewrowanimationfade break voidcontrollernsfetchedresultscontroller controller didchangesectionid nsfetchedresultssectioninfosectioninfo atindexnsuintegersectionindex forchangetypensfetchedresultschangetypetype nslogcontrollerdidchangesection switchtype case nsfetchedresultschangeinsert selftableview insertsectionsnsindexset indexsetwithindexsectionindex withrowanimationuitableviewrowanimationfade break case nsfetchedresultschangedelete selftableview deletesectionsnsindexset indexsetwithindexsectionindex withrowanimationuitableviewrowanimationfade break voidcontrollerdidchangecontentnsfetchedresultscontroller controller nslogcontrollerdidchangecontent the fetch controller has sent all current change notifications so tell the table view to process all updates selftableview endupdatesi am implementing both methods for section and row number which returns 1 for sections and 0 for rows nsinteger numberofsectionsintableviewuitableview tableview int sections selffetchedresultscontroller sections count nslogsectionsi sections return sections nsintegertableviewuitableview tableview numberofrowsinsectionnsintegersection idnsfetchedresultssectioninfo sectioninfo selffetchedresultscontroller sections objectatindexsection int rows sectioninfo numberofobjects nslogrowsi rows return rows,['ios'] +222651,in jquery how do i check if the dom is ready possible duplicatejavascript domready i want to check whether function is readyreturn true if dom is ready false otherwise,"['javascript', 'jquery']" +222654,how to use pseudoterminals in linux with c i am trying to figure out how to use pseudoterminals in linux essentially i want to create a telnetd clone something i mentioned in an earlier questioni understand the concept of master and slave terminal and i have a basic grasp on how to use syscalls in cmy question concerns the next step after opening a slave master file descriptor how to i launch getty in the slave are there any good resources on the net for using the forkpty openptyor another apisome examples in c would help this was a very similar question but no one really provided any examples,['c'] +222680,java arrays why is the output 1 why is the output in this example 1 public static void mainstring args int a 1 2 3 4 int b 2 3 1 0 systemoutprintln a a b3 i thought it would be 2 ie the expression is evaluated asaab3ab3 because a is now pointing to ba0 should not a0 be 2 because a is pointing to bthanks in advance,['java'] +222716,model view controller what should create what according to good programming practices at the beginning of the program runtime which of the controller model and view components should be created first and which of them should create the other two i mean should the main function first create the controller then the controller should create both the model and the view and make itself known to them somehow or should i rather begin with creating the view which before thisplaying itself would initialise the controller which would create the model or maybe the model should come first or they all should be created in the main function in parallel whats the right way of implementing mvc edit i am interested in a general answer though currently i am working with java swing and windows phone 7,['java'] +222718,get the first and last visible element in a scrollable div i have list of thumbs in a scrollable div animated with nextprev button each click on next button should match the attribute of the first visible element each click on prev button should give me the attribute of the last visible element i do not really know how to mathematically solve that because the scroll thistance is variable when the list ends can someone please help me outhtmldiv idscrollcontent ul idassetlist li dataassetid15201li li dataassetid15202li li dataassetid15203li uldiva classnext hrefnextaa classprev hrefprevajqueryanextclickfunction var scrollheight scrollcontentscrolltop scrollcontentanimatescrolltopscrollheight375500function get dataassetid of first visible element in viewport aprevclickfunction var scrollheight scrollcontentscrolltop scrollcontentanimatescrolltopscrollheight375500function get dataassetid of last visible element in viewport check out the fiddlethank you,['jquery'] +222719,detect exception in autocloseable close i want to build a custom autocloseable class so i can turn thistry begin dothings commit finally if transactionisactive rollbackinto the easiertry transaction t begin too bad i have to store it in t though i do not use it dothingstransaction would be the autocloseable here and in close it would commit or rollback the transaction as appropriatebut to make that work i would need to detect in transactionclose whether an exception occurred inside the try block or it completed normally is this possible at allif it requires parsing the stack trace from a new exception that is ok easier programming would be worth the tiny performance hit that brings,['java'] +222722,load user control dynamically with parameters i have created a user controlpublic partial class controls pagegeneral systemwebuiusercontrol private int pageid private int itemindex public int pageid get return pageid set pageid value public int itemindex get return itemindex set itemindex value protected void page loadobject sender eventargs e something very cool happens here according to the values of pageid and itemindex now i want to dynamically create this control and pass it parametersi have tried using the loadcontrol function but it only has two constructures one with string path and another with type t and array of parametersthe first method works but because of my parameters and have to use the more complicated method of loadcontrol but i do not get how to use it how can i case my path string of my control to that weird object type tthank you for you help,"['c#', 'asp.net']" +222729,scrapy read list of urls from file to scrape i have just installed scrapy and followed their simple dmoz tutorial which works i just looked up basic file handling for python and tried to get the crawler to read a list of urls from a file but got some errors this is probably wrong but i gave it a shot would someone please show me an example of reading a list of urls into scrapy thanks in advancefrom scrapyspider import basespiderclass dmozspiderbasespider name dmoz allowed domains dmozorg f openurlstxt start urls f def parseself response filename responseurlsplit2 openfilename wbwriteresponsebody,['python'] +222744,java coding style emacs ccmode configuration i am using gnuemacs head with the included ccmode cversion 5322 on a gnulinux debian machinei am trying to define a custom style to manage the code conventions for the java programming language androids code style guidelines for contributors and some custom rulesas a lisp beginner it does not seem wise to start from scratch as a consequence i used googlecstyle as a starting point and i managed to get the intended behavior for the most indenting rules with an exception on nested condition see the code snippet belowfrom that post i have defined arglistcontnonempty in my custom style full code customjavastyleel unfortunately although most cases is indented as intendedif condition1 condition2 condition3 condition4 condition5 condition6 dosomethingaboutit somemethodlongexpression1 longexpression2 longexpression3 longexpression4 longexpression5nested condition are wrongly indentedif deviceregistredgetaddressequalsignorecasedeviceadress deviceregistredgetnameequalsignorecasedevicename dosomethingaboutitctrlc ctrls report syntactic analysis arglistcontnonempty 2447 2450 arglistcontnonempty 2447 2452 on the second line and i obviously have a 16 spaces 2 times indentation instead of 8 i would like to get the following indentationif deviceregistredgetaddressequalsignorecasedeviceadress deviceregistredgetnameequalsignorecasedevicename dosomethingaboutiti tried to define a when fboundp a condition like the one used for statementcont but without success my lack of lisp knowledge do not help eithernow the question is my approach right or wrong how couldshould i implement the intended behavior ie detect when i am in a nested condition to get the right indentationi do not want to use malabarmode or jdee so please do not tell me to use themcheersrenaudupdate 201206 reacting to the commentswe wouldnt begin a holy war here those who want to use emacs for their own reasons can stick to emacs the others will do as they wantasaying that i work within a team in which i am the only one to use emacs the others are fond of eclipse since i am in charge of the coding rules i have worked with my colleagues to get the right save actions and help to configure the eclipses formatter all i could say is that the eclipse save actions and formatter are not easy to configure at alla the main difference is that you have a nice gui with nice checkboxes but it does not help much to reduce the complexityi stick with emacsa,['java'] +222755,addition is not working in javascript i am trying to learn javascript here i am confused with the following codewhen i put xy in the function it is going wrong for example 2 5757but are working why is not working please help me thanks a lot in advance,['javascript'] +222761,using camera with no sd card on android i just want to confirm that the camera cannot be used without an sd card on androidi fire the mediastoreaction image capture intent to use the camera and was trying to the get the camera to store the image in the apps data folder contentvalues values new contentvalues valuesputmediatitle image valuesputimagesmediabucket id pathhashcode valuesputimagesmediabucket thisplay name name valuesputimagesmediamime type imagepng valuesputmediadescription image capture by camera valuesput data constantsimagepath uri uri getcontentresolverinsert mediaexternal content uri values cameraintentputextramediastoreextra output uri startactivityforresultcameraintent picture activityi assume the camera can not access the apps data folderso without a sd card there is no way to use the camera,['android'] +222762,how to cin to a vector i am trying to ask the user to enter numbers thats put into a vectorthen using a function call to cout the numbers why is this notworking i am only able to cout the first numbertemplate typename tvoid write vectorconst vectort v cout the numbers in the vector are endl forint i0 i vsize i cout vi int main int input vectorint v cout enter your numbers to be evaluated endl cin input vpush backinput write vectorv return 0,['c++'] +222767,why cannot i extend everyones pocket in nowjs i am trying to provide functions in everyones pocket of nowjs i would like to do so by extending everyones pocket ie everyonenow for some reason which i cannot understand extend fails to properly provide the function at the client sidethis is my current codevar requireunderscore everyone requirenowjsinitializeappeveryonenowfoo function extendeveryonenow bar function consolelogeveryonenowfoo functionconsolelogeveryonenowbar undefinedon both the server and client sides i can do nowfoo just fine on the other hand nowbar fails because nowbar is not defined this is the case on both the client and server sides i tried to check for existence at the server side as shown above on the last line however this line logs undefinedunderscores extend function obviously does work on other objects so i guess it has something to do with the magical namespace that nowjs useshow come extending does not work with everyonenow and how can i get it to workedit 2 i digged some more into proxies it seems like setting a property on a proxy by passing a variable as its name does not work i removed my first edit because this testcase is more narrowed downwhy is this not working is this a bug most of the times i ask this myself i know it is not but this is really making me cluelessvar proxy proxycreate get functionpr name consolelogget called return null set functionpr name value consolelogset called var key fooproxyfoo barproxy key barproxyfooproxy key log resultset calledget calledget calledapparently proxy key bar does not cause set to be called on the proxy why is that,['javascript'] +222771,xcode ios project only shows my mac 64bit but not simulator or device this just started happening that my ios project is only showing my mac 64bit rather than the simulator or my iphone to build to i have no idea why this is happening i do not think that i have changed anythingi have my project set to ios 5 as the base sdk but no matter what i do it seems to never show my any other options to build for i have restarted xcode a few times and still no luckwhy is the happeningxcode 42 build 4d199,['ios'] +222800,generating unique random numbers integers between 0 and x i need to generate a set of unique no duplicate integers and between 0 and a given numberthat isvar limit 10var amount 3how can i use javascript to generate 3 unique numbers between 1 and 10,['javascript'] +222804,how to grab ipport with regex okay so i am creating a small ipport scraper in php problem is that i am pretty unfamiliar with regexso i have been piecing together what i canheres what i have gotb25052040901090932505204090109090915bi know this is not the best at least not the end to grab the port because it means that ports will be able to be things like 9 also it seems to return two matches this way the ipport and the port i just need it to grab the full ipport not one or the othercan anyone help,['php'] +222824,androids media scanner how do i remove files i am writing an app that removes files that may or may not be listed in any one of the types of media libraries such as music or pictures while i can use the mediascannerconnectionscanfile method to add files to the media library there does not seem to be any call to notify the service that the file has been removed sending it the path of the file that no longer exists does not result in the desired behavior either how should i go about removing items from the library that no longer exist on the android storage,['android'] +222827,purpose of args parameter of getloadermanagerinitloader does anyone have a description of the usage of the bundle args parameter of initloader is the object merely set on the resulting cursor or is there a way to get access to that object from the data source being queried like a content providerfrom docsargs optional arguments to supply to the loader at construction if a loader already exists a new one does not need to be created this parameter will be ignored and the last arguments continue to be usedthank you in advance,['android'] +222834,android how do i set the textsize for a layout i am trying to set the textsize at a global level and cannot figure or find a way to do itfor example i have something like thisxml version10 encodingutf8scrollview xmlnsandroid androidlayout widthfill parent androidlayout heightfill parenttablelayout xmlnsandroid androidid idtable androidlayout widthfill parent androidlayout heightfill parent androidshrinkcolumns androidstretchcolumnstablelayoutscrollviewthe tablerows and textviews themselves are generated dynamically depending on user inputthe problem is i would like to set the base textsize globally based on a resource file without having to go and touch a bunch of code is there a way to tell the app hey app use this as your base textsize for all the textviewsor phrased another way in html i can set the font size at the body div and table levels is there something analogous i can do at one the layout linearlayout tablelayout scrollview etc levels,['android'] +222847,whats the difference between thistribution and release build configurations they both sound like the same thing thistribution release somehow having a hard time figuring out what the difference is,"['iphone', 'ios']" +222869,how is lazyset in javas atomic classes implemented in this video about thisruptor a concurrency framework the lazyset method of javas atomic classes eg atomiclong is mentioned according to the documentation this method eventually sets to the given valuedoes anybody know what the underlying mechanism is to implement this specifically on x86 on windows if that is relevant it cannot be interlockedexchange because that would set the value and make sure cache lines are flushed before returning if i am not mistaken,['java'] +222896,is there an sqlalchemy equivalent of djangoevolution all i want is to have a workflow somewhat similar toadd django evolution to the installed apps for your projectrun managepy syncdbmake modifications to the model files in your projectrun managepy evolve hint executewhich is super simple and even though it does not support advanced features like multiple databases it does know how to addremove columns which is a common use casesqlalchemymigrate has an insanely complex workflow in comparison and both tutorials 1 2 referenced by the docs are either outdated or irrelevant,['python'] +222903,append does not work after previously appended contents deleted i convert user input urls to bbcode and append it to the textarea but after you delete one of the lines i appended it would not append morebut you could see the newly appended values in the firebugreally strangeheres my codefunction addurlclickfunction addurlslidedown suclickfunction ifuvallength3 addurluval uval inputvaluexclickfunctionaddurlfadeoutfunction addurle patthttps ifematchpatt ue else uhttpe textareanamecontentappendnrurluurlnrand heres the jsfiddle,"['javascript', 'jquery']" +222946,equivalent function for xticks for an axessubplot object so i am trying to use axes objects to control my matlibplot figure i am not using plt aka import matlibplotpyplot as plt because i am embedding the figure in my tkinter gui per thishowever i am also using subplots in the figure so something likea fadd subplot121a2 fadd subplot122aplotfn2maga2barrange010 magbin widththis is all well and good i can use the axes properties to control things ie aaxesmethod but i want string labels for my bar plots per this see codemy dilemma is that i cannot usepltxticksindwidth g1 g2 g3 g4 g5 as in the example because i cannot use plt if i want to embed it into my tkinter gui i am limited to what i can do with axes objects i am trying to use a2set xticks but this does not allow for the string as ticks functionality i need for my bar chartany help in this regard would be amazingtyler,['python'] +223018,how do i deploy web2py on pythonanywhere how do i get a basic web2py server up and running onpythonanywhere,['python'] +223020,minus operator in mysql i have some tables where i am getting the emails and i do not want to get the emails in table tbl unsubscribe i wrote the query like select cand email from tbl cand dataunionselect emp email from tbl emp dataunionselect email from tbl uptade listunionselect feed email from tbl feedbackunionselect admin email from tbl admin emails but i am getting a syntax error is the minus operator not valid for mysql,"['php', 'mysql']" +223030,mysql substring return empty value select substringfieldname020 from tablei try on phpmyadmin and returned empty valuehow i use this function,['mysql'] +223034,setting itemid in options menu i have a menu defined via an xml resource now dynamically i add a menu itempublic boolean oncreateoptionsmenumenu menu menuinflater inflater getmenuinflater inflaterinflatermenumainmenu menu ifmyconditiontrue menuadd0 99 0 new entry return truein onoptionsitemselectedmenuitem item i have a case statement which checks for 99 and it performs my actions technically that works fine i just wonder what number here 99 i shall pick the items created in the xml got an id via the resource file i assume android has some logic to create these items i wonder if it can happen that a generated menu item gets by accident as well 99 and then it would not work anymore what would be the best way,['android'] +223047,having issues sending a character through ajax request i have simple aspnet web application which is using yui for ajax request application read text from text box and send ajax request to server following is the codebody form idform1 runatserver div input idtxt nametxt typetext valueenter some value input idbtn typebutton valuebutton div div idoutdiv formbodyfollowing is the client script that initializes the ajax requestyahooutileventondomreadyfunction yahooutileventaddlistenerbtn click functionevt var url serveraspxtypetesttxt documentgetelementbyidtxtvalue var btn documentgetelementbyidout var cobj yahooutilconnectasyncrequestget url success functiono btninnerhtml div oresponsetext oresponsetextcharcodeat0 div failure functiono confirmits failure cache false what i do in application is accept character entered by user save it to db and write it to ajax response system does not support unicode databasenow my problem is that when registered a character 0174 is entered in the text box and sent to server i am getting 65533 which is not what user has entered on the text box also a this character is not unicode character then why this behavior,"['javascript', 'asp.net']" +223051,get an accurate time difference between two nsdate is there any way to find out an accurate difference between two nsdatei have found solutions but they are not accurate enough i need to take into account daylight saving the fact that different months have a different number of days etca simple calculation such as 606024 etc to work out minutes hours and days does not take them into accountlets say i need to work out the difference between the time right now nsdate date and december 25th 1022pm date chosen by user using date picker datepicker date just as an example how would i do thisknowing the exact time difference is not the key so long as i have an accurate difference of days months and years it will do,"['ios', 'objective-c']" +223069,update multiple rows with multiple values and multiple conditions mysql i am facing a complex situation of sql queries the task is to update multiple rows with multiple values and multiple conditions following is the data which i want to updatefield to update sales condition fields campid and dateif campid 259 and date 2262011 then set sales 200else if campid 259 and date 2162011 then set sales 210else if campid 260 and date 2262011 then set sales 140else if campid 260 and date 2162011 then set sales 150i want to update all these in one query,['mysql'] +223079,converting a double to an int in javascript without rounding in c the following code returns 2double d 29int i intddebugwritelineiin javascript however the only way of converting a double to an int that i am aware of is by using mathroundfloortofixed etc is there a way of converting to an int in javascript without rounding i am aware of the performance implications of number so i would rather avoid converting it to a string if at all possible,['javascript'] +223081,get element type with jquery is it possible using jquery to find out the type of an element with jquery for example is the element a div span select or inputfor example if i am trying to load values into a dropdown list with jquery but the same script can generate code into a set of radio buttons could i create something liketriggerliveclick function var elementtype thisprevattrwhat is itgiven a dropdown list with a button next to it with the trigger class my elementtype variable should return select upon the button being pressed,['jquery'] +223102,any good community translation tools for android one of my applications is getting more and more popular and i would like to support multiple languages but there are a few problemsi do not know every single language out therei am actively developing the application so strings change and new ones are added oftenthat is why i have been looking at the possibilities of an online community translation tool i would like for it to be free and open source and it would be great if it supports androidsorry if this is offtopic i was a bit unsure but i think it is a problem that many android developers have to deal with,['android'] +223105,java enum elements with spaces im working on java i have created an enum as followspublic enum myenum india russian england north americaabove example gives errors while using space in the name of element ie north americaany suggestions how to resolve above issue,['java'] +223114,looking for a rest with json client library i need to connect to an endpoint that serves out json via rest interfaces i cannot really find anything that combines these 2 technologies in a coherent manner i am looking for a library that will let me get started quickly,['c#'] +223123,where to manage build configurations in xcode 4 i remember in xcode 3 there was debug release and possibly thistribution there was a dialog where we could duplicate the release build config and rename it to thistribution in order to modify some build settings for thistributionin xcode 4 i cannot find references to these build thistributions as known from xcode 3 when i click on my project in the navigator i get a big window on the right there i click build settings and choose the all filter along with levelsit shows me these columns settings resolved appname aproject ios defaultit seems that they compressed all the different configurations into this massive list many build settings show up in different flavors for example architecture debug thistribution releaseon the other hand other build settings do not appear splitted up into these 3 build configuration types for example there is just one base sdk setting despite the fact that it would be nonsense to set different base sdk for different build config or maybe notunfortunately the itunes connect integrated help system is still hanging around in xcode 3 good old days and telling me to duplicate a release build config which i cannot in xcode 4 the ios app development workflow guide does not go into detail about how to actually do it in xcode 4 only about three paragraphs on that page refer to building for the app store it mentions an appstore scheme which i do not even have since i did not create my project with xcode 4 initially,['ios'] +223124,django select option in template in my django template i am using the list of objects in a drop down menu i am processing it based on the selectionthe html template select idorg nameorg list onchangeredirecturl option value selectedselectedselectoption for org in organisation option valueorgidorgnamecapfirstoption endfor selectthe problem is that when i am selecting the value from the drop down menu i am getting the contents which belong to the selection since the attribute selectedselected which only fixes to the select element unless i put the selectedselected inoption valueorgid selectedselectedorgnamecapfirstoptionin these organisation the last iterated element is only being fixed with drop down but i want the selected element to be thisplayed in the drop down menuhow can i solve this issue,['html'] +223132,revert to unstyled text when web fonts are slow to load i am using google web fonts like thisfontface fontfamily vollkorn fontstyle normal fontweight normal src localvollkorn regular localvollkornregular url 80hnwwoff formatwoffbody fontfamily vollkorn georgia times serifworking in chrome there is no flash of unstyled text as described in this typekit blog post instead the text does not load at all until the web font is finished downloading over a fast connection it is great because the fonts load asynchronously and very quickly however over a slowish connection the page looks like it is empty for several seconds until the web font has loaded which is poor usability is there a clever way to show the text in georgia initially then add the vollkorn fontface once the resource has loadedi guess what i am saying is that i would actually quite like the flash of unstyled text rather than a blank page and would like to enforce this behaviour,"['html', 'css']" +223155,virtual studio 2008 aspnet jquery 171 vsdoc javascript intellisense does anyone have the location to download jquery 171 vsdocand also what to do to make it work i current have the following and i am a getting massive error in the vsdoc when doing ctrshiftj to update intellisensescript typetextjavascript srcincludesjqueryjsscript if false then script typetextjavascript srcincludesjqueryvsdocjsscript end ifi have both the service pack 1 and the patch update to make vsdoc work in vs 2008,"['jquery', 'asp.net']" +223176,what is the best word or characterbased diff algorithm out there so i want to be able to find the diff between two strings on a perword basis maybe faster than percharacter though if percharacter is faster then i would want to do it that wayhere is an example of what i want to achievesource text hello theremodified text helay scerediffhelloay thscerethe bracketed text is what was removed the parenthetical text is what was addedthere is kind of a super hackish way to do this using a commandline tool such as opendiff but it requires a newline character inbetween every character as opendiff is linebasedi am using ruby and have not found any tools to do this but language is not terribly important as algorithms can be ported pretty easilythanks,['ruby'] +223185,benefit of signing dll with strong name i have a c solution that contains multiple c class libraries i am being doing some research recently and it is suggested that the outputted assemblies from my libraries should be signed making them signed with a strong name firstly i am wondering if it is best that i progress with such the libraries that outputted from these class libraries are used in multiple other projectsif it is advised from my previous question that yes i should sign my dlls the snk i use can this be used for each of the class libraries in the solution or must it be one key per class library,['c#'] +223199,how to implement a lock with a timeout in python 27 is there a way to implement a lock in python for multithreading purposes whose acquire method can have an arbitrary timeout the only working solutions i found so far use polling whichi find inelegant and inefficientdoes not preserve the bounded waiting progress guarantee of the lock as a solution to the critical section problemis there a better way to implement this,['python'] +223202,django admin group permissions to edit or view models i am searching for a way to customize the django administration to support permissions based on the user groupfor example i have just created the developers group now i have also created the tickets model with adminmodel to specify how to list datai would like to have this model visible only by developers and hidden to each other not in this group eg filter the view based on groupsi have read a lot of documentations but could not really find and understand what to do to have it workingfor security purposes i would also need to check user groups at runtime when addingdeleting objects for a specific model the one i have hidden to people outside the developers group otherwise it would only need to know the url to use the model sit looks like a simple task but maybe i am missing something any 3rd party middleware or just a way to do it i am also ready to edit the administration views if needed but i need to know what do tothank you,['python'] +223207,is it a good security practice to have separated read and write users for a database so if some parts of the code are prone to sql injection at least the user cannot write anything to the database if he happens to be using the front end which does not have universal write access to everything,['sql'] +223220,how to convert ipv4 to integer using coffescript in coffeescript how would i go about converting an ip standard ipv4 127001 into an integeredit lots of great answers here thanks everyone,['javascript'] +223264,application loader apple stuck on sending api usage to itunes connect i am submitting an ios app to the app store using application loader however it never gets past the sending api usage to itunes connect stage there is no error this stage just does not completei have verified that the mac is connecting to the internet i can visit websites also the app is tiny 6mb so this cannot conceivably just be a long upload i have tried leaving this for 20 minutesthe background to this is that i developed in flash cs5 on a windows pc built it for thistribution there and now on the mac i am loading the final file into application loader to submit it it verifiesvalidates the file just fine but would not go beyond this pointany ideas anyone perhaps it is a network issue,"['iphone', 'ios']" +223308,does java jar option alter classpath options i have a jar file which mentions the main class in the manifestwhen i try to execute the jar using the following commandjava cp comfoomainclassthe code executes and workswhen i try to execute the jar using the following commandjava cp jar myjarjari get class not found execptions for some jars which are in the same folder as myjarjar i hoping that the cp option will include those jars in class pathi modified my code to print javaclasspath property in the first case it listed all jars in the current directory in second case it just listed myjarjari also modified the manifest to add classpath element to it with all jars then the second command works but in my code i am trying to load a aribtrary class whose name is provided at command prompt so i want the class path to contain all jars in a folder how do i make the second command work in this scenario,['java'] +223324,no software buttons for the ics emulator so i am working on an update for my application from 30 to 40 and i am having issues with the emulator specifically the software buttons do not appear when using the galaxy nexusish skin i am not sure its exact but it should be close enough this is the wxga720 its valueshardware backhome keys noabstracted lcd density 320keyboard lid support nomax vm heap 48device ram size 1024the first line is the most important because it tells the emulator we need software keys for backhome this works using the wxga800 skin tablet even using api level 14 ics do not mind the jaged edges in the screenshot i have the emulator scaled down this does not affect the keys not appearing as you can see its difficult to interact with the emulator since i have no backhome buttonsso the software keys show up for the tablet skin but not the phone has anyone else solved this issueediti have changed the screenshot to reflect the latest version of the tools r16the buttons appear using the wvga800 skin and hardware backhome no,['android'] +223328,setting content between div tags using javascript i am trying to set some content in between some div tags on a jsp page using javascriptcurrently the div tag on the jsp page looks like thisdiv idsuccessanderrormessagesdivi want to fill the content in those div tags using some javascript method so that it will look like sodiv idsuccessanderrormessagesdiv classportletmsgerrorthis is an error messagedivdivi know you can go like thisdocumentgetelementbyidsuccessanderrormessagesvaluesomecontentbut that just changes the value of the value attribute it does not fill in content between those div tags anyone out there that can point me in the right direction,"['javascript', 'html']" +223339,joptionpane yes or no window i am trying to create a message with a yes or no button then a window will appear with a certain message that depends on if the user clicked yes or no here is my codepublic class test public static void mainstring args default icon custom title int and joptionpaneshowconfirmdialog null would you like green eggs and ham an inane question joptionpaneyes no option iftrue joptionpaneshowmessagedialognull hello else joptionpaneshowmessagedialognull goodbye systemexit0 right now it prints hello whether or not you press yes or no how do i get it to show goodbye when the user chooses no,['java'] +223348,how to implement a volume key shutter for iphone i want to implement the same behavior with the native camera of ios5press the volume button to take a photowhats the ideal way to archive it are there any ways to capture the volume key pressed eventafter googling searching around for hours i found 1 solution using nsnotificationcenter nsnotificationcenter defaultcenter addobserverself selectorselectorvolumechanged nameavsystemcontroller systemvolumedidchangenotification objectnil voidvolumechangednsnotification notification self takephoto however it has 2 issuesthere is an semitransparent overlay of current system volume show up every time when pressing the volume key this is not what i wanted for the native camera when you press the volume key as shutter the system volume would not change however by using the above method the system volume will change,"['iphone', 'ios']" +223349,are there any good descriptions of stdnested exception and friends i have noticed that there are a few more interesting declarations in exception in c11 can anybody shed any light on what they mean and how to use themthe ones i am wondering about arestdnested exceptionstdthrow with nestedstdrethrow if nestedadditionally while they seem selfexplanatory it might be nice to know how these workedstdexception ptrstdmake exception ptrstdcurrent exceptionstdrethrow exception,['c++'] +223365,jmeter response time calculation can someone explain me please how jmeter calculate response timei need to understand this graph response times over time,['java'] +223367,custom class loadingoverriding androidnative classes main goal is to override android system class activity view etc with my own implementationclassloader for custom class loading is implemented loading nonsystem class custom class worksbut when i try to load activity with my implementation it does not load because classloader already has this class in its cache returns the class with the specified name if it has already been loaded by the virtual machine or code null if it has not yet been loaded param classname the name of the class to look for return the code class object or code null if the requested class has not been loaded protected final class findloadedclastring classname classloader loader if this bootclassloadergetinstance loader null else loader this return vmclassloaderfindloadedclassloader classnamehow can i change class loader to inject my own class instead of system,"['java', 'android']" +223384,systemoutprintln hazard in java ee application when i was starting study java i was being told not to do systemoutprintln in java ee application however i do not really know what is the reason of not doing soi am fully aware that if we really need to print an important it should be logged using logging frameworkwhat i really want to ask here is there any real hazard that systemoutprintln make does it cause any performance issue,['java'] +223441,like contains in jquery possible duplicatejavascript string containsjquery how to see if string contains substring in asp net c i use string aa aa bbif aacontainsaa some task i want to same thing in client side means in jquerysome thing like belowvar aa aa bbifaa want help herethere is any method to do thisthanks,"['javascript', 'jquery']" +223444,determining 3g vs edge i know that the reachability example allows detection of whether network is accessible via wifi or cell but is there a way to determine whether the cell connection is over 3g or edge,"['objective-c', 'ios']" +223458,uipageviewcontroller return the current visible view how do you know what is the current pageview thisplayed inside an uipageviewcontrolleri have overridden the viewdidappear method of my child views so that they send an id to the parent view in their viewdidappear methodhowever the problem is this i cannot reliably use that id as id for the thisplayed page because if the user turns the page but halfway through decides to stop the turning and put the page back viewdidappear will already have been called the view is visible behind the curled pagemaybe i should only switch to a new id if the current view thisappears but i wonder if there is not a more simple way to return the view that is currently visible,"['iphone', 'ios']" +223472,read a xml from a string and get some fields problems reading xml i have this xml stored in a c string called myxmlxml version10 encodingutf16mydataz xmlnsxsi xmlnsxsd lists sog field1123field1 field2afield2 field3bfield3 sog sog field1456field1 field2cfield2 field3dfield3 sog listsmydatazand i would like to browse all sog elements for each of them i would like to print the child field1so this is my code xmldocument xmldoc new xmldocumentstring myxml xml version10 encodingutf16mydataz xmlnsxsi xmlnsxsdlistssogfield1123field1field2afield2field3bfield3sogsogfield1456field1field2cfield2field3dfield3soglistsmydatazxmldocloadmyxmlxmlnodelist parentnode xmldocgetelementsbytagnamelistsforeach xmlnode childrennode in parentnode httpcontextcurrentresponsewritechildrennodeselectsinglenodefield1valuebut seems i cannot read a string as xml i get systemargumentexception,"['c#', '.net']" +223519,vs2008 replace var with inferred type my team just received the code written by a contractor and the contractor had a preference for using type inference with var our team prefers explicit typing by using the actual type as in belowtype somename new typeilisttypetwo someother someclassgetstuffwhereas the contractor deliveredvar someother someclassgetstuffvisual studio 2008 knows what the inferred type is as i can see by hovering the var keywordmy question is is there a way to do a global find and replace var to the inferred type,['c#'] +223540,how do you read directly from physical memory in c or c windows how do you read ram by giving a physical not virtual addressthat means without going trough virtual memory system mmu tables and being specific to one processi already know the api readprocessmemory which reads from ram used by most trainers but it is only for a specific processi searched on msdn and found that devicephysicalmemory seems to give such possibility but i found no practical example and this feature seems to have been turned off by windows service packs to fix some vulnerabilityi know it is possible to do because winhex does it if you choose tools open ram physical memory it will then thisplay ram content from 0x0 to your ram size just like when you open a traditional file it requires administrator rights but there is no driver to install which means winhex does it from user modeedit added information about os,"['c++', 'c']" +223549,converting latlong to jts i am trying to integrate hibernate spatial with jpa for geo searches i have been referencing the tutorial on the official site i am not associated with hibernatespatial the tutorial unfortunately does not cover how to create a point instance from a latitudelongitude pair i am attempting to do this here but i am still not sure if this is this the right way to convert a latitudelongitude pair to a jts point instanceimport comvividsolutionsjtsgeomcoordinateimport comvividsolutionsjtsgeomgeometryfactoryimport comvividsolutionsjtsgeompointimport orggeotoolsgeometryjtsjtsfactoryfinderimport orghibernateannotationstypeimport javaxpersistenceentitypublic class location private double latitude private double longitude typetype orghibernatespatialgeometryusertype private point coordinates private final geometryfactory geometryfactory jtsfactoryfindergetgeometryfactorynull prepersist preupdate public void updatecoordinate if thislatitude null thislongitude null thiscoordinates null else thiscoordinates geometryfactorycreatepointnew coordinatelatitude longitude public double getlatitude return latitude public void setlatitudedouble latitude thislatitude latitude public double getlongitude return longitude public void setlongitudedouble longitude thislongitude longitude,['java'] +223551,how to thismiss a dialogfragment when pressing outside the dialog i am using a dialogfragment and while i have successfully set an image to close ie thismiss the dialog when pressed i am having a hard time finding the way to thismiss the dialog when the user clicks anywhere outside it just as it works with normal dialogs i thought there would be some sort of dialogfragmentsetcanceledontouchoutsidetruecall but i do not see that in the documentationis this possible with dialogfragment at all or am i looking in the wrong places i tried intercepting touch events in the parent activity but apart from not getting any touch event it did not seem right to me,['android'] +223554,partial specialization of variadic templates consider the following class template x and its partial specializationstemplate class typesstruct x 1template class t1struct xt1 2template class t1 class typesstruct xt1 types 3xint x 2 or 3 i suspect xint is ambiguous it is becauseit is obvious that both 2 and 3 are more specialized than 1 2 and 3 are now compared according to 14552 let us consider which of the following 2 and 3 is more specializedtemplate class t1void fxt1 2template class t1 class typesvoid fxt1 types 3according to 14824 the first step is the template argument deduction using 2 as the argument template and 3 as the parameter template given the only argument type is xa1 the deduced t1 is a1 and types is emptya xa1 p xt1 types t1 a1 types the second step is done using 3 as the argument template and 2 as the parameter template given the only argument type is xa1 args according to 148259 note that this paragraph is recently revised by n3281 args is simply ignored the deduced t1 is a1 and argument deduction succeedsa xa1 args p xt1 t1 a1 args is ignoredfinally the bidirectional argument deductions succeeded so 2 is just as specialized as 3 in conclusion xint is ambiguousmy question is is my interpretation correctif this interpretation is correct the definition of stdcommon type in 209763 is inappropriatetemplate class tstruct common type 1template class tstruct common typet 2 typedef t typetemplate class t class ustruct common typet u 3 typedef decltypetrue declvalt declvalu typetemplate class t class u class vstruct common typet u v 4 typedef typename common typetypename common typet utype vtype typewhen common typea b is used 3 and 4 are ambiguousnote on the first example gcc 470 snapshot and clang 30 select 2 however these compilers are so unreliable that they do not follow the other changes by n3281,['c++'] +223578,reload page after message is shown jquery right now i have a form where user enters the info it is than processed bu jquery ajax function and is set to return false so no page reload happens after user submits a formalthough i need to reload page but if i remove return false it refreshes page before success message is shown this message is shown after user submits data ajax type post url scriptsprocessphp data datastring success function st messagehtmlp your article was successfully addedp i need to reload page after the above message is shown return falseso how can i reload page after the p your article was successfully addedp message is shown with a slight delay say 2 3 seconds so user can actually read the message,['jquery'] +223589,function try catch syntax and main a little known but almost never used c feature is given a declarationvoid fone possible legal definition could bevoid foo try throw 42catch here the whole function implementation wrapped is within a trycatch pair which seems to be similar to allowing thisis that legal to do for int main egint main try throw 42catch the rules for main n3290 a 361 mostly talk about what arguments it should take and what it returns they do not seem to explicitly forbid it as they do with various other odd things eg linkages you might be tempted to tryis this legal and well defined,['c++'] +223619,variable of interface type i am learning java i saw the following description regards to interface in a bookwhen a variable is declared to be of an interface type it simply means that the object is expected to have implemented that interfacewhat does it mean if i define an interface public interface myinterface void method one int method twothen i declare a variable to be of an interface type for examplemyinterface foo new myinterfacehow the interface get implemented under what circumstance i should define a interface type variable i completely get confused by the books description,['java'] +223623,best way to call managed net code from unmanaged code i am trying to find the best performing method of calling into managed net code from unmanaged c code i have found information on hosting net within my c application and i am able to create a pruntimehost and start it without a problemthe executeindefaultappdomain seems very limited since i really want to send it a few parameters and have it return a structure of information the most obvious alternative is to use com methods but the current c code is not really setup as interfaces with methodseither way i want to return integers strings char s doubles and other core c types there is too much code on both sides to convert the c to c and using managed c is not an acceptable solution since the other groups using this c code do not want to start using managed code for performance reasonsthe goal is modify the existing c and c code as little as possible but still use methods within the c code at specific points within the c without majorly affecting the speed of the c codebased on code found on the internet the startup and shutdown sequence to host net isinclude stdafxhinclude metahosthpragma commentlib mscoreelibint tmainint argc tchar argv iclrmetahost pmetahost null iclrmetahostpolicy pmetahostpolicy null iclrdebugging pclrdebugging null hresult hr hr clrcreateinstanceclsid clrmetahost iid iclrmetahost lpvoidpmetahost hr clrcreateinstanceclsid clrmetahostpolicy iid iclrmetahostpolicy lpvoidpmetahostpolicy hr clrcreateinstanceclsid clrdebugging iid iclrdebugging lpvoidpclrdebugging dword dwversion 0 dword dwimageversion 0 iclrruntimeinfo pruntimeinfo hr pmetahostgetruntimelv4030319 iid iclrruntimeinfo lpvoid pruntimeinfo iclrruntimehost pruntimehost null hr pruntimeinfogetinterfaceclsid clrruntimehost iid iclrruntimehost lpvoid pruntimehost hr pruntimehoststart dword dwretcode 0 hr pruntimehostexecuteindefaultappdomainargv1 lmynamespacemyclass lmessage lhello world dwretcode stop the clr runtime and shutdown cleanly hr pruntimehoststop hr pruntimehostrelease hr pruntimeinforelease hr pclrdebuggingrelease hr pmetahostpolicyrelease hr pmetahostrelease return 0,"['c#', 'c++']" +223628,jquery each input hasclass for my needs i useform inputeach functioni if thishasclassdonot thisattrthisabled thisabled is there a better way to not use the if condition to check if the input has the class donot thanks for your helpchris,['jquery'] +223629,programmatically determine user who last modified file on windows i have been tasked with writing a simple command line utility in c that will monitor a directory on a server that several users will be accessing to copycutpasteview data i used filesystemwatcher to do this but it is lacking a couple features is it possible to determine the user or at least the computer name from where the file is being accessedmodified note this does not have to be with filesystemwatcher i am looking for any way to do this,['c#'] +223634,when should i write the keyword static before a nonmember function i have recently seen a bit on so about the static keyword before a function and i am wondering how to use it properly1 when should i write the keyword static before a nonmember function2 is it dangerous to define a static nonmember function in the header why notside question3 is it possible to define a class in the header file in a certain way so that it would only be available in the translation unit where you use it first the reason that i am asking this is because i am learning stl and it might be a good solution for my predicates etc possibly functors since i do not like to define functions other than memberfunctions in the cpp filealso i think it is related in a way to the original question because according to my current reasoning it would do the same thing as static before a function doeseditanother question that came up while seeing some answers4 many people tell me i have to declare the static function in the header and define it in the source file but the static function is unique to the translation unit how can the linker know which translation unit it is unique to since header files do not directly relate to a source file only when you include them,['c++'] +223640,finding element of numpy array that satisfies condition one can use numpys extract function to match an element in an array the following code matches an element a exactly in an array suppose i wantto match all elements containing how would i do that note that in this case there would be two matches i would also like to get the row and column number of the matches the method does not have to use extract any method will do thanksin 110 x nparrayacdefgin 1 a xout1 array true false false false dtypeboolin 112 npextracta x xout112 arraya dtypes2,['python'] +223647,sending data from nodejs to java using sockets i am trying to send data from nodejs to java through sockets i searched around but nothing was really useful i am used to socketio but in this case it does not seem really suitable for this it seems like all the socket extensions for nodejs are not really suited for sending messages but rather listening to messages and answering somethingmy java app basically should receive some work to do from nodejs do the work and send some result to nodejs back and no the work cannot be done on nodejs it has to be done by java which actually is scala but whateverdoes anyone of you know how can i do something like thisthanks,"['java', 'javascript']" +223648,confusing encoding exception in nstextstorage i have an nsdocument subclass for a simple text editor using lions new document based app template with few customisations and i am encountering a strange bug loading the file content into the text storageheres my code voidloadtextcontentintostorage if selftextstorage textcontenttoload return selftextstorage beginediting nslogstorage length lu textcontent selftextstorage unsigned longselftextstoragelength textcontenttoload selftextstorage replacecharactersinrangensmakerange0 selftextstoragelength withstringtextcontenttoload selftextstorage replacecharactersinrangensmakerange0 0 withstringhello world selftextstorage endeditingthe bug happens when irun the app in xcode as a debug buildopen any documentquit the app without closing the documentrun the app again from xcodeit crashes in replacecharactersinrangewithstring with unable to convert bytes in string 0x104d430 to nscstringencodingbut it only happens on every second launch of the app a third launch will not crash and it will automatically reopen the document it crashed trying to open the previous time it also only happens when i run the app from xcode release builds have never crashed on launchi thought it might be an encoding issue with the autosave system but it even crashes when i comment out that code and just load hello world string into the text view as shown in the above code similarly the commented out nslog does not show anything weird the text storage is valid loaded from the xib file the text storage length is 0 and the textcontent is the contents of the file being opened edit i have learned this problem is related in some way to the comapplesecurityappsandbox entitlement if entitlements sandbox are enabled then my app does not crash if either entitlements or the appsandbox feature are thisabled then my app crashes on every second launch trying to restore previously opened documentsi had only noticed it crashing when doing a buildrun from inside xcode because that was my only build configuration with the sandbox thisabled edit does anyone have any ideas the full exception follows and the full source code is on github terminating app due to uncaught exception nsinternalinconsistencyexception reason unable to convert bytes in string 0x104d430 to nscstringencoding first throw call stack 0 corefoundation 0x07f84afb286 exceptionpreprocess 198 1 libobjcadylib 0x07f88991d5e objc exception throw 43 2 corefoundation 0x07f84afb0ba nsexception raiseformatarguments 106 3 corefoundation 0x07f84afb044 nsexception raiseformat 116 4 foundation 0x07f835bfae4 copyfromstringtostorage 262 5 foundation 0x07f835bf979 nsbigmutablestring replacecharactersinrangewithstring 10 6 foundation 0x07f835bc3f7 nsconcretemutableattributedstring replacecharactersinrangewithstring 375 7 appkit 0x07f86149e14 nsconcretetextstorage replacecharactersinrangewithstring 81 8 dux 0x0102f9a mytextdocument loadtextcontentintostorage 1338 9 dux 0x01022a0 mytextdocument windowcontrollerdidloadnib 640 10 appkit 0x07f860f1328 nswindowcontroller windowdidload 667 11 appkit 0x07f860e89a3 nswindowcontroller window 109 12 appkit 0x07f8615d761 nsdocument windowforsheet 86 13 appkit 0x07f860e82c4 nsdocument shouldshowautosavebuttonforwindow 50 14 appkit 0x07f860e7fbb nswindowcontroller setdocument 237 15 appkit 0x07f8629c9b6 nsdocument makewindowcontrollers 139 16 appkit 0x07f8615d5 nsdocumentnspersistentuisupport restoredocumentwindowwithidentifierstatecompletionhandler 90 17 appkit 0x07f8615d4aa nsdocumentcontrollerpersistentrestoration loadeddocumentforautoid 179 18 appkit 0x07f8615cfbe nsdocumentcontroller reopendocumentforurlwithcontentsofurlthisplaycompletionhandler block invoke 8 187 19 appkit 0x07f86148e14 nsdocumentcontroller reopendocumentforurlwithcontentsofurlthisplaycompletionhandler block invoke 5 163 20 appkit 0x07f86148d5f nsdocumentcontroller reopendocumentforurlwithcontentsofurlthisplaycompletionhandler block invoke 4 697 21 appkit 0x07f86148aa1 nsdocumentcontroller opendocumentwithcontentsofurlusingprocedure 530 22 appkit 0x07f8614868d nsdocumentcontroller reopendocumentforurlwithcontentsofurlthisplaycompletionhandler block invoke 3 242 23 libthispatchdylib 0x07f8be8ba thispatch call block and release 18 24 libthispatchdylib 0x07f8bbc072a thispatch main queue callback 4cf 308 25 corefoundation 0x07f84a904dc cfrunlooprun 1724 26 corefoundation 0x07f84a8fae6 cfrunlooprunspecific 230 27 hitoolbox 0x07f8852f3d3 runcurrenteventloopinmode 277 28 hitoolbox 0x07f8853663d receivenexteventcommon 355 29 hitoolbox 0x07f885364ca blockuntilnexteventmatchinglistinmode 62 30 appkit 0x07f85ef23f1 dpsnextevent 659 31 appkit 0x07f85ef1cf5 nsapplication nexteventmatchingmaskuntildateinmodedequeue 135 32 appkit 0x07f85e62d nsapplication run 470 33 appkit 0x07f8616d80c nsapplicationmain 867 34 dux 0x0101e32 main 34 35 dux 0x0101e04 start 52 36 0x03 0x0 3,['objective-c'] +223659,change event not firing on text input using jquery in chrome i have a problem with a jquery change event on a text input that works as expected in firefox and ie but not in chrome i also have a keyup event on the text input to manipulate the input as it is entered but when the input is done i need to run some extra code i tried using the blur event and the focusout event as someone here had suggested as a substitute but then i could not change focus at all the input kept grabbing it back somehow here is the code textinputkeyupfunctionevent do stuff textinputchangefunctionevent alertchanged do other stuff and the html input typetext classtextinput value i am using jquery 163 any suggestions would be greatly appreciatedh,['jquery'] +223660,poedit keywords plurals i incorporated a gettextlike localization system in my app but my translation function looks like this tcategory string plural string number vprintf argumentsmy poedit keywordst2t23t2 tells poedit to parse string and it works apparentlyt23 should tell poedit to parse both string and plural string but it is not it only sees string so i do not get the plural forms parsed how can i fix that i do not want to switch my function to a different argument format because i like this one also this function acts like a sprintf replacementif 3rd argument plural string is a array then the function will consider the values from the array as arguments to vsprintfif 3rd argument is a string and number is provided the function will consider vprintf arguments as arguments to vsprintf if they are provided and plural string as the plural form of stringanyway poedit should not interfere with non quoted arguments right i mean it will only parse plural string as string if it looks like abc abc,['php'] +223694,reading data from bluetooth device in android i am using bluetooth chat in order to connect and recieve data from a bluetooth devicei use the following code for reading datapublic void run byte buffer new byte1024 int bytes logvmr start listening keep listening to the inputstream while connected while true try read from the inputstream logdmr buffer in try bytes mminstreamreadbuffer logdmr input stream new stringbuffer send the obtained bytes to the ui activity mhandlerobtainmessageconnmessage read bytes 1 buffersendtotarget logdmr buffer after catch exception e logemr error egetmessage connectionlost break logdmr buffer after while the device is sending data all the time without stoppingwith the above code i get the message oflogdmr buffer in trythen it goes to the next linebytesmminstreamreadbufferand never returns from that call i guess this is because it starts reading data from the device and does not stop until it thisconnects how can i read a certain amount of bytes at a timeeditunless it stay to the bytes mminstreamreadbuffer code due to that it dont get any data back on from the device,"['java', 'android']" +223749,saving webpage in cache using webview in android i am working on an application where i load few websites in webview now i want to save webpages so after sometime even if there is not internet user will able to see those pages but i am confused on how to save whole webpage in cache or any other medium the main thing is we need to show pages back even if there is not internet has anyone implemented this before please provide some demo code as this is my first attempt on cachethank you,['android'] +223752,what ios version is required to use autoreleasepool when i run code using autorelease keyword on ios 43x it throws this errordyld lazy symbol binding failed symbol not found objc autoreleasepoolpush referenced from userseonillibraryapplication supportiphone simulator432applications3782382e293a4d5e86e628be35cf6048eonilcocoacomplementstesterappeonilcocoacomplementstester expected in developerplatformsiphonesimulatorplatformdevelopersdksiphonesimulator43sdksystemlibraryframeworksfoundationframeworkfoundationdyld symbol not found objc autoreleasepoolpush referenced from userseonillibraryapplication supportiphone simulator432applications3782382e293a4d5e86e628be35cf6048eonilcocoacomplementstesterappeonilcocoacomplementstester expected in developerplatformsiphonesimulatorplatformdevelopersdksiphonesimulator43sdksystemlibraryframeworksfoundationframeworkfoundationi thought the keyword is just replacement of explicit autoreleasepool creationdeletion anyway it was not and threw an error does it supported only in specific version of ios so where can i check the version information about this keyword,['ios'] +223758,how to make nsassert log the description in xcode4 xcode 4 tells me when an nsassert has failed but the assert description and backtrace are no longer logged i have seen this question how to make xcode4 stop at nsassert failurewhich is helpful but i would rather log the assertion and continue how can i make nsassert behave this way thanks,['ios'] +223777,how to change the color of text in uitabbaritem in ios 5 with more appearance control in ios 5 how do we change the uitabbaritem text color from default white to other color editworking solution uitabbaritem appearance settitletextattributes nsdictionary dictionarywithobjectsandkeys uicolor blackcolor uitextattributetextcolor uicolor whitecolor uitextattributetextshadowcolor nsvalue valuewithuioffsetuioffsetmake0 1 uitextattributetextshadowoffset uifont fontwithnamerok size00 uitextattributefont nil forstateuicontrolstatenormal,"['iphone', 'ios']" +223789,how do i exclude a member from linqtosql mapping i have this classpublic class myclass columnnamestoredcolumn dbtypeint public int stored public int forthisplay get return stored 10 the point is forthisplay is not to be stored in the database i just need it for more convenient codei try to run an sql query that returns a rowset and get this invalidoperationexceptioncannot assign value to member forthisplay it does not define a setteri do not want forthisplay to be touched by linqtosql how do tell lingtosql to not touch it,"['c#', '.net']" +223831,configurationelementcollection and linq i have written some custom configuration collections elements etc now i would like to do a simple linq statementserverdetails servers configurationmanagergetsectionserverdetails as serverdetailsvar server from s in servers where sname servername select si get the errorcould not find an implementation of the query pattern for source type mynamespaceserverdetails where not foundthe serverelement has two propertiespublic class serverelement configurationelement configurationpropertyip public string ip get return stringbaseip set baseip value configurationpropertyname iskey true isrequired true public string name get return stringbasename set basename value serverdetailspublic sealed class serverdetails configurationsection configurationpropertyservercollection configurationcollectiontypeofservercollection additemname add public servercollection servercollection get return thisservercollection as servercollection servercollectionpublic sealed class servercollection configurationelementcollection public void addserverelement serverelement thisbaseaddserverelement public override configurationelementcollectiontype collectiontype get return configurationelementcollectiontypeaddremoveclearmap protected override configurationelement createnewelement return new serverelement protected override object getelementkeyconfigurationelement element return serverelementelementname am i missing something do i need to add something in so that i can use linq with a custom configuration elementby the way i have using systemlinq defined as i am using it else where within the same class,['c#'] +223836,string array as comma separated string in xaml how i can set value of string property in xamli hava control with next property string propnamei want to set value of this property in next waynssomecontrol propnameval1val2,['.net'] +223854,how to connect to db when running via command line when i run zend framework project from browser everything is ok it connects to dbwhen i run project from command line it cannot connect to db and it throws an errorfatal error uncaught exception pdoexception with message sqlstatehy0 2002 no such file or directory in usrlocalzendsharezendframeworklibraryzenddbadapterpdoabstractphp129i have usedrunning a zend framework action from command line s answers it is my applicationini files db partphpsettingsmysqldefault socketusrlocalzendmysqltmpmysqlsockresourcesdbadapter pdo mysqlresourcesdbparamshost localhostresourcesdbparamsport 3306resourcesdbparamsusername rootresourcesdbparamspassword rootresourcesdbparamsdbname iteamresourcesdbisdefaulttableadapter trueresourcesdbparamscharset utf8,['php'] +223865,prevent upload php script to be executed i have a system where user pay for support each user have a folder i have many like 200 sub folder in my website each of these needs the css images js etci also create folders every week for new users when they register each user can upload php script or js script or images screenshot of their problemmy problem is in my htacess i have a rule that checks for php script and redirects to the proper page eg sitecomuserpage will go to sitecomuserpagephpwhat i want to do is prevent the user from breaking the system for example bysitecomuseruploadtest will go to his testphp and run ithow can i prevent these kind of attacks,['php'] +223879,how to merge ruby hashes how can i merge these two hashescar color redcar speed 100mphto getcar color red speed 100mph,['ruby'] +223883,how do i use monowebbrowser i read through this page twice yet i have no clue how to use itthere is no assembly nor can i type using monowebbrowser using it directly also causes an error because it is not founddo i need some separate installs and how am i supposed to set it up and runningi am trying to have a gecko rendering a page on windows mac os x and linux,['c#'] +223901,how do you organize your bundles in symfony2 projects i have the exact question that this guy has threadthreadcd35132cc6972f29i will just copypaste it herei was wondering what different ways of organizing bundles within a project people are usingi seem to end up with either one massive bundle for a project or a lot of bundles which are closely related dependant to each other egi implemented my own user entity and login forms etc but the users are linked to an organization with some functionality etc it is mostly the entities that overlap a lot i guess do you guys split them up or dump them all in the same bundle,['php'] +223904,scheduled nstimer when app is in background how do people deal with a scheduled nstimer when an app is in the backgroundlet us say i update something in my app every hour updatetimer nstimer scheduledtimerwithtimeinterval600600 targetself selectorselectorupdatestuff userinfonil repeatsyeswhen in the background this timer obviously does not fire what should happen when the user comes back to the app is the timer still running with the same timesand what would would happen if the user comes back in over an hour will it trigger for all the times that it missed or will it wait till the next update timewhat i would like it to do is update immediately after the app comes into the foreground if the date it should have fired is in the past is that possible,"['iphone', 'ios']" +223905,c chaining of the operator for stdcout like usage possible duplicatestdendl is of unknown type when overloading operatoroperator overloading i am currently programming a logger class but the operator method causes a compiler error heres a minimized version of the class in file loggerhinclude iostreamclass logger public logger m filestdcout template typename t logger operatorconst t a m filea return this protected stdostream m fileit is included in my maincpp and works perfecly when i output a string literallog hi however the following would not compileinclude loggerhint main logger log log stdendlthe g compiler reportssrcmaincpp5 error no match for operator in log stdendl,['c++'] +223928,why cannot i pass a various numbers of references to a function i want to do something like thisdouble a b c d eparseandwrite1 2 3 ref a ref b ref cparseandwrite4 5 ref d ref e a 1 b 2 c 3 d 4 e 5however i can not write a function like thisprivate void parseandwritestring leinput params ref double targets this does not work for some reason one can not use ref and params at the same time why soedit ok heres some more information on why i need this through an interface i get a lot of strings containing values with a syntax like thisinputconfig step stepheight rstep rstepheight niterations split smooth outputconfig dataselection corrected units outliercount restoreoriginalrange names in brackets are optional those values need to be parsed and stored in all specific variables that is they are not arrays at all they are more like commandline arguments but around 20 of them i can of course do all that sequencially but that produces hundreds of lines of code that contain a redundant pattern and are not well maintainable,"['c#', '.net']" +223951,private field captured in anonymous delegate class a public event eventhandler aeventclass b private a foo private int bar public void attachtoaevent fooaevent delegate usebar bar since delegate captures variable this bar does it implicitly hold to the instance of b will instance of b be referenced through event handler and captured variable by an instance of awould it be different if bar was a local variable of the attachtoaevent methodsince in my case an instance of a lives far longer and is far smaller than an instance of b i am worried to cause memory leak by doing this,['c#'] +223985,how to use stdvector in php using swig i am working on wrapping a c api in php using swig i am most of the way there but i am having problems with a function that returns a vector the header looks something like thisinclude vectornamespace stfclass myclass public const stdvectormyotherclass getlistthe interface file looks like thisinclude std vectoriimport stf myotherclassi include stf myotherclassh include stf myclasshinclude stf myclasshi seem to be able to call the function fine but it is returning a php resource instead of an object specifically it is a resource of type p std vectort stf myclass thow can i either get this to return an object that i can iterate through preferably with a foreach loop or how can i iterate through this resourceupdatei have been working on a solution based off of what i read here basically i am trying to convert the vector into a python arraytypemapout stdvectorstfmyotherclass array init return value stdvectorstfmyotherclassiterator itr itr 1begin for itr itr 1end itr zval tmp make std zval tmp swig setpointerzval tmp itr descriptorstfmyotherclass 2 add next index zval return value tmp this is very close to working i put a breakpoint inside the wrapper code within swig zts setpointerzval when it goes to initialize the object it does a zend lookup class for stf myotherclass which fails it does not find a class i am not sure why it cannot find the class,"['php', 'c++']" +224029,integer vs int with regard to memory i was wondering if there is a difference in the memory occupied by integer n and int ni know int n occupies 4 bytes normally how about integer n,['java'] +224035,how to create and destroy cdi weld managed beans via the beanmanager i am trying to create instances of cdi managed beans using the beanmanager rather than instance selectget this was suggested as a workaround to an issue i have been having with applicationscoped beans and garbage collection of their dependents see cdi application and dependent scopes can conspire to impact garbage collection for background and this suggested workaround if you use the instance programmatic lookup method on an applicationscoped bean the instance object and any beans you get from it are all ultimately dependent on the applicationscoped bean and therefore share it is lifecycle if you create beans with the beanmanager however you have a handle on the bean instance itself and apparently can explicitly destroy it which i understand means it will be gced my current approach is to create the bean within a beanmanagerutil class and return a composite object of bean instance and creationalcontextpublic class beanmanagerutil inject private beanmanager beanmanager suppresswarningsunchecked public t destructiblebeaninstancet getdestructiblebeaninstancefinal classt type final annotation qualifiers destructiblebeaninstancet result null beant bean beant beanmanagerresolvebeanmanagergetbeanstype qualifiers if bean null creationalcontextt creationalcontext beanmanagercreatecreationalcontextbean if creationalcontext null t instance beancreatecreationalcontext result new destructiblebeaninstancetinstance bean creationalcontext return result public class destructiblebeaninstancet private t instance private beant bean private creationalcontextt context public destructiblebeaninstancet instance beant bean creationalcontextt context thisinstance instance thisbean bean thiscontext context public t getinstance return instance public void destroy beandestroyinstance context from this in the calling code i can then get the actual instance put it in a map for later retrieval and use as normalprivate mapworker destructiblebeaninstanceworker beansbytheirworkers new hashmapworker destructiblebeaninstanceworkerdestructiblebeaninstanceworker destructible beanutilsgetdestructiblebeaninstanceworkerclass workerbindingqualifierworker worker destructiblegetinstancewhen i am done with it i can lookup the destructible wrapper and call destroy on it and the bean and its dependents should be cleaned updestructiblebeaninstancejamworker workerbean beansbytheirworkersremoveworkerworkerbeandestroyworker nullhowever after running several workers and leaving my jboss 710alpha1snapshot for 20 minutes or so i can see gc occurring2011002 gcdesired survivor size 15794176 bytes new threshold 1 max 151884205k1568621k3128704k 091281 secsyet a jmap histogram still shows the old workers and their dependent instances hanging around ungced what am i missingthrough debugging i can see that the context field of the bean created has the contextual of the correct worker type no incompleteinstances and no parentdependentinstances it has a number of dependentinstances which are as expected from the fields on the worker one of these fields on the worker is actually an instance and when i compare this field with that of a worker retrieved via programmatic instance lookup they have a slightly different creationalcontext makeup the instance field on the worker looked up via instance has the worker itself under incompleteinstances whereas the instance field on the worker retrieved from the beanmanager does not they both have identical parentdependentinstances and dependentinstancesthis suggests to me that i have not mirrored the retrieval of the instance correctly could this be contributing to the lack of destructionfinally when debugging i can see beandestroy being called in my destructiblebeaninstancedestroy and this goes through to managedbeandestroy and i can see dependent objects being destroyed as part of the release however they still do not get garbage collectedany help on this would be very much appreciated thanks,['java'] +224040,php run shell script i am trying to run a shell script from a php frontendheres the shell file runsh chmod to 7binbashwget o indexhtml python hw79py indexhtml echo doneheres the php front endphp output shell execrunsh echo preoutputprebut it php page does not return anything except prepre,['php'] +224055,where appears androiddescription label from your manifest androidlabel parameter is thisplayed just under your icon on the home screen but i cannot see where the androiddescription label is thisplayed on the phone home screen applications settings menu i did not find the answer in the android official documentationany idea,['android'] +224063,is ruby quiz still alive a google search brings up 3 retired versions wrubyquizcom v1 v2 v3 it looks like that last quiz posted to v3 was in 2010is there a ruby quiz 4 or something like it,['ruby'] +224070,read floats from a txt file how can i read floats from a txt file depending on the name at the begining of each line i want to read a different number of coordinates the floats are seperated by spaceexample triangle 12 24 30the result should be float x 12 float y 24 float z 30the file has more lines with differens shapes which can be more complex but i think if i know how to do one of them i can do the others on my ownmy code so farinclude iostreaminclude fstreamusing namespace stdint mainvoid ifstream source build a readstream sourceopentexttxt ios basein open data if source if it does not work cerr cannot open datan else if it worked char c sourcegetc get first character ifc t if c is t read in 3 floats float x float y float z whilec go to the next space sourcegetc to do but now i do not know how to read the floats else ifc r only two floats needed float x float y whilec go to the next space sourcegetc to do else ifc p only one float needed float x whilec go to the next space sourcegetc todo else cerr unknown shapen return 0,['c++'] +224075,convert rcppcharactervector to stdstring i am trying to open a file within an rcpp function so i need the file name as a char or stdstringso far i have tried the followinginclude rcpphinclude boostalgorithmstringhppinclude fstreaminclude stringrcppexport sexp readdatasexp f1 rcppcharactervector f1 stdstring fname rcppasff stdifstream fi fiopenfnamec strstdiosin stdstring line fi line rcppcharactervector rline rcppwrapline return rlinebut apparently as does not work for rcppcharactervector as i get a compile time errorfoocpp in function sexprec readdatasexprecfoocpp8 error no matching function for call to asrcppcharactervectormake fo error 1is there a simple way to get a string from the argument or somehow open a file from the rcpp function argument,['c++'] +224077,specifiedpickupdirectory will not create files until viewed by a user on the server i am using a trick nicely described here to store my emails on the application server during testingmy config file looks like thissystemnet mailsettings smtp deliverymethodspecifiedpickupdirectory from specifiedpickupdirectory pickupdirectorylocationeemailstore smtp mailsettingssystemnetthe directory exists and it has no rights issues here is the problem the files would not be created until i navigate to the folder on the server then all of a sudden bang all the files are poping into the directoryanyone have any idea what is going oni have noticed there is another choice pickupdirectoryfromiis but i am unclear when i should use specifiedpickupdirectory and when i should use pickupdirectoryfromiiswhat is the difference between specifiedpickupdirectory and pickupdirectoryfromiis when should i use one over the other is this the cause of the files not appearing till i navigate,['asp.net'] +224081,reasons that the passed intent would be null in onstartcommand is there any other reason that the intent that is passed to onstartcommandintent int int would be null besides the system restarting the service via a flag such as start stickyalso when the service is restarted by the system the intentgetaction method returns null sometimes intent is not null just getactioni asked here too but have not received an answer just yetupdate after chatting with mark murphy he suggested that i return start redeliver intent in the onstartcommand callback in my service instead of start sticky so that the entire intent is sent following a restart i did not do this initially because i was concerned that if the service was attempting to do something then in the middle of that something the service was restarted will it recognize that it started doing that something i guess that is logic i will need to be responsible for,['android'] +224088,webpage not available with webviewloaddata only in emulator i am calling loaddata on my webview and passing it some html in the form of a string like sowebviewloaddata htmlstring texthtml utf8 it works fine on my galaxy tab 101 but the webview thisplayswebpage not available when running on the emulator with everything set up to match my galaxy tab setting androidpermissioninternet in the manifest has no effect though i should not need that permission since i am rendering inmemory html and not accessing anything over the data connection whats going on,['android'] +224108,how to get configuration options programmatically does someone know a way to find out all configuration options from an extjs control programmatically i do mean options like width height etc as described in the extjs documentation,['javascript'] +224115,generate metrics of project with doxygen i currently use doxygen to generate the documentation of my c projects as doxygen is great and generates a lot of information i was wondering if there was a way to integrate metrics of the project in the generated documentation when i talk of metrics i think of lines of code number of classes number of functions cyclomatic complexity etcis there something to do that if that is not possible directly is there a way we can create a little plugin to doxygen to add more informations to the generate documentation,['c++'] +224145,java how to check if a field is of type javautilcollection i have a utility method that goes through various classes and recursively retrieves the fields i want to check if that field is a collectionhere is some sample codevoid mymethodclass classtocheckfield fields classtocheckgetdeclaredfieldsforfield fieldfields check if field if a collectionthanks in advance for the help,['java'] +224158,how to create a custom exception type in java possible duplicatehow can i write an exception by myself i would like to create a custom exception in java how do i do ittrystring wordreaderreadlineifwordcontains create custom exceptioncatchwhen i create my custom exception with throw new i obtain the error unreported exceptionmust be caught or declared to be thrown,['java'] +224166,android tool to generate selector xml for buttons i was wondering if anyone knows of a tool to generate xml selector files for your custom buttons i am getting a bit tired creating buttons convert them to 9png files and then copying and pasting a custom selector in xmli am aware of these toolsas handy as they are in generating assetsresources i miss the option to select 4 images and generate a readytouse selector xml which outputs something likexml version10 encodingutf8selector xmlnsandroid pressed item androidstate pressedtrue androidbackgrounddrawableimg pressed focused item androidstate focusedtrue androidbackgrounddrawableimg focussed default item androidbackgrounddrawableimg default selectori am considering in creating one myself but cannot believe noone already did it thanks,['android'] +224171,does a core data parent managedobjectcontext need to share a concurrency type with the child context can i set the parent context of my managedobjectcontext to a managedobjectcontext with a different concurrency type for examplebackgroundmanagedobjectcontext nsmanagedobjectcontext alloc initwithconcurrencytypensprivatequeueconcurrencytypebackgroundmanagedobjectcontext setpersistentstorecoordinatorcoordinatormanagedobjectcontext nsmanagedobjectcontext alloc initwithconcurrencytypensmainqueueconcurrencytypemanagedobjectcontext setparentcontextbackgroundmanagedobjectcontext my goal is to hopefully get a fast save for managedobjectcontext as it only needs to save things to the parent inmemory context and then have the backgroundmanagedobjectcontext do a save on its own queue unless i happen to need to do another save from the foreground queue before the background one saves my user should never see long save timesi am running into what look like deadlocks but i am not sure if they are related to this or if my problem is elsewheredetails for the one place where i can more or less reliably produce the deadlocki have a managed object context for the main thread it is backed by a managed object context with a private queue concurrency type and that one has a persistent storei have a handful of entity types about 5 each with one or two bidirectional relationships to another entitymy app wants to use icloud i have that code dialed for these tests so it cannot ship with a prepopulated database it needs to build it when it detects an empty oneso when i see an empty database this is checked on the main thread i add around 4 or 8 of all but one of the entity types and that last one gets about 100 all of the adds happen on the main thread the main thread does a savecontext after that completes with no errors it asks the other managed object context to run a block that also does a savecontext this savecontext is definitely a deadlock participant this is also the only stuff done with the background nsmanagedobjectcontext at allthe exact control flow is a little murky after this as a nsfetchedresultscontroller all of a given entity type which has 3 members with a simple sort and a batch size of 20 or so drive the next round of core data activity but there is call from the tableviewcontroller asking how many items it needs to manage which is how many results does the fetched results controller have that call is the other side of the deadlock all this is in the main thread,['ios'] +224172,1d linear convolution in ansi c code rather than reinvent the wheel i wonder if anyone could refer me to a 1d linear convolution code snippet in ansi c i did a search on google and in stack overflow but could not find anything in c i could use for example for arrays a b and c all doubleprecision where a and b are inputs and c is output having lengths len a len b and len c len a len b 1 respectively my array sizes are small and so any speed increase in implementing fast convolution by fft is not needed looking for straightforward computation,['c'] +224190,coredata clear changes from nsmanagedobjectcontext i am instantiating a nsmanagedobjectcontext object at the application delegate level and sharing it across all my uiviewcontrollers heres the code that i use to access it in one of my view controllers nsmanagedobjectcontext managedobjectcontext appdelegatemanagedobjectcontext modelobj model nsentitydescription insertnewobjectforentityfornamemodel inmanagedobjectcontextappdelegate managedobjectcontextnow in this screen i have a uitableview with 9 rows each cell has a uitextfield as the user inputs values into the textfields i assign them into modelobj now my user has an option to cancel out and thiscard all the changes or save them to thisk i have the save code working fine but in the case when a user tries to thiscard the changes i am not sure what to do there does not seem to be a managedobjectcontext thiscardchanges method to throw them all awayi can think of a couple of ways of solving thiscreate a new instance of nsmanagedobjectcontext for each controller instead of sharing one across the application or i could create a bunch of nsstrings in my code and save user values in them and call insertnewobjectforentityforname only if the user clicks savewhich way is the right one or is there a way to make nsmanagedobjectconext thiscard all the changes that were made to itthanks teja,"['objective-c', 'ios']" +224232,is there such a thing as an all inclusive sibling css selector my htmlpdoggiespp classgreen guysfroggiesppcupcakespiggiespan all inclusive sibling selector as i wish it to be when used to select green guys siblings would select the doggies cupcakes and piggiesother selectorsthe selector aka adjacent sibling selector would only select the cupcakesgreen guys p selects the p element that immediately follows green guys the selector aka general sibling selector would only select the cupcakes and piggiesgreen guys p selects all p elements that follow green guys,['css'] +224256,how to change uisegmentcontrol font and selected segment colour possible duplicateuisegmentedcontrol selected segment coloruisegmentcontrol appearances causing issues hi i will like to change the default uisegmentcontrol font to a custom font and change the selected segment color to another color instead of a darker colorthanks from thisto thiseditsolution called change font size remove shadow selected text background color are different from normal state voiddefinesegmentcontrolstyle normal segment nsdictionary normalattributes nsdictionary dictionarywithobjectsandkeys uifont fontwithnamerok size200uitextattributefont uicolor colorwithred7502550 green7502550 blue7502550 alpha10 uitextattributetextcolor uicolor clearcolor uitextattributetextshadowcolor nsvalue valuewithuioffsetuioffsetmake0 1 uitextattributetextshadowoffset nilnsdictionary dictionarywithobject uicolor redcolorforkeyuitextattributetextcolor infosegment settitletextattributesnormalattributes forstateuicontrolstatenormal nsdictionary selectedattributes nsdictionary dictionarywithobjectsandkeys uifont fontwithnamerok size200uitextattributefont uicolor whitecolor uitextattributetextcolor uicolor clearcolor uitextattributetextshadowcolor nsvalue valuewithuioffsetuioffsetmake0 1 uitextattributetextshadowoffset nil nsdictionary dictionarywithobject uicolor redcolorforkeyuitextattributetextcolor infosegment settitletextattributesselectedattributes forstateuicontrolstateselected,"['iphone', 'ios']" +224261,passing intent extra to android broadcast receiver i have created a alarmreceiver class which is used as broadcast receiver for alarm the issue is that i need to send some values from the class which is setting the alarm to the broadcast receiver class setalarmmanagerjava intent i new intentmcontext alarmreceiverclass iputextrakey rowid longtaskid pendingintent pi pendingintentgetbroadcastmcontexttaskid intipendingintentflag one shot malarmmanagersetalarmmanagerrtc wakeup whengettimeinmillis pii need to get the key rowid from intent in alarmreceiver class how can i do that the alarmreceiver class is shown belowpublic class alarmreceiver extends broadcastreceiver public static final string alarm alert action comandroidalarmclockalarm alert public static final string alarm intent extra intentextraalarm override public void onreceivecontext context intent intent here i need the values from intent using bundle or anything,['android'] +224265,android activity restarts after unlocking device i am creating a simple android project but my every activity gets restart when user unlock the screenafter locking is it normal behavior of android app or i have to handle it in manifest or some where else please help,['android'] +224334,tfs 2010 how to produce a changelog ie list of work items between two releases of the application using labels i am looking for a way to automatically produce a changelog actually a list of workitems between two releases of my application i have two versions of my application v1 and v2 each is identified by a label in tfs 2010 label1 and label2 that i manually created before building the setups of my appi have a branching system which means i have a trunk were most of bugs are fixed and a branch where patches are applied mostly using merges from the trunk but there are also some fixes on the branch only that do not concern the trunk the two versions of my application v1 and v2 are versions from the branchi would like tfs 2010 to be able to return the list of bugs that were fixed ie the list of work items with type bug that are closed and verified between these two labelsi tried to achieve this using the web ui of tfs 2010 or using visual studio but i did not find any waythen i tried to ask tfexe for a history using the following command linetf history serverhttpserver urlcollection name project path versionllabel1llabel2 recursive noprompt formatbriefwhere label1 is the label that has been associated with the source code of the v1 of the application and label2 the label that has been associated with the source code of the v2 of the applicationit actually fails in two ways the command line only returns a list of changesets not a list of associated closed work items the list of changesets only contains the changesets that i applied on the branch itself not the changesets that i also applied and the trunk and then merged to the branch setting or not the slotmode parameter does not change anythingthere i tried to write a piece of c code to retrieve the list of workitems not the list of changesetsvar tfs tfsteamprojectcollectionfactorygetteamprojectcollectionnew urihttpserver urlcollection nameversioncontrolserver controlserver tfsgetserviceversioncontrolserverversioncontrolserver vcs tfsgetserviceversioncontrolserverversionspec sfrom versionspecparsesinglespecllabel1 nullversionspec sto versionspecparsesinglespecllabel2 nullvar changesets vcsqueryhistory project path sto 0 recursiontypefull null sfrom sto intmaxvalue true false slotmode to falsedictionaryint workitem dico new dictionaryint workitemforeach changeset set in changesets foreach workitem zz in setworkitems if dicocontainskeyzzid dicoaddzzid zz foreach keyvaluepairint workitem pair in dicoorderbyz zkey consolewritelinestringformatid 0 title 1 pairkey pairvaluetitlethis actually works i get the list of workitems between my two labels which is actually what i wanted but only workitems associated to changesets that were committed on the branch itself are taken into account the workitems of type bug that were solved on the trunk then merged to the branch do not appear slotmode does not change anythingthen i finally tried to replace versionspecs that were defined by a label with versionspecs that are defined by changesetsversionspec sfrom versionspecparsesinglespecc5083 nullversionspec sto versionspecparsesinglespecc5276 nulland my code finally worksso my question is how could i get the same result with labels which are the tfs objects i use to identify a version if it is not possible how should i identify a version in tfs 2010thxbtw i found some questions on stackoverflow but none of them gave me answers with labels for instancequestion example,['c#'] +224345,signalrhub can send a message except signal maker i am studying singalrit is quite interesting frameworki am really want to send a message to all connection except the person who makes a eventfor examplein chatting application there is three clientabcclient a type a message hello and clikc submitclientsaddmessagedata send hello to all cleintinclude cleint ai want to send hello only client b and ccould you help me how can i achieve it i think this can get all clients rightvar clients hubgetclientschatreally sorry for my englishthank you,['asp.net'] +224387,systemdataentityexception the underlying provider failed on commit using entity framework i received a number of the following exceptions last night in one of my applicationssystemdataentityexception the underlying provider failed on commit systemdatasqlclientsqlexception timeout expired the timeout period elapsed prior to completion of the operation or the server is not responding at systemdatasqlclientsqlinternalconnectiononerrorsqlexception exception boolean breakconnection at systemdatasqlclienttdsparserthrowexceptionandwarning at systemdatasqlclienttdsparserstateobjectreadsnierrortdsparserstateobject stateobj uint32 error at systemdatasqlclienttdsparserstateobjectreadsnidbasyncresult asyncresult tdsparserstateobject stateobj at systemdatasqlclienttdsparserstateobjectreadnetworkpacket at systemdatasqlclienttdsparserstateobjectreadbuffer at systemdatasqlclienttdsparserstateobjectreadbyte at systemdatasqlclienttdsparserrunrunbehavior runbehavior sqlcommand cmdhandlersqldatareader datastream bulkcopysimpleresultset bulkcopyhandler tdsparserstateobject stateobj at systemdatasqlclienttdsparsertdsexecutetransactionmanagerrequestbyte buffer transactionmanagerrequesttype request string transactionname transactionmanagerisolationlevel isolevel int32 timeout sqlinternaltransaction transaction tdsparserstateobject stateobj boolean isdelegatecontrolrequest at systemdatasqlclientsqlinternalconnectiontdsexecutetransactionyukontransactionrequest transactionrequest string transactionname isolationlevel iso sqlinternaltransaction internaltransaction boolean isdelegatecontrolrequest at systemdatasqlclientsqlinternalconnectiontdsexecutetransactiontransactionrequest transactionrequest string name isolationlevel iso sqlinternaltransaction internaltransaction boolean isdelegatecontrolrequest at systemdatasqlclientsqlinternaltransactioncommit at systemdatasqlclientsqltransactioncommit at systemdataentitycliententitytransactioncommit end of inner exception stack trace at systemdataentitycliententitytransactioncommit at systemdataobjectsobjectcontextsavechangessaveoptions options at systemdataentityinternalinternalcontextsavechanges at systemdataentityinternallazyinternalcontextsavechangeswhats interesting about this error is that the data was actually written to the database i found a related post on a ms site that seemed to indicate that this was a network related errora few questions that i could use assistance on arewhat options do i have to trouble shoot this erroris it more than likely network related or could the db be a suspecthow can i tell from the code whether the transaction really did completeshould i query the db on this error to check if success or simply retry the transactionif i do retry the transaction how can this be accomplished automatically with entity framework or do i simply catchretrywhat other items should i be looking atthanks in advanceupdateusing ignite for sql we were able to determine that a secondary sql process from another group was monopolizing the cpu preventing our application from functioning properly in short were moving forward with adding a secondary server to prevent further conflicts between the two teamswhats still interesting about the exception is that the transaction actually succeeded rather than failed,['.net'] +224395,could not load file or assembly microsoftpracticesenterpriselibrarycommon or one of its dependencies i have searched google for this and could not find the solution to the problemmy website references dal custom dll which references enterprise library data access componentsi have added the enterprise library from the nuget package manager and when i try to build the website this compilation error pops uperror 44 could not load file or assembly microsoftpracticesenterpriselibrarycommon or one of its dependencies the located assemblys manifest definition does not match the assembly referencei have tried setting the copy local true in the dal for the enterprise library dlls and the dlls are transferred to the bin directory of the website along with dal dll but still the error pops upcan anyone guide me on this,"['c#', 'asp.net']" +224402,why is this call ambiguous can anyone explain why does the following code produce the error compiling in microsoft visual studio 2008class base1 class base2 interface i1 interface i2 class c i1 i2 static class program static t m1tthis t t i1 x where t base1 return t static t m1tthis t t i2 x where t base2 return t static void mainstring args base1 b1 new base1 c c new c b1m1c the error is the call is ambiguous between the following methods or properties consoleapplication1programm1consoleapplication1base1consoleapplication1base1 consoleapplication1i1 and consoleapplication1programm1consoleapplication1base1consoleapplication1base1 consoleapplication1i2 i thought the compiler could thistinguish between two methods using the where clauses,['c#'] +224410,thisplay line number in textarea i want to thisplay the line number in a textarea like this is possible in jqeuryi looked for answers on so but i cannot find what i wantthisplay current line and column number for a textareaspecify and limit number of lines in textarea and thisplay line count using jqueryalso the solution i tried from the jsfiddle provided from the comments show me the textarea like thiswhich line 1234 is the first line and the second line is 5678,['jquery'] +224424,how secure is it to call secret urls in an ios app we want to use a web service in our app which obviously requires to call a url it is not https just plain old http using nsurlconnectionthe problem is this web service is very expensive and every thousand calls costs us real money the fear is that someone could figure out which url we call and then misuse that letting the costs explode there is no way for us to track if a call to that web service was legitimatewere calculating based on how many apps we sell multiplied by an assumption of how often that app will be used per user in average we have some good statistics on which we base our assumptionsare there known ways of figuring out which url an app is calling on the internet to retrieve information,"['iphone', 'ios']" +224471,how to correctly set mysql timezone i have a weird problem concerning mysql timezonein my website config file i have this line which sets the timezone mysql queryset session time zone offset offset is properly calculated no worries about thatthe funny part is that if i add another line right after this like this q mysql queryselect now as nowrow mysql fetch arrayrowecho rownowafter executing that code the time is thisplayed correctlybut in some other queries i insert rows in tables that have a column named date that defaults to current timestamprows are inserted like thisinsert into sessions user id values 1the sessions table has a date column that defaults to current timestampbut the value inserted in db still points back to the timezone of the server any ideas how to work through this,"['php', 'mysql']" +224498,cross domain login check i have bookmarklet if i open a random page not mine and click the bookmarklet i would like to check if the user is logged in on my pagei am already doing crossdomain ajax request using accesscontrolalloworigin but it looks like there is not session id or cookie send hereis there a way to do this,"['php', 'javascript']" +224504,any performance benefit to locking down javascript objects javascript 185 ecmascript 5 adds some interesting methods that prevent future modifications of a passed object with varying degrees of thoroughnessobjectpreventextensionsobjobjectsealobj objectfreezeobj presumably the main point of these is to catch mistakes if you know that you do not want to modify an object after a certain point you can lock it down so that an error will be thrown if you inadvertently try to modify it later providing youve done use strict that ismy question in modern js engines such as v8 is there any performance benefit eg faster property lookups reduced memory footprint in locking down objects using the above methodssee also john resigs nice explanation a does not mention performance though,['javascript'] +224532,no such file or directory in capistrano deploy here is the error when doing cap deploy err 151946 find varwemclabreleases201208184942publicimages err 151946 no such file or directory err 151946 find varwemclabreleases201208184942publicstylesheets no such file or directory err 151946 find varwemclabreleases201208184942publicjavascripts err 151946 no such file or directoryany thoughts what causes the error thanks,['ruby-on-rails'] +224553,datareaderi vs datareadergetvaluei vs datareadergetstringi isdatareaderilogically equivalent todatareadergetvalueiare they the same are they different is there a situation where one would be appropriate over the otherthere are documented differentlygets the column located at the specified indexreturn the value of the specified fieldbut when i use them they both return the value of the field what does it mean to get the column what does it mean to return the value of a fieldbonus chatterwhen i callreaderireadergetvalueireadergetstringii get a string each time,['.net'] +224579,php ios aes encryption i have been having trouble trying to communicate between php and my ios application using aes encryption so far i have considered two methods of implementation the first was to use opensslon the ios side i implemented in a way to mimic the code shown here aesctxton the php side i took the generated key and iv from the iphone and used it as input to the php openssl encrypt the results differed in terms of the outputi have also considered but this so post aescrypt decryption between ios and php fixed deterred methe project is not tied down to aes it just seemed like a strong encryption algorithm that wouldnt be too hard to implement my basic question is what is the easiest way to implement a good encryption algorithm that can easily be used to communicate between ios and php,"['php', 'ios']" +224583,restkit image upload i am using restkit to drive interactions with my web server i am trying to use routing to post an event object to the server with an image attached to it the code is as follows rkobjectmanager manager rkobjectmanager sharedmanager rkobjectmapping map self eventmapping managerserializationmimetype rkmimetypeformurlencoded maprootkeypath event managermappingprovider setserializationmappingmap forclassevent class managerrouter routeclassevent class toresourcepathv1eventsjson formethodrkrequestmethodpost manager postobjectevent delegateself blockrkobjectloader loader rkobjectmapping sermap rkobjectmanager sharedmanager mappingprovider serializationmappingforclassevent class nserror error nil nsdictionary d rkobjectserializer serializerwithobjectevent mappingsermap serializedobjecterror rkparams p rkparams paramswithdictionaryd p setdataevent imagedata mimetypeimagejpeg forparamimage loaderparams p if i create an instance of rkparams using the serialized event object then add the image data and assign it as the rkobjectloaders params property all the properties become one massive serialized string there must be a way to upload an image without the massive string serializationi have also tried having an nsdata property that is mapped to some attribute converting a uiimage into nsdata along the way but restkit complains that it cannot be mapped has anyone done this before,"['objective-c', 'ios']" +224596,yii how to retrieve model data into a layout page i wish to list some categories name on my layout mainphp pagesince the layout does not have any associated controller or model i wish to create a static method like this on category modelpublic static function getheadermodels get all models here return modelsand then in the main layoutphpmodels categorygetheadermodelsforeachmodels as model my question is a very basic onehow can i retrieve those category names from the model here is the full modelclass category extends cactiverecord public static function modelclassname class return parentmodelclassname public function tablename return category public function rules return array arrayparent id numerical integeronly true arrayname length max 255 arrayid parent id name safe on search public function relations return array users arrayselfmany many user categoriescategory id user id public function scopes return array toplevelarray condition parent id is null public function attributelabels id yiittrans id parentid yiittrans parent name yiittrans name return array id id parent id parentid name name public function search criteria new cdbcriteria criteriacompareid thisid criteriacompareparent id thisparent id criteriacomparename thisname true return new cactivedataproviderget classthis array criteria criteria public static function getheadermodels what sintax should i use to retrieve the models here a a return models,['php'] +224599,how to find the windows dialing rules in net this should be simple but is not apparently sincewindows 3 or so there is a control panel called phone or phone modem in that control panel is a bunch of information about how a modem would dial up assuming you have a modem hooked up for example do you need to dial 9 to get out what is the area code and so forth how can i access this information programmatically i am using c net 2010,"['c#', '.net']" +224620,how to use twitter bootstrap popovers for jquery validation notifications i can make popovers appear using bootstrap easily enough and i can also do validations using the standard jquery validation plugin or the jquery validation engine but i cannot figure out how to feed one into the otheri think what i need is some hook which is called by the validator when it wants to thisplay a notification give it a closure that passes the message and the target element to a popover this seems like a kind of dependency injectionall nice in theory but i just cannot figure out where that hook is or even if one exists in either validation engine they both seem intent on taking responsibility for thisplaying notifications with all kinds of elaborate options for placement wrappers styles when all i am after is the error types i do not necessarily even need message text and element it relates to i have found hooks for the entire form not the individual notificationsi much prefer validation systems that use classes to define rules as they play nicely with dynamically created formsanyone have a solution or a better idea,['jquery'] +224652,pretty urls in php frameworks i know that you can add rules in htaccess but i see that php frameworks do not do that and somehow you still have pretty urls how do they do that if the server is not aware of the url rulesi have been looking yiis url manager class but i do not understand how it does it,['php'] +224655,ipad using scrolltop with fixed navigation not functioning properly only works first time i am developing a single page site with vertical scroll for navigation i have a fixed position nav bar and my scrolling content is supposed to go up and down while being floated right of the navigation here is a preview link the problem is that it works perfectly fine in firefox safari and chrome when i view it on an ipad the first time i select a nav item the scroll works perfectly as soon as it completes all the click functionality from my nav is not working even the ones that are not controlling the slider contenti do not get the error when i am animating a different property like margintop that will not work in my project because i also need to be able to navigate throughout the site by using the page scrollerdoes anyone have any ideas on how i can solve this problemthank you,['jquery'] +224672,can you define an android intentfilter using a string resource i wanted to define the string name of my intent in the stringsxml file and then bind that string to an intent filter as so intentfilter action androidnamestringapp intent action category androidnameandroidintentcategorydefault categoryintentfilterwhen i tried this however i get various errors about the system could find no activity to handle my intent i was trying to keep values ie the intent names centralized instead of hardcoded in the manifest as well as in code as it is at least this lets me centralize it out of the application code but i still have it hardcoded in the manifest is this really impossible to do or is there some way to make it work,['android'] +224679,detached entity and managed entity what a detached entity meanshow is it possible to convert a managed entity to a detached entity during a transaction,['java'] +224712,does an android game center exist i am working on one android application which needs the gaming center like an apple game center does android provide any game center like apple game center centerand if so is it an opensource or paid onewhat are the limitations of this one as compared to apple game centeror what are the features of it as compared with apple game centerwhich devices supports game center of androidi am working on one application in which i want to share my application with more than one user at a time at a same time say multi player game apple game store provides facility for multiplayer game i want this kind of facility in android,['android'] +224735,android how to add view at start of layout my question is simple i have a linearlayout it has some child views now i want to add a view at the start of the child means in normal addviewview the view s added at the end of the layout but i want to add it at start at first position any idea,['android'] +224772,using an if statement in a mysql select query i am trying to use an if statement in a mysql select query i am getting an error after the and statement where the first ifselect jjob idecompany namejjob descjtjobtype namejcompensationststate namemcmetro city nameiindustry name jjob contact personjdt insrtjjob titlejjob exp datejskills from jobs j join employer e on jcompany idecompany id join lookup jobtype jt on jjob typejtjobtype id join lookup state st on jstate idststate id join jobs location jl on jjob idjljob id join lookup metro city mc on jlmetro city idmcmetro city id join lookup industry i on jindustry idiindustry id join jobs qualification jq on jjob idjqjob id join lookup degree qualification ldq on ldqqualification id jqqualification id where jactivey and jdt insrt coalescepemailsntdtdate subsysdateinterval 4 day andifjqcourse id0 thenifjqdegree id0then jskills like concat pskillselsejqdegree idpdegreeid or jskills like concat pskillsend ifelsejqcourse idpcourseid or ifjqdegree id0 then jskills like concat pskills else jqdegree idpdegreeid or jskills like concat pskills end ifend if group by jjob id order by jdt insrt descwhy does not this work and what is the proper way to do an if statement in a mysql query,['mysql'] +224773,easiest way to check if a string is palindrome i want to check if a string is a palindrome or not i would like to learn an easy method to check the same using least possible string manipulations,['java'] +224780,why does parseint return an unexpected result when i pass a string with a leading zero parseint1 1parseint01 1parseint5 5parseint05 5parseint8 8 but whyparseint08 0parseint09 0,['javascript'] +224790,iframe contents thisappear when manipulated by mootools i have got a third party mootools library creating tabs and i have got google double click for publishers dfp creating ads dfp creates the ads in an iframe then the tabs script grabs an anchestor of the iframe and messes with it to create the tabs the contents of the iframe gets lost in the processi am looking for a way of coping with this tried firing the dfp stuff after the tabs had loaded but then the google scripts crashedthe iframe is from a different domain to the parent window so anything which tries to do stuff to elements within the iframe is going to failaddtab functiontext title content var grab content var container grab new elementdiv setstylethisplay none addclassthisoptionsclasscontainer thiswrapperadoptcontainer var pos thistabslength var evt thisoptionshover mouseenter click var tab container container toggle new elementligrabnew elementa href title title grab new elementspan html text addeventevt thisonclickbindwitheventthis posinjectthismenu if grab typecontent string taburl content thistabspushtab return thisfireeventonadded tabtoggle tabcontainer pos,['javascript'] +224802,javalangruntimeexception system server dead my appwidget crashes with following erroreandroidruntime 5572 fatal exception maineandroidruntime 5572 javalangruntimeexception unable to start receiver comandroidmlweatherwidgetweatherwidgetlarge javalangruntimeexception system server deadeandroidruntime 5572 at androidappactivitythreadhandlereceiveractivitythreadjava1805eandroidruntime 5572 at androidappactivitythreadaccess2400activitythreadjava117eandroidruntime 5572 at androidappactivitythreadhhandlemessageactivitythreadjava981eandroidruntime 5572 at androidoshandlerthispatchmessagehandlerjava99eandroidruntime 5572 at androidoslooperlooplooperjava130eandroidruntime 5572 at androidappactivitythreadmainactivitythreadjava3683eandroidruntime 5572 at javalangreflectmethodinvokenativenative methodeandroidruntime 5572 at javalangreflectmethodinvokemethodjava507eandroidruntime 5572 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava839eandroidruntime 5572 at comandroidinternaloszygoteinitmainzygoteinitjava597eandroidruntime 5572 at dalviksystemnativestartmainnative methodeandroidruntime 5572 caused by javalangruntimeexception system server deadeandroidruntime 5572 at comandroidmlhomeappwidgetappwidgetmanagergetappwidgetidsappwidgetmanagerjava375eandroidruntime 5572 at comandroidmlweatherwidgetweatherwidgetlargeonreceiveweatherwidgetlargejava202eandroidruntime 5572 at androidappactivitythreadhandlereceiveractivitythreadjava1794eandroidruntime 5572 10 moreeandroidruntime 5572 caused by androidosdeadobjectexceptioneandroidruntime 5572 at androidosbinderproxytransactnative methodeandroidruntime 5572 at comandroidmlhomeappwidgetilauncherappwidgetstubproxygetappwidgetidsilauncherappwidgetjava256eandroidruntime 5572 at comandroidmlhomeappwidgetappwidgetmanagergetappwidgetidsappwidgetmanagerjava369eandroidruntime 5572 12 morecan anybody understand from the above log what exactly is causing this error,['android'] +224807,systemnethttphttpclient caching behavior i am using httpclient 060 from nugeti have the following c codevar client new httpclientnew webrequesthandler cachepolicy new httprequestcachepolicyhttprequestcachelevelcacheifavailableclientgetasynchttpmyserviceasdfthe service this time couchdb returns an etag value and status code 200 ok there is returned a cachecontrol header with value mustrevalidateupdate here are the response headers from couchdb taken from the visual studio debuggerserver couchdb1 erlang otpr14b04etag 127964df653cea4316d0acbab10fd9c04date fri 09 dec 2011 115607 gmtcachecontrol mustrevalidatenext time i do the exact same request httpclient does a conditional request and gets back 304 not modified which is righthowever if i am using lowlevel httpwebrequest class with the same cachepolicy the request is not even made the second time this is the way i would want httpclient also behaveis it the mustrevalidate header value or why is httpclient behaving differently i would like to do only one request and then have the rest from cache without the conditional requestalso as a sidenote when debugging the response status code is shown as 200 ok even though the service returns 304 not modified,['c#'] +224830,partial include paths in mustachejs i am trying to include a partial inside my template from within a directorythis worksheaderthis does notincheaderheaderany location other than a sibling does not seem to be picked up is this normal,['javascript'] +224844,conditional compilation when using arc is there a way to ask the compiler if arc is turned on and then conditionally compile based upon that value for example i have a protocolprotocol protocolarequiredvoidprotocolmethodoneoptionalvoidprotocolmethodtwoendif i am using arc i would like to make protocolmethoda optional when using arc and required when not using arc this is because one of the main reasons for utilizing this method is to dealloc the object instancewith that said heres what i would like to happenprotocol protocolaifdef some arc variable optionalelse requiredendifvoidprotocolmethodoneoptionalvoidprotocolmethodtwoend,"['iphone', 'objective-c']" +224848,aspnet hidden field vs invisible textbox what are benefits of using a hidden field in aspnet when we can use another invisible element such as label or text box,['asp.net'] +224854,how to convert nsvalue to nsdata and back a have a number of nsvalue obtained via kvc valueforkey that i need to append to an nsdata object in order to send it over the network using game center obviously i will also need to convert the nsvalue back from nsdata for more kvc setvalueforkey i do not know the exact type of each nsvalue so i am limited to using the interfaces provided by nsvalue and nsdata i should mention that the nsvalue are never pointer typesi am surprised that there is no nsdata datawithvaluevalue and neither something like value datawithencoding or similar but maybe i am blind and not seeing the obvious choice i thought about using getvalue to copy the value into a void buffer but how am i supposed to determine the buffer length other than by using objctype and comparing that with all possible typeshow should i go about thisnotenskeyedarchiver is out of the question because it is terribly inefficient a 4 byte float is archived to a 142 bytes nsdata a 8 byte cgpoint uses 260 bytes when archived to nsdata keeping the amount of data sent to a minimum is crucial to what i am doing,['objective-c'] +224877,aspnet mvc receives null as a string instead of null i have something wrong with either json or aspnet mvc i am using aspnet mvc and here is what i am sending from the clientnoteafter debugging in chrome i am explaining that this is what is passed within javascript i am not manually setting state to null as it is coming as result from somewhere else as null which once again is not in my control as it is coming from databasewhile debugging state thisplays that it is null instead of null but while debugging in mvc it is thisplaying null instead of nullajax clientpost method post data country us this is null because it is coming from somewhere else as null state null my aspnet mvc handler receivespublic actionresult postclient model ifmodelstate null this is true ifmodelstate null this should be true is it problem of aspnet mvc or jqueryso is it jquery that sends null as null or is it mvc that is setting null as nullsolutioni had to just recursively create new object hierarchy cloning the object and send it to jquery as jquery sent data as form encoded in which there is no way to represent null however ideally jquery should not have serialized null at all,"['javascript', 'jquery']" +224881,use namespace in param is it good practice to include namespaces for classes in param annotations i know that phpdoc does not support namespaces but how will other tools like phpdox or doxygen actwhich way is better more commonnamespace foosomenamespaceuse foosomeothernamespacemyotherclass with namespace param foosomeothernamespacemyotherclass otherclass class myclassmyotherclass otherclass do something without namespace param myotherclass otherclass class myclassmyotherclass otherclass do something,['php'] +224912,why use weak pointer for delegation i cannot understand why it is correct to define a delegate with weak pointer property nonatomicweak id delegatei cannot realize why is not necessary to retain a reference to the delegate i do not want the object that i use as the delegate to be deallocated thus i would prefer using a strong reference not a weakin many cases the delegate is the same object where the instance of my class will be created in this case creating a weak reference would be a great solution to avoid retain cycle but what if i choose a totally different object as the delegate i searched for other questions on stack overflow but i cannot find something that can help me to fully understand this situation,['objective-c'] +224916,what does this method is deprecated mean for application developers i see quite a few good old useful methods or even entire classes being deprecated and obsolete but code that used to call those methods continues to work so what does this mean to me as an android applications developercontinue using this method as long as i want because newer sdkswill always remain backward compatibleit will work as long as i build for older targets eg api 8 butif i build from api 14 up the compiler will refuse to completethe buildboth 1 and 2otherthis is especially confusing when no alternatives are provided as in the case of webviewpicturelistenerhtmlonnewpicture,['android'] +224923,php detect mysql updateinsertion failure due to violated unique constraint this is kind of similar to this questionphp mysql insert fails due to unique constraintbut i have a different twist let us say i have a table with only one column the columns name is title and it has a unique constraint placed on itfirst i insert a row where title something the next time i try to insert something it will fail due to a unique key constraint which is good what i would like to do is allow it to fail and check the error code provided by mysql to ensure it failed due to a unique key constraint ie let the database handle the uniqueness and i just handle the error code and tell the user that title already exists when the result comes backis there a way to do this,"['php', 'mysql']" +224935,oracle bulk insert i am not familiar with plsql however i have to perform a bulk insert for a task basically i have to query table one to get one column and then use it on a different table to insert it something like thisfor ids in a file as cur idselect thistinct column1 as col1 list from table1 where idcur idfor cols in col1 list as cur col insert into table2 values cur idcur col214234first 3 chars of cur colnow i have around 4k ids in the file and each id would have different range of thistinct col1 max165 million min 2ki am trying to achieve this read from one table and insert into other using bulk insert it is okay if this runs overnight etc i got this script from some research online create or replace procedure test procistype tobjecttable is table of all objectsrowtypeobjecttable tobjecttablebegin select bulk collect into objecttable from all objects forall x in objecttablefirstobjecttablelast insert into t1 values objecttablex endi think this might be useful in my case but i dont quite understand the semantics where do i mention column1 also for insert values are expressed as objecttablex insetead of values can someone please explain the script to me and help me modify it to my use case using table1table2col1 ids etc variables that i mentioned in my example the db is 10gthanks,['sql'] +224938,can modern c compilers inline functions that are defined in a cpp file i am aware that the keyword inline has useful properties eg for keeping template specializations inside a header fileon the other hand i have often read that inline is almost useless as hint for the compiler to actually inline functionsfurther the keyword cannot be used inside a cpp file since the compiler wants to inspect functions marked with the inline keyword whenever they are calledhence i am a little confused about the automatic inlining capabilities of modern compilers namely gcc 443 when i define a function inside a cpp can the compiler inline it anyway if it deems that inlining makes sense for the function or do i rob him of some optimization capabilities which would be fine for the majority of functions but important to know for small ones called very often,['c++'] +224958,how to turn screen off or send device to sleep i want to send device to sleep or turn the screen off i have investigated and found this topic turn off screen on androidbasically the are three ways to do it but i have found problems for the threea choice 1powermanager manager powermanager getsystemservicecontextpower servicemanagergotosleepint amountoftimeproblem it causes fc i have read i need device power permissions but it cannot be granted for normal appsb choice 2powermanager manager powermanager getsystemservicecontextpower servicepowermanagerwakelock wl managernewwakelockpowermanagerpartial wake lock your tagwlacquirewlreleaseproblem this does not work for me i do not know why it does not give me a fc but it is innocuousc choice 3windowmanagerlayoutparams params getwindowgetattributesparamsflags layoutparamsflag keep screen onparamsscreenbrightness 0getwindowsetattributesparamsproblem i can get it to work but when try to turn on device it does strange things like do not like to return or if my apps is in front automatically goes to sleep just after pressing on button this looks more like a tip or workaround than normal solutioncan anyone tell me any good method to send device to sleep or turn screen off that can run without problems it sound rare to me that a simple functionality like this has not a good way to use it or at lest well documented,['android'] +224971,add no of days in a date to get next dateexcluding weekends i have an date i need to add no of days to get future date but weekends should be excludedie input date 9dec2011no of days to add 13next date should be 27dec2011here weekendssatsun are not counted,"['javascript', 'jquery']" +224986,check if path is current path in symfony2 how do i check if the current page is this path pathsomenamepath i want to set a css class to the a element or possible remove it altogether eg if iscurrentpathsomenamepath a href pathsomenamepath classyouareheremy linka else a href pathsomenamepath my linka endif,['php'] +224998,when to use stdbegin and stdend instead of container specific versions are there any general preferences or rules that explain when container specific versions of begin and end should be used instead of free functions stdbegin and stdendit is my understanding that if the function is a template whereby the container type is a template parameter then stdbegin and stdend should be used ietemplateclass t void do stuff const t t stdfor each stdbegint stdendt some stuff what about in other scenarios such as a standard member function where the type of container is known is it still better practice to use stdbegincont and stdendcont or should the containers member functions contbegin and contend be preferredam i correct in assuming that there is no benefit in performance by calling contend over stdendcont,['c++'] +225009,rest client example in ruby can anyone explain me with an example by using rest client to do getpostput operations in a rest web servicein postput using rest client need to pass the whole xml body to dopostput operationsfor example using rest clienti need to get the content of a service using restclientgeturlpost an xml to an url restclientposturlentirexmlput an xml to an url restclientputurlentirexmldelete using rest clientcan anyone help me with examples for all the rest client http methods with examplei need to send the whole xml along with namespace to a rest service using putpost operations of rest clientif anyone have examples on this kindly post then please,['ruby'] +225015,when would a uiviews boundsorigin not be 0 0 when would an uiviews boundsorigin not be 0 0 this post was helpful to meimportant bounds x and y the origin are for moving inside the view for eample x5 moving 5pix to the left of the frames origin meaning draw all content within this view to the left 5pix of frames origin it does not do anything to itself it is what being drew on it that get affectedbut it describes only the case when i had set the value of boundsorigin myselfin what other cases the value of boundsorigin 0 0,"['ios', 'objective-c']" +225031,android sidebar like facebook or firefox with the new facebook app it comes with an hidden sidebar that i would love to use something like that in my applications it looks kinda like the sidebars that firefox mobile havedo you have any idea how to implement it besides reimplementing the viewpager i have tried with an horizontalscrollview but that would also lead to reimplementation of iti am not seeing any other way besides these two any suggestionsthanks in advance,"['java', 'android']" +225040,javascript callback function parameter with same name as other variable var str internetperformactionfunctionstr consolelogstris there a problem with having a private variable str and also having a callback function with a parameter of the same namethanks,['javascript'] +225070,open url in same window and in same tab i want to open a link in the same window and in the same tab that contains the page with the linkwhen i try to open a link by using windowopen then it opens in new tabanot in the same tab in the same window,"['javascript', 'html']" +225073,how can i link source to a jar package in eclipse how can i link source to a jar package in eclipsei am trying to add the external library chntbusb i added the jar file to my build path but when i tried to run the application it returned the following errorthe jar file chntbusb has no source attachmenti have used jdgui to decompile the jar file and the source code is contained,['java'] +225075,inline definitions pg474 knkingthe general rule in c99 is that if all toplevel declarations of a function in a particular file include inline but not extern then the definition of the function in that file is inlinewhat is a toplevel declaration of a functionif the function is used anywhere in the program including the file that containts its inline declaration then an external declaration of the function will need to be provided by some other file when the function is called the compiler may choose to perform an ordinary call using the functions external definition or perform inline expansion using the functions inline definition there is no way to tell which choice the compiler will make so it is crucial that the two definitions be consistentwhat is he saying herevariables with static storage duration are a particular problem for inline functions with external linkagebut i thought you could not call a function with external linkage thecompiler would give an error pg 473so attempting to call average from another file will be considered an errorconsequently c99 imposes the following restrictions on an inline function with external linkage but not on one with internal linkage the function may not define a modifiable static variable the function may not contain references to variables with internal linkagewhy if a function is inline and extern then even if it does declare astatic int i since the function cannot be linked to you cannot call itbut would not a static variable be created outside the inline functionsstackframe so you should be able to link to it do inline functions have a stack frame whats going on here,['c'] +225076,dbunit best practices for performance what are some best practicesprinciples to follow beyond those recommended on the actual dbunit site that can greatly speed up tests as well as keep them maintainable i long for a library like factory girl for java but it does not look like it is possible because of the static typing my current thinking is to have 1 xml dataset per test class at this point maybe i share some of these and maybe i do not while some test data might be duplicated acrossed datasets i am finding it too hard to maintain shared datasets across 30 unitintegration tests and i have got a long more to gowould appreciate any principles to follow that lead to tests that perform well and easy to maintain,['java'] +225077,change chrome print preview default options in chrome print preview under options tab the default is having headers and footers ticked on is it not possible to set it default to off via javascript chrome extension anything outside telling user to do it manuallyor is it possible to remove the date thisplayed there,['javascript'] +225090,svg animate with dynamically added elements based on this code i am trying to animate a dynamicallygenerated svg elementvar svgnode documentcreateelementnssvgvar circle documentcreateelementnscirclecirclesetattributecx 10circlesetattributecy 10circlesetattributer 10circlesetattributefill bluevar ani documentcreateelementnsanimatetransformanisetattributeattributename transformanisetattributeattributetype xmlanisetattributetype translate anisetattributefrom 10anisetattributeto 100anisetattributebegin 0sanisetattributedur 2sanisetattributefill freezecircleappendchildanisvgnodeappendchildcircledocumentgetelementbyidmydivappendchildsvgnodethe svg shows up fine but the animation does not work if i write the equivalent code in plain htmlsvg it works i am using chrome,['javascript'] +225122,crash on imageloadermacho on app loading on iphone i am getting a crash when the app load from the debugger exc bad access on this line asm dyld zn16imageloadermacho12bindlocationerkn11imageloader11linkcontextemmpks0 hpkcls7 320i understand it has something with image loader but i cannot figure what any ideathanks,"['iphone', 'ios']" +225125,rtree implementation java i was searching the last few days for a stable implementation of the rtree with support of unlimited dimensions 20 or so would be enough i only found this but they only support 2 dimensionsanother option would be a multidimensional implementation of an intervaltree maybe i am completly wrong with the idea of using an rtree or intervalltree for my problem so i state the problem in short that you can send me your thoughts about thisthe problem i need to solve is some kind of nearestneighbour search i have a set of antennas and rooms and for each antenna an interval of integers eg antenna 1 min 92 max 85 in fact it could be represented as room set of antennas interval for antenna the idea was that each room spans a box in the rtree over the dimension of the antennas and in each dimension by the interval if i get a query with nantennas and values for each antenna i then could just represent the information as a query point in the room and retrieve the rooms nearest to the point hope you got an idea of the problem and my idea,['java'] +225126,mysql2so libmysqlclient rso15 cannot open shared object file no such file or directory i am trying to run a rails two app with ubuntu 1004 server sphinx myql2 version 027 and percona server 55 myslql 55 mysql2 in irb works ok i can connect to the db this rails 2 app is working in another centos server with mysql 51 when i runscriptserver e production i getmysql2so libmysqlclient rso15 cannot open shared object file no such file or directoryhere are the libs i have ls l usrlib grep sqlrwrr 1 root root 10581008 2018 1651 libmysqlclientalrwxrwxrwx 1 root root 16 201210 0548 libmysqlclient ra libmysqlclientalrwxrwxrwx 1 root root 20 201210 0548 libmysqlclientso libmysqlclientso16lrwxrwxrwx 1 root root 29 201210 0601 libmysqlclientso15 usrliblibmysqlclientso16rwrr 1 root root 7332 2018 1644 libmysqlservicesarwrr 1 root root 562520 20100208 0659 libsqlite3arwrr 1 root root 973 20100208 0659 libsqlite3lalrwxrwxrwx 1 root root 19 201207 1715 libsqlite3so libsqlite3so086lrwxrwxrwx 1 root root 19 20110309 1843 libsqlite3so0 libsqlite3so086rwrr 1 root root 528668 20100208 0659 libsqlite3so086drwxrxrx 3 root root 4096 201210 0547 mysqlhow can i fix it,['mysql'] +225130,how to build a free version from a paid version without duplicating the xcode 4 project i have heard rumors that it is possible to build different variations of an app without duplicating xcode projects by using targets and conditional compilation instructions likeif free version self loadgreatfeatureelseself loadboringfeaturesohow to set xcode 4 up to be able to thistinguish between building archiving a free or paid version of the projecthow to tell xcode 4 to include a certain set of images and other resources in the paid version but not in the free version and vice versahow to tell xcode 4 to build the free or paid version do not want to build both of them all the time as this would slow development downwhat are the caveats of this approachi do know whats the caveat of duplicating the xcode project once i fix a bug in either version i must do the same thing in the other same goes for making improvements and modifications,"['iphone', 'ios']" +225165,how do i write a generic java enum rotator how do i make a generic enum rotator it would be a generic version of next in this example public class testenum enum temperature hot cold public static void mainstring args temperature t temperaturehot temperature t2 nextt static temperature nexttemperature t if tordinal temperaturevalueslength 1 return temperaturevalues0 else return temperaturevaluestordinal 1 edit in the comments irreputable suggests a superior solution irreputable if you post it as an answer i will select it you might want to save time by copying this answer static t extends enumt t nextt t int index tordinal suppresswarningsunchecked enumt constants tgetclassgetenumconstants if index constantslength 1 suppresswarningsunchecked t result tconstants0 return result else suppresswarningsunchecked t result tconstantsindex 1 return result,['java'] +225188,change sizecolor of vertex in jung how do you change the size of a specific vertex in jung visualization library i am reading the documentation but i am not extremely familiar with java and i cannot find any good examples on line,['java'] +225191,whats wrong with array declaration invalid digit in octal constant int arr2020 080297381500407504050778521250779108 49494017811857608717409843694804566200 8149317355791429937140675388300349133665 5270952304601142692468560132567137023691 2231167151676389419236542240402866331380 2447326099034502447533537836842035171250 3298812864236710263840675954706618386470 6726206802621220956394396308409166499421 24580566739926971778789683148834896372 2136230975007644204535140061339734313395 7817532822753167159403800462161409535692 163905429635314758240017542436298557 8656004835718907054374460215851541758 19808168059447692873921386521704895540 0452088397359916079757321626267933279866 8836688757622072034633674655123263935369 0442167338253911249472180846293240627636 2069364172302388346299698267598574043616 2073352978319001743149714886811623570554 0170547183515469169233486143520189196748 i get the following errorq11c810 error invalid digit 8 in octal constantq11c867 error invalid digit 8 in octal constantq11c1549 error invalid digit 8 in octal constantq11c1719 error invalid digit 9 in octal constantq11c1858 error invalid digit 9 in octal constantq11c2216 error invalid digit 8 in octal constantq11c2446 error invalid digit 8 in octal constant,['c'] +225237,interface type cannot be statically allocated i tried to put this in the header file of my view objectproperty nonatomic uicolor colorto store the color that lines should be drawn with in this viewxcode gives me an error on this lineinterface type cannot be statically allocatedwhat does that mean and what should i doediti did add a and at the point of synthesis it saidarc forbid synthesizing a property of objective c object with unspecified ownership or storage attribute,['objective-c'] +225240,make div appear and change the whole html to be darker i have a div with embedded youtube after i click some button i would like the div to appear i know how to achieve this but i want the whole background to become darker this is inline with overlaysi have tried using opacity i change the opacity of the whole html with jquery ie htmlcssopacity05 and change back the opacity of the div to normal but for some reason the opacity of the div stays the same 05 i do not quite like the opacity since actually it does not make the background darker rather lighter any ideas how to make the background darker,"['javascript', 'jquery']" +225246,how can i assign an id to a view programmatically in an xml file we can assign an id to a view like androidididsomething and then call findviewbyid but when creating a view programmatically how do i assign an idi think setid is not the same as default assignment setid is extracan anybody correct me,['android'] +225264,python map string split list i am trying to map the strsplit function to an array of string namely i would like to split all the strings in a string array that follow the same format any idea how to do that with map in python for example let us assume we have a list like this a 2012 4631201220 201917 201220 010921want to split the strings by space split using map to have a list as 2012 4631 201220 201917 201220 010921,['python'] +225282,what is the c equivelant of nsmutablearray and nsarray what is the c equivelant of nsmutablearray and nsarraydoes c have a mutable and nonmutable i noticed that string appears to be mutable by default obviously i am completely new to cif you could tell me how to quickly populate the array in c that would be a bonus thanks,"['c#', '.net', 'objective-c']" +225292,examples of forcing freeing of native memory direct bytebuffer has allocated using sunmiscunsafe jdk provides abillity to allocate socalled direct bytebuffers where memory is allocate outside of java heap this can be beneficial since this memory is not touched by garbage collector and as such does not contribute to gc overhead this is a very useful for property for longliving things like cacheshowever there is one critical problem with existing implementation underlying memory is only allocated asynchronously when the owning bytebuffer is garbagecollected there is no way to force early deallocation this can be problematic since gc cycle itself is not influenced by handling of bytebuffers and given that bytebuffers are likely to reside in old generation memory area it is possible that gc is called hours after bytebuffer is no longer in usebut in theory it should be possible to use sunmiscunsafe methods freememory allocatememory directly this is what jdk itself uses for allocatingdeallocating native memorylooking at code one potential concern i see is possibility of doublefreeing of memory so i would want to make sure that state would be properly cleanedcan anyone point me to code that does this ideally would want to use this instead of jnanote i saw this question which is sort of relatedlooks like the answers pointed out are good way to go here is code example from elastic search that uses the idea thanks everyon,['java'] +225318,how to remove round corners in jquery mobile how to remove the round edges borderradius from the particular element or from div tag that is using jquery mobile,"['jquery', 'css']" +225323,how can i switch to another user in mysql via cmd hello everyone i am try very hard to switch to other user created by me with password but i am not able to switch it i have searched on google but i do not know what type of error is it it says access denied for user localhost to database and i get one more error when i try to switch user and it says you have an error in your sql syntax check the manual that corresponds to your mysql server version for the right syntax to use near mysql and atlast when i listed current user it showed me localhost in current user columnplease helpthx in advance,['mysql'] +225351,jpa when to use gettransaction when persisting objects i have recently starting working with jpa on the google app engine in reading some examples i have noticed a couple variations in the way objects are persisted in one case i have seen something like thisentitymanagergettransactionbeginentitymanagerpersistobjectentitymanagergettransactioncommitin other cases i do not see the use of gettransaction i simply see entitymanagerpersistobject when is it appropriate to use gettransaction,['java'] +225375,why are protected variables not allowed by default in checkstyle i get a lot of warnings in eclipse like thesevariable myvariable must be private and have accessor methodsi think i get them because i did not set protectedallowed manually to true in eclipse but why is it set to false by default should not i use protected attributes,['java'] +225388,algorithm for slicing planes in place out of an array of rgb values i have got a flat array of byte rgb values that goes r1 g1 b1 r2 g2 b2 r3 g3 b3 rn gn bn so my data looks likechar imagedatawidth height 3but i want to pass a widthheight array to an existing c library that expects a single plane of this data that would be a sequence of just the r values or just the g or just the bit is easy enough to allocate a new array and copy the data duh but the images are very large if it werent a c library but took some kind of iteration interface to finesse the slicing traversal that would be great but i cannot edit the code i am callingit wants a plain old pointer to a block of sequential memoryhowever i have write access to this array it is viable to create a routine that would sort it into color planes i would also need a reverse transformation that would put it back but by definition the same method that sorted it into planes could be applied to unsort ithow efficiently can i in place turn this array into r1 r2 r3 rn g1 g2 g3 gn b1 b2 b3 bn and then back again any nonnaive algorithms,"['c++', 'c']" +225416,java conventions use getterssetters within the class my professor really emphasizes protecting against privacy leaks by always using accessors and mutators to access private instance variables however do i have to use the getterssetters of a class within the claso for instance if i have the following classpublic class person private string name private int ageand i want to write a tostring method for it can i just writepublic string tostring return name ageor do i need to do something like thispublic string tostring return thisgetname thisgetage,['java'] +225425,how do i deserialize into an existing object c in c after serializing an object to a file how would i deserialize the file back into an existing object without creating a new object all the examples i can find for custom serialization involve implementing a constructor that will be called upon deserialization which is exactly what i want except that i do not want the function to be a constructorthanks,['c#'] +225431,how to get abstract syntax tree ast out of jison parser so i have generated a parser via jison mygeneratorjsvar parser requirejisonparser a grammar in jsonvar grammar lex rules s skip whitespace af09 return hex bnf hex strings hex strings hex hex grammar can also be a string that uses jisons grammar formatvar parser new parsergrammar generate source ready to be written to thiskvar parsersource parsergenerate you can also use the parser directly from memory returns trueparserparseadfe34bc e82a throws lexical errorparserparseadfe34bc zxgmy question is how do i retrieve the ast now i can see that i can run the parser against input but it just returns true if it works or fails if notfor the record i am using jison,['javascript'] +225437,how to free up the memory in javascript i am working with canvas and its imagedata object which contains a huge amount of data millions of integers so working with a few arrays already takes a lot of memory up to 300mb is there a way to free up the memory of some array when it is unnecessary i am trying to assign undefined to that variable is it right,['javascript'] +225462,stack vs heap c i just had a quick question about how stack variables versus heap variables work as i understand it stack variables are variables that after functions return will be deleted and heap variables are persistent but what i am really confused about is how to allocate heap variables inside functionsint myobjectaddobjectconst char a myobject newobjecta return 0say that i have a constructor for myobject that is newobjectconst char a then in this function when it is called after the return does the newly constructed newobject get deleted if yes how can you allocate to the heap within a function then if not how do you cleanup your memory laterfurthermore what exactly is the role of a destructor and when is it called,['c++'] +225485,start ics emulator without menu button i am trying to see the overflow menu in the actionbar on ics and i do not have a devicei am using the emulator and want to know how do i start the emulator without a menu button i want to emulate a device with no menu hardware buttoni have looked on but i do not see how to do thisthanks for any help,['android'] +225512,does webdriver support pagefactory for python i was reading about page objects and design patterns on the webdriver project site and came across pagefactory it does not look like the webdriver for python api includes pagefactory is this true,['python'] +225515,using mock patch to mock an instance method i am trying to mock something while testing a django app using the imaginatively named mock testing library i cannot seem to quite get it to work i am trying to do thismodelspyfrom somelib import fooclassclass promotionmodelsmodel foo modelsforeignkeyfooclass def barself print do something i do not wanttestpyclass viewsdosomethingtestcase view my appviewsdo something def test enter promotionself patchobjectmy appmodelsfooclass bar def fake barself mock my method print do something i want return true selfclientgetreverseviewwhat am i doing wrong,['python'] +225521,cannot downcast because class is not polymorphic is it possible to have inheritance with no virtual methods the compiler is saying that the following code is not polymorphicexampleclass a int a int getareturn aclass b a int b int getbreturn bin another class we are trying to downcast from an a object to a b object a a b b dynamic castbabut this gives the following error cannot dynamic cast source type is polymorphic,['c++'] +225531,how to create gridtile view with css for example i have some class article and i want to view this class as grid view so i applied this stylearticle width100px height100px background3 floatleft margin5pxthat style will make the article look tiledgrid it is work fine with fixed height but if i want to set the height to auto automatically stretch according to the data within it the grid look nasty and i want to make the view like this,['css'] +225532,webresourceaxd not found i cannot get script files to load on my website everything else works fine i have not tried scriptresourceaxd howeveri have verified this issue exists on both cassini and iis7i have verified my 64bit 40 webconfig contains the mapping for webresourceaxdmy system time is correct i heard there may be issues with that i have verified that it works in other projects so the culprit has to be my web applicationmy web application is 40 mvc3 web applicationmy webconfig can be found herethis error is killing me any help would be appreciated,['asp.net'] +225585,accessing azure storage tables from c code i have a c dll running on azure instance role with no problemsi want the dll to be able to access read and write into an azure storage account specifically read and write to a storage tableis it even possiblewould appreciate any examplesthanksnava,['c++'] +225598,how to pass devises current user as user id i am practicing my ruby on rails by creating a simple application where users can sign up using devise and post articles after installing devise i go ahead and generate a scaffold for the articles rails g scaffold article titlestring articletext user idintegerthen i create the devise user controllerrails generate devise usermy article controllerclass article activerecordbase belongs to userendmy user controllerclass user activerecordbase has many articles devise database authenticatable registerable recoverable rememberable trackable validatable attr accessible email password password confirmation remember meendnow my question is how do you make it so that user id in httplocalhost30articlesnew is automatically current useridalso in httplocalhost30articles the user should only be able to view the articles associated with their user id not anyone elses what changes to the articles controller should i make to do thisit is my first time posting here at stack overflow and your help would be appreciated thanks a bunchedit found the solution to the first question for future referencei put fhidden field user id in formhtmlerb and def create articleuser id current userid endto my article controller this is successfully passing the current userid as the articles user id perfectly,['ruby-on-rails'] +225619,using alassetslibrary and alasset take out image as nsdata i wish to extract the image using alassetslibrary and alasset directly in the form of a nsdata objectusing a nsurl i take out the image in the following mannernsurl referenceurl newurlalassetslibrary library alassetslibrary alloc initlibrary assetforurlreferenceurl resultblockalasset asset uiimage copyoforiginalimage uiimage imagewithcgimageasset defaultrepresentation fullresolutionimagenow here we take the image as a uiimage but i need to take the image directly as nsdatai wish to do this because i have read that once you take the image in uiimage then we lose all the exif details of the imagethat is the reason i want to extract the image directly as nsdata instead of doing this nsdata webuploaddatauiimagejpegrepresentationcopyoforiginalimage 05this step makes me lose all the exif detailsplease help,['iphone'] +225625,problems loading and saving images from camera and camera roll what am i doing wrong i am building an app in which you can make pictures or pick an image from the camera roll and save these inside the app to be thisplayed in a tableview and detailviewthe problem is that when i make a picture from inside the app and save it the tableview and detailview get terribly slow as if the app is freezingi also get this error cgaffinetransforminvert singular matrix when i load a picture from the camerarol that was not taken from inside my app there is no problem and the app runs very smouthlythis is the code for when i open the camera and camera rollvoidactionsheetuiactionsheet actionsheet didthismisswithbuttonindexnsintegerbuttonindexif buttonindex actionsheetcancelbuttonindex returnuiimagepickercontroller picker uiimagepickercontroller alloc initpickerdelegate selfpickerallowsediting noswitch buttonindex case 0 if uiimagepickercontroller issourcetypeavailableuiimagepickercontrollersourcetypecamera pickersourcetype uiimagepickercontrollersourcetypecamera break case 1 if uiimagepickercontroller issourcetypeavailableuiimagepickercontrollersourcetypesavedphotosalbum pickersourcetype uiimagepickercontrollersourcetypesavedphotosalbum breakself presentmodalviewcontrollerpicker animatedyes this is where i save it to the camera roll and put the image in an imageviewvoidimagepickercontrolleruiimagepickercontroller picker didfinishpickingmediawithinfonsdictionary infonsstring mediatype info objectforkeyuiimagepickercontrollermediatypeuiimage mijnimageif cfstringcompare bridge retained cfstringrefmediatype kuttypeimage 0kcfcompareequalto mijnimage uiimage info objectforkeyuiimagepickercontrolleroriginalimage mijnplaatje image mijnimage uiimagewritetosavedphotosalbummijnimage nil nil nil picker thismissmodalviewcontrolleranimatedyes and here i save the image inside my appibactionsaveidsenderdrankjesplaatje mijnplaatje imageself thismissmodalviewcontrolleranimatedyeswhat am i doing wrong,['iphone'] +225648,where you can and cannot declare new variables in c i heard probably from a teacher that one should declare all variables on top of the programfunction and that declaring new ones among the statements could cause problemsbut then i was reading kr and i came across this sentence declarations of variables including initializations may follow the left brace that introduces any compound statement not just the one that begins a function he follows with an example if n 0 int i for i0ini i played a bit with the concept and it works even with arrays for example int main int x 0 while x10 if x5 int yx y0 10 printfd dny0y4 x so when exactly i am not allowed to declare variables for example what if my variable declaration is not right after the opening brace like hereint main int x 10 x printfdnx int z 6 printfdnzcould this cause trouble depending on the programmachine,['c'] +225662,pythonic way to add datetimedate and datetimetime objects i have two objects that represent the same event instance one holds the date the other the time of this event and i want to create a datetime object since one cannot simply add date and time objects following call fails datetimedate2011 01 01 datetimetime10 23,['python'] +225667,equality operators always leftassociative will it matter in c language specificationits to be found except for the assignment operators all binary operators are leftassociativebut will it make at difference for equality operators and saybool xyz return xyz and so onwont the result always be the same even if the order of xyz differs in the return statementalways return the same value if the init values of xyz is the same obviouslyxyz equals to xyz and for xyz equals to xyz right,['c#'] +225681,how do i write to a python subprocess stdin i am trying to write a python script that starts a subprocess and writes to the subprocess stdin i would also like to be able to determine an action to be taken if the subprocess crashesthe process i am trying to start is a program called nuke which has its own built in version of python which i would like to be able to submit commands to and then tell it to quit after the commands execute so far i have worked out that if start python in the command prompt like and then start nuke as a subprocess then i can type in commands to nuke but id like to be able to put this all in a script so that the master python program can start nuke and then write to its stdin and thus into its built in version of python and tell it to do snazzy things so i write a script that start nuke like thissubprocesscallcprogram filesnuke63v5nuke63 t enuketesttestnkthen nothing happens because nuke is waiting for user input does anyone know how i would now write to the stdini am doing this because i am running a plugin with nuke that causes it to crash intermittently when rendering multiple frames so i would like this script to be able to start nuke tell it to do something and then if it crashes try again so if there is a way to catch a crash and still be ok then that would be great,['python'] +225691,my own storage engine crashes because of a too small sort buffer i am working on my own storage engine for mysql so far this storage engine works reliable and correct but only for small 100 mb tablesfor big tables i get a segmentation fault when i try to execute a query with an order by so something like this will lead to a segfaultselect from item order by i authorso i compiled mysql in debug mode and saw that the there is now an assertion failure in the merge buffers function in filesortcc the following will fire if there is not enough space in sort buffer dbug assertmaxcount0honestly i have no idea what i can change in my storage engine to make this error thisappear it first looked like i have to change the configuration paramater sort buffer size but even setting this thing higher than the size of the table does change anything with this errordoes anyone who know how to write mysql storage engines have any idea how to solve this,"['c++', 'mysql']" +225712,open a numeric keyboard without forcing the edittext to be numeric only i have come across this while doing work on creating my own keyboard but cannot for the life of me remember where i ran across iti want top open the numeric keyboard however i want my edittext to only accept an ip address adding a filter to my edittext was not too hard thanks to this answerhowever now i want to make the numeric keyboard to open rather than the standard text keyboard unfortunately search results are saturated with the same how do you limit edittext to numeric input questions over and overcould anyone point me to the right place for manually opening the numeric keyboard,['android'] +225720,jaxrs in relation to jersey and jsrs i am trying to get my head around some concepts in javajsrs describe specifications but carry no actual implementations eg is the home for javaa api for restful web services it serves as a common reference for all implementations of jsr311one can download the interfaces of jsr311 from however unless you are implementing jsr311 by yourself these have no particular valuejsrs will usuallyalways have a reference implementation to find it youll have to google jsr x reference implementation or see the specifications home page eg for jsr311 this reference implementation is jersey using maven you can get the jersey server from since jersey provides an implementation according to the interfaces found in you only need to add jersey as a dependency in your project and not the jsr311api itself this applies to all jsr technologiesputting both and as dependencies in your project will possibly cause classpath problemsam i completely off or onto someting,['java'] +225721,printwriter println no new line created i am trying to decode an outlook msg file to a text file using apache poi classes everything works fine except for the println method of printwriter it doesna t create a new line it just concatenates every sentence directly one after another the result of the code snippet below is de textpara iso de para i tried the code on several machines it works on my local tomcat instalation windows machine but fails on a tomcat or weblogic instalation on a solaris platform i thought it had something to do with the encoding algorithm so i used printstream in stead of printwriter indicating the encoding iso88591 but no luck neitherany idea try byte msgbyte base64decodebase64msgbase64 inputstream inputmsg new bytearrayinputstreammsgbyte msg new mapimessageinputmsg 1 transform msg to txt try txtout new printwriteroutputmsg try string thisplayfrom msggetthisplayfrom txtoutprintlnde thisplayfrom catch chunknotfoundexception e loggerinfoerror extrayendo thisplayfrom e try string thisplayto msggetthisplayto txtoutprintlnpara thisplayto catch chunknotfoundexception e loggerinfoerror extrayendo thisplayto e finally iftxtout null txtoutclose else loggererrorno se ha podido parsear el mensaje,['java'] +225732,which c standard library functions use malloc under the hood i want to know which c standard library functions use malloc and free under the hood it looked to me as if printf would be using malloc but when i tested a program with valgrind i noticed that printf calls did not allocate any memory using malloc how come how does it manage the memory then,['c'] +225774,cannot cast array to pointer i have the following source include iostreamusing namespace stdvoid mainint j char arr1010 char ptr ptr arrwhen i compile it using vs2010 i get this error error a value of type char 10 cannot be assigned to an entity of type char i thought arrays in c were just pointers so a char could also be char what am i doing wrong,['c++'] +225781,merge two json objects with jquery i have two json objectsandi have been looking for a way to combine these two objects into one objectthanks in advance,['jquery'] +225806,remove spacing between table cells and rows i am designing an html email template which forces me to use tables in the code below i am having trouble 1 removing the spacing below the placeholder image and 2 removing the space between the image and the caption heres a screenshot of how it looks in chrome 15 on os x 1068 doctype htmlhtmlhead titleemail templatetitle meta httpequivcontenttype contenttexthtmlcharsetutf8 headbody table styleborder 1px solid b50b32 margin 30px auto width 600px padding 0 borderspacing none cellspacing0 cellpadding0 tr td idmain stylebackgroundcolor f2f2f2 h2 stylecolor b50b32 fontfamily lucida grande arial sansserif fontsize 22px fontweight normal padding 15px margin 25px 0 backgroundcolor fmajor headline goes hereh2 table classmainstoryimage stylefloat left width 180px margin 0 25px 25px 25px trtd stylepadding 0 border 1px solid redimg srcplaceholderjpg width180 height130 styleborder none margin 0 padding 0 altplaceholder tdtr trtd stylepadding 0 border 1px solid redp classimagecaption stylebackgroundcolor bebebe color 3 fontfamily lucida grande arial sansserif margin 0 padding 5pxcaptionptdtr tablemainstoryimage p stylemargin 0 50px 25px 25pxlorem ipsum dolor sit ametp pa hrefclick here to read more ap div styleclear bothdiv tdmain tr tablebodyhtmlthe red borders are there only to show the outlines of the cells i do not want them there in the final version,"['html', 'css']" +225810,escaping single quote from an mvc 3 razor view variable i have a variable within itemname that contains the string it is tuesday to alleviate javascript errors in the c controller i have already escaped this single quoteon the webpage it appears like this it is tuesday this at least prevents any javascript errors however i do not want the actual string thisplayed to contain the backslash that has escaped ithow might i be able to revert the escaping once the javascript errors have already been taken care of this feels like a rather simple problem but i am a bit unfamiliar with mvc 3 any hint is much appreciated my searching did not find me any example specific to thisan example of my code in the razor viewforeach var item in model htmlthisplayformodelitem itemname itemname it is tuesday,['javascript'] +225813,ruby openfile path errnoenoent no such file or directory i keep getting this no such file or directory error when trying to open a file i am doingfile open 242ca0e342 mjpg according to the rubydoc and keep getting such errorwhat am i doing wrong,['ruby'] +225816,link error when declaring public static variables in c i have this class with variable configuration parameters i want to include it in other classes jugadorhumano jugadoria main partidaclasica partidamisionpragma onceclass configuracionpublic static int max ataques static int div territoriosint configuracionmax ataques 5int configuraciondiv territorios 3what i want is to be able to modify or read the values from the other classes i cannot declare a static variable and define it in the declaration i cannot let that variables without definition either because i get unresolved external errors1jugadoriaobj error lnk2005 public static int configuracionmax ataques max ataquesconfiguracion2ha already defined in jugadorhumanoobj1jugadoriaobj error lnk2005 public static int configuraciondiv territorios div territoriosconfiguracion2ha already defined in jugadorhumanoobj1mainobj error lnk2005 public static int configuracionmax ataques max ataquesconfiguracion2ha already defined in jugadorhumanoobj1mainobj error lnk2005 public static int configuraciondiv territorios div territoriosconfiguracion2ha already defined in jugadorhumanoobj1partidaclasicaobj error lnk2005 public static int configuracionmax ataques max ataquesconfiguracion2ha already defined in jugadorhumanoobj1partidaclasicaobj error lnk2005 public static int configuraciondiv territorios div territoriosconfiguracion2ha already defined in jugadorhumanoobj1partidamisionobj error lnk2005 public static int configuracionmax ataques max ataquesconfiguracion2ha already defined in jugadorhumanoobj1partidamisionobj error lnk2005 public static int configuraciondiv territorios div territoriosconfiguracion2ha already defined in jugadorhumanoobj1dleiremy dropboxcarpetas compartidascompartidos victorpracticas poo iip3p3m10debugp3m10exe fatal error lnk1169 one or more multiply defined symbols foundwhat should i do to avoid this redefinition i get i cannot figure it out and i cannot find a similar problem,['c++'] +225854,operation not supported on readonly collection c wp7 im trying to implement a lazy load more items when the user gets to the bottom of the listbox but everytime i try to add new items to the listbox i get results like thisoperation not supported on readonly collectioni have already tried several solutions from forums to blogs none seem to work i cannot even understand the logic behinds the problem which seems a bit odd for mewhat i am doing is basically loading a list of items and assigning as the itemsource of my listbox winefilterlistboxitemssource wineswhen the user gets to the bottom of the list i add more items just like twitter app for wp7public observablecollectionwine wines if atbottom int count pagewinefilterlistboxitemscount int end count 10 for int i count i end i pageloadwinelistcount private void loadwinelistint count 1 winefilterlistboxitemsaddwines,"['c#', '.net']" +225856,how to throw a c exception i have a very poor understanding of exception handlingie how to customize throw try catch statements for my own purposesfor example i have defined a function as follows int compareint a int bi would like the function to throw an exception with some message when either a or b is negativehow should i approach this in the definition of the function,['c++'] +225866,how to parse an xml file containing bom i want to parse an xml file from url using jdom but when trying thissaxbuilder builder new saxbuilderbuilderbuildaurli get this exceptioninvalid byte 1 of 1byte utf8 sequencei thought this might be the bom issue so i checked the source and saw the bom in the beginning of the file i tried reading from url using aurlopenstream and removing the bom with commons io bominputstream but to my surprise it did not detect any bomi tried reading from the stream and writing to a local file and parse the local file i set all the encodings for inputstreamreader and outputstreamwriter to utf8 but when i opened the file it had crazy characters i thought the problem is with the source url encoding but when i open the url in browser and save the xml in a file and read that file through the process i described above everything works fine i appreciate any help on the possible cause of this issue,['java'] +225877,is there a json equivalent of xqueryxpath when searching for items in complex json arrays and hashes like id 1 name one objects id 1 name response 1 objects etc is there some kind of query language i can used to find an item in 0objects where id 3,['javascript'] +225878,is anything wrong with using sinatra to develop a full website i am in the process of developing a new website the level of complexity of the site would be somewhere on the order of yelpcom i am pretty new to ruby but decided i want to develop the backend using it in the process i stumbled across sinatra i really love the simplicity of the routing in sinatra and decided to use it as the starting point for my development it seems most places say sinatra is great for quick development and for small web apps is there an inherent scaling problem with sinatra or are the comments stemming from the fact that you basically have to build everything up from scratch any comments regarding your opinion about using sinatra as the basis for a large scale web app would be appreciatedi am not sure if stackoverflow is the correct place to ask an opinion question such as this but it is the only resource i currently have at my thisposal to actually get some feedback about something like this,['ruby'] +225881,is text case sensitive is the jquery text selector case sensitivefor exampleinput typetextdoes not match butinput typetextdoes matchthis appears to be the case i am just looking for verificationeditit is looking like even the typetext selector is case sensitive in chrome and firefox but not ie8 in ie8 document mode,['jquery'] +225905,how can i get msbuild to increment the clickonce publish revision version number on a build server we have an nant script that checks out from cvs and then runs msbuild to publish the application the problem is we have to remember to always increment the version in visual studiowe have the option to auto increment this on publish but this gets wiped on the next checkout and i would rather not have to get the build script to check in the project fileis there a simple way to do this,['.net'] +225910,rails fragment cache testing with rspec i feel like this is a notsomuch documented topic at least i have had a lot of trouble finding our about the best practices herei am fragment caching in the view using a cache keytbody employeeseach do employee cache employee do tremployee td employeename td employeecurrent positions td employeehome base td employeejob classesnow i can add touch true on the belongs to side of my has many associations and this will do everything i need to keep this fragment caching up to date but for the life of me i am having a hard time figuring out how to test thisdropping in touch true is easy and convenient but it spreads the expiry logic around a couple places i would love to have an rspec request spec that walks through and checks the behavior on this something that is not liable to change much but can bring all the caching requirements into one specific file that describes what is supposed to be occurringi tried along these linesrequire spec helperinclude authenticationmacrosdescribe employee index caching do before do railscacheclear actioncontrollerbaseperform caching true login confirmed employee end after do actioncontrollerbaseperform caching false end specify the employee cache is cleared when position assignments are modified specify the employee cache is cleared when home base assignments are modifiedendthe specs were fleshed out with the capybara steps of going through and making the updates of course and i thought i was quite on the right track but the tests were flickering in weird ways i would modify the specs to output the employee objects cache key and sometimes the cache keys would change and sometimes not sometimes the specs would pass and sometimes notis this even a good approachi know so wants questions that are answerable so to start how can i set up and tear down this test to use caching when my test env does not have caching on by default in general however i would really like to hear how you might be successfully testing fragment caching in your apps if you have had success with thisediti am accepting cailinannes answer as it addresses the problem that i specifically ask about but i have decided however that i do not even recommend integration testing caching if you can get away from itinstead of specifying touch in my association declarations i have created an observer specific to my caching needs that touches models directly and am testing it in isolationi would recommend if testing a mulitmodel observer in isolation to also include a test to check the observers observed models otherwise you can stub out too much of realitythe particular answer that lead me to this is here,['ruby-on-rails'] +225922,run css3 animation only once at page loading i am making a simple landingpafe driven by css3 to make it look awesome there is an a plopping upkeyframes splash from opacity 0 transform scale0 0 50 opacity 1 transform scale11 11 to transform scale1 1 and to make it even more awesome i added an hover animationkeyframes hover from transform scale1 1 to transform scale11 11 but there comes the problem i assigned the animations like thisa some basic styling here animation splash 1s normal forwards easeinoutahover animation hover 1s infinite alternate easeinouteverything works just fine the a splashes into the users face and has a nice vibration when he hovers it bit as soon as the user blurs the a the smooth stuff ends abruptly and the a repeats the splashanimation which is logically to me but i do not want it tois there some way to solve this problem without some javascript class jiggery pokery,['css'] +225951,creating an array of generic collections actually the question should becreating an array of generic anythingwhy cannot the compiler take care of itthe following would be flagged as an error cannot create generic arraylistmydto dtolists new arraylistmydto anexistingdtolistto overcome that i need tolistmydto dtolists listmydtoarraynewinstancearraylistclass 2dtolists0 new arraylistmydtodtolists1 anexistingdtolistso why cannot the compiler convert the first case into the second casei do realise that generics are compiletime determinate and not runtime determinate while arrays are runtime determinate and therefore need a determinate type in order to create an arraywhat are the technologicallogical barriers compiler designers would encounter that would prevent them being able to implement thisis the issue purely philosophical concerning language orthogonality if so how would such a behaviour violate language orthogonalityis it a question of complexity explain the complexityi am hoping answers to my question would give me better insight into java compiler behaviour when it concerns genericsside notecmon stop being trigger happy the answers array of generic listdo not answer my question why cannot compilers spontaneously perform the conversion,['java'] +226018,why serialization when a class object in memory is already binary cc my guess is that data is scattered in physical memory even the data of a class object is sequential in virtual memory so in order to send the data correctly it needs to be reassembled and to be able to send over the network one additional step is the transformation of host byte order to network byte order is it correct,"['c++', 'c']" +226023,cakephp or condition originaly posted on cakephp qa but i will put it up here in hope of getting some answersi have a bunch of companies that has a status of 0 as default but sometimes get a higher status now i want to use the high status if exists but revert to 0 if not i have tried a bunch of different approaches but i always get either only the ones with status 0 or the ones with the status i want never giving me status if exists and 0 if notgives me only the status i specify not giving me the ones with status 0company array conditions array or array companystatus 0 companystatus status gives me only status of 0company array conditions array or array companystatus status companystatus 0 status definition and retrieving data in codefunction getcountryid null status null bunch of code for retrieving country with id and all it is companies etc all with status 0 status less companies thiscountryfind if status status companies thiscountryfindfirst array conditions array countryid id contain array product array company array conditions array or array companystatus status companystatus 0 mergin status less companies and status companies and returning data to flex applicationi changed the name for the models for this question just to make more sense people are generaly frighten away when i tell them i work with cakephp for my flex application i guess the logic to this question does not make sense but trust me that it makes sense in my applicationthanks,['php'] +226044,ie 8 overflow hidden and maxwidth i want to thisplay text in the table and i want to cut it when it is wider than 150px but i do not want fixed width of the table cell if there is no text width will be 0px everything works in ie9 firefox chrome opera but not in ie8code example in ie8code example in chromeheres the codedoctype html public w3cdtd html 401 transitionalen htmlheadstyletd span border 1px solid red maxwidth 150px whitespace nowrap overflow hidden textoverflow ellipsisspan border 1px solid green thisplay blockstyleheadbodytabletr tdspanworks in firefox chrome opera ie 79 but not in ie 8spantd tdworks in firefox chrome and opera but no dotstd td stylethisplay blockworks in firefox chrome and opera with dotstdtrtablebodyhtmlit is possible do so without any javascript or setting fixed width,"['html', 'css']" +226062,how to cast an integer to void pointer while working with threads in c i am facing the warningwarning cast to pointer from integer of different sizethe code is as followsincludestdiohincludesystypeshincludestdlibhincludepthreadhvoid printvoid id int a10 printfmy thread id is ldnpthread self printfthread d is executingnid return void 42int main pthread t th5 int t int i int status void ret fori0i5i statuspthread createthinullprintvoid i getting warning at this line ifstatus printferror creating threadsn exit0 pthread jointhiret printfdnint ret pthread exitnullcan anybody explain how to pass an integer to a function which receives void as a parameter,['c'] +226072,customized the suggestion list of autocomplete text view this is the code for my autocompletetextview string countries getresourcesgetstringarrayrarraycountries array final arrayadapterstring adapter new arrayadapterstringthisrlayoutitem list countries textview autocompletetextview dialogfindviewbyidridautocompletetextview1 adaptersetnotifyonchangetrue textviewsetadapteradapterthis is item list xml version10 encodingutf8textview xmlnsandroidandroidlayout widthfill parentandroidlayout heightwrap contentandroidpadding10dpandroidtextsize16spandroidtextcolor0 androiddrawablerightdrawablearrowand this is the output i want to change this popup kind of suggestion box and want to show the suggestion list a little bit below from the autocompletetextview similar to this please thisregard the apple design itas just about where the results appear how can i do this please suggest thanks,['android'] +226088,how can i add a onscroll event to iscroll4 the onscroll event is not yet supported by the iscroll4 is there a known way to extend the iscroll to support an onscroll event,"['javascript', 'jquery']" +226113,or which is the best practice when nesting inline and anchor tagsstronga hreflinkastrong or a hrefstronglinkstrongasurprisingly enough i have not found the answer here or googling it,['html'] +226129,how do i subtract one week from this date in jquery this is my codevar mydate new datetodaysdate mydategetdate mydategetmonth mydategetfullyeartxtenddatevaltodaysdatei need txtenddates value todays date one week,"['javascript', 'jquery']" +226137,play an audio file using jquery when a button is clicked i am trying to play an audio file when i click the button but it is not working my html code ishtml body div idcontainer button idplay play music button div bodyhtmlmy javascript is documentreadyfunction playclickfunction var audio audiowalk new audio audiowalksrc audiowalkaddeventlistenerload function audiowalkplay i have created a fiddle for that too,"['javascript', 'jquery', 'html']" +226144,change position of view after end of animation i develop a widget based on viewgroup and my problem is that i need to save position of items after the end of animation i called setfillaftertrue in my animation object i created animationlistener and in it is onanimationend method call viewlayoutltrb to set the position after animation because i want animation to start from new items position next time but in this case it looks like items are layouted twice if i do not use viewlayoutltrb at the end of animation next animation starts from previous position here is my codeprivate void scrollup forint i 0 i getchildcount i final view child getchildati final int index i final int newleft childgetleft moffsetbetweenitems final int newtop childgettop moffsetbetweenitems translateanimation scrollup new translateanimation0 moffsetbetweenitems 0 moffsetbetweenitems scrollupsetduration1500 scrollupsetfillaftertrue scrollupsetanimationlistener new animationlistener override public void onanimationstartanimation animation override public void onanimationrepeatanimation animation override public void onanimationendanimation animation childlayoutnewleft newtop newleft childgetmeasuredwidth newtop childgetmeasuredheight childstartanimationscrollup please give me an advice how should i reset views position accordingly to the end position of animation,['android'] +226159,how to know from class file if debug metadata is included how can i tell if compiled java classes have debug metadata includedoptionalit would be nice only if i could see if debug metadata is lines vars or source or combination of some of themfound nice tool for viewing class files but that is where i am stuck not sure where to look thank you,['java'] +226174,get bitmap from visible zoomed image android i have an imageview which is zoomed and rotatedi have used multitouch zooming so how can i get bitmap of only visible contenti mean when i zoom the image the part of the bitmap may go out of the screen so what i want is the bitmap that is visible on the screen so is there any built in feature in api to create a small bitmap from a big one or is there any function to crop the image using xy coordinates actually i want the zoomed or rotated part to go to the next activity,['android'] +226203,php mysql select id from one table and information from another table i have two tables one table is called queuelist and the other is call info in the queuelist table it just lists different ids i am trying to get the clientid from that table and match it with the id in the other table that contains all of the info and thisplay it back on the page here is how the tables looktable queuelistid clientid1 5892 2543 486table infoid name phone256 bob 51231234486 jack 51231234589 jill 51231234,"['php', 'mysql']" +226241,how do i get a model from a backbonejs collection by its id in my app everything i do with data is based on the primary key as the data is stored in the database i would like to grab a model from a collection based on this keyusing collectionat requires the array index collectiongetbycid requires the client id that backbone randomly generateswhat is the best way to grab the model i want from the collection with the given id value i figure the worst i could do would be to iterate over each item getid and return that one,['javascript'] +226254,expectedfailure is being counted as an error instead of as passed i am using expectedfailure because there is a bug that i want to record that i cannot fix right now but want to come back to it in the future my understanding of expectedfailure is that it would count the test as passed but in the summary say that there were x number of expected failures similar to how it works with skipped tets however when i run my test suite i get the following managepy test eavquerytestcreating test database for alias defaulterror test q object with exclude eavtestsmanagersquerytest expectedfailureerror test q objects unioned eavtestsmanagersquerytest expectedfailureran 3 tests in 1095sfailed errors2destroying test database for alias defaulti am not sure if this lies with djangos test runner or something i am doing wrongunittestexpectedfailuredef test q object with excludeself everyone except bob q set eav mprocessobjectsexclude qeav details city containsy selfassertequalq setcount 4,['python'] +226265,drag and drop image upload plugin for tinymce i am looking for a tinymce plugin or an external jquery solution easy to integrate into tinymce that allows drag and drop image uploading and insertion in a tinymce textarea either directly dropping the image in the textarea itself or in a defined drop zone something similar to the new media upload button in wordpress or even better without showing any dialogi do not want extra functions like a gallery browser or image repository management already tried several plugins that do that and the customer finds it too tedious and complicated he just wants do drop the image and forget about it as he is not going to use that image ever again,"['javascript', 'jquery']" +226282,gridview rowcommand event not firing i have a gridview that looks something like thisaspgridview idgridview1 allowpagingtrue onrowcommandrowcommand onpageindexchanginggridview pageindexchanging runatserver columns asptemplatefield itemtemplate aspbutton idbutton1 buttontypebutton commandnameitemexport commandargument evalexport textexport runatserver itemtemplate asptemplatefield columns aspgridviewhere is rowcommandprotected void rowcommandobject sender gridviewcommandeventargs e if ecommandname itemexport etc clicking the button is not firing the rowcommand event at all however rowcommand fires when i click a page index in the gridviews pager,"['c#', 'asp.net']" +226290,listbox owerflows when printing from ie when i print a page with a listbox from ie the content owerflows this only happens in ie and it is only the actual print the print preview looks goodheres a code sample doctype html public w3cdtd xhtml 10 transitionalen html xmlns headtitletitlehead body form nameform1 methodpost actionieprinttestaspx idform1 select size4 namelistbox idlistbox option valueitem1item1option option valueitem2item2option option valueitem3item3option option valueitem4item4option option valueitem5item5option option valueitem6item6option option valueitem7item7option option valueitem8item8option option valueitem9item9option option valueitem10item10option option valueitem11item11option option valueitem12item12option option valueitem13item13option option valueitem14item14option option valueitem15item15option option valueitem16item16option option valueitem17item17option select form bodyhtmlthis renders just fine but if i try to print this from ie it will look like thisimage of printdoes anyone know how to fix thisthanks,['html'] +226292,efficiently find the next visible table row with jquery in a table with some rows hidden i want to get the next visible row if one exists this will do the jobrow selectedrownextallvisibleif rowlength 0 selectedrow rowbut it is very slow when many rows follow the selected row a scripted approach isvar row selectedrownextwhile rowlength 0 rowisvisible row rownextif rowlength 0 selectedrow rowthis is much faster but there is got to be an elegant alljquery approach i can use,['jquery'] +226320,what does slash equal in javascript do i was recently reviewing some javascript code in a jquery plugin and came across this line of codeduration 2it appears from other code that the duration variable is a numeric valuecan someone explain exactly what that does with the slash equal,"['javascript', 'jquery']" +226327,hide uisearchbar cancel button i have a uisearchthisplaycontroller and uisearchbar hooked up to my viewcontroller via outlets from my nibi would like to hide the cancel button so that the user never sees it the problem is that the following code hides the button but only after thisplaying it to the user for a millisecond eg it flashes on the simulator and device and then thisappears out of view voidsearchthisplaycontrollerdidbeginsearchuisearchthisplaycontroller controller controllersearchbarshowscancelbutton nois there a better way to hide it,"['objective-c', 'ios']" +226336,alert when new version of ios app is available is there an open source library out there for presenting an inapp alert when a new version is available to download push notification would be a plus also,['ios'] +226339,binding an unsigned long uint64 in an sqlite3 statement c i am using the sqlite3 library that is available at sqliteorgi have some unsigned longs that i would like store in a database i do not want to construct the query myself and leave it open to some sort of injection whether it be accidental or not thus i am using the sqlite bind functions to sanitize my parameters the issue is that there is not a function type for unsigned long integers just integers int sqlite3 bind intsqlite3 stmt int intint sqlite3 bind int64sqlite3 stmt int sqlite3 int64i am definitely going to have numbers that will overflow if i am unable to store them in an unsigned manneram i going to need to manage this myself ie casting to an unsigned type after selecting from the db or casting to signed type before inserting into databaseif i do have to manage this myself how would one do some comparison queries that are stored as a signed long integer when the comparisons are really meant to be in the unsigned rangelooking at the integer datatypes that get converted one would think that unsigned longs could be represented without issueif there are other solutions available please enlighten me thanks,['c++'] +226348,get the page file name from the address bar i was wondering if it would be possible to get the page name from the address bar using jquery or javascript i know this can be done using php but do not really want to as it is only a html website ie if the address is wmywebsitecomhellohtm how do i get the hellohtm part out of the addressthanks for any help you can provide,"['javascript', 'jquery', 'html']" +226356,wcf rest service gaining access to http reponse header i have a self hosted wcf rest service that i am using to simulate a service that i do not have access to yet see json rest service contentencoding gzip i gziped my response but have not found a way to set the contentencoding within the http response header is there a way to get to the http header object so i can set this field,['c#'] +226370,how do you thisable lazy class loadinginitialization in suns jvm by default suns jvm both lazily loads classes and lazily initializes ie calls their clinit methods them consider the following class clinitbomb which throws an exception during a static blockpublic class clinitbomb static explode private static void explode throw new runtimeexceptionboom now consider how to trigger the bombpublic class main public static void mainstring args systemoutprintlna try classfornameclinitbomb catch exception e eprintstacktracesystemout systemoutprintlnb clinitbomb o2 new clinitbomb systemoutprintlnc were guaranteed the explosion happens before point b since fornames documentation says so the question is whether it happens before point a when main is loaded in suns jvm even though main contains a static reference to clinitbomb it happens after ai want a way to tell the jvm to load and initialize clinitbomb as soon as it initializes main so the bomb explodes before point a in general i want a way to say whenever loadinginitializing class x also do so for any classes y it referencesis there a way to do that,['java'] +226384,allow for rangebased for with enum classes i have a recurrent chunk of code where i loop over all the members of an enum classthe for loop that i currently use looks very unwieldly compared to the new rangebased foris there any way to take advantage of new c11 features to cut down on the verbosity for my current for loopcurrent code that i would like to improveenum class color blue red green purple firstblue lastpurpleinline color operator color x return x colorintx 1 int mainint argc char argv any way to improve the next line with rangebased for for color ccolorfirst ccolorlast c do work return 0in other words it would be nice if i could do something likefor const auto c color do work,['c++'] +226435,matlab cannot see some of my java classes not all in jar package i have a problem that is driving me nutsmatlab sees only some of my classes embeded in a jar fileif i compile the classes outside of a package and add the path to the class in matlab using javaaddpath i do not encounter any problemwhen i compile the class in a package and then try to access them under matlab i have problems below some matlab codejavaaddpathusersmedocumentsworkspaceekgtestjarclear javaimport comneuroskythinkgearmethodsekgsensemethods for class comneuroskythinkgearekgsenseekgsense getclass notify reset addtemplate getclassificationresults notifyall tostringequals hashcode processdata wait methodsekgepochno methods for class ekgepoch or no class ekgepochnow i look in the package all of the classes are public this is a result of jar tfosxusersmedocumentsworkspace jar tf ekgtestjarmetainfmanifestmfmetainfrefactoringsxmlcomcomneuroskycomneuroskythinkgearcomneuroskythinkgearekgepochclasscomneuroskythinkgearekgepochjavacomneuroskythinkgearekgparametersclasscomneuroskythinkgearekgparametersjavacomneuroskythinkgearekgtemplateclasscomneuroskythinkgearekgtemplatejavacomneuroskythinkgearmatlabclasscomneuroskythinkgearmatlabjavacomneuroskythinkgearekgsenseclasscomneuroskythinkgearekgsensejavacomneuroskythinkgearthistancearrayclasscomneuroskythinkgearthistancearrayjavaand below of javap classpathosxusersmedocumentsworkspace javap classpath usersmedocumentsworkspaceekgtestjar comneuroskythinkgearekgepochcompiled from ekgepochjavapublic class comneuroskythinkgearekgepoch extends javalangobject implements javalangcloneable public int numberofsamples public float data public comneuroskythinkgearekgepochint public comneuroskythinkgearekgepochint float public comneuroskythinkgearekgepochfloat public comneuroskythinkgearekgepochcomneuroskythinkgearekgepoch public comneuroskythinkgearekgepochorgjsonjsonarray public orgjsonjsonarray tojsonarray public static float convolvefloat float public float getlinenoiseamplitude public comneuroskythinkgearekgepoch subtractcomneuroskythinkgearekgepoch public comneuroskythinkgearekgepoch subepochint int public comneuroskythinkgearekgepoch square public comneuroskythinkgearekgepoch subtractfloat public comneuroskythinkgearekgepoch diff public boolean exceedvaluefloat int int public comneuroskythinkgearekgepoch smoothint public float mean public float sum public float max public float median public comneuroskythinkgearekgepoch clone public comneuroskythinkgearekgepoch sort public int sortindicescomneuroskythinkgearekgepoch public float std public int find heart beatsint float public comneuroskythinkgearekgepoch detrend public javalangobject clone throws javalangclonenotsupportedexceptionosxusersmedocumentsworkspace javap classpath usersmedocumentsworkspaceekgtestjar comneuroskythinkgearekgsensecompiled from ekgsensejavapublic class comneuroskythinkgearekgsense extends javalangobject public comneuroskythinkgearekgparameters params public comneuroskythinkgearekgtemplate templates public comneuroskythinkgearekgtemplate currentdata public int lasttemplateind public float lastepochvalue public comneuroskythinkgearekgsensecomneuroskythinkgearekgparameters public void reset public void addtemplatejavalangstring float public void addtemplatecomneuroskythinkgearekgtemplate public javalangstring getclassificationresults public boolean processdatafloati am running matlab on osx i have tried with matlab 770471 r2008b and 7110584 r2010b and got the same problem both matlab are using the native osx java java 160 26b0338410m3425 with apple inc java hotspottm 64bit server vm mixed mode which should be the same as the one in eclipse i have checked and eclipse compiles with 16remember that i can see the missing class no problem when i remove the package statement and some imports at the top of the java files in all the classes of course and when i simply add the path to the class files not access them in a jar fileany help would be greatly appreciatedthanksjason,['java'] +226438,how to identify html5 is there anyway to determine whether an html file was written in html5,['html'] +226461,integrate mupdf reader in an app i am working on some stuff that should be able to read pdf in my app and i want to put pdf view in my custom layout i had preferred android pdf viewer but when i performed zoomin zoomout it takes too much timeso currently i am supposed to use mupdf open source project to integrate in my project it is based on jni and i am not used to iti am using cygwin to build the library for native code hence i am unclear with few thingshow to integrate the mupdf in my project as per my question titleonce i will succeed to integrated it then how can i put pdf reader in my custom view in the xml or programmaticaly,['android'] +226467,how to plot a gradient color line in matplotlib to state it in a general form i am looking for a way to join several points with a gradient color line using matplotlib and i am not finding it anywhereto be more specific i am plotting a 2d random walk with a one color line but as the points have a relevant sequence i would like to look at the plot and see where the data has moved a gradient colored line would do the trick or a line with gradually changing transparencyi am just trying to improve the vizualization of my data check out this beautiful image produced by the ggplot2 package of r i am looking for the same in matplotlib thanks,['python'] +226491,make a label for a textarea go next to it but aligned in the center vertically please take a look at this fiddle as you can see the label for the textarea id footexttextarea is next to the textarea as it should be however i would like to make the label vertically next to the textarea or at the top of the textarea instead of at the bottom like it is in that fiddlei have tried setting it is css to verticalalign middle but that did not work what must i do to make the label aligned at the top or the middlethanks,['css'] +226493,play framework pdfing a template that uses highcharts js library via a job this is an extension of a previous post i madeto summarize what is going oni am using a job that gets executed hourly that will generate a pdf to send as an attachment in an emailthe job does not do much but call directly onto a controller to generate the pdf and send the email i call a controller to do the work since i am using the pdf module which currently requires an http request as part of its pdf processing here is how i call the controller via the jobwsurlmyurlthatpointstothecontrollergetmy previous issue with pdfing a template that includes a highcharts js chart is that it generated the chart clientside which was too late for the pdf generation and hence my pdf got produced minus the chart to get around this i am now using highchartsserversideexport to generate the chart serversideif i use the same classes above and render the template in the browser ie go via the controller directly and ignore the job the chart gets created server side and the view gets rendered correctly in the browseri am generating the chart in the template by calling another controller like thisimg srcchartgeneratorgothe chartgenerator controller just basically builds the chart serverside as per the highchartsserversideexport documentation and calls plays renderbinary methodas i said the template renders fine in the browser with the serverside generated chart however when going via the job that executes hourly the chartgeneratorgo call does not seem to work the console spits this outinfo chartgeneratorgo is not a url may be relativedoes anyone have any ideas how this can be fixed i have proved that it works minus the job and now need to figure out why when going via the job it does not seem to workedit as per peres suggestion my template now calls the chartgenerator class by doing this note the double s img srcchartgeneratorgoi think that has gotten me a bit further with now this getting spat out in the logserror during job execution funemailjobexecution exception in funemailjobjava around line 19runtimeexception occured javautilconcurrentexecutionexception javautilconcurrenttimeoutexception no response received after 6092354687 warn bad url given httpfull urlchartgeneratorgojavanetsockettimeoutexception read timed outif i hit the url of http full url chartgeneratorgo in the browser the highcharts png file gets rendered in the browser correctly and as expected even after this double change if i render the template in the browser without pdfing the template renders correctly with the serverside generated chartedit 2 with these problems i seem to be having by calling a controller from within a template to render an image binary i am wondering whether it is possible to pass the file object containing the image as a parameter to the render method for the template so for example let us say the controller that renders the template does thisfile image png chart as built by the highchartsserversideexport libraryfile emailattachment new fileattachmentpdfpdfwritepdfemailattachment mytemplatehtml image this calls the pdf module to render the pdf from the given template and write it to the attachmentpdf file objecti am wondering whether i could somehow render that image in the template directly without having to go via the wayi tried putting image in the template but that just rendered attachmentpdf on the screen kinda expectededit 3 here is what the chartgenerator class looks likepublic final class chartgenerator extends controller public static void go throws exception chartoptions options samplesfactorygetsingletoncreatecolumnbasic highchartsexporter pngexporter exporttypepngcreateexporter file chart new filecolumnbasicpng pngexporterexportoptions null chart responsesetcontenttypeifnotsetimagepng renderbinarychart i am currently just generating a sample chart serverside to prove that it can be pdfed the sample chart generation is done as per the highchartsserversideexport documentationedit 4 i also tried adding an action method to the controller to allow pdfing while in the browser and the server side generated highchart also does not appear in the pdf and the previously mentioned exception still occurs so i can rule out it being a problem with the workflow of job to controller of course rendering the template without pdfing still works fineedit 5 to help narrow down the possible causes of the problem i decided to ignore highcharts along with the highchartsserversideexport library and just use the simple server side charting library jfreechart again i can render the template without pdfing but as soon as i try and pdf a template that includes a chart rendered via the aforementioned call it ends up failing for the same reason ie bad url given javanetsockettimeoutexception read timed out,['java'] +226503,escape semicolon character when writing to csv file i want to write something like hyperlink exampleto a commaseparated csv file but excel parses the semicolon and puts example part in another cell i tried escaping the semicolon with backslash and wrapping everything in double quotes without any luckany help,['php'] +226509,how to mock a builder with mockito i have a builderclass builder private string name private string address public builder setnamestring name thisname name return this public builder setaddrestring address thisaddress address return this mocking the builder in mockito will gives me null for every method so is there an easy way to get the builder return itself on every function call without mocking every function itself using whenthenreturn,['java'] +226514,sqlite database maximum storage capacity i have a small question about storing data on a sqlite database how many records in an sqlite database can we maximally store is there any limitation if the data goes beyond this limitation what type of error does it give will the whole the system fail or what else happens,['android'] +226516,audiovideo live streaming between two browsers which technologies i am searching for the best open source technologies to use to implement a bidirectional audiovideo communication between two browsersfor now i have unearthed these trackswebrtc w3c spec and an ericssons implementationred5 and the bigbluebutton implementation as an examplecumulus a red5 implementation of cirrushtml5 and his many new features but not before 20142015 aparentlymaybe some jabberspeex kind of implementation that i am missingis there something i am missing what can be the best solution to use also to be more precise i would like to implement this feature in my application developped using djangopython,"['javascript', 'python']" +226517,threejs how can i dynamically change objects opacity this is my objectvar object new threemesh geometry new threemeshlambertmaterial map threeimageutilsloadtexture imagepng objectpositionset2 3 15now after i have created this object in init function i can directly go to the object and change his positionlike thisobjectpositionx 15now the question is how can i change the opacity of the texturethanks,['javascript'] +226532,how to create a base64encoded string from image resource i have sent a base64 encoded string via ajax to php and created an image resource with imagecreatefromstring all is finenow i want to get the base64 encoded string after resizing te image but i cant find a function to get the base64encoded string,['php'] +226558,tracking the selecting text in android webview in android webview we can able to select the text in web pages after selection finished the toast will appear like text copied to clipboard whether its possible to avoid that toast also i want to call a function after selecting text how can i do thishelp me,['android'] +226568,how do i use jquery to remove all script tags in a string of html suppose i have a string of html code i want to use jquery to remove all script tags from the stringhow can i do thatnote i want to use jquery not regex to do thisdoes this work varfindscriptremove,"['javascript', 'jquery', 'html']" +226586,c dynamically allocated memory i do not quite get the point of dynamically allocated memory and i am hoping you guys can make things clearer for mefirst of all every time we allocate memory we simply get a pointer to that memoryint dynint new intso what is the difference between doing what i did above andint someintint dynint someintas i understand in both cases memory is allocated for an int and we get a pointer to that memory so whats the difference between the two when is one method preferred to the otherfurther more why do i need to free up memory with delete dynintin the first case but not in the second casemy guesses arewhen dynamically allocating memory for an object the object does not get initialized while if you do something like in the second case the object gets initialized if this is the only difference is there a any motivation behind this apart from the fact that dynamically allocating memory is fasterthe reason we do not need to use delete for the second case is because the fact that the object was initialized creates some kind of an automatic destruction routinethose are just guesses would love it if someone corrected me and clarified things for me,['c++'] +226612,how to return a new instance of self from a ruby instance method i have a module which exists to be included in two similar classes some of the methods to be included in the module for identical use by both classes return a new instance but how to i encode in the module that the constructor for the containing class should be calleda simplified examplemodule point3d def initializexyz x x y y z z end def scalar myclassnewx scalar y scalar z scalar endendclass vertex include point3dendclass vector include point3dendso in the definition of how would i call the constructor such that in the context of the vertex class it returned a new vertex and in the context of the vector class it returned a new vector without redeclaring all such methods in each class,['ruby'] +226617,ajax streamlining techniques my question is a bit abstractwere all familiar with ajax preloadersspinners that come up when an ajax request is being made my question is how do you avoid thesetake for example a sortable list when a user drags and drops items to resort them an ajax call is made to update the orderbefore i would pop up a fullscreen ajax spinner to prevent the user from doing anything until the ajax call was completemy question is how would i go about avoiding the ajax spinner and streamlining ajax requests to ensure if a user initiates 20 ajax requests in 2 seconds that they will be executed in orderi do not really need code examples just accepted or popular techniquesideas or if i am going completely off track herethank you,"['javascript', 'jquery']" +226627,javascript how to set request header for a browser get if we do windowlocation browser does a get of the url but if we want to set authentication header of the request before doing get of the url because the server is a rest server and it does not support cookies how to do this in all of the cases i am using ajax to call service but this time i need to show the response in a new window response is a pdf file contentthanks in advance,['javascript'] +226678,maybe kindof monad in python trying to find a way to clean up some of my codeso i have something like this in my python codecompany nonecountry noneperson personfindid12345if person is not none found company companyfindpersoncompanyid if company is not none country countryfindcompanycountryidreturn person company countryhaving read a tutorial on haskells monads in particular maybe i was wondering if it is possible to write in another way,['python'] +226692,ios mobile web app not updating maybe i am missing something obvious sorry buti have a simple jquery mobile web app that when i make a change i upload it to my server i then open it using safari via the url and everything is there all ok if i then make a home screen icon shortcut and open it via the app icon i get an old version ie the version before the change on my devices i have cleared the cache and history and deleted any old home screen icons i check the server version and only the new one is there where is jquery mobile or ios storing the old version and how can i clear it thanks,['ios'] +226737,jquery ajax callback never called javascript code using jquery 17 function getajax dummy function alertfoo with firebug i can see that the http get request is sent and a hello world response with code 200 is returned so everything seems fine but the callback is never called i have no idea what is wrong this should be so simple right,"['javascript', 'jquery']" +226742,c standard io vs unix io basics heres a very basic question i have in my professors lecture slide there is a example i dont really getshe wroteprintfu writestdout fileno m 1 printfdnand she said the out put of this code would bemudi do not get it so if anyone understand why this happens please explain to mereference this question in the second last slide page,['c'] +226789,java dates whats the correct class to use so the whole java datecalendargregoriancalendar thing is obviously a joke whats the right date class to useedit building an sdk for third parties on android where the application needs to provide a datemore edit things that make this so obviously a joke99 of date is deprecateddates year is offset from 1900dates month is zeroindexed while day is oneindexeddates are mutableyoure supposed to use a calendar to create a date except you really have to use a gregoriancalendar do a significant percent of developers want to use a different calendarcalendargettime returns a datethere is no date math like how far apart are two dates in yearsmessing with milliseconds since epoch does not countyou cannot chain parts together to get an expression like the date one year ago todayprobably more stuff,"['java', 'android']" +226793,calculating length in utf8 of java string without actually encoding it does anyone know if the standard java library any version provides a means of calculating the length of the binary encoding of a string specifically utf8 in this case without actually generating the encoded output in other words i am looking for an efficient equivalent of thissome really long stringgetbytesutf8lengthi need to calculate a length prefix for potentially long serialized messages,['java'] +226809,why is the relation between a configurable product and a simple product stored twice deep dive on the magento internals here not looking for a solution to a concrete problem just trying to understand some implementation details when you create a configurable product in magento and then create child simple products to implement things like shirt size color etc magento stores this relationship in two separate tablescatalog product relationcatalog product superlink tablewhy are these relationships stored twice is this legacy code or is there a semantic thistinction between a product relation link and a product superlink link does the system expect these to be the same or is it a valid object state to have these tables representing different parentchild relationships,"['php', 'mysql']" +226815,android intent when my app is installed i need to perform an action when my application is installed i have looked into usingintentpackage addedbut i do not receive the intent in the app that is being installed i want to run code when my app is installed for the first timethe use case is registering with an online service i can listed for boot completed which is fine if the app is already installed but i need to handle the case when the user first installs the appthis postcan you run an intent or script when your app gets installed on androidsuggests listening to timer tick and on the first broadcast perform the registration and set a flag so as not to perform it upon the next timer tick this seems problematic because whether you do something or not in the receiver you are still starting your receiver every single minute and using up battery in the processis there a better solution,['android'] +226829,are there algorithms for computing the bounding rects of sprites drawn on a monochrome background imagine a plain rectangular bitmap of say 1024x768 pixels filled with white there are a few nonoverlapping sprites drawn onto the bitmap circles squares and trianglesis there an algorithm possibly even a c implementation which given the bitmap and the color which is the background color white in the above example yields a list containing the smallest bounding rectangles for each of the spritesheres some sample on the left side you can see a sample bitmap which my code is given together with the information that the background is white on the right side you can see the same image together with the bounding rectangles of the four shapes in red the algorithm i am looking for computes the geometry of these rectangles some painting programs have a similiar feature for selecting shapes they can even compute seemingly arbitrary bounding polygons instead of dragging a selection rectangle manually you can click the background whats background and whats not is determined by some threshold and then the tool automatically computes the shape of the object drawn onto the background i need something like this except that i am perfectly fine if i just have the rectangular bounding areas for objectsi became aware of opencv it appears to be relevant it seems to be a library which includes every graphics algorithm i can think of and then some but in the fast amount of information i could not find the way to the algorithm i am thinking of i would be surprised if opencv could not do this but i fear youve got to have a phd to use it,['c++'] +226840,why can template instances not be deduced in stdreference wrappers suppose i have some object of type t and i want to put it into a reference wrapperint a 5 b 7stdreference wrapperint pa qb or auto p stdrefanow i can readily say if p q because the reference wrapper has a conversion to its wrapped type all is happy and i can process a collection of reference wrappers just like they were the original objectsas the question linked below shows this can be a useful way to produce an alternate view of an existing collection which can be rearranged at will without incurring the cost of a full copy as well as maintaining update integrity with the original collectionhowever with some classes this does not workstdstring s1 hello s2 worldstdreference wrapperstdstring t1s1 t2s2return t1 t2 errormy workaround is to define a predicate as in this answer but my question iswhy and when can operators be applied to reference wrappers and transparently use the operators of the wrapped types why does it fail for stdstring what has it got to do with the fact that stdstring is a template instance update in the light of the answers it seems that using stdlesst is a general solution,['c++'] +226868,how to compile the code using include i am trying to compile some c code that uses threadsinclude iostreaminclude threadvoid hello stdcouthello concurrent worldnint mainint argc tchar argv stdthread thello tjoin return 0i get errors when compilingctempapp1app1app1cpp6 fatal error c1083 cannot open include file thread no such file or directorydocumentsc g o thread1 thread1cpp d reentrant lpthreadin file included from usrincludec45thread350 from thread1cpp2usrincludec45bitsc0x warningh312 error error this file requires compiler and library support for the upcoming iso c standard c0x this support is currently experimental and must be enabled with the stdc0x or stdgnu0x compiler optionshow do i fix these errors,['c++'] +226869,marshal dumps faster cpickle loads faster i am implementing a program that needs to serialize and deserialize large objects so i was making some tests with pickle cpickle and marshal modules to choose the best module along the way i found something very interestingi am using dumps and then loads for each module on a list of dicts tuples ints float and stringsthis is the output of my benchmarkdumping a list of length 7340032pickle 14675 secondslength of pickle serialized string 31457430cpickle 2619 secondslength of cpickle serialized string 31457457marshal 0991 secondslength of marshal serialized string 117440540loading a list of length 7340032pickle 13768 secondssame length 7340032 7340032cpickle 2038 secondssame length 7340032 7340032marshal 6378 secondssame length 7340032 7340032so from these results we can see that marshal was extremely fast in the dumping part of the benchmark148x times faster than pickle and 26x times faster than cpicklebut for my big surprise marshal was by far slower than cpickle in the loading part22x times faster than pickle but 31x times slower than cpickleand as for ram marshal performance while loading was also very inefficienti am guessing the reason why loading with marshal is so slow is somehow related with the length of the its serialized string much longer than pickle and cpicklewhy marshal dumps faster and loads slowerwhy marshal serialized string is so longwhy marshals loading is so inefficient in ramis there a way to improve marshals loading performanceis there a way to merge marshal fast dumping with cpickle fast loading,['python'] +226897,friend declaration of template specialization fails the following code containing friend declaration fails with indicated error see templateclass t void foo templatetypename tclass a void foo friend void foot error variable or field foo declared voidint main foointif the order of friend declaration and member function declaration reversed then the code compiles without problems see templateclass t void foo templatetypename tclass a friend void foot void fooint main foointthis does not happen if the friend declaration does not contain template specialization nontemplate friends are ok as well as a template friends also using qualified name in template specialization allows code to compilemy question is why does the first example fail it seems compiler looking up names in class scope at the point of friend declaration and only for template specialization where in the standard this behavior is specified,['c++'] +226908,c pointer arithmetic sizeofstruct here is the code in questioninclude stdiohstruct test unsigned char t unsigned short u unsigned char vint main struct test a void 0x10 printfx p pn sizeofstruct test a sizeofstruct test a sizeofstruct test return 0the sizeofstruct test prints 6 so i would expect to see6 0xffa 0x1006instead i get6 0x1024 0xfdclast time i checked 0x24 or 36 was not equal to 6 it is not even aligned to anything that i can tell i am at a complete losscan someone please explain to me why i am getting these values,['c'] +226920,linq different syntax style different result can someone tell me the difference the following two linq statements pleasevar chkunique dbbusinessfilefirstordefaultc crocno txtboxidtextandvar chkunique from c in dbbusinessfile where crocno stringtxtboxidtext select cchkunique null returns false for the top one when a match cannot be found and true for the latter and i cannot figure out why this is happeningi am new to linq so i could have missed something really basic but its driving me nuts at the moment,['c#'] +226956,clientside validation of input type date does not work i have a form containing a date and datetime fieldhtmltextboxformodel modela new type datetime htmltextboxformodel modelb new type date modelpublic class testmodel datatypedatatypedate public datetime a getset datatypedatatypedate public datetime b getsetby using these input types an ipad shows nice datetime pickers the fields are validated using clientside validation for the datetime field a it works but the date field b will raise an error please enter a valid date how do i solve thisexamplesthis ipad safari value for datetime is valid according to mvc clientside validation 15 dec 2011 920this ipad safari value for date is invalid 15 dec 2011it is hard to debug code on an ipad so i have no clue how safari changes the date format when setting the inputs value attributeediti thiscovered the datetime format is universal datetime format ymmddthhmmz while the date format is ymmdd probably the clientside validator does understands universal datetime and not ymmdd due to localization,['c#'] +226980,how to get text from textview if i have set text in textview in such way which is not problem tvsettext ansithis simply getting from this way string a tvgettexttostring int a integerparseintabut in case of setting value in textview tv1settext xi n yiwhich is like this 5 9i have problem this value how to get,['android'] +226981,how to find out a specific character is present in a nsstring or not i have two nsstrings named country and searchtext i need to check whether the country contains the searchtexteg country iceland and searchtext c here the word iceland contains the character cthanks,['ios'] +227007,jquery animate from css top to bottom i am looking to animate a div element from an absolute top position to an absolute bottom position on the page loadthe combination of css and jquery code below fails to move anythingcsslinethree positionabsolute width100 left0px top113pxjquery linethreeanimate bottom 100px 1200thank you for your helpediti have tried changing it to this as per graphicdevines suggestions but still no cigarvar footeroffsettop linethreeoffsetbottom linethreecsspositionabsolutetopbottomfooteroffsettop linethreedelay100animate bottom 100px 1200,"['jquery', 'css']" +227025,how to stop an html textarea from decoding html entities i have a strange problemin the database i have a literal ampersand lt semicolon ltdiv whenever its printed into a html textarea tag the source code of the page shows the gt as how do i stop this decoding,['html'] +227028,how to check if string has a correct html syntax i would like to check if a given string has a correct html syntax i do not know which html elements should be inside the only one thing i know is that string should be a correct html expression anyone has an idea how to check it in c,"['c#', 'html']" +227036,mysql ddl trigger diff table schema for column rename i am creating a php script to compare schema of two databasesi have managed to check for schema changes with regard to droppedadded tables columns indexes references but when it comes to renamed columns i am a bit stuckin the following example the source database contains the most up to date schema and the destination database contains similar schema but is likely out of dateprerequisitesi am not aware of changes which have occurred since the last diffthe data in the databases will not match but the schema should after the difftake for example the following schema in the destination databasefield type null key default extrafield1 int11 no null field2 int11 no null field3 int11 no null and then assume the following schema in the source databasefield type null key default extrafield1 int11 no null field4 int11 no null field3 int11 no null without knowing explicitly what occurred i am unable to determine whether or not field2 changed to field4 by way of drop add after or change column the following two queries achieve the same result in terms of table structure but the data is lost using the former1 alter table demo drop field2 alter table demo add field4 int 11 not null after field1 2 alter table demo change field2 field4 int 11 not null i can obviously drop the old column name and create a new one but that then loses any data in the original column i need to use an alter table table change column field new name structure query rather than drop column from table followed by alter table table add column definitioni was hoping that i could use a ddl trigger to track changes in schema and insert a record of such changes into a table in the source database i could later query this table to determine how a certain column came to be however as far as i can tell it is not possible to run triggers on ddl queries in mysql which rules out logging these changes i had a read of this worklog wl2418 ddl triggers on mysql forge now residing in mysql developer zone but it appears to be pending implementation still unfortunatelyis there a way in which i can update tables to match a schema with regard to renamed columns without data lossi have looked at things like mysqldiff but it needs to be built into an existing bit of code so i am having to build it myselfideas i have consideredadd a comment to each column which is a unique number or string call it a hash for the sake of argument query the information schema table to retrieve this value and compare it on each column if it is unique then it is a new column or if it matches a hash but not a name or structure then it is been renamedreconfiguredcompare the schema if there is a new column check it is position with regard to adjacent columns if the name of the new column is in the same position as one which is missing compare the structure of that column if it matches consider it renamed if not consider it deleted then added,"['php', 'mysql']" +227053,eclipse compilation error the hierarchy of the type class name is inconsistent i have downloaded some open source software written in java and tried to compile it using eclipsei got the error the hierarchy of the type class name is inconsistent in some fileswhat causes these errors and how do i fix them,['java'] +227058,opencv cvfindhomography runtime error i am using to compile and run code from features2d homography to find a known object tutorial and i am getting thisopencv error assertion failed npoints 0 points2checkvector2 npoints points1type points2type in unknown function file cusersvpworkocvopencvmodulescalib3dsrcfundamcpp line 1062runtime error after debugging i find that the program is crashing at findhomography functionunhandled exception at 0x760ab727 in opencvtemplatematchexe microsoft c exception cvexception at memory location 0x0029eb3cin the introduction of opencv the cv namespace chapter says that some of the current or future opencv external names may conflict with stl or other libraries in this case use explicit namespace specifiers to resolve the name conflictsi changed my code and use everywhere explicit namespace specifiers but problem did not solved if you can please help me in this problem or say which function do same thing as findhomography and do not crash programand this is my codeinclude stdiohinclude iostreaminclude opencv2corecorehppinclude opencv2features2dfeatures2dhppinclude opencv2highguihighguihppinclude opencv2calib3dcalib3dhppvoid readme function main int main int argc char argv if argc 3 readme return 1 cvmat img object cvimread argv1 cv load image grayscale cvmat img scene cvimread argv2 cv load image grayscale if img objectdata img scenedata stdcout error reading images stdendl return 1 step 1 detect the keypoints using surf detector int minhessian 400 cvsurffeaturedetector detector minhessian stdvectorcvkeypoint keypoints object keypoints scene detectordetect img object keypoints object detectordetect img scene keypoints scene step 2 calculate descriptors feature vectors cvsurfdescriptorextractor extractor cvmat descriptors object descriptors scene extractorcompute img object keypoints object descriptors object extractorcompute img scene keypoints scene descriptors scene step 3 matching descriptor vectors using flann matcher cvflannbasedmatcher matcher stdvector cvdmatch matches matchermatch descriptors object descriptors scene matches double max thist 0 double min thist 100 quick calculation of max and min thistances between keypoints for int i 0 i descriptors objectrows i double thist matchesithistance if thist min thist min thist thist if thist max thist max thist thist printf max thist f n max thist printf min thist f n min thist draw only good matches ie whose thistance is less than 3min thist stdvector cvdmatch good matches for int i 0 i descriptors objectrows i if matchesithistance 3min thist good matchespush back matchesi cvmat img matches cvdrawmatches img object keypoints object img scene keypoints scene good matches img matches cvscalarall1 cvscalarall1 stdvectorchar cvdrawmatchesflagsnot draw single points localize the object stdvectorcvpoint2f obj stdvectorcvpoint2f scene for int i 0 i good matchessize i get the keypoints from the good matches objpush back keypoints object good matchesiqueryidx pt scenepush back keypoints scene good matchesitrainidx pt cvmat h cvfindhomography obj scene cv ransac get the corners from the image 1 the object to be detected stdvectorcvpoint2f obj corners4 obj corners0 cvpoint00 obj corners1 cvpoint img objectcols 0 obj corners2 cvpoint img objectcols img objectrows obj corners3 cvpoint 0 img objectrows stdvectorcvpoint2f scene corners4 cvperspectivetransform obj corners scene corners h draw lines between the corners the mapped object in the scene image 2 cvline img matches scene corners0 cvpoint2f img objectcols 0 scene corners1 cvpoint2f img objectcols 0 cvscalar0 255 0 4 cvline img matches scene corners1 cvpoint2f img objectcols 0 scene corners2 cvpoint2f img objectcols 0 cvscalar 0 255 0 4 cvline img matches scene corners2 cvpoint2f img objectcols 0 scene corners3 cvpoint2f img objectcols 0 cvscalar 0 255 0 4 cvline img matches scene corners3 cvpoint2f img objectcols 0 scene corners0 cvpoint2f img objectcols 0 cvscalar 0 255 0 4 show detected matches cvimshow good matches object detection img matches cvwaitkey0 return 0 function readme void readme stdcout usage surf descriptor img1 img2 stdendl,['c++'] +227061,ignore views in mysql db backup using mysqldump i need to ignore all view in my database and take backup using mysqldump currently i am using below optionignoretableview1 ignoretableview2 ignoretableview3is there any way to take backup omitting all views without specifying all view names,['mysql'] +227068,python pdb debugger thisp equivalent is there a pdb equivalent to thisp in gdbeg when i am debugging c using gdb i can have variables printed on every step through the code by typingthisp varwhen i am debugging python using pdb i would like similar functionality but thisp does not seem to be there the python pdb documentation does not seem to offer an alternative but it seems like an odd omission,['python'] +227069,get a file name from a path what is the simplest way to get the file name that from a path string filename cmydirectorymyfilebatin this example i should get myfile without extension,['c++'] +227074,jquery fire function on all class elements i want to execute some function on all class elements how can i do thatwhat i want is something like i want to fire my function on all class elementsmyclassgofunction my function using this objecti know this is a dumb question i used to work on propotype for some time and now i do not remember proper function for jquery,"['javascript', 'jquery']" +227087,cannot add an image to a pdf using pdfbox i am writing a java app that creates a pdf from scratch using the pdfbox libraryi need to place a jpg image in one of the pagei am using this codepddocument document new pddocumentpdpage page new pdpagepdpagepage size a4documentaddpagepage pdpagecontentstream contentstream new pdpagecontentstreamdocument page code to add some text to the page inputstream in new fileinputstreamnew filecmyimgjpgpdjpeg img new pdjpegdocument incontentstreamdrawimageimg 100 700contentstreamclosedocumentsavecmydocpdfwhen i run the code it terminates successfully but if i open the generated pdf file using acrobat reader the page is completely white and the image is not placed in itthe text instead is correctly placed in the pageany hint on how to put my image in the pdf,['java'] +227096,storing kerberos authentication for later impersonation is it possible to store a kerberos ticket to later use it to impersonate the user i have the scenario where a user directly invokes an external system to process some data the external system relies on the user being impersonatedauthenticated correctly in the ad now the calling system has to change so that a queue sits between the user and the external system and work from the queue is handed over to the external system from that queue by a windows servicethis service needs to impersonate the user in order for the external system to correctly handle userrightsgiven that i cannot change the external system and can not store the username and password in the queue can i save a kerberos ticket when the user adds new work items to the queue and later impersonate the user by the service when it hands over the data to the external system how would i do that in c,"['c#', '.net']" +227102,the variable variable name is either undeclared or was never assigned i have a question related to the error on the title im working with c and visual studio 2010i have a form declared as public class formulariogeneral form which is the base for the rest of the forms in my application when i try to access the designer view i get this error several times as you can see in the imageall the errors references lines inside the initializecomponent method where the value is assigned to a property like this one thispanelmargenizquierdocapabasebackcolor m colorcapabasebut all the variables are declared in the same class as readonly properties and all of them are assigned inside a method which is called in the constructordeclaration of properties protected color m variablename public color variablename get return m variablename set constructor code public formulariogeneral configurarui accionesconstructor initializecomponent postinicializacioncomponentes establecericono inicializarlocalizacionformulario configurarui methodpublic virtual void configurarui m altobordesuperiorcapabase 30 m altobordeinferiorcapabase 7 m anchobordeslateralescapabase 7 m colorcapabase colorfromargb50 100 150 m colortextocapabase colorwhite m colortextobotonaplicacion colorblack m fuentetextoizquierdocapabase new systemdrawingfontverdana 110f systemdrawingfontstyleregular systemdrawinggraphicsunitpoint byte0 m fuentetextocentrocapabase new systemdrawingfontverdana 140f systemdrawingfontstylebold systemdrawinggraphicsunitpoint byte0 so as far as i know all the variable which are giving the errors are correctly declared and have a value assigned before the initilizecomponent function is calledim stuck at this point and dont know what to do to solve the problem hope some of you can help me with this issue dthank you all t,"['c#', '.net']" +227125,infinity vs numberpositive infinity i understand that numberpositive infinity has a value of infinity and numbernegative infinity has a value of infinityis there a reason i would use numberpositive infinity instead of infinity or numbernegative infinity instead of infinityon a related note are there any crossbrowser issues with isfinite,['javascript'] +227136,is the state of any standard class after being moved specified if i move shared ptr a into shared ptr b is a guaranteed to be nullis the state of any standard class after being moved specified,['c++'] +227152,javascript get current filescript path how can i get the path of the current script in javascript using jqueryfor example i have sitecomjsscriptjs and there is a code in this scriptdocumentreadyfunction alert this code it should return alert box with the jsscriptjs message this function should work like magic file constant in phpso why do i need thisi want to set background image dynamically somedivcssbackgroundimage url script path imagesimgpngand images directory is the js directory near the scriptjs fileand js folders name can be dynamically set so script and images can be in the myprogectjavascriptfiles directory,"['javascript', 'jquery']" +227155,programming p2p application i am writing a custom p2p program that runs on port 4900 in some cases when the person is behind a router this port is not accessible from the internet is there an automatic way of enabling the access to the port from the internet i am not really sure of how other p2p applications work can anyone please throw some light on this,"['c#', '.net']" +227163,which linux cc soap library need very lightweight recommendations i need to do just one soap over http request in an application no other transports than http i will just to the request and crunch the response due to it being just one request i do not really need something that has a c code generator from wsdl just some api to build the request withthis will be on a cpu and memory constrained system arm also generally crippled in the support libraries departmenti can do plain c or c i have some kind of also crippled stl but not much else and i would rather not add too many megabytes of librariesi have libxml2 not sure if it has any connection but i am a soap noob on my target platformneeds to compile on gcclinux of course i can handle any x86arm transition odditiesgsoap is out of the question because of licensing and hugenesome googling led me to but i would like to hear if there are any alternatives before i dive inso any other sugesstions from fellow so members thank yousimplesoap does not compile with a modern gcc example error taking address of temporary fpermissive i can probably fix that but not for one requestso manual it is,['c++'] +227172,jquery add row before fourth to last row i have an invoice table the last four rows are as follows starting from last grand total tax subtotal add a line linkso i need to add a row before the add a link link row this thread add table row in jquery shows how to add a row after the last row i just need to modify it to add a row before the fourth to last row,"['javascript', 'jquery']" +227189,ios stop a nstimer possible duplicatenstimer doesnt stop i have this codenstimer scheduledtimerwithtimeinterval1100 targetself selectorselectortargetmethod userinfonil repeatsyes void targetmethodnstimer timernsloghello worldin targetmethod i can stop timer with timer invalidate but out of this method how can i stop targetmethod,['ios'] +227190,is hover only limited to child elements i just saw this code in an answerhtmldiv classthumbnail img src img classoverthumb srcdivcssoverthumb thisplay none thumbnailhover overthumb position absolute top 15px left 15px thisplay inlinelive demo here for this code to work overthumb must be a child of thumbnailbut if some one has this codediv classthumbnail img srcdivptphow would you select the p tag if thumbnail is hovered,['css'] +227206,converting exe project to class library i have a semilarge c exe project in visual studio 2010 ultimate and i would like to convert it to a dll class library is there an easy way to do this that does not involve creating a new class library project thanks beforehand,['c#'] +227242,generate password using a for loop i am making a password generator that generates a random number then i have it converted to a letter using ascii inside the for loop i need the letters to convert a string instead of a list it works but it just thisplays random letters as a list using systemusing systemcollectionsgenericusing systemlinqusing systemtextusing systemthreadingclass mainclass static void main int x 1 int length string a press any key to continue object num while x 1 consolewritelinehow many characters would you like the password to be press 1 to stop length converttoint32consolereadline try for int i 0 i length i int num1 number int32 ascii num1 num charnum1 if length 0 consolewritelinenum catch consolewritelinea if length 1 break static random r new random static int number return rnext65 90 decimal,['c#'] +227247,is aspnet mvc stateless i have heard that mvc net is stateless what are the implications of this and why is it that mvc is stateless,['c#'] +227271,free java data visualization library i am looking for a free java library to visualize some data i want to do something similar as the following two images is there any possibility i first thought of prefuse but this is not developed since 2007 so any oher libraries,['java'] +227324,what is the advantage of using memset in c i was curious as to whether or not there was any advantage in regards to efficiency to utilizing memset in a situation similar to the one belowgiven the following buffer declarationsstruct more buffer info unsigned char a10 unsigned char b10 unsigned char c10struct my buffer type struct more buffer info buffer info100struct my buffer type my buffer5unsigned char pp unsigned char my bufferbesides having less lines of code is there an advantage to using thismemsetvoid p 0 sizeofmy bufferover thisfor i 0 i sizeofmy buffer i p 0,['c'] +227335,radio button styling i want to style radio buttons with pure css no classes or ids just inputtyperadioi want to use a background image for unselected and selectedhowever the vendorappearancenone does not work with trident or gecko just webkitin those browsers you can see the background image as a background to the radio button but the button is still there rather than just thisplaying the image how can i get rid of the button so just the background image thisplays the fiddle,['css'] +227337,enabling the photo library button on the uiimagepickercontroller does anyone know how to enable the photo album button on the uiimagepickercontroller when its in the camera mode like how the camera app on on the iphone can toggle between image and video taking and also has the button to view the photo library,['ios'] +227340,changing development team in itunes connect i am a member of two apple development programs and i am trying to upload a new app the problem is that every time i log in to itunesconnect it logs me in to one team and i cannot find a way to switch teams i have tried logging in on developerapplecom first and choosing the correct team but as soon as i go to itunesconnect it relogs me in to the wrong teamis there any way to change teams on itunesconnect i have tried this in safari chrome and firefox and i have cleared my history and cachethanks,['iphone'] +227342,remove portion of string in javascript i have a string like this in javascriptstring usernamewhats on your mindi need to get rid of whats on your mind from the stringhow would i do that,['javascript'] +227349,is there a quiet version of subprocesscall is there a variant of subprocesscall that can run the command without printing to standard out or a way to block out it is standard out messages,['python'] +227350,how to show twitter bootstrap modal via js request in rails i want to show a twitter bootstrap modal as a response to a js request my showjserb function looks something like thisdocumentreadyfunction dialogmodalshowhere dialog is the modals id the modal code itself looks something like thisdiv iddialog classmodal hide fade div classmodalheader a href classclosetimesa h3 showing modal h3 div div classmodalbody i need to show up div div classmodalfooter a href classbtn primarydonea divdivone thing i am sure of is that the javascript is being called i can have it alter items on the page another thing is that modal is working fine it shows up just fine when i use an html button to trigger the request like thisbutton datacontrolsmodaldialog databackdroptrue datakeyboardtrue classbtn danger show buttonany idea why the modal does not show up on js request thank you,"['javascript', 'ruby-on-rails']" +227369,what is a void pointer in c possible duplicatewhat is a void pointer and what is a null pointer i often see code which resembles something like the followingvoid fooint barwhat does this mean does it mean that it can return anything is this similar to dynamic or object in c,['c++'] +227372,most pythonic way to split an array by repeating elements i have a list of items that i want to split based on a delimiter i want all delimiters to be removed and the list to be split when a delimiter occurs twice for example if the delimiter is x then the following lista b x x c d x x f x gwould turn intoa b c d f gnotice that the last set is not spliti have written some ugly code that does this but i am sure there is something nicer extra points if you can set an arbitrary length delimiter ie split the list after seeing and delimiters,['python'] +227419,wifi lock does not work how to prevent wifi power save i had done an app that transform the phone into a webcam and use the phone connection to send image to internet web space i am using ad activity that set an alarm manager to execute a service every 5 or 15 minutesto perform the entire execution of the service i do a wake lock but it is dropped when service finischedall this works perfect with mobile connection but does not do the same with wifii had set in wifi options th policy never for wifi sleepbut after a time not always the same the phone seems to go on power save mode wifi icon is yet on status bar but the phone is not able to connect even is i use browserso i must thisconnect and manually reconnect the message in the logcat notify conn break ioex close connectioneven with phone plugged on powerwhy 1doing experiment with another app formed by an activity that start a service always running with a wake lock so i have added the wifi lock to be sure of connectivity but also this method sometimes runs and some other not always the same notify conn break ioex close connection why 2the last experiment is derived from the first app alarm manager and to be sure that the wifi does not go on sleeppower save mode witch one i have turn the phone in airplane mode after the execution of the code and i turn it off connection on when the cycle begin this work ok for two days but after only sometimes it is work each hour or two instead each 5 minutes or sometimes does not work for an entire day and then restart without any reason so why airplane mode sometimes does not reestablish the prewious wifi connection and some other times it does 3the phone is a samsung galaxy ace with originale 22 and is always plugged to charge,['android'] +227448,how do you run javascript script through the terminal for instance if you were to run a python script you would type python filenamepy or if you wanted to run a c program make filename then filename how do you do this with js files,['javascript'] +227449,gson custom object deserialization ok so i edited the question because it was not clear enoughedit 2 updated the json filei am using gson in an android app and i need to parse json files that come from a server and are a little too complexes i do not want to have my object structure too heavy so i would like to simplify the contents so the structure of my object would not be the structure of the json file for example if in the json i have this object1 attribute1 test1 attribute40 test40 user id1 namefoo example total10 list tagtag1 nameobject name 1 pos1 tagtag10 nameobject name 10 pos10 object2 attribute1test i do not want to keep in my current object structure an object example that contains an arraylist and an int total but i would like to keep only a simple string with the value object name 1object name 2 moreover i would like to store only the user id not the complete user because i already have the complete user stored somewhere else with an other server api callso my class class would be something like class foo int userid string example object name 1object name 2 so i suppose that we can achieve this with a custom deserializer but i do not find how i would like if possible to minimize the memory so i do not think that having a full object example and then use it to build my string example is a correct way in the worst case if it is too complicated i would like to be able to store at least only the list of tag items when i parse the example object so i need a custom deserializer to get rid off the int total so i would have class foo int userid arraylisttag example,"['java', 'android']" +227460,how to retrieve array of objects as a result from ksoap web service in android if i am trying to retrieve first array using string responsegetproperty0 but it was returning me a full stringhere is the code of webservice callingpublic static object getresponsestring methodname string actionname linkedhashmapstring string valuestrings soapobject soapobject new soapobjectletusclickapiconstantscommon namespace methodname object response null for mapentrystring string mapkeys valuestringsentryset soapobjectaddpropertymapkeysgetkey mapkeysgetvalue final soapserializationenvelope envelope new soapserializationenvelopesoapenvelopever11 envelopedotnet false envelopesetoutputsoapobjectsoapobject final androidhttptransport androidhttptransport new androidhttptransportletusclickapiconstantscommon url try androidhttptransportcallactionname envelope response envelopegetresponse logdresponse responsetostring catch final ioexception e logdexception e catch final xmlpullparserexception e logdexception e return responsei got an response in vector typeclientuserid93 nicknameladies clientuserid94 nicknameabcd i have tried many ways but i am not success to retrieve in any way,['android'] +227464,undefined function sha256 i have this php codepassword sha256 postpasswordbut when i run this code it saysfatal error call to undefined function sha256 in on line ix it as what is wrong with this code and what must i do to fix this as i know that sha256 existsi have also triedpassword sha256trim postpasswordbut that does not work either,['php'] +227471,properly accessing a segues destination view controller to assign protocol delegates i am encountering some problems in integrating segue and protocols while implementing a selection listin my selection list h i haveimport uikituikithprotocol selectionlistviewcontrollerdelegate nsobjectrequired voidrowchosennsintegerrowendinterface selectcolor uitableviewcontroller nsfetchedresultscontrollerdelegateibactionsaveselectedcolorproperty nonatomic strong id selectionlistviewcontrollerdelegate delegateendin my selection list m i haveimplementation selectcolorisynthesize delegatethis method is called from a button on uiibactionsaveselectedcolore selfdelegate rowchosenlastindexpath row selfnavigationcontroller popviewcontrolleranimatedyesi would like to access to this selection list view by performing a segue from another table viewimplementation tablelist voidselectnewcolor selectcolor selectcontroller selectcolor alloc init selectcontrollerdelegate idself selfnavigationcontroller pushviewcontrollerselectcontroller animatedyes execute segue programmatically self performseguewithidentifier selectcolorsegue sender self voidrowchosennsintegerrow uialertview erroralert uialertview alloc initwithtitleerror title messageerror text delegateself cancelbuttontitleok otherbuttontitlesnil erroralert showif i navigate to the selection list using selfnavigationcontroller pushviewcontrollerselectcontroller animatedyesthe alert is thisplayed if i instead useself performseguewithidentifier selectcolorsegue sender selfno alert is thisplayed because i think i do not pass to the destination selection list the selectcontroller any ideas to solve this issue please,['ios'] +227475,net framework 4 installation in silent mode can anyone explain how to make silent without any user interface install of net 4 it looks like net installer ignores any switches from this article and show interface alwaysnet framework 4 installer is packed by nsis,['.net'] +227521,linking libraries with incompatible dependecies i am working on a c project that needs two third party libraries libfooso and libbarso my operating system is linuxlibfooso is dynamically linked to libpng14so14 148 edit 1libbarso seems to be statically linked to an unknwon version of libpng libpng 128 edit 1i say seems to be becauseldd libbarso does not show nothing about pngnm d libbarso grep png read png says 004f41b0 t png read pngless libbarso grep png read png says 4577 004f41b0 738 func global default 10 png read pngwhen i start my program it abortterminate called after throwing an instance of char constthis is gdb backtrace0 0xb7ffd424 in kernel vsyscall 1 0xb5e776a1 in raise from liblibcso62 0xb5e78de2 in abort from liblibcso63 0xb60a997f in gnu cxx verbose terminate handler from usrlibgcci686pclinuxgnu445libstdcso64 0xb60a78a5 in from usrlibgcci686pclinuxgnu445libstdcso65 0xb60a78e2 in stdterminate from usrlibgcci686pclinuxgnu445libstdcso66 0xb60a7a21 in cxa throw from usrlibgcci686pclinuxgnu445libstdcso67 0xb5abf76d in from usrliblibfreeimageso38 0xb6fb9346 in png error from liblibfsdkso9 0xb6fa2a59 in png create read struct 2 from liblibfsdkso10 0xb6fa2b7a in png create read struct from liblibfsdkso11 0xb5abfa44 in from usrliblibfooso12 0xb5aa766b in freeimage loadfromhandle from usrliblibfreeimageso313 0xb5aa59f6 in freeimage loadfrommemory from usrliblibfreeimageso314 0xb68a94a5 in fooimageload this0xb4eff560 inputas you can see exception is thrown in fooimageload which belong to libfoosothisabling the part of my code that uses libbarso and removing linking to it fooimageload does not throw any exception and works fine so i guess it can be due to some ambiguity in symbol table how can i fix itedit 1png access version numberwith libbarso linked png access version number return 10208 version 128without libbarso linked png access version number return 10408 version 148,['c++'] +227535,uitextfield textrectforbounds vs editingrectforbounds whats the difference between a uitextfields rectangle for its text vs editable texti just want to move where the text is thisplayed inside the text field should i just override both methods with the same exact implementationuitextfield class referencetextrectforboundsreturns the drawing rectangle for the text fieldas texteditingrectforboundsreturns the rectangle in which editable text can be thisplayed,['ios'] +227537,drupal login via rest server i am developing a website who uses an external drupal for the articles and pagesthe purpose is to show the articles in a website using just htmlcssjsi have added an rest server module to the drupal backend so i can do http requests for retreiving the articles now retreiving the articles from the drupal backend works see code below restdrupal is the name of my site and restendpoint is the name of the rest servers endpoint captian obviousajax url datatype json success functiondata further code now i want my customer to be able to add some articles so i need to login firsti have been searching the internet for days now and tried a million things but nothing worked for me the latest thing i have tried with jquery was this ajax url datatypeapplicationjson type put data namemyusernamepassmypassword success functiondata further code errorfunctiondata error handling i have also changed the put into postthe response i am getting is no mather what i do the same 406 not acceptable unsupported request content type applicationxwformurlencodedcould please somebody help mekind regardsceetn,['jquery'] +227557,backgroundcolorspan with additional vertical padding in my app i have something similar in appearance to labels in gmail app ui for those who may not know they look like this labels are these colorful bars in order to achieve similar effect i use ninepatch drawables for each label i am creating a textview and assign drawable to it this is simple solution but i do not like it it is not elegant it is quite slow as shown by profiler and i just do not think it is the right way to do iti changed the design of the ui to make it more icsy so i removed rounded corners from the labels and i started thinking how i could replace 9patch solution the most obvious thing is to use backgroundcolorspan but it has one small drawback i want my labels to have some padding with drawables it was easy to achieve with spans it is harder to make horizontal padding i can just add spaces at the beginning and at the end of the string but how to make vertical padding larger to clear things up this is a screenshot of the label with backgroundcolorspani want to make the colored parts above and below the text larger i think i should use some kind of metricaffectingspan but i could not figure out which one or maybe i should write my own or finally maybe spans are just not able to fulfill my needs and i should stay with images or create a canvas and manually draw everything as in gmail app,['android'] +227583,java the meaning of the full context beingpublic class rclasst extends comparabletwould i be right in saying that the statement in the title means that the arguments plugged into the method must either be an object of a class which implements comparable or one of its derived classesthanks,['java'] +227606,php new line every x characters in long characters sequence how can i add a new line characters nr in txt file every 10 characterswhat i have is a long sequence of characters and i like to create a new line for each 10 charactersin example let us say i have that sequence of charactersfade4fh73d4f3fab5fnf4fbtkhus591f60b55hseand i like to convert it to thatfade4fh73d4f3fab5fnf4fbtkhus591f60b55hsehow can i do that i know that i can use a loop for that but because the above string is an example and my string that i have to split it is really very very long just i wander if there is any faster and more easy way to spit my string,['php'] +227623,how to post data to a website i need to post data to a website so i created a small app in cnet where i open this website and fill in all the controls radio buttons text boxes checkboxes etc with the values from my database i also have a click event on the submit button the app then waits for 1015 seconds and then copies the response from the webpage to my databaseas you can see this is really a hectic process if there are thousands of records to upload this app takes much longer due to fact that it waits 15s for the response is there any other way to post data i am looking for something like concatenating all the fields with its value and uploading it like a stream of data how will this work if the website is https and not http,['c#'] +227632,hide line beginning and end text separators two solutions below one with pure css the second with jquery allowing any kind of symbolimage to be a separatorpre fairly hard to formulate and find such questionssolutions so i am sorry if duplicatingi have a multiline justified block with randomnot entirely text hyperlink elements tagscategoriesetc without fixed width separated by symbol and spaces around looks pretty much like a tag cloud but with a fixed fontweight size and other formatting can contain more than one word in a hyperlink element the problem rises when a separator is placed just before the end of the line or at the beginning of the line actually it happens always one way or another as i set nowrap to link elements so this looks really ugly seeking for a solution to remove separators in the beginning and end of the linesfor better understanding i will try to draw an example herec php css asp javascript jquery html 5 stackoverflowsomething like that of course with justification and much more lines in a row and another drawing of what i want to achievec php css aspjavascript jqueryhtml 5 stackoverflowso fixed number of elements in a line is not an option fixed width is also not an optionthe only solution i came up with is to set font to monospace and to count symbols and print pragmatically linebyline with serverside scripting the downside of course is the monospace fontsseeking for a better solution like pure htmlcss would be perfect javascriptjquery formatting after outputthank you in advanceedit answering to a comment below markup can be anything you wish basically something likediva hreftag 1a a hreftag 2a a hreftag 3adiv,"['javascript', 'jquery', 'html', 'css']" +227640,how to use jqueryvalidate with a jquerymultiselect dropdown so the situation is this attempting to add a dropdown box using the jquerymultiselect plugin on a form that current uses the jqueryvalidate plugin that has other fields text input fields single text input that has a float value range that all currently validate correctlywhen i attempt to add validation rules i simply cannot get jqueryvalidate to validate my multiselect dropdown whatsoever here are snippets of my code all assumes that required plugins are loaded see below for versions usedthe htmlform actionsomeaction idmyform methodpost input 1 input typetext value nameinput1 maxlength200 idinput1br input 2 input typetext value nameinput2 maxlength100 idinput2br input 3 input typetext value nameinput3 maxlength50 idinput3br select select clasomeselect namemyselect idmyselect multiplemultiple option valuesome val1some valueoption option valuesome val2some other valueoption select input typesubmit valuesubmit formthe javascriptdocumentreadyfunction myselectmultiselect noneselectedtext select something required selectedlist 3 classes myselect validatoraddmethodneedsselection functionvalue element return elementmultiselectgetcheckedlength 0 validatoraddmethodispercent functionvalue element return parsefloatvalue 0 parsefloatvalue 100 validatormessagesneedsselection you gotta pick something validatormessagesispercent must be between 0 and 100 myformvalidate rules myselect required needsselection input1 required ispercent input2 required input3 required errorclass invalid versionsif there is an explicitknown issue with compatibility between the versions then i may upgrade if that solves the issue but i have tested using the newest versions for my purposes and it did not seem to solve my issuejquery 144jqueryvalidate 190jquerymultiselect 18and as always i can provide more information where possibleneeded,['jquery'] +227664,how to fix ssl no available certificate i want to make a server ssl socket connection using the following codeint port 120serversocketfactory ssocketfactory sslserversocketfactorygetdefaultserversocket ssocket ssocketfactorycreateserversocketport listen for connectionssocket socket ssocketaccepti get a javaxnetsslsslexception no available certificate or key corresponds to the ssl cipher suites which are enabled when doing the accept i created a keystore that contains a rsa key usingkeytool genkeypair alias clubconnectioncert keyalg rsa validity 7 keystore clubconnectionkeystoreand i start my program with the following optionsdjavaxnetsslkeystoreclubconnectionkeystore djavaxnetsslkeystorepasswordmypassword do i miss some code to read in the keystore or how can i testdebug that the given keystore is actually used,['java'] +227677,whats the quickest way to add several views to a linearlayout i have a linearlayout view that already contains several elements i want to add a lot more views to it programmatically and because this is inside a scrollview everything will be scrolledso what i do is go through my list and add new instances of my custom view to it that custom view inflates a xml layout and adds a few methodsthis approach works well the problem is that it is super slow even without any crazy code a list with 10 items takes around 500ms to instantiate as an user experience standpoint this is hard to swallowmy question is is this the correctbest approach android seems to take a lot of time inflating the layout even though rlayoutmy list item is super simple i wonder if there is a way to maybe to reuse inflated layouts for additional views kinda caching the more complex parsingi have tried doing this with a listview and adapter and a wrapper and it seems to be much faster the problem is that i cannot use a simple listview my layout is more complex than a simple list the linearlayout itself contains additional custom icons and it has another parent with even more views before it is wrapped by the scrollviewbut is there a way to use an adapter for a linearlayout would that be faster than trying to add the views myselfany help is appreciated i would love to make this fastercode followsmain activity the linearlayout that will contain everythinglinelist linearlayout findviewbyidridlinelist add a lot of items for testingfor int i 0 i 10 i addlistitemitem number iprotected void addlistitemstring title mylistitem li li new mylistitemthis lisettitle title linelistaddviewli mylistitempublic class mylistitem extends relativelayout protected textview texttitle public mylistitemcontext context super context init public mylistitemcontext context attributeset attrs super context attrs init public mylistitemcontext context attributeset attrs int attrsdefstyle super context attrs attrsdefstyle init protected void init inflate the xml layout layoutinflater inflater layoutinflater getcontextgetsystemservicecontextlayout inflater service inflaterinflaterlayoutmy list item this create references texttitle textviewfindviewbyidridtexttitle public void settitlestring text texttitlesettext text what i am trying to accomplish is this consider this layoutthis layout is a framelayout outer box containing a imageview in gray a textview inner rectangle on top and a linearlayout inner rectangle on bottom this linearlayout rectangle is the one i am dynamically populating with a few itemsafter i populate it i want the final result to be this where every new rectangle is a new mylistitem instancethat is everything is scrollable the background image for example is aligned on top the linearlayout is not scrollable by itself everything else follows hence why a listview from what i know wouldnt work very well in my case,['android'] +227684,php how can use curl instead file get contents i use file get contents function to get and show external link on my specific pagein local everything is ok but my server does not support file get contents functioni try to use curl with this codefunction file get contents curlurl ch curl init curl setoptch curlopt header 0 curl setoptch curlopt returntransfer 1 curl setoptch curlopt url url data curl execch curl closech return data echo file get contents curlbut return me blank pagewhat is wrong,['php'] +227697,best way to get files from a dir filtered by certain extension in php possible duplicatephp list of specific files in a directoryuse php scandirdir and get only images so right now i have a directory and i am getting a list of filesdir f whateverrandomfiles scandirdir fthat however retrieves every file in a directory how would i retrive only files with a certain extension such as ini in most efficient way,['php'] +227719,setting a buttons value using javascript i am sure i am going to feel stupid after seeing the answer but i keep running into prehistoric code around the web which i am not sure still applies my question is how do i change the value of a button inside a form using javascript heres what i have right nowfunction myfuncform formelementssubmitbuttonvalue newbrtext other stuff that actually works return falsefollowed by form onsubmitreturn myfuncthis button namesubmitbuttonoriginalbrtextbuttonformthe other stuff that actually works actually works so i am sure the function is getting called and the button is getting found i just cannot seem to stick newtext into the buttonhelp much appreciated,"['javascript', 'html']" +227743,chrome not setting cookie path to root i am setting a cookie in javascript using the following code setcookiecart itemsproduct namefunction setcookienamevaluedays if days var date new date datesettimedategettimedays24606010 var expires expiresdatetogmtstring else var expires documentcookie namevalueexpires pathbut the cookie path is not set to root in chrome instead it gets set to the path from where the web page is being executed i tested with ie and ff it works fine with both these browsers what might be wrong with chrome or is it the problem with cookie creation code i am usingin chrome 16091263 path xin ff 60 path in ie 9path,['javascript'] +227749,how to use fragment in android 22 i have an application which support android 22 libraryin this app i want to use fragmentsomeone suggest me if possible how to do itthanks,['android'] +227774,detected memory leaks in my wxwidgets application while running in debug mode i got this message in output of visual studio 2010 the application ran fine and i only saw this after closing itdetected memory leaks dumping objects 9554 normal block at 0x003cdcc0 44 bytes long data e and d 20 c1 65 01 01 00 00 00 6e 00 00 00 9c ce 64 01 9553 normal block at 0x003cdb58 8 bytes long data d e 44 bd 65 01 c0 dc 3c 00 9552 normal block at 0x003cdc50 48 bytes long data e a0 95 65 01 01 00 00 00 19 00 00 00 19 00 00 00 object dump completein my program i am not explicitly allocating memory however the wxwidgets framework is i have got such a message for first time and do not know the exact cause of ithow can i get rid of this memory leak,['c++'] +227816,why override needed in java or android in java or android there are override annotations what does it mean i found that it is used when method is from subclass or inherited interfaces method i want to know further and other is suppresswarnings its also anonation if yes how many annonation used by java and for which purpose,"['java', 'android']" +227818,find the most popular element in int array int a new int101234567how can i write a method and return 7i want to keep it native without the help of lists maps or other helpersonly arrays,['java'] +227827,the most condensed shortest way to append a new line to a file there are various method of appending text to files although i was wondering if any knows the shortest way to do this eg add a new line to an existing txt fileline1line2newlinehere,"['c#', '.net']" +227842,why is not there a javalangarray class if a java array is an object should not it extend object here is the java packagetreei read a tutorial on java which stated that in java arrays are objectswhere is the array class how comes we can make arrays like this byte bytearr new bytechar chararr new charint intarr new intand the arrays will inherit methods from object for example byte thisbyte 1 byte thatbyte 2 byte thesebytes new byte thisbyte thatbyte int inheritance thesebyteslength inherited length field and some methods int wasntinwill thatbytelength errorwhats going on hereeditas per the answers i now know it is a final class in javalangreflect packagei have now created a package javalangreflect in my android project and have added a class called arrayjava to it to confirm this is in the way of the original class eclipse gave me the error already exists in pathtoandroidjarif i write out the same class as javalangreflectarray but change the tostring method this should work within my application right,['java'] +227848,hide block and remember it with javascript and cookies i want to implement on my site showhidden div block as on stackoverflowcom at a time when the user wants to hide it himself putted on button x may already have a readymade solution i am not verse in javascript and would be very grateful for the helppicture,"['javascript', 'html']" +227872,how to use polynomials instead of bits to improve the performance i have a 128bit string and my supervisor has asked me to represent those 128 bits as a polynomial this is a scan of the paper he was writing onhis idea is since we are eliminating the 0s from these bits we will be able to perform the next operations most of which are xor between the bitspolynomials much faster than if we worked on all bitsi understand what the requirement is and i can do it on paper and also in the application but my way will not achieve his goal which is improving the performance he actually said that there are libraries already that do this but unfortunately i could not find any the only thing i found was a polynomial class that evaluates polynomials which is not what i wantso do you guys know how can i implement this to improve the performance any codesnippetsarticles is very much appreciatedthe application is written in java if that makes any differencethanksmotaupdatemy supervisor says that this c library will do the task i could not though figure out how it works and how it will do this,['java'] +227880,why does pip install raise a syntaxerror i am trying to use pip to install a package i try to run pip install from the python shell but i get a syntaxerror why do i get this error how do i use pip to install the package pip install selenium syntaxerror invalid syntax,['python'] +227919,opposite of stdbind add dummy parameters to function i need something that is the opposite of stdbind that adds dummy parameters to a function signature instead of how boostbind binds parameters awayeg i have this functionstdfunctionvoid void myfuncbut i want to convert it into a stdfunctionvoidint to pass into this functionvoid processfunction stdfunctionvoidint func,['c++'] +227943,what is the difference between objects and classes in c possible duplicatedifference between object and instance i have couple of questionsevery instance of a class except an abstract class is an objectabstract classes cannot be instantiated hence they are not objectscould anyone help me better understand the above concepts as they relate to c,"['c#', '.net']" +227957,responsewrite in webservice i want to return json data back to the client in my web service method one way is to create soapextension and use it as attribute on my web method etc another way is to simply add scriptservice attribute to the web service and let net framework return the result as d something json back to the user d here being something out of my control however i want to return something likemessage action was successfulthe simplest approach could be writing a web method likewebmethodpublic static void stopsiteint siteid httpresponse response httpcontextcurrentresponse try doing something here responsewritemessage action was successful catch exception ex responsestatuscode 500 responsewritemessage action failed this way what i will get at client is message action was successful d nullwhich means that aspnet is appending its success result to my json result if on the other hand i flush the response after writing the success message like responseflush the exception happens that saysserver cannot clear headers after http headers have been sentso what to do to just get my json result without changing the approach,['asp.net'] +228001,mysql insert datetime into other datetime field this sounds so easy but i am uncertain how to do it best and google wouldnt helpi have a table with a datetime columni would like to select this datetime value and insert it into another columni did this note 201218 131717 is the value the former select gave me from the datetime fieldupdate products set former date201218 131717 where id1and get 1064 you have an error in your sql syntax check the manual that corresponds to your mysql server version for the right syntax to use near 131717 where itemid1 at line 1ok i understand it is wrong to put an unquoted string in there but is datetime just a string in the first placewhat do i put in there all i want is reliably transfer the existing value over to a new datetime fieldthanks for readingeditsorry if this is a stupid questions the reason i ask is i have this special definition datetime and somehow i thought it gives me some security and other advantages when handling dates now it seems it is simply a specialized varchar so to speakthanks for your answers it seems this is indeed the intended behaviour,['mysql'] +228023,embedding lua in c i have been trying to embed lua in a c application but to no avail since the compiler complains about lua openi am using lua 52i found alot of articles claiming that lua open was replaced in the fifth version but none of them mentioned with whatheres the code i am trying to compileextern c include lualuahinclude lualualibhinclude lualauxlibhint main int s0 lua state l lua open load the libs lual openlibsl lual dofilelexamplelua printfndonen lua closel return 0,['c++'] +228041,rename a column in mysql table without having to repeat its type definition is it possible to rename a column in mysql without having to repeat its type definitionplease without having to hack into information schema,['mysql'] +228065,complicated mysql query issue i want to show in my dashboard the top 5 product on each product i want to show the total of order views and the percentage of where that product is based on others exgame 1 for xbox 200 orders 10 views 20game 2 for wii 180 orders 2100 views 18game 3 for ps3 170 orders 390 views 17game 4 for ps3 90 orders 1400 views 9game 5 for wii 20 orders 30 views 2so 200 orders for game 1 out of 10 orders is 20 of total orders which means 20 of my products were game 1heres my queryselect productsname productstype productsviews count as orders from productsinner join orders on productsid ordersproduct idgroup by ordersproduct idhow do i get the percentage,['mysql'] +228095,waitfornonstaleresults per documentstore is there any way to tell ravendb to use waitfornonstaleresults mode for all queries of some documentstore or documentsession,['.net'] +228096,syncadapter without an account i am trying to create a syncadapter for my android app to show youtube videos from one specific channel the videos are public domain so i do not want the user to login create an account authenticate themselves upload data or use the contacts database i simply want the syncadapter to periodically update my apps database with the newest video metadata from that channel i already built a contentprovider to access my database i do like the fact that the syncprovider will handle the ability to turn off syncing scheduling and retry backoff mechanisms for updating i asked earlier if a syncadapter was a good choice for my use case and i was told it was i watched the google io video read the docs read blogs see list below i have been unable to get anything to work the best i have gotten was to have the syncadapter account show up in the global accounts sync settings but be nonfunctional even if this worked it would be less than ideal because i prefer the user to not see the account except from inside my app this would be acceptable if there was no other option so long as they do not need to access it to set it up as everything would default to automatic once a day syncing i even tried to use the samplesyncadapter asis and put breakpoints in the authentication code sections not a single breakpoint is hit so i cannot see what triggers the calls or what data is contained i would have thought i would at least get that much i am starting to think using a syncadapter is a bad idea despite the recommendation i have yet to find an example that is close to what i want let alone a tutorial or complete organized and clear docs this seems like it should be a common task many apps would want to do please add to this post any good documentation on this use case i can find nonewithout this i think it is fair to recommend to everyone to not use syncadapters for this use case i am not speaking for other use cases here so do not jump on with how it worked for your use case if it is not like mine it would also be helpful to know what version of the api level is considered ready for primetime there is a number of issues posted regarding version numbers i am trying to stay as low as possible to get the most users my current api target is 7 heres list of links i have tried to no avail others may find these more helpfulandroid syncadapter without authentication vs android servicewhy does contentresolverrequestsync not trigger a sync,['android'] +228105,where to put super or this in my classes i have a servlet class i made to handle functions i do not want to repeat on every servlet i have i am still working on it ie it still only loads indexjsp and not other filespublic class myservlet extends httpservlet public myservlet super public void loadview httpservletrequest request httpservletresponse response throws servletexception ioexception requestthispatcher thispatcher requestgetrequestthispatcherindexjsp responsesetcontenttypetexthtmlcharsetutf8 systemoutprintlnmyservletloadview success thispatcherforwardrequest response my servlet is as followswebservletname editservlet urlpatterns contenteditpublic class editservlet extends librarymyservlet public editservlet super public void doget httpservletrequest request httpservletresponse response throws servletexception ioexception systemoutprintlneditservlet loaded i am however unable to compile my codesevere exception while deploying the app contentmanagement class contentmanagementcontenteditservlet method init signature v constructor must call super or thisupdateok removing void on my constructors and calling super got the must call first portion to go away but it is still saying i have to call super despite that it is already being calledupdatei do not understand the responses below they keep saying to put super within the constructor when my examples already show that being done and it is the first line of code any other advice would be appreciatedany thoughtsthis is now a nonissue i do not know what resolved this issue but with multiple changes and rebuilding my app from the ground up i am no longer experiencing this issue,['java'] +228106,in ruby is there a way to tell where a method is defined in ruby is there a way to tell where a method is defined i am going through the rubyguides and there is a line of code that reads postall how can i tell where all is defined,"['ruby-on-rails', 'ruby']" +228128,most efficient way to return common elements from two string arrays in java whats the most efficient way to return the common elements from two string arrays i can do it with a pair of for loops but that does not seem to be very efficient the best i could come up with was converting to a list and then applying retainall based on my review of a similar so questionliststring comparelist arraysasliststrarr1liststring baselist arraysasliststrarr2baselistretainallcomparelist,['java'] +228130,set div to remaining height using css with unknown height divs above and below is it possible to make the wrapper fill the window height no scrolling and the center div scrollable without messing around with pixels and javascriptdiv idwrapper h1headerh1 div idcenter div styleheight10pxhigh contentdiv div div idfooterfooterdivdivbasically i want the header to be visible at the top and the footer to be always visible at the bottom and have a scrollable content in the center which occupies the remaning heightthe header footer and center divs heights are all unknown no set px or ie variable fontsize or padding is it possible with pure css,"['html', 'css']" +228135,c factory pattern with heterogenous constructor constraint i am implementing a c program that can programmatically instantiate objects given an input file which provides the class names and arguments to pass to the constructorsthe classes are derived from a common base class but their constructor signature variesthey are declared as followsclass base class class1 base class1int a1 int a2 class class2 base class2int a1 int a2 int a3 and so onthe argument types do not have to be ints in fact they could be any builtin type or complex custom typethe program input could look like this in json form class1 arg11 arg12 class2 arg21 arg22 arg23 and so onreading through the docs for boostfunctionalfactory it appears that it could solve my problem were it not for the fact that in my application the constructor signature varies the heterogeneity constraint boostfunctionfactorys approach is to normalize the constructor signatures however this is not possible in my applicationin a dynamic language like python this would be rather trivial obj klassargs where klass class1 and args arg11 arg12so how would one go about implementing the factory pattern with the heterogenous constraint in care there other libraries besides boost that i have overlooked that may be of assistanceis it possible to implement this such that the only dependency is the standard library ie no boostfurthermore in the case where a constructor argument is of a complex type so that it must be specially constructed from its json representation how does it affect the complexity of the problem,['c++'] +228182,open mail client of iphone programmatically in my application if the user gave their gmail account then i am required to open the mail client with the gmail login credentials which comes when we select gmail option of mail programmatically but if that account is already stored in mail then i am required to redirect the user directly to their account can anybody pliz give me a glimpse of how i can achieve this programmatically,['iphone'] +228184,jquery lazyload plugin and callback function i download jquery lazyload plugin from this site from their doc i have not found that one can use any callback or not with lazyload pluginsuppose my html look likediv idgallery classbusyimg srcblahjpg divdiv idgallery classbusyimg srcblah2jpg divdiv idgallery classbusyimg srcblah3jpg divmy script likegallery imglazyloadclass busy will just set a busy image at the center of div so i need a callback and from the callback i need to detect image download completed or not if completed then i just remove the class from corresponding parent div of image tag so please show me the way to implement callback with lazyload and also need sample code by which i can remove the class from corresponding parent div of image tag thanks,['jquery'] +228187,how to subdivide uibezierpath and store it in two different objects i have uibezierpath in the application when the finger touch on the path is recognized i want to subdivide that curve and store that two curves into two different objects so touch coordinates will work as endpoint for one curve and startpoint for second curve again if i touch on any of this curve that curve will subdivide into two other curves and so oni searched for this a lot but could not find any good solutionalso i do not have idea if there is any other way to do this any help would be greatly appreciatedthanks,['iphone'] +228194,what is the default value for a field if no default value is provided i hope this is not a dumb question you can set a default value for all variables or a function for when it is inserted but if the field is not required to insert and you do not allow null values what is the blank value that you see in phpmyadmin in a query is it returned as empty string etc just trying to figure it out i want to query for all records such that the value for a specific column in that record is not empty or blank or whatever thanks,['mysql'] +228224,android launching google navigation from an app i am currently in progress of an android app which takes some coordinates by the user starting point from gps and destination defined by the useri would like my app to launch the google navigation so that it can guide the user through these points at a next step i would like to give navigation more points eg some points of interest so that it will guide the user through a specific route containing all the points is that possible all that i find is nodocumented practices and no examples is there anyone who has solved this problem if not can someone suggest some other navigation programm thank you in advancegeorge,['android'] +228231,javascript type conversion true 1 vs true 1 javascript is nonstrictly typed language as javafor exampleas we know it converts value of result dependently upon context2 3 results 232 3 results 6this is quite clear and ok for understandingi just tried following expressions and got confusedtrue 1 results 1 true 1 results truewhy the first gives number and the second gives booleanconsidering javascript conversion rulesi expect to get boolean values in both casesdue to boolean context of expression,['javascript'] +228246,python in does not check for type false in 0true typefalse type0falsethe reason i stumbled upon thisfor my unittesting i created lists of valid and invalid example values for each of my types with my types i mean they are not 100 equal to the python typesso i want to iterate the list of all values and expect them to pass if they are in my valid values and on the other hand fail if they are notthat does not work so well now valid values 1 0 1 2 3 invalid values true false foo for value in valid values invalid values if value in valid values print valid value value valid value 1valid value 0valid value 1valid value 2valid value 3valid value truevalid value falseof course i thisagree with the last two valid valuesdoes this mean i really have to iterate through my valid values and compare the type,['python'] +228249,removing duplicate columns and rows from a numpy 2d array i am using a 2d shape array to store pairs of longitudeslatitudes at one point i have to merge two of these 2d arrays and then remove any duplicated entry i have been searching for a function similar to numpyunique but i have had no luck any implementation i have beenthinking on looks very unoptimizied for example i am trying with converting the array to a list of tuples removing duplicates with set and then converting to an array againcoordskeys nparraylistsettuplex for x in coordskeysare there any existing solutions so i do not reinvent the wheelto make it clear i am looking for a nparray1 1 2 3 1 1 5 4 2 3 unique rowsaarray1 1 2 35 4btw i wanted to use just a list of tuples for it but the lists were so big that they consumed my 4gb ram 4gb swap numpy arrays are more memory efficient,['python'] +228265,aligning jmenu on the right corner of jmenubar in java swing so if i have a jmenu jmenubar defined such that jmenubar1 new javaxswingjmenubarjmenu1 new javaxswingjmenujmenu1settextaboutjmenubar1addjmenu1 finallysetjmenubarjmenubar1and with this the menu about is aligned to the left most side of the menu bar is there anyway that i can align this menu on the right most side of the menu bar,['java'] +228287,make nothing to be done for all i am going through an eg pgm to create a make filemy folder eg make creation contains the following filesdesktopeg make creation lsfactorialc functionsh hello helloc mainc makefilemakefile i am a comment and i want to say that the variable cc will be the compiler to useccgcc hwy i am comment no2 i want to say that cflags will be theoptions i will pass to the compilercflagsc wallallhellohellomaino factorialo helloo cc maino factorialo helloo o hellomainomainc cc cflags maincfactorialofactorialc cc cflags factorialchelloohelloc cc cflags hellocclean rm rf o helloerrordesktopeg make creation make allmake nothing to be done for allplease help me understand to compile this program,['c'] +228289,why does the doublevalueof javadoc say it caches values when it does not in openjdk for the methodpublic static double valueofdouble dthe javadoc saysreturns a double instance representing the specified double value if a new double instance is not required this method should generally be used in preference to the constructor doubledouble as this method is likely to yield significantly better space and time performance by caching frequently requested valuesheres the actual codepublic static double valueofdouble d return new doubledthe cache is a lie whats going on here,['java'] +228293,compile stdregex iterator with gcc i can create o file with g c testcpp stdc0x but cant link it got next errorstestcpptext0xe5 undefined reference to stdregex iteratorchar const char stdregex traitschar regex iteratorchar const char const stdbasic regexchar stdregex traitschar const stdbitset11utestcpptext0xf1 undefined reference to stdregex iteratorchar const char stdregex traitschar regex iteratorcodeinclude regex include iostream include stringhtypedef stdregex iteratorconst char myiter int main const char pat axayaz myiterregex type rxa myiter nextpat pat strlenpat rx myiter end return 0,['c++'] +228312,htmlcss mobile zoomed at start having a issue where all mobile devices is zoomed 50 in at start that is every device other than ipad tried to do a php check to scale 50 out if all other than ipad but when you moved from landscape portrait landscape it would then scale 50 out once againhere is my current meta tagsmeta namehandheldfriendly contenttrue meta nameviewport contentwidth640 height700 initialscale10 maximumscale10 minimumscale10 my html does not use any width 100 only in px overall the content does not extend 640 width and 700 heightdo anyone have any idea on how i could possible avoid this issueeditcame to the conclusion that hakre was right about the scale of the pixels my fix was to set every width in rather than px this way it auto sized no matter what one thing to note is that i removed the scale reason why is that it seem to mess up the layout on some devices thanks once again hakre,"['php', 'html', 'css']" +228324,know if fieldsproperties of an object are simpleprimitive types or other objects i got the following code that generate a dll sample exemple public class pluginclass private string mystring public string mystring get return mystring set mystring value raisepropertychangedmystring public int myint public speedgenerator speedgenerator1 new speedgenerator public gaugevaluegenerator gaugevaluegenerator1 get set public pluginclass gaugevaluegenerator1 new gaugevaluegenerator as you can see i got 4 fieldsproperties1 primitive field primitive is intstringbooletcetc myint1 primitive property mystring1 object field speedgenerator11 object property gaugevaluegenerator1when im parsing my dll i got to do some code that is in the function writepropertyvar fields typegetfieldsbindingflagspublic bindingflagsinstancevar props typegetpropertiesforeach fieldinfo field in fields writepropertyfieldfieldtype fieldname xforeach propertyinfo prop in props writepropertyproppropertytype propname xmy question is on x that is a boolean that indicate if my fieldproperty is primitive so it must be set to false if it is an objecti fell like i tried quite everything but i cannot resolve itany help will be very appreciate my idea was to callvar props propertytypegetpropertiesbindingflagsinstance bindingflagspublic bindingflagsdeclaredonlyand consider that it should be empty for simpleprimitive types but no for example on string this return the properties chars char and length intnb of course i do not wanna do a string operation on fieldpropertynamefullname something likeif propertytypefullnamecontainssystemwould be very very sucky and inaccurate,['c#'] +228325,how to get all checked checkboxes i have a set of input checkboxes with same nameand i would like determine which checkboxes have been checked using javascript how can i achieve thati know only how to get all the checkboxes as followsvar checkboxes documentgetelementsbynamemycheckboxes,"['javascript', 'html']" +228329,how to mock an outgoing socket connection in integration tests jdk 6 i am trying to catch all outgoing tcp connections and mock them looks like i should use javanetsocketsetsocketimplfactory method works fine at the moment but i cannot understand how i can get an access to original factory in order to instantiate original jdkprovided socketimpl class i need this mostly because i want to let some connections to go out freely without mocking can you suggest some manualsguidelinesinstructions about this problem,['java'] +228351,switch without break i have some switch statement as shown below notice there is no breakfindbugs is reporting error on the second case statement only the error is switch statement found where one case falls through to the next caseswitchx case 0 code case 1 code case 2 code,['java'] +228362,why are we installing ruby 192193 gems into a 191 folder this comes about because the gem installation directory used by the gem command seen when using gem env is set to something likebase ruby dirlibrubygems191my question is whyshould not the folder be calledbase ruby dirlibrubygems19xorbase ruby dirlibrubygems19or else could not there be one per version of ruby likecruby191librubygems191cruby192librubygems192cruby193librubygems193not a critical problem i know i was just wondering,['ruby'] +228395,jquery remove onclick events from a tags this is a weird question we have some production links down on our intranet some rouge javascript is returning a false on all links on our intranet homepagewe do not have access to the source to rebuild the control and fix this javascriptso as a temporary bandaid i want to move all the onclick events on the links using jquerythe links right now are like thisa href onclickaddhitheader mysitecom return false titlemysite homewmysitecomai want to write some jquery to get ride of the onclickaddhit code,['jquery'] +228421,delay hover in css3 is there a way to delay the hover event without using javascript i know there is a way to delay animations but i have not seen anything on delaying the hover eventeditedsorry i should have included this to begin with i am building a sonofsuckerfish like menu i would like to simulate what hoverintent does without adding the extra js weight i would prefer to treat this as a progressive enhancement and not make js a requirement for using the menuupdatedhere is the final code thanks for all the help,['css'] +228448,is there a net library for minifying javascript i am programatically creating javascript files from a net web app and would like to minify it before passing it on to the user is there a library or technique for doing this on the flythank,"['javascript', '.net']" +228458,redrawing a uiview with a fade animation in twui there is a method called redraw on tuiview it forces the view to redraw but it also comes with a free fading animation between the old and new state of the viewi am wondering if something like that is possible in a normal uiview basically how can i redraw the view setneedsthisplay with a fading animation between the old and the new states,"['iphone', 'objective-c', 'ios']" +228484,pyqt getting file name for file dropped in app i am trying to set up an application that will accept havin files dropped into it so i am looking for a way to extract the path when they are dropped in right now i have drag and drop enabled for the right part of the application and it will accept text dropped in but i do not know how to handle having a file dropped ini am usingdef pte dragentereventself e if emimedatahasformattextplain eaccept else eignore def pte dropeventself e newtext selfuifilelistptetoplaintext nn emimedatatext selfuifilelistptesetplaintextnewtextwhich is slightly modifying the code provided in the drag and drop in pyqt4 tutoriali could not quite get ekhumoro answer to work for me but it gave me more places to look and i found pyqt4 drag and drop files into qlistwidget which helpedin addition to the suggestions made by ekhumoro i needed to implement the drag move event what i finally used looked likedef dragentereventself event if eventmimedatahasurls eventaccept else eventignoredef dragmoveeventself event if eventmimedatahasurls eventsetdropactionqtcoreqtcopyaction eventaccept else eventignoredef dropeventself event if eventmimedatahasurls eventsetdropactionqtcoreqtcopyaction eventaccept newtext selfuifilelistptetoplaintext for url in eventmimedataurls newtext n strurltolocalfile selfuifilelistptesetplaintextnewtext selfemitqtcoresignaldropped else eventignore,['python'] +228493,is there any danger to using input fields outsidewithout forms in htmljavascript pages input fields are usually associated to forms but i would like to use them in a simple javascripthtml page i do not need the form i see no issue with my html page but is there any danger or bad practice i am not aware of i just do not want my page to bug down the roadbasically a field in my page can be javascript enabled or thisabled according to values in other fields,"['javascript', 'html']" +228502,storing messages using xmppframework for ios i am not sure how to use the xmppframeworks core data to store incoming messages does anyone have any tutorials on how to do this i see user objects which in turn can have many resources is each message received supposed to be a new resource that i create and persisti do not know what part is my responsibility and what part the framework provides regarding message history i can intercept every incoming message then am i supposed to create and store each message inside a messages table using core data i would have a message entity and each xmppuser would have an array of message objects but then wouldnt i be rolling my own solution which would be working against the frameworkthanks,"['iphone', 'ios']" +228503,how can i consolelog functions alongside all their properties i am using the google chrome console frustratingly the following codevar f function fa 1consolelogfwill only logfunction why does it not print the properties of f such as fa and fprototype how can i print them,['javascript'] +228504,hiding types from being listed in assemblygettypes in net ive been looking everywhere for a possible solution to this but cannot seem to find an answer my issue is that i have a few classes that need to completely hidden from assemblygettypes as i am writing a plugin for an application and it is picking up types that i need to remain hidden this happens even if they are declared as private or internal classesanyone know how to either alter what assemblygettyes returns or an aficionado attribute that will keep those types from being listed,['c#'] +228511,why does the jdk have both mathrandom and the random class is it just because of large api syndrome or generating random numbers that are more biased favored in some situations if it wasi would think that controlling the biasness would be important,['java'] +228515,retaining arc objects in c classes i have some code that must remain as c but i need to store objectivec objects in these c classes the objects will not be referenced anywhere else while they are stored here so i cannot have them deleted out from under me before arc i just retained them before putting them into the c class and autoreleased them when they were removed everything worked finesbut with arc i am not sure what to do is making the c variables unsafe unretained enough does not seem like it is because once the objc code is not using that objects anymore it will be deleted or am i not understanding what unsafe unretained does can i call cfretain and cfautorelase under arcwhat is the right way to deal with this under arc what does nsarray do down deep to keep the objects it is storing,['objective-c'] +228568,submitting forms with mechanize python well i am trying to login to a site using python and mechanizei have got the site openedsite bropenand i have got a list of the forms with brformsget applicationxwformurlencodedhiddencontrolsearch1 readonlypost applicationxwformurlencodedtextcontrolusernamepasswordcontrolpasswordcheckboxcontrolstay1submitcontrolnonelog in readonlyi have been trying to submit the username and password fieldsi tried doing it like thisbrselect formnr0brformusername usernameherebrformpassword passwordherebrsubmitthen i realised that the forms i were trying to fill in werent the first on the page but changing the 0 did not help with anything what should i do for selecting the form on a page like thishowever that is not the only problemwhen i run it i get this errortraceback most recent call lastfile cpython26loginpy line 34 in modulebrformusername usernameherecontrolnotfounderror no control matching name usernamehow can i fix this d or am i doing it totally wrong if it is the latter how would i go about doing it,['python'] +228582,java visitor pattern instead of instanceof switch in this question it is said i can use visitor pattern instead of a bunch of instanceofs jmg said if you are not free to change a b and c you could apply the visitor pattern to achieve the sameas far as i understand i still have to make a b and c support visitor have an accept method for examplemy problem is i have absolutely no possibility to change a b and c i just get the car object from the foreign library and have to call wash method specific for trucks race cars and busesi think i still need an ifelseifconstruction with instanceofs am i right,['java'] +228604,how to make text input box resizable like textarea by dragging its rightbottom corner using jquery i would like to have preferrably in jquery regular text input box which can be clicked and dragged by its rightbottom corner eg like textareas have in chrome and resized by user cannot find any jquery plugin already implementing this can anybody give me hint if something like this exists or how could it be easily implemented thank you in advanceedit i want to be resizable similarly like textarea is in chrome,"['javascript', 'jquery']" +228617,see call stack while debugging in pydev is there a way to see the call stack while debugging python in pydev,['python'] +228628,c pre post increment confusions i am a little confused about how the c compiler handles pre and post increments and decrementswhen i code the followingint x 4x x xx will have the value 10 afterwards i think this is because the preincrement sets x to 5 which makes it 55 which evaluates to 10 then the postincrement will update x to 6 but this value will not be used because then 10 will be assigned to xbut when i codeint x 4x x xthen x will be 2 afterwards can anyone explain why this is the casethanks,['c#'] +228629,android how can i convert string to date i store current time in database each time application starts by usercalendar c calendargetinstance string str cgettimetostring logicurrent time strin database side i store current time as string as you see in above code therefore when i load it from database i need to cast it to date object i saw some samples that all of them had used dateformat but my format is exactly as same as date format so i think there is no need to use dateformat am i rightis there anyway to directly cast this string to date object i want to compare this stored time with current timethanksupdatethanks dear guys i used following codeprivate boolean ispackageexpiredstring date boolean isexpiredfalse date expireddate stringtodatedate e m d hhmmss zz y if new dateafterexpireddate isexpiredtrue return isexpired private date stringtodatestring adatestring aformat ifadatenull return null parseposition pos new parseposition0 simpledateformat simpledateformat new simpledateformataformat date stringdate simpledateformatparseadate pos return stringdate,['android'] +228652,using new linen in string and rendering the same in html i have a string saystring thisplay txt 1st line text n 2nd line textin jquery i am trying to use somedivhtmlthisplay txtcsscolor greenquite clearly i am expecting my msg to be thisplayed in 2 lines but instead and is being thisplayed in the message any quick fixes for thatthanks,"['jquery', 'html']" +228668,rake in rails should i be using dbreset i am a little confused by the intended use of the default rails rake tasks and would like advice on whether i should be using dbreset or writing a custom rake task nothing clever just daily housekeeping and i may well be missing an obvious doc as i am new to railsmy problem i want to throw away my database and run from a completely clean setup in order that i can be sure the database contains known data only this is useful for demo prep for debugging and for making sure jenkins is comparing likewithlike in testscurrently i am writing thisbinrake dbdropall dbcreateall dbmigrate dbseed dbtestpreparethis is a lot to type but leaves seed data only in both dev and test databases i am unsure how this differs from dbreset which would be more convenient to typeshould i use dbreset or write a custom dbfrom scratch task,['ruby-on-rails'] +228683,is handling of curly braces in javascript regex is the same across all modern browsers curly braces in javascript regex is used to denote quantifiers so writinga24will match aa a and a but if you mistype this quantifier like thisx1xit will match the literal text x1x at least in firefoxis this behavior common to modern browsersthe ecma standard prohibits this behavior and requires the escaping of the bracesbackground i have to write a parser for javascript regexes at work,['javascript'] +228726,how to know when page is ready without using jquery alternative way possible duplicatedocumentready equivalent without jquery if you have jquery called in your page you can simply do itdocumentreadyfunction code inside but how to do similar thing without jquery,['javascript'] +228733,c about memory management i am a bit new to c and been doing programming in objc and java up until nowsay i have a classclass person private wife current wife so obv i need to implement a setter method to change the wife instance variablelike thispersonsetcurrentwife wife new wife current wife new wifethat would be a shalow copyso somewhere from the main loop or something i callperson some person new personwife wife new wife some personsetcurrentwifewifeso i am confused will there be a memory leak here should i delete the wife object here or in persons destructor in objc i would release the current wife and then send a retain message to wife object above but what is the proper way of doing setter methods in c,['c++'] +228742,cannot convert list to ienumerable getting an invalidcastexception when trying something like this ienumerableobject test ienumerableobjectnew listkeyvaluepairstring inthowever this did workienumerableobject test ienumerableobjectnew listdictionarystring intso whats the big difference why can a keyvaluepair not be converted to an objectupdate i should probably point out that this did workobject test objectkeyvaluepairstringstring,['c#'] +228747,pythonclass attributevariable inheritance with polymorphism in my endeavours as a pythonapprentice i got recently stuck at some odd from my point of view behaviour if i tried to work with class attributes i am not complaining but would appreciate some helpful comments to shed some light on this issueto reduce a complex matter into a more concise question i would formulate it like thiswhat is the pythonic way to ensure that a classattribute behaves more like a static variable in an inheritance treeit seems to me like a classattribute behaves like a copy on read default value with polymorphic characteristics as long as i do readonly operations it stays a singletonbut as soon as i access the classattribute with an assignment through the derived class or instance it gets morphed into a new reference loosing the relation to the inherited basereferenceit has sure potential for some interessting features but you have to understand it toembrace it so some insight is highly appreciatedclass aobject classvar a def setclassvarself value aclassvar value def str self return s ids aclassvar hexidaclassvar21upperclass a1a passclass bobject classvar b def setclassvarself value self class classvar value def str self cvar self class classvar return s ids cvar hexidcvar21upperclass b1b def setclassvarself value self class classvar valuea a1 a a1a1setclassvaraprint new instance a s aprint new instance a1 s ab b1 b b1b1setclassvarbbprint new instance b s bprint new instance b1 s b1a1setclassvaraaprint new value a1 s aprint new value a s aa1classvar aprint direct access a1 s ids a1classvar hexida1classvar21upperprint method access a1 s a1print direct access a s aproduces the followingnew instance a a idb73468a0 new instance a1 a idb73468a0 new instance b b idb73551c0 new instance b1 bb idad1bfc new value a1 aa idad1be6 new value a aa idad1be6 direct access a1 a ida3a494method access a1 aa idad1be6 direct access a aa idad1be6so either the direct assigning access objectclassvar or mediated through self class classvar are not the same as baseclassclassvaris this a scope issue or somethin totaly different looking forward to your answers and thanks in forward edit there was an answer for a very short time suggesting the use of classdescriptors likehow can i make a class property in pythonunfortunatly that does not seem to workclass hotelbar def init self hotelbar 1hotel hotelassert hotelbar 51assert hotelbar foobarthe 2nd assertion fails hotelbar does not reference the same object as foobar and hotelbar references somethin other then hotelbar2nd edit i am quite aware that singletons are considered an antipattern and i did not intend to use them extensivly therefore i did not mention them in the questiontitel even so there are many solutions thiscussing and providing solutions with and about singletons my question stays why can a classvariable detach it is reference so easily ruby behaves more the way it feels natural to me,['python'] +228758,css fit relative positioned parent to height of absolute positioned child i am trying to build a simple slideshow so far the basic markup looks like thish1my slideshowh1pthis paragraph behaves as expectedpdiv claslidecontainer div claslide h2first slideh2 psome stuff on this slideap div div claslide h2second slideh2 pand some more stuff hereap divdivpthis paragraph will thisappear beneath the stacked imagespthis is the corresponding cslidecontainer position relativeslide position absolute top 0 just for the looks width 20em padding 0 1em border 1px solid steelblue background whitethe problem is that the slidecontainer does not fit to the height of its child or children slide see screenshoti know i can set the height of the slidecontainer manually but i want to put this in a fluid grid where the height is variable is there any way to achieve this,['css'] +228759,securing website api keys in chrome extensions i am building a chrome extension using the remember the milk web api in order to call methods in this api i need to sign my requests using an api key and a shared secret keymy concern is that any user could just crack open the extension and pull out these values if i include them in the published extension this may or may not pose a security rise for the user but he or she could certainly useabuse my api key and maybe get it revokedis this something i should be concerned about are there any best practices for protecting this type of information in published javascript applications,['javascript'] +228760,how to install javadoc for android compatibility package how to generate custom javadoc for android 14 compatibility packagethe reference docs are available online example but is there some place where i can get a zip with javadoc available offlinei suppose using the javadoc would be pretty simple just a matter of setting the javadoc location for the compatibility jar,['android'] +228766,explode a string on upper case characters ho can i explode param string into chunks pieces based on uppercase charactersstring setifunmodifiedsincemethod substrstring 0 3param substrstring 3 split param and implode with separatorchunks splitatuppercaseparam chunks are if unmodified and sincefield implode chunks get ifunmodifiedsince http field name,['php'] +228781,why does trying to use string nullable string in c produce a syntax error i have a method that returns null if the postcode is invalid and just returns the string if it is valid it also transforms the data in certain cases i have the following unit test below but i am getting syntax errors on the lines where it is using string could anyone tell me why public void isvalidukpostcodetest validpostcode mocksyntaxvalidator target new mocksyntaxvalidator 0 string fieldvalue bb1 1bb string fieldname int linenumber 0 string expected bb1 1bb string actual actual targetisvalidukpostcodefieldvalue fieldname linenumber assertareequalexpected actual,"['c#', '.net']" +228792,return string vs integer vs undefined vs null why does javascript prefers to return a string over any other choices consider the following snippetvar arr hello1 hello2 hello3arrayprototypeitem functionx return thisx null aa e 12 undefined consolelog arritem43 returns aa ei intentionally called a nonexistent array elementhowever i cannot understand why does arritem43 returns the string why not null or undefined or even 12,['javascript'] +228793,how to extract common file path from list of file paths in c what is the best way extract the common file path from the list of file path strings in cegi have a list 5 file paths in list variable like below cabcpqrtmpsamplebtxtcabcpqrtmpnew2c1txtcabcpqrtmpb2txtcabcpqrtmpb3txtcabcpqrtmptmp2b2txt output should be cabcpqrtmp,['c#'] +228803,python config parser to get all the values from a section i want to get all the values from a section using config parser i used this but it gives only the first valuedef configsectionmapsection dict1 options configoptionssection for option in options try dict1option configgetsection option if dict1option 1 debugprintskip s option except printexception on s option dict1option none return dict1 config configparserconfigparser configreadetcharvestconf print configsectionmapfilesvalues,['python'] +228814,jquery animate textshadow css property so as i have worked with jquerys animate method i have learned that in order to animate the left margin you would have to use something like thisthinganimatemarginleft 20 10which is different than using the css property marginleft 20pxhow could i use the textshadow property inside animate,"['jquery', 'css']" +228834,prevent scrolling of oversized child in parent with overflow hidden webkit i have an issues with webkit browsers the issue happens when i focus my cursor to the input element and start to move mouse without releasing the buttonhere is a screencast here is a htmlcss demo bughtmlhow can i prevent this behavior,"['html', 'css']" +228843,style hover state of element when hovering over overlapping elements with css i have a dom structure containing several divs visually some of these divs are children of others but in the dom structure they are all siblingsi need to style the hover state of the parent divs even when hovering over its child divsis there a way of doing this without javscript maybe by using the current position of the divs to know they are inside of another divupdatethe problem is the parents are actually siblings there is only one container and let us say 8 children divs 2 are bigger divs and the other six are shown 3 inside each bigger div something likeonly the parent surrounding the hovered children should change colori cannot change the dom structure btw,"['html', 'css']" +228861,javascript calling private method from prototype method i am sure that this must be a pretty common question but after scouring the internets for several hours i have not found an answer here is the questionsuppose that i have an interface called mammal every mammal has to be able to sleep and eat in the future i may throw exceptions for the mammal class to force children to implement the functionfunction mammal mammalprototypeeat function mammalprototypesleep function now suppose that i have a dog class who implements the mammal classfunction dog dogprototype new mammaldogprototypeeat function dogprototypesleep function the dogs eat function is very complicated and i would like to use a helper function i have not been able to figure out what the best way to do this is here are the points of consideration the helper function should never be called from outside of the dog class so ideally it should be privatethe eat function does not have access to private functions prototypes do not have access to private functionsi could put the helper function into a privalaged function but this would still be a public function ie everyone has the right to call itit would not be part of the prototype so every dog would need to have its own helper function if there were lots of dogs this seems inefficient i cannot make the eat function a privaliged function because in order for prototype inheritance to work it needs to be part of the prototype question how can i call a private function from a prototype function or more generally when an object child object inherits from another object parent object how should children methods use helper functions and is it possible to make these private,['javascript'] +228887,what is the best place to store static assets files in rails 31 pdf forms xls files etc i have a bunch of static assets not jpg css js rather files like pdf forms xls that i need to serve to users they rarely change before i used to store them in public folder but with the introduction of the assets pipeline in rails 31 what is the best place to store files like that now nowthanks,['ruby-on-rails'] +228914,when does gc decide to collect generation 2 during the day i see a lot of gen 2 collections in our windows servicewhen does gc decide to do full collection instead of collecting only gen1 and gen0 or only gen0,['.net'] +228917,multiple webviews in scrollview giving issues android i have a scrollview which has multiple webviews these webviews are loading some pagesthe problem is that i cannot explain so you have to see the webviews upon scrolling get thistorted as shown in the picture when load for the first time they are ok,['android'] +228927,how can i repeat a transition forever i have a transition looking like thisxml version10 encodingutf8transition xmlnsandroid item androiddrawabledrawabledivider item androiddrawabledrawabledivider activetransitionand code looking like thisview divider vfindviewbyidriddividerif divider null transitiondrawable transition transitiondrawable dividergetbackground transitionstarttransition20my problem is i do not know how to repeat this transition forever so i can create a pulsing effecteditto make things clear the code gets executed when creating a view listitem so loops are no solution,['android'] +228929,getting last two rows in a text file so i am creating a list of lines in a text file like thisvar lines filereadalinescfiletosearchtxt wherex xendswith9and looping through the lines like thisforeach var line in lines if linecounter 1 outputresultsaddodatatocanadianformatfileheader else if linecounter 2 outputresultsaddodatatocanadianformatbatchheader else odatafromuslineformatline outputresultsaddodatatocanadianlineformat linecounter linecounter 1 textbuilder line brsimilary like i access the first two rows i would like to access the last and second last row individually,"['c#', 'asp.net']" +229009,does spring have a shutdown process to put cleanup code when my spring web app shuts down is there an event i can wireup to somehow that i can perform some cleanup code to empty out some pools etc,['java'] +229022,thisabling validation in htmltextboxfor in net i am using aspnet mvc 3 i have an entity called student having the properties id name age rollno in the create page of student i have used validation framework but in advanced search page i am using all the properties but do not want to use validation framework as users may not want to use all the fields for searchingi would also like to mention that i have used required annotation in model classplease help me to overcome this issueregardsmolay,['.net'] +229066,some coredata relationships are lost after closing app this is the overview of my problemi am adding and confirm they are added about 1400 relationships loaded from a soap service into coredat after i close the app and open it again some of the relationships are lost i only see around 800 of them although it varies also i am not getting any errorsand now more detailsi have an object called user that has information about services a user have saved it looks something like thisinterface oosuser nsmanagedobject oosuser userfromslug nsstring slug property nonatomic retain nsstring name property nonatomic retain nsstring slug property nonatomic retain nsmutableset service services void addservicesobject service service void removeservicesobject service serviceendimplementation user dynamic name dynamic slug dynamic services static nsstring fetchpredicate slug user userfromslugnsstring slug user result super objectwithpredicate fetchpredicate slug if result result super create resultslug slug return result endin the part of the code where the data is used the relationships are saved like thisnsmutableset userservices selfuserservicesfor service service in servicestoadd selfservices addobject service bool contained false for service userservice in userservices if contained userserviceslug isequaltostringserviceslug break if contained userservices addobjectservice selfuser addservicesobject service nserror error nil if service managedobjectcontext saveerror nslogsaving failed nslogerror error localizeddescription else nslogregistered service d selfservicescount serviceslug the case is that i have checked with the debugger and i can see that all the over 1400 relationships are added but when the app is reset and they are restored though selfuserservices i only get around 800 objectswhy could this be happening anybody had this beforethanks in advanceupdatepeople keep suggesting that i am not using core data correctly but the problem is that the data is lost after restarting the app there is absolutely no problem with it while using it i am using core data as correct as it could be given the limited documentation and examples you get from apple,"['iphone', 'objective-c']" +229071,passbyreference not working with additional parameters for array walk recursive unless it is the deprecated calltime passbyreference for a while now i have been using a traditional recursive function to flatten multidimensional arrays such asbasearray arrayarrayalpha arraybetagamma array arrayarraydeltaepsilon arrayzetaarrayeta theta arrayiota to a simple 1d arraylast night i thought i would take a look at using array walk recursive to see if i could make it more efficient and cleanermy first attempt was not very successfulfunction flattenarrayarrayvalue arraykey flatarray flatarray arrayvalueflattenedarray arrayarray walk recursivebasearrayflattenarrayflattenedarrayi thought it should work but all i got was a series of errorswarning cannot use a scalar value as an array in cxampphtdocsarraytestphp on line 16and a result ofarray0 type hinting in my flattenarray function gave mecatchable fatal error argument 3 passed to flattenarray must be an array integer given in cxampphtdocsarraytestphp on line 16using a closure gave identical resultsthe only way i could get it to work without recourse to using a global or a static for my flattenedarray was using calltime passbyreferencefunction flattenarrayarrayvalue arraykey flatarray flatarray arrayvalueflattenedarray arrayarray walk recursivebasearrayflattenarrayflattenedarraywhich produces the correct resultarray9 0 string5 alpha 1 string4 beta 2 string5 gamma 3 string5 delta 4 string7 epsilon 5 string4 zeta 6 string3 eta 7 string5 theta 8 string4 iota but gives me a notunexpected warningdeprecated calltime passbyreference has been deprecated in cxampphtdocsarraytestphp on line 22i know php is a quirky language but this seems a bit extreme the documentation clearly shows that the first parameter to array walk recursive is passbyreference but it seems that additional arguments can only be passbyreference at calltime weirdphp version is 538any suggestions as to how i can use array walk recursive to flatten my array correctly without getting deprecated errors besides filing a bug reporteditpsi am aware that i can bypass this problem using a closureflattenedarray arrayarray walk recursivebasearray functionarrayvalue arraykey useflattenedarray flattenedarray arrayvalue var dumpflattenedarraybut as this is required for a library which currently allows use with php 520 it is not a practical option to use a feature that requires a significantly later version of php,['php'] +229109,why does jqplots dateaxisrenderer crash when showing a single data point i have isolated an end case with jqplot that causes it to crash halt indefinitely my entire pages javascript this happens when i use the dateaxisrenderer in a line chart with a single value like sofunction function var data now plot1 now new date single data point in the series data now 1 return plot1 jqplotplottarget data axes xaxis if i remove this renderer the crash does not happen renderer jqplotdateaxisrenderer callthiswhy does this happen is this a bug in jqplot or am i doing something wrongalso noticed if i add more values with the same date into the series the same problem occurs if i add more values with different dates the problem goes awayi am using jquery v164 jqplot v100b2 r1012 and rendering on firefox 801,['jquery'] +229151,how can i change included xml layout to another layout on java code i have a problem i develop android applicationi included second layout to first layout like thisxml version10 encodingutf8relativelayout xmlnsandroid androidlayout widthmatch parent androidlayout heightmatch parent relativelayout xmlnsandroid androidlayout width300dp androidlayout heightmatch parent androidlayout gravityclip horizontal androidlayout alignparentlefttrue androidididrlmenu button androidididbmusteriler androidlayout widthfill parent androidlayout heightwrap content androidtextmusteriler androidtextsize45dp androidlayout alignparentlefttrue relativelayoutrelativelayout xmlnsandroid androidlayout widthfill parent androidlayout heightmatch parent androidlayout torightofidrlekranlar include androidididinclude1 androidlayout widthfill parent androidlayout heightwrap content layoutlayoutikinci relativelayoutrelativelayoutproblem is how can i change included layout when clicked a buttonon java code sorry for my englishthanks,['android'] +229163,what advantages does ceylon have over java or scala yesterday i saw the announcement from the ceylon team that the first milestone release had been made publicly available and from what i can see it looks interstingfrom looking at the information on ceylon its purpose seems largely in line with the purpose of scalaceylon is deeply influenced by java you see were fans of java but we know its limitations inside out ceylon keeps the best bits of java but improves things that in our experience are annoying tedious frustrating difficult to understand or bugproneso in a nutsheel ceylon and scala seem to be saying in my interpretation we like java but there are annoyances so we want to build on top of java to make life betterbut want i want to know is why create yetanotherjavakiller as some have billed ceylon when scala already exists what sets ceylon apart or above scalanote please no i like x over y i am looking for an objective view of what ceylon offers the development community,['java'] +229166,how to do pos tagging using the nltk pos tagger in python i just started using a partofspeech tagger and i am facing many problems i started pos tagging with the followingimport nltktextnltkword tokenizewe are going outjust you and mewhen i want to print text the following happensprint nltkpos tagtexttraceback most recent call lastfile stdin line 1 in modulefile fpython26libsitepackagesnltktag init py line 63 in pos tagtagger nltkdataload pos taggerfile fpython26libsitepackagesnltkdatapy line 594 in loadresource val pickleload openresource urlfile fpython26libsitepackagesnltkdatapy line 673 in open return findpathopen file fpython26libsitepackagesnltkdatapy line 455 in find raise lookuperrorresource not found lookuperror resource taggersmaxent treebank pos taggerenglishpickle not found please use the nltk downloader to obtain the resource nltkdownload searched in cdocuments and settingsadministratornltk data cnltk data dnltk data enltk data fpython26nltk data fpython26libnltk data cdocuments and settingsadministratorapplication datanltk datai used nltkdownload but it did not work,['python'] +229172,cancelalloperations does not work for nsoperationqueue mainqueue cancelalloperations does not work on the mainqueue the cancel method is not called on the nsoperation object am i missing somethingi have to iterate through all operations and call the cancel method to get it work,['ios'] +229176,iteration count in python let us say i have a list of tuples l and i do something like thisfor ab in l do something with ab and the index of ab in lis there an easy way to get the index of ab i can use the index method of list but what if ab is not unique i can also iterate on the indexes in the first place but its cumbersome is there something simpler,['python'] +229199,when should i use synchronousqueue new synchronousqueuenew linkedblockingqueue1what is the difference when i should use synchronousqueue against linkedblockingqueue with capacity 1,['java'] +229210,how to assert that an event has been subscribed to with fakeiteasy i have a fake class that contains an event my code should subscribe to that event and i want to test that i am using fakeiteasy with nunit and i am looking for a way to check that my code actually subscribes to that eventthanks,['c#'] +229215,dynamic assemblies and methods i have programmed net and c for years now but have only recently encountered the dynamicmethod type along with the concept of a dynamic assembly within the context of reflection they seem to always be used within il runtime code generationunfortunately msdn does an extraordinarily poor job of defining what a dynamic assemblymethod actuallty is and also what they should be used for could anyoen enlighten me here please are there anything to do with the dlr how are they different to static normal generation of assemblies and methods at runtime what should i know about how and when to use them,"['c#', '.net']" +229226,error arithmetic overflow error converting numeric to data type varchar error arithmetic overflow error converting numeric to data type varchargetting error at this line why and what should be chnaged convertvarchar8convertdecimal84currentloansprice previousloansprice previousloansprice 100,['sql'] +229248,how to crop camera preview i would like to run a camera preview in a higher resolution of those that are available on the device from this preview i would like to crop a smaller part of the image and then thisplay that scaled in on a surface view so to make it clear an example of what i want to achieve 1 run camera preview let say in 800x600 resolution 2 crop a piece of preview say 400x400 3 scale that to 200x200 and show that on 200x200 surfaceviewas far as i could see the preview is scales automatically to the surfaceview size so this last part is taken care of automatically at least i hope soso how to crop camera preview and scale it,['android'] +229249,how to load content without refresh with multiple querystring i want to load a dynamic content to specific div name with multiple querystring from a menu example dynamic menu linkindexphptag2indexphpcategory1tag2indexphpcategory2tag2location3example query process in php for link indexphpcategory1tag2tag intval gettagcat intval getcategoryifissettag issetcat select dbqueryselect from table where catcat and tagtag fetch resultsquestion with jquery how to tell user clicked the link then send the callback to php process show the results in the specific div name without refresh the pagelet me know,"['php', 'jquery', 'mysql']" +229285,how mature is htmlcss now in relation to generating reports for printing i am considering creating all the reports of a series of desktop business apps directly to html most of the reports are tables maybe compound reports headers footers etc no images vector graphics etc after a search in so i have read lots of post regarding problems with page breaks and things like that i do not need pixel positioning at all but yes control at page breaksfor example let us say i have a big table with currency values and i need the last row of the table per page to thisplay the running totals at that point it is something feasible to do easily or i will run in lots of troublewhat technologies can help me herehtml5javascriptcssphp librarysjquerysome notesthe html will be thisplayed with the chrome or firefox engine embeded so the diferences between browsers it is not a problem for mei can have the php preprocessor embedded if that helps to generate more easily the reports i am just looking fot the best technology at hand to make the work welli am tired of report generators with wysiwyg designers crystal report fastreport reportbuilder etcthanks,"['php', 'javascript', 'html']" +229290,adding variables to dom elements i would like to ask if is legal to add custom variables to document body elementsfor exampledocumentgetelementbyidelem1customvariable xthis code just work but i do not know if it is allowedit does not appear in list of tags arguments but variable is usable in further code,['javascript'] +229343,is there a wpf equivalent to a dom explorer when i am drawing a layout on a webpage using css there can be dozens of rules scattered across dozens of files that could possibly influence how an element is actually thisplayed which is why the dom explorers are such critical tools i can select an element on a browser and see exactly what css rules are being applied to itin wpf there can again be many rules styles and templates and inline attributes and settings injected from the codebehind that could possibly be interacting to determine how a given element is thisplayedis there a way for me to look at an element say a combobox and to quickly determine exactly why it is drawing three times as tall as i think it should,['.net'] +229350,counting with template metaprogramming i have been trying to think up a creative solution to this problem on and off for some time but i have not as of yet been able to i recently considered that it might be solvable with template metaprogramming though i am not sure due to my relative lack of experience with the techniqueis it possible to use template metaprogramming or any other mechanism with the c language to count the number of classes which are derived from some base class such that each derived class is given a unique static class identifierthanks in advance,['c++'] +229351,count the null columns in a row in sql i was wondering about the possibility to count the null columns of row in sql i have a table customer that has nullable values simply i want a query that return an int of the number of null columns for certain rowcertain customer,['sql'] +229370,add contact intent does not return data onactivityresult under ics i want my application to prompt the user to create a new contact through the standard contacts interface on android then i want to be able to read the information back from the newly created contact my code is based on the adding a new contact from this siteintent intent new intentintentaction insertintentsettypecontactscontent typeintentputextracontactscontractintentsinsertphone numberstartactivityforresultintent pick contactand thenoverrideprotected void onactivityresultint requestcode int resultcode intent data intent intent new intentthis fooclass uri uri datagetdata i get nullpointer here on ics intentputextracontact contactaccessorgetinstanceloadcontactthis uri startactivityintent finishthis code runs fine on android 22 and 23 it starts the contacts application and lets the user input stuff like name and email address and when they are done and hit ok or save or whatever it returns to my app and i can read the stuff they entered on android 40 ics however it does not return back to my app when the user is done creating the contact and when i exit the contact view through the back button it does not include any intent with the contact informationwhat intent should i use to get the same behavior on ics,['android'] +229372,systemexit0 vs jframeexit on close is there any difference between the two i was reading an article about that you should always usesystemexit0currently i use jframesetdefaultcloseoperation jframeexit on close the article says that even for a java swing application you should add a listener windowadapter and and call systemexit inside its method windowclosingwindowevent e is there any difference is one method better then the other,['java'] +229375,how to delete an element from a vector while looping over it i am looping through a vector with a loop such as forint i 0 i vecsize i within this loop i check a condition on the element at that vector index and if a certain condition is true i want to delete that elementhow do i delete a vector element while looping over it without crashing,['c++'] +229389,reverse inlines in django admin with more than one model say i have some django models something like thisclass addressmodelsmodel passclass personmodelsmodel address modelsforeignkeyaddressclass storemodelsmodel address modelsforeignkeyaddressclass companymodelsmodel address modelsforeignkeyaddreso in the admin interface i would like to be able to edit a person and have the address inlined i know it is possible to do thisclass addressmodelsmodel person modelsforeignkeyperson blanktrue store modelsforeignkeystore blanktrue company modelsforeignkeycompany blanktrueclass personmodelsmodel passclass storemodelsmodel passclass companymodelsmodel passthen i can do the usualclass addressinlineadmintabularinline model addressclass personadminadminmodeladmin model person inlines addressinlineclass companyadminadminmodeladmin and so onbut this then means that i would have more than one address per person and my address model does not feel right any moreany help will be appreciated,['python'] +229391,sort array by two object properties using anonymous function i have the following arrayarray 0 stdclass object timestamp 1 id 10 1 stdclass object timestamp 123 id 1 2 stdclass object timestamp 123 id 2 i am currently using the following code to sort the array by the timestamp propertyfunction sort comments by timestampcomments prop usortcomments functiona b use prop return aprop bprop 1 1 how can i also sort id by id descending when timestamp is the same,['php'] +229416,assigning a variable inside an if exists clause trying to assign a variable inside an if exists clause for tsqldeclare myvar intif exists select myvar thetablevariwant i thought this would work but apparently not or perhaps more likely i am doing it wrong,['sql'] +229435,calculate thistance given 2 points latitude and longitude possible duplicatemysql latitude and longitude table setup i know this question has probably been asked many times i have researched a lot and i need help with specific thinglets say i have a form and user enters longitude and latitude and i have a database which has table containing longitudes and latitudes how would i search for a point or points in that table that are within 15 miles of radius,['mysql'] +229476,in jsf getting the clients locale to thisplay time in browsers timezone i am writing a webapp in jsf 20 that thisplays timestamps as part of the information to the useri would like the user to see the timestamps localized to their location browsers localeso far whatever i did the timestamps would always appear localized to the timezone of the serveri tried getting the locale with these methodslocale browserlocale facescontextgetcurrentinstancegetviewrootgetlocaleorlocale browserlocale facescontextgetcurrentinstancegetexternalcontextgetrequestlocaleboth returned the servers localei then use the locale object with simpledateformat to print timestampsam i using the correct apii have read somewhere that you have to use client side code javascript to get the browsers timezone is that correct how would you do thatthanks n advanceupdate found this jstimezonedetect javascript code but i am still not sure how to translate the timezone to a java locale object,['javascript'] +229488,role based access control correct mvc pattern i started using the mvc pattern a half year ago and i still have some misunderstandingsnow i want to implement a role based access control in my application however my question is not about rbac it is about mvcmy implementation of rbac is thisuserrolepermissionso every user ex usera can have many roles ex reader editor admin and every role can have many permissions read update delete etcmysql tablesusers list of usersroles list of rolespermissions list of permissionroles permissions list of rolespermissions connections ex editorupdateusers roles list of usersroles connections ex useraeditornow my question ishow should i implement this in mvchave a separate model for users roles permissions roles permissions users roles than have an authmanager class that creates users roles permission roles permissions and user roles is this way correct is there a better maybe more elegant way,['php'] +229495,android get image path from drawable as string is there any way that i can get the image path from drawable folder in android as string i need this because i implement my own viewflow where i am showing the images by using their path on sd card but i want to show a default image when there is no image to showany ideas how to do that,['android'] +229533,what is maximum allowable value of max pool size in sql connection string what is the maximum allowable value of max pool size in a connection stringsuppose this is my connection string in appconfigadd namename providernamesystemdatasqlclient connectionstringdata sourceservernamenetwork librarydbmssocninitial catalogdatabasenameuserusernamepasswordpasswordmax pool size1024poolingtruewhat is the maximum value i can use instead of 1024 remember it is maximum value not default value,['c#'] +229567,is eventcurrenttarget always equal to this in jquery is this phrase always truepclickfunctionevent alert eventcurrenttarget this is one method preferred over the other i like to use this instead of eventcurrenttarget but can one do better in some conditions which is better are absolutely the sameand another nuance when checking on firebug consolelogthis and consolelogthis gives me exactly the same element if they are the same what is different since i know i can write this thiscsscolorwhite but cannot write thiscsscolorwhite,"['javascript', 'jquery']" +229569,memory size of classes in objectivec i am interested in knowing the size of memory allocating some objectivec objectsfor example is nsstring stringwithstring2 bigger than nsnumber numberwithint2 or not and how much bigger is nsnumber numberwithint2 than int num2 is there some documentation from apple about this question i think this information is very important for memory optimisation,"['iphone', 'ios']" +229577,mysql or condition check out this mysql query and then i will show you what i really want it to domysql queryselect from drinks where emailemail and datedate today or datedate yesterday or datedate twodaysago or datedate threedaysago or datedate fourdaysago or datedate fivedaysago or datedate sixdaysago or datedate sevendaysagothe problem with it is that i want it to always match the email in this case for example if the date equals date sixdaysago then it will be selected from the query even if email does not equal the email columnso in short i want the email to always equal the email column and if the query pulls a date that equals daye twodaysago or date threedaysago etc but does not equal the email then do not pull iti guess my query would look kind of like this but i am pretty sure it would not workmysql query select from drinks where emailemail and datedate today date yesterday date twodaysago date threedaysago date fourdaysago date fivedaysago date sixdaysago date sevendaysago,"['php', 'mysql']" +229603,xpath queries in ie use zerobased indexes but the w3c spec is onebased how should i handle the difference the problemi am converting a relatively large piece of javascript that currently only works on internet explorer in order to make it work on the other browsers as well since the code uses xpath extensively we made a little compatibility function to make things easierfunction selectnodesxmldoc xpath ifselectnodes in xmldoc use ie logic else use w3cs documentevaluate this is mostly working fine but we just came across the limitation that positions in ie are zerobased but in the w3c model used by the other browsers they are onebased this means that to get the first element we need to do books0 in ie and books1 in the other browsersmy proposed solutionthe first thought was using a regex to add one to all indexes that appear in the queries if we are using the documentevaluate versionfunction addonen return 1 parseintnstr 10 xpath xpathreplace sdsg function nstr return addonenstr my questionis this regex based solution reasonably safeare there any places it will convert something it should notare there any places where it will not convert something it shouldfor example it would fail to replace the index in booksposition1 but since ie does not appear to support position and our code is not using that i think this particular case would not be a problemconsiderationsi downloaded sarissa to see if they have a way to solve this but after looking at the source code apparently they do noti want to add one to the w3c version instead of subtracting one in the ie version to ease my conversion effortin the endwe decided to rewrite the code to use proper xpath in ie too by setting the selection languagexmldocsetpropertyselectionlanguage xpath,['javascript'] +229627,why are not generic type constraints inheritablehierarchically enforced item classpublic class item public bool checkint value base abstract class with generic type constraintpublic abstract class classbasetitem where titem item protected ilisttitem items public classbaseienumerabletitem items thisitems itemstolist public abstract bool checkallint valueinherited class without constraintspublic class myclasstitem classbasetitem public override bool checkallint value bool result true foreachtitem item in thisitems if itemcheckvalue this does not work result false break return result i would like to know why are not generic type constraints inheritable because if my inherited class inherits from base class and passes over its generic type which has a constraint on the base class it automatically means that generic type in inherited class should have the same constraint without explicitly defining it should not itam i doing something wrong understanding it wrong or is it really that generic type constraint are not inheritable if the latter is true why in the world is thata bit of additional explanationwhy do i think that generic type constraints defined on a class should be inherited or enforced on child classes let me give you some additional code to make it bit less obvioussuppose that we have all three classes as per above then we also have this classpublic class danteitem public string converthelevelint value as we can see this class does not inherit from item so it cannot be used as a concrete class as classbasedanteitem forget the fact that classbase is abstract for now it could as well be a regular class since myclass does not define any constraints for its generic type it seems perfectly valid to have myclassdanteitembut this is why i think generic type constraints should be inheritedenforced on inherited classes just as with member generic type constraints because if we look at definition of myclass it saysmyclasst classbasetwhen t is danteitem we can see that it automatically cannot be used with myclass because it is inherited from classbaset and danteitem does not fulfill its generic type constraint i could say that generic type on myclass depends on classbase generic type constraints because otherwise myclass could be instantiated with any type but we know it cannot beit would be of course different when i would have myclass defined aspublic class myclasst classbaseitemin this case t does not have anything to to with base class generic type so it is independent from itthis is all a bit long explanationreasoning i could simply sum it up byif we do not provide generic type constraint on myclass it implicitly implies that we can instantiate myclass with any concrete type but we know that is not possible since myclass is inherited from classbase and that one has a generic type constrainti hope this makes much more sense now,['c#'] +229653,jquery datatables header misaligned with vertical scrolling i have posted this in the datatablesnet forums but after a week still no response hopefully i can find help herei am using datatables version 181 and am having nightmares over column header alignment with vertical scrolling enabled with the code posted below the headers line up correctly in firefox and ie8 and ie9 but chrome and ie7 are off i am using a lot of datatables on this project and this is a problem with every one i am desperate for helpedit i have figured out that this has something to do with setting the width of the table the datatable takes the width of its container if i set no width everything lines up fine but the table is too big for where i need it on the page if i give the tables div or a parent div somewhere higher up a width at all the headers do not line up properlythanksscreenshotswdennissheppardnetfirefox alignmentpngwdennissheppardnetchrome alignmentpngwdennissheppardnetie7 alignmentpngotable order review griddatatable fnrowcallback function nrow strings thisplayindex dataindex return formatrownrow dataindex fndrawcallbackfunction checkifordersubmittedthis aocolumndefs bvisible false atargets col product bsortable false atargets col image col delete sclass right align atargets col price sclass center align atargets col brandcol pack sclass left align atargets col description sdom t sscrolly405px bscrollcollapsetrue aasortingtable idorder review grid classgrid table cellpadding0px cellspacing0px thead classgrid column header row idorder review grid column header row tr td class idsequencenumberseq td td classgrid sc header idstatuscodesctd td classgrid sc header idonorderguideogtd td classgrid image header idimageimagetd td classgrid description header iddescriptiondescriptiontd td classgrid brand header idlabelbrandtd td classgrid pack header idpacksizepacktd td classgrid price header idpricepricetd td classgrid qtrfull header idcasequantityfulltd td classgrid qtrypart header ideachquantitypartialtd td classgrid refnum header idreferencenumberref td td classgrid refnum headernbsptd tr thead tbody class loaded data will go here tbodytable,"['javascript', 'jquery', 'html']" +229667,tomcat http keepalive and javas httpsurlconnection i have two tomcat servers that need to maintain a persistent connection to cut down on ssl handshaking one server the proxy sits in a dmz while the other one is safely behind another firewall the proxy basically just runs a simple servlet that does some sanity checking before forwarding requests over to the secure machine on an intial request the machines exchange certificates before performing the real work therefore i would like to maintain a persistent connection with a timeout of a few minutesto talk to the secure server the servlet on the proxy uses httpsurlconnection i have set up wireshark and i have noticed that no matter what keepalivetimeout value i set for connector on the secure machine the tcp connection gets closed after about 5 or 10 seconds this number seems to match up with what i have read is the default timeout and how java handles http keepalive this link explains that java honors the keepalive timeout if it is sent by the server otherwise it uses 5 seconds direct connections or 10 seconds proxy connections before it closes the connectionwhat i am trying to figure out is how can i force tomcat to send the keepalive header not connection keepalive but keepalive timeoutxi have experimented with apache http server and modifying the keepalivetimeout in httpdconf does cause the keepalive header to change its timeout value furthermore java does honor this timeoutupdate 122311 after running a few more experiments i tried whipping up some quick and dirty code using apache is httpclient 31 rather than httpsurlconnection it appears that httpclient when set to use keepalive simply waits for the server to close the connection i do not know how long it will wait though i am shooting to keep the http connection alive for 3 to 5 minutes,['java'] +229692,avplayeritem fails with avstatusfailed and error code cannot decode i am running into a strange issue i hope someone can help in my ios app i create a video with a custom soundtrack using mutablecomposition by combining a video from the users photo library and an audio file from the app bundle i then use an avplayer and avplayeritem to play the video back to the user using a custom video player i madeeach time a new composition is created the assets the player and the composition are cleared released and it basically starts from a clean init state all works fine until after exactly 4 successful videos created this way every other attempt to create the player fails with error cannot decode it does not matter if its the same video i am recreating has no relation to the sizelength of the video or the audio file it simply always fails exactly on the fifth attempt like clockwork once it fails it will then always failthis is weird because it just decoded the same video four times with no problem so all of a sudden it fails so if anyone has a clue please let me know,"['iphone', 'ios']" +229697,how to test facebook like button working on integrating the like button into a sitethe site is currently running on xampp in localhost mode not visible anywhere outside this computerupon the site user clicking the button i need to log the event into the database i have their information from a form they filledout prior to even seeing the buttonheres my problem i am trying to debug the code that does a lot of this however if i click on the like button just one time it is forever grayedout after that i can clear cookies on firefox and get the button back this also means that i have to login to fb again this makes for a very difficult debugging session surely there is a better way,"['php', 'javascript']" +229701,intellij organize imports does intellij have an organize imports feature similar to that in eclipsewhat i have is a java file with multiple classes missing their imports examplepackage comtestpublic class foo public map map public jtable tablein eclipse i could use organize imports and it would automatically import both javautilmap and javaxswingjtable in intellij i have to individually go to each class select it then press altenter there is an optimize imports feature but all it seems to do is sort and expand the existing importsi am using intellij 105,['java'] +229704,given 10 functions yabx and 10s of xy data points rounded to ints how to derive 10 best ab tuples we build software that audits fees charged by banks to merchants that accept credit and debit cards our customers want us to tell them if the card processor is overcharging them pertransaction credit card fees are calculated like thisfee fixed variabletransaction pricea fee scheme is the pair of fixed variable used by a group of credit cards eg mastercard business debit gold cards issued by first national bank of hollywood we believe there are fewer than 10 different fee schemes in use at any time but we are not getting a complete nor current list of fee schemes from our partners yes i know that some fee schemes are more complicated than the equation above because of caps and other gotchas but our transactions are known to have only a bx schemes in use heres the problem were trying to solve we want to use pertransaction data about fees to derive the fee schemes in use then we can compare that list to the fee schemes that each customer should be using according to their bank the data we get about each transaction is a data tuple card id transaction price fee transaction price and fee are in integer cents the bank rolls over fractional cents for each transation until the cumulative is greater than one cent and then a rounding cent will be attached to the fees of that transaction we cannot predict which transaction the rounding cent will be attached to card id identifies a group of cards that share the same fee scheme in a typical day of 10 transactions there may be several hundred unique card ids multiple card ids will share a fee scheme the data we get looks like this and what we want to figure out is the last two columnscard id transaction price fee fixed variable12345 200 22 67890 300 21 56789 150 8 34567 150 8 34567 150 rounding cent 9 34567 150 8 the end result we want is a short list like this with 10 or fewer entries showing the fee schemes that best fit our data like this fee scheme id fixed variable1 22 02 21 03 4 the average fee is about 8 cents this means the rounding cents have a huge impact and the derivation above requires a lot of data the average transaction is 125 cents transaction prices are always on 5cent boundaries we want a short list of fee schemes that fit 98 of the 30 transactions each customer gets each day if that is not enough data to achieve 98 confidence we can use multiple days of data because of the rounding cents applied somewhat arbitrarily to each transaction this is not a simple algebra problem instead it is a kind of statistical clustering exercise that i am not sure how to solve any suggestions for how to approach this problem the implementation can be in c or tsql whichever makes the most sense given the algorithm,"['c#', 'sql']" +229715,how to wrap each word of an element in a span tag divdate contents filter function return thisnodetype 1 wrapspani am new and thought that code would have done the trick but it wraps everything in the span like sodiv classdatespandec 22 2011spandivit is supposed to look like thisdiv classdate spandecspan span22span span2011spandiv,"['javascript', 'jquery']" +229730,how to find out timezone of specific datetime in specific location i have dates of events in another country which i need to save in database problem is that those dates have no timezone information included timezone used in this location is cet standard time or cest summer timewhat is the easiest way to detect which one is in play,['php'] +229753,implications of using an ampersand before a function name in c given the example inline string getlabel return m labelwhere m label is a private class member variable the way i think i understand it this function will return a reference to the variable m label what would be the implications of using this throughout my program and would it be a better to just return the value instead of the reference thank you,['c++'] +229770,how do i create an android intent that carries data i might have misunderstood how intents are supposed to be used so i might be asking the wrong thing here if that is the case please help me get on the right track with this anywayi have just started working on an android app that will poll my server for messages every so often and when a new message is available i want to show it to the user i am trying to implement this by having a service that polls the server and when a new message is received the service should give the message to an activity that shows itto facilitate this communication i am trying to create an intent with action view but i cannot figure out how to give the message to the activity is there no way to pass a string or a regular java object via the intentfor what it is worth this is what i would like to dogetapplicationstartactivitynew intentmessageservicethis viewmessageactivityclass messagebut of course that does not even compile,['android'] +229794,how exactly does function work i have seenfunction code used in several places to immediately execute an anonymous function normally it is used in lieu offunction code anyone know how the actually makes the function execute,['javascript'] +229802,javascript random positive or negative number i need to create a random 1 or 1 to multiply an already existing number by issue is my current random function generates a 1 0 or 1 what is the most efficient way of doing this,['javascript'] +229807,piracy piracy piracy what can i do i have just released an app a paid app 4 days later a user told me there is another web site in china hosts my app i downloaded it from there and it does run fine on my device there are posts here saying people can change the package name and republish an apk but this is not my case the cracked version still uses the same package name i used android vending licensing in the program but the cracked version does not do licensing check at all i used proguard to obfuscate it but that does not thiscourage the hackersquestion 1 i signed the apk file according to googles instructions but still they modified the code and took out the licensing check part am i wrong that signing an apk file is designed to keep people from tampering with the file contentquestion 2 for win32 exe programs i used to use a checksum to determine if the file has been altered this is how it works when a exe is created i used a tool to calculate the sum of byte contents of the file then stuff it into somewhere in the file for example 4 bytes after a text pattern my signature then at run time the program opens the exe file and calculates the byte sum compares it with the integer after the signaturehas anybody tried this approach on apk files care to share your experiences,['android'] +229815,array of php objects so i have been searching for a while and cannot find the answer to a simple question is it possible to have an array of objects in php such asararray arobj1 arobj2for some reason i have not been able to find the answer anywhere i assume it is possible but i just need to make sure,['php'] +229827,fetching connection string from appconfig file in c i have the following connection string declared in my appconfig file connectionstrings add namesqlconnectionstring connectionstringdata sourcexinitial catalogxuser idxxpasswordx providernamesystemdatasqlclient connectionstringswhen i try to fetch this connection string using the following c code snippet i get the value null i am not able to obtain the connection string is there anything wrong in the syntaxfirst attemptvar settings configurationmanagerconnectionstringssqlconnectionstringstring result settingsconnectionstringsecond attemptstring result configurationsettingsappsettingssqlconnectionstring,['c#'] +229859,c excel interop put a line break in the text of a cell in a excel i am writing an excel sheet using interop in the sheet i need to put a set of sentences in to a cell the text should be in a line break manner how can i achieve thisthanks in advance,['c#'] +229878,using propertiessettings for application settings i use the builtin settings provided by visual studio to store simple application settings until now i have accessed this in my application by using the conventionpropertiessettingsdefaultmysettingand then call methods like save by usingpropertiessettingsdefaultsavehowever someone recently told me that it is more correct to access the properties by creating a member variable like thisprivate propertiessettings settings new propertiessettingsand then using the member settings to access properties and methods likesettingsmysettingsettingssavei vaguely recall that they justified this by describing differences in the way the settings are stored in the users areacan anyone confirm or give further details on the differences many thanks,['c#'] +229881,automatically login to current website if user is logged in to another website i have about 100 websites coded in asp classic each website accepts orders and stores them in database however the payment of these orders must be made on another website also coded in asp classic all websites are owned by same company hosted on same iis server and use the same sql server database now the user registers by entering some personal information and logs in to one of these website eg websitefornewjerseycom and places an order he is then redirected to the payments website paymentsmasterwebsitecom on https where some of his personal information address city state for shipping name for credit card holders name etc appears on the payment form credit card specific information is entered on that pagebecause of the sensitivity of information shown on that page the user must login to the payment website before heshe can view the prefilled payment form and i do not want the user to login twice once on each website is there a reliable way of checking if the user is logged in to the referring website using classic asplong story shorton website b i need to check if the visitor is logged into website aon website b i need the id session variable from website aboth websites use same database serveri need clear instructionsphp or aspnet solution is acceptable if it is genericportable,"['php', 'asp.net']" +229894,paste from excel into c app retaining full precision i have data in an excel spreadsheet with values like this069491375031220394the cells are formatted as percentage and set to thisplay two decimal places so they appear in excel as69493122i have a c program that parses this data off the clipboardvar dataobj clipboardgetdataobjectvar format dataformatscommaseparatedvalueif dataobj null dataobjgetdatapresentformat var csvdata dataobjgetdataformat do somethingthe problem is that csvdata contains the thisplay values from excel ie 6949 and 3122 it does not contain the full precision of the extra decimal placesi have tried using the various different dataformats values but the data only ever contains the thisplay value from excel egdataformatsdifdataformatsrtfdataformatsunicodetextetcas a test i installed libreoffice calc and copypasted the same cells from excel into calc calc retains the full precision of the raw dataso clearly excel puts this data somewhere that other programs can access how can i access it from my c applicationedit next stepsi have downloaded the libreoffice calc source code and will have a poke around to see if i can find out how they get the full context of the copied data from exceli also did a getformats call on the data object returned from the clipboard and got a list of 24 different data formats some of which are not in the dataformats enum these include formats like biff12 biff8 biff5 format129 among other formats that are unfamiliar to me so i will investigate these and respond if i make any thiscoveries,['c#'] +229908,start an android appintent from an nfc tag on an android device equipped with nfc reader hardware is there any inbuilt support to use the nfc tag contents to fire off an intent eg starting an app i am asking whether the support is there by default i know i could build my own app to listen for nfc events and handle themall the nfc tag writing apps i have seen appear to only support texturlscontacts and the contacts support seems useless as many are far too big to fit in a tag,['android'] +229931,jquery if statement to check visibility i am trying to write a script that will hiddenshow div depending on other elements visibility the action should take place when i click on other element heres what i have wrote so farcolumnleft formhide showsearchclickfunction columnleft formstoptrue trueslidetoggle300 if columnleft formcssthisplay none offersshow else offershide it hides the div but it does not come back when i hide the form will be greatful for any help editok i have managed to achive the desired effect by writing thiscolumnleft formhide showsearchclickfunction if columnleft formishidden columnleft formslidetoggle300 offershide else columnleft formslidetoggle300 offersshow i do not know if it is written correctly but it works thanks everybody for help,['jquery'] +229939,how to check if a variable is a number or a string how to check if a variable is a number or a string in ruby,['ruby'] +229956,integer division in c11 i was noticing some wording changes to section 56 for c11 i am looking at the draft c standard n3242 dated 20110228 the new draft standard includes the sentencefor integral operands the operator yields the algebraic quotient with any fractional part thiscardedthis statement is not in 56 of the 03 standard isoiec148822003 but i do not think this is a change is it this is how c and c has worked for years unless i have lost my mind which may have happened anyway,['c++'] +229958,classes generated by custom t4 generator look messy after running the generator output files with code look really thisordered i know i will probably never look into those files but it is nice to see generated code nicely structured while developing a generatorany suggestions are welcome,"['c#', '.net']" +229959,double negation in c is it guaranteed to return 01 is x guaranteed by the standard to return 01note that i am not asking about c where a bool type is defined,['c'] +229975,recursive search for a node in nonbinary tree i want to search for an item in nonbinary tree any node can have and children and exit from recursion immediately the node in question can be any node not only leafsthis is my code but i do not get complete searchprivate nnode recursivesearchdata ginnode node if nodegetdatagi return node nnode children nodegetchildren if childrenlength0 for int i 0 i childrenlength i return recursivesearchgi childreni return null nnode contains arraylist mchildren it is childrenand data object,['java'] +229977,creating c structs in cython i would like to create my very own list container using cython i am a very new begginer to it and following the documentation i could get to creating such a structure cdef struct s intlist int value void nextctypedef s intlist intlistbut when comes the time to acces the struct members i cannot find the good syntaxcpdef void foo cdef intlist li livalue or livaluethrows warning intlistspyx812 local variable li referenced before assignmentwhich let me assume that my cython structs usage is incorrectany idea of what i am doing wrong here please thank you for you help,"['python', 'c']" +229980,stdexception subclass string member variable the following code works just fineinclude exceptionusing namespace stdclass fileexception public exception error occurs here int error string error this would cause the errorpublic fileexceptionint error fileexceptionstring error const char what const throwbut as soon as i change the type of error to string the following compile error occursexception specification of overriding function is more lax than base version,['c++'] +229984,javascript oddness with array of objects and indexof not quite grasping whats going on here given the array arr first name dan last name woodson id 1 first name jen last name woodson id 2 first name yoshi last name woodson id 3 and the object obj first name yoshi last name woodson id 3why would arrindexofobj return 1 especially since i retrieved the object from the array using it is id parameter earlier in the function,['javascript'] +229986,using a blocks return value in javascript on a lot of browsers i have tested javascript blocks actually return a value you can test it out in any consoleforvar i 0 i 10 i var sqrt mathsqrti ifmathfloorsqrt sqrt i the return value is the last square number that is 9 but since it is not an expression i suppose you cannot do thisforvar i 0 i 10 i 5that does not work it gives 5 or 5 of course because it is a separate statement putting the loop in parentheses obviously fails and if a block is in parentheses eg f r does not work it is treated as an object and throws a syntax errorone way to take advantage of the return value as such is to use evalevalforvar i 0 i 10 i var sqrt mathsqrtiifmathfloorsqrt sqrt i 5 14but i am obviously not going to want to use that if eval is the only solution is there a way to use a blocks resultant value without using eval that i am missing i really like this feature,['javascript'] +229996,thisplaying a loading gif for 5 seconds automatically i want to thisplay a loading gif automatically when the user goes to the website and then after 5 seconds it goes awayi found this script which does what i want but it does not do it automatically the user needs to click on the button to start it which kind of defeats the purposeinput type button value show image for 5 seconds onclick showbrbrdiv id mydiv stylethisplaynoneimg id myimage src imagesajaxloadergifdivbrscript type textjavascriptfunction show documentgetelementbyidmydivstylethisplayblock settimeouthide 50 5 secondsfunction hide documentgetelementbyidmydivstylethisplaynonescriptyou can see it hereif there is any way in which i can do this or if there is a better way of doing it please just comment,['javascript'] +230000,unit test accessing private variables i have a unit test class tester i want it to access private fields of a working classclass working private int m variableclass tester void testvariable working w test wm variable i have the following optionsmake m variable public uglymake method test getvariable overcomplicatedadd friend class tester to working then working knows about the tester explicitly which is not goodmy ideal would be class working private int m variable friend class testbaseclass testbase class tester public testbase void testvariable working w test wm variable where working knows about testbase but not each test but it does not work apparently friendship does not work with inheritance what would be the most elegant solution here,['c++'] +230034,backbonejs using trigger to trigger event and pass data i am writing a tab menu component using backbonejs as an mvc framework when a user clicks on a tab the component will switch tabs internal operation but then i would like listeners of the component to respond to the action associated with the event the idea behind this is that i am abstracting the various clicks into specific actions for instance the model for each tab is a hash with the following structure label string actioncommand save tabclass stringthe event that will be triggered will be called action so listeners will respond to action but will then forward the specific command for instancethistriggeraction actioncommand savethe listener in turn would handle the event similarly to the followinghandleaction functionevent if eventactioncommand save do something is this possible i could not glean this from the documentation thanks in advance for any insight you can offer,['javascript'] +230037,why does auto attribute for margin not work vertically while it works horizontally i have seen that while developing websites vertically centering a container of fixed height inside a container of random height always comes as a nightmare for the web developer at least me while when it comes to horizontal centering a container of fixed width inside a container of random width the margin0px auto tends to serve an easy way out in the standard modelwhen things can be as simple as that why does not css work out with the marginauto 0px when it comes to centering a container of fixed height inside a container of random height is there any specific reason to do so thanks for your insights in advance,"['html', 'css']" +230047,video processing in android i am using android 22 with eclipsei would like to make an application that captures video and for each frame its send it as a bitmap to a method that processes it and returns a new bitmap and shows the processed bitmapi am not very familiar with android so please can anyone send me to the resources i need to look at to do such a thing,"['java', 'android']" +230065,why are collection initializers on reassignments not allowed i always thought it worked fine both ways then did this test and realized it is not allowed on reassignmentsint a 0 2 4 6 8works fine but notint aa 0 2 4 6 8 any technical reason for this i thought i would ask about it here because this behavior was what i expected intuitively,"['c#', '.net']" +230079,rails activerecordhasmanythroughsourceassociationnotfounderror could not find the source associations i have the following code somewhat simplified create table signatures do t tinteger signer id tinteger card id ttimestampsendwith the models looking like class signature activerecordbase belongs to card belongs to userendclass card activerecordbase has many signatures has many signers through signatures foreign key card idendclass user activerecordbase has many sent cards class name card foreign key sender id has many received cards class name card foreign key recipient id has many signatures has many signed cards through signatures foreign key signer idendi see the following error using the rails console ruby192p0 u15signed cardsactiverecordhasmanythroughsourceassociationnotfounderror could not find the source associations signed card or signed cards in model signature try has many signed cards through signatures source name is it one of card or user from homeslabountyrvmgemsruby192p0gemsactiverecord310libactive recordreflectionrb517in check validity from homeslabountyrvmgemsruby192p0gemsactiverecord310libactive recordassociationsassociationrb27in initialize from homeslabountyrvmgemsruby192p0gemsactiverecord310libactive recordassociationscollection associationrb24in initialize from homeslabountyrvmgemsruby192p0gemsactiverecord310libactive recordassociationsrb164in new from homeslabountyrvmgemsruby192p0gemsactiverecord310libactive recordassociationsrb164in association from homeslabountyrvmgemsruby192p0gemsactiverecord310libactive recordassociationsbuilderassociationrb41in block in define readers from irb11 from homeslabountyrvmgemsruby192p0gemsrailties310librailscommandsconsolerb45in start from homeslabountyrvmgemsruby192p0gemsrailties310librailscommandsconsolerb8in start from homeslabountyrvmgemsruby192p0gemsrailties310librailscommandsrb40in top required from scriptrails6in require from scriptrails6in maini get the same thing when i do add the source carduser should be card in this case i believeany ideas what i am doing wrong hereshowing a partial solution because i wanted to clean up afew things the migration remained the same as the previous version i am nowseeing a sql error see below where it cannot find user id in signature ihate to say it but mostly i have been putting in foreign key whereever i thinkthey might help to no avail class signature activerecordbase belongs to card belongs to signer class name user end class card activerecordbase correct has many signatures has many signers through signatures source user end class user activerecordbase wrong has many signatures foreign key signer id has many signed cards through signatures source card endwith the error minus stack traceruby192p0 u15signed cards card load 05ms select cards from cards inner join signatures on cardsid signaturescard id where signaturesuser id 15 order by cardscreated at descsqlite3sqlexception no such column signaturesuser id select cards from cards inner join signatures on cardsid signaturescard id where signaturesuser id 15 order by cardscreated at descactiverecordstatementinvalid sqlite3sqlexception no such column signaturesuser id select cards from cards inner join signatures on cardsid signaturescard id where signaturesuser id 15 order by cardscreated at desccardsigners returns an empty array as expectedstill looking for some help on this one i have not been able to locate much in the way of simple straightforward explanations of this where youre not using the same names ie you need a foreign key and source,"['ruby-on-rails', 'ruby']" +230102,javascript iif like statement coming from vb javascript is not very easy to get the hang of please do not be negative i have tried and searched loads but with no luck btw i am creating a dropdown control initialized from a select option list in jsdummy codevar col tarthis var x option value col very roomyoptioni would like to add selected after the value of col only if col is equal to screwdriveri have tried using the if statement with the and the but cannot seem to get my head around it having as the false value does not work no items are selected and the list is blank remove the if statement and all worksany ideas and again sorry for the newbness,['javascript'] +230153,autostart application not working properly i am having a simple autostart application with timertask implementation that works fine in almost many devices the problem is that it is not working in samsung galaxy y236 and dell xcd3522 when the device boots timertask works for some seconds and then shuts down i check in the applicationmanage application i saw that the applcation was already in force stop state that means some how my application gets stopped after some seconds so what is the reason for this weird behaviour in these two devices if anyone has the solution do share itbelow is my codemyreceiverjavapublic class myreceiver extends broadcastreceiver private timer mtimer new timer override public void onreceivecontext context intent arg1 toastmaketextcontext device booted toastlength longshow logdtagdevice booted mtimerscheduleatfixedratenew mytimertask 2020 private class mytimertask extends timertask override public void run logdtagtimertask executed androidmanifestxmlxml version10 encodingutf8manifest xmlnsandroid packagecomautostartapp androidversioncode1 androidversionname10 usessdk androidminsdkversion8 usespermission androidnameandroidpermissionreceive boot completed application androidicondrawableic launcher androidlabelstringapp name receiver androidnamemyreceiver intentfilter action androidnameandroidintentactionboot completed intentfilter receiver applicationmanifest,['android'] +230160,passing a variable into a jinja import or include from a parent html file the scenario would be you have a variable called person which contains a number of fields like name address etc which you want to pass to a partial piece of html this solution could be results from a search for customers for examplesnippethtmldiv iditem ul li spannamespan spanaddrespan li uldivmypagehtmldiv idresult include snippethtml passing person divwhat is the best way to achieve this in the documentation it talks about passing context around everywhere but that seems to me to be a rather large object when rendering templates surely it is easier to pass specific objects into each template,['python'] +230174,store run configuration with project in eclipse i am programming in netbeans however i like to get used to eclipse as well i have a maven project what i have developed in netbeans and after importing it compiles fine in eclipse i am using the run or debug feature of netbeans a lot and it is very comfortable that the run configuration gets stored with the project so i can actually commit it into version control and others can use it as well say i have a java application project which has a main class to run this i need to define the correct class path for the exec goal actually netbeans automatically does this for me when creating the new project in eclipse i have to define run configurations which as far as i know gets stored in the workspace but not in the project is there any similar feature in eclipse what i am looking for,['java'] +230178,why to use returned instance after save on spring data jpa repository here is the coderepositorypublic interface accountrepository extends jparepositoryaccount long jparepository from spring data jpa projecthere is the testing codepublic class jpaaccountrepositorytest extends jparepositorytest inject private accountrepository accountrepository inject private account account test transactional public void createaccount account returnedaccount accountrepositorysaveaccount systemoutprintfaccount id is d and for returned account id is dn accountgetid returnedaccountgetid here is the resultaccount id is 0 and for returned account id is 1here is from crudreporsitorysave javadocsaves a given entity use the returned instance for further operations as the save operation might have changed the entity instance completely here is the actual code for simplejparepository from spring data jpa transactional public t savet entity if entityinformationisnewentity empersistentity return entity else return emmergeentity so the question is why do we need to use the returned instance instead of the original one yes we must do it otherwise we continue to work with detached instance but whythe original entitymanagerpersist method returns void so our instance is attached to the persistence context does some proxy magic happens while passing account to save to repository is it the architecture limitation of spring data jpa project,['java'] +230213,runtime check failure 0 the value of esp was not properly saved across a function call i created a simple program that demonstrates the runtime error i am getting with my qt application that uses multiple inheritance the inheritance tree looks likeqgraphicsitem abstract qgraphicslineitem myinterface abstract mysubclassand here is the code maincpp include qapplicationinclude qgraphicssceneinclude qgraphicslineitemsimple interface with one pure virtual methodclass myinterfacepublic virtual void myvirtualmethod 0multiple inheritance subclass simply overrides the interface methodclass mysubclass public qgraphicslineitem public myinterfacepublic virtual void myvirtualmethod int mainint argc char argv qapplication appargc argv init qapplication qgraphicsscene scene new qgraphicsscene create scene sceneadditemnew mysubclass add my subclass to the scene q foreachqgraphicsitem item sceneitems should only have one item myinterface minterface myinterfaceitem cast as myinterface minterfacemyvirtualmethod this causes the error return 0debugging in visual studio results in a runtime error when my interface method is called runtime check failure 0 the value of esp was not properly saved across a function call this is usually a result of calling a function declared with one calling convention with a function pointer declared with a different calling conventionany idea what the problem is,['c++'] +230219,c parse string to type known at runtime i have a file holding some of the variables of a class and each line is a pair variable value i am looking for a way to load these at runtime ala xmlserializer using reflectionis there a way to parse a string into a type known only at runtimethe following is a wishful code sample where the last line with the pisetvalue is not correct because propertytype is of class type which does not have a generic parse methodusing var sr new streamreadersettingsfilename string line while line srreadline null string configvaluestrs linetrimsplitseps propertyinfo pi configurablepropertiessinglep pname configvaluestrs0trim pisetvaluethis pipropertytypeparseconfigvaluestrs1trim null how do i manage this since all of the relevant variables are ints doubles strings or booleans as a last resort i can switch on the type and use the corresponding totype method but i bet there is a more elegant solution,['c#'] +230224,can i create a node in neo4j with specified id i want to hold relationships in neo4j but maybe i have not decided yet to keep the objects in different db sort of rethisand if to do so it would be good to sync ids in storage db and in neo4jso can i create a node in neo4j passing the id to itpsproject in php and accessing neo4j via rest api,['php'] +230237,is cc pointer keeps absolute memory address or relative to application or relative to module for example if i declare a function in the main application and a pass a pointer to it from a dynamically loaded library via dlopen under linux or loadlibrary under windows using a gotten symbol argument via dlsym or getprocaddress respectively and try to call that function would it work properlysame if pass pointer from one dynamically loaded library to another i think it should work if pointer at least relative to application but not relative to modulelibraryanother example i declare a function in one application and pass pointer to it to another fullyindependent application both c and c somehow parameter string or file io idk how just an idea and try to call this function would it work too i could expect it to work if the pointers are absolute maybe it just would not work because system would not like such crosscall at all because of safety,['c++'] +230245,replace a uiviewcontroller in the uinavigationcontroller hierarchy i have an iphone app which uses a standard implementation of uinavigationcontroller for the app navigationi am trying to figure out a way to replace a view controller in the hierarchyin other words my app loads into a rootviewcontroller and when the user presses a button the app pushes to firstviewcontroller then the user pushes another button to navigate the app to secondviewcontroller again the use navigates down to another view controller thirdviewcontroller however i want the backbutton of the thirdviewcontroller to pop back to firstviewcontroller essentially when the user pushes to thirdviewcontroller i would like it to replace secondviewcontroller in the navigation hierarchyis this possible i know it is using three20 but i am not in this case nevertheless if it is possible in three20 then it certainly should be using straight sdk calls does anyone have any thoughtscheersbrett,"['iphone', 'objective-c']" +230261,why is my text not aligning properly in wxpython i am using wxpython to build a gui and i am trying to align some text but it is not working at alli am trying align three different static text items in three places right aligned center aligned and left aligned in three seperate panels the result that i am getting though is that all three static text controls are aligned in the top left corners of their respective panelsthis is code i have selflasttextwxstatictextselftextthisplaypanel1 labelselflastwords stylewxalign right selfcurrenttextwxstatictextselftextthisplaypanel2 labelselfcurrentwords stylewxalign centre selfnexttextwxstatictextselftextthisplaypanel3 labelselfnextwords stylewxalign leftany ideas on how i fix thisthank youi am running mac osx 1072 with python 271 and wxpython 28121,['python'] +230310,how to add video playback and resource to android application i have got problem with my idea on andriod app i would like to play video in it but i do not want to download it from interenet in other case i want to have it on device so person is download it from android market and can play video without downloading it i have came up with some solutions for it but none is good first one was adding it to application resources but you cannot have video in theresecond one was adding or better creating folder during install more specyfic first oncreate method and then copying there video from app well not so bad option you can for example download then one time only video from web using background service but i have no idea how to delete in on uninstall since your app dont know when it is unistalledso does anyone know or have any idea on it,['android'] +230317,how to force windows to reconnect to network drive we try to access a directory which is within a network directory but get wrong results cwindowsvar exists directoryexistszsessionsdata1z is the network directory sessions is a directory where a recording software constantly creates directories eg data1 and puts some data in itit seems that windows caches the wrong state about data1 the method returns false but when i access the directory via explorer it is here when i run the method directoryexists after accessing the directory with explorer it returns true of course i can guarantee that the directory actually exists at the first attemptwhat is the reason for this behaviour what can i do about iteditit seems that windows could not connect the network drive to the remote computer when i try to navigate into the directory with explorer it automatically tries to connect the driveso the question changesis there a way to force windows to try a reconnect via netsolutionreconnecting a thisconnected network drive,"['c#', '.net']" +230327,call to pure virtual function from base class constructor i have a base class mybase that contains a pure virtual function void printstartmessage 0i want each derived class to call it in their constructorthen i put it in base classmybase constructor class mybase public virtual void printstartmessage 0 mybase printstartmessage class derivedpublic mybase public void printstartmessage void main derived derived but i get a linker error this is error message 1 build started project s1 configuration debug win32 1compiling 1s1cpp 1linking 1s1obj error lnk2019 unresolved external symbol public virtual void thiscall mybaseprintstartmessagevoid printstartmessagemybaseuaexxz referenced in function public thiscall mybasemybasevoid 0mybaseqaexz 1cusersshmueliandocumentsvisual studio 2008projectss1debugs1exe fatal error lnk1120 1 unresolved externals 1s1 2 errors 0 warningsi want force to all derived classes to a implement itb call it in their constructor how i must do it,['c++'] +230340,how to read post data in a jersey based restful webservice how do i read the data which i pass in a post or put method using d option in curlcurl xput hostportservice d some datais there an annotation similat to like queryparam for query parameters,['java'] +230342,what is the scope of loadermanager when creating an android application using loaders should every activity and fragment have its own loadermanager or should there only be one loadermanager that the application owns and lastly are the unique ids that are used to identify specific loadermanagers visible outside of the claspecifically i am having trouble deciding which classes in my application should implement the loadercallbackcursor methods ie should each fragment implement these callbacks or should i have one fragment implement the callbacks and query the results sending them to other fragmentsactivities as necessarythanks in advance to anyone who can help me out i could not find too much information about this online,['android'] +230359,group concat order by i have a table like client id views percentage 1 6 20 1 4 55 1 9 56 1 2 67 1 7 80 1 5 66 1 3 33 1 8 34 1 1 52 i tried group concatselect liclient id group concatliviews as views group concatlipercentage from li group by client id client id views group concatlipercentage 1 649275381 20566780663452 but i want to get the views in order like client id views percentage 1 123456789 526733556620803456,['mysql'] +230365,click the javascript popup through webdriver i am scraping a webpage using selenium webdriver in pythonthe webpage i am working on has a form i am able to fill the form and then i click on the submit buttonit generates an popup window javascript alert i am not sure how to click the popup through webdriverany idea how to do it thanks,['python'] +230405,how to get screen metrics outside an activity i have a generic pool that i am making herepublic class fruitpool extends genericpoolsprite constants fields private final textureregion mtextureregionprivate scene mscene constructors public fruitpoolfinal textureregion pfruittextureregion scene mscene2 thismtextureregion pfruittextureregion thismscene mscene2 getter setter methods forfrom superclassinterfaces overrideprotected sprite onallocatepoolitem random rand new random i want to get the screens thisplay metrics here sprite fruit new sprite0 0 thismtextureregion msceneattachchildfruit return fruiti am trying to get the screens thisplay metrics like this final thisplay thisplay getwindowmanagergetdefaultthisplay camera width thisplaygetwidth camera height thisplaygetheightthe only problem is is that i cant figure out how to do this outside of an activityis this even possible or will i have to use sharedpreference or something,['android'] +230430,easiest way in c to find out if an app is running from a network drive i want to programmatically find out if my application is running from a network drive what is the simplest way of doing that it should support both unc paths 127001d and mapped network drives z,"['c#', '.net']" +230453,python indentationerror unexpected indent i really cannot see the indentation error here i am getting crazy with this loopwhile d end date print dstrftimeymd fecha dstrftimeymd set url url fecha 1 descargamos fichero response urllib2urlopenurl abrimos fichero output openfnamewb escribimos fichero outputwriteresponseread cerramos y guardamos fichero outputclose fecha d delta,['python'] +230470,android magnifying glass effect i wonder if it is possible for a widget to create an area that works as a magnifying glass over whatever background the user has setthanks in advance,['android'] +230506,want to get the contents of infobubble of a marker i am using gmap v3 i am facing a problemthe problem is that i am creating dynamically marker and at similar time i am creating the infowindow of that marker now i want to add some contents in any infowindow of a markerbut do not know how i can get the content of a infowindowi have stored my markers objects in a array and also infowindows objectsbut not found any solutioni want to get infowindows content on the basis of markereditvar markerarray new arrayvar infoarray new arrayfunction placemarkerpointid contentsvar marker new googlemapsmarker icon image position point map map title namemarkerarrayid markervar infobubble new infobubblevar content contentsinfobubblesetcontentcontentgooglemapseventaddlistenermarkermouseoverfunctionevent forvar i0 i infoarraylength i infoarrayiclose infobubbleopenmapmarkerinfoarraypushinfobubblethis function is called within a function many time that create marker on mapnow on a condition two markers are at same lat long and i want to show single marker with infowindow of both markers content i have able to create single marker but not able to append the content in a info window,['javascript'] +230558,is there a saas for logging user activity in almost every app that i build i create some kind of user log table to log various activities that my actual users not visitors but someone with an account perform on the site this is primarily used for customer service issues to allow me to pull up a record of the pages and actions that a user has visitedthe downside to this is the size of the userlogs table it gets immense i am not sure if it is common practice or not for others to log individual not aggregate like google analytics user behavior to a database but if it is i am wondering if any form of a saas exists to help offload this task i essentially need a restful api that lets me store and retrieve individual user activity quickly and securelyanyone know of any or am i the only one who has this issue,['ruby-on-rails'] +230569,jqueryajax in nodejs is it possible to use jqueryajax in nodejs exactly as it is syntaxwise i am trying to share nonui browser code with nodejs i do not want to replace all the existing function calls with my own wrapper currently when i try it it would say no transport by default because jquery does domain detection if i turn it off by setting jquerysupportcors it would say xmlhttprequestopen not available,['jquery'] +230577,javascript reflection get all properties of an object how to get all get all properties of an object using reflection in javascript,['javascript'] +230596,uitableview with static cells does not appear i have created a new xcode project using storyboards tab view template i added a couple of view controllers to my storyboard and wanted to use a uitableview with static cells for one i created it but when i run in the simulator the cells do not appear i have not changed anything in the project except for this storyboard file i am showing screenshots of the storyboard editor and the simulator running the label shows up so the view is loading correctly i set the background color to gray so i can see the talbeview is loading all cells are set to visible i changed their style to basic and edited the label and added a thisclosure indicator that is all,['ios'] +230611,how do i get into a nonpassword protected java keystore or change the password i am trying to import a trusted certificated into the java cacerts keystore but i have a problem i tried to list existing trusted certificates and it seems that the keystore is not password protected keytool list keystore cacertsenter keystore password warning warning warning the integrity of the information stored in your keystore has not been verified in order to verify its integrity you must provide your keystore password warning warning warning keystore type jkskeystore provider sunyour keystore contains 76 entriesi tried to import a trusted certificate keytool importcert alias jiracert file rootc9sslcrt keystore etcjava6sunsecuritycacertsenter keystore password keystore password is too short must be at least 6 charactersenter keystore password keystore password is too short must be at least 6 charactersenter keystore password keystore password is too short must be at least 6 characterstoo many failures try lateri also tried to change the password from none to something keytool storepasswd keystore cacertsbackenter keystore passwordkeystore password is too short must be at least 6 charactersenter keystore passwordkeystore password is too short must be at least 6 charactersenter keystore passwordkeystore password is too short must be at least 6 characterstoo many failures try later,['java'] +230613,c template function inside template class i have this code template class t class myclass public template class u void foo you a ainvoke i want it in this form template class t class myclass public template class u void foo template class t void myclasstfoo you a ainvoke how i can to do this what is the right syntax,['c++'] +230628,null reference exception when generating a url with urlhelperaction method for some reason when certain bots visit the site generating a url with the urlhelperaction method raises a null exception from systemwebhttpservervarscollectionget i have done some debugging and the call stack originiates with an attempt to get the http x original url from the httpcontextbaserequestservervariables collectionif i visit the same address directly from a browser no problem the page is server and no error is logged it only seems to occur when visited by a botnot sure if it is relevant or not but the site was just migrated to iis 75 still using net 20 in integrated modelooking at the code as reversed by reflector the only place where a null exception can occur directly in the get method is the call to this requestfetchservervariables as if the complete request was not set up properlyhas anyone else faced this problem or thiscovered a workaround why would the request be set up differently when visited by a botupdate some additional debugging has shown that the httpservervarscollection was thisposed along with it is parent httprequest object the question now is how can the request object returned by httpcontextcurrent be exposed before the request is completehttpservervarscollectionget methodpublic override string getstring name if this populated string simpleservervar thisgetsimpleservervarname if simpleservervar null return simpleservervar thispopulate if this iis7workerrequest null return thisgetservervarbasebasegetname string servervar thisgetservervarbasebasegetname if stringisnulloremptyservervar only place null reference can happen servervar this requestfetchservervariablename return servervarfull stack tracenullreferenceexception object reference not set to an instance of an object systemwebhttpservervarscollectiongetstring name 8645730 systemcollectionsspecializednamevaluecollectionget itemstring name 7 systemwebmvcpathhelpersgenerateclienturlinternalhttpcontextbase httpcontext string contentpath in cdevsitemvcmicrosoftsrcsystemwebmvcmvcpathhelperscs39 systemwebmvcpathhelpersgenerateclienturlhttpcontextbase httpcontext string contentpath in cdevsitemvcmicrosoftsrcsystemwebmvcmvcpathhelperscs21 systemwebmvcurlhelpergenerateurlstring routename string actionname string controllername routevaluedictionary routevalues routecollection routecollection requestcontext requestcontext boolean includeimplicitmvcvalues in cdevsitemvcmicrosoftsrcsystemwebmvcmvcurlhelpercs136 systemwebmvcurlhelpergenerateurlstring routename string actionname string controllername routevaluedictionary routevalues in cdevsitemvcmicrosoftsrcsystemwebmvcmvcurlhelpercs101 systemwebmvcurlhelperactionstring actionname string controllername object routevalues in cdevsitemvcmicrosoftsrcsystemwebmvcmvcurlhelpercs51 wcmsextensionsdocumenturlhelper urlhelper string path in cdevsitewcodecmsextensionscs33 wcmsextensionsdocumenturlhelper urlhelper document document in cdevsitewcodecmsextensionscs20 wc thisplayclass17loadb cdocument d in cdevsitewglobalasaxcs251 fringinecmsdocumentcontentparserreplacedocumentrefsiresolvingdocumentcache cache match match 258 fringinecmsc thisplayclass4parsecontentb 2match m 17 systemtextregularexpressionsregexreplacementreplacematchevaluator evaluator regex regex string input int32 count int32 startat 234 systemtextregularexpressionsregexreplacestring input matchevaluator evaluator int32 count int32 startat 28 systemtextregularexpressionsregexreplacestring input matchevaluator evaluator 38 systemtextregularexpressionsregexreplacestring input string pattern matchevaluator evaluator regexoptions options 47 fringinecmsdocumentcontentparserparsecontentstring content iresolvingdocumentcache cache 83 fringinecmsresolvingdocumentcacheparseb 0string d 21 fringinecmsdocumentcachegetparseddatastring id string content idocumentservice documentservice func2 parser 216 fringinecmsresolvingdocumentcacheparsestring id string content 67 fringinecmscacheddocumentgetsummary 966 fringinecmscacheddocumentget summary 19 aspviews document widget feeddocumentsummary ascx render control1htmltextwriter w control parametercontainer 841 systemwebuicontrolrenderchildreninternalhtmltextwriter writer icollection children 256 systemwebuicontrolrenderchildrenhtmltextwriter writer 19 systemwebuicontrolrenderhtmltextwriter writer 10 systemwebuicontrolrendercontrolinternalhtmltextwriter writer controladapter adapter 27 systemwebuicontrolrendercontrolhtmltextwriter writer controladapter adapter 99 systemwebuicontrolrendercontrolhtmltextwriter writer 25 systemwebuicontrolrenderchildreninternalhtmltextwriter writer icollection children 134 systemwebuicontrolrenderchildrenhtmltextwriter writer 19 systemwebuipagerenderhtmltextwriter writer 29 systemwebmvcviewpagerenderhtmltextwriter writer in cdevsitemvcmicrosoftsrcsystemwebmvcmvcviewpagecs107 systemwebuicontrolrendercontrolinternalhtmltextwriter writer controladapter adapter 27 systemwebuicontrolrendercontrolhtmltextwriter writer controladapter adapter 99 systemwebuicontrolrendercontrolhtmltextwriter writer 25 systemwebuipageprocessrequestmainboolean includestagesbeforeasyncpoint boolean includestagesafterasyncpoint 1266,['.net'] +230642,how to create serverside application logic on racer derbyjs i am learning the ins and outs of the new derbyjs stack and i cannot find a way to put application logic serverside the stated intent is that all code should be able to run both in the server and in the client however i need certain data to be kept hidden and only sent to the client if authenticated based on user session info how can i accomplish this using a racer store,['javascript'] +230655,icomparable behaviour for null arguments i am implementing icomparable and icomprablet in one of my classes is there any recommendation on how the compareto method in each case should behave when given a null argument should it return a positive number or throw an argumentnullexception or can this behaviour vary depending on the implementing classi saw the msdn documentation here and here but it has nothing to say on this subject any help will be appreciated,"['c#', '.net']" +230677,how to serve static content with jaxrs i have a self hosted jaxrs rest service implemented with the jaxrs restlet extensionnow i have to serve static content and i was wondering how to do it with jaxrs note that i do not know the physical directory structure at compiletime so given a url likehttpblabla8182staticyabadabadoopngthe file rootyabadabadoopng has to be returned where root is the static content root directoryis it possible to do it with pure jaxrsthankseditknown at compiletime file system path of the static content root folderhttp url used to reference the static content root folderunknown at compiletimethe actual content of the root folder how many files file types directory structure,['java'] +230679,c map string to enum possible duplicateeasy way to use variables of enum types as string in c is there any elegant way to convert a user input string to an enum value is straight c besides the manual waya simplified example of calling a function that takes an enum as an argumentenum mondaytuesdaywednesdayget user to enter a day of the week from command lineset the work day according to user inputif strcmpuser inputmonday0 set work daymonday else if strcmpuser inputtuesday0 set work daytuesdaythanks,['c'] +230702,caught typeerror while rendering init got an unexpected keyword argument use decimal while running the program i am getting the following error messagecaught typeerror while rendering init got an unexpected keywordargument use decimalhere is my code i am using jquery 164 def load chartschart listnone render to embed script script typetextjavascriptn var chartit hco array snscriptn script srcs typetextjavascriptnscript if chart list is not none if isinstancechart list chart pivotchart chart list chart list chart list chcoptions for c in chart list render to list sstrip for s in render tosplit for hco render to in izip longestchart list render to list if render to hcochartrenderto render to embed script embed script simplejsondumpschart list use decimaltrue chart loader url else embed script embed script chart loader url return mark safeembed script,"['jquery', 'python']" +230703,how to use getprocessmemoryinfo in c i am trying to use the function getprocessmemoryinfo of psapih inside a c application on windows 7 32biti followed some tutorial and i did something likepprocess memory counters pmemcountrpmemcountr new process memory countersbool result getprocessmemoryinfogetcurrentprocess pmemcountr sizeofpprocess memory countersthe problem is that i always obtain false from the execution of the getprocessmemoryinfo method what am i doing wrong here,['c++'] +230725,java library to compare image similarity i spent quite some time researching for a library that allows me to compare images to one another in javai did not really find anything useful maybe my googlesearchskill is not high enough so i thought i would ask you guys if you could point me into a direction of where i could find something like thisbasically what i want to do is to compare two images with each other and get a value of how much the two are similar like a percentage or soi hope you guys have something i can use i wouldnt know how to write something like that myselfps it does not necessarily has to be in java that is just the environment my app will be running,['java'] +230732,how to close sqlalchemy connection in mysql this is a sample code i would like to runfor i in range120 db create enginemysqlrootlocalhosttest database conn dbconnect some simple data operations connclose dbthisposeis there a way of running this without getting too many connections errors from mysqli already know i can handle the connection otherwise or have a connection pool i would just like to understand how to properly close a connection from sqlalchemythanks in advance,['mysql'] +230738,get all types implementing specific open generic type how do i get all types that implementing a specific open generic typefor instancepublic interface iuserrepository irepositoryuserfind all types that implement irepositorypublic static ienumerabletype getalltypesimplementingopengenerictypetype opengenerictype assembly assembly,['c#'] +230754,viewdidappear called twice in ios5 i am developing an app with an uinavigatorcontroller i am using the method viewdidappear in the second pushed viewcontroller to find information in an external serverwell while in ios5 worked fine at the beginning i realized that viewdidappear was not being called in ios43 so i put this code in the root voidnavigationcontrolleruinavigationcontroller navigationcontroller didshowviewcontrolleruiviewcontroller viewcontroller animatedboolanimated viewcontroller viewdidappearanimatedthereafter the app started to work properly in ios43 however in ios5 did not because it is calling twice viewdidappear the one which was being called at first and the one from the navigationcontrollerdidshowviewcontrolleranimatedwhat should i do to have only called once viewdidappearthank you very much,['ios'] +230786,accent insensitive search query in mysql is there any way to make search query accent insensitivethe columns and tables collation are utf8 polish ci and i do not want to change themexample word toruaselect from pages where title like torunit does not find torua how can i do that,['mysql'] +230807,ie8 windowfn fn can someone explain this ie8 function windowfoo function foo consolelog windowfoo foo false,['javascript'] +230812,how to implement pull to refresh on a listfragment i am trying implement pull to refresh on a listfragment but right now none of the drop in libraries seem to support it there is no way to detect overscroll on the list fragment that i can see so i am wondering if anyone has found a means to get this workingusing christians tip i used the following for my oncreateview methodoverridepublic view oncreateview layoutinflater inflater viewgroup container bundle savedinstancestate pulltorefreshlistview listview new pulltorefreshlistviewgetactivity madapter new hometweetlistadaptergetactivity rlayouttweet list item tweets listviewsetadaptermadapter return listviewlike christian said you can only do this with a fragment returning anything other than a listview on a listfragment errors outeditto clarify i am using johans pulltorefresh library,"['java', 'android']" +230844,delete xcdatamodel file from xcode i made a lightweight migration that i decided i do not want anymore is there any way to just delete the file i have already changed the current model version to the one before it and the app runs however when i rightclick on the xcdatamodel file in the xcode file viewer delete is greyedout i also tried to remove the file from finder but it keeps the file in xcode reddedoutis there any way to fix this,['ios'] +230857,is there a way to set the page title by databinding using knockoutjs i have a viewmodel with a title property i would like to set the page title using that property heres what i tried already which did not workhtml head title databindtext titletitleheadbody span databindtext title this thisplays the title properly bodythe browser title is blankdefault instead of the value of my title property,"['javascript', 'html']" +230877,jquery on method does not see new elements i am getting a json element and building a list from its items like thisgettitles functiondata data data var list getjson titles data functiondata eachdatadata functionkey val listpush lia href valhref valtitle aspan classcount valcount spanli titleitemshtmllistjoin and i am binding click event for a elements like thisaonclick functione alertclicked epreventdefaultold a elements shows alert but new ones follow url event handler does not work for new ones how can i solve this,"['javascript', 'jquery']" +230884,change soap prefixes in php i am rewriting a soap web service from net to php by default php is giving me tags that look like thissoapenvenvelope xmlnssoapenv xmlnsns1soapenvheaderns1findallcategoriessoapenvheadersoapenvbodyns1findallcategoriesresponsens1findallcategoriesresultns1artistcategorydtoetcbut i need thissoapenvelope xmlnssoap xmlnsxsi xmlnsxsdsoapbodyfindallcategoriesresponse xmlnsfindallcategoriesresultartistcategorydtothis is similar to the question here php and soap change envelope however i would like to not hack it the way he did also i am creating a soap service that will be consumed by an existing iphone app not using php to consume a soap service using soapclient the iphone app just parses the raw xml and i cannot change the iphone app right now,['php'] +230903,how to pad nsstring with spaces for example i need the nsstring have at least 8 charsinstead of using a loop to add the left pad spaces on this is there anyway to do itexamplesinput outputhello hellobye byevery long very longabc abc,['objective-c'] +230914,difference registerforcontextmenu and setoncreatecontextmenulistener whats the difference between registerforcontextmenu registers a context menu to be shown for the given view multiple views can show the context menu this method will set the viewoncreatecontextmenulistener on the view to this activitycall registerforcontextmenu and pass it the view you want to give a context menu when this view then receives a longpress it thisplays a context menuand setoncreatecontextmenulistener register a callback to be invoked when the context menu for this view is being built if this view is not long clickable it becomes long clickablewhich one to use and about the long clickable stuff both are doing the same thing thanks,['android'] +230919,mysql find row through another table i have two tablesgameid int11game tagsgame int11tag id int11game tagsgame gameidi am horrible with mysql so here is my question i want to be able to find what games have a certain amount of tag ids so if i have four tag ids 3 5 7 11 i want to be able to find what games will have all four of those tags by looking through the game tags table here is an example of what i meanpseudomysqlselect from gameswhere search through game tags table and find which rows have the same game field and all of the tag ids that i need to search forlimit 0 15i know i explained this horrible could not word it like in my mind so if you have any questions just leave a comment,"['php', 'mysql', 'sql']" +230933,is there an addunique method similar to addrange for alist in c i have a list in c var list new listcar listaddrangegetgreencars listaddrangegetbigcars listaddrangegetsmallcarsthe issue is that some of the same cars get returned in different functions and i do not want them in the list more than once each car has a unique name attribute is there anyway i can have something like this above but will only add items if they are unique,['c#'] +230935,statusbar notification in android phonegap i have a problem in status bar notification at 10 second intervali have done with code for thisplay it for one time by creating pluginbut i want to thisplay it at every 10 minutes intervalso i used alarmmanager for generating notification at every 10 minutesbut it does not call onreceivecontext ctx intent intent method of firstquotealarm classi have following code for thisplay notification and alarmmanagerpublic void shownotification charsequence contenttitle charsequence contenttext int icon rdrawablenofication long when systemcurrenttimemillis notification notification new notificationicon contenttitle when intent notificationintent new intentctx ctxgetclass pendingintent contentintent pendingintentgetactivityctx 0 notificationintent 0 notificationsetlatesteventinfocontext contenttitle contenttext contentintent mnotificationmanagernotify1 notification date dt new date date newdate new datedtgetyear dtgetmonth dtgetdate1014dtgetseconds long triggerattime newdategettime long repeat alarm every 10 quotessettingon 1 alarmmanager am alarmmanager ctxgetsystemservicecontextalarm service intent intent new intent refresh alarm intent intent1 new intentctxfirstquotealarmclass pendingintent pi pendingintentgetbroadcastctx 0 intent1 0 amsetrepeatingalarmmanagerrtc wakeup triggerattime repeat alarm every pi logicall2msg,['android'] +230946,retaining image quality while drawing high resolution pdf to iphone i have a problem related to pdf drawing in iphone when i draw the pdf in ipad it works fine but in iphone quality of image of page is not good that image contains dark spots at the place of gray backgroundcan anyone help me to solve this problemthanks uiimage imageforpageindexnsuintegerpageindex uiimage image nil if delegate illustration enable cgcolorspaceref colorspace cgcolorspacecreatedevicergb cgcontextref context cgbitmapcontextcreatenull pagesizewidth pagesizeheight 8 bits per component pagesizewidth 4 bytes per row colorspace kcgimagealphapremultipliedlast kcgbitmapbyteorder32big cgcolorspacereleasecolorspace cgcontextcliptorectcontext cgrectmake0 0 pagesizewidth pagesizeheight self renderpageatindexpageindex oncontextcontext cgimageref cgimage cgbitmapcontextcreateimagecontext cgcontextreleasecontext image uiimage imagewithcgimagecgimage cgimagereleasecgimage else cgcolorspaceref colorspace cgcolorspacecreatedevicergb cgcontextref context cgbitmapcontextcreatenull pagesizewidth pagesizeheight 8 bits per component pagesizewidth 4 bytes per row colorspace kcgimagealphapremultipliedlast kcgbitmapbyteorder32big cgcolorspacereleasecolorspace cgcontextcliptorectcontext cgrectmake0 0 pagesizewidth pagesizeheight self renderpageatindexpageindex oncontextcontext cgimageref cgimage cgbitmapcontextcreateimagecontext cgcontextreleasecontext image uiimage imagewithcgimagecgimage cgimagereleasecgimage return imagevoidrenderpageatindexintindex oncontextcgcontextrefctx if delegate illustration enable if index1 imagelist count return uiimage image nil image uiimage imagewithcontentsoffileimagelist objectatindexindex1 cgrect rect1 cgrectmake0 0 imagesizewidth imagesizeheight cgrect rect2 cgcontextgetclipboundingboxctx cgaffinetransform transform self aspectfillrect1 rect2 cgcontextconcatctmctx transform cgcontextdrawimagectx cgrectmake0 0 imagesizewidth imagesizeheight imagecgimage else cgpdfpageref page cgpdfdocumentgetpagepdf index cgrect rect1 cgpdfpagegetboxrectpagekcgpdfmediabox cgrect rect2 cgcontextgetclipboundingboxctx cgaffinetransform transform if takebookmarkimg transform self aspectfillrect1 rect2 else transform self aspectfitrect1 rect2 cgcontextconcatctmctx transform cgcontextdrawpdfpagectx page cgaffinetransform aspectfitcgrectinnerrect cgrect outerrect scalefactor minouterrectsizewidthinnerrectsizewidth outerrectsizeheightinnerrectsizeheight basescalefactor scalefactor cgaffinetransform scale cgaffinetransformmakescalescalefactor scalefactor cgrect scaledinnerrect cgrectapplyaffinetransforminnerrect scale cgaffinetransform translation cgaffinetransformmaketranslationouterrectsizewidth scaledinnerrectsizewidth 2 scaledinnerrectoriginxtotalmovexmovex outerrectsizeheight scaledinnerrectsizeheight 2 scaledinnerrectoriginytotalmoveymovey return cgaffinetransformconcatscale translation,"['iphone', 'objective-c']" +230950,invoking a search or filter on an android listfragment i am using the android compatibility library and i am using a listfragment i have it set up to thisplay the items in my list quite nicely however now i want to give the users the ability to filtersearch the data how do i set this up is it any different then it was with the regular listview and if so do i place all my code for that in the listfragment or the parent activity,['android'] +230975,how can i show a message box with details in winforms just now i noticed that visual studio shows a message box with details when a property is set to an invalid value for exampleis it possible to make this type of message box in winformsi have tried the following codemessageboxshowerror in division filln exmessage information messageboxbuttonsok messageboxiconinformation messageboxoptionsrightalignbut this produced the following errorerror 24 the best overloaded method match for systemwindowsformsmessageboxshowstring string systemwindowsformsmessageboxbuttons systemwindowsformsmessageboxicon systemwindowsformsmessageboxdefaultbutton has some invalid argumentsgjagadeeswarannov 17mcssps schoolmcssps schoolcertificatetransfercs 164 21 mcssps schoolhow can i fix this error and get a message box that shows additional details,"['c#', '.net']" +230999,windows mobile attach on call starting and recording a call i need to implement a small feature in my project for windows mobile 60 platform i want to attach to an event when a phone call is answered and to record the 2 way call i saw this questionwindows mobile 2 way call recording cbut it does not work in my case when i start to record the microphone is blocked and the person on the other side cannot hear my voice i thought that maybe the problem is in the telephonehtc touch hd but there are some programs that work for examplei have two questionshow to attach to a phone callhow to record the phone calli appreciate your help thanksivo,"['c#', '.net']" +231024,how can i get current date in android i wrote the following code date d new datecharsequence s dateformatformatm d y dgettimebut is asking me parameter i want current date in string formatlike 28dec2011so that i can set over textviewexplain a bit if you think something is necessary i am new to android development,['android'] +231074,is net stopwatch standbysleephibernate aware does systemdiagnosticsstopwatch count time during computer stand by,['.net'] +231108,what is the difference between getwidthheight and getmeasuredwidthheight in android sdk the android documentation says that there is two sizes for a view the measured dimensions and the drawing dimensions the measured dimension is the one computed in the measure pass the onmeasure method while the drawing dimensions are the actual size on screen particularly the documentation says thatthese values may but do not have to be different from the measured width and heightso my question is what could make the drawing dimension be different of the measured dimension if the onmeasureintint method respects the layout requirements given as the parameters widthmeasurespec and heightmeasurespec how could the sdk decides that the view should have a different drawing sizeadditionally howwhere in the android source code the measured widthheight is used to compute the drawing widthheight i tryed to look into the view source code but i cannot figure out how the measuredwidthheight is used to compute the final widthheight maybe it has something to do with the padding but i am not sure,['android'] +231113,ruby get object keys as array i am new to ruby if i have an object like this apple fruit carrot vegetablehow can i return an array of just the keysapple carrot,['ruby'] +231119,why are all my log4net levels false i am using log4net in my aspnet mvc3 project but all logging properties such as isdebugenabled falsein my assemblyinfo i haveassembly xmlconfiguratorwatch truein my log class i havepublic log4netlogger log4netconfigxmlconfiguratorconfigure logger logmanagergetloggersystemreflectionmethodbasegetcurrentmethoddeclaringtypemy related config stuff in webconfig isxml version10 encodingutf8 for more information on how to configure your aspnet application please visit configuration configsections sectiongroup nameapplicationsettings typesystemconfigurationapplicationsettingsgroup system version40 cultureneutral publickeytokenb77a5c561934e089 section namelog4net typelog4netconfiglog4netconfigurationsectionhandler log4net requirepermissionfalse sectiongroup configsections log4net debugfalse appender nameadonetappender typelog4netappenderadonetappender buffersize value100 connectiontype valuesystemdatasqlclientsqlconnection systemdata version10330 cultureneutral publickeytokenb77a5c561934e089 connectionstring valueremoved commandtext valueinsert into logging datethreadlevelloggermessageexception values log date thread log level logger message exception parameter parametername valuelog date dbtype valuedatetime layout typelog4netlayoutrawtimestamplayout parameter parameter parametername valuethread dbtype valuestring size value255 layout typelog4netlayoutpatternlayout conversionpattern valuethread layout parameter parameter parametername valuelog level dbtype valuestring size value50 layout typelog4netlayoutpatternlayout conversionpattern valuelevel layout parameter parameter parametername valuelogger dbtype valuestring size value255 layout typelog4netlayoutpatternlayout conversionpattern valuelogger layout parameter parameter parametername valuemessage dbtype valuestring size value40 layout typelog4netlayoutpatternlayout conversionpattern valuemessage layout parameter parameter parametername valueexception dbtype valuestring size value20 layout typelog4netlayoutexceptionlayout parameter appender possible levels debug info warn error fatal root level valueall appenderref refadonetappender root log4net applicationsettingsconfigurationi already got frustrated to a point of just wanting to dopublic log4netlogger logger logmanagergetloggersystemreflectionmethodbasegetcurrentmethoddeclaringtype loggerisdebugenabled truehowever of course loggerisdebugenabled does not have any setters what do i have to do to get this damn thing to work,['c#'] +231140,android high resolution image processing from experiments and from reading other posts like this one it seems that it is hard to process high resolution images on android because there is a limit on how much memory the vm will allow to allocateloading a 8mp camera pictures takes around 20 mb of memoryi understand that the easy solution is to downsample the image when loading it bitmapfactory offers such an option but i still would like to process the image in full resolution the camera shoots 8mp why would i only use 4mp and reduce the qualitydoes anyone know good workarounds for that,['android'] +231151,context to use call and apply in javascript guys can any one explain context to use call and apply methods in javascriptwhy to use call and apply instead of calling a function directly,['javascript'] +231186,setting background color of uiview subclass does not work i am trying to change background color of one of my uiview subclasses for some reason selfbackgroundcolor uicolor whitecolordoes not do anything when i put it in my idinitwithframecgrectframemethod inside the view the view is always black i have also tried selfmyviewbackgroundcolor from my views controller but that did not work either any ideas on what i am doing wrong the relevant code looks like this interface paperview uiviewimplementation paperview idinitwithframecgrectframe self super initwithframeframe if self initialization code selfbackgroundcolor uicolor whitecolor this does not do anything the view is always black return self,"['objective-c', 'ios']" +231188,finding all references on eclipse i have been using the eclipse references ctrlshiftg for sometime now i notice that eclipse misses finding some references sometimes is there something i must configure to get this working correctly,['java'] +231204,how to target html element from a specific class of a body element using drupal the theme has a background color assigned to the html element i am creating a separate print css for one particular page and wish to remove the background color only for this page when the user prints the page the html element has no class or id but the body element doeshtml stylebackgroundcolor6 body claspecialpage bodyhtmlis there a way to specify that i want the parent element of body or some way of targeting html based on the class of bodyedit html body,"['jquery', 'html', 'css']" +231245,android how to upload photo from the sd card to the facebook wall i use the facebook android sdkgoalcreate multiple posts in news feed of facebook logged in user that will contain photo from the android device its sd card and some comment the result should be the same as when you do it using the add photovideo feature directly in facebook in the end it should look like thiswanted facebook resultproblemi cannot do iti went through the numerous similar posts on stack overflow but no answer there so farwhat i have tried to implement so farapproach 1 sd card photos 2 facebook albumhowupload pictures from my mobile its sd card to an album that is created for my application the first time i upload a picture from it in this case when constructing the params object i use the picture key and put the bytes of the picture as its value i use mephotos in the request call of the facebook or asyncfacebookrunner object the problemnot all uploaded images are thisplayed on my wall instead there is something like x photos were added to the album xthe code snippet is this for one picturebundle params new bundleparamsputstringmessage uploaded on nowparamsputbytearraypicture bytes bytes contains photo bytes no problem hereasyncrunnerrequestmephotos params post new postphotorequestlistener nullfacebook resultapproach 2 internet photos 2 facebook news feedhowthisplay pictures stored somewhere on the internet in posts on my wall in this case when constructing the params object i use the link key and set the url to picture as its value i use mefeed in the request callthe problemthis produces some strange output but it is not what i wantthe code snippet is this for one picturebundle params new bundleparamsputstringmessage uploaded on nowparamsputstringlink radabota2jpgasyncrunnerrequestmefeed params post new postphotorequestlistener nullfacebook resultapproach 3 mix of approach 1 and 2howi try to use the picture key and set photo bytes as its value as in 1 and call the request with mefeed as in 2the problemmessage is produced as i would like it to be but no photo is includedthe code snippet is this for one picturebundle params new bundleparamsputstringmessage uploaded on nowparamsputbytearraypicture bytes bytes contains photo bytes no problem hereasyncrunnerrequestmefeed params post new postphotorequestlistener nullfacebook resultso any ideas how i could reach my goaledit workaround foundit seems that the only way to create new posts containing photos on users wall is to add photos and related comments to users wall photos albumhow code snippetbeware the facebookrequest call should be replaced with async call so the operation does not block the ui thread string wallalbumid nullstring response facebookrequestmealbumsjsonobject json utilparsejsonresponsejsonarray albums jsongetjsonarraydatafor int i 0 i albumslength i jsonobject album albumsgetjsonobjecti if albumgetstringtypeequalsignorecasewall wallalbumid albumgetstringid logdjson wallalbumid break and thenif wallalbumid null bundle params new bundle paramsputstringmessage uploaded on now paramsputbytearraysource bytes asyncrunnerrequestwallalbumidphotos params post new postphotorequestlistener null,['android'] +231247,how do i add a missing bundle in eclipse when installing tools for aws in eclipse i encountered the following errorcannot complete the install because one or more required items could not be found software currently installed amazon simpledb management 100v20161400 comamazonawseclipsedatatoolsenablementsimpledbfeaturefeaturegroup 100v20161400 missing requirement eclipse data tools platform amazon simpledb ui plugin 100v20161400 comamazonawseclipsedatatoolsenablementsimpledbui 100v20161400 requires bundle orgeclipsedatatoolssqltoolssqlscrapbook 100 but it could not be found cannot satisfy dependency from amazon simpledb management 100v20161400 comamazonawseclipsedatatoolsenablementsimpledbfeaturefeaturegroup 100v20161400 to comamazonawseclipsedatatoolsenablementsimpledbui 100v20161400what is the problem here and how do i resolve it sorry but i am new to eclipse and java dev in general could the following message be the key requires bundle orgeclipsedatatoolssqltoolssqlscrapbook 100 but it could not be found,['java'] +231280,set css border color to text color is there a way to set the bordercolor in css to be the same as the text colorfor instance having a class which adds a bottom dotted border but leaving the color of said border to match the color of the text in much the same way as the color of textdecorationunderline is the color of the text color property,['css'] +231303,android application stats on android market place net usersinstalled we have recently released an application on android market place in stats it is showing 330 total installs users90 net installs deviceswe are confused as to how can there be so much difference between total installs and net installsmy question is what exactly is net installs and total installs what is the differnce is net install same as active installhow can there be so much difference between net and total installs,['android'] +231304,comparing functionality between keylisteners and key bindings this question arose when an anonymous user downvoted an answer of mine involving keylisteners and suggested the use of key bindings instead this anonymous user informed me that the keylistener interface was an old awt solution and should not be used however i do not know if i should trust that information completely i have researched both on various websites oracle included and found nothing regarding the functionality of keylisteners or key bindings i am aware of the fact that the two perform similar tasks but am unsure of exactly what goes on behind the scenes so to speaki am kind of leaning towards using key bindings in future projects simply because i acquired research suggesting that the keylistener interface required that the component in question have focus while key bindings did not but i am confused why is this so how are key bindings triggered differently than keylistenersps i am pretty sure this is a rarity but are there some circumstances where using keylisteners is more appropriate,['java'] +231313,how to copy image file from gallery to another folder programatically in android i want to pick image from gallery in and copy it in to other folder in sdcardcode to pick image from gallaryintent photopickerintent new intentintentaction pick photopickerintentsettypeimage startactivityforresultphotopickerintent request code choose picture from gallaryi get contentmediaexternalimagesmedia681 this uri onactivityresulti want to copy the imageform path contentmediaexternalimagesmedia681 to path filemntsdcardsharedresources this path of sdcard in androidhow to do this,['android'] +231332,php functionclass that formatsindents my html code is there a php functionclass that cleans my html codefor examplehtml ulliitem1liliitem2liecho htmlcleanhtml outputs ul liitem1li liitem2li ul,"['php', 'html']" +231366,saving a bitmap into a memorystream should i allocate the memory or just the object of the memory streamis this okmemorystream memorystream new memorystreambitmapsavememorystream systemdrawingimagingimageformatjpegif i need to define the memorystream size how can i get it from bitmap,['c#'] +231390,javascript regular expression to validate url i am validating url with following regular expression i want to validate googlecom also but it returns false what can be changed in re below to validate googlecomconsoleloglearnregexp falseconsoleloglearnregexp trueconsoleloglearnregexp trueconsoleloglearnregexp trueconsoleloglearnregexpgooglecom falsefunction learnregexp return ftphttpswaz093az3testlearnregexparguments0,"['javascript', 'html']" +231393,uiwebview background is set to clear color but it is not transparent i am developing an ios 4 application using ios sdk latest version and xcode 42i have a xib with a uiwebview with alpha 10 background set to clear color and opaque is not set on this xib i setup an image as background with this code idinitwithnibnamensstring nibnameornil bundlensbundle nibbundleornil self super initwithnibnamenibnameornil bundlenibbundleornil if self uicolor background uicolor alloc initwithpatternimageuiimage imagenamedaboutbackgroundpng selfviewbackgroundcolor background background release return selfthe uiwebview is showing an static htmlhtmlheadheadbody stylemargin0 autotextaligncenterbackgroundcolor transparent colorwhitebodyhtmlon ios 5 simulator its background is transparent but on an ios 4 device is greyany clue,"['iphone', 'objective-c', 'ios']" +231422,how to use jquery with jsf 20 i am learning jquery i want to use jquery inside my jsf 20 application like i have html file in which i am using jquery like thishead titlethe devils dictionarytitle meta httpequivcontenttype contenttexthtml charsetutf8 link relstylesheet hrefcss06css typetextcss script typetextjavascript srcjsjquery171jsscript script typetextjavascript srcjs06jsscriptheadi simply downloaded the jquery171js file form jquery official website included it into my directory and then start using jquery my 06js file conatin code like thisdocumentreadyfunction lettera aclickfunction the load method does all our heavy lifting for us we specify the target location for the html snippet by using a normal jquery selector and then pass the url of the file to be loaded as a parameter to the method now when the first link is clicked the file is loaded and placed inside div iddictionary the browser will render the new html as soon as it is inserted dictionaryloadahtml return false end of lettera aclick occasionally we do not want to retrieve all the javascript we will need when the page is first loaded we might not know what scripts will be necessary until some user interaction occurs we could introduce script tags on the fly when they are needed but a more elegant way to inject additional code is to have jquery load the js file directly pulling in a script is about as simple as loading an html fragment in this case we use the getscript function which like its siblings accepts a url locating the script file as shown in the following code snippet letterc aclickfunction getscriptjscjs return false end of letterc aclickfunction end of documentreadyfnhere is my html file code snippethtmlhead titlethe devils dictionarytitle meta httpequivcontenttype contenttexthtml charsetutf8 link relstylesheet hrefcss06css typetextcss script typetextjavascript srcjsjquery171jsscript script typetextjavascript srcjs06jsscriptheadbody div idcontainer div classletters div classletter idlettera h3a hrefaah3 div div classletter idletterb h3a hrefbah3 div div classletter idletterc h3a hrefcah3 div div div iddictionary div divbodyi want to ask if i create the same page on jsf20 then jquery will work in the same way or i have to downlaod some plugin to use jquery inside my jsf 20 application or to modify something inside my webxml thanks,['jquery'] +231465,ember model to json i am looking for an efficient way to translate my ember object to a json string to use it in a websocket message below model appnode emberobjectextend name thename type thetype value thevaluethe websocket methodappioemitnode node hash hash should be the json representation of the node name thename type thetype there must be a fast onliner to do this i dont want to do it manualy since i have many attributes and they are likely to change,['javascript'] +231466,jlabel hyperlink to open browser at correct url i need to create a label with java swing that is clickable and able to open the default browser on the desktop and redirect it to a specific url my code is able to open up the browser but not redirecting it to the correct url the default home page is loaded my test code import javaawt import javaxswing import javaawtevent import javaioioexception import javanet public class linktest extends jframe public linktest jpanel p new jpanel jlabel link new jlabelclick here linksetcursorcursorgetpredefinedcursorcursorhand cursor linkaddmouselistenernew mouseadapter public void mouseclickedmouseevent e if egetclickcount 0 if desktopisdesktopsupported desktop desktop desktopgetdesktop try uri uri new uri desktopbrowseuri catch ioexception ex exprintstacktrace catch urisyntaxexception ex exprintstacktrace paddlinkgetcontentpaneaddborderlayoutnorth p public static void mainstring args linktest linktest new linktest linktestsetsize640100 linktestshow how can i have a default browser open and redirect to the correct url with java swing,['java'] +231481,is there a relation between object size and locking performancein java in the famous java concurrency in practice section 24 it says that intrinsic locking approach as against explicit locks was a bad design decision as its confusing and also it forces jvm implementors to make tradeoffs between object size and locking performancecan someone please explain how object size effects locking performance,['java'] +231503,javascript error cannot call method appendchild of null i am new to javascript and programming in general and have been trying to get a basic grasp on working with the dom apologies if this is a very basic mistake but i looked around and could not find an answer i am trying to use the appendchild method to add a heading and some paragraph text into the in the very basic html file below html head titlejs practicetitle headbody script srcscriptjsscript div id main h1simple html pageh1 pthis is a very simple html pagep pit is about as basic as they come it has p ul lian h1 tagli litwo paragraphsli lian unordered listli ul div div idjavascript divbodyhtmlhere is the js code var newheading documentcreateelementh1 var newparagraph documentcreateelementp newheadinginnerhtml new heading newparagraphinnerhtml some text for a paragraph documentgetelementbyidjavascriptappendchildnewheading documentgetelementbyidjavascriptappendchildnewparagraph running it causes an error cannot call method appendchild of nullhelp i cannot figure out why this is not working,['javascript'] +231526,pythonic way to iterate over part of a list i want to iterate over everything in a list except the first few elements egfor line in lines2 foolinethis is concise but copies the whole list which is unnecessary i could dodel lines02for line in lines foolinebut this modifies the list which is not always goodi can do thisfor i in xrange2 lenlines line linesi foolinebut that is just grossbetter might be thisfor iline in enumeratelines if i 2 continue foolinebut it is not quite as obvious as the very first exampleso whats a way to do it that is as obvious as the first example but does not copy the list unnecessarily,['python'] +231530,ilmerge hangs on merge i am using ilmerge to combine 9 net dlls written in c net 4 the problem is ilmerge gets stuck no error message or anythingthe log shows that ilmerge merges all the assemblies correctly then sets out to write the target assembly it runs the assembly resolver for a bunch of references and then nothing after successfully resolving systemconfiguration the log shows nothing else the program continues to use the cpu but i do not see if it is doing anythingany one else had a similar experience,['.net'] +231545,hide all modal view controllers i have a login view presented as a modelviewcontroller and i have a register view presented as a navigationcontrolloer on top of itlogin modelviewcontrollerregisternavigationcontrolleri am presenting the register viewcreateaccount at the loginview as followcreateaccount createaccount alloc initwithnibnamecreateaccount bundlenilnavcontroller uinavigationcontroller alloc initwithrootviewcontrollercreateaccountuibarbuttonitem cancelbuttunuibarbuttonitem allocinitwithtitlecancel styleuibarbuttonitemstylebordered targetself actionselectorhidemeuibarbuttonitem registerbuttunuibarbuttonitem allocinitwithtitleregister styleuibarbuttonitemstylebordered targetself actionselectorregistercreateaccountnavigationitemleftbarbuttonitem cancelbuttuncreateaccountnavigationitemrightbarbuttonitemregisterbuttuncreateaccounttitlecreate accountself presentmodalviewcontrollernavcontroller animatedyesthe login controller has the nsurlconnectiondelegate for booth the login and the registerwhen registration finishs i simply call theself thismissmodalviewcontrolleranimatedyeswhich will thismiss the registration view onlyi want to thismiss the login view also so i can go back to my main application,"['iphone', 'ios', 'objective-c']" +231555,cannot understand stringreplaceall nongreedy behavior possible duplicatejava regex anomaly any idea why the following test fails returns xx instead of xtest public void testreplaceall assertequalsx xyzreplaceall xi do not want to do i want to understand this behavior any clues,['java'] +231557,out of context variables in visual studio 2010 debugger i am having a very odd problem with local variables being out of context in the visual studio 2010 debugger for a c console application targeting net 40 i have searched for other similar questions on so but while some have the same symptoms none seem to apply directly to this problem they all appear to have other root causesthe problem is that for some variables but not all i do not get a tooltip with their value they do not appear in the locals window and i get the name xyz does not exist in the current context if i add them to the watch window it appears to affect some variables but not others and i cannot figure out a pattern it does not seem to be based on member vs local class vs struct or any other differentiator i have restarted my computer and visual studio verified i am in a clean debug build made sure the debugging frame is correct made sure to refresh the variables in the watch screen and attempted various spells and incantationsi have included a screenshoot below bigger version at any thoughtseditadding some additional informationthe problem is repeatable the exact same variables either work or do not work even after completely shutting down and restarting visual studio this leads me to believe there is actually something systematic going wrong rather than just memory corruption or somethingi have also thiscovered that it appears to be related to the trycatch block if i position the breakpoint outside the try statement i can see any of the inscope variables normally as soon as the execution point enters the try statement all the variables outside the try block become inaccessible and i can only access the ones inside the try statement it is almost as though the debugger is treating the try block as a separate method though you can see the codecompiler still does have access to inscope variables has anyone seen this behavior beforeanother editi partially take back what i said about the trycatch being suspect it appears that in this portion of the code the debugger exhibits this odd taking stuff out of context for any enclosing block for example if i set a breakpoint directly inside the foreach statement in the screenshot i can see the port variable value on each iteration but none of the variables outside the foreach statement which thisappear as soon as i enter the foreach block then as soon as you enter the try block the port variable suddenly goes away this is getting really weirdalso as requested the code for the entire method is belowprivate void configureannouncersocketsxdocument configdocument xelement socketselement configdocumentxpathselectelementconfigurationnetworkannouncersockets bool usedefault true if socketselement null use the default announcers they will be added at the end xattribute defaultattribute socketselementattributeusedefault if defaultattribute null usedefault converttobooleandefaultattribute get the default frequency int defaultfrequency announcerdefaultfrequency xattribute frequencyattribute socketselementattributefrequency if frequencyattribute null defaultfrequency converttoint32frequencyattributevalue get all sockets foreach xelement socketelement in socketselementxpathselectelementssocket get the address ipaddress address ipaddressbroadcast string addressattribute stringsocketelementattributeaddress ifgetaddressaddressattribute ref address true intelliplexlogwarninvalid announcer socket address addressattribute continue get the local address ipaddress localaddress null string localaddressattribute stringsocketelementattributelocaladdress ifgetaddresslocaladdressattribute ref localaddress false intelliplexlogwarninvalid announcer socket local address localaddressattribute continue get the ports listint ports new listint string ranges stringsocketelementattributeportsplitnew foreach string range in ranges string portpair rangesplitnew int firstport converttoint32portpair0 int lastport portpairlength 1 converttoint32portpair1 firstport do portsaddfirstport while firstport lastport get the local port int localport socketelementattributelocalport null converttoint32stringsocketelementattributelocalport 0 get the frequency int frequency socketelementattributefrequency null converttoint32stringsocketelementattributefrequency defaultfrequency create the sockets and add itthem to the manager foreach int port in ports try ipendpoint endpoint new ipendpointaddress port ipendpoint localendpoint localaddress null new ipendpointipaddressany 0 new ipendpointlocaladdress localport announcer socket new announcerfrequency endpoint localendpoint announcersocketsaddsocket catch exception ex intelliplexlogwarncould not add announcer socket exmessage add default announcement sockets if usedefault configuredefaultannouncersockets,['c#'] +231567,generic syntactic sugar or true improvement i have a question regarding the following method callsvar ctl1 thisfindcontrolrecursivelysomefield as hiddenfieldvar ctl thisfindcontrolrecursivelyhiddenfieldsomefieldheres il for these two callsil 0010 ldstr asyncresetil 0015 call class systemwebsystemwebuicontrol amcwebg081methodextensionsamcwebg081controlextensionsfindcontrolrecursivelyclass systemwebsystemwebuicontrolstringil 001a isinst systemwebsystemwebuiwebcontrolshiddenfieldil 001f stloc0il 0020 ldarg0il 0021 ldstr asyncresetil 0026 call 0 amcwebg081methodextensionsamcwebg081controlextensionsfindcontrolrecursivelyclass systemwebsystemwebuiwebcontrolshiddenfieldclass systemwebsystemwebuicontrolstringi have always thought in this situation the generic version of this method was more syntactic sugar vs true improvement is the il telling a different story,"['c#', 'asp.net']" +231587,401 could not authenticate you header rejected by twitter when trying to upload a picture with php to twitpic i am using meltingices api for twitpic and when i try to upload a picture i get a 401 error with the message could not authenticate you header rejected by twittermy headers retrieved from the http request2 object arearray useragent http request2200 request2 php5217 xverifycredentialsauthorization oauth realm oauth consumer key oauth signature methodhmacsha1 oauth token oauth timestamp1325192643 oauth nonce oauth version10 oauth signature3d xauthserviceprovider credentialsjson contenttype multipartformdatai made sure that the verify credentials signature is using get and i cannot see any other issueswhat am i doing wrongthanks edit heres my source codevenue thisvenuefindbyidvenueidtwitterdata json decodevenuevenuetwitter datatoken twitterdatatokensecret twitterdatasecretthistwitterlogintwitterusertoken secretrequire oncew roottwitpictwitpicphptwitpic new twitpic token secretresultresult twitpicuploadarraymedia hometodayspublic htmltsmappwebrootfilesuploadslogoa7v1 10png message testand i am sure that the token secret and app credentials are correct as they work in my twitter api without any problems i have also double checked the twitpic api key,['php'] +231602,what library to use to write xml file in a c program what library to use to write xml file in a c programi have found two classes posted in codeproject xmlwriteraspx writeraspxbut want to check if there is more standard option than these i am only concerned with writing and not parsing xml,['c++'] +231657,how do i prevent a buttons background image from stretching i am allocating a uibuttontypecustom uibutton to a uiview with a background image that is smaller than the buttons frame reason why the image is smaller is because i am trying to add more of a target area for the uibutton however the image is being scaled to the full size of the frame rather than just being the images sizei have tried setting the uibutton and uibuttons imageview contentmode property to uiviewcontentmodescaleaspectfit but no luck the image still gets stretched outis there a way to do what i am trying to do programmaticallythanks in advance,['ios'] +231658,consumer closed input channel or an error occurred events0x8 dandroidruntime11752 dandroidruntime11752 androidruntime start comandroidinternalosruntimeinit dandroidruntime11752 checkjni is onddalvikvm11752 creating instr width tableejdwp 11752 pipe failedwprocestate11752 opening devbinder failed too many open filesdandroidruntime11752 calling main entry comandroidcommandsamamimamarduke diag 1726 data is available nowimamarduke diag 1726 exec result javalangnullpointerexceptionidmic 1726 javalangnullpointerexceptionisystemout 1726 wifi state end1ddalvikvm 1726 gc explicit freed 31k 41 free 7507k12551k external 1625k2137k paused 58msddalvikvm 1726 gc explicit freed 0k 41 free 7507k12551k external 1625k2137k paused 58msisystemout 1726 run in test i7cameraisystemout 1726 run in test i8cecisystemout 1726 run in test i9edidisystemout 1726 wifi state start1imamarduke diag 1726 data is available nowimamarduke diag 1726 exec result isystemout 1726 wifi state end1ddalvikvm 1726 gc explicit freed 36k 41 free 7474k12551k external 1625k2137k paused 57msddalvikvm 1726 gc explicit freed 0k 41 free 7474k12551k external 1625k2137k paused 58msisystemout 1726 run in test i10irisisystemout 1726 wifi state start1iactivitymanager 1491 starting intent actcomandroidcamerairison flg0x10 cmpcomiancapdtestcasecameraeximagecamera from pid 1726isystemout 1726 oncreateisystemout 1726 onresumeisystemout 1726 test irist onisystemout 1726 excutecmdsysbusspidevicesspi20irisstateeinputthispatcher 1491 channel 40643898 comiancapdcomiancapdtestcasecameraeximagecamera server consumer closed input channel or an error occurred events0x8einputthispatcher 1491 channel 40643898 comiancapdcomiancapdtestcasecameraeximagecamera server channel is unrecoverably broken and will be thisposeddandroidruntime 1726 shutting down vmwdalvikvm 1726 threadid1 thread exiting with uncaught exception group0x40015560iwindowmanager 1491 window died window40643898 comiancapdcomiancapdtestcasecameraeximagecamera pausedfalseeandroidruntime 1726 fatal exception maineandroidruntime 1726 javalangruntimeexception could not read input channel file descriptors from parceleandroidruntime 1726 at androidviewinputchannelnativereadfromparcelnative methodeandroidruntime 1726 at androidviewinputchannelreadfromparcelinputchanneljava138eandroidruntime 1726 at androidviewiwindowsessionstubproxyaddiwindowsessionjava409eandroidruntime 1726 at androidviewviewrootsetviewviewrootjava498eandroidruntime 1726 at androidviewwindowmanagerimpladdviewwindowmanagerimpljava177eandroidruntime 1726 at androidviewwindowmanagerimpladdviewwindowmanagerimpljava91eandroidruntime 1726 at androidviewwindowlocalwindowmanageraddviewwindowjava424eandroidruntime 1726 at androidappactivitythreadhandleresumeactivityactivitythreadjava2170eandroidruntime 1726 at androidappactivitythreadhandlelaunchactivityactivitythreadjava1668eandroidruntime 1726 at androidappactivitythreadaccess1500activitythreadjava117eandroidruntime 1726 at androidappactivitythreadhhandlemessageactivitythreadjava931eandroidruntime 1726 at androidoshandlerthispatchmessagehandlerjava99eandroidruntime 1726 at androidoslooperlooplooperjava130eandroidruntime 1726 at androidappactivitythreadmainactivitythreadjava3683eandroidruntime 1726 at javalangreflectmethodinvokenativenative methodeandroidruntime 1726 at javalangreflectmethodinvokemethodjava507eandroidruntime 1726 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava839eandroidruntime 1726 at comandroidinternaloszygoteinitmainzygoteinitjava597eandroidruntime 1726 at dalviksystemnativestartmainnative methodwactivitymanager 1491 force finishing activity comiancapdtestcasecameraeximagecamerawactivitymanager 1491 activity pause timeout for historyrecord4069a248 comiancapdtestcasecameraeximagecamerawhy do consumer closed input channel or an error occurred events0x8 happen after many times running that is too say my program can run at first but after many times the exception happeni read this input transport and input thispatcher error on 23 but i have no idea how to solve it who can help mei run my program in real device the android version is 23update 1i found the root cause of could not read input channel file descriptors from parcelit is ejdwp 11752 pipe failed why do create pipe failed because the pipe is out of the max in the system that is to say we create a lot of pipe or file descriptors in the system and then we found the reason and try to modify it my friend change the code like that in his activity original source code private class myhandler extends handler myhandlerlooper looper superlooper override public void handlemessagemessage msg switchmsgwhat case release camera synchronized cameraholderthis in cameraholderopen the release camera message will be removed if it is found in the queue however there is a chance that this message has been handled before being removed so we need to add a check here if cameraholderthismusers 0 releasecamera break handlerthread ht new handlerthreadcameraholderhtstartmhandler new myhandlerhtgetlooperchange to private class myhandler extends handler myhandlerlooper looper superlooper override public void handlemessagemessage msg switchmsgwhat case release camera synchronized cameraholderthis in cameraholderopen the release camera message will be removed if it is found in the queue however there is a chance that this message has been handled before being removed so we need to add a check here if cameraholderthismusers 0 releasecamera break mhandler new myhandlerthose file descriptors will reduce obviously why how to explain this case and i add mhandlerremovemessage this function to onpause in my activity and those file descriptors also reduce obviously why who can explain this case for me i am trying to understand this,['android'] +231673,how to remove the extra black line beneath uisearchbar after setting the tint of a uisearchbar to whitethere is an extra black line between the search box and the tablehow can i remove the black line,['iphone'] +231678,cancelabortconfirm an html 5 state change event onpopstate with unload event of window it is possible to show the user a confirmation dialog let us say in a situation where there is an ongoing request you are waiting for to finish and navigating away from the page will terminate that requestis there a way to accomplish this with onpopstate of html5 history api or any other way with the same outcome,['javascript'] +231692,multiple lines when using jquerys html method i would like to have multiple lines when i use jquerys html method like thissomeidhtml h1headline 1h1 h1headline 2h1 however this snippet of code does not work is there a way to use multiple lines when using jquerys html method,['jquery'] +231706,what is the reason for having unreserved identifiers as builtin macros in gcc today i stumbled upon a rather interesting compiler errorint main int const unix 0 errorline return unixgives the following message with gcc 432 yes ancienterror expected unqualifiedid before numeric constantwhich is definitely quite confusingfortunately clang 30 is a little more helpful as usualerror expected unqualifiedid int const unix 0 builtin12714 note expanded fromdefine unix 1 i certainly did not expect unix which is neither written in uppercase nor begin with underscore to be a macro especially a builtin onei checked the predefined macros in gcc and there are 2 on my platform that use unreserved symbols g e dm devnull grep v define unix 1define linux 1all the others are wellbehaved macros with leading underscores using the traditional reserved identifiers sampledefine linux 1define linux 1define gnu linux 1define unix 1define unix 1define char bit 8define x86 64 1define amd64 1define lp64 1it is a mess and there does not seem to be any particular orderfurthermore there are lots of similar symbols so i guess there is an issue of backward compatibilityso where do the unix and linux macros come from,['c++'] +231717,django model error typeerror x is an invalid keyword argument for this function i get the errortypeerror person is an invalid keyword argument for this functionmy model is class investmentmodelsmodelcompany modelsmanytomanyfieldcompany related name investments companyfinancial org modelsmanytomanyfieldfinancial org related name investments financial orgperson modelsmanytomanyfieldperson related name investments personmy test that gives the errorinvestment1 investmentcompany financial org financial1 person,['python'] +231720,entity framework persisting enums generically trying to create a workaround for processing enums in the entity framework using generics but ef does not seem to care for generic properties for examplepublic enum myenum one two threepublic class somepocowithenum i want this to persist as an int but ef does not like generics public enumwrappermyenum myenumproperty get set the intention is to have the enum persist as an int in the database is there any special way using fluent or perhaps some other mechanism method whereby i can create said generic class and have it persist as an int to the database within efthe intention is to keep things generic as i have about two dozen enums that need persisting and i would rather not write individual wrapper classes for each of themhere is the generic enumwrapper class which demonstrates what i would like to accomplish implicit conversion to enum but persistence as an intpublic class enumwrappert where t struct private t enumvalue public int value get return converttoint32enumvalue set enumvalue tenumparsetypeoft valuetostring public t enumvalue get return enumvalue set enumvalue value public static implicit operator tenumwrappert wt return wtenumvalue public static implicit operator enumwrappertt t return new enumwrappert enumvalue t public override string tostring return enumvaluetostring,['c#'] +231721,what is wrong with control characters in phpunit command line tool when i run phpunit from a command line the control characters are being printed out instead of acting like control characters take look at thisphpunit 365 by sebastian bergmannconfiguration read from aphpunitxmlthisttime 1 second memory 1200mba13042ma12kok 3 tests 3 assertionsa10ma12ki assume that signs like a13042m are some kind of control characters and should be used by console in different way positioning the cursor deleting characters etcwhat can be wrong here,['php'] +231742,noclassdeffounderror for code in an java library on android i am experiencing an error quite often among my users the app crashes during startup when the mainactivity is supposed to be loaded the vm apparently cannot find the class i cannot figure out why the architecture of the app is that there is a common project that both my free and pro version are using do not know if it is relevant see the stack trace below any thoughtsjavalangnoclassdeffounderror comandroidcommonmainactivityat commycompanymyappsplashoncreatesplashjava23at androidappinstrumentationcallactivityoncreateinstrumentationjava1047at androidappactivitythreadperformlaunchactivityactivitythreadjava1615at androidappactivitythreadhandlelaunchactivityactivitythreadjava1667at androidappactivitythreadaccess1500activitythreadjava117at androidappactivitythreadhhandlemessageactivitythreadjava935at androidoshandlerthispatchmessagehandlerjava99at androidoslooperlooplooperjava130at androidappactivitythreadmainactivitythreadjava3687at javalangreflectmethodinvokenativenative methodat javalangreflectmethodinvokemethodjava507at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava842at comandroidinternaloszygoteinitmainzygoteinitjava600at dalviksystemnativestartmainnative methodcaused by javalangclassnotfoundexception comandroidcommonmainactivity in loader dalviksystempathclassloadersystemframeworkcomgoogleandroidmapsjardataappcomandroidpro1apkeditthanks for the comment below richard now i have changed comandroidsplash to something else it was not the real classname anyway my bad,['android'] +231760,detecting memory access to a process i am trying to check if an application tries to manipulate a particular process for ex hooks itself to it i could not find a proper approach to accomplish this is computing checksum over running process possible if it is not how can i detect this situation,['c#'] +231767,checking if 2 arrays have atleast 1 equal value currently i have 2 arrayarray1 2 3 4array4 5 6 7how can i check if there is atleast one equal value in both of them the example above has 1 equal value 4 so the function should return true,['php'] +231771,opencart show category images on homepage i am using the most up to date version of open cart what i am wanting to do is show the image from the store category page on every page page as i am wanting to implement it into the menu you can see what i mean here in the cetegorytpl file i found php if thumb div classimageimg srcphp echo thumb altphp echo heading title divphp but i have come to realise that it is not as easy as copy and pasting this into the headertpl etc what do i do,['php'] +231782,why are python strings immutable best practices for using them what are the design reasons of making python strings immutable how does it make programming easieri am used to mutable strings like the ones in c how am i supposed to program without mutable strings are there any best practices,['python'] +231808,can you assign multiple variables at once in php like you can with java i want to create 5 variables of type array all at once is this possible in java i know you can but cannot find anything about php i would like to do something like thisvar1 var2 var3 var4 var5 array,['php'] +231810,why does not int00 cause an access violation for educational purposes i am writing a set of methods that cause runtime exceptions in c to understand what all the exceptions are and what causes them right now i am tinkering with programs that cause an accessviolationexceptionthe most obvious way to me to do this was to write to a protected memory location like thissystemruntimeinteropservicesmarshalwriteint32intptrzero 0just as i had hoped this threw an accessviolationexception i wanted to do it more concisely so i decided to write a program with unsafe code and do what i thought was exactly the same thing by assigning 0 to the zeropointerunsafe int0 0for reasons that elude me this throws a nullreferenceexception i played around with it some and found out that using int1 instead also throws a nullreferenceexception but if you use a negative number like int1 it will throw an accessviolationexceptionwhats going on here why does int0 0 cause a nullreferenceexception and why does not it cause an accessviolationexception,['c#'] +231826,android 22 mediaplayer is working fine with one shoutcast url but not with the other one please see the code i am using for streaming shoutcast stream it works with one url but not with the other onethis one worksuri myuri uriparsebut not with this oneuri myuri uriparsehttpsomeotherurlsimplemusicstreamjavaimport androidappactivityimport androidmediaaudiomanagerimport androidmediamediaplayerimport androidneturiimport androidosbundleimport androidutillogimport androidviewviewimport androidwidgetbuttonpublic class simplemusicstream extends activity implements mediaplayeroncompletionlistener mediaplayeronpreparedlistener mediaplayeronerrorlistener mediaplayeronbufferingupdatelistener private string tag getclassgetsimplename private mediaplayer mp null private button play private button pause private button stop override public void oncreatebundle icicle superoncreateicicle setcontentviewrlayoutmain play button findviewbyidridplay pause button findviewbyidridpause stop button findviewbyidridstop playsetonclicklistenernew viewonclicklistener public void onclickview view play pausesetonclicklistenernew viewonclicklistener public void onclickview view pause stopsetonclicklistenernew viewonclicklistener public void onclickview view stop private void play uri myuri uriparse try if mp null thismp new mediaplayer else mpstop mpreset mpsetdatasourcethis myuri go to initialized state mpsetaudiostreamtypeaudiomanagerstream music mpsetonpreparedlistenerthis mpsetonbufferingupdatelistenerthis mpsetonerrorlistenerthis mpprepareasync logdtag loadclip done catch throwable t logdtag ttostring override public void onpreparedmediaplayer mp logdtag stream is prepared mpstart private void pause mppause private void stop mpstop override public void ondestroy superondestroy stop public void oncompletionmediaplayer mp stop public boolean onerrormediaplayer mp int what int extra stringbuilder sb new stringbuilder sbappendmedia player error switch what case mediaplayermedia error not valid for progressive playback sbappendnot valid for progressive playback break case mediaplayermedia error server died sbappendserver died break case mediaplayermedia error unknown sbappendunknown break default sbappend non standard sbappendwhat sbappend sbappend what sbappendextra logetag sbtostring return true public void onbufferingupdatemediaplayer mp int percent logdtag playerservice onbufferingupdate percent mainxmlxml version10 encodingutf8linearlayout xmlnsandroid androidlayout widthfill parent androidlayout heightfill parent button androidtextplay androidididplay androidlayout widthwrap content androidlayout heightwrap contentbutton button androidtextpause androidididpause androidlayout widthwrap content androidlayout heightwrap contentbutton button androidtextstop androidididstop androidlayout widthwrap content androidlayout heightwrap contentbuttonlinearlayoutthe logcat shows errorsnuhttpdatasource33 server did not give us the content lengthmedia player error unknown 1 2147483648media player error unknown 1 1002can someone help me to fix iteditjust to share with you people that our current code works with android 21 minor versions but not works with android 22 or higherthanks,['android'] +231828,microsoft jscript runtime error function expected i have the following javascript function with some jquery in it when i call the createappointmentconfirm function it tries to call the sendmailid function but throws an errormicrosoft jscript runtime error function expectedand firefox debugger throws an errorsendmail is not a function break on this error sendmaildatamessagehere is the code thank you for your helpfunction createappointmentconfirmdata if dataerror alertdatamessage else if sendmailattrchecked checked sendmaildatamessage refreshappointmentlist function sendmailid ajax url sendmailattrtitle data id id type post beforesend function sendingmaildialog modal true success function data if dataerror alertdatamessage sendingmaildialogclose error function alerterror sending mail sendingmaildialogclose,"['javascript', 'jquery']" +231841,background colour of sliding drawer i am currently working on an android project and making use of the slidingdrawer but i am having a problem with changing the background colour by default the slidingdrawer appears to be transparent so when it is slid up over the content it is hard to read the content of the slidingdrawer due to the main screen being shown underneath i wanted to change the background colour to black but for some reason this changes the background colour of the main content so you cannot see any of the content and only the content of the sliding drawer when it is pushed up the screen below is the code that i have used to generate the sliding drawerslidingdrawer androidlayout widthfill parent androidlayout heightfill parent androidididdrawer androidhandleidhandle androidcontentidcontent androidbackgroundcolorblack imageview androidlayout widthwrap content androidlayout heightwrap content androidididhandle androidsrcdrawableic launcher linearlayout androidlayout widthfill parent androidlayout heightfill parent androidorientationvertical androidididcontent textview androidlayout widthwrap content androidlayout heightwrap content androidtexti am a sliding drawer hello world linearlayout slidingdrawerthanks for any help you can provide,['android'] +231849,how to do mysql in clauses using zend db i am trying to fetch rows that are in an array of integers that i have using zend framework 1thisdbselect fromtable prefix product link joinlefttable prefix product link name table prefix product linkproduct link name ref id table prefix product link nameproduct link name id whereproduct ref id in implode product idswhen i use the tostring method of thisdbselect i get select phc thistrib product link phc thistrib product link name from phc thistrib product link left join phc thistrib product link name on phc thistrib product linkproduct link name ref id phc thistrib product link nameproduct link name id where product ref id in 10 12this only returns rows satisfying the condition where product ref id 10how can i get the in clause to be product ref id in 10 12or product ref id in 10 12using zend db prepared statements so i can fetch all rows contained inside the product id array,['mysql'] +231850,best way to consume json from rest api in net i am working on a net web app in c and i need to consume a rest service from a third party they are not using wcf i am coming from a background of using web service calls where there was a wsdl available and visual studio would build all of the underlying code and then i am ready to gois there no tool or framework that can to some degree simulate this behavior i understand that without a contract there is no way for a tool to know what to expect but i would think i could go through a wizard where i supply parameters to make a rest call and then help the wizard work out the details of the response at the end of the process i would have a set of objects that model the rest api similar to how the web service behave i know that rest and json have some great advantages to them but the lack of a standard out of the box contract to allow automated code generation seems like a real step backwards am i missing something obvious or is that just the current state of affairs when consuming rest in net do i really need to write boiler plate code for each new api,['.net'] +231864,finding the most common threeitem sequence in a very large file i have many log files of webpage visits where each visit is associated with a user id and a timestamp i need to identify the most popular ie most often visited threepage sequence of alla the log files are too large to be held in main memory at oncesample log fileuser ida page idaa a a a a a a a a 1aa a a a a a a a a 2aa a a a a a a a a 3ba a a a a a a a a 2ba a a a a a a a a 3ca a a a a a a a a 1ba a a a a a a a a 4aa a a a a a a a a 4corresponding resultsai14 123i14 234 bi14 234 234 is the most popular threepage sequencemy idea is to use use two hash tables the first hashes on user id and stores its sequence the second hashes threepage sequences and stores the number of times each one appears this takes on space and on timehowever since i have to use two hash tables memory cannot hold everything at once and i have to use thisk it is not efficient to access thisk very oftenhow can i do this better,"['c++', 'c']" +231874,how to set up acts as follower i am using the gem acts as follower in a rails app i set it up and it works in console however i am clueless as to how to set it up in a view i want to make a button correspond to the userfollow and userstop following methodsthe github does not explain this help please,['ruby-on-rails'] +231892,uploading a file to wcf service using html5 andor jquery i am trying to upload a file to my wcf service using only html5 and javascriptjquery the wcf service is self hosted from a windows service instead of iis so i do not think i can use php or aspx upload handlers the files are binary and not textideally i would like to end up with a net stream object where i can write the file locally server side at this point i am just looking for very very basic file uploadingi can do json communication currently but cant make the leap to binary files currently i am this far and stuckservice interfaceoperationcontractwebinvokemethod post uritemplate sendfilestring sendfilestream streamservice implementation public string sendfilestream stream this works for strings but i want a filestream streamreader reader new streamreaderstream string data readerreadtoend return data html input typefile idfileinput onchangesendfile javascript jquery function sendfile submitbuttonthisabled true setinnertextsending file var file documentgetelementbyidfileinputfiles0 var url ajax url url type post data file in the chrome console i get an illegal invocation error i could use data filename and that would work fine however i need to send a stream of the file contents so i can rebuild it on the server sideany ideas,['jquery'] +231900,how to stitch images with very little overlap i am trying to create a panorama using images with very little overlap but i know the angle of the camera so i know exactly how much overlap there is and i know the order of the images so i know where each one belongs in the panorama as a first pass i simply cocantenated the images together but the result is not good enoughis there a way to crop the bitmaps to trapezoids to eliminate most of the the overlap then stretch the bitmaps back to rectangles before the concantenationi know this will produce thistortion during the stretching and that a trapezoid is just a close approximation to how the bitmap actually needs to be cropped but i am hoping this will be good enough,['c#'] +231906,scale html canvas to browser window size but do not scale elements within the canvas is there a way to scale your html canvas to the browser window widthheight but not scale the contents within it say i was creating asteroids and want to use the entire browser window but do not want the rocks and ship to scale updown when i resize the window,['html'] +231931,how does an ajax request differ from a normal browser request everybody this question has been bugging me for a whileis there a difference in how a web page is called and loaded when called through an javascript ajax request instead of a direct browser requestie do requests look different from the serverside and are answers handled differently on the clientbrowser side,"['javascript', 'html']" +231932,adding header to python request module earlier i used httplib module to add header in the request now i am trying same thing with the request modulethis is the python request module i am usinghow can i add header to the requestpost and requestget say i have to add foobar key in each request in header,['python'] +231935,how to specify androidlistselectornull programmatically for some reason i did not have extra space around gridviews column borders in emulator but found out that the extra pixels in my real device galaxy s so i would like to tryandroidlistselectornull programmaticallyi know its related method is setselector but what number or id should i give for null i tried 0 but it made app crashupdate i resolved the problem by making my own selector,['android'] +231946,what is nak limit am trying to understand how the android open accessory api works with the arduino adk board i have been able send and receive information but i just want to know how everything works i got to this function descriptionint androidaccessoryreadvoid buff int len unsigned int naklimit return usbnewintransfer1 in len char buff naklimit from some googling i figured that nak is some code that gets sent if something went wrong during the handshake so is nak limit the number of communication errors one is able to receive,['android'] +231967,weird render on heroku with rendering templates appappviews i am having a weird issuelocally everything renders fine and when i fire it up on heroku i get this error201231t0626230 appweb1 actionviewmissingtemplate missing template pagesindex applicationindex with handlerserb builder formatshtml localeen en searched in201231t0626230 appweb1 appappviews201231t0626230 appweb1 why is it blows up with appappviews why would it have two apps in there i am not sure whats wrong it is a pretty basic app i have not done anything fancy,['ruby-on-rails'] +231968,facebook key hash android keystore confusion keytool exportcert alias mykeystore keystore mykeystore openssl sha1 binary openssl base64hello i am using the above command to generate my facebook key hash it asks for my password and gives me a key hash i put this key hash in the facebook app settings yet it does not work for my signed android appwhen i was debugging the android app i saw the console message saying it did not recognize android key hash blahblahblah so i copied blahblahblah into the facebook app and that worked my android app was able to use the facebook stuff while in debug mode but clearly that was only for the debug keystore now for the real keystore the one it generates is still wrong so a production version of my app will not be able to use facebook apione thing about my keystore is that it was made in eclipse it is one keystore with two keys in it i have noticed that eclipse keystore acts different than command line keystore things and that they are incompatible for signing things yet i have already released a version of my app so i need to make due with the keys i am already usinginsight appreciated,['android'] +231972,validate a filename in python i am writing a personal wikistyle program in python that stores textfiles in a user configurable directorythe program should be able to take a string eg foo from a user and create a filename of footxt the user will only be able to create the file inside the wiki directory and slashes will create a subdir eg foobar becomes pathtowikifoobartxt what is the best way to check that the input is as safe as possible what do i need to watch out for directory traversal null bytes 0 i realize that taking user input for filenames is never 100 safe but the program will only be run locally and i just want to guard for any common errorsglitches,['python'] +231984,is it possible for an aspnet mvc action method to receive json without declaring its specific type on the parameter if so how so it pretty much is all in the title basically i want to send a json through jquery from client to aspnet mvc i am wondering if it is possible for it to receive but not necessarily parse any json i want to send from jquery ajax call regardless of it is type without me having a concrete typemodel representation of it basically like a dynamic typedoing this the regular way with me declaring the passing argument as type object just brings about nulls which was what i expectedbasically i want to do some kind of reflection for json type stuff when i receive it and be able to get it is properties through some kind of foreach loop and etcthanks in advance any help would be great,['c#'] +231992,trigger 500 internal server error in php and thisplay apache error page how can i trigger 500 internal server error or 404 page not found apache errors in phpfor 500 internal server error i have tried following code headerhttp10 500 internal server errorbut it shows me a blank pagehow can i show the error in apache is default formatplease guide,['php'] +231993,c cad libraries i have 3 projects to be done by the end of next semester on 3d cad programming i am very good at c i came to know that c offers great support with opengl directx etc but it takes a lot of time for me to learn them if i use c my development time will be greatly reduced i would like to know the followingare there any net libraries that can be used for this purposecan gdi be used for 3d programming please note that my program needs to have standard cad features like panning rotating and zooming object selection vertex picking etc,"['c#', '.net']" +231994,using favicon with css i want to set the favicon for a fairly large number of pages but instead of using the html head tag link relshortcut icon hreffaviconico i would like to set it in the css file i have limited access to some of the html files and limited control to their life cycle,"['html', 'css']" +231996,when to use swingutiliesinvokeandwaitinvokelater i read somewhere that for any thread that affects the visuals of the gui it should be ran in the edt using swingutilitiesinvokeandwaitinvokelaterfor a basic gui is it necessary to put something like new swingguisetvisibletrue in the line of the edt using invokeandwait just to thisplaydoes this count,['java'] +232016,adding jquery ui to greasemonkey script fails with external css file i am trying to add jqueryui to a greasemonkey script my full code testuserjs userscript name test namespace rajatkhandelwal description test script include require jsjquery162minjs require jsjqueryui1816customminjs require cssuidarknessjqueryui1816customcss userscriptalerthiand in current directory i added js and css directory it throws error saying syntax error in css error syntax errorsource file filecusersrajatappdataroamingmozillafirefoxprofilespoxivdqydefaultgm scriptstestjqueryui1816customcssline 13line 13 is uihelperhidden thisplay none what is the problem how can i add jqueryui and use it in my userscript,['jquery'] +232017,using managed threads and fibers in clr okay the following link has a warning that the thiscussion uses unsupported and undocumented apis well i am trying to use the code sample any way it mostly works any ideas about the specific issue below relating to exceptionsfyi i made an improvement over the original sample it was maintaining a pointer to the previousfiber instead the updated sample below uses a mainfiber pointer which gets passed to every fiber class in that way they always yield back to the main fiber that allows the main fiber to handle scheduling for all other fibers the other fibers always yield back to the main fiberthe reason for posting this question has to do with throwing exceptions inside a fiber according to the article by using the corbindtoruntime api with createlogicalthreadstate switchoutlogicalthreadstate etc the framework will create a managed thread for each fiber and properly handle exceptionshowever in the included code examples it has an uunit test which experiments with throwing a managed exception within a fiber and also catching it within the same fiber that soft of works but after handling it by logging a message it seems the stack is in a bad state because if the fiber calls any other method even an empty method the whole application crashesthis implies to me that switchoutlogicalthreadstate and switchinlogicalthreadstate maybe are not being used properly or else maybe they are not doing their jobnote one clue to the problem is that the managed code logs out the threadcurrentthreadmanagedthreadid and it is the same for every fiber this suggests that the createlogicalthreadstate method did not really create a new managed thread as advertisedto analyze this better i have made a pseudocode listing of the order of low level apis called to handle the fibers remember that fibers all run on the same thread so there is nothing concurrently happening it is a linear logic the necessary trick of course is to save and restore the stack that is where it seems to be having troubleit starts out as simply a thread so then it converts to a fiberconvertthreadtofiberobjptrcreatefiber create several win32 fibersnow invoke a fiber the first time it is startup method does thiscorhostswitchoutlogicalthreadstatecookie the main cookie isheld on the stackswitchtofiber first time calls the fiber startup methodcorhostcreatelogicalthreadstaterun the main fiber abstract methodeventually the fiber needs to yield back to the main fibercorhostswitchoutlogicalthreadstatecookieswitchtofiberfibercorhostswitchinlogicalthreadstatecookie the main fiber cookie rightalso the main fiber will resume a preexisting fibercorhostswitchoutlogicalthreadstatecookieswitchtofiberfibercorhostswitchinlogicalthreadstatecookie the main fiber cookie rightthe following is fiberscpp which wraps the fiber api for managed codedefine win32 winnt 0x400using mscorlibdllinclude windowshinclude mscoreehinclude iostreamusing namespace stdif definedyieldundef yieldendifdefine corhostnamespace fibers typedef systemruntimeinteropservicesgchandle gchandlevoid callback unmanaged fiberprocpvoid pvoid gc private struct stopfiber enum fiberstateenum fibercreated fiberrunning fiberstoppending fiberstoppedpragma unmanagedif definedcorhosticorruntimehost corhostvoid initialize corhost corbindtocurrentruntime0 clsid corruntimehost iid icorruntimehost void corhostendifvoid corswitchtofibervoid fiber if definedcorhost dword cookie corhostswitchoutlogicalthreadstatecookieendif switchtofiberfiberif definedcorhost corhostswitchinlogicalthreadstatecookieendifpragma managed gc abstract public class fiber public systemithisposable publicif definedcorhost static fiber initialize corhost endif fiber statefibercreated void objptr void gchandleop explicitgchandleallocthis fiber convertthreadtofiberobjptr mainfiber fiber systemconsolewriteline screated main fiber fiberfiber mainfiber statefibercreated void objptr void gchandleop explicitgchandleallocthis fiber createfiber0 unmanaged fiberproc objptr mainfiber mainfiberfiber systemconsolewritelinescreated worker fiber property bool get isrunning return state fiberstopped int gethashcode return int fiber bool resume iffiber state fiberstopped return false if state fiberstoppending thispose return false void current getcurrentfiber iffiber current return false corswitchtofiberfiber return true void thispose iffiber void current getcurrentfiber iffiber current state fiberstoppending corswitchtofibermainfiber state fiberstopped systemconsolewriteline sndeleting fiber deletefiberfiber fiber 0 protected virtual void run 0 void yield corswitchtofibermainfiber ifstate fiberstoppending throw new stopfiber private void fiber mainfiber fiberstateenum stateprivate public void main state fiberrunning try run catchsystemobject x systemconsoleerrorwriteline snfibersdll main caught 0 x thispose void fibermainvoid objptr systemconsolewriteline snfibermain systemintptr ptr systemintptr objptr gchandle g gchandleop explicitptr fiber fiber static castfibergtarget gfree fibermain systemconsolewriteline snfibermain returningpragma unmanagedvoid callback unmanaged fiberprocpvoid objptr if definedcorhost corhostcreatelogicalthreadstateendif fibermainobjptrif definedcorhost corhostdeletelogicalthreadstateendifthe above fiberscpp class file is the only class in the visaul c project it is built as a dll with clr support using clroldstyle switchusing systemusing systemthreadingusing fibersusing nunitframeworknamespace tickzoomutilities public class fibertask fiber public fibertask public fibertaskfibertask maintask basemaintask protected override void run while true consolewritelinetop of worker loop try work catch exception ex consolewritelineexception exmessage consolewritelineafter the exception work private void work consolewritelinedoing work on fiber gethashcode thread id threadcurrentthreadmanagedthreadid counter consolewritelineincremented counter counter if counter 2 consolewritelinethrowing an exception throw new invalidcastexceptionjust a test exception yield public static int counter testfixture public class testingfibers test public void testideas var fibertasks new systemcollectionsgenericlistfibertask var mainfiber new fibertask for var i0 i 5 i fibertasksaddnew fibertaskmainfiber for var i 0 i fibertaskscount i consolewritelineresuming i var fibertask fibertasksi if fibertaskresume consolewritelinefiber i was thisposed fibertasksremoveati i for var i 0 i fibertaskscount i consolewritelinethisposing i fibertasksithispose the above unit test gives the following output and then crashes badlyresuming 0top of worker loopdoing work on fiber 476184704 thread id 7incremented counter 1resuming 1top of worker loopdoing work on fiber 453842656 thread id 7incremented counter 2throwing an exceptionexception just a test exceptionafter the exception,"['c#', 'c++']" +232064,c have a simple loop that does arithmetic calculation profiler shows this is a bottleneck how to speed it up my first post here a great site and resourcei did search a bit and looked at the questions with similar titles but could not find something specifically about thisi am trying to remove any redundancy and bloat from a c astronomical calculation library that my c program uses i ran a simple profiler verysleepyhere is the code that the profiler showed as using the most time aside from c library functions sprintf etcdouble swi echebconst double x const double const coef const int ncf int j ncf 1 double x2 br brp2 brpp x2 x 2 br 0 brp2 0 dummy assign to silence gcc warning brpp 0 for j 0 j 039s brp2 brpp 001s brpp br 032s br x2 brpp brp2 coefj 349s 014s return br brp2 5 006s 005sthis particular function is deeply embedded within others and the main kickoff function that my program calls is called thousands of timesyou can see the standout statement with 349s as much higher than all the other statement times i know there are ways to speed c arithmetic with using multiplication over division when possible but i do not know much more than thatlikewould it be better to split this statement up into smaller piecesbr x2 brppbr brp2br coefjany other ideas or critiques i did not write this code though i did add the const to the function parameters as i love constcorrectnessi have never tried using registers or other fancy tricks to speed things up before anyone think something like that can work herei know people will say try it so i will and will update what i get if it helps anyone with similar arithmetic questionsedit posting results i have tested from suggestionsin order from fastest to slowest here are what i have found so far profiler is verysleepy compiler is visual studio 2008 pro ed compile options for both library and my application aredebug c7 format o2 ob2 oi ot oy gt gl gf fd mtd gs gy fpfast fasthe following is andrews suggestion about doing 4 iterations per loop it was the fastest so fartotal time spent in function times from the other statements in the function are not shown here 208 secondsfor index 3 index 4 002s brp2 brpp brpp br 002s br x2 brpp brp2 coefindex 025s brp2 brpp brpp br 013s br x2 brpp brp2 coefindex 1 033s brp2 brpp brpp br 013s br x2 brpp brp2 coefindex 2 034s brp2 brpp brpp br 014s br x2 brpp brp2 coefindex 3 042sfor index 0 index 003s brp2 brpp 003s brpp br br x2 brpp brp2 coefindex 011sthe next fastest was the original unaltered code with a total time of 239 seconds inside the function again including the statements outside the loop note that this is less than my original post my original post was unoptimized code but since everyone suggested it all of my tests were subsequently as optimized as i could get in vs08for j ncf 1 j 0 j 002s brp2 brpp 003s brpp br 007s br x2 brpp brp2 coefj 214safter this original code the next fastest was drews idea of setting the pointer in advance and using that total time spent inside function was 249 seconds including times from statements outside loopfor index coef index 001s brp2 brpp brpp br 006s br x2 brpp brp2 index 224si also tried a mix of both andrews loop unrolling and drews pointer usage but that took 239 seconds the same as the unaltered codebased on the results the loopunrolling is the way to go so far for my usage,['c'] +232071,how to get language locale currently android app thisplays how to get know language locale currently android app uses to thisplay texts to useri know i can use localegetdefault to get default os locale but it may differ from locale used by app to thisplay text and other resources if this locale is not supported by appi need to determine language locale thisplayed by the app thus the app can pass language to the server so it can localise returned results,['android'] +232134,why the current year in the date saved as 3912 to get the current date and timefinal calendar c calendargetinstancemyear cgetcalendaryearmmonth cgetcalendarmonthmday cgetcalendarday of monthmhour cgetcalendarhour of daymminute cgetcalendarminuteto create current date objectdate todate todatesetyearmyear todatesetmonthmmonth todatesetdatemdaydate enddate todatewhen printing enddate object i got mon jan 01 131100 gmt0300 3912why,['android'] +232156,check to see if a domain is available or not using php if i have a domain like wexamplecom and i want to check if it is available using dns records not whoisis it possible to do this using php,['php'] +232231,how is it possible to pass nsnumber to a method expecting a bool selfviewwindow subviews makeobjectsperformselectorselectorsetuserinteractionenabled withobjectnsnumber numberwithboolnoi saw this code in another questions answer how to thisable touch input to all views except the topmost view and it surprised me when it worked as setuserinteractionenabled expects a bool which as it is not an objectivec object cannot be passed in performselectorwithobject type methodswhere is the documentation that says that passing an nsnumber is ok does it work for all methods or is a special implementation needed and does it only work with bools or can it be done with types like int,['objective-c'] +232244,creating a uisearchthisplaycontroller programmatically i am trying to create a uisearchthisplaycontroller programmatically i have a method which should set up my search controller but when i call it nothing happensthis my setupsearch method voidsetupsearch uisearchbar mybar uisearchthisplaycontroller mycon mybar uisearchbar alloc initwithframecgrectzero mybar sizetofit mycon uisearchthisplaycontroller alloc initwithsearchbarmybar contentscontrollerself mybar release mycondelegate self myconsearchresultsdatasource self myconsearchresultsdelegate self setup scopes nsmutablearray scopes nsuinteger count i nsstring ascope count scope count scopes nsmutablearray alloc initwithcapacitycount fori 0 i count i i create four scopes here myconsearchbarscopebuttontitles scopes scopes release mycon releasei call the above method in the viewdidload method of my subclassed uitableviewcontroller unfortunately nothing happens when my table view controller gets thisplayed in a uitabbarcontrollerany help would be greatly appreciated,['ios'] +232302,how to maintain when django switches to python 3 i am in the process of learning python and had a question about the future i know it is not the most pressing thing to think about currently but i am curious currently django only supports up to python 27 however in the near future it will be supporting python 3 in terms of writing code in python 27 and using the related django framework what happens when the transition to python 3 actually comes alongpresumably i would learn and code in the newer version however what about maintaining the old code does it stay as is does it need to be rewritteni am just curious as to how these transition work also does it make a difference that python 3 is not backwardscompatible what is the consequence of that for instance i read that ruby versions 18 to 19 and even the future 2x were backwardscompatible and less of a leap than python 2x to 3x i wonder if that split between python versions creates any fragmentation problems or code maintenance problems so if someone could try explaining to me what goes on with these updates and the issues at hand when dealing with them i would really appreciate it thanks,['python'] +232308,rake rails save not updating database i am trying to save changes to my database trough a rake task in my rake task i do something likenamespace parts do desc update parts table swap names in title task swap environment do partswap endendin my part class i dodef selfswap partalleach do part if parttitle regex 0 parttitlegsub regex 2 1 puts parttitle partsave end endendhowever this does not save the part the save does return true the puts parttitle does return the value i want if i call partupdatepartid title parttitlethe database updates properly why is this am i doing something wrong in my loop i am working with rails 313 rake 0922 and mysql2 037,['ruby-on-rails'] +232312,application not installed in your phone i run the application in the emulator it works successfully and the icon of the application is show in the emulator menu but when i try to run again that app from the emulator menu it cannot allow me to run from that and thisplay the toast application is not installed in your phonein the image the red rounded is my application icon,['android'] +232340,strange sleep behaviour between systems i have a program that uses sleep win32 api call to make a thread wait for a specific amount of timein short it simulates a camera by sending images prefetched in memory i am using sleep to simulate the frame rate sleep10 fpsthis works fine in my development system intel i5 1st gen win7 64 but when i run it on another system intel i72600 sandybridge the sleep times are totally different and inaccuratefor examplesleep16 sleeps for around 32mssleep3 sleeps for 16msin the past i thought there was a minimum sleep time in windows of 15ms but i do not get that limitation on my dev systemany ideasin addition is there a better way to achieve the frame rate of my simulator,['c++'] +232351,how to validate xml with dtd using java i have following xml filexml version 10 employemp id e001emp idemp name vinod emp nameemp email emp emailemployeei have following dtd fileelement employee emp id emp name emp emailelement emp id pcdataelement emp name pcdataelement emp email pcdatai want to validate this xml file with above dtd using javaplease help thanks,['java'] +232372,how to do sum of sum in mysql query select aid as supplier sum processed weight as total qtyfrom supplier inward ainner join warehouseb on aid bsupplierwhere amaster product id 38group by bsupplieroutput presentsupplier total qty12046 4750012482 9900output neededtotal qty57400here i need the sumtotal qty in this query how to achieve this,"['mysql', 'sql']" +232374,xmlhttprequest in firefox extension i am writing a firefoxextension and want to load data from server but when i try to initialize the xmlhttprequest withvar request new xmlhttprequestthe error console says referenceerror xmlhttprequest is not defineddo i have to include something or why the xmltprequest is not recognized,['javascript'] +232375,extract text and images from pdf using itext5 i need help with extracting text and images from a pdf file with mappings or references to the images in the extracted text using the java library itext5 if itext5 is the wrong tool for this please advise me by recommending another java library that does the same functionthis is so far what i have doneimport javaioioexceptionimport comitextpdftextdocumentimport comitextpdftextdocumentexceptionimport comitextpdftextpdfpdfreaderimport comitextpdftextpdfparserpdfreadercontentparserimport comitextpdftextpdfparserpdftextextractorimport comitextpdftextparagraphpublic class iconverter param args static int page number the new document to which weve added a border rectangle public static final string result homesarahjava for dummies 4th editionimgss public static void mainstring args string doctext string pdfname homesarahjava for dummies 4th editionpdf document document new document documentopen try pdfreader reader new pdfreaderpdfname page number readergetnumberofpages forint i 1 i page number i doctext pdftextextractorgettextfrompagereader i extractimagespdfname documentaddnew paragraph catch exception e eprintstacktrace documentclose parses a pdf and extracts all the images param src the source pdf param dest the resulting pdf public static void extractimagesstring filename throws ioexception documentexception pdfreader reader new pdfreaderfilename pdfreadercontentparser parser new pdfreadercontentparserreader myimagerenderlistener listener new myimagerenderlistenerresult for int i 1 i page number i parserprocesscontenti listener import javaawtimagebufferedimageimport javaiofileoutputstreamimport javaioioexceptionimport javaximageioimageioimport comitextpdftextpdfpdfnameimport comitextpdftextpdfparserimagerenderinfoimport comitextpdftextpdfparserpdfimageobjectimport comitextpdftextpdfparserrenderlistenerimport comitextpdftextpdfparsertextrenderinfopublic class myimagerenderlistener implements renderlistener the new document to which weve added a border rectangle protected string path creates a renderlistener that will look for images public myimagerenderlistenerstring path thispath path see comitextpdftextpdfparserrenderlistenerbegintextblock public void begintextblock see comitextpdftextpdfparserrenderlistenerendtextblock public void endtextblock see comitextpdftextpdfparserrenderlistenerrenderimage comitextpdftextpdfparserimagerenderinfo public void renderimageimagerenderinfo renderinfo try string filename fileoutputstream os pdfimageobject image renderinfogetimage pdfname filter pdfnameimagegetpdfnamefilter if pdfnamedctdecodeequalsfilter filename stringformatpath renderinfogetrefgetnumber jpg os new fileoutputstreamfilename oswriteimagegetstreambytes osflush osclose else if pdfnamejpxdecodeequalsfilter filename stringformatpath renderinfogetrefgetnumber jp2 os new fileoutputstreamfilename oswriteimagegetstreambytes osflush osclose else if pdfnamejbig2decodeequalsfilter ignore filter not supported else bufferedimage awtimage renderinfogetimagegetbufferedimage if awtimage null filename stringformatpath renderinfogetrefgetnumber png imageiowriteawtimage png new fileoutputstreamfilename catch ioexception e eprintstacktrace see comitextpdftextpdfparserrenderlistenerrendertext comitextpdftextpdfparsertextrenderinfo public void rendertexttextrenderinfo renderinfo,['java'] +232394,how to find identical byteobjects in two arrays concurrently i am trying to implement an collision attack on hashes i am visiting the course cryptography therefore i have two arrays of hashes bytesequences byte and want to find hashes which are present in both arrays after some research and a lot of thinking i am sure that the best solution on a singlecore machine would be a hashset add all elements of the first array and check via contains if elements of the second array are already presenthowever i want to implement a concurrent solution since i have access to a machine with 8 cores and 12 gb ram the best solution i can think of is concurrenthashset which could be created via collectionsnewsetfrommapnew concurrenthashmapab using this data structure i could add all elements of the first array in parallel and after all elements where added i can concurrently check via contains for identical hashesso my question is do you know an algorithm designed for this exact problem if not do you have experience using such a concurrenthashset concerning problems and effective runtime complexity or can you recommend another prebuilt data structure which could help meps if anyone is interested in the details i plan to use skandium to parallelize my program,['java'] +232402,jquery datatables ajax method cell alignment i am thisplaying the database table values using data tables i am doing this using the ajax method here is the codeexample1datatable bprocessing true sajaxsource filenamephp bjqueryui true spaginationtype full numbers the output of the filenamephp is aadata 1input typecheckbox nameusernbsptest nameleader35 the html code istable cellpadding0 cellspacing0 border0 classthisplay tablehead idexample1 thead tr classcolhead newbg th width17 aligncenternoth th width194 alignleftuserth th width56 alignleftroleth th width31 alignrightageth tr thead tbody tbody tablein the above html you can see the first column is center aligned and the next two columns are left aligned and the last one is right aligned but in the data out put all are center aligned i tried to use the following aadata div aligncenter1divdiv alignleftinput typecheckbox nameusernbsptest namedivdiv aligncenterleaderdivdiv alignright35div now i got the correct thisplay but while sorting by age it is not correct please help thanks,"['php', 'jquery', 'css']" +232403,python class instance variables and class variables im having a problem understanding how class instance variables work in python i dont understand why when i try this code the list variable seems to be a class variableclass testclass list def init self selflistappendthingp testclassprint plistf testclassprint flistoutputthingthing thingand when i do this it seems to be an instance variableclass testclass def init self selflist selflistappendthingp testclassprint plistf testclassprint flistoutputthingthingmany thanks jon,['python'] +232408,jquery loop through each div i am pretty sure this will be a really easy answer for you jquery whizzes and i am also pretty such it involves a loop of some kindi am trying to perform essentially the same calculation on two separate divs but assigning a different css width value to each id based on the number of images found the calculations i am performing are irrelevant to my problem really but i put them in anyway because it is the actual code i am working withhere is the markupdiv id test1 classtarget div clascrolling img img img divdivdiv id test2 classtarget div clascrolling img img img divdivbelow is my current jquery which works fine but it is inefficient because i have to write another chunk of code for every div added how can i standarthise this so that it runs through every div with the class of target thanks measure the width of each image test1 div1 scrolling imgwidthtest2 div2 scrolling imgwidth find out how many images there are test1img div1 scrolling imglengthtest2img div2 scrolling imglength do the maths final1 test1 test1img12final2 test2 test2img12 apply the maths to the css div1 scrollingwidthfinal1div2 scrollingwidthfinal2,['jquery'] +232410,using nonarc code in an arcenabled project adding facebook when i created my project i made it to support arc so my project will support ios 43 and abovenow i need to integrate twitter and facebook to it both facebook and twitter frameworks given by the companies does not support arcmost of the files have dealloc and released its variables some say to scrap the project and redo it thisabling arc but i cannot afford to do this since i have done most of the stuffi added the fbconnect files there were 4 of them and added fnoobjcarc as described in this tutorial still i get filelocalhostusersillepmorgandocumentsprojectsillepuntitled20folderalphaprojectalphaprojectfbrequestm error automatic reference counting issue existing ivar delegate for unsafe unretained property delegate must be unsafe unretainedi need help i cannot redo this again,"['iphone', 'objective-c']" +232414,binary to string better than a dictionary objective convert binary to stringexample 01010110010101001101010110110110101100101100101 testcode without spacei use a dictionary and my function i search a better way and more efficientfrom textwrap import wrapdico x00 00 x04 0100 x08 010 x0c 01100 x10 010 x14 010100 x18 0110 x1c 0100 010 0100100 01010 0101100 0 01104 0110100 8 010 0100 010d 010100 h 010010 l 01001100 p 01010t 01010100 x 010110 010100 0110d 01100100 h 011010 l 01101100 p 010t 010100 x 010 0100 x03 011x07 01 x0b 01011 x0f 01 x13 010011x17 0101 x1b 011011 x1f 01 01011 01001 0101011 0101 3 0110011 7 01101 01011 01 c 01011 g 0101k 01001011 o 01001 s 01010011 w 010101 01011011 0101 c 011011 g 011001k 01101011 o 01101 s 010011 w 0101 01011 x7f 01 x02 010 x06 0110n 01010 x0e 010 x12 010010 x16 010110x1a 011010 x1e 010 01010 0100110 0101010 01010 2 0110010 6 0110110 01010 010 b 01010 f 010110 j 01001010n 010010 r 01010010 v 01010110 z 01011010 01010 b 011010 f 01100110 j 01101010n 011010 r 010010 v 010110 z 01010 010 x01 01 x05 0101 t 01001 r 01101x11 0101 x15 010101 x19 011001 x1d 0101 0101 0100101 0101001 01011011 01101 5 0110101 9 01001 0101a 0101 e 010101 i 01001001 m 01001101q 010101 u 01010101 y 01011001 010101a 01101 e 01100101 i 01101001 m 01101101q 0101 u 010101 y 01001 0101def decryptbinary function to convert binary into string binary wrapbinary 8 ch for b in binary for i j in dicoitems if j b ch i return chthank by advance,['python'] +232420,python catch any exception and print or log traceback with variable values when i catch unexpected error with sysexcepthook import sysimport tracebackdef handleexceptionexctype excvalue trace print error tracebackprint exceptionexctype excvalue tracesysexcepthook handleexceptionh 1k 0print hkthis is output i geterrortraceback most recent call last file testpy line 13 in module print hkzerodivisionerror integer division or modulo by zerohow can i include variable values h k in traceback simillar to when i include cgitb result is sameeditgreat answer i only modified it like this so it logs trace in a filedef handleexceptionexctype excvalue trace cgitbhooklogdirospathdirname file thisplayfalse formattextexctype excvalue trace,['python'] +232440,what is the most advanced javascript 3d library for the html5 canvas i am looking for a 3d library similar to something like the away3d project flash in javascriptparticularily i need the followingcameras with pan tilt etc preferably with options for smooth movement like the away3d hovercam3d text proper 3d models not just a drop shadowmeshes textures etca collection of primitives like triangles along with objects such as sphereslightingsupport for ie so possibly something that renders webgl for chrome then switches to something worse for iepreferably open source but commercial would be fine at a good pricethanks in advance,"['javascript', 'html']" +232460,custom error 403 page php i created a htaccess inside a directory in which i do not want the files to be directly accessed it works and fires the default 403 page access forbidden of the apache server how can i create a custom 403 page thanks,['php'] +232480,alternative for ms research chess is there any alternative for ms research chess library for unit testing net multithreading applications,['.net'] +232519,what do i need to know to port cyanogenmod to unsupported phonestablets what do i need to know to port cyanogenmod to currently unsupported android phones and tabletsdoes it involve modifying and building the kernel from sourcedoes it involve modifying and building cyanogenmod from sourcewhere can i get the base cyanogenmod which is the starting point for ports to specific devicesi saw somewhere that i need to know cc would i also need to know assembly or javado people write the device drivers for the new hardware from scratch how do they know how to talk to the new hardwaredo you use adb over usb and run linux commands like dmesg to get hints about what went wrong in initial builds do you use anything else to get hints about what went wrong i would like an overview of what is involved in porting cyanogenmod to different hardware so that i can know what to learn where to start and where to go from there,['android'] +232521,custom classes and formatting on flash messages for twitter bootstrap defaults i am integrating twitter bootstrap css into my application going along just finebut i do not know how to customize the css and wrappers for my flash messagesi would like my flash messages to be formatted with the default bootstrap classes div classalertmessage error a classclose hrefaa pstrongoh snapstrong change this and that and a hreftry againap divcurrently i output my flash messages with flasheach do name msg content tag div msg id flash name end is there an easy way to run a little switch that would make notification or other rails flash messages map to the classes in bootcamp like info,['ruby-on-rails'] +232524,datagridview setting row height in code and thisable manual resize in my grid i had following line of code which thisabled users manual resizingdgvtruckavailautosizerowsmode datagridviewautosizerowsmodeallcellsnow i needed to set column height in code and it did not work see datagridview setting row height doesnt worki figured that it was this line of code that caused nonsizing issue however now i need to figure out how to size rows in codeandprevent user sizing rows themselvesany pointers,['c#'] +232528,how to stub out wardendevise with rspec in capybara test i want to stub out a logged in user with devisewarden using rspec mocks in a capybara test suite in my rails app this would save a ton of time and would mean that my test suite canwill be run regularlypreviously i was able to do this using authlogic by stubbing out my session model with some code like thisdef loginuser user session mock modelusersession user user usersessionstubfindand returnuser sessionendnow that i am using devise i no longer have access to a usersession object and since i am using capybara to test my code i do not have direct access to the request object to use devises built in sign in test helpermy question is how can i simulate a logged in user with capybara devise and spec mocks without requiring every scenario with a logged in user to first go to the sign up path fill in the form submit wait for response and then go to the desired page,"['ruby-on-rails', 'ruby']" +232545,can i use inapp purchase on ios pirated application to ask for the user to pay for it does inapp purchase works on an ios pirated applicationbeing a developer i was thinking about the potential following usecasesome internet user install my application by pirating iti let him play with itafter a while once he is convinced of the interest of the application i thisplay a popup this application is not free you have not purchased it please buy it now cancel purchaseif he accepts i thisplay an inapp purchase dialogif he does not i thisable the key feature of the applicationit seems slightly more effective than simply asking someone who just pirated an app to go buy it on the app store,['ios'] +232557,converting nested hash keys from camelcase to snake case in ruby i am trying to build an api wrapper gem and having issues with converting hash keys to a more rubyish format from the json the api returnsthe json contains multiple layers of nesting both hashes and arrays what i want to do is to recursively convert all keys to snake case for easier useheres what i have got so fardef convert hash keysvalue return value if not valueis aarray and not valueis ahash result valueinject do new key value newto snake casekeyto sto sym convert hash keysvalue new end resultendthe above calls this method to convert strings to snake casedef to snake casestring stringgsub gsubazazaz1 2 gsubazdaz1 2 tr downcaseendideally the result would be similar to the followinghash hashkey nestedhashkey key valueconvert hash keyshash hash key nested hash key key valuei am getting the recursion wrong and every version of this sort of solution i have tried either does not convert symbols beyond the first level or goes overboard and tries to convert the entire hash including valuestrying to solve all this in a helper class rather than modifying the actual hash and string functions if possiblethank you in advance,['ruby'] +232574,visually modifying a uitoolbar from xcode storyboard i am using xcode 4 and storyboarding an application i am creating however i cannot visually modify the uitoolbari am attempting to modify a uitoolbar that is inside of a uitableviewcontroller however i have to place the uitoolbar out of the correct hierarchy in order to be able to modify it visually i have tried placing it onto the view controller area but that does not make it show up at one point i was able to make it appear below as it is own object however i was not able to recreate thatonce i was able to get it to look like this,['ios'] +232597,how can i access sorcery in my rspec tests sorcery authentication gem sorcerys creator provides an example rails app with sorcery test helpers included in its testunit functional tests controller testrb testunit functional test examplerequire test helperclass userscontrollertest actioncontrollertestcase setup do user usersnoam end test should show user do login user get show id userto param assert response success endbut i cannot figure out how to get login user to work in my rspec controller specsgemssorcery075libsorcerytest helpersrailsrb7in login user undefined method auto login for nilnilclass nomethoderrorheres the relevant code in the sorcery gem regarding the above error helpersrailsrbmodule sorcery module testhelpers module rails logins a user and calls all callbacks def login useruser nil user user controllersendauto loginuser controllersendafter loginuserusersendusersorcery configusername attribute namesfirstsecret end def logout user controllersendlogout end end endendupdateas per sorcerys documentation testing in rails 3 i have indeed added include sorcerytesthelpersrails to my spec helperrbthe sorcery test helper login user acts on controller but i am getting the error because controller is nil in my controller spec heres my specspeccontrollersforums controller specrbrequire spec helperdescribe forumscontroller do render views describe get new do describe when guest do it should deny and redirect do get new responseshould redirect toroot path end end describe when admin do p controller nil user usercreateusername test password secret email login user where the error occurs it should resolve do get new responseshould render templatenew end end endend,['ruby'] +232603,could not load file or assembly invalid pointer exception from hresult 0x804003 e pointer i have rebuilt my solution and got the following compilation errorerror 9 could not load file or assembly componentartwebui version20091181935 cultureneutral publickeytoken9bc9f846553156bb or one of its dependencies invalid pointer exception from hresult 0x804003 e pointer dmyprojaccountlcthe dll is in infra folder and is moved finaly to the bin folder of the output project websiteany productive ideas what else should i check it seems all other projects in this sln compilesunless i get this error to soon btw whats lc under project column,"['c#', 'asp.net']" +232627,can the type of a base class be obtained from a template type automatically i am trying to use template metaprogramming to determine the base class is there a way to get the base class automatically without explicitly specializing for each derived classclass foo public char name return foo class bar public foo public char name return bar template typename t struct classinfo typedef t base template struct classinfobar typedef foo base int main classinfofoobase a classinfobarbase b stdcout aname foo stdcout bname foofor right now any automatic method would need to select the first declared base and would fail for private bases,['c++'] +232683,get the complete month name in english i use datetimenowtostringm in order to get the current months full name it works well but i get it in hebrew is there an option to control the output language i need it to be english,"['c#', 'asp.net']" +232689,how to get the key value in json object how to get the key valu in json object and length of the object using javascriptfor example amount 12185 job gapa month january year 2010 amount 147421 job gapa month may year 2010 amount 2347 job gapa month august year 2010 here length of this array is 3 for getting value is fine 0amount in index0 it has 3 name value pairso i need to get the name like amount or job totally four name and also to count how many names are there,['javascript'] +232693,reset all select dropdowns i have have a function that gets called by onbeforeunload within i wish to reset all the dropdowns but i cannot find the right method to reset them back to the 0 valuehead script typetextjavascript function thisplaymessage documentgetelementsbytagnameselectvalue 1 or documentgetelementsbytagnameselectoptionslength 0 scriptheadbody form input typebutton valueclick me onclickthisplaymessage form select namedatarate1512num rooms idr15ro12 option value00optionoption value11 roomsoption option value22 roomsoptionoption value33 roomsoptionoption value44 roomsoption option value55 roomsoptionoption value66 roomsoptionoption value77 roomsoption option value88 roomsoptionoption value99 roomsoption select select namedatarate1512num rooms idr15ro12 option value00optionoption value11 roomsoption option value22 roomsoptionoption value33 roomsoptionoption value44 roomsoption option value55 roomsoptionoption value66 roomsoptionoption value77 roomsoption option value88 roomsoptionoption value99 roomsoption selectbodyhtml,"['javascript', 'jquery']" +232725,triggerinvoke a chrome extension from a web page for the project i am currently working on i need to know if it is possible to invoke a chrome extensionie clicking on a button or a link on my page would call the read it extension something like that,['javascript'] +232743,set default value on datetime field in symfony2 form i have a form containing several fields one of them is a datetime field how to define a default value for that field i have tried setting a value on the related entity in controller in constructor and construct myentity new myentitymyentitysetmydatenew datetimeform thiscreateformnew addmyentity myentitynot working tried to define the data variable in the buildform builderaddmydate date array format intldateformattershort input datetime widget single text data new datetimenownot working either any ideas symfony2 communityedit adding entity on demand of faost ormcolumnnamemydate typedatetime assertnotblank private mydate,['php'] +232748,executing code before main in objectoriented languages c you can execute code before main by using a global object or a class static object and have their constructors run the code you wantis there any way to do this in c i do not have any specific problem i am trying to solve i am just curious one thing this might be useful for is automatically initializing a library,['c'] +232750,why result of unsigned char unsigned char is not unsigned char i am getting results from left shift to which i could not find an explanationunsigned char value 0xff 1 1unsigned char 0x01 0 01stdcout sizeof value sizeofvalue n prints 1 as expectedstdcout sizeof shift sizeofshift n prints 1 as expectedstdcout result value shift n prints 510 stdcout sizeof result sizeofvalue shift n prints 4 i was expecting result to be 1 10 but instead i get int with value of 1 1 10how can the bits of an unsigned char be shifted to the left so that bits are truncated and the result is 1 10what i am trying to do is to read series of bytes and interpret them as integers of varying lengths 132 bitsf0 f51 0 1 0101 could be0f first 4 bits0f next 8 bits05 last 4 bitshas this something to do with the fact that arithmetic is not done with types smaller than int,['c++'] +232752,how to get eclipse cdt debugger to show contents of unicode strings i have a c project that uses icu unicode strings heavily recently i started using the eclipse cdt ide but i cannot watch the contents of the strings while debugging the only options are printing them to logs or casting them to stdstringdoes anyone know of a way to get eclipse to show the contents of icu strings in the expression viewupdate it seems this is a known issue with eclipse gdb does not parse the contents of unicode strings it is possible to add macrosfunctions to enable gdb to parse them but how can i make eclipse use them in the expressions window while debugging,['c++'] +232754,appending items to a list of lists in python i am getting mad with list indexes and cannot explain what i am doing wrongi have this piece of code in which i want to create a list of lists each one containing values of the same circuit parameter voltage current etc that i am reading from a csv file that looks like thissample v1 i1 v2 i20 3 001 3 0021 3 001 3 003and so on what i want is to create a list that for example contains v1 and i1 but i want to chose interactively in the form v1 i1 so33 001 001the code that i am using is thisplot data lenpositions for row in reader for place in rangelenpositions value floatrowpositionsplace plot dataplaceappendvalueplot data is the list that contains all the values while positions is a list with the indexes of the columns that i want to copy from the csv file the problem is that if i try the commands in the shell seems to work but if i run the script instead of appending each value to the proper sublist it appends all values to all lists so i obtain 2 or more identical lists,['python'] +232756,android save image to sd card updateadded usespermission androidnameandroidpermissionwrite external storage to the manifest all works ok nowok so i have a app i have started to create which in the end i want to be able to take a picture which then takes you to another screen which lets you be able to use or retake the picturewhen the image is took it needs to be saved into a new folder on the sd card if the folder is not there then it needs to create it i had all this working a couple of weeks ago but after i did some editing and shut down eclipse i cant seem to get it back workingthe section for this is after int imagenum 0 i have added imagesfoldermkdirs which i belive is correct to create a new folder but even this seems not to be working nownow the image just gets took and neither the new folder gets created or the image gets savedpublic class androidcamera extends activity implements surfaceholdercallback camera camerasurfaceview surfaceviewsurfaceholder surfaceholderboolean previewing falselayoutinflater controlinflater nullfinal int result saveimage 0 called when the activity is first created overridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain setrequestedorientationactivityinfoscreen orientation portrait getwindowsetformatpixelformatunknown surfaceview surfaceview findviewbyidridcamerapreview surfaceholder surfaceviewgetholder surfaceholderaddcallbackthis surfaceholdersettypesurfaceholdersurface type push buffers controlinflater layoutinflaterfromgetbasecontext view viewcontrol controlinflaterinflaterlayoutcontrol null layoutparams layoutparamscontrol new layoutparams layoutparamsfill parent layoutparamsfill parent thisaddcontentviewviewcontrol layoutparamscontrol button buttontakepicture button findviewbyidridtakepicture buttontakepicturesetonclicklistenernew buttononclicklistener public void onclickview arg0 todo autogenerated method stub cameratakepicturemyshuttercallback mypicturecallback raw mypicturecallback jpg shuttercallback myshuttercallback new shuttercallback public void onshutter todo autogenerated method stub picturecallback mypicturecallback raw new picturecallback public void onpicturetakenbyte arg0 camera arg1 todo autogenerated method stub picturecallback mypicturecallback jpg new picturecallback public void onpicturetakenbyte arg0 camera arg1 todo autogenerated method stub bitmap bitmappicture bitmapfactorydecodebytearrayarg0 0 arg0length int imagenum 0 intent imageintent new intentandroidprovidermediastoreaction image capture file imagesfolder new fileenvironmentgetexternalstoragedirectory beatemup imagesfoldermkdirs string filename image stringvalueofimagenum jpg file output new fileimagesfolder filename while outputexists imagenum filename image stringvalueofimagenum jpg output new fileimagesfolder filename uri urisavedimage urifromfileoutput imageintentputextramediastoreextra output urisavedimage outputstream imagefileos try imagefileos getcontentresolveropenoutputstreamurisavedimage imagefileoswritearg0 imagefileosflush imagefileosclose toastmaketextandroidcamerathis image saved toastlength longshow catch filenotfoundexception e todo autogenerated catch block eprintstacktrace catch ioexception e todo autogenerated catch block eprintstacktrace camerastartpreview public void surfacechangedsurfaceholder holder int format int width int height todo autogenerated method stub if previewing camerastoppreview previewing false if camera null try camerasetpreviewthisplaysurfaceholder camerastartpreview previewing true catch ioexception e todo autogenerated catch block eprintstacktrace public void surfacecreatedsurfaceholder holder todo autogenerated method stub camera cameraopen try cameraparameters parameters cameragetparameters if thisgetresourcesgetconfigurationorientation configurationorientation landscape this is an undocumented although widely known feature parameterssetorientation portrait for android 22 and above camerasetthisplayorientation90 uncomment for android 20 and above parameterssetrotation90 else this is an undocumented although widely known feature parameterssetorientation landscape for android 22 and above camerasetthisplayorientation0 uncomment for android 20 and above parameterssetrotation0 camerasetparametersparameters camerasetpreviewthisplayholder catch ioexception exception camerarelease camerastartpreviewpublic void surfacedestroyedsurfaceholder holder todo autogenerated method stub camerastoppreview camerarelease camera null previewing false,['android'] +232765,infinite for loop in python i am new to python actually i implemented something using java as shown below for switchexpression case c1 statements case c2 statements default statement how do i implement this in python,"['java', 'python']" +232771,queryselector wildcard element match is there a way to do a wildcard element name match using queryselector or queryselectorall i see support for wildcards in attribute queries but not for the elements themselfsthe xml document i am trying to parse is basically a flat list of properties and i need to find elements that have certain strings in their namesi realize the xml document is probably in need of a restructuring if i need this but that is just not goign to happenany solution except going back to using apparently deprecated xpath support ie9 dropped it,['javascript'] +232776,is not const redundant when passing by value i was reading my c book deitel when i came across a function to calculate the volume of a cube the code is the followingdouble cube const double side return side side sidethe explanation for using the const qualifier was this one the const qualified should be used to enforce the principle of least privilege telling the compiler that the function does not modify variable sidemy question is not the use of const redundantunnecessary here since the variable is being passed by value so the function cannot modify it anyway,['c++'] +232781,python variables naming convention so i am trying to switch to pep8 notation from a rather personal camelcase notation and i was wondering how you guys are tackling the cases where existing functionsvariables would be overwritteneg having something likeopen high low close sum rowwould already overwrite the open and sum functions first if i wouldnt use a good ide i wouldnt even notice that i have just overwritten important basic functions second how would you name the variables insteadin this example i would have used apps hungarian and wouldnt have encountered any potential problem at allthanks,['python'] +232786,polymorphism fundamentals i am studying inheritance and polymorphism now and i have came across the concept that the compiler will evaluate using reflection what type of object is stored in a basetype reference in order to decide what method to run upon calling a method with an overrideso for exampleclass shape public virtual void draw consolewritelinedrawing shape class circle shape public override void draw consolewritelinedrawing circle static void main shape theshape new circle theshapedrawthe following will be outputdrawing circleit is always been my understanding that on declaring any type of object it is a way of sort of designating memory for that specific type of object so int32 i 2l would mean that i have now put memory aside as a sort of placeholder for an integer but in the code above i have put memory aside for a shape but it can infact referencestore an object of type circle,['c#'] +232799,enabling browsers form autofilling i am making a signup form for my website it contains various standard form fields such as name address phone number user name password etcwhen i doubleclick on a field in chrome 16 so i can autofill my address i get this messagethis webpage has thisabled automatic filling for this formi did not thisable it so how do i enable it i tried adding autocompleteon to the form tag and to some of the input tags and that did not helpdo i need to add autocompleteon to every field also how does the browser know what field is what do i need to name the fields something specialanother question is there some kind of onautocomplete event that gets triggered when a form is autofilled on my form when you enter a zip code it looks in our database via ajax and then gets the state and city city and state are dropdowns because zip codes can be for more than one city and fills them in for you i was hoping i could have that run after the form was autofilledps i am using the jquery form validation plugin if that matters,['html'] +232808,check if any column is not null i need to check whether a column is not null in my sql statement my sql queryselect column a column b column c column d column xfrom mytablei have a lot of columns in my select so i have got a performance issue if i would do the followingselect column a column b column c column d column xfrom mytablewhere column a is not null or column b is not null or column c is not null or column x is not nullis there another better way to check if there are any columns that are not null,['sql'] +232816,implementing interfaces in c i usually program in c but am trying to do a bit of c and am struggling somewhat trying to implement interfaces in cin c i would do something like thisclass baset public void dosomethingt value do something here interface idoubledosomething void dosomethingdouble valueclass foo basedouble idoubledosomethingin c i have implemented it like thistemplate class tclass basepublic virtual void dosomethingt value do something here class idoubledosomethingpublic virtual void dosomethingdouble value 0class foo public basedouble public idoubledosomethingthe problem is that i cannot instantiate foo because it is abstract does not implement dosomething i realise i can implement dosomething and just call the method on base but i was hoping there is a better way of doing this i have other classes which inherit from base with different data types and i have other classes which inherit from idoubledosomething which do not use baseany help appreciated,"['c#', 'c++']" +232823,what does mean in css i have been looking at the css files for many websites like facebook and youtubein almost all of them i see this code margin 0padding 0it is odd as removing that block in chrome web developer tools does not affect the layout of the pagewhat does this code mean and when is it used and why,['css'] +232827,javascript strings utf16 vs ucs2 i have read in some places that javascript strings are utf16 and in other places they are ucs2 i did some searching around to try to figure out the difference and found thisq what is the difference between ucs2 and utf16a ucs2 is obsolete terminology which refers to a unicode implementation up to unicode 11 before surrogate code points and utf16 were added to version 20 of the standard this term should now be avoideducs2 does not define a thistinct data format because utf16 and ucs2 are identical for purposes of data exchange both are 16bit and have exactly the same code unit representationsometimes in the past an implementation has been labeled ucs2 to indicate that it does not support supplementary characters and does not interpret pairs of surrogate code points as characters such an implementation would not handle processing of character properties code point boundaries collation etc for supplementary charactersvia bomhtmlutf1611so my question is is it because the javascript string objects methods and indexes act on 16bit data values instead of characters what make some people consider it ucs2 and if so would a javascript string object oriented around characters instead of 16bit data chunks be considered utf16 or is there something else i am missingedit as requested here are some sources saying javascript strings are ucs2edit for anyone who may come across this be sure to check out this link,['javascript'] +232828,python how to tell if file executed as import vs main script i am writing a python file mylibpyi would like mylibpy to do something based on sysargv if it is being executed as a script but if it is imported from some other script i do not want it to do thathow can i tell if my python file is being imported or it is a main scripti have seen how to do this before but i forgot,['python'] +232838,purpose of returning by const value what is the purpose of the const in thisconst object myfunc return myobjecti have just started reading effective c and item 3 advocates this and a google search picks up similar suggestions but also counterexamples i cannot see how using const here would ever be preferable assuming a return by value is desirable i do not see any reason to protect the returned value the example given for why this might be helpful is preventing unintended bool casts of the return value the actual problem then is that implicit bool casts should be prevented with the explicit keywordusing const here prevents using temporary objects without assignment so i could not perform arithmetic expressions with those objects it does not seem like there is ever a case that an unnamed const is usefulwhat is gained by using const here and when would it be preferableedit change arithmetic example to any function that modifies an object that you might want to perform before an assignment this is my first post and wow i cannot believe how fast people put together good answers with code examples and potholed links thanks,['c++'] +232843,ios push services is an invisible push notification possible i am building a iphone application which depends data from an online database to update the data in the app i could check at a certain time interval if an update is necessary but it is way cooler if i could use a push services which sends a notification to the app letting it know it is time for an update i am not talking visible push notifications here just a invisible push notification to fire the update method in my app is there a standard way to do this or could i use apples push notification services for this purpose with other words i am now using pull to get updates is there a push way to let the backend of my app know it is time for an updateedit and if it is impossible what would be good time interval for the update 003 kb if there are no updates is it to much to check it every 30 seconds,['ios'] +232853,questions about a readonly property in arc in my interface h file i havepropertyreadonly nsstring fooand in my implementation m file i havesynthesize foowith arc turned on the compiler gives me this error automatic reference counting issue arc forbids synthesizing a property of an objectivec object with unspecified ownership or storage attributethe error goes away if i add a strong weak or copy to the property why is this why would there be any differences between these things for a readonly property what are those differences and why does the programmer have to worry about them why canat the compiler intelligently deduce a default setting for a readonly propertyanother question while iam at it strong weak or copy are the only things that make sense in arc right i shouldnat be using retain and assign anymore should i,['objective-c'] +232884,iphone call another phone number in response to the first not answering i am attempting to create an application that will initiate a call to a priority 1 contact on a callcenterlike listthen if that contact does not answer let us forget the whole problem of answering machines here i would like to call the priority 2 contact and so on until one of them answers or i exhaust my listis this possiblei have tried the followinghook into the ctcallcentercalleventhandler event and checking the call state for ctcallstateconnected and ctcallstatethisconnected and i get it to respond to the fact that the call thisconnected without ever connecting and then attempt to initiate another call like i did the first but this second attempt just sits dead in the wateroverride the didenterbackground method and periodically check the ctcallcallstate property basically again trying to respond to a thisconnect that was never connected but this does not appear to work eitheri also tried adding a short delay 1 second 25 seconds and 10 seconds after detecting the thisconnected state before attempting the next dial to allow for the phone application to settle down after aborting the call this did not change anything,"['iphone', 'ios']" +232889,rails 3 simple format do not wrap result in paragraph tags how can i make simple format not wrap the returned value in p tagssimple format span classrequiredspan,"['ruby-on-rails', 'ruby']" +232890,when is the concurrentmodificationexception thrown in gae i am reading the official gae documentation on transactions and i cannot understand when a concurrentmodificationexception is thrownlook at one of the examples which i am copypasting hereint retries 3while true transaction txn datastorebegintransaction try key boardkey keyfactorycreatekeymessageboard boardname entity messageboard datastoregetboardkey long count long messageboardgetpropertycount count messageboardsetpropertycount count datastoreputmessageboard txncommit break catch concurrentmodificationexception e if retries 0 throw e allow retry to occur retries finally if txnisactive txnrollback now all the writes to the datastore in this example are wrapped under a transaction so why would a concurrentmodificationexception be throwndoes it happen when some other code which is not wrapped in a transaction updates the same entity that is being modified by the above code if i ensure that all code that updates an entity is always wrapped in a transaction is it guaranteed that i would not get a concurrentmodificationexception,['java'] +232902,c linq where clause as a variable i am trying to make a linq statement where the where clause comes from a variable for examplestring whereclause addresszip 23456var x from something in somelist where whereclauseis this possible i cannot seem to get it to work thanksupdate my where clause is predefined and will be based on user input so i do not think this will work for me basically whereclause is not constructed in the method it is a parameter of the method which does the linq i did not explain that well here is a better examplepublic void dolnqstring whereclause var x from something in somelist where whereclause doworkxupdate just to sum up some of the suggestions and centralize everything i cannot use a switch to generate the where clause because there are way to many possibilities the dynamic linq post that a few of you have posted does look promising but i am having trouble related the linq to sql example to my linq to objects problem and slaks after looking through msdn i am having trouble figuring out where you meant to use asqueryablethanks,['c#'] +232924,how to process long running requests with an http handler under iis i need to process long running requests inside iis handling the request itself is very lightweight but takes a lot of time mostly due to io basically i need to query another server which sometimes queries a third server so i want to process as many requests as i can simultaneously for that i need to process the requests asynchronously how do i do that correctlyusing the socket class i could easily write something like listening code accepting codevoid calledonreciverequest request process the request a little context context new context contextsocket requestsocket remoteserverbegin longrunningdemonicmethodrequestsomeparameter donecallback contextvoid donecallback iasyncresult result remoteserverbegin callsomeverylongrunningdemonicmethod requestsomeparameter donecallback context socket socket resultcontextsocket socketsendresultresultin the example above the thread is released as soon as i call the begin method and the response is sent on another thread so you can easily achieve very high concurrency how do you do the same in an http handler inside iis,"['c#', 'asp.net', '.net']" +232928,python utf8 xml parsing suds removing invalid token heres a common error when dealing with utf8 invalid tokens in my example it comes from dealing with a soap service provider that had no respect for unicode characters simply truncating values to 100 bytes and neglecting that the 100th byte may be in the middle of a multibyte character for examplename xsitypexsdstringaaoa14aoaaooeea ae eea14ecaecaa34aeexefxbcnamethe last two bytes are what remains of a 3 byte unicode character after the truncation knife assumed that the world uses 1byte characters next stop sax parser andxmlsax exceptionssaxparseexception unknown12392 not wellformed invalid tokeni do not care about this character anymore it should be removed from the document and allow the sax parser to function the xml reply is valid in every other respect except for these valuesquestion how do you remove this character without parsing the entire document and reinventing utf8 encoding to check every byteusing pythonsuds,['python'] +232952,why is stringlength a method if a string object is immutable and thus obviously cannot change its length why is length a method as opposed to simply being public final int length such as there is in an arrayis it simply a getter method or does it make some sort of calculationjust trying to see the logic behind this,['java'] +232984,uimodaltransitionstylepartialcurl causing uibutton text to animate i have got a uiview that gets used in a modal view using the uimodaltransitionstylepartialcurl transition style when it appears this uiview includes a uibutton the odd thing is that whenever the view appears as the primary page peels up to the top of the window the button on the modal view animates itself with the text seeming to get typed onto the button from the center of itself the movement of this animation is a bit thistractingwhy does this happen is there any way to prevent itthe uibutton does use a custom background but it is defined in the xib for the modal view and does not use any special subclass of my own it is a standard button,['ios'] +233016,is the java native interface jni affected by c abi compatibility issues is the java native interface jni affected by c abi compatibility issuesi am developing a java application i would like to use the java native interface jni to call functions in a c library i have access to the code for the c library and i can rebuild it however i may need to for example i can statically link the c runtimei can require my users to have jre 6 or greater but i cannot require them to have any particular c runtimea coworker pointed me to this blog article which advises against using dynamically loaded c codeanother coworker pointed me to this bug report bugdobug id4694590 which details how these issues were addressed back in java 142the gist of the problem as i understand it is that the binary interface of libstdc often changes if a c application loads a c shared library that was built with a different compiler two incompatible libstdc libraries will be loaded into memory at the same timethe bug report explains the solution for java 142 we statically link the c runtime in jdk and enabled linker script to hide symbols from libstdc and other internal symbols as the result those symbols become invisible to jni code and when some native code needs to call into c runtime the call will be resolved with the appropriate libstdcso there are still two libstdcso being loaded at the same time but it should be benigni have a few questions about thisfirst does openjdk continue to take this approachedit i asked this question on openjdks builddev mailing list the answer is yes hotspot still statically links libstdc but apparently most linux thistros patch this out another developer notes that this does not even require a patch settingstatic cxxfalse should be enough it defaults to truesecond even in this case is it truly benign to have two incompatible libstdcso loaded at the same timethird does this approach to hide the symbols in the jdk address all of the compatibility issuesthe blog article referenced above warns that code compiled against different abis is simply not binary compatible and later that the language runtime support typically rely on some data being shared eg to access some kind of lock or global data structure similar to how c programs need a shared errnothis makes it sound like the problem cannot be solvedthen again maybe abi incompatibility is not a problem anymore the blog article is over six years old one answer for another stackoverflow question gcc abi compatibility asserts that since gcc340 the abi is forward compatible has that been successfuli would appreciate any guidance on these issues and hey thanks for reading all of thiseditsmy question was getting pretty long so i did not give all the specifics to address wills commentsi only need to call extern c functions for example i use javah to generate the c header filei do not need to interact with the c runtime in the jvm i basically just need to send strings to a c library,"['java', 'c++']" +233037,how to print something without a new line in ruby puts statement in ruby automatically adds a new line how do i avoid it,['ruby'] +233056,embedded software maintainability configuation i am developing a embedded software that is meant to run on two to three different family of micro controllers for now we have makefiles that reads the configuration switches and does compilationthe process is getting more and more tedious for both developers and non developers to stay updated with compile switches and build configurations i know linux kernel uses ncurses for generating compile configurations i am looking for a similar tool but cross platform it should run on windows and linux i know this will still not solve the problem but its more appealing to non developers also i can quickly share my config file or compare it with existing the configurations will be in specific order and a diff tool here will helpcan anyone share their experience with similar project maintenance or a reference project embedded and common code base for multiple micros just want to know best practicesps language used c 816 bit micros no os just timer based batch scheduler baremetal,['c'] +233063,convert string to variable name i have an xml file i have a node and i read all childnodes the name of the childnode match to a variable i have to set with the value of this childnodein the loop i would like set myvar1 to myvalue1myvar2 to myvalue2the c code protected string myvar1protected string myvar2the xml content look like this parameters myvar1myvalue1myvar1 myvar2myvalue2myvar2parametersc set variables foreach var item in xmlparaminstallationselectnodesparameters0childnodes any idea thanksupdate 1the value field in the loop is null all the timepublic class parameterstest public string myvar1 get set public string myvar2 get setvar type typeofparameterstestforeach xmlnode item in xmlparaminstallationselectnodesparameters0childnodes var field typegetfielditemlocalname fieldsetvaluefield iteminnertext,['c#'] +233084,php datetimediff results comparison i was trying to compare the difference between 2 dates but it seems the results are pretty wrong for example this codedatetime1 new datetime20091011datetime2 new datetime20091013interval datetime1diffdatetime2echo intervalformatra daysbr datetime1 new datetime20091011datetime2 new datetime20091015interval2 datetime1diffdatetime2echo interval2formatra daysbr ifinterval interval2 echo true elseecho false returns true but above you can see the date differences are not the same in fact echo prints 2 and 4 any idea in how to compare 2 date differencesedit the datetimediff returns a dateinterval object in fact it does not implement comparison operators i will use dateinterval vars to check the difference thanks for the answers,['php'] +233099,unkown error compiling opencv framework xcode is giving me the following error i do not really know what to do is driving my crazyi am importing an opencv framework so maybe the problem is there or something related to the compilercould anyone tell me what to do or search forthanks undefined symbols cgimagedestinationcreatewithurl referenced from cvimageioencoderwritecvmat const stdvectorint stdallocatorint constin opencvgrfmt imageioo cgimagedestinationaddimage referenced from cvimageioencoderwritecvmat const stdvectorint stdallocatorint constin opencvgrfmt imageioo cgimagesourcecreateimageatindex referenced from cvimageiodecoderreadheader in opencvgrfmt imageioo cgimagedestinationfinalize referenced from cvimageioencoderwritecvmat const stdvectorint stdallocatorint constin opencvgrfmt imageioo cgimagesourcecreatewithurl referenced from cvimageiodecoderreadheader in opencvgrfmt imageioo ld symbols not found collect2 ld returned 1 exit status,['c++'] +233130,how can i add an image file into json object i want to add an image file into json object is it possible to add image file into json objecti tried below code but its not working because i want to send that json object to the server then server will read my image file and store into that databasejsonobject test new jsonobjecttestputphotonew file here i set image uriso when i print this json object it only show me the image path where the image stored i want file for sending it to server,['android'] +233137,how to use less css with django i am using twitter bootstrap and django i have got my dependencies handled with a pip requirements filei have got 2 questionshow can i use less while i am developing so it will get compiled when i edit one of my less fileshow can i create some kind of build script that will compress and combine my js and generate css from less as part of a deploymenti have written a custom build script that creates a virtualenv runs pip install r requirementstxt django syncdb django migrate and then off we gowhats the easiest way of integrating less into thisthanks,['python'] +233144,how can i browse a picture from iphone picture library i am new in ios development i am doing a photo cropper app i want to browse an image from the iphone picture library by clicking browse button that i added in my app and load it to uiimageview that i placed in a viewhow can i browse the image is it possible to browse the complete phone memory just like aspfileuploadis there any control available in iphone to use just like aspfileupload thanks in advance,"['iphone', 'ios']" +233156,play audio file when receiving the call possible duplicateplay an audio clip onto an ongoing call suppose we have recorded file in our mobilewhen we call to any personas soon as he picked up the call he should listen recorded voice filewhich we have recordedi have gone through the below mentioned links still the problem persists how to play audio file when call startsi tried but i did not get he solution now what i have to do,['android'] +233168,how to operate on postgresql interval datatype using jdbcspringjdbc not using pginterval java date time datatypes are as everybody knows there is no need to focus on thathowever when i am using jdbc or springbased extensions such as simplejdbctemplate to retrieve and store interval values what java type should i use if i do not want to use orgpostgresqlutilpginterval class this class is internal of postgresql driver so using it would make the code dbspecific i think it should be possible to operate on intervals in dbagnostic way because it is one of standard sql types,['java'] +233174,ie8 only object does not support property or method widget i am getting an error related to jcoverflip1 that only occurs in ie8 the following error occurs script438 object does not support property or method widget jqueryjcoverflipjs line 508 character 1which relates to the following codewidget uijcoverflip i have jquery and jqueryui both included before the script plus the script runs fine in all other browserswhats causing the issue,"['javascript', 'jquery']" +233192,why does not c code return a struct while it is very handy i very rarely if ever come across functions that return structs or unions in c whether they are dynamically linked functions or statically defined functionsthey instead return the data through a pointer parameteran dynamic example in windows is getsysteminfowhats the reason behind thisis it because of a performance issue an abi compatibility issue or something else,['c'] +233197,create a color picker similar to photoshops using javascript and html canvas i am not at all versed in computer graphics and am in need of creating a color picker as a javascript tool to embed in an html pagefirst and looking at photoshops one i thought of the rgb palette as a threedimensional matrix my first attempt envolvedscript typetextjavascript var rgcanvas documentcreateelementcanvas rgcanvaswidth 256 rgcanvasheight 256 rgcanvasstyleborder 3px solid black for g 0 g 256 g for r 0 r 256 r var context rgcanvasgetcontext2d contextbeginpath contextmovetorg contextstrokestyle rgb r g 0 contextlinetor1g1 contextstroke contextclosepath var bcanvas documentcreateelementcanvas bcanvaswidth 20 bcanvasheight 256 bcanvasstyleborder 3px solid black for b 0 b 256 b var context bcanvasgetcontext2d contextbeginpath contextmoveto0b contextstrokestyle rgb 0 0 b contextlineto20 b contextstroke contextclosepath documentbodyappendchildrgcanvas documentbodyappendchildbcanvas scriptthis results in something likemy thought is this is too linear comparing to the ones i see in photoshop and on the webi would like to know the logic behind the color mapping in a picker like thisi do not really need the algorythms itself i am mainly trying to understand the logicthanks,['javascript'] +233204,fragmentactivity lifecycles and orientation change fragments are funny things but so i thought once you know their quirks they are an invaluable tool for writing good code across multiple deviceshowever while fixing an orientation change bug i have run up against a wall for my fragment to work it needs access to a view which belongs to it is containing activity leading me on a merry chase trying to find how the activity fragment lifecycles interacti am adding a fragment to my activities view in it is oncreate method only add a fragment once as after it is been added it cannot be replaced even though there is a replace method which is a massive gaping hole in fragments as a technology if you ask meifsavedinstancestate null mainmenufragment menu new mainmenufragment fragmenttransaction transaction getsupportfragmentmanagerbegintransaction transactionreplaceridmenuframe menu transactioncommitleading to this activityfragment lifecycle0104 151727226 wsinglepaneactivity 0 oncreate0104 151727378 wmainmenufragment 0 onattach to singlepaneactivity 00104 151727378 wmainmenufragment 0 oncreate0104 151727453 wmainmenufragment 0 onactivitycreated0104 151727476 wmainmenufragment 0 onstart0104 151727476 wsinglepaneactivity 0 onstart0104 151727476 wsinglepaneactivity 0 onresume0104 151727476 wmainmenufragment 0 onresumean orientation change however highlights that this is not usually the case a fragments oncreate method is not called after it is parent activities oncreate infact the first lifecycle call of a fragments onattach occurs before the activity has even been created null is passed as an argument0104 151049589 wmainmenufragment 0 onpause0104 151049589 wsinglepaneactivity 0 onpause0104 151049589 wmainmenufragment 0 onstop0104 151049589 wsinglepaneactivity 0 onstop0104 151049589 wmainmenufragment 0 ondestroyview0104 151049589 wmainmenufragment 0 ondestroy0104 151049589 wmainmenufragment 0 ondetach0104 151049609 wsinglepaneactivity 0 ondestroy0104 151049617 wmainmenufragment 1 onattach to null0104 151049617 wmainmenufragment 1 oncreate0104 151049617 wsinglepaneactivity 1 oncreate0104 151049890 wmainmenufragment 1 onactivitycreated0104 151049917 wmainmenufragment 1 onstart0104 151049917 wsinglepaneactivity 1 onstart0104 151049921 wsinglepaneactivity 1 onresume0104 151049921 wmainmenufragment 1 onresumei have absolutely no idea why this is occuring could anyone shed any light on why fragmentonattach is being called before it is containing activity has been createdfragments i have got which do not need access to their containing activity until ui interaction work as expected,['android'] +233207,how can i stop firefox from caching the contents of a textarea on localhost i am working on a site locally which has a lot of textarea elements however everytime i reload the site the content in the textarea is still there this only happens when i hit reload f5what can i do to stop the site from being cached without using any inbrowser functionsi am looking for a solution within the site so when other users in my office opens it they would not have the same problem,"['javascript', 'html']" +233209,php get key name of array value i have an array as the followingfunction example some stuff here that pushes items with dynamically created key strings into an array return array now lets pretend it returns the created array firststringname whatever secondstringname somethingelse arr example now i know that arr contains arrfirststringnamei need to find out the index of arrfirststringname so that i am able to loop through array keysarr and return the key string firststringname by its index how can i do that,['php'] +233218,is hosting a ruby application on windows server a viable setup i am starting a new web app project with the only real technology requirement being a host running windows server i considered both aspnet mvc and ruby on rails i would like to learn ruby so i am wondering of hosting it on a windows platform is doable or if it will cause me more grief than it is worth railsinstaller made dev environment setup a snap but i am more worried about the production deploymentthe proposed setup is a ruby on rails application running on windows server 2003 iis driven by a sql server database i know that will make many open source people cringe but i am wondering how viable this is from a strictly practical standpoint or if this is just a bad idea what might be a better way to go also any other practical advice on technology choices for ruby on windows or deployment ideas would be helpful best deployment package should i be using jruby etcthanks,"['ruby-on-rails', 'ruby']" +233229,when should we consider using private or protected just wondering when should we actually must use private or protected for some methods in the modelsometimes i cannot not be bothered to group my methods in private nor protected i just leave it as it is but i know it must be a bad practice otherwise these 2 groupings would not be created in programmingthanks,"['ruby-on-rails', 'ruby']" +233244,java ee and desktop apps i am new to java and have just started with some simple codei am on a linux machine use the vim editor use javac for compilation and java for runningprogramsbasically for the time being i am looking for building a desktop application using java i have heard about java eeseme and my assumptions about them arecore java is the basic java languagewith all the rules about variables looping methods classes etcjava se is for desktop appsjava ee is for web apps using the http protocoljava me is for mobile appshowever i came to know that the difference among them is that specification from difference between java se java eeso my question is can i create desktop apps using java ee as well or are they only for creating web apps,['java'] +233275,maximum call stack size exceeded i am trying to call my function every 4 seconds so it will increment a number live for some reason i keep getting errors heres my codehtmlheadtitlerecycle countertitlescript typetextjavascript function randfrom to return mathfloormathrandom to from 1 from generates random number var num rand10 10 function getnum gets triggered by page load so innerhtml works documentgetelementbyidcounterinnerhtml num 7 settimeoutgetnum 40 scriptheadbody onloadgetnum div idcounter divbodyhtml,"['javascript', 'html']" +233302,enum within an enum this is not a matter of me being stuck but rather i am looking for a tidy way to write my codeessentially i am writing an event driven application the user triggers an event the event gets sent to the appropriate objects and the objects handle the events now i am working on writing the even handler methods and i was hoping to use switch statements to determine how to handle the event right now whilst i am working on the general structure the event class is really simplepublic class event public static enum action move foo bar private action action private int duration public eventaction action int duration thisaction action thisduration duration public action getaction return action public int getduration return duration then in another class i will have something likepublic void handleeventevent evt switcheventgetaction case move dosomething break case foo dosomething break case bar dosomething break default break what i would like to do is something like this though i would of course stick the switch statements into their own functions to avoid it turning into a nasty hairball of switches and casespublic void handleeventevent evt switcheventgetaction case move switcheventgetaction case up break case down break case left break case right break case foo break case bar break default break so i would want to create nested enums like sopublic static enum action public enum move up down left right foo barit is not like i cannot avoid the scenario it would just be convenient so whilst the above does not actually work is there some similar method to achieve this it would be nice if i could send an event with the action moveup and the method would identify it first as an action of type move and then further identify that it is specifically in the up direction that is just a simple example it would be grat if i could also make longer chains something like deletepage1paragraph2sentence2word11letter3 the way i see it i am just going to have to use strings and lots of ifelse statements hoping there is a better way oh and performance matters in my case if that helps,['java'] +233322,why cannot i play sounds more than once using html5 audio tag this is how the sound is storedaudio id hammer srcressoundsbuildinghammerwavaudioin the actual game which i use sounds for i use this to play the sound function playsoundsoundid documentgetelementbyidsoundidcurrenttime 0 documentgetelementbyidsoundidplay but the sound plays only the first time and never againi tried resetting the currenttime in the console to 0 but i literally get thisdocumentgetelementbyidhammercurrenttime 00documentgetelementbyidhammercurrenttime0340why is this happening how do i fix it,['javascript'] +233328,test if xsendfile header is working i am looking for a way to confirm if xsendfile is properly handling requests handed back to the webserver by a script php images are being served correctly but i thought i would see the header in curl requests curl i http11 200 okdate wed 04 jan 2012 171945 gmtserver cherokee12100 arch linuxetag 4dd2e3069da0lastmodified tue 17 may 2011 210510 gmtcontenttype imagejpegcontentlength 40352xpoweredby php538contentthisposition inline filenameamosleefeaturejpgconfigurationcherokee 12100 with phpfpm 538 in fastcgicherokeeconf vserver20rule500handlerxsendfile 1set by vserver behavior extensions php handler allow xsendfile check enabledwordpress network wpmu 331definewpmu sendfiletrue is set in the wpconfigphp the following just before wpsettingsphp is included this will trigger the following code to be executed in wps wpincludesmsfilesphp50 serves up files for a particular blogheader xsendfile file exiti have confirmed that the above snippet is executing by adding an additional header for thisposition right before the exit call that contentthisposition is present with curl results above and not originally in the msfilesphp code the code that was added isheadercontentthisposition inline filenamebasenamefileresearchi haverebooted phpfpm cherokee daemons after making configuration changestried several tricks in the comments over at phpnetreadfile and replaced the simple header in msfilesphp with more complete code from examplesphpnetmanualenfunctionreadfilephpwjasnynetarticleshowiphpxsendfilecodeutopianetblog20090306sendingfilesbetterapachemod xsendfileandphpconfirmed cherokee support5 and tested with and without6 compression even though i do not think it would apply since my images are serving correctly i also found a suspiciously similar problem from a lighttpd postcherokeeprojectcomdocother goodieshtmlcodegooglecompcherokeeissuesdetailid1228webdevrefinerycomforumstopic4761xsendfilefound a blurb here on so that may indicate the header gets strippedstackoverflowcomquestions7296642djangounderstandingxsendfiletested that the headers above are consistent from curl wget firefox chrome and websniffernetfound out that i cannot post more than 2 links yet due to lack of reputationquestionswill xsendfile be present in the headers when it is working correctly or is it stripped outcan the access logs be used to determine if xsendfile is workingi am looking for general troubleshooting tips or information here not necessarily specific to php cherokeeupdatei have found a suitable way to confirm xsendfile or xaccelredirect in a test or sandbox environment thisable xsendfile and check the headerswith allow xsendfile thisabled in cherokee curl i http11 200 okdate fri 06 jan 2012 153449 gmtserver cherokee12101 ubuntuxpoweredby php53613ubuntu33contenttype imagejpegxsendfile srvhttpwordpresswpcontentblogsdir2files201105amosleefeaturejpgcontentlength 40352the image will not load in browsers but you can see that the header is present after reenabling allow xsendfile the image loads and you can be confident that xsendfile is working,['php'] +233347,rails 31 paperclip s3 uninitialized constant awss3base i am getting the following error when trying to upload an image using paperclip and s3 storage the app worked fine uploading locally but when i have made the required changes to use s3 i get the followingnameerror in imagescontrollercreateuninitialized constant awss3basegemfilesource gem rails 313gem sqlite3group assets do gem sassrails 315 gem coffeerails 311 gem uglifier 103 gem dynamic formendgem awssdkgem paperclipmodelsimagerbclass image activerecordbase has attached file file styles featured 970x560 thumb 192x112 storage s3 s3 credentials railsrootconfigamazon s3ymlendconfigamazon s3ymlbucket myappdevaccess key id secret access key bundled gemsawssdk 125paperclip 245 rails 313,['ruby-on-rails'] +233350,android compass example i am searching for a compass example for android all i need to do is to get the correct bearing in portrait landscape modei already found several samples some use only sensortype orientation some use a combination of sensortype accelerometer sensortype magnetic fieldwhich is the correct common way to get the bearing for let us say android 16 40,['android'] +233351,math interface vs cmath in c the interface on my build system macos 1063 for the posix math library is mathh however on my target system the name of the interface file is cmathh at school we use cmath and i would like to be sure my project compiles when it is handed in how is this achieved the servers and workstations at school are x86 running windows xp the gcc is available on both platforms,['c++'] +233355,html5 structure and usage good dayi just started to learn html5 have no issues everythings going perfectlyi have only one small question about semantic usage of article section and div tagsi know that div element has no semantic meaning in html5 it should be used mainly for scriptingstyling purposes here everything is clear for me i found a lot of useful informations in so question html5 has new tags article section and aside when should i use div taghowever i have some issues with article and section usage w3c html5 specification says that article tagspecifies independent selfcontained content could be a newsarticle blog post forum post or other articles which can be thistributed independently from the rest of the site where section tag should be usedfor a section in a document such as chapters headers footers or any other sections of the documentin theory everythings clear however while preparing the code for my first html5 website i found it a bit hard to differlet me explain my website structure backgrounds are added to the body element working perfectlyi use 960gs grid system in my every htmlcss project this time i am using it too as you surely know it requires a container to be added with a class container 12 in my caseto conclude explanation of my structureas a main container i have used div classcontainer 12the first element in my document is a header it contains few elements slider and top bar the top bar is a section it has two child elements telephone number on the left and language list on the right for those elements i have used section too for a slider or a short slogan placeholder on inner pages i have used section tag which contains two section tags left and right columnas a main content wrapper for homepage i have decided to use section element for inner pages i am using article for pages like about us etc for blogs list i am using a section with a list of article tags inside for a single post i am using article elementobviously for a footer i am using footer element with three section elements as a column wrappersmy layout before convertion to html5div classcontainer 12 div classgrid 12 header div classbar grid 12 alpha omega div classgrid 6 alpha phone number div div classgrid 6 omega german english french div div div classgrid 6 alpha logotype div div classgrid 6 omega ul navigation ul div div classgrid 12 alpha omega div classgrid 6 alpha slider i col div div classgrid 6 omega slider ii col div div div div classgrid 12 content div div classgrid 12 footer div classgrid 4 alpha footer i col div div classgrid 4 footer ii col div div classgrid 4 omega footer i col div divdivheres my code after converting it to html5div classcontainer 12 header classgrid 12 section classbar grid 12 alpha omega section classgrid 6 alpha phone number section section classgrid 6 omega german english french section section section classgrid 6 alpha logotype section nav classgrid 6 omega ul navigation ul nav section classgrid 12 alpha omega section classgrid 6 alpha slider i col section section classgrid 6 omega slider ii col section section header section classgrid 12 content section footer classgrid 12 section classgrid 4 alpha footer i col section section classgrid 4 footer ii col section section classgrid 4 omega footer i col section footerdivis my approach correct could you add or correct somethingto avoid any questions i know that section is not a replacement for a div,['html'] +233360,how to identify invalid corrupted values stored in oracle date columns oracle 10205what is the easiest way to identify rows in a table that have invalid values in date columns by invalid here what i mean is a binary representation that violates oracle rules for date valuesi recently had an issue with an invalid date stored in a columni was able to use a query predicate to find a particular problematic row where to chardate exprymmddhh24miss 0in the case i had the century byte was invalid select dumphbid close date from mytable h where hid 54321 typ12 len7 220121the century byte should be 100 two digit century in this case there was an extra 100 added as if the century value was 120 making the year 12011 the only way i know to get invalid date values into the database is using oci using native 7byte date representationin this case the to char function returned an identifiable string which i could use for identifying the wonky date valuemy question is there an more general or easier approach preferably using a sql select statement to identify rows with invalid values in date columns,['sql'] +233363,getting image from byte array in json object to android app heres my situationi have a restful wcf service running on my server the service is meant to get various types of data about people from a database and makes that data available as a single json object it works greateditthere is another service that maintains an image cache in the file system on the server when a request is sent to the restful service that service then requests an image from the image service if the image is already in the cache same width height and person as the request it returns that as a byte array we must use this service to retrieve imagesnow what i want is the image of that person in our database the image is a long raw ew however i have dealt with that issue already previous paragraph the image is now a byte array i am pretty new to android and i am not sure what the best way to retrieve this image is what i thought i could do was add the byte array to the json object and then use the base64 decoder to convert it into a drawable image however everytime i try it times out and tells me it expected or at some arbitrary index of the char buffer for the json objecti have been able to pull the small bits of data out of the json object without an issue but now that there is a huge byte array in it the jsonobject hates me what would be a better way to get this image from my service,['android'] +233365,how to manually invoke an event i have the following line in c timerelapsedtick somefunction1 timerelapsedtick somefunction2 timerelapsedtick somefunction3how to invoke all methods subscribed to timerelapsedtick without specifying the somefunction somewhere along this pseudolineinvoke timerelapsedtickyour help is very much appreciatedupdateexample from mbabcock is working the fireevent method does the magic thank youclass invokefromme public event eventhandler raisemeclass mainclass public mainclass invokefromme fromme new invokefromme frommeraiseme fromme raiseme frommeraiseme fromme raiseme1 fireeventfromme raiseme null eventargsempty works systemtimerstimer timer new systemtimerstimer timerelapsed timer elapsed fireevent timer onintervalelapsed null null throws exception private void timer elapsedobject sender elapsedeventargs e consolewriteline timer elapsed raised private void fromme raisemeobject sender eventargs e consolewritelineevent handler 0 raised private void fromme raiseme1object sender eventargs e consolewritelineevent handler 1 raised public void fireeventobject onme string invokeme params object eventparams multicastdelegate eventdelagate multicastdelegateonmegettypegetfieldinvokeme systemreflectionbindingflagsinstance systemreflectionbindingflagsnonpublicgetvalueonme delegate delegates eventdelagategetinvocationlist foreach delegate dlg in delegates dlgmethodinvokedlgtarget eventparams class program static void mainstring args mainclass m new mainclass,['c#'] +233377,c reference wrapper for value type i want to use c point type as a reference type it is a struct i thought of having a class cpoint which would contain a point member is there any way to raise the members of the point to act as members of the cpoint i am trying to avoidcpointpointxcpointpointyi would like to docpointxcpointyas well as keep all the conversions operators empty etccan this easily be done,"['c#', '.net']" +233382,using nested ternary operators i have been trying to use isset in nested form like belowisset postselectedtemplate postselectedtemplateisset getselectedtemplate getselectedtemplate0but seems i am missing something can anyone assist me how to do it,['php'] +233398,spring async uncaught exception handler overrideasyncpublic void asyncexceptiontest int i10how can i log this using spring async framework without having to put try catch around every async method it doesnt seem to pass to the defaultuncaughtexceptionhandler like normal,['java'] +233494,android sdk manager is not showing arm eabi v7a system image option i am trying to setup environment to build application on android platform i have followed steps from and did install sdk and eclispe adt plugins while running hello world application i received an error sdk manager unable to find a userdataimg file for abi armeabi to copy into the avd folderto overcome this i tried installing arm eabi v7a system image using sysimg armv7a14 r01zip file surprisingly my android sdk manage does not show option of arm eabi v7a system image to reinstall this package did i miss any step,['android'] +233502,use of classpathxmlapplicationcontext in standalone java class i am not exposed to spring as yet i saw the below code in one of the standalone java projects that i have in my system can you please help me understand the below codei am unable to see springxml in the project is it something that must be there and is missing appcontext new classpathxmlapplicationcontextnew string classpathmetainfspringxml classpathmyapplicationapplicationcontextxml,['java'] +233542,whats the name property of swing components for whats the intended use of the name property of swing components is it used swing internallybackground a colleague implemented a internationalization mechanism by storing the key for the text string in the name property then he simply walks through all swingelements and gets the key stored in the name property of the component he argued that the name property does not seem to be used otherwise and that this was the easiest way to do it,['java'] +233543,html5 web sql transactions skipped without error when touch triggered in ios i am experiencing problems making database transactions on ios devicesif the user does not touch the phone everything works like expectedif the user tapsscrollstouches the screen some transactions directly call their successcallback without ever calling the actual transaction callbacksimplified example here to test just open in your mobile safari on ios and do not touch the device while loading you will see a list of debug messages being generated looking like thisdatabase is runningtable will be clearedstore method called for 10about to insert 10transaction successful for 10store method called for 9about to insert 9transaction successful for 9store method called for 8about to insert 8transaction successful for 8now reload the page and while loading scroll and tap randomlyyou will see some about to insert messages are missingdatabase is runningtable will be clearedstore method called for 10about to insert 10transaction successful for 10store method called for 9about to insert 9transaction successful for 9store method called for 8transaction successful for 8 where is my about to insert 8 store method called for 7about to insert 7transaction successful for 7this is because the transactioncallback is completely skipped but why and why does the successcallback fire instead of the errorcallbackthis is a simplified example please do not tell me not to do this settimeout stuff in the real world there is data being loaded async and then being inserted i think there is a similar problem here html5 web sql transaction missing in action but there is no solution or hint eitherany ideas i am stuck thanks,"['javascript', 'iphone', 'sql', 'ios']" +233576,can i get write access to raw thisk sectors under vista and windows 7 in user mode from the rawthisk website the new security model of windows vista puts tight restrictions on applications executed in user mode even with elevated administrative rights the application canat get write access to raw thisk sectorsis this truefrom the microsoft docthe changes to the file system and to the storage stack do not apply if the volume is not mounted or if the volume has no file systemplease giveeither a link to the official microsoft doc confirming the rawthisk websiteor a working code example i obviously failed to create one createfile call fails with error access denied if generic write is setother relevant microsoft docs that i have so far foundblocking direct write operations to volumes and thisksirp mj write at sl force direct writeflt io parameter block structure at sl force direct write,"['c++', 'c']" +233581,how to add orgapachecommonsiofilenameutils to maven in intellij i should add orgapachecommonsiofilenameutils to intellij 10 how can i add it to maven and use it in the codei need to be able to use filenameutils in my codei have already this orgapachecommons in mavenimport orgapachecommonsiofilenameutils,['java'] +233590,how to programmatically set thiscoverable time without user confirmation i usually use thisprivate void ensurethiscoverable ifd logdtag ensure thiscoverable if mbluetoothadaptergetscanmode bluetoothadapterscan mode connectable thiscoverable intent thiscoverableintent new intentbluetoothadapteraction request thiscoverable thiscoverableintentputextrabluetoothadapterextra thiscoverable duration 300 startactivitythiscoverableintent but that prompts a user confirmation is there a way to bypass this programmaticallyalso i suppose there are no news on the always thiscoverable mode,"['java', 'android']" +233593,how to get imei number in phonegap i am developing a phonegap android mobile application using jqueryjavascript and html i want to get the mobile imei i have tried this code from this tutoriali am getting the number97734a345d234dlike thisi have checked my device to get imei number using 06i dunno whether it is correct or wrong please kindly guide methanks in advance,['android'] +233597,nested methods best practice i am currently fiddling around with jquerys ajax method to get some data from a json feed and animating some bars according to the dataas i am hacking away i do not really know if my approach is rightajax url echojson type post data data success functiondata value1bar usagebarfillanimate width datavalue1 2500 function animation complete value2bar usagebarfillanimate width datavalue2 2500 function animation complete datatype jsonis it ok to animate the divs from inside the ajax method or is there a more correct way to do this formatting wise memory wise etcis it better to some how return some variables from the ajax method and executing the animation method from outside the ajax methodcheck out jsfiddle example here i know this is a pretty broad question but being a graphic designer come selftaught web designer i never really know if what i am doing is good practice,"['javascript', 'jquery']" +233599,how to grey out a button i have a button defined as shown below when i want to thisable it i use my btnsetenabledfalse but i would also like to grey it out how can i do thatthanksbutton androidididbuy btn stylestylesrp button stylesrp buttonstyle namesrp button parentandroidstylewidgetbutton item nameandroidbackgrounddrawablebtn defaultitem item nameandroidlayout widthwrap contentitem item nameandroidlayout heightwrap contentitem item nameandroidtextcolorfitem item nameandroidtextsize14spitem item nameandroidtypefaceserifitem item nameandroidpaddingleft30dpitem item nameandroidpaddingright30dpitem item nameandroidpaddingtop5dpitem item nameandroidpaddingbottom5dpitemstyledrawablebtn defaultxmlxml version10 encodingutf8shape xmlnsandroid solid androidcolorcolorpink corners androidradius6dp shape,['android'] +233617,difference between uibutton methods that set image please tell me whats the difference between two uibutton methods voidsetbackgroundimageuiimage image forstateuicontrolstatestateand voidsetimageuiimage image forstateuicontrolstatestateapple documentation says nothing about it,['ios'] +233656,debugging android widget in intellij idea when debugging widget every breakpoint causes anr there is solution for eclipse but i cannot find solution for idea,['android'] +233662,contains with collator i have to test whether a string is included in another one but without considering case or accents french accents in this casefor example the function must return true if i search for rhone in the string vallae du rha nethe collator is useful for string comparison with accents but does not provide a contains functionis there an easy way to do the job a regex maybe additional information i just need a true false return value i do not care about number of matches or position of the test string in the reference string,['java'] +233668,sqlite foreign keys contraints ios 5 it seems that foreign keys constraints are supported since version 36x in sqlite the version of sqlite on ios50 is 377 found in sqlite3hbut when i try to insert a row in a table that has a constraint my row is correctly inserted even if the related foreign key is not existing i have no errordoing the same insert statement using apps like navicat gives me a constraint violation errordo you know if foreign keys are supported on ios 5 here is the database schemacreate table artist artistid integer primary key artistname textcreate table track trackid integer primary key autoincrement trackname text trackartist integer constraint trackartist foreign key trackartist references artist artistid on delete cascade on update cascadereally simple is not it thanksemmanuel,['ios'] +233677,performselectorwithobjectafterdelay not making call in a method i want to call a method after and seconds selftoolbarstate nsnumber numberwithint1 self changebuttonnames self drawmap self performselectorselectorshowactionsheet withobjectnil afterdelay2i want to show the action sheet 2 seconds after drawmap is complete when i use this performselector it never makes the callif i just put self showactionsheet it works just fine is there reason why the performselector is not making the calledit in another part of my code i make the same call and it workshud mbprogresshud alloc initwithviewselfviewselfview addsubviewhudhuddelegate id selfhud showwhileexecutingselectordrawmap ontargetself withobjectnil animatedyesself performselectorselectorshowactionsheet withobjectnil afterdelay6here the showactionsheet gets called 6 seconds after drawmap has completed i am guessing there is something going on with the threads that i do not understand yetedit2voidshowactionsheet inspectappdelegate datacenter inspectappdelegate uiapplication sharedapplication delegate if datacenterfieldidtopass nil uiactionsheet actionsheet uiactionsheet alloc initwithtitleselected boundary options delegateid self cancelbuttontitlecancel destructivebuttontitlenil otherbuttontitlesanalyze a fieldretrieve saved analysi geotag photos refresh the mapnil actionsheettag 0 actionsheet showinviewselfview else uiactionsheet actionsheet uiactionsheet alloc initwithtitleselected boundary options delegateid self cancelbuttontitlecancel destructivebuttontitlenil otherbuttontitlesanalyze a fieldretrieve saved analysi geotag photos attribute the field refresh the mapnil actionsheettag 0 actionsheet showinviewselfview edit3ok so the progress of method calls isvoid founddoubletapuitapgesturerecognizer recognizer hud showwhileexecutingselectorselect ontargetself withobjectnil animatedyesvoid select self changebuttonnames self drawmap self performselectorselectorshowactionsheet withobjectnil afterdelay2showactionsheet never gets called like i said i am pretty sure its a threading issue if call it with self showactionsheet it will run,"['iphone', 'objective-c', 'ios']" +233679,is there a way to get last inserted id of a non auto incremented column in mysql i know how last insert id works for auto incremented columns but i cannot find a way to get the last id i inserted for a non auto incremented column is there a way i can do that,['mysql'] +233690,where should i implement this private helper function my class definition is spread across headers and source files thppclass t public void foo tcppvoid tfoo if tfoo needs to make use of some helper function that need be visible only to t which of the below solutions is best1 private member thppclass t public void foo private void helper tcppvoid tfoo helpervoid thelper 2 free function accessible only in class definitions tu thppclass t public void foo tcppnamespace void helper void tfoo helperis there any difference except that with the former i will end up with more functions in the header file,['c++'] +233691,how to handle double opacity of two overlapping divs i have two divs both with 06 opacity i need them to overlap but retain their opacity and not create a new combined opacity level i cannot use an image edit the little circle is supposed to have a canvas element in it not sure if pseudoelements would be the best solutionis there anyway to do this with css or should i just use canvasexample htmldiv idfoo div idbar divdivcss double opacity bodybackgroundgreenfooheight150pxwidth250pxbackgroundrgba0 0 0 06positionabsoluteleft40top20barheight40pxwidth40pxbackgroundrgba0 0 0 06borderradius40pxpositionabsolutetop15pxleft15px,['css'] +233693,convert postgresql dump file to mysql i want to convert a postgresql dump file i received to a mysql dump file or even sql text to be generated,"['mysql', 'sql']" +233697,thread local variables and fs segment i am reading from a thread local variable in my code like this tid local is declared as thread int tid locallong tid tid locallooking around the thissassembled code i saw something like this which i suspect is the instruction which assigns tid by reading tid localmovslq fs0xfcrbxnow my question is if this can really be the instruction which is doing this that is reading from the local thread variable and if gcc always uses the fs segment for storing thread local variables how is this supposed to work,['c'] +233719,assignment with or in python is it considered bad style to assign values to variables like thisx foobar or noney some variable or nonein the above example x gets the value foobar,['python'] +233734,xcode shortcut for jumping to implementation of a method is there a keyboard shortcut in xcode for jumping to the implementation of a method i am aware of the fact the commandclick will jump to definition but i want to jump to the implementation method not the definition also i want to use keyboard shortcuts with no involvement of the mouse including clicks,"['iphone', 'ios']" +233751,how do you decide what byte size to use for inputstreamread when reading from inputstreams how do you decide what size to use for the byte int nreadbyte data new byte16384 this number is the one i am wondering aboutwhile nread isreaddata 0 datalength 1 do somethingwhen do you use a small one vs a large one what are the differences does the number want to be in increments of 1024 does it make a difference if it is an inputstream from the network vs the thiskthanks much i cannot seem to find a clear answer elsewhere,['java'] +233756,arc or not to arc iphone ios5 i have developed an iphone application which should support ios4 and ios5 based iphoneipadmy application leaks memory at few places which is becoming hard to debug due to the size of code i recently read about arc automatic reference counting my query isdo i need to modify my source code retainrelease allocdealloc to compile with arcalso what all changes we need to perform using arcis it advisable to shift to arcwill my app work on ios4 phone if i use arcthanks,"['iphone', 'ios']" +233766,sort xml nodes by alphanumeric using c say i have an xmldocument that i generate that has innerxml that looks like thisorm o01 msh msh9 msg2o01msg2 msh9 msh6 hd113702hd1 msh6 msh orm o01patient pid pid18 cx1secondtestfincx1 pid18 pid3 cx1108cx1 pid3 pid orm o01patientorm o01as you can see node pid18 is before node pid3 msh9 is also before msh6restructuring my generation would cause my nice clean code to become very messyis there a way to sort the nodes so that it will sort alpha until it hits the last period then sort numeric if the last values are numbersby numeric sorting i mean it will look at the whole number rather than char by char so 18 3,"['c#', '.net']" +233795,how can i check multiple textboxes if null or empty without a unique test for each i have about 20 text fields on a form that a user can fill out i want to prompt the user to consider saving if they have anything typed into any of the text boxes right now the test for that is really long and messyifstringisnulloremptytxtbxafterpictext stringisnulloremptytxtbxbeforepictext stringisnulloremptysplitcontainer1panel2 many more testsis there a way i could use something like an array of any where the array is made of the text boxes and i check it that way what other ways might be a very convenient way in which to see if any changes have been made since the program startedone other thing i should mention is there is a date time picker i do not know if i need to test around that as the datetimepicker will never be null or emptyediti incorporated the answers into my program but i cannot seem to make it work correctlyi set up the tests as below and keep triggering the applicationexit call it starts out saying everything is empty bool allfieldsempty true foreachcontrol c in thiscontrols checks if its a textbox and if it is is it null or empty ifthiscontrolsoftypetextboxanyt stringisnulloremptyttext this means soemthing was in a box allfieldsempty false break if allfieldsempty false messageboxshowconsider saving else this means nothings new in the form so we can close it applicationexit why is it not finding any text in my text boxes based on the code above,['c#'] +233804,osx javavm awtswing and possibly a deadlock i am really new to java programming therefore i apologise in advance if this sounds like a stupid questioni am trying to build a simple application written in plain c which must create a javavm and then create a new window by loading java code based on awtswingfollowing this technical note iv learned that in mac osx only javavm must be invoked from a thread different from the main thread in order to be able to create a gui based on awttherefore in the main function of my c application i created a new thread that performs everything from the creation of the javavm to the creation of the guisince the application is not in reality so simple i will post a simplified versionmain functionint mainint argc char argv runtime loading of javavm framework void result result dlopensystemlibraryframeworksjavavmframeworkjavavm rtld lazy if result printfcannot open library javavm sn dlerror else printflibrary javavm loadedn start the thread that runs the vm pthread t vmthread create a new pthread copying the stack size of the primordial pthread struct rlimit limit size t stack size 0 int rc getrlimitrlimit stack limit if rc 0 if limitrlim cur 0ll stack size size tlimitrlim cur pthread attr t thread attr pthread attr initthread attr pthread attr setscopethread attr pthread scope system pthread attr setdetachstatethread attr pthread create detached if stack size 0 pthread attr setstacksizethread attr stack size start the thread that we will start the jvm on pthread createvmthread thread attr startjava void thread data struct pthread attr destroythread attr pthread exitnull return 0thread functionvoid startjavavoid jvm lib javavminitargs args const char classpath getenvclasspath determine classpath char classpath opt str printfdjavaclasspaths classpath javavmoption option mallocsizeofjavavmoption 2 option0optionstring classpath opt option1optionstring str printfverbosejni argsversion jni version 1 6 argsnoptions 2 argsoptions option argsignoreunrecognized jni false do not ignore unrecognized options fptr jni createjavavm jni createjavavm fp fptr jni createjavavmdl dlsymjvm lib jni createjavavm int result jni createjavavm fpjvm void env args freeoption freeclasspath opt launch java code jclass init class envfindclassenv orgclassesloader jmethodid load id envgetstaticmethodidenv init class load ljavalangstringlorgclassesstuffjv envcallstaticvoidmethodenv init class load idjava code updatedpackage orgclassesimport javaawtawtexceptionimport javaawtcomponentimport javaawtframeimport javaawtimagebufferedimageimport javaawteventqueuepublic class loader public static void loadstring basedir stuff stuff long nativepointer eventqueueinvokelaternew runnable public void run systemloadlibrarydrawinghelperlibrary start test window frame frame new frame framesetsize640480 framesetlocation50 50 framesetvisibletrue all of the above code executes successfully except for the creation of the window which causes a deadlock or something similar since terminal remains busy without any cpu usage and both threads remain aliveif i comment out the lines concerning the creation of the window the application execute successfully and quitthis is the output from jstackfull thread dump java hotspottm 64bit server vm 204b02402 mixed modeattach listener daemon prio9 tid1040b1800 nid0x11b80 waiting on condition 0 javalangthreadstate runnablelow memory detector daemon prio5 tid1038060 nid0x10b1370 runnable 0 javalangthreadstate runnablec2 compilerthread1 daemon prio9 tid103805800 nid0x10b0340 waiting on condition 0 javalangthreadstate runnablec2 compilerthread0 daemon prio9 tid103804800 nid0x10af310 waiting on condition 0 javalangthreadstate runnablesignal thispatcher daemon prio9 tid1038040 nid0x10ae2e0 runnable 0 javalangthreadstate runnablesurrogate locker thread concurrent gc daemon prio5 tid1038030 nid0x10ad2b0 waiting on condition 0 javalangthreadstate runnablefinalizer daemon prio8 tid10409b800 nid0x10ac280 in objectwait 10ac270 javalangthreadstate waiting on object monitor at javalangobjectwaitnative method waiting on 7f3001300 a javalangrefreferencequeuelock at javalangrefreferencequeueremovereferencequeuejava118 locked 7f3001300 a javalangrefreferencequeuelock at javalangrefreferencequeueremovereferencequeuejava134 at javalangreffinalizerfinalizerthreadrunfinalizerjava159reference handler daemon prio10 tid10409b0 nid0x10ab250 in objectwait 10ab240 javalangthreadstate waiting on object monitor at javalangobjectwaitnative method waiting on 7f30011d8 a javalangrefreferencelock at javalangobjectwaitobjectjava485 at javalangrefreferencereferencehandlerrunreferencejava116 locked 7f30011d8 a javalangrefreferencelockmain prio5 tid1040800 nid0x10048d0 runnable 10048a0 javalangthreadstate runnable at javalangclassloadernativelibraryloadnative method at javalangclassloaderloadlibrary0classloaderjava1827 locked 7f30010a8 a javautilvector locked 7f3001100 a javautilvector at javalangclassloaderloadlibraryclassloaderjava1724 at javalangruntimeloadlibrary0runtimejava823 locked 7f3004e90 a javalangruntime at javalangsystemloadlibrarysystemjava1045 at sunsecurityactionloadlibraryactionrunloadlibraryactionjava50 at javasecurityaccesscontrollerdoprivilegednative method at sunawtnativelibloaderloadlibrariesnativelibloaderjava38 at sunawtdebughelperclinitdebughelperjava29 at javaawtcomponentclinitcomponentjava566 at orgclassesloaderloadloaderjava69vm thread prio9 tid1040960 nid0x10aa220 runnable gang worker0 parallel gc threads prio9 tid1040020 nid0x1035040 runnable gang worker1 parallel gc threads prio9 tid104002800 nid0x1036070 runnable concurrent marksweep gc thread prio9 tid10404d0 nid0x10a6f0 runnable vm periodic task thread prio10 tid103817800 nid0x10b23a0 waiting on condition exception catcher thread prio10 tid104001800 nid0x1034010 runnable jni global references 913i really do not know what more can i do maybe it is a stupid mistake but i am not skilled enough with this javac mix since it is the first time that i am looking at it update i have updated the java code thanks to trashgod but it still does not workam i missing something,"['java', 'c']" +233816,how to get a pixels xy coordinate color from an image is there any way to check if a selectedxy point of a png image is transparent,['javascript'] +233829,android can not perform this action after onsaveinstancestate i am still apparently not clear on handling fragments along with other things going on in my activity the following is the stack tracejavalangruntimeexception failure delivering result resultinfowhonull request2 result1 dataintent has extras to activity comghcssoftwaregedstarcomghcssoftwaregedstargedstar javalangillegalstateexception can not perform this action after onsaveinstancestateat androidappactivitythreaddeliverresultsactivitythreadjava2747at androidappactivitythreadhandlesendresultactivitythreadjava2790at androidappactivitythreadaccess20activitythreadjava122at androidappactivitythreadhhandlemessageactivitythreadjava1035at androidoshandlerthispatchmessagehandlerjava99at androidoslooperlooplooperjava132at androidappactivitythreadmainactivitythreadjava4028at javalangreflectmethodinvokenativenative methodat javalangreflectmethodinvokemethodjava491at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava844at comandroidinternaloszygoteinitmainzygoteinitjava602at dalviksystemnativestartmainnative methodcaused by javalangillegalstateexception can not perform this action after onsaveinstancestateat androidsupportv4appfragmentmanagerimplcheckstatelossfragmentmanagerjava1299at androidsupportv4appfragmentmanagerimplenqueueactionfragmentmanagerjava1310at androidsupportv4appfragmentmanagerimplpopbackstackfragmentmanagerjava471at comghcssoftwaregedstarpersontabpersontabfragpopstackpersontabjava157at comghcssoftwaregedstarpersontabpersontabfragfilldatapersontabjava165at comghcssoftwaregedstarviewtabfilldataviewtabjava96at comghcssoftwaregedstargedstarfilldatagedstarjava589at comghcssoftwaregedstargedstaronactivityresultgedstarjava514at androidappactivitythispatchactivityresultactivityjava4541at androidappactivitythreaddeliverresultsactivitythreadjava2743so this looks like it is my call to popbackstack within this function where i am cleaning out any stacked fragments in one of my view panes pop fragments from second pane private void popstack if mdualpane mbottomid 0 mviewtabgettabhelpertabgetfragmanagerpopbackstackmbottomid fragmentmanagerpop back stack inclusive mbottomid 1 mainly i am not sure why any of this is occurring after onsaveinstancestate has been called or if that is whats really happening any possible explanations would popbackstackimmediate make a differencefor what it is worth i have not been able to recreate the circumstances in my testing so it is only showing up in the reports,['android'] +233842,softkeyboard does not thisplay for a newly thisplayed fragment i have a fragmentactivity that initially thisplays a fragment with a few buttons on itwhen you click one of the buttons the fragmentactivity thisplays a new fragment with some edittext fields i cannot seem to get the soft input keyboard to thisplay when my new fragment with the edittext fields is thisplayed using the windowsoftinput mode on the manifest is out as that thisplays the keyboard right away androidwindowsoftinputmodestateunchangedi have tried using getwindowsetsoftinputmodewindowmanagerlayoutparamssoft input state visibleto no availheres how i thisplay the new fragment from my activitypublic void clickhandlerview view switch viewgetid case ridlogin loginfragment new loginfragment fragmenttransaction transaction getsupportfragmentmanager begintransaction transactionreplaceridfragment container loginfragment transactionaddtobackstacknull transactioncommit getwindowsetsoftinputmodewindowmanagerlayoutparamssoft input state visible breaki have also tried calling setsoftinputmode from within the fragments oncreate and that has not worked as well thinking it was a timing issue i tried it with handlerpostdelayed and that did not work either it looked like thisonresume handler handler new handler runnable runnable new runnable override public void run getactivitygetwindowsetsoftinputmodewindowmanagerlayoutparamssoft input state visible handlerpostdelayedrunnable 10any help will be appreciated thanks,['android'] +233843,uiwebview and define dictionary i had the copy and define option built in with the uiwebview it worked just fine on the ipad but on the iphone it only works once when i highlight the text and use the dictionary and the second time i tried it it does not show up the popover any ideaupdatei am getting the following error as well when thismissing the dictionary on the iphoneunbalanced calls to beginend appearance transitions for uifallbackpresentationviewcontrollerupdatewhen i present a uialertview and cancels it the dictionary works again wonder why,"['iphone', 'objective-c', 'ios']" +233861,mobile safari bug on fixed positioned button after scrolltop programmatically changed i am just about done a webpage but there is one bug in mobile safari iphone and ipad ios 501 with two buttons that are fixed to the upper and lower right corners the buttons are not faded in until after clicking submit on a textbox which opens up to the rest of the page after the rest of the page is loaded and the buttons are faded in you can click on either of them and they both work however clicking them causes a programmatic scroll and after that scroll is complete you can no longer click on either of the buttons until you physically scroll the page with your finger even just a tiny one pixel scrollwhat i have noticed is that after the programmatic scrolling if you tap just slightly below the top button you see the highlight as if you were tapping the bottom button and the action of the bottom button is processed which tells me the bug is that when scrolling programmatically the fixed position button still moves with the rest of the page and does not go back to it is fixed position until an actual touch scroll is performed does anyone know a way around thisi have added a popup that shows which button was pressed so you can test it remember after the first press of the down button which works trying pressing down again it would not work but click just below the up button and youll see the down button actions happeningthanks for the help thomasalso if you can point me to where i can submit a bug to apple that would be good too unless one already has beenedit just click either of the submit arrows you do not need to enter a wagesalary it has defaultsedit 2 here is a simpler example to show the same issueedit 3 bug reported to apple,['jquery'] +233883,how to pass values from controller to view in aspnet i am developing an application where i need to pass the value of username from a controller to a viewi tried viewdata as given in my code in controller is public actionresult indexstring username string password viewdatausername username return viewwhere username and password are obtained from another formand the code in the view is viewbagtitle index h2indexh2 viewdatausername but when i run this code the thisplay shows viewdatausername instead of the actual username say for example xyzhow should i thisplay the actual usernamethank you very much in advance for your help,['c#'] +233906,show flash message without redirect eg forward messages shown twice is it possible to show flash messages in symfony 2 without redirect or editing core files in another possible solution on google groupssymfonycomponenthttpfoundationsession public function setflashname value persist true if false thisstarted thisstart thisflashesname value ifpersist unsetthisoldflashesname else thisoldflashesname value updateoh actually i noticed if i just used a forward flash messages will show but it will still show on next request,['php'] +233909,how to get exact browser name and version i have tried some solutions but i am unable to get exact name and versioni am trying following codebrowseragent serverhttp user agentecho browseragentoutput of above codemozilla50 x11 linux i686 applewebkit53424 khtml like gecko chrome11069668 safari53424but i am usinggoogle chrome 11069668on ubuntu 1004so i can find in chrome11069668 in output string but it is also showing some other browsers names that is confusing to extract exact browser nameversion from string,"['php', 'javascript', 'jquery']" +233920,is there any replacement of long double in java i was reading about data types in c i found the range of long double is more than that of double in java for very huge number we can use long double in c if i want to store the same number in java what we have to do which datatype we can use double in java takes 8 bytes64 bits ie 754 it covers a range from 494065645841246544e324d to 179769313486231570e308d positive or negativelongdouble in c takes 10 bytes 80 bitscan anyone tell me is there any replacement of longdouble in java,"['java', 'c']" +233935,how to convert two dimensional array to one dimensional array in php5 possible duplicateturning multidimensional array into onedimensional array i have this kind of an arrayarray 0 array 0 868 1 array 0 867 2 array 0 869 3 array 0 870 i need to convert this to one dimensional array how can i do thatfor example like thisarray 0 868 1 867 2 869 3 870 any php built in functionality is available for this array conversion,['php'] +233942,hide line in default state in highcharts how to hide line in default state in highcharts jsscripti have 7 series on my canvas 34 of them are optional and i want to make them hidden when the page is load but also show them in legend to inform user that he can enable them if wants,['javascript'] +233954,how to interpret objectivec type specifier eg returned by method copyreturntype given i have a type specifier as returned by method copyreturntype in the gnu runtime delivered with the gcc there are various methods to work with such a type specifier like objc sizeof type objc alignof type and otherswhen using the apple runtime there are no such methodshow can i interpret a type specifier string eg get the size of a type using the apple runtime without implementing an ifelse or case switch for myselfupdatei am not able to use the apple foundation,['objective-c'] +233958,how to change front color of navigation bar title i am using navigation controller in my application and want to change title color of navigationbari am doing so using below code nsdictionary dic nsdictionary dictionarywithobjectsandkeysuicolor graycoloruitextattributetextcolornil selfnavcontrollernavigationbar settitletextattributesdicone more thing i am using arc xcode 42 and this code is placed on appdelegate onlyit is working fine in ios 4but not working on below versionsplease help me how to do this from single code on appdelegate,"['iphone', 'objective-c', 'ios']" +233966,parallel for loops are they wait for finish i have two for loops which the second loop must be started after finishing the first loopso if i use two parallelfor loops will the second loop runs after the finishing the first loop,"['c#', '.net']" +233976,androidhow do i connect my android phone to projector thru usbhdmi is it possible to project an android phone to projector via usbhdmi,['android'] +233997,valign vs textalign in html i cannot figure out the difference between valign vs textalign in html in context with the following code table width500 border0 tr td colspan2 stylebackgroundcolorffa500 h1main title of web pageh1 td tr tr valigntop td stylebackgroundcolorffd700width100pxtextaligntop bmenubbr htmlbr cssbr javascript td td stylebackgroundcoloreheight200pxwidth400pxtextaligntop content goes heretd tr tr td colspan2 stylebackgroundcolorffa500textaligncenter copyright a 2012td tr table,"['html', 'css']" +234008,ef4 mapping varbinarymax to binary code first error i have a poco class called attachment that maps to a table in sqlserver with a varbinarymax field in it the field contains files the poco class looks like this public class attachment public string attachmentid get set public string attachmenttypeid get set public string title get set public string text get set public binary data get set the mapping looks like thismodelbuilderentityattachmentpropertya adatahascolumnnamecol datahowever the mapping is throwing an errorthe type systemdatelinqbinary must be a nonnullable value type in order to use it as a parameter tthe mapping works fine if i use a byte array but this seems to be corrupting the data on the way through the file in the database has an initial binary string like0x504b0304140808027923401f0i think this is a jpg file any help getting the file out of the db in one piece would be appreciated,['c#'] +234033,how can i create a aopen witha list as in explore in my own application in my application the user can select reference to file for example a image file i would like to make button with a arrow that opens a list with the programs installed on the system witch can open this file typei know that i can get the program names from the registry hkey current usersoftwaremicrosoftwindowscurrentversionexplorerfileexts but how can i filter the entries out that have no meaning dllhostexe miauiexe etcand how can i open the file with program that the user choose lars tech if i look in registry hkey current usersoftwaremicrosoftwindowscurrentversionexplorerfileexts and then openwithlist for the extension jpg i see more entries that if if rigt click on jpg file and choose open with see my first images and i only want thoseand yes there is programs entries that i properly self have added but that have no meaning to a jpg file and windows can filter them out so will i,['c#'] +234045,whats the simplest algorithmsolution for a single pair shortest path through a realweighted undirected graph i need to find a shortest path through an undirected graph whose nodes are real positive and negative weighted these weights are like resources which you can gain or loose by entering the nodethe total cost resource sum of the path is not very important but it must be more than 0 and length has to be the shortest possiblefor example consider a graph like soastart node dend nodea10b 0 c5 d5 e5 f10the shortest path would be aefeddijkstras algorithm alone does not do the trick because it cannot handle negative values so i thought about a few solutionsfirst one uses dijkstras algorithm to calculate the length of a shortest path from each node to the exit node not considering the weights this can be used like some sort of heuristics value like in a i am not sure if this solution could work and also it is very costly i also thought about implement floydawarshalls algorithm but i am not sure how another solution was to calculate the shortest path with dijkstras algorithm not considering the weights and if after calculating the paths resource sum it is less than zero go through each node to find a neighbouring node which could quickly increase the resource sum and add it to the pathseveral times if needed this solution would not work if there is a node that could be enough to increase the resource sum but farther away from the calculated shortest pathfor examplea start node e end nodea10b5 c40 d5 e5 could you help me solve this problemedit if when calculating the shortest path you reach a point where the sum of the resources is equal to zero that path is not valid since you cannot go on if there is no more petrol,['java'] +234054,changed order in mainxml now i get classcastexception using eclipse and the android sdk i managed a simple test app with a button and a progressbar all runs fine except i didt want the progressbar to move the button when the progressbar was made visible so just for testing i changed the order that they are defined in the reslayoutmainxml file which uses a linearlayout compiling and running i then get a classcastexception at the final progressbar line belowpublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain 0106 143739590 eandroidruntime863 javalangruntimeexception javalangclasscastexception androidwidgetbutton cannot be cast to androidwidgetprogressbar final progressbar progressbar progressbar findviewbyidridprogressbar1 here progressbarsetvisibilityprogressbargone final button exebutton buttonfindviewbyidridbutton1 exebuttonsetonclicklistenernew viewonclicklistener etcnow i understand what the clascastexception says and means i just do not understand why it appears i am not trying to cast a button to a progressbar i do not get it,['android'] +234057,are you able to pass the top number as a parameter to a stored procedure possible duplicatesql server use a parameter to select the top x of the result set my query in my stored procedure looks something likeselect top 9 from my tablei would like to edit the stored procedure to dynamically produce the limit from a parameter however this does not seem to be workingalter procedure dbomy stored procedure n int2asbeginselect top n from my tableis this doable or do i have to do something liken int2sql varchar30sql select top n from my tableexecsqlthanks,['sql'] +234089,how to format a phone number with jquery i am currently thisplaying phone numbers like 21247710 however i need the number to be formatted in a more humanreadable form for example 21247710 heres my current htmlp classphone21247710p,"['javascript', 'jquery']" +234105,mysql alter table on tables too large to duplicate when adding a column to a myisam table mysql will createcopydroprename i have a table which is sufficiently large that it cannot be duplicated in the servers remaining free space attempting to add a column then results in the thisk filling time is not an issue here neither is table availability just thisk spaceshort of copying the data to another server truncating altering and copying back is there a way to add a column to a myisam table without it creating a temporary table and duplicating all the data,['mysql'] +234129,peter piper piped a python program and lost all his unicode characters i have a python script that loads a web page using urllib2urlopen does some various magic and spits out the results using print we then run the program on windows like sopython programpy outputhtmheres the problemthe urlopen reads data from an iis web server which outputs utf8 it spits out this same data to the output however certain characters such as the long hyphen that word always inserts for you against your will because it is smarter than you get garbled and end up like a insteadupon further investigation i noticed even though the web server spits out utf8 data the outputhtm file is encoded with the iso88591 character setmy questionswhen you redirect a python program to an output file on windows does it always use this character setif so is there any way to change that behaviorif not is there a workaround i suppose i could just pass in outputhtm as a command line parameter and write to that file instead of the screen but i would have to redo a whole bunch of logic in my programthanks for any helpupdateat the top of outputhtm i addedxml version10 encodingutf8doctype html public w3cdtd xhtml 11en however it makes no difference the characters are still garbled if i manually switch over to utf8 in firefox the file thisplays correctly both ie and ff think this file is western iso even though it is clearly not,['python'] +234159,synchronous and asynchronous activities can anyone help me to understand synchronous and asynchronous activities in androidwhat is exactly meant by synchronous and asynchronous activity in androidstartactivity startsubactivity and startacivityforresult start an activity synchronously or asynchronously or can they behave in both waysplease explain as i have gone through many articles but could not find any proper explaination over this,['android'] +234166,what is the best way to force a try block to break in between i have a trycatch block that i wish to break like a switch block but i could not find a recommended way of doing it i am fetching a lot of data in the trycatch block and wish to stop the fetching in between in case a certain condition is met just to get it working for now i have deliberately forced the code to go into the catch blockint i0 try do stuff ifis condition met i 10 divide 1 by 0 a definite exception catch exception e do nothingis it safe to do this or should i go for another wayediti am fetching some xml dataactually a lot depending on the internet connection i need to stop the parsing after sometimetimeout rather than go through the entire stream i go through loops but i also make some calculations later it does not make any sense to calculate with incomplete data so i would prefer to just skip the whole thing,['java'] +234178,how to compare time in ruby i need to use a time object as a int timeobjectto ithen i need to convert a int back to a time to compare against the original timeshort examplet1 timenowt2 timeatt1to iputs t1 t2 says falseputs t1eqlt2 says falsewhy this says its false when i print both time objetcs shows the same thing dputs t1 shows 20120106 160153 0300puts t2 shows 20120106 160153 0300puts t1to ato s shows 53 1 16 6 1 2012 5 6 true clst puts t2to ato s shows 53 1 16 6 1 2012 5 6 true clst they are the same thing d but when trying to compare with or eql says they are diferentsorry for my bad english,['ruby'] +234183,how do write if else statement in a mysql query how do i write an if else statement in a mysql query something like thismysql queryirrelevant code ifaction2state0state1then down in my array i should be able to do this rowstate this should equal 1 the query should not change anything in the database just the variable for returning the information,['mysql'] +234186,loading jquery onthefly i cannot figure out what is wrong with my code here i am trying to load jquery dynamically if it is not present on the page head script function if typeof jquery undefined jquery is already loaded verify minimum version number of 142 and reload newer if needed if 10123401testjqueryfnjquery 11testjqueryfnjquery 12testjqueryfnjquery 13testjqueryfnjquery loadjq else loadjq function loadjq adds a link to jquery to the head instead of inline so it validates var headelement documentgetelementsbytagnamehead0 linkelementdocumentcreateelementscript linkelementsrc linkelementtypetextjavascript headelementappendchildlinkelement alertheadelement scriptheadthis is my body body buttonclick mebutton script typetextjavascript documentreadyfunction alerthello buttonclickfunction thishide script bodywhen i put this in a html page i get an error saying that is not defined anyone has any idea why,"['javascript', 'jquery']" +234188,how to make a circular div in chrome i have this div which acts a lens in zooming of the image but the problem is that i want it circular i am using this for thatwebkitborderradius9pxmozborderradius9pxborderradius9pxthe problem is that it makes the div circular but does not hide the image corners which are not part of the circle and hence shows a rectanglethe url is click on the desert picture and then see the bigger image on the right for zoom effect if you give the lens div border 1px solid red then you can see that the div is actually circular but it does not hide the useless part of imagesany ideas,"['css', 'html']" +234189,c gif image to memorystream and back lose animation i have a small problem and i do not find any solutionsi want to convert a gif to a byte and then back to a gif i works fine but i lose the animationit is a perfectly animated gif when i start i show it in a picturebox element but after conversion i get stuck with the first framehttpwebrequest httpwebrequest httpwebrequesthttpwebrequestcreatecreativetechscomitip imagesexampleanimationgifhttpwebresponse httpwebreponse httpwebresponsehttpwebrequestgetresponsestream stream httpwebreponsegetresponsestreamimage img imagefromstreamstreammemorystream ms new memorystreamimgsavemsimgrawformatbyte bytes mstoarrayimage img2 imagefromstreamnew memorystreambytesint frames1 imggetframecountsystemdrawingimagingframedimensiontimeint frames2 img2getframecountsystemdrawingimagingframedimensiontimei also tried to use not rawformat but systemdrawingimagingimageformatgif did not change a thing frames1 is right number of frames frames2 is 1i have 2 picturebox elements in my gui one showing img and the other img2 but img2 is not animated while img is what is wrongi have also tried to use serialization instead to create my bytei serialized the image and deserialized it again and it did not change anything either how is this possible,['c#'] +234205,how can i check for real touch support on a browser today or very recently chrome beta updated to 17 for me and with it i noticed some funkiness in my web app i noticed it was because a class was being added to the body element that normally only gets put there if there is touch event support which i check like this try documentcreateeventtouchevent devicetouch true catch e devicetouch false and sure enough i can create and trigger touch events on chrome 17 first idea i had was oh i can check for touch and see if a mouse click fails therefore there is a mouse but mouseevents trigger toohow else can i check without user agent sniffing that it is an actual touchable device and not just a browser that supports touch events,"['javascript', 'jquery', 'ios']" +234209,is there a way to grant all privileges to the same user from multiple lan addresses in a single command i am using the following commandgrant all privileges on to userip identified by password with grant optionto grant all privileges to a user is there a way i can make the ip a wildcard like 1921681 so that i do not need to manually add each lan ip i want give the user access to connect from,['mysql'] +234214,how to compare two images using byte arrays i want to be able to convert from byte to image and vice versai have this two methods from herepublic byte imagetobytearraysystemdrawingimage imagein memorystream ms new memorystream imageinsavemssystemdrawingimagingimageformatgif return mstoarraypublic image bytearraytoimagebyte bytearrayin memorystream ms new memorystreambytearrayin image returnimage imagefromstreamms return returnimagethey seem to work but if i dobyte pic getimagefromdbbool result pic imagetobytearraybytearraytoimagepici get result falseany way to correct this methods or some different functions to achieve my goalthanks,['c#'] +234215,what is best performance for retrieving mysql eav results as relational table i want to extract results from eav entityattributevalue tables or more specifically entitymetadata tables think like wordpress wp posts and wp postmeta as a nicely formatted relational table in order to do some sorting andor filteringi have found some examples of how to format the results within the query as opposed to writing 2 queries and joining the results in code but i would like to know the most efficient method for doing so especially for larger result setsand when i say most efficient i mean for something like the following scenariosget all entities with last name like xyzreturn a list of entities sorted by birthdayeg turn this entity id name whatever 1 bob etc 2 jane etc 3 tom etc meta id entityid key value 1 1 first name bob 2 1 last name bobson 3 1 birthday 19831010 2 first name jane 2 last name janesdotter 2 birthday 19830810 3 first name tom 3 last name tomson 3 birthday 19800810into this results eid name first name last name birthday 1 bob bob bobson 19831010 2 jane jane janesdotter 19830810 3 tom tom tomson 19800810so i can sort or filter by any of the meta fieldsi found some suggestions here but i cannot find any thiscussion of which performs betteroptionsgroup concatselect e group concat concat ws mkey mvalue order by mkey separator from entity e join meta m on eid mentityidmultijoinselect e m1value as first name m2value as last name m3value as birthdayfrom entity eleft join meta m1 on eid m1entityid and m1meta key first nameleft join meta m2 on eid m2entityid and m2meta key last nameleft join meta m3 on eid m3entityid and m3meta key birthdaycoalescingselect e max ifmkey first name mvalue null as first name max ifmkey last name mvalue null as last name max ifmkey birthday mvalue null as birthdayfrom entity ejoin meta m on eid mentityidcodeselect e from entity e where eid whateverin php create a placeholder object from resultselect m from meta m where mentityid whateverin php loop through results and attach to entity object likeeresultkey resultvaluewhich is better in general and for filteringsortingrelated questionsbinding eav resultshow to pivot a mysql entity,['mysql'] +234219,markov clustering algorithm i have been working through the following example of the details of the markov clustering algorithm presentation2pdfi feel like i have accurately represented the algorithm but i am not getting the same results that this guide at least was getting for that inputcurrent code is ati am not sure if perhaps i have just missed a small fact or just need a small tweak somewhere for this but i have tried a few variations includingswapping the inflationexpansionchecking for equality based on a precisionremoving the normalization since the original guide did not require it although the official mcl documentation states to normalize the matrix on every passall of these have returned the same result the node only influences itself i have even found a similar algorithm implementation in vband my code seems to match up with the exception of their numbering 600 thistance for instance this is the expansion function take the powerth power of the matrix effectively multiplying it with itself pow timesthismatrixexpand functionmatrix pow var resultmatrix forvar row0rowmatrixlengthrow resultmatrixrow forvar col0colmatrixlengthcol var result 0 forvar c0cmatrixlengthc result matrixrowc matrixccol resultmatrixrowcol result return resultmatrix and this is the inflation function applies a power of x to each item in the matrixthismatrixinflate functionmatrix pow forvar row0rowmatrixlengthrow forvar col0colmatrixlengthcol matrixrowcol mathpowmatrixrowcol powand finally the main passthru function girvananewman algorithmthisgetmarkovcluster functionpower inflation var lastmatrix var currentmatrix thisgetassociatedmatrix thisprintcurrentmatrix thisnormalizecurrentmatrix currentmatrix thismatrixexpandcurrentmatrix power thismatrixinflatecurrentmatrix inflation thisnormalizecurrentmatrix whilethisequalscurrentmatrixlastmatrix lastmatrix currentmatrixslice0 currentmatrix thismatrixexpandcurrentmatrix power thismatrixinflatecurrentmatrix inflation thisnormalizecurrentmatrix return currentmatrix,['javascript'] +234221,escaping special characters in sql is there an easy way in oracle to escape special characters in a sql statement ie i saw this link in regard to manually escaping characters but i thought oracle may have provided an easier way to do sonote i am generating dynamic sql select statements through an orm,['sql'] +234227,programmatically getting the maven version of your project how do i get the maven version of my project programaticallyin other wordsstatic public string getversion what goes herefor example if my project would generate the jar calculatorapp123jar i want getversion to return 123,['java'] +234228,how to get specific element count in xml or xelement variable consider this xmlemployees person id10id namenimaname lnameaghalname person person id1001id namelighaname lnamelighalname person person id1002id namejighaname lnamejighalname person person id1003id nameabaname lnameabalname personemployeesi declare a xelement variable and create the xml assigning it to that how i can get count of id elements in this xml variable in c,['c#'] +234247,scipylinalgeig return complex eigenvalues for covariance matrix the eigenvalues of a covariance matrix should be real and nonnegative because covariance matrices are symmetric and semi positive definitehowever take a look at the following experiment with scipy anprandomrandom5 bnprandomrandom5 ab npvstackabt cnpcovab eigc790174997e01 0e00j2383473e17 615983679e17j2383473e17 615983679e17j176100435e17 0e00j 542658040e33 0e00jhowever reproducing the above example in matlab works correctlya 06271 04314 03453 08073 09739b 01924 03680 00568 01831 00176ccovabeigc0 0 0 07902,['python'] +234249,mysql update two tables at once i have two tables that need need the exact same values for denormalization purposesheres the queryfirst tableupdate table one set win win1 streak streak1 score score200 where userid 1 and lid 1 limit 1second tableupdate table two set win win1 streak streak1 score score200 where userid 1 limit 1as you can see the only difference between both tables is their name and table two does not have the field lid anyway to combine both updates to just one,['mysql'] +234288,is there a loop startover there is continue to stop the loop and move to the next loopthere is break to stop the loop and move to the end of the loopis not there some kind of start that stop the loop and move to the beginning of the loopi know it is easy to achieve all of these three actions by just modifying the value of i but i always try to look for already builtit functions,['javascript'] +234292,using appmobi can i create android apps and iphone apps for free besides googleapple costs in a quest for an answer whether to go for native iphone development vs hybrid html5cssjs development coming from some android experience i would like to understand the following about appmobi frameworkwith appmobi xdk which i can download for free and without paying any particular online service will i be able to build and obtain an android package ready for android market and an iphone package ready for appstoresame question as before but with phonegap xdk download it for free no cloud services fee and still be able to obtain app packages ready for respective storesi have been through several appmobi tutorials faq and forum threads but those two points are not really clear to me anyway i must say i started to look at this just during the days appmobi was going through quite a change open sourcing freepaid online build etc so i have found some contrasting freshold information at the time i have also digged here on so but with no lucki understand that their pricing is actually not that exaggerated but at the moment i would like to try out the whole journey from development up to publishing on store i might go for paid services later oneditfor clarification here i am not considering googleapple marketplace subscription costs when i say free i am referring just to the appmobi side of thingsta,"['android', 'iphone']" +234339,fluidwidth google maps i have a 2 column layout for the website with the left fixedwidth column and a right fluidwidth google maps that fills the rest of the width not taken by the left column problem however i cannot seem to get google maps div idmap canvas to be fluid and take up the rest of the width did i set it up wrongly thankshtmldiv idmain container div idsidebardiv div idmap container div idmap canvasdiv divdivcssmain container width 100 height 500px float left clear both position relative zindex 1map container height 100 float left position relativesidebar width 270px float leftmap canvas height 100 minwidth 100px float left thisplay block position absolute zorder 10,['css'] +234369,volatile piggyback is this enough for visiblity this is about volatile piggybackpurpose i want to reach a lightweight vars visibilty consistency of a b c is not important i have a bunch of vars and i do not want to make them all volatileis this code threadsafeclass a public int a b c volatile int sync public void setup a 2 b 3 c 4 public void sync sync final static a a new athread0asetupendthread1for async logic with a ab acthread2for async logic with a ab ac,['java'] +234411,difference between ob clean and ob flush whats the difference between ob clean and ob flushalso whats the difference between ob end clean and ob end flush i know ob get clean and ob get flush both get the contents and end output buffering,['php'] +234450,how to tally wins and losses using sum and case i am using sql server 2008i am trying to tally the wins and losses for any given bike each time a user votes he casts a vote for one bike 1 and a vote against another bike 0 my vote table looks like thisvoteid bikeid vote1 100 12 101 03 100 04 101 15 102 16 100 07 102 08 101 1i want my results to look like this when i run a query for a specific bikewins losses5 6right now my results look like thiswins losses5 nullnull 6 my query looks like thisselect sumcase when vote 1 then 1 end as wins sumcase when vote 0 then 1 end as lossesfrom voteswhere bikeid 101group by votewhat do i need to do to get the results on one line,['sql'] +234469,basic mathematical operations in xaml is is possible to do basic mathematical operations like addition division etc in xamlfor example i want to set the height of a button to binding elementnamemwpathheight2,"['c#', '.net']" +234484,invalidoperationexception a twoway or onewaytosource binding cannot work on the readonly property i am using the mvvm pattern and am receiving the following when i run my appinvalidoperationexceptiona twoway or onewaytosource binding cannot work on the readonly property options of type viewmodelsynergyviewmodeli have commented all my source out in my view model and have traced this back to a check box if i comment out the the checkbox or the properity in my view model the app runs minus the functionality below i have listed the code for my checkbox and the property within the viewmodelcheckbox gridcolumn4 horizontalalignmentright margin5055 ischeckedbinding options contentoptionsprivate bool optionspublic bool options get return options private set if options value return options value onpropertychangedoptions systeminvalidoperationexception occurred messagea twoway or onewaytosource binding cannot work on the readonly property options of type viewmodelmyviewmodel sourcepresentationframework stacktrace at msinternaldatapropertypathworkercheckreadonlyobject item object info innerexception any ideas on what i am what i am missing here,['c#'] +234495,firephp suddenly stopped working my firephp modules seems to have stopped working instead i get this error messagethere was a problem wriephpfirebugconsole01typeerror node is undefinedbreak on this error filtered chrome url chromefirebugcontentlibdomplatejsdomplatejs line 515systemi suspect it is related to using firephp for chrome but i have removed that with no joy,['php'] +234522,selecting first anchor inside li element with jquery my html looks like this li classlitopa classtop sub hrefblaha liwhat i am trying to do is to select the anchor tag so i can change the color of the text blah but heres the catch i am using closest because i am starting from a descendant of that li tag thisclosestlilitophow do i get that anchor tag from this starting point i tried next each children etc i cannot get it thanks,"['javascript', 'jquery', 'html', 'css']" +234528,jquery detecting the operating system and operating system version i have been writing a userscript for the past few months for my company and have just designed the main site for it with installation instructions our employees are based all around the world and very few have heard of userscripts let alone used them so this frontend is meant to cut down the time i spend supporting the scriptwhat i would like to do is on the installation page detect which browser and os os version they are using so that i can highlight the most relevant instructions slightly darker than the rest or simply not thisplay irrelevant sectionsfor example for ie6 you must use trixie i believe to install userscripts and this is supported on win xp only ie7 is supported on win xp ie8 is supported on win xp win 7 and ie9 is supported on win 7 only for ie7 8 9 i am advising to use iepro the difference between trixie iepro is that trixie requires a file extension of userjs which must be saved in cprogram filesbhelpuri iepro on the other hand requires the extension to be ieuser and saves to a different location for ie specifically i would like to detect the version and thisplay only the correct link either userjs or ieuser depending on what plugin they should be using for their current browser so that they are taken to the correct version of the file for that browser with the correct save path for that os os version is this making any sense so farbasically my question is does anyone know of a way to detect the operating system version i am currently using but that does not give the os version only the os i have tried looping through all of the variables stored in the navigator object with no success any help would be greatly appreciatededit thanks to nates answer i have put the exact code at i hope this helps someone in the future,"['javascript', 'jquery']" +234532,how to retrieve a twitter users name using twitter 4j i am new to android development and java in general i am building an application that requires a user to signup by loggingin to their twitter account from where their basic information is imported and saved the information required would be birthday name full names username location sex etci am using twitter4j to accomplish this i have tried looking at the twitter4j documentation but being an android newbie and java in general the documentation is a little bit hard to understand so i seem to be unable to get it to do something other than set a status updatethis is the code in my activitypackage colocalsquareappimport androidcontentintentimport androidneturiimport androidosbundleimport androidwidgettoastimport oauthsignpostoauthproviderimport oauthsignpostbasicdefaultoauthproviderimport oauthsignpostcommonshttpcommonshttpoauthconsumerimport oauthsignpostexceptionoauthcommunicationexceptionimport oauthsignpostexceptionoauthexpectationfailedexceptionimport oauthsignpostexceptionoauthmessagesignerexceptionimport oauthsignpostexceptionoauthnotauthorizedexceptionimport twitter4jtwitterimport twitter4jtwitterfactoryimport twitter4jhttpaccesstokenpublic class connecttwitteractivity extends baseactivity public final static string consumer key valid key public final static string consumer secret valid secret public final static string callback url localsquareconnecttwitteractivity2 private commonshttpoauthconsumer commonhttpoauthconsumer private oauthprovider authprovider private twitter twitter called when the activity is first created override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutconnect twitter commonhttpoauthconsumer new commonshttpoauthconsumerconsumer key consumer secret authprovider new defaultoauthprovider token token try string oauthurl authproviderretrieverequesttokencommonhttpoauthconsumer callback url thisstartactivitynew intentintentaction view uriparseoauthurl catch oauthmessagesignerexception e toastmaketextthis egetmessage toastlength longshow eprintstacktrace catch oauthnotauthorizedexception e toastmaketextthis egetmessage toastlength longshow eprintstacktrace catch oauthexpectationfailedexception e toastmaketextthis egetmessage toastlength longshow eprintstacktrace catch oauthcommunicationexception e toastmaketextthis egetmessage toastlength longshow eprintstacktrace protected void onnewintentintent intent superonnewintentintent uri uri intentgetdata if uri null uritostringstartswithcallback url string verifier urigetqueryparameteroauthsignpostoauthoauth verifier try authproviderretrieveaccesstokencommonhttpoauthconsumer verifier accesstoken accesstoken new accesstokencommonhttpoauthconsumergettoken commonhttpoauthconsumergettokensecret twitter new twitterfactorygetinstance twittersetoauthconsumerconsumer key consumer secret twittersetoauthaccesstokenaccesstoken alternate way twitter new twitterfactorygetoauthauthorizedinstanceconsumer key consumer secret new accesstokencommonhttpoauthconsumergettoken commonhttpoauthconsumergettokensecret tweet message to be updated string tweet hi there this was sent from my application oauth twitter twitterupdatestatustweet catch exception e toastmaketextgetbasecontext egetmessage toastlength long how exactly can i solve my problem,['android'] +234537,how with is better than trycatch to open a file in python i got that the with statement help you to turn thistry f openmy file do stuff that failsexcept passfinally fcloseintowith openmy file as f do stuff that failsbut how is that better you still got to handle the case with the file not being able to be opened like prompting the user to tell him he does not have permissions so in reality youd havetry with openmy file as f do stuff that failsexcept ioerror oserror failure as e do stuff when it doesnt workwhich is equivalent totry f openmy file do stuff that failsexcept ioerror oserror faillure as e do stuff when it doesnt workfinally fcloseyes you gained two lines but you added a level of nesting wich does not make it easier to read is the purpose of the with statement to save you two lines or am i missing something it seems a lot to add a keyword just for that so i feel like there is some syntaxe to handle the additional tryexcept that i do not know about,['python'] +234545,what inspired rubys begin end comment block syntax i know that a lot of ruby was inspired by perl eg stdin as a global constant or unix shell eg the end heredoc syntax but i do not know where the block comment syntax comes from the syntaxbeginthis is a comment lineit explains that the next line of code thisplays a welcome messageendwhere does this come from my knowledge of perl is sketchy is it perl,['ruby'] +234551,inplace run length decoding given a run length encoded string say a3b1c2d1e1 decode the string inplacethe answer for the encoded string is abccde assume that the encoded array is large enough to accommodate the decoded string ie you may assume that the array size maxlengthencodedstirnglengthdecodedstring this does not seem trivial since merely decoding a3 as a will lead to overwriting b of the original stringalso one cannot assume that the decoded string is always larger than the encoded stringeg encoded string a1b1 decoded string is ab any thoughtsand it will always be a letterdigit pair ie you will not be asked to converted 0515 to 05,['c'] +234557,mysql python like wildcard i want to do a python mysql query such ascursor connectioncursorsql select text from steps where text like startcursorexecutesqlbut the is not seen as a wildcard it is expecting a variable i guess i get an errortypeerror not enough arguments for format stringnothing seems to work it would also be nice if i could use a variable instead of start,"['python', 'mysql']" +234566,jquery drop down hover menu i am new to jquery i was hoping you guys could help me i am trying to make a hover dropdown menu but it is extremely buggy can you help me clean up my javascript look at my code pleaseit does not work on jsdoit for whatever reason but it works in komodo edittry out the code yourself if you really want to the problem is mainly the javascript can you help me make it so that when the user hovers over imgmenu class ulfile menu drops down and then if i wanted i could hover over something in ul and it would drop out horizantally not verticallythanks for helping i appreciate itshould i just give up and make it work in css,"['javascript', 'jquery']" +234567,mysql order by a function of two columns i have two integer fields a and b in table t i want to do something like select from t order by fab descwhere fab is a linear combination of a and b ie fab ma nb where m and and are numberswhat is the right syntax,"['php', 'python', 'mysql', 'sql']" +234597,parameter name omitted c vs c in c i tend to omit the parameters name under some circumstances but in c i got an error when i omitted the parameters namehere is the codevoid fooint forwarddecl it is ok to omit the parameters name in both c and cint main foo0 return 0void fooint definition in c it cannot compile with gcc printfin foonvoid fooint definition in c it can compile with g cout in foo endlwhy is that cannot i omit the parameters name in c function definition,"['c++', 'c']" +234626,simple sorting by number script 3 lines does not sort last few lis correctly why the listelements are sorted accordingly by the number in their span why is it that the last few numbers are out of order i am confusedjqueryfunction sortemab return parseintspan atext parseintspan btext 1 1lisortsortemprependtoultesthtmlul idtest li cups span12span li li plates span18span li li forks span03span li li knives span08span li li bowls span55span liul,"['javascript', 'jquery']" +234629,how to control json encode behavior is there any way to control json encode behavior on objects like excluding empty arrays null fields and so oni mean something like when using serialize where you can implement magic sleep method and specify what properties should be serializedclass myclass public yes i should be encodedserialized public empty array do not encode me public null null do not encode me public function sleep return arrayyes obj new myclassvar dumpjson encodeobj,['php'] +234641,can a python generator be easily saved and reloaded from thisk is there a way to serialize a generator current state and all local variables etc so that you can load the string containing the serialized generator later and be able to pick up right from where the last yield statement exited the function if yes and you know of a web page with a code sample please share a link to it,['python'] +234650,c using others code ive downloaded a c interval tree collection class class from here right hand side downloadhowever i cannot open the whole project on my microsoft visual c 2010 express that also runs c xna becausesolution folders are not supported in this version of the applicationalso i just want the class to use separately in my own seprate projecti tried to copy the three important seeming files intervalcs intervalnodecs and intervaltreecs into my project but this generated the compile errorthere are no importers which handle this file typei have also tried to copy and paste the contents of the three files into my project encapsulating them into there own namespace as well as there was a lot of code i had to rearange some of the usings a little but have run into the problem that possibly it wants powercollections dll and pcb files as using wintellectpowercollections causesthe type or namespace name wintellect could not be found are you missing a using directive or an assembly referencei am not sure how to continue or if i am doing the right thing at all in how to get this class to work,['c#'] +234652,dealing with massive graphs traveling salesperson i am teaching myself how to program algorithms involving tsps djikstra kruskal and i am looking for some start up advice i am working with c and sql ideally i would like to be able to do this strictly in sql however i am not sure if that is possible i assume the runtime would be awful after 50 vertices so i guess the question is can i do this is only sql and if so what is the best approach if not and i have to get c involved what would be the best approach there,"['c#', 'sql']" +234679,screenshot from background service of another application programmatically when i use the browser i want to save screenshots of the site that i visited because some pages thisappear in the future so i decided to do a background service that would make the screenshots at regular intervals of time when i visit the site say wsitecom who can give me any tips links to tutorials examples ps my phone is rooted android 21 and do not say that it is impossible updatescreenshots in jpg format or html without a difference the method which is easier to make,['android'] +234727,efficient way to reduce a vectors magnitude by a specific length lets say i have an arbitrary vector a what is the most efficient way to reducing that vectors magnitude by arbitrary amountmy current method is as followsvector shortenlengthvector a float reductionlength vector b a bnormalize b reductionlength return a bis there a more efficent way to do this possibly removing the square root required to normalize b,['c++'] +234737,popupwindow badtokenexception unable to add window token null is not valid i have the following error when showing a popupwindowthe errors are triggered by the linecheckinpopupshowatlocationviewgroup mapviewgetparent gravitycenter horizontal 0 0mapview is a mapview and nothing is null the stacktrace0108 1809402 eandroidruntime27768 caused by androidviewwindowmanagerbadtokenexception unable to add window token null is not valid is your activity running0108 1809402 eandroidruntime27768 at androidviewviewrootimplsetviewviewrootimpljava5130108 1809402 eandroidruntime27768 at androidviewwindowmanagerimpladdviewwindowmanagerimpljava3010108 1809402 eandroidruntime27768 at androidviewwindowmanagerimpladdviewwindowmanagerimpljava2150108 1809402 eandroidruntime27768 at androidviewwindowmanagerimplcompatmodewrapperaddviewwindowmanagerimpljava1400108 1809402 eandroidruntime27768 at androidviewwindowlocalwindowmanageraddviewwindowjava5370108 1809402 eandroidruntime27768 at androidwidgetpopupwindowinvokepopuppopupwindowjava9880108 1809402 eandroidruntime27768 at androidwidgetpopupwindowshowatlocationpopupwindowjava8450108 1809402 eandroidruntime27768 at androidwidgetpopupwindowshowatlocationpopupwindowjava8090108 1809402 eandroidruntime27768 at comgeolocactivitycheckinoncreateactivitycheckinjava500108 1809402 eandroidruntime27768 at androidappactivityperformcreateactivityjava44650108 1809402 eandroidruntime27768 at androidappinstrumentationcallactivityoncreateinstrumentationjava1049this is the code from my activity that extends mapactivity protected void oncreatebundle icicle superoncreateicicle setcontentviewrlayoutcheckin mapview mapview findviewbyidridmapview layoutinflater inflater layoutinflater getsystemservicecontextlayout inflater service checkinpopup new popupwindowinflaterinflatecheck in popup layout null false checkinpopupsetoutsidetouchabletrue checkinpopupsetheight100 checkinpopupsetwidth200 checkinpopupshowatlocationviewgroup mapviewgetparent gravitycenter horizontal 0 0thank you for sharing your thoughts,['android'] +234749,what are the alternatives for a multidatabase library for cc i want to write an application which should be able to connect to multiple databases this will be configured by parameters at startup the application will have different queries for each database engine this is not a problemthe problem is that i want to be able to connect to different database engines java has jdbc perl has dbi what does c havewhats more i do not want to use database drivers with too strict licences commercial ones gpl could be but i would like to avoid that,"['c++', 'c']" +234760,continue playing audio from html5 player when in ios background mode we built our musicoriented app in html5 and javascript with sencha touch for thistribution we wrapped it in xcode with uiwebview everything runs fine except one thing that does not work audio playing in multitask modei know the general idea add the uibackgroundmodes in infoplistdone now we can play the audio even in background modeuntil we reach the end of the song to start the next song we have to bring the app to foreground again or we can hit the play or next song button on the iphone audio controllerafter some research i found a promising workaround at entering background on ios4 to play audio where the workaround is to edit avaudiosessioncategoryplayback and work with the uibackgroundtaskidentifierthe problem for me is just like in any other fix i found so far that those solutions always assume that the audio is played either with avaudioplayer or mpmusicplayercontroller but in my case i user neither our audio is played by our html5 player wrapped in uiwebview anyone has any advice on how to continue playing the audio in ios multitask mode when the audio player is a html5javascript player,['ios'] +234771,how dangerous is it in javascript really to assume undefined is not overwritten every time anyone mentions testing against undefined it is pointed out that undefined is not a keyword so it could be set to hello so you should use typeof x undefined instead this seems ridiculous to me nobody would ever do that and if they did it would be reason enough to never use any code they wrote righti found one example of someone who accidentally set undefined to null and this was given as a reason to avoid assuming that undefined is not overwritten but if they would done that the bug would have gone undetected and i fail to see how that is betterin c everyone is well aware that it is legal to say define true false but nobody ever advises you avoid true and use 0 0 instead you just assume that nobody would ever be a big enough jerk to do that and if they do never trust their code againhas this ever actually bitten somebody where someone else assigned to undefined on purpose and it broke your code or is this more of a hypothetical threat i am willing to take my chances to make my code marginally more readable is this a really bad ideato reiterate i am not asking for how to protect against reassigned undefined i have seen those tricks written 100 times already i am asking how dangerous it is to not use those tricks,['javascript'] +234777,pango attributes with pygobject i have the following code that uses pygtkattr pangoattrlistattrchangepangoattrsize 50 window height 100 10 0 1attrchangepangoattrfamilysans 0 1attrchangepangoattrweightpangoweight bold 0 1attrchangepangoattrforeground65535 65535 65535 0 1selflabelset attributesattri am trying to port it to pygobject but there is no class pangoattrfamily neither pangoattrweight neither pangoattrforeground and i can not instantiate a pangoattrsizethe question is how to use pango attr size new pango attr weight new pango attr family new and pango attr foreground new through instrospectioni know i could use markup to do this but 1 using attributes would keep things simpler and 2 i want to know what is happening here i have already spent a lot of time trying to solve it,['python'] +234854,read devinputevent in android via java programming language i want to record all the input events done across the android phone save it in some file and later use that file to see what user input has happened at what time afaik i should invokedevinputevent to get the input events please guide me so as to how can i do the same via an android activity,['android'] +234889,adding custom font to theme in android is there any way to add custom fonts in themes in android i have read quick tip customize android fonts but here we have to programmetrically add custom font to texttextview txt textview findviewbyidridcustom font typeface font typefacecreatefromassetgetassets chantelli antiquattf txtsettypefacefont but i want to set the custom font by styletheme,['android'] +234909,rethis mongo or hazelcast we have a java web app which uses postgressingle database with a slave for storing all the important data we are now moving from a single server setup to mutiple servers due to which i need to make some changes to address the new requirements1 non sticky session ids for load balancing and partition tolerance2 cache of frequently read data accessible from all web servers in memorymemcache alternative3 queuesemail sms tasks to executed over the cluster typically all of them have to be executed over an xml api or screen scrapingavoiding duplicate processing of tasks is important but sometimes it can happen 4 persistent storage of api requests and responseslots of xml lots of rows but small number of columns probably archive by removing old requests and responses to keep the data set small5 logging to a common place the table will keep on growing also i would need a tool to access logs of production without stopping them some sort of search should be possible based on time and or search stringi want a single solution to address all these requirements and looking at rethis mongo and hazelcastin order of my personal preference as possible alternativesother important considerations1 less intrusion into our code2 easy backupreplication strategies at least master slave3 manageability community and tried and testedrunning in productionwhich will be able to perform all or most out of this features and requirementsedit what i didrethis backed session manager for tomactrethis for cachingjesque respues java version backed by rethispostgresslf4j backed by log4j2,['java'] +234920,listview with section header android is it possible in android listview headerbarsection not scroll untill the list of that section not scroll like as iphone tableview i used section listview but i want like this iphone tableview is it any possiblities for that thanks,['android'] +234954,typesafe setting of objects with a dictionary that has a type key i have a generic dictionary of objects where the key is of type typepublic class dynamicobject idictionarytype objectthe idea is that this object is shared in a pluginbased architecture and so a type which could reside in a plugin dll is used as a key in order to prevent clashes between plugins this type is also used to store metadata about the field such as a description of that field or the actual type of that fieldcurrently plugins need to set the value of fields on this object using code similar to thisdynamicobject someobjectstring somevaluesomeobjecttypeofusernamefield somevaluethe only problem with this is that this is not type safe even though the type usernamefield is aware of the exact type of the value it is expecting eg int or in this case string the value supplied here is just typed as an object i would like to use generics to make setting getting of properties type safe but i am not sure how so far the best i have come up with is this field is a base class for all types used as keys on dynamicobjectdescriptionusername of the userpublic class usernamefield field public static void setdynamicobject obj string value objtypeofusernamefield somevalue to set fieldsusernamefieldsetobj somevaluethis is type safe however it means that each of my field types eg usernamefield has a nearly identical static set methodhow can i have typesafe access to values in this way without having lots of nearly identical methods on each of my field typesas an aside is using type as a key like this a good idea or are there hidden pitfalls that i am not yet aware of,['c#'] +234997,image scaling with css i do not actually need it now but just out of curiositysuppose we have a fluid website layout that works perfectly well on 1920px thisplays and on small smartphones now let us say we have images there and obviously obviously we want to scale them weve uploaded 2560px images on a server because who cares about bandwidth nowadays and set width 100 property to the img tagso we have two users a programmer with a 1920px thisplay let us call him jo and a female student with a smartphone let us call her nancy because everything is better with nancy rightjo and nancy are happy because our plan with images scaling using width 100 works but what if we decided to show small images too something like 400px width nancy would not notice anything but for jo it would be a thisasterso the question is can we make jo and nancy happy without using javascript,['css'] +235013,how to detect if a qstring is made up of all numeric characters what do you guys think is the best way to tell if a qstring is made up of just numbersthere does not appear to be a convenience function in the qstring librarydo i have to iterate over every character one at a time or is there a more elegant way that i have not thought of,['c++'] +235016,multiple where clauses with linq extension methods i have a linq query that looks like the followingdatetime today datetimeutcnowvar results from order in contextorders where orderorderdate today today orderorderdate select orderi am trying to learn understand linq in some cases i need to add two additional where clauses in an effort to do this i am usingif useadditionalclauses results resultswhereo oorderstatus orderstatusopen now i am stuckas you can see i know how to add an additional where clause but how do i add multiple for instance i would like to add where oorderstatus orderstatusopen and ocustomerid customeridto my previous query how do i do this using extension methodsthank you,['c#'] +235037,how can i find the missing value more concisely the following code checks if x and y are thistinct values the variables x y z can only have values a b or c and if so sets z to the third characterif x a and y b or x b and y a z celif x b and y c or x c and y b z aelif x a and y c or x c and y a z bis is possible to do this in a more concise readable and efficient way,['python'] +235069,is a certain look and feel guaranteed to be available from what i have found out the nimbus look and feel was introduced in java 6 update 10i have project where i use that look and feelis there any situation where the user has a java vm newer than 6 update 10 for example 6 update 26 and the nimbus look and feel is not available this situation might occur if for example look and feels can be manuallyexplicitly removed but i have not been able to find out if this can be doneso basically is there a 100 guarantee that if the user has the proper java vm version the nimbus look and feel will be available 100 of the time thank you in advance,['java'] +235080,selenium and firefox 9s will you help improve mozilla firefox popup i am trying to test a java web app using selenium 2161 when selenium opens firefox i see a band at the top of the page with message will you help improve mozilla firefoxfor some reason this breaksseleniumclickidsubmitseleniumwaitforpagetoload60which is trying to log in it becomes a noop and the test fails because it is then expecting to have logged in if i break on the click line and clear the will you help band before continuing then the form submit succeedsis there a way to suppress this band from appearing i expect that would mean setting a property in firefoxs default profile where do i find that or is there a way to get selenium to spot and thismiss this first thanks i am using firefox 901solved thanks danny just in case it is not clear from the answers and comments belowthis was an issue with 2161 and imo the best solution is to upgrade to 217 or laterpeter points out below that this question is highly ranked for the will you help message itself if youre looking to thisable itfirefox 910 and please vote up peters answerfirefox 689 or earlier please vote up dannys answer,['java'] +235097,is it possible to create desktop applications with nodejs i have created an application using nodejs and i am interested to know if it is possible to pack the client side js html css and the server side into a standalone application that does not required browser,['javascript'] +235123,how to check whether a string contains small letter big letter special character and number i have been googling a lot and i did not find an answer for my questionhow can i check with a regular expression whether a string contains at least one of each of thesebig lettersmall letterdigitspecial characters so i need at least a big letter and at least a small letter and at least a digit and at least a special characteri am sure the answer is very simple but i cannot find it any help is greatly appreciatedbest regardslajos arpad,['java'] +235126,live bytes vs real memory in activity monitor on ios i am working on an ios app that will create a lot of small objects and floats and trying to get an idea for how much memory usage it is consumingwhen i run the allocations instrument it says i have about 2mb of live bytes and the figure stays roughly constant as i move through the app spikes up to 3mb or so when the app is busy but then drops back down to 2mbbut when i run the activity monitory instrument my apps real memory is 25mb once it finishes launching and grows rapidly whenever drawing occurs inside my calayer in less than a minute it goes over 100mbwhy would live bytes show 2mb but real memory shows 100mbmy calayer is drawing tons of paths it pegs the cpu at 100 for a few seconds just to finish a single draw operation and it is loading all of these points out of an nsdata object into cgpoint values then deallocing them again the nsdata object is a compressed version of the points being drawn storing deltas from one point to the next so i keep it in ram but do not keep the actual cgpointsit also caches the result of the drawing in a uiimage and these are kept in a firstinfirstout array that would not grow to more than about 500kb,"['objective-c', 'ios']" +235141,casting a result to float in method returning float changes result why does this code print false in net 4 it seems some unexpected behavior is being caused by the explicit casti would like an answer beyond floating point is inaccurate or do not do thatfloat afloat x float y return x y float bfloat x float y return float x y void main consolewriteline a 10f 1f10f b 10f 1f10f ps this code came from a unit test not release codepps the unit test was passing in net 35 but now fails after the upgrade to net 4,"['c#', '.net']" +235197,how can i avoid multiple asserts in this unit test this is my first attempt to do unit tests so please be patient with mei am still trying to unit test a library that converts lists of pocos to adorecordsetsright now i am trying to write a test that creates a listpoco converts it into a recordset using the method i want to test and then checks if they contain the same information like if pocofoo rsfoo and so onthis is the pocopublic class testpoco public string stringvalue get set public int int32value get set public bool boolvalue get set and this is the test so far i am using xunitnetfactpublic void thetest var input new listtestpoco inputaddnew testpoco boolvalue true int32value 1 stringvalue foo var actual inputtorecordset assertequalactualboolvalue true assertequalactualint32value 1 assertequalactualstringvalue foowhat i do not like about this are the three asserts at the end one per property of the pocoi have read lots of times that multiple asserts in one test are evil and i understand the reasons why and i agreethe problem is how can i get rid of themi have roy osheroves excellent book the art of unit testing right in front of me and he has an example which covers exactly this for those who have the book chapter 726 page 202203in his example the method under test returns an analyzedoutput object with several properties and he wants to assert all the properties to check if each one contains the expected valuethe solution in this casecreate another analyzedoutput instance fill it with the expected values and assert if it is equal to the one returned by the method under test and override equals to be able to do thisbut i think i cannot do this in my case because the method that i want to test returns an adodbrecordsetand in order to create another recordset with the expected values i would first need to create it completely from scratch this probably does not actually compile the actual conversion method does not exist yet and this is just to show the ideavar expected new adodbrecordsetclassexpectedfieldsappendboolvalue adodbdatatypeenumadbooleanexpectedfieldsappendint32value adodbdatatypeenumadintegerexpectedfieldsappendstringvalue adodbdatatypeenumadvarwcharexpectedaddnewexpectedboolvalue trueexpectedint32value 1expectedstringvalue fooexpectedupdatei do not like this either because this is basically a duplication of some of the code in the actual conversion method the method under test which is another thing to avoid in testssowhat can i do nowis this level of duplication still acceptable in this special situation or is there a better way how to test this,['c#'] +235215,rails 31 better way to expose an engines helper within the client app i have found a few articles addressing the issue of helpers within an engine not being accessible to the consuming parent application to make sure we are all on the same page let us say we have thismodule myengine module importanthelper def some important helper do something important end endendif you look at the rails engine documentation in the isolated engines helpers l293 it says sometimes you may want to isolate engine but use helpers that are defined for it if you want to share just a few specific helpers you can add them to applications helpers in applicationcontroller class applicationcontroller actioncontrollerbase helper myenginesharedenginehelper end if you want to include all of the engines helpers you can use helpers method on an engines instance class applicationcontroller actioncontrollerbase helper myengineenginehelpers endso if i ask anybody consuming my engine to add this to their application controllerrb then they will get access to all my important helper methodsclass applicationcontroller actioncontrollerbase helper myengineimportanthelperendthis is what i want and it works but that is kind of a pain especially if as is my use case everything the engine exposes canshould be used anywhere in the consuming app so i dug around a bit more and found a solution that suggested i do the followingmodule myengine class engine railsengine isolate namespace myengine configto prepare do applicationcontrollerhelperimportanthelper end endendnow this is exactly what i want to add all my importanthelper method to the parent apps application helper however it does not work can anybody help me figure out why this morebetter solution does not worki am running ruby 187 with rails 313 let me know if i missed any important info germane to the issue and thanks in advance,['ruby-on-rails'] +235216,rearrange array keys php i have this arrayarray15 13116 mark one answer19 you see a car on the hard shoulder of a motorway with a help pennant thisplayed this means the driver is most likely to be20 a thisabled person first aid trained21 a foreign visitor22 a rescue patrol person25 des s15 hc r278how do i get it to sort the keys from 0to get this i know there is a function but my head is burned the sort function does not fit my needs since they rearrange values and i need them to be conserved array0 1311 mark one answer2 you see a car on the hard shoulder of a motorway with a help pennant thisplayed this means the driver is most likely to be3 a thisabled person first aid trained4 a foreign visitor5 a rescue patrol person6 des s15 hc r278,['php'] +235220,auto from const stdvector object or reference suppose we have an object with the following interfacestruct node t const stdvector something getchilds const nodenow i access the property with an auto variable like thisauto childs nodegetchildswhat is the type of childs a stdvector something or a reference to one,['c++'] +235236,html parsing of cricinfo scorecards aimi am looking to scrape 2020 cricket scorecard data from the cricinfo website ideally into csv form for data analysis in excelas an example the current australian big bash 2012 scorecards are available fromgame 1 last game background i am proficient in using vba either automating ie or using xmlhttp and then using regular expressions to scrape data from websites ie extract values from html td and trin that same question a comment was posted suggesting html parsing which i had not come accross before so i have taken a look at questions such as regex match open tags except xhtml selfcontained tagsquerywhile i could write a regex to parse the cricket data below i would like advice as to how i could efficiently retrieve these results with html parsingplease bear in mind that my preference is a repeatable csv format containingthe datename of the matchteam 1 name the output should dump up to 11 records for team 1 blank records where players have not batted ie did not batteam 2 name the output should dump up to 11 records for team 2 blank records where players have not battednirvana for me would be a solution that i could deploy using vba or vbscript so i could fully automate my analysis but i presume i will have to use a separate tool for the html parsesample site links and data to be extracted,['html'] +235261,in ckeditor how to copyget all formating from a selected text i am using ckeditor ver36 in my aspnet mvc 3 applicationmy requirement is to create paint format option in the google doci need to implement paint format option in a ckeditorin ckeditor how to copyget all formating such as font font effects centered paragraph alignment from a selected textsource to a newly selected text destinationplease suggest a proper solution,"['javascript', 'asp.net', 'css']" +235271,convert string text to bitmap is it possible to convert string text that is inside an edittext box into a bitmap in other words is there any way to convert string text into a bitmap that means the text will thisplay as an imagebelow is my codeclass texttoimage extends activity protected void oncreatebundle savedinstancestate create string object to be converted to image string sampletext sample text string filename image create a file object file newfile new file filename jpeg create the font you wish to use font font new fonttahoma fontplain 11 create the fontrendercontext object which helps us to measure the text fontrendercontext frc new fontrendercontextnull true true,['android'] +235316,stl map operator bad my code reviewers has pointed it out that the use of operator of the map is very bad and lead to errorsmapi new someclass potential dangling pointer when executed twiceorif mapinull implicitly create the entry i in the map although i understand the risk after reading the api that the insert is better of since it checks for duplicate thus can avoid the dangling pointer from happening i do not understand that if handled properly why can not be used at alli pick map as my internal container exactly because i want to use its quick and selfexplaining indexing capabilityi hope someone can either argue more with me or stand on my side,['c++'] +235325,using object types with jasmines tohavebeencalledwith method i have just started using jasmine so please forgive the newbie question but is it possible to test for object types when using tohavebeencalledwithexpectobjectmethodtohavebeencalledwithinstanceof stringi know i could this but it is checking the return value rather than the argumentexpectk instanceof namespaceklasstobetruthy,['javascript'] +235341,simulate a click on a tag in chrome i have a link a tagi am trying to click it using javascriptwhile click does well in ff en ie it fails in chromechrome says the object does not have the click methodtriggering the onclick or redirecting to the href would not do the jobany ideas on how to do thispreferably i wouldnt get an entire library just for this,"['javascript', 'html']" +235355,override django form fields name attr i have built a django form that submits to a page on another domain that i do not control the idea is that i have a nicely styled neatly generated form that fits neatly into my own site and takes the user elsewhere when it is submittedhoweverif that other form changes the names of any of its fields i need to change the names of the fields in my form and then change those names everywhere else in my application since the name attr is coupled to the name of the property used for the fieldif the remote form uses silly names then my form object must also have properties with silly names which pollutes my applications codeshould those names happen to be reserved words in python eg from then it is difficult or impossible to create a django form object representationis there a way to specify a different string to use for the name attribute when the field is thisplayed thus decoupling the html form from the class that represents itthis would need two componentsoverride the name value in the widgetmake the form read this value from requestpost when it is boundi only need step 1 in this case but step 2 is relevant to solve the problems i listed above more generally,['python'] +235389,checking whether a string starts with x i would like to know how to check whether a string starts with hello in pythonin bash i usually doif string hello then do something herefihow do i achieve the same in python,['python'] +235409,google chrome frame overlay works only once i have a page that prompts for a google chrome frame installation if the user uses an outdated browserit works great if the user chooses to install the plugin but if heshe choose not to install it and closed the layer it is impossible to open the layer again using the same button basically it works only onceis there any way i can force google chrome frame to open every time i click on install i have tried forcing a cookie but does not seem to workupdate 1test page heredoctype htmlhtml head script srcscript if ie script typetextjavascript srcscript endif head body a href classdngcfprompta script function if browsermsie browserversion 9 if navigatoruseragentindexofchromeframe 0 dngcfbindclick function documentcookie thisablegcfcheck0path cfinstallcheck url mode overlay destination else alertgcf is already installed else alertyou need ie 6 7 or 8 in order to see the bug script bodyhtmlupdate 2this seem to be a sessionrelated problemwhen i restart the browser the link works again once but does not however when i only refresh the pageconclusionthis behavior is by design it allows an admin to check for gcf on every single page without annoying the user with a prompt every time the accepted answer allows you to circumvent this behavior,"['javascript', 'jquery']" +235420,eclipse multiple projects with same name but different location i have two copies of the same directory structure basically trunk and a feature branch which both contain a java project call it projectx in a subdirectory of the respective base directoryi have painstakenly set up eclipse the way i want it to work with regards to settings colors etcnow i want to be able to switch between working in either trunkprojectx or featurebranchprojectx these are completely separate on thisk which is why i feel that the accepted answer to how to create multiple projects with same name in eclipse does not address my concern but since they share the name projectx on thisk eclipse does not seem to want to let me add them to the same workspaceworking sets do not help me because the projects are not yet in the same workspaceremoving and readding the projects very quickly becomes errorpronemaking a copy of the workspace directory and opening that seemed to lose quite a few of my settings colors servers etc why that is is another interesting question and as far as i could tell there was no easy way to tell which workspace i am actually working in right nowmy question what is the recommended way to deal with a situation like thisi guess i am hoping for some way to define an alias of some kind such that i can add trunkprojectx as trunkprojectx and featurebranchprojectx as fbprojectx then use working sets to switch between them,['java'] +235429,how do extension methods work underthehood a contractor where i work is using extension methods to implement crud on wellknown internal classes that we own i say it is better to use normal inheritance over extension methods for the following reasonsusing extension methods obfuscates hides confuses the source of the crud methodsi assume extension methods make heavy use of reflection which is slowerhis logic is it is compiled so it is fast maybe i am wrongbut just because it is compiled does not mean it does not use reflection nor does it mean it is faster than normal inheritanceso my questions arehow do extension methods work underthehoodis it better to use inheritance or extension methods on wellknown classes that you own,"['c#', 'asp.net']" +235445,python multiprocessing pickling error i am sorry that i cannot reproduce the error with a simpler example and my code is too complicated to post if i run the program in ipython shell instead of the regular python things work out well i looked up some previous notes on this problem they were all caused by using pool to call function defined within a class function but this is not the case for me exception in thread thread3traceback most recent call last file usrlib64python27threadingpy line 552 in bootstrap inner selfrun file usrlib64python27threadingpy line 505 in run self targetself args self kwargs file usrlib64python27multiprocessingpoolpy line 313 in handle tasks puttaskpicklingerror cannot pickle type function attribute lookup builtin function failedi would appreciate any help update the function i pickle is defined at the top level of the module though it calls a function that contains a nested function ie f calls g calls h which has a nested function i and i am calling poolapply asyncf f g h are all defined at the top level i tried simpler example with this pattern and it works though,['python'] +235501,c implementation of a class methods in a separated shared library i figure out i can have the implementation of parts of a class in a shared lib as far as the symbols are loaded when usedmyclasshclass c void methodmaincppinclude myclasshint main dynamically load mylibso using dlopendlsymdlclose c c new c cmethod delete cmylibso compiled separatelymylibcppinclude mylibhvoid cmethod this works finehowever once i finished using cmethod i would like to unload it so i can change recompile and reload it without having to restart the main programint main dynamically load mylibso using dlopendlsymdlclose c c new c cmethod delete c close the lib remove the handle char pause cin pause before carrying on change the cmethod recompile it dynamically load again mylibso using dlopendlsymdlclose c c new c cmethod delete c the problem is that it does not unload the library when doing the first dlclose probably because an instance of my class c existsany way to force thisusing g 423 on linux ubuntu 1004,['c++'] +235511,i am looking for a visually stunning graphingcharting api for the web i am currently working on a custom webbased survey platform for use in boardroom presentations wherein participants answer questions the responses from which are thisplayed as a graph usually from a projectori have been tasked with updating the existing graphing system which uses the urlbased google chart tools image charts api to create 3d pie and bar charts the primary requirement is that the new graphics be stunning some examples floated to me were apples glasslike reflective cover flow windowss aero ui and charts produced by the latest powerpointan example of what we can currently produce using the google chart tools image chart apievidently the 3d pie and bar charts produced by googles chart tools image charts are insufficiently stunning similarly the heavilyinteractive graphs produced by google visualization api are too boringso i am looking for a webbased graphing tool which is preferably accessible through an api which may respond to our requirement of being visually stunning something free would be nice too any ideasi did have a look at fusioncharts and it looks like a possible solution but it is not free and is not apibasedi have a question over at ux regarding the best way of graphing results from matrixranking questions related to the same project,['php'] +235523,jquery ui combining selectable with draggable as the question states i am trying to combine jquery uis selectable and draggable functions into a working dragndrop interface with the user being able to select multiple divs and move those divs into jquery droppables here is the code i have to allow the user to select divs across a row in a table trselectable filter div selected functionevent ui uiselecteddraggable containment document axis y snap true snapmode inner revert invalid opacity 08 drag functione ui uiselectedcss top uipositiontop yaxis only uiselectedaddclassuidraggabledragging stop function uiselectedremoveclassuiselected uidraggable as you can see i have tried adding the known classes that jquery ui adds to elements being draggedselectedetc but the only element that seems to act as an actual draggable is the one that the user has clicked on is actually draggingmy desire is to have the user drag the entire selected group and have them all act as draggables ie revert on invalid snap to droppable etcdoes anyone have any idea how to do this or where to go from here also here is a jsfiddle to demonstrate exactly what i mean and where i am currently at on this you might have to resize the results view so the table cells are all the same width,"['javascript', 'jquery']" +235525,nested parallelfor loops speed and performance i have a nested for loopi have replaced the first for with a parallelfor and the speed of calculation increasedmy question is about replacing the second for inside one with a parallelfor will it increase the speed or there is no difference or it will be sloweredit since the cores are not unlimited usually there is 2 to 8 cores the inside loop is running parallel so if i change the inside for with a parallelfor again it runs parallel but i am not sure how it changes the performance and speed,['c#'] +235561,html5 number input type that takes only integers i am using the jquery tools validator which implements html5 validations through jquery it is been working great so far except for one thing in the html5 specification the input type number can have both integers and floating point numbers this seems incredibly shortsighted since it will only be a useful validator when your database fields are signed floating point numbers for unsigned ints youll have to fall back to pattern validation and thus loose extra features like the up and down arrows for browsers that support it is there another input type or perhaps an attribute that would restrict the input to just unsigned integers i could not find any thankseditok guys i appreciate your time and help but i see many undeserved upvoting going on d setting the step to 1 is not the answer since it does not restrict the input you can still type a negative floating point number into the textbox also i am aware of pattern validation i mentioned it in my original post but that was not part of the question i wanted to know if html5 allowed restricting an input of type number to positive integer values to this question the answer it seems would be no it does not i did not want to use pattern validation because this causes some drawbacks when using jquery tools validation but it now seems that the specification does not allow for a cleaner way to do this,['jquery'] +235562,find memory leaks with windbg when lots of objects are present in gen2 i have got a memory problem in my net application where my app starts off consuming about 1gb in the gen2 heap after everything is initialized and loaded it slowly over time 45 hours ends up consuming 4gb in the gen2 heap i have used windbg to analyze things that i see that some of my object types and associated memory usage are increasing all of the objects that growing in instances and mem usage are referenced by the same parent object type this parent object type has about 3900 instances this never changes somehow i am adding child objects to some of these parent instances but i do not have a good way to see which of the 3900 instances are being added to dumpheap mt will show me all my parent types but the sizes are all the same because it does not count children objsize will count the size of the children too but will only take one object at a time for an argument or all objects of all types not just my parent type which is way too many objectslooking at the child objects and tracing them back to the parent is not helpful either because there are a couple million of these types and i do not see a way to do some kind of aggregate tracetools like clrprofiler and ants slow down my app too much ants less so to make the problem happen in any reasonable amount of timei have tried running my application with a small subset of data that it normally runs on in order to make debugging easier but i do not get memory issues here i think there are some edge cases in my entire data set that cause strange things but i do not know what those edge cases are in order to isolate them into a subset of my entire data sethave read widely on this and cannot see anyone suggesting what to do when are lots of objects in gen2 that are supposed to be there and a small amount of objects of the same type that keep increasingany tips would be most appreciated,"['c#', '.net']" +235583,trycatch syntactic sugar in java i am wondering if there is a way in java pure code not some eclipse thing to syntactic sugar up repetitive try catch code namely i have to wrap a bunch of functionspublic void foo try bla catch exception e systemoutprintlncaught exception eprintstacktrace public void bar try other bla catch exception e systemoutprintlncaught exception eprintstacktrace and so on i would like to writeexcepted public void foo blaexcepted public void bar other blai think sugar of this type was possible in python is it possible in java,['java'] +235607,how to use a global variable in gcc inline assembly i am trying to use inline assembly like this for a global variable but the compiler gives an error by saying undefined reference to saved sp asm volatile movq saved sp rspnt saved sp is declared as static long saved sp globally for a file that is what mistake am i doing here,['c'] +235611,how to transfer the data from my production db to my staging db in heroku i am trying to transfer the data from my production db to my staging db without successi am following herokus documentation on it these are the commands i have run heroku addonsadd pgbackups remote staging heroku addonsadd pgbackups remote production heroku pgbackupscapture remote production heroku pgbackupsrestore database heroku pgbackupsurl remote production remote stagingand this is the message i getusage heroku pgbackupsrestore database backup idbackup urlrestore a backup to a databaseif no database is specified defaults to database url and latest backupif database is specified but no backup id defaults to latest backupit seems i am spelling something wrong but i cannot figure it outi have also tried the same command using the name of the apps instead of the remote heroku pgbackupsrestore database heroku pgbackupsurl app myapp app myappstagingbut i get the same message with no actual transfer going on any help is deeply appreciated,"['ruby-on-rails', 'ruby']" +235631,how to get every possibile pattern of an array of letters possible duplicateare there any better methods to do permutation of string lets say i have the lettersa b c dand i want to get every single possible patterncombination of these letters in a string that is 4 letters longa ba ca dabaa acacad abbaand so onwhat loop or pattern can i use to list every combination possiblei am writing this in c but examples in c and javascript are welcome as wellmy current idea only increments one letter for each letter possible then shifts to the right once and repeats this does not cover patterns likeabba,"['c#', 'javascript']" +235656,can i thisplay an image created with phpgd without saving and without using external php with image header i am trying to create a way to show an image created with phpgd in an oop fashion in order to accomplish that i created a class that among other things creates an image something like thisphp class myclass public image function construct thisimage imagecreatetruecolor100100 bg imagecolorallocatethisimage100100100 imagefilledrectanglethisimage00100100bg myvar new myclassi tried to create a function within the class that would output the image something like thisfunction show echo img src imagejpegthisimage100 but it did not work i also triedfunction show echo img srcdataimagejpegbase64 imagejpegthisimage100 but this also did not work the idea was to simply call the function from the html like thisdiv idanyid php myvarshow divam i going all wrong on this is there a way to accomplish what i want i tried to think of a way to use the imgmycodephp but it does not work for me because the class has to be created before the page loads and the image appears half way through the pagethanks,['php'] +235691,alternative to iframe so i have been looking around and am a bit lost on this topic people have said that there is alternatives to iframes but i do not see any that fit the bill for what i am trying to do i essentially created a small game that uses videos and plays particular ones based on corret button input from the keyboard all of that is in a seperate html file and i want to thisplay it on a different html file to be in an iframe like state on a different webpage but i cannot seem to figure out the best approach to thisthe iframe is just too slow the game itself runs fine but when i put it in an iframe it lags like crazy half the time or stuff does not render because it is going so slowlyany ideas of where to start,['javascript'] +235707,thumbsdb file in resdrawablehdpi folder there is this file in my resdrawablehdpi folder called thumbsdb and it has an error on iti cannot compile my project because of this what exactly does this file do should i delete this file i mean is it safe thanks,['android'] +235764,receiver type for instance message is a forward declaration in my ios5 app i have nsobject states class and trying to init itstates states inithere is init method in states id init if self super init pickedglasses 0 return selfbut there is error in the line states states initreceiver type states for instance message is a forward declarationwhat does it mean what am i doing wrong,"['iphone', 'ios', 'objective-c']" +235791,versus nsstring string i am trying to work out the pros and cons of and nsstring string as they appear to behave in a similar fashion i guess i am hoping nsstring string returns a static value thus avoiding unnecessary string creation in memory can anyone shed some light as the documentation is inconclusive,['objective-c'] +235816,is it possible to access backing fields behind autoimplemented properties i know that i can use the verbose syntax for propertiesprivate string postalcodepublic string postalcode get return postalcode set postalcode value or i can use autoimplemented propertiespublic string postalcode get set can i somehow access the backing field that is behind the autoimplemented property in this example that would be postalcode edit my question is not about design but rather about let us say theoretical ability to do so,['c#'] +235818,java the import collides with another import statement i have imported an existing java application into my workspace i see that a class with same name is present in different packages with in the applicationfor example a class named statusjava is present with in comtatamodelcommonstatuscombayerfrontlayerdaostatuswhen i tried to use both of them within a class for example as shown below import comtatamodelcommonstatusimport combayerfrontlayerdaostatuspublic class adapterit started giving an error in eclipse stating the import combayerfrontlayerdaostatus collides with another import statementis there anyway to solve this without changing the name of the classesthank you,['java'] +235822,create a password protected excel file using apache poi i am developing a simple java program to create excel file using apache poi apii am using oracle 10g as a database and using ojdbc14 jari have a table called userinfo having 3 columns namely usernamepassword namenow using apache poi i have been able to put all the rows in excel file since file contain sensitive data such as username and password i want to make it password protectedon forums i have found how to read password protected files but not how to create themso how i can achieve thisthanks in advance,['java'] +235823,a loop with an empty body in java during bug fixing in very old project i have faced with strange method it looks like this void waiter for int i 0 i 20 i does it cause halting some time or it will be omitted by jvm optimization,['java'] +235844,save modified wordprocessingdocument to new file i am attempting to open a word document change some text and then save the changes to a new document i can get the first bit done using the code below but i cannot figure out how to save the changes to a new document specifying the path and file nameusing systemusing systemcollectionsgenericusing systemlinqusing systemtextusing systemdiagnosticsusing documentformatopenxmlpackagingusing systemionamespace wordtestclass program static void mainstring args string template cdatahellodocx string documenttext using wordprocessingdocument worddoc wordprocessingdocumentopentemplate true using streamreader reader new streamreaderworddocmaindocumentpartgetstream documenttext readerreadtoend documenttext documenttextreplacename paul documenttext documenttextreplacemake samsung using streamwriter writer new streamwriterworddocmaindocumentpartgetstreamfilemodecreate writerwritedocumenttext i am a complete beginner at this so forgive the basic question,['c#'] +235849,how do i connect to a specific wifi network in android programmatically i want to design an app which shows a list of wifi networks available and connect to whichever network is selected by the useri have implemented the part showing the scan results now i want to connect to a particular network selected by the user from the list of scan resultshow do i do this,['android'] +235851,strange behavior of java argument i wrote this class public class listarg public static void mainstring args forint i0iargslengthi systemoutprintlnargsi javac listargjava compiled classi compiled above class and run like java listarg but listarg is thisplaying current directory contents on console and not,['java'] +235862,tbbdll not found i am using cvcanny function in opencv 23 it compiles finebut while executing it gives an error saying tbbdll not foundwhat is the use of this dll and where can i find thisthanks,"['c++', 'c']" +235880,callback function pointers c withwithout classes i got stuck i am trying to form a function that will eat classless function pointers and ones from objects here is my current code that hopefully explains moreit should run on a arduino so i cannot use big librariesfirst off i am using this library for the arduino simpletimer a timer library for arduino author copyright c 2010 ottotecnica italy which takes functions which it calls on a set timer interval of this typetypedef void timer callbackvoidas far as my knowledge goes it is a classles function the webpage pointers to member functions got me really far but not far enough probably a terminology deficit on my sidenow i have made my own class which i would like in turn to use this simpletimer library but if i feed the simpletimer my class functions it does not like them what i understand but how would it be possible to make this happen without altering the simpletimer libraryso there is the class robot which has robothalt i want the robot to move forward for a set amount of time like sovoid robotforwardint speed long time reset timersettimertime c func 1 analogwritel a speed analogwriter a speed ismovingtruevoid robothalt ismoving false digitalwriter a low digitalwriter b low digitalwritel b low digitalwritel a lowthe c func variable is a classless function at this point but i would like to use the robothalt function i have looked read learned but have not succeeded yet i just cannot seem to wrap my head around this one because i am missing some anglei triedtimersettimertime thishalt 1timersettimertime robothalt 1timersettimertime robothalt 1but it would all amount to the same problem me just stabbing in the dark hereeditearlier i said not wanting to change the simpletimer library code i want to comeback on this one i guess altering it there would be the better optionthanks for all the current answers already i was only allowed to flag one as a viable answer actually everyhting i read here was extremely helpfulto continue this changing the simpletimer code this class needs to have a reference to the object that holds my halt function right so overloading the settimer function to something that takes my object and my function as two seperate pointers would work i think i am getting the hang of this but i am not there yet with my headediti do not know who came with this one again but anyone finding this thread if found member function pointers and the fastest possible c delegates to give a very nice introduction in function pointers and member function pointerseditgot it working changed the simpletimer library to use this delegate systemit integrated very nicely and it could be nice to have a standard delegate system like this in the arduino librarycode as in test workingtypedeftypedef fastdelegate0 funcdelegatecode in robot classvoid robottest funcdelegate f delegate f delegate makedelegatethis robothalt timersettimerdelg1 f delegate 1void robothalt serialprintlntestcode in simpletimer classint simpletimersettimerdelglong d funcdelegate f int n farduino prints test in the consolenext step putting it in an array do not see a lot of problems there thanks everyone i cannot believe the stuff i learned in two dayswhats that smell is that the smell of successfor the ones interested the used delegate system does not amount to memory capacity issueswith fastdelegateavr memory usagedevice atmega2560program 17178 bytes 66 fulltext data bootloaderdata 1292 bytes 158 fulldata bss noinitfinished building sizedummywithout fastdelegateavr memory usagedevice atmega2560program 17030 bytes 65 fulltext data bootloaderdata 1292 bytes 158 fulldata bss noinitfinished building sizedummy,['c++'] +235888,error when detaching sqlite database database is locked i have a system that is based on the sqlite database each client has a local database and once in a while the update arrives from the main server just a small delta db file the task is to merge to local database with the delta file the schema is identical in bothfor my database management i use fmdb wrapper that can be found here in the main thread i keep the connection to the local database open the delta file arrives in the background and i want to do the merge in the background to avoid any user interface freezes that this could causeas for the merge itself the only option that i found is to attach the delta database to the local database then insertupdate the rows and finally detach the delta this does not work as smooth as i expectedcode descriptionthe ondeltagenerated method is invoked in a background thread whenever delta database is ready to be processed arrives from the server and is saved in the readable locationthe deltadbpath is the absolute location of the delta database in the filesystemthe db variable references open fmdatabase connectioncode voidondeltageneratednsnotificationn nsstring deltadbpath n userinfo objectforkeydeltapathsynchronizeddb db executeupdateattach database as delta deltadbpath if db haderror nslog error d db lasterrorcode db lasterrormessage else nslogdelta attached from deltadbpath db begintransaction bool update1 no bool update2 no bool transaction no update1 db executeupdateinsert or replace into equipment select from deltaequipment if update1 nslog error update 1 failed nslog error d db lasterrorcode db lasterrormessage update2 db executeupdateinsert or replace into equipmentext select from deltaequipmentext if update2 nslog error update 2 failed nslog error d db lasterrorcode db lasterrormessage transaction db commit if transaction nslog error transaction failed nslog error d db lasterrorcode db lasterrormessage db executeupdatedetach database delta if db haderror nslog error d db lasterrorcode db lasterrormessage else nslogdelta detached after this method is invoked for the first time all seem to be fine until i try to detach the database when i try to do it i get the following error201201 120852106 dbapp141511507 error calling sqlite3 step 1 sql logic error or missing database sqlite error201201 120852107 dbapp141511507 db query detach delta201201 120852107 dbapp141511507 error 1 database delta is lockedi also tried to the same but without putting inserts into transaction the result is identical another thing was to remove the synchronized clause but also no luck my guess is that if fails when trying to access local database connection from the background thread but then how come it manages to attach and insert any help appreciatedediti moved the code to the main thread so the db is now accessed from the main thread only the problem remainsedit2ok so after trying everything i gave up on this for a moment and then came back when the first answer appeared here surprisingly everything seems to work fine now so my code must be correct i suspect this was the problem with different threads locking the file as i used xcode sqlitedatabasebrowser and my application to open the database even though the lsof showed that the file was not locked i think it was wrong and either xcode or sqlitedatabasebrowser was locking it i consider the problem solved and the lesson taken from this is not to thrust lsof so much and also plan the debugging better next time,['objective-c'] +235901,is it possible to change text color based on background color using css is it possible to change text color based on background color using csslike in the this image as the text crosses over from one div whitespacenowrap is it possible to change the text color using css or jqueryjavascriptthanks,"['javascript', 'jquery', 'css']" +235904,how to format numbers in velocity templates i am getting a java object in my velocity template the object has a double value which i want to format to 2 decimal places and thisplay it in my templatethe class for which im getting an object is something like thisclass pricedouble valuestring currencyin my velocity template im getting the value like thispricevaluebut i need to format it to 2 decimal places before thisplaying iti want to convert 2359004 to 2359357 to 357030 to 3009 to 900please tell me how can i do it in velocity template i searched a lot for this and found that i can use velocity tools but there are no examples related to it and can i use velocity tools in templates,['java'] +235914,why magic does an locking an instance of systemobject allow differently than locking a specific instance type i have been learning about locking on threads and i have not found an explanation for why creating a typical systemobject locking it and carrying out whatever actions are required during the lock provides the thread safety exampleobject obj new objectlock obj code hereat first i thought that it was just being used as a place holder in examples and meant to be swapped out with the type you are dealing with but i find examples such as dennis phillips points out does not appear to be anything different than actually using an instance of objectso taking an example of needing to update a private dictionary what does locking an instance of systemobject do to provide thread safety as opposed to actually locking the dictionary i know locking the dictionary in this case could case synchronization issueswhat if the dictionary was publicwhat if this was publicprivate dictionarystring string somedict new dictionarystring stringvar obj new objectlock obj do something with the dictionary,['c#'] +235925,android how to create my own activity and extend it i need to create a base class that extends activity which does some common tasks in my application and extend my activities from itin the following formpublic baseactivity extends activitypublic subactivity extends baseactivityin subactivity i need to give values to some variables and ui components defined in baseactivity i may need to define a different layout for subactivity according to some flag value alsoin subactivity i want to execute asynctask that is defined in baseactivityis this possible if yes is there any tutorial that may helpthank you in advance,['android'] +235928,why is access to the path denied i am having a problem where i am trying to delete my file but i get an exceptionif result success if fileuploadhasfile try filedeleterequestphysicalapplicationpath app settingslogin images txtuploadstatustext string filename pathgetfilenamebtnfileuploadfilename btnfileuploadsaveasrequestphysicalapplicationpath app settingslogin images filename catch exception ex messageextostring also i should note that the folder i am trying to delete from has full control to network servicesthe full exception message issystemunauthorizedaccessexception access to the path cusersgowdyndocumentsvisual studio 2008projectshybridhybridtemp loginimagesenviromentaljpg is denied at systemio errorwinioerrorint32 errorcode string maybefullpath at systemiofiledeletestring path at hybriduser controlsimgloader add edit tblbtnupdate clickobject sender eventargs e in cusersgowdyndocumentsvisual studio 2008projectshybridhybriduser controlsimgloader add edit tblascxcsline 242 any ideas,"['c#', 'asp.net']" +235951,is quicker to use array keys in a foreach statemnt or set a value variable that is never used suppose i want to iterate over an array and either i never look at the values or i am setting things in them so i only want the keys which is quicker set a variable each iteration which is unusedforeach array as key value arraykeyfoo bar call array keys before iteratingforeach array keysarray as key arraykeyfoo bar,['php'] +235959,plot line graph from histogram data in matplotlib i have a numpy array of ints representing time periods which i am currently plotting in a histogram to get a nice thistribution graph using the following codeaxhistdatabins100rangeminimummaximumfacecolorrhowever i am trying to modify this graph to represent the exact same data using a line instead of bars so i can overlay more samples to the same plot and have them be clear otherwise the bars overlap each other what i have tried so far is to collate the data array into an array of tuples containing time count and then plot it usingaxplotdata0data1colorredlw2however that is not giving me anything close as i cannot accurately simulate the bins option of the histogram in my plot is there a better way to do this,['python'] +235975,css dotted border render issue i am seeing a rendering issue for a 2px dotted border similar to css dotted border issue in adjacent columns in a table rendered as dash in chrome but on desktop safari and chrome i tried several widths and it happens in all of themthis is a samplethe vertical line ending has the same issue but it is out of the picturesample,['css'] +236000,objects lifespan in java vs net i was reading clr via c and it seems that in this example the object that was initially assigned to obj will be eligible for garbage collection after line 1 is executed not after line 2void foo object obj new object obj nullthat is because local variable lifespan defined not by scope in which it was defined but by last time you read itso my question is what about java i have written this program to check such behavior and it looks like object stays alive i do not think that it is possible for the jvm to limit variable lifetime while interpreting bytecode so i tried to run program with java xcomp to force method compilation but finalize is not called anyway looks like that is not true for java but i hope i can get a more accurate answer here also what about androids dalvik vmclass testprogram public static void mainstring args testprogram ref new testprogram systemgc override protected void finalize systemoutprintlnfinalized addedjeffrey richter gives code example in clr via c something like thispublic static void main string args var timer new timertimercallback null 0 10 call every second consolereadlinepublic static void timercallbackobject o consolewritelinecallback gccollecttimercallback called only once on ms net if projects target is release timer destroyed after gccollect call and called every second if target is debug variables lifespan increased because programmer can try to access object with debugger but on mono callback called every second no matter how you compile it looks like monos timer implementation stores reference to instance somewhere in thread pool ms implementation does not do this,"['c#', 'java', 'android', '.net']" +236054,how do you leave a team when a member of multiple teams on iphone developer program i am a member of multiple developer teams on my iphone developer account some of them are old contracting arrangements that are no longer relevant i have not been kicked off and i cannot find a way to leave how do you quit a team,['iphone'] +236055,is a string array subclass of an object array i think i am missing something basic here any explanation or pointers to previously asked questions will be very helpfulimport javautilarraysimport javautillistpublic class st public static void blaobject gaga gaga0 new date throws arraystoreexception systemoutprintlngaga0 public static void blalistobject gaga systemoutprintlngagaget0 public static void mainstring args string nana bla blanana works fine liststring bla1 arraysaslistargs blabla1 wont compile systemoutprintlnnew string0 instanceof object prints true systemoutprintlnnanagetclassgetsuperclassgetsimplename prints object so it seems like a liststring is not a subclass of a listobject but a string is a subclass of objectis this a valid assumption if so why if not whythanks,['java'] +236065,what is the difference between and in java i was looking over some mock ocjp questions i came across a really baffling syntax here it isclass oddstuff public static void mainstring args boolean b false systemoutprintlnb b false systemoutprintlnb b true why does the output change between and,['java'] +236067,width and height of an options menu is there a way to get the width and height of an options menu in dpi or any other measurement,['android'] +236081,how to convert hhmms to milliseconds i have a string 0130500 which is equivalent to 90500 milliseconds i tried using simpledateformat which give milliseconds including current date i just need that string representation to milliseconds do i have to write custom method which will split and calculate milliseconds or is there any other way to do this thanksi have tried as follows string startafter 01305 simpledateformat dateformat new simpledateformathhmms date date dateformatparsestartafter systemoutprintlndategettime,['java'] +236101,jquery mobile size is too small i am making an app on phonegap using jquery mobile the app runs fine on the pc browser and on the simulator but when i install it on my phone everything is very small on my home page i have a listview that is searchable and when i tap the textfield to search something the page adjusts to a more readable sizehow can i solve this i want it to be readable from the start,"['html', 'css']" +236113,event delegation vs direct binding when adding complex elements to a page i have some markup like this classes are just for explicationol idroot clasortable li header clashowaftercollapsetopline infoheader section classhideaftercollapse ol clasortableconnected li header clashowaftercollapsetopline infoheader section classhideaftercollapse divcontent adiv section li ol section li li header section classhideaftercollapse ol clasortableconnected li header section classhideaftercollapse divcontent bdiv section li ol section liolthat is nested sortable lists the sortable plugin suffices however since each li hereafter item maintains its level though the inner lists are connected the items have an alwaysvisible header and a section visible when in expanded state toggled by clicking the header the user can add and remove items from either level at will adding a toplevel item will include an empty nest list inside it my question is with respect to js initialization of the newly created item while they will share some common functionality which i can cover viarootonclick li header function thisparenttoggleclasscollapsedandlicollapsed section thisplay noneside question would this be an appropriate place to use the detailssummary html5 tags it seems sort of iffy about whether those will even make it into the final spec and i want a sliding transition so it seems like i would need js for that anyway but i throw the question to the masses hello massesif the root list is the only relevant element guaranteed to be in existence at page load for on to work effectively i have to bind all the events to that element and spell out the precise selector for each as i understand it so for example to tie separate functions to two buttons right next to each other i would have to spell out the selector in full each time a larootonchange li section buttonb1 function b1functiononchange li section buttonb2 function b2functionis that accurate that being the case does it make more sense to forgo on and bind my events at the time the new item is added to the page the total number of items will probably number in the dozens at most if that makes a difference in the response,"['javascript', 'jquery']" +236125,application with 2 launcher activities i have an application that contains two activities with intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilterin the manifest i did this so that there are 2 separate entries in the app drawer it functions properly with regards to the app drawer as it is my question comes during the install after you install an app with only one mainlauncher activity the last page has an open button that will launch the app that was just installed with my app this open button is greyed out i assume it is because it does not know which of the two activities i would want it to launch if the open button were pressed is there anything i can set in the manifestor elsewhere to specify which activity i would like the open button to launch at the end of the install process i am thinking there must be something i can set because when i install the app through adb with eclipse it launches one of the two activities and luckily it is actually the one that i would like it to launch,['android'] +236127,necessity of volatile array write while in synchronized block question concerning the jmm and the semantics concerning volatile fields that are written to in a synchronized block but read unsynchronizedin an initial version of the below code i was not synchronizing access since it was unnecessary for earlier requirements and abusing a self assignment thiscache thiscache ensured volatile write semantics certain requirements have changed necessitating synchronization to ensure that duplicate updates are not sent out the question i have is does the synchronization block preclude requiring the self assignment of the volatile field cache of byte data by row and column private volatile byte cache public byte getdataint row int col return cacherowcol public void updatedataint row int col byte data synchronizedcache if arraysequalsdatacacherowcol cacherowcol data volatile write the below line is intentional to ensure a volatile write is made to the array since access via getdata is unsynchronized thiscache thiscache notification code removed mentioning it since it is the reason for synchronizing without synchronization i believe that the self assignment volatile write is technically necessary although the ide flags it as having no effect with the synchronized block i think it is still necessary since the read is unsynchronized but i just want to confirm since it looks ridiculous in the code if it is not actually required i am not sure if there are any guarantees that i am unaware of between the end of a synchronized block and a volatile read,['java'] +236129,uiimageview vs uiview w image efficiency this is not really a question about addressing a specific problem but more a request to be pointed in the right directioni am making an app where i am loading several images saved as jpgs onto a screen at the same time and this has to be the way it is i cannot unload any of them because they are all being shown at oncei tried loading 30 images at about 800px600px resolution naively thinking that it only loads the compressed size of the pictures into memory this being about 200 kb so a total of 6 mb of course several memory warnings later i realised how stupid i was so i now resize them to about 400px300px each and my iphone 4s just about copes with the memory requirements i originally used a uiview where in the drawrect i drew a custom drawn image but changing over to using a uiimageview improved the situation dramatically the app is so much faster and responsive i also found that switching off rasterization in my layer made a huge difference in performancethese sorts of thiscoveries have taken me hours to work out and what i was wondering was if there are particular design patterns or resources that i can use to load my images to the screen as efficiently as possible mainly regarding using as little memory as possible are there are good rules of thumb why did using uiimageview vs uiview w image make such a differencewould be very grateful if someone could helpthanks,"['iphone', 'objective-c']" +236150,why is matlab so popular in the computer vision community even with opencv being so complete i have noticed that matlab is very popular among the computer vision and image processing community still to this day even though opencv is a very mature package for c i have never used matlab but looking at it i see no advantages over opencv in c it is so commonly used however that i am considering picking it upwhy is it so popular among this crowd what are its advantages over opencv,['c++'] +236159,jquery validation plugin adding rules that apply to multiple fields i am using the jquery validation plugini have several fields in a large form that i want to apply the same rules to i have simplified the code for this example this code does not work but i want to do something like this the second rule should apply to both first name and last name i want to encapsulate all the rules here in this function and not edit the class lists of some of the form elements to add a required class or whateveragain i have several different groups of form fields with different requirements that i want to group i only put required true in that element for simplicityaffiliate signupvalidate rules email required true email true first namelast name required true password required true minlength 4 thanks in advance,['jquery'] +236173,anyone experience caching issues with web apps ran in fullscreen mode iosmobile safari i am having a very strange issue with my web app which is ran in fullscreen mode from the home screen and mobile safari usually as i develop i edit the files with the changes that i want to make and then i relaunch the app from the homescreen as per ios design the web app will refresh and reload the sitehowever in some odd but frequent situations when i launch the application i get a cached older version of the app if i navigate to the app through mobile safari not from home screen then everything looks great i have added meta no cache tags all over the space and even attempted to thwart the cache by adding query strings to css files etc but for some odd reason when a cached version decides it wants to thisplay it will thisplay no matter what clearing cache and data from the settings menu and then relaunching will only sometimes fix the problemanyone else run into this issue if so how did you fix it is it a known ios bug i am thinking about adding some onload code to check if the application is running in full screen mode and then explicitly force a refreshplease help this is extremely annoying and frustratingrich,['ios'] +236180,why does arrayto s return brackets for an array when i typeputs array0 text yet when i typeputs array0to s textwhy the brackets and quotes what am i missingaddendum my code looks like thispage openurl f fread page array pagescanregex pulls partial urls into an arraypartial url page array0to sfull url base url partial url adds each partial url to a consistent base urlputs full urlwhat i am getting looks likequestions,['ruby'] +236210,c sign data with rsa using bouncycastle does anyone know of a simple tutorial or sample code of how to sign data in c using bouncy castle in java there are tons of tutorials and samples i cannot find a single example in c does anyone know how to do this,['c#'] +236224,does adding a block to objectsend pass it to the called method i just completed the ruby koans and neither the unit on calling methods using objectsend nor the ruby documentation on the method provides any information on using blocks with the send method will a block attached to the send method be passed to the method it calls or will the block be lostexamplefoosenda method baranother method,['ruby'] +236225,android how to read qr code in my application in my application i need to read qr code i searched the net and found zing codes however lots of developers had problem with using it and it seems it is buggyif i assume that my customers has qr reader installed on their device how can i use those applications and call them via implicit intents if user does not have any qr reader what will happen to the application if it crashes may i ask user to download for example qrdroid and after that use it,['android'] +236230,javascript documentation is there something like javadocs for javascript when i press ctrlspace in netbeans ide whilewriting javascript the javascript documentation comes out for the object specified but this documentation is i guess netbeans propertyif we write javascript in proper commented way netbeans builds docs for our custom javascript toocan we find any such javascript documentation outside netbeans so that we can refer to itthanks for answer,['javascript'] +236267,how can i highlight code with ace editor i would like to syntax highlight more than a dozen small snippets of code and then make them editable with ace editor by clicking on them since i think it would be much faster than setting up the full editor for each i see there is a simple command for setting up an ace editordiv ideditorsome textdivscript srcsrcacejs typetextjavascript charsetutf8scriptscriptwindowonload function var editor aceediteditorscriptis there a simple way to call into the api to just highlight the text without setting up the editor the ideal api would take in some text and return html with tags that could be used for highlighting i am aware there are specialized highlighting libraries for javascript but i would like to try using the same highlighter both for text that is being thisplayed and text that is being edited,['javascript'] +236272,operation is not valid due to the current state of the object error during postback i had an aspx page which was working well but suddenly i am getting the error operation is not valid due to the current state of the object whenever a postback is donethe stack trace isat systemwebhttpvaluecollectionthrowifmaxhttpcollectionkeysexceeded at systemwebhttpvaluecollectionfillfromencodedbytesbyte bytes encoding encoding at systemwebhttprequestfillinformcollectioncan someone help,['asp.net'] +236333,how to determine which points are inside of a polygon and which are not large number of points i have got a large set of data points 10 stored in a 2dimensional numpy array 1st column x coordinates 2nd column y coordinates i have also got several 1dimensional arrays storing additional information for each data point i would now like to create plots from subsets of these 1d arrays which include only the points which are in a given polygoni came up with the following solution which is neither elegant nor fastxy is the 2d arraya is one of the 1d arrayspoly is a matplotlibpatchespolygonmask nparrayboolpolyget pathcontains pointi for i in xymatplotlibpylabhistamask 100matplotlibpylabshowcould you please help me to improve this code i tried playing around with npvectorize instead of the list comprehension but could not manage to get it to work,['python'] +236372,how to ensure a method logic is executed only once per arguments combination i am designing a class library that have a bunch of method of kind ensurex the idea of this methods is to be called whenever a calling code requires something than can requires an initialization specific to the arguments it is similar the ensurechildcontrols method of aspnet but with arguments as thiscriminatorsex public static class someutilityclass public static void ensuresomethingstring arg1 int arg2 object arg3 logic should be called once for each args combination public class callerclass public void foo someutilityclassensuresomethingmycustomerid 4 mydatasomeproperty public void foo2 someutilityclassensuresomethingmycustomerid 4 mydatasomeproperty as such pattern will be reuse at several places and called very often i have to keep performance as a target i also have to have a threadsafe methodfor this purpose i wrote a small utility class public sealed class callhelper private static readonly hashsetint g yetcalled new hashsetint private static readonly object g syncroot new object public static void ensureoncetype type action a params object arguments algorithm for hashing adapted from int hash 17 hash hash 41 typegethashcode hash hash 41 agethashcode for int i 0 i argumentslength i hash hash 41 argumentsi 0gethashcode if g yetcalledcontainshash lock g syncroot if g yetcalledcontainshash a g yetcalledaddhash the consuming code looks like this public static class program static void main somemethod1 1 1 somemethod2 1 1 somemethod1 1 1 somemethod1 1 null consolereadline static void somemethodstring arg1 int arg2 object arg3 callhelperensureoncetypeofprogram consolewritelinesomemethod called only once for 0 1 and 2 arg1 arg2 arg3 arg1 arg2 arg3 the output is as expected somemethod called only once for 1 1 and 1somemethod called only once for 2 1 and 1somemethod called only once for 1 1 andi have some questions related to this approach i think i have properly locked the class to ensure thread safety but am i right is hashsetint and my method of computing the hash correct i am especially wondering if the null handling is correct and if i can hash an action delegate this waymy methods currently supports only static methods how can i move to a instance compatible method adding the instance as a thiscriminator without memory leakingis there any way to avoid passing all arguments manually to the utility method just specifying the action without exploring the stacktrace because of the performance impact i fear a lot of bugs introduced because of a missing arguments from the outermethodthanks in advance,['c#'] +236415,allow specific tag to override overflowhidden i have got a div that is a certain height and width and overflowhidden so that specfic inner images are clipped however i want one image in the div to pop out of the border ie to override the overflowhidden how do i do this,"['html', 'css']" +236416,an invalid floating point operation occurred sql server 2008 i have weird problem with this code if i run it like shown below i get erroran invalid floating point operation occurredbut if i change parameter longitude to 98508730 notice only last digit changed code works just fine the code is supposed to lists properties in milesradius around some latlng pointlatitude and longitude parameters are of the same type as longitude and latitude fields in table addresswhat can i do here thanksdeclare latitude decimal 106declare longitude decimal 106declare milesradius intset latitude 29607654set longitude 98508731set milesradius 5select adrlineone as address adrcity as city adrlatitude as latitude adrlongitude as longitude 3959 acoscosradianslatitude cosradiansadrlatitude cosradiansadrlongitude radianslongitude sinradianslatitude sinradiansadrlatitude as thistancefrom sharedaddress adrwhere adrlatitude is not null and adrlongitude is not null and 3959 acoscosradianslatitude cosradiansadrlatitude cosradiansadrlongitude radianslongitude sinradianslatitude sinradiansadrlatitude milesradius order by thistance,['sql'] +236418,how do i get large images in my tumblr custom theme in tumblr the maximum image size is 500px i want to know how to get larger images in my custom theme,"['html', 'css']" +236431,android honeycomb datepicker text color i am searching for a possibilitie to adjust the text color of the datepicker widget in an android honeycomb app i knew that the widget inherent the global textcolor which is white in my case but i need a black textcolor for the datepicker as the background here is light greyanyone know how to fix this,['android'] +236435,php closure function appended to stdobject and chained possible duplicatecalling closure assigned to object property directly if i have a class like thisclass test function one thistwofunc since test is returned why can i not call func function two test object array testfunc function echo does this work return test new new testnewone expecting does this workso my question is when i call function two from function one function two returns the test variable which has a closure function of func attached to it why can i not call that as a chained methodediti just remembered that this can also be done by using thisfunc invoke for anyone that needs that,['php'] +236443,android load drawable programatically and resize it how can i load drawable from inputstream assets file system and resize it dynamically based on the screen resolution hdpi mdpi or ldpi the original image is in hdpi i only need resizing for mdpi and ldpidoes anyone know how android does dynamic resizing of the drawables in res,['android'] +236457,prepareforsegue is not called after performseguewithidentifier with popover style i have a universal app where i am sharing the same controller for a ipad and iphone storyboardi have put a uilongpressgesturerecognizer on a uitableview that when a cell is pressed on iphone it calls an action that perform a segueibactionshowdetailidsender uilongpressgesturerecognizer gesture uilongpressgesturerecognizersender if gesturestate uigesturerecognizerstatebegan cgpoint p gesture locationinviewselfthetableview nsindexpath indexpath selfthetableview indexpathforrowatpointp if indexpath nil self performseguewithidentifiersegue detail senderindexpath the segue is a detail view performed as a push the first thing you should notice is that the sender is an nsindexpath is the only way i found for passing the selected cell maybe there is a better solutioneverything works fine in a sense that the segue is performed and before the prepareforsegue is called toohowever it happens that on ipad i have changed the segue identifier to popovernow things are working in part the segue is performed but prepareforsegue is not called and therefore the destination view controller is not set up as it should bewhat am i doing wrong,['objective-c'] +236464,configure log4net for aspnet mvc3 project ok so i am understood how to configure the log4net in my application but now first i want to improve the configuration by differencing the level of the logs if the application it is a release or a debug how can i do this second if i had a folder in my project called log how can i set the configuration to not used the physical folder of my applicationfor example instead offile valuecphysicalpathlogloglog usedfile valuelogloglog orfile valuesome variablelogloglog,"['c#', 'asp.net']" +236474,c determine if class is comparable i am more or less java programmer so this might be a stupid question but i did not manage to find any simple solutioni have a class like this in ctemplateclass t class node and i need t to be comparable to have at least operators defined is there any simple way to do this or what is the best practice for this in java it would be something like thispublic class nodet extends comparable thanks for your help,['c++'] +236490,why does not this sql query return any results comparing floating point numbers i have this in a mysql tableid and bolag id are int lat and lngitude are doubleif i use the the lngitude column no results are returnedlngitude query select from location forslag wherelngitude 138461208however if i use the lat column it does return resultslat query select from location forslag wherelat 583902782what is the problem with the lngitude column,['mysql'] +236524,force dom redrawrefresh on chromemac every once in a while chrome will render perfectly valid htmlcss incorrectly or not at all digging in through the dom inspector is often enough to get it to realize the error of its ways and redraw correctly so it is provably the case that the markup is good this happens frequently and predictably enough in a project i am working on that i have put code in place to force a redraw in certain circumstancesthis works in most browseros combinations elstylecsstext webkittransformrotatez0deg eloffsetheight elstylecsstext webkittransformnoneas in tweak some unused css property then ask for some information that forces a redraw then untweak the property unfortunately the bright team behind chrome for the mac seem to have found a way to get that offsetheight without redrawing thus killing an otherwise useful hackthus far the best i have come up with to get the same effect on chromemac is this piece of ugliness elcssborder solid 1px transparent settimeoutfunction elcssborder solid 0px transparent 10as in actually force the element to jump a bit then chill a second and jump it back making it worse if you drop that timeout below 500ms to where it would be less noticeable it often would not have the desired effect since the browser would not get around to redrawing before it goes back to its original stateanybody care to offer a better version of this redrawrefresh hack preferably based on the first example above that works on chromemac,"['javascript', 'css']" +236534,how to enable python interactive mode in cygwin i like python in interactive mode when on linux however on cygwin the interactive mode does not start i do not see the prompt and whatever i enter does not result in anythingsolved i figured out the problem from the answers below i was using a windows installation of python and it needs i option to start in interactive mode,['python'] +236537,how to create a semitransparent instruction page in android i am new to android and trying to work on this problem for last 2 days but could find a solution any help will be highly appreciated how to create a semitransparent page for instruction as used by an app calorie counter in android market,['android'] +236599,adding a google 1 button in android app i was just wondering if there was anyway to add a google 1 button inside my android appi have seen a 1 on the android market so i would think there would be some way to do this,['android'] +236604,is there any reason not to use stdmake shared when constructing objects i cannot think of any situation wherestdshared ptrobject objnew objectfoo 1would be preferred toauto obj stdmake sharedobjectfoo 1the latter always results in better locality and reduces memory fragmentation is there any situation where you would prefer or be forced to use the first form except interfacing with code returning raw pointers,['c++'] +236640,how to resolve no known instance method for selector performselectorwithobjectafterdelay when migrating to arc the arc migration tool is refusing to accept this code prior to starting with migrationselfdelegate performselectorselectoroverlaythismissed withobjectself afterdelay0the delegate is forced to implement this method with a protocol and it should work fineprotocol overlaydelegate nsobject voidoverlaythismissedoverlayoverlayendinterface overlay uiimageview idoverlaydelegate delegateproperty nonatomic assign idoverlaydelegate delegatewhats wrong with arc why is it telling me that there is no known instance method for selector performselectorwithobjectafterdelay,['ios'] +236671,javascript asynchronous execution will a callback interrupt running code i was just hoping someone could clarify this for me if i have the following code running serverside with nodejs not in a browserconsolelogadbgetselect from table1 functionresultconsolelogbconsolelogcpresuming the database call is asynchronous i should get the resultacbbut if i were to add the following line to the bottom of my codewhile1then b would never execute am i right,['javascript'] +236684,is it possible to declare an 1bit variable in java my algorithm use a huge array of boolean and as i was taught it take 1 byte for each boolean variable is there anyway to declare a boolean array and reduce the memory usage because i am working on phone environmentedit my friend and i are thiscussing if bitset is slower than normal boolean array please clarify this the algorithm still needs performance as best demand,"['java', 'android']" +236686,unable to connect to ssl i have configured the openssl with wamp apache server but while i using gdata api i am getting following error fatal error uncaught exception zend http client adapter exception with message in czend 1 11 11libraryzendhttpclientadaptersocketphp on line 234 zend http client adapter exception unable to connect to sslaccountsgooglecom443 error 10060 a connection attempt failed because the connected party did not properly respond after a period of time or established connection failed because connected host has failed to respond in czend 1 11 11libraryzendhttpclientadaptersocketphp on line 234somebody help me on this,['php'] +236689,rails cache expire i have a rails application in that i am using simple rails cache my testing is as followsrailscachewritetempdatetodayexpires in 60secondsi can read it through railscachereadtemp and railscachefetchtemp the problem is it does not expire it will still be alive after 60 seconds can any one tell me what is missing herefyi i have declared in my developmentrb as follows configaction controllerperform caching trueconfigcache store memory storeis there anything i missed out i want to expires my cache,['ruby-on-rails'] +236695,when do i use minitestunittestcase versus minitestspec i have been learning tddbdd using minitest what i am trying to figure out is what parts of my code should be tested with minitestunittestcase and which parts should be tested using minitestspeci understand the difference between unit testing and integration testing what i cannot seem to grasp from examples across the web is whether or not a testcase and a spec are both unit tests or if a testcase is used for a unit test and a spec used for integration testingshould i keep my quick unit tests in minitestunittestcase classes and longer integration testing which more often describe features in minitestspec expectations does it even matter or is it a question of personal preference,['ruby'] +236710,how to give a href inside the button tag in html i need to open two links when a button is clicked in the html page i figured it as by calling onclick function and creating anchor tag using createelement in javascript but how to include another link is there a way to give a href in button tag,"['javascript', 'html']" +236727,drupal 7 new module install link do not show when i go to modules tab i cannot find new module install linkplease tell me how to view this new module install link in drupal7,['php'] +236768,are there any ruby orms which use cursors or smart fetch i am looking for a ruby orm to replace activerecord i have been looking at sequel and datamapper they look pretty good however none of them seems to do the basic not loading everything in memory when you do not need iti mean i have tried the following or equivalent on activerecord and sequel on table with lots of rows postseach p puts p both of them go crazy on memory they seem to load everything in memory rather than fetching stuff when needed i used the find in batches in activerecord but it is not an acceptable solutionactiverecord is not an acceptable solution because we had too many problems with itwhy should my code be aware of a paging mechanism i am happy to configure somewhere the size of the page but that is it with find in batches you need to do something likepostfind in batches batch batcheach p puts p but that should be transparentso is there somewhere a reliable ruby orm which does the fetch properlyupdateas sergio mentioned in rails 3 you can use find each which exactly what i want however as activerecord is not an option except if someone can really convince me to use it the questions arewhich orms support the equivalent of find eachhow to do itwhy do we need a find each while find should do it should not it,['ruby'] +236781,reactive throttle returning all items added within the timespan given an iobservablet is there a way to use throttle behaviour reset a timer when an item is added but have it return a collection of all the items added within that timebuffer provides a similar functionality it that it chunks the data up into ilistt on every time span or count but i need that time to reset each time an item is addedi have seen a similar question here does reactive extensions support rolling buffers but the answers do not seem ideal and it is a little old so i wondered if the release version of rxmain now supports this functionality out the box,['c#'] +236783,how can i implement an offline geocoder for a single city using osm data in android i am trying to develop an offline android map that makes use of osm map tiles of a particular zoom level for this purpose i used an open source library osmdroidnow i m looking into the possibility of creating an offline geocoding reverse geocoding for a single city that can be integrated with my applicationcan i use osm xml data for that purpose if so then can anyone suggestexplain how to use it to create sqlite db to be used wit my appi read here and also here about spatialitebut cannot quite understand its working and implementationthanks,['android'] +236795,thistinct union on select errors on ntext data type i am pretty useless at sql but i find myself having to write a stored procedure for a very simple keyphrase searchi am trying to do a simple select on name using like keyword then another select on description same keyword and joining union the 2 selects however i get the errorthe ntext data type cannot be selected as thistinct because it is not comparablei tried using union all but that returned duplicate rows in certain instances depending on the keywordphrasei also tried to work out using temp tables and selecting thistinct on that but that is where i got really confusedrulesi cannot change the data typei need the rows from select on the name to be above the rows from the select on the descriptioni can only use 1 stored procedure and cannot change the data adapter as i am plugging it into a system i have no control overfurther infotable columns the important 2 i am working with are name and descriptionproductid intname varchar255introduction varchar255description ntextmaterial ntextcolour varchar255active bitdimensions varchar255photo varchar255price decimal10 2thisplayorder intproductreference varchar255categoryid intfriendlyurl varchar10sqlselect productsproductid name introduction description active material colour dimensions photo price thisplayorder friendlyurl productreference categories products lookupcategoryidfrom products inner join categories products lookup on productsproductid categories products lookupproductidwhere active 1 and tproductname like keywordunionselect productsproductid name introduction description active material colour dimensions photo price thisplayorder friendlyurl productreference categories products lookupcategoryidfrom productsinner join categories products lookup on productsproductid categories products lookupproductidwhere active 1 and productsdescription like keywordany help getting out a table of thistinct rows would be really appreciated also explaining to me as a layman would be great,['sql'] +236799,error with facebook verification code using coldfusion i have a facebook application that was using a cfc i had found on riaforge to authenticate the userapp and allow permissions this one but it no longer works so i set about writing a version of facebooks php example as cfml but when i get to the point of retrieving the access token i get the following error back from facebookoauth facebook platform invalid code error validating verification codethere is no problem with the setup of the app in facebook as i have tested the php code provided by them with my details and it works fine please find below the php example and also where i have got to using cfphp app id your app idapp secret your app secretmy url your urlsession startcode requestcodeifemptycode sessionstate md5uniqidrand true csrf protection dialog url id app id redirect uri urlencodemy url state sessionstate echoscript toplocationhref dialog url script if requeststate sessionstate token url token client id app id redirect uri urlencodemy url client secret app secret code code response file get contentstoken url params null parse strresponse params graph url token paramsaccess token user json decodefile get contentsgraph url echohello username else echothe state does not match you may be a victim of csrf cfmlcfset appid app idcfset secret key secret keycfset app url app urlcfparam nameurlcode default0cfparam nameurlstate default0cfset code urlcodecfif code eq or code eq 0 cfset sessionstate hashcreateuuidmd5 cfset dialog url id appid redirect uri app url state sessionstate cf javascript typescript scripttoplocationhrefdialog urlcfifcfif sessionstate eq urlstate cfset token url tokenclient id appid redirect uri app url client secret secret key code code cfhttp urltoken url resultaccesstoken methodget cfdump varaccesstokencfif,['php'] +236823,is it possible to determineassert that if one virtual function gets overridden another one is overridden too i have an existing class that declares a virtual method and defines a default implementation now i want to overload that method with a differend parameter and also give a default implementation additionaly i want to enforce the constraint that if the first method got overridden by a subclass then the second overloaded virtual method must be overridden toois this even possible inside c if so is it possible at compile timeexample codeclass parama class paramb class basepublic virtual void methodparama a default behavior virtual void methodparamb b default behavior class derived public basepublic virutal void methodparama special behavior my goal is to detect classes of type derived and enforce them to implement their verison of methodparamb b,['c++'] +236831,which boost features overlap with c11 i put my c skills on the shelf several years ago and it seems now when i need them again the landscape has changedwe have got c11 now and my understanding is that it overlaps many boost featuresis there some summary where those overlaps lie which boost libraries going to become legacy recommendation of which c11 features to use instead of boost ones and which better not,['c++'] +236856,what is the state focused state for a button i would like a button background to remain a certain color after the button is clicked and change colors again when some other button is pressed i thought this was the state focused state but the only two states i seem to have for my button is pressed or not pressed do i understand the state focused state correctly or is my statelistdrawable see below wrongxml version10 encodingutf8selector xmlnsandroid item androidstate focusedtrue androidstate pressedfalseshape solid androidcolor00ff00 shapeitem item androidstate pressedtrueshape solid androidcolorff0 shapeitem itemshape solid androidcolor0ff shapeitemselector,['android'] +236857,deserialize json to anonymous object using jsonnet im using jsonnet do deserlaize an object but i cant get it to work with the current structure of the object that im usingmy object currently looks liks this i want to pass a list of objects id concurrent user fieldtype 190 value id system type fieldtype 191 value nullim getting the errorcannot deserialize json array into type f anonymoustype13systemstringsystemstringsystemstringwhat i need is something similar to example 2 a container object containing a list any help is appreciated thanksc codepublic void getpoints string inputfields httpcontextcurrentrequestinputfields var test new id stringempty fieldtype stringempty description stringempty var example new containerarray new id stringempty fieldtype stringempty description stringempty var fields jsonconvertdeserializeanonymoustypeinputfields example javascriptquoteonly inputlivechange keyup function var container quoteonlycontainer var containerobject var containerarray containerfindquoteonly inputeachfunction var fieldtype thisdatafieldtype var id thisdataid var currentobject id id fieldtype fieldtype switch fieldtype case 190 textbox currentobjectvalue thisval break case 191 select currentobjectvalue thisval break case 192 radio currentobjectvalue thispropchecked true 1 0 break case 193 checkbox currentobjectvalue thispropchecked true 1 0 break containerarraypushcurrentobject containerobjectcontainerarray containerarray ajax url sentineloperationsuigenerichandlerashx data functionname getpoints inputfields jsonstringifycontainerobject success function data,"['c#', 'asp.net']" +236862,how to make popup window in java hello guys i am currently developing java applicationi want to show new window that contains a text area and a button are there any idea,['java'] +236935,parse date string to some java object i am working in a project that reads files and processes data there i got to work with dates for example20120110 231326january 13 2012i found the package joda kinda interesting package but do not know if it is the easiest aroundi was able to parse the first example to a datetime object joda regex and string manipulation ex by replacing the space by and passing it to constructornew datetime20120110 231326replace i guess it worked but the problem is with the second format how can i use such an input to extract a an object preferably a joda object i sure can write a function to change the format to what joda supports but was wondering if there would be some other way even some native java library to do itif there are any thing better than joda out there please let me know it as wellthank you,['java'] +236990,eventdriven php framework i am wondering if there are any completely eventdrive frameworks out there for php which are based around dependency injection for decoupling i know there are some frameworks that make use of these patterns but in the end the entire lifecycle of the application is still predefined and linear in stylefor example most frameworks are built to receive process and return results from http requests an event drive framework would have handlers for that but also be able to be used for new purposes like background processing command line interaction or other nonstandard use cases,['php'] +236992,must i copy a block here i understand that you must copy blocks in order for them to stick around after a stack frame exits but how does that apply to stackallocated blocks used within a nested block as in the following code example dosomethingfunkythencallvoidint somevaluecallback nsoperationqueue currentqueue addoperationwithblock do some work here potentially nesting into further blocks callbackresult obviously the dosomethingfunkythencall stack frame will terminate before the callback is executed so it will have to be copied but will this happen automatically in the call to addoperationwithblock or do i have to do it manually,['objective-c'] +236995,problems encoding amazon flexible payments secret string in php i am trying to use amazon payment services and they require me to do something like thishere is the complete signature so you can see i added the signature methodstring to sign getnauthorizepaymentssandboxamazoncomncobrandeduiactionsstartsignaturemethodhmacsha256signatureversion2callerkeymy keycallerreferenceyourcallerreferencepaymentreasondonationpipelinenamesingleusereturnurlhttp3a2f2fyourwebsitecom2freturnhtmltransactionamount40and then i encrypt it like belowencoded string to sign urlencodebase64 encodehash hmacsha256 string to sign my secret keyi do that but then i get an error from them sayingcaller input exception the following inputs are either invalid or absentsignaturemethodany idea what might be going wrong herehere is the entire code for this the variables are assigned values abovephpstring to sign getauthorizepaymentssandboxamazoncomcobrandeduiactionsstartsignaturemethodhmacsha256signatureversion2callerkeyakiajenbysjcjx2idwdqcallerreferenceyourcallerreferencepaymentreasondonationpipelinenamesingleusereturnurlhttp3a2f2fproblemiocomtransactionamount40 encoded string to sign urlencodebase64 encodehash hmacsha256 string to sign my secret keyamazon request sandbox returnurlreturn urlpaymentreasonpayment reasoncallerreferenceyourcallerreferencecallerkeymy access key idtransactionamount40pipelinenamesingleusesignaturemethodhmacsha256signatureencoded string to signecho amazon request sandbox use this if you want to see the resulting request and paste it into the browserheaderlocation amazon request sandboxthanks,['php'] +237013,failed to find pdf header pdf not found i am trying to download pdf content from webservice endpoint which is coming as binary after decoding into base64 i am attaching the decoded file to webview in which failed to find pdf header error is thisplayingdoes anyone know how can i proceed to fix this error am i missing any step herethanks,"['iphone', 'objective-c', 'ios']" +237016,how do i run multiple rake tasks programmatically at once at the command line i can run multiple tasks like thisrake environment task1 task2 task3how can i do this programmatically i know that i can run one task like thisraketasktask1invoke,['ruby'] +237022,android countdowntimer skips last ontick code public class smh extends activity public void oncreatebundle b superoncreateb setcontentviewrlayoutmain textview tv textview findviewbyidridtv new countdowntimer10 20 public void onticklong m long sec m101 tvappendsec seconds remainn public void onfinish tvappenddone start output 10 seconds remain 8 seconds remain 6 seconds remain 4 seconds remain done problem how do i get it to show 2 seconds remain the time elapsed is indeed 10 seconds but the last ontick never happens if i change the second parameter from 20 to 10 then this is the output 10 seconds remain9 seconds remain8 seconds remain7 seconds remain6 seconds remain5 seconds remain4 seconds remain3 seconds remain2 seconds remaindone so you see it seems to be skipping that last ontick call and btw the xml file is basically the default mainxml with the textview assigned the id tv and the text set to,"['java', 'android']" +237031,asset pipeline not finding js file my railsapplicationconfigassetspaths contains the directory for an asset i would like autocomplete userskiranbapplicationappassetsimages userskiranbapplicationappassetsjavascripts userskiranbapplicationappassetsstylesheets userskiranbapplicationvendorassetsjavascripts userskiranbapplicationvendorassetsstylesheets userskiranbrvmgemsruby192p290applicationgemsrails3jqueryautocomplete105libassetsjavascripts userskiranbrvmgemsruby192p290applicationgemsjqueryrails1019vendorassetsjavascriptsthe libassetsjavascripts for the autocomplete gem containsautocompleterailsuncompressedjs autocompleterailsjsand my applicationjs includes require jquery require jquery ujs require jqueryui require autocompleterails require tree however i keep getting the errorcould not find file autocompleterails in userskiranbapplicationappassetsjavascriptsapplicationjs11it has no trouble finding any other assets though what am i doing wrong,['ruby-on-rails'] +237038,casting between two types derived from the same interface i have an interface and two types that derive from ithowever i cannot do the followingb objectb b objectawhere b derives from interface1 i am making up the name of classes but the point still stands and likewise for objecta which is of type a i get the following error messagecannot cast expression of type a to b both types are deriving from the interface what am i missing,"['c#', '.net']" +237057,calling stored procedure from another stored procedure sql server i have 3 insert stored procedures each sp inserts data in 2 different tablestable 1 table 2 idperson idproduct name productname phonenumber productdescription fkidproductsp for table 1 sp for table 2create procedure test1 create procedure test2with with execute as caller execute as calleras asdeclare declareidperson int idproduct intname varchar20 productname varchar50phone varchar20 productodescription varchar50 set nocount on set nocount on begin begin insert into table1 insert into table2 idperson idproduct name productname phone productdescription values values idperson idproduct name productname phone productdescription end endi need to call stored procedure test 2 from stored procedure test 1 and insert the fkid in the table 1,['sql'] +237093,simple opencv command works in debug mode but not release mode i am trying to load in a training xml file with cascadeclassifierload and it works just fine in debug mode but in release mode i get a runtime errorthe error i get isunhandled exception at 0x07feefbf4938 in testingexe 0xc05 access violation writing location 0x027my code is as followscascadeclassifier cif cloadcdatahaarcascade frontalface altxml exit1the code crashes on the loading line why would this happen,['c++'] +237129,guava multiset vs map my understanding of multiset is a set with frequency but i can always use map to represent the frequency is there other reason to use multiset,['java'] +237130,what does value initializing something mean possible duplicatewhat do the following phrases mean in c zero default and valueinitialization if i have a class for exampleclass info int x int ywhich i used to created an objectinfo p new infodoes the brackets beside info mean i am value initializing it how does it different from this info p new info i know there is a question which differentiate between different meanings in new and old c language but i want to know the semantic difference between default and value initialization eg does value initialization means initializing something to zero,['c++'] +237151,ios background downloads when the app is not active when my app is initially downloaded the user needs to download a large file something like 200mb upper limit i definitely cannot expect the user to keep the app open till this file is downloaded so heshe might close the app the app will go into background how can i continue to download the file in this scenario is this even possible in ios,"['objective-c', 'ios']" +237200,unexpected end of file error i hope you can help me cause i have no idea about whats going on i am having the following error while trying to add beecrypt library to my projectfatal error c1010 unexpected end of file while looking for precompiled header did you forget to add include stdafxh to your sourceactually i did not forget to add include stdafx to my source the compiler points the error to be at the end of this cxx filedefine beecrypt cxx dll exportifdef have config h include confighendifinclude beecryptcsecuritysecurerandomhinclude beecryptcsecuritysecurerandomspihinclude beecryptcsecuritysecurityhusing namespace beecryptsecuritysecurerandom securerandomgetinstanceconst string algorithm throw nosuchalgorithmexception securityspi tmp securitygetspialgorithm securerandomassertdynamic castsecurerandomspitmpcspisecurerandom result new securerandomreinterpret castsecurerandomspitmpcspi tmpprov tmpnamedelete tmpreturn result securerandom securerandomgetinstanceconst string type const string provider throw nosuchalgorithmexception nosuchproviderexception securityspi tmp securitygetspitype securerandom providerassertdynamic castsecurerandomspitmpcspisecurerandom result new securerandomreinterpret castsecurerandomspitmpcspi tmpprov tmpnamedelete tmpreturn result securerandom securerandomgetinstanceconst string type const provider provider throw nosuchalgorithmexception securityspi tmp securitygetspitype securerandom providerassertdynamic castsecurerandomspitmpcspisecurerandom result new securerandomreinterpret castsecurerandomspitmpcspi tmpprov tmpnamedelete tmpreturn result void securerandomgetseedbyte data int size entropygathernextdata size securerandomsecurerandom securityspi tmp securitygetfirstspisecurerandomassertdynamic castsecurerandomspisecurerandomspi tmpcspi rspi securerandomspi tmpcspi type tmpname prov tmpprovdelete tmp securerandomsecurerandomsecurerandomspi rspi const provider provider const string type rspi rspi prov provider type type securerandomsecurerandom delete rspi void securerandomgenerateseedbyte data int size rspienginegenerateseeddata size void securerandomsetseedconst byte data int size rspienginesetseeddata size void securerandomnextbytesbyte data int size rspienginenextbytesdata size const string securerandomgettype const throw return type const provider securerandomgetprovider const throw return prov and here is h fileifndef class bee security securerandom hdefine class bee security securerandom hinclude beecryptbeecrypthifdef cplusplusinclude beecryptcsecuritysecurerandomspihusing beecryptsecuritysecurerandomspiinclude beecryptcsecurityproviderhusing beecryptsecurityproviderinclude beecryptcsecuritynosuchalgorithmexceptionhusing beecryptsecuritynosuchalgorithmexceptioninclude beecryptcsecuritynosuchproviderexceptionhusing beecryptsecuritynosuchproviderexception namespace beecrypt namespace security ingroup cxx security m class beecryptcxxapi securerandom public object public static securerandom getinstanceconst string type throw nosuchalgorithmexception static securerandom getinstanceconst string type const string provider throw nosuchalgorithmexception nosuchproviderexception static securerandom getinstanceconst string type const provider provider throw nosuchalgorithmexception static void getseedbyte int private securerandomspi rspi const provider prov string type protected securerandomsecurerandomspi spi const provider provider const string type public securerandom virtual securerandom void generateseedbyte int void nextbytesbyte int void setseedconst byte int const string gettype const throw const provider getprovider const throw endif endifsorry for so much code,['c++'] +237221,what would be a python alternative to a system like nanoc is there a python publishing system have no idea whether this is an appropriate name for such a thing but they are calling it that way similar to nanoc generally a thing which will convert a lot of markupasciidoc files to html in an orderly fashioni know of pythonmarkdown but one by one page with no support for outside css pages is not what i am looking forso is there something python based of more or less this quality,"['python', 'ruby']" +237228,python find similar colors best way i have made a function to find a color within a image and return x y now i need to add a new function where i can find a color with a given tolerence should be easycode to find color in image and return x ydef findcolorinrgb xmin xmax ymin ymax image imagegrabgrab for x in rangexmin xmax for y in rangeyminymax px imagegetpixelx y if px0 r and px1 g and px2 b return x ydef findcolorrgb image imagegrabgrab size imagesize pos findcolorinrgb 1 size0 1 size1 return posoutcometaken from the answers the normal methods of comparing two colors are in euclidean thistance or chebyshev thistance i decided to mostly use squared euclidean thistance and multiple different colorspaces lab deltae lch xyz hsl and rgb in my code most colorspaces use squared euclidean thistance to compute the difference for example with lab rgb and xyz a simple squared euc thistance does the trickif xx12 yy12 zz12 tol2 then lch and hsl is a little more complicated as both have a cylindrical hue but some piece of math solves that then it is on to using squared eucl here as wellin most these cases i have added separate parameters for tolerance for each channel using 1 global tolerance and alternative modifiers huetol tolerance huemod or lighttol tolerance lightmodit seems like colorspaces built on top of xyz lab lch does perform best in many of my scenarios tho hsl yields very good results in some cases and it is much cheaper to convert to from rgb rgb is also great tho and fills most of my needs,['python'] +237244,javas return value in trycatchfinally mechanism i have just encountered this following codepublic class testfinally public static void mainstring args int returnvalue function systemoutprintlnreturn value returnvalue public static int function try return 1 catch exception e return 2 finally return 3 it is without a doubt that running this code will yield an output of return value 3 however i am curious as tothe mechanism of the innards in the jvm does anyone know if the vm actually replaces the return value on the stack by overwriting the first return 1 if so where can i find more information on thisi have yet to find the use for a return in the finally mechanism that is used this way and allowed in the implementedin the jvm if this code construct is used as a means to returnerror code it is in my opinion there are better ways to log errorsor return these error codes has anyone found a use for such aconstructmany thanks in advancecheersvern,['java'] +237250,how to push an opencv image viewing window into a qt gui with visual studio i want to create a gui with 2 rectangles for viewing videos one where you see the input video one where you see the postprocessed video i want it to be integrated into a qtmade gui but i want these video areas to be populated from opencv as an alternative to opencvs cvnamewindow methodhow can i do this,['c++'] +237252,compare javascript array of objects to get min max i have an array of objects and i want to compare those objects on a specific object property heres my arrayvar myarray id 1 cost 200 id 2 cost 10 id 3 cost 50 id 4 cost 500i would like to zero in on the cost specifically and a get a min and maximum value i realize i can just grab the cost values and push them off into a javascript array and then run the fast javascript maxminhowever is there an easier way to do this by bypassing the array step in the middle and going off the objects properties in this case cost directly,['javascript'] +237322,do shared libraries use the same heap as the application say i have an application in linux that uses shared libraries so files my question is whether the code in those libraries will allocate memory in the same heap as the main application or do they use their own heap so for example some function in the so file calls malloc would it use the same heap manager as the application or another one also what about the global data in those shared memories where does it lie i know for the application it lies in the bss and data segment but do not know where it is for those shared object files,['c'] +237351,is stringequalsstring1substring0 x string2 better than string1startswithstring2 i am using string comparisons to test url paths using stringcomparisonordinalignorecasemsdn gives the following string comparison advice here but does not clarify whymsdn example halfway down the above pagepublic static bool isfileuristring path pathstartswithfile stringcomparisonordinalignorecase return truemsdn advicehowever the preceding example uses the stringstartswithstring stringcomparison method to test for equality because the purpose of the comparison is to test for equality instead of ordering the strings a better alternative is to call the equals method as shown in the following examplepublic static bool isfileuristring path if pathlength 5 return false return stringequalspathsubstring0 5 file stringcomparisonordinalignorecasequestion why does msdn suggest the second example is betterthiscussion pointsclearly the return true in the first example is a bug and should be return pathstartswith we can safely ignore this as a bug as the vb code is correctcreation of a substring prior to comparing for equality would appear to only use another memory resource than just calling stringstartswiththe length 5 test is a nice shortcircuit however it could be used with the prior code just the samethe second example could be construed as clearer code but i am concerned with performance the creation of the substring seems unnecessary,"['c#', '.net']" +237361,adding extra fields to djangouserena forms i am using djangouserena i have a model called userprofile i have added extra fields in signup form and these fields are show up correctly but data is not saved i want to save some fields data into another model business too for example i have two field like contact and business i want contact field will goes to userprofile model and business field will goes to business model any clue thank youhere is my codeclass signupformextrasignupform address formscharfieldlabel uaddressmax length30requiredfalse contact formscharfieldlabel ucontactmax length30requiredfalse business formscharfieldlabel ubusiness namemax length30requiredfalse def saveself override the save method to save the first and last name to the user field user profile supersignupformextra selfsavecommitfalse user profileaddress selfcleaned dataaddress user profilecontact selfcleaned datacontact user profilebusiness selfcleaned databusiness user profilesave return user profileupdate i am storing those values on a user instance i want toe storing them on profile model an instance that is bound to the user,['python'] +237365,recompilation of dependencies with maven possible any performance boost i was thinking about dependencies in maven maven downloads them but it is unknown for what target version of jvm are they compiled for and with what compiler this raises two questionswould dependency recompilation bring faster dependency librariesi tried to search for this but have not found sufficient answer i found out that for 16 there is split bytecode verification that is done when compiling with target 16there is also a question are java 6s performance improvements in the jdk jvm or both where it is mentioned that newer versions of javac might generate more optimized codeis it possible with maven to perform recompilation of depending libraries would it be possible to configure maven to download sources put there information about 16 target and perform mvn clean installi am aware of maven dependency plugin and dependencysources goal that could be used for source downloadthere is also maven replacer plugin allowing replacing of text in files as stated in its issue 58 there was implemented xpath support for itwould it be possible to implement it with these plugins for dependency and also for its dependencies to perform it i am not sure on how to perform it on the dependencies perhaps with maven replacer plugin injecting the configuration into unpacked dependencies pomxmlor is there a simpler way to configure target java version with build profile in users settingsxml that would take precedence of project settings and therefore avoiding pomxml modification,['java'] +237370,the best way to register process start time i am writing a program that must register time of starting a process such as notepadi thought that it is good to create a timer that checks all of processes every second but i think that it will slow down the users computer is there a better way of doing this,['c#'] +237451,issue building a single project using msbuild that has multiple configurations issuewe are using config transforms inside our solution for example debug test staging releasehowever those configurations are only used on our mvc projects all of the libraries only use debug and release which makes more sense because our libraries only need to be built in either debug mode or release modethe issue arises when attempting to build a single project from the command line i need to be able to do this in order to auto deploy our builds from teamcity to our testing environment when i build the single project like thismsbuild myprojectcsproj tbuild pconfigurationtest pplatformanycpu pdeployonbuildtrue pdeploytargetmsdeploypublish pmsdeployserviceurlhttpsserver8172msdeployaxd pallowuntrustedcertificatetrue pmsdeploypublishmethodwmsvc pcreatepackageonpublishtrue pusernameusername ppasswordpasword pdeployiisapathiisapathi get the following errormyprojectcsproj build target 1 csrcmyprojectcsproj default target 18 cwindowsmicrosoftnetframeworkv4030319microsoftcommontargets4839 error the outputpath property is not set for project samplelibrarycsproj please check to make sure that you have specified a valid combination of configuration and platform for this project configurationtest platformanycpu you may be seeing this message because you are trying to build a project without a solution file and have specified a nondefault configuration or platform that does not exist for this projecti know what it means because my samplelibrary does not have a configuration for test and the mapping for the samplelibrary would be contained in my sln filequestionis there a way to resolve this without having to add those configurations for every library project it smells like an ugly hack here,['c#'] +237459,how to neutralize boxshadow currently i am using thisboxshadow 0 1px 3px rgba0 0 0 015 insetbut on specific size of screen i do not want boxshadowhow can i override to thisable the shadow,['css'] +237488,osx lion new bash session rvm default ruby not used i use osx lion i have installed rvm and have put this line in my bash profile file s usersanandrvmscriptsrvm source usersanandrvmscriptsrvm this loads rvm into a shell sessioni installed ruby192p290 and set it as default rvm ruby with this commandrvm use default ruby192p290and when i checked rubyvruby 192p290 20110709 revision 32553 x86 64darwin1120the problem is every time i open a new terminal window or a tab the default ruby is not getting set the system ruby is instead getting used ruby v gives thisruby 187 20090612 patchlevel 174 i686darwin1032this also happens with reading rvmrc file in a ruby project when i am inside a project and when a new tab gets opened it gets me into the project directory but is not setting ruby according to rvmrc in that project what should i do to fix this,['ruby'] +237500,c11 abstracting over const volatile lvalue reference and rvalue reference qualified member function pointers c03 lets you qualify function parameters as being const volatile andor lvalue references c11 adds one more rvalue references furthermore c lets you overload functions based on the qualifiers of their parameters so that the most appropriate overload is selected when calling the functiona member function can conceptually be thought of as a function which takes an extra parameter whose type is a reference to an instance of the class of which it is a member it is possible to overload a member function based on the qualifiers of this extra parameter in much the same way as any other parameter this is expressed by putting the qualifiers at the end of the function signaturestruct foo int data return a nonconst reference if this is nonconst const int data const return a const reference if this is constin c03 const and volatile qualifiers are possible and c11 also allows and could theoretically have been allowed in c03 but it was notany combination of qualifiers can be used with the exception that and are mutually exclusive which makes for 22 4 possibilities in c03 and 244 12 in c11this can be quite a pain when you want to work with member function pointers because they are not even a little bit polymorphic in these qualifiers the qualifiers on the this type of a member function pointer passed as an argument must exactly match those on the type of the parameter it is being passed as c also offers no explicit facility to abstract over qualifiers in c03 this was mostly ok because you would have to write a const version and a nonconst version and no one cares about volatile but in the pathological case in c11 which is not as uncommon as it is pathological you could have to manually write as many as 12 overloads per functioni was very happy to thiscover that if you are passing the type of the enclosing class as a template parameter and derive the type of a member function pointer from it that const and volatile qualifiers are allowed and propagated as you would expecttemplatetypename objectstruct bar typedef int objectsigintbarbaz sig will be int bazintbarconst baz sig will be int bazint constbarvolatile baz sig will be int bazint volatilebarconst volatile baz sig will be int bazint const volatilethis is a great deal nicer than having to write out all of the cases manuallyunfortunately it does not seem to work for and gcc 47 sayserror forming pointer to reference type abazabut that is not too surprising given that gcc as of 47 does not yet have support for reference qualifiers on thisi also tried it with clang 30 which does have such supporterror member pointer refers into nonclass type baz oh wellam i correct in concluding that this is not possible and that there is no way to abstract over reference qualifiers on the this type of member function pointers any other techniques for abstracting over qualifiers especially on this other than in the specific case when youre passing the this type as a template parameter would also be appreciatedit is worth pointing out that if c did not thistinguish between member functions and normal functions this would all be trivial youd use the template parameter as the type of a parameter of the function pointer and the template argument would be passed through asis qualifiers intact no extra thought necessary,['c++'] +237507,rails app takes a long time to generate error page my rails app generates error page very slowly rail 3132 ruby 192193 eg i have added my bad variable to some haml template and rendered feesindexhtmlhaml within layoutsapplication 977521mscompleted 500 internal server error in 99579msactionviewtemplateerror undefined local variable or method my bad variable for 0x03bbf0c8after deleting this fake variablecompleted 200 ok in 327ms views 2747ms activerecord 98msany suggestions,['ruby-on-rails'] +237525,strange behaviour updating sprite position i am coding a simple roguelike game in c using sdl library and i have some problems moving my character on the screen each time a frame needs to be rendered i update the position of the sprite using the update function which does nothing if the player is standing still to issue the movement command and thus starting the animation i use the step function called only once per each player movement from one tile to another upon receiving the up command the game behaves fine and the character moves smoothly in one second to the new position however when the down command is given he moves at about half the speed and obviously after one second has passed he is instantly teleported to the final position with a sudden flicker the code for the movement is basically identical but for the fact that in one case the delta movement is summed to the y position in the other case is subtracted maybe the fact that the position is an integer and the delta is a double is causing problems does sum and subract behave differently maybe different rounding here is the relevant code sorry for the lengthvoid playerstepplayerdirection dir ifm status standing no animation while standing return switchdir case up ifm currmaptileatm xpos m ypos m currmaptileheightm type tilefloor if next tile is not a wall set up animation m status walking up m ydelta m currmaptileheight sprite have to move by a tile m yvel m currmaptileheight 10f in one second m ynext m ypos m currmaptileheight store final destination break case down ifm currmaptileatm xpos m ypos m currmaptileheightm type tilefloor m status walking down m ydelta m currmaptileheight m yvel m currmaptileheight 10f m ynext m ypos m currmaptileheight break default break m animtimer sdl getticksvoid playerupdate m animtimer sdl getticks m animtimer get the ms passed since last update switchm status case walking up m ypos m yvel m animtimer update position m ydelta m yvel m animtimer update the remaining space break case walking down m ypos m yvel m animtimer m ydelta m yvel m animtimer break default break ifm xdelta 0 m ydelta 0 if i am done moving m xpos m xnext adjust position m ypos m ynext m status standing and stop else m animtimer sdl getticks else update timeredit i removed some variables and only left the elapsed time the speed and the final position now it moves without flickering but the down and right movements are visibly slower than the up and left ones still wonder whyedit 2 ok i figured out why this is happening as i supposed in the first place there is a different rounding from double to integer when it comes to sum and subtraction if i perform a cast like thism xpos intm xvel m animtimerthe animation speed is the same and the problem is solved,['c++'] +237548,artefacts from riemann sum in scipysignalconvolve short summary how do i quickly calculate the finite convolution of two arraysproblem descriptioni am trying to obtain the finite convolution of two functions fx gx defined byto achieve this i have taken thiscrete samples of the functions and turned them into arrays of length stepsxarray x i steps for i in rangestepsfarray fx for x in xarraygarray gx for x in xarrayi then tried to calculate the convolution using the scipysignalconvolve function this function gives the same results as the algorithm conv suggested here however the results differ considerably from analytical solutions modifying the algorithm conv to use the trapezoidal rule gives the desired resultsto illustrate this i letfx expxgx 2 exp2 xthe results arehere riemann represents a simple riemann sum trapezoidal is a modified version of the riemann algorithm to use the trapezoidal rule scipysignalconvolve is the scipy function and analytical is the analytical convolutionnow let gx x2 expx and the results becomehere ratio is the ratio of the values obtained from scipy to the analytical values the above demonstrates that the problem cannot be solved by renormalising the integralthe questionis it possible to use the speed of scipy but retain the better results of a trapezoidal rule or do i have to write a c extension to achieve the desired resultsan examplejust copy and paste the code below to see the problem i am encountering the two results can be brought to closer agreement by increasing the steps variable i believe that the problem is due to artefacts from right hand riemann sums because the integral is overestimated when it is increasing and approaches the analytical solution again as it is decreasing edit i have now included the original algorithm 2 as a comparison which gives the same results as the scipysignalconvolve functionimport numpy as npimport scipysignal as signalimport matplotlibpyplot as pltimport mathdef convolveoriginalx y the original algorithm from recipes in pythonhtml p q and lenx leny lenx leny 1 z for k in rangen t lower upper 0 max0 k q 1 minp 1 k for i in rangelower upper 1 t t xi yk i zappendt return nparrayz modified to include conversion to numpy arraydef convolvey1 y2 dx none compute the finite convolution of two signals of equal length param y1 first signal param y2 second signal param dx optional integration step width note based on the algorithm at recipes in pythonhtml p leny1 determine the length of the signal z create a list of convolution values for k in rangep t 0 lower max0 k p 1 upper minp 1 k for i in rangelower upper t y1i y2k i y1i 1 y2k i 1 2 zappendt z nparrayz convert to a numpy array if dx none is a step width specified z dx return zsteps 50 number of integration stepsmaxtime 5 maximum timedt floatmaxtime steps obtain the width of a time steptime dt i for i in range steps create an array of timesexp1 mathexpt for t in time create an array of function valuesexp2 2 mathexp2 t for t in timecalculate the analytical expressionanalytical 2 mathexp2 t 1 mathexpt for t in timecalculate the trapezoidal convolutiontrapezoidal convolveexp1 exp2 dtcalculate the scipy convolutionsci signalconvolveexp1 exp2 mode fullslice the first half to obtain the causal convolution and multiply by dtto account for the step widthsci sci0steps dtcalculate the convolution using the original riemann sum algorithmriemann convolveoriginalexp1 exp2riemann riemann0steps dtplotpltplottime analytical label analyticalpltplottime trapezoidal o label trapezoidalpltplottime riemann o label riemannpltplottime sci label scipysignalconvolvepltlegendpltshowthank you for your time,['python'] +237551,how can i set css only for specific ie browsers i have a cssjquery checkbox style script the problem is in current browsers in order for the span to float over the input the inputs position must be absolute but in ie8 below the script will not work and therefore i am left with and absolutely positioned input that is just floating over other elements i am not asking for the script to work in ie8 belowi want to know how i can use css to set a specific style if it is ie8 and below i guess jquery would be acceptable if it is necessary but i do not think it is i know this can be done with just css html i just do not know how,['css'] +237554,how to make a class deserialize as a different name for instance something likeapple will serialize just fine to a class called apple however if i want to call that class dragon it will not serialize which makes sense i want to know how to mark up dragon such that when the xmlserializer sees it it knows that dragon is the same as,"['c#', '.net']" +237574,getting input values from text box i am trying to get the text from a text box i have 2 input text boxes that are not in a form and i am trying to retrieve the value and store it in a variable this code returns undefined in the alert box that pops up script var userpass documentgetelementbyidpass var username documentgetelementbyidfname function submit alertuserpassvalue scriptwhen i run it with usernamevalue as a parameter in the alert function it will work and thisplay what ever you type in the box here is the html table idlogin tr tdlabeluser namelabeltd tr tr td colspan2input classtextbox idfname typetext maxlength30 requiredtd tr tr td idpasslabelpasswordlabeltd tr td colspan2input classtextbox idpass typetext maxlength30 requiredtd tr tr tdinput typebutton classloginbuttons valuelogin onclicksubmitnbspnbspnbsp input typebutton classloginbuttons valuecanceltd table,"['javascript', 'html']" +237575,stopping propagation of mousedownmouseup from a click handler heres a demoi have two divs an inner and an outerdiv idouter div idinnerdivdivwith some css so you can see which is whichouter width 250px height 250px padding 50px background yellowinner width 250px height 250px background bluei try to stop propagation of mousedown and mouseup events from within a click handler like soinneronclick functione estoppropagation thiscssbackground green return falseouteronmousedown functione thiscssbackground greenouteronmouseup functione thiscssbackground yellowthis does not seem possible what does work is calling stoppropagation from within other mousedown and mouseup calls as shown here another demoinneronmousedown functione estoppropagation return falseinneronmouseup functione estoppropagation return falsei may have already answered my own question but i am not sure if my approach is the best or most reasonable is this the right way to stop an event bubbling up to a mousedown and mouseup,"['javascript', 'jquery']" +237580,heroku error r14 memory quota exceeded how do i solve this i have a rails 31 app on heroku i am seeing a lot of these errorserror r14 memory quota exceededtypically the preceding log entry is showingprocess running mem522m1021this does vary a little but never by much and can occur after almost any url request so it is not related to a specific controller action as far as i can tellthis is a classic block of log entries20120116t0235570 herokurouter put prizequizherokuappcommobile users1 dynoweb1 queue0 wait0ms service55ms status401 bytes2720120116t0235580 herokurouter put prizequizherokuappcommobile users1 dynoweb1 queue0 wait0ms service155ms status200 bytes120120116t0236020 herokurouter put prizequizherokuappcommobile users1 dynoweb1 queue0 wait0ms service13ms status401 bytes2720120116t0236020 herokurouter put prizequizherokuappcommobile users1 dynoweb1 queue0 wait0ms service147ms status200 bytes120120116t0236090 herokurouter post prizequizherokuappcommobile users dynoweb1 queue0 wait0ms service87ms status201 bytes62420120116t0236110 herokurouter get prizequizherokuappcomquizzes1questions dynoweb1 queue0 wait0ms service5ms status401 bytes2720120116t0236110 herokurouter get prizequizherokuappcomquizzes1questions dynoweb1 queue0 wait0ms service290ms status200 bytes8141220120116t0236150 herokurouter put prizequizherokuappcommobile users1 dynoweb1 queue0 wait0ms service10ms status401 bytes2720120116t0236160 herokurouter put prizequizherokuappcommobile users1 dynoweb1 queue0 wait0ms service67ms status200 bytes120120116t0236330 herokurouter post prizequizherokuappcomquizzes1scores dynoweb1 queue0 wait0ms service10ms status401 bytes2720120116t0236330 herokurouter post prizequizherokuappcomquizzes1scores dynoweb1 queue0 wait0ms service132ms status201 bytes23020120116t0236550 herokuweb1 process running mem522m102120120116t0236550 herokuweb1 error r14 memory quota exceeded20120116t0237170 appweb1 20120116t0237170 appweb1 20120116t0237170 appweb1 started post quizzes1scores for 177538025 at 20120116 023717 020120116t0237170 appweb1 cache post quizzes1scores invalidate pass20120116t0237170 appweb1 20120116t0237170 appweb1 20120116t0237170 appweb1 started post quizzes1scores for 177538025 at 20120116 023717 020120116t0237170 appweb1 cache post quizzes1scores invalidate pass20120116t0237170 herokurouter post prizequizherokuappcomquizzes1scores dynoweb1 queue0 wait0ms service44ms status201 bytes23020120116t0237170 herokuweb1 process running mem522m102120120116t0237170 herokuweb1 error r14 memory quota exceeded20120116t0237170 herokurouter post prizequizherokuappcomquizzes1scores dynoweb1 queue0 wait0ms service16ms status401 bytes2720120116t023720 appweb1 20120116t023720 appweb1 20120116t023720 appweb1 started get quizzes1scorescurrent game for 177538025 at 20120116 023720 020120116t023720 appweb1 cache get quizzes1scorescurrent game miss20120116t023720 appweb1 20120116t023720 appweb1 20120116t023720 appweb1 started get quizzes1scorescurrent game for 177538025 at 20120116 023720 020120116t023720 herokurouter get prizequizherokuappcomquizzes1scorescurrent game dynoweb1 queue0 wait0ms service8ms status401 bytes2720120116t023720 appweb1 cache get quizzes1scorescurrent game miss20120116t023720 herokurouter get prizequizherokuappcomquizzes1scorescurrent game dynoweb1 queue0 wait0ms service6ms status401 bytes2720120116t023720 appweb1 20120116t023720 appweb1 20120116t023720 appweb1 started post quizzes1scores for 177538025 at 20120116 023720 020120116t023720 herokurouter post prizequizherokuappcomquizzes1scores dynoweb1 queue0 wait0ms service33ms status401 bytes2720120116t023720 appweb1 cache post quizzes1scores invalidate pass20120116t023720 appweb1 20120116t023720 appweb1 20120116t023720 appweb1 started get quizzes1scorescurrent game for 177538025 at 20120116 023720 020120116t023720 appweb1 20120116t023720 appweb1 i have new relic installed but have been unable to identify anything of any usewill gladly supply more info if needed i also have an outstanding support request on heroku for this but as yet 2 days marked as urgent i have had no responseadding web dynos makes no differenceupdate i have added the oink gem and this is a sample result20120126t0824250 appweb1 20120126t0824250 appweb1 20120126t0824250 appweb1 started put mobile users1 for 11049234219 at 20120126 082425 020120126t0824260 appweb1 oink action mobile usersupdate20120126t0824260 appweb1 memory usage 286276 pid 1620120126t0824260 appweb1 instantiation breakdown total 2 mobileuser 220120126t0824260 appweb1 oink log entry complete20120126t0824260 appweb1 cache put mobile users1 invalidate pass20120126t0824260 herokurouter put prizequizherokuappcommobile users1 dynoweb1 queue0 wait0ms service460ms status200 bytes120120126t0824380 herokuweb1 process running mem537m104920120126t0824380 herokuweb1 error r14 memory quota exceeded20120126t0824430 appweb1 20120126t0824430 appweb1 20120126t0824430 appweb1 started put mobile users1 for 103116523 at 20120126 082443 020120126t0824430 herokurouter put prizequizherokuappcommobile users1 dynoweb1 queue0 wait0ms service544ms status401 bytes2720120126t0824430 appweb1 oink action mobile usersupdate20120126t0824430 appweb1 memory usage 2876 pid 1920120126t0824430 appweb1 instantiation breakdown total 020120126t0824430 appweb1 oink log entry complete20120126t0824430 appweb1 cache put mobile users1 invalidate pass20120126t0824470 appweb1 20120126t0824470 appweb1 20120126t0824470 appweb1 started put mobile users1 for 103116523 at 20120126 082447 020120126t0824480 appweb1 oink action mobile usersupdate20120126t0824480 appweb1 memory usage 286412 pid 1620120126t0824480 appweb1 instantiation breakdown total 2 mobileuser 220120126t0824480 appweb1 oink log entry complete20120126t0824480 herokurouter put prizequizherokuappcommobile users1 dynoweb1 queue0 wait0ms service432ms status200 bytes120120126t0824480 appweb1 cache put mobile users1 invalidate pass20120126t0824590 herokuweb1 process running mem537m104920120126t0824590 herokuweb1 error r14 memory quota exceeded20120126t082520 herokuweb1 process running mem537m104920120126t082520 herokuweb1 error r14 memory quota exceeded20120126t0825410 herokuweb1 process running mem537m104920120126t0825410 herokuweb1 error r14 memory quota exceeded20120126t0826320 herokurouter put prizequizherokuappcommobile users1 dynoweb1 queue0 wait0ms service34ms status401 bytes2720120126t0827040 appweb1 20120126t0827040 appweb1 20120126t0827040 appweb1 started put mobile users1 for 103116523 at 20120126 082704 020120126t0827040 appweb1 oink action mobile usersupdate20120126t0827040 appweb1 memory usage 2876 pid 1920120126t0827040 appweb1 instantiation breakdown total 2 mobileuser 220120126t0827040 appweb1 oink log entry complete20120126t0827040 appweb1 cache put mobile users1 invalidate pass20120126t0827040 herokurouter put prizequizherokuappcommobile users1 dynoweb1 queue0 wait0ms service337ms status200 bytes120120126t0827050 herokuweb1 process running mem537m104920120126t0827050 herokuweb1 error r14 memory quota exceeded20120126t0827260 herokuweb1 process running mem537m104920120126t0827260 herokuweb1 error r14 memory quota exceeded20120126t0827480 herokuweb1 process running mem537m104920120126t0827480 herokuweb1 error r14 memory quota exceeded20120126t0828080 herokuweb1 process running mem537m105020120126t0828080 herokuweb1 error r14 memory quota exceeded20120126t0828290 herokuweb1 process running mem537m105020120126t0828290 herokuweb1 error r14 memory quota exceeded20120126t0828510 herokuweb1 process running mem537m105020120126t0828510 herokuweb1 error r14 memory quota exceeded20120126t0829080 appweb1 20120126t0829080 appweb1 20120126t0829080 appweb1 started put mobile users1 for 8526234218 at 20120126 082908 020120126t0829080 appweb1 oink action mobile usersupdate20120126t0829080 appweb1 memory usage 382404 pid 1320120126t0829080 appweb1 instantiation breakdown total 020120126t0829080 appweb1 oink log entry complete20120126t0829080 appweb1 cache put mobile users1 invalidate pass20120126t0829080 herokurouter put prizequizherokuappcommobile users1 dynoweb1 queue0 wait0ms service86ms status401 bytes2720120126t0829090 appweb1 20120126t0829090 appweb1 20120126t0829090 appweb1 started put mobile users1 for 8526234218 at 20120126 082909 020120126t0829090 appweb1 oink action mobile usersupdate20120126t0829090 appweb1 memory usage 382404 pid 1320120126t0829090 appweb1 instantiation breakdown total 2 mobileuser 220120126t0829090 appweb1 oink log entry complete20120126t0829090 appweb1 cache put mobile users1 invalidate pass20120126t0829090 herokurouter put prizequizherokuappcommobile users1 dynoweb1 queue0 wait0ms service160ms status200 bytes120120126t0829110 appweb1 20120126t0829110 appweb1 20120126t0829110 appweb1 started put mobile users1 for 8526234218 at 20120126 082911 020120126t0829110 herokurouter put prizequizherokuappcommobile users1 dynoweb1 queue0 wait0ms service101ms status401 bytes2720120126t0829110 appweb1 oink action mobile usersupdate20120126t0829110 appweb1 memory usage 382404 pid 1320120126t0829110 appweb1 instantiation breakdown total 020120126t0829110 appweb1 oink log entry complete20120126t0829110 appweb1 cache put mobile users1 invalidate pass20120126t0829120 appweb1 20120126t0829120 appweb1 20120126t0829120 appweb1 started put mobile users1 for 8526234218 at 20120126 082912 020120126t0829120 herokuweb1 process running mem537m105020120126t0829120 herokuweb1 error r14 memory quota exceeded20120126t0829120 appweb1 oink action mobile usersupdate20120126t0829120 appweb1 memory usage 2876 pid 1920120126t0829120 appweb1 instantiation breakdown total 2 mobileuser 220120126t0829120 appweb1 oink log entry complete20120126t0829120 appweb1 cache put mobile users1 invalidate pass20120126t0829120 herokurouter put prizequizherokuappcommobile users1 dynoweb1 queue0 wait0ms service169ms status200 bytes120120126t0829330 herokuweb1 process running mem537m105020120126t0829330 herokuweb1 error r14 memory quota exceededi have no idea what that proves other than it seems i am not using as much memory as heroku thinks i ammemory usage 2876 vs process running mem537m1050,['ruby-on-rails'] +237581,what happens to an html5 web worker thread when the tab is closed while it is running i am wondering what happens when a user closes the tab which spawned the worker thread while the thread is still working does it halt everything if so is there a way to run the thread in the background even when the tab is closed,['javascript'] +237586,difference between hashtable and collectionssynchronizedmaphashmap as far as i know javautilhashtable synchronizes each and every method in the javautilmap interface while collectionssynchronizedmaphash map returns a wrapper object containing synchronized methods delegating calls to the actual hash map correct me if i am wrongi have two questions what difference does it make to synchronize each and every method and to have a wrapper class what are the scenarios to choose one over the otherwhat happens when we do collectionssynchronizedmaphash table will this be equal to simply using a normal javautilhashtable,['java'] +237607,viewdidload method in uiviewcontroller when does it get called i have a uiviewcontroller called launchcontroller that is launched in my iphone app when the app first opensinterface launchcontroller uiviewcontrolleruinavigationcontrollerdelegate uiimagepickercontrollerdelegatethen when a button is clicked i push another view controller maincontroller c maincontroller alloc initwithimageimage self presentmodalviewcontrollerc animatednomaincontroller has the following constructor which i use idinitwithimageuiimage img self super init if self image img nsloginited the image return selfand then it has a viewdidload method as follows voidviewdidload nslogcalling view did load super viewdidload uiimageview imageview uiimageview alloc initwithimageimage selfview addsubviewimageview nslogthisplaying main controllerwhen the program runs i see that the constructor for maincontroller is called due to the output of nslog however viewdidload never gets called even though i am calling presentmodalviewcontroller why is this why is not viewdidload being called,"['iphone', 'ios']" +237616,php switch case statement to handle ranges i am parsing some text and calculating the weight based on some rules all the characters have the same weight this would make the switch statement really long can i use ranges in the case statementi saw one of the answers advocating associative arraysweights arrayazaz 1009 100 250there are more rules which have been left out for the sake of clarity and brevitytotal weight 0foreach text as character total weight weightcharacterecho weightwhat is the best way to achieve something like thisis there something similar to the bash case statement in phpsurely writing down each individual character in either the associative array or the switch statement cannot be the most elegant solution or is it the only alternative,['php'] +237646,generating guid without hyphen i am generating a guid using the following statement in my codebyte keybytes encodingutf8getbytes guidnewguid tostring substring 0 12 but when a guid is generated i find that it contains the hyphen character too how do i go about in generating a guid with only letters upper case and lower case and numbers i do not want the hyphen can someone give me so idea,['c#'] +237654,change the font style set lable text in allcaps format in objective c i want to set the uilable text font style in smallcaps format like below image please give me the solution for this if anyone knowthanks,"['iphone', 'objective-c']" +237661,running unit tests on the server jaxrs i am writing a jaxrs jerseymaven application that does some tricky things eg call native executables embedded in the war i need to run some of my unit tests junit4 on the server amazon elastic beanstalk running tomcat 7022 to check that everything is okis there a standard flexible way of doing this other than ryo roll your own the things i found seem to have more to do with integration testing on the developer machine ie jersey test framework even ryo is confusing me how could i call code in the test packages from source packagesbasically i want to create a test resource that i can call that will return my unit test results from the server in a pretty format even better if i could do testcategory,['java'] +237667,android post data with login details for php file https i am currently trying to post data via android to my websitethe php script i want send data to needs a loginvia browser i can use login data like in the link shown belowhttpsdemofoophpbar42if i try the same with the following code nothing happenspublic void postdata create a new httpclient and post header httpclient httpclient new defaulthttpclient string posturl httpsdemofoophp httppost httppost new httppostposturl try add your data listnamevaluepair namevaluepairs new arraylistnamevaluepair2 namevaluepairsaddnew basicnamevaluepairbar 42 httppostsetentitynew urlencodedformentitynamevaluepairs execute http post request httpresponse response httpclientexecutehttppost catch clientprotocolexception e todo autogenerated catch block catch ioexception e todo autogenerated catch block the only error i get the response401 authorization requiredunfortunately i do not know how to fix that error thanks to francesco vadicamo working codepublic void postdata create a new httpclient and post header defaulthttpclient httpclient new defaulthttpclient string posturl httphost targethost new httphostwexamplecom 1 https httpclientgetcredentialsprovidersetcredentials new authscopetargethostgethostname targethostgetport new usernamepasswordcredentialsdemo demo httppost httppost new httppostposturl try add your data listnamevaluepair namevaluepairs new arraylistnamevaluepair2 namevaluepairsaddnew basicnamevaluepairbar 42 httppostsetentitynew urlencodedformentitynamevaluepairs execute http post request httpresponse response httpclientexecutetargethost httppost catch clientprotocolexception e todo autogenerated catch block catch ioexception e todo autogenerated catch block,['android'] +237710,how is using entity linq not just essentially hard coding my queries so i have been developing with entity linq for a bit now and i am really starting to wonder about best practices i am used to the model of if i need to get data reference a stored procedure stored procedures can be changed on the fly if needed and do not require code recompiling i am finding that my queries in my code are looking like thislistint intlist from query in contextdbtable where queryforeignkeyid fkidtosearchfor select queryidtolistand i am starting to wonder what the difference is between that and thislistint intlist somemgrthatdoessqlexecutegetresults stringformatselect id from dbtable where foreignkeyid 0 fkidtosearchformy concern is that that i am essentially hard coding the query into the code am i missing something is that the point of entity if i need to do any real query work should i put it in a sproc,"['c#', '.net']" +237713,syncronizing actions in silverlight i have a silverlight app that uses actions to get data from the model which again gets the data from wcf servicesi need to somehow sync two actioncallbacks or wait for them and then execute some codeexample modelgetmytypelistlist mytypelistaddrangelist modelgetstigtypelistlist stigtypelistaddrangelistdosomethingwhenbothhavereturnedi know i can use a counter to keep track of how many has returned but is there not a better way to do thisedit user24601 has a good answer but countdownevent does not exist in silverlight any other great ideas,['c#'] +237746,java for vs whiletrue what is the difference between a standard whiletrue loop and foris there any or will both be mapped to the same bytecode after compiling,['java'] +237749,best practice for storing data in a dom element 1 json or multiple data attributes i have a list of 4 articles with small photo and a place for 1 article with a bigger photo when i click an article i will use javascript to thisplay that small article in the big placeto thisplay the the article with bigger photo there are 3 things i have to know of the article title detailurl and photourl of the bigger photo i want to catch this with javascriptmethode 1 using jquery find to search the domsmallfindimgattrsrcmethode 2 storing everything in seperate data attributesdatatitletitel1 datadetailurlarticle1htmlmethode 3 storing a json stringdatajson title titel1 detailurl article1html i think the 3th methode is the best fastest is that righthere the html,"['jquery', 'html']" +237753,is there a map with a variable key length in java world i need a map but when i call getkey n it should should return not only all the records with the searched key value but also all where the and last significant bits of the key are the same as the search key eg applying something like key1n11is there something like this already implemented in java,['java'] +237777,utf8 problems while reading csv file with fgetcsv i try to read a csv and echo the content but the content thisplays the characters wrong max ma14stermann maax maa14stermaannencoding of the csv file is utf8 without bom checked with notepadthis is the content of the csv filemaxma14stermannmy php scriptdoctype html public w3cdtd xhtml 10 transitionalen html xmlnsheadmeta httpequivcontenttype contenttexthtml charsetutf8 headbodyphphandle fopen specialcharscsvrecho table border1trtdfirst nametdtdlast nametdtrtrwhile data fgetcsv handle 10 num count data for c0 c num c output data echo tddatactd echo trtrbodyhtmli tried to use setlocalelc all de deutf8 as suggested here without success the content is still wrong thisplayedwhat i am missingeditan echo mb detect encodingdatacutf8 gives me utf8 utf8echo file get contentsspecialcharscsv gives me maaxmaa14stermaannandprint rstr getcsvresetexploden file get contentsspecialcharscsv gives mearray 0 maax 1 maa14stermaann what does it mean,['php'] +237781,find the last index of in a string in java can anyone help me find the lastindexof in a string in java i wrote the code asint i applastindexofapp is my string but there is a error as invalid character constant i tried using double quotes but still no use can anyone help me on this,['java'] +237790,is a wcf service a web service is it correct to call a wcf service a web servicei am working on a assigment for school and i made a restful wcf service and in the report i refered to it at times as a web service is it correct to refer to a wcf service as a web service,['c#'] +237817,set focus to uitextfield in tablecell i am creating a table view with uitextfields dynamicallyl textfield uitextfield alloc initwithframetextfieldframel textfieldtag cellrowl textfielddelegate selfl textfieldfont uifont boldsystemfontofsize14l textfieldtextcolor uicolor blackcolorl textfield setenabledyescellcontentview addsubviewl textfieldand now i want to set focus on this text field when user touch cell i write this voidtableviewuitableview tableview didselectrowatindexpathnsindexpath newindexpath uitextfield field uitextfield tblview viewwithtag newindexpathrow field resignfirstresponderbut this does not work,['ios'] +237831,dealing with quotes added by pdoprepare according to the php documentation pdoprepare adds quotes to all your parameters so that you do not have to worry about doing itthe parameters to prepared statements do not need to be quoted the driver automatically handles this if an application exclusively uses prepared statements the developer can be sure that no sql injection will occur however if other portions of the query are being built up with unescaped input sql injection is still possible the problem with this for me is the way i am building my queries and my database structure usually the from part of an sql statement wouldnt need to be parametrized because the table probably would be defined by direct user input however with my code that is the case in some places and thus i feel more comfortable with the parametrized versionselect from where as opposed to select from tablename where so my question is this is it possible to prevent my pdo object from adding the quotes around the from parameter so that i do not get sql errors thrown in my face or do i have to do this in a different manner,"['php', 'mysql', 'sql']" +237832,jquery move to anchor location on page load i have a simple page setup such asdiv idaboutus about us contentdivdiv idheader header contentdivwhen the page loads i need the page to automatically scroll down no animation needed to header so the user cannot see the about us div unless they scroll upaboutus has a fixed height so there is not any need for any variables to determine the height or anything if that is even neededi came across this other question and tried to modify some of the answers for my situation but nothing seemed to workany help would be appreciated,['jquery'] +237842,jcarousel how to get pause on hover with autoscroll jcarousel have recently changed january 2011it used to have a way to implement pause on hover with autoscrollwith the new version i cannot solve how to get autoscroll to stop on hoveri would like the scroll to stop on mouseover and start again on mouseoutany suggestionsexample code is here jcarousel here githubcomjsorjcarousellink to jquery javascript to load thumbs here,['jquery'] +237874,getting the widthheight of a layout in android i am wondering how to measure the dimensions of a view in my case it is aan absolute layout i have read the answers concerning those questions but i still do not get it i am fairly new to programming so maybe it is just me this is my codepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain absolutelayout layoutbase absolutelayout findviewbyidridlayoutbase drawoval public void drawoval int screenwidth int screenheight absolutelayout layoutbase absolutelayout findviewbyidridlayoutbase int screenwidth layoutbasegetwidth int screenheight layoutbasegetheight logimyactivity screenwidth screenwidth screenheight screenheight coordinates c new coordinatesbuttonsizescreenwidthscreenheight some code viewgroup layoutbase addviewmybutton new absolutelayoutlayoutparamsbuttonsize buttonsize cmx cmy mybuttonsetonclicklistenernew viewonclicklistener public void onclickview v showtextmybutton public void showtextview button int x findviewbyidlayoutgetwidth int y findviewbyidlayoutgetheight toast message toastmaketextthis x x toastlength short messageshow the getwidth command works great in showtext but it does not in drawoval i know it looks a bit different there but i also used the int x findviewbyidlayoutgetwidth version in drawoval and xy are always 0 i do not really understand why there seems to be no widthheight at that earlier point even if i actually draw a button on the absolute layout getwidth returns 0 oviously i want to measure the sizes in drawovali would appreciate any helpthanks,['android'] +237891,xcode c development clarification needed i absolutely love the way xcode offers insight into possible available member functions of the language and would prefer to use it relative to say text mate if not for an oddity i noticed todaywhen string s test string the only available substr signature is as shownfrom what i understand however and what i see online the signature should bestring substr size t pos 0 size t and npos constindeed ssubstr12 is both understood and works in xcodewhy does it not show when i try to method complete ctrlspace,['c++'] +237906,how to attach the rubymine ide debugger to a shell process i want to use rubymines ide debugger to debug a ruby process running in the command shell as it is spawned eg by rails consolei have gotten great mileage out of the debugger when running the web server from within rubymine or test suites also run from within rubyminehowever if the process is not started by rubymine i am at a loss of how to attach the debuggeri am using version rubymine 324 on ubuntu with sun java 160 26 ruby ree 187 and the latest debug gemsrubydebugbase 0104rubydebugide 0417beta8thoughts,['ruby'] +237917,linq query to get shared items in a sublist i have a class that has a property which is a list i will name this class a then i have a listai need a linq for objects to get all the objects b that are present on all the items on the listaexample to clarifyvar list new lista new a b new listb b1 b2 b3 b4 new a b new listb b3 b4 b5 b6 new a b new listb b2 b3 b4 b5 b6 the query must return the objects b3 and b4 because are the only ones contained on all the lista objects,"['c#', '.net']" +237933,how to handle up button how to handle up button sdk version 11 i am referring to the one at the top of screen that holds the application iconin android design articles it was named as up button but i did not found it or similar in keyevent fields,['android'] +237934,implementing a composite pattern using mvcbackbonejs my webapp has a composite structure ie each category collection can contain a mixture of individual items and other categories as its rowsnodeschildren not sure of the correct terminology here in actual fact it is a little bit simpler than that as each collection is represented by a model category so essentially each category collection has both item models and category models as its childrenin general is this an advisable way to implement this structure using mvc more specifically in backbonejs is it possible for a collection to have a model factory taking the json and calculating which model to generate based on the jsons structure instead of a static model property,['javascript'] +237945,google chrome sync check if enabled via apiextension is it possible to programmatically check if chrome sync is configured in google chromethe reason i ask is that i am coding an extension for chrome that depends on chrome sync and would like to checkinform the user if it is not configuredbefore posting this question i checked the obvious places chrome extension apis stackexchange and google but so far i have not had any luckif anyone has an ideasolution i would appreciate the helpcheers,['javascript'] +237947,how to get doxygen to produce call caller graphs for c functions i have spent some time reviewing the docs and going through my doxy config file from end to end i cut doxygen loose on my config file and it produces documentation and indices for structs and cpp classes but i do not see call or caller graphs for the multitude of c functions in my source treecan anybody tell me how to configure doxygen to produces these call and caller trees i do have graphviz installed,['c'] +237954,sorting sort array based on multiple conditions in ruby i have a mulitdimensional array like so name age date gender name age date gender i am wondering the best way to sort this array based on multiple conditionsfor instance how would i sort based on age first then by namei was messing around with the sort method like soarraysort ab a1 a0 b1 b0 besides that i do not really understand this syntax i am not getting the results i would expect should i be using the sort method should i be individually comparing results by mapping the array,['ruby'] +237960,matplotlib problems plotting logged data and setting its xy bounds i am using log plots as follows in matplotlib roughly as followspltscatterx y use log scalespltgcaset xscalelogpltgcaset yscalelog set xy limitspltxlim1 3pltylim1 3the first problem is that without xy limits matplotlib sets scales such that most of the data is not visible for some reason it does not use the minimum and maximum values along the x and y dimensions so the default plot is extremely misleadingwhen i do set the limits manually using pltxlim pltylim which i interpret to be 1 to 3 in log10 units ie 110th to 30 i get a plot like the one attachedthe axes labels here do not make sense it goes from 101 to 103 whats going on herei am including a more detailed example below that shows all these problems with dataimport matplotlibimport matplotlibpyplot as pltfrom numpy import x array58 0 20 2 2 0 12 17 16 6 257 0 0 0 0 1 0 13 25 9 13 94 0 0 2 42 83 0 0 157 27 1 80 0 0 0 0 2 0 41 0 4 0 10 1 4 63 6 0 31 3 5 0 61 2 0 0 0 17 52 46 15 67 20 0 0 20 39 0 31 0 0 0 0 116 0 0 0 11 39 0 17 0 59 1 0 0 2 7 0 66 14 1 19 0 101 104 228 0 31y array60 0 9 1 3 0 13 9 11 7 177 0 0 0 0 1 0 12 31 10 14 80 0 0 2 30 70 0 0 202 26 1 96 0 0 0 0 1 0 43 0 6 0 9 1 3 32 6 0 20 1 2 0 52 1 0 0 0 26 37 44 13 74 15 0 0 24 36 0 22 0 0 0 0 75 0 0 0 9 40 0 14 0 51 2 0 0 1 9 0 59 9 0 23 0 80 81 158 0 27c 001pltfigurefigsize53s pltsubplot1 3 1pltscatterx c y cplttitleunloggeds pltsubplot1 3 2pltscatterx c y cpltgcaset xscalelog basex2pltgcaset yscalelog basey2plttitleloggeds pltsubplot1 3 3pltscatterx c y cpltgcaset xscalelog basex2pltgcaset yscalelog basey2pltxlim2 20pltylim2 20plttitlelogged with wrong xlimylimpltsavefigtestpngthis produces the plot belowin first subplot from left we have the raw unlogged data in second we have logged values default view in third we have logged values with xy lims specified my questions arewhy are the default xy bounds for the scatter plot wrong the manual says it is supposed to use the min and max values in the data but this is obviously not the case here it picked values that hide the vast majority of datawhy is it that when i set the bounds myself in third scatter plot from left it reverses the order of the labels showing 28 before 25 it is very confusingfinally how can i get it so that the plots are not squished like that by default using subplots i wanted these scatter plots to be squareedit thanks to joe and honk for reply if i try to adjust subplots like this to be squarepltfigurefigsize53 dpi10s pltsubplot1 2 1 adjustablebox aspectequalpltscatterx c y cplttitleunloggeds pltsubplot1 2 2 adjustablebox aspectequalpltscatterx c y cpltgcaset xscalelog basex2pltgcaset yscalelog basey2plttitleloggedi get the result belowhow can i get so that each plot is square and aligned with each other it should just be a grid of square all equal sizes edit 2to contribute something back here is how one would take these log 2 plots and make the axes appear with their nonexponent notationimport matplotlibfrom matplotlibticker import funcformatterdef log 2 productx pos return 2f xc 001pltfigurefigsize105 dpi100s1 pltsubplot1 2 1 adjustablebox aspectequalpltscatterx c y cplttitleunloggedplottingaxes squares1s2 pltsubplot1 2 2 adjustablebox aspectequalmin x max x minx c maxx cmin y max y miny c maxy cplottingaxes squares2pltxlimmin x max xpltylimmin y max ypltgcaset xscalelog basex2pltgcaset yscalelog basey2pltscatterx c y cformatter funcformatterlog 2 products2xaxisset major formatterformatters2yaxisset major formatterformatterplttitleloggedpltsavefigtestpngthanks for your help,['python'] +237967,how to select sum or 0 if no records exist i need to write a query that returns the sum of all values that meet a certain criteria but the query needs to return 0 if no rows are found rather than null for exampletab descr num hello there 5 hi there 10 hello 10 hi there 15 this queryselect sumnum as val from tab where descr like helloshould and does return 15 howeverselect sumnum as val from tab where descr like greetingsshould return 0 but does return nullcan someone explain if this is possible,['mysql'] +237972,is it ok to have one instance of sqliteopenhelper shared by all activities in an android application would it be ok to have a single instance of sqliteopenhelper as a member of a subclassed application and have all activities that need an instance of sqlitedatabase get it from the one helper,"['java', 'android']" +237985,why typeid returns that int and const int are same types iftypeidint typeidconst int cout same types endlprogram outputsame typesam i missing somethingthese are not same types lol,['c++'] +237994,unescape special characters correctly from the url in rails 303 i am using rails 303 with ree ruby 187 and gem mysql2 026there is a search feature in my project that enable people to use the get method using url or using forms and then generate the url examplei want to searchorigin city arhus denmark and destination city asuncia3n paraguaythey both have a special character a and a3 so the url will be generated like this when someone click the search buttonoriginc5rhus2c20denmarkdestinationasuncif3n2c20paraguayproblemwhen i search that city it is not unescaped like i want i tried using like cgi uri even some gems when i see at the console activerecord received the query like thisparameters destinationasuncii12n paraguay origini12rhus denmark sortnewestcity load 01ms select cities from cities where citiesname i12rhus order by citiesname asccity load 68ms select cities from cities where citiesname asuncii12n paraguay order by citiesname ascconclusion the cities cannot be found but i found an interesting thingwhen i made an error on the file asociated with this function the output will be like this requestparametersdestinationasuncia3nparaguayoriginarhusdenmarksortnewestit is a valid onequestiondo you guys have an idea how to solve this thanks in advance,"['ruby-on-rails', 'ruby']" +237996,what is the difference between new a and anewinstance when should i prefer one over the other what is the purpose of the method shown belowclass a public static a newinstance a a new a return a can someone explain to me the differences between these two calls,"['java', 'android']" +237997,eclipse cdt indexing and stdunique ptr i am using stdunique ptr in this piece of code which compiles and runs as i expected stdstringstream outout stdsetw3 stdsetfill0 istdunique ptrstdstring snew stdstringoutstrsinsertsend2 1 return stdmoveshowever i am getting error messages from eclipse cdt at the fourth line method insert could not be resolved method end could not be resolvedpreviously i was also getting errors on appearances of the name stdunique ptr this was solved by setting the preprocessor symbol gxx experimental cxx0x and rebuilding the index as described in the answer to this questionis there a way to make cdt understand that s is of type stdstring and that it should look in stdstring for sinsert and send ps i am using eclipse 371 and cdt 800201106081058ps2 i would have liked to post this as a comment in the above question but i cannot presumably because i am a new user,['c++'] +238000,mustache scalate vs mustache java i need to pick a mustache rendering engine for a scala project of mine seems like the only two choices are mustachejava and scalate are there any comparisons which one is the more stableperformant of the two,['java'] +238025,how to make mysql work on grails 20 grails 20 seems to have some changes to datasourcegroovy and i do not seem to be able to get mysql running as it was in 137i did grails installdependency mysqlmysqlconnectorjava5116 rather than just dumping the jar in lib i hear this is the way to do it these dayshere is what i have replaced in my datasourcegroovydriverclassname orgh2driverurl jdbch2memdevdbmvcctruewithdriverclassname commysqljdbcdriverurl jdbcmysqllocalhost3306dbnamerautoreconnecttruechanging of course the username password and dbnamer to valid entries what am i doing wrong is there a grails 20 tutorial that covers setting up mysqli get this monster error loading grails 200 configuring classpath environment set to development packaging grails application compiling 1 source files running grails application error 20120116 213910134 thread9 error contextgrailscontextloader error executing bootstraps error creating bean with name transactionmanagerpostprocessor initialization of bean failed nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name transactionmanager cannot resolve reference to bean sessionfactory while setting bean property sessionfactory nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name sessionfactory cannot resolve reference to bean hibernateproperties while setting bean property hibernateproperties nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name hibernateproperties cannot resolve reference to bean dialectdetector while setting bean property properties with key hibernatedialect nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name dialectdetector invocation of init method failed nested exception is orgspringframeworkjdbcsupportmetadataaccessexception error while extracting databasemetadata nested exception is orgapachecommonsdbcpsqlnestedexception cannot load jdbc driver class commysqljdbcdrivermessage error creating bean with name transactionmanagerpostprocessor initialization of bean failed nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name transactionmanager cannot resolve reference to bean sessionfactory while setting bean property sessionfactory nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name sessionfactory cannot resolve reference to bean hibernateproperties while setting bean property hibernateproperties nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name hibernateproperties cannot resolve reference to bean dialectdetector while setting bean property properties with key hibernatedialect nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name dialectdetector invocation of init method failed nested exception is orgspringframeworkjdbcsupportmetadataaccessexception error while extracting databasemetadata nested exception is orgapachecommonsdbcpsqlnestedexception cannot load jdbc driver class commysqljdbcdriver line method 334 innerrun in javautilconcurrentfuturetasksync 166 run in javautilconcurrentfuturetask 10 runworker in javautilconcurrentthreadpoolexecutor 603 run in javautilconcurrentthreadpoolexecutorworker 679 run in javalangthreadcaused by beancreationexception error creating bean with name transactionmanager cannot resolve reference to bean sessionfactory while setting bean property sessionfactory nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name sessionfactory cannot resolve reference to bean hibernateproperties while setting bean property hibernateproperties nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name hibernateproperties cannot resolve reference to bean dialectdetector while setting bean property properties with key hibernatedialect nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name dialectdetector invocation of init method failed nested exception is orgspringframeworkjdbcsupportmetadataaccessexception error while extracting databasemetadata nested exception is orgapachecommonsdbcpsqlnestedexception cannot load jdbc driver class commysqljdbcdriver 334 innerrun in javautilconcurrentfuturetasksync 166 run in javautilconcurrentfuturetask 10 runworker in javautilconcurrentthreadpoolexecutor 603 run in javautilconcurrentthreadpoolexecutorworker 679 run in javalangthreadcaused by beancreationexception error creating bean with name sessionfactory cannot resolve reference to bean hibernateproperties while setting bean property hibernateproperties nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name hibernateproperties cannot resolve reference to bean dialectdetector while setting bean property properties with key hibernatedialect nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name dialectdetector invocation of init method failed nested exception is orgspringframeworkjdbcsupportmetadataaccessexception error while extracting databasemetadata nested exception is orgapachecommonsdbcpsqlnestedexception cannot load jdbc driver class commysqljdbcdriver 334 innerrun in javautilconcurrentfuturetasksync 166 run in javautilconcurrentfuturetask 10 runworker in javautilconcurrentthreadpoolexecutor 603 run in javautilconcurrentthreadpoolexecutorworker 679 run in javalangthreadcaused by beancreationexception error creating bean with name hibernateproperties cannot resolve reference to bean dialectdetector while setting bean property properties with key hibernatedialect nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name dialectdetector invocation of init method failed nested exception is orgspringframeworkjdbcsupportmetadataaccessexception error while extracting databasemetadata nested exception is orgapachecommonsdbcpsqlnestedexception cannot load jdbc driver class commysqljdbcdriver 334 innerrun in javautilconcurrentfuturetasksync 166 run in javautilconcurrentfuturetask 10 runworker in javautilconcurrentthreadpoolexecutor 603 run in javautilconcurrentthreadpoolexecutorworker 679 run in javalangthreadcaused by beancreationexception error creating bean with name dialectdetector invocation of init method failed nested exception is orgspringframeworkjdbcsupportmetadataaccessexception error while extracting databasemetadata nested exception is orgapachecommonsdbcpsqlnestedexception cannot load jdbc driver class commysqljdbcdriver 334 innerrun in javautilconcurrentfuturetasksync 166 run in javautilconcurrentfuturetask 10 runworker in javautilconcurrentthreadpoolexecutor 603 run in javautilconcurrentthreadpoolexecutorworker 679 run in javalangthreadcaused by metadataaccessexception error while extracting databasemetadata nested exception is orgapachecommonsdbcpsqlnestedexception cannot load jdbc driver class commysqljdbcdriver 334 innerrun in javautilconcurrentfuturetasksync 166 run in javautilconcurrentfuturetask 10 runworker in javautilconcurrentthreadpoolexecutor 603 run in javautilconcurrentthreadpoolexecutorworker 679 run in javalangthreadcaused by sqlnestedexception cannot load jdbc driver class commysqljdbcdriver 1429 createconnectionfactory in orgapachecommonsdbcpbasicdatasource 1371 createdatasource in 1044 getconnection in 334 innerrun in javautilconcurrentfuturetasksync 166 run in javautilconcurrentfuturetask 10 runworker in javautilconcurrentthreadpoolexecutor 603 run in javautilconcurrentthreadpoolexecutorworker 679 run in javalangthreadcaused by classnotfoundexception commysqljdbcdriver 217 run in javaneturlclassloader1 205 findclass in javaneturlclassloader 321 loadclass in javalangclassloader 266 loadclass in 1420 createconnectionfactory in orgapachecommonsdbcpbasicdatasource 1371 createdatasource in 1044 getconnection in 334 innerrun in javautilconcurrentfuturetasksync 166 run in javautilconcurrentfuturetask 10 runworker in javautilconcurrentthreadpoolexecutor 603 run in javautilconcurrentthreadpoolexecutorworker 679 run in javalangthread,['mysql'] +238029,get plain text from a qlabel with rich text i have a qlabel that contains rich texti want to extract just the actual visible text from the qlabel and none of the code for formattingi essentially need a function similiar to the toplaintext method of other qt widgetsi can not simply call text and string manipulate away the html tags as suggested in this thread get plain text from qstring with html tags since the returned qstring contains all the doctype html public w3cdtd html 40en nonsensehow do i extract the plain texti am open to any method even if indirect eg preexisting functions that convert html to plain textthanks specspython 272pyqt4windows 7,['python'] +238034,how to detect ie7 and ie8 using jquerysupport how can i detect ie 7 and ie 8 using jquerysupport propertiesis it possible to detect the browser versions using jquerysupport or just those blah blah blah browser features,['jquery'] +238054,how do i make a custom validation for uniqueness in core data i have an entity in core data which has an attribute that needs to be unique there is no way to set this in the visual interface i assume i need to create a custom class that inherits from nsmanagedobject and then write my own validation methodi successfully created the custom class by selecting the entities in the visual editor and choosing file new new file nsmanagedobject subclass i use this to add creation timestamps so i know it worksbut now what which methods do i needthe nsmanagedobject reference guide tells me to implement methods of the form validateerror but does not provide an examplesimilar questions here and here but i need a bit more help a complete example would be awesome but any help is much appreciated,['ios'] +238065,how to sort a datagridview by 2 columns how do i sort a datagridview by two columns ascending i have two columns day and statusif i need to sort by one column i dothisdatagridview1sort thisdatagridview1columnsday listsortdirectionascendingbut for two,['c#'] +238066,how to set password as pixels of image in androidcued click point or grapical password am creating an login application where am going to make the password as pixels of imageslet me more specific i have 3 category animalscarbabys each category contain the there imagesnow the user can select pictures from this category and select any portion of the image and can set the password example in animals i select the eye of a lion as the first password like that i can select as many passwords as i can now how can i implement this method can any one give me some ideas or any source code so that i can implement this idea,['android'] +238078,how to increase the space between the elements in linearlayout in android in my application i had used linearlayout inside that i am having 3 edittext elements now i want to increase the spacepadding between the edittext element is it possible,['android'] +238088,immutable vs unmodifiable collection from the collections framework overview collections that do not support modification operations such as add remove and clear are referred to as unmodifiable collections that are not unmodifiable are modifiablecollections that additionally guarantee that no change in the collection object will be visible are referred to as immutable collections that are not immutable are mutablei cannot understand the thistinctionwhat is the difference between unmodifiable and immutable here,['java'] +238089,convert set to list without creating new list i am using this code to convert a set to a listmapstring list mainmap new hashmapstring listforint i0 isomethingsize i set set getset return different result each time list listofnames new arraylistset mainmapputdifferentkeynamelistofnamesi want to avoid creating a new list in each iteration of the loop is that possible,['java'] +238090,yii framework and android application i like to raise some questions regrading yii framework and android applications i am going to build a mobile application in android platform and implementing yii framework as server side i like to know how much yii framework supports android platform are yii framework web services fully compatible with androidand if can anyone suggest some tutorial or useful information that will be very useful to me,['android'] +238107,check if key exists in json array using jquery i have done ajax validation and validated message is returned as a json array therefore i need to check whether the keys like name and email are in that json arraynameisemptyvalue is required and cannot be empty emailisemptyvalue is required and cannot be emptyonly if the key name is present i need to write an error message to the name fieldfollowing is the code to thisplay an error if fields is enteredifobjnameisempty nameafterc1label classerror objnameisemptylabel ifobjemailisempty emailafterc4label classerror objemailisemptylabelbut if the name field is entered it will not be in json arrayso the checking statement ifobjnameisempty will result in an error objname not found it is not necessary to have key name in the array at same time i need to check for this to thisplay the error if the array possesses the key name,['jquery'] +238123,hardware support from a web application i have a web application running with support for some specific pieces of hardware this is achieved in the following stepsuser runs a small installer that places java files and a coupleothers on the client machine the main piece is a jar called hardwaremanageruser visits web app the web app runs a java applet which due toa javapolicy file placed during the install has permission tointeract with the client machine outside the browser sandboxthe applet checks to make sure the hardwaremanager is runningand if not runs a command to start ituser interacts with the web app which sends commands to the applet viajavascript the applet then writes commands to a text fileon the client machine the text file is constantly monitored by thehardwaremanager which runs any commands it reads inthis works but seems clunky i have a couple ideas on how to improve it but i do not know which if any are even worth tryingwould it be better to set up the hardwaremanager as a socketserver and have the applet connect directly to it rather than going through text files is that even possible is there a way to eliminate the applet altogether and have the javascript talk directly to the hardwaremanager maybe by writing the hardwaremanager to be a local http server what port should it run on do javascript xss limitations fit in here somewhere,"['java', 'javascript']" +238132,how to getelementbyid using dom i am having part of html page given below and want to extract the content of div tag its id is hiddendivhl using dom parserpart of a html pagediv idhiddendivhl stylethisplaynonecatid882newsid123069innersep cmsgall content201212012 1thumbimg117 jan 2012 0221787jpginnersepa2 a3a2a2a2 a2a3a2 a2a2a2 a2a2a3a2 a2a234a2a2outersepso far i have used the below code but i am unable to use getelementbyidhow to do thatdom parser try url url new url androidphphome1catid882newsid27593 documentbuilderfactory dbf documentbuilderfactorynewinstance documentbuilder db dbfnewdocumentbuilder document doc dbparsenew inputsourceurlopenstream docgetdocumentelementnormalize nodelist nodelist docgetelementsbytagnameitem assign textview array lenght by arraylist size name new textviewnodelistgetlength website new textviewnodelistgetlength category new textviewnodelistgetlength for int i 0 i nodelistgetlength i node node nodelistitemi namei new textviewthis element fstelmnt element node nodelist namelist fstelmntgetelementsbytagnamehiddendivhl element nameelement element namelistitem0 namelist nameelementgetchildnodes nameisettextname node namelistitem0getnodevalue layoutaddviewnamei catch exception e systemoutprintlnxml pasing excpetion e set the layout view to thisplay setcontentviewlayout,"['java', 'android']" +238140,how to delete a file from phptemp wrapper in php i am using an inmemory or rather temp inmemory file to load an image from an external url into a gd resourcefile phptempimgcopyuri filesrc img imagecreatefromjpegfilehowever as i understand it this file remains in memory even though i have no use for it after imagecreatefromjpegis there a way to free memory used by a phptemp wrapper fileor atleast signal that the file is no longer used,['php'] +238156,ups api php end point url i have downloaded a php sdk for the ups api i have the following code and have no idea what an end point url is the documentation does not provide any information on what this is configuration access 0c81234564c2567 userid leannetest passwd 456hththd8hf acceschemafile schemasaccessrequestxsd requestschemafile schemasraterequestxsd responseschemafile schemasrateresponsexsd endpointurl add url here outputfilename xoltresultxmlcan anyone help,['php'] +238165,ensuring only a single formula could ever apply to 4 random elements i have a list of formulae for combining elementsa b c xd e f yg h i zi want to ensure that given any random 4 elements there will never be more than 1 applicable formula for example the formulae below should not be allowed as if i get elements a b c and d then both are applicablea b c xb c d yevery formula will consist of 3 elements on the lhs and it is the lhs that i want to enforce the rule on a the elements are sortable if that helpsan alternative equivalent problemi have a list of an array of 3 elements listelement3 how do i ensure that no 2 elements appear in more than one arraywhat would be a reasonably efficient runtime speed way of doing this for a large number of elements and a large number for formulae beyond brute forcing,['c#'] +238172,using pytables which is more efficient scipysparse or numpy dense matrix when using pytables there is no support as far as i can tell for the scipysparse matrix formats so to store a matrix i have to do some conversion egdef store sparse matrixself grp1 selfgetfilehandlecreategroupselfgetgroup m selfgetfilehandlecreatearraygrp1 data mtocsrdata selfgetfilehandlecreatearraygrp1 indptr mtocsrindptr selfgetfilehandlecreatearraygrp1 indices mtocsrindicesdef get sparse matrixself return sparsecsr matrixselfgetgroupmdata selfgetgroupmindices selfgetgroupmindptrthe trouble is that the get sparse function takes some time reading from thisk and if i understand it correctly also requires the data to fit into memorythe only other option seems to convert the matrix to dense format numpy array and then use pytables normally however this seems to be rather inefficient although i suppose perhaps pytables will deal with the compression itself,['python'] +238211,pure css speech bubble with border so i am working on a pure css speech bubble but i would like to have the border surround the entire speech bubble as seen here i am using the following markupdiv claspeechbubblepthis is a speech bubble created using only css no images to be found herepdivand i have so far styled it as followsspeechbubble margin 3emwidth 320pxpadding 10pxbackgroundcolorrgba250 250 250 095color 6font normal 12px segoe ui arial sansserifmozborderradius 10pxwebkitborderradius 10pxborderradius 10pxborder 10px solid rgba095speechbubblebeforecontent border solid 20px transparent set all borders to 10 pixels width bordertop 0 we do not need the top border in this case borderbottomcolorrgba250 250 250 095width 0height 0overflow hiddenthisplay blockposition relativetop 30px borderwidth of the after element padding of the root element margin autospeechbubble p margintop 15pxfontsize 125emas you can see i can only add a border to the content box speechbubble but not the callout speechbubblebefore my border will also need to be transparant not sure if this matters but it is something to bear in mind any advice,['css'] +238229,how to convert byte to bitmapimage i need help i have this method to get a bitmapimage from a bytepublic bitmapsource bytetobitmapsourcebyte image bitmapimage imagesource new bitmapimage using memorystream stream new memorystreamimage streamseek0 seekoriginbegin imagesourcebegininit imagesourcestreamsource stream imagesourcecacheoption bitmapcacheoptiononload imagesourceendinit return imagesourceimagesourceendinit throws an error we found no imaging component suitable to complete this operation,['c#'] +238241,conditions in loops best practices say i have a loop like thisfor int i 0 i someint i if i somecondition dosomething continue dosomeotherstuffversusfor int i 0 i someint i if i somecondition dosomething else dosomeotherstuff is there any reason to use one over the other or is it just personal preferencethe main language i am asking this for is java but i guess it also applies to most others,"['java', 'c++']" +238267,class and method level generic type constraints interaction consider the following classpublic class derivedclasspooltbase where tbase class public tbase gettype componenttype not important but you get the idea return activatorcreateinstancecomponenttype as tbase public tderived somemethodtderived where tderived tbase return gettypeoftbase as tderived note that i have restricted the tbase generic class argument to be a class where tbase classi have also restricted the tderived generic method argument to be tbase or something derived from that where tderived tbasei get an error on the as tderived linethe type parameter tderived cannot be used with the as operator because it does not have a class type constraint nor a class constrainti understand that to prevent the error i need to add the constraint class so i would getwhere tderived class tbasewhy do i have to do this when tbase is already constrained to be a class and tderived is constrained to be a tbase or derived from it,['c#'] +238272,short form for java if statement i know there is a way for writing java if statement in short formif citygetname null name citygetname else namenadoes anyone know how to write short form for above 5 lines into one line,['java'] +238340,what are the technical reasons to avoid injecting the service container instead of individual services normally when i need to inject one or more services into another service i explicitly inject each one however i have a situation where injecting the service container itself will really make things easier i know this is not a recommended practice but i am curious what the technical reasons are for thiscouraging this is it something legitimate like it is too resource intensive or a more personal feeling that it is too messy,['php'] +238346,standard or free posix path manipulation c library is there any standard or widely used simple posix path manipulation library for c path join filename stripping etc actually because i am mostly working under windows i currently use shlwapi path functionsis there any equivalent set of functions available for posix paths,['c'] +238380,is element before or after another element in dom is there a means of detecting whether an element appears before or after another element in markup this is regardless of position in dom it could be a child a sibling a parent or a parents parent this is a general question so no markup to shareto clarify this is in regards to the elements position in markup not its thisplay position now that i think about it my question is a bit strange because if you have element x and element y then you can have these scenariosin regards to yx y aftery beforex xy x not really before or after is it,"['javascript', 'jquery']" +238384,constructing a url with parameters using jquery i have for example the following url stored in a global variablevar myurl then a function has to add let us say another parameter called column how would that function add parameters to a preexisting url string using jqueryexample of the expected generated stringcolumn9the problem is that myurl could also be justvar myurl notice that there are not preexisting parameters,"['javascript', 'jquery']" +238385,how can i get xcode to link and debug an app with boost filesystem tldrobjectivec app linked with static library that dynamic links boost filesystem app can be run from output directory using terminal but trying to run from xcode debugger or finder gives error dyld library not loaded libboost filesystemdylib snip reason image not foundproblemin my xcode project i have a structure that looks like thismainproject objectivec static lib that uses filesystem cto get everything to link i added libboost system and libboost filesystem dylibs to the link binary with libraries build phase in mainprojectwhen i try to run the app from either xcode or finder i getsharedlibrary applyloadrules allwarning unable to read symbols for libboost filesystemdylib file not foundwarning unable to read symbols from libboost filesystemdylib not yet mapped into memorywarning unable to read symbols for libboost systemdylib file not foundwarning unable to read symbols from libboost systemdylib not yet mapped into memoryswitching to process 43957 thread 0x0dyld library not loaded libboost filesystemdylib referenced from usersteelelibrarydeveloperxcodederiveddatamainprojectdqrhyuarllykslftblocjdzxlranbuildproductsdebugmainprojectappcontentsmacosmainproject reason image not foundi added a build stage to copy the dylibs to the frameworks directory in the bundle this does not help i changed this to copy them to the executables directory which also did not helphaving them in the executables directory does allow me to run the app from terminalhow can i get the app to find the dylibs when run from finderxcodebackground infoi am using xcode 42 on lion and currently targeting lion only i built my shared libraries for filesystem like thisb2 threadingmulti macosxversion107 withfilesystem stagethis creates libboost systemdylib libboost filesystemdylib and also a equivalents in the stagelib directory i am referencing them in the project directly from there,['c++'] +238470,how to import xsd types into root schema this is my existing xsd schema in fooxsd that declares just the typexsschema xmlnsxs version10 targetnamespacefoo xscomplextype namealpha skipped xscomplextypexsschemathis is another schema that declares the elementxsschema xmlnsxs version10 targetnamespacefoo xsimport schemalocationfooxsd namespacefoo xselement namerootelement typealphaxsschemathis is what i am getting from sax parser in javathe namespace attribute foo of an import element information item must not be the same as the targetnamespace of the schema it exists inwhat am i doing wrong,['java'] +238501,thread pool handling duplicate tasks i want to be executing some different tasks in parallel but have the concept that if a task is already queued or is currently processing it will not get requeued i have read up a little on the java api and have come up with the code below which seems to workcan anybody shed light on whether the method i am using is the best approach any dangers thread safety or better ways to do thiscode is as belowimport javautilhashmapimport javautilconcurrentfutureimport javautilconcurrentlinkedblockingqueueimport javautilconcurrentthreadpoolexecutorimport javautilconcurrenttimeunitpublic class testexecution implements runnable string key1 string key2 static hashmaptestexecution future executions new hashmaptestexecution future static linkedblockingqueuerunnable q new linkedblockingqueuerunnable static threadpoolexecutor tpe new threadpoolexecutor2 5 1 timeunitminutes q public static void mainstring args try executenew testexecutiona a executenew testexecutiona a executenew testexecutionb b threadsleep80 executenew testexecutionb b catch interruptedexception e eprintstacktrace static boolean executetestexecution e systemoutprintlnhandling ekey1ekey2 if executionscontainskeye future f future executionsgete if fisdone systemoutprintlnprevious execution has completed executionsremovee else systemoutprintlnprevious execution still running return false else systemoutprintlnno previous execution future f tpesubmite executionspute f return true public testexecutionstring key1 string key2 thiskey1 key1 thiskey2 key2 public boolean equalsobject obj if obj instanceof testexecution testexecution t testexecution obj return key1equalstkey1 key2equalstkey2 return false public int hashcode return key1hashcodekey2hashcode public void run try systemoutprintlnstart processing key1key2 threadsleep40 systemoutprintlnfinish processing key1key2 catch interruptedexception e eprintstacktrace follow up to comment belowthe plan is that triggering the tasks to execute will be handled by cron calling restful web service for example below is the setup for one task triggered at 930 every day plus another scheduled every two minutes 02 restclientpl key11 key12 30 09 restclientpl key21 key22in this case if task key11key12 is running or already queued to run i do not want to queue another instance i understand we have other options for scheduling however we tend to use cron for other tasks so i want to try to keep thissecond update in response to comments so far i have rewritten the code could you comment on any issues with the following updated solutionimport javautilconcurrentlinkedblockingqueuepublic class testexecution implements runnable string key1 string key2 static testthreadpoolexecutor tpe new testthreadpoolexecutornew linkedblockingqueuerunnable public static void mainstring args try tpeexecutenew testexecutiona a tpeexecutenew testexecutiona a tpeexecutenew testexecutionb b threadsleep80 tpeexecutenew testexecutionb b catch interruptedexception e eprintstacktrace public testexecutionstring key1 string key2 thiskey1 key1 thiskey2 key2 public boolean equalsobject obj if obj instanceof testexecution testexecution t testexecution obj return key1equalstkey1 key2equalstkey2 return false public int hashcode return key1hashcodekey2hashcode public void run try systemoutprintlnstart processing key1key2 threadsleep40 systemoutprintlnfinish processing key1key2 catch interruptedexception e eprintstacktrace import javautilcollectionsimport javautilhashsetimport javautilsetimport javautilconcurrentlinkedblockingqueueimport javautilconcurrentthreadpoolexecutorimport javautilconcurrenttimeunitpublic class testthreadpoolexecutor extends threadpoolexecutor setrunnable executions collectionssynchronizedsetnew hashsetrunnable public testthreadpoolexecutorlinkedblockingqueuerunnable q super2 5 1 timeunitminutes q public void executerunnable command if executionscontainscommand systemoutprintlnprevious execution still running return else systemoutprintlnno previous execution superexecutecommand executionsaddcommand protected void afterexecuterunnable r throwable t superafterexecuter t executionsremover,['java'] +238504,is a nonblocking singlethreaded asynchronous web server like nodejs possible in net i was looking at this question looking for a way to create a singlethreaded eventbased nonblocking asynchronous web server in netthis answer looked promising at first by claiming that the body of the code runs in a single threadhowever i tested this in cusing systemusing systemiousing systemthreadingclass program static void main consolewritelinethreadcurrentthreadmanagedthreadid var sc new synchronizationcontext synchronizationcontextsetsynchronizationcontextsc var path environmentexpandenvironmentvariables systemrootnotepadexe var fs new filestreampath filemodeopen fileaccessread filesharereadwrite 1024 4 true var bytes new byte1024 fsbeginreadbytes 0 byteslength ar scpostdummy var res fsendreadar are we in the same thread consolewritelinethreadcurrentthreadmanagedthreadid null null threadsleep100 and the result was1 5so it seems like contrary to the answer the thread initiating the read and the thread ending the read are not the sameso now my question is how do you to achieve a singlethreaded eventbased nonblocking asynchronous web server in net,['c#'] +238516,how to set table column in android i am having some difficulty setting layout parameters of table rows containing text views i want to add some columns to get a good layout i am doing it dynamically in code tablerow textview androidlayout widthwrap content androidlayout heightwrap content androidtextok textview androidlayout widthwrap content androidlayout heightwrap content androidtextbyetablerowi want these two textviews to become two columns and layout on screen accordingly,['android'] +238538,how to read from a text file fastersmarter i want to know if it is possible to read from a text file in a faster and smarter waythis is a typical format of my data in a text filecall this partid1field1 sometextfield2 sometextfield3 sometextfield4 sometextfield5 sometextfield6 sometextfield7 sometextfield8 sometextend id 01 somedata02 somedata48 somedataendcardi have thousands of them in a text fileis it possible to use linq to read it part by part i do not want to loop through every single linewill it be possible for linq to start at id1 and end at endcard the reason for this is that i want to create a object for every parti had something like this in mindstring lines systemiofilereadalinessomefilepathcleaning up the text file of unwanted textvar cleaneduplines from line in lines where linestartswithfield1 linestartswithfield5 linestartswithfield8 select linesplithere i want to linqtotext part by partthis i do not want to doforeach string line in cleaneduplines,"['c#', '.net']" +238557,serialport not receiving any data i am developing program which need to interact with com portsby learning from this qa net serialport datareceived event not firing i make my code like thatnamespace consoleapplication1 class program static serialport comport public static void onserialdatareceivedobject sender serialdatareceivedeventargs args string data comportreadexisting consolewritedatareplacer n static void mainstring args string port com4 int baud 9600 if argslength 1 port args0 if argslength 2 baud intparseargs1 initializecomportport baud string text do string mystring systemioportsserialportgetportnames text consolereadline int stx 0x2 int etx 0x3 comportwritecharconvertfromutf32stx text charconvertfromutf32etx while texttolower q private static void initializecomportstring port int baud comport new serialportport baud comportportname port comportbaudrate baud comportparity paritynone comportstopbits stopbitsone comportdatabits 8 comportreceivedbytesthreshold 9 comportrtsenable true comportdtrenable true comporthandshake systemioportshandshakexonxoff comportdatareceived onserialdatareceived openportcomport public static void openportserialport comport try if comportisopen comportopen catch exception e throw e my problem is datareceived event never gets firedmy program specifications arejust net console programmingi use vspe from my computer has com1 and com2 ports alreadyi created com2 and com4 by using vspei get output result from mystring array com1 com2 com3 com4but i still do not know why datareceived event is not firedupdatedunfortunately i still could not make to fire datareceived event in any wayso i created new project by hoping that i will face a way to solveat that new project just console application i created a classpublic class mytest public serialport spcom4 public mytest spcom4 new serialport ifthisserialportopenspcom4 4 thissendtoportspcom4 com test private bool serialportopensystemioportsserialport objcom string portname bool blnopenstatus false try objcomportname com portname objcombaudrate 9600 objcomdatabits 8 int serparity 2 int serstop 0 switch serparity case 0 objcomparity systemioportsparityeven break case 1 objcomparity systemioportsparityodd break case 2 objcomparity systemioportsparitynone break case 3 objcomparity systemioportsparitymark break switch serstop case 0 objcomstopbits systemioportsstopbitsone break case 1 objcomstopbits systemioportsstopbitstwo break objcomrtsenable false objcomdtrenable false objcomhandshake systemioportshandshakexonxoff objcomopen blnopenstatus true catch exception ex throw ex return blnopenstatus private bool sendtoportsystemioportsserialport objcom string strtext try int stx 0x2 int etx 0x3 if objcomisopen strtext objcomwritecharconvertfromutf32stx strtext charconvertfromutf32etx catch exception ex throw ex return true i am not sure that i face good luck or bad luck because this new class could make fire datareceived event which is from older console application that is still running it is miracle to me which i have no idea how this happenlet me tell you more detail so that you could give me suggestion for better wayfinally i created 2 console projectsfirst project is the class which i posted as a question yesterdaysecond project is the class called mytest which could make fire datareceived event from first project at the same time when two of the project is runningcould anyone give me suggestions on how could i combine these two projects as a single project,['c#'] +238560,retrieving info from database i am going to retrieve information from a database using linq but i do not know why i am getting this errorinvalid object name retriveinfosmy class is heretable nameretriveinfospublic class retriveinfo column public string name get set column public string lastname get set columnisprimarykey true public int id get set and then using this line of code to connect and retrieving informationdatacontext dcon new datacontextdata sourcesqlexpressattachdbfilenamefsecond school projectreview sitereview siteapp datareviewdatabasemdfintegrated securitytrueuser instancetruetableretriveinfo retriveinfos dcongettableretriveinfovar c from d in retriveinfos where did 1 select new dname dlastname foreach var a in c responsewriteanametostring alastnametostring,['c#'] +238579,why is a a nil in ruby i watched this video why is a a evaluated to nil if a is not defineda a nilb c q c nil,['ruby'] +238588,get the value of an asphiddenfield using jquery i have two pages from the first page i open a modal with a querystring that holds that value of a client name i then use this to set a hiddenfield on the modal that openedi need a textbox on the new modal to thisplay the value that has been sent through from the first screen i have tried getting the value usingvar hv hidclientfieldvalbut this does not seem to workthis is my hidden fieldasphiddenfield idhidclientname runatserver i set it in the code behind on the page load like thishidclientnamevalue requestquerystringclient name any ideas will be much appreciated,"['jquery', 'asp.net']" +238602,should i use camel case or underscores in python so which is better and whydef my functionordef myfunction,['python'] +238608,what things to be aware of when using the withstatement for own classes i am planning to implement clike constructordestructor functionality to one of my python classes using the handy with statement i have come accross this statement only for file io up to now but i thought it would be rather helpful for connectionbased communication tasks as well say sockets or database connections things that eventually need to be closedin pep 343 linked above it is said that with needs the methods enter and exit and my straightforward implementation of this appears to work as intendedclass myconnection def init self pass def enter self print constructor todo open connections and stuff make the connection available in the withblock return self def exit self args print destructor todo close connections and stuffwith myconnection as c todo do something with c passwhich yields the output as expectedconstructordestructorshould it really be this easy what are the things to consider besides this why do so many libraries apparantly lack this functionality yet have i missed something,['python'] +238619,how to match the ymmddthhmmsstzd timezone format in ruby i would like to check the iso8601 format for the date entered in ruby like start date 20110505 should be matched for the format 20110505t0400 and errors returned accordingly should we use regex here or any method is present for this,"['ruby-on-rails', 'ruby']" +238635,how to print all key and values from hashmap in android i am very new for android development and i am trying to use hashmap in android sample project now am doing sample project for learn android i just store keys and values in hashmap i want to show the keys and their values in editview i followed below code in my sample project but first key and value only printing in editview mapstring string map new hashmapstringstring mapputios 100 mapputandroid 101 mapputjava 102 mapputnet 103 set keys mapkeyset for iterator i keysiterator ihasnext string key string inext string value string mapgetkey textviewsettextkey value in editview ios 100 is only printing i want to print all keys and their value in edittext can anyone please tell me where i am doing wrong thanks in advance,"['java', 'android']" +238642,how to approximate the count of thistinct values in an array in a single pass throught it i have several huge arrays millions members all those are arrays of numbers and they are not sorted and i cannot do that some are uint8 t some uint16 t3264 i would like to approximate the count of thistinct values in these arrays the conditions are followingspeed is very important i need to do this in one pass through the array and i must go through it sequentially cannot jump back and forth i am doing this in c if that is importanti do not need exact counts what i want to know is that if it is an uint32 t array if there are like 10 or 20 thistinct numbers or if there are thousands or millionsi have quite a bit of memory that i can use but the less is used the betterthe smaller the array data type the more accurate i need to be i dont mind stl but if i can do it without it that would be great no boost though sorry if the approach can be easily parallelized that would be cool but its not a mandatory conditionexamples of perfect outputarraya uint32 t 3m members 128 thistinct valuesarrayb uint32 t 9m members 10 thistinct valuesarrayc uint8 t 50k members 25 thistinct valuesarrayd uint8 t 700k members 64 thistinct valuesi understand that some of the constraints may seem illogical but thats the way it isas a side note i also want the top x 3 or 10 most used and least used values but that is far easier to do and i can do it on my own however if someone has thoughts for that too feel free to share themedit a bit of clarification regarding stl if you have a solution using it please post it not using stl would be just a bonus for us we dont fancy it too much however if it is a good solution it will be used,['c++'] +238646,visual c express 2010 shortcut to comment a code block i am looking for the equivalent of vs2010s ctrle ctrlc on express edition,['c#'] +238675,using linq to extract ints from a list of strings i have a liststring and some of these strings are numbers i want to extract this subset into a listint i have done this in quite a verbose looking way as below but i get the feeling there must be a neater linq way to structure this any ideasliststring mystrs somelistfromsomewherelistint myints new listintforeach string mystr in mystrs int outint if inttryparsemystr out outint myintsaddoutint obviously i do not need a solution to this it is mainly for my linq education,['c#'] +238692,what is the function of an asterisk before a function name i have been confused with what i see on most c programs that has unfamiliar function declaration for mevoid func namevoid param what does imply for the function my understanding about in a variable type is that it creates a pointer to another variable thus it can be able to track what address at which the latter variable is stored in the memory but in this case of a function i do not know what this asterisk implies,['c'] +238696,strange behavior when casting a float to int in c i have the following simple code int speed1 int62f 10float tmp 62f 10int speed2 inttmpspeed1 and speed2 should have the same value but in fact i have speed1 61speed2 62i know i should probably use mathround instead of casting but i would like to understand why the values are differenti looked at the generated bytecode but except a store and a load the opcodes are the samei also tried the same code in java and i correctly obtain 62 and 62can someone explain this edit in the real code it is not directly 62f 10 but a function call a constant i have the following bytecode for speed 1 il 01b3 ldlocs v 8il 01b5 callvirt instance float32 mypackagemyclassgetspeedil 01ba ldcr4 10il 01bf mulil 01c0 convi4il 01c1 stlocs v 9for speed 2 il 01c3 ldlocs v 8il 01c5 callvirt instance float32 mypackagemyclassgetspeedil 01ca ldcr4 10il 01cf mulil 01d0 stlocs v 10il 01d2 ldlocs v 10il 01d4 convi4il 01d5 stlocs v 11we can see that operands are floats and that the only difference is the stlocldlocas for the virtual machine i tried with monowin7 monomacos and netwindows with the same results,['c#'] +238707,how to use registerhotkey in c i am trying register a hot key i am translating this c codei wrote itusing systemcollectionsgenericusing systemlinqusing systemtextusing systemruntimeinteropservicesnamespace consoleapplication1 class program dllimportuser32dll public static extern bool registerhotkeyintptr hwnd int id uint fsmodifiers int vk dllimportuser32 public static extern bool getmessageref message lpmsg intptr handle uint mmsgfilterinmain uint mmsgfiltermax public const int mod alt 0x01 public const int mod control 0x02 public const int mod shift 0x004 public const int mod norepeat 0x400 public const int wm hotkey 0x312 public const int dsix 0x36 static void mainstring args if registerhotkeyintptrzero 1 mod alt mod norepeat dsix consolewritelinefailed key register message msg new message while getmessageref msg intptrzero 0 0 if msgmessage wm hotkey consolewritelinedo work consolereadline public class message public int message get set but it registerhotkey ever returns false i am not sure about the arguments passed in method intptrzero is for be to equivalent to null and message class to be object required in second argument can someone clarify please any help is very appreciated,"['c#', '.net']" +238725,how to access nested objects with mustache js templating engine i have this json return timeline id 2 self uid 2 username ptamzz file fid 43 file name first name connection fid 4 username tom action viewed your document time 20120116 122303 tags engineering computer science java java library id 1 self uid 2 username ptamzz file fid 41 file name write up connection fid 4 username tom action favorited your document time 20120116 1204 tags design according to the tutorial at sample 6 nested object section you can access dot notation to access the nested objectsfrom the above json i want to retrieve the data like selfusername filefile name etc etcnow i have my template as timeline li selfusername litimelinebut selfusername does not workhow do i retrieve these nested values,['javascript'] +238728,session created but theres no phpsessid in serverhttp cookie i am experiencing some weird problems with session variables on my phpajax online shopping cartwhen i first view the page the session is created and works within the page then when i navigate to another php page within the same directory the session is completely lost whats weird is that this only happens once once the user goes through this process of completely losing their session upon changing page the session works in full across the entire carti started mailing myself var exports of both session and server data on each page view it seems that when a page is first viewed the session exists and contains data however there is no phpsessid generated in the serverhttp cookie variable on navigating to another page the phpsessid gets created and the session will start working but the initial session data of the first page view is lostis there a way to generate a phpsessid if one has not yet been generated for the session or is this typical behaviour and is irrelevant to my random session loss problem i am using php 52every page in the cart starts the exact same waytitletitlekeywordskeywordsdescriptiondescriptionincludeheader cartphpand then at the top of header cartphp there issession startifisset sessionactive sessionactive serverremote addr,"['php', 'mysql']" +238733,get the last day of the month possible duplicatephp last day of the month is there any function like dategetmonthdays or dategetlastdayofmonth in php to get the number of days in a given month or the last day numberstart new datetime20120201end clone start interval last day of the month minus current day in startinterval startgetlastdayofmonth intvalstartformatjendaddnew dateintervalp interval dedit thanks voted to close it is a duplicate sorry for asking,['php'] +238734,is there a way to avoid the linear search on this i have a large pool of objects with starting number and ending number for example9 23 data 0 128 data 235 865 dataassuming that the intervals do not overlap with each other and i am writing a function that takes a number and locate the object that low high contains it say given 3 i want the 3rd objects on the list is there any way i can do this as efficiently as possible short of linear search i was thinking about binary search but having some difficulties of coping with the range check,['python'] +238769,abusing generics to implement a curried composition function in java so after playing around with java generics a bit to get a deeper understanding of their capabilities i decided to try to implement the curried version of the composition function familiar to functional programmers compose has the type in functional languages b c a b a c doing currying arithmetic functions was not too hard since they are just polymorphic but compose is a higher order function and its proven taxing to my understanding of generics in javahere is the implementation i have created so far public class currying public static void mainstring argv basic usage of currying systemoutprintlnaddap3ap4 next lets try 3 4 2 first lets create the 2 function fninteger integer plus2 addap2 next the times 3 function fninteger integer times3 multap3 now we compose them into a multiply by 2 and add 3 function fninteger integer times3plus2 composeapplus2aptimes3 now we can put in the final argument and print the result without compose systemoutprintlnplus2aptimes3ap4 with compose systemoutprintlntimes3plus2apnew integer4 public static abc fnfnbc b c f fnfnab a b g fnac a c compose return new fnfnbc fnfnab fnac public fnfnab fnac apfinal fnbc f return new fnfnab fnac public fnac apfinal fnab g return new fnac public c apfinal a a return fapgapa curried addition public static fninteger fninteger integer add return new fninteger fninteger integer public fnintegerinteger apfinal integer a return new fninteger integer public integer apfinal integer b return a b curried multiplication public static fninteger fninteger integer mult return new fninteger fninteger integer public fnintegerinteger apfinal integer a return new fninteger integer public integer apfinal integer b return a b interface fna b public b apfinal a athe implementations of add mult and compose all compile just fine but i find myself having a problem when it comes to actually using compose i get the following error for line 12 the first usage of compose in maincurryingjava12 apfnjavalangobjectjavalangobject in fnfnjavalangobjectjavalangobjectfnfnjavalangobjectjavalangobjectfnjavalangobjectjavalangobjectcannot be applied to fnjavalangintegerjavalanginteger fnintegerinteger times3plus2 composeapplus2aptimes3i assume this error is because generic types are invariant but i am not sure how to solve the problem from what i have read wildcard type variables can be used to alleviate invariance in some cases but i am not sure how to use it here or even whether it will be usefulthisclaimer i have no intention of writing code like this in any real project this is a fun can it be done kind of thing also i made the variable names brief in defiance of standard java practice because otherwise this example becomes an even more of an incomprehensible wall of text,['java'] +238774,send subview to back i am trying to mimic the facebook ios side menu and have it working however the issue i am having is that i cannot send the sidemenu to the back as thiscussed in another question on so iphone facebook side menu using objective c i am not using the library suggested but instead using the code that was suggested i have voidviewdidload nslogview did load is running activityspinner uiactivityindicatorview alloc initwithactivityindicatorstyleuiactivityindicatorviewstylegray activityspinnerframe cgrectmake00 00 400 400 activityspinnercenter selfviewcenter selfview addsubviewactivityspinner sidemenuview mydelegate sidemenuview alloc init self setsidemenudelegatemydelegate set the delegates currentviewcontroller property so that we can add a subview to this view sidemenudelegate setcurrentviewcontrollerself sidemenu sidemenuview alloc initwithnibnamesidemenuview bundlenil selfview addsubviewmydelegateview selfview sendsubviewtobackmydelegateview super viewdidload selfsearchthisplaycontrollersearchbarscopebuttontitles nil self fetchcustomers do any additional setup after loading the view typically from a nibin my controller where i want the side menu but the view seems to get loaded into the current view instead of just going to the back so it can be seen when i slide the menu overcan someone help me get the mydelegate view to the back,"['iphone', 'objective-c']" +238798,invalid application of sizeof to incomplete type with a struct so i am trying to make a game and i have a struct where i put all the information about the players that is my structstruct player int startingcapital int currentcapital int startingposition int currentposition int activeplayer int canplay and that is my maininclude stdiohinclude stdlibhinclude headerhint mainint argc char argv int sinumofplayers struct player players printfgive the number of players n scanfdnumofplayers players struct player callocnumofplayerssizeofstruct player systempause return 0so as you can see i am asking the user to give the number of players and then i try to allocate the needed memory but i am getting this compiler error that i cannot figure out invalid application of sizeof to incomplete typeplayer,['c'] +238809,ios uiimageview how to handle uiimage image orientation is it possible to setup uiimageview to handle image orientation when i set the uiimageview to image with orientation right it is photo from camera roll the image is rotated to right but i want to show it in proper orientation as it was takeni know i can rotate image data but it is possible to do it more elegant thank you,['ios'] +238822,whats the difference between htmllangen and htmllangen in css the css language pseudoclass to allow us specify different styles for different languages like sohtmllangen foo however this does not work in ie7 so i have been using an attribute selectorhtmllangen foo they seem to do the same thing but are there any subtle differences and if not why does css even have a language pseudoclass when the attribute selector does the exact same thing,['css'] +238827,thisable arrow key scrolling in users browser i am making a game using canvas and javascriptwhen the page is longer than the screen comments etc pressing the down arrow scrolls the page down and makes the game impossible to playwhat can i do to prevent the window from scrolling when the player just wants to move downi guess with java games and such this is not a problem as long as the user clicks on the game i tried the solution from how to thisable page scrolling in ff with arrow keys but i could not get it to work,['javascript'] +238831,what happens if a user exits browser or change page before ajax request is over i am calling a php script over ajax to do some database maintenance if the user closes the page hits back or clicks a link will the php script be fully executed is there a way to do itmaybe if the php script called the exec method or something similar which would in turn call a script via the console as such php varwhttpdocsmaintenancephp,"['php', 'jquery']" +238833,querying compositetype columns in cassandra using hector heres a sample of the scenario i am facing say i have this column family create column family compositetypecf with comparator compositetypeintegertypeutf8type and key validation class utf8type and default validation class utf8typeheres some sample java code using hector as to how i would go about inserting some data into this column family cluster cluster hfactorygetorcreateclustertest cluster 192168169160 keyspace keyspaceoperator hfactorycreatekeyspacecompositetesting cluster composite colkey1 new composite colkey1addcomponent1 integerserializerget colkey1addcomponenttest1 stringserializerget mutatorstring mutator hfactorycreatemutatorkeyspaceoperator stringserializerget mutatorstring addinsertion mutatoraddinsertionrowkey1 compositetypecf hfactorycreatecolumncolkey1 some data new compositeserializer stringserializerget mutatorexecutethis works and if i go to the cassandracli and do a list i get this list compositetypecfusing default limit of 100rowkey rowkey1 column1test1 valuesome data timestamp13269169375470my question now is this how do i go about querying this data in hector basically i would need to query it in a few waysgive me the whole row where row key rowkey1give me the column data where the first part of the column name some integer valuegive me all the columns where the first part of the column name is within a certain range,['java'] +238868,is it possible to emulate nonenumerable properties es5 has a enumerable flag exampleexamplevar getownpropertydescriptor objectgetownpropertydescriptor pd getownpropertydescriptorobjectprototype tostringassertpdenumerable false enumerability has the wrong valuepartial implementationpartial implementation is doable by having objectkeys and objectgetownpropertynames filter out new nonenumerable properties using the shimmed objectdefinepropertyintroductionthis allows for properties to be non enumerable this clearly means that examplefor var key in assertkey tostring i should never printthis allows us to add properties to say objectprototype exampleobjectdefinepropertyobjectprototype touppercasestring value function touppercasestring return thistostringtouppercase enumerable falsefor var key in assertkey touppercasestring i should never printconsolelogtouppercasestring object objectquestionhow can we emulate this in nones5 compliant browsersbrowser compat tablein this case we care about potentially solving this for ie 9 ie8 only works on dom objectsfirefox 36safari 4opera 115 opera 116 solves thisthe es5shim does not have a solution for thisthe es5 shim has a solution for most es5 features that will break your code if it does not workis there any black magic that can be done with propiotory ie only apis maybe with vbscript,['javascript'] +238874,getting a raw unparsed http response are there any straightforward ways to make a http request and get at the raw unparsed response specifically the headers,['python'] +238878,cast via reflection and use of classcast possible duplicatejava classcast vs cast operator i am unsuccessfully trying to find out what does classcast do or what it may be good for in same time i am wondering whether i can somehow cast an object via reflectionfirst i thought something like lines below might have worked wronglyobject o a stringstring str classfornamejavalangstringcastobjectbut without explicit cast it does not workso what is cast method of class class good for and is it somehow possible just with reflection to cast objects so you find the objects class use classforname on it and cast it somehow,['java'] +238898,rails 31 how override inherited resources and permit rails scaffolding to work normally again solution found see commentbuilding a new rails 31 app started with a basic blog entries model to get the hang of it no surprises then i added activeadmin got that working okay with my existing model but now when i try to scaffold a new modeletc with thisrails g scaffold community namestring guidstringeverything seems right views migration except the controller does not have crud options and looks like thisclass communitiescontroller inheritedresourcesbaseendthe problem is that activeadmin uses inherited resources which prevents manual rails scaffolding from working normallydoes anyone know a way to force rails to scaffold correctly despite activeadmin using inherited resources,['ruby-on-rails'] +238901,jasmine mock window object how do i mock window object i am doing firefox extension and i want to use jasmine for javascript testingin my javascript i have function submit var url windowarguments0obviously i have to mock windowarguments0 in jasmine because that object does not exists if not passing any parameter from windowopendialogthis is my attempt to mock it with withitshould submit to server function var localcontext window arguments httplocalhost withlocalcontextbut i still get this error typeerror cannot read property 0 of undefined it is like when the test is run windowarguments0 gets wiped out with the real window because if i do windowarguments0inside the test it prints out httplocalhost correctly but when it comes to submit method it shows the error that windowargument is undefined,['javascript'] +238906,capture image with imagegrabscreen and wamp i am trying to capture a local web page with imagegrabscreen but i only get a black screenshot i tried almost every solution from questions here on so and others sites and nothing worksi am using and done the followingwindows 7 64bitwamp 22a 64bitphp 538gd2 version bundled 2034 compatible is installed and enabledallowed the apache service to interact with the desktopi do not have a secondary thisplay or anythingphp im imagegrabscreen imagepngim myscreenshotpng imagedestroyim and all i get is a black image 1024x768 png,['php'] +238907,where is the documentation for the jqueryeventspecial api for custom events i am creating a fork of the textchange jquery plugin which uses the jqueryeventspecial api to create its own custom events textchange hastext and notext i am going crazy trying to find the documentation for the eventspecial api i have searched jquerys site and found nothing that mentions the special functionality i have found several blogs that talk about api and even reference a link to it but that page does not talk about it at allcan someone please point me toward some documentation for this special api i am mainly interested in jquerys documentation because i want to know the official source of this apiupdatei looked at jquerys source and they use the eventspecial api for certain events including ready and hover so it is obviously not obsolete as i previously thought,"['javascript', 'jquery']" +238918,is it possible to reference a column other than id for a joincolumn i have an item entity that has a manytoone relationship to a category entity i want them to be joined by a field other than categorys id in this case a field called id2 my schema is listed below class item ormid ormcolumnname id type integer ormgeneratedvaluestrategy auto protected id ormmanytoonetargetentity category ormjoincolumnname category id referencedcolumnname id2 protected categoryclass category ormid ormcolumnname id type integer ormgeneratedvaluestrategy auto protected id ormcolumnname id2 type string length 255 unique true protected id2when i try saving an item i get this errornotice undefined index id2 in vendordoctrinelibdoctrineormpersistersbasicentitypersisterphp line 511 sure enough if i change id2 to id in the joincolumn annotation everything works fine but i need the entities to be connected through id2 is this possibleeditwhat i want to achieve is impossible according to the official doctrine 2 docsit is not possible to use join columns pointing to nonprimary keys doctrine will think these are the primary keys and create lazyloading proxies with the data which can lead to unexpected results doctrine can for performance reasons not validate the correctness of this settings at runtime but only through the validate schema commandsource,['php'] +238923,why are systemwindowspoint systemwindowsvector mutable given that mutable structs are generally regarded as evil eg why are mutable structs evil are there potential benefits that might have prompted the designers of the net framework to make systemwindowspoint systemwindowsvector mutablei would like to understand this so i can decide whether it would make sense to make my own similar structs mutable if ever it is possible the decision to make point and vector mutable was just an error in judgment but if there was a good reason eg a performance benefit i would like to understand what it wasi know that i have stumbled over the implementation of the vectornormalize method a few times because it surprise does not return a fresh vector it just alters the current vectori always think it should work like thisvar vector new vector7 11var normalizedvector vectornormalize bz would not compilebut it actually works like thisvar vector new vector7 11vectornormalize this compiles but now i have overwritten my original vectorso it seems like immutability is a good idea simply for avoiding confusion but again perhaps it is worth that potential confusion in some cases,"['c#', '.net']" +238940,how do i know the default include directories default link directories and default link libraries of gcc gc in ubuntu 1104 for the following 3 compile cases gcc o helloc helloc 1g o hellocpp hellocpp 2c o hellocpp hellocpp 3how do i know the default include directories default link directories and default link libraries in each case i am using gcc 452 in a 32 bit ubuntu 1104 environmentfor case 1 is gcc using the standard c libraries or the gnu c libraries is there difference between the two c libraries comparing cases 2 and 3 is there any difference in the default link libraries used by the compiler are they using the standard c libraries or the gnu c libraries what is the difference between the two c libraries thanks in advance for any suggestionlawrence tsang,['c++'] +238951,a function to check if the nth bit is set in a byte i want a simple c function which will return true if the nth bit in a byte is set to 1else it will return falsethis is a critical function in terms of execution timeso i am thinking of the most optimal way to do that,['c'] +238982,how to trace the path in a breadthfirst search how do you trace the path of a breadthfirst search such that in the following exampleif searching for key 11 return the shortest list connecting 1 to 1 4 7 11,['python'] +238999,net custom configuration how to case insensitive parse an enum configurationproperty one of the configurationproperty i have in my configurationsection is an enum when net parses this enum string value from the config file an exception will be thrown if the case does not match exactly is there away to ignore case when parsing this value,"['c#', '.net']" +239006,why is not parallelforeach running multiple threads today i tried do some optimization to foreach statement that works on xdocumentbefore optimizationforeach xelement elem in xdocdescendantsapseventtolist some operationsafter optimizationparallelforeachxdocdescendantsapseventtolist elem same operationsi seen that net in parallelforeach opens only one thread as a result timespan of parallel was bigger than standard foreachwhat do you think why net can not open 1 threads because of locking of filethanks,['c#'] +239018,annotation not found on object with runtime retention ok i am a little bit confused here i am trying to select a dao class by using an annotation on the modelentitytablenamethispatcher use the kamailio base dao for code that supports this annotationdaoselectordao daobasekamailioclass public class thispatcherset extends model here is the annotation defenitiontargetelementtypetyperetentionretentionpolicyruntimedocumentedpublic interface daoselector class daoi use the following code to return the proper dao classpublic static daointerface getcorrectdaofinal object object throws exception final daoselector annotation objectgetclassgetannotationdaoselectorclass ifannotation null systemoutprintlnannotation present annotationdaogetname for class objectgetclassgetname final object dao annotationdaonewinstance ifdao instanceof daointerface throw new exceptioninvalid base dao in annotation for entity objectgetclassgetname return daointerface dao else systemoutprintlnannotation not present for class objectgetclassgetname return new daobase however when i feed a thispatcherset object annotation is always null1038498 info stdout annotation not present for class modelthispatchersetam i missing something hereeditok found something interesting i am running this code inside a jboss container and when i print out all the annotationsproxy76proxy708proxy77one of these should be a proxied instance of the daoselector annotation i am guessing so that is probably why getannotationdaoselectorclass would not work checking it outedit2 nope they are not an instance of daoselector,['java'] +239024,smarty section loop i am trying to get a loop for followingproductmin val 2productmax val 8and i am trying followingsection nameval startproductmin val loopproductmax val step0p idsmartysectionvalindexsmartysectionvalindexpsectionit prints followingp id22pp id33pp id44pp id55pp id66pp id77pyou might have noticed that its missing p id88p according to productmax val thanks,['php'] +239033,using ofstream on aix i am trying to write a simple c program on an aix boxthe program is given below include iostream include fstreamusing namespace std int main ofstream of ofopenlicensetxt ofhelloendl ofclose my ldflags has is set as followingmaix64 lthisk3toolsgcctoolsgcc451libppc64 lthisk3toolsgcctoolsgcc451libgccpowerpcibmaix6100451ppc64 lthisk3toolsgcctoolsgcc451libgccpowerpcibmaix6100451 lthisk3toolsopenssllibcflags iso2 maix64 ithisk3toolsopensslinclude d all source d xopen source d xopen source extended dss 64bit server d posix source d 64bit ithisk3toolsopensslinclude iusrinclude ithisk3toolsgcctoolsgcc451libgccpowerpcibmaix6100451includethe program compiles fine but when i try to run the same the program comes out with a segmentation faulti ran the same with gdb and found the following issue when i use ofstreamprogram received signal sigsegv segmentation fault0x09036107c4 in stdlocaleoperatorstdlocale const thisfindvarc706 internalerror value from register value not stored anywhereany idea on why this is happening any help is appreciated note fstream in itself works,['c++'] +239040,div aside with position absolute and sticky footer i am in trouble with the following html layouti know that there are other questions about absolute positioning and sticky footer i tried a lot of solutions but i did not make this work so i tried to post the whole layout html code to see if someone can find a solutioni used this stickyfooter solutionthe problem is the right barit shoud stay fixed at 25px from the footer but as you see if the bar content grows the content goes down over the footer and outside the bar bottom borderobviously i would the content stay inside the bar causing the bar to grown and pushing the footer downdoctype htmlhead style typetextcss sticky footer margin 0 html body form height 100 wrapper minheight 100 height auto important height 100 margin 0 auto 50px the bottom margin is the negative value of the footers height footerpage divpush height 50px push must be the same height as footer end sticky footer body backgroundcolor0 width960px margin0 auto positionrelative fontfamilytahoma verdana divwrapper backgroundcolorf positionrelative headerpage divheaderimg height100px navpage height30px lineheight 30px fontsize16px backgroundcolor90bfe7 padding0 10px positionrelative overflowhidden verticalalign middle divsubmenu backgroundcolor 90bfe7 lineheight 28px padding 10px verticalalign middle sectionbar zindex10 positionabsolute right10px top13px width200px bottom75px footer height 25px bordersolid 2px 90bfe7 backgroundcolorf padding15px 10px footerpage positionrelative padding10px backgroundcolor90bfe7 color0 sectionpage padding12px 10px 10px 10px width700px styleheadbodydiv classwrapper div idsectionbar div iddivbarcontent div lorem ipsum dolor sit amet consectetur adipiscing elit nunc blandit aliquam metus non imperdiet vivamus eu velit a velit pellentesque faucibus donec massa erat fermentum vel laoreet non commodo sit amet nulla in placerat magna ac fringilla varius justo ante rutrum magna vel interdum nisi eros vel nibh cras aliquet metus tristique velit vulputate mollis lorem ipsum dolor sit amet consectetur adipiscing elit quisque eu dignissim nisi nulla vitae ante magna sed pharetra nunc donec tincidunt dignissim mi ac tempus fusce ut ante tellus et egestas libero donec facilisis tellus at sagittis iaculis arcu orci posuere elit a luctus odio nunc ac sem etiam at erat et neque tristique eleifend curabitur blandit turpis sit amet tortor tempor eu euismod ligula sollicitudin suspenthisse non sapien eu nibh faucibus feugiat vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae integer quam turpis porttitor nec congue convallis fringilla sit amet purus donec at elit mauris vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae donec ligula tellus rhoncus eget faucibus vitae bibendum vel arcu pellentesque ante lectus sodales at interdum sit amet sollicitudin cursus quam fusce eget orci vel eros scelerisque dictum cras facilisis metus vitae venenatis aliquet nibh sem blandit mi sit amet viverra massa ipsum ut quam vivamus vitae nunc eget justo pellentesque mollis vel non justo mauris tempus mattis rutrum donec nec viverra nulla cras commodo felis sit amet nulla fringilla mollis div div div div idheaderpage div idnavpagemenudiv div iddivheaderimgdiv div iddivsubmenusub menudiv div div idsectionpage lorem ipsum dolor sit amet consectetur adipiscing elit nunc blandit aliquam metus non imperdiet vivamus eu velit a velit pellentesque faucibus donec massa erat fermentum vel laoreet non commodo sit amet nulla in placerat magna ac fringilla varius justo ante rutrum magna vel interdum nisi eros vel nibh cras aliquet metus tristique velit vulputate mollis lorem ipsum dolor sit amet consectetur adipiscing elit quisque eu dignissim nisi nulla vitae ante magna sed pharetra nunc donec tincidunt dignissim mi ac tempus fusce ut ante tellus et egestas libero donec facilisis tellus at sagittis iaculis arcu orci posuere elit a luctus odio nunc ac sem etiam at erat et neque tristique eleifend curabitur blandit turpis sit amet tortor tempor eu euismod ligula sollicitudin suspenthisse non sapien eu nibh faucibus feugiat vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae lorem ipsum dolor sit amet consectetur adipiscing elit nunc blandit aliquam metus non imperdiet vivamus eu velit a velit pellentesque faucibus donec massa erat fermentum vel laoreet non commodo sit amet nulla in placerat magna ac fringilla varius justo ante rutrum magna vel interdum nisi eros vel nibh cras aliquet metus tristique velit vulputate mollis lorem ipsum dolor sit amet consectetur adipiscing elit quisque eu dignissim nisi div div iddivpushdivdivdiv idfooterpagefooterdivbodyhtml,['css'] +239054,jsf 2 inject spring beanservice with managedproperty and no xml i would like to use jsf annotations and some springannotations to inject a spring beanservice into a jsf managed beanon the jsf bean i only want to use jsf annotationsi dont want to use annotations like named injecti have tried to find a solution on the net but without any luckexamplemanagedbeanviewscoped public class mybean managedpropertyvalue myspringbean private myspringbean myspringbean public void setmyspringbeanmyspringbean myspringbean thismyspringbean myspringbean public void dosomething do something with myspringbean is something like this possible without the use of xml for example i would not like to use something likefacescontextutilsgetwebapplicationcontextcontextgetbeanmyspringbeanor in facesconfigxmlmanagedbean managedbeannamemybeanmanagedbeanname managedbeanclasscommytestmybeanmanagedbeanclass managedbeanscopeviewmanagedbeanscope managedproperty propertynamemyspringbeanpropertyname valuemyspringbeanvalue managedpropertymanagedbeanis something like the above possible with annotations and withoutdefining all the jsf beansproperties and the spring beansproperties forevery bean in the config xml files,['java'] +239060,cast list to list public interface idic int id get set string name get set public class client idichow can i cast listclient to listidic,"['c#', '.net']" +239077,javascript object push function i have a javascript object i actually get the data through an ajax requestvar data i have added some stuff into itdata0 id 1 status valid data1 id 2 status invalid now i want to remove all objects with an invalid status but keep everything the ordering samevar tempdata for var index in data if dataindexstatus valid tempdatapush data data tempdatain my mind all of this should work but i am getting an error that tempdatapush is not a function i understand why it is not the same as an array but what could i do otherwise,['javascript'] +239081,how to set tab bar item title programatically in objective c i want to set title to tab item programatically but it not works my code is below ibactiontab1clickidsender mytabbarcontroller uitabbarcontroller alloc init view2controller view2controller alloc init view2controller settitletitle view3controller view3controller alloc init deneme viewcontroller alloc init mytabbarcontrollerviewcontrollers nsarray arraywithobjectsdeneme view2controllerview3controller nil selfview addsubviewmytabbarcontrollerview mytabbarcontrollerselectedindex1,['objective-c'] +239089,get cultureinfo object from country name or regioninfo object given a specific country code eg ch how can i get a cultureinfo object the specific country code is dynamic changes at runtimei only have the country code and i want to know if it is possible to create a cultureinfo object from just the country code it does not matter which exact culture i get frchdechi am trying do something like thiscultureinfo c cultureinfocreatespecificculturechwould it be possible to create a culture from a regioninfo objectthen it would look like thisregioninfo r new regioninfochcultureinfo c cultureinfocreatespecificculturerobviously the preceding examples do not compile they just give an idea of what i am trying to achieve,"['c#', 'asp.net']" +239107,return default enum value when enum type is not known i have a method that attempts to match string to descriptionattribute of enum values and then return the enum value in case a match is not found it should return a default value which i thought i could just return 0 but it is not going to happenprivate enum getenumfromdescriptiontype enumtype string description var enumvalues enumgetvaluesenumtype foreach enum e in enumvalues if stringcomparedescription getdescriptione true 0 return e return 0 not compilinghow should i code the above,['c#'] +239132,convert base2 binary number string to int i would simply like to convert a base2 binary number string into an int something like this 1frombinarytoint255is there a way to do this in python,['python'] +239135,how can i run common code for most requests in my spring mvc web app iei have various urls mapped using spring mvc requestmappingrequestmappingvalue mystuff method requestmethodget requestmappingvalue mystuffdsf method requestmethodget requestmappingvalue mystuffe method requestmethodget etci want to run some common action before about 90 of my requests these are across several controllersis there anyway to do that without delving into aop and if i have to use aspects any guidance on how to do thisthanksmore infoit is to run some app specific security we are chained to a parent security set up which we need to read and call into and then need to access a cookie prior to some most of ours calls but not all,['java'] +239147,settimeout on object method es5 bind or closure let us say i am doing some animations with the html5 canvas if i am looking to animate an objects method which would be preferable performance wise assuming i do not care about ie8 settimeoutthisrenderbindthis 15orvar self thissettimeoutfunction selfrender 15my particular case is not intense enough to really make a difference visually i am just trying to find out the best practice i would think creating a new function with bind would have less overhead than creating a closure but i wanted to ask the experts,['javascript'] +239156,create an array in smarty template i need to create a new array from other one dimensional array in smarty templateso what are the best possibilities to create an array in template filethankssachin,['php'] +239157,how to properly set up varnish for symfony2 sites i have a website with esi that uses symfony2 reverse proxy for caching average response is around 100ms i tried to install varnish on server to try it out i followed guide from symfony cookbook step by step deleted everything in cache folder but http cache folder was still created when i tried it out so i figured i could try to comment out kernel new appcachekernel from aphp that worked pretty well http cache was not created anymore and by varnishstat varnish seemed to be working12951 0 008 cache hitpass cache hits for pass 1153 0 001 cache miss cache missesthat was out of around 140 requests so i thought everything would be alright but after echoping i found out responses raised to 2 secondsapache runs on port 90 and varnish on 8080 so i echoping using echoping n 10 h httpservername x8080i have no idea what could be wrong are there any additional settings needed to use varnish with symfony2 or am i simply doing something wrongper requests heres my defaultvcl with modifications i have done so fari found 2 issues with varnishs default configit does not cache requests with cookies and everyone in my app has session assignedit ignores cachecontrol nocache headerso i added conditions for these cases to my config and it performs fairly well now 175 reqs up from 160 with s2 reverse proxy but honestly i expected bit more i just have no idea how to check if it is all set ok so any inputs are welcomemost of pages have cache varied by cookie with smaxage 1200 common esi includes are not varied by cookie with smaxage quite low articles article lists user profile pages are not cached at all nocache and i am not really sure if esi includes on these are even being cached by varnish only esi that is varied by cookies is header with user specific information that is on 100 of pageseverything in this post is varnish 3x specific i am personally using 302also after few weeks of digging into this i have really no idea what i am doing anymore so if you find something odd in configs just let me know,['php'] +239159,why is the first element always blank in my rails multiselect using an embedded array i am using rails 320rc2 i have got a model in which i have a static array which i am offering up through a form such that users may select a subset of array and save their selection to the database stored in a single column in model i have used serialize on the database column which stores the array and rails is correctly converting the users selections into yaml and back to an array when reading that column i am using a multiselect form input to make selectionsmy problem is that the way i currently have it everything works as i would expect except that the users subset array always has a blank first element when it is sent to the serverthis is not a big deal and i could write code to cut that out after the fact but i feel like i am just making some kind of syntactical error as it does not seem to me that the default rails behaviour would intentionally add this blank element without some reason i must have missed something or forgot to thisable some kind of setting please help me understand what i am missing or point me in to some good documentation that describes this with more depth than what i have been able to find on the intertubesmysql database table modelsincludes a column named subset array which is a text fieldclass model includes the following settingsserialize subset arrayall possible values value1 value2 value3 form for editing models includes the following input optionfselect subset array modelall possible values multiple true selected modelsubset arrayput to server from client looks something like thisassuming only value1 and value3 are selectedmodel subset array value1 value3 database update looks like thisupdate models set subset array n n value1n value3nas you can see there is this extra blank element in the array being sent and set in the database how do i get rid of that is there a parameter i am missing from my fselect callmuch thanks appreciated edit this is the generated html code from the fselect statement it looks as though there is a hidden input being generated which may be the cause of my issue why is that thereinput namemodelsubset array typehidden valueselect idmodel subset array multiplemultiple namemodelsubset array selectedselected option valuevalue1 selectedselectedvalue1option option valuevalue2value2option option valuevalue3 selectedselectedvalue3option optionoptionselect,"['html', 'ruby-on-rails']" +239170,automatically open a file as binary with ruby i am using ruby 19 to open several files and copy them into an archive now there are some binary files but some are not since ruby 19 does not open binary files automatically as binaries is there a way to open them automatically anyway so class would be binary txt not,['ruby'] +239194,where can i find mad mean absolute deviation in scipy it seems scipy once provided a function mad to calculate the mean absolute deviation for a set of numbershowever i can not find it anywhere in current versions of scipy of course it is possible to just copy the old code from repository but i prefer to use scipys version where can i find it or has it been replaced or removed,['python'] +239211,how can i convert systemdrawingicon to systemdrawingimage i am getting icon from another application using thisicon ieicon iconextractassociatediconcprogram filesinternet exploreriexploreexehow to convert it to systemdrawingimage thanks in advance,"['c#', '.net']" +239226,android getting file size of image before sharing it intentaction send i successfully wrote an app based on this blog post but simpler which streams an image over http using a post requestwhat i cannot figure out after searching the web and crawling inside android sdk docs is how do i get the size of the image before i share itthere is only a possibility to open an input stream that i see in the exampkle and anywhere elsecontentresolver cr getcontentresolverinputstream is cropeninputstreamurithe given blog post example uses getbytesfromfileis so one could get the size there but this is not a solution some images are huge while android apps are limited in heap space i want my app to work for all thinkable sizes of images not a problem when sharing over wifitherefor the only option for me is to forward the input stream to some http output stream which i do and which works but this approach do not give me the image size before sending it,['android'] +239252,delayed job does not work rails 313 trying to use gem delayed job from collectiveidea job in my project but it throws exception uninitialized constant delayeddelayproxyjobwhat i have done to install itgemfilegem daemonsgem delayed jobgem delayed job active recordcommand linebundle installrails generate delayed jobactive recordrake dbmigraterake jobsworkusing it in controllervideodelayconverti have done all of this like in instruction but it does not work googled much but cannot find helpful instruction i have found railscasts sources with delay work but all codegemfile script controllers models is the same as mine but rcs code works mine nops i am new to ruby and rails may be my question is lame but i am trying to solve this problem second day and sorry for my bad english,['ruby-on-rails'] +239259,phantomjs download using a javascript link i am attempting to scrape the below websitestatsbatlgallqual0type8season2011month0season12011ind0team0rost0players0if you click the small button at the topright of the table titled export data a javascript script runs and my browser downloads the file in csv form i would like to be able to write a phantomjs script that can do this automatically any ideasthe above button is coded into html as sucha idlb cmdcsv hrefjavascript dopostbacklbcmdcsvexport dataadivi also found this function in the html source codescript typetextjavascriptcdatavar theform documentformsform1if theform theform documentform1function dopostbackeventtarget eventargument if theformonsubmit theformonsubmit false theform eventtargetvalue eventtarget theform eventargumentvalue eventargument theformsubmit scripti am very new to phantomjsjavascript and could use some pointers here i think i have found all the info i need to do this automatically correct me if i am wrong but just not sure where to start on coding it thanks for any helpedit this is what my script looks like right nowvar page new webpageurl statsbatlgallqual0type8season2011month0season12011ind0team0rost0 players0pageopenencodeuriurl function status if status success consolelogunable to access website else pageevaluatefunction dopostbacklbcmdcsv phantomexit0,['javascript'] +239269,listview inside of scrollviewer prevents scrollviewer scroll i have a scrollviewer with a couple listboxes in it the problem is if a user uses the middle mouse roller to scroll the scrollviewer while their mouse is over a listview the listview scrolls its internal scrollviewer to the bottom and then continues to capture the mouse preventing the containing scrollviewer from scrollingany ideas on how to handle this,['c#'] +239324,c namespaces and assemblies best practice c are there any guidelines best practices when it comes to dividing a solution up into namespaces and assemblies should name spaces normally be nested with the most low level and fundamental classes in the top level name space should there generally be one namespace to one assembly are their any pitfalls to having multiple assemblies in one namespace or multiple namespaces in one assembly are there any compile time run time penalties for multiple assemblies or very large assemblies,['c#'] +239332,how jvm starts looking for classes i was curious about what all locations jvm looks for executing a program i am more interested in understanding in what sequence and where does jvm look for class files like does it look into java libs extension libs classpath any directory like the current directory from where the java is invoked i am more interested in jvm behaviour and not how class loader load class which i know has parent delegation mechanism till rootif a class is executed from directory where the compiled class is kept on file system and also in a jar file in the same directory would jvm load both or just one and which onesay you have a thread unsafe vector and if we compare it performance to arraylist which one would be better and why,['java'] +239337,index pdf documents in solr from c client basically i am trying to index word or pdf documents in solr and found the extractingrequesthandler but cannot figure out how to write code in c that performs the http post request like in the solr wiki i have installed solr 34 on tomcat 7 7022 using the files from the examplesolr directory in the solr zip and i have not altered anything the extractingrequesthandler should be configured out of the box in the solrconfigxml and ready to use rightcan some of you give an c httpwebrequest example of how you make the http post request and upload a pdf file like it is done using curl in the solr wikii have look all over this site and many others trying to find an example or a tutorial on how this is done but have not found anythingediti finally managed to get it to work using solrnetin order for it to work you need to copy this to a libfolder in your solr installation directory from the solr zipapachesolrcell340jar file from the thist foldercontent of contribextractionlib directorywith solrnet 040 beta 2 this code does the jobstartupinitindexdocumentyoursolrservicepathvar solr servicelocatorcurrentgetinstanceisolroperationsindexdocumentusing filestream filestream fileopenreadfilepathforthefiletobeindexed var response solrextract new extractparametersfilestream doc1 extractformat extractformattext extractonly false solrcommitsorry for the trouble i hope however that others will find this useful,['c#'] +239339,how can i access amazon dynamodb via python i am currently using hbase with my python apps and wanted to try out amazon dynamodb is there a way to use python to read write and query data,['python'] +239346,rails 31 cannot write to column in same migration that adds it i had an add column migration that would run fine however after running it and firing up a console i would find the first name and last name columns completely empty i tried using save instead and it had the same effectno errors reported heres the originalclass useraddfirstnameandlastname activerecordmigration def change add column first name last name string add column users first name string add column users last name string useralleach do u ufirst name first name ulast name last name usave end endendi also thought this might be some class loading issue so i inserted the line user to force the user class to reload before the loop no dicewhen i split this up into two migrations the desired effect was achieved does someone have an explanation for this i swear i have even done this in the same project with past migrationsother notes devise for user engine added the new columns to attr accessible in user class before running migration,['ruby-on-rails'] +239351,replace auto keyword with deduced type clang or vs2010 has anyone written a script plugin or executable that replaces each instance of auto with the compilerdeduced type i need to port some c11 code that uses auto all over the placeclang is my first candidate has anyone modified it to do something like thisan alternative is to parse the errors from a compiler as the expected type might be in the error output i could dautoint and possibly get back could not convert stdvectorintiterator to int,['c++'] +239362,using beautifulsoup to search html for string i am using beautifulsoup to look for user entered strings on a specific page for example i want to see if the string python is located on the page when i usedfind string soupbodyfindalltextpythonfind string returned but when i usedfind string soupbodyfindalltextrecompilepython limit1find string returned upython jobs as expectedwhat is the difference between these two statements that makes the second statement work when there are more than one instances of the word to be searched,['python'] +239389,iqueryable c select this is my code but i need select only column to thisplay in my datagridviewi need the code to select only some columns exampleselectt tusu login t tusu loginpublic listtb usuario getfilterdefinition filter var contexto new indnet entities iqueryabletb usuario consulta contextotb usuarioasqueryabletb usuario wheret tusu ativo 1 orderbyt tusu login return consultatolist,['c#'] +239402,android spinner fire event when same item selection is made i want to fire a event when the same item is selected in spinner methodoverride public void onitemselectedadapterview parent view arg1 int position long arg3 is called only when we different selection is made my purpose is to thisplay a toast when any item is selected either the same item is reselected or different selection is madeoverride public void onnothingselectedadapterview parent above method does not solve my problem,['android'] +239410,wrong data type returned for date in jtdsjar i have a table on ms sql server with a column having data type as date i am using jtdsjar for jdbc connection with db i am taking databasemetadata from connection while checking columns from databasemetadata i observed that int itype rsmetagetintdata typereturns column type as javasqltypesvarchar which is a string and not date but it also returns string tmp rsmetagetstringtype nametype name as datebut for oracle it returns the date datatype as javasqltypesdatewhy is such a difference,['java'] +239411,how to set id of dynamic created layout i want to give id to some views textview imageview etc in a layout that is programmetically created so what is the best way to set id,['android'] +239418,can we show badge number on android app icon like iphone possible duplicateis there a way to add a badge to an application icon in android i just wanted to know that can we show the badge number in android app iconi know that android notifications are different then iphone but i want to do in my android appis that applicablethanks for your answer,['android'] +239435,urlseturlstreamhandlerfactory i am developing a web application using an executable jar with embedded jettymy jar contains a dependent jarjar in jari referenced to the jarrsrcloader and rsrcurlstreamhandlerfactory that developed by eclipsejarrsrcloader is using urlseturlstreamhandlerfactoryrsrcurlstreamhandlerfactory to resolve rsrc protocolthereby it can resolve class path for jarbut it becomes impossible to solve the usual protocol as side effectsfor example filex or jarxrsrcurlstreamhandlerfactory has seturlstreamhandlerfactory methodmaybe i think i should set the default implement to this methodi do not know what set this method,['java'] +239459,why array assignment operation does not exist but structure assignment does in c language int a10int b10a b illegaltypedef struct int real int imag complexcomplex cdc d legali realize that a and b are addresses in 1st casebut symbols in 2nd case,['c'] +239466,parsing json file java i want to parse a json file in java and get the following values from the file mentioned below status ok origin addresses vancouver bc canada seattle atat de washington atatsunis destination addresses san francisco californie atatsunis victoria bc canada rows elements status ok duration value 340110 text 3 jours 22 heures thistance value 1734542 text 1 735 km status ok duration value 24487 text 6 heures 48 minutes thistance value 129324 text 129 km elements status ok duration value 2834 text 3 jours 8 heures thistance value 1489604 text 1 490 km status ok duration value 14388 text 4 heures 0 minutes thistance value 135822 text 136 km from every element i want to get the value field of both thistance and duration how do i do this,['java'] +239470,why was the constructor interface of stdvector changed with c11 why was the default argument removed with the new standard often i constructed a vector variable like this stdvectormy pod struct buf100 i guess i would get an compiler error with a c11 compilerexplicit vector size type count const t value t until c11 const allocator alloc allocator vector size type count const t value since c11 const allocator alloc allocator,['c++'] +239472,implicit method group conversion gotcha part 2 simplified from this question and got rid of possible affect from linqpadno offsensive a simple console application like thispublic class program static void m static void mainstring args action a new actionm delegate b new actionm consolewritelinea b got false here consoleread the false results from the operator ceq in cil of the code abovevisit the original question for details so my questions are1 why is translating to ceq instead of call delegate equalshere i do not care about the unwrapping between delegate and action at the very last when evaluating a b a is of type action while b is a delegate from the spec734 binary operator overload resolution an operation of the form x op y where op is an overloadable binary operator x is an expression of type x and y is an expression of type y is processed as followsa the set of candidate userdefined operators provided by x and y for the operation operator opx y is determined the set consists of the union of the candidate operators provided by x and the candidate operators provided by y each determined using the rules of a735 if x and y are the same type or if x and y are derived from a common base type then shared candidate operators only occur in the combined set once a if the set of candidate userdefined operators is not empty then this becomes the set of candidate operators for the operation otherwise the predefined binary operator op implementations including their lifted forms become the set of candidate operators for the operation the predefined implementations of a given operator are specified in the description of the operator a78 through a712 a the overload resolution rules of a753 are applied to the set of candidate operators to select the best operator with respect to the argument list x y and this operator becomes the result of the overload resolution process if overload resolution fails to select a single best operator a bindingtime error occurs735 candidate userdefined operators given a type t and an operation operator opa where op is an overloadable operator and a is an argument list the set of candidate userdefined operators provided by t for operator opa is determined as follows a determine the type t0 if t is a nullable type t0 is its underlying type otherwise t0 is equal to t a for all operator op declarations in t0 and all lifted forms of such operators if at least one operator is applicable a7531 with respect to the argument list a then the set of candidate operators consists of all such applicable operators in t0a otherwise if t0 is object the set of candidate operators is emptya otherwise the set of candidate operators provided by t0 is the set of candidate operators provided by the direct base class of t0 or the effective base class of t0 if t0 is a type parameterfrom the spec a and b have a same base class delegate obviously the operator rule defined in delegate should be applied herethe operator invokes delegateequals essentially but now it looks like the candidate list of userdefined operators is empty and at last object is applied2 shoulddoes the fcl code obey the c language spec if no my first question is meaningless because something is specially treated and then we can answer all of these questions using oh it is a special treatment in fcl they can do something we cannot the spec is for outside programmers do not be silly,"['c#', '.net']" +239482,how do i clear previous webviews content before loading the next webview my scenario is initially i am loading a webview and later on i am loading the same webview with a different urlmy problem is whenever i am loading the next url i can see the previously loaded url contents and then my currently loaded url contents gets thisplayedi want to clear the contents whenever i am loading the different urlsayif pos 0 mwebclearcachetrue mwebclearhistory mwebloadurlelse if pos 1 mwebclearcachetrue mwebclearhistory mwebloadurlboth clearcache and clearhistory does not work for me,['android'] +239512,how can i run a sql text file on a mysql database i am new to mysql i want to execute a text file containing sql queriesi tried to run source desktoptestsql and received the errormysql homesivakumardesktoptestsql error failed to open file homesivakumardesktoptestsql error 2,['mysql'] +239530,dimenxml or dimensxml i usually store dimensions in dimenxml file however intellij ideas intellisense places dimensions into file dimensxml now what if i place dimensions into the file dimensxml how will eclipse handle thisi see that docs allow both files to be used which one should be used if the project will be used by both eclipse and idea users,['android'] +239542,magento grid column position i am editing the order grid by adding custom columns like thisthisaddcolumnpagamenti array header paymentsource width50px align left type text renderer blablabla adminhtml block sales order renderer lolbut every column is positioned on the far right of the table no matter where i call addcolumnsis there a way to force the positionthanks,['php'] +239568,google mock unit testing static methods c i just started working on unit testing using boost framework for testing but for mocks i have to use google mock and i have this situation class astatic int method1int a int breturn abclass bstatic int method2int a int b return amethod1abso i need to create mock class a and to make my class b not to use real method1 from a class but to use mocki am not sure how to do this and i could not find some similar example,['c++'] +239591,how do i make hudsonjenkins fail if sonar thresholds are breached i am using maven to build my java app jenkins for ci and sonar for metricscurrently i have a build job that creates the sonar report triggered via a postbuild step in jenkinsi would like to set this up to fail the build if certain thresholds are met ie any major or blocker violations or complexity more than 17any guidance would be appreciated l,['java'] +239601,codesniffer using pear standard ignore line indent using codesniffer with pear standardi got over 20tsd errors cause of line indentsi use tabstops for indentingi try to thisable that check but i failedi removed the last rule from the generic standards in the rulesetxml for the pear standardyet the indenting is still considered an errorhow do i remove the indention checks completely for the pear standard,['php'] +239610,what does the last sentence below in bold has to do with copying a thrown exception this is an excerpt of stroustups book 3rd edition at page 362 in principle an exception is copied when it is thrown so the handler gets hold of a copy of the original exception in fact an exception may be copied several times before it is caught consequently we cannot throw an exception that cannot be copied the implementation may apply a wide variety of strategies for storing and transmitting exceptions it is guaranteed however that there is sufficient memory to allow new to throw the standard outofmemory exception bad alloc,['c++'] +239650,replace url querystring value on change of dropdown i have a dropdown which had dual role user can come to the pagehttpmysiteeventspagesdefaultaspx straight and use the dropdown or they can first do a search and the filter the search resuld further by selecting the dropdown first case url will be likehttpmysiteeventspagesdefaultaspxhoscarmel and second case urlhttpmysiteeventspagesdefaultaspxkwdhealthtypeeventshoscarmelthis is what i am doing right now but it behaves weird and does sth like this to url hoscarmelso if user selected carmel from the dropdown the first time and decided heshe wanted to look for indianapolis then it should either replace carmel with indianapolis or replace the whole querstring hoscarmel with hosindianapolis for the second case and hoscarmel with hosindianapolis for the first scenariohospitaldropdownchangefunctione var querystringwindowlocationsearch var currenturllocationattrhref iflocationhrefindexof 1 windowlocationhref httpmysiteeventspagesdefaultaspxhosthisval else windowlocationhref thisval all hospitals httpmysitesiteeventspagesdefaultaspx locationhref hos thisval i found some nifty code that uses regex to handle the querystring but i do not understand how regex workshow can i use sth like below in my casefunction replacequerystringurlparamvalue var re new regexp param i if urlmatchre return urlreplacere1 param value 2 else return url param value,"['javascript', 'jquery']" +239674,how do i morph animate a custom shape into a circle canvas js i have a slicesegment of a circle and want to animate it morphing into a new complete circle with a biological feel to itby biological i mean a way other than increasing the arclength of the segmenthow can i get the kind of animation you would get if tweening a square to a circle in flash but in canvas js,['javascript'] +239691,how to know the repeating decimal in a fraction i already know when a fraction is repeating decimals here is the functionpublic bool isrepeatingdecimal get if numerator denominator 0 return false var primes mathalgorithmsprimesdenominator foreach int and in primes if n 2 and 5 return true return false now i am trying to get the repeated number i am checking this web site decimalpublic decimal repeatingdecimal if isrepeatingdecimal throw new invalidoperationexceptionthe fraction is not producing repeating decimals int digitstotake switch denominator case 3 case 9 digitstotake 1 break case 11 digitstotake 2 break case 13 digitstotake 6 break default digitstotake denominator 1 break return mathextensionstruncateatdecimalnumerator denominator digitstotakebut i really realized that some numbers has a partial decimal finite and later infinite for example 128do you know a better way to do this or an algorithm,['c#'] +239692,whats the point of html forms name attribute whats the point of the name attribute on an html form as far as i can tell you cannot read the form name on submission or do anything else with it does it serve a purpose,['html'] +239696,select box truncating text when body font size changed via javascript on document ready in ie 9 ie 9 is behaving quite strangely for me i have got a page fontsize changing control that saves the users setting and then in the document ready sets the body fontsize to that size it works fine the issue is when a page with dropdowns loads in ie 9 sometimes the text is cut off i have simplified the code down to this jsfiddle to demonstratethe htmlselect idtheselect nametheselect option value2 letter 85 x 11quot option option value3 selectedselecteda4 827 x 1169quot option selectthe cselect fontsize1em width240pxand the javascriptvar userprefsizeoffset 2function var currentfontsize bodycssfontsize var currentfontsizenum parsefloatcurrentfontsize bodycssfontsize currentfontsizenum userprefsizeoffsethas anyone come across this strange behaviour is there a simple fixit does not happen in ie 8 or firefox or safari or chrome,"['javascript', 'css']" +239704,how to use an objects identity as key for dictionary is it possible to use an object as a key for a dictonaryobject in such a way that the dictionary treats objects as equal only if they are identicalfor example in the code below i want line 2 to return 11 instead of 12dictionaryobject int dict new dictionaryobject intobject a new uriobject b new uridicta 11dictb 12consolewritelinea b line 1 returns false because a and b are different objectsconsolewritelinedicta line 2 returns 12consolewritelinedictb line 3 returns 12the current dictionary implementation uses objectequals and objectgethashcode on the keys but i am looking for a different kind of dictionary that uses the objects identity as a key instead of the objects value is there such a dictionary in net or do i have to implement it from scratch,"['c#', '.net']" +239705,is there an equivalent to the matlab function bsxfun in python i am trying to port some of my code from matlab to python and some of it uses the bsxfun function for virtual replication followed by multiplication or division i also use it for logical operations i would like to be able to do this without actually replicating the vector either with a function or with some kind of diagonal matrix before multiplying or dividing to save on memory and timeif there is an equivalent of bsxfun in a c library of some kind that would of course also work,"['python', 'c']" +239710,pause javascript execution in uiwebview i placed multiple uiwebviews side by side into a uiscrollview every uiwebview includes a web browser view that thisplays a local html file unfortunately i have no idea how to load the webviews in the background and at the same time to prevent or stop the javascript functions from executing that are included into the html files i mean by in the background as i watch the first few panels and in the meantime the remainder panels just lazy load silently i saw different applications like pugpig do this it lazy loads the html pages and stops the javascript animations it can somehow stop the javascript to animate the whole fade effect that i use frequently in my html pages between tab switches and at the moment i load the panel it continues the fade animation so the question ishow can i pause a javascript animation and prevent memory issues using objectivec code and how can i continue the fade animation once i thisplay the panel,"['javascript', 'objective-c', 'ios']" +239719,convert json timestamp to normal date and time in javascript i have a json timestamp that i would like to convert into simple date time format using javascripti need the date and time in the following format ddmmy hrmnhere is an example json date from i wish to extract the timestamp timestamp 1326439500 count 2 d title apple iphone 4s sale cancelled in beijing amid chaos design you trust description advertise here with bsa apple cancelled its scheduled sale of iphone 4s in one of its stores in chinaas capital beijing on january 13 crowds outside the store in the sanlitun thistrict were waiting on queues overnight there were incidents of scuffle between shoppers and the storeas security staff when shoppers hundreds of them were told that the sales source design you trustexplore iphone iphone 4 phone link timestamp 1326439500 image null embed null language null user null user image null user link null user id null geo null source wikio favicon type blogs domain wikio id 2388575404943858468 title apple to halt sales of iphone 4s in china fame dubai blog description shanghai a apple inc said on friday it will stop selling its latest iphone in its retail stores in beijing and shanghai to ensure the safety of its customers and employees go to sourcesource fame dubai blogexplore iphone iphone 4 phone link timestamp 1326439320 image null embed null language null user null user image null user link null user id null geo null source wikio favicon type blogs domain wikio id 16209851193593872066,['javascript'] +239721,is there a convention for pointer declarations in c when declaring pointers in c there are 2 edit 3 variantsvariant aint ptrvariant bint ptrvariant cint ptrin a the indirection operator has been appended to the typein b the indirection operator has been prepended to the variable in c the indirection operator stands freely in between type and variablethe way a pointer is declared differs depending on the type of documentation i read some authors seem to have a preference for certain variants others use severalam i correct to assume that there is no difference in functionality between the different variantsif yes is there a convention for which variant one should be using in c,['c'] +239723,ordering sql server results by in clause i have a stored procedure which uses the in clause in my aspnet application i have a multiline textbox that supplies values to the stored procedure i want to be able to order by the values as they were entered in the textbox i found out how to do this easily in mysql using field function but not a sql server equivalentso my query looks likeselect from mytable where item in itemso i would be passing in values from my application like 113113112112114114 in an arbitrary order i want to order the results by that list would a case statement be feasible i wouldnt know how many items are coming in the textbox data,"['asp.net', 'sql']" +239740,how do i get a three column layout with twitter bootstrap i am trying to create a three column layout that is like the followingit should be a fixed width fluid width fixed width layoutusing twitter bootstrap the left sidebar and fluid content work great but i need the addition of a right sidebar too,['css'] +239798,django model auto increment primary key based on foreign key i am trying to figure out how to lay out two of my django models so that when a new model is saved to the database its primary key is incremented such that it is the next highest value for all records with the same foreign keyit is much like this question asked but i am wondering how you would do it in django heres an excerpt from the question which demonstrates a similar situationid job id title0 1 hi1 1 hello2 1 goodbye0 2 hi1 2 helloi know you cannot have multiple primary keys in a django model and you can use unique together but the documentation says it uses the equivalent unique statement in the create statements would class modelamodelsmodel key modelspositiveintegerfieldprimary key true fk modelsforeignkeymodelb def metaself unique together key fkin the models work with this answer to accomplish what i am looking for the relationship between the models is one modela having many modelbs but each modelb having only one modela,"['python', 'mysql']" +239825,pythonic circular list say i have a listl 1 2 3 4 5 6 7 8i want to grab the index of an arbitrary element and the values of its neighbors for examplei lindexnj li1k li1however for the edge case when i lenl 1 this fails so i thought i would just wrap it aroundif i lenl 1 k l0else k li1is there a pythonic way to do this,['python'] +239842,how to parse json data with jquery javascript i have a ajax call that returns some json like thisdocumentreadyfunction ajax type get url httpexamplefunctionsphp data get param value success function data var names data candhtmldata inside the cand div i will get id 1 name test1 id 2 name test2 id 3 name test3 id 4 name test4 id 5 name test5 how can i loop through this data and place each name in a div,['jquery'] +239857,how to portably parse the unicode degree symbol with regular expressions i am writing a simple regular expression parser for the output of the sensors utility on ubuntu heres an example of a line of text i am parsingtemp1 310ac crit 1070acand heres the regex i am using to match that in pythontemp re recompilertemp1sddwwcs rcritssddwwcthis code works as expected and matches the example text i have given above the only bits i am really interested in are the numbers so this bitddwwcwhich starts by matching the or sign and ends by matching the ac my question is why does it take two w nonalphanumeric characters to match a rather than one will the code break on systems where unicode is represented differently to mine if so how can i make it portable,['python'] +239861,how does ejb and jpa relate i am reading the ejb 3 in action book and i have the following question is the pojos you write and annotate with enitity and so on also a ejb entity type i do not understand what jpa has to do with ejb is not jpa a own specification now the entities are also contained in a own persistence container they talk about ejb 3 java persistence api etc but i do not understand what entities has to do with ejb,['java'] +239879,thisplay abpeoplepickernavigationcontroller using storyboard segue i have a new project where i want to thisplay a people picker when a button is touchedso i have a uibutton that segues to a generic uiviewcontroller with the identifier showcontacts i set the class of this viewcontroller to abpeoplepickernavigationcontrollernow in my root viewcontroller i have this code to initialize my pickerpragma mark seguesvoidprepareforsegueuistoryboardsegue segue senderidsender ifsegueidentifier isequaltostringshowcontacts abpeoplepickernavigationcontroller ppnc seguedestinationviewcontroller ppncpeoplepickerdelegate self ppncaddressbook abaddressbookcreate ppncthisplayedproperties nsarray arraywithobjectnsnumber numberwithintkabpersonphoneproperty although i have added test contacts to my simulator address book the results looks like thiswith the following code which is very similar to what i do in the prepareforsegue method i manage to show a picker via an ibaction ibactionshowpickeridsender abpeoplepickernavigationcontroller picker abpeoplepickernavigationcontroller alloc init pickerpeoplepickerdelegate self nsarray thisplayeditems nsarray arraywithobjectsnsnumber numberwithintkabpersonphoneproperty nsnumber numberwithintkabpersonemailproperty nsnumber numberwithintkabpersonbirthdayproperty nil pickerthisplayedproperties thisplayeditems show the picker self presentmodalviewcontrollerpicker animatedyesthe resultit is not clear to me why the people picker does not show,"['objective-c', 'ios']" +239881,clicking app icon does not trigger onoptionsitemselected i am currently working on an android app i would like to use the app icon in the action bar to navigate to the home activity i read on this page that all that needs to be done is to add an onoptionsitemselected and look for the id androidridhome this is the code that i have implemented in my activity where i want to press the app icon to return to homeactivityoverridepublic boolean onoptionsitemselectedmenuitem item switchitemgetitemid case androidridhome intent intent new intentthis homeactivityclass intentaddflagsintentflag activity clear top startactivityintent return true default return superonoptionsitemselecteditem however nothing happens when debugging i can see that clicking the icon does not trigger the onoptionsitemselected at all do i have to do something with the icon somewhere as of now it is all default just this in the androidmanifestxmlapplication androidicondrawableic launcher androidlabelstringapp name,['android'] +239905,cannot use arrayscopyofrange i do not seem to be able to access arrayscopyofrange in my android project in eclipse indigo 371 on ubuntu 10my jre is java6openjdk which i thought included arrayscopyofrangefor example if i have this codeint debug new int5int x arrayscopyofrangedebug04eclipse tells methe method copyofrangeint int int is undefined for the type arraysi do not understand because the android reference arrays includes this method for arraysany ideas,['android'] +239918,valueerror too many values to unpack django so i just got my first django app deployedi did a syncdb and created my superuser account for the sitenow when i access the page and press the login button i get this error i think it has something to do with the password but i am not surevalueerror at accountslogintoo many values to unpacki am using the generic login view raccountslogin login template name authenticationloginhtmlthe following is the tracebackenvironmentrequest method postrequest url pagedjango version 131python version 272installed applicationsdjangocontribauth djangocontribcontenttypes djangocontribsessions djangocontribsites djangocontribmessages djangocontribstaticfiles djangocontribadmin bc system app djangocontribhumanizeinstalled middlewaredjangomiddlewarecommoncommonmiddleware djangocontribsessionsmiddlewaresessionmiddleware djangomiddlewarecsrfcsrfviewmiddleware djangomiddlewarecsrfcsrfresponsemiddleware djangocontribauthmiddlewareauthenticationmiddleware djangocontribmessagesmiddlewaremessagemiddlewaretracebackfile usrlocallibpython27thistpackagesdjangocorehandlersbasepy in get response 1 response callbackrequest callback args callback kwargsfile usrlocallibpython27thistpackagesdjangoutilsdecoratorspy in wrapped view 93 response view funcrequest args kwargsfile usrlocallibpython27thistpackagesdjangoviewsdecoratorscachepy in wrapped view func 79 response view funcrequest args kwargsfile usrlocallibpython27thistpackagesdjangocontribauthviewspy in login 35 if formis validfile usrlocallibpython27thistpackagesdjangoformsformspy in is valid 121 return selfis bound and not boolselferrorsfile usrlocallibpython27thistpackagesdjangoformsformspy in get errors 112 selffull cleanfile usrlocallibpython27thistpackagesdjangoformsformspy in full clean 268 self clean formfile usrlocallibpython27thistpackagesdjangoformsformspy in clean form 296 selfcleaned data selfcleanfile usrlocallibpython27thistpackagesdjangocontribauthformspy in clean 85 selfuser cache authenticateusernameusername passwordpasswordfile usrlocallibpython27thistpackagesdjangocontribauth init py in authenticate 55 user backendauthenticatecredentialsfile usrlocallibpython27thistpackagesdjangocontribauthbackendspy in authenticate 18 if usercheck passwordpasswordfile usrlocallibpython27thistpackagesdjangocontribauthmodelspy in check password 275 return check passwordraw password selfpasswordfile usrlocallibpython27thistpackagesdjangocontribauthmodelspy in check password 42 algo salt hsh enc passwordsplitexception type valueerror at accountsloginexception value too many values to unpack,['python'] +239922,why python for loop does not work like c for loop c include stdiohmain int i for i0 i10 i if i5 ii1 printfdi python for i in range10 if i5 ii1 print iwhen we compile c code it goes into a infinite loop whereas in python it does not why notthe python output is0 1 2 3 4 5 5 6 7 8,"['python', 'c']" +239946,listview items are not clickable why i have a listview that uses a customized adapter but i cannot click on the listview item activity for list view package comadhamenayaprojectsimport javautilarraylistimport androidappactivityimport androidcontentcontextimport androidosasynctaskimport androidosbundleimport androidviewlayoutinflaterimport androidviewviewimport androidviewviewonclicklistenerimport androidviewviewgroupimport androidwidgetbaseadapterimport androidwidgetbuttonimport androidwidgetfilterimport androidwidgetfilterableimport androidwidgetlistviewimport androidwidgettextviewimport androidwidgettoastimport comadhamenayaclassesplacepublic class placeslistactivity extends activity private arraylistplace places private arrayliststring items gridviewadapter madapter private listview lvplaces private efficientadapter adap public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutplaces list lvplaces listview thisfindviewbyidridlvplaces new dowanloadplacesexecute private void bindlistarraylistplace places thisplaces places start creating the list view to show articles items new arrayliststring for int i 0 i placessize i itemsaddstringvalueofplacesgetimname adap new efficientadapterthis adapnotifydatasetchanged lvplacessetadapteradap efficientadapter to make a customized list view item public class efficientadapter extends baseadapter implements filterable the function of inflater to convert objects from xml layout file ie mainxml to a programmable layoutinflater inflater context context public efficientadaptercontext context inflater layoutinflaterfromcontext thiscontext context public int getcount get the number of items in the list return itemssize public object getitemint position to return item from a list in the given position return itemsgetposition public long getitemidint position todo autogenerated method stub return 0 public view getviewfinal int position view convertviewviewgroup parent viewholder holder if convertview null convertview inflaterinflaterlayoutadaptor content null holder new viewholder create an object to hold at components in the list view item holdertextline textview convertviewfindviewbyidridtextline holderbuttonline button convertviewfindviewbyidridbuttonline holderbuttonlinesetonclicklistenernew onclicklistener private int pos position public void onclickview v placesremovepos bindlistplaces to bind list items toastmaketextgetapplicationcontextdeleted successfuly toastlength longshow convertviewsettagholder else holder viewholder convertviewgettag bind the data efficiently with the holder holdertextlinesettextstringvalueofplacesgetpositionmname return convertview public filter getfilter todo autogenerated method stub return null viewholder class that represents a list view items static class viewholder textview textline button buttonline downloadrssfeedstask works in a separate thread private class dowanloadplaces extends asynctaskstring void arraylistplace override protected arraylistplace doinbackgroundstring params arraylistplace places new arraylistplace place p new place forint i 0i25i pmname al mathaf hotel placesaddp return places override protected void onpostexecutearraylistplace places bindlistplaces places listxml layoutxml version10 encodingutf8linearlayout xmlnsandroid androidorientationvertical androidlayout widthfill parent androidlayout heightfill parent listview androidlayout widthmatch parent androidlayout heightwrap content androidididlvplaces listviewlinearlayoutadaptor contentxml layoutimageview androidididimageview1 androidlayout widthwrap content androidlayout heightwrap content androidlayout alignleftidtextline androidlayout centerverticaltrue androidsrcdrawablesettings relativelayout,['android'] +239965,how to use cellpadding and cellspacing on html5 am trying to use css3 to set the cellspacing and the cellpadding for my table since html5 does not support these attributesi have found many resources on the internet says that you should use borderspacing and padding using cssunfo i tried all these tricks but it seems that no thing changing at all the spacing is very important because am including image structure on the different cell of the tableso how i can solve it now plz need your help searchtable bordercollapse collapse padding0px 0px 0px 0pxsearchtable td padding0 borderspacing0px 0px,['css'] +239969,using the checkbox hack on live websites so recently there has been a lot examples of what the checkbox hack is possible of with csscsstricks has a good explanation on what the hack doesthe checkbox hack is where you use a connected label and checkbox input and usually some other element you are trying to controlsource more information of the hackwhat recently got me liking the hack was codrops experiment with radio buttons to create filter functionality with just css just amazingthe hack can do some pretty amazing stuff that would require javascript without the problem is that the checkbox and radio buttons is only suppose to be used for forms so it is bad semantics but i do not see the problem of using a hack that is compatible in most browsers and workaround for mobile devices if it means less javascript and better performancedo you think that this kind of hack would be okay to use on live websites even though it is bad semantics or you think it is okay to use,"['html', 'css']" +240012,scenario of extending thread class and implementing runnable interface i am new to thread programming in java and hence this basic question i checked but could not find this question previously askedi read that threads can be created either by inheriting the thread class or by implementing the runnable interfacei saw a code which had both to the same classpublic class threadexample extends thread implements runnable i was wondering what kind of situation would want this and if there is any advantage to this what is it,['java'] +240026,what are python dictionary view objects in python 27 we got the dictionary view methods availablenow i know the pro and cons of the followingdictitems and values keys returns a list so you can actually store the resultdictiteritems and the like returns a generator so you can iterable over each value generated one by one what are dictviewitems and the like for what are their benefits how does it work what is a view after alli read that the view is always reflecting the changes from the dictionary but how does it behave from the perf and memory point of view what are the pro and cons,['python'] +240034,how do you export a method in a cil dll so that a native program can call it i have reviewed ecma 335 and i have only found a reference to the export keyword which seems promising but has very little documentation i have found similar questions on stackoverflow with respect to doing this in c however none of that has lead me anywhere useful so farthe bottom line is i have a cil dll and i want to invoke some of its static methods from a native c application,['.net'] +240036,javalangnumber does not implement or any other operators i am creating a class which is supposed to be able to be used with an array of any type of number float int etc so here is one method i have t extends numberpublic synchronized t average number ret new numberqueue0length for int i 0 i retlength i for int j 0 j size j reti queueji wtf error reti size wtf error return tretexcept this would not compile because number does not implement the or operators event worse javas number class does not implement even the most basic operators like or how can i make a method which returns the average of an array of numbers if java would not let me compile it because it thinks that numbers cannot be added,['java'] +240053,list with repeat objects what is the memory cost after instantiating a list so ignoring the overhead associated with creating a list what is the memory cost of adding the same object to a list over and over i believe that the following is just adding the same pointer to memory to the list over and over and therefore this list is actually not taking up a lot of memory at all can somebody confirm that to be the caselistnewtype list new listnewtypenewtype example new newtypefor int i 0 i 10 i listaddexamplelet us assume that a new newtype takes up a considerable amount more of memory than a pointer doeseditnewtype is a class sorry for not clarifying that,"['c#', '.net']" +240063,conditionally set css class how to convert this erb codediv classhighlight if jobdone into haml code,['ruby'] +240076,how do i include http headers with mediaplayer setdatasource i am passing a uri to the setdatasource method of the mediaplayer object i am targeting api version less than 14 so believe that i cannot use the new method that allows headers to be included how can i include headers specifically authentication header with the mediaplayer request and still support older android devicesmy code looks like mediaplayersetdatasourceurl mediaplayersetaudiostreamtypeaudiomanagerstream music mediaplayerprepareasync,"['java', 'android']" +240110,time tracking in java using currenttimemills i got an interesting timetravel problem today using the following codefor int i 0 i 1 i long start systemcurrenttimemillis some code here systemoutprinti t systemcurrenttimemillis start start systemcurrenttimemillis some code here systemoutprintlnt systemcurrenttimemillis startand i got the result0 15 606and it seems that it is not repeatable anyone has any clues on what happened inside during the running time just curiousnew edit i used a small test to confirmed the answers below i run the program and change the system time during the run and finally repeat the timetravel0 3563323 163case closed thanks guysmore words both currenttimemillis and nanotime are systemtimer based so they will be not monotonic if the system timer is updated turned back specifically it is better to use some internetbased timer for such cases,['java'] +240111,sql server is using rowcount safe in multithreaded applications i am using sql server 2008i have a table a which accepts many insertupdate in one seconds after insert update i want to get the number of rows affectedinsert into a id values 1if rowcount 0 print no rows affectedwhile query is being executed the same query may be called again by application so what happens if the current execution is after insert but before if block at that momentdo you think rowcount may give wrong result for that reasonor is it always safe in its context,['sql'] +240154,similar to jquery closest but traversing descendants is there a function similar to jquery closest but for traversing descendants and returning only closest onesi know that there is find function but it returns all possible matches not closestedithere is definition of closest at least for mein first place all childrens are traversed then each individuals childrens are traversedin example given below id2 is closest closest descendants of idfindmyclosestdescendantdiv idfindmyclosestdescendant div div classclosest id1div div div classclosest id2divdivplease see jsfiddle link,['jquery'] +240183,is there a simpler way to check multiple values against one value in an ifstatement basically what i want to do is check two integers against a given value therefore classically what you would do is something like thisjust to get some values to checkint a ba intmathrandom5b intmathrandom5the actual thing in questionifa 0 b 0then do somethingbut is there a more concise format to do this possibly similar to this which returns a bad operand type just to get some values to checkint a ba intmathrandom5b intmathrandom5the actual thing in questionifab 0then do something,['java'] +240185,php declare arguments type of a function i am tring to make a function with declared arguments types to check quickly if they are in the right format but when is a string return allways that errorcatchable fatal error argument 2 passed to myfunction must be an instance of string string given called in path to file on line 69 and defined in path to file on line 49function myfunction array array string string int integer return args format correct myfunctionarray1234 test 1234where is the mistake,['php'] +240194,is there a best practicescoherent way to update a database field that contains a hash keyvalue store i am referring to rails 32s data store feature in which there is the option to store keyvalue stores in a textfield even if youre using a relational database like mysqlit works fine when programmatically manipulating the fieldsbut what documentation is there to update these fields from a restful html form or is this something that is not recommended at all that is the better solution would be to go to nosql,['mysql'] +240215,android call python script via sl4a from java code is it possible to callrun a python script file from java code on the android platform using sl4a basically i have a full blown java android app and i have several python scripts that scrape some information from various web pages i would like to be able to call these python scripts with the web page and get the results back is this possible if so can anyone point me in the direction of an example or twothank youharry,"['java', 'android', 'python']" +240219,string to array of integers php i wan to convert a string for example 123456 to an array of integers in phpi find functions that only have access to the first character of the string for example 1how can i conert the whole string to arrayfunction read id txt handle file fopentemporalfiletxt r i0 while array vari fgetshandle file 4096 echo br print rarray vari i fclosehandle file tempexplode array var0 return temp,['php'] +240229,storing multiple values in a session variable with php i am creating a site which has a shopping cart i do not need any special functionality so i am creating the cart on my own rather than integrating any ready one my products do not have a predefined price in the database the price is being generated dynamically based on the values entered by a user on the product page so the user chooses some specifications enters the quantity and i get the following valuesitem idquantitytotal pricei need to store those values in the session variable and then loop over it when needed to get the results and print them in the shopping cart the problem is that there are a lot of products and i need to store all those values quantity total price thistinctively for the chosen product that said how do i store item id quantity and total price in the session variable and associate those values with each other thanks for helpingedit my code implementing michaels suggestionsitemid dbescape postproductid itemquantity dbescape postitemquantity totalprice dbescape posttotalprice sessionitems array sessionitemsitemid arrayquantity itemquantity total totalprice var dump session,['php'] +240238,cannot resolve symbol objectstatemanager i have getting an error of cannot resolve symbol objectstatemanager when trying to call it on my database context from entity framework 4 i cannot find anyone else having this issue i have tried using systemdata and systemdataobjectsis there a specific entity framework that needs to be made in order to use the objectstatemanager or am i missing some sort of install package i am using database first entity frameworkhere is the code it is giving my error line 7httppost public actionresult editprofileuser user if modelstateisvalid dbusersattachuser dbobjectstatemanagerchangeobjectstateuser entitystatemodified dbsavechanges return redirecttoactionprofile,['c#'] +240240,why c does not support the intersection of protected and internal accessibility protected internalthe union of protected and internal accessibility this is less restrictive than protected or internal alonethe clr has the concept of intersection of protected and internal accessibility but c does not support thisso my question iswhats the meaning of omitting this access modifier is there a concrete reason so why c should not support it,['c#'] +240247,how do i learn python 2 if i already know python 3 i have some knowledge of python 3 i am not a beginner but i am not an expert i am interested in web development so i want to use django what are the differences between the two versions of python how should i switch from 3 to 2x,['python'] +240273,hibernatejpa importsql utf8 characters corrupted i am using importsql to write my development data to db i am using mysql server 55 and my persistencexml is herexml version10 encodingutf8persistence version20xmlns xmlnsxsixsischemalocation 2 0xsdpersistenceunit namemobilhm transactiontyperesource local providerorghibernateejbhibernatepersistenceprovider classtrcomstigmadbentitydoctorclass classtrcomstigmadbentitypatientclass classtrcomstigmadbentityrecordclass classtrcomstigmadbentityuserclass properties property namehibernatehbm2ddlauto valuecreate property namehibernateshow sql valuetrue property namehibernateformat sql valuetrue auto detect annotation model classes property namehibernatearchiveautodetection valueclass datasource property namehibernateconnectiondriver class valuecommysqljdbcdriver property namehibernateconnectionusername valuemobilhm property namehibernateconnectionpassword valuemobilhm property namehibernateconnectionurl valuejdbcmysqllocalhostmobilhm property namehibernatedialect valueorghibernatedialectmysqldialect propertiespersistenceunitsome characters in my importsql is not shown correctly in db for example character a14 becomes aa14 in db default charset in mysql is utf8 and i am creating tables like create table doctor doctorid int unsigned not null auto increment name varchar45 not null surname varchar45 not null primary key doctorid engineinnodb default charsetutf8it is weird that if i import using mysql importexport manager data is correct but using hibernatehbm2ddlautocreate makes characters corruptedhow can i solve thiseditalso i have tried adding property namehibernateconnectionuseunicode valuetrue property namehibernateconnectioncharacterencoding valueutf8 property namehibernateconnectioncharset valueutf8 to persistencexml but it did not helpfixi have solved it eventually i am using tomcat and that is the point of corruption not hibernate or mysql i have started it with set java optsdfileencodingutf8 command and my problem goes awaythe title of question became misleading now sorry for that,['mysql'] +240293,are genericlist and genericdictionary thread safe in net how do we know whether a method is thread safe or notfor example if i check there is nothing that indicates its threadsafety,['.net'] +240342,jquery and dom manipulation performance issue in ie8 i have developed a module at my work in jquery it is basically a table with the following functionalitycell level editrow level edit drop and drop rows to change positionshowhide columnscolumn resizeevery thing works fine on latest browsers like ff90 ie9 and chrome but in older browsers like ie8 and ff36 as the number of rows in the table increases the performance of the page reduces significantly i have tried many optimization from jquery and dom manipulation but still no effect on the performance any idea if i am missing something or some tip to make the performance better ie to an acceptable level i have not use any plugin everything is my custom implementation the javascript file is quite huge and i am looking for some general good practices and tips,"['javascript', 'jquery']" +240343,how to get year and month from a date php how to get year and month from a given dateeg datevalue 20120105from this date i need to get year as 2012 and month as january,['php'] +240358,find angle of a point from center of circle if i have an image 720 720 that looks like thishow do i work out the angle of the touched xy given that the center x and y are 360 360a lot of calculations i see for this assume the origin is 00 which is top left so i get incorrect resultsi am assuming 0 is always to the top and not rotated,['java'] +240360,64bit linux performance issue with memset i am debugging an application that is running quite a bit slower when built as a 64bit linux elf executable than as a 32bit linux elf executable using rational ibm quantify i tracked much of the performance difference down to drum roll memset oddly memset is taking a lot longer in the 64bit executablei am even able to see this with a small simple applicationinclude stdlibhinclude stringhdefine buffer length 80int main unsigned char buffer mallocbuffer length sizeofunsigned char forint i 0 i 10 i memsetbuffer 0 buffer length sizeofunsigned chari build like this gcc m32 stdgnu99 g o3 mscand gcc m64 stdgnu99 g o3 msc the wallclock time as reported by time is longer for the m64 build and quantify confirms that the extra time is being spent in memsetso far i have tested in virtualbox and vmware but not baremetal linux i realize i need to do that next the amount of extra time spent seems to vary a bit from one system to the nextwhats going on here is there a wellknown issue that my googlefoo is not able to uncoveredit the thisassembly gcc s on my system shows that memset is being invoked as an external function32bitlbb2 loc 1 14 0 movl 80 8esp loc 1 12 0 addl 1 ebx loc 1 14 0 movl 0 4esp movl esi esp call memset64bitlbb2 loc 1 14 0 xorl esi esi movl 80 edx movq rbp rdilvl1 loc 1 12 0 addl 1 ebx loc 1 14 0 call memsetsystemcentos 57 2618274171el5 x86 64gcc 412intelr coretm i72600k cpu 340ghz virtualboxthiscrepancy is worse on a xeon e5620 240ghz vmware,['c'] +240385,how to know the caller class of a function hello is there a way to know the caller class name of a function specifically for a javagwt application,['java'] +240407,systemconsole returns null from eclipse but fine with command prompt when i use systemconsole from eclipse helios it always returns null however when i use it directly from command line ie compiling and executing a java source code manually from command prompt i do get a console object to know why this happens i checked this link according to it when i run my java code from eclipse a background job scheduler must be starting my jvm what does this meanand how differently is my jvm started when i start it from command linei also checked this link here mcdowell says that cmdexe is a console device so then i am again confused that exactly is a console device,['java'] +240427,li float vs thisplay inline is there a best choice out of float left or thisplay inline for aligning list items horizontallyeg personally i thislike float but that maybe more of an emotional thing rather than logical,['css'] +240430,ios safari scroll to top does not work on certain pages why thisclaimer the site has meanwhile been updated this issue does not occur anymore with the new version of the design on a new site i built i noticed a weird quirk in safari ios 5 usually you can tap the black bar on top of safari to scroll to the top of any webpage on my new website this works on the homepage but not on single article pages try it versbetonnl works vs versbetonnl201201versvloeibaar does not workhow can i debug such a situation as far as i know there is no firebug or similar debugging tool for ios,"['jquery', 'ios']" +240433,acra how can i write acra report to file in sd card i can use acra library to manage force close error by handling uncaught exception the report can sent to google doc email and custom web service successfully but what i wanthow can i write the report to file ex sdcardmyappmylogtxt why i want thismy app user may not have internet connection while force close occurs if so then i will miss the report if i write the report to file then i can sent to my server when the internet connection available,['android'] +240436,crossdomain connection in socketio is it possible to use socketio in a cross domain manner if so how the possibility is mentioned around the web but no code examples are given anywhere,['javascript'] +240437,maven javac source release 16 requires target release 16 note this appears to be a limit in the javac programi have java 6 code that needs to be built for a java 5 jvm my previous work with the javac ant target both with the jdk compiler and with ecj led me to believe that it would simply be a matter of setting source and target for javac hence this pomxml fragmentplugin groupidorgapachemavenpluginsgroupid artifactidmavencompilerpluginartifactid version232version configuration source16source target15target configurationpluginwhich works as expected from within eclipse 37 with maven support unfortunately running maven directly from the command line give mejavac source release 16 requires target release 16which is the same as generated by javac source 16 target 15 to clarify this is the official openjdk 6 for ubuntuxjenkins javac versionjavac 160 20xjenkins javac source 16 target 15javac source release 16 requires target release 16xjenkinsthe official oracle java 7 jdk for windows show the same behaviornote i do not want to build against java 5 libraries or anything just that the active javac generates java 5 compatible bytecodehow do i get what i want while still being compatible with the eclipse maven plugin edit in addition to the override i also want to compile against the jaxws libraries in java 6 when used but still generated java 5 byte code i can then add the jaxws libraries deliberately in the web container when deploying to a java 5 installationedit it turns out that mavencompilerplugin can be told to use another compiler and the eclipse compiler can do this plugin using the eclipse compiler allows for different source and target which is a good thing outweighing that this is a rarely used combination and most people use javac this should also allow us to run maven builds on a jre and not a jdk note that initial experiments with an earlier version of mavencompilerplugin showed that the eclipse compiler bundled with that gave incorrect lines in the debug information by using a newer version of the plexuscompilereclipse plugin this is hopefully less of an issue if not we must also bundle a newer version of the eclipse compiler itself groupidorgapachemavenpluginsgroupid artifactidmavencompilerpluginartifactid version30version configuration source16source target15target debugtruedebug optimizefalseoptimize forktruefork compilerideclipsecompilerid configuration dependencies dependency groupidorgcodehausplexusgroupid artifactidplexuscompilereclipseartifactid version21version dependency dependencies pluginwhich compiles the class to java 15 bytecode without complaints this is also supported out of the box for m2e for eclipse java ee 422edit i found that of all things the javadoc tool thislikes the output from the eclipse compileredit 20150628 i did a quick test recently and the latest ecj corresponding to eclipse 44 worked fine with javadoc,['java'] +240449,what is the exhaustive list of all androidintentaction actions available in the android sdk hi fellowsi would like to know if there is some exhaustive reference of all intent actions defined in the standard android sdk i am thinking of the full androidintentactionsomeaction names not the restricted list of conveniently aliased actions defined in the intent class eg intentaction view intentaction power connected etcfor those who believe all intent actions are aliased in the intent class i was one of them until very recently i have at least one action which is not androidintentactionhdmi plug defined in mediajavaandroidmediaaudioservicejava and i believe there are many othersbut i could not find some exhaustive list in the android reference so maybe if you can direct me to some place i can find it thanks update 23012012 15h36 thanks to commonsware for mentioning hdmi plug is not at all part of the android sdk it was a bad example but still there are intents that are not defined in intentjava such as telephonymanageraction phone state changed,['android'] +240451,how to turn off the automatic proxy detection in the amazons3 object when using the amazons3 object for the first time after the application starts there is a large delay of approx 14 seconds this large time delay is not present for all subsequent callsi have encountered this exact delay issue before with other http related classes and it is caused when the class in question tries to determine the local machines proxy settings and whether to use them or notto stop this from happening with webclient you set webclientproxy null and it does not try to auto detect the proxy settings but i cannot figure out how to thisable the proxy detection functionality of the amazons3 objecti have specifically tried setting the proxyhost to null s3client awsclientfactorycreateamazons3clientawsaccesskey awssecretaccesskey new amazons3config proxyhost null which did not work we are currently using the amazon net sdk v13170is there a way to turn off the proxy detection,"['c#', '.net']" +240462,sorting chapter stuff like 14123 and 14101234 i have got various chapters with different depthsso there are 141 and 1442 and 147882 and so onalphanumerical sorted the 1410 will appear before 142 that is bad it should come after 149is there an easy way to sort theese without adding leading zeros fe with linq,['c#'] +240465,stdmapemplace missing outdated libraries i am trying to use the c11 emplace function of a map but netbeans says a map has no such function looking at the headers it is right there is no mention on fedora 16 of emplace which is all well and good you know but i kinda wanna use emplacehow do i go about enabling this functionality i know for a fact that it is existed since march of last year probably earlier a thorough search shows that emplace basically only exists on my system in the headers for lists and vectors since there has not been a major revision of c in almost a decade i am not having any luck finding documentation on what to do if the libraries are wrong,['c++'] +240552,how to check if javalangreflecttype is an enum i want to check whether a javalangreflecttype instance represents an emum object or noti can check whether it is an instance of a specific class using comparisons egtype stringclass worksbut this does not seem to work for the enum classtype enumclass does not work this makes sense as the instance would be of a specific enum but i would like to check whether the type is for any enum or notcould someone explain the obvious to me of how to tell whether the type is an enum or not please,['java'] +240563,delete row in table view with fetchedresultcontroller during swype deleting most importatnt lines of this method voidtableviewuitableview tableview commiteditingstyleuitableviewcelleditingstyleeditingstyle forrowatindexpathnsindexpath indexpath if editingstyle uitableviewcelleditingstyledelete table deleterow selffetchedresultscontroller objectatindexpathindexpath selfmanagedobjectcontext deleteobjectdeleterow tableview deleterowsatindexpathsnsarray arraywithobjectindexpath withrowanimationuitableviewrowanimationfade when deleting row i get this error terminating app due to uncaught exception nsinternalinconsistencyexception reason invalid update invalid number of rows in section 2 the number of rows contained in an existing section after the update 1 must be equal to the number of rows contained in that section before the update 1 plus or minus the number of rows inserted or deleted from that section 0 inserted 1 deleted and plus or minus the number of rows moved into or out of that section 0 moved in 0 moved outif i comment last line of code tableview deleterowsatindexpaths everything works fine but i have to refresh view to see that row was deletedhow to do it properlyeditconsidering kyr dunenkoff responce i have added voidcontrollernsfetchedresultscontrollercontroller didchangeobjectidanobject atindexpathnsindexpathindexpath forchangetypensfetchedresultschangetypetype newindexpathnsindexpathnewindexpath uitableview tablev self tableview switchtype case nsfetchedresultschangedelete tablev deleterowsatindexpathsnsarray arraywithobjectindexpath withrowanimationuitableviewrowanimationfade break voidcontrollerdidchangecontentnsfetchedresultscontrollercontroller self tableview endupdates voidcontrollerwillchangecontentnsfetchedresultscontrollercontroller self tableview beginupdateshowever this did not change the crashing error atm it just caused that adding new rows is not working any more,"['ios', 'objective-c']" +240578,sql statement triggers vs for each row edit i do not know what thistro it is it is in an exam paperi am just not getting this sadly i am quite happy with row level triggers but could someone explain to me how the results would differ if the trigger was statement level insteadrelationstatement triggerrow level triggeremployeeid varchar230 salary numbercreate trigger autoraiseafter insert on employeereferencing new table as ntupdate employeeset salary salary select avgsalary from ntcreate trigger autoraiseafter insert on employeereferencing new table as ntfor each rowupdate employeeset salary salary select avgsalary from nti understand that in the for each row trigger it will fire for each row affected by the triggering statement now would the statement level trigger modify the results differently say if i inserted five tuples in one statement would it set the salary etc for them all if so whats the benefit of the row level trigger herei have tried searching but i just cannot get my head around itthanksedit now i am just being dense but would either trigger produce different outputs for the statement level trigger if i used the example valuesin table before triggers creationa50added in one statement after trigger is createdb70 c30the first trigger would set the salary for each tuple being inserted surely so the first would become 120 as the average is 50 70 50 120 and the second would become 80 if this is true how does the second trigger differ in results,['sql'] +240607,how to use guices assistedinject i have read but it does not say how to pass in the values of the assistedinject arguments what would the injectorgetinstance call look like,['java'] +240608,how to configure spring to avoid setting pragma nocache my system is spring mvc based and i checked that spring automatically sets pragma nocache the system is available to the users through ssl when the users try to download something using the internet explorer 7 or 8 an error like internet explorer cannot download file from server appears more details enusq316431i tried to configure the webcontentinterceptor like the code bellow but does not workmvcinterceptors bean idwebcontentinterceptor classorgspringframeworkwebservletmvcwebcontentinterceptor property namecacheseconds value2100 property nameuseexpiresheader valuefalse property nameusecachecontrolheader valuefalse property nameusecachecontrolnostore valuefalse beanmvcinterceptorswhat can i do avoid spring send the pragma nocache and related to cache controlregards,['java'] +240613,how to do perpage javascript with the rails asset pipeline i understand that for performance reasons it is better to let the asset pipeline concatenate and minify all my javascript and send the whole lot with every page request that is fair enoughhowever a bunch of my javascript is things like binding specific behaviours to specific page elements stuff likebuttonclickfunctione inputselvalthisname and i would feel more comfortable if i knew that this code was being executed only on that page not on evey other page which might coincidentally have elements with the same ids or which matched the same selectors how do people deal with thisi would rather not put all this stuff inline in elements just because when it gets to be more than about two lines long keeping javascript correctly indented inside an htmlerb file is more work than it needs to be,"['javascript', 'ruby-on-rails']" +240630,php session not saving i have this written at the very first line on every page of my website includerestdphpand restdphp contains the following lines session startifisset sessionidelse headerlocationindexphpthe problem i am facing is that when ever i click or do something on my website it logs me out and takes me to indexphpim sure its something to do with the session ive tried every single thing to avoid this problem but i ahve used restdphp because i dont want anyone to copy the url of someone and paste and get into the websiteanyone who is logged in only can view others pages if they arent logged in then they will be redirected to indexphpedit and guys a confusing thing is that all this is working fine on my testing server which is easyphp5380 but this problem is coming up when i upload all the files to my server,['php'] +240635,how to call a method when back button on a uinavigationcontroller is pressed iphone how can i call a method when the back button on a uinavigationcontroller is pressed i need to be able to call a method before the previous view is thisplayed is this possible if so please can someone advise on how to do this,['iphone'] +240647,how to override zurb foundation css properties using rails 31 hi there im working on a new rails app and i just started to use foundationi did the installation using rails g foundationinstalleverything is working as espected i mean by that i can see the css in my source code and also the visual effect of it pi just dont understand how to override the defaults proprieties of zurb foundationi saw online that im supposed to edit some foundationcss or appcss but here doesnt seems to be any file like that in my application folderi did the installation by editing the gemfile then a bundle installcheers,"['ruby-on-rails', 'css', 'ruby']" +240714,persistent python subprocess is there a way to make a subprocess call in python persistent i am calling a program that takes a while to load multiple times so it would be great if i could just leave that program open and communicate with it without killing itthe cartoon version of my python script looks like thisfor text in textcollection myprocess subprocesspopenmyexecutable stdin subprocesspipe stdout subprocesspipe stderr none myoutputtext err myprocesscommunicateinputtexti need to process each text separately so joining it all into one large text file and processing it once is not an optionpreferably if there is an option like thismyprocess subprocesspopenmyexecutable stdin subprocesspipe stdout subprocesspipe stderr none for text in textcollectionfor text in textcollection myoutputtext err myprocesscommunicateinputtextwhere i can leave the process open i would really appreciate it,['python'] +240748,how can i remove the extra and different pseudopadding on text inputs in webkit and gecko the problem only happens on inputtypetext in webkit no matter what i do there is the equivalent of an extra padding 1px 0 0 1px top and left only on the elementa similar problem happens in gecko inputtypetext has an equivalent extra padding 1px 0 0 1px and inputtypebutton has an extra padding 1px 0 0 0heres a jsfiddle showing you everything i have tried and nothing works interestingly when you set the lineheight of all the elements to 0 the only unaffected elements are the ones with the problems so i am assuming that the browser is defaulting to a specific lineheight and i am now looking for a way to override iti have found nothing in the webkit base styles that would do this but feel free to check yourself this is not a mozfocusinner problem or an appearance none problem or a boxsizing problem or an outline problem and i cannot find any other solutionsedit see my answer below for the vertical padding problems but i am still looking for a solution to the extra paddingleft 1px equivalent on textinputs only in webkit and gecko,"['html', 'css']" +240751,enforcing java annotations at compile time hi i wanted to make sure that an annotation is present at compile time in a class is this possible i realize that annoataions are themselves classes so i assume so but im just not sure syntactically where and how to enforceimplement such a structure in my classes,['java'] +240792,unsupportedclassversionerror unsupported majorminor version 510 unable to load class possible duplicateexception in thread main javalangunsupportedclassversionerror a unsupporte d majorminor version 510 i have developed an web application in java using jdk 170 eclipse ide indigo and is running that application on the tomcatapachetomcat7023 configured in eclipse ide when i tried to run my application through ide it runs fine but when i created its war and placed it in apache deployment folderwebapps and run it from outside the ide the start page gets successfully loaded but when i tried to do any operation over it it gives me an errorunsupportedclassversionerror unsupported majorminor version 510 unable to load class beanmyclassnamei have checked the java version outside ide its jdk 170 and also the java home environment variable is set to cprogram filesjavajdk170 01,['java'] +240808,split list of datetimes into days i have got a sorted list of datetimes with day gapslist of dts datetimedatetime2012110 datetimedatetime2012100 datetimedatetime2012120 datetimedatetime2012130 datetimedatetime2012150 and i would like to split them in to a list for each dayresult datetimedatetime2012110 datetimedatetime2012100 datetimedatetime2012120 datetimedatetime2012130 empty list for no datetimes on day datetimedatetime2012150 algorithmically it should be possible to achieve at least onperhaps something like the followingthis obviously does not handle missed days and drops the last dt but it is a startdef dt to dlist of dts result start dt list of dts0 day start dt for i dt in enumeratelist of dts1 previous start dt if i 0 else list of dtsi1 if dtday previousday or dtmonth previousmonth or dtyear previousyear split to new sublist resultappendday day loop for each day gap dayappenddt return resultthoughts,['python'] +240815,jdk jre an jars compatibility i know a bit about jdk and jre source and binary compatibility eg this and this but not sure about the following situationconsider i have an application which is compiled using jdk5 and runs on jre6 it uses some libraries jars which are also compiled using jdk5now i want to compile my application using jdk6 what new problems could arise in runtime in such a case particularly in compatibility with the old jars should i fully retest the application touch every library or can rely on promised jdkjre compatibility,['java'] +240846,sql server need to escape i need to escape in an sql query for sql serverselect from sometable where name like somethingi actually am looking for a before something and i do not want it to act like a wildcard i tried select from sometable where name like somethingbut get error message from thismsg 102 level 15 state 1 line 1 incorrect syntax near something msg 105 level 15 state 1 line 1 unclosed quotation mark after the character string,['sql'] +240864,creating and managing multiple connections in rethis python i am using rethis to store two databases 0 and 1 via the rethispy client library i would like to create two connections for each database currently i am doing this connection0 rethisconnectionhost localhost port 6379 db 0 connection1 rethisconnectionhost localhost port 6379 db 1 connection0connecthowever i do not seem to find a way to create a rethis object from the connection store0 rethisrethisconnection0 store0infotraceback most recent call last file stdin line 1 in module file libraryframeworkspythonframeworkversions70libpython27sitepackagesrethis2411py27eggrethisclientpy line 341 in info return selfexecute commandinfo file libraryframeworkspythonframeworkversions70libpython27sitepackagesrethis2411py27eggrethisclientpy line 278 in execute command connectionsend commandargs file libraryframeworkspythonframeworkversions70libpython27sitepackagesrethis2411py27eggrethisconnectionpy line 258 in send command selfsend packed commandselfpack commandargs file libraryframeworkspythonframeworkversions70libpython27sitepackagesrethis2411py27eggrethisconnectionpy line 241 in send packed command selfconnect file libraryframeworkspythonframeworkversions70libpython27sitepackagesrethis2411py27eggrethisconnectionpy line 187 in connect sock self connect file libraryframeworkspythonframeworkversions70libpython27sitepackagesrethis2411py27eggrethisconnectionpy line 198 in connect sockconnectselfhost selfport file libraryframeworkspythonframeworkversions70libpython27socketpy line 224 in meth return getattrself socknameargstypeerror coercing to unicode need string or buffer connection foundam i making a rookie mistake here,['python'] +240910,how to align center the text in html table row i am using a html table i want to align the text of td to the center in each cellhow to align the text as horizontally and vertically center,"['html', 'css']" +240917,advantage of schemaless data storing over data storing with schema i want to choose a back end web service for my app reading documentation of these servicesparse proxomo cocoafish stackmob etc reveal that some of them offers to store data in schemaless form while other mention that schema must be specified apriori i understand what is schema of data is and hope schemaless will be easy to use but want to know merits and demerits of each any explanation will be greatly appreciated,"['android', 'iphone']" +240923,quartz scheduler max thread count property i have the following situation 8 tasks scheduled to run with orgquartzthreadpoolthreadcount set to 5 but in reality i can see that all 8 tasks are running how this could be possibleif i set orgquartzthreadpoolthreadcount5 and i submitted 10 tasks for quartz it is true that only 5 tasks will run in parallel what is the meaning of orgquartzthreadpoolthreadcount propertyi have such designwe have some tasks that do some work on entities in dbwe have special jobrunner that executes one taskwe scan for tasks to run and schedule task for running in quartz service that is configured with schedulerfactorybean with orgquartzthreadpoolthreadcount set to 5as i understand if quartz service with schedulerfactorybean will have 5 tasks running and if we will try to schedule additional task quartz itself should throw an exception is this truethanks,['java'] +240928,trouble with static field and singleton i have two classespublic class singleton private singleton private static class instanceholder private static final singleton instancenew singleton public static singleton getinstance return instanceholderinstance andpublic class someclass private static final singleton singletonsingletongetinstance public static singleton getsingleton return singleton problemif somewhere actually in another singletonclass constructor i use something like thisprivate final singleton singletonsomeclassgetsingletonmy singleton always nullquestion why,['java'] +240975,hosting an wcf service into a website issue systemargumentexception servicehost only supports class service types i have something like thismathservicelibrary wcf service libraryservicecontractpublic interface imathservice operationcontract int addint x int y operationcontract int multiplyint x int ypublic class mathservice imathservice public int addint x int y return x y public int multiplyint x int y return x y behaviors servicebehaviors behavior namedefaultservicebehavior servicemetadata httpgetenabledtrue behavior servicebehaviorsbehaviorsservices service behaviorconfigurationdefaultservicebehavior namemathservicelibrarymathservice endpoint addressmex bindingmexhttpbinding contractimetadataexchange endpoint addressmath bindingwshttpbinding contractmathservicelibraryimathservice host baseaddresses add baseaddresshttplocalhost8080 baseaddresses host service servicesif i run this i can see the wcf test client and everything is oknow i want to host this service into iis so i create a web site and add a reference to mathservicelibraryi have this mssvc servicehost languagec debugtrue servicemathservicelibraryimathservice and this webconfig systemservicemodel services service behaviorconfigurationdefaultservicebehavior namemathservicelibrarymathservice endpoint addressmex bindingmexhttpbinding contractimetadataexchange endpoint address bindingwshttpbinding contractmathservicelibraryimathservice identity dns valuelocalhost identity endpoint service services behaviors servicebehaviors behavior namedefaultservicebehavior servicemetadata httpgetenabledtrue servicedebug includeexceptiondetailinfaultsfalse behavior servicebehaviors behaviors servicehostingenvironment multiplesitebindingsenabledtrue systemservicemodelwhen i right click on mssvc view in browser i get thisdescription an unhandled exception occurred during the execution of the current web request please review the stack trace for more information about the error and where it originated in the codeexception details systemargumentexception servicehost only supports class service typessource erroran unhandled exception was generated during the execution of the current web request information regarding the origin and location of the exception can be identified using the exception stack trace belowstack traceargumentexception servicehost only supports class service types systemservicemodeldescriptionservicedescriptiongetservicetype servicetype 129075 systemservicemodelservicehostcreatedescriptionidictionary2 implementedcontracts 55 systemservicemodelservicehostbaseinitializedescriptionurischemekeyedcollection baseaddresses 154 systemservicemodelservicehostinitializedescriptiontype servicetype urischemekeyedcollection baseaddresses 49 systemservicemodelservicehostctortype servicetype uri baseaddresses 151 systemservicemodelactivationservicehostfactorycreateservicehosttype servicetype uri baseaddresses 30 systemservicemodelactivationservicehostfactorycreateservicehoststring constructorstring uri baseaddresses 420 systemservicemodelhostingmanagercreateservicestring normalizedvirtualpath 1440 systemservicemodelhostingmanageractivateservicestring normalizedvirtualpath 44 systemservicemodelhostingmanagerensureserviceavailablestring normalizedvirtualpath 615 serviceactivationexception the service mathwebsitemssvc cannot be activated due to an exception during compilation the exception message is servicehost only supports class service types systemruntimeasyncresultendiasyncresult result 679246 systemservicemodelactivationhostedhttprequestasyncresultendiasyncresult result 190 systemservicemodelactivationhostedhttprequestasyncresultexecutesynchronoushttpapplication context string routeservicevirtualpath boolean flowcontext boolean ensurewfservice 234 systemservicemodelactivationhttpmoduleprocessrequestobject sender eventargs e 355 systemwebsynceventexecutionstepsystemwebhttpapplicationiexecutionstepexecute 148 systemwebhttpapplicationexecutestepiexecutionstep step boolean completedsynchronously 75 i cannot figure out what i am missing,['.net'] +241001,pros and cons of using an existing net assembly versus a commandline tool for same purpose i have searched the internet and i cannot seem to find anything related to this topic i would think there would have been some thiscussion on it i just cannot find itbasically what i am looking for is good reasons to use an existing net assembly to do the same thing an older commandline executable would do therefore if i used the assembly i would include it and begin using it in my c code to us the old commandline tool i would do a procestart and so forthbackground on this isi have a requirement to perform pgp encryption and decryption on files transferred to and from our system my current options are to use the commandline gpg tool or the bouncy castle net assemblyi have been asked why i do not just automate the old gpg commandline tool within my code i would like to answer this with some intelligence right now i can only think of two reasonserror handling i should be able to not only get better error information using the net assembly but handle them better via the trycatch with exceptions etc i could even roll my own exceptions as needed etccode portability anything i build with the net assembly is more or less stand alone i do not need to find and copy the gpg executable to each place i copy the applications i write using itperformance possibly i do not have any experience or data regarding thisi would appreciate any input on this topic,"['c#', '.net']" +241035,animate spinner when loading new page i have a uitableview which from an external rss feedwhen you select a row it uses navigationcontroller and slides in from the right the problem is that the rss feed contains images therefore it can can take a few seconds to load and without any indication of what is going on you can mistake it for an application crashi decided to add a spinner so that you know that new page is loadinghere is my coderootviewcontrollerm voidtableviewuitableview tableview didselectrowatindexpathnsindexpath indexpath nslogloading new pagetableview deselectrowatindexpathindexpath animatedyesdetailsviewcontroller detailviewcontroller detailsviewcontroller alloc initwithnibnamedetailsviewcontroller bundlenildetailviewcontrolleritem rssitems objectatindexfloorindexpathrow2selfnavigationcontroller pushviewcontrollerdetailviewcontroller animatedyesdetailviewcontroller releaseuiactivityindicatorview spinner uiactivityindicatorview alloc initwithactivityindicatorstyleuiactivityindicatorviewstylegrayspinnercenter cgpointmake160 240selfview addsubviewspinnerspinner startanimatingspinner releasedetailsviewcontrollerm voidviewdidload super viewdidload nsstring imgurl item objectforkeyimage nsdata mydata nsdata alloc initwithcontentsofurlnsurl urlwithstringimgurl item photoimage uiimage alloc initwithdatamydata item titletext item objectforkeytitle item datetext nsstring stringwithformatdate item objectforkeydate item timetext nsstring stringwithformattime item objectforkeytime item costtext nsstring stringwithformatcost aitem objectforkeycost item infotext item objectforkeydescription selfnavigationitemtitle event typethere are two problems with this codethe spinner does not active until after the new page has loadedthe spinner does not thisable once loadedif anyone could help me with this problem i would be truly gratefully,"['objective-c', 'ios']" +241051,run code only if script called from the command line so when i call my script from the command line i want it to take in an int and do something with the valueruby scriptrbputs argv0 etchowever whenever the script is loaded or required and not called from command line i want to completely skip this part of the code how can i detect whether the script has been called via command line or just loaded thanks,['ruby'] +241053,uitableview change header title color i am styling the uitableview in inappsettingskit and want to change the color of the header titlethe labels without title and text field should be white how can this be donethanks,"['iphone', 'ios']" +241064,python conditional module object has no attribute error with personal package thistinct from circular import issue i am getting a module object has no attribute error when trying to use a package heirarchy i created the error is reminiscant of the error you get when there is a circular import ie module a imports b and module b imports a but i cannot see that issue here i have gone through many posts with a similar error but none of the explanations i saw quite fitthis was seen with python 271 and python 243i have watered it down to the following exampleconsider the following heirarchy see code belowalphaalpha init pyalphabravoalphabravo init pyalphabravocharliepyalphabravodeltapyalphabravoechopythe module charlie imports echo which in turn imports delta if the alphabravo init py like alpha init py is essentially blank a script can doimport alphabravocharliethe problem surfaces if i try to import alphabravocharlie in alphabravo init py with the thinking i could surface relevant classesmethods there and a script would do import alphabravocodealpha init pyblankalphabravo init pyimport alphabravocharliealphabravocharliepyimport alphabravoechodef charlie foox return strxdef charlie barx return alphabravoechoecho bizalphabravodeltapydef delta foox return strxalphabravoechopyimport alphabravodeltaprint alphabravodeltadelta foo1def echo biz return blahif i trypython c import alphabravoi gettraceback most recent call last file string line 1 in module file homekmkc980svnworkingazcifpythonlibalphabravo init py line 1 in module import alphabravocharlie file homekmkc980svnworkingazcifpythonlibalphabravocharliepy line 1 in module import alphabravoecho file homekmkc980svnworkingazcifpythonlibalphabravoechopy line 2 in module print alphabravodeltadelta foo1attributeerror module object has no attribute bravobut if i comment out the import line in alphabravo init py then all seems okpython c import alphabravopython c import alphabravocharlie1moreover if i use the same code above including the import line in alphabravo init py but edit everything to exclude the alpha level of the hierarchy it seems to work fineso the hierarchy is now justbravobravo init pybravocharliepybravodeltapybravoechopyand i change all the lines with alphabravo to bravothen no problempython c import bravo1i have been able to work around the issue but i would still like to understand it thanks,['python'] +241066,error when running phpunit i get the following error when i try to run phpunit from within my projects tests folderphp fatal error call to undefined method php codecoverage filtergetinstance in usrsharephpphpunitframeworkphp on line 46i installed phpunit via these commandssudo pear channelthiscover pearsymfonyprojectcomsudo pear channelthiscover componentseznosudo pear install alldeps phpunitphpunitas none of the other methods seem to work including aptgeti think codecoverage changed their singleton pattern at some point in time and hence removed getinstance but i do not know how to fix this error how can i either downgrade codecoverage or upgrade phpunit i tried manually installing the latest versions of everything via the following commandssudo aptget install gitmkdir phpunit cd phpunitgit clone gitgithubcomsebastianbergmannphpunitgitgit clone gitgithubcomsebastianbergmanndbunitgitgit clone gitgithubcomsebastianbergmannphpfileiteratorgitgit clone gitgithubcomsebastianbergmannphptexttemplategitgit clone gitgithubcomsebastianbergmannphpcodecoveragegitgit clone gitgithubcomsebastianbergmannphptokenstreamgitgit clone gitgithubcomsebastianbergmannphptimergitgit clone gitgithubcomsebastianbergmannphpunitmockobjectsgitgit clone gitgithubcomsebastianbergmannphpunitseleniumgitgit clone gitgithubcomsebastianbergmannphpunitstorygitgit clone gitgithubcomsebastianbergmannphpinvokergitsudo cp r dbunitphpunit usrsharephpsudo cp r phpcodecoveragephp usrsharephpsudo cp r phpfileiteratorfile usrsharephpsudo cp r phpinvokerphp usrsharephpsudo cp r phptexttemplatetext usrsharephpsudo cp r phptimerphp usrsharephpsudo cp r phptokenstreamphp usrsharephpsudo cp r phpunitphpunit usrsharephpsudo cp r phpunitmockobjectsphpunit usrsharephpsudo cp r phpunitseleniumphpunit usrsharephpsudo cp r phpunitstoryphpunit usrsharephpsudo cp r phpunitphpunitphp usrsharephpbut that did not help any now i just have a bunch of junk all over the place version infopear version 194php version 53613ubuntu33zend engine version 230phpunit 369 by sebastian bergmanninstalled packages channel pearphpunitdepackage version statefile iterator 131 stablephpunit 369 stablephpunit mockobject 1 stablephp codecoverage 1 stablephp invoker 110 stablephp timer 102 stablephp tokenstream 112 stabletext template 1 stable,['php'] +241072,recursion using yield is there any way to mix recursion and the yield statement for instance a infinite number generator using recursion would be something likedef infinitystart yield start recursion here it infinity1 nextit1 nextit2i trieddef infinitystart yield start infinitystart 1anddef infinitystart yield start yield infinitystart 1but none of them did what i want the first one stopped after it yielded start and the second one yielded start then the generator and then stoppednote please i know you can do this using a whileloopdef infinitystart while true yield start start 1i just want to know if this can be done recursively,['python'] +241080,test if a string contains any of the strings from an array how do i test a string to see if it contains any of the strings from an arrayinstead of using ifstringcontainsitem1stringcontainsitem2stringcontainsitem3,['java'] +241089,why does my irb prompt with ansi color codes mess up page updown behavior with copypaste i added to my irbrcirbconfpromptreverse mergerails env prompt icurrent app rails env prompt prompt ncurrent app rails env prompt prompt snil prompt c return sn irbconfprompt mode rails envif i do something likecurrent app e31mfoo bar appe0mrails env e32mrails enve0mthen the prompt shows up beautifully colorized but if i copy some text into my copybuffer and paste it if i do pageuppagedown to go to the beginningend of the current text entered my cursor like jumps to the middle of the text for pageup and for pagedown it jumps way out to the right into an area of blank spaces where nothing had been typed then my cursor position is totally screwed upis there a way i can correct this i would really like a colorized prompt,['ruby'] +241090,any idea why my c code cannot read from proc i have been able to write a program that can read any text files except the ones found in proc any file that i try to read from proc shows up emptybut whenever i typecat proccpuinfoon terminal i am presented with my cpu infoi can also see the file when i open it with a text editor such as gedit or leafpadso it seems that proc files are indeed text files but my c program is having a hard time reading theminclude stdiohinclude stdlibhinclude stringhinclude unistdhchar readfilestring char loc char filedat file pfile long lsize pfile fopen loc r grab the file size fseekpfile 0l seek end lsize ftell pfile fseekpfile 0l seek set filedat calloc lsize 1 sizeofchar fread filedat 1 lsize pfile return filedatint main void char cpuinfo cpuinfo readfilestring proccpuinfo printf sn cpuinfo return 0any idea why,['c'] +241164,is there an official list of supported countries for iad where can i find it or can anyone please update whats the countries that are currently has iad coverage,['iphone'] +241183,mocking member variables of a class using mockito i am a newbie to development and to unit tests in particular i guess my requirement is pretty simple but i am keen to know others thoughts on this suppose i have two classes like so public class first second second public first second new second public string dosecond return seconddosecond class second public string dosecond return do something let us say i am writing unit test to test firstdosecond method however suppose i want to mock seconddosecond class like so i am using mockito to do this public void testfirst second sec mocksecondclass whensecdosecondthenreturnstubbed second first first new first assertequalsstubbed second firstdosecondi am seeing that the mocking does not take effect and the assertion fails is there no way to mock the member variables of a class that i want to test,['java'] +241186,what does the prefix in nslog mean when i use nslog i get output similar to the following20120124 170532860 app2185671939 logging goes herei recognize that 20120124 170532860 is the date app is the app name but i have no clue what 2185671939 means can someone fill me in on what that is and where it is generated atall i am trying to do is get logging that lines up nicely so it is easy to read but the 2185671939 varies in digits enough to mess up any alignment attempts if i knew how the numbers in 2185671939 were generated i could add spaces as needed to make it line up correctly but that is my only idea at this pointany help would be much appreciated,"['objective-c', 'ios']" +241202,how to hide grid lines in jtable i am trying to hide the grid lines of a jtable but with no results even trying to change the color of the grid lines does not work here is my code build the tabletableview new jtablettmspecifify the selection listener and modellistselectionmodel tableviewgetselectionmodellistselectionmodeladdlistselectionlistenernew sharedlistselectionhandlertableviewtableviewsetselectionmodellistselectionmodeladd a mouse listener to our table and implement double click eventtableviewaddmouselistenernew mouseadapter public void mouseclickedmouseevent e if double click in a message show the message details window if egetclickcount 2 showmessagedetail set my own renderercustomcellrenderer mtr new customcellrenderertableviewsetdefaultrendererobjectclass mtr table propertiestableviewsetgridcolorcolorblacktableviewsetshowgridfalsetableviewsetshowverticallinesfalsetableviewsetshowhorizontallinesfalsetableviewsetselectionmodelistselectionmodelsingle selectionhide headertableviewsettableheadernull hide the id columnstring columname tableviewgetcolumnnametablemodelcolumn idtableviewgetcolumncolumnamesetmaxwidth0tableviewgetcolumncolumnamesetminwidth0tableviewgetcolumncolumnamesetwidth0load the messages in the tableloadmessagesadjust column widthtableview autoresizecolwidthtableview ttm public class customcellrenderer extends jpanel implements tablecellrenderer first gradient color private static final color color 1 new color255 255 255 200 second gradient color private static final color color 2 new color255 0 255 200 controls gradient direction private static final float side 50private gradientpaint gradientpaint new gradientpaint0 0 color 1 side side color 2 trueprivate jlabel label new jlabel public customcellrenderer setopaquetrue setlayoutnew borderlayout addlabel borderlayoutcenter labelsethorizontalalignmentswingconstantscenter public component gettablecellrenderercomponentjtable table object value boolean isselected boolean hasfocus int row int column labelsettextvaluetostring return this override protected void paintcomponentgraphics g superpaintcomponentg graphics2d g2 graphics2d g g2setpaintgradientpaint g2fillrect0 0 getwidth getheight white grid lines are always being drawn i am stuck heredo i have to implement a custom viewport to get rid of thisthanks in advancealex,['java'] +241209,how to list files inside a a file how can i get to know what files are part of my a file which command should i use,"['iphone', 'ios']" +241236,android crashing after camera intent i have an app published and one of the fundamental features is to allow the user to take a picture and then save that photo in a specific folder on their external storage everything seems to be working fine but i have gotten two reports now that claim that after taking a photo and clicking done to exit the camera and return back to the activity the app is forced closed bringing the user back to the home screen this happens on a samsung nexus s and the galaxy tab below i have posted my code to show i set up my intent and how i handle saving and thisplaying the photo in onactivityresult any guidance on what might be causing it to crash after they click done to exit the camera app would be greatly appreciated again this seems to be working fine on most devices but i was wondering if their is a more efficient universal approach i should be taking thank youhow i am firing the camera intent case action bar camera numbered image name filename image stringvalueofnumimages jpg output new filedirect fileseparator filename create output while outputexists while the file exists numimages increment number of images filename image stringvalueofnumimages jpg output new fileoutputfolder filename camera new intentandroidprovidermediastoreaction image capture urisavedimage urifromfileoutput get uri of the output cameraputextramediastoreextra output urisavedimage pass in uri to camera intent startactivityforresultcamera 1 break default return superonhandleactionbaritemclickitem position return truehow i am setting up onactivityresultoverrideprotected void onactivityresultint requestcode int resultcode intent data todo autogenerated method stub superonactivityresultrequestcode resultcode data if resultcode result ok if data was passed successfully bundle extras datagetextras bundle extras datagetbundleextramediastoreextra output ad new alertdialogbuilderthiscreate adseticonandroidrdrawableic menu camera adsettitlesave image adsetmessagesave this image to album adsetbuttonok this adshow bmp bitmap extrasgetdata set the bitmap to the bundle of data that was just received imagesetimagebitmapbmp set imageview to image that was captured imagesetscaletypescaletypefit xy,['android'] +241238,what is the difference between w and w i am looking at the documentation for ruby i am confused between using w or w later w is upcase what is the difference between both can you point me to some documentation,['ruby'] +241255,why does an anchor tags href values need http preprended to the url a hrefwstackoverflowcom target blankclick hereaclicking the above link on a sites html page would try to take the user to siteindexhtmlwstackoverflowcomwhere as following works finea href target blankclick hereawhat is the rationale for this behavior,['html'] +241308,scope of usefulness of interface in java interfaces consists of abstract methods and final variables well it is used as a generalized contract put forth so that classes implementing it should follow the rules by implementing methods in itis this the only usescope of interface in java have they introduced the concept of interface only for this or am i missing something please help me in understanding the use of interfaces with examples not on how to use or create interfaces but to show how they are helping programmersthank you,['java'] +241317,how to secure dll functions from being used outside of my application i want to restrict other application from using dll functions that i have writtenegif i hav databasedll containg two functionspublic void insertintodatabsepublic void cleardatabasenow if my application has called insertintodatabse and is doing some other worktill this time if some other application calls cleardatabase by referencing databasedll the databse would be cler outso how can i restrict calls to these functions form third party application,['c#'] +241335,install python fabric on windows how to get a working python fabric installation on windows,['python'] +241348,python regular expressions research vs refindall for school i am supposed to write a python re script that extracts ip addresses the regular expression i am using seems to work with research but not with refindallexp d133d13ip blah blah 1921680185 blah blahmatch researchexp ipprint matchgroupthe match for that is always 1921680185 but its different when i do refindallexp d133d13ip blah blah 1921680185 blah blahmatches refindallexp ipprint matches00i am wondering why refindall yields 0 when research yields 1921680185 since i am using the same expression for both functions and what can i do to make it so refindall will actually follow the expression correctly or am i making some kind of mistake,['python'] +241371,is there any rules engine implemented on nodejs in javascript i need a lightweight rules engine we have around 50 rules right now but the rules keep changing frequentlywe could use drools but i figure that would be overkill are there any lighter foss implementations i am aware of the other similar question but that is 2 years old and does not have a good answer and i do not have enough rep to comment on that question,['javascript'] +241373,the reason to use js call method i am interested whats the reason to have call method in js it seems it duplicates usual method of calling thisfor example i have a code with callvar obj objtype dogf functiondid what what alertthisobjtype did what whatfcallobj ate foodthe output is dog ate food but the same result i can get assigning the function to the objectvar obj objtype dogf functiondid what what alertthisobjtype did what whatobja fobjaate foodthe result is the same but this way is more understandable and convenient to use why call is needed,['javascript'] +241391,netbeans maven error javac invalid target release 17 i am trying to build an existing maven project on a fresh install of the latest netbeans but am getting the following error any help is much appreciatedfailed to execute goal orgapachemavenpluginsmavencompilerplugin232compile defaultcompile on project comroryngptest compilation failurefailure executing javac but could not parse the errorjavac invalid target release 17i think it has something to do with paths but am not sure exactly here is the contents of my usrlibjvm directorybash41 pwdusrlibjvmbash41 ls java javaopenjdk jre160openjdkx86 64java150gcj1500 jre jregcjjava160 jre150 jreopenjdkjava160openjdk1600x86 64 jre150gcjjava160openjdkx86 64 jre160,['java'] +241402,why main method in c is always placed inside the class but not in c why we put main method always inside the class in c while in c it always placed outside of the class,"['c#', 'c++']" +241409,is there a way to run gui application in a headless way in mac i am using following techniques to run gui application in linux and windowslinux xvfb 99 ac thisplay99 appthis would not work for 100 in mac os x even though xvfb is installed by default since most applications run in aqua environment and simply ignore thisplay variable settingwindows programmatic wayhdesk hdeskcreatedesktoptextvirtualnullnullnullgeneric allnullifhdesknull create process in this desktop closedesktophdeskmac os xhow do i do the same in mac os x either from command line or in a programmatic waythanks,"['java', 'c++']" +241420,problems getting left outer join to work i thought i understood how left outer joins work but i have a situation that is not working and i am not 100 sure if the way i have my query structured is incorrect or if it is a data issuefor background i have the following mysql table structuresmysql describe achievement field type null key default extra id varchar64 no pri null game id varchar10 no pri null name varchar64 no null description varchar255 no null image url varchar255 no null gamerscore smallint5 unsigned no 0 hidden tinyint1 no 0 base hidden tinyint1 no 0 8 rows in set 0 secandmysql describe gamer achievement field type null key default extra game id varchar10 no pri null achievement id varchar64 no pri null gamer id varchar36 no pri null earned epoch bigint20 unsigned no 0 offline tinyint1 no 0 5 rows in set 0 secas for the data this is what i have populated here only pertinent columns included for brevity id game id name 1 1480656849 cluster buster 2 1480656849 star gazer 3 1480656849 flower child 4 1480656849 oystermeister 5 1480656849 big cheese of the south seas 6 1480656849 hexic addict 7 1480656849 collapse master 8 1480656849 survivalist 9 1480656849 ticktock doc 10 1480656849 marathon mogul 11 1480656849 millionaire extraordinaire 12 1480656849 grand pearl poohbah 12 rows in set 0 secand achievement id game id earned epoch offline 1 1480656849 0 1 2 1480656849 0 1 3 1480656849 0 1 4 1480656849 1149789371 0 7 1480656849 1149800406 0 8 1480656849 0 1 9 1480656849 1149794790 0 10 1480656849 1149792417 0 8 rows in set 002 secin this particular case the achievement table is the master table and will contain the information that i always want to see the gamer achievement table only contains information for achievements that are actually earned for any particular game for any particular gamer there can be any number of rows in the gamer achievement table including none if no achievements have been earned for that game for example in the sample data above achievements with ids 5 6 11 and 12 have not been earnedwhat i currently have written isselect aid aname gaearned epoch gaofflinefrom achievement a left outer join gamer achievement ga on aid gaachievement id and agame id gagame idwhere gagamer id fba8fcaaf57b44c694314ab78605b024 and agame id 1480656849order by convert aid unsignedbut this is only returning the full information for those achievements that have actually been earned the unearned achievement information from the right side table gamer achievement is not being show with the null values as i would expect from this type of query this is what i am expecting to see id name earned epoch offline 1 cluster buster 0 1 2 star gazer 0 1 3 flower child 0 1 4 oystermeister 1149789371 0 5 big cheese of the south seas null null 6 hexic addict null null 7 collapse master 1149800406 0 8 survivalist 0 1 9 ticktock doc 1149794790 0 10 marathon mogul 1149792417 0 11 millionaire extraordinaire null null 12 grand pearl poohbah null null 12 rows in set 0 secwhat am i missing here from what i understand the basic query looks right to me but i am obviously missing some piece of critical information,"['mysql', 'sql']" +241427,possible to pass self anyfunction in blocks without weak object ios 5 arc is it possible to pass self anyfunction in blocks without a weak object from selfas an example this is valid code from the system frameworkuiview animatewithduration08 animations do animationstuff completionbool finished self anyfunction you can pass self anyfunction in the completion block without a warning but if you write your own method with a completion block the following warning occurs capturing self strongly in this block is likely to lead to a retain cyclea working solution is quite simple ios 5 arc before the block declare weak myclass weakself selfand in the completion block you have to callweakself anyfunctionbut back to my question why there is no need in the system framework apis to use a weak object and to use self without any warnings and how to implement a method without the need of a weak object in the blockthank you for your effort,"['iphone', 'objective-c', 'ios']" +241440,gcc compiler error when extracting a char from a temporary stream i am trying to read a single character from a stream with the following code i get a ambiguous overload compiler error gcc 432 and 434 what i am doing wronginclude iostreaminclude sstreamint main char c stdistringstreama c return 0remarksvisual studio 2008 compiles without errorsother types int double are workingif i first create a variable stdistringstream issa iss c the compiler gives no error,['c++'] +241450,what is the difference between new doublesomestring and doubleparsedoublesomestring as far as i can tell new doublesomestring and doubleparsedoublesomestring give me the exact same result is there any reason i would want to use one over the other,['java'] +241469,android i18n with parameters i know there is support in android for 18n an application but can i give parameters to such a string in rails i can do something like thisen hello hello name youve got count messagesthello name klaus count 5is there something similar in android or do i have to do it myself,['android'] +241471,issue in playing m3u8 file in android 32 i am trying to play apple test stream video m3u8 in android this is the link indexm3u8but i am not able to play it in android 32this is the code i have used to play the videovoid playvideostring url string linkurl logeurllink mediacontroller mc new mediacontrollerthis mcsetmediaplayervideoview videoviewsetmediacontrollermc videoviewsetvideouriuriparse indexm3u8 videoviewrequestfocus videoviewstart please suggest me the way to play m3u8 file in different android versions,['android'] +241495,input elements on android 4x can not be styled when focused updatethere is a fixwebkitusermodify readwriteplaintextonlyoriginal questioni am trying to boil this down to a simple examplei have a simple input element like thisinput classmyclass typetextthe style looking likemyclass myclassfocus backgroundcolor blackthis works fine on android 2x and 3x except some devices that are known not to respect css on focused input elementssince i updated a nexus s to 403 i cant get the input field to accept any stylessome testing revealed the followingthe styles are actually applied but for some reasons the browser renders a white rectangle over the input rendering styles useless using weinre i was able to move the real input element so that i was able to thisplay bothany suggestion on this are very much welcome,"['android', 'css']" +241513,is there any workaround to rethrow an exception and preserve the stacktrace in javascript i know that chrome has a known bug not preserving the stacktrace when rethrowing an exception in javascripti have the following code running in chrometry try runcodethatmaythrowanexception catch e i am handing the exception here thisplaying a nice message or whatever now i want to rethrow the exception throw e catch e the stacktrace was lost here is there any way to keep the stacktrace a jquery plugin maybe any workaround or ideas,['javascript'] +241525,how to combine collection and property assertions using fluentassertions i would like to combine fluent assertions collection assertions and property assertions eg assert that two ienumerables are pairwiseequal using propertybyproperty possibly nested comparison ie structural equality in functional language parlanceconcrete examplevar dic new dictionaryint string 1 hi 2 bye var actual dictoselectlistitems0orderbysi sitextvar expected new listselectlistitem new selectlistitem selected false textbye value2 new selectlistitem selected false texthi value1here i wrote an extension method toselectlistitems that converts a dictionary to an ienumerable of selectlistitems from aspnet mvc i want to assert that actual and expected are structurally equal noting that the reference type selectlistitem does not override equals and thus uses reference equality by defaultupdatecurrently using the following handrolled solution still hoping for something better built into fluentassertionspublic static void shouldbestructurallyequaltot uthis ienumerablet actual ienumerableu expected actualshouldhavecountexpectedcount actualzipexpectedforeachpair pairitem1shouldhaveallpropertiesincludingnestedobjectsequaltopairitem2note zip here is my own ienumerable extention which uses tuplecreate as the default projectionupdate 2here are two minimal examplespublic class foobar public string foo get set public int bar get set public class testclass test public void minimalexample listfoobar enumerable1 new listfoobar new foobar foo x bar 1 new foobar foo y bar 2 listfoobar enumerable2 new listfoobar new foobar foo x bar 1 new foobar foo y bar 2 enumerable1shouldhavesharedpropertiesincludingnestedobjectsequaltoenumerable2 test testclassminimalexample failed systemreflectiontargetparametercountexception parameter count mismatch at systemreflectionruntimemethodinfoinvokeobject obj bindingflags invokeattr binder binder object parameters cultureinfo culture boolean skipvisibilitychecks at systemreflectionruntimemethodinfoinvokeobject obj bindingflags invokeattr binder binder object parameters cultureinfo culture at systemreflectionruntimepropertyinfogetvalueobject obj bindingflags invokeattr binder binder object index cultureinfo culture at systemreflectionruntimepropertyinfogetvalueobject obj object index at fluentassertionsassertionspropertyequalityvalidatorassertselectedpropertiesareequalobject subject object expected at fluentassertionsassertionspropertyequalityvalidatorvalidateuniqueobjecttracker tracker string parentpropertyname at fluentassertionsassertionspropertyequalityvalidatorvalidate at fluentassertionsassertionspropertyassertions1equaltoobject otherobject string reason object reasonargs at fluentassertionsassertionspropertyassertions1equaltoobject otherobject miscassertionscs320 at testclassminimalexample test public void minimalexample2 ienumerablefoobar enumerable1 new listfoobar new foobar foo x bar 1 new foobar foo y bar 2 castfoobar foobar enumerable2 new new foobar foo x bar 1 new foobar foo y bar 2 enumerable1shouldhavesharedpropertiesincludingnestedobjectsequaltoenumerable2 test testclassminimalexample2 failed systeminvalidoperationexception please specify some properties to include in the comparison at fluentassertionsassertionspropertyequalityvalidatorvalidateuniqueobjecttracker tracker string parentpropertyname at fluentassertionsassertionspropertyequalityvalidatorvalidate at fluentassertionsassertionspropertyassertions1equaltoobject otherobject string reason object reasonargs at fluentassertionsassertionspropertyassertions1equaltoobject otherobject miscassertionscs520 at testclassminimalexample2,['c#'] +241544,onlocationchanged callback is never called i am trying to get the users current location using the locationmanager i have done a lot of research and cannot seem to find anyone with the same problem the onlocationchanged callback never seems to be called below is my various code and the logcatprotected locationlistener locationlistenerprotected locationmanager locationmanagerprotected context contextmy oncreate methodoverridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate logvtag in on create thiscontext getactivity registerlocationupdatesmy registerlocationupdates methodvoid registerlocationupdates criteria criteria new criteria criteriasetaccuracycriteriaaccuracy low criteriasetpowerrequirementcriteriapower low criteriasetaltituderequiredfalse criteriasetbearingrequiredfalse locationmanager locationmanagergetactivitygetsystemservicelocation service provider locationmanagergetbestprovidercriteria true cant get a hold of provider if provider null logvtag provider is null shownoprovider return else logvtag provider provider locationlistener new mylocationlistener locationmanagerrequestlocationupdatesprovider 1l 1f locationlistener connect to the gps location service location oldlocation locationmanagergetlastknownlocationprovider if oldlocation null logvtag got old location latitude doubletostringoldlocationgetlatitude longitude doubletostringoldlocationgetlongitude waitingforlocationupdate false getnearbystores else logvtag no last location found my locationlistenerprivate class mylocationlistener implements locationlistener public void onlocationchangedlocation location latitude doubletostringlocationgetlatitude longitude doubletostringlocationgetlongitude logvtag in on location change if waitingforlocationupdate getnearbystores waitingforlocationupdate false locationmanagerremoveupdatesthis public void onstatuschangedstring s int i bundle bundle logvtag status changed s public void onproviderenabledstring s logetag provider thisabled s public void onproviderthisabledstring s logetag provider thisabled s my permissions in the androidmanifestusespermission androidnameandroidpermissioninternet usespermission androidnameandroidpermissionaccess network state usespermission androidnameandroidpermissionaccess fine location and finally the logcat after i run my app0125 094310963 verbosenearbylistfragment3060 in on create0125 094310963 verboselocationmanagerservice1329 getproviders0125 094310963 verboselocationmanagerservice1329 getproviders0125 094310973 verboselocationmanagerservice1329 getproviders0125 094310983 verbosenearbylistfragment3060 provider gps0125 094310983 debuglocationmanager3060 requestlocationupdates provider gps listener cofusionwebdealsplusappnearbyitemsnearbylistfragmentmylocationlistener46ef46800125 094310983 debuggpslocationprovider1329 setmintime 10125 094310983 verbosenearbylistfragment3060 no last location found0125 094310983 verboselocationmanagerservice1329 requestlocationupdates listener receiver47421e68 listener androidosbinderproxy47421a680125 094311003 verbosecountingfragment3060 in on create view0125 094311003 warngpslocationprovider1329 duplicate add listener for cofusionwebdealsplus0125 094311013 verbosescrolistener3060 in constructor0125 094311013 verbosescrolistener3060 scrolling0125 094311033 debuggpslocationprovider1329 startnavigating0125 094311043 debuglib locapi1329 loc eng set qos time outstandalone 60 agps 890125 094311043 debuglib locapi1329 loc eng set qos accuracyaccuracy 500125 094311043 verboselib locapi1329 persistradioagpsmode 0125 094311043 debuglib locapi1329 loc eng set position mode client 1 interval 1 mode 10125 094311043 verboselib locapi1329 loc eng ioctl called client 1 ioctl type 20125 094311043 verboselocapi rpc glue1329 loc ioctl0125 094311043 debugrpc1329 written rpc packet size 960125 094311043 debugrpc1329 read rpc packet0125 094311043 debugrpc1329 read rpc packet size 280125 094311043 verboselocapi rpc glue1329 loc api sync ioctl select id 0 loc ioctl returned 00125 094311043 debugrpc1329 read rpc packet0125 094311043 debugrpc1329 read rpc packet size 800125 094311043 verboselocapi rpc glue1329 callback received 80 cb id0x5310 handle10125 094311043 debugrpc1329 written rpc packet size 280125 094311043 verboselib locapi1329 loc eng ioctl result client 1 ioctl type 2 success0125 094311043 debuglib locapi1329 loc eng start0125 094311043 debuglocapi rpc glue1329 loc start fix0125 094311043 debugrpc1329 written rpc packet size 440125 094311043 debugrpc1329 read rpc packet0125 094311053 debugrpc1329 read rpc packet size 280125 0943103 debugrpc1329 read rpc packet0125 0943103 debugrpc1329 read rpc packet size 800125 094313 verboselocapi rpc glue1329 callback received 100 cb id0x5310 handle10125 094313 verboselib locapi1329 process deferred action pthread cond wait returned0125 094313 debuglib locapi1329 loc eng report status gps status session begin0125 094313 debuglib locapi1329 loc eng report status update status0125 094313 verbosegpslocationprovider1329 reportstatus status 10125 094313 debuggpslocationprovider1329 acquiring wakelock0125 0943123 debugrpc1329 written rpc packet size 280125 0943183 debugpowermanagerservice1329 new lightsensor value40 lcdvalue770125 094311273 debugrpc1329 read rpc packet0125 094311273 debugrpc1329 read rpc packet size 800125 094311273 verboselocapi rpc glue1329 callback received 100 cb id0x5310 handle10125 094311273 verboselib locapi1329 process deferred action pthread cond wait returned0125 094311273 debuglib locapi1329 loc eng report status gps status engine on0125 094311273 debuglib locapi1329 loc eng report status update status0125 094311273 verbosegpslocationprovider1329 reportstatus status 3and the android sdk location parts of the logcat keep repeating them selves i have tried everything that i can think of and have seen on google and stackoverflow als just as a side note i have been able to get it to work on a 23 device using the requestsingleupdate which is available in api 9 and by following the guide a deep dive into location but i need it to work on 21 or 22 and higher using the old sdk so if you have any hints or would like to know more please let me know thanks in advance,['android'] +241551,crmsvcutil is only creating organizationservicecontext derivants should be crmorganizationservicecontext i am using crmsvutil this waycrmsvcutilexe urlhttpcrm2011mytestorgxrmservices2011organizationsvc outgeneratedcodecs namespacexrm servicecontextnamexrmdatacontextand the output contains thousands of business objects and this context clasystemcodedomcompilergeneratedcodeattributecrmsvcutil 5096881533public partial class xrmdatacontext microsoftxrmsdkclientorganizationservicecontextbut looking at the samples namely sdkwalkthroughsportalconsoleappwalkthrough i clearly can see there that the context class should be derived from a more mighty sub class of organizationservicecontext crmorganizationservicecontextsystemcodedomcompilergeneratedcodeattributecrmsvcutil 509688583public partial class xrmservicecontext microsoftxrmclientcrmorganizationservicecontexti definitely need crmorganizationservicecontext because only then i have the constructors i need so what i am doing wrong or which setting did i miss,"['c#', '.net']" +241559,how to do like on dictionary key how can i do a like to find a dictionary key i am currently doingmydictcontainskeykeynamebut some keynames have an additional word appended separated by a space i would like to do a like or startswith the comparisons will look like thiskey1 key1 matchkey1 key1 someword partial matchi need to match in both cases,"['c#', '.net']" +241561,shifting a java bitset i am using a javautilbitset to store a dense vector of bitsi want to implement an operation that shifts the bits right by 1 analogous to on intsis there a library function that shifts bitsetsif not is there a better way than the belowpublic static void logicalrightshiftbitset bs for int i 0 i bsnextsetbiti 0 i is the first bit in a run of set bits set any bit to the left of the run if i 0 bsseti 1 now i is the index of the bit after the end of the run i bsnextclearbiti nextclearbit never returns 1 clear the last bit of the run bscleari 1 010 a b i starts off the loop at a and ends the loop at b the mutations change the run to 010,['java'] +241564,how to speed adding items to a listview i am adding a few thousand eg 53709 items to a winforms listviewattempt 1 13870 msforeach object o in list listviewitem item new listviewitem refreshlistviewitemitem o listviewitemsadditemthis runs very badly the obvious first fix is to call beginupdateendupdateattempt 2 3106 mslistviewbeginupdateforeach object o in list listviewitem item new listviewitem refreshlistviewitemitem o listviewitemsadditemlistviewendupdatethis is better but still an order of magnitude too slow let us separate creation of listviewitems from adding listviewitems so we find the actual culpritattempt 3 2631 msvar items new listlistviewitemforeach object o in list listviewitem item new listviewitem refreshlistviewitemitem o itemsadditemstopwatchstartlistviewbeginupdate foreach listviewitem item in items listviewitemsadditemlistviewendupdatestopwatchstopthe real bottleneck is adding the items let us try converting it to addrange rather than a foreachattempt 4 2182 mslistviewbeginupdatelistviewitemsaddrangeitemstoarraylistviewendupdatea bit better let us be sure that the bottleneck is not in the toarrayattempt 5 2132 mslistviewitem arr itemstoarraystopwatchstartlistviewbeginupdatelistviewitemsaddrangearrlistviewendupdatestopwatchstopthe limitation seems to be adding items to the listview maybe the other overload of addrange where we add a listviewlistviewitemcollection rather than an arrayattempt 6 2141 mslistviewbeginupdatelistviewlistviewitemcollection lvic new listviewlistviewitemcollectionlistviewlvicaddrangearrlistviewendupdatewell that is no betternow it is time to stretchstep 1 make sure no column is set to autowidthcheckstep 2 make sure the listview is not trying to sort the items each time i add onecheckstep 3 ask stackoverflowchecknote obviously this listview is not in virtual mode since you do notcannot add items to a virtual list view you set the virtuallistsize fortunately my question is not about a list view in virtual modeis there anything i am missing that might account for adding items to the listview being so slowbonus chatteri know the windows listview class can do better because i can write code that does it in 394 mslistview1itemsbeginupdatefor i 1 to 53709 do listview1itemsaddlistview1itemsendupdatewhich when compared to the equivalent c code 1349 mslistviewbeginupdatefor int i 1 i 53709 i listviewitemsaddnew listviewitemlistviewendupdateis an order of magnitude fasterwhat property of the winforms listview wrapper am i missing,['c#'] +241568,python 2d contour plot from 3 lists x y and rho i have a simple problem in python and matplotlibi have 3 lists x y and rho with rhoi a density at the point xi yiall values of x and y are between 1 and 1 but they are not in a specific orderhow to make a contour plot like with imshow of the density rho interpolated at the points x ythank you very muchedit i work with large arrays x y and rho have between 10 and 10 elements,['python'] +241585,media player called in state 0 error 380 i am currently trying to design a simple app that streams an internet radio station i have the url for the station and am setting up the media player like mediaplayer mediaplayer new mediaplayer try mediaplayersetdatasourceurl catch illegalargumentexception e eprintstacktrace catch securityexception e eprintstacktrace catch illegalstateexception e eprintstacktrace catch ioexception e eprintstacktrace try mediaplayerprepare catch illegalstateexception e eprintstacktrace catch ioexception e eprintstacktrace mediaplayerstartthe program is not crashing when emulated but nothing is playing and i am get the following errorstart called in state 0and right below it iserror 380does anyone know what this means i have read a little about these state errors but could not find anything that applies to my project,['android'] +241613,why did underscorejs remove support for amd 130 a jan 11 2012 removed amd requirejs support from underscore if youd like to use underscore with requirejs you can load it as a normal script wrap or patch your copy or download a forked versionwhy have they done it does anyone know because they added it only few month ago in october and amd asynchronous module definition is said to be far superior to commonjs modulesupdate as of december 2013 this has been supported again,['javascript'] +241619,inject spring beans into resteasy is it possible to inject spring beans into an resteasy path class i managed to do it with jersey with injectparam annotation but for some other reasons i need to switch to resteasy and i cannot seem to find a way to do it tried good ol javaxinjectinject but nothingeditthis solution worksbut it is not injection i would still prefer something a little more elegant,['java'] +241623,implementing gethashcode correctly i would like to hear from the community on how i should go about implementing gethashcode or override it for my object i understand i need to do so if i override the equals method i have implemented it a fair amount of times sometimes just calling the base method i understand that my object should equal another instance of the object if it contains the same details members what is the best way to get a hash code from the clas members,"['c#', '.net']" +241626,hresult e fail in unsafenativemethodsiwebbrowser2navigate2 we developed a complex application in net 35 inside office 2007 in some forms we use the webbrowser control to navigate to our html pages the problem is that on some machines when the control invoke the navigate method it raises an exception error hresult e fail has been returned from a call to a com componentfrom the stack trace we note that the exception come from the webbrowser control when invoking the navigate method in systemwindowsformsunsafenativemethodsiwebbrowser2navigate2object url object flags object targetframename object postdataobject headers in systemwindowsformswebbrowserperformnavigate2object url objectflags object targetframename object postdata object headers in systemwindowsformswebbrowserperformnavigatehelperstringurlstring boolean newwindow string targetframename byte postdatastring headers in systemwindowsformswebbrowserset urluri value in systemwindowsformswebbrowserset documentstreamstream value in systemwindowsformswebbrowserset documenttextstring valuepcs are vista with ie8 and office 2007 service pack 2 we use visual studio 2010 and vsto 30thanks a lot,['c#'] +241639,can we force xmlwriter to issue rather than by default somexmlwriterwriteelementstringmytag somestringproduces mytag i looked around xmlwritersettings class for possible options that would force the writer to produce mytagmytag instead but did not find anythingis there a simple way of forcing the xmlwriter to issuing empty elements with open tag close tag rather than with the shorthand formedityes i realize that with regards to xml validity the two notations are equivalent valid and all i am however working with legacy code which parses such xml using read ie at node level and fumbles things up by reading when on an empty nodehence my question comes in the context of limiting the amount of changes to this legacy code the question is indeed overlapping with this so question as suggested none of the options offered there are however easily applicable to my situation,['.net'] +241650,mvc3 net session randomly losing session value and is return as null i have a production issue with inproc session stateour application is base on mvc 3 net framework and is integrated into our site running sitecore cmsour users have been experiencing object reference not set to an instance of an object randomly through out the application flowafter extensive logging and tracing we could conclude this was caused when the session object returns nullheres to some details about what we found and what we knowsession id is being persistent for the same user and passed allthe way into the application correctly i do not believe this is a code issue because this only happen on production at random interval never happen on local dev or staging environmentthere is two production server running through a load balanceris not a server persistent issue as we tested by sleeping one of the server and having all traffic route to one server also through logging we could identify that user are hitting the same server but the session have became nullthis does not seem to be a client issue as well because they are able to go through the application successfully even if they have encountered an error beforethis does not seem to be a traffic load or server load issue because it happen through out the day at random times and happens to random users duringthis does not seem to be caused by recycling the app poolthis does not seem to be caused by session timeout as we have set the timeout to be two hour and while we track the log users could experience this 510min into the flowside note we must use inproc session state due to our sitecore cms so changing the design is not an optioni have a theory it might have something to do with session locking or being corrupted from concurrent access attemptsa few place we see the occurrence of this problem a lot from our application is when the users is being redirected by a javascript windowslocationand in areas where async ajax calls are being madewe been scratching our heads on this for a while i am wondering if anyone out there would have any insight or theory to what might the problem bethanks added notemystere h27studio so i have also thiscovered something relating to sessionid or session reset issues in some case we thiscover that on a page redirect it is triggering two duplicate gets calls to the method with the first call missing a sessionid and randomly get redirected to one of the server this is because the server persistent session from the load balancer is base on client ip sessionid and other header information to create unique session to keep a client on one server this happen every time during the flow when our redirect page is using a windowlocation this will cause the object reference not set issue for the client if the bad no sessionid call hit the same server this probably because the first bad call with no sessionid is causing the application to create a new session which overrides the original sessions object so even on the second call where the correct sessionid is pass into the application we will thiscover that session object contain nullso i believe there is an issue with the duplicate call that is clearing out the session object which not sure why or what is causing that to begin withanyone have clue regarding this thanksupdatewe are planning to take these steps in hope to resolve this issuewe have issues in areas where async ajax calls were made so we are planning to remove the async feature and let it the ajax run in syncwe have issues where a windowslocation javascript redirect is happening we have created an alternative method using postback in hope of fixing the issue in this areaother areas which are not related to one of the above issue are still up in the aireffect of change will be posted once we deploy it to productionthanks for all the comments,['.net'] +241673,hang andor segfault when using boostthreads from matlab not when called directly what the problem was in case people have a similar problem after some thiscussions with mathworks support it turned out to be a conflict between the system boost and matlabs shipped boost libraries when i compiled with system boost headers and linked with older matlab boost libraries it segfaulted when i compiled and dynamically linked with system boost but then it dynamically loaded the matlab boost libraries it hung foreverstatic linking to system boost works as does downloading the correct headers for the version of boost that matlab ships with and compiling with those of course the mac builds of matlab do not have version numbers in their filenames though the linux and supposedly windows builds do r2011b uses boost 144 for referencei have some multithreaded code that works fine when it is compiled directly but segfaults andor deadlocks when it is called from a matlab mex interface i do not know whether the different environment is revealing a flaw in my code or what but i cannot figure it outi am running this on three machine configurations though there are several of the centos boxesosx 107 g 42 boost 148 matlab r2011a clang 21 also works for standalone have not tried to get mex to use clangancient centos g 412 boost 1331 debug and not debug matlab r2010bancient centos g 412 boost 140 no debug versions installed matlab r2010bheres a pareddown version with this behaviorinclude queueinclude vectorinclude boostthreadhppinclude boostutilityhppifndef no mexinclude mexhendifclass worker boostnoncopyable boostmutex jobs mutex stdqueuesize t jobs boostmutex results mutex stdvectordouble results public workerboostmutex jobs mutex stdqueuesize t jobs boostmutex results mutex stdvectordouble results jobs mutexjobs mutex jobsjobs results mutexresults mutex resultsresults void operator size t i float r while true get a job boostmutexscoped lock lkjobs mutex if jobssize 0 return i jobsfront jobspop do some work r rand 315612 write the results boostmutexscoped lock lkresults mutex resultsi r stdvectordouble doworksize t n stdvectordouble results resultsresizen boostmutex jobs mutex results mutex stdqueuesize t jobs for size t i 0 i n i jobspushi worker w1jobs mutex jobs results mutex results boostthread t1boostrefw1 worker w2jobs mutex jobs results mutex results boostthread t2boostrefw2 t1join t2join return resultsifdef no mexint main elsevoid mexfunctionint nlhs mxarray plhs int nrhs const mxarray prhs endif stdvectordouble results dowork10 for size t i 0 i resultssize i printfg resultsi printfnnote that on boost 148 i get the same behavior if i change the functor into a standard function and just pass boostrefs to the mutexesdata as extra arguments to boostthread boost 1331 does not support this thoughwhen i compile it directly it always runs fine i have never seen it fail in any situation g o testing testingcpp lboost threadmt dno mex testing532521 895008 514128e06 312074e06 362505e06 148984e06 320100 461912e06 462206e06 635983e06running from matlab i have seen a lot of different behaviors after making different tweaks to the code and so on though no changes that actually make any sense to me but heres what i have seen with the exact code aboveon osx boost 148if it is linked to a releasevariant boost i get a segfault trying to access a near0 address inside of boostthreadstart thread being called from t1s constructorif it is linked to a debugvariant boost it hangs forever in the first boostthreadjoin i am not entirely certain but i think the worker threads have actually completed at this point do not see anything in info threads that is obviously themon centos boost 1331 and 140with release boost i get a segfault in pthread mutex lock being called from the boostthreadjoin on t1with debugging boost it hangs forever in l lock wait inside pthread mutex lock in the same place as shown below the worker threads have completed at this pointi do not know how to do anything more with the segfaults since they never occur when i have debugging symbols that can actually tell me what the null pointer isin the hangingforever case i seem to always get something like this if i am stepping through in gdb99 worker w1jobs mutex jobs results mutex resultsgdb 100 boostthread t1boostrefw1gdb new thread 0x47814940 lwp 19390102 worker w2jobs mutex jobs results mutex resultsgdb 103 boostthread t2boostrefw2gdb thread 0x47814940 lwp 19390 exitednew thread 0x48215940 lwp 19391thread 0x48215940 lwp 19391 exited105 t1jointhat sure looks like both threads are complete before the call to t1join so i tried adding a sleep1 call in the doing work section between the locks when i am stepping through the threads exit after the call to t1join and it still hangs forever106 t1joingdbthread 0x47814940 lwp 20255 exitedthread 0x48215940 lwp 20256 exited still hangingif i up out to the dowork function results is populated with the same results that the standalone version prints on this machine so it looks like all that is going throughi have no idea whats causing either of the segfaults or the crazy hangingness or why it is that it always works outside matlab and never inside or why it is different withwithout debugging symbols and i have no idea how to proceed in figuring this out any thoughtsat alanxzs suggestion i have run the standalone version of the code under valgrinds memcheck helgrind and drd toolson centos using valgrind 35 none of the tools give any nonsuppressed errorson osx using valgrind 37memcheck does not give any nonsuppressed errorshelgrind crashes for me when run on any binary including eg valgrind toolhelgrind ls on osx complaining about an unsupported instructiondrd gives over a hundred errorsthe drd errors are pretty inscrutable to me and though i have read the manual and so on i cannot make any sense of them heres the first one on a version of the code where i commented out the second workerthreadthread 2conflicting load by thread 2 at 0x04b518 size 8 at 0x3b837 void boostcall oncevoid boostonce flag void in usrlocalboostboost 1 48 0stageliblibboost threadmtddylib by 0x2bcd4 boostdetailset current thread databoostdetailthread data base in usrlocalboostboost 1 48 0stageliblibboost threadmtddylib by 0x2ba62 thread proxy in usrlocalboostboost 1 48 0stageliblibboost threadmtddylib by 0x2d88be pthread start in usrlibsystemlibsystem cdylib by 0x2dbb74 thread start in usrlibsystemlibsystem cdyliballocation context data section of rlocalboostboost 1 48 0stageliblibboost threadmtddylibother segment start thread 1 at 0x41b4de bsdthread create in usrlibsystemlibsystem kerneldylib by 0x2b959 boostthreadstart thread in usrlocalboostboost 1 48 0stageliblibboost threadmtddylib by 0x101b54 boostthreadthreadboostreference wrapperworker boostreference wrapperworker boostthisable ifboostis convertibleboostreference wrapperworker boostdetailthread move tboostreference wrapperworker boostthreaddummytype threadhpp204 by 0x101434 boostthreadthreadboostreference wrapperworker boostreference wrapperworker boostthisable ifboostis convertibleboostreference wrapperworker boostdetailthread move tboostreference wrapperworker boostthreaddummytype threadhpp201 by 0x10b50 doworkunsigned long testingcpp66 by 0x10ce1 main testingcpp82other segment end thread 1 at 0x41bbca psynch cvwait in usrlibsystemlibsystem kerneldylib by 0x3c0c3 boostcondition variablewaitboostunique lockboostmutex in usrlocalboostboost 1 48 0stageliblibboost threadmtddylib by 0x2d28a boostthreadjoin in usrlocalboostboost 1 48 0stageliblibboost threadmtddylib by 0x10b61 doworkunsigned long testingcpp72 by 0x10ce1 main testingcpp82line 66 is the construction of the thread and 72 is the join call there is nothing but comments in between as far as i can tell this is saying that there is a race between that part of the master thread and the worker threads initializationbut i do not really understand how that is possiblethe rest of the output from drd is here i am not getting anything out of it,['c++'] +241699,understanding view controller nesting in ios ive been tearing my hair out over the last couple of days trying to understand this one seemingly basic concept of ios developmentif i want to have two or more view controllers thisplayed and usable in the same screenful is thisnot advisable as per apples one vc per screenful of contentcompletely possible by adding the vcs via codejust not done instead use one vc and simply add code that mimics the functionality of the view controllers you wantlet me rephrase a bitif i wanted to have in an ipad app a uiview a that takes up a large portion of the left side of the screen and a second uiview b that takes up the rest of the right side of the screen and i wanted to add a button to uiview b that when clicked would use the modal transition to slide up a uitableview to replace uiview b and this uitableview would then act like a typical uitableviewcontroller whereby when the user picks an item from the table the typical events are sent to the tableview controller to push in a new set of items is this possibleit just seems to me that if im already able to easily create two separate uiviewcontrollers and have a button in one vc modally bring up the second vc why cant i combine this functionality so that one vc has two children vcs and those children vcs handle their own modal transitionsor is the best practice in a case like this to simply have one vc that handles everything and then manually handle animating the slides in out of various views after various clicks on various ui elementsas you can tell i think ive read too many different conflicting responses to questions similar to this that ive gotten entirely confused about whats what anymore if anyone out there understands what im getting at and can lend a helping explanation or some pointers id greatly appreciate it,['ios'] +241715,magnifier effect for d3graphgl force directed network visualization is it possible to create a smooth animated magnifying effect similar to the dock on mac os x when hovering over nodes in a forcedirected graph visualization using the d3 or graphgl libraries the nodes would need to expand and thisplace the others around it while maintaining the forcedirected layoutif someone could fork this to demonstrate that would be great thanksnote this is different from a simple zoom as in this question,"['javascript', 'jquery']" +241809,core data sync tracking deleted objects i am setting up a basic sync service for an ipad application i am developing the goal is to have data consistent throughout several instances of the ipad app as well as having a readonly version of the data on the web hence rolling a custom solutionthe current flow is thiseach entity has a created modified and uuid field which are automatically updated by core dataon sync each entity with a created or modified date after the last sync date is serialised into json and sent to the serverthe server persists any changes to a mysql database using the clientgenerated uuids as pks if there is a conflict it just uses the most recently modified entity as the true version nothing fancy there and sends back any updated entities to the clientthe client then merges these changes back into its core data dbthis all seems to be working fine my problem is how to track deleted objects using this method i am guessing i can add a deleted flag to each entity and set this whenever a client deletes something i can then push that change to the server with the rest of the sync data once the sync is complete then the client can actually delete these entities my questions arecan i override core datas delete methods to automatically set this flagwill this require keeping all deleted entities indefinitely on the server well have no way of knowing when every client has synced and actually deleted each entity i am not currently tracking client instancesis there a better way of doing this,"['iphone', 'mysql', 'ios']" +241836,android how to avoid multiple deployment of the same jar my problem is as follows i need to develop several android apps deployed as different apks each application needs a set of thirdparty jars i would like to deploy these files just onceall the approaches i have found up to now require that if i develop 5 different applications each in an thistinct apk the ten shared 3rd party jars are deployed 5 timesthis most certainly is no good to me how can this be avoidedthanks regardsvincenzo,['android'] +241840,how to keep floating div inside frame of parent div i have a div containing several other divs with setting floatleft now i want a frame around all of them so i put a border on the parent div but the floating ones flow out of the framecssrendering paddingleft10pt borderwidth 1px borderstyle solidcolumn floatleft paddingleft10pthtmldiv classrendering div classcolumn img classimageplugin srcsomeimage div div classcolumn span classphone9span span classnameassangespan divdivwhat can i do in css to keep them inside the parent frame,"['html', 'css']" +241841,efficient template population say i have a text template with a number of fields that need to be populatedvar template hello name you are age years old you live in locationand an idictionarystringstring of values to substitutekey valuename spenderage 38location ukthe naive way of populating the template might be something likevar output templateforeachvar kvp in templvalues output outputreplacestringformat0 kvpkey kvpvaluehowever this seems painfully inefficient is there a better way,['c#'] +241846,remove rows from data overlapping time intervals edit i am looking for solution for this question now also with other programming languagesbased on the other question i asked i have a dataset like this for r users dput for this below which represents user computer sessions username machine start end1 user1 d5599domaincom 20110103 094418 20110103 0947272 user1 d5599domaincom 20110103 094629 20110103 1009163 user1 d5599domaincom 20110103 140736 20110103 1456174 user1 d5599domaincom 20110105 150317 20110105 1523155 user1 d5599domaincom 20110214 1439 20110214 1440166 user1 d5599domaincom 20110223 135430 20110223 1358237 user1 d5599domaincom 20110321 101018 20110321 10328 user1 d5645domaincom 20110609 101241 20110609 1058599 user1 d5682domaincom 20110103 120345 20110103 12294310 user2 d5682domaincom 20110112 142605 20110112 14325311 user2 d5682domaincom 20110117 150619 20110117 15442212 user2 d5682domaincom 20110118 150730 20110118 15424313 user2 d5682domaincom 20110125 152055 20110125 15243814 user2 d5682domaincom 20110214 150300 20110214 15074315 user2 d5682domaincom 20110214 145923 20110214 151447there may be several concurrent overlapping based on time sessions for the same username from the the same computer how can i remove those rows so that only one sessionsis left for this data original data set has approx 500 0 rowsthe expected output is rows 2 15 removed username machine start end1 user1 d5599domaincom 20110103 094418 20110103 0947273 user1 d5599domaincom 20110103 140736 20110103 1456174 user1 d5599domaincom 20110105 150317 20110105 1523155 user1 d5599domaincom 20110214 1439 20110214 1440166 user1 d5599domaincom 20110223 135430 20110223 1358237 user1 d5599domaincom 20110321 101018 20110321 10328 user1 d5645domaincom 20110609 101241 20110609 1058599 user1 d5682domaincom 20110103 120345 20110103 12294310 user2 d5682domaincom 20110112 142605 20110112 14325311 user2 d5682domaincom 20110117 150619 20110117 15442212 user2 d5682domaincom 20110118 150730 20110118 15424313 user2 d5682domaincom 20110125 152055 20110125 15243814 user2 d5682domaincom 20110214 150300 20110214 150743here is the datasetstructurelistusername cuser1 user1 user1user1 user1 user1 user1 user1user1 user2 user2 user2 user2 user2 user2 machine structurec1l 1l 1l 1l 1l 1l 1l 2l 3l3l 3l 3l 3l 3l 3l label cd5599domaincom d5645domaincomd5682domaincom d5686domaincom d5694domaincom d5696domaincomd5772domaincom d5772domaincom d5847domaincom d5855domaincomd5871domaincom d5927domaincom d5927domaincom d5952domaincomd5993domaincom d6012domaincom d6048domaincom d6077domaincomd5688domaincom d5815domaincom d6106domaincom d6128domaincom class factor start structurec1294040658 12940407891294056456 1294232597 1297686819 1298462070 1300695018 13076035611294049025 1294835165 1295269579 1295356050 1295961655 12976885801297688363 class cposixct posixt tzone end structurec12940408471294042156 1294059377 1294233795 1297687216 1298462303 13006963421307606339 1294050583 1294835573 1295271862 1295358163 129596187812976863 1297689287 class cposixct posixt tzone names cusernamemachine start end rownames cna 15l class dataframe,['python'] +241857,android thisable screen support x large screens is it possible to thisable support for extra large screens in the android manifest file we have developed an app but have yet to alter the design for tablets so we would like to thisable tablet support until a later release we have developed the app using phonegaphtml5 so our java knowledge is limitedmy manifest file lists the following supportsscreens androidlargescreenstrue androidnormalscreenstrue androidsmallscreenstrue androidresizeabletrue androidanydensitytrue is there a property for extra large screenscheerspaul,['android'] +241863,exceptiongetmessage output with class name i am trying to fix an issue in my application i have this codetry object1method1 catchexception ex joptionpaneshowmessagedialognul error exgetmessageand the object1 would do something like thatpublic void method1 some code throw new runtimeexceptioncannot move filei get a mesage in my option pane like thiserror javalangruntimeexception cannot move filebut i used getmessage and not tostring method so the name of the class shouldna t appear rightwhat i am doing wrongi already tryied with a lot of exceptions even exception itself i am looking to solve this no without the need to implement my own exception subclassproblem solved thank you all the try and catch were actually being called in get method from swingworker which constructs an executionexception with my exception thrown from doinbackgroundi fixed doing thisoverrideprotected void done try object you object get do whatever you want catchexecutionexception ex joptionpaneshowmessagedialognull error exgetcausegetmessage catchexception ex joptionpaneshowmessagedialognull error exgetmessage,['java'] +241873,how to have a shared context per toplevel processthread without using inheritablethreadlocal i would like to see if there is a good pattern for sharing a context across all classes and subthreads of a toplevel thread without using inheritablethreadlocali have got several toplevel processes that each run in their own thread these toplevel processes often spawn temporary subthreadsi want each top level process to have and manage it is own database connectioni do not want to pass around the database connection from class to class and from thread to subthread my associate calls this the community bicycle pattern these are big toplevel processes and it would mean editing probably hundreds of method signatures to pass around this database connection right now i call a singleton to get the database connection manager the singleton uses inheritablethreadlocal so that each toplevel process has it is own version of it while i know some people have problems with singletons it means i can just say dbconnectorgetdbconnectionargs to paraphrase whenever i need the correctly managed connection i am not tied to this method if i can find a better and yet stillclean solutionfor various reasons inheritablethreadlocal is proving to be tricky see this questiondoes anyone have a suggestion to handle this kind of thing that does not require either inheritablethreadlocal or passing around some context object all over the placethanks for any helpupdate i have managed to solve the immediate problem see the linked question but i would still like to hear about other possible approaches fortytwos suggestion below is good and does work thanks but see the comments for why it is problematic if people vote for jtahlborns answer and tell me that i am being obsessive for wanting to avoid passing around my database connection then i will relent select that as my answer and revise my worldview,['java'] +241877,using this and attributes in member function trailing return types in this answer i gave it made sense to use this and the attribute of the class arg in the trailing return type as part of the decltype expression it is possible to do without but inconvenientneither clang 30 see below nor gcc 452 accepted it thoughinclude iostreamclass myclass public myclassint i argi template typename f auto applyf f decltypef arg return f arg template typename f auto applyf f decltypefthis arg return fthis arg private int argstruct id template typename v v operatorv v const return v struct complexid template typename c typename v v operatorc const v v return v 1 int main id id complexid complex myclass c0 stdcout capplyid capplycomplex nclang 30 says clang stdc11 weverything testcpptestcpp838 error use of undeclared identifier arg auto applyf f decltypef arg testcpp845 error type name requires a specifier or qualifier auto applyf f decltypef arg testcpp845 error c requires a type specifier for all declarations auto applyf f decltypef arg testcpp87 error auto return without trailing return type auto applyf f decltypef arg testcpp1339 error invalid use of this outside of a nonstatic member function auto applyf f decltypefthis arg testcpp1352 error type name requires a specifier or qualifier auto applyf f decltypefthis arg testcpp1352 error c requires a type specifier for all declarations auto applyf f decltypefthis arg testcpp137 error auto return without trailing return type auto applyf f decltypefthis arg 8 errors generatedhum not so greathowever the support of c11 is hacky at best in most compilers and i could not find specific restrictions mentionned in the standard n3290in the comments xeo suggested that it might have been a defect in the standardso is this allowed or not bonus and do more recent versions of clang gcc support this,['c++'] +241882,c ide that can build over ssh we are moving our development for c to c but all build servers run linux and development happens on windows machines our c editor does not do c very well so we are looking at alternativesthe code itself lives on the build server connected by optcode type link in windowswe need ssh as that is the normal connection to the build servers we would like an integrated solution for errorswarnings being able to opened in the editor we do not care about running the codeare there any free editors that can execute builds over ssh thanks,['c++'] +241901,ios5 stable app crashing in ios43 simulator i am getting an nsinvalidargumentexception with reason uitapgesturerecognizer initwithcoder unrecognized selector sent to instancemy understanding was that uitapgesturerecognizers were supported in ios4xis it possible to load a different xib file for sub ios5 versions,['objective-c'] +241909,how can i download the latest java ee jars without installing glassfish i need to get the latest java ee jars but i do not need glassfish on my computer on the oracle download site i see versions of the install with and without jdk but none without glassfish when running the installers advanced install i see an option to skip configuring glassfish but not to skip installing it how can i just get the java ee jars by java ee jars i mean the modularized jars that contain the java ee functionality javax such as mailjar,['java'] +241941,pythondaemon context fails to start when a stale pid file is present i am using pythondaemon and having the problem that when i kill 9 a process it leaves a pidfile behind ok and the next time i run my program it does not work unless i have already removed the pidfile by hand not oki catch all exceptions in order that contextclose is called before terminating when this happens eg on a kill the varrunmydaemonpid files are removed and a subsequent daemon run succeeds however when using sigkill kill 9 i do not have the chance to call contextclose and the varrun files remain in this instance the next time i run my program it does not start successfully the original process returns but the daemonized process blocks at contextopenit seems like pythondaemon ought to be noticing that there is a pidfile for a process that no longer exists and clearing it out but that is not happening am i supposed to be doing this by handnote i am not using with because this code runs on python 24from daemon import daemoncontextfrom daemonpidlockfile import pidlockfilecontext daemoncontextpidfile pidlockfilevarrunmydaemonpidcontextopentry retry main loopexcept exception e passcontextclose,['python'] +241943,restart unicorn issue capistrano i have got following settings in deployrb to restart my servernamespace deploy do task restart do run if f unicorn pid e proccat unicorn pid then kill usr2 cat unicorn pid else cd deploy tocurrent bundle exec unicorn c unicorn conf e rails env d fi endendbut it does not work i mean that command executes it asks me the password and gives no errors but all changes in config files are still ignored ie number of worker processes or database settings,['ruby-on-rails'] +241976,get phone orientation but fix screen orientation to portrait i want to get the phone orientation but keep the screen orientation to portraitso no matter the user turns the phone to landscape or portrait the view stays the same but i can get whether it is turned to landscape or portraitsetting the activity to androidscreenorientationportrait will fix both but i wouldnt be able to detect the phone orientation viapublic void onconfigurationchangedconfiguration newconfig switch newconfigorientation case configurationorientation portrait toastmaketextthis portrait toastlength shortshow break case configurationorientation landscape toastmaketextthis landscape toastlength shortshow break default break has anyone an idea how to fix that,['android'] +241981,datetimetostring month and day language i have a list of email addresses of people that have different nationalities for each person i have the iso codewhen i send the email to all these people in the text of the mail i need to to convert a datetime field to a string formatted in their specific culturefor this i am doing cultureinfo ci new cultureinfoisomystringdate mydatetostringcidatetimeformatshortdatepatternand work perfect but if i use longdatepattern instead short for thisplaying date like monday 13 june 2010 its work fine except the language of the day and monthif the person culture is itit i need to thisplay martedi and giugno not monday and junehow can i do that without change the current ui culture,['c#'] +241982,using xpath contains against html in java i am scraping values from html pages using xpath inside of a java program to get to a specific tag and occasionally using regular expressions to clean up the data i receive after some research i landed on html cleaner as the most reliable way to parse raw html into a good xml format html cleaner however only supports xpath 10 and i find myself needing functions like contains for instance in this piece of xmldiv td id1234 foo 5678hellotddivi would like to be able to get the text hello with the following xpathdivtdcontainsid footextis there any way to get this functionality i have several ideas but would prefer not to reinvent the wheel if i do not need toif there is a way to call html cleaners evaluatexpath and return a tagnode which i have not found i can use an xml serializer on the returned tagnode and chain together xpaths to achieve the desired functionalityi could use html cleaner to clean to xml serialize it back to a string and use that with another xpath library but i cannot find a good java xpath evaluator that works on a stringusing tagnode functions like getelementsbyattvalue i could essentially recreate xpath evaluation and insert in the contains functionality using stringcontainsshort question is there any way to use xpath contains on html inside an existing java library,['java'] +242005,download image from remote source and resize then save do any of you know of a good php class i can use to download an image from a remote source resize it to 120x120 and save it with a file name of my choosingso basically i would have an image at save to my web server imagesmychosennamejpg as a 120x120 pixelsthanks,['php'] +242008,running emulator after building android from source i am able to pull down the latest android source code into a ubuntu virtual machine 32bit host windows 7 64bit the build completes without any errorsthen i tried to follow these instructions where it mentions that i should run the emulator on the root of my source code however when i tried that i get an error stating that this command is not foundso i went to the folder outhostlinuxx86bin and i found out that there are couple files for emulatoremulatoremulatorarmemulator rendereremulatoruiemulatorx86when i typed the emulator and emulatorx86 here it also does not work here is the error i am gettingxouthostlinuxx86bin emulatorx86emulator error you did not specify a virtual device name and the systemdirectory could not be foundif you are an android sdk user please use name or avd nameto start a given virtual device see helpavd for detailsotherwise follow the instructions in helpthiskimages to start the emulatorso when i run emulatorx86 helpthiskimages i see the followingif you are building from the android build system you shouldhave android product out defined in your environment and theemulator shall be able to pickup the right image files automaticallysee helpbuildimages for more detailsi built this myself so i would think that android product out is set in my environment variables but i do not see it so i think that i should run some other shell script to get that seti looked at the img files i saw couple at the location outtargetproductgenericramthiskimgsystemimguserdataimgcould anyone shed some light on this and assist me on what i should do next i am new to android and i did some research on this but i could not find any similar issues,['android'] +242032,how to generate a repeatable random number sequence i would like a function that can generate a pseudorandom sequence of values but for that sequence to be repeatable every run the data i want has to be reasonably well randomly thistributed over a given range it does not have to be perfecti want to write some code which will have performance tests run on it based on random data i would like that data to be the same for every test run on every machine but i do not want to have to ship the random data with the tests for storage reasons it might end up being many megabytesthe library for the random module does not appear to say that the same seed will always give the same sequence on any machineedit if youre going to suggest i seed the data as i said above please provide the documentation that says the approach valid and will work on a range of machinesimplementations edit cpython 271 and pypy 17 on mac os x and cpython 271 and cpython 2522 ubuntu appear to give the same results still no docs that stipulate this in black and whiteany ideas,['python'] +242039,what are extensions in php v8js i have started using v8js with php for a while now but the documentation is really thinone thing that is not explained is extensionsit is possible to registerextension but it is not explained in detail how these behave or whats their purpose or benefitscan anyone provide a good description or link to a documentation that explains extensionsthanks to everyone for taking time to read and answer,"['php', 'javascript']" +242040,good ide for nodejs coffeescript jasmine what good ides are there to develop with the combination of jasmine nodejs and coffeescriptso far were considering webstorm but it is really hard to get started we find very little documentation on nodejs and coffeescript in combination with the idewhat other options are there and are there any guides that can help us get startedup and runningedit me and my team are running windowsosxvimemacs is not an option we need something with a graphical interfacean ideit must be easy to get started with nodejs and coffee in the ide preferably somewhat tailored for use with nodejswebstorm promises to do just that however getting started turns out to be pretty difficult running coffee does not seem to workthanks,['javascript'] +242077,from xmldocument to xmlreader net after an advice from a user that answered to my question i am tring to convert my xmldocument code to xmlreader code but i am having some troublesthis is xml generated from phpmysql page rowidlink64idlinkidhost3idhosturlurlrowrowidlink68idlinkidhost4idhosturlurlrow until about 10 rowsthis is my xmldocument code xmldocload if xmldocdocumentelement null foreach xmlnode node in xmldocdocumentelement if nodename row listaddnew links idlink converttoint32nodechildnodes0innertext idhost converttoint32nodechildnodes1innertext url nodechildnodes2innertext return listnow i have some trouble to convert in xmlreader i tried many code but i cant handle it using xmlreader reader new xmltextreader if readernodetype xmlnodetypeelement,['.net'] +242081,virtual extension methods in upcoming java 8 release when i see code snippets like interface a void a void b default systemoutprintlnb void c final systemoutprintlnc i have one question have not we already got enough sht in java why one might need this,['java'] +242111,porting my c app to run in a browser is there an easy way to port a c opengl app to a browser it is already ported to pc mac and ios if there is some relatively easy way would that be portable between computer browsers i would have to use different binaries for different platforms of course i remember hearing something about some sandboxed environment for chrome some time ago but that would exclude the other browsers how did they id do with quake in the browser,['c++'] +242123,check for database connection otherwise thisplay message i would like to check if the website can connect to mysql if not i would like to thisplay an error saying that the user should try to access the page again in a few minutesi really do not know how to do this any help would be greatly appreciatedstring mysql error resource link identifier but how do i use thisthis just gives me the error but i want the message to thisplay with any errorthanks,"['php', 'mysql']" +242139,what does s and d mean in printf in the c language i do not understand what the s and d do in this c codefor i0isizeofcodesizeofchar i printfsdsdn length of string i is strlencodei str codei printfsdscnthe first character in string i is str0i am new to the c language and my background is in javawhat do the sdsd symbols denotewhy are there so many of themis the comma used here for concatenation instead of a,['c'] +242160,linq not any vs all do not often i want to check if a provided value matches one in a list eg when validatingif acceptedvaluesanyv v somevalue exception logicrecently i have noticed resharper asking me to simplify these queries toif acceptedvaluesallv v somevalue exception logicobviously this is logically identical perhaps slightly more readable if youve done a lot of mathematics my question is does this result in a performance hitit feels like it should ie any sounds like it shortcircuits whereas all sounds like it does not but i have nothing to substantiate this does anyone have deeper knowledge as to whether the queries will resolve the same or whether resharper is leading me astray,"['c#', '.net']" +242164,do we need mfence when using xchg i have a set and test xchg based assembly lock my question is do we need to use memory fencing mfence sfence or lfence when using xchg instruction edit 64 bit platform with intel nehalem,"['c++', 'c']" +242186,how to create a direct link to any fancybox box i need that when i click in anything that uses fancybox it generates a specific url for that so when i send this link to someone it opens the specific box i wantfor examplefancyboxnethomewhen i click in the first image the link still fancyboxnethomei want that when i click in the image the url is generated and appears in address bar like fancyboxnethomeimageid1so when i send fancyboxnethomeimageid1 to someone it already opens the image in the boxthanksit is like facebook photos when you click in any photo the photo opens in a box but the address bar changes to the image linkupdate 1i did what jfk suggested but after one hour trying i still do not know why the boxes are not the samelook the diference betweenthe codescript typetextjavascriptvar thishash windowlocationhashdocumentreadyfunction ifwindowlocationhash thishashfancybox preveffect none nexteffect none closebtn false arrows true nextclick true helpers thumbs width 80 height 80 title type inside buttons afterload function thistitle thisindex 1 de thisgrouplength div idcurtiiframe srcampsendtrueamplayoutstandardampwidth45ampshow facesfalseampactionlikeampcolorschemelightampfontampheight35 scrollingno frameborder0 stylebordernone overflowhidden width56px height24px allowtransparencytrueiframediv triggerclick fancylinkfancybox preveffect none nexteffect none closebtn false arrows true nextclick true helpers thumbs width 80 height 80 title type inside buttons afterload function thistitle thisindex 1 de thisgrouplength div idcurtiiframe srcampsendtrueamplayoutstandardampwidth45ampshow facesfalseampactionlikeampcolorschemelightampfontampheight35 scrollingno frameborder0 stylebordernone overflowhidden width56px height24px allowtransparencytrueiframediv readyscript whats wrong in that script,['jquery'] +242199,apidata sources linking and payperuse i am an independent developer who wanted to write a simple commercial app to thisplay movie showtime information after doing a whole lot of research i could not find any good legal way of getting this dataone option i considered was screenscraping or scraping xml feeds but reading through the terms and conditions i do not think this option is the right way to go another option is to figure something out with a company called tribune media services looks like this company supplies showtime api to sites such as google yahoo fandango etc but an individual developer like me cannot probably afford this for a small commercial appthen i decided to look for other ideas like building a finance related app but again data source became a big issue i do not understand why several sites like billboards provide api but not for commercial use i am all for paying for using apidata but i could not find an amazonwebservicelike scheme where individual or small business folks can pay for what they use i think this would encourage a lot of innovation and can also provide the data content owners some moneyare there such apis out there in the entertainment or finance domain where i can develop commercial apps without doing any screenscraping lastly would linking to a showtimes page be considered legal for example if user wants to see showtimes for a particular theater can we generate a link to the google showtimes page in the app when clicked takes you to the google showtimes page on the browser,"['android', 'iphone']" +242205,how to run an android app in background this code will run an app automatically after booting the system but the app will close after pressing the back button if the app is run normally by clicking it is icon it will continuously run even after pressing the back button or running other appspublic class autoboot extends broadcastreceiver override public void onreceivecontext context intent intent intent i new intentcontext myactivityclass iaddflagsintentflag activity new task contextstartactivityi my question is how to make this auto run code to continuously run even after pressing the back button or running other apps,['android'] +242210,how to solve android screen size for different mobile devices i am testing the android application in a small screen mobile if i use samsung tablets like other landscape mobile to test my android application the contents are moved slightly how do i solve the screen resolution in android,['android'] +242227,how to change font color of uisegmentedcontrol i try to change font color from white to black for uisegmentedcontrol for ios 4uisegmentedcontrol button uisegmentedcontrol alloc initwithitemsnsarray arraywithobjectsitemtitle nil autoreleasebuttonmomentary yesbuttonsegmentedcontrolstyle uisegmentedcontrolstylebarbuttontintcolor uicolor redcolor for id segment in button subviews for id label in segment subviews if label iskindofclassuilabel class uilabel titlelabel uilabel label titlelabel settextcoloruicolor blackcolor uibarbuttonitem barbuttonitem uibarbuttonitem alloc initwithcustomviewbutton autoreleasebut text color does not changed what i should do for change text color for uisegmentedcontrol,"['iphone', 'objective-c']" +242228,gcc segfaults when decltype used in nested lambda i created a macro that conveniently builds lambda functions using which i can iterate through tensor objects in a library that i wrote however nesting these macros seemed to cause gcc to undergo an internal segmentation fault upon expanding the compilers preprocessor output and going through some trial and error i thiscovered that cause seems to be the use of decltype in the parameter list of a nested lambda function declared in the method of a class or struct below follows a minimal example using the standard libraryinclude iostreaminclude type traitstemplate class iterator class funcvoid for eachconst iterator first const iterator last func func for iterator it first it last it funcit template class tclass helper typedef typename tsize type typetemplate class tclass helpert typedef typename tsize type typetemplate class tclass helpert typedef typename tsize type type struct bar struct foo typedef int size type foo void test int arr 1 2 3 for eacharr arr 3 int i x the typename type segfaults g for eacharr arr 3 typename helperdecltypefoo type j int main return 0compiler output g wall stdc0x nested lambdacppnested lambdacpp in lambda functionnested lambdacpp4256 internal compiler error segmentation faultplease submit a full bug reportwith preprocessed source if appropriatesee fileusrsharedocgcc46readmebugs for instructionspreprocessed source stored into tmpccqyohfaout file please attach this to your bugreporti initially opted to use decltype because an object is passed to a macro and i need to extract the objects type from the objects type t t or t i would use a traits class to pull tsize type size type would then be the type of the lambda function parametershow can i circumvent this issue without having to use a typedef to declare the type of the lambda function parameter in advance if you can think of some other solution that could easily be implemented in a macro ie copied and pasted repeatedly in the parameter list of a lambda function that would work too,['c++'] +242231,different ways of comparing nsdecimalnumber for example with primitive i will do thisif x 60 x 20 do something here and with nsdecimalnumber this is what i haveif x comparensnumber numberwithint60 nsorderedsame x comparensnumber numberwithint60 nsordereddescending x comparensnumber numberwithint20 nsorderedsame x comparensnumber numberwithint60 nsorderedascending do something hereis there any other ways easier and more elegant to this comparison if i convert the value to primitive what primitive do i use i do not want to use cgfloat float or double as i am handling with currency here or if i do convert them to those mentioned above can someone verify explain about the precision,"['objective-c', 'ios']" +242252,file and bundleresource urls i have been breaking my head over this for quite a while now and cant find a solution for this problemi have an eclipse rcp application that uses a custom library packaged as jar from the plugin i am calling a method within the jarwithin this method i am getting a resource using thisclassgetresourcerelpath whereas relpath is a hardcoded relative path to a file i need this returns me an url which i can use to construct a filenow this works perfectly if i am not calling this method from the plugin but from a simple javaprogramthe difference eclipse rcps classloader returns an url of protocol bundleresource which is not supported by file whereas when running a simple javaprogram a fileurl is returned which is completely fine to construct a filei am aware of the filelocatorclass of the eclipse sdk which resolves bundleresourceurls to fileurls but i cannot use it within the library because i dont want to tie it to the eclipse rcp platform it should be possible to use this lib from noneclipsercp sources as wellanyone any idea on how i can load this resource from a relative path in a manner that will work both when the method is called from an eclipse rcpplugin or any other clienti need to construct a file on the directory of this relative path to search for files within i am completely stuck on thisupdate if there is a possibility other than using filelist to get directory contents this would already help meany hints greatly appreciated,['java'] +242289,canvas mask an image and preserve its alpha channel heres what i am trying to doget image a and image b image b is a black and white mask imagereplace image as alpha channel with image bs red channeldraw image c on the canvasdraw image a on top of image ceverything seems ok until step 4 image c is not visible at all and where image a should be transparent there is white colorcxputimagedataimagea 0 0var resultdata cxgetimagedata0 0 viewwidth viewheightfor var h0 hresultdatadatalength h4 resultdatadatah3 imagebdatahcxputimagedataimagec 0 0cxputimagedataresultdata 0 0,['javascript'] +242323,c function to insert text at particular location in file without overwriting the existing text i have written a program which takes a file as input and whenever it finds a line with length 80 it adds and and to that file to make it 80 chars in width maxthe problem is that i have used fseek to insert and and whenever the length exceeds 80 so it overrides two characters of that line which exceeds length 80 is there a way using which i can insert text without overriding the existing text here is my codeincludestdiohincludestringhint mainint argc char argv file fp1fp2 int prev0now0 char ch int flag0 long cur fp1fopenargv1r iffp1null printfunable to open the file to read program will exit exit0 else whilechfgetcfp1eof ifch chn nownow1 else ifnow80 fseekfp1curseek set fputcfp1 fputcnfp1 now0 continue ifchn flag0 now0 continue else prevnow curftellfp1 nownow1 fclosefp1 return 0to run it you need to do followinguserubuntu cc xyzcuserubuntu aout file to checktxt,['c'] +242346,javascriptserializerdeserialize array i am having trouble deserializing an array in net mvc3 any help would be appreciatedheres the code snippet using httpwebresponse response requestgetresponse as httpwebresponse using streamreader reader new streamreaderresponsegetresponsestream javascriptserializer jsserializer new javascriptserializer string jsondata readerreadtoend result bigcommerceorderproductsjsserializerdeserializebigcommerceorderproductsjsondata heres the subset of the data string returned by json as jsondata i have remove extra fields id33order id230025id34order id230025here are the objectsserializablepublic class bigcommerceorderproducts public listbigcommerceorderproduct data get set serializablepublic class bigcommerceorderproduct public int id get set public int order id get set i am getting this errortype pxomodelsbigcommercebigcommerceorderproducts is not supported for deserialization of an arrayany ideas,['c#'] +242356,viewpager in scrollview i need to have a viewpager inside a scrollview but viewpager just does not appear when it is in scrollview everything is ok when i do not use scrollviewi have seen a couple questions like this being asked here on stackoverflow or on other sites and all of them have been answered that you have to put androidfillviewporttrue to your scrollview to fix the problem but this solution doesnt work for me viewpager still does not appear even if i have androidfillviewporttrue in my scrollviewi guess something got changed in the android apis or something and this solution does not work anymore does anyone know how i could possibly make a viewpager appear in a scrollviewupdate a working scrollview layout xmlscrollview androidididscrollview1 androidlayout widthfill parent androidlayout heightfill parent androidfillviewporttrue linearlayout androidididlinearlayout1 androidlayout widthfill parent androidlayout heightfill parent androidorientationvertical androidsupportv4viewviewpager androidididitemsviewpager2 androidlayout widthfill parent androidlayout heightwrap content androidsupportv4viewviewpager linearlayout scrollview,['android'] +242362,portable way of determining if a process can movedelete a file what would be a portable way to determine if a python process can movedelete a file without having to movedelete the file in questionuse case i would like to inform the user of a script whether or not movedelete operations will succeedfail prior to starting processingif there is a solution that only works in linux i would be ok with that for the momentthanksupdate i understand that osaccess can be used but is limited to real uidgid,['python'] +242369,mvc unit testing the wrong things whilst practicing some tdd at work for an aspnet mvc project i ran into a number of scenarios where i was writing tests to ensure that particular actions returned the correct views or had particular attributes on them childactiononly etc in fact i found a number of interesting posts here so about useful extension methods to help acheive thiswhen i was first introduced to the concepts of unit testing and tdd when on a course a few years ago the emphasis was based strongly on that tests should be focusing on testing logic behind the userdesired features and functionality the core project requirements if you willmy question is if this is the case are menial tests checking for the correct view file to be rendered or an action having a particular attribute etc not really encompassing what the unit testing methodology is all about am i writing tests for the wrong reasons ie simply protecting myself and other colleagues from making a refactoring mistake or are these valid cases of valuable unit tests,['c#'] +242392,apache cxf spring simple certificate authentication i have started learning the apache cxf with spring first of all i have created a simple clientserver model see herenow i am trying to use a simple certificate authentication so that i have changed the configuration files for the server and clientcxfservletxmlbeans xmlnsxmlnsxsixmlnsjaxwsxsischemalocation jaxwsendpoint idhelloworld implementorservicehelloworldimpl addresshelloworld jaxwsfeatures bean classorgapachecxffeatureloggingfeature jaxwsfeatures jaxwsininterceptors bean classorgapachecxfbindingsoapsaajsaajininterceptor ref beanwss4jininterceptor jaxwsininterceptorsjaxwsendpointbean idwss4jininterceptor classorgapachecxfwssecuritywss4jwss4jininterceptor constructorarg map entry keyaction valuesignature entry keypasswordcallbackref ref beanpasswordcallback entry entry keysignaturepropfile valueserver signproperties map constructorargbeanbean idpasswordcallback claservicepasswordcallbackhandler server signpropertiesorgapachewssecuritycryptoproviderorgapachewssecuritycomponentscryptomerlinorgapachewssecuritycryptomerlinkeystoretypejksorgapachewssecuritycryptomerlinkeystorepasswordkeystorepasswordorgapachewssecuritycryptomerlinfilepublicstorejkscxfclientservletxmlbeans xmlns xmlnsxsi xmlnsjaxws xsischemalocation bean idclient claservicehelloworld factorybeanclientfactory factorymethodcreatebean idclientfactory classorgapachecxfjaxwsjaxwsproxyfactorybean property nameserviceclass valueservicehelloworld property nameaddress valuehttplocalhost8080serviceshelloworld property nameoutinterceptors list bean classorgapachecxfbindingsoapsaajsaajoutinterceptor ref beanwss4joutinterceptor list propertybeanbean idwss4joutinterceptor classorgapachecxfwssecuritywss4jwss4joutinterceptor property nameproperties map entry keyaction valuesignature entry keyuser valuewsclient entry keypasswordcallbackref ref beanpasswordcallback entry entry keysignaturepropfile valueclient signproperties map propertybeanbean idpasswordcallback classclientpasswordcallbackhandler the client is working perfectly it uses it is passwordcallbackhandler the problem is the server does not seem to use its passwordcallbackhandler i have run the server in a debug mode but it does not go to this class can anybody please explain what do i do wrongthanks in advanceprogress if you try to provide a request from a user which certificate is not in the servers keystore the error is raised no certificates for user wsclient1 were found for signature from the resource as you can see in the jbosswscxfxml file above a keystore password callback handler is also configured while the properties file has the password for the keystore this callback handler is used to set password for each key it has to match the one used when each key was imported in the store,['java'] +242399,unable to connect remote server web service i have tried to integrate this web service into my aspnet project but it popups such type of error if you have any idea regarding this kindly give me solution there are very rare materials about oodle web services and oodle apitry this url to have more idea about my problemregionchicagocategoryvehiclecar,"['c#', 'asp.net']" +242412,aspnet development server concurrent processing does not work i am trying to find out why aspnet development server is not processing the requests concurrently so i have created a simple aspx page with the following codeprotected sub page loadbyval sender as object byval e as systemeventargs handles meloadsystemthreadingthreadsleep10end subif i open the page two times the response takes 20 seconds that means the server executes requests one by one not concurrently following advice provided in this topic i have added enablesessionstatefalse to the page but that does not seem to helpany ideas how to make the requests process concurrently,"['asp.net', '.net']" +242424,java move components with mouse i tried to make any component draggable by simply adding mouse listeners and using the setlocation function of javaawtcomponent i started with jbutton to test if it were possible the way i thoughthere is a code example for what i am trying to doimport javaawtimport javaxswingpublic class dragbutton extends jbuttonprivate volatile int draggedatx draggedatypublic dragbuttonstring text supertext setdoublebufferedfalse setmarginnew insets0 0 0 0 setsize25 25 setpreferredsizenew dimension25 25 addmouselistenernew mouseadapter public void mousepressedmouseevent e draggedatx egetx getlocationx draggedaty egety getlocationy addmousemotionlistenernew mousemotionadapter public void mousedraggedmouseevent e setlocationegetx draggedatx egety draggedaty public static void mainstring args jframe frame new jframedragbutton framesetlayoutnull framegetcontentpaneaddnew dragbutton1 framegetcontentpaneaddnew dragbutton2 framegetcontentpaneaddnew dragbutton3 framesetsize300 300 framesetdefaultcloseoperationjframeexit on close framesetlocationrelativetonull framesetvisibletrue somehow this fails to work properly and i do not get why the actual thistance dragged is half the thistance of the mouse movement and it flickers around that thistance while dragging as if two mouse positions are competing over the mousemotionlistenermay anyone help a swingawt noob many thanks in advanceeditok so the problem was that i did not know that the event would refire at each mouse location with the position being relative to the firing jcomponent so this is the corrected and working codeimport javaawtimport javaawteventimport javaxswingpublic class dragbutton extends jbutton private volatile int draggedatx draggedaty public dragbuttonstring text supertext setdoublebufferedfalse setmarginnew insets0 0 0 0 setsize25 25 setpreferredsizenew dimension25 25 addmouselistenernew mouseadapter public void mousepressedmouseevent e draggedatx egetx draggedaty egety addmousemotionlistenernew mousemotionadapter public void mousedraggedmouseevent e setlocationegetx draggedatx getlocationx egety draggedaty getlocationy public static void mainstring args jframe frame new jframedragbutton framesetlayoutnull framegetcontentpaneaddnew dragbutton1 framegetcontentpaneaddnew dragbutton2 framegetcontentpaneaddnew dragbutton3 framesetsize300 300 framesetdefaultcloseoperationjframeexit on close framesetlocationrelativetonull framesetvisibletrue thanks adel for your efforts and mkorbel for the link,['java'] +242431,c logitech g19 sdk getting started does anyone have a sample tutorial or a link on how to use the logitech g19 keyboard sdk with visual studio 2010 and c for programming the lcd i cannot find anything anywhere for c,['c#'] +242461,how do i get the location of the userconfig file in programmatically i would like to thisplay the location of the userconfig file in my windows forms application so a user can easily find iti understand how the path is created thanks to can i control the location of net user settings to avoid losing settings on application upgradehowever in case this changes i would rather not have to construct path this in my app especially if there is an easy method for getting the userconfig file location,['c#'] +242465,break two for loops possible duplicatehow to break out of multiple loops in python is it possible to break out of two for loops in pythonie for i in range1100 for j in range1100 break all the loops,['python'] +242508,access protected members from templated static member function ok so i am taking a sort of modified crtp route here to avoid virtual function lookups but i just cannot understand one error it gives meso i am trying to translateclass apublic static void fooa pa pabar protected virtual void bar trace0 tabarn class b public aprotected virtual void bar trace0 tbbarn which works as expected toclass apublic template class t static void foot pt ptbar protected void bar trace0 tabarn class b public aprotected void bar trace0 tbbarn which gives the errorerror c2248 bbar cannot access protected member declared in class bsee declaration of bbarsee declaration of bsee reference to function template instantiation void afoobt being compiled with tbnow i know this is easily fixed by adding friend class a to class b but that is not very neat is not there another wayedit example usageb bbfoobbedit 2 the member function foo being static does not matter i noticed,['c++'] +242517,what is the enumerable argument for in objectcreate in what usages of objectcreate do you want to set enumerable to true,['javascript'] +242530,how do i store an array of objects in a cookie with jquery cookie i have a list of javascript objectsvar people name abel age 1 name bella age 2 name chad age 3 i tried to store them in a browser cookie with jquery cookiecookiepeople peoplei then retrieve this cookie and then try to push another object into itvar people cookiepeoplepeoplepush name daniel age 4 however this does not work i analyzed this code in firebug and console noted that people was a string object objectobject objectobject object and that the push function did not existwhat is going on what is the proper way to store and retrieve a list of objects,"['javascript', 'jquery']" +242614,call static method given a class object in java ifclass myclass public static void mainstring str systemoutprintlnhello world in some other file and methodclass klass classfornamemyclasshow can i call myclassmain i do not have the string myclass at compile time so i cannot simply call myclassmainstring,['java'] +242633,java calling outer class method in anonymous inner class recently i ran into a mysterious problem in an android project which i described here i somehow solved the problem but still do not know the exact reason behind it let us say i want to call a function foo in the inner class the question is whats the difference between calling it directly likefor calling it with the outer class instanceouterclassthisfoobesides i will appreciate if anyone can check my last question related to this and give me a clue about why the error occurs many thanksps i read somewhere that the nonstatic inner class will always hold an instance of the outer class so it will call outer function using that instance if i only use foo,"['java', 'android']" +242648,regex to match words of a certain length i would like to know the regex to match words such that the words have a maximum length for eg if a word is of maximum 10 characters in length i would like the regex to match but if the length exceeds 10 then the regex should not match i tried w10but that brings me matches only if the minimum length of the word is 10 characters if the word is more than 10 characters it still matches but matches only first 10 characters,['java'] +242683,how to change the background color of android status bar i want to change the background color of the status bar by writing an application my android device has black color i want to change it to some other color i saw some posts related to it here but they are telling about notification backgroundif any body knows about this please help methe default status barafter using a drawable as background to status bar,['android'] +242721,library for dialogs and widgets in win32 console application in c i have seen a lot of console apps that run on windows having some dialog boxes and widgets inside them say for examplea there are a lot more now my question is there any library in c for creating dialogs and widgets in a win32 console appupdate seen pdcurses but it lacks libraries from the real ncurses library like menuh and formh so ss there any other that is easy to usethanks a bunch,['c'] +242738,fastest way to incrementally read a large file when given a buffer of max buffer size and a file that far exceeds it how can oneread the file in blocks of max buffer sizedo it as fast as possiblei tried using nio randomaccessfile afile new randomaccessfilefilename r filechannel inchannel afilegetchannel bytebuffer buffer bytebufferallocatecaparicy int bytesread inchannelreadbuffer bufferflip while bufferhasremaining bufferget bufferclear bytesread inchannelreadbuffer afilecloseand regular io inputstream in new fileinputstreamfilename long length filenamelength if length integermax value throw new ioexceptionfile is too large byte bytes new byteint length int offset 0 int numread 0 while offset byteslength numread inreadbytes offset byteslength offset 0 offset numread if offset byteslength throw new ioexceptioncould not completely read file filename incloseturns out that regular io is about 100 times faster in doing the same thing as nio am i missing something is this expected is there a faster way to read the file in buffer chunksultimately i am working with a large file i do not have memory for to read it all at once instead i would like to read it incrementally in blocks that would then be used for processing,['java'] +242739,set javascript api accesstoken i am developing a facebook app i have a server side oauth flow which allows me to authenticate a user without requiring him to click on any button i hence retrieve his accesstoken as long as other information and use those ones on the server side before to generate the pagein my application i now need to use the javascript api which could technically share the same oauth tokenis it possible to instantiate the fb javascript object with a given oauth token i know it is possible to do the contrary meaning doing the oauth process on the client side and share the oauth key with the server side via the cookie but this has two many drawbacks in my opinion first it implies to have this login button which is to me not a good user experience for a facebook app also i do not get how this oauth process is supposed to behave if my application is composed of two different pages going from one page to another reloads entirely the javascript will this oauth process with the popup and so forth be done on each page reloading thanks for your help,['javascript'] +242746,how to sort hashmap keys i have one problem hashmapstring listaprjmilestone datemilestonemap new hashmapstring listaprjmilestonei am putting dynamic key in hashmap object like thisdatemilestonemapputcratedatevaluefinally i am getting result like this28012012value01012012value26012012valuei want return key value pairs in desc or asc order how can i do that,['java'] +242750,uifont with custom font fails with nil i am trying to add a custom font to my project in xcode 42 but whenever i try to use it i get a error that the object is nili have done the following1 added a row to my plist fonts provided by application value lcdmono2 ultrattf2 added the font to my supporting files and showed it in xcode to verify it was added3 verified using get info that the full name is lcdmono2 ultra4 created the font in my project withuifont myfont uifont fontwithnamelcdmono2 ultra size16and i have tried this variantuifont myfont uifont fontwithnamelcdmono2 ultra size16f5 tried to use the font name addobjectmyfontfontname generating the nil errorwhat could be causing the error could it be something like the space in the name,"['iphone', 'objective-c']" +242767,how to determine the direction on onmousemove event on some condition i want to cancel onmousemove event when mouse goes down for example is it possible to determine the direction of onmousemove event jq or js is oki have draganadrop elements the user drags the elenment up if for example the bottom of the element reaches some position in the document ie 500px from the top of the document the onmousemove stops and if the user will try to drag the element up again the function will not start only drag down will be possible for this element so i thought it would be quite easy to do it by catching the direction of the mousemove event but it seems thereas no such kind of standard properties,"['javascript', 'jquery']" +242768,keep track of parent class from member imageview i have class a with an instance variable imageview currently i use settag to get from the imageview back to the instance of class a could that present circular loop i also heard of mention of weak references what is the best way to get at the parent class a of the imageview my usage scenario is i am dragging the imageview around the screen and i need to access class a for information about the imageview being dragged,"['java', 'android']" +242780,how to uninstall own app from systemapp i am able to install own application into systemapp using adb shell commands but how to uninstall it is there any commands to do it my phone is rooted,['android'] +242800,whats the pythonic way of generating a range of chars in other languages i would use a construct like thisazi could not come up with a better solution than thischrx for x in rangeorda ordz 1is there a shorter more readable way of building such a list,['python'] +242833,add inverted circle overlay to map view using ios 5 and xcode 42i have followed the instructions here refdocuidtp409497ch6sw15 and used the mkcircle and mkcircleview classes to add a circle overlay on my mkmapview however what i actually want is an inverted circle overlay like the left map in the sketch below currently i have a circle overlay like the one on the rightfor the inverted circle the overlay should cover the entire map apart from the visible circleis there an easy way to accomplish this using the mkcirclemkcircleview classes or will i have to go deeper and define a custom overlay objectviewthank you for your help,['ios'] +242856,android 40 ics app icon on action bar not clickable for some reason when testing on my motorola xoom with ice cream sandwich the app icon in the action bar is not clickable even though i have implemented an event handler this only occurs after changing the targetsdkversion to 15 if it is 13 it is still clickable even on ics why is this happening and how can i make it clickable like a button i searched the documentation and could not find anythingthank youupdate here is my codeandroidmanifestxmlusessdk androidminsdkversion4 androidtargetsdkversion15 application androidicondrawableicon androidlabelstringapp name androidthemestyleandroidthemehololightbaseactivityjava my activities all inherit from this classoverridepublic boolean onoptionsitemselectedmenuitem item switch itemgetitemid case androidridhome app icon in action bar clicked go home intent intent new intentthis mainactivityclass intentaddflagsintentflag activity clear top startactivityintent return true default return superonoptionsitemselecteditem,"['java', 'android']" +242869,rotating text with css and ie i need to rotate text with css i have the following style rules but they do not appear to work in internet explorerfooter descr span moztransform rotate20deg firefox otransform rotate20deg opera webkittransform rotate20deg safari y chrome transform rotate20deg safari y chrome fontsize40px thisplayblock float left margin 0 10px 0 0how can i rotate text in ie with css,"['html', 'css']" +242871,android glsurfaceview causes leak i am trying to use glsurfaceview on android and experiencing problemsi am using the code from this opengl articleit works well but when i rotate the device i notice that the allocated memory is growingso i use mat to check if i have a memory leak and found that there are multiple activity instances there if i use dominator tree i found multiple glthread objects but only one is runningso is this an android glsurfaceview bug or i am misunderstanding something about glsurfaceview,['android'] +242878,twitter bootstrap dropdown menu i am trying to use twitter bootstraps dropdown menu in its top nav bar you can see an example working here in mine the arrow indicating that it is a dropdown shows on the menu but when i hover or click on it it does not reveal my dropdown links i think i have included all the necessary classes and i do not believe twitters requires javascript can you see what i am doing wrongmy dropdown div classtopbar datadropdowndropdown div classfill div classcontainer ul classnav li link to home main approot path li li link to outlines main appoutlines path li li classdropdown a href classdropdowntoggleassessmenta ul classdropdownmenu lia hrefsecond link ali lia hrefthird link ali ul li i go on to close all the divs etc the nav bar looks great but the dropdown just does not work twitter bootstrapdiv classtopbar datadropdowndropdown div classtopbarinner div classcontainer h3a hrefproject nameah3 ul classnav li classactivea hrefhomeali lia hreflinkali lia hreflinkali lia hreflinkali li classdropdown a href classdropdowntoggledropdowna ul classdropdownmenu lia hrefsecondary linkali lia hrefsomething else hereali li classdividerli lia hrefanother linkali ul li ul form classpuleft action input typetext placeholdersearch form ul classnav secondarynav li classdropdown a href classdropdowntoggledropdowna ul classdropdownmenu lia hrefsecondary linkali lia hrefsomething else hereali li classdividerli lia hrefanother linkali ul li ul div div topbarinner div,['css'] +242892,converting string 2a12 two and a half into 25 right now i am building a small app that imports data from a spreadsheet and due to the nature of the original entry there is a string being read in that has values such as 8a12 2a12 etcmy goal with a simple function is to convert 2a12 into float 25 for examplei have tried the to f method but that has left me with a weird value of 202a12any insight or suggestions here would be very much appreciated,"['ruby-on-rails', 'ruby']" +242897,why is my s3 presigned request invalid when i set a response header override that contains a i am using the amazon net sdk to generate a presigned url like thispublic systemwebmvcactionresult asactionresultstring contenttype string contentthisposition responseheaderoverrides headeroverrides new responseheaderoverrides headeroverridescontenttype contenttype if stringisnullorwhitespacecontentthisposition headeroverridescontentthisposition contentthisposition getpresignedurlrequest request new getpresignedurlrequest withbucketnamebucketname withkeyobjectkey withprotocolprotocolhttps withexpiresdatetimenowaddminutes6 withresponseheaderoverridesheaderoverrides string url s3clientgetpresignedurlrequest return new redirectresulturl permanent falsethis works perfectly except if my contenttype contains a in it this happens when i try to get an svg file for example which gets a content type of imagesvgxml in this case s3 throws a signaturedoesnotmatch errorthe error message shows the stringtosign like thisget 1234567890 blahblabhblahsvgresponsecontentthispositionfilenameblahsvgresponsecontenttypeimagesvg xmlnotice there is a space in the responsecontenttype where it now says imagesvg xml instead of imagesvgxml it seems to me like that is what is causing the problem but whats the right way to fix itshould i be encoding my content type enclose it within quotes or something the documentation does not say anything about this,['c#'] +242928,find the count of substring in string i have to find the count of a substring in a string using the c languagei am using the function strstr but it only finds the first occurrencemy idea of the algorithm is something like searching in the string while strstr does not return null and to substring the main string on each loopmy question is how to do that,['c'] +242939,force high quality thumbnails for youtube is there a way to force a high quality thumbnail for youtubemy videos are of very high quality and once they start streaming they run fine in 720p however the thumbnail for the video is of variable quality sometimes it is high other times it is really blurryis there a way of forcing a high quality thumbnail i have found this in the api docs but it does not detail how to use the media tag,['javascript'] +242959,removing one list from another in python 27 we can do a 1 2 3 b 4 5 a b1 2 3 4 5however we cannot do a bsince python seems to have something cool for nearly everything what is the most pythonesque to do a b in your opinionsimilar question for dictionaries which can neither do a b or a b where a and b are both dictionaries thanks,['python'] +242977,autoloading classes in ruby without its autoload i love the autoload functionality of ruby however it is going away in future versions of ruby since it was never threadsafeso right now i would like to pretend it is already gone and write my code without it by implementing the lazyloading mechanism myself i would like to implement it in the simplest way possible i do not care about threadsafety right now ruby should allow us to do thislet us start by augmenting a class const missingclass dummy def selfconst missingconst puts const missingconstinspect superconst endendruby will call this special method when we try to reference a constant under dummy that is missing for instance if we try to reference dummyhello it will call const missing with the symbol hello this is exactly what we need so let us take it furtherclass dummy def selfconst missingconst if oauth const require dummyoauth const getconst warning possible endless loop else superconst end endendnow if we reference dummyoauth it will require the dummyoauthrb file which is expected to define the dummyoauth constant there is a possibility of an endless loop when we call const get since it can call const missing internally but guarding against that is outside the scope of this questionthe big problem is this whole solution breaks down if there exists a module named oauth in the toplevel namespace referencing dummyoauth will skip its const missing and just return the oauth from the toplevel most ruby implementations will also make a warning about thiswarning toplevel constant oauth referenced by dummyoauththis was reported as a problem way back in 2003 but i could not find evidence that the ruby core team was ever concerned about this today most popular ruby implementations carry the same behaviorthe problem is that const missing is silently skipped in favor of a constant in the toplevel namespace this wouldnt happen if dummyoauth was declared with rubys autoload functionality any ideas how to work around this,['ruby'] +243005,python requests exception handling how to handle exceptions with python library requestsfor example how to check is pc connected to internetwhen i try try requestsgetexcept connectionerror handle the exceptionit gives me error name connectionerror is not defined,['python'] +243007,calling a javascript function from console in chromes javascript console how do i call a function that belongs to a js file included in the webpage i am viewing,['javascript'] +243010,nsproxy and key value observing nsproxy seems to work very well as standin objects for those that do not yet exist for example nsmethodsignature methodsignatureforselectorselsel return selftarget methodsignatureforselectorsel voidforwardinvocationnsinvocation invocation invocation invokewithtargetselftargetthe above code will transparently pass any method invocation to the target that the proxy represents however it does not seem to handle kvo observations and notifications on the target i tried to use a nsproxy subclass as standing for objects to be passed to nstableview but i am getting the following error cannot update for observer nsautounbinderobservance 0x105889dd0 for the key path objectvaluestatus from nstablecellview 0x105886a80 most likely because the value for the key objectvalue has changed without an appropriate kvo notification being sent check the kvocompliance of the nstablecellview classis there a way to make transparent nsproxy that is kvo compliant,['objective-c'] +243028,is androids camerainfoorientation correctly documented incorrectly implemented in android you can get a description of the properties of a camera by retrieving a camerainfo i am interested in orientation as described at however the documentation seems inconsistent with how all four of my devices behave and i have news of a fifth device for which this seemly fixed value changesin particular the documentation saysthe value is the angle that the camera image needs to be rotated clockwise so it shows correctly on the thisplay in its natural orientation for example suppose a device has a naturally tall screen the backfacing camera sensor is mounted in landscape you are looking at the screen if the top side of the camera sensor is aligned with the right edge of the screen in natural orientation the value should be 90 if the top side of a frontfacing camera sensor is aligned with the right of the screen the value should be 270but in the stated example it is the camera image that is rotated 90 degrees clockwise relative to the naturally tall orientation not the other way around that is the image whose top is aligned with the right hand side of the device needs 270 degrees clockwise rotation to align with the devices top sideat least all four of my devices report 90 for this value and all act as if the cameras top is the right side of the device when held in natural orientation that is the image must be rotated 270 degrees clockwise not 90 to match the natural orientation the example seems correct the first line does notthis example code seems to support my conclusion as it only gives the right result when orientation is interpreted as abovestrangely i have log evidence from one users device that shows it reporting this value as 90 at times and 0 at other times it ought to be a physical property of how the camera is seated in the device rightcan anyone confirm that the first line of the documentation is in fact wrong and the example is righthas anyone observed a changing value of camerainfoorientation is there evidence in docs that this is legal behavior or is it likely a bug in the deviceany other related comments experiences gotchas i have not run into yet,['android'] +243036,combine hash and nonhash urls in backbonejs is there some way how to combine hash and nonhash urls in backbonejs applicationi set backbonehistorystartpushstate true when user click on some link i fetch json data from server update page and call backbonehistorynavigate to change url in browser from for example from examplecomzlinskykampanmf to examplecommoravskoslezskykampanmfif user copy url from browser and open in second tab he will see same page so every page updated this way have corresponding page on server this is exactly what i wantbut now i have problemi have several select on page too when user change value in them i make some dynamic changes on page without fetching json from server updates is done only on client side i would like change urls according to select for example to examplecommoravskoslezskykampanmfstate1 so when somebody send this url the other side will see same page in same state as senderi could not find way how to do it in backbonejs if i set pushstate true on backbonehistory router ignore hash tagsif i set pushstate false i am not able to set urls like i describe in first paragraph abovethank you for any hint,['javascript'] +243044,profiling advice trying to pinpoint site loading issue i have taken over a wordpress ecomm although this question is more about profiling generally site which has a performance issue which seemingly only affects one specific area in the admin section of the cms when trying to edit one particular type of product which has a large number of attributes attached to it the page effectively causes the browser to crash 99 of the time i expected this to be down to mysql queries causing the bottleneck however when i profiled the db i got the following resultstotal queries 174 total time of mysql queries 011370this suggests the bottleneck is happening elsewhere but i am not sure where it could be if i run yslow on the page there is nothing drastic there which would explain the issue although there are around 20 scripts and stylesheets loaded so some optimisation could be done there i am going to enable an opcode cache library which will improve php performance but is there anything else i can do to try to identify the issue here thanks,"['php', 'mysql']" +243046,what is the difference between synchronizedthis and synchronizedclassnameclass i read somewhere that synchronizedthis should be avoided for various reasons yet some respectable code that i encountered uses the following in the constructorpublic someclasscontext context if double checked lock null synchronized someclassclass if double checked lock null some code here is there really a difference between synchronizedthis and synchronizedsomeclassclass,['java'] +243048,what perfmon counters are useful for identifying aspnet bottlenecks given the chart here what should i be looking at to identify the bottleneck as you can see requests are averaging nearly 14 seconds under load and the bulk of that time is attributed to the clr in new relics profiling data in the performance breakdown for a particular page it attributes the bulk of the time to the webtransactionaspx page,"['asp.net', '.net']" +243051,work around spellcheckersession leak i thiscovered my activity is leaking on the ics emulator hprof seemed to show spellcheckersession keeping a reference to my activity around and there appears to have been a fix frameworks basecommitdf3722895172e03c81787f62d922daabaad3e20bbut is there any way to work around this in the mean time can i thisable spell checking somehow,['android'] +243081,long long not bigger than longmax value if i have an assignmentlong c a bis there an easy way to check that a b is not biggersmaller than longmax valuelongmin value,['java'] +243115,why does not immutablemapbuilderbuild pick the correct type parameters why does mapstring test immutablemapbuilderbuild fail to compile but mapstring test immutablemapstring objectbuilderbuild work finethe first code sniplet fails witherror incompatible types mapstring test immutablemapbuilderbuild required mapstring found immutablemapobjectobjecti believe the guava committers meant for this to work,['java'] +243131,how should stale indexes be handled during testing i am using ravendb in inmemory mode for unit testing my queries are backed by static indexes i am not using waitfornonstaleresults api nor do i want totypical workflow for a test isinitialise ravendb in inmemory modeintegrate indexes using indexcreationcreateindexesassembly idocumentstoreinsert test data for verifying query behaviourrun queryverify query outputi have noticed steps 13 happen so quickly that static indexes do not have time to get updated before step 4 therefore the indexes are stalei have created a quick workaround for this after step 3 i executewhile documentstoredocumentdatabasestatisticsstaleindexeslength 0 threadsleep10this feels cumbersome what i would like to know isis it normal for indexes to be stale when running ravendb in inmemory modeis there a better way to avoid stale indexes during testing,['c#'] +243143,how to add static value when doing insert into with select in a mysql query i have two mysql tables a and b with fields x and y table b has 1 extra field z table a is in database db1 and b is in db2 i want to copy x and y from a to b and set a static value for z how can i do that db1ax db2bxdb1ay db2by4 db2bzso far i haveinsert into db2b xy select xy from db1ahow do i set db2bz to 4 i do not want to set a permanent default variable for the table,"['mysql', 'sql']" +243156,eclipse indigo typing lag on os x lion i am working on a fairly large project and have recently bumped into the good old friend of mine from the 90s typing lagmy setup is macbook pro 22 ghz i7 8gb with ssd drive and it has not had any serious performance issues so fari have increased the memory allocations to xmx1024m and xxmaxpermsize512m there is no heavy use of plugins involved also this only happens on java files in the default editorwhat could be the problemediti found the problem i noticed that the problem occurred only when editing large java files in my case the class had 1800 rowsit is weird though since i am not facing the same problem with the same eclipse setup on ubuntu it seems like eclipse on mac just cannot handle java files that big i was editingany suggestionsedit2i am using the eclipse indigo for java ee with the latest updates 371xinstalled pluginsm2eclipsemercurialeclipse aka hge 191 from the official eclipse update sitesubclipse installed but not used in the workspace where the typing lag occursadt installed but not used in this projectall plugins are installed via eclipse marketplace and are updated to the latest release unless stated otherwise,['java'] +243207,android sqlite query with multiple where heres my current sqlite codecursor c sqldatabaserawqueryselect docid as id recipeid from table recipe name where key ownerid new string owneridit works fine but when i tried adding multiple where to something like thiscursor c sqldatabaserawqueryselect docid as id recipeid from table recipe name where key ownerid key partnerid key advertiserid key chefid new string ownerid partnerid advertiserid chefid it returns an error so how do i deal with multiple,['android'] +243214,auto height on parent container with absolutefixed children im trying to set an automatic height a div that contains 2 child elements positioned fixed and absolutely respecitvelyi want my parent container to have an auto height but i know this is hard as the child elements are taken out of the page structure with their positionsi have tried setting a height to my parent div that works but with my layout being responsive when its scaled down to mobile the height remains the same where as the content within becomes stacked and so the height needs to increase with its childrennot sure if this makes sense i dont have my actual code on me atm but ive made a fiddle trying to explain,"['html', 'css']" +243220,how to read aloud python list comprehensions my question is about python list comprehension readability when i come across code with complexnested list comprehensions i find that i have to reread them several times in order to understand the intentis there an intuitive way to read aloud list comprehensions seems like i should start reading from the middle then read the if conditions if any and read the expression lastheres how i would read the follow line of code aloud in order to understand itx y for x in 123 for y in 314 if x yfor each element in list x and each element in list y if the two elements are not the same create a list of tuplestwo examples that i am struggling withhow would you read the following list comprehensions aloudfrom another question in stack overflow x for b in a for x in bpython docs has this examplerowi for row in matrix for i in range4any suggestions or pointers for ways to read aloud list comprehensions such that the intention becomes clearer is much appreciated,['python'] +243222,how do i autocrop a uiimage i have a uiimage which contains a shape the rest is transparent i would like to get another uiimage by cropping out as much of the transparent part as possible still retaining all of the nontransparent pixels similar to the autocrop function in gimp how would i go about doing this,['ios'] +243260,xcode ios how to determine whether code is running in debug release build i am making an app that processes sensitive credit card dataif my code is running in debug mode i want to log this data to the console and make some file dumps however on the final appstore version ie when it is running in release mode it is essential all of this is thisabled security hazardi will try to answer my question as best i can so the question becomes is this solution path the right or best way to do it add is debug1 to your debug build preprocessor settings if is debug define mylogargs nslogargs else define mylogargs endif,['ios'] +243279,how to settorecipients with mfmailcomposeviewcontroller i am trying to get emails that i select to send an emailbut i dont know how to settorecipients which users that i heve selected in the mfmailcomposeviewcontroller viewif mfmailcomposeviewcontroller cansendmail mailer mfmailcomposeviewcontroller alloc init mailermailcomposedelegate self mailer setsubjecta message from blablabl nsmutablearray usersto nsmutablearray alloc init torecipients usersto mailer settorecipientstorecipients nsstring emailbody blablablabal mailer setmessagebodyemailbody ishtmlyes only for ipad mailermodalpresentationstyle uimodalpresentationpagesheet self presentmodalviewcontrollermailer animatedyes else uialertview alert uialertview alloc initwithtitlefailure messageyour device does not support the composer sheet delegatenil cancelbuttontitleok otherbuttontitles nil alert show delegate,"['iphone', 'objective-c']" +243318,can i use uipinchgesturerecognizers to thistinguish between horizontal and vertical pinches i have a view which the user can pinch to grow or shrink i would like this to work along two axes if the pinch is mostly horizontal it will growshrink the object horizontally but if the pinch is mostly vertical it will growshrink the object verticallycan i achieve this with one or two pinch recognizers and if so how,"['objective-c', 'ios']" +243362,passing parameters to constructors using autofac i am very new to autofac so it is possible that i am completely misusing itlet us say i have a class that has this structurepublic class helperclass ihelperclass public helperclastring a string b thisa a thisb b and i have two classes that use that class but require different defaults for the constructor the second constructor is just for testing purposes we will always want a helperclass in the real apublic class doessomething idoessomething public doessomething thisnew helperclassdo something internal doessomethingihelperclass helper thishelper helper public class doessomethingelse idoessomethingelse public doessomethingelse thisnew helperclassdoes somethingelse internal doessomethingelseihelperclass helper thishelper helper heres my autofac modulepublic class somethingmodule module protected override void loadcontainerbuilder builder builderregistertypedoessomethingasidoessomething builderregistertypedoessomethingelseasidoessomethingelse my questionswhen i call resolve on doessomething or doessomethignelse will it resolve the internal constructor instead of the public one do i need to leave ihelperclass unregisteredif yes how do i make it pass different parameters to each instance of ihelperclass depending on whether it is used in doessomething or doessomethingelse,['c#'] +243380,jquery ajax how to get response data in error i have a simple web applicationi have created the server rest api so it will return a response with http code and a json or xml object with more details application code specific to scenario message that describe what happened etcso for example if a client send a register request and the password is too short the response http code will be 400 bad request and the response data will be appcode 1020 message password is too shortin jquery i am using the ajax function to create a post request when the server returns something different from http code 200 ok jquery defines it as error the error handler can get 3 parameters jqxhr textstatus errorthrownho can i get the json object that sent by the server in error caseedit1 here is my js codefunction register username password var postdata postdatausername username postdatapassword password ajax datatype json type post url serverrestregister data postdata success functiondata showresultsucceeddata hidewaitingdone error function jqxhr textstatus errorthrown showresultfailedjqxhrresponsetext hidewaitingfail 2 when looking at firebug console it seems like the response is emptywhen invoking the same request by using rest testing tool i get a response with json object it itwhat am i doing wrong,"['javascript', 'jquery']" +243400,can i override a jsr303 validation annotation i have a test like belowpublic class testsizeannotationpublic static void mainstring args systemoutprintln validationbuilddefaultvalidatorfactorygetvalidatorvalidatenew cpublic static class p private liststring lst newarraylistaa sizemax0 messagep public liststring getlst return lst public void setlstliststring lst thislst lst public static class c extends p override sizemax5 messagec public liststring getlst return supergetlst with the following outputconstraintviolationimplinterpolatedmessagep propertypathlst rootbeanclassclass comvalidatortestsizeannotationc messagetemplatephowever i expected that the annotation can size be overridden and no warning will appearis there a way to accomplish that edit i found a bug seems related to that but i run 420 final and still get the above behavior,['java'] +243410,sql server count the number of times the id from table a occurs in table b i have two tables products and orders orders references products via productid as a foreign key i want to know how many times each product has been sold including the product being sold only once i can almost get it to work using a left join but that still gives one row with a count of one for all products regardless of whether they exist in the orders table or notis there a way to do this that will have you ending up with something like thisproduct times soldmilk 5bread 18cheese 0 and so on,['sql'] +243426,best way to negate an instanceof i was thinking if exist a betternicer way to negate a instanceof in javaactually i do something likeifstr instanceof string do something but i think that should exist a beautiful syntax to do thissomeone know if it exists and how the syntax look likeeditby beautiful i might say something like thisifstr instanceof string do something compile failure,['java'] +243431,given that an object is an array of any type how do you test that it is empty in java please help me complete my isempty methodpublic static boolean isemptyobject test if testnull return true if testgetclassisarray if test instanceof string string sstringtest return s if test instanceof collection collection ccollectiontest return csize0 return falsewhat code would i put int to establish that if i am dealing with an array it will return true if it is length is zero i want it to work no matter the type whether it is int object just so you know i can tell you that if you put an int into an object variable it will throw an exception,['java'] +243447,howwhere to find microsoft default styles for wpf controls i am looking to change the style of a control but i basically want to copy part of a default style does anyone know how i can figure out what the default style of a control isin my case i am wanting to make the column headers in a datagrid go blue on mouse over like the row headers do,['c#'] +243452,python file does not read whole file iofileio does why the following code executed in python 272 on windows only reads in a fraction of the underlying fileimport osin file openospathjoinsettingsbasepathcompanynamedocxincontent in filereadin fileclosewhile this code works just fineimport ioimport osin file iofileioospathjoinsettingsbasepathcompanynamedocxincontent in filereadin fileclosewhy the difference from my reading of the docs they should perform identically,['python'] +243456,are there any rules of thumb for when javascript values are copied by reference and not by value even as a somewhat seasoned js dev i find myself constantly suprised at shallow vs deep copies of objectsare there any rules of thumb for when javascript values are copied by reference and not by value for the major object types for example i know string values are always copied by value not reference,['javascript'] +243480,make lines of text have equal length in centered h1 elements if the text falls on multiple lines line breaks make the text look like this this is a header that takes up two lines this is a header that takes up three lines because it is really really longis there a way to manipulate these elements so that the length of the lines of text is roughly equal like this this is a header that takes up two lines this is a header that takes up three lines because it is really really longthe jquery plugin widow fix prevents singleword lines but i am looking for something that evens out all the lines in a multiline element are there any jquery plugins for this or can you recommend a strategy,"['javascript', 'jquery']" +243527,contain an image within a div i want to contain an image into a 250 x 250 div forcing the image to resize but not stretch how can i do this by the way the image will usually be bigger than the div itself which is why resizing comes into the picturediv id container img src whatever divcontainer width250px height250px border1px solid 0 heres a jsfiddle which someone can edit,['css'] +243531,are pointers always set to nil on declaration i have found various peoplearticles eg this so answer suggesting that the value of pointers in objectivec is not defined until you assign something to it however i am finding in practice that they are automatically set to nil even before i call alloc the following code runs for me without assertingnsstring foo 1assertfoonil foo is nilfoo nsstring alloc 2assertfoonil after alloc not nilfoo foo init 3assertfoonil still not nilcanshould i rely on this is it guaranteed or do i just happen to be running my compiler xcode in some sort of debug mode i am new to objectiveca corollary question what is the correct terminology to describe foo in the state at the end of the lines marked 1 2 and 3 i imagine at least one of 1 2 them is termed uninitialised and one of 2 3 is initialised but which and what do we call the third option,['objective-c'] +243539,split string into string array i have been playing around with programming for arduino but today i have come across a problem that i cannot solve with my very limited c knowledgeheres how it goesi am creating a pc application that sends serial input to the arduino deviceid command commandparameters this arduino will transmit that command over rf to other arduinos depending on the deviceid the correct arduino will perform the commandto be able to determine the deviceid i want to split that string on the this is my problem i know how to do this easily in java even by not using the standard split function however in c it is a totally different storycan any of you guys tell me how to get this workingthanks serial event example when new serial data arrives this sketch adds it to a string when a newline is received the loop prints the string and clears it a good test for this is to try it with a gps receiver that sends out nmea 0183 sentences created 9 may 2011 by tom igoe this example code is in the public domain string inputstring a string to hold incoming data boolean stringcomplete false whether the string is complete string receiveddata void setup initialize serial serialbegin9600 reserve 200 bytes for the inputstring inputstringreserve200 void loop print the string when a newline arrives if stringcomplete serialprintlninputstring clear the string inputstring stringcomplete false serialevent occurs whenever a new data comes in the hardware serial rx this routine is run between each time loop runs so using delay inside loop can delay response multiple bytes of data may be available void serialevent while serialavailable get the new byte char inchar charserialread if inchar n stringcomplete true add it to the inputstring ifstringcomplete false inputstring inchar if the incoming character is a newline set a flag so the main loop can do something about it string splitcommandstring text char splitchar int splitcount countsplitcharacterstext splitchar string returnvaluesplitcount int index 1 int index2 forint i 0 i splitcount 1 i index textindexofsplitchar index 1 index2 textindexofsplitchar index 1 ifindex2 0 index2 textlength 1 returnvaluei textsubstringindex index2 return returnvalue int countsplitcharactersstring text char splitchar int returnvalue 0 int index 1 while index 1 index textindexofsplitchar index 1 ifindex 1 returnvalue1 return returnvalue i have decided i am going to use the strtok functioni am running into another problem nowserialeventcpp in function void splitcommandstring charserialevent68 error cannot convert string to char for argument 1 to char strtokchar const charserialevent68 error null was not declared in this scope string inputstring a string to hold incoming data void splitcommandstring text char splitchar string temp int index 1 int index2 fortemp strtoktext splitchar temp temp strtoknull splitchar serialprintlntemp forint i 0 i 3 i serialprintlncommandi,['c'] +243560,the best practice for not null if statements i have been writing my if this variable is not empty statements like soif var yupbut i have asked if this is correct it has not caused a problem for me here is the answer i found onlineif error null yupthis actually looks longer than my approach but is it better if so why,['php'] +243564,converting roman numerals to decimal i have managed to get my code to convert most roman numerals to its appropriate decimal value but it does not work for some exceptional cases example xcix 99 but my code prints 109here is my codepublic static int romanconvertstring roman int decimal 0 string romannumeral romantouppercase forint x 0xromannumerallengthx char converttodecimal romancharatx switch converttodecimal case m decimal 10 break case d decimal 500 break case c decimal 100 break case l decimal 50 break case x decimal 10 break case v decimal 5 break case i decimal 1 break if romannumeralcontainsiv decimal2 if romannumeralcontainsix decimal2 if romannumeralcontainsxl decimal10 if romannumeralcontainsxc decimal10 if romannumeralcontainscd decimal100 if romannumeralcontainscm decimal100 return decimal,['java'] +243580,post an array from an html form without javascript i have a form that is a little complex and i am hoping to simplify the serverside php processing by natively posting an array of tuplesthe first part of the form represents a userfirst namelast nameemailaddressetcthe second part of the form represents a treefruitheightetcthe problem is that i need to be able to post multiple trees for a single user in the same form i would like to send the information as a single user with an array of trees but this might be too complex to do with a form the only thing that comes to mind is using javascript to create some json message with a user object and an array of tree objects but it would be nice to avoid javascript to support more users some people have scripts turned off,['html'] +243589,html5 data attribute rules i was wondering if you can have a data attribute that is just data or just data what are the rules here,['html'] +243623,shared preferences inside broadcastreceiver in my appi want to use shared preferences inside a broadcast receiverbut i cant access the getpreferences method inside sharedpreferences sharedpreferences getpreferencesmode privatei cant call with the context objectany other method,['android'] +243638,how to autoplay html5 mp4 video on android i had developed a mobile page by aspnet to play mp4 videoi know ios had thisabled the autoplay function to minimize user bandwidth so how can i autoplay html5 mp4 video on android i had already put autoplay in html5 code but it does not workthe following is my codevideo autoplay controls idvideo1 width100 posterimagestop iconpng webkitenterfullscreen poster preloadtruesource src typevideomp4 codecsavc142e01e mp4a402 videomoreover i had fixed the problem that user click on the image overlay can play the videothanks karthihere are the codescript typetextjavascript documentreadyfunction video1bindclick function var vid thisget0 if vidpaused vidplay else vidpause scriptthanksjoe,['android'] +243644,mysql 55 on lion not working i have installed mysql 55 via the thisk image on mac os x 107 i have also added usrlocalmysqlbin to my path in bash profilewhich mysql returns usrlocalmysqlbinmysqlhowever i cannot seem to get the server running no matter whatever i trymysql u root returnserror 2002 hy0 cannot connect to local mysql server through socket tmpmysqlsock 2sudo usrlocalmysqlbinmysqld safe starts and then immediately stops the daemon120130 231857 mysqld safe logging to usrlocalmysqldatabryansmacbookprolocalerr120130 231857 mysqld safe starting mysqld daemon with databases from usrlocalmysqldata120130 231859 mysqld safe mysqld from pid file usrlocalmysqldatabryansmacbookprolocalpid endedi feel that i have tried every possible solution that can be found and i am out of ideas now i have even tried installing an older version of mysql 51 and got the same results and efforts invainfurther informationrunning mysqld results in mysqld120209 00223 warning setting lower case table names2 because file system for usrlocalmysql5520osx106x86 64data is case insensitive120209 00223 note plugin federated is thisabledmysqld table mysqlplugin does not exist120209 00223 error cannot open the mysqlplugin table please run mysql upgrade to create it120209 00223 innodb the innodb memory heap is thisabled120209 00223 innodb mutexes and rw locks use gcc atomic builtins120209 00223 innodb compressed tables use zlib 123120209 00223 innodb initializing buffer pool size 1280m120209 00223 innodb completed initialization of buffer pool120209 00223 innodb highest supported file format is barracuda120209 00223 innodb 118 started log sequence number 1595675120209 00223 error mysqld unknown option skiplocking120209 00223 error aborting120209 00223 innodb starting shutdown120209 00224 innodb shutdown completed log sequence number 1595675120209 00224 note mysqld shutdown completeupdatewell i removed mysql completely from my system reinstalled an older version 51 and it is actually starting up now however i still cannot run rails server i get the following errorusersbrickerrvmgemsruby187p352gemsmysql2027libmysql2mysql2bundle dlopenusersbrickerrvmgemsruby187p352gemsmysql2027libmysql2mysql2bundle 9 library not loaded optlocallibmysql5mysqllibmysqlclient r16dylib loaderrorso i have run this commandsudo install name tool change libmysqlclient r16dylib optlocallibmysql5mysqllibmysqlclient r16dylib rvmgemsruby187p352gemsmysql2027libmysql2mysql2bundlebut still receive the error when attempting to start the rails serverupdate 2okay final update after everything reinstalling mysql numerous times seeing all these errors it turns out that perhaps the original problem was a conflict between gems mysql2027 and mysql20311 to ultimately fix the problemremoved all mysqlrelated files from my system see bash script belowinstalled mysql 5161 64bit from the thisk image provided on the mysql websiteran the following linessudo install name tool change libmysqlclient r16dylib optlocallibmysql5mysqllibmysqlclient r16dylib rvmgemsruby187p352gemsmysql2027libmysql2mysql2bundlesudo install name tool change libmysqlclient16dylib usrlocalmysqlliblibmysqlclient16dylib rvmgemsruby187p352gemsmysql2027libmysql2mysql2bundleran gem uninstall mysql2 and selected the version 0311 the only version left on this rvm section is mysql2027now everything seems to be working thanks again for all the helpbash script to remove mysqlrelated files from mac os x 106 107binbashsudo rm usrlocalmysqlsudo rm rf usrlocalmysqlsudo rm rf librarystartupitemsmysqlcomsudo rm rf librarypreferencepanesmysudo rm rf librarypreferencepanesmysudo rm rf libraryreceiptsmysqlsudo rm rf libraryreceiptsmysqlsudo rm rf vardbreceiptscommysqlecho donecopy into removemysqlsh make it executable chmod x removemysqlsh and run it,['mysql'] +243679,android menu and action bar conversion there is a new concept in androidbut it is not clear fro me i have an application which is support from 16 to 40 and i want to follow the new concept but i cannot set showasaction property in the menu xml becauseno resource identifier found for attribute showasaction in package androidit is normal because there is in the docnote the androidshowasaction attribute is available only on android 30 api level 11 and greaterhow can i set the menu that under 30 is a simple menu but over 30 as an actionbar,['android'] +243709,is there a way to ignore the unreachable statement error is it possible to somehow ignore this error i find it much easier to just put return in front of the code i do not want to run than to comment it when the comments overlap and behave badly,['java'] +243712,can adding const to a pointer help the optimization i have a pointer int p and do some operations in a loop i do not modify the memory just read if i add const to the pointer both cases const int p and int const p can it help a compiler to optimize the codei know other merits of const like safety or selfdocumentation i ask about this particular case rephrasing the question can const give the compiler any useful for optimization information ever,"['c++', 'c']" +243715,intentrecieverleakedexception are you missing a call to unregisterreceiver in android i am trying the following sms example frombut i am getting the following exception if i try to send messagesexception 0207 123815447 erroractivitythread839 activity commicromytest has leaked intentreceiver commicromytest1435a0c70that was originally registered here are you missing a call tounregisterreceiver 0207 123815447 erroractivitythread839 androidappintentreceiverleaked activity comtestsendsms has leakedintentreceiver comtestsendsms 1435a0c70 that was originallyregistered here are you missing a call to unregisterreceiver 0207 123815447 erroractivitythread839 at androidappactivitythreadpackageinforeceiverthispatcherinitactivitythreadjava707 0207 123815447 erroractivitythread839 at androidappactivitythreadpackageinfogetreceiverthispatcheractivitythreadjava535 0207 123815447 erroractivitythread839 at androidappapplicationcontextregisterreceiverinternalapplicationcontextjava748 0207 123815447 erroractivitythread839 at androidappapplicationcontextregisterreceiverapplicationcontextjava735 0207 123815447 erroractivitythread839 at androidappapplicationcontextregisterreceiverapplicationcontextjava729 0207 123815447 erroractivitythread839 at androidcontentcontextwrapperregisterreceivercontextwrapperjava278 0207 123815447 erroractivitythread839 at commicromytestsendsmssendsms java98 0207 123815447 erroractivitythread839 at commicromytestoncreatesendsms java42 0207 123815447 erroractivitythread839 at androidappinstrumentationcallactivityoncreateinstrumentationjava1123 0207 123815447 erroractivitythread839 at androidappactivitythreadperformlaunchactivityactivitythreadjava2231 0207 123815447 erroractivitythread839 at androidappactivitythreadhandlelaunchactivityactivitythreadjava2284 0207 123815447 erroractivitythread839 at androidappactivitythreadaccess1800activitythreadjava112 0207 123815447 erroractivitythread839 at androidappactivitythreadhhandlemessageactivitythreadjava1692 0207 123815447 erroractivitythread839 at androidoshandlerthispatchmessagehandlerjava99 0207 123815447 erroractivitythread839 at androidoslooperlooplooperjava123 0207 123815447 erroractivitythread839 at androidappactivitythreadmainactivitythreadjava3948 0207 123815447 erroractivitythread839 at javalangreflectmethodinvokenativenative method 0207 123815447 erroractivitythread839 at javalangreflectmethodinvokemethodjava521 0207 123815447 erroractivitythread839 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava782 0207 123815447 erroractivitythread839 at comandroidinternaloszygoteinitmainzygoteinitjava540 0207 123815447 erroractivitythread839 at dalviksystemnativestartmainnative method 0207 123815496 erroractivitythread839 activity commicromytest has leaked intentreceiver comtestmytest2435a13b8that was originally registered here are you missing a call tounregisterreceiver 0207 123815496 erroractivitythread839 androidappintentreceiverleaked activity comtestsendsms has leakedintentreceiver comtestsendsms 2435a13b8 that was originallyregistered here are you missing a call to unregisterreceiver 0207 123815496 erroractivitythread839 at androidappactivitythreadpackageinforeceiverthispatcherinitactivitythreadjava707 0207 123815496 erroractivitythread839 at androidappactivitythreadpackageinfogetreceiverthispatcheractivitythreadjava535 0207 123815496 erroractivitythread839 at androidappapplicationcontextregisterreceiverinternalapplicationcontextjava748 0207 123815496 erroractivitythread839 at androidappapplicationcontextregisterreceiverapplicationcontextjava735 0207 123815496 erroractivitythread839 at androidappapplicationcontextregisterreceiverapplicationcontextjava729 0207 123815496 erroractivitythread839 at androidcontentcontextwrapperregisterreceivercontextwrapperjava278 0207 123815496 erroractivitythread839 at commicromytestsendsmssendsms java129 0207 123815496 erroractivitythread839 at commicromytestoncreatesendsms java42 0207 123815496 erroractivitythread839 at androidappinstrumentationcallactivityoncreateinstrumentationjava1123 0207 123815496 erroractivitythread839 at androidappactivitythreadperformlaunchactivityactivitythreadjava2231 0207 123815496 erroractivitythread839 at androidappactivitythreadhandlelaunchactivityactivitythreadjava2284 0207 123815496 erroractivitythread839 at androidappactivitythreadaccess1800activitythreadjava112 0207 123815496 erroractivitythread839 at androidappactivitythreadhhandlemessageactivitythreadjava1692 0207 123815496 erroractivitythread839 at androidoshandlerthispatchmessagehandlerjava99 0207 123815496 erroractivitythread839 at androidoslooperlooplooperjava123 0207 123815496 erroractivitythread839 at androidappactivitythreadmainactivitythreadjava3948 0207 123815496 erroractivitythread839 at javalangreflectmethodinvokenativenative method 0207 123815496 erroractivitythread839 at javalangreflectmethodinvokemethodjava521 0207 123815496 erroractivitythread839 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava782 0207 123815496 erroractivitythread839 at comandroidinternaloszygoteinitmainzygoteinitjava540 0207 123815496 erroractivitythread839 at dalviksystemnativestartmainnative methodthe method which sends smspublicvoid sendsmsstring phonenumber string message string sent sms sent string delivered sms delivered pendingintent sentpi pendingintentgetbroadcastthis 0 new intentsent 0 pendingintent deliveredpi pendingintentgetbroadcastthis 0 new intentdelivered 0 when the sms has been sent the following line line 98 throws exception registerreceiver new broadcastreceiver public void onreceivecontext arg0 intent arg1 switch getresultcode case activityresult ok toastmaketextgetbasecontext sms sent toastlength shortshow break case smsmanagerresult error generic failure toastmaketextgetbasecontext generic failure toastlength shortshow break case smsmanagerresult error no service toastmaketextgetbasecontext no service toastlength shortshow break case smsmanagerresult error null pdu toastmaketextgetbasecontext null pdu toastlength shortshow break case smsmanagerresult error radio off toastmaketextgetbasecontext radio off toastlength shortshow break new intentfiltersent when the sms has been delivered registerreceiver new broadcastreceiver public void onreceivecontext arg0 intent arg1 switch getresultcode case activityresult ok toastmaketextgetbasecontext sms deliveredtoastlength shortshow break case activityresult canceled toastmaketextgetbasecontext sms not delivered toastlength shortshow break new intentfilterdelivered smsmanager sms smsmanagergetdefault smssendtextmessagephonenumber null message sentpi deliveredpi,['android'] +243738,textview onclick not working heres my code for mainxml merge xmlnsandroid relativelayout androidididcontainer androidlayout widthfill parent androidlayout heightfill parent xmlnsandroidinclude layoutlayouttabs scrollview androidfillviewporttrue androidscrollbarsnull androidlayout heightfill parent androidlayout widthfill parent linearlayout androidpaddingtop10dp androidlayout widthfill parent androidlayout heightwrap content androidorientationvertical first text view textview androidbackgroundcolorgrey androidtextcolorcolorwhite androidtextstringcategory androidididcategory1 androidlayout heightwrap content androidlayout widthfill parent androidlayout margintop65dp androidtextsize17dp androidtypefaceserif first horizontal scrollview horizontalscrollview androidscrollbarsnull androidididhorizontalscrollview1 androidlayout widthwrap content androidlayout heightwrap content linearlayout androidididlinearlayout1 androidorientationhorizontal androidvisibilityvisible androidlayout heightwrap content androidlayout widthwrap content image view should be here linearlayout horizontalscrollview linearlayoutscrollviewrelativelayoutmergeheres my code for tabsxmlxml version10 encodingutf8 relativelayout xmlnsandroidandroidlayout widthwrap contentandroidlayout heightwrap contentandroidorientationhorizontal androidbackground3textview androidtextcolorcolorgradient green androidididviewall androidlayout width85dp androidlayout height25dp androidlayout marginleft10dp androidlayout alignparentlefttrue androidlayout alignparenttoptrue androidtextsize17dp androidtextstylebold androidtextstringview all androidonclickonclick androidfocusablefalse androidclickabletrue textview androidtextcolorcolorwhite androidididpic androidlayout width45dp androidlayout height25dp androidlayout alignparenttoptrue androidlayout torightofidviewall androidtextsize17dp androidtextstylebold androidtextstringpic androidonclickonclick androidfocusablefalse androidclickabletrue relativelayoutand heres the code inside the mainjava public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain textview all textview thisfindviewbyidridviewall textview pic textview thisfindviewbyidridpic allsetonclicklistenernew onclicklistener override public void onclickview v textview all textview findviewbyidridviewall textview pic textview findviewbyidridpic toastmaketextmainthis view all toastlength shortshow allsettextcolorgetresourcesgetcolorstatelistrcolorgradient green picsettextcolorgetresourcesgetcolorstatelistrcolorwhite pdfsetonclicklistenernew onclicklistener override public void onclickview v textview all textview findviewbyidridviewall textview pic textview findviewbyidridpic toastmaketextmainthis view all toastlength shortshow allsettextcolorgetresourcesgetcolorstatelistrcolorwhite picsettextcolorgetresourcesgetcolorstatelistrcolorgradient green so if i set the setcontentview in the mainclass or mainjava as setcontentviewrlayouttabs instead of setcontentviewrlayoutmain the onclick works what should i do or whats wrong with my code that hinders onclick not to work,['android'] +243745,control sql injection in mvc it is my first time developing using mvc and i want to make it securewhen i use htmlencode it converts the string to the equivalent html stringthe user can enter in the search for example ali or ali and they exist in my database how to control my search and login from sql injection pleasealso any tutorial or best practice to prevent script injection,['asp.net'] +243756,sse simd multiply vector by scalar a common operation i do in my program is scaling vectors by a scalar vs eg 12342 2468 is there a sse or avx instruction to do this other than first loading the scalar in every position in a vector eg mm set ps2 and then multiplyingthis is what i do now m128 scalar mm set ps m128 result mm mul ps vector scalari am looking for something like m128 result mm scale ps vector s,['c'] +243777,intentservice why my onhandleintent is never called i am working with android xml rpc to mount a server for that i am using and intentservice the only problem is that when the server class is launched my onhandleintent which contains the server is never called i have made some research and i found someone who had the same problem he managed solving it by using super class but i am new in programming and did not manage to do what he did linkhere is my codepackage tfermacissbeimport orgxmlsaxattributesimport orgxmlsaxinputsourceimport orgxmlsaxsaxexceptionimport orgxmlsaxxmlreaderimport orgxmlsaxhelpersdefaulthandlerimport orgxmlpullv1xmlpullparserexceptionimport orgxmlrpcandroidmethodcallimport orgxmlrpcandroidxmlrpcserverimport androidappintentserviceimport androidcontentintentimport androidutillogimport androidwidgettoastimport javaioioexceptionimport javaiostringreaderimport javanetmalformedurlexceptionimport javanetserversocketimport javanetsocketimport javautilarraylistimport javaxxmlparsersparserconfigurationexceptionimport javaxxmlparserssaxparserimport javaxxmlparserssaxparserfactorypublic class server extends intentservice public string mydata public string streamtitle path public void oncreate logdserver oncreate public server superserver public void onstart intent intent int startid logdserver started override protected void onhandleintentintent intent logdserver handlingintent try serversocket socket new serversocket8214 xmlrpcserver server new xmlrpcserver logdserver opening on port socket while true socket client socketaccept methodcall call serverreadmethodcallclient string name callgetmethodname if nameequalsnewimage arraylistobject params callgetparams assume add method has two integer params so no checks done mydata string paramsget0 int i1 integer paramsget1 serverrespondclient new object 200 intent new intent this parsefunctionclass startservice intent toastmaketextthis mydata toastlength shortshow logdparsefunction started intent i new intent this bclass iputextra azo mydata iaddflagsintentflag activity new task startactivity i else serverrespondclient null catch ioexception e eprintstacktrace catch xmlpullparserexception e eprintstacktrace,"['java', 'android']" +243822,what is unary used for in javascript i have found some code from underscorejs map collect functionobj iterator context var results if obj null return results if nativemap objmap nativemap return objmapiterator context eachobj functionvalue index list resultsresultslength iteratorcallcontext value index list if objlength objlength resultslength objlength return results i would like to know what if objlength objlength does,['javascript'] +243834,defining a javascript object in console when i type simple objects to chrome javascript console i get an output like thistruetrue1303and so onbut a syntax error occurs when i type objects a 1 b 2 syntaxerror unexpected token arguments array10 length 1 proto array0get message function getter native code get stack function getter native code set message function setter native code set stack function setter native code type unexpected token proto errorwhile i know for sure that this expression could be correctly used in initializing an object becauseobj a 1 b 2 objecta 1b 2 proto objectmaybe it is a silly question but i really want to know the reason why is this happening,['javascript'] +243845,how to upload files to soundcloud using python i am building an application that would record what people say generate an audio file and upload it to soundcloud and get the url of the uploaded track using pythoni used pyaudio to record and generate an audio file a wave filebut i need to know how to upload the file to soundcloud by research i found there is a python wrapper for soundcloud api and with python library poster one can easily upload files to soundcloud how do i do it i have not used this api thing before and i do not find a proper tutorial or a guide to how to make use of it so if anybody can help me with this please answer my question here how to use this soundcloud python api wrapper to upload files to soundcloud using python with the help of the python library poster,['python'] +243854,does removing a script element remove its functions from memory var scripts documentgetelementsbytagnamescriptfor var iscriptslength i scriptsiparentnoderemovechildscriptsisomeone asked me this question and my first thought was no however when you remove the style elements the page automatically updates removing the styling this could be because of how the browser hooks css i think i recall that css updates on every event mouse movement clicks type etci just wanted to confirm that getting rid of the script tag would not get rid of the function that was already created since i am not at a computer where i can testthis also has got me thinking of good practice to help secure code against firebuglike users,['javascript'] +243876,access logging in php i want to log access to any files in the files folder so i can process it with php to generate some statisticsi do not want to write a custom php handler called via rewriterule because i do not want to have to deal with status codes mimetypes and caching headers and file locking issuesi do not have access to the server configuration so i cannot use customlog i do have access to htacessi cannot use xsendfile because it is not enabledi do not have access to the accessloglooking for an authorative answer,['php'] +243899,google analytics authorization in java i am looking for the simplest way of programmatically logging in into analytics and get data google documentation writes and gives examples for oauth 20 which involves a user manually logging into with his google account and then being redirected to my site with authorization but this is not what i want to achieve i am building an automatic tool that needs to have userpass or any other authorization key to be hardcoded and then log in without any user involvement this is a periodic reporting tool i already found something about api key but i cannot find any example how to do that or how to to that with google java librariesi would be very grateful for pointing me into right direction also this may be valuable clue for others how to do it the simplest way and i think logging should be simple,['java'] +243902,alert handling selenium webdriver selenium rc 2180 exception my automation test software for a web application runs on ie firefox chrome and safari and is written using c and selenium webdriver ie firefox chrome selenium rc safari a new error occurred when i upgraded to version 2180 today i am seeing the following exception systeminvalidoperationexception modal dialog present unexpectedalertopeni saw this exception beingn thrown for ie firefox and safari so fari looked up the release documentation and did not find anything that suggests that i should do differently to accept or cancel on alerts is this a bug or is there a new procedure to follow pertaining to alerts,['c#'] +243922,symbol table in python how can we see the symboltable of a python source codei mean python makes a symbol table for each program before actually running it so my question is how can i get that symboltable as output,['python'] +243945,visual studio file corrupted after power outage i had a generic handler c file with an ashx extension open in visual studio 2010 professional when i experienced a sudden power outage now after restarting my computer and reopening the file all i see is a bunch of hex values instead of c codei would really appreciate some help in recovering the contents of the file it is the most important one in the project,['c#'] +243952,using javamail to send from hotmail i have got gmail and yahoo working but not hotmail heres what i have what am i doing wrongprivate string mailhost smtplivecom public hotmailsenderactivitystring user string password thisuser user thispassword password this connects to the actual mailserver securityaddprovidernew comproviderjsseprovider properties props new properties propssetpropertymailtransportprotocol smtp propssetpropertymailhost mailhost propsputmailsmtpstarttlsenable true propsputmailsmtpauth true propsputmailsmtpport 587 propsputmailsmtpsocketfactoryport 587 propsputmailsmtpsocketfactoryclass javaxnetsslsslsocketfactory propsputsmtpstarttlsenable true propsputmailsmtpsocketfactoryfallback false propssetpropertymailsmtpquitwait false session sessiongetdefaultinstanceprops this i have tried port 25 587 without the ssl stuff i have tried port 465 with the ssl stuff the email and password are correct ive hard coded them to be sure i do not receive any errors so whats the problem,"['java', 'android']" +243958,using knockoutjs and server side validation in net mvc2 i am using mvc2whats the recommended way of server side validation of forms when using knockoutcurrently most of my forms are in partial views which have a c viewmodel with validation attributes something like thispublic class somethingviewmodel required public string name get set required public int number get set so when the form gets submitted to the server i get all the model errors and i can return the form with errors which are thisplayed with something like htmlvalidationmessageform mname this is then reloaded into the element that holds the form on the main page so that the user can see the errors this would kill any bindings i had with the form in knockout i would assumei am not really sure how to go about this using knockout,['c#'] +243959,unable to find a userdataimg file for abi armeabi once again i have made the mistake of updating eclipse with the latest android sdktools and have rendered it uselessrunning eclipse on a macwhen i try to create an avd it tells me it is unable to find a userdataimg file for abi armeabi i have read all the similar questions here that tell me to go to runrun configurations and make sure i have the latest arm eabi v7a system image downloaded i have done that i have restarted my machine still no joyfwiw i am not trying to create a 4x emulator just 233 update i can successfully create a 22 emulator with all the same parameters screen size storage card size memory etc as i was trying for 233 also i can successfully create a 4x emulator with those parameters just not 233again i have read all the similar questions doing what i did seems to have solved the problem for several developers running win7 other questions end with someone saying i am downloading the file now but no update as to whether it worked or not in my case after downloading the file i see no change in behaviorthanks for any help,['android'] +243982,some guidance on aspnet mvc 3 architecture required i am an experienced net developer who has primarily been working with webforms i am familiar with mvc but have not used it commercially yet i am currently conducting some selfeducation in this area and am somewhat confused by the differences in opinion on the subject of architecture let me prefix this question with the understanding that there is not a right or wrong answer but i am simply seeking what is an elegant solutioni will start out by saying that i am not using the entity framework or any sort of orm a i would like to directly implement my own business objects and data access code using ado sprocs etc to ensure they are optimal this is a personal preference this is where i am struggling to find consistent information as it appears most information relates to the use of linq to sql or the entity frameworkmy application has been structured with the following projectsweb mvc 3 web applicationmodels class librarythere are only two projects because i am having issues decoupling things this is the root of my questionmy model class library containsa classic business objects with fields and propertiesa repository class for each business object which contains data access code adonet straight forward sqldatareaders etcan interface for each repository classthe issue i have is the dependency between all these layers it does not feel right at all1the business objects should contain methods that implement the business logic so aside from the fields and properties there are methods to implement any required logic2the repository classes execute data access code but know about the business objects this again does not feel right the data access code should sit in its own class library and know nothing about the objects3the controllers in the web layer leverage the repository interfaces but why they should not contain business logic the amodela or business object should the controllers should certainly not contain business logic so again this is not right i donat want business logic in repositories as they are hitting the databasei am struggling to find an elegant architecture for the application just a basic outline of how to implement my own objects my own data access code and ensure the application is loosely coupled can anyone offer me any guidance please,"['c#', '.net']" +243990,how can python subprocesspopen see selectpoll and then later not select module object has no attribute poll i am using the awesome mrjob library from yelp to run my python programs in amazons elastic map reduce it depends on subprocess in the standard python library from my mac running python272 everything works as expectedhowever when i switched to using the exact same code on ubuntu lts 1104 also with python272 i encountered something strangemrjob loads the job and then attempts to communicate with its child processes using subprocess and generates this error file usrlocallibpython27thistpackagesmrjob031py27eggmrjobemrpy line 1212 in build steps steps self get steps file usrlocallibpython27thistpackagesmrjob031py27eggmrjobrunnerpy line 1003 in get steps stdout stderr steps proccommunicate file usrlibpython27subprocesspy line 754 in communicate return self communicateinput file usrlibpython27subprocesspy line 1302 in communicate stdout stderr self communicate with pollinput file usrlibpython27subprocesspy line 1332 in communicate with poll poller selectpoll attributeerror module object has no attribute pollthis appears to be a problem with subprocess and not mrjobi dug into usrlibpython27subprocesspy and found that during import it runs if mswindows snip else import select has poll hasattrselect pollby editing that i verified that it really does set has polltrue and this is correct easily verified on the command linehowever when execution progresses to using popen communicate with poll somehow the select module has changed this is generated by printing dirselect right before it attempts to use selectpoll epollerr epollet epollhup epollin epollmsg epolloneshot epollout epollpri epollrdband epollrdnorm epollwrband epollwrnorm pipe buf pollerr pollhup pollin pollmsg pollnval pollout pollpri pollrdband pollrdnorm pollwrband pollwrnorm doc name package error selectno attribute called poll how did it go awayso i hardcoded has pollfalse and then mrjob happily continues with its work runs my job in aws emr with subprocess using communicate with select and i am stuck with a handmodified standard libraryany advice,['python'] +244051,rsync via php exec with ssh passwordless ssh login if i run the command via php exec it does not work but if i use bash it runs perfect any idea what the problem might be i was thinking maybe it is executing rsync as apache and not allowing ssh loginexecrsync au varwhtmlf1 varwhtmlf2,['php'] +244052,gallery of images using viewpager zoom in imageviews what am i trying to implementa gallery of images using viewpager i choose this option because the smooth transition between images i am using imageview it is nice and quite easy to implement what is my problem exactlyi have been able to implement all this but zoom is not working i can see in logcat how it is printed zoom the code is at the end of the post but the image is not enlarged just a few notes about the following codeimageviewhelperurlseturldrawableimageview img url rdrawableno image i am using urlimageviewhelper to download asynchronously the images from the webapigetlisturls it is an arraylist where i have the image urlsi have tried also using an imageview from rdrawable instead of downloading the imageimport androidcontentcontextimport androidcontentintentimport androidgraphicsmatriximport androidgraphicspointfimport androidosbundleimport androidsupportv4appactionbarimport androidsupportv4appfragmentimport androidsupportv4appfragmentactivityimport androidsupportv4appfragmentmanagerimport androidsupportv4appfragmentpageradapterimport androidsupportv4viewmenuimport androidsupportv4viewmenuitemimport androidsupportv4viewviewpagerimport androidutilfloatmathimport androidutillogimport androidviewlayoutinflaterimport androidviewmenuinflaterimport androidviewmotioneventimport androidviewviewimport androidviewviewontouchlistenerimport androidviewviewgroupimport androidviewviewgrouplayoutparamsimport androidwidgetgalleryimport androidwidgetimageviewimport androidwidgettoastpublic class slide extends fragmentactivity private viewpager mpager public static api api public static int position public static actionbar topbar public static context ctx override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutfragment ctx slidethis position 0 topbar getsupportactionbar get portadas api new api apigeturlsfromapi topbarsetthisplayshowhomeenabledfalse topbarsetthisplayshowtitleenabledtrue mpager viewpager findviewbyidridpager mpagersetadapternew testadaptergetsupportfragmentmanager override protected void onresume todo autogenerated method stub superonresume mpagersetcurrentitemposition static final class testadapter extends fragmentpageradapter public testadapterfragmentmanager fm superfm override public int getcount return apigetlisturlssize override public fragment getitemint position testfragment f new testfragment furl apigetlisturlsgetpositiongeturl fposition position return f public static class testfragment extends fragment string url integer position 0 public testfragment setretaininstancetrue override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate sethasoptionsmenutrue override public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate imageview img new imageviewgetactivity imgsetpadding6 6 6 6 imgsetlayoutparamsnew gallerylayoutparamslayoutparamsfill parent layoutparamsfill parent imageviewhelperurlseturldrawableimageview img url rdrawableno image imgsetontouchlistenernew ontouchlistener private static final string tag slideimageview these matrices will be used to move and zoom image matrix matrix new matrix matrix savedmatrix new matrix we can be in one of these 3 states static final int none 0 static final int drag 1 static final int zoom 2 int mode none remember some things for zooming pointf start new pointf pointf mid new pointf float oldthist 1f override public boolean ontouchview v motionevent event imageview view imageview v dump touch event to log dumpeventevent handle touch events here switch eventgetaction motioneventaction mask case motioneventaction down savedmatrixsetmatrix startseteventgetx eventgety logdtag modedrag mode drag break case motioneventaction pointer down oldthist spacingevent logdtag oldthist oldthist if oldthist 10f savedmatrixsetmatrix midpointmid event mode zoom logdtag modezoom break case motioneventaction up case motioneventaction pointer up mode none logdtag modenone break case motioneventaction move if mode drag matrixsetsavedmatrix matrixposttranslateeventgetx startx eventgety starty else if mode zoom float newthist spacingevent logdtag newthist newthist if newthist 10f matrixsetsavedmatrix float scale newthist oldthist logdtag zom scale matrixpostscalescale scale midx midy break viewsetimagematrixmatrix return true indicate event was handled show an event in the logcat view for debugging private void dumpeventmotionevent event string names down up move cancel outside pointer down pointer up 7 8 9 stringbuilder sb new stringbuilder int action eventgetaction int actioncode action motioneventaction mask sbappendevent action appendnamesactioncode if actioncode motioneventaction pointer down actioncode motioneventaction pointer up sbappendpid append action motioneventaction pointer id shift sbappend sbappend for int i 0 i eventgetpointercount i sbappendappendi sbappendpid appendeventgetpointeridi sbappendappendint eventgetxi sbappendappendint eventgetyi if i 1 eventgetpointercount sbappend sbappend logdtag sbtostring determine the space between the first two fingers private float spacingmotionevent event float x eventgetx0 eventgetx1 float y eventgety0 eventgety1 return floatmathsqrtx x y y calculate the mid point of the first two fingers private void midpointpointf point motionevent event float x eventgetx0 eventgetx1 float y eventgety0 eventgety1 pointsetx 2 y 2 return img override public void oncreateoptionsmenumenu menu menuinflater inflater override public boolean onoptionsitemselectedmenuitem item return superonoptionsitemselecteditem i have already tried the following tutorial with no successhow to use multitouch in android 2 part 6 implementing the pinch zoom gesture,['android'] +244053,python set in operator uses equality or identity class aobject def cmp self print cmp return object cmp self def eq self rhs print eq return truea1 aa2 aprint a1 in seta1print a1 in seta2why does first line prints true but second prints false and neither enters operator eqi am using python 26,['python'] +244058,mongoose js queries all coming back null or empty i am trying to create a simple mongoosejs example program that gets a list of items from a collection and it is coming back empty every time here is the codevar mongoose requiremongoose schema mongooseschemavar sampleschema new schema samplefield stringvar db mongooseconnectmongodblocalhost27017testvar samplecollection mongoosemodelsamplecollection sampleschemasamplecollectionfind function err items consolelogitems outputs consolelogerr outputs null itemsforeach functionitem consolelogitem does not reach this code i have a default instance of mongodb running and this is what i have entered in the shell use test dbsamplecollectionsavesamplefield hello dbsamplecollectionsavesamplefield goodbye dbsamplecollectionfind id objectid4f28944b38b59225012109da samplefield hello id objectid4f28945138b59225012109db samplefield goodbye any idea why my code does not return any datathanks for your helpdave,['javascript'] +244075,is there any way to simulate some gae server error are there ways to test my error handlers setup in the appyaml file especially the error code over quota,['python'] +244089,how to compare that sequence of doubles are all approximately equal in java i have a method in java that returns a double number and i want to compare every double number that is returned every time i call the methodsay 5 times so that i can conclude that the number returned is almost the same every timehow can i do this,['java'] +244131,uitableview load data on scroll in my app i am getting the data from the webservice and i have to thisplay it in uitableviewbut the condition here is i have to thisplay only 10 records initiallythen once the user scroll down i have to load more recordsi tried searching it but did not get any useful answeri agree that i will use voidtableviewuitableview tableview willthisplaycelluitableviewcell cell forrowatindexpathnsindexpath indexpath to thisplay the valuebut how will i fetch only 10 records from the service and then other record based on scrollplease provide some pointers or sample codethanks,['iphone'] +244137,check if a folder exist in a directory and create them using c how can i check if directory c contains a folder named mp upload and if it does not exist create the folder automaticallyi am using visual studio 2005 c,"['c#', 'asp.net']" +244155,get position in listview i use listview to show several itemsmy rowxml as belowtextview androidtexttextandroidididtvviewrowandroidlayout widthwrap contentandroidlayout heightwrap contenttextviewbutton androidtextclick meandroidididbtntoclickandroidlayout widthwrap contentandroidlayout heightwrap contentandroidonclickmyclickbuttonand i define myclick in activity as belowpublic void myclick view v linearlayout vwparentrow linearlayoutvgetparenthow to get the positionhow to know the position which buttom be clickedthe position mean same as the method onlistitemclicksoverrideprotected void onlistitemclicklistview l view v int position long id,['android'] +244183,sdwebimage building for archive thistribution i am using the sdwebimage open source project for loading images asynchronouslyi can build run for the simulator as well as for my local devicehowever when i try to build for thistribution ie archive the compiler does not seem to understand what the header file isimport uiimageviewwebcacheh no such file or directoryi pretty much followed the instructions with relative ease described here ongithubcomrssdwebimagei knew things were going way too smoothilyeasily to be trueoddly i have never really faced an issue that is exclusive to archivinganybody tried archiving with sdwebimage before updated i updated based on comment below now i am getting the following error while archive buildingarmappledarwin10llvmgcc42 pollbuildproductspathreleaseiphoneoslibsdwebimagea no such file or directory command developerplatformsiphoneosplatformdeveloperusrbinllvmgcc42 failed with exit code 1the strange thing is that i have the sdwebimagea file in my project there is actually 2 one that i copied and included and the 2nd one from the sdwebimage project itself update 2 upon further investigation my sdwebimage project is not getting built when i archive the a file is red but any other build type works fine i looked everywhere and it seems like the sdwebimage project has the thistribution configurations not sure what else could be the issue here,['iphone'] +244194,how to retrieve the activity requested by an intent say i have an intent like this intent intent new intentcontext myactivityclassi then want a method that will return true for the following boolean found intentgetsomemethodtoretrieveactivity instanceof myactivitybasically is there any way to find out what activity the intent resolves toany ideaseditperusing the src i can see i can get the class name like this intentgetcomponentgetclassnamewhich will return commypackagemyactivity which is close but i would like to use instanceof,['android'] +244222,uitableview run code when tablefooterview is thisplayed i am using the uiview tablefooterview of in my uitableview to show a loading more label at the bottom of my table when the uiview in tablefooterview is shown i need to start some lazy download of content how do i know when the tablefooterview is thisplayed,"['objective-c', 'ios']" +244238,android fileinputstream read txt file to string any experts available to help me in my android main activity i am trying to save a string to a file and then retrieve it if the user has set it before was not able to find any examples close to what i am doing i would most appreciate any help here is my test case that crashesstring teststring worksstring readstringoverridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain fileoutputstream fos try fos openfileoutputtesttxt contextmode private foswriteteststringgetbytes fosclose catch filenotfoundexception e eprintstacktrace catch ioexception e eprintstacktrace file file getbasecontextgetfilestreampathtesttxt if fileexists fileinputstream fis try fis openfileinputtesttxt fisreadreadstringgetbytes fisclose catch ioexception e eprintstacktrace txtdatesettextstringvalueofreadstring else more code,"['java', 'android']" +244262,atomically appending a line to a file and creating it if it does not exist i am trying to create a function for purposes of loggingappendpath datathatcreates file if it does not exist andatomically appends data to itit has tosupport high concurrencysupport long strings andbe as performant as possibleso far the best attempt isfunction appendfile data ensure file exists just opening it with w or a might cause 1 process to clobber anothers fp fopenfile x if fp fclosefp append lock strlendata 4096 assume pipe buf is 4096 linux fp fopenfile a if lock flockfp lock ex throw new exceptioncannot lock file file fwritefp data if lock flockfp lock un fclosefpit works ok but it seems to be a quite complex is there a cleaner builtin way to do it,['php'] +244282,intentextra email not populating the to field i am trying to use an intent to send an email from my application but the to field of the email will not populate if i add code to fill in the subject or text they work fine just the to field will not populatei have also tried changing the type to textplain and texthtml but i get the same problem can anyone help pleasepublic void email intent emailintent new intentintentaction send emailintentsettypemessagerfc822 set the email recipient string recipient getstringrstringintegralemailaddress emailintentputextraandroidcontentintentextra email recipient let the user choose what email client to use startactivityintentcreatechooseremailintent send mail using the email client i am trying to use is gmail,['android'] +244320,ios facebook status location i am confused as to how i use a location in a users status i see there is a place field but i dont know how to use it the instructions just say an object it does not specify at all what object it wants and in what format it wants can anyone give me a hand on posting a status with a location on itthis is my code now voidpostwithmessagensstring message imageuiimage image locationcllocation location nsmutabledictionary params nsmutabledictionary dictionary nsstring path feed params setobjectstatus forkeytype if message message isequaltostring params setobjectmessage forkeymessage if image path mephotos params setobjectphoto forkeytype nsdata imagedata uiimagepngrepresentationimage params setobjectimagedata forkeysource if location stole this from ios hackbook that facebook wrote but it was not helpful nsstring centerlocation nsstring alloc initwithformatff locationcoordinatelatitude locationcoordinatelongitude params setobjectcenterlocation forkeycenter facebook requestwithgraphpathpath andparamsparams andhttpmethodpost anddelegateself,['ios'] +244382,member function template with the number of parameters depending on an integral template parameter i have the following class templatetemplateclass t unsigned nclass myclasswhere t is some type n number of components it is possible to initialize the class using myclassa1 a2 a3 where the number of arguments is equal to ni want to add a member function template let us name it foo of myclass that would meet the following requirementsit is templated by another type t2 ie templateclass t2 void fooit accepts enough data to construct myclasstn but not less and not more violating this results in a compiletime errorit deduces t2 from the types of the parameters ie i want that it would be possible to call fooa1 a2 a3 or fooa1 a2 a3 or similar without typing double or myclassdoublen every timeis there a way to implement the function so that the above requirements are satisfiedi have already thought about andor tried the following solutions1 the obvious onetemplateclass t2void foomyclasst2 n arg afoo123 compiletime errorcannot work in principle because braced initializer lists are a nondeduced context thus they cannot deduce any types that is quite unfortunate i would be very happy if this worked2 initializer listcannot work in principle because it cannot check the number of arguments at compiletime3 variadic template magicsomething like the function below would be neattemplateclasst2 class stdenable ifsizeoft2 n inttype 0void foot2 argsfoo123however i could not get it to work t2 still could not be deduced maybe someone knows why i used gcc47 20120121 snapshot4 the ugly oneessentially this is the same as the above one just expanded into several overloads for different n i would better reimplement myclass as a set of specializations for different ns than to use this onetemplateclass t2 class stdenable ifn 1 inttype 0void funt2 a1 if and 1templateclass t2 void funt2 a1 t2 a2 if and 2templateclass t2 void funt2 a1 t2 a2 t2 a3 if and 3,['c++'] +244385,difference between google api libraries googleapidotnetclient vs googlegdata what is the difference between the google apis client library for net googleapidotnetclient and net library for the google data api googlegdata as they pertain to the google analytics api,"['c#', '.net']" +244402,android jni apk packing i have implemented a jni android application this application requires a few additional shared libs to be packed as part of the apk using ecplise i have added these libs to the projects libsarmeabi folderhowever when launching the application through the integrated debugger my added shared libs are removed from the armeabi folderhow can i prevent these additional libs from being removedhow can i make sure the additional required sos are packed in the apk,['android'] +244414,fprintf and ctime without passing and from ctime i have an issue with inserting time in a text file i use the following code and i get 214313105 wed feb 01 204232 2012 which is normal but what i want to do is place the time before the numbers for example like wed feb 01 204232 2012 214313105 however i cant do so cause when i use the fprintf with ctime function before fprintf the numbers it recognizes the and within ctime and so it changes line 1st and then printing the numbers it goes like wed feb 01 204232 2012 214313105which is something that i dont want how can i fprintf the time without swiching to the next line in the text thanks in advancefprintffile for i0i6i bufferilucky numberrand491 range 149 for j0jij if bufferjlucky number i itoa bufferidraw no10 fprintffilesdraw no if i5 fprintffile fprintffile sctimet,['c'] +244418,emacs pythoninferior shell not showing prompt after matplotlib show command so i have been experimenting with numpy and matplotlib and have stumbled across some bug when running python from the emacs inferior shellwhen i send the py file to the shell interpreter i can run commands after the code executed the command prompt appears fine however after i invoke a matplotlib show command on a plot the shell just hangs with the command prompt not showing pltplotxu k1matplotliblinesline2d object at 0x04a9a358 pltshowi am running the traditional cpython implementation under emacs 233 with fabian gallinas python pythonel v 0231 on win7 a similar question has been raised here under the ipython platform running matplotlib or enthoughtmayavimlab from a pyshell inside emacs on windowsupdate i have duplicated the problem on a fresh instalation of win 7 x64 with the typical python 272 binaries available from the python website and with numpy 161 and matplotlib 110 on emacs 233 and 234 for windowsthere must be a bug somewhere in the emacs shell,['python'] +244436,how to convert a decimal into time eg hhmmss i am trying to take a decimal and convert it so that i can echo it as hours minutes and secondsi have the hours and minutes but am breaking my brain trying to find the seconds been googling for awhile with no luck i am sure it is quite simple but nothing i have tried has worked any advice is appreciatedhere is what i havefunction converttimedec hour floordec min round60dec hourlike i said i get the hour and minute without issue just struggling to get seconds for some reasonthanks,['php'] +244445,css outside border i want to be able to draw a border outside of my div so if my div is say 20px by 20px i want a 1px border outside of this so in essence i get a div 22x22px large i understand that i can just make the div 22x22 to start with but for reasons i have i need the borders to be on the outsidecss outline works but i want only borderbottom or bordertop thingy so something like outlinebottom which does not work is what i wantis there a way to do thisthanks,['css'] +244448,use of typeid to make a comparison between derived classes i have a vector of pointers to derived objects insert by the user so i guess the correct term is known only in runtimevectorperson vectthe derived classes are male and femalei want to make an iteration on the vector to select only the female objects and call the copyconstructor of thati thought 3 solutionsto use a flag to use typeid to insert a calling to the copy constructor in the default constructor of female so every time the user creates one automatically create the twini do not like the first option in the case of many kind of derived classesi do not like the third option too because would cause a problem of relationship the world knows every female but the female cannot know the worldso i should use the second optionexampletypeidvectatitypeidfemaleis this expression correctis there another way to outline the problem,['c++'] +244465,how to load json data with jquery php and mysql i want to create a dynamic dropdown menu that one select is based on the value of another select i tried so many times and failed i have the code as follows anyone can help me to find out what the problem istemplatescript typetextjavascript function getselectval grouptypeschangefunction getselectval function getselectval getjsonphp echo url forgroup utilizationgroupmodification grouptypesgrouptypesvalfunctiondata var groups groups optiongroupsremove eachjsonfunctionindexarray var option option valuearrayidarraytitleoption selectappendoption scriptgrouptype select idgrouptypes php foreachgrouptypes as type php echo option value typename typename option php endforeach selectbr br resultspan idlistofgroupsspanbr group select namegroup idgroupsselectbr another file for returning database returned valueifisset getgrouptypes grouptypes getgrouptypes query select gname from groups g inner join group types gt ongtid ggroup type id and gtname groups dbgetresultsforqueryquery grouptypes echo json encodegroups,"['php', 'javascript', 'jquery', 'mysql']" +244498,is there a way to write these ifs nicer i need to write these four ifs in python notice what it does is changing between four possible states in a loop 10 01 10 01 and back to firstif dx dy 10 dx dy 0 1if dx dy 0 1 dx dy 1 0if dx dy 1 0 dx dy 0 1if dx dy 0 1 dx dy 1 0can anyone suggest me a betternicer way to write this,['python'] +244524,should super loadview be called from loadview or not in programming ios 4 by matt newburg he statesto provide a uiviewcontroller with a view manually implement its loadview method you must not call superin the ios 5 developers cookbook by erica sadun she statesthe loadview method allows you to set up the screen and layout any subviews make sure to call super loadview whenever you inherit from a specialized subclass such as uitableviewcontroller or uitabbarcontrollerthis to me at least is confusing,['ios'] +244543,command line input working incorrectly okay so i made this program to help me out with my homework and because i wanted to improve my c expertise everything compiles fine when i do gcc filec lm but when i run it with a number at the command line as an argument my program only returns 70include stdiohinclude mathhinclude stdlibhdouble tempdouble hour double t 31412hour double c cosdoublet double temp 13 c 57 return temp int main int argc char argv double temperature tempdoubleatolargv0 printffn temperature,['c'] +244545,user friendly urls mod rewrite and php redirections so far i have done thisrewritebase rewritecond request filename frewritecond request filename drewriterule indexphpload1 qsalthen on my index page in the root directory i am using php to determine which page to load swap to variables load getload home page if load load includehomephp exit dashboard if load dashboard includedashboardphp exit about if load about includeaboutphp exit username data array arrayusername load select account connectprepareselect from users where username username select account executedata array account amount select accountrowcount if account amount 0 includeprofilephpnameload exit redirect to 404 if there are no results include404php exiteverything so far is working but users can upload photos to a gallery and i want them to be viewed like sowmysitecomusernamegallerybut if you were to type that as the url the rewrite reads usernamegallery as one section which means load usernamegallery which would give me a 404there is probably a better solution to getting the desired results but i am not too good with the htaccess and rewriting i would like to add that i like this rewrite too since i have subdirectories called signup and signin which both have subdirectories in them too but if i go to the urlwmysitecomsignupwmysitecomsigninit ignores the rewrite and goes to the directory instead of running it through the load statements which is what i wantalso to note on registering an account any username which matches strings such as dashboard or about etc it does not allow them to use it this stops usernames and the load ifelse statements and their includes being mixed up etceditanother thing i forgot to note is since they can call the gallery whatever they like it needs to do a search to see if that gallery exists so for examplewmysitecomusernamemyfirstalbumit would first need to check the username exists then check the album exists then thisplay it if it does or 404redirect to wherever if it does not so basically both parametersqueries will be dynamic not only that but then individual photos within that album need to work the same for examplewmysitecomusernamemyfirstalbummypicturei hope that makes sense,['php'] +244573,1evalthis vs evalthis in javascript i start to read javascript pattern some codes confused mevar global function return this 1 evalthishere are my questionsq1 1 eval evalwhy it works how q2 why not justvar global function return this evalthisor var global function return thiscould anyone tell me thank you,['javascript'] +244587,how to upload image from gallery in android i want to upload image from my phone gallery into my application in my application there is button named upload when i click buttonit should move to gallery and in gallery if i select image that selected image should thisplay as thumbnail in applicationi want to upload 10 images from gallery in my application,['android'] +244604,undefined local variable or method confirmed at for user i am using rails 3 there is a possible duplicate here but it did not solve my problem neither did any other solutionmy migration is as followsclass addconfirmabletodevise activerecordmigration def change change tableusers do t tconfirmable end add index users confirmation token unique true endendi do have devise confirmable added in user modelmy rake dbmigrate gives no output and my sign up page gives the errorundefined local variable or method confirmed at for useranybody has a clue,['ruby-on-rails'] +244605,warning ipad icon72png icon dimensions 0 x 0 i got this problem warning ipad icon72png icon dimensions 0 x 0 do not meet the size requirements the icon file must be 72x72 pixels in png format 19014 when build for archive the ipad only apphave checked my icon is 72x72 pixels also checked on infoplist file the key cfbundleiconfiles already there before this have no problem to submit the app after rejected by app review i want to resubmit no changes has been made on my xcode project but the error appear does it because of i have upgraded to mac osx lion 1073 i just update to mac osx lion 1073 before resubmit the appwonder why does the warning says icon dimensions 0 x 0please help me thanks,"['objective-c', 'ios']" +244612,rails postgresql ssl decryption failure i have an app running on my production server that uses the pg gem for talking to a postgres database postgres is running on the default port and is behind a firewall so it is not accessible from anything but localhost i have not configured postgres to do anything sslrelatedi am accessing the rails app via ssl and the certificate is signed for another domain so the first time you hit it a certificate error is presentedbut that is the only thing sslrelated that is weirdand yet i am seeing this intermittently in my rails logs accompanied by a 500 error in the browser when it happensstarted get adminpages for x at 20120202 015203 0500processing by pagescontrollerindex as htmlcompleted 500 internal server error in 4msactiverecordstatementinvalid pgerror ssl error decryption failed or bad record mac select pages from pages appcontrollerspages controllerrb36in indexwhat the hell,"['sql', 'ruby-on-rails', 'ruby']" +244621,how to reduce netty garbage production i have network application that handles about 40k msgsec written using netty framework and i want to reduce the number of garbage collector calls while profiling i found that there is significant amount of byte instances and i suspect that it comes from this part of code public class messagehandler extends simplechannelhandler public void messagereceivedchannelhandlercontext ctx final messageevent e channelbuffer message channelbuffer egetmessageis it possible to force netty to reusepool channelbuffers somehow to prevent it to construct them every time,['java'] +244653,androidjava how to sort a list of objects by a certain value within the object im trying to sort through an arraylist of objects by a particular value within the object what would be the best approach to do such a thing should i use collectionssort with some kind of comparator im trying to sort a list of objects by a float value they hold in one of the variableseditthis is what i have so farpublic class customcomparator implements comparatormarker override public int comparemark o1 mark o2 return o1getthistancecomparetoo2getthistance the error states cannot invoke comparetodouble on the primitive type doubleis it because a comparator cant return anything other than a certain type,"['java', 'android']" +244658,how do i add a resize event to the window in a view using backbone i have been trying to attach a handler to the resize event in one of my backbone views after doing some research i have thiscovered that you can only attach events to the views element or its descendantsthis is an issue for me because the visual effect i am trying to achieve is not possible using pure css and requires some js to set the dimensions of the content area element based on the window minus the header elementif you are having trouble visualizing what i am trying to do imagine a thin header and a content area which must occupy the remaining space with no css background trickery i have attached a code example if you have any other pointers i would also love to hear themdefine jquery underscore backbone mustache textsrccommonresourcehtmlbasehtml function backbone mustache basetemplate var baseview backboneviewextend el body events resize window resize render function var data var render mustacherenderbasetemplate data thiselhtmlrender thisresize resize function var windowheight windowheight var headerheight thiselfindheaderheight thiselfindapplicationheight windowheight headerheight return new baseview any assistance would be greatly appreciated by my facethankyoualex,['javascript'] +244665,can i write a css selector selecting elements not having a certain class i would like to write a css selector rule that selects all elements that do not have a certain class for example given the following htmlhtml classprintable body classprintable h1 classprintableexampleh1 nav some menu links nav a hrefjavascriptvoid0 onclickjavascriptselfprintprint mea p classprintable this page is super interresting and you should print it p bodyhtmli would like to write a selector that selects all elements that do not have the printable class which in this case are the nav and a elementsis this possiblenote in the actual html where i would like to use this there are going to be a lot more elements that do not have the printable class than do i realize it is the other way around in the above example,"['html', 'css']" +244677,login logout issue with facebook ios sdk we have got sruck in the ios facebook login logout issue when i login to facebook using my application it will prompt for user permission with login and cancel button but this screen appears only on the very first time ie once we logged in using safari or the app and even if we logged out from facebook application the screen prompting for user permission thisplays only an ok button it doesnt allow to sign in as a different user why the screen with login and cancel button not thisplaying each time the application launches i tried by deleting cookies and removing nsuserdefaults but no luckthe problem is after logout i am unable to login to the facebook as another user it still shows as the same useri am calling the below logout function in sdkvoidlogoutidfbsessiondelegatedelegate selfsessiondelegate delegate accesstoken release accesstoken nil expirationdate release expirationdate nil nshttpcookiestorage cookies nshttpcookiestorage sharedhttpcookiestorage nsarray facebookcookies cookies cookiesforurl nsurl urlwithstring for nshttpcookie cookie in facebookcookies cookies deletecookiecookie if selfsessiondelegate respondstoselectorselectorfbdidlogout sessiondelegate fbdidlogoutalso in fbdidlogout delegate function i removed all nsuserdefaults objects nsuserdefaults defaults nsuserdefaults standarduserdefaultsif defaults objectforkeyfbaccesstokenkey defaults removeobjectforkeyfbaccesstokenkey defaults removeobjectforkeyfbexpirationdatekey defaults synchronizeregrdsshihab,['ios'] +244690,bind temporary to nonconst reference rationalei try to avoid assignments in c code completely that is i use only initialisations and declare local variables as const whenever possible ie always except for loop variables or accumulatorsnow iave found a case where this doesnat work i believe this is a general pattern but in particular it arises in the following situationproblem descriptionletas say i have a program that loads the contents of an input file into a string you can either call the tool by providing a filename tool filename or by using the standard input stream cat filename tool now how do i initialise the stringthe following doesnat workbool const use stdin argc 1stdstring const input slurpuse stdin static caststdistreamstdcin stdifstreamargv1why doesnat this work because the prototype of slurp needs to look as followsstdstring slurpstdistreamthat is the argument i nonconst and as a consequence i cannot bind it to a temporary there doesnat seem to be a way around this using a separate variable eitherugly workaroundat the moment i use the following solutionstdstring inputif use stdin input slurpstdcinelse stdifstream inargv1 input slurpinbut this is rubbing me the wrong way first of all itas more code in slocs but itas also using an if instead of the here more logical conditional expression and itas using assignment after declaration which i want to avoidis there a good way to avoid this indirect style of initialisation the problem can likely be generalised to all cases where you need to mutate a temporary object arenat streams in a way illdesigned to cope with such cases a const stream makes no sense and yet working on a temporary stream does make sense,['c++'] +244710,appropriate way to subclass guavas immutableset i have a class along the lines of class receipt private setorder orders public receiptsetorder orders thisorders immutablesetcopyoforders this has served me well however because of some typeerasure persistence issues i am facing i would like to now introduce a form ofclass orderset extends setorder obviously i cannot extend setorder as it is an interface i would like to keep my implementation as immutable however i cannot extend immutablesetorder as the docs statenote although this class is not final it cannot be subclassed outside its package as it has no public or protected constructors thus instances of this type are guaranteed to be immutablei could use composition giving orderset a backing collection of immutableset and delegate all the set methods to it however this seems overkillis there another way i can achieve a nongeneric subclass here,['java'] +244725,how to cast object in python i have two classes let us call them working and returnstatement which i cannot modify but i want to extend both of them with logging the trick is that the workings method returns a returnstatement object so the new mutantworking object also returns returnstatement unless i can cast it to mutantreturnstatement saying with code these classes cannot be changedclass returnstatementobject def actself print i am a returnstatementclass workingobject def doself print i am working return returnstatement these classes should wrap the original onesclass mutantreturnstatementreturnstatement def actself print i am wrapping returnstatement return returnstatementactclass mutantworkingworking def doself print i am wrapping working this is not working i would need that casting working return mutantreturnstatement workingdors mutantworkingdo i can use mutantworking just like workingprint just to separate outputrsact this must be mutantreturnstateact i need the overloaded methodthe expected resulti am wrapping workingi am workingi am wrapping returnstatementi am a returnstatementis it possible to solve the problem i am also curious if the problem can be solved in php too unless i get a working solution i cannot accept the answer so please write working code to get accepted,['python'] +244728,mono develop assembly systemdeployment not found i have some simple c application single form originally written in vs on win now i have opened it with mono develop and i got that warning and errorwarning assembly systemdeployment not found make sure that the assembly exists in thisk if the reference is required to build the project you may get compilation errors tringfiscalprimjererror the compiler appears to have crashed check the build output pad for details tringfiscalprimjerany idea how to compile this app under linux,['c#'] +244735,how to convert calendar to javasqldate in java calendar calstring sql insert into ttable dt values dt is a datetime field in ttablepreparedstatement stmt connectionpreparestatementsqlstmt setdate1cal not workingstmtexecutestmtclosei would like to convert cal to a date type to insert into table,"['java', 'sql']" +244741,jackson how to prevent field serialization i have an entity class with a password fieldclass user private string password setter getteri want this field to be skipped during serialization but it should still be able to deserialize this is needed so that the client can send me a new password but is not able to read the current onehow do i accomplish this with jackson,['java'] +244759,where can i find a list of escaped characters in msil string constants i have written a program in c that reads and manipulates msil programs that have been generated from c programs i had mistakenly assumed that the syntax rules for msil string constants are the same as for c but then i ran into the following situationthis c statementstring s do you wish to send anywaygets compiled into among other msil statements thisil 0128 ldstr do you wish to send anywayi was not expecting the backslash that is used to escape the question mark now i can obviously take this backslash into account as part of my processing but mostly out of curiosity i would like to know if there is a list somewhere of which characters get escaped when the c compiler converts c constant strings to msil constant stringsthanks,"['c#', '.net']" +244769,fast algorithm to find the x closest points to a given point on a plane i would like to find a fast algorithm in order to find the x closest points to a given point on a plane we are actually dealing with not too many points between 10 and 10 but i need the x closest points for every of these points where x usually will be between 5 and 20i need to write it in ca bit more context about the use case these points are coordinates on a map i know this means we are not exactly talking about a plane but i hope to avoid dealing with projection issues in the end points that have many other points close to them should be thisplayed in red points that have not too many points close to them should be thisplayed green between these two extremees the points are on a color gradient,['c#'] +244808,wcf test client cannot add service cannot obtain metadata can anyone tell me why i get this error when i try to add my serviceerror cannot obtain metadata from httpmyservermyapp if this is a windows r communication foundation service to which you have access please check that you have enabled metadata publishing at the specified address for help enabling metadata publishing please refer to the msdn documentation at wsmetadata exchange error uri httpmyservermyapp metadata contains a reference that cannot be resolved httpmyservermyapp the remote server returned an unexpected response 405 method not allowed the remote server returned an error 405 method not allowedhttp get error uri httpmyservermyapp there was an error downloading httpmyservermyapp the request failed with http status 403 forbiddenupdate i have the following endpoint alreadyendpoint addressmex bindingmexhttpbinding namemetadata contractimetadataexchange i also have the service behaviors set servicebehaviors behavior namemybehavior servicemetadata httpgetenabledtrue servicedebug includeexceptiondetailinfaultsfalse behavior servicebehaviors,['c#'] +244810,address of this i try to find address of this pointer but this code is showing a strangeerrorinclude iostreamusing namespace stdclass base public void test void address of this this coutaddress of thisendl int main base k ktest return 0 error nonlvalue in unary can you explain this error also point that what is illegal in taking address of this,['c++'] +244814,how to find a 2 unpaired elements in array you have an array with n2k2 elements where 2 elements have not pair example for 8 elemets array 1 2 3 47 3 1 2 0 47 and 0 have not pair in array if i have array where only 1 element hast pair i solve this problem with xor but i have 2 unpair elements what can i do solution could be for a on time performance and for o1 additional memory,['c'] +244832,css transform translate moves postionfixed inner div the following example shows a div inside a div the inner div is position fixedwhen i add transform translate0px 0pxto the outer div the inner div will no longer behave as fixedlink to the example so does translate actually change the viewport can anyone help me to keep the inner div fixed using css when the outer div has a translate stylethank youfelix,['css'] +244835,openid how to develop a provider currently i am developing some infrastructure and i have implemented my own restful authentication mechanismnow i have in mind that maybe i should not go this way and use an industry standard so interoperability with my project could be trivial and easier to understand in terms of authentication and authorizationafter checking some articles googling everywhere and reading some qa here in stackoverflow i do not find how to be an openid provider i am not talking about authenticate users using google windows live facebook connect and so i want to develop an openidenabled system so if some want to register into my services they will do in my own domain actually my question is can anyone become an openid provider and is dotnetopenauth a library to develop this protocol in your own infrastructure thank you,"['c#', '.net']" +244866,jul to slf4j bridge i am currently observing that a 3rd party library namely restfb is using javautillogging and i am seeing those logs end up in stdout even though i do not have an slf4j console appender configured in my logbackxml i also have the jultoslf4j bridge in my classpath does the jultoslf4j bridge only log to the appenders configured by logback when the bridge is installed or does it also log to stdout,['java'] +244892,simple gui toolkits for use with clojure the long and short of this question is which gui tool kits create very simple uis and are easy to use work with clojure here are further details to narrow down my questioni want to create very simple gui applications that will run on windows without investing in a huge gui design effort for example our personnel department gets an insurance bill from our vendor for a number of subscribers and wants to audit that information against what their local insurance application thinks the subscribers arei would like to write these applications in clojure and also take advantage of simple gui packages which is the simplest tool that can be used with clojure to create a primitive ui by primitive ui i mean something like an old windows 31 16bit modal dialog box,['java'] +244904,android portait video orientation wrong in videoview i capture a new video in portrait orientation on an android device like thisintent intent new intentandroidprovidermediastoreaction video capture startactivityforresultintent 1886and it gives me this file mntsdcarddcimcameravideo20120202104548mp4then i play it like thisprivate videoview videoview videoview findviewbyidridvideoviewstring videourl mntsdcarddcimcameravideo20120202104548mp4videoviewsetmediacontrollernew mediacontrollerthis videoviewsetvideouriuriparsevideourlvideoviewstartheres my layout filexml version10 encodingutf8relativelayout xmlnsandroidandroidlayout widthfill parentandroidlayout heightfill parent videoview androidididvideoview androidlayout widthfill parent androidlayout heightfill parent androidlayout centerinparenttrue relativelayoutwhen i play it in the standard android gallery the orientation is correct but when i play the video in the videoview above it is rotated 90 degrees landscape works great the only problem are portrait videoshow can i rotate this video in the videoviewalso how can i programmatically determine the orientation,['android'] +244943,how do hashsets in java work possible duplicatehow does java hashmap work can someone explain to me how hashsets in java work and why they are faster than using arraylists,['java'] +244944,websockets tutorial on aspnet is there a simple down to earth sampleexampletutorial for websockets server and client implementation in aspnet 40 to get me started i know this question has been asked but it has not been answered properly there is a lot of stuff about client side but cannot find a simple explanation about serverside in aspnetthanksupdatei found this tutorial but cannot make it work the connection closes right after attempting to connect any one can make it work,['asp.net'] +244946,ios copy directories including subdirectories i am working with ios document folder called temp that allocates subdirectories that contain files dowloaded from remote url now i need to copy temp directory and all its contents to main folder overwrite existing that was previously created i know how to handle files but how to copy whole directory thank you,"['iphone', 'objective-c', 'ios']" +244948,safari for ipad not reporting line numbers on javascript errors i am using ipad 2 with ios 5 to develop a web applicationi have enabled the developer console to get logs but when javascript error occurs it does not include corresponding line numbersince the web application handles touch and gesture events i cannot test them on desktop version of the browserany help will be appreciated,['javascript'] +244951,connecting two udp clients to one port send and receive i tried the suggestion from this question with very little successplease any help will be greatly appreciatedhere is my codestatic void mainstring args ipendpoint localpt new ipendpointipaddressany 60 udpclient udpserver new udpclientlocalpt udpserverclientsetsocketoption socketoptionlevelsocket socketoptionnamereuseaddress true udpclient udpserver2 new udpclient udpserver2clientsetsocketoption socketoptionlevelsocket socketoptionnamereuseaddress true udpserver2clientbindlocalpt exception here,['c#'] +244981,how can i position the windows position on startup to the right side of the users screen i am currently creating a sidebarlike wpf application in c when a user starts the application i would like the window to automatically position it is self to the side of the users screen i have tried a few methods and google searches but have not found any helpheres an example of what i am trying to dohow can i efficiently go about achieving something like thisdknaacki tried this codeprivate void window loadedobject sender routedeventargs e thisleft systemwindowsformsscreenprimaryscreenworkingarearight thiswidth thistop 0 thisheight systemwindowsformsscreenprimaryscreenworkingareaheight and got the following errors error 1 the type systemdrawingsize is defined in an assembly that is not referenced you must add a reference to assembly systemdrawing version40 cultureneutral publickeytokenb03f5f7f11d50a3a cuserstestdocumentsexpressionblend 4projectswindbar prototype 1windbar prototype 1mainwindowxamlcs 32 13 windbar prototype 1and error 2 systemdrawingsize does not contain a definition for width and no extension method width accepting a first argument of type systemdrawingsize could be found are you missing a using directive or an assembly reference cuserstestdocumentsexpressionblend 4projectswindbar prototype 1windbar prototype 1mainwindowxamlcs 32 78 windbar prototype 1any help,['c#'] +244991,cannot get site root url in asp mvc i need to get site root url in razor page in javascript codevar siterooturl urlcontentbut all i get from this is,['javascript'] +244993,jquery ui slider value returned from slide event on release is different from change value i have a jquery ui sliderdivsliderslider range true step 250 min 10 max 50 values 1050 change functionevent ui consolelogthisslidervalues 0thisslidervalues 1 slide functionevent ui consolelogthisslidervalues 0thisslidervalues 1 for some odd reason when releasing the slider mouseup the value changes slightly from what it was the slide event is returning something different than what the change event is anyone have any ideas what might be causing this and how i could solve iti am going to have a pretty intense operation in the callback for the change event meaning i cannot just use sldie but also need to show the values of the slider live so i cannot use just one or the otherheres a fiddle with this oddity in action thanks in advance,"['javascript', 'jquery']" +245018,multiple moq itis matching arguments with moq is it valid to have more than one matching argumentitisstring in this example i want the mockmembershipservice to return a different provideruserkey depending on the user suppliedmockmembershipservicesetup x xgetuser itisstring s scontainsjoe provideruserkeyreturns1234abcdmockmembershipservicesetup x xgetuser itisstring s scontainstracy provideruserkeyreturns5678efghthe setup defaults to the second statement rather than evaluating each on its own merits,['c#'] +245021,importerror no module named bottle sudo pip install bottle downloadingunpacking bottle downloading bottle0107targz 55kb 55kb downloaded running setuppy egg info for package bottleinstalling collected packages bottle found existing installation bottle 0107 uninstalling bottle successfully uninstalled bottle running setuppy install for bottle changing mode of buildscripts26bottlepy from 640 to 755 changing mode of usrlocalbinbottlepy to 755successfully installed bottle helpmodulesblahblahbottleblahblah ls usrlocallibpython26thistpackagesbottle0107egginfo bottlepy bottlepycbut pythonpython 266 r26684292 sep 15 2010 155239 gcc 445 on linux2type help copyright credits or license for more information import bottletraceback most recent call last file stdin line 1 in moduleimporterror no module named bottlewtf ubuntu 1010solution chmod r 775 usrlocallibpython26thistpackages is help for me thanks for all,['python'] +245095,how to expire php session if user is inactive for 15 mins i have created one project in php into which i am managing sessionsi am creating session in my configphp file by writing following line of codesession startand to destroy this session in logoutphp file i have write following linesession destroyand i have not mention any code for session in any other project file but the problem is session is active untill i call logoutphpwhat i want is session should expire if user is inactive for 15 minutescan anyone help me for this i am new to php please give some example code or link to achieve this,['php'] +245155,how to write qhash for a qset container i need to implement a set of sets in my applicationusing qset with a custom class requires providing a qhash function and an operatorthe code is as follows class custom int x int y some other irrelevant here inline uint qhashcustom c return qhashcx qhashcy bool operatorcustom c1 custom c2 return c1xc2x c1y c2y now i can use qsetcustomhow can i implement qhashqsetcustom to be able to use qset qsetsomeclass edit additional questionin my application the set of sets can contain up to 150 sets each subset up to 25 custom class pointers how to guarantee that qhashqsetcustom will be unique enough,['c++'] +245159,can abstract classes have implementation in c the compiler does not seem to mind it so far but i just wanted to double check whether i am setting myself up for failure in any way by implementing certain methods in my abstract class,['c#'] +245165,how to make android gridlayout compatible to older version new gridlayout for android 4 is good both in terms of code maintainability and performancei wanted help with backward compatibility for gridlayout for older version waiting for official compatibile package is taking too long i know its possible and someone did mention that this could be done by copying the class from version 4 platform sourcewould be really great if anybody could guide me how to do thisfor reference please check this post on google plus,['android'] +245196,tracing a c blocking system call i am trying to trace a high level function call that blocks a certain process an example of such is scanf which blocks the terminal until it receives a n now i traced scanf down to the getc scanf uses getc to acquire characters from stdin my question is what is the process that takes to interpret the data that comes from the keyboard all the way through the kernel and to the return of getc also how does scanf stops the terminal is the computer idling or working on another taskthank you,['c'] +245225,c function template specialization for known size typedefed array please consider the following codeinclude iostreaminclude typeinfotemplate typename type void func type var stdcout function var var typeid var name stdendl stdcout var is scalar size sizeof type stdendlif 1template typename type void func type var stdcout function var var typeid var name stdendl stdcout var is array size sizeof type stdendlendifint main typedef char char16 16 char16 c16 16 bytes chars stdcout size of char16 sizeof char16 stdendl func c16 return 0if i compile it and run i see this g wall g3 spec f pointercpp o spec f pointer spec f pointersize of char16 16func var 16 bytes chars pc var is array size 8clearly the sizeof printed inside func refers to the size of a pointer and not the size of the typedef array as given in mainnow i wonder how to correctly do the trick for getting my func to specialize in such a way that it correctly knows about my typedef and its sizedoes anyone here can help me pleasereally thankseditimplementing a specialization astemplate typename type void func type const var stdcout function var var typeid var name stdendl stdcout var is array size sizeof type stdendlthe output issize of char16 16func var 16 bytes chars a16 c var is scalar size 16i noticed the type change from pc to a16 cdoes it help,['c++'] +245239,javascript idiom for limiting a string to a number of thiscrete values in c i might use an enumeration in javascript how can i limit a value to a set of thiscrete values idiomatically,['javascript'] +245312,what causes saxexception2 instance of acomfoobara is substituting ajavalangobjecta but acomfoobara is bound to an anonymous type migrating existing jaxb uses both jaxb101 and jaxb 205 application on jboss 43 with jdk5 to jaxb 2110 supplied with jdk6 update jdk160 30i cannot modify the customerprovided schema i have removed all references of jaxws20 jwsdp jaxp and jaxb jars from sun ri and am using jars provided by jdk 6 onlyany pointers caused by comsunistacksaxexception2 instance of acomfoobara is substituting ajavalangobjecta but acomfoobara is bound to an anonymous type comfoobara2e3ssat comsunxmlbindv2runtimexmlserializerreporterrorxmlserializerjava247at comsunxmlbindv2runtimexmlserializerchildasxsitypexmlserializerjava662at comsunxmlbindv2runtimepropertyarrayelementpropertyserializelistbodyarrayelementpropertyjava165at comsunxmlbindv2runtimepropertyarrayerpropertyserializebodyarrayerpropertyjava152at comsunxmlbindv2runtimeclassbeaninfoimplserializebodyclassbeaninfoimpljava332at comsunxmlbindv2runtimexmlserializerchildasxsitypexmlserializerjava698at comsunxmlbindv2runtimepropertysingleelementnodepropertyserializebodysingleelementnodepropertyjava152at comsunxmlbindv2runtimeclassbeaninfoimplserializebodyclassbeaninfoimpljava332at comsunxmlbindv2runtimexmlserializerchildassolecontentxmlserializerjava592at comsunxmlbindv2runtimeclassbeaninfoimplserializerootclassbeaninfoimpljava320at comsunxmlbindv2runtimexmlserializerchildasrootxmlserializerjava493at comsunxmlbindv2runtimemarshallerimplwritemarshallerimpljava325,['java'] +245345,javascript dateformat is not a function i am using this piece of code to get string representing date ymmdd from a hidden field and then format it as neededvar date string enddatevalvar splitdate date stringsplitvar end date new datesplitdate0 splitdate1 1 splitdate2end dateformatd m ds ybut it throws an errorend dateformat is not a functionwhy does it happen and how to solve this issue,"['javascript', 'html']" +245359,what is the default actionbar title font size seems to be 17dip just want to confirm it if anyone knows the exact size,['android'] +245366,how to find a node in a tree with javascript i have and object literal that is essentially a tree that does not have a fixed number of levels how can i go about searching the tree for a particualy node and then return that node when found in an effcient manner in javascriptessentially i have a tree like this and would like to find the node with the title randomnode 1var data title topnode children title node1 children title randomnode 1 title node2 children title randomnode 2 children title node2 children title randomnode 3,['javascript'] +245367,css specificity how does it decide which styles to apply in a nutshell how does css determine when to apply one style over anotherin the past year i have been working with a lot of javascript and the css based selectors used in jquery pushed me to learn more about how they work i have been through the w3 css3 selectors document a few times and that has helped me understand how to better use css selectors in jquery but it has not really helped me understand when one css rule will be applied over anotheri will show you an example of what i do not understandi have the following the htmldiv classitem alink 1a a claspeciallink 2adivi have the following cssitem a textdecoration none color black fontweight bold fontsize 1em special textdecoration underline color red fontweight normal fontsize 2em given the above both link 1 and link 2 will be styled the same as determined by the item a css why does the style associated with special not take precedence for link 2obviously i can get around it like thisspecial textdecoration underline important color red important fontweight normal important fontsize 1em important but i feel like that is a hack that i have to sprinkle in due to my lack of understanding when i use important i feel a little bit like an addict slipping some small amount of a forbidden substance telling himself it is ok to indulge onelasttime before quitting for goodadditionally if i wanted to really learn css are there any excellent books to recommend,['css'] +245459,botos3 copy on a key object loses contenttype metadata heres some sample code of copying an s3 key there is a lot of reasons you might want to do this one of which is to update key metadata and while this does seem to be the widely accepted solution for that there is a big issue the problem is when i do the example below i actually lose my contenttype which defaults back to applicationoctetstream not very useful if trying to serve web images get bucketconn s3connectionself aws key self aws secretbucket connget bucketself aws bucket create keyk keybucketkkey key copy old keykmetadataupdate meta key meta value k2 kcopykbucketname kname kmetadata preserve acltruek k2any ideas thanks,['python'] +245462,how can i go about using the gemfiles path argument to reference local gems in development with a value that is os agnostic i am writing a gemfile to help with the development of a few gems my team is creating i know that the gemfile allows the use of the path argument to reference local directories that contain a gemspec filegem my gem path ruby libsmy gemhowever the members of my team are using different oss os x win xp win 7 when writing their code so my question is how can i go about using the gemfiles path argument to reference local gems in development with a value that is os agnostic,['ruby'] +245466,how to check dependencies of floats i want to determine in c if one float number is the multiplicative inverse of another float number the problem is that i have to use a third variable to do it for instance this codefloat x5y02ifx1y coutthey are the multiplicative inverse of eachotherendlelse coutthey are not the multiplicative inverse of eachotherendlwill output they are not which is wrong and this codefloat x5y02zz1yifxz coutthey are the multiplicative inverse of eachotherendlelse coutthey are not the multiplicative inverse of eachotherendlwill output they are which is rightwhy is this happening,['c++'] +245470,net dll for natural language to sqlsparql i am trying to build an interface for my tool to query from semanticrelational db using cneti now need to have a layer above the query layer to convert nl input to sqlsparql i read through papers of nlis the process of making such a layer is such a load for my project besides it is not the main target it is an addoni do not care if the dll supports guided input only or freely input text and handles unmatchings i just need a dll to start from and add some code on itthe fact of whether it should support both sql and sparql does not really matter because i can manage to convert one to another in my projects domain something localany idea on available dlls,['sql'] +245492,how to make a view follow my finger using onscroll and gesturedetector android i have a relativelayout with a textview in the middle i have got it to detect onfling ondown and onscroll events using simpleongesturelisteneri would like the textview to follow my finger around the screen can be just in the x axis and when i lift my finger for it so animate either out of the screen or back to the middle depending on how far i have moved iti have no idea how this can be done any ideasthanks,['android'] +245493,select then immediately delete mysql record i have a php script that runs a select query then immediately deletes the record there are multiple machines that are pinging the same php file and fetching data from the same table each remote machine is running on a cron jobmy problem is that sometimes it is unable to delete fast enough since some of the machines ping at the exact same timemy question is how can i select a record from a database and have it deleted before the next machine grabs it for right now i just added a short delay but it is not working very well i tried using a transaction but i do not think it applies herehere is an example snippet of my scriptphpquery select from queue limit 1result mysql queryquery or diemysql errorwhilerow mysql fetch arrayresult email rowemail campaign id rowcampaignqueryx delete from queue where email emailresultx mysql queryqueryx or diemysql errorreally appreciate the help,"['php', 'mysql']" +245498,nsnull handling for nsmanagedobject properties values i am setting values for properties of my nsmanagedobject these values are coming from a nsdictionary properly serialized from a json file my problem is that when some value is nsnull null i cannot assign directly to the property fightwinnerid dict objectforkeywinnerthis throws a nsinvalidargumentexceptionwinnerid desired type nsstring given type nsnull value nulli could easily check the value for nsnull null and assign nil insteadfightwinnerid dict objectforkeywinner nsnull null nil dict objectforkeywinnerbut i think this is not elegant and gets messy with lots of properties to setalso this gets harder when dealing with nsnumber propertiesfightround nsnumber numberwithunsignedintegerdict valueforkeyround unsignedintegervaluethe nsinvalidargumentexception is nownsnull unsignedintegervalue unrecognized selector sent to instancein this case i have to treat dict valueforkeyround before making an nsuinteger value of it and the one line solution is gonei tried making a try catch block but as soon as the first value is caught it jumps the whole try block and the next properties are ignoredis there a better way to handle nsnull null or perhaps make this entirely different but easier,['objective-c'] +245506,rtsp video performance as browser triggered intent vs my application triggered intent hi i am creating an app which will play livestreamcoms rtsp live channeli am launching the player using intent within my app as following iplayer new intentintentaction view iplayersettypevideo iplayersetdatauriparsevideourl startactivityiplayer when the media player is launched through my application the video performance is very poor it stops for buffering every few seconds plays for few seconds and pauses for buffering againon the other hand if i open the url in android browser eg it has a video tag on that page and triggers video player this time the video runs very smoothany idea why this might happen and how this can be fixedi do not want to launch browser url as intentthis is done on atmel cortex a9 chipset with android 234,['android'] +245513,parallel linq query optimization for some time now i have been structuring my code around methods with no sideeffects in order to use parallel linq to speed things up along the way i have more than once stumbled on lazy evaluation making things worse instead of better and i would like to know if there are any tools to help with optimizing parallel linq queries i ask because i recently refactored some embarrassingly parallel code by modifying some methods and peppering asparallel in certain key places the run time went down from 2 minutes to 45 seconds but it was clear from the performance monitor that there were some places where all the cores on the cpu were not being fully utilized after a few false starts i forced some of the queries to execute by using toarray and the run time went down even further to 16 seconds it felt good to reduce the run time of the code but it was also slightly thisconcerting because it was not clear where in the code queries needed to be forced with toarray waiting until the last minute for the query to execute was not the optimal strategy but it was not clear at all at what points in the code some of the subqueries needed to be forced in order to utilize all the cpu coresas it is i have no idea how to properly pepper toarray or other methods that force linq computations to execute in order to gain maximum cpu utilization so are there any general guidelines and tools for optimizing parallel linq queriesheres a pseudocode samplevar firstquery somedictionaryselectmanyfirsttransformationvar secondquery firstqueryselectsecondtransformationvar thirdquery secondqueryselectthirdtransformationwheresomeconditioncheckvar finalquery thirdqueryselectfinaltransformationwherex x nullfirsttransformation secondtransformation thirdtransformation are all cpu bound and in terms of complexity they are a few 3x3 matrix multiplications and some if branches someconditioncheck is pretty much a null check finaltransformation is the most cpu intensive part of the code because it will perform a whole bunch of lineplane intersections and will check polygon containment for those intersections and then extract the intersection that is closest to a certain point on the linei have no idea why the places where i put asparallel reduced the run time of the code as much as it did i have now reached a local minimum in terms of run time but i have no idea why it was just dumb luck that i stumbled on it in case youre wondering the places to put asparallel are the first and last lines putting asparallel anywhere else will only increase the run time sometimes by up to 20 seconds there is also a hidden toarray hiding in there on the first line,['c#'] +245519,why is it important to use static cast instead of reinterpret cast here at a reply of a blog post of raymond chena questioner pointed outraymond i believe the c example is not correct since the position of the base class subobject in the derived class is unspecified according to iso c 2003 standard 103 page 168 and you assume that the base class subobject is always at the beginning the c example would be fine in c too so i would stick with it raymond repliedthe code does not make this assumption that is why it is important to use static cast instead of reinterpret cast try it add a virtual method to overlapped so a vtable goes in front and observe what the compiler does raymondi could guess after read his comments using static cast is fine at the example but reinterpret cast is not because reinterpret cast is not convert vtable do i understand it rightlythough if i use cstyle cast at therenot reinterpret cast could it also go wrongi reread more effective cs cast explanation to understand that but there was no answer about that,['c++'] +245522,cannot use modulus on doubles i have a program in c compiled using g i am trying to apply two doubles as operands to the modulus function but i get the following errorerror invalid operands of types double and double to binary operatorheres the codeint main double x 63 double y 2 double z x y,['c++'] +245541,how to use the mysql client ssl setting with mysql connect in php i have a ca certificate of the mysql database i am trying to connect to it is on amazon rds i cannot find a good example of how to connect to the mysql database using phps mysql connect function and using that ca certificate stored at homeusernamemysql ca certpem to connectcould anyone help me with a simple example,"['php', 'mysql']" +245568,uiscrollview scrollrecttovisibleanimated is there a way that a method can be called when animation ends is there a way to know when the animation has end and uiscrollview has come to rest,['ios'] +245571,udp hole punching implementation i am trying to accomplish udp hole punching i am basing my theory on this article and this wiki page but i am facing some issues with the c coding of it here is my problemusing the code that was posted here i am now able to connect to a remote machine and listen on the same port for incoming connections bind 2 udp clients to the same portfor some reason the two bindings to the same port block each other from receiving any datai have a udp server that responds to my connection so if i connect to it first before binding any other client to the port i get its responses backif i bind another client to the port no data will be received on either clientsfollowing are 2 code pieces that show my problem the first connects to a remote server to create the rule on the nat device and then a listener is started on a different thread to capture the incoming packets the code then sends packets to the local ip so that the listener will get it the second only sends packets to the local ip to make sure this works i know this is not the actual hole punching as i am sending the packets to myself without living the nat device at all i am facing a problem at this point and i do not imagine this will be any different if i use a computer out side the nat device to connectedit 242012i tried using another computer on my network and wireshark packet sniffer to test the listener i see the packets incoming from the other computer but are not received by the listener udp client udpserver or the sender udp client clientedit 252010i have now added a function call to close the first udp client after the initial sending and receiving of packets only living the second udp client to listen on the port this works and i can receive packets from inside the network on that port i will now try to send and receive packets from outside the network i will post my findings as soon as i find somethingusing this code i get data on the listening clientstatic void mainstring args ipendpoint localpt new ipendpointdnsresolvednsgethostnameaddresslist0 4545 threadpoolqueueuserworkitemdelegate udpclient udpserver new udpclient udpserverexclusiveaddressuse false udpserverclientsetsocketoptionsocketoptionlevelsocket socketoptionnamereuseaddress true udpserverclientbindlocalpt ipendpoint inendpoint new ipendpointipaddressany 0 consolewritelinelistening on localpt byte buffer udpserverreceiveref inendpoint this line will block forever consolewritelinereceive from inendpoint encodingasciigetstringbuffer threadsleep10 udpclient udpserver2 new udpclient60 the following lines work and the data is received udpserver2connectdnsresolvednsgethostnameaddresslist0 4545 udpserver2sendnew byte 0x41 1 consolereadif i use the following code after the connection and data transfer between my client and server the listening udp client will not receive anythingstatic void mainstring args ipendpoint localpt new ipendpointdnsresolvednsgethostnameaddresslist0 4545 if the following lines up until serverconnect are removed all packets are received correctly client new udpclient clientexclusiveaddressuse false clientclientsetsocketoptionsocketoptionlevelsocket socketoptionnamereuseaddress true clientclientbindlocalpt remoteserverconnect connection to remote server is done here response is received correctly and printed to the console threadpoolqueueuserworkitemdelegate udpclient udpserver new udpclient udpserverexclusiveaddressuse false udpserverclientsetsocketoptionsocketoptionlevelsocket socketoptionnamereuseaddress true udpserverclientbindlocalpt ipendpoint inendpoint new ipendpointipaddressany 0 consolewritelinelistening on localpt byte buffer udpserverreceiveref inendpoint this line will block forever consolewritelinereceive from inendpoint encodingasciigetstringbuffer threadsleep10 udpclient udpserver2 new udpclient60 i expected the following line to work and to receive this as well udpserver2connectdnsresolvednsgethostnameaddresslist0 4545 udpserver2sendnew byte 0x41 1 consoleread,['c#'] +245615,explain the use of a bit vector for determining if all characters are unique i am confused about how a bit vector would work to do this not too familiar with bit vectors here is the code given could someone please walk me through thispublic static boolean isuniquecharsstring str int checker 0 for int i 0 i strlength i int val strcharati a if checker 1 val 0 return false checker 1 val return trueparticularly what is the checker doing,['java'] +245619,initializing const member within class declaration in c in php and c the constants can be initialized as they are declaredclass calendar3 const int value1 12 const double value2 01i have the following c declaration of a functor which is used with another class to compare two math vectorsstruct equal vec bool operator const vector3d a const vector3d b const vector3d thist b a return thistlength2 tolerance static const float tolerance 01this code compiled without problems with g now in c0x mode stdc0x the g compiler outputs an error messageerror aconstexpra needed for inclass initialization of static data member atolerancea of nonintegral typei know i can define and initialize this static const member outside of the class definition also a nonstatic constant data member can be initialized in the initializer list of a constructorbut is there any way to initialize a constant within class declaration just like it is possible in php or cupdatei used static keyword just because it was possible to initialize such constants within the class declaration in g i just need a way to initialize a constant in a class declaration no matter if it declared as static or not,['c++'] +245620,generic class that accepts either of two types i want to make a generic class of this formclass mygenericclasst extends number problem is i want to be acceptable for t to be either integer or long but not double so the only two acceptable declarations will bemygenericclassinteger instancemygenericclasslong instanceis there any way to do that,['java'] +245622,facebook login secure i want to let people to log in with facebook loginbut i wonder if it is secure enough or i am just doing it wrongwhat i am getting back after a successful login is the user data with the facebook id which i am inserting to the db passed by a javascript reuest to the server via handler since i am using aspnetbut what i think that by a malicious use one can change that data and insert rubbish to the server or even insert different facebook idso i wonder if the facebook login is secure enough to use or that i am doing it wrongi thought about other option to pass that client data to the server by postback the server with a hidden runatserver textboxes but still malicious use can change those textboxes i have read here about the option to let the users add password to their facebook username but it sounds a bit not userfriendlyam i right is that a way to do it more secure is there any cookie that facebook put on the client browser that i can read from the server as though a lot of websites use this facebook login there might be another way that i didnt think about,"['c#', 'asp.net']" +245629,qt webkit tutorial for c is there any basic tutorial for qt webkit applications for ci am using qt creator on the official site there is section for webkit but it is empty therere no links or any materials on it,['c++'] +245636,smooth scrolling easing effect with mouse wheel i recently came across this website and i love the way the mouse wheel scrolling works the easing is very smoothi have been searching google but i cannot find anything similardoes anybody have any suggestions on how to replicate this effect with jquery,['jquery'] +245704,jquery scroll detect when user stops scrolling ok with this windowscrollfunction slides layoverremoveclashowing layover slides effectshowi can tell when someone is scrolling from what i understand so with that i am trying to figure out how to catch when someone has stopped from the above example you can see i am removing a class from a set of elements while the scrolling is occurring however i want to put that class back on when the user stops scrollingthe reason for this is i am intent on having a layover show while the page is scrolling to give the page a special effect i am attempting to work on but the one class i am trying to remove while scrolling conflicts with that effect as its a transparency effect to some nature,"['javascript', 'jquery']" +245710,c reverse bits in unsigned integer i am converting an unsigned integer to binary using bitwise operators and currently do integer 1 to check if bit is 1 or 0 and output then right shift by 1 to divide by 2 however the bits are returned in the wrong order reverse so i thought to reverse the bits order in the integer before beginning is there a simple way to do thisexampleso if i am given the unsigned int 10 1010while x not eq 0 if x 1 output a 1 else output a 0 right shift x by 1this returns 0101 which is incorrect so i was thinking to reverse the order of the bits originally before running the loop but i am unsure how to do this,['c'] +245734,calling javascript on rendering views in backbone js postrender callback behold a backbone view render callrender function thiselhtmlthistemplatetitle test 1 thisrenderscatterchart return thisso i call a standard render at 1 and then i call a method this time it is a wrapper for charting lib that looks for a div the div is rendered by the render call but at this point it is not attached to the dom yet right so the chart call sadly dieswhat is the pattern for this i would love hear that there is a postrender callback i have tried a few hacks around this and sometimes i get the chart to work but events do not bind,['javascript'] +245762,symfony2 echoing json from a controller for use in an extjs 4 grid i am just getting started with symfony2 and i am trying to figure out what the correct approach is for echoing out json from a controller eg people for use in an extjs 4 gridwhen i was doing everything using a vanilla mvc approach my controller would have method called something like getlist that would call the people models getlist method take those results and do something like thisphpclass peoplecontroller extends controller public function getlist model new people data modelgetlist echo json encodearray success true root people rows datarows count datacount what does this kind of behavior look like in symfony2is the controller the right place for this kind of behaviorwhat are the best practices within symfony for solving this kind of problem,['php'] +245767,which ios classes that do not support zeroing weak references is there a list of classes in ios that cannot be referred with a weak pointer when using automatic reference counting arc apples transitioning to arc release notes only lists mac classes so farwhich classes donat support zeroingweak referencesyou cannot currently create zeroingweak references to instances of the following classesnsatstypesetter nscolorspace nsfont nsfontmanager nsfontpanel nsimage nsmenuview nsparagraphstyle nssimplehorizontaltypesetter nstablecellview nstextview nsviewcontroller nswindow and nswindowcontroller in addition in os x no classes in the av foundation framework support weak referencesis there a similar list for uikit classes or even iosspecific classes in generalthanks,"['objective-c', 'ios']" +245772,ios uimenucontroller uimenuitem how to determine item selected with generic selector method with the following setupmyuimenuitem someaction myuimenuitem allocinitwithtitle something action selectormenuitemselectedmyuimenuitem someaction2 myuimenuitem allocinitwithtitle something2 action selectormenuitemselected ibaction menuitemselected id sender uimenucontroller mmi uimenucontroller senderhow to figure out which menu item was selectedand do not say that you need to have two methods thanks in advance,['ios'] +245813,how to get child pid in c i am creating child processes in a forloop inside the child process i can retrieve the child pid with getpid however for some reason when i try to store the value of getpid into a variable declared by the parent process the change is nullified when i check for it in the parent process i am assuming this has to do with some sort of process variable scope not really familiar with c so cannot be too sureanyhow what is a way of storing the result of getpid of a child pid when called from the child process into a variable in the parent processor maybe another approach is storing fork into a variable in the parent and calling some function on that variable to retrieve the childs pid i do not know how to do this either so if this is the better way how would you do this,['c'] +245814,change the navigation bar tint using xcode i have been looking on this site and on other how to set the navigation bar tint change i have seen examples but is not quite what i need so any help will be appreciatedon my app delegate i havesynthesize windowsynthesize tabbarcontrollersynthesize navigationcontrollersynthesize navigationcontroller1synthesize navigationcontroller2synthesize viewcontrollersynthesize viewcontroller2synthesize viewcontroller3pragma mark pragma mark application lifecycle boolapplicationuiapplication application didfinishlaunchingwithoptions nsdictionary launchoptions override point for customization after application launch set the tab bar controller as the windows root view controller and thisplayselfwindowrootviewcontroller selftabbarcontrollerselfwindow makekeyandvisible return yeswhen i enter the code selfnavigationcontrollernavigationbar settintcoloruicolor blackcolor on the above it only changes one of my navigation controllers but not the one i needi have 7 items on my tabbar and when i press the more i get a table view with the other items that do not fit on the main screen the navigation bar is added automatically and no matter what i do i can not change this navigation bar tint i can change the ones that i have synthesize but not the automatically entered onecan someone please let me know how to change the automatically placed navigation bar,['ios'] +245826,rails 321 heroku asset precompile error i have added these two lines to applicationrbconfigassetsinitialize on precompile falseconfigassetscompile truehowever i still get errors when i push to heroku20120205t0948340 appweb1 completed 500 internal server error in 3ms20120205t0948340 appweb1 20120205t0948340 appweb1 actionviewtemplateerror bootstrapcss is not precompiledany suggestions,['ruby-on-rails'] +245838,how to fork and child processes correctly in c that is my codeinclude stdiohinclude stdlibhint main int argc char argv int i pidfori 0 i atoiargv1 i pid fork ifpid 0 printferror exit1 else if pid 0 printfchild d dn i 1 getpid exit0 else waitnull the output is like thatchild 1 5676child 2 4624child 3 4800child 4 5596child 5 5580however that is not the expect output in the my homeworkit should be like that whats wrong with code can someone help mechild 2 4625child 1 4624child 3 4626child 4 4627child 5 4628thank you for your help now i will try it outps sorry my english is bad i hope you can understand what i said,['c'] +245844,how to make clang compile to llvm ir i want clang to compile my cc code to llvm bytecode rather than binary executable how can i achieve that and if i get the llvm bytecode how can i take it to further compile it to binary executable basically i want to add some of my own code to the llvm bytecode before compiling to binary executable,['c'] +245852,domdocumentloadhtml error i build a script that combines all css on a page together to use it in my cms it worked fine for a long time now i i get this error warning domdocumentloadhtml domdocumentloadhtml tag header invalid in entity line 10 in cssphp on line 26 warning domdocumentloadhtml domdocumentloadhtml tag nav invalid in entity line 10 in cssphp on line 26 warning domdocumentloadhtml domdocumentloadhtml tag section invalid in entity line 22 in cssphp on line 26 this is the php script this is my codephpheadercontenttype textcssinclude globalphpif usetpl 1 client new client tplname clienttemplate location templatestplnameheaderphp page file get contentslocation else page file get contentsindexphpclass stylesheets extends domdocument implements iteratoraggregate public function construct source parent construct thisloadhtmlsource public function getiterator static array if null array xp new domxpaththis expression headlinkrelstylesheethref array array foreach xpqueryexpression as node array nodenodevalue return new arrayiteratorarray foreach new stylesheetspage as index file css file get contentsfile echo css,['php'] +245880,closing urlconnection and inputstream correctly i have seen many different examples of using httpurlconnection inputstream and closing them or not closing them after use this is what i came up with to make sure everything is closed after finished whether there is an error or not is this validhttpurlconnection conn nullinputstream is nulltry url url new url set connection and read timeouts on the connection conn httpurlconnectionurlopenconnection is new bufferedinputstreamconngetinputstream dosomethingwithinputstreamis catch exception ex finally if is null try isclose catch ioexception e if conn null connthisconnect thanks,['java'] +245884,select the top and rows from a table i am making some paging and i need to make some query and get the result form defined slicing for example i need to get all top rows in range 20n x 40n etcselect from reflow where reflowprocessid somenumberorder by id descand now i need to make my sliding by column called id any suggestions how to so i need to run my query on mysql mssql and oracle,"['mysql', 'sql']" +245903,confused about java properties file location i have simple java project with structurepackage comabc ajava bjava cpropertiesi have database configuration parameters configured in cproperties fileinside ajava and bjava i am loading properties file usingproperties p new propertiesinputstream in thisgetclassgetresourceasstreamcpropertiesploadinthis works fine but the main question is once i prepare executable jar by exporting this code properties file also gets packaged in jar file if someone else wants to modify properties file for different database configuration how can he do itdo i have to store properties file in some fixed location in local machine eg c then give jar along with properties file to the other person then he needs to copy properties file inside c locationalso one more question how can i make this location generic for windows and linux machine,['java'] +245917,intellij idea deploy a simple java servlet no jsp to tomcat 7 i tried following the tutorial here to deploy a servlet but that only works if you specify a jsp file the problem is that without the jsp i do not know what to set the startup page in the tomcat rundebug configuration so any idea what to dothanks,['java'] +245922,getting marshall result into string jaxbcontext context jaxbcontext newinstancecreateexemptioncertificateclass marshaller m contextcreatemarshaller msetpropertymarshallerjaxb formatted output booleantrue mmarshalcc systemoutin the code above i am getting the result to the console i mean xml is getting printed on the console i want to get this xml to a string i am not getting which argument i should pass to the marshal method to get xml string in a string variable instead of printing it on the console anybody having any idea please share,['java'] +245946,deterministically checking whether a large number is prime or composite i am searching for an algorithm to primality test large like 10200 numbers are there any good algorithms ideally i would prefer an algorithm that is not probabalisticnote numbers have over 50 and less then 200 digits,['c++'] +245953,testing endianess at compiletime is this constexpr function correct according to the standard after some search for a way to check endianess at compiletime i have come up with the following solution static const int a1constexpr bool is big endian return chara 1gcc accepts this code only in some contexts where constexpr is requiredint bis big endian 12 25 worksstdarrayint testendian 12 25 c failsfor the second case gcc says error accessing value of a through a achara glvalue in a constant expression i could not find anything in the standard that forbids such thing maybe someone could clarify in which case gcc is correct,['c++'] +245973,configuring the sublime linter plugin to use ruby 19 syntax i would like to get the sublime linter plugin to recognize ruby 19 syntax has anybody been able to get this to work in sublimetext 2 here is my current default settings file sublimelinter default settings sets the mode in which sublimelinter runs true linting occurs in the background as you type the default false linting only occurs when you initiate it loadsave linting occurs only when a file is loaded and saved sublimelinter true maps linters to executables for nonbuilt in linters if the executable is not in the default system path or on posix systems in usrlocalbin or bin then you must specify the full path to the executable linter names should be lowercase this is the effective default map your mappings may override these sublimelinter executable map perl perl php php ruby ruby sublimelinter executable map maps syntax names to linters this allows variations on a syntax for example python django to be linted the key is the base filename of the tmlanguage syntax files and the value is the linter name lowercase the syntax maps to sublimelinter syntax map python django python an array of linter names to thisable names should be lowercase sublimelinter thisable the minimum delay in seconds fractional seconds are okay before a linter is run when the sublimelinter setting is true this allows you to have background linting active but defer the actual linting until you are idle when this value is greater than the built in linting delay errors are erased when the file is modified since the assumption is you do not want to see errors while you type sublimelinter delay 0 if true lines with errors or warnings will be filled in with the outline color sublimelinter fill outlines false if true lines with errors or warnings will have a gutter mark sublimelinter gutter marks false if true the find nextprevious error commands will wrap sublimelinter wrap find true if true when the file is saved any errors will appear in a popup list sublimelinter popup errors on save false jshint options for linting javascript see for more info by deault eval is allowed jshint options evil true regexdash true browser true wsh true trailing true sub true strict false a list of pep8 error numbers to ignore by default line too long errors are ignored the list of error codes is in this file search for en where n is a 3digit number pep8 ignore e501 if you use sublimelinter for pyflakes checks you can ignore some of the undefined name x errors comes in handy if you work with postprocessors globalsbuiltins available only at runtime etc you can control what names will be ignored with the user setting pyflakes ignore example pyflakes ignore some custom builtin o mine a global constant pyflakes ignore ordinarily pyflakes will issue a warning when from foo import is used but it is ignored since the warning is not that helpful if you want to see this warning set this option to false pyflakes ignore import true objectivej if true nonascii characters are flagged as an error sublimelinter objj check ascii false,['ruby'] +246005,guice injecting only some of the constructor suppose i have some message class like the following this is a madeup class for simplicitypublic class message private string text public messagestring text thistext text public void sendperson recipient i think i should be guiceinjecting the sender messagesender sender new emailbasedmessagesender sendersendrecipient thistext since i have different messagesender implementations and might want to unit test this sending ability i think i should be injecting the messagesender in messages send method but how do i do thisall the guice examples i have seen and that i understand seem to do the injection in the constructorpublic class message private string text private messagesender sender i do not know what to do here since the text argument should not be injected inject public messagestring text messagesender sender thistext text thissender sender public void sendperson recipient thissendersendrecipient thistext public class messagesendermodule extends abstractmodule override protected void configure bindmessagesenderclasstoemailbasedmessagesenderclass but my message class takes in a text argument in its constructor which i do not want to inject so what am i supposed to do insteadnote i am a complete google guice noob i think i understand dependency injection but i do not understand how to actually implement it with guice,['java'] +246044,regexp match character group or end of line how do you match begin of line and end of line in a character groupsimple examplehaystack string zaztyrulesmatch any z or yif preceded byan a b orat the beginning of the linepassmatch the first two za regexp that would work isaabbzzyybut i keep thinking it would be much cleaner with something like that meant beginningend of line inside the character groupaabbzzyy in that example assumes the means beginning of line and not what it really is there a negative for the character groupnote using python but knowing that on bash and vim would be good tooupdate read again the manual it says for set of chars everything lose it is special meaning except the character classes eg wdown on the list of character classes there is a for beginning of line but this does not work abbzzyyany idea why,['python'] +246072,how to copy a row and insert in same table with a autoincrement field in mysql i have a table eg tab what i am trying to do is copying a row with an autoincrement column id1 and insert the data into same table with a row and column id2using mysqlhow can i do this in a single queryplease help,"['mysql', 'sql']" +246073,add commas for a number in input field while typing this does it incorrectlycan jquery add commas while user typing numbers inputnumberkeypressfunctionevent ifeventwhich 37 eventwhich 40 eventpreventdefault var this this var num thisvalreplaceg thisvalnumreplacedd3dg 1 i need 10 to be 10 or better with spaces 1 0 0please help thanks,['jquery'] +246082,curious to know the trick for live wallpapers on lock screen on iphone this application and this application says it thisplays live wallpapers on lock screen we have similar requirementfrom reviews came to know that it is playing music in background with silent volume but it is not relevant to setting wallpapers totally bummer topic for us can anyone please suggest some point where to begin referred this and referred this questions on our forum but says that it would not be approved by apple so how does current application exist on store noteplease consider this as genuine programming questions as there is no starting point we can find,"['iphone', 'ios']" +246088,serialize enum to string i have an enumpublic enum action remove1 add2and a classdatacontractpublic class container datamember public action action get setwhen serialize instance of container to json i get action1 in case action is removei would like to get actionremove instead of int i need to tostring form of the enumcan i do it without adding another member to the class,['c#'] +246089,linking against opencv 231 on ubuntu i am new to opencv and i got a problem with linkage i am using ubuntu 10 opencv 231 was installed according to this guide i am building many small applications with it and it looks fineusually i am building with pkgconfig libs cflags opencvnow i am trying to build some framework that someone else wrote it compiles without any problems but i cannot link it there is a long list of unresolved reference to thousands of them all symbols related to opencv core are not found i tried to recompile opencv without precompiled header support did not help of course the test opencv core application is running fine but opencv rand failed i think it says that opencv core is correct in general but it still does not work when i need itcan you please try to give me some hint i am lost therethank you in advancedavid updatesolvedgcc 461 require that the libs and sources will apear in the command line before pathes to shared libs why do not know just spent 24 hours for this stupid mistake updateunderstandable from the ld man pagethe linker will search an archive only once at the location where it is specified on the command line if the archive defines a symbol which was undefined in some object which appeared before the archive on the command line the linker will include the appropriate files from the archive however an undefined symbol in an object appearing later on the command line will not cause the linker to search the archive againsee the option for a way to force the linker to search archives multiple timesthat is it,['c++'] +246101,how do i raise the same exception with a custom message in python i have this try block in my codetry do something that might raise an exceptionexcept valueerror as err errmsg my custom error message raise valueerrorerrmsgstrictly speaking i am actually raising another valueerror not the valueerror thrown by do something which is referred to as err in this case how do i attach a custom message to err i try the following code but fails due to err a valueerror instance not being callabletry do something that might raise an exceptionexcept valueerror as err errmsg my custom error message raise errerrmsg,['python'] +246111,nsbundle pathforresource returns nil i have been trying to load a simple text file in a unit test for an ios appnsstring resourcepath nsbundle mainbundle pathforresource stoppointsincircledata oftypetxtnsstring stoppointdata nsdata datawithcontentsoffile resourcepathmy problem is that pathforresource returns nilthe file stoppointsincircledatatxt is located in the directory of the test code and the file is listed correctly under copy bundle resources in the build phases of the test targeti have tried to relax the search by setting oftype to nil but thet did not work eitherany help is very much apprechiated,['objective-c'] +246112,android no activity found to handle intent error how it will resolve no activity found to handle intent error how it will resolvepreference custompref preference findpreferencedataentryscreen custompref setonpreferenceclicklistenernew onpreferenceclicklistener public boolean onpreferenceclickpreference preference intent i new intentcomscytecdatamobilevdguiandroidapreferenceactivity startactivityi return true,['android'] +246121,how to access file system of another phone using bluetooth in android after pairing with a phone via bluetooth is it possible to access the sd card contents like music or imagesare there any tutorials or sample code for thisi see an application named bluetooth file transfer and want to make another like that i read about bluetooth bluetooth socket but not found any thing useful how to perform that operation i am researching more if i found i will post here the solution if anyone found soon then please post here thanks,['android'] +246128,postbuild uiautomation script not running in jenkins i am trying to do endtoend automation for an ios project my aim is to automate the continuous integration process with attaching uiautomation scripts as post build action so from the time when a user do check his code in svn and till we get test result of automation everything will be automatedjenkins is installed on my local machine and running on localhostnow i have automated build process through jenkins and at other end i have my shell script ready which will run uiautomation java scripts on build outputwhen i use my shell script as post build action then i get error in running instrument commandwritten inside shell script but if i run this script manually through terminal then it works fineinstruments6470360f nsalert alertwitherror called with nil nserror a generic error message will be thisplayed but the user deserves better registerapplication failed to establish the default connection to the windowserver cgsdefaultconnection is null mon feb 6 131520 inpunml310743 instruments64703 error kcgerrorfailure set a breakpoint cgerrorbreakpoint to catch errors as they are logged 20120206 131520179 instruments6470360f recording cancelled at least one target failed to launch aborting run instruments trace error failed to start trace build step execute shell marked build as failure finished failurethen i tried this command with sudo then i got following errorsudo no tty present and no askpass program specifiedplease let me know how can i run these commands successful only this step is left in my task,['ios'] +246134,colored output in c is there a way to print colored output using iostream and xcode i would like to be able to for example print hello world with hello red world blue and yellow how can i do that,['c++'] +246139,is it possible to set an animated gif file as live wallpaper in android i am new to android platform i wish to develop a live wallpaper application when i was searched regarding this in search engines many of them created a live wallpaper as their code using surfaceview and canvas i am not much aware in this here my doubt is any possible to set a gif images as a live wallpaper,['android'] +246203,ninject constructor injection in wpf is it possible to use ninject for dependency injection in such a way that the result would be something like the injection i can get in mvc to elaborate if i use the mvc ninject adapter i can declare my web controllers as having constructor parameters which would then automatically be injected by ninjecthowever i have not found such a ninject extension for wpf which would enable me to have a window such as thispublic partial class mainwindow window private readonly iservice injectedservice public mainwindowiservice injectedservice thisinjectedservice injectedservice i would like to do this without explicitly using the ikernel in my main application startup to obtain an instance of mainwindow i would much prefer to use the normal method of xaml configuration to obtain an instance of the main window and all subsequent windowsis this possible is there any way to hook into the object creation generated by xaml to modify it to use ninject for constructor dependency injection,['c#'] +246231,what exactly does orgapachecommonslangbuildercomparetobuilder do i learned about the comparable interface for which a class must implement compareto method a project i am using that method aspublic class employeeassignmenttotal implements comparableemployeeassignmenttotal serializable private employee employeeprivate int totalpublic int comparetoemployeeassignmenttotal other return new comparetobuilder appendemployee otheremployee appendtotal othertotal tocomparisonwhat exacly does comparetobuilder do here and how is it interacting with the employee and total attributesi did read the javadocs but i cant make head or tail of what they are doing with the constructor and the multiple appends does this question indicate unclear intentions and zero research,['java'] +246252,how to set silverlight currentuiculturecurrentculture correctly i am working on a sl5 app with c and i am looking to internationalize it i found the following to set the ui culturevar culture new cultureinfothreadcurrentthreadcurrentuiculturetwoletterisolanguagenamethreadcurrentthreadcurrentuiculture culturethreadcurrentthreadcurrentculture culturesome controls like the datepicker seem to pick this up if i format any datetime by using the d format string i still get the default format mddy howeverexactly how does sl interpret culture and how can i set it correctly for the entire applicationthanksupdatefound the answerfirst of all set the appropriate cultures in the application startupvar culture new cultureinfonlbethreadcurrentthreadcurrentuiculture culturethreadcurrentthreadcurrentculture culturethe key element however is to add the following to force the rootvisuals culturelanguagevar root rootvisual as pageif root null rootlanguage xmllanguagegetlanguagethreadcurrentthreadcurrentculturename,"['c#', '.net']" +246254,is there a light alternative to jquery mobile for just page transitions i am looking for an ultralight framework or snippet which handles webkit css page transitions in a similar way to jqm or jqtouch they work fine but i do not want to add almost 200kb of resources just to get some transitionsi would like it to feature 1 pagetopage switching divs within a single htmldoucment2 do a flip and possibly a slide transitionhas anyone seen such a thingedit i would like to avoid using jquery all together,['javascript'] +246295,using portaudio wrapper in ruby to record sound to wav i have been playing around with ruby recently and i decided to start a simple project to write a ruby script that records linein sound to a wav file i thiscovered that ruby does not provide very good access to hardware devices and it probably should not but that portaudio does and i thiscovered a great wrapper for pa here it is not a gem i think because it uses rubys ffi to attach to portaudio and the pa library could be in a variety of places i have been muddling through portaudios documentation and examples to figure out how pa works i have not written or read c in years i am running into difficulty with what parameters i should be passing to a stream during creation and a buffer during creation for example what exactly is a frame and how is it related to other parameters like channel and sample rate i am totally new to audio programming in general as well so if anyone could point me to some general tutorials etc about device level audio i would appreciate it rubyportaudio provides a single example that creates a stream and a buffer writes a sin wave to the buffer then sends the buffer to the stream to be played some of the ruby i am having trouble with in the example specifically the loop block portaudioinit block size 1024 sr 44100 step 10sr time 00 stream portaudiostreamopen sample rate sr frames block size output device portaudiodevicedefault output channels 1 sample format float32 buffer portaudiosamplebuffernew format float32 channels 1 frames block size playing true signaltrapint playing false puts ctrlc to exit streamstart loop do stream bufferfill frame channel time step mathcostime 2 mathpi 4400 mathcostime 2 mathpi break unless playing end streamstopif i am going to be recording i should be reading a stream into a buffer then manipulating that buffer and writing it to file rightalso if i am barking up the wrong tree here and there is an easier way to do this in ruby some direction would be nice,['ruby'] +246296,is there a method to get the max and min of an nsmutablearray is there a way in ios for me to get the max and min values of an nsmutablearray of double numbers i am looking for an already existing method not for me to sort the array my self if there is a method for me build into the api for me to sort the array that would interest me toothank you,['ios'] +246301,django virtualenv nginx uwsgi import module wsgi error im trying to setup my django project on a staging server with nginx virtualenv and uwsgi but i keep getting an import module wsgi errorif theres a community i can find an answer is here thank you all in advancethis are my configuration filesuwsgipy on my django projectimport osimport sys import sitesiteaddsitedirospathjoinosenvironworkon homeprojectlibpython26sitepackagessyspathappendospathabspathospathdirname file syspathappendospathjoinospathrealpathospathdirname file syspathappendospathjoinospathrealpathospathdirname file osenvirondjango settings module projectconfigsstagingsettingsimport djangocorehandlerswsgiapplication djangocorehandlerswsgiwsgihandlernginx configuration nginx configuration for projectmaumercadocomserver server name projectmaumercadocom access log homeubuntulogsprojectnginxaccesslog error log homeubuntulogsprojectnginxerrorlog location uwsgi pass unixtmpuwsgisock include etcnginxuwsgi params location static root homeubuntudjangoprojectsprojectprojectmedia location media root homeubuntudjangoprojectsprojectprojectmedia and my uwsgiconf file etcinituwsgiconf description uwsgi starterstart on localfilesystems and runlevel 2345stop on runlevel 016respawn home is the path to our virtualenv directory pythonpath the path to our django application module the wsgi handler python scriptexec homeubuntuveprojectbinuwsgi uid wdata pythonpath homeubuntudjangoprojectsprojectprojectconfigsstaging socket tmpuwsgisock chmodsocket module wsgi logdate optimize 2 processes 2 master logto homeubuntulogsprojectuwsgilognginx logs does not state anything besides a 500 in accesslog so heres the uwsgilogmon feb 6 135823 2012 starting uwsgi 1021 32bit on mon feb 6 135823 2012 mon feb 6 135823 2012 compiled with version 445 on 06 february 2012 123236mon feb 6 135823 2012 current working directory mon feb 6 135823 2012 detected binary path homeubuntuveprojectbinuwsgimon feb 6 135823 2012 setuid to 10mon feb 6 135823 2012 your memory page size is 4096 bytesmon feb 6 135823 2012 chmod socket to 6 for lazy and brave usersmon feb 6 135823 2012 uwsgi socket 0 bound to unix address tmpuwsgisock fd 3mon feb 6 135823 2012 python version 266 r26684292 sep 15 2010 160257 gcc 445mon feb 6 135823 2012 set pythonhome to homeubuntuveprojectmon feb 6 135823 2012 python main interpreter initialized at 0x9a9d740mon feb 6 135823 2012 your server socket listen backlog is limited to 100 connectionsmon feb 6 135823 2012 operational mode preforking mon feb 6 135823 2012 added homeubuntudjangoprojectsproject to pythonpathimporterror no module named wsgimon feb 6 135823 2012 unable to load app 0 mountpoint callable not found or import errormon feb 6 135823 2012 no app loaded going in full dynamic mode mon feb 6 135823 2012 uwsgi is running in multiple interpreter mode mon feb 6 135823 2012 spawned uwsgi master process pid 551mon feb 6 135823 2012 spawned uwsgi worker 1 pid 588 cores 1mon feb 6 135823 2012 spawned uwsgi worker 2 pid 589 cores 1i do not know if the way i set up my project has anything to do with it but anyways heres the manage file that i use to redirect django utilitiesmanageshbinbashpython projectconfigsdeployment targetcommonmanagepy and just in case this is how i have set up a django projectprojectmanagesh this fellow is redirected to settingspy production common or stagingrequirementstxtreadmedashbardpyprojectsqlite project apps accounts other internal apps configs common for local development settingspy managepy urls staging managepy settingspy wsgipy loggingconf production managepy settingspy wsgipy loggingconf media templates,['python'] +246312,python property gettersetter confusion i am a bit confused about properties in python consider the following codeclass a property def nself printa getter return self n nsetter def nselfv printa setter self and v def init self self and 1class b property def nself printb getter return selfan nsetter def nselfv printb setter selfan v def init self selfa aif name main bb bn 2 printbn ban bn 3 printbn banb should be something like a wrapper for a it uses getters and setters to map as properties on itself of course one could also do it via inheritancethe problem is that it simply does not work as expected in python26 while it does in python3 python2 testpya getter2 1a getter3 1 python3 testpyb settera setterb gettera gettera getter2 2b settera setterb gettera gettera getter3 3am i doing anything wrong or where exactly is the problem,['python'] +246314,how can a connection started with nsurlconnection while in the foreground be continued in the background i have been searching for literally weeks to try to find an answer or an example of how to do thisall the examplestutorials for nsurlconnection show it starting in the foreground or starting in the background ditto all the examples for beginbackgrountaskwithexpirationhandler show how to start a background task after entering the backgroundas far as i can tell there is nothing out there on the internet or books that shows how to start a connection while in the foreground and then if its not finished continue it in the backgroundthe answer to this question does not actually answer the questionhow should beginbackgroundtaskwithexpirationhandler be dealt with for an nsurlconnection that is already in progressif you read the referened beyond the basics section it says while the app is in the foreground the background task would not have any effect this means it is not possisble to start a background task using nsurlconnection while in the foreground if you want to download in the foreground,['ios'] +246317,whats the significance of 532459699 this is a number that is returned as an exit code in many net exceptions particularly com exceptions i thinkin this question someone used reflector to find out that this value was initialized to a private variable in nearly every exception constructormy question is why what significance does this number have it is hard to believe that it was chosen arbitrarily i do not even see any numeric significance eg in its binary or hex representation,['.net'] +246322,the onclick of clickablespan is not working for urlspan in a textview i want to popup a toast whenever a hyperlink is clicked instead of opening the corresponding url in a browser i use the following code but the problem here is the onclick method seems never be calledstring source a hreflinka get spannablestringbuilder object from html codecharsequence sequence htmlfromhtmlsource imggetter nullspannablestringbuilder strbuilder new spannablestringbuildersequence get an array of urlspan from spannablestringbuilder objecturlspan urlspans strbuildergetspans0 strbuilderlength urlspanclass add onclick listener for each of urlspan objectfor final urlspan span urlspans int start strbuildergetspanstartspan int end strbuildergetspanendspan strbuildersetspannew clickablespan override public void onclickview widget toast toast toastmaketextcontext well done you click spangeturl toastlength short toastshow start end spannedspan exclusive exclusivetextview t4 textview findviewbyidridtext4t4settextstrbuilder no action if this is not sett4setmovementmethodlinkmovementmethodgetinstancecan anyone tell me whats wrong with my code and how to fix it thanks,['android'] +246334,custom columns using django admin i have a model data associated to a table like this the model data is made up of only integerfieldsubject year quarter sales 1 2010 1 20 1 2010 2 100 1 2010 3 100 1 2010 4 20 1 2011 1 30 1 2011 2 50 1 2011 4 40 2 2010 1 30 2 2010 2 20 go on this wayi want to have a djangoadmin table in readonly having columns current year 2011 quarter 1subject sales current year sales current quarter sales last year sales current quarter last year 1 110 30 240 20and so onthe question is it is possible do that using djangoadmin whats the way out,['python'] +246356,self organizing applications i have the following requirements for an application that many people will be using in the office no server component all instances of client apps should somehow negotiate between themselves to decide which client will take on the server role and the clients should communicate between themselves via ipif and when the client app goes down another client must take over in a seamless manner i understand that having a server would be much much simpler but because the app must be very resilient the powers that be do not want to risk server going down or even its backup and rather rely on this hybrid mesh connectivity where the server role hops from client to client i think i got the app connectivity down basically when the app starts it announces itself via udp either to a predefined ip address that everything listens to or via udp broadcast from there on the communication proceeds in a similar mannerthe part i am having problems with is how to negotiateselforganize between the clients to pick one with a server role and how to reliably detect that a client has gone down and then a new negotiation must take place the final difficulty is replicating data that is been accumulated by the client with a server role i created a prototype in c that communicates and tries to replicate data but the negotiation part particularly coupled with an client failure initially i thought that is what zeroconf aka bonjour did but that just announces available network services anyway i do not want to reinvent and i cannot be the first person to want to do this so my questionsis there a pattern that already implements what i described aboveif so is there an available net or even native library for thiswhat are good ways to negotiate server role among the clients,['c#'] +246389,convert rgba png to rgb with pil i am using pil to convert a transparent png image uploaded with django to a jpg file the output looks brokensource filecodeimageopenobjectlogopathsavetmpoutputjpg jpegorimageopenobjectlogopathconvertrgbsavetmpoutputpngresultboth ways the resulting image looks like thisis there a way to fix this i would like to have white background where the transparent background used to besolutionthanks to the great answers i have come up with the following function collectionimport imageimport numpy as npdef alpha to colorimage color255 255 255 set all fully transparent pixels of an rgba image to the specified color this is a very simple solution that might leave over some ugly edges due to semitransparent areas you should use alpha composite with color instead source keyword arguments image pil rgba image object color tuple r g b default 255 255 255 x nparrayimage r g b a nprollaxisx axis1 ra 0 color0 ga 0 color1 ba 0 color2 x npdstackr g b a return imagefromarrayx rgbadef alpha compositefront back alpha composite two rgba images source keyword arguments front pil rgba image object back pil rgba image object front npasarrayfront back npasarrayback result npemptyfrontshape dtypefloat alpha npindex exp 3 rgb npindex exp 3 falpha frontalpha 2550 balpha backalpha 2550 resultalpha falpha balpha 1 falpha old setting npseterrinvalidignore resultrgb frontrgb falpha backrgb balpha 1 falpha resultalpha npseterrold setting resultalpha 255 npclipresult 0 255 astypeuint8 maps npnan and npinf to 0 result resultastypeuint8 result imagefromarrayresult rgba return resultdef alpha composite with colorimage color255 255 255 alpha composite an rgba image with a single color image of the specified color and the same size as the original image keyword arguments image pil rgba image object color tuple r g b default 255 255 255 back imagenewrgba sizeimagesize colorcolor 255 return alpha compositeimage backdef pure pil alpha to color v1image color255 255 255 alpha composite an rgba image with a specified color note this version is much slower than the alpha composite with color solution use it only if numpy is not available source keyword arguments image pil rgba image object color tuple r g b default 255 255 255 def blend valueback front a return front a back 255 a 255 def blend rgbaback front result blend valuebacki fronti front3 for i in 0 1 2 return tupleresult 255 im imagecopy do not edit the reference directly p imload load pixel array for y in rangeimsize1 for x in rangeimsize0 px y blend rgbacolor 255 px y return imdef pure pil alpha to color v2image color255 255 255 alpha composite an rgba image with a specified color simpler faster version than the solutions above source keyword arguments image pil rgba image object color tuple r g b default 255 255 255 imageload needed for split background imagenewrgb imagesize color backgroundpasteimage maskimagesplit3 3 is the alpha channel return backgroundperformancethe simple noncompositing alpha to color function is the fastest solution but leaves behind ugly borders because it does not handle semi transparent areasboth the pure pil and the numpy compositing solutions give great results but alpha composite with color is much faster 893 msec than pure pil alpha to color 796 msec if numpy is available on your system that is the way to go update the new pure pil version is the fastest of all mentioned solutions python m timeit import image from appsfront import utils i imageopenulogopng i2 utilsalpha to colori10 loops best of 3 467 msec per loop python m timeit import image from appsfront import utils i imageopenulogopng i2 utilsalpha composite with colori10 loops best of 3 893 msec per loop python m timeit import image from appsfront import utils i imageopenulogopng i2 utilspure pil alpha to colori10 loops best of 3 796 msec per loop python m timeit import image from appsfront import utils i imageopenulogopng i2 utilspure pil alpha to color v2i10 loops best of 3 11 msec per loop,['python'] +246408,in eclipse how do i get the debugger to show all stack frames without clicking expand on each of the threads i have a server that has 100 running threads and i would like to know if there is a easy way to expand all threads to show their stack frames in one click,['java'] +246411,how do i identify the part of speech of a word within a nsstring the app i am currently working on requires me to determine the part of speech of a word in nsstringso basically is there a librarydatabaseclass which you can access in objective c which allows one to check if a single word in the form of a nsstring is a noun an adjective an adverb or a verbsomething along the lines ofnsstring foocatif foo worthisnoun do somethingon a similar but slightly unrelated note is it possible to check if two nsstring containing verbs of the same stem but different tense ask asking asked etc have the same stem it would be very useful as well,"['iphone', 'objective-c', 'ios']" +246430,how to create borderless buttons in android the android design guidelines say to use borderless buttons see picture below but do not really explain how someone asked this same question a few weeks ago here how to create standard borderless buttons like in the design guidline mentioned and there was an answer marked as the answer but i am still lost and i do not see a way to add comments to a question that has been closedthe answerer said look into the theme attributes buttonbarstyle buttonbarbuttonstyle and borderlessbuttonstylebut i still cannot figure out how to actually use those things i googled around a bit and could not find anything so i figured i would just ask the question again and hopefully someone can provide a little more detail on how this works,['android'] +246440,implicit declaration using stdc99 i am getting this warning stdc99 pedanticwarning implicit declaration of function astrndupa wimplicitfunctiondeclarationbut i am importing these libsinclude stdiohinclude stdlibhinclude stringhso what filec include fileh strndup fileh include stdioh include stdlibh include stringh,['c'] +246463,how do you automagically minify your js and css on os x or in webstorm i use two different ides based on what i am doing my primary ide is visual studio whereby i use chirpy to mash and minify my code it works flawlessly and i love it problem is that when i am not on my windows box i do not have access to itwhen not using visual studio i am usually writing javascript apps in webstorm on my macbook pro here in lies the problem i have not found a webstorm plugin or any other app that i can configure to watch my scripts and mashminify themhow do you mac users mashminify your js and css at design time with minimal effort,"['javascript', 'css']" +246474,why using intptr for handle when using pinvoke i noticed that we need to use intptr to refer to windows handles i am wondering why not just use int for the handle my understanding of a handle is that it is just an integer value,"['c#', '.net']" +246476,why is my iis 7 refusing to serve up css or js when i change enable 32bit applications to false i have a very simple web application aspnet mvc3 net 4 using iis not visual studios embedded server 64bit windows 7 when i change the settings in the application pool for my application and set enable 32bit applications to false my applications view shows up but none of the static content contentsitecss or scriptsmyscriptjs shows up instead i get status code 500 on those requestshttp error 50 internal server errorthe page cannot be thisplayed because an internal server error has occurredthe reason i am changing this value is that i am trying to use the 64bit oracledataaccessdll and if i have this value set to true it causes the application pool to run in wow64 mode and it tries to load the dll with the wrong formati have searched online for a while and cannot find very much info about this i have tried playing with permissions on the files i have tried running aspnet regiis with all kinds of flags i am out of ideas why would not iis serve up this static content when running in 64bit mode,['asp.net'] +246503,jqgrid all rows in inline edit mode by default i have a jqgrid where a row is editable on click ie editrow inside onselectrow works fine but my requirement is to load the grid with all rows in edit mode by default inline edit so there should not be any need for me click individual rows can someone throw some lights oni tried the below code but didnt workvar data val mygridgetrowdatafor var i0idata vallengthimygrideditrowdata vali true,['jquery'] +246514,when is reading and writing to memory legal please correct me if i am wrong i am asking this question to clarify some ideas that i havetoday in school i learned that when a process program executes then the operating systems gives it a space in memory so take for instance this two programsprogram1 static void mainstring args unsafe in debug options on the properties enable unsafe code int a 2 int pointer 1 a create pointer1 to point to the address of variable a breakpoint in here in the debug i should be able to see the address of pointer1 copy it and type it in the console string hexvalue consolereadline convert the hex value to base 10 int decvalue intparsehexvalue systemglobalizationnumberstyleshexnumber create a new pointer that point to the address that i typed in the console intptr pointer 2 new intptrdecvalue consolewritelinethe address of a 0 value 1 inta a try consolewritelinethe address of 0 points to value 1 intpointer 1 intpointer 2 different approach of acomplishing the same consolewritelinemarshalreadint32pointer 2 catch consolewritelineyou are supposed to be debuging this program program 2 static void mainstring args unsafe intptr pointer 0 new intptr95151860 see address of variable from program1 int pointer 1 intpointer 0 try to access programs 1 object consolewritelineaddrees of 0 points to value 1 intpointer 1 pointer 1 so i understand that in program 2 i will get an error i will be accessing restricted memory so far what i have learned makes sense ok know here is where things do not make sensethere is a very nice program called autoit used to automate tasks for example it can send mouse clicks move the mouse send key strokes etcanyways autoit comes with a program called autoit window info where that program enables you to get the handles pointers of controls on windows for example i could see the handle of the windows control by draging the finder tool to the control that i wish on getting informationint this picture i am dragging the finder tool to the calculators input control i could also drag it to button 7 for instance so if you see in the picture i now have the address of that control i could then be able to access it from my programyet another example of how you can access memory that does not belong to my programstep 1 get the pointer of any window with autoit window infostep 2 in my computer that pointer is that is the window of google chrome the place where i am typing this questionthis class will send a window to the back public static class sendwndtoback dllimportuser32dll static extern bool setwindowpos intptr hwnd intptr hwndinsertafter int x int y int cx int cy uint uflags const uint32 swp nosize 0x01 const uint32 swp nomove 0x02 const uint32 swp noactivate 0x0010 static readonly intptr hwnd bottom new intptr1 static readonly intptr k new intptr12 public static void windowhandleintptr windowhandle setwindowposwindowhandle hwnd bottom 0 0 0 0 swp nosize swp nomove swp noactivate and then if i call the method with the poniter that i just got with the help of autoit and call it as sendwndtobackwindowhandlenew intptr0x0510b2then i will send that window to the backi post some examples in order to ilustrate my point but my question is when are you allowed to access other parts of the memory if i make my variable public other programs will be able to access it why can i access some controls of windows from my own program,['c#'] +246516,how do i set textarea scroll bar to bottom as a default i have a textarea that is being dynamically reloaded as user input is being sent in it refreshes itself every couple seconds when the amount of text in this textarea exceeds the size of the textarea a scroll bar appears however the scroll bar is not really usable because if you start scrolling down a couple seconds later the textarea refreshes and brings the scroll bar right back up to the top i want to set the scroll bar to by default show the bottom most text anyone have an idea of how to do so,"['javascript', 'css']" +246561,python opencv cvwaitkey spits back weird output on ubuntu modulo 256 maps correctly i am running ubuntu 10 lenovo t400 with opencv 22 i believe as imports are done as import cv2cv as cv this problem also happens if i just import cv insteadi recently started having this problem and it is kind of a weird one i do not know anything significant i did i have restarted since it started happening i installed a couple programs but i do not think those would affect thiswhen i run with an artificial image showing just a black image i try to poll cvwaitkey10 it spits back garbageheres my opencv codeimport cv2cv as cvimport timecvnamedwindowcamera 1img cvcreateimage400400 8 3valkeys range1255f openhomeandrewwebuploadskeyboardtest wbwhile true cvshowimagecamera img k cvwaitkey10 if k is 1 pass else print writing s strk fwritestrk fcloseheres the output i get from the program1048678 1048676 1048673 1048691 1048676 1048678 1048689 1048695 1048677 1048688 1048687 1048681 1048677 1048677 1048695 1048624 1048633 1048690 1048633 1048624 1048695 1048677 1048690 1048624 1048633 1048681 1048677 1048681 1048688 1048687 1048677 1048681 1048692 1048688 1048681 1048688 1048687 1048681 1048681 1048688 1048687 1048585 1048687 1048681 1048688 1048687 1048681 14085 1179728 1179727 1179721 1179728 1179721 1245153 1245289 1179727 1179721 1179727 1179721 1179728 1179727 1245155 1441865 1179728 1179727 1179721 1179728 1179727 1179721 1179728 1179727 1179718 1179721 1179716 1179728 1179727 1179731 1179721 1179713 1179728 1179727 1179687 1179723 1179716 1179736 1179724 1179715 1179734 1179725 1179692 1179736 1179738 1179725 1179715 1179734 1179692 1245155 1441859 now i can modulo 256 these numbers and get somewhat sensible results out just tried it it correctly identified all my keys however why would i need to do this it did work previously without doing anything print chrk would give me a letter anyone have any ideas,['python'] +246565,wcf datetimeoffset compatibility i have a net wcf service with a few operation contracts that takes a datetimeoffset the idea is to avoid any confusion with dst and time zoneshowever i am in doubt that using datetimeoffset is a good idea after all since it is fairly nonstandard and would cause headaches for anyone trying to connect with say a java application or a net application bound to an older net versionan alternative is to expect a utc datetime but this introduces the risk that someone will forget to use utc time and call the service with a local timei could also expect a local time datetime since clients will always be in the same timezone but this leaves some subtle but classic ambiguity around dst changesdoes anyone have headache stories with datetimeoffset in a service interface or is it relatively unproblematic to use after all,['.net'] +246572,rails strategies for internationalization of large amounts of text and some html i am creating a website that will be in english chinese and korean there are large portions of layout and text on certain pages for example the about page this page will have many headers many paragraphs of text and some layoutwhats the recommended way to internationalize my website all the examples i have seen are for short bits of text or text for buttonslinks and the likeis my only option to have a ton of keyvalue pairs in my locales yaml files or is there a better way of doing this currently i have a keyvalue in my yaml with the key ending in html so i can have html in the key but it all has to be on one line so it is quite ugly hard to maintain and error prone,['ruby-on-rails'] +246584,deployinginstalling an outlook addin i am trying to install my outlook addin on client computersunfortuantely the addin can never be enabled it is always shown in the thisabled addin sectionis there a simple step by step guide on how to create the correct setup application and install an outlook addineditok so ive gone back to basics but i still cant get it to install correctlyi create a new outlook addin using vs2010 project wizardit generates files etc and then i change my code like sonamespace outlookaddin1 public partial class thisaddin private void thisaddin startupobject sender systemeventargs e messageboxshowworked private void thisaddin shutdownobject sender systemeventargs e region vsto generated code summary required method for designer support do not modify the contents of this method with the code editor summary private void internalstartup thisstartup new systemeventhandlerthisaddin startup thisshutdown new systemeventhandlerthisaddin shutdown endregion if i install this one i get the same error messagenot loaded the managed addin loader failed to initializewhen installing the addin i ensure the registry keys are createdi have also added the manifest file and the vsto file to the setup projectstill stumped,['c#'] +246588,inconsistent object deallocation with arc i was playing around with memory deallocation stuff on a simple command line app for mac osx 107 built using xcode version 421 with arc enabled and the default build settings i cannot explain the behaviour i am getting from what i understand about arc so i am hoping someone can explain whats going on herefirst off in the following code i am getting the behaviour i expect please note that the nlog output is given in the comment after the corresponding statementimport foundationfoundationhint main int argc const char argv nsobject objptr1 nsobject alloc init nsobject objptr2 objptr1 weak nsobject weakref objptr1 nslog objptr1 description nsobject 0x1001107d0 objptr1 nil nslog objptr2 description nsobject 0x1001107d0 objptr2 nil nslog weakref description null return 0so in the above right after weakref is assigned the nsobject instance has two strong pointers to it and therefore a retain count of 2 after zeroing objptr1 there is still one retaining pointer to the instance so it is still in memory and responds to the description message after niling objptr2 there are no strong pointers to the object and it is deallocated i am assuming it is since weakref has been zeroed so far so goodnow the same code with a small changeimport foundationfoundationhint main int argc const char argv nsobject objptr1 nsobject alloc init nsobject objptr2 objptr1 unsafe unretained nsobject weakref objptr1 unsafe unretained instead of just weak nslog objptr1 description nsobject 0x1001107d0 objptr1 nil nslog objptr2 description nsobject 0x1001107d0 objptr2 nil nslog weakref description nsobject 0x1001107d0 why was the object instance not deallocated and the preceding statement not crash the program return 0i was expecting weakref to become a dangling pointer sending a message through which would cause the program to crash in the third nslog statement but it seems the object instance is still alive and wellanother thing i find weirdimport foundationfoundationhint main int argc const char argv nsobject objptr1 nsobject alloc init nsobject objptr2 objptr1 weak nsobject weakref objptr1 weak again nslog weakref description nsobject 0x1001107d0 objptr1 nil nslog weakref description nsobject 0x1001107d0 objptr2 nil nslog weakref description nsobject 0x1001107d0 return 0this last code is like the first one using the zeroed weak pointer the only difference is that the description message was sent to the object through weakref in each of the three nslog calls but this time round the object is not deallocated even after the two strong references have been removed since it is still responding to messages through weakrefso whats going on here,['objective-c'] +246595,linq combining join and group by i have a query that combines a join and a group but i have a problem the query is like var result from p in products join bp in baseproducts on pbaseproductid equals bpid group p by psomeid into pg select new productpriceminmax someid pgfirstordefaultsomeid countrycode pgfirstordefaultcountrycode minprice pgminm mprice maxprice pgmaxm mprice baseproductname bpname cannot use bp as you see it joins the products table with the baseproducts table and groups on an id of the product table but in the resulting productpriceminmax i also need a property of the baseproducts table bpname but it does not know bp any idea what i am doing wrongthanks,['c#'] +246597,python networkx i need help since i am not expert in programminghow can i draw a planar graph a graph is said to be planar if it can be drawn in the plane such that there are no edgecrossings for a given graph with and nodes and e edges and then flip the edges to have another planar graph for loop until we get all the possibilities thanks in advanceand i appreciate your helppyvisualize with pygraphviz apgvagraph file stdin line 6 apgvagraph syntaxerror invalid syntax aadd edges fromgedges traceback most recent call last file stdin line 1 in module nameerror name a is not defined alayoutprogdot traceback most recent call last file stdin line 1 in module nameerror name a is not defined adrawplanarpng traceback most recent call last file stdin line 1 in module nameerror name a is not defined,['python'] +246601,why cannot you develop xna games in vbnet i know there is no vbnet project type for the xna games but as a simple test i threw together a vb solution which references microsoftxna it has a class which implements microsoftxnaframeworkgame then in the c game1cs i simply removed all the boilerplate code and modified it to inherit from my vb classnamespace mygame public class game1 gameengineengine which is inheritingpublic class engine inherits microsoftxnaframeworkgame protected overrides sub updategametime as microsoftxnaframeworkgametime if gamepadgetstateplayerindexonebuttonsback buttonstatepressed then meexit end if for each element in elements elementupdategametime next mybaseupdategametime end sub this seems to work and i have been able to load content render a model take gamepad input etcso what i am asking is is there really a restriction due to some advanced features not supported in vbnet or is it merely that no project templatessupport are availableis there some performance optimisation when compiling to msil that the vb compiler misses,['.net'] +246617,html to chm file under linux i have html filesdirectories i want to convert them to chm help file under linux using command lines at terminal any help would be appreciated,['html'] +246676,sqlite browser goes non responsive while inserting data into sqlite i am developing and android application for elearning purposenow in this application i want to store the questions and answers in the sqlite databasemy following query works fine when the questionanswer is of 1 line onlybut application hangs when i try to enter a multiline answerplease help me how to resolve it or suggest any other option for doing thisquery this works fine insert into ques ans values3what are the principle concepts of oops object oriented programming organizes a program around its dataeditwhile querying following data sqlite browser hangsinsert into ques ans values3what is the java java is a programming language and computing platform first released by sun microsystems in 1995there are lots of applications and websites that would not work unless you have java installed and more are created every day java is fast secure and reliable from laptops to datacenters game consoles to scientific supercomputers cell phones to the internet java is everywhere it is the underlying technology that powers stateoftheart programs including utilities games and business applicationswhile i try to insert the above mentioned multiline data no row is created in my sqlite table,['android'] +246681,navigate and post data from silverlight my project is silverlight navighation project inbrowseri want to navigate to an url such as systemwindowsbrowserhtmlpagewindownavigatenew uristringformathttp01reportprojectaspxsuppliesrequestgoodsrequestgoodsdashboard applicationcurrenthostsourcehost applicationcurrenthostsourceport blank and send many parameters with post method to target pagehow i can do this,['c#'] +246682,how does jboss forge compares to spring roo i have just found out jboss forgei wonder how it compares with spring roocan anybody highlight the principal coincidences and differences of these two tools,['java'] +246711,how to test if array pointer is at first element in foreach loop in a for loop it is simplefor idx 0 idx count array idx if idx 0 this is the first element of the array how the hell is this done in a foreach loopis there a function like is first or somethingi am looking for something likeforeach array as key value if is the first element do logic on first element else all other logic i was thinking i could set a bool like is first true and then as soon as the loops been iterated once set the bool to falsebut php has a lot of prebuilt functions and id rather use that or another waythe whole bool way seem almost like cheeting scheers alex,['php'] +246728,when to use an eventstore i am not quite sure i understood what an eventstore is i thought of it as some kind of transactionlog for domainobjects what are the advantagesthisadvantages of it and what are good scenarios to use it and when should not it be usededitsince i may be asking too much i would be happy if there would be a simple scenario when to use an eventstore and when not in other words is it possible to describe the 2 scenarios in just some sentences or do i need to read 5 books to understand it,['.net'] +246741,python utf16 csv reader i have a utf16 csv file which i have to read python csv module does not seem to support utf16i am using python 272 csv files i need to parse are huge size running into several gbs of dataanswers for john machin questions belowprint repropentestcsv rbread100output with testcsv having just abc as contentxffxfeax00bx00cx00i think csv file got created on windows machine in usa i am using mac osx lionif i use code provided by phihag and testcsv containing one recordsample testcsv content used below is print repropentestcsv rbread10 outputxffxfe1x00x002x00x00gx00x00sx00x00hx00 x00fx00xfcx00rx00 x00ex00 x00x96x00 x00mx00 x00x85x00x00x00ix00rx00nx00code by phihagimport codecsimport csvwith opentestcsvrb as f sr codecsstreamrecoderfcodecsgetencoderutf8codecsgetdecoderutf8codecsgetreaderutf16codecsgetwriterutf16 for row in csvreadersr print rowoutput of the above code1 2 g s h fxc3xbcr e xc2x96 m xc2x85 iexpected output is1 2 g s h fxc3xbcr e xc2x96 m xc2x85i,['python'] +246791,is it acceptable style for nodejs libraries to rely on object key order enumerating the keys of javascript objects replays the keys in the order of insertion for key in z1a1b consolelogkey zabthis is not part of the standard but is widely implemented as thiscussed hereecma262 does not specify enumeration order the de facto standard is to match insertion order which v8 also does but with one exceptionv8 gives no guarantees on the enumeration order for array indices ie a property name that can be parsed as a 32bit unsigned integeris it acceptable practice to rely on this behavior when constructing nodejs libraries,['javascript'] +246829,is onload equal to readystate4 in xmlhttprequest i am confuse about the xhr return event as i can tell there are not so much different between onreadystatechange readystate 4 and onload is it truevar xhr new xmlhttprequestxhropenget url falsexhronreadystatechange function if xhrreadystate 4 do some thing xhrsendnullorxhronload function do something,['javascript'] +246836,c static member pointer to function how to initialize it i have a static pointer to function like the following in my class but i am not sure how to instantiate itclass foo private static double my ptr fundoubledouble,['c++'] +246845,autodetect character encoding in java seems to be a fairly hit issue but i have not yet been able to find a solution perhaps because it comes in so many flavors here it is though i am trying to read some comma delimited files occasionally the delimiters can be a little bit more unique than commas but commas will suffice for nowthe files are supposed to be standardized across the industry but lately weve seen many different types of character set files coming in i would like to be able to set up a bufferedreader to compensate for thiswhat is a pretty standard way of doing this and detecting whether it was successful or notmy first thoughts on this approach are to loop through character sets simplecomplex until i can read the file without an exception not exactly ideal thoughthanks for your attention,['java'] +246864,c directory watching how to detect copy has ended i have a folder to which files are copied i want to watch it and process files as soon as they are copied to the directory i can detect when a file is in the directory whether through polling my current implementation or in some tests using windows apis from a few samples i have found onlinethe problem is that i detect when the file is first created and its still being copied this makes my program that needs to access the file through errors because the file is not yet complete how can i detect not when the copying started but when the copying ended i am using c on windows so the answer may be platform dependent but if possible i would prefer it to be platform agnostic,['c++'] +246868,android emulator failed to pull selection android 22 emulator when i am trying to pull a file from ddmsfile explorer it says20120208 025252 failed to pull selection20120208 025252 nullwhy and what to do with it,['android'] +246874,applying different css class on click using jquery i am currently setting up a wordpress site using this template from themeforest and here is the live preview of what i am currently working on which now should be working please let me know if it is not workingi configured the css so the left border when hovered would be the light gray color then when the link was clicked on the left border would then be the blue color i selectedas shown below the main problem i am having with the navigation is in the css the portfolio link portfolio section in picture still has the selected class being applied along with the internal unordered list item i would like to have it look like the blog section in the picture where the blog link no longer applies the selected class itemi asked the creator of the template why this was occurring his response was there needs to be another link below that contained the title attribute allportfolio so it would work properly i tried adding this attribute to the main portfolio link but then closed the list completelywhen the menu is created the browser creates the portfolio selection the following way in htmlul classmainmenu idmenumainmenu li classparent selected idmenuitem1172 pa hrefhttplocalhostportfolio stylecolor rgb57 57 57portfolioap div ul clasubmenu li classmenuitem idmenuitem1158pa datafilterwebsitedesign datacategorytrue hrefwebsite designapli li classmenuitem idmenuitem1157pa datafilterprint datacategorytrue hrefprintapli li classmenuitem selected idmenuitem1156pa datafiltermotion datacategorytrue hrefmotionapli li classmenuitem idmenuitem1155pa datafilteridentity datacategorytrue hrefidentityapli li classmenuitem idmenuitem1167pa datafilterlogos datacategorytrue hreflogosapli ul div lii tried to so something similar to this answer but did not work since it did not seem to include anything within the list item the following jquery code below is my attemptportfolio links remove selected css setting ulmenumainmenu ulsubmenu li p aclick function ulmenumainmenu liremoveclassparent selected thisaddclassparent menuitem i feel stuck because i cannot figure out how to have the html look like below taking out the css class selected and add the css class menuitemul classmainmenu idmenumainmenu li classparent menuitem idmenuitem1172 pa hrefhttplocalhostportfolio stylecolor rgb57 57 57portfolioap div ul clasubmenu li classmenuitem idmenuitem1158pa datafilterwebsitedesign datacategorytrue hrefwebsite designapli li classmenuitem idmenuitem1157pa datafilterprint datacategorytrue hrefprintapli li classmenuitem selected idmenuitem1156pa datafiltermotion datacategorytrue hrefmotionapli li classmenuitem idmenuitem1155pa datafilteridentity datacategorytrue hrefidentityapli li classmenuitem idmenuitem1167pa datafilterlogos datacategorytrue hreflogosapli ul div liupdate limelights answer seemed to work but i found some jquery that affects the link hover effects on the website and was not sure if that was the reason the answer to the code was not working is in the scriptsjs file of the wordpress template links roll over effect aeachfunction ifthisdatafilter thisparentparentparenthasclasspagination thishoverfadecolor also i am very close to what i want to accomplish using this code to finally keep the internal links openportfolio links remove selected css setting ulmenumainmenu li div ulsubmenufirst limenuitem p aclick function ulmenumainmenu liremoveclaselected ulmenumainmenu licsscolor 2addclassmenuitem ulmenumainmenu li divfirstshow but what it is still doing as seen below is that it still has the text chosen like the selected textany help is greatly appreciated,"['jquery', 'css']" +246894,vertical qlabel or the equivalent i want axis labels for a plot i am making and naturally the yaxis label should be oriented vertically i am pretty sure qwtplot does this but i am trying to keep things light so i am just using a simple qwidget qpainter for now i did not see any way to change qlabel orientation in the documentation some solutions are given in this 2002 thread but i would like something that does not seem like such a hack i am using qt 48 now is there really no way to do this aside from qpainterdrawtext,['c++'] +246896,android edittext default numeric keyboard and allow text possible duplicateedittext with number keypad by default but allowing alphabetic characters wondering if it is possible to default to a numeric keyboard on focus for an edittext field but also allow users to input characters none of the input types seem to support thisthanks,['android'] +246903,linking error when building google test on mac commandline i am currently trying to build some test code that uses google c test framework but i keep getting an error stating ld warning in usrlocalliblibgtestdylib file was built for unsupported file format which is not the architecture being linked i386i have tried to make the issue as simple as possiblei have a main functioncmtestccinclude gtestgtesth main entry point int mainint argc charargv charenvarg testinginitgoogletestargc argv returnrun all testsreally basic test codecrazytestccinclude gtestgtesthtestcrazytest one expect eq2 2i use the following commands to build gtest and my test codeg o crazytesto c wall werrornonvirtualdtor pipe stdc98 fnortti fnoexceptions fnostrictaliasing wnodeprecated g arch i386 arch x86 64 mmacosxversionmin1054 dgtest has tr1 tuple0 dgtest has rtti0 ioptgtest160include crazytestccg o cmtesto c wall werrornonvirtualdtor pipe stdc98 fnortti fnoexceptions fnostrictaliasing wnodeprecated g arch i386 arch x86 64 mmacosxversionmin1054 dgtest has tr1 tuple0 dgtest has rtti0 ioptgtest160include cmtestccg o gtestallo c wall werrornonvirtualdtor pipe stdc98 fnortti fnoexceptions fnostrictaliasing wnodeprecated g arch i386 arch x86 64 mmacosxversionmin1054 dgtest has tr1 tuple0 dgtest has rtti0 ioptgtest160 ioptgtest160include optgtest160srcgtestallccar rc libgtesta gtestalloranlib libgtestag o cmtest arch i386 arch x86 64 mmacosxversionmin1054 crazytesto cmtesto lstdc lgtestthe final build step gives me the following error and i am unable to figure out why i am able to get the actual tests not the simple one shown to build on other oss the mac os leopard is giving me problems ld warning in usrlocalliblibgtestdylib file was built for unsupported file format which is not the architecture being linked i386undefined symbols for architecture i386 testingtesttest referenced from crazytest one testcrazytest one testin crazytesto crazytest one testcrazytest one testin crazytesto testinginternalasserthelperasserthelper referenced from crazytest one testtestbody in crazytesto testingtesttest referenced from crazytest one testcrazytest one testin crazytesto testinginternalgettesttypeid referenced from static initialization and destruction 0int intin crazytesto testingtestteardown referenced from vtable for crazytest one testin crazytesto testinginternaleqfailurechar const char const testinginternalstring const testinginternalstring const bool referenced from testingassertionresult testinginternalcmphelpereqint intchar const char const int const int constin crazytesto testingunittestgetinstance referenced from main in cmtesto testinginternalistruebool referenced from testinginternalscoped ptrstdbasic stringstreamchar stdchar traitschar stdallocatorchar resetstdbasic stringstreamchar stdchar traitschar stdallocatorchar in crazytesto testinginternalscoped ptrstdbasic stringchar stdchar traitschar stdallocatorchar resetstdbasic stringchar stdchar traitschar stdallocatorchar in crazytesto testingunittestrun referenced from main in cmtesto testinginternalasserthelperoperatortestingmessage const const referenced from crazytest one testtestbody in crazytesto testinginternalasserthelperasserthelpertestingtestpartresulttype char const int char const referenced from crazytest one testtestbody in crazytesto testingassertionsuccess referenced from testingassertionresult testinginternalcmphelpereqint intchar const char const int const int constin crazytesto testingtestsetup referenced from vtable for crazytest one testin crazytesto testinginternalmakeandregistertestinfochar const char const char const char const void const void void testinginternaltestfactorybase referenced from static initialization and destruction 0int intin crazytesto testinginitgoogletestint char referenced from main in cmtestold symbols not found for architecture i386collect2 ld returned 1 exit statuslipo cannot open input file vartmpcczqif8kout no such file or directoryi have defined arch i386 and arch x86 64 for everything i have built so i am unable to figure out what i have missed i do not do a lot of programming on macs and this particular issue has me stuck any suggestions would be helpful,['c++'] +246906,android badtokenexception when using a webview container so i followed a post on avoiding webview memory leaks which suggests to use a webview container and then programmatically addremove the webview from the container in activity codesmemory leak in webviewhowever i hit the following crash when clicking on an html element which prompts a list of options to select eg datemonth drop down menuwdalvikvm17767 threadid1 thread exiting with uncaught exception group0x4001d5a0wwindowmanager129 attempted to add window with nonapplication token windowtoken4094b730 tokennull abortingfatal exception mainandroidviewwindowmanagerbadtokenexception unable to add window token null is not for an application androidviewviewrootsetviewviewrootjava561 androidviewwindowmanagerimpladdviewwindowmanagerimpljava177 androidviewwindowmanagerimpladdviewwindowmanagerimpljava91 androidappdialogshowdialogjava265 androidwebkitwebviewinvokelistboxrunwebviewjava9170 androidoshandlerhandlecallbackhandlerjava587 androidoshandlerthispatchmessagehandlerjava92 androidoslooperlooplooperjava150 androidappactivitythreadmainactivitythreadjava4263 javalangreflectmethodinvokenativenative method javalangreflectmethodinvokemethodjava507 comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava839 comandroidinternaloszygoteinitmainzygoteinitjava597 dalviksystemnativestartmainnative methodi have the following in my layoutframelayout androidididwebview container androidlayout widthfill parent androidlayout heightfill parent androidlayout belowidtitlebarframelayouti have the following in oncreatemwebviewcontainer framelayoutfindviewbyidridwebview containermwebview new webviewgetapplicationcontextmwebviewcontaineraddviewmwebviewmwebviewsetwebchromeclientnew webchromeclienti also set a webviewclienti have verified that mwebviewgetwindowtoken does return a nonnull valueany ideas as to why this issue might be happeningediti have done some more experimenting and looking around but still have not solved this issue everything functions fine if i put the webview directly in the layout itself but i do not want to do that because i want to be able to dynamically swap webviews,['android'] +246964,find out the line row number of the cursor in a textarea i would like to find out and keep track of the line number rows of the cursor in a textarea the bigger picture is to parse the text on the line every time a new line is createdmodifiedselected if of course the text was not pasted in this saves parsing the whole text unnecessarily at set intervalsthere are a couple of posts on stackoverflow however none of them specifically answer my question most questions are for cursor position in pixels or thisplaying lines numbers besides the textareamy attempt is below it works fine when starting at line 1 and not leaving the textarea it fails when clicking out of the textarea and back onto it on a different line it also fails when pasting text into it because the starting line is not 1 my javascript knowledge is pretty limitedhtmlheadtitledevbugtitlescript typetextjavascript var total lines 1 total lines var current line 1 current line var old line count main editor function function codee declare some needed vars var keypress code ekeycode key press var editor documentgetelementbyideditor the editor textarea var source code editorvalue contents of the editor work out how many lines we have used in total var lines source codesplitn var total lines lineslength do stuff on key presses if keypress code 13 enter current line 1 else if keypress code 8 backspace if old line count total lines current line 1 else if keypress code 38 up if total lines 1 current line 1 current line 1 else if keypress code 40 down if total lines 1 current line total lines current line 1 else documentgetelementbyidkeycodesinnerhtml keypress code for some reason chrome does not enter a newline char on enter you have to press enter and then an additional key for and to appear making the total lines counter lag if total lines current line total lines 1 putput the data documentgetelementbyidtotal linesinnerhtml total lines total lines documentgetelementbyidcurrent lineinnerhtml current line current line save the old line count for comparison on next run old line count total linesscriptheadbodytextarea ideditor rows30 cols100 value onkeydowncodeeventtextareadiv idtotal linesdivdiv idcurrent linedivbodyhtml,['javascript'] +246968,programatically check an item in checkboxlist where text is equal to what i want in c i am trying to check an item in a checkboxlist where the text equals what i requirei would modify the code to check items that exist in the databaseif you would like an example i need to select the checklistbox item that equals to abc,['c#'] +246973,why a virtual call to a pure virtual function from a constructor is ub and a call to a nonpure virtual function is allowed by the standard from 104 abstract classes parag 6 in the standard member functions can be called from a constructor or destructor of an abstract class the effect of making a virtual call to a pure virtual function directly or indirectly for the object being created or destroyed from such a constructor or destructor is undefinedassuming that a call to a nonpure virtual function from a constructor or destructor is allowed by the standard why the difference edit more standards quotes about pure virtual functionsa 1042 a virtual function is specified pure by using a purespecifier 92 in the function declaration in the class definition a pure virtual function needs be defined only if called with or as if with 124 the qualifiedid syntax 51 note a function declaration cannot provide both a purespecifier and a definition aend note a 1249 a destructor can be declared virtual 103 or pure virtual 104 if any objects of that class or any derived class are created in the program the destructor shall be definedsome questions that need answering arewhere the pure virtual function has not been given an implementation should this not be a compiler or linker error insteadwhere the pure virtual function has been given an implementation why can it not be welldefined in this case to invoke this function,['c++'] +246978,decoding and understanding assembly code so a little background i am a beginner with c and assembly code we have an bomb assignment written in cwhich calls methods that require certain passwords but the code is not visible and i need to determine the correct password by looking at the assembly codethe code indicates the password for this method is 6 numbers which is passed as input to method phase 2 i am trying to avoid triggering the part i am getting confused on is is jumping from 64 to 42 it seems to be a loop but i am unsure how the stack is affected with each pass it looks like the loop exits if the last two numbers are the same and it has something to do with adding and subtracting 4 but i am unsure how the addresses are traversedif anyone can translate what exactly is going on or if i need to look in any particular registerslocations it would help greatly there are 4 more phases which are each supposed to be more complex so i want to get a good understanding in how to approach reading thesealso if anyone has a good resource like a printable table with assembly code keywords that would be helpful too and also if there are any differences between 32bit and 64bit registers i need to worry about other than the register names 82 phase 2inputgdb thisas phase 2dump of assembler code for function phase 20x040106b phase 20 push rbp0x040106c phase 21 push rbx0x040106d phase 22 sub 0x28rsp0x0401071 phase 26 mov rsprsi0x0401074 phase 29 callq 0x401457 read six numbers0x0401079 phase 214 cmpl 0x0rsp0x040107d phase 218 jne 0x401086 phase 2270x040107f phase 220 cmpl 0x10x4rsp0x0401084 phase 225 je 0x40108b phase 2320x0401086 phase 227 callq 0x401421 explode bomb0x040108b phase 232 lea 0x8rsprbx0x0401090 phase 237 lea 0x18rsprbp0x0401095 phase 242 mov 0x8rbxeax0x0401098 phase 245 add 0x4rbxeax0x040109b phase 248 cmp eaxrbx0x040109d phase 250 je 0x4010a4 phase 2570x040109f phase 252 callq 0x401421 explode bomb0x04010a4 phase 257 add 0x4rbx0x04010a8 phase 261 cmp rbprbx0x04010ab phase 264 jne 0x401095 phase 2420x04010ad phase 266 add 0x28rsp0x04010b1 phase 270 pop rbx0x04010b2 phase 271 pop rbp0x04010b3 phase 272 retq,['c'] +246980,recursively traverse nsdictionary of unknown structure has anyone done a recursive ordered traversal of an nsdictionary of unknown structure i would like to take any nsdictionary and process each level in hierarchical order1 this data is coming from validated json is it safe to say that the nsdictionary created from a framework such as sbjson json framework would only result in a combination of nested dictionaries arrays and arbitrary leafs2 how can a generic traversal be done using fast enumeration that works for both arrays and dictionaries with the code below once i get to a dictionary within an array it stops traversing however if i continue the recursion in the array condition to check for dictionaries within arrays it barfs on the next iteration of id value dict valueforkeykey with a nscfdictionary length unrecognized selector sent to instance sigabrt i do not know why this would be a problem because i already got past that line with a toplevel dictionary where the array of sublevel dictionaries were foundvoidprocessparsedobjectiddict counterinti parentnsstring parent for id key in dict id value dict valueforkeykey nslogi i value class parent key if value iskindofclassnsdictionary class i nsdictionary newdict nsdictionaryvalue self processparsedobjectnewdict counteri parentnsstringkey i else if value iskindofclassnsarray class for id obj in value nslogobj type obj class many thanks,"['iphone', 'ios']" +246998,how can i store a lambda expression as a field of a class in c11 i would like to create a class where the client can store a lambda expression like void as a field of the class but i cannot figure out how to do so one answer suggested using decltype which i tried with no success here is a ideone source link the below is the source and resultinclude cstdioauto voidlambda voidclass myclass public decltypevoidlambda t myclassdecltypevoidlambda t thist t int main myclass printfhi resultprogcpp in constructor myclassmyclasslambdaprogcpp379 error no matching function for call to lambda lambda0progcpp220 note candidates are lambdalambdaconstlambdaprogcpp220 note lambdalambdalambdaprogcpp388 error no match for operator in myclassthismyclasst tprogcpp in function int mainprogcpp527 error no matching function for call to myclassmyclassmainlambdaprogcpp348 note candidates are myclassmyclasslambdaprogcpp314 note myclassmyclassconst myclassdoes anyone know how to do this,['c++'] +247009,how to multiplex multiple blocking python generators into one consider the following pseudo codedef g user while true yield read user inputdef g socket while true yield read socket inputdef g combinedgu gs should read user or socket input whichever is available while true sel selectgu gs if selcontainsgu yield gunext if selcontainsgs yield gsnextgc g combined g user g socket how to implement this in easiest way,['python'] +247010,button height inconsistency crossbrowser i am having a problem whilst setting the height of a button basically i cannot manage to have it crossbrowser with firefox it is higher than normal without any reasonhere it is a screenshot firefox safari and opera in this orderand here the code i also tried adding some specific declarations i found on the web but actually they just reduced the height a bit but still they are not the same in the same orderand here the code how could i fix this,['css'] +247031,using alias for select as in sqlalchemy let us say i have a table shares with the following columnscompany price quantitymicrosoft 100 10google 99 5google 99 20google 101 15i would like to run the equivalent of a sql statement like thisselect price sumquantity as num from shares where companygoogle group by pricethe closest i have come isresult dbsessionquerysharesprice funcsumsharesquantityfiltersharescompany googlegroup bysharespricealli am having trouble with setting up the sumquantity as num in sqlalchemy it appears i need to use alias but i cannot figure out how by looking at the documentation i would be grateful if someone could show me how to do itmany thanks,['python'] +247092,animated cursor support in web applications do any web browsers support animated cursorsi have been searching the web to add custom cursors to my web application i have been finding a lot of non animated cur and animated ani cursors and using the correct css so that my application has custom cursors it seems that the animated cursors are not supported in the web browsers i tried and i was wondering if there is any way possible to put animated cursors into my web application,['css'] +247111,css thisplay inline vs inlineblock possible duplicatewhat is the difference between thisplay inline and thisplay inlineblock in css thisplay can have values of inline and inlineblock can anyone explain in detail the difference between inline and inlineblocki searched everywhere the most detailed explanation tells me inlineblock is placed as inline but behaves like block but it does not explain what exactly behave as a block means is it any special featurean example would be an even better answer thanks,['css'] +247121,pdo with pdostatement reconnect on mysql server gone error when mysqls wait timeout has been exceeded i lose connection on my php cli script i cannot change wait timeout so how would one build a trycatch statement that reconnects when i use pdostatement to execute my queries,"['php', 'mysql']" +247127,is there a set of lorem ipsums files for testing character encoding issues for layouting we have our famous lorem ipsum text to test how it looks likewhat i am looking for is a set of files containing text encoded with several different encodings that i can use in my junit tests to test some methods that are dealing with character encoding when reading text filesexamplehaving a iso 88591 encoded testfile and a windows1252 encoded testfile the windows1252 have to trigger the differences in region 8016 a 9f16 in other words it must contain at least one character of this region to thistinguish it from iso 88591maybe the best set of testfiles is that where the testfile for each encoding contains all its characters once but maybe i am not aware of sth we all like this encoding stuff right is there such a set of testfiles for characterencoding issues out there,['java'] +247168,return json from mvc controller but date format not proper in javascript i am working in a project where i create a grid using data from database in my controller i have this codelistiemployentity list new employeeconnectionstringgetemployeerecordit returns me list of employees with some date and further i convert it to json using return jsonlistbut the date format i got in my java script grid like date1325075075113 my javascript code is like ajax url getrecord type post data async false success function result if result create grid,"['c#', 'javascript', 'jquery']" +247180,how to connect a socket to an http server through proxy recently i wrote a program using sockets in c to connect to an http server running locally and thereby to do requests to thatthat worked fine for me after that i tried the same code to connect to another server on the web eg wgooglecom but i was not able to connect and was getting another html response from the proxy server in my networkmy local ip is 100258the proxy ip is 101this is the response i got http11 302 foundexpires fri 10 feb 2012 124735 gmtexpires 0cachecontrol maxage180cachecontrol nostore nocache mustrevalidatecachecontrol postcheck0 precheck0pragma nocacheconnection closelocation contenttype texthtmlcontentlength 0date wed 08 feb 2012 104735 gmtserver lighttpd1429how can i bypass this proxy to connect to external serversresponse got when tried with connecthttp11 302 foundexpires fri 10 feb 2012 133758 gmtexpires 0cachecontrol maxage180cachecontrol nostore nocache mustrevalidatecachecontrol postcheck0 precheck0pragma nocacheconnection closelocation contenttype texthtmlcontentlength 0date wed 08 feb 2012 113758 gmtserver lighttpd1429working code which connects to my local apacheincludeunistdhincludestdiohincludesystypeshincludesyssockethincludenetinetinhincludearpainethincludenetdbhincludestringhdefine max buffer size 1024int mainint argcchar argv int clsdssdstatus char buffer1024 char requestget http11rnhost100258rnrn struct sockaddr in srvr addr struct addrinfo hintsres srvr addrsin familyaf inet srvr addrsin porthtons80 srvr addrsin addrs addrinet addr100258local server clsd socketaf inetsock streamipproto tcp ifclsd0 perrorsocket init failednreturn 1 ssdconnectclsdstruct sockaddr srvr addrsocklen tsizeof srvr addr ifclsd0 perrorsocket connect failednreturn 1 writeclsdrequeststrlenrequest memsetvoid request0x00strlenrequest memsetbuffer0x00max buffer size do statusreadclsdbuffermax buffer size write1bufferstatus memsetvoid request0x00strlenrequest memsetbuffer0x00max buffer size do statusreadclsdbuffermax buffer size write1bufferstatus whilestatus0 closeclsd return 0,"['c++', 'c']" +247219,getting resizeable appwidget dimensions or getting around it i created a nice widet for my app it just thisplays a list of items downloaded from a server well to be precise it only looks like a list since listview in remoteviews is not supported in older android versions which i want to supporti want my widget to show a list of uptodate items and i want these items to take all available widget space to better show my problem lests assume wlog that i want a widget with the tv schedule of selected programme knowing thatdownloading from server is costlywlog we can assume that there are aleph zero items on server that i can downloadthe tv schedule may change so we do not want to download schedule for a whole month but at most half of a daythe first item thisplayed will contain show currently being broadcastedhow i can ensure that there will be no empty space at the bottom of the widget if the user will resize it to make it larger i searched so and it seems that when user will change widget size on ics or custom launcher go launcher ex allows it it will be impossible correct me if i am wrong to get widgets new dimensionsbut i do not really need them i would like to know how many items will fit in the widget and calculating this from widgets size is just one of the methodsso i am asking you if it is possible to for example receive notification if a remote view will become visible or create custom view for use in remoteviews which would somehow allow me to estimate the number of visible itemsif it would not be possible i will just have to use some reasonable defaults but it would be nice to know how many rows i can show,['android'] +247244,overflowing of unsigned int what will the unsigned int contain when i overflow it to be specific i want to do a multiplication with two unsigned ints and want to know what will be in the unsigned int after the multiplication is finishedunsigned int someint 25347382913482018273,['c++'] +247295,select dropdown list item findbytext without case sensitivity vbnet i want to select one item in drop down list in aspnet written with vbnet i have values and texts in listbox like thisvolvoaudietcbut values coming from other place in upper case volvo audithis codedropdownlistfindbyvaluecapitalis not working and giving null for volvo please help,['asp.net'] +247321,javalangnosuchmethoderror when use getfragmentmanager with actionbarsherlock library my own project usesusessdk androidminsdkversion7 androidtargetsdkversion13 to implement action bar i uses actionbarsherlock library i imported the sherlock library into my eclipse as an existing project for sherlock the target platform is android v32 api 13 then i added sherlock as a library project to my own project i saw there is library projects under my own project everything seem goes wellmy own project main activity looks like thispackage comtestimport androidappfragmentmanagerimport androidappfragmenttransactionimport androidosbundleimport androidsupportv4appfragmentactivitypublic class myactivity extends fragmentactivity hosts a fragment and the fragment will inflate a layout to show override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate fragmentmanager fragmgr fragmenttransaction fragtrans fragmgr getfragmentmanager error complains here firstfragment list new firstfragment fragtrans fragmgrbegintransaction fragtransaddandroidridcontent listcommit but when i run my application i got the following errorjavalangnosuchmethoderror comtestmyactivitygetfragmentmanagerwhy getfragment can not be resolved as a method i have used sherlock as a project library for my own project,['android'] +247349,illegal mix of collations utf8 general ciimplicit and utf8 unicode ciimplicit within stored procedure all the tables are in utf unicode cii have done this to checkselect table schema table name column name character set name collation name from information schemacolumnswhere collation name utf8 unicode ci and table schema like my database order by table schema table name ordinal positionand converted every table just in casealter table my databasetable name default collate utf8 unicode ci alter table my databasetable name convert to character set utf8 collate utf8 unicode ci my database collation settings are in utf8 unicode cicharsets aremysql show variables like char variable name value character set client utf8 character set connection utf8 character set database utf8 character set filesystem binary character set results utf8 character set server utf8 character set system utf8 character sets dir usrsharemysqlcharsets 8 rows in set 002 seccollations aremysql show variables like colla variable name value collation connection utf8 unicode ci collation database utf8 unicode ci collation server utf8 unicode ci 3 rows in set 0 secthe error is triggered whether i call the stored procedure via web browser or via mysql bash client just in case my ubuntulinux locale settings are localelanges esutf8languagees esutf8lc ctypees esutf8lc numerices esutf8lc timees esutf8lc collatees esutf8lc monetaryes esutf8lc messageses esutf8lc paperes esutf8lc namees esutf8lc addresses esutf8lc telephonees esutf8lc measurementes esutf8lc identificationes esutf8lc allthe only way i have been able to solve this issue is using convert inside each query that causes the error or using collate inside the query but the problem is that there are a lot of quite complex stored procedures so it is hard to identify the bad queries and takes a lot of timei guess that somehow the variables passed to the stored procedure from my system ubuntu mysql client browser are being sent in utf8 general ci so it makes conflict with ut8 unicode ci from my database it seems that the os is working with utf8 general ci even though the mysql connection is set to utf unicode ci,['mysql'] +247379,java bufferedreader check next lines of a loop before looping i am parsing a cvs filefor each line of the cvs i create an object with the parsed values and put them into a setbefore putting the object in the map and looping to the next i need to check if the next cvss line is the same object as the actual but with a particular property value differentfor that i need check the next lines of the buffer but keep the loops buffer in the same positionfor examplebufferedreader input new bufferedreadernew inputstreamreadernew fileinputstreamfileiso88591string line nullwhile line inputreadline null do something while nextline inputreadline null now i have to check the next lines i do something with the next lines and then break do something else and continue the first loop,['java'] +247386,is there a maximum size to android internal storage allocated for an app i want to save a json file with all the application data something similar to preference but im not sure what is the limit size because if the app cant use this file it will not function probably is this information known beforehand and the os reserve some space for your app or its based on the size available update i dont really care about external storage since is not always available in the device and could be changed sd card and i could check for internal storage using this but this is not what i want to know what i want to know if there is a memory size allocated for internal storage for the device,['android'] +247402,how to get the integer value of day of week how do i get the day of a week in integer format i know tostring will return only a string datetime clockinfofromsystem datetimenowint day1string day2day1 clockinfofromsystemdayofweektostring it is not workingday2 clockinfofromsystemdayofweektostring it gives me string,['c#'] +247417,why is ruby unable to verify an ssl certificate this is my first time trying to use the xmlrpcclient library to interact with a remote api and i keep receiving this errorwarning peer certificate would not be verified in this ssl sessionsearching around i have found loads of people that have gotten that error usually it is with selfsigned certificates and they just want it to go away so they do something dirty like monkey patch the way xmlrpcclient is opening it is http sessioni first assumed this was simply the client not caring whether the certificate was valid or not so i continued my search and came across this gem it simply forces verification of all ssl certificates and throws a hard error if it is not able too this was exactly what i wanted i included it ran the code again and now i am getting thisopensslsslsslerror ssl connect returned1 errno0 statesslv3 read server certificate b certificate verify failedof course the certificate is bad but i double check just to make sure with openssls builtin s client like soopenssl s client connect subexamplecom443and what do i getconnected03certificate chainsnipverify return code 0 okso now we get to my question openssl the command line version says the certificate is good openssl the ruby library thisagrees all of my web browsers say the certificate is gooda few additional details that might be of use the certificate is a wildcard but is valid for the domain the openssl s client was run on the same machine seconds apart from the ruby code this is ruby 187 p357 which is installed with rvmdoes ruby use something other than the ca bundle provided by the host os is there a way to tell ruby to use a specific ca bundle or the system one,['ruby'] +247433,join multiple iterators in java does anybody know how to join multiple iterators in java the solution i found iterate through one iterator first and then move on to the next one however what i want is when next gets called it first returns the first element from the first iterator next time when next gets called it returns the first element from the second iterator and so onthanks,['java'] +247475,do files created with pathgettempfilename get cleaned up automatically i have always assumed the answer is yes but now i am trying to find the truthwhen i create a temp file using pathgettempfilename will windows automatically clean that up laterwhat about if i create a directory under pathgettemppath will windows clean it upor is it the developers responsibility to delete files created there,['.net'] +247494,what is angle brackets for argument values and what is it used for i am used to angle brackets being used to specify a type as a parametervectorint vecofints but in rapidjson there is code like thisdocumentparse0json the documentparse methods signature istemplate unsigned parseflagsgenericdocument parseconst ch str rapidjson assertparseflags kparseinsituflag genericstringstreamencoding sstr return parsestreamparseflagssi did not know you could pass a value inside angle brackets thought angle brackets were used for typenames alonewhat is the code here doing and why is he passing a value in the angle bracketsis this a good idea when,['c++'] +247522,phpfpm and nginx session problems i have been having this problem for the past week or so i have been working on a php project that relies heavily on sessions for some reason weve been having troubles with the sessions saving the past few days any idea whyheres the errorwarning unknown opentmpsess mmd0ru5pl2h2h9bummcu1uu620 o rdwr failed permission denied 13 in unknown on line 0 warning unknown failed to write session data files please verify that the current setting of sessionsave path is correct tmp in unknown on line 0warning session start opentmpsess mmd0ru5pl2h2h9bummcu1uu620 o rdwr failed permission denied 13nginx versionnginx version nginx1011phpfpm config fpm configuration all relative paths in this configuration file are relative to phps install prefix include one or more files if glob3 exists it is used to include a bunch of files from a glob3 pattern this directive can be used everywhere in the fileincludeetcphpfpmdconf global options global pid file default value nonepid varrunphpfpmphpfpmpid error log file default value varlogphpfpmlogerror log varlogphpfpmerrorlog log level possible values alert error warning notice debug default value noticelog level notice if this number of child processes exit with sigsegv or sigbus within the time interval set by emergency restart interval then fpm will restart a value of 0 means off default value 0emergency restart threshold 0 interval of time used by emergency restart interval to determine when a graceful restart will be initiated this can be useful to work around accidental corruptions in an accelerators shared memory available units seconds minutes hours or days default unit seconds default value 0emergency restart interval 0 time limit for child processes to wait for a reaction on signals from master available units seconds minutes hours or days default unit seconds default value 0process control timeout 0 send fpm to background set to no to keep fpm in foreground for debugging default value yesdaemonize yes pool definitions see etcphpfpmdconfnginxconf this is the main nginx configuration file more information about the configuration options is available on the english wiki the russian documentation main module directives that cover basic functionality user nginx nginxworker processes 5error log varlognginxerrorlogerror log varlognginxerrorlog noticeerror log varlognginxerrorlog infopid varrunnginxpid events module events worker connections 4096 http core module http include etcnginxmimetypes default type applicationoctetstream log format main remote addr remote user time local request status body bytes sent http referer http user agent http x forwarded for access log varlognginxaccesslog main index indexphp indexhtml indexhtm sendfile on tcp nopush on keepalive timeout 0 keepalive timeout 65 gzip on load config files from the etcnginxconfd directory the default server is in confddefaultconf include etcnginxconfdconf server listen 80 server name statssmilingdevilcom error page 404 404php root varw access log varlognginxaccesslog error log varlognginxerrorlog location set page to view indexphp try files uri uri rewrites root varw index indexphp location rewrites if uri az09 set page to view 1php rewrite az 1php last location php include etcnginxfastcgiconf fastcgi pass 12700190 fastcgi param script filename varwfastcgi script name,['php'] +247563,java questions on clone method i got these asked in an interviewdo we need to take care of clone method in a concurrent environment can we synchronize the clone method does it make any sense to use clone method in singleton classes i did not have convincing answers for this during the interview,['java'] +247571,is it possible to modify style using cucumber capybara so i have the scenario where i want to demonstrate to the business how cucumber can be of benefit it is easy to setup a demo and run but without the proper visuals the business would not really see the benefit question is is it possible to add a css class whilst the feature is being executedsomething like thisanchor pagefind linklinkanchorstylevalue outlineyellow solid thicksleep 1click linklinkwhat i am not sure is the second line how can i achieve an outline style on an element that is about to be clickedi could not find anything similar on the actual cucumber spec any help would be appreciated,"['css', 'ruby']" +247574,how to catch error connection reset by peer errnoeconnreset the following code sometimes generates a connection reset by peer error can anyone show me how to handle this exceptiondoc nokogirihtmlopenurlconnection reset by peer errnoeconnreset,['ruby'] +247578,how would one implement a numberpicker in android api 7 there is a numberpicker widget in api 11 but i am building for a minimum api of 7 how would i go about implementing one is there a custom widget that i can use or is there a way to get at the components that make up datepicker timepicker,['android'] +247579,javascript howcan i set an object reference to null from a function i am wondering if this is even possible basically i have a couple objects that i pass to a function and under certain conditions i want that function to set the object to nullexvar o val 0f functionv v nullfo would like this to set o to nullunfortunately it seems i can only set the functions argument to null after calling the function o will still refer to an objectso is it even possible to do this and if so how,['javascript'] +247600,can you use google apps script with python google apps script looks to be pretty perfect for a school project however i am not terribly comfortable with javascript and the entire rest of the project is going to be done in python is there a way to access it using a python library or do i need to suck it up and learn javascriptthis tutorial is the closest thing i have found in my searching and is not quite what i want,['python'] +247630,how to thisablehide threedot indicatoroption menu indicator on ics handsets how to thisablehide threedot indicatoroption menu indicator on ics handsets which doest have menu button i am running application as usessdk androidminsdkversion5 in manifest code is compiled with 40 threedot indicator shows on every screen example for preference activities i do not want show threedot indicator since it doest have any menu optionsadding androidtargetsdkversion14 in manifest it works however do not want hideremove three dots button on all screens only in preference activities do not want to show this three dots button,['android'] +247650,is it possible to run selenium scripts without having an x server running too i have a python script that uses selenium rc specifically webdriveri would love to have the script run as a postcommit hook ideally through ie safari if possible chrome firefox but i am not sure what i would need to do since every time i run it on my local machine a browser pops upi have heard of saucelabs is it the best solution,['python'] +247653,heavy javascript page gap of 15 seconds between response and page load i have a page a which is a heavy javascript page when i leave this page to go to page b it takes a long time when i go to page b from a different page it is really fast so it has something to do with page a and probably its javascript when i run the network profiler from the developer tools in ie 9 it shows a gap of 15 seconds between the response and the domcontentloadedevent page a is heavy with javascript because it runs the xopus editor a rich text xml editor does anybody have any ideas on what i could do to either analyse the gap as to what happens or what i could do to make page a unload faster,['javascript'] +247655,how to copyclone a virtual environment from server to local machine i have an existing python django project running in web server now the client needs to make some changes in the existing code so i need to set it up in my local machine all the packages needed for this project is installed in a virtual environment how can i copy or clone this virtual environment to my local machine to run this project,['python'] +247668,why do we need list for each safe in for deleting nodes in kernel linked list i am learning how to use the kernel linkedlist api from listhi learned that i need to use list for each safe when deleting nodes off with list del instead of using list for eachcode for list for each safedefine list for each safepos n head for pos headnext and posnext pos head pos n and posnextcode for list for each for pos headnext pos head pos posnexti notice they both are very similar except that the safe version takes an extra argument to be used as temporary storage stated here listhi understand when to apply the function correcly safe version for deleting normal version for accessing but i am curious how the extra argument made it safe consider the following where i am deleting every node in a linked list using list for each safestruct kool list int to struct list head list int from struct kool list tmpstruct list head pos qstruct kool list mylistlist for each safepos q mylistlist tmp list entrypos struct kool list list printffreeing item to d from dn tmpto tmpfrom list delpos freetmp how does giving q help in deletingthanks for any help,['c'] +247678,how to split spring mvc request mapping by parameter value in spring mvc 3 i want to handle the same url with two different controller classes depending on value of url parameter requestmapping annotation even has such field params and i thought following would be two different mappings i use mapping on class levelrequestmappingvalue myurl params nameval1andrequestmappingvalue myurl params nameval2but it is not spring throws exception for second case that controller for myurl already mapped by first caseis there some accurate solution for splitting request mapping by parameter may be extending requestmapping or using proxy as controller and call different controllers depending on parameterany thoughtsupdatethis works but only on methods level not on class levelthis willcontrollerrequestmappingvalue myurlpublic class class123 requestmappingvalue edithtm params src1 public string open1mapstring object map throws exception requestmappingvalue edithtm params src2 public string open2mapstring object map throws exception this would notcontrollerrequestmappingvalue myurl params src1public class class123 1 requestmappingvalue edithtm public string openmapstring object map throws exception controllerrequestmappingvalue myurl params src2public class class123 2 requestmappingvalue edithtm public string openmapstring object map throws exception and i would like to split logic in different classes,['java'] +247687,error msb6006 cmdexe exited with code i am building driver for my usb device while building using msvisual studio10 i am getting following two errors cprogram filesmsbuildmicrosoftcppv40microsoftcppcommontargets1515 error msb6006 cmdexe exited with codeandcboost32includeboost1 48boostnumericconversiondetailpreprocessednumeric cast traitshpp34error c2766 explicit specializationboostnumericnumeric cast traitscharchar has already beendefined 2 cboost32includeboost1 48boostnumericconversiondetailpreprocessednumeric cast traitshpp18 see previous definition of numeric cast traitscharcharvoidhelp me out in getting rid of these two errors which are hindering tyhe building process of my project,['c++'] +247699,web cam type video camera to ipad2 streaming over wired communication i want to develop an app that requires wired communication between web cam type video camera and ipad2 basically i will directly connect web cam and ipad2 using cable and when i start web cam whatever imagespicturevideo captured by web cam should be thisplayed on ipad2 based on my research on this i found that ipad2 cable is only made for ipod program so the connector is not a traditional usb port i cannot do direct communication between web cam and ipad2 am i missing anythingwe are going to use vivotek camera and they have mentioned here that we can use safari to receive the motionjpeg stream i am wondering if that could also possible on ipad 2 and is it reliablefurther i found apples mfi program to develop electronic accessories that connect to ipod iphone and ipad is there anyone out here used this already and know more about this if i can go for thisthanks,"['objective-c', 'ios']" +247715,mysterious number 18 one of our testers managed to set a slider bound variable to 18 which can only take values between 1100 normally i can observe it in view model which is saved to a xaml file whats special about this numberhere are some details the application has a slider it is bound to an observable property in a view model normally when application saves the workspace this viewmodel is saved along using xamlservicessave my tester reported some awkward behaviour the value of the slider showing 214 upon loading this project i asked him to send me the file and the value in the saved xaml contains my mysterious number i know this is the result of a bug in my code or some other library code i will hopefully nail it down however normal garbage values cannot be like this when i google i see some nonprogramming related pages which shows somehow this number was generated in history of internet so it is not my cats doing in short i am trying to figure out how this number can be created in the first place like when you see int max 1 if you are experienced enough you can recognize it 2137483648 anyone,"['c#', '.net']" +247719,opengl es 20 multiple programs or multiple shaders or what how does it work the problem tldrmy problem fundamentally is that i do not know how opengl es 20 expects me to write and use multiple shaders or if it is even advisableexpected that a person will do sothe fundamental question here is if i have an apple a glowing rock and a fuzzy mesh all in the same 3d world all best drawn with different shader programs but using the same mvpmatrix then how would i go about using all of them in the same opengl render such that they all use their most appropriate shaders that i have writtenwhat have i doneso i have written a basic opengl es 20 program for my android game that works perfectly in that it can draw the outline of the objects to the screen but it does nothing else pretty much because the shaders look like thisvertex shaderuniform mat4 umvpmatrixattribute vec4 apositionvoid main gl position umvpmatrix apositionfragment shadervoid main gl fragcolor vec410 10 10 10now they are pretty basic the reason that i have not gone further is because i cannot figure out if i am supposed to write one shader to apply to all of my different objects or if i am supposed to use multiple shaders and if i am supposed to use multiple shaders to draw multiple different objects then how do i go about doing that in an efficient wayi get the feeling that this must be basic knowledge to anybody that does opengl es 20 day in and day out so i am hoping that somebody can answer my question or point me in the right directioni havelooked at multiple tutorials none of which use anything but the most basic shadersread the entire opengl es 20 glsl spec none of which mentioned how it was intended to be used it was just about what everything did rather than how it fits togethertried to modify my shaders a bitso i am hoping that i am close to understanding the opengl workflow but i do not seem to be there yet edit i found this well afterwardsif your application is written for opengl es 20 do not create a single shader with lots of switches and conditionals that performs every task your application needs to render the scene instead compile multiple shader programs that each perform a specific focused taskthat is from the ios opengl es 20 guidelines,['android'] +247761,using strong typedef as a more lightweight alternative to boost parameter library i often use the boost strong typedef utility to improve the safety of my programs for example by writing code like thisboost strong typedefint xboost strong typedefint yboost strong typedefint widthboost strong typedefint heightstruct rect rectx x y y width w height h usagerect rectx10 y20 width800 height600the strong typedef here improves both code readability and safety the compiler will report an error if the arguments are provided in the wrong order which would not have been the case if the arguments were all intmy questions areis it ok to use boost strong typedef for this purpose the documentation is very briefare there important reasons to prefer the boost parameter library instead,['c++'] +247792,saving nsarray to nsuserdefaults and getting it in nsmutablearray how can i save nsarray in nsuserdefaults and then load it back in an nsmutablearray to populate the uipickerviewalso the issue is that new values would be added to that nsmutablearray and then that array will be converted to nsarray to be saved in nsuserdefaults as nsmutablearray cannot be saved in nsuserdefaultsany help appreciated thanks,"['iphone', 'objective-c', 'ios']" +247809,doubleclick event on wpf window border is there any event which fires on doubleclick event on wpf window borderhow i can catch itthanks,"['c#', '.net']" +247813,how to stop thread returning before join is called this is purely a theoretical question as i am not sure the conditions to cause this issue would be commonsay for example you have a thread that you kick off with it is start methodthread c new threadcstartthen directly after you call the join method on the thread to tell the method you are in to wait until the thread had been executed to continuecjoinis not it a possibility that the thread could possibly be executed and finish before the join method is called therefore leaving the method unaware that it had to wait for c to finish before it continued i suppose you could try calling the join method before you call the start method yet whenever i have tried this in test cases there is an erroranyone know a possible fix for this or does the jvm handle it as i said i have not been able to trigger this sort of situation but theoretically it is possible,['java'] +247818,how to set precision of a float someone can explain me how to choose the precision of a float with a c functionexamplesthefatfunction06 3 return 0667thefatfunction01 3 returns 01,['c'] +247825,function acting as both decorator and context manager in python this might be pushing things a little too far but mostly out of curiositywould it be possible to have a callable object functionclass that acts as both a context manager and a decorator at the same timedef xargs kw or as a classxfoo bardef im decorateda b printdo the stuffwithxfoo bar printdo the stuff,['python'] +247828,html javascript one click print no dialogs is it possible to have a print option that bypasses the print dialogi am working on a closed system and would like to be able to predefine the print dialog settings and process the print as soon as i click the buttonfrom what i am reading the way to do this varies for each browser for example ie would use activex chrome firefox would require extensions based on this it appears i will have to write an application in c that can handle parameters passed by the browser to auto print with proper formatting for labels then i will have to rewrite it as an extension for chrome firefox end result being that users on our closed system will have to download install these features depending on which browser they usei am hoping there is another way to go about this but this task most likely violates browser security issues,['html'] +247842,how to properly set the 100 div height to match documentwindow height i have a wrapper positioned to center with an yrepeated background imagebody div idwrapper some content divbodywrapperwidth 900pxmargin 0 auto 0 autobackgroundimage urlimagejpg 250px 0px repeatyproblem when the window size is higher than the wrappers height inherited from its content the image obviously does not repeat on yaxis all the way to the bottom of the windowi have used jquery to dynamically apply inline css style to the wrapper according to actual document height when dom is ready and on window resize eventfunction wrappercssheightdocumentheightpx windowresizefunction wrappercssheightdocumentheightpx the problem with this approach is that every time one extends the window height to a size larger than the previously resized largest size the document height extends by this difference essentially making the wrapper div infinite if you keep resizing the window infinitely and have a infinite vertical thisplay spaceon a typical 30 inch thisplay with 1600px height when user opens the website with a window height 10px and wrapper is 800px high the jquery above sets the height to 10px tiling the background image correctly at this point once the user extends the window size to eg 1400px the 1400px is a new document size remembered default and does not update itself even if the user resizes his window back to the original 10px height adding 400px to the scrollbar height at the bottomhow to fix thisupdate windowheight does not seem to work because window height is a viewport height when your viewport is smaller than the content and you scroll it the wrapper always stays the size of the viewport and does not extend to the bottom of the current viewport position,"['jquery', 'html', 'css']" +247888,how to output the content of a scenegraph in javafx 2 to an image how to output the content of a scene graph in javafx 2 to an image actually i am working on an app which basically designs cards so the user just clicks to the various options to customize the scene finally i would like to export the scene content to an image file how do i do that,['java'] +247950,how to find the position of an element in the web browser control i have a form with web browser control which loads a webpage its working fine the page loads oknow my issue is i want to find whether a particular urllink is below the fold or above the fold i mean whether the user have to scroll down to see this link or not whether this v is visible with out scrolling or we need to scroll to see it i hope i am cleari have done extensive search but looks like no info is available about find an html elements position above or below current viewdoes anybody knows something about this and can point me in right direction pleasei am looking for c solution winforms update big thanks to john koerner for the code really appreciate the time and effort he put in solving my issueand to jonathan everybody else also i wish i could mark jonathans reply also as answer but it allows only one reply to be marked as answer his comment was also clear and useful hint thanks you guys are great,['c#'] +247973,highcharts add a custom image button i want to add and image button on highchartsso far i have successfully created a image button and have attached a click event on itbut problem is that the image sunpng is on left side of chart and image button is right aligned the default position of toolbar any fix for this exporting buttons popupbtn symbol urlimagessunpng titlekey popupbtntitle x 10 symbolfill b5c9df hoversymbolfill 779abf onclick function alertad popupchartthis exportbutton enabled false printbutton enabled false also if there are other methods to add an image in chart which have click event those methods are welcomed too,"['javascript', 'jquery']" +247978,compiling icu using armlinuxandroideabi443 i would like to crosscompile icu static libs for android using cygwin so far i have been able to configure and make the cygwinmsvc and cygwin versions i have installed the androidndkr7 and can see a version of gcc in the toolchains directory several examples suggest using hostarmeabi but this is not present on my machinei have copied mhlinux to mhunknown in icusourceconfig and run the followingexport host icucygdrived externalsqliteicuexport icu cross buildcygdrived externalsqliteicucygwinexport ndk rootcygdrived androidndkr7export cppflagsindk rootplatformsandroid8archarmusrinclude o3 fnoshortwchar du using icu namespace0 du gnuc utf16 string0 fnoshortenums nostdlibexport cxxflagsindk rootplatformsandroid8archarmusrinclude o3 fnoshortwchar du using icu namespace0 du gnuc utf16 string0 fnoshortenums nostdlibexport cflagsindk rootplatformsandroid8archarmusrinclude o3 fnoshortwchar du using icu namespace0 du gnuc utf16 string0 fnoshortenums nostdlibexport ldflagslc wlrpathlinkndk rootplatformsandroid8archarmusrlib l ndk rootplatformsandroid8archarmusrlibhost icusourceconfigure withcrossbuildicu cross build enableextrasno enablestrictno enablestatic enablesharedno enabletestsno enablesamplesno enabledyloadno enabletoolsno hostarmeabi withdatapackagingarchivei get the following errorchecking for icu version numbers release 4811 library 4811 unicode version 60checking build system type i686pccygwinchecking host system type armunknowneabichecking target system type armunknowneabichecking whether to build debug libraries nochecking whether to build release libraries yeschecking for armeabigcc nochecking for gcc gchecking whether the c compiler works noconfigure error in cygdrivedprojects externalsqliteicuandroidconfigure error c compiler cannot create executablessee configlog for more detailsi am sure this is a stupid question but how do i get the icu configure script to point to the gcc under ndk roottoolchainsarmlinuxandroideabi443prebuiltwindowsarmlinuxandroideabibin am i missing some setup or install should i be setting my path so that the first gcc found is the one in armlinuxandroiedeabiupdate 1 i just noticed that while windowsarmlinuxandroideabibin contains gcc windowsbin contains armlinuxandroideabigcc how do i get icu to call thisupdate 2 on the suggestion of steven r loomis i picked up updates for configsub and configguess fromablob plainfconfigsubhbhead ablob plainfconfigguesshbheadplaced androidndkr7toolchainsarmlinuxandroideabi443prebuiltwindowsbin into my path and reran configure with hostarmlinuxandroideabi this timechecking for armlinuxandroideabigcc armlinuxandroideabigchecking whether the c compiler works nodefinitely closer detailed error from configloggcc version 443 gconfigure3125 0configure3114 armlinuxandroideabigcc v 5armlinuxandroideabigccexe v option must have argumentconfigure3125 1configure3114 armlinuxandroideabigcc qversion 5armlinuxandroideabigccexe unrecognized option qversionarmlinuxandroideabigccexe no input filesconfigure3125 1configure3145 checking whether the c compiler worksconfigure3167 armlinuxandroideabigcc icygdrivedprojectsandroidndkr7platformsandroid8archarmusrinclude o3 fnoshortwchar du using icu namespace0 du gnuc utf16 string0 fnoshortenums nostdlib icygdrivedprojectsandroidndkr7platformsandroid8archarmusrinclude o3 fnoshortwchar du using icu namespace0 du gnuc utf16 string0 fnoshortenums nostdlib lc wlrpathlinkcygdrivedprojectsandroidndkr7platformsandroid8archarmusrlib l cygdrivedprojectsandroidndkr7platformsandroid8archarmusrlib conftestc 5dprojectsandroidndkr7toolchainsarmlinuxandroideabi443prebuiltwindowsbinlibgccarmlinuxandroideabi443armlinuxandroideabibinldexe cannot find lccollect2 ld returned 1 exit statusconfigure3171 1configure3209 result noconfigure failed program was confdefsh define package name define package tarname define package version define package string define package bugreport define package url end confdefsh int main return 0 configure3214 error in cygdrivedprojects externalsqliteicuandroidconfigure3216 error c compiler cannot create executablessee configlog for more detailsupdate 3 the changes to configsub and configguess worked in that we are now using the right gcc compiler the lc failure comes from not being able to find libcso which is in androidndkr7platformsandroid8archarmusrlib even though this is in the ldflags i did have an extra space after l in the original ldflags but removing this did not helpupdate 4 according to an older post in threadthread46295616a889bc12the windows ndk toolchain is thankfully native to windows so it doesnt go through the cygwin translation layer which would translate cygdrive pathsupdate 5 swapped all instances of cygdrived with d now c compiler works though it still does not make suspect that icu cross build has to be in the icusource directorychecking whether the c compiler works yeschecking for c compiler default output file name aoutchecking for suffix of executableschecking whether we are cross compiling yeschecking for suffix of object files ochecking whether we are using the gnu c compiler yeschecking whether armlinuxandroideabigcc accepts g yeschecking for armlinuxandroideabigcc option to accept iso c89 none neededchecking for armlinuxandroideabig armlinuxandroideabigchecking whether we are using the gnu c compiler yeschecking whether armlinuxandroideabig accepts g yeschecking how to run the c preprocessor armlinuxandroideabigcc echecking for a bsdcompatible install usrbininstall cchecking for gmake usrbingmakeconfigure error dprojects externalsqliteicucygwinconfigicucrossmk not found please build icu in dprojects externalsqliteicucygwin firstupdate 6 i reconfigured and rbuilt my cygwin folder in icucygwin go figure this time icucrossmk was there successful configuration butupdate 7 make did not end up so well makedprojects externalsqliteicusourceconfigmhlinux41 target pattern contains no stopwhat it seems that now we want cygwin paths again update 8 changed my paths so that host icu and icu cross build use cygwin paths but ndk root is windows path since android ndk ld cannot handle cygwin pathsthis time further butarmlinuxandroideabigccexe cygdrivedprojects externalsqlit eicusourcestubdatastubdatac no such file or directoryarmlinuxandroideabigccexe no input filesseems that what has to happen is that armlinuxandroideabigcc needs to be made for cygwin or the crossbuild will not workupdate 9 it seems that armlinuxandroideabigcc does not support cygwin paths though ndk build does however icu is set to call armlinuxandroideabigcc while make requires cygwin paths maybe time to switch to osx or linux to do thisupdate 10 still no successcygwin apparently the armlinuxandroideabi crystax build also does not support cygwin paths in l attempting to crosscompile under cygwin will give the lc error since it cannot parse the lcygdrived path to the library changing to d helps but later causes make to fail since it is cygwin makelinux using the normal ndk r7 build configuration will fail with a wchar t 0 error the crystax ndk build will fix this and make will fail complaining about uint64 t in androids systypeh see icu library in android ndk you can force it to be defined and it will lead to yet another error about size mismatchosx probably the most successful compiling using the official build or the crystax build it leads directly to the uint64 t bug if you hack around it it will lead you toicusourcecommonustrenumcpp118 error must include typeinfo before using typeidhelp,['android'] +247981,add metadata to image upload to s3 with python i am successfully adding an image to a bucket on s3 but the problem is i am not sure how to set the contenttype to imagepng here is my codeimage imageopenselfimageconn s3connectionsettingsaws access key id settingsaws secret access key out im2 cstringiostringioimagesaveout im2 pngb connget bucketnew test bucketk bnew keyselftitlepngkset contents from filenamestrselfimagecurrently it is being uploaded as applicationoctetstream,['python'] +247982,jquerygetjson and jqueryparsejson return object object edit i have gotten the famous question badge with this question so i figured i would come back to it and stick what happened to me right at the very tippy top for people searching it to get an answer right awaybasically i was new to json json is an object obviously as it contains all kinds of stuff so i was like hey javascript just pop up an alert with all of this json data expecting it to give me the json data as a string but javascript does not do that which is good so it was like hey this is how we thisplay objects object objectwhat i could have done is something like alertobjdata01 and it wouldve shown me that bit of the objectwhat i really wanted was to verify that i was making good json data which i could have checked with jsonstringifyanyway back to our regularly scheduled questionsi am trying to get some json data with an ajax call but jquery does not seem to like my jsonif i do something likefunction init2 alertinside init2 jqueryajax url mobile reportingchaincfm type post async false success function data alertdata var obj jqueryparsejsondata alertobj i get this as from alertdata columnsmfirst namemlast namemmddl namememply idmaim nbremply id datafname1 lname1 mi1 01471890260010627276 fname2 lname2 mi2 0123021011850147189 fname3 lname3 mi3 09136191021012302 fname4 lname4 mi4 025968710210913619 which jsonlint says is valid json alertobj gives me this howeverobject objectadding datatype json or text json just makes it report object object at alertdatai would really like to get this figured out does anyone know why it is doing this i am pretty new at jquery my goal is to get an array for each of the columns the same code i am using has worked on a different page it looks like which is whats bothering me the most,['jquery'] +247989,dealloc not being called on arc app i have a uiviewcontroller that is pushed onto a container controller and then popped off and using the allocations instrument i can see that the view controller is destroyed afterwards however a breakpoint in the controllers dealloc is never reached does anyone know why dealloc is not called is it possible for arc to destroy an object without calling deallocalso i have thisabled nszombies some have said that can cause dealloc not to fire editdealloc does not do much just prints to the console and it never gets called voiddealloc nslogdeallocatingi cannot post the container controllerait is proprietary and too complicated dealloc is called consistently on some controllers and not others if i can find the time i will try and post a simplified version that reproduces the problemis there any way to verify that nszombies is thisabled edit2i am posting a screenshot from instruments it looks to me like it is properly deallocating,['ios'] +248004,how to handle when user closes aphysical locationa prompt in firefox and chrome i am using the geolocation object and getcurrentpositionhave you seen that everytime you use getcurrentposition firefox and chrome prompt these massages chromeexamplecom wants to track your physical location allow deny x close firefoxexamplecom wants to know your location share location do not share closemy question is how to handle when a user does not allow nor deny location option but instead closes the prompti have this javascript code but it does not work when user closes the prompt if navigatorgeolocation navigatorgeolocationgetcurrentposition onsuccess onerror enablehighaccuracy true timeout 50 maximumage 120 alerthola else alertgeolocation not supported i am having some problems with that any help pleasethis question is related with this post how to call function when user allows or denies access to physical location,['javascript'] +248013,javascript suppress this page is asking you to confirm that you want to leave popup on onbeforeunload when a user leaves a page i need to ask him if he wants to perform a particular action before leavingscript typetextjavascriptdocumentreadyfunction windowonbeforeunload askconfirmfunction askconfirm var addfriend confirmwould you like to ping if addfriend var xmlhttp if windowxmlhttprequest xmlhttpnew xmlhttprequest else xmlhttpnew activexobjectmicrosoftxmlhttp xmlhttpopengettrue xmlhttpsend return nulldepending on the value of that last return statement null true false or not having a return statement at all i can have one of two situations1 the user gets the would you like to ping confirmation good the ping is sent good and the user is presented with a this page is asking you to confirm that you want to leave popup bador2 the user gets the would you like to ping confirmation good the ping is not sent bad and the user is not presented with a this page is asking you to confirm that you want to leave popup goodhow can i have the ajax ping sent yet suppress the this page is asking you to confirm that you want to leave popupedit as ridiculous as it sounds the work around that i found for this issue is to alert after the xmlhttpsend statement the only clean way to do that is to alert the user that his ping has been sent if future stackoverflowers find a better solution i would love to knowthanks,['javascript'] +248040,c scott meyers effective stl item 31 know your sorting options help to understand good dayin his effective stl scott meyers wrotea third is to use the information in an ordered container of iterators to iteratively splice the lists elements into the positions youd like them to be in as you can see there are lots of options item 31 second partcan someone explain me this waymore text to understand the contextthe algorithms sort stable sort partial sort and nth element require random access iterators so they may be applied only to vectors strings deques and arrays it makes no sense to sort elements in standard associative containers because such containers use their comparison functions to remain sorted at all times the only container where we might like to use sort stable sort partial sort or nth element but cannot is list and list compensates somewhat by offering its sort member function interestingly listsort performs a stable sort if you want to sort a list then you can but if you want to use partial sort or nth element on the objects in a list you have to do it indirectly one indirect approach is to copy the elements into a container with random access iterators then apply the desired algorithm to that another is to create a container of listiterators use the algorithm on that container then access the list elements via the iterators a third is to use the information in an ordered container of iterators to iteratively splice the lists elements into the positions youd like them to be in as you can see there are lots of options,['c++'] +248042,wrong mailbox items being retreived using exchange web services managed api in c i am trying to retreive inbox items from a specific mailbox in which i have permissions using exchange web services managed api i have tested the code first using my own email address via autothiscoverurl and it works fine however when i tried using the other email address ews still retrieves my own inbox items is this due to a cache or something my code is as follows exchangeservice ex new exchangeserviceexchangeversionexchange2010 sp1 exautothiscoverurl finditemsresultsitem findresults exfinditemswellknownfoldernameinbox new itemview10 foreach item item in findresultsitems consolewritelineitemsubject,['c#'] +248064,how to use external memory on a microcontroller in the past i have worked a lot with 8 bit avrs and msp430s where both the ram and flash were stored on the chip directly when you compile and download your program it sort of just works and you do not need to worry about where and how variables are actually storednow i am starting a project where i would like to be able to add some external memory to a microcontroller a ti stellaris lm3s9d92 if that matters but i am not entirely sure how you get your code to use the external ram i can see how you configure the external bus pretty much like any other peripheral but what confuses me is how the processor keeps track of when to talk to the external memory and when to talk to the internal onefrom what i can tell the external ram is mapped to the same address space as the internal sram internal starts at 0x20 and external starts at 0x60 does that mean if i wrote something like thisint x 0x20int y 0x60would x and y would point to the first 4 bytes assuming 32 bit ints of internal and external ram respectively if so what if i did something like thisint x9 some super big array that uses all the internal ramint y9 this would have to be in external ram or it wouldnt fiti imagine that i would need to tell something about the boundaries of where each type of memory is or do i have it all wrong and the hardware figures it out on its own do linker scripts deal with this i know they have something to do with memory mapping but i do not know what exactly after reading about how to set up an arm cross compiler i get the feeling that something like winavr avrgcc was doing a lot of stuff like this for me behind the scenes so i wouldnt have to deal with itsorry for rambling a bit but i would really appreciate it if someone could tell me if i am on the right track with this stuffupdatefor any future readers i found this after another few hours of googling combined with answers here it helped me a lot,['c'] +248094,how to trim all inputs by model in c mvc i found all value passed by model is not trimmed in aspnet mvc3is there a way toapply a trim on every field in model all string fields at least but all form fields are string before processed by model so better trim them allmust before modelstateisvalid because i often found code stucked at weird modelstateisvalid and later found because the form item did not be trimmedthanks,"['c#', 'asp.net']" +248127,passing multiple flags to an intent in android i have this activity that lists some information which i provide a refresh button for the way i am refreshing it probably not the best way by any means is just launching the activity all over again to make the back stack work the way i need it to i need to pass in the flag activity clear top flag to the intent and it works fine but to give the illusion that the information is refreshing the information within the activity and not completely relaunching it i also need to add the flag flag activity no animation so far i have not been able to get these two flags to work together i have tried the following methodstheintentsetflagsintentflag activity no animationintentflag activity clear toptheintentsetflagsintentflag activity no animationintentflag activity clear toptheintentsetflagsintentflag activity no animationtheintentaddflagsintentflag activity clear topclear top works correctly for all of them but the animation is still there any help would be greatly appreciated,['android'] +248141,how do you verify ducktyped interfaces in python class itesttypeobject sample interface type metaclass abcmeta abstractmethod def requiredcallself returnclass testtype1object valid type def requiredcallself passclass testtype2itesttype valid type def requiredcallself passclass testtype3itesttype invalid type passin the example above issubclasstypetype itesttype will return true for 2 and false for 1 and 3is there an alternative way to use issubclass or an alternative method for interface testing that will allow 1 and 2 to pass but reject 3it would be extremely helpful for me to be able to use duck typing rather than explicitly binding classes to abstract types but also allow object checking when ducktyped objects pass through particular interfacesyes i am aware that python people do not like interfaces and the standard methodology is find it when it fails and wrap everything in exceptions but also completely irrelevant to my question no i cannot simply not use interfaces in this project editperfect for anyone else who finds this question heres the an example of how to use subclasshookclass itesttypeobject sample interface type metaclass abcmeta abstractmethod def requiredcallself return classmethod def subclasshook cls c required requiredcall rtn true for r in required if not anyr in b dict for b in c mro rtn notimplemented return rtn,['python'] +248143,where to start with magento shopping cart abandonment i am attempting some type of shopping cart abandonment system with magento using it is builtin cron module what i basically need is a system that checks for abandoned shopping carts every 15 mins and sends select cart data to another web service if certain criteria is met with each cartbasically here is my process but feel free to suggest a better waythe processget list of abandoned cartsfor each abandoned cart add 15 mins to that carts abandoned duration field in databasecheck if the abandoned duration is at 45 or 1440 1 day or 4320 3 days if yes send cart information to another web serviceif abandoned duration is at 4320 3 days delete abandoned cartelse continuerepeat every 15 mins using magento cronthe questionsis this possible in magentois there a better process to do this using magentowhat are the steps needed to go about implementing this for example which core modules are necessarywhich controllers need to be extendedshould i create my own module for thiswhat is the best way to get abandoned shopping carts as an arraythe reason i am reaching out to the community is because the magento documentation and tutorials are very vague i am new to the magento mvc however i am not new to php oop and mvcsany guidance here would be stellar cheers,['php'] +248164,how to change the border colorunfocused of an edittext i changed the background color of the edittext to transperant now the edittext looks invisible when not focused so how can i change the unfocused border color of edittextwhat is the xml attribute for this,['android'] +248177,how orchard cms does the logging i am working with orchard cms and it is better cms for me i want to understand how it does the logging and whether i can add my own logging or not i saw that orchard uses nulogger class and it does no work i have opened the app datalogs folder and have seen that there are the log files but how i searched in code where is the trick that replaces nulogger with log4net i guess this is log4net because the log format and the formatting for log4netconfig are very similar but i have not found thiscan somebody answer mehow orchard does the loggingwhether i can add my own logger and if yes what best practices exist to do thisthanks andrey,['asp.net'] +248183,using task or asyncawait in ihttpasynchandler since the very begining of writing aspnet applications when i wanted to add a threading there are 3 simple ways i can accomplish threading within my aspnet application using the systemthreadingthreadpool using a custom delegate and calling its begininvoke method using custom threads with the aid of systemthreadingthread classthe first two methods offer a quick way to fire off worker threads for your application but unfortunately they hurt the overall performance of your application since they consume threads from the same pool used by aspnet to handle http requeststhen i wanted to use a new task or asyncawait to write ihttpasynchandler one example you can find is what drew marsh explains here my guess is that using task or asyncawait still consume the thread from the aspnet thread pool and i do not want for the obvious reasoncould you please tell me if i can use task asyncawait on the background thread like with systemthreadingthread class and not from thread pool thanks in advance for your helpthomas,['asp.net'] +248197,utility for releasing packages to pypi i have a number of python packages in github repositories and it would be really great to have these available in pypi i know i could do these releases manually update the version number perhaps update a changelog tag the release in github get the download url from github update pypi with the release etc but i keep thinking that there must be a scriptutility somewhere to make this a singlecommand processi am not massively familiar with the python packaging process so perhaps i am coming at this from the wrong angle i just do not think i can be the first one to have the idea of making this whole process a lot easieredit as there seems to be some confusion about what i am asking for are there any tools that make releasing python packages to pypi a faster and more streamlined processi have tried searching around but have yet to find anything,['python'] +248206,portable printing of exponent of a double to c iostreams i want to print a double value to stdcout portably gcc clang msvc such that the output is the same on all platformsi have a problem with the formatting of the exponentthe following programinclude iostreamint main stdcout 01e7 stdendl return 0has this output with gcc1e08and the following output with msvc1e008how can i make both outputs the samei am sorry if this is a dumb question but i have not found an answer so farall formatting seems to evolve around the formatting of everything before the mantissaedit the output of gcc is 1e08 not 1e8 as originally stated so it is conforming sorry for the confusionedit2 actually renamed mantissa to exponent following dietmars remark there also is a section on wikipedia on mantissa vs significant,['c++'] +248224,apply updatesourcetriggerpropertychanged to all textboxes wpf how can i write template look like this datatemplate textblock updatesourcetriggerpropertychanged datatemplate,"['c#', '.net']" +248228,android where is sqlite database stored possible duplicatewhere does android emulator store sqlite database i am using sqlite and phonegap to create a multi platform app however i have run across an issuei am now looking for the location the phonegap stores the database files named 01db and databasedbi have found this for iphone however cannot seem to get the location for the android i am currently running on a simulator and actual device archos,['android'] +248241,always seeing mirror image while capturing from front camera ios 50 while capturing data from front camera i am always getting mirror image how can i get what i am seeing in my preview window i have set videomirrored to be true following is the code snippet avcaptureconnection lconnection nil for avcaptureconnection connection in lhandlem output connections for avcaptureinputport port in connection inputports if port mediatype isequalavmediatypevideo lconnection connection break if lconnection isvideoorientationsupported lconnection setvideoorientationavcapturevideoorientationportraitif lconnection isvideomirroringsupported lconnection setvideomirroredtruechanging setvideomirrored to truefalse also does not change anythingisvideomirroringsupported returns success,"['iphone', 'ios']" +248252,how to convert to use the yii cdataprovider on view i am trying to learn yii and have looked at yii documentation but still do not really get it i still have no idea how to use the cdataprovider on the controller and view to thisplay all the blog posts available on the view can anyone please advise or give an example based on the followingthe actionindex in my postcontrollerpublic function actionindex posts postmodelfindall thisrenderindex arrayposts poststhe view indexphpdivphp foreach post as post h2php echo posttitle h2php echo chtmldecodepostcontent php endforeach divinstead of doing the above can anyone please advise how to use the cdataprovider to generate insteadmany thanks,['php'] +248253,how can i support inbrowser thisplay of a pdf file in internet explorer 64bit adobe does not seem to support the thisplay of pdfs in the browser when using the 64bit version of internet explorer once a pdf link is clicked the 64bit internet explorer will always span a new adobe window to thisplay the pdf the 32bit internet explorer will thisplay the pdf embedded in the browser itself i noticed this issue when using the webbrowser control in a 64bit complied winforms net application i do not believe it is possible to use the 32bit webbrowser control in the 64bit application so i am looking for some solutions to this problem even if it requires the use of a third party plugin any suggestions would be greatly appreciatedthanks,['c#'] +248277,how to properly use webkitdevicepixelratio on ios and android webkitdevicepixelratio query is supported by both ios and android but since ios does not support targetdensitydpidevicedpi it leads to different results for examplemedia screen and webkitdevicepixelratio 2 body fontsize 2em will make font look good on galaxy nexus but on iphone 4 it will be too bigis there a way to emulate targetdensitydpidevicedpi on ios without javascript or to thisable webkitdevicepixelratio on ios and leave its users with blurry images as a fallback,"['android', 'css']" +248285,how do i make entire div a link i have a div like this div classxyzdiv and all the content in that div is in the css how do i make that div into a link i tried wrapping the a tag around it but that did not seem to workthanks,"['html', 'css']" +248294,jenkins not showing maven compiler errors when building our multimodule maven 3 project in jenkins if there is a build error we get this cryptic message that the maven compiler plugin failed this only just started happening within the last weekinfo build failureinfo info total time 1122340sinfo finished at fri feb 10 094402 cet 2012info final memory 171m318minfo mavenexecutionresult exceptions not emptymessage failed to execute goal orgapachemavenpluginsmavencompilerplugin202compile defaultcompile on project meactivityimpl compilation failurecause compilation failurestack trace orgapachemavenlifecyclelifecycleexecutionexception failed to execute goal orgapachemavenpluginsmavencompilerplugin202compile defaultcompile on project meactivityimpl compilation failure at orgapachemavenlifecycleinternalmojoexecutorexecutemojoexecutorjava213 at orgapachemavenlifecycleinternalmojoexecutorexecutemojoexecutorjava153 at orgapachemavenlifecycleinternalmojoexecutorexecutemojoexecutorjava145 at orgapachemavenlifecycleinternallifecyclemodulebuilderbuildprojectlifecyclemodulebuilderjava84 at orgapachemavenlifecycleinternallifecyclemodulebuilderbuildprojectlifecyclemodulebuilderjava59 at orgapachemavenlifecycleinternallifecyclestartersinglethreadedbuildlifecyclestarterjava183 at orgapachemavenlifecycleinternallifecyclestarterexecutelifecyclestarterjava161 at orgapachemavendefaultmavendoexecutedefaultmavenjava320 at orgapachemavendefaultmavenexecutedefaultmavenjava156 at orgjvnethudsonmaven3launchermaven3launchermainmaven3launcherjava79 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava39 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava25 at javalangreflectmethodinvokemethodjava585 at orgcodehausplexusclassworldslauncherlauncherlaunchstandardlauncherjava329 at orgcodehausplexusclassworldslauncherlauncherlaunchlauncherjava239 at orgjvnethudsonmaven3agentmaven3mainlaunchmaven3mainjava158 at hudsonmavenmaven3buildercallmaven3builderjava104 at hudsonmavenmaven3buildercallmaven3builderjava70 at hudsonremotinguserrequestperformuserrequestjava118 at hudsonremotinguserrequestperformuserrequestjava48 at hudsonremotingrequest2runrequestjava287 at javautilconcurrentexecutorsrunnableadaptercallexecutorsjava417 at javautilconcurrentfuturetasksyncinnerrunfuturetaskjava269 at javautilconcurrentfuturetaskrunfuturetaskjava123 at javautilconcurrentthreadpoolexecutorworkerruntaskthreadpoolexecutorjava650 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava675 at javalangthreadrunthreadjava595caused by orgapachemavenplugincompilationfailureexception compilation failure at orgapachemavenpluginabstractcompilermojoexecuteabstractcompilermojojava516 at orgapachemavenplugincompilermojoexecutecompilermojojava114 at orgapachemavenplugindefaultbuildpluginmanagerexecutemojodefaultbuildpluginmanagerjava101 at orgapachemavenlifecycleinternalmojoexecutorexecutemojoexecutorjava209 27 moremaven schlug mit fehlern fehlan attempt to send an email to empty list of recipients ignoredwhen building from the commandline we get the normal build errorsinfo info build failureinfo info total time 524906sinfo finished at fri feb 10 081731 est 2012info final memory 173m328minfo error failed to execute goal orgapachemavenpluginsmavencompilerplugin232compile defaultcompile on project meactivityimpl compilation failure compilation failureerror p4viewsvmbasemainmodulesactivityimplsrcmainjavacomsapmeactivityimplextensionconfigurationservicejava101812 cannot find symbolerror symbol class activityruntimetypeerror location class comsapmeactivityimplextensionconfigurationserviceerror p4viewsvmbasemainmodulesactivityimplsrcmainjavacomsapmeactivityimplextensionconfigurationservicejava20016 cannot find symbolerror symbol class activityruntimetypeerror location class comsapmeactivityimplextensionconfigurationserviceerror p4viewsvmbasemainmodulesactivityimplsrcmainjavacomsapmeactivityimplextensionconfigurationservicejava23416 cannot find symbolerror symbol class activityruntimetypeerror location class comsapmeactivityimplextensionconfigurationserviceerror p4viewsvmbasemainmodulesactivityimplsrcmainjavacomsapmeactivityimplextensionconfigurationservicejava26316 cannot find symbolerror symbol class activityruntimetypeerror location class comsapmeactivityimplextensionconfigurationserviceerror p4viewsvmbasemainmodulesactivityimplsrcmainjavacomsapmeactivityimplextensionconfigurationservicejava29420 cannot find symbolerror symbol class activityruntimetypeerror location class comsapmeactivityimplextensionconfigurationserviceerror p4viewsvmbasemainmodulesactivityimplsrcmainjavacomsapmeactivityimplextensionconfigurationservicejava316 cannot find symbolerror symbol class activityruntimetypeerror location class comsapmeactivityimplextensionconfigurationserviceerror p4viewsvmbasemainmodulesactivityimplsrcmainjavacomsapmeactivityimplextensionconfigurationservicejava102347 cannot find symbolerror symbol variable activityruntimetypeerror location class comsapmeactivityimplextensionconfigurationserviceerror p4viewsvmbasemainmodulesactivityimplsrcmainjavacomsapmeactivityimplextensionconfigurationservicejava102567 cannot find symbolerror symbol variable activityruntimetypeerror location class comsapmeactivityimplextensionconfigurationserviceerror help 1errorerror to see the full stack trace of the errors rerun maven with the e switcherror rerun maven using the x switch to enable full debug loggingerrorerror for more information about the errors and possible solutions please read the following articleserror help 1 errorerror after correcting the problems you can resume the build with the commanderror mvn goals rf meactivityimplwere using maven304 both for local builds and on jenkins jenkins version was 13ish but i upgraded to 1450 to see if the issue would go away it did not this happened about the time we moved from maven221 to maven304 but i could swear although i do not have evidence that i was getting normal build errors on jenkins just after the maven upgrade so i do not think that is it but it is the only change i can think of that would cause this the compiler plugin version is 202i saw a similar posting here but his issue had to do with eclipse builds not jenkins,['java'] +248323,ios copy files from main bundle to documents directory i am trying to copy files that i add to a folder called includes to a folder on documents directory called also includes i get for rescontents nil value why thank you voidcopyresources nsstring sourcepath nsbundle mainbundle resourcepath stringbyappendingpathcomponentincludes nsstring destpath self applicationdocumentsdirectory stringbyappendingpathcomponentincludes nsarray rescontents nsfilemanager defaultmanager contentsofdirectoryatpathsourcepath errornull for nsstring obj in rescontents nserror error if nsfilemanager defaultmanager copyitematpathsourcepath stringbyappendingpathcomponentobj topathdestpath stringbyappendingpathcomponentobj errorerror nslogerror error,"['iphone', 'objective-c', 'ios']" +248375,nuget behind proxy i figure out that nuget allows proxy settings configuration since 14 version but i cannot find any command line examplei am trying to run some build and nuget cannot connect how to configure the proxy settings in the command line,['c#'] +248376,jquery parsing xml get an element with a specific attribute i am developing an html5 applicationi want to parse an xml like this onexml version10 encodingutf8 cards card id3 name langesname description langesdescription name langenname description langendescription card cardsi want to get the name and description that have attribute langeni start writing code but i do not know how to finish itfunction loadcardslang ajax type get url dataenglishxml datatype xml successparsecardsxml function parsecardsxmlxml xmlfindcardeachfunction var id thisattrid var name thisfindname by the way loadcards function has an argument or parameter called langhow can i pass this argument to function parsercardsxmlxmlhow can i get name and description with a specific attribute,"['javascript', 'jquery']" +248379,retrieve first and last name of the current windows user i know you can retrieve the username with something like systemgetpropertyusername but i am looking for a way to retrieve the first and last name of the current user is there a native java library that does this or do you have to plug into the windows api or maybe you have to pull it from active directory this seems relatively easy with net but i cannot find a way to do it in java,['java'] +248388,how do i create and cancel unique uilocalnotification from a custom class currently i have a timer with an alarm local notificationi want to create a timer class from this code to create multiple timers and notifications at most 5 and i am struggling with how to create and cancel unique notifications with a class method uilocalnotification startalarm self cancelalarm clear any previous alarms alarm uilocalnotification alloc init alarmalertbody alert msg alarmfiredate nsdate datewithtimeinterval alarmduration sincedate starttime alarmsoundname uilocalnotificationdefaultsoundname uiapplication sharedapplication schedulelocalnotificationalarmmy assumption is that if i have a class method that creates a uilocalnotification called alarm ios will see all of the notifications as being the same notification and the following method will not function the way i want it to voidcancelalarm if alarm uiapplication sharedapplication cancellocalnotificationalarm so i need a way to name these uilocalnotifications as they are created eg alarm1 alarm2alarm5 so i can cancel the right onethanks in advance,"['objective-c', 'ios']" +248401,change placeholder text using jquery i am using a jquery placeholder plugin i need to change the placeholder text with the change in dropdown menu but it is not changing here is the codefunction inputplaceholder textareaplaceholderplaceholder sermemddchangefunction var k thisval if k 1 sermemtbattrplaceholder type a name lastname firstnameplaceholder else if k 2 sermemtbattrplaceholder type an idplaceholder else if k 3 sermemtbattrplaceholder type a locationplaceholder my htmldiv classfilterbox select nameddselect idsermemdd option value1 selectedselectedsearch by nameoption option value2search by idoption option value3search by locationoption select input idsermemtb typetext stylewidth 490px placeholdertype a name lastname firstname input idsemembut typebutton valuesearch divcan anyone figure this out,['jquery'] +248408,why compile error use of unassigned local variable my code is the following int tmpcnt if name dude tmpcnt why is there an error use of unassigned local variable tmpcnt i know i did not explicitly initialize it but due to default value table a value type is initialized with 0 anyways the reference also reminds meremember that using uninitialized variables in c is not allowed but why do i have to do it explicitly if it is already done by default wouldnt it gain performance if i wouldnt have to do it just wondering,"['c#', '.net']" +248418,authenticated wcf service for monotouch mono for android and wp7 iam writing a phone app where the end user should be able to access their own personal messages and other personal contentdoes anyone have some good ideas of how to create a service like this should i use soap or rest should i simply send the usernamepassword with every request or what would be the best choice for a service i would like to access from all three platforms and that only returns information specific to the authenticate user,['c#'] +248431,how to get current canvas i have drawview if i touch this view it draws small circles i wont to draw circles but not to touch view with help function setpoints what i do package comsamplesimport public class drawview extends view arraylistpoint points new arraylistpoint paint paint new paint private int psize 5 private int pcolor colorblack public drawviewcontext context attributeset attrs supercontext attrs setfocusabletrue setfocusableintouchmodetrue thissetontouchlistenernew viewontouchlistener override public boolean ontouchview v motionevent event vsetontouchlistenerthis point point new point pointx eventgetx pointy eventgety pointsaddpoint invalidate return true requestfocus override public void ondrawcanvas canvas for point point points canvasdrawcirclepointx pointy psize paint public void setpointsfloat xp float yp point point new point pointx xp pointy yp pointsaddpoint postinvalidate class point float x y override public string tostring return x y please tell me how get canvas out setpoints functionupdatewow it is really interesting problem my drawview contains in horizontalscrollview because if i set in this drawview right coordinates no one knows where are drawable circles,['android'] +248460,what is the correct sequent for calling super viewwillappear super viewdidload etc when providing an implementation of viewwillappear viewdidload viewdidappear loadview etcshould the calls to the superclasses corresponding methods be made before or after performing custom actionwhat are some possible consequences if performed in the wrong orderie should it be voidviewwillappearboolanimated super viewwillappearanimated stuffor voidviewwillappearboolanimated stuff super viewwillappearanimatedetc,"['ios', 'objective-c']" +248461,how to hide a in a menu with css i have realized that chrome it seems will not allow me to hide option in a select firefox willi need to hide the options that match a search criteria in the chrome web tools i can see that they are correctly being set to thisplay none by my javascript but once then select menu is clicked they are shownhow can i make these options that match my search criteria not show when the menu is clicked thanks,"['javascript', 'jquery', 'css']" +248462,spinlock and readonly fields just reading through the msdn page about new net 40 feature spinlock and can not understand idea behind the following statementdo not store spinlock instances in readonly fieldsmy feelings that this is somehow related to valuetype specifics but not sure how exactly and why could anybody bring more light on this point,"['c#', '.net']" +248513,case within a select case in mysql i am getting sick of trying to hook up to mssql so i am switching over to mysql it is slow progress heres my current stumper mssqlcreate function wm varchar255 returns int begindeclare e intset e select countn from p where and mdeclare t intset t dbocmreturn case t when 0 then 1 when 1 then case e when 0 then 1 else 1 endwhen 2 then case e when 1 then 1 when 2 then 0 when 3 then 0 when 4 then 1 endwhen 3 then case e when 1 then 1 when 2 then 1 endwhen 4 then case e when 1 then 1 when 2 then 0 when 3 then 1 endendendi would like to switch this to mysql is there a valid mysql way toselect select case and when 0 then 1 when 1 then 2 end into varhow about set var select case and when end,['mysql'] +248563,how long can a tld possibly be i am working on an email validation regex in php and i need to know how long the tld could possibly be and still be valid i did a few searches but could not find much information on the topic so how long can a tld possibly be,['php'] +248573,convert html to datatexthtml link using javascript heres my htmlaview it in your browseradiv idhtml h1doggiesh1 p stylecolorbluekittiespdivhow do i use javascript to make the href attribute of my link point to a base64 encoded webpage whose source is the innerhtml of divhtmli basically want to do the same conversion done here with the base64 checkbox checked except for in javascript,"['javascript', 'html']" +248577,rpython sys methods do not work i have the following codeimport sysdef entry pointargv sysexit1 return 0def targetargs return entry point nonehowever when i run python pypypypytranslatorgoaltranslatepy tpy i get the following errortranslationerror exception unexpected prebuilt constant builtin function exittranslationerror processing blocktranslationerror block9 is a class pypyobjspaceflowflowcontextspamblocktranslationerror in t3entry pointtranslationerror containing the following operationstranslationerror v0 simple callbuiltin function or method exit 1translationerror endthere was actually more to the error but i thought only this last part was relevant if you think more of it might be helpful please comment and i will editin fact i get another error when i replace sysexit with something even simpler like sysstdoutwriteimport sysdef entry pointargv sysstdoutwritesome mesgn return 0def targetargs return entry point nonegives metranslationerror annotatorerror annotation of v0 degenerated to someobjecttranslationerror v0 getattrmodule sys stdouttranslationerrortranslationerror in functiongraph of t3entry point at 0x10d03de10translationerror happened at file tpy line 4translationerrortranslationerror sysstdoutwritesome mesgntranslationerrortranslationerror previous annotationtranslationerror nonetranslationerror processing blocktranslationerror block3 is a class pypyobjspaceflowflowcontextspamblocktranslationerror in t3entry pointtranslationerror containing the following operationstranslationerror v0 getattrmodule sys stdouttranslationerror v1 getattrv0 writetranslationerror v2 simple callv1 some mesgntranslationerror endare sys methods simply off limits for rpython it seems kind of weird to me because exit and stdout are so readily available in c however the error messages kind of look like they might be about different things so i might just be barking down the wrong treecurrently i am using this guide to figure out roughly what is allowed and not allowed in rpython are there other rather accessible references i could use for more information,['python'] +248589,how to perform bulk actions with active admin in active admin is it possible to add a checkbox to each item in an index page this is not hard and add some kind of menu to perform bulk actions on all selected items like delete all selected items at oncei cannot find an other way to do this than to create a custom page but i would rather not do that seems like overkill to me,['ruby-on-rails'] +248610,django app engine 2012 refresh before you close the topic yes it is been asked before but the last time was early 2010are there any uptodate efforts to use django on gae djangonorel seems a little dated along with its effort to get joins and hence manytomany which i need i have not gone too far with django so if i would save myself a headache by changing to a different framework that still has orm i will accept that as a good answer tooin the long run i am trying to run something with the orm capabilities of django and the template capabilities of django on google app engine so i will take whatever solution meets my needsfor future readers i ended up using flask and the google app engines inbuilt datastore models,['python'] +248611,can i still receive broadcast receiver intent after i force stopped my app on android a simple question does it happens that i still receive the registered broadcast receivers after i force stopped the application,['android'] +248639,what is murmurhash3 seed parameter murmurhash3 x86 32 expects a seed parameter what value should i use and what does it do,['c++'] +248650,android userspace filesystem driver on nonrooted device can i write a custom userspace file system that can be run on nonrooted factory devices through the standard available utilitiesi am aware of the existence of fuseandroid however as far as i have understood it requires a rooted device if that is not the case please do correct methe goal i am trying to achieve is create a fake fs that actually is mounted to a file,['android'] +248655,merging two complex objects in php i have two data objects converted from json both are quite deeply complex and i would like to merge them in a similar fashion to how jquery would merge two objects using extendexamplejson 1 blah params foo default bar misc 0 json 2 blah params foo value val misc 1 merged into blah params foo default bar value val misc 1 whats the best way to approach this with php objects,['php'] +248709,never evaluates false i am having a problem with jstl and empty operator i already made few simple pages and everything worked fine but now i have page languagejava contenttypetexthtml charsetutf8 pageencodingutf8 taglib prefixc uri html body form actionprojektmyaccount methodpost table border1 tr tdartisttd tdrecord nametd tddeletetd tr cforeach varitem itemsrecords tr tditemartisttd tditemrecordnametd td input typecheckbox nameitemrecordnameitemrecordname td tr cforeach table hr input typesubmit nameback valueback cif testnot empty records input typesubmit namedelete valuedelete selected cif form body htmlnow no matter if i set the records attribute or not the delete button shows upcif testnot empty records input typesubmit namedelete valuedelete selected cifin normal situation to records attribute i pass arraylist and then use foreach but sometimes arraylist is empty so in those situations i do not want delete button to show up i fought that easiest way to achieve this would be to use this empty operator where am i making a mistakei even tried to manually set this attribute to nullif arsize 0 requestsetattributerecords arelse requestsetattributerecordsnulleditqwe yes you are right it worked for me before because i tested if attribute was empty in my way it was always true because i used wrong construct but it worked because i just wanted to show one string if there was no string nothing showed up so i was thinking that everything worked fine,['java'] +248742,setting up vim for ruby on rails i work with ruby on rails and wish to use vim as the editor of choice however i cannot find anywhere simple set of step by stepidiot proof instructions with well explained steps as to how to set it up properly i wish to set vim properly with nice plugins link vim for rails nerdtree and stuff like that please help me i would be most gratefulso far i have installed ror vim and git,['ruby-on-rails'] +248797,are lib files useless without the header files i have some lib files but i do not have access to the h header filesdoes this mean the lib files are useless nowif not how can i use them againi tried using this line in my program but it does not seem to be compiled into the final executable verified with cff explorerpragma commentlib somelibfilelibso the only way to link lib file is through the use of its header filesare there any tools to recover a header file for the lib file,['c++'] +248825,choosing svg or css3 for gradients i would like to use gradients heavily in a new website i am working on i have been wondering if it would be better to implement the gradients in css3 or svgtypically i only need multistop linear gradients so both meet my needs there i initially assumed this was best done in css3 but started to question my decision and would appreciate other opinionsmy thinking thus far is that svg as a css background may be better becauseit works in ie9my css is cleaner wo browser prefixeseasy reuse of gradientcss3 may be better becauseseems like a job for cssless downloads for the clienteverything is in one placean important consideration that i do not know the answer to is which performs betteris there a best practice for implementing background gradients,['css'] +248836,how to add libsvm class to weka classpath on a mac i am running max os x 107 lion and i want to use weka with libsvm from command line i get this errorproblem evaluating classifier libsvm classes not in classpathi found the libsvm library here i need to add it to my java classpath so that weka can find it the download contains several files shown below i do not know how to add them to my classpath for javai am attempting to use the libsvm classifier in weka because it is preferable for me over smo i am also unsure if this means the java classpath or if it is specific to weka i also do not know where to get these classes from any help is appreciated,['java'] +248840,c lightweight configuration library i am looking for a crossplatform c lighweight configuration library with non restrictive licence i need something more complex than standard properties file with sections but i do not want to use xml too much writing i would like to write configuration this wayrender window width 800 height 600,['c++'] +248844,ruby concurrency nonblocking io vs threads i am playing around with concurrency in ruby 193p0 and have created a very simple ioheavy proxy task first i tried the nonblocking approachrequire rackrequire rackfiber poolrequire emhttprequire emsynchronyrequire emsynchronyemhttpproxy lambda result emsynchronysync eventmachinehttprequestnewget 200 resultresponseuse rackfiberpool size 10run proxybegin thin p 30 e production r racksynchronyru start thin web server v131 codename triple espresso ab c100 n100 httplocalhost30concurrency level 100time taken for tests 5602 secondshtml transferred 21900 bytesrequests per second 1785 sec meantime per request 5602174 ms meanendhmm i thought i must be doing something wrong an average request time of 56s for a task where we are mostly waiting for io i tried another onerequire sinatrarequire sinatrasynchronyrequire emsynchronyemhttpget do emhttprequestnewgetresponseendbegin ruby sinatrasynchronyrb p 30 e production sinatra131 has taken the stage on 30 for production with backup from thin thin web server v131 codename triple espresso ab c100 n100 httplocalhost30concurrency level 100time taken for tests 5476 secondshtml transferred 21900 bytesrequests per second 1826 sec meantime per request 5475756 ms meanendhmm a little better but not what i would call a success finally i tried a threaded implementationrequire rackrequire exconproxy lambda result exconget 200 resultbody run proxybegin thin p 30 e production r rackthreadedru threaded noepoll start thin web server v131 codename triple espresso ab c100 n100 httplocalhost30concurrency level 100time taken for tests 2014 secondshtml transferred 21900 bytesrequests per second 4965 sec meantime per request 2014005 ms meanendthat was really really surprising am i missing something here why is em performing so badly here is there some tuning i need to do i tried various combinations unicorn several rainbows configurations etc but none of them came even close to the simple old ioblocking threading ideas comments and obviously suggestions for better implementations are very welcome,['ruby'] +248850,working with pdf in php shortwhat i want to do is to prepare php generated result for print with strong rules tried all possible ways with csshtml set dimensions in px mm cm nothing helped each browser even each printer printed absolutely different paper results tried both with wo border print also did not get result after long research found that css is not best way for this purpose and better way to use pdf creation functionality with php so installed tcpdf but cannot get it work with logical part that i created for html outputwhat i want to gettables first and last rows margin from top and bottom sides of paper must be 11 margin between rows 0 mmtables rows must be at 4 mm from left and right sides of paper2 mm between every column38 mm width x 212 mm height each cell13 x rows 5 x columns 13x565 cellseach table in new page in other words after each table page breakin each cell code 39 barcode value must be idonly tables in pdf result no header no footer no title etchere is more detailed explanation on imagewhat i am gettingafter form submission processing in php side takes too long about minute and opens blank page instead of pdf resultcodecode is not so huge comments are making it look like sophprequire oncetcpdfconfiglangengphprequire oncetcpdftcpdfphp create new pdf documentpdf new tcpdfpdf page orientation pdf unit pdf page format true utf8 falsepdfsetprintheaderfalsepdfsetprintfooterfalse set document informationpdfsetcreatorpdf creatorpdfsetauthorjohn smithpdfsettitlefalsepdfsetsubjectfalsepdfsetkeywordsfalse set default header dataset all false because do not want to output header footerpdfsetheaderdatafalse false false false set header and footer fontspdfsetheaderfontarraypdf font name main pdf font size mainpdfsetfooterfontarraypdf font name data pdf font size data set default monospaced fontpdfsetdefaultmonospacedfontpdf font monospacedset marginspdfsetmargins4 11 4pdfsetheadermarginpdf margin headerpdfsetfootermarginpdf margin footerset auto page breakspdfsetautopagebreaktrue pdf margin bottomset image scale factorpdfsetimagescalepdf image scale ratioset some languagedependent stringspdfsetlanguagearrayl set fontpdfsetfonthelvetica 10 add a pagepdfaddpage define barcode stylestyle array position align c stretch false fitwidth true cellfitalign border true hpadding auto vpadding auto fgcolor array0 0 0 bgcolor false array255255255 text true font helvetica fontsize 8 stretchtext 4ob startstyle typetextcss table width 100 bordercollapse collapse td img height10mm td padding 0 1mm 0 1mm verticalalignmiddle cell width 38mm height21mm fontstyle bold textalign center tr height21mm margin0 padding0 stylephpi 0item new itemdbforeach postcheckbox as id details itemgetdetailsid qt isset postqt postqt detailsqt for cnt 1 cnt qt cnt check if it is the beginning of a new table if i 65 0 echo table check if it is the beginning of a new row if i 5 0 echo tr echo tddiv classcellwfetyfrbr pdfcell0 0 code 39 ansi mh108m1983 usd3 3 of 9 0 1 pdfwrite1dbarcodeid c39 18 04 style n pdfln echo br detailshcode divtd check if it is the end of a row if i 1 5 0 echo tr check if it is the end of a table if i 1 65 0 echo trtable i if the last table is not full print the remaining cellsif i 65 0 for j i 65 j 65 j if j 65 0 echo table if j 5 0 echo tr echo tdtd if j 1 5 0 echo tr if j 1 65 0 echo table markup ob get clean output the html contentpdfwritehtmlmarkup true false true false reset pointer to the last pagepdflastpage close and output pdf documentpdfoutputbcsheetpdf iscript works like thatuser selects items checkboxesafter form submission php gets values of checked checkboxes via ajaxin foreach loop php gets quantities of each item from databasegenerated table,['php'] +248851,confusion regarding quartz2d core graphics core animation core images i am working on a project which requires some image processing i also asked question regarding it and i got very good solution here is the link create whole new image in ios by selecting different propertiesbut now i want to learn this in more detail and i am confused from where should i start learning quartz 2d or core animation or core graphics or core imageapple documents say regarding quartz 2d thatthe quartz 2d api is part of the core graphics framework so you may see quartz referred to as core graphics or simply cgand apple docs says about core graphics that the core graphics framework is a cbased api that is based on the quartz advanced drawing enginethis is confusing how they both relate to each othernow core animation contains all concepts of coordinates bounds frames etc which is also required in drawing imagesand core image is introduced in ios 5 from where should i start learning or i which sequence i start learning all these,['ios'] +248868,android animate drop downup view proper okay i am trying to do a proper slide down animation the view that slides down should push all views bellow it down in one smooth movement and again when it slides up all the views should follow in one smooth movementwhat i have tryed in codelinearlayout lin linearlayoutfindviewbyidriduser list container setlayoutanimslidedownfromtoplin this linaddviewgetlayoutinflaterinflaterlayoutuser panelnull0andpublic static void setlayoutanimslidedownfromtopviewgroup panel context ctx animationset set new animationsettrue animation animation new alphaanimation00f 10f animationsetduration100 setaddanimationanimation animation new translateanimation animationrelative to self 00f animationrelative to self 00f animationrelative to self 10f animationrelative to self 00f animationsetduration500 setaddanimationanimation layoutanimationcontroller controller new layoutanimationcontrollerset 025f panelsetlayoutanimationcontrollermy user panelxmlxml version10 encodingutf8linearlayout xmlnsandroid androidlayout widthmatch parent androidlayout height40dp androidorientationvertical imageview androidlayout alignparentlefttrue androidlayout heightwrap content androidlayout widthwrap content androidsrcdrawableicon linearlayouttop of main xmllinearlayout androidididuser list container androidlayout alignparenttoptrue androidorientationvertical androidlayout widthfill parent androidlayout heightwrap content linearlayout androidididcontainer androidlayout belowiduser list container androidorientationvertical androidlayout widthfill parent androidlayout heightwrap contentthe problem with above approach is that when i start the animation first the empty space for the view is created and then the view slides down i would like it to slowly push all the other views down instead of doing it in one hard motion,['android'] +248883,pyside pyqt detect if user trying to close window is there a way to detect if user trying to close windowfor example in tkinter we can do something like thisdef exit dialog do stuff passroot tkrootprotocolwm delete window exit dialogrootmainloopthanks,['python'] +248884,g optimization options affect the value of sin function i have a problem with sin function of libcinclude cmathinclude stdiohint mainint argc char argv double tt 628318530717958620 2 m pi double yy sintt printf32fn yy return 0when compile the above code using g without any optimization option it would output 024492127076447545 but if with o3 option it would output 024492935982947064why does not it return 024492935982947064 without o3thanks in advance,"['c++', 'c']" +248890,postgresql how to implement minimum cardinality as answered in this question cardinality in postgresql cardinality is enfforced using constraintscardinality rules define the allowable counts of the relationships a onetomany manytomany etc manytomany is achieved using jointables and onetomany using foreign keybut how can one implement onetoone or many oneto1 relationship which is same as to ask how can i enforce minimum cardinality in postgresqla practical situation would be where one needs to store say address or telephone number which must be provided but can be more that one by the person say user or customereditthe above mentioned situation is a special case with cardinality one of a general problem the general problem being how to enforce cardinality of arbitrary numberas answered by jug a nonnull foreign key reference can be used as a workaround if minimumcardinality is one it will also provide an additional feature to select default among manybut consider another situation of relationship between team of cricket and its players every team must have a minimum of 11 players to qualify as a team here the minimum cardinality is eleven 11similary a relation between a course and a student in a school where every student must enroll in atleast 5 courses and every course must have a minimum of 10 students,['sql'] +248892,how to check if iframe is loaded or it has a content i have an iframe with id myiframe and here my code to load it is content myiframeattrsrc my urlthe problem is sometimes it take too long for loading and sometimes it loaded very quickly so i must to use settimeout function settimeoutfunction if something shows iframe is loaded or has content my code else myiframeattrsrc stop loading content 50all i want to know is how to find out if an iframe is loaded or it has content using iframecontentsfind will not work i cannot use iframeloadfunction,"['javascript', 'jquery']" +248927,what are the real advantages of using blocks in objectivec i have learned about blocks in objc the syntax is clear and simple i can read ablocks are a great feature the syntax isa almost everywhere however i miss the real advantages of their using maybe it is a silly question i have just started with objc but what are the real advantages of blocks over a atraditionala approach can anybody give me some brief and clear explanation,['objective-c'] +248934,memory limit hit with appenginemapreduce i am working on appenginemapreduce function and have modified the demo to fit my purposebasically i have a million over lines in the following format userid time1 time2 my purpose is to find the difference between time1 and time2 for each userid however as i run this on google app engine i encountered this error message in the logs sectionexceeded soft private memory limit with 18056 mb after servicing 130 requests totalwhile handling this request the process that handled this request was found to be using too much memory and was terminated this is likely to cause a new process to be used for the next request to your application if you see this message frequently you may have a memory leak in your applicationdef time count mapdata time count map function entry text fn data text text fn try q textsplitn for m in q reader csvreadermreplace0 skipinitialspacetrue for s in reader calculate time elapsed sdw s1 start date timestrptimesdwmdy imsp edw s2 end date timestrptimeedwmdy imsp time difference timemktimeend date timemktimestart date yield s0 time difference except indexerror e loggingdebugedef time count reducekey values time count reduce function time 00 for subtime in values time floatsubtime realtime inttime yield s dn key realtimecan anyone suggest how else i can optimize my code better thankseditedheres the pipeline handlerclass timecountpipelinebase handlerpipelinebase a pipeline to run time count demo args blobkey blobkey to process as string should be a zip archive with text files inside def runself filekey blobkey loggingdebugfilename is s filekey output yield mapreduce pipelinemapreducepipeline time count maintime count map maintime count reduce mapreduceinput readersblobstorezipinputreader mapreduceoutput writersblobstoreoutputwriter mapper params blob key blobkey reducer params mime type textplain shards32 yield storeoutputtimecount filekey outputmapreduceyamlmapreduce name make messages lowercase params name done callback value done mapper handler mainlower case posts input reader mapreduceinput readersdatastoreinputreader params name entity kind default mainpost name processing rate default 100 name shard count default 4 name make messages upper case params name done callback value done mapper handler mainupper case posts input reader mapreduceinput readersdatastoreinputreader params name entity kind default mainpost name processing rate default 100 name shard count default 4the rest of the files are exactly the same as the demoi have uploaded a copy of my codes on dropbox,['python'] +248947,set canvas size using javascript i have the following code in htmlcanvas idmycanvas width 800 height800i want instead of specifying the width as 800 to call the javascript function getwidth to get the width eg canvas idmycanvas width getwidth height800what is the correct syntax to do it because what i am doing does not work,"['javascript', 'html']" +248949,stacking astronomy images with python i thought this was going to be easier but after a while i am finally giving up on this at least for a couple of hoursi wanted to reproduce this a trailing stars image from a timelapse set of pictures inspired by thisthe original author used low resolution video frames taken with virtualdub and combined with imagej i imagined i could easily reproduce this process but with a more memoryconscious approach with python so i could use the original highresolution images for a better outputmy algorithms idea is simple merging two images at a time and then iterating by merging the resulting image with the next image this done some hundreds of times and properly weighing it so that every image has the same contribution to the final resulti am fairly new to python and i am no professional programmer thatll be evident but looking around it appears to me the python imaging library is very standard so i decided to use it correct me if you think something else would be betterheres what i have so farprogram to blend many images into oneimport osimagefiles oslistdirfinalimageimageopenfiles0 add the first imagefor i in range1lenfiles note that this will skip files0 but go all the way to the last file currentimageimageopenfilesi finalimageimageblendfinalimagecurrentimage1floati1alpha is 1i1 so when the image is a combination of i images any adition only contributes 1i1 print r stri1 strlenfiles lousy progress indicatorfinalimagesaveallblendedjpgjpegthis does what it is supposed to but the resulting image is dark and if i simply try to enhance it it is evident that information was lost due lack of depth in pixels values i am not sure what the proper term here is color depth color precision pixel size heres the final result using low resolution imagesor one i was trying with the full 4k by 2k resolution from another set of photosso i tried to fix it by setting the image modefirstimageimageopenfiles0size firstimagesizefinalimageimagenewisizebut apparently imageblend does not accept that image modevalueerror image has wrong modeany ideasi also tried making the images less dark by multiplying it before combining them with impointlambda i i 2 but results were just as bad,['python'] +248950,prevent page scroll on drag in ios and android i am working on a html5 canvas game but i do not know how to handle touch events when a user touch the screen and drag then the browser will scroll the page i would like to prevent it and get the touch start and touch end position is it possiblethanks in advance,['javascript'] +248956,css selector spanfirstchild issue i have a div inside that div i have a table with 2 rows in the second row i have a single td in that td i have first a img than a span than another span and finally another img i would like to select through css the first span and give it a red color here below my code unfortunately it is not working hope someone can help thank you in advance for your replies cheers marc by the way the html structure might look stupid i agree i just simplified to ease the lecture so no need to comment the codediv idmydiv table cellspacing0 tr td spansome textspan td tr tr td img srcimgquotesopenpng alt spanspan1span spanspan2span img srcimgquotesclosepng alt td tr table divmydiv trnthchild2 spanfirstchild colorred,['css'] +248959,core data nsfetchrequest returns unsorted array after deleting object and refetching data i have a core data database built using a uimanageddocument that i load into a uitableview and also plot certain points of that data on a graph i find that when i add an object to the database or delete an object from the database and then fetch the data the array that nsfetchrequest returns is not sorted even though i have a sort descriptor in the request the interesting part is that if i wait a few seconds and then fetchrefetch the data it now comes back sorted i think i must be doing something wrong is there some kind of callback i should be using from core data to know that the database change was completed it is strange because all the data is always in the database just not sorted i am not super experienced with it so i am not sureheres the code from my fetch requestnsfetchrequest request nsfetchrequest alloc initwithentitynamefuelpurchasenssortdescriptor sortdescriptor nssortdescriptor alloc initwithkeydatetimestamp ascendingyesrequestsortdescriptors nsarray arraywithobjectsortdescriptornserror error nilselffuelpurchasedatabasemanagedobjectcontext executefetchrequestrequest errorerror,"['iphone', 'ios']" +248969,android sending post requests to django server csrf failing i would like my android app to be able to send some information to my django server so i made the android app send a post request to the mysiteupload page and djangos view for this page would do work based on the post data the problem is the response the server gives for the post request complains about csrf verication failed looking in to the problem it seems i might have to get a csrf token from the server first then do the post with that token but i am unsure how i do this edit i have found out that i can knock off the crsf verification for this view using a view decorator csrf exempt but i am not sure if this is the best solution my android code create a new httpclient and post header httpclient httpclient new defaulthttpclient httppost httppost new httpposturl add your data listnamevaluepair namevaluepairs new arraylistnamevaluepair2 namevaluepairsaddnew basicnamevaluepairscoreone scoreone namevaluepairsaddnew basicnamevaluepairscoretwo scoretwo httppostsetentitynew urlencodedformentitynamevaluepairs systemoutprintlnhuzah execute http post request httpresponse response httpclientexecutehttppost bufferedreader in new bufferedreadernew inputstreamreaderresponsegetentitygetcontent stringbuffer sb new stringbuffer string line string nl systemgetpropertylineseparator while line inreadline null sbappendline nl inclose string result sbtostring systemoutprintlnresult resultand my views code for handling the upload uploads a players matchdef uploadrequest if requestmethod post scoreone intrequestpostscoreone scoretwo intrequestpostscoretwo m matchobjectscreate matchparticipantobjectscreateplayer playerobjectsgetpk1 match m score scoreone matchparticipantobjectscreateplayer playerobjectsgetpk2 match m score scoretwo return httpresponsematch uploaded enter code here,['android'] +248975,android showhide a view using an animation i have been looking through many google results questions on here to determine how to showhide a view via a vertical animation but i cannot seem to find one that is exactly right or not too vaguei have a layout undo bar that is below another layout and above multiple other widgets this undo bar should vertically slide open and slide closed depending on the circumstancescurrently all i do right now is set the view to be visible or goneplease help,['android'] +248978,how to implement a hashkey navigation i want to implement a ajax based hashkey navigation like thisany advice herethanks in advance,['javascript'] +248989,python web framework most like aspnet mvc 3 as much as i enjoy building on aspnet mvc it is time to move off windowsi would like to switch to something pythonbased with the least amount of painwithout thiscussing the merits of or reasons for switching which python web framework is most similar to aspnet mvc 3 in terms of architecturearchitectural examplesi am talking about the flow not the languagetypical net routeroutesmaproute maps requests at product to productcontroller products route name productactionid url with parameters new controller product action index id urlparameteroptional parameter defaultstypical net controllerpublic class productcontroller public actionresult indexindexinputmodel inputmodel do something with inputmodel var viewmodel new productindexviewmodel products productlist return viewviewsproductindexcshtml viewmodel typical viewsproductindexcshtml net razor viewmodel productindexviewmodelh2productsh2foreach var product in modelproducts h3producttitleh3 pproductdescriptionp span classpriceproductpricespan,['python'] +248994,undefined reference to pthread create a linker command option order libraries beforeafter object files when i try to compile that i receive a particular error but it is not possible because i use the right flag in serverc there is the library pthreadhso how can i resolve my linking problemi am using linux ubuntu makegcc c wall wunused ansi pedantic ggdb o server1o servercgcc c wall wunused ansi pedantic ggdb utilcgcc o server1exe wall wunused ansi pedantic ggdb lpthread lm server1o utiloserver1o in function mainhomeruggeroruggero fineserverc1002 undefined reference to pthread createcollect2 ld returned 1 exit statusmake server1exe errore 1,['c'] +248999,space between uitableview cells i have a uitableview which contains x amount of cells however i want to have 20 px thistance between each cell my tableview only contains one sectioni have googled around and searched the forum but i could not find anything that works for my purpose is it possible to set content offset to the cell or the imageview inside the cellcan someone please help me,"['iphone', 'objective-c']" +249029,appending nsdictionary to other nsdictionary i have one nsdictionary and it loads up uitableview if a user scrolls more and more i call api and pull new data this data is again in the form of an nsdictionary is it possible to add the new nsdictionary to the existing one,"['objective-c', 'ios']" +249066,ef migrations for databasefirst approach were using database first approach with entityframeworkweve several customers and when we deploy new product version were now applying db schema changes manually with tools like sql compareis there a way how ef migrations could help to apply changes to customers db automatically,['c#'] +249076,python 2 different meaning of the in keyword for sets and lists consider this snippetclass someclassobject def init self someattributesomevalue selfsomeattribute someattribute def eq self other return selfsomeattribute othersomeattribute def ne self other return not self eq otherlist of objects someclassprintsomeclass in list of objectsset of objects setsomeclassprintsomeclass in set of objectswhich evaluates totruefalsecan anyone explain why the in keyword has a different meaning for sets and listsi would have expected both to return true especially when the type being tested has equality methods defined,['python'] +249100,array of interface in java i have an interfacepublic interface module void init void actionswhat happens when i try to create an array like thismodule instances new module20how can i implement this array,['java'] +249122,horizontal vs vertical table design sql apologies if this has been covered thoroughly in the past i have seen some related posts but have not found anything that satisfies me with regards to this specific scenarioi have been recently looking over a relatively simple game with around 10k players in the game you can catch and breed pets that have certain attributes ie wings horns manes there is currently a table in the database that looks something like this pet id wings1 wings1 hex wings2 wings2 hex horns1 horns1 hex 1 1 f null null 2 0 2 null null null null null null 3 2 ff0 1 f 3 00ff00 4 null null null null 1 0ff etcthe table goes on like that and currently has 100 columns but in general a single pet will only have around 18 of these attributes a new attribute is added every 12 months which requires table columns to be added the table is rarely updated and read frequently i have been proposing that we move to a more vertical design scheme for better flexibility as we want to start adding larger volumes of attributes in the future ie pet id attribute id attribute color attribute position 1 1 f 1 1 3 0 2 3 2 f 1 3 1 ff0 2 3 3 00ff00 3 4 3 0ff 1 etcthe old developer has raised concerns that this will create performance issues as users very frequently search for pets with specific attributes ie must have these attributes must have at least one in this colour or position must have 30 attributes currently the search is quite fast as there are no joins required but introducing a vertical table would presumably mean an additional join for every attribute searched and would also triple the number of rows or sothe first part of my question is if anyone has any recommendations with regards to this i am not particularly experienced with database design or optimisationi have run tests for a variety of cases but they have been largely inconclusive the times vary quite significantly for all of the queries that i ran ie between half a second and 20 seconds so i suppose the second part of my question is whether there is a more reliable way of profiling query times than using microtimetrue in phpthanks,"['php', 'mysql']" +249132,thisable screenshots in android ics for one of our secure apps there is a requirement to thisable the screenshot capability for the app in android ics is this possible on a nonrooted devicethanksrajath,['android'] +249164,jquery collect all option values from select box in a json array i have a select boxselect idx option value1vineetoption option value2vivekoption option value3madhuoptionselectthe options are added dynamically to it at the end i want to collect the values of all option elements contained within this select box into an array i searched the forum for the answer but qa are there for getting the selected option onlyi tried thisvar mylist xeachfunction mylistpush thisvalue in firebug it gives this errormissing after property listbut i fail to see any missing what am i doing wrong here,"['javascript', 'jquery', 'html']" +249173,debugging when using requirejs cache using requirejs i noticed that often the dependencies are cached by the browser and do not get updated even if i force the page to completely reload commandshiftrin order to have always the updated file i made requirejs ask for the files adding datestamp after the url the only problem with this approach is that the breakpoints do not remain in chrome or firebug after reloading making the debug painfuldo you have any suggestion,['javascript'] +249203,eclipse with android plugin blocked at calculating requirements and dependencies i have a problem during the installation of android in eclipse indigo and helios i have tried many different versions when i search the plugin with the adress or localy with the archive it does not workit found the developpment tools but it block at calculating requirements and dependencieswhats the problem,['android'] +249204,how to write to a file using non blocking io i want to write to a file using a nonblocking method in python on some googling i found that the language supports fcntl in order to do so but the method to implement the same is not very clear to me this is the code snippet i do not know where i am going wrongimport os fcntlnf fcntlfcntl0fcntlf unclkfcntlfcntl0fcntlf setfl nf oso nonblock nf open testtxt a nfwrite sample text nis this the correct way to perform a nonblocking io operation on a file i doubt it also could you suggest any other modules in python which allow me to do so,['python'] +249206,is using actioninvoke considered best practice if i have the below code should i just call the action or should it call actioninvokepublic class classa public event actionstring onadd private void somethinghappened if onadd null onaddit happened should it be onaddinvokeit happened public class classb public classb var myclass new classa myclassonadd add private void addstring input do something,"['c#', '.net']" +249210,is it possible to create properties on the fly with a net dynamic object i am trying to create a some json in my mvc app and i only want to include the properties from my source object if it has some properties values setegpublic class foo public string a get set public string b get set public int c get set public lol d get set example outputsa and c have values onlyreturn jsonnew a sourcea c sourcecvalue d only has been setreturn jsonnew d sourced see how i was trying to create an anonymous object on the fly well i can do that because in this contrite example i know what was set but when it comes to real code i would have to do figure out what was really set and then dynamically return thatthe idea is based upon stack exchanges api wrapper where they have some optional values that they return via json if they are set,"['c#', '.net']" +249217,bigdecimalmovepointright hangs with very large numbers the following program freezes and i cannot work out why import javamathpublic class bigdec public static bigdecimal expdouble z find ez eintpart efracpart return new bigdecimalmathepowintz mathcontextdecimal128 multiplynew bigdecimalmathexpzintz mathcontextdecimal128 public static void mainstring args this works ok bigdecimal x new bigdecimal3e200 systemoutprintlnx x systemoutprintlnxmovepointright1 xmovepointright1 this does not x exp123456789 systemoutprintlnx x systemoutprintlnxmovepointright1 xmovepointright1 hangs for the present purposes the first method just creates a very large bigdecimal details it finds e to the power of z even when this too large to be a double i am pretty sure this method is correct though the mathcontexts may not be in the best places i know e123456789 is extremely big but i really do want to use numbers like this any answers would be very gratefully received,['java'] +249224,using boilerpipe to extract nonenglish articles i am trying to use boilerpipe java library to extract news articles from a set of websites it works great for texts in english but for text with special characters for example words with accent marks hista3ria this special characters are not extracted correctly i think it is an encoding problemin the boilerpipe faq it says if you extract nonenglish text you might need to change some parameters and then refers to a paper i found no solution in this papermy question is are there any params when using boilerpipe where i can specify the encoding is there any way to go around and get the text correctlyhow i am using the libraryfirst attempt based on the url url url new urllinkstring article articleextractorinstancegettexturlsecond on the htlm source codestring article articleextractorinstancegettexthtml page as string,"['java', 'html']" +249231,is this possible to customize printf i have some struct that i need to print frequently for now i am using a classical print wrapper around this struct void printf mystructstruct my struct if my structnull return printfvalue1d value2d structvalue1 structvalue2this function is handy but is also really limited i cannot prepen or append some text without making a new wrapper i know that i can use va arg family to be able to prepend or apprend some text but i feel like i would be reimplementing the wheeli am wondering if it is possible to write a customizing function to printf i would like to be able to write something like this register2printfmys printf mystruct if incorrect printfl struct is incorrect mysn log level my structis this possible how can i do this nb i am under ubuntu linux 1004 and i use gcc,['c'] +249240,how can i sort method implementations according to their declaration order is there any visual studio 2008 addin or macros to sort method implementations in cpp file according to the order of their declarations in h fileedit any recent visual studio 2010 2013 2015,['c++'] +249255,is there any thisadvantage to using print in my stored procs i cannot believe after all these years i am asking this question butis there any thisadvantage to using print in my stored procs i have bee using it for debugging but should i remove them after i am done i would rather not if i do not have to,['sql'] +249273,hibernate spring mvc objects mapping configuration is there any way to define objects in hibernatecfgxml by scope and not one by onefor example in spring you can define all controllers by such annotationcontextcomponentscan basepackagecrmcontroller can i define hibernate classes in the same way or it must be defined one by onethank you,['java'] +249281,c stl duplicating code due to missing baseclass for iterator and reverse iterator in my current cproject i have an stl map which maps integer keys onto objects an algorithm returns a set of entries the returned data depends on the algorithms input and hence cannot be predicted class myclass int myalgorithmvectorintiterator inputit return a key for mymap which is calculated by the current value of inputdata int mainint argc char argv vectorint inputdata mapint myclass mymap fill map with some data fill inputdata vectormyclass result for vectorintiterator it inputdatabegin it inputdataend it int mymapkey myalgorithmit count 0 means check whether element exists performance can be improved by replacing the operator and count calls by mapfind however i want to simplify things in this example if mymapcountmymapkey 0 in some cases there is no entry in mymap resultpush backmymapmymapkey as mentioned in the example i can replace mapcount and operatorcalls with find the stlreference says that mapfinds complexity is logarithmic in size olog ni thiscovered that in most cases the entries in mymap are very close for two sequent entries in the result therefore i came to the conclusion that i would achieve better performance if i replaced the mapfind calls by iterators mapint myclassiterator mymapit mymapbegin for vectorintiterator it inputdatabegin it inputdataend it int mymapkey myalgorithmit just increment iterator while mymapkey mymapitfirst mymapit we did not find anything for the current input data if mymapit mymapend mymapitfirst mymapkey break i know that i am checking this twice but that is not the point of my question if mymapit mymapend mymapitfirst mymapkey probably it would be better to move the iterator back to the position where we started searching to improve performance for the next entry mymapit mymapbegin else resultpush backmymapitsecond this concept works but i have a big problem depending on the inputdata i have to search forward or backward consider that i call the code inside main multiple times and the inputdata changes for these calls instead of checking whether to increment or decrement the iterator inside the whileloop i could decide that before entering the forloopi thought that i am fine with just switching the mapiterator to mapreverse iterator and using rbeginrend instead of beginend but then i realized that reverse iterator and iterator have no common base class mapint myclassbase iterator myit if mymapit mymapbegin mymapendit mymapend else mymapit mymaprbegin mymapendit mymaprend for that would be great but there is no base iteratori know a simple workaround for this problem i just need to copy the whole forloop and adjust it for both cases if for which uses normal iterator in the whileloop else for which uses reverse iterator in the whileloop very bad do you know a better solution,['c++'] +249282,install java program as a windows service alternative to javaservice i would like to install a java application as a windows service i did so successfully a couple of years ago using this java service wrapper unfortunately it seems like this tool is not in development anymore and thus no windows 7 and 64 bit versions are available i need to install my java application on windows 7 and xp machines does anyone know a good alternativeedit i need this for commercial use the suggested java service wrapper from tanuki is too expensive,['java'] +249287,color console output with c in windows is there a way to output colored text to the consolei am using visual studio 2010 and only need the code to work in windowsi have been unsuccessful in finding anything except the windows color command but that changed the color for the entire screen and i am looking for something that will change only the part i wish to output i have seen it done in managed ceg color redcout hello color bluecout worldnwould yield hello world in red and blue,['c++'] +249326,file upload in spring 3 mvc null pointer exception i am using spring mvc 3 i have been trying to access the attributes of the uploaded file but i keep getting the following error message i can access the other fields of the form that is posted but i cannot access the uploaded filenullhandleform failed to convert property value of type javalangstring to required type orgspringframeworkwebmultipartcommonscommonsmultipartfile for property file nested exception is javalangillegalstateexception cannot convert value of type javalangstring to required type orgspringframeworkwebmultipartcommonscommonsmultipartfile for property file no matching editors or conversion strategy found htmljsp filepage languagejava contenttypetexthtml charsetiso88591 pageencodingiso88591taglib prefixform uri doctype htmlhtmlhead meta httpequivcontenttype contenttexthtml charsetutf8 titlejsp pagetitleheadbody presponsep h1upload songsh1 table formform action commandnamehandleform tr tdsong name td tdforminput pathsongnametd tr tr tdartist name td tdforminput pathartistnametd tr tr tdgendre td tdforminput pathgendretd tr tr tddescription td tdformtextarea pathdescriptiontd tr tr tdbrowse file td tdforminput typefile pathfile td tr tr td colspan2 styletextalign centerinput typesubmit valuesubmit td tr formform table bodythe form handlerclasspublic class handleform private string songnameprivate string artistnameprivate string gendreprivate string description private commonsmultipartfile filepublic commonsmultipartfile getfile return filepublic void setfilecommonsmultipartfile file thisfile file public string getartistname return artistnamepublic void setartistnamestring artistname thisartistname artistnamepublic string getdescription return descriptionpublic void setdescriptionstring description thisdescription descriptionpublic string getgendre return gendrepublic void setgendrestring gendre thisgendre gendrepublic string getsongname return songnamepublic void setsongnamestring songname thissongname songname the controllercontrollerpublic class admincontroller requestmappingvalue admin method requestmethodgetpublic string showadmin return adminindexrequestmappingvalue adminuploadsongs method requestmethodgetpublic string showcontactsmodel model modeladdattributenew handleform return adminuploadrequestmappingvalue adminuploadsongs method requestmethodpostpublic string doformmodelattributevalue handleform handleform handleform bindingresult result model model ifresulthaserrors string stringlist null listfielderror errors resultgetfielderrors for fielderror error errors stringlist errorgetobjectname errorgetdefaultmessage n modeladdattributeresponse stringlist modeladdattributesongname handleformgetsongname works fine modeladdattributefilename handleformgetfilegetoriginalfilename throws an error return adminuploadany help would be much appreciated thanks in advance,['java'] +249330,accessing emails from gmail using imap javamail api i am trying to access emails from gmail accounts through imap with the help of the javamail api i was wondering why the code works for one email account but does not work for another i am able to access the inbox folder of both email accounts but for one of the email accounts other folders like spamgmailspam are not able to be accessed and it throws a foldernotfoundexception exception could anybody please explain what is going wrong thank you in advancehere is the codeimport javaioimport javautilimport javaxmailimport javaxmailflagsflagimport javaxmailinternetimport comsunmailimapimapfolderimport comsunmailimapimapmessagepublic class folderfetchimap public static void mainstring args throws messagingexception ioexception imapfolder folder null store store null string subject null flag flag null try properties props systemgetproperties propssetpropertymailstoreprotocol imaps session session sessiongetdefaultinstanceprops null store sessiongetstoreimaps storeconnectimapgooglemailcom password folder imapfolder storegetfoldergmailspam this does not work for other email account folder imapfolder storegetfolderinbox this works for both email account iffolderisopen folderopenfolderread write message messages foldergetmessages systemoutprintlnno of messages foldergetmessagecount systemoutprintlnno of unread messages foldergetunreadmessagecount systemoutprintlnmessageslength for int i0 i messageslengthi systemoutprintln systemoutprintlnmessage i 1 message msg messagesi systemoutprintlnmsggetmessagenumber object string systemoutprintlnfoldergetuidmsg subject msggetsubject systemoutprintlnsubject subject systemoutprintlnfrom msggetfrom0 systemoutprintlnto msggetallrecipients0 systemoutprintlndate msggetreceiveddate systemoutprintlnsize msggetsize systemoutprintlnmsggetflags systemoutprintlnbody n msggetcontent systemoutprintlnmsggetcontenttype finally if folder null folderisopen folderclosetrue if store null storeclose,['java'] +249332,creating mysql users via linux command line i am working on a python script to setup servers quickly and it basically has a list of commands i want to execute on the linux commandlinei can install all the software i need but not sure how to create a mysql user solely via command line i can i can go into the mysql shell and do it but is there a way to do it solely from the linux shellonce the user is created i can do all the database setup remotely with a python script,['mysql'] +249380,is copying of entire queue with operator thread safe c i have generic queuet systemcollectionsgeneric which is accessed for writing from one thread and it must be accessed from another thread for readingi do not want to do any process synchronization which includes using concurrentqueuet for performance reasons so i came up with idea to copy the entire queue to another queue object of same type in the reading thread subsequent operations in the reading thread will be done on the copy copying will be done with simple operator here is some pseudocodecreating main queuequeuemytype queue1 new queuemytypewriting threadperform writing in the main queuequeue1enqueueobjectqueue1dequeuereading threadcopy main queue queuemytype queue2 queue1perform all operations in reading thread on queue2so is such solution thread safeupd thank you very much i was not aware that this is merely copying of the link so is there a way to copy entire object by value in threadsafe manner,['c#'] +249421,iostream vs ostream what is different as book says exploring c the programmers introduction to cthe istream header declares input operators and ostream declares output operatorsi can perfectly run that code without adding include ostreaminclude iostreamusing namespace stdint main cout hello world endl return 0but in books example likeinclude iostreaminclude ostream whyusing namespace stdint main cout hello world endl return 0so iostreamostreamistream are header files rightif ostream is not necessary iostream makes the jobs why author include it in example or why ostream header file still existnote in bruce eckels vol 1 book which is published in 20 there is nothing about ostream or istream only one header file which is iostream,['c++'] +249445,php metaphone implementation bug i am testing a metaphone implementation for c and comparing its results against the builtin metaphone function from php however i have come across a bug which is previously documented in phps issue tracker and thiscussed on a mailing list but i am trying to understand the c code behind their bug for my own personal interestbasically according to the metaphone algorithm most instances of gh should be rendered silent in the specific test case of wright i expect and generate with my own algorithm a metaphone key of rtwr ri ignoredgh ignoredt tresult rthowever phps metaphone function returns rft clearly it is converting the gh to an f as if it were at the end of a word eg rough but in the case of the word wright this is incorrect because the gh does not come at the end of the word looking at the metaphonec file in the php source thistribution i see a few key things these prevent gh from becoming f define noghtofc encodec 16 bdh go and letters back define look back lettern w idx and toupperwordw idxn 0and then on line 342case g if next letter h if noghtoflook back letter3 look back letter4 h phonizef skip lettercan someone help me understand what exactly the noghtof function does and why this code is incorrectly rendering an f for the gh in wright i am not really a c guy so the code is not at all clear to me,"['php', 'c']" +249446,why does upgrading to rails 321 cause multiple rspec tests to fail all 211 specs in my test suite were passing fineuntil i upgraded from rails 32 to rails 321 now 197 of my specs fail with errors most of these error have the wrong number of arguments 0 for 1 error described belowexample 1class documentlibrary activerecordbase extend friendlyid friendly id title use slugged has many shelves dependent destroy has many documents through shelves validates title presence true uniqueness true default scope order titleendspec it can be shown on the company menu do dl factorygirlcreatedocument library title test menu false company true dlshould be valid endfails with 1 documentlibrary can be shown on the company menu failureerror dl factorygirlcreatedocument library title test menu false company true argumenterror wrong number of arguments 0 for 1 specmodelsdocument library specrb6in block 2 levels in top requiredif i place a call to the debugger before the the factorygirlcreate line i getusersjasonrvmgemsruby193p125gemsactivesupport321libactive supportdependenciesrb252rdb1 cusersjasonrvmgemsruby193p125gemsactivesupport321libactive supportcore extmoduleremove methodrb4 nilclass from usersjasonrvmgemsruby193p125gemsrspeccore280librspeccoreexample grouprb249in set it up from usersjasonrvmgemsruby193p125gemsrspeccore280librspeccoreexample grouprb200in subclass from usersjasonrvmgemsruby193p125gemsrspeccore280librspeccoreexample grouprb187in describe from usersjasonrvmgemsruby193p125gemsrspeccore280librspeccoredslrb18in describe from usersjasoncoderailsteamsitespecmodelsdocument library specrb4in top required from usersjasonrvmgemsruby193p125gemsrspeccore280librspeccoreconfigurationrb698in load from usersjasonrvmgemsruby193p125gemsrspeccore280librspeccoreconfigurationrb698in block in load spec files from usersjasonrvmgemsruby193p125gemsrspeccore280librspeccoreconfigurationrb698in map from usersjasonrvmgemsruby193p125gemsrspeccore280librspeccoreconfigurationrb698in load spec files from usersjasonrvmgemsruby193p125gemsrspeccore280librspeccorecommand linerb22in run from usersjasonrvmgemsruby193p125gemsrspeccore280librspeccorerunnerrb80in run in process from usersjasonrvmgemsruby193p125gemsrspeccore280librspeccorerunnerrb69in run from usersjasonrvmgemsruby193p125gemsrspeccore280librspeccorerunnerrb10in block in autorunusersjasonrvmgemsruby193p125gemsactivesupport321libactive supportcore extmoduleremove methodrb4example 2class album activerecordbase belongs to photo library validates title presence true validates title uniqueness scope photo library idendclass photolibrary activerecordbase default scope order title has many albums dependent destroy validates title presence true validates title uniqueness trueendspec before each do photo library factorygirlcreatephoto library title products login admin end it destroys an album do 3times factorygirlcreatealbum photo library photo library visit photo library pathphoto library findh3click link delete findnoticeshould have contentalbum deleted successfully albumcountshould eq 2 endfails with1 albums destroys an album failureerror login admin argumenterror wrong number of arguments 0 for 1 appcontrollerssessions controllerrb8in create eval2in click button specrequestsalbums specrb7in block 2 levels in top requiredline 8 in my sessions controller isuser userfind by emailparamsemailinspecting the params at this point shows everything including email is present as it should becontrasting example 3this spec with factorygirl passes fine it is unique within a library do pl factorygirlcreatephoto library title products pl2 factorygirlcreatephoto library title competitors a factorygirlcreatealbum title gold series photo library pl na albumcreatephoto library id plid title gold series nashould not be valid natitle cyclone nashould be valid na albumcreatephoto library id pl2id title gold series nashould be valid endthe factories are defined as follows factory document library do sequencetitle n library titlen end factory photo library do sequencetitle n photo library titlen end factory album do sequencetitle n albumn endif i comment out the friendlyid lines from the documentlibrary model example 1 passes i have no idea why that makes a differencehowever some specs still do not pass consider the following model which does not use friendlyid and spec that flunks in 321class drawinglibrary activerecordbase validates title presence true default scope order title has many drawings dependent destroyend it thisplays in alpha order do factorygirlcreatedrawing library title c factorygirlcreatedrawing library title b factorygirlcreatedrawing library title a ts drawinglibraryalleach do draw lib ts draw libtitle end tsshould eq abcend1 drawinglibrary thisplays in alpha order failureerror drawinglibraryalleach do draw lib argumenterror wrong number of arguments 0 for 1 specmodelsdrawing library specrb19in block 2 levels in top requiredresults of rspec specmodelsdocument library specrb backtrace 1 documentlibrary can be shown on the company menu failureerror dl factorygirlcreatedocument library title test menu false company true argumenterror wrong number of arguments 0 for 1 specmodelsdocument library specrb6in block 2 levels in top requiredi am using rvm with ruby 193 with rubygems at 1816 factory girl is at 260 with factory girl rails at 170 rspecrails is at 281heres what i know so fardowngrading back to rails 320 makes everything work againupgrading to edge rails does not fix the problemrunning edge versions of the rspec gems does not fix the problemthe app runs properly and as expected in development mode only tests seem to be affecteddowngrading to ruby 192 does not fix the problemupgrading to ruby 193p125 does not fix the problemchanging from mysql to sqlite for the test environment does not fix the problemdowngrading factory girl rails to 160 or even 150 does not fix the problemusing factorycreate instead of factory does not fix the problemusing factorygirldefine and factorygirlcreate does not fix the problemcommenting out the friendlyid stuff makes some of the specs pass see belowrunning dbtestprepare or dbreset dbmigrate does not fix the problemchanging all factorygirl definitionscreations to be consistent does not fix the problemreinstalling gems under a new rvm gemset or even reinstalling rvm entirely does not fix the problemrewriting these tests in testunit and factorygirl produces no errors so factorygirl might not be the problemcan anyone point me in a direction on this or offer troubleshooting adviceheres my gemfilesource gem rails 321gem mysql2gem dynamic formgem friendly idgroup assets do gem sassrails 323 gem coffeerails 321 gem uglifier 103endgem jqueryrailsgem therubyracergem bcryptrubygem capistranogem paperclip git gitgithubcomthoughtbotpaperclipgitgroup test development do gem rspecrails gem launchy gem rubydebug19 gem database cleaner gem capybarawebkit gem spork 090rc gem guardsporkendgroup development do gem fuubar gem powderendgroup test do gem turn require false gem capybara gem factory girl rails gem guardrspecendthe only differences in gemfilelock after upgrading to rails 321 are with the rails core libraries no testing gems changed,['ruby-on-rails'] +249448,logging http request start and finish from embedded android webview i am looking for a way to log the requests and startend times made by an embedded webview i am not able to find a way to do it so far other than rooting the phone and running tcpdump that works for me but i need to run this in the field so that is not really viable there are lots of ways to log the url and start time but i cannot see the finish or bonus the full response metadatashouldloadresource could work if i could wrap the current request but i would have to fetch it myself with http support in order to return it en masse because there is not enough api exposed to fully forward to the inner request i do not want to do that for a number of reasons including that webview on devices does not use the same network stack as the http classes and because it will change the timing of subresourcesi have been trying to find ways to turn on chromium net debug flags to do this but i cannot figure out how do do that in the context of the webview or system propertiesi would really rather not ship my own webcore to do this but if needs must,['android'] +249474,determine whether browser supports printing i think the answer to this is almost certainly no because i have done a little testing and searching around but is there any trick to detect whether windowprint even might work from inside a page ie from javascript i know that even on a desktoplaptop it is never going to be possible to know whether there is a printer configured on the system for example but at least the browser will put up a print dialogmy android phone has a windowprint function but it unsurprisingly does not do anythingagain i am asking mostly so there is a good question on the topic at so,['javascript'] +249498,safe twitter oauth authentication in javascript jquery plus server side helper what is the best way to do twitter oauth authentication safely in javascripti am trying to write a program to let the user analyze his twitter usage and followers friends i have written a server side version which works using the python tweepy module i would like to share it with people but i would like it to run in the browser to be scalable vs running on my small serveri see another question where the upshot is that it is not recommended and not safejavascript oauth sign in with twitterwhich makes sense if one were sending the consumer app secret or access user secret in the apps javascriptbut why could not i build the url on the server side like here then send the authentication url back to the browser something like this from the oauth tool on twitters my applications page not valid credentialsgethttps3a2f2fapitwittercom2f12fget252faccount252fverify credentials json3d26oauth consumer keygd0bgcgmu4mdwnfkqplfqs326oauth nonce3d24ad5049501dee1292afd8cf22307d6826oauth signature method3dhmacsha126oauth timestamp3d132917362626oauth tokenupupxsbc3d283768289ltq6r1ez1ked8dossm5xpqjaki28ysyh26oauth version3d10then have jquery use that to authenticate with the users credentials and run the analysisit is a significant piece of work i would hate to do that and then find out it does not work or is an unsafe approach or it is already been doneis that safe it does not seem to expose any secretswill that workany pointersexamples on the right way to do the authentication for a jquery noob with the necessary authorization header and cookieredirect processing i feel like i am missing something and either there is a reason this would not work or it should already exist somewhere but have not found it many thanks,"['javascript', 'jquery']" +249510,how to combine left join and where clause with jpql i have two jpa entities schedule containing a list of reservationsreservation containing a date field date resdatemy goal is to only retrieve reservations matching a date parameter planningdate while retrieving all schedules no matter if the reservation exists or not at this given dateso i wrote select s from schedule as s left join sreservations as r where rresdate planningdate order by sstarthourwhy are not schedules without reservations on this date retrieved despite my left join probably like native queries left join looks like inner join when combining with a where clause so how could the query be changed to fulfill my requirement i have not found a specific feature in jpql,['java'] +249531,how to bubble custom jquery event to windowdocument i have written an absolutely positioned dropdown menu i am triggering a custom event when this menu openspsdropdownprototype onopencomplete function thistriggermenu open thisthis works great when i know which instance of psdropdown to targetvar dd new psdropdownddonmenu open fnhowever i would like for my custom event to bubble up to windowdocument if the event is not stopped from propagating for examplevar dd new psdropdownddonmenu open functionevent instance this would stop bubbling to windowdocument eventstoppropagationwindowdocumentonmenu open functionevent instance bubbledis there any way to accomplish this with jqueryedit to add a example by analogya click on a button element will trigger an event this event will continue to bubble up the parentelement chain until it reaches windowdocument unless propagation is stopped by an event listener i am interested in synthesizing this behavior for custom events such that if eventstoppropagation is not called it will bubble to windowdocument or event or some other window global it does not matter,"['javascript', 'jquery']" +249555,what is this javascript syntax ci cc i am doing some ff addon development and i am seeing syntax like thisvar cc ci requirechromejust curious what that syntax is and if it is special to ff development or something else,['javascript'] +249569,segmentation fault core dumped i am relatively new on c i am trying to run a simple program and i get this error message segmentation fault core dumped i just want to print any value of the array bits but i can not i would appreciate any help on this errorinclude stdiohinclude stdlibhinclude mathhinclude mallochint main const long int and 10 const int smalln 1250 char bitssmalln forint i0 ismalln i bitsi0xff printfcharacter c n bits5,['c'] +249583,edittext in listview android i have listview with editext and textviewwhen i touch on edittext then edittext lost focusi resolved this problem by setting androidwindowsoftinputmodeadjustpanandroidmanifestxmlnow i touch on edittext than editext get focus but application label and some raw of listview thisappeartop parti want to get focus when user touch on edittext without loss application label and some raw of listviewcode that i have implemented below coding get focus when user touch on edittext but application label and some raw of listview thisappear when soft keypad pop upi want to get focus when user touch on edittext without loss application label and some raw of listview1androidmanifestxmlapplication androidicondrawableicon androidlabelstringapp name activity androidnamemylistviewdemoactivity androidlabelstringapp name androidwindowsoftinputmodeadjustpan intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activityapplication2 raw layoutxmllinearlayout xmlnsandroid androidorientationvertical androidlayout widthfill parent androidlayout heightfill parent edittext androidididmedittext androidlayout widthfill parent androidlayout heightwrap content linearlayout3 mainxmllinearlayout xmlnsandroid androidorientationvertical androidlayout widthfill parent androidlayout heightfill parent listview androidididmlistviewandroidlayout widthfill parentandroidlayout heightwrap contentlinearlayout4 mylistviewdemoactivitypublic class mylistviewdemoactivity extends activity private listview mlistview called when the activity is first created override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain mlistviewlistviewfindviewbyidridmlistview mlistviewsetadapternew myadapterthis class myadapter extends baseadapter private activity mcontext private string characterabcdefghij public myadapteractivity context mcontextcontext override public int getcount todo autogenerated method stub return characterlength override public object getitemint position todo autogenerated method stub return null override public long getitemidint position todo autogenerated method stub return 0 private class holder edittext medittext override public view getviewint position view convertview viewgroup parent todo autogenerated method stub final holder holder if convertview null holder new holder layoutinflater inflater mcontextgetlayoutinflater convertview inflaterinflaterlayoutraw layout null holdermedittext edittext convertview findviewbyidridmedittext convertviewsettagholder else holder holder convertviewgettag holdermedittextsettextcharacterposition holdermedittextsetonfocuschangelistenernew onfocuschangelistener override public void onfocuschangeview v boolean hasfocus todo autogenerated method stub if hasfocus final edittext etxt edittext v holdermedittextsettextetxtgettexttostring return convertview,['android'] +249627,python fabric logging i came across fabric modules its really cool it works well for me now i have an issue how to collect output from fabric script cat fabfilepyfrom fabricapi import from fabriccontribconsole import confirmenvhosts localhost 17216101121721610106envusertestuserenvpassword testuserparalleldef uptime rununame ai would like to use logging modules with fabric and use them inside the code itself do not want to use normal redirection like fab uptime logout,['python'] +249668,redefining or changing macro value i am currently working on an already developed project written in mfc c and am facing a problem with an already present macro having the definitiondefine height tests 13i am trying to change the value from within the code but i think since its a preprocessed definition i am unable to do that is there a way i could get around this problem without having to change the original macro overall as it might affect the original functionality of the program i am just intending to change it in one particular condition rest everywhere else it remains the samejust to let everyone know i have obviously tried out using a different macro definition with the value 17 i am intending to use but no luck as suchany help would be much appreciated,['c++'] +249682,creating groups of consecutive days meeting a given criteria i have table the following data structure in sql serverid date allocation 1 20120101 0 2 20120102 2 3 20120103 0 4 20120104 0 5 20120105 0 6 20120106 5etcwhat i need to do is get all consecutive day periods where allocation 0 and in the following formstart date end date daycount20120101 20120101 120120103 20120105 3etcis it possible to do this in sql and if so how,['sql'] +249687,how to set integer tag to a widget in xml layout file i have simple layout but i can only set string tag how to set integer tag imageview androidlayout widthwrap content androidlayout heightwrap content androidtag1 androidsrcdrawableimage updatei found out how to set integer tags in xml layout we need to specify an integer variable in any xml resource file that should look like thatresvaluesvaluexmlxml version10 encodingutf8resourcesinteger nameint115integerinteger nameint21integerresourcesand now we are free to use integerint1 or integerint2 as tags for our xml widgets for exampleimageviewandroidlayout widthwrap contentandroidlayout heightwrap contentandroidtagintegerint2androidsrcdrawableimage however in my case i preferred to set tag programmatically,['android'] +249704,define action bar overflow items if i define the following items for my action barresmenuaction menuxml xml version10 encodingutf8menu xmlnsandroid item androidtitlelabel item androidtitlelabel1 item androidtitlelabel2 item androidtitlelabel3 item androidtitlelabel4menuin my activityoverridepublic boolean oncreateoptionsmenumenu menu menuinflater inflater getmenuinflater inflaterinflatermenuaction menu menu return trueis there anyway to allow me define certain items move to action overflow part and how to do itps action overflow part is the rightmost part of action bar which hide certain items like a popup menu,['android'] +249710,tfs2010 retrieve all changesets associated with a branch full recursion this follows my previous question about tfs 2010 and the possibility to create a changelogi was previously using labels to identify a version of the program but as labels are not fixed points in time now i am using branchesheres how the branch hierarchy looks likeas you can see there are two different applications that are branches of the trunk app a application a and app b application b both are almost identical but there are some functional differenceshere is the process to create a new version of the application say version 13the main trunk is modified new functionalities are added bug fixesfrom the modified main trunk a new branch is created main trunk 13app a branch might be modified so unique functionalities of app a will work with modification of v13app b branch might be modified so unique functionalities of app b will work with modification of v13main trunk 13 is merged to app a and app b so both app a and app b applications receive the modifications of the main trunkfrom the modified app a branch a new branch is created app a 13from the modified app b branch a new branch is created app b 13my goal is to be able to produce a changelog between app a 13 and app a 12by changelog i mean a list of workitems each changeset that is checkedin is associated with one or more workitem for instance a bug item i would like to be able to get the list of all workitems that were linked to a changeset that has impacted app a 13 those changesets might come from the main trunk step 1 above the app a branch step 3 above or even the app a 13 branch itself if hotfixes are checkedin after the branch has been createdto get this list of workitems i tried to get the list of all changesets that are linked to app a 12 linked the code that was checkedin in the changeset is now on the branch app a 12 and the list of all changesets that are linked to app a 13then i will be able to know which changesets are linked to app a 13 and not linked to app a 12 from this subset of changesets i will get all associated workitems and thus my changelogheres my problem how could i get the list of all changesets that are linked with a specified branch i am using the tfs 2010 api for c codethe input of my program that would retrieve all changesets for a specified branch would be the name of the branch say app a 12 and the output would be the list of following changesetschangesets applied on app a 12 branch itselfchangesets applied on app a branch before app a 12 was createdchangesets applied on main trunk 12 branch before it has been merged to app achangesets applied on main trunk branch before main trunk 12 was createdi have wrote the following pieces of code to get all those changesets gets the list of all changesets id from app a 12 branchvar branch1changesets myversioncontrolserverqueryhistory pathapp a 12 versionspeclatest 0 recursiontypefull null null null intmaxvalue false falseoftypechangesetselectz zchangesetidtolisteven if recursiontypefull is specified the above code only returns changesets that were checkedin on the app a 12 branch itself this is identical to the history command on source code explorer view in visual studiothen i tried the following piece of code gets the list of all changesets id from app a 12 branchvar branch1mergedchangesets myversioncontrolserverquerymerges null null pathapp a 12 versionspeclatest null null recursiontypefullselectz zsourceversiontolistthis returns changesets that were checkedin on app a 12 branch those that were chekedin on app a branch before app a 12 was created much better but not sufficient i cannot find a way to make the recursion work with branches that are above app a main trunk in my caseanyone has an ideaalso any better ideas to get the changelog between two branches are welcomethx,['c#'] +249713,java how to mock calendargetinstance in my code i have something like thisprivate void dosomething calendar today calendargetinstance how can i mock it in my junit test to return a specific date,['java'] +249718,how to search a string in another string possible duplicatehow to see if a substring exists inside another string in java 14 how would i search for a string in another stringthis is an example of what i am talking aboutstring word catstring text the cat is on the tableboolean foundfound findinstringword text this method is what i want to knowif the string word is in the string text the method findinstringstring string returns true else it returns false,['java'] +249728,how do i get a list of webcam devices using opencv i am using opencv22 with videoinput i want to upgrade to opencv231 where videoinput has apparently been merged into opencv23my problem is that there does not appear to be a listdevices function to return all the video sources availabledoes anybody know the new equivalent,['c++'] +249746,multilevel relative import multilevel relative importi have following folder structuretop init py util init py utiltestpy foo init py foopy bar init py foobarpyi want to access from foobarpy the module utiltestpy i tried following relative import but this does not workfrom utilutiltest import i always get valueerror attempted relative import beyond toplevel packagehow to do such a multileve relative import,['python'] +249759,core plot xaxis should remain visible while scrolling horizontally or vice versa i am using core plot to make a line graph with a long xaxisrange i made the vertical direction of the graph fixedconstant and let it only scroll horizontally however if i start scrollingswiping horizontally the yaxis will not move along like the xlabel the yaxis is only visible at starting point of the graph i would appreciate if somebody can help me thank you very much in advance,['iphone'] +249762,windows shutdown hook on java application run from a bat script i have a bat script which runs a java application if i press ctrlc on it it the application terminates gracefully invoking all the shutdown hooks however if i just close the cmd window of the bat script the shutdown hooks are never invoked is there a way to solve this perhaps there is a way to tell the bat script how to terminate the invoked applications when its window is closed,['java'] +249767,can i extend the console object for rerouting the logging in javascript is it possible to extend the console objecti tried something likeconsoleprototypelog functionmsg consoleprototypelogcallmsg alertmsgbut this did not worki want to add additional logging to the console object via a framework like log4javascript and still use the standard console object in cases where log4javascript is not available in my codethanks in advance,['javascript'] +249802,datepickerdialog with theme holo light how is it possible to get a datepickerdialog with holo light themewhen creating a datepickerdialog as follows datepickerdialog dpd new datepickerdialognew contextthemewrapperthis androidrstyletheme holo light dialog noactionbar new datelistenerv mtimeyear mtimemonth mtimemonthdayor with theme androidrstyletheme holo light or androidrstyletheme holo light dialog i get a date picker with a standard title and standard buttons i tried to use a custom theme with a holo light parent too but it did not work either it seems to work with theme androidrstyletheme holo but the result is a dark background as expected but i would like to have a light onethe applications androidjar is of version 14 the application is running on a divice with android version 32i have seen an example here which shows a datepickerdialog with the holo light theme the way i would like to have it i do not know why it does not work with my setup thank you for help,['android'] +249835,how to call builtinproductpackagingutility in command line when you specify an entitlement and a code signing identity in build settings xcode 421 you have the following output when you build from xcodeprocessproductpackaging myappnameentitlements pathtomyappnamexcentcd pathtomyappnamesourcecodebuiltinproductpackagingutility pathtomyappnamesourcecodemyappnameentitlements entitlements format xml o pathtomyappnamexcentcodesign pathtogarfields comic boom 10appcd pathtomyappnamesourcecodesetenv codesign allocate developerusrbincodesign allocateusrbincodesign force sign mycertificate entitlements pathtomyappnamexcent pathtomyappnameappi would like to sign my app folder at the end of the build and not during the xcode buildmy problem is i do not know how to generate the xcent file in the command line question how do you generate xcent files in command line i did a find from the root there is nothing called productpackagingutility,['ios'] +249857,stop mysql tolerating multiple nulls in a unique constraint my sql schema iscreate table foo bar int null name varchar 59 not null unique name bar engine innodbmysql is allowing the following statement to be repeated resulting in duplicatesinsert into foo bar name values null abcdespite havingunique name bar why is this tolerated and how do i stop it,"['mysql', 'sql']" +249860,serialize multiple forms together can you serialize multiple forms into one so that only one post or ajax request is made i have searched around and it is all for submiting each form separently via postajax,['jquery'] +249868,android keep listviews item highlighted once one has been clicked so i have an activity with 2 listview widgets when you select a value in the first one the second is populated with values related to the selection in the first listview this mechanic works without a problem but now i want the user choices to stay highlighted i have read a good ammount of question related to this topic and it seems there is a myriad of ways one can accomplish this but after trying about 45 of em i still cannot get it to worki have got it working on the second listview using the androidlistselectorc xml attribute but this seems to be wiped clean once a onitemclicklistener is introduced into the mix like the one i use on my first listviewso far heres what i have gotcustom onitemclicklistener i found browsing various answer regarding this topic slightly modified it in order for it to load my info the second listview private class itemhighlighterlistener implements onitemclicklistener private view oldselection null public void clearselection ifoldselection null oldselectionsetbackgroundcolorandroidrcolortransparent public void onitemclickadapterview parent view view int pos long id clearselection oldselection view viewsetbackgrounddrawableviewgetcontextgetresourcesgetdrawablerdrawablelist selector loadclubsmxmlportaloptionsgetregionposgetid mclublistsetadapternew arrayadapterstringgetapplicationcontext rlayoutlist item white mclubs heres my list selectorxml file xml version10 encodingutf8selector xmlnsandroid item androidstate selectedtrueshape solid androidcolorc shapeitem item androidstate selectedfalseshape solid androidcolorf shapeitemselectorthe method onitemclick is called and executed but the background of my listitem stays the same color i cannot believe that this simple task has proven so complicatedif i have omitted code that could be useful or if my question is lacking details feel free to point that out and i will do my best to explain myself,['android'] +249875,cgcontextstrokepath not working when zooming and drawing images i am drawing lines according to touchesmoved method and normally it works fine but when i zoom into the image and draw the previously drawn lines are both thisplaced and keep getting more and more blurry ultimately vanishing i have tried using uipinchgesturerecognizer and simply increasing the frame of myimageview for multitouch events only but the problem occurs both ways heres the code for drawing voidtouchesmovednsset touches witheventuievent event nsarray alltouches touches allobjects int count alltouches count ifcount1single touch case for drawing line uitouch touch touches anyobject cgpoint currentpoint touch locationinviewmyimageview uigraphicsbeginimagecontextmyimageviewframesize drawimageimage drawinrectcgrectmake0 0 myimageviewframesizewidth myimageviewframesizeheight cgcontextsetlinecapuigraphicsgetcurrentcontext kcglinecapround cgcontextsetlinewidthuigraphicsgetcurrentcontext 20 cgcontextbeginpathuigraphicsgetcurrentcontext cgcontextmovetopointuigraphicsgetcurrentcontext lastpointx lastpointy cgcontextaddlinetopointuigraphicsgetcurrentcontext currentpointx currentpointy cgcontextstrokepathuigraphicsgetcurrentcontext drawimageimage uigraphicsgetimagefromcurrentimagecontext uigraphicsendimagecontext lastpoint currentpoint elsemulti touch case handle pinchzoom here is the image drawn over without zoomingand this is the image depicting the problem after zoomingin with the red arrow showing the segment that was already drawn before zoomingin as shown in previous image the image is both blurred and thisplacedit can also be noticed that a part of the line drawn towards the end is unaffected and the phenomenon occurs for lines drawn back in time i believe the reason for this is that the image size attributes are being lost when i zoom inout which probably causes the blur and shift but i am not sure about thatedit i have uploaded a short video to show whats happening it is sort of entertainingedit 2 heres a sample singleview app focussing on the problem,"['iphone', 'ios']" +249908,jquery ui autocomplete 18 scroll i am having troubles configuring the autocomplete module of jqueryui i need that when the amount of data to select is big enough an scroll bar appearsthis is what i triedin the jqueryui1816css i have setted thisuiautocomplete maxheight 100px overflowy auto overflowx hidden as shown in the uidocumentation examplethis is how i declare and autocomplete inputmyinputautocomplete source mysource minlength 0 i dont know why the scroll bar does not appear any help would be appreciated thank you very much,['jquery'] +249931,switch statement with string as argument in android i would like to use a switch statement as in java 17 which also allows switchsomestring however if i change the java compiler to 17 the project breaks and i either have to go back to 15 or use android tools fix projectis there any way to use switch with strings in android development,"['java', 'android']" +249932,eclipse android project how to reference library within workspace i followed some steps i found here cannot find the url right now sorry to convert my android project in eclipse to a layout where 9 of my code is in a library project and then i have 2 other shell projects under the same workspace that are mostly just the androidmanifestxml files and a few resource files this was done so i can support 2 builds of the same project with just some minor texticon changes between the 2 the application name is also different so i can publish both on the android market at the same timeever since i did this about every 10 times i compile maybe once every day or two i get dalvik error 1 and something about access already exists access being the name of the first java unit in my library projectto work around the issue i go in to the java build path for my stubproject that i am trying to build and remove the jar file from my main library from the libraries tab then i can build without the errorthen a while later maybe 1 or 2 days i will get an error about missing classes when i compile my stubproject not my library so i will go back to the java build path and put the reference to the jar file back in and all is good again for 1 or 2 days then i am back to the same error as beforeis this just a known issue and something i need to do or can i resolve by a restructure of my projectsworkspaces currently i havelib project only has 2 libs on build path android 21 and comandroidideeclipseadtlibrariesfirst stub project that uses above lib has the same 2 libs as above project plus sometimes i use add jar to include the jar from the above projects bin folder2nd stub project same libs as first stub projectshould i reference the jar from my lib project using one of the other tabs under build path options maybe the project tab instead or the source tab i do not currently have it under any of those other areaswhen i get in to the weird state doing a clean project also does not help i have tried that several times and openclose the ide between cleaning to no resolveat this point we are in the final testing stages so my normal daily task ismake a minor update bug fix in the lib projectuse the publish wizard to export both projects and update android market and other places we keep the apk filesso i would like those steps to stay simple without having to openclose multiple workspaces or go through a lot of build steps if possible,['android'] +249933,bad performance with guava cache on android we use a loading google guava loadingcache for bitmaps in an android application in the application i am running a drawing thread that paints the bitmaps in the cache to a canvas if a specific bitmap is not in the cache it does not get drawn so that no loading will ever block the drawing threadhowever the painting results in visual stuttering and the frames per second rate is not how we would like it i nailed it down to the getifpresent method of the cache that alone takes over 20 of the applications total cpu time in getifpresent localcachesegmentget takes over 80 of the timebear in mind this is only a lookup of an already present bitmap there will never happen a load in get i figured there would be a bookkeeping overhead in get for the lru queue that decides which eviction takes place if the segment is full but this is at least an order of magnitude slower of what a keylookup in lrulinkedhashmapget would give mewe use a cache to get fast lookups if an element is in the cache if the lookup is slow there is no point in caching it i also tried getallpresenta and asmap but it gives equal performancelibrary version is guava1101jarloadingcache is defined as followsloadingcachetilekey bitmap tiles cachebuildernewbuildermaximumsize100buildnew cacheloadertilekeybitmap override public bitmap loadtilekey tilekey systemoutprintlnloading in threadcurrentthreadgetname tilekeyx tilekeyy final file tilefiles surfacestatemapfilegetbuilding getfloorsgettilekeyfloorid getbackgroundtilekeyzoomidgettilefiles string tilepath tilefilestilekeyytilekeyxgetabsolutepath options options new bitmapfactoryoptions optionsinpreferredconfig bitmapconfigrgb 565 return bitmapfactorydecodefiletilepath options my questions aredo i use it wrongis it is implementation unsutible for androiddid i miss a configuration optionis this a known issue with the cache that is being worked onupdateafter about 100 frames painted the cachestats areisystemout 6989 cachestatshitcount11992 misscount97loadsuccesscount77 loadexceptioncount0 totalloadtime1402984624 evictioncount0after that misscount stays basicly the same as hitcount increments in this case the cache is big enough for loads to happen sparsely but getifpresent is slow nontheless,"['java', 'android']" +249940,access method after uiimageview animation finish i have an array of images loaded into a uiimageview that i am animating through one cycle after the images have been thisplayed i would like a selector to be called in order to thismiss the current view controller the images are animated fine with this codensarray imagearray nsarray alloc initwithobjects uiimage imagenamedhowto1png uiimage imagenamedhowto2png niluiimageview instructions uiimageview alloc initwithframeuiscreen mainscreen boundsinstructionsanimationimages imagearrayimagearray releaseinstructionsanimationduration 160instructionsanimationrepeatcount 1instructionscontentmode uiviewcontentmodebottomleftinstructions startanimatingselfview addsubviewinstructionsinstructions releaseafter the 16 seconds i would like a method to be called i looked into the uiview class method setanimationdidstopselector but i cannot get it to work with my current animation implementation any suggestionsthanks,"['iphone', 'objective-c']" +249973,why does 1 in 10 true evaluate to false when i was looking at answers to this question i found i did not understand my own answeri do not really understand how this is being parsed why does the second example return false 1 in 10 this is expectedtrue 1 in 10 true this is strangefalse 1 in 10 true this is what i wanted it to betrue 1 in 10 true but it is not just a precedence issue it did not raise an exception on the second exampletraceback most recent call last file pyshell4 line 1 in module 1 in 10 truetypeerror argument of type bool is not iterablethanks for any help i think i must be missing something really obviousi think this is subtly different to the linked duplicatewhy does the expression 0 0 0 return false in pythonboth questions are to do with human comprehension of the expression there seemed to be two ways to my mind of evaluating the expression of course neither were correct but in my example the last interpretation is impossiblelooking at 0 0 0 you could imagine each half being evaluated and making sense as an expression 0 0 0true 0 0 0trueso the link answers why this evaluates false 0 0 0falsebut with my example 1 in 10 true does not make sense as an expression so instead of there being two admittedly wrong possible interpretations only one seems possible 1 in 10 true,['python'] +249975,how to use sha1 hashing in c programming i am trying to write a c program that proves sha1 is nearly collision free but i cannot figure out how to actually create the hash for my input values i just need to create the hash and store the hex value into an array after some google searches i have found openssl documentation directing me to use this include opensslshah unsigned char sha1const unsigned char d unsigned long n unsigned char md int sha1 initsha ctx c int sha1 updatesha ctx c const void data unsigned long len int sha1 finalunsigned char md sha ctx ci believe i should be using either unsigned char sha1 or sha1 init but i am not sure what the arguments would be given x is my input to be hashed would someone please clear this up for me thanks,['c'] +249976,jsr 303 validation if one field equals something then these other fields should not be null i am looking to do a little custom validation with jsr303 javaxvalidationi have a field and if a certain value is entered into this field i want to require that a few other fields are not nulli am trying to figure this out not sure exactly what i would call this to help find an explanation any help would be appreciated i am pretty new to thisat the moment i am thinking a custom constraint but i am not sure how to test the value of the dependent field from within the annotation basically i am not sure how to access the panel object from the annotationpublic class statusvalidator implements constraintvalidatornotnull string override public void initializenotnull constraintannotation override public boolean isvalidstring value constraintvalidatorcontext context if canceledequalspanelstatusgetvalue if value null return true else return false it is the panelstatusgetvalue giving me trouble not sure how to accomplish this,['java'] +249988,local notifications that expire while device is turned off are lost if my app queues a local notification but then the device is turned off while the notification is due to fire then upon restarting the device there is no indication there ever was a notification that firedsame thing seems to happen with calendar alarmsthis does not seem like the correct behavior to me from a users perspective if the notification were a calendar reminder for something very very important and i happened to reboot at the very instant it fired then i have lost that important reminder even if my device were only turne3d off for 3 seconds if the notification was due to fire in the 3 seconds its lost foreveram i missing something,['ios'] +249997,rhino mocks telling me arg inside assertwascalled needs more arguments heres the call inside a test youtubeserviceassertwascalledd dgetfeedbyauthorwithrequestmark argyoutuberequestisanythingheres the function on the interface for youtubeservicefeedvideo getfeedbyauthorwithrequeststring author youtuberequest requestheres the error rhino mocks gives me when i run the testsysteminvalidoperationexception when using arg all arguments must be defined using argis argtext arglist argref or argout 2 arguments expected 1 have been definedi use argisanything all the time with other types usually strings so i am not sure what else it needs,['c#'] +250002,how to change the jquery mobile flip switch state from code i have some jquery mobile flip toggle switches on my androidipad application and i need tochange their states onoff dynamically using javascripti was looking for a solution here change value of flip toggle dynamically with jquery mobile and i tried several ways valon sliderenable but it seems the control is not working at allis there a solution for this issue how can i do to change the flip switch state from code,"['javascript', 'jquery', 'android']" +250007,on android how do i make oddly shaped clipping areas here is how to create a clipping area the shape of a circlepath path new pathpathaddcircle200200100directioncwcclippathpath c is a canvasnow there is a clipping area on the canvas which prevents drawing anything outside the bounds of that circle but what if i want to have the clipping area be shaped like a donut or whateveri tried playing around with creating a second path and using toggleinversefilltype on it and then adding that to the original path but that does not seem to workalternatively instead of using a path is it possible to just create a bitmap to use as a mask and set it as a clipping mask on the canvas somehowedit the answer is exactly what i needed with one small addition when doing multiple operations on a canvas always use opreplace on the first clippath call that will replace any existing clippath on that canvasfor reference here is what i thiscovered what the 6 different regionop values mean imagine a venn diagram with 2 circles b is the part where the 2 circles overlap a is the nonoverlapping left circle c is the nonoverlapping right circlecclippatharegionopreplacecclippathbregionopdifference a regionopintersect b regionopreplace bc regionopreverse difference c regionopunion abcregionopxor acthe indicates the part that is not drawn sorry if that is not particularly clear it is hard to describe well without graphics,['android'] +250021,nodejs expressjs how to overrideintercept resrender function i am building a nodejs app with connectexpressjs and i want to intercept the resrenderview option function to run some code before forwarding it on to the original render functionappgetsomeurl functionreq res resrender functionview options callback view testviews view resprototyperenderview options callback resrenderindex title hello world it looks like a contrived example but it does fit in an overall framework i am buildingmy knowledge of oop and prototypal inheritance on javascript is a bit weak how would i do something like thisupdate after some experimentation i came up with the followingappgetsomeurl functionreq res var response responseprototype res responserender functionview opts fn parent sub view testviews view thisprototyperenderview opts fn parent sub responserenderindex title hello world it seems to work not sure if it is the best solution as i am creating a new response wrapper object for each request would that be a problem,['javascript'] +250071,conflict between copy constructor and forwarding constructor this problem is based on code that works for me on gcc46 but not for another user with clang30 both in c0x modetemplate typename tstruct mybaseprotected t m template typename args mybase args x m stdforwardargsx an object of mybase can take any list of constructor arguments as long as t supports that construction signature the problem has to do with the specialmember functionsiiuc the constructor template cancels the automaticallydefined default constructor however since the template can accept zero arguments it will act as an explicitlydefined default constructor as long as t is defaultconstructibleiiuc determination of a class copyconstruction policy ignores constructor templates that means in this case that mybase will gain an automaticallydefined copy constructor as long as t is copyable thatll channel t copyconstructionapply the previous step for moveconstruction tooso if i pass a mybaset const as the sole constructor argument which constructor gets called the forwarding one or the implicit copying onetypedef stdvectorint int vectortypedef mybaseint vector vb typeint vector a 1 3 5 vb type b a vb type c b which constructor gets calledmy users problem was using this in as a base class the compiler complained that his class could not synthesize an automaticallydefined copy constructor because it could not find a match with the base class constructor template should not it be calling mybase automatic copyconstructor for its own automatic copyconstructor is clang in error for coming up with a conflict,['c++'] +250078,multiple files communication with coffeescript when i create a new coffeescript file i cannot access the code in the compiled code from another file because it gets wrapped in some function scope for examplecoffeescriptclass chatservice constructor io generated javascriptfunction var chatservice chatservice function function chatserviceio thisio io return chatservice callthiswhen trying to call chatservice in another file it is not defined how do i handle multiple files with coffeescript,['javascript'] +250108,adding vertical scroll to a jpopupmenu i would like to add a way to scroll through menu items in a jpopupmenu much like scrolling through a list of items in a jcomboboxlet us say i have 10 menu items i would like to thisplay only 5 menu items at a time and i would use a vertical scroll button at the bottom or top of the jpopupmenu to show the menu items that are not listed and hide the ones that i just sawis it possible i am using jide softwares jidesplitbutton which thisplays a jpopupmenu when clicked i am trying to keep the look and feel of the command bar on which i placed the jidesplitbutton so i do not want to replace it with a jcombobox unless i really have to,['java'] +250138,how to log generated sql queries out of simpledata orm for net how to log generated sql queries without mysql profileri am using simpledatamysql,['.net'] +250141,paging does not work and maybe i found the cause i am trying to implement the stream news feed paging function to my app but it does not work as expected i found many similar question here but there are no solution to solve this problemi tried both graph api and fql and the behavior was similar it success to get the result one or two times but after that it fails to get the result gets the empty json arrayfinally i found this problem depends on access token if i just change the source code to use android sdk stream example app id rather than my own app id for authentication it works perfectlyso i believe facebook server checks the app id and returns some weird or restricted access token to my appare there any condition to get the valid access token i tried the exact same permissions with android sdk stream example app but it could not solve the problemi want to share this information with anyone who are facing the same problem and check if changing the app id to get the valid access token will solve your case,['android'] +250163,nodejs vs net performance i have read a lot about nodejs being fast and able to accommodate large amounts of load does anyone have any real world evidence of this vs other frameworks particularly net most of the articles i have read are anecdotal or do not have comparisons to netthanks,['.net'] +250170,doxygen and add a value of an attribute to the output documentation servicestack marks rest paths for web services using c attributes for example restservicehello1restservicehello2public class helloi would like to make doxygen include values of the restservice attribute in the doxygen output for the hello class i am not concerned too much with pretty formattin if the full line with brackets is included in the output document any suggestionsa quick and dirty trick would be a preferable to writing a doxygen extension cheerstymekeditthe python version so will work on windows easily of doxygen users answer would beusrbinenv pythonimport sysimport reif lensysargv 2 print no input fileelse f opensysargv1 line freadline while line re1 recompilerestservice re1searchline sysstdoutwritere1subr b restservice 2 1n n line sysstdoutwriteline line freadline fcloseand the doxyfile would haveinput filter doxygenfilterpy,['c#'] +250217,what is the role of the activity class in mvc i know there have been quite a few questions about this however i am still struggling to understand what role the activity class should play when implementing the traditional modelviewcontroller design pattern on android my gut feel is that it should be the controller however that means a onetoone relationship between ui screens since you must have one activity per screen and controllers which defeats the point of mvcs loose coupling between the different components,['android'] +250244,how to remove comma if string having comma at end i want to remove comma at end if string ends with commafor example string names abci need to remove last comma if string ends with,['java'] +250272,what exactly does the iphone accelerometer measure the apple documentation for uiacceleration class says when a device is laying still with its back on a horizontal surface each acceleration event has approximately the following values x 0 y 0 z 1now i am confused how can the acceleration be nonzero when you clearly say the device is laying stillupdatejudging by the responses i think this should be called something like forceometer or gravitometer and not accelerometer,"['iphone', 'ios']" +250322,export generics in mef i want to export a generic class to a generic interface via mef my objects arepublic interface iservicet exporttypeofiservicet errorpublic class servicet public class clientt import private iservicet servicebut when i try to export iservicet i get this errorattribute argument cannot use type parameterscan anybody guide me to do this please,['c#'] +250402,sqlcommandthispose before sqltransactioncommit would it work to thispose a command assigned to a transaction before the transaction is committed i tested the following code myself and it seems to have worked fine but this is a rather small example so i am looking for confirmation if someone positively knowsinternal static void testtransaction try programdbconnectionopen using sqltransaction transaction programdbconnectionbegintransaction boolean dorollback false for int i 0 i 10 i using sqlcommand cmd new sqlcommandinsert into testdbdbotransactiontest testvalcol values index programdbconnection transaction cmdparametersaddwithvalueindex i try cmdexecutenonquery catch sqlexception dorollback true break if dorollback transactionrollback else transactioncommit finally programdbconnectionclose,"['c#', '.net']" +250422,is it possible to accelerate dynamic linq queries using gpu i have been searching for some days for solid information on the possibility to accelerate linq queries using a gputechnologies i have investigated so farmicrosoft accelerator cudafybrahmain short would it even be possible at all to do an inmemory filtering of objects on the gpuleta s say we have a list of some objects and we want to filter something likevar result mylistwherex xsomeproperty somevalueany pointers on this onethanks in advanceupdateia ll try to be more specific about what i am trying to achieve the goal is to use any technology which is able to filter a list of objects ranging from 50 0 to 2 0 0 in the absolutely fastest way possiblethe operations i perform on the data when the filtering is done sum min max etc is made using the built in linqmethods and is already fast enough for our application so thata s not a problemthe bottleneck is simply the filtering of dataupdatejust wanted to add that i have tested about 15 databases including mysql checking possible cluster approach memcached solution h2 hsqldb velocitydb currently investigating further sqlite mongodb etc and none is good enough when it comes to the speed of filtering data of course the nosql solutions do not offer this like the sql ones but you get the idea andor the returning of the actual datajust to summarize what iwe needa database which is able to sort data in the format of 200 columns and about 250 0 rows in less than 100 msi currently have a solution with parallellized linq which is able on a specific machine to spend only nanoseconds on each row when filtering and processing the resultso we need like subnanosecondfiltering on each rowwhy does it seem that only inmemory linq is able to provide thiswhy would this be impossiblesome figures from the logfiletotal tid far 1164 fragor 2579this is swethish and translatestotal time for 1164 queries 2579where the queries in this case are queries likewhere someproperty somevalueand those queries are all being done in parallell on 225639 rowsso 225639 rows are being filtered in memory 1164 times in about 25 secondsthata s 95185952917007032597107300413827e9 seconds row but that also includes the actual processing of the numbers we do count not null total count sum min max avg median so we have 7 operations on these filtered rowsso we could say ita s actually 7 times faster than the the databases wea ve tried since we do not do any aggregationstuff in those casesso in conclusion why are the databases so poor at filtering data compared to inmemory linq filtering have microsoft really done such a good job that it is impossible to compete with it it makes sense though that inmemory filtering should be faster but i dona t want a sense that it is faster i want to know what is faster and if ita s possible why,['c#'] +250424,are c11 standard containers final we should know that c standard library containers including stdstring are not meant to be inherited from but still c9803 did allow us to do it even if it was leading to bugsnow that the final keyword is available are those standard library container marked final to prevent bad use of inheritance with themif not why is that,['c++'] +250433,how to connect to rild socket i am trying to write an app to talk to the rild and yes i know this is not politically correct but it is an embedded industrial telemetry app so i am not concerned about user experience portability and all that stuffthe problem is that when i try to connect i get a javaio permission denied exception can anybody help methe phone nexus one is rooted with cyanogenmod 7 and the app is running as superuser using the superuser app from marketmy code abbreviatedtry msocket new localsocket msockaddr new localsocketaddress rild localsocketaddressnamespacereserved msocketconnect msockaddr catch exception e dbgp connect failed e i see the rild and rilddebug sockets in devsocketsrwrw 1 root radio 0 feb 13 1914 rildsrwrw 1 radio system 0 feb 13 1914 rilddebugcould it be that the dialer app is already connected and hogging the socketbtw i initially tried to use the frameworks but got a humongus boatload of errors mostly about java and and third party classes unknown so i gave up after days of hairpulling i have also stfw and this site lots of dancing around the issue but no concrete adviceany help greatly appreciatedjohn,['android'] +250443,python and operator with ints what is the explanation for this behavior in pythona 10b 20a and b 20b and a 10a and b evaluates to 20 while b and a evaluates to 10 are positive ints equivalent to true why does it evaluate to the second value because it is second,['python'] +250444,convert docx to pdf using php i am currently generating multiple docx files using phpword i need to find a way to combine these docx files and save them as 1 pdf file is there a way that this can be done,['php'] +250476,jwplayer for fullscreen background video i am looking to use jwplayer for fullscreen background video that simply plays in a loop as the background of the sitei am testing this here with moderate success in chrome on mac osx please excuse the size of the video file dextersgospelcomfullscreenvideohtmlon page load i grab the width and height of the browser window and set the values as the width and height parameters in jwplayer setup awesomenow what i would like to add is functionality that resizes the video if the browser window is resized i have looked into the onresize and onfullscreen events but cannot figure out how to implement those to make this work or tell if those are even the solution i have also looked into the jquery resize function to no availi would also like to prevent the video from being paused when clickedif anyone could provide some tips on how to use jwplayer for fullscreen background video it would be much appreciated,['jquery'] +250486,where and how is the viewstartcshtml layout file linked heres the aboutcshtml from the default mvc 3 template viewbagtitle about ush2abouth2p put content herepi would expect that a reference to the viewstart file would be found in the aboutcshtml but clearly it is noti have looked in globalasax and webconfig but i cannot find out how the aboutcshtml file is linked with the layout from the viewstart file everything works as expected i would just like to know whats going on under the hood,['.net'] +250529,how to add a h1 tag with gwt well the question might seem stupid but i really cannot figure it out how can you add dynamically a html heading tag to your page using the google web toolkiti do not want to do this for the style of the heading as i could add any style to any label it is because i want to use the jqueryui accordion it works with a pair of header and content panelhow can i do this,['html'] +250536,passing maven properties to spring i know this is probably a dumb question but i cannot figure it out for the life of me basically i am using maven to set my datasource username password and driver class name when i look in the effective pomxml it all appears fine as follows datasourcedriverclassnameoraclejdbcdriveroracledriverdatasourcedriverclassnamedatasourceusernamesomeusernamedatasourceusernamedatasourcepasswordsomepassworddatasourcepasswordi am trying to use this information when declaring a spring datasource the code appears as followsbean iddatasource classorgapachecommonsdbcpbasicdatasource destroymethodclose property namedriverclassname valuedatasourcedriverclassname property nameurl valuedatasourceurl property nameusername valuedatasourceusername property namepassword valuedatasourcepasswordbeani then pass the datasource into a jdbctemplate but when i use the template to run sql statements in my code i get an error saying that no driver with the name datasourcedriverclassname can be found this is obviously because the string constant is being passed rather than the variable what am i missingthanks,['java'] +250555,multiple inputs with mrjob i am trying to learn to use yelps python api for mapreduce mrjob their simple word counter example makes sense but i am curious how one would handle an application involving multiple inputs for instance rather than simply counting the words in a document multiplying a vector by a matrix i came up with this solution which functions but feels sillyclass matrixvectmultiplytastmrjob def multiplyselfkeyline line mapfloatlinesplit vcol line1line1 for i in xrangelencol yield icoliv def sumselfioccurrences yield isumoccurrences def stepsself return selfmr selfmultiplyselfsumif name main matrixvectmultiplytastrunthis code is run matrixpy inputtxt and the reason it works is because the matrix stored in inputtxt by columns with the corresponding vector value at the end of the line so the following matrix and vectorare represented as inputtxt asin short how would i go about storing the matrix and vector more naturally in separate files and passing them both into mrjobthanks,['python'] +250577,are there hooks in aspnet mvc prior to layout execution and post body render when aspnet mvc executes a page containing razor it will first run the body eg the renderbody method then it runs the code for the layout and weaves it together this is documented in this blog postsystemwebmvcrazorviewrenderview systemwebwebpageswebpagebaseexecutepagehierarchy non virtual version systemwebwebpageswebpagebasepushcontext systemwebwebpageswebpagebaseexecutepagehierarchy virtual version thisexecute generated code from our view systemwebwebpageswebpagebasepopcontext rendersurroundingvirtualpath body render layout which is similar to views rendering process essentially you can have nested layout verifyrenderdbodyorsetionsi want to add code to my views and layout that traces the actual logical position in the page is there a way i can hook up a method to run just before rendersurrounding and just after renderbody finishes executing,['c#'] +250580,how can i bind the css backgroundimage property is it possible to make a style backgroundimage binding i tried this codediv databindforeach itemlist div databindstyle backgroundimage urltemppng some textdiv divi also tried backgroundimage without quotes in url without after url but it is still not working all the others like color or backgroundcolor bindings are working perfectly,"['javascript', 'html', 'css']" +250589,system vs shellexecute differences in c what are the main differences between system and shellexecutein what situations should i use system and shellexecute,['c++'] +250599,how to find maximum value of set of variables i was wondering if anyone could help me find the maximum value of a set of variables and assign them to another variable here is a snippet of my code that may help with understanding what i am talking about ask for quarter values systemoutprintlnwhat is the value of the first quarter firstquarter inputnextdouble systemoutprintlnwhat is the value of the second quarter secondquarter inputnextdouble systemoutprintlnwhat is the value of the third quarter thirdquarter inputnextdouble systemoutprintlnwhat is the value of the fourth quarter fourthquarter inputnextdouble tell client the maximum valueprice of the stock during the year maxstock this is where i need help systemoutprintlnthe maximum price of a stock share in the year is maxstock,['java'] +250610,c 40 compile time error fails to resolve overload when wrong overload contains parameter types defined in net components that are not referenced heres simple code for a c 40 console programusing systemdirectoryservicesprotocolsnamespace overloadtest class program static void mainstring args var request new searchrequest searchscopebase null searchrequest has 3 constructors only the two which take 4 parameters matter for this examplebetween these two constructors they have identically typed and named parameters for their first third and forth parameters only the second parameters differ string ldapfilter versus xmldocument filterthe above code is obviouslytome calling the constructor which has its second parameter declared as string ldapfilterbut if the project that this code is in does not have a reference to systemxml then a compile results in the following errorthe type systemxmlxmldocument is defined in an assembly that is not referenced you must add a reference to assembly systemxml version40 cultureneutral publickeytokenb77a5c561934e089apparently the compiler cannot evaluate which overload to use because the wrong overload has a parameter of a type that is not understood due to the lack of reference to the declaring component sure the compiler has to find a best method to match my code but as my second passed parameter is a string why does the compiler need to bother worrying about matching my code to the xmldocument overload or alternatively as systemdirectoryservicesprotocolssearchrequest is using the xmldocument type as a constructor parameter type why does not the compiler already know enough enough about what an xmldocument is to determine that a string is not one and thus be able to choose the correct overloadi have already got two workarounds that compile without erroradd a reference to systemxml in the projectname the 2nd parameter and thus the 3rd and 4th too by necessity like sovar request new searchrequest ldapfilter searchscope searchscopebase attributelist nullfor my particular case this works because the two overloads second parameters differ not just in type but also in name ldapfilter versus filterit would be nice though if neither workaround was needed,['c#'] +250629,jqueryui dialog positioning i am using jquery ui and would like to position my dialog horizontally centered but vertically above center maybe by a fixed amount of pixels or a relative thistance from the top of the page is there an easy way to do this it looks like there are just a couple predefined values or i can use an exact position but is there an easy way to accomplish this dialogformdialog autoopen false width 630 position center modal true resizable false closeonescape false,"['jquery', 'html', 'css']" +250648,rails 32 heroku push rejected no cedarsupported app detected rails newbie here i am trying to deploy my rails 31ruby 193p0 app to heroku and have followed all the steps according to heroku but i keep running intoheroku push rejected no cedarsupported app detectedi have tried all the suggestions in this question but so far unsuccessful,['ruby-on-rails'] +250657,apache virtual host not parsing php i decided to enable virtual hosts on my apache server and chose to make it portbasedfirst thing i did of course was rtfm i followed the instructions found here well it worked kind of as far as the virtual host running it does the content pulled from 80 is different from 8080but php is not working the original site port 80 is running php just great the port 8080 site however sends the php to the browser i see nothing in the browser but the source code showsphpecho it workedthis topic seems to be very loosely documented on a few websites but either i cannot find a solution in them or the solution listed is not working for meagain the virtual host itself is running fine php on the other hand is notany ideas on what it could be what content from my httpdconf file should i provide so i do not blow up my question by copypasting the whole thingsorry i forgot to post that i had these in place phil adding to avoid further confusionlisten 80listen 8080namevirtualhost 80namevirtualhost 8080virtualhost 80 servername mysitecom documentroot varwvhostssite1httpdocsvirtualhostvirtualhost 8080 servername mysitecom documentroot varwvhostssite2httpdocsvirtualhosti tried adding this inside the tagsaddhandler php5script phpaddtype texthtml phpbut to no avail,['php'] +250664,how to fail ajax request in rails when user clicks a specific item i use jquerys post method to update something in the databasepostposts post id update something some param some value success handlerwhere update something looks like thisdef update something post postfindparamsid postupdate attributessome field paramssome param render nothing trueendthe problem is if update attributes fails the request still succeeds and success handler is executedhow could i cause the request to fail when update attributes fails such that success handler would not be executed,"['jquery', 'ruby-on-rails']" +250673,how can i tell if a child is asking for stdin how do i tell it to stop that in bash when i run a command like wc or cat that wants standard in right away it returns immediately with1 stopped cathow is this accomplished how do i stop a program that i started with exec and how do i know to stop these programs in the first place is there some way to tell that these programs want stdinthanksps also what is the about i have always wondered but that is really hard to google,['c'] +250690,multiple inheritance i have looked on line for information that would help me solve a design issue that is confusing me i am new to complicated inheritance situations so my solution could actually just be rooted in a better design but in trying to figure out what my design should be i keep ending up thinking i really just need to inherit more than 1 base classmy specific case involves assets and different types of assetsstarting with the assetevery physicaldevice is an assetevery virtualdevice is an assetevery server is an assetevery physicalserver would need to be both a physicaldevice and a serverevery virtualserver would need to be both a virtualdevice and a serverevery netdevice is a physicaldevice every storagearray is a physicaldevice one solution i guess is to duplicate the server code for both physicalservers and virtualservers however i feel like this goes against what im trying to do which is inheritthey need to be separate classes because each of the types will have properties and methods for instance server will have oscaption memory procs etc physicaldevice will have things like location serial vendor etc and virtualdevice will have a parentdevice state vhdlocation etcif the inheritance is liner then i run into the problem of not being able to describe these types accurately something that seems intriguing is interfaces it seems that i can define all base classes as interfaces and implement them in my main classes as needed but i am simply unsure of what the implications are if i were to do thatfor instance something like physicalserver iasset iserver iphysicali am in deep water so iam really just looking for suggestions or guidance,['c#'] +250698,what approach of improving incremental building of the maven projects do you prefer i am going to optimize time of building our projects one of the most timeconsuming thing is a compilation of the projectsdue to known problem of the maven mentioned in particular heremaven incremental buildingwe have to use mvn clean before every building processi have investigated this question and found out two approachesincrementalbuildplugin maven mojomaven 2 reactor plugini have tested incrementalbuildplugin maven mojo and it looks pretty good as i see maven 2 reactor plugin implements almost the same functionality but the special command should be specified to achieve results mvn reactormake for instanceso i have made conclusion that maven 2 reactor plugin is more convenient only for developers if they are going to optimize time of the buildings on their local computers but i have some hesitation because maven 2 reactor plugin is hosted and as i think is supported as official maven plugin but incrementalbuildplugin maven mojo is hosted on javanetand my questions areare my conclusions that these two plugins solve almost the same problem rightdo anybody has any experience using both of these plugin and able to give any feed back about themdo you have other ideas of optimization of the building,['java'] +250699,is it possible to get structural elements from a pdf file using itextsharp we are using itextsharp with a c winforms application to parse a pdf file using itextsharp i can easily extract the text data from the pdf file suppose a pdf file contains an image surrounded by two lines of text in this case i could not extract the information about the imagemy requirement isget structural elements of the pdf fileprocess whether each is of type text image table or otherfor example the structural elements are similar to the followingtext paragraph1text paragraph2imageimagetext paragraph3tabletable infotext paragraph4if i can obtain information in a format like this i can easily understand the text image table header or footer informationso is it possible to get this kind of information using itextsharp if yes please enlighten me on this otherwise could you please suggest some other tools capable of meeting this requirementthanks to allsaravanan,['c#'] +250714,show the password with edittext i use an edittext to enter passwordand a checkbox to show password or notbelow function is the partpublic void showpassword if cbischecked passwordsetinputtypeinputtypetype text variation visible password else passwordsetinputtypeinputtypetype text variation password when it checked it show passwordbut when it not checked it does show starshow to modify it to show star while the cb is not checked,['android'] +250762,checkbox gets unchecked on scroll in a custom listview i know that this question has been asked over and over again but still i have not been a able to find a suggestion that really helps me the checkbox is unchecked whenever the list is scrolled down yes i am using a boolean array to store the values but this still does not fix the problem here is my code please suggest a solution for this thank you public view getviewfinal int position view convertview viewgroup parent todo autogenerated method stub final viewholder holderfinal boolean itemcheckednew boolean30 layoutinflater inflater contextgetlayoutinflater ifconvertviewnull convertview inflaterinflaterlayoutcustom list null holder new viewholder holdertxtviewtitle textview convertviewfindviewbyidridtitle text holdertxtviewdescription textview convertviewfindviewbyidriddescription text holdercbcheckbox convertviewfindviewbyidridcb convertviewsettagholder else holderviewholderconvertviewgettag holdercbsetoncheckedchangelistenernew compoundbuttononcheckedchangelistener override public void oncheckedchangedcompoundbutton buttonview boolean ischecked todo autogenerated method stub itemcheckedposition ischecked ifitemcheckedposition holdercbsetcheckedtrue else holdercbsetcheckedfalse holdertxtviewtitlesettexttitleposition holdertxtviewdescriptionsettextdescriptionposition holdercbsetcheckeditemcheckedposition holdertxtviewdescriptionsetfocusablefalse holdertxtviewtitlesetfocusablefalsereturn convertview,['android'] +250782,how to create cgpathref from array of points hi all i have been working in a map application where i needed to draw the route between two locations i have got route coordinates too using google direction api and kept it in an array now all i need to do is creating a path from the array of points later i will use the path with mkoverlaypathview for creating real routes on the map here my problem is how to create a cgpathref from the array of coordinates or any other way to do the same operationthanks in advance,['objective-c'] +250820,twitterbootstrap simple form not making horizontal form or correct html output i do not know why its not duplicating like the example when i put the following code to have this form simple form forresource as resource name url registration pathresource name html class formhorizontal do f finput user name input html class span3 hint just letters and numbers please end right now it looks like thiswhen i want it to be like this the first example here the problem lies in the html being generated my html isdiv classinput string optional label foruser user name clastring optional user namelabel input typetext size50 nameuseruser name maxlength25 iduser user name clastring optional span3 span classhintno spaces or special characters just letters and numbers pleasespandivand simple forms htmldiv classcontrolgroup string required label forarticle name clastring required abbr titlerequiredabbr name label div classcontrols input typetext size50 namearticlename idarticle name clastring required span6 p classhelpblockadd your article title herep divdivtotally different i am thinking the bootstrap generator does not generate what do you think what should i doresources form formbootstrap,['ruby-on-rails'] +250830,javascriptjquery random number between 13 and 13 excluding numbers between 3 and 3 i am using var min 13var max 13var random mathfloormathrandom max min 1 minbut it returns all numbersrandom between 13 and 13 how can i get it to generate a random number between 13 to 4 exluding 3 2 1 0 1 2 3 and including 4 to 13,"['javascript', 'jquery']" +250832,html5 video seeking updated how can i get my video player to skipseek to a certain time i have had a go at this and it works when the page first loads in chrome but not in any other browser i also have a flash fallback which could be a pain but for now the priority is the html side of thingsthe major issue is that it does not work outside chrome edit this now works in ie9 chrome and firefox however not with the flash fallbackbelow is my attempt so fari am using the following js so far script languagejavascript function var v videoget0 playclickfunction vplay sclickfunction alertclicked thishtml has time of thisattrs vcurrenttime thisattrs vplay scriptwhich links to the followingvideo idvideo controls width500 if firefox source srcvideoogg typevideoogg if safarichrome source srcvideomp4 typevideomp4 if the browser does not understand the video element then reference a flash file you could also write something like use a better browser if youre feeling nasty better to use a flash file though object typeapplicationxshockwaveflash dataplayerswf width854 height504 param nameallowfullscreen valuetrue param nameallowscriptaccess valuealways param nameflashvars valuefilevideomp4 if ieparam namemovie valueplayerswfendif pyour browser canat play html5 videop object video with the context of having buttons with a class s and custom attribute s60 for 60 seconds etc,"['javascript', 'jquery']" +250836,why does listforeach allow its list to be modified if i usevar strings new liststring sample foreach string s in strings consolewritelines stringsadds the add in the foreach throws an invalidoperationexception collection was modified enumeration operation may not execute which i consider logical since we are pulling the rug from under our feethowever if i usevar strings new liststring sample stringsforeachs consolewritelines stringsadds it promptly shoots itself in the foot by looping until it throws an outofmemoryexceptionthis comes as a suprise to me as i always thought that listforeach was either just a wrapper for foreach or for fordoes anyone have an explanation for the how and the why of this behaviorinpired by foreach loop for a generic list repeated endlessly,['c#'] +250853,maven fail build when unit test takes too long i have in my project a lot of unit tests written in junit and testng the building process is based on maven with surefire pluginis there any wayplugin for maven to fail the build when at least one unit test takes too many seconds i know that there are some plugins to fail build in teamcity jenkins but this is too farin my project i want to have only fast tests to have unit testing process effective i can improve my old tests but i need to protect for the future commitments,['java'] +250889,monodevelop on mac export settings we are having a new developer well versed in visual studio start working in monotouch on the maci have my settings in monodevelop after using for a while setup exactly like visual studiohotkeys like f5 f6 f10 ctrlj ctrl etccode formattingmodified and additional code snippetsis there a way to export these and import on another machine i do not mind to manually copy files i am using monodevelop 2864 should be latest nonbeta right nowi would also like to put my settings up on github if this is something that is possible i know a lot of netters would make use of it,['c#'] +250899,how to paginate rabls collections i have this template appviewspostsindexrablcollection posts postsattributes id title subjectchilduser attributes full name noderead post postread byuser witch returns posts post id 5 title subject user full name read true and i would like to add to add some pagination params in order to rendering this posts post id 5 title subject user full name read true total 42 total pages 12any ideas many thanks,['ruby-on-rails'] +250928,javascript web app best practices i am having a hard time writing my question succinctly and clearly so let me describe what i am working withi am building a web application thathas it is own api hosted on a subdomain has the main application hosted on the tld the tld does not have any database access but instead interacts with the api to work with datathe tld authenticates with the api through oauth and stores the access token and access token secret in a sessionwhen the session ends the access token is no longer used thus logging the user outi have a route in the tld let us call it ajax for this question that the javascript calls get put post or delete to make requests to the api this way nobody ever has to see the access token access token secret consumer key or consumer secretthe way i see it the access token and access token secret are really the only things i need to store in a session since i can grab everything else using the api but instead of making a call every single time for every piece of data i need i think some things should persist like aspects of the users profile layout preferences etcwhat is the best way for me to accomplish this local storage cookies should i scrap this and just store it in sessionsand if you have some time what other best practices are there for building sites like this that i may not know of,['javascript'] +250937,trying to understand over and partition by i am trying to get the over and partition by functionality wrapped around my head here is an example that i just do not understandhere is the data i havesalesorderid orderdate 43894 08012001 43664 07012001 43911 08012001 43867 08012001 43877 08012001 44285 10012001 44501 11012001 43866 08012001 43895 08012001 43860 08012001when i run this queryselect row number overpartition by orderdate order by orderdate asc as rownumber salesorderid orderdatefrom test2order by rownumberhere are the results i getrownumber salesorderid orderdate 1 43664 07012001 1 43911 08012001 1 44109 09012001 1 483 11012001 1 44285 10012001 2 43867 08012001 2 44501 11012001 3 43895 08012001 4 43894 08012001 5 43877 08012001 can someone explain this query to me i am not new to sql but windowing i have been struggling with and cannot get my head wrapped around this,['sql'] +251006,python logging module custom loggers i was trying to create a custom attribute for logging callers class name module name etc and got stuck with a strange exception telling me that the logrecord instance created in the process did not have the necessary attributes after a bit of testing i ended up with thisimport loggingclass myloggerlogginggetloggerclass value noneloggingsetloggerclassmyloggerloggers logginggetlogger logginggetlogger logginggetloggernamefor logger in loggers printisinstancelogger mylogger hasattrlogger valuethis seemingly correct piece of code yieldsfalse falsefalse falsetrue truebug or feature,['python'] +251071,skin options menu android i am trying to skin the options menu on android i have the background color changed with a custom theme but i cannot get the text color to change for some reason my themestyle namedefault parentandroidstylethemenotitlebar menu panel colors item nameandroidpanelbackgroundcoloroptionsmenubackgroundcoloritem item nameandroidpanelfullbackgroundcoloroptionsmenubackgroundcoloritem menu item colors item nameandroiditemtextappearancestyleoptionsmenufontitem stylemy style for the options menu fontstyle nameoptionsmenufont parentandroidstyletextappearancewidgeticonmenuitem item nameandroidtextcolordrawablemenu item fontitemstylemy drawable for the button color selector menu item fontxmlxml version10 encodingutf8selector xmlnsandroid put other state colors up top item androidcolorcoloroptionsmenutextcolor selectorthat color is just a hex color c4c4c4what am i missing here,['android'] +251074,moving django models into their own files in the name of maintainability i moved some of my larger models to their own files so before i had thisapp modelspyand now i have thisapp models init py model apy model bpythis works fine but when i use managepy to do sync db it does not create a table for these models anymoream i forgetting somethingthanks,['python'] +251082,double underscore in cakephp 20 i thought double underscore always meant private function but what does it mean in cakephp 20 in such examples as thisfor examplethissessionsetflash the user could not be saved please try again,['php'] +251087,how to log stack trace using log4net c how to log stack trace with log4net i am using net version they way i have is logerrorexthanks,['c#'] +251100,inline blob binary data types in sql jdbc let us say i want to avoid using bind variables in jdbc and run sql using adhoc statements egconnectioncreatestatementexecutequeryselect is there any convention jdbc escape syntax to inline blob data types i know that h2 has this syntaxinsert into lob table values x01ffbut that is not a standard any general solutions note i am interested in a general approach i know that this can turn out to be terribly inefficient,['sql'] +251107,markdown to html using a specified css first let me say i love markdown truly love it it is simple it is elegant it is sexy it is everything i wish for in a markup language if i could i would propose to it so far i have been using it in a very nice and simple way vim pythonmarkdown fast preview in my browser of choicebut it has one drawback the css sheet is hardcoded somewhere inside the plugin and i cannot change it note i know zero python or something very close to itis there a markdown to various formats plugin that lets you specify a css page to use so that i could have several and create several versions of the same document using the one i wish at that time it would go something likemarkdown mydocumentinmarkdown csheetcss coollookingdocumenthtml,"['python', 'css']" +251164,unable to append to clipboard whenever i try the following in my python interpreter i am able to copy the word helloto the command line even after i close the interpreterfrom tkinter import tkr tkrclipboard append hello however if i put this in a file called testpy and then trypython testpythis will not work i cannot append this to the system clipboarddoes any one know why not or know what difference between running it in a script and in the interpreter would cause,['python'] +251169,set encoding in python 3 cgi scripts when writing a python 31 cgi script i run into horrible unicodedecodeerrors however when running the script on the command line everything worksit seems that open and print use the return value of localegetpreferredencoding to know what encoding to use by default when running on the command line that value is utf8 as it should be but when running the script through a browser the encoding mysteriously gets redefined to ansi x341968 which appears to be a just a fancy name for plain asci now need to know how to make the cgi script run with utf8 as the default encoding in all cases my setup is python 313 and apache2 on debian linux the systemwide locale is en gbutf8,['python'] +251172,how to change the android emulator ram size from the command line i want to edit or change the ram size while creating the android emulator from command line ex while creating the emulator it is taking default ram sizeandroid sdk 403 512 mbbut i want to increase it to 768mb or decrease it to 256mbi want to change only ram size because there is an option to change the ram size do you wish to create a custom hardware profile no yesif you entered yes we need to provide so many things,['android'] +251205,how to check object is null or empty in cnet 35 if objects contains null or empty then how to validate or check the condition for the samehow to bool check whether object obj is null or emptyi have code as followsclass program static void mainstring args object obj null double d converttodoublestringisnulloremptyobjtostring 00 obj consolewritelinedtostring with this code i am getting nullreference exception as object reference not set to an instance of an objectpls helphere i am not gettinghow to validate whether that object is null or empty without converting into tostring is there an approach to check the same,"['c#', 'asp.net']" +251211,programmatically creating a cmspage in magento i saw the following answer to the post where are magento static cms blocks stored regarding programatically using php generating cmsblocks in magentoi changed the code to the followingnewblock magegetmodelcmspage settitletest cms page title setcontenthello i am a new cms page setidentifierthisisthepageurl setisactivetrue save and it works i see a new page show up in the cms pages area in the backend what i need to add to this is the ability to set the content of the other fields in the cmspage namelylayout trying to set to 1 column meta keyword meta description fields these fields are blank currently i so far have not been able to figure this part out thanks,['php'] +251228,iphone image captured from camera rotate 90 degree automatically programatically i have fetched image from my camera in my app it has been fetched nicely but when i shift to another view and thismiss that view at that time my image automatically rotate 90 degreeand this change occurs only first time after that when i shift no change occurs means image stays in 90 degree state and this happens only when i captued image from camera when i fetch image from photo library no issue has been foundfollowing image is my original imageand this is rotated imagei do not know why this change happen,"['ios', 'objective-c', 'iphone']" +251286,handling migrations with mongodb just to give a little more context to the question i have a web application asp mvc which basically wraps crud operations to a mongodb instance it carries out validation and certain business logic before the model is verified and sent over to be stored retrieved etcnow one problem we have his is that in the new version the models have changed but the existing data has not here is an example it is c specific but the question really is language agnosticpublic class person public guid id get set public string name get set public int age getset public string badgeno getsetpublic class person public guid id get set public string name get set public int age getset public string employeeno get set still contains same data as badgeno just called something differentas you can see the structure of the objects have changed but in mongo land it is still passing out a badgeno not an employeeno in an sql land we would usually have a migration script which is run as part of the build script which would change the schema and updateinsertdelete any additional data for that deltaso how is it best to manage these sort of migrations with mongo should i also have a script which i use to update all instances within mongo or is there some other preferred practise for doing this sort of thingany advice on the subject would be great edit it seems like currently i am wanting to go with the migration option rather than a phasing out approach so with this in mind can anyone recommend any tools for helping in this area as otherwise each migration assuming a rollin rollout would have to be a pre compiled assembly of some kind with all the logic in i was thinking something along the lines of fluentmigrator but instead of working with sql you are working with mongo currently my build scripts are using nant i have seen some ruby tools but not sure if there are any net equivalent,['.net'] +251297,jquery cookie path i use the jquery cookie plugin for storing cookies with the following code i can save a cookie for 7 days but it only saves it for the page its created on i want the cookie to be available for the whole websitecookiebasketbasket expires 7 i tried to set a path but that did not seem to workcookiebasketbasket expires 7 path full code this works fine but it only saves the cookie for the current pagefunction add to basketidtitleifcookiebasket basketcookiebasket var basket array basketsplit var index jqueryinarrayidbasket array ifindex 1 return false else basketid cookiebasketbasket expires 7 else basketid consolelogbasket cookiebasketbasket expires 7,"['javascript', 'jquery']" +251320,winforms adjust controls to push up vertically when others are invisible i have create a c winforms formit has a bunch of labels positioned and a flowlayoutpanelon certain occasions i set one of the labels and the flowlayoutpanel to visible falseas a result i want all labels beneath them to be pushed up at the moment there is a gap where they werealso i would like the flowlayoutpanel to grow and shrink depending on the number of items it hasat the moment it is just the size i set it to be in the designerplease can you help with these 2 issuesthanks,['c#'] +251331,how to place actionbar items in main actionbar and bottom bar the google app has a layout where it has action bar items in the main action bar and the bottom currently i am using androiduioptionssplitactionbarwhennarrow to place items in the bottom bar how can i place items on both the top and bottom,['android'] +251356,initialize private readonly fields after deserializing i need to initialize private readonly field after deserialization i have folowing datacontractdatacontractpublic class item public item constructor not called at deserialization because of formatterservicesgetuninitializedobject is used so field will not be initialized by constructor at deserialization privatereadonlyfield new object initialization will not be called at deserialization same reason as for constructor private readonly object privatereadonlyfield new object datamember public string someserializableproperty get set ondeserializing public void ondeserializingstreamingcontext context with this line code even not compiles since readonly fields can be initialized only in constructor privatereadonlyfield new object all what i need that after deserialization privatereadonlyfield is not nullany suggestions about this is it possible at all or i need to remove readonly key which is not a good option,['c#'] +251364,why does not pdos oracle driver implement lastinsertid i get this error in pdoerror message pdolastinsertid pdolastinsertid sqlstateim001 driver does not support this function driver does not support lastinsertidwhen trying to get last inserted id from an oracle database i added the sequence string to the last insert id function but still not working google does not say much regarding this error on oracle with pdo,['php'] +251374,process va args in c i have a function a and b now i have to call b inside a any methods to pass that from a into b pseudocodevoid a some operators b instead of i need to pass as argsps i know this could be done using macros but what about functions,['c++'] +251376,java classpath linux i am trying to understand how classpath really works after searching around the web this is where i have reached so fari have added export classpathhomefoohomefoojava codemy codeat etcenvironment i am running ubuntu by the wayjava finds the path and compiles without problemthe problem is that if i change the classpath and then i do source etcenvironment the new classpath is not applied it is applied if and only if i restart the system for example if i delete the export classpathhomefoohomefoojava codemy codeline then i do source etcenvironment and i finally do echo classpath what i get is homefoohomefoojava codemy code i think i should get an empty line should not i is there a way to apply the changes in path or classpath variables immediately without having to restart the systemit might help you know that the etcenvironment file originally contained only the following linepathusrlocalsbinusrlocalbinusrsbinusrbinsbinbinusrgamesthank you for your time,['java'] +251419,best way to pass a list of property names as lambda expressions i have a class mydummyclass to which i would like to pass some properties in form of a lambda expression for a later evaluation so what i can do something likepublic class mydummyclasst public mydummyclassexpressionfunct object property and then use that class like new mydummyclasspersonxxname rightbut then i would like to pass not only a single property but a list of properties so i would write my class likepublic class mydummyclasst public mydummyclassienumerableexpressionfunct object properties and i would like to use it like new mydummyclasspersonnew xxname xxsurname but unfortunately that does not work instead i have to writenew mydummyclassperson new expressionfuncperson object xxname xxsurnamebut this is a bit awkward to write is not it of course using params would work but this is just a sample out of a more complicated piece of code where using params is not an optiondoes anyone have a better option to come out of this,"['c#', '.net']" +251451,browser keeps rendering its cached version i want to always force a get how do i prevent the client browser from rendering its cached version for a page so that it must always perform a get when the visitor visits the pagei am using djangos never cache decorator in the view which adds cachecontrolmaxage0 to the http get header however when i visit the page in google chrome and firefox the only browsers i have tested so far the cached version is inevitably rendered confirmed by visiting the network tab for the request which reports 200 ok from cacheif i now click the refresh button it will render the fresh content from the server network tab for the request says 200 ok and the headers as shown belowin lieu of setting cachecontrolmaxage0 i also tried setting the expires http header parameter to be a date in the past this did not work eitherrequest methodgetstatus code200 okrequest headersaccepttexthtmlapplicationxhtmlxmlapplicationxmlq09q08acceptcharsetiso88591utf8q07q03acceptencodinggzipdeflatesdchacceptlanguageenusenq08cachecontrolmaxage0connectionkeepaliveifmodifiedsincefri 17 feb 2012 152521 gmtuseragentmozilla50 macintosh intel mac os x 10 7 3 applewebkit53511 khtml like gecko chrome17096356 safari53511response headerscachecontrolmaxage0connectionkeepalivecontentencodinggzipcontenttypetexthtml charsetutf8datefri 17 feb 2012 1511 gmtetagremovedexpiresfri 17 feb 2012 1511 gmtlastmodifiedfri 17 feb 2012 1511 gmtservernginxtransferencodindgchunkedvarycookieacceptencodingxhandledby12700180,['html'] +251454,why is one overlapping another here is my pages htmlbody headerheader div classconteudo representantesdiv div classrodapedivbodyi have content inside the conteudo representantes div that is going over the rodape footer divhere is my pages cssconteudo representantes marginleft auto marginright auto width 960px minheight586px margintop40px position relativerodape position relative width960px height50px margin36px auto backgroundtransparent urlimgheader patternpng repeat top leftthe full page source can be found in this example click on the second line of the list where it says 02 sao paulo capital to see this problem in actionwhat am i doing wrong,"['html', 'css']" +251469,numerical library for scala i am looking for a library to do numerical computing in scala or java although something that can use scala functions would be way nicer with at least the following capabilitieslbfgsminimizers powell quasinewton numerical differentiation of multivariable functionsnumerical integration not strictly necessary but highly preferredi am also only looking for something that is actively maintained last update during 2011 at the earliest preferably but not necessarily freealso numerical stability is required aka all operations should be implemented in a way that gives consistent results where precision is preserved as much as possiblei am already aware of imsl but would prefer something elsethanks in advance,['java'] +251497,dropdown menu with twitter bootstrap following on from this question i am still struggling with the twitter bootstrap i have managed to get my navigation bar to appear and i am trying to add a drop down menu to it no matter what i try i cannot actually get the drop down part of the menu to work here is a screenshot of my menuas you can see i have account settings which should be a drop down menu but when i click on it no drop down options appear below is my codedoctype htmlhtmlhead meta charsetutf8 titleviewbagtitletitle script srcurlcontentscriptsmodernizr17minjs typetextjavascriptscript script srcurlcontentscriptsbootstrapjs typetextjavascriptscript script typetextjavascript srcscript script typetextjavascript documentreadyfunction dropdowntoggledropdown script link hrefurlcontentcontentbootstrapmincss relstylesheet typetextcss headbody div classnavbar div classnavbarinner div classcontainer ul classnav a classbrand hrefpresent ideasa li classactivea hrefhomeali lia hrefblogali lia hrefaboutali lia hrefhelpali li classdropdown idaccountmenu a classdropdowntoggle datatoggledropdown hrefaccount settingsb classcaretba ul classdropdownmenu lia hrefloginali lia hrefregisterali li classdividerli lia hreflogoutali ul li ul div div div div classcontainerfluid renderbody divbodyhtmlas you can see i am referencing the dropdown javascript file from twitter i have also tried referencing this locally which made no difference i have also included the javascript that i believe should hookup the drop down menu and call into twitters javascript filei am at a loss as to why this is not working,"['javascript', 'asp.net', 'css']" +251512,how to create a trampoline function for hook i am interested in hooking and i decided to see if i could hook some functions i was not interested in using a library like detours because i want to have the experience of doing it on my own with some sources i found on the internet i was able to create the code below it is basic but it works alright however when hooking functions that are called by multiple threads it proves to be extremely unstable if two calls are made at nearly the same time it will crash after some research i think i need to create a trampoline function after looking for hours all i was not able to find anything other that a general description on what a trampoline was i could not find anything specifically about writing a trampoline function or how they really worked if any one could help me write one post some sources or at least point me in the right direction by recommending some articles sites books etc i would greatly appreciate itbelow is the code i have written it is really basic but i hope others might learn from ittestcppinclude stdafxhhook hooktypedef int winapi tmessageboxhwnd hwnd lpctstr lptext lpctstr lpcaption uint utypedword hmessageboxhwnd hwnd lpctstr lptext lpctstr lpcaption uint utype hookremovehook tmessagebox omessagebox tmessageboxhookfuncptr int ret omessageboxhwnd lptext hooked utype hookapplyhookhmessagebox return retvoid hookmessagebox printfhooking messageboxn ifhookfindfuncuser32dll messageboxa ifhookapplyhookhmessagebox printfhook applied nn else printfhook could not be appliedn hookcppinclude stdafxhbool hookfindfuncchar libname char funcname hookfuncptr voidgetprocaddressgetmodulehandlealibname funcname return hookfuncptr nullbool hookremovehook dword dwprotect ifvirtualprotecthookfuncptr 6 page execute readwrite dwprotect writeprocessmemorygetcurrentprocess lpvoidhookfuncptr hookorigdata 6 0 virtualprotecthookfuncptr 6 dwprotect null return true else return falsebool hookreapplyhook dword dwprotect ifvirtualprotectfuncptr 6 page execute readwrite dwprotect writeprocessmemorygetcurrentprocess lpvoidfuncptr hookhookdata 6 0 virtualprotectfuncptr 6 dwprotect null return true else return falsebool hookapplyhookvoid hook return sethookataddresshookfuncptr hookbool hooksethookataddressvoid funcptr void hook hookfuncptr funcptr byte jmp6 0xe9 jmp 0x00 0x00 0x00 0x00 address 0xc3 retn dword dwprotect ifvirtualprotectfuncptr 6 page execute readwrite dwprotect make memory writable readprocessmemorygetcurrentprocess lpvoidfuncptr hookorigdata 6 0 save old data dword offset dwordhook dwordfuncptr 5 tofrom5 memcpyjmp1 offset 4 write address into jmp memcpyhookhookdata jmp 6 save hook data writeprocessmemorygetcurrentprocess lpvoidfuncptr jmp 6 0 write jmp virtualprotectfuncptr 6 dwprotect null reprotect return true else return false,['c++'] +251516,linker error calling cfunction from objectivec i have got a weird linker issue i have code that looks like so double given amount selfmodelcontrollerlevelcompleterewardamount swrve currency givenswrve cfstringrefcurrencyname given amounti have this code in two separate places in an objectivec and an objectivec file it compiles fine in objectivec land but the swrve currency given function causes the following in my wgcontrollermm fileundefined symbols for architecture armv7 swrve currency givenswrve cfstring const double referenced from wgcontroller givetheusersomecashforplayingthislevel in wgcontrollerold symbols not found for architecture armv7collect2 ld returned 1 exit statusi am not entirely sure if this error is related to the objc vs c thing but it feels like it my theory is that it perhaps thinks that it is a function on the objc class the swrve code is 3rd party code one h and c file and i am importing like soimport swrvehany help is appreciatedthanks,['objective-c'] +251528,how to countdown to a date i am wondering if anyone can help me after hours of searching tirelessly on here and the web i cannot seem to find a simple countdown using jquery i do not want to use any sort of plugin just a simple jquery code to countdown from a date i have managed to find this code below but even with this code placing it in my website nothing appears i added the jquery file from jquerycom and added the proper divs with counter id and nothing if anyone can explain or show me how to make a simple countdown in a function that takes in a date format and returns a countdown i would appreciate the helpvar end new date02192012 101 am var second 10 var minute second 60 var hour minute 60 var day hour 24 var timer function showremaining var now new date var thistance end now if thistance 0 clearintervaltimer documentgetelementbyidcountdowninnerhtml expired return var days mathfloorthistance day var hours mathfloorthistance day hour var minutes mathfloorthistance hour minute var seconds mathfloorthistance minute second documentgetelementbyidcountdowninnerhtml days days documentgetelementbyidcountdowninnerhtml hours hrs documentgetelementbyidcountdowninnerhtml minutes mins documentgetelementbyidcountdowninnerhtml seconds secs timer setintervalshowremaining 10,['javascript'] +251535,what are the rules to initialization order in c possible duplicatewhat is the static variable initialization order in c for fun i ran this code i was not expecting 2 2 3 i was expecting a compiler error circlur dependency or 8 5 3what are the rules to initialization order in cedit i tried making a not static and i got what i expected why is b 2 before and now 5 i do not think i am going to like the rules luckily i never do anything like this so i have not had a problemusing systempublic class test public static void main at class a static int a bb c public static int c 3 static public void t consolewriteline0 1 2 a bb c class b public static int b ac2,['c#'] +251537,in what way is my array index an illegal string offset when futureproofing code by testing it on php 54 i get a warning i do not understandfunction clone thischanged true foreach thisconditions as key condition if conditionfield instanceof queryconditioninterface thisconditionskeyfield cloneconditionfield i broke out conditionfield into its own row to reduce the amount of code to focus on about that specific line php has this to saywarning illegal string offset field in databasecondition cloneand i just cannot see how field is an illegal string offset i am guessing that i am just missing something obvious but if the community cannot find a problem i will file a bug reporti interpret the warning as under no circumstances is field a valid key this error would have made sense if i had tried to us for example an array as a key,['php'] +251555,how do you use tornadotesting for creating websocket unit tests i am working on a project that works with tornados websocket functionality i see a decent amount of documentation for working with asychronous code but nothing on how this can be used to create unit tests that work with their websocket implementationdoes tornadotesting provide the functionality to do this if so could someone provide a brief example of how to make it happenthanks in advance,['python'] +251561,using a python dict for a sql insert statement i am trying to use a dict to do a sql insert the logic would basically beinsert into table dictkeys values dictvalueshowever i am having a tough time figuring out the correct syntax flow to do this this is what i currently have data sorted column headers list sorted column values list for k v in dataitems sorted column headers listappendk sorted column values listappendvsorted column headers string joinsorted column headers listsorted column values string joinsorted column values listcursorexecuteinsert into title s values s sorted column headers string sorted column values stringfrom this i get a sql exception i think related to the fact that commas are also included in some of the values that i have what would be the correct way to do the above,"['python', 'mysql', 'sql']" +251594,jquery load with fadein effect i am trying to load content of a url via ajax using jquery within primary it loads but does not fadein what am i doing wrong menu aliveclick functionevent var link thisattrhref contentfadeoutslow function primaryloadlink content function contentfadeinslow return false many thanks for your help,['jquery'] +251607,hotspot7 hsthis printassembly intel syntax it annoys me every time i use xxprintassembly with hotspot and have to read the horrible att syntaxis there a way to tell it to use the intel syntax,['java'] +251619,is there a way for an activity to know what fragment was just created an activity may inflate an arbitrary layout xml that may or may not have a fragment placeholder in it if it does the fragment will be instantiated and attached to the activityis there any way to get a reference to the fragment from the activity that has been attached to it fragmentmangerfindfragmentbyid assumes you know the id in advance to make it work but in this situation i am proposing it is not availablethe behavior i would ideally like to have is that the activity is aware of any fragments attaching itself to it so that it may respond to it,['android'] +251625,why hotspot will optimize the following using hoisting reading effective java the author mentioned thatwhiledone ican be optimized by hotspot into if done whiletrue ii am very confused about it done is usally not a const why can compiler optimze that way,['java'] +251665,twig templates engine get current url how can i get the current url from a twig templatei am using twig with php without any other framework,['php'] +251672,unescaping escaped characters in a string using python 32 say i have a string in python 32 like thisnwhen i print it to the console it shows as a new line obviously what i want is to be able to print it literally as a backslash followed by an n further i need to do this for all escaped characters such as t so i am looking for a function unescape that for the general case would work as follows s nt printunescapes ntis this possible in python without constructing a dictionary of escaped characters to their literal replacementsin case anyone is interested the reason i am doing this is because i need to pass the string to an external program on the command line this program understands all the standard escape sequences,['python'] +251680,how to reduce numbers significance in jsons stringify i have an array with numbers coordinates and i want to thisplay those using json like so jsonstringifyarraymy array looks likex0825y0 x15812503y05625 x2251562504y1546875but i am only interested in the first lets say 4 significant digits iex0825y0 x15813y05625 x22516y15469is there a way to easily ditch the remaining insignificant numbers,['javascript'] +251706,java jfilechooser windows network shares with password protection i need to present to the user or my application a dialogue in which that point to a particular file so naturally the easiest choice is to use a jfilechooserhowever the file that needs to be selected is on a windows network driveshare but it is mapped to a drive on the host computer running my app the network share is password and jfilechooser does present the drive in its dialoge but it cannot browse the drive until i use another program eg windows explorer to view the network share where it will ask for the passwordis it possible for the jfilechooser to request the user for a password does jfilechooser receive notification from the system that passwordauthentication is required using the sun example here it just fails silently which is not what i want to happen i want the user to be prompted for a password can i do this,['java'] +251734,ifliststrsize 0 versus ifliststrisempty liststring liststr new arrayliststringifliststrsize 0versusifliststrisemptyin my view one of the benefits of using liststrisempty is that it does not check the size of the list and then compares it to zero it just checks if the list is empty are there any other advantages as i often see ifliststrsize 0 instead of ifliststrisempty in codebases is there is a reason it is checked this way that i am not aware of,['java'] +251789,how does shovel i was going through ruby koans tutorial series when i came upon this in about hashesrbdef test default value is the same object hash hashnew hashone uno hashtwo dos assert equal uno dos hashone assert equal uno dos hashtwo assert equal uno dos hashthree assert equal true hashoneobject id hashtwoobject idendthe values in assert equals is actually what the tutorial expected but i could not understand how there is a difference between using operator and operatormy expectation was that hashone would be unohashtwo would be doshashthree would be can someone please explain why my expectation was wrong,['ruby'] +251793,read csv from within zip file i have a directory of zip files approximately 10 small files within each is a csv file i am trying to read and split into a number of different csv filesi managed to write the code to split the csv files from a directory of csvs shown below that reads the first atribute of the csv and depending what it is write it to the relevent csvimport csvimport osimport sysimport reimport globreader csvreaderopencprojectstestcsv rb delimiter quotecharwrite10 csvwriteropenouput10csv w delimiter lineterminatorn quotechar quotingcsvquote nonnumericwrite15 csvwriteropenouput15csv w delimiter lineterminatorn quotechar quotingcsvquote nonnumericheadings10record identifiercustodian namelocal custodian nameprocess datevolume numberentry datetime stampversionfile typewrite10writerowheadings10headings15record identifierchange typepro orderusrnstreet descriptionlocality nametown nameadminstrative arealanguagewrite15writerowheadings15for row in reader type row0 if 10 in type write10writerowrow elif 15 in type write15writerowrowso i am now trying to read the zip files rather than wasting time extracting them firstthis is what i have so far after following as many tutorials as i have foundimport globimport osimport csvimport zipfileimport stringiofor name in globglobcprojectsabasezip base ospathbasenamename filename ospathsplitextbase0datadirectory cprojectsabasedatafile filenamearchive joindatafile zipfullpath joindatadirectory archivecsv joindatafile csvfilehandle openfullpath rbzfile zipfilezipfilefilehandledata stringiostringiozfilereadcsvreader csvreaderdatafor row in reader print rowhowever and error gets thrown attributeerror str object has no attribute readerhopefully someone can show me how to change my csv reading code that works to read the zip filemuch appreciatedtim,['python'] +251800,how to add submenu items to actionbar action in code via xml i can add submenu items to my action in the actionbarmain menuxmlxml version10 encodingutf8menu xmlnsandroid item androidididmenu new form androidicondrawableic new form androidtitlestringmenu new form androidshowasactionifroomwithtext menu item androidididform1 androidicondrawableattachment androidtitleform 1 androidonclickonsort item androidididform2 androidicondrawableattachment androidtitleform 2 androidonclickonsort menu itemmenubut how can i add these sub items via java code it does not work as below the sub items are getting added to the wrong action and also the drawable is not shown the very right button not my new form buttonmain menuxmlxml version10 encodingutf8menu xmlnsandroid item androidididmenu new form androidicondrawableic new form androidtitlestringmenu new form androidshowasactionifroomwithtext itemmenujava codeoverridepublic boolean oncreateoptionsmenumenu menu superoncreateoptionsmenumenu menuinflater inflater getmenuinflater inflaterinflatermenumain menu menu logdmainmenu menu title0 menugetitem0gettitle returns new form menuaddsubmenu0 menunone 1 form 1seticonrdrawableattachment menuaddsubmenu0 menunone 2 form 2seticonrdrawableattachment return trueis there a way to achieve this adding sub menu items via java code instead of xml without using a popupmenu update solutionmy final code snippet i ended up with to populate the submenu dynamically following adamps reply menu optionsprivate static final int menu preferences menufirstprivate static final int menu logout 2overridepublic boolean oncreateoptionsmenufinal menu menu superoncreateoptionsmenumenu menuinflater inflater getmenuinflater inflaterinflatermenumain menu menu menuadd0 menu preferences 0 getstringrstringgeneral preferencesseticon androidrdrawableic menu preferences load all available form templates cursor c managedqueryformsproviderapiformscolumnscontent uri null null null null try int ixthisplayname cgetcolumnindexformsproviderapiformscolumnsthisplay name int ixid cgetcolumnindexformsproviderapiformscolumns id int cnt 0 while cmovetonext cnt logdid id cgetintixid misusing the group id for the form id menugetitem1getsubmenuaddsubmenucgetintixid menunone cnt cgetstringixthisplaynameseticonrdrawableattachment dark catch exception e logetag error init form templates list e return true,['android'] +251875,how to search for a javascript file in google so i recently launched a jquery plugin and people are downloading it but i am trying to figure out how i can tell where it is being used the only way i can think of is to try search for the js or css file somehow maybe the folder nameis there anyway to search for this,"['javascript', 'jquery']" +251888,where should i store the sqlite db for my iphone app i have several ios apps on the market and in all of them i have a small sqlite database file connected to the app to provide the user with my data once installed the user customizes this db by changing certain options until now all of these apps store the db in nsdocumentsdirectory after submitting my last update it was rejected for storing data in the wrong location for the apps rejected i changed the storage location to nscachesdirectory i am now afraid that the cache will get cleared and erase the users customizations the app would still function the db would get recreated but all changed tables would be reset thereby upsetting userswhere should this type of database file be stored was i right to put it in the docs dir according to apple the docs dir is for critical data which is either user generated data or data needed for proper operation of the app i feel that it falls under that category persisting my users settings is proper operation but who wants to await an appeal,"['ios', 'iphone']" +251920,whats the meaning of this usage of java generics i would like to know what the first t represents in the following line of java code i have read several tutorials on generics but none of the examples have 2 generics before the method name thankspublic t providert scopekeyt key providert unscoped,['java'] +251959,2d geometry library lgpl alternative to cgal cgal seems to do just about everything i need and a little more for my upcoming project it can create polygons out of arc line segments and run boolean operations on them it has spatial sorting packages already that would save me a lot of time regarding a few things and the whole library seems quite standardized and well plannedthere is just the issue with the license being qpl gpl for the upcoming version 40 for most of the packages except the very basic ones i have got a meager budget and can likely not gather funds to buy the commercial licenses for those specific packages in cgal that require itmy specific needs of such a library would beexact precision 2d euclidean spacecomplex polygonspolygons able to have curved line arc segmentsboolean operations on those polygonspolygon offsettingpolygon partitioning or effective triangulationinscribed area and polygon fitting algorithmspossibly some spatial sorting structures with circular range searchesall in all i am looking for a well rounded 2d geometry c library with exact precisionpreferably with mit lgpl at a stretch or a low cost onetime royaltyfree license below 500boost got some basic structures down but from what i can tell they lack a lot of the higher level functionality any libraries that has expanded on this i would consider doing it myself but i lack the expertise to do it well and it would prolong my project by quite a bitjust to be clear i am not looking for a 2d graphics library just pure geometry structures,['c++'] +251974,whats the difference between fseek lseek seekg seekp i was asked by an interviewer that how would i implement tail yes the one in linux shell my answer was first seek to the end of the file then read characters onebyone forward if encounters a n means one line is down blah blah blah i assume my answer is correctthen i found this problem which seek should i use to implement tail i thought i can simply use seekg c thing but i was told that i should use lseek linux system callso including fseek ansi c thing which one should i use to implement tailand is there any big difference between them,"['c++', 'c']" +251981,what resolution should a mobile website be optimized for i am having trouble understanding how the mobile resolution works from what i know standard website mobile resolution is 320px width the problem seems to be with iphone 4 which seems to have 640px width screen resolution but yet it thisplays web in 320pxwhat is the solution here do i code 2 different resolutions for 320px and 640px screens how do i force iphone 4 to thisplay 640px web,"['iphone', 'css']" +252015,denormalized floating point in objectivec what is the relevance of stack overflow questionanswer why does changing 01f to 0 slow down performance by 10x for objectivec if there is any relevance how should this change my coding habits is there some way to shut off denormalized floating points on mac os xit seems like this is completely irrelevant to ios is that correct,"['c++', 'objective-c']" +252112,character size in java vs c why does a character in java take twice as much space to store as a character in c,"['java', 'c']" +252132,how to get the value of a bit at a certain position from a byte if i have a byte how would the method look to retrieve a bit at a certain positionhere is what i have know and i do not think it workspublic byte getbitint position return byte id position 1where id is the name of the byte i am retrieving information from,['java'] +252135,javascript to active twitter bootstrap tooltips i am playing around with twitter bootstraps tooltips but am having problems since they moved away from twipsy the correect javascript is included in the pagelet us say i have the followingpa href reltooltip dataoriginaltitlehellohover on meapwhat is the exact javascript i need to use to make the tooltip appear thanks in advancevanessa,"['javascript', 'jquery']" +252148,sun codemodel generic method does anyone know to to generate the following generic method declaration using codemodelpublic t t getvalueclasst clazzusagevaluetype value getvaluevaluetypeclaseems not to be handled by the existing implmentationi know i could handle the code as follows but it requires a castpublic object getvalueclass classusagevaluetype value valuetypegetvaluevaluetypeclassobviously this is a bit messy because of the cast,['java'] +252150,xcode uiviewcontroller loadviewfromnibnamedbundle loaded the nib but the view outlet was not set error i am using xcode 4 and when i run my app the first screen does not load it fails in the simulators and on a device i have searched for answers and they all say to make sure i have dragged the circles in files owner to the correct views sorry i do not remember the names of the things i am new to xcode i have dragged the circles to the correct view and tried many things but none of them worked what could i be doing wronghere is the full error20120219 125954655 ponyboard271207 terminating app due to uncaught exception nsinternalinconsistencyexception reason uiviewcontroller loadviewfromnibnamedbundle loaded the ponyboardviewcontroller nib but the view outlet was not set call stack at first throw 0 corefoundation 0x00f095a9 exceptionpreprocess 185 1 libobjcadylib 0x0105d313 objc exception throw 44 2 corefoundation 0x00ec1ef8 nsexception raiseformatarguments 136 3 corefoundation 0x00ec1e6a nsexception raiseformat 58 4 uikit 0x0020d709 uiviewcontroller loadviewfromnibnamedbundle 295 5 uikit 0x0020b134 uiviewcontroller loadview 120 6 uikit 0x0020b00e uiviewcontroller view 56 7 uikit 0x0017ed42 uiwindow addrootviewcontrollerviewifpossible 51 8 ponyboard 0x02a87 ponyboardappdelegate applicationdidfinishlaunchingwithoptions 135 9 uikit 0x0015bc89 uiapplication callinitializationdelegatesforurlpayloadsuspended 1163 10 uikit 0x0015dd88 uiapplication runwithurlpayloadlaunchorientationstatusbarstylestatusbarhidden 439 11 uikit 0x00168617 uiapplication handleeventwithnewevent 1533 12 uikit 0x00160abf uiapplication sendevent 71 13 uikit 0x00165f2e uiapplicationhandleevent 7576 14 graphicsservices 0x031fd992 purpleeventcallback 1550 15 corefoundation 0x00eea944 cfrunloop is calling out to a source1 perform function 52 16 corefoundation 0x00e4acf7 cfrunloopdosource1 215 17 corefoundation 0x00e47f83 cfrunlooprun 979 18 corefoundation 0x00e47840 cfrunlooprunspecific 208 19 corefoundation 0x00e47761 cfrunloopruninmode 97 20 uikit 0x0015d7d2 uiapplication run 623 21 uikit 0x00169c93 uiapplicationmain 1160 22 ponyboard 0x029c9 main 121 23 ponyboard 0x02945 start 53terminate called after throwing an instance of nsexception,['iphone'] +252175,jdbc realm with glassfish v3 realm properties and configuration error i have the following database schema mysqlmy login is a form based authentication system to which i am trying to create a jdbc realmmy webxml loginconfig authmethodformauthmethod realmnameemdjdbcrealmrealmname formloginconfig formloginpageindexjspformloginpage formerrorpagewebinfloginerrorjspformerrorpage formloginconfigloginconfigsecurityconstraint webresourcecollection webresourcenamelogin pagewebresourcename urlpatternurlpattern webresourcecollection authconstraint rolenameadmrolename rolenameusrrolename authconstraint userdataconstraint transportguaranteeconfidentialtransportguarantee userdataconstraintsecurityconstraintsecurityrole description rolenameusrrolenamesecurityrolesecurityrole description rolenameadmrolenamesecurityroleand the mappings in sunwebxmlsecurityrolemapping rolenameadmrolename groupnameadmgroupnamesecurityrolemappingsecurityrolemapping rolenameusrrolename groupnameusrgroupnamesecurityrolemappingi do not know why but it is not working for me i get the following fine cannot load group commysqljdbcexceptionsjdbc4mysqlsyntaxerrorexception unknown column group name in field list at sunreflectnativeconstructoraccessorimplnewinstance0native method at sunreflectnativeconstructoraccessorimplnewinstancenativeconstructoraccessorimpljava39 at sunreflectdelegatingconstructoraccessorimplnewinstancedelegatingconstructoraccessorimpljava27 at javalangreflectconstructornewinstanceconstructorjava513 at commysqljdbcutilhandlenewinstanceutiljava407 at commysqljdbcutilgetinstanceutiljava382 at commysqljdbcsqlerrorcreatesqlexceptionsqlerrorjava1052 at commysqljdbcmysqliocheckerrorpacketmysqliojava3603 at commysqljdbcmysqliocheckerrorpacketmysqliojava3535 at commysqljdbcmysqliosendcommandmysqliojava1989 at commysqljdbcmysqliosqlquerydirectmysqliojava2150 at commysqljdbcconnectionimplexecsqlconnectionimpljava2626 at commysqljdbcpreparedstatementexecuteinternalpreparedstatementjava2119 at commysqljdbcpreparedstatementexecutequerypreparedstatementjava2281 at comsungjcspijdbc40preparedstatementwrapper40executequerypreparedstatementwrapper40java641 at comsunenterprisesecurityauthrealmjdbcjdbcrealmfindgroupsjdbcrealmjava480 at comsunenterprisesecurityauthrealmjdbcjdbcrealmauthenticatejdbcrealmjava312 at comsunenterprisesecurityauthloginjdbcloginmoduleauthenticatejdbcloginmodulejava72 at comsunenterprisesecurityauthloginpasswordloginmoduleauthenticateuserpasswordloginmodulejava90 at comsunappservsecurityappservpasswordloginmoduleloginappservpasswordloginmodulejava141 at sunreflectgeneratedmethodaccessor209invokeunknown source at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava25 at javalangreflectmethodinvokemethodjava597 at javaxsecurityauthloginlogincontextinvokelogincontextjava769 at javaxsecurityauthloginlogincontextaccess0logincontextjava186 at javaxsecurityauthloginlogincontext4runlogincontextjava683 at javasecurityaccesscontrollerdoprivilegednative method at javaxsecurityauthloginlogincontextinvokeprivlogincontextjava680 at javaxsecurityauthloginlogincontextloginlogincontextjava579 at comsunenterprisesecurityauthloginlogincontextdriverdopasswordloginlogincontextdriverjava341 at comsunenterprisesecurityauthloginlogincontextdriverloginlogincontextdriverjava199 at comsunenterprisesecurityauthloginlogincontextdriverloginlogincontextdriverjava152 at comsunwebsecurityrealmadapterauthenticaterealmadapterjava479 at comsunwebsecurityrealmadapterauthenticaterealmadapterjava418 at orgapachecatalinaauthenticatorformauthenticatorauthenticateformauthenticatorjava264 at orgapachecatalinaauthenticatorauthenticatorbaseprocesecuritycheckauthenticatorbasejava1015 at orgapachecatalinaauthenticatorauthenticatorbaseinvokeauthenticatorbasejava614 at orgapachecatalinacorestandardpipelineinvokestandardpipelinejava615 at comsunenterprisewebwebpipelineinvokewebpipelinejava97 at comsunenterprisewebpesessionlockingstandardpipelineinvokepesessionlockingstandardpipelinejava85 at orgapachecatalinacorestandardhostvalveinvokestandardhostvalvejava185 at orgapachecatalinaconnectorcoyoteadapterdoservicecoyoteadapterjava325 at orgapachecatalinaconnectorcoyoteadapterservicecoyoteadapterjava226 at comsunenterprisev3servicesimplcontainermapperservicecontainermapperjava165 at comsungrizzlyhttpprocessortaskinvokeadapterprocessortaskjava791 at comsungrizzlyhttpprocessortaskdoprocessprocessortaskjava693 at comsungrizzlyhttpprocessortaskprocessprocessortaskjava954 at comsungrizzlyhttpdefaultprotocolfilterexecutedefaultprotocolfilterjava170 at comsungrizzlydefaultprotocolchainexecuteprotocolfilterdefaultprotocolchainjava135 at comsungrizzlydefaultprotocolchainexecutedefaultprotocolchainjava102 at comsungrizzlydefaultprotocolchainexecutedefaultprotocolchainjava88 at comsungrizzlyhttphttpprotocolchainexecutehttpprotocolchainjava76 at comsungrizzlyprotocolchaincontexttaskdocallprotocolchaincontexttaskjava53 at comsungrizzlyselectionkeycontexttaskcallselectionkeycontexttaskjava57 at comsungrizzlycontexttaskruncontexttaskjava69 at comsungrizzlyutilabstractthreadpoolworkerdoworkabstractthreadpooljava330 at comsungrizzlyutilabstractthreadpoolworkerrunabstractthreadpooljava309 at javalangthreadrunthreadjava619 fine jaas authentication aborted finest dopasswordlogin fails javaxsecurityauthloginloginexception security exception at javaxsecurityauthloginlogincontextinvokelogincontextjava856 at javaxsecurityauthloginlogincontextaccess0logincontextjava186 at javaxsecurityauthloginlogincontext4runlogincontextjava683 at javasecurityaccesscontrollerdoprivilegednative method at javaxsecurityauthloginlogincontextinvokeprivlogincontextjava680 at javaxsecurityauthloginlogincontextloginlogincontextjava579 at comsunenterprisesecurityauthloginlogincontextdriverdopasswordloginlogincontextdriverjava341 at comsunenterprisesecurityauthloginlogincontextdriverloginlogincontextdriverjava199 at comsunenterprisesecurityauthloginlogincontextdriverloginlogincontextdriverjava152 at comsunwebsecurityrealmadapterauthenticaterealmadapterjava479 at comsunwebsecurityrealmadapterauthenticaterealmadapterjava418 at orgapachecatalinaauthenticatorformauthenticatorauthenticateformauthenticatorjava264 at orgapachecatalinaauthenticatorauthenticatorbaseprocesecuritycheckauthenticatorbasejava1015 at orgapachecatalinaauthenticatorauthenticatorbaseinvokeauthenticatorbasejava614 at orgapachecatalinacorestandardpipelineinvokestandardpipelinejava615 at comsunenterprisewebwebpipelineinvokewebpipelinejava97 at comsunenterprisewebpesessionlockingstandardpipelineinvokepesessionlockingstandardpipelinejava85 at orgapachecatalinacorestandardhostvalveinvokestandardhostvalvejava185 at orgapachecatalinaconnectorcoyoteadapterdoservicecoyoteadapterjava325 at orgapachecatalinaconnectorcoyoteadapterservicecoyoteadapterjava226 at comsunenterprisev3servicesimplcontainermapperservicecontainermapperjava165 at comsungrizzlyhttpprocessortaskinvokeadapterprocessortaskjava791 at comsungrizzlyhttpprocessortaskdoprocessprocessortaskjava693 at comsungrizzlyhttpprocessortaskprocessprocessortaskjava954 at comsungrizzlyhttpdefaultprotocolfilterexecutedefaultprotocolfilterjava170 at comsungrizzlydefaultprotocolchainexecuteprotocolfilterdefaultprotocolchainjava135 at comsungrizzlydefaultprotocolchainexecutedefaultprotocolchainjava102 at comsungrizzlydefaultprotocolchainexecutedefaultprotocolchainjava88 at comsungrizzlyhttphttpprotocolchainexecutehttpprotocolchainjava76 at comsungrizzlyprotocolchaincontexttaskdocallprotocolchaincontexttaskjava53 at comsungrizzlyselectionkeycontexttaskcallselectionkeycontexttaskjava57 at comsungrizzlycontexttaskruncontexttaskjava69 at comsungrizzlyutilabstractthreadpoolworkerdoworkabstractthreadpooljava330 at comsungrizzlyutilabstractthreadpoolworkerrunabstractthreadpooljava309 at javalangthreadrunthreadjava619 caused by javalangsecurityexception at javaxsecurityauthloginlogincontextinvokelogincontextjava857 34 more warning web login failed login failed javaxsecurityauthloginloginexception security exceptionam i putting the accurate properties based on the database schema that i have i would appreciate your help because i could not understand what i am doing wrong updatethis if for anyone who has the same scenariobased on perissf glassfish jdbc realm does not support normalized tables check perissfs link for a tutorial on how should the schema behowever what i did isi kept the normalized schema and created a mysql view that contains all required columns ie columns username pass group nameand i modified the jdbc properties as followthe reason behind using a view is that as matt handy said jdbcrealm requires that the user name column name needs to be the same in the user table and in the group tableso this creates duplicate data in my case thus i used a view,['mysql'] +252179,alternatives to python pastescripts paster create it seems like pastescripts paster create functionality is just about the only widely used framework for buildinggenerating a project skeleton within python i am wondering if there are any alternatives in the python world that folks useupdatei want to comment on my experience since originally asking this question the accepted answer still stands there are a number of templatingskeleton packages out there one could use however from the other answers given i did start to use mrbob and have checked out cookiecutter both are generic as in not bound to a particular framework easy to use and relatively current and active projects which were part of the criteria i was looking for but did not detail in my original question,['python'] +252191,int main vs void main in c in c i know that int main returns an int where void main does not other than that is there a difference between them is first better than second,['c'] +252219,how typedef works for function pointers i think i may be suffering from the dreaded accidental programmer thisease at least when it comes to typedefs and function pointers so i have been experimenting with all kinds of combinations involving these to analyse the results based on all the output i get but as i kept on trying different combinations instead of analyzing the results i am now just lost in process i am hoping you guys will help me figure out this messfirst code exampletypedef void printvoidvoid do something void printfhello worldn print prpr do somethingpr hello worldsecond code exampletypedef void printvoidvoid do something void printfhello worldn print prpr do somethingpr hello worldhow do both the above code examples work it is as if has no effect on function namethird code exampletypedef void printvoidvoid do something void printfhello worldn print prpr do something compile errorpr do something compile errorpri was hoping one of the above assignments to work here but damn i really do not understand function pointers and maybe typedef too,"['c++', 'c']" +252232,how i can find function in shared object files using objdump and bash functions in linux i have got a folder in linux which is contained several shared object files so how i can find function in shared object files using objdump and bash functions in linuxfor instance the following example is found me function func1 in mylibsoobjdump d mylibso grep func1but i want to find func1 in folder which is contained shared object files i do not know bash language and how to combinate linux terminal commands,['c'] +252250,making a control transparent i am currently developing a simple image editing tool using winforms and net 35 work environmenti have a requirement that when the user clicks a select tool button a square rectangle in c will appear that they can scale between 100x100 and 400x400 i have this bit fixed the issue comes with making the background of the rectangle transparenti am a little unclear on if transparency is supported in net 35 i have tried the followingsetstylecontrolstylessupportstransparentbackcolor truepnlselectareabackcolor colortransparentpnlselectareaforecolor colortransparentselectarea1backcolor colortransparentselectarea1forecolor colortransparentbut this has no effect any advice would be appreciated,['c#'] +252251,rails nested attributes children callbacks are not fired i am running into a bizarre issue where children callbacks are not fired when the parent is updatedi have the following model setupclass budget activerecordbase has many line items accepts nested attributes for line itemsend class lineitem activerecordbase belongs to budget before save update totals private def update totals selfsome field value endendin my form i have the fields nested built using fields for form for budget do f ftext field name ffields for line items do ff fftext field amountwhy is the update totals callback on the child never fired what can i do to make it fire,['ruby-on-rails'] +252305,how to make a lib file when have a dll file and a header file i am trying to create an application in visual studio that will be able to access a dll file that already exists i need the application to call up routines i also have a header file that already existsi have been researching on the internet and have found that i need to create a lib file looking at similar questions on here i found a link i cannot however follow the directionsthe information in the link says to make a def file i read elsewhere that this needs to be compiled as a dll with the same name but not sure what that name is the same name as the dll file but i do not understand the first direction to use dumpbin exports i then need to stub out functions and then something to do with obj files i do not know what these files areare there any stepbystep directions similar to the link above that are easy to follow,['c++'] +252320,postfix label text with colon i use aspnet mvc 3 for my forms i align the labels text to the right also there is a colon between the label and the input field firstname last can i automatically insert this colon using css or some c code in mvc 3 the best thing i came up with so far is to use the thisplaynamefirstname attribute but this has the side effect of also including this colon in validation messagesrequiredthisplayname firstnamestringlength100 errormessage the 0 must be at least 2 character long minimumlength 1public string firstname get set the other alternative was to use the labelfor method overload but this forces me to specify the label text twice once in the model and once in cshtml filediv div classeditorlabelhtmllabelforx xfirstname firstnamediv div classeditorfieldhtmltextboxforx xfirstnamedivdivany better suggestions,['css'] +252344,update mysql version from 51 to 55 in centos 62 i tried to update mysql from 51 to 55 in centos 62 the following is the process i did1 rpm uvh 2 yum install libmysqlclient15 enablerepowebtatic3 yum remove mysql mysql4 yum install mysql55 mysql55server enablerepowebtaticwhen i tried the 4th step i got the following outputrootd2005 yum install mysql55 mysql55server enablerepowebtaticfailed to set locale defaulting to cloaded plugins fastestmirror prestoloading mirror speeds from cached hostfile base yumsinglehopcom extras centosmirrorstdsnet updates pubmirrorsreflectednetsetting up install processresolving dependencies running transaction check package mysql55x86 64 055101w5 will be installed processing dependency mysql55libs 55101w5 for package mysql5101w5x86 64 package mysql55serverx86 64 055101w5 will be installed processing dependency perldbdmysql for package mysql55server55101w5x86 64 running transaction check package mysql55libsx86 64 055101w5 will be installed package perldbdmysqlx86 64 040133el6 will be installed processing dependency libmysqlclientso16libmysqlclient 1664bit for package perldbdmysql40133el6x86 64 processing dependency libmysqlclientso1664bit for package perldbdmysql40133el6x86 64 running transaction check package mysqllibsx86 64 051611el6 21 will be installed processing conflict mysql55libs55101w5x86 64 conflicts mysqllibs 5510 finished dependency resolutionerror mysql55libs conflicts with mysqllibs you could try using skipbroken to work around the problem you could try running rpm va nofiles nodigesthow to fix it,['mysql'] +252347,android how to get accurate altitude i need to get an accurate measurement of altitude using gps onlyi tried locationgetaltitude but that is terribly inaccurateany advice,['android'] +252353,making html content unbreakable in one line i have a line made of inputs and spans which should represent a phone number inserting it into a table with some columns with content causes the line to breakthe last input is pushed into the next line one way to fix this could be setting a fixed td width or minwidth however for the sake of any future projects i would like to know is there a way to make the html content unbreakable without touching the td width thanks for any info,"['html', 'css']" +252371,what is the best practice organize a jquery mobile application i have found article that skims over this but my main question is do i need a separate html file for each screen i am thinking yes but i would like an unanimous vote also does that go for separate js files tooedit jqm app is basically to admin users and roles,['jquery'] +252377,how to associate iphone application with every file type there is iphone app another mail client that should be able to open any file to send it as attachment so i want to associate this application with any file with any extensionfollowing the documentation we should declare support for files with the root utitype publicdata a any file should belong to this type it works but not at all in this case our app will not be able to open any file but only those which have already been registered in the system for example if in any application eg dropbox well try to open in file with an unknown extension fileunknowntype using uidocumentinteractioncontroller then the answer will be negative despite the fact that we have already registered our application and it supports the root utitype publicdata but if you install another application which supports files with extension unknowntype then our application will also be able to open these files and will appear in open in application listupd gabriel this is cfbundledocumenttypes part of my infoplist filekeycfbundledocumenttypeskeyarray dict keycfbundletypenamekey stringmymailstring keylsitemcontenttypeskey array stringpublicdatastring array keycfbundletyperolekey stringviewerstring keylshandlerrankkey stringdefaultstring keycfbundletypeiconfileskey array stringicon29pngstring stringicon114pngstring array dictarray,"['iphone', 'objective-c', 'ios']" +252379,serverside highstock charts generation with nodejs i am using highstock to generate some charts in browser but now i want to store some of them at the server so i know that highcharts can be exported to the server but i would rather use some other way if possible the thing is to run highstock at the server and convert the svg to some image format and then store it therequick googling gives me this page combining highcharts and nodejs seems to be the right way but this solution does not work for newer versions of highcharts more precisely using jsdom module v0210 the latest in nodejs with highstock v102 look at the following codevar jsdom requirejsdomvar fs requirefsvar jquery fsreadfilesyncjsjquery17minjstostringvar highstock fsreadfilesyncjshighstockjstostringjsdomenv html div idcontainerdiv src jquery highstock done functionerrors window if errors return consolelogerrors var highcharts windowhighcharts var chart new highchartschartoptions throws an exceptionerror invalid character invalid character in tag name somehow these two libraries does not seem to work together so this may work with older versions of highstock but actually i need highstock v102is there any solution for this problem some better library that jsdom or some strange yet working tricks any idea appreciated edit thanks to recoder i have managed to get it working main thing was to add forexport flag to the options preventing exceptions unfortunetly this generated the chart but did not update the holder i have managed to get it working after adding exporting module part of highstock package the full working code looks like thisvar jsdom requirejsdomvar fs requirefsvar jquery fsreadfilesyncjsjquery17minjstostringvar highstock fsreadfilesyncjshighstocksrcjstostringvar exporting fsreadfilesyncjsexportingsrcjstostringjsdomenv html div idcontainerdiv src jquery highstock exporting done functionerrors window if errors return consolelogerrors var highcharts windowhighcharts var chart new highchartschart chart renderto container animation false forexport true exporting enabled false xaxis categories jan feb mar apr may jun jul aug sep oct nov dec series animation false name tokyo data 70 69 95 145 182 215 252 265 233 183 139 96 animation false name new york data 02 08 57 113 170 220 248 241 201 141 86 25 animation false name berlin data 09 06 35 84 135 170 186 179 143 90 39 10 animation false name london data 39 42 57 85 119 152 170 166 142 103 66 48 var svg chartgetsvg fswritefiletestsvg svg functionerr iferr consolelogerr else consolelogthe file was saved the chart is not as good as it should be for example labels badly placed but maybe it is a matter of tuning options at least it works,['javascript'] +252383,how to select not first tr and not last td cssmytable trtrhover background dfdfdfhtmltable idmytable tr tdatd tdbtd tdctd tr tr td1td td2td tdxtd tr tr td3td td4td tdxtd trtablei managed to hover row 2 and 3 but while hover on 2 and 3 how can i skip the td x preferable not using jquery selector,['css'] +252416,301 or 302 redirection with php i am considering using the following code during a website launch phase to show users a down for maintenance page while showing me the rest of the site is there a way to show the correct 302 redirection status to search engines or should i look for another htaccess based approachvisitor serverremote addrif preg match19216801visitor headerlocation else headerlocation,['php'] +252430,openlayers write and save a kml based on your map is it possible to write and save a kml from openlayers anyone know of an example of exporting one,['javascript'] +252436,cleanly bindingunbinding to a service in an application i have an android application that is binding to a persistent service once started with startservicethe service is an integral part of the application and thus is used in almost every activity hence i want to bind to the service just once instead of bindingunbinding in every activity and keep the binding during the lifetime of my applicationi have extended from application and bind to the service in applicationoncreate however i now have the problem that i do not know when my application exists since applicationonterminate is never called see javadocthis method is for use in emulated process environments it will never be called on a production android device where processes are removed by simply killing them no user code including this callback is executed when doing soso how do i cleanly unbind from a service bound in application,['android'] +252442,remove not alphanumeric characters from string having trouble with the character i want to convert the following string to the provided output input testredbobfrednewoutput testredbobfrednewi have not found any solution that will handle special characters like r n b etcbasically i just want to get rid of anything that is not alphanumeric here is what i have triedattempt 1 testredbobfrednewreplace wg output 1 testedobredewattempt 2 testredbobfrednewreplace gi output 2 testedobred newline ewattempt 3 testredbobfrednewreplaceazaz09 output 3 testedobred newline ewattempt 4 testredbobfrednewreplaceaz09sgi output 4 testedobred newline ewone other attempt with multiple stepsfunction cleanidid id idtouppercase id idreplace t t id idreplace n n id idreplace r r id idreplace b b id idreplace f f return idreplace azaz09 with resultsattempt 1 cleanidtestredbobfrednewoutput 1 btestredobfrednewany help would be appreciatedworking solutionfinal attempt 1 return jsonstringifytestredbobfrednewreplace wg output 1 testredbobfrednew,['javascript'] +252443,fork and output i have a simple programint main stdcout hello world forkafter the program executes my output is hello world hello world why does this happen instead of a single hello world i am guessing that the child process is rerun behind the scenes and the output buffer is shared between the processes or something along those lines but is that the case or is something else happening,['c++'] +252455,entity framework 43 does not create database i created new project and added the newest entity framework to it version 43 i created classes and the context as in previous ef versions however during the very first run when the database should be created in my case it is sql server 2005 i am receiving the following erroran error occurred while executing the command definition see the inner exception for detailswith the following inner exceptioninvalid object name dbo migrationhistoryas i understand this table is for migrations but this table does not exist if there is no database am i doing something wrongmore infofor testing purposes i created only one classpublic class test key public int testid get set public string name get setpublic class context dbcontext public context basemyconnection public dbsettest tests get setupdate 1after some tests i realized that application is throwing unhandled exception from visual studio and break in visual studio the exception was systemdataentitycommandexecutionexception once i ignored that expection and did not stop code execution database was createdupdate 2after another few hours working with database i found out that playing with enablemigrations option and updatedatabase from console also is solving that issue it is creating database before application start and do not break in visual studio,"['c#', '.net']" +252465,php is locking a deleted session file our php app running under apache is occaisionally trying to lock a deleted session file this hangs the apache process and eventually we run out of processesthe evidence strace flock89 lock ex stuck in flock for file descriptor 89and then lsof for the same process httpd 22161 apache 89u varlibphpsessionsess mf7svvirg7rbu9l0m59pm6h4 deletedany ideas as to why this is occurring and what we could do to prevent it,['php'] +252496,android round to 2 decimal places possible duplicateround a double to 2 significant figures after decimal point i know that there are plenty of examples on how to round this kind numbersbut could someone show me how to round double to get value that i can thisplay as a string and always have 2 decimal places,['android'] +252500,service account google analytics oauth accesstype offline c i have got credentials of an account with access to google analyticsi am looking to utilise the analytics core reporting api i have found examples which use usernamepassword calling setusercredentials but have seen comments this is less securehas a low request limit and does not exist in the lastest clientplus i have seem examples which use oauth but require user interaction and grant access to the users google accounthowever i am looking to run a service which does not require any user interaction and connects to a predefined google account unrelated to the user viewing iti can then store the results in a database and end users can query the results from the databasei have seen information about using accesstype offline when you first login which then returns an access token and a refreshtokenin my example though the end user will never login to the application could i have a seperate admin application which gets a refresh token and stores the refresh token in the configlookup tablethen the main application can use the refresh token pulling from the configlookup table and get an access token to be able to query the google analytics accounti am looking for a c example which uses accesstype offline and seperates out the fetching of the refresh token and using the refresh token to get an access token to query the google analytics account,"['c#', 'asp.net']" +252510,divide a string at first space for a chatbot if someone says say it will recite what you say after the space simpleexample inputsay this is a testdesired outputthis is a testthe string can be represented as s for sake of argument ssplit yields an arrayssplit 1 is just the first word after the space any ideas on completely dividing and getting all words after the first spacei have tried something along the lines of thisplit for int i 0 i slength i if si say si the input beingsay this is a testthe outputsaywhich is obviously not what i wanted pi know there are several answers to this question but none written in c from where i searched,['c#'] +252521,understanding the zend framework bootstrap process and resource loading from applicationini i am pretty familiar with zend framework details and how most things work one area that i still do not fully understand is the way zend framework loads resources from applicationinii understand i can create my own protected init functions and these will be called automatically during bootstrapthe zend framework documentation is lacking in certain areasfor example how and when does the resourcesdb config options get loaded i have nothing in my bootstrap that talks about db does this get loaded on demand or actually during the bootstrap processany links of references explaining this would be very helpful,['php'] +252536,how do i check if array value is empty here is my array ouputarray 1 1 2 2 3 how do i know the 3 is emptyforeach array as key value if emptyvalue echo key empty br else echo key not empty brmy out put showing all is not empty what is correct way to check is empty,['php'] +252539,custom uiscrollview paging with scrollviewwillenddragging i am trying to use the new scrollviewwillenddraggingwithvelocitytargetcontentoffset uiscrollview delegate call in ios 5 but i cannot seem to get it to actually respond to me correctly i am changing the targetcontentoffsetx value but it never ends up being used i know the code is being ran because it will hit breakpoints in that function i have even tried setting the offset value to a hard coded number so i would know where it would end up but it never workshas anyone been able to use this correctly and make it work is there any other delegate call that must be implemented in order for this to workheres my code in case someone sees something wrong with it voidscrollviewwillenddragginguiscrollview scrollview withvelocitycgpointvelocity targetcontentoffsetinout cgpoint targetcontentoffset goodoffsetx returns the contentoffset i want the scrollview to stop at cgfloat goodoffsetx self horizontalcontentoffsetfortargethorizontalcontentoffsettargetcontentoffsetx velocityvelocityx nslog nslog scrollviewwillenddragging nslog velocity f velocityx nslog currentx f scrollviewcontentoffsetx nslog uikit targetx f targetcontentoffsetx nslog pagedx f goodoffsetx targetcontentoffsetx goodoffsetx,['ios'] +252540,are static methods a di antipattern i am a java developer who is beginning to grasp the full power of dependency injections and it suddenly dawned on me that there is no way to inject a static method so it got me thinking are static methods di antipatternsmore importantly if i were to embrace dependency injection does this mean i need to stop coding static methods i ask because there is no way to mock them and inject mock statics during unit tests which is a huge turnoff for meedit i know that a common way to wrap and inject an existing static method is like thispublic class foo public static void bar public interface foowrapper public void barpublic class foowrapperimpl implements foowrapper public void bar return foobar but i am not asking how to inject an existing static methodi am asking if i should stop writing them altogether if all my code from this point forward is going to embrace the notion of dialso i see a lot of similarlyrelated questions to this but could not find an exact match that asked this same question if you see that it is indeed a dupe of another question please point it out to me and i will close this question myself please do not just closevote it,['java'] +252544,wix 35 install features based on checkboxes i am trying to make it so that when the user selects something via check box a corresponding feature will be installed i am aware of the prebuilt feature tree that wix provides but there are some other things that i am doing that do not allow me to use this function i am curious as to how to link the two together so that when the user selects the check box install feature x feature x is installed when the user clicks the install buttonany advice would be greatly appreciated,['c#'] +252580,calculating the size of an sprintf buffer a very long while ago i regularly used the following code then on msvc 6 to determine the memory needed to format a string for a function with variadic argumentsvoid logprintconst char pszformat int nbytes char pszbuffer va list args va startargs pszformat nbytes vsnprintf0 0 pszformat va va endargs error checking omitted for brevity pszbuffer new charnbytes 1 va startargs pszformat vsnprintfpszbuffer nbytes pszformat va va end the obvious error youre getting in a more recent version of msvc i am using 2010 now iswarning c4996 vsnprintf this function or variable may be unsafe consider using vsnprintf s instead to thisable deprecation use crt secure no warnings see online help for detailsi am a big fan of the treat warnings as errors option for any ccompiler and obviously my build fails it feels like cheating to me to simply employ pragma warning thisable4996 and get on with itthe suggested safer alternative vsnprintf s however is doomed to return 1 when input conditions of its unsafe predecessor occurtldr is there a way to implement the expected behavior of vsnprintf to return the memory needed to fulfil its task using the new safer variants of itedit simply defining crt secure no warnings would not cut it there is a lot of strcpy flying around too the new variant of which is not broken so i would like to still see these,['c++'] +252600,access global mochajs functions when using requirejs i am including mochajs with the excellent use shim for a requirejsbased sitehow do i access the define and it bdd functions declared by mocha when using requirejshere is a basic code exampletestjsvar mocha requireusemocha testfile requiretestfilejsmochasetupbddmocharuntestfilejsdefinefunctionrequire describe and it are not available describebook function itshould have pages function i get the error uncaught referenceerror describe is not defined when running in the browseri have tried windowdescribe and tried moving the requiretestfilejs to after the mochasetupbdd i know i am missing something probably passing the context to mocha somehow,['javascript'] +252603,how to use signalr with net 35 i would like to build a winform business solution using siganlr but i am not able to install net 40 on the client machine it looks like signalr has a mininum requirement of net 40 what is the best way to use signalr from a winform and net 35 i would like to include the sendreceive message functions in the client application i will be hosting signalr on iis on my intranet using net 40 on the server sidewould it be possible to create and api in net 35 similar to pubnub c can anyone point me in the right direction,"['c#', '.net']" +252606,debugwriteline shows nothing when usingusing systemdiagnosticsanddebugwritelinetesthaving run the application no test can be seen in output but if i use the msgbox function instead the msgbox pops up so the line is reachedam i looking in the wrong window or what do i have to changei am using vc express,['c#'] +252631,strtok on 64 bit machines the following code works differently on 64 bit and on 32 bit which is causing me trouble to port my code char tmp how are youprintfsize of char ld and size of strtok return val ld nsizeofchar sizeofstrtoktmp following is the output 32 bit size of char 4 and size of strtok return val 4 64 bitsize of char 8 and size of strtok return val 4the man page of strtok says include stringh char strtokchar str const char delimreturn value the strtok and strtok r functions return a pointer to the next token or null if there are no more tokensthe char on a 64 bit machine is supposed to be 8 bytes as printed so why is strtok returning a 4 bytes char pointer on a 64 bit machine thanks,['c'] +252636,should overload resolution select private methods consider this codeclass foo public void doitstring strs systemoutprintlnthis is varargs private void doitstring str systemoutprintlnthis is single class bar public static void main string args new foodoit with javac version 160 29 it fails to compile statingvarargserrorjava14 doitjavalangstring has private access in foo new foodoit 1 erroryes this is silly code and there are at least two obvious workarounds but i am curious based on section 15122 of the specification this compilation error seems like a bug in javac because the first step should remove the nonvarargs doit as it is inaccessible according to section 661 am i missing some other details in the lookup algorithm or is this as obviously wrong as i think it is,['java'] +252643,capistrano no such file to load deploy when i try to run any cap commands i get a no such file to load deploy errorhere is the outputtylersmacbookprocap app tyler cap tuserstylerrvmrubiesruby192p290librubysite ruby191rubygemscustom requirerb36in require no such file to load deploy loaderrorfrom userstylerrvmrubiesruby192p290librubysite ruby191rubygemscustom requirerb36in requirefrom userstylerrvmgemsruby192p290gemscapistrano2110libcapistranoconfigurationloadingrb152in requirefrom capfile1in loadfrom userstylerrvmgemsruby192p290gemscapistrano2110libcapistranoconfigurationloadingrb93in instance evalfrom userstylerrvmgemsruby192p290gemscapistrano2110libcapistranoconfigurationloadingrb93in loadfrom userstylerrvmgemsruby192p290gemscapistrano2110libcapistranoconfigurationloadingrb172in load from filefrom userstylerrvmgemsruby192p290gemscapistrano2110libcapistranoconfigurationloadingrb89in loadfrom userstylerrvmgemsruby192p290gemscapistrano2110libcapistranoconfigurationloadingrb86in block in loadfrom userstylerrvmgemsruby192p290gemscapistrano2110libcapistranoconfigurationloadingrb86in eachfrom userstylerrvmgemsruby192p290gemscapistrano2110libcapistranoconfigurationloadingrb86in loadfrom userstylerrvmgemsruby192p290gemscapistrano2110libcapistranocliexecuterb65in block in load recipesfrom userstylerrvmgemsruby192p290gemscapistrano2110libcapistranocliexecuterb65in eachfrom userstylerrvmgemsruby192p290gemscapistrano2110libcapistranocliexecuterb65in load recipesfrom userstylerrvmgemsruby192p290gemscapistrano2110libcapistranocliexecuterb31in executefrom userstylerrvmgemsruby192p290gemscapistrano2110libcapistranocliexecuterb14in executefrom userstylerrvmgemsruby192p290gemscapistrano2110bincap4in top requiredfrom userstylerrvmgemsruby192p290bincap19in loadfrom userstylerrvmgemsruby192p290bincap19in mainhere is the gemfilesource gem rails 321 bundle edge rails instead gem rails git gitgithubcomrailsrailsgitgem sqlite3gem capistrano gems used only for assets and not required in production environments by defaultgroup assets do gem sassrails 323 gem coffeerails 321 see for more supported runtimes gem therubyracer gem uglifier 103endgem jqueryrails to use activemodel has secure password gem bcryptruby 300 to use jbuilder templates for json gem jbuilder use unicorn as the web server gem unicorn deploy with capistrano gem capistrano to use debugger gem rubydebug19 require rubydebugconfigdeployrbrequire bundlercapistranoset application capistranoapp set repository sshprojectdirgitset applicationdir varwapplicationset domain rorweaponxocomset scm gitset branch masterset git shallow clone 1set scm verbose true or accurev bzr cvs darcs git mercurial perforce subversion or nonerole web domain your http server apacheetcrole app domain this may be the same as your web serverrole db domain primary true this is where rails migrations will runset deploy to applicationdirset deploy via remote cache if youre still using the scriptreaper helper you will need these process scripts if you are using passenger mod rails uncomment this namespace deploy do task start do end task stop do end task restart roles app except no release true do run try sudo touch filejoincurrent pathtmprestarttxt end endcapfilerequire deploy uncomment if you are using rails asset pipeline load deployassetsdirvendorgemsrecipesrbvendorpluginsrecipesrbeach plugin loadplugin load configdeploy remove this line to skip loading any of the default tasksi am guessing the deploy is the reference to require deploy from the capfilewhat did i mess upthankseditchanging the first line of the capfile to load deploy if respond tonamespace cap2 differentiatorworks any idea why the capfile ships by default with this broken line in it do i need to do something different than capify,['ruby-on-rails'] +252667,how to add a class to the input component in a wrapper in simple form 2 i am trying to have classtext in my input fields when using a custom wrapper called hinted in simple form 200rcconfigwrappers hinted do b buse input class textendbut the output does not have that class i tried wrap with class text to no availdoes anyone know how this is donethank you,['ruby-on-rails'] +252676,is it possible to create my own unchecked exception in java is it possible to create my own unchecked exception in javabasically i would like tohave my own exception class myuncheckedexceptionthat does not make me update all methods that call the method that throws this exception with a flood of own throws,['java'] +252696,intparse input string was not in a correct format how would i parse an empty string intparsetextbox1text gives me an error input string was not in a correct format systemformatexception input string was not in a correct formatif the text is empty textbox1text it throws this error i understand this error but not sure how to correct this,['c#'] +252697,find the best region of interest after edge detection in opencv i would like to apply ocr to some pictures of 7 segment thisplays on a wall my strategy is the followingcovert img to grayscaleblur img to reduce false edgesthreshold the img to a binary imgapply canny edge detectionset region of interest roi base on a pattern given by the silhouette of the numberscale roi and template match the regionhow to set a roi so that my program does not have to look for the template through the whole image i would like to set my roi base on the number of edges found or something more useful if someone can help mei was looking into cascade classification and haar but i do not know how to apply it to my problem here is an image after being preprocessed and edge detectedoriginal image,['c++'] +252727,detect windows font size 100 125 150 i created an application that works perfectly until the user selects 125 or 150 it would break my application i later found a way to find the font size by detecting the dpi this was working great until people with chinese versions of windows 7 starting using my application the entire application breaks on chinese windows 7 from what i can tell i cant really test it for i only have english version and installation the language packs does not cause the problem chinese chars are causing a weird dpi that breaks my applicationmy current code works like this if dpidpix 120 for 125 fonts resize form and set default font to correct problems else if dpidpix 96 for 100 and 150 fonts resize form and set default font to correct problems on english versions of windows 7 that works great but some how chinese versions skip right by this and the form destroys it self with controls not even showing up font extremely large and pushing past the problem picture boxes being moved aroundso what is a good way to detect the windows font scale 100125 and 150 without detecting api i need something solid that will work on all windows 7 operating systems and languages,"['c#', '.net']" +252745,special use of java generics hack or nice productivity boost we have been simplifying some definition and usage of generics in our codenow we got an interesting case take this examplepublic class myweirdclass public void entrypoint dosomethingweird suppresswarnings unchecked private t extends a b t getmyclass if systemcurrenttimemillis 2 0 return t new myclass 1 else return t new myclass 2 private t extends a b void dosomethingweird t obj getmyclass objmethodfroma objmethodfromb static interface a void methodfroma static interface b void methodfromb static class myclass 1 implements a b public void methodfroma public void methodfromb static class myclass 2 implements a b public void methodfroma public void methodfromb now look at the method doseomthingweird in myweirdclassthis code will compile correctly using the eclipse jdt compiler however it will fail when using the oracle compiler since the jdt is able to produce working bytecode it means that at jvm level this is valid code and it is only the oracle compiler not allowing to compile such dirty stuffwe understand that oracles compiler would not accept the call t obj getmyclass since t is not a really existent type however since we know that the returned object implements a and b why not allowing it the jdt compiler and the jvm donote also that since the generics code is used only internally in private methods we do not want to expose them at class level polluting external code with generics definitions that we are not interested at from outside the classthe school book solution will be to create an interface ab extends ab however since we have a larger number of interfaces which are used in different combinations and coming from different modules making shared interfaces for all the combinations will significantly increase the number of dummy interfaces and finally make the code less readable in theory it would require up to npermutations of different wrapper interfaces in order to cover all the casesthe businessorientedengineerother people call it the lazyengineer solution would be to leave the code this way and start using only jdt for compiling the codeedit it is a bug in oracles javac 6 and works without problems also on oracles javac 7what do you mean are there any hidden dangers by adopting this strategyaddition in order to avoid thiscussion on for me not relevant pointsi am not asking why the code above does not compile on oracles compiler i know the reason and i do not want to modify this kind of code without a very good reason if it works perfectly when using another compilerplease concentrate on the definition and usage without giving a specific type of the method dosomethingweirdis there a good reason why we should not use only the jdt compiler that allows writing and compiling this code and stop compiling with the oracles compiler which will not accept the code abovethanks for inputedit the code above compiles correctly on oracle javac 7 but not on javac 6 it is a javac 6 bug so this means that there is nothing wrong in our code and we can stick on itquestion is answered and i will mark it as such after the two days timeout on my own answerthanks everybody for the constructive feedback,['java'] +252762,debugging does not start when i hit f5 debugging mode nothing happens building works correctly exe file i can launch properly but cannot start debug why,['c#'] +252766,how to use fast scroll in android i have a list of events which are seperated by month and year jun 2010 jul 2010 etci want to enable fast scrolling because the list is really longhow do i enable fast scroll on listviews in android,['android'] +252778,i have been writing php without classes for years what am i missing for the life of me i cannot seem to wrap my head around classes in phpi have managed to write large scalable and popular websites without themwhat am i missing and how do i learn,['php'] +252817,what are the advantages of lldb over gdb in ios development in xcode 43 now you can enable using lldb as the debugger for ios targets what advantages does it have over using the good old gdb gdb still works with llvm and i cannot see any obvious differences in everyday debugging tasks,['ios'] +252821,is lock taking cpu time i have 6 threadsone of the thread get in some scope and turn on the lock and all the other threads are waiting and want to enter to the same scope now is the other threads will get cpu time does the other thread are in the thread schedule i understand that all the other thread are in waiting state but the cpu will try to make the thread continue and try to get in the scope even if the scope is not accessible,"['c#', '.net']" +252826,bigint mysql performance compared to int i am trying to find out if my table will get less performant if i change the primary key to bigint20 at the moment i am using int7 and have about 30 entries already with large ids 7 or 8 digitsi searched a lot already but only found out that it uses more thiskspace which is obvious all of my ids have 7 digits right now but my customer wants to change to 8 digits i would not be able to easily change the software in the future so i thought about using bigint20 now just in case would it be less performant if i use bigint even though i do not need to yetdoes anyone with experience doing this have suggestions regarding speed and performance,['mysql'] +252865,how to dynamically add a class method using the objectivec runtime how do i add the method layerclass to the private uigrouptableviewcellbackground class not to its superclass uiview note this is only for testing to see how uitableviewstylegrouped sets cell backgroundview selectedbackgroundview,['objective-c'] +252881,what does the eh in ehcache stand for just out of idle curiosity and google did not give me an answer but what does the eh stand for in ehcache,['java'] +252889,how to plot cdf in matplotlib in python i have a thisordered list named d that looks like0 1239877098709876 i just simply want to plot a cdf graph based on this list by using matplotlib in python but do not know if there is any function i can used d sorted for line in fdreadlines addr videoid userag usertp timeinterval linesplit dappendfloattimeintervald sorted sorteddclass thiscrete cdf def init data self data data must be sorted self data len floatlendata def call point return lenself databisect leftself data point self data lencdf thiscrete cdfd sortedxvalues range0 maxd sortedyvalues cdfpoint for point in xvaluespltplotxvalues yvaluesnow i am using this code but the error message is traceback most recent call lastfile hitratioparea 0117py line 43 in modulecdf thiscrete cdfd sortedtypeerror init takes exactly 1 argument 2 given,['python'] +252893,why is splitting a string slower in c than python i am trying to convert some code from python to c in an effort to gain a little bit of speed and sharpen my rusty c skills yesterday i was shocked when a naive implementation of reading lines from stdin was much faster in python than c see this today i finally figured out how to split a string in c with merging delimiters similar semantics to pythons split and am now experiencing deja vu my c code takes much longer to do the work though not an order of magnitude more as was the case for yesterdays lessonpython codeusrbinenv pythonfrom future import print function import timeimport syscount 0start time timetimedummy nonefor line in sysstdin dummy linesplit count 1delta sec inttimetime start timeprintpython saw 0 lines in 1 seconds formatcount delta sec endif delta sec 0 lps intcountdelta sec print crunch speed 0formatlpselse printc codeinclude iostream include stringinclude sstreaminclude timehinclude vectorusing namespace stdvoid split1vectorstring tokens const string str const string delimiters skip delimiters at beginning stringsize type lastpos strfind first not ofdelimiters 0 find first nondelimiter stringsize type pos strfind first ofdelimiters lastpos while stringnpos pos stringnpos lastpos found a token add it to the vector tokenspush backstrsubstrlastpos pos lastpos skip delimiters lastpos strfind first not ofdelimiters pos find next nondelimiter pos strfind first ofdelimiters lastpos void split2vectorstring tokens const string str char delim stringstream str convert string to stream string item whilegetliness item delim tokenspush backitem add token to vector int main string input line vectorstring spline long count 0 int sec lps time t start timenull cinsync with stdiofalse thisable synchronous io whilecin getlinecin input line splineclear empty the vector for the next line to parse i am trying one of the two implementations per compilation obviously split1spline input line split2spline input line count count subtract for final overread sec int timenull start cerr c saw count lines in sec seconds if sec 0 lps count sec cerr crunch speed lps endl else cerr endl return 0compiled with g wall o3 o split1 split 1cppnote that i tried two different split implementations one split1 uses string methods to search for tokens and is able to merge multiple tokens as well as handle numerous tokens it comes from here the second split2 uses getline to read the string as a stream does not merge delimiters and only supports a single delimeter character that one was posted by several stackoverflow users in answers to string splitting questionsi ran this multiple times in various orders my test machine is a macbook pro 2011 8gb quad core not that it matters much i am testing with a 20m line text file with three spaceseparated columns that each look similar to this foobar 127001 homefoobarresults usrbintime cat test lines double splitpy 1561 real 001 user 038 syspython saw 20 lines in 15 seconds crunch speed 13 usrbintime cat test lines double split1 2350 real 001 user 046 sysc saw 20 lines in 23 seconds crunch speed 869565 usrbintime cat test lines double split2 4469 real 002 user 062 sysc saw 20 lines in 45 seconds crunch speed 4what am i doing wrong is there a better way to do string splitting in c that does not rely on external libraries ie no boost supports merging sequences of delimiters like pythons split is thread safe so no strtok and whose performance is at least on par with pythonedit 1 partial solutioni tried making it a more fair comparison by having python reset the dummy list and append to it each time as c does this still is not exactly what the c code is doing but it is a bit closer basically the loop is nowfor line in sysstdin dummy dummy linesplit count 1the performance of python is now about the same as the split1 c implementation usrbintime cat test lines double split5py 2261 real 001 user 040 syspython saw 20 lines in 22 seconds crunch speed 909090i still am surprised that even if python is so optimized for string processing as matt joiner suggested that these c implementations would not be faster if anyone has ideas about how to do this in a more optimal way using c please share your code i think my next step will be trying to implement this in pure c although i am not going to trade off programmer productivity to reimplement my overall project in c so this will just be an experiment for string splitting speed thanks to all for your helpfinal editsolutionplease see alfs accepted answer since python deals with strings strictly by reference and stl strings are often copied performance is better with vanilla python implementations for comparison i compiled and ran my data through alfs code and here is the performance on the same machine as all the other runs essentially identical to the naive python implementation though faster than the python implementation that resetsappends the list as shown in the above edit usrbintime cat test lines double split6 1509 real 001 user 045 sysc saw 20 lines in 15 seconds crunch speed 13my only small remaining gripe is regarding the amount of code necessary to get c to perform in this case one of the lessons here from this issue and yesterdays stdin line reading issue linked above are that one should always benchmark instead of making naive assumptions about languages relative default performance i appreciate the education thanks again to all for your suggestions,"['c++', 'python']" +252906,how to run an api made for 32bit on a 64bit machine i am writing a java application which has to communicate with has to communicate with an xbee radio over a usbcableto do this i use the xbeejava api on my old 32bit machine it all worked fine but when i imported the project to a 64bit machine it throws immediately an exception which says cannot load ia 32bit dll on a amd 64bit platform i do not have any idea how i can solve this problem the error code javalangunsatisfiedlinkerror cuserstomdocumentsxbeejavarxtxserialdll cannot load ia 32bit dll on a amd 64bit platform thrown while loading gnuiorxtxcommdriverclosing connection with local xbexception in thread thread1 javalangunsatisfiedlinkerror cuserstomdocumentsxbeejavarxtxserialdll cannot load ia 32bit dll on a amd 64bit platform at javalangclassloadernativelibraryloadnative method at javalangclassloaderloadlibrary0unknown source at javalangclassloaderloadlibraryunknown source at javalangruntimeloadlibrary0unknown source at javalangsystemloadlibraryunknown source at gnuiocommportidentifierclinitcommportidentifierjava83 at comrapplogicxbeerxtxserialcommopenserialportrxtxserialcommjava71 at comrapplogicxbeerxtxserialcommopenserialportrxtxserialcommjava61 at comrapplogicxbeeapixbeeopenxbeejava140 at meserverhardwarecommunicationssensorlistenerrunsensorlistenerjava47 at javalangthreadrununknown sourcethanks tom,['java'] +252920,adb error codes we have an android device and as part of testing i need to excute a console test application on the target device if the test application detects an error it returns 1i can use adb shell to run the test applications remotely on the target but i cannot find a way of getting back the return code i need this so i that i can build this into an automated test suite i could try grepping the console output for some failure text but that is a bit grubby does anyone know of a more elegant solution,['android'] +252939,unobtrusive client validation using fluentvalidation and aspnet mvc lessthanorequalto not firing i have the following rulesthe 1st does work using unobtrusive client side validation the second does notany ideas whyruleforx xstartdate lessthanorequaltox xenddatevalue withlocalizedmessage commonresless than or equal to filters commonresstart date filters commonresend dateruleforx xstartdate greaterthanorequaltox xabsolutestartdate lessthanorequaltox xabsoluteenddate withlocalizedmessage commonresbetween filters commonresstart date filters filtersabsolutestartdate filters filtersabsoluteenddate,"['c#', 'jquery']" +252940,how to prevent jquery or jquery ui from setting uistatethisabled on a div i am using jquery draggable and when i do adivdraggablethisabledtruejquery is setting a uistatethisabled to that div uistatethisabled is implemented in jquery ui css i still want jquery ui css i would prefer not to change uistatethisabled so i can use it somewhere elseis it possible to prevent jquery from setting uistatethisabledsince thisabledtrue seems to be setting that css class is there another way to make a draggable objet thisabled,['jquery'] +252959,why does java use hash 0x7f tablength to decide the index of a key from the link below i know java uses hash 0x7f tablength to decide which slot of an array to put the key value inmy question is why java first does hash 0x7f is there any particular purpose,['java'] +252961,how to see if resource file exists in java i am trying to output text to a resource file in java like sofile file new filemlmclassgetclassloadergetresourcemazestxttostringbufferedwriter out new bufferedwriternew filewriterfilebut because the resource file has not been created i get a null pointer exception how can i create a blank resource file first if it does not exist already to avoid this error,['java'] +252991,does c pick the wrong type for var when parsing a dynamic object i am using the following code to convert some json into a dynamic object when i use datetimeparse on a property of my dynamic type i would expect the var to guess that it is type is a datetime instead it stays as a dynamic this cannot be right can itfull example belowvar settings new javascriptserializerdeserializedynamicjsonvar startdate datetimeparsesettingsstartdatevar enddate datetimeparsesettingsenddatevar userid intparsesettingsuseridstartdate enddate and userid are all still dynamic which means i then cannot use them in a later lambda expressions obviously i can fix the code withdatetime startdate datetimeparsesettingsstartdatedatetime enddate datetimeparsesettingsenddateint userid intparsesettingsuseridbut it seems like the compiler is making a bad guess can anyone explain this to methanks,['c#'] +252995,solution to minify object properties in my javascript application i use several objects for internal purposes only the users do not need to access them for examplevar images blankblankgif plusplusgif minusminusgifwhen i use a minifier like uglifyjs the property names blank plus minus are kept as is is there a way to minify themwhat i have considered so faruse google closure minifier in advanced mode but this crushes my codereplace object properties with variables eg var imagesblankblankgif but it makes the code less readableis there a better way,['javascript'] +253010,why does a method invocation expression have type dynamic even when there is only one possible return type inspired by this questionshort version why cannot the compiler figure out the compiletime type of mdynamic arg if there is only one overload of m or all of the overloads of m have the same return typeper the spec a765an invocationexpression is dynamically bound a722 if at least one of the following holdsthe primaryexpression has compiletime type dynamicat least one argument of the optional argumentlist has compiletime type dynamic and the primaryexpression does not have a delegate typeit makes sense that forclass foo public int mstring s return 0 public string mint s return stringempty the compiler cannot figure out the compiletime type ofdynamic d dynamicvar x new foomdbecause it would not know until runtime which overload of m is invokedhowever why cannot the compiler figure out the compiletime type if m has only one overload or all of the overloads of m return the same typei am looking to understand why the spec does not allow the compiler to type these expressions statically at compile time,['c#'] +253024,replacement for huge case statements i am trying to improve a java project which uses a lot of large case statements in cases where the case statement is used it is used to handle an event which has an attribute associated to it for examplepublic void jumpoverwallint wallid switch wallid case 0 case 1213 case 2123 case 3123 case 4123 the numbers are non sequential and all require a different action to be performed for example saying you cannot jump over this wall or moving the character to a set position there are very few cases in which the case response follows a set pattern what i mean by this is that the switch statements do not follow a pattern that would allow for code similar topublic void jumpoverwallint wallid somearray1213 10 somearray3123 20 if playerjumpingskill somearraywallid do something else sendplayermessageyou cannot do this therefore i am wondering the best possible way of handling these events the whole idea of an event handler style system is something that appeals to me but i am stuck as how to implement it or a better solution to the problem there are too many events in my opinion to have a separate class for each oneis there a method design for hooking events would this be applicable work i would be looking to a method of easy hooking such ashookevent1213 new someinterface boolean eventok do something return true then these hooks would be checked for and called,['java'] +253025,how can i find circular relations in a graph with python and networkx consider i have the following grapha bb cc dc awhat is the easiest way to find that a b c a is a circular relation is there such a function already built into networkx or another easy to use python library,['python'] +253034,how to center a div with bootstrap2 i tried like all combinationsdiv classrow div claspan7 offset5 box divdivor div classcontainer div classrow div claspan7 offset5 box div div divchanged span and offset numbersbut i cant get a simple box perfectly centered on a page i just want a 6columnwide box centerededitdid it with div classcontainer div classrow idlogincontainer div claspan8 offset2 box div divdivbut the box is too wide is there any way i can do it with span7 span7 offset2 gives extra padding to the left span7 offset3 extra padding to the right,['css'] +253049,how can i detect herokus environment i have a django webapp and i would like to check if it is running on the heroku stack for conditional enabling of debugging etc is there any simple way to do this an environment variable perhapsi know i can probably also do it the other way around that is have it detect if it is running on a developer machine but that just does not sound right,['python'] +253061,what does pythons eval do in the book that i am reading on python it keeps using the code evalinputblah i read the documentation and i understand it but i still do not see how it changes the input function what does it do can someone explain,['python'] +253079,difference between compile parse and render in mustachejs what is the difference betweenmustachecompile mustacheparse and mustacherender in the new mustachejs version 050 and perhaps for bonus points you could tell us what the difference between parsing and compiling is in general,['javascript'] +253113,easy tool to decompose sprite image i have a lot of sprite images that contain dozens of icons is there an easy way to unravel the sprites into separate image files either automatically or feeding it coordinates widths and heights,['css'] +253144,rest api authorization authentication web mobile i have read about oauth amazon rest api http basicdigest and so on but cannot get it all into single piece this is probably the closest situation creating an api for mobile applications authentication and authorizationi would like to built apicentric website service so in the beginning i would have an api in center and website php mysql would connect via curl android and iphone via their network interfaces so 3 main clients 3 api keys and any other developer could also develop via api interface and they would get their own api key api actions would be acceptedrejected based on userlevel status if i am an admin i can delete anything etc all other can manipulate only their local account datafirst authorization should i use oauth xauth or my somekindofmyown implemenation see as i understand on amazon service user is api user have api key on my service i need to separate standard usersaccount the one who registered on the website and developer accounts who should have their api keyso i would firstly need to authorize the api key and then authenticate the user itself if i use amazons scheme to check developers api keys authorize their app which sheme should i use for user authenticationi read about getting a token via apiexampleorgauth after via https http basic posting my username and password and then forward it on every following request how manage tokens if i am logged in simultaneously on android and a website what about maninthemiddleattack if i am using ssl only on first request when username and password are transmitted and just http on every other is not that a problem in this example password protecting a rest service,['php'] +253154,make sure a javascript script is first to run i have noticed some scripts seem to be called before others on a certain page i was wondering what is the specific order for scripts to load inpage before referenced js scripts are they run in order from first script mentioned to last in page or is this browserdependent how can one make sure that a specific script is first to run in a page,['javascript'] +253165,losing transparent background when downloading an external png image i am thisplaying an external image in an image view by fist downloading it like thisbitmap bitmapfactorydecodestreaminputstreamnew urlurlgetcontentthen setting this bitmap to the imageview like thisimageviewsetimagebitmapbitmapthis works all good except that one of the images is a png and i lose the transparent background when using the bitmapfactorycan anyone tell me how i can keep the transparent background,['android'] +253167,what xml parser should i use in c i have xml documents that i need to parse andor i need to build xml documents and write them to text either files or memory since the c standard library does not have a library for this what should i usenote this is intended to be a definitive cfaqstyle question for this so yes it is a duplicate of others i did not simply appropriate those other questions because they tended to ask for something slightly more specific this question is more generic,['c++'] +253181,suds generates empty elements how to remove them major edit based on experience since 1st post two days agoi am building a python soapxml script using suds but am struggling to get the code to generate soapxml that is acceptable to the server i had thought that the issue was that suds was not generating prefixes for inner elements but subsequently it turns out that the lack of prefixes see shdata and inner elements is not an issue as the shdata and metaswitchdata elements declare appropriate namespaces see belowsoapenvenvelope xmlnsns3 xmlnsns0 xmlnsns1 xmlnsns2 xmlnsxsi xmlnssoapenv soapenvheader ns2body ns3shupdate ns3useridentitymeribeltd test sub gateway 3ns3useridentity ns3datareference0ns3datareference ns3userdata shdata xmlns repositorydata serviceindicationmeta subg baseinformationserviceindication sequencenumber0sequencenumber servicedata metaswitchdata xmlns ignoresequencenumberfalse metaswitchversion meta subg baseinformation actionapply networkelementnamemeribelnetworkelementname descriptiontd test sub gateway 3description domainnametestdatconcoukdomainname mediagatewaymodelcisco atamediagatewaymodel callfeatureservercontrolstatus callagentcontrolstatus usestaticnatmapping authenticationrequired providerstatus deactivationmode meta subg baseinformation metaswitchdata servicedata repositorydata shdata ns3userdata ns3originhostclientversion73ns3originhost ns3shupdate ns2bodysoapenvenvelopebut this still fails the issue is that suds generates empty elements for optional elements marked as mandatory no in the wsdl but the server requires that an optional element is either present with a sensible value or absent and i get the following error because the callfeatureservercontrolstatus element is not one of the allowable valuesthe user data provided did not validate against the metaswitch xml schema for user data details cvcenumerationvalid value is not facetvalid with respect to enumeration controlling abandoned cautiously controlling it must be a value from the enumerationif i take the generated soapxml into soapui and delete the empty elements the request works just fineis there a way to get suds to either not generate empty elements for optional fields or for me to remove them in code afterwardsmajor updatei have solved this problem which i have seen elsewhere but in a pretty inelegant way so i am posting my current solution in the hope that a it helps others andor b someone can suggest a better workaroundit turns out that the problem was not that suds generates empty elements for optional elements marked as mandatory no in the wsdl but rather that that suds generates empty elements for optional complex elements for example the following meta subg baseinformation elements are simple elements and suds does not generate anything for them in the soapxmlxselement namecmts typexsstring minoccurs0 xsannotation xsdocumentation dthisplayname firstversion50 lastversion74cmtsdthisplayname dvalidfrom50dvalidfrom dvalidto74dvalidto dtype firstversion50 lastversion74stringdtype dbaseaccess firstversion50 lastversion74rwrwrwdbaseaccess dmandatory firstversion50 lastversion74nodmandatory dmaxlength firstversion50 lastversion741024dmaxlength xsdocumentation xsannotationxselementxselement nametaglocation typexsstring minoccurs0 xsannotation xsdocumentation dthisplaynamepreferred location of trunk gatewaydthisplayname dtypestringdtype dbaseaccessrwrwrwdbaseaccess dmandatorynodmandatory ddefaultvaluenoneddefaultvalue dmaxlength1024dmaxlength xsdocumentation xsannotationxselementin contrast the following meta subg baseinformation element is a complex element and even when it is optional and my code does not assign a value to it it ends up in the generated soapxmlxselement nameproviderstatus typetmeta subg baseinformation providerstatus minoccurs0 xsannotation xsdocumentation dthisplaynameprovider statusdthisplayname dtypechoice of valuesdtype dbaseaccessrdbaseaccess dmandatorynodmandatory dvalues dvalueunavailabledvalue dvalueavailabledvalue dvalueinactivedvalue dvalueactivedvalue dvalueout of servicedvalue dvaluequiescingdvalue dvalueunconfigureddvalue dvaluepending availabledvalue dvalues xsdocumentation xsannotationxselementsuds generates the following for providerstatus which as stated above upsets my serverproviderstatusthe workaround is to set all meta subg baseinformation elements to none after creating the parent element and before assigning values as in the following this is superfluous for the simple elements but does ensure that nonassigned complex elements do not result in generated soapxmlsubgatewaybaseinformation clientfactorycreatens1meta subg baseinformationfor el in subgatewaybaseinformation subgatewaybaseinformation setitem el0 nonesubgatewaybaseinformation action applysubgatewaybaseinformationnetworkelementname meribeletcthis results in suds generating soapxml without empty elements which is acceptable to my serverbut does anyone know of a cleaner way to achieve the same effectsolution below is based on answers comments from both dusan and roland smith belowthis solution uses a suds messageplugin to prune empty xml of the form subscribertype before suds puts the request on the wire we only need to prune on shupdates where we are updating data on the server and the logic especially the indexing down into the children to get the service indication element list is very specific to the wsdl it would not work for different wsdlclass mypluginmessageplugin def marshalledself context pruned req contextenvelopechildren1children0 if reqname shupdate si reqchildren2children0children0children2children0children0 for el in sichildren if rematchazaz09 elementplainel prunedappendel for p in pruned sichildrenremovepand then we just need to reference the plugin when we create the clientclient clienturl pluginsmyplugin,['python'] +253188,capture the close event of popup window in javascript i need to perform some action before a popup windowusing windowopen closessomething like will be goodvar new window windowopensome urlnew windowonbeforeunload function my codehow can i achieve that,['javascript'] +253228,delete an sms from inbox i would like to delete an sms from the inbox once it is read by the user how to do thiseditpublic class smsreceiver extends broadcastreceiver overridepublic void onreceivecontext context intent intent todo autogenerated method stub bundle bundle intentgetextras smsmessage msgs null string address null ifbundlenull string info object pdus object bundlegetpdus msgs new smsmessagepduslength for int i0 imsgslength i msgsi smsmessagecreatefrompdubytepdusi addressmsgsigetthisplayoriginatingaddress info msgsigetmessagebodytostring string strbundlegetstringstate logvstatestr ifphonenumberutilsiswellformedsmsaddressaddress set and address length abortbroadcast logvphone numwellformed uri deleteuri uriparsecontentsms cursor c contextgetcontentresolverquerydeleteuri null null null null while cmovetonext try delete the sms string pid cgetstring0 get id string uri contentsmsconversations pid contextgetcontentresolverdeleteuriparseuri null null catch exception e logvexceptionoccurred what is wrong with this code the sms is not getting deleted,['android'] +253231,how and where to add custom xml in my android app i want to add one xml file which has some static data related to my application to my android app the important thing is that we cannot add the data to the stringxml fileat the time the application is launched it should load all static data from the xml file to my data structureproblems1 how do i add xml to my android app using eclipse2 where should i add my custom xml inside the values folder or res folder or anywhere else3 as per my understanding we have to write an xml parser class for this is it correct or is there any other way to automatically get the parsed xml value in android,['android'] +253286,how can jquery return an array and still have it be a jquery object i am attempting to reproduce jquerys 171 object structure to better understand how it it works i have the following codefunction window undefined var document windowdocument navigator windownavigator location windowlocation windowmyclass function var con function return new confninit confn conprototype init function return this test function consolelogtest1 return this confninitprototype confn contest function consolelogtest2 return this return con windowmy console looks like this myclasstest test1 confn coninit myclasstest test2 function return new confninit my confusion is how jquery is able to return an array and still have it be a jquery object jquery being executed from the console might look something like documentbody bodyabodya documentbodycsswidth 1263pxin fact one thing that i definitely noticed is the lack of for the return object so what exactly is going on here i have searched all over google to explain how jquery works to no avail maybe i am just getting the terminology wrong i am not sure it seems i cannot find any detailed source explaining thisperhaps my code is just incomplete but the basic structure that i have so far is what i have been able to extract so far please correct what i have so far if it is wrong incomplete or inefficient and by all means please feel free to provide good reading aboutjavascript best practiceshow jquery worksefficient javascript classesthings all about javascript object structuressingletonsprototypesanything else related to whatever this type of structure is called,"['javascript', 'jquery']" +253288,static object array public class array static string a new string red green blue static point p new point new point1 2 34 public static void mainstring args systemoutprintlnhello class point int x int y pointint x int y thisx x thisy y pointstring s string a ssplit x a0parseint y a1parseint in the above program the static point array initialization fails reporting errorarrayjava4 nonstatic variable this cannot be referenced from a static context static point p new point new point1 2 34 but the static string array succeeds whats the difference between themi really need a static object array because it is easy to refer to without instantiate the outer classthanks,['java'] +253304,modify app assets using phonegaps file api i worked on a phonegap application using html5 for a month i handle offline json files using file apiit seems that the json files i store are automatically saved on mntsdcardthe problem is i find myself handling 3 files for each file i want1 st the file packaged with my app jsproductsjs2 nd the remote file that sends me updates httpwebsiteremote productsjs3 rd the local file on sdcard i update with the remote data mntsdcardupdatedproductsjsis it possible to instead of saving on the sdcard update my apps assets using file api or create a new file in my app assets folder the json file packaged with my app found in jsproductsjsif yes how plz thx,"['javascript', 'android']" +253342,magento not sending out any mails how to debug magento is not sending out any emails transnational contact form gives error cannot send your mail at this momenti checkedmail setup in magento all email accounts are set in settingsphp mail works fine a testphp with php mail sends out a messagechecked my mailserver logs but see nothing there no errorsvarlogsystemlog and exceptionlog shows only an error not the cause of the error exception zend mail transport exception with message unable to send mail in varwebshophttpdocslibzendmailtransportsendmailphp137,['php'] +253350,java jpanel inside jscrollpane i have a jframe in this jframe i have a jpanel that i draw on this panel can be any size and so i placed it into a jscrollpane to let me scroll when the panel is larger than the window screen sizeunfortunately does not work as i expectedmaking the jframe window smaller than the jpanel size does not show scroll barsthe jscrollpane size now seems locked to the size of the jpanel i have added to it where as before it resized to the bounds of it is jframe window it still kinda does this but only vertically nowthe jpanel seems to assume the size of the jscrollpane regardless of what i set for preferred sizei am sure i am doing something stupid if someone could point out what i would be most gratefuljpanel imagecanvas new jpanel canvas to draw onjscrollpane scrollpane new jscrollpane set size of canvas imagecanvassetminimumsizenew dimension100100 scroll pane smaller then the size of the canvas so we should get scroll bars right scrollpanesetminimumsizenew dimension5050 add a border to canvas imagecanvassetborderborderfactorycreatelinebordernew javaawtcolor0 0 0 scrollpanesetviewportviewjpanelmany thanksdavid,['java'] +253357,how to run a 32bit jvm on a 64bit linux i am trying to run a 32bit hotspot jvm on a 64bit debian mint machine at first sight it all works until youll try to run something using swingjavalangunsatisfiedlinkerror optjavadevjdk170 03 32bjrelibi386xawtlibmawtso libxextso6 cannot open shared object file no such file or directoryadding that to the library path export ld library pathusrlibx86 64linuxgnu but then it gives this error javalangunsatisfiedlinkerror optjavadevjdk170 03 32bjrelibi386xawtlibmawtso libxextso6 wrong elf class elfclass64any idea what else has to be done here,['java'] +253373,best practices with large dataset in c currently i am working in desing and implement a software who has to implement crud operations over two tables with masterdetail arquitecture header has about half million of rows and detail about million of rowsfill all this data in a dataset is crazy also data can change and i am not interested in have a local copy of database i am interested in that software works fluently although dataset may be not the best solution i should use this to be consistent with other software partsfirst i think to use a typeddataset and some methos like getnext getfirst getbycod but i am not sure if is the best solutioni am doing a little test and do not work very fluentlyi am interested in know how other developers do this best practices and whats the best choice to do operations with large datai am using visual studio 2008 and sql server 2005added when you talk about of using sqldatareader youre referring something like this using sqlconnection con new sqlconnectioncon conopen sqlcommand cmd new sqlcommandselect from table cmdconnection con sqldatareader rd cmdexecutereader bindingsource bindingsource new bindingsource bindingsourcedatasource rd bindingnavigator1bindingsource bindingsource txtfcoddatabindingsaddtext bindingsource field,['c#'] +253379,tooltip is not a function i am trying to use the tooltip that i found from the following jqueryui tooltip what i have is a rails app that has some information in a table in separate cells currently you can view the full information of a cell by clicking it which opens up jquery dialog which works fine what i am trying to add to it is so that there will be two options1 click the cell which brings up jquery dialog which works already2 or hover a cell which shows an overviewimagefrom the image currently you have a booking that you can click on and it will show the booking information however i am trying to extend it so that the user has the option of clicking to view the information or hovering over the cell to view the information what is the best way to do this i have the following code which works with and brings up the dialog i tried addingtd class bookingstatus onmouseoverbooking bookingid tooltipbefore which did not work and i probably understand that it wouldnt work because there would be a conflict between the two in addition to this i did try using simpletip and qtip but seemed to not have no luck is what i am trying to do not feasible td class bookingstatus onclickbooking bookingid dialog center bookingreference number if current useris booking manager bookingcompany name end centerdiv stylethisplaynone if not bookingprovisional or current useris booking manager div idbooking bookingid titlebooking information else div idbooking bookingid titleedit booking end render partial booking dialog locals booking booking div divtd,['jquery'] +253388,not able to set location of jlabel on a jpanel i have set location 00 for the jlabel with respect to the jpanel but it is appering at the center and top what mistake am i making import javaawt import javaxswing import javaawteventpublic class main extends jframe private jpanel panelprivate jlabel label1public main panel new jpanel panelsetbackgroundcoloryellow imageicon icon1 new imageicon3png label1 new jlabelicon1 label1setlocation00 paneladdlabel1 thissetdefaultcloseoperationjframeexit on close thisgetcontentpaneaddpanel thissetsize500500 thissetvisibletrue public static void main string args new main,['java'] +253397,add loading indicatorprogress bar to phonegap android splashscreen i have a phonegap 141 jquerymobile 101 android project which is showing the resdrawablesplashpng just fine and the splashscreen goes away once the webview is loadedi would like to add some sort of progress indicator percentage text to the splashscreen but have been unsuccessful so fari have had success with this in the past by using a normal webview like somywebviewsetwebviewclientnew webviewclient override public void onpagefinishedwebview view string url myloadingviewsetvisibilityviewgone mywebviewsetvisibilityviewvisible mywebviewloadurlbut all that was just a layout with a progress indicator text and a background image that would get updated withmywebviewsetwebchromeclientnew webchromeclient public void onprogresschangedwebview view int progress myloadingviewsettextprogress does anyone know how i can add this functionality to the existing phonegap implementation or know how i can replace the phonegap one with an implementation of my own,['android'] +253440,is md5 decryption possible possible duplicateis it possible to decrypt md5 hashes i accidentally encrypted some data with the md5 encryption i need to recover it how can i decrypt the md5 encrypted data,['php'] +253450,androidappsupernotcalledexception activity did not call through to superonstop im using a few sensors mediarecorder and mediaplayer notificationmanager a wakelock and locationlistener here is my onresume and onpause functionsvoid onresume superonresume gps sensor locationlistener new mylocationlistener locationmanager locationmanagergetsystemservicecontextlocation service locationmanagerrequestlocationupdates locationmanagergps provider 0 0 locationlistener notification manager gnotificationmanager notificationmanager getsystemservicecontextnotification service gnotification new notification gnotificationvibrate gvibratevoid onpause superonpause release the recorder if mrecorder null mrecorderrelease mrecorder null release the media player ifmplayer null mplayerrelease mplayer null release power manager wakestop wake null release location listener locationmanagerremoveupdateslocationlistener locationmanager nulland heres the logcat outputthreadid1 thread exiting with uncaught exceptiongroup0x40015560 fatal exception mainandroidappsupernotcalledexception activitychangethispackagebeforesubmittingtothemarketsonicdriftchangethispackagebeforesubmittingtothemarketsonicdriftsonicdriftdid not call through to superonstopat androidappactivityperformstopactivityjava3875at androidappactivitythreadperformdestroyactivityactivitythreadjava2619at androidappactivitythreadhandledestroyactivityactivitythreadjava2690at androidappactivitythreadaccess2100activitythreadjava117at androidappactivitythreadhhandlemessageactivitythreadjava964at androidoshandlerthispatchmessagehandlerjava99at androidoslooperlooplooperjava130at androidappactivitythreadmainactivitythreadjava3683at javalangreflectmethodinvokenativenative methodat javalangreflectmethodinvokemethodjava507at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava839at comandroidinternaloszygoteinitmainzygoteinitjava597at dalviksystemnativestartmainnativemethod winputmanagerservice 96 window already focused ignoringfocus gain ofcomandroidinternalviewiinputmethodclientstubproxy40713650iprocess 17118 sending signal pid 17118 sig 9iactivitymanager 96 processchangethispackagebeforesubmittingtothemarketsonicdrift pid 17118has died iwindowmanager 96 win death window40958d98changethispackagebeforesubmittingtothemarketsonicdriftchangethispackagebeforesubmittingtothemarketsonicdriftsonicdriftpausedfalse iwindowmanager 96 win death window40991f90surfaceview pausedfalsehow do i fix this error i have tried to add superonstop to my onpause,['android'] +253487,how do i run a python script on my web server i have just started learning python and i am pretty lost right now i want to run my script on my server that is hosted through hosting24com their faq says they support python but i have no clue where to put my script for it to run there is a folder called cgibin in my root i am guessing that is where i put my script can someone explain to me how this works,['python'] +253490,how to get the attr reference in code i am looking to get the pointing reference from an attribute via code in my xml layouts i can easily get the referenced drawable like thisandroidbackgroundattrlistitembackgroundthe attribute reference is set by my theme i am looking to see if it is possible to get that referenced drawable via code i can work around this by creating style attr and reading the value inside a custom view but in this case i want to figure out if this is possible without doing all that i would think it would be possible but i have not found ways to get that attribute referencethanks,['android'] +253493,use a html renderer in an embedded environment i am working on a project where i will design a gui for an embedded device and would love to go with html for this i hope you guys can help me find a render engine that suits my needsrequirementsthe webpage must be rendered into a memory buffer i will then transfer the memory buffer to the thisplayi must be notified though callback or event that the render engine need to fetch a new item html page image etc the reason for this is that i must fetch the resource and feed it to the render engine the reason is that the device does not have tcpip in all configurations and will then need to fetch the item over serial line and also for security i need to validate that the request is allowedi must be able to inject mouse and keyboard events into the rendering engineonly c andor cmust be easily portable and lack dependencies to libraries that only exist for winlinuxmac the device i have runs a custom ossmall footprint and memory consumption i can probably get away with 10mb footprint and 510 mb allocated memory during rendering but not much moreboth open source as well as commercial solutions are welcomei do not need full html5 and css3 support i mean if i can use basic html and some css i am more than happyi have looked at some webkit chromium gecko berkelium and awesomium but not really found that they fit my needsis there anything out there that comes close to what i need or should i just give up this idea and build the gui in some other way i appreciate any help,"['c++', 'html']" +253498,remove css top and left attributes with jquery im building a draggable map that when the map is dragged the element is given a left and top attribute with values for each as sodiv classmap styletop200px left100pxmapdivi have a button that i want to remove the top and left attribute from the inline style on the div when clicked is this possible with jquery,['jquery'] +253511,how to deal with the need to change css class names i am looking for peoples strategies for dealing with the inevitable need to change or otherwise adapt a css class to accommodate new html elements i find myself in this situation fairly often so i am hoping other people share my pain and can advise hereimagine you have a table of products with the nice semantic class name products this is styled appropriately in your stylesheet a few months down the line your boss asks you to create a staff list on the site styled exactly the same as the products listthis immediately raises an important question what to call the new staff table the only options i can think of aregive it the class name products as well this is the quickest solution but ruins the semantics the naming makes little sense especially to future developerschange the class name to something that can encompass both products and staff listings this would negate the utility of separation of markup from style as the html would need changing also i cannot think of a single nonpresentational class name that could conceivably apply to a products and a staff listintroduce a new class name and edit the css file such that products becomes products staff and products thead thnumber fontweight bold becomes products thead thnumber staff thead thnumber fontweight bold etc another ugly solution which will only get more complicated as time goes bywhats the best course of action to take herenb i am sure this problem is easily solved using frameworks like less i have not used it personally but this solution strikes me more as a coverup than an actual remedy,"['html', 'css']" +253515,what does update method of messagedigest do and what is base64encoder meant for following is a code that will encrypts the user string import javaiounsupportedencodingexceptionimport javasecuritymessagedigestimport javasecuritynosuchalgorithmexceptionimport sunmiscbase64encoderimport javaioclass encrypter public synchronized string encryptstring plaintext throws exception messagedigest md null try md messagedigestgetinstancesha catchexception exc throw new exceptionexcgetmessage try mdupdateplaintextgetbytesutf8 catchexception exc throw new exceptionexcgetmessage byte raw mddigest string hash new base64encoderencoderaw return hashpublic static void mainstring args try encrypter encrypter new encrypter bufferedreader br new bufferedreadernew inputstreamreadersystemin string userinput brreadline string encryptedpassword encrypterencryptuserinput systemoutprintlnencryptedpassword catchexception exc systemoutprintlnexc when i compile the code i get the these warnings encrypterjava4 warning base64encoder is internal proprietary api and may be removed in a future releaseimport sunmiscbase64encoder encrypterjava23 warning base64encoder is internal proprietary api and may be removed in a future release string hash new base64encoderencoderaw 2 warningsis there any other method to encrypt strings in java what does the method update of class messagedigest do ie what does the statement mdupdateplaintextgetbytesutf8 do what is a base64encoder class i could not find it is doc,['java'] +253560,how do i check if 2 jquery selectors are pointing to the same elements if i try something such as thisfoo foo false i get false if i instead try this queryfooget0 fooget0 true i get truethat is becauseamyobject amyobjectmyobject myobjectmyobject myobjecti am wondering if there is any succinct way to test for this equality preferably built into jquery the 2nd method i wrote only works correctly if there is at most one element which matches foo the solution should work for any amount of elementsobviously i do not want to just check foo foo since the actual selections i am using are more complicated i just simplified them for this example eg i may want to check that this is selecting the same thing as foo,"['javascript', 'jquery']" +253632,android viewpager throwing indexoutofbounds exception when setting current itempage i have a viewpager with three items i am trying to set the viewpager to view the page furthest to the right which would be the 2nd element this is returning an indexoutofbounds exception though i know the index ought to be in bounds here is the exact stack02 1250256 eandroidruntime384 fatal exception main02 1250256 eandroidruntime384 javalangindexoutofboundsexception index1 count002 1250256 eandroidruntime384 at androidviewviewgroupaddinarrayviewgroupjava205002 1250256 eandroidruntime384 at androidviewviewgroupaddviewinnerviewgroupjava199402 1250256 eandroidruntime384 at androidviewviewgroupaddviewinlayoutviewgroupjava195802 1250256 eandroidruntime384 at androidviewviewgroupaddviewinlayoutviewgroupjava193902 1250256 eandroidruntime384 at androidsupportv4viewviewpageraddviewviewpagerjava91702 1250256 eandroidruntime384 at androidviewviewgroupaddviewviewgroupjava182802 1250256 eandroidruntime384 at ustagversepagertestmasteractivitypadapterinstantiateitemmasteractivityjava51802 1250256 eandroidruntime384 at androidsupportv4viewpageradapterinstantiateitempageradapterjava11002 1250256 eandroidruntime384 at androidsupportv4viewviewpageraddnewitemviewpagerjava64902 1250256 eandroidruntime384 at androidsupportv4viewviewpagerpopulateviewpagerjava78302 1250256 eandroidruntime384 at androidsupportv4viewviewpageronmeasureviewpagerjava101602 1250256 eandroidruntime384 at androidviewviewmeasureviewjava831302 1250256 eandroidruntime384 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava313802 1250256 eandroidruntime384 at androidwidgetlinearlayoutmeasurechildbeforelayoutlinearlayoutjava101702 1250256 eandroidruntime384 at androidwidgetlinearlayoutmeasureverticallinearlayoutjava38602 1250256 eandroidruntime384 at androidwidgetlinearlayoutonmeasurelinearlayoutjava30902 1250256 eandroidruntime384 at androidviewviewmeasureviewjava831302 1250256 eandroidruntime384 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava313802 1250256 eandroidruntime384 at androidwidgetframelayoutonmeasureframelayoutjava25002 1250256 eandroidruntime384 at androidviewviewmeasureviewjava831302 1250256 eandroidruntime384 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava313802 1250256 eandroidruntime384 at androidwidgetframelayoutonmeasureframelayoutjava25002 1250256 eandroidruntime384 at androidviewviewmeasureviewjava831302 1250256 eandroidruntime384 at androidviewviewrootperformtraversalsviewrootjava83902 1250256 eandroidruntime384 at androidviewviewroothandlemessageviewrootjava185902 1250256 eandroidruntime384 at androidoshandlerthispatchmessagehandlerjava9902 1250256 eandroidruntime384 at androidoslooperlooplooperjava12302 1250256 eandroidruntime384 at androidappactivitythreadmainactivitythreadjava368302 1250256 eandroidruntime384 at javalangreflectmethodinvokenativenative method02 1250256 eandroidruntime384 at javalangreflectmethodinvokemethodjava50702 1250256 eandroidruntime384 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava83902 1250256 eandroidruntime384 at comandroidinternaloszygoteinitmainzygoteinitjava59702 1250256 eandroidruntime384 at dalviksystemnativestartmainnative methodnote that the cause is javalangindexoutofboundsexception index1 count0 this would imply that the count of the pagesitems is 0 and the index i am requesting is 1 neither of these things are true here is how i am calling my viewpager and requesting the given pageviewpager pager viewpager findviewbyidridma viewcontainerpadapter adapter new padapterpagersetadapteradapterpagersetcurrentitem2note that this call does not give any error and correctly sets the current item to the middle item index 1viewpager pager viewpager findviewbyidridma viewcontainerpadapter adapter new padapterpagersetadapteradapterpagersetcurrentitem1i have a count of 3 items in the view pager here is my full padapter class which extends the pageradapter classprivate class padapter extends pageradapter implements titleprovider private int count 3 private static final int settings activity 0 private static final int main activity 1 private static final int friend list activity 2 override public int getcount return count override public object instantiateitemview collection int position linearlayout layout new linearlayoutgetapplicationcontext layoutinflater inflater layoutinflater getapplicationcontextgetsystemservicecontextlayout inflater service switchposition case main activity layout linearlayout inflaterinflaterlayoutmain null false initmainlayoutlayout break case settings activity layout linearlayout inflaterinflaterlayoutsettings null false initsettingslayoutlayout break case friend list activity layout linearlayout inflaterinflaterlayoutfriend list null false initfriendlistlayoutlayout break viewpagercollectionaddviewlayout position return layout override public void destroyitemview collection int position object view viewpagercollectionremoveviewlinearlayoutview override public boolean isviewfromobjectview v object o return v linearlayouto override public void finishupdateview arg0 no need override public void restorestateparcelable arg0 classloader arg1 no need override public parcelable savestate return null override public void startupdateview arg0 no need override public string gettitleint position resources res getapplicationcontextgetresources switchposition case main activity return resgetstringrstringapp name case settings activity return resgetstringrstringsettings case friend list activity return resgetstringrstringfriend list default return null the line viewpagercollectionaddviewlayout position causes the crashas you can see three items using setcurrentitem with a parameter of 0 or 1 works just fine but 2 causes this strange error i have run out of ideas to solve it unfortunately viewpager resides in some uncharted waters of android it seems if anyone has some insight on how to solve this it would be much appreciated thanksedit as per shereefs suggestion i tried logging the child count via collectiongetchildcount and got the following result02 152042274 echildren count645 count 002 152042454 echildren count645 count 102 152042594 echildren count645 count 2this is interesting what this tells me is that its creating an empty pageradapter and adding them one at a time instantiateitem is called 3 times for the three visible views center left and right so i added this block of code inside the instantiateitem methodifviewpagercollectiongetchildcount 2 viewpagercollectionsetcurrentitem2so only if the count is established to be 2 will it set the page to 2 this is a hacky solution which does not fully address the problem but was worth a try i got a similar error stack which pointed first to the line viewpagercollectionsetcurrentitem2 then viewpagercollectionaddviewlayout positionhope this helps give some insight,['android'] +253684,how to get started editing the source for chromium i am a somewhat novice programmer by which i mean i am proficient in many programming languages but have never taken formal classes and would like to heavily mod the chromium web browser for my own purposes i would need to change the ui significantly as well as make somewhat major changes to the v8 embedded javascript engine and i would like to know where i can start i guess what i really need to know isare there certain programming conventions i should observe to better understand how chromium works are there any guidestutorials on how the file system used for the source works are there any guidestutorials on how to editinterpret the chromium source code specifically should i try to mod chromium or should i try to build my own web browser using webkit and v8 i am also considering basing by browser on firefox would that be easier to get started with since i plan on learning as i work i would like to be able to understand the any help would be greatly appreciated as well as any gems of wisdom from your own personal experiencesps i am running ubuntu 10 if that makes a difference at all,['c++'] +253688,are cocoa auto layouts backwards compatible with xcode 4 on os x 107 lion apple introduced a fantastic new way of handling the spacial relationships of nibbased ui elements auto layoutsat the top of the doc page for auto layouts apple declaresnote auto layout is available only in mac os x v107 and later if you are running xcode 4 in mac os x v106 auto layout is not availableat first glance one would assume that auto layouts either would not compile for or run on prelion systems however as i reread the notice and doc page it began to look like auto layouts just do not exist in xcode on prelion systemsso do auto layouts after being compiled on a lionbased machine work on prelion machines i would imagine that apple could have accomplished this by compiling down the auto layouts into springstrutlike settingshow to thisable auto layouts in interface builder,['objective-c'] +253695,use the same lock object at two different code block can i use the same lock object at two methods accessed by two different threads goal is to make task1 and task2 thread safeobject lockobject new object thread 1void method1 locklockobject task1 thread 2void method2 locklockobject task2,['c#'] +253709,how to change navbar collapse threshold using twitter bootstrapresponsive i am using twitter bootstrap 201 in a rails 312 project implemented with bootstrapsass i am loading both the bootstrapcss and the bootstrapresponsivecss files as well as the bootstrapcollapsejs javascripti have a fluid layout with a navbar similar to the example this follows the navbar responsive variation instructions here it works fine if the page is narrower than about 940px the navbar collapses and thisplays a button that i can click on to expandhowever my navbar looks good down to about 550px wide ie it does not need to be collapsed unless the screen is very narrowhow do i tell bootstrap to only collapse the navbar if the screen is less than 550px widenote that at this point i do not want to modify the other responsive behaviors eg stacking elements instead of thisplaying them side by side,['css'] +253715,android losing incoming hispeed usb data when using android i am losing data on an incoming usb data stream that i do not lose when reading the same devicestream in windows i know that android is not a realtime os but neither is windows and windows is having no problem keeping up with the datai have data coming in at about 35mbsec using an ftdi 2232h chip which has a built in 4k buffer the bulk transfer calls in libusb can ask for 16k at a time so android needs to reap the contents of the usb buffer every 4ms or soi have tried writing in java and in c raising the thread andor process priority to it is highest sync and async routines and i even pass a separate buffer for each usb read so i do not even have to copy data between successive reads there is no garbage collection going on during the transfer i only need to buffer 20mb of data so it is all to ramstill android is not getting around to the usb data sometimes waiting as long as 12ms between reads causing a bunch of data to be lostdoes anyone have any ideas dma some sort of realtime request to the kernel,['android'] +253745,c undefined reference to vtable and inheritance file ahifndef a h define a h class a public virtual a virtual void doworkendiffile childhifndef child h define child h include ahclass child public a private int xypublic child child void doworkendifand childcpp include childhchildchild x 5childchildvoid childdoworkthe compiler says that there is a undefined reference to vtable for ai have tried lots of different things and yet none have workedmy objective is for class a to be an interface and to seperate implementation code from headers,['c++'] +253752,rsa encryptdecrypt i am writing a c program that encryptsbased on the private key and decryptsbased on the public key text i am trying to do this with the openssl lib does anyone know any good tutorial quick starting guide or sample code i have not found any decent one on the web,['c'] +253755,android spinner with date picker like google calendar app i am trying to get a text box that looks like a spinner to activate a date picker dialog this is done in both the google calendar app and the contacts app for birthdate on ics do i need to use a spinner and if so how do i change it is input view to be a date picker or if not how do i get a text view to have the little triangle that usually indicates a spinner,['android'] +253769,launch failed binary not found eclipse for c in windows i installed eclipse cdt plugin and also the following packagesminsysmingwi have also added paths to their bin in the path environment variable even then i am unable to compile and run any sample program in eclipsehow can i fix this thanks for your concern,['c'] +253775,python eval that coerces values to floating point is there a way to execute an evallike function that coerces its values to floating point i am hoping toeval13and have it return the floating point value 3 rather than the integer value 0,['python'] +253785,prezi html5 editor via impressjs i recently known that impressjs has been created as a html5 version of prezi this helps us to move away from the proprietary flash technology and instead use an open web standard that will become universal to all platformshowever it is annoying to type up the code on a html text editor like writing the translation rotation and the scale values for the slide it becomes difficult to visualize the presentation especially when the code is extended to an unbearable lengthso here is an example i just created when reading the html code below it is hard to know exactly where the slides are and how they will be thisplayeddiv idimpress div clastep datax0 datay0 slide 1 at origin div div clastep datax100 datay100 datascale05 slide 2 has been moved southeastern side and shrunk by half compared to slide 1 div div clastep datax500 datay405 datarotatex50 datarotatey34 datarotatez50 datascale25 slide 3 has been rotated in 3d and is 25x larger than slide 1 divdivscript typetextjavascript srcimpressjsscripta js fiddle exampleso is there a wysiwyg html5 prezi editor that i could use i would want one as it will make it much easier to create presentations based on html5 css3 and javascript,['javascript'] +253798,zend search lucene tries to allocate 3503812093817007931 bytes i have around 250kb of static html that i have to search through i figured i would use zend lucene for that creating indexes takes a few secs and all is nice and good except if i search for about it ends up with this fatal error allowed memory size of 134217728 bytes exhausted tried to allocate 3503812093817007931 bytes in varwu1938159datawprotectedvendorszendsearchlucenestoragefilefilesystemphp on line 163other words seem to be ok for it moreover the files contain some foreign texts so i have to use case insensitive analyzerzend search lucene analysis analyzersetdefault new zend search lucene analysis analyzer common utf8 caseinsensitivezend search lucene search queryparsersetdefaultencodingutf8in which case it takes an eternity to load and does not work at all crashing with this error occured while file readingdoes lucene have serious issues or did i mes something up myself,['php'] +253856,windows azure worker role not getting past first line of code i have a worker role that works perfectly in development but does not work when deployed does not work is rather vague but that is really all i have to go on as i am not seeing any errors or anything in the event log anyway maybe there is somewhere else i can look i have added some trace statements to my code and i am seeing the first one come out but none of the othersworkerrole codepublic class workerrole roleentrypoint region member variables private iwindsorcontainer container private ijob jobs endregion region methods public override bool onstart configurediagnostics tracewritelineworkerroleonstart try initialize tracewritelineresolving jobs jobs containerresolveallijob startjobs return baseonstart catch exception ex traceutiltraceexceptionex throw finally tracewritelineworkerroleonstart complete traceflush summary sets up diagnostics summary private void configurediagnostics diagnosticmonitorconfiguration dmc diagnosticmonitorgetdefaultinitialconfiguration dmclogsscheduledtransferperiod timespanfromminutes1 dmclogsscheduledtransferloglevelfilter loglevelverbose diagnosticmonitorstartconstantsdiagnosticsconnectionstring dmc summary sets up the ioc container etc summary private void initialize tracewritelineworkerroleinitialize try tracewritelineconfiguring automapper automapperconfigurationconfigure tracewritelineconfiguring windsor container new windsorcontainer tracewritelinestringformatinstalling assemblies from directory0 pathcombineenvironmentgetenvironmentvariableconstantsroleroot constantsapproot containerinstallfromassemblyindirectory new assemblyfilterpathcombineenvironmentgetenvironmentvariableconstantsroleroot constantsapproot tracewritelinestringformatsetting the default connection limit servicepointmanagerdefaultconnectionlimit 12 finally tracewritelineworkerroleinitialize complete summary starts all of the jobs summary private void startjobs tracewritelineworkerrolestartjobs try foreach ijob job in jobs jobstart finally tracewritelineworkerrolestartjobs complete public override void onstop tracewritelineworkerroleonstop try foreach ijob job in jobs jobstop containerthispose finally tracewritelineworkerroleonstop complete endregion region private util classes public static class automapperconfiguration public static void configure mapperinitializex xaddprofilemodelprofile endregiontraceutil codepublic static class traceutil public static void traceexceptionexception ex stringbuilder buffer new stringbuilder while ex null bufferappendformat0 exgettype bufferappendlineexmessage bufferappendlineexstacktrace ex exinnerexception tracetraceerrorbuffertostring configxml version10 encodingutf8 configuration systemdiagnostics trace autoflushtrue listeners add typemicrosoftwindowsazurediagnosticsdiagnosticmonitortracelistener microsoftwindowsazurediagnostics version10 cultureneutral publickeytoken31bf3856ad364e35 nameazurediagnostics filter type add listeners trace systemdiagnosticsconfigurationonce the worker has started if i look in the wadlogstable all i see is workerroleonstart and nothing elseany ideas on what the problem could be or how to troubleshoot this would be appreciatedupdate if i stop the role i do not see any of the debug statements from the onstop method eitherupdate i must have something configured incorrectly with my diagnostics i thought i was seeing my debug come out correctly when debugging locally but it turns out i am not i see everything in the output window but i do not see everything in the storage table i am seeing the following entries in developmentworkerroleonstartworkerroleinitializeconfiguring automapperi realize that the trace output is only periodically uploaded but i have waited 5 minutes or so so i think this should be long enough since i have it set to 1 minuteupdate as suggested by kwill in the comments section i have tried adding a file trace listener as follows systemdiagnostics trace autoflushtrue listeners add typemicrosoftwindowsazurediagnosticsdiagnosticmonitortracelistener microsoftwindowsazurediagnostics version10 cultureneutral publickeytoken31bf3856ad364e35 nameazurediagnostics add add namefile typesystemdiagnosticstextwritertracelistener initializedatactextwriteroutputlog listeners trace systemdiagnosticsthis works fine in my development environment and seems more reliable as well as i get all of the debug out that i would expect when i deploy it to staging however the textwriteroutputlog file is not even createdi really need a reliable way of getting debug out of my worker role so that i can troubleshoot the ultimate problem which is that my jobs are not working at this point i still have no idea what they are even trying to do as i cannot get any debug outupdate i am pretty sure that the missing dll idea suggested by most people is not the problem to hopefully prove this i have overridden the run method as shown below and i am seeing the heartbeat debug come out it seems to me that either the diagnostics functionality or at least the way i have it configured is unreliable which is preventing me from investigating why on earth my jobs are not running public override void run tracewritelinelearningmilesjobprocessorworkerrolerun information try while true threadsleep10 tracewritelineheartbeat verbose catch exception ex traceutiltraceexceptionex throw finally tracewritelinelearningmilesjobprocessorworkerrolerun complete information update i have now cross posted this problem on the windows azure msdn forumupdate as suggested in the comments i have now tried removing all useful code in development this resulted in all of the debug being output i then tried just removing the call to automapperconfigurationconfigure since previously i was seeing nothing come out after that call this resulted in some of the trace statements not coming out again importantly however i was seeing the trace statements that i have put in the jobs since it is the jobs not running that i ultimately want to resolve i deployed that version of the code to staging but there i just see the onstart trace and the heartbeat trace i do not think this really helps but maybe it will give someone some ideas,['.net'] +253860,validating jenkins plugin forms with ruby i am developing a jenkins plugin in ruby youre supposed to be able to configure every node that connects to the server so that an email is sent to a specified address when the node loses its connection to the master emailnodeproperty adds a field to enter an email address save an email property for every nodeclass emailnodeproperty jenkinsslavesnodeproperty require java import hudsonutilformvalidation thisplay name email notification attr accessor email def initializeattrs email attrsemail end def docheckemail value puts enpdocheckemailvalue endendwhen you configure a node there is a field named email where you can enter an email address i want this field to be validated when you enter an addresswhen you save the configuration an emailnodeproperty is created whence that is right you can access the email addressmycomputerlisteners offline gets called when a node loses its connectionclass mycomputerlistener include jenkinsslavescomputerlistener include jenkinspluginproxy def onlinecomputer listener end def offlinecomputer do nothing when the master shuts down if computerto smatchmaster nil list computernativegetnodegetnodeproperties proxy listfind emailnodeproperty if proxyis ajenkinspluginproxy rubyobject proxygettarget email rubyobjectemail accesses the email from emailnodeproperty end end endendmycomputerlistener finds the email address and sends an emaildoes anybody know if it is possible to validate the form in ruby according to the jenkins wiki this is whats supposed to be implemented field is supposed to be exchanged for the field name so i guess it should be docheckemailpublic formvalidation docheckfieldqueryparameter string value iflooksokvalue return formvalidationok else return formvalidationerrorthere is a problem herehow would you do this in ruby where should the method be implemented in emailnodeproperty or in mycomputerlistener how do you handle the queryparameter the would make it an intstance variable in ruby what is a queryparameterany help would be much appreciatedjonatan,['ruby'] +253864,removing title bar of android application i am making a small android application and i want to remove the android title bar i have tried using the thisrequestwindowfeaturewindowfeature no titlebut it still makes the title bar show for 01 second when the application starts i would love to make it not even show it when the app is loading i have searched a bit around and somebody mentions that you can change the style of the app but i have no idea how to do that i have only just started making apps so i do not have a lot of experience,"['java', 'android']" +253874,plsql update with inner join could someone please verify whether inner join is valid with update statment in pl sqlegupdate table tset tvaluevaluefrom tableb b inner joinon tidbidinner join tablec c oncidbidinner join tabled d ondidcidwhere dkey1,['sql'] +253888,git submodule workflow advice so i started using git a few days ago very late to the party do not scold really starting to get comfortable with the basic commands ideas and workflows however submodules are really taking my brain for a ride i am attempting to contribute code to fuelphps github and i could use some guidance and tipsi am running the following commands in the terminal1 clone the repository from fuels githubgit clone gitgithubcomfuelfuelgit2 move into the main fuel directorycd fuel3 initilize the submodules populate gitconfig with submodule datagit submodule init4 download the submodulesgit submodule update5 move into the core directory which is a submodulecd fuelcore6 change branch from no branch to 11developgit checkout 11develop7 open random file in text editor make some small change ie typo save filesudo gedit classesautoloaderphp8 add this file to the staging areagit add classesautoloaderphp9 commit this file under 11develop branchgit commit m im committing a submodule10 push the new commit to my not fuels github repo yes i have renamed the repogit push jordanarsenofuelcoregit11 changes are reflected on github looks good12 back way out to fuel again time to push the submodule commit separatelycd 13 add the fuelcore submodule to the staging areagit add fuelcore14 commit the submodule changegit commit m submodule pushed pushing super now15 push the commit to my not fuels github repogit push jordanarsenofuelgitspecifically my questions areis this the proper workflow for working with submodules is it what you would dowhy does git pull down the 11develop branch in a submodule but set me on no branch by default can i modify this behaviourwhat part of the fuel submodule tells git to pull 11develop to begin with there are other branches 11master 10develop etcwhy cannot we call it a day at step 11 the submodule push worked fine i push the super afterwards because the manual tells me it is a good idea and indeed heading over to github and looking at my super a commit is made this commit 845de87 however appears to be just a reference to fuels super and not my super should not it link to my repo and not theirsrunning cat gitconfig in super showsalong with all the submodulesremote originfetch refsheadsrefsremotesoriginurl gitgithubcomfuelfuelgitrunning cat git config in the core submodule showsremote originfetch refsheadsrefsremotesoriginurl gitgithubcomfuelcoregitwould it be wise to change these urls to my own repo on github fuel denies pushes anyway if i perform a submodule update will they be overwritteni have also asked this over on fuels forums but it is more of a general question and there are more gitters here thanks,['php'] +253889,ruby statistical gem what ruby gems are there that can perform data processing,['ruby'] +253894,android get checked checkbox values i need to get checked checkbox values when button clickedjava codedualcamera1 checkboxfindviewbyidridcamera1 dualthisplaydualcamera2 checkboxfindviewbyidridcamera2 dualthisplaydualcamera3 checkboxfindviewbyidridcamera3 dualthisplaydualcamera4 checkboxfindviewbyidridcamera4 dualthisplaydualthisplay buttondialogfindviewbyidridthisplaydualvideo,['android'] +253909,how to get column value from sqlite cursor i am trying to get column value from cursor this column is generated at run time by calculations inside the query i am getting null value of this column i am able to get value of all other columns which exists in sqlite tablei execute the same query on sqlite editor it also shows the value of generated column in result setwhy this giving null value when i am retrieving it from cursor,['android'] +253921,passing a generic function as a parameter i know that what i am doing can be done in a different way but i am curious about how things work the following is a simplified code which does not compile but it supposed to show my goalprivate void execute generalizedfunction1 2 i transformivoid generalizedfunctionstring astringa string astringb funcstring t aaction a result1 aactionastringa b result2 aactionastringb do something with a and b heret transformtstring astring return defaultransform is a generic convertion from string to some object think deserializationgeneralizedfunction uses two specializations of transform one for type a and one for type b i know i can do this in a number of other ways say by introducing a parameter for the type of the object but i am looking for explanations of whether it is possible or impossible to do this with genericslambdas if transform is specialized before it is passed as a parameter to generalizedfunction then it is impossible then the question is why this possibility is restricted,['c#'] +253935,making variables captured by a closure volatile how do variables captured by a closure interact with different threads in the following example code i would want to declare totalevents as volatile but c does not allow thisyes i know this is bad code it is just an exampleprivate void waitfor10events volatile int totalevents 0 error cs0106 someeventgeneratorsomeevent s e totalevents whiletotalevents 10 threadsleep100edit people seem to be missing the point of my question a bit i know i cannot use volatile on local vars i also know that the example code code is bad and could be implemented in other ways hence my bad code thisclaimer it was just to illustrate the problemanyway it would appear that there is no way to force volatile semantics onto captured local variables so i will implement a different way thanks for the answers though i have learned a couple of useful things anyway,['c#'] +253956,how to access role in jsp using spring security i want to print a user role in jsp i know there is a spring security tag called as secauthentication propertyprincipalusernameusing this tag i can access the user namebut how to access and print the current role in jsp,['java'] +253970,private methods in objectivec in xcode 43 i no longer need to declare them in my implementation file i have a lot question marks tolling above my headwhat i do not get is before xcode 43 i needed to declare forward declarations for private methods in my implementation filelike in my m file deleting this with xcode 43 the below code still does work in previous versions i had to put this because otherwise the compiler cannot find methodfirstinterface detailviewcontroller voidmethodfirst voidmethodsecondendimplementation detailviewcontroller void methodsecond if i delete the forward declaration now adays i dont get a compiler error that he cant find method first self methodfirst void methodfirstendnow it seems i do not need to do that anymore did apple update the compiler so that it is not needed anymore to put forward declarationsi cannot find any reference to an official apple source about this change i wonder what other people have encountered in their new environment,['objective-c'] +253986,if you overwrite a field in a subclass of a class the subclass has two fields with the same nameand different type i have 3 classespublic class alpha public number numberpublic class beta extends alpha public string numberpublic class gama extends beta public int numberwhy does the following code compile and why does the test pass without any runtime errorstestpublic void test final beta a new gama anumber its a string alpha anumber 13 gama anumber 42 assertequalsits a string anumber assertequals13 alpha anumber assertequals42 gama anumber,['java'] +253995,how to show private inheritance relationship in a uml class diagram in c since private inheritance is not considered as an isa relationship how is it supposed to be shown in a class diagram and if it is shown as a hasa relationship then how can it be differentiated between a composition and a private inheritance,['c++'] +254005,c function call and parameter tracing test case and mock generation i have a large code base of quite old c code on an embedded system and unfortunately there are no automated test casessuites this makes restructuring and refactoring code a dangerous taskmanually writing test cases is very time consuming so i thought that it should be possible to automate at least some part of this process for instance by tracing all the function calls and recording of the input and output values i could then use these values in the test cases this would not work for all but at least for some functions it would probably also be possible to create mock functions based on the gathered datahaving such test cases would make refactoring a less dangerous activityare there any solutions that already can do this what would be the easiest way to get this to work if i had to code it myselfi thought about using ctags to find the function definitions and wrapping them in a function that records the parameter values another possibility would probably be a gcc compiler plugin,['c'] +254052,when is it sensible to use threadsleep i always see people using threadsleep for creating delays in processing or something similar and people are always derided for using it this waywhen is it sensiblerequired to use threadsleep,"['c#', 'java']" +254084,dynamically load an animationdrawable in a textview i need to replace phrases of text in a with images and then append that to a textview for regular drawables this is no problem but when the drawable is an animationdrawable i do not know where and when to call startthis is how i append text to the textviewtextviewappendhtmlfromhtmltextwithhtmlimgtags imagegetter nullthe image tags in the textwithhtmlimgtags are replaced using imagegetternew imagegetter override public drawable getdrawablestring source ifsourceendswith ani logicmv this is an animated drawable animationdrawable dra animationdrawableresgetdrawablesresgetsource drasetbounds0 0 dragetintrinsicwidth dragetintrinsicheight drastart this does not work return dra drawable dr resgetdrawablesresgetsource drsetbounds0 0 drgetintrinsicwidth drgetintrinsicheight return dr my animationdrawables are added but they are not animated they are stuck on frame 1in the documentation it saysit is important to note that the start method called on the animationdrawable cannot be called during the oncreate method of your activity because the animationdrawable is not yet fully attached to the window if you want to play the animation immediately without requiring interaction then you might want to call it from the onwindowfocuschanged method in your activity which will get called when android brings your window into focussince the images are added dynamically i do not think it has anything to do with oncreateso i guess i call my start when my drawable is not yet fully attached to the window but wherewhenhow should i call itthanks in advance,['android'] +254105,how do i get my accordion to load with all the menus closed i am trying to follow the example herei have placed a mockup hereloading behavior is strange it shows menu1 then collapses it then shows menu2 and menu3 i would like everything to open collapsed i have tried the following without successaccordioncollapsehide true,"['javascript', 'html']" +254115,javascript showhide password i am trying to get this simple script to work bascically when a user clicks on the show link it will thisplay the password in the password text box and hide it when it is clicked again i have searched for solutions but could not find anything for what i need here is the codejavascript function toggle passwordtarget var tag getelementbyidtarget var tag2 getelementbyidshowhide if tag2innerhtml show tagsetattributetype text tag2innerhtml hide else tagsetattributetype password tag2innerhtml show htmllabel forpwd0passwordlabelinput typepassword value namepassword idpwd0 a href onclicktoggle passwordpwd0 idshowhideshowawhen i click the link nothing happens i have tested this without using the if statement too and still did nothing,['javascript'] +254136,python parser for pythonlike language i am looking to write a python import filter or preprocessor for source files that are essentially python with extra language elements the goal is to read the source file parse it to an abstract syntax tree apply some transforms in order to implement the new parts of the language and write valid python source which can then be consumed by cpython i want to write this thing in python and am looking for the best parser for the taskthe parser built in to python is not appropriate because it requires the source files be actual python which these will not be there are tons of parsers or parser generators that will work with python but it is hard to tell which is the best for my needs without a whole bunch of researchin summary my requirements areparser is written in python or has python bindingscomes with a python grammar that i can tweak or can easily consume a tweakable python grammar available elsewhere such as can reserialize the ast after transforming itshould not be too horrific to work with apiwiseany suggestions,['python'] +254211,c mono new bitmapfilename just hangs on osx when trying to load either a bmp png or jpg on osx 1073 using monos version of the systemdrawingbitmap object the applications just hangs i get no error the app just is stuck on the bitmaps constructorwhen i run the same code on archlinux or windows everything works finepublic static void main string args using var bitmap new bitmapimagebmp consolewriteline hello world never gets hereif i pause the application in debug mode it opens the thisassembly window and shows its stuck on this linecall status systemdrawinggdiplusgdiplusstartup uint64 gdiplusstartupinput gdiplusstartupoutputnote after pausing the application in debug mode a couple of times it magically started to work while writing this i promis i did not change any code anybody know what can cause systemdrawinggdiplus to hang so i know how to avoid it is there a mono codex setting file or something that could have bin messed up,['c#'] +254280,c overloading constructors with optional parameters named arguments this is not a question on proper coding practice i am just working through the semantics lets say i have the following constructorspublic fooclastring name thefoo fooname name public fooclastring name int num 7 bool boo true thisname foonum num foobool boo is it possible to use named arguments thuslyfooclass foo1 new fooclassnum1 where i am only passing one named argument relying on the optionals to take care of the restor call the constructor fooclastring int bool with no arguments as infooclass foo2 new fooclass,['c#'] +254295,php object instantiation context odd behaviour is it php bug i am not asking a typical question about why some code failed yet i am asking about why it workedit has worked with me while coding and i needed it to failcasea base abstract class with a protected constructor declared abstracta parent class extends the abstract class with public constructor over riddinga child class extends the very same abstract class with a protected constructor abstract class baseclass abstract protected function construct class childclass extends baseclass protected function construct echo it works class parentclass extends baseclass public function construct new childclass obj new childclass will result in fatal error expected obj new parentclass that workswhyquestionparent class instantiates child class object and it workshow come it doesas far as i knowobject cannot be instantiated if its constructor declared protected except only internally or from within any subclasses by inheritancethe parent class is not a subclass of the child classit does not inherit a dime from it yet both extend the same base abstract class so how come instantiation does not faileditthis case only happens with an abstract baseclass that has also an abstract constructorif baseclass is concerete or if its protected constructor is not abstract instantiation fails as expected is it a php bugfor my sanity i need really an explanation to why php behaves this way in this very specific casethanks in advance,['php'] +254321,hp touchpad usb driving on android can i do app development on hp touchpad running cyanogenmod 9i have an hp touchpad with cyanogenmod 9 installed and am trying to build to the device from eclipse the ide does not appear to recognize the device at all though is the problem with the driver where can i find it,['android'] +254379,whats the difference between weak and assign in delegate property declaration whats the difference between thisproperty nonatomic weak id subclassdelegate delegate and thisproperty nonatomic assign id subclassdelegate delegate i want to use property for delegates,"['objective-c', 'ios']" +254394,actionbar not scrolling to selected tab if this one is outside the visible bounds of actionbar on screen i set up an actionbar in my application i get back the actionbar by calling the activitygetactionbar then i set all the tabs i need thanks to actionbaraddtab and actionbarnewtab methodswhen i am in landscape mode all my categories are thisplayed on screen ie user can see all available tab i select the last category on the right of the screenafter a screen rotation i am now in portrait mode i save the selected category and restore it on my actionbar thanks to actionbarsetselectednavigationitem methodalthough the tab is well selected in the actionbar ie its label is underlinedhighlighted the considered tab is not currently visible on screen indeed the screen width is to small to thisplay all available tabs of actionbarmy problem is setselectednavigationitem does not make the actionbar scroll to the selected tab so that the user can see its label the user must manually scroll into actionbar to visualize which tab is currently selectedcould someone help me solve this problem,['android'] +254401,tinymce editor a potentially dangerous requestform value was detected from the client i have aspx in that i am calling a ascx user control in that i am using tinymce editor when i am trying to save data i am getting the errora potentially dangerous requestform value was detected from the client usercontrol1textbox1fghfghji already check a potentially dangerous requestform value was detected from the clienti triedwebconfig i setpages validaterequestfalsehttpruntime requestvalidationmode20 requestpathinvalidcharacterscompilation debugtrue targetframework40page validaterequestfalseserverhtmlencodetextbox1textencoding xml this is solving the prob but text is converting in html tag i do not want thatplease someone help me,"['c#', 'asp.net']" +254424,get page height in js crossbrowser what is the best way to get the actual page not window height in js that is crossbrowser compatiblei have seen a few ways but they all return different valuesselfinnerheightordocumentdocumentelementclientheightordocumentbodyclientheightor something elseone way of doing it which seems to work is var body documentbody html documentdocumentelementvar height mathmax bodyscrollheight bodyoffsetheight htmlclientheight htmlscrollheight htmloffsetheight,['javascript'] +254455,difference between windowwidth vs documentwidth what is the major difference between windowwidth vs documentwidth in jquerywhether window denotes the browser and document represents the body of html page am i correct,"['javascript', 'jquery']" +254465,loading kernel module in android kernel i am listing my problem here i have a google nexus one aka passion phone with me fastboot and adb tools are installed in the phone and the boot loader is unlocked my task i have to add a linux kernel module to the android kernel what i have donei followed the steps in and downloaded the kernel for android236 r1 passion and have built it i am also able to flash it on the phone and the new android kernel also works fine now what i want is to modify the kernel and add my own kernel module and then flash it on the phone so that the kernel on the phone is my modified kernelnow i have come across two approaches to do this1cross compile my kernel module with the android kernel and push it on the device with adb command the makefile i use in the kernel is as followsversion 2patchlevel 3sublevel 6extraversion 054g5f01537objm hello1okdirhomeapurvaandroid dirpwd shell pwdall make c kdir archarm cross compilehomeapurvaandroid dirprebuiltlinux x86toolchainarmeabi440binarmeabi subdirspwd modulesclean make c kdir archarm cross compilehomeapurvaandroid dirprebuiltlinuxx86toolchainarmeabi440binarmeabi subdirspwd cleannow this is not able to generate new hello1ko i do not know why i guess there is some problem with the version patchlevel sublevel and extraversion values are these necessary i tried these value from android236 r1 also but still it does not work i am not sure what is this extraversion valuei even tried with the hello1ko generated from the compiler in my ubuntu i pushed this hello1ko into the emulator with the following adb commandrootbinsrcouthostlinuxx86binadb shell mountrootbinsrcouthostlinuxx86binadb push hello1ko datarootbinsrcouthostlinuxx86binadb insmod datahello1kobut that hello1ko is not able to insmod and i get the following error insmod error in init module hello1ko function not implementedwhereas the hello1c is quite simpleinclude linuxmoduleh needed by all modules include linuxkernelh needed for kern info int init modulevoid printkkern info hello world 1n return 0void cleanup modulevoid printkkern info goodbye world 1n2the second approach of doing this can be placing my source files of the kernel module in the kernel directory of android may be in the system directory or somewhere else and ask the make to build these source files also along with the other source but i am not sure where to ask the make process to do so i tried to do so in mainmk and created a androidmk file in the source directory of my source files but it did not work may be this is a better solution but i could not find any help on thisafter doing this my kernel modules should be able to control the wnic wireless network interface device of the android phone it should be able to put the wnic in sleep mode and then wake it up after receiving command from my kernel module if you have some pointers on how to do this that will be a help i have found that on android it is controlled through wpa supplicant private driver commands like wpa cli driver powermode 0 auto wpa cli driver powermode 1 activecan do my task but i am not sure since i have not tried i have not reached that stageplease look into this and provide some helpguidancethanks apurva,['android'] +254473,change widget visibility on click my widget consists two relative layouts i have made both the layouts clickable following are the ids of the layoutandroidididupper layout androidididbottom layoutnow what i need is that if a user clicks on the upper layout bottom layout should be invisible here is what i have tried so far but it is not working can you check what i am doing wrongor maybe suggest some other ways to achieve thiscode public class bobswidget extends appwidgetprovider public static string action widget receiver clicked override public void onupdatecontext context appwidgetmanager appwidgetmanager int appwidgetids remoteviews remoteviews new remoteviewscontextgetpackagename rlayoutmain intent active new intentcontext bobswidgetclass activesetactionaction widget receiver pendingintent actionpendingintent pendingintentgetbroadcastcontext 0 active 0 remoteviewssetonclickpendingintentridupper layout actionpendingintent appwidgetmanagerupdateappwidgetappwidgetids remoteviews override public void onreceivecontext context intent intent todo autogenerated method stub check if our action was called if intentgetactionequalsaction widget receiver remoteviews remoteviews new remoteviewscontextgetpackagename rlayoutmain remoteviewssetviewvisibilityridbottom layout viewinvisible superonreceivecontext intent,['android'] +254477,switching uikeyboardtypenamephonepad default view i am curious is there a way of switching the uikeyboardtypenamephonepad textfield keyboard layout to the phonepad by default you get the name pad then when you click the numbers it switches to the phone pad is there a way of defaulting this style of keyboard to the phone pad and be able to switch to the name padthanksmichael,['ios'] +254543,mysql compare two tables and return rows that have the same primary key but different data in other fields i have two structurally identical tables table2 is a staging ground for new data that will be used in bulk updating table1i need to find out which rows would be updated in table1 i want to ignore those rows that would be inserted and those that would be deleted i am just interested in the updated rows where the primary key stays the same but one or more of the other fields in the row contains different dataso far the closest i have come is the following statementselect table2 from table2inner join table1on table1primarykey table2primarykeywhere table1field1 table2field1or table1field2 table2field2or table1field3 table2field3this returns 0 rowsedit the query actually works there was a problem with the data itself i am going to go facepalm for a whilethank you everyone for your input,"['mysql', 'sql']" +254569,java saxparser different between localname and qname in java handler class contains method which name is startelementthis method has prototypepublic void startelementstring uri string localname string qname attributes attributesi have read on oracle java website but i still not understand what different between localname and qname parameterhere they explainlocalname the local name without prefix or the empty string if namespace processing is not being performed qname the qualified xml 10 name with prefix or the empty string if qualified names are not availablein above definition i do not know some concepts prefix prefix of what namespacewho can explain for me as most simple as you can about these parameter pleasethanks,['java'] +254572,net implementation of efficient xml i am exporting large databases into xml format this xml data needs to be compressed into the smallest possible format i have heard alot about efficient xml exi and was wondering if there was a net implementation so that it can be called from within codedoes anyone have an example of this as online resources seem to be a bit sparse,['c#'] +254612,jquery random div order i have this jquery and html div classcontainer div classyellowdiv div classreddiv div classgreendiv div classbluediv div classpinkdiv div classorangediv div classblackdiv div classwhitediv divadivcontainer diveachfunction var color thisattrclass thiscssbackgroundcolor colori am trying to randomise the order so the divcontainer div is in any random position meaning not the same position it started and the div must remain within the divcontainer i have tried and more functions i found on the net but non are workingahow can i get the divs to thisplay in a random order,"['javascript', 'jquery', 'html']" +254641,key in treemap returning null so i have a very odd bug i stumbled across it when i was originally using a keyset to iterate over the first 10 keys of a large treemap one of the keys was returning null which should not be possible as far as my understanding goes so i wrote the test code belowint i 0 for mapentrystring integer es sortedmapentryset if i 10 break if sortedmapcontainskeyesgetkey systemoutprintlnesgetkey sortedmapgetesgetkey else systemoutprintlnkey esgetkey does not exist yet systemoutprintlnthis does work esgetkey esgetvalue systemoutprintlnthis does not work esgetkey sortedmapgetesgetkey i and get the following resultssoap967excerpt679type679key author url does not exist yetthis does work author url679this does not work author urlnulldate679android437tls295message283server230monthly215dumping mapsoap967 excerpt679 type679 author url679 date679 android437 tls295 message283 server230 monthly215i cut off the map after the top ten as there is a lot more in there but all of it is a key with a valueso my question is this why am i getting a null when using the key to directly getkey from the treemap but the entryset returns the correct key and value here is my comparator since i am ordering on integerclass valuecomparator implements comparatorobject mapstring integer base public valuecomparatormapstring integer base thisbase base public int compareobject a object b if integer basegeta integer basegetb return 1 else if integer basegeta integer basegetb return 0 else return 1 and the treemap is built as followingvaluecomparator bvc new valuecomparatorallmatchestreemapstring integer sortedmap new treemapstring integerbvcsort the hashmapsortedmapputallallmatcheswhere allmatches is a hashmapstring integer,['java'] +254649,css fade out horizontal rule line styled div effect without images i am a big fan of minimal use of images and was wondering if anyone had a tactic or if it is possible to create this kind of thing with pure static css i am referring an effect of a line seemingly getting skinnier and fading out and the shadow effect underneath iti was thinking it might be possible to do a css shape trick with it like the trianglesor perhaps with rotation on boxshadow using transformzenelementscomblogcss3transformany ideas,['css'] +254666,c dictionary type with unique keys and values i was wondering if there was a built in type in c that was like dictionary but where both tkey and tvalue had to be uniquefor example dadd1 1dadd2 1 this would not be ok because 1 has already been used as a valuei know this is kind of exotic but it seems that since there are about a billion collection types in the bcl it might exist any ideas,['c#'] +254702,make a java program sleep without threading i have a java program that does some calculations and then uploads the results to a mysql database hosted in another computer in the same network i sometimes face the problem that the program does calculations faster than it uploads the result therefore it is not able to upload all the results the program currently is not threaded is there a way i can make the program sleep for a few milliseconds after it has done the calculations so that the upload takes place properly like in other languages sleep or wait functioni can thread the program but that will be too much rewriting is there an easier waythanks,['java'] +254706,sizeof class with int function virtual function in c this is an online c test question which has been done includeiostreamusing namespace std class aclass bint i class cvoid fooclass dvirtual void fooclass eint i virtual void fooclass fint i void fooclass g void foo int i void foo1class h int i virtual void foo virtual void foo1int maincout sizeofclass a sizeofa endl cout sizeofclass b adding the member int i sizeofb endl cout sizeofclass c adding the member void foo sizeofc endl cout sizeofclass d after making foo virtual sizeofd endl cout sizeofclass e after adding foo virtual int sizeofe endl cout sizeofclass f after adding foo int sizeoff endl cout sizeofclass g after adding foo int sizeofg endl g gcout sizeofclass g after adding foo int sizeofg endl cout sizeofclass h after adding int 2 virtual sizeofh endl return 0 outputsizeofclass a 1sizeofclass b adding the member int i 4sizeofclass c adding the member void foo 1sizeofclass d after making foo virtual 8sizeofclass e after adding foo virtual int 16sizeofclass f after adding foo int 4sizeofclass g after adding foo unsigned int 4sizeofclass g after adding foo unsigned int 4sizeofclass h after adding int 2 virtual 16my questions why siszeofa is 1 and sizeofc is 1 too why siszeofh is 16 but sizeofg is 4 why siszeofe is 16 but sizeoff is 4 why siszeofd is 8 but sizeofe is 16 my guess a virtual function is a pointer with 8 bytes but i do not know why e size is 16 adding a function to an empty class does not change its size any help is appreciated thanks,['c++'] +254711,from import vs import i am wondering if there is any difference between the code fragmentfrom urllib import requestand the fragmentimport urllibrequestor if they are interchangeable if they are interchangeable which is the standardpreferred syntax if there is onethanks,['python'] +254737,using an instance of an object as a key in hashmap and then access it with exactly new object i have a hasmap with a key object hashmapkey object testand make new keythe same as keyso its liketestputnew keythe same someobjectwithout storing that key in a variableso after a while i want to access the hashmapbecause i do not have the object i have tried to make new keythe same and make it as a keybut it didnt workhow to make it work without saving the first object key in a variableso meanwhile for now im using string object as a keyhashmapstring object,['java'] +254770,flask static folder hosted on s3 i am trying to reroute all of my static content to host on amazon s3 my first thought was to use global configpath throughout my jinja templates but this would not work for external css and js files plus it is kind of messy i found the static folder and static url path released in 07 and this seems like what i want however when i go to httplocalhost80staticimgabcjpg it does not locate the files on s3 am i using this feature right or is there some other way to do thisthanks,['python'] +254782,rails 31 and ruby 193p125 rubydebug19 still crashes with symbol not found ruby threadptr data type possible duplicaterubydebug with ruby 193 i had heard rumors that ruby 193p125 has a solution for the rubydebug19 problem so per instructions on the rvm site i reinstalled 193 rvm reinstall 193 patch debug forceautoconf ruby v ruby 193p125 20120216 revision 34643 x86 64darwin1120thengem install rubydebug19added this entry to my gemfilegem rubydebug19then rails server u booting webrick rails 313 application starting in development on call with d to detach ctrlc to shutdown serveryou need to install rubydebug to run the server in debugging mode with gems use gem install rubydebugexitingto get past this error i changed my gemfile entry togem rubydebug19 require rubydebugnow a new error from the serverusersdonrvmgemsruby193p125gemsactivesupport313libactive supportdependenciesrb240in require dlopenusersdonrvmgemsruby193p125gemsrubydebugbase1901125libruby debugbundle 9 symbol not found ruby threadptr data type loaderror referenced from usersdonrvmgemsruby193p125gemsrubydebugbase1901125libruby debugbundle expected in flat namespace in usersdonrvmgemsruby193p125gemsrubydebugbase1901125libruby debugbundle usersdonrvmgemsruby193p125gemsrubydebugbase1901125libruby debugbundlei am very confused by the hundreds of posts out there on how to handle this rubydebug19 issue i was hoping it had been solved apparently not any suggestions if anyone suggests a patch please provide step by step instructions on how to apply it i have struggled with patches in the past,"['ruby-on-rails', 'ruby']" +254817,empty pseudoclass when adding dynamic content i have read in this sitepoint page and quirksmode page about the new empty pseudoclass sitepoint said that even when there is dynamic content appended the empty style will still take effect it is noted that firefox was the one who behaves this wayquirksmode said that it thiscards the empty state when it it filled in with some elements or text the demo on this site works in my browser chrome 19 so i assumed only firefox would be buggyhowever i have this piece of code in my plugin which dynamically fills up a list with items it does not seem to work heres a fiddle which appends list items even if you click the button the items would not appear until you try to debug it in the console they magically appear when you click the li in the element tree why is this happening and is there a work around to forcethiscard the empty stylei know there are other ways to do what i am doing in the fiddle and currently doing one of these other ways but the empty method is a lot easierupdateadded a remove item button when the last item is removed the list should thisappear still does not work hm i will try to check in another browserfixtemporary fixalternative to using empty and thisplaynone is to have the element have zero width height borders margins and paddings additionally positionabsolute to remove it from the flow,['css'] +254819,does anything like number exist as we use a hreftelnumbernumbera or a hrefmailtomailidmailidafor telephone number email does anything like a hreffaxnumbernumbera for fax exist,['html'] +254831,basic webserver with nodejs and express for serving html file and assets i am making some frontend experiments and i would like to have a very basic webserver to quickly start a project and serve the files one indexhtml file some cssjsimg files so i am trying to make something with nodejs and express i played with both already but i do not want to use a render engine this time since i will have only a single static file with this code i get the html file but not the assets error 404var express requireexpress app expresscreateserverappconfigurefunction appuseexprestatic dirname staticappget functionreq res ressendfile dirname indexhtmlapplisten30is there a simple way to do it in one file if possible or express requires the use of a view and render engine,['javascript'] +254833,file explorer always empty in eclipse the file explorer view in eclipse used to work so that while an app was running i could see and manage files in its memory but since a couple of days the file explorer is always completely empty both for the emulator and for physical devicesany suggestions about how to make this feature work again are very welcome,['android'] +254865,alarm clock app in ios i have to create an alarm clock app for the iphone in which user can set alarm time and soundin doing so i have used uilocalnotification to set off the alarm now in uilocalnotification first we get notification alert with option close and view if the user taps on view then my delegate receives the applicationdidreceivelocalnotification message and the alarm sound playsbut in the systemnative alarm app we do not see a notification alert it just directly plays the alarm sound how can i have my app use this behavior,"['iphone', 'ios']" +254876,lists or dicts over zeromq in python what is the correctbest way to send objects like lists or dicts over zeromq in pythonwhat if we use a pubsub pattern where the first part of the string would be used as a filteri am aware that there are multipart messages but they where originally meant for a different purpose further you can not subscribe all messages which have a certain string as the first element,['python'] +254878,how to include rails helpers on rspec i am trying to include some helpers to test with rspec but no luckwhat i didcreated a supporthelpersrb file under my spec foldersupporthelpersrbmodule helpers include actionviewhelpersnumberhelper include actionviewhelperstexthelperendand tried to require this file in spec helperrb this file is copied to spec when you run rails generate rspecinstallrequire rubygemsrequire sporkrequire supporthelperssporkprefork doendthis generates the following errorspecsupporthelpersrb2in modulehelpers uninitialized constant helpersactionview nameerrorhow should i do this helpers to be available with rspecthanks,['ruby-on-rails'] +254897,converting image file to base64 string using javascript i want to upload image file into couchdb using javascript for this i am using inline attachment concept while uploading file i have to use base64 encode this method has string argument only how can i convert image file to base64 string using javascript please can anybody share me the sample snippetthanks,['javascript'] +254898,where are keywords defined in ruby i was looking at the ruby documentation and am wondering if everything is an object then keywords are objects as well correct and if so where are they defined in rubythe following page totally confused me caused it showed the object with all the keywords in it however this is not the official object that is used by all classes is this mixedin somehow from a different classi guess there are lots of questions above the main one is how do ruby keywords get into ruby,['ruby'] +254899,how to thisable javadoc spell checker in netbeans i am used to writing javadocstyle comments for all the public fields and methods in my programs netbeans has this annoying habbit of checking how i spell everything in these comments if it finds a word that it thinks it is not ok it underlines it i hate it and i want it gone but i cannot find any option to thisable itdoes anyone know any way of doing this,['java'] +254911,creating a binary tree in java for genetic programming purposes i am working on a project for a software engineering class i am taking the goal is to design a program that will use genetic programming to generate a mathematical expression that fits provided training datai have just started working on the project and i am trying to wrap my head around how to create a binary tree that will allow for userdefined tree height and keep each node separate to make crossover and mutation simpler when i get to implementing those processeshere are the node classes i have created so far please pardon what i am sure is my evident inexperiencepublic class node node parent node leftchild node rightchild public void setparentnode p parent p public void setleftchildnode lc lcsetparentthis leftchild lc public void setrightchildnode rc rcsetparentthis rightchild rc public class operatornode extends node char operator public operatornode double probability mathrandom if probability 25 operator else if probability 25 probability 50 operator else if probability 50 probability 75 operator else operator public void setoperatorchar op if op op op op operator op node that holds x variables public class xnode extends node char x public xnode x x import javautilrandompublic class operandnode extends node int operand initializes random number generator sets the value of the node from zero to 9 public operandnode random rand new random operand randnextint10 manually changes operand public void setoperandint o operand o this accomplishes everything i need out of the nodes themselves but i am running into problems trying to figure out how to turn these into a larger tree i realize i need to use a collection type of some sort but cannot seem to find one in the library that seems appropriate for what i am trying to doeven a nudge in the right direction would be greatly appreciated,['java'] +254917,codeigniter passing data from controller to view i want to pass data from the controller named poll to the results view however i am getting an undefined variable error php if definedbasepath exitno direct script access allowedclass poll extends ci controller public function construct parent construct thisloaddatabase thisloadhelperform public function index thisloadviewpoll viewdata public function vote echo voting successfull thisdbinsertvotes post public function results echo these are the results query thisdbgetvotes data hello thisloadviewresults view data results viewphphtmlphp echo data html,['php'] +254955,set the popup window to center jquery right now i am setting the position of the modal jquery window in this way var winh windowheight var winw windowwidth set the popup window to center idcsstop winh2idheight2 idcssleft winw2idwidth2how do i center the popup when i scroll down,"['javascript', 'jquery']" +254960,publishing objects and thread safety i read in java concurrency in practice that publishing objects before they are fully constructed can compromise thread safety could someone explain this,['java'] +254962,does stdvector call the destructor of pointers to objects possible duplicatedeleting pointers in a vector i know when an stdvector is destructed it will call the destructor of each of its items does it call the destructor of pointers to objectsvectormyclass stuffwhen stuff is destroyed do the individual objects pointed to by the pointers inside stuff get destructed,['c++'] +254988,how to override validation with rails devise i am trying override the message validates presence of email and password but i can not how to i solve this,['ruby-on-rails'] +255003,sqlalchemy tutorial example not working i am trying to work my way through the example given in the sqlalchemy tutorial but i am getting errors as far as i can tell i am following the example to the letter heres the code that i have from it so far it fails when i first after i query the dbi am on version 075 and python 27from sqlalchemy import column integer stringfrom sqlalchemyextdeclarative import declarative basefrom sqlalchemy import create enginefrom sqlalchemyorm import sessionmakerengine create enginesqlitememory echotrueengineexecuteselect 1scalar works finesession sessionmakerbindenginesession sessionbase declarative baseclass userbase tablename users id columninteger primary keytrue name columnstring fullname columnstring password columnstring def init self name fullname password selfname name selffullname fullname selfpassword password def repr self return userss s selfname selffullname selfpasswordjeff user userjeff jeff foosessionaddjeff userour user sessionqueryuserfilter bynamejefirst fails herejeff userpassword foobarsessionadd all userwendy wendy williams foobar usermary mary contrary xxg527 userfred fred flinstone blahsessiondirty shows nothing as dirtysessionnew shows nothing as newhere is the error message20120225 174833879 info sqlalchemyenginebaseengine begin implicit20120225 174833886 info sqlalchemyenginebaseengine insert into users name fullname password values 20120225 174833886 info sqlalchemyenginebaseengine jeff jeff foo20120225 174833887 info sqlalchemyenginebaseengine rollbacktraceback most recent call last file learning sqlpy line 35 in module our user sessionqueryuserfilter bynameedfirst fails here file usrlocallibpython27thistpackagessqlalchemyormquerypy line 2024 in first ret listself01 file usrlocallibpython27thistpackagessqlalchemyormquerypy line 1918 in getitem return listres file usrlocallibpython27thistpackagessqlalchemyormquerypy line 2092 in iter selfsession autoflush file usrlocallibpython27thistpackagessqlalchemyormsessionpy line 983 in autoflush selfflush file usrlocallibpython27thistpackagessqlalchemyormsessionpy line 1559 in flush self flushobjects file usrlocallibpython27thistpackagessqlalchemyormsessionpy line 1630 in flush flush contextexecute file usrlocallibpython27thistpackagessqlalchemyormunitofworkpy line 331 in execute recexecuteself file usrlocallibpython27thistpackagessqlalchemyormunitofworkpy line 475 in execute uow file usrlocallibpython27thistpackagessqlalchemyormmapperpy line 2291 in save obj executestatement params file usrlocallibpython27thistpackagessqlalchemyenginebasepy line 1405 in execute params file usrlocallibpython27thistpackagessqlalchemyenginebasepy line 1538 in execute clauseelement compiled sql thistilled params file usrlocallibpython27thistpackagessqlalchemyenginebasepy line 1646 in execute context context file usrlocallibpython27thistpackagessqlalchemyenginebasepy line 1639 in execute context context file usrlocallibpython27thistpackagessqlalchemyenginedefaultpy line 330 in do execute cursorexecutestatement parameterssqlalchemyexcoperationalerror operationalerror no such table users uinsert into users name fullname password values jeff jeff foothe expected print out is this our user sessionqueryuserfilter bynameedfirst begin implicitinsert into users name fullname password values ed ed jones edspasswordselect usersid as users id usersname as users name usersfullname as users fullname userspassword as users passwordfrom userswhere usersname limit 1 offset 0ed our userusereded jones edspasswordfor some reason my code is causing a rollback when it should be select,['python'] +255075,php save image after imagecopyresampled image p imagecreatetruecolornew width new heightimage imagecreatefromjpegfilenameimagecopyresampledimage p image 0 0 0 0 new width new height width heighthow can i save the resized image to folder and how can i detect the image type is jpgpnggif,['php'] +255080,determinate a geopoint from another a thistance and a polar angle i am working on an android app that uses geopoints and i want to determinate a geopoint from another geopoint a thistance in any format and a polar angle for example i want to get coordinates of a place 100 meters in the northnortheast 225 degres of my location got by the gps in my phonethe only method i have found is locationthistancebetween,['android'] +255081,rails bundler how to undo bundle package how do i undo bundle packagei deleted everything in vendorcache but it is reinstalled there when i run bundle install,"['ruby-on-rails', 'ruby']" +255099,why use async requests instead of using a larger threadpool during the techdays here in the netherlands steve sanderson gave a presentation about c5 aspnet mvc 4 and asynchronous web he explained that when requests take a long time to finish all the threads from the threadpool become busy and new requests have to wait the server cannot handle the load and everything slows downhe then showed how the use of async webrequests improves performance because the work is then delegated to another thread and the threadpool can respond quickly to new incoming requests he even demoed this and showed that 50 concurrent requests first took 50 1s but with the async behavior in place only 12 s in totalbut after seeing this i still have some questionswhy cannot we just use a bigger threadpool is not using asyncawait to bring up another thread slower then just increasing the threadpool from the start it is not like the server we run on suddenly get more threads or something the request from the user is still waiting for the async thread to finish if the thread from the pool is doing something else how is the ui thread kept busy steve mentioned something about a smart kernel that knows when something is finished how does this work,"['c#', 'asp.net']" +255108,alternative to python string item assignment what is the best correct way to use item assignment for python string ie s abcdefgh s1 a s1b normal way will throw str object does not support item assignment,['python'] +255125,stepbystep connection between a scala highorder function to provided examples i am having difficulty figuring out how to make the jump from a scala highorder function definition to the example provided it was provided in this slide show on slide 81heres the highorder function definitiontrait xa def mapbf a b xb heres the examples provided1 to 10 map x x 2 evaluates to vector2 4 201 to 10 map 2 shorthandhuh there just has to be some steps in here i am missing i get that the examples may be leveraging both the function definition and some scala niceties i just do not have enough experience reading scala and making the connecting assumptions yetmy background is as a java oo i am now learning scala and functional programming and this is not the first example like this i have not understood it is just the first one where i felt i had the courage to post knowing i would look ignoranti did try to research this first i went to the scala bible programming in scala 2nd edition and attempted to make sense of if from there pages 1659 then i did a search here on stackoverflow and i found several links that talk around the area but nothing actually shows me stepbystep the connection between a scala highorder function definition and the provided examples in a way that maps to the particular instance in this slideheres what i found on stackoverflowscala workshop advicemore on generic scala functionsscala how to define generic function parametersi am just now realizing that i skipped google and came straight to stackoverflow hm if you google and find just the right link i would love seeing it i have run out of time to sift through all the google links which use terms like monkeymonad blastomorphisms etc while leaving me even more confused and less likely to try and figure this out,['java'] +255132,how to sha hash in cocoaios given the message and the salt how can i encode it returning the hashed stringi need reproduce the php functionhash hmacsha256messagesaltthanks,"['objective-c', 'ios']" +255154,java iterator concurrency i am trying to loop over a java iterator concurrently but am having troubles with the best way to do thishere is what i have where i do not try to do anything concurrentlylong l iteratorlong i getuseridswhile ihasnext l inext someobjectdosomethingl anotheobjectdosomethinglthere should be no race conditions between the things i am doing on the non iterator objects so i am not too worried about that i would just like to speed up how long it takes to loop through the iterator by not doing it sequentiallythanks in advance,['java'] +255161,text field glowing effect like twitter and tumblr login pages whats the best way to achieve a glowing effect when focusing on a text field in html can it be done with css alone or does it involve images check out the login pages for twitter and tumblr for working examples,"['html', 'css']" +255181,android mapsfailed to find style mapviewstyle in current theme i am trying to use maps in my application and i get this errorfailed to find style mapviewstyle in current themei have generated the key properly and have tried all solutions offered for the same problem at other places1my target api and the one mentioned in the manifest file are the same2there is no importr in my project3i have cleaned my project4useslibrary element is a child of the applicationthis is my xml filelinearlayout xmlnsandroid androidlayout widthmatch parent androidlayout heightmatch parent androidorientationvertical comgoogleandroidmapsmapview androidididmapview1 androidlayout widthmatch parent androidlayout heightmatch parent androidclickabletrue androidapikey androidenabledtrue linearlayoutand this is my corresponding java filepackage comepidemicatorprototypeimport androidosbundleimport comgoogleandroidmapsmapactivitypublic class mapacti extends mapactivity public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmapview override protected boolean isroutethisplayed todo autogenerated method stub return false please help me out herethanks,['android'] +255190,aggregate function in mysql list like listagg in oracle i need function that returns list of stringsi have data in table like thisid mystring 1 first 2 second 3 third 4 fourthi need function like this something like this works in oracleselect listaggmystring as mylist where id 4that returns something like thismylistfirst second thirdany ideas,['mysql'] +255196,simple javascript physics engine is there a simple javascript physics engine available that can handle some simple 3d scenariosi am aware of the box2d implementation but i do not think that can do what i need in essence i want to simulate the behavior of a ball as it interacts with a hole like putting in golf where depending on the speed the ball can spin around the hole etc,['javascript'] +255203,how to define a move constructor i am trying some new c11 features on visual studio 11 started with the move constructor i wrote a simple class called myclass containing a move constructorclass myclasspublic explicit myclass int aicount mpisize new int aicount misize2 aicount myclass myclass rcother mpisize rcothermpisize misize rcothermpisize rcothermpisize 0 rcothermisize 0 myclass delete mpisize private int mpisize int misize2i got there questions here i assumed that the compiler would generate a move constructor for myclass if i do not implement one but it does not seems so is the implementation of the move constructor correct for myclassis there a better way to implement the move constructor for myclass,['c++'] +255243,how to create an android activity and service that use separate processes i have an android app that consists of an activity and a service currently they both exist in the same process and use the same heap but i want have to separate processheap for the service ie i want the service to be completely independent of the activity so that if the activity crashes it would not affect the service i do however want them to be installable as a single application is this possible,['android'] +255249,read mp3 in python 3 what i want to do is simplymp3 read mp3mp3 filenameaudio left mp3audio channels0where audio left will contain raw pcm audio datai was looking at play a sound with python but most of the suggested modules are not ported to python 3 yet if possible i would like to avoid having to install a fullyfledged game dev libraryi am a complete python beginner so i would like to start off using python 3,['python'] +255284,include jfactory class in an external php file joomla i am writing a module for joomla at this point i really need to be able to connect to the database using jfactory normally one could simply use db jfactorygetdbo but the php error tells me the jfactory class is not included so now i need to know how to include this jfactory class i have tried a couple of suggestions found on the internet absent success yet this is the code it works perfect on standalone php server infoserver localhostuser sspass oodb ssconnection mysql connectserver user pass or die could not connect to server n mysql error mysql select dbdb or die could not connect to database n mysql error ifisset postusernameusername postusernameusername mysql real escape stringusernamesql check mysql queryselect username from users where usernameusernameifmysql num rowssql checkecho font colorcc0strongusernamestrong is already in usefontelseecho oki hope my problem is clear to you your help will be much appreciated attempt 1phpincludeconfigurationphpincludelibrariesjoomlafactoryphpconfig jfactorygetconfig server infoserver2 hostuser2 userpass2 passworddb2 dbconnection mysqli connectserver2 user2 pass2 or die could not connect to server n mysqli error mysqli select dbdb2 or die could not connect to database n mysqli error ifisset postusernameusername postusernameusername mysql real escape stringusernamesql check mysql queryselect username from users where usernameusernameifmysql num rowssql checkecho font colorcc0strongusernamestrong is already in usefontelseecho okbut this is not working eitherattempt 2 successfulincludeconfigurationphpjc new jconfigtable usersusers jcdbprefix table connect to the databasemysqli new mysqlijchost jcuser jcpassword jcdbnow it is all working as i want the only thing is now safety i am not too sure about this being hacker proof can someone review this thanks,"['php', 'mysql']" +255289,php library for amazon s3 with local fallback is there a library out there for php to access amazon s3 that will let me use the exact same code to either readwrite s3 buckets or to do the same with local filesi would like to use s3 but i need a way to run my application locally for testingif there is not a library that directly supports switching to a local filesystem is there one that is written in a good oop manner so that i could use the same interface to make a local filesystem version of iti am using symfony2 so if there are bundles for this that would be a plus but i can always make it a bundle myselfupdatei am trying to make a bundle now to do this i just need the operations create exists and delete so i made an interface to handle that then i have a local implementation and an s3 implementationwhats a clean symfony2 method of allowing another class to access some service by id and get either the localstorage or the s3storage class depending on a config parameter i thought about using a class parameter but my s3 service has a dependency on the underlying amazons3 class using the aws bundle,['php'] +255298,how identify which bluetooth device causes an action acl connected broadcast i want to listen for connectionthisconnection with a number of specific bluetooth devices whose mac addresses i know but which are not necessarily paired i do not want to mess with the users list of paired devices and vice versa i am only interested in thiscovering their presence not communicating with themthis works very well with my code below but my problem is that i cannot find out which specific device is connectingthisconnecting only that it happens to someone of them how can i find out which one the action concernsfirst i instantiate objects for my two specific physical bluetooth devices and add them to my intent filter bluetoothdevice mypinkheadset mbluetoothadaptergetremotedevice18170ceb9c81 bluetoothdevice mypcbluetoothdongle mbluetoothadaptergetremotedevice5a7acc4bc508 intentfilter intentfilter new intentfilter intentfilteraddactionmypinkheadsetaction acl connected intentfilteraddactionmypinkheadsetaction acl thisconnected intentfilteraddactionmypcbluetoothdongleaction acl connected intentfilteraddactionmypcbluetoothdongleaction acl thisconnectedthen i listen for broadcasts about them final broadcastreceiver intentreceiver new broadcastreceiver public void onreceivecontext context intent intent string action intentgetactionnow i want to find out which one has been connected andor thisconnected and i do not see how i can do thateither 1 i use bluetoothdevice directly it reacts to the broadcast alright but it does not tell me which of the two physical devices the action concerns is their a way to find out bluetoothgetname is not allowed because it is not a static classif bluetoothdeviceaction acl connectedequalsaction or 2 i listen for both actions for both devices if mypinkheadset action acl connectedequalsaction logvtag connected to mypinkheadset else if mypinkheadset action acl thisconnectedequalsaction logvtag thisconnected from mypinkheadset else if mypcbluetoothdongle action acl connectedequalsaction logvtag connected to mypcbluetoothdongle else if mypcbluetoothdongle action acl thisconnectedequalsaction logvtag thisconnected from mypcbluetoothdongle but then it logs that it connects with mypinkheadset even if it is mypvbluetoothdongle i activate physically it always goes for the one which comes first of the if tests it cares only about the action itself not about which object it concernsi saw that extra device is used as a parcelable bluetoothdevice extra field in every intent broadcast by this class but it only returns null to mestring extra intentgetstringextrabluetoothdeviceextra device,['android'] +255315,c global variable not initialized when linked through static libraries but ok when compiled with source i have created a system that automatically registers function objects functors into a map based on the constructor of an global instancein each cpp file that defines the functor there is a global instance of the registrar class instance to register the functor to a singleton stdmapint stdfunction objectthis is the definition of registrar classtemplate typename map type typename handler typestruct registrar registrar map type map object boostuint16 t cmd code const handler type handler map objectinsertstdpairboostuint16 t handler typecmd code handler in each cpp file the global instance is defined like thisnamespace one way static registrar in out map type handler post receiverin out map typeinstance command handlersall works fine if i compile all the cpp with the maincpp together but if i compile the cpp file into a static library and link it to maincpp the registration does not worki tested with vc10 and gcc461 both on windows and ubuntu 10 both faili found a thread with the same problem but op did not say whether he solved it or notam i missing anythingeditthanks for all responses including the comments every response indeed helped me to think more and investigate deep into this method after all the study and trials i finally gave up the idea of relying on globalstatic variable for selfregistration across binary boundaries because there is no portable way to guarantee it will work my final way is to keep the registration within one binary,['c++'] +255324,what is the difference between char a string and char p string as the heading says what is the difference between char a string and char p string this question was asked to me in interviewi even dont understand the statementchar a stringhere what is operator is it a part of a string or it has some specific meaning,['c++'] +255325,output redirection with screen command might be a simple problem but i am running centos 54 command line remotely i want to redirect the output of a simple java file lets say loop to print a hundred thousand numbers in console to a text file the thing is i have to use the screen command to be able to run it in background even if i loose my session with the remote computer and this command does not write to the desired file i tried the method screen java myclass logtxt also screen java myclass logtxt but it does not write to the file why is this happening and is there any solution thanks,['java'] +255344,aspnet mvc global error handling i have a custom handleerror attribute that deals with errors on the mvc pipeline i have an protected void application errorobject sender eventargs e method on my globalasax which handles errors from outside the pipelinei have come across an scenario i did not know was possible in implementing di there is a dependency for a connectionstring which is taken from the application configuration fileas the connection string did not exist yet an error raises when creating the controller this usually makes the application error handler fire and a proper error page is rendered through rendering a partial view as string and sending it as the response and in case this fails it just writes fatal exception to the responseexcept in this case i get the fugly default aspnet runtime error yellow screen of death telling meruntime error description an application error occurred on the server the current custom error settings for this application prevent the details of the application error from being vieweddetails to enable the details of this specific error message to be viewable on the local server machine please create a tag within a webconfig configuration file located in the root directory of the current web application this tag should then have its mode attribute set to remoteonly to enable the details to be viewable on remote machines please set mode to offi do not have a defaultredirect set in my customerrors nor is it turned off because i do not want to redirect but to render errors on the same page the user is in avoiding a needless redirecthow can i handle an scenario such as this and whats even the reason why it behaves this way and not like any other error outside a controlleri realize it is not likely to happen often but i would like being able to stop the ysod partly because i want to hide the technology i am using but mostly because it is not pretty nor user friendly at alli even tried registering a handler for unhandledexceptions but it did not fire eitherappdomaincurrentdomainunhandledexception currentdomain unhandledexceptionthe code that ultimately produces this isreturn configurationmanagerconnectionstringskeyconnectionstring where connectionstringskey is nullupdatethis is how applicaion errors are handled protected void application errorobject sender eventargs e thishandleapplicationerrornew resourcecontroller public static void handleapplicationerrorthis httpapplication application basecontroller controller if application null throw new argumentnullexceptionapplication if controller null throw new argumentnullexceptioncontroller applicationresponseclear exception exception applicationservergetlasterror logapplicationexceptionapplicationresponse exception try renderexceptionviewresponseapplication exception controller catch exception exceptionrenderingview now were in trouble let us be as graceful as possible renderexceptiontextresponseapplication exceptionrenderingview finally applicationserverclearerror private static void logapplicationexceptionhttpresponse response exception exception if exception is httpexception httpexception httpexception httpexceptionexception if httpexceptiongethttpcode inthttpstatuscodenotfound logdebugresourceserrorwebresourcenotfound httpexception responsestatus resourcesconstantsnotfound return logerrorresourceserrorunhandledexception exception private static void renderexceptionviewresponsehttpapplication application exception exception basecontroller controller if renderasjsonresponseapplication resourcesuserunhandledexceptionjson errorviewmodel model webutilitygeterrorviewmodelexception string result controllerrenderviewtostringresourcesconstantserrorviewname model applicationresponsewriteresult private static void renderexceptiontextresponsehttpapplication application exception exceptionrenderingview applicationresponseclear if renderasjsonresponseapplication resourcesuserfatalexceptionjson applicationresponsewriteresourcesuserfatalexception logfatalresourceserrorfatalexception exceptionrenderingview private static bool renderasjsonresponsehttpapplication application string message if applicationrequestisajaxrequest applicationresponsestatus resourcesconstantshttpsuccess applicationresponsecontenttype resourcesconstantsjsoncontenttype applicationresponsewritemessage return true return false this is the attribute i use to decorate my base controllerpublic class errorhandlingattribute handleerrorattribute public type loggertype get set public errorhandlingattribute thistypeoferrorhandlingattribute public errorhandlingattributetype loggertype loggertype loggertype public override void onexceptionexceptioncontext filtercontext if filtercontextexceptionhandled return if filtercontexthttpcontextrequestisajaxrequest onajaxexceptionfiltercontext else onregularexceptionfiltercontext internal protected void onregularexceptionexceptioncontext filtercontext exception exception filtercontextexception ilog logger logmanagergetloggerloggertype loggererrorresourceserrorunhandledexception exception filtercontexthttpcontextresponseclear errorviewmodel model webutilitygeterrorviewmodelexception filtercontextresult new viewresult viewname resourcesconstantserrorviewname viewdata new viewdatadictionarymodel filtercontextexceptionhandled true internal protected void onajaxexceptionexceptioncontext filtercontext exception exception filtercontextexception ilog logger logmanagergetloggerloggertype loggererrorresourceserrorunhandledajaxexception exception filtercontexthttpcontextresponseclear filtercontexthttpcontextresponsestatus resourcesconstantshttpsuccess string errormessage webutilitygetuserexceptionmessageexception true filtercontextresult new exceptionjsonresultnew errormessage filtercontextexceptionhandled true and this is my customerrorscustomerrors modeon as you can see these are pretty extensive however they do not even fire in the case of accessing the connectionstrings where the connectionstring does not exist which is kind of puzzlingit does fire in any controller contained exception or exceptions not within a controller so i do not understand why this case is any different,['c#'] +255348,media player looping android i am having 3 secs of mp3 file i want to play that mp3 file continuously still the user click pause button is there any method to loop the single file and play it again again till user pauses it,['android'] +255355,using instruments to work through low memory warnings i am trying to work through some low memory conditions using instruments i can watch memory consumption in the physical memory free monitor drop down to a couple of mb even though allocations shows that all allocations is about 3 mb and overall bytes is 34 mb i have started to experience crashing since i moved some operations to a separate thread with an nsoperationqueue but i was not using instruments before the change nevertheless i am betting i did something that i can undo to stop the crashesby the way it is much more stable without instruments or the debugger connectedi have the leaks down to almost none maybe a hundred bytes max before a crashwhen i look at allocations i only see very primitive objects and the total memory reported by it is also very low so i cant see how my app is causing these low memory warningswhen i look at heap shots from the start up i do not see more than about 3 mb there between the baseline and the sum of all the heap growth valueswhat should i be looking at to find where the problem is can i isolate it to one of my view controller instances for example or to one of my other instances what i have donei powered the device off and back on and this made a significant improvement instruments is not reporting a low memory warning also i noticed that physical free memory at start up was only about 7 mb before restarting and its about 60 mb after restartinghowever i am seeing a very regular periodic drop in physical free memory dropping from 43 mb to 6 mb an then back up to 43 mb i would like to knwo what it causing that i do not have any timers running in this app i do have some performselectorafterdelay but those are not active during these testsi am not using arc,['ios'] +255363,where does h2s embedded databases store the data so i just recently started learning about how databases work how to use sql ect and decided to start implementing an embedded database into my java application specifically the h2 database and seemed to work fairly well on the computer i was coding onwhen i moved over to a different computer to continue my coding i noticed that even if i ported the embedded database file h2jar all of the prepared tables i created in the first computer do not exist on the second one i somehow had the preconception that the actual data generated through the database engine are also stored in the embedded database fileso my question is where is the data from the database actually stored is it possible to prepare a database which already contains thousands of records and thistribute it with the actual application i should also mention that the way i connect to the database on the first computer was through a jdbc connection ie the url jdbch2test and when i tried to connect to that database on the second computer it did not existthanks,['java'] +255369,login session not transferring to new webpage using webrequestresponse ok i have been racking my brain on this one solo for too long i have been unable to crack it even with hours spent on this and many other sitesessentially i am trying to strip some data from a webpage behind a login page using webrequestresponse i have gotten this to work using a webbrowser control with some layered events which navigate to the different web pages but it is causing some problems when trying to refactor not to mention it is been stated that using a hidden form to do the work is bad practicethis is what i have string formparams stringformatj username0j password1 username userpass string cookieheader webrequest request webrequestcreate signinpage requestcontenttype textplain requestmethod post byte bytes encodingasciigetbytesformparams requestcontentlength byteslength using stream os requestgetrequeststream oswritebytes 0 byteslength webresponse response requestgetresponse cookieheader responseheaderssetcookie webrequest getrequest webrequestcreatesessionhistorypage getrequestmethod get getrequestheadersaddcookie cookieheader webresponse getresponse getrequestgetresponse try using streamreader sr new streamreadergetresponsegetresponsestream textbox1appendtextsrreadtoend catch exception ex messageboxshowexmessage throw so far i am able to get to the proper page from the first link but when i go to the second it sends me back to the login page as if i did not log inthe problem may lie in cookies not getting captured correctly but i am a novice so maybe i am just doing it wrong it captures the cookies sent back from the post jsessionid and s2v however when we go to the get using firefox webconsole the browser shows that it sends jsessionid s2v and a spring security remember me cookie which i believe is the cookie used when i click the remember me box on the login formi have tried many different ways of doing this using the resources of so but i have yet to get to the page i need so for the sake of the hair i have left i have decided to ask for help on good ole so this is one of those things i do not want to let up on stubborn like that sometimesif someone wants the actual address of the site i am trying to log into i would be more than happy to send it to a couple people in a private messagecode that i have to reflect a suggested answer by walvar request httpwebrequestwebrequestcreatesessionhistorypagerequestcredentials new networkcredentialusername userpassrequestcookiecontainer new cookiecontainerrequestpreauthenticate truewebresponse getresponse requestgetresponsetry using streamreader sr new streamreadergetresponsegetresponsestream textbox1appendtextsrreadtoend catch exception ex messageboxshowexmessage throwthis suggestion at least the way i implemented it did not workas krizz suggested i changed the code to use cookiecontainer and transferring the cookies from one request to the other however the response just gives me back the original login page as if i did not loginare there certain sites that just will not allow this type of behaviorfinal solutionthe final solution was proposed by adrian iftode where he stated that the website i am trying to log in might not allow to have an authentication without a valid session so adding a get to the beginning of the process allowed me to get that cookiethanks for all your help guys,"['c#', '.net']" +255384,symfony2 and anonymous access to some route with this configurationfirewalls login pattern login anonymous security false foo pattern foo anonymous security false secured area pattern form login login path login check path login check logout path logout target access control path roles role admin path foo roles is authenticated anonymously i want to be able to make foo anonymously accessible however when i try to go there even after clearing the cache it would not allow me to and redirects to login screenhow do i make one route to be anonymously accessible while retaining the rest of the system to be secured,['php'] +255432,can i create a custom configuration qualifier for android i know that i can use the android configuration qualifiers for different screen sizes and different orientations i am using android 22but i need to build my app to a very specific tablet with its unique screen sizeresolutioncan i have another configuration qualifier for my specific tablet so whenever one runs my app using that tablet it will get its layoutdimentsions etc from that specific configuration qualifierfor example i want to have a directory named drawablespecialtablet and valuesspecialtablethow can i do it,['android'] +255475,get element an observable is bound to with knockout this is not an ideal situation but due to another knockout binding i am using i am in a situation where i am needing to get the element an observable is bound to if it is indeed bound to anythingso is there a way to do this update i did not want to add any extra context incase it confuses the question but as it may get an answer more in line with expectations here is the scenarioi am using the knockout validation binding which exposes all the errors using the kovalidationgroupmodel method however the problem is that only gives you the textual errors it does not give you any context as to what part of the model gave you those errors so i have made a small change to the source to now pass back the observable tied to each error as this may be useful for a few scenarios but from here i need to be able to tie this to an element so i can thisplay some inline validation of some kindknockout validation provides a very basic inline validation where it creates a span after your element and you can give it a class but this is too basic for my needs as currently we are using qtip and other notification systems to thisplay validation errors and because of this i need to be able to have a dom element and an error so far i have an observable and an error but i need to tie that observable object which could be any koobservable property from the model to its given dom element if it does have an element bindingas all i have is an object and i am using validation driven from the model not the ui the problem is not really going to be solved via a custom binding ideally i need to be able to crack open the marry up the observable object an unknown koobservable to an elementnot to go too project specific but my current project abstracts validation where events are fired off ie eventsystemsendeventvalidationeventsvalidationfailed element error then a validation system listens for these events and ties the error to the element be it a tooltip a growl style notification an alert box etc so i am trying to find the best way to keep this abstraction when driving the validation from the models observables not the uis dom elements ie jqueryui edit 2 i was a bit thrown by the way knockout validation knows the elements for observables to put in its own validation elements however they just piggy back off the existing value binding so i am just going to change that to add the elements for any validation elements based on their isvalidatable method at least that way for each error i can tie it to an observable and for any observables with element bindings i can tie them to the elements and if there are none then it is fine they would just be form wide validation errors i will give this a try as this should be something like not tested yetifutilsisvalidatablevalueaccessor valueaccessorextendhaselementalbinding true elementalbinding elementelse valueaccessorextendhaselementalbinding falseat around line 250 in the registervaluebindinghandler i will leave this question open for a while longer incase someone else has a better solution,['javascript'] +255524,exception during lock possible duplicatein c does a locked object stay locked if an exception occurs inside it what happens when you have code such as this lockmylock try some code catchsomeexception e throw e will mylock get released properly i have a situation where this is necessary so how would i go about it short of writing my own lock that has an explicit release method i can call in the try catchs finally method,['c#'] +255558,why does sync add and fetch work for a 64 bit variable on a 32 bit system consider the following condensed code compile gcc pthread m32 ansi xc include stdiohinclude inttypeshinclude pthreadhstatic volatile uint64 t v 0void func void x sync add and fetch v 1 return xint main void pthread t t pthread create t null func null pthread join t null printf v priu64n v return 0i have a uint64 t variable that i want to increment atomically because the variable is a counter in a multithreaded programto achieve the atomicity i use gccs atomic builtinsif i compile for an amd64 system m64 the produced assembler code is easy to understand by using a lock addq the processor guarantees the increment to be atomic 400660 f0 48 83 05 d7 09 20 lock addq 0x10x2009d7ripbut the same c code produces a very complicated asm code on an ia32 system m32804855a a1 28 a0 04 08 mov 0x804a028eax804855f 8b 15 2c a0 04 08 mov 0x804a02cedx8048565 89 c1 mov eaxecx8048567 89 d3 mov edxebx8048569 83 c1 01 add 0x1ecx804856c 83 d3 00 adc 0x0ebx804856f 89 ce mov ecxesi8048571 89 d9 mov ebxecx8048573 89 f3 mov esiebx8048575 f0 0f c7 0d 28 a0 04 lock cmpxchg8b 0x804a028804857c 08 804857d 75 e6 jne 8048565 func0x15here is what i do not understandlock cmpxchg8b does guarantee that the changed variable is only written if the expected value still resides in the target address the compareandswap is guaranteed to happen atomicallybut what guarantees that the reading of the variable in 0x804855a and 0x804855f to be atomicprobably it does not matter if there was a dirty read but could someone please outline a short proof that there is no problemfurther why does the generated code jump back to 0x8048565 and not 0x804855a i am positive that this is only correct if other writers too only increment the variable is this an implicated requirement for the sync add and fetch function,['c'] +255579,cocos2dx literatue i want to use cocos2dx for my games so i want to read something about it but besides poor official documentation i did not find anythingcan you give some materials on cocos2dxif you no something better than cocod2dx for android ios development please let me knowtnx,"['android', 'ios']" +255586,android http connection refused i am trying to access from an android device over wifi a local web server which i can access from my laptop either on the browser or using curl i can also access the server on the android device browser the code i am using to access the server yields a connection refused exceptionthis is the codepublic void getcontroller1 httpclient httpclient new defaulthttpclient httpget httpget new httpget httpresponse response null systemoutprintlnhttpgettostring try response httpclientexecutehttpget txtviewstatussettextcontroller 1 okresponse catchexception e eprintstacktrace txtviewstatussettextcontroller 1 errore,['android'] +255599,how to encrypt ios files eg pdfs from user access is there a way to secure files downloaded within an app to prevent them from being accessed by the user via a jail broken device or something like iexplorer when the device is plugged into a computer i am primarily thinking of things like pdf files and have considered encrypting them in someway and then storing the data in an sqlite database the other thing i have looked into is nsdatawritingfileprotectioncomplete but that only seems to encrypt data when the phone is lockedany suggestions more than welcome thanks,['ios'] +255606,execution of printf and segmentation fault includestdiohint main char name vikram printfsname name1s printfsname return 0there is no output printed on terminal and just get segmentation fault but when i run it in gdb i get following program received signal sigsegv segmentation fault0x0400525 in main at seg2c77 name1sgdb this means program receive seg fault on 7th line obviously i cannot write on constant char array then why printf of line number 6 is not executed,['c'] +255608,way to make pdf of a storyboard in xcode is there an easy way to make a pdf or image file png jpg jpeg of a full storyboard in xcode 43 to export and send to someone else or post a question on this forum i would just make a screenshot but my storyboard is way too big for my monitor and i would rather not have to manually paste it back together in an image editing program,['ios'] +255611,how do real time strategy games work in php some mmo real time strategy games such as travian or ogame are coded in phpcould you briefly explain how such a game works behind the scenes how does the game make real time db updates without player requests also what kind of server load bandwidth would one have to expect when running a rts game such as travian with 10 active players,['php'] +255629,explode on empty string returns array count as 1 explode on empty string returns array count as 1 consname explodedocdetdoc cons filename countconsnameif there is some value in docdetdoc cons filename like abcdde then countconsname returns 3but its returning 1 if docdetdoc cons filename has empty valueis it possible to return count as 0 if we perform countexplodedocdetdoc cons filename where docdetdoc cons filename can anyone help me with solution,['php'] +255646,button half width of screen i have a single button in a linear layout i want the button to take up half the width of its parent is there a way to do this in the layout xmllinearlayout androidididlinearlayout1 androidlayout widthmatch parent androidlayout heightwrap content androidorientationhorizontal androidgravitycenter horizontal androidpadding6dp button androidididbuttoncollect androidlayout widthwrap content androidlayout heightmatch parent androidtextstringhello androidpaddingleft8dp androidpaddingright8dplinearlayout my question is much like this one assign width to half available screen width declaratively except i only have a single button,['android'] +255666,whats the benefit of using thispatch sync if it has to wait until the main thread completes why would anyone ever use thispatch sync if the block has to wait until the main thread finishes what is the benefit of using this function rather than writing code inline nonblock and outside of grand central thispatch i may be misunderstanding what thispatch sync actually does thanks,['ios'] +255683,how to i undo the vendorgems bundle install i ran bundle install vendorgems and all the gems got saved to the gems directory as expected but when i delete them like rm rf vendorgemsrails s could not find rake0922 in any of the sources run bundle install to install missing gemsi need to run bundle install again and all the gems install to the vendorgems again is there a way to get this behavior to stop and just install as i used to using my rvmrc file and not package the gems in the vendorgems directory,['ruby-on-rails'] +255687,circos style plots with matplotlib does anybody know if there is a way to make circosstyle plots with matplotlib python package or any other python library they do not have to be as nice looking as the example,['python'] +255692,jquery flot tickdate alignment codeexample of my problem goali want the graph to be a bar graph like so but obviously with dates as the x axis if i add my data into that fiddle it messes up like the one listed above as seen here questionswhy are all 3 days provided in the data variable not thisplayingwhy are the bars not lined up with their appropriate xaxis tickswhy does changing the data and mode to time totally mess up what would otherwise be a functional and accurate bar graphenvironmentjquery 171jquery mobile 101flot 07thankslet me know if any additional information is required,['javascript'] +255697,passing params to cancan in ror i have a controller with a method likedef show if paramsformateqlpdf do something elsif paramsformateqlcsv do something endendbut i have users with different roles so i use cancan to manage access controlnow i want x role can do the action show in controller iff paramsformateqlcsvi think it can be like can show resource if paramsformateqlcsv so how can i send parameters to abilityrbany ideathanks,"['ruby-on-rails', 'ruby']" +255707,ios5 please help finding cicolormatrix example i am trying to find out how to change the colorhue of a uiimage i found out that ios5 has a lot of image filters but i have hard time finding documentation on the proper use of the cicolormatrix filter voiddocicolormatrixfilter does not work returns nil image ciimage inputimage ciimage imagewithcgimageuiimage imagenamedbuttonjpgcgimage cifilter myfilter nsdictionary myfilterattributes myfilter cifilter filterwithnamecicolormatrix myfilter setdefaults myfilterattributes myfilter attributes myfilterattributes setvalueinputimage forkeyinputimage how to set up attributes cicontext context cicontext contextwithoptionsnil ciimage ciimage myfilter outputimage cgimageref cgimg context createcgimageciimage fromrectciimage extent uiimage uimage uiimage imagewithcgimagecgimg scale10f orientationuiimageorientationup imageview setimageuimage cgimagereleasecgimgwhat code goes into the dictionary for this filterthank you,"['iphone', 'objective-c']" +255708,python is it worthwhile to invest time in apparently stagnant modules to make it quick and dirty i am a newb programmer whos looking hard at pyglet it looks like a really clean and friendly module to use unlike something like pygame which is even by looking with my own inexperienced eyes a beasthowever pygame is constantly being used updated reused by lots of people and seems to have quite a following pyglet has not been updated since january 2010 most works of art are never finished only abandoned but two years and it is still on v 114 seems troublingso while i might be specifically asking about pyglet vs pygame i am also not because it leads me wonder about other ghostly modules that might be lurking out there that had promise once upon a time but for some reason got dropped or shoved in a corner and are not really relevant are such abandoned projects not worth the time and brainspace investment,['python'] +255804,how do i retrieve the words that i tweeted most i have been reading the developers site of twitter but there is not a method in the resp api for doing that i think it is with the streaming api can someone guide me how to do this i want something similar to tweetstats just show me the most tweeted wordsthanks for answering,['php'] +255812,google maps api v3 markers all share the same infowindow i have been digging around everywhere and i cannot seem to figure this out it is driving me crazy i am a newbie to javascript in general so i cannot quite put a finger on the translation that would fix my issue i noticed that a lot of people have this problem but they all seem to use more advancedor just confusing code than i anyway here goesi have been having the problem where all of my markers share the same contentfunction initialize var myoptions center new googlemapslatlng34151271 118449537 zoom 9 maptypeid googlemapsmaptypeidroadmap maptypecontrol false streetviewcontrol false pancontrol false zoomcontrol true zoomcontroloptions style googlemapszoomcontrolstylesmall var map new googlemapsmapdocumentgetelementbyidmap canvas myoptionssetmarkersmap clubsvar clubs poop 34223868 118601575 dookietest poop 34151271 118449537 test businessfunction setmarkersmap locations var image new googlemapsmarkerimageimagesimagepng new googlemapssize25 32 new googlemapspoint00 new googlemapspoint0 32var shape coord 1 1 1 20 18 20 18 1type polyfor var i 0 i locationslength i var club locationsivar mylatlng new googlemapslatlngclub1 club2var infowindow new googlemapsinfowindowvar marker new googlemapsmarker position mylatlng map map icon image shape shape title club0googlemapseventaddlistenermarker click function infowindowsetcontentclub3 infowindowopenmap thisi know i am crappy but someone please help me p,['javascript'] +255823,whats the use of icloud thisplay sets when adding icloud support to ios app one can configure icloud thisplay set and link it with an app by specifying nsubiquitousthisplayset but icloud works even without it so my question is whats the purpose of icloud thisplay sets at allcould not find any clear answer anywhere in the docs and whats more based on the apple docs it seems as if specifying thisplay set for your app was mandatory if you use icloud that did confuse me a bitit is so that one might want to share the same thisplay set for multiple applications or for ios and mac app versions,"['objective-c', 'ios']" +255876,android unable to remove the color at the top and bottom i have added a scrollview and if deploy on the android tabletit has some problems but it works fine on cellphonewhen users move to the top or bottom of the whole pageit will automatically show the blue shadow which indicates users reaching the bottom of the page i want to remove those indicator since it affects the uiis there any way to remove or set in the xmli have tried different parameter to set on the scrollview but it does not workplease help,['android'] +255880,favourite content is not shown correctly on webview i am developing a language dictionary app i save the favourite word into preference the favourite content in the xml file looks like the followingxml version10 encodingutf8 standaloneyes map string namehistory dict name160170hidict name157140hemandict name184774jetdict name34527black string string namewaitingtime 0 string boolean namesavefavourite valuetrue string namedefaultdictionary dict name string string namefavourite dict name149271godict name25481backdict name184774jet string boolean namesavehistory valuetrue mapi use the following code to load the favourite content into the webviewpublic class user extends activity private static final string favourite tag mydict favouriteview private static final string content tag null private listview mlstfavourite null private arrayliststring lstdict null private arraylistinteger lstid null private arrayliststring mwordfavourite null private arrayadapterstring aptlist null private sharedpreferences prefs override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutfavourite prefs preferencemanagergetdefaultsharedpreferencesgetapplicationcontext if prefsgetbooleansavefavourite true string strfavourite prefsgetstringfavourite logifavourite tag favourite loaded if strfavourite null strfavouriteequals mwordfavourite new arrayliststringarraysasliststrfavouritesplit else mwordfavourite new arrayliststring else mwordfavourite new arrayliststring logdfavourite tag mwordfavourite mwordfavouritesize mlstfavourite listview findviewbyidridlstfavourite imagebutton btnclear imagebutton findviewbyidridbtnclear imagebutton btnbacktocontent imagebutton findviewbyidridbtnbacktocontent if lstdict null lstdict new arrayliststring lstid new arraylistinteger aptlist new arrayadapterstringgetapplicationcontext rlayoutcustomlist lstdictclear lstidclear aptlistclear if mwordfavourite null mwordfavouritesize 0 try for int i 0 i mwordfavouritesize i logifavourite tag item mwordfavouritegeti string arrpart mwordfavouritegetisplit if arrpartlength 3 logicontent tag loaded content arrpartlength wordid arrpart1 logicontent tag loaded 0 lstdictaddi arrpart0 logicontent tag loaded 1 lstidaddi integerparseintarrpart1 logicontent tag loaded 2 aptlistaddarrpart2 else logifavourite tag wrong entry mwordfavouritegeti catch exception ex logifavourite tag wrong entry found logicontent tagadapter size aptlistgetcount assign result return mlstfavouritesetadapteraptlist mlstfavouritesetonitemclicklistenernew adapterviewonitemclicklistener public void onitemclickadapterview arg0 view v int arg2 long arg3 medwordsettextmadaptergetitemarg2 intent i new intent iputextradict lstdictgetarg2 iputextrawordid lstidgetarg2 setresultresult ok i finish btnclearsetonclicklistenernew viewonclicklistener override public void onclickview v todo autogenerated method stub mwordfavouriteclear aptlistclear mlstfavouritesetadapteraptlist sharedpreferenceseditor editor prefsedit editorputstringfavourite editorcommit setresultresult ok finish btnbacktocontentsetonclicklistenernew viewonclicklistener override public void onclickview v setresultresult canceled finish the favourite content is successfully loaded the favourite words are listed in the webview but the problem is that it only shows the definition of the latest word added to the favourite regardless of what word is chosen for exampleword1word2word3despite word1 andor word2 is selected for meaning the definition of the last word which is word3 is always shown my purpose is to thisplay the definition of word1 when word1 is selected and the definition of word2 when word2 is selected and so on and so forth i save my dictionary data in sqlite databasecan anybody there help to solve this problem,['android'] +255888,integrated database for my javase application i do not know if its right place to ask this question or not but i am asking herewhat i have tried till now in all my projects in javase swings javafx etc i have used mysql oracle ms sql server for my backendbut for any of these i need to install an individual software like mysql server etci was wondering if it is possible to get some alternative of this thing so that i do not need to install any extra individual software for databasedatabase should be integrated within my javase application like we see in normal softwares we just install the software not the individual dbms for itsuch a database that allows me to take backupany suggestions for this,['java'] +255902,get pitch yaw roll from a cmrotationmatrix i have a cmrotationmatrix rot and i would like to get the pitch yaw roll from the matrixany ideas how i could do thatthanks,['ios'] +255912,suddenly application crash fatal execution engine error 7a0bc59e 80131506 completely random and suddenly our application crashes on its production environment the application runs on windows xp and net framework 35 sp1 in the application we provide a wcf service and we use the serial portwhen the application crashes it leaves messages in the application lognet runtime version 20507273625 fatal execution engine error 7a0bc59e 80131506 for more information see help and support center at andfaulting application exe version 10 stamp 4f48b8fc faulting module mscorwksdll version 20507273625 stamp 4e154c98 debug 0 fault address 0x0a03eafor more information see help and support center at on our test environment we do have similar problemson the internet i find several identical problems all mention hot fixes or reinstalls but i want to know what happens and do not want happens does anyone knows what happens and how we can fix iteditbesides the application also sophos antivirus and mysql is installededit 2in our application we use a clibrary wrapped in a net package we use the library in more applications and in those it does not give the exceptionsedit 3 cannot answer my own questionwell i found something958481 list of the issues that are addressed by the application compatibility update for the net framework 20 service pack 2 in the net framework 35 sp1 because of the changes that are made in checking a null value to support address space layout randomization aslr a failure case causes an access violation in the runtime this access violation manifests as an executionengineexception exception additionally the process is terminatedthisplaylangenid106,"['c#', '.net']" +255924,highcharts hide series name from the legend i try to solve this problem several times and give up now when i have met him again i decided to ask for some helpi have this code for my legendlegend layout vertical align right verticalalign top x 10 y 100 borderwidth 0 labelformatter function ifthisnameseries 1 return thisname else return legend if i change the return from legend to the text is not shown but still there is a dash on the top of the legend if i do not use label formater function i have series 1 dash like a first row in my legend how to hide themplease note my version is highcharts205this is a simple view of my legend and the dash i want to remove,['javascript'] +255942,rmagick imagemagick gives error no decode delegate for this image format the problem occurs when i try to manipulate an image uploaded from sinatra fileopenparamsfiletempfile do p thumb magickimagereadp thumbcrop resized75 75 magicknorthgravityendthe uploaded file is a jpeg form data when uploading image includesfilename299732 176749115737355 102068035867 380115 618512842 njpg typeimagejpeg namefile tempfilefilevarfoldershfd6vx6vg56nbd5n44jjrp84k80gntrackmultipart20120228559471fd2l6c headcontentthisposition formdata namefile filename299732 176749115737355 102068035867 380115 618512842 njpgrncontenttype imagejpegrnand also imagemagick has the necessary delegatesconvert list configurereturnsdelegates bzlib freetype jpeg jng jp2 lcms png tiff x11 xml zlibso i should be able to upload and transform a jpeg but it whines about delegatesalso i am working on mac osx 107 maybe another weird problem with mac,['ruby'] +255954,tomcat 7 setenvsh is not found i downloaded and extracted the apachetomcat70 as per the instructions in the runningtxt catalina baserunningtxt it should set the jre home in the setenvsh filewhere is this file located documentation said it would be in catalina homebin directory however this file is not present there,['java'] +255980,set margin in style and apply that style to textview programmatically in my application i want to set top and bottom margin of 8 dip to a textview so if i do it like textviewandroidididtv text1androidlayout widthwrap contentandroidlayout heightwrap contentstylestylesettings plain textit works fine where the style contents are style namesettings plain text item nameandroidlayout margintop 8dip item item nameandroidlayout marginbottom 8dip item item nameandroidtextsize 18sp itemstylebut when i apply the same style to that textview programmatically like textviewsettextappearancecontext rstylesettings plain textit does not show the top and bottom margin that i have set in styleplease help,['android'] +255985,how to horizontal center a form using bootstrap hi there i am trying to position a login form in the middle of the screen using bootstrap 2 i have tried several combinations using offset etc but i do not seem to have anu luckdiv classrowfluid form action methodpost idloginform classformhorizontal autocompleteoff formdivany suggestions on how i can achieve this,['html'] +255997,python create dictionary from list of dictionaries i have a list of dictionaries in pythonid1 name test 1 slug test1id2 name test 2 slug test2id3 name test 3 slug test3id4 name test 4 slug test4id5 name test 5 slug test4i want to turn this list into a dictionary of dictionaries with the key being slug if the slug is duplicated as in the example above it should just ignore it this can either be by copying over the other entry or not bothing to reset it i am not bothered as they should be the sametest1 id1 name test 1 slug test1test2 id2 name test 2 slug test2test3 id3 name test 3 slug test3test4 id4 name test 4 slug test4what is the best way to achieve this,['python'] +256023,argmax of numpy array returning nonflat indices i am trying to get the indices of the maximum element in a numpy arraythis can be done using numpyargmax my problem is that i would like to find the biggest element in the whole array and get the indices of thatnumpyargmax can be either applied along one axis which is not what i want or on the flattened array which is kind of what i wantmy problem is that using numpyargmax with axisnone returns the flat index when i want the multidimensional indexi could use divmod to get a nonflat index but this feels ugly is there any better way of doing this,['python'] +256099,ideal way to organize java constants we have a huge projects based on an old jdk 14 we have migrated the web app to jdk 16 but still lot of inefficient practices and bad design exist in the codeon of the major pain point huge java classes 2500 lines of code in single java file so many files like thesein an attempt to refactor the classes i had started off by removing constants and putting constants in different constantsjava file but since there are so many constants throughout the application the constants file has the risk of growing to humongous proportionsi would appreciate feedback on what strategy are developers adopting to keep code clean and maintainable,['java'] +256110,what orm bltoolkit is not more popular i search to work with data aces orm faster and speed for fetch and implementationi came across bltoolkit in the ormbattle which seems absolutely amazing in terms of performance speed maintainability and flexibilitybut is not very known is that it is true comparison in if someone have an idea with bltoolkit can help me thanks,['.net'] +256121,is there a way to comment out a large block of code in textmate i do not see anything in the ruby bundle that will help me add comments to a large block of code the links i have found online to such a shortcut do not appear to be valid any more,['ruby'] +256122,how can i multiply a float and a generic type i am programming in unity 342 on os x using ci have a class like the followingclass foot public t dofoot bar float afloatvalue 10f do other stuff return afloatvalue bar when unity compiles this class it gives me this error messageerror cs0019 operator cannot be applied to operands of type float and ti know that the types i provide for t will support multiplication with float how can i implement generic multiplication in this case,['c#'] +256126,sql alchemy orm returning a single column how to avoid common post processing i am using sql alchemys orm and i find when i return a single column i get the results like soresult result 2 etcwith a set like this i find that i have to do this oftenresults r0 for r in results so that i just have a list of result valuesthis is not that bad because my result sets are usually small but if they werent this could add significant overhead the biggest thing is i feel it clutters the source and missing this step is a pretty common error i run intois there any way to avoid this extra stepa related aside this behaviour of the orm seems inconvenient in this case but another case where my result set was id value it ends up like thisresult 1 id result 1 val result 2 id result 2 vali then can just doresults dictresults so i have a map of id to valuethis one has the advantage of making sense as a useful step after returning the resultsis this really a problem or am i just being a nitpick and the post processing after getting the result set makes sense for both cases i am sure we can think of some other common post processing operations to make the result set more usable in the application code is there high performance and convenient solutions across the board or is post processing unavoidable and merely required for varying application usageswhen my application can actually take advantage of the objects that are returned by sql alchemys orm it seems extremely helpful but in cases where i cannot or do not not so much is this just a common problem of orms in general am i better off not using the orm layer in cases like thisi suppose i should show an example of the actual orm queries i am talking aboutsessionqueryormobjcolumn nameallorsessionqueryormobjid column name ormobjvalue column nameallof course in a real query there would normally be some filters etc,['python'] +256130,phpexcel to store entries in an array and thisplay here is the extract of my code that thisplay the excel entries and stores into array the logic is first detect which entry is invalid mark it down then for other valid entry check whether it is duplicate if it is mark it downeventually scan through the whole sheet again retrieve all the entries that is not in that two list duplicate or invalidthe problems of it are1 when i thisplay the table although it can thisplay but it warns me that datatables warningrequest unknown parameter 0 from the data source for row 02 when i store into array it can only store for the first line of rowso i would like to know are there any mistake in my looping logic and had i used the phpexcel to read spreadsheet in a correct way thank you reader phpexcel iofactorycreatereaderreadertypephpexcel readerloadfilesheet phpexcelgetsheet0highestrow sheetgethighestrowhighestcolumn phpexcel cellcolumnindexfromstringsheetgethighestcolumnpatternwazaz27for row 1 row highestrow rowfor head 0 head highestcolumn headtestmail sheetgetcellbycolumnandrowhead rowgetvalueif preg matchpatterntestmailmailcolumnheadifissetmailcolumndieno email column detected please check your file and import againinvaild null email null duplicate null for row 1 row highestrow row for y 0 y highestcolumn y val sheetgetcellbycolumnandrowy rowgetvalue if y mailcolumn preg matchpatternval invaildrow elseif y mailcolumn in arrayvalemail duplicateval duplicaterow elseif in arrayrowduplicate in arrayrowinvaild echo val if y mailcolumn emailval emailarray uniqueemail invaildarray uniqueinvaildforeach invaild as cecho cecho brforeach duplicate as decho ddiv idstylized classviewh1echo file resulth1 pimport from spreadsheet filesp div idcontainertable cellpadding0 cellspacing0 border0 classthisplay idviewimporttheadtrfor head 0 head highestcolumn headif headmailcolumnecho th fieldcolhead email address thelseecho th fieldcolhead unname coloum head thtrtheadfor row 1 row highestrow row echo tr for y 0 y highestcolumn y if in arrayrowduplicate in arrayrowinvaild val sheetgetcellbycolumnandrowy rowgetvalue echo td if val echo else echo val echo td echo tr tabledivi work on this these day but still get this thisplay error thank youenter image description here1,['php'] +256140,finding if a circle is inside another circle i am having a bit of trouble i have an assignment that requires me to find if a second circle is overlapping inside or neither a second circle however i am having trouble checking for overlapping and if the second circle is inside the firstvariables used are x1 x2 y1 y2 r1 r2 thistanceheres what i haveif thistance r1 r2 no overlap systemoutprintlncircle2 does not overlap circle1 else if thistance mathabsr1 r2 overlap systemoutprintlncircle2 overlaps circle1 else if thistance mathabsr1 r2 inside systemoutprintlncircle2 is inside circle1i fear the problem is with the overlapping and inside checks but i cannot figure out how to properly set it up so i can reliably check if the second circle is inside the firstany help or advice would be greatly appreciated as i have tried multiple approaches but the solution simply escapes me every time,['java'] +256149,how to get a full res image from an amazon zoom window i started this just to use as an internal reference for a project and now i am kind of obsessed with it amazon uses a zoom plugin to slice up a large image into pieces and each piece is an image otherviews z 5ieutf8sbooksimg5but i figure somewhere there has to be a full highres image that is not sliced up anyone know how to grab this i can get a small one and i can get all the large pieces but i want to get the complete large image,['html'] +256197,how to make 52week participation bar graphs like github has done i am trying to make bar graphs similar to how github does it for showing how many commits or how many people are watching repositories eg does anyone know what library they used to make it update i wanted to reopen this question if possible reinvestigating this the solutions below while awesome in their own right seem a little too involved for what i am looking fori have switched to using this nice nettuts tutorial which draws a single bar graph but i am having trouble adapting it to draw multiple bar graphs i have made a fiddle where i have manually added code to deal with a 2nd graph but i believe i need some for loops to make this work for a variable number of graphs heres that fiddle might someone be able to edit this fiddle to tackle this question,"['javascript', 'jquery']" +256231,how to make a pure css triangle which has a white center i want to create an upward and downward facing arrow with css like the following however instead of a solid color i want to set it up so the inside is white and there is just a border around the triangle so the triangle would be multicolored one color on the inside and a different colored borderis this possible and if so how can it be done,"['html', 'css']" +256232,return user to previous page after login rails on a rails 238 site i have login links on each page that takes a user to a separate signin page after a successful login the user is currently redirected to root instead i would like to redirect to the page they were previously viewingi have tried using requestrefererredirect back or defaultrequestrefererwhere redirect back or defaultdef redirect back or defaultdefault redirect tosessionreturn to default sessionreturn to nilendbut that generates an access denied error even though the login is successful,['ruby-on-rails'] +256235,websocket django python webservice i was wondering how to create a django webservice responds with xml with websocketsi have already a django webservice which accepts xml requests parse those requests makes a database query creates a response xml and send that xml back to the requesterbrowser just a normal http xml request where the response is shown as xml within the browserbut how would i now create a websocket django webservice lets say i would like to send a xml response to the requesterbrowser with the latest data from database whenever a new magical event occurs i have read a lot of posts and blogs but it was kinda all too general can i solve this only with django apache or do i need something else next to django and another server only to handle websocketsi am right now using django 13 apache wsgi but i would be ready to switch any configuration that would workupdatethere are many possible websockets out there termwebsocketsubmitsearchbut which one could be used in my case,['python'] +256277,prototypal oo with objectcreate and named constructors i am coming to javascript from a background in python and smalltalk and i appreciate the linage of self and lisp in the language with ecmascript5 i wanted to try my hand at prototypal oo without the new operator constraints optional new operator to create classesprototype chain must be correct for instanceofnamed constructors for webinspector debugging supportallocinit creation sequence like objectivec and pythonhere is my attempt at the implementation to meet the criteriafunction subclassclass base use strict function createself args if self instanceof this self objectcreatethisprototype var init self init return init initapplyself args self if base instanceof function base baseprototype else if baseundefined base objectprototype classprototype objectcreatebase classprototypeconstructor class classcreate create classdefine function definename fn return classprototypename fn classdefine name classname return classand it seems to work in a simple mockupfunction familyreturn familycreatethis argumentssubclassfamily objectfamilydefine init function init nthisnamen return thisfunction tribereturn tribecreatethis argumentssubclasstribe familyfunction genusreturn genuscreatethis argumentssubclassgenus tribefunction speciesreturn speciescreatethis argumentssubclaspecies genususing the class as a factory functionvar dog speciesdogconsoleassertdog instanceof objectconsoleassertdog instanceof familyconsoleassertdog instanceof tribeconsoleassertdog instanceof genusconsoleassertdog instanceof speciesor using the new operatorvar cat new speciescatconsoleassertcat instanceof objectconsoleassertcat instanceof familyconsoleassertcat instanceof tribeconsoleassertcat instanceof genusconsoleassertcat instanceof speciesconsoleassertobjectgetprototypeofdog objectgetprototypeofcathave i overlooked needed features of prototypal oo in my implementation are there javascript conventions or interactions i should make changes for in summary what are the gotchas here and are there any obvious improvements to be madei wanted to be dryer with the constructor definitions but i found that a functions name property is not writable and that is what supports the webkit inspectors object names i was able to construct an eval to accomplish what i wanted but yuck,['javascript'] +256283,refused to thisplay document because thisplay forbidden by xframeoptions i am building a facebook app and i have noticed that when attempting to get the login status of the user using their javascript api i sometimes get the errorrefused to thisplay document because thisplay forbidden by xframeoptionsi have been able to reproduce this every time i hit the check login status page of the app only while using facebook as a page rather than my user account this is easy enough to avoid now that i know this causes the problem but obviously my users may not know thisis there a way to determine whether or not the user is using facebook as a page or not since that seems to pretty much ruin my entire app,['javascript'] +256294,is there a list of characters that look similar to english letters iam having a crack at profanity filtering for a web forum written in pythonas part of that iam attempting to write a function that takes a word and returns all possible mock spellings of that word that use visually similar characters in place of specific letters eg sa aaka vara wi expect iall have to expand this list over time to cover peopleas creativity but is there a list floating around anywhere on the internet that i could use as a starting point,['python'] +256312,ctags in sublime text i have just download sublime text 2 beta 2182 under ubuntu 1010 with exuberant ctags 58i want to use it for c coding and i need some auto completition and code navigation i was used to eclipse with cdti googled and i found ctags a cool tool that can do it and there is a plugin support for sublime text herethe problem is that i want create tag file fromc standard lib stdvector stdmap etcall classes of the framework i am usingpoint 1 is i think the same of point 2 i just only have to create a tag list of std lib in my usrincludec445so i have downloaded the plugin and installed it i made a taglist in this way cd absolute path of my cpp framework ctags r i modified homemeconfigsublimetext2packagesctagssctagssublimesettings with this line extra tag files gemtags absolute path of my cpp frameworktagsnow i open a cpp file point the cursor on a class name of my framework and used the key binding ctrlt ctrlt and nothing happened only this message in the bar in the bottomcannot find class namecan someone help me,['c++'] +256315,string parameter in ajaxoption null on submit but showing in response in this piece of codeusing ajaxbeginformmyaction myroutevalues new ajaxoptions onsuccess myjsfunction modelintegerparameter modelstringparameter why does my javascript recognize modelintegerparameter correctly but modelstringparameter as null i am sure it has data on it as i check the response and it shows like thisdataajaxsuccessmyjsfunction1 39a39my view model is really simple and it looks like thispublic class myviewmodel public int integerparameter get set public string stringparameter get set how do i fix thisadded infoi tried changing the second parameter to int now its not passing as null but 0 and still it shows in the response in firebugi added the htmlraw but it still gets a null value in javascripthere is a real world screenshot of what i get in the console responseanother update i tried all the suggestions but it seems to be a bug in mvc sarp i tried in different projects and on different pcs it still happens for me i noticed this only happens if its coming from a model it looks like what happens in between the response to javascript the value of string gets lost regardless whether its the first second or any position in the parameter but if i use a hard coded value such asmyjsfunction modelintegerparameter ai get a successful result also if i use jquery like such myjsfunction modelintegerparameter searchstringvalthis also works but if i do pass a model that is a string like suchmyjsfunction modelintegerparameter modelstringparameter this does not workso is you want to see what really happens on real world where i taken account the suggestions of darin and shark here is a screenshotas you see in the response it is there but when passed to javascript it gets lost here is the real life javascript as wellthisplayresultspopupwindow function model var postdata transactionid modeltransactionid searchstring modelsearchstring postinvoicinggetsearchresults postdata function data windowhelperthisplaywindowadd airline transaction div idmatchbookingresults unescapedataviewhtml div 640 500,"['c#', 'jquery']" +256318,java scannerfile misbehaving but scannerfileinputstream always works with the same file i am having weird behavior with scanner it will work with a particular set of files i am using when i use the scannerfileinputstream constructor but it would not with the scannerfile constructorcase 1 scannerfilescanner s new scannernew filefilewhileshasnextline systemoutprintlnsnextlineresult no outputcase 2 scannerfileinputstreamscanner s new scannernew fileinputstreamnew filefilewhileshasnextline systemoutprintlnsnextlineresult the file content outputs to the consolethe input file is a java file containing a single classi double checked programmatically in java thatthe file existsis readableand has a nonzero filesizetypically scannerfile works for me in this case i am not sure why it does not now,['java'] +256331,stumped by a simple regex i am trying to see if the string s contains any of the symbols in a regex the regex below works fine on rubulars asdds but in ruby 192 it gives this error messagesyntax error unexpected expecting tcolon2 or or s asdd s what is wrong,['ruby'] +256359,is boost threads boostunique lock a scoped lock i understand that variable locked by a boostmutexscoped lock is automatically unlocked when it is out of scopehow about boostunique lock does it automatically unlock the variable when it is out of scopecan anyone also point a reference for that feature as welldouble xboostmutex x mutexvoid foo boostunique lockboostmutex lockx mutex x rand some calculation which takes 10 second is x still locked here thanks,['c++'] +256368,whats the difference between the implements extends keywords in java whats the difference between the following keywords in java implements extends,['java'] +256391,any css or javascript techniques to thisplay a slice of a circle image i am trying to write a program where users upload circular images like this deliciously warm pizzathe user then specifies the start and end of the arc in degrees so that a function will be called to thisplay the same image with a lower opacity on the leftover portionfunction cutpizza startarcdegree endarcdegreethis is where i need help cutpizza150 225are there any css or javascript techniques to help me achieve this or any or ways for that matter,"['javascript', 'css']" +256431,pick a number and name from contacts list in android app i want to pick a contact with it is number from my contacts listi read a lot of solutions and research for couple weeks but all of articles did not work properlysome codes like followingintent intent new intentintentaction pick contactscontractcontactscontent uristartactivityforresultintent pick contact and in activityresultif resultcode activityresult ok uri contactdata datagetdata cursor c managedquerycontactdata null null null null if cmovetofirst string name cgetstringcgetcolumnindexorthrowcontactscontractcontactsthisplay name tv1settextname or this code for getting all contacts but i cant have the number of contactsstring contacts new string peoplename peoplenumber uri contenturi peoplecontent uri cursor cursor managedquerycontenturi contacts null null null string textcontacts if cursormovetofirst string myname null string mynumber null do textcontacts textcontacts cursorgetstringcursorgetcolumnindexpeoplename cursorgetstringcursorgetcolumnindexpeoplenumber n while cursormovetonext tv1settexttextcontactscan anyone help me plz my android is 233,['android'] +256462,how to downsample images within pdf file need a javabased solution or at the worst commandline for linuxi tried to use ghostscriptgs sdevicepdfwrite dpdfa dbatch dnopause duseciecolor sprocesscolormodeldevicecmyk spdfacompatibilitypolicy1 soutputfiledowngradedpdf leon range my12 w22 brochurepdfbut i got a lot of errors,['java'] +256466,widget with content provider impossible to use readpermission so i have just implemented a widget for my app it gets its data from the database through my contentprovider i define my own readwritepermissions in my manifest state that i use them does not seem to make a difference and require them in the content provider define my permissions for the provider permission androidnamecomnononsenseappsnotepadpermissionsread androiddescriptionstringpermission read desc androidlabelstringpermission read label androidpermissiongroupandroidpermissiongrouppersonal info androidprotectionlevelnormal permission androidnamecomnononsenseappsnotepadpermissionswrite androiddescriptionstringpermission write desc androidlabelstringpermission write label androidpermissiongroupandroidpermissiongrouppersonal info androidprotectionlevelnormal usespermission androidnamecomnononsenseappsnotepadpermissionsread usespermission androidnamecomnononsenseappsnotepadpermissionswrite usespermission androidnameandroidpermissionbind remoteviews provider androidnamenotepadprovider androidauthoritiescomnononsenseappsnotepad androidenabledtrue androidexportedtrue androidlabelstringapp name androidreadpermissioncomnononsenseappsnotepadpermissionsread androidsyncabletrue androidwritepermissioncomnononsenseappsnotepadpermissionswrite granturipermission androidpathpattern provideri update my widget through a service as per the widget tutorial list widget receiver androidnamecomnononsenseappsnotepadwidgetlistwidgetprovider intentfilter action androidnameandroidappwidgetactionappwidget update intentfilter metadata androidnameandroidappwidgetprovider androidresourcexmllistwidgetinfo receiver service androidnamecomnononsenseappsnotepadwidgetlistwidgetservice androidexportedfalse androidpermissionandroidpermissionbind remoteviews and that service in turn does this with a bunch of code not included this is the service that provides the factory to be bound to the collection service public class listwidgetservice extends remoteviewsservice overridepublic remoteviewsfactory ongetviewfactoryintent intent return new stackremoteviewsfactorythisgetapplicationcontext intent this is the factory that will provide data to the collection widget class stackremoteviewsfactory implements remoteviewsserviceremoteviewsfactory public stackremoteviewsfactorycontext context intent intent mcontext context observer new listcheckernull mappwidgetid intentgetintextraappwidgetmanagerextra appwidget id appwidgetmanagerinvalid appwidget idpublic void ondatasetchanged logdtag ondatasetchanged refresh the cursor if mcursor null mcursorclose get widget settings sharedpreferences settings mcontextgetsharedpreferences listwidgetconfiguregetsharedprefsfilemappwidgetid mcontextmode private if settings null string listwhere settingsgetstringlistwidgetconfigurelist where null listid settingsgetlonglistwidgetconfigurelist id 1 string sorton settingsgetstringlistwidgetconfiguresort on notepadnotesalphabetic asc order mcursor mcontextgetcontentresolverquery notepadprovidercontent visible uri projection listwhere null sorton so heres the problem when i add the widget to the homescreen a securityexception is immediately thrown inside the ondatasetchanged method when i try to query the provider this appears to be because the homescreen does not hold the permission to read my content provider my intuition was that it would not be a problem since my own app has the permission and the service is obviously a part of my appeverything works beautifully if i remove the readpermission requirement from the provider but that seems like a security problem because then any app can access the provider without the user having to approve anythingso is there a way to use a provider with a readpermission with a widget or are you forced to use an unsecured exported provider,['android'] +256467,how would i sum a multidimensional array in the most succinct python the closest was this one summing columnsso i will do something similar in my questionsay i have a python 2d list as belowmy list 1234 2456 i can get the row totals with a list comprehensionrow totals sumx for x in my list in one line how can i sum the entire 2darray27,['python'] +256484,uisearchthisplaycontrollerawhy does my search result view contain empty cells i am about to go out of my mind here in my core data databse i have a lot of users i have hooked the database up to a tableviewcontroller via nsfetchedresultcontroller and when the view loads i see all my users and i can perform a push to a detail viewcontroller via storyboard segue so far so god my tableview contains a custom cell with an image view and 2 uitextlabels that all has their tag values assignednow when i perform the search i create a new nsfetchedresultcontroller with a predicate and performs the performfetch i then get the fetchedobjects property and it contains the users that match so the search request is also working like a charm in all my tableviews datasources i check if selftableview selfsearchthisplview to see which controller i should query data from in all the controllers delegates i check to see which controller is active so i know which view to reload if i nslog a lot of data it is all fine behind the scenes the delegate and datasource methods all use the correct view and fetchcontrollerin my cellforrowatindexpath i can log out my username and that is always correct also when searchingthe issue is that the uisearchthisplaycontroller view that is on top only has empty cells unless i set my uitableviewcontrollers dynamic prototype cell to basic then both tableviews contain that label with the users name the segue from the cell still does not work but there is data in the cellit seems as the uisearchthisplaycontrollers view is a generic view at least when it comes to segues and cell layouti have checked all the connections from the uisearchthisplaycontroller to my uitableviewcontroller and all looks finewhy will the searchthisplaycontrollers view not accept my cell layout and segue thank you update has just figured out what is going wrong but not found the solution yetin my cellforrowatindexpath the cell is always configured as the default cell when thr searchthisplayview is in this method do i really need to create my cell in code for the uisearchthisplay to work why can it not use the configured cell from the storyboard uitableviewcell tableviewuitableview tableview cellforrowatindexpath nsindexpath indexpath static nsstring cellidentifier personcelluitableviewcell cell tableview dequeuereusablecellwithidentifiercellidentifierif cell nil nslogdefault cell cell uitableviewcell alloc initwithstyleuitableviewcellstyledefault reuseidentifiercellidentifiernsfetchedresultscontroller controller tableview selftableview selffetchedresultscontroller selffetchedresultscontrollerforsearchperson pp controller objectatindexpathindexpath uilabel cell viewwithtag1 settextpname uilabel cell viewwithtag2 settextstatus ifpavatarimage uiimage avatar uiimage alloc initwithdatapavatarimage uiimageview cell viewwithtag3 setimageavatar return cell,['iphone'] +256490,custom views with storyboard in complex screens view controllers i used to separate the whole thing in smaller pieces i call them widgets these widgets consist basically of a mywidgeth and a mywidgetm file as well as a mywidgetxib file where the root element is a uiview and the mywidget class is the file owner of the uiview in the init of this widget i do a loadnibnamedin my view controller i then do a mywidget alloc init which i add to views controller main view as a sub view this so far works perfectlyi am now wondering how to do the same with storyboard because i cannot really start to drag in a uiview somewhere i always have to start with an uiviewcontroller which i do not want toif there is no possible way doing this with a storyboard can i simply do it the old way by using the storyboard for my main screens and segues and use a separate xib file to define custom views,['ios'] +256493,customizing a potentially dangerous requestpath value was detected error page when i call a page with a non authorized character such as i get a yellow page a potentially dangerous requestpath value was detectedit looks like it is a 400 error pagemy goal is to customize this page and show a clean error page or redirect to home page i tried both solutionshere is what i wrote in my webconfigsystemwebserver httperrors errormodecustom remove statuscode400 substatuscode1 remove statuscode404 substatuscode1 error statuscode400 pathpagenontrouveeaspxstatus400 responsemodeexecuteurl error statuscode404 path responsemodeexecuteurl httperrorsi am using iis7the point is my 400 page is still shown as a yellow error page there must be a workaround because although the stack exchange data explorer has this problem with nbsp stack overflow itself does not nbspany ideas,['.net'] +256494,is conversion from unsigned to signed undefined void fun signed int a5 unsigned int b5 printfthe value of b is unb ifab printfsamen else printfdiffit is printing 4294967291samein the 2nd line signed value is converted to unsigned value so b has the value uintmax 1 5 4294967291my question is what is happening in the comparison operation 1 is a again converted to unsigned and compared with b 2 will bie unsigned be ever casted to signed value and compared automatically3 is conversion from unsigned to signed undefined due to int overflow i have read other posts on the topic i just want clarification on questions 2 and 3,['c'] +256514,objective c accessing files in zip without extracting zip i am looking for a way to access files within a zip file without extracting the whole file all the zip solutions i find on the internet seems to extract the whole zip does anyone know of a solution,['objective-c'] +256532,how to compare the java byte array public class bytearr public static void mainstring args byte a byte0x03 byte0x00 byte0x00 byte0x00 byte b byte0x03 byte0x00 byte0x00 byte0x00 byte aa byte0x03 byte0x00 byte0x00 byte0x00 byte bb byte0x03 byte0x00 byte0x00 byte0x00 systemoutprintlna systemoutprintlnb systemoutprintlna b systemoutprintlnaequalsb systemoutprintlnaa systemoutprintlnbb systemoutprintlnaa bb systemoutprintlnaaequalsbb i do not know why all of them print falsewhen i run java bytearray the answer is false false false falsei think the a equals b but the jvm is telling me i am wrong whyi14i14,['java'] +256553,access c function from qml i am trying to make a little program with qt i have a maincpp with the following codeinclude qtguiqapplicationinclude qmlapplicationviewerhq decl export int mainint argc char argv qscopedpointerqapplication appcreateapplicationargc argv qmlapplicationviewer viewer viewersetorientationqmlapplicationviewerscreenorientationauto viewersetmainqmlfileqlatin1stringqmltw looptijden berekenenmainqml viewershowexpanded return appexecint reken tijden uit return trueand i have a qml fileimport qtquick 11rectangle width 360height 360text text qstrhello world anchorscenterin parentmousearea anchorsfill parent onclicked qtquit now when i click on the mousearea the program quits what i want is that it calls the function reken tijden uit in the maincpp filei have googled a lot and searched on this site to i have found a couple of answers but i did not get one workingso what code do i put where so i can call the function reken tijden uit in cthanks in advancethe header file looks like thisifndef eigen function header hdefine eigen function header hclass myobject public qobject q objectpublic explicit myobject qobject parent 0 qobjectparent q invokable int reken tijden uit return 1 endif eigen function header hmaincppinclude qtguiqapplicationinclude qmlapplicationviewerhinclude eigen function headerhqscopedpointerqapplication appcreateapplicationargc argvqmlregistertypemyobjectcommyself 1 0 myobjectq decl export int mainint argc char argv qscopedpointerqapplication appcreateapplicationargc argv qmlapplicationviewer viewer viewersetorientationqmlapplicationviewerscreenorientationauto viewersetmainqmlfileqlatin1stringqmltw looptijden berekenenmainqml viewershowexpanded return appexecand the qml fileimport qtquick 11import commyself 10rectangle width 360 height 360 text text qstrhello world anchorscenterin parent myobject id myobject mousearea anchorsfill parent onclicked myobjectreken tijden uit and the errors are as followdmaincpp6 error argc was not declared in this scopedmaincpp6 error argv was not declared in this scopedmaincpp8 error expected constructor destructor or type conversion before tokenso what did i do wrong,['c++'] +256560,install parent pom without building child modules i have a parent pom in a maven project with this structure parent child1 child2i want to install the pom of the parent in the local repo to allow child1 take some changes that i did in the dependencymanagement but i cannot do a regular clean install because child2 is broken and will not buildwhich is the proper way to do this with maven other than going to the parent pom and commenting the child2 module,['java'] +256581,ios objective c thisplay rtf document i want to show a rtf document in a view this document will be developed in microsoft word and will contains imageswhat is the best way to do this using standard routines providedi would really like sample code to load a rtf document from the bundlekind regards jason,['ios'] +256589,run process under current user there is setup project in vs during installation i launch another procesystemdiagnosticsprocess process new systemdiagnosticsprocessfill startinfo and run call startprocestartif i run installer under windows 7 and install for everyone process start under the system if i install just for me process start under current user how do i always start process under current user,['c#'] +256595,javascript documentation on getparameterbyname i cannot seem to find any detailed documentation on getparameterbyname i have searched mozilla google and here am i missing something,['javascript'] +256607,80040154 class not registered with interop from aspnet i am receiving the following error on a windows xp pro sp2 x64 machine running iis6systemruntimeinteropservicescomexception retrieving the com class factory for component with clsid3c250cbd6cc911d2945704b48467e failed due to the following error80040154 class not registered exception from hresult 0x80040154 regdb e classnotregthis occurs when trying to instantiate a com interop objectoddly enough this works fine from a console application running under the same account as the application pool a user in ad ie both use userx so it does not seem like an obvious permissions issueanyone else had anything similar,"['c#', 'asp.net', '.net']" +256644,symfony2 how to set the hostbase url in cli scripts i am currently writing a newsletter tool and therefore have to generate absolute urls in a cli script which is called via cronunfortunately the symfony cli command does not know anything about my hostbase url so the router generates absolute urls with a wrong base url it always uses httplocalhost as baseis there a way to tell the router the correct base urlmy codethiscontainergetroutergenerateroute parameters true,['php'] +256679,serialize a c class to xml with attributes and a single value for the class i am using c and xmlserializer to serialize the following classpublic class title xmlattributeid public int id get set public string value get set i would like this to serialize to the following xml formattitle id123some title valuetitlein other words i would like the value property to be the value of the title element in the xml file i cannot seem to find any way to do this without implementing my own xml serializer which i would like to avoid any help would be appreciated,['c#'] +256682,when using jquery mobile how do i handle styling when javascript is thisabled i am playing with jquery mobile 110 rc1 because it basically does all the work of making my website look nice on mobile deviceswhat am i supposed to do if javascript is thisabled i am still new to html5 but my understanding is that the styling is based on the data attributes and without jquery being able to read which themerole it needs no styling can be appliedi cannot find a default stylesheet that i can just apply and the theme roller does not give a base swatch does jquery mobile have any kind of fallback for this or do i need to write a custom set of stylesheets myself,['jquery'] +256691,running jquery on a static html file from bash i am trying to write a simple script to simply check a webpage for a specific valueainfgheadertext deliveredi would like to automate this from a bash script to be run at an interval i am also fine with using python i need to essentially make an http request get the response and have a way to intelligently query the result is there a library which will help me with the querying part,"['jquery', 'python']" +256701,how do i prevent resharpers error in solution window from showing cssjavascript errors i love resharpers solution analysis tool it has served me very well in a lot of desktop and server applications now i need to do some web development i want to use resharper for the c code but javascripthtmlcss errors appear in the list as well altshiftpagedown sends me to these errors all the time in our team someone else is in charge of the frontend i do not even have the skill to judge of the quality of their code all i want is to exclude all errors that are not c so i can concentrate on my backend code is this or some other workaround possible,"['c#', 'asp.net']" +256747,crash at selfwindow makekeyandvisible my application was running fine until today it started to crash at selfwindow makekeyandvisiblein app delegate boolapplicationuiapplication application didfinishlaunchingwithoptionsnsdictionary launchoptionsselfwindow uiwindow alloc initwithframeuiscreen mainscreen bounds override point for customization after application launchif uidevice currentdevice userinterfaceidiom uiuserinterfaceidiomphone selfviewcontroller viewcontrollerwordhelper alloc initwithnibnameviewcontrollerwordhelper iphone1 bundlenil else selfviewcontroller viewcontrollerwordhelper alloc initwithnibnameviewcontrollerwordhelper iphone bundlenilselfwindowrootviewcontroller selfviewcontrollerselfwindow makekeyandvisiblereturn yesif i debug and step inside at selfwindow makekeyandvisible the next statement before crashing is synthesize window window in the same app delegateall the previous versions that used to work behave the samei restarted my computer and still the same is happening i am using xcode 42 is there anything in xcode setup that i may have accidentally changedthanks for any helpthe following is the whole debug windowgnu gdb 635020050815 apple version gdb1708 mon aug 15 160310 utc 2011copyright 2004 free software foundation incgdb is free software covered by the gnu general public license and you arewelcome to change it andor thistribute copies of it under certain conditionstype show copying to see the conditionsthere is absolutely no warranty for gdb type show warranty for detailsthis gdb was configured as x86 64appledarwinsharedlibrary applyloadrules allattaching to process 440pending breakpoint 3 viewcontrollerwordhelperm136 resolvedpending breakpoint 4 appdelegatem41 resolvedpending breakpoint 5 viewcontrollerwordhelperm27 resolvedpending breakpoint 6 viewcontrollerwordhelperm166 resolvedcurrent language auto currently objectivecgdb,['ios'] +256754,how to add a new device to a team provisioning profile i have a new device for our app to be tested on so i added it to the provisioning portalthere are currently two development provisioning profiles however the provisioning portal will not let me edit the team provisioning profile in order to add the new device but i am sure this something i have done before as i have previously added new devices as they arrived to enable testing with themhow can i add the new device if the profile is not editable the limit has not been reached there is only several devices in the portal in total,['ios'] +256777,net 45 customreflectioncontext what is it useful for whats new in the net framework 45 developer preview mentionsability to customize a reflection context to override default reflection behavior through the customreflectioncontext classwhat is the purpose of the reflectioncontext msdn is not quite clear on the subject,['.net'] +256791,why am i getting undefined method assert valid keys any idea why i am getting this errorexception encountered nomethoderror undefined method assert valid keys for widgetsymbolwhen i try to do a factorybuildwidget on the following modelclass widget activerecordbase belongs to designer vendor endwhen i remove the belongs to line the error goes away,['ruby-on-rails'] +256827,datepicker date off by one day the date returned by date picker is off by one day is it a problem in my code or is it a bugthe date sent to date picker is 20120321 the date returned by datepicker is tue mar 20 2012 var end date end calendargetformateddateymd end date datepickerformatdated m dd yy new dateend date,['javascript'] +256833,expression templates and ranged based for in c11 it is my understanding that expression templates will break on ranged based for in c11 as for auto x expr has an implicit auto range expr in it and this will result in dangling referencesis there a way create expression template classes so that they either behave correctly with ranged based for or at the very least throw a compile errorbasically i would like to prevent the possibility that expression templates would correctly compile but fail at run time due to dangling references i do not mind having to wrap expression templates in something before using them in a ranged based for as long as there are no silent runtime errors if the user forgets to wrap the expression templates,['c++'] +256847,dualcore cpu utilization w single java thread running possible duplicatewould a multithreaded java application exploit a multicore machine very well i have a plain and simple java thread like this running on my dualcore machine windows xp 32bit enviromentpublic static void mainstring strs long j 0 forlong i 0 ilongmax value i j systemoutprintlnj my expectation was that it would stick to a single cpu to fully exploit the highspeed cachesince in the loop we keep operating with local variable j hence one cpu utiliaztion would be 100 and the other would be pretty much idleto my suprise both of the cpus are being utilized at around 4060 after the thread starts and the utilization of one cpu is slightly higher than the othermy question is that is there any os loadbalancing mechanism that kicks in when outofbalance has been detected in my case is it possible that windows os found that one cpu is hitting nearly 100 and the other is almost idle so it reschedules the thread to another cpu periodicallyedit1i have found a possible explanation,['java'] +256891,ios check if nsarray null i am receiving some response from json and is working fine but i need to check for some null valuesi have found different answers but seems is not working stillnsarray productidlist packitemdictionary objectforkeyproductidlisti have tried withif productidlistcount which breaks the appif productidlist nsnull null warning comparison of thistinct pointer types nsarray and nsnullso what is happening how to fix this and check for null in my arraythanks,['ios'] +256904,removing children of div after certain number i have this html div classcontrol label classlabel herelabel input typetext div classuiresizablediv div classuiresizablehandlediv div classuiresizablehandle uiresizablesediv div stylethisplay inline classdeletespan classuiicon uiiconclosethickclosespan div div stylethisplay inline classproperties txtboxspan classuiicon uiiconwrenchpropertiesspandivdivhow can i remove the second third and fourth divs from this html using jquery,['jquery'] +256924,multiple class attributes in html what happens when an element has multiple class attributesdiv idtest classone two three classfouri am trying to add a class to the output of post class in a wordpress plugin but the function itself is creating the entire part classone two threeis it equivalent to classone two three fouror does the first or second winor is it undefined behaviour in which case what do the major browsers doif you know the correct way of adding a class to this snippet wordpress plugin then that would also be appreciateddiv idpostphp the id php post class,"['php', 'html', 'css']" +256957,python elementtree get the namespace string of an element this xml file is named examplexmlxml version10project xmlns xmlnsxsi xsischemalocation 0 0xsd modelversion1400modelversion groupidcomfoobarflubbergroupid artifactiduberportalconfartifactid version13snapshotversion packagingpompackaging nameenvironment for uberportalconfname descriptionthis is the descriptiondescription properties birduberportalversion11birduberportalversion promotiondeviceversion9promotiondeviceversion foobarportalversion6foobarportalversion eventuberdeviceversion2eventuberdeviceversion properties a lot more here but as it is irrelevant for the problem i have removed it projectif i load examplexml and parse it with elementtree i can see its namespace is from xmletree import elementtree tree elementtreeparseexamplexml print treegetrootelement project at 0x26ee0f0i have not found a method to call to get just the namespace from an element without resorting to parsing the stran element of an element it seems like there got to be a better way,['python'] +256997,how to access self or ivars from a block when debugging in the debugger gdb and llvm i usually dopo selfpo myivarp cgpointwhateverand works fine except when i am inside of a block how can i access them in the debugger i do not like very much writing nslogs everywhere i suppose inside blocks in the debugger i need to access ivars in a different way but i do not know how,['objective-c'] +257007,multiple apps with a shared code base since it is popular to have both a free and a paid version in the android market of the same app i had decided to do the same initially i just duplicated the complete codebase and adapted some code here and there added ads built in some limitations etc since there was no option to do library projects at that time but that left me with two projects that are horrific to manage fixes to bugs as i need to do those twice since r14 we can use library projects with resources so that would be a great solution to this particular problem as far as i can tell therefore i have read up on library projects and conciderations and i am curious to know what the minimum amount of files needed in the projects of the different versions are my questions therefore arecould i have all of the code in the shared project and have bare bone project with basically just a manifestif so should i is this the optimal way conceptually so apart from the fact that it depends on my code basehow should i deal with library package naming are there specific rulesare there tools about that can compare code from two different projects and perhaps merge them automagically or automanually and which one is preferred,['android'] +257020,lldb fails to print variable values with error reference to id is ambiguous since i updated to xcode 43 and let it switch my debugger over to lldb any request to print a member variable fails with this error messagelldb print requesterror error reference to id is ambiguousnote candidate found by name lookup is idnote candidate found by name lookup is iderror 1 errors parsing expressionself is oklldb print selfloginviewcontroller 6 0x1cd54d50and other forms of printing the member variable also faildb print selfrequesterror property request not found on object of type loginviewcontroller did you mean to access ivar requesterror 1 errors parsing expressionlldb print selfrequesterror error reference to id is ambiguousnote candidate found by name lookup is idnote candidate found by name lookup is iderror 1 errors parsing expressioneverything else otherwise seems to be working fine xcodes variable window can correctly retrieve the value i have tried a clean build and deleting librarydeveloperxcodederiveddata googling has not revealed any other instances of the same problemi found one thread on apples dev forum but no solutioni have reported this to apple as bug id 11029004,"['objective-c', 'ios']" +257021,why use urlcontent can someone please explain why i should use or should iscript typetextjavascript srcurlcontentscriptssomescriptjsscriptvs script typetextjavascript srcscriptssomescriptjsscriptthanks,['.net'] +257061,how can i create an asynchronous function in javascript i mean check it out this code a href idlinklinkaspanmovingspanlinkclickfunction consolelogenter linkanimate width 200 20 function consolelogfinished consolelogexit as you can see in console the animate function is asynchronous and it fork the flow of the event handler block code in fact linkclickfunction consolelogenter asyncfunct consolelogexit function asyncfunct consolelogfinishedfollow the flow of the block codeif i wish to create my function asyncfunct with this behaviour how can i do it with javascriptjquery i think there is a strategy without use settimeout a,"['javascript', 'jquery']" +257064,constructor called with wrong this pointer is this stack corruption edit i have figured it out with the help of commenters to answer the question posed in my title no it is not stack corruption its gdb reporting the wrong values the program actually behaves as expected and has the right this pointerthe actual buggy behaviour which prompted me to post this question is probably completely unrelated to the issue i describe herefirst a warning i believe this is a memory corruption issue and i would normally not expect an answer except for check your code thoroughly but i have seen this behaviour pop up repeatedly and was hoping some of you had insight on the problem and how i can find its sourcei am currently implementing an interval static analysis which tracks the possible range of variables in a c program the copy constructor for my base interval class looks like this itvtitvtconst itvt i iitype intbv new intbv intervaltii null fitype float new float intervaltif null typeitype other bottomiother bottom now i found a memory corruption bug and managed to trace it to the following snippet of codeitvt itvtget splitbool le const itvt resultthis using gdb i find that the call to the constructor does not seem to construct the result objectbreakpoint 1 itvtget split this0x1016af560 lefalse at itvcpp517517 itvt resultthisgdb n519 ifis singleton is botgdb print result3 i m ptr 0x7f5fbfe100 f m ptr 0x7f5fbfed60 type 1606410016 other bottom 255gdb print this4 i m ptr 0x1020833a0 f m ptr 0x0 type itvtintbv other bottom falselooking deeper i find that inside the copy constructor the this pointer points to the wrong objectbreakpoint 1 itvtget split this0x1016af560 lefalse at itvcpp517517 itvt resultthisgdb print result5 itvt 0x7f5fbfdee0gdb s itvtitvt this0x7f5fbfdf80 i0x1016af560 at itvcpp500500 typeitype other bottomiother bottomgdb print this6 itvt const 0x7f5fbfdf80since result is allocated on the stack at address 0x7f5fbfdee0 i would expect the this pointer inside the copy constructor to point to the same address instead it points to 0x7f5fbfdf80it looks like the copy constructor is initialising something but not the result object on the stack on which it is called in fact i can access the memory location that the constructor initialised perfectly wellbreakpoint 1 itvtget split this0x1016af560 lefalse at itvcpp517517 itvt resultthisgdb s itvtitvt this0x7f5fbfdf80 i0x1016af560 at itvcpp500500 typeitype other bottomiother bottomgdb finishrun till exit from 0 itvtitvt this0x7f5fbfdf80 i0x1016af560 at itvcpp500itvtget split this0x1016af560 lefalse at itvcpp519519 ifis singleton is botgdb print const itvt 0x7f5fbfdf807 i m ptr 0x1016b6d10 f m ptr 0x0 type itvtintbv other bottom falsemy first question can the fact that the this pointer points to the wrong object be explained as normal behaviour it seems like some weird memory corruption issue but maybe i am missing something i am compiling with g and o0 ggdb flags and did a fresh recompile of everything btw heres my g versionleoscythe ai g versioni686appledarwin11llvmg42 gcc 421 based on apple inc build 5658 llvm build 23351500copyright c 2007 free software foundation incthis is free software see the source for copying conditions there is nowarranty not even for merchantability or fitness for a particular purposemy second question if it is memory corruption do you have any advice on how i can track down the source i usually follow such issues to their root cause using gdb but i do not know where to look nowthis is not the first time i encounter this specific behaviour i have seen it happen when looking into other peoples bugs i have never actually directly managed to address it directly it just stopped happening or at least being a visible issue after some other code change this leads me to believe that maybe its just an odd artefact of looking at the stack using gdbi thankful for any advice or insight you can offeredithere are is the relevant snippet of the itvt classclass itvtprotected typedef stdauto ptrintbv intervalt iptrt typedef stdauto ptrfloat intervalt fptrt iptrt i fptrt fpublic typedef enum intbv float other itv typet itv typet type bool other bottom copy constr itvtconst itvt i inline intbv intervalt i return i inline float intervalt f return f inline const intbv intervalt i const return i inline const float intervalt f const return f itvt get splitbool le const,['c++'] +257078,difference between tuple and set in mdx what is the difference between tuple and set in mdx how we can thistinguish both and when we are using them,['sql'] +257102,restricting values for curve fit scipyoptimize i am trying to fit a logistic growth curve to my data using curve fit using the following function as the inputdef logisticx y0 k d a b if b 0 and a 0 y k pow1 npexpd a b x 1b y0 elif b 1 or b 0 or a 0 y k pow1 npexpd a b x 1b y0 return yas you can see the function i am using has some restrictions on the values it can accept for parameter a and b any guess on how to handle the incorrect values should the input function raise an exception or return a dummy valuethanks in advance,['python'] +257110,generate minimized jar with only used classes i am in need of creating the minimal jar of utils library for use in android i am using some methods from apache commons libraries such as ioutils stringutils however each such usage makes me import the whole library commonslang commonsio etc which is absolutely acceptable under tomcat wars are mamootsized anyway but absolutely unacceptable for android projectso my aim is to pack all used classes from dependencies into one jar but only that classes that are needed i remember once being in touch with maven plugin that done that task unfortunatelly i cannot remember its name nor find it via googleso please do you know maven plugin that will do such minimization of dependencies or any standalone tool that will do the same,"['java', 'android']" +257138,why does this closure work say i have a simple function that alerts a messagefunction callmessagemsg alertmsg now when i call it like so it does not work throws error hey is not definedfunction sayhi var hey hi there settimeoutcallmessagehey 10 sayhibut when i call it inside an anonymous function it does workfunction sayhi var hey hi there settimeoutfunctioncallmessagehey 10 sayhiwhy is the hey variable only visible when i put it inside an anonymous function,['javascript'] +257164,how to execute php code from the command line i would like to execute a single php statement like iffunction existsmy func echo function exists directly with the command line without having to use a seperate php filehow is it possible,['php'] +257178,spring mvc map controller to context root while using mvcresources morninghaving issues mapping a controller to ie localhost8080someapp would map to controller while also using mvcresourceswebxml mapping servletmapping servletnamespringservletservletname urlpatternurlpattern servletmappingmvcresourcesmvcresources mappingresources locationresources the server loads the page correctly but when i map to an asset ielink typetextcss relstylesheet hrefcurl valueresourcescssblueprintprintcss when clicking the css file via viewsource in a web browser the server response maps back to the index page rather than the resource leads me to believe it is related to the servletmappingany help with this would be greatthankseditforgot to mention if i bind the controller to saycontrollerpageseverything works fine just would rather have the context root be able to respond correctly,['java'] +257204,char or int for boolean value in c i find that there is no native bool type people either use int or char though it seem that int might be more frequently used than char is this truemy first impulse was to use char as it is a smaller data type but there something i have missed is int better for boolean values and if so why,['c'] +257213,how to handle http options with spring mvc i would like to intercept the options request with my controller using spring mvc but it is catched by the thispatcherservlet how can i manage that,['java'] +257239,find the number of strings in an array of strings in c char namesa b cis there a way to find the number of strings in the array like for example in this case it has to be 3 please let me know thanks,['c'] +257252,php cli in windows handling ctrlc commands how can i handle ctrlc in php on the command line pcntl functions do not work in windows,['php'] +257257,adding attributes to instance methods in python i would like to add an attribute to an instance method in one of my classes i tried the answer given in this question but this answer only works for functions as far as i can tellas an example i would like to be able to do something likeclass fobject def barself selfbarcounter 1 return selfbarcounter barcounter 1 but when i call foobar i getattributeerror instancemethod object has no attribute countermy goal in doing this is to try to impress that the counter variable is local to the bar method and also to avoid cluttering my class namespace with yet another attribute is there a way to do this is there a more pythonic way of doing this,['python'] +257285,starting multiple delayedjob workers w specific queues via capistrano tasks i am looking into using queues with delayed job i have found this page which outlines various ways of starting workers however i would like to keep my currently capistrano methodset delayed job args n 2 p ecv2productionafter deploystart delayed jobstarti was wondering how i could modify the delayed job args to handle spawning 1 worker with a specific queue and 1 worker for every other job so far all i have is overriding each task like sonamespace delayed job do task restart roles app do run cd current path rails envrails env scriptdelayed job p ecv2production queueexport restart run cd current path rails envrails env scriptdelayed job p ecv2production restart endend but that is no fun any suggestions,"['ruby-on-rails', 'ruby']" +257290,what is zuckmail xmailer zuckmail version 100i mean is this custommade smtp mailer or xmailer header with custom value like xmailermymailer,['php'] +257304,backend technology for frontend technologies like twitter bootstrap this a noob alike question but here we goia ve read about twitter bootstrap among other presentation frameworks which gives the designerprogrammer the tools to build easily the front end of a webapp what i dona t know is how to integrate that with a for example java ee backend i mean do those presentation frameworks allow to integrate them with any backend technology such as java php python etc or are they linked to a specific technologyi have built a few java ee web applications using gwt for the presentation layer and java in the server side but as ia ve pointed before i still dona t catch how it would be integrate bootstrap with java for examplei know ita s a very general question but ia d appreciate any help,['java'] +257305,sqlalchemy raises none causes typeerror i am using the declarative extension in sqlalchemy and i noticed a strange error when i attempted to save an instance of a mapped class with incorrect data specifically a column declared with nullablefalse with a value of nonethe class simplifiedclass userbase tablename users id columninteger primary keytrue autoincrementtrue userid columnstring50 uniquetrue nullablefalsecausing the error session is a sqlalchemy session you user sessionaddu sessioncommittypeerror exceptions must be oldstyle classes or derived from baseexception not nonetypelooking at the code that causes this exception i found in sqlalchemyormsessionexcept transactionrollback capture exceptiontrue raisethe exception being caught in this case is a sqlalchemyexcoperationalerror if i change these lines toexcept exception as e transactionrollback capture exceptiontrue raise ethen the problem goes away and the operationalerror gets thrown instead of none should not the original code work in any recent version of python though i am using 272 is this error somehow specific to my applicationpython 272sqlalchemy 075update the error seems to be specific to my application in some way i am wrapping an eventletdb pool with a sqlalchemy engine which appears to be the source of the problem somehow running my simple test with either inmemory sqlite or basic mysql engine does not have this problem but with the db pool it doestest case the full traceback istraceback most recent call last file test case 9525220py line 41 in module sessioncommit file usrlocalcellarpython272frameworkspythonframeworkversions27libpython27sitepackagessqlalchemyormsessionpy line 645 in commit selftransactioncommit file usrlocalcellarpython272frameworkspythonframeworkversions27libpython27sitepackagessqlalchemyormsessionpy line 313 in commit self prepare impl file usrlocalcellarpython272frameworkspythonframeworkversions27libpython27sitepackagessqlalchemyormsessionpy line 297 in prepare impl selfsessionflush file usrlocalcellarpython272frameworkspythonframeworkversions27libpython27sitepackagessqlalchemyormsessionpy line 1547 in flush self flushobjects file usrlocalcellarpython272frameworkspythonframeworkversions27libpython27sitepackagessqlalchemyormsessionpy line 1635 in flush raisetypeerror exceptions must be oldstyle classes or derived from baseexception not nonetype,['python'] +257309,how do i use instrumentationretransformclasses correctly from within asm code i am using the asm library to perform some java bytecode modification specifically to modify my classes to implement a new interface and associated methods my current approach is using the core asm api via a javaagent i would like to keep this dynamic approach as opposed to statically modifying class filesat a higher level my problem is that if i choose to modify class a which extends from b i also need to modify b given my understanding of how classes are loaded in the jvm i believe that class b will always be handed to a transformer before class a please correct me if i am wrong given that assumption i am thinking that i then need to go back and retransform b my approach is captured in this bit of codepublic byte transformclassloader l string name class clazz protectiondomain d byte b throws illegalclassformatexception 1 systemoutprintln name if interestingclassname try classreader cr new classreaderb classwriter cw new classwritercr classwritercompute maxs classwritercompute frames pyclassvisitoradapter pv new pyclassvisitoradaptercw name cracceptpv 0 2 retrieve the superclass and try to transform that if ljavalangobjectequalspvgetsupername string cname classjvmtocanonicalpvgetsupername class classes instgetaloadedclasses for class c classes if cgetnameequalscname instretransformclassesc break dump the transformed class classreader cr2 new classreadercwtobytearray classwriter cw2 new classwritercr2 0 traceclassvisitor tcv new traceclassvisitorcw2 new printwritersystemout cr2accepttcv 0 return cw2tobytearray catch exception ex exprintstacktrace return null else return b inst is a handle to instrumentation which gets passed in in the constructorthe part i am having a hard time with is the block marked in the comments with 2 let us say again that a extends b and i am interested in transforming a what i am expecting is that i would see the name of the superclass b being printed at 1 but not getting transformed because i do not think it is interesting on the first pass and then once i get to 2 and thiscover that as superclass is b i should be trying to retransform b at this point i am expecting this method to be called again via instretransformclasses and that i would see b getting printed at 1 however i do not i have added print statements and am sure i am reaching the retransform call i have also checked that instrumentationisretransformclassessupported and instrumentationismodifiableclassc both return truei believe i have set up the agent correctly setting both canretransformclasses and canredefineclasses to true in the manifest also when i add the transformer to the instrumentation in the agents premain method i do thispublic static void premainstring agentargs instrumentation inst instaddtransformernew pyclassfiletransformerinst trueany insights as to what i am doing wrong here thanks,['java'] +257365,how to check for not null column constraint in oracle sql how do i check if a column in a table has a not null constraint in an oracle db can it be checked with the data dictionary,['sql'] +257371,why does a string index in a javascript array not increase the length size in the example below the array2length is only ten when in my mind it should be 13 why does the string keyed indexes not increase the length of the array i can store things and still access it and the vs debugger shows that those arrays are being stored properly so why is the length not increasedvar array2 new arrayarray2a new arrayarray2b new arrayarray2c new arrayfor var i 0 i 10 i array2i new arrayvar nothing for var i 0 i array2length i nothing,['javascript'] +257373,can the twitter bootstrap carousel plugin fade in and out on slide transition i have a very basic implementation of the twitter bootstrap carousel plugin on a site that i am working on i was just wondering if anyone had extended the carousel plugin so that it fades in and fades out on slide transitioni found this issue 2050 on githubcom that seems to suggest that at this point it is not possible just wanted to see if it could be or has been done,['jquery'] +257391,prevent expression templates binding to rvalue references i understand that doing something like the followingauto x matrix1 matrix2 matrix3stdcout x23 stdendlwill cause a silent runtime error if the matrix operations use expression templates such as boostublasis there any way of designing expression templates to prevent the compiler from compiling such code that may result in the use of expired temporaries at runtimei have attempted unsuccessfully to work around this issue the attempt is here,['c++'] +257394,how do i construct an iso 8601 datetime in c i am working with the azure rest api and they are using this to create the request body for table storagedatetimeutcnowtostringowhich produces20120302t0407340218628zit is called roundtrip and apparently it is an iso standard see 8601 but i have no idea how to replicate it after reading the wiki articledoes anyone know if boost has support for this or possibly qtnote i will get back to you after the weekend after comparing it to c,['c++'] +257437,can i change the fill color of an svg path with css i have the following code span svg height32 version11 width32 xmlns styleoverflow hidden position relative left 001626px top 09837px descdesc defs path style fill3 strokenone dm159855972c842259728910049228915078c2289179554302912768274z svgnbsp spanis it possible to change the fill color of the svg path with css or some other means without actually changing it inside the path tag,"['javascript', 'jquery', 'html', 'css']" +257466,what is the rails way to define tomorrows date in a rails 32 app i have a query defined to return all event items with due date equal to todaydue today eventwheredue date timenowbeginning of daytimenowend of dayi want to modify this to return all events due today and tomorrowwhat is the best way to do thisi know there are several options available to me datetomorrowdatecurrenttomorrowdatenowtomorrowdatetimenowtomorrowto datetimenowtomorrowto datedatecurrent1i am sure there are others are all of these interchangeable are there any differences in performance are there any issues associated with different approaches i would welcome any suggestions as to which is the best way to do thisfor extra kudos i also want to thisplay the due date as today hhmm or tomorrow hhmm where hhmm is the time is there a method backed in to rails to thisplay dates as today or tomorrow or will i need to define my own scopemany thanks,"['ruby-on-rails', 'ruby']" +257478,javascript pubsub message priorities more of a thiscussion than a questioni have been reading an article titled patterns for largescale javascript application architecture and so far it is been quite an eye openerthe author of this article advocates the use of a pubsub architecture with the use of a mediatorcontroller there are not any realworld examples given but on the actual slide show he advocates using amplifyjslike many other pubsub implementations amplify supports message priorities my understanding is that with a mediator in place the need for prioritising messages is diminished because the mediator takes control of what happens when and where is this a valid pointmessage priorities scare me because when the application grows and varies you could end up with a heap of modules all with different priorities set on their subscriptions and no real control over whats going on is this a valid concern or simply a misunderstanding of how they should actually be used,['javascript'] +257482,javascript dynamically monitor cpumemory usage i am considering writing a game in javascript using webgl and associated technologies i would like to make the game as intelligent as possible so i am looking into monitoring cpumemory usagefor examplefor high cpu usage scale back the graphics a bit or offload computations to the serverfor high memory usage offload data to the server for storage and later retrievali would like to get the data that chrome offers in it is task manager i know how to track fps and that can lead to some flexibility but i would like to be have as much information as possible the main use case is for a low power mode where the cpu is utilized as little as possible for laptops or an idle mode when the user is browsing forums etci know how to use profilers but i would like access to these tools from javascriptis this possible if not do you know if it has been proposed for standardizationi would be willing to live with an extension as long as it could be queried from javascript but i would like to avoid it if a native feature exists i am trying to target recent versions of firefox and chrome but i could restrict myself to a single browser if one supports this,['javascript'] +257492,parsing hostname and port from string or url i can be given a string in any of these formatsurl eg string eg wacmecom456 wacmecom 456 or wacmecom i would like to extract the host and if present a port if the port value is not present i would like it to default to 80i have tried urlparse which works fine for the url but not for the other format when i use urlparse on hostnameport for example it puts the hostname in the scheme rather than netloci would be happy with a solution that uses urlparse and a regex or a single regex that could handle both formats,['python'] +257520,problems with https no peer certificate in android problemi want to send https request to the site my own server and get response from it and save it for example in a string i have found some example codes in internet and try to test them for my problem but they are not helpful below i present some parts of codes which i have testedcode examplei try this code but i always get same exception no peer certificate why try hostnameverifier hostnameverifier orgapachehttpconnsslsslsocketfactoryallow all hostname verifier defaulthttpclient client new defaulthttpclient schemeregistry registry new schemeregistry sslsocketfactory socketfactory sslsocketfactorygetsocketfactory socketfactorysethostnameverifierx509hostnameverifier hostnameverifier registryregisternew schemehttps socketfactory 443 singleclientconnmanager mgr new singleclientconnmanagerclientgetparams registry defaulthttpclient httpclient new defaulthttpclientmgr clientgetparams set verifier httpsurlconnectionsetdefaulthostnameverifierhostnameverifier example send http request final string url httppost httppost new httpposturl httpresponse response httpclientexecutehttppost bufferedreader rd new bufferedreadernew inputstreamreaderresponsegetentitygetcontent string line while line rdreadline null logidownloadimagetaskclassgetname line catchioexception ex logedownloadimagetaskclassgetname exgetmessageexception0302 165825234 wsystemerr1868 javaxnetsslsslpeerunverifiedexception no peer certificate 0302 165825238 wsystemerr1868 at orgapacheharmonyxnetproviderjssesslsessionimplgetpeercertificateslsessionimpljava137 0302 165825238 wsystemerr1868 at orgapachehttpconnsslabstractverifierverifyabstractverifierjava93 0302 165825238 wsystemerr1868 at orgapachehttpconnsslsslsocketfactorycreatesocketsslsocketfactoryjava381 0302 165825238 wsystemerr1868 at orgapachehttpimplconndefaultclientconnectionoperatoropenconnectiondefaultclientconnectionoperatorjava165 0302 165825250 wsystemerr1868 at orgapachehttpimplconnabstractpoolentryopenabstractpoolentryjava164 0302 165825250 wsystemerr1868 at orgapachehttpimplconnabstractpooledconnadapteropenabstractpooledconnadapterjava119 0302 165825250 wsystemerr1868 at orgapachehttpimplclientdefaultrequestdirectorexecutedefaultrequestdirectorjava360 0302 165825250 wsystemerr1868 at orgapachehttpimplclientabstracthttpclientexecuteabstracthttpclientjava5 0302 165825250 wsystemerr1868 at orgapachehttpimplclientabstracthttpclientexecuteabstracthttpclientjava487 0302 165825250 wsystemerr1868 at orgapachehttpimplclientabstracthttpclientexecuteabstracthttpclientjava465 0302 165825250 wsystemerr1868 at comhttpstestdownloadimagetaskdoinbackgroundhttps testactivityjava78 0302 165825250 wsystemerr1868 at comhttpstestdownloadimagetaskdoinbackgroundhttps testactivityjava1 0302 165825250 wsystemerr1868 at androidosasynctask2callasynctaskjava264 0302 165825253 wsystemerr1868 at javautilconcurrentfuturetasksyncinnerrunfuturetaskjava305 0302 165825253 wsystemerr1868 at javautilconcurrentfuturetaskrunfuturetaskjava137 0302 165825253 wsystemerr1868 at androidosasynctaskserialexecutor1runasynctaskjava208 0302 165825257 wsystemerr1868 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava1076 0302 165825257 wsystemerr1868 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava569 0302 165825257 wsystemerr1868 at javalangthreadrunthreadjava856questionwhat i am doing wrong and how i can solve this issue why i get no peer certificate exception thankseditedwindows server settingsvirtualhost 443 servername 1022020 alias fidoezpay dfidoezpay alias fidoezpay dfidoezpay directory dfidoezpay options indexes followsymlinks multiviews allowoverride all order allowdeny allow from alldirectory these are the actual ssl directives needed to get it all working sslengine on sslcertificatefile cwampbinapacheapache2217confsslfidoservercrt sslcertificatekeyfile cwampbinapacheapache2217confsslfidoserverpemvirtualhost,"['java', 'android']" +257546,chrome extensions support copy image to clipboard i search in goggle and did not find any answerthe new clipboard api support copy image to clipboard by using documentexec commandif yes how can i copy image data url to clipboard as imagei am the developer of webpage screenshot extension and i search for a way to copy the image to clipboardi also search for a way to open the image with specific software,['javascript'] +257559,embedding json data into yaml file i am writing a fixture for my table and a one of the coloums takes in a json string as a valuethe problem is the fixture is not loading failing asfixtureformaterror a yaml error occurred parsing homesaurajeetcodedcboxtestfixtureshardwareyml please note that yaml must be consistently indented using spaces tabs are not allowed please have a look at the exact error was argumenterror syntax error on line 145 col 73 portslist nameob1port num0port typenetworknameob2port nuany solutions to this,"['ruby-on-rails', 'ruby']" +257573,ruby on rails action without view i have what i think is a very simple problem i am coming from a php background and used to do this all the time so i may be looking at this the wrong wayi am trying to create an ajax handler in ror when the user clicks a button javascript fires off a post and gives the user feedback using the success parameter of jquerys ajax functionthe problem is ror is trying to load a view for the ajax handler when i really just need a few lines in the controller to do the database work and echo out a status code that will be interpreted by the users javascriptthis is all just a mailchimp subscribe holding page so i am only using the home controllermy routesmaproot controller homemapconnect mcsubscribe controller home action mcsubscribemy home controllerclass homecontroller applicationcontroller def index no content end def mcsubscribe print paramsemail endendand my testing javascript just so you understand whats going onfunction mcsubscribe var email jquerysignup input emailval jqueryajax type post url data email email cache false success functionresult alertresult i thought this would be a common problem but i have googled around and only managed to find suggestions to redirect as the user will never visit the mcsubscribe page that does not seem appropriate,['ruby-on-rails'] +257587,organizing solutions projects and svn i would like some help in setting up a project in svn with regards to directory structure i have read several answers regarding this on so but as i am new to this most of them are difficult to understandi am building a single library on which several other thistinct project depends oni need the ability to export mylibrary headers and lib only easily for use by third partiesmylibrary1depends on external libraries should be able to manage different versions of these librariesmylibrary2depends on external libraries fmod glew project 1 2 4 5 6 depends on mylibrary1 2 or botheach project could need versions for multiple platforms osx windows i would like to know of a good way to organize this do keep in mind that i am rather new to this a more pedantic answer would be helpful for example if you write something like src do explain what is supposed to go into it i would be able to guess but i wont be sure editi cant put this into a comment so here goesjn thanks for the extensive reply i would like to clarify some stuff i hope i understood what you meant properlyroot library foo branches old versions of foo tags releases of foo trunk current version build stuff required by makefiles tools scripts to launch tests ect data test data needed when running output binaries exe files dependencies libraries that foo needs lib name include lib docs documentation releases generated archives sample sample project that shows how to use foo source h cpp program bar branches old versions of bar tags releases of bar trunk current version build stuff required by makefiles tools scripts to launch tests ect data test data needed when running output binaries exe files dependencies libraries that bar needs lib name include lib docs documentation releases generated archives sample sample project that shows how to use bar source h cpp1 where do the sln files go in build2 do i need to copy foosource into bardependenciesfooinclude after all bar depends on foo3 where do dll files go if foo has dependencies on dll files then all programs using foo need access to the same dll files should this go into rootdlls,['c++'] +257631,tsql select into temp table from dynamic sql this seems relatively simple but apparently it is noti need to create a temp table based on an existing table via the select into syntaxselect into temptable from existing tablethe problem is the existing table name is accepted via a parameteri can get the tables data viaexecute select from tablenamebut how do i marry the two so that i can put the results from the execute directly into the temp tablethe columns for each table that this is going to be used for are not the same so building the temp table before getting the data is not practicali am open to any suggestions except using a global temp tableupdatethis is completely ridiculous but my reservations with the global temp table is that this is a multi user platform lends itself to issues if the table will linger for long periods of timeso just to get past this part i have started by using the execute to generate a global temp tableexecuteselect into globaldynamicformtable from tsformtable i then use the global temp table to load the local temp tableselect into temptable from globaldynamicformtablei then drop the global tabledrop table globaldynamicformtablethis is dirty and i do not like it but for the time being until i get a better solution its going to have to workin the endi guess there is no way to get around it the best answer appears to be eithercreate a view in the execute command and use that to load the local temp table in the stored procedurecreate a global temp table in the execute command and use that to load the local temp table with that said i will probably just stick with the global temp table because creating and dropping views is audited in my organization and i am sure they are going to question that if it starts happening all the timethanks,['sql'] +257635,why is the bss segment required what i know is that global and static variables are stored in the data segment and uninitialized data are in the bss segment what i do not understand is why do we have dedicated segment for uninitialized variables if an uninitialised variable has a value assigned at run time does the variable exist still in the bss segment onlyin the following program a is in the data segment and b is in the bss segment is that correct kindly correct me if my understanding is wronginclude stdiohinclude stdlibhint a10 1 2 3 4 5 6 7 8 9int b20 uninitialized so in the bss and will not occupy space for 20 sizeof int int main also consider following program include stdiohinclude stdlibhint var10 uninitialized so in bss int main var0 20 initialized where this var will be,['c'] +257637,android error you must supply layout width attribute sorry because my title similar with many others on stackoverflow but none of those solution meet with my problemi am designing a layout use relative layout after design in code view when i change to graphic view eclipse notices you must supply a layout width attributeyou must supply a layout height attribute when i run this program will notice error in logcat caused by javalangruntimeexception binary xml file line 2 you must supply a layout width attributehere is my xml filexml version10 encodingutf8relativelayout xmlnsandroid androidlayout widthfill parent androidlayout heightfill parent textview androidididcontact name androidtextsam androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparenttoptrue androidlayout alignparentlefttrue androidlayout marginleft20dp androidlayout margintop20dp androidtextsize20dp textview androidididcontact phone androidlayout widthwrap content androidlayout heightwrap content androidtextsize10dp androidtext39256493 androidlayout belowidcontact name androidlayout alignleftidcontact name androidlayout margintop5dp relativelayout,['android'] +257689,how do i put comments on each line in vbnet i used to be a c developer so this commenting style was very easy in c this is driving me crazy but how do you do this in vbnet without getting a syntax errorprivate readonly property acceptabledataformatbyval e as systemwindowsformsdrageventargs as boolean get return edatagetdatapresentdataformatsfiledrop this is a file that a user might manipulate orelse edatagetdatapresentfilegroupdescriptor this is a typical outlook attachment end getend property,['.net'] +257706,can pythons argparse permute argument order like gnu getopt gnu getopt and command line tools that use it allow options and arguments to be interleaved known as permuting options see nodeusinggetopthtmlusinggetopt perls getoptlong module also supports this with qwconfig gnu getopt argparse seems to not support or even mention permuting optionsthere are many so questions related to argopt order but none seem answer this question can argparse be made to permute argument order like getoptthe use case is a prototypical command line signature like gnu sortsort opts filesin which 1 options and files are permuted and 2 the file list may contain zero or more argumentsfor exampleimport argparsep argparseargumentparserpadd argumentfilesnargsdefaultpadd argumentzactionstore truepparse argszbarfoo okpparse argsbarfooz okpparse argsbarzfoo not okayusage ipython h z files files i have triedpparse known args does not complain but does not actually permute either and it does not balk about arguments that look like invalid options eg bogus or b abovepadd argumentfilesnargsargparseremainder option z is included in files unless before positional argspadd argumentfilesnargsactionappendi want to implement something close to the gnu sort prototype above i am not interested in a flag that can be specified for each file eg f file1 f file2,['python'] +257710,is there a way to use on duplicate key to update all that i wanted to insert i know that you can use on duplicate key update to update a certain value if there is a record for that key alreadyi can do thisinsert into tablename abc values 1 2 3on duplicate key update a1 b2 c3but how can i do this without having to write out the columns and values twice,['mysql'] +257722,how can i filter an array of hashes to get only the keys in another array i am trying get a subset of keys for each hash in an array the hashes are actually much larger but i figured this is easier to understand id2 start 330 break 30 num attendees 14 id 3 start 3 40 break 40 num attendees 4 id 4 start 4 40 break 10 num attendees 40 i want to get only the id and start valuesi have triedreturn keys idstartreturn array eventsselectkeyval keyto sin return keysbut this returns an empty array,['ruby'] +257765,why does omission of include only sometimes cause compilation failures i am a beginner with c when i write the code sometimes i write include string and the code works other times i do not write include string and the code does not work but sometimes it works without include stringso do i have to write include string so that the code works,['c++'] +257766,icsharpcodesharpziplib validate zip file using icsharpcodesharpziplib for c how can i validate that the file being passed is actually a valid zip file not something that has been right clicked and renamed as ziphttppost public actionresult uploadhttppostedfilebase filedata if filedata null filedatacontentlength 0 if pathgetextensionfiledatafilename zip var zipfile servermappathcontentuploads pathgetfilenamefiledatafilename filedatasaveaszipfile filestream fs systemiofileopenreadzipfile zipfile zf new zipfilefs foreach zipentry zipentry in zf if zipentrynameendswithhtm zipentrynameendswithhtml return jsonnew success true fsclose fsthispose systemiofiledeletezipfile else var filename servermappathcontentuploads pathgetfilenamefiledatafilename filedatasaveasfilename return jsonnew success true return jsonnew success false,"['c#', 'asp.net']" +257776,rename an environment with virtualenvwrapper i have an environment called doors and i would like to rename it to django for the virtualenvwrapperi have noticed that if i just rename the folder virtualenvsdoors to django i can now call workon django but the environment still says doorshobbes3hobbes3,['python'] +257780,update ui from thread in winrt since the windows 8 consumer preview was released a few days ago i am working on the new winrt for metro applications in c and i had ported my self written irc class to the new threading and networking the problem is my class is running an thread for receiving messages from the server if this happens the thread is making some parsing and then firing an event to inform the application about this the subscribed function then should update the ui an textblockthis is the problem the thread cannot update the ui and the invoker method that has worked with net 40 does not seem to be possible anymore is there an new workaround for this or even an better way to update the ui if i try to update the ui from the event subscriber i will get this exceptionthe application called an interface that was marshalled for a different thread exception from hresult 0x8001010e rpc e wrong thread,['c#'] +257783,finding and dealing with duplicate users in a large user database with the following format and sample data we are trying to identify duplicated peopleid first name last name email 1 chris backer 2 chris backer 3 chris backer 4 chris backer 5 carl castle 6 mike rotch i am using the following queryselect group concatid as ids concatupperfirst name upperlast name as name count as duplicate count from users group by name having duplicate count 1this works great i get a list of duplicates with the id numbers of the involved rows we would reassign any associated data tied to a duplicate to the actual person set user id 2 where user id 3 then we delete the duplicating user rowthe trouble comes after we make this report the first time as we clean up the list after manually verifying that they are indeed duplicates some are not duplicates there are 2 chris backers that are legitimate userswe do not want to keep seeing chris backer in subsequent duplicate reports until the end of time so i am looking for a way to flag that user id 1 and user id 4 are not duplicates of each other for future reports but they could be duplicated by new users added laterwhat i triedi added a is not duplicate field to the user table but then if a new duplicate chris backer gets added to the database it will cause this situation to not show on the duplicate report the is not duplicate improperly excludes one of the accounts my having statement would not meet the 1 threshold until there are two duplicates of chris backer plus the real one marked is not duplicatequestion summed uphow can i build exceptions into the above query without looping results or multiple queriessubqueries are fine but the size of the dataset makes every query count and i would like the solution to be as performant as possible,"['mysql', 'sql']" +257793,ios app next key would not go to the next text field i have a simple scene using storyboard in ib with a username and password text box i have set the keyboard to close when you are on the password text field but cannot get the nextreturn button to work on the username to switch the focus or first responder to the password text boxi am closing the keyboard while on the password text field like this booltextfieldshouldreturnuitextfield thetextfield if thetextfield selftextpassword thetextfield resignfirstresponderreturn yesi know it is something similar to this but just cannot nail it down,"['iphone', 'objective-c', 'ios']" +257794,add box shadow with transition effect i am adding a class to a div that adds a box shadow to that div this happens dynamically via jquery now when the class is added the shadow effect is added automatically as well without any effect is there a way to add some transition effect via css in this casehtmldiv idboxdivcssbox width 50px height 200pxshadow webkitboxshadow 0px 0px 4px 2px d50e0e mozboxshadow 0px 0px 4px 2px d50e0e boxshadow 0px 0px 4px 2px d50e0e,"['html', 'css']" +257822,thisplay all items in array using jquery i have an array that i want to have thisplayed in htmli do not want to write multiple lines for posting each item in the array but all should be exactly the same ievar array code that fills the arrayelementhtmlspanarrayspanwhat i want here is to create a span for each item in the array,"['jquery', 'html']" +257863,how to position the form in the center screen i am a net developer but somehow i was task to create a simple application in java for some extra reason i was able to create that application but my problem is how can i center the form in the screen when the application is launched here is my codeprivate void formwindowactivatedjavaawteventwindowevent evt get the size of the screen dimension dim toolkitgetdefaulttoolkitgetscreensize determine the new location of the window int w thisgetsizewidth int h thisgetsizeheight int x dimwidthw2 int y dimheighth2 move the window thissetlocationx ythe code above works fine but the problem is i have seen the form moving from the topleft most to center screen i also tried adding that code in formwindowopened event and still shows same action is there a better way for this just like in net application there is a centerscreen position or if the code above is correct on what event will i put itthanks for reading this,['java'] +257867,javascript time zones and daylight savings time welcome to this weeks episode of yet another time zone questioni have done a fair bit of reading on so tried to manipulate momentjs and datejs into helping me and generally been plagued by a feeling of frustration since i started trying to solve this so if someone could help or point me at the duplicate question on so that i just have not been able to find that would be awesomei have a page this page thisplays a series of times eg 728 738 748 i know whether these are ampm these times are always americanew york they do not change when daylight savings time changes as the event they correspond to always happens at that time regardless of dst let us call them a schedule i want to highlight the time that is coming up nextthis is trivial for people living in americanew yorkthis is not too terrible for people living in americalos angeles assuming my logic worksi can take the current time of the computer in americalos angeles convert it to utc then determine if americalos angeles is currently observing dst or not and determine whether americanew york should be 0400 or 0500 apply that to the utc and make my comparison this hurts a little because youre still always dealing with a date based in americalos angeles and not actually changing the time zone of the date object but i have a reliable means of rolling back or forward the hours from the utc timewhat happens however when i try to determine if daylight savings time is being observed from a computer in a region that does not observe daylight savings time at alljavascript will only create date objects for the current time zone to my knowledge and then doing any determination of dst is based on that date objectshould i just not care the times are primarily relevant only to people living in americanew york anyway i am just trying to build an application that makes sense when viewed from another time zone such that when it is 3am in country without dst and it is 2pm in americanew york the schedule highlights that the 205pm thing is about to happen and not the 305am thing,['javascript'] +257887,objectivec property and synthesize logic what is an actual name of instance variable say topspeed as from lectures of stanford university about the objectivec and ios development here is the code property nonatomic double topspeedlooking at this code i will think that i have defined a variable topspeed in the classi cannot understand why it will declare automatically the getter method with the name the same as the variable name topspeedanother question is when we use synthesize topspeed topspeedand if we look at what the synthesize will generate double settopspeeddoublespeed topspeed speed double topspeed return topspeedwhat is topspeed here and what is topspeed i have declared a variable topspeed not the topspeed what if i do not use property what would the variable name be,['objective-c'] +257888,ioc container for portable class libraries is there any ioc container out there which supports or can be made to the portable class libraries yeti fiddled around with some simpleinjector autofac but they always had one dependency or another which prevented me from using them as a portable class libraryi am fairly new to the topic so i maybe totally on the wrong track herein more detaili want to create a library containing my models and later viewmodels for a mmvm app which should run on net 45 wp7 and winrt this models should be saveable as files since the implementation of the particular save algorithms desktop filesystem isolated storage is specific to every platform i hoped to utilize an ioc container to decouple it from the models themselves,"['c#', '.net']" +257904,php json or array to xml whats the easiest way to take a json or array object and convert it to xml maybe i am looking in all the wrong places but i am not finding a decent answer to get me on track with doing it is this something i would have to somehow build myself or is there something like json encodejson decode that will take an array or json object and ust pop it out as a xml object,['php'] +257921,notifications on corebluetooth returning a cberrordomain code0 i am trying to write an app that uses the corebluetooth framework i am able to search for devices and connectthisconnect to one and write values to characteristics in the device when i try to enable notificationsperipheral setnotifyvalueflag forcharacteristiccharacteristicthis triggers voidperipheralcbperipheral peripheral didupdatenotificationstateforcharacteristiccbcharacteristic characteristic errornserror errorhowever it is always returning the error error domaincberrordomain code0 the operation couldnat be completed cberrordomain error 0i have looked online to see what this could possibly mean i have cleaned it built it again restarted my iphone restarted xcode but i keep running into this error could anyone help me understand what this means and how i can fix itthanks so muchandy,['ios'] +257923,how to kill a running select statement how can i stop a running select statement by killing the sessionthe command is continuously giving me output based on the select statement i want to stop it in between,['sql'] +257927,sql azure federation in nhibernate how to use federation in sql azure connection using nhibernate for example i want a federation to split data using customerid and i want to direct all session calls to be directed to a specific federation based on a configurable customerid,"['c#', 'sql']" +257969,iphone app not starting on simulator no errors i am having a problem where my simple ios app builds fine says running but on the simulator i just get a blank screen in xcode it still says running x on iphone 50 simulator but also give a thread 1 signal sigabrtthere are no readable errors in the bottom window justargc int 1 argc char 0xbf578it has been absolutely fine until now i had the problem after trying to swap out a few images and their 2x versions for ones that i would slightly tweakedi have done a clean and i have cleaned the build folder i have also emptied the deriveddata folder and tried rebooting i have tried to add breakpoints in my appdelegate in the didfinishlaunchingwithoptions method but it seems to never reach thempretty much run out of things i can think of to trydebug navigatoreditwhen i comment outproperty strong nonatomic uiwindow windowfrom interface appdelegateand comment outsynthesize window windowfrom implementation appdelegate it loads fine albeit with a blank screen because i guess the window is not loading,['iphone'] +258038,how to setup a basic ruby project i want to create a small ruby project with 1020 classes files i need some gems and i want to use rspec as test frameworki might want to build a gem later on but that is not certainis there some howto or guide that shows me how to setup the basic structure of my projectquestions that i have arewhere do i put all my custom errorsexceptionsare there some conventions out there for naming directories like lib bin src etcwhere do i put test data or documentswhere do i require all my files so i have access to them in my projecti know i could do everything from scratch but i would like some guidance there are some good gems out there that i could copy but i am not certain what i really need and what i can deletei looked at but it stops after setting up bundler,['ruby'] +258047,what does this symbol mean in javascript what is thisthis is a collection of questions that come up every now and then about syntax in javascript this is also a community wiki so everyone is invited to participate in maintaining this listwhy is thisstack overflow does not allow searching for particular characters as a consequence many questions about operators and other syntax tokens are not found easily when searching for them this also makes closing duplicates more difficult the list below is to help with this issuethe main idea is to have links to existing questions on stack overflow so it is easier for us to reference them not to copy over content from the ecmascript specadditionally this is a blatant copy of the php symbol reference we needed a js one please help edit and add links to other operatorssyntax references or if you cannot find good questionsanswers on a particular piece of syntax add an answer to this question and link it,['javascript'] +258065,thor yaml outputting as binary i am using thor and trying to output yaml to a file in irb i get what i expect plain text in yaml format but when part of a method in thor its output is differentclass foo thor include thoractions desc bar test def set test name xavier age 30 puts test namexavier age30 puts testto yaml binary bmftzq binary wgf2awvy binary ywdl 30 fileopendataconfigyml w f fwritetestto yaml endendany ideas,['ruby'] +258082,hide page until everything is loaded advanced i have a webpage which heavily makes use of jquerymy goal is to only show the page when everything is readywith that i want to avoid showing the annoying page rendering to the useri tried this so far body holder is a wrapper inside bodyfunction body holderhidewindowloadfunction body holdershowthis works completely fine but messes up the layoutthe problem is that hiding the wrapper interferes with the other jquery functions and plugins used eg layoutplugin so i guess there must be another trick to do this maybe lay a picture or div over the body until windowload has occurredwhat approaches do you useeditthe solution most likely has to be another way than thisplaynone or hide,"['javascript', 'jquery']" +258098,jquery selectors on a html string i am going to get a element from a htmlstring with jquery but i always get an undefined in my consolemy string istd classtestasdtdtd clasecondfghtdtd classlastjkltdand i want to get the tdtesti have testedconsolelogtest td classtestasdtdtd clasecondfghtdtd classlastjkltdinnerhtmlconsolelogtest td classtestasdtdtd clasecondfghtdtd classlastjkltdhtmlconsolelogtest td classtestasdtdtd clasecondfghtdtd classlastjkltdfirstinnerhtmland some more but nothing works does anyone know a solution for my problem,"['jquery', 'html']" +258101,put method form for i am using the following to try and set a put method on the form but it is still doing a post i have referred to the docs and it seems like im doing this rightform for firm html autocomplete off url firm path method put do f,['ruby-on-rails'] +258106,getting value of a thread variable from outside lets say i have a thread running like thisprivate boolean working trueoverride public void run working true do something working false and in my main thread i am constantly putting out the state of working withwhilethreadclassobjectisworking systemoutprintlnthreadclassobjectisworkingwould this work i tried this example and it seems to work but is there a way that this could crash what eg happens if the thread is in the process of changing working while at the exact same time the mainthread tries to read it,['java'] +258111,c stdatomic vs boost atomic in my application i have an int and a bool variable which are accessed multiple writeread by multiple threads currently i am using two mutexes one for int and one for bool to protect those variablesi heard about using atomic variables and operators to write lockfree multithread program my questions arewhats the definition of atomic variables and operatorswhats the main difference between stdatomic andboostatomichpp which one is more standard or popularare these libraries platformdependent i am using gnu gcc 46 onlinux at the moment but ideally it shall be crossplatform i heard that the definition of atomic actually depends on the hardware as well can anyone explain that as wellwhats the best way to share a bool variable among multiple threads i would prefer not to use the volatile keywordare these code threadsafedouble double m double m is only accessed by current threadstdatomicbool atomic bool xatomic bool x true double m 125int int n int and is only accessed by current threadstdatomicint atomic int xstdatomicint atomic int yatomic int y atomic int x int n,['c++'] +258113,how to get property name when it uses yield return how do i get property name of the executing property if the property uses return then methodbasegetcurrentmethodname returns the name of the property but when i use yield return methodbasegetcurrentmethodname returns movenext how do i get the executing property name when it uses yield returnsample code class program static void mainstring args var x myprogramsomething consolereadline public class myprogram public static ienumerablestring something get string var methodbasegetcurrentmethodname for int i 0 i 5 i yield return var,['c#'] +258161,how do i get the users home directory in objectivec in a sandboxed app nshomedirectory is retuning my sandbox root not my home directory stringbyexpandingtildeinpath is doing the same thingthis usersusernamelibrarycontainersappiddata is whats being returned how do i get usersusername,['objective-c'] +258173,introduce icloud in coredata applications after being shipped how to migrate old data i am planning to ship a coredata application but i am unsure if introducing icloud functionality this question come after i have been beta testing my app on iphone filling it with relevant datai then added icloud functionality and start testing on ipad i thiscovered that only new entry were sync between devices this are the tentatives i didworking on iphone fill data enable icloud start working on empty ipadbut i got some weird problems such as child entities attached to wrong parent then i tried thisexport application documents from iphone and import in ipadin this case data are the same on both devices but i still was not able to synchronize old data while new one get perfectly sync most of the time after secondsi understand that coredata sync happen with transaction log exchange so it could be obvious that old data do not get sync but at this point i am asking if someone has already faced this problem which seems quite common to me or if i am missing something some kind of settings or lines of code to make this working as expected,['objective-c'] +258178,boost asio ssl handshake never finishes i have a c client app that uses boost asio to make ssl connections to various servers but against 2 specific servers the ssl connection cannot be established it hangs in the call to boostasiosslstreamhandshakei have used wireshark to observe the conversation between client and server a working ssl connection seems to do thislsocketlowest layerconnect endpoint ec c syn sc syn ack sc ack slsockethandshake sslsocketclient ec c 209 bytes sc 690 bytes sc 198 bytes sc 415 bytes sand at this point the asio handshake call returns indicating all is well and the ssl socket connection works finebut against 2 different servers the handshake looks like thislsocketlowest layerconnect endpoint ec c syn sc syn ack sc ack slsockethandshake sslsocketclient ec c 209 bytes s2 minute pausec rst slooking at log files on these servers it seems as if after the initial 209 bytes are sent in the handshake the server considered the ssl connection fully established but the client is still sitting in the boost asio handshake call and eventually returns ec104 when the connection is resetso i am thinking maybe there are different types of ssl handshakes and maybe there is a simpler one i should be using i know someone will want to know one of the servers causing this problem with the client app is filezilla server for windows setup to use ssltls ftps and the other is a proprietary service running on linuxupdate sam miller asked that i post my code describing how the ssl context is setupclass hpp file contains thistypedef boostasiosslstreamboostasioiptcpsocket sslsocketboostasioio service ioserviceboostasiosslcontext sslcontextsslsocket ssldatasocketboostsystemerror code ecconstructor has these initializersioservice 2 sslcontext ioservice boostasiosslcontextsslv23 ssldatasocket ioservice sslcontext and this codesslcontextset options boostasiosslcontextdefault workarounds boostasiosslcontextverify none and this is the code where the ssl socket is established and the handshake hangsstdcout connecting ssl socket to endpoint buffer stdendlssldatasocketlowest layerconnect tcpendpoint ec stdcout connect done ec ecvalue stdendlif ec throw test 1stdcout starting ssl handshake stdendlssldatasockethandshake sslsocketclient ec stdcout handshake done ec ecvalue stdendlif ec throw test 2,['c++'] +258205,checkboxes inside labels i see all over the web two ways that people code checkboxes which one is correctinput ida typecheckboxlabel foracheckboxlabellabel forbinput idb typecheckboxcheckboxlabelthey both work fine in chrome is one more cross browser than the other is there any differencedemo,"['html', 'css']" +258207,delete white space between divs i am getting some strange whitespace between two divs i haveeach div has the css property thisplay inlineblock and each have a set height and widthi cannot find where the whitespace ishere is a fiddle,"['css', 'html']" +258257,android setvisibility does not thisplay if initially set to invisble i have a glsurface occupying the full screen at the click of a button i want another layout to appear settings type of thing if i start with the overlay being visible i can make it invisible and then visible again with no problem but if i start with it invisible i cannot make it ever visible again code followsxml version10 encodingutf8relativelayout xmlnsandroidandroidlayout widthmatch parentandroidlayout heightmatch parent androidopenglglsurfaceview androidididglplaysurface androidlayout widthmatch parent androidlayout heightmatch parent androidopenglglsurfaceviewradiogroup androidididradiogroup1 androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentbottomtrue androidlayout alignparentlefttrue androidorientationhorizontal radiobutton androidididbtnrotate androidlayout widthwrap content androidlayout heightwrap content androidlayout marginleft10dp androidcheckedtrue androidtextr androidtextcolor0 radiobutton androidididbtnpan androidlayout widthwrap content androidlayout heightwrap content androidlayout marginleft15dp androidtextp androidtextcolor0 radiogroupbutton androidididbtnlights androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentbottomtrue androidlayout marginleft15dp androidlayout torightofidradiogroup1 androidtextlights relativelayout xmlnsandroid androidididlayoutlights androidlayout width100dp androidlayout height100dp androidvisibilityvisible does not work if set to invisible androidlayout alignparentbottomtrue androidlayout alignparentrighttrue androidbackgroundf button androidididbtnlightsok androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentbottomtrue androidlayout alignparentlefttrue androidlayout marginleft15dp androidtextok button androidididbtnlights androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentbottomtrue androidlayout alignparentlefttrue androidlayout marginleft15dp androidtextok relativelayoutrelativelayoutprivate onclicklistener monlightsclick new onclicklistener public void onclickview arg0 ifmlayoutlightsgetvisibility viewvisible mlayoutlightssetvisibilityviewinvisible else mlayoutlightssetvisibilityviewvisible,['android'] +258260,cost of inlining methods in c i have recently implemented a quicksort algorithm in c sorting on an integer array containing millions of items the codes performance is approximately 10 behind nets implementation private static void qsint arr int left int right if left right return var pindex partitionarr left right qs arr left pindex qs arr pindex 1 righton an array of 5 million items this code is about 60ms slower than netssubsequently i created an another method that has the partition method inlined into qs eliminating the method call and the return statement this however resulted in a drop in perfomance to about 250ms slower than nets sort methodwhy does this happenedit this is the code the partition method in the inlined version of qs the entire content of this method with the exception of the return statement replaces the var pindex partitionarr left right lineprivate static int partitionint arr int left int right int pivot arrleft int leftpoint left 1 int pindex right 1 int temp 0 while true do pindex while arrpindex pivot do leftpoint while arrleftpoint pivot if leftpoint pindex temp arrleftpoint arrleftpoint arrpindex arrpindex temp else break return pindexedit 2in case anyones interested in compiling heres the code that calls the algorithmsedit 3new test code from haymos suggestionprivate static void mainstring args const int globalruns 10 const int localruns 10 var source enumerablerange1 20orderbyn guidnewguidtoarray var a new intsourcelength int start end total for int z 0 z globalruns z consolewritelinerun 0 z1 total 0 for int i 0 i localruns i arraycopysource a sourcelength start environmenttickcount arraysorta end environmenttickcount total end start consolewriteline0tl 1mstavg 2ms net total total localruns total 0 for int i 0 i localruns i arraycopysource a sourcelength start environmenttickcount quicksortsortinlinea end environmenttickcount total end start consolewriteline0tl 1mstavg 2ms inlined total total localruns total 0 for int i 0 i localruns i arraycopysource a sourcelength start environmenttickcount quicksortsortnoninlinea end environmenttickcount total end start consolewriteline0tl 1mstavg 2msn not inlined total total localruns,['c#'] +258301,php remove line break or cr lf with no success i did a function to remove line break with php with no success i tryed all replace code and i still get these line break i create a json file and i cannot read it from jsonp with jquery because of these line break seem to break it allfunction cleantexttext trim preg replace s text text preg replacernnrti textreturn textwhen i look at the source there some line break appening in all href img and brthis is a json encode outputexample ahref titlelink to content websiteline break afer ait is hapenig to img src and brthe only way i can remove these break it withtext preg replacesi textbut you understant that there is no space left in all the string and it is not what we want,['php'] +258309,nodejs reliability for large application i am new to nodejs and am currently questioning its reliabilitybased on what i have seen so far there seems to be a major flaw any uncaught errorexceptions crashes the server sure you can try to bulletproof your code or put trycatch in key areas but there will almost always be bugs that slip through the crack and it seems dangerous if one problematic request could affect all other requests there are 2 workarounds that i founduse daemon or module like forever to automatically restart the server when it crashes the thing i do not like about this is that the server is still down for a second or two for a large site that could be hundreds of thousands of requestcatch uncaught exceptions using processonuncaughtexception the problem with this approach as far as i know is that there is no way to get a reference to the request that causes the exception so that particular request is left hanging user sees loading indicator until timeout but at least in this case other nonproblematic requests can still be handledcan any nodejs veteran pitch in,['javascript'] +258316,n is negative positive or zero return 1 2 or 4 i am building a powerpc interpreter and it works quite well in the power architecture the condition register cr0 eflags on x86 is updated on almost any instruction it is set like this the value of cr0 is 1 if the last result was negative 2 if the last result was positive 4 otherwisemy first naive method to interpret this isif n 0 cr0 1else if n 0 cr0 2else cr0 4however i understand that all those branches would not be optimal being run millions of times per second i have seen some bit hacking on so but none seemed adeguate for example i found many examples to convert a number to 1 0 or 1 accordingly to the sign or 0 but how to make 1 1 1 2 0 4i am asking for the help of the bit hackersthanks in advanceupdatefirst of all thanks guys youve been great i will test all of your codes carefully for speed and youll be the first to know whos the winnerjalf about your first advice i was not actually calculating cr0 on every instruction i was rather keeping a lastresult variable and when and if a following instruction asked for a flag do the comparison three main motivations took me back to everytime update on ppc youre not forced to update cr0 like on x86 where add always change eflags even if not needed you have two flavours of add one updating if the compiler chooses to use the updating one it means that it is going to use the cr0 at some point so there no point at delayingthere is a particularly painful instruction called mtcrf that enables you to change the cr0 arbitrarly you can even set it to 7 with no arithmetic meaning this just destroys the possibility of keeping a lastresult variable,['c++'] +258363,how to hide a vertical scroll bar when not needed i have a textarea which is contained in a div as i have jquery hint and wanted to use opacity without changing the borderthere is a visible vertical scroll bar how i only want this thisplayed when i am typing in the text field and it goes beyond the container i have tried overflow auto but does not worktextfieldlabel div idname textarea namemessage typetext idmessage titleenter message here rows9 cols60 maxlength20textarea divlabelstylesname border 1px solid c810ca width 270px height159px overflow hidden position relative message height 400px width 235px overflow hidden position absolute,"['html', 'css']" +258372,java no enclosing instance of type foo is accessible i have the following codeclass hello class thing public int size thing size 0 public static void mainstring args thing thing1 new thing systemoutprintlnhello world i know thing does nothing but my hello world program compiles just fine without it it is only my defined classes that are failing on meand it refuses to compile i get no enclosing instance of type hello is accessible at the line that creates a new thing i am guessing eitheri have system level problems either in drjava or my java install ori have some basic misunderstanding of how to construct a working program in javaany ideas,['java'] +258374,make xcode 43 warn about undeclared methods that exist in the current implementation xcode 43 does not warn about undeclared methods when they exist in the current implementation which is a great new feature however this is causing an issue in certain circumstances when using my project on xcode 42how do i reenable the warnings for undeclared methodsfor exampleinterface mashtun nsobject voidfooendimplementation mashtun voidfoo cgrect rect self smallrect nslogmy small rect nsstringfromcgrectrect cgrectsmallrect return cgrectmake0 0 100 100endin xcode 42 this failswarning instance method smallrect not found return type defaults to iderror initializing cgrect aka struct cgrect with an expression of incompatible type id i completely understand the warning and error in xcode 42 since it is not allowing the search for methods within the current implementation scope the fix is simple either put the smallrect method above the foo method or declare the smallrect method in a category or the header but how do i turn on a warning in xcode 43 to catch this error before passing it on to colleagues running 42,['objective-c'] +258386,how do i use the python scrapy module to list all the urls from my website i want to use the python scrapy module to scrape all the urls from my website and write the list to a file i looked in the examples but did not see any simple example to do this,['python'] +258400,android how to turn screen on and off programmatically before marking this post as a duplicate i am writing this post because no other post holds the solution to the problemi am trying to turn off the device then after a few minutes or sensor change turn it back onturn off thisplay testsi am able to turn off the screen usingparamsflags layoutparamsflag keep screen onparamsscreenbrightness 0getwindowsetattributesparamsi have been unable to turn off the screen using the wlrelease methodturn on thisplay testmy first guess as follows does not work nothing happens screen remains offparamsflags layoutparamsflag keep screen onparamsscreenbrightness 1fgetwindowsetattributesparamsi also then tried to use wakelocks with no successpowermanagerwakelock wl pmnewwakelockpowermanagerscreen bright wake lock tag wlacquirefinally i have tried the following with no resultgetwindowaddflagswindowmanagerlayoutparamsflag turn screen onall in all i do not get any kind of error in the console for any of these methods my test text screen should be on is on the the screen when i turn on the device using the power button this shows that the code should have ran please only answer if you have tested the code it seems like many of the functions such as paramsscreenbrightness 1 do not work as they should according to the sdkthanks,['android'] +258428,how to stub carrierwave in rspec i want to stub carrierwave to prevent it from fetch images on the web during my tests how would i stub things to achieve thismy crawler parses a remote web page and saves one image url into the model carrierwave will fetch that image automatically during the save operation it works well however i have a test about the parsing of pages and everytime it will download the file which slows down the testingupdatei mount the uploader as the following in the preexisting paperclip columnmount uploader image topicimageuploader mount on image file namei tried to stub the following but neither workedtopicany instancestubstore imagetopicany instancestubstore image file nametopicany instancestubstore image remote url,['ruby-on-rails'] +258481,what exactly is a sideeffect in c is it a standard term which is well defined or just a term coined by developers to explain a concept and what is the concept as i understand this has something to do with the allconfusing sequence points but am not surei found one definition here but does not this make each and every statement of code a side effecta side effect is a result of an operator expression statement or function that persists even after the operator expression statement or function has finished being evaluatedcan someone please explain what the term side effect formally means in c and what is its significancefor reference some questions talking about side effectsis comma operator free from side effectforce compiler to not optimize sideeffectless statementsside effects when passing objects to function in c,['c++'] +258496,wix customactiondata is empty in called customaction once again i am stuck at a problem that is probably easy to solvei want to extend a setup created with wix to make changes in the configuration file of the installed program in order to do this i have created a customaction to be able to change the configuration file i need to know the instalocation of it within my customaction therefore i try passing the instalocation and filename to my customaction here lies the problem the customactiondataattribute is always empty and the setup throws an exceptionmy customaction is a c dll file demodatumerzeugencadll it contains a method datumeintragen which modifies the configuration file i am trying to access the data this waystring path sessioncustomactiondatalocationthis is where the exception is thrown i only got the german error message but it says something along the lines the supplied key was not found in the dictionary der angegebene schla14ssel war nicht im warterbuch angegebenthis is how i try passing the properties from my setupscript to my custom actionbinary iddemodatumeinrichtenca sourcefiledemodatumerzeugencadllcustomaction iddemodatumsetproperty returncheck propertydatumeintragen valuelocationinstalocationnamestrategieplanconfigxmlcustomaction iddemodatum binarykeydemodatumeinrichtenca dllentrydatumeintragen executedeferred returncheck hidetargetnoinstallexecutesequence custom actiondemodatumsetproperty afterinstallfiles custom actiondemodatum afterdemodatumsetpropertyinstallexecutesequencei have seen many examples where it was done the same way or at least very similar i have tried many things but nothing seems to help like changing the value after in custom actiondemodatumsetproperty afterinstallfiles customactiondata is always zeroi check it with sessioncustomactiondatacountonce again i am pretty thankful for any help or hints where i have done something wrong,['c#'] +258509,the source was not found but some or all event logs could not be searched i am getting the following exception i have given full control to aspnet account on eventlogs in registry editsecurityexception the source was not found but some or all event logs could not be searched inaccessible logs securitysystemdiagnosticseventlogfindsourceregistrationstring source string machinename boolean readonly boolean wanttocreate 664systemdiagnosticseventlogsourceexistsstring source string machinename boolean wanttocreate 109systemdiagnosticseventlogsourceexistsstring source 14 microsoftapplicationblocksexceptionmanagementdefaultpublisherverifyvalidsource 41i guess this is due to some configuration issue on server,"['c#', '.net']" +258517,wix auto update i have standalone setup project created with wix and i need some solution for autoupdate my application my application shuold check for new version on startup and automatically download and install new version if availablewhats the best solution to do this is there something lik clickonce in wix clickthrough seems to be dead am i right,"['c#', '.net']" +258522,who reads the value of envssl cert file i used to receive the following erroropensslsslsslerror ssl connect returned1 errno0 statesslv3 read server certificate b certificate verify failedfrom cruby192libruby191nethttprb678in connect after reading through this i thiscovered that the fix is to download the cacertpem file from here the post recommends doing something like thisenvssl cert file filejoinfiledirname file cacertpemand indeed this solves the problem however who reads the value of ssl cert file altering the environment does not seem like the ruby way of doing it i am looking for a solution that could work with both rails and sinatra,"['ruby-on-rails', 'ruby']" +258523,android list files contained in assets subfolder i create some folders into assets each folder contains files that i would like to list i am using following code but i always get a null value for filelist thank youi used listfilesassetsimagesnothingprivate void listfilesstring dirfrom string dirto file f new filedirfrom string filelist flist if filelist null for int i 0ifilelistlengthi logdfilelisti,"['java', 'android']" +258542,best practices for synchronizing a sql database with a rest remote server on android i have a custom android contentprovider which stores and retrieves data from a sqlite databaselet us assume one of the db tables has an id column and a name column and a content like this id name 1 d1 2 d2 3 d3 4 d4 this sqlite db is kept in sync with a remote database and new data is fetched periodically over the networkthe possible operations on the table are as followsexisting rows can be deletednew rows can be addedthe name column of existing rows can be modifiedlet us now assume that all the possible operations happen at once and after fetching some uptodate data from a remote server the new content of this table has to be set as follows id name 1 d7 3 d3 4 d6 5 d5 there can be two different approaches to do thatquery the database and check each existing rows to see if they need to be updated then add any new rows and delete any missing rows though this method can be a bit tricky in case we want to update the database with a pagination approach and not with a single network fetchdelete the entire table with a single delete sql command and then add all the rows received from the serveron android i am currently implementing the second method with batch operations to maximize the performancefinal arraylistcontentprovideroperation operations new arraylistcontentprovideroperation with this uri the content provider deletes all rowsoperationsaddcontentprovideroperationnewdeleteuserscontent uribuildfinal contentvalues values new contentvaluesvaluesputid column 1valuesputname column d7valuesputid column 3valuesputname column d3valuesputid column 4valuesputname column d6valuesputid column 5valuesputname column d5operationsaddcontentprovideroperationnewinsertuserscontent uriwithvaluesvaluesbuildgetapplicationcontextgetcontentresolverapplybatchmycontentproviderauthority operationsis this the best approach or would method 1 or some other method be better in terms of performanceedit for example taking approach 2 an overridden contentproviderbulkinsert which uses database transactions could speed up the batchinsert operation a lot see this question,"['android', 'sql']" +258553,thisplay duration in milliseconds i want to thisplay duration with milliseconds on a web page so far i have done this i managed to thisplay this output on a label 0250 but i want to thisplay milliseconds as well so the result should look like this 0250 how do i achieve this code behindprotected void page loadobject sender eventargs e datetime starttime datetimenow sleep for 25s threadsleep2500 datetime stoptime datetimenow timespan duration stoptime starttime resulttext durationtostringmmssff,['c#'] +258554,java jpanel with margins and jtextarea inside i want to create something like thismain panel has its margins x and textarea in the center of that panel which almost fills up the panelat the bottom is another panel with custom size height y which can be toggled visible and unvisible with some shortcut bottom panel has flowlayout and few elementsthe problem is i have no idea how to do thisboxlayout has no marginsi tried with gridbaglayout but i does not work or i cannot understand it enough i tried also with setting jtextarea marginstextmainsetmarginnew insetsinsettop insetleft insetbottom insetrightbut when there is a lot of text top and bottom margin thisappear so now i am trying with panelscan someone help me with this please,['java'] +258566,how to add a link to a file in visual studio using envdte i am writing a custom scaffolder for our project and this scaffolder should add links to dto declarations for client side appi have a possibility to retrieve an instance of project itemfolder getprojectfolder viewsshared and i already found that it is possible to add links using projectnodeaddnewfilenodetohierarchystring string methodi can get a reference to the dte service by simply accessing dte variable predefined in powerconsolethe question is how to get instance of projectnode i am interested in,['c#'] +258574,converting html to excel i know that excel is capable of opening html files directly but the content of the file will still be html is there any way i can change the contents of the file from html to xls or xlsx,['html'] +258586,include jaxb using maven working on my 160 16 jdk i generated my stub classes from a wsdl using apache cxf 252 which uses the most recent jaxbapi 22 i know it is possible to have it use jaxbapi 21 but in order to avoid compatibility issues i would rather have it use the current version since my jdk features jaxb 21 the build fails with the following messageerror at xmlelementrefname protocol namespace urnchbeoemc type jaxbelementclass required falsetherefore i tried to make maven include the most recent jaxb api and impl using the following dependenciesdependency groupidjavaxxmlbindgroupid artifactidjaxbapiartifactid version225versiondependencydependency groupidcomsunxmlbindgroupid artifactidjaxbimplartifactid version225versiondependencywhile the two jars have been added to maven dependencies in eclipse the error message persists both in eclipse and maven buildhow can i include these jars in my maven build and have them used both in eclipse and on the target systemps please find the complete pom hereproject xmlns xmlnsxsi xsischemalocation 0 0xsd modelversion400modelversion groupidchbeogroupid artifactidemcfrontartifactid version313snapshotversion repositories repository idjbossid namejbossname urlurl repository repository idfreehepid namefreehepname urlurl repository repository idjcurlid urlurl repository repository idjavanetid urlurl repository repository iddjmaven2id urlurl namedynamicjasper public repositoryname repository repositories properties projectbuildsourceencodingutf8projectbuildsourceencoding properties build defaultgoalcompiledefaultgoal sourcedirectorysrcmainjavasourcedirectory testsourcedirectorysrctestjavatestsourcedirectory outputdirectorytargetmainoutputdirectory testoutputdirectorytargettesttestoutputdirectory resources resource targetpathchbeoemcfrontresourcestargetpath directorysrcmainresourcesdirectory excludes excludesrcmainresourcessecurityjarsignexclude excludes resource resources testresources testresource targetpathchbeoemcfrontresourcestargetpath directorysrctestresourcesdirectory testresource testresource targetpathchbeoemcfrontresourcestargetpath directorysrcmainresourcesdirectory excludes excludesrcmainresourcessecurityjarsignexclude excludes testresource testresources plugins plugin groupidorgapachemavenpluginsgroupid artifactidmavencompilerpluginartifactid configuration source16source target16target configuration plugin plugin groupidorgcodehausmojogroupid artifactidaspectjmavenpluginartifactid version11version configuration compliancelevel16compliancelevel aspectlibraries aspectlibrary groupidorgspringframeworkgroupid artifactidspringaspectsartifactid aspectlibrary aspectlibraries configuration executions execution goals goalcompilegoal goaltestcompilegoal goals execution executions plugin plugin groupidorgapachemavenpluginsgroupid artifactidmavenassemblypluginartifactid configuration archive manifest mainclasschbeoemcfrontfactoryfrontmainclass addclasspathtrueaddclasspath classpathprefixlibclasspathprefix manifest archive descriptors descriptorassemblyxmldescriptor descriptors configuration executions execution idmakeassemblyid phasepackagephase goals goalsinglegoal goals execution executions plugin plugin groupidorgapachemavenpluginsgroupid artifactidmavensurefirepluginartifactid configuration includes includechbeoemcfrontalltestsjavainclude includes configuration plugin plugin groupidorgapachemavenpluginsgroupid artifactidmavenshadepluginartifactid version14version executions execution phasepackagephase goals goalshadegoal goals configuration createdependencyreducedpomfalsecreatedependencyreducedpom transformers transformer implementationorgapachemavenpluginsshaderesourcemanifestresourcetransformer mainclasschbeoemcfrontfactoryfrontmainclass transformer transformer implementationorgapachemavenpluginsshaderesourceappendingtransformer resourcemetainfspringhandlersresource transformer transformer implementationorgapachemavenpluginsshaderesourceappendingtransformer resourcemetainfspringschemasresource transformer transformers configuration execution executions plugin plugin groupidorgapachemavenpluginsgroupid artifactidmavenjarpluginartifactid executions execution idsignid phasepackagephase goals goalsigngoal goals configuration keystoresrcmainresourcessecurityjarsignserverpfxkeystore typepkcs12type aliasbeoitchalias storepastorepass signedjarprojectbuilddirectorysignedprojectbuildfinalnamejarsignedjar verifytrueverify configuration execution executions plugin plugins build dependencies dependency groupidcoml2fprodgroupid artifactidl2fprodcommonallartifactid version691version dependency dependency groupidorgswixmlgroupid artifactidswixmlartifactid version15144version dependency dependency groupidnetjavaballoontipgroupid artifactidballoontipartifactid version11version dependency dependency groupidorgswinglabsgroupid artifactidswingxartifactid version16version dependency dependency groupidorgspringframeworkgroupid artifactidspringcoreartifactid version256sec01version dependency dependency groupidorgspringframeworkgroupid artifactidspringcontextartifactid version256sec01version dependency dependency groupidorgspringframeworkgroupid artifactidspringaopartifactid version256sec01version dependency dependency groupidorgspringframeworkgroupid artifactidspringaspectsartifactid version256sec01version dependency dependency groupidorgspringframeworkgroupid artifactidspringtxartifactid version256sec01version dependency dependency groupidorgspringframeworkgroupid artifactidspringtestartifactid version256sec01version scopetestscope exclusions exclusion artifactidjunitartifactid groupidjunitgroupid exclusion exclusions dependency dependency groupidjfreegroupid artifactidjfreechartartifactid version109version dependency dependency groupidjunitgroupid artifactidjunitartifactid version44version scopetestscope dependency dependency groupidcomsunjavajnlpgroupid artifactidjnlpartifactid version60version dependency dependency groupidcomthoughtworksxstreamgroupid artifactidxstreamartifactid version131version dependency dependency groupidcommonslanggroupid artifactidcommonslangartifactid version25version dependency dependency groupidorgjsciencegroupid artifactidjsr275artifactid version080version dependency dependency groupidorgapachepoigroupid artifactidpoiartifactid version37version dependency dependency groupidnetsfjasperreportsgroupid artifactidjasperreportsartifactid version374version exclusions exclusion groupidcommonsbeanutilsgroupid artifactidcommonsbeanutilsartifactid exclusion exclusion groupidcommonscollectionsgroupid artifactidcommonscollectionsartifactid exclusion exclusion groupidcommonslogginggroupid artifactidcommonsloggingartifactid exclusion exclusion groupidjfreegroupid artifactidjcommonartifactid exclusion exclusion groupidjfreegroupid artifactidjfreechartartifactid exclusion exclusion groupidxmlapisgroupid artifactidxmlapisartifactid exclusion exclusion groupidbouncycastlegroupid artifactidbcmailjdk14artifactid exclusion exclusion groupidbouncycastlegroupid artifactidbcprovjdk14artifactid exclusion exclusion groupidbouncycastlegroupid artifactidbctspjdk14artifactid exclusion exclusion artifactidjdtcoreartifactid groupideclipsegroupid exclusion exclusions dependency dependency groupidorgeclipsejdtcorecompilergroupid artifactidecjartifactid version351version dependency dependency groupidarcomfdvsgroupid artifactiddynamicjasperartifactid version312version exclusions exclusion groupidjasperreportsgroupid artifactidjasperreportsartifactid exclusion exclusion groupidcommonslogginggroupid artifactidcommonsloggingartifactid exclusion exclusions dependency dependency groupidjavaxxmlbindgroupid artifactidjaxbapiartifactid version225version dependency dependency groupidcomsunxmlbindgroupid artifactidjaxbimplartifactid version225version dependency dependenciesproject,['java'] +258610,drag and drop in android 3x causes illegalstateexception after small number on drags there is a problem with drag and drop mechanism at android 3x after doing some drags say 30 drags an exception accrues see the attached linkmsgandroidplatform2apvo248nnyrki5dct8xcj i am getting in log the same thing as attached to that postandroid technician answers there that it is bug in the api and says the only way to avoid the problem is to call garbage collector i did it the exception not been thrown anymore but after a while say more 3040 drags android stops calling the drop event from some reasoni tried to refresh all view by release all resourcescanvasdrawing cacherecycling bitmaps and recreate them and it did not helps did not throw the exception anymore but still after some drags the drop event do not work the only thing that helps is close the activity and restart it againanyone solved this problem somehow or have a good simple alternative beside implement my own drag and drop functionalityi would like to get solution that would not force me to restart or recreate anything that do not suppose tohere is sample code that demonstrate the bug not demonstrates the part which i said about the problem with the drop event after using the systemgc public class draganddropexampleactivity extends activity private boolean misbeendragged falseoverridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain final imageview imageviewtodrag imageview findviewbyidridimage view to drag imageviewtodragsetclickabletrue imageviewtodragsetontouchlistenernew ontouchlistener override public boolean ontouchview v motionevent event if eventgetaction motioneventaction down misbeendragged true dragshadowbuilder shadowbuilder new dragshadowbuilderimageviewtodrag imageviewtodragstartdragnull shadowbuilder imageviewtodrag 0 else if eventgetaction motioneventaction up misbeendragged false return false this is the xmlxml version10 encodingutf8framelayout xmlnsandroidandroidididmain frameandroidlayout widthfill parentandroidlayout heightfill parent imageview androidididimage view to drag androidlayout widthwrap content androidlayout heightwrap content androidsrcdrawableic launcher imageviewthis is the stack trace0604 133432730 eview8061javalangillegalargumentexception at androidviewsurfacelockcanvasnativenative method at androidviewsurfacelockcanvassurfacejava350 at androidviewviewstartdragviewjava11489 at comshowdragandropdraganddropexampleactivity1ontouchdraganddropexampleactivityjava32 at androidviewviewthispatchtoucheventviewjava4617 at androidviewviewgroupthispatchtransformedtoucheventviewgroupjava1560 at androidviewviewgroupthispatchtoucheventviewgroupjava1291 at androidviewviewgroupthispatchtransformedtoucheventviewgroupjava1560 at androidviewviewgroupthispatchtoucheventviewgroupjava1291 at androidviewviewgroupthispatchtransformedtoucheventviewgroupjava1560 at androidviewviewgroupthispatchtoucheventviewgroupjava1291 at androidviewviewgroupthispatchtransformedtoucheventviewgroupjava1560 at androidviewviewgroupthispatchtoucheventviewgroupjava1291 at comandroidinternalpolicyimplphonewindowdecorviewsuperthispatchtoucheventphonewindowjava 1862 at comandroidinternalpolicyimplphonewindowsuperthispatchtoucheventphonewindowjava1286 at androidappactivitythispatchtoucheventactivityjava2315 at comandroidinternalpolicyimplphonewindowdecorviewthispatchtoucheventphonewindowjava1835 at androidviewviewthispatchpointereventviewjava4689 at androidviewviewrootdeliverpointereventviewrootjava2415 at androidviewviewroothandlemessageviewrootjava2077 at androidoshandlerthispatchmessagehandlerjava99 at androidoslooperlooplooperjava132 at androidappactivitythreadmainactivitythreadjava4126 at javalangreflectmethodinvokenativenative method at javalangreflectmethodinvokemethodjava491 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava844 at comandroidinternaloszygoteinitmainzygoteinitjava602 at dalviksystemnativestartmainnative methodto make the exception accrue just drag the image to some point on the screen and leave the finger repeat that exactly 30 times and the exception is throwni made this very simple example to demonstrate that the exception thrown without any overhead caused by my application tia,['android'] +258632,what is a c delegate what is the general idea of a delegate in c what are they how are they used and what are they used fori would like to first learn about them in a black box way but a bit of information on the guts of these things would be great toothis is not c at its purest or cleanest but i notice that the codebase where i work has them in abundance i am hoping to understand them enough so i can just use them and not have to delve into the horrible nested template awfulnessthese two the code project articles explain what i mean but not particularly succinctlymember function pointers and the fastest possible c delegatesthe impossibly fast c delegates,['c++'] +258646,making a column in slickgrid a hyperlink as the title says i am trying to make a cell for each row a hyperlink using slickgrid i have been trying to insert it in the code behind c but the grid does not seem to like html being passed into the field value it thisplays the link as plain texti thought there might be a formatter for it but apparently not any ideas cheerseditthe examples say formatters should go when you declare the columns matma using your suggestion would it be something like this name action field link id link sortable false width 100 var linkformatter function row cell value columndef datacontext return a hreflink datacontextid value a sorry for being a bit crpanswer for anyone who comes looking name action field link id link sortable false width 100 formatter linkformatter function row cell value columndef datacontext return a hreflink datacontextid value a,['jquery'] +258651,how to enter rails console on production via capistrano i want to enter the rails console on production server from my local machine via capistranoi found some gists eg and when i enter console via cap production console i get the following result1921680100foldername username cap console rails envproduction executing console executing cd varwmyappcurrent rails console production servers wexamplede wexamplede executing command wexamplede rvm pathhomervm homervmbinrvmshell 193 c cd varwmyappcurrent rails console productionvarwmyappreleases20120305102218appcontrollersusers controllerrb3 warning already initialized constant verify peerloading production environment rails 321switch to inspect modeand thats it now i can enter some text but nothing happenshas anybody an idea how to get that work or another solution for my problem,['ruby-on-rails'] +258653,can you explain me this strange behaviour of c with optional arguments possible duplicatec optional parameters on overridden methods this is the output of the following codepeter 1peter 0fred 1fred 1can you explain me why the call of peter ptellyourage and pdosomething is not identicalhere the code to try it yourself vs2010 and fw 4 static void mainstring args peter p new peter ptellyourage expected 1 result 1 pdosomething expected 1 result 0 fred f new fred ftellyourage1 expected 1 result 1 fdosomething expected 1 result 1 consolereadkey public abstract class person public abstract void tellyourageint age abstract method without default valuepublic class peter person public override void tellyourageint age 1 override with default value consolewritelinepeter age public void dosomething tellyourage public class fred person public override void tellyourageint age override without default value consolewritelinefred age public void dosomething tellyourage1,['c#'] +258656,custom method names in aspnet web api i am converting from the wcf web api to the new aspnet mvc 4 web api i have a userscontroller and i want to have a method named authenticate i see examples of how to do getall getone post and delete however what if i want to add extra methods into these services for instance my usersservice should have a method called authenticate where they pass in a username and password however it does not workpublic class userscontroller baseapicontroller public string getall return getall public string getint id return get 1 id public user getauthenticatestring username string password string applicationname logwriterwritestringformatreceived authenticate request for username 0 and password 1 and application 2 username password applicationname check if valid leapfrog login var decodedusername usernamereplace40 var encodedpassword passwordlength 0 utilityhashstringpassword stringempty var leapfrogusers leapfroguserdatafindalldecodedusername encodedpassword if leapfroguserscount 0 return new user id uintleapfrogusers0id guid leapfrogusers0guid else throw new httpresponseexceptioninvalid login credentials i can browse to myapiapiusers and it will call getall and i can browse to myapiapiusers1 and it will call get however if i call myapiapiusersauthenticateusername0password1 then it will call get not authenticate and errorthe parameters dictionary contains a null entry for parameter id of nonnullable type systemint32 for method systemstring getint32 in navtrakserviceswcfnavtrakapicontrollersuserscontroller an optional parameter must be a reference type a nullable type or be declared as an optional parameterhow can i call custom method names such as authenticate,['c#'] +258668,jna memory leak given this c codevoid loaddatachar myvar std string strreally long string here unsigned int size strlength 1 myvar new charsize strncpymyvar strc str sizeand this jna javapointer myvar new memorypointersizethislibloaddatamyvarthissomevar myvargetpointer0getstring0i am having memory leaks as i understand it getpointer0 should create a pointer object that should be released on finalize but it seems to not beam i missing something this seems up to spec and i can run the function above with no leaks in c finei call the java code in a loop to test the leak i have tried putting in pauses and manually calling the gc also it will bloat to gigabytes rather quickly this wayi have been banging my head against this for a few days now and it sucks to get hung up on something so trivial as attempting to free memoryas far as i can tell i can only manually free memory in java if i have the address but i cannot see how i would get thateditnevermind i do not even think there is a way to do manually free through jna without extending it,"['java', 'c++', 'c']" +258675,why is visual studio 2010 prettyprinting in c mode while stepping through c code i am encountering a strange issue i have all the latest updates in my pc my os is windows 7 can anyone help me out with this i have tried resetting the visual studioand here is the exact problem blown up to make it easier to see,"['c#', '.net']" +258711,how to show the next slide when you click on the image in flexslider i am using the flexslider plugin and i wanted to know if there is an easy way apart from changing the core of the plugin which is what i am going to do if i do not find an easy answerto show the next slide when you click on the current slide i set up the flexslider like thisflexsliderflexslider directionnav false slideshow false animation slide controlscontainer flexcontainer i thisabled the prevnext command because i did not like them what should i do,"['javascript', 'jquery']" +258716,why does observablecollection not support bulk changes what are the potential problems caused by an observablecollection supporting operations like addrange or removerange there must be a reason why microsoft did not provide them now that observablecollection is so frequently used with wpfyou could implement your own collection that supports bulk operations and implements inotifycollectionchanged what happens if i bind such a control to an itemscontroldoes anyone know of itemscontrols that do not support bulk changes,['c#'] +258761,find string index from last in python i think it might be a silly question but as i am totally new to python i do not know anything about iti want to find the last position of a target string in given str as a inputfor exstrhelloand targetl then it should output 3how can i do this,['python'] +258772,count number of days between two dates how do i count the number of days between these two datesstart date dateparse 20120302 144621 0100end date dateparse 20120402 144621 0200,"['ruby-on-rails', 'ruby']" +258791,joomla getitems and how it works i am looking at line 34 of administratorcomponentscom contactviewscontactsviewhtmlphp where is says thisitems thisgetitems what i do not understand is how that is actually calling the protected function getlistquery on line 123 of administratorcomponentscom contactmodelscontactsphpthere are also some other things i do not understand how are working like thispagination thisgetpaginationthisstate thisgetstatewhat are these calling i looked at the documentation for get but it does not say what these are actually calling because i do not see any methods called getpagination getstate or getitems it appears the getitems is somehow magically calling getlistquery,"['php', 'html']" +258804,how to evaluate user expressions in a sandbox i want my app to evaluate an expression from an untrusted user that i will be reading from a json file such asvalue gettime 60 and isfoobari have found many threads about this here on stackoverflow usually recommending using javas own scriptengine class which can read javascript or recommending the user to either use an existing library such as jexl mvel or any other from this list but they all seem to rely on a trusted user ex a configuration file you write yourself and want to do some scripting in it but in my case i want my expression evaluation to run in a secure sandbox so the user cannot do something as simple asvalue whiletrue orvalue new javaiofilerttxtdelete this works on mveland lock up my app or access unwanted resources1 so are any of those existing libraries able to be easily configured so that it can run on a safe box by easily i mean high level configuration api that would faster for me to use than to write my own expression evaluator after doing a little bit of my own research both jexl and mvel seem to be out2 or is there an existing expression language that is extremely simple so that it cannot be exploited by an untrusted user all the ones i found are very complex and implement things like loops import statements etc all i need is to parse math logic operators and my own defined variables and methods anything beyond that is outside of my scope3 if the only solution is to write my own expression evaluator then where can i find some guidance on how to write a consistent security model i am new to this and have no idea of what are the common tricks used for code injection which is why i wanted avoid having to write this on my own,"['java', 'android']" +258810,file get contents failed to open stream http request failed http11 404 not found i am having some weird problems with file get contents after moving my site to a new domain i had to set up a new domain and ip address using plesk to get a new ssl certificate working now my file get contents calling a script on the same domain is giving me thisfailed to open stream http request failed http11 404 not foundif i call the same url using file get contents on another server it works fine and if i call wgooglecom from the server thats failing that works so it only seems to be if i call a url on the same severi have a feeling it might have something to do with having two ips with two different ssl certificates on the one server when i file get contents index page of the server from the server i get the plesk this is a new domain page so its like apache isnt looking up the right virtual host when its called from its own severto clarify hopefullyon the server hosting the domainfile get contentsoffset0s date20120205e date20120313orderrelease datedirdesccid12gives failed to open stream http request failed http11 404 not foundfile get contentsworks correctlyon another serverfile get contentsoffset0s date20120205e date20120313orderrelease datedirdesccid12works finei have tried turning ssl off and i still get the same problem,['php'] +258819,does c 4 optimize away namespaces in a manner that previous c versions did not this question is for interest sake i am working with a thirdparty library and came across the following documentation on a cmssecuritydummy class do not delete this class this class prevents the compiler from dropping entire namespace under net 40does anybody know or can anybody speculate why net 4 would drop the namespace if the dummy class were removed because net 4 is explicitly named in the source code comment i assume previous c versions exhibit behaviour that do not require this dummy class that is purely speculative though screen shotdecompiled source code region assembly cmssettingsproviderdll v4030319 solutionwrootbincmssettingsproviderdllendregionusing systemnamespace cmssecurity summary do not delete this class this class prevents the compiler from dropping entire namespace under net 40 public class dummy summary do not delete this class this class prevents the compiler from dropping entire namespace under net 40 public dummy,['c#'] +258830,creating an async method in net 40 that can be used with await in net 45 i have a net project that uses c in net 40 and vs2010what i would like to do is add some async overloads to my library to make doing async programming easier for users in net 45 with the await keyword right now the methods that are being overloaded are nonasynchronous also i do not want to use any async methods myself just create new ones and make them availableis creating async methods in net 40 and vs2010 possible and if so what should the net 40 async method look likebecause i am using vs2010 i do not have access to the async keyword so what needs to happen to emulate that behavior in net 40 for example does it need to return any particular type and does any code need to happen inside the method to make the currently nonasynchronous code it is calling happen asynchronously,"['c#', '.net']" +258831,writing test cases for django models half way through my current project after suffering the pain of spending uncountable minutes on debugging i have decided to adopt tdd to start i am planning to write a set of unit tests for each existing models but for models that only have attributes defined ie no additional methodsproperties i am not sure what i need to test nor how class productmodelsmodel name modelscharfieldmax length50 description modelstextfielddefault blanktrue retails modelsmanytomanyfieldretail verbose nameretail stores that carry the product manufacturer modelsforeignkeymanufacturer related nameproducts date created modelsdatetimefieldauto now addtrue date modified modelsdatetimefieldauto nowtrueusing product as an example what are the things about it that unit tests should cover and how should foreignkey and manytomanyfield be covered,['python'] +258837,no peer certificate error in android 23 but not in 4 getting the javaxnetsslsslpeerunverifiedexception no peer certificate error in an emulator running android 23 but not in 4 in 4 it works perfectly i am trying to connect to a live server via https it uses a valid thawte certificate works fine in all browsers and android 3 and 4if anyone has code help please and thanks also if anyone has any suggestions on a secure workaround i would appreciate it i am still learning and i have been on this problem for a week it has to end so i can continue working and learning urghhere is httpclient code courtesy antoine hauck import javaioinputstream import javasecuritykeystore import javasecuritycertcertificateexception import javaxnetsslsslcontext import javaxnetssltrustmanager import javaxnetsslx509trustmanager import javaxsecuritycertx509certificate import orgapachehttpconnclientconnectionmanager import orgapachehttpconnschemeplainsocketfactory import orgapachehttpconnschemescheme import orgapachehttpconnschemeschemeregistry import orgapachehttpconnsslsslsocketfactory import orgapachehttpimplclientdefaulthttpclient import orgapachehttpimplconnsingleclientconnmanager import androidcontentcontext public class myhttpclient extends defaulthttpclient final context context public myhttpclientcontext context thiscontext context override protected clientconnectionmanager createclientconnectionmanager schemeregistry registry new schemeregistry registryregisternew schemehttp plainsocketfactorygetsocketfactory 80 register for port 443 our sslsocketfactory with our keystore to the connectionmanager registryregisternew schemehttps newsslsocketfactory 443 return new singleclientconnmanagergetparams registry private sslsocketfactory newsslsocketfactory try get an instance of the bouncy castle keystore format keystore trusted keystoregetinstancebks get the raw resource which contains the keystore with your trusted certificates root and any intermediate certs inputstream in contextgetresourcesopenrawresourcerrawmy cert try initialize the keystore with the provided trusted certificates also provide the password of the keystore trustedloadin my passtochararray finally inclose pass the keystore to the sslsocketfactory the factory is responsible for the verification of the server certificate sslsocketfactory sf new sslsocketfactorytrusted hostname verification from certificate sfsethostnameverifiersslsocketfactorystrict hostname verifier return sf catch exception e throw new assertionerrore and here is the code that instantiates itdefaulthttpclient client new myhttpclientgetapplicationcontext httppost post new httppostserver login url list namevaluepair parameters new arraylist namevaluepair parametersaddnew basicnamevaluepairusername user parametersaddnew basicnamevaluepairpassword pass try postsetentitynew urlencodedformentityparameters httputf 8 catch unsupportedencodingexception e2 todo autogenerated catch block logddebug tag in unsupportedencodingexception e2getmessage e2printstacktrace execute the get call and obtain the response httpresponse getresponse null try getresponse clientexecutepost catch clientprotocolexception e todo autogenerated catch block toastmaketextgetbasecontextmessagetoastlength longshow logddebug tag in clientprotocolexception egetmessage catch ioexception e todo autogenerated catch block toastmaketextgetbasecontextmessagetoastlength longshow logddebug tag in clientexecute ioexception egetmessage eprintstacktrace the error is caught in the ioexception block here is the stackjavaxnetsslsslpeerunverifiedexception no peer certificateorgapacheharmonyxnetproviderjssesslsessionimplgetpeercertificateslsessionimpljava258orgapachehttpconnsslabstractverifierverifyabstractverifierjava93orgapachehttpconnsslsslsocketfactorycreatesocketsslsocketfactoryjava381orgapachehttpimplconndefaultclientconnectionoperatoropenconnectiondefaultclientconnectionoperatorjava164orgapachehttpimplconnabstractpoolentryopenabstractpoolentryjava164orgapachehttpimplconnabstractpooledconnadapteropenabstractpooledconnadapterjava119orgapachehttpimplclientdefaultrequestdirectorexecutedefaultrequestdirectorjava359orgapachehttpimplclientabstracthttpclientexecuteabstracthttpclientjava5orgapachehttpimplclientabstracthttpclientexecuteabstracthttpclientjava487orgapachehttpimplclientabstracthttpclientexecuteabstracthttpclientjava465orgffbtoolssplashactivitylogintaskmakeconnectionsplashactivityjava506orgffbtoolssplashactivitylogintaskdologinsplashactivityjava451orgffbtoolssplashactivitylogintaskdoinbackgroundsplashactivityjava439orgffbtoolssplashactivitylogintaskdoinbackgroundsplashactivityjava1androidosasynctask2callasynctaskjava185javautilconcurrentfuturetasksyncinnerrunfuturetaskjava306javautilconcurrentfuturetaskrunfuturetaskjava138javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava1088javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava581javalangthreadrunthreadjava1019here is the chain order from openssl commandthe chain looks good i think icusothawte incoudomain validated sslcnthawte dv ssl ca 1 scusothawte incoudomain validated sslcnthawte dv ssl ca icusothawte incoucertification services divisionouc 2006 thawte inc for authorized use onlycnthawte primary root ca 2 scusothawte incoucertification services divisionouc 2006 thawte inc for authorized use onlycnthawte primary root ca iczastwestern capelcape townothawte consulting ccoucertification services divisioncnthawte premium server caemailaddress,['android'] +258851,automatic reference counting issue assigning retained object to unsafe unretained variable object will be released after assignment i am getting this warningautomatic reference counting issue assigning retained object to unsafe unretained variable object will be released after assignmenthere is the codehinterface myobject nsobjectproperty assign id progressenergyendmimplementation myobjectsynthesize progressenergyidinit if self super init progressenergy progress alloc init warning appear on this line return selfendi have already triedproperty assign progress progressenergybut no luckcan you please help me figure out what is wrong,['objective-c'] +258855,how can i iterate over manytomanyfield a simple question and yet i cannot find an answer for iti have a model with a manytomany fieldclass stuffmodelsmodel things modelsmanytomanyfieldthingthen in a different function i want to do thismystuff stuffobjectsgetid1for t in mystuffthingsall but that is giving metypeerror instancemethod object is not iterablehow can i iterate over a manytomanyfield,['python'] +258859,ocunit tests to existing ios project ld file not found i have been following this blog post adding unit tests to existing projecti am getting this error however ld file not found buildproductsdebugiphoneosmyappappmyapp command developerplatformsiphonesimulatorplatformdeveloperusrbinclang failed with exit code 1i have my test target propertiesbundle loader built products dirmyappappmyapptest host bundle loaderwhich both equate to builddebugiphoneosmyappappmyappmy wild guess is that those variables are not pointing to the same location as the compiler builddebugiphoneos vs buildproductsdebugiphoneosi could be totally wrong on that guess but either way does anyone know whats causing this error or how i would fix those environment variablesthanks for any helpsam,"['objective-c', 'ios']" +258863,how can i include a button in a toast notification first of all i know this has been asked before android button in custom toastthis is nearly an exact duplicate but i think that it warrants a new question based on the fact that it is been used in apps namely gmail for ics it appears when you delete a messagethe linked question says that it is not possible to include a button in a toast because toasts cannot be focused is this wrong outdated or did gmail find a way around it,['android'] +258871,how to get time in milliseconds since the unix epoch in javascript possible duplicatehow do you get a timestamp in javascriptcalculating milliseconds from epoch how can i get the current epoch time in javascript basically the number of milliseconds since midnight 19700101,['javascript'] +258884,celery call function on task done i am using celery with django and rabbitmq to create a message queue i also have a worker which is originating from a different machine in a django view i am starting a process like thisdef processtaskrequest name args ls l mytaskdelayargs return httpresponsetask set to executemy task is configured like thisclass mytasktask def runself args p subprocesspopenargs stdoutsubprocesspipe stderrsubprocesspipe out err pcommunicate return outmy question now is how can a broker my django project now receive the output from the ls l command that the worker executed on his computer i guess the best thing would be for worker to call a function in broker whenever it is ready to send the output from the executed command i would like to receive the output from worker asynchronously then update the webpage with the output but that is for another time for now i would only like to receive the output from worker updateright now i have added a http get request that is triggered at the end of task notifying the web application that the task is done i am also sending the task id in the http get the http get method calls django view which creates asyncresult and gets the result but the problem is that when calling resultget i get the following errorusrlib64python26sitepackagesdjango celery251py26eggdjcelerymanagerspy178 txisolationwarning polling results with transaction isolation level repeatableread within the same transaction may give outdated results be sure to commit the transaction for each poll iteration polling results with transaction isolation levelany ideas why i am not using database because i am using rabbitmq with amqpupdatei would very much like to use third option which seems like the best option for small and big return values my whole task looks like thisclass mytasktask def call self args kwargs return selfrunargs kwargs def after returnself status retval task id args kwargs einfo if selfwebhost is not none conn httplibhttpconnectionselfwebhost selfwebport connrequesthead vulntaskoutputtask id def runself args webhostnone webportnone selfwebhost webhost selfwebport webport r this is a basic result string used for code clarity return rso i have overridden the after return function which should also release the lock on my task since the tasks run function already returned a value in the head request i am basically calling a django function which calls asyncresult on task id which should provide with the result of the task i have used arbitrary result for testing purposes in my case since it is only for testingi would like to know why the above code does not work i can use on success but i do not think it will make a difference or will it,['python'] +258945,regular expression to select all whitespace that is not in quotes i am not very good at regex can someone give me a regex to use in java that will select all whitespace that is not between two quotes i am trying to remove all such whitespace from a string so any solution to do so will workfor examplethis is a test sentence for the regexshould becomethisisatestsentence for the regex,['java'] +258966,skip first couple of lines while reading lines in python file i want to skip the first 17 lines while reading a text filelet us say the file looks like0good stuffi just want the good stuff what i am doing is a lot more complicated but this is the part i am having trouble with,['python'] +258998,python update xmlfile using elementtree while conserving layout as much as possible i have a document which uses an xml namespace for which i want to increase grouphousedogs by one the file is called housesxmlxml version10group xmlns house id2821id dogs2dogs housegroupmy current result using the code below is the created file is called houses2xmlns0group xmlnsns0 ns0house ns0id2821ns0id ns0dogs3ns0dogs ns0housens0groupi would like to fix two things if it is possible using elementtree if it isna t ia d be greatful for a suggestion as to what i should use insteadi want to keep the xml version10 linei do not want to prefix all tags ia d like to keep it as isin conclusion i dona t want to mess with the document more than i absolutely have tomy current code which works except for the above mentioned flaws generating the above result followsi have made a utility function which loads an xml file using elementtree and returns the elementtree and the namespace as i do not want to hard code the namespace and am willing to take the risk it impliesdef elementtreerootandnamespacexml file from xmletree import elementtree import re element tree elementtreeparsexml file search for a namespace on the root tag namespace search researchs element treegetroottag keep the namespace empty if none exists if a namespace exists set namespace to namespacename namespace if namespace search namespace namespace searchgroup1 return element tree namespacethis is my code to update the number of dogs and save it to the new file houses2xmlelementtree namespace elementtreerootandnamespacehousesxml insert the namespace before each tag when when finding current number of dogs as elementtree requires the namespace to be prefixed within when a namespace is used in the documentdogs elementtreefindnshousensdogsformatns namespace increase the number of dogs by onedogstext strintdogstext 1 write the result to the new file houses2xmlelementtreewritehouses2xml,['python'] +259008,separating class code into a header and cpp file i am confused on how to separate implementation and declarations code of a simple class into a new header and cpp file for example how would i separate the code for the following classclass a2dd private int gx int gy public a2ddint xint y gx x gy y int getsum return gx gy,['c++'] +259023,how can i simplify code generation at runtime i am working on a piece of software which generates assembler code at runtime for instanceheres a very simple function which generates assembler code for calling the getcurrentprocess function for the win64 abivoid gengetcurrentprocess char codeptr farproc addressforgetcurrentprocessfunction ifdef win64 mov rax addressforgetcurrentprocessfunction codeptr 0x48 codeptr 0xb8 farproc codeptr addressforgetcurrentprocessfunction call rax codeptr 0xff codeptr 0xd0else mov eax addressforgetcurrentprocessfunction codeptr 0xb8 farproc codeptr addressforgetcurrentprocessfunction call eax codeptr 0xff codeptr 0xd0endifusually i would use inline assembler but alas this does not seem to be possible with the 64bit msvc compilers anymore while i am at it this code should work with msvc6 up to msvc10 and also mingw there are many more functions like gengetcurrentprocess they all emit assembler code and many of them get function pointers to be called passed as argumentsthe annoying thing about this is that modifying this code is errorprone and weve got to take care of abispecific things manually for instance reserving 32 bytes stack space before calling functions for register spillingso my question is can i simplify this code for generating assembler code at runtime my hope was that i could somehow write the assembler code directly possibly in an external file which is then assembled using mlml64 but it is not clear to me how this would work if some of the bytes in the assembled code are only known at runtime the addressforgetcurrentprocessfunction value in the above example for instance maybe it is possible to assemble some code but assign labels to certain locations in the code so that i can easily modify the code at runtime and then copy it into my buffer,['c++'] +259059,converting from byte to int in java i have generated a secure random number and put its value into a byte here is my codesecurerandom rangen new securerandombyte rno new byte4 rangennextbytesrnoint i rno0intvaluebut i am getting an error byte cannot be dereferenced,['java'] +259076,unable to call thispose this one has confused me a little attempting to thispose of an xmlreaderxmlreader reader xmlreadercreatefilepathreaderthispose provides the following errorsystemxmlxmlreaderthisposebool is inaccessible due to its protection levelhowever the following is fineusingxmlreader reader xmlreadercreatefilepathwhen i look at the definition in reflector i cannot understand why i cannot call thisposeimplementation of thisposecan anyone point out what i am missing,['.net'] +259103,what is the purpose of intentsender i want to known what is the purpose of the intentsender class for our application how do we use it in our applicationare there any good examples apart from the android intent based apis part seven a intentsenders and pendingintents,['android'] +259106,rails 3 remote form how do i specify the content type i am using rails 32 i have a form and i want it to be posted via ajax and have the controller return json i am using a form for helper like so form forobject remote true format json do fmy objects controller create method looks like this def create respond to do format if objectsave formathtml redirect to object formatjson render json object status created location object else formathtml render action new formatjson render json objecterrors status unprocessable entity end end endthe form is submitting ajaxly as expected but the controller is returning html not jsoninspecting the request with firebug and sure enough the contenttype http header on the ajax request is being set to applicationhtmlthe documentation around this is pretty sparse format json seems to just append json to the forms action not actually modify any http headersi have also tried content type json to no effecti cannot simply hard code the controller to return json as there are other places where i do want it to return htmlso does anyone know how to tell the controller to render json when using form forthanks for any help,['ruby-on-rails'] +259158,backbonejs fetch not actually setting attributes i have a basic backbone model its urlroot attribute is set and the corresponding target on the server side returns a correct json output both json string and applicationjson headeri call a fetch like thisvar athlete new athlete id 1 athletefetchat this point if i add aconsolelogathletei can see the model and inspecting it in firebug i can open the attributes object and see all the values returned from the serverbut if i do aconsolelogathletegetnamei get undefined the name appears under the attributes in the dom inspection i mentioned abovealso doing aconsolelogathleteattributesreturns an object containing only id 1 which is the argument i passed while creating the modelif i create the model like thisvar athlete new athletejson string copypasted from the server responsethen everything works fine the get method returns whatever i ask and athleteattributes shows all the valueswhat am i doing wrong,['javascript'] +259182,why is not this a pod type i ran the below with g stdc0x pod testcpp on g 462 mingw i get an error on a4 why is not a4 podinclude iostreaminclude newinclude cstringusing namespace stdstruct a int a b char cstruct a2 short buf1struct a3a struct a4a short buf1static assertstdis podavalue struct must be a pod typestatic assertstdis poda2value struct must be a pod typestatic assertstdis poda3value struct must be a pod typestatic assertstdis poda4value struct must be a pod typeint main,['c++'] +259186,why does crash my page thisclaimer do not try this at homewhy if i am using jquery does freeze the page,"['javascript', 'jquery']" +259192,reg free com interop with c possible is it possible to use registration free com with dotnet interop and c if so how does one add a reference to the com object in the c projecti have a reg free atl com server dll with an embedded manifest and two test clients one cpp the other c the cpp client correctly references the com object using an import statement and eitherpragma commentlinker manifestdependencytypewin32 nametestcomsvr2 version10or setting additional manifest dependencies to typewin32 nametestcomsvr1 version10 under linkermanifest file options after which the cpp client will run correctly just so long as the com component is in the same directorythe c client though refuses to play at allattempting to add a file reference to either the unregistered com component dll or unregistered tlb results in the errora reference to blah blah could not be added please make sure that the file is accessible and that it is a valid assembly or com componentregistering just the type library with regtlib testcomsvr and then creating either a file or com reference to that results in the c project failing to build witherror loading type librarydll exception from hresult 0x80029c4a type e cantloadlibraryregistering the com component and creating a reference normally in the c project setting the reference to isolated building the c project then unregistering the component and running the c project results in this exceptionretrieving the com class factory for component with clsid b1d0a80f00504856bacd87d664e58cbe failed due to the following error 80040154 class not registered exception from hresult 0x80040154 regdb e classnotregnote even if this worked it wouldnt be a useful case anyway since ultimately it still requires registration of the component i just tested it for thoroughneso far the only way i have been able to reference the com object from c at all is by registering the com object itself which of course utterly defeats the point since then it is not regfree at allanyone got any ideasthis is on winxp with vs2010 sp1,['c#'] +259212,python paths and import order ok so i really want to get this right because i keep running into it when generating some big py2apy2exe packages so i have my package that contains a lot of modulespackages that might also be in the users site packagesdefault location if a user has a python thistribution but i want my thistributed packages to take effect before them when running from my thistribution now from what i have read here pythonpath should be the 1st thing added to syspath after the current directory however from what i have tested on my machine that is not the case and all the folders defined in sitepackageseasyinstallpth take precedence over this so could someone please give me some more in depth explanation about this import orderhelp me find a way to set the environmental variables in such a way that the packages i thistribute take precedence over the default installed ones so far my attempt is for example on macos py2app in my entry point script osenvironpythonpath data path osenvironpythonpath osenvironpythonpath ospathjoindata path lib osenvironpythonpath osenvironpythonpath ospathjoin data path lib python27 sitepackages osenvironpythonpath osenvironpythonpath ospathjoin data path lib python27 sitepackageszipthis is basically the structure of the package generated by py2app then i just server subprocesspopenpython exe path m binrpserver cfgrpc server ip cfgrpc server port shellfalse stdinin file stdoutout file stderrerr filehere python exe path is the path to the python exe that is added by py2app to the package now this works fine on a machine that does not have a python installed however when python thistribution is already present their sitepackages take precedence,['python'] +259260,how can i stop a double click of the window title bar from maximizing a window of formborderstylefixedtoolwindow i am annoyed that the i am promised a fixed window that the user cannot resize but then of course they are allowed to double click the title bar to maximize this unresizable window how can i turn this off can i do it with winforms code or must i go down to win32thanks,['c#'] +259281,find closest longitude and latitude in array i have a longitude and latitude as a string in php like below496481103575312and i want to take that and look in an array of values to find the closest one the array looks likearray0arrayitem1otheritem1details556456454253231arrayitem1otheritem1details1006456454025323i want to return the array that has the closest long and lad in this case it would be the first one and yes i know 400 is not a a possible valueis there any quick and easy way to do this i tried array searching but that did not workdifference codefunction thistancelat1 lon1 lat2 lon2 unit theta lon1 lon2 thist sindeg2radlat1 sindeg2radlat2 cosdeg2radlat1 cosdeg2radlat2 cosdeg2radtheta thist acosthist thist rad2degthist miles thist 60 11515 unit strtoupperunit if unit k return miles 1609344 else if unit n return miles 08684 else return miles,['php'] +259297,how to query delayed job handler i am playing with delayed job and i need to delete all the job with a specified handler value i tried in this wayclass auction activerecordbase def clean jobs delayedjoballeach do job jobdelete if jobpayload objectauction id id end endendand it works but i have to go through the entire queuenot cool how can i work around thisthank you,['ruby-on-rails'] +259301,in c what does bool bool true mean in my hunt for some help to a problem i was having i came across this penabled penabled truewhat exactly does this mean ive never seen it before nb the preceeding line was var p thispagerepositorygetpageid,['c#'] +259320,xcode scribble guard edges and guard malloc can someone explain what do these options in xcode doenable scribbleenable guard edgesenable guard mallocwhat they are and what they do and how useful can they be for debuggingtestingthanks,"['iphone', 'ios']" +259330,should i use this within a class within a member function of a class in c does it make a difference if i use thisdatamember or just datamember what is considered better style is there any performance differencei am not talking about the case where a local variable has the same name as the data member in which case you must to my knowledge use this to thistinguish between them,['c++'] +259344,what is difference between sysexit0 and os exit0 please help me in clarifying the concept of these two python statements in terms of difference in functionalitysysexit0os exit0,['python'] +259379,view with low alpha subview with high alpha i have a uiview with an alpha of 5i have added a subview with an alpha of 1the subview seems to inherit the alpha value of the parent is there a way to make the subview more opaque than its parent viewcode looks like thiscgrect promptframe cgrectmake55 80 180 50uiview inputprompt uiview alloc initwithframe promptframeinputprompt setbackgroundcolor uicolor darkgraycolorinputprompt setalpha 5inputpromptlayercornerradius 8inputpromptlayermaskstobounds yescgrect filetextfieldframe cgrectmake10 15 150 25uitextfield fileprompt uitextfield alloc initwithframe filetextfieldframefileprompt setborderstyleuitextborderstyleroundedrectfileprompt setclearbuttonmodeuitextfieldviewmodewhileeditingfileprompt setbackgroundcolor uicolor whitecolorfileprompt setalpha 1the result looks like thisi would like to be able to see the button below the gray uiview but not below the white uitextfield how do i do this,"['objective-c', 'ios']" +259390,how can you sort an array without mutating the original array let us suppose i wanted a sort function that returns a sorted copy of the inputted array i naively tried thisfunction sortarr return arrsortand i tested it with this which shows that my sort method is mutating the arrayvar a 237537134sortaalerta alerts 1234577i also tried this approachfunction sortarr return arrayprototypesortarrbut it does not work at allis there a straightforward way around this prefereably a way that does not require handrolling my own sorting algorithm or copying every element of the array into a new one,['javascript'] +259412,creating a temporary table from a query using sqlalchemy orm i can create a temporary table this waysessionexecutecreate table temptable select existingtableid existingtablecolumn2 from existingtable where existingtableid10but the new table is unreadable because it says it has no primary key existingtableid is the primary key of exisitingtable so i expected it to get the same treatment in the temp table however i would rather find some orm way of doing this anyway giventemp table tabletemptable metadata columnid integer primary keytrue columncolumn2 integer useexistingtrue class temptableobject passmappertemptable temp tabletemp tablecreatebindsessionbind checkfirsttrueif sessionquerytemptabledelete make sure it is empty sessioncommithow can i populate temp table with some selected contents of existingtable without doing 10 sessionqueryaddtemptable commands or is there a way of creating the table from a query similar to the plain sql version above,"['python', 'sql']" +259423,compile and run a c program in emacs i can not find how to run a c program in the emacs terminal i can compile it with mx cc filenamec and it works fine what is the command to run the program mx what do i type,['c'] +259429,how to hide google maps api markers with jquery hello this might be really silly question but i am trying to make markers thisappear whenthey are clicked the marker is located properly on the map but when i click it it does notdo anything i was wondering why its not working thank you script typetextjavascript srcjqueryjsscript script typetextjavascript documentreadyfunction var myoptions center new googlemapslatlng401 882 zoom 13 maptypeid googlemapsmaptypeidroadmap var map new googlemapsmapdocumentgetelementbyidmap canvas myoptions var mylatlng new googlemapslatlng401 882 var temp marker new googlemapsmarker position mylatlng map map titlehello world consolelogtemp marker consolelogtemp marker temp markerclickfunctionthishide temp markerclickfunctionconsolelogclick is working thishide scriptheadbody div idmap canvas stylewidth100 height100divbody,['jquery'] +259463,getting systemnetmailmailmessage as a memorystream in net 45 beta so the below code used to work in net 4 to get a systemnetmailmailmessage object as a memorystream however with the release of net 45 beta a runtime exception occursassembly assembly typeofsmtpclientassemblytype mailwritertype assemblygettypesystemnetmailmailwriterusing memorystream stream new memorystream constructorinfo mailwritercontructor mailwritertypegetconstructorbindingflagsinstance bindingflagsnonpublic null new typeofstream null object mailwriter mailwritercontructorinvokenew object stream methodinfo sendmethod typeofmailmessagegetmethodsend bindingflagsinstance bindingflagsnonpublic sendmethodinvokemessage bindingflagsinstance bindingflagsnonpublic null new mailwriter true null runtime exception occurs on sendmethodinvoke,['c#'] +259479,protocol https not supported or thisabled in libcurl i am using authorizenet in my applicationits in oscommerce when the user making payment its returning empty response i debugged and find that it returning this errorprotocol https not supported or thisabled in libcurli am sending a prober url starts with https there is no space in that my application in shared hosting server my doubt is this is server side problem or programming problem,['php'] +259483,android use done button on keyboard to click button ok in my app i have a field for the user to input a number i have the field set to only accept numbers when the user clicks on the field it brings up the keyboard on the keyboard on ics there is a done button i would like for the done button on the keyboard to trigger the submit button i have in my application my code is as followspackage commichaelpeermanprobabilityimport androidappactivityimport androidaprogressdialogimport androidcontentdialoginterfaceimport androidcontentdialoginterfaceoncancellistenerimport androidosbundleimport androidoshandlerimport androidosmessageimport androidviewviewimport androidviewviewonclicklistenerimport androidwidgetbuttonimport androidwidgetedittextimport androidwidgettextviewimport javautilrandompublic class probabilityactivity extends activity implements onclicklistener private button submitprogressdialog dialogint incrementthread backgroundint heads 0int tails 0public void oncreatebundle parambundle superoncreateparambundle setcontentviewrlayoutmain submit button findviewbyidridsubmit submitsetonclicklistenerthispublic void onclickview view increment 1 dialog new progressdialogthis dialogsetcancelabletrue dialogsetmessageflipping coin dialogsetprogrestyleprogressdialogstyle horizontal dialogsetprogress0 edittext max edittext findviewbyidridnumber int maximum integerparseintmaxgettexttostring dialogsetmaxmaximum dialogshow dialogsetoncancellistenernew oncancellistener public void oncanceldialoginterface dialog backgroundinterrupt textview result textview findviewbyidridresult resultsettextheads heads ntails tails background new threadnew runnable public void run heads0 tails0 for int j 0 threadinterrupted j dialoggetmax j int i 1 new randomnextint2 if i 1 heads if i 2 tails progresshandlersendmessageprogresshandlerobtainmessage backgroundstarthandler progresshandler new handler public void handlemessagemessage msg dialogincrementprogressbyincrement if dialoggetprogress dialoggetmax dialogthismiss textview result textview findviewbyidridresult resultsettextheads heads ntails tails,['android'] +259486,guide to systemreactivejoins i am looking for an introduction some documentation of systemreactivejoins which includes the pattern plan queryablepattern and queryableplan classes google does not turn up anything systemreactivejoins msdn has nothing there are no samples here and the excellent resources from this question do not cover this namespacedoes anyone have some pointers,['c#'] +259505,how to convert int to const int to assign array size on stack i am trying to allocate a fixed size on stack to an integer arrayincludeiostreamusing namespace stdint main int n1 10 const int and const castconst intn1 const int and 10 cout nnendl int foon return 0however this gives an error on the last line where i am using n to define a fixederror c2057 expected constant expression however if i define n as const int and 10 the code compiles just fine how should i typecast n1 to trat it as a const inti tried const int and const castconst intn1 but that gives error edit i am using ms vc 2008 to compile this with g it compiles fine,['c++'] +259527,choose nondefault googlecalendar with googlejavaclientapi i want to get all the calendars which are in my googleaccount using the google java client apiin my application i want that a user can choose in wich calendar his events will be saved not only in the default but therefore i need their calendarids i do not want that the users have to search their calendar ids to write them by hand into the appwould it be possible to create a new calendar in his account to write all the events in this new onesorry for my bad english,"['java', 'android']" +259596,how to use unittests selfassertraises with exceptions in a generator object i got a generator object that i want to unittest it goes through a loop and when at the end of the loop a certain variable is still 0 i raise an exception i want to unittest this but i do not know how take this example generatorclass example def generatorexampleself count 0 for int in range1100 count 1 yield count if count 0 raise runtimeerror an example error that will always happenwhat i would like to do isclass testexampleunittesttestcase def test generatorexampleself selfassertraisesruntimeerror examplegeneratorexamplehowever a generator object is not calable and this gives typeerror generator object is not callableso how do you test if an exception is raised in a generator function,['python'] +259604,wcf the service certificate is not provided specify a service certificate in servicecredentials i am trying to create a wcf service that uses the membershipprovider for authentication because it is an internal service i am currently not interested in applying transport level security https and i want to for now do this without a certificate besides this will complicate rolling out the service and i wish to do this at a later point in time i have built a basic configuration even without configuring the membershipprovider but wcf keeps throwing me the following exceptionthe service certificate is not provided specify a service certificate in servicecredentialsheres my configurationsystemservicemodel bindings ws2007httpbinding binding nameservice1ws2007httpbindingconfig security modemessage transport clientcredentialtypenone message clientcredentialtypeusername security binding ws2007httpbinding bindings services service namewcfservice1service1 endpoint addresshttplocalhost9800service1svc bindingws2007httpbinding bindingconfigurationservice1ws2007httpbindingconfig contractwcfservice1iservice1 service services behaviors servicebehaviors behavior name servicemetadata httpgetenabledtrue httpsgetenabledfalse servicedebug includeexceptiondetailinfaultsfalse behavior servicebehaviors behaviors servicehostingenvironment multiplesitebindingsenabledfalse serviceactivations add relativeaddreservice1svc servicewcfservice1service1 serviceactivations servicehostingenvironmentsystemservicemodelstacktrace of the exceptioninvalidoperationexception the service certificate is not provided specify a service certificate in servicecredentials systemservicemodelsecurityservicecredentialssecuritytokenmanagercreateserverx509tokenprovider 12382737 systemservicemodelsecurityservicecredentialssecuritytokenmanagercreatelocalsecuritytokenproviderrecipientservicemodelsecuritytokenrequirement recipientrequirement 63 systemservicemodelsecurityservicecredentialssecuritytokenmanagercreatesecuritytokenprovidersecuritytokenrequirement requirement 48 systemservicemodelsecurityservicecredentialssecuritytokenmanagercreatetlsnegoserverx509tokenproviderrecipientservicemodelsecuritytokenrequirement recipientrequirement 191 systemservicemodelsecurityservicecredentialssecuritytokenmanagercreatetlsnegosecuritytokenauthenticatorrecipientservicemodelsecuritytokenrequirement recipientrequirement boolean requireclientcertificate securitytokenresolver sctresolver 683 systemservicemodelsecurityservicecredentialssecuritytokenmanagercreatesecuritytokenauthenticatorsecuritytokenrequirement tokenrequirement securitytokenresolver outofbandtokenresolver 12383208 systemservicemodelsecuritysessionrenewsecuritytokenmanagercreatesecuritytokenauthenticatorsecuritytokenrequirement tokenrequirement securitytokenresolver outofbandtokenresolver 81 systemservicemodelsecuritysymmetricsecurityprotocolfactoryonopentimespan timeout 181 systemservicemodelsecuritywrappersecuritycommunicationobjectonopentimespan timeout 21 systemservicemodelchannelscommunicationobjectopentimespan timeout 318 systemservicemodelsecuritysecuritylistenersettingslifetimemanageropentimespan timeout 94 systemservicemodelchannelssecuritychannellistener1onopentimespan timeout 240 systemservicemodelchannelscommunicationobjectopentimespan timeout 318 systemservicemodelthispatcherchannelthispatcheronopentimespan timeout 72invalidoperationexception the channelthispatcher at httplocalhost9800service1svc with contracts issueandrenewsession is unable to open its ichannellistener systemservicemodelthispatcherchannelthispatcheronopentimespan timeout 118 systemservicemodelchannelscommunicationobjectopentimespan timeout 318 systemservicemodelservicehostbaseonopentimespan timeout 1 systemservicemodelchannelscommunicationobjectopentimespan timeout 318 systemservicemodelsecuritysecuritysessionsecuritytokenauthenticatoronopentimespan timeout 131 systemservicemodelsecuritywrappersecuritycommunicationobjectonopentimespan timeout 21 systemservicemodelchannelscommunicationobjectopentimespan timeout 318 systemservicemodelsecuritycommunicationobjectsecuritytokenauthenticatoropentimespan timeout 20 systemservicemodelsecuritysecuritysessionserversettingsonopentimespan timeout 792 systemservicemodelsecuritywrappersecuritycommunicationobjectonopentimespan timeout 21 systemservicemodelchannelscommunicationobjectopentimespan timeout 318 systemservicemodelsecuritysecuritylistenersettingslifetimemanageropentimespan timeout 148 systemservicemodelchannelssecuritychannellistener1onopentimespan timeout 240 systemservicemodelchannelscommunicationobjectopentimespan timeout 318 systemservicemodelthispatcherchannelthispatcheronopentimespan timeout 72invalidoperationexception the channelthispatcher at httplocalhost9800service1svc with contracts iservice1 is unable to open its ichannellistener systemservicemodelthispatcherchannelthispatcheronopentimespan timeout 118 systemservicemodelchannelscommunicationobjectopentimespan timeout 318 systemservicemodelservicehostbaseonopentimespan timeout 1 systemservicemodelchannelscommunicationobjectopentimespan timeout 318 systemservicemodelhostingmanageractivateservicestring normalizedvirtualpath 206 systemservicemodelhostingmanagerensureserviceavailablestring normalizedvirtualpath 651serviceactivationexception the service service1svc cannot be activated due to an exception during compilation the exception message is the channelthispatcher at httplocalhost9800service1svc with contracts iservice1 is unable to open its ichannellistener systemruntimeasyncresultendiasyncresult result 688590 systemservicemodelactivationhostedhttprequestasyncresultendiasyncresult result 190 systemservicemodelactivationhostedhttprequestasyncresultexecutesynchronoushttpapplication context string routeservicevirtualpath boolean flowcontext boolean ensurewfservice 234 systemservicemodelactivationhttpmoduleprocessrequestobject sender eventargs e 359 systemwebsynceventexecutionstepsystemwebhttpapplicationiexecutionstepexecute 148 systemwebhttpapplicationexecutestepiexecutionstep step boolean completedsynchronously 75what is wrong with my configuration and how can i solve this,"['c#', '.net']" +259622,backbonejs route optional parameter is it possible to have optional parameters in a backbonejs routeeg thisroutes searchquery searchindexinstead ofroutes search searchindex searchquery searchindex,['javascript'] +259699,how to use matplotlib tight layout with figure i found tight layout function for pyplot and want to use it in my application i embed matplotlib plots into qt gui and use figure and not pyplot is there any way i can apply tight layout there would it also work if i have several axes in one figure,['python'] +259703,caching this in jquery is a best practice we all know it is good to cache calls to the dom so instead of calling someelement more times just save it to a var someelement and use thatbut is it the same when using this inside an event listener for exampleshould this be cachedthank you,['jquery'] +259741,sql query to show gaps between multiple date ranges im working on a ssrs sql project and trying to write a query to get the gaps between dates and i am completely lost with how to write thisbasically we have a number of devices which can be scheduled for use and i need a report to show when they are not in usei have a table with device id eventstart and eventend times i need to run a query to get the times between these events for each device but i am not really sure how to do thisfor exampledevice 1 event a runs from 01012012 0800 01012012 10device 1 event b runs from 01012012 1800 01012012 20 device 1 event c runs from 02012012 1800 02012012 20 device 2 event a runs from 01012012 0800 01012012 10device 2 event b runs from 01012012 1800 01012012 20my query should have as its result device 1 01012012 10 01012012 1800device 1 01012012 20 02012012 1800device 2 01012012 10 01012012 1800there will be around 4 5 devices on average in this table and maybe 200 300 eventsupdatesok i will update this to try give a bit more info since i dont seem to have explained this too well sorrywhat i am dealing with is a table which has details for events each event is a booking of a flight simulator we have a number of flight sims refered to as devices in the table and we are trying to generate a ssrs report which we can give to a customer to show the days times each sim is available so i am going to pass in a start end date parameter and select all availabilities between those dates the results should then thisplay as something likedevice available from available to 1 01012012 10 01012012 1800 1 01012012 20 02012012 1800 2 01012012 10 01012012 1800also events can sometimes overlap though this is very rare and due to bad data it doesnt matter about an event on one device overlapping an event on a different device as i need to know availability for each device seperately,['sql'] +259742,add extra row to a uitableview managed by nsfetchedresultscontroller i am using a uitableviewcontroller for a table in my app and i have added an nsfetchedresultscontroller to provide the data to show in the table setting self as it is delegatehowever i would like to add a unique cell as the last cell of the table unrelated to the items produced by the nsfetchedresultscontrollers predicate i want this cell to always be at the bottom of the tablei have tried simply added 1 to these methods in the table view data source nsuintegernumberofsectionsintableviewuitableview sender return selffetchedresultscontroller sections count 1 nsuintegertableviewuitableview sender numberofrowsinsectionnsuintegersection return selffetchedresultscontroller sections objectatindexsection numberofobjects 1and then catching the case where this extra row is being generated like so the table only has 1 section uitableviewcell tableviewuitableview sender cellforrowatindexpathnsindexpath indexpath if indexpathrow selffetchedresultscontrollerfetchedobjects count generate the last cell in table else generate the rest of the cells like normal return nil to keep the compiler happythis checks to see if the index is the last cell and deals with it appropriatelyhowever i am still getting the following error at runtime terminating app due to uncaught exception nsrangeexception reason nsarraym objectatindex index 1 beyond bounds 0 0any idea whats causing this or is there a better way of adding an extra row to a table view controlled by an nsfetchedresultscontroller,['ios'] +259770,submit trial version of wp7 application i have written a wp7 app which includes source code for both a trial and full version using for exampleif appistrial show trial mode else show full modethis means that the trial version and full version are in the same xap file when i submit the app to the market do i submit each version separately or do i submit once for both versions,['c#'] +259777,marking rails migrations as migrated i have ended up with 9 migrations effectively duplicated i think this is because i installedupdated gems andor pulled in their migrations on both my dev and production machines but am not entirely sure at this stagei moved out one set of the duplicated 9 from the rails directories on the production server but now that i want to dbmigrate on production in order to run another migration i am getting bundle exec rake dbmigrate rails envproductiondeprecation warning nested i18n namespace lookup under activerecordattributescheckout is no longer supported createpages migrating create tablepagesrake abortedan error has occurred all later migrations canceledmysql2error table pages already exists create table pages id int11 default null auto increment primary key title varchar255 body text slug varchar255 created at datetime updated at datetime engineinnodbthis is because the migrations have effectively already been runi would rather avoid doing dbmigratedown and dbmigrateup for each one i think this will mean data in the production datbase is lost a couple of static pages in spree in this caseis there a way i can tell this installation of rails to forget all outstanding migrations effectively marking all outstanding migrations as done,"['ruby-on-rails', 'ruby']" +259784,using web references so been a few days now learning about web references within my projects i have now came across a strange problem using a simple console app i did thisnamespace webservices09004961 class program static void mainstring args convertconverttemperaturesoapclient client new convertconverttemperaturesoapclient while true consolewriteenter temperature in celsius double tempc doubleparseconsolereadline double tempf clientconverttemptempc converttemperatureunitdegreecelsius converttemperatureunitdegreefahrenheit consolewritelinethat is tempf degrees farenheit i have added in the service reference convert related to this linkhowever i get this erroran endpoint configuration section for contract convertconverttemperaturesoap could not be loaded because more than one endpoint configuration for that contract was found please indicate the preferred endpoint configuration section by nameis this because you can only have one service reference allocated at any one time the reason i ask is because my local service reference within the same project build still works fine yet this one doesnt it did when i first created itor is this a seperate problemalso what are the limitations on soap,"['c#', 'asp.net']" +259801,get a php object property that is a number i am trying to get a property from json data decoded into a php object it is just a youtube data api request that returns a video object that has a content object liks socontent stdclass object 5 fvideosappyoutube gdata 1 rtspv4cache7cyoutubecomciileny73wiagqn6psl0wagirxmydsanfeggugz2awrlb3mm0video3gp 6 rtspv6cache3cyoutubecomciileny73wiagqn6psl0wagirxmyesarfeggugz2awrlb3mm0video3gp doingobjectcontent5throws unexpected t dnumber which makes perfect sense but how do i get the value of a property that is a numberi am sure i should know this thanks in advance,['php'] +259850,how to unpair or delete paired bluetooth device programmatically on android the project is to use my android phone to connect with my arduino devices but how can i unpair the paired ones i see it seems the paired list is stored where bluetoothadapter could retrieve anytimeps1st i know long press paired device will unpair itbut the question here is how can i make this happen programmatically2nd i have checked bluetoothdevice and bluetoothadapter class there is no function to implement thisthanks,['android'] +259873,how to make a qtip tooltip move with cursor i am using the js library qtip tooltip i want to make the qtip tooltip move with my cursor as i hover over the hover row in a table i know how to make my own tooltip move with my cursor but am struggling with qtip please explain the code it you answer thanksmy htmltable div idhoverdivdiv tr classhover hovertextsome text tdtotal creditstd td total credit td trtablei can create a normal tooltipwithout qtip js lib to follow my cursor using the following jquery codedocumentreadyfunction hovermousemovefunctione var hovertext thisattrhovertext hoverdivtexthovertextshow hoverdivcsstop eclienty10cssleft eclientx10mouseoutfunction hoverdivhideand the code to thisplay a static qtip tooltipdocumentreadyfunction hovereachfunction thisqtip content thisattrhovertext this is what i have tried so fardocumentreadyfunction hovermousemovefunctione thisqtip content thisattrhovertext csstop eclienty10cssleft eclientx10,['jquery'] +259888,glassfish 3 how do you change the default logging format the question originated from here without an answerthe default glassfish 3 logging format is very annoying much too long20120302t0922031650100severeglassfish312javaxenterprisesystemstdcomsunenterpriseserverlogging threadid113 threadnameawteventqueue0 message this is just a horrible default imo the docs just explain all the fields but not how to change the format 01html8212416ablukhtmlnote that i deploy slf4j along with my webapp which should pick up the format as wellhow do you change the logging formatfyithe links here are outdated install log formater in glassfishthe question here has not been answered how to configure glassfish logging to show milliseconds in timestampsthe posting here resulted in nothing it looks like glassfish logging configuration is an issue of its own can anybody help,['java'] +259901,where to store db passwords when using windows net or aspnet applications i have a scenario that has been troubling me for years if you have to connect to a database or other service like a web service using a username and password where would be the safest place to store this information if you are connecting through a net assembly i understand that you would have to encrypt the password but then you run into a kind of chickenegg problem fine you can encrypt it but then where do you put the keyin net you cannot hardcode the password because you can decompile net codei looked at using assembly based rights with isolated storage but ms recommends against storing unencrypted secret items there because priveledged users can gain access so again we are moving the problem from point a to point b so for examplem a domain admin with no need to know about the information in a database would be able to get access because of the ability to be an admin on any workstation on the domainyou can encrypt appconfig and webconfig but i believe priveledges users can access the keys i think you run into the same problem with dpapii had considered storing the passwords encrypted in a remoted database and getting them through os authentication but our department prohibits the storage of passwords on database servers i am pretty sure i am stuck and wanted confirmation,"['c#', 'asp.net']" +259921,uiimageview isresizable unrecognized selector sent to instance sigabrt i have got this code trying to run a simple set of images in a cycle all i have in the app is one uiimageview declared in my view controllers h fileproperty strong nonatomic iboutlet uiimageview imagethisplayand the following in my m files viewdidload methodnsmutablearray imageview nsmutablearray alloc initimageview addobjectuiimageview alloc initwithimageuiimage imagenamedeyeanim1pngimageview addobjectuiimageview alloc initwithimageuiimage imagenamedeyeanim2pngimageview addobjectuiimageview alloc initwithimageuiimage imagenamedeyeanim3pngimageview addobjectuiimageview alloc initwithimageuiimage imagenamedeyeanim4pngimageview addobjectuiimageview alloc initwithimageuiimage imagenamedeyeanim5pngimageview addobjectuiimageview alloc initwithimageuiimage imagenamedeyeanim6pngimageview addobjectuiimageview alloc initwithimageuiimage imagenamedeyeanim7pngimagethisplayanimationimages imageviewimagethisplayanimationduration 025imagethisplayanimationrepeatcount 50imagethisplay startanimatingthe code seems to be crashing on the imagethisplayanimationimages line as if i create the uiimageview create its getter and setter and build it is fine until i uncomment that line if i do uncomment it it keeps giving me the error until i delete the uiimageview and create a new onenot too sure whats happening any help appreciated,['ios'] +259948,how do you set the spinner text color i have been unable to set the color on the spinner widget how is this styled,['android'] +259965,default button in jframe is not firing when the enter key is being pressed i have a jframe with three jbuttons on it i have set txtsearch a jtextfield component to have the focus when jframe loads one of the buttons is set as the default button this is my codeprivate void formwindowopenedjavaawteventwindowevent evt btnrefreshsetmnemonickeyeventvk r even if this line is not commented but still the event wouldnt fire thisgetrootpanesetdefaultbuttonbtnrefreshwhen it loads the button is just selected but it did nothing when the enter key was being pressed how do i correctly implement itbtnrefreshaddactionlistenernew javaawteventactionlistener public void actionperformedjavaawteventactionevent evt btnrefreshactionperformedevt private void btnrefreshactionperformedjavaawteventactionevent evt joptionpaneshowmessagedialogthis pressed other codes here replace by joptionpane,['java'] +259990,compiling against 51 sdk forces new uipopovercontroller slide in presentation of popovers how to thisable compiling my ipad app against the 51 sdk release version causes uipopovercontroller to show itself using the new slide in from the left presentation this completely breaks my popover presentation which relied on having a black style header and a certain height i have tried setting presentswithgesture to no but that only seems to thisable the swipe gesture and does not stop the presentation stylethis same app without being recompiled but running on ios 51 uses the old popover presentation style so i know ios 51 still supports the backwardscompatible method how can i choose to activate the old presentation of the popoverthis is really critical to my app unfortunatelyfailing that is there any way to get the black style header on the new popoversalthough i have a uisplitviewcontroller in my app it is not responsible for showing the popover instead i am using this code selfpopovercontroller presentpopoverfromrectipadbuttonmenuframe inviewselfview permittedarrowdirectionsuipopoverarrowdirectionup animatedyesthis question is a crosspost from the apple developer forums here i am hoping somebody has the answerexpected presentation presentation after compiling under ios 51 sdk,['ios'] +260033,android empty linear layout contents i have a text view inside an linear layout now i want to delete this text view in java this text view is generated dynamically i have linear layouts id how to empty all contents inside this linear layout linearlayout androidlayout widthmatch parent androidlayout heightwrap content androidorientationvertical androidididmyidtextview textview textview linearlayout,['android'] +260039,skipping the first line when reading in a file in 193 i am using rubys file to open and read in a text file inside of a rake task is there a setting where i can specify that i want the first line of the file skipped heres my code so far desc import users task import users environment do fileopenuserstxt r reach do line id name age email linestripsplit you usernewid id name name age age email email usave end endi tried linelineno and also doing fileopenuserstxt r reach do line index and next if index 0 but have not had any luck,['ruby'] +260043,environmentgetcommandlineargs why is it a method why not a property i am trying to understand the design considerations of the team that created the method environmentgetcommandlineargsit could have been a static property very much like systemwebhttpcontextcurrent after all the returned value should not change once available so it is more like a property of the current running processi know that any property in net is a syntactic sugar to gettersetter methods but that is the exact reason for using a property rather than an explicit getter methodor maybe there is there something i am missing herewhat do you think,['.net'] +260081,ruby sort array of an array i am having a problem figuring out how i can sort an array of an array both arrays are straight forward and i am sure it is quite simple but i cannot seem to figure it outheres the arrayhappy 1 sad 2 mad 1 bad 3 glad 12i want to sort it by the integer value of the inner array which is a value of how many times the word has occurred biggest number first,"['ruby-on-rails', 'ruby']" +260082,can anyone explain this c reference usage possible duplicateglobal const string smells bad to me is it truly safe i have stumbled across the following code and wondered of its meritsstdstring const thestring xyz it is the fact that it is constructing the object and referring to it by a reference i am used to seeing stdstring const thestring xyz and was wondering what the difference was i am reasonably happy that the object wouldnt be destructed early as the object lives on the stack along with the reference,['c++'] +260086,why does xsdexe generate string property for xsinteger when i generate a c class from a xsd schema with xsdexe i find this behaivor a bit wierdmy elementxselement nameinvoiceno typexsintegeris generated tosystemxmlserializationxmlelementattributedatatypeinteger order5public string invoiceno why is that property not generated as an int instead of string,"['c#', '.net']" +260095,select max timestamp with jpa2 criteria api so my entity hascolumnnamets nullablefalseprivate javasqltimestamp timestamp my generated metamodel haspublic static volatile singularattributemyentitytimestamp timestampi want to select by the max timestamp valuerootmyentity root queryfrommyentityclassexpression maxexpression cbmaxrootgetmyentity timestampbut i am not allowed becausemaxexpressionn x create an aggregate expression applying the numerical max operation n extends javalangnumber expressionof course timestamp does not extend number how can i do a max on a timestamp column using the typesafe criteria api thanks,['java'] +260116,java to excel 2010 first of all hello to everybodyi have a piece of code which is creating an excel file by using an open source library named openxls606my pc has windows xp professional and office 2003however i have notice that since i have migrated to windows 7 and office 2010 i am not able to open the generated excel file anymorei went to the openxls website and indeed is specified that compatible with excel 972003 xls file formats so here is my question is anybody aware of a library that is able to generate excel files compatible with office 2010i had a quick check on excelapi and poi but it is mentioned that they deal with excel up to the office 2003 versionat least this was my understandingthank you very much in advance and kind regardsmarius,['java'] +260121,return a default record from a sql query i have a sql query that i run against a sql server database egselect from mytable where id 2this may return a number of records or may return none if it returns none i would like to alter my sql query to return a default record is this possible and if so how if records are returned the default record should not be returned i cannot update the data so will need to alter the sql query for this,['sql'] +260126,difference between extracting and packaging libraries into a jar file i would like to know the difference between extracting and packaging libraries into a jar file from eclipse with the runnable jar file creationif my program runnable jar uses other classes which require these external librariesjars what should i pick,['java'] +260138,eclipse upgrade not working my eclipse out of the blue stopped building my android so i removed the old version and have installed indigo when i try to import an android project in i get this errorerrors occurred during the builderrors running builder android resource manager on project accuwx honeycombjavalangnullpointerexceptionerrors running builder android pre compiler on project accuwx honeycombjavalangnullpointerexceptionerrors running builder java builder on project accuwx honeycombjavalangnullpointerexceptionplease help,['android'] +260147,python regular expression with codons struggling with re to search for sequences taa triplets of 3 characters taa againi tried the followingrefindalltaataaseq which of course does not give triplets but does give me sequencesrefindalltatgc3taa seq however gives me a list as output agg tct gtg tgg tga tatany ideas as i of course can check the output from refindalltaataaseqif length 3 0 but how to do this with re,['python'] +260167,needs overload operator and null check ia m overloading the lessthanoperator in c and im wondering whether this needs to check for null below you can find an examplepublic static bool operator myclass x myclass y if x null y null return false if x null return true false if y null return false true return xvalue yvalueor is this correctpublic static bool operator myclass x myclass y return xvalue yvaluei didna t find any instruction on this but maybe i missed something,['c#'] +260181,how can i pause all jquery animations i am going to have cases where i need to pause all the animations on the page in order to do some user interaction and then resume all the animations as soon as the user has respondedfor example i might have an animation that is fading in over a 1s period and 400ms in i need to pause it it should stop at 40 opacity and stay there until i resume at which point it should pick up where it left off and spend another 600ms completing its fadein from 40 to 100there might be multiple animations on the page simultaneously and i want to pause them all additionally some animations might have further animations queued to continue after they complete and that all needs to work when i resume the current animation needs to finish and then the next one in the queue needs to start just as if nothing happenedjquery does not seem to have any builtin support for pausing animations the closest i can find is stop which will stop at the current spot in the animation but cannot resume later and it either moves on to the next animation in the queue immediately or clears the animation queue entirelyhow can i pause the animations in a way that will let me resume them later,['jquery'] +260185,resolving javaxnetsslsslhandshakeexception sunsecurityvalidatorvalidatorexception pkix path building failed error i am getting this errordetailed message sunsecurityvalidatorvalidatorexception pkix path building failed sunsecurityprovidercertpathsuncertpathbuilderexception unable to find valid certification path to requested targetcause javaxnetsslsslhandshakeexception sunsecurityvalidatorvalidatorexception pkix path building failed sunsecurityprovidercertpathsuncertpathbuilderexception unable to find valid certification path to requested targeti am using tomcat 6 as webserver i have two https webbapplication installed on different tomcat on differte port but on same machine say app1port 8443 and app2port 443 app1 connects to app2 when app1 connects to app2 i get above error i know this is very common error so came across many solutions on different forums and sites i have below entry in serverxml of both tomcat iekeystorefileckeystore keystorepasschangeitevery site says the same reason that certificate given by app2 is not in the trusted store of app1 jvm this seems to be true also when i tired to hit the sameurl in ie browser it workswith warming there is a problem with this web sites security certificate here i say continue to this website but when same urlis hit by java clientin my case so i get the above error so to put it in trustore i tried these tree options ieoption1systemsetpropertyjavaxnetssltruststore ckeystoresystemsetpropertyjavaxnetssltruststorepassword changeitoption2setting below in environment variablecatalina opts param namedjavaxnetssltruststoreckeystore djavaxnetssltruststorepasswordchangeit param valueoption3setting below in environment variablejava opts param namedjavaxnetssltruststoreckeystore djavaxnetssltruststorepasswordchangeit param valuebut nothing worked what at last worked is executing the java approach suggested in how to handle invalid ssl certificates with apache httpclient by pascal thivent ie executing the program installcert but this approach is fine for devbox setup but i can not use it at production environment i am wonderingwhy three approaches mentioned above did not work when i have mentioned same values in serverxml of app2 server and same values in truststore by settingsystemsetpropertyjavaxnetssltruststore ckeystore and systemsetpropertyjavaxnetssltruststorepassword changeitin app1 programfor more information this is how i am making the connectionurl url new urlurlstrurlconnection conn urlopenconnectionif conn instanceof httpsurlconnection httpsurlconnection conn1 httpsurlconnection urlopenconnection conn1sethostnameverifiernew hostnameverifier public boolean verifystring hostname sslsession session return true replyloadconn1getinputstream,['java'] +260188,mkmapview userlocation showing 00 in simulator i have a mapview outlet on my view mkmapviewdelegate with shows user location enabledin the viewdidload for that controller i havecllocation userloc mapviewuserlocationlocationcllocationcoordinate2d usercoordinate userloccoordinatensloguser latitude fusercoordinatelatitudensloguser longitude fusercoordinatelongitude mapviewdelegateselfthe simulator shows the correct user location on the map i am using custom location in the ios simulatorbut the nslog shows 0 and 0 for latitude and longitudeshould not i be able to get the custom longitude and latitude in the simulatorupdate with answerneeded to implement voidmapviewmkmapview mapview didupdateuserlocationmkuserlocation userlocation selfmapviewcentercoordinate userlocationlocationcoordinate,['ios'] +260190,javascript dom get node text without losing spacing info i am using javascript and want to traverse the html tree getting all the text as it appears to the user however i am losing spacing informationlet us say i have two docshtmlxpyy yyphtmlhtmlxpyynbspnbspnbspyyphtmlthe first one will appear with 1 space between the ys the second will have 3 spaces however if i traverse the tree and for each text node usetext nodenodevaluethen the text for both nodes will have 3 spaces i no longer know which one has the real nbsp spaces i can use nodeinnerhtml for the p elements which will show the nbsp but i do not think that i can use innerhtml to get just the x text without some kind of text subtraction i could just get innerhtml of the whole document and parse that however i also need to get the computed style of each element which i am going to get using windowgetcomputedstyletheelementgetpropertyvaluetextalignso i will be traversing each node also innerhtml shows the source as is while traversing the nodes fixes html errors adding end tags etc that is a good thing and something i would like to keep,['javascript'] +260193,how can i init a text field in a uialertview the updated uialertview now has a style which allows a text input field in uialertview iealertalertviewstyle uialertviewstyleplaintextinputthis works well but i wanted to init the input text with a defualt text like samplei see that folks in the past have used undocumented api like which works greatalert addtextfieldwithvaluesample text labeltext fieldbut since this is still not an official apple public api i cannot use itany other way to handle this i did try to init in willpresentalertview but text field seem to be readonlythanks,"['iphone', 'ios']" +260237,fiddler not capturing http requests from java application i am currently writing a java application that uses http post to upload a csv file and a few other parameters to a server the server keeps returning 500 errors to my application and i would like to view the http request in fiddler so i can see the post requestwhen i run fiddler it will not capture any http traffic from the java application i have written a get request that works so i know i can communicate with the server however no traffic is shown through fiddler,['java'] +260263,how to get backbone model attributes without get in backbone it seems that i have to get model attributes via modelgetatt namei would prever to get them the way i would get any public field within an object modelatt namecan anyone think of a way to get around thiseg in python world i would override getattr on the model something like thisdef getattrself att return selfgetattoh and i am using coffeescript,['javascript'] +260309,aspnet session variable i have a aspnet project with c code behind i have a static class called globalvariable where i store some information like the currently selected product for examplehowever i saw that when there are two users using the website if one changes the selected product if changes it for everybody the static variables seem to be commun to everybodyi would want to create from the c code some kind of session variable used only from the c code but not only from the page but from any class,"['c#', 'asp.net']" +260314,where is the samplezipfileprovider class at the bottom of the section in googles dev guide on expansion files there is the following textapezprovider most applications do not need to use this class this class defines a contentprovider that marshals the data from the zip files through a content provider uri in order to provide file access for certain android apis that expect uri access to media files the sample application available in the apk expansion package demonstrates a scenario in which this class is useful to specify a video with videoviewsetvideouri see the sample apps class samplezipfileprovider for an example of how to extend this class to use in your applicationthe sample application in question does not contain this class but it does contain a reference to a samplevideoplayeractivity file in the androidmanifestxml which is not present in the project eitherhas anyone tried to implement a concrete class based on the apezprovider and used it with videoviewsetvideouri i have implemented the classpublic class zipfilecontentprovider extends apezprovider override public string getauthority return commycompanymyappnameproviderzipfilecontentprovider but i do not know how to use it with the videoviewsetvideouri call can anyone help,['android'] +260351,convert float32 array to datetime64 in numpy 161 what is the proper way of converting integer dates to datetime64 in numpy i triedimport numpya numpyarray20090913 20101020 20110125numpydatetime64aastypes8but get an incorrect conversion how about reading them in correctly as numpydatetime64 objects using numpyloadtxt they are coming from a csv file,['python'] +260360,how to start anonymous thread class i have the following code snippetpublic class a public static void mainstring arg new thread public void run systemoutprintlnblah here how do i call the start method for the thread without creating an instance of the thread class,['java'] +260378,mediaplayer setdatasource better to use path or filedescriptor let us say i have a full path to a file which is the better approach to loading that file into a mediaplayer string filepath somepathsomefilemp3mediaplayersetdatasourcefilepathorstring filepath somepathsomefilemp3file file new filefilepathfileinputstream inputstream new fileinputstreamfilemediaplayersetdatasourceinputstreamgetfdinputstreamclosedoes it matter simply using the path seems easier but is there a reason to do the extra work to use a filedescriptor,['android'] +260388,should the call to the superclass method be the first statement the results of a speech recognition can be read in the onactivityresultint requestcode int resultcode intent data method as shown in this example this method overrides the same method in class activity why is the call to the superclass method not the first statementoverrideprotected void onactivityresultint requestcode int resultcode intent data if requestcode voice recognition request code resultcode result ok fill the list view with the strings the recognizer thought it could have heard superonactivityresultrequestcode resultcode data,['android'] +260395,why are all my bitmaps upsampled 200 i am having severe memory issues in my application 1 in order to investigate this i took heapdumps of my app at different states i saw that some bitmaps were taking huge amounts of memory i wrote a small tool 2 that decodes the byte arrays to windows bitmap files bmp so that i can see the bitmaps and compare them to the files i have in my resdrawable folderwhat i thiscovered is that all my files are upsampled twicei first checked with the biggest one had a byte array buffer of more than 9mb in the heap which was decoded to be a nice 1920x1280 picture while the original one was a 960x640 png filei tried with the second biggest over 3mb which once decoded showed a nice 754x1200 picture the original size was guess what a nice 377x600 jpg filewhat givesi have enabled hw acceleration in my android manifest file though i am not sure i really need it i am just using some basic views and activitiesi am running stock android 402 on a gsm galaxy nexus yakju i am receiving feedback from my testers that the issue is present on their 403 nexus s though i could not check their heap dumps yeti am trying to save memory here if android doubles everything no wonder the app crashes quickly because the heap usage gets too high around 64mb in my case i hope there is a reason and a way around itreferencesoutofmemoryerror when loading activitieshow to actually see a bitmap taken from an android heap dump,['android'] +260408,android unknownhostexception is there a way to set timeout when i connect to my webservice to retreive data the phone is sometimes getting thisconnected dns messed up etc then i get an unknownhostexception which is perfectly finewhat i want to do is to set a timeout when looking for the hostname here response httpclientexecutehttpgeti have already set httpconnectionparamssetconnectiontimeouthttpparameterstimeoutconnectionhttpconnectionparamssetsotimeouthttpparameters timeoutsocketbut they do not seem to apply for hostlookup is there any way to set the timeout at host lookupediti just found that the user cannot modify the timeout of nslookup in this post on the hcdev mailing listi will have to manually throw a timeout exception from a timer at that point,"['java', 'android']" +260420,cannot unmarshal a json array of objects using jersey client a oneelement json array that i am trying to unmarshal id42 statusactive namepurple monkey thishwasher the corresponding java class getters setters omitted for brevityxmlrootelementxmlaccessortypexmlaccesstypefieldpublic class badge xmlelementnameid private string id xmlelementnamestatus private status status xmlelementnamename private string name public static enum status active notactive the jersey client code which makes an http request and is supposed to unmarshal the above json into a oneelement listfooclient client clientcreatewebresource apiroot clientresourcehttplocalhost90apilistbadge badges apirootpathbadgesgetnew generictypelistbadgethe last line specifically the webresourceget call throws the following exceptionjavaxxmlbindunmarshalexception unexpected element uri localstatus expected elements are badge at comsunxmlbindv2runtimeunmarshallerunmarshallingcontexthandleeventunmarshallingcontextjava662 at comsunxmlbindv2runtimeunmarshallerloaderreporterrorloaderjava258 at comsunxmlbindv2runtimeunmarshallerloaderreporterrorloaderjava253 at comsunxmlbindv2runtimeunmarshallerloaderreportunexpectedchildelementloaderjava120 at comsunxmlbindv2runtimeunmarshallerunmarshallingcontextdefaultrootloaderchildelementunmarshallingcontextjava1063 at comsunxmlbindv2runtimeunmarshallerunmarshallingcontext startelementunmarshallingcontextjava498 at comsunxmlbindv2runtimeunmarshallerunmarshallingcontextstartelementunmarshallingcontextjava480 at comsunxmlbindv2runtimeunmarshallerinterningxmlvisitorstartelementinterningxmlvisitorjava75 at comsunxmlbindv2runtimeunmarshallerstaxstreamconnectorhandlestartelementstaxstreamconnectorjava247 at comsunxmlbindv2runtimeunmarshallerstaxstreamconnectorbridgestaxstreamconnectorjava181 at comsunxmlbindv2runtimeunmarshallerunmarshallerimplunmarshal0unmarshallerimpljava369 at comsunxmlbindv2runtimeunmarshallerunmarshallerimplunmarshalunmarshallerimpljava341 at comsunjerseycoreproviderjaxbabstractlistelementproviderreadfromabstractlistelementproviderjava232 at comsunjerseyapiclientclientresponsegetentityclientresponsejava552 at comsunjerseyapiclientclientresponsegetentityclientresponsejava522 at comsunjerseyapiclientwebresourcehandlewebresourcejava617 at comsunjerseyapiclientwebresourcegetwebresourcejava191 at comredactedbadgeclientbadgerimplfindallbadgesbadgerimpljava105 at comredactedwebappadminbadgeactionunspecifiedbadgeactionjava40 at orgapachestrutsactionsthispatchactionthispatchmethodthispatchactionjava245 at orgapachestrutsactionsthispatchactionexecutethispatchactionjava170 at orgapachestrutschaincommandsservletexecuteactionexecuteexecuteactionjava58 at orgapachestrutschaincommandsabstractexecuteactionexecuteabstractexecuteactionjava67 at orgapachestrutschaincommandsactioncommandbaseexecuteactioncommandbasejava51 at orgapachecommonschainimplchainbaseexecutechainbasejava190 at orgapachecommonschaingenericlookupcommandexecutelookupcommandjava304 at orgapachecommonschainimplchainbaseexecutechainbasejava190 at orgapachestrutschaincomposablerequestprocessorprocesscomposablerequestprocessorjava283 at orgapachestrutsactionactionservletprocessactionservletjava1913 at orgapachestrutsactionactionservletdogetactionservletjava449 at javaxservlethttphttpservletservicehttpservletjava617 at javaxservlethttphttpservletservicehttpservletjava717 at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava290 at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava206 at comopensymphonymodulesitemeshfilterpagefilterparsepagepagefilterjava119 at comopensymphonymodulesitemeshfilterpagefilterdofilterpagefilterjava55 at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava235 at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava206 at comredactedwebappfiltermemberfilterdofiltermemberfilterjava83 at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava235 at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava206 at comredactedwebappfilterauthfilterdofilterauthfilterjava113 at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava235 at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava206 at orgthisplaytagfilterresponseoverridefilterdofilterresponseoverridefilterjava125 at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava235 at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava206 at comredactedwebappfilterlanguagehandlingfilterdofilterlanguagehandlingfilterjava151 at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava235 at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava206 at comredactedwebappfiltersetcharacterencodingfilterdofiltersetcharacterencodingfilterjava146 at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava235 at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava206 at comredactedwebappfilterpartnerfilterdofilterpartnerfilterjava59 at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava235 at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava206 at comredactedwebappfiltersessionstatusfilterdofiltersessionstatusfilterjava113 at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava235 at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava206 at orgapachecatalinacorestandardwrappervalveinvokestandardwrappervalvejava233 at orgapachecatalinacorestandardcontextvalveinvokestandardcontextvalvejava191 at orgapachecatalinaauthenticatorauthenticatorbaseinvokeauthenticatorbasejava470 at orgapachecatalinacorestandardhostvalveinvokestandardhostvalvejava127 at comgooglecodepsiprobetomcat60agentvalveinvoketomcat60agentvalvejava30 at orgapachecatalinavalveserrorreportvalveinvokeerrorreportvalvejava102 at orgapachecatalinacorestandardenginevalveinvokestandardenginevalvejava109 at orgapachecatalinaconnectorcoyoteadapterservicecoyoteadapterjava298 at orgapachecoyotehttp11http11processorprocesshttp11processorjava859 at orgapachecoyotehttp11http11protocolhttp11connectionhandlerprocesshttp11protocoljava588 at orgapachetomcatutilnetjioendpointworkerrunjioendpointjava489 at javalangthreadrunthreadjava680i have tried a variety of combinations of annotations on badge or using an array instead of generictypelistbadge badges arraysaslistapirootpathbadgesgetbadgeclassor using an intermediate clientresponsegenerictypelistbadge type new generictypelistbadgeclientresponse clientresponse apirootpathbadgesgetclientresponseclasslistbadge badges clientresponsegetentitytypebut none so far have solved the problemeven more confounding is the fact that my existing setup has no problems unmarshalling jsonencoded badges which are inside of other structures like this userid123456789 userbadges badge id42 statusactive namepurple monkey thishwasher earned20120306 181618172 what am i doing wrong,['java'] +260431,stripe webhook on rails i know there is another question that exists similar to this one but i do not think it was askedanswered very well basically i have a working rails app where users can sign up for my subscription enter credit card information etc that is all working but i need to handle the situation where a users card is declined at some point during this recurring subscription the types of events they send are here typesi am having trouble accessing the chargefailed object in my app the docs on webhooks are also here and any help would be much appreciated,['ruby-on-rails'] +260436,arithmetic operations between constants consider this codedefine a 5define b 3int difference a bdoes value of difference is hardcoded as 2 in compile time or does it get calculated on runtime,['c'] +260442,default argument in function template c just to be sure from what i have read and tried i cannot put a default argument in a function template correct i have picked that much up both from my compiler and from what others have responded with i am asking because i am a newb and some of the more technical responses are hard to understand is there a work around for this i am trying to create a findmax function that uses a default relational operator but with the option to overloadietemplate typename type typename compare stdlesstype type findmaxstdvectortype vec compare comp compare return stdmax elementi suppose i could make a class for this but it seems like a lot of work when all i really want is one function thanksi should add another question as well about something that i have seen beforewhat does this function tempate do specifically what is the cmpfn default argument doingtemplate typename elemtype elemtype findmaxvectorelemtype v int cmpfnelemtype elemtype operatorcmp,['c++'] +260452,android how to get a custom attribute of an xml in activity class how do i get the attribute value required in my activity class1 valuesattrsxmldeclarestyleable nameedittext attr namerequired formatboolean declarestyleable 2 layouttextxmllinearlayout xmlnsandroid xmlnscustom androidbaselinealignedfalse androidlayout widthfill parent androidlayout heightfill parent androidorientationvertical edittext androidididtxttest androidlayout heightwrap content androidlayout widthfill parent androidinputtypetext customrequiredtrue,['android'] +260456,jquery how to determine if a div changes its height or any css attribute i wanna know how to trigger an event when a div changes its height or any css attribute i have a div with id maincontent i want jquery to automatically trigger an event when it changes its height i did something like this maincontentchangeheight function separatorcssheight maincontentheighti know its wrongheres my whole code i pasted all of it because i cannot get into jsfiddle for some reason i do not know htmlheadstyle typetextcsshtml body width 100 height 100 margin 0 padding 0separator borderright 1px solid blackstylescript typetextjavascript srcjquery164minjs scriptscript typetextjavascriptdocumentreadyfunction separatorcssheight bodyheightfunction btnsample1clickfunction maincontentcssheight 400px maincontentcsswidth 600px maincontentcssbackgroundcolor f0f0f0 btnsample2clickfunction maincontentcssheight 1600px maincontentcsswidth 700px maincontentcssbackgroundcolor f0f0f0 maincontentchangeheight function separatorcssheight maincontentheight scriptheadbodytable stylewidth 100 tr td valigntop stylewidth 19 table idmainmenu trtdinput idbtnsample1 typebutton valuesample 1 tdtr trtdinput idbtnsample2 typebutton valuesample 2 tdtr table td td valigntop stylewidth 1 div idseparatordiv td td valigntop stylewidth 80 div idmaincontentdiv td trtablebodyhtmli am trying to adjust the height of the div idseparator based on the height of maincontent whenever the height of maincontent changesps in this case i know i can use the button event to do this but i want the div to trigger the event when the height is changed please help thanks in advance,"['javascript', 'jquery', 'css']" +260462,why polymorphic association does not work for sti if type column of the polymorphic association does not point to the base model of sti i have a case of polymorphic association and sti here appmodelscarrbclass car activerecordbase belongs to borrowable polymorphic trueend appmodelsstaffrbclass staff activerecordbase has one car as borrowable dependent destroyend appmodelsguardrbclass guard staffendin order for the polymorphic assocation to work according to the api documentation on polymorphic assocation that i have to set borrowable type to the base classof sti models that is in my case is staff the question is why does not it work if the borrowable type set to sti clasome test to prove it now the test speaks only truth testfixturescarsymlone name enzo borrowable staff stafftwo name mustang borrowable guard guard testfixturesstaffsymlstaff name jullia gillardguard name joni bravo type guard testunitscar testrbrequire test helperclass cartest activesupporttestcase setup do staff staffsstaff guard staffsguard end test should be destroyed if an associated staff is destroyed do assert differencecarcount 1 do staffdestroy end end test should be destroyed if an associated guard is destroyed do assert differencecarcount 1 do guarddestroy end endendbut it seems to be true only with staff instance the results are running testsffinished tests in 0146657s 136373 testss 136373 assertionss 1 failuretest should be destroyed if an associated guard is destroyedcartest privatetmpguineapigtestunitcar testrb16carcount did not change by 11 expected but was2thanks,['ruby-on-rails'] +260464,how to draw vertical text in uilabel i am currently working on drawing vertical chinese text in a label heres what i am trying to achieve albeit with chinese charactersi have been planning to draw each character rotate each character 90 degrees to the left then rotating the entire label via affine transformations to get the final result however it feels awfully complicated is there an easier way to draw the text without complicated coregraphics magic that i am missing,['iphone'] +260505,extract numbers from a text in sql server i was searching script to extract number from text in sql server and i found thiscreate function dbogetnumbersfromtextstring varchar20returns number table number intasbegindeclare count intdeclare intnumbers varchar10set count 0set intnumbers while count lenstringbeginfind a numeric charactorif substringstringcount1 0 and substringstringcount1 9beginset intnumbers intnumbers substringstringcount1endif the next charactor is not a numeric one the current number ends so add a separatorif substringstringcount11 0or substringstringcount11 9 and substringstringcount1 0 and substringstringcount1 9beginset intnumbers intnumbers endset count count 1endsplit string to give a table with the numbers in the textinsert into numberselect thistinct items from dbosplitintnumbers returnendand call it likeselect number from dbogetnumbersfromtextgive me 120 this week and 50 next weekit works fine but i need more short code can i use patindex to extract number from textplease anyone share small good logic to do so thanks,['sql'] +260517,upload large file in android without outofmemory error my upload code as belowstring end rnstring twohyphens string boundary try url url new urlactionurlhttpurlconnection con httpurlconnection urlopenconnectionconsetdoinputtrueconsetdooutputtrueconsetusecachesfalseconsetrequestmethodpostconsetrequestpropertyconnection keepaliveconsetrequestpropertyaccept textconsetrequestpropertycontenttype multipartformdata boundary boundarydataoutputstream ds new dataoutputstreamcongetoutputstreamdswritebytestwohyphens boundary enddswritebytescontentthisposition formdata namefolder end enddswritesavepathgetbytesutf8dswritebytesenddswritebytestwohyphens boundary enddswritebytescontentthisposition formdata namefiledata filenamedswritefilenamegetbytesutf8dswritebytes enddswritebytesendfileinputstream fstream new fileinputstreamuploadfilepathfilenameint buffersize 1024byte buffer new bytebuffersizeint length 1int pro 0whilelength fstreamreadbuffer 1 dswritebuffer 0 length dswritebytesenddswritebytestwohyphens boundary twohyphens endfstreamclosedsflushinputstream is congetinputstreamint chstringbuffer b new stringbufferwhilech isread 1 bappendcharchdsclosecatchexception e eprintstacktracewhile smaller than 16 mb it upload successbut while it more than 16 mb the outofmemory error showhow to avoid the outofmemory error,['android'] +260535,ios 51 with xcode 431 uicolor colorwithpatternimage strange behavior only on device when i compile my app in xcode 431 with ios 51 i notice there is a strange behavior with background textures only on actual device there is a 1px gap in between texture tiles shown in screenshot belowmy texture are 150x150 and 300x300 at 2xso far i have tested the same build onsimulator iphoneipad both 5051 no bugiphoneipad running 501 no bugiphoneipad running 51 buggy,['iphone'] +260543,whats the general solution to typeerror object does not support this property or method on ie8 i saw several specific questions about this problem getting typeerror object does not support this property or method in ie8 each with its specific answersuppose i have a large website with lots of code i do not know what specific snippet is causing this erroris there a general method to debug this i have tried with the ie developer tools and it does not break on error is this caused by incorrect javascript syntax should i try something like js lintwhats the correct general way to identify and deal with this problem,['javascript'] +260572,how to get id from url in cake php this is my action url of which i would like to get the 16httplocalhostcarsdirectorygalleriesadd16please help me,['php'] +260594,why is my publishing failing in tomcat v70 server because of locks by another process i have a tomcat v70 server setup in my eclipse helios environment which i use for testing web applications currently i have in my workspace a struts webapp which is loaded correctly into the server along with two ther dynamic web projects which im trying to upload mainly a simple class which i want to turn into a web service for axis2 for the first project and a simple html page made for testing this issue for the second one however neither one are loading correctly inside the server and i am seeing locks by another process errorsthe error given by the server console is publishing failed with multiple errorscould not delete cdocuments and settingsxgenericworkspaceskillinventorymetadatapluginsorgeclipsewstservercoretmp1wtpwebappswstest3webinflibactivation11jar may be locked by another processcould not delete cdocuments and settingsxgenericworkspaceskillinventorymetadatapluginsorgeclipsewstservercoretmp1wtpwebappswstest3webinflibantlr277jar may be locked by another processcould not delete cdocuments and settingsxgenericworkspaceskillinventorymetadatapluginsorgeclipsewstservercoretmp1wtpwebappswstest3webinflibaxiomapi1211jar may be locked by another processcould not delete cdocuments and settingsxgenericworkspaceskillinventorymetadatapluginsorgeclipsewstservercoretmp1wtpwebappswstest3webinflibaxiomdom1211jar may be locked by another processcould not delete cdocuments and settingsxgenericworkspaceskillinventorymetadatapluginsorgeclipsewstservercoretmp1wtpwebappswstest3webinflibaxiomimpl1211jar may be locked by another processcould not delete cdocuments and settingsxgenericworkspaceskillinventorymetadatapluginsorgeclipsewstservercoretmp1wtpwebappswstest3webinflibaxis2adb160jar may be locked by another processcould not delete cdocuments and settingsxgenericworkspaceskillinventorymetadatapluginsorgeclipsewstservercoretmp1wtpwebappswstest3webinflibaxis2adbcodegen160jar may be locked by another processcould not delete cdocuments and settingsxgenericworkspaceskillinventorymetadatapluginsorgeclipsewstservercoretmp1wtpwebappswstest3webinflibaxis2antplugin160jar may be locked by another processcould not delete cdocuments and settingsxgenericworkspaceskillinventorymetadatapluginsorgeclipsewstservercoretmp1wtpwebappswstest3webinflibaxis2clustering160jar may be locked by another processcould not delete cdocuments and settingsxgenericworkspaceskillinventorymetadatapluginsorgeclipsewstservercoretmp1wtpwebappswstest3webinflibaxis2codegen160jar may be locked by another processcould not delete cdocuments and settingsxgenericworkspaceskillinventorymetadatapluginsorgeclipsewstservercoretmp1wtpwebappswstest3webinflibaxis2corba160jar may be locked by another processcould not delete cdocuments and settingsxgenericworkspaceskillinventorymetadatapluginsorgeclipsewstservercoretmp1wtpwebappswstest3webinflibaxis2fastinfoset160jar may be locked by another process could not delete cdocuments and settingsxgenericworkspaceskillinventorymetadatapluginsorgeclipsewstservercoretmp1wtpwebappswstest3webinflibaxis2java2wsdl160jar may be locked by another processcould not delete cdocuments and settingsxgenericworkspaceskillinventorymetadatapluginsorgeclipsewstservercoretmp1wtpwebappswstest3webinflibaxis2jaxbri160jar may be locked by another processetchas someone already encountered this issue and knows of a solution,['java'] +260636,spring autowired bean for aspect aspect is null i have the following spring configurationcontextcomponentscan basepackageukcomysitegooglecontactsyncaopbean namesimpleemailsender classukcomysiteutilemailsimplesimpleemailsenderimplementationaopaspectjautoproxythen i have an aspectaspectpublic class syncloggingaspect autowired private simpleemailsender simpleemailsender afterreturningvalueexecution ukcomysitedatasyncpollingpollerdopoll returningpusher public void afterpollpusher pusher simpleemailsendersendnew pusheremailpusher this aspect works i can hit a breakpoint on afterpoll but simpleemailsender is null unfortunately i cannot find clear documentation on why this is for the record my simpleemailsender bean exists and is correctly wired into other classes the following things confuse meis contextcomponentscan supposed to be picking up aspect if it is then surely it would be a spring managed bean thus autowired should workif contextcomponentscan is not for creating aspects how is my aspect being created i thought aopaspectjautoproxy just creates a beanpostprocessor to proxy my aspect class how would it do this if it is not a spring managed beanobviously you can tell i do not have an understanding of how things should be working from the ground up,['java'] +260640,libgdx spritebatch not thisplayed with perspectivecamera while i do have the basic knowledge of opengl i am just starting with libgdxmy question is why having the exact same code but only switching from orthographiccamera to perspectivecamera has the effect of no longer thisplaying any of my spritebatches heres the code i usethe create methodpublic void create texturemesh new texturegdxfilesinternaldatatexmeshtestpng texturespritebatch new texturegdxfilesinternaldatatexspritebatchtestpng squaremesh new meshtrue 4 4 new vertexattributeusageposition 3 a position new vertexattributeusagetexturecoordinates 2 a texcoords squaremeshsetverticesnew float squarexinitial squareyinitial squarezinitial 01 lower left squarexinitialsquaresize squareyinitial squarezinitial 11 lower right squarexinitial squareyinitialsquaresize squarezinitial 00 upper left squarexinitialsquaresize squareyinitialsquaresize squarezinitial10 upper right squaremeshsetindicesnew short 0 1 2 3 spritebatch new spritebatch and the render methodpublic void render glcommon gl gdxgl cameraupdate cameraapplygdxgl10 spritebatchsetprojectionmatrixcameracombined glglcleargl10gl color buffer bit gl10gl depth buffer bit glglenablegl10gl depth test glglenablegl10gl texture 2d texturemeshbind squaremeshrendergl10gl triangle strip 0 4 spritebatchbegin spritebatchdrawtexturespritebatch 10 0 spritebatchend now if in my resizeint width int height method i setup the camera like so public void resizeint width int height float aspectratio float width float height camera new orthographiccameracameraviewheight aspectratio cameraviewheighti get thisbut if i change the camera typepublic void resizeint width int height float aspectratio float width float height camera new perspectivecamera64 cameraviewheight aspectratio cameraviewheight i get thisthe reason i am asking is because i really liked libgdxs built in ability to draw text font in opengl but in their examples they use a spritebatch which they path to the font instance and they also always use ortho camera i would like to know then if spritebatch and font drawing functionality work with perspectivecamera,['java'] +260673,how to call a method of multiple arguments with delay i am trying to call a method after some delayi know there is a solution for thatself performselectorselectormymethod withobjectnil afterdelaydelayi saw this question and documentationbut my question is how can i call a method that takes two parametersfor instance void movesomethigfromidfrom toidtohow would i call this method with delay using performselectorwithobjectafterdelaythanks,['ios'] +260728,combining multiple transform entries in less i have two mixins which both convert to webkittransformrotatedeg webkittransform rotatedegscalefactor webkittransform scalefactorwhen i use them togetherdiv rotate15deg scale2 they as expected show up asdiv webkittransform rotate15deg webkittransform scale2this does not seem to be valid css as the second has precedence over the first the first is thiscarded to combine transform entries it should bewebkittransform rotate15deg scale2how can i accomplish such css to be generated by less ie multiple transform entries that are combined correctly,['css'] +260799,ios the new ipad uidevicehardware hwmachine codename so i have the following code machine names for the current lineup of ios devices does anyone know with some certainty what the codes for the new ipad is ipad announced mar 7 2012if platform isequaltostringiphone11 return iphone1g gsmif platform isequaltostringiphone12 return iphone3g gsmif platform isequaltostringiphone21 return iphone3gs gsmif platform isequaltostringiphone31 return iphone4 gsmif platform isequaltostringiphone33 return iphone4 cdmaif platform isequaltostringiphone41 return iphone4sif platform isequaltostringiphone51 return iphone5if platform isequaltostringipod11 return ipod 1gif platform isequaltostringipod21 return ipod 2gif platform isequaltostringipod31 return ipod 3gif platform isequaltostringipod41 return ipod 4gif platform isequaltostringipad11 return ipad wifiif platform isequaltostringipad21 return ipad2 wifiif platform isequaltostringipad22 return ipad2 gsmif platform isequaltostringipad23 return ipad2 cdmavif platform isequaltostringipad24 return ipad2 cdmasif platform isequaltostringi386 return simulatorif platform isequaltostringx86 64 return simulator,"['objective-c', 'ios']" +260809,query fields in a mongodb collection i am trying to query specific fields in a mongodb collection here is my code and output mongo m new mongo db db mgetdb mydb dbcollection coll dbgetcollectionstudent adding data basicdbobject moz new basicdbobject mozputname mozammil collinsertmoz dbcursor cursor collfind while cursorhasnext systemoutprintlncursornext this returns the following id oid 4f5a4477c5e80f71ece56797 name mozammilhowever i want only the name part googling around this should do the job dbcursor cursor collfind name1 while cursorhasnext systemoutprintlncursornext but it is not working help please,['java'] +260824,using multiple namespaces in html element could having multiple namespaces in the html element cause any problems or conflicts i realize this is a very broad question so i am not expecting specific pinpoint answers just overall possibilitieshtml xmlns xmlnsfb,['html'] +260848,delete a child and a parent row with one sql script instead of deleting the child row and then writing another sql statement to delete the parent row i wanted to use one statement which will do both fyi we use oracle databaseupdate i dont have a privilege to do delete on cascade,['sql'] +260849,what changed in the driver signature requirements for windows 8 i have got a passthrough nthis intermediate driver consisting of two inf files one standard and one miniport and a sys file because of the windows 7 driver signing requirements i had to get a codesigning certificate and sign the sys file in order for the driver to install on a 64bit system this works fine and i have many successful windows 7 installshowever the same installer fails on the windows 8 consumer preview 64bit if i boot with windows signature enforcement turned off it installs correctly so it is definitely a signature issue what new requirements were added between windows 7 windows 8 that i need to follow in order to get my driver to install,['c++'] +260853,javascript i18n internationalization frameworkslibraries for clientside use we are currently creating a javascript application with backbonejsand we need it translated or at least to support internationalization i18n in the futurei have been looking around and found many libraries that help some are fairly simple where others seem overly complex i found these in the past few hoursi18nextjsjsperantojsjedjsmessageformatjsjqueryi18n pluginpolyglotjsare there some blogs or sites that compare such frameworksi would like to see if others already pointed out the pluses or pitfalls on any of these librarieswe created our app module based on requirejs so if it has module support that is definitely a plusanother requirement would be setting the locale after initialization after we fetch the data from a webservice we cannot store static json files except maybe for a default language with the app the translations come from a database and need to be sent to the app via a webservice so we need to set the localization data dynamically instead of through json files this is supported at least in jed and i18next and jsperanto but most likely also in others in any case the app must never be blocked from executioni am asking for help deciding which library suits bestsomething i noticed that is already missing in jed is providing a graceful alternative when a translation is not present in the locale dictionary jed just throws an error something i find thisturbingi prefer a cleaner way of handling missing translations either provide a default string print the key back to the screen additionally but definitely not required one could have the feature like i18next has to post missing translations to a webservice though we would not need this it is a nice feature,['javascript'] +260867,rails assets do not get updated i have a rails 31 app and for some reason when i change css the changes do not show up i did bundle exec rake assetsprecompile and it helped once but now i am stuck with the old css no matter what,['ruby-on-rails'] +260870,convert from ascii string encoded in hex to plain ascii how can i convert from hex to plain ascii in pythonnote that for example i want to convert 0x7061756c to paul,['python'] +260887,c11 make pair with specified template parameters does not compile i was just playing around with g 47 one of the later snapshots with stdc11 enabled i tried to compile some of my existing code base and one case that failed somewhat confuses mei would appreciate if someone can explain what is going onheres the codeinclude utilityinclude iostreaminclude vectorinclude stringint main stdstring s abc 1 ok stdpair stdstring int a stdmake pair s 7 2 error on the next line stdpair stdstring int b stdmake pair stdstring int s 7 3 ok stdpair stdstring int d stdpair stdstring int s 7 return 0i understand that make pair is meant to be used as the 1 case if i specify the types then i might as well use 3 but i do not understand why it is failing in this casethe exact error istestcpp in function aint maina testcpp1183 error no matching function for call to amake pairstdstring inta testcpp1183 note candidate is in file included from gcc47usrlocallibgcci686pclinuxgnu470includec470utility720 from testcpp1 gcc47usrlocallibgcci686pclinuxgnu470includec470bitsstl pairh2745 note template constexpr stdpair type typename std decay and strip t2 type stdmake pair t1 t2 gcc47usrlocallibgcci686pclinuxgnu470includec470bitsstl pairh2745 note template argument deductionsubstitution failed testcpp1183 note cannot convert asa type astdstring aka stdbasic stringa to type astdbasic stringaagain the question here is just whats going on i know that i can fix the problem by removing the template specification but i just want to know whats failing here under the covers thanks in advanceeditg 44 compiles this code with no problemsremoving stdc11 also compiles with code with no problems,['c++'] +260890,how can i measure how my multithreaded code scales speedup what would be the best way to measure the speedup of my program assuming i only have 4 cores obviously i could measure it up to 4 however it would be nice to know for 8 16 and so onideally i would like to know the amount of speedup per number of thread similar to this graphis there any way i can do this perhaps a method of simulating multiple cores,['c++'] +260905,footer at the bottom in fluid layout i have a fluid layout but as a consequence when there is no enough content in the page my footer keeps moving up as in this example a popular solution to keep the footer at the bottom of the page is using position fixed or position absolute however when i do that the content can collide with the footer on resizing you can see what i mean here try to resize your window to the point in which the text is hiding behind the footerso how can i get a footer at the bottom but moving accordingly with the rest of the page in a fluid layoutthanks,"['jquery', 'css']" +260917,eager loading the right way to do things i am running ruby on rails 31 i read the following articles and documentations about eager loading and i would like to find a right way to do thingseager loading associations official documentationactiverecordassociationsclassmethods see the section eager loading of associations official documentationeager loading blog articlethe 2 saysnote that using conditions like postincludesauthor commentswherecommentsapproved trueall can have unintended consequencesthe 3 says that those unintended consequences are note examples are pretty the same so i quote the exact text of the blog article but you have to keep in mind the workaround not the specific implementationthis query since it would use a left join would also thiscard all posts without a comment with the word afirsta on any of itas commentsthat is if there are non associated objects the main associated object will not be loaded this is what happens when i try to use eager loading by adding some condition like wherecategory relationships user id current userid in a my previous question but i do not want that to happenso defeatist because i probably can not use the eager loading in my case where condition can not be set in the has many statement note that in the above code the current userid is set dynamically unlike in examples present in mentioned sites i would like to know if there are pratiquestechniquesstrategies so to limit database queries since i have a n 1 problemmaybe those pratiquestechniquesstrategies are implementable by using the ruby on rails framework at all the 1 sayseven though active record lets you specify conditions on the eager loaded associations just like joins the recommended way is to use joins insteadwhat and how to solve this issue the right waymaybe a solution is to retrieve and build myself what needs to be loaded by running specific and separated database queries but then the problem would be how to pass associate interpolate those retrieved associated objects to the main associated object so that those can be used a la eager loading way that is how to make possible see the mentioned question for more information to use code like articlecomments and get only comments that i eager loaded myself after my eager loading is it possible correct to make something like articlecomments my eager loaded comments so to passassociateinterpolate comments to articles,"['ruby-on-rails', 'ruby']" +260921,is it possible to grey out not just thisable a menuitem in android there is a question for the same functionality on blackberry and a few different threads referred to this bug which has since been closed without resolution as far as i can tell but i have not found one specifically for androidi am calling setenabledfalse on certain menuitems based on some state but they visually look the same i would like them to be offset in some way so that the user knows that the option currently is not available is there any way to do that,['android'] +260928,throwing exception from constructor in c i have read several articles here and else where that it is ok to throw exception from constructor however i have noticed that it does not call destructor of base class or its data members if an exception is thrown from the constructor consider the following exampleinclude iostreamusing namespace stdstruct c c cout function endl c cout function endl struct e public c c c e cout function endl throw 4 e cout function endl int main e e g testcpp aexecceterminate called after throwing an instance of intaborted core dumpedin this case es constructor throws an exception but cs destructor as a data member or as a base class is not called now if cs destructor performs some cleanup operation like closing filessockets and deleting heap allocations this can cause problems so my question is why and when is it ok to throw exceptions from constructors,['c++'] +260943,java including variables within strings ok so we all should know that you can include variables into strings by doingstring string a string avariableis there a way to do it likestring string a string avariablein other words without having to close the quotation marks and adding plus signs it is very unattractive,['java'] +260946,whats the equivalent of something retain autorelease in arc whats the equivalent of something retain autorelease in arci have a problem where a class dbrequest calls my delegate to signify completion my delegate then sets the dbrequest instance to nil which deallocs it but then when the stack pops out of my delegate and jumps back to the dbrequest it of course then crashesif i was not in arc in my delegate i would simply do thedbrequest retain autorelease before releasing my reference to it so that it would survive long enough until the next run loop autoreleased itwhat should i do in arc,"['iphone', 'objective-c', 'ios']" +260956,difference between parsing a text file in r and rb mode what makes parsing a text file in r mode more convenient than parsing it in rb modeespecially when the text file in question may contain nonascii characters,['python'] +260984,php object literal in php i can specify array literals quite easilyarray arrayname john hobby hiking arrayname jane hobby dancing but what if i want array of objects how can i specify object literal in phpie in javascript it would be name john hobby hiking name jane hobby dancing,['php'] +261020,can not import comgoogleandroidmapsmapactivity i try to import comgoogleandroidmapsmapactivity but my program can not recognize it i also have useslibrary androidnamecomgoogleandroidmaps and set the apikey in my projectcan anybody explain why i can import the above linethanks in advance,['android'] +261035,even though it is not cannot submit apps to itunes connect trying to upload my app the app sends fine but i get this error via email once the binary has been sentdear developerwe have thiscovered one or more issues with your recent binary submission for myapp before your app can be reviewed the following issues must be correctedcorrupt png file the png icon file appears to be corruptonce these issues have been corrected go to the version details page and click ready to upload binary continue through the submission process until the app status is waiting for upload and then use application loader to upload the corrected binaryregardsthe app store teami have tried replaced the and resubmitted but i got the same email,['iphone'] +261064,what are best practices for using svg icons on android i am about to create my first android native so not browser based app and looking for some good practices regarding icon creatingprovisioningsince it should support multiple devicesresolutions i thought it is best to use svg to create them there is at least this lib that promises to offer support for svg on androidso far i have not found resources describing the usage of this or another library as a means to render svg icons on the device so i am a bit reluctant in using it the best i have seen so far is using svg as the source format for prerendering png based icons in different resolutionsso my questions is are svg icons a good option to use directly on the device without a png prerendering step does it work at all and if why does nobody seem to use this approach,['android'] +261092,python cdecimal invalidoperation i am trying to read financial data and store it the place i get the financial data from stores the data with incredible precision however i am only interested in 5 figures after the decimal point therefore i have decided to use t quantizecdecimaldecimal01 roundingcdecimalround up on the decimal i create but i keep getting an invalidoperation exception why is this import cdecimal c cdecimalgetcontext cprec 5 s 452091080109 s 0257585003972054 works t cdecimaldecimalsquantizecdecimaldecimal01 roundingcdecimalround uptraceback most recent call last file stdin line 1 in module cdecimalinvalidoperation class cdecimalinvalidoperationwhy is there an invalid operation here if i change the precision to 7 or greater it works if i set s to be 0257585003972054 instead of the original value that also works what is going onthanks,['python'] +261100,how can i get array of elements including missing elements using xpath in xslt given the following xmlcompliant htmldiv aa1a bb1bdivdiv bb2bdivdiv aa3a bb3b cc3cdivdoing a will returna1a3the problem with above is that the third column data is now in second place when a is not found it is completely skippedhow can you express an xpath to get all a elements which will returna1 null a3same case for c i wonder if it is possible to getnull null c3update consider another scenario where are no common parents divh1heading1h1 aa1a bb1bh1heading2h1 bb2bh1heading3h1 aa3a bb3b cc3cupdate i am now able to use xslt as well,"['java', 'html']" +261104,how to set the background color of the whole page in css i am trying to set the background color of the page at yumdomcom to yellowi have tried the following and it fails body backgroundcolor yellow only a sliver under the header turns yellowdoc3 backgroundcolor yellow result same as abovebd backgroundcolor yellow result same as aboveyuimain backgroundcolor yellow a rectangle turns yellow ending at where the content ends i want this rectangle to extend all the way to the footeralso note that if in the developer tools in chrome i highlight either one of the html elements above i get only a certain portion of the page highlighted a footer and the section below the content remain unhighlightedi want the yellow to fill the entire space between the header and the footer and leave no white space outnote that we are using yui reset fonts and grids css templates v 280r4many thanks,"['html', 'css']" +261141,undefined variable session i am getting e notice errors in a core cakephp file when it tries to reference a neverset or unset session cakelibscake sessionphp line 372function readname null if is nullname return this returnsessionvars if emptyname return false result setclassicextract session namei have done a search through my code in the app directory and i cannot find references to session or session destroy am i missing anythingthis error shows up when i try to run any unit tests is thisnormal i have cleared out the cake directory and replaced it with another one same version just to make sure that i had not inadvertently modified anything in the core files but i still get the same error i am not sure if this is just a flaw in the framework or something elseedithere are the results of the test run on the command linewelcome to cakephp v1311 consoleapp apath varwprogramappcakephp test shellrunning app case modelsowners equitye notice undefined variable session in varwprogramcakelibscake sessionphp on line 372e notice undefined variable session in varwprogramcakelibscake sessionphp on line 372errorunexpected php error undefined variable session severity e notice in varwprogramcakelibscake sessionphp line 372 in testgenerateownerwithdrawals in balancetestcase in varwprogramapptestscasesmodelsowners equitytestphperrorunexpected php error undefined variable session severity e notice in varwprogramcakelibscake sessionphp line 372 in testgenerateownerwithdrawals in balancetestcase in varwprogramapptestscasesmodelsowners equitytestphp,['php'] +261152,using multiple allocators efficiently i have been researching switching my allocation method from simpling overloading new to using multiple allocators through the code base however how can i efficiently use multiple allocators the only way i could devise through my research was having the allocators be globals although this seemed to have issues since it is typically a bad idea to have the use of many globalsi am looking to find out how to use multiple allocators efficiently for example i may have one allocator use only for a particular subsystem and a different allocator for a different subsystem i am not sure if the only way to do this is through using multiple global allocators so i am hoping for a better insight and design,['c++'] +261153,ipad retina thisplay suffix i am looking to put ipad retina crazy quality images into my app for the new ipads launch on the 16th martch however i cannot find the correct suffix for my file names anywhere in the documentsi use 2x suffix for iphone and ipod retina thisplay if anyone else knows what it iswill be for the ipad and even more can show me a link to the official documents on this i would really appreciate itthanks dextrathought i would just leave a bit of code i have started using to use my iphone 2x images for the ipad nonretina ones as most of my 2xiphone and ipad images were the same and duplicates are just a waste of space uiimageimagenamedsmartnsstringname uiimage returnimage uiimage imagenamednsstring stringwithformat name if ui user interface idiom uiuserinterfaceidiompad if uiscreen mainscreen respondstoselectorselectorscale uiscreen mainscreen scale 2 ipad scale 2 ie 3rd gen ipad else ipad scale 1 ie 1st and 2nd gen ipad return uiimage imagenamednsstring stringwithformat2x name return returnimage this means instead of callinguiimage imagenamedimagenameyou callself imagenamedsmartimagenamehope this help people a bit more di found this idea by goggling but i cannot find the original site to link so thank you whoever you were,['ios'] +261161,good low level http library for net i am looking for a library for net which would let me have full control over what gets sent via net i am going to use it for http experiments i know of cs httpwebrequest and i want to try something different because i cannot control all the headers have you ever tried to change the case of keepalive header that it sends or selectively ignore certificate errors i want to experiment with this stuff my language of choice is ccan anybody recommend a good http library which would let me meddle with the lowlevel stuff when i want but wouldnt burden me with it when i do not,['c#'] +261195,issue updating ruby on mac with xcode 431 i am using rvm to install it and it gives me this errorthe provided compiler usrbingcc is llvm based it is not yet fully supported by ruby and gems please read rvm requirementsi am on lion 1073 and i have xcode 431,['ruby'] +261198,what does java compiler interprets by byte char int long 1 possible duplicateweird java behavior with casts to primitive types why does this code in javaint i byte char int long 1systemoutprintlniprints 1 why does it even compilesource java code geeks,['java'] +261211,h2 sql create table with multicolumn primary key how can i create a multicolumn primary key within the create table statement using the h2 databasefrom my investigations the code to do so in mysql and apache derby databases iscreate table sampsched class code char7 not null day smallint not null starting time ending time primary key class code daybut this does not work in h2 it results in a orgh2jdbcjdbcsqlexception syntax error in sql statementany help is much appreciated thanks,['sql'] +261214,how to annotate rails models in rails version 321 im trying to follow some online tutorial on annotating my models in rails however it seems all the tutorials are either talking about outdated annotation versions or incorrect installations its a meso far ive tried the following1 added this in the gemfilegem annotate 2402 then the commandbundle install3 i then saw that the annotation gem was installed and showing up on the commandbundle show4 lastly in order to annotate my models i used the commandbundle exec annotate position beforeat this point i was expecting my models to be annotated however what i got was the following error messageusersamrvmgemsruby192p290gemsactiverecord321libactive recordrailtiesdatabasesrake4in top required undefined method namespace for mainobject nomethoderrorfrom usersamrvmgemsruby192p290gemsactiverecord321libactive recordrailtierb33in loadfrom usersamrvmgemsruby192p290gemsactiverecord321libactive recordrailtierb33in block in classrailtiefrom usersamrvmgemsruby192p290gemsrailties321librailsrailtierb184in instance execfrom usersamrvmgemsruby192p290gemsrailties321librailsrailtierb184in block in load tasksfrom usersamrvmgemsruby192p290gemsrailties321librailsrailtierb184in eachfrom usersamrvmgemsruby192p290gemsrailties321librailsrailtierb184in load tasksfrom usersamrvmgemsruby192p290gemsrailties321librailsenginerb423in block in load tasksfrom usersamrvmgemsruby192p290gemsrailties321librailsapplicationrailtiesrb8in eachfrom usersamrvmgemsruby192p290gemsrailties321librailsapplicationrailtiesrb8in allfrom usersamrvmgemsruby192p290gemsrailties321librailsenginerb423in load tasksfrom usersamrvmgemsruby192p290gemsrailties321librailsapplicationrb145in load tasksfrom usersamrvmgemsruby192p290gemsrailties321librailsrailtieconfigurablerb30in method missingfrom rakefile7in top requiredfrom usersamrvmgemsruby192p290gemsannotate240libannotaterb17in loadfrom usersamrvmgemsruby192p290gemsannotate240libannotaterb17in load tasksfrom usersamrvmgemsruby192p290gemsannotate240binannotate66in top requiredfrom usersamrvmgemsruby192p290binannotate19in loadfrom usersamrvmgemsruby192p290binannotate19in mainso feeling completely stumpedany ideas on how to proceedthanks,['ruby-on-rails'] +261216,custom login using a third parameter i am working on a relatively simple login system for symfony2i have the basics down and working just finewhat makes this a bit special is i need a way to provide a third value an ecosystem value the user names in my database are not unique on their own but make unique pairs with an ecosystem valuethe ecosystem value is provided by the form that they log in fromhow can i use this ecosystem value be taken into consideration when performing a login,['php'] +261224,do i need to generate a css file from pygments for my jekyll blog to enable colorful code snippet this is my first time to use jekyll and pygments but i do not know how to insert colorful code snippeti successfully installed pygments following the official steps with the markdown like this highlight ruby def foo puts fooend endhighlight i see the html source code including the classes however there is no color for the this snippet do i need to generate some css files from pygments and include them and how,['css'] +261226,treat object like dictionary of properties in c i want to be able to access property values in an object like a dictionary using the name of the property as a key i do not really care if the values are returned as objects so dictionarystring object is fine this is the intended usageobject person new name bob age 45 idictionarystring object lookup new propertydictionarypersonstring name stringpersonnamepersonage intpersonage 1 potentially editablei was about to implement my own class for this but then i started noticing classes like dynamicobject implement the idictionary interface which made think this was already being done for me somewherewhat i want is similar to the functionality used by aspnet mvc that allows using anonymous types to set html tag attributes i have a lot of classes that use dictionaries as data sources but most of the time i should be able to pass in objects as wellsince this is for a generalpurpose library i thought i would create a reusable class that simply decorated an object with the idictionary interface it will save me from creating an explosion of overloads,['c#'] +261232,how to set decode pixel format in libavcodec i decode video via libavcodec using the following codeopen input fileifavformat open inputctx filename null null0 return false could not open fileifavformat find stream infoctx null0 return false could not find stream informationvideostream 1find video streamfori0 ictxnb streams i ifctxstreamsicodeccodec typeavmedia type video videostreami break if videostream 1 return false did not find a video streamvideo codec ctxctxstreamsvideostreamcodecfind decodervideo codecavcodec find decodervideo codec ctxcodec idifvideo codecnull return false codec not foundifavcodec openvideo codec ctx video codec0 return 1 could not open codecvideo frameavcodec alloc framescaled frameavcodec alloc framestatic struct swscontext img convert ctx ifimg convert ctx null int w video codec ctxwidth int h video codec ctxheight img convert ctx sws getcontextw h video codec ctxpix fmt w h dst pix fmt sws bicubic null null null ifimg convert ctx null fprintfstderr cannot initialize the conversion contextn return false whileb play if av read framectx packet 0 break ifpacketstream indexvideostream decode video frame avcodec decode video2video codec ctx video frame framefinished packet did we get a video frame ifframefinished if video codec ctxpix fmt dst pix fmt if video codec ctxpix fmt dst pix fmt sws scaleimg convert ctx video framedata video framelinesize 0 video codec ctxheight scaled framedata scaled framelinesize av free packetpacketthe code works correctly but it is necessary to convert each frame to the required formatis it possible to set the pixel format for decoding to get the correct format without sws scalemany thanks for your answers,"['c++', 'c']" +261274,how to approach unittesting and tdd using python nose i have been trying to get the hang of tdd and unit testing in python using nose and there are a few basic concepts which i am stuck on i have read up a lot on the subject but nothing seems to address my issues probably because they are so basic they are assumed to be understoodthe idea of tdd is that unit tests are written before the code they test unit test should test small portions of code eg functions which for the purposes of the test are selfcontained and isolated however this seems to me to be highly dependent on the implementation during implementation or during a later bugfix it may become necessary to abstract some of the code into a new function should i then go through all my tests and mock out that function to keep them isolated surely in doing this there is a danger of introducing new bugs into the tests and the tests will no longer test exactly the same situationfrom my limited experience in writing unit tests it appears that completely isolating a function sometimes results in a test that is longer and more complicated than the code it is testing so if the test fails all it tells you is that there is either a bug in the code or in the test but its not obvious which not isolating it may mean a much shorter and easier to read test but then its not a unit testoften once isolated unit tests seem to be merely repeating the function eg if there is a simple function which adds two numbers then the test would probably look something like assert adda b a b since the implementation is simply return a b whats the point in the test a far more useful test would be to see how the function works within the system but this goes against unit testing because it is no longer isolatedmy conclusion is that unit tests are good in some situations but not everywhere and that system tests are generally more useful the approach that this implies is to write system tests first then if they fail isolate portions of the system into unit tests to pinpoint the failure the problem with this obviously is that its not so easy to test corner cases it also means that the development is not fully test driven as unit tests are only written as neededso my basic questions areshould unit tests be used everywhere however small and simple the functionhow does one deal with changing implementations ie should the implementation of the tests change continuously too and does not this reduce their usefulnesswhat should be done when the test gets more complicated than the code its testingis it always best to start with unit tests or is it better to start with system tests which at the start of development are much easier to write,['python'] +261349,android camera how can i take a specific rectangle from the byte array i have created an application that shoots and saves photosi have a preview and an overlay on top of that previewthe overlay defines a square the area around the square shows the preview a bit darker as you can see in the imageexamplewhat i need to do is to extract the part of the image where the square isthe square is defined like this rect frame new rect35050450150how can i do that i have the byte array byte data that i can save but i want to change the application so that only the square area will be savededit i have tried the followingint pixels new int10 bytearrayoutputstream bos new bytearrayoutputstream bitmap bitmap bitmapfactorydecodebytearraydata 0 datalength bitmapgetpixelspixels 0 480 350 50 100 100 bitmap bitmapcreatebitmappixels 0 100 100 100 configargb 4 bitmapcompresscompressformatjpeg 0 bos byte square bostobytearrayand then write the array square to a new filethe problem is that i get a picture made of lines there is a problem with the transformation that i made,['android'] +261364,how to prevent simulated mouse events in mobile browsers mobile browsers simulate mouse events in order to support websites that only attach handlers to mouse events however if you want to implement two interaction models one for mouse events and one for touch events then it is helpful to prevent the browser from simulating mouse eventson ios safari this is fairly straightforward simply run preventdefault on touchendjquerydocumentontouchend functione do some logic epreventdefaultthat is pretty sane unfortunately neither androids default browser nor dolfin cancel mouse simulation using this technique dolfin will cancel mousedown when preventdefault is run on touchstart but that is not very helpful because you do not know what action the finger will take on touchstartis there some other way of conditionally or even not conditionally preventing simulated mouse events from firingeditin order to begin to understand the problems better i have started a touch events compatibility table at,['javascript'] +261365,weird linker error linking to opencv lnk1107 invalid or corrupt file cannot read at 0x2e8 this opencv build was working for me a few nights ago i am trying to run the example grabcutcpp file given with the opencv examples and so i set up a quick project and brough the cpp file in then i set up all of the standard configurations and got this error on buildingerror lnk1107 invalid or corrupt file cannot read at 0x2e8 opencv calib3d231dllwhat does this mean,['c++'] +261374,mediaplayersetdatasource causes ioexception for valid file this code used to work then maybe i changed something somewhere or if i know android right an update introduced a bug in the media player it stopped working on some devices especially my nexus s 236the file testm4a 17a 775a 201 bytes was downloaded by the app to verify its integrity i copied it to the sd and played it on my pc no problem also binarycompared it with the original file and it matched 100try mediaplayer new mediaplayer mediaplayersetoncompletionlistenerthis mediaplayersetonpreparedlistenerthis mediaplayersetonseekcompletelistenerthis mediaplayersetonbufferingupdatelistenerthis mediaplayersetoninfolistenerthis mediaplayersetonerrorlistenerthis i even tried reading the file from sd card same error file file new filedatadatacommycompanymyappfilesmediacachetestm4a fileisfile true filelength expected value fileinputstream is new fileinputstreamfile mediaplayersetdatasourceisgetfd throws if i use the filename as parameter it throws later when preparing the media player mediaplayerprepareasynccatch exception e javaioioexception setdatasourcefd failed status0x80 eprintstacktraceq what might cause this ioexception for setdatasourcefd when the file is indeed validupdate heres a 98 kb audio file that i cannot play on my nexus s 236a friend of min runs some zte device 22 and it seems to work i do not get it,['android'] +261396,ios5 nsmanagedobjectcontext concurrency types and how are they used literature seems a bit sparse at the moment about the new nsmanagedobjectcontext concurrency types aside from the wwdc 2011 vids and some other info i picked up along the way i am still having a hard time grasping how each concurrency type is used below is how i am interpreting each type please correct me if i am understanding anything incorrectly nsconfinementconcurrencytypethis type has been the norm over the last few years mocs are shielded from each thread so if thread a moc wants to merge data from thread b moc via a save message thread a would need to subscribe to thread bs moc save notification nsprivatequeueconcurrencytypeeach moc tree parent children mocs share the same queue no matter what thread each is on so whenever a save message from any of these contexts is sent it is put in a private cue specifically made only for this moc treensmainqueueconcurrencytypestill confused by this one from what i gather it is the like nsprivatequeueconcurrencytype only the private queue is run on the main thread i read that this is beneficial for ui communications with the moc but why why would i choose this over nsprivatequeueconcurrencytype i am assuming that since the nsmainqueueconcurrencytype is executed in the main thread does this not allow for background processes is not this the same as not using threads,"['iphone', 'ios']" +261422,is there a way to sortorder keys in javascript objects for example the followingvar data states nsw vic countries gbr aus capitals syd melfor var item in data consolelogitemprintsstatescountriescapitalsis there a way to sort alphabetically so that it printscapitalscountriesstates,['javascript'] +261424,ofstream as function argument is there a way to pass output stream as argument like void foo stdofstream dumfile i tried that but it gave error class stdbasic ofstreamchar stdchar traitschar has no suitable copy constructor,['c++'] +261454,glob cannot find file names with multibyte characters on windows i am writing a file manager and need to scan directories and deal with renaming files that may have multibyte characters i am working on it locally on windowsapache php 538 with the following file names in a directoryfilenamejpg 14nn1jpgfileanamejpg ojpgaajpgtesting on a live unix server woked fine testing locally on windows using globpath returns only the first one filenamejpgusing scandir the correct number of files is returned at least but i get names like jpg note those are regular question marks not the i12 characteri will end up needing to write a search feature to search recursively through the entire tree for filenames matching a pattern or with a certain file extension and i assumed glob would be the right tool for that rather than scan all the files and do the pattern matching and array building in the application code i am open to alternate suggestions if need beassuming this was a common problem i immediately searched google and stack overflow and found nothing even related is this a windows issue php shortcoming whats the solution is there anything i can doaddendum not sure how related this is but file exists is also returning false for these files passing in the full absolute path using notepad the php file itself is utf8 encoding no bom i am certain the path is correct as neighboring files without multibyte characters return trueedit glob can find a file named filenamea14jpg previously in my htaccess file i had adefaultcharset utf8 which i did not consider before filenamea14jpg was printing as filenamei12i12i12jpg the only effect removing that htaccess line seemed to have was now that file name prints normallyi have deleted the htaccess file completely and this is my actual test script in it is entirety i changed a couple of file names from the original postprint rscandiruploads print rglobuploadsoutput locally on windowsarray 0 1 2 jpg 3 jpg 4 jpg 5 filenamea14jpg 6 filenamejpg 7 testtestjpgarray 0 uploadsfilenamea14jpg 1 uploadsfilenamejpgoutput on remote unix server array 0 1 2 filenamea14jpg 3 filenamejpg 4 testi testjpg 5 14n n1jpg 6 ojpg 7 aajpgarray 0 uploadsfilenamea14jpg 1 uploadsfilenamejpg 2 uploadstesti testjpg 3 uploads 14n n1jpg 4 uploads ojpg 5 uploadsaajpgsince this is a different server regardless of platform configuration could be different so i am not sure what to think and i cannot fully pin it on windows yet could be my php installation ini settings or apache config any ideas,['php'] +261474,how do i programmatically locate my dropbox folder using c how do i programmatically locate my dropbox folder using c registry environment variable etc,['c#'] +261505,how do i output raw html when using razorengine not from mvc i am trying to generate emails with html content this content has already gone through sanitation so i am not worried in that regard however when i callrazorparsetemplate modelon the following razor templatedoctype html public w3cdtd html 40 transitionalenhtml body new systemwebhtmlstringmodelemailcontent bodyhtmlthe email that is outputted is html encoded but i need it decoded how can i accomplish this,['c#'] +261527,use regular expression to findreplace substring in nsstring i would like to use regular expression to find every instances of a regular expression pattern ie in my string and remove that from so the return value is the original string without any of the matches also would like to use the same function to match multiple spaces between words and have a single space instead could not find such a function sample input string nsstring str 123 1245 ross test 12return value should be 123 ross test 12 if anything matching this pattern or multiple white spaces and replaces it with,"['objective-c', 'ios']" +261536,is there easy way to handle uialertview result without delegation i have a function that shows a uialertview with yesno buttons and it is used only inside the functions scope so i dont want to implement a delegation to catch the user feedback is there any way to know what button users clicked without implement uialertviewdelegate something likealert showifalert indexofclickedbutton indexofyesor lamda expression as in animation,"['iphone', 'ios']" +261543,override valueof and tostring in java enum the values in my enum are words that need to have spaces in them but enums cannot have spaces in their values so it is all bunched up i want to override tostring to add these spaces where i tell it toi also want the enum to provide the correct enum when i use valueof on the same string that i added the spaces tofor examplepublic enum randomenum starthere stopherecall tostring on randomenum whose value is starthere returns string start here call valueof on that same string start here returns enum value startherehow can i do this,['java'] +261552,how to stop video playing in videoview programmatically in android i am using videoview for playing videoi would like to stop the playing video completelyplease help me on this for solving itthanks,['android'] +261565,how to integrate matlab code library with android i have an algorithm and some other code which is in matlab and i want to use it in my android application how can i do thiscan i make a jar file from matlab for use with androidi have to do something else,['android'] +261580,java is allocating extra 2gb of memory i got a new vps to run some java programs that me and some buddies have made i start the process with a line like thisjava xmx512m jar programjaron our old vps you could use the top command to see how much virtual and resident memory was being used it would use like 600700mb of virtual memory now on our new vps with that same command the virtual memory seems to always be an extra 2gb over the xmx value so instead of the virtual memory being around 600700mb it is instead 270030mbthe old vps is running centos 57 and the new is running centos 62 both are running jre 17u3 64bitwhy is this and how can i fix itedit toppid user pr ni virt res shr s cpu mem time command27645 pyro 20 0 3003m 270m 10m s 50 17 11918 java xmx512m jar cserverjaranother editi am not questioning why virtual memory is using more memory than specified in the java command line i am questioning why it is using so much more than it used to,['java'] +261584,csvreader and inputstream i have created csvreader and i am trying to read csv file from assets for that reason i should use inputstream but my code below does not have inputstream constructor could anyone tell me how i could add or change something in code so i can use inputstreampublic class csvreader private bufferedreader br private boolean hasnext true private char separator private char quotechar private int skiplines private boolean linesskiped public int linescount 0 public static final char default separator public static final char default quote character public static final int default skip lines 0 public csvreaderreader reader thisreader default separator default quote character default skip lines public csvreaderreader reader char separator char quotechar int line thisbr new bufferedreaderreader thisseparator separator thisquotechar quotechar thisskiplines line public string readnext throws ioexception string nextline getnextline return hasnext parselinenextline null public string getnextline throws ioexception if thislinesskiped for int i 0 i skiplines i brreadline thislinesskiped true string nextline brreadline if nextline null hasnext false return hasnext nextline null public liststring readall throws ioexception liststring allelements new arrayliststring while hasnext string nextlineastokens readnext if nextlineastokens null allelementsaddnextlineastokens return allelements private string parselinestring nextline throws ioexception if nextline null return null liststring tokensonthisline new arrayliststring stringbuffer sb new stringbuffer boolean inquotes false do if inquotes continuing a quoted section reappend newline sbappendn nextline getnextline linescount if nextline null break for int i 0 i nextlinelength i char c nextlinecharati if c quotechar if inquotes nextlinelength i1 nextlinecharati1 quotechar sbappendnextlinecharati1 i else inquotes inquotes ifi2 nextlinecharati1 thisseparator nextlinelengthi1 nextlinecharati1 thisseparator sbappendc else if c separator inquotes tokensonthislineaddsbtostring sb new stringbuffer else sbappendc while inquotes tokensonthislineaddsbtostring return string tokensonthislinetoarraynew string0 public void close throws ioexception brclose,"['java', 'android']" +261610,different row layouts in listview this post is related to this viewholder not working on that post i was following a tutorial on how to use viewholder on a listview what i want now is to have the last item on a listview to have a different layout than the rest heres my codeint lastpos mlistsize1 systemoutprintlnposition position mlist lastpos ifpositionlastpos view viinflaterlayoutlist item record null holdertextview textviewviewfindviewbyidridrecord view else view viinflaterlayoutlist item bn null holdertextview textviewviewfindviewbyidridtv name viewsettagholderi just get the listview size minus 1 and have a condition that checks the if current position is equal to the last item however this code sets the last items layout same as the rest getview method full codeprivate class customlistadapter extends arrayadapter private arraylist mlist private context mcontext public customlistadaptercontext context int textviewresourceid arraylist list supercontext textviewresourceid list thismlist list thismcontext context public view getviewfinal int position view convertview viewgroup parent view view convertview final togglebutton tb if view null viewholder holder new viewholder layoutinflater vi layoutinflater getsystemservicecontextlayout inflater service int lastpos mlistsize1 systemoutprintlnposition position mlist lastpos ifpositionlastpos view viinflaterlayoutlist item record null holdertextview textviewviewfindviewbyidridrecord view else view viinflaterlayoutlist item bn null holdertextview textviewviewfindviewbyidridtv name viewsettagholder final itemsthisplay listitem itemsthisplay mlistgetposition if listitem null viewholder holder1 viewholderviewgettag holder1textviewsettextlistitemgettag viewsetonclicklistenernew onclicklistener public void onclickview arg0 clickonlistitem toastmaketextgetbasecontext button is position listitemgettag toastlength longshow tb togglebutton viewfindviewbyidridtogglebutton tbsetonclicklistenernew viewonclicklistener public void onclickview v iftbischecked toastmaketextgetbasecontext button is position checkedtbischecked listitemgettag toastlength longshow else toastmaketextgetbasecontext button is position checkedtbischecked listitemgettag toastlength longshow return view could anybody help me with this,['android'] +261637,spring prototype scope use cases i have clear understanding of the various scopes of spring beans but i am looking for some use cases of prototype scope of a bean in enterprise tier projects it would be great if you can share some real life use cases of the prototype scope not the request scope,['java'] +261653,using opencv filestorage on ios i am creating an object classifier using opencv and to avoid having to train the classifiers every time the app is launched i would like to somehow store them in a file the most convenient way available seems to be using opencvs filestorage classi gave this a shot but it did not seem to work the saved file did not show up anywhere though i did not receive an error i suppose ios does not just let you save any file an alternative way would be to retrieve the yaml as a string convert it to an nsstring and save it in a property list but i am not sure how this can be done or whether it is even possibleany help would be greatly appreciated,"['c++', 'objective-c', 'ios']" +261683,the foreach block is missing a closing character i am having fun with razor today can you see what is wrong with this view and explain why it errorsforeach var item in modelif itemid previousorderid div classorderdetail div classcustomer p clastrongorderidp pitemidp p clastrongorder datep pstringformat0g timezoneinfoconverttimeitemdateinitialised timezoneinfofindsystemtimezonebyidgmt standard timep p clastrongcustomer namep pitemwebsiteusernamep p clastrongpractice namep pitemwebsiteuserpracticenamep p clastrongcustomer emailp pitemwebsiteuseremailaddressp div div classdetail span clastronglicence keyspanspanitemlicencelicencekeyspan span clastrongserial nospanspanitemlicenceserialnumberspan div if itemid previousorderid previousorderid 0 div div classcleardiv previousorderid itemid,"['c#', '.net']" +261699,getting useful gcov results for headeronly libraries for my headeronly c library lots of templates etc i use gcov to check test coverage however it reports 100 coverage for all headers because the unused functions are not generated by the compiler in the first place manually spotting uncovered functions is easy but defeats the purpose of continuous integrationahow does one solve this automatically should i just use lines hit loc as my coverage metric and just never reach 100 again,['c++'] +261740,how to extend a views touch area i have a vertical linearlayout it shall act as a quick jump bar so the width is very small and the height matches nearly the whole screen height when i touch it and move around inside everything is fine that means my ontouchevent is called and i can get and follow the position of the finger but since the bar is not very wide the user can easily drift outside of that view so it would be necessary to let the user continue the movement even when outside the view in fact the same thing like a listview doesi do not know why a listviews ontouchevent is called even when outside the listview but not in case of my linearlayout i tracked it down back to the thispatchtouchevent here the situation is the same that method is always called for the listview even when outside but not in case of the linearlayout when moving outsidei would be very happy if someone could give me a hint thanks a lotbernd,['android'] +261775,how can i force the browser to print a pdf version of a webpage consider a static html page as testhtml and a printable version of the page has been stored in testpdf how can i guide browser to load and print testpdf instead of testhtml when visitors tell their browser to printif it is not possible how can i introduce a print button using javascript within the html page to do so,"['javascript', 'html']" +261843,spring 3 mvc onetomany within a dynamic form addremove on createupdate i am looking for a solution to manage a onetomany relation within an html form using jquery i am developing with spring spring mvc and hibernate i found many tracks on the web but not any working fullexamplethe backgroundi have three jpa entitiesconsultjava 1entitytablename consultpublic class consult private integer id private string label private setconsulttechno consulttechnos getters setters consulttechnojava 2entitytablename consult technopublic class consulttechno private integer id private techno techno private consult consult private string level getters setters technojava 3entitytablenametechnopublic class techno private integer id private string label private setconsulttechno consulttechnos getters setters as shown a consult 1 contains n consulttechnos 2 which are caracterized by a level and a techno 3the needsusing an html form i would like to have a add a techno button which dynamically adds two fields in the dominput typetext nameconsultconsulttechnostechnoid input typetext nameconsultconsulttechnoslevel of course each time the user clicks on the button those two fields should be readded etc i chose input typetext for the example but at the end the fields will be two selectfour kinds of operation should be coveredadd a child entity when creating a new master entityremove a child entity when creating a new master entityadd a child entity when updating a new master entityremove a child entity when updating a new master entitythe problemthat layout part already works but when posting the form i cannot manage to bind the dynamically added fields to my modelattribute consultdo you have any idea of how to do that kind of jobs i hope i have been clear enoughthanks in advance,['java'] +261877,spring security not hitting defaulttargeturl after successful authtication i have implemented springsecurity in my application my springsecurityxml has following formlogin tagformlogin loginpageloginhtm defaulttargeturldashboardhtm authenticationfailureurlloginhtmerrortrue authenticationsuccesshandlerrefauthenticationsuccesshandler i want to login from loginhtm and after successful authetication i want user to hit dashboardhtm everythig is working fine except for the fact that after successfull authetication it does not hit dashboardhtm but hits the contextbut if i manually type dashboardhtm in url then everything works fineyesi have the implementation of authticationsuccesshandler,['java'] +261903,interacting with bash from python i have been playing around with pythons subprocess module and i wanted to do an interactive session with bash from python i want to be able to read bash outputwrite commands from python just like i do on a terminal emulator i guess a code example explains it better proc subprocesspopenbinbash proccommunicateusermachine proccommunicatelsnfile1 file2 file3obviously it does not work that way is something like this possible and howthanks a lot,['python'] +261913,memory usage of thread or process in java in my application i run some threads with untrusted code and so i have to prevent a memory overflow i have a watchdog wich analyses the time of the current thread the threads were called in serialbut how i can determine the memory usagei only know the memory usage of the whole vm with runtimetotalmemory if there is a possibility to find out the usage of the thread or the usage of the single process it would be great with the memory usage of the process i could calculate the usage of the thread anyway,['java'] +261925,how to refresh datatables i am using datatables plugin to make my table interactivethe table is echod by php on the pagewhen i add a record to the db i am loading the table using jquery load but this breaks datatableshow can i update the table while still keeping datatables intactnote i am using dom as the data source and not server side processing,['jquery'] +261947,subsequent pcntl signal signals not kicking off handler lemme begin by giving a basic description of the code i have i start off with a main parent process note i am not showing all functions for simplicity let me know if you need me to expand at any pointdeclareticks1pcntl signalsighup arrayforker restartsignalhandlerifforker is not running new forkerclass forker private active forks array private parent pid null public function construct thisparent pid getmypid thiscreate fork thiswait for active public function wait for active whileemptythisactive forks foreachthisactive forks as kfork ifthisfork no longer runningfork unsetthisactive forksk pseudo code public function fork no longer runningpid return true if ps elf grep pid does not returns only the grep command else return false aka the fork is still running public function create fork pid pcntl fork ifpid 1 posix killthisparent pid sigterm else ifpid add the pid to the current fork thisactive forks pid else run our process pcntl execusrbinphp arraydomaindevwindexphpholderprocess exit0 public function restartsignalhandler forks thisactive forks foreachforks as pid thiscreate fork posix killpid sigint class holder public function process x new processor class processor public function construct pcntl signalsigint arraythis shutdownsignalhandler public function shutdownsignalhandler echo shutting down exit here is what is happeningi start my script and i properly get the processes eg parentpid2 childpid3i then send the parent a sighup signal and it properly kills andstarts a new child process eg parentpid 2 childpid4i then send the parent a 2nd sighup signal and it properly tries and adds a new child process but it refuses to kill the 2nd childpid eg parentpid2 undyingchildpid4 newchildpid5lemme know if that needs more detailsdoes not make sense i cannot figure out why the first time it would properly kill the children but the 2nd time it does notthe even weirder part is that when i change it so that i change my restart handler so that it keeps trying to kill the child with a sigint it fails each time but when i send it a sigkill command it kills the child processiftime passed 60 posix killpid sigkilli need the child to be able to be killed by sigint in order to handle it properly i do not want to just sigkill it is there any reason as to why the 2nd time around sigint wouldnt work but sigkill will,['php'] +261961,console unavailable in class library c this question here seems contrary to what i have experienced i cannot access the console from within a new class library i have using system at the top i am using visual studio 11 on windows 8 i doubt that this has been lost in the update so that means that i am doing something wrongalso once this is working is the console available in a portable class libraryedithere is just a test file i madeusing systemusing systemcollectionsgenericusing systemlinqusing systemtextusing systemthreadingtasksnamespace adamlibutilconsolesupport class saferead private void test systemconsolewritelinetest console is not found in system this is in the class libraryresolvedlike i thought it was my faultthanks to darindimitrov who pointed out that with vs 11 and metro console support has been removed for use with metro so to resolve this i needed to create a new project with the second kind of class library there are two listed and i used the one with the description that includes metro to resolve the issue i had to use the other type without metro in the descriptionthanks again to all that helped,['c#'] +261963,mvc 4 beta you must write an attribute typeobject after writing the attribute with local name type i am working with the webapi in the new mvc 4 beta i came across this error when trying to get an entity that has a virtual icollection property to populate is there a way to get around this as of right now i understand this is in the beta stage so this might be fixed down the road it was just a curiosity if there is a solution out there for this,['c#'] +262009,how to automatically classify images by dominant color i have many images tens of thousands of fairly large jpg images each is an image of an index card most of them are white but some have standard indexcard colors these colors the colors correspond to data attributes so i would like to programmatically classify these cards by color i know itas possible to extract the dominant color from images in a web browser using a canvas element and a an algorithm like color thief and it worksait gives me an rgb value which is enough to bin the cardsbut i canat see how i could run such a thing through a web browser on so many images iam wondering if anyone can recommend a commandline tool perhaps a python or ruby module that could do something similar,"['python', 'ruby']" +262023,change file split size in hadoop i have a bunch of small files in an hdfs directory although the volume of files are relatively small the amount of processing time per file is huge that is a 64mb file which is the default split size for textinputformat would take even several hours to be processed what i need to do is to reduce the split size so that i can utilize even more nodes for a job so the question is how is it possible to split the files by let us say 10kb do i need to implement my own inputformat and recordreader for this or is there any parameter to set thanks,['java'] +262025,find all columns of a certain type in all tables in a sql server database how can i find all columns of a certain type for example ntext in all tables in a sql server databasei am looking for a sql query,['sql'] +262031,is it possible to reuse boostspiritqi grammar in another grammar definition is it possible to reuse boostspiritqi grammar in another grammar as a rule for examplefor example if i define a grammar to parse line of text into a structure holding street address template typename iter struct address grammar qigrammar iter address qirule iter stdstring street name qirule iter stdstring street number qirule iter address address i might want to reuse that grammar in two other grammars for example one might be for parsing of a vector of addresses stored in a file another reuse might be in more complex structure where one of the fields is this street address structure template typename iter struct company grammar qigrammar iter company qirule iter stdstring comp name can i reuse the address grammar somehow here qirule iter company company instead of defining the whole grammar in one place i am thinking to split it into smaller reusable blocks it is fine if they are inside one header file my data structures are slightly more complex couple of fields inside struct with a list of other structures and so on so i do not want to put it into one grammaris it possible to reuse boostspiritqi grammar in this wayedit thinking about it do i just define qirules in a namespace and then put together a grammar from the rules that i need,['c++'] +262116,changing cursor to waiting in javascriptjquery how would i get my cursor to change to this loading icon when a function is called and how would i change it back to a normal cursor in javascriptjquery,"['javascript', 'jquery', 'html']" +262126,android get device id for admob possible duplicatehow can i get device id for admob i am testing admob on my android device and following with documentation i am trying to get device id executing adrequest however i am not able to find device id in the logcat what i am doing wrong adrequest adrequest new adrequest adrequestaddtestdeviceadrequesttest emulator adrequestaddtestdevicetest edit it is not a duplicate those methods from other post are not working for me,"['java', 'android']" +262136,xcode 431 a valid provisioning profile for this executable was not found tonight i upgraded from snow leopard to lion and upgraded to xcode 431 ios 51 and now when i try and run debug mode on my device ipad i get a valid provisioning profile for this executable was not found i have tried every suggestion in past posts on this issue i have generated a new certificate i have set my code signing to use the new certificate i have updated the provisioning profile to use the new certificate i have gone into the pbxproj file and deleted all references to the provisioning profile i have cleaned and closed xcode a million times no matter what i do i still get the same error when trying to run on the devicein organizer the provisioning profile shows up as valid profile in my library but under the provisioning profiles listed for the device there are none listed i have tried clicking the add button and importing it manually nothing happens it does not show up when i click on the device icon in organizer is says provisioning no provisioning profiles however when i go to my ios provisioning portal online and click on the device the provisioning profile shows up there as being associated to the deviceany ideas i am pulling my hair out here,['iphone'] +262149,why is the following jquery selector not returning both elements i have run into a situation where i am creating a jquery object from an html string and need to select all elements within it with a particular classwhat i am finding odd is that its returning one or the other depending on which type of selecting mechanism i am using a test case is shown herevar tmpl ulli classfootestliuldiv classfoobardivconsolelog foo tmpl li classfootestliconsolelog tmplfindfoo li classfootestliconsolelog tmplfilterfoo div classfoobardivin this example both an li element in a ul and a nondescendant div have the class foo in the example i use the foo selector and set context to the template string second i use find on the string finally i use filter on the string can someone explain why the selector mechanisms are acting as they do and also how to achieve the goal i mentioned in the beginning,"['javascript', 'jquery']" +262178,destroying all delayed job in rails i am using collectiveidea for rails 238 i am creating array of delayed jobs to perform some tasks after some time i want to destroy all the delayed jobs which are running if anyone know the way to do this please help me,"['ruby-on-rails', 'ruby']" +262186,html 5 video streaming buffering only a certain portion of a longer video we have a long piece of video up to 1 hour long we want to show users small 30 second chunks of this videoit is imperative that the video does not stutter at any pointthe user cannot then jump around the rest of the video they only see the 30 second chunkan example would be say a football match the whole match is on video but clicking a button in another page would load up the full video and play just a goalis this possible with html5 video would it have anything to do with timerangesdoes the video have to served over a pure streaming protocol can we buffer the full 30 second chunk before playing itthe goal is to cut down on the workflow required to cut out all the little clips and the time transcoding these to all the different html 5 video formats we can just throw up a transcoded piece of footage and send the user to a section of that footageyour thoughts and input are most welcome thanks,['javascript'] +262198,java web application for 50 users for the first time hopefully not the last in my life i will be developing an application that will have to handle a high number of users around 50 and manage lots of data i have developed an application that manages lots of data around 100 gb of data not so much by many of your standards but the user count was pretty low around 50here is the list of tools frameworks i think i will be usingvaadin ui frameworkhibernatepostgresqlapache tomcatmemcached for session handlingthe application will mainly be run inside a company network it might be run on a cluster of servers or not depends on how much money the company wants to spend to make its life easierso what do you think of my choices and what should i take caution ofcheers,['java'] +262205,why is the compiler allowing this virtual function in a template class i know there are few threads about this topic but what really confused me is the result i got is different from what everyone is sayinglook this code below compiled using gcc441include iostreamusing namespace stdtemplateclass tclass a public at t at virtual a cout dtora endl virtual void print cout a a endl t aclass b public aint public bint t aintt b cout dtorb endl void print cout b endl int main b b2 aint a b aprint aint a2 new b4 a2print delete a2the result isb b dtorbdtoradtorbdtoraif virtual function is not allowed in template class why did i get this result,['c++'] +262222,android exit from full screen mode i am working in android i need to show my activity in full screen mode and i did this using following code getwindowsetflagswindowmanagerlayoutparamsflag fullscreen windowmanagerlayoutparamsflag fullscreennow its looking like thisnow i want to exit from this full mode so my activity should show as before like thisi have a button which is used to switch between full mode or normal mode i will switch mode again and again please suggest me how can i do this means how can get normal screen from full screenthank you in advance,['android'] +262225,java appropriate exception for initialization error which exception should i throw when a static factory method fails to initialize a new object i prefer raising a meaningful exception rather than returning null,['java'] +262243,android call phone permission is required in my app i want to make a one tap call without using the androidpermissioncall phone is it possible because of this permission user scare to install this appthanks,['android'] +262267,is there a way to redirect input from file to stdin in netbeans i am developing application with netbeans and maven my application should obtain data from stdin but i could not understand how to test it putting datatxt into args list does not worki need the same as java myprogram datatxt,['java'] +262305,chromefirefox how to run a javascript command i am using a gwt based ui design framework called gxt in the docs for this framework it is mentioned that running javascriptiscshowconsole when the app is running will open the developer console in browserhowever when i run this in chrome it instead does a google search for the command in firefox it simply does not workhow do i execute this javascript in firefox or chromejavascriptiscshowconsole,['javascript'] +262335,difference between shared objects so static libraries a and dlls so i have been involved in some debate with respect to libraries in linux and would like to confirm some thingsit is to my understanding please correct me if i am wrong and i will edit my post later that there are two ways of using libraries when building an applicationstatic libraries a files at link time a copy of the entire library is put into the final application so that the functions within the library are always available to the calling applicationshared objects so files at link time the object is just verified against its api via the corresponding header h file the library is not actually used until run time where it is neededthe obvious advantage of static libraries is that they allow the entire application to be selfcontained while the benefit of dynamic libraries is that the so file can be replaced ie in case it needs to be updated due to a security bug without requiring the base application to be recompiledi have heard some people make a thistinction between shared objects and dynamic linked libraries dlls even though they are both so files is there any thistinction between shared objects and dlls when it comes to cc development on linux or any other posix compliant os ie minix unix qnx etc i am told that one key difference so far is that shared objects are just used at run time while dlls must be opened first using the dlopen call within the applicationfinally i have also heard some developers mention shared archives which to my understanding are also static libraries themselves but are never used by an application directly instead other static libraries will link against the shared archives to pull some but not all functionsresources from the shared archive into the static library being builtthank you all in advance for your assistanceupdatein the context in which these terms were provided to me i have found out the slight differences in these terms which may even be just colloquialisms in my industryshared object a library that is automatically linked into a program when the program starts and exists as a standalone file the library is included in the linking list at compile time ie ldoptslmylib for a library file named mylibso the library must be present at compile time and when the application startsstatic library a library that is merged into the actual program itself at build time for a single larger application containing the application code and the library code that is automatically linked into a program when the program is built and the final binary containing both the main program and the library itself exists as a single standalone binary file the library is included in the linking list at compile time ie ldoptslmylib for a library file named myliba the library must be present at compile timedll essentially the same as a shared object but rather than being included in the linking list at compile time the library is loaded via dlopendlsym commands so that the library does not need to be present at build time for the program to compile also the library does not need to be present necessarily at application startup or compile time as it is only needed at the moment the dlopendlsym calls are madeshared archive essentially the same as a static library but is compiled with the exportshared and fpic flags the library is included in the linking list at compile time ie ldoptslmylibs for a library file named mylibsa the thistinction between the two is that this additional flag is required if a shared object or dll wants to statically link the shared archive into its own code and be able to make the functions in the shared object available to other programs rather than just using them internal to the dll this is useful in the case when someone provides you with a static library and you wish to repackage it as an so the library must be present at compile time,"['c++', 'c']" +262355,programmatically detect whether an ipad has retina thisplay how can i programmatically objectivec whether an ipad has a retina thisplay,"['objective-c', 'ios']" +262368,which svg support detection method is best somebody has already asked my question about detecting svg support in browsers but there are three leading solutions and not a lot of thiscussion about the merits of eachso which if any is best in terms of portability and correctness that is false negatives ie no svg are undesirable but acceptable false positives are notexhibit avar testimg dataimagesvgxmlbase64phn2zyb4bwxucz0iahr0cdovl3d3dy53my5vcmcvmjawmc9zdmciihdpzhropsiynzuiighlawdodd0imjc1ij48l3n2zz43dvar img documentcreateelementimgimgsetattributesrctestimgreturn imgcomplete exhibit breturn documentimplementationhasfeature 11exhibit creturn documentcreateelementns documentcreateelementns svg createsvgrect,['javascript'] +262391,lost messages over xmpp on device thisconnected i am trying to develop a turn base game over xmpp the only solution i found for multiplatform game i can send messages without problems if the other user is not online the server openfire save it for later deliverthe problem cames when a device change the network change from 3g to wifi change 3g ip or the device lost the network turn off 3g wifi or lost connection the server thinks that the device is online and send the message but it obviusly never arrive so packet is losti know one solution implement ack over my game protocol but i do not like this idea to much do you have any other suggestion i think this is a server problem do you know another server witch implements tcp or ackthank youedit i do that connect device to server i turn down the 3g and wifi connectivity to the device android and the server still thinking that the connection is alivepd i ask to openfeint for they multiplayer api but they did not asnwer me,['android'] +262392,can i use two languages in a heroku app i want to use nodejs as a sharejs server and ruby for the frontend as far as i know heroku only allows one webfacing process called web does anyone have some experience trying to do something like this,['ruby'] +262429,develop an android app to support english and arabic layout alignment i am developing an android app to support both enar but i faced a problem that if the user changes from en to ar the alignment of the user interface must turns from left to right to right to leftexample textviewedittext this is in en but in ar it should be edittexttextviewis there a way to do this without creating two different layouts or two different versions,['android'] +262458,implementing haskells maybe monad in c11 i am trying to implement the maybe monad from haskell using the lambda functions in c11 and templates heres what i have so farincludefunctionalincludeiostreamusing namespace stdtemplatetypename t1struct maybe t1 data bool validtemplatetypename t1 typename t2maybet2 operatormaybet1 t stdfunction maybet2 t1 f maybet2 return value iftvalid false return valuevalid false return return value else return ftdata int main maybeint x 5 true maybeint y 29 false auto z int a maybeint maybeint s sdata a1 svalid true return s maybeint p x z maybeint q y z coutpdata pvalidendl coutqdata qvalidendl when it comes to the actual call i am getting a compiler error saying that no match found for operator is my understanding of c11s lambda functions failing me here,['c++'] +262473,magento request frontend or backend how can i tell if the current request is for a backend or frontend page this check will be done inside an observer so i do have access to the request object if that helpsi considered checking magegetsingletonadminsessiongetuser but i do not think that is a very reliable method i am hoping for a better solution,['php'] +262524,remove all occurrences except last i want to remove all occurrences of substring in a string except the last oneeg1234should become1234,['javascript'] +262553,how do i convert a 64bit integer to a char array and back i am having trouble converting a int64 t to a char array and back i do not know what is wrong with the code below it makes complete logical sense to me the code works for a as shown but not the second number b which clearly falls into the range of int64 t include stdiohinclude stdinthvoid int64tocharchar mesg int64 t num forint i 0 i 8 i mesgi num 81i8int64 t charto64bitnumchar a int64 t and 0 and a0 56 0xff0u a1 48 0x00ff0u a2 40 0x0ff0u a3 32 0x0ff0u a4 24 0x0ff0u a5 16 0x0ff0u a6 8 0x0ff00u a7 0x0ffu return nint mainint argc char argv int64 t a 123456789 char astr new char8 int64tocharastr a int64 t anum charto64bitnumastr printfanum lldnanum int64 t b 51544720029426255 char bstr new char8 int64tocharbstr b int64 t bnum charto64bitnumbstr printfbnum lldnbnum return 0output isanum 123456789bnum 717215744221775the code also gives two warnings that i do not know how to get rid ofwarning integer constant is too large for aunsigned longa typewarning left shift count width of type,['c'] +262556,phps datetimediff gets it wrong datetimediff should calculate a proper interval and take into account daylight savings time dst and leap years although apparently it is not so code of horrord1 new datetime201030 010500 new datetimezoneeuropestockholmd2 new datetime201030 030500 new datetimezoneeuropestockholmecho d1getoffset 60 60prints 2 keep in mind thus that utc time 1h 2h 230500 the day beforeecho d2getoffset 60 60prints 1 dst happened utc time 3h 1h 020500di d1diffd2echo hours of dateinterval dihprints 2 wronghoursofdiff d2gettimestamp d1gettimestamp 60 60echo calculated difference in hours hoursofdiffprints 3 correctwhen the clock turned 030 at the given date all swedes turned their clock back one hour to 020 that means that total amount passed between 0105 until 0305 is three hours much like the manual calculation echoed when using the unix timestamp and much like we calculates on our fingers if we use an analogue clock even more so when we calculate the difference between the two utc timestamps i got using phps own logic of offsets is it php or have my brain ceased to work properly a reprimand from anyone of you all gods that exist on this site would make me so happyi am using php 54 vc9 on an apacheserver unfortunately i use windows 7 x64 as os i have tested my setup against all claims of bugs in phps datetime classes there are a couple related to windows and can confirm that my system have none of them except from the above stated code i have not found any other errors i pretty much validated all code and output the book php architects guide to date and time programming had to offer therefore i must conclude it has to be my brain witch has defaulted but i thought i would give it a shoot here first,['php'] +262580,what is the difference between int int16 int32 and int64 what is the difference between int systemint16 systemint32 and systemint64 other than their sizes,"['c#', '.net']" +262593,php constant inside js file i am facing a problem that i can not understand during a plugin development i am including a filejsphp registerenqueue filejsphpheadercontenttype applicationjavascriptpath constantwp plugin dir test with functionpath 2 wp plugin dir test directlycan cause a problem with older browsers use textjavascript begin tests var templatedir php echo wp plugin url var templatedir2 php echo path var templatedir3 php echo path 2 var templatedir4 php echo constantwp plugin url var templatedir5 php echo file var templatedir6 php echo plugins url somedirsomefilepng dirname file results var templatedir wp plugin url simply outputs a string of the constant namevar templatedir2 null or emptyvar templatedir3 wp plugin dir simply outputs a string of the constant namevar templatedir4 warning constant could not find constant wp plugin url in var templatedir5 pathtojsphp only one that works var templatedir6 call to undefined function plugins url in so my tests showed me that magic constants work but any wp constant will be unavailable that includes my own constants that were declared in the pluginphp actually this is the reason why i even began testing the wp constants interesting enough not only constants are unavailable but any wp function is returning unavailable php constant are meant to be available at all times through the appis that a wp specific problem is that intentional or am i doing something wrong note i know there are other ways to do it like using localize script to pass variables to js or just use a function to output the path in the header but first those methods will not be ideal for me and more importantly is the fact that i want to understand why this method is failing edit i althouh matt beckman pointed in the right direction his specific method did not workit is true that a file from wp must be included for me both the following work includewploadphprequire once dirnamedirnamedirnamedirnamedirname file wploadphpboth as you can imagine are equal but the problem remains those are somewhat hardcoded like salman a suggested what if the plugina s dir changes what is the solution in that case note that the both wploadphp and wpconfigphp worked for me i do not know what is better or which can present some security issues but i guess it is for another question bottom line this solution is only temp until i will find the right answer my plugin is loading via the wordpress plugin mechanisem enqueue script register script init etc and therefor i can not grasp why it does so bu for now it works like described above,"['php', 'javascript']" +262600,button image size in android i have put image as background of button but i do not know at what size of images should i create in photoshop for all three folders drawablehdpidrawableldpi and drawablemdpithank you,['android'] +262623,what makes reference comparison work for some strings in java i have following lines of codes to compare string str1 not equal to str2 which is understandable since it compares object reference but then why s1 is equal to s2 string s1 abcstring s2 abcstring str1 new stringabcstring str2 new stringabcif s1s2 systemoutprintlns1s2 else systemoutprintlns1s2if str1str2 systemoutprintlnstr1str2 else systemoutprintlnstr1str2if s1str1 systemoutprintlnstr1s1 else systemoutprintlnstr1s1output s1s2 str1str2 str1s1,['java'] +262630,position of dialogfragment in android i have a dialogfragment to show a view like a popup screenthe window appears always in the middle of the screenis there a way to set the position of the dialogfragment windowi have looked in to the source code but could not find anything yet,['android'] +262706,clearrect does not clear the canvas when drawing vertical lines i hit a weird edge case building something with canvas at work clearrect does not clear the canvas when drawing vertical lines that go from the top to the bottom of the canvas when rendering other stuff clearrect works finei am not sure if i am missing something obvious if this is intentional behavior or a browser bug unlikely since the behavior is identical in chrome safari firefox and opera on macif it is intentional behavior does anybody know the rationale behind it andor can perhaps point to some documentationi made a small test case that shows the behavior clearly only the combination clearrectvertical lines does not clear the canvasthanks,['javascript'] +262726,how pass reference to this on href javascript function i have a link with this hrefhrefjavascriptfoothiswhen i call it this points to the window object not the link how do i pass a reference to the linkedit note the question is how to pass with href not generally i know about onclickand not copying id and make getelementbyid that is not this it is dom search for certain element no need to make it inline in htmlthe anwer is not possible,['javascript'] +262734,net adays issue the next 2 lines adds the same amount to the same date and the results date part is the same but somehow the there is difference in the time partnew datetime20131800adays4535 new datetime20131800addmonths149youll get a difference of 15 secs and with both are at least roundable to days i do not know why this happend but it happens only with adays but not addmonths even with thousands of months addededit 1so i have tried to make a sample project but no luck if i run my main project and put the sample lines into the watches than i get 2 separate values if i make a fresh start the problem is not there the project is 35 c vs2010 win7hp x64 proj x86 i am trying to reproduce it also in a fresh small project i will be writing back if i have itthese are my results in the main project copeid from watchesnew datetime20 1 3 18 0 0adays4535ticks 63474343215360 longnew datetime20 1 3 18 0 0addmonths149ticks 6347434320 longedit 2i have managed to narrow it down even more we have a selfmade component panel base we draw on it with directx if i make that visiblefalse than visibletrue than the error comes before the visibletrue or show the calculation is correct what in the world can be there that the result gets something else of a formula where no variable is used culture is not affected in the component,"['c#', '.net']" +262744,using inject to join strings from an array i am going through an online lesson which usually has a very simple one line solution a problem states that given the following arrayemperor joshua abraham nortoni must use inject to get a single string of all names joined together with a string each name initial capped like thisemperor joshua abraham nortonwhile this could easily be done with map and join this particular exercise requires the use of inject only i came up with something like thisemperor joshua abraham nortoninject do memo word memo wordcapitalize endwhich would give meemperor joshua abraham norton where the whitespace at the end of the string does not pass as the correct solutionhow do i achieve this without the whitespace at the endis this even the right way to use inject passing an empty stringam i making correct use of the to combine strings,['ruby'] +262752,http 404 page not found in web api hosted in iis 75 i have a web api application it works perfectly well when i tested it using the vs 2010 debugging dev server but i now deployed it to iis 75 and i am getting a http 404 error when trying to access the applicationhere is my webconfigxml version10 encodingutf8configuration connectionstrings add namedefaultconnection connectionstringdata sourcesqlexpressinitial catalogaspnetflowgearproxy20123141219integrated securitytrue providernamesystemdatasqlclient connectionstrings appsettings add keywebpagesversion value20 add keywebpagesenabled valuetrue add keypreserveloginurl valuetrue add keyclientvalidationenabled valuetrue add keyunobtrusivejavascriptenabled valuetrue appsettings systemweb compilation debugtrue targetframework40 authentication modeforms forms loginurlaccountlogin timeout2880 authentication pages namespaces add namespacesystemwebhelpers add namespacesystemwebmvc add namespacesystemwebmvcajax add namespacesystemwebmvchtml add namespacesystemwebrouting add namespacesystemwebwebpages namespaces pages systemweb systemwebserver validation validateintegratedmodeconfigurationfalse modules runallmanagedmodulesforallrequeststrue systemwebserverconfiguration,['c#'] +262757,blurry uiview with catransform3d only on retina i am thisplaying a uiview with a uilabel on it and this viewlabel become blurry as soon as it gets to these lines codecatransform3d transform catransform3didentity transformm34 10500viewlayertransform transformthroughout the app i use ca3drotations and other stuff and this never happened beforealso i set the frame of the view and the label only using integers so it is not a halfpixel problem or something like that i know that that causes most blurry problems but not mineon the simulator it is not blurry ipad is not blurry iphone3gs is not blurry only on an iphone4 with retina thisplay it becomes blurry even before i do any 3d rotations does anybody have a clue before i go insane,['iphone'] +262787,is knockbackjs production ready i have used backbonejs i have learned about knockoutjs however now i found out about knockbackjs it is supposed to get the best out of the other two tried proven frameworksdo you have any experience with knockback in production i am wary to use it since it does not seem to be mature enough,['javascript'] +262815,jpa embeddedid with manytoone i have a problem with my code obviously and after many searches on internet i do not find an answer to my problem so i ask my question herei have this entitypublic class resident attributes embeddedid private idresident idresident embeddablepublic class idresident columnnamenom private string nom manytoone joincolumnnamecode private port port entitypublic class port attributes id columnnamecode private string code columnnamenom private string nom and i am using maven i have write this in my persistencexml classbeansportclassclassbeansresidentclass but when i run the program no matter what i have write i have this exception description the mapping port from the embedded id class class beansidresident is an invalid mapping for this class an embeddable class that is used with an embedded id specification attribute idresident from the source class beansresident can only contain basic mappings either remove the non basic mapping or change the embedded id specification on the source to be embeddedi do not see where is my mistake i think it is because of the idresident class wich has an entity object in it but i do not know how to fiw it,['java'] +262816,most efficient way to draw particles in html5 on ipad 2 i am trying to create moving lights with trails for an html5 websiteapp targeted at ipad 2i wonder what the best way to do this is and whether using html5 is viable at all i chose html5 because it is easier and cheaper to develop and deploy than native ios apps with objective c of course if it turns out that html5 simply does not offer enough performance i might have to swallow the bitter pillanyway to give you an impression what i am talking about this is what i got so faror you can see it in action here only works in webkit based browsersat first i tried using html5 canvas and drawing radial gradients as particles in similar manner you see above it worked but the framerate was horrible even on my desktop computerso after a bit of reading i found out that css3 transforms may be hardware accelerated so i build the version you see above every particle is a 64x64 png image for each light there is the head light one img followed by a trail consisting of 115 img elements each img element is transformed using translate3d as well as scale and rotation also the opacity of each element is adjusted dynamically doing it this way provided much better framerates on my computer but i doubt the ipad 2 will handle iti would be grateful if anyone could give me some hints on how to improve the performance of this in general and considering the target platformthanks for any help in advance,['javascript'] +262832,check glibc version for a particular gcc compiler i have two gcc compilers installed on my system one is gcc 412 default and the other is gcc 4 how can i check the libc version used by gcc 4 because liblibcso6 shows the glibc used by gcc 412 since it is the default compiler,['c'] +262841,avaudiorecorder record method returns no at random times iam currently developing an app which supports inapp audio recording the user can get a standard tableview of locally saved audio files heshe have already recorded through the app or press a button to go to a new recording view from where it is possible to record a new audio session which will automatically get saved to the apps sandboxnow this function works well most of the time i can record new files and play them from the app but at random times the audio recorder will fail to start a recording in this methodvoid startrecordingif isrecording isrecording yes bool recordingsucess audiorecorder record if recordingsucess nslogwe started the recording else nslogwe did not start the recording start the timer recordtiming nsdate date timecheck nstimer scheduledtimerwithtimeinterval10f targetself selectorselectortimecheck userinfonil repeatsyesthat is the nslog will print out awe did not start the recordinga indicating that it failed to start the recording this results in an empty audio file still being saved to the app with a constant file size of exactly 4096 bytesthis is how the audio recorder object is initializedid initwithcontenturlnsurl contenturlself super initif self nsloginitializing audio recorder specific settings for the audio recording nsdictionary recordsettings nsdictionary dictionarywithobjectsandkeys nsnumber numberwithintavaudioqualitymin avencoderaudioqualitykey nsnumber numberwithint8 avencoderbitratekey nsnumber numberwithint 2 avnumberofchannelskey nsnumber numberwithfloat220 avsampleratekey nil nserror error nil audiorecorder avaudiorecorder alloc initwithurlcontenturl settingsrecordsettings errorerror audiorecorderdelegate selfthere is also nslog checks which checks to see if the error is nil or not so at this point iam sure that the initialization does not seem to failwhat exactly could cause the record method to fail at seemingly random times while it works perfectly good at most other times,"['iphone', 'objective-c', 'ios']" +262848,getting started with backbonejs what should a server return i am totally new to backbonejs library and read through the whole documentation and understood the working of the library in the below cases what should the response from the server be for proper working of application designed using backbone without putting a extra strokecodeassume a model like belowwindowperson backbonemodelextend defaults name email urlroot personappwhat json should server return assuming validation went well for modelsavewhat json should server return for modelfetchwhat json should server return for modeldestroy,['javascript'] +262856,how to implement uniqueness where the order of the fields does not matter i think the following example will explain the situation bestlet us say we have the following table structuremember1 int not null fkpkmember2 int not null fkpkstatust char1 not nullhere are the table contents for the tablemember1 member2 status 100 105 amy question is how do i implement uniqueness so that the following insert statement will fail based on that one row already in the tableinsert status table member1member2status values105100dbasically i am trying to model a relationship between two members the status field is the same whether we have 100105 or 105100 i know i could use a before insert and before update trigger to check the contents in the table but i was wondering if there was a better way to do it should my database model be different,['sql'] +262868,i18n in rails 3 with a admin namespace i am developing an rails app on the advice of the rails guides to create the folder tree and files with the translationsmy folder tree is similar to thisdefaultsesrbenrbmodelsbookesrbenrbviewsdefaultsesrbenrbbooksesrbenrbusersesrbenrbnavigationesrbenrbthe content in configlocalesviewsbooksenyml is similar to thises books index title tatuloa in inside appviewsbooksindexhtmlerb template like this note the dot t title when i have no namespace my translations in views work well but with the namespace admin that i use in my backend it does not work anyone know what is the problem,"['ruby-on-rails', 'ruby']" +262891,python functions and their call attribute i am using python 272 i want to understand the relationship between calling a function and calling the call attribute of the function for example consider the following codedef foo return 5print foo 5print foo call 5foo call lambda 6print foo 5print foo call 6the firsts four lines seem to indicate the calling the function foo is the same as calling the call attribute of foo however the last three lines seem to indicate that they are different beasts since i changed the call attribute but it did not change the value returned by a call to foocan someone explain the relationship between calling foo and calling foo call is there a way to modify the behavior of the function so that foo as well as foo call now returns 6 instead of 5,['python'] +262911,android bottom white stripe when filling webview content once an html is loaded in to a webview i get a white stripe on the right and bottom of the layout for the right one i solved it usingsetscrollbarstylewebviewscrollbars inside overlayhowever i have tried many options to remove the bottom one with no success even after i read all the related posts if more code is required please let me knowxmllinearlayout xmlnsandroidandroidlayout widthfill parent androidlayout heightfill parentwebview androidautolinkweb androidlayout widthfill parent androidlayout heightfill parent androidididwebview1 androidtextcolorandroidcolorblack webviewlinearlayoutactivitybrowse webview findviewbyidridwebview1browsegetsettingssetjavascriptenabledtruebrowsegetsettingssetusewideviewporttruebrowsegetsettingssetloadwithoverviewmodetruebrowsesetscrollbarstylewebviewscrollbars inside overlaybrowsesetscrollbarfadingenabledfalse,"['java', 'android']" +262961,algorithm or software for slicing a mesh what is the right approach for slicing a 3d mesh the mesh are all closed surfaces and the slices need to be binary images of whats inside the mesh so for example a mesh representing a sphere and slice images are those of filled circles i am looking for a software library or algorithm that i can integrate into my current c project,['c++'] +262967,connect to user model in django quick probably foolish question this is the flow of my site user logs in and is redirected to a custom admin page on this admin page they have the ability to make a profile i want to associate the profile they create with their user data such that 1 user associates to 1 profile for some reason the following is not working simply trying to associate useradminmodelsfrom djangodb import modelsfrom djangocontribauthmodels import userclass profilemodelsmodel username modelsforeignkeyuser firstname modelscharfieldmax length200 lastname modelscharfieldmax length200 email modelsemailfieldmax length200 def unicode self return selfusernameuseradminviewsdef createprofilerequest user userobjectsgetid1 profile profileusernameuser firstnamejoe lastnamesoe email profilesavei keep getting table useradmin profile has no column named username idany ideas appreciatededitdeleted my db and ran a fresh syncdb changed to username modelsonetoonefielduser now i cam getting cannot assign usuperuser profileusername must be a user instance,['python'] +262992,jquery load scripts in order i am trying load some scripts dynamically with jqueryvar scripts script1jsscript2jsscript3jseachscripts functioni val getscriptval function consolelogloaded valbut sometimes the order of loaded scripts changes how can i load each script after the previous one has successfully loaded,['jquery'] +263015,removing markdown formatting for quick excerpt anyone know of a script or already built function that will help me create a quick excerpt using already existing markdown formatted contenti am looking at formatting results like stackoverflow where i have the title and a short excerpt for basically news view i want to remove the markdown fully and just preserve the few wordsmy concern is that i am going to use a codeigniter helper word limiterto limit the output which may create broken markdownthis is a sentence which has some markdown that is cutoffso i am not sure how to go about itall my content is stored with markdown not html formatting otherwise i would do striptags etci have found something similar for ruby on so here truncate markdown but i would love something for phpi am just not sure if i should just strip all characters basically but if there is a url split in half i am worried it will look nastythoughts i have looked around a bit but at first glance have not found anything that strips markdown,['php'] +263039,what does todo auto generated method stub mean i see it all the time and cannot find a simple description,['java'] +263044,how do you read this ternary condition in ruby i came across a ternary in some code and i am having trouble understanding the conditionalstrsplitsmap do match match0 match some stringendjoini do understand that i am splitting a string at certain points and converting the total result to an array and dealing with each element of the array in turn beyond that i have no idea whats going on,['ruby'] +263057,why are not cs mathminmax variadic i need to find the minimum between 3 values and i ended up doing something like thismathminmathminval1 val2 val3it just seems a little silly to me because other languages use variadic functions for this i highly doubt this was an oversight thoughis there any reason why a simple minmax function shoundnt be variadic are there performance implications is there a variadic version that i did not notice,['c#'] +263108,finding and autofilling html login forms in a uiwebview using javascript i have a uiwebview which acts like an internet browser and loads the html of the webpages that it is atin the webviewcontroller the method webviewdidfinishload would have loaded the html from the webpage when the webpage finish loading on the uiwebviewfrom the html i would like to sieve out textfields to facilitate the auto population of that textfield with values stored in my databaseany methods to do that the method should be able to work on all websitesset text for a textfield in uiwebview has almost what might help me but i have tried it and the text field never got filledin a login page there will be two text fieldsso i tried using documentgetelementsbytagnameinput0valuedocumentgetelementsbytagnameinput1value to input in the values but no magicediti have tried other position in the array the username and password for facebook is 3 and4 whereas for amazon it is 11 and 14so the position of where the fields are using the above method is kinda random any other suggestion that will work for all websiteedit2i could try documentgetelementsbyidid namevaluebut the id method is not going to work for me as i need a universal method that will identify textfields on any websitesall websites uses different id namesalso it seems to me that some of the websites have consistently set this tabindex1 for username and tabindex2 for password for instance in the webpage like facebook input typetext classinputtext nameemail idemail value tabindex1 input typepassword classinputtext namepass idpass tabindex2 amazon input idap email nameemail value typeemail size30 maxlength128 tabindex1 autocorrectoff autocapitalizeoff input idap password namepassword typepassword maxlength1024 size20 tabindex2 onkeypressthisplaycapswarningeventap caps warning this classpassword dbs bankinput typetext tabindex1 maxlength20 size32 nameuid iduidinput typepassword onkeyupkeyupevent onkeydownreturn onlynumericsevent tabindex2 maxlength9 size32 namepin idpin autocompleteoffbut i did not see this tabindex in google input typetext spellcheckfalse nameemail idemail valueinput typepassword namepasswd idpasswdany suggestionthe ultimate goal is to be able to sieve out username and password text field for allany websites,"['javascript', 'html', 'ios']" +263128,mysql create table as select everytime i use mysqls create table as select all the tablesindexes being selected from are locked for the duration of the query i do not really understand why is there any way around thisusing mysql 5141 and innodbadded examplefor example the following query might take up to 10 minutes to completecreate table temp lots of data x as select a b cfrom aleft join b on afoo bfooleft join c on afoo cfootrying to update values in tables a b or c during the above query will wait for the above query to finish first i want to avoid this lock as i am not interested in the most complete data in the created temp tableps set transaction isolation level read uncommitted yields no change in behavior,['mysql'] +263156,azure programmatically querying wadlogstable for trace data i am trying to use the following code to get all trace data for the last hour from azure storagecredentialsaccountandkey storagecredentialsaccountandkey new storagecredentialsaccountandkeyaccountname key cloudstorageaccount csa new cloudstorageaccountstoragecredentialsaccountandkey true tableservicecontext tableservicecontext new tableservicecontextcsatableendpointtostring csacredentials var results tableservicecontextcreatequerytableserviceentitywadlogstablewhere x xtimestamp datetimeutcnowaddhours1tolisthowever i am finding that no results are found when i know that there is data in the table for the last hour i am comparing the output to cerebratas azure diagnostics manageri have two questionsis this the right way to query wadlogstable why am i not seeing anyresultswhat is the correct type to pass in as the genericparameter tableserviceentity is a base class that only definesthree columns i would like to know if there is a type that represents awadlogstable entity specifically do i just create a type withproperties the same as the column names,['c#'] +263193,threejs insert image i am trying to attach a simple image on a planegeometry mesh but it does not seem to workwindowonload function var renderer new threewebglrenderer renderersetsizewindowinnerwidth windowinnerheight documentbodyappendchildrendererdomelement camera var camera new threeperspectivecamera95 windowinnerwidth windowinnerheight 1 10 camerapositiony 250 camerapositionz 400 camerarotationx 45 mathpi 180 scene var scene new threescene var img new threemeshlambertmaterial mapthreeimageutilsloadtextureimgfrontjpg plane var plane new threemeshnew threeplanegeometry200 200img planeoverdraw true sceneaddplane add subtle ambient lighting var ambientlight new threeambientlight0x5 sceneaddambientlight add directional light source var directionallight new threedirectionallight0xf directionallightpositionset1 1 1normalize sceneadirectionallight create wrapper object that contains threejs objects var three renderer renderer camera camera scene scene plane plane rendererrenderscenecamera this is my full javascript file with a canvas of 580x300i only see a black square whenever i run it any ideas thankshere is my reference for those who need it,"['javascript', 'jquery']" +263206,when blocks are more useful than functions ruby i have two examples that give the same resultwith blockdef selfdo somethingobject id selfwith paramsobject id do params some stuffparams endenddef selfwith paramsobject id block find object by id calculate params hash blockcallparams hashendand with methoddef selfdo somethingobject id some stuffselfget paramsobject idenddef selfget paramsobject id find object by id calculate params hash params hashendthe second solution seems more straightforward but i found some usages of the first one in our application code my question is in which situation the first one is recommended what are the pros and cons of each one,"['ruby-on-rails', 'ruby']" +263221,do i have to do stringioclose some codeimport cstringiodef f buffer cstringiostringio bufferwritesomething return buffergetvaluethe documentation saysstringioclose free the memory buffer attempting to do further operations with a closed stringio object will raise a valueerrordo i have to do bufferclose or it will happen automatically when buffer goes out of scope and is garbage collectedupdatei did a testimport stringio weakrefdef handlerref print buffer dieddef f buffer stringiostringio ref weakrefrefbuffer handler bufferwritesomething return buffergetvalueprint before ffprint after fresultvicwicprojects python testpy before fbuffer diedafter fvicwicprojects,['python'] +263236,generate random password string with requirements in javascript i want to generate a random string that has to have 5 letters from az and 3 numbers how can i do this with javascripti have got the following script but it does not meet my requirements var chars 0123456789abcdefghijklmnopqrstuvwxtzabcdefghiklmnopqrstuvwxyz var string length 8 var randomstring for var i0 istring length i var rnum mathfloormathrandom charslength randomstring charssubstringrnumrnum1,['javascript'] +263265,java local timeformat without year i like to format the local timeformat into a string without the year at the moment i am able to show the local format containing the year javatextdateformat df javatextdateformatgetdateinstancejavatextdateformatshortstring datestring dfformatdatetherefore i receive an time string output like 1203201203122012for the different countries now i like to get a short form like 12030312how would i do thisthanks for your help,['java'] +263267,referencing a calculated column in the where clause sql this line of code is a snippet from my select statementfrdfreedays datediffddconreceipttostockgetdate as freedaysremainingbelow is a snippet from my where clauseand frdfreedays datediffddconreceipttostockgetdate intfreedaysthe question i have is how can i reference the freedaysremaining column and so i can compare it to intfreedaysi am looking for something like thisfreedays intfreedays,['sql'] +263279,what are the uses of main default and launcher in manifest file in android activity androidnameapidemos intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorydefault category androidnameandroidintentcategorylauncher intentfilter activitycan any one explain about main default and launcher what are the use of those properties in manifest for activity if used more than 1 activity in my project,['android'] +263297,attach debugger to ios app after launch i have an issue i am troubleshooting which occurs very infrequently and does not seem to happen when i have things running under xcode is it possible to run an app normally ie from springboard until my issue occurs and then attach a debugger at that pointi would prefer to do this without jailbreaking if possible,['ios'] +263340,why does malloc0 return a nonnull address in windows the code below returns an address when executed in windows though i was expecting it to return nullint main char ptr null ptr malloc0 printfmalloc returned un ptrwhat could have prompted such an implementation of malloc is there any reason behind it since this is a 0 byte memory i did not experiment writing any data but can this memory be used for anything at all,['c'] +263345,httpclient times out when changing from 3g to wifi i perform some large downloads i start a download being connected to 3g all is fine then i switch to wifi connection but the request returns a timeout exception i have used httpclient library i have implemented a retry mechanism so when the request returns an exception it sleeps for 05 seconds and tries to execute again and again i would expect that after connecting to a wifi the http request could execute but it seems that the http execute method returns a null response all the time after that very strange if i commute again to 3g the execute method returns again a good response can anyone help me please,['android'] +263386,how to capture onclick event in thisabled edittext in android app i have a edittext which i am presenting as thisabled so that user cannot edit the contents and also to avoid poppingup keyboard but now i want to capture onclick event in the edittext and identify the individual words that are being clickedany help is most welcomethanksbalkrishna,['android'] +263388,prevent copypaste and rightclick meant for textbox email address i would like to prevent a user from eithercopy and pasting from the first textbox to the secondrightclick and use the context menu to copy and paste from the first textbox to the secondthis is not workinghtml head runatserver titleconfirm email pagetitle script typetextjavascript languagejavascript function thisablerightclickevent for mouse right click if eventbutton 2 function thisablectrlkeye var code documentall eventkeycode ewhich look for ctrl key press if parseintcode 17 windoweventreturnvalue false script head body stylefontfamily verdana fontsize 1em form idform1 runatserver div h1confirm emailh1 asplabel idlabel2 runatserver textenter email address asplabel asptextbox idtextbox2 runatserver oncopyreturn false onmousedownthisablerightclickevent asptextboxbr asplabel idlabel3 runatserver textconfirm email address asplabel asptextbox idtextbox3 runatserver onkeydownreturn thisablectrlkeyeventasptextboxbr div form bodyhtmlgot it workingdivh1copy paste preventerh1 asplabel idlabel1 runatserver textenter username asplabel asptextbox idtextbox1 runatserverasptextboxbr asplabel idlabel2 runatserver textenter email address asplabel asptextbox idemail runatserver oncopyreturn false onpastereturn false oncutreturn false oncontextmenuforms0elements0value return falseasptextboxbr asplabel idlabel3 runatserver textconfirm email address asplabel asptextbox idtextbox3 runatserver oncopyreturn false onpastereturn false oncutreturn false oncontextmenuforms0elements0value return false asptextboxbr div,"['c#', 'asp.net']" +263446,how to make a list of tsql results with commas between them suppose we have a simple query like thisselect x from twhere ty zif we have one record in the result set i want to set variable v to that one value if we have two or more records i would like the results to be separated by a comma and a space what is the best way to write this tsql codeexampleresult set of 1 recordvalue1result set of 2 recordsvalue1 value2result set of 3 recordsvalue1 value2 value3,['sql'] +263447,submit form values using controller and model in magento admin module i am building an admin module and need to process a form but am having troubles getting the variables to post and am just redirected to the dashboard the form looks like this form namenotes actionphp echo magehelperadminhtmlgeturlfooindexprocessnotes methodpostinput typehidden nameanother form key value echo thisgetformkey i am doing it that way because the secure keys are turned on for admin it gives me a url like fooindexprocessnoteskey4745f5fbb9c168778958d5d4a4c2c0efin the controller i have public function processnotesaction model magegetmodelfooprocess i am not sure how i am supposed to send post values here and in packagefoomodelprocessphpi would hope to be able to process the post variables from my form in here but i can not see what is wrong and i am just sent to dashboardphpclass package foo model process extends mage core model abstract public function noteprocess test postmyvalue echo test updateafter reading the answers i wanted to add a bit more of what my real code is doing and how i am using post i was setting up a simple example to just get the form to post but realizing there are probably many things i am doing wrong in magento queryinsert into notes value color the id the value values sku postcolorarray pop postforeach post as key value values sku id value query implode values the dream is i could resourcegetconnectioncore write to actually insert this into the database but feeling less optimistic with how it is going so far,['php'] +263459,how to preserve newlines when showing a text file with jquery i want to fetch the content of an text file and i have manage to do that everything is working except for one thing detecting new linesmy solution to fetch the content in the text fileajax url nhagyavifilestextfileschangelogtxt success functiondata loadchangeloghtmldiv stylefontfamily courier new data div the content of the text file20120315 snabbfixar detta ar en fin liten rad som berattar vad som ar nytt en till rad tillsammans med en a hrefjavascriptvoid0lankahow the result looks like on my page20120315 snabbfixar detta ar en fin liten rad som berattar vad som ar nytt en till rad tillsammans med en lanki do not know how i can use print r in jquery so i cannot really see how the lines really looks like anyone who knows how i can fix my problem,"['jquery', 'css']" +263472,java and eclipse 32 vs 64bit i am a little bit confused about the two different versions of eclipse 3264bitas far as i know java bytecode build of your code is platform independend if a user runs your bytecode in a 32bit jre the code is executed in as a 32bit process if a user runs your bytecode in a 64bit jre the code is exectued as a 64bit process eclipse needs the jre to run cause it is written in java but why are there 32 and 64bit versions of eclipse on the eclipse download page if only the users jre version does matterdoes a 64bit eclipse version need a 64bit jre or jdk if yes whysecond confusion i understand the need for a 32 and 64 bit version of the jre but why are there 32 and 64 bit versions of the jdk if the resulting bytecode is platform independetthank you,['java'] +263478,what codecs does xuggler support yes i know that the faq pretends to answer this but it does not really instead it instructs you to build the project from source and the build instructions are quite convoluted that kind of defeats the entire point let us save everyone in the world the hassle of having to build yet another opensource project in order to find out whether it actually solves their problem what codecs does xuggler support,['java'] +263487,how to create options of a select element dynamically using jquery i need to create options of a select element dynamically via an ajax call the number of options and their content will vary this is how it looks prior to the ajax call select namegroupid stylewidth100option value0 selectedplease select an optionoptionselecthere is one of my attempts to create an option element with a dummy valueoptionoption value 9appendtoselectgroupbut it adds it outside of select i also do not know how to set the text within any ideas i have seen some questions about populating existing select forms with a static number of existing options but not one like this thanks,['jquery'] +263496,where to build new domain entities controller repository or mapper let us say for each domain entity i have a repository that provides an api to a data mapper for example if i have a userentity then i would have a userrepository that speaks to a usermapper to persist user data in a databasenow let us say a form is submitted on a web page and my controller knows it needs to create a new userentity based on the submitted infodoes itdo new userentity right there on the spot and run all the necessary setter methods according to the form data submitted then pass the userentity to the repo who passes to the mapper for insertioncontroller creates userentity repo mapper dbturn the form data into an array and pass it to the userrepository who then runs new userentity and the setters and passes it to the mapper for insertioncontroller passes user data repo creates userentity mapper dbpass the array to the userrepository who passes the array to the mapper for new userentity and insertioncontroller passes user data repo passes user data mapper creates userentity dbwhose responsibility is it to manage the creation of objects,['php'] +263516,setting thisplay errors0 and log errors1 without phpini for reasons outside my control i am unable to set thisplay errors0 and log errors1 in phpini on my production server i know i can set error reporting0 to completely suppress all error messages but this impacts both the log errors and the thisplayed errors i was hoping there would be an equivalent to setting thisplay errors0 and log errors1 at runtime is this possible thanks,['php'] +263525,function evaluation timed out when examining variables in debugstepping through when debuggingstepping through code and i try to examine a variable in the watch i get errors for every innervariable stating function evaluation timed outdoes anyone know why this is and how to avoid it as it impacts my ability to debug codethis is within vs2010 premium,"['c#', '.net']" +263527,how to use unordered set with custom types is it required that i create my own hash function for custom types is there no defaults i can use with unordered set,['c++'] +263561,reason for calling setenabledfalse in jpanel i am working on swing for a while now but never had a situation in practice when i had to call setenabledfalse in jpanel still i see such code sometimes in some sophisticated gui but i really do not undarstand why someone wants to use itso please give me some examples of real life common situations when you need to use setenabledfalse on jpanelalso in javadoc it says thisabling a component does not thisable its childrenactually i had a bug because table inside thisabled jpanel did not show mouse resize cursor when resizing columns i suspect there are other unpleasant surprises here,['java'] +263565,performance of stringindexof ordinalignorecase vs currentcultureignorecase possible duplicatestring comparison in dotnet framework 4 i noticed a performance problem on my machine in a ui app that is doing lots of string comparisons to do filtering of large lists i tracked the issue down to using ordinalignorecase in a call to stringindexof the following benchmarks were run in release without the debugger attached it is a 40 project built in vs 2010 windows 7 i do have the 45 beta installed on this machine i am not sure if that would affect this1190 seconds for ordinalignorecase0178 seconds for currentcultureignorecase0175 seconds for invariantcultureignorecase0101 seconds for ordinal0132 seconds for currentculture0126 seconds for invariantculture1176 seconds for ordinalignorecase0189 seconds for currentcultureignorecase0183 seconds for invariantcultureignorecase0104 seconds for ordinal0138 seconds for currentculture0127 seconds for invariantcultureas you can see ordinalignorecase is over 65x slower but without ignorecase ordinal is the fastest in multiple places microsoft recommends ordinalignorecase for the best performance can anyone replicate these results or explain why ordinalignorecase is going so much slower in this testprivate static void teststring search string key stringcomparison comparison int trials var sw stopwatchstartnew for int i 0 i trials i searchindexofkey comparison consolewriteline0 seconds for 1 swelapsedmilliseconds 10 comparisonstatic void mainstring args int trials 10 var search guidnewguidtostringn var key 34 testsearch key stringcomparisonordinalignorecase trials testsearch key stringcomparisoncurrentcultureignorecase trials testsearch key stringcomparisoninvariantcultureignorecase trials testsearch key stringcomparisonordinal trials testsearch key stringcomparisoncurrentculture trials testsearch key stringcomparisoninvariantculture trials testsearch key stringcomparisonordinalignorecase trials testsearch key stringcomparisoncurrentcultureignorecase trials testsearch key stringcomparisoninvariantcultureignorecase trials testsearch key stringcomparisonordinal trials testsearch key stringcomparisoncurrentculture trials testsearch key stringcomparisoninvariantculture trials,['c#'] +263572,setting http cache control headers in wcf service i am working on an http rest service implemented on wcf i would like to set the http cache control headers for my operations appropriately i have seen a few examples that involve using the weboperationcontextcurrentoutgoingresponse to modify the headers in each method but let us be honest that is a pain in the butt especially since nearly all of my operations are going to use the same cache control policy nocachei am thinking there must be an elegant way to set this perhaps a combination of a servicebehavior to set a servicelevel default and operationbehaviors to override that for certain operations or maybe there is some better way to do this,['asp.net'] +263621,positioning an images outside of the layout i am making a website thats 960px wide but i want images on both sides of the header that you can see if you have a bigger screenbecause i want to keep the site 960px wide i need these extra side images to not be counted by the browser i can get it to work on the leftsee here leftworkshtmlcodedoctype html public w3cdtd xhtml 10 transitionalen html xmlnsheadmeta httpequivcontenttype contenttexthtml charsetutf8 titleuntitled documenttitlestyle typetextcssbody margin 0 padding 0 border 0 backgroundcolor096 img border 0 main width960px height216px backgroundimageurlmainjpg positionrelative top0 margin 0 autoleft width170px height216px backgroundimageurlleftjpg floatleft left170px positionrelativeright width170px height216px backgroundimageurlrightjpg floatright left170px positionrelativestyleheadbody div idmain div idleftdiv div idrightdiv divbodyhtmlif you make your window thinner the left red image thisappears off the site without causing the browser window to get a bottom scroll bar however when i try and do the same thing to the right side it does not worksee herecode is equal only div idrightdiv is missingthe css is in the sourceyou can also see it being used on this site to show the date sticking out the left of the page without impacting the overall sites widthwhy does this work on the left but not the right,"['css', 'html']" +263628,has anyone gotten html emails working with twitter bootstrap i am using the premailerrails3 gem which pulls styles inline for html emails and i am trying to get it working with twitter bootstrapit looks like some styles come in correctly but not all of them i am wondering if anyone has a nice working example of getting their twitter bootstrap css modified or not into an html emailthanks,['html'] +263655,how to access the current rails object id in javascript if i am on a view how can i access the id of the ruby object that is currently represented by that vieweg if i am on blahcomjobs1 how do i get 1i thought about trimming the current url but that seems way too brittle especially given i have nested resources the only other easy way i can think of is to have a hidden field but it seems silly to have a hidden input on a show page where there are not any forms,"['javascript', 'ruby-on-rails', 'ruby']" +263705,can a mysql trigger simulate a check constraint i want to use the check constraint in mysql but it is not supported unlike other rdbms it will understand but not enforce the checksi have seen some workarounds with triggers but they tend to set a default value to the field in question instead of returning an erroris it possible to construct a trigger that returns an error if a condition is not metultimately i want a trigger that copies a check constraint,['mysql'] +263718,can we use developer provisioning profile to upload ipa to testflight i wanted to know that with the provisioning profile of the of iphone developer i was able to generate the ipa for uploading to testflightapp but it gives me an error in the testflight that it is invalid ipa is that because of the fact the i am using the developer profile and not thistribution profile,"['iphone', 'ios']" +263749,findall in yii emailarchive tableid email id to from1 101 uk msm2 102 uu avc3 101 rk uk4 103 xyz abc5 104 xyz poi6 104 abc xyz7 101 xyz abcnow in yii i want record where email id101i am using below code but its not workingid 101criteria new cdbcriteriacriteriaaddconditionemail id email idcomments emailarchivemodelfindallcriteria arrayemail id id,['php'] +263763,how to create a countup effect for a textview in android i am working on an app that counts the number of questions marks in a few paragraphs of textafter the scanning is done which takes no time at all i would love to have the total presented after the number goes from 0 to total so for 10 0123456789 10 and then stopi have tried a couple of different techniques textview sentscore textview findviewbyidridsentscore long freezetime systemclockuptimemillis for int i 0 i sent i if systemclockuptimemillis freezetime 500 sentscoresettextsenttostring also i tried this for int i 0 i sent i try threadsleep500 catch interruptedexception ie sentscoresettextitostring i am sure these are both completely amateur attempts any help would be muchappreciatedthanksrichard,"['java', 'android']" +263817,char encoding if i write the statement below in c under visual studio what will be encoding hereconst char c aunder the visual studio project settings i have set the charset to not set,['c++'] +263818,best practice to choose fields for equals implementation when writing unittests i often face the situation when equals for some object in tests in assertequals should work differently from how it works in actual environment take for example some interface reportconfig it has id and several other fields logically one config equals to another one when their ids match but when it comes to testing some specific implementation say xmlreportconfig obviously i want to match all fields one solution is not to use equals in tests and just iterate over the object properties or fields and compare them but it does not seem like a good solutionso apart from this specific type of situations i want to sort out what are best practices to implement equals semantically not technically,['java'] +263819,how to redirect to external url from c controller i am using a c controller as webservicein it i want to redirect the user to an external urlhow do i do ittriedsystemwebhttpcontextcurrentresponseredirectbut it did not work,['c#'] +263831,weird error nsassert i cannot figure out why i get use of undeclared identifier cmd did you mean rcmdon the line where nsassert isimport foundationfoundationhint main int argc const char argv nsautoreleasepool pool nsautoreleasepool alloc init int x 10 nsassertx 11 x should be greater than d x pool drain return 0,['objective-c'] +263835,getting notified when user presses search on keyboard in uisearchthisplaycontroller i am using a uisearchthisplaycontroller to let the user search through a list of buildings on a university campus sometimes the user will know exactly what building they want enter the buildings number and that building will then be the only building result showing in the uitableview at the moment if the user proceeds to hit search on the keyboard the keyboard animates off the screen and the user then has to make a second tap on the sole item in the uitableview to be sent to a point on a map showing the location of that building my question is is there a way to be notified when the user hits the search button on the keyboard inside a uisearchthisplaycontroller so that i can perform a check to see if there is only one result and if so take the user straight to that result rather than requiring them to explicitly make the second tap i have looked at the methods provided by the uisearchthisplaydelegate but cannot see anything relevant,['ios'] +263849,php array copy certain keys builtin functions nested loop performance i have a php array that i would like to duplicate but only copy elements from the array whose keys appear in another arrayhere are my arraysdata123 adata423 bdata543 cdata231 data642 edata643 fdata712 gdata7 hkeys to copy 123keys to copy 231keys to copy 643keys to copy 712keys to copy 7copied data123 acopied data231 dcopied data643 fcopied data712 gcopied data7 hi could just loop through the data array like thisforeach data as key value if in arraykey keys to copy copied datakey value but this will be happening inside a loop which is retrieving data from a mysql result set so it would be a loop nested within a mysql data loop i normally try and avoid nested loops unless there is no way of using phps builtin array functions to get the result i am looking forbut i am also weary of having a nested loop within a mysql data loop i do not want to keep mysql hanging aroundi am probably worrying about nested loop performance unnecessarily as i will never be doing this for more than a couple of hundred rows of data and maybe 10 keysbut i would like to know if there is a way of doing this with builtin php functionsi had a look at array intesect key but that does not quite do it because my keys to copy array has my desired keys as array values rather than keysanyone got any ideascheers b,['php'] +263858,mailto link in chrome is triggering windowonbeforeunload can i prevent this possibly related to how to open mailto link in chrome with windowopen without creating a new tabhi all i have a form page where i have put a windowonbeforeunload confirm to stop people navigating away and losing their changes by accidentwindowonbeforeunload function ifchanged return you have unsaved changes do you really want to leave this page without saving where changed is a variable i set to true whenever the user makes any changes that is all fine however i have also added some mailto links to the page like soa classbutton buttonalt hrefmailtoreport a problemaeven though the mailto is not navigating away from the page it is opening the users default mail app it is still triggering the onbeforeunload event prompting the confirm box which is annoying i can get round it setting target blank on the link but then the user is left sitting in an empty tab can i set the mailto link to not trigger the onbeforeunload event i thought of a horribly hacky way of doing it by having another temporary javascript variable which causes the onbeforeunload confirm to not trigger but it seems kind of dirty i will do it anyway while i wait for a response but does anyone have a nicer solutionthanks max,['javascript'] +263868,collection to iterable how can i get a javalangiterable from a collection like a set or a listthanks,['java'] +263871,mocha plugin for maven working on a project that is being run off of a java based apache maven environmentthe front end is utilizing mocha tests and i would like to be able to run the rests from mavenany ideasmocha maven,['javascript'] +263883,utf8 problems in php var export returns 0 null characters and ucfirst strtoupper etc behave strangely we are dealing with a strange bug in a joyent solaris server that never happened before does not happen in localhost or two other solaris servers with identical php configuration actually i am not sure if we have to look at php or solaris and if it is a software or hardware problemi just want to post this in case somebody can point us in the right directionso the problem seems to be in var exportwhen dealing with strange charactersexecuting this in the cli we get the expected result in our localhost machines and in two of the servers but not in the 3rd one all of them are configured to work with utf8 php r echo var exportau truegives this in older servers and localhost expectedaubut in the server we are having problems with php version 536 it adds 0 null characters whenever it encounters an uncommon character a a a you name it 0 0 uany idea on where should be looking at thanks in advancemore infophp version 536setlocale is not solving anythingdefault charset is utf8 in phpinimbstringinternal encoding is set to utf8 in phpinimbstringfunc overload 0this happens in both cli example and web application phpfpm nginxiconv encoding is also utf8all files utf8 encodedsystemlocale returnslangen usutf8lc ctypeen usutf8lc numericen usutf8lc timeen usutf8lc collateen usutf8lc monetaryen usutf8lc messagesen usutf8lc allsome of the tests done so far clinormal behaviour php r echo bin2hexau c3b175 php r echo mb strtoupperau au php r echo serializexc3xb1 s2a php r echo bin2hexaddcslashesbxc3xb1 c3b1 php r echo ucfirstiau iaunot normal php r echo strtoupperau u php r echo ucfirstau u php r echo ucfirstbxc3xb1u u php r echo bin2hexucfirstau 00b175 php r echo bin2hexvar exporta 1 2727202e20225c30202e202727202e20225c30202e202727 php r echo bin2hexvar exportbxc3xb1 1 2727202e20225c30202e202727202e20225c30202e202727so the problem seems to be in var export and string functions that use the current locale but operate bytebybyte docs view hakres answer,['php'] +263884,charts for android i am working on a project which have some charts graphs tick chart candlestick chart and range chart but the problem is there is no library for that charts i have got google chart api for candlestick chart but i do not want graphchart in a webview this is the link for example of candlestick chart based on google chart api,['android'] +263889,deleting nullptr performance overhead operator delete checks itself if the pointer is nullptr is there any performance overhead when calling delete on a nullptr without checking it yourselfdelete ptrorif ptr nullptr delete ptr which of the above executes faster if ptr is nullptr,['c++'] +263894,ckeditor unwanted characters how can i thisable ckeditor to get me every time nbsp when i do not want them i am using ckeditor with jquery adapter i do not want to have any nbsp tags,"['javascript', 'jquery']" +263913,is there an enum string resource lookup pattern for android i have an enumeration where i need to thisplay the values as localized strings my current approach has been thispublic enum myenum value1rstringvalue1 value2rstringvalue2 value10rstringvalue10 private int mresid 1 private muenumint resid mresid resid public string tolocalizedstringresource r if 1 mresid return rgetstringmresid return thistostring is there any easier way to to do this i would love it if i could somehow lookup the resource based on the enumeration value name ie value1xml version10 encodingutf8resources string namevalue1my stringstring string namevalue2my string 2string string namevalue10my string 3stringresourcesedit just for future reference this is the solution that worked best for me public enum myenum value1 value2 value10 returns a localized label used to represent this enumeration value if no label has been defined then this defaults to the result of link enumname pthe name of the string resource for the label must match the name of the enumeration value for example for enum value enum1 the resource would be defined as rstringenum1 param context the context that the string resource of the label is in return a localized label for the enum value or the result of name public string getlabelcontext context resources res contextgetresources int resid resgetidentifierthisname string contextgetpackagename if 0 resid return resgetstringresid return name,['android'] +263929,given a string find the first embedded occurrence of an integer this was asked in an interviewgiven in any string get me the first occurence of an integerfor examplestr98 then it should return 98str87uyuy232 it should return 87i gave the answer as loop through the string and compared it with numeric characters as in if c 0 c 9then i got the index of the number parsed it and returned it somehow he was not convincedcan any one share the best possible solution,['java'] +263946,remove an item from an observablecollection in a collectionchanged event handler i am hoping to be able to reject some items after they have been added to an observablecollection i am not able to subclass the observablecollection or use any sort of view so i seem to be limited to using the one event handler defined collectionchanged to perform a remove on the prohibited items it is fine if the items exist for the short period between the event being raised and then handled the items should just not persist in the collection calling remove within the collectionchanged event handler does not appear to be allowed at runtime net throws an invalidoperationexceptioncannot change observablecollection during a collectionchanged eventpersonally i think net should allow me to if i create an infinite loop it is my own darn faultthe code i would like to use would look likemycollectioncollectionchanged sender args if argsaction notifycollectionchangedactionremove return foreach var itm in mycollection if itmname fred mycollectionremoveitm i am not sure what options i have using a thispatcher does not seem to work triggering another event and placing the remove call in another handler is the only other option that comes to mind,['c#'] +263948,i need a gems full path from inside a rails app i am running a rails 31 app which uses an engine called awesome engine awesome engine has some asset stuff i need to get at but compas load paths do not include the engines assets path my understanding is that it should be there but it is noti need to add it so i modified my configcompassrb to include compas additional import paths config setting the problem is this is how i get the path to the required gembegin gem root load pathfindi iincludeawesome enginegsubawesome engine awesome engineappassetsstylesheetsscss additional import paths gem rootrescueendthis works but there has got to be an easierbettercleaner way to get a gems full path anyone,['ruby-on-rails'] +263952,generate mdm certificate i am new to ios development i have to create mdm certificate for utilize default ios mdm capabilitiesi have gone through the documents how to generate apns certificate for mdm serverbut i am not getting clear idea how to generate mdm certificate which can be used to provide mdm service for all the devices registered with the mdm server,['ios'] +263960,ios udid deprecated mac address as we know apple is deprecating developers access to udid but to my knowledge it is possible to get an idevices mac address so whats the difference thenboth mac address and udid are unique identifier of a hardware which is not app specific,['ios'] +263985,set css of code when it contains reserved words what i am trying to do as stated in the title i want to set the css of a word if it is a reserved wordhtml html body code idjava public static void mainstring argsbr pre systemoutprintlnhello worldpre code bodyhtmljquerydocumentreadyfunction get the text inside the code tags var code javatext split up each word var split codesplit array of reserved words var array abstractassertbooleanbreakbytecase catchcharclassconstcontinuedefault dodoubleelseelse ifenumextendsfinal finallyfloatforgotoifimportimplements instanceofintinterfacelongnativenewnull packageprivateprotectedpublicreturnshort staticstrictfpsuperswitchsynchronizedthis throwthrowstransientvoidvolatilewhile added when text contains a reserved word var css fontweightboldcolor2400d9 array jquerymaparray functionni for int j0 jarraylength j if spliticontainsarrayj spliticsscss problem i have referred to the documentation for several methods in the references section below but i am not too sure where the problems lies to narrow the issue down my questions would beis split even a method in jqueryshould i use a for loop to run through all the words in the array to see if the code contains a reserved word or is there a better approach such as eachif i should use each could someone please give me a simple example i do not understand the examples in the documentationreferencessplit in jquerymapeach,"['javascript', 'jquery', 'html', 'css']" +263989,how to take camera capture without a preview from a service or thread is it possible to capture an image without showing the camera preview i have a requirement that i should be able to capture the image from a thread or from a service without thisturbing the foreground application where i do not want to show the camera preview but still i want to capture the image in background and store it in the device,['android'] +263997,test php headers with phpunit i am trying to use phpunit to test a class that outputs some custom headersthe problem is that on my machine thisphpclass headerstest extends phpunit framework testcase public function testheaders ob start headerlocation foo headers list headers list header remove ob clean thisassertcontainslocation foo headers list or even thisphpclass headerstest extends phpunit framework testcase public function testheaders ob start headerlocation foo header remove ob clean return this errornamehost test phpunit verbose headerstestphp phpunit 3610 by sebastian bergmannetime 0 seconds memory 225mbthere was 1 error1 headerstesttestheaderscannot modify header information headers already sent by output started at usrlocallibphpphpunitutilprinterphp173testheaderstestphp9failurestests 1 assertions 0 errors 1this looks as if there is something else outputting to the terminal before the test runs even though there is no other file included and there is no other character before the beginning of the php tag could it be something inside phpunit that is causing thiswhat could the issue be,['php'] +264028,concurrent file access in android i know that many oses perform some sort of locking on the filesystem to prevent inconsistent views are there any guarantees that java andor android make about threadsafety of file access i would like to know as much about this as possible before i go ahead and write the concurrency code myself if i missed a similar question that was answered feel free to close this thread thanks,"['java', 'android']" +264033,how can i open an external link in safari not the apps uiwebview i have a phonegap cordova application where i want to load some external webpages within the phonegap webview and i have other external webpages that i want to load in safari when the user activates themtypically most people have the problem where they want to open an external link in the webview setting openallwhitelisturlsinwebview to yes in cordovaplistphongapplist solves that problembut i do not want to open all links the the webview just somei was hoping i could just call windowopenhttpsomeexternalsite to open in safari and windowparentlocationhref httpmysite to open it in the webviewany idea how to do this,"['javascript', 'ios']" +264054,min value of float in java is positive why when we use min value function on either of primitive types in java it give us minimum value possible for that typebutin case of float and double it returned minimum positive value though float and double can have negative values also,['java'] +264063,does accessing the first field of a struct via a c cast violate strict aliasing does this code violate strict aliasingstruct int x ainta 3more abstractly is it legal to cast between different types as long as the primitive readwrite operations are type correct,"['c++', 'c']" +264080,slim framework always return 404 error these days i am using slim framework as my simplest tool to develop the php web apiusing these two articlescoenraetscodingthisi follow some of the steps from there downloading the slim framework putting the correct directory files adjusting the initation statements such as1 require slimrequireslimslimphp2 instantiate slimapp new slim3 define routesappgetbooks function id show book with id idand then i modify the rest accordingly such as my checklist that already doneloadmodule rewrite module modulesmod rewriteso enabledslim htaccessrewriteengine on rewritecond request filename f rewriterule bootstrapphp qsalhttpdconf shared linkbut after once i run this statementapprunand i run it on my browser then i got 404 error while testing it on my localhost whats the solution for fixing thatfyi here is my simplest php file that i am currently using it shared link,['php'] +264092,radio group onclick event not firing how do i tell which is selected i am using radio group but radiogroup onclick event is not firing and the method getcheckedradiobuttonid is returning null here is the element in my layout radiogroup androidididrg1 androidlayout widthwrap content androidlayout heightwrap content androidorientationhorizontal androidonclickonrgclick methodpublic void onrgclickview v toastmaketextthis test 10show,['android'] +264094,why f is placed after float values i do not know why f or f is placed after float values in java or other languages for instancefloat fvariable 123fany features other than indicating that this is a float value,['java'] +264111,how to use rmysql in windows i tried to use rmysql package but i get this error doinginstallpackagesrmysqlwarning in installpackages package armysqla is not available for r version 2142what can i do to use mysql with rthank you,['mysql'] +264112,how to pauseresume all threads in an executorservice in java i submitted bunch of jobs to an executorservice in java and i somehow want to temporarily pause all these jobs whats the best way to do this how can i resume or am i doing this completely wrong should i follow some other pattern for what i want to achieve ie ability to pauseresume execution services,['java'] +264123,prevent a multiline textview from unnecessarily expanding to it is maximum width a textview that expands to multiple lines seems to automatically expand to fit it is maximum possible width how can i prevent that from happeninghere is an example layout testxmlxml version10 encodingutf8relativelayout xmlnsandroidandroidlayout widthmatch parentandroidlayout heightmatch parentandroidbackgroundcolorwhitetextviewandroidbackgroundcolorgreenandroidlayout alignparentrighttrueandroidididfooandroidlayout widthwrap contentandroidlayout heightwrap contentandroidgravityrightandroidtextthis is the message a much shorter messageandroidtextappearanceandroidattrtextappearancemediumandroidtextcolorcolorblack relativelayoutif i add a margin on the left it correctly shrinks the width of the textview without reformatting the content but the size of the margin would have to calculated given the contents of the textviewxml version10 encodingutf8relativelayout xmlnsandroidandroidlayout widthmatch parentandroidlayout heightmatch parentandroidbackgroundcolorwhitetextviewandroidlayout marginleft32dpandroidbackgroundcolorgreenandroidlayout alignparentrighttrueandroidididfooandroidlayout widthwrap contentandroidlayout heightwrap contentandroidgravityrightandroidtextthis is the message a much shorter messageandroidtextappearanceandroidattrtextappearancemediumandroidtextcolorcolorblack relativelayout,['android'] +264126,python for ios interpreter possible duplicatepython or ruby interpreter on ios i just thiscovered this apps pypad and python for ios they have like an interpreter an editorso which app would you recomend but most importantly how does this interpreter work and where can i see an example of how the obj c and python get to work togheterthanks,"['python', 'ios']" +264132,how to calculate x509 certificates sha1 fingerprint in ccobjectivec backgroundi am writing a client utility which is capable of connecting to a remote server using ssltls the client uses openssl to perform the ssltls transactions and i would like to allow users to specify authorized ca certs in the case of self signed certs or private ca setups used to sign the servers certificate i plan on using the certs fingerprint common name and validity dates to allow the user to quickly view the certs the client uses to validate serversquestionhow do you calculate the sha1 hashfingerprint of an x509 cert stored within a pem file using ccobjectivecafter days of search and experimenting i found a solution and will post it as an answer however i welcome better or more correct solutions,['c'] +264135,fast inputoutput in competitive programming i have come across this particular snippet of code many times in solutions of competitive programming contests i understand the basic use of this code to beat time limits but i want to understand it more deeply i know that unistdh gives access to system call wrapper functions such as fork pipe and io primitives read write it will also be great if anyone can explain or guide me to resources that can help me understand it furtherinclude stdlibhinclude stdinthinclude unistdhclass fastinput public fastinput m dataoffset 0 m datasize 0 m v 0x80 uint32 t readnext if m dataoffset m datasize int r read0 m buffer sizeofm buffer if r 0 return m v m dataoffset 0 m datasize 0 int i 0 if m buffer0 0 if m v 0x80 m datam datasize m v m v 0x80 for i r m bufferi 0 i for i r if m bufferi 0 m v m v 10 m bufferi 48 i else m datam datasize m v m v 0x80 for i i 1 i r m bufferi 0 i return m datam dataoffset public uint8 t m buffer32768 uint32 t m data16384 size t m dataoffset m datasize uint32 t m vclass fastoutput public fastoutput m dataoffset 0 fastoutput void flush if m dataoffset if write1 m data m dataoffset m dataoffset 0 void printuintuint32 t v char d if m dataoffset 11 sizeofm data flush if v 10 if v 10 if v 10 m datam dataoffset 0 v 48 m dataoffset 1 else if v 100 m datam dataoffset 1 v v 10 10 48 v 10 m datam dataoffset 0 v 48 m dataoffset 2 else m datam dataoffset 2 v v 10 10 48 v 10 m datam dataoffset 1 v v 10 10 48 v 10 m datam dataoffset 0 v 48 m dataoffset 3 else if v 10 m datam dataoffset 3 v v 10 10 48 v 10 m datam dataoffset 2 v v 10 10 48 v 10 m datam dataoffset 1 v v 10 10 48 v 10 m datam dataoffset 0 v 48 m dataoffset 4 else m datam dataoffset 4 v v 10 10 48 v 10 m datam dataoffset 3 v v 10 10 48 v 10 m datam dataoffset 2 v v 10 10 48 v 10 m datam dataoffset 1 v v 10 10 48 v 10 m datam dataoffset 0 v 48 m dataoffset 5 else if v 10 if v 10 m datam dataoffset 5 v v 10 10 48 v 10 m datam dataoffset 4 v v 10 10 48 v 10 m datam dataoffset 3 v v 10 10 48 v 10 m datam dataoffset 2 v v 10 10 48 v 10 m datam dataoffset 1 v v 10 10 48 v 10 m datam dataoffset 0 v 48 m dataoffset 6 else if v 10 m datam dataoffset 6 v v 10 10 48 v 10 m datam dataoffset 5 v v 10 10 48 v 10 m datam dataoffset 4 v v 10 10 48 v 10 m datam dataoffset 3 v v 10 10 48 v 10 m datam dataoffset 2 v v 10 10 48 v 10 m datam dataoffset 1 v v 10 10 48 v 10 m datam dataoffset 0 v 48 m dataoffset 7 else m datam dataoffset 7 v v 10 10 48 v 10 m datam dataoffset 6 v v 10 10 48 v 10 m datam dataoffset 5 v v 10 10 48 v 10 m datam dataoffset 4 v v 10 10 48 v 10 m datam dataoffset 3 v v 10 10 48 v 10 m datam dataoffset 2 v v 10 10 48 v 10 m datam dataoffset 1 v v 10 10 48 v 10 m datam dataoffset 0 v 48 m dataoffset 8 else if v 10 m datam dataoffset 8 v v 10 10 48 v 10 m datam dataoffset 7 v v 10 10 48 v 10 m datam dataoffset 6 v v 10 10 48 v 10 m datam dataoffset 5 v v 10 10 48 v 10 m datam dataoffset 4 v v 10 10 48 v 10 m datam dataoffset 3 v v 10 10 48 v 10 m datam dataoffset 2 v v 10 10 48 v 10 m datam dataoffset 1 v v 10 10 48 v 10 m datam dataoffset 0 v 48 m dataoffset 9 else m datam dataoffset 9 v v 10 10 48 v 10 m datam dataoffset 8 v v 10 10 48 v 10 m datam dataoffset 7 v v 10 10 48 v 10 m datam dataoffset 6 v v 10 10 48 v 10 m datam dataoffset 5 v v 10 10 48 v 10 m datam dataoffset 4 v v 10 10 48 v 10 m datam dataoffset 3 v v 10 10 48 v 10 m datam dataoffset 2 v v 10 10 48 v 10 m datam dataoffset 1 v v 10 10 48 v 10 m datam dataoffset 0 v 48 m dataoffset 10 m datam dataoffset d void printcharchar d if m dataoffset 1 sizeofm data flush m datam dataoffset d void replacecharint offset char d m datam dataoffset offset d public uint8 t m data32768 size t m dataoffsetone more thing is it good practice to employ similar techniques in production level code,['c++'] +264144,how to loop in navigablemap in java is there any way to loop in navigablemap in java i want to access all of item in navigablemap,['java'] +264148,pipe sign in php code i wanted to concatenate 2 variables and by error i typed another code and i got a strange resultthis is what looks like the code echo hello world testresult eo worldwhat the pipe sign do if not concatenated,['php'] +264163,how to convert integer into date object python i am creating a module in python in which i am receiving the date in integer format like 20120213 which signifies the 13th of feb 2012 now i want to convert this integer formatted date into a python date objectalso if there is any means by which i can subtractadd the number of days in such integer formatted date to receive the date value in same format like subtracting 30 days from 20120213 and receive answer as 20120114,['python'] +264174,ruby require error cannot load such file i have one file mainrb with the following contentrequire tokenizerrbthe tokenizerrb file is in the same directory and its content isclass tokenizer def selftokenizestring return stringsplit endendif i try to run mainrb i get the following errorcdocuments and settingsmysrcfolderruby mainrbcruby193libruby191rubygemscustom requirerb36in require cannot load such file tokenizerrb loaderror from cruby193libruby191rubygemscustom requirerb36in require from mainrb1in maini just noticed that if i use load instead of require everything works fine what may the problem be here,['ruby'] +264209,how i can check if a window has visible scrollbars using his hwnd i want to check if the window of an external application has the vertical or horizontal scrollbar visible using the hwnd handle of the window exist any winapi function to get this information i really try the getscrollinfo function but it seems that not retrieve information about the visibility of the scrollbars,['c++'] +264226,change the text will paginate renders how can change the text that will paginate showsright now it renders previous next i need to put that in french pracadent suivant i checked on google and got this link paginateandrails3however i was wondering if there was an easier way,['ruby-on-rails'] +264239,take a photo automatically without user interaction i used this code to capture an image from the camerapackage androidtakeowneshipimport javaiofileimport androidappactivityimport androidcontentcontentvaluesimport androidcontentintentimport androiddatabasecursorimport androidgraphicsbitmapimport androidgraphicsbitmapfactoryimport androidneturiimport androidosbundleimport androidprovidermediastoreimport androidwidgetimageviewimport androidwidgettoastpublic class camera extends activity private static final int capture image activity request code 100 uri imageuri private imageview imageview override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain define the filename to save photo taken by camera activity string filename newphotonamejpg create parameters for intent with filename contentvalues values new contentvalues valuesputmediastoreimagesmediatitle filename valuesputmediastoreimagesmediadescriptionimage capture by camera imageuri is the current activity attribute define and save it for later usage also in onsaveinstancestate imageuri getcontentresolverinsert mediastoreimagesmediaexternal content uri values create new intent intent intent new intentmediastoreaction image capture intentputextramediastoreextra output imageuri intentputextramediastoreextra video quality 1 startactivityforresultintent capture image activity request code protected void onactivityresultint requestcode int resultcode intent data if requestcode capture image activity request code if resultcode result ok use imageuri here to access the image toastmaketextthis picture has been taken imageuri toastlength shortshow else if resultcode result canceled toastmaketextthis picture was not taken toastlength shortshow else toastmaketextthis picture was not taken toastlength shortshow public static file convertimageuritofile uri imageuri activity activity cursor cursor null try string projmediastoreimagesmediadata mediastoreimagesmedia id mediastoreimagesimagecolumnsorientation cursor activitymanagedquery imageuri proj which columns to return null where clause which rows to return all rows null where clause selection arguments none null orderby clause ascending by name int file columnindex cursorgetcolumnindexorthrowmediastoreimagesmediadata int orientation columnindex cursorgetcolumnindexorthrowmediastoreimagesimagecolumnsorientation if cursormovetofirst string orientation cursorgetstringorientation columnindex return new filecursorgetstringfile columnindex return null finally if cursor null cursorclose but in this code it opens the camera and user has to click the button to take the photowhat i want is to take the photo automatically without a preview and saves it in the memory card,['android'] +264240,slide toggle for android anyone know of any open source implementation of a slide toggle for android the default android toggletogglebutton is not pretty i am looking for anything similar to ios i should be able to implement one from scratch but if anything similar is already available then i can build on itthanks in advance to the wonderful stackoverflow communityedit1 what i meant by ios slide toggle is uiswitchedit2 just want to summarize the answer commonsware provided the clue i ended up back porting the switch code from 40 to2 thanks to the opensourced code back porting was not very difficult the code is hosted on git hub a screenshot from that project,['android'] +264254,ipad 3 opengl bug with keagldrawablepropertyretainedbacking and retina i have an ios opengl app which uses the keagldrawablepropertyretainedbacking property to draw the current frame on top of the previous frame it is a cheap way of getting effects like motion trailsit works great on all devices including iphone w retina and all device simulators but on the actual ipad 3 device the previous frame is vertically squished to 75 of its previous sizefor example if i were to draw a 100 x 100 square at the bottom of the screen each framethen in frame 0 i have one square in frame 2 there is an echo that is 100 x 75 and offset towards the top of the screen in frame three there is an additional echo that is 100 x 56 56 75 075 and is more offset towards the top and soon what should happen is that all the echoes remain in placei have verified the behavior on two devices so i do not think it is a just a broken ipadany ideas tiaorion,['ios'] +264285,listview selection remains persistent after exiting choice mode i have a listview subclass that i allow selections on when the context action bar cab is active the cab is set as a callback to the onitemlongclick eventpublic boolean oncreateactionmodeactionmode mode menu menu inflate a menu resource providing context menu items menuinflater inflater modegetmenuinflater inflaterinflatecontext menu menu getlistviewsetchoicemodelistviewchoice mode single return truethis is fine and the listview works as expected with the currently selected item staying highlighted when touchedwhen i close the cab i want the listview to return to normal ie touch mode the problem is that the last selected item remains highlighted indefinitely regardless of what methods i try to clear itpublic void ondestroyactionmodeactionmode mode unselect any rows listview lv getlistview lvclearchoices has no effect lvsetchoicemodelistviewchoice mode none has no effect on the highlighted item lvsetfocusablefalse has no effect lvsetselection0 has no effect mactionmode nullany suggestions,"['java', 'android']" +264294,converting epoch time to date string i have seen this question asked multiple times and none of the answers seem to be what i needi have a long type variable which has an epoch time stored in itwhat i want to do is convert it to a stringfor example if the epoch time stored was for today the final string would read17032012how would i to this,"['java', 'android']" +264300,rails simple form bootstrap when errors fields not turning red i have started using simpleform and bootstrap and i have tried to follow this reference simple form bootstrap but i do not know what is going on because when a field is failing here is what happensregarding this screenshot i have a question 1 as you see the price field is not being red surrounded how can i do thathere is my code for the form simple form for lesson html class well do lesson form if lesson formerror notification div classalert alerterror fade in a classclose datathismissalert hreftimesa lesson formerror notification div end lesson forminput title lesson forminput category lesson forminput description lesson forminput price lesson formbutton submit label create class btn btnprimary btnlarge end,['ruby-on-rails'] +264322,whats the difference between pytz and pythondateutil i am trying to implement timezone awareness in my python application and i have come across two different python modules that implement this feature pytz and pythondateutil i am wondering what the difference between these two modulespytz pythondateutil,['python'] +264336,why can tuples contain mutable items if a tuple is immutable then why can it contain mutable itemsit is seemingly a contradiction that when a mutable item such as a list does get modified the tuple it belongs to maintains being immutable,['python'] +264341,how do i get a utc timestamp in javascript while writing a web application it makes sense to store server side all datetimes in the db as utc timestampsi was astonished when i noticed that you could not natively do much in terms of timezone manipulation in javascripti extended the date object a little does this function make sense basically every time i send anything to the server it is going to be a timestamp formatted with this functioncan you see any major problems here or maybe a solution from a different angledateprototypegetutctime function return new date thisgetutcfullyear thisgetutcmonth thisgetutcdate thisgetutchours thisgetutcminutes thisgetutcseconds gettime it just seems a little convoluted to me and i am not so sure about performance eitherthanksmerc,['javascript'] +264377,setting actionbarsherlock theme for android app read update 2 below for the answeri am trying to use actionbarsherlock in my app i checked out the 400 release from the project github repo built it in netbeans then copied the library400jar file into my projects lib directory i am not using eclipseit is just a skeleton activity right now and it launches just fine in ics but when i run it on gingerbread i get the following exception complaining that i have not the app theme to themesherlock or similarjavalangruntimeexception unable to start activity componentinfocomarashpayanprayerbookcomarashpayanprayerbookprayerbook javalangillegalstateexception you must use themesherlock themesherlocklight themesherlocklightdarkactionbar or a derivative at androidappactivitythreadperformlaunchactivityactivitythreadjava1647 at androidappactivitythreadhandlelaunchactivityactivitythreadjava1663 at androidappactivitythreadaccess1500activitythreadjava117 at androidappactivitythreadhhandlemessageactivitythreadjava931 at androidoshandlerthispatchmessagehandlerjava99 at androidoslooperlooplooperjava130 at androidappactivitythreadmainactivitythreadjava3683 at javalangreflectmethodinvokenativenative method at javalangreflectmethodinvokemethodjava507 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava839 at comandroidinternaloszygoteinitmainzygoteinitjava597 at dalviksystemnativestartmainnative methodcaused by javalangillegalstateexception you must use themesherlock themesherlocklight themesherlocklightdarkactionbar or a derivative at comactionbarsherlockinternalactionbarsherlockcompatgeneratelayoutactionbarsherlockcompatjava987 at comactionbarsherlockinternalactionbarsherlockcompatinstalldecoractionbarsherlockcompatjava899 at comactionbarsherlockinternalactionbarsherlockcompatsetcontentviewactionbarsherlockcompatjava852 at comactionbarsherlockactionbarsherlocksetcontentviewactionbarsherlockjava655 at comactionbarsherlockappsherlockfragmentactivitysetcontentviewsherlockfragmentactivityjava316 at comarashpayanprayerbookprayerbookoncreateprayerbookjava44 at androidappinstrumentationcallactivityoncreateinstrumentationjava1047 at androidappactivitythreadperformlaunchactivityactivitythreadjava1611 11 morethe line it complains about prayerbook44 is the call to setcontentview the app just consists of a single activity with an oncreate method that i call settheme from at the toppublic void oncreatebundle savedinstancestate setthemecomactionbarsherlockrstyletheme sherlock superoncreatesavedinstancestate textview roottextview new textviewthis roottextviewsettexthello world setcontentviewroottextview getsupportactionbarsetnavigationmodeactionbarnavigation mode tabs actionbartab tab getsupportactionbarnewtab tabsettextprayers getsupportactionbaraddtabtab tab getsupportactionbarnewtab tabsettextrecents getsupportactionbaraddtabtab tab getsupportactionbarnewtab tabsettextbookmarks getsupportactionbaraddtabtabi must be setting the theme incorrectly but i just do not see how can anyone helpupdatebelow commonsware noted that the theme can be set in the androidmanifestxml i have tried that like soapplication androidlabelstringapp name androidicondrawableicon androidthemestylethemesherlock activity androidnameprayerbook androidlabelstringapp name androidconfigchangesorientationkeyboardhiddenscreenlayoutuimodemccmnclocalenavigationfontscalescreensize intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity activity androidnamelanguagesactivity applicationbut ant gives me an error when it tries to build the appusersarashcodingprayerbookandroidmanifestxml7 error error no resource found that matches the given name at theme with value stylethemesherlockupdate 2with commonswares help in his follow up comments i was able to get it working i needed to add actionbarsherlock as a project dependency to do so1 i removed library400jar and androidsupport40jar from my projects lib directory2 next navigate into the library folder inside the root of the actionbarsherlock directory checked out from github type android update project so a buildxml and proguardcfg file will be created for the library3 finally cd back into the main project directory and add abs as a library dependency with android update project path library actionbarsherlocklibrarythe path to the library in the command will vary according to where you checked out the repo actionbarsherlock and my apps project directory were sibling directories,['android'] +264408,pandas convert dataframe to array of tuples i have manipulated some data using pandas and now i want to carry out a batch save back to the database this requires me to convert the dataframe into an array of tuples with each tuple corresponding to a row of the dataframemy dataframe looks something likein 182 data setout182 index data date data 1 data 20 14303 20120217 2475 2503 1 12009 20120216 2500 2507 2 11830 20120215 2499 2515 3 6274 20120214 2468 2505 4 2302 20120213 2462 2477 5 14085 20120210 2438 2461 and i want to convert it to an array of tuples likedatetimedate201221724752503datetimedate201221625002507etc any suggestion on how i can efficiently do this,['python'] +264417,model and backend interface generators for zend framework by doing some research one of the thisadvantages often reported about zend framework is the amount of work required to get off the ground for me this could be addressed if zf had strong model and backend interface generators like symfony does i have been looking for those and here is what i foundmodel generators looks like official one based on user feedback the documentation seems to be awful though seems quite advanced updated 3 months ago not updated in 2 years looks dead single php file could be interesting to use as basis and extend as neededbackend interfacesas usual one can use database administration tools quite complete with plenty of new features since 35 hard to extend singlefile backend interface quite complete the use of plugins seems to make extending functionality easybackend interface generators which comes from what looks like a very active zf related project i have recently come across this framework which allows you to create desktoplike applications around zend which one could use to create a backend interfacesetting up the interface seems to be quite easy for instance here is how you would thisplay a form to edit contacts on the same page as you would edit membersphpclass membercontacts extends kwf model db protected table member contacts protected referencemap array member array column member id refmodelclass members a demo of koala frameworks is available to be honest it looks quite impressiveq which model generators and backend interface generators do you use for zend and why,['php'] +264452,how to get a list of variables in specific python module let us assume i have the following file structuredatapyfoo bar abc defcorepyimport data do something here a print a foo bar abci need to get all the variables defined in datapy file how can i achieve that i could use dir but it returns all the attributes of the module including name and so on,['python'] +264457,how to check if an element of a list is a list in python if we have the following listlist umm uma ulasterulterif i need to find out if an element in the list is itself a list what can i replace avalidlist in the following code withfor e in list if e avalidlist return trueis there a special import to use is there a best way of checking if a variableelement is a list,['python'] +264465,all in one social share button javascript for websites nearly all of us use social media these days and yes its very hard for mea developer to combine every single social button share into onefacebooktwittergoogle pluslinkedinanything else is a extrai found some good examples likebut is there any alternative that i havent seenref for readers,['javascript'] +264517,dll size in memory size on the hard thisk is there a relationship between dll size in memory and size on the hard thiskthis is because i am using task manager extension ms and i can go to an exe in the list and right click module then i can see all the dlls this exe is using it has a length column but is it in bytes and the value length of the dll seems to be different from the dll size on the hard thisk why,['c++'] +264535,timesleep requires integers i am writing a macro that will click certain spots on the screen when i press a key the first time i press a key everything runs finehowever any other key press results in the error timesleep01typeerror an integer is requiredhere is the codeimport win32apiimport win32conimport timeimport pythoncomimport pyhookimport osdef clickxy win32apisetcursorposxy win32apimouse eventwin32conmouseeventf leftdownxy00 win32apimouse eventwin32conmouseeventf leftupxy00def deleterunevent click1250 741 timesleep01 click649261 timesleep01 click651 348 timesleep01 click800 442 timesleep01 click865 612click2020keygrabber pyhookhookmanagerkeygrabberkeydown deleterunkeygrabberhookkeyboardpythoncompumpmessagesit seems the first time the deleterun function is run by pyhook timesleep accepts floatson any following function calls it seems it only accepts integerswhat is causing thisi cannot wait 5 seconds for the mouse arrangement it is supposed to save timespecspython 272 windows 7 32,['python'] +264555,on github what does build status mean especially if a rails gem for example has failing as its build status,['ruby-on-rails'] +264569,backbone js difference between getters vs direct access of model attributes what is the advantage reason for backbonejs to use the syntaxusing a model instance called modelmodelgetattributeand not modelattributeim just starting to use backbone and i always ind myself trying to access the attributes directly,['javascript'] +264580,why objectequals and instanceobjectequals are not same string s1 t string s2 ttostring consolewritelines1equalss2 returning true consolewritelineobjectequalss1 s2 returning truehere it is returning same result now when i am using stringbuilder it is not returning same value what is the underneath reason stringbuilder s1 new stringbuilder stringbuilder s2 new stringbuilder consolewritelines1equalss2 returning true consolewritelineobjectequalss1 s2 returning falseedit1 my above question answered below but during this thiscussion what we find out stringbuilder does not have any override equals method in its implementation so when we call stringbuilderequals it actually goes to objectequals so if someone calls stringbuilderequals and s1equalss2 the result will be different,['c#'] +264584,is a html table within a table valid in html is it valid to have a table inside of a table table tr td table tr tdtd tr table td tr trtrtable,['html'] +264585,does a unique constraint automatically create an index on the fields should i define a separate index on the email column for searching purposes or is the index is automatically added along with uniq email user constraintcreate table if not exists customer id int11 not null auto increment user id int11 not null first varchar255 not null last varchar255 not null slug varchar255 not null email varchar255 not null created at datetime not null updated at datetime not null primary key id unique key uniq slug slug unique key uniq email user emailuser id key idx user user id engineinnodbedit as suggested by corbin i queried for explain select from customer where email address on empty table this is the result i do not know how to interpret itid select type type possible keys key key len ref rows extra1 simple all null null null null 1 using wherewhile adding an ixd email to the table the same query showsid select type type possible keys key key len ref rows extra1 simple ref idx email idx email 257 const 1 using where,"['mysql', 'sql']" +264593,measure elapsed time between two motionevents in android i am new in android programming so i am asking for your help in my problemi am trying to measure in secondsmilliseconds the amount of time between a mouseeventaction down and mouseeventaction upoverridepublic boolean ontoucheventmotionevent event long start0 if eventgetaction motioneventaction down manage down press startsystemnanotimestart systemoutprintlnstart else if eventgetaction motioneventaction move manage move systemoutprintlneventgetrawxeventgetrawy else manage up long finishsystemnanotimefinish long seconds finishstart 10for seconds toastmaketextthis finish duration seconds toastlength shortshow systemoutprintlnfinish duration seconds return truelogcat0319 040427140 isystemout4348 start0319 040427160 isystemout4348 5170280319 040427190 isystemout4348 5170280319 040427200 isystemout4348 5170280319 040427220 isystemout4348 5170280319 040427250 isystemout4348 5170280319 040427260 isystemout4348 5170280319 040427300 isystemout4348 5170280319 040427310 isystemout4348 5170280319 040427330 isystemout4348 finish duration 16545my problem consist in fact that seconds variable does not show what i want i even do not know if its measuring correctlyfor the above example duration was 16545 but it should have been between 13 secondswhat shall i do to measure correctly in seconds or milliseconds the time between two motionevents or what am i wrong in my example thank you,"['java', 'android']" +264616,capturing repeating subpatterns in python regex while matching an email address after i match something like yasarwebmail i want to capture one or more of wwhat i am doing is a little bit more complicated this is just an example i tried adding w but it only captures last match for example matches but only include tr after yasarwebmail part so i lost something and edu groups can i do this in python regular expressions or would you suggest matching everything at first and split the subpatterns later,['python'] +264623,onlistitemclick is not working for listview hi onlistitemclick for listview is not working here i am fetching datas from sqlite using asynctask and thisplaying it in a list view and i wants to do some actions when a list in a listview has clicked but the click is not happening i had tried a lot for this please help mehere is my code package comapplexusappmobilesalesorderimport javautilarraylistimport javautilmapimport javautiltreemapimport comapplexusapplibrarysqlsqlconnectorimport androidapplistactivityimport androidcontentcontextimport androidcontentintentimport androidcontentsharedpreferencesimport androiddatabasecursorimport androidosasynctaskimport androidosbundleimport androidutillogimport androidviewkeyeventimport androidviewlayoutinflaterimport androidviewviewimport androidviewviewgroupimport androidviewwindowimport androidviewinputmethodeditorinfoimport androidwidgetadapterviewimport androidwidgetadapterviewonitemclicklistenerimport androidwidgetbaseadapterimport androidwidgetedittextimport androidwidgetlinearlayoutimport androidwidgetlistviewimport androidwidgetprogressbarimport androidwidgettextviewimport androidwidgettextviewoneditoractionlistenerpublic class soldtopartieslist extends listactivity private arrayliststring data new arrayliststring private arrayliststring idk new arrayliststring private arrayliststring name1 new arrayliststring private arrayliststring inco1 new arrayliststring private arrayliststring email new arrayliststring private arrayliststring tel new arrayliststring private arrayliststring vwerk new arrayliststring private sharedpreferences prefs private string prefnamesalesorgid salesorgid private string prefnamethistchnlid thistchnlid private string prefnamedivid divid private string prefname mso private textview titlename private static class viewholder textview tvlist textview tvlistsmall private class efficientadapter extends baseadapter private context context layoutinflater inflater public efficientadaptercontext context todo autogenerated constructor stub thiscontext context inflater layoutinflaterfromcontext override public int getcount todo autogenerated method stub return datasize override public object getitemint position todo autogenerated method stub return position override public long getitemidint position todo autogenerated method stub return position override public view getviewint position view convertview viewgroup parent todo autogenerated method stub viewholder holder final int place position if convertview null convertview inflaterinflaterlayoutlistso null holder new viewholder holdertvlist textview convertview findviewbyidridtextviewlist holdertvlistsmall textview convertview findviewbyidridtextview1 convertviewsettagholder else holder viewholder convertviewgettag holdertvlistsettextidkgetposition holdertvlistsmallsettextdatagetposition return convertview mapstring string map new treemapstring string sqlconnector con string salorg string thistch string division context co this boolean searchablefalse textview tvmc textview tvmn override protected void oncreatebundle savedinstancestate todo autogenerated method stub superoncreatesavedinstancestate requestwindowfeaturewindowfeature no title setcontentviewrlayoutmateriallist titlename textview findviewbyidridtextviewtitle titlenamesettextrstringsoldtoparties tvmctextviewfindviewbyidridtextviewmc tvmntextviewfindviewbyidridtextviewmn prefs getsharedpreferencesprefname mode private salorg prefsgetstringprefnamesalesorgid thistch prefsgetstringprefnamethistchnlid divisionprefsgetstringprefnamedivid downloadwebpagetask task new downloadwebpagetask taskexecutenew string null listview lvlistviewfindviewbyidandroidridlist lvsetonitemselectedlistenernew edittext es linearlayout ls linearlayout mc linearlayout mn boolean searchflag false string search override protected void onresume todo autogenerated method stub superonresume es edittext findviewbyidridedittextsearch ls linearlayout findviewbyidridlinearlayoutsearch private class downloadwebpagetasksearch extends asynctaskstring void string cursor c progressbar pb override protected string doinbackgroundstring urls con new sqlconnectorco try if searchflag c conselectselect kunnrnamename1inco1vwerksmtpaddrtelf1 from tb soldtoparties where salesorg salorg and channel thistch and name like search and divisiondivision else c conselectselect kunnrnamename1inco1vwerksmtpaddrtelf1 from tb soldtoparties where salesorg salorg and channel thistch and kunnr like search and divisiondivision catch exception e eprintstacktrace int in cgetcount cmovetofirst for int i 0 i in i idkaddcgetstring0 dataaddcgetstring1 name1addcgetstring2 inco1addcgetstring3 vwerkaddcgetstring4 emailaddcgetstring5 teladdcgetstring6 cmovetonext return null override protected void onpostexecutestring result setlistadapternew efficientadaptersoldtopartieslistthis pb progressbar findviewbyidridprogressbar1 pbsetvisibilityviewinvisible searchabletrue conclose override protected void onpreexecute superonpreexecute idkclear dataclear name1clear inco1clear vwerkclear emailclear telclear setlistadapternew efficientadaptersoldtopartieslistthis pb progressbar findviewbyidridprogressbar1 pbsetvisibilityviewvisible searchablefalse private class downloadwebpagetask extends asynctaskstring void string cursor c progressbar pb override protected string doinbackgroundstring urls con new sqlconnectorco try c conselectselect kunnrnamename1inco1vwerksmtpaddrtelf1 from tb soldtoparties where salesorg salorg and channel thistch and divisiondivision catch exception e eprintstacktrace int in cgetcount cmovetofirst logdsize in for int i 0 i in i idkaddcgetstring0 dataaddcgetstring1 name1addcgetstring2 inco1addcgetstring3 vwerkaddcgetstring4 emailaddcgetstring5 teladdcgetstring6 cmovetonext return null override protected void onpostexecutestring result setlistadapternew efficientadaptersoldtopartieslistthis pb progressbar findviewbyidridprogressbar1 pbsetvisibilityviewinvisible searchabletrue conclose override protected void onpreexecute superonpreexecute idkclear dataclear name1clear inco1clear vwerkclear emailclear telclear pb progressbar findviewbyidridprogressbar1 pbsetvisibilityviewvisible searchablefalse class clickonlist implements onitemclicklistener override public void onitemclickadapterview arg0 view arg1 int arg2 long arg3 logdlistview positionarg2 public onitemclicklistener thelistlistener new onitemclicklistener public void onitemclickandroidwidgetadapterview parent view v int position long id logdpositionposition override protected void onlistitemclicklistview l view v int position long id superonlistitemclickl v position id int placeposition logdpositionposition and layout code is materiallistxmlxml version10 encodingutf8linearlayout xmlnsandroid androidlayout widthfill parent androidlayout heightfill parent androidbackgroundcolorbluebg androidorientationvertical linearlayout androidididlinearlayout1 androidlayout widthfill parent androidlayout heightwrap content androidbackgrounddrawablebar1 androidgravitycenter vertical androidminheight50dp androidorientationhorizontal linearlayout androidididlinearlayout2 androidlayout widthwrap content androidlayout heightfill parent androidlayout margin5dp androidlayout weight1 androidgravitycenter verticalleft textview androidididtextviewtitle androidlayout widthwrap content androidlayout heightwrap content androidlayout margin5dp androidshadowcolor0 androidshadowdx1 androidshadowdy1 androidshadowradius15 androidtextstringmaterials androidtextappearanceandroidattrtextappearancelarge linearlayout linearlayout androidididlinearlayout3 androidlayout widthwrap content androidlayout heightfill parent androidlayout margin5dp androidgravitycenter progressbar androidididprogressbar1 styleandroidattrprogressbarstylesmall androidlayout widthwrap content androidlayout heightwrap content androidvisibilityvisible linearlayout linearlayout linearlayout androidididlinearlayout2 androidlayout widthfill parent androidlayout heightwrap content androidorientationvertical linearlayout androidididlinearlayout3 androidlayout widthfill parent androidlayout heightwrap content linearlayout androidididlinearlayout4 androidlayout widthfill parent androidlayout heightfill parent androidlayout weight1 androidgravitycenter edittext androidididedittextsearch androidlayout widthwrap content androidlayout heightwrap content androidlayout margin5dp androidlayout weight1 androidhintstringsearch androidimeoptionsactiondone androidinputtypetexturi edittext linearlayout linearlayout androidididlinearlayoutsearch androidlayout widthwrap content androidlayout heightfill parent androidgravitycenter androidclickabletrue imageview androidididimageview1 androidlayout widthwrap content androidlayout heightwrap content androidlayout margin5dp androidsrcdrawablesearch linearlayout linearlayout linearlayout linearlayout androidididlinearlayout6 androidlayout widthfill parent androidlayout heightwrap content androidorientationvertical linearlayout androidididlinearlayout7 androidlayout widthfill parent androidlayout heightwrap content androidbackgrounddrawablelistbg2 linearlayout androidididlinearlayoutmc androidlayout widthfill parent androidlayout heightfill parent androidlayout weight1 androidbackgrounddrawablelbg1 androidgravitycenter textview androidididtextviewmc androidlayout widthwrap content androidlayout heightwrap content androidlayout marginleft5dp androidtextcode androidtextcolorcolorblack linearlayout linearlayout androidididlinearlayoutmn androidlayout widthfill parent androidlayout heightfill parent androidlayout weight1 androidbackgrounddrawablelbg2 androidgravitycenter textview androidididtextviewmn androidlayout widthwrap content androidlayout heightwrap content androidlayout marginleft5dp androidtextname androidtextcolorcolorblack linearlayout linearlayout linearlayout linearlayout androidididlinearlayout10 androidlayout widthfill parent androidlayout heightwrap content androidorientationvertical listview androididandroididlist androidlayout widthfill parent androidlayout heightwrap content androiddividercoloroffwhite listview linearlayoutlinearlayoutand listso3xml isxml version10 encodingutf8linearlayout xmlnsandroid androidlayout widthfill parent androidlayout heightwrap content androidbackgrounddrawablelbg androidorientationvertical textview androidididtextviewnamelist3 androidlayout widthwrap content androidlayout heightwrap content androidlayout margin5dp androidtextappearanceandroidattrtextappearancesmall androidtextcolorcolorblack androidfocusablefalse textview androidididtextviewkunn2list3 androidlayout widthwrap content androidlayout heightwrap content androidlayout marginbottom5dp androidlayout marginleft5dp androidtextappearanceandroidattrtextappearancesmall androidtextcolorcolorblack androidfocusablefalse linearlayout,['android'] +264638,foreman start error serverrb33 missing argument after trying to start foreman i get this error note that it does seem to work on heroku though so i guess this is a strictly local problemhrn039textthechange jon foreman start0220 web1 started with pid 7363022001 web1 usersjonrvmgemsruby193p0gemsrailties321librailscommandsserverrb33in parse missing argument e optionparsermissingargument022001 web1 from usersjonrvmgemsruby193p0gemsrack141librackserverrb280in parse options022001 web1 from usersjonrvmgemsruby193p0gemsrack141librackserverrb180in options022001 web1 from usersjonrvmgemsruby193p0gemsrailties321librailscommandsserverrb54in set environment022001 web1 from usersjonrvmgemsruby193p0gemsrailties321librailscommandsserverrb42in initialize022001 web1 from usersjonrvmgemsruby193p0gemsrailties321librailscommandsrb50in new022001 web1 from usersjonrvmgemsruby193p0gemsrailties321librailscommandsrb50in top required022001 web1 from scriptrails6in require022001 web1 from scriptrails6in main022001 web1 process terminated022001 system sending sigterm to all processesthe procfile only has one line as specified by herokuweb bundle exec rails server thin p port e rack envand my gemfile hasgem thingoogle is not being very helpful with this errorthanks,['ruby-on-rails'] +264658,how to send zip file without creating it on physical location i want to send email with zip file attachment i m able to send pdf files without saving them on physical location using bytearrayoutputstream but when i try zip those file an send it its not working it gives exception illegal attachment below is the code which i have written to create zipprivate mimebodypart zipattachment listbytearrayoutputstream attachmentlist liststring reportfilenames mimebodypart messagebodypart null try file file filecreatetempfile reportsziptmp fileoutputstream fout new fileoutputstreamfile bytearrayoutputstream bout new bytearrayoutputstreamattachmentlistsize zipoutputstream zos new zipoutputstream bout zipentry entry for int i 0 i attachmentlistsize i bytearrayoutputstream attachmentfile attachmentlistget i byte bytes attachmentfiletobytearray entry new zipentry reportfilenamesget i entrysetsize byteslength zosputnextentry entry zoswrite bytes messagebodypart new mimebodypart datasource source new bytearraydatasource bouttobytearray applicationzip messagebodypartsetdatahandler new datahandler source messagebodypartsetfilename reportszip catch exception e todo handle exception return messagebodypart,['java'] +264674,how to create an sql view with sqlalchemy everything is in the title is there a pythonic way i mean no pure sql query to define an sql view with sqlalchemy thanks for your help,['python'] +264694,accessing httpservletrequest object in a normal java class from spring i have a normal java class in a spring mvc 306 web application in this class i would like to inject or get hold of the httpservletrequest object in a method i know i can pass this around but i was wondering how can i get hold of the request without passing it in to the method perhaps using annotations or similaralso what are the real concerns with getting hold of the request this way except some peoples opinions of it being ugly coding i mean is it unstable to access it this waypreferably non application server dependent wayi have seen httpservletrequest requestcontextholdergetrequestcontextgetexternalcontextgetnativerequest but this does not seem to work for spring mvc 306 requestcontextholder does not have the method getrequestcontext,['java'] +264711,java oracle exception maximum number of expressions in a list is 10 i am passing a list of strings to my querysql query written to fetch the required databut i am getting this exception ora01795 maximum number of expressions in a list is 10i checked that i have more than 10 entries in the list passed to the query in parameter,['java'] +264727,javautiluuidfromstring not checking length when i looked into the implementation of javautiluuidfromstring i found that it does not check for the uuid length is there any particular reason for this it only checks the components separated by string components namesplit if componentslength 5 throw new illegalargumentexceptioninvalid uuid string nameshould it also throw illegalargumentexception when length is not 36currently without the length checking numbers are automatically prepended with 0s if less than the component length or shifted if more the downside is if one entered a uuid string with a missing digit it is accepted as valid and prepended with 0 this is hard to debugfor example this 12345678123412341234123456789ab becomes 123456781234123412340123456789ab notice the 0 added and this 12345678123412341234123456789abcd becomes 1234567812341234123423456789abcd with the 1 removedto push this even further the string 12345 will also be treated as valid and becomes 0102030405edit to clarify my question is this a bug or done on purpose to follow some standard or principle,['java'] +264743,create a nsdate from a string i have an nsstring like this 3152012 915 pm and i would like to convert it to nsdate i have done like this nsstring str 3152012 915 pmnsdateformatter formatter nsdateformatter allocinitformatter setdateformatmmddy hhmmnsdate date formatter datefromstringnslog date date nullcan you help me please thanks,"['objective-c', 'ios']" +264766,create copy of exe with different resource at runtime wed like to offer our client the ability to make customised exes based on ours for their clientsie basically the ability to make a copy of an exe with a different xml configuration file embedded in it the include it in the install is not an option we want this to look as if it was custom made for our clients clientsi am currently thinking of writing a dll at runtime including the resource using an assemblybuilder and then calling ilmerge to embed it in the final exe but this is slightly more hackish than i would likeso it is a tallask but perhaps worth asking anyway is there a net library which allows modifying a net exes resources which could avoid the whole dll holding a resource embedded by ilmerge bitor alternatively is there a better approach to this which still meets the stated goals,"['c#', '.net']" +264785,c faster generation of md5 hashes i have a project where i have been given a md5 hash of a number between 1 and 2 billion and i have to write a thistributed program which obtains the number by brute force i have successfully coded this program and it works i was wondering if there is a way to speed up the generation of hasheshere is my current function to generate the hashes static string generatehashstring input md5 md5hasher md5create byte data md5hashercomputehashencodingdefaultgetbytesinput stringbuilder sbuilder new stringbuilder for int i 0 i datalength i sbuilderappenddataitostringx2 return sbuildertostring thanks for any help,['c#'] +264786,is the pdo library faster than the native mysql functions i have read several questions regarding this but i fear they may be out of date as newer versions of the pdo libraries have been released since these questions were answeredi have written a mysql class that builds queries and escapes parameters and then returns results based on the query currently this class is using the builtin mysql functionsi am well aware of the advantages of using the pdo library eg it is compatible with other databases stored procedures are easier to execute etc however what i would like to know is simply is using the pdo library faster then using the mysql builtin functionsi have just written the equivalent class for mssql so rewriting it to work with all databases would not take me long at all is it worth it or is the pdo library slower,"['php', 'mysql', 'sql']" +264794,using regex to match any character except i am trying to write a string validation to match any character regular digit and special except here is what i have written string patternstring wsw pattern p patterncompilepatternstring matcher m pmatcherstr ifmmatches systemoutprintlnmatches else systemoutprintlndoes notbut it matches the input string 20090909 1223125 with the patternhow can i exclude or any other character for that matter from the pattern string,['java'] +264799,c variable has initializer but incomplete type i am trying to compile 2 classes in c with the following commandg catcpp cat maincpp o catbut i receive the following errorcat maincpp1010 error variable acat joeya has initializer but incomplete typecould someone explain to me what this means what my files basically do is create a class catcpp and create an instance cat maincpp here is my source codecatcppinclude iostreaminclude stringclass catusing namespace stdint main cat joeyjoey joeymeow return 0cat maincppinclude iostreaminclude stringusing namespace stdclass cat public catstring str variables string name functions void meowcatcatstring str thisname strvoid catmeow cout meow endl return,['c++'] +264818,how do i set multiple input types in an edittext on android i am trying to create an edittext with autocapitalization and autocorrection implemented i have manually figured out how to add inputfilters to allow autocapitalization though this only works after the first letter is typed and i have had no luck with auto correction i tried to create an inputfilter that used autotext but i am not sure how all that works ideally i could just use edittextsetinputtype to handle everything but so far this has not worked is there a way to achieve this my failed attempt is shown below i just get normal inputedittext medittext new edittextthisint inputtype inputtypetype class textif auto capitalize inputtype medittextgetinputtype inputtypetype text flag cap charactersif auto correct inputtype medittextgetinputtype inputtypetype text flag auto correctmedittextsetinputtypeinputtypeplease note i am only interested in solutions for creating this edittext in code not via xmlediti found sound new documentation describing textkeylistener however after trying to use thismedittextsetkeylistenernew textkeylistenertextkeylistenercapitalizecharacters trueand using farble1670s idea of using setrawinputtype so as not to affect the keylisteners there is still no change to the text,['android'] +264822,mvc3 complex json list binding having issues getting aspnet mvc3 to bind my complex json object that contains a listheres the structure i have for my objectspublic class pagemodel public pagemodel public customobject1 customobject get set public ienumerablecustomobject2 objects get set public class customobject1 public customobject1 required public int customid1 get set public string customname get set public class customobject2 public customobject2 required public int custom2id get set public customobject3 subitem get set public int subitemid get set you can assume customobject3 is of similar structure no need to duplicate yet another made up class so i figure you can use your imagination heres the javascriptjquery that makes the post call assume all the js leading up to this provides the correct dataobj1 has all data for the first objectvar firstobj firstobjcustomid1 obj1idfirstobjcustomname obj1namevar i 0objects is an array with all the dataeachobjects function objsarrayi custom2id thisid subitemid thisitemid iajax type post url actionmethod data customobject firstobj objects objsarray successerror handlers hereand finally i know quite some code heres an overview of the method i havepublic class actioncontroller controller public jsonresult methodpagemodel model gets here modelcustomobject is filled correctly and modelobjects has a correct count of whatever data i passed to the method but all of the properties are empty as i said the first object is filled and all of the data is there when i debug and step through if i pass two objects in the objects array in the json object i see a count of 2 in the controller but custom2id and subitemid are empty what giveswhen i specify a contenttype of applicationjson in my ajax call mvc complains about the data being passed also tried splitting the model parameter in the mvc method into two separate parameters but it does not helpany help is greatly appreciated this one has me stumped,['jquery'] +264828,beveling a pathshape in core graphics i am trying to bevel paths in core graphics has anyone done this already for arbitrary shapes and if so are they willing to share codei have included my implementation below i use three variables to determine the bevel cgfloat bevelsize uicolor highlightcolor uicolor shadow note that the angle of the light source is always 135 degrees i have not finished implementing this yet but heres essentially what i am trying to do split into two parts part one generate focal pointsi find the bisectors for the angles between each adjacent lines in the path for arcs the bisector is the line perpendicular to the line created by the two end points of the arc originating from the midpoint this should take care of the majority of situations in which an arc is used i do not take the bisector of an arc and a line the arc bisector should work fine in those casesi then calculate focal points based on the intersection of each adjacent bisectorsif a focal point is within the shape it is used otherwise it is thiscardedthe purpose of generating the focal points is to shrink the shape proportionally the second part is a little more complicated i essential create each sidesegment of the bevelled shape i do this by drawing in by the bevelsize each point of the original shape along radius of the line that extends from the nearest focal point to the point in question when i have two consecutive bevelpoints i create a uibezierpath that extends along from the bevelpoints to the original points and back to the bevelpoints note this includes arcs this creates a sidesegment i can use to fill on straight sides i simply fill with either the shadow or highlight color depending on the angle of the side for arcs i determine the radian arc if that arc contains a transition angle m pi 4 or m pi m pi 4 i fill it with a gradient from shadow to highlight or highlight to shadow which ever is appropriate otherwise i fill it with a solid colorupdatei have split out my answer see below into a separate blog post i am not longer using the implementation details you see above but i am keeping it all there for reference i hope this helps anybody else looking to use core graphics,['objective-c'] +264845,javascript async loop processing i have a javascript loop that takes some time to process i wish i could slim it down but it has to process a large amount of data while it is running the browser becomes unresponsive of course i have read the best way to handle this in javascript is using an asynchronous loop of some sort this way mouse clicks etc can continue to be processed in between loop processing is there any standard async frameworks that will work well for this or can someone provide a simple example of how this might be coded thanks,['javascript'] +264871,pythonsqlite3 cannot commit no transaction is active i am trying to code a book indexer using python traditional 27 and sqlite 3the code boils down to this sequence of sql statementsselect count from tag dict 30 select count from file meta 63613 begin transaction select id from archive where name 158326158457zip 20 select id from file where name and archive 158328fb2 20 122707 delete from file meta where file 122707commit transaction error cannot commit no transaction is activethe isolation level is deferred exclusive is no betteri have attempted to use connectioncommit instead of cursorexecutecommit nothing useful happenedsure i have searched stackoverflow and the net but the answers found are irrelevantautocommit mode is unacceptable for performance reasoni use the only database file at a timemy code runs in single threadall the sql execution is being done via single function that ensures that i have no more than only one cursor open at a timeso whats wrong with transaction hereif i use connectioncommit note there is no connectionbegin method then i merely loose my datasure i have doubetriplequaruple checked file permissions on the database file and its directorywell as it often happens i found the solution just a minutes after posing the questionas a newbie i cannot anwer my own question for 8 hoursso the anwer is now therethe solution was found here and consists of the only ideanever use begincommit in non autocommit mode in python application use dbcommit and dbrollback onlyit sounds odd but it works,['python'] +264874,css change color of hr tag possible duplicatecss change color of hr tag how do you change the color of an hr tag i looked it up and found this but it didnt workhr colorc backgroundcolorcany ideas,"['html', 'css']" +264881,csprojuser issues when checked into tfs we made the mistake of allowing csprojuser files to be checked in to tfs so we could set start external program defaults this worked poorly especially when branchingnow were trying to undo thisif i delete the csprojuser file for a project and then try to set new project debug properties i gettf14050 cannot change item xcsprojuser because it already has a pending change that is not compatibleif i check in the delete and make changes tfs then tries to readd my csprojuser filehow can we fix this for existing projects in source controlupdatei think destroying them is the best option we ended up just deleting them with the tfs power tools though the trick was to first remove the source control file type we had for user even though it was already thisabled now tfs appears to completely ignore these files,['c#'] +264893,haml if elsif construction i need this construction in my haml code if something1 diva elsif something2 divb elsif something3 divc else divd div another contenti would expected i get something likediv classabcd divanother contentdivdivbut in the fact i get div classabcddiv divanother contentdivhow i must to update my code if i need to get another content,['ruby'] +264916,why does height and top attribute not work when position is relative this will position the box a little below the topdiv styleheight 10em width 50 left 25 top2em position relative background whitehello worlddivthis will position the box near the top and it looks like neither the height nor top property isworking the height of the box is not 50 and the box is not 50 below the top div styleheight 50 width 50 left 25 top20 position relative background whitehello worlddivi am pretty much a beginner at this stuff but it would seem if left and width work with a percentage should not top and height,"['html', 'css']" +264947,binary tree using php mysql i am implementing an mlm tree for a website using php codeigniter and mysql i need a binary tree implementation in the database the followings things are to be considered for each node minimum of the number of childrennodes in left subtree and the number of childrennodes in right subtree is called a pair for each pair one nodes gets 1 point which should be stored in database nodes represent userswhen a new node is created wherever it is possible that many of the nodes pair is incremented so whenever a node is created every nodes point should be updatedincremented by one when applicableanother constraint is each day any node can not have more than 100 pointsi also need to construct thisplay in a webpage the tree only 45 levels are to be shownthe database is likely to have 10 nodesi have found mainly 4 models for implemmenting hieararchical data in mysqlphpadjacency list path enumeration nested sets closure tableso i would like to find a solution that will reduce the insertion overhead and successfully update the points for all nodes applicablei have tried the adjacency list solution node id parentid leftchildidrightchildidleftcountrightcount userstatidsdatepairsmlmincomeeach time one node is insertedi go upward and keep incrementing the child counts if new pair is made then i increment that also and increment the pointi am doing these with stored proceduresthe reason why i chose this solution over nested set is for each node inserted the number of nodes to be updated for nested set is always more than adjacency listthough the rate of constructing tree is more than insertion and nested set is better in constructing trees am i in the right direction please help thnx in advance,"['php', 'mysql']" +264959,developing same app on two different computers i am using eclipse to develop an app and i have two computers a desktop and laptop that i want to use to develop this app i recently set up my laptop with eclipse and imported the project over to that computer however i realized that i cannot launch the application from my laptop onto my phone because the signature that is automatically generated when i build the app from my desktop does not match the one that is automatically generated on the laptop unless i uninstall it on the phone does anyone know how to export the automatically generated signature from one eclipse and import it into another,['android'] +264971,gapless transition from video to video using html5 i am trying to create a feature where a user can change back and forth between multiple videos while maintaining a single consistent audio think of being able to watch a concert from multiple angles but listening to a single audio the trouble i am having with this feature is that there can not be a lag between the changes in video or the audio will no longer sync with the videos especially true after multiple changesi have tried two methods both using html5 only i would prefer not use flash although i will eventually have a fallback that have not worked seamlessly although depending on the browser and hardware it can come very closebasic methodsmethod 1 preloading all videos and changing the video src path on each click using javascriptmethod 2 again preloading video and using multiple tags and changing between them using javascript on each clickis there anyway to get either of these two methods to work seamlessly without a gap should i be using a slight of hand trick like playing both videos concurrently for a second before revealing the second and stoping the first can this just not be done with html5 players can it be done with flashi have seen this type of question a couple of times with both video and audio with no clear solution but they were a couple of months old and i was hoping there is now a solution thanks for the help,['javascript'] +264983,are floats bad what should be used in its place i have made the jump from table design to css about a week ago and have since been reading more about it yesterday i read a long post here on so where the posters were knocking floats and about how depreciated they are there was a lot of talk about inlineblock being used in its placei have a html5 design that i just finished and it looks fantastic in firefox and chrome but when tested from other computers running explorer versions 7 8 and 9 the design absolutely explodes it seems to me that anything in this design that i have floated right is not honored in ie it just seems to wrap under whatever is to the left of iti would like to know if i am ok with floats or if i should i be using inlineblock instead an example of how to have two divs next to one another where one is on the left side and the other on the right using inlineblock would be nicei have another dilemma here that hopefully someone can help me with i am on an old development machine running xp sp1 the best ie browser i can test with is 6 i would like to somehow get a hold of something that will allow me to test versions 7 8 and 9 and 10 if it is out yet can someone recommend any solution for this,['css'] +265020,whats the correct way to expose a requirejs module to the global namespace i want to expose a javascript api as a standalone library without polluting their global namespace i have created the wrapper so i do not pollute their own requirejs according to i have simplified what i have so far as below but i am not sure if this is the correct way or if i should be doing it some other wayvar myapi myapi var myapirequirejs function requirejs pasted here return requirejs requirejs require require define definefunctionrequire define requirejs requireconfig baseurl jsscripts waitseconds 30 define myapi jquery underscore function noconflicttrue noconflict function apimethod args callback do stuff here return api api require myapi function myapi myapi myapi myapirequirejsrequire myapirequirejsdefine myapirequirejsrequirejssites using this library would include a script tag referencing the above code and then call the api usingmyapiapisome remote method foo bar functionresult handle the result,['javascript'] +265057,is writing a daemon in python a good idea i have to write a daemon program that constantly runs in the background and performs some simple tasks the logic is not complicated at all however it has to run for extended periods of time and be stable i think c would be a good choice for writing this kind of application however i am also considering python since it is easier to write and test something quickly in it the problem that i have with python is that i am not sure how its runtime environment is going to behave over extended periods of time can it eat up more and more memory because of some gc quirks can it crash unexpectedly i have never written daemons in python before so if anyone here did please share your experience thanks,['python'] +265067,c const pointer declaration i am reviewing some code and i ran across some code i am unfamiliar with after some searching i could not come up of any example of why this is done or the benefit of this declaration myclass const const myptr myclassgetpointeris this a declaration of a const pointer or something entirely different,['c++'] +265108,highlevel system language that compiles to c i am looking for a higherlevel system language if possible suitable for formal verification that compiles to standard c so that it can be run crossplatform with relatively low overheadthe two most promising such languages i have stumbled during the past few days arebitc while the design goals of this language match my needs it even supports the functional paradigm it is in very unstable state the documentation is out of date and generally it seems like a very long shot for a realworld projectlisaac it supports designbycontract which is very cool and has a relatively low performance overhead however the website is dead there has not been a new release since 08 and generally it seems the language is deadi would also like to note that it is not meant for a realtime system so a gc or generally nondeterminism in the realtime sense is not an issuethe project involves mainly audio processing though it has to be crossplatformi assume someone would point me to the obvious answer plain ol c while it is truly crossplatform and very effective the code quantity would probably be greateredit i should clarify that i mean crossplatform and crossarchitecture that is why i consider only languages compiled to c in the first place but if you can point me to another example i would be grateful,['c'] +265124,the import javaxservletannotation cannot be resolved im trying to create servlet for my project but encountered the import javaxservletannotation cannot be resolved i have already added javaxservlet and servletapijar from tomcat please refer the image below,['java'] +265143,why is mcrypt encrypt putting binary characters at the end of my string here is a php demo script that encrypts and decrypts dataencryptionkey h8y2p9d1card nbr 1234echo original card nbr card nbr brncard nbr encryptedencrypt datacard nbrecho card nbr encrypted card nbr encrypted brncard nbr decrypteddecrypt datacard nbr encryptedecho card nbr decrypted card nbr decrypted brnlenstrlencard nbr decryptedecho length len brnfunction encrypt datatext global encryptionkey iv size mcrypt get iv sizemcrypt rijndael 256 mcrypt mode ecb iv mcrypt create iviv size mcrypt rand encrypted text mcrypt encryptmcrypt rijndael 256 encryptionkey text mcrypt mode ecb iv return encrypted textfunction decrypt datatext global encryptionkey iv size mcrypt get iv sizemcrypt rijndael 256 mcrypt mode ecb iv mcrypt create iviv size mcrypt rand decrypted text mcrypt decryptmcrypt rijndael 256 encryptionkey text mcrypt mode ecb iv return decrypted textthe output isoriginal card nbr 1234card nbr encrypted vya zag3a34a13a2aarza vacard nbr decrypted 1234 and 28 binary characterslength 32 the output is successfully decrypted but 28 binary characters are added to the end this can most easily be seen in firefox when viewing html sourcethe string length of 32 also demonstrates this any ideas,['php'] +265181,bidirectional map can you suggest a kind of map or similar data structure where we can get both the value and key from each other at equal ease that is to say that each may be used to find other,['java'] +265229,how do i create a delete button on every row using the slickgrid plugin how do i create a delete button on every row using the slickgrid plugin i need a button that can delete the whole corresponding row,['jquery'] +265238,function with variable number of arguments as the title says i need to know if there is a corresponding syntax as javas in method parameters likevoid printreportstring header int numbers numbers represents varargs systemoutprintlnheader for int num numbers systemoutprintlnnum code courtesy of wikipedia,"['c#', 'java']" +265241,items list or item list english is not my native language and i cannot understand how to write the specified samples rightwhen you say something what aggregates plural object such as collection of stamps you can say alternatively stamps collection am i right if you will say stamp collection it will mean some collection which is a single stampbut often i see classes with names like itemlist does not it mean that such class is a list which is an item of something elsesuch sample is more flaringclass itemlist listitemis not it have to be soclass itemslist listitemwhy is it rarely written so or is it some programming languages naming convention or just proper english sentences,['c++'] +265248,how to get the request parameters in symfony2 i am very new to symfony in other languages like java and others i can use requestgetparameterparmeter name to get the valueis there anything similar that we can do with symfony2i have seen some examples but none is working for me suppose i have a form field with the name username in the form action i tried to use something like thisrequest thisgetrequestusername requestrequestgetusername i have also tried username requestgetparameterusername andusernamerequestrequestgetparameterusernamebut none of the options is workinghowever following worked fineforeachrequestrequestall as req print rrequsernamewhere am i doing wrong in using getparameter method any help will be appreciated,['php'] +265278,save curl content result into a string in c int mainvoid curl curl curlcode res curl curl easy init ifcurl curl easy setoptcurl curlopt url curl easy setoptcurl curlopt ssl verifypeer 0l curl easy setoptcurl curlopt ssl verifyhost 0l res curl easy performcurl curl easy cleanupcurl getch return 0string contents i would like to save the result of the curl html content in a string how do i do thisit is a silly question but unfortunately i could not find anywhere in the curl examples for cthanks,['c++'] +265336,assign class boolean value in python if statements in python allow you to do something like if not x print x is falsethis works if youre using an empty list an empty dictionary none 0 etc but what if you have your own custom class can you assign a false value for that class so that in the same style of conditional it will return false,['python'] +265357,select multiple rows in one result row in one of my tables i store my advertisement data thats one row per advertisementi also store some dates in an other table but that is one row per date because i do not know howmany dates a specific advertisement getsi want to select al the dates where id adventisement 1 in the same query as the data selection seperated bij a komma only problem is that i get as many rows as there are dates i only want one row with al the dataatable 1 advertisementsid adv data 1 data21 name1 picture12 name2 picture2 3 name3 picture34 name4 picture4table 2 datesid id adv date1 2 1120122 2 2120123 3 1120124 3 2120125 3 3120126 3 412012outcome query select id adv data1 data2 dates where id adv 33name3picture3112012212012312012412012the dates column can be one string with al the dates seperated by a commany ideas,['mysql'] +265358,how do i obtain an id that allows me to tell difference instances of a class apart imagine i have a single class with two instancesmyclass a new myclassmyclass b new myclassmyclass has a method printuniqueinstanceidvoid printuniqueinstanceid consolewriteunique id for the instance of this class 0 what goes here ideally the output would be something likeunique id for the instance of this class 23439434 from aprintuniqueinstanceidunique id for the instance of this class 89654 from bprintuniqueinstanceidso what would i insert in what goes here above which prints a unique number for every unique instance of the classideasperhaps cast this to an int pointer and use thatuse gchandle somehow access a property of this within the method to uniquely identify itoptional background information for expertsthe reason i need this is that i am using aop and postsharp to automatically detect threading issues i need to look up each unique instance of the class in a dictionary in order to verify that multiple threads are not accessing the same unique instance of a class its ok if there is one thread per class instanceupdateas others have pointed out i should mention that i cannot touch any of the existing classes in the 30 line project printuniqueinstanceid above is an aspect see postsharp that is added to the top level class is inherited by every class in the entire project and executes on every method entry in the entire projectonce i have verified that everything is thread safe i will remove the aspect to restore performance,"['c#', '.net']" +265403,how to add a view behind other view in ios i want to add a view under my tab bar analog in ios and then show it with animation coming from behind it but when i use my code the view that must come from behind my tab bar overlaps my tab bar for a while this is my code voidhandlepressedbutton if pressedbuttonselected uiview beginanimationsnil contextnil uiview setanimationduration05 cgaffinetransform transform1 cgaffinetransformmaketranslation1960 00 cgaffinetransform transform2 cgaffinetransformmaketranslation00 00 leftpanelview settransformtransform1 movedview settransformtransform2 uiview commitanimations pressedbuttonselected noelse pressedbuttonselected yes if leftpanelview leftpanelview removefromsuperview leftpanelview nil cgrect viewframe cgrectmake196 0 236 748 leftpanelview uiview alloc initwithframeviewframe leftpanelviewbackgroundcolor uicolor colorwithpatternimageuiimage imagenamedleftnavcontentpng code to populate leftpanelview according to what button is pressed self populateleftpanelview uiview beginanimationsnil contextnil uiview setanimationduration05 selfview addsubviewleftpanelview cgaffinetransform transform1 cgaffinetransformmaketranslation2360 00 cgaffinetransform transform2 cgaffinetransformmaketranslation1120 00 leftpanelview settransformtransform1 movedview settransformtransform2 uiview commitanimationshere the leftpanelview is the view that must come under a tab bar moved view is another view that is at the right of left panel do not mind it,"['iphone', 'ios']" +265409,why supergetclass in a subclass returns subclass name i am inside a subclass and when i am trying to find the name of super class i tried supergetclass but it is returning me the name of the subclass onlywhy,['java'] +265427,the memcache extension must be loaded for using this backend i got memcached installed this is from phpinfobut when using it like thisprivate static function getzendcachememcachedobject frontendopts array caching true lifetime 3600 automatic serialization true backendopts array servers array array host localhost port 11211 weight 1 compression false return zend cachefactorycore memcached frontendopts backendoptspublic function fooid cache selfgetzendcachememcachedobject cachekey foo id xml cacheloadcachekey if false xml xml thishttpclientfoo cachesavexml cachekey return xmli get this errorthe memcache extension must be loaded for using this backendany ideas,['php'] +265430,inefficient use of string concatenation i was creating a logger in my javaapp with netbeans as ide when suddenly i saw a warning saying inefficient use of string concatenation in loggermy oringinal code issrcloggergetloggerloglevelinfouploadbeandoupload completado filegetname nbut netbeans suggested to convert it to a template what a template means here giving this codesrcloggergetloggerloglevelinfo uploadbeandoupload completado 0n filegetnamewhats the different between these two ways of concatenation i never used the latter thoughcheers,['java'] +265447,vs 2010 remote debugger breakpoint will not currently be hit no symbols have been loaded for this document 1 make an windows account on host machine log in2 make an windows account with same user name and password as host machine on the remote machine log in3 copy all pdb files to same directory as exe on the remote machine4 run remote debugger on the remote machine5 tools options6 radio button to no authentication native only and check allow any user to debug ok7 run the exe debug build on the remote machine8 on the host machine open your solution9 debug attach to process10 transport remote native only with no authentication 11 qualifier server ip12 refresh13 choose the application to debug14 attachapplication seems to be running in the visual studio but all the breakpoints grey out with the following comment breakpoint will not currently be hit no symbols have been loaded for this documenti did the folowing i deploy my applicatiob including the pdb files in the remote pc under cabci add the symbols location as you can see in the screenshot and i try to debug from my pc to the remote pc butstill no breackpointany idea,['c#'] +265475,should i use thin or unicorn on heroku cedar i recently upgraded my app to the cedar platform on heroku by default i am using thin as a web server but i have always been tempted to use unicorn for concurrency and having my dyno dollar go father but i worry there are some gotchas in using something other than thindoes anyone have real life experience with this decisionthanksjonathannotesthis was the article that got me excited about the idea i know every app is different and that you should build a staging env and try it for yourself but if it looks great in your staging env are they any pitfalls that we should know abouti want to know reasons why everyone should not do this,['ruby-on-rails'] +265476,how do apache httpd and tomcat work together i am inheriting a project involving a java web app whose backend is powered by an apache httpdtomcat combo the web server is being used to serve back js static content and to perform general load balancing and tomcat is serving back jsps via a single war filei will be receiving access to the code base later on today or tomorrow but wanted to try and do some research ahead of timemy question can be summed up as how do these two work togetherwho first receives http requestshow does httpd know when to forward jsp requests on to tomcat or to just respond to a request itselfhow does httpd pass the request to and receive the response from tomcat does it just copynpaste the requestresponse to a port tomcat is listening on is there some sort of oslevel interprocess communication going on etcthese are just general questions about how the technologies collaborate with each other thanks in advance,['java'] +265486,gc tuning preventing a full gc i am trying to avoid the full gc from gclog sample belowrunning a grails application in tomcat in productionany suggestions on how to better configure the gc14359317 full gc 14359317 cms 3453285k3099828k4194304k 131778420 secs 4506618k3099828k6081792k cms perm 261951k181304k264372k icms dc0 131786310 secs times user1315 sys004 real1318 secs my vm params are as followxms6gxmx6gxxmaxpermsize1g xxnewsize2g xxmaxtenuringthreshold8 xxsurvivorratio7xxuseconcmarksweepgc xxcmsclassunloadingenabled xxcmspermgensweepingenabled xxcmsincrementalmode xxcmsinitiatingoccupancyfraction60 xxusecmsinitiatingoccupancyonly xxheapdumponoutofmemoryerror xxprintgcdetails xxprintgctimestamps xxprinttenuringthistribution dsunreflectinflationthreshold0 14169764 gc 14169764 parnew desired survivor size 107347968 bytes new threshold 8 max 8 age 1 15584312 bytes 15584312 total age 2 20053704 bytes 35638016 total age 3 13624872 bytes 492628 total age 4 14469608 bytes 63732496 total age 5 10553288 bytes 74285784 total age 6 11797648 bytes 86083432 total age 7 12591328 bytes 98674760 total 1826161k130133k1887488k 01726640 secs 5216326k3537160k6081792k icms dc0 01733010 secs times user066 sys003 real017 secs 14218712 gc 14218712 parnew desired survivor size 107347968 bytes new threshold 8 max 8 age 1 25898512 bytes 25898512 total age 2 10308160 bytes 36206672 total age 3 16927792 bytes 53134464 total age 4 13493608 bytes 628072 total age 5 14301832 bytes 80929904 total age 6 10448408 bytes 91378312 total age 7 11724056 bytes 103102368 total age 8 12299528 bytes 115401896 total 1807957k147911k1887488k 01664510 secs 5214984k3554938k6081792k icms dc0 01671290 secs times user061 sys0 real017 secs 14251429 gc 14251430 parnew desired survivor size 107347968 bytes new threshold 7 max 8 age 1 25749296 bytes 25749296 total age 2 2018 bytes 45861184 total age 3 7580776 bytes 53441960 total age 4 16819072 bytes 70261032 total age 5 13209968 bytes 834710 total age 6 140856 bytes 97559856 total age 7 10371160 bytes 107931016 total age 8 11426712 bytes 119357728 total 1825735k155304k1887488k 0180 secs 5232762k35742k6081792k icms dc0 01895340 secs times user074 sys006 real019 secs 14291342 gc 14291343 parnew desired survivor size 107347968 bytes new threshold 7 max 8 age 1 25786480 bytes 25786480 total age 2 21991848 bytes 478328 total age 3 16650 bytes 64428328 total age 4 7387368 bytes 71815696 total age 5 167584 bytes 88593280 total age 6 13098856 bytes 101692136 total age 7 14029704 bytes 115721840 total 1833128k151603k1887488k 01941170 secs 5252046k3591384k6081792k icms dc0 01947390 secs times user082 sys004 real020 secs 14334142 gc 14334143 parnew desired survivor size 107347968 bytes new threshold 6 max 8 age 1 31541800 bytes 31541800 total age 2 208268 bytes 52368688 total age 3 19155264 bytes 71523952 total age 4 164240 bytes 87946192 total age 5 7235616 bytes 95181808 total age 6 165490 bytes 1730808 total age 7 13026064 bytes 124756872 total 1829427k167467k1887488k 01890190 secs 5269208k3620753k6081792k icms dc0 01896630 secs times user080 sys003 real019 secs 14359317 full gc 14359317 cms 3453285k3099828k4194304k 131778420 secs 4506618k3099828k6081792k cms perm 261951k181304k264372k icms dc0 131786310 secs times user1315 sys004 real1318 secs 14373287 gc 1 cmsinitialmark 3099828k4194304k 31094k6081792k 00107380 secs times user001 sys0 real0 secs 14373298 cmsconcurrentmarkstart 14472579 gc 14472579 parnew desired survivor size 107347968 bytes new threshold 8 max 8 age 1 42849392 bytes 42849392 total 1677824k86719k1887488k 01056680 secs 47652k3186547k6081792k icms dc0 01063280 secs times user061 sys0 real011 secs 14506980 gc 14506980 parnew desired survivor size 107347968 bytes new threshold 8 max 8 age 1 42002904 bytes 42002904 total age 2 35733928 bytes 736832 total 1764543k96136k1887488k 00982790 secs 4864371k3195964k6081792k icms dc0 00988960 secs times user053 sys001 real010 secs 14544285 gc 14544286 parnew desired survivor size 107347968 bytes new threshold 8 max 8 age 1 26159736 bytes 26159736 total age 2 37842840 bytes 64002576 total age 3 33192784 bytes 97195360 total 1773960k130799k1887488k 01208590 secs 4873788k3230628k6081792k icms dc0 01215900 secs times user059 sys002 real013 secs 14589266 gc 14589266 parnew desired survivor size 107347968 bytes new threshold 4 max 8 age 1 28010360 bytes 28010360 total age 2 21136704 bytes 49147064 total age 3 35081376 bytes 84228440 total age 4 32468056 bytes 116696496 total 1808623k148284k1887488k 01423150 secs 4908452k3248112k6081792k icms dc0 01429440 secs times user070 sys002 real014 secs 14630947 gc 14630947 parnew desired survivor size 107347968 bytes new threshold 8 max 8 age 1 28248240 bytes 28248240 total age 2 20712320 bytes 48960560 total age 3 18217168 bytes 671728 total age 4 34834832 bytes 102012560 total 1826108k140347k1887488k 01784680 secs 4925936k3275469k6081792k icms dc0 01790920 secs times user098 sys003 real018 secs 14664779 gc 14664779 parnew desired survivor size 107347968 bytes new threshold 5 max 8 age 1 258410 bytes 258410 total age 2 264960 bytes 48105960 total age 3 17730104 bytes 65836064 total age 4 17988048 bytes 83824112 total age 5 34739384 bytes 118563496 total 1818171k147603k1887488k 01714160 secs 4953293k3282725k6081792k icms dc0 01720530 secs times user082 sys011 real017 secs 14702488 gc 14702489 parnew desired survivor size 107347968 bytes new threshold 8 max 8 age 1 26887368 bytes 26887368 total age 2 21403352 bytes 48290720 total age 3 187324 bytes 67022944 total age 4 17640576 bytes 84663520 total age 5 17942952 bytes 102606472 total 1825427k142695k1887488k 02118320 secs 4960549k3312168k6081792k icms dc0 02124630 secs times user113 sys014 real021 secs the strategy i was aiming ati want to limit to the minimum what gets tenured i am serving requests and expect that beyond a certain amount of shared objects every other objects are useful only to the request at hand therefore by using a big newsize and an increased tenuringthreshold and was hoping to have none of these single serving objects stick aroundthe following are there to support my strategyxms6gxmx6gxxnewsize2g big space so that parnew does not occur to often and let time for objects to expirexxmaxtenuringthreshold8 to limit the tenuring some morexxsurvivorratio7 based on examplesxxcmsinitiatingoccupancyfraction60 to prevent a full gc caused by promotion allocation failedxxusecmsinitiatingoccupancyonly to go with the one above based on examplemaxpermsize1g and dsunreflectinflationthreshold0 are related to another issue i would rather keep separatedxxcmsclassunloadingenabled and xxcmspermgensweepingenabled are there because of grails which rely heavily and extra classes for closures and reflexionxxcmsincrementalmode is an experiment which has not yield much success,['java'] +265489,php mongo query not null anyone know the syntax for writing a phpmongo query to use not nulli know how to do this when i query for nullphpcursor collectionfindarraysomefield nullis this even possible,['php'] +265526,modifying the params hash in rails i am creating a nested model in rails but i want to add fields to the nested models in the controller i am not using hidden field tag since it could be tampered withhere is my params hash parameters dummyusers attributes0email id destroyfalse 1email id destroyfalse commitcreate dummywhat i want is for there to be a field under each user attributes called companyid let us say i wanted companyid to be company then i thought that this would worklen paramsdummyusers attributessize counter 0 while counter len paramsdummyusers attributescountercompanyid company counter counter 1endbut i get undefined method for nilnilclass error for the first line in the while loop i am not exactly sure whycan someone help me out so i can modify the params hash editso i finally figured it out i did not really use any of the solutions exactly first i set a hidden field tag to be blank for companyid then in my controller i put paramsdummyusers attributeseach do key val paramsdummyusers attributeskeycompanyid company endnot the most elegant code but it will work,['ruby-on-rails'] +265553,how to stop uitableview cell is overwriting the contents i am using a uitableview and i am noticing that the cells in my tableview are getting progresively bolder as i scroll it is overwriting the contents and i want to stop this but cannot see where i am going wrongon my uitableview for some reason when i scroll the contents of the tableview get messed up with the the manually created uilabeli require a manual uilabel because i need to have custom cells later onas i scroll up and down the labels get progressively bolder and bolder they always overlap and sometimes even affects rows lower down even before they are in the viewportif i keep doing it the cell contents become unintelligablethis only happens if there the backgroundcolor is not set as clearcolori have attempted celabel setclearscontextbeforedrawingyes and selftableview setclearscontextbeforedrawingyes to no effectif i use celltextlabeltext then the problem seems to go awaycode and an image sample follows simple table view uitableviewcell tableviewuitableview tv cellforrowatindexpathnsindexpath indexpath static nsstring cellidentifier cell uitableviewcell cell tableview dequeuereusablecellwithidentifiercellidentifier if cell nil cell uitableviewcell alloc initwithstyleuitableviewcellstyledefault reuseidentifiercellidentifier autorelease configure the cell self configurecellcell atindexpathindexpath nsstring txt product celltextlabeltext txt cellselectionstyle uitableviewcellselectionstylenone uiview cellview uiview alloc initwithframecgrectmake0 0 200 cellframesizeheight uilabel celabel uilabel alloc initwithframecgrectmake20 10 120 35 celabel settexttxt celabel setfontuifont boldsystemfontofsize12 celabel setbackgroundcoloruicolor clearcolor cellview addsubviewcelabel celabel release cellcontentview addsubviewcellview cellview release return cell image followsimage of uitableview1 1 edit to include contexti am using a dictionary to thisplay the contents of the uitableviewcellsi have attempted to do the following uitableviewcell tableviewuitableview tv cellforrowatindexpathnsindexpath indexpath static nsstring cellidentifier cell uitableviewcell cell tableview dequeuereusablecellwithidentifiercellidentifier if cell nil cell uitableviewcell alloc initwithstyleuitableviewcellstyledefault reuseidentifiercellidentifier autorelease self configurecellcell atindexpathindexpath end if configure the cell moved to inside the cellnil return cell voidconfigurecelluitableviewcell cell atindexpathnsindexpath indexpath get the txt from the dictionaryplist removed due verboseness uilabel celabel uilabel alloc initwithframecgrectmake20 10 120 35 celabel settexttxt celabel setfontuifont boldsystemfontofsize12 celabel setbackgroundcoloruicolor clearcolor cellcontentview addsubviewcelabel celabel releasethis although it fixes the problem of overwriting it causes a problem it makes labels repeatedly appear in totally random places the following is just an example other fields and labels also repeatsee picture below,"['objective-c', 'ios']" +265573,jenkins cannot run xcodebuild from project folder i am attempting to set up a ci environment for an ios application so far i have gotten xcodebuild to build the test build correctly from the command line but when jenkins tries to execute it i get the following read out in the consolestarted by user anonymousbuilding in workspace userssharedjenkinshomejobsunit testsworkspaceworking directory is usersiosappdevdocumentsxcode projectsrulesrules usrbinxcodebuild versionfatal cannot run program usrbinxcodebuild in directory usersiosappdevdocumentsxcode projectsrules error13 permission deniedjavaioioexception cannot run program usrbinxcodebuild in directory usersiosappdevdocumentsxcode projectsrules error13 permission denied at javalangprocessbuilderstartprocessbuilderjava460 at hudsonproclocalprocinitprocjava244 at hudsonproclocalprocinitprocjava216 at hudsonlauncherlocallauncherlaunchlauncherjava707 at hudsonlauncherprocstarterstartlauncherjava338 at hudsonlauncherprocstarterjoinlauncherjava345 at aucomrayhxcodebuilderperformxcodebuilderjava224any thoughts i am fairly new to jenkins but i have done my best to answer this question with google fu to no avail i did originally run into this problem with a manual installation of jenkins homebrew technically but recently used the osx installer and it resulted in the same errori am guessing this has more to do with unixlinuxosx permissions than jenkinsxcode but do not have enough expertise to determine that for certaineditproject directory permissions set to 775i have also tried changing the ownership to the user jenkins runs onheres the output for when i attempted to run xcodebuild as the daemon user sudo u daemon xcodebuilddevimacrules iosappdev sudo u daemon xcodebuildshellinit error retrieving current directory getcwd cannot access parent directories permission deniedshellinit error retrieving current directory getcwd cannot access parent directories permission denied20120321 110546161 xcodebuild141170b mt dvtassertions assertion failure in sourcecacheidexcode3projectsupportidexcode3projectsupport1196xcode3sourcesxcodeideframeworksdevtoolsbasepbxcorexcode3modelxcode3projectm266details assertion failed directorypath isabsolutepathobject xcode3projectmethod projectfilesindirectorythread nsthread 0x40010a260name null num 1hints nonebacktrace 0 0x010025b85f dvtassertionhandler handlefailureinmethodobjectfilenamelinenumbermessageformatarguments in dvtfoundation 1 0x010025b6b5 dvtassertionfailurehandler in dvtfoundation 2 0x01011559bc xcode3project projectfilesindirectory in devtoolscore 3 0x01008a424b xcode3commandlinebuildtool resolveinputoptions in xcode3core 4 0x01008aa097 xcode3commandlinebuildtool run in xcode3core 5 0x01001d7db6 in xcodebuild 6 0x01001d7c2c in xcodebuild,['ios'] +265637,rails 322 or 321 postgresql 913 ubuntu 10 connection error i am using postgresql 913 postgresql 913 on x86 64pclinuxgnu compiled by gcc46real ubuntulinaro 4619ubuntu3 461 64bit and rails either 322 or 321 on ubuntu 10now i can connect with below command with postgresqlsu postgresenter password and i can see postgresi am placing below details in my configdatabaseyml and executing rails db it is working finedevelopmentadapter postgresqlencoding utf8reconnect falsedatabase sample app dbpool 5username postgrespassword passwordherehost localhosti am using rvm to access my rails environment but when i start server using rails s command and hit url with httplocalhost30 say connection not establish,['ruby'] +265649,css transitions with before and after pseudo elements cannot seem to animate pseudo elements with webkittransition the fiddle below shows what i mean when run in chromesafari i guess this is not supported right now,['css'] +265650,when to use left join and when to use inner join i feel like i was always taught to use left joins and i often see them mixed with inners to accomplish the same type of query throughout several pieces of code that are supposed to do the same thing on different pages here goesselect acreac ptpt name socsoc name ptpt soc codefrom aecounts ac inner join 1 low level term llt on acreac lltllt name left join 1 pref term pt on lltpt code ptpt code left join 1 soc term soc on ptpt soc code socsoc codelimit 10010thats one i am working oni see a lot likeselect countthistinct pcase as countfrom fda casereports cr inner join ae indi i on iisr crisr left join ae case profile p on crisr pisrthis seems like the left may as well be inner is there any catch,['mysql'] +265692,decode audio using libavcodec and play using libao i use following code snippet to decode audio files tested with mp3wavwmvbut when it plays the audio it just gives static sounds and crashes time to timeany hints on what i am doing wrong here include stdlibhinclude stdiohinclude stringhinclude mathhextern c include libavutilmathematicshinclude libavformatavformathinclude libswscaleswscalehinclude aoaohvoid dieconst char msg fprintfstderrsnmsg exit1int mainint argc char argv const char input filenameargv1 avcodec register all av register all av ini avformatcontext containeravformat alloc context ifavformat open inputcontainerinput filenamenullnull0 diecould not open file ifav find stream infocontainer0 diecould not find file info av dump formatcontainer0input filenamefalse int stream id1 int i fori0icontainernb streamsi ifcontainerstreamsicodeccodec typeavmedia type audio stream idi break ifstream id1 diecould not find audio stream avdictionary metadatacontainermetadata avcodeccontext ctxcontainerstreamsstream idcodec avcodec codecavcodec find decoderctxcodec id ifcodecnull diecannot find codec ifavcodec openctxcodec0 diecodec cannot be found ctxavcodec alloc context3codec initialize ao lib ao initialize int driverao default driver id ao sample format sformat sformatbits16 sformatchannels2 sformatrate44100 sformatbyte formatao fmt native sformatmatrix0 ao device adeviceao open livedriversformatnull end of init ao lib avpacket packet av init packetpacket avframe frameavcodec alloc frame int buffer sizeavcodec max audio frame size uint8 t bufferbuffer size packetdatabuffer packetsize buffer size int len int framefinished0 whileav read framecontainerpacket0 ifpacketstream indexstream id printfaudio frame read n int lenavcodec decode audio4ctxframeframefinishedpacket frame ifframefinished printffinished reading frame d dnpacketsizelen ao playadevice charframedata len av close input filecontainer ao shutdown return 0,['c++'] +265720,add event handler to html element using javascript i want to add an event handler to a paragraph for when any user clicks on it for example i have a paragraph which would show an alert when a user clicks it but without using onclick on html p idp1this is paragraph click herep a href idlink1 testa documentgetelementbyidp1onmouseover paragraphhtml,['javascript'] +265745,html5 email input cannot assign id and runatserver aspnet 4 hi i am trying to assign an id to an html5 input so that i can access its value from the code behind in the web form however with the this code input typeemail required autofocus placeholderemail address classtxtinput txtinputusername idmytextbox runatserver visual studio 2010 is telling me that it cannot resolve the symbol idmytextboxany ideas on how i can fix this because i have been searching for an answer for nearly a day thanks,"['c#', 'asp.net']" +265763,screen orientation and values in manifestxml i want to use all activities in my form in landscape or portraitwhen user select orientation this is valid for all activitiestried with behind option orientation according to google orientation will depend on previous activitymy first activity use setrequestedorientation to set selected from user orientationnext activities have to follow same orientationdo i have to put setrequestedorientation in their code too or relly on behind parameter in manifet putting setrequestedorientation may be cause oncreate againupdatetried portrait and setrequestedorientation resilt si oncreate was called 2 timesproblem is in next activity because of portrait in first activity android started next activity with same orientation it ignores landscape orientation wich was set by me,['android'] +265769,push notifications on all 3 platforms androidioswindows phone i am planning a crossplatform app is it possible to implement push notifications on all 3 of them iphone android windowsphone using only one apimodule is there any other alternative what needs to be done serverside please point me in the right direction documentation example code if existsthanks in advance,"['android', 'ios']" +265777,what is the right order of insertiondeletionmodification on dataset the msdn claims that the order is child table delete recordsparent table insert update and delete recordschild table insert and update recordsi have a problem with thatexample parenttable have two records parent1id 1 and parent2id 2childtable have a record child1id 1 parentid 1if we update the child1 to have a new parent parent2 and then we delete parent1we have nothing to delete in child tablewe delete parent1 we broke the constraint because the child is still attached to parent1 unless we update it firstso what is the right order and is the msdn false on the subjectmy personnals thoughts is child table delete recordsparent table insert update recordschild table insert and update recordsparent table delete recordsbut the problem is with potentially unique constraint we must always delete the records in a table before adding new so i have no solution right now for commiting my datas to my databaseedit thanks for the answers but your corner case is my daily case i opt for the ugly solution to thisabled constraint then update database and reenabled constraint i am still searching a better solution,"['c#', '.net', 'sql']" +265805,reverse the order of a doctrine collection i am looking for a clean way to reverse the order of a doctrine collectioni know it sounds weird so let me explain my simple goal i need to thisplay the x latestnewest record but i have to thisplay it in the reverse order the oldest 1st etcif it is unclear here is an example lets say i have this in my table lets call it example id date1 201201212 201203193 201202214 20120321so far i have done thisdoctrinegettableexamplecreatequeryd orderbydate desc limit3which returns thatid date4 201203212 201203193 20120221but i want thatid date3 201202212 201203194 20120321editi have found a solution to this using intermediate array using array reverse on it but it does not look good here is the code i have written query doctrinegettableexample createquerye orderbydate desc limit3 collection queryexecute here is the dirty hack itemarray array foreach collection as item itemarray item itemarray array reverseitemarray orderedcollection new doctrine collectiondoctrineclass foreachitemarray as item orderedcollectionadditem orderedcollection is ok but come on there must be a cleaner way to do itedit 2 answer from adam kiss query doctrinegettableexample createquerye orderbydate desc limit3 collection queryexecute here is the lovely hack orderedcollection new doctrine collectionexample for icollectioncount 1 i0i orderedcollectionaddcollectiongeti,['php'] +265817,combine two bitmap and save as jpg format in android i have two bitmap in my project what i need is that i need to combine those two bit map and combine those bit map to a single image i will show my codepublic class fotosurpriseactivity extends activity called when the activity is first created bitmap overlay paint ptouchint x 100int y 100canvas c2overridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate getwindowsetflagswindowmanagerlayoutparamsflag fullscreen windowmanagerlayoutparamsflag fullscreen requestwindowfeaturewindowfeature no title bitmap mbitmap bitmapfactorydecoderesourcegetresources rdrawableandroid bitmap mbitmapover bitmapfactorydecoderesourcegetresources rdrawabless overlay bitmapfactorydecoderesourcegetresourcesrdrawablesscopyconfigargb 8 true c2 new canvasoverlay ptouch new paintpaintanti alias flag ptouchsetxfermodenew porterduffxfermodemodetarget ptouchsetcolorcolortransparent ptouchsetmaskfilternew blurmaskfilter15 blurnormal setcontentviewnew bitmapviewthis mbitmapmbitmapoverclass bitmapview extends view bitmap mbitmap null bitmap mbitmapover null public bitmapviewcontext context bitmap bm bitmap bmover supercontext mbitmap bm mbitmapover bmover override public boolean ontoucheventmotionevent ev switch evgetaction case motioneventaction down x int evgetx y int evgety invalidate break case motioneventaction move x int evgetx y int evgety invalidate break case motioneventaction up break return true override protected void ondrawcanvas canvas called when view is drawn paint paint new paint paintsetfilterbitmaptrue the image will be scaled so it will fill the width and the height will preserve the imageas aspect ration double aspectratio double mbitmapgetwidth mbitmapgetheight rect dest new rect0 0 thisgetwidthint thisgetheight aspectratio double aspectratio2 double mbitmapovergetwidth mbitmapovergetheight rect dest2 new rect0 0 thisgetwidthint thisgetheight aspectratio2 canvasdrawbitmapmbitmap null dest paint canvasdrawbitmapmbitmapover null dest2 paint draw background canvasdrawbitmapmbitmap 0 0 null copy the default overlay into temporary overlay and punch a hole in it c2drawbitmapmbitmapover 0 0 null exclude this line to show all as you draw c2drawcirclex y 80 ptouch draw the overlay over the background canvasdrawbitmapoverlay 0 0 null how can i make this happen,['android'] +265839,how to design a sequential hashlike function i want to develop something similar to jsfiddle in where the user can input some data and then save it and get a unique random looking url that loads that datai do not want to make the saves sequential because i do not want anyone to grab all of my entries as some can be private however on the server i would like to save it in sequential orderis there a function or technique that converts a number into a hash that has 4 charactors without any collisions until 62 62 62 62 14776336 entriesfor example the first entry on the server will be named 1 on the server but iuew3 to the user the next entry will be 2 on the server but uegr to the useredit i am not sure if it is obvious but this hashlike function needs to be reversible because when the user requests uegr the server needs to know to server it file 2,['php'] +265844,how to prevent focus event in ie when mousedown happens eventpreventdefaultreturn falseeventstoppropagationany of them can prevent focus event from happening when i trigger a mousedown event in firefox and chrome but it failed in iein factchrome has another problem when mousedowning hover css is not working input typetext idnamediv idsuggest divmarkdiv divsamdiv divjohndivdivnamefocussuggestshowblursuggesthidewhat i expected is when i click the sub div such as samand then namevalsambut the problem is when i press the mousejust mousedownnot released the nameblur runs immediately and suggest div becomes hide,['javascript'] +265857,edittext line number and currentline cursor position now i am working on a android application i created a custom keyboard with functionalities i am using a edittext for thisplaying the entered texts edit text may have and number of linesnow my problem is i have a up button in my keyboardso if i click the up button then i have to go the previous lines same positionbut i could not able to find out the edittext line number and curser position of the currentline please help me friends,['android'] +265880,getting data from the info plist whenever i want to get data from a plist file i use the following codensstring filepath nsbundle mainbundle pathforresourcefile name oftypeplistnsdictionary plistdata nsdictionary dictionarywithcontentsoffilefilepath but now i am trying to read in data from the info plist and filepath is nil is there a different way to get data from the info plist,"['objective-c', 'ios']" +265888,how to express in linq an sql orderby clause over two fields i need to write the following sql statement in linq lambdasselect from productorder by productscore desc productid asci guess this codeproductorderbydescendingm mproductscoreorderbym mproductidit is not equivalent since the second orderby will overwrite the first one is there any equivalent thanks,['sql'] +265906,covariance and contravariance in c i will start by saying that i am java developer learning to program in c as such i do comparisons of what i know with what i am learning i have been playing with c generics for a few hours now and i have been able to reproduce the same things i know in java in c with the exception of a couple of examples using covariance and contravariance the book i am reading is not very good in the subject i will certainly seek more info on the web but while i do that perhaps you can help me find a c implementation for the following java codean example is worth a thousand words and i was hoping that by looking a good code sample i will be able to assimilate this more rapidlycovariancein java i can do something like thispublic static double sumlist extends number numbers double summation 00 fornumber number numbers summation numberdoublevalue return summationi can use this code as followslistinteger myints aslist12345listdouble mydoubles aslist314 55 789listlong mylongs aslist1l 2l 3ldouble result 00result summyintsresult summydoublesresult summylongsnow i did thiscover that c supports covariancecontravariance only on interfaces and as long as they have been explicitly declared to do so outin i think i was not able to reproduce this case because i could not find a common ancestor of all numbers but i believe that i could have used ienumerable to implement such thing if a common ancestor exists since ienumerable is a covariant type rightany thoughts on how to implement the list above just point me into the right direction is there any common ancestor of all numeric typescontravariancethe contravariance example i tried was the following in java i can do this to copy one list into anotherpublic static void copylist extends number source list super number destiny fornumber number source destinyaddnumber then i could use it with contravariant types as followslistobject anything new arraylistobjectlistinteger myints aslist12345copymyints anythingmy basic problem trying to implement this in c is that i could not find an interface that was both covariant and contravariant at the same time as it is case of list in my example above maybe it can be done with two different interfaces in cany thoughts on how to implement thisthank you very much to everyone for any answers you can contribute i am pretty sure i will learn a lot from any example you can provide,"['c#', 'java']" +265908,how to atomically negate an stdatomic bool the naive boolean negationstdatomic bool bb bdoes not seem to be atomic i suspect this is because operator triggers a cast to plain bool how would one atomically perform the equivalent negation the following code illustrates that the naive negation is not atomicinclude threadinclude vectorinclude atomicinclude iostreamtypedef stdatomic bool boolvoid flipahundredthousandtimesbool foo for size t i 0 i 10 i foo foo launch nthreads stdthreads each thread calls flipahundredthousandtimes on the same booleanvoid launchthreadsbool foo size t nthreads stdvectorstdthread threads for size t i 0 i nthreads i threadsemplace backflipahundredthousandtimes stdreffoo for auto thread threads threadjoinint main stdcout stdboolalpha bool footrue launch and join 10 threads 20 times for int i 0 i 20 i launchthreadsfoo 10 stdcout result should be true foo n the code launches 10 threads each of which flips the atomic bool a larrge even number of times 10 and prints out the boolean this is repeated 20 times edit for those who want to run this code i am using a gcc 47 snapshot on ubuntu 10 with two cores the compilation options arestdc0x wall pedanticerrors pthread,['c++'] +265931,requirejs two classes in one file i just started out with requirejs but i am stuck at the part where i want to use one js file which has two defines in it like thisfilename testjsdefinetest1 jquery function return method1 function consolelogtest1 method 1 method2 function consolelogtest1 method 2 definetest2 jquery function return method1 function consolelogtest2 method 1 method2 function consolelogtest2 method 2 i also have a bootstrapjs file which is automatically loaded by the requirejs frameworkrequirejquery test test2 function t1 t2 consolelogt1it does find the 2nd param the test file only it returns a null it cannot find test2 because it tries to look for a file called test2js actually i would like to do something likerequirejquery testtest1 testtest2 function t1 t2 consolelogt1but in anyway i would like to get a handler to both the objects what am i doing wrong,['javascript'] +265934,post max array size i have a really big form with 10 elements they are already nested inside the form html structure foreach fromresult itemitem tr tdinput typetext valueitemreceivername nameitemitemidreceivername td tdinput typetext valueitemreceiveraccount number nameitemitemidreceiveraccount number td tdinput typetext valueitemreceiverbank code nameitemitemidreceiverbank code td tdinput typetext valueitemamount nameitemitemidamount td tdinput typetext valueitemusagefirst nameitemitemidusagefirst td tdinput typetext valueitemusagesecond nameitemitemidusagesecond td tdinput typetext valueyourdelivery gmbh nameitemitemidusagethird td td input typecheckbox value1 nameitemitemidimport td tr foreachit is to create a dataus file for mass bank transactions but after reaching more than 10 rows no more elements are added to the post array and the debugger shows the following element counti already added max post size to 100m for testing but nothing helped,['php'] +265954,ipad safari scrolling causes html elements to thisappear and reappear with a delay i am currently developing a web app using html5 and jquery for ipad safari i am running into a problem wherein large scroll areas cause the elements that are offscreen to appear after a delay when i scroll down to themwhat i mean by that is if i have a row of images or even a div with a gradient that is offscreen when i scroll down or up to it the expected behavior is for the element to appear on screen as i am scrolling to ithowever what i am seeing is that the element does not appear until i lift my finger off the screen and the scroller finishes all its animationsthis is causing a super noticeable problem for me making the whole thing look choppy although it is not i am guessing the ipad safari is trying to do something to save memory is there any way in which i can prevent this choppyness from happening additionally i would also appreciate if anyone can shed light on what the ipad safari is actually trying to do,"['css', 'ios']" +265963,joptionpane showinputdialog position how can i specify the position of a joptionpane can anyone make a class that extends joptionpaneshowinputdialog that also takes in an xy position,['java'] +265969,mysql time zones is there an exhaustive list of mysql time zonesit seems that the valid values for time zone in mysql settings are dependent on the host operating system but i have been unable to find a list of possible valuesi need the time to show calgary local time,['mysql'] +265978,webviewclient onpagestarted vs shouldoverrideurlloading i am using webviewclient should we be seeing onpagestarted callbacks always paired with an shouldoverrideurlloading callback if i load examplecom in my webview should we be seeing both methods get called back from the docsonpagestartednotify the host application that a page has started loading this method is called once for each main frame load so a page with iframes or framesets will call onpagestarted one time for the main frame this also means that onpagestarted will not be called when the contents of an embedded frame changes ie clicking a link whose target is an iframeshouldoverrideurlloadinggive the host application a chance to take over the control when a new url is about to be loaded in the current webview if webviewclient is not provided by default webview will ask activity manager to choose the proper handler for the url if webviewclient is provided return true means the host application handles the url while return false means the current webview handles the urli am put a log statement in each method and i see that they are not always paired together in what cases would they not bethanks,['android'] +265983,why do we use 10022 to connect to local web server instead of using computer ip address in android client we normally use 10022port number in the url to connect to the local web serverbut we should use the computers ip address instead of 10022then why do we use 10022,['android'] +266006,why is junit 4 on android not working as the documentation of android says note that the android testing api supports junit 3 code style but not junit 4 testing fundamentals it should be clear that junit 4 cannot be used out of the box with androidbut why is this the case is it because the tests are executed within the dvm in that the android runtime only has support for junit 3 on a jvm one on its own could choose the junit runtime that should be used is not this possible within the dvm,"['java', 'android']" +266012,how to check if isnumeric possible duplicatehow to identify if string contain a number in vb there is an isnumeric function is there something similar in c to get around it i just wrote the code if int32parsetxtmytexttexttrim 0i was just wondering if there is a better way to do this,['c#'] +266018,app icon not changing after updating app getting reports that after updating our app the springboard icon does not update requiring the device to be turned off and on for the change to take effectthis has happened when updating from a live version to a test build via itunes and updating from an old live version to the latest live version via appstore on devicethis is not a regular occurrence but i am wondering what might be causing this,['iphone'] +266021,gdb corrupted stack frame how to debug i have the following stack trace is it possible to make out anything useful from this for debuggingprogram received signal sigsegv segmentation fault0x02 in gdb bt0 0x02 in 1 0x01 in 2 0xbf284 in backtrace stopped previous frame inner to this frame corrupt stackgdb where to start looking at the code when we get a segmentation fault and the stack trace is not so usefulnote if i post the code then the so experts will give me the answer i want to take the guidance from so and find the answer myself so i am not posting the code here apologies,['c'] +266038,get database path im new to android and i want to create kind of crud with sqlitei have a public class databasehelper which have a constructorpublic databasehelpercontext context thiscontext contextand a getter for datebasepublic sqlitedatabase getdatabase if database null try database contextopenorcreatedatabasedatabasehelperdbname contextmode private null databaseexecsqlcreate table databasehelperaccounttblname id integer primary key autoincrement name text address text password text catchexception e logecontexttostring egetmessage if database null databaseclose return databaseif i start a program for the first time everything seems to be okay database is null and i create it with a table but when i restart my app database is null again and table cannot be createdi have decided to write a checkdb function which tries to open a database but where can i get a path for it i dont want it to be hardcodedor may be i am doing some kind of antipattern,['android'] +266085,how to show all privileges from a user in oracle can someone please tell me how to show all privilegesrules from a specific user in the sqlconsole,['sql'] +266086,devise separate sign out for two different models i have two models user and adminwith railsadmin that use devise i sign in as user and then sign in as admin but the result of signing out from one of that models is signing out of two models at the same time how can i fix itplease help,['ruby-on-rails'] +266097,what is the lookup time complexity of hashsetiequalitycomparer in cnet i like using hashsets because of their supposed o1 time complexity for lookups if i have a large set of data that is going to be queried i often prefer using a hashset to a list since it has this time complexitywhat confuses me is the constructor for the hashset which takes iequalitycomparer as an argumentin the link above the remarks note that the constructor is an o1 operation but if this is the case i am curious if lookup is still o1in particular it seems to me that if i were to write a comparer to pass in to the constructor of a hashset whenever i perform a lookup the comparer code would have to be executed on every key to check to see if there was a match this would not be o1 but ondoes the implementation internally construct a lookup table as elements are added to the collectionin general how might i ascertain information about complexity of net data structures,['c#'] +266098,net serializing object to a file from a 3rd party assembly to make selenium webdriver faster end goal for serializing firefoxdriver my question here making webdriver fasterbelow is a link that describes how to serialize an object but it requires you implement from iserializable for the object you are serializing what i would like to do is serialize an object that i did not definean object based on a class in a 3rd party assembly from a project reference that is not implementing iserializable is that possible how can this be doneproperty iwebdriver interface typeprivate iwebdriver driverobject instance firefoxdriver is a class typedriver new firefoxdriverfirefoxprofile3212012 update after answer postedwhy would this throw an error it does not like this lineserializedobjectdriverinstance firefoxdriverdrivererrorcannot implicitly convert type openqaseleniumiwebdriver to openqaseleniumfirefoxfirefoxdriver an explicit conversion exists are you missing a casthere is the code firefoxdriverserialized serializedobject new firefoxdriverserialized serializer serializer new serializer serializedobject serializerdeserializeobjectcfirefoxdriverqa driver serializedobjectdriverinstance if driver null driver new firefoxdriverfirefoxprofile serializedobjectdriverinstance firefoxdriverserializeddriver serializerserializeobjectcfirefoxdriverqa serializedobject here are the two serializer classes i builtpublic class serializer public serializer public void serializeobjectstring filename firefoxdriverserialized objecttoserialize stream stream fileopenfilename filemodecreate binaryformatter bformatter new binaryformatter bformatterserializestream objecttoserialize streamclose public firefoxdriverserialized deserializeobjectstring filename firefoxdriverserialized objecttoserialize stream stream fileopenfilename filemodeopen binaryformatter bformatter new binaryformatter objecttoserialize firefoxdriverserializedbformatterdeserializestream streamclose return objecttoserialize serializablepublic class firefoxdriverserialized firefoxdriver iserializable private firefoxdriver driverinstance public firefoxdriver driverinstance get return thisdriverinstance set thisdriverinstance value public firefoxdriverserialized public firefoxdriverserializedserializationinfo info streamingcontext ctxt thisdriverinstance firefoxdriverinfogetvaluedriverinstance typeoffirefoxdriver public void getobjectdataserializationinfo info streamingcontext ctxt infoaddvaluedriverinstance thisdriverinstance 3232012 update 2 fixed serializationdeserialization but having another issuethis fixed the calling code because were deleting the qa file when we call the webdriverquit because that is when we chose to close the browser this will kill off our cached driver as well so if we start with a new browser window well hit the catch block and create a new instance and save it to our qa file in the serialized form firefoxdriverserialized serializedobject new firefoxdriverserialized serializer serializer new serializer try serializedobject serializerdeserializeobjectcfirefoxdriverqa driver serializedobjectdriverinstance catch driver new firefoxdriverfirefoxprofile serializedobject new firefoxdriverserialized serializedobjectdriverinstance firefoxdriverdriver serializerserializeobjectcfirefoxdriverqa serializedobject however still getting this exceptionacuqamaintest 0055 giftcertificate usercheckoutsetup systemruntimeserializationserializationexception type openqaseleniumfirefoxfirefoxdriver in assembly webdriver version21600 cultureneutral publickeytoken1c2bd1631853048f is not marked as serializableteardown systemnullreferenceexception object reference not set to an instance of an objectthe 3rd line in this code block is throwing the exception public void serializeobjectstring filename firefoxdriverserialized objecttoserialize stream stream fileopenfilename filemodecreate binaryformatter bformatter new binaryformatter bformatterserializestream objecttoserialize this line streamclose update 3 3242012 simplified firefoxdriver instance by not passing anything to the constructor i will make it more complex later by passing in firefoxprofile into the constructor i still get the same exception as update 2calling codefirefoxdriverserialized serializedobject new firefoxdriverserializedserializer serializer new serializertry serializedobject serializerdeserializeobjectcfirefoxdriverqa driver serializedobjectdriverinstancecatch driver new firefoxdriverfirefoxprofile driver new firefoxdriver serializedobjectdriverinstance firefoxdriverdriver serializerserializeobjectcfirefoxdriverqa serializedobjectalso had to add base to my constructor in my serialized object claserializablepublic class firefoxdriverserialized firefoxdriver iserializable private firefoxdriver driverinstance public firefoxdriver driverinstance get return thisdriverinstance set thisdriverinstance value public firefoxdriverserialized base public firefoxdriverserializedserializationinfo info streamingcontext ctxt thisdriverinstance firefoxdriverinfogetvaluedriverinstance typeoffirefoxdriver public void getobjectdataserializationinfo info streamingcontext ctxt infoaddvaluedriverinstance thisdriverinstance update 4 just documenting stub signatures for openqaseleniumfirefoxfirefoxdriver classusing openqaseleniumusing openqaseleniumremoteusing systemnamespace openqaseleniumfirefox public class firefoxdriver remotewebdriver itakesscreenshot class data members public static readonly bool acceptuntrustedcertificates public static readonly string binarycapabilityname public static readonly bool defaultenablenativeevents public static readonly int defaultport public static readonly string profilecapabilityname constructors public firefoxdriver public firefoxdriverfirefoxprofile profile public firefoxdrivericapabilities capabilities public firefoxdriverfirefoxbinary binary firefoxprofile profile public firefoxdriverfirefoxbinary binary firefoxprofile profile timespan commandtimeout properties protected firefoxbinary binary get protected firefoxprofile profile get methods protected override remotewebelement createelementstring elementid public screenshot getscreenshot protected void prepareenvironment protected override void startclient protected override void stopclient,['.net'] +266110,matplotlib artist to stay same size when zoomed in but also move with panning this is a very direct followup on this questionusing matplotlib i would like to be able to place a sort of highlighting bar over a range of data markers that i know will all be in a straight horizontal line this barrectangle should be slightly taller than the markers and contain them something like this for the three markers belowin order to be a sensible highlighting bar it needs to have the following two traitsif the plot is panned the bar moves with the markers so it always covers themif the plot is zoomed the bars thisplay height does not change so it always is slightly taller than the markersif it is helpful to know these markers have no meaningful y values they are plotted all at y1 only meaningful x values therefore the height of the bar is meaningless in data coordinates it merely needs to be always just tall enough to enclose the markers,['python'] +266148,jquery bind click and hover how to check if click i have combined function like thissimplified versionlabelbindclick hover function labelremoveclassactive thisaddclassactivehow can i add an if to check if it is a click,"['javascript', 'jquery']" +266152,how to convert datetime to timestamp using cnet ignoring current timezone how do i convert datetime to timestamp using c net ignoring the current timezonei am using the below codeprivate long converttotimestampdatetime value long epoch valuetouniversaltimeticks 6213559680 10 return epochbut it returns the timestamp value according to the current time zone and i need the result without using the current timezone,"['c#', 'asp.net']" +266158,why does my ko computed observable not update bound ui elements when its value changes i am trying to wrap a cookie in a computed observable which i will later turn into a protectedobservable and i am having some problems with the computed observable i was under the opinion that changes to the computed observable would be broadcast to any ui elements that have been bound to iti have created the following fiddlejavascriptvar viewmodel simulating a cookie store this part isnt as importantvar cookie function simulating a value stored in cookies var privatezipcode 12345 return write function val privatezipcode val read function return privatezipcode viewmodelzipcode kocomputed read function return cookieread write function value cookiewritevalue owner viewmodel koapplybindingsviewmodelhtmlzipcodeinput typetext databindvalue zipcode br zipcode span databindtext zipcodespani am not using an observable to store privatezipcode since that is really just going to be in a cookie i am hoping that the kocomputed will provide the notifications and binding functionality that i need though most of the examples i have seen with kocomputed end up using a koobservable underneath the coversshould not the act of writing the value to my computed observable signal the ui elements that are bound to its value should not these just updateworkaroundi have got a simple workaround where i just use a koobservable along side of my cookie store and using that will trigger the required updates to my dom elements but this seems completely unnecessary unless kocomputed lacks the signaling dependency type functionality that koobservable hasmy workaround fiddle youll notice that the only thing that changes is that i added a seperateobservable that is not used as a store its only purpose is to signal to the ui that the underlying data has changed simulating a cookie store this part isnt as importantvar cookie function simulating a value stored in cookies var privatezipcode 12345 extra observable that isnt really used as a store just to trigger updates to the ui var seperateobservable koobservableprivatezipcode return write function val privatezipcode val seperateobservableval read function seperateobservable return privatezipcode this makes sense and works as i would expect because viewmodelzipcode depends on seperateobservable and updates to that should and does signal the ui to update what i do not understand is why does not a call to the write function on my kocomputed signal the ui to update since that element is bound to that kocomputedi suspected that i might have to use something in knockout to manually signal that my kocomputed has been updated and i am fine with that that makes sense i just have not been able to find a way to accomplish that,['javascript'] +266166,return best fit item from collection in c 35 in just a line or two here is some sample code i have basically written thousands of times in my life find bestest thingything bestthingfloat bestgoodness float minforeach thing x in arrayofthings float goodness somefunction xproperty localvariable if goodness bestgoodness bestgoodness goodness bestthing x return bestthingand it seems to me c should already have something that does this in just a line something likereturn arrayofthingsmax delegatex return somefunction xproperty localvariable but that does not return the thing or an index to the thing which would be fine that returns the goodnessoffit valueso maybe something likevar sortedbygoodness from x in arrayofthings orderby somefunction xproperty localvariable ascending select xreturn xfirstbut that is doing a whole sort of the entire array and could be too slowdoes this exist,['c#'] +266178,smarter wordwrap in php for long words i am looking for a way to make wordwrap in php a bit smarter so it does not prebreak long words leaving any prior small words alone on one linelet us say i have this the real text is always completely dynamic this is just to showwordwraphello hereisaverylongword 25 br truethis outputshello hereisavery longwordsee it leaves the small word alone on the first linehow can i get it to ouput something more like thishello he ereisaverylongwordso it utilizes any available space on each line i have tried several custom functions but none have been effective or they had some drawbacks,['php'] +266199,line height in fpdf multicell i am using fpdf multicell to thisplay an address each line in the address will be thisplayed in a new line like 102 south avenue suite 107 scottsdale az 85260 101but the line height between each line is more than a new line any idea how to set the line height for multicell in fpdf,['php'] +266241,getversionex under windows 8 i am writing a c code to determine what os it is running on i use getversionex api to do that and this code as a tutorial but it does not seems to handle windows 8 does anyone know how to fix it to run under windows 8,['c++'] +266291,how to convert jar to osgi bundle using eclipse and bndtools i am looking for a step by step guide to convert jar into an osgi bundle using the eclipse bndtools plugin i know it is possible to do it with bnd using the command line but would be nice to know how to do the same via the idei might be missing something but this tutorial only explains how to create a project from scratch,['java'] +266299,how to capture the hide keyboard event on ios using javascript i need to do some resizing of the content of a web page when the hide keyboard button is pressed on an ipad virtual keyboard does anybody know which javascript event is launched when the keyboard is hidden,"['javascript', 'ios']" +266306,get attributes of model in backbonejs i have this modelvar item backbonemodelextend url httplocalhostinterpriseposproductloaditembycategoryevent materialsvar onsuccess function alertsuccess and a collectionvar items backbonecollectionextend model itemand the rest of my code is herevar item new itemvar items new itemsitemfetch success onsuccess alertitemsgetitemcodewhat i want is to simply get the attributes of the model now i have this on firebug also when i run it on the browser i get the alert success and the next alert is undefinedthis is the outputerrormessagenullitemserrormessagenullcategorycodeevent materialsclasscodenullcomponentsnullgroupcodenullimageurlnullitemcodeitem123itemdescriptionold world lamppostu0du0au0du0aitemnameget123itemtypenullkititemnullmatrixnullprefixnullretailprice107990salestaxcodenullupccodenullunitmeasurecodeeachunitsinstock0valuenullwholesaleprice950notethat is just one of the items it returns i just posted on item so that it would not be that long,['javascript'] +266310,ignoring null fields in jsonnet i have some data that i have to serialize to json i am using jsonnet my code structure is similar to thispublic struct structa public string field1 public structb field2 public structb field3public struct structb public string subfield1 public string subfield2problem is my json output needs to have only field1 or field2 or field3 it depends on which field is used ie not null by default my json looks like this field1 null field2 subfield1 test1 subfield2 test2 field3 subfield1 null subfield2 nulli know i can use nullvaluehandlingignore but that gives me json that looks like this field2 subfield1 test1 subfield2 test2 field3 and what i need is this field2 subfield1 test1 subfield2 test2is there simple way to achieve this,"['c#', '.net']" +266327,ajax authorization request headers fails again and again i am working on a consumer for a selfmade api and having serious difficulties with setting the authorization header i am using jquery for the ajax requests but the beforesend does not work at all using fiddler to examine the requeststhis is my beforesend code ajax type get url urlprojects contenttype applicationjson charsetutf8 beforesend function req reqsetrequestheaderauthorization authbuilderusername password success function result alertsuccess error function xhr ajaxoptions thrownerror alertfail well if that fails what do you do go back to the old way for sending ajax requests well this does not work either this is my regular codefunction getaddress callback error request getxmlhttpobjectrequestopenget url address truevar base64 base64encodeusername passwordalertbase64requestsetrequestheaderauthorization basic base64requestsendrequestonreadystatechange function alertrequestreadystate code requeststatus if requestreadystate 4 requeststatus 200 callbackjqueryparsejsonrequestresponsetext else if requestreadystate 4 requeststatus 400 errorrequeststatus requeststatustext do not mind the fact that i am not asking for json specifically because the service returns json by defaultin additional info the origin does not matter the service allows all origins has been tested and confirmedthe authorization works when set by headers tested in other clientsthe authorization headers just are not sentauthbuilderusername password gives the correct format of the basic auth header contentthe getxmlhttpobject is just some copy paste code and worked beforeany thoughts,"['javascript', 'jquery']" +266338,entityframework update partial model i am working on mvc project with repository pattern and entity framework now on my form i have a sample modelsamplemodel1 name2 age3 address4 notes5 date updatedi am thisplaying only following data on the edit form1 name2 age3 addressnow if i update the model with missing property values using the repository the notes dateupdated field goes nullmy question is how do i update only few selected properties using the repository tryupdatemodel not available in repository and i dont want to call the original object and map the properites with the updated modelis there any way there must be,['c#'] +266396,how to assert that a function does not raise an exception qunit has an assertion for testing that a function raises an exception qunitraises is it possible using qunit to assert that a function does not raise an exceptioni realize that it is possible to test it like in the following codetry thetest oktrue catch e okfalse expected to succeedbut i think it ought to be possible using qunit any clues,['javascript'] +266398,css before and firstchild combined i am using the following code to add separators between my menu itemsnavigation center libefore content color fnow i want the first item not to have a separator in front of it so i figured out the following codenavigation center libeforefirstchild content nonebut that is not doing anything is it possible to combine before and firstchild,['css'] +266414,how to force https using a webconfig file i have searched around google and stackoverflow trying to find a solution to this but they all seem to relate to aspnet etci usually run linux on my servers but for this one client i am using windows with iis 75 and plesk 10 this being the reason why i am slightly unfamiliar with iis and webconfig files in an htaccess file you can use rewrite conditions to detect whether the protocol is https and redirect accordingly is there a simple way to achieve this using a webconfig file or even using the url rewrite module that i have installedi have no experience with aspnet so if this is involved in the solution then please include clear steps of how to implementthe reason for me doing this with the webconfig and not php is that i would like to force https on all assets within the site,"['c#', 'asp.net']" +266433,set http request contenttype how do you set the content type of an http requesti have tried thisheadersaccept applicationxmlheaderscontenttype applicationxmlcurl setoptch curlopt httpheader headersand this is the result http11 200 okcontentencoding gzipcontenttype texthtmlcharsetutf8date thu 22 mar 2012 140436 gmtbut no luck so farwhat do i have to do to get an contenttype applicationxml in my http response,['php'] +266438,mongoosejs find user by username like value i like to to go find a user in mongodb by looking for a user called valuethe problem withusername peteris that i dont find it if the username is peter or peter or something like thatso i want to do like sqlselect from users where username like peterhope you guys get what im askin forshort field like value in mongoosejsmongodb,['javascript'] +266445,play framework persistenceexception the type is not a registered entity ebean i am following the play framework 20 tutorial for java and get this error when trying to save an ebean model tasksavepersistenceexception the type class modelstask is not a registered entity if you do not explicitly list the entity classes to use ebean will search for them in the classpath if the entity is in a jar check the ebeansearchjars property in ebeanproperties file or check serverconfigaddjar,['java'] +266478,how to access the fields of a test class with in an rule in junit i want to write an junit rule version 410 to setup some objects an entity manager and make them available in the test by injecting it into an variablesomething like thispublic class mytestclass rule myentitymanagerinjectrule new myentitymanagerinjectrule myentitymanagerinjectrule inject the entity manager entitymanger em testthe problem is that i do not know how to get the current instance of mytestclass in the myentitymanagerinjectrule extends testrule because it has only one methodstatement applystatement base description descriptionwithin description there is only the class mytestclass but not the instance used for the testan alternative would be using orgjunitrulesmethodrule but this is deprecatedbefore and after are not sufficient for this task because then i would need to copy the code to the tests and they are more or less deprecated too see block4jclassrunnerwithbefores withaftersso my question in how could i access the test class instance without using deprecated stuff,['java'] +266513,ios segue animation left to right horizontal i am nearly a newbie to xcode 4there is a way to add to a segue a custom transition animation that it is not among the four presented by the interface builder in the storyboard management specifically i want an animation similar to the normal cover vertical but horizontal i want the a view to pass to another sliding from left to right or right to left instead that from up to bottom as it happens in the cover vertical transitioni tried with the swipe gesture but no fortune even that is transitioning from up to bottom and anyway i do not understand why the defaul transition is from up to bottom when the default transition of all the app usually is right to left or left to right especially in the case you do swipei tried also a programatically way but no fortune even in this case using this codeimport jhcustomseguehimplementation jhcustomsegue void perform uiviewcontroller src uiviewcontroller selfsourceviewcontroller uiviewcontroller dst uiviewcontroller selfdestinationviewcontroller uiview transitionwithviewsrcnavigationcontrollerview duration05 optionsuiviewanimationoptiontransitionflipfromleft animations src presentmodalviewcontrollerdst animatedno completionnullendin the interface builder i defined this class as the class of my segue using breakpoint i saw it enter the function perfom but do not performi have blocked the app in portrait mode do not know if it is a problem i tried to run the application on a real ipad and on a simulated iphone same problem,['ios'] +266525,uinavigationcontroller force rotate my application is primarily portrait however there is one view that requires a landscape orientationmy views are contained within a uinavigationcontroller which apparently is the cause of this issueall uiviewcontrollers except one have this boolshouldautorotatetointerfaceorientationuiinterfaceorientationinterfaceorientation return yes for supported orientations return interfaceorientation uiinterfaceorientationportraitthe uiviewcontroller that requires landscape has this boolshouldautorotatetointerfaceorientationuiinterfaceorientationinterfaceorientation return yes for supported orientations return interfaceorientation uiinterfaceorientationlandscapeleft interfaceorientation uiinterfaceorientationlandscaperightnow what happens is when the user reaches the landscape uiviewcontroller it is shown in portrait the user can then rotate their phone and it thisplays in landscape as i want it to locking to landscape the user then progresses onwards to a portrait uiviewcontroller and the same happens it start in landscape then they rotate their phone and it becomes portrait again and locks to portraitit seems orientation locking is allowed between uiviewcontrollers however autorotation programmatically changing the orientation is somehow blockedhow do i force the phone to update to the correct orientationthere is a temporary solution i can detect the orientation of the device and show a message asking them to rotate the device if it is not correct however this is not optimal,"['iphone', 'objective-c', 'ios']" +266547,how to load initial data or seed data using java jpa i have a jpa project and i would like to insert some initial data just on development so i can check if everything is running smoothly easymy research lead me to find only solution with direct sql script but that is not right if i am using a framework to abstract database details why would i create script for an specific databasein the ruby on rails world we have the command rake dbseed that simple executes a file named seedrb that has the function to add the initial data on the database calling the abstraction layer is there something like that on javathe ideal solution i can think of would be to execute a maven goal that would execute a java class is there an easy way or a maven plugin to do it,['java'] +266569,how to increase the maximum call stack in javascript i have an event which can fire itself i try to make the code as efficient as possible but it can hit maximum call stack in some circumstances which are out of my control it is not an infinite stack and it will end at some point but sometimes it can potentially crashe before it finishes because of the limit will i increase the number of call stack if i set up 2 similar event listeners and split the code or what can i doupdate it is on dom change event working with webkit only so do not care about other browsers which can also modify the dom based on some conditions i have not really hit that limit yet but theoritically it potentially can i am still optimizing the code to make as less dom manipulations as possibleupdate 2 i am including sample not real exampledocumentaddeventlistenerdomsubtreemodified functionevent thisapplypolicyevent truefunction applypolicyevent if typeof event undefined eventstoppropagation eventstopimmediatepropagation if isbuttonallowed buttonnotthisabledeachfunction thisattrthisabled true this is just a sample code but even in this case if you have say 100s of buttons the call stack will be in 100s too note that if you use buttonattrthisabled true this will cause call stack problem because jquery will be trying to modify the dom infinitely,"['javascript', 'jquery']" +266576,how to tell if a page is being called via ajax or on it is own i have a page that loads other pages via ajax think frames except without the frames obviously these pages can all be called independently so i want to detect if they are being called via the ajax and if not redirect to the main ajax pagethe pages are php pages so i have access to that as wellindex goto standaloneprogramsphp var clear br styleclearboth ifgoto ajax url goto context documentbody success functiondata mainwindowhtmldata clear mainwindowfindscripteachfunctioni evalthistext,"['php', 'jquery']" +266613,in coffeescript is there an official way to interpolate a string at runtime instead of when compiled i have an options object in my cs class and i would like to keep some templates in itclass myclass options templates list ul class foo ul listitem li foo bar li etcthen i would like to interpolate these strings later in the code but of course these are compiled to ul class foo ul and foo is undefinedis there an official coffeescript way to do this at runtime using replaceedit i ended up writing a little utility to help interpolate a string to replace placeholder keys with passed object valuesstringinterp values replace w g ph key valueskey or so my options now look liketemplates list ul class foo ul listitem li baz liand then later in the codetemplate optionstemplateslistiteminterp baz foo barmylistappend template,['javascript'] +266620,using backbonejs view what is the best way to attach an onload event to an image tag i want to attach an onload event for an image in a backbonejs view i am currently including it in the events as load imgfunction but it is not getting fired offany suggestions for doing this,['javascript'] +266631,using rspec how can i test the results of a rescue exception block i have a method that has a begin rescue block in it how do i test the rescue block using rspec2class capturer def capture begin status externalservicecall return true if status 200 return false rescue exception e loggerlog exceptione return false end endenddescribe capture do context an exception is thrown do it should log the exception and return false do c capturernew success ccapture assert that logger receives log exception assert that success false end endend,['ruby'] +266637,c throwing a derived class by reference does not work when catching base class i want to throw my own exceptions with the base class exception there is a virtual method print which will be overwritten by the subclasses i only catch the type exception and use print to get the specific error the problem is that once i throw a reference of a subclass it is trated as if it were the base classhere is an exampleinclude iostreamusing namespace stdclass exception public virtual void print cout exception endl class illegalargumentexception public exception public virtual void print cout illegalargumentexception endl int mainint argc char argv try illegalargumentexception i exception ref i cout refprint refprint throw ref catchexception e cout catched eprint the output of this example isrefprint illegalargumentexceptioncatched exceptionusing a reference should result in the print method from the derived class being used inside the try block the reference does use it why does not the catched exception act like an illegalargumentexception and how can i get that behaviorthe following code seems to do what it is supposed totry illegalargumentexception i exception pointer i throw pointercatchexception e cout pointer catched eprintbut does not the pointer become possibly invalid outside the scope of the try block it would then be risky to do this and if i allocate memory on the heap to get around that problem i have the responsibility for the deletion inside the catch block which is not pretty either so how would you solve the problem,['c++'] +266648,how to stop a for loop i am using this to iterate through an array and find a matching array elementvar remsize szstring remdata remindex ifor i 0 i remsizelength i i am looking for the index i when the condition is true remsizeisize remdatasize remindex i remindex 1 the array contains these sizes 34 36 38 remdatasize is the size i am looking for eg 36i need to return the index i if the size i am searching for is in the index otherwise i need to return 1 is there a better way to do this,['javascript'] +266672,how does the javascript sort function workas an algorithm the javascript sort function which takes a parameter allows one to pass in a function for examplevar myarray25 8 7 41myarraysortfunctionabreturn a b array now becomes 7 8 25 41how is it that the codefunctionab return a bis interpreted to be ascending it is supposed to be divided into three cases 0 0 and 0 but how does this make sense when a and b can be anythingthank you,['javascript'] +266687,change polyline color dynamically i have a web app that will draw a polyline for each user tracks movement and i would like to incorporate some functionality that allows the web app user to focus on a certain user by changing the color of the polyline it will have to first change all the polylines to red and then change the selected polyline to blue i think this is best to avoid focusing on one line then trying to focus on another and having them both blue i am really not sure how to implement this but i have functionality that returns a user id when the name is pressed i just need to iterate over each object each users polyline to change them to red first then change the specific one to blue here is some code below if you could point me in the right direction i would appreciate it thanks this is a condensed version of my code so i hope it provides enough informationfunction userid thisid idthislocations thismark 0thisgetid function return thisidthisaddlocation functionlatitude longitude thislocationsthislocationslength new googlemapslatlnglatitude longitude var polylinethisdrawpolyline functionloc polyline new googlemapspolyline map map path loc strokecolor ff0 strokeopacity 10 strokeweight 2 polylinesetmapmapthisremovepolyline function if polyline undefined polylinesetmapnull thisget user info functionuser id var datastr id user idajax type post url user apiphp data datastr datatype json success functiondata var phone id data0 var leftdiv documentcreateelementdiv create left div leftdivid left assign div id leftdivsetattributestyle floatleft width665 lineheight 26px textalignleft fontsize12pt paddingleft8px height26px set div attributes leftdivstylebackground divcolor user name documentcreatetextnodefullname set user name a documentcreateelementa ahref javascriptsetfocus phone id ainnerhtml fullname leftdivappendchilda function setfocusphone id alertphone idfunction users thisusers thiscreateuser functionid thisusersid new userid return thisusersidthisgetuser functionid return thisusersid thisremoveuser functionid var user thisgetuserid delete thisusersid return uservar users new users,['javascript'] +266693,getting wrong data when using simpledateformatparse i am getting the strangest error when trying to parse a string as a calendarit seems that it messes up the date object which i use to set the result calendars time the error is pretty inconsistent or i see no logic in it can anyone point out what i might be doing wrong public class caltestpublic static final simpledateformat sdf new simpledateformatymmdd hhmmspublic static void mainstring args string date1 19920311 120012123 string date2 19930311 120012123 string date3 19940311 120012123 string date4 19950311 120012123 parsestringascalendardate1 parsestringascalendardate2 parsestringascalendardate3 parsestringascalendardate4public static string calendartostringcalendar cal return sdfformatcalgettimepublic static calendar parsestringascalendarstring s date time null try time sdfparses catch parseexception e systemoutprintlnexception eprintstacktrace systemoutprintlntimetostring gregoriancalendar ret new gregoriancalendar retsettimetime return retthe output is sun dec 29 120012 cet 1991sun dec 27 120012 cet 1992sun dec 26 120012 cet 1993sun jan 01 120012 cet 1995,['java'] +266735,cucumber rerun failed scenarios automatically with a tag in our build there are certain scenarios that fail for reasons which are out of our control or take too long to debug properly things such asynchronous javascript etcanyway the point is sometimes they work sometimes they do not so i was thinking it would be nice to add a tag to a scenario such as rerun on failure or retry which would retry the scenarion x number of times before failing the buildi understand this is not an ideal solution but the test is still valuable and we would like to keep it without having the false negativesthe actual test that fails clicks on a link and expects a tracking event to be sent to a server for analytics via javascript sometimes the selenium webdriver loads the next page too fast and the event does not have time to be sent thanks,['ruby'] +266743,what happens when you logical not a float i assume this just returns an int is there anything else going on i should be aware of cc differencesfloat a 25a what does this return int float,"['c++', 'c']" +266764,spring security and cas integration can anyone paste simple steps to integrate spring security and cas over here for single sign on and single sign outnote i dont want any role based accessi have a web application which is already integrated with spring security now i was trying to perform sso with casbut i am getting this error sunsecurityprovidercertpathsuncertpathbuilderexception unable to find valid certification path to requested targetthis is my current spring securityxml xml version10 encodingutf8beans xmlns xmlnssec xmlnsxsi xmlnsaop xmlnscontext xsischemalocation sechttp entrypointrefcasprocessingfilterentrypoint secintercepturl pattern accessrole user seclogout logoutsuccessurlloggedoutjsp invalidatesessiontrue seccustomfilter refcasauthenticationfilter aftercas filter sechttp secauthenticationmanager aliasauthenticationmanager secauthenticationprovider refcasauthenticationprovider secauthenticationmanagerbean idcasauthenticationfilter classorgspringframeworksecuritycaswebcasauthenticationfilter property nameauthenticationmanager refauthenticationmanager property nameauthenticationfailurehandler bean classorgspringframeworksecuritywebauthenticationsimpleurlauthenticationfailurehandler property namedefaultfailureurl valuecasfailedjsp bean property property nameauthenticationsuccesshandler bean classorgspringframeworksecuritywebauthenticationsimpleurlauthenticationsuccesshandler property namedefaulttargeturl value bean property bean bean idcasprocessingfilterentrypoint classorgspringframeworksecuritycaswebcasauthenticationentrypoint property nameloginurl value property nameserviceproperties refserviceproperties bean bean idcasauthenticationprovider classorgspringframeworksecuritycasauthenticationcasauthenticationprovider property nameuserdetailsservice refuserservice property nameserviceproperties refserviceproperties property nameticketvalidator bean classorgjasigcasclientvalidationcas20serviceticketvalidator constructorarg index0 value bean property property namekey valuean id for this auth provider only bean bean idserviceproperties classorgspringframeworksecuritycasserviceproperties property nameservice valuehttplocalhost8080dbcomparisionj spring cas security check property namesendrenew valuefalse bean bean iduserservice classcomtcscegservicesimpluserserviceimpl secglobalmethodsecurity prepostannotationsenabled sechttp patterncss securitynone sechttp patternimages securitynone sechttp patternjs securitynone sechttp patternindexjsp securitynone sechttp patternappaddnewuserjson securitynone sechttp patterndbcomploginjsp securitynone sechttp patternloggedoutjsp securitynone sechttp useexpressionstrue allow all other requests in a real application you should adopt a whitelisting approach where access is not allowed by default secintercepturl pattern accessisauthenticated secformlogin loginpagedbcomploginjsp authenticationfailureurldbcomploginjsplogin error1 defaulttargeturlindexjsp seclogout logoutsuccessurlloggedoutjsp deletecookiesjsessionid secrememberme sechttp bean idmyuserservice classcomtcscegservicesimpluserserviceimpl secauthenticationmanager secauthenticationprovider userservicerefmyuserservice secauthenticationmanager beansthis is my webxmlxml version10 encodingutf8webapp xmlnsxsi xmlns xmlnsweb 2 5xsd xsischemalocation 2 5xsd idwebapp id version25 thisplaynamespring3mvcthisplayname contextparam paramnamecontextconfiglocationparamname paramvalue webinfspringrootcontextxml webinfspringsecurityxml paramvalue contextparam filter filternamespringsecurityfilterchainfiltername filterclassorgspringframeworkwebfilterdelegatingfilterproxyfilterclass filter filtermapping filternamespringsecurityfilterchainfiltername urlpatternurlpattern filtermapping loads the root application context of this web app at startup listener listenerclassorgspringframeworkwebcontextcontextloaderlistenerlistenerclass listener welcomefilelist welcomefileindexjspwelcomefile welcomefilelist servlet servletnamespringservletname servletclass orgspringframeworkwebservletthispatcherservlet servletclass loadonstartup1loadonstartup servlet servletmapping servletnamespringservletname urlpatternappurlpattern servletmapping filter filternamecas single sign out filterfiltername filterclassorgjasigcasclientsessionsinglesignoutfilterfilterclass filter filtermapping filternamecas single sign out filterfiltername urlpatternurlpattern filtermapping listener listenerclassorgjasigcasclientsessionsinglesignouthttpsessionlistenerlistenerclass listenerwebappthis is my springrootcontextxmlxml version10 encodingutf8beans xmlns xmlnsxsi xmlnsaop xmlnscontext xmlnsjee xmlnslang xmlnsp xmlnstx xmlnsutil xmlnsmvc xsischemalocation contextannotationconfig mvcannotationdriven contextcomponentscan basepackagecomtcsceg jeejndilookup iddatasource1 jndinamejdbcpmdds bean idsessionfactory classorgspringframeworkormhibernate3localsessionfactorybean property namedatasource refdatasource1 property nameconfiglocation valueclasspathhibernatecfgxmlvalue property property nameconfigurationclass valueorghibernatecfgannotationconfigurationvalue property property namehibernateproperties props prop keyhibernatedialectorghibernatedialectpostgresqldialectprop prop keyhibernateshow sqltrueprop prop keycurrent session context classthreadprop prop keycacheprovider classorghibernatecachenocacheproviderprop prop keyhibernateconnectionrelease modeautoprop props property bean txannotationdriven bean idtransactionmanager classorgspringframeworkormhibernate3hibernatetransactionmanager property namesessionfactory refsessionfactory bean beansthis is my springservletxmlxml version10 encodingutf8beans xmlns xmlnsxsi xmlnsaop xmlnscontext xmlnsjee xmlnslang xmlnsp xmlnstx xmlnsutil xmlnsmvc xsischemalocation bean idviewresolver classorgspringframeworkwebservletviewurlbasedviewresolver property nameviewclass value orgspringframeworkwebservletviewtiles2tilesview value property bean bean idtilesconfigurer classorgspringframeworkwebservletviewtiles2tilesconfigurer property namedefinitions list valuewebinftilesxmlvalue list propertybeanbean idmessagesource classorgspringframeworkcontextsupportreloadableresourcebundlemessagesource property namebasename valueclasspathmessages property namedefaultencoding valueutf8beanbean idlocalechangeinterceptor classorgspringframeworkwebservleti18nlocalechangeinterceptor property nameparamname valuelang beanbean idlocaleresolver classorgspringframeworkwebservleti18ncookielocaleresolver property namedefaultlocale valueenbeanbean idhandlermapping classorgspringframeworkwebservletmvcannotationdefaultannotationhandlermapping property nameinterceptors ref beanlocalechangeinterceptor propertybean bean idmultipartresolver classorgspringframeworkwebmultipartcommonscommonsmultipartresolver one of the properties available the maximum file size in bytes property namemaxuploadsize value10 beanbeansproblem 1 sunsecurityprovidercertpathsuncertpathbuilderexception unable to find valid certification path to requested targetproblem 2 custom userserviceimpl is not getting called problem 3 is this correct property nameservice valuehttplocalhost8080dbcomparisionj spring cas security check note in my program no request mapping is there for j spring cas security check,['java'] +266794,where is a good place to work on accountsprofile in django with the django registration app i have noticed that after i log in with django registration it redirects me to accountsprofile by default django registrations urlpy does not handle accountsprofile so i need to create my ownactually this questions is threefoldwhy does after logging in it redirects to accountsprofile is there a way to change that preferably after successfully logging in i would like django to redirect back to the page before the login pageif i were to create my own view and template for accountsprofile then where should i put it djangos builtin users auth user is shared among all django apps inside a project so should i place the viewpy in the project folder and not inside the app folderor does django profile actually takes care of this whole accountprofiles thing i already extended djangos user class with my own userprofile but it is more like additional fields to the user table than an actual profile i did not create avatars or anything like that just simple stuff like addresses and phone numbers but most importantly some custom user types that my app depends on,['python'] +266800,controllers split by areas possible duplicatehow do i register a controller that has been created in an area i have the question is it possible to do the nexti have three areas defaultsiteonesitetwoinside each area i have a apicontroller with the same name but in different namespaces of coursemvcappliactionareas defaultcontrollersvaluescontrollermvcappliactionareassiteonecontrollersvaluescontrollermvcappliactionareassitetwocontrollersvaluescontrolleri also have a value of current which i would like to use area in configurationi would like to map user to controller in the proper area which i can find in the configuration if he enters in the browserapivaluesfor example if current area in config file is siteone then this request should be mapped to mvcappliactionareassiteonecontrollersvaluescontroller controller but if i change current area in config file to sitetwo of default it should be mapped to correct controllerps with mvc controller it is easy you just have to set your routeroutesmaproute name default url controlleractionid defaults new controller home action index id urlparameteroptional namespaces new mvcapplicationwebareas sitename controllers,['c#'] +266806,no row returned from db but there are records to be returned i am executing the select statement with using jdbc sybase driver jconn3 i checked the statement with executed manually on isql and all rows returned correctly the statement which is executing on jdbc select from mytable where date between and i added the dateformat as ymmdd hhmmss and set the time value as 0 for begin date and 235959 for end date it is not working the row count must be 10 but it is sometimes 770 sometimes 990 sometimes 564 etc there is no any specific row count which everytime returnedafter that i added an extra execution which returns only row count first i am executing the select count from statement then executing select from and now select from query returns the correct number of records everytime this can not be related with caching and weird thing is i am using same preparedstatement and resultset objects for those two executionany idea on that issuerulmeq here is the code added on 20120329resultset rs nullpreparedstatement ps nullps myconngetconnectionpreparestatementselect count from mytable where date between and pssetdate1 new javasqldatebegindategettime format ymmddpssetdate2 new javasqldateenddategettime format ymmddrs psexecutequeryrsnext some logs hereps myconngetconnectionpreparestatementselect from mytable where date between and pssettimestamp1 new javasqltimestampbegindategettime format ymmdd hhmmss pssettimestamp2 new javasqltimestampenddategettime format ymmdd hhmmss rs psexecutequerywhilersnext,"['java', 'sql']" +266860,how to get custom attribute value from an xmpp xml message ok guys simple question but pretty important to meso other android client are sending this xml msgmessage id6ymdm19 tosmack typechat subjectnormalsubject received xmlnsurnxmppreceipts idhvgqw5messageand my listener is roughly like thisprivate class msglistener implements chatstatelistener constructor public msglistener overridepublic void processmessagechat chat orgjivesoftwaresmackpacketmessage message string xmlmessage messagetoxml logvtag xml chat xmlmessage getextension namespace try urnxmppreceipts ifxmlmessagecontainsrequest xmlns logdtag new chat message arrive reply with received replyreceivedmessage else ifxmlmessagecontainsreceived xmlns logdtag received notification arrived packetextension statusextension messagegetextensionurnxmppreceipts logdtag extension name statusextensiongetelementname logdtag extension xml statusextensiontoxml logdtag extension string statusextensiontostring in this case i want to get the value of attribute id inside the received element tagbut what i got on my log is like thisreceived notification arriveddchatadapter320 extension name receiveddchatadapter320 extension xml received xmlnsurnxmppreceiptsreceiveddchatadapter320 extension string orgjivesoftwaresmackpacketdefaultpacketextension44f10430so how i can get the hvgqw5 updateactually there is something weirdi have receive the xml accordinh from my smack debug like this dsmack320 054028 pm rcv 1156991856 message id6ymdm19 tosmack fromsmack typechatsubject dsmack320 054028 pm rcv 1156991856 normalsubjectthreadcr0900thread received xmlnsurnxmppreceipts idhvgqw5active xmlns dsmack320 054028 pm rcv 1156991856 olchatstatesmessagebut when i execute messagetoxml it is just print out like thisxml chat message id6ymdm19 tosmack fromsmack typechatsubjectnormalsubjectthreadcr0900threadreceived xmlnsurnxmppreceiptsreceivedactive xmlns messagewhy this is happening why do i miss the id,"['java', 'android']" +266880,ios a are uitableviewcell reuseidentifiers global what is the scope of the table view cells reuse identifiers aa are they shared within one table view instance or within all the table views that use the same reuse identifiereg i have a footableviewcontroller and a bartableviewcontroller both of them have a tableview and both of them use cell identifier in tableviewcellforrowatindexpath but the cell propertiesstyling are different the question is will those cells be reused across table views or not,"['iphone', 'ios']" +266902,how to determine if python script was run via command line backgroundi would like my python script to pause before exiting using something similar toraw inputpress enter to closebut only if it is not run via command line command line programs should not behave this wayquestionis there a way to determine if my python script was invoked from the command line python myscriptpyverses doubleclicking myscriptpy to open it with the default interpreter in the os,['python'] +266921,how to combine c strings and arduino strings i have been writing a library for my project for now i am using arduino the problem that i have is that string in c and in arduino differthat is i would like my library to be independent of arduino so i am using include string and later declaring string s however in arduino strings are defined by arduino and declared string s2when i include my library to the sketch i get error string no such file or directory on the line where i try to include c string library include stringis there a way to make arduino use c string library or convert string to arduino string when compiling,['c++'] +266928,how to thisplay a pdf stream in a browser using javascript i am accessing an existing wcf web service which returns a pdf as a byte stream using jquerys ajax methodswhen the call to the service completes i end up with a javascript variable containing a pdf the variable has the binary data in starting pdf14i would like to thisplay this pdf in a new browser window but i am having difficulty achieving this my research so far shows that i might be able to achieve what i want using a data uri so my code that is called when the ajax call completes is as followsfunction gotpdfdata here data contains pdf14 etc var datauri dataapplicationpdfbase64 base64encodedata var win windowopen your pdf width1024height768resizableyesscrollbarsyestoolbarnolocationnodirectoriesnostatusnomenubarnocopyhistoryno windocumentlocationhref dataurithis causes a new browser window to open but the contents are blankinterestingly if i point my browser ie9 at an existing file on my local thisk by using a file uri such as filectmpexamplepdf then i get the same result ie a blank windowis there any way i can thisplay this pdf data,"['javascript', 'jquery']" +266945,how to implement erb partials in a non rails app i want to do something like thisrequire erbvar testtemplate erbnew filenewtemplateerbreadrendered templateresultbindingbut how can i use partials in templateerb,['ruby'] +266951,does there exists a dotnet 45 async timer i would like to have a timer where i can wait on with the await keyword i was just curious if it exists,"['c#', '.net']" +266971,optimisticconcurrencyexception with systemwebproviders i am using the new universal providers from microsoft for session in sql server the old implementation of session on sql server required a job running every minute to clear expired sessions the new one does this check and clear on every request since i am actually running in sql azure i do not have sql agent to schedule jobs so this sounds like a reasonable way to go about it no i do not want to pay for azure cache for sessionthe problem is when multiple users access the site at the same time they are both trying to clear the same expired sessions at the same time and the second gets an optimistic concurrency exceptionsystemdataoptimisticconcurrencyexception store update insert or delete statement affected an unexpected number of rows 0 entities may have been modified or deleted since entities were loaded refresh objectstatemanager entries at systemdatamappingupdateinternalupdatetranslatorupdateientitystatemanager statemanager ientityadapter adapter at systemdataobjectsobjectcontextsavechangessaveoptions options at systemwebprovidersdefaultsessionstateproviderpurgeexpiredsessions at systemwebprovidersdefaultsessionstateproviderpurgeifneeded at systemwebsessionstatesessionstatemodulebeginacquirestateobject source eventargs e asynccallback cb object extradata at systemwebhttpapplicationasynceventexecutionstepsystemwebhttpapplicationiexecutionstepexecute at systemwebhttpapplicationexecutestepiexecutionstep step boolean completedsynchronouslyi am using elmah for error logging and this is showing up with some frequency before i try to configure elmah to ignore the errors does anyone know of a way to stop the errors from happening in the first place is there some configuration with the new providers that i am missing,['asp.net'] +266992,does the mysql cli tool provide a way to thisplay binary data in a consolefriendly manner i have a mysql database containing a table with a binarytyped column i would like to be able to project that column without having to run it through eg hex does the mysql cli tool have a configuration option or other means to thisplay a representation of binary data in a manner that would not output arbitrary bytes for my console to interpret in hilariousannoying ways,['mysql'] +267001,file icon overlay in java for windows i am trying to implement icon overlaying on files and folders just like tortoise svn or dropbox does i did a lot of searching on the internet but i cannot find a solution in javacan anyone help me with this,['java'] +267006,how to make the mysql memory engine store more data i want to alter a table from innodb to memory engineso i typed this commandalter table sns enginememorythen the mysql shows error 14 hy0 the table sql738 19 is fullthe data size for the table is 1gb and i have 8gb memoryi checked mycnf and i did not find where to change the max size setting should not i be able to store more data,['mysql'] +267015,what are the differences between mappingbinding and parsing i am starting to learn webservices in java ee6i did web development before but never nothing related to web servicesall is new to me and the books and the tutorials i find in the web are to technical i started learning about xsd schemas and also xml in that topic i feel confident i understand what are the schemas used for and what validation meansnow my next step is learning about jaxbjava api for xml binding i rode some about it and i did also some practice in my ide but i have lots of basic doubts that make me stuck and cannot feel confident to continue to the next topicill appreciate a lot if someone could explain me well my doubtswhat does it mean mapping and what is a mapping toolwhat does it mean binding and what is a binding toolwhat does it mean parsing and what is a parsing toolhow is jaxb related to mappingbinding and parsingi am seeking for a good answer built by you not just a copy paste from googleive already been online a few hours and only got confused,['java'] +267036,salesforce on ios login without using the salesforce webview i am creating an iphone application that uses salesforce as it is serverside data component i need to access the database from the application to retrieve data for whichever user logs into the app to do this i need to authenticate with sales forcei am using the rest api template that was available in xcode after installing salesforce but i keep getting thisis there any way i can login to salesforce programmatically i would like our use of salesforce to be behind the scenes so to speak so that our users never have to directly interact with salesforce themselves is there any way to do this,"['iphone', 'ios']" +267047,line breaks in textarea used in a mvc c website app i am using aspnet mvc c in visual studio web dev i have a couple of textareas which are populated with data and then updated to a database record is it possible to have line breaks saved when a record is updated to the database i currently view the data on the homepage but at the moment if someone writes couple of paragraphs including line breaks the formatting will be lostif this is not possible no problem but just wanted to ask if it is thanksthe code on the view page looks like thisdiv classeditorfield htmltextareaformodel modelpara1 new cols 75 rows 5 htmlvalidationmessageformodel modelpara1divi then have a button that submits the formthe controller code that handles the submission looks like thishttppost public actionresult updatedata data if modelstateisvalid dataid 1 ef need to know which row to update in the database dbentrydatastate entitystatemodified dbsavechanges return redirecttoactionindex home return viewdata and the model code for the database looks like thisusing systemusing systemcollectionsgenericusing systemlinqusing systemwebusing systemdataentityusing systemcomponentmodeldataannotationsnamespace dfaccountancymodels public class data datatypedatatypemultilinetext public int id get set public string para1 get set public string para2 get set public class datadbcontext dbcontext public dbsetdata data get set the homepage codemodel ienumerabledfaccountancymodelsdata viewbagtitle indexh2 df accountancyh2divfieldsetlegendabout uslegendforeach data in modeltable tr td rowspan2 width50 b suspenthisse lectus massa feugiat at cursus ac sollicitudin a metus quisque adipiscing commodo sem vitae eleifend maecenas ante risus hendrerit ac tempor et feugiat eu sapien sed sem massa sodales a varius sit amet porta in turpis duis ullamcorper magna sed risus lobortis luctus quisque volutpat enim ut erat tristique sit amet posuere sem ullamcorper nulla consequat lectus in sapien sagittis cursus quisque elit augue luctus sed semper non fringilla sed quam pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas fusce vitae augue quis nisi tincidunt ullamcorper duis posuere ultricies turpis at dictum vivamus at odio eros nunc orci lectus ornare non tincidunt sed venenatis id lorem nulla ullamcorper leo quis pellentesque sollicitudin dui libero vehicula lectus lobortis consequat orci dui in augue ut gravida enim convallis sem luctus sit amet eleifend lorem malesuada suspenthisse in augue diam eu laoreet diam b td td div classthisplayfield htmlrawdatapara1replaceenvironmentnewline br div td tr tr td div classthisplayfield htmlrawdatapara2replaceenvironmentnewline br div td trtable fieldsetdivthe full update view page codemodel dfaccountancymodelsdata viewbagtitle update h2updateh2script srcurlcontentscriptsjqueryvalidateminjs typetextjavascript scriptscript srcurlcontentscriptsjqueryvalidateunobtrusiveminjs typetextjavascriptscriptscript typetextjavascript function cl button1clickfunction para1val function cl button2clickfunction para2val scriptusing htmlbeginform htmlvalidationsummarytruefieldset legenddatalegend div classeditorlabel htmllabelformodel modelpara1 div div classeditorfield htmltextareaformodel modelpara1 new cols 75 rows 5 htmlvalidationmessageformodel modelpara1 input idcl button1 typebutton valueclear paragraph div div classeditorlabel htmllabelformodel modelpara2 div div classeditorfield htmltextareaformodel modelpara2 new cols 75 rows 5 htmlvalidationmessageformodel modelpara2 input idcl button2 typebutton valueclear paragraph div p input typesubmit valueupdate input typereset valuereset to begining pfieldsetdiv htmlactionlinkback to list indexdiv,['c#'] +267055,can i override a hidden but public method and call its super method there is a non public api that i need to override in order to workaround a quirk with androids webviewthe api is hidden but it is public hide pending api council approval public boolean selecttext so i can override it by simply declaring it in my own webview class minus the overridepublic boolean selecttext is it possible to call the super method from my override normally i could writepublic boolean selecttext return superselecttextbut the method is hidden so superselecttext is not available if i use reflectionpublic boolean selecttext return boolean webviewclassgetmethodselecttextinvokethis object nulli get an infinite loop because it calls my overridden methodis there anyway to override this method and be able to call the super methodthanks,"['java', 'android']" +267067,allowing simplified chinese input the company i work for is bidding on a project that will require our ecommerce solution to accept simplified chinese input after doing a bit of research it seems that aspnet makes globalization configuration easyconfiguration systemweb globalization fileencodingutf8 requestencodingutf8 responseencodingutf8 culturezhhans uicultureenus systemwebconfigurationquestionsis this really all there is to it in aspnet it seems to good to be trueare there any db considerations with sql server 2005 will the db accept the simplified chinese without additional configuration,"['c#', 'asp.net']" +267092,py2app picking up git subdir of a package during build we use py2app extensively at our facility to produce self contained app packages for easy internal deployment without dependency issues something i noticed recently and have no idea how it began is that when building an app py2app started including the git directory of our main librarycommonlib for instance is our root python library package which is a git repo under this package are the various subpackages such as database utility etccommonlib git because commonlib is a git repo init py database init py utility init py etcin a given project say foo we will do imports like from commonlib import xyz to use our common packages building via py2app looks something like python setuppy py2appso the recent issue i am seeing is that when building an app for project foo i will see it include everything in commonlibgit into the app which is extra bloat py2app has an excludes option but that only seems to be for python modules i cant quite figure out what it would take to exclude the git subdir or in fact what is causing it to be included in the first placehas anyone experienced this when using a python package import that is a git reponothing has changed in our setuppy files for each project and commonlib has always been a git repo so the only thing i can think of being a variable is the version of py2app and its deps which have obviously been upgraded over timeediti am using the latest py2app 064 as of right now also my setuppy was first generated from py2applet a while back but has been hand configured since and copied over as a template for every new project i am using pyqt4sip for every single one of these projects so it also makes me wonder if its an issue with one of the recipesupdatefrom the first answer i tried to fix this using various combinations of exclude package data settings nothing seems to force the git directory to become excluded here is a sample of what my setuppy files generally look likefrom setuptools import setupfrom myapp import versionappname myappapp myapydata files options includes atexit sip pyqt4qtcore pyqt4qtgui strip true iconfileuimyappicns resourcessrcmyapng plist cfbundleiconfileuimyappicns cfbundleidentifiercomcompanymyapp cfbundlegetinfostring appname cfbundleversion version cfbundleshortversionstring version setup appapp data filesdata files optionspy2app options setup requirespy2appi have tried things likesetup exclude package data commonlib git exclude package data git exclude package data commonlibgit exclude package data git update 2i have posted my own answer which does a monkeypatch on thistutils its ugly and not preferred but until someone can offer me a better solution i guess this is what i have,['python'] +267112,php oop core framework i am just posting this question so some of you might be able to point me in the right way i am slowly warming up to oop starting to understand the concept i want to make a good solid core or foundation to be used as a cms backend it will also use mvc i have been using as the mvc basethe thing i cant figure out is the followingsay on the projectpage in the backend i have 2 sections htmltext and projects and i should be able to edit them both the uri would be something likedomainbackendprojects the method would be the index and show the 2 sectionswhen i click on projects how should it be handleddomainbackendprojectsprojects ordomainbackendprojectslistone step further a project will hold some images or a gallerydomainbackendprojectsedit5gallery2my question here is first would this be a good way to go and even more important how would this be implemented in oopthe main projects controllerclass projects function index view index function edit project new project projectdata projectload5 a single project controllerclass project function construct thisprojectmodel thisloadmodelproject model prepare the model to be used function loadid thisprojectmodelloadprojectid project modelclass project model extends model extends for db access and such function construct do stuff function loadprojectid return thisdbqueryselect from projects where id id limit 1 now my question if this project has images where should i load the image class to handle those should i load it in the project model like thisimages new images and have a function inside the modelfunction loadimagesid thisimagesloadidand then images would be something likeclass image extends model extends for db access and such function construct function loadid return thisdbqueryselect from project images where id id limit 1 it seems controllers and models gets mixed up this way yet in a logical way a project is a container that holds projectinfo which could be text images and maybe videos how would i go about to set that up logically as well,['php'] +267129,trouble installing pg gem trying to install the pg gem gives me errorsi am using ruby 193p125 built using rbenvrubybuild i installed postgresql using the oneclick installer i am able to connect to the db using pgadmin i am running out of ideas gem install pg building native extensions this could take a whileerror error installing pg error failed to build gem native extension userssandropadinrbenvversions193p125binruby extconfrbchecking for pg config yesusing config values from usrbinpg configchecking for libpqfeh yeschecking for libpqlibpqfsh yeschecking for pg config manualh yeschecking for pqconnectdb in lpq yeschecking for pqconnectionusedpassword yeschecking for pqisthreadsafe yeschecking for pqprepare yeschecking for pqexecparams yeschecking for pqescapestring yeschecking for pqescapestringconn yeschecking for pqgetcancel yeschecking for lo create yeschecking for pg encoding to char yeschecking for pg char to encoding yeschecking for pqsetclientencoding yeschecking for rb encdb alias yeschecking for rb enc alias yeschecking for struct pgnotifyextra in libpqfeh yeschecking for unistdh yeschecking for rubysth yescreating extconfhcreating makefilemakecompiling pgccompiling pg connectioncpg connectionc in function apgconn wait for notifyapg connectionc1986 warning arb thread selecta is deprecated declared at userssandropadinrbenvversions193p125includeruby191rubyinternh379pg connectionc in function apgconn blockapg connectionc2512 warning arb thread selecta is deprecated declared at userssandropadinrbenvversions193p125includeruby191rubyinternh379compiling pg resultclinking sharedobject pg extbundleld in usrlocalliblibssl098dylib missing required architecture x86 64 in file for architecture x86 64collect2 ld returned 1 exit statusmake pg extbundle error 1gem files will remain installed in userssandropadinrbenvversions193p125librubygems191gemspg0132 for inspectionresults logged to userssandropadinrbenvversions193p125librubygems191gemspg0132extgem makeout,['ruby'] +267147,how to detect safari chrome ie firefox and opera browser i have 5 addons extensions for ff chrome ie opera and safari i need the code to recognize the user browser and redirect on click in an install button to download the corresponding addon,['javascript'] +267175,rotate a triangle around its center with javascript it is late on a friday and i am scratching my head on this onei am trying to draw an equilateral triangle and rotate it around it is center but for some reason i am having trouble determining it is center pointheres a jsfiddle where you can see how i am translating to the center of the canvas and then drawing the triangle out from there using the equationvar width 30var height width mathsqrt32to determine the ratio of width heightwhat am i missing here any thoughts would be most appreciated,['javascript'] +267180,controlling python ply lexer states from parser i am working on a simple sql select like query parser and i need to be able to capture subqueries that can occur at certain places literally i found lexer states are the best solution and was able to do a poc using curly braces to mark the start and end however the subqueries will be delimited by parenthesis not curlys and the parenthesis can occur at other places as well so i cannot being the state with every openparen this information is readily available with the parser so i was hoping to call begin and end at appropriate locations in the parser rules this however did not work because lexer seem to tokenize the stream all at once and so the tokens get generated in the initial state is there a workaround for this problem here is an outline of what i tried to dodef p value subqueryp value start sub end sub p0 p1 def p start subp start sub opar start subqueryplexer p0 p1def p end subp end sub cpar subquery end subqueryplexer p0 subquerythe start subquery and end subquery are defined like thisdef start subquerylexer lexercode start lexerlexpos record the starting position lexerlevel 1 lexerbeginsubquery def end subquerylexer value lexerlexdatalexercode startlexerlexpos1 lexerlineno valuecountn lexerbegininitial return valuethe lexer tokens are simply there to detect the closeparenlextokenrdef t subquery subqstt lexerlevel 1lextokenrdef t subquery subqent lexerlevel 1lextokenrdef t subquery anychart passi would appreciate any help,['python'] +267219,something seems wrong with the layout jbutton showing unexpected behaviour at resize of the window jre version 17 update 3expected behaviouras i run the program it works as expected everything works smoothly as when i click on stop jbutton the animation stops and the text on the same jbutton changes to start now when i click on ball colour jbutton the colour of the ball changes as well as the colour of the ball colour jbutton also changes to that of the ball this whole behaviour works if i run my application as is without resizingunexpected behaviourbut when i resize my jframe by pulling the right side that is when unexpected behaviour of my application is shown in the sense that if i press stop jbutton and then click on ball colour button the text on the jbutton clicked earlier whose text changed to start will change to stop again when it should not be as well as the colour of the ball colour jbutton will remain unchanged or will turn to blue when it should be changed to the colour of the ball i am attaching the pics for more info but if you will try to resize it back to it is original size or closer to that then things will come back to normal why is this happening any idea or clue will be much appreciatedas my application runs with expected behaviour as described above and here the unexpected behaviourbottomline why the application runs as usual as it should be at the beginning but not when resized by dragging it is right side but again if you bring it to it is original size or closer to it things come back to normal it works as expected so considering the scenario am i doing something wrong in the program or is this exactly the situation where i should be using the swingworker or is this an issue with the layout or something hidden related to content pane please do put some light here is the code i am using i had brought it down to the minimum as i think to demonstrate my problem import javaawtimport javaawteventimport javaxswingpublic class ballanimation private int x private int y private boolean positivex private boolean positivey private boolean istimerrunning private int speedvalue private int diameter private drawingarea drawingarea private timer timer private int colourcounter color colours colorbluedarker colormagentadarker colorblackdarker colorreddarker colorpinkdarker colorcyandarker colordark graydarker coloryellowdarker colorgreendarker private color backgroundcolour private color foregroundcolour private actionlistener timeraction new actionlistener public void actionperformedactionevent ae x getx y gety drawingareasetxycolourvaluesx y backgroundcolour foregroundcolour private jpanel buttonpanel private jbutton startstopbutton private jbutton speedincbutton private jbutton speeddecbutton private jbutton resetbutton private jbutton colourbutton private jbutton exitbutton private componentadapter componentadapter new componentadapter public void componentresizedcomponentevent ce timerrestart startstopbuttonsettextstop istimerrunning true public ballanimation x y 0 positivex positivey true speedvalue 1 colourcounter 0 istimerrunning false diameter 50 backgroundcolour colorwhitebrighter foregroundcolour colourscolourcounter timer new timer10 timeraction private void createandthisplaygui jframe frame new jframeball animation framesetdefaultcloseoperationjframeexit on close framesetlocationbyplatformtrue drawingarea new drawingareax y backgroundcolour foregroundcolour diameter drawingareaaddcomponentlistenercomponentadapter frameaddmakebuttonpanel borderlayoutline end frameadrawingarea borderlayoutcenter framepack framesetvisibletrue private jpanel makebuttonpanel buttonpanel new jpanel buttonpanelsetlayoutnew gridlayout0 1 buttonpanelsetborderborderfactorycreatelineborder colordark gray 5 true startstopbutton new jbuttonstart startstopbuttonsetbackgroundcolorgreendarker startstopbuttonsetforegroundcolorwhitebrighter startstopbuttonaddactionlistenernew actionlistener public void actionperformedactionevent ae systemoutprintlnstartstop jbutton clicked if istimerrunning startstopbuttonsettextstop timerstart istimerrunning true buttonpanelrevalidate buttonpanelrepaint else if istimerrunning startstopbuttonsettextstart timerstop istimerrunning false buttonpanelrevalidate buttonpanelrepaint startstopbuttonsetborderborderfactorycreatelineborder colorwhite 4 true buttonpaneladdstartstopbutton colourbutton new jbuttonball colour colourbuttonsetbackgroundcolourscolourcounter colourbuttonsetforegroundcolorwhite colourbuttonaddactionlistenernew actionlistener public void actionperformedactionevent ae systemoutprintlncolour jbutton clicked timerrestart colourcounter if colourcounter 9 colourcounter 0 foregroundcolour colourscolourcounter drawingareasetxycolourvaluesx y backgroundcolour foregroundcolour drawingareasetforegroundforballforegroundcolour colourbuttonsetbackgroundforegroundcolour colourbuttonrevalidate colourbuttonrepaint timerstart colourbuttonsetborderborderfactorycreatelineborder colorwhite 2 true buttonpaneladdcolourbutton exitbutton new jbuttonexit exitbuttonsetbackgroundcolorreddarker exitbuttonsetforegroundcolorwhitebrighter exitbuttonaddactionlistenernew actionlistener public void actionperformedactionevent ae systemoutprintlnexit jbutton clicked timerstop systemexit0 exitbuttonsetborderborderfactorycreatelineborder colorreddarkerdarker 4 true buttonpaneladdexitbutton return buttonpanel private int getx if x 0 positivex true else if x drawingareagetwidth diameter positivex false return calculatex private int calculatex if positivex return x speedvalue else return x speedvalue private int gety if y 0 positivey true else if y drawingareagetheight diameter positivey false return calculatey private int calculatey if positivey return y speedvalue else return y speedvalue public static void mainstring args runnable runnable new runnable public void run new ballanimationcreateandthisplaygui swingutilitiesinvokelaterrunnable class drawingarea extends jcomponent private int x private int y private int balldiameter private color backgroundcolor private color foregroundcolor public drawingareaint x int y color bcolor color fcolor int dia thisx x thisy y balldiameter dia backgroundcolor bcolor foregroundcolor fcolor setborderborderfactorycreatelineborder colordark graydarker 5 true public void setxycolourvaluesint x int y color bcolor color fcolor thisx x thisy y backgroundcolor bcolor foregroundcolor fcolor repaint public dimension getpreferredsize return new dimension500 400 public void paintcomponentgraphics g gsetcolorbackgroundcolor gfillrect0 0 getwidth getheight gsetcolorforegroundcolor gfillovalx y balldiameter balldiameter latest edit,['java'] +267228,how to ignore characters on a mysql select like i have a table with a phone column where data may have spaces dotsdashes or signs between the numbersi need to do a search with like wildcards that ignore all those characters for examplea record may have phone as 123456 7890a query looking for 6789 or any complete or incomplete sequence of proper digits in order should bring up that recordunfortunately i cant cleanup the original table to remove the nondigit characters and do a plain select like mysql has functions to substituteremove characters from strings but cannot find a way to use them inside a query with a widlcarded likeany help will be much appreciated,['mysql'] +267276,js windowopen then print print does not work in ie after opening a new window it works in chromeheres a testerhtmlheadscript typetextjavascript function openwin mywindowwindowopenwidth200height100 mywindowdocumentwritepthis is mywindowp mywindowfocus mywindowprint does not work scriptheadbodyinput typebutton valueopen window onclickopenwin bodyhtml,"['javascript', 'html']" +267298,getting info about bad memory address in lldb i am trying to debug an exc bad access in my iphone app it is crashing on a method call and on the line of the method is exc bad access code1 address x before i would have just used gdb info mallochistory x to start debugging but i am having trouble finding a parallel command in lldb i saw this thread that said to use instruments but when i do i still get the crash but i cannot figure out how to tell exactly where the app is crashing from in instrumentsi just need to figure out where this piece of memory that is crashing was pointing to what is the best way to do this either using lldb or instruments,['iphone'] +267304,how can a lamp guy easily implement websockets i have always worked with apache mysql and php i would like to eventually branch out to pythondjango or rubyruby on rails but that is another thiscussion two great things about apache mysql and php are all three are ubiquitous and it is very easy to launch a website just set up an apache virtual host import the database into mysql and copy the php files onto the server that is it this is all i have ever done and all i have ever known please keep this in mindthese days it is becoming increasingly important for websites to be able to deliver data in realtime to the users users expect this too due to the live nature of facebook and gmail this effect can be faked with ajax polling but that has a lot of overhead as explained here i would like to use websockets now remember that i have always been a lamp guy i have only ever launched websites using the method i described earlier so if i have say a cakephp site how can i add on the feature of websockets do i need to install some other server or something or can i get it to work smoothly with apache will it require apache 24 please explain the process to me keeping in mind that i only know about lamp thanks,['php'] +267305,refresh fragment when dialogfragment is thismissed is there any way i can detect when a dialogfragment is thismissed so that i can update its parent fragment,['android'] +267346,when adding an html5 manifest all my jquery mobile ajax requests fail with status 0 i have a working jquery mobile application which does some simple ajax requests for static json files all is well until i add a manifest merely changing html to html manifestmyappappcache breaks my ajax heres my manifestcache manifestcachejquerymobile101cssimagesajaxloaderpngimagesicons18whitepngjquery164jsjquerymobile101jsi have tried addingnetworksalesorgjsonmakes no difference serious de ja vu here but i do not know what the solution was,['jquery'] +267351,instantiate a class from its textual name do not ask me why but i need to do the followingstring classname someclassname object o magicallycreateinstancesomeclassnamei want to know how many ways there are to do this is and which approach to use in which scenarioexamplesactivatorcreateinstanceassemblygetexecutingassemblycreateinstanceany other suggestions would be appreciatedthis question is not meant to be an open ended thiscussion because i am sure there are only so many ways this can be achieved,['c#'] +267362,how do i get the network interface and its right ipv4 address i need to know how to get all network interfaces with their ipv4 address or just wireless and ethernetto get all network interfaces details i use thisforeach networkinterface ni in networkinterfacegetallnetworkinterfaces ifninetworkinterfacetype networkinterfacetypewireless80211 ninetworkinterfacetype networkinterfacetypeethernet consolewritelineniname and to get the all hosted ipv4 addresses of the computeripaddress ips dnsgethostaddressesdnsgethostnameforeach ipaddress ip in ips if ipaddressfamily addressfamilyinternetwork consolewritelineip address ip but how to get the network interface and its right ipv4 address,['c#'] +267386,javascript uncaught typeerror cannot call method addeventlistener of null i am trying to do something fairly simple but for the reason of me probably not being good enough to search documentation i cannot get this to worki have a functioning inline js that looks like thisa titlewolfram ip calc hrefjavascripttxtpromptenter20ip20address20eg2010203040291234520iftxt20windowopentxtvoidocomputeafor various reasons i am trying to seperate the js and this is where i hit a snagi have created the following test page that gives me the error uncaught typeerror cannot call method addeventlistener of nullhtml head profile script typetextjavascriptvar compute documentgetelementbyidcomputecomputeaddeventlistenerclick computethatthing falsefunction computethatthing txtpromptenter20ip20address20eg20102030402912345 iftxt windowopentxt scriptheadbodya titlewolfram ip calc idcompute hrefjavascriptvoidotestabodyhtmlthe only thing i have been able to find that points to a problem like that is that addeventlistener cannot work with a but should handle img which suits me fine as i am going to pour this on some images so i tried adding the following to no availimg idcompute src thanks in advance for pointing out what i am doing wrong it is probably glaringly obvious but i have close to zero experience with js and i have gone mostly by cargo culting when i have needed it until now,['javascript'] +267412,what does denote in c i am new to c and directly diving into modifying some code for a project i received however i keep seeing code like this class samplecollectiontand i cannot make sense of what the t means nor what it is calledif anyone would care to help me just name what this concept is called i can search it online however i am clueless as of now,"['c#', '.net']" +267415,why does this c code output the result this is the c codeincludeiostreamusing namespace stdint a8int funint a a return aint main cout a endl funa endl a endl return 0why does it output64 64 8the operators associativity is left to right so why not output 8 64 64does it have the relation to the sequence point and the effect side,['c++'] +267420,viewpager fragments getting destroyed over time i am using androids supportv4 package to develop a viewpager containing multiple fragmentsi am trying to hide the views when the user changes page so i implemented an onpagechangelistener to listen to my adapter and call an update method in my fragments when when a page change occurs but i am getting a nullpointerexception and i cannot figure out whyhere is the codepublic class myactivity extends fragmentactivity implements onpagechangelistener private static final int num items 2 private viewpager mpager private static spaceadapter madapter called when the activity is first created override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutfragment pager madapter new spaceadaptergetsupportfragmentmanager mpager viewpager findviewbyidridpager mpagersetadaptermadapter mpagersetonpagechangelistenerthis public static class spaceadapter extends fragmentpageradapter public spaceadapterfragmentmanager fm superfm override public int getcount return num items override public fragment getitemint position switch position case 0 return new myfragment case 1 return new myfragment default return new myfragment override public void onpagescrollstatechangedint arg0 logipagination scroll state changed arg0 override public void onpagescrolledint arg0 float arg1 int arg2 logipagination page scroll arg0 with arg1 arg2 if madaptergetitemarg0 instanceof iupdateonpage iupdateonpage madaptergetitemarg0updateonpage override public void onpageselectedint arg0 logipagination page selected arg0 andpublic class myfragment extends fragment implements surfaceholdercallback iupdateonpage private surfaceview charts override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate override public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate view v inflaterinflaterlayoutcrew null bindviewsv return v private void bindviewsview v charts surfaceview vfindviewbyidridciv charts chartsgetholderaddcallbackthis logiwtf huh stringvalueofcharts null logs false override public void updateonpage if charts null logicrew surface hidden chartssetvisibilityviewgone else logicrew surface charts is null this here gets logged wwhen i copypasted i removed the surfaceholdercallback methods but they are there the bindviewsv method logs if charts null and that always returns false when i page updateonpage gets called and charts null returns true why does this happen and how do i get around itand this is line 108chartssetvisibilityviewgone,"['java', 'android']" +267442,minheight and table cells i have done a little bit of research on this but i just wanted to ask to people whod know much better than iis it true that setting a height to a table cell only acts as minheighti know this is true in firefox but what other browsers does this happen in,['css'] +267463,endianness and socket programming in c i am making a program that communicate with certain patient monitor using c sockets i am using connectionless sockets udp to communicate with the device but there is endianness mismatch between my computer and device and so far i was doing this to get parse response from the patient monitorrecvfromint socket char buffer size t length int flags struct sockaddr address socklen t address lenthen i was casting the buffer directly to structure and using the ntohs and ntohl to change the byte ordering for examplestruct a a struct a bufferstruct a bbv1 ntohsav1bv2 ntohlav2after reading few examples over internet i figured out that this may be wrong approach due to compiler dependent padding but i am not sure about it i need simple way to unmarshall a buffer to a c structure with correct endiannes the structure that i am receiving can be of unpredictable length and little complex as well i need fast and easy approach to do the unmarshallingi do not control sender sender is in network byte order my question is only thatis is safe to cast a buffer to a structure and then use ntohs and ntohl on this casted structure to make hostbyte order replica of this structure is it a fastest approach if not then what can be the fastest approach,['c'] +267467,an alternative to the device udid preparing ourselves possible duplicateuidevice uniqueidentifier deprecated what to do now i know there have been quite a few questions on so about this but i think that because apple is moving ahead of schedule and actively denying applications that make use of udids us developers need to take an active approach and thiscuss this matter in bulkso the question is what is a good stable and correct alternative for unique device identification other than accessing it is udid property,['ios'] +267470,windows unicode c stream output failure i am currently writing an application which requires me to call getwindowtext on arbitrary windows and store that data to a file for later processing long story short i noticed that my tool was failing on battlefield 3 and i narrowed the problem down to the following character in its window titleso i created a little test app which just does the followingstdwcout lu2122low and behold that breaks output to the console window for the remainder of the programwhy is the msvc stl choking on this character and i assume others when apis like messageboxw etc thisplay it just finehow can i get those characters printed to my filetested on both vc10 and vc11 under windows 7 x64sorry for the poorly constructed post i am tearing my hair out herethankseditminimal test caseinclude fstreaminclude iostreamint main stdwofstream test filetesttxt test file lu2122 stdwcout lu2122expected result a character printed to console and fileobserved result file is created but is empty no output to consolei have confirmed that the font im using for my console is capable of thisplaying the character in question and the file is definitely empty 0 bytes in sizeeditfurther debugging shows that the failbit and badbit are set in the streamsediti have also tried using boostlocale and i am having the same issue even with the new locale imbued globally and explicitly to all standard streams,['c++'] +267476,full screen in customize theme my app need to show as full screen now i know how to add this feature into application tag in mainfest usingandroidthemeaandroidstylethemenotitlebarfullscreenhowever i have my own theme called codefont and i cannot use two themes at the same application how i can add this feature into my own style tag in my resources file there is no such androidstyle tagplz help thx,['android'] +267483,use data type class type as key in a map i have class base and classes derived 1 derived 2 i need derived classes to have an id those ids are used for further lookups etc and thus need to be consecutive no just some random numbers because derived classes are created by user id can not be member of derived n so i came up with derivedtype classclass derivedtype static unsigned id unsigned m idpublic derivedtype m idid now i want to create a mapping between derived n and derivedtypewhenever derived n is created this mapping looks if derivedtype for particular derived n already exist and returns it otherwise create new and stores in the mapactual questionis there any way to use stdmap with data type as key in the mapi am not afraid of any templatemetaprogram solutionor is there elegant way how to achieve my goaledit date type data type i mean like classtype i am sorry i want to use it likederived 5 dderivedtype dt gettyped derived 5 is looked up in map returning particular derivedtypedtgetidevery instance of derived n with same n should have the same id throu derivedtypeedit2 my answeri found better solution for my problem it is like thisatomic counter s nexteventclassidtypedef int cid ttemplateclass eventclassclass eventclassidpublic static cid t getid static cid t classid eventclassidnext return classid static cid t next return s nexteventclassid since my question was how to use datatype in a map i will mark some of yours answers thank you,['c++'] +267484,ios how to put some view on top of presented modal view controller i have an activity view that i have added in appdelegate class to tap barselfmaintabbarview addsubview spinnerwhen there are connection problems it is visible in each view controller and is spinningthere is some button at certain view controller makes to present some modal view controllerthat modal view controller overlaps the spinner how to make that spinner always be on top of all views or at least on top of that modal view controlleri tried to make such a thing in view controller that presents modal view controllerself presentmodalviewcontrollerselectionviewcontroller animatedyesselfview bringsubviewtofrontselftabbarcontrollerview viewwithtag15not works,"['iphone', 'objective-c']" +267493,how to retrieve the primary key when saving a new object in anorm i am using scala play framework with anorm to persist the data model to the database i followed the example code here case class barid pklong name stringobject bar val simple getpklongid getstringname map case idname barid name def findall seqbar dbwithconnection implicit connection sqlselect from barasbarsimple def createbar bar unit dbwithconnection implicit connection sqlinsert into barname values nameon name barname executeupdate trying to expand on it i want to retrieve the primary key just created and store it in the case classhow can i retrieve the primary key,['sql'] +267520,creating dynamic expression i want to create a dynamic expressionfuncty here is the code which works for string but does not work for datetime by does not work i mean i get this exceptionexpression of type systemnullable1systemdatetime cannot be used for return type systemobjectcan anybody analyze the mistake type type typeofdsvpnprojection parameterexpression arg expressionparametertype x expression expr arg propertyinfo propertyinfo typegetpropertysidx expr expressionpropertyexpr propertyinfo var expression expressionlambdafuncdsvpnprojection objectexpr argdo i need to change the object to some other type if yes then which as you can see i am trying to dynamically fetch the propertyinfo and use that as the 2nd parameter in func,"['c#', '.net']" +267522,python overwrite previous line how do you overwrite the previous print in python 27i am making a simple program to calculate pi here is the codeo 0hpi 10i 1print pi calculatoracc intraw inputenter accuracyifacc9 print warning this might take a very long time to terminate press ctrlzprint precision straccwhile i acc ifo0 hpi 10ii o 1 elifo1 hpi i10i o 0 else print loop error i 1 if i 10 0 print strhpi2print strhpi2it basicly outputs the current pi after 10 calculations how can i make it overwrite the previous calculation,['python'] +267563,sqlalchemy how to order query results order by on a relationships field modelsfrom sqlalchemyextdeclarative import declarative basefrom sqlalchemy import column foreignkeyfrom sqlalchemy import integerfrom sqlalchemy import unicodefrom sqlalchemy import timestampfrom sqlalchemyorm import relationshipbasemodel declarative baseclass basebasemodel tablename base id columninteger primary keytrue location columnunicode12 foreignkeylocationterrainlocation uniquetrue name columnunicode45 ownerid columnintegerforeignkeyplayerid occupierid columninteger foreignkeyplayerid submitid columnintegerforeignkeyplayerid updateid columnintegerforeignkeyplayerid owner relationshipplayer primaryjoinbaseowneridplayerid join depth3 lazyjoined occupier relationshipplayer primaryjoinbaseoccupieridplayerid join depth3 lazyjoined submitter relationshipplayer primaryjoinbasesubmitid playerid join depth3 lazyjoined updater relationshipplayer primaryjoinbaseupdateid playerid join depth3 lazyjoinedclass playerbasemodel tablename player id columninteger foreignkeyguildmemberplayerid primary keytrue name columnunicode45searchingbases dbsessionquerybasebases basesorder bybaseownernamethis does not work i have searched everywhere and read the documentationbut i just do not see how i can sort my base query on their owner relationships nameit always results in attributeerror neither instrumentedattribute object nor comparator object has an attribute namethis must be easy but i do not see it also looked into comparators which seemed logical but i do not see where the query part for the order by is generated or what i should be returning since everything is generated dynamically and making a comparator for each of my player relationships to do a simple thing seems over complicated,['python'] +267583,using mysql with rails how do i set this up i want to use mysql with a rails app i have never used mysql before my experience has been solely with sqlite3 and postgresql which are really easy to usei am now creating a new app to learn to use mysql i installed mysql with homebrew brew install mysql and created a new rails app that uses mysql rather than sqlite3 i have included the right gem in my gemfile gem mysql2 026however i do not know how to proceed i have not set up anything more in mysql other than to install it on my system i do not understand anything to do with how you set it up to run where it stores the database for my app and so onplease could anyone let me know either the next steps or a tutorial that would get me understanding enough to develop my app to function just as it would with a simpler sqlite database system,"['mysql', 'ruby-on-rails']" +267605,cucumber claims its support files are broken using cucumber for ruby on rails i ran a test that failed for a silly reason i would made a typo i fixed the problem and suddenly cucumber would not run anymore i did not change any of the files it refers tousrlocallibrubygems191gemscucumber118libcucumberjs supportjs dsljs3 syntax error unexpected expecting keyword then or or nusrlocallibrubygems191gemscucumber118libcucumberjs supportjs dsljs6 syntax error unexpected keyword else expecting else usrlocallibrubygems191gemscucumber118libcucumberjs supportjs dsljs7 syntax error unexpected expecting tassocusrlocallibrubygems191gemscucumber118libcucumberjs supportjs dsljs13 syntax error unexpected expecting end syntaxerrorusrlocallibrubygems191gemsactivesupport310libactive supportdependenciesrb234in loadusrlocallibrubygems191gemsactivesupport310libactive supportdependenciesrb234in block in loadusrlocallibrubygems191gemsactivesupport310libactive supportdependenciesrb225in load dependencyusrlocallibrubygems191gemsactivesupport310libactive supportdependenciesrb234in loadusrlocallibrubygems191gemscucumber118libcucumberjs supportjs languagerb114in initializeusrlocallibrubygems191gemscucumber118libcucumberruntimesupport coderb74in newusrlocallibrubygems191gemscucumber118libcucumberruntimesupport coderb74in load programming languageusrlocallibrubygems191gemscucumber118libcucumberruntimesupport coderb185in programming language forusrlocallibrubygems191gemscucumber118libcucumberruntimesupport coderb169in load fileusrlocallibrubygems191gemscucumber118libcucumberruntimesupport coderb83in block in load filesusrlocallibrubygems191gemscucumber118libcucumberruntimesupport coderb82in eachusrlocallibrubygems191gemscucumber118libcucumberruntimesupport coderb82in load filesusrlocallibrubygems191gemscucumber118libcucumberruntimerb175in load step definitionsusrlocallibrubygems191gemscucumber118libcucumberruntimerb40in runusrlocallibrubygems191gemscucumber118libcucumberclimainrb43in executeusrlocallibrubygems191gemscucumber118libcucumberclimainrb20in executeusrlocallibrubygems191gemscucumber118bincucumber14in top requiredusrlocalbincucumber19in loadusrlocalbincucumber19in mainobviously something has gone terribly terribly wrong my question is simply how do i go about fixing this is this a known bug canshould i reinstall cucumber the whole stack i have very little experience with rails and cucumber and the obvious solutions are failing me the file it complains about is fine actually fairly readable nothing odd about it running it again reveals it was not just a fluke breaking the feature i fixed changes nothing lines 37 of js dsl are if func null jslanguageexecute step definitionregexp else jslanguageadd step definitionregexp func so i checked the step definition file and that also looks fine usually a step definition being wrong gives an error message not a complete failure like this,['ruby-on-rails'] +267617,finstrumentfunctions does not work with dynamically loaded g shared objects so i am testing finstrumentfunctions with g shared object so files on ubuntu these days i found a strange behavior that finstrumentfunctions seems to work only if the library is statically linked if i link to the library with dlopendlsym etc the functionality of the code still works but it would not call the cyg profile functionshere are some codes to quickly reproduce the problemmylibhifndef mylib h define mylib h class mylibpublic void sayhelloendifmylibcppinclude mylibhinclude iostreamusing namespace stdvoid mylibsayhello couthelloendlmylibstubcpp c interface to the soinclude mylibhextern c void loadmylib mylibsayhellotracecppinclude stdiohifdef cplusplusextern c void cyg profile func entervoid this fn void call site attribute no instrument function void cyg profile func exitvoid this fn void call site attribute no instrument functionendifvoid cyg profile func entervoid this fn void call site printfentering pn intthis fnvoid cyg profile func exitvoid this fn void call site printfexiting pn intthis fnmainstaticcppinclude iostreamusing namespace stdextern c void loadmylib int main loadmylib return 0maindynamiccppinclude iostreaminclude dlfcnhconst char pszlibname libmylibso00const char pszfuncname loadmylibint main void plibhandle dlopenpszlibname rtld now ifplibhandle return 1 void pfuncload 0 resolve the function in mylibstubcpp pfuncload void dlsymplibhandle pszfuncname ifpfuncload return 1 pfuncload dlcloseplibhandle return 0and compile with the following commands under ubuntu 10g g finstrumentfunctions wall wlsonamelibmylibso0 shared fpic rdynamic mylibcpp mylibstubcpp tracecpp o libmylibso00 ln s libmylibso00 libmylibso0 ln s libmylibso00 libmylibso g mainstaticcpp g wall lmylib l o mainstatic g maindynamiccpp g wall ldl o maindynamicwhen called with mainstaticit gives something likeentering 0xb7693fentering 0xb7689bexiting 0xb7689bexiting 0xb7693fentering 0xb76998entering 0xb7680chelloexiting 0xb7680cexiting 0xb76998however when called with maindynamicit only gives a hellohellodoes anybody here know why there is such difference between statically and dynamically linked libraries is there any solution to make it work even when dynamically loaded thanks in advance,['c++'] +267640,how to get method object in java without using method string names i am looking for a convenient workaround for getting the method object from a method the ideamethod foomethod getmethod new myobjectfoo returns method foo in myobjectthe obvious way is to use the name of the method as a stringmethod foomethod myobjectclassgetmethodfoobut i want to avoid this because if i rename foo that code will stop working or i have rename the string in all the places where it is usedthe use case is that i want to use something similar to properychangelisteners however those rely on the method name as string i would like to use the actual method safely and not rely on stringswhat could i use to get the method in a rename safe wayupdatei would like to find a pure java solution that does not rely on ide features,['java'] +267641,how does bb a0 swap between a and b as gdoron pointed out var a avar b ba bb a0will swap a and b and although it looks a bit of hacky it has triggered my curiosity and i am very curious at how it works it does not make any sense to me,['javascript'] +267651,in place editor with autocomplete has anyone been able to do this is it possible i am writing a rails 3 app and it seems like it should be possible to do this with jquery autocomplete and bestinplace but i have not seen it,"['ruby-on-rails', 'jquery']" +267660,java string pool and type casting my question is in regard to the way java handles string literals it is quite clear from the java language specs jls that string literals are being implicitly interned in other words objects that are created in the string constant pool part of the heap in contrast to the heapbased objects created when calling new stringwhateverwhat does not seem to line up with what the jls says is that when creating a new string using string concatenation with a casted constant string type which should be considered as a constant string as per the jls apparently the jvm is creating a new string object rather than interning it implicitly i appreciate any explanation about this particular behaviour and whether or not this is a platformspecific behaviour i am running on a mac osx snow leopard public class test public static void mainstring args create a string object on the string constant pool using a string literal string hello hello final string lo lo this will be created in the string pool as well compare the hello variable to a string constant expression that should cause the jvm to implicitly call stringintern systemoutprintlnhello hel lo this should print true here we need to create a string by casting an object back into a string this will be used later to create a constant expression to be compared with the hello variable object object lo final string stringobject string object as per the jls casted string types can be used to form constant expressions compare with the hello variable systemoutprintlnhello hel stringobject this should print true but it does not,['java'] +267682,insert echo into the specific html element like div which has an id or class i have this codehtmlheadstyle typetextcssbodybackground6divborder1px solid redstyleheadbodyphpcon mysql connectlocalhostrootif condiecould not connect mysql errormysql select dbjuliver conresult mysql queryselect from hiwhilerow mysql fetch arrayresultecho img srcrowname echo divrownamedivecho divrowtitledivecho divrowdescriptiondivecho divrowlinkdivecho br mysql closeconbodyhtmlthe above code worksnow i want to insert thisecho img srcrowname echo divrownamedivecho divrowtitledivecho divrowdescriptiondivecho divrowlinkdivecho br into the specified div or other element in the html example i will insert thisecho img srcrowname into the html element i dont know how to do this please help me thanksjuliver,"['php', 'javascript', 'jquery']" +267724,insert row in middle of datagridview c i would like to insert a new datagridviewrow into my datagridview at a specific index if i just create a new row like datagridviewrow dgwr new datagridviewrowdatagridview1rowsinsertindex dgwri will not get the settings of the datagridview like for example my cells will be 0 this does not happen if i usedatagridview1addbut then again then i cant chose where in the list i would like my postis there anyway to combine these advantages nick,['c#'] +267755,big headache codeigniter or custom made framework whats your thoughts if youd like to develop a webapp which you know that is going to scale and become bigger and bigger over time would you use codeigniter or your custom made frameworkwhats your arguments for using an open source framework and whats your arguments against ithere are my thoughtscodeigniter prosgreat documentation easier to work in a teamall the development time is invested in the business logicnot reinventing the wheelcodeigniter consnot sure how scalable it is if i will want to growmit license not sure what it means but if i will want to sell my app on per license basis i am not sure i will be able to do thatcustom coded framkework prosscalable i can decide how it will growi own the codeflexcible designcustom coded framework consneed to document it so others will be able to collaborateneed to invest time to maintain the frameworkunexpected errorsbugswhats your take on that my brain tells me to go with codeigniter my heart tells me to build my own framework,['php'] +267768,illegal string offset warning php i get a strange php error after updating my php version to 5403i have this arrayarray host 127001 port 11211when i try to access it like this i get strange warnings print memcachedconfighost print memcachedconfigport warning illegal string offset host in warning illegal string offset port in i really do not want to just edit my phpini and reset the error levelthanks for any help,['php'] +267795,how to get a single columns values into an array right now i am doing something like this to select a single column of datapoints postfind by sqlselect point from poststhen passing them to a method i would like my method to remain agnostic and now have to call hashpoint from within my method how can i quickly convert this into an array and pass the data set to my method or is there a better way,"['ruby-on-rails', 'ruby']" +267829,why do major websites not pass w3c validation properly in an attempt to understand if w3c validation can assist better dom rendering or if it is just a standard for html coding i tried to validate major websites but all of them fail with some errorshere are typical examplesgooglecom 36 errors 2 warningsfacebookcom 42 errorsyoutubecom 91 errors 3 warningsyahoocom 212 errors 8 warningsamazoncom 510 errors 138 warningswhen major websites do not seem to spend enough time for w3c validation is it needed to spend time to do so for small and mediumsized websites,['html'] +267880,make your app a default app to open a certain file how do i make my android app the default application to open a certain file typei tried to clear the defaults but the option is greyed out does anyone know how to do thisi want to make my app open with my somethingwhatever files in android,['android'] +267884,tomcat 7 javalangnoclassdeffounderror orgapachelog4jspithrowableinformation i am facing the following exceptionmar 26 2012 12034 pm orgapachecatalinaloaderwebappclassloader loadclassinfo illegal access this web application instance has been stopped already could not load orgapachelog4jspithrowableinformation the eventual following stack trace is caused by an error thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access and has no functional impactjavalangillegalstateexceptionat orgapachecatalinaloaderwebappclassloaderloadclasswebappclassloaderjava1562at orgapachecatalinaloaderwebappclassloaderloadclasswebappclassloaderjava1521at orgapachelog4jspiloggingeventinitloggingeventjava165at orgapachelog4jcategoryforcedlogcategoryjava391at orgapachelog4jcategoryerrorcategoryjava322at comabcsupervisionmanagermonitoringrunmonitoringjava205at javalangthreadrunthreadjava662exception in thread thread monitoring javalangnoclassdeffounderror orgapachelog4jspithrowableinformationat orgapachelog4jspiloggingeventinitloggingeventjava165at orgapachelog4jcategoryforcedlogcategoryjava391at orgapachelog4jcategoryerrorcategoryjava322at comabcsupervisionmanagermonitoringrunmonitoringjava205at javalangthreadrunthreadjava662caused by javalangclassnotfoundexception orgapachelog4jspithrowableinformationat orgapachecatalinaloaderwebappclassloaderloadclasswebappclassloaderjava1676at orgapachecatalinaloaderwebappclassloaderloadclasswebappclassloaderjava1521 5 morei googled about this exception and found that most answers points that it is bug in tomcat 55 and it will be solved in version 5528however i am currently using tomcat 711 with log4j1216jar i am still facing the same issue,['java'] +267886,php implode wrap in tags been trying to google an answer but cant seem to find anything i have the followingphp values array maptrim get post custom valueskey value implodevalues echo div classtopmetavalsapply filters valuen valuedivi want to wrap each and every value in a span tag but im unsure how i triedphpvalue spanimplodevalues spanwith no luck can anybody give me an idea of where im going wrong,"['php', 'html']" +267898,my current location always returns null how can i fix this i am trying to find my current location for an android project when the application is loaded my current location is always null i have set up the permissions in the manifest etc when i find the current location i intend to use the coordinates to find thistances to other locations on the map my code snippet is below why do i always get a null value locman locationmanager getsystemservicecontextlocation service criteria crit new criteria towers locmangetbestprovidercrit falselocation locmangetlastknownlocationtowers if location null systemoutprintlnlocation is not null lat int locationgetlatitude 1e6 longi int locationgetlongitude 1e6 geopoint ourlocation new geopointlati longi overlayitem overlayitem new overlayitemourlocation 1st string 2nd string custompinpoint custom new custompinpointd mainmapthis custominsertpinpointoverlayitem overlaylistaddcustom overlaylistclear else systemoutprintlnlocation is null towers toastmaketextmainmapthis could not get providertoastlength short show,['android'] +267902,dgps corrections on android i am developing a project that is intended to use the gps capabilities of an android phone and a nearby station to compute positioning to a much more precise degree cm using rtk dgps technologyso far i have not been able to see anyone saying they actually managed to perform a similar task apart from gpsmaster who does not explain how and the apk does not seem to offer any information from the gps chip other than location and nmea message updates i need if possible pseudoranges and carrier phasesi was wondering ifit would be possible to look for lower level hooks on my phone using native code or other lower level snoopingit would be possible to send rtcm corrections to the gps chip present on one of these devicesany ideas,['android'] +267915,using apache httpclient how to set the timeout on a request and response i need to set time out for the http request we make to a service not a web service we are using apache http client i have added these 2 lines of code to set the time out on request and response to the service httpconnectionparamssetconnectiontimeoutparams 10httpconnectionparamssetsotimeoutparams 101 currently i have set 10 seconds as the timeout since i see the response coming from the service almost instantaneously should i increase or decrease the timing 2 what will happen when response is takes more than 10 seconds will it throw exception and what exception will it be is there any thing else i need to add to set the time out in the below codepublic hashmapstring object getjsondatastring url throw exception defaulthttpclient httpclient new defaulthttpclient httpparams params httpclientgetparams httpconnectionparamssetconnectiontimeoutparams 10 httpconnectionparamssetsotimeoutparams 10 httphost proxy new httphostgetproxy getproxyport connrouteparamssetdefaultproxyparams proxy uri uri inputstream data null try uri new uriurl httpget method new httpgeturi httpresponse response httpclientexecutemethod data responsegetentitygetcontent catch exception e eprintstacktrace reader r new inputstreamreaderdata hashmapstring object jsonobj hashmapstring object genericjsonutilfromjsonr return jsonobj,['java'] +267916,generating jaxb classes from a schema i am trying to use the jaxb classes generator in eclipse to generate jaxb classes from my schemai receive the following errorthe classpath for this project does not appear to contain the necessary libraries to proceed with class generationplease insure that a jaxb implementation is available on the classpathhow can i solve this problem,['java'] +267917,cannot get scipy hierarchical clustering to work i wrote a simple script that is intended to do hierarchical clustering on a simple test dataset i found the function fclusterdata to be a candidate to cluster my data into two clusters it takes two mandatory call parameters the data set and a thresholdthe problem is i could not find a threshold that would yield the expected two clustersi would be happy if anyone can tell me what i am doing wrong i would also be happy if anyone could point on other approaches that would be better suited for my clustering i explicitly want to avoid to specify the number of clusters beforehandhere is my codeimport timeimport scipyclusterhierarchy as hclusterimport numpyrandom as randomimport numpyimport pylabpylabiondata randomrandn2200data100100 10for i in range515 thresh i10 clusters hclusterfclusterdatanumpytransposedata thresh pylabscatterdata cclusters pylabaxisequal title threshold f number of clusters d thresh lensetclusters print title pylabtitletitle pylabdraw timesleep05 pylabclfhere is the outputthreshold 050 number of clusters 129threshold 060 number of clusters 129threshold 070 number of clusters 129threshold 080 number of clusters 75threshold 090 number of clusters 75threshold 10 number of clusters 73threshold 110 number of clusters 58threshold 120 number of clusters 1threshold 130 number of clusters 1threshold 140 number of clusters 1,['python'] +267924,why are asobservable and asenumerable implemented differently the implementation of enumerableasenumerabletthis ienumerablet source simply returns source however observableasobservabletthis iobservablet source returns an anonymousobservablet subscribing to the source rather than simply returning the sourcei understand these methods are really useful for changing the monad within a single query going from iqueryable ienumerable so why do the implementations differthe observable version is more defensive in that you cannot cast it to some known type if it original were implemented as a subjectt youd never be able to cast it as such so why does the enumerable version not do something similar if my underlying type is a listt but expose it as ienumerablet through asenumerable it will be possible to cast back to a listtplease note that this is not a question on how to expose ienumerablet without being able to cast to the underlying but why the implementations between enumerable and observable are semantically different,['c#'] +267926,round to 5 or 10 in sql i am looking to round values like23913 25467 45211 2how can i manage this in sqlthanks,['sql'] +267930,scale drawable does setimagelevel dictate the scale i have created a small test app to try out scale drawable i define my drawable in xml and save it as scale upxml i have a mainxml layout file with an imageview i use androidsrcdrawablescale up in the imageview to use the drawable i created in xml in my activity i use myimageviewsetimagelevelsome level here to set the level of the imageview defined in mainxml alls well and the imageview thisplays the drawable defined in scale upmy confusion is the followingchanging the scaleheight and scalewidth in scale upxml makes no perceivable difference if the level is set at 10changing the level in setimagelevel between 0 and 10 changes the size of the image really only perceivable at around 50 the higher the value for scaleheight and scalewidth the smaller the image depending on the value of setimageleveli suppose my questions areis it correct to use setimagelevel passing a level between 0 and 10 in the activity to control the size of the drawable defined in the xml filewhat is the relationship between scaleheight scalewidth and setimagelevel as i see it now i may as well just set the scaleheight and scalewidth to 100 and then use setimagelevel50 to get a 50 scaled image ie increasing or reducing setimagelevel0 to 10 will change the scale making the scaleheight and scalewidth pretty pointlessappreciate any clarification of this and perhaps an example of how to use scale drawable defined in xml correctly,['android'] +267933,find available port for php server php 54 comes with a builtin server for development purposes this is the kind of thing i have been waiting for months because up until now i have had to sort of hack together a php script that listens for incoming connections and handles them because i do not want to go to the trouble and overhead of installing an actual serverthe main thing left for me to worry about is how can i have a port assignedin my php script i used to do thissocket bindsocklocalhost0 or diecould not bind socketsocket getsocknamesockipportport would then be the port number assigned by the os based on what is availablei was just wondering if any such feature existed in phps builtin server and if so what the command line should be to access it,['php'] +267945,how to create a bundled runnable jar using ant i looked at this question but it did not really solve my problem so i figured i would post a new onei need to create a runnable jar runnable simply by double clicking using ant i have the following java code and buildxml file which compiles the code just fine and creates a jar file but when i try to run the jar by double clicking i get a message saying could not find main class httpcontrollerjavai have the suspicion that my problem has to do with loading the external apache httpjar as i have successfully built and run a jar for a project that is identical except that it does not reference any external jarshere is my codehttpcontrollerjavapackage packimport javaiobufferedreaderimport javaioioexceptionimport javaioinputstreamreaderimport orgapachehttphttpentityimport orgapachehttphttphostimport orgapachehttphttpmessageimport orgapachehttphttpresponseimport orgapachehttpclientclientprotocolexceptionimport orgapachehttpclientmethodshttpgetimport orgapachehttpimplclientdefaulthttpclientpublic class httpcontroller public static void mainstring args defaulthttpclient client new defaulthttpclient httphost httphost new httphostlocalhost 80 try httpmessage req new httpgettesthtml httpresponse resp clientexecutehttphost httpget req httpentity entity respgetentity bufferedreader in new bufferedreadernew inputstreamreader entitygetcontent string line null while line inreadline null systemoutprintlnline catch clientprotocolexception e eprintstacktrace catch ioexception e eprintstacktrace finally shutdown the connection clientgetconnectionmanagershutdown buildxml xml version10 encodingiso88591 project nametest basedir defaultjar property namesourcedir valuesrc property namelibdir valuelib property nameclassdir valuebin property namejardir valuethist property namemainclass valuepackhttpcontroller path idlibrariespath fileset dirlibdir include namejar fileset path target nameclean descriptiondelete old files delete dirclassdir delete dirjardir target target namecompile descriptionbuild class files dependsclean mkdir dirclassdir javac srcdirsourcedir destdirclassdir classpath refidlibrariespath javac target target namejar dependscompile mkdir dirjardir mkdir dirjardirlibdir copy todirjardirlibdir flattentrue path refidlibrariespath copy jar destfilejardirantprojectnamejar basedirclassdir manifest attribute namemainclass valuemainclass attribute nameclasspath valuejardirlibdirapache httpjar manifest jar target target namerun dependsjar java jarjardirantprojectnamejar forktrue targetprojectmanifestmfmanifestversion 10antversion apache ant 183createdby 160 31b05 sun microsystems incmainclass httpcontrollerclasspath thistlibedit buildxml has been updated as per mikes answer problem is still not solved also posted contents of manifest file as per danations answer,['java'] +267957,how can i use an enum class in a boolean context i have some generic code that works with flags specified using c11 enum class types at one step i would like to know if any of the bits in the flag are set currently i am using the codeif flags static caste0 works but uglyi could also force users to specify a particular name for an allzero field which is more readable but imposes my naming conventions on anyone using itif flags enone works if you manually define none 0but neither of these reads as nicely as the traditionalif flags does not work with class enumsis it possible to specify a custom function to evaluate a class enum in a boolean context,['c++'] +267973,idiomatic way to collect report multiple exceptions in python what have people used to catch log and report multiple data validation errors at once in pythoni am building an application in python 3 that first validates input data and then processes it reporting errors in the first step is part of the intended functionality of the program so i do not want my validator to give up on the first exception in particular the data are tabular and i want be able to return rather than raise an exception for each line of the table that does not validatea forum thiscussion from a couple of years ago contemplates multiple solutions including the following which seems the cleanest to meerrors for item in data try processitem except validationerror as e errorsappendeif errors raise multiplevalidationerrorserrorswhere the multiplevalidationerrors class would have an appropriate str method to list useful information about all the validationerrors in itothers recommend using the traceback module but since the exceptions i want to catch are data validation errors rather than program errors that seems inappropriate getting the logging module involved might be appropriate though,['python'] +267983,is there a way to use css transform and not affect children elements i created a mockup to demonstrate my problem i fear the solution falls in what i did with the first example box1just not sure why i cannot apply a css transform to a parent element and avoid applying it to the child element or at least override itlet me know if there is a way to get the effect of the first example using the transform property i do not want the second image to be scaled as well just the parent divnotei am trying to use this property to enable gpu acceleration,['css'] +267994,how do i compute derivative using numpy how do i calculate the derivative of a function for example y x21 using numpylet us say i want the value of derivative at x 5,['python'] +268002,with arc why use properties anymore in nonarc code retained properties handily take care of memory management for you using the selfproperty syntax so we were taught to use them for practically everythingbut now with arc this memory management is no longer an issue so does the reason for using properties evaporate is there still any good reason obviously other than providing public access to instance variables to use properties anymore,"['objective-c', 'ios']" +268010,mysqli store result vs mysqli use result the questionwhat is the difference between mysqlistore result and mysqliuse resultthe storyvague documentationthe documentation on phpnet seems very vague about the difference between the two the mysqliuse resultpage does not offer any codesamples and links you to the mysqlimulti querypage to look for them in that page the following codesample is given see the page for the full code store first result set if result mysqlistore result while row resultfetch row printfsn row0 resultfree print divider if mysqlimore results printfnthe mysqlistore resultpage uses exactly the same codesample with one exception store first result set if result mysqliuse result yeah store result became use result note that even the comment above is still saying storeeven more confusinghaving seen the code samples i thought all right so it is an alias but wait the documentation gives the following descriptionsmysqli store result a transfers a result set from the last querymysqli use result a initiate a result set retrievalthey seem like two different things and are not brought like aliases at all taking a closer look i found out that there was yet another exception in the codesample of the mysqliuse resultpage resultfree became resultclose however my hopes for finding out the truth were soon after shattered when i found that on that same page in the second code sample the procedural equivalent mysqli free resultresult was used and not the expected mysqli close resultresult,['php'] +268037,getting max value in a m128i vector with sse i have just started using sse and i am confused how to get the maximum integer value max of a m128i for instance m128i t mm setr ps0123 maxt 3searching around led me to maxps instruction but i cannot seem to find how to use that with xmmintrinh also is there any documentation for xmmintrinh that you would recommend rather than looking into the header file itself,['c'] +268038,how to filter list using predicate private static class filterbystringcontains implements predicatestring private string filterstring private filterbystringcontainsfinal string filterstring thisfilterstring filterstring override public boolean applyfinal string string return stringcontainsfilterstring i have a list of strings i want to filter it by the specified string so the returned value contains a list of only the specified strings i was going to use a predicate as above but not sure how to apply this to filter a list,['java'] +268048,how do i get the user agent with flask i am trying to get access to the user agent with flask but i either cannot find the documentation on it or it does not tell me,['python'] +268051,eliminate ghost margin below html5 canvas element when we create an html5 canvas element a ghost margin appears below the canvas element even though we set the margin and padding to 0example we tried a variety of things but cannot erase the ghost marginhow can we create the canvas element without that ghost margin,['css'] +268102,android how to make listener to a custom variable i have seen this thread android how to implement listener about implement listenersits actually pretty simple but i do not get how exactly its done and how to implement in my own codei have this static variable variable apploaderisinternetoni want to build a listener which will listen to this variable changes and update a textviewshould i do this build an interfacepublic interface internetstatelistener public void onstatechangerun it in my activitypublic class myactivity extends activity private internetstatelistener mlistenersetthelistenerthispublic void setthelistenerinternetstatelistener listen mlistener listenprivate void onstatechange if mlistener null if apploaderisinterneton textsettexton else textsettextoff,['android'] +268111,patterncompile in this statement taken from the pagerank source codepatterncompilewhat does the pattern mean i have tried studying it it says 2 slashes mean a single slash but what are the,['java'] +268119,how to align c forloop body w gcc in our embedded architecture we have a 64bit iab instruction alignment buffer in order to optimize the fetch sequence it is required that the body of a loop will start aligned to an 8byte boundaryit is easy to achieve this in assembly using the balign directive but i cannot find a syntax that will hint the c compiler to align the codetrying to precede the for loop with inline assembly with the balign directive does not work as it aligns the for loop prolog setup and not the loop body itselfdoing the same where the asm line is inside the loop adds nops to the loop body that cost precious cyclesedit 1 assume the code asm volatilenop asm volatilenop for j00 j0n j04 cj0 0 aj0 0 bj0 0 cj0 1 aj0 1 bj0 1 cj0 2 aj0 2 bj0 2 cj0 3 aj0 3 bj0 3 i want the first cab to be aligned to an 8byte address i can add the nops like above after a preliminary compilation but this is an adhoc solution that will break with the 1st code changeedit 2 thanks to r the solution is to use the falignloops8 compiler option,['c'] +268135,button in expandable listview android i have a expandablelistactivity with an custom adapterif the custom row of the adapter contains a imageviewall is done but if i change this view from imageview to imagebutton the expandable listview do not expandis there any method to put a button that can be clicked and the expandablelist does not lose the functionality to expand,['android'] +268140,windows service template missing when i go to create a new project the windows service template is not therecan someone please either tell me where i can get it or provide a download link to it,['c#'] +268147,os starts killing processes when multithreaded python process runs this is the strangest thing i have a multithreaded client application written in python i am using threading to concurrently download and process pages i would use the curl multihandle except that the bottleneck is definitely the processor not the bandwidth in this application so it is more efficient to use a thread pool i have a 64b i7 rocking 16gb ram beefy i launch 80 threads while listening to pandora and trolling stackoverflow and bam the parent process sometimes ends with the messagekilledother times a single page which is it is own process in chrome will die other times the whole browser crashes if you want to see a bit of code here is the gist of ithere is the parent processdef start while true for url in to download queueput url uri id to download if queueqsize batch size to download get more urls batch size if threadingactivecount num threads for thread in threads if not threadisalive print respawning threadjoin threadsremove thread t clientthread queue tstart threadsappend t timesleep 05 and here is the gist of the clientthreadclass clientthread threadingthread def init self queue threadingthread init self selfqueue queue def run self while true try selfurl selfurl id selfqueueget except raise systemexit html stringiostringio curl pycurlcurl curlsetopt pycurlurl selfurl curlsetopt pycurlnosignal true curlsetopt pycurlwritefunction htmlwrite curlclose try curlperform except pycurlerror error errno errstr error print errstr curlclose edit oh rightforgot to ask the questionshould be obvious why do my processes get killed is it happening at the os level kernel level is this due to a limitation on the number of open tcp connections i can have is it a limit on the number of threads i can run at once the output of cat procsyskernelthreadsmax is 257841 soi do not think it is thati think i have got itoki have no swap space at all on my drive is there a way to create some swap space now i am running fedora 16 there was swapthen i enabled all my ram and it thisappeared magically tailing varlogmessages i found this errormar 26 195403 gazelle kernel 700140851877 15961 500 15961 12455 7292 1 0 0 postgresmar 26 195403 gazelle kernel 700140851880 out of memory kill process 15258 chrome score 5 or sacrifice childmar 26 195403 gazelle kernel 700140851883 killed process 15258 chrome totalvm214744kb anonrss70660kb filerss18956kbmar 26 195405 gazelle dbus system activating service nameorgfedoraprojectsetroubleshootd using servicehelper,['python'] +268156,getting superinterfaces in java i have been trying to do this for quite some time now and cannot seem to get the desired output what i want to do is have a class name say javautilvectorget thethe directly implemented interfaces if javautilvectorthe interfaces directly implemented by the superclassesand transitively all superinterfaces of these interfacesany help would be appreciated,['java'] +268169,unable to multithread a scalable method update to help clarify what i am asking i have posted a little java code that gets the idea acrossa while ago i asked a question on how to get an algorithm to break down a set of numbers the idea was to give it a list of numbers 12345 and a total10 and it would figure out all the multiples of each number that would add up to the total110 or 121314 or 25etc it was the first programming exercise i ever did so it took me a while and i got it working but now i want to try to see if i can scale it the person in the original question said it was scalable but i am a bit confused at how to do it the recursive part is the area i am stuck at scaling the part that combines all the resultsthe table it is referring to is not scalable but applying caching i am able to make it fasti have the following algorithmpseudo codegenerates tablefor i 1 to k for z 0 to sum for c 1 to z x i if tz c x ii 1 is true set tzi to trueuses table to bring all the parts togetherfunction recursivelylistallthatworkk sum using last k variables make sum base case if weve assigned all the variables correctly list this solution if k 0 print what we have so far return recursive step try all coefficients but only if they work for c 0 to sum x k if tsum c x kk 1 is true mark the coefficient of x k to be c call recursivelylistallthatworkk 1 sum c x k unmark the coefficient of x ki am really at a loss at how to threadmultiprocess the recursivelylistallthatwork function i know if i send it a smaller k which is int of total number of items in list it will process that subset but i do not know how to do ones that combine results across the subset for example if list is 12345678910 and i send it k3 then only the 123 get processed which is fine but what about if i need results that include 1 and 10 i have tried to modify the tablevariable t so only the subset i want are there but still does not work because like the solution above it does a subset but cannot process answers that require a wider rangei do not need any code just if someone can explain how to conceptually break this recursive step to so other coresmachines can be used update i still cannot seem to figure out how to turn recursivelylistallthatwork into a runnablei know technically how to do it but i do not understand how to change the recursivelylistallthatwork algorithm so it can be ran in parallel the other parts are just here to make the example work i only need to implement runnable on recursivelylistallthatwork method heres the java codeimport javaawtpointimport javautilarraylistimport javautilarraysimport javautillistpublic class main public static void mainstring args systemoutprintlnstarting int target sum 100 int data new int 10 5 50 20 25 40 list t tablegeneatortarget sum data listinteger coeff create coeffdatalength recursivelylistallthatworkdatalength target sum t coeff data private static listinteger create coeffint i todo autogenerated method stub integer integers new integeri arraysfillintegers 0 listinteger integerlist arraysaslistintegers return integerlist private static void recursivelylistallthatworkint k int sum list t listinteger coeff int data todo autogenerated method stub if k 0 print what we have so far for int i 0 i coeffsize i systemoutprintlndatai coeffgeti systemoutprintln return integer x k datak1 recursive step try all coefficients but only if they work for int c 0 c sumx k c the c variable caps the percent if tcontainsnew pointsum c x k k1 mark the coefficient of x k to be c coeffsetk1 c recursivelylistallthatworkk 1 sum c x k t coeff data unmark the coefficient of x k coeffsetk1 0 public static list tablegeneatorint target sum int data list t new arraylist taddnew point0 0 float max percent 1 int r int target sum max percent datalength for int i 0 i datalength i for int s r s r 1 s int max value int mathabstarget sum max percent datai for int c 0 c max value 1 c if tcontainsnew points c datai i point p new points i 1 if tcontainsp taddp return t,['java'] +268170,find out if a function has been called i am programming in python and i am wondering if i can test if a function has been called in my code def example passexamplepseudocodeif examplehas been called printfoo barhow would i do this,['python'] +268186,how do i create a view model for a populated drop down list in aspnet mvc 3 i am trying to teach myself mvc3 im converting from webformsi need to create a view model that includes a dropdown list that i can pass to the controller and eventually render in the viewhow can i accomplish this i have the skeleton but i dont know what the code is to actually create the name value pairs for the view namespace dhviewmodels public class sharedlayoutviewmodel public ienumerableselectlistitem products some code to setup the valuename pairs to be rendered in the view example option value1mustardoption option value2ketchupoption option value3mayooption option value4relishoption option value5bbqoption thanks,"['c#', 'asp.net']" +268191,browser busy indicator when loading data i am trying to achieve what has been explained here i am trying to load some data from server to the client side using dynamic script tags ie i create a script tag set its src to my json controller and append it to my head or body tag the script loads correctly with the data returned from server but during the script load the browser does not thisplay busy indicator tried with chromefirefox while according to this reference page 35 this should be the default behavior also i have added sleep method to my server side method to simulate a longrunning process to see the busy indicator appears but still no luck ps when i use iframe instead of script everything works fine and the busy indicator is thisplayed by browser but coulnt do it with script tag,['javascript'] +268214,thisadvantages of separating javascript codes i have a page which has many event handlers the code now reached 10 lines of codes and i am beginning to have difficulty reading the codes i am now planning to separate the codes to different files my question is is there any thisadvantages in separating js codes into different files,['javascript'] +268225,fastest packing of data in python and java sometimes our host is wrong nanoseconds matter i have a python twisted server that talks to some java servers and profiling shows spending 30 of its runtime in the json encoderdecoder its job is handling thousands of messages per secondthis talk by youtube raises interesting applicable pointsserialization formats no matter which one you use they are allexpensive measure donat use pickle not a good choice foundprotocol buffers slow they wrote their own bson implementation whichis 1015 time faster than the one you can downloadyou have to measure vitess swapped out one its protocols for an httpimplementation even though it was in c it was slow so they rippedout http and did a direct socket call using python and that was 8cheaper on global cpu the enveloping for http is really expensivemeasurement in python measurement is like reading tea leavesthereas a lot of things in python that are counter intuitive likethe cost of grabage colleciton most of chunks of their apps spendtheir time serializing profiling serialization is very depending onwhat you are putting in serializing ints is very different thanserializing big blobsanyway i control both the python and java ends of my messagepassing api and can pick a different serialisation than jsonmy messages look likea variable number of longs anywhere between 1 and 10k of themand two alreadyutf8 text strings both between 1 and 3kbbecause i am reading them from a socket i want libraries that can cope gracefully with streams its irritating if it does not tell me how much of a buffer it consumed for examplethe other end of this stream is a java server of course i do not want to pick something that is great for the python end but moves problems to the java end eg performance or torturous or flaky apii will obviously be doing my own profiling i ask here in the hope you describe approaches i wouldnt think of eg using struct and what the fastest kind of stringsbuffers aresome simple test code gives surprising resultsimport time random struct json sys pickle cpickle marshal arraydef encode json 1args return jsondumpsargsdef encode json 2longsstr1str2 return jsondumpslongslongsstr1str1str2str2def encode pickleargs return pickledumpsargsdef encode cpickleargs return cpickledumpsargsdef encode marshalargs return marshaldumpsargsdef encode struct 1longsstr1str2 return structpackidqlenlongslenlongslenstr1lenstr2longsstr1str2def decode struct 1s i j k structunpackis12 assert lens 34 8i j k lens34 8i j k longs structunpackdqis1212i8 str1 s12i812i8j str2 s12i8j return longsstr1str2struct header 2 structstructidef encode struct 2longsstr1str2 return join struct header 2packlenlongslenstr1lenstr2 arrayarrayllongstostring str1 str2def decode struct 2s i j k struct header 2unpacks12 assert lens 34 8i j k lens34 8i j k longs arrayarrayl longsfromstrings1212i8 str1 s12i812i8j str2 s12i8j return longsstr1str2def encode ujsonargs return ujsondumpsargsdef encode msgpackargs return msgpackerpackargsdef decode msgpacks msgunpackerfeeds return msgunpackerunpackdef encode bsonlongsstr1str2 return bsondumpslongslongsstr1str1str2str2def from dictd return dlongsdstr1dstr2tests encodedecodemassage for check encode struct 1decode struct 1none encode struct 2decode struct 2none encode json 1jsonloadsnone encode json 2jsonloadsfrom dict encode picklepickleloadsnone encode cpicklecpickleloadsnone encode marshalmarshalloadsnonetry import ujson testsappendencode ujsonujsonloadsnoneexcept importerror print no ujson support installedtry import msgpack msgpacker msgpackpacker msgunpacker msgpackunpacker testsappendencode msgpackdecode msgpacknoneexcept importerror print no msgpack support installedtry import bson testsappendencode bsonbsonloadsfrom dictexcept importerror print no bson support installedlongs i for i in xrange10str1 150str2 250randomseed1encode data longsrandomrandint2lenlongs str1randomrandint2lenstr1 str2randomrandint2lenstr2 for i in xrange10for encoderdecodermassage before check in tests do the encoding start timetime encoded encoderijk for ijk in encode data encoding timetime print encoder name encoding took 04fencodingstart sysstdoutflush do the decoding decoded decodere for e in encoded decoding timetime print decoding 04fdecodingencoding sysstdoutflush check it if massage before check decoded massage before checkd for d in decoded for ilongs astr1 astr2 alongs bstr1 bstr2 b in enumeratezipencode datadecoded assert longs a listlongs b ilongs alongs b assert str1 a str1 b istr1 astr1 b assert str2 a str2 b istr2 astr2 bgivesencode struct 1 encoding took 04486 decoding 03313encode struct 2 encoding took 03202 decoding 01082encode json 1 encoding took 063 decoding 06718encode json 2 encoding took 05740 decoding 08362encode pickle encoding took 81587 decoding 95980encode cpickle encoding took 11246 decoding 14436encode marshal encoding took 01144 decoding 03541encode ujson encoding took 02768 decoding 04773encode msgpack encoding took 01386 decoding 02374encode bson encoding took 5861 decoding 293953bson msgpack and ujson all installed via easy installi would love to be shown i am doing it wrong that i should be using cstringio interfaces or however else you speed it all upthere must be a way to serialise this data that is an order of magnitude faster surely,"['java', 'python']" +268238,visual studio c compiler options why does o2 define gs the visual studio c compiler option o2 maximize speed is equivalent toog oi ot oy ob2 gs gf gywhy gs how does it help maximize speed note that it is gs not gs,['c++'] +268248,does selenium webdriver support safari i am using selenium webdriver with java i want to use safari browser does selenium webdriver support safari,['java'] +268268,in windows java securerandomgenerateseed failed unexpected cryptoapi failure in production environmentwindows 2008 r2 amd 64 8 gb ram the application sometimes throws the following exception restart the application solves the problemcaused by javalanginternalerror unexpected cryptoapi failure generating seedat sunsecurityprovidernativeseedgeneratorgetseedbytesnativeseedgeneratorjava43at sunsecurityproviderseedgeneratorgenerateseedseedgeneratorjava117at sunsecurityprovidersecurerandomenginegenerateseedsecurerandomjava114at javasecuritysecurerandomgenerateseedsecurerandomjava475the code should have no problem public void generatetoken securerandom securerandom new securerandom int seedbytecount 20 byte seed securerandomgenerateseedseedbytecount securerandomsetseedseed string random stringvalueofsecurerandomnextlong settokenrandom took a look at jdk code find out that the error is because java sun security provider nativeseedgenerator nativegenerateseed returns false openjdk7u2fcssrcb1317 nov 2011jdksrcwindowsnativesunsecurityproviderwincapiseedgeneratorc jniexport jboolean jnicall java sun security provider nativeseedgenerator nativegenerateseedjnienv env jclass clazz jbytearray randarray hcryptprov hcryptprov jboolean result jni false jsize numbytes jbyte randbytes if cryptacquirecontextahcryptprov j2se null prov rsa full 0 false if csp context has not been created create one if cryptacquirecontextahcryptprov j2se null prov rsa full crypt newkeyset false return result numbytes envgetarraylengthenv randarray randbytes envgetbytearrayelementsenv randarray null if cryptgenrandomhcryptprov numbytes randbytes result jni true envreleasebytearrayelementsenv randarray randbytes 0 cryptreleasecontexthcryptprov 0 return result cryptgenrandom or cryptacquirecontexta returns false but i do not know why it fails and how to work around itanyone knows why this happens the work around or how to continue to investigate this problem thanks for any advice or reply thanksbtw i found the following resources but not quite useful to this problem bugdobug id6202721proper use of javaas securerandomsecure random number generation in java,['java'] +268301,entity framework efficiently grouping by month i have done a bit of research on this and the best i have found so far is to use an asenumerable on the whole dataset so that the filtering occurs in linq to objects rather than on the db i am using the latest efmy working but very slow code is var trenddata from d in expenseitemsviewabledirectasenumerable group d by new period der approved dateyeartostring der approved datemonthtostring00 into g select new period gkeyperiod total gsumx xitem amount averagepertrans mathroundgaveragex xitem amount2 this gives me months in format ymm along with the total amount and average amount however it takes several minutes every timemy other workaround is to do an update query in sql so i have a ymm field to group natively by changing the db is not an easy fix however so any suggestions would be appreciatedthe thread i found the above code idea mentions waiting until net 40 is there anything recently introduced that helps in this situation,"['c#', '.net']" +268337,the value of an empty list in function parameter example here possible duplicateleast astonishment in python the mutable default argument def fa l lappenda return lprintf1 1 2printf1printf2printf3i wonder why the other f1 f2 f3 has not append to the first f1 12i guess the result should be 1 2 11 2 1 11 2 1 1 21 2 1 1 2 3but the result is not this i do not know why,['python'] +268343,check if checkbox is checked javascript i am buildin a mobile web app with jquery mobile andi want to check if a checkbox is checked here is my codescript typetextjavascriptfunction validateif rememberchecked 1 alertchecked elsealertyou did not check it let me check it for youscriptinput idremember nameremember typecheckbox onclickvalidate but for some reason or another it does not execute itplease help editthis is what i have for the momentdiv datarolecontent datathemeg div classuigridglogin form methodpost actionprobe266 datathemec pdata errorp div idmail datarolefieldcontain label formailemaillabel input idmail namemail typeemail div div idpass datarolefieldcontain label forpasspaswoordlabel input idpass namepass typepassword div div idremember datarolefieldcontain label forrememberonthoud mijlabel input idremember nameremember typecheckbox onclickvalidate div pinput classbtn namesubmit valuelogin typesubmit onclickvalidatep form divdiv content script typetextjavascriptfunction validate var remember documentgetelementbyidremember if rememberchecked alertchecked else alertyou did not check it let me check it for you scripteditsolved it the problem was that the fieldcontain was also named remember,['javascript'] +268357,how to call class methods in the ios simulator with lldb i am trying to debug an ios app and i am having problems with lldb in the simulator calling class methods does not seem to work instance methods work finelldb po categoryno resultlldb po category classerror could not prepare the expression for execution in the targetlldb po selftagstableviewcontroller 5 0x085585a0 tagstableviewcontroller 0x85585a0i have tried the 43 and 51 simulators but both exhibit the same issueseverything works fine when debugging on a device,['ios'] +268376,how to get user local time at page load i have a web page written in aspnet and i need to retrieve the end users local time at page load i thought about using javascript to get the local time by using new date but the problem is that the script is run after the server events any ideas on how to accomplish thisedit my page is quite complex it thisplays a chart with lots of calculated fields from a database objectfields selection lists etc the customer now requested that it should consider the users timezone and that the timezone should be determined automatically by the web page the user date is important to determine the chart interval which day to thisplay data ondata loading since it is so complicated is done in both page load and page prerender giving up these events would require a full page rewritefinal solution inspired by answerhere is how i solved the problem eventually i am keeping the local date in a cookie here is the method that sets the cookiefunction setlocaldatecookie var cookiename localdate var localdate new date var realmonth localdategetmonth 1 var localdatestring localdategetfullyear realmonth localdategetdate setcookiecookiename localdatestring 2 try var exdate new date exdatesetdateexdategetdate 2 documentcookie cookiename escapelocaldatestring expires exdatetogmtstring catch e in my master page i call this method on documentready on the page where i use this cookie i added the following code to page initif stringisnulloremptycookiehandlerinstancegetcookiecookiekeyslocaldate responseclearcontent responsewriteform idlocal methodpost namelocal script typetextjavascript setlocaldatecookie documentgetelementbyidlocalsubmit script form responseflush responseendthen i can just use the cookie value in the c codethank you for your answerscomments,"['c#', 'javascript', 'asp.net']" +268378,mediaplayer error 190 after repeated plays i have a game in which a sound plays when a level is completed everything works fine to start with but after repeating a level 10 or 20 times the logcat suddenly reportsmediaplayer error 190 andor mediaplayer start called in state 0 and the sounds are no longer madei originally had the all sounds in mp3 format but after reading that ogg may be more reliable i converted them all to ogg but the errors appeared just the sameany idea how i can fix this problem,['android'] +268395,how to add two google charts on the one page what i have donei have added google chart to the head of my page this returns an image of a chartwhat i need to doi simply need to add a second chart to the same pagethe problemthe code for the second chart is ignored i largely suspect this is due to me incorrectly combining the code for each chartthe codefirst chart line load the ajax apiscript typetextjavascript srcscriptscript typetextjavascript load the visualization api and the piechart package googleloadvisualization 10 packagescorechart set a callback to run when the google visualization api is loaded googlesetonloadcallbackdrawchart callback that creates and populates a data table instantiates the pie chart passes in the data and draws it function drawchart var data new googlevisualizationdatatable dataaddcolumnstring month dataaddcolumnnumber apples dataaddcolumnnumber oranges dataaddrows oct 11 20 0 nov 11 0 0 dec 12 0 20 jan 12 0 10 feb 12 0 10 march 12 10 10 set chart options var options width960 height300 instantiate and draw our chart passing in some options var chart new googlevisualizationlinechartdocumentgetelementbyidline chart chartdrawdata options scriptsecond chart pie load the ajax apiscript typetextjavascript srcscriptscript typetextjavascript load the visualization api and the piechart package googleloadvisualization 10 packagescorechart set a callback to run when the google visualization api is loaded googlesetonloadcallbackdrawchart callback that creates and populates a data table instantiates the pie chart passes in the data and draws it function drawchart create the data table var data new googlevisualizationdatatable dataaddcolumnstring topping dataaddcolumnnumber slices dataaddrows mushrooms 3 onions 1 olives 1 zucchini 1 pepperoni 2 set chart options var options titlehow much pizza i ate last night width400 height300 instantiate and draw our chart passing in some options var chart new googlevisualizationpiechartdocumentgetelementbyidchart div chartdrawdata options scripteach of the charts are called in the body using a container div with a unique iddiv idchart divdivmy questionhow do i stitch these two blocks of code together i have tried copying drawchart and specifying unique function names and variables but to no avail,['javascript'] +268404,how does operator binding work in this python example i have recently stumbled over this expressiontrue false in falseit evaluates to false but i do not understand whytrue false is false and false in false is true so both to me plausible possibilitiestrue false in falseandtrue false in falseevaluate to true as i would have expectedwhat is going wrong here,['python'] +268432,get array of property value of each object in another array without a for loop this might be a basic question but i cannot seem to find an answersuppose i have an nsarray cararray with objects of a certain type caris it possible to get an nsarray colorarray with all values of a property color of these objects without iterating cararray with a for loop cfr linq in netnsmutablearray colorlist nsmutablearray alloc initwithcapacity0for car car in cararray colorlist addobjectcarcolorthanks in advance,"['objective-c', 'ios']" +268455,boostenable if c does not seem to work possible duplicatehow to use enable if to enable member functions based on template parameter of class i have a class templatetemplatetypename t size t n class vectori want to enable constructors for specific n so i dovectortypename boostenable if cn2 ttype const e0 t const e1 data0 e0 data1 e1but compiler msvc 2010 sp1 gives me an error instead of applying sfinae the error iserror c2039 type is not a member of boostenable if cbt with bfalse tfloat what is the problem is it a known problem how can i fix it is it the only solution to use static assertedit gcc does not succeed either,['c++'] +268459,getting activity from context in android this one has me stumpedi need to call an activity method from within a custom layout class the problem with this is that i do not know how to access the activity from within the layoutprofileviewpublic class profileview extends linearlayout textview profiletitletextview imageview profilescreenimagebutton boolean isempty profiledata data string name public profileviewcontext context attributeset attrs string name final profiledata profiledata supercontext attrs heres where things get complicated public void onclickview v need to get the parent activity and call its method profileactivity x profileactivity context xactivitymethod profileactivitypublic class profileactivityactivity extends activity in here i am creating multiple profileviews and adding them to the activity dynamically public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutprofile activity main public void addprofilestothisview profiledata temppd new temppd context actvitiycontext thisgetapplicationcontext profile view needs context null name and a profiledata profileview pv new profileviewactvitiycontext null temp temppd profilelayoutaddviewpv as you can see above i am instantiating the profileview programatically and passing in the activitycontext with it 2 questionsam i passing the correct context into the profileviewhow do i get the containing activity from the context,['android'] +268461,ios uilocalnotification no delegate methods triggered when app is running in background and the icon is clicked upon notification iphone version 51 9b176below is the series of events during local notification where in which didfinishlaunchingwithoptions method is not invokedapp is running in background got local notification simple notification no dialogclick on the app icon which shows the badge numberexpected as per apple documentation as a result of the presented notification the user taps the action button of the alert or taps or clicks the application icon if the action button is tapped on a device running ios the system launches the application and the application calls its delegateas didfinishlaunchingwithoptions method if implemented it passes in the notification payload for remote notifications or the localnotification object for local notificationsif the application icon is tapped on a device running ios the application calls the same method but furnishes no information about the notification actual didfinishlaunchingwithoptions not invoked but applicationwillenterforeground and applicationdidbecomeactive were invoked,['iphone'] +268490,loading properties file in init of servlet without using contextparam tag in webxml i have a servlet that reads in a properties file on init my code not the one below works if i have a contextparameter set in my webxml but i read that a contextparameter is globally accessible and i do not want that as this servlet is just a piece of a bigger web application i just want to be able to do this using the initparam tagi tried thispublic void initservletconfig config throws servletexception try string filename configgetinitparameterconfigfile systemoutprintlnfilename file file new filefilename fileinputstream fis new fileinputstreamfile p new properties ploadfis catch ioexception e eprintstacktrace but i keep getting file not found exception i have searched the internet but most people use servlet contexts how else can i load my properties file without including the contextparam tag in my webxmlthankseditjavaiofilenotfoundexception cwebinfclassesmyaproperties the system cannot find the path specifiedat javaiofileinputstreamopennative methodat javaiofileinputstreaminitfileinputstreamjava120at javaiofileinputstreaminitfileinputstreamjava79at ipadserviceproxyservletinitproxyservletjava53at orgapachecatalinacorestandardwrapperloadservletstandardwrapperjava1206at orgapachecatalinacorestandardwrapperallocatestandardwrapperjava827at orgapachecatalinacorestandardwrappervalveinvokestandardwrappervalvejava129at orgapachecatalinacorestandardcontextvalveinvokestandardcontextvalvejava191at orgapachecatalinacorestandardhostvalveinvokestandardhostvalvejava127at orgapachecatalinavalveserrorreportvalveinvokeerrorreportvalvejava102at orgapachecatalinacorestandardenginevalveinvokestandardenginevalvejava109at orgapachecatalinaconnectorcoyoteadapterservicecoyoteadapterjava293at orgapachecoyotehttp11http11processorprocesshttp11processorjava859at orgapachecoyotehttp11http11protocolhttp11connectionhandlerprocesshttp11protocoljava602at orgapachetomcatutilnetjioendpointworkerrunjioendpointjava489at javalangthreadrunthreadjava662,['java'] +268496,how to improve this method using polymorphismoverloading so as to reduce is type check for examplebaseclass mybase public int addbaseclass next if this is inheriteda next is inheriteda return 1 else if this is inheriteda next is inheritedb return 2 else if this is inheritedb next is inheriteda return 3 else if this is inheritedb next is inheritedb return 4 where inheriteda and inheritedb are its inherited classes in fact there are more inherited classes and the add returns different results based on the order and types of its operandi am thinking of rewriting it using polymorphism and overloading however it becomes rather complicated i have to introduce an helper method to resolve the type of either endeginheriteda mya public override int addbaseclass next return nextaddtothis now i have to put addto into baseclass and override it in inherited class as wellinheriteda mya public override int addtoinheriteda next return 1 public override int addtoinheritedb next return 3 baseclass mybase public abstract int addbaseclass next public abstract int addtoinheriteda next public abstract int addtoinheritedb nextis there a better way of doing it,['c#'] +268506,can you use list to get around the 2gb object limit i am running up against the 2gb object limit in c this applies even in 64 bit for some annoying reason with a large collection of structs est size of 42 gig in totalnow obviously using list is going to give me a list of size 42gb give or take but would using a list made up of smaller lists which in turn contain a portion of the structs allow me to jump this limitmy reasoning here is that it is only a hardcoded limit in the clr that stops me instantiating a 9gig object on my 64bit platform and it is entirely unrelated to system resources also lists and arrays are reference types and so a list containing lists would only actually contain the references to each list no one object therefore exceeds the size limitis there any reason why this wouldnt work i would try this myself right now but i do not have a memory profiler on hand to verify,['c#'] +268547,how to statically dump all objc methods called in a cocoa app assume i have a cocoabased mac or ios app i would like to run a static analyzer on my apps source code or my apps binary to retrieve a list of all objectivec methods called therein is there a tool that can do thisa few pointsi am looking for a static solution i am not looking for a dynamic solution something which can be run against either a binary or source code is acceptable ideally the output would just be a massive deduped list of objectivec methods likeamyclass fooansmutablestring stringwithcapacityansstring lengthaif it is not deduped that is coolif other types of symbols c functions static vars etc are present that is finei am familiar with classdump but afaik it dumps the declared classes in your binary not the called methods in your binary that is not what i am looking for if i am wrong and you can do this with classdump please correct mei am not entirely sure this is feasible so if it is not that is a good answer too,"['objective-c', 'ios']" +268552,in usrlibsystemlibcachedylib missing required architecture armv6 in attempting to compile a dummy program for iphoneos xcode4 gcc does not appear to reach beyond the initial sysroot directory echo isysrootapplicationsxcodeappcontentsdeveloperplatformsiphoneosplatformdevelopersdksiphoneos51sdk gcc arch armv6 sysrootisysroot testcppld in usrlibsystemlibcachedylib missing required architecture armv6 in file for architecture armv6collect2 ld returned 1 exit statusif i leave out sysroot gcc arch armv6 testcppld warning ignoring file usrlibcrt1o missing required architecture armv6 in fileld warning ignoring file usrliblibgcc s1dylib missing required architecture armv6 in fileld warning ignoring file usrliblibsystemdylib missing required architecture armv6 in fileundefined symbols for architecture armv6 start referenced from u command line optionld symbols not found for architecture armv6collect2 ld returned 1 exit statusthe following works but it feels very cheesy and not scalable whats going on here gcc arch armv6 lisysrootusrlibsystem sysrootisysroot testcppupdate apparently this is a known issue though it still is not clear how to pass sysroot to gcc but isysroot to ldwhen compiling the library if you see this error ald file not found usrlibsystemlibcachedylib for architecture armv7a3 then your linker command is using aasysroota which doesnat work in xcode 4 instead change the linker command to use aisysroota note this only applies to the linker command the compile commands must continue to use aasysroota see here for more details,['ios'] +268581,php remove empty array elements from a multidimensional array i cannot seem to find a simple straightforward solution to the ageold problem of removing empty elements from arrays in phpmy array may look like this array 0 array name emailaddress and so on if there is more data although there may not beif it looks like the above i want it to be completely empty after i have processed it so print rarray would outputarray if i run arrayx array filterarrayxi still get the same print r output everywhere i have looked suggests this is the simplest way of removing empty array elements in php5 howeveri also tried arrayx array filterarrayxempty arraybut i got the following error warning array filter functionarrayfilter the second argument empty array should be a valid callbackwhat am i doing wrong,['php'] +268589,how to transform array to comma separated words string possible duplicatehow to create comma separated list from array in php my array looks like thisarray 0 lorem 1 ipsum 2 dolor 3 sit 4 amethow to transform this to a string like this with phpstring lorem ipsum dolor sit amet,['php'] +268642,how does aspnet mvc relate a view to a controller action i have opened a sample aspnet mvc projectin homecontroller i have created a method action named methodapublic actionresult methoda return viewi have right clicked on methoda and created a new view called methoda1redid it and created a new view called methoda2how is this magical relationship done i looked for the config to tell the compiler that views methodax are related to action methoda but found nonewhat view will the controller return when methoda is called,['c#'] +268669,capybara and rspec correct way to use within and have selector together i use rspec 260 and capybara 1 for acceptance testingwith a view like the following tr tdteam 3 nametd tdtruetd tda hrefteams3showatd tda hrefteams3editeditatd tda hrefteams3deactivateatdtrtr tdteam 4 nametd tdtruetd tda hrefteams4showatd tda hrefteams4editeditatd tda hrefteams4deactivateatdtri want to write an acceptance test that states team 3 does not have the deactivate link i expect the following to failwithintr text team 3 name do ref pageshould not have selectora text deactivateendbut it passes to further test what is going on i wrote the absurd lock falsewithintr text team 3 name do ref pageshould have selectora text deactivate pageshould not have selectora text deactivate lock trueendlockshould be truewhich passes as welli am assuming from this that the scope the have selector call is using is not limited by the within block but i am not sure why this is the capybara documentation uses this pattern and does not seem to mention any gotchaswhat is the correct way to use within to limit the scope of my selectthank you salernost,"['ruby-on-rails', 'ruby']" +268678,nssortdescriptor not sorting integers correctly i am trying to sort by date then start time start time is minutes from midnight so if the start time is 100 it will not sort properly nsfetchedresultscontroller fetchedresultscontroller if fetchedresultscontroller nil return fetchedresultscontroller set up the fetched results controller create the fetch request for the entity nsfetchrequest fetchrequest nsfetchrequest alloc init edit the entity name as appropriate nsentitydescription entity nsentitydescription entityfornameappointments inmanagedobjectcontextdatamanager sharedinstance managedobjectcontext fetchrequest setentityentity fetchrequest setincludespendingchangesyes set the batch size to a suitable number fetchrequest setfetchbatchsize20 sort using the date then time property nssortdescriptor sortdescriptordate nssortdescriptor alloc initwithkeydate ascendingyes nssortdescriptor sortdescriptortime nssortdescriptor alloc initwithkeystart time ascendingyes nsarray sortdescriptors nsarray alloc initwithobjectssortdescriptordate sortdescriptortime nil fetchrequest setsortdescriptorssortdescriptors use the sectionidentifier property to group into sections nsfetchedresultscontroller afetchedresultscontroller nsfetchedresultscontroller alloc initwithfetchrequestfetchrequest managedobjectcontextdatamanager sharedinstance managedobjectcontext sectionnamekeypathdate cachenamelist afetchedresultscontrollerdelegate self selffetchedresultscontroller afetchedresultscontroller nslogfetchedcontroller fetchedresultscontroller return fetchedresultscontrollerhow could i make this sort integers properly,['objective-c'] +268680,deploying mpi application on windows azure there is an existing mpi scientific application written in c for linux that i would like to run on windows azure is that possibleif possible how to go about deploying the application is it necessary to convert it to microsoft mpi is there a specific kind of azure service i need to buy for thisis it necessary to write a managed wrapper to make it workany suggestionsviewsreferences would be very helpfulps i am new to azure,"['.net', 'c']" +268692,interop native dll and visual studio build process confusing title confusing question but i hope i can get your attention to the pointi have a vs solution with three projects project1 a native dll interop wrapper which imports nativedllproject2 a winforms project that make calls to the wrapper contained by project1project3 a mstest project that make calls to the wrapper contained by project1 project2i have included nativedll in the project1 and configured it to be copied to the output folder this setup will result in the dllimport failing saying that the target dll could not be found the reason is simple i am either running project 2 or 3 and in each caseproject2 when built it copies the project1dll generated by the build process but does not copy nativedll when the code is run the folder is projectdirbindebug or release and the nativedll is not available project3 it is a mstest project when asked to run all tests it compiles the application and copies the output exe and dll to the output folder however it does not copies the nativedll in both examples the dll is copied to the debug folder of the project1 which is uselessis there a simple way to correct this project by simple i mean i would like to avoid using post build to copy or other manual process i would also like to try avoiding using a absolute path to copy the dlli am using visual studio 2010thanksupdate the scenario above was stating that project3 referenced project1 which is not the case project3 references project2 which references project1 in this case the nativedll is copied to project2 output folder but not to the project3 output folder i have also added a project4 of class library type added a reference to project2 and it also does not copies in other words if a project pa has a item x with copy to output rule and a pb references it pb also copies x however if a pc references pb it thisregards the copy rule,['c#'] +268712,recommendations for a development board for embedded programming possible duplicatewhat is the best evaluation kit for learning embedded cc development i am an electronics and software student and i would like to enter the embedded devices world at this point it is just a personal interest not a career choicei am somewhat experienced in cc mostly c i am an experienced linux user i have an arduino but i thislike it because of the java layer on top there are ways to upload c code on the device and i have done this however at this point i am a bit confused i have seen dev kits with debugger and programmer devices i do not know what these are used for i need info on those there are also a lot of dev kits out there that seem to offer various functions some come with software mplab on pics such as compilers and ides that make life easieri have searched for books and information but most either focus on some processor that i cannot find or costs 500 others spend most time teaching c i know c alreadyalso i have the feeling that starting on an arm processor would be best i am not sure that is the best processor to start with but they seem to have a lot of features and are very popular now they also pack a significant throughput i am aware they also consume more power any recommendations on that i have looked at this a book recommendation would also be welcome as i have said i have looked at some which focus on pic mostly sb noss 1urlsearchalias3dapsfieldkeywordsembeddedsystemsx0y0i have found a good book on arm but i am not sure it is for people new to embedded development i think it might be for people new to arm but with experience in embeddedthanks and hope it is not a double,"['c++', 'c']" +268744,ajax is producing object object i am getting an object object from my ajax response ajax type get data id 1id 1id 2id 2 urlajaxurlphp donefunctiondata var left datafindleft lefthtmlleft alertleft in my url i just have a simple codingifisset getid 1 isset getid 2 id 1 getid 1 id 2 getid 2 right dbhprepareselect count from table where id 1 rightexecutearrayid 1 left dbhprepareselect count from table where id 1 leftexecutearrayid 2 div idrightphp echo rightfetchcolumndiv div idleftphp echo leftfetchcolumndivwhen i this is all done it alerts back object objectanyone know why it does thatthanksediti added some coding in the donefunction,"['javascript', 'jquery']" +268762,log1x is to log1p as log1x is to mathh provides a more accurate method for computing log1x for doublesis there a similarly precise manner for computing log1x the reason i ask is because i am trying to do some work in logspace for greater precision i am mostly multiplying and summing numbers very close to zero i found it easy to write a function that gives log explog of a explog of b log a b by using log1p i am trying to make a similar function for the differencelog explog of a explog of b log a b where a b of course essentially as long as neither log a or log b inf the function should simply returnreturn log 1 explog blog a log ain my log add function i end up with a log 1 and so i use log1p but here i have log 1 just in case i even googled log1m but no luckwhen the argument x is in the range inf 1 then i could simply use log1px given my assertion a bis that the best way to go about solving this i feel i must be doing work that has been done beforei would really appreciate your help knowing how to get the most accurate results i can or explaining why i cannot get results more accurate than this,['c++'] +268773,how to add favicon in rails 32 i know new rails apps come with an empty faviconico file i want to know how i go about adding a favicon i know you can use the favicon link tag helper but i am not sure how to populate the faviconico file do you use favicon generators if so which one is besti also want to be able to cache it does rails do that automatically as wellthanks,['ruby-on-rails'] +268774,count of defined array elements given following arrayvar arr undefined undefined 2 5 undefined undefinedi would like to get the count of elements which are defined ie those which are not undefined other than looping through the array is there a good way to do this,['javascript'] +268799,adobe air and iphone how it works anyone knows how the adobe air application are converted to iphone apps i see two ways either the adobe air virtual machine mus be part of every application or they must convert all actionscript calls to cocoa touch calls somehow or have an objectivec twin for every actionscript class and then compile it to arm assembleri am just curious how it is technically donebrsten,"['iphone', 'ios']" +268802,visual studio unable to add to the web site unable to add file access is denied error 550 i am trying to publish my project from my development machine to the staging environment i would right click the project in visual studio and click publish most of the files would publish just fine but a few were giving me problems in the output log there were multiple error messages all statingunable to add axexta to the web site unable to add file axexta access is denied 550i am following this but i do not find the readonly attribute checkboxso have you any ideas thanks in advance,['c#'] +268831,absolute positioning with jquery ui dialogs i am using a few jquery ui modal dialogs and the positioning of each dialog is set to relative by default this is causing me a few problems and i would like to know if there is some way i can get the positioning to be absolute by defaultit seems to me that absolute positioning would make more sense in any case is there any reason in particular for the use of relative positioning for dialogsthanks,['jquery'] +268838,how to get time and date from datetime stamp in php i have 1 string like 8292011 1612 am i want to save in variable like dat 8292011 and tme 1612 amhow would is possible can you give me example,['php'] +268839,how to get client machines mac address in a web application i have to get mac address of clients pc where my website is running so how to get mac address of clients machine not of the servers mac address where website is hosted i need script that is compatible with ie firefox safari and chrome,['asp.net'] +268848,jquery does not support postmessage event when i use jquery event listener to handle message event like belowwindowonmessage functione var data edata data undefineddata is undefined i am sure that i have passed data to current window because if i use addeventlistener everything goes wellso whats the problem,['jquery'] +268862,focus not working as expected in listview i am developing an accessible app for this purpose it is important that all elements of the interface can obtain the focus correctly so that they can be read by talckbacki build a preferenceactivity with a listview inside like in this question preference list only shows first element it works perfect in touch mode but when i try to access to the listview with the talckback activated it is like i try to get focused the listview it does not work like i expected i want the children of the list get the focus not the entire list gets the focus i have an additional problem the two listviews inside my preferenceactivity has scroll and the scroll is not working right can i make the listview no scrollablethankscodelistpreferencesjava custom listviewimport combattleshiprimport androidcontentcontextimport androidcontentsharedpreferencesimport androidpreferencepreferenceimport androidutilattributesetimport androidutillogimport androidviewlayoutinflaterimport androidviewviewimport androidviewviewgroupimport androidviewviewgrouponhierarchychangelistenerimport androidwidgetarrayadapterimport androidwidgetlinearlayoutimport androidwidgetlistviewimport androidwidgetradiobuttonimport androidwidgetradiogroupimport androidwidgetradiogrouponcheckedchangelistenerimport androidwidgettoastpublic class listpreferences extends preference implements oncheckedchangelistener onhierarchychangelistener private listview listview private view thisview private int listheight 0 public listpreferencescontext context supercontext public listpreferencescontext context attributeset attrs supercontext attrs public listpreferencescontext context attributeset attrs int defstyle supercontext attrs defstyle override protected void onclick superonclick toast t toastmaketextgetcontext hola 3 tshow override protected view oncreateviewviewgroup parent thissetlayoutresourcerlayoutlistview preference layout thisview superoncreateviewparent listview listview thisviewfindviewbyidandroidridlist listviewsetonhierarchychangelistenerthis string contentstring new string3 if getkeyequalstheme contentstring new string getcontextgetstringrstringsettings theme default getcontextgetstringrstringsettings theme black getcontextgetstringrstringsettings theme white else contentstring new string getcontextgetstringrstringsettings font big getcontextgetstringrstringsettings font medium getcontextgetstringrstringsettings font little arrayadapterstring array new arrayadapterstringgetcontext androidrlayoutsimple list item single choice androidridtext1 contentstring listviewsetadapterarray listviewsetchoicemodelistviewchoice mode single listviewsetfocusablefalse listviewsetdescendantfocusabilityviewgroupfocus after descendants return thisview private void updatepreferenceint intradio sharedpreferenceseditor editor geteditor editorputintgetkey intradio editorcommit override public void oncheckedchangedradiogroup group int checkedid updatepreferencecheckedid notifychanged override public void onchildviewaddedview parent view child int childheight childgetmeasuredheight ifchildheight 0 listheight listviewgetadaptergetcount childheight thisviewsetminimumheightlistheight logilistaonchildviewadded done listheight childheight public void onchildviewremovedview parent view child preferencexml xml of preferenceactivityxml version10 encodingutf8preferencescreen xmlnsandroid preferencecategory androidkeyplayer settings androidtitlestringsettings player config edittextpreference androiddefaultvaluestringsettings player default name androiddialogmessagestringsettings player summary androiddialogtitlestringsettings playersname androidkeyplayer name androidsummarystringsettings player summary androidtitlestringsettings playersname preferencecategory preferencecategory androidkeyvolume androidtitlestringsettings volume combattleshippreferencesseekbarpreferences androiddefaultvalue50 androidkeyvolume androidtitlestringsettings volume preferencecategory preferencecategory androidkeyshine androidtitlestringsettings shine combattleshippreferencesseekbarpreferences androiddefaultvalue50 androidkeyshine androidtitlestringsettings shine preferencecategory preferencecategory androidkeythemetitle androidtitlestringsettings group themes combattleshippreferenceslistpreferences androidkeytheme preferencecategory preferencecategory androidkeyfontstitle androidtitlestringsettings group font size combattleshippreferenceslistpreferences androidkeyfont preferencecategorypreferencescreensettingsactivityjava preferenceactivitypackage combattleshipimport combattleshiprimport androidosbundleimport androidpreferencepreferenceactivityimport androidutillogimport androidviewmotioneventimport androidviewviewpublic class settingsactivity extends preferenceactivity public void oncreatebundle savedinstancestate superoncreatesavedinstancestate addpreferencesfromresourcerxmlpreferences override public view getcurrentfocus logdfoco supergetcurrentfocus return supergetcurrentfocus override public boolean ontrackballeventmotionevent event logdtrackball event return superontrackballeventevent,['android'] +268887,how do i get the local ip address of the server using php i am developing a php application that will be run only on the local network of a business the application will be installed to the server using a custom installer like thing we made using stunnix advanced webserveras part of making the application more user friendly i am planning to thisplay the local ip of the server so that it is extremely easy for the other computers in the network to access the application by just typing this ip in their address barthe problem is i cannot get the local ip of the serveri have tried server name thisplays just 127001 remote addr thisplays client external ip server addr thisplays the correct ip but it does so only if i access it from a client using the ip which totally defeats its purpose i just want to thisplay the local ip of the server upon access directly from the server through httplocalhost itselfi am somewhat sure that this is not possible but if it is please helpediti am developing a cross platform php server application kind of thing we bundle apachephp installers and a sqlite database as a one click installer alongside our php application to make it as user friendly as possible anyone can deploy it on their computer running windowsmac or linux after installing when the user opens the application on the server he can see the ip address local ip and port which can be used to connect to this server the application will be run only on the local network and not on the internetit should show the local ip just like the android app called air droid does screenshot 4nvydwlg8x0qwdberedwghg5xku4s,['php'] +268891,background image for uinavigationcontroller i want to add background image to uinavigationcontroller please help me,"['iphone', 'objective-c', 'ios']" +268892,confusion about get and call in python see the simple example belowclass celsiusobject def init self value00 selfvalue floatvalue def get self instance owner return selfvalue def set self instance value selfvalue floatvalue def call self print call calledclass temperatureobject celsius celsius def init self selfcelsius1 celsiust temperatureprinttcelsius tcelsiusprinttcelsius1 tcelsius1outputtcelsius 00tcelsius1 main celsius object at 0x023544f0i wonder why they have different outputi know tcelsius will call the get and tcelsius1 call the call,['python'] +268929,issues with setting some different font for uilabel i would like to set the font size and familyname to the titlelabel helvetica neue ultralight titlelabel setfontuifont fontwithnamehelvetica neue ultralight size250fthis is not working kindly tell me what could be wrongany help will be appreciated,"['iphone', 'ios']" +268932,how to convert enum names to string in c is there a possibility to convert enumerator names to string in c,['c'] +268935,mysql date formats difficulty inserting a date i am trying to further a question i asked yesterday where i wanted to know how to query a date in a different format but now i am trying to dao an insert using this method see below however i cant get it to work i have checked the manual but it is not beginner freindlyinsert into custorder values kevinyes str to date1012012 dmy,['mysql'] +268963,how to closecancelthismiss a system dialog programmatically android i have an app that make ussd calls but after all ussd calls i got a dialog with the result to the useri know that is possible to thismiss this dialog because the ussd checker app do this they get the response from ussd without showing the user dialogin the phone utils classhas the function thisplaymmicomplete that after complete the ussd call show a type system dialog in the phoneutilsjava they use the dialog like this alertdialog newdialog new alertdialogbuildercontext setmessagetext setpositivebuttonrstringok null setcancelabletrue createnewdialoggetwindowsettype windowmanagerlayoutparamstype system dialognewdialoggetwindowaddflags windowmanagerlayoutparamsflag dim behindnewdialogshowthen i cannot just send some flag to thismiss it and i cannot use that import its a system classand when i do x consecutive calls appears x dialogs to the user close and my app will need to do consecutive calls there is anyway to programmatically close this system dialog,['android'] +268972,django djangoextensions commands unavailable graph models i am trying to install djangoextensions graphviz pygraph but i cannoti have done the following steps under ubuntu sudo aptget install graphviz libgraphvizdev graphvizdev pythonpygraphvizin the project virtualenv running python 272source path to virtualenvbinactivatepip install django djangoextensionsif i runwhich pythonit selects the python in my virtualenv so the python i am using is the right onein the virtualenvs sitepackage i have pygraphviz and djangoextensionspython managepy shellimport django extensionsimport pygraphviz runs okin my django project i have added django extensions in my installed appsbut when i runpython managepy helpi cannot see the commands and they are unavailablepython managepy graph models a g o modelpngunknown command graph modelstype managepy help for usagehow can i fix this thanks,['python'] +268981,html why do buttons in forms send data this is a very rudimentary question but i am sure someone out there knows why in html when i make a button element by itself and do not give it and onclick and no jquery click the button will just do nothing perfect but when i do this and but the button inside a form element it tries to send get data of all the form elements to the root address of my website why is it doing that i did not make it a submit button or even define a method or action on that formthanks for the info in advance edit this is what i did to fix the problem for buttons inside the form usebutton typebuttonbuttonand it will not do anything by default,['html'] +269016,convert json into uriencoded string i got a jsonjavascript object which i would like to get xwformurlencodedsomething like myformserialize but for objectsthe following object firstname jonas lastname gauffinwould get encoded tofirstnamejonaslastnamegauffin do note that special characters should get encoded properly,"['javascript', 'jquery']" +269027,how fast is thread local variable access on linux how fast is accessing a thread local variables in linux from the code generated by the gcc compiler i can see that is uses the fs segment register so apparently the access to the thread local variable should not cost extra cycles however i keep on reading horror stories about the slowness of thread local variable access how come sure sometimes different compilers use a different approach than using fs segment register but is accessing thread local variable through fs segment register slow too,['c'] +269057,how to stretch input field to full width i have a simple html form i would like the right widgets in the second column text field combox and so on to stretch and fill the full columnmy html looks like thistable classformtable tr td classcol1report numbertd td classcol2input typetexttd tr tr td classcol1report typetd td classcol2selectselecttd trtablemy css looks like thisformtable bordercolor blackformtable td padding 10pxformtable col1 textalign rightformtable col2 width 100any ideas,"['html', 'css']" +269068,ejabberd retrieve chat history from mysql db i am building a chat system based on ejabberd using an ios client and xmppframeworkmy current chat system supports only oneonone conversations between users saving a chat history on a mysql databasein order to recreate the same chat system i would need ejabberd to retrieve chat history from my database so the users do not lose previous conversations when switching to the new chat system i would like not to save the conversation clientside since the ios app can be deleted and reinstalled or the user could switch deviceis it possible to make ejabberd read chat history from my mysql db,['mysql'] +269100,get specific version of a deleted file in tfs i have this really weird problem with tfs that i cannot seem to solveabout a year ago i created a file called extensionscs and placed it in source control let us say around changeset 10 at changeset 50 the file was deleted as it was no longer needed and life continued no problems of coursenow i need to build an older program from around changeset 30 it just so happened to use extensionscs but i cannot check that file out at changeset 30 or any changeset for that matter even though it would have existed at that time i can see the file in the source control explorer but it is grayed out and its latest status is listed as deletedit would seem silly that i would not be able to get it back out so what i am doing wrong and how do i solve this problem,['c#'] +269111,adding event hovertext in fullcalendar i am trying to include a hover text on events in a month calendar page of full calendari have and array object declaring the events that need to be on the page as loaded in by a php script it looks as followedcalendarfullcalendarevents title event1 start 20100101 title event2 start 20100105 end 20100107 i am trying to use the eventmouseover function to include a hover text with each event this functions prototype is as followed function event jsevent view where event is the event object jsevent is the native javascript event with lowlevel information such as mouse coordinates and the view holds the view object of fullcalendar i am not able to correctly call the arguments of this function my info is coming from here and i am totally cool with other ways of achieving a hovertext on each event thank you,"['javascript', 'jquery']" +269114,how can i thisable squidunusedprotectedmethod in sonar for a class or method i have a couple hadoop map and reduce classes that override protected methods sonar flags these withunused protected methodplugin squid key unusedprotectedmethodi know there is a fix in sonar that addresses this and that at some point my organization will use a version with that fix in the meantime i would like to thisable the warning i have triedsuppresswarningsunusedprotectedmethodandsuppresswarningssquidunusedprotectedmethodto no availsuppresswarnings works for pmd issues eduumdcsfindbugsannotationssuppresswarningsvalue blah works for findbugs issues is there another variant for squid issues or is it just not supported yet,['java'] +269131,c close standard out i would like to be able to detach my program from the console much like wget b a code fragment might look likestatic void mainstring args var settings new settingsargs if settingsbackground tell the user whats going on systemconsolewritelinedetatching from console the program will still be running systemconsoleoutclose do work then exitbut systemconsoleoutclose does not do the right thingto clarify the right thing is when running this program from the console the prompt should reappear or when running this program from explorerexe the console window should closeplease let me know if i am not being clear,['c#'] +269164,delegate all method calls on a model to an association i am having an activerecord model with a polymorphic association like thisclass reach activerecordbase belongs to reachable polymorphic trueendthis model acts like a proxy what i need to do is to forward all method calls on that object to the associated object reachable i think delegate would not help here because i have to explicitly name all the methods i need to delegate i need something like delegate all to delegate all methods not all method,"['ruby-on-rails', 'ruby']" +269179,how to set both min and max size for an imageview in android i would like so specify both min widthheight and max widthheight for an imageview the image should be scaled to fitdoing thisimageview androidlayout widthwrap content androidlayout heightwrap content androidminwidth100dp androidmaxwidth200dp androidminheight100dp androidmaxheight200dp androidsrcdrawableic launcher the min width and height perform as they should but max width and height are ignoredif i set androidadjustviewboundstrueimageview androidlayout widthwrap content androidlayout heightwrap content androidadjustviewboundstrue androidscaletypefitcenter androidminwidth100dp androidmaxwidth200dp androidminheight100dp androidmaxheight200dp androidsrcdrawableic launcher than the max width and height perform as they should but min width and height are ignoredis there a way to have both,['android'] +269206,bootstrapsass undefined variable baselineheight i have integrated bootstrap into my app using bootstrapsass the app works fine on my local machine but when i go to deploy via capistrano i get this errorundefined variable baselineheightin varwcollegesportsbluebooksharedbundleruby191gemsbootstrapsass201vendorassetsstylesheetsbootstrap accordionscsswhen the capistrano attempts to run assetsprecompilei think this variable is throwing the error because it is the first variable in the first scss file that is attempted to be precompiledsomething is not loading up right any ideas what it might beeditfull trace here edit 2added applicationrb and productionrb to gist,['ruby-on-rails'] +269226,android sqlite no such table exception im starting into sqlite and databases in android and i just found this issue have red a lot of similar questions but i have not found a solution yetthis is the error code i am gettingeandroidruntime529 caused by androiddatabasesqlitesqliteexception no such table ligas bd while compiling select from ligas bdthis is my code dbhelper mydbhelper new dbhelperthis mydbhelper new dbhelperthis try mydbhelpercreatedatabase catch ioexception ioe throw new errorunable to create database try mydbhelperopen sqlitedatabase db null db mydbhelpergetwritabledatabase string args new string cursor c dbrawquery select from ligas bd args error in this line if cmovetofirst do string cod cgetstring0 string nombre cgetstring1 string flag cgetstring0 string cod url cgetstring0 ligasaddnew item liganombre flag cod cod url whilecmovetonext catchsqlexception sqle throw sqle dbhelperjavapublic class dbhelper extends sqliteopenhelperprivate static string db name ligas bdprivate sqlitedatabase mydatabaseprivate final context mycontextpublic dbhelpercontext context supercontext db name null 1 thismycontext contextpublic void createdatabase throws ioexception boolean dbexist checkdatabase ifdbexist else thisgetreadabledatabase try copydatabase catch ioexception e throw new errorerror copiando base de datos private boolean checkdatabase sqlitedatabase checkdb null try string mypath db path db name checkdb sqlitedatabaseopendatabasemypath null sqlitedatabaseopen readonly catchsqliteexception e ifcheckdb null checkdbclose return checkdb null true falseprivate void copydatabase throws ioexception inputstream myinput mycontextgetassetsopendb name string outfilename db path db name outputstream myoutput new fileoutputstreamoutfilename byte buffer new byte1024 int length while length myinputreadbuffer0 myoutputwritebuffer 0 length myoutputflush myoutputclose myinputclosepublic void open throws sqlexception try createdatabase catch ioexception e throw new errorha sido imposible crear la base de datos string mypath db path db name mydatabase sqlitedatabaseopendatabasemypath null sqlitedatabaseopen readonlyoverridepublic synchronized void close ifmydatabase null mydatabaseclose supercloseoverridepublic void oncreatesqlitedatabase db overridepublic void onupgradesqlitedatabase db int oldversion int newversion i also checked in my phone with root explorer datadatamypackagenamedatabases and the database apears there as normalthanks in adviceedit my database and the main table have the same name as you can see in this pic of sqlite database browseredit2 i forgot to say that i am not creating the table i created it before using sqlite database browser and i am just trying to read from itedit3 do not know how but i finally fixed it i just started again this time following this tutorial hope it helps,['android'] +269236,looping through view model properties in a view i have a painfully simple view modelpublic class tellafriendviewmodel public string email1 get set public string email2 get set public string email3 get set public string email4 get set public string email5 get set and then the corresponding inputs on my view but i am wondering if there is a better way such as a loop to write similar textboxes to my viewusing htmlbeginform htmlantiforgerytoken htmltextboxforvm vmemail1 htmltextboxforvm vmemail2 htmltextboxforvm vmemail3 htmltextboxforvm vmemail4 htmltextboxforvm vmemail5,"['c#', '.net']" +269249,openmp and gsl rng performance issue 4 threads implementation 10x slower than pure sequential one quadcore cpu i am trying to turn a c project of mine from sequential into parallel programming although most of the code has now been redesigned from scratch for this purpose the generation of random numbers is still at its core thus bad performance of the random number generator rng affects very badly the overall performance of the programi wrote some code lines see below to show the problem i am facing without much verbositythe problem is the following everytime the number of threads nt increases the performance gets singnificantly worse at this workstation linux kernel 26334 gcc 4 intel quadcore cpu the parallel forloop takes roughly 10x longer to finish with nt4 than with nt1 regardless of the number of iterates nthis situation seems to be described here but the focus is mainly in fortran a language i know very little about so i would very much appreciate some helpi tried to follow their idea of creating different rng with a different seed to be accessed by each thread but the performance is still very bad actually this different seeding point for each thread bugs me as well because i cannot see how it is possible for one to guarantee the quality of the generated numbers in the end lack of correlations etci have already thought of dropping gsl altogether and implementing a random generator algorithm such as mersennetwister myself but i suspect i would just bump into the same issue later onthank you very much in advance for your answers and advice please do ask anything important i may have forgotten to mentionedit implemented corrections suggested by lucas1024 pragma forloop declaration and jonathandursi seeding setting a as a private variable performance is still very sluggish in multithreadmodeedit 2 implemented solution suggested by jonathan dursi see comments include stdioh include stdlibh include timeh include gslgsl rngh include omph double d t struct timespec t1 struct timespec t2 return t2tv sect1tv secdoublet2tv nsect1tv nsec10 int main int argc char argv double a b int ijk int natoiargv1 seedatoiargv2 ntatoiargv3 printfnnt d n printfnseedt d seed printfnntt d nt struct timespec t1 t2 t3 t4 clock gettimeclock process cputime id t1 initialize gsl random number generator const gsl rng type rng t gsl rng rng gsl rng env setup rng t gsl rng default rng gsl rng mallocnt sizeofgsl rng pragma omp parallel for num threadsnt fori0inti rngi gsl rng alloc rng t gsl rng setrngiseedi clock gettimeclock process cputime id t2 for i0ini a gsl rng uniformrng0 clock gettimeclock process cputime id t3 omp set num threadsnt pragma omp parallel privateja j omp get thread num pragma omp for fori0ini a gsl rng uniformrngj clock gettimeclock process cputime id t4 printfnninitializingt1 f seconds d tt1t2 printfnsequencial for looptt2 f seconds d tt2t3 printfnparalel for looptt3 f seconds f t2 d tt3t4 doubled tt3t4doubled tt2t3 printfnnumber of threadstnt dn nt free random number generator for i0inti gsl rng freerngi freerng return 0,['c'] +269261,how to use modules in rails application i just created a module locationrb inside lib folder with following contentsmodule location def selfmy zipcode zip code 11215 endendand now in my controller i am trying to call my zipcode methodclass directorycontroller applicationcontroller def search require location zip code locationmy zipcode endendbut it throws an errorundefined method my zipcode for locationmodule,"['ruby-on-rails', 'ruby']" +269302,how to get names of background running apps i am making an app in which i need to show the names of apps running in background i did rd on it and came to know that we can know only about apples apps like photos camera etc but i could not know how please help me if you know how to get just names of background running appsfor background running processes i have used following method nsarray runningprocesses int mib4 ctl kern kern proc kern proc all 0 size t miblen 4 size t size int st sysctlmib miblen null size null 0 struct kinfo proc process null struct kinfo proc newprocess null do size size 10 newprocess reallocprocess size if newprocess if process freeprocess return nil process newprocess st sysctlmib miblen process size null 0 while st 1 errno enomem if st 0 if size sizeofstruct kinfo proc 0 int nprocess size sizeofstruct kinfo proc if nprocess nsmutablearray array nsmutablearray alloc init for int i nprocess 1 i 0 i nsstring processid nsstring alloc initwithformatd processikp procp pid nsstring processname nsstring alloc initwithformats processikp procp comm nsdictionary dict nsdictionary alloc initwithobjectsnsarray arraywithobjectsprocessid processname nil forkeysnsarray arraywithobjectsprocessid processname nil processid release processname release array addobjectdict dict release freeprocess return array autorelease return nilif you think its impossible then kindly have a look to this app i have also got a solution but its not a proper way i have mentioned in the last comment below this questionthanks,['iphone'] +269308,thisable user edit in jtable when a jtable component is created cell editing is enabled by default how can i prevent the user from editing the content of a jtable,['java'] +269324,how do i add a link from the django admin page of one object to the admin page of a related object to deal with the lack of nested inlines in djangoadmin i have put special cases into two of the templates to create links between the admin change pages and inline admins of two modelsmy question is how do i create a link from the admin change page or inline admin of one model to the admin change page or inline admin of a related model cleanly without nasty hacks in the templatei would like a general solution that i can apply to the admin change page or inline admin of any modeli have one model post not its real name that is both an inline on the blog admin page and also has its own admin page the reason it cannot just be inline is that it has models with foreign keys to it that only make sense when edited with it and it only makes sense when edited with blogfor the post admin page i changed part of fieldsethtml from if fieldis readonly p fieldcontents p else fieldfield endif to if fieldis readonly p fieldcontents p else ifequal fieldfieldname blog p fieldfieldforminstanceblog linksafe p else fieldfield endifequal endif to create a link to the blog admin page where blog link is a method on the modeldef blog linkself return a hrefssa reverseadminmyblog blog change argsselfblogid escapeselfblogi could not find the id of the blog instance anywhere outside fieldfieldforminstanceon the blog admin page where post is inline i modified part of stackedhtml fromh3b inline admin formsetoptsverbose nametitle bnbspspan classinline label if inline admin formoriginal inline admin formoriginal else forloopcounter endif spantoh3b inline admin formsetoptsverbose nametitle bnbspspan classinline label if inline admin formoriginal ifequal inline admin formsetoptsverbose name post a hrefadminmyblogpost inline admin formpk fieldfieldvalue inline admin formoriginal a else inline admin formoriginal endifequal else forloopcounter endif spanto create a link to the post admin page since here i was able to find the id stored in the foreign key fieldi am sure there is a better more general way to do add links to admin forms without repeating myself what is it,['python'] +269333,eclipse does not highlight matching variables eclipse does not highlight matching variables for mei have already tried to change mark occurrences viawindow preferences java editor mark occurrencesbut it did not work i am not sure why this is not working while others have been able to fix the problemcan anyone tell me how can i set highlighting matching variables looking for same variables with my eyes really bothering me too much,['java'] +269360,how can i check a php file for undefined functions calling php l checks the syntax of a php fileis there a way to check for undefined functions i do not need it to work with functions defined at runtime nor with dynamic callscalling the file obviously would not work i need to check the whole file not only the branch that gets executed see the follwing examplemyfilephpfunction imhere mainphprequire once myfilephpif true imhereelse imnhothere i need to get a warning about this,['php'] +269376,is not calling delete on a dynamically allocated object always a memory leak from the thiscussion started here i would like to know whether the following code has a memory leakint main new int or int x new int return 0i know the memory is reclaimed by the os but is it a leak anyway i believe it iswhat defines a memory leak i could only find one reference in the standard and it was not very helpfuledit i do not want to start a debate i think that is not the kind of answer i am looking for i am mostly interested in sources what c books or websites or whatever have to say about it,['c++'] +269394,how to handle a delegated event for child elements only when delegating events using on how do i target child elementsi have tried childselector nthchildnbut nothing is selected when i start with selectoronevent childselector handlersometimes i want to target a direct child sometimes i do not pseudo codevar func functionselector subselector selectoronclick subselector function alertmy subselector is clicked funcwrapper directchildselectorfuncwrapper some other selectorfirstthats why i am asking for a selector and not a fix,"['javascript', 'jquery']" +269430,pinching zoom for text view i want to do pinching functionality zoom in zoom out for text view i have already refer to many tutorials but not getting any fruitful please help me if any one have done it or knows how to do it can i do it also with using button as zoom in and out andor using 2 finger pinching any help would be appreciated thanksnot working code setcontentviewrlayoutmain mainview linearlayoutfindviewbyidridlinearlayout button buttonzoomout buttonfindviewbyidridbuttonzoomout button buttonnormal buttonfindviewbyidridbuttonnormal button buttonzoomin buttonfindviewbyidridbuttonzoomin buttonzoomoutsetonclicklistenernew viewonclicklistener public void onclickview v zoom05f05fnew pointf00 buttonnormalsetonclicklistenernew onclicklistener public void onclickview v zoom1f1fnew pointf00 buttonzoominsetonclicklistenernew viewonclicklistener public void onclickview v zoom2f2fnew pointf00 zooming is done from here public void zoomfloat scalexfloat scaleypointf pivot mainviewsetpivotxpivotx mainviewsetpivotypivoty mainviewsetscalexscalex mainviewsetscaleyscaley,['android'] +269441,how to use intent for choosing file browser to select file how to use intent to prompt user to choose finish action with to choosing app to select file assuming there is a few app to browse file in the devicei want to filter the file using an extension eg sav props thank you in advance,['android'] +269445,removing duplicate objects with underscore for javascript i have this kind of arrayvar foo a 1 b 2 a 1 i would like to filter it to havevar bar a 1 b 2 i tried using uniq but i guess because a 1 is not equal to itself it does not work is there any way to provide underscore uniq with an overriden equals function,['javascript'] +269544,can i set a value on a struct through reflection without boxing actually i should have asked how can i do this and remain cls compliant because the only way i can think of doing this is as follows but using either makeref fieldinfosetvaluedirect or just systemtypedreference in general invalidates cls compliance code illustrating the issuetestfields fields new testfields maxvalue 1234 test struct with one fieldfieldinfo info fieldsgettypegetfieldmaxvalue get the fieldinfo actual magic no boxing not cls complianttypedreference reference makereffieldsinfosetvaluedirectreference 4096the compliant counterpart of setvaluedirect is setvalue but it takes an object as the target hence my struct will be boxed making me setting a value on a copy not the original variable a generic counterpart for setvalue does not exist as far as i know is there any other way of setting the field of a reference to a struct through reflection,['c#'] +269547,styling native tooltip from titletooltip text i have input element that has title attribute which of course will result with tooltip with message of the attribute valuefor some reason this tooltip needs to be styled with css how can it be done i do not know in which container it will be rendered i do not know nothing about it also it cannot be accessed by developer tools of firebug,['css'] +269581,method post status canceled error message i have the following code which is giving me a method post status canceled error messagedocumentreadyfunction var xhr false get default txt1keyup function ifxhr xhrreadystate 4 alertabort xhrabort if txt1vallength 2 get data txt1val else get default function get data phrase xhr ajax type post url httpintranetwebservicesasmxgetdata data phrase phrase contenttype applicationjson charsetutf8 datatype json success function results div1empty if resultsd0 each resultsd function index result div1append resultcol1 resultcol2 br else alert no data available message goes here error functionxhr status error var err eval xhrresponsetext alerterrmessage function get default div1emptyappenddefault content goes here the code actually works as long as each ajax request completes but if i type fast into txt1 ie type the next character before the previous request finishes i get the error message method post status canceledanyone know why this is happening and how to correct the error,"['javascript', 'jquery']" +269651,call the default aspnet httphandler from a custom handler i am adding aspnet routing to an older webforms app i am using a custom httphandler to process everything in some situations i would like to map a particular path back to an aspx file so i need to just pass control back to the default httphandler for aspnet the closest i have gotten is this public void processrequesthttpcontext context when we decide to pass it on var handler new systemwebuipage handlerprocessrequestcontext memorystream steam new memorystream streamwriter writer new streamwriterstream htmltextwriter htmlwriter new htmltextwriterwriter handlerrendercontrolhtmlwriter write headers etc send stream to responseit does not do anything there is nothing output to the stream mss documentation for systemwebuipage as an ihttphandler say something to the effect of do not call the processrequest method it is for internal use from looking around it seems like you can do this with mvc eg mvchttphandler doesnt seem to implement ihttphandlerthere is also this thing systemwebuipagehandlerfactory which appears that it would just produce a page handler for an aspx file but it is internal and i cannot use it directlythis page refers to the default aspnet handler but does not identify a class or give any indication how one might use itany ideas on how i can do this is it possible,['asp.net'] +269652,differentiate regular menu keyevent from ime opening in listening for key events in actionbarsherlock in order to show the overflow menu on preics devices and am i am facing an interesting problem it would seem that i am unable to differentiate a simple key press versus when the user is longpressing the menu key with the intention of thisplaying the ime both keyevent instances are exactly the same and look like thisis there a straightforward way to differentiate between these two thistinct events,['android'] +269662,fragmentactivity causing classnotfoundexception i just used android sdk manager to update android sdk tools to revision 17 and android compatiblity to revision 7 now the program i have been running for ages crashes on startupnarrowing down the issue i have created a new blank project added androidsupportv4jar to the build path and changed activity to fragmentactivity and that is all now it crashesthe error message isjavalangclassnotfoundexception comexampletesttestactivity in loader dalviksystempathclassloaderdataappcomexampletest2apkthe code ispackage comexampletestimport androidosbundleimport androidsupportv4appfragmentactivitypublic class testactivity extends fragmentactivity called when the activity is first created override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain everything else including the manifest is unchanged from the defaults any help is much appreciatededit manifest included belowxml version10 encodingutf8manifest xmlnsandroid packagecomexampletest androidversioncode1 androidversionname10 usessdk androidminsdkversion9 application androidicondrawableic launcher androidlabelstringapp name activity androidnametestactivity androidlabelstringapp name intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity applicationmanifest,['android'] +269675,apple macho linker errors 20 undefined symbols for architecture armv7 i received these errors after i added all load in the other linker flags build setting once i added libpushercombineda and its header files i followed the instructions exactly up to the part of typing in all load under using a precompiled static library in the adding to your ios project but i ended up getting 20 macho linker errors could anyone please help me with thishere are the errorsundefined symbols for architecture armv7 utf8 nextcharsafebody referenced from srwebsocket pumpscanner in libpushercombinedasrwebsocketo scerror referenced from reachability startnotifier in libpushercombinedareachabilityo utf8 counttrailbytes referenced from srwebsocket pumpscanner in libpushercombinedasrwebsocketo scnetworkreachabilitysetthispatchqueue referenced from reachability startnotifier in libpushercombinedareachabilityo reachability stopnotifier in libpushercombinedareachabilityo kcfhttpversion1 1 referenced from srwebsocket didconnect in libpushercombinedasrwebsocketo cfhttpmessageisheadercomplete referenced from 30srwebsocket readhttpheader block invoke 0 in libpushercombinedasrwebsocketo cfhttpmessagecreaterequest referenced from srwebsocket didconnect in libpushercombinedasrwebsocketo scnetworkreachabilitycreatewithaddress referenced from reachability reachabilitywithaddress in libpushercombinedareachabilityo scerrorstring referenced from reachability startnotifier in libpushercombinedareachabilityo scnetworkreachabilitycreatewithname referenced from reachability reachabilitywithhostname in libpushercombinedareachabilityo cfhttpmessagecopyallheaderfields referenced from 30srwebsocket readhttpheader block invoke 0 in libpushercombinedasrwebsocketo cfhttpmessagegetresponsestatuscode referenced from srwebsocket httpheadersdidfinish in libpushercombinedasrwebsocketo cfhttpmessagesetheaderfieldvalue referenced from srwebsocket didconnect in libpushercombinedasrwebsocketo 25srwebsocket didconnect block invoke 0 in libpushercombinedasrwebsocketo cfhttpmessagecreateempty referenced from srwebsocket readhttpheader in libpushercombinedasrwebsocketo cfhttpmessagecopyserializedmessage referenced from srwebsocket didconnect in libpushercombinedasrwebsocketo scnetworkreachabilitysetcallback referenced from reachability startnotifier in libpushercombinedareachabilityo reachability stopnotifier in libpushercombinedareachabilityo scnetworkreachabilitygetflags referenced from reachability isreachable in libpushercombinedareachabilityo reachability isreachableviawwan in libpushercombinedareachabilityo reachability isreachableviawifi in libpushercombinedareachabilityo reachability connectionrequired in libpushercombinedareachabilityo reachability isconnectionondemand in libpushercombinedareachabilityo reachability isinterventionrequired in libpushercombinedareachabilityo reachability reachabilityflags in libpushercombinedareachabilityo cfhttpmessagecopyheaderfieldvalue referenced from srwebsocket checkhandshake in libpushercombinedasrwebsocketo cfhttpmessageappendbytes referenced from 30srwebsocket readhttpheader block invoke 0 in libpushercombinedasrwebsocketold symbols not found for architecture armv7clang error linker command failed with exit code 1 use v to see invocationif you need more information just ask i hope that i am not giving too much trouble thanks in advance,"['iphone', 'ios']" +269693,added a shadow to a uiimageview on a uitableview kills performance why i have a uitableview that has three uiimageview views per cell with three cell thisplaying on the view at one time for a total of nine uiimageview views think of it as a bookshelf sometimes i can have as many as 500 booksi have added shadow to the uiimageview with code that is thisuiimageview itemimageview uiimageview alloc initwithframecgrectmake25 7 65 75itemimageviewcontentmode uiviewcontentmodescaleaspectfititemimageviewtag 6itemimageviewlayershadowcolor uicolor blackcolorcgcoloritemimageviewlayershadowoffset cgsizemake3 1itemimageviewlayershadowopacity 07itemimageviewlayershadowradius 30itemimageviewclipstobounds nocellcontentview addsubviewitemimageviewwhen i add the shadow code as seen above scrolling performance is just totally killed and becomes choppy each image has a different rect so the shadow has to be created for each item as it scrolls anyone have any tips on how to add shadows to my images on a uitableview without having this issue,"['iphone', 'objective-c', 'ios']" +269728,downloadmanagerrequestsetnotificationvisibility fails with jsecurityexception invalid value for visibility 1 i am trying to use the downloadmanager to download large pdf files from my app i want notifications to be thisplayed during the download as well as when the download finishes however setting the visibility causes above exceptionthis error is different from this post downloadmanagerrequestsetnotificationvisibility fails with jsecurityexception invalid value for visibility 2the other post is asking for help when setting the visibility to visibility hidden for which you need permission in the manifest i am trying to set the visibility to downloadmanagerrequestvisibility visible notify completed like sopublic class dmnotifytestactivity extends activity called when the activity is first created overridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain downloadmanager mgr downloadmanager getsystemservicedownload service long downloadid mgr enqueuenew downloadmanagerrequesturiparse reference 17pdf setnotificationvisibility downloadmanagerrequestvisibility visible notify completed setdestinationinexternalpublicdirenvironmentdirectory downloads hellopdf setdescriptionmytestpack docwhich results in this stacktraceeandroidruntime24794 caused by javalangsecurityexception invalid value for visibility 1eandroidruntime24794 at androidosparcelreadexceptionparceljava1321eandroidruntime24794 at androiddatabasedatabaseutilsreadexceptionfromparceldatabaseutilsjava182eandroidruntime24794 at androiddatabasedatabaseutilsreadexceptionfromparceldatabaseutilsjava136eandroidruntime24794 at androidcontentcontentproviderproxyinsertcontentprovidernativejava447eandroidruntime24794 at androidcontentcontentresolverinsertcontentresolverjava721eandroidruntime24794 at androidappdownloadmanagerenqueuedownloadmanagerjava877eandroidruntime24794 at mytestpackdmnotifytestactivityoncreatedmnotifytestactivityjava18without setting visibility the code works fine i have already attempted adding various permissions to the manifest but still no go this is targeting level 11 so honeycomb and up permissions i have tried areandroidpermissiondownload without notificationandroidpermissionsend download completed intentsandroidpermissionaccess download managerandroidpermissionaccess download manager advanced,['android'] +269743,how do i submit a form in jquery async in mootools i would do something like form idsendsuccessfunctionreswhat is the parallel syntax in jqueryanother wordshow would i put my form data assume idbob into the following codeajax type post url url data data success success datatype datatype,['jquery'] +269756,should i leave an unreachable break in a case where i throw an exception is it silly of me to leave unreachable break statements in a case that just throws an exception anyway the defensive part of me wants to leave it there in the event that the logic changes another part of me does not want other developers seeing compiler warnings on my code unreachable code detectedswitch someint case 1 do something break case 2 do something else break case 3 oh we do not use threes here throw new exceptionbusiness rules say do not use 3 anymore break unreachableuntil the fickle business rules change default throw new exceptionsome default exception break unreachableuntilwell you get the ideawhat to doupdatei see a few responses saying that removing the throw at a later date would cause a compiler error however simply removing or commenting the throw without a break following it would stack the cases which may be unintended behavior i am not saying it is a likely scenario butwell is defensive programming about combating only likely scenarios,['c#'] +269781,design suggestion llvm multiple runtime contexts my application needs to run many separate contexts in the same singlethreaded process they all share a single llvmcontext the process will run many contexts in the thread sense that is each one runs a function in a continuation object based on boostcontext still on vault preapproved lib it means that each context can yield but they basically run in the same singlethreaded process each one should run basically independent of the other and more importantly a compilation error in each one should not affect the execution of the otherseach of these contexts will invoke code dynamically that spans multiple translation units tu some translation units may be shared across many of these contexts compilation errors in a new or modified translation unit should not affect other contextsclarification editfor example tu a might be shared among two contexts context x and y just for the sake of having a full picture lets say that x will also be running code from other translations units ie b and d while y will have also c at some point x decides to make a modification to a so it creates a new tu a1 which is a copy of a and applies the modification there so those will not affect context y hope this example makes it clear the requirement my initial impulse was to associate one llvmmodule for each context but since its undefined in llvm what happens with a module in an intermediate state of compilation i decided to add one llvmmodule for each translation unit see this question for the reason plus the copyonwrite policy i explained before for when modifications of a translation unit happen locally to a context in order to avoid a modification affecting other contextsthe main twofold question i have have ishow do i link together the different modules in a context in order to invoke them as an unified library i am using the c api i am particularly wary of this nasty old bug affecting this functionality would this bug still affect me if i transferred ownership of all the modules to the jit with executionengineaddmodulewhat are the required steps once a modification on a translation unit forces the update of one of the modules do i need to dropdelete the old module object and create a new one is there a recycling policy that i have not read abouta secondary question i have about this ishow many executionengine do i need one for the whole application one per context one per module hope the scope of the question is not too overwhelming,['c++'] +269789,can i globally set the timeout of http connections i have a program that uses javaxxmlwsservice to call a remote service defined by a wsdl this program runs on the google app engine which by default sets the http connection timeout to 5 seconds1 i need to increase this timeout value since this service often takes a long time to respond but since this request is not being made with urlconnection i cannot figure out how to call urlconnectionsetreadtimeoutint2 or otherwise change the timeout is there any way to globally set the http connection timeout on the app engine and for purposes of sharing knowledge how would one go about solving this sort of problem generally1 2 int,['java'] +269795,css background position top right add a margin so i have the following mark up background 7bc145 urlimagesill people leadgenpng norepeat right topand its nearly perfect but i just want to add a bit of margin on top of the image just wondering how i could add that to above,['css'] +269800,why is a pointtovolatile pointer like volatile int p useful volatile is to tell the compiler not to optimize the reference so that every readwrite does not use the value stored in register but does a real memory access i can understand it is useful for some ordinary variable but do not understand how volatile affects a pointervolatile int p some addrint a p cpu always has to load the address then does a memory access anyway rightwhat is the difference if it has been declared as int p some addr,['c'] +269820,mysql datetime range query issue i have a quick question i am have a db an audit table with a datetime column in it ie 20120327 0 and i am building a mysql query to return a set of rows if the date is in between the two dates i am giving itso far my query looks like thisselect from util audit where dated date03152012 and dated date03312012if i just useselect from util audit where dated date03152012 it will return all my record because they were dated this weeki also tried thisselect from util audit where dated 02152012 0 and dated 03312012 0and nothing it will return zero rows when i know i have all of them dated from the 27 of this month to today am i missing something here why does it work on its own but not when i add the second datei am probably overlooking something,['mysql'] +269828,sip and rtp implementation in c are there reliable open source libraries written in c to implement sip and rtp protocols if not is it easy to implement them using boostasio,['c++'] +269829,how to write a nodejs function that waits for an event to fire before returning i have a node application that is not a web application it completes a series of asynchronous tasks before returning 1 immediately before returning the results of the program are printed to the consolehow do i make sure all the asynchronous work is completed before returning i was able to achieve something similar to this in a web application by making sure all tasks we completed before calling resend but i have not any equivalent for a final event to call before letting a script returnsee below for my broken function currently attempting to wait until callstack is empty i just thiscovered that this is a kind of nonsensical approach because node waits for processhub to complete before entering any of the asynchronous functions called in processobjwithreffunction processhubhubfilecontents var callstack var mynewobj processobjwithrefsamplepayload mynewobj callstack whilecallstacklength0 do nothing return 1note i have tried many times previously to achieve this kind of behavior with libraries like async see my related question at how can i make this call to request in nodejs synchronous so please take the answer and comments there into account before suggesting any answers based on just use asynch,['javascript'] +269838,can php and c pass data between each other i have a lot of mathematical calculations in my php script which can be quite slow at times i am wondering if it is possible to pass data from php to c do the calculations in c then pass the results back to phpps i am not very good at c,"['php', 'c++']" +269846,can i pass an array into fromcharcode i might be asking the wrong question here so i apologize if the answer is on another thread but i have looked around to no avail in a snippet why does not this workarray 7269767679documentwritestringfromcharcodearrayi am collecting key events in an array and want to be able to write them out as chars when prompted and though this worksdocumentwritestringfromcharcode7269767679i cannot seem to get it to work when i pass it along as an array i have also tried to convert the array tostring first as well arrayjoin to create a comma separated list yet nothing any ideas is there a better way to convert the values i collect in my array into chars,['javascript'] +269855,sorting 5d array in c i am trying to figure out how to sort a multidimensional data 5 dimensions in c i know that using a 5d array is a solution that fromreading others posts on so about this topic many folks find if not altogether unethical so aesthetically repugnant so as to provoke unceasing projectile vomitingso i apologize in advanceessentially i have an incoming set of data to which i must apply a series of thiscrete algorithms each algorithm has a set of variables and i need to calculate a ranking of the efficiency of each algorithm with every permutation of thevariables possible ultimately i need a list sorted by the besttoworst performing algorithm the wholecalculation is dynamic so what works best on one incoming piece of data is unlikely to be the best performer on anotherso i cannot eliminate any of the variables because they are poor performershere is how the data looksdatavalue algo lengthvar durationvar plasticityvar fungibilityvarthere are35 algorithms10 length variables230 duration vars27 plasticity vars400 fungibility varsin addition to sorting by algorithm i would like to have the flexibility to sort on any of the 5 dimensionsthis will be run on a 12 physical 24 logical core machine with 192 gig not meg of ram using vs 2010 c not ci am assuming that qsort would be the most efficient sorting option i have searched google and so extensively for how to do this to no avail there are answers for 1d arrays multidimensional arrays in php or c etc but not for cor at least i cannot find one,['c'] +269858,unique lists from a list given a list i need to return a list of lists of unique items i am looking to see if there is a more pythonic way than what i came up withdef unique listsl m for x in l mx mx if mgetx none else x return x for x in mvalues printunique lists12234567889output1 2 2 3 4 5 5 5 6 7 8 8 9,['python'] +269866,performance impact of virtual methods to accommodate unit testing and mocking it is become a common practice to declare methods and properties as virtual is there a performance impact of declaring something virtual as supposed to nonvirtual,['c#'] +269874,mysql error 1005 cannot create table errno 150 when i try create more than 1 fk i have this tablecreate table if not exists produtos id int11 not null auto increment idcatprodutos int11 not null idcategoria int11 not null idmarca int11 not null nome varchar100 not null primary key id key fk produtos 2 idcatprodutos key fk produtos 3 idmarca key fk produtos 4 idcategoria engineinnodb default charsetlatin1 row formatdynamic auto increment39 and this tablecreate table if not exists sugestoes id int11 not null auto increment idproduto int11 not null idsugestao1 int11 not null idsugestao2 int11 not null idsugestao3 int11 not null idsugestao4 int11 not null primary key id key fk sugestoes prod idproduto engineinnodb default charsetlatin1 row formatfixed auto increment9 i already have created a fk sugestoesidproduto produtosid working but i want each of the other fields also refer to the produtosid through new fkrun this command below that return mysql error 1005 cannot create table errno 150alter table infantilesugestoes add constraint fk sugestoes 2 foreign key fk sugestoes 2 idsugestao1 references produtos id on delete set null on update cascade row format fixeddoes anyone have any idea whats going on,['mysql'] +269903,choosing between filereader and inputstreamreader i have two methods to read text file in java one using filereader and other file inputstreamfilereader frnew filereaderctestqtesttxtbufferedreader brnew bufferedreaderfrstring swhilesbrreadlinenull systemoutprintlnvalue are sand other is fileinputstream fstream new fileinputstreamctestnewouttextdatainputstream in new datainputstreamfstreambufferedreader br new bufferedreadernew inputstreamreaderinstring strlinewhile strline brreadline null systemoutprintln strlinethough both give me output i just want to know which is the best way to do it,['java'] +269917,creating metro style winform in windows 7 using c is it possible to design a metro styled winform in visual studio 10 or visual studio 11 on windows 7 if so where can i find info on how to do it i have already found some links like but i do not get the windows metro stylecan anyone help me with this,['c#'] +269934,what triggers javascript code execution in case you do not know what i am talking about please read john resig how javascript timers work and is javascript guaranteed to be singlethreadedthere are several triggers that enqueue tasks in the js engines execution fifo this is not part of any standard so i am trying to find an exhausive list of those triggers i guess it all boils down to internal event handlers like script load events or timer events but i would rather ignore the engines internals and look at things from the users point of viewso far i have identifiedscript elements in the initial document including the ones added by documentwritescript elements inserted by js at runtimeevent handlers these include a wide variety of cases such as user interaction error events web worker messages or ajax callbacks windowsettimeoutwindowsetinterval only in browserdom environmentsany more any differences between js engines,['javascript'] +269942,how do i convert an integer to binary in javascript i would like to see integers positive or negative in binaryrather like this question but for javascriptprint an integer in binary format in java,['javascript'] +269949,how to create encrypted paynow button on the fly for thirdparty customers using paypal nvp api i need to create encrypted paynow paypal buttons on the fly for a websitei read all the documentation i can find on the paypal websitei understood that i need to use the bmcreatebutton buttonmanager nvp apibut i have been unable to find any information nor any reasonably simple and documented sample code about how i am supposed to call these api do i need to put my parameter in a form and post it on some kind of serverdo i need to put all the parameter on an url call this url ad use the resulthow do i authenticate to this servicei am going to create encrypted paynow button for different paypal business accountcan someone show me some vbnet or c code that actually call this bmcreatebutton nvp apiso that i can seehow to do the callhow to authenticate to the servicehow to formatuse the parameters of the api callhow to get the resultsvarious link to useful resource thanks to this answer i have been able to find some useful sample code here and there about how to call paypal api here is more usefull information about how paypal nvp api works here an interesting website that generate api call url for the bmcreatebutton api here you can find instruction for obtaining third party api credentials thanks to this answer some more useful information here about paypal api integration here you can find the current and latest version number of the paypal api update 1now i have created some code that actually do something but it give me an errorthis code actually create an encrypted paynow button using the bmcreatebutton apiit seem to works but when i click the paynow button it show all the payment parameters but also show the error there was a problem with the decryption of your secure order please contact your merchanthere is the codepublic shared sub paypaltest3web dim nvp as new dictionaryof string string dim strusername as string aso 1273063882 biz api3megatestoit dim strpassword as string 1273063582 dim strsignature as string a22sd7623rgusdudhdsfu57n7dfhfs23duyvhdf85du8s6fj6d5bfoh5 dim strnvpsandboxserver as string nvpadduser strusername nvpaddpwd strpassword nvpaddsignature strsignature dim bvcount as integer bvcount 0 nvpaddmethod bmcreatebutton nvpaddversion 850 nvpaddbuttoncode encrypted cleartext encrypted nvpaddbuttontype buynow nvpaddbuttonsubtype products optional products services bvcount bvcount 1 nvpaddl buttonvar bvcount businessd64tg758hiwj2 merchant id bvcount bvcount 1 nvpaddl buttonvar bvcount cmd sxclick dont specify the cmd parameter if specifien it will generate an error on the decription of the secure order i do not know why bvcount bvcount 1 nvpaddl buttonvar bvcount lcit bvcount bvcount 1 nvpaddl buttonvar bvcount button subtypeproducts bvcount bvcount 1 nvpaddl buttonvar bvcount item nametest product bvcount bvcount 1 nvpaddl buttonvar bvcount item number123456 bvcount bvcount 1 nvpaddl buttonvar bvcount amount1200 bvcount bvcount 1 nvpaddl buttonvar bvcount currency codeeur bvcount bvcount 1 nvpaddl buttonvar bvcount quantity1 build the parameter string dim parambuilder as new stringbuilder for each kv as keyvaluepairof string string in nvp dim st as string st kvkey httputilityurlencodekvvalue parambuilderappendst next dim param as string param parambuildertostring param paramsubstring0 paramlength 1 remove the last create web request and web response objects make sure you using the correct server sandboxlive dim wrwebrequest as httpwebrequest directcastwebrequestcreatestrnvpsandboxserver httpwebrequest wrwebrequestmethod post dim requestwriter as new streamwriterwrwebrequestgetrequeststream requestwriterwriteparam requestwriterclose get the response dim responsereader as streamreader responsereader new streamreaderwrwebrequestgetresponsegetresponsestream and read the response dim responsedata as string responsedata responsereaderreadtoend responsereaderclose urldecode the results dim result as string result httputilityurldecoderesponsedata dim formattedresult as string formattedresult request on strnvpsandboxserver vbcrlf httputilityurldecodeparamreplace vbcrlf vbcrlf vbcrlf result vbcrlf result vbcrlf vbcrlf vbcrlf show the results tracewritelineresult messageboxshowresultend subhere is the html responseform action methodpostinput typehidden namecmd value sxclickinput typehidden nameencrypted valuebegin pkcs7miihwgyjkozihvcnaqceoiihszccb68caqexgge6miibngibadcbnjcbmdelmakga1uebhmcvvmxezarbgnvbagtcknhbglmb3juawexetapbgnvbactcfnhbibkb3nlmruwewydvqqkewxqyxlqywwsieluyy4xfjaubgnvbasudxnhbmrib3hfy2vydhmxfdasbgnvbamuc3nhbmrib3hfyxbpmrwwggyjkozihvcnaqkbfg1yzubwyxlwywwuy29tageama0gcsqgsib3dqebaquabigai72cfjxbjrighu2il7lzsoxp4tbuezxk5jdgftpab9ygoqsew4geuhe7vpm33tcjyjhg7kyusn8puea6znqufwqma0i3wvbwphlefpn15xwn3sglgwp4yaxxhmxnid5hy9rqxjbqqvo9oqbapja2l5v8eieflhjpiaqnrn4xczajbgurdgmcgguamiibdayjkozihvcnaqcbmbqgccqgsib3dqmhbagpl562fjbvycb6aoyjbts5q3dcy94frnievebgwwinzlbh7yube3qwz0pqzrqogld41cyj0r4tbnqoo78upoygj7pi7lgzlbgum0iuqv9ltha6pm5m59jmouzz5nv2uvsljkrd820tyf0sjrcnae3ft18ae7vtft3og6yqcspt82clfime1ataez68tmyyiyom9qjv1n5w1k8hx7wnxrmfmk7ohcaaxgjkvqcndtutqhib2zd93x2ya7wtqkehb7xddjwhs1ji7mneqxgoxeo92edewizvhg5fjf2n1q5mimrcacom36golmiidotccawqgawibagibadanbgkqhkig9w0baqufadcbmdelmakga1uebhmcvvmxezarbgnvbagtcknhbglmb3juawexetapbgnvbactcfnhbibkb3nlmruwewydvqqkewxqyxlqywwsieluyy4xfjaubgnvbasudxnhbmrib3hfy2vydhmxfdasbgnvbamuc3nhbmrib3hfyxbpmrwwggyjkozihvcnaqkbfg1yzubwyxlwywwuy29tmb4xdta0mdqxota3mdi1nfoxdtm1mdqxota3mdi1nfowgzgxczajbgnvbaytalvtmrmweqydvqqiewpdywxpzm9ybmlhmrewdwydvqqhewhtyw4gsm9zztevmbmga1uechmmugf5ugfslcbjbmmumrywfaydvqqlfa1zyw5kym94x2nlcnrzmrqwegydvqqdfatzyw5kym94x2fwatecmbogcsqgsib3dqejaryncmvacgf5cgfslmnvbtcbnzanbgkqhkig9w0baqefaaobjqawgykcgyeat5bjv0n0qn3tibl1lejpo1jeqpajc1fdicc6t6ttbq55od4pot8xjsznh5s48ihdzh0c7eqfe1mpcc2cojqcspdqxmoro9qxsjhwanx6sb6fohhpspm7wgqyumdsnwtwt3ogr398ermbzzcol5owf3zbsprp0nltwonpmcaweaobdcb9tadbgnvhq4efgqugy4i2asqic1rp5ms81dx8nfvqdiwgcuga1udiwsbvtcbuoaugy4i2asqic1rp5ms81dx8nfvqdkhgz6kgzswgzgxczajbgnvbaytalvtmrmweqydvqqiewpdywxpzm9ybmlhmrewdwydvqqhewhtyw4gsm9zztevmbmga1uechmmugf5ugfslcbjbmmumrywfaydvqqlfa1zyw5kym94x2nlcnrzmrqwegydvqqdfatzyw5kym94x2fwatecmbogcsqgsib3dqejaryncmvacgf5cgfslmnvbyibadambgnvhrmebtadaqhma0gcsqgsib3dqebbquaa4gbafc288dygxgx2wpdwdxwficfrlg0v9gbpjzykzjq069wzrkuuwfqopd2yhppnegezmw3au2cgrdkhorbjrrcpoo3fjhhmxwkqgbqqdwdg7sl8n1qfdppjpulorcngeuy41imjzjtylbjq1b5pbbjgip0ppk48cdfmyibpdccacaqewgz4wgzgxczajbgnvbaytalvtmrmweqydvqqiewpdywxpzm9ybmlhmrewdwydvqqhewhtyw4gsm9zztevmbmga1uechmmugf5ugfslcbjbmmumrywfaydvqqlfa1zyw5kym94x2nlcnrzmrqwegydvqqdfatzyw5kym94x2fwatecmbogcsqgsib3dqejaryncmvacgf5cgfslmnvbqibadajbgurdgmcgguaof0wgayjkozihvcnaqkdmqsgcsqgsib3dqehatacbgkqhkig9w0bcquxdxcnmtiwndazmdcxmda5wjajbgkqhkig9w0bcqqxfgqul2sp4h6jn0c8fejmdz5ioejcpmwdqyjkozihvcnaqebbqaegycjmqurkhtdo2g9qbrvaxxhvrmp54jncodglambauyhalyjlk2r5kq3xgauuiaj47a0qglpoyqwddhyf0r4ffph0ocraxlh9rc8jz2cqxrt8fia7h1ohdwihjynj6eipmfzm3t0wytza6x8gnzaoj0mtkqoeojkzjl61feqend pkcs7input typeimage src usibtnbtn buynow lggif border0 namesubmit altpaypal il sistema di pagamento online pia1 facile e sicuroimg alt border0 src itiscrpixelgif width1 height1formand here is the error i get after clicking on this encrypted paynow buttonas you can see all the parameters item name price item id are correctbut i am unable to understand why i am getting this error if you want to try this code you should substitute your api userpasswordsignature the generated paynow button only works when you are logged in your paypal sandbox accountdo you have any idea about how to solve this errornote after solving this issue i will need to understand how to create encrypted button for a third paypal business account we will need to create encrypted button for paypal accounts of our customers using our api credentials customer merchant code and having our api credential configured up in our customers paypal account is not enought it say that merchant code is not valid probably i am missing somethingupdate 2it seem that i have found how to solve the aforementioned error simply remove the cmd sxclick xclick parameters if the cmd is not specified the paynow button does not seem to generate any error more testing is needed anyway i have commented the code line in the code examplenow back to businesslet us do some testing and then find the proper way to create paynow button for third party paypal accounts,"['c#', 'asp.net']" +269959,how to have only a vertical scroll bar on a div i have a table which is in a div the length of the table can vary and i use the div to enforce a heightdiv idcamlistdivtable thead thinput typecheckbox idselectallth thlocal camera listth thead tbody trtdcamera 1 data tdtr trtdtdtr trtdcamera x data tdtr tbodytabledivcsscamlistdiv height 340px float left overflow auto overflowy hiddenmy problem is when the vertical scrollbar is needed the space it occupies causes a horizontal scrollbar to appear i do not need the horizontal scrollbar and i tried to use the overflowy hidden css property to hide it but this causes both scrollbars to be hiddendoes anyone know why overflowyhidden is not working as expected or how to stop the horizontal scrollbar from being visible,"['javascript', 'html', 'css']" +269993,whats the difference between a nonunmanaged type and a managed type when i wrote the following snippet for experimenting purposes it raised the hovererror see screenshotcannot declare pointer to nonunmanaged type dynamicthe snippetdynamic pointertodynamic fieldswhile the code is clearly not allowed you cannot take the address of a managed type it raised with me the question what is a nonunmanaged type and how is it different to a managed type or is it just visual studio trying to be funny,"['c#', '.net']" +270026,g warning options for casting pair i just found that c does not give any warnings for casting from pairdouble int to pairint int which is a little surprising here is my program test paircppinclude vectorinclude utilityusing namespace stdint main stdvectorpairint int v pairdouble int p make pair38 3 vpush backp i compile it using g test typecpp wall wconversion but still no warnings are generated i am using g v461 anyone got any idea how to make g generate a warning for this or it just cannot be done,['c++'] +270031,when to clear the cache dir in android i have an application that thisplays pictures from the internet showcase for designer work i start caching my content in the internal cache directory but the app content could take about 150 mb in cache size and what android docs says you should always maintain the cache files yourself and stay within a reasonable limit of space consumed such as 1mb when the user uninstalls your application these files are removedso i took a look at the currents app galaxy nexus and the cache size for the application is 110 mb but whats weird is that applications like google currents google maps cache the content in something called usb storage data so what is this usb storage data that the previous application uses and if you implement caching in your application do you loop over all your application files in cache to get the size every time you need to insert something and then compare and clear it or do you keep caching the content until android decides its time to clean some application cache directory i am really interested to know what is the flow of managing cache in android or at least what other applications do with large content to cache,['android'] +270052,how to delete a localstorage item when the browser windowtab is closed my case localstorage with key value that should be deleted when browser is closed and not single tabplease see my code if its proper and what can be improvedcreate localstorage key value if not existiflocalstorage localstoragemypagedataarrnamedanlastnamebonny when browser closed psedocodewindowunloadfunction localstoragemypagedataarrundefined,"['javascript', 'jquery']" +270068,application failed codesign verification 19011 for a few days im being stuck at this problem i have tried to deleteclean all the keyscertification and redownload them i have tried to remove all provision profiles and revoke them and renew them but every time i am getting this problemim running the latest xcode 432warning application failed codesign verification the signature was invalid contains thisallowed entitlements or it was not signed with an iphone thistribution certificate 19011validate usersjimmylind91librarydeveloperxcodederiveddatajagharaldrigbkpyqdmptyxcntauxwsbrsqbmljibuildintermediatesarchiveintermediatesjagharaldrigintermediatebuildfilespathuninstalledproductsjagharaldrigapp cd usersjimmylind91documentsxcodejag har aldrig setenv path applicationsxcodeappcontentsdeveloperplatformsiphoneosplatformdeveloperusrbinapplicationsxcodeappcontentsdeveloperusrbinusrbinbinusrsbinsbin setenv product type comappleproducttypeapplication applicationsxcodeappcontentsdeveloperplatformsiphoneosplatformdeveloperusrbinvalidation usersjimmylind91librarydeveloperxcodederiveddatajagharaldrigbkpyqdmptyxcntauxwsbrsqbmljibuildintermediatesarchiveintermediatesjagharaldrigintermediatebuildfilespathuninstalledproductsjagharaldrigappwarning application failed codesign verification the signature was invalid contains thisallowed entitlements or it was not signed with an iphone thistribution certificate 19011 executableusersjimmylind91librarydeveloperxcodederiveddatajagharaldrigbkpyqdmptyxcntauxwsbrsqbmljibuildintermediatesarchiveintermediatesjagharaldrigintermediatebuildfilespathuninstalledproductsjagharaldrigappjagharaldrig codesign wrapper0710 using apple ca for profile evaluation usersjimmylind91librarydeveloperxcodederiveddatajagharaldrigbkpyqdmptyxcntauxwsbrsqbmljibuildintermediatesarchiveintermediatesjagharaldrigintermediatebuildfilespathuninstalledproductsjagharaldrigapp valid on thisk usersjimmylind91librarydeveloperxcodederiveddatajagharaldrigbkpyqdmptyxcntauxwsbrsqbmljibuildintermediatesarchiveintermediatesjagharaldrigintermediatebuildfilespathuninstalledproductsjagharaldrigapp satisfies its designated requirement testrequirement code failed to satisfy specified code requirements codesign wrapper0710 failed to execute codesign1 null,['iphone'] +270071,nssortdescriptor sort with number as string got a an array full of dictionary likes this order 10 name david order 30 name jake order 200 name michael when i am using nssortdescriptor like the code below it only sorts regarding to the first char so 200 is lower then 30 i can of course change the order object into a nsnumber instead of string and it would work but is there a way to sort a string as int values without changing the source objectnssortdescriptor descriptor nssortdescriptor alloc initwithkeynorder ascendingyesdepartmentlist sortusingdescriptorsnsarray arraywithobjectsdescriptornilupdatethanks to bandejapaisahere is the a working version for ios 5 xcode where compaliningnsarray sortedarraysortedarray departmentlist sortedarrayusingcomparatornscomparatorid a id b nsnumber num1 nsnumber numberwithinta objectforkeynorder intvalue nsnumber num2 nsnumber numberwithintb objectforkeynorder intvalue return num1 comparenum2departmentlist sortedarray mutablecopy,"['objective-c', 'ios']" +270108,making a table row into a link in rails i am trying to make a row in a table link to the edit page i know the links are being created because i can print them out i am close but am missing something important what do i change to make the link work properlyh1scoutsh1p button to add a new scout new scout path method get pdiv classmessageboard table tr thnameth thrankth thadvancement dateth thageth tr scoutseach do scout tr link to edit scout pathscout td scoutname td td scoutrank td td scoutadvancement td td scoutage td tr end tablediv,['ruby-on-rails'] +270109,multidimensional arrays via ajax to php ok seriously struggling here i am having some problems trying to send a multdimensional array to php via ajax heres what i have been tryingto simplify rather than copy paste a wall of code peoplearray0 name john age 28 sex male peoplearray1 name julie age 20 sex female main arrayitem x main arraysomething x main arrayanother xi want to get this to php via post i figured i may aswell just join them together as i am multidimensional anyway thus main arraypeoplearray peoplearraynow to do the ajax var data jsonstringifymain arrayvar send ajax type post cache false url theurl data datamain array i do change this main array when using the above stringifysenddonefunctionmsg consolelogmsgin php i am just doing the following right nowdata postdataprint rdatain firebug an empty stringwhen i have the var data jsonstringifymain array uncommented i get the following if i add data json decode postdata to the php i getarray basically the main array i realise does not need to be an array and so i can get that stuff across no problem but what i need to do is get the peoplearray over so that i can do some foreach etc with it in php any help would be much appreciated i am sure i am just being stupidedit the reasoning behind this is that peoplearray could have 0 or 100 entries so i just need to get it to php so i can foreach it to do the db inputs if there is a better approach i would be very grateful to hear it as i am still pretty new to thisedit thanks to nicolas answer everything is passing fine except the important part which is mainarrypeoplearray it is not appearing in the the return consolelog and i cant access it in php any solutions on this or do i have to put the foreach intelligence in the javascript and just send everything individually,"['php', 'javascript', 'jquery']" +270114,python extracting bits from a byte i am reading a binary file in python and the documentation for the file format saysflag in binarymeaning1 n n indicates that there is one data byte to follow that is to be duplicated n n 127 maximum times0 n n indicates that there are n n bytes of image data to follow 127 bytes maximum and that there are no duplicationsn 0 0 end of line field indicates the end of a line record the value of and may be either zero or one note that the end of line field is required and that it is reflected in the length of line record field mentioned abovewhen reading the file i am expecting the byte i am at to return 1 n n where the n n part should be 50i have been able to do this using the followingflag byte 7numbytes intbinbyte3 2but the numbytes calculation feels like a cheap workaroundcan i do more bit math to accomplish the calculation of numbyteshow would you approach this,['python'] +270122,optimal method for posponing onevent in my little app i receive a series of queued oneventx from the system not controlled by methe timing of those oneventx is not guaranteed the only thing guaranteed is that they are received in the order in which they were put into the queueinside oneventx i have to fire an operation o that cannot start while another process p is going onbut i cannot just thiscard this firing an operation o i must wait until that process p is complete then fire itiow i have to queue or at least postpone that firing an operation until that process p is completemy immediate idea for implementing this was that instead of firing the operation o i wouldstart a oneshot timer that would periodically check on process pwhen timer elapses if process p is not complete start the time itself againwhen timer elapses if process p is complete fire operation obut knowing the richness of android i am suspecting there is a better way of doing this already built into the systemapiif there is a better way to implement the above what would it be,['android'] +270123,using c can i make an ssl connection using server name indication sni i currently have this code that makes an ssl connection to a serverusing client new tcpclient clientconnecthostname port var callback new remotecertificatevalidationcallbackvalidateservercertificate using stream new sslstreamclientgetstream false callback streamauthenticateasclienthostname however i do not think it supports sni because the wrong certificate is being returned from the sni configured server is there anyway to make the ssl connection using snii am using net 2 willing to upgrade if necessary i am using windows 7 but would like the software to work on other platforms such as windows 2008 if possible,['c#'] +270196,timeout for threadjoin is it possible to set a timeout for a call to stdthreadjoin i want to handle the case in which the thread is taking too long to run or terminate the thread i may be doing this for multiple threads say up to 30preferably without boost but i would be interested in a boost solution if that is the best way,['c++'] +270198,hashchange firing popstate heres what i am working withcodea href onclickwindowonpopstate function alertpop return false set up windowonpopstateabra hrefsomehash2change hashadiv onclickalertlocationhrefshow locationhrefdivawhy does clicking the change hash link fire the popstate should not it only be fired if i click the change hash link then click back,['javascript'] +270208,windows 8 share target crashing with jquery i am developing an app that receive contente uri and i am testing it with ie10 sharingthe problem is that my elements span divs or buttons that have onclick event handler associated closes the sharing panel in the second click the second click in the window on any element causes the crashi have tested the code running the page as the default page of the app and everything works fine this undesired behavior occurs only on share panelafter some time of manual debugging i found the piece of code that is causing the crase the jquery lib if jquery is presente in the page it causes crash in share panelis not possible to debug this using visual studio because this crash occurs only i do not have the debugger attached with the debugger attached to it everything works finesomeone can help on this see my simple page belowdoctype htmlhtml head titletitle winjs references script srcmicrosoftwinjs06jsbasejsscript script srcmicrosoftwinjs06jsuijsscript script srcjsdefaultjs typetextjavascriptscript script srcjsjquery172js typetextjavascriptscript script var curr function test if curr currclassname cls1 curr eventsrcelement currclassname cls2 script style cls1 backgroundcolor f00 cursor pointer cls2 backgroundcolor 0094ff cursor pointer style head body h1shareh1 br div onclicktest classcls1buttondiv div onclicktest classcls1buttondiv bodyhtmlthanks,['jquery'] +270216,iterate through multiple collections in the same for loop i wonder if there is such a way to iterate thru multiple collections with the extended for each loop in javaso something likefor object element collection1 collection2 do something thanks,['java'] +270218,pattern to avoid dynamic cast i have a classclass a public virtual void func virtual void func2 and some derived classes from this one lets say bcd in 95 of the cases i want to go through all objects and call func or func2 so therefore i have them in a vector likestdvectorstdshared ptra myvecfor auto it myvecbegin it myvecend it itfunchowever in the rest 5 of the cases i want to do something different to the classes depending on their subclass and i mean totally different like calling functions that takes other parameters or not calling functions at all for some subclasses i have thought of some options to solve this none of which i really likeuse dynamic cast to analyze subclass not good too slow as i make calls very often and on limited hardwareuse a flag in each subclass like an enum is subclass b is subclass c not good as it doesnt feel ooalso put the classes in other vectors each for their specific task this doesnt feel really oo either but maybe i am wrong here likestdvectorstdshared ptrb vecfordoingspecificoperationstdvectorstdshared ptrc vecfordoinganotherspecificoperationso can someone suggest a stylepattern that achieves what i want,['c++'] +270229,how to configure setuppy to have pip install from github master rather than pushing a release to pypi and github it would be easier to have pypi use the latest github master is there are proper way to do thisi know you can list dependencies as github repos in install requires but is there a way to do this for the primary packagefor example when you use easy install to install flask it reads from multiple sources including github which is listed in the setup url sudo easy install flasksearching for flaskreading reading is listing the url in setuppy what causes easy install to also read from githubif so will it always install from github if the github version is more current than the pypi versionand does this work the same for pip,['python'] +270235,iphone developer does not match any valid nonexpired certificateprivate key pairbut i am creating and ipad app possible duplicatecode sign error the identity aiphone developera doesnat match any valid certificateprivate key pair in the default keychain why do i get this message when i have specified that i am developing for the ipad and not for the iphone is there a separate private key that i need when i look at keychain access certificates i do have a valid iphone developer certificate valid through jan 182013 so whats the problem,['iphone'] +270255,how to combine lines in two files with condition in python i need to combine lines in two files basing in the condition that in the line of one of the files is a part of the line of the second filea part of the first file123190 647357668067227 01052148685535 123190 7968527661064425 013231739754026 123190 9469642857142858 015117839559513543 123190 10959301470588237 0182783185642743 12319001 9970264355742297 048329515727315125 12319001 84613445378152 04060446341409862 12319001 697032037815126 029803063228455073 12319001 5493886554621849 020958105041136763 12319001 39937394957983194 013623056582981297 12319001 2505574229691877 007748669438398018 12319001 9716386554622 0028110643107892755 a part of the second file123190abf mutant 1 12319001abf mutant 2 12319002abf mutant 3 i need to create a file where the line consists of this all line from the first file and everything from the line of the second one except for the filename in the first columnas you can see there are more than one line in the first file cooresponding to a line in the second one i need that operation to be done with each line so the output should be like this123190 9469642857142858 015117839559513543 mutant 1 123190 10959301470588237 0182783185642743 mutant 1 12319001 9970264355742297 048329515727315125 mutant 2 12319001 84613445378152 04060446341409862 mutant 2 i have written this codeoocytes openfile with oocytes r results openospathjoinpath resultscsv r results new openospathjoinpath results with oocytescsv w for line in results for lines in oocytes if lines07 in line print line lines12 but it prints out this and nothing more thow there are 45 line in the first file123190 994952380952381 03011778623990699 mutant 1 123190 994952380952381 03011778623990699 mutant 2 123190 994952380952381 03011778623990699 mutant 3 what is wrong with the codeor it should be done somehow completely differently,['python'] +270263,java generic string to parser is there a straightforward way to implement a method with the following signature at minimum the implementation would need to handle primitive types eg double and integer nonprimitive types would be a nice bonusattempt to instantiate an object of type t from the given input stringreturn a default value if parsing fails static t t fromstringstring input t defaultvalueimplementation would be trivial for objects that implemented a fromstring interface or equivalent but i have not found any such thing i also have not found a functional implementation that uses reflection,['java'] +270276,shrinktofit div and paragraph based on image the code below is a simplified version of my website on my site the image width varies from page to page and the text is around 100 words that means the paragraph stretches the div to be wider than the image using only css is it possible to shrink the div and the paragraph to the width of the imagejsfiddle hereexample of what i am trying to describe here top is what i am getting bottom is what i wanthtmldiv img srcimagejpg plorem ipsum dolor sit ametpdivcssdiv thisplay inlineblock,"['html', 'css']" +270288,best practice extending or overriding an android library project class were using an android library project to share core classes and resources across different builds targets of our android application the android projects for each specific target reference the core library project behind the scenes eclipse creates and references a jar from the referenced library projectoverriding resources such as images and xml layouts is easy resource files placed in the target project such as the app icon or an xml layout automatically override the core librarys resources with the same name when the app is built however sometimes a class needs to be overridden to enable targetspecific behavior for example the amazon target preferences screen cannot contain a link to the google play app page requiring a change in the amazon projects preferencesxml and preferences activity classthe goal is to reduce the amount of duplicate code among target projects while removing as much targetspecific code from the core library as possible weve come up with a couple of approaches to implement logic specific to different targetswrite the targetspecific functions within core library classes and use ifswitch blocks to select behavior based on product sku this approach is not very modular and bloats the core library codebaseextend the particular core class in a target project and override the base core class functions as needed then keep a reference to the baseclass object in the core library and instantiate it with an extended class object from android library project how to overwrite a classare there other strategies to override or extend an android library project class what are some of the best practices for sharing and extending common classes among android app targets,"['java', 'android']" +270308,highlighting the clicked row of a striped html table heres an example of my problem on jsfiddlei have a table with striped rows imposed by using trnthchildodd in the css as is done in twitter bootstrap for the tablestriped class i want to highlight the most recent clicked row of that table i do that with the following javascriptmytable tbody trliveclick functionevent clicked tr this clicked trparentchildreneachfunction thisremoveclasshighlight clicked traddclasshighlightthat code works fine in a table without striped rows but with striped rows the background color of the highlight class would not override the background color of the tablestriped class why is that and how can i make it work,"['javascript', 'css']" +270320,styling rails button link helpers with twitter bootstrap i am using rails helpers to generate buttons and i am trying to style the buttons with twitter bootstrap styles for buttons i have added classes with the html option the page is not breaking but the styles are not showing up button tosign up new user registration path html class btnbtnlargebtnprimary button to sign up user omniauth authorize pathfacebook html class btnbtnlargebtnprimary this is page source for the facebook buttonform actionuserssign up classbutton to methodpostdivinput htmlclassgtquotbtnbtnlargebtnprimaryquot typesubmit valuesign up input nameauthenticity token typehidden valueqivzqd9brv8tmspmvckaujhc68nm3ntyqcxvrhfa4pe divformform actionusersauthfacebook classbutton to methodpostdivinput htmlclassgtquotbtnbtnlargebtnprimaryquot typesubmit valuesign up input nameauthenticity token typehidden valueqivzqd9brv8tmspmvckaujhc68nm3ntyqcxvrhfa4pe divformany idea what i am doing wrong,['ruby-on-rails'] +270335,a const field of a reference type other than string can only be initialized with null error i am trying to create a 2d array to store some values that do not change like thisconst int hiveindices new int 200362250370213410 400330 380282 437 295 325 405 379413 343453 450382510395468430 585330 645340 603375but while compiling i get this errorhiveindices is of type int a const field of a reference type other than string can only be initialized with nullif i change const to static it compiles i do not understand how adding the const quantifier should induce this behavior,"['c#', '.net']" +270342,tab widget have always in capital alphabets in android 40 in android 40 i put tab bar with two widget in code i write in small alphabatesnew but in application it should always thisplay new how to write small alphabates on tab in android 40,"['java', 'android']" +270344,programmatically find maximum static array size in c i am curious whether it is possible to determine the maximum size that an array can have in c include iostream using namespace std define max 20 int main long arraymax cout message endl return 0 this compiles just fine but then segfaults as soon as i run it even though array is not actually referenced i know it is the array size too because if i change it to 10 it runs just fineso is there some define somewhere or some way of having define max max allowed array size for my machine defined somewhere for mei do not actually need this for anything this question is for curiositys sake,['c++'] +270378,filter datatablesnet without included filterbox input i want to use the filter function of datatables but do not want to use their search box with itin their docs under bfilter it saysnote that if you wish to use filtering in datatables this must remain true to remove the default filtering input box and retain filtering abilities please useafter which the sentence is left incompletei triedvar otable sortabledatatable bpaginatefalse binfofalse bfilter true thisplays search box setting false removes filter ability all togetheraccumulateclickfunction otablefnfilteraccumulate,['jquery'] +270381,hibernate error querysyntaxexception users is not mapped from users i am trying to get a list of all the users from users table and i get the following errororghibernatehqlinternalastquerysyntaxexception users is not mapped from usersorghibernatehqlinternalastutilsessionfactoryhelperrequireclasspersistersessionfactoryhelperjava180orghibernatehqlinternalasttreefromelementfactoryaddfromelementfromelementfactoryjava110orghibernatehqlinternalasttreefromclauseaddfromelementfromclausejava93this is the code i wrote to addget userspublic listuser getusers session session hibernateutilgetsessionfactorygetcurrentsession sessionbegintransaction listuser result listuser sessioncreatequeryfrom userslist sessiongettransactioncommit return resultpublic void adduseruser user session session hibernateutilgetsessionfactorygetcurrentsession sessionbegintransaction sessionsaveuser sessiongettransactioncommitpublic void adduserlistuser users session session hibernateutilgetsessionfactorygetcurrentsession sessionbegintransaction for user user users sessionsaveuser sessiongettransactioncommitadding users works but when i use the getusers function i get these errorthis is my hibernate config filehibernateconfigurationsessionfactory property nameconnectionurljdbcmysqllocalhost3306testproperty property nameconnectionusernamerootproperty property nameconnectionpasswordrootproperty property nameconnectiondriver classcommysqljdbcdriverproperty property namehibernatedefault schematestproperty property namedialectorghibernatedialectmysql5dialectproperty property nameshow sqltrueproperty property nameformat sqltrueproperty property namehbm2ddlautocreatedropproperty jdbc connection pool use the builtin property nameconnectionpool size1property property namecurrent session context classthreadproperty mapping files will go here mapping classmodelcompany mapping classmodelconference mapping classmodelconferencesparticipants mapping classmodelconferenceparticipantstatus mapping classmodelconferencesusers mapping classmodellocation mapping classmodeluser sessionfactoryand this is my user classentitytable name users public class user implements serializable private long userid private int pasportid private company company private string name private string email private string phone1 private string phone2 private string password may be nullempty will be kept hashed private boolean isadmin private date lastlogin user not public on purpose public userint countryid company company string name string email string phone1 string phone2 string password boolean isadmin thispasportid countryid thiscompany company thisname name thisemail email thisphone1 phone1 thisphone2 phone2 thispassword password thisisadmin isadmin id generatedvaluegeneratorincrement genericgeneratornameincrement strategy increment public long getuserid return userid public void setuseridlong userid thisuserid userid any idea why i get this error,['java'] +270431,get posted value in c aspnet i have a dynamic form that allow to add many fields dynamicallyi know how to get the value of single field in aspnet using requestformmyfieldbut here i have more than field and i dont know the count of these fields since these are dynamicthe fields name is ordersexforminput typetext nameorders valueorder1 input typetext nameorders valueorder2 input typetext nameorders valueorder3 formin phpi get the values as an array by accessing postordersexorders postordersforeachorders as order execute how can i do this in c,"['c#', 'asp.net']" +270439,if then join else other join i am trying to figure out a query which joins several tables cca 8 at one point i need to join one of two tables so lets call the result until this point a now i want to join b or c when i use b i get smaller result or no result if there is no result after the join i need to join c insteadto summarize intersection of ac gives bigger result and i only want to join c if intersection of ab is emptywhat would be a smooth way to say this in mysql,"['mysql', 'sql']" +270477,detect user scroll down or scroll up in jquery possible duplicatedifferentiate between scroll updown in jquery is it possible to detect if user scroll down or scroll up example windowscrollfunction if user scroll down do action if user scroll up do another actionthanks,['jquery'] +270486,is it possible to add somewhere a beforeeach hook so that all spec file can run it i am using ruby on rails 322 and rspecrails281 in order to make my spec files dry do not repeat yourself and to seed the test database i would like to run a beforeeach hook for all those spec files that is in all my spec files i have the following codedescribe test description do beforeeach do load railsrootdbseedsrb end endis it possible to add somewhere that beforeeach hook so that all spec files can run it what do you advice,"['ruby-on-rails', 'ruby']" +270508,enabling php pdo odbc extension on a mac osx i am trying to get the pdo odbc extension for php enabled on my mac which is running php 53 here is what i did to try to get it to worki installed unixodbc with brew brew install unixodbcdownloaded the source for php 538 in the terminal i navigated to the pdo odbc folder then did the following phpize configure withpdoodbcunixodbc makethere was an error userstodownloadsphp538extpdo odbcpdo odbcc43 error azend mod enda undeclared here not in a functionuserstodownloadsphp538extpdo odbcpdo odbcc in function azm startup pdo odbcauserstodownloadsphp538extpdo odbcpdo odbcc135 warning cast to pointer from integer of different sizebased on some blogs i replaced zend mod end with nullnull null and ran make again this time it compliedthen i ran sudo make installand that installed the extension in the right place i modifed phpini to enable it and it shows up in phpinfoso far so good but when i start running simple tests i get errors about every other tryphp200480x7f796f1960 malloc mmapsize2977160837258543104 failed error code12 error cannot allocate region set a breakpoint in malloc error break to debugterminate called throwing an exceptionabort trap 6this was thrown when i tried to execute this codephp dsn odbcdriverfilemaker odbcserverlocalhostdatabasecaldav pdo new pdodsn odbc odbc sql select from users where id 2 r pdoquerysql print rrfetchpdofetch assoc sql select from users where id stmt pdopreparesql stmtexecutearray2 print rstmtfetchpdofetch assocthis line causes the exceptionstmtexecutearray2does anyone have any experience getting pdo odbc to work on the mac i would really like to get this extension working suggestions,['php'] +270528,javascript get word before cursor okay i have been looking all over the web to find a solution but i could not find one is there a way to get the word before the caret position in an editable div so a bit likethis is some demo textsthis should return the word some i do not know if this is possible i would be glad for any help thanks,"['javascript', 'html']" +270538,is there a regex delete in ruby all of my string deletes with regex use gsub is there a shorter waystringgsuba,['ruby'] +270539,how do i check honeycomb or higher is running and accordingly call a method for that version for android versions 30 and higher i want to call a certain methodis there a way to check if a certain method is available in the running android versionto be more precise my minsdk is 7 android 21 targetsdk is 8 android 22 and i need to testif honeycomb android 30 or higher is runningdepending on that how can i call that honeycomb methodthe second part of the question arises because simply calling that honeycomb method will not compile as i am building against 22,['android'] +270565,consuming a web service using post instead of the going the usual wsdl route this is how i have currently managed to consume a particular microsoft web service notice that it is located on an https server and that it requires a username a password and a cer file to be installed in the operating systems root certificate authoritieswshttpbinding binding new wshttpbindingbindingsecuritymode securitymodetransportwithmessagecredentialbindingsecuritymessageclientcredentialtype messagecredentialtypeusernamebindingsecuritymessagenegotiateservicecredential truebindingsecuritymessagealgorithmsuite systemservicemodelsecuritysecurityalgorithmsuitedefaultbindingsecuritymessageestablishsecuritycontext trueendpointaddress endpoint new endpointaddressgreatclient was created for me automatically by runningsvcutilexe greatclient client new greatclientbinding endpointusername and password for the authentication notice that i have also installedthe required cer certificate into the systems root certificate authoritiesclientclientcredentialsusernameusername usernameclientclientcredentialsusernamepassword passwordnow i can start using the client as i wishmy question is this how can i obtain all the information necessary so that i can consume the web service with a direct post to and how do i actually perform the post with c i only want to use post where i can supply raw xml data using post directly to and get back the result as raw xml data the question is what is that raw xml data and how exactly should i send it using postthe purpose of this question the reason i ask is that i wish to consume this service using something other than c and net such as ruby or cocoa on mac os x i have no way of knowing how on earth to do that since i do not have any easytouse svcutilexe on other platforms to generate the required code for me this is why i figured that just being able to consume the service using regular post would allow me to more easily to consume the service on other platforms,['c#'] +270580,bootstrapping module specific stylesscripts in zend framework i am trying to load specific stylesscript resources for a specific module within my applicationhere is my application structure application configs controllers forms layouts models modules admin configs controllers models views bootstrapphp views bootstrapphpthe problem i am having is the styles and scripts i am loading through headlink and headscript in applicationmodulesadminbootstrapphp are also being loaded in my controlleractions that are not in the admin module here are my bootstrapphpsapplicationbootstrapphpprotected function initdoctype this loggerinfobootstrap method init the view thisbootstrapview view thisgetresourceview viewdoctypexhtml1 strict set title and separator viewheadtitlesunny rose photography setseparator load global stylesheets viewheadlinkappendstylesheetstylesstyles maincss headlinkappendstylesheetscriptsjqueryui1817themesbasejqueryuicss load scripts viewheadscriptprependfilescriptsjquery171jquery171js headscriptappendfilescriptsjqueryui1817uiminifiedjqueryuiminjs headscriptappendfilescriptsgalleryjs headscriptappendfilescriptsscripts mainjsapplicationmodulesadminbootstrapphp protected function initdoctype thisbootstrapview view thisgetresourceview viewheadlinkappendstylesheetstylesadminstyles admincss viewheadscriptappendfilescriptsadminscripts adminjsi can see how or maybe why it is doing it because i am getting the view from the main bootsrap my question is how does one load module specific stylesheets andor script filesi apologize if this is a duplicate question i searched for various wordings of the title of the question and i did not find anything conclusivethanksken,"['php', 'javascript', 'css']" +270632,css backgroundrepeat x and y is it possible to use with small picture for the background div to repeat x and y togethersee examplethanks,"['html', 'css']" +270637,is an array argument passed to a function not a constant pointer consider the codevoid foochar a a works fine gets compiled now consider thisvoid foo char a50 a compiler error i heard an array is equivalent to a constant pointer and cannot be incremented as it is not a lvaluethen why does first code gets compiled is it so because array arguments to functions are passed as a pointer ie t is converted to t for passingso fooa passes a as a pointerbut is it not back converted to t again because is declared asvoid foochar a,"['c++', 'c']" +270642,sound not playing with avaudioplayer i have searched and i believe my problem is quite unique i am aware of the simulator 51 bug when using avaudioplayer which is not my problem i am running on a ios 51 deviceheres my header fileimport uikituikithimport foundationfoundationhimport avfoundationavaudioplayerhibactionpushbellendand my implementation fileimport bellviewcontrollerhinterface bellviewcontroller endimplementation bellviewcontrolleribactionpushbell nsstring soundpath nsbundle mainbundle pathforresourcebell1 oftypecaf nsurl soundurl nsurl fileurlwithpathsoundpath nserror error avaudioplayer theaudio avaudioplayer alloc initwithcontentsofurlsoundurl errorerror theaudio setdelegateself theaudio setnumberofloops0 theaudio playendand i have a button in my xib that plays the fileto make sure i referenced my audio file correctly i deliberately type a wrong file name and indeed i got an exception to make sure the file is playable i mailed it to myself and played it on the devicewhen i tap the button i hear nothing there are no errors i do not know what is wrongmore informationiphone 4 with ios 51xcode 432audio is about 700kbps converted to caf format using afconvert from a big wav file,"['iphone', 'ios']" +270682,how to thisplay login screen only one time i am creating a project where i have a login screen which is used for user to login into theapplication this login screen should only be visible the first time so the user can fill it and log in but when user opens the application at the second time the application must show mainactivity how to use shared preference i do not understand how to do this,['android'] +270683,what does objectcall mean function bb graphics graphicscontext objectcallthis thisbbdevicenull thisbbmatrixsp0 thisbbix10 thisbbiy0 thisbbjx0 thisbbjy10 thisbbtx0 thisbbty0 thisbbtformed0 thisbbmatdirty0 thisbbcolor r0 thisbbcolor g0 thisbbcolor b0 thisbbalpha0 thisblend0 thisbbscissor x0 thisbbscissor y0 thisbbscissor width0 thisbbscissor height0 thisbbmatrixstacknew number array192what does objectcallthis mean,['javascript'] +270699,try catch in finally section is it considered bad programming to write a try and catch within a finally clausei am having in my main method a fileinputstream which i want to close i want to place the close in the finally so it will close no matter what i do not want to add a throws declaration to the main method as it is the main method p finally try commandfileclose catch ioexception e throwexceptione is it okthanks,['java'] +270703,is it possible to write a selfdestructive program in c is it possible to write a program in c that upon execution deletes itself the binary and then terminates successfully if so whats the easiest way of doing this,['c'] +270765,best way to do columns in htmlcss i am looking for a way to thisplay 3 columns of content i have found a way to thisplay wraparound columns but i do not want that for this page i am looking for a way to saycolumn content column3 times and have 3 columns thisplayed beside each other the best example i have offhand is the verge what is the best way to do this,"['html', 'css']" +270780,best strategy for dealing with optional dependencies i am currently in the process of removing the spring dependency from flyway in the future though other types of dependencies might be needed to support a subset of users such as jboss vfs supportwhich is the best way to support optional dependencies optionaltrue in maven pomqualities of the solution would beease of use for endusers minimum work required to use functionality if dependency is presentease of use for developers code dealing with optional dependency should be as readable and as straightforward as possibleno unnecessary required dependencies if some enduser do not need this functionality no need to pull in the dependency,['java'] +270803,how to thisable afnetworking cache is it possible to thisable all the cache features from afnetworkingi am building my own custom cache system and do not want this to take up thisk space toothanksashley,['ios'] +270805,what contenttransferencoding should i use when sending a php mail containing a long httplink i have got a script that sends emails that looks kinda like thisheaders from headers replyto headers mimeversion 10rnheaders contenttype textplain charsetutf8rnheaders contenttransferencoding 8bitorgsubject a subject with some swethish characters like a a and anewsubjectutf8bbase64 encodeorgsubjectbody a lot of textsome more texta long urlhash23jh4lk2j3h4lkjh674598xzxlk2j34hanotherhashh2k3j4h23kh42kj34h2lk3it is tested thoroughly but some users i think outlook users get a url looking like thishash3d3d23jh4lk2j3h4lkjh674598xzxlk2j34hanotherhash3dh2k3j4h23kh42kj34h2lk3the equal signs is now followed by 3d which makes the url useless in my case i guess this has something to do with the contenttransferencoding or perhaps the contenttype do i need to encode the body message to base64 or somethingupdatejust found this forum post so i removed the contenttransferencoding and it seems to work fine but on the other hand i could never reproduce the error where the url contained the 3d text so i cannot be certain that this will work does anyone know if removing the contenttransferencoding would solve my problem,['php'] +270839,is there something similar to nhibernate mapping by code for hibernate in nhibernate we have fluent nhibernate and now the builtin mapping by code feature in nhibernate 32 both allow you to programmatically construct the mappings for your domain and we could either write some conventions to map all the domain or we could write individual classes for each corresponding domain objectanything similar for hibernate,"['c#', 'java']" +270862,whats the advantage of a java enum versus a class with public static final fields i am very familiar with c but starting to work more in java i expected to learn that enums in java were basically equivalent to those in c but apparently this is not the case initially i was excited to learn that java enums could contain multiple pieces of data which seems very advantageous however since then i have found a lot of features missing that are trivial in c such as the ability to easily assign an enum element a certain value and consequently the ability to convert an integer to an enum without a decent amount of effort ie convert integer value to matching java enumso my question is this is there any benefit to java enums over a class with a bunch of public static final fields or does it just provide more compact syntaxedit let me be more clear what is the benefit of java enums over a class with a bunch of public static final fields of the same type for example in the planets example at the first link what is the advantage of an enum over a class with these public constantspublic static final planet mercury new planet3303e23 24397e6public static final planet venus new planet4869e24 60518e6public static final planet earth new planet5976e24 637814e6public static final planet mars new planet6421e23 33972e6public static final planet jupiter new planet19e27 71492e7public static final planet saturn new planet5688e26 60268e7public static final planet uranus new planet8686e25 259e7public static final planet neptune new planet1024e26 24746e7as far as i can tell casablancas answer is the only one that satisfies this,['java'] +270875,calling a method inside a linq query i want to insert into my table a column named s that will get some string value based on a value it gets from a table columnfor example for each id az i want to gets it is string value stored in another table the string value is returned from another method that gets it through a linq queryis it possible to call a method from linqshould i do everything in the same querythis is the structure of the information i need to getaz is the id in the first square in table 1 from this id i get another id in table 2 and from that i can get my string value that i need to thisplay under column svar q from a in va join b in vb on ai equals bj where ak a ah 0 select new t ai s somemethodaztostring return qthe line s somemethodaztostring causing the following error unable to cast object of type systemdatalinqsqlclientsqlcolumn to type systemdatalinqsqlclientsqlmethodcall,['c#'] +270881,how to chain where query in rails 3 active record i need to add conditions depending on params datausers userwhereid paramsid unless paramsidnilusers userwhereemail paramsemail unless paramsemailnilusers userlimit10but it does not work for some reasonthanks,"['ruby-on-rails', 'ruby']" +270928,aligning a button to the center i have a simple submit button i am wanting to align it to the center here is my codeinput typesubmit namebtnsubmit valuesubmit onclicksubmit aligncenterhowever it does not work what is the besteasiest way to do thisthanks,"['html', 'css']" +270949,onclick on option tag not working on ie and chrome i am using onclick event in option tag for select box select option onclickcheckoneoption option onclickchecktwooption option onclickcheckthreeoptionselectonclick event is not working on ie and chrome but it is working fine in firefoxhere i do not want to use onchange event on select tag bcz it will not trigger an event if user selects same option againegsay first time user selects one dropdown i will open a popup after processing some stuff user closes the popupsuppose if user wants to select same one dropdown it will not trigger any eventthis can be solved using onclick event on option tag but its not working on ie and chrome is there any work around for this,['html'] +270979,how can i create multistyled cell with epplus library for excel i use epplus for excel file generationi mean i need to convert html text bold italic font colornamesize parameters to excel cell i suppose it needs to create multistyled cell likecell text is hellostyle i want ishe boldll italico red colored fontor more complexhello boldll italic also boldo red colored also boldi know about ms openxml library it allows me do what i need this is good but bit more complex library for implementationthanks,['c#'] +270980,what is the correct way to clear sensitive data from memory in ios i want to clear sensitive data from memory in my ios appin windows i used to use securezeromemory now in ios i use plain old memset but i am a little worried the compiler might optimize itcode snippet nsdata somesensitivedata memsetvoid somesensitivedatabytes 0 somesensitivedatalengthany help will be appreciated,['ios'] +271005,crossplatform c use the native string encoding or standarthise across platforms we are specifically eyeing windows and linux development and have come up with two differing approaches that both seem to have their merits the natural unicode string type in windows is utf16 and utf8 in linux we cannot decide whether the best approachstandarthise on one of the two in all our application logic and persistent data and make the other platforms do the appropriate conversionsuse the natural format for the os for application logic and thus making calls into the os and convert only at the point of ipc and persistenceto me they seem like they are both about as good as each other,['c++'] +271056,android layout placeholder for dynamically added view in my android activity i need to add a single view dynamically at runtime at a specific position in a layout the view to be added is determined at runtime for example may layout may look something like thislinearlayout textview dynamic item to be added here textview linearlayoutwhat is the best way to achieve thisone solution is to use layoutaddviewview index but i would prefer not to hardcode the indexanother solution is to use a framelayout as a placeholder and place may dynamic view inside the framelayout for examplelinearlayout textview framelayout androidididplaceholder textview linearlayoutthenfindviewbyidridplaceholderaddviewviewhowever this adds an unnecessary view in the hierarchywhat would be the recommended way to do this,['android'] +271065,type parameter with multiple bounds this code compilesimport javaioserializableimport javautilarraysclass testt extends arrays serializable but if i replace the last line withclass testt extends serializable arrays i get interface expected here why,['java'] +271069,make iframe automatically adjust height according to the contents without using scrollbar for exampleiframe namestack src width740 frameborder0 scrollingno idiframe iframei want it to be able to adjust its height according to the contents inside it without using scroll,['html'] +271124,what architectural patterns should i use for my ria i am building a web application that interacts heavily with the dom and need direction in making my code scalable and maintainablethe application overview upon interaction i have toolbars and overlays that guide the user to edit the page i then send back the edited page to the serverso far i have successfully built what i wanted but it is jquery all tied together and i need help on how to rewrite my code to make it scalable and maintainableresearch so farrequirejs i have looked at requirejs and thought this was a great starting point and got it all workingjquery cannot get away from this awesome librarynicholas zakas presentation on scalable javascript application architecture awesome idea but how do i implement this i am fairly new to advanced javascripti will also need some kind of event pooling to manage all these events if i use jquerys builtin event pooling bind trigger will this not force me away from zakas idea that only my application core should have access to my jquery librarywhat type of framework should i be looking at to solve my problem,['javascript'] +271129,default parameters and reflection if parameterinfoisoptional then is defaultvalue always reliable i am looking at how parameterinfoisoptional is defined i am adding default parameter support to an internal ioc framework and it seems to me that when true there is no guarantee that parameterinfodefaultvalue or indeed parameterinforawdefaultvalue are actually the default values that are to be appliedif you look at the msdn example given for isoptional it seems possible in il to define a parameter that is optional but for which no default is supplied given that the parameterattributeshasdefault must be explicitly supplied ie potentially leading to a situation that a parameter type is say int32 parameterinfoisoptional is true but parameterinfodefaultvalue is nullmy language is c therefore i can work on what that compiler will do based on that i can have a simple test as follows parameter here is a parameterinfo instance and the method is meant to return an instance to be used as the runtime argument for the parameterifno config value ifparameterisoptional throw new invalidoperationexception it is optional so read the default return parameterdefaultvalueelse return current method for getting valuebut i am thinking that some languages and i want to get this right at the illevel rather than just based on what one particular compiler does can place the onus on the caller to determine the default value to be used if so a defaultparameterparametertype would need to be in orderthis is where it gets a little more interesting because defaultvalue is apparently dbnullvalue according to the documentation for rawvalue if there is no default which is no good if the parameter is of type object and isoptionaltruehaving done a bit more digging i am hopeful that the reliable way to solve this is to physically read the parameterinfoattributes member reading the bitflags individually first to check for parameterattributesoptional and then check for parameterattributesdefault only if both are present then reading parameterinfodefaultvalue will be correcti am going to start coding and writing tests around this but i am asking in the hope that there is someone with more il knowledge that can confirm my suspicions and hopefully confirm that thisll be correct for any ilbased language thus avoiding the need to mock up loads of libraries in different languages,['.net'] +271136,mutually selfreferencing type parameters compiling under jdk6 but not 7 the following code compiles using jdk6 i tried 160 24class xya extends xya b b extends xyb a but compiling under jdk7 eg 170 i get this errorxyjava1 error type argument b is not within bounds of typevariable aclass xya extends xya b b extends xyb a where ba are typevariables b extends xyba declared in class xy a extends xyab declared in class xy1 errorcan anyone point as to whether this was an intentional change to javas generics,['java'] +271137,memory considerations for longrunning php scripts i want to write a worker for beanstalkd in php using a zend framework 2 controller it starts via the cli and will run forever asking for jobs from beanstalkd like this examplein simple pseudolike codewhile true data beanstalkreserve class dataclass params dataparams job new classparams jobthe job has here an invoke method of course however some things in these jobs might be running for a long time some might run with a considerable amount of memory some might have injected the beanstalk object to start new jobs themselves or have a zenddilocator instance to pull objects from the dici am worried about this setup for production environments on the long term as perhaps circular references might occur and at this moment i do not explicitly do any garbage collection while this action might run for weeksmonthsyears in beanstalk reserve is a blocking call and if no job is available this worker will wait until it gets any response back from beanstalkmy question how will php handle this on the long term and should i take any special precaution to keep this from blockingthis i did consider and might be helpful but please correct if i am wrong and add more if possibleuse gc enable before starting the loopuse gc collect cycles in every iterationunset job in every iterationexplicitly unset references in destruct from a jobnb update from herei did run some tests with arbitrary jobs the jobs i included were simple just set a value longarray create an array of 10 values producer let the loop inject pheanstalk and add three simplejobs to the queue so there is now a reference from job to beanstalk locatoraware where a zenddilocator is given and all job types are instantiated though not invoked i added 10 jobs to the queue then i reserved all jobs in a queueresults for simplejob memory consumption per 10 jobs with memory get usage0 5639210 54883220 107446430 153865640 212572850 259811260 305411270 351011280 422825690 471702410 5173024picking a random job measuring the same as above thistributionproducer int2431longarray int2588locatoraware int2526simple int2456memory0 6616410 81005620 156945230 225803640 308303250 379125660 448002870 516388480 610781290 682432010 7518020the execution code from above is updated to thisbasememory memory get usagegc enablefor i 0 i 10 i data bheanstalkreserve class dataclass params dataparams job new classparams job job null unsetjob if i 10 0 gc collect cycles echo sprintf 8d i memory get usage basememory br as everybody notices the memory consumption is in php not leveraged and kept to a minimum but increases over time,['php'] +271167,python argument parser list of list or tuple of tuples i am trying to use argument parser to parse a 3d coordinate so i can use cord 123 246 369and get 123246369my attempt isimport argparseparser argparseargumentparserparseradd argumentcord helpcoordinate destcord typetuple nargs3args parserparse argscord123246369varsargs cord 1 2 3 2 4 6 3 6 9what would the replacement of the comma be,['python'] +271180,how to calculate the area of an svg path c if anyone can help with calculating the area of an svg path i would be very gratefuli have a function to get the total length which works really welli have seen a javascript method that converts the path in to a polygon path to polygonxhtmlconverting this to c would be a good route as i have a function that gets the area of a polygon to a sufficient accuracyregardsif there is any doubt as to whats being asked hereif you know anything about the svg file format youll know that svg path shapes are defined by a bunch of coordinates like thisdm19530364357 c6576684119155141005725154 c3689192982785413204273090549 c0545126552361918749273090549 c184496513502184011008225087 c169748135713803114829451 c279715313809439638097812 c0498345884955384s95533417955384c03416101262838077812c18958456263193613595219530364357 zc and c define bezier curveswould have posted the imagewhat i am asking is how to calculate the area for such a shape using the coordinatescurve pointsthe solution using ironpython and the inkscape function works really well,['c#'] +271192,razor and interface inheritance in aspnet mvc3 why cannot this property be found i have an odd problem with one of my razor views in an aspnet mvc3 application i am getting an error telling me that a property cannot be found when the property does seem to exist when i write out its value to the debugger consolemy view takes as its model a class called formeditviewmodel formeditviewmodel has a property of type iform an interface that inherits from another interface iformobject iformobject defines a property name so anything implementing iform must implement a property called name the concrete type form implements interface iform and defines a name property as requiredwhen i run the code and inspect the formeditviewmodel object that is passed to the view i can see that it has a property form of type iform and this form object has a name property if i insert the following line into my controller to write out the value of formeditviewmodelname just before it is passed to the view the output window shows the correct namedebugwritelinename vmformnameyet when i run the view i get an error saying that the property mycompanymyapplicationdomainformsiformname could not be found why can razor not find the name property when c code in the controller evidently canmy view goes like this the line that throws the exception is htmllabelformodel modelformname form titleusing mycompanymyapplicationviewmodelsmodel formeditviewmodel viewbagtitle edit formscript srcurlcontentscriptsjqueryvalidateminjs typetextjavascriptscriptscript srcurlcontentscriptsjqueryvalidateunobtrusiveminjs typetextjavascriptscriptdiv classmyapplicationcontainer using htmlbeginformupdateform zooform div classformheader htmlvalidationsummarytrue htmlhiddenid modelformzooformid div ideditformtitlediv div classformfieldcontainer htmllabelform id htmltextboxform mformzooformid new thisabled true div div classformfieldcontainer htmllabelformodel modelformname form title htmleditorformodel modelformname htmlvalidationmessageformodel modelformname div heres the view modelusing systemusing systemcollectionsgenericusing systemlinqusing systemwebusing mycompanymyapplicationdomainformsusing mycompanyappwebviewmodelsnamespace mycompanymyapplicationviewmodels public class formeditviewmodel viewmodelbase public iform form get set public int id get return formzooformid public ienumerabletype types get set public dictionarystring string friendlynamesfortypes get set public dictionarystring string friendlynamesforproperties get set public ienumerablestring propertiesforuseinforms get set public objectbrowsertreeviewmodel objectbrowsertreeviewmodel get set the form object is really long so i would not paste the whole thing in here it is declared like thispublic class form formobject iformthe form object does not redefine the name property but inherits it from the formobject class formobject starts like thispublic abstract class formobject iformobjecthere is the interface iform as you can see it does not declare a name member but expects to inherit that from iformobjectusing systemnamespace mycompanymyapplicationdomainforms public interface iform iformobject bool containsrequiredfields mycompanymyapplicationdomainformsfactoriesiformfieldfactory formfieldfactory get mycompanymyapplicationdomainformsfactoriesiformpagefactory formpagefactory get string friendlyname get set systemcollectionsgenericlistiformfield getallfields systemcollectionsgenericienumerabledomainobjectplaceholder getobjectplaceholders systemcollectionsgenericienumerableiformfield getrequiredfields systemcollectionsgenericienumerablemycompanymyapplicationmodelsformsformobjectplaceholder getrequiredobjectplaceholders systemcollectionsgenericlistiformsection getsectionswithmultipliableoption mycompanymyapplicationbllihighlevelformutilities highlevelformutilities get int masterid get set domainobjectplaceholder masterobjectplaceholder get set mycompanymyapplicationdomainformsadaptersiobjectplaceholderadapter objectplaceholderadapter get mycompanymyapplicationdomainformsadaptersiobjectplaceholderrelationshipadapter objectplaceholderrelationshipadapter get systemcollectionsgenericlistiformpage pages get set mycompanymyapplicationrepositoryiapprepository apprepo get set int zooformid get mycompanymyapplicationbllipocoutils pocoutils get void removesectionwithoutchangingdatabaseint sectionid int topicid get set domainobjectplaceholder topicobjectplaceholder get set systemcollectionsgenericienumerablefluentvalidationresultsvalidationresult validationresults get set and here is the interface iformobjectusing systemusing systemcollectionsgenericusing systemlinqusing systemtextnamespace mycompanymyapplicationdomainforms public interface iformobject string name get string longname get guid uniqueid get string prefix get string idpath get set string idpathwithprefix get the question is why does the razor view give me the following exception when i run it since i would have expected iform to inherit its name property from iformobjectserver error in applicationthe property mycompanymyapplicationdomainformsiformname could not be founddescription an unhandled exception occurred during the execution of the current web request please review the stack trace for more information about the error and where it originated in the code exception details systemargumentexception the property mycompanymyapplicationdomainformsiformname could not be foundsource error line 24 divline 25 div classformfieldcontainerline 26 htmllabelformodel modelformname form titleline 27 htmleditorformodel modelformnameline 28 htmlvalidationmessageformodel modelformnamesource file cusersmedocumentsvisual studio 2010projectszoodbmainzoodbzoodbviewszooformeditcshtml line 26 stack trace argumentexception the property mycompanymyapplicationdomainformsiformname could not be found systemwebmvcassociatedmetadataprovidergetmetadataforpropertyfunc1 modelaccessor type containertype string propertyname 505385 systemwebmvcmodelmetadatagetmetadatafromproviderfunc1 modelaccessor type modeltype string propertyname type containertype 101 systemwebmvcmodelmetadatafromlambdaexpressionexpression1 expression viewdatadictionary1 viewdata 421 systemwebmvchtmllabelextensionslabelforhtmlhelper1 html expression1 expression string labeltext 56 asp page views zooform edit cshtmlexecute in cusersmedocumentsvisual studio 2010projectszoodbmainzoodbzoodbviewszooformeditcshtml26 systemwebwebpageswebpagebaseexecutepagehierarchy 272 systemwebmvcwebviewpageexecutepagehierarchy 81 systemwebwebpagesstartpagerunpage 58 systemwebwebpagesstartpageexecutepagehierarchy 94 systemwebwebpageswebpagebaseexecutepagehierarchywebpagecontext pagecontext textwriter writer webpagerenderingbase startpage 173 systemwebmvcrazorviewrenderviewviewcontext viewcontext textwriter writer object instance 220 systemwebmvcbuildmanagercompiledviewrenderviewcontext viewcontext textwriter writer 115 systemwebmvcviewresultbaseexecuteresultcontrollercontext context 303 systemwebmvccontrolleractioninvokerinvokeactionresultcontrollercontext controllercontext actionresult actionresult 13 systemwebmvcc thisplayclass1cinvokeactionresultwithfiltersb 19 23 systemwebmvccontrolleractioninvokerinvokeactionresultfilteriresultfilter filter resultexecutingcontext precontext func1 continuation 260 systemwebmvcc thisplayclass1einvokeactionresultwithfiltersb 1b 19 systemwebmvccontrolleractioninvokerinvokeactionresultwithfilterscontrollercontext controllercontext ilist1 filters actionresult actionresult 177 systemwebmvccontrolleractioninvokerinvokeactioncontrollercontext controllercontext string actionname 343 systemwebmvccontrollerexecutecore 116 systemwebmvccontrollerbaseexecuterequestcontext requestcontext 97 systemwebmvccontrollerbasesystemwebmvcicontrollerexecuterequestcontext requestcontext 10 systemwebmvcc thisplayclassbbeginprocessrequestb 5 37 systemwebmvcasyncc thisplayclass1makevoiddelegateb 0 21 systemwebmvcasyncc thisplayclass81beginsynchronousb 7iasyncresult 12 systemwebmvcasyncwrappedasyncresult1end 62 systemwebmvcc thisplayclasseendprocessrequestb d 50 systemwebmvcsecurityutilgetcallinapptrustthunkb 0action f 7 systemwebmvcsecurityutilprocessinapplicationtrustaction action 22 systemwebmvcmvchandlerendprocessrequestiasyncresult asyncresult 60 systemwebmvcmvchandlersystemwebihttpasynchandlerendprocessrequestiasyncresult result 9 systemwebcallhandlerexecutionstepsystemwebhttpapplicationiexecutionstepexecute 8971485 systemwebhttpapplicationexecutestepiexecutionstep step boolean completedsynchronously 184version information microsoft net framework version4030319 aspnet version4030319547i appreciate that my inheritance hierarchy is a bit messy and that this is not the most beautiful code but i am curious to know why this happens and what my options are for fixing it am i failing to understand something about how interface inheritance works in c,['c#'] +271195,why does python use else after for and while loops i understand how this construct worksfor i in range10 printi if i 9 printtoo big i am giving up breakelse printcompleted successfullybut i do not understand why else is used as the keyword here since it suggests the code in question only runs if the for block does not complete which is the opposite of what it does no matter how i think about it my brain cannot progress seamlessly from the for statement to the else block to me continue or continuewith would make more sense and i am trying to train myself to read it as suchi am wondering how python coders read this construct in their head or aloud if you like perhaps i am missing something that would make such code blocks more easily decipherable,['python'] +271223,core dump taken with gcore jmap conversion to hprof file format fails with error message we recently had one of our jvms crash leaving behind a core dump file produced by the gcore command we want to have a look at the contents of the file and find out exactly what caused the crash using the jmap command you are supposed to be able to turn core dump files into files in the hprof file format which you can then analyse using visualvm and a number of other tools i have tried this and get an error message this was the command that i ran on the same box that the crash took place using the same jvmjmap dumpformatbfiledumphprof usrjavajdk160 16binjava coredump2878the response in it is entirety was attaching to core coredump8483 from executable usrjavajdk160 16binjava please wait error attaching to core file cannot attach to the core filethat is not a very helpful error message i wondered if it was a permissions issue but i get the same message running the command as the same use that ran the jvm that caused the core dump i also wondered if the core file was corrupt so i decided to use gdb to see if i could open up the core file and see what was in it this is what i get gdbgnu gdb gdb red hat enterprise linux 70137el5 71license gplv3 gnu gpl version 3 or later this is free software you are free to change and rethistribute itthere is no warranty to the extent permitted by law type show copyingand show warranty for detailsthis gdb was configured as x86 64redhatlinuxgnufor bug reporting instructions please seegdb corefile coredump8483new thread 2889new thread 2893new thread 2894new thread 2895new thread 2896new thread 2904new thread 2915new thread 2916new thread 2917new thread 2921new thread 2922new thread 3175new thread 3239new thread 3252new thread 3258new thread 3260new thread 3356new thread 3509new thread 3510new thread 3514new thread 3523new thread 3541new thread 3542new thread 3543new thread 4022new thread 4057new thread 4058new thread 4077new thread 4078new thread 4079new thread 4080new thread 6128new thread 6140new thread 6162new thread 6376new thread 6389new thread 6408new thread 6422new thread 6429new thread 6451new thread 6497new thread 6513new thread 6514new thread 6516new thread 6517new thread 6532new thread 6533new thread 65new thread 6675new thread 6676new thread 6687new thread 6689new thread 6692new thread 6706new thread 6707new thread 6735new thread 6736new thread 7033new thread 7034new thread 7056new thread 7077new thread 7079new thread 7080new thread 7082new thread 7089new thread 7090new thread 7091new thread 7092new thread 7103new thread 7105new thread 7107new thread 7108new thread 7116new thread 7229new thread 7308new thread 7493new thread 7505new thread 7510new thread 7511new thread 7517new thread 7523new thread 7604new thread 7617new thread 7618new thread 7619new thread 8676new thread 8693new thread 8700new thread 8851new thread 8860new thread 87new thread 9007new thread 9118new thread 9119new thread 9120new thread 9413new thread 9427new thread 9495new thread 9508new thread 9519new thread 9535new thread 9536new thread 9537new thread 9554new thread 9556new thread 9659new thread 9660new thread 9663new thread 9664new thread 9665new thread 96new thread 9667new thread 9668new thread 9669new thread 9670new thread 9671new thread 9678new thread 9870new thread 9953new thread 98new thread 102new thread 10118new thread 10119new thread 10122new thread 10149new thread 10152new thread 10155new thread 10176new thread 10178new thread 10179new thread 10180new thread 10182new thread 10194new thread 10195new thread 10196new thread 10198new thread 10199new thread 10200new thread 10201new thread 10202new thread 10203new thread 10205new thread 10206new thread 10244new thread 10246new thread 10247new thread 10248new thread 10249new thread 10251new thread 10252new thread 10254new thread 10255new thread 10256new thread 10257new thread 10258new thread 10259new thread 10260new thread 10261new thread 10262new thread 10263new thread 10264new thread 10265new thread 10267new thread 10268new thread 10269new thread 10271new thread 10476new thread 10477new thread 10479new thread 10552new thread 10607new thread 10611new thread 10612new thread 10613new thread 10615new thread 10617new thread 10623new thread 10624new thread 10625new thread 10641new thread 10642new thread 10649new thread 10736new thread 10742new thread 10756new thread 10758new thread 10760new thread 10761new thread 10762new thread 11278new thread 11412new thread 11513new thread 11514new thread 2878gdb quitand at that point i quit because i know absolutely nothing about gbd and how to use it to diagnose this sort of issue i do not even really understand what that last command did one thing worth noting is that there are exactly 134 of those new thread lines present in the output and if each one represents a new thread spawning in the jvm this could be the reason the jvm diedso my question is in fact three fold 1 any idea why the jmap command may have given that error message 2 any ideas what the gdb output means 3 any idea how to use gdb to further diagnose this issue,['java'] +271224,resource relations in angularjs angulars usual way of defining an isolated resource isangularservicetheservice functionresource return resourceapiurli am trying to figure out the best way to write a model that relates to other models such as an order that has 1 or more orderitems my first idea is thiscreate the orderservice and orderitemservice as independent resource modelswrite a controller that queries the orderservice and watches the result arraywhen the result array changes query the orderitemservice for all of the item ids and decorate the order object with extended information as it comes inthat seems a bit messy is there a more elegant way,['javascript'] +271226,create a pivot table from a datatable i am using c winforms to create an application that needs to turn a datatable into a pivot table i have the pivot table working fine from a sql end but creating it from a datatable seems trickier i could not seem to find anything built into net for this note i do have to do this from a net side as i manipulate the data prior to creating the pivoti have read through some articles that did some similar things as this but i have had difficultly applying them to my problem i have a datatable with the columns startdatetime tap and data the startdates should be grouped together and data values averaged sometimes more than one data value per startdate the table is shown belowpivot table should output like the image below not rounded values though the column numbers are the thistinct tap numbers one for each unique onehow can i go about creating this pivot table from the datatable edit forgot to mention these tap values are not always from 14 they do vary in number and value,['c#'] +271235,how to call overrided method which have overloads i have the following simple codeabstract class a public abstract void testint32 valueclass b a public override void testint32 value consolewritelineint32 public void testdouble value testint321 when i ran this code the line testint321 causes stack overflow due to infinite recursion the only possible way to correctly call proper method with integer parameter i found isthis as atest1but this is not appropriate for me because both methods test are public and i am willing the users to be able to call both method any suggestions,['c#'] +271236,how to pass an array of integers to aspnet web api i have aspnet web api rest service where i need to pass an array of integers how can this be done in aspnet 4 web apipublic ienumerablecategory getcategoriesint categoryids code to retrieve categories from databaseurl to access the above servicecategoriescategoryids1234,['c#'] +271261,data type of results of java arithmetic calculation in java i know the data type of the result of an arithmetic calculation depends on the data types of the numbers involved in the calculation for example int int intlongdoubledoublea but i cannot find any references which can give me all these rules could someone help meb how to avoid over flow in arithmetic calculation for example the results of 2 long may not fit into a long anymore thanks a lot,['java'] +271269,path routing in flask i want to run a python cgi on a shared hosting environment i followed flasks example and came up with a tiny application as belowfrom flask import flaskapp flask name approutedef hello return hello worldapproutepidef pi return 31416if name main apprunmy htaccess containsoptions execcgi addhandler cgiscript cgi py rbdirectoryindex indexcgi indexhtmand my indexcgi is usrbinenv pythonfrom wsgirefhandlers import cgihandlerfrom firstflask import appcgihandlerrunappit successfully maps the path to index however it fails to map the path pi to pi instead returning a 404 error i guess i miss something obvious thanks for the help,['python'] +271272,how to access magento customers session from outside magento first up my question is very similar to questions asked in stackoverflow and the web such ashow to access magento users session from outside magentowhat i need is if a customer is logged into a magento site i want him to be logged on to a forum too but try as i might i am unable to get isloggedin to be true any suggestions on what i might be missing heres the minimal code chunk that should get me loggedin informationrequire once abspathtomagephpumask0mageappdefaultmagegetsingletoncoresession arrayname frontendsession magegetsingletoncustomersession zend debugdumpsessionisloggedini checked the followingcookie path is set to i dumped the session variable and did not get wiseras described here i tried setting use session id in frontend but it appears my magento does not have that option we use magento 1324i am checking the variable of course by logging in and out as a customeram including magephpany help on what i might be missing,['php'] +271284,limiting performance factors of websocket in aspnet 45 msdn documentation does not seem to have good coverage on aspnet 45 support of html5 websockets protocolthis is what i am looking forhow many live connections can a serverapplicationcpu support is there any maximum number of incoming connections that could be setgetwhat is the optimum number of sockets per application regardless of data transfer over the socketupdaterequests from flash rtmp sockets an alternative to websocket could be well configured on adobe media server application server is not any sort of configurations for number of requests ideal time size of chunks for aspnet inside application or iis 8 configuration,"['c#', 'asp.net']" +271311,webkit animation is leaving junk pixels behind on the screen the following code puts a white box on the screen if you run this on an ipad you can adjust the pixels to run it on an iphone too when you touch the box it will scoot off the screen and leave a trail of whiteish pixels along its bottom edgedoctype htmlhtml head meta httpequivcontenttype contenttexthtml charsetutf8 meta nameviewport contentwidthdeviceheight userscalableno maximumscale1 minimumscale1 titleline bug demotitle stylebody background blackpanel background white position absolute zindex 2 width 10px height 500px top 34px left 12px webkitborderradius 20px webkittransition left 03s easeinoutpanelhide left 10px style head body div classpanel onclickthissetattributeclass panel hidediv bodyhtmlthe key to getting the bug is using a border radius and doing animation if you just pop it off the screen no trail if there is no border radius no trailhere are the workarounds i have found so farpanelhide webkitborderradius 0 ugly and not really practical for my application because i am animating the panel both in and out and i really want the rounded corners when it is on screenanotherpanel webkittransform translatez0 that puts the panel into the hardware pipeline which does the compositing correctly although this works with this simple demo using the hardware pipeline in my real web app causes outofmemory errors of the drastic huge immediate varietyany other ideas of how i might get rid of this trail,"['css', 'ios']" +271341,is there a way in java to find the name of the variable that was passed to a function i have a java function called testfornull public static void testfornullobject obj if obj null systemoutprintlnobject is null i use it to test multiple objects to ensure they are not null but i am unable to tell the name of the variable that way for eg if i say testfornullx testfornully testfornullzi cannot tell which of the three lines caused the object is null output of course i can simply add another parameter to the function and have something like testfornullx x testfornully y testfornullz zbut i want to know whether it is possible to deduce the name of the variable without passing it explicitly thanks,['java'] +271345,activeadmin generate link to index with filter preset in an activeadmin page i would like to include a link to a list of related resources for example given that a site has many sections and a section belongs to a site in my activerecord models i would like my site show page to include a link to sections within the site which would go to the section index page with the site filter presetnote that i do not want to use activeadmins belongs to function i do not want nested resources for a number of reasons depth of nesting 2 as well as usability concerns what i want is to generate a url similar to the one activeadmin generates if i first go to the sections index page and then filter by sitethe query parameter list generated by activeadmins filtering feature is pretty crazy is there a helper method i could use to achieve this goalthanks,['ruby-on-rails'] +271364,jquery on does not work but live does since the live method is deprecated as of version 17 i started going through my source and converting all of my live event handlers over to on i was under the impression that the change would be simple and everything would work as it had before however i ran into some code that does not behave as it shouldi have the following jquery select to bind the click event of a table tagtableaccordionheaderliveclick function e gobs of code and it works just fine ie my table tag click event is raised even after asynchronous postbacks on the page occur but if i change the code to the followingtableaccordionheaderonclick function e gobs of codethen the click event is no longer raised after any asynchronous postbacks on the page occur please note the click event does work up to any asynchronous postbacks but afterwards it no longer works so what am i missing here,['jquery'] +271371,code signing error application failed codesign verification i am very new to ios development i have an app all set and ready to be thistributed but i seem to get this error every single time i run the application on my device only the ios simulator works just fine heres the full errorapplication failed codesign verification the signature was invalid contains thisallowed entitlements or it was not signed with an iphone thistribution certificate 19011heres the entire logvalidate usersmasonsochalibrarydeveloperxcodederiveddatamultibrowserbrgeiknbjgrywwehhohafjwxjqnkbuildproductsapp storeiphoneosmultibrowserapp cd usersmasonsochadesktopappsmultibrowser setenv path applicationsxcodeappcontentsdeveloperplatformsiphoneosplatformdeveloperusrbinapplicationsxcodeappcontentsdeveloperusrbinusrbinbinusrsbinsbin setenv product type comappleproducttypeapplication applicationsxcodeappcontentsdeveloperplatformsiphoneosplatformdeveloperusrbinvalidation usersmasonsochalibrarydeveloperxcodederiveddatamultibrowserbrgeiknbjgrywwehhohafjwxjqnkbuildproductsapp storeiphoneosmultibrowserappwarning application failed codesign verification the signature was invalid contains thisallowed entitlements or it was not signed with an iphone thistribution certificate 19011executableusersmasonsochalibrarydeveloperxcodederiveddatamultibrowserbrgeiknbjgrywwehhohafjwxjqnkbuildproductsapp storeiphoneosmultibrowserappmultibrowsercodesign wrapper0710 using apple ca for profile evaluationassertmacros trust result ksectrustresultunspecified file codesign wrapperc line 594assertmacros profile file codesign wrapperc line 918codesign wrapper0710 failed to load provision profile from usersmasonsochalibrarydeveloperxcodederiveddatamultibrowserbrgeiknbjgrywwehhohafjwxjqnkbuildproductsapp storeiphoneosmultibrowserappembeddedmobileprovision nulli have already tried shortening the length of the project name that did not help i am currently using osx lion on xcode 432 i have spent all night pulling my hair out please help,['ios'] +271409,how to call codeigniter controller function from view how to call codeigniter controller function from view when i call the function in a controller get a 404 page,['php'] +271427,how to add digital signature image to pdf in ios can anybody help me to solve this problemi am working on iphone development this is new for mei need to generate a pdf with digital signature i do not have any idea about this i have googled past 1 week still i am not able to crack this problem please can anybody explain the step by step procedure or provide me some source code examplealso provide me some good links,['iphone'] +271445,activity as dialog in android i want to use an activity as dialog and i made the theme of the activity as dialog i succeedbuti have the problem here is when i click outside of the activity its automatically get closed the previous activity get startedi tried a thing to make transparent parent layout it does not look like a dialogi want to use this activity to create new account in my application as it has only 3 fields so in tablet it looks large space unused so i want to use activity as dialogthenx in advanceexamples will be appreciated,['android'] +271488,page scroll when soft keyboard poped up i have a scrollview layoutxml version10 encodingutf8scrollview xmlnsandroid androidididmy scrollview androidlayout widthfill parent androidlayout heightwrap content linearlayout androidlayout widthfill parent androidlayout heightwrap content androidorientationvertical edittext androidididinput one androidlayout width300dp androidlayout heightwrap content androidlayout gravitycenter androidinputtypenumber edittext androidididinput two androidlayout width300dp androidlayout heightwrap content androidlayout gravitycenter androidinputtypenumber edittext androidididinput three androidlayout width300dp androidlayout heightwrap content androidlayout gravitycenter androidinputtypenumber button androidididok btn androidlayout width200dp androidlayout heightwrap content androidlayout gravitycenter androidlayout margintop20dp androidtextstringok str linearlayoutscrollviewas you see above the simple layout consists of three input fields and an ok buttoni run my app with the above layout when i tap on the 1st input field idinput one the soft keyboard will pop up from the bottom of the screen it hides the 3rd input field and the ok button since i use scrollview i thought i can scroll the page up in order to see the 3rd input field and ok button which are hiden by the soft keyboard but the page is not scrollable why how to get rid of it basically i would like to see every input fields and ok button even the soft keyboard poped up,['android'] +271539,webconfig allow location access for specific user i have a webserver from where users can download files that are specific for each user to be sure each user can only download its own files they must authenticate via basicauthentication so for each user there is a windowsaccount on the server that has read permissions to the user specific foldernow i want to move this functionality to another server i do not want to create windows accounts for the users but still keep the basicauthentication so i use the custom basic authentication http module in combination with a custom membershipprovider that lets me define users in the webconfigthe authentication works quite fine but after logging in with either jack or jill see webconfig i am able to access both locations dir1 and dir2 this is also the case if i comment out the allow usersjack part in the location tagsadditional infoi created a defaultaspx file and added a responsewritehttpcontextcurrentuseridentityname which returns the correct user name depending on who logged in responsewritehttpcontextcurrentuseridentityisauthenticated returns truewhat do i have to do that only jack is able to access download files from dir1 and only jill is able to access download files from dir2 but not the other way roundedit i tried to add webconfig files for each subdirectories instead of the location tags as mentioned by utkai with the same result every user can access any directoryhere is my webconfig fileconfigurationsystemwebserver modules add namecustombasicauthentication typeleastprivilegecustombasicauthenticationcustombasicauthenticationmodule leastprivilegecustombasicauthenticationmodule version10 cultureneutral publickeytokenf20dc168dfd54966 modules security authentication custombasicauthentication enabledtrue realmtest providernameaspnetwebconfigmembershipprovider cachingenabledtrue cachingduration15 requiresslfalse authentication authorization deny users authorization securitysystemwebserversystemweb membership defaultprovideraspnetwebconfigmembershipprovider providers add nameaspnetwebconfigmembershipprovider typeleastprivilegeaspnetsecuritysampleswebconfigmembershipprovider webconfigmembershipprovider providers membership authentication modeforms forms credentials passwordformatclear user namejack passwordjack user namejill passwordjill credentials forms authentication authorization deny users authorizationsystemweblocation pathdir1 allowoverridefalse systemweb authorization allow usersjack deny users authorization systemweblocationlocation pathdir2 allowoverridefalse systemweb authorization allow usersjill deny users authorization systemweblocationconfiguration,['asp.net'] +271584,runonuithread undefined for class i am trying to throw and alert dialog on the ui thread from my background thread but i am having problems with runonuithread being undefined i have tried findlocationthisrunonuithread and runonuithread but both seem to throw the same error the method runonuithreadnew runnable is undefined for the type new locationlistener or the type findlocation any ideas why here is a snippet of my findlocationjava class this is called by my main activitypublic class findlocation extends thread public boolean injurisdictionpublic boolean alertnotice falseprivate locationmanager locmanagerprivate locationlistener loclistenercontext ctxpublic string useridpublic findlocationcontext ctx thisctx ctx public void startstring userid thisuserid userid superstart overridepublic void run looperprepare final string usr userid get a reference to the locationmanager locmanager locationmanager ctxgetsystemservicecontextlocation service checked to receive updates from the position loclistener new locationlistener public void onlocationchangedlocation loc string lat stringvalueoflocgetlatitude string lon stringvalueoflocgetlongitude double latitude locgetlatitude double longitude locgetlongitude if latitude 3915296 longitude 86547546 latitude 39184901 longitude 86504288 injurisdiction false logitest yes injurisdiction true findlocationthisrunonuithreadnew runnable error here public void run alertdialogbuilder alert new alertdialogbuilderctx alertsettitlesent alertsetmessageyou will be contacted shortly alertsetpositivebuttonok new dialoginterfaceonclicklistener public void onclickdialoginterface dialog int which,"['java', 'android']" +271598,how to approach desktop application development with web and mobile apps in mind i have been tasked with the requirement to produce a desktop application with a sexy look and feel i intend to use wpf to achieve this one of the requirements is that the desktop application will later expand to an aspnet mvc web application and then a mobile probably android first application all while maintining the same look and feel in this context sexy means sliding menus and a generally modern look and feelwith this in mind what is the best approach to take when beginning the desktop ui design if i want to reuse components andor styleeg in creating the desktop application i would be using xaml for the ui but considering there will be a web version of the app that should look the same as the desktop shouldcould i use htmlcss instead is it ridiculous to even think that,['c#'] +271612,bezier curve and canvas how i can draw bezier curve in canvas i have only start point and end point i want to draw line from start point to end point how i can do this,['android'] +271620,python literal r not accepted r in python does not work as expected instead of returning a string with one character a backslash in it it raises a syntaxerror r does the samethis is rather cumbersome if you have a list of windows paths like thesepaths rblafoobar rblafoobloh rbuff r is there a good reason why this literal is not accepted,['python'] +271631,set android sdk behind server proxy how can i download android sdk package behind a server proxy,['android'] +271635,what is the most efficient way to store retrieve items in aspnet httpcontextcache i have a website where i cache a lot of info i am seeing conflicting information around storing stuff in the aspnet cachefor example lets say i have this data structure dictionarystring listcar mydictionaryi could store the whole thing with a string key as mydictionary and then drill down once i pull out the object httpcontextcacheaddmydictionary mydictionary null cachenoabsoluteexpiration new timespan10 0 0 cacheitemprioritynormal null var mydict httpcontextcachemydictionary as dictionarystring listcarthe other thing i could do is break it down and store each item in my dictionary separately in the cache given the cache is a dictionary anyway dictionarystring listcar mydictionary foreach var item in mydictionarykeys httpcontextcacheadditem mydictionaryitem null cachenoabsoluteexpiration new timespan10 0 0 cacheitemprioritynormal null var myitem test var mydict httpcontextcachemyitem as listcarwould the performance implication be very different given i am assuming that everything is in memory anyway,['asp.net'] +271644,javascript pass selected value from popup window to parent window input box i am building an order form with php and mysqlthe php form has an input box where the user types in a product code in the event that the user does not know the product code i want them to click on an image or button next to the input box which opens a popup with a list of all product codes they can then click on the product they want and the product code is passed from the popup to the input box on that table rowi have the code of my page below and the image of the page it creates so you can get a feel for what i am wanting to acheiveparent pagetable border0 idhorminimalista trth valignbottomkvithth valignbottompack codethth valignbottom width250descriptionthth valignbottom width40whsethth valignbottom width25suthtrtr idr1 td input typecheckbox namekvi1 idkvi1 value1 td td input size10 typenumber idsku1 namesku1 onchangeshowuser1 thisvalue input typebutton namechoice onclickwindowopenskuphppopuppagewidth400toolbar1resizable1scrollbarsyesheight400top100left100 value td td div alignleft idtxthint1nbspdiv td td div alignleft idwhse1nbspdiv td td div alignleft idsu1nbspdiv tdtrtr idr2 td input typecheckbox namekvi2 idkvi2 value2 td td input size10 typenumber idsku2 namesku2 onchangeshowuser2 thisvalueimg srcqpng td td div alignleft idtxthint2nbspdiv td td div alignleft idwhse2nbspdiv td td valignbottom div alignleft idsu2nbspdiv tdtrtr idr3 td input typecheckbox namekvi3 idkvi3 value3 td td input size10 typenumber idsku3 namesku3 onchangeshowuser3 thisvalueimg srcqpng td td div alignleft idtxthint3nbspdiv td td div alignleft idwhse3nbspdiv td td div alignleft idsu3nbspdiv tdtrtr idr4 td input typecheckbox namekvi4 idkvi4 value4 td td input size10 typenumber idsku4 namesku4 onchangeshowuser4 thisvalueimg srcqpng td td div alignleft idtxthint4nbspdiv td td div alignleft idwhse4nbspdiv td td div alignleft idsu4nbspdiv tdtrtableformthe popup page code and image is below con mysql connectlocalhost dbuser dbpass if con diecould not connect mysql error mysql select dbdatabasename con skusqlselect packcodecategorydescriptiongroupingpackconfigsellingunitseottpoints from skudata order by category packcode resultskumysql queryskusql script languagejavascript beginfunction sendvalue svar selvalue svaluewindowopenerdocumentgetelementbyiddetailsvalue selvaluewindowclose end script form nameselectform table border0 width10 idhorminimalista tr thpack codeth thnbspth thcategoryth thproduct descriptionth thgroupingth thpack configth thsuth thpointsth trphp whilerowsmysql fetch arrayresultsku tr tdinput namedetails size5 valuephp echo rowspackcode td tdinput typebutton valueselect onclicksendvaluethisformdetailstd tdphp echo rowscategory td tdcenterphp echo rowsdescription td tdcenterphp echo rowsgrouping td tdcenterphp echo rowspackconfig td tdcenterphp echo rowssellingunits td tdcenterphp echo rowseottpoints td tr php tablei am trying to pass the value of the product code from the selected popup window row to the parent window input box for pack codei was trying to adapt a script i came across but am not pulling it off any help appreciated as alwaysregardsryanupdate to questionparent pagehtmlheadtitleunilever sales portaltitlestyleimport urlstylecstylescript typetextjavascript function showuserusernumber str if str documentgetelementbyidtxthint usernumberinnerhtml return if windowxmlhttprequest code for ie7 firefox chrome opera safari xmlhttpnew xmlhttprequest xmlhttponreadystatechangefunction if xmlhttpreadystate4 xmlhttpstatus200 documentgetelementbyidtxthint usernumberinnerhtmlxmlhttpresponsetext var responsetext xmlhttpresponsetext var description responsetext var warehouse var sellingunits if responsetextindexofnot a valid 1 description responsetextsubstring12 responsetextindexofwarehouse warehouse responsetextsubstringresponsetextindexofwarehouse11 responsetextindexofsellingunits sellingunits responsetextsubstringresponsetextindexofsellingunits15 documentgetelementbyidwhse usernumberinnerhtml warehouse documentgetelementbyidtxthint usernumberinnerhtml description documentgetelementbyidsu usernumberinnerhtml sellingunits xmlhttpopengetgetdata1phpqstrtrue xmlhttpsend script script typetextjavascript function selectvalueid open popup window and pass field id windowopenskuphpid encodeuricomponentidpopuppage width400toolbar1resizable1scrollbarsyesheight400top100left100 function updatevalueid value this gets called from the popup window and updates the field with a new value documentgetelementbyididvalue value script headskuphp con mysql connectlocalhost dbuser dbpass if con diecould not connect to server mysql error dbmysql select dbdbname con if db diecould not connect to db mysql error sqlselect packcodecategorydescriptiongroupingpackconfigsellingunitseottpoints from skudata order by category packcoderesultmysql querysql script typetextjavascript function sendvaluevalue var parentid php echo json encode getid windowopenerupdatevalueparentid value windowclose script form nameselectform table border0 width10 idhorminimalista tr thpack codeth thnbspth thcategoryth thproduct descriptionth thgroupingth thpack configth thsuth thpointsth tr php whilerowsmysql fetch arrayresult tr tdinput namedetails size5 valuephp echo rowspackcode td tdinput typebutton valueselect onclicksendvaluethisformdetailstd tdphp echo rowscategory td tdcenterphp echo rowsdescription td tdcenterphp echo rowsgrouping td tdcenterphp echo rowspackconfig td tdcenterphp echo rowssellingunits td tdcenterphp echo rowseottpoints td tr php table here is the images to show the workingsparent pagepopup pageparent page after popupthanks again for the helpregardsryan,['javascript'] +271645,whats the best way to store different images in the database what is the best way regarding database design for storing images for different purposesi have a bunch of user photos and i got another 5 different sets of photos like user photos but with no connection to user photosis the best thing to store all photos in a single database table and try to reference them from within that table or is the best to create different tables for each set of photosi can see one benefit from creating multiple tables and that is the cascade delete function for removing the photo when the main object is deletedany other aspects to consideranother example could be addresses a user can have an address but so can a company or a location create one table for all addresses and try to have some sort of index tables to reference what address belongs to what object or have different tables and eliminate the problem,['sql'] +271694,how to set onbackbutton listener to an activity i have a class a which runs activity via startactivityforresult by passing intent to it in other class lets say b i get this intent and recreate activity by it how can i listen events for that activity eg activity which was started for result is running and user pressed back button so i want to do some actionhow can i do thisthank you on advanceactivity in which i recreate instance of object is not derived from activity class it is just activity so i have only object is there any way to do such stuff with instance of class but not a class,['android'] +271715,command line args in c program using netbeans i am new to usintg netbeans in linux so i am facing problem how to specify command line args for example atxt and btxt for my program in c using netbeans its pretty simple to pass them as args using command line but now for debugging purpose i need to use netbeans 71 on ubuntu version 11 any help would be highly appreciatedthanks,['c'] +271735,is it possible to pass a class as a parameter to a function in c i have a function with void as one of its parameters the void is used as a generic object but to be able to call a function in that generic object i need to cast it first and for that i need to know what type the class is and i wanted to know is it possible to pass a class or some information that allows me to cast the object as a function parameter,['c++'] +271754,jquery tagit using a value and label object list just tried the excellent tagit plugin for jquery but i cannot get it to work how i would likei have an object list like thisvar food value1labelpizzavalue2labelburgervalue3labelsaladwhich i pass to the tagsource option in my setupmy food tagstagit tagsource food singlefield true singlefieldnode my food placeholdertext start typing a food namethis works fine except when i click the autocomplete list item it thisplays the numeric value in the tag rather than the food nametherefore it is possible to have to value entered in to the hidden field and the label to show as the tag namehere is a screenshot of what i mean the value is appearing in the tag label and the label is being lost to the ether could anyone please help me here it would be very much appreciatedthanks in advanceseb,['jquery'] +271759,make android jenkins build fail if tests fail i have seen several post regarding making a build in jenkins fail if the unit test execution fail eg this one it turns out that by default jenkins reports builds with failing tests as unstable and some people do not like that this however will be perfectly fine for me i just want to be able to easily differentiate builds with passing tests from such with failing tests and here is the catch i am developing for android so my build is configured following this page basically the tests are run with the following commandant all clean emma debug install testas result coverage report is generated and published in jenkinsall posts i have read about configuring the jenkins result according to tests resultswere dealing with ant task manipulation however if we look at the android buildxml the android tests are run with adb command adb shell am instrument i do not know how to configure this command to print the tests results it can be configured to print the coverage report i have already done that but was never able to make the build fail according to the coverage reporti hope somebody else also faced the same problem and managed to solve it any guidance will be most appreciated,['android'] +271765,how to register a custom speech recognition service i created a simple speech recognition service for this purpose i created a subclass of androidspeechrecognitionservice and i created an activity to start and stop this servicemy custom speech recognition service trivially uses the default speech recognizer because my goal is simply to understand how the recognitionservice and recognitionservicecallback classes workpublic class simplevoiceservice extends recognitionservice private speechrecognizer m enginesr override public void oncreate superoncreate logisimplevoiceservice service started override public void ondestroy superondestroy logisimplevoiceservice service stopped override protected void oncancelcallback listener m enginesrcancel override protected void onstartlisteningintent recognizerintent callback listener m enginesrsetrecognitionlistenernew voiceresultslistenerlistener m enginesrstartlisteningrecognizerintent override protected void onstoplisteningcallback listener m enginesrstoplistening private class voiceresultslistener implements recognitionlistener private callback m userspecifiedlistener param userspecifiedlistener public voiceresultslistenercallback userspecifiedlistener m userspecifiedlistener userspecifiedlistener override public void onbeginningofspeech try m userspecifiedlistenerbeginningofspeech catch remoteexception e eprintstacktrace override public void onbufferreceivedbyte buffer try m userspecifiedlistenerbufferreceivedbuffer catch remoteexception e eprintstacktrace override public void onendofspeech try m userspecifiedlistenerendofspeech catch remoteexception e eprintstacktrace override public void onerrorint error try m userspecifiedlistenererrorerror catch remoteexception e eprintstacktrace override public void oneventint eventtype bundle params override public void onpartialresultsbundle partialresults try m userspecifiedlistenerpartialresultspartialresults catch remoteexception e eprintstacktrace override public void onreadyforspeechbundle params try m userspecifiedlistenerreadyforspeechparams catch remoteexception e eprintstacktrace override public void onresultsbundle results try m userspecifiedlistenerresultsresults catch remoteexception e eprintstacktrace override public void onrmschangedfloat rmsdb try m userspecifiedlistenerrmschangedrmsdb catch remoteexception e eprintstacktrace i start and stop the service using the following activitypublic class voiceservicestarteractivity extends activity called when the activity is first created override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate button startbutton new buttonthis startbuttonsettextstart the service startbuttonsetonclicklistenernew viewonclicklistener override public void onclickview v startvoiceservice button stopbutton new buttonthis stopbuttonsettextstop the service stopbuttonsetonclicklistenernew viewonclicklistener override public void onclickview v stopvoiceservice linearlayout layout new linearlayoutthis layoutsetorientationlinearlayoutvertical layoutaddviewstartbutton layoutaddviewstopbutton setcontentviewlayout private void startvoiceservice startservicenew intentthis simplevoiceserviceclass private void stopvoiceservice stopservicenew intentthis simplevoiceserviceclass finally i declared my service on the androidmanifestxml see voicerecognition sample within android sdk folderservice androidnamesimplevoiceservice androidlabelstringservice name intentfilter action androidnameandroidspeechrecognitionservice category androidnameandroidintentcategorydefault intentfilterservicethen i installed this application on an android device and i start it when i start the service it starts properly when i stop it it stops properlybut if i launch the following code in a another activity the activities list contains only an element which is the default speech recognizerpackagemanager pm getpackagemanagerlistresolveinfo activities pmqueryintentactivities new intentrecognizerintentaction recognize speech 0why is my speech recognizer not returned among those present in the system,['android'] +271767,a daemon on the rocks i am writing a daemon in php i did not take a os class in college so i am wondering what are the serverother statistics that i need to be looking at to make sure my daemon is not consuming too much system resources and will be able to scale when there are more mysql records basically my daemon is processing a bunch of mysql table rows for example i understand i need to see how long the daemon is taking to process a certain number of rows and the amount of memory it is using but how do i determine if it is leaking memory also what other system parameters should i be judging the daemon by,"['php', 'mysql']" +271782,css absolute position would not work with marginleftauto marginright auto say you have the following css applied to a div tagdivtagabs position absolute marginleft auto marginrightauto the marginleft and marginright does not take effectbut if you have relative it works fine iedivtagrel position relativemarginleft auto marginrightautowhy is that i just want to center an elementcan someone explain why setting margins to auto in absolute position does not work,"['html', 'css']" +271792,how to get xdebug var dump to show full objectarray i am using xdebug php xdebug21253vc9dll on wamp when i use var dump on a large object or variable it does not show the full variablearraynode array my form array form array without xdebug it shows as should be expected i looked at the documentation but did not see a solution does anyone know how i can fix this so xdebug var dump shows the full object,['php'] +271799,maintain php session in web app on iphone i have a jquery mobile web app on my iphone when i am on the web app i have a login and session variables if i leave the app to go to another location on the phone and then return to the web app i have to log in again it seems like the session is not maintained further if i have an external link and it opens safari for that link that same session is not transfered to the safari window is there a way to maintain the session,"['jquery', 'iphone']" +271819,how to improve sqlalchemy performance i made a client application that uses http to communicate with a python 2 server using a simple api the server uses sqlalchemys orm quite extensively to serve the data for those http requests the problem is that my cpu usage is quite high even with only few active clients this server should be able to serve a few hundred clients at the same time at around 1 request a second per client so it should still be manageable or so i hopehow can i improve the performance i know the problem is the orm as cprofile shows this quite clearly a single query apparently executes around 10 python instructions which seems quite odd i tried plugging in different database enginesbackends and changed the interpreter to pypy just for fun but it obviously did not help the original problem and also did not improve performancewhat am i doing wrong here i really hope this is a well duh problemshould my relationships be of a different type eager lazy dynamic etc right now i do not specify anything in particularhelp greatly appreciated,"['python', 'sql']" +271832,jquery ui not loading my test div is below if i put all of this into its own page everything works perfectly if it put it onto my final page i get an error saying that datepicker is undefinedhow do i figure out what is causing jquery ui to breakdivscript srcajaxgoogleapiscomajaxlibsjquery172jqueryminjs typetextjavascriptscriptscript typetextjavascript srcscriptlink typetextcss hrefcssuilightnessjqueryui1818customcss relstylesheet script typetextjavascriptdocumentreadyfunction for calendar date todatepicker date fromdatepicker end for calendarscriptinput iddate toinput iddate fromdiv,['jquery'] +271833,aspnet mvc upload a file with signalr i want to upload a file from the client to the server is there a way to upload a file with signalr or must i need a controller for this,['asp.net'] +271835,ajax post to google spreadsheet i am attempting to post form data to a google spreadsheet currently if the form is validated then the following occursif validateform true ajax type post url data workplzserialize success alertworkplzserialize else i used the success setting to verify my form data is being serialized properly it is and that it is successful however my google spreadsheet is not being updated no data is going through i used the example code here changing doget to dopost and have made the google spreadsheet publicly available and editable by anyone i followed the instructions copying in the code to googledocs and then running the setup twice first time asked for permission second time i ran it i did not notice anything happen can anyone help me i feel like i am super close,['jquery'] +271849,detect kinks in parallel lines to bezier curves i was hoping someone could help me figure out a computationally inexpensive method for detecting kinks in a line drawn parallel to a bezier curve as you can see herewhat i would like to do is be able to determine the intersection of the kink the segment with a starting point before the intersection and the first segment with an ending point after the kink this way i can simply remove any unnecessary segments and adjust the first and last segments to meet at the intersectionapologies if i am using the incorrect terms but as far as i understand it the way i am positioning these segments is by determining the unit vector of the segments for the bezier curve yellow and multiplying it by the offset and finding the normal vector to create two new start and end points for the offset segment whitemathematics is not my strong suit so i am hoping someone can give me a push in the right directionedit the image has actually been resized by html so if youre having a hard time seeing what i am talking about heres the direct link,['c#'] +271865,could not load file or assembly crystaldecisionsreportappserverclientdoc i have looked at similar questions on so but nothing quite matches my issue as far as i can tellthe exception messagecould not load file or assembly crystaldecisionsreportappserverclientdoc version13020 cultureneutral publickeytoken692fbea5521e1304 or one of its dependencies the system cannot find the file specifiedthe file is in my gac i am developing on a 32 bit machine windows 7 running vs2010 everything is net4 the target hosting machine is 64bit win 2008 r2 my local machine has the cr installation for vs2010 the hosting machine has the 64bit runtimes for vs2010 i am compiling all my code in any cpu mode for this web applicationit is blowing my mind that it cannot find the file in the gac this is an iis application is there some sort of permissions issue i would think iis would have access to the gacsome suggestions of what to do would be appreciated,['c#'] +271873,applied ducktyping in plain c in my opensource plain c code i use this simple structure to read and parse data from a string buffertypedef struct lts loadstate const unsigned char pos size t unread lts loadstatethe buffer is accessed with this simple api initialize buffer void ltsls initlts loadstate lsconst unsigned char data size t len do we have something to read actually a macro bool ltsls goodls how much do we have to read actually a macro size t ltsls unreadls eat given number of characters return pointer to beginning of eaten data const unsigned char ltsls eatlts loadstate ls size t lennote ltsls unread may be replaced with return ltsls goodls size max 0 without breaking the current implementationthis code is used to load some data in a custom format from a string buffer this may be a better illustrationnow i need to load data not from a string buffer but from a file pointeri would hate to copypaste the implementation and would like to reuse existing code instead i am ok with refactoringadapting it of coursethis is a textbook stuff in c but how to do that in plain c without incurring runtime overheadhere is an example function that uses the lts loadstate api and that is not to be copypasted but may be changed of course to support both string buffer and file static int ltsls readline lts loadstate ls const unsigned char dest size t len const unsigned char origin lspos unsigned char last 0 size t read 0 while ltsls goodls if ltsls unreadls 0 unsigned char b lspos ok this should be ltsls eat char macro lspos lsunread if b n dest origin len last r read 1 read return luatexts esuccess last b read else lsunread 0 lspos null return luatexts eclipped,['c'] +271890,use error messages in rails 32 raises undefined method error i am getting the following error in my rails 32 functional testsactionviewtemplateerror undefined method error messages for actionviewhelpersformbuilder0x007ff8ad00d3b0the view code that is creating the error form for camp program do f ferror messages problematic code flabel name end here is the code in my controller that is calling the above view coderender action edit status bad requestand here is the test i am runningtest update a program with a bad request do put update id programstraditionalto param program min age a camp id camps123uri assert response bad requestenddoes anyone have any insight into why this error is occurring in a rails 32 appthanks,"['ruby-on-rails', 'ruby']" +271924,gcc array type has incomplete element type i have declared a struct and i try to pass an array of those structs as well as a double array of doubles and an integer into a function i get an array type has incomplete element type message from gcc when i compile it what have i got wrong in how i pass the struct into the functiontypedef struct graph node int x int y int active g nodevoid print graphg node graph node double weight int nodesi have also tried struct g node graph node but i get the same thing,['c'] +271959,generic inherited type restriction in c i have an inelegant solution for what i need but am looking for an elegant solution to replace itthe following code does not compile but represents what i would like to dointerface iwebserviceabstract class baseclienttclass specializedclient baseclientiwebserviceclass clienthelpert where t baseclientwhere the t in clienthelpert is any class that extends baseclient regardless of the templated type passed inthe inelegant solution i found isclass clienthelpert u where t baseclientu the reason this becomes inelegant is my project ends up with a class similar toclass myclassa b c d e f g where a mybaseclassb c d e f gall the way down to the base class that takes a single type is this simply the cost of having a complex inheritance tree of generic classes or is there a simpler way to do this while retaining type restrictions on the templated types,['c#'] +271966,jasper reports how to compile subreports i have a standalone application and one of its duties is to take the path of a jrxml file and compile iti can do this without problem until a report with a subreport comes up where the compilation of the master does not compile any of its children resulting in a subreport jasper file not found later down the trackis there any way to1 set the jaspercompilemanager to automatically pick up subreports2 get a list of paths to subreports contained within either a jasperdesign or jasperreport objecti have no direct access to the jrxml files so modifying the reports to suit the compile method is not an option nor is applying any standard naming scheme to infer which subreports belong to which reportsthere is a similar problem here id102forumid103topicid40683where a jrvisitor is used to produce a list of jrsubreport objects however there is no explanation of how to use this to get a path to the subreport in order to compile it and recursively look for subreports of subreports and i cant figure it out,['java'] +271967,python classes and oop basics i do not fully understand classes i have read the python documentation and several other tutorials i get the basic gist of it but do not understand the nuance for instance in my code here class whiteroom pick a door red blue green or black do raw input if red in do print you entered the red room elif blue in do print you entered the blue room elif green in do print you entered the green room elif black in do print you entered the black room else print you sit patiently but slowly begin to stave youre running out of time return whiteroomgame whiteroomgameoriginal codepadi would like to return the class whiteroom which is either not possible or not being done correctly if you could clear up how to return a class or how to link two classes together so that whiteroom repeats on the else and the other rooms which would be classes are returned when called that would be awesomealso i am super shaky on init and am still not really sure what its purpose is everyone keeps telling me that it initializes which i am sure it does but that does not seem to be helping my brain out,['python'] +272013,python mysql not showing inserted records i am using python 27 with mysqldb 32bit alongside with mysql 558 running locali am driving myself crazy over this i have never seen anything like itbasically i am inserting records into mysql from python viadbmysqldbconnecthostlocalhostuserroot passwdmypassworddbpythonport3307curdbcursorcurexecuteinsert into mytablemyfield valuesomedatai have verified that it is connected properly and that it can successfully select data from the databasehere is the odd partfrom mysql query browser gui tool and from mysql via cmd i am unable to see the inserted recordsi can insert and select records from my python script but they do not show up in my database it just returns empty set 0 secand here is the really weird part i can truncate and delete data from the gui tool and from the consoleto sum up i can insert and select data from the python script i can not see that data in mysql however i can truncate and delete that data using mysqli am completely lost at this point,"['python', 'mysql']" +272083,heroku wrongly detecting my node app as a ruby app i have a node project that is using bundler and guard to handle my precompilations stepsthis means that i have a gemfile in the root of my project along with the packagejson filemy problem is that heroku believes that my project is a ruby app just because the gemfile exists and complains that i have not committed the gemfilelock which i do not want to commit heroku receiving push ruby app detected gemfilelock is required please run bundle install locally and commit your gemfilelock heroku push rejected failed to compile ruby appis there a way to tell heroku that the app is a node app and not a ruby app,['ruby'] +272088,install gem on demand i would like to install a gem json on the client side but only if has not been installed already some 19 ruby thistros have json bundledi could not find a clue on how to do that from gem help install and running gem install json on a windows system with ruby 19 installed with json bundled results in error error installing json the json native gem requires installed build tools it tries to install it ignoring the fact that the gem is already thereand i cannot do bash tricks like grepping gem list output because the client might be windowsso whats the multiplatform way of installing a gem only if it is not present in the system already,['ruby'] +272094,android action bar batch selection for versions prior to 30 i have a listview for which i want to enable batch selection for android 30 and above i have added a modal multi choice to the listview and set the multi choice mode listenerhow can i do the same for android versions prior to 30 with or without a third party library i have looked at actionbarsherlock but i have not found this feature in any samples nor searching for information on the web ps when the user clicks an item in the listview i want to perform a different action so it needs to be longclick for batch selection or a single item selectionversions prior to 30 that go back to api 7,['android'] +272097,verticalalign image in div i have problem with image verticalalign in divimg thumb float left height 120px marginbottom 5px marginleft 9px position relative width 147px backgroundcolor rgba0 0 0 05 borderradius 3pximg thumb img thisplay block marginleft auto marginright auto verticalalign middlediv classimg thumb a classimages class hreflargejpg relimagesimg srcsmalljpg titleimg title altimg alt adivas far as i know i need thisplay block to position image in center and that worksalso in tutorials i find many answers but they are not useful because all of my image are not at the same height,['css'] +272112,interactive text fields with fabricjs i have been playing with fabricjs a lot in the last few weeks but regarding text fields i have only found it possible to set the text on creationis there any possible way to make an interactive text field or do i have to find a workaround to achieve that with interactive text field i mean an area of the canvas i can click on and write directly into it,['html'] +272127,how do i output something in rhino i am looking for the javascript equivalent of python2xs print hii am working with the rhino javascript interpreter in the ubuntu terminalwhen i typedocumentwritehii get the error that document is not defined,['javascript'] +272164,why the handle in jquery ui slider is tag i was reading the code in the official demo page for slider and i was wondering why an a tag is used for handle why not a divdiv classdemodiv idslider classuislider uisliderhorizontal uiwidget uiwidgetcontent uicornerall a classuisliderhandle uistatedefault uicornerall uistatehover href styleleft 19 adivdiv,['jquery'] +272178,can i define multiple static blocks can i define multiple static blocksif possible why should i define muliple static blocks,['java'] +272193,prevent caching in aspnet mvc for specific actions using an attribute i have an aspnet mvc 3 application this application requests records through jquery jquery calls back to a controller action that returns results in json format i have not been able to prove this but i am concerned that my data may be getting cached i only want the caching to be applied to specific actions not for all actionsis there an attribute that i can put on an action to ensure that the data does not get cached if not how do i ensure that the browser gets a new set of records each time instead of a cached set,"['c#', 'jquery', '.net']" +272284,how to wrap class in java and save interface i have class likemyclass extends myabstractclass implement myinterface1 myinterface2i need create new class with additional fieldsmytype1 field1mytype2 field2seems that correct create new class that will wrap myclass likemywrapclass myclass myclassnew myclass mytype1 field1 mytype2 field2 but mywrapclass used as type myinterface1 or myinterface2so question is should i declare all methods that are needed for interfaces myinterface1 myinterface2 in mywrapclass or exists another waythanks,['java'] +272291,responsewrite and updatepanel i generate a vcard that i send to the client using the following code snippetresponseaddheadercontentthisposition stringformatattachment filename0 filenameonlyresponsecontenttype textxvcardresponsecontentencoding encodinggetencodingiso88591responsewritevcardtostringresponseendhowever i need to use vcards on a page that has the control inside and updatepanel unfortunately according to update panel and response write this does not work and causes an error i am wondering what are some alternative ways to send the contents of the vcardfile to the clients browser and have it thisplay opensave dialog that do not involve responsewrite,['asp.net'] +272296,how to place components at specific positions how to place components in layout on specific position like i want to place 2 text boxes in first row below 3 combo boxesbut when i am trying to put they all appear in one line and i have used flowlayout i have used the border as well when i am resizing the window sizes of the components are going out from bordercan you suggest me some layouts to use and how to use ithere is my code toppanelnew jpaneltoppanelsetlayoutnew flowlayouttoppanelsetbordernew titledbordernew etchedborder customer datacnametextfield new jtextfield 20 create the customer name text fieldcnametextfieldseteditabletrue set editable text boxcidlabelnew jlabelcustomer idc idtextfield new jtextfield 10c idtextfieldseteditabletrue set editable text boxtoppaneladdcnametextfieldtoppaneladdc idtextfield create and populate room type combo boxroomtypecombo new jcomboboxroomtypecomboadditem budget50 create and populate meal type combo boxmealcombo new jcomboboxmealcomboadditem none create and populate days combo boxdayscombo new jcomboboxforint i0i31 i populate combobox with days dayscomboadditemi adding rest of the components to top paneltoppaneladdroomtypecombotoppaneladdmealcombotoppaneladayscombothanks,['java'] +272297,removing an entry from an bundle ie extras does not seem to work in combination with the back button i have a broadcastreceiver that listen to incoming sms if the message is from a certain sender the broadcastreceiver starts my app with the following codefinal intent activityintent new intentcontext mainactivityclassactivityintentputextrasmschallenge smstextactivityintentputextrasmssendernumber sendermobilnumberactivityintentaddflagsintentflag activity new taskactivityintentaddflagsintentflag activity clear topcontextstartactivityactivityintentin the mainactivity of my app ie in oncreate i extract the value smschallenge out of the intent and delete it after the extraction with the following codebundle extras getintentgetextrasif extras null smschallenge extrasgetstringsmschallenge extrasremovesmschallengeso my app gets started from the sms and runs fine but if i choose to press the back button and restart the application ie through the taskmanager the value smschallenge is still in the bundle extrasthis means my restarted app thinks that it is restarted because of a new sms which is not trueany ideas why removing the keyvalue from the bundle does not seem to work when using the back button and restarting the app again,['android'] +272307,jquery find element with rel attribute i have two kind of elementsi reltooltip classiconoki titleteste classiconinfothe first one is a tooltip effect the second a popoverwhat i am trying to do is avoid rework so i do not need to create a script based on the class on every html i havei did this on my base htmlbodyfinditooltipthe problem is that it is adding the tooltip effect on the other i elements without the rel attributei need to search for elements with the rel attribute and set the tooltip effect on themthankseditif i try to do the opposite of what was said on the correct answer get the i elements without the rel attributefound the solution here jquery selectors find objects without specified attribute vrutberg jquerylinotstylehide,"['jquery', 'html']" +272337,java best practices when throwing exceptions throwing core java exceptions instead of throwing new exceptionsome message maybesomecause which means that all callers of my method will need to catch exception which can include runtimeexceptions i would like to throw a more specific type of exception when a problem occursi can create my own exception types which extend exception or another exception type but i am curious if it is a good idea to reuse some exceptions that come with core java language such asillegalargumentexceptionunsupportedoperationexceptionioexceptionothersare there others that i am missing i found a basic list of the core exceptions here with humous explanationsthankseditis there a good list of core exceptionslist so farjava 7 exception class api,['java'] +272405,how use sql like in pymongo how use sql like in pymongo dbhousesfindcount11616 dbhousesfindhidu169count1 dbhousesfindhidu9count0the documentation says that sql like select from users where name like joe in mongodb is dbusersfind namejoe if you specify a query directly to the cliclient interface mongodb then everything works correctly but does not work in pymongowhat is the problemthanks,['python'] +272409,manual model binding with net mvc i am wondering if there is a way to use the built in model binding similar to the internal model binding that occurs before a controller actionmy problem is that i want to be able to control the binding as i would not know the type of object to bind until i am actually in the context of the controller actioni understand i can inherit the defaultmodelbinder to perform custom binding but i am happy with whats already on offer and just want to utilise it take this ideal example to get an idea of what i am afterpublic actionresult docustombindingstring modeltype logic to determine type to check and create strong actual type object model bindmodelactualtype do something with bound model return viewi have looked into using the defaultmodelprovider but unsure if this is the right way of going about this and i was not sure how to obtain the modelbindingcontext,['c#'] +272411,how does defining square bracket method in ruby work i am going through programming ruby a pragmatic programmers guide and have stumbled on this piece of codeclass songlist def key if keykind ofinteger return songskey else for i in return songsi if key songsiname end end return nil endendi do not understand how defining method works why is the key outside the but when the method is called it is inside can key be without parenthesis i realize there are far better ways to write this and know how to write my own method that works but this method just baffles me any help is greatly appreciated thanks,['ruby'] +272414,could not translate date to spanish with localees es i am trying to do a simple date format it does work great it is very easy but the problem is the language i used the locale es es to get miarcoles instead of wednesday and sorts like that but i failedheres my codesimpledateformat formato new simpledateformate d de m de y new localees esstring fecha formatoformatnew datethe expected value of the fecha string ismiarcoles 4 de abril de 2012but i am still gettingwednesday 4 de april de 2012what am i doing wrong,['java'] +272418,uiview bringsubviewtofront does not bring view to front i am implementing a simple ios solitaire game that allows the user to drag the cards around in the usual way the cards are represented with the uiview subclass cardview all the card views are siblings which are subviews of solitaireview the following snippet tries to bring a card to the front so that it is above all the other views as it is being draggedvoidtouchesbegannsset touches witheventuievent event uitouch touch touches anyobject if touchviewtag card tag cardview cardview cardview touchview self bringsubviewtofrontcardview unfortunately the cards zorder remains unchanged during the drag in the images below i am dragging the king notice how it is correctly on top the nine in the left image but is incorrectly under the two under the entire stack actually in the right image i also tried alter the layerzposition property as well to no availhow can i bring the card view to the front during the drag i am mystified,['ios'] +272433,calling async task i am streaming a radio stream i want to generate a notification when the song in the stream changes i am using streamscraper to get the metadata of the current stream and i try to generate a notification when the metadata changes here is the async task that i created to implement this public class updatemetadata extends asynctaskstring void playlistsongbaseartist basealbum private static final string tag updatemetadataclassgetsimplename private playlistsongbaseartist basealbum oldsong null private playlistsongbaseartist basealbum newsong null private metadataharvester fetchmetadata new metadataharvester private string streamurl null override protected playlistsongbaseartist basealbum doinbackgroundstring urls for string url urls try oldsong fetchmetadataprepareradiosongurl catch exception e eprintstacktrace streamurl url newsong oldsong while newsong oldsong try newsong fetchmetadataprepareradiosongstreamurl catch exception e eprintstacktrace return newsong override protected void onpostexecuteplaylistsongbaseartist basealbum song logvtag new song songgettitle the application is built on two linked projects project a is where the application is initialised and project b contains the collections and the playing logic i want to use this task in project b here is the play function in project bprotected synchronized void playfinal imediaplayerwrapper mp streamurl streamfetchergetstreamurl logitag stream url streamurl try logitag testing metadata harvester radiosong metadataprepareradiosongstreamurl catch exception e logwtag e updatemetadataradiosong currentplaylistmanagerclearplaylist currentplaylistmanagerappendsongatendradiosong listenerinformerinformcurrentsongchangelistenerradiosong try mpsetsongradiosong streamurl mpplay if mpisplaying setplayerstateplayerstateplay catch exception e logwtag e setplayerstateplayerstateerror updatemetadata metadatachecker new updatemetadata metadatacheckerexecutestreamurl when i try to execute it the application crashes here is the complete error trace0404 233434975 ewindowmanager18080 activity chethzdcgpancho2viewradioplayerradioplayeractivity has leaked window comandroidinternalpolicyimplphonewindowdecorview4053e8f0 that was originally added here0404 233434975 ewindowmanager18080 androidviewwindowleaked activity chethzdcgpancho2viewradioplayerradioplayeractivity has leaked window comandroidinternalpolicyimplphonewindowdecorview4053e8f0 that was originally added here0404 233434975 ewindowmanager18080 at androidviewviewrootinitviewrootjava2580404 233434975 ewindowmanager18080 at androidviewwindowmanagerimpladdviewwindowmanagerimpljava1480404 233434975 ewindowmanager18080 at androidviewwindowmanagerimpladdviewwindowmanagerimpljava910404 233434975 ewindowmanager18080 at androidviewwindowlocalwindowmanageraddviewwindowjava4240404 233434975 ewindowmanager18080 at androidappdialogshowdialogjava2410404 233434975 ewindowmanager18080 at androidaprogressdialogshowprogressdialogjava1070404 233434975 ewindowmanager18080 at androidaprogressdialogshowprogressdialogjava900404 233434975 ewindowmanager18080 at chethzdcgpancho2viewradioplayerradioplayeractivity5onclickradioplayeractivityjava2760404 233434975 ewindowmanager18080 at androidviewviewperformclickviewjava24850404 233434975 ewindowmanager18080 at androidviewviewperformclickrunviewjava90800404 233434975 ewindowmanager18080 at androidoshandlerhandlecallbackhandlerjava5870404 233434975 ewindowmanager18080 at androidoshandlerthispatchmessagehandlerjava920404 233434975 ewindowmanager18080 at androidoslooperlooplooperjava1300404 233434975 ewindowmanager18080 at androidappactivitythreadmainactivitythreadjava36830404 233434975 ewindowmanager18080 at javalangreflectmethodinvokenativenative method0404 233434975 ewindowmanager18080 at javalangreflectmethodinvokemethodjava5070404 233434975 ewindowmanager18080 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava8390404 233434975 ewindowmanager18080 at comandroidinternaloszygoteinitmainzygoteinitjava5970404 233434975 ewindowmanager18080 at dalviksystemnativestartmainnative methodi am confused in my understanding of async tasks is this not the correct way to use themedit answer added separately,['android'] +272434,when to use sqlconnectionclearallpools in c i have noticed that my code errors out on sqlwriteexecutenonquery after executing 200 insert queries in couple of seconds i always thought that using will make sure the resources are reused properly and there will be no need to do anything this is the first time i get this error and i have been dealing with sqlc for almost 3 years doing different thingsusing sqlconnection varconnection localesqlconnectonetimelocalesqldataconnectiondetails using var sqlwrite new sqlcommandpreparedcommand varconnection sqlwriteparametersaddwithvaluevar agr fname var agr fname object dbnullvalue var agr fname sqlwriteexecutenonquery public static sqlconnection sqlconnectonetimestring varsqlconnectiondetails var sqlconnection new sqlconnectionvarsqlconnectiondetails try sqlconnectionopen catch dialogresult result messageboxshownew form topmost true baad poaaczenia z baza danych czy chcesz spra3bowaa nawiazac poaaczenie ponownie baad poaaczenia 01 messageboxbuttonsyesno messageboxiconstop if result dialogresultno if applicationmessageloop applicationexit use this since we are a winforms app else environmentexit1 use this since we are a console app else sqlconnection sqlconnectonetimevarsqlconnectiondetails return sqlconnectionerror message a transportlevel error has occurred when sending the request to the server provider shared memory provider error 0 no process is on the other end of the pipeconsidering advice for this error i should be using sqlconnectionclearallpools to make sure connections are reset or thiscarded properly so i can use it but the question is where to use it and when how to know if the limit is going to break wheres the limit at 50 150 200 or should i use it every single time in a loop,['c#'] +272481,ios uisplitviewcontroller cannot be pushed to uinavigationcontroller i have an xcode ipad project using a navigation controller i tried to get a button to push a uisplitviewcontroller to the navigation stack but got this errorsplit view controllers cannot be pushed to a navigation controllerturns out uisplitviewcontroller does not play nicely with uinavigationcontroller however i still need to show the split view controller when this button is clicked how do i do this and also important how do i make a back button so the user can be returned to the navigation controller,['ios'] +272511,how to build boost required modules only i just started compiling boost c libraries with the following commands i issued it is building whole of the boost libraries which is time consuming and is not necessary for my need just unpacked the boost 1 49 07z archive and from visual studio 2010 command line tool i ran bootstrapbat and it created the b2 executable using this executable i ran b2 toolsetmsvc100 buildtypecomplete architecturex86 addressmodel64 stage to build the librariesat this moment all i need is the signals module to be built what switch commands need to be supplied to the bootstrap created executable to compile and build only those specific libraries,['c++'] +272525,android difference between battery status thischarging and battery status not charging i want to know the difference between the two flags batterymanagerbattery status thischargingandbatterymanagerbattery status not chargingi developed an application that uses these two flags and i expected to see thischarging when i unplugged the phone from the charger but instead it simply says not chargingwhat is the difference between the two,['android'] +272543,signed division in c i was reading the section on c portability in the book c traps and pitfalls by andrew koeningon an integer divisonq abr abif a is a negative number apparently the reminder r can be a negative or positive number while satisfying the property q b r anormally i would expect r to be negative if dividend a is negative and that is what i see in a intel machine with gcc i am just curious have you ever seen a machine that would return a positive reminder when the dividend is a negative number,['c'] +272580,which is a better way to check if an array has more than one element i just need to check if an array has more than one element i am trying to do it this way if issetarr1the other traditional way is if sizeofarr1which of the two is better in such situaions how should i judge between two alternate methodsis there any performance check meter available to measure which is better,['php'] +272582,android viewpager performance issues when using background i have got an activity made by xml i have set it is background to a background image i have in my drawable folderin the same activity i have created a viewpager to allow swiping back and forth between viewsall the views inside the viewpager contain one imagewhenever i swipe left or right the transition is very slowi tried removing the background image by setting it to white f and all the lag was gone it worked perfect the problem is that i do need that background for the applicationis there any way to optimize a background image or something so swiping will go smoothly againcurrently it is too frustrating to use because of the lagi also tried cropping the image to a small size and then just stretched it over the screen but i did not notice any performance improvements also it is not the images fault that are located in the viewpager when i tested it with textviews instead there was the same lag,['android'] +272602,override home and back button is case a boolean is true i was wondering if i can override the action of the back and home button is some cases normally these buttons should just react like they always do but in a case some setting is true i want to override the buttons and let them call my own methodsia m using these two methods to override these buttons override public void onbackpressed call my backbutton pressed method when booleantrue override public void onattachedtowindow thisgetwindowsettypewindowmanagerlayoutparamstype keyguard superonattachedtowindow call my homebutton pressed method when booleantrue,['android'] +272603,how can i denote unused function arguments when deconstructing a tuple i can use to denote tuple elements i am not interested in eg a 123 a1using python 2x how can i express the same with function arguments i tried to use underscores def fa return a file stdin line 1syntaxerror duplicate argument in function definitioni also tried to just omit the argument altogether def fa return a file stdin line 1 def fa return a syntaxerror invalid syntaxis there another way to achieve the same,['python'] +272617,using eventtarget to get element i am basically trying to get the target element from eventtarget and if not equal processhow can i get the below thing to work documentreadyfunction documentclickfunctionevent ifeventtargetcontents if clicked element is not div contents show alert how can i achieve this alert,['jquery'] +272640,actionbarsherlock abs how to customize the text of action mode close item i am using abs vers 4 and i need to simply change the default done text that is thisplayed besides the action mode close icon but i really cannot figure out how to do iti think that text needs to be customizable for at least two good reasonsdone is not appropriate for all contexts eg cancel could be more appropriate and i have seen some apps such as the my files app on galaxy tab use itdone needs to be localized according to the users languageis it possible to do customize that text if so can anyone tell me how to do it thanks in advanceediti have found a temporary workaround that i post in the followingprivate textview getactionmodeclosetextview abs 40 defines action mode close button text only for large layouts if getresourcesgetconfigurationscreenlayout configurationscreenlayout size mask configurationscreenlayout size large retrieves the linearlayout containing the action mode close button text linearlayout action mode close button linearlayout getactivityfindviewbyidridabs action mode close button if found returns its last child in abs 40 there is no other way to refer to it since it does not have an id nor a tag if action mode close button null return textview action mode close buttongetchildataction mode close buttongetchildcount 1 return nullthat is the method i came up with please note that it does heavily rely upon the structure of the abs action mode close itemxml of abs 40this works for my scenario but as you can see it cannot be considered sufficiently satisfying to promote it to a real answer that is why i only edited my previous posthope that helps someone else but i also hope that someone could share a better and cleaner solution,['android'] +272650,jquery validate success event i am using the jquery validate plugin on my site and then submitting the form via ajax is there an event i can use when the entire form is valid,['jquery'] +272657,how to resolve autofac instanceperhttprequest i have registered a component like this in my globalasaxcscontainerbuilder builder new containerbuilderbuilderregistercontrollersassemblygetexecutingassemblybuilderregistertypewebworkcontextasiworkcontextinstanceperhttprequesticontainer container builderbuilddependencyresolversetresolvernew autofacdependencyresolvercontainer this is where my error happens not sure whyvar workcontext containerresolveiworkcontextwebworkcontext classpublic class webworkcontext iworkcontext left out other codeiworkcontext interfacepublic interface iworkcontext left out other codethe error that i am getting isno scope with a tag matching httprequest is visible from the scope in which the instance was requested this generally indicates that a component registered as perhttp request is being reqested by a singleinstance component or a similar scenario under the web integration always request dependencies from the dependencyresolvercurrent or ilifetimescopeproviderrequestlifetime never from the container itselfhow do i get this to work this reason why i want it this way is because the work context handles stuff like getting the current customer etcsome more questions is it wisebest practices to register every at once will the be scenarios that i will need to add more components at another stage,['c#'] +272698,find events that occured xtimes during given period let us say i have following tablecreate table occurences object id int10 not null seen timestamp int10 not null engineinnodb default charsetutf8which contains id of object not unique it repeats and timestamp when this object id has been observedobservation is running 247 and inserts every occurrence of object id with current timestampnow i want to write query to select all object ids which has been seen during any 10 minute period at least 7 timesit should function like detection of intrusionsimilar algorithm is used in denyhost script which checks for invalid ssh loginsif find configured number of occurrences during configured time period it blocks ipany good suggestion,['mysql'] +272701,in what situations would ajax longshort polling be preferred over html5 websockets i am building a small chat application for friends but unsure about how to get information in a timely manner that is not as manual or as rudimentary as forcing a page refreshcurrently i am implementing this using simple ajax but this has the thisadvantage of regularly hitting the server when a short timer elapsesin researching longshort polling i ran across html5 websockets this seems easy to implement but i am not sure if there are some hidden thisadvantages for example i think websockets is only supported by certain browsers are there other thisadvantages to websockets that i should be aware ofsince it seems like both technologies do the same thing in what sorts of scenarios would one prefer to use one over the other more specifically has html5 websockets made ajax longshort polling obsolete or are there compelling reasons to prefer ajax over websockets,['javascript'] +272713,is it valid to define a pure virtual signal in cqt i am making an abstractbaseclass and was thinking i might want a pure virtual signal but when i compiled i get a warning for the pure virtual signals i have definedfile1h27 warning signals cannot be declared virtualfile1h28 warning signals cannot be declared virtualis it valid to define a pure virtual signal in cqt is it valid to define a virtual signalqts signal and slot documentation page says you can define virtual slots but does not talk about signals i cannot seem to find good information on pure virtual signals,['c++'] +272715,c meaning of const charconst in one of the c programs i saw a function prototype int classifiercommandint argc const charconst argvwhat does const charconst argv mean is it the same as const char argvdoes const char argv also mean the same,['c++'] +272731,difference between applemobilewebappcapable and appletouchfullscreen iphone ios meta tags i have a question for which i could not find answer neither in google or directly at apple developer forumwhat is the exact difference betweenmeta nameappletouchfullscreen contentyes andmeta nameapplemobilewebappcapable contentyes,"['iphone', 'html']" +272742,isfinite equivalent what is the c replacement for the following definedefine is finitex 0x7ff0 unsigned shortx 3 0x7ff0maybe doubleisinfinityx false or doubleisnegativeinfinityx falsethanks,"['c#', 'c++']" +272784,getactionbar returns null calling getactionbar returns null this has been frequently reported so i have made sure to include the solutions others have used my minsdkversion11 i do have a titlebar and i am calling getactionbar after setcontentview also my activity is not a child activity setcontentviewrlayoutmain experiment with the actionbar actionbar actionbar getactionbaractionbarhidedevice is a samsung galaxy tab 101 running android 32thanks in advance for any ideas or suggestions,['android'] +272801,how to write simple geometric shapes into numpy arrays i would like to generate a numpy array of 200x200 elements in size and put into it a circle centered into 100100 coordinates radius 80 and stroke width of 3 pixels how to do this in python 27 without involving file operations possibly using geometry or imaging libraries to allow generalisation to other shapes,['python'] +272853,how do i stop my application from zombifying after i handle an uncaught excepition i am handling any uncaught exceptions that occur in my application viathreadsetdefaultuncaughtexceptionhandlerthiswere this is my launcher activity implementing uncaughtexceptionlistener i handle the exception and send it off to my log server just fine however my application then does not end it just runs along as a zombie until the home or back button is pressed how can i kill the process after handling the exceptionedithere is a test and working activity that throws an uncaught exception that is to be caught by thread and handled the toast is never posted and the process goes zombie once the exception is logged class testactivity extends activity implements uncaughtexceptionlistener override public void oncreatebundle icicle superoncreateicicle threadsetdefaultuncaughtexceptionhandlerthis throw new runtimeexceptioni am a destuctive booger setcontentviewrlayoutactivity test override public void uncaughtexceptionthread thread throwable toss logetag an uncaught exception has been recieved toss toastmaketextthis big error toastlength longshow,['android'] +272870,taskfactorystartnew overloads i have got really simple codestatic void mainstring args var task taskfactorystartnewgetint var task2 taskfactorystartnew return getint static int getint return 64why do i get a compiler error for the first taskthe method signatures no params return type is int are equal are not theyi know a solutionwhich is quite simple var task taskfactorystartnewintgetint but i would like to know whats the problem with the code above,['c#'] +272874,conditional statement using bitwise operators so i see that this question has already been asked however the answers were a little vague and unhelpful okay i need to implement a c expression using only the expression needs to resemble a b cso from what i have been able to tell the expression needs to look something likereturn a b a cthis works when a 0 because anding it with b will give zero and then the or expression will return the right side a c which works because 0 gives all ones and anding c with all ones returns chowever this does not work when a 0 can someone try to explain why this is or how to fix it,['c'] +272905,how to programmatically create a true excel file possible duplicategenerating an excel file in aspnet heres my question how do you programmatically create a true excel filenote i do not mean a csv htmlcss or xml file i mean a file written in the same format excel uses to save spreadsheetsbackground i am working on an aspnet application which includes teleriks radgrid were currently using the radgrids exporttoexcel function but some of our customers need to be able to view these exports using excel viewer teleriks function exports an htmlcssbased file which the fullversion of excel can open but excel viewer cannoti am sure its possible to programmatically create a true excel file but i am not sure where to begin is there an sdk which could help me do thisany suggestions would be appreciated thanks in advance,['asp.net'] +272914,how to debug unresponsive page in google chrome i have got a fairly complex javascript application it uses no external frameworks that users are currently testing a couple thousand lines i have been getting reports that users are getting the popup in google chrome sayingthe following pages have become unresponsive you can wait for them to become responsive or kill themthey report that the only way to keep using the app is to open a new chrome window but that the messages comes back up every few minutes and only happens when they try to go to a new page they specifically said that they click to go to a new page and the current page never changes they just see the spinning loading icon for a minute until the popup comes supthe odd thing is that i have tested extensively on the exact version of chrome 18 that these users are having issues with and i have seen no problems i am sort of stumped and do not know where to look now since i have been unable to duplicate it any ideas on where to look next to at least try and figure out what could even be causing that error,['javascript'] +272915,java legal forward referencing is the following code the case of legal forward referencing if yes whypublic class myclass private static int x getvalue private static int y 5 private static int getvalue return y public static void mainstring args systemoutprintlnx,['java'] +272922,how to name the blank value in select i use simple form in my apphow do i give the blank value in my selects a different text than i just find an option to include blank or not,['ruby-on-rails'] +272932,jvm native code compilation crazyness i seem to suffer odd performance penalties for some time even after the code is compiled why issuewhen benchmarking a simple quicksort implementation in java i faced unexpected humps in the n vs time graphics i was plottingi know hotspot will attempt to compile code to native after it seems certain methods are being heavily used so i ran the jvm with xxprintcompilation after repeated trials it seems to be compiling the algorithms methods always in the same way iteration 6 sortingquicksortswap 15 bytes iteration 7 sortingquicksortpartition 66 bytes iteration 7 sortingquicksortquicksort 29 bytesi am repeating the above graphic with this added info just to make things a bit clearerat this point we must all be asking ourselves why are we still getting those ugly humps after the code is compiled maybe it has something to do with the algorithm itself it sure could be and luckily for us there is a quick way to sort that out with xxcompilethreshold0bummer it really must be something the jvm is doing in the background but whati theorized that although code is being compiled it may take a while until the compiled code actually starts to be used maybe adding a couple of threadsleeps here and there could help us a bit sorting this issue outouch the green colored function is the quicksorts code ran with a 10ms internal between each run details in the appendix while the blue colored function is our old one just for comparison at fist giving time to the hotspot only seems to make matters worse maybe it only seems worse by some other factor such as caching issuesthisclaimer i am running 10 trials for each point of the shown graphics and using systemnanotime to measure the resultseditsome of you may at this stage wonder how the use of sleep might thistort the results i ran the red plot no native compilation again now with the sleeps inbetweenscaryappendixhere i present the quicksort code i am using just in casepublic class quicksort public t extends comparablet void sortint table quicksorttable 0 tablelength 1 private static t extends comparablet void quicksortint table int first int last if first last there is data to be sorted partition the table int pivotindex partitiontable first last sort the left half quicksorttable first pivotindex 1 sort the right half quicksorttable pivotindex 1 last author sort private static t extends comparablet int partitionint table int first int last int pivotindex first last 2 int pivotvalue tablepivotindex swaptable pivotindex last int storeindex first for int i first i last i if tableipivotvalue 0 swaptable i storeindex storeindex swaptable storeindex last return storeindex private static t void swapint a int i int j int h ai ai aj aj h as well the code i am using to run my benchmarkspublic static void mainstring args throws interruptedexception ioexception quicksort quicksort new quicksort int trials 10 file file new filelongtostringsystemcurrenttimemillis systemoutprintlnsaving filegetabsolutepath for int x 0 x 30 x if x 4 x 17 threadsleep10 int values new intx long start systemnanotime for int i 0 i trials i quicksortsortvalues double duration systemnanotime start trials string line x t duration systemoutprintlnline fileutilswritestringtofilefile line rn true,['java'] +272950,c template class with static members same for all types of the class if you have a template class with a static variable is there any way to get the variable to be the same across all types of the class rather than for each oneat the moment my code is like this template typename t class templateclass public static int numberalive templateclass thisnumberalive templateclass thisnumberalive template typename t int templateclasstnumberalive 0and maintemplateclassint t1templateclassint t2templateclassbool t3cout t1 t1numberalive endlcout t2 t2numberalive endlcout t3 t3numberalive endlthis outputs t1 2 t2 2 t3 1where as the desired behaviour is t1 3 t2 3 t3 3i guess i could do it with some sort of global int that any type of this class increments and decrements but that doesnt seem very logical or objectorientedthank you anyone who can help me implement this,['c++'] +272971,why should i use entity framework codefirst if it cannot be used in production safely and things like indexes cannot be described i am just starting out an extremely large web project and really trying to do everything rightmy tools using so far areaspnet mvc 3 entity framework 43ninject 3all is going well but i am finding a few things with entity framework codefirst a bit sketchyfor example i had to use to setup membership information as part of the code first setup this feels a bit ropey to have to use something third party of this obviously i should be 1337 enough to roll my own but i do not want to bite off too much from the get go running aspnet regsql feels horrible and will get lost with each db update anyway got it all working with the above library and it is not too bad scaffolding seems to have broken howevernow beyond all this it now seems that this stuff is going to become probamatic when i am running in the live environment any schema changes i am going to want to make between the dev db and live db will have to be manually managed with scripts anyway so at that point am i not losing the point of code firsti have been working with google app engine for the last year and was hoping that code first would essentially work in the same way ie make changes and they modify the live data now i assume due to not having done severe refactoring in app engine that it basically does not harm anything in production so you could never rename a table with appengine it would always create a new table and leave the old one you would have to manually port dataso i am now thinking why not just go database first i have been working with linq2sql for 3 years and very comfortable with going db first although tbh my db source control stratergy has been a littlelacking so i was hoping code first would enforce that situation to improve but it actually makes me feel that i should go db first and just be strict about keeping it under controli would really appreciate any thoughts on this kind of situation and also how does this compare to using nhibinate,['c#'] +272978,point of sale and inventory database schema iam trying to create a basic point of sale and inventory management systemsome things to take into accountthe products are always the same same id through the whole system but inventory available units for sale per product is unique per location location y and z may both have for sale units of product x but if for example two units are sold from location y location zas inventory should not be affected its stocked units are still intactselling one 1 unit of product x from location y means inventory of location y should subtract one unit from its inventoryfrom that i thought of these tableslocationsidnameproductsidnametransactionsiddescriptioninventories headeridlocation idproduct idinventories detailinventories idtransaction idunit costunit pricequantityorders headeriddatetotal calculated from orders detail quantity price just for future data validationorders detailorder idtransaction idproduct idquantitypriceokay so are there any questions of coursehow do i keep track of changes in units cost if some day i start paying more for a certain product i would need to keep track of the marginal utility costquantity pricequantity marginal utility some way i thought of inventories detail mostly for this i wouldnat have cared otherwiseare relationships well stablished i still have a hard time thinking if the locations have inventories or if inventories have several locations itas maddeninghow would you keepknow your current stock levels since i had to separate the inventory table to keep up with cost updates i guess i would just have to add up all the quantities stated in inventories detailany suggestions do you want to shareiam sure i still have some questions but these are mostly the ones i need addressing also since iam using ruby on rails for the first time actually as a learning experience itas a shame to be stopped at design not letting me punch through implementation quicker but i guess thatas the way it should bethanks in advance,['ruby-on-rails'] +272993,showing sum in last row of table using mysql i have the following table elements how do i run a query that reproduce the table but hav an extra row at the bottom showing the sum of col2col1 col2 water 22 water 3 water 5 air 10 earth 3 air 5,"['mysql', 'sql']" +273064,how to extract file extension from byte array i have got bytes array in databasehow to extract file extension mimetype from byte array in java,"['java', 'sql']" +273080,is it necessary to call super encodewithcoder when subclassing a object that implements nscoding i know that when you write the initwithcoder method of a subclass of an object that implements nscoding you have to call super initwithcoder instead of super init but do i have to call super encodewithcoder in the implementation of encodewithcoder,['objective-c'] +273088,interpolate constant not variable into heredoc php definemy const 100 echo myecho pthe value of my const is my constpmyechoif i put a variable inside the braces it prints out but not the constant how can i do itthanks,['php'] +273094,default profile in spring 31 in my application i have beans annotated with profileprod and profiledemothe first one as you can guess is used on beans that connect to production db and second one annotates beans that use some fake db hashmap or whatever to make development fasterwhat i would like to have is default profile prod that will be used always if it is not overridden by somethingelseperfect would be to have in my webxmlcontextparam paramnamespringprofilesactiveparamname paramvalueprodparamvaluecontextparamand then override this with dspringprofilesactivedemo so that i could domvn jettyrun dspringprofilesactivedemo but sadly this is not working any idea how could i achive that setting dspringprofilesactiveprod on all my environments is not an option,['java'] +273115,jquery ajax statuscode else in a jquery ajax call i am currently handling statuscode of 200 and 304 but i also have error defined to catch any errors that could come back if there is a validation message related we return the status code of 400 bad request this then falls into the error function before falling into the statuscode 400 function i had defined which means two actions happenideally i would like to not define error and success and only define statuscode but what i need is to have a else so that i do not need to declare every statuscode that exists only the 23 i want to handle differentlyajax type post contenttype applicationjson url apiemployeessvc employeeid company companyid data jsonstring statuscode 200 function employee company saved now updated hideloading showalertmessagesavesuccessful 20 manageemployeedialogclose 304 function nothing to save to employee company hideloading manageemployeedialogclose if nothingtochange employee showalertmessagenothingtoupdate 20 else showalertmessagesavesuccessful 20 error function xmlhttprequest textstatus errorthrown ajaxerrorxmlhttprequest textstatus errorthrown,"['javascript', 'jquery']" +273123,sample code for unit testing api controllers is there an sample code that shows unit testing a controller that inherits from the api controlleri am trying to unit test a post but it is failing i believe i need to set up the httpcontrollercontext for testing but do not know howthanks,['.net'] +273129,how to replace string in all documents in mongo i need to replace a string in certain documents i have googled this code but it unfortunately does not change anything i am not sure about the syntax on the line bellowpulpdb dbgetsisterdbpulp databasevar cursor pulpdbreposfindwhile cursorhasnext var x cursornext xsourceurlreplacea b is this correct dbfooupdate id x id xi would like to add some debug prints to see what the value is but i have no experiences with mongodb shell i just need to replace this source url httpaxy with source url httpbxy,['javascript'] +273175,javascript count number of columns in a table row i have a table similar totable idtable1tr tdinput typetext value td tdinput typetext value td tdinput typetext value td tdinput typetext value tdtrtr tdinput typetext value td tdinput typetext value td tdinput typetext value td tdinput typetext value tdtrtablei want to count the number of td element in a row i am trying documentgetelementbyidcellslengthdocumentgetelementbyidlengthdocumentgetelementbyidgetelementsbytagnametdlengthit did not show actual result,"['javascript', 'html']" +273200,filling a path with a gradient on ios on a cashapelayer i have drawn a closed uibezierpath i can fill this shape by setting the fillcolor however i want to fill the shape with a gradient how can i set up the cagradientlayerso it clips to the shape outlined by the bezier path,['ios'] +273212,how to determine if user is an administrator even if nonelevated in my c application i need to check if the current user is a member of the administrators group it needs to be compatible with both windows xp and windows 7currently i am using the following codebool isadministrator get windowsidentity identity windowsidentitygetcurrent windowsprincipal principal new windowsprincipalidentity return principalisinrolewindowsbuiltinroleadministrator the problem is that this method returns false if the application is run on windows 7 with uac turned on as a nonelevated administrator how can i determine if the user is an administrator even if the application is run as a nonelevated administrator,"['c#', '.net']" +273216,getting classcastexception when trying to insert relativelayout dyanmically setcontentviewrlayoutmain2 out new arraylisttextview llay relativelayout findviewbyidridthisplaypoll relativelayoutlayoutparams lparams new relativelayoutlayoutparamslayoutparamsfill parent layoutparamsfill parent relativelayoutlayoutparams lparams1 new relativelayoutlayoutparamslayoutparamsfill parent layoutparamsfill parent layoutparams lpar new layoutparamslayoutparamswrap content layoutparamswrap content logvmyrched outaddnew textviewthis outget0setlayoutparamslpar outget0setid1 lparams1addrulerelativelayoutalign bottomriduser name llaysetlayoutparamslparams1 outget0settexttitle 0n my pollthisllayaddviewoutget0 for int i 1 i 3imjsonarraylength i outaddnew textviewthis outgetisetlayoutparamslpar outgetisetidi1 logvmyhey outgeti1getid lparamsaddrulerelativelayoutbelowoutgeti1getid llaysetlayoutparamslparams outgetisettexttitle in llayaddviewoutgeti logvmyrasaschedby executing the program i am getting this error0406 203049372 eandroidruntime1093 fatal exception main0406 203049372 eandroidruntime1093 javalangclasscastexception androidwidgetrelativelayoutlayoutparams0406 203049372 eandroidruntime1093 at androidwidgetscrollviewonmeasurescrollviewjava3010406 203049372 eandroidruntime1093 at androidviewviewmeasureviewjava81710406 203049372 eandroidruntime1093 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava31320406 203049372 eandroidruntime1093 at androidwidgetframelayoutonmeasureframelayoutjava2450406 203049372 eandroidruntime1093 at androidviewviewmeasureviewjava81710406 203049372 eandroidruntime1093 at androidwidgetlinearlayoutmeasureverticallinearlayoutjava5260406 203049372 eandroidruntime1093 at androidwidgetlinearlayoutonmeasurelinearlayoutjava3040406 203049372 eandroidruntime1093 at androidviewviewmeasureviewjava81710406 203049372 eandroidruntime1093 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava31320406 203049372 eandroidruntime1093 at androidwidgetframelayoutonmeasureframelayoutjava2450406 203049372 eandroidruntime1093 at androidviewviewmeasureviewjava81710406 203049372 eandroidruntime1093 at androidviewviewrootperformtraversalsviewrootjava8010406 203049372 eandroidruntime1093 at androidviewviewroothandlemessageviewrootjava17270406 203049372 eandroidruntime1093 at androidoshandlerthispatchmessagehandlerjava990406 203049372 eandroidruntime1093 at androidoslooperlooplooperjava1230406 203049372 eandroidruntime1093 at androidappactivitythreadmainactivitythreadjava46270406 203049372 eandroidruntime1093 at javalangreflectmethodinvokenativenative method0406 203049372 eandroidruntime1093 at javalangreflectmethodinvokemethodjava5210406 203049372 eandroidruntime1093 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava8680406 203049372 eandroidruntime1093 at comandroidinternaloszygoteinitmainzygoteinitjava6260406 203049372 eandroidruntime1093 at dalviksystemnativestartmainnative methodthis is the xml file i m using relativelayoutandroidididthisplaypollandroidlayout widthfill parentandroidlayout heightfill parentandroidbackgrounddrawableback blue gradandroidpadding0dp textview androidididuser name androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparenttoptrue androidlayout centerhorizontaltrue androidtextpriyank bharad androidtextcolorf androidtextsize28dp androidtextstylebold imageview androidididp image androidlayout width35dp androidlayout height35dp androidlayout marginright10dp androidsrcdrawablefinal fb androidlayout toleftofiduser namerelativelayoutscrollview,['android'] +273240,getting local ip address i am trying to get the local ip address of my android device using mono for android but failingthe code i use for the full and compact framework is thisvar iplist from a in dnsgethostaddressesdnsgethostname where aaddressfamily addressfamilyinternetwork select atoarraylocaladdress iplist0under m4a however it falls down early the dnsgethostname call fails withsystemnetsocketssocketexception an address incompatible with the requested protocol was usedis there a known issue with dnsgethostname under m4a is there an alternate way to get the local address using m4a,['c#'] +273242,unix what happens when a read file descriptor closes while calling select say that i call select on a fd set containing a bunch of read file descriptors what happens if during the select call one of the file descriptor closes assuming that some sort of error occurs then is it my responsibility to find and remove the closed file descriptor from the set,['c'] +273248,php save session when using session write close i have one page where i do a long polling i have to use at the begin of this page thissession startsession write closebecause to prevent concurrent writes only one script may operate on a session at any timeso if i do not and the long polling is running the user will not be able to load another pageso accessing to my data in session from this polling page is possible but at some point in my script i have to save my session back to the server because i made some change in itwhats the way to do itthat will be very nice it will be a way to do something likesession write opendo stuffsession write closebut the session write open does not existthanks,['php'] +273272,including c 11 headers with clang llvm i have installed clang and llvm from source and am trying to compile some c code using features of the new standardi have found that while for example the use of for ranges eg for i vector works fine i am having trouble cannot find header file when i need to import a header eg unordered set or tupledo i need to use the new libc to use these headers or is there just a simple build change i need to make at the moment i have just built clang and llvm into a folder in my home directory and am calling clang from there,['c++'] +273293,how to prevent chrome fetching the last 128 bytes of an mp3 file i am having a problem with this for a while now so i thought i would ask for your helpfor a proof of concept project i created a html 5 only lastfm player using jplayer it works fine with firefox but does not play using the html solution when using chromechromiumfirst chrome tries to fetch the mp3 file via the stream url after it has prebuffered a bit it always tries to read the last 128 bytes by making another http requestthe problem now is that the lastfm streaming servers only seem allow one connection per file at a time which causes both http connections to failit seems chromechromium is ignoring the preloadnone property of the audio tag as far as i could find out the tag is only a recommendation to the browsernormal mp3 files work like a charm also when entering the redirected streaming url in the browser it starts playing it seems lastfm is using the original urls as kind of onetime access tokenaccess control filter whereas the resolved stream url is valid for a whilefor the full http headers cookies censored see copied from chromium element inspectoris there any way to circumvent this problem from within the browser,['jquery'] +273314,add property to expandoobject with the same name as a string is there a way to add a property to an expandoobject with the same name as a string valuefor example if i havestring propname productnumberdynamic obj new systemdynamicexpandoobjecti can create the property productnumber likeobjproductnumber 123but can i create the property objproductnumber based on the string propname so if i do not know what the name of the property will be in advanced i can create it based on this input if this is not possible with expandoobject any other areas of c i should look into,['c#'] +273324,css backgroundcolor only inside the margin i have searched for an answer but could not find it anywhere my question is reasonably simple i have a background color of my body then a large margin and now i want a different background color inside the marginhow do i do that with css,"['html', 'css']" +273339,does applegoogle provide specifications for ical field support in ios or android i am attempting to publish a proprietary software calendar via ical using the ddayical package if that matters so that customers can view their appointments on their phone or tablet or in any other piece of software that supports ical such as outlook or google calendar unfortunately it seems that the ical spec provides support for a lot of fields that go unused by these consumers such as comment status categories class and so on and right now i am shooting in the dark trying to figure out what is supported and where it gets thisplayed on the devicedoes apple or google or microsoft publish a list of the ical fields that they support,"['android', 'ios']" +273349,service locator dependency injection and container and inversion of control i have been programming for some time but never got interested in knowing in theory what each concept means i may be using a variety of programming concepts but without knowing itservice locatorfor me refers to a record of shortcuts to speed up development by reducing the amount of code one question is may locator refer to namespacesclasses only or i can have a registry of variableshere is my understanding of itlocator new servicelocatorlocatorsetapp new systemapplicationlocatorsetdb new systempdo get the objectslocatorgetdbconnectlocatorgetapprundependency injection and dependency injection containerinjecting objects within objects allowing faster access to these regardless of the factory pattern and di containerhere is my understanding of itapp new systemapplicationsystemconfigloadinversion of controldo not understand this design pattern or understand but do not know if what i do is iocthen in theory preferably with simple examples what does each of these concepts mean am i correct or what is wrong can be improvedthanks,['php'] +273355,g error using flto option i am trying to enable link time optimization in g my program compiles fine without the flto option when i add it to my makefile the object files compile without errors egg maincpp i includes stdc0x fopenmp wall pedantic wnovla flto d info c o objmainobut when it comes to link the programg fwholeprogram i includes stdc0x fopenmp wall pedantic wnovla flto d info objmaino objatomo objbeeo objcolonyo includesobjerroro includesobjcmdlineo includesboost lib deblibboost program optionsa includesgmp lib debliblibgmpxxa includesgmp lib debliblibgmpa o beebenchi get a lot of errors like theseincludesgmp lib debliblibgmpxxa includesgmp lib debliblibgmpa o beebenchtypeinfo for boostprogram optionstoo many positional options error referenced in section rodata ztvn5boost15program options33too many positional options errorevtable for boostprogram optionstoo many positional options error of includesboost lib deblibboost program optionsacmdlineo defined in thiscarded section gnulinkoncet ztin5boost15program options33too many positional options errore of objmaino symbol from plugintypeinfo for boostprogram optionstoo many positional options error referenced in section rodata ztin5boost16exception detail19error info injectorins 15program options33too many positional options erroretypeinfo for boostexception detailerror info injectorboostprogram optionstoo many positional options error of includesboost lib deblibboost program optionsacmdlineo defined in thiscarded section gnulinkoncet ztin5boost15program options33too many positional options errore of objmaino symbol from plugintypeinfo for boostprogram optionsinvalid command line style referenced in section rodata ztvn5boost15program options26invalid command line styleevtable for boostprogram optionsinvalid command line style of includesboost lib deblibboost program optionsacmdlineo defined in thiscarded section gnulinkoncet ztin5boost15program options26invalid command line stylee of objmaino symbol from plugini cannot figure out what is going wrong i compile all my object files using flto the libs namely boost and gmp are compiled without flto option is this causing the error the gcc manual says that its ok to mix object files compiled with without flto option or am i missing something else for example what is this plugin the error is speaking abouti am using g 463 on debian wheezyupdateas adviced in the comments i made a minimal example the code of my test program is only thisinclude boostprogram optionshppint main int argc char argv return 0when i compile it usingg o test i includes wall stdc0x testcpp flto fwholeprogram staticit gives similar errors as described above if i omit the static flto or stdc0x option it compiles without errors the fwholeprogram option does not change the result i now also tested with g 47 same errorany suggestions is this really a compiler error or am i still doing something wrong,['c++'] +273356,packaging a net application so it will run on a computer without net i have been recently trying to deploy a c application on a computer that does not have net installedi know that there have been many questions around the same topic here on stackoverflow here are a few of them of which i read the responses to allpackaging up the net framework with a net application deploymentrun a net application without installing net client profilerun c windows application in windows xp without installing net frameworkso all of the responses to the above questions state that it is impossible without specific software etc one software mentioned was the salamander net linker the only problem with that is that i cannot seem to be able to run the application after it has been processed by salamender i understand that this in itself is impossible as it requires the net virtual machine to run however in the past i have made java applications and along with them i shipped the entire jvm surprisingly they still worked so the reason why this is not a duplicate of the above questions is because my true question is what items of the net framework would i need to package if i do manage to package all would placing them in the same directory as the application i am running allow the application to runi found one solution to this the microsoft net rethist package the only problem with this is that it has a gui of its own aside from that it would be a perfect fit so could anyone tell me one of two things is there a commandline net package and if so where do i download itif there is not or it would be impractical to do so approximately what directories would i need to copy from the net installationsi understand that these files and directories are system specific and that my net installation may not work on your computer but if c is like java then this should be achievable is it size is not a limitation it does not matter to me whether or not the application and all its files is 1gb or if it is only 1mb if in case there is no other solution i used dependency walker to check all the dependencies of my program if i were to package most of them would my application in theory work,"['c#', '.net']" +273366,how do i get coverage for view specs with rspec rails and simplecov i have a project in which i am using rails 323 rspec 290 and simplecov 061 all seem to be the latest gemsi am getting code coverage results for my controllers and models but not my views i have tried adding the group in my simplecov setupsimplecovstart rails do add group views appviewsendand even explicitly saying i want erb files includedsimplecovstart rails do add group views appviewserbendbut no dice the views group is there in my coverage results but no files are listed therehas anyone gotten this working,['ruby-on-rails'] +273384,ajax form using simple form with preserved error validation this might be one of the more difficult questions i have asked but i have been stuck for a few days and i thought it would be best to get support from the more experienced rails community i am working on a dummy app that follows this guide roughly ajaxjquery tutorial making my own customizations the guide helped me to create a brand includes nested models model submodel and style submission form using simple form and brands listing on the same page this works perfectly and the validation for my models is enforced however when i put the form and brand listing on the same page i lose the neat inline validation errors that were appearing on submission failure see image below not being able to get the inline errors to work has made me realize that i have more to learn about rendering and that is why i am fixated on finding the answer to this question and here is the listingbelow is the controller for the index action def index this is for the product listing brands brandallreverse this is for the form brand brandnew model modelnew submodel submodelnew style stylenew respond to do format formathtml end endthe above form creates the brand model submodel and style for use in the nested submission form below is the code for the form simple form for brand html class formhorizontal remote true do m fieldset style margintop34px legendlegend minput name label brand msimple fields for models model do p pinput name label model psimple fields for submodels submodel do s sinput name label submodel ssimple fields for styles style do ss ssinput name label style end end end div classformactions msubmit nil class btn btnprimary link to cancel brands path class btn div fieldset end now as you can see i am using remote true i would like for the form to either create the new brand or for the form to reload with inline validation errors at the moment my create action looks likedef create brand brandnewparamsbrand respond to do format if brandsave formathtml redirect to brands url notice brand was successfully created formatjson render json brand status created location brand formatjs else formathtml render action index formatjson render json branderrors status unprocessable entity formatjs render reload end end endthe code that appears under if brandsave seems to work but the code below else does not work the way i would like so what is happening when brand does not save i believe that the code within the index action is being run then branderrors is converted to json which i assume is for the simple form validation errors and then reloadjserb is being run in an attempt to reload the form with validation errors i have put the line entryformloadlocationhref entryform into reloadjserb when i put invalid data into my form reloadjserb is being called but all that happens is that the form fields reload blank instead of having the data entered and inline validation errors i hope i have provided enough info here to get help really struggling on this one thanks,"['jquery', 'ruby-on-rails']" +273386,how do i bind new elements using knockout how can i bind a new element create after the page has loadedi have something like thissystem function thishello function alerthello thismakeui functioncontainer div documentcreateelementdiv divinnerhtml button databindclick helloclickbutton koapplybindingsnew systemif i try this thismakeui functioncontainer div documentcreateelementdiv divinnerhtml button databindclick helloclickbutton koapplybindingsnew systemdiv but according to these posts it will not work,['javascript'] +273417,burmese speech to text conversion in android can we add custom language for recognizerintenti have search many so question like is there a speech to text api by googlethat solve my problem of using limited number of language during speech to text conversionmy problem is that i need to used burmeselocal language of burma speech and convert it to text any other help can be appreciatedupdate googles servers currently support english mandarin chinese and japanese speech input api for android,['android'] +273498,how to to manage develop big typo3 projects i am developing typo3 projects since 2006 now and projects are getting bigger and more complex setting up a simple cms site with a contact form and news listing is all routineright now we finished a bigger project a platform for an international company with countless extensionslogin registration news listing database records dynamic contact forms surveys statistics intranet functions document upload download several backend tweaks per tca modifications etc the project managers got upset at us developers because sometimes after we finished on function x and later committed function y to the dev server function x was broken this was related to typoscript settings extension interdependencies versioning errors or sometimes simple programming mistakes and typosi know how to take care of the latter but in general from your experience how can we develop an errorproof system in typo3 where everything works in hand and extensions do not get in their way in other words how can we secure and isolate functionalities extensions and avoid those interdepency issueswe are working in a dev team with two developers and we already usesubversion repositorylocal dev server for development testingexternal typoscript configuration files split into single files for each extensionedit for bountyhunters what i am looking for is a bestpracticesummary that might include these topicsgeneral workflow habitsgeneral coding habitsreliability of our subversion commits or gitunit testing phpunit seleniumdeployment i have not yet figured out how automated deployment canhelp ustyposcript best practices,['php'] +273509,when a child element overflows horizontally why is the right padding of the parent ignored given this simple structurediv idparent div idchildlorem ipsumdivdivwith this cssparent width 200px height 200px padding 20px overflowx scrollchild width 500px live demo notice that the parent has a 20px padding and that the child overflows horizontally because it is wider if you scroll the parent all the way to the right youll see that the child touches the right edge of the parentso the parent should have a right padding but it is ignored it seems that when the child has a fixed width the right padding of the parent does not apply is this specified by a standard i would love to know please let me know if you find anythingis there a way to force the right padding to be applied in this scenario without having to remove any of the elements from the flow by floating or positioningscreenshot 1 the right padding is ignored this is how all current browsers behave screenshot 2 the right padding applies this is what i am trying to accomplish btw the screenshot is from ie7 which is the only browser which does not ignore the right padding,"['html', 'css']" +273515,sscanf newlines i need to parse a response from a server like thisrisposta200nlen 1040nexpire 30nn1n1n1ni am trying with sscanfsscanfrisposta dnlen dnexpire dnns0 risptype risplen rispexpire risprisorsabut it puts only 1 in risprisorsahow to resolve ps struct risptypedef struct server risp int type int expire int len int sup int inf char risorsa50 server risp,['c'] +273519,python 27 on system pip and virtualenv still using 26 how do i switch them to use 27 i am on macosx 1068 and i have python 27 installedpython v producespython 272 v2728527427914a2 jun 11 2011 152234 gcc 421 apple inc build 56 dot 3 on darwintype help copyright credits or license for more informationdlopenlibraryframeworkspythonframeworkversions27libpython27libdynloadreadlineso 2import readline dynamically loaded from libraryframeworkspythonframeworkversions27libpython27libdynloadreadlinesoi them run virtualenv venvand then venvbinactivateand do a python vand i getpython 261 r26167515 jun 24 2010 214749 gcc 421 apple inc build 5646 on darwintype help copyright credits or license for more informationdlopenusersnkhdevvenvlibpython26libdynloadreadlineso 2import readline dynamically loaded from usersnkhdevvenvlibpython26libdynloadreadlinesocan someone tell me the steps to use have virtualenv create and use python 27 from my system or have virtualenv use python 27 period i do not care if the version is my system version,['python'] +273521,middleware soa by example i am an inexperienced java developer trying to wrap my head around some fundamental middlewaresoa concepts and technologies specificallyserviceoriented architecture soamessageoriented middleware mommessage queueapache camelmuleejbsendpoints routesservice busesbjmsafter looking each of these up onlineon wikipedia i was able to get for the most part decent definitions for each of these what i am not understanding is how all of these technologiesconcepts work together on the backend to provide a 2ndbusiness tier solutioncan someone please give an example of an architecture that would use all of these technologiesconcepts and explain what role each of them play in the overall solution once i see a working example i am sure it will help me connect most of the dotsedit since i added the bounty i have had several answers that suggest reading books although i appreciate all feedback here i simply cannot part ways with 300 reputation points for an answer that essentially boils down to rtm especially when i am flat broke and cannot afford the manual to reiterate the bounty and definitive answer will go to someone who can hit all of these bullets in a meaningful practical example this does not have to be a middleware compendium just a paragraph or two that shows how all these can be used together in harmony to produce a java businesstier solution thanks again,['java'] +273536,concurrent c11 which toolchains can be used i use thread atomic mutex etc heavily in my code which includes several lockfree algorithms i am targeting eventually a linux environment i have been developing with the visual studio 2011 beta which while lacking horribly in other c11 features seems to be the only toolchain that implements the concurrent featuressee c 11 support hereclang 3gcc 47msvc 11now if the others simply lack a library containing the c 11 concurrent features i can easily use justthread however both clang and gcc answer no to the c11 memory model which at least visual c seems to support i am not exactly sure what the effect of this would be probably optimizing away of apparently side effect free code among other erroneous thingsif for now i completely avoid optimized builds and compile only debug builds without optimizations enabled is it reasonable to use the clang or gcc toolchain,['c++'] +273561,extend traits with classes in php why we are not allowed to extend traits with classes in phpfor exampletrait t class c use t or class c extends t is there any potential conflict for such syntax i do not think so,['php'] +273597,how can i get vidpid from usb flash drives in c i need to perform a check on all drives and see if any of the vidspid match a specific one if it does i need to get the drive letter of that flash drivethanks to all,['c#'] +273604,accessing items in a ordereddict lets say i have the following codeimport collectionsd collectionsordereddictdfoo pythondbar spamis there a way i can access the items in a numbered manner like d0 foos outputd1 bars output,['python'] +273631,transparent jpanel i want to create a semitransparent jpanel i have done it by simply using rgba value of color constructor but problem is when i m using event handling is not woking properly my requirement is a semi transparent jpanel when mouse enters it border of this panel became visible and if mouse exit the border shoud not visible i have done this by following code but problem is its not working properly for transparent backgroud rgba but it working fine for rgb color import javaxswingimport javaxswingborderimport javaawtimport javaawteventpublic class mdcw extends jframe private jpanel contentpane launch the application public static void mainstring args eventqueueinvokelaternew runnable public void run try mdcw frame new mdcw framesetvisibletrue catch exception e eprintstacktrace create the frame public mdcw setdefaultcloseoperationjframeexit on close setbounds100 100 1013 551 contentpane new jpanel contentpanesetbackgroundnew color0 139 139 contentpanesetbordernew emptyborder5 5 5 5 setcontentpanecontentpane contentpanesetlayoutnull final jpanel panel new jpanel panelsetbackgroundnew color0 0 050 paneladdmouselistenernew mouseadapter override public void mouseenteredmouseevent e panelsetbordernew linebordernew color255 255 255 5 override public void mouseexitedmouseevent e panelsetbordernull panelsetbounds360 155 215 215 contentpaneaddpanel final jpanel panel 1 new jpanel panel 1setbackgroundnew color0 0 0 panel 1addmouselistenernew mouseadapter override public void mouseenteredmouseevent e panel 1setbordernew linebordernew color255 255 255 5 override public void mouseexitedmouseevent e panel 1setbordernull panel 1setbounds84 155 215 215 contentpaneaddpanel 1,['java'] +273638,how do i fix undefined reference to imp i am trying to compile something that depends on gtkspell whichdepends on enchant under mingw i am getting errors like gtkspellgtkspellc757 undefined reference to imp enchant broker initi suspect this is either due to the fact that i am trying to linkagaint a staticdynamic library when i should be linking against theother one or because there is only one underscore before the imp andthere should be two i get objdump t doptenchant160liblibenchanta grep enchant broker init 85sec 1fl 0x00ty 20scl 2 nx 0 0x02ac0 enchant broker initand objdump t doptenchant160liblibenchantdlla grep enchant broker init 6sec 1fl 0x00ty 0scl 2 nx 0 0x0 enchant broker init 7sec 3fl 0x00ty 0scl 2 nx 0 0x0 imp enchant broker initthe internetsuggests that the imp mangling comes from declspecdllimportexportthough enchant seems to use declspecdllimportexport and commenting out the relevant lines in enchanth makes gtkspellcrequest enchant broker init rather than imp enchant broker init butdoes not change the symbols that show up in libenchant is there a wayto make gcc not mangle the names or does anyone have ideas about whatmight be going wronghow to fix itheres a minimal example that reproduces the problem on my systemif i have a file enchanttest1c with contentsinclude stdiohinclude enchanthint mainifdef enchant module export printfnenchant foundnelse printfnenchant not foundnendif return 0and a file enchanttest2c with contentsinclude stdiohinclude enchanthint main enchantbroker b enchant broker initifdef enchant module export printfnenchant foundnelse printfnenchant not foundnendif return 0thengcc enchanttest1c pkgconfig cflags enchant aexegives enchant found butgcc enchanttest2c pkgconfig cflags enchant aexegivescusersjasong1appdatalocaltempccydlptcotestenchantctext0xf undefined reference to imp enchant broker initcollect2 ld returned 1 exit status,['c'] +273644,mysql replace backslash in strings i am having the following problemi have a table t which has a column name with names the names have the following structureabcyou can create on yourself like thiscreate table t name varchar10insert into t values abcselect from tnow if i do thisselect name from t where name abcthat does not work i need to escape the backslashselect name from t where name abcfinebut how do i do this automatically to a string namesomething like the following would not do itselect replaceabc i get abcany suggestions many thanks in advance,['mysql'] +273675,android draw circle around text i have a textview with a single character in it all single digit numbers 0 9 i would like to draw a circle or a square around the number i saw a thread mention using a ninepatch to style around it but i am unsrure of how to do this or if it is the best way to do it how can i have a circle around the number thanks,['android'] +273703,mvvm execute command on viewmodel from other viewmodel i am struggling for about 14 days now with a simple task in database i have definitions for hardware categories for example hddinternalexternalflashthis list is in database defined like this id parrentid name 1 0 hdd 2 1 internal 3 1 external 4 1 flash through entity framework i get these rows into my application from this flat data i then create structured object which is my datamodel this model is defined as follows public class category private int id 1 private string name private listcategory subcategories null property getters and setters constructors and bool hassubcategories now from these i create viewmodel called subcategoryviewmodel to which is binded my treeview so i can view my categories in treeview and with my defined and maintained hierarchy this works just fine in subcategoryviewmodel is defined a command through attached behavior for mousedoubleclick which is also binded to treeview so when user doubleclicks on item in subviewcategorymodel defined method will execute particular code list of subcategoryviewmodel is nested in hwdocumentviewmodel which is a main viewmodel for my window what i need now is obvious when user doubleclicks on item in treeview i need to load items from database and show them in listview my opinion is that in hwdocumentviewmodel i need to define an collection of items and load them accordingly to selected category in listview but i do not know how to execute a method on hwdocumentviewmodel from subcategoryviewmodel because treeview is binded to list of subcategoryviewmodel items so when doubleclick occurs the method on subcategoryviewmodel is executed i am searching for a way how to execute a method on main viewmodel hwdocumentviewmodel i tried this approach i created a property public static subcategoryviewmodel selectedcategory on hwdocumentviewmodel when doubleclick occurs i set this property from subcategoryviewmodel as this so in this property is object which executed doubleclick event delegate great now i have in hwdocumentview model an object which user selectedso i need to load items to listview but will i load them from method in subcategoryviewmodel i do not think so instead i should load them from main view model by creating a viewmodel for them and bind it to listview right but how can i from subcategoryviewmodel call a method in hwdocumentviewmodel should i write a static methodon a hwdocumentviewmodel which will be accessible from subcategoryviewmodel or is there a way how to call command defined on hwdocumentviewmodel from subcategoryviewmodel or generally did i take a right approach to create a warehouselike application in wpf thanks a lotedit xaml for my treeview looks like this treeview xnametvcategories backgroundwhite itemssourcebinding categories treeviewitemcontainerstyle style targettypextype treeviewitem setter propertyisexpanded valuebinding isexpanded modetwoway setter propertyisselected valuebinding isselected modetwoway setter propertyfontweight valuenormal setter propertybehaviorsmousedoubleclickcommand valuebinding mousedoubleclickcommand setter propertybehaviorsmousedoubleclickcommandparameter valuebinding styletriggers trigger propertyisselected valuetrue setter propertyfontweight valuebold trigger styletriggers style treeviewitemcontainerstyle treeviewresources hierarchicaldatatemplate datatypextype localvmsubcategoryviewmodel itemssourcebinding children stackpanel orientationhorizontal textblock textbinding categoryname stackpanel hierarchicaldatatemplate treeviewresources treeview,['c#'] +273745,duplicate file in amazon s3 i am trying to duplicate a file from a bucket to another but i cannot seam to see the new file on the destination bucketi am getting no errors at allrequestresponsexml version10 encodingutf8copyobjectresult xmlns lastmodified20120408t1126360zlastmodified etagquota5f9084078981b64737b57dbf1735fcfquotetagcopyobjectresultbut i keep checking the last modified date on s3 and i cannot find any information about this new file either i can access it directly content faviconicowhat am i doing wrongmethodpublic void duplicatefileincloudstring original string destination try copyobjectrequest request new copyobjectrequest if originalstartswithhttp could be from other bucket url will show all data example string bucket getbucketnamefromurloriginal jkv30 key getkeyfromurloriginal predefinedfilesfavicons002ico requestwithsourcebucketbucket requestwithsourcekeykey else same bucket copypaste operation requestwithsourcebucketthisbucketname requestwithsourcekeyoriginal requestwithdestinationbucketthisbucketname requestwithdestinationkeydestination requestcannedacl s3cannedaclpublicread using amazons3 client amazonawsclientfactorycreateamazons3clientthisaccesskey thissecretaccesskey s3response response clientcopyobjectrequest responsethispose catch amazons3exception s3exception throw s3exception,['c#'] +273750,converting nsnumber to nsinteger i am trying to determine what a value is in an array and then implement changes on the array but i cannot access the array in the first placensnumber row nsnumber numberwithintrecognizerviewtag nsinteger newrow row integervalue nsinteger index selecteditems indexofobjectrow0not selected 1selected nslog row if index 0 selecteditems removeobjectatindexnewrow selecteditems insertobject1 atindex newrow uitableviewcell recognizerview setaccessorytypeuitableviewcellaccessorycheckmark else selecteditems removeobjectatindex newrow selecteditems insertobject0 atindex newrow uitableviewcell recognizerview setaccessorytypeuitableviewcellaccessorynone as you can see i am trying to get information from the row variable which is a nsnumber and find the value of the array with the index variable also i declared this in my onloadselecteditems nsarray arraywithobjects 0 0 0 nilthe problem is that i get all of these warnings sayingincompatible integer to pointer conversion initializing nsinteger aka int with an expression of type nsuinteger aka unsigned int whenever i use the varaibles row or newrow as you can see newrow is just row as an integer what am i doing wrong,"['iphone', 'objective-c']" +273751,call cc from d language how to call c function from d programi still cannot understand how to do itwhat commands do i need to executei use dmd in fedora,"['c++', 'c']" +273754,c combobox with text and value possible duplicatec winforms combobox with label and value how would one approach storing a thisplay value and a real value in a comboboxie the combobox thisplaysdestroy worldfire slingshotsummon cthulhubut the values as retrieved aredwscvisual studio net 20 please additional detailsi want to be able to retrieve the value of the selected item in a way similar to thisstring selectedvalue combobox1selectedvaluebut they need to see a more user friendly string in the combobox itselfhow it is been donedictionarystring string filteritems new dictionarystring string destroy world dw fire slingshot fs summon cthulu scthisoptions filterbydatasource new bindingsourcefilteritems nullthisoptions filterbythisplaymember keythisoptions filterbyvaluemember valuenow for some reason although the thisplaymembers are absolutely fine for some amount of time after the program loads the valuemembers return dictionary objectsprivate void options filterby selectedindexchangedobject sender eventargs e messageboxshowoptions filterbyselectedvaluetostringthis returns dictionaries for the first few times i change the selected item of the combobox but eventually returns strings as neededthe fixin response to the above problem the fix is to set the thisplaymember and valuemember properties before the datasource i presume this is a bugthe code should readthisoptions filterbythisplaymember keythisoptions filterbyvaluemember valuethisoptions filterbydatasource new bindingsourcefilteritems null,['c#'] +273777,javascript smooth scroll without the use of jquery i am coding up a page where i only want to use raw javascript code for ui without any interference of plugins or frameworksand now i am struggling with finding a way to scroll over the page smoothly without jqueryhope somebody could guide me the way,"['javascript', 'html']" +273791,how to add a new row to datagridview programmatically if add row to datatabledatarow row datatable1newrowrowcolumn2column2rowcolumn6column6datatable1rowsaddrowhow about datagridview,['c#'] +273817,how can i access my localhost server from other computers i am new to php so i do not know how to explain it i am running wamp on my computer and i would like to be able to access my localhost from another computer is it possible how can i do this,['php'] +273821,running profile startup files in an embedded ipythoninstance i want to use an embedded ipython shell with a user ns dictionary and a my profile configuration ipython configpy and the startup files the purpose is to run a django shell with models imported on startup djangoextensions implements a command called shell plus that does this extensionsmanagementcommandsshell pluspyfrom ipython import embedembeduser nsimported objectsthe problem is that this does not load my startup files embed calls load default config which i figure loads ipython configpy how do i make the embedded ipython instance run my profile startup files,['python'] +273832,php dependency injection i am trying to get my head around dependency injection and i understand it for the most parthowever say if for some reason one of my classes was dependent on several classes instead of passing all of these to this one class in the constructor is there a better more sensible method i have heard about di containers is this how i would go about solving this problem where should i start with this solution do i pass the dependencies to my dic and then pass this to the class that needs these dependencies any help that would point me in the right direction would be fantastic,['php'] +273837,modules assemblies headers in clr i have been reading clr with c 30 and i have been reflecting on assemblies modules and headers however things got complicated this is what i understood but if would be great if someone can clarify things little bit moremodules are result of cscexe which contains il code and metadata tables metadata tables contains three different tables which aredefinition tables such as moduledef typedef propertydef methoddef eventdef fielddefreference tables such as typeref moduleref memberrefetcmanifest tablesassemblies are containers which contain many modules as well as resources such as images docs pdf etcpe files that stands for portable executable are files can be exe or dll these files have pe32 or pe32 headers clr headers metadata il codethe books says assembly is a container consists of modules and it also says managed module is managed modulea managed module is a standard 32bit microsoft windows portable executable pe32 file or a standard 64bit windows portable executable pe32 file that requires the clr to executerichter jeffrey 20100205 clr via c kindle locations 696697 oreilly media a kindle editiondefinition of assemblyan assembly is a logical grouping of one or more modules or resource filesrichter jeffrey 20100205 clr via c kindle locations 766767 oreilly media a kindle editionso it seems that managed module are actually part of the assembly in the image taken from the same bookpe32 headers belong to assemblies however author also says it belongs to managed modules as well etcwhats the separation here why did he use module and assemblies interchangeable even thought they look separate enougha managed pe file has four main parts the pe32 header the clr header the metadata and the il the pe32 header is the standard information that windows expects the clr header is a small block of information that is specific to modules that require the clr managed modulesrichter jeffrey 20100205 clr via c kindle locations 16281629 oreilly media a kindle editionalso the image clearly shows that modules have only metadata not pe32 clr headers etc do you think manifest and metadata can be used interchangeablyand also could you please explain manifest tables in the modules as well,"['c#', '.net']" +273838,mod explanation today i was writing an program in c and i used to calculate some index my program didt work so i debuged it and i realized that is not working like in other program languages that i knowfor examplein python returns values like thisfor x in xrange 5 6 print x 5 x 55 5 04 5 13 5 22 5 31 5 40 5 01 5 12 5 23 5 34 5 45 5 0in cfor int i 5 i 6 i consolewritelinei 5 i 55 5 04 5 43 5 32 5 21 5 10 5 01 5 12 5 23 5 34 5 45 5 0my question isdid i done something wrong or is not working like it should,['c#'] +273869,google chrome extension manipulate dom of open or current tab ok javascriptjquery i got that i can work with that to do what i want in general however what i am trying to do currently is work with the dom of the opencurrent tab and i am wondering if that is possible or is all the work i do with an extension limited to the html i provide it with a backgroundhtml or equivalentfor todays attempt at taking a strike at a google extension i want to take images on a page and store them in an array to create a slide show like effect from it via a bar i want to add to the bottom of the page appending it to the existing dom of the opencurrent tab i then want hide elements in the dom til the bar is closedso my first question is is something like this possible can i manipulate the dom in such a way and read from it,"['javascript', 'jquery']" +273886,mockito matcher and array of primitives with mockito i want to verify a method call with byte in its argument list but i did not find how to write this mymethod byte i just want something like anybytearray how to do that with mockito,['java'] +273905,how to maintain jtable cell rendering after cell edit you guys were so awesome in point me in the right direction on my last question and i have sort of an extension of my original question herehow to set a jtable column as string and sort as doubleas i now have my price column formatted as 0 by using my custom cell renderer i have now set up a jtextfield editor for the cell as well the editing of the cell works just fine except for when the value is updated the number format set in my custom renderer no longer seems to format the cell i am loosing the after edit is committed is this renderer not supposed to render the cells even after the initial thisplay of the datai have tried to use the following with no luckabstracttablemodel tablegetmodelfiretabledatachangedi was hoping that this would force the table to revalidate and repaint the cells using the custom renderer to render the new values but this unfortunately did not workam i missing something obviously but what,['java'] +273910,aws dynamodb and mapreduce in java i have a huge dynamodb table that i want to analyze to aggregate data that is stored in its attributes the aggregated data should then be processed by a java applicationwhile i understand the really basic concepts behind mapreduce i have never used it beforein my case let us say that i have a customerid and ordernumbers attribute in every dynamodb item and that i can have more than one item for the same customer likecustomerid 1 ordernumbers 2customerid 1 ordernumbers 6customerid 2 ordernumbers 1basically i want to sum the ordernumbers for each customerid and then execute some operations in java with the aggregate aws elastic mapreduce could probably help me but i do not understand how do i connect a custom jar with dynamodb my custom jar probably needs to expose both a map and reduce functions where can i find the right interface to implementplus i am a bit confused by the docs it seems like i should first export my data to s3 before running my custom jar is this correctthanks,['java'] +273920,fixed point arithmetic in c programming i am trying to create an application that stores stock prices with high precision currently i am using a double to do so to save up on memory can i use any other data type i know this has something to do with fixed point arithmetic but i cannot figure it out,['c'] +273964,download file inside webview i have a webview in my android application when user goes to webview and click a link to download a file nothing happens url my urlmwebview webview findviewbyidridwebviewmwebviewsetwebviewclientnew hellowebviewclientmwebviewgetsettingssetdefaultzoomzoomdensityfarmwebviewloadurlurllogvtheurl urlhow to enable download inside a webview if i thisable webview and enable the intent to load the url on broswer from application then download works seamlesslystring url my urlintent i new intentintentaction viewisetdatauriparseurlstartactivityican someone help me out here the page loads without issue but the link to a image file in the html page is not working thanks in advance for your time,['android'] +273977,how to start an android activity from a unity application i know this seems to be a trivial question but i could not find any concrete answer anywhere on the internet i saw this very similar question on stackoverflow how to start unity application from android activity but it is exactly opposite from my question additionally the android activity must be able to receive some input strings from the unity application much like how one use system calls with line arguments to start another program on a pcthe following is the code i have for a test button event handler for my test unity app on androidprivate void externalappcallhandler ifapplicationplatform runtimeplatformwindowseditor procestartcprogram files x86notepadnotepadexe else ifapplicationplatform runtimeplatformandroid procestartinternet when i use unity editor to test the application successfully opens notepadexe when i click on the test button however when i tried to open the internet app on my samsung galaxy s2 device it failed does anyone knows why this is the case what should be the correct string for opening another android application using procestart,"['c#', 'android']" +274007,how to trim a b c into a b c possible duplicatehow do i replace multiple spaces with a single space in c what is the most elegant way how to trim whitespace in strings like amany spacesb c into a b c so repeated whitespace is shrunk into one space,"['c#', '.net']" +274048,why cannot we create our own ostream object if cout is an object of ostream class then why cannot we declare our own object say out from the same class ie is not the following code supposed to workincludeiostreamusing namespace stdint main ostream out outsomethingor otherwiseincludeiostreamusing namespace stdint main ostream withassign out outsomething,['c++'] +274134,should memory usage increase when using elementtreeiterparse when clearing trees import osimport xmletrelementtree as etfor ev el in etiterparseossysstdin elclearrunning the above on the odp structure rdf dump results in always increasing memory why is that i understand elementtree still builds a parse tree albeit with the child nodes cleared if that is the cause of this memory usage pattern is there a way around it,['python'] +274162,can a c struct be defined multiple times i have read in several places that a c struct can safely be defined multiple times and yet i get a redefinition of struct error from gcc for multiply defining a struct through multiple includes a very simplified example looks like thisfoocinclude ahinclude bhint mainint argc char argv struct bar b ba 2 return 0ahstruct bar int a int bbhinclude ahstruct buz int x int yif i run gcc fooc i getin file included from bh10 from fooc2ah18 error redefinition of astruct baraah18 note originally defined herei know i have not put any include guards and those will fix the compile error but my understanding was that this should work nonetheless i also tried two struct bar definitions in fooc and i get the same error message so can structs be defined mutiple times in c or not,['c'] +274177,chrome extension to modify pages script includes and js i work on a javascript library that customers include on their site to embed a ui widget i want a way to test dev versions of the library live on the customers site without requiring them to make any changes to their code this would make it easy to debug issues and test new versionsto do this i need to change the script include to point to my dev server and then override the load method that is called in the page to add an extra parameter to tell it what server to point to when making remote callsit looks like i can add js to the page using a chrome extension but i do not see any way to modify the page before it is loaded is there something i am missing or are chrome extensions not allowed to do this kind of thing,['javascript'] +274202,nokogiri recursively get all children the problemi am running some statistics against various urls i want to find the top level element with the most concentrated number of children the method that i would like to follow is to identify all top level elements and then determine what percentage of all the elements on the page belong to itgoalrecursively get all children of a given elementinputs a nokogiri elementoutputs an array of nokogiri elements or the count of total number of childrensetupruby 192nokogiri gemwhat i ended up coming up with this works but is not as pretty as my chosen answer belowgetchildcountelem children elemchildren return 0 unless children and childrencount 0 child count childrencount childreneach do child child count getchildcountchild end child countend,['ruby'] +274241,phpunit not continuing with tests after fatal error when using processisolation i have a phpunit test suite that is currently causing a fatal error due to a class definition that is not being found this ultimately is a failure of the testing code itself and a failure by the developer to vindicate the test itself before committing code however things like this do happen from time to time and it would be wonderful if when a fatal error occurs regardless of whos ultimately responsible the test simply be marked as a failure and the remainder of the test suite still be executedi have read about the processisolation switch and as far as i can tell it should take care of this since each test runs in a separate process if the child dies due to a fatal error the parent can still continue to run in fact this is stated explicitly in this answer to a similar question which shows the exact type of output i would like to see myselfhowever i seem to get the exact same output regardless of whether or not i use the processisolation flagwithout process isolationkogiphagocyte usrbinphpunit colors verbose coveragehtml targetcoverage appzendtestsapplicationphp fatal error class rmd database oldobject not found in homekogiappzendprivatemodelstranslatepollphp on line 9php stack tracephp 1 main usrbinphpunit0php 2 phpunit textui commandmain usrbinphpunit46php 3 phpunit textui commandrun usrsharepearphpunittextuicommandphp130php 4 phpunit runner basetestrunnergettest usrsharepearphpunittextuicommandphp150php 5 phpunit framework testsuiteaddtestfiles usrsharepearphpunitrunnerbasetestrunnerphp96php 6 phpunit framework testsuiteaddtestfile usrsharepearphpunitframeworktestsuitephp419php 7 phpunit util fileloadercheckandload usrsharepearphpunitframeworktestsuitephp358php 8 phpunit util fileloaderload usrsharepearphpunitutilfileloaderphp79php 9 include once usrsharepearphpunitutilfileloaderphp95php 10 require once homekogiappzendtestsapplicationtranslatepolltestphp11fatal error class rmd database oldobject not found in homekogiappzendprivatemodelstranslatepollphp on line 9call stack 03 91584 1 main usrbinphpunit0 076 612672 2 phpunit textui commandmain usrbinphpunit46 076 613744 3 phpunit textui commandrun usrsharepearphpunittextuicommandphp130 00246 1249464 4 phpunit runner basetestrunnergettest usrsharepearphpunittextuicommandphp150 00706 1626680 5 phpunit framework testsuiteaddtestfiles usrsharepearphpunitrunnerbasetestrunnerphp96 01691 8053584 6 phpunit framework testsuiteaddtestfile usrsharepearphpunitframeworktestsuitephp419 01693 8057320 7 phpunit util fileloadercheckandload usrsharepearphpunitframeworktestsuitephp358 01694 8057664 8 phpunit util fileloaderload usrsharepearphpunitutilfileloaderphp79 01711 8240600 9 include oncehomekogiappzendtestsapplicationtranslatepolltestphp usrsharepearphpunitutilfileloaderphp95 01805 9187768 10 require oncehomekogiappzendprivatemodelstranslatepollphp homekogiappzendtestsapplicationtranslatepolltestphp11with process isolationkogiphagocyte usrbinphpunit colors verbose coveragehtml targetcoverage processisolation appzendtestsapplicationphp fatal error class rmd database oldobject not found in homekogiappzendprivatemodelstranslatepollphp on line 9php stack tracephp 1 main usrbinphpunit0php 2 phpunit textui commandmain usrbinphpunit46php 3 phpunit textui commandrun usrsharepearphpunittextuicommandphp130php 4 phpunit runner basetestrunnergettest usrsharepearphpunittextuicommandphp150php 5 phpunit framework testsuiteaddtestfiles usrsharepearphpunitrunnerbasetestrunnerphp96php 6 phpunit framework testsuiteaddtestfile usrsharepearphpunitframeworktestsuitephp419php 7 phpunit util fileloadercheckandload usrsharepearphpunitframeworktestsuitephp358php 8 phpunit util fileloaderload usrsharepearphpunitutilfileloaderphp79php 9 include once usrsharepearphpunitutilfileloaderphp95php 10 require once homekogiappzendtestsapplicationtranslatepolltestphp11fatal error class rmd database oldobject not found in homekogiappzendprivatemodelstranslatepollphp on line 9call stack 03 91752 1 main usrbinphpunit0 076 612824 2 phpunit textui commandmain usrbinphpunit46 076 613896 3 phpunit textui commandrun usrsharepearphpunittextuicommandphp130 00246 1250360 4 phpunit runner basetestrunnergettest usrsharepearphpunittextuicommandphp150 00708 1627528 5 phpunit framework testsuiteaddtestfiles usrsharepearphpunitrunnerbasetestrunnerphp96 01688 8054296 6 phpunit framework testsuiteaddtestfile usrsharepearphpunitframeworktestsuitephp419 01690 8057992 7 phpunit util fileloadercheckandload usrsharepearphpunitframeworktestsuitephp358 01691 8058336 8 phpunit util fileloaderload usrsharepearphpunitutilfileloaderphp79 01707 8241296 9 include oncehomekogiappzendtestsapplicationtranslatepolltestphp usrsharepearphpunitutilfileloaderphp95 01801 9188464 10 require oncehomekogiappzendprivatemodelstranslatepollphp homekogiappzendtestsapplicationtranslatepolltestphp11for those of us that cannot effectively diff in our heads the two outputs are literally identical other than the execution time and memory usage which is negligibly differentin both cases the fatal error kills the entire test suite in this particular case this happens in the 3rd test and the remaining 150 tests in several other filessuites are never executedwhat am i doing wrong here is there some other way to survive a fatal error marking the test as failed in one test and still execute remaining testsediti am using phpunit 3610editcomments on the answer to this question have inspired a new ticket on phpunit is github page,['php'] +274246,precautions to take to prevent memory leaks due to added event handles i am going to make a gui that will have dynamically created sets of controls with events assigned to them i will need to add and remove those controls at runtime it will look like thisflowlayoutpanelcontrolsclear add new controls assigning click events with i have heard that assigning event handlers with can cause memory leaks more specificly memory will not be freed until application has exited i want to avoid this i know i can write some functions like here how to remove all event handlers from a control to find all event handlers and remove them but it looks very complex is there another way does calling thispose help remove those event handlers can you destroy objects to force their memory to be freed like in ccthanksps problem is i dont know what event to detach i will create lots of labels and add different kinds of onclick events to them when its time to clean the flow layout panel there is no way to know what event handler was attached to which labelthis is the example code flowlp is a flowlayoutpanel this refresh function is ran multiple times before the application exits private void refresh label l random rnd new random what code should i add here to prevent memory leaks flowlpcontrolsclear l new label ltext 1 if rndnext3 0 lclick method1 if rndnext3 0 lclick method2 if rndnext3 0 lclick method3 flowlpcontrolsaddl l new label ltext 2 if rndnext3 0 lclick method1 if rndnext3 0 lclick method2 if rndnext3 0 lclick method3 flowlpcontrolsaddl l new label ltext 3 if rndnext3 0 lclick method1 if rndnext3 0 lclick method2 if rndnext3 0 lclick method3 flowlpcontrolsaddl l new label ltext 4 if rndnext3 0 lclick method1 if rndnext3 0 lclick method2 if rndnext3 0 lclick method3 flowlpcontrolsaddl l new label ltext 5 if rndnext3 0 lclick method1 if rndnext3 0 lclick method2 if rndnext3 0 lclick method3 flowlpcontrolsaddl l new label ltext 6 if rndnext3 0 lclick method1 if rndnext3 0 lclick method2 if rndnext3 0 lclick method3 flowlpcontrolsaddl,['c#'] +274252,difference between two arrays i have following two arrays i want the difference between these two arrays that is how can i find the values that do not exist in both arrays array1array 0 64 1 98 2 112 3 92 4 92 5 92 array2array 0 3 1 26 2 38 3 40 4 44 5 46 6 48 7 52 8 64 9 68 10 70 11 72 12 102 13 104 14 106 15 92 16 94 17 96 18 98 19 100 20 108 21 110 22 112,['php'] +274262,handling regex escape replacement text that contains the dollar character string input hello worldstring pattern worlduniversestring replacement 1string result regexreplaceinput pattern replacementhaving the following example the result would be hello world as the 1 gets replaced with the first group worlduniverse however the result i want is hello 1the regexescape method is meant to be used to escape a regex pattern not the replacement as it can escape other characters like slashes and other regex pattern characters the obvious fix to my problem is to have my replacement equal to 1 and will achieve hello 1 but i was wondering if the dollar sign is the only value i have to escape assuming replacement is user generated and i do not know it ahead of time or is there a helper function that does this alreadydoes anyone know of a function to escape the replacement value that regexreplacestring input string pattern string replacement uses,['c#'] +274298,unable to get blueimpjqueryfileupload plugin to work am trying use this jquery plugin for cross domain image uploads jqueryfileuploadi think the plugin uses requirejs which i have already included because i use it load javascript code for my pagethe plugin doesnt seem to required that i include requirejs but when i test my page i getthis erroruncaught error mismatched anonymous define module function undefined can someone please point me in the right direction,['jquery'] +274305,is there a way to give promocoupon codes for people to download your app for free i need a way to share my app to allow people to download it for free with a coupon code or promo code or checkout code i would like to post the code to a board and invalidate it after some time my app uses licensing and inapp billing so mailing the apk may not be appropriate the last question i saw regarding this was 6 months old so i did not know if there was a newer solution available,['android'] +274327,why does my d3 forcedirected graph not thisplay edges i created a simple forcedirected graph using d3 why are the edges of the graph not showing here is my entire html file you could also see it and tinker with it by going to view source on my linked page of course it is based on the example from the d3 websitedoctype htmlhtml head titleforcedirected layouttitle script typetextjavascript srcd3v2jsscript style typetextcssdivnode borderradius 6px width 12px height 12px margin 6px 0 0 6px position absolutedivlink position absolute borderbottom solid 9 1px height 0 webkittransformorigin 0 0 moztransformorigin 0 0 mstransformorigin 0 0 otransformorigin 0 0 transformorigin 0 0 style head body div idchartdiv script typetextjavascriptvar width 960 height 500var color d3scalecategory20var force d3layoutforce charge120 linkthistance30 sizewidth heightvar svg d3selectchartappendsvg attrwidth width attrheight heightd3jsonnewjsonjson functionjson force nodesjsonnodes linksjsonlinks start var link svgselectalinelink datajsonlinks enterappendline attrclass link stylestrokewidth functiond return mathsqrtdvalue var node svgselectallcirclenode datajsonnodes enterappendcircle attrclass node attrr 5 stylefill functiond return colordgroup callforcedrag nodeappendtitle textfunctiond return dname forceontick function linkattrx1 functiond return dsourcex attry1 functiond return dsourcey attrx2 functiond return dtargetx attry2 functiond return dtargety nodeattrcx functiond return dx attrcy functiond return dy script bodyhtmlshould not var link thisplay the edges my json file is also pretty simplenodes namemyrielgroup1 namenapoleongroup1 namenapoleongroup2 links source1target0value1 source1target0value1 source1 target2 value1,['javascript'] +274352,mysql char varchar character sets storage sizes wondering how much actual storage space will be taken up by these two datatypes as the mysql documentation is slightly unclear on the mattercharm m a w bytes 0 m 255 where w is the number of bytes required for the maximumlength character in the character setvarcharm varbinarym l 1 bytes if column values require 0 a 255 bytes l 2 bytes if values may require more than 255 bytesthis seems to imply to me that given a utf8encoded database a char will always take up 32 bits per character whilst a varchar will take between 8 and 32 depending on the actual byte length of the characters stored is that correct or does a varchar imply an 8bit character width and storing multioctet utf8 characters actually consumes multiple characters from the varchar or does the varchar also always store 32 bits per character so many possibilitiesnot something i have ever had to worry this much about before but i am starting to hit inmemory temp table size limits and i do not necessarily want to have to increase mysqls available pool for the second time,['mysql'] +274380,how to see whether include inheritable permissions is unchecked for a file or folder i am writing a little utility in c to make sure a specified folder and all of its contents have appropriate access rights i want to give the authenticated users group full access the following code seems to work properly for updating the top level folders acl access control listsecurityidentifier allusers new securityidentifierwellknownsidtypeauthenticatedusersid nullinheritanceflags iflags inheritanceflagscontainerinherit inheritanceflagsobjectinheritfilesystemaccessrule newrule new filesystemaccessruleallusers filesystemrightsfullcontrol iflags propagationflagsnone accesscontroltypeallowdirectoryinfo info new directoryinfofolderpathdirectorysecurity security infogetaccesscontrolsecurityaddaccessrulenewruleinfosetaccesscontrolsecurityi have noticed however that this new access rule does not propagate to subfolders that have the include inheritable permissions a option unchecked in their security properties that only makes sense so what i want to do is turn security permission inheritance back on for any such subfoldersmy digging has uncovered the objectsecuritysetaccessruleprotection method which should be half of what i need however it seems sloppy to just blindly use the above method on objects that already inherit their parents dacl thus i want to determine which objects have their permission inheritance turned off but i cannot seem to find the corresponding method or property which returns this information is there one am i missing something here,"['c#', '.net']" +274381,dynamically create bootstrap alerts box through javascript i am using bootstrap 20 for my project and i would like to dynamically add bootstrap alert box in my page i want to do something likebootstrapalertwarninginvalid credentials,['javascript'] +274411,doublepositive infinity floatpositive infinity i triedsystemoutprintlndoubleisinfinitefloatpositive infinitysystemoutprintlndoubleisinfinitefloatnegative infinityand the output wastruetrueso this means infinity is the same for both data types,['java'] +274414,where to code inorder to override backbonesync i want to override backbonesync i have already asked this but the problem is i do not quite get it i need to know where to put the codes if i were to override the sync function if i put it on the model like thismodel backbonemodelextend sync then how should i call it if i were to use the save method also i need to change the methodmap of create from post to put temporarily i resorted to this create put actually editing the backbonejs file iknow its not good before i forgot i also need to add thissendauthentication function xhr xhrsetrequestheaderauthorization auth as a beforesend parameter since my server has authentication again where should i do it where should i go and put the codes in my model in my collection or in my views any help thank youupdatealso can i override the sync on my collection i mean can i have something like thiscollection backbonecollectionextend sync,['javascript'] +274440,how to count the number of columns in a table using sql how to count the number of columns in a table using sqli am using oracle 11gplease helpt,['sql'] +274470,why does a push back on an stdlist change a reverse iterator initialized with rbegin according to some stl documentation i found inserting or deleting elements in an stdlist does not invalidate iterators this means that it is allowed to loop over a list from begin to end and then add elements using push fronteg in the following code i initialize a list with elements a b and c then loop over it and perform a push front of the elements the result should be cbaabc which is exactly what i getstdliststdstring testlisttestlistpush backatestlistpush backbtestlistpush backcfor stdliststdstringiterator itlist testlistbegin itlist testlistend itlist testlistpush frontitlistfor stdliststdstringconst iterator itlist testlistbegin itlist testlistend itlist stdcout itlist stdendlwhen i use reverse iterators loop from rbegin to rend and use push back i would expect similar behavior ie a result of abccba however i get a different resultstdliststdstring testlisttestlistpush backatestlistpush backbtestlistpush backcfor stdliststdstringreverse iterator itlist testlistrbegin itlist testlistrend itlist testlistpush backitlistfor stdliststdstringconst iterator itlist testlistbegin itlist testlistend itlist stdcout itlist stdendlthe result is not abccba but abcba that is right there is one additional c addedit looks like the first push back also changes the value of the iterator that was initialized with rbegin after the push back it does not point anymore to the 3rd element in the list which was previously the last one but to the 4th element which is now the last onei tested this with both visual studio 2010 and with gcc and both return the same resultis this an error or some strange behavior of reverse iterators that i am not aware of,['c++'] +274560,can not connect to facebook with a curl request i have created a simple facebook application some weeks ago i was getting user information through the facebook api by asking permission from the users but it stopped working last week out of nothing and i have been looking for an answer since thenbasically i used to use file get contents to get the user information from facebook api but i tried changing it to curl after it started failing but still not working i tried using the facebook phpsdk even debugged the code to makerequest method but i get the same return in all methodswhen a curl request is made to facebook open graph url the request fails either with error number 7 or 28 they are both error codes for unable to connect to the site or getting time outmy site is on a shared hosting i have tried using curl to get other sites and it works fine but when i try to get even curl returns falsethe hosting has ssl certificate has curl enabled etc and it was working fine some time ago i have read through various threads and posts about this tried many different curl options and none of them seem to workany ideasindexphpauth url id app id redirect uri urlencodeglobalscanvas page scopepublish streamemailsigned request postsigned requestlistencoded sig payload explode signed request 2data json decodebase64 decodestrtrpayload trueif emptydatauser id echoscript toplocationhref auth url script else sessionoauth token dataoauth token sessionuser id datauser id user new user sessionuser id sessionoauth tokenuser classfunction constructfid at thisfacebook new facebookarray appid app id secret facebook secret id thisfid fid thistoken at if data thisgetgraph public function getgraph session thisfacebookgetuser if session try access token thisfacebookgetaccesstoken attachment arrayaccess token access token result thisfacebookapi thisfid get attachment result thisfacebookapi thisfid get return result catch facebookapiexception e return false notesafter checking the facebook php sdk methods i have realized that i do not need to send access token as it will set it if access token is not in the paramsit goes down to makerequest method in sdk and returns false from the curl exec,['php'] +274562,how to get depth of current node in jtree i have a jtree with a few nodes and subnodes when i click on a node i want to know on which depth is it 0 1 3 how can i know that selected nodegetdepth does not return the depth of current node,['java'] +274576,print a table from an html page i have a html page from which a table needs to be sent to a printer i am using windowprint right now but that prints the whole page while i need to print just the table any ideas,"['javascript', 'html']" +274580,check if a webservice exists could someone please be kind enough to show me the best way to determine if a webservice aspnet exists at a given url i assume an approach will be something along the lines of issuing a request using systemnetwebclient but how could i determine if it is a valid webservice and what sort of request should i issueedit to add a bit more context i am determining if a webservice exists because i am attempting to build a generic tool that uses arbitrary webservices,"['asp.net', '.net']" +274604,c dictionary how to add multiple values for single key i have created dictionary object dictionarystring liststring dictionary new dictionarystringliststringi want to add string values to the list of string for a given single keyif the key does not already exists then i have to add a new key liststring is not predefined i mean i did not create any list object and then supplied to dictionaryaddkeylistname how to create dynamically this list object in dictionaryaddkeylistname and then add strings to this list if i have to add 100 keys then do i have to create 100 lists before executing dictionaryadd instruction and also do i have to pedefine the contents of this lists thank you,['c#'] +274623,dynamically create type and call constructor of baseclass i need to create a class dynamically most things work fine but i am stuck in generating the constructorassemblybuilder assemblybuilder appdomaincurrentdomaindefinedynamicassemblynew assemblynamemybuilder assemblybuilderaccessrunmodulebuilder modulebuilder assemblybuilderdefinedynamicmodulemymodulepublic static object getinstancetsource teventargsthis tsource source string eventname where tsource class var typename mytypename var typebuilder modulebuilderdefinetypetypename typeattributesclass typeattributespublic create type like class myclass generictypemyclass tsource teventargs var basenotgenerictype typeofgenerictype var basetype basenotgenerictypemakegenerictypetypebuilder typeoftsource typeofteventargs typebuildersetparentbasetype the base class contains one constructor with string as param var basector basenotgenerictypegetconstructorbindingflagsnonpublic bindingflagsinstance null new typeofstring null var ctor typebuilderdefineconstructormethodattributespublic callingconventionsstandard callingconventionshasthis new type0 var ilgenerator ctorgetilgenerator i want to call the constructor of the baseclass with eventname as param ilgeneratoremitopcodesldarg 0 push this ilgeneratoremitopcodesldstr eventname push the param ilgeneratoremitopcodescall basector ilgeneratoremitopcodesret var type typebuildercreatetype return on call of the constructor i am getting a badimageformatexception what am i doing wrongas requestedthe baseclass looks something like thispublic abstract class generictypegt teventsource teventargs baseclass where gt generictypegt teventsource teventargs new where teventargs eventargs where teventsource class protected generictypestring eventname eventname eventname what i would like to have as a result in runtimepublic class mytype baseclassmytype concretesourcetype concreteeventargstype protected mytype basesomename,['c#'] +274642,print keys of nsdictionary instead of values i download some content from a json webserviceis it possible print the keys and not the values instead for the eventuality of not knowing what the keys are,['ios'] +274654,knockoutjs how do i bind to a sub property i know how to bind to a property but how do i bind to a property likeparentchildusing the hello world example on knockout jscomhtmlpfirst name input databindvalue firstname pplast name input databindvalue lastname ph2hello span databindtext fullname spanh2h2childproperty span databindtext parentpropertychildproperty spanh2javascriptvar viewmodel functionfirst last thisfirstname koobservablefirstthislastname koobservablelastthisparentproperty koobservable childproperty i am a child property thisfullname kocomputedfunction knockout tracks dependencies automatically it knows that fullname depends on firstname and lastname because these get called when evaluating fullname return thisfirstname thislastname thiskoapplybindingsnew viewmodelplanet earthi would like to create a binding to the childpropertyi created a jsfiddle herethanks,['javascript'] +274657,no unexpired provisioning profiles found that contain any of the keychains signing certificates horror i have seen a few other questions that addressed this topic but none like mine yesterday i innocently added a device to the list of devicesquestioni am under the impression that once you add a device it will now be linked to the provisioning profile however i believe it was not linked to one of my thistribution profiles so i went into edit the profile clicked the checkmark next to the device and hit submit this is where the problems begani notice two things i recently renewed my certificateprovisioning profiles about a week ago now it thinks i renewed my provisioning profile yesterday or at least it says so in the organiser also when i try to build any project i get the awful no unexpired provisioning profiles found that contain any of the keychains signing certificates in the build settings my signing identity shows up under identities without provisioning profiles i have read horror stories of people having to tear everything down and rebuild and i hope i do not have to do that hererelated questioncode sign error no unexpired provisioning profiles found that contain any of the keychains signing certificates,['ios'] +274666,why does not java include the timespace complexity of each function in the javadoc hi i want to know what is the time complexity of the replaceall function of the string class but i cannot find any information on itwouldnt it be better for java to include the complexities in the javadoc i believe it is a very important thing for someone to know,['java'] +274676,how can i remove button of expandablelistview i have used a custom expandablelistadapter in my project how can i remove this button,['android'] +274690,stop form from submitting using jquery i am trying to stop my form from submitting if a validation fails i tried following this previous post but i does not work for me what am i missinginput idsavebutton typesubmit valuesave input idcancelbutton typebutton valuecancel script srcscriptsjquery141vsdocjs typetextjavascriptscriptscript typetextjavascript documentreadyfunction formsubmitfunction e ajax url urlactionhasjobinprogress clientchoices data id modelclientid success function data showmsgdata e cache false cancelbuttonclickfunction windowlocation urlactionlist default new clientid modelclientid typetextfocusfunction thisselect function showmsghascurrentjob sender if hascurrentjob true alertthe current clients has a job in progress no changes can be saved until current job completes if sender null senderpreventdefault return false script,['jquery'] +274707,observableobject or inotifypropertychanged on viewmodels i was curious what was the best thing to do with viewmodels is it better to implement the interface inotifypropertychanged or to derive from observableobjectobservableobject class implements inotifypropertychanged and do some of the boring code like raisepropertychanged inotifypropertychanged require to implement propertychanged event from my point of view it seems more logical to use observableobject but in most of the tutorial they implement inotifypropertychanged interface on their viewmodeldo you think it is for the sake of simplicity or there is a logical reason,['c#'] +274736,noclassdeffounderror jsonautodetect while parsing json object i am developing a webapp using amazons cloud services and i need to make use of json objects how my project is set up is i have an html form where the user will fill in their information and submit once submitted the data will be placed into an online database and a confirmation email is sent to them before i can submit the data to the data base i need to place all of it into a json object my servlet done in java looks like thispublic class formhandling extends httpservlet doget function public void doget httpservletrequest request httpservletresponse response throws servletexception ioexception in this part of the code i take in the user data and build an html page and return it to the user create string mapping for user data object mapstringobject userdata new hashmapstringobject map the names into one struct in the code below we are creating values for the namestruct from the information the user has submitted on the form mapstringstring namestruct new hashmapstringstring namestructputfname requestgetparameterfname namestructputlname requestgetparameterlname namestructputminit requestgetparameterminit map the three emails together providing there are 3 this is the same logic as the names mapstringstring emailstruct new hashmapstringstring emailstructputemail requestgetparameteremail1 emailstructputemail requestgetparameteremail2 emailstructputemail requestgetparameteremail3 put name hash value pair inside user data object userdataputname namestruct userdataputemails emailstruct userdataputage 22 create the json data from the userdata createjsonuserdata close writer outclose public file createjsonmapstringobject userdata throws jsongenerationexception jsonmappingexception ioexception file user new fileuserjson create mapper object objectmapper mapper new objectmapper add the userdata information to the json file mapperwritevalueuser userdata return user when i submit the form using this code i get the following error messagejavalangnoclassdeffounderror comfasterxmljacksonannotationjsonautodetect comfasterxmljacksondatabindintrospectvisibilitycheckerstdvisibilitycheckerjava169 comfasterxmljacksondatabindobjectmapperobjectmapperjava197 edutcnjformhandlingcreatejsonformhandlingjava115 edutcnjformhandlingdogetformhandlingjava104 edutcnjformhandlingdopostformhandlingjava131 javaxservlethttphttpservletservicehttpservletjava641 javaxservlethttphttpservletservicehttpservletjava722now i know that error means that it is not finding the jackson databind library i am developing in eclipse and i know the build path messes up from time to time so i also placed the libraries in the webcontentwebinflib folder this has solved issues i have had before however this does not seem to solve my problem this time around i have even opened the jar files to physically check that the library and class needed are there and they are i have tried searching all over and looking into different ways to include the library but nothing seems to work,['java'] +274757,what is the purpose of the extra braces in switch case i am curious about this thing see exampleswitchx casea do stuff break caseb do stuff breakall my life i have done it like case b but since c allows me to use it and visual studio allows me to collapse that thing i am curious what is the real difference between case a with braces and case b,['c#'] +274771,mysql if value exists update else insert i have some code that looks like this there is also an autoincrement field in the table that i must retain it is used in other tables i would like to simplify and optimize this codequery select from models where col1 footestresult mysql queryquery or dieerror query failed ifmysql fetch arraytestresult null insert query insert into models col1 col2 col3 values foo bar alph result mysql queryquery or dieerror query failedelse update query update models set col1foo col2bar col3alph where col1foo and col2bar result mysql queryquery or dieerror query failed edit the primary key id is the field that is auto incremented i never want to alter this however when another fields isare duplicated this is when i want to update that record,"['php', 'mysql']" +274786,add carriage return to a string i have a long stringstring s1 990249905099070991439917399191992019920299203992049921199212992139921499215992179921899219221992992319923299238992393569935799371993749938199382993839938499385993869939199392i want string s2 99024 99050 99070 99143 99173 99191 99201 99202in other words maybe it likesstring s2 99024n99050n99070n99143ni need a concise code maybe linq thanks,['c#'] +274792,combining lazyload and jquery masonry i have been trying to piece together masonry and moo tools lazyload however they both dont seem to go very well together although it possibly could just be because i am slightly useless at coding the masonry works on this pagehowever when i try to put it together with lazyload it seems to totally mess up does anyone have any idea how to implement both plugins together i have spent 6 days trying to figure it out and this is my final hope hathanks,['jquery'] +274798,abaddressbookregisterexternalchangecallback called several times i have a strange problem where i register my iosapp to listen to changes in the phones address book the correct method is called when something changes in the address book but it gets called 2 6 times when the object gets created singleton so only one object i register for notifications with this codeabaddressbookregisterexternalchangecallbacknotificationaddressbook addressbookchanged bridge retained void selfthe method that is called looks like thisvoid addressbookchangedabaddressbookref ab cfdictionaryref info void contextabaddressbookrevertab nslogaddressbook changed phonebookcopy updatecopyany ideas how to solve this,"['iphone', 'ios']" +274822,how to avoid initialization of a large array i allocate a large array of doubles asdouble x new double and where and is large and i want to avoid initialization to save time is it possible,['java'] +274842,android viewpager show preview of page on left and right i am using androids viewpager what i want to do is to show a preview of the page on both the left and the right i have seen where i can use a negative pagemargin to show a preview of the right sidesetpagemargin100is there anyway that i can show a preview of the left side aswell its basically something similar to the gallery widget that i am looking for,['android'] +274862,date difference between consecutive rows complicated i had previously posted a question which was answered but i need a query for this tooi have a table structure with data like this dates in the format ddmmyid account number unit admit date thisch date1 1001 w32 01042012 2 1002 w32 01042012 010420123 1001 ccu 030420124 1001 w33 050420125 1003 cicu 040420126 1001 ccu 070420127 1001 ccu 07042012 100420128 1003 w33 050420129 1003 w33 05042012 08042012basically this table deals with patients getting admitted to a particular ward and transferred between wards and then finally thischarged either on same day or few days laterthe expected result from query would beaccount number no of days1001 01042012 03042012 21001 03042012 05042012 21001 05032012 07042012 21001 07042012 10042012 31002 01042012 01042012 01003 04042012 05042012 11003 05042012 08042012 3the thischarge date field will only be filled when the patient is thischarged hence i would like to calculate date difference between each date of movement of the patient including both admission and the date of thischargei use ms access 2003i hope that some one will be able to help me with this,['sql'] +274878,firemonkey ios rad studio xe2 thisplay image on form loaded from url is it possible to place a timage on an fmx form for ios and load image jpg from an url into this timage to be thisplayed in the ios appi have tried with no success any hints or point in the right direction is appreciated,['ios'] +274920,how to use uiimagepickercontrollercroprect i just figured out a way to change rect for crop box which appears after capturing an image from uiimagepickerviewcontroller this can be done with help of uiimagepickercontrollercroprect but i have no idea how to use it originally the crop box is square i want it to be rectangularcan someone help me or share an example with mebest regardsnitish,"['iphone', 'ios']" +274922,how can i use switch statement on typesafe enum pattern i found a goodlooking example about implementation enums in a different way that is called typesafe enum pattern i think i started using it but i realized that i can not use it in a switch statement my implementation looks like the followingpublic sealed class mystate private readonly string m name private readonly int m value public static readonly mystate passed new mystate1 ok public static readonly mystate failed new mystate2 error private mystateint value string name m name name m value value public override string tostring return m name public int getintvalue return m value what can i add to my class in order to be able to use this pattern in switch statements in cthanks,['c#'] +274924,file getting copied to syswow64 instead of system32 i have to copy a pstool utility to system32 folder when my application runsi am on 64 bit windows 7 and whenever i try to copy the exe to system32 bit folder through filecopy the exe always gets copied to syswow64 insteadwhen i put a breakpoint on destfile the path is shown as cwindowssystem32 but the file does not go in there goes to syswow64 i have tried the special folder systemx86 but the file again goes to syswow64string sourcefile cbindebugsomexeexestring destfile pathcombineenvironmentgetfolderpathenvironmentspecialfoldersystem utilitynamefilecopysourcefile destfile trueany suggestions what i am missing hereeditas pointed out below in the answer there is file system redirection taking place i am developing the app with the default settings of visual studio for a console application on a 64 bit os i am not sure what settingsswitches have to be kept while compiling so that the application works both on 32 bit and 64 bit osbasically it should just set copy the file to system32 only regardless of what bit os it is later in the program i have to access the pstools utility through command line which is not available if i place it in syswow64 if i make change to use syswow64s 32 bit cmdexe this would again be something 64 bit platform specific which i do not want to optany solution which can have the app running both on 32bit and 64 bit without an problems do i have to modify the code how or do i have to modify some properties of this console application project which properties,"['c#', '.net']" +274930,chrome extension inject sidebar into page i would like my chrome extension to be able to inject a 300px sidebar on the right side of any page when it is activated i am looking for the best way to constrain the entire page to documentbodyclientwidth 300 thereby leaving the 300px on the right for my sidebar the sidebar i currently inject is appended to documentbody and has a style like sowidth300pxposition fixedtop 0pxright 0pxheight500pxi need a way to prevent the existing page elements from bleeding over into my sidebar i was hoping that there would be a way to trick the existing elements into thinking that they were rendering into a browser client 300px narrower than their actual window thereby leaving space for my sidebar but i have not found any easy way to do so,"['javascript', 'css']" +274966,moving matplotlib legend outside of the axis makes it cutoff by the figure box i am familiar with the following questionsmatplotlib savefig with a legend outside the plothow to put the legend out of the plotit seems that the answers in these questions have the luxury of being able to fiddle with the exact shrinking of the axis so that the legend fits shrinking the axes however is not an ideal solution because it makes the data smaller making it actually more difficult to interpret particularly when its complex and there are lots of things going on hence needing a large legendthe example of a complex legend in the documentation demonstrates the need for this because the legend in their plot actually completely obscures multiple data points guidehtmllegendofcomplexplots what i would like to be able to do is dynamically expand the size of the figure box to accommodate the expanding figure legendimport matplotlibpyplot as pltimport numpy as npx nparange2nppi 2nppi 01fig pltfigure1ax figadd subplot1axplotx npsinx labelsineaxplotx npcosx labelcosineaxplotx nparctanx labelinverse tanlgd axlegendloc9 bbox to anchor050axgridonnotice how the final label inverse tan is actually outside the figure box and looks badly cutoff not publication qualityfinally i have been told that this is normal behaviour in r and latex so i am a little confused why this is so difficult in python is there a historical reason is matlab equally poor on this matteri have the only slightly longer version of this code on pastebin,['python'] +274993,how does synchronous and asynchronous communication work exactly i was trying to understand the terms synchronous and asynchronous communication but i am getting confused a bit i tried to dig a bit into this but there are still confusions my questions are as follows1how does the synchronous and asynchronous communication work also with reference to the above mentioned what are the signals used for asynchronous communication 2how does the synchronous and asynchronous process workany example to illustrate this is would be helpful apologies in case this is a very simple question i am new to programming hoping your answers help me thanks in advance,['c'] +275011,how to use thousand separator in nsstring nsstring just like 10 and 1008972how can i format them to 10 and 100897700that is my question and help me with this thank you in advance,['ios'] +275027,how to get round shape in android how would i achieve a round shape in android like below through an android shape drawable,['android'] +275048,how to set networkx edge labels offset to avoid label overlap i am trying to add edge labels for a graph it all works well only problem is when the two edges intersect i only see one of the labels as they happen to overlapas you can see the hphobalpha label is shown but the polaritybeta label is not shown my guess is that it is right under the previously mentionedi could not find any documentation on how to reposition the labels any advice how to set some kind of offset to move the labelscode used to generate the graphtry import matplotlibpyplot as pltexcept raiseimport networkx as nxgnxgraphahphobbpolaritycalphadbetagadd edgeabweight05gadd edgebcweight05gadd edgecdweight05gadd edgeadweight05gadd edgeacweight05gadd edgebdweight05posnxspring layoutg positions for all nodes nodesnxdraw networkx nodesgposnode size70 node colorwhite edgesnxdraw networkx edgesgpos width6alpha05edge colorblack labelsnxdraw networkx labelsgposfont size20font familysansserifnxdraw networkx edge labelsgpos abx bcy cdw adz acv bdr pltaxisoffpltsavefigweighted graphpng save as pngpltshow thisplay,['python'] +275131,how do i measure how long a function is running i want to see how long a function is running so i added a timer object on my form and i came out with this codeprivate int counter 0 inside button click i havetimer new timertimertick new eventhandlertimer ticktimerstartresult result new resultresult new geneticalgorithmstabusearchparameterstabu functiatimerstopandprivate void timer tickobject sender eventargs e counter btntabusearchtext countertostringbut this is not counting anything why,['c#'] +275134,how to handle the pylint message idw0612 unused variable i am updating some code to pep 8 standard using pylint part of the code is throwing the w0612 unused variable error but it is because it is using a module that returns xy for example when only x is needed in this particular case this is whats done var 1 var 2 funcdef func aa bb return abvar 1 is then returned but var 2 is never used and therefore throws the error how should i handle this i am thinking thisvar func0what is the best way to handle it,['python'] +275188,how to simulate database failure to test 2phase commit in java i am implementing a 2phase commit involving thistributed resources how do i simulate the failure of a participating database pulling out the newtork cable doesnt work as it causes table deadlock i am currently using hooks in my application code which throw staleconnectionexception at different points like before query execution after query execution my concern with this approach isis there a better way to simulate the db failurewhat happens to the connection object when db connection goes bad does it retain its value or does it become nullwhat actually happens when application tries to reconnect to dbwhat value does connection object getdoes it use an existing value from the connection pool i would also like to test at intermediate points like during query exectuion during commit after prepare is sent etc right now i put application into debug mode and step into the function call and pull the plug in between but this approach is manual and wnt work for a scale testingis there a simulatoremulator or tool which can help me do this,['java'] +275212,how do i set windowlocation to a specific path without a host i am using the window location method to redirect a webpage to another after a set amount of time the url needs to change from wmyurlcomhome to wmyurlcomother the problem is that i do not know what the final urls will be so i cannot use absolute links they have to be a path only this is what i have so far windowlocationpathname mobilityhtml,"['javascript', 'jquery']" +275217,efficiently generate all composite numbers less than and with their factorizations i would like to build an efficient python iteratorgenerator that yieldsall composite numbers less than nalong with their prime factorizationi will call it composites with factorsassume we already have a list of primes less than n or a primes generator that can do the samenote that ido not need the numbers to be yielded in numerical orderdo not care if 1 is yielded at the beginning or notdo not care if primes are yielded too i figure this can be done with a clever recursive generator so for example a call to composites with factors16 may yield yields values in form of composite value factor tuple2 24 2 28 2 2 26 2 312 2 2 310 2 514 2 73 39 3 315 3 55 57 711 13 13as you can see from the order of my output i conceive of this working by starting with the smallest prime on the available primes generator and outputting all powers of that prime less than n then try again through the powers of that prime but at each stage seeing if i can apply powers of additional primes and still be less than n when all combinations with that prime are done drop it and repeat with the next lowest prime number available on the primes generatormy attempts to do this with recursive generators have gotten me very confused on when to pop out of the recursion with yield or raise stopiteration or return or simply fall out of the recursed functionthanks for your wisdomadditional notei do have one way to do this now i have written a function to factor numbers so i can factor them down to primes and yield the results no problem i keep this blazingly fast by relying on a cache of what is the lowest prime factor of number n for and up to 10 millionhowever once i am out of the cache well it devolves to naive factoring yuckthe point of this post isi am assuming that generating large composites from their factors will be faster than factoring large composites especially since i do not care about order andhow can you have a python generator recursively call itself and yield a single stream of generated things,['python'] +275220,unable to find an entry point when calling c dll in c i am trying to learn pinvoke so i created a simple dll in ckingfucshnamespace kingfuncs class kingfuncs public static declspecdllexport int givemenumberint i kingfunscppinclude kingfuncshinclude stdexceptusing namespace stdnamespace kingfuncs int kingfuncsgivemenumberint i return i so it does compile then i copied this dll into my wpfs debug folder with codedllimportkingfuncdlldll entrypoint givemenumber setlasterror true charset charsetansi exactspelling true callingconvention callingconventionstdcall public static extern int givemenumber int i and calling it in button clickprivate void button clickobject sender routedeventargs e int num givemenumber123but it gives me exceptionunable to find an entry point named givemenumber in dll kingfuncdlldllreally what have i done wrong it obviously able to find the dll otherwise would be another exception but my method name is exactly the same i cannot think of other reason,"['c#', 'c++']" +275223,should i call cleartimeout before overwriting the timeout variable just found this codesnippet in our application i am wondering if the first line is superfluous does one need to call cleartimeout on a variable if it is immediately overwritten or is there some condition i should be aware offunction countdown cleartimeoutsessiontimeouthandle sessiontimeouthandle settimeoutfunction countdownhandler millisecondsmy hunch is yes you need to call cleartimeout because i cannot think of why the cleartimeout method would exist if it was ok to just set the timeout variable to nulli suppose the better question isvar timeouthandler settimeoutcountdownhandler millisecondstimeouthandler settimeoutcountdownhandler millisecondsdo i now have two functions waiting to fire in approximately milliseconds or just one,['javascript'] +275224,what is the fastest way to search a list across multiple properties i have a process i have inherited that i am converting to c from another language numerous steps in the process loop through what can be a lot of records 100k200k to do calculations as part of those processes it generally does a lookup into another list to retrieve some values i would normally move this kind of thing into a sql statement and we have where weve been able to but in these cases there is not really an easy way to do that in some places weve attempted to convert the code to a stored procedure and decided it was not working nearly as well as we had hopedeffectively the code does thisvar match costwherer rrypstartswithrecordformtrimend ryear recordyear rperiod recordperiodfirstordefaultcost is a local list type if i was doing a search on only one field i would probably just move this into a dictionary the records are not always unique eitherobviously this is really slowi ran across the open source library i4o which can build indexes however it fails for me in various queries and i do not really have the time to attempt to debug the source code it also does not work with startswith or contains startswith is much more important since a lot of the original queries take advantage of the fact that doing a search for a would find a match in abcare there any other projects open source or commercial that do this sort of thing editi did some searching based on the feedback and found power collections which supports dictionaries that have keys that are not unique i tested tolookup which worked great it is still not quite as fast as the original code but it is at least acceptable it is down from 45 seconds to 34 seconds i will take a look at the trie structure for the other look ups thanks,['c#'] +275226,embedding matplotlib in c i am reading a message from a socket with c code and am trying to plot it interactively with matplotlib but it seems python code will block the main thread no matter i use show or ion and draw ion and draw would not block in pythonany idea how to plot interactively with matplotlib in c codean example would be really goodthanks a lot,"['c++', 'python']" +275243,read dock information osx i am trying to read information about the dock and retrieve the applications and their positions on the dockcan anyone give me a pointer on how to do this edit from librarypreferencescomappledockplist i can get all information related to staticfixed apps and folder but not about launched and minimized application tilesfor launched apps we can use nsworkspace big question is still minimized application tiles,['objective-c'] +275250,underscorejs determine if all values in an array of arrays match i have an array of arrays which looks something like thissome string some other stringsome third string some fourth stringi think i can use the all method in underscore to determine if all of the arrays match 100 that is all of their values match but i am not sure how to write the required iterator to run the checkanyone have an idea,['javascript'] +275319,implementing alternative forms of lda i am using latent dirichlet allocation with a corpus of news data from six different sources i am interested in topic evolution emergence and want to compare how the sources are alike and different from each other over time i know that there are a number of modified lda algorithms such as the authortopic model topics over time and so onmy issue is that very few of these alternate model specifications are implemented in any standard format a few are available in java but most exist as conference papers only what is the best way to go about implementing some of these algorithms on my own i am fairly proficient in r and jags and can stumble around in python when given long enough i am willing to write the code but i do not really know where to start and i do not know c or java can i build a model in jags or python just having the formulas from the manuscript if so can someone point me at an example of doing this thanks,['python'] +275322,when are javascript objects destroyed in c i can define a constructor and destructor explicitly and then cout c or d called from with in the constructordestructor function to know exactly wherehowever in javascript how do i know when an object is destructed the example below is the case that concerns mei am calling an internal function on a timeout and i am wondering if the object stays alive as long as the timer is running waiting to call next againuser click calls control calls controlcontrol calls messagevar message object new message response element message calls effectsnew effectsfade thiselement down 40 message objectthisplay empty effects effects build out as needed element holds the element to fade direction determines which way to fade the element max time length of the fade var effects function thisfade function element direction max time elementelapsed 0 cleartimeout elementtimeout id function next elementelapsed 10 if direction up elementstyleopacity elementelapsed max time else if direction down elementstyleopacity max time elementelapsed max time if elementelapsed max time elementtimeout id settimeout next 10 next,['javascript'] +275326,android minimum button height 48dp 9mm i am currently working on wireframes for a mobile app and there is something that seems to slip my mind in the android design guidelines they state the followingon average 48dp translate to a physical size of about 9mm with some variabilitybut according to the android developpers dev guide they calculate a dp using the following formulathe densityindependent pixel is equivalent to one physical pixel on a 160 dpi screen which is the baseline density assumed by the system for a medium density screen at runtime the system transparently handles any scaling of the dp units as necessary based on the actual density of the screen in use the conversion of dp units to screen pixels is simple px dp dpi 160 for example on a 240 dpi screen 1 dp equals 15 physical pixels you should always use dp units when defining your applications ui to ensure proper thisplay of your ui on screens with different densitiesso let say that for simplicity i am doing my design at 160dpi so my graphics have the right size according to recommended standards when printed i scale down my document by 2 160dpi72dpi so the printed result gives the actual physical size on paperi want my buttons to be 48dp high but if i do the maths following everything i read i am nowhere close to a 9mm size by specifying 48 as my button height48dp 160dpi 03 inches so 762 mmwhat am i clearly missingdoing wrong where is that 9mm coming fromthanksupdateheres what helped me understand what i was missing from the accepted answertake as an example the screen density of 200 android will use 240 to base its calculations so240dpi 160dpi 15 of scale 48dp 15 of scale 78 physical pixels 78 px 240dpi 03 inches which is exactly the same as 48dp 160dpinow the trick is that the actual device density was 200 so the pixels will appear bigger than on a 240dpi screen to get the physical size on the 200dpi device we have to get the difference between both resolution and apply it to the 03 inches240dpi 200dpi 12 03 in 12 of difference 036in which gives 9144mmi know this is exactly the same as stated by kabuko48dp 200ppi 15 254 mmin 914400but the step by step way helped me figuring out what was happening under the hood,['android'] +275329,setting simple events in meteor i am trying out leaderboards example in meteor but i am doing something wrong in setting the click event in this example i have three buttons one to change the sort by column another to add 5 bonus points to everyoneheres the html div idouter sorter leaderboard div template namesorter spansorted by sortedbyspan if sortbyname input typebutton idsortscore valuesort by score else input typebutton idsortname valuesort by name if input typebutton classincall value5 bonus points to all templateand heres the jstemplatesorterevents click sortname function sessionsetorderby nameclick sortscore function sessionsetorderby scoreclick inputincall function playersfindforeachfunctionplayer playersupdateplayer id inc score 5 calling sessionsetorderby name in the console works and updates the html accordingly but clicking in the buttons does not so what am i missingthanks,['javascript'] +275332,best way to parse a url query string what is the best way to parse data out of a url query string for instance data appended to the url by a form in python my goal is to accept form data and thisplay it on the same page i have researched several methods that are not quite what i am looking for i am creating a simple web server with the goal of learning about sockets this web server would not be used for anything but testing purposesget 1pmsample2pm3pm4pm5pm http11host localhost50useragent mozilla50 windows nt 61 wow64 rv110 gecko20100101 firefox110accept texthtmlapplicationxhtmlxmlapplicationxmlq09q08acceptlanguage enusenq05acceptencoding gzip deflateconnection keepalivereferer httplocalhost501pmsample2pm3pm4pm5pm,['python'] +275353,preventing index out of range error i want to write a check for some conditions without having to use trycatch and i want to avoid the possibilities of getting index out of range errorsif arrayelement0objectlength 0 arrayelement1objectlength 0 making sure there is at least one object array that has values if arrayelement0object0itemlength 0 arrayelement1object0itemlength 0 this is where i check that at least one of the items strings is not empty execute code here so the problem i am facing is that in the second check i need to see whether i have one item that is not empty however if i do not have element1 i get the index out of range exception the problem is that there could be 2 elements and oneor both of them may have empty object arrays the code will have to be executed only if one of thos item strings is not emptyhopefully i explained it well how do i go about avoiding getting that exception under any condition,['c#'] +275372,applying colorfilter to imageview with shapeddrawable i have an imageview with androidsrc set to a shapeddrawable namely a white circle what i want is to colorize this imageview in runtime responding to some events imgviewsetcolorfilter seems to be solution but after using this tried different parameters the image becomes invisible i do not see it at the screenhow to solve this and are there better ways to have color circles,['android'] +275377,how to keep a c class name unmodified with cython i have a c class called foo if i follow the cython c tutorial i will need to call the python class differently pyfoo for example however i really need to call the python class foo as well how to do that efficientlyedit i am trying to interface an existing c library that was previously interfaced with boost python for different reasons i would like to test cython instead since with boostpython python classes were called with the same name as in c i would like to continue with this naming convention it is not a python cpython requirement to call classes differently but it seems to be imposed by cython at least in the tutorial i can of course use a pure python module to define a foo class that calls pyfoo but this seems both boring and inefficient,"['c++', 'python']" +275388,save nswindow size on resize close for user i have noticed that all applications on os x seem to save the size you set it at the next time you open it it is typically in the same position and sizei am making an app and i have noticed that after resizing if i launch the application again it is just the size of what i have set in xcode 4s ib and not the size that i resized it to on launchdo i have to manually save the window size each time its changed or is there an easier way to do this through ib my window does have a minimum size set if that changes anything,['objective-c'] +275397,pybrain when creating network from ground up how and where do you create a bias following the pybrain documentation building networks with modules and connections i am building a neural network piecewise in contrast to using the buildnetwork shortcut i am constructing a simple 3layer input hidden output neural network how do i properly add a bias uniti am guessing i construct a biasunit module as inb biasunitnamebiasnetworkaddmodulebis this the right way do i have to create fullconnection object if so what should i be connecting,['python'] +275402,4 different scenarios of this whats the correct interpretation these are taken from the tutspremium jquery vid tutorials jeff explains what this is referring to each time but i am not sure i have grasped the reasoning behind them all eg 1function dosomethinge epreventdefault consolelogthis aonclick dosomethingin this case this refers to the a element being in this case the parent objecti guess that is because here the statement equates to aonclick function e epreventdefault consolelogthis so a is the parent object eg 2var obj doit functione epreventdefault consolelogthis aonclick objdoitin this case this still refers to the a element but apparently it is not the parent objectit seems this time were calling a method but the statement still equates to the same thing as eg 1 one thing in the tutorial has me a bit confused i thought this always refers to the parent object so in this case a is still the parent object but at 0523 in the tutorial he infers that is not the case stating there may be times when you want this to refer to it is parent object which would be obj in which event he creates eg3 eg 3var obj doit function consolelogthis aonclick functione objdoit epreventdefault in this case this refers to the obj object i presume this to with the fact that this is in a nested function as this statement equates to aonclick function function consolelogthisepreventdefault i do not really understand why though particularly as i read in an article that in nested functions this loses its way and refers to the head object window object eg4 var obj doit function consolelogthis aonclick functione objdoitcallthis epreventdefault in this case this refers to the aaccording to javascript definitive guide the first argument to both call is the object on which the function is to be invokedhere this is the used as the first argument but this is not the object on which the function is to be invokedi think i get that the call function is there to invoke the function and use its first parameter as a pointer to a different object but i do not get why using this means the function is invoked by a it is not something i have seen in other call examples eithersorry for such a mammoth post hopefully someones still reading by this stagea,['jquery'] +275452,converting from datetime to sqldatetime is inaccurate i have a method that gets a date property from a source either a datarow or a sqldatareaderprotected sqldatetime getsqldatetimepropertyvaluestring propertyname object source var objvalue getpropertyvaluepropertyname source var value objvalue dbnullvalue null datetimeobjvalue var sqlvalue new sqldatetime if valuehasvalue sqlvalue valuevalue return sqlvaluebut the conversion appears to be changing the date slightly so that my test always failsdoes anyone know why this method would be converting wrongly at the end of the method it looks like the conversion to sqldatetime does some roundingvaluevalueticks 634698391707468296sqlvaluevalueticks 634698391707470,"['c#', 'asp.net']" +275457,overridependingtransition shows second activity too quickly i have 2 activities and i want to create an animated transition between the two activities such that both activitiess views slides up as if the second activity is pushing the first activity upwards in my first activity i useintent isecondactivity new intentfirstactivitythissecondactivityclassfirstactivitythisstartactivityisecondactivityfirstactivitythisoverridependingtransitionranimslide ranimslide2and my slidexml looks likexml version10 encodingutf8set xmlnsandroid androidinterpolatorandroidanimaccelerate interpolator translate androidinterpolatorandroidanimdecelerate interpolator androidfromydelta0 androidtoydelta100p androidduration20 setand my slide2xml looks likexml version10 encodingutf8set xmlnsandroid androidinterpolatorandroidanimaccelerate interpolator translate androidinterpolatorandroidanimdecelerate interpolator androidfromydelta100p androidtoydelta0 androidduration20 sethowever the problem is that when the startactivity is called the second activitys view is already rendered while the transition just starts sliding i would like to see the first activitys view slide up but instead i am seeing the second activitys view rendered over the first activitys view slide upthe second problem is that i am seeing the replacement view being the first activitys view i would like the replacement view to be the second activitys view that is pushing upwardsit is hard to explain so please let me know if i can explain anything in more detail apologies for any confusion and thanks for reading thisps i am using textviews i guess that renders too quickly i am also using motorola razr not that it should matter,['android'] +275460,how can i style an android switch the switch widget introduced in api 14 is styled by default with holo themei want to style it slightly different changing its colors and shape a bit for branding reasons how does one go about this i know it must be possible as ive seen the difference between default ics and samsungs touchwiz theme i assume i will need some state drawables and i have seen a few styles in with switch thumb and switch track that look like what i might be after i just do not know how to go about using themi am using actionbarsherlock if that makes a difference only devices running api v14 or above will be able to use a switch at all of course,['android'] +275511,ios creating multi page pdf from html content i have a long html page and wanted to convert it in to a multipage pdf filei have followed the instructions provided inapple and here how to make multi page pdf for a given string contentbut the formatting the nsstring with some like data is difficult than creating a html page i have created this html and thisplaying it in a uiwebviewnow i want to create a pdf out of this html to a multi page pdf filethe code i am using can create single pdf voidcreatepdffromuiviewuiwebview aview savetodocumentswithfilenamensstringafilename creates a mutable data object for updating with binary data like a byte array nsmutabledata pdfdata nsmutabledata data points the pdf converter to the mutable data object and to the uiview to be converted uigraphicsbeginpdfcontexttodatapdfdata aviewbounds nil uigraphicsbeginpdfpage cgcontextref pdfcontext uigraphicsgetcurrentcontext draws rect to the view and thus this is captured by uigraphicsbeginpdfcontexttodata aviewlayer renderincontextpdfcontext remove pdf rendering context uigraphicsendpdfcontext retrieves the document directories from the ios device nsarray documentdirectories nssearchpathfordirectoriesindomainsnsdocumentdirectory nsuserdomainmaskyes nsstring documentdirectory documentdirectories objectatindex0 nsstring documentdirectoryfilename documentdirectory stringbyappendingpathcomponentafilename instructs the mutable data object to write its context to a file on thisk pdfdata writetofiledocumentdirectoryfilename atomicallyyes nslogdocumentdirectoryfilename documentdirectoryfilenamecan any one give some help,"['objective-c', 'ios']" +275512,objc storekit restorecompletedtransactions returns zero transactions i am having some problems restoring completed transactionsskpaymentqueue defaultqueue restorecompletedtransactionsi have added the observer mentioned in several examples i have tried adding paymentqueuerestorecompletedtransactionsfinished and already have updatedtransactions paymentqueuerestorecompletedtransactionsfinished says i have zero transactionsi can buy a product and if i try to buy again it stops me and says i have already bought the product using this codeskpayment payment skpayment paymentwithproductidentifierproductidentifierskpaymentqueue defaultqueue addpaymentpaymenti thought maybe i had a problem with my bundle identifier but that seems fine and the buy wouldnt work if it was noti having been trying this on the device as well as the simulator but this has the same result also it does not make a difference if i am using uk or us storei am really grasping at straws to find out why this does not work for me,"['iphone', 'objective-c']" +275538,generating emacs tags file for a ruby on rails project i am generating a tags file for emacs for my ruby on rails project with the following commandctags f tags extraf languagesjavascript excludegit excludelog e r rvm gemdirgemswhen i try to find tags using m some tags are working fine but with lots of other tags i get errors liketagfindfileoftagnoselect file userssimaodocumentsspofea a not foundetagsgototaglocation rerun etags class toolsfilteringsteps not found in userssimaodocumentsspofelibgeo dbrbhow are you generating tags for your ror projects with emacs did you ever see this problem beforethis is the output of ctags versionexuberant ctags 58 copyright c 19962009 darren hiebertcompiled mar 9 2012 154735addresses optional compiled features wildcards regexmy emacs versiongnu emacs 240951 x86 64appledarwin ns appleappkit103836 of 20120402,"['ruby-on-rails', 'ruby']" +275550,requirements file for aptget similar to pip i like how you can manage dependencies with pip requirements is there something similar in case of aptget,['python'] +275560,stdthread naming your thread the new c has this stdthread type works like a charmnow i would like to give each thread a name for more easy debugging like java allows you towith pthreads i would dopthread setname nppthread self thread namebut how can i do this with c0xi know it uses pthreads underneath on linux systems but i would like to make my application portable is it possible at all,['c++'] +275562,how to make class in c that can be cast to datetime how can i make class that can be cast to datetime but i need to cast my class when it packed for exampleobject date1 new mydatetimedatetime date2 datetimedate1i need directly this working examplei know how to do it but my way will work without packing i am not sure is there way to do itplease helpps i need cast directly object to datetime so mydatetime have to be packed before explicit works well but it does not help if you have packed object and it have to cast just using ordinary casting like datetime object mydatetime,['c#'] +275563,how to record video from background of application android i am developing an application which will be able to record video from background of application by using serviceproblem description in my application recording will be scheduled if user want to record video from 1 pm to 3 pm he will schedule the task and can exit from application application will automatically start recording at 1pm to 3pm what i did yet i googled about my query but did not get solution many articles say that it is not possible but in google play there are some applications for eg mycar recorder which can record video from background of application i got an article about same but its not working what is the way to implement this functionality,['android'] +275576,why i cannot use run android lint from menu window in eclipse in toolbar i can run it is it ok i have just updated sdk and adt for eclipse and now there is one thing confused mei cannot use run android lint from menu windowbut i can run it from eclipse toolbar or richtclick on my project then android tools run lint i am not sure if this is a bug from android or i have done something wrong by updating hat anybody the same problem as ithank youwith best regardskatrina,['android'] +275596,replace a fragment programmatically i have three fragments as shown in below figure i have added all these three fragments in linearlayout using xml file and when my launcher activity starts i load that xml layout using setcontentviewi have some controls on fragment2 clicking on any one loads thefragment4 programmatically using fragmenttransaction and commit method this fragments is added to the screen but the problem is the prgrammatically added fragment4 take the whole screen area what can be the problemnote on any item click at f2 i want to replace only f2 with new fragment f4 keep in mind i have added f1 f2 f3 through xml layout file and adding new fragment f4 programmatically,['android'] +275603,ios 51 and defaultpng i am developing an application using ios 51 and i am experiencing some strange behavior with the defaultpng filesi have added the following files to my applicationdefaultpng iphone iphone retinadefaultportraitipadpng ipad defaultportrait2xipadpng ipad retinawhen the application starts it seems that it selects the correct defaultpng image to use for each occasion however in my appdelegate i have a simple splash screen to make smoother the loading of the application and the transition to the app doing something likeuiimageview splashview uiimageview alloc initwithframecgrectmake00windowframesizewidth windowframesizeheight splashviewimage uiimage imagenameddefault window addsubviewsplashview window bringsubviewtofrontsplashview however the uiimage imagenameddefault in turn does not select the correct file for each device and i believe the problem is the portrait part of the filenameso as a quick solution i did thisif uidevice currentdeviceuserinterfaceidiom uiuserinterfaceidiompad force the image used by ipads if uiscreen mainscreen respondstoselectorselectorscale uiscreen mainscreen scale 20 splashviewimage uiimage imagenameddefaultportrait2xipad else splashviewimage uiimage imagenameddefaultportraitipad else splashviewimage uiimage imagenameddefaultis this how i should be doing this does this look funny to you,['ios'] +275636,android imageview scaletype and item height things looked quite simple first but in the end the result is not goodi have an image which has a width larger than screens width so i need to scale it down in my imageview i looked over the scaletype options and tried them all but none is ok first center only thisplays the image centered on the layout no scaling done fitcenter scales the image to fit in my layout but has a major drawback the height of the item remains as it would have the large image in it take a look at the second screen in the attached image how can i force the list item to reduce its height to wrap both the text and the image,['android'] +275668,encoding sql latin1 general cp1 ci as into utf8 i am generating a xml file with php using domdocument and i need to handle asian characters i am pulling data from the mssql2008 server using the pdo mssql driver and i apply utf8 encode on the xml attribute values everything works fine as long as there is no special charactersthe server is ms sql server 2008 sp3the database table and column collation are all sql latin1 general cp1 ci asi am using php 5217heres my pdo objectpdo new pdomssqlhostmyserver1433dbnamemydatabase user123 password123my query is a basic selecti know storing special characters into sql latin1 general cp1 ci as columns is not great but ideally it would be nice to make it work without changing it because other nonphp programs already use that column and it works fine in sql server management studio i can see the asian characters correctlyconsidering all the details above how should i process the data,['php'] +275669,jquery ui blind effect reveal from bottom this could be really obvious and i am completely missing iti have searched for hours and cannot seem to find a way to using jquery reveal a hidden div from the bottom up what i am trying to achieve is exactly as in the following link but in reverse i can slide a div from the bottom to the top but this reveals itself as it moves rather than being masked inlike i said this could should be really obvious and i am not seeing it but i have been looking for ages and cannot find a solution to this relatively simple problemthanksronnie,['jquery'] +275670,can you thisable rotation globally in an ios app i have an app made up of a lot of view controllers in the project summary i have set portrait orientation as the only supported device orientationhowever the app still gets messed up when turned sidewaysmy question is is there a way to globally thisable autorotation through app delegate or somethingor do i have to go into all of my view controllers and add the shouldautorotatetointerfaceorientation methodjust do not want to miss adding it to one or somethingthanks,['ios'] +275675,alternative schemes for implementing vptr this question is not about the c language itselfie not about the standard but about how to call a compiler to implement alternative schemes for virtual functionthe general scheme for implementing virtual functions is using a pointer to a table of pointers class base private int m public virtual methaequivalently in say c would be something likestruct base void vtable int mthe first member is usually a pointer to a list of virtual functions etc a piece of area in the memory which the application has no control of and in most case this happens to cost the size of a pointer before considering the members etc so in a 32bit addressing scheme around 4 bytes etc if you created a list of 40k polymorphic objects in your applications this is around 40k x 4 bytes 160k bytes before any member variables etc i also know this happens to be the fastest and common implementation among c compilesi know this is complicated by multiple inheritance especially with virtual classes in them ie diamond struct etcan alternative way to do the same is to have the first variable as a index id to a table of vptrsequivalently in c as belowstruct base char classid the classid here is an index into an array of vtables int mif the total number of classes in an application is less than 255including all possible template instantiations etc then a char is good enough to hold an index thereby reducing the size of all polymorphic classes in the applicationi am excluding alignment issues etcmy questions is is there any switch in gnu c llvm or any other compiler to do this or reduce the size of polymorphic objectsedit i understand about the alignment issues pointed out also a further point if this was on a 64bit systemassuming 64bit vptr with each polymorphic object members costing around 8 bytes then the cost of vptr is 50 of the memory this mostly relates to small polymorphics created in mass so i am wondering if this scheme is possible for at least specific virtual objects if not the whole application,['c++'] +275697,root element is missing i am reading xml from x url but i am getting error as root element is missingmy code to read xml response is as follows xmldocument doc new xmldocument docloadurl from which i am reading xml xmlnodelist nodes docgetelementsbytagnameproduct xmlnode node null foreach xmlnode and in nodes and the xml response is as followsall products product productcodegftproductcode productnamegift certificateproductname productdescriptionshortgive the perfect gift productdescriptionshort productdescriptiongive the perfect giftproductdescription productnameshortgift certificateproductnameshort freeshippingitemyfreeshippingitem productprice550productprice taxableproductytaxableproduct product all productscan you please tell where i am going wrong,"['c#', 'asp.net']" +275711,avplayer layer inside a view does not resize when uiview frame changes i have a uiview which contains an avplayer to show a video when changing orientation i need to change the size and location of the videoi am not very experienced with resizing layers so i am having problems making the video resizei start by creating the avplayer and adding its player to my videoholderviews layernsurl videourl nsurl fileurlwithpathvideopathselfavplayer avplayer playerwithurlvideourlavplayerlayer playerlayer avplayerlayer playerlayerwithplayerselfavplayerplayerlayerframe videoholderviewboundsplayerlayervideogravity avlayervideogravityresizeaspectplayerlayerneedsthisplayonboundschange yesvideoholderviewlayer addsublayerplayerlayervideoholderviewlayerneedsthisplayonboundschange yesthen at a later point i change the size and location of the videoholderviews framevideoholderview setframecgrectmake0 0 768 502at this point i need the avplayer to resize to these same dimension this does not happen automatically the avplayer stays at it is small size within the videoholderviewif anyone can help i would really appreciate any advicethanks guys,['objective-c'] +275713,does javascript have a standard for commenting functions i am currently writing some client side javascript code and wondering how to comment my functionsi come from a c background where there is an officially recommended commenting style documented by microsoft which i follow which allows the compiler and other tools to autogenerate documentationsimilarly phps phpdoc style is ubiquitous and on its way to becoming an official standard recommended by phpfigdoes javascript similarly have a universally accepted toolchain standard or set of best practices that i can apply when commenting my functions,['javascript'] +275719,why in this simple test the speed of method relates to the order of triggering i was doing other experiments until this strange behaviour caught my eyecode is compiled in x64 releaseif key in 1 the 3rd run of list method cost 40 more time than the first 2 output is list costs 9312list costs 9289array costs 12730list costs 11950if key in 2 the 3rd run of array method cost 30 more time than the first 2 output is array costs 8082array costs 8086list costs 11937array costs 12698you can see the pattern the complete code is attached following just compile and runthe code presented is minimal to run the test the actually code used to get reliable result is more complicated i wrapped the method and tested it 100 times after proper warmed upclass listarrayloop readonly int myarray readonly listint mylist readonly int totalsessions public listarrayloopint looprange int totalsessions myarray new intlooprange for int i 0 i myarraylength i myarrayi i mylist myarraytolist thistotalsessions totalsessions public void arraysum var pool myarray long sum 0 for int j 0 j totalsessions j sum poolsum public void listsum var pool mylist long sum 0 for int j 0 j totalsessions j sum poolsum class program static void mainstring args stopwatch sw new stopwatch listarrayloop test new listarrayloop10 10 string input consolereadline if input 1 swstart testlistsum swstop consolewritelinelist costs 0swelapsedmilliseconds swreset swstart testlistsum swstop consolewritelinelist costs 0 swelapsedmilliseconds swreset swstart testarraysum swstop consolewritelinearray costs 0 swelapsedmilliseconds swreset swstart testlistsum swstop consolewritelinelist costs 0 swelapsedmilliseconds else swstart testarraysum swstop consolewritelinearray costs 0 swelapsedmilliseconds swreset swstart testarraysum swstop consolewritelinearray costs 0 swelapsedmilliseconds swreset swstart testlistsum swstop consolewritelinelist costs 0 swelapsedmilliseconds swreset swstart testarraysum swstop consolewritelinearray costs 0 swelapsedmilliseconds consolereadkey,['c#'] +275724,uidocument openwithcompletionhandler not completing on ios device i am trying to open a managed document using openwithcompletionhandlerthe problem i am coming across is that it works fine on the simulator but when i test it on my iphone 4 the completion handler never finishes the code looks like thisthemanageddocument openwithcompletionhandlerbool success ifsuccess self documentisready ifsuccess nslogcould not open documentthis works fine on the simulator and i get to the documentisready call or the could not open document if it errors but on the iphone 4 it never runs the completionhandler block i have put breakpoints all through the block before and after both if statements and nothing is getting called no could not open document on the console no call to documentisreadyi must also mention that it seems like the first time i run the app on the iphone it will work properly i also have this encapsulated in an if statement with a fileexistsatpath call it is getting inside the if statement just fine and calling the openwithcompletionhandler but the completion block just never gets firedi am using ios 51 and xcode 432,"['ios', 'iphone']" +275766,backbone collection filtering and rendering the collection loses reference to the original unfiltered collection i am setting up an app driven by backbone i am facing a shouldbesimple problem where i have a model called message a collection called messagelist and views called messageview and messagelistviewthe messagelistview code renders the messagelist i have 4 toggle buttons that filter what the messagelistview shows the filter buttons are all active flagged and ignored all is the initial filter on the page load when a user presses the flagged filter only messages with a flag1 should appear when all is pressed again all the messages should appear againthe problem i am running into and the problem in my design is that when i filter the collection based on the filterstring the reference to the original entire collection gets lost so when all is pressed again messages have been lost i am curious as to the best way to do this in backboneheres the setup code var messagelistview new messagelistviewcollection messagelistheres the messagelistview codemessagelistview backboneviewextend initialize function thiscollectiononadd functionmodel var view new messageviewmodel model divcamerasprependviewrenderel thiscollectiononremove functionmodel var id modelid message idparentdivmessageremove thiscollectiononreset functionmodels divcamerasempty modelseachfunctionmessage var view new messageviewmodel message divcamerasprependviewrenderel filtermessages functionfilterstring var filtered thiscollectionfilterfunctionmodel if filterstring all return true else if filterstring active return modelgetignore 0 else if filterstring ignore return modelgetignore 1 else if filterstring flag return modelgetflag true thiscollectionresetfiltered,['javascript'] +275791,find indexes on two lists based on items condition lets say i have two lists they are lists of ratings of books on a scale from 5 to 5i want to know when list1s element is 1 and list2s element 0 so for examplelist1 3 3 1 0 3 0 3 0 0 3 0 5 3 0 1 0 0 5 3 0 0 0 0 1 0 3 0 1 0 0 3 5 3 3 0 0 0 5 0 5 0 3 3 0 3 0 0 5 1 5 3 0 3 0 0list2 5 0 0 0 0 0 5 0 0 1 0 5 3 0 0 0 0 3 0 0 0 0 0 3 0 5 0 0 0 0 5 5 5 3 0 0 0 3 0 0 0 5 3 0 0 0 0 5 0 5 3 0 0 0 0list11 3 and list21 0 i want to be able to find all the different indexes of where this happens at sorry if this is confusing but i do not really know how else to word this,['python'] +275798,set text property of asplabel in javascript proper way i have a series of textboxes on a form when the user inserts numbers into these textboxes calculations are made and asplabel controls are updated via javascript to reflect these calculationsdocumentgetelementbyidtotalloansclientid innerhtml totalloansthis correctly updates the ui however when i try to access the value in the codebehind the text property is empty this makes sense i guess since i was updating the innerhtml property via the javascripttotalloanstext will always be equal to in this scenariodouble btotalloans stringisnulloremptytotalloanstext 0 converttodoubletotalloanstexthow do i update the text property of the asplabel via javascript in such a way that i can read the property in the codebehindupdatethis is a small problem on a large form that contains 41 labels each of which thisplays the results of some calculation for the user taking the advice of fishbasketgordo i converted my asplabel to a thisabled asptextbox i am setting the value of the new textbox as such documentgetelementbyidtotalloansclientid value totalloansagain in the codebehind the value of totalloanstext is always equal to i do not mind changing how i approach this but heres the crux of the matteri am using javascript to manipulate the property values of some controls i need to be able to access these manipulated values from the code behind when submit is clicked any advice how i can go about thisupdate 2regarding the answer by james johnson i am not able to retrieve the value using innertext property as suggested i have enableviewstate set to true on the asplabel is there something else i am missingi do not understand why when i type in a textbox and submit the form i can access the value in the codebehind but when i programmatically change the text of a textbox or label by way of javascript i cannot access the new value,"['javascript', 'asp.net']" +275806,performing unit testing with nested dependencies and factory classes i am new to unit testing and phpunit but i have reading a lot lately about design patterns and isolated tests and i have decided to refactor an application i am working on to get rid of static classes singletons hardcoded dependencies and anything else defined on the global scope hopefully making it testable and not a pain in the ass to mantain in the future since it is meant to be a long term projectso far i believe i understand the theory behind unit testing but i was wondering in a scenario where one delegates handling nested dependencies of objects to a factory how should one go about unit testing said factory or is it just redundant to test it and what is the best approach to test that the chain of dependencies work well in synclet me illustrate the questions suppose you have the following legacy codeclass house protected material protected door protected knob public function construct thisdoor new door thisknob thisdoorgetknob thismaterial stone echo house material thismaterial php eol br echo door material thisdoorgetmaterial php eol br echo knob material thisknobgetmaterial php eol br class door protected material protected knob public function construct thisknob new knob thismaterial wood public function getknob return thisknob public function getmaterial return thismaterial class knob protected material public function construct thismaterial metal public function getmaterial return thismaterial house new housethis is as far as my understanding goes bad for unit testing so we replace the hardcoded dependencies with di a factory classclass house protected material protected door protected knob public function constructdoor thisdoor door thisknob thisdoorgetknob thismaterial stone echo house material thismaterial php eol br echo door material thisdoorgetmaterial php eol br echo knob material thisknobgetmaterial php eol br class door protected material protected knob public function constructknob thisknob knob thismaterial wood public function getknob return thisknob public function getmaterial return thismaterial class knob protected material public function construct thismaterial metal public function getmaterial return thismaterial class housefactory public function create knob new knob door new doorknob house new housedoor return house housefactory new housefactoryhouse housefactorycreatenow and again as far as i understand house door and knob can be unit tested with mocked dependencies just fine but1 what happens with housefactory nowshould one justnot test it since it does not have any application logic worth testing yet and factories generally stay that way assume that if the independ tests for house door knob pass the factory should be finerefactor the factory somehow ie using functions within the class to get each instance in such a way that one may override these functions via phpunit to return mock objects just in case there is some extra logic in the class that could use some testing in the future2 is it feasible to set up tests that rely on several not mocked dependencies at once i understand this is technically not unit testing integration testing perhaps but i guess it is still perfectly doable using phpunit given the example above i would like to be able to set up a test that not only tests house door knob and housefactory in isolation but also the results of the interaction of the real objects with each other perhaps with some of their functions mocked such as the ones which deal with data is phpunit a bad choice for this kind of teststhanks in advance for your time i realize some of the assumptions i am making may not be correct since i am obviously not an expert on the matter corrections are welcome and appreciated,['php'] +275812,how to write a caption under an image i have two images that need to kept inline i want to write a caption under each imagecenter a href img srchellopng width100px height100px a nbspnbspnbspnbspnbspnbspnbspnbspnbspnbspnbspnbsp a href img srchipng width100px height100px acenterhow can i implement,"['html', 'css']" +275830,best practices to using global variables in c someone once saida global variable is really a variable you create to simply hold some information because your object model is weak and you have not found a true purpose for the variable to exist global variables are almost always a sign of a larger architectural deformitythat might be true but i do not know of any good example of any big and good program made without global variables and certainly not used as little as above suggested scope is the actual key you can say in a program with only one class that its parameters are not global vars but they areanywayi am still grasping the concept of singleton and as far as i can tell they actually make no sense in c also i get the feeling that when having a global state cannot be avoided we still should avoid simply using a public class full of static propertiesso if not singletons nor a public class what should we do to have global vars in cand when are we supposed to use them assuming they most likely cannot be avoided everand why should we avoid using a static class or static in general if that is indeed the case for cin one sentence what are the best practices on using global variables in csharp,['c#'] +275849,sql index performance asc vs desc i have got a user table keyed on an autoincrement int column that looks something like this create table user def user id int11 not null auto increment user name varchar20 not null date created datetime not null primary key user id unique key user name unique user name enginemyisamare there any practical performance advantages to using a desc index primary key rather than the default ascmy suspicion reasoning is as followsi am assuming that more recent users are going to be more active ie accessing the table more often therefore making the index more efficientis my understanding correct,"['mysql', 'sql']" +275913,php best way to iterate two parallel arrays as seen in this other answer there are several ways to iterate two samesized arrays simultaneously however all of the methods have a rather significant pitfall here are some of the caveats with the methods suggestedyou cannot use false values in one of the arraysyou can only use scalar values in one of the arraysyou must use numerically indexed arraysboth arrays must share the same keysetcmy question is is there a method for doing this which does not suffer from any of these or other significant caveatsbear in mind that i am simply asking this out of curiosity i have no usecase in mind nor do i even know if such a case actually exists or would be usefulpractical in a realworld scenario however here is some example dataarr1 a 1 b false c new datetime arr2 foo true 7,['php'] +275926,how to handle facebooks deprecation of offline access when you use token both in both ios app and a server facebooks deprecation of the offline access permission is coming may 2012 and the documentation is not giving us enough information on how to handle itwe have an ios app and corresponding service that powers it and integrates with facebook in a deep way to leverage a users friend list within out app so if your fb friends are also using the app you can more easily connect this is like how all social apps seem to work so nothing special hereclientour app uses facebook ios sdk to allow user to login which we currently ask for offline access the token is persisted in our ios app but also sent to our server where it is saved the client acts on behalf of user to post updates to a users newsfeed we also ask for publish stream permission serverour server periodically checks to see if users fb friends are now using our app next time user signs in we expose content and relationships in a certain way to promote that users friends the server also acts on behalf of the user to periodically connect to the graph api and get the users current friends list this is so we can account for changes in a users relationships and have them reflected in our app we do this when the user is not currently using the app so they have the best experience the next time they do use it to enable this our ios app sends the access token to our server which it uses and why we ask for offline access note if user signs out of our app explicitly we delete the access tokens from both client and serverproblemsnow that there is no longer a perpetual access token we can use i am trying to figure out the best practice for still enabling our scenarios while leveraging facebooks new intended way of handling and extending access tokens the documentation is unfortunately not totally helpfulquestionsa when you authenticate through the newest facebook ios sdk what is the default lifetime of the access token you get this document says an extended token request will give you one that lasts 60 days this other document talks about the first access token request and mentions varying validities but it is unclear and does it talk about specific validity timesemphasis is minewhen you obtain an access token from facebook it will be valid immediately and usable in requests to the api for some time period defined by facebook after that period has elapsed the access token is considered to have expired and the user will need to be authenticated again in order for your app to obtain a fresh access token the duration for which a given access token is valid depends on how it was generatedthere are also events which may cause an access token to become invalid before its expected expiry time such events include the user changing their password an application refreshing it is app secret dealing with varying access token expiry times and handling the case when an access token becomes invalid before its expected expiry time is essential for building robust social experiencesb for the client now that the access token is not necessarily long lived is the right approach for us to let use login through fb then detect whenever the access token is expired if it is then call into fb ios sdk to reauthenticationreauthorize this should just trigger user to bounce out to fb ios app and in most cases come immediately back to our app with a new access tokenc according to this blog post i found you can only extend an access token oncecan i exchange my 60 day access token for a new 60 day access tokenno sorry you cannot you can only exchange a valid meaning current user access token for an extended one you cannot extend an already extended access tokenon the client i can just handle this by prompting a reauthenticationreauthorization as i mentioned in question b however this does not work on our server we could certainly have the server renew it once to 60 days but what happens on the 61st day the server just stops being able to sync the friends listd it seems to make sense to check the validity of the fb access token every time the app starts or rehydrates from sleep what is the best way for our ios app to check this is there a recommended endpoint to call to validate a token should we just call into passing the access token and checking the responsenote we can certainly record the expires time when we get the initially extended token but this is not reliable since the user could revoke our apps permission anytime which makes the expires time an unreliable data point on validity,['ios'] +275931,how can a dynamic be used as a generic how can i use a dynamic as a genericthisvar x something not strongly typedcallfunctionxand thisdynamic x something not strongly typedcallfunctionxboth produce this errorerror 1 the type or namespace name x could not be found are you missing a using directive or an assembly referencewhat can i do to x to make it legitimate enough to be used in x,['c#'] +275959,how to use php string in mysql like query i am trying to find the number of rows that match a specific pattern in this example all that start with 123this is workingquery mysql queryselect from table where the number like 123count mysql num rowsquerythe problem is the like will vary so i am trying to define it in the script then execute the query but this is not workingprefix 123query mysql queryselect from table where the number like prefixcount mysql num rowsqueryhow can i get this query to work properly in the second exampleedit i have also tried it without the period also not workingquery mysql queryselect from table where the number like prefix,"['php', 'mysql', 'sql']" +275966,availableprocessors returns 1 for dualcore phones i recently bought a moto atrix 2 mobile when i tried to look at the processor specs in the phoneruntimegetruntimeavailableprocessors returned 1proccpuinfo too had information about just processor 0out of curiosity i checked the same in my friends samsung galaxy s2 which is again a dual core phone this too showed that no of cores is 1i checked the same in my moto xoom tablet which is again dual core this time availableprocessors returned 2 and cpuinfo also had both processor 0 and processor 1 detailsi am confused why some devices carry different information can someone explain this anomaly,"['java', 'android']" +275968,what are the differences between streampos and pos type streamoff and off type what are the differences between streampos and pos type streamoff and off type except they are defined differently what should i use with the basic streamseeks functions,['c++'] +275982,how to cancel a task in await i am playing with these windows 8 winrt tasks and i am trying to cancel a task using the method below and it works to some point the cancelnotification method does get called which makes you think the task was cancelled but in the background the task keeps running then after it is completed the status of the task is always completed and never cancelled is there a way to completely halt the task when it is cancelledprivate async void trytask cancellationtokensource source new cancellationtokensource sourcetokenregistercancelnotification sourcecancelaftertimespanfromseconds1 var task taskintfactorystartnew slowfunc1 2 sourcetoken await task if taskiscompleted messagedialog md new messagedialogtaskresulttostring await mdshowasync else messagedialog md new messagedialoguncompleted await mdshowasync private int slowfuncint a int b string somestring stringempty for int i 0 i 20 i somestring a return a bprivate void cancelnotification,['c#'] +275998,bluetooth connection between android and another phone over the handsfree profile i am trying to use my android phone as a handsfree kit like the one for cars in order to connect to another phone any phone and perform some handsfree functionality like answer an incoming call reject etc which can be done using the at commands for handsfree profile for that i am using the wellknown bluetooth chat app and reflection work around in order to establish a connection with any devicemethod m devicegetclassgetmethodcreaterfcommsocket new class intclasstmp bluetoothsocket minvokedevice1 however in order to achieve the handsfree functionality and understand the at commands that i am sending the connected phone needs to be over the handsfree profile which uses the uuid 01f01080805f9b34fbtherefore is there a way to achieve a connection to the handsfree profilethanks,['android'] +276031,jit optimizations at their finest i have read and heard a lot about how jit compilers can make optimizations that are impossible for native code compilers and that these optimizations can give huge performance boostsso i was wondering what are the most important optimizations that say the net framework or the jvm do that a native compiler cannot do also how do these give huge performance boostsi do not know whether i have phrased this question properly guess i may have a lot of explaining to do in the comments,['.net'] +276102,the microsoft jet database engine could not find the object sheet1 i am attempting to read a spreadsheet file called book1xls which contains a worksheet called sheet1however i am getting the following errorthe microsoft jet database engine could not find the object sheet1 make sure the object exists and that you spell its name and the path name correctlyhere is a snippet of the code i am usingdim dt as datatable new datatableselect case fileext case csv dim reader as new csvreader dt readergetdatatablefilepath case xls xlsx dim oledbconnstr as string select case fileext case xls oledbconnstr providermicrosoftjetoledb40data source filepath extended propertiesexcel 80hdryesimex2 case xlsx oledbconnstr providermicrosoftaceoledb120data source filepath extended propertiesexcel 120hdryesimex2 end select using oledbconn as oledbconnection new oledbconnectionoledbconnstr oledbconnopen dim oledbcmd as new oledbcommandselect from sheet1 oledbconn dim oledbda as new oledbdataadapteroledbcmd oledbdafilldt oledbconnclose end usingend selecti cannot understand why the code cannot find my worksheet why is this and how can i resolve it,['asp.net'] +276103,how to detect properly windows linux mac operating systems i could not found anything really efficient to detect correctly what platform windows linux mac my c progrma was running on especially on mac which returns unix and cannot hardly be differenciated with linux platforms so i made something less theoretical and more practical based on specificities of maci am posting the working code as an answer please comment if it works well for you too can be improvedthanks response here is the working code public enum platform windows linux mac public static platform runningplatform switch environmentosversionplatform case platformidunix well there are chances macosx is reported as unix instead of macosx instead of platform check well do a feature checks mac specific root folders if directoryexistsapplications directoryexistssystem directoryexistsusers directoryexistsvolumes return platformmac else return platformlinux case platformidmacosx return platformmac default return platformwindows,['c#'] +276108,best way to save variables between postbacks aspnet how can i save variables in aspnet between postbacki am using httpcontextcurrentitems but it always thisposes after postback is there any other option to do that,"['c#', 'asp.net', '.net']" +276128,process start event using wmi not all process starts being detected i am using the following c code in a windows service which runs as nt authoritysystem to create an event handler for receiving process creation events using wmi and wqlstring querystring select from win32 procestarttracemanagementeventwatcher watcher new managementeventwatchernew wqleventqueryquerystringwatchereventarrived new eventarrivedeventhandlerprocestarteventwatcherstartin procestarteventint processid intparseeneweventpropertiesprocessidvaluetostringprocess proc processgetprocessbyidprocessidoutreceived process procprocessnamethe problem i am having is that for some strange reason not every process start is captured and reported by the program if i start about 6 processes simultaneously one may not show up in the outputi have tried to do some research on capturing process creation events using wmi but there is limited information available i have seen that it is also possible to capture process starts using something similar toselect targetinstancefrom instancecreationeventwithin 2where targetinstance isa win32 processas seen in this stack overflow answerare there any major differences between using instancecreationevent and win32 procestarttrace could this be the cause of my problemsis there an explanation as to why i am not receiving events for all process starts is there something more obvious that i am doing wrong here,['c#'] +276135,modify stroke and fill of svg image with javascript i am trying to modify the stroke and fill of an svg imagei have been getting some information from is it possible to manipulate an svg document embedded in an html doc with javascripti used javascript to manipulate it the javascript in the headerfunction svgmod var s documentgetelementbyidsvg img ssetattributestroke0ffthe htmlbody onloadsvgmodimg idsvg img srcimagesvg any help appreciatededit1i think the main problem here is how to thisplay an svg image as an svg element an actual image that instead of an ending like png or jpeg uses an ending of svg and furthermore how the fill and stroke of it can then be manipulated,"['javascript', 'html']" +276161,background time issue for bluetooth le app for iphone 4s i am using corebluetooth framework for my app in iphone4sthis is typically has to be a background app which can run as longer as possible now it is only running for 40 min 1 hour max i am hoping for at least 1 day or so for this bluetoothcentral value is added in required background modes key in plist file it seems like my app is going to suspend mode at the end since when i open the app again background to foreground state it is sending the notification again it means the bluetooth connection is still connected and bledevice is still sending notification if i press home button and app comes to background it does not get notification againcan anybody tell me why my app live in background mode only for max 1 hour it should continue run like normal music app in background for like foreveris apple say anything specific about on which condition an background app which is one of those continuous running background app falling with in the 5 categories failing which it will go to suspend modereferring iphoneaprogrammingguide on communicating with a bluetooth accessory sectioni come to know that for long running background task for bluetooth le application 2 implementations are necessory1 uibackgroundmodes key should be bluetoothcentral in infoplist file2 any app that supports the background processing of bluetooth data must be sessionbasedso for my app the first implementation was incorporated and with that application is able to run in background and do all the tasks formax 1 hour durationnow i need to implement 2nd implementation ie sessionbased which will allow to get the events even if the app is in suspend stateaccording to the documentation i tried to find to create a suitable session specific to bluetooth le core bluetooth framework like theeasession present for classic bluetooth external accessory framework but i did not find itbasically i am not sure which session class i need to use for ble purpose for audiovideo networking and internet external accessorythere are individual session class available there is none for core bluetooth frameworkcould anybody help me with which session class is suitable for ble,['ios'] +276254,what is wrong with this logback pattern i am using this pattern patterndhhmms 5level logger36 fileline msgnpatternyet the output looks like094225811 warn andaoapianapi anapijava153the pattern appears to be truncated after the line it also happens if i use l what am i doing wrongi need this specific pattern so that eclipses console will recognize it,['java'] +276297,java jar file use resource errors uri is not hierarchical i have deployed my app to jar file when i need to copy data from one file of resource to outside of jar file i do this codeurl resourceurl getclassgetresourceresourcedatasavfile src new fileresourceurltouri error herefile dst new filecurrentpathdatasav currentpath path of jar file do not include jar file namefileinputstream in new fileinputstreamsrcfileoutputstream out new fileoutputstreamdst some excute code herethe error i have met is uri is not hierarchical this error i do not meet when run in ideif i change above code as some help on other post on stackoverflowinputstream in modelclassgetclassloadergetresourceasstreamresourcedatasavfile dst new filecurrentpath datasavfileoutputstream out new fileoutputstreamdstbyte buf new byte1024int lenwhile len inreadbuf 0 null pointer exception,['java'] +276322,get the html of the javascriptrendered page after interacting with it i would like to be able to save the state of the html page after i have interacted with itsay i click a checkbox or the javascript set the values of various elementshow can i save the javascriptrendered pagethanks,"['javascript', 'html']" +276328,libgdx shaders basic shader but screen is blank i am trying to understand shaders using libgdx coming from an xnahlsl background i am trying to get a vertfrag shader pair to reproduce the output i get without a shader but it is not thisplaying anythingshader creationvoid setupshader shaderprogrampedantic false shader new shaderprogram gdxfilesinternalassetsdefaultvertreadstring gdxfilesinternalassetsdefaultfragreadstring ifshaderiscompiled gdxapplogproblem loading shader shadergetlog batchsetshadershaderdefaultvertattribute vec4 a positionattribute vec4 a normalattribute vec2 a texcoordattribute vec4 a coloruniform mat4 you projtransvarying vec2 v texcoordsvarying vec4 v colorvoid main v color a color v texcoords a texcoord gl position you projtrans a positiondefaultfragifdef gl esprecision mediump floatendifvarying vec2 v texcoordsvarying vec4 v colorvoid main gl fragcolor v colorrenderingbatchbeginfor gameobject gobj gameobjects gobjdrawbatchbatchendany suggestions here i am new to opengles as well so i may be missing something obvious i looked around a bit before posting and the doc for spritebatchsetshadershaderprogram was as followssets the shader to be used in a gles 20 environment vertex position attribute is called a position the texture coordinates attribute is called called a texcoords0 the color attribute is called a color see shaderprogramposition attribute shaderprogramcolor attribute and shaderprogramtexcoord attribute which gets 0 appened to indicate the use of the first texture unit the projection matrix is uploaded via a mat4 uniform called u proj the transform matrix is uploaded via a uniform called u trans the combined transform and projection matrx is is uploaded via a mat4 uniform called u projtrans the texture sampler is passed via a uniform called u texture call this method with a null argument to use the default shader,['java'] +276333,android how to change texts in the preferences activity dynamically hello fellow programmers i have a little problem with preferences activityi have got just one preference category and a listpreferencexml version10 encodingutf8preferencecategory androidtitlestringbasic settings listpreference androiddefaultvalue70 androidentriesarraylistarray androidentryvaluesarraylistvalues androidkeyupdates interval androidpersistenttrue androidsummarystringsome summary androidtitlestringsome title preferencecategoryi need to have the selected value the default one or the user defined one written in the summary of the listpreference for examplewe will have at least 70 charactershow can i do this from the code any help is appreciated,['android'] +276341,boostasio shared memory and interprocess communication i have an application that is written to use boostasio exclusively as its source of input data as most of our objects are network communication based due to some specific requirements we now require the ability to use shared memory as an input method as well i have already written the shared memory component and it is working relatively wellthe problem is how to handle notifications from the shared memory process to the consuming application that data is available to be read we need to handle the data in the existing input thread using boostasio and we also need to not block that input thread waiting for datai have implemented this by introducing an intermediate thread that waits on events to be signaled from the shared memory provider process then posts a completion handler to the input thread to handle reading in the datathis is working now also but the introduction of the intermediate thread means that in a significant amount of cases we have an extra context switch before we can read the data which has a negative impact on latency and the overhead of the additional thread is also relatively expensiveheres a simplistic example of what the application is doinginclude iostreamusing namespace stdinclude boostasiohppinclude boostthreadhppinclude boostscoped ptrhppinclude boostbindhppclass simple threadpublic simple threadconst stdstring name name name void start thread resetnew boostthread boostbindsimple threadrun this private virtual void do run 0 void run cout started name thread as thread get id n do run protected boostscoped ptrboostthread thread stdstring name class input thread public simple threadpublic input thread simple threadinput boostasioio service svc return svc void do run boostsystemerror code e boostasioio servicework wsvc svc rune private boostasioio service svc struct dot void operator cout class interrupt thread public simple threadpublic interrupt threadinput thread input simple threadinterrupt input input void do run do boostthis threadsleepboostposix timemilliseconds500 input svcpostdot whiletrue private input thread input int main input thread inp interrupt thread intrinp inpstart intrstart whiletrue sleep10 is there any way to get the data handled in the input thread directly without having to post it in via the interrupt thread the assumption is that the interrupt thread is totally driven by timings from an external application notification that data is available via a semaphore also assume that we have total control of both the consuming and providing applications that we have additional objects that need to be handled by the input thread object so we cannot simply block and wait on the semaphore objects there the goal is to reduce the overhead cpu utilization and latency of the data coming in via the shared memory providing application,['c++'] +276362,ternary operation in coffeescript i need to set value to a that depends on a conditionwhat is the shortest way to do this with coffeescripteg this is how i would do it in javascripta true 5 10 a 5a false 5 10 a 10,['javascript'] +276442,javascript hide a div at startup load i have a div in my php page that uses jquery to hide it once the page has loaded but is there a way to hide it from the very start of loadupthe reason i ask is because for a brief second you can see the div when the page is loading and then hides when the page is fully loadedit looks unprofessionaljust wondering if there is a way around thisthanks,"['javascript', 'jquery', 'css', 'html']" +276446,setting itemssource of derived listbox throws catastrophic failure i am developing for windows 8 winrt framework the following sample code throws an exception catastrophic failure exception from hresult 0x80f e unexpectedis this one more bug in the current winrt framework i am using vs11 and consumer preview has someone an idea how to solve this problembtw i have tested the same code with windows phone 75 silverlight and it works without problemsthanks for your helppublic class mylistbox listboxpublic sealed partial class blankpage page public blankpage thisinitializecomponent protected override void onnavigatedtonavigationeventargs e var box1 new listbox box1itemssource new listobject new object works without problems content box1 var box2 new mylistbox box2itemssource new listobject new object throws exception content box2,['c#'] +276451,recurring events in calendar rails i am searching for the best way to model recurring events i am using fullcalendar to thisplay events but i guess recurring events are best handled on the rails backendi already looked at other questions and existing example code but i did not find anything which fitsit should behave similar like google calendar so it should be possible to deletemodify single events of the recurring event series but saving all events of the event series in the database seems inefficient also it should be possible to create single events without any recurrencewhat would be a good model architecturemy event model right now looks like that without additional attributes table name events id integer not null primary key employee id integer created at datetime updated at datetime starts at datetime ends at datetimeclass event activerecordbase attr accessible starts at ends atend,['ruby-on-rails'] +276458,philosophically why cannot markup be binary data ie why cannot we compile html for the web given the vast efforts to make the web as efficient as possible why cannot html and all the various other plain text files eg css javascript be compiled into a single resource and sent down the wire i am aware of chm files these are along the lines of this concepti understand the open nature of the web an effort i stand behind but one could conceive of an open specification that requires multiple resources compile down into binary decomplication by the useragent could be required by the specification this allowing individuals to view the dom etci guess i am just surprised given the efforts at performance in other areas were still relying on plain text to push around pages or am i just overestimating the savings a binary format would provide,['html'] +276465,force nonmonospace font into fixed width using css is there any way to force a font to be monospaced using cssby this i mean using a nonmonospace font can you force the browser to render each character at a fixed width,['css'] +276477,c arrays and make unique as a follow up to this post i wonder how its implementation of make unique plays with allocating functiontemporary buffer arrays such as in the following codef auto buf new intn temporary buffer use buf delete bufcan this be replaced with some call to make unique and will the version of delete be used then,['c++'] +276517,how to convert strings in any language and character set to valid filenames in java i need to generate file names from user inputted names these names could be in any language for example john smithea2aauu 31u u 1 u12u2 u3uthese are use inputted values so i have no guarantee that the names do not contain characters that are invalid to be in file names users will be downloading these files from their browser so i need to ensure the file names are valid on all operating systems in all configurationsi am currently doing this for english speaking countries by simply removing all nonalphanumeric characters with a simple regex string stringreplaceallazaz09 string stringreplacealls some example conversionsjohn smith john smithextjohn ohenry john ohenryextjohn van smith i john van smith iextobviously this does not work internationally i have considered findinggenerating a blacklist of all characters that are invalid on all file systems and stripping those from the names i have been unable to find a comprehensive list i would prefer to use existing code in a common library if possible i imagine this is an already solved problem however i cannot find a solution that works internationally the filename is for the user downloading the file not for me i am not going to be storing these files these files are dynamically generated by the server upon request from data in a database the filenames are for the convenience of the person downloading the file,['java'] +276525,lightweight database sql or nosql i am currently working on a website that must exist on a vm with very low memory availability at the moment i am told to expect 512mb unfortunately at least in the immediate future the database and web application must be the same servernow i have read through some questions here and tried to do my own research but there are just so many options to choose from essentially what will be a light enough database server that i can install sql or nosql does not really matter it would not be database intensive but i would like to not be constraint with whatever i choose now meaning if possible a path towards multiserver scaling would be great but obviously not a requirement at this stagemy current thoughts are either mongodb or mysql but i am not sure if those are the best choicesmy web application is running on nginx with php which i think is the best choice for now so my main concern is the database side,['sql'] +276544,upload file on ftp i want to upload file from one server to another ftp server and following is my code to upload file but it is throwing an error as the remote server returned an error 550 file unavailable eg file not found no accessthis my code string completedpath ftp url string uname username string pwd password webrequest reqobj webrequestcreatecompletedpath filename reqobjmethod webrequestmethodsftpuploadfile reqobjcredentials new networkcredentialuname pwd filestream streamobj systemiofileopenreadservermappathfilename byte buffer new bytestreamobjlength 1 streamobjreadbuffer 0 bufferlength streamobjclose streamobj null reqobjgetrequeststreamwritebuffer 0 bufferlength reqobj null can you please tell me where i am going wrong,"['c#', 'asp.net']" +276545,array to an unordered list i am trying to map some arrays values to an unordered list php files scandirdir remove and print rfiles ul php foreachfiles as file li file li php endforeach ulit does iterate through the array correctly as it gives bullets for li elements however no string output is seen next to those bullets also when i print r the array the values are therethe output looks like this with the correct number of bullets but no text next to them what am i doing wrong here thanks in advance,"['php', 'html']" +276567,dynamically arrange some elements around a circle i am looking for a function to arrange some elements around a circleresult should be something like,"['javascript', 'jquery']" +276575,javascript match regular expression against the array of items is there a way in javascript to get boolean value for a match of the string against the array of regular expressionsthe example would be where the if statement is representing what i am trying to achievevar thisexpressions something something else and something elsevar thisstring elseif matchinarraythisstring thisexpressions,['javascript'] +276594,stop devise from clearing session it seems when a user logs out via standard devise controllers devise destroys the entire session store not just its own data is there any way to avoid this behavior i have other irrelevant data that should be kept aroundsessionmy var 123log out via deviseputs sessionmy var nil,"['ruby-on-rails', 'ruby']" +276617,microsoft rewriting module force w on url or remove w from url i have a shared hosting plan with windows server 2008 and iis75 and there is microsoft rewriting module installed and enabledrewrite rules rule namemyrule patternsyntaxwildcard rewriting code rule rulesrewriteso how to redirect mydomaincomeverywhereinsitemypagehtml to wmydomaincomeverywhereinsitemypagehtml with microsoft rewriting moduleand what if i want to redirect wmydomaincomeverywhereinsitemypagehtml to mydomaincomeverywhereinsitemypagehtml,['asp.net'] +276632,scroll part of content in fixed position container i have a position fixed div in a layout as a sidebar i have been asked to have part of it is content stay fixed to the top of it internally and the rest to scroll if it overflows the bottom of the divi have had a look at this answer however the solution presented there does not work with position fixed or position absolute containers which is a paini have made a jsfiddle demonstration of my problem here the large amount of text should ideally scroll instead of overflowing into the bottom of the page the height of the header can vary with content and may be animatedjsfiddle example codecssdivsidebar padding 10px border 1px solid c background f position fixed top 10px left 10px bottom 10px width 280pxdivfixed background 76a7dc paddingbottom 10px color fdivscrollable overlowy scrollhtmldiv clasidebar div idfixed fixed content here can be of varying height using jquery animate div div idscrollable potentially long content divdivawithout a fixed header i can simply add overflowy scroll to divsidebar and i can happily scroll all it is content if it overflows the bottom of the container however i am running into issues with having a fixed variable height header at the top of the sidebar and having any content underneath that scroll if it is too long to fit into the container divsidebar must stay position fixed and i would very much like to do this without any hacks as well as make it as cross browser as possible i have attempted various things but none of them work and i am unsure as to what to try from herehow can i make a div inside a position fixed container scroll only in the y direction when it is content overflows the containing div with a fixed header of varying indeterminate height i would very much like to stay away from js but if i have to use it i will,['css'] +276656,height of outer div not expanding with inner div i have a bodymain div of 100 width inside it is a body div 800px with auto margincan i use body as id inside this are two divs bodyleft and bodyright 200px and 600px wide respectively when i add content to inner divs neither bodymain nor body expands in height all heights are autohere is the code htmlbody div idbodymain div idbody div idbodyleft left text goes herebr div div idbodyrightright text goes here div div divbodycssbodymain border1px solid red width100 heightautobody border1px solid green width804px heightauto marginautobodyleft border1px solid blue floatleft width200px heightautobodyright border1px solid orange floatright width600px heightauto,"['html', 'css']" +276667,looking for algorithm to find boundary of color region i have a canvas with image drawn to itwhen the user clicks on the image i need to find the color region that the user clicked on a region is defined as a set of 4way connected pixels with the same color as the pixel that was clicked oni need the region in a form that i could use to set a clipping path on the canvas so that i could fill the area with say a gradient etcare there efficient algorithms for finding a boundary something more optimal than flood fill algorithms i do not need to fill i just need to find a path around my region,['javascript'] +276693,cure for the string is not permitted within comments exception i am using java 6 i have this dependency in my pom dependency groupidxercesgroupid artifactidxercesimplartifactid version2100version dependencyi am trying to parse an xhtml doc with this line if gte mso 9xml wworddocument wviewnormalwview wzoom0wzoom wtrackmoves wtrackformatting wpunctuationkerning wvalidateagainstschemas wsaveifxmlinvalidfalsewsaveifxmlinvalid wignoremixedcontentfalsewignoremixedcontent walwaysshowplaceholdertextfalsewalwaysshowplaceholdertext wdonotpromoteqf wlidthemeotherenuswlidthemeother wlidthemeasianjawlidthemeasian wlidthemecomplexscriptxnonewlidthemecomplexscript wcompatibility wbreakwrappedtables wsnaptogridincell wwraptextwithpunct wuseasianbreakrules wdontgrowautofit wsplitpgbreakandparamark wenableopentypekerning wdontflipmirrorindents woverridetablestylehps wusefelayout wcompatibility mmathpr mmathfont mvalcambria math mbrkbin mvalbefore mbrkbinsub mval msmallfrac mvaloff mthispdef mlmargin mval0 mrmargin mval0 mdefjc mvalcentergroup mwrapindent mval1440 mintlim mvalsubsup mnarylim mvalundovr mmathprwworddocument xmlendifusing this code documentbuilderfactory factory documentbuilderfactorynewinstance factorysetvalidatingfalse factorysetexpandentityreferencesfalse factorysetfeature false final documentbuilder builder factorynewdocumentbuilder final inputsource s new inputsourcenew stringreaderstr orgw3cdomdocument result builderparsesbut my parsing is dying with the following exception fatal error 91947 the string is not permitted within commentsorgxmlsaxsaxparseexception the string is not permitted within comments at orgapachexercesparsersdomparserparseunknown source at orgapachexercesjaxpdocumentbuilderimplparseunknown source at commycomyprojectutilxmlutilitiesgetstringasdocumentxmlutilitiesjava201 at commycomyprojectutilnetutilitiesgeturlasdocumentnetutilitiesjava67 at commycomyprojectparsersimplforesighteventsparsergeteventsfromelementforesighteventsparserjava133 at commycomyprojectparsersimplforesighteventsparserparsepageforesighteventsparserjava99 at commycomyprojectparsersimplforesighteventsparsergeteventsforesighteventsparserjava58 at commycomyprojectdomaineventfeedrefresheventfeedjava87 at commycomyprojectdomaineventfeedgeteventseventfeedjava72 at commycomyprojectparsersimplforesightparsertesttestparserforesightparsertestjava49 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava39 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava25 at javalangreflectmethodinvokemethodjava597 at orgjunitrunnersmodelframeworkmethod1runreflectivecallframeworkmethodjava44 at orgjunitinternalrunnersmodelreflectivecallablerunreflectivecallablejava15 at orgjunitrunnersmodelframeworkmethodinvokeexplosivelyframeworkmethodjava41 at orgjunitinternalrunnersstatementsinvokemethodevaluateinvokemethodjava20 at orgjunitinternalrunnersstatementsrunbeforesevaluaterunbeforesjava28 at orgspringframeworktestcontextjunit4statementsrunbeforetestmethodcallbacksevaluaterunbeforetestmethodcallbacksjava74 at orgspringframeworktestcontextjunit4statementsrunaftertestmethodcallbacksevaluaterunaftertestmethodcallbacksjava83 at orgspringframeworktestcontextjunit4statementsspringrepeatevaluatespringrepeatjava72 at orgspringframeworktestcontextjunit4springjunit4classrunnerrunchildspringjunit4classrunnerjava231 at orgjunitrunnersblockjunit4classrunnerrunchildblockjunit4classrunnerjava50 at orgjunitrunnersparentrunner3runparentrunnerjava193 at orgjunitrunnersparentrunner1scheduleparentrunnerjava52 at orgjunitrunnersparentrunnerrunchildrenparentrunnerjava191 at orgjunitrunnersparentrunneraccess0parentrunnerjava42 at orgjunitrunnersparentrunner2evaluateparentrunnerjava184 at orgspringframeworktestcontextjunit4statementsrunbeforetestclasscallbacksevaluaterunbeforetestclasscallbacksjava61 at orgspringframeworktestcontextjunit4statementsrunaftertestclasscallbacksevaluaterunaftertestclasscallbacksjava71 at orgjunitrunnersparentrunnerrunparentrunnerjava236 at orgspringframeworktestcontextjunit4springjunit4classrunnerrunspringjunit4classrunnerjava174 at orgeclipsejdtinternaljunit4runnerjunit4testreferencerunjunit4testreferencejava50 at orgeclipsejdtinternaljunitrunnertestexecutionruntestexecutionjava38 at orgeclipsejdtinternaljunitrunnerremotetestrunnerruntestsremotetestrunnerjava467 at orgeclipsejdtinternaljunitrunnerremotetestrunnerruntestsremotetestrunnerjava683 at orgeclipsejdtinternaljunitrunnerremotetestrunnerrunremotetestrunnerjava390 at orgeclipsejdtinternaljunitrunnerremotetestrunnermainremotetestrunnerjava197without changing my xhtml anyone know how i can parse this document successfullyedit per the comments given i removed the term wellformed from my original question i am still really interested in how to make this exception go away without changing the text i am parsing which i do not have control over for the purposes of this question you can assume the within comments is the only violation of the term wellformed,['java'] +276711,saving state of webview and restoring in android i have an android application which built with viewpager and seperated webviews in each page every webview points different web sites for instance page1 facebook page2 twitter page3 google user can addremove pagesmy mpagersetoffscreenpagelimit1 where mpager is an instance of viewpager which means when user views 3 page the first fragment is being thisposed and recreated when user views 2 page againwhat i want is to save first webviews state before destroys and save its state somewhere and then restore it when user sees it because it reloads the page and obviously its annoying and i do not want user to reload web pages on every swipe i have tried with mwebviewsavestateoutstatemwebviewrestorestatesavedinstancestatebut it does not seem work any ideas for saving and restoring states of webviewsi have tried saving webview itself in some class saving states etc,['android'] +276745,how can i get gcc to add a prefix to all symbol names i know that in the past there was an option fprefixfunctionname that would add a prefix to all generated symbols it does not seem to be part of gcc anymore is there any other way to do this,"['c++', 'c']" +276776,making a module inherit from another module in ruby i am making a small program for rails that includes some of my methods i have built inside of a module inside of the applicationhelper module heres an examplemodule helper def time timenowyear endendmodule applicationhelper inherit from helper hereendi know that applicationhelper helper and include helper would work in the context of a class but what would you use for moduletomodule inherits thanks,['ruby'] +276777,efficient integration of qt and opencv i am working on an interactive application which needs to read and manipulate several very large images at once 25 images at a time roughly 350 mb total size opencv is quite speedy and handles the algorithms with relative ease but drawing them with qt is proving to be a problem here are two lessthanideal solutions i have triedsolution 1 too slowevery time you need to draw a different opencv image convert it to a qimage and draw that the conversion unfortunately takes a while and we cannot switch between images at interactive speedssolution 2 too memoryintensivemaintain two stacks of images one for opencv and one for qt use the appropriate one at the appropriate timei have direct access to the opencv pixel data i know the width and height of the image and i know that pixels are 3byte rgb values it seems like it should be possible to draw the opencv image quickly without copying it to a qimage container that as far as i can tell just contains a duplicate of the datawhere do i need to look to get this kind of capability out of qt,['c++'] +276784,documentheadappendchild or documentcreateelement not working in ie i have a script running in the head of my html document and it works in every browser except for internet explorer tested in opera safari chrome firefox internet explorermy code is as followshtml head script type textjavascript var date new date var month dategetmonth 1 if month 3 month 5 var newscript documentcreateelementscript newscripttype textjavascript newscriptsrc source1js var newstyles documentcreateelementlink newstylesrel stylesheet newstylestype textcss newstyleshref css1css documentheadappendchildnewscript documentheadappendchildnewstyles else var newscript documentcreateelementscript newscripttype textjavascript newscriptsrc source2js var newstyles documentcreateelementlink newstylesrel stylesheet newstylestype textcss newstyleshref css2css documentheadappendchildnewscript documentheadappendchildnewstyles script head body my content goes here bodyhtmli am not sure if it is the documentcreateelement or documentheadappendchild that is not working in ie as stated before it works in all other browsers that i have tested it in help with this would be greatly appreciated as i will continue to find the problem solution myself thanks,['javascript'] +276794,internet explorer and base64 image thisplay in aim to manipulate more easily various images on client side with javascript i wrote a function on server side in vb 2010 to convert a file into a base64 string that i send to the client when i tried it in internet explorer 80 with 3 different images 1 portrait and 2 landscapes i realized that only the portrait image was thisplayed entirely meanwhile both landscape images were truncated i can see just the upper part of the imagei thought i had a bug in my conversion function until i tried my local page with firefox every image is perfectly thisplayed by firefoxso there is my question is this a wellknown bug of internet explorer if the answer is yes is there a wellknown remedy for that wellknown bug,['javascript'] +276808,need to reset the value of sequence in oracle i am working with spring and hibernate to develop web applications in java let us assume that i have a table when i delete some records from this table sometimes i need to reset the value of the primary key field let us say that i have 10 records in a table and i delete the last 5 records now when i insert new records the value of the primary key field should be started at 6 but it would start at 11if i need to start the primary key value at 6 maximum 1 in mysql i just need to execute the following sql statementalter table table name auto increment1this will automatically reset the value of auto increment to maximum 1 value of that field may conceptually be incorrect but it works in oracle 10g i am using sequence with the primary key is there a way in oracle to reset the value of the sequence to maximum 1 value when some records are deleted from the database,['java'] +276835,update datatables jquery when button is clicked i have created a simple form and i am using the datatables jquery plugin to thisplay some data in it data are being populated by a php script processphp which returns the proper results in json format in the form there is a button that sends the value of the textbox to the processphp the problem is that i cannot updatealter datatable with the new data received by processphp script when the button is clickedthe code of the formform namemyform idmyform action methodpost label foridenter an idlabel input typetext nametxtid idtxtid value input typebutton idbtnsubmit namebtnsubmit valuesearch formdiv idresults table classthisplay idexample thead tr thidth thsurnameth thnameth tr thead tbody data goes here tbody tablediv to create the datatable i am using the following jquery code documentreadyfunction var otable exampledatatable spaginationtype full numbers ithisplaylength 10 bserverside true sajaxsource processphp btnsubmitclickfunction ajax type post url processphp data txtid txtidval success functionresult otablefnreloadajax otablefndraw processphp script works fine isphpresultif empty requesttxtid result aadata1surname1name1else result aadata2surname2name2print result,['jquery'] +276846,how to print list as table in console application i need method to print list as table in console application and preview in convenient format like thispom no item code ordered qty received qty1011 item code1 ordered qty1 received qty1 1011 item code2 ordered qty2 received qty21011 item code3 ordered qty3 received qty31012 item code1 ordered qty1 received qty1 1012 item code2 ordered qty2 received qty21012 item code3 ordered qty3 received qty3,"['c#', '.net']" +276858,blurry text in wpf even with cleartypehinting enabled i have a grid with this template and styles in wpfxamlsetter propertytextoptionstextformattingmode valuethisplay setter propertyrenderoptionscleartypehint valueenabled setter propertytemplate settervalue controltemplate targettypextype datagridcell border paddingtemplatebinding padding borderbrushtemplatebinding borderbrush borderthicknesstemplatebinding borderthickness backgroundtemplatebinding background snapstodevicepixelstrue contentpresenter xnamecellcontent snapstodevicepixelstemplatebinding snapstodevicepixels renderoptionscleartypehintenabled border controltemplatetriggers trigger propertyisselected valuetrue setter targetnamecellcontent propertytextoptionstextformattingmode valuethisplay setter targetnamecellcontent propertyrenderoptionscleartypehint valueenabled setter targetnamecellcontent propertyeffect settervalue dropshadoweffect shadowdepth2 blurradius2 colorblack renderingbiasquality settervalue setter trigger controltemplatetriggers controltemplate settervaluesetterthe dropshadoweffect i have when you select a grid row seems to make the text rendering blurry gray antialiasingwhen i remove the drop shadow effect it looks clear because it now uses cleartype and not gray subpixel antialiasingi have tried applying renderoptionscleartypehintenabled to the contentpresenter as seen above but it does not helphow do i force wpf to render the text that gets thisplayed with drop shadow effect to retain cleartype antialiasing instead of that ugly blurry gray subpixel antialiasingsome believe it is blurry because of the drop shadow this is not true it is blurry only because cleartype is not used this is how it looks like in firefox when shadow and cleartypecleartype enabled text is colorful but that blurry text is not because it does not use cleartype it uses gray subpixel antialiasing and that is not how cleartype works the question is how do i enable cleartype for this text,"['c#', '.net']" +276875,getting the gpu connection type in windows xp i need to detect in code c how the graphics card is connected to the monitors ie vga or dvi etc i found two ways that i could do thisby querying the windows management instrumentation for d3dkmdt video output technology or using the nvidia api function nvapi thisp getmonitorcapabilities but both of these are only supported in windows vista or higher there must surely be a way of doing this in xp but after much searching i just cannot find one and it is becoming quite urgent that i find a way any ideas,['c++'] +276876,eclipse change name of existing package with classes inside in eclipse is it possible to change name of the package if it has name default package and has classes inside it,['java'] +276895,contenteditable div vs iframe in making a richtextwysiwyg editor i am trying to weigh the pros and cons of using a div vs iframe in making my own rich textwysiwyg editorin doing so why cannot i just use a contenteditable div and why do so many people prefer the iframe background thiscussiona common way to go about making a wysiwyg editor as i understand is to make a div or iframe contenteditable and to then to do execcommand on the document containing the div or the iframe body to make its text bold or whateverheres the htmlhtmlparent doc bodybutton typebutton classbtnboldboldbutton div contenteditabletruediv bodyhtmlvshtmlparent doc bodybutton typebutton classbtnboldboldbutton iframe body contenteditabletruebody iframe bodyhtmland the jsdocumentbodyonclick btnbold function documentexeccommandbold false null vsdocumentbodyonclick btnbold function windowframes0documentbodyexeccommandbold false null it looks like most wellmade richtext editors use an iframe while i can easily get this contenteditable execcommand combo to work on a diviframe in webkit browsers i am having a hellish time trying to get the iframe to work in firefox i am having to resorting to loading scripts and stylesheets into the iframe and all sorts of nonsense to duplicate what i can easily accomplish with the divbased version so the divbased method seems preferable any strong reasons i reconsider,"['javascript', 'jquery']" +276911,how do i remove the divider from a listview on android i am developing a app that have a listview and the items from list already have a style i do not need the dividerhow do i set as hidden or remove the divider from the listview,['android'] +277005,how to declare an enum value as being deprecated in objectivec 20 suppose a long time ago i had created the following enumerationtypedef enum geometricpoint geometricline geometricsquare geometricrectangle geometriccirclegeometricfiguresi introduced those a while ago within my awesome engine and now i have finally decided that people should not use geometricsquare anymore as that is covered by geometricrectangle alreadyfor a start i would possibly change my enumeration towards something like thistypedef enum geometricpoint geometricline geometricrectangle geometricsquare geometricrectangle geometriccirclegeometricfiguresthat would certainly keep my awesome engine backwards compatible but on the other hand increase the legacy junk hence i would like to remove geometricsquare altogether in a foreseeable future to make that obvious to the users of my engine i would like to mark geometricsquare as being deprecatedmy goal is that the documentation doxygen as well as the code completion xcode and last but not least the compiler gcc will make it obvious to the user that geometricsquare should not be used anymore and has been replaced by geometricrectangle for the documentation i would simply use deprecated keywordtypedef enum geometricpoint geometricline geometricrectangle deprecated has been replaced by geometricrectangle geometricsquare geometricrectangle geometriccirclegeometricfiguresbut how about xcode and gccunfortunately the usual gcc method attribute does not seem to do the job adding attribute deprecated as drafted below causes a syntax error typedef enum geometricpoint geometricline geometricrectangle geometricsquare geometricrectangle attribute deprecatedparse issue expected geometriccirclegeometricfiguresso obviously that either does not work altogether or i am simply using it wrong,['objective-c'] +277019,are the alert and confirm functions built into javascript or are they part of the dom are the alert and confirm functions built in to javascript or are they part of the dombonus points if you can refer me to a reference that will allow me to easily tell what functions are directly built in to javascript,['javascript'] +277020,how do i get yaml in ruby as of 193 to dump ascii8bit strings as strings heres the problem i might have strings that are utf8 and i might have strings that are usascii regardless of the encoding i would like yamldumpstr to actually dump string objects instead of these useless binary objects as the example showsis there a flag or something i am not seeing to force yamldump to do the right thingruby 191 exampleyamlversion 060a foo fooaforce encodingbinary fooyamldumpa foon ruby 193 exampleyamlversion 122a foo foo aforce encodingbinary foo yamldumpa binary n zm9vnupdate got my own answeryamlengineyamlersyckyamldumpa foon so looks like using the old yamler engine with force the old behavior,['ruby'] +277043,how to make a jquery getajax request to a privatecustom url protocol on both mac and ios platforms it is possible to do twoway interchange with the native runtime through custom uri schemes a nsurlprotocol for example to request an nsimage from a native objectivec method you can register your custom handler a simple string here i used mycustomprotocol with webkit your webview nsview and call it from js likeavar theurl mycustomprotocol textfieldvalueimginnerhtml img srctheurl idstringi would like to be able to use jquery to do make requests as at this point it is more familiar than 90sstyle js but as far as i can find on the web get and ajax only do httpswould something like javascriptdocumentlocation mycustomprotocoloverride jquerys url handling i am a dumbdumb when it comes to javascript i am sure this is easily done i do believe this is how the entire jquery mobile framework is implemented via private uris so why is there nothing on google or so about it huh can i get some help from my sister friends,"['jquery', 'ios']" +277088,encrypting decrypting a string in c what is the most modern best way of satisfying the following in cstring encryptedstring somestaticclassencryptsourcestringstring decryptedstring somestaticclassdecryptencryptedstringbut with a minimum of fuss involving salts keys mucking about with byte etcbeen googling and confused at what i am finding you can see the list of similar so qs to see this is a deceptive question to ask,['c#'] +277100,decoding an arbitrary block of nsdata if i have an arbitrary block of nsdata as a hex value is there a way to determine what the object might have been before it was archived or serialized i do not mind a few guess and check methods but i need some pointers in the right direction i have an nsdata object with some hex in it what methods of nsdata should i look at are there other classes to try as welldo not want to scare people away from answering but i have a file of game data which was likely encoded using a cocoa touch class the data when viewed in a hex editor shows gibberish and a username which leads me to suspect that it is an archived or encoded object of sorts i have copied the hex from the hex editor into a sample project which i am using to try and unarchive the datai do not believe this is related to the 3d format the file extension is arbitraryheres the data i am hoping it does not get lost in translationakaxna14ahf9a39vaceea zahmoshbermaoaa3a14ppa1ava4aalkasafagtmqa14a 87a ya3qa2alaasg4sa123a12ja9a awxida2ma14ab39a a34a3a7a34aa aoaa3aefarbmaygaaqlua3aaoa14a 6a a14agoaajsepsa aeaa 6a2aa3a a142a a 7acaal4qga a aaxka4fzaapaattuan4aa3afaga and the corresponding hex27 b5 6b f6 01 00 00 00 58 4e 5b ce c0 fc f7 68 2f 46 86 87 83 39 f3 39 9e 56 ec f1 b0 63 9e 65 45 b8 7a b6 3d 07 99 48 6d 6f 73 68 62 65 72 6d 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 90 86 fa 03 0e ab f3 bc 0b 50 70 f9 23 dd 87 56 03 d4 3d 34 90 e2 ae 4c 2c 94 9e 8e 15 4b 0c 83 8c 3b 03 ca e7 3b 1b 41 53 c0 26 04 cb f7 eb d3 25 c8 3b da 66 8a ac 47 7d 8a 7f 74 6d 51 3b b5 19 e9 fc f8 5f 38 37 b4 11 0c 79 a9 12 e3 a9 21 df b6 f3 51 f2 41 e7 db 85 02 9f 6c a9 e2 53 47 1f 34 86 53 bd 33 fd 4a d7 aa 39 c3 a4 f4 a1 77 78 69 44 b2 4d bc cf 42 5d 33 39 f8 fe 97 3a 81 f3 f1 10 37 aa be 86 91 f7 1f e8 83 ba a3 c8 33 cf 1d a2 cd 45 7f 46 1f cd a2 aa bb 1a 72 5d 42 02 6d c1 0f 27 d2 2b e5 0b 79 67 de c5 1a 51 3f 14 6c 75 f3 3e f7 fa bc e8 36 8e b8 7c 02 1c 7d 01 00 92 8c 19 5b bc 5b b6 d1 a6 67 7f 21 5c 84 13 4f ce 0c d2 4a 53 19 82 45 1b 2e 2e 96 70 53 df 26 5f c8 1c 45 8f e4 f8 29 36 f2 eb 9d 95 f3 a8 bc 32 b6 f0 b0 e6 91 98 1a e0 99 60 ef 37 cb 3d c3 a5 3a 63 0c c6 a7 3d 4c 34 71 47 2d 22 b5 28 d0 dd ef df 09 d3 e3 58 6b c0 17 34 66 7a e6 b7 70 5c f1 f1 54 3c 74 94 75 a5 c6 15 a9 9e 14 3b cc 15 10 83 6e 34 a3 b3 cf 0f a2 9c cc 8e 46 8c e5 00 00 47 b4 17 05 00 00 00 00if anyone cares to help figure this out it would be much appreciated,"['iphone', 'objective-c', 'ios']" +277102,restkitrestkith file not found error version 0100 i am losing my hair in my attempts to get restkit to build and work i get the dreaded lexical or preprocessor issue restkitrestkith file not found message i use xcode 42 my project is for iosearlier i had debug mode working perfectly with restkit 090 then i ran into issues while trying to archive after reading this forum and attempting some solutions i decided to upgrade to 0100 with hopes that it will solve the issuenow my project is not even building in debug mode and i get the same restkitrestkith file not found errori have this under header search path built products dirheaders can you please suggest for 0100 version1 where should the physical location of restkit be it may not matter but which one worked for you with hopes that i can mirror your setting2 i tried to point my header search path to developerlibraryrestkitrestkit69adee9 and later to developerlibraryrestkitrestkit69adee9buildthroughly confused and frustratededit1 after several hours i gave up nuked my project created a fresh project recreated the files copy paste from prev project now restkit not found error is gone but now i am getting this other errorundefined symbols for architecture i386 objc class rkobjectmapping referenced fromobjcclassref in myclassname1o objc class rkobjectmanager referenced fromobjcclassref in myclassname2old symbols not found for architecture i386clang error linker command failed with exit code 1 use v to see invocationi checked made sure that i did not add restkitframework i have no idea why the clang error is happening nowedit2 the librestkita was red it is ok according to just for the heck of it i removed all the linked dependencies removed the other linker flags closed reopened xcode put them all back that error is gone maybe i missed a framework which resulted in clang error but it is highly unlikely for i checked double checked it works nowit builds archives on debug mode i have not tried the thistribution mode yetedit3 apple approved my app in the first go it is live i still do not know what caused the issue here nuking an existing project creating a new one copying over the old files periodically checking if build goes through cannot be a solution so i am leaving this question open,"['iphone', 'ios']" +277130,how can i invoke a restful service through apache camel i am currently using a http method for invoking some url which will create a jira issuenow i want to use apache camel how can i use thati need to invoke the following link through camelhttplocalhost8080restapi2project key componentsas i am new to camel please suggest some solutions and examples toothanks,['java'] +277143,mysql error 1449 the user specified as a definer does not exist when i run the following query i get an errorselect asl id as sl id aquote id as quote id asl date as sl date asl type as sl type asl status as sl status bclient id as client id bbusiness as business baffaire type as affaire type bquotation date as quotation date btotal sale price with tax as total sale price with tax bstatus as status bcustomer name as customer namefrom tbl supplier list a left join view quotes b on bquote id aquote idlimit 0 30the error message is1449 the user specified as a definer web2vi does not existwhy am i getting that error how do i fix it,['mysql'] +277176,how can i clear notification in button click in my project i have notification option can i remove this notification in a button click i can cancel notification when click on this notification using the code checkin notificationflags notificationflag auto cancelbut i in my application i want to clear notification after showing it it should be in a button clickthanks in advance,['android'] +277259,how to iterate a dictionary in reverse orderfrom last to first in c i have one dictionary and added some elements on itfor exampledictionarystring string d new dictionarystring stringdaddcontentlevel0daddgdlhlevel1daddshowslevel2daddytyelevel0in c dictionary keeps elements in natural orderbut i now want to iterate those values from last to firstie reverse orderi meanfirst i want to read ytye then showsgdlh and finally contentplease guide me to get out of this issue,['c#'] +277263,regular expression include and exclude special characters i am finding a regular expression which adheres below rules allowed charactersalphabet az aznumbers 09special characters spaces should be allowednot allowedspecial characters,['java'] +277267,how to change the size of a switch widget in ice cream sandwich a switch widget was introduced that thisplays an on off slider i added the switch like this switch androidlayout widthfill parent androidlayout height48dp androidtextstylebold androidthumbdrawableswitch thumb selector androidtrackdrawableswitch bg selector the track and thumb drawables are nine patch images that should scale to all possible sizesi hoped that the switch would scale to the maximum size inside the given bounds but it seems as if the drawables are just centered inside the supplied space is it possible to increase the size of the switch to make it appear bigger,['android'] +277275,drag and drop file upload library for internet explorer i found a great library called jquery file upload for draganddrop files uploads in modern browsers unfortunately draganddrop does not work in internet explorerdraganddrop file upload in ie is a requirement of the project so i would like to find a solution for this specific situation my idea is to end up with two versions of the upload page one for ie and another one for the rest of the worlddoes anyone know a good activex library for such uploads in ie that does not require any installation,['javascript'] +277283,cannot assign value to final variable in java private void pushbuttonactionperformedjavaawteventactionevent evt final int c0 final jdialog dnew jdialog jlabel lnew jlabelenter the element jbutton but1new jbuttonok jbutton but2new jbuttoncancel final jtextfield fnew jtextfield10 jpanel panel new jpanel but1addactionlistenernew actionlistener public void actionperformedactionevent e cintegerparseintfgettext dsetvisiblefalse dthispose but2addactionlistenernew actionlistener public void actionperformedactionevent e dsetvisiblefalse dthispose i am using netbeans 711 this is my code here i have declared c as final int but the line cintegerparseintfgettext i am getting an error cannot assign a value to a final variable if i am deleting the word final from the declaration and making it just as int c then in the same line i get an error local variable c cannot be accessed from within a classneeds to be declared final can anyone tell me why is this happening,['java'] +277292,why cannot i reference systemcomponentmodeldataannotations i am trying to use dataannotations in my wpf project to specify a maximum length of strings with the followingusing systemcomponentmodeldataannotationshowever i get the errorthe type or namespace name dataannotations does not exist in the namespace systemcomponentmodel are you missing an assembly referencei have seen other examples where dataannotations does exist in this namespace i am using c4 is there any reason why i cannot use this what can i do to fix it,['c#'] +277319,how to route a aspx page in aspnet mvc 3 project i have a aspx page in the following pathareasmanagementviewsticketreportaspxi want to route that to the following path in my browserhttplocalhostreportsticketshow can i do thati try thisroutesmaproute tickets route name areasmanagementviewsticketreportaspx original url new controller reports action tickets new url but i got the 404 errorwhat i am doing wrongobs i put that before the default route,"['c#', 'asp.net']" +277324,maintain textbox scroll position while adding line in my winform application i have a multiline textbox control uiresults which is used for reporting progress while processing a large number of items using appendtext works great for automatically scrolling to the bottom at every update but if the user scrolls back to read some older data i need to turn off the autoscroll i would rather stay away from pinvoke calls if possibleis it possible to detect if the user has scrolled back without using pinvoke for now i just check selectionstart which works but requires the user to move the caret from the end of the textbox to stop the autoscrollifuiresultsselectionstart uiresultstextlength uiresultsappendtextresult environmentnewlinemy main problem is that when appending a string using the text property the textbox is scrolled to the beginning i tried to solve this by storing the caret position and resetting and scrolling to it after the update but this causes the current line to move to the bottom of course since scrolltocaret scrolls no more than the necessary thistance to bring the caret into viewcontinued from aboveelse int pos uiresultsselectionstart int len uiresultsselectionlength uiresultstext result environmentnewline uiresultsselectionstart pos uiresultsselectionlength len uiresultsscrolltocaret,"['c#', '.net']" +277348,very simple wpf program locks up hangs on keyboard layout change the following program locks up reproducibly whenever the user changes the keyboard layout via a key combination it does not lock up if the keyboard layout is changed via the tray applet it does not lock up when changing the layout to english it does not lock up if the task never executesxamlstackpanel textboxtextbox button clickbutton clickclick mebuttonstackpanelcprivate void button clickobject sender routedeventargs e taskfactorystartnew var visual new drawingvisual using var context visualrenderopen before the button click i can switch keyboard layouts as i please after the click the program locks up on the first attempt to switch layoutsimportantly this bug only occurs if the layouts are switched via altshift2 or ctrlshift2 and 3 but not 1itas way way too late to avoid the use of drawingvisual on background threads this has become an integral core feature of the product any ideas for how to work around this are very welcomethis bug reproduces on net 40 win7 32bit and 64bitbounty this bug affects few people in terms of percentage but those it does affect will constantly cause the lockup with the corresponding data loss every time they habitually change the keyboard layout via the shortcut i would like a workaround which does not change the fact that some visuals are rendered on a separate thread,['.net'] +277353,dynamically set func types is there any way to set func type arguments dynamically so i do not have to use endless if statementssomething liketype t typegettypesystemdecimalfunct foo new functsome functioninstead offuncdecimal foo new funcdecimalsome functionupdateheres a snippet from my codetype t typeofstavkadokumentagetpropertypdpoljepropertytypeparameterexpression pe expressionparametertypeofstavkadokumenta stavkaexpression expr expressionsresolvecompleteexpressionpe pdexpressionexpression final expressionconvertexpr tif t typeofdecimal var lambda expressionlambdafuncstavkadokumenta decimalfinal pe o lambdacompileinvokestavkaif t typeofdecimal var lambda expressionlambdafuncstavkadokumenta decimalfinal pe o lambdacompileinvokestavkaelse if t typeofint var lambda expressionlambdafuncstavkadokumenta intfinal pe o lambdacompileinvokestavkaelse if t typeofint var lambda expressionlambdafuncstavkadokumenta intfinal pe o lambdacompileinvokestavkaelse if t typeofstring var lambda expressionlambdafuncstringfinal null o lambdacompileinvokepdpolje is string name of a property inside stavkadokumenta classpdexpression is string expression that must evaluate to type of poljestavka is an instance of stavkadokumenta,['c#'] +277408,instead of trigger would it infinitely loop would an insert statement on a table that has an instead of trigger cause an infinite instead insert loop of executionsfor example this create trigger setdesctoupper on part numbersinstead of insertasbegin insert into part numbers cola colb part description select cola colb upperpart description from insertedendgowould the insert statement inside the instead of trigger cause a loopi dont wanna thisable recursive triggersdo i need to temporarily thisable the triggersource sql server after insert trigger update another column in the same table,['sql'] +277416,phprethis on windows 7 64bit xampp i am trying to make rethis work on my windows machine for development purposes i already made rethis up and running on my ubuntu 1004 server with phprethis clientat the moment on my windows machine i can start rethis server because it requires no installation and it is good enaugh for development but i cannot figure out how to install phprethis it seems very confusing i already spend two days working on this and no resulti have cloned source files with git but i did that using git bash but that was last command who worked in the same way as ubuntu i also have downloaded two dll files one with ts and another with nts have no idea what is the difference there is manual how to install phprethis but it works only on ubuntu for my i am very newbie for a command line and i am not sure if this even suppose to work on windows like with cmd or git bashso my question is how can i make that phprethis work on windows is there is any way to make that happen i know there is prethis and i already tried that one but because i am planning to use phprethis on my server i would like to use same on development machine,['php'] +277428,how to convert a binary string to a base 10 integer in java i have an array of strings that represent binary numbers without leading zeroes that i want to convert to their corresponding base 10 numbers considerbinary 1011 becomes integer 11binary 1001 becomes integer 9binary 11 becomes integer 3 etc whats the best way to proceed i have been exploring javalangnumber without finding a direct conversion method integerparseintb yields an integer equal to the stringeg 1001 becomes 1001 instead of 9and does not seem to include a parameter for an output base tobinarystring does the conversion the wrong direction i suspect i will need to do a multistep conversion but cannot seem to find the right combination of methods or subclasses i am also not sure the extent to which leading zeros or lack thereof will be an issue anyone have any good directions to point me,['java'] +277432,jquery dialog open and automatically close after 3 seconds i am trying to open a jquery dialog with no buttons to thisplay with some animations and then automatically stay there for like 3 seconds then close here is a jsfiddle of what i think should work but as you can see it just opens and closes without waitng the 3 secondsjsfiddle anyone know how to straighten this outthanks,['jquery'] +277439,issue replacing default scroll bar using jquery plugin i would like to replace the default scrollbar of my site this page in particular using a jquery plugin called tinyscrollbar however for some reason i am getting the following error on the pagejquerytinyscrollbarminjs1uncaught typeerror cannot read property offsetheight of undefinedyou can see this error by inspecting element in chromemight anyone have any ideas why this error is occurring the code i am using to initialize the plugin can be seen belowfullheighttemplatecontainertinyscrollbar,['jquery'] +277440,spring framework in simple terms i have done some research on this but still only have a vague understanding of it at best can anyone who is knowledgable on this give me a simple or as simple as possible description that someone with a basic understanding of programming could understand thanks for any help,['java'] +277475,does windows have a limitation when a process started by a scheduled task under one set of creds runs another program under a different set of creds so i have a simple example where i have app a which has some hard coded creds to user x a local admin and then it launches app b with those credentials using a hardcoded absolute path both a and b and dotnet console applications however they do not interact with the console just just write out info to a filewhen i run a interactively under my creds by double clicking or through cmdexe or an interactive powershell session it runs fine successfully calling bwhen i run it through a scheduled tasks with a being under by creds and calling b with user x the error code of the procestartmystartinfo is 1073741502 or 0xc0142 in hex which means the application failed to initialize properlyhowever if i run the scheduled task calling a with user x credentials it worksi made this small test mostly because i see similar behaviour when trying to do startjob credential in powershell from either a scheduled task or remoting or calling startprocess in powershell or systemdiagnosticprocestart from within powershell in the same scenarios at first i thought it was a bug in powershell but it seems to be deeper either windows or specifically dotnet and i want to know if this is knowndocumented and if there are any workarounds,['c#'] +277483,how to use kaudiosessionproperty overridecategorymixwithothers i would like to make my virtual instrument app able to being used via a midi keyboard when the app is in the background this works fine by setting uibackgroundmodes to audio and setting the audiosessionss category to avaudiosessioncategoryplayback furthermore to allow mixing with the music player app i set the property kaudiosessionproperty overridecategorymixwithothersto save battery energy it is recommended to let the user switch off the background operation if it is not needed so there is a switch in my app to toggle between the category avaudiosessioncategoryambient and the category avaudiosessioncategoryplayback with kaudiosessionproperty overridecategorymixwithothers the code is like this error handling omittednsstring category supportsbackgroundoperation avaudiosessioncategoryplayback avaudiosessioncategoryambientsession setcategorycategory errornilif category avaudiosessioncategoryplayback uint32 allowmixing true audiosessionsetpropertykaudiosessionproperty overridecategorymixwithothers sizeofallowmixing allowmixingnow the problem suppose the music application is playing in the background the user is playing the virtual instrument in the foreground via a midi keyboard to accompany the music player and decides to start yet another app say a slide show to enjoy why playing the instrument so heshe goes to the settings view of my app and activates background operation then the above code is executed boom the music application gets silent as i understand it the kaudiosessionproperty overridecategorymixwithothers property can only be set after setting the category but when i set the category to avaudiosessioncategoryplayback the music player is silenced by the system before i have a chance to set kaudiosessionproperty overridecategorymixwithothersis this was happens can there anything be done i tried to deactivateactivate the session beforeafter changing the category but that lead to other troublemarkus,['ios'] +277512,how to pass member function as argument in python i want to pass something similar to a member function pointer i tried the followingclass dummy def func1selfname print hello s name def func2selfname print hi s namedef greetfname d getsomedummy dfnamegreetdummyfunc1balaexpected output is hello bala,['python'] +277553,copy an image and preserve its exifiptc data with php imagecreatefromjpeg i having some problems with an image that has exifiptc data stored in it when i use imagecreatefromjpeg to rotatecrop or etc the newly stored file does not preserve the exifiptc data my current code looks like thisphp before executing exifiptc data is there checkedimage pathtomyimagejpgsource imagecreatefromjpegimagerotate imagerotatesource900imagejpegrotateimage after executing exifiptc data does not exist anymore am i doing something wrong,['php'] +277571,whats the difference between rubys dup and clone methods the ruby docs for dup sayin general clone and dup may have different semantics in descendent classes while clone is used to duplicate an object including its internal state dup typically uses the class of the descendent object to create the new instancebut when i do some test i found they are actually the sameclass test attr accessor xendx testnewxx 7y xdupz xcloneyx 7zx 7so what are the differences between the two methods,['ruby'] +277573,console is undefined error in ie9 i have a graphics page which shows svg graphics i am using raphael graphics framework the page thisplays properly in firefox also if the f12 developer tools is set on in ie9 it works fine the map show partial data its a node link diagram and it shows only one child node out of 12 nodes in ie9 if the f12 developer mode is set off and application is started with browser cache cleared simulating a general userupdate i kept the debugger on and shows me the error console is undefined so i think its not a graphics rendering issue and also i am not using the console explicitly maybe the mindmap js is using it internally but how to again get rid of this issueupdatei found the issue and commented out the consolelog entries from the js filesthanks,['javascript'] +277599,how can i thistinguish between an unset float and one with a value of 0 i have a method that needs to do a different thing when given an unset float than a float with the value of 0 basically i need to check whether or not a variable has been counting it as set if it has a value of 0so what placeholder should i use as an unset value nil null no etc and how can test to see if a variable is unset without returning true for a value of 0,['objective-c'] +277660,fully transparent actionbarsherlock by using theme i am using actionbarsherlock 402i need a fully transparent action bar without the neon color bottom divider hence i have the following stylestyle nameapptheme parentstylethemesherlock item namewindowactionbaroverlaytrueitem item nameicondrawableic homeitem item nametitletextstylestyleactionbarcompattitleitem item nameandroidwindowfullscreentrueitemstyleby using above code i will still have the following effectin order to thisable the background i put the following code in sherlockfragmentactivityoncreate then the problem gonegetsupportactionbarsetbackgrounddrawablenullhowever i would like to see the solution being implemented in stylesxml instead of java code as i have many other devices with different screen configuration i modified the stylesxml to the following without using the previously mentioned fix in the java codestyle nameapptheme parentstylethemesherlock item namewindowactionbaroverlaytrueitem item nameicondrawableic homeitem item nametitletextstylestyleactionbarcompattitleitem item nameandroidwindowfullscreentrueitem item nameandroidbackgrounddrawabletransparentitem item namebackgrounddrawabletransparentitemstylehowever the neon divider still visible it seems that my fix using androidbackground and background does not work am i missing something,['android'] +277689,this selector imgthis possible i am trying to select a img inside a this selector i know i can find it by using findimg but is this possibleimgthis whats the most optimal way to do thisoriginally codea classpicture hreftesthtml img srcpicturejpg altawesomea,['jquery'] +277747,sorting algorithm with qtc sort a qlist of struct i wonder whether their is some algorithm in stl or in qt that sorts an array of double and return the indices of sorted items in the original list eg l 1 2 5 3l sort 1 2 3 5indices 1 2 4 3so that i can afterwards calculate anotherlistindices the same order prevails in both lists with respect to the original list l in the end i thought of creating a qlist each mystruct containing two members one of same type ltype as elements in l the other of same type anothertype as elements in anotherlist and then ordering with respect to members of type ltype however i have this idea i do not know properly how to proceed in qt thanks and regards,['c++'] +277760,tracking the position of the line of a streamreader hi guys what i need to do is track the position of the line that i am reading from the stream reader when i say readerreadline i need to know the position of that line in the file and i also want to be able to then read the file from the position i have previously trackedis this possible if so please assisthelp is much appreciatedthanks in advance,['c#'] +277809,ioc in class library where to bootstrap i am using a class library that can be reused by other components in this class library i am using unity for dependency injection for this class library i create a test project the caller also gets a test project one thing i am uncertain about is the location of the bindings should i incorporate this in the class library or should i do this from the calling application,['c#'] +277932,why does djangolint tell me the auto now add is deprecated hi fellow djangonautsi checked my project with djangolint and it yieldsw216mymodel timestamp uses superceded auto now or auto now addthe commit messageauto nowauto now add not technically deprecated but they still suckwhy do they say auto nowauto now add suck i had no problem implementing the createdlastupdated pattern with these two field parametersis there a better approach for this pattern custom field classes and why if this approach is better it has not been integrated into django,['python'] +277990,python pandas how to turn a dataframe with factors into a design matrix for linear regression if memory servies me in r there is a data type called factor which when used within a dataframe can be automatically unpacked into the necessary columns of a regression design matrix for example a factor containing truefalsemaybe values would be transformed into1 0 00 1 0or0 0 1for the purpose of using lower level regression code is there a way to achieve something similar using the pandas library i see that there is some regression support within pandas but since i have my own customised regression routines i am really interested in the construction of the design matrix a 2d numpy array or matrix from heterogeneous data with support for mapping back and fort between columns of the numpy object and the pandas dataframe from which it is derivedupdate here is an example of a data matrix with heterogeneous data of the sort i am thinking of the example comes from the pandas manual df2 dataframea one one two three two one sixb x y y x y x xc nprandomrandn7 df2 a b c0 one x 03431 one y 00556512 two y 02491943 three x 14864624 two y 04069305 one x 02239736 six x 0189001 the a column should be converted into 4 floating point columns in spite of the meaning there are only four unique atoms the b column can be converted to a single floating point column and the c column should be an unmodified final column in the design matrix thankssetjmp,['python'] +277993,handle events in dart i am new to dart i read the language overview and checked example code in dart editor so far i could not find how to handle events in dart for eg onclickcall dart methodhow can we handle events in dart,['javascript'] +278014,confusing error about missing left parenthesis in sql statement sqlplus says i have missing left parenthesis with this statement in my sql scriptcreate table people id int not null primary key name varchar2i had uploaded my script with sftp could that have played around with the script,['sql'] +278021,given a unix timestamp how to get beginning and end of that day i have a unix timestamp like thistimestamp1330581600how do i get the beginning of the day and the end of the day for that timestampegbeginofday start of timestamps dayendofday end of timestamps dayi tried thisendofday timestamp 60 60 23but i do not think it will work because the timestamp itself is not the exact beginning of the day,['php'] +278030,execute lambda expression immediately after its definition is there a way to execute a lambda expression immediately after its definitionin other words invalid c code consolewritelinehello world invoke,['c#'] +278062,android class not found exception androidsupportv4appfragmentpager in my code iimport androidsupportv4viewviewpagerbut i get a classnotfoundexception androidsupportv4viewviewpager when i set content view to this xml file androidsupportv4appfragmentpager androidlayout height0px androidlayout widthmatch parent androidlayout weight1 androidididpager androidsupportv4appfragmentpager,['android'] +278075,is there a compiler as service for c in short i am looking for something like roslyn but for cin detaili am dealing with a c project where i have to work with c files i have a bunch of h about 250 files and cpp and i would like to map the classes and functions and what not that are defined in these filesit is for a modeling task i do not wish to use the actual c libraryi did not write the c code so i cannot be sure if there are nested classes anywhere so this is not a simple regex taskthe project is in c and the library i would like to use is in c i cannot change that,"['c#', 'c++']" +278076,count number of times value appears in particular column in mysql this has probably been asked before but i am unable to make my way through the myriad of search resultsgiven a nonnormalized mysql table what is the most optimized query to count the number of times each thistinct value of column x was usedeg given a table containingmikemarymikereturn results likemike 2mary 1from the mysql documentation it would seem that count is an aggregate function that can be used with group by but it is not doing what i want it is returning the total number of rows in the group by not the number of appearances for each row ie this does not work select countemail as c from orders group by email,['mysql'] +278097,ios json nsstring parse i have a json string as an nsstring object in ios i want to parse this and pull out the given parameters in the json string is there a efficient way to parse this or is the only way to search for substrings etc,['ios'] +278104,create hello world websocket example edit 3 able to send data now deleted old examplesthis is my new version of the program thanks to your answers and the code of maksims mihejevs serverusing systemusing systemnetsocketsusing systemnetusing systemsecuritycryptographyusing systemthreadingnamespace consoleapplication1 class program static socket serversocket new socketaddressfamilyinternetwork sockettypestream protocoltypeip static private string guid 258eafa5e91447da95cac5ab0dc85b11 static void mainstring args serversocketbindnew ipendpointipaddressany 8080 serversocketlisten128 serversocketbeginacceptnull 0 onaccept null consoleread private static void onacceptiasyncresult result byte buffer new byte1024 try socket client null string headerresponse if serversocket null serversocketisbound client serversocketendacceptresult var i clientreceivebuffer headerresponse systemtextencodingutf8getstringbuffersubstring0i write received data to the console consolewritelineheaderresponse if client null handshaking and managing clientsocket var key headerresponsereplaceey split1 dghlihnhbxbszsbub25jzq rn replacer splitn0 dghlihnhbxbszsbub25jzq trim key should now equal dghlihnhbxbszsbub25jzq var test1 acceptkeyref key var newline rn var response http11 101 switching protocols newline upgrade websocket newline connection upgrade newline secwebsocketaccept test1 newline newline secwebsocketprotocol chat superchat newline secwebsocketversion 13 newline which one should i use none of them fires the onopen method clientsendsystemtextencodingutf8getbytesresponse var i clientreceivebuffer wait for client to send a message once the message is received decode it in different formats consolewritelineconverttobase64stringbuffersubstring0 i consolewritelinennpress enter to send data to client consoleread var suba subarraybytebuffer 0 i clientsendsuba threadsleep10wait for message to be send catch socketexception exception throw exception finally if serversocket null serversocketisbound serversocketbeginacceptnull 0 onaccept null public static t subarraytt data int index int length t result new tlength arraycopydata index result 0 length return result private static string acceptkeyref string key string longkey key guid byte hashbytes computehashlongkey return converttobase64stringhashbytes static sha1 sha1 sha1cryptoserviceprovidercreate private static byte computehashstring str return sha1computehashsystemtextencodingasciigetbytesstr javascriptdoctype html public w3cdtd xhtml 10 transitionalen html xmlnshead script typetextjavascript function connect var ws new websocketwslocalhost8080service wsonopen function alertabout to send data wssendhello world i want to send this message to the server alertmessage sent wsonmessage function evt alertabout to receive data var received msg evtdata alertmessage received received msg wsonclose function websocket is closed alertconnection is closed scriptheadbody stylefontsizexxlarge div a href onclickconnectclick here to startadivbodyhtmlwhen i run that code i am able to send and receive data from both the client and the server the only problem is that the messages are encrypted when they arive to the server here are the steps of how the program runsnote how the message from the client is encrypted,"['c#', 'javascript']" +278116,a uilabel with rounded corners drop shadow and background pattern i have been trying every single method i found but i was not able to make it i simply want to make a label with rounded corners a drop shadow with a background pattern the shadow works only if i do not want rounded corners i cannot get them both togetherhere is my code with the shadow labeltext msglabeltextalignment uitextalignmentcenterlabelframe cgrectmake201028040labelbackgroundcolor uicolor alloc initwithpatternimageuiimage imagenamedmsg box bgpnglabellayer setcornerradius10labellayer setmaskstoboundsno shadow labellayershadowcolor uicolor blackcolorcgcolorlabellayershadowopacity 06labellayershadowoffset cgsizemake00labellayershadowradius 3this gives me shadow without rounded corners but if i uselabellayer setmaskstoboundsyesthis will give me rounded corners with no shadow i have taken the advise to use a shadow path so the code with the shadow path looks like thislabeltext msglabeltextalignment uitextalignmentcenterlabelframe cgrectmake201028040labelbackgroundcolor uicolor alloc initwithpatternimageuiimage imagenamedmsg box bgpnglabellayer setcornerradius10labellayer setmaskstoboundsyes shadow labellayershadowcolor uicolor blackcolorcgcolorlabellayershadowopacity 06labellayershadowoffset cgsizemake00labellayershadowradius 3labellayershadowpath uibezierpath bezierpathwithroundedrectlabelframe cornerradius10cgpathlabellayershouldrasterize yesthis code does give me rounded corners but no shadow any suggestionsthanks,['ios'] +278139,proper way to do const stdstring in a header file i am writing a cocos2dx game where the player enemies and other characters store their attributes in a ccmutabledictionary which is somewhat of a decorator class for stdmapstdstring ccobject a value in the dictionary can be accessed via the ccmutabledictionaryobjectforkeyconst stdstring key methodnow in a header file included by many of my cpp files i have got a few const char const strings for accessing values in the dictionaries like this in constantshconst char const kattributex xconst char const kattributey y in a cpp fileccobject x somedictionaryobjectforkeykattributexso correct me if i am wrong but stdstrings copy constructor is being called and a temporary stdstring is on the stack every time i call one of the above objectforkey methods using a const char const rightif so i feel that it would be more efficient at runtime if those constant attribute keys were already stdstring objects but how do i do that the right waydefining them in the constantsh file like the following compiles fine but i have a feeling that something just is not right in constantshconst stdstring kattributex xconst stdstring kattributey ymy apologies if this question has already been asked i could not seem to find the exact answer i was looking for here on stackoverflow,['c++'] +278162,clgeocoder returning locations in other countries i have the following codeclgeocoder geo clgeocoder alloc initclregion region clregion alloc initcircularregionwithcenter cllocationcoordinate2dmake3733233141 12203121860 radius100 identifiersan francisco geo geocodeaddrestringstarbucks inregionregion completionhandlernsarray placemarks nserror error nslog placemarksthis returns a starbucks location in the philippines even though the center is in the middle of san francisconsarray 3 0x07cd9d10 nsarraym 0x7cd9d10starbucks metro manila quezon city republic of the philippines 146361775212103067530 10m region identifier 146358490012102951050 radius 16635 146358490012102951050 radius 16635many ideas,"['objective-c', 'ios']" +278163,pandas dataframe find row where values for column is maximal how can i find the row for which the value of a specific column is maximaldfmax will give me the maximal value for each column i do not know how to get the corresponding row,['python'] +278204,antihack solution for a secret key in android app i need to store a private string key inside of the app its value will never change and is set manually in code i cannot obviously just store it as a string as reverseengineering method would reveal it even with obfuscation applied how do you suggest i protect this private keyi though of saving it into a database but a database can be pulled out of the phone as wellps this key is a special parameter so an important method and it is crucial it stays unknown to anyone it is not a decrypting key this string will be used as a parameter to encryption method md5 or similar and then a result will be sent to our internet service editsorry for making it so complicated i thought i could get an answer with as few info as possible this app will allow users to send some text to an internet service which then posts that text to a web site we need to make sure that the text is sent via android phone as any web robot script can mimic android phone and post a spam as captchalike methods are not welcome on mobile phones there will be a secret key which will be put through md5 with some other things to generate a hash code this hash will be sent to an internet service the internet service will use the same key to get a md5 result and then compare it to see if the sender is a mobile phone or some robot this is really the max i am allowed to say i hope it is enough,"['java', 'android']" +278205,when do i use cfrelease i am studying ios programmingi wrote code that associated an addressthere is so many methods likei am dividing a groupheres group1abaddressbookcreateabrecordcopycompositenameargumentabrecordcopyvalueargument1 argument2abrecordcopyvalueargument1 argument2abmultivaluecopylabelatindexargument1 argument2abmultivaluecopyvalueatindexargument1 argument2and another one is right here group2cfarraygetcountargumentcfarraygetvalueatindexargument1 argument2abmultivaluegetcountargumenti know there is so many other methodsbut i wonder when i use cfrelease methodi think group2s all methods do not do cfreleasebecause that contain the word get not allocatedand i think group1s all method have to use cfreleasebecause there is a string copyi have a bookbut there is used cfrelease twiceone is release abaddressbookcreateanother one is abaddressbookcopypeoplewithnameall of other things do not use cfreleaseso i wonder when i use cfreleaseplease tell me when i use cfrelease,"['iphone', 'objective-c', 'ios']" +278218,mac os x wants to use system keychain when compiling the project i am asked to type in the system admin user name and password when i compile my xcode project the whole message is mac os x wants to make changestype an administrators name and password to allow this mac osx wants to use system keychaindoes anyone have a solution for this,['ios'] +278219,can i specify the output path for the msbuild tag is it possible to specify a different folder for the output of the following filecontent includeteststl copytooutputdirectorypreservenewestcopytooutputdirectorycontent,['.net'] +278221,define function within another function in javascript function fooa if some condition perform task 1 perform task 3 else perform task 2 perform task 3 i have a function whose structure is similar to the above i want to abstract task 3 into a function bar but i wish to limit the access of this function to only within the scope of fooato achieve what i want is it right to change to the followingfunction fooa function bar perform task 3 if some condition perform task 1 bar else perform task 2 bar if the above is correct does bar get redefined every time fooa gets called worrying about waste of cpu resource here,['javascript'] +278226,how to assign nsarray data to nsmutablearray in iphone in my application i have an nsarray which contains some data i want to take that data and put it into an nsmutablearray called subarraydata i am able to insert the data from my first array into the mutable array but when the application runs i am getting warningincompatible pointer types assigning to nsmutablearray from nsarray please help outfollowing is my codeh fileimport uikituikithinterface addnew uiviewcontroller nsmutablearray subarraydatapropertynonatomic retainnsmutablearray subarraydatam fileimport addnewhimport dashboardpagehimport submityourlistinghimplementation addnewsynthesize subarraydatavoidaccommodationandtravel subarraydata nsarray alloc initwitharraynsarray arraywithobjectsselect oneaccommodation and travel hospitalityapartments and villasbed and breakfastcaravan parks and campsiteshospitality hotels and motelssnow and ski lodgestourist attractions and tourism informationtours and holidaystravel agents and servicesnil,"['iphone', 'objective-c', 'ios']" +278231,doctrine query thistinct related entity i am probably overlooking something very simple and just been staring at it too much but i cannot get this dql query to work i get an exception statingcannot select entity through identification variables without choosing at least one root entity aliasheres my query user has a manytoone relation to group note that this is a unidirectional relation that may make no sense to you but it makes sense in our domain logicselect thistinct gfrom entityuser uleft join ugroup gwhere uactive activecan you tell me what i am missing here,['php'] +278234,code performance sql server query vs cnet web application i am writing a complex logic to calculate sales and customer bonuses i have million of records to calculate bonuses i want expert opinions so that mathematical operation do not take much time to thisplay result on web pageso where i need to write calculation part in sql server queries using stored procedure and functions or aspnet cnet business logic layer which one is the best practice processing on database server or processing on application serverregardsmohsin jk,"['c#', 'asp.net']" +278266,custom tab in file properties dialog i want to show some additional info in file properties dialog in windows for some specified types for example add new tab summary for txt files and show there number of words number of lines etci can use c and c but file summary is collected by net library so i would prefer to delegate this task to net to the extent possible,"['c++', '.net']" +278315,googlemock mock a method that returns a complex datatyp i want to mock a method that returns a complex datatypclass aclasspublic virtual const qmapqstring qstring amethod constclass mockaclass public aclasspublic mock const method0amethod const qmapqstring qstringthis code does not compile macro mock const method0 passed 3 arguments but takes just 2i think that the googlemock macro does not understand qmap and interpret the comma as parameter separatoris there a way to tell googlemock that qmap is the return value,['c++'] +278318,how to make fabric continue running the next command after getting the exit status 1 i am going to install check mk plugin by writing a simple fabfile like thisfrom fabricapi import env run roles execute parallelenvroledefs monitoring 1921683118 mkagent 1921683230 1921683231 1921683232rolesmonitoringdef mk run f check mk12p7targz wget mk12p7targz run d check mk12p7 tar zxvf check mk12p7targz runcd check mk12p7 sudo setupshparallel rolesmkagentdef mk agent run rpm qa grep c xinetd eq 0 sudo yum y install xinetdx86 64 runsudo rpm ivh mkagent120b21noarchrpm def check mk executemk executemk agentbut as you can guess if the xinetd package is already installed fabric will be stopped with below errorsfatal error run received nonzero return code 1 while executingrequested rpm qa grep c xinetd eq 0 sudo yum y install xinetdx86 64executed binbash l c rpm qa grep c xinetd eq 0 sudo yum y install xinetdx86 64abortingis there any solution in this situation,['python'] +278341,why does iterating over getconsumingenumerable not fully empty the underlying blocking collection i have a quantifiable repeatable problem using the task parallel library blockingcollectiont concurrentqueuet getconsumingenumerable while trying to create a simple pipelinein a nutshell adding entries to a default blockingcollectiont which under the hood is relying on a concurrentqueuet from one thread does not guarantee that they will be popped off the blockingcollectiont from another thread calling the getconsumingenumerable methodi have created a very simple winforms application to reproducesimulate this which just prints integers to the screentimer1 is responsible for queueing up the work items it uses a concurrent dictionary called tracker so that it knows what it has already added to the blocking collectiontimer2 is just logging the count state of both the blockingcollection of the trackerthe start button kicks off a paralellforeach which simply iterates over the blocking collections getconsumingenumerable and starts printing them to the second list boxthe stop button stops timer1 preventing more entries from being added to the blocking collectionpublic partial class form1 form private int counter 0 private blockingcollectionint entries private concurrentdictionaryint int tracker private cancellationtokensource tokensource private taskfactory factory public form1 entries new blockingcollectionint tracker new concurrentdictionaryint int tokensource new cancellationtokensource factory new taskfactory initializecomponent private void timer1 tickobject sender eventargs e adding timer listbox 1 forvar i 0 i 3 icounter if trackertryaddcounter counter entriesaddcounter listbox1itemsaddstringformatadding 0 counter private void timer2 tick 1object sender eventargs e logging timer list box 3 listbox3itemsaddstringformattracker count 0 entries count 1 trackercount entriescount private void button1 clickobject sender eventargs e start button logs to list box 2 var options new paralleloptions cancellationtoken tokensourcetoken maxdegreeofparallelism 1 factorystartnew parallelforeach entriesgetconsumingenumerable options dowork timer1enabled timer2enabled true timer1start timer2start private void doworkint entry threadsleep10 sleep for 1 second to simulate work being done invokemethodinvoker listbox2itemsaddstringformatprocessed 0 entry int oldentry trackertryremoveentry out oldentry private void button2 clickobject sender eventargs e stop button timer1stop timer1enabled false heres the sequence of eventspress starttimer1 ticks listbox1 is immediately updated with 3 messages adding 0 1 2listbox2 is subsequent updated with 3 messages 1 second apartprocessing 0processing 1processing 2timer1 ticks listbox1 is immediately updated with 3 messages adding 3 4 5listbox2 is sbsequent updated with 2 messages 1 second apartprocessing 3processing 4processing 5 is not printed would appear to have gone missingpress stop to prevent more messages being added by timer 1wait processing 5 still does not appearyou can see that the concurrent dictionary is still tracking that 1 item has not yet been processed subsequently removed from trackerif i press start again then timer1 begins adding more 3 more entries and the parallel loop comes back to life printing 5 6 7 8 i am at a complete loss as to why this occurs calling start again obviously calls a newtask which calls a paralell foreach and reexecutes getconsumingenumerable which magically finds the missing entry iwhy is the blockingcollectiongetconsumingenumerable not guaranteeing to iterate over every item that is added to the collectionwhy does the addition of more entries subsequently cause it to get unstuck and continue with it is processing,"['c#', '.net']" +278353,get time zone using latitude and longitude i having current latitude and longitude and i want the time zone from that latitude and longitude i want that this latitude and longitude from which time zonei want output likelatitude225726460longitude883638950this is latitude longitude of kolkataindia and when i have this lat long i want asiakolkataas outputplease suggest any api or any idea which can solve out my problem,"['php', 'iphone']" +278358,serialport class occasionally hangs on thispose i have written a net 40 console application which periodically talks to a gsm modem to get a list of the receieved sms messages it is a usb modem but the code connects to it via a serial port driver and sends at commands incidentally it is a sierra wireless modem but i cannot change it and i have the latest driver what happens is that after some period of time maybe hours maybe days it just stops working here is a log snippet20120417 230731 debug modem check 108 executing at command atcpmsme20120417 230731 debug modem check 108 finished executing atcpmsme20120417 230731 debug modem check 108 detaching event handlers for com1320120417 230731 debug modem check 108 thisposing the serialport for com13that is the end of the log nothing more even though i would expect to see at least one more statement here is the relevant codeinternal t execute var modemport new serialport t ret try modemporterrorreceived modemporterrorreceived modemportportname descriptorportname modemporthandshake handshakenone modemportdatabits 8 modemportstopbits stopbitsone modemportparity paritynone modemportreadtimeout readtimeout modemportwritetimeout writetimeout modemportnewline rn modemportbaudrate descriptorbaud if modemportisopen modemportopen ret commandexecutemodemport logger loggerdebugdetaching event handlers for 0 descriptorportname modemporterrorreceived modemporterrorreceived loggerdebugthisposing the serialport for 0 descriptorportname catch ioexception ex loggererrorexmessage throw new commandexception stringformatcultureinfocurrentculture modemwrapperstringscommand error exmessage ex catch unauthorizedaccessexception ex loggererrorexmessage throw new commandexception stringformatcultureinfocurrentculture modemwrapperstringscommand error exmessage ex finally modemportthispose loggerdebugmodem on port 0 thisposed descriptorportname return retas you can see it hangs on the thispose method of the serialport classi did some googling and i came to this issue serial port close hangs the application from this thread serial port hangs whilst closing the consensious seems to be to close the port in a different thread but is that just for a forms application in my case i have a simple console application so i do not think it applies it is just running in a loop in the main thread i am not even sure it is actually this issue my feeling is that it is more likely that there is an issue with the serial port driver from the modem but i do not know and perhaps i am being unfair to the modem as far as i see it i have three choicesclose the port in a different threadput in a delay before closing the portleave the port open foreveri do not really like any of those workarounds but i am thinking of leaving the port open and just seeing what happens i have this feeling that it will leak memory or worse expose some other issue with the modem but maybe i am just pessimistic and if that is the case i could probably get away with closing it every 24 hours say and reopening it again so my question isis there an alternative problem with this code that could be causing this bevahior or is there an alternative workaround to what i have outlined above,"['c#', '.net']" +278382,how to thisable sqlalchemy caching i meet a cache problem when i use sqlalchemy i use sqlalchemy insert a data into mysql database i have the other application process this data then update this data directly but my sqlalchemy always got old data rather than updated data i think sqlalchemy cached my request so how to thisable it,"['python', 'mysql']" +278391,not a singlegroup group function i have some tables which basically look as followstbl useruser id numberuser name varchartbl stuffstuff id numberstuff user id numberi want to query for all user information including the number of stuff they have i was trying something like thisselect user id user name countstuff id from tbl user left outer join tbl stuff on stuff user id user id where user id 5but i get an error which says not a singlegroup group functionis there some other way i should be doing this,['sql'] +278409,is there a way to remove quotes in a c macro suppose i want to unstringify the macro argument which should transform text to textdefine un stringifyx some macro magic here now calling this macro will remove from its argumentun stringifytext results in textthis would be the opposite of macro stringificationdefine stringifyx xis this possible or am i playing with macro evilness,"['c++', 'c']" +278436,how can i order a list i have this list iliststring listaservizi new liststring how can i order it due to the strings inside it alphabetic and ascending,['c#'] +278465,python asks for older paths on mac after deleting duplicate python installation i am having the below error after a clean installation of python via brew install python the link belongs to a previous python installation which i deleted manually virtualenv envpython posix spawn systemlibraryframeworkspythonframeworkversions27resourcespythonappcontentsmacospython no such file or directoryi am using macos 1073 and i installed virtualenv via pip sudo usrlocalsharepythonpip install virtualenv downloadingunpacking virtualenv downloading virtualenv1712targz 21mb 21mb downloaded running setuppy egg info for package virtualenv warning no previouslyincluded files matching found under directory docs templates installing collected packages virtualenv running setuppy install for virtualenv warning no previouslyincluded files matching found under directory docs templates installing virtualenv script to usrlocalsharepython successfully installed virtualenv cleaning up virtualenv env python posix spawn systemlibraryframeworkspythonframeworkversions27resourcespythonappcontentsmacospython no such file or directoryhow can i fix thisedit i reinstalled macosx and now returned back to my previous status that made me delete the preinstalled python which python libraryframeworkspythonframeworkversions27binpython which pip usrlocalbinpip sudo pip install virtualenvdownloadingunpacking virtualenv downloading virtualenv1712targz 21mb 21mb downloadedrunning setuppy egg info for package virtualenvwarning no previouslyincluded files matching found under directory docs templatesinstalling collected packages virtualenvrunning setuppy install for virtualenvwarning no previouslyincluded files matching found under directory docs templatesinstalling virtualenv script to usrlocalbinsuccessfully installed virtualenvcleaning up python virtualenvpy envlibraryframeworkspythonframeworkversions27resourcespythonappcontentsaamacospython cannot open file virtualenvpy errno 2 no such file or directorythe virtualenvpy is located at librarypython27sitepackagesvirtualenvpy and systemlibraryframeworkspythonframeworkversions27extraslibpythonpy2apprecipesvirtualenvpy but somehow python misses all why there is so much mess how should i proceed to fix this,['python'] +278490,thiscard millisecond part from timestamp how can i thiscardround the millisecond part better if the second part is also removed from a timestamp wo timezone,['sql'] +278503,javascript showmodaldialog not returning value in chrome i made a small calendar popup in javascript very simple using the calendar control from aspnet i call the popup window with showmodaldialog in the modal window changing the current month of the calendar causes problems because of the postback and i found in several places that the solution is to putbase target selfin the head part of the aspx file everything works great except for one thing and only in google chrome to get back the selected date i set the returnvalue of the popup to the date selected in the calendar in ie and firefox it always works in chrome however it works only if i do not change the current month in the calendar as soon as i change it the return value is not passed back to the caller of showmodaldialog it is as if the modal window is not the original one anymore the return value is undefinedhas anyone experienced that behavior and have a suggestion to make it work i tried using dialogarguments to keep trace of the caller window but it gets passed only to the first modal window it is lost after changing the current month the code in the calling procedurevar d windowshowmodaldialogthe code in the modal windowwindowreturnvalue selecteddate selfcloseas i said to teemu selecteddate and windowreturnvalue are both always correct however in the case of google chrome after a month change in the calendar returnvalue is not passed back by showmodaldialog and d is undefined,['javascript'] +278505,mono on raspberry pi i have seen a lot of talk about running mononet code on the raspberry pi has there been any suceses in actually running any mono code on the raspberri pion their site they list several linux thistributions that work on the device and some of these thistributions include mono however none detail whether mono works on itis there a working implementation,['.net'] +278506,how to check if an option is selected myselectbox optioneachfunction if thisischecked alertthis option is selected else alertthis is notapparently the ischecked does not work so my question is what is the proper way to do thisthanks,['jquery'] +278511,real time morse code converter in javascript after seeing googles april fools joke of the morse code gmail i thought i would try to create a realtime morse code converter in javascripti am using regex and replace to change the morse code into character for examplereplace g areplace g rthe issue i am having is that when i am typing for r it give me an a because it sees firsthow can i make it replace only exact matchesupdated and working thanks to every one that helped me my original code rewritten by shawn chin rewritten by matthias tylkowskiif anyone has other ways of writting this program please post a jsfiddleid love to see how else this can be done,['javascript'] +278557,js is there a way to check if an event exists i am trying to detect if a certain webkit event webkitanimationend is supported by the browser to do so i like to check if the event exists but i cannot seem to figure out how does anyone have a clue,['javascript'] +278570,no identities were available administrator request i had problems while archiving my app i think there are invalid profiles because of iphone update to 51 and xcode update to 422i have taken now more than 4 hours to get rid of certification issues while using this thread step by step 3 times which costs a lot of time a valid signing identity matching this profile could not be found in your keychaini still have the following faultno identities were availablean administrator must request identities before they can be downloadedthe download identities button went back to this window after processing some secondsdo you know how to get out of this wood of certification documentations and solve that fault,"['ios', 'iphone']" +278572,check if string contains any substring in an array in ruby i am using the tmail library and for each attachment in an email when i do attachmentcontent type sometimes i get not just the content type but also the name examplesimagejpeg nameexample3jpgimagejpeg nameexamplejpgimagejpeg namephotojpgimagepngi have an array of valid content types like thisvalid content types imagejpegi would like to be able to check if the content type is included in any of the valid content types array elementswhat would be the best way of doing so in ruby,['ruby'] +278581,thisplay numbers upto to two decimals places without trailing zeros in my code i will be accepting multiple values for example87456878and i need to have them appear as 874878ie thisplay up to two decimal placei understand that tofixed2 will help me with the first value but on the 2nd and 3rd value there will be trailing zeroes that i do not wantany thoughts on how to produce my desired results,['javascript'] +278584,easy install is not recognized as an in internal or external command operable program or batch file i have just downloaded and installed the latest version of python on my windows 7 machinepython 273now i want to install a twitter library i found onlinehowever when i try to run easy install tweepy i get this error messageeasy install is not recognized as an in internal or external command operable program or batch filepython has already been placed into my path as i can invoke the python program into the command linehere is a screenshot of my folder where python is installedand inside the tools folderand inside the scripts folder,['python'] +278611,coding standards for documenting javascript function possible duplicatewhat options are available for documenting your javascript code in python to document a function there is docstring example belowdef complexreal00 imag00 form a complex number keyword arguments real the real part default 00 imag the imaginary part default 00 if imag 00 and real 00 return complex zero wondering whats the coding standards i should follow for documenting function in javascript,['javascript'] +278618,why should i make the underlying type of an enum int32 instead of byte given the following enumpublic enum operations perhourtype byte holes 1 pieces 2 sheets 3 strips 4 studs 5when i run the microsoft code analysis tool it tells meca1028 microsoftdesign if possible make the underlying type of enumsoperations perhourtype systemint32 instead of byte it will never have more than a couple possible values so i declared it as a byte why would they recommend using int32 more values for future scalability or is there a performance improvement,"['c#', '.net']" +278653,transfering json between browsers with webrtc i was excited by the prospect of webrtc when i heard about it initially it sounded like websockets but without a server unfortunately all of the tutorials i have been able to find have stressed the video and and audio aspects of webrtc i cannot find anything about sending textdatajson between browsers could you help me write a simple hello world of sorts just sending some data from one browser to another with webbrtc,['javascript'] +278655,why does qtestx take so long when i runqtestxin chrome or ie it takes 10 seconds to complete firefox is able to evaluate it almost instantlywhy does it take so long and whyhow is firefox able to do it so quicklyof course i would never run this particular regex but i am hitting a similar issue with the url regex at regex for matching urls and it seems to boil down to this ie there are certain urls which will cause the browser to lock upfor examplevar re bhttpswd03az09az24sairetesta,['javascript'] +278658,netbeansspecific c error undefined reference to x solution posted i wrangled with this problem for a good 5 or 6 hours pulling my hair out until i finally found a solution i wanted to post this not sure if there is a specific place to post solutions to unasked questions as a solution for others who may run into the same difficultyi am coding a c project in netbeans 711 running on linux mint lisa and kept on getting an undefined reference to x error when trying to use a static variable coming from a background in c and thus not very familiar with header files and the like i searched for hours expecting to find a problem with the way i declared my variable or my class i could not find anything,['c++'] +278673,rails javascript asset missing after precompile the rails guides saysif there are missing precompiled files in production you will get an sprocketshelpersrailshelperassetpathsassetnotprecompilederror exception indicating the name of the missing filesi do executebundle exec rake assetsprecompilehowever i do not get any error and my javascript file is missing in the manifestyml also it is not appearing in publicassets so the problem is only on productioni have in the applicationjs require formalizejqueryformalizewhat am i missing thanks,"['javascript', 'ruby-on-rails']" +278688,jquery dataattribute is cutting of leading zero i am attempting to grab a data with jquery my problem is that jquery reads my string of numbers as a number and as such drops the leading zerohtmltr datastringnumber0123456789 website layout jk trjquery 172var string number selectordatastringnumber string number 123456789 string number 0123456789seems simple enough however this always drops the leading zerodatastringnumber is always going to be a number and may or may not have a leading zero currently it has a standard length but i cannot say at this point if that will stay truecurrent only thought is to prefix it with a nonnumeric and remove it straight away this feels hacky and makes me sadany thought appreciatedthanks,"['javascript', 'jquery']" +278695,clear answer on how to mask a uiview as a uitableviewcell selectedbackgroundview i have read and tried a few answers i have found on stackoverflow i have also read and tried a few things from blogs but nothing seems to accomplish what i am looking fori create a uiview and set it is background color to my desired uitableviewcell selection color instead of the standard blue or gray selection colors i add this uiview to my cells selectedbackgroundview and this works fine my cell changes to the desired color on user selectionthis method works great on plain uitableviews not so well on grouped on a grouped uitableview the 1st and last cell do not conform to clip mask bounds as demonstrated in the below screenshotsi know there is no way to round just the topleft and topright corners onlyi want to do this strictly by code without images questiondoes anyone know of a nice little work around to change the selectedbackgroundview color of a uitableviewcell using only the uiview and not images and to make the 1st and last cell conform to the rounded corner boundariesexample uitableviewcell tableviewuitableview tableview cellforrowatindexpathnsindexpath indexpath static nsstring cellidentifier cell wcsbadgedcell cell wcsbadgedcell alloc initwithstyleuitableviewcellstylesubtitle andbadgestyle0 reuseidentifiercellidentifier if cell nil cell wcsbadgedcell alloc initwithstyleuitableviewcellstyledefault andbadgestyle0 reuseidentifiercellidentifier uiview bgcolorview uiview alloc init bgcolorview setbackgroundcolordarkbrown bgcolorview setclipstobounds yes celayer setmaskstoboundsyes cell setselectedbackgroundviewbgcolorview celltextlabel settext testing a cell return cellscreenshotssolutioni accepted codafis answer because he added a comment which pointed to a pretty nice yet lengthy solution i had to do quite a bit of revamping but in the end i now have the selectedbackgroundviews i needed which round the corners on the 1st and last cells thanks againhere is a and example of how i achieved this,['ios'] +278699,is datetoday in utc calling datetoday in ruby returns the current date however what timezone is it in i assume utc but i want to make sure the documentation does not state either way,['ruby'] +278703,untrusted groovy script security in java we are attempting to provide scriptable elements with in an enterprisy product we would like to use groovy but we are having difficulty securing very basic thingsfor example we would like to prevent a client from simply goingclassfornamemycompanyinternalsecruitytoolsrunasawesomeweve installed a security manager with a policy that only allows accesdeclaredmembers and have overwritten the checkpackageaccess method and only allow white listed packages unfortunately the default classloader chain appears to just bypass this and load the class any howit would seem like this is a fairly common thiscussed problem but i cannot for the life of me find a library or even a good blog post on how to lock down untrusted scripts with in the context of a much greater applicationhas any one done this succesfully am i missing some fairly obvious posts concepts is there already a solid library for this maybe groovytinfoilhatmodetrue,['java'] +278745,cannot close excel completely using win32com on python this is my code and i found many answers for vba net framework and is pretty strange when i execute this excel closesfrom win32comclient import thispatchexexcel thispatchexexcelapplicationwbs excelworkbookswbscloseexcelquitwbs noneexcel none excel closes herebut when i do the following it does not closeexcel thispatchexexcelapplicationwbs excelworkbookswb wbsopendxaguara1xlsmwbclosefalsewbscloseexcelquitwb nonewbs noneexcel none not closing i found some possible answer in stack overflow question excel process remains open after interop traditional method not working the problem is that is not python and i do not find marshalreleasecomobject and gc i looked over all the demos on sitepackageswin32com and otherseven it does not bother me if i can just get the pid and kill iti found a workaround in kill process based on window name win32may be not the proper way but a workround isdef close excel by forceexcel import win32process import win32gui import win32api import win32con get the windows process ids hwnd excelhwnd t p win32processgetwindowthreadprocessidhwnd ask window nicely to close win32guipostmessagehwnd win32conwm close 0 0 allow some time for app to close timesleep10 if the application did not close force close try handle win32apiopenprocesswin32conprocess terminate 0 p if handle win32apiterminateprocesshandle 0 win32apiclosehandlehandle except passexcel thispatchexexcelapplicationwbs excelworkbookswb wbsopendxaguara1xlsmwbclosefalsewbscloseexcelquitwb nonewbs noneclose excel by forceexcel you die die,['python'] +278764,samsung galaxy note emulator i am trying to create emulator for samsung galaxy note but it is not workingi tried the following configsdk r17platform 233resolution 1280x800density 320emulator skin is comeup but it does not have any navigation keys menu back and home keys also no keyboard thisplayedi also tried with platform 403 same problem there emulator comes up without any keysfor galaxy tab i use samsung addon so no problem with emulatorbut i could not find any addon for galaxy note,['android'] +278796,how to create a rotating wheel control i am trying to implement the rotatory wheel in android just like the image thisplayed belowi came across the tutorial from this link but i want to implement just as shown in the below imagethe wheel consists of individual imagesdoes anybody have any idea regarding this implementation any help would be appreciatedthanks in advanceakash,['android'] +278812,need some help on bump api sending images i need some help here i will like to transfer an jpg or png images from one iphone to another through bump i encountered success and failure where images does not sent at allbelow are a nsobject file that will be call when user selected an images from uiimagepickerthe receiver will not sent any data but only receiveplease help me have a look on the code and give me any comment or pointthanks and appreciated your assistance id init ifself super init bumpobject bumpapi sharedinstance nserror error nsurl fileurl nsurl fileurlwithpathnsbundle mainbundlepathforresourcesound bump tap oftypeaif bumpsound avaudioplayer alloc initwithcontentsofurlfileurl errorerror bumpsound preparetoplay return selfvoid configbump bumpobject configapikeymy api key put your api key here get an api key from bumpobject configdelegateself bumpobject configparentviewselfbumpshareview bumpobject configactionmessagebump with your friend to start void startbump self configbump bumpobject requestsession void stopbump bumpobject endsessionpragma mark pragma mark private methods for debug prints contents of nsdictionaryvoidprintdictnsdictionary ddict nslogprinting dictionary nsarray keys ddict allkeys for id key in keys nslog key value keyddict objectforkeykey pragma mark pragma mark public methods void senddetailsuiimage selectedimage bumpshare showhud now we need to package our message dictionary up into an nsdata object so we can send it up to bump well do that with with an nskeyedarchiver nsloghere got called selfselectedimg nsdata wholeimagedata nskeyedarchiver archiveddatawithrootobjectuserchunk int datalength wholeimagedata length int maxchunksize 262144 int chunkcount datalength maxchunksize if chunkcount 1 data is 254kb or under nsdata movechunk nskeyedarchiver archiveddatawithrootobjectselfselectedimg bumpobject senddatamovechunk else if datalength maxchunksize nslogsending data d bytes in d chunks datalength chunkcount for int i 1 i chunkcount i int ithchunklength 0 if maxchunksize i datalength ithchunklength datalengthmaxchunksizei1 else ithchunklength 262144 nsdata movechunk wholeimagedata subdatawithrangensmakerangemaxchunksizei1ithchunklength nskeyedarchiver archiveddatawithrootobjectselfselectedimg subdatawithrangensmakerange262144i1maxr nslogsending chunk d d bytesimovechunk length bumpobject senddatamovechunk nsdata photodata uiimagejpegrepresentationselfselectedimg 09 nsdata userchunk nskeyedarchiver archiveddatawithrootobjectselfselectedimg ifnskeyedarchiver archiveddatawithrootobjectphotodatalength 262144 int dlen nskeyedarchiver archiveddatawithrootobjectphotodata length nslogsending data i bytes in d chunksdlenintceilfloatdlen 2621440f for int i1 i intceilfloatdlen 2621440f i int maxr0 if 262144i dlen maxr dlen262144i1 else maxr 262144 nsdata movechunk nskeyedarchiver archiveddatawithrootobjectphotodata subdatawithrangensmakerange262144i1maxr nslogsending chunk d d bytesimovechunk length bumpobject senddatamovechunk else data is 254kb or under nsdata movechunk nskeyedarchiver archiveddatawithrootobjectphotodata bumpobject senddatamovechunk self printdictmovedict userdict release calling send will have bump send the data up to the other users mailbox the other user will get a bumpdatareceived callback with an identical nsdata chunk shortly packetsattempted bumpobject senddatauserchunk void startconnectionuiimage selectedimage set local and remote user names bumpshare setlocalusernamebumpobject me username bumpshare setremoteusernamebumpobject otherbumper username bumpshare updateusernames self senddetailsselectedimagepragma mark utilityvoid quickalertnsstring titletext msgtextnsstring msgtext uialertview alert uialertview alloc initwithtitletitletext messagemsgtext delegatenil cancelbuttontitleok otherbuttontitlesnil alert show alert release voidimagesavedtophotosalbumuiimage image didfinishsavingwitherrornserror error contextinfovoid contextinfo nsstring message nsstring title if error title nslocalizedstringsave success message nslocalizedstringsave success message hudcustomview uiimageview alloc initwithimageuiimage imagenamedcheckmarkpng hudmode mbprogresshudmodecustomview hudlabeltext photo saved to photo album hud hideyes afterdelay15 saved 1 selfimageoverlayalpha 07 bumpshare hidehud self performselectorselectorsavesuccess withobjectnil afterdelay05 else title nslocalizedstringsave failed message error description hudcustomview uiimageview alloc initwithimageuiimage imagenamedsad facepng hudmode mbprogresshudmodecustomview hudlabeltext error saving to photo album hud hideyes afterdelay3 voidsavesuccess bumpshare pushtosuccesspragma mark pragma mark bumpapidelegate methods void bumpdatareceivednsdata chunk the chunk was packaged by the other user using an nskeyedarchiver so we unpackage it here with our nskeyedunarchiver nslogchunk length ichunk length nsdata receiveddata nskeyedunarchiver unarchiveobjectwithdatachunk if chunk length 262144 nslogcalled length ireceiveddata length if selfreceiveddata selfreceiveddata nsmutabledata datawithcapacitychunk length selfreceiveddata setdatachunk else selfreceiveddata appenddatachunk self stopbump uiimage receivedimage nskeyedunarchiver unarchiveobjectwithdataselfreceiveddata uiimagewritetosavedphotosalbumreceivedimage self selectorimagesavedtophotosalbum didfinishsavingwitherror contextinfo nil else ifchunk length 262144 nslogcalled length ireceiveddata length nslogcalledin length ichunk length if selfreceiveddata selfreceiveddata nsmutabledata datawithcapacitychunk length selfreceiveddata setdatachunk else selfreceiveddata appenddatachunk void bumpsessionstartedwithbumperotherbumper self startconnectionnil void bumpsessionendedbumpsessionendreasonreason nsstring alerttext switch reason case end lost net alerttext connection to bump server was lost break case end other user lost alerttext connection to other user was lost break case end user quit alerttext you have been thisconnected break default alerttext you have been thisconnected break ifreason end user quit if the local user initiated the quitrestarting the app is already being handled other wise well restart here uialertview alert uialertview alloc initwithtitlethisconnected messagealerttext delegatenil cancelbuttontitleok otherbuttontitlesnil alert show alert release nslogsending chun nslogselfreceived data iselfreceiveddata length if selfreceiveddata length200 nsdata imgdata nskeyedunarchiver unarchiveobjectwithdataselfreceiveddata uiimage receivedimage uiimage imagewithdataimgdatanskeyedunarchiver unarchiveobjectwithdataselfreceiveddata uiimagewritetosavedphotosalbumreceivedimage self selectorimagesavedtophotosalbum didfinishsavingwitherror contextinfo nil else bumpshare hidehud self performselectorselectorsavesuccess withobjectnil afterdelay15 void bumpsessionfailedtostartbumpsessionstartfailedreasonreason nsstring alerttext switch reason case fail network unavailable alerttext please check your network settings and try again break case fail invalid authorization the user should never see this since well pass in the correct api auth strings just for debug alerttext failed to connect to the bump service auth error break default alerttext failed to connect to the bump service break ifreason fail user canceled if the user canceled they know it and they do not need a popup uialertview alert uialertview alloc initwithtitleconnection failed messagealerttext delegatenil cancelbuttontitleok otherbuttontitlesnil alert show alert release,"['iphone', 'ios']" +278815,dapper intermediate mapping slightly more advanced mapping then in my previous question tablescreate table primary id int not null customerid int not null customername varchar60 not null date datetime default getdate constraint pk primary primary key idcreate table secondary primaryid int not null id int not null date datetime default getdate constraint pk secondary primary key primaryid id constraint fk secondary primary foreign key primaryid references primary idcreate table tertiary primaryid int not null secondaryid int not null id int not null date datetime default getdate constraint pk tertiary primary key primaryid secondaryid id constraint fk tertiary secondary foreign key primaryid secondaryid references secondary primaryid idclassespublic class primary public int id get set public customer customer get set public datetime date get set public listsecondary secondaries get set public class secondary public int id get set public datetime date get set public listtertiary tertiarys get set public class tertiary public int id get set public datetime date get set public class customer public int id get set public string name get set is it possible to use one select to fill them all something like thisconst string sqlstatement select pid pcustomerid pcustomername pdate sid sdate tid tdate from primary p left join secondary s on pid sprimaryid left join tertiary t on sprimaryid tprimaryid and sid tsecondaryid order by pid sid tidand thenienumerableprimary primaries connectionqueryprimary customer secondary tertiary primary sqlstatement here comes dragons edit1 i could do it with two nested loops foreach secondaries foreach tertiaries and perform a query for each item but just wonder if it could be done with single database calledit2 maybe the querymultiple method would be appropriate here but if i understand correctly then i would need multiple select statements in my real life example the select has more then 20 conditions in where clause where the search parameter could be null so i would not like to repeat all those where statements in all the queries,['c#'] +278817,cost of a page fault trap i have an application which periodically after each 1 or 2 seconds takes checkpoints by forking itself so checkpoint is a fork of the original process which just stays idle until it is asked to start when some error in the original process occurs now my question is how costly is the copyonwrite mechanism of fork how much is the cost of a page fault trap that will occur whenever the original process writes to a memory page first time after taking a checkpoint that is as copyonwrite mechanism will make sure that it gives the original process a different physical page than the checkpointin my opinion the page fault trap overhead could be quite high as an interrupt occurs we land from userspace land to the kernel space land and then back from kernel to userspace how many cpu cycles can i lose from such a a page fault trap assume that the ram is big enough and we do not ever need to swap to the hard thiskwell i know that its difficult to imagine a checkpointing scheme more efficient than this and therefore you could say why i am worrying about page trap fault overhead but i am asking just to have an idea how much cost will be there for this scheme,['c'] +278830,interfaces what if not all implementations use all methods i am fairly new to programming against interfaces and am trying to get it right as a major tool for developing test driven currently we have a lot of manager classes that all implement a crud interface however some managers do not yet do updates and some do not do delete some may never do so not implemented exceptionis it okay to just throw new notimplementedexceptionuntil the method gets implemented or even for all time if it never doesobviously with a source code comment telling the programmer this method is not supposed to be used as eg types like male female do never get deletedsplitor should i split my crud interface into creatable readablesearchable updatable and deletable wouldnt that clutter my class definitionpersonmanager implements creatableperson updateableperson deletableperson searchablepersonsplit and combineor should i combine some interfaces like all 4 into crud and maybe some other combinations like read update maybe that would also create a load of interfaces where one has to click through a big inheritence path to find out which interface implements all the desired atomic interfaces for the current situation i need read and create so which one just implements the two and this can get a lot more complex quickly,['java'] +278860,is it possible to execute many stored procedures in a single operation i am coding to read xml files to update the database i get about 500 xml files and i want to process them as fast i canall database operations are done using stored proceduresthere are about 35 different stored procedures called for each xml fileinitially i had written the code like thisvar cmd new sqlcommandexec updateteamstatsteamidpointscmdcommandtype commandtypetextbut after going through some best practices i changed it to var cmd new sqlcommandupdateteamstatscmdcommandtype commandtypestoredprocedurecmdparametersaddteamid 21cmdparametersaddpoints 2because of the high number of stored procedures being called from the program i realized i have to make lesser number of calls in order to optimizeso i want to collect all the 35 stored procedures together and execute them in one gothe stored procedures are different with different parameters and i dont know a way to collect and execute them together after the parameter changes i did abovei was thinking of calling one giant stored procedure and inside that stored procedure calling the other 35 but i am not very good at sql and it will lead to unnecessary complexityis it possible to do this entirely in c or is there some other better method to queue up the storedprocedures and run them quickly,"['c#', '.net']" +278861,playing flvhttp in android application in my application i need to play flvhttp streams on android 2x libvlc supports this function i have tested my flv streams with vlcandroid player and it seems to workbut a year ago one of the developers described is as followsvlc on android is incomplete unfinished buggy slow it does not even compile why are so much people trying to build it anywayso is the idea to use vlc for my project good or it is better to search some other way are there some other means for playing flv on andoid,['android'] +278919,nslog outputs unicode characters as garbage when debugging on the iphone edit nslog output works well in the simulator but does not work when connected to a real device and it seems that it is a bug a also it happens that it is related to the lldb switching xcode to gdb resolves the problem either it is possible to jetbrains appcode which works well with the lldbi have a bunch of unicode strings in the application and if i try to output any of those strings using something like nslog astring then all the ascii characters in the string will be printed fine but all the cyrillic letters will be messed up so instead ofnewlocation coordinate6001958430284954 n12ni am gettingnewlocation coordinate6001958430284954 aa14aiaia and that is quite hard to do any debugging with that kind of output and because that app is targeted for the russian market only i cannot just change locale and use english stringsso i wonder if there any way to make nslog work well with unicode characters and i am looking only for some kind of oneliner solution i know that there are some ways to write half a page of code and output unicode chars but i am looking for something shorter ideally i am looking for some method of nsstring that will make it all work egnslog astring somethingthatmakesunicodeworkwithxcodeconsole,"['iphone', 'objective-c', 'ios']" +278927,custom url scheme for sharing url in native facebook iphone app i know the available custom url schemes for the native facebook iphone appwhat are all the custom url schemes supported by the facebook iphone appbut i cannot find a way to publish a url to my wall timeline in that way that facebook collects shows the site title and thumbnail as it does with the touchfacebookcomsharerphp file the only way i see so far is to callfbpublishtextwdomaincombut this only post the link to my timeline not title thumbnail and site description does anyone know a better way,['ios'] +278930,interface extends another interface but implements its methods in java when an interface extends another interfacewhy does it implement its methodshow can it implement its methods when an interface cannot contain amethod bodyhow can it implement the methods when it extends the other interfaceand not implement itwhat is the purpose of an interface implementing another interfacethis has major concepts in javaedit public interface firesdragevents void adraghandlerdraghandler handler void removedraghandlerdraghandler handlerpublic interface dragcontroller extends firesdragevents void adraghandlerdraghandler handler void removedraghandlerdraghandler handler void dragend void dragmovein eclipse there is the implement sign besides the implemented methods in dragcontrollerand when i mousehover it it says that it implements the method,['java'] +278933,how to debug java application from sublime text editor sometimes i am doing simple fixes for rather huge java application and i do not want to open eclipse for this task eclipse starts long and since the project is build out of large number of subprojects which are build anyway by maven it takes ages before eclipse is usable at least ages in impatient java developer scalealmost everything i need can be done in sublime text editor however one place where eclipse shines is debugger my workflow is make a fix then test it running application on server using debugger to check if everything is okso is there any sublime plugin or other nonide solution for easy debugging of java applicationnote i have seen this post its pretty old maybe there is something better,['java'] +278965,how to make div height 100 between header and footer is there a way to setup a layout so that the header is 50px body is 100 and footer is 50pxi would like the body to use up the entire viewing area at minimum i would like to have the footer and header to be on the screen at all times,"['html', 'css']" +279041,beforeclass annotations invoking methods twice when using arquillian on remote server were transitioning from using testng with an embedded jboss to using arquillian with a remote serverwe are running a simple test that has a method annotated with beforeclass that does some test setup after a lot of digging it looks like that setup method is being called twice once on the console where were executing our maven command to run the test and again when the test war is deployed to our remote server and the test runs these are two separate jvms one running outside the container and another running inside the container my preference is to just have the latter runis this the behavior i should expect or is there something i may be missingfor now were actually checking to see if were in the container or not and if so we run our setup code this works but i would like to know if there is a better waysome snippets of our code please ignore the simplicity of the code and the fact that the setupcomponents method really is not needed here there are much more complicated tests that were migrating that will need this functionalitypublic class basetest extends arquillian private static log log logfactorygetlog seamtestclass deployment public static archive createdeployment snip basically we create a test war here todo there might be a better way to do this private boolean runningincontainer try new initialcontext lookup javacompenv return true catch namingexception ex return false beforeclass public void setuponce throws exception getlogdebug in setuponce runningincontainer if runningincontainer new componenttest protected void testcomponents throws exception setupcomponents run public user createuser public log getlog snip public userdao getuserdao public abstract class componenttest protected abstract void testcomponents throws exception public void run throws exception try testcomponents finally public class userdaotest extends basetest userdao userdao override protected void setupcomponents getlogdebug in setupcomponents runningincontainer userdao getuserdao test public void testgetuser throws exception getlogdebug in testgetuser runningincontainer new componenttest protected void testcomponents throws exception user user0 createuser user0setname frank userdaomerge user0 user retrieveduser userdaofindbyname frank assertnotnull retrieveduser run this basically gives me output that looks like thisfrom the console where mvn is being executedin setuponce falsefrom the jboss serverin setuponce truein setupcomponents truein testgetuser true,['java'] +279116,js library for creating a mindmap like interface i have to create an interface similar to what provides for drawing a network architecture for different purposes than what they are doingbasically users should be able to drag drop elements to a canvas and connect them using directional arrowswhat library should i use for this i am looking at d3 raphael and ocanvas,['javascript'] +279125,pass datetimetimestamp from php to javascript by echo how can i pass a datetimetimestamp from php to javascript the following does not appear to workstartlive new datephp echo dateu strtotimestart date,"['php', 'javascript']" +279137,fastest efficent markdown in javascript i am looking for a javascript markdown md engine for both inbrowser serverside via nodejs most of the time the intended output will be html5 though i may use md for xml pdf the various epub formats uncertain if direct md to xformat or html to xformat would be best fast conversion of a large md file would be best but i am also planning to use it on lowerend mobile phones so memory usage is also to be consideredi imagine there is javascriptmd experience out there that i cannot find tests people have run etc so far here is the information i have collected built for speed older no longer maintainedother research most olderwhat is the best jquery wysiwym textile editormarkdown to convert double asterisks to bold text in javascriptjavascript to convert markdowntextile to html and ideally back to markdowntextileis there any good markdown javascript library or controlhow would you go about parsing markdown,['javascript'] +279143,launch bootstrap modal on page load i do not know javascript at all the bootstrap documentation says to call the modal via javascript mymodalmodaloptionsi have no clue how to call this on a page load using the supplied code on the bootstrap page i can successfully call the modal on an element click but i want it to load immediately on a page load,['javascript'] +279148,calling ccli delete on c object i am in the middle of converting some code from ccli to c one of the objects has a destructor in the ccli version some other ccli code calls delete on this object after usewhich method do i need to implement in the c version of this object so those deletes continue to function the same ithisposablethispose the finalizer or something else that i am missing,['c#'] +279216,c object null check i read my database using datareaderand some row does not have fdate value so when i convert the null date to datetime then error occurs how can i check the field empty or notadscommand cmd conncreatecommandcmdcommandtext select namefdate from abcadsdatareader reader cmdexecutereaderdatetime flsdate readerfdateequalsnull converttodatetimereaderfdate datetimetodayi tried with equals but it does not workanybody know how to check the null object to avoid convert errorthank you,"['c#', 'asp.net', '.net', 'sql']" +279235,allow all remote connections mysql i had been using sql server and am now using mysql for a project with sql server our developers can connect to the remote database on their local machines if they know the host username password with mysql though to give a developer access from their local machines i have been having to log in to mysql and executegrant all on to useraddress identified by password flush privilegeswhere address is the ip address of the developers machine of course if they change networks i have to execute it again is there a way to allow all remote connections like i have experienced with sql server or is this a bad idea for some reason we have username and password still i am obviously a little confusedalso this is a development database and is only accessible from our internal network i understand why it is a bad idea to give everyone access to a production database,['mysql'] +279243,c operator overloading no known conversion from object to reference when i try to compile the following g 463class a a operator a a const a b return aa operator const a a const a b return a a bint main int char a a b a ab return 0i get the errortmptestcxx in function aa operatorconst a const aatmptestcxx1420 error no match for aoperatora in a a batmptestcxx1420 note candidate istmptestcxx61 note a operatora const atmptestcxx61 note no known conversion for argument 1 from a to athis puzzles me how can a conversion from a class to a reference to that class not be knownchanging the declaration of class a as follows does not have any effectclass apublic a a const a same errori would be extremely grateful for hints as to whats going on here,['c++'] +279268,heroku rails procfile i am very new to herokui uploaded my rails app to heroku and would like to run it with thin instead of webrick following herokuas guide i am supposed to use web bundle exec rails server thin p port e rack env to create the procfile however i always get the response web command not foundwhat am i missing,['ruby-on-rails'] +279269,bottom margin or padding does not work in relative layout in xml on android i have a relativelayout for a row that goes inside a listview the row looks likerelativelayout xmlnsandroid androidididrelativelayout1 androidlayout widthwrap content androidlayout heightfill parent imageview androidididplacedetailicon img androidlayout height50dp androidlayout width50dp androidlayout alignparentlefttrue androidpaddingbottom20dp androidpaddingtop20dp androidpaddingleft20dp androidpaddingright20dprelativelayouti also tried it with margin imageview androidlayout height50dp androidlayout width50dp androidididplacedetailicon img androidlayout alignparentlefttrue androidlayout marginright10dp androidlayout margintop10dp androidlayout marginleft10dp androidlayout marginbottom10dpneither apply the margin or padding around the imageview how do create this type of spacing,['android'] +279304,creating a runnable jar various problems i have been working on a command line executable java program it is in the testing phase and packaging it up has proved a bit of an issue the crux of this problem revolves around the many dependencies my application has my lib folder containing jars is close on 500mbat the moment i have been using the eclipse runnable jar export wizard works flawlessly except it has to be done from eclipse it generates a jar about 500mb in size do not ask suffice to say there need to be a lot of cobol programs being packaged inside this program this process takes 30sideally i would like this to be an ant task of some kind runnable via jenkins and published to a repository that way a user can just grab a jar and run itoptions i have investigatedcustom classloader fatjar onejar etcworksslow to execute at runtime as it is required to unpack the jarfile structure is basically a jar full of jars and the main class is delegated through the custom classloaderfast build time 5 minstarget namehello dependscompile property nameclassesdir valueonejar property namebuilddir valuebin onejar destfilehellojar manifest attribute nameonejarmainclass valuemainclass attribute nameclasspath value attribute nameonejarshowexpand valuetrue manifest main fileset dirbuilddir main lib fileset dirlib include namejar fileset lib onejartargetmanually collecting dependencies unpacking them into a folder then jarring them all up with a custom manifest filecannot get it to work large 1500mb slow build time 20min target namecompile dependsresolve javac srcdirsrc destdirbin debugtrue deprecationon classpath path refidivypath classpath javactargettarget namejar dependscompile descriptioncreate one big jarfile jar jarfilethistdepsjar zipgroupfileset dirlib include namejar zipgroupfileset jar sleep seconds1 jar jarfilethistmyjarjar basedirbin zipfileset srcthistdepsjar excludesmetainfsf manifest attribute namemainclass valuemymainclassishere manifest jartargetso yeah does anyone have any suggestions i am interested to hear peoples thoughtsedit specifically why the eclipse runnable jar export wizard can export my jar in less then 30s yet my build times are 30 minutes,['java'] +279316,cc program that prints its own source code as its output wikipedia says it is called a quine and someone gave the code belowcharscharscscmainprintfs34s34mainprintfs34s34but obviously you have to addinclude stdioh corrected from include stdlibhso that the printf could workliterally since the above program did not print include stdioh it is not a solution i am confused about the literal requirement of print its own source code and any purpose of this kind of problems especially at interviews,['c'] +279331,dynamic uilabel heightswidths in uitableviewcell in all orientations my question essentially boils down to the best way to support dynamic heights of uilabels and i suppose other elements in a uitablecell and also correctly resize the label widthheight and cell heights when rotatingi am aware of how to get the expected height of uilabels and size the heights accordingly but things seem to get pretty tricky when you support landscape orientation as welli am thinking this might go the route of layoutsubviews but i am not sure how you would combine that with the table needing to calculate the height of cells another interesting post sets the frame manually on init to make sure they are doing calculations off a known quantity but that only addresses part of the issueso heres an image of what i am dealing with with red arrows pointing to the dynamic height labels and blue arrows pointing towards the cells that will change heighti have managed to get it working correctly but not sure if its the correct method heres a few of the things i learnedthe cellframe in cellforrowatindexpath always gives its size in portrait mode ie for the iphone app it always reports 320storing a prototype cell for reference in a property has the same issue always in portrait modeautoresizing masks for the width of labels seem to be useless in this use case and in fact cause issues with the calculated height on rotationthe tableviewframe in cellforrowatindexpath gives its size in the correct orientationyou need to call tableview reloaddata on rotation i could not find any other way to update the cell and label heightshere are the steps i took to get this working for methisable any autoresize masks on uilabels as they interfere with getting the right label height for some reasonon viewdidload i grab a reference to each label font and a float for the label width percentage compared to the tableview in portraitcwproductdetaildescriptioncell cell selftableview dequeuereusablecellwithidentifierdescriptioncellselfdescriptionlabelwidthpercentage celldescriptionlabelframesizewidth 320selfdescriptionlabelfont celldescriptionlabelfontin heightforrowatindexpath i calculate the cell height using the tableview width and the percentage i already grabbedcase tablesectiondescription cgfloat labelwidth selftableviewframesizewidth selfdescriptionlabelwidthpercentage cgsize newlabelframesize self sizeforstringselfproductdescriptiontext withconstraintcgsizemakelabelwidth maxfloat andfontselfdescriptionlabelfont return newlabelframesizeheight ktextcellpaddingin cellforrowatindexpath i calculate the frame for the label frame and update itcell tableview dequeuereusablecellwithidentifierdescriptioncellcwproductdetaildescriptioncell celldescriptionlabeltext selfproductdescriptiontextcgrect oldframe cwproductdetaildescriptioncell celldescriptionlabelframecgfloat labelwidth selftableviewframesizewidth selfdescriptionlabelwidthpercentagecgsize newlabelframesize self sizeforstringselfproductdescriptiontext withconstraintcgsizemakelabelwidth maxfloat andfontcwproductdetaildescriptioncell celldescriptionlabelfontcwproductdetaildescriptioncell celldescriptionlabelframe cgrectmakeoldframeoriginx oldframeoriginy labelwidth newlabelframesizeheightin didrotatefrominterfaceorientation you need to selftableview reloaddataproblems with this methodyou cannot leverage the autoresizing masks and margins you might set in ibthose do not seem to fire until after youve returned the cell in cellforrowatindexpath not sure if this is exactly truethey mess up the height calculation somehow and your labels end up taller than desired in landscapeif your labels width is not an equal percentage in portrait and landscape youll need to know both percentagesyou need to knowcalculate your labels width percentages ideally you would be able to calculate these on the fly after an autoresizing mask has done its thing it just feels clumsy i have a feeling i am going to run into more headaches in editing mode with indentingso what is the right way to do this i have seen lots of so questions but none quite address this exactly,['ios'] +279343,how to package ruby shoes apps on osx 107 i have been making an app using ruby shoes i am happy with how it turned out and would like to share it with some friends however the gui packager does not work in osx and the windows packager only seems to make a shy file i have been reading around looking for solutions and i do not understand any of them can someone clearly explain stepbystep how to package a ruby shoes app to say a dmg or an exe file,['ruby'] +279351,smoothly rotate and change size of uiview with shadow i have a uiview with a shadow and a uiimageview subviewi want to resize the view when the ipad is rotated and i am trying to do this in the willrotatetointerfaceorientation callbackif i set the shadow on the uiview in the basic way the rotation is very choppy so i would like some suggestions from others on how to set the shadow setting layershadowpathi have tried animating the frame size change using uiview animatewithdurationanimations and setting the new shadowpath in the same block but the shadow path snaps to the new sizeand if i do not change the layers shadowpath in the animations block it does not changefrom a few searches i have done animating changes to layer properties need to be done with a cabasicanimationso i think the question may be how do i animate a uiviews frame size and layer change simultaneously,['ios'] +279358,interrupt pause running python program in pdb in gdb you can interruptpause the program by cc and resume can you do this in pdb,['python'] +279371,how do you cache an image in javascript my friends and i are working on a website where we would like to cache certain images in order to thisplay them faster in the future i have two main questionshow do you cache an imagehow do you use an image once it has been cached and just to verify if an image is cached on page a it is possible to call it from the cache to use it on page b rightalso is it possible to set when the cached version of the image will expireit would be much appreciated if an example andor a link to a page which describes this further was includedwere fine using either raw javascript or the jquery version,"['javascript', 'jquery']" +279378,inserting null values into date fields i have a formview where i pull data from one table ms access and then insert it plus more data into another table i am having issues with the dates the first table has two date fields date submitted and date updated in some records date updated is blank this causes me to get a data mismatch error when attempting to insert into the second tableit might be because i am databinding the date updated field from the first table into a hiddenfield on the formview it then takes the value from the hiddenfield and attempts to insert it into the second tabledim hfdaterequestupdated as hiddenfield formview1findcontrolhfdaterequestupdatedmydaterequestupdated hfdaterequestupdatedvalue it then attempts to insert mydaterequestupdated into the databaseit works when there is a value there but apparently you cannot insert nothing into a datetime field in access i suppose i could make a second insert statement that does not insert into date updated to use when there is no value indate updated but is that the only way to do it seems like there should be an easierless redundant wayedit okay so i have tried inserting sqldatetimenull nothing and dbnullvalue sqldatetimenull results in the value 1900 being inserted into the database nothing causes it to insert 112001 and if i try to use dbnullvalue it tells me that it cannot be converted to a string so maybe i did not do something quite right there at any rate i was hoping that if there was nothing to insert that the field in access would remain blank but it seems that it has to fill it with somethingedit i got dbnullvalue to work and it does insert a completely blank value so this is my final working codedim hfdaterequestupdated as hiddenfield formview1findcontrolhfdaterequestupdateddim mydaterequestupdated nothingif hfdaterequestupdatedvalue nothing then mydaterequestupdated dbnullvalueelse mydaterequestupdated datetimeparsehfdaterequestupdatedvalueend ifthanks everyone,"['asp.net', 'sql']" +279390,optimal usage of battery as a programmer what are the measures i can take to take care that my app does not hog a lot of resources and drain the battery,['android'] +279395,sql open connection in read only mode this question comes out of curiosity i searched google for this but did not get a cluesuppose a user has full readwrite access to mysql database i am wondering is there any way some parameter in connection string to connect to database by the same username and password in readonly modei want this without changing this users permissions because the same user might require write permission too at some other time this would be useful if possible to prevent accidental modification to database,['mysql'] +279404,bug in twtweetcomposeviewcontroller i am using twtweetcomposeviewcontroller when available to send tweets from inside my ios app i prepopulate the view controller with boilerplate text then let the user modify and send at their thiscretion it works great for the most part thistilled down it looks like this with body pointing at a valid nsstringif nsclassfromstringtwtweetcomposeviewcontroller twtweetcomposeviewcontroller ios5twitter twtweetcomposeviewcontroller alloc init ios5twitter setinitialtextbody ios5twittercompletionhandler twtweetcomposeviewcontrollerresult result selfviewcontroller thismissviewcontrolleranimatedyes completionnil selfviewcontroller presentviewcontrollerios5twitter animatedyes completionnil ios5twitter releaseelse do something else when the framework is missing now if body is too long ie more than 140 characters the resulting tweet view is empty of any text at all character countdown set to 140 i might have expected truncation in this case although it does not appear to be documented in the class reference one way or the other what happens when the initial text is too long but i can accept that i have to do the truncation to maximum tweet length before passing to setinitialtextwhat i do not understand is that certain messages which are shorter than 140 characters also produce the empty tweet viewinitially i saw what seemed to be a perfectly valid string with 139 characters failing i noticed that shortening the string made it work but after a great deal of experimenting i also noticed that replacing a url which happened to appear inside the text with random text of the same length made it work in other words the url itself is causing a problemso i thought maybe there was something weird about the url i was using but i thistilled it down to this this one worksnsstring body while this does notnsstring body httpaobservationsthey are both 140 characters long and report that way in the console with body length the only difference is the presence of something vaguely urllike embedded in the middle of the second onethe position of the url within the string does not seem to matter but if i change any one of those nonperiod characters to a period thus making it not like a url anymore it ceases to be brokenif i shorten the broken one shaving 14 periods off the end it works that is this particular url embedded in periods for a total length of 126 characters is fine 127 or larger is broken not clear how or if this relates to the length of the url itselfanybody ever seen something like this any idea what is going on am i doing something wrong or is the ios twitter framework just broken,['ios'] +279410,azure service bus queue subcription filter change we are planning to use azure service bus queue along with topicsubscriptionwe have multiple subscriptions for a given topic with different filter conditionsmy question is can we change the filter of subscription dynamically once subscription is created how can i change the filter condition for subscription once it is createdi cannot find any methods which allows this the only option i see is delete subscription and recreate it any idea how to change filter without deleting subscription,['.net'] +279438,how can i make my device vibrate i am making a game in flash for android with as3 i want the user to know that he pressed a button by making the device vibrate for a brief second can someone explain to me how i can make this happen do i need to import a specific class and what should the code look likethanks in advance,['android'] +279445,short and sweet sequence of integers in java there must be a short and sweet way to generate a listinteger or perhaps an array of integer or int with sequential values from some start value to an end valuethat is something shorter than but equivalent to1void listinteger makesequenceint begin int end listinteger ret new arraylistendbegin1 for int ibegin iend i retaddi return ret but it is evading me use of guava or commons is fine1 perhaps with the exception of error handling eg if end begin or if the size exceeds some implementation or jvm limits eg arrays larger than 2311,['java'] +279455,android difference between getcount and getchildcount in listview what is difference between getcount and getchildcount in listview,"['java', 'android']" +279471,how to create a box when mouse over text in pure css i have tried many times to do this but it has not worked out yetwhen i mouse over this textthen it must show me this boxi want to achieve this effect purely with css if anybody can do this,['css'] +279474,ipad how to detect that multitasking gestures are enabled i created an ipad app in which it is helpful if multitasking gestures are not enabled i know you cannot thisable them from the app itself thank god apps cannot decide that on their own but what i want to do is thisplay a warning on startup if multitasking gestures are enabled and advice the user to turn them off for optimal usagei have seen apps do this very same thing like apples garageband in that app multitasking gestures can thisturb the working of the app when youre playing piano for instance garageband thisplays a warning exactly like the one i want to thisplaythe setting for multitasking gestures i am talking about is located in settings general multitasking gestures,['ios'] +279480,onclick on viewpager not triggered i set a click listener on a viewpager but the onclick event is never called i guess the touch event detection of the viewpager is interfering but i cannot see how to solve itanybody could helpthanksmviewpagersetonclicklistenernew onclicklistener override public void onclickview v never called,['android'] +279497,python generating integer partitions i need to generate all the partition of a given integeri found this algorithm by jerome kelleher that states to be the most efficient onedef accelascn a 0 for i in rangen 1 k 1 a0 0 y and 1 while k 0 x ak 1 1 k 1 while 2x y ak x y x k 1 l k 1 while x y ak x al y yield ak 2 x 1 y 1 ak x y y x y 1 yield ak 1reference by the way it is not quite efficient for an input like 40 it freezes nearly my whole system for few seconds before giving its output if it was a recoursive algorithm i would try to decorate it with a caching function or something to improve its efficiency but being like that i cannot figure out what to dodo you have some suggestions about how to speed up this algorithm or can you suggest me another one or a different approach to make another one from scratchthank you,['python'] +279536,java image resize maintain aspect ratio i have an image which i resizeifwidth null height null try scale image on thisk bufferedimage originalimage imageioreadfile int type originalimagegettype 0 bufferedimagetype int argb originalimagegettype bufferedimage resizeimagejpg resizeimageoriginalimage type 200 200 imageiowriteresizeimagejpg jpg file catchioexception e systemoutprintlnegetmessage this is how i resize the imageprivate static bufferedimage resizeimagebufferedimage originalimage int type integer img width integer img height bufferedimage resizedimage new bufferedimageimg width img height type graphics2d g resizedimagecreategraphics gdrawimageoriginalimage 0 0 img width img height null gthispose return resizedimagenow the problem is i also need to maintain aspect ratio that is i need the new 200200 image to contain the new image scaled something like thisi tried some things but did not work out as expectedany help is appreciated thanks alot,['java'] +279538,get the google id used to download the application how can i find out which google account downloaded the applicationthis question is related to get the google id used in an inapp billing purchasethank you,['android'] +279544,is it necessary to add a in front of an sqlparameter name in one of our application the parameters passed to a stored procedure in this waydim parm as new sqlparametersearchtext sqldbtypevarcharparmdirection parameterdirectioninputparmsize 50parmvaluetestcmdparametersaddparmand the procedure contains a parameter as searchtextie the parameter name passed from the code is searchtext and that in the stored procedure is searchtext but it is working properly i am always getting the required resultsso my question is like so there is no need to specify before the parameter whether it will append can anyone please give an answer for this,['.net'] +279589,sql server convert varchar to datetime i have this date format 20110928 180100 in varchar and i want to convert it to datetime changing to this format 28092011 180100 how can i do it,['sql'] +279611,treedendrogram with elbow connectors in d3 i am very new to d3js and svg in general and i want to do something simple a treedendrogram with angled connectorsi have cannibalised the d3 example from here and i want to make it more like the protovis examples here i have made a start here and i think it is the following snippet that is wrong var diagonal d3svgdiagonalprojectionfunctiond return dy dx however there is no obvious replacement i could use d3svgline but i do not know how to integrate it properly and ideally i would like an elbow connectoralthough i am wondering if i am using the wrong library for this as a lot of the d3 examples i have seen are using the gravitational force to do graphs of objects instead of trees,['javascript'] +279616,spring interface injection example no one so far was capable of providing a working correct example of interface injection in spring framework martin fowler article is not for mortals everything else just words positioned in a very confusing way i have surfed over thirty articles where people either tell spring doesnt directly supports for interface injectionand because i do not know exactly how i will only describe setter and constructor injections or either i will thiscuss it in my other threads or either there will be few comments below saying that it is wrong example i do not ask for explanation i beg for examplethere are three types of injection constructor setter and interface spring does not support the latest directlyas i have observed people saying so how is it done exactlythank you,['java'] +279623,scala tuple type inference in java this is probably a very noobish question but i was playing a bit with scalajava interaction and was wondering how well did tuples play alongnow i know that the type1 type2 syntax is merely syntactic sugar for tuple2type1 type2 and so when calling a scala method that returns a tuple2 in a plain java class i was expecting to get a return type of tuple2type1 type2for clarity my scala codedef testtupleintint 01java codetuple2objectobject objectobjecttuple2 testtesttupleit seems the compiler expects this to be of parameterized types objectobject instead of in my case integerinteger this is what i was expecting at leastis my thinking deeply flawed and is there a perfectly reasonable explanation for this oris there a problem in my scala code and there is a way of being more explicit in the cases that i know will provide an api for java codeor is this simply a limitation,['java'] +279632,python recover exception from try block if finally block raises exception say i have some code like thistry try raise exceptionin the try finally raise exceptionin the finallyexcept exception e print try block failed s ethe output istry block failed in the finallyfrom the point of that print statement is there any way to access the exception raised in the try or has it thisappeared forevernote i do not have a use case in mind this is just curiosity,['python'] +279642,determine which version of opencv i want to write to short code snippet in python to determine which version of opencv has been installed in my system how do i do it thank you,['python'] +279654,naming a rails has many through polymorphic relationship im having a bit of an issue setting up a rails has many through polymorphic relationshipi am aware this subject is well documented on so but i think my problem is down to my model and foreign key names as opposed to syntax ie i think this is a i have been looking at code too long issue that just requires another set of eyesanyway i have the following setupclass milestone activerecordbase has many responsible items as responsibility has many responsible through responsible itemsendclass responsibleitem activerecordbase belongs to responsible class name user belongs to responsibility polymorphic trueendclass user activerecordbase has many responsible items foreign key responsible id has many responsibilities through responsible itemsendthis seems to work fine without error from the milestone side of things for example in terminal i can writemilestonefirstresponsibleaand get an empty collection as i would expecthowever from the user side of things runninguserfirstresponsibilitiesais returning an ar erroractiverecordhasmanythroughassociationpolymorphicsourceerror cannot have a has many through association userresponsibilities on the polymorphic object responsibilityresponsibilityi am assuming the issue is something to do with the fact that i am referring to the user relationship as responsible is this rightany help would be much appreciated thanks,"['ruby-on-rails', 'ruby']" +279678,python beginner faster way to find and replace in large file i have a file of about 100 million lines in which i want to replace text with alternate text stored in a tabdelimited file the code that i have works but is taking about an hour to process the first 70k linesin trying to incrementally advance my python skills i am wondering whether there is a faster way to do this thanksthe input file looks something like thischromosome iv ncrna gene 5723085 5723105 idgenewbgene045518 chromosome iv ncrna ncrna 5723085 5723105 parentgenewbgene045518and the file with replacement values looks like thiswbgene045518 21ur5153here is my codeinfile1 openf1txt rinfile2 openf2txt routfile openouttxt wimport refrom datetime import datetimestarttime datetimenowudict for line in infile1 line linestrip linelist linesplitt udict1 linelist0linelist1 udictupdateudict1mult10k for x in range100 mult10kappendx 10 linecounter 0for line in infile2 for key value in udictitems matches linecountkey if matches 0 print key value line linereplacekey value outfilewriteline n else outfilewriteline n linecounter 1 if linecounter in mult10k print linecounter print datetimenowstarttimeinfile1closeinfile2closeoutfileclose,['python'] +279679,is it possible to see different forms of a word through the word api i am wondering if it is possible to see a different form of a word through the word api i am in the process of making an open source tool that automatically adds documentation to properties and methods when saving the document it will only do it to methods that are public or protectedthe way i want it to work is that if you follow a specific naming convention and use for instance the method name addperson or add person the code takes these method names and converts them into an array of words add and personfrom these words i would like to detect if it is a verb or a noun for instance in this example add is a verb and person is a nounonce this has been detected i would furthermore like to transform the words to form the following documentation statement addpersonperson personadds a personperson the personi hope you understandso in short how can i convert add into adds in a smart way and how can i detect if add is a verb or a noun programmaticallyi assumed the word api would be a good start i just have no idea how,['c#'] +279705,html 5 audio element not looping in rails i am trying to use this javascript to loop an audio elementmusicjsmyaudio new audioassetsdrumloopmp3myaudioloop truemyaudioplay when i include this as a script in a plain html file and open the html file in safari 51 it loops just fine when i include this javascript from my rails application running on a local rails server the audio plays but does not loop i have tried using a callback on the ended event to set the time to zero and play again as suggested here but that does not work eitheris it possible that rails is not sending enough information in the http header,"['javascript', 'ruby-on-rails']" +279735,serializing python object instance to json i am trying to create a json string representation of a class instance and having difficulty let us say the class is built like thisclass testclass value1 a value2 ba call to the jsondumps is made like thist testclassjsondumpstit is failing and telling me that the testclass is not json serializabletypeerror main testclass object at 0x0227a400 is not json serializablei have also tried using the pickle module t testclassprintpickledumpst picklehighest protocoland it gives class instance information but not a serialized content of the class instancebx80x03c main ntestclassnqx00x81qx01qx02bwhat am i doing wrong,['python'] +279739,is this a good way to generate a random string on iphone heres the code i came up withnsstring randomstring for int x0xnumber of charsx randomstring randomstring stringbyappendingformatc char65 arc4random 25return randomstringeditto answer the comments1 i am mostly concerned with brevity of code 2 i also wonder if this is secure against guessing the string andor proof against collisions if number of chars is a high number say 40 not for this application but in other cases 3 also is there is a faster way if i want to make a ton of strings some day this seems like it will be slow since it makes an object each time through the loop,"['objective-c', 'ios']" +279740,lightweight mongodb odmorm for python i am looking for mondodb python odmorm that takes the best from two worlds odmorm ultra fast direct dictionary readin other words package shall comply with following requirementsallows to define and enforce schemaallows to validate fieldsallows to read objects directly from mongodb no odmorm overheadcollectionsobjects returned directly by pymongo can be accessed using odmorm layer wo extra queriesi would imagine some kind of lazy field added by pymongo driver to objects that provides access to orm juice pymongo allows for such extensionsimagine use case for fast read we go directly to driver for data entry we use full odmorm functionalitygeofields supportgridfs support of normal files and imagesdbref supportdoes not enforce any hidden framework specific fieldswill work with flask has forms frameworkforms cover sublistssubdictsbackbone based forms would be just awesomecreates backbone models collections validators based of python definitioni know that i am asking for much but wouldnt it be awesome to have something like this in fact question could be rephrased intowhich of existing python mongodb odmorms mongokit mongoengine could be easily extended this way,['python'] +279805,change default asp mvc request header to add your own values im trying to change all my asp mvc http response headers to have another value by default for implementing pingback autothiscovery in my blog applicationthe default header on cassini is cachecontrol privateconnection closecontentlength 20901contenttype texthtml charsetutf8date fri 20 apr 2012 224611 gmtserver aspnet development server10xaspnetversion 4030319xaspnetmvcversion 30and i want an extra value added xpingback httplocalhost4912pingbackxmlrpcserveri have googled a bit and found a neet solution to derive from actionfilterattribute and override the onresultexecuted methodpublic class httpheaderattribute actionfilterattribute public string name get set public string value get set public httpheaderattributestring name string value name name value value public override void onresultexecutedresultexecutedcontext filtercontext filtercontexthttpcontextrequestheadersaddname value baseonresultexecutedfiltercontext and then simply i put the attribute on my controllers methodshttpheaderxpingbackhttplocalhost4912pingbackxmlrpcserver public actionresult index var allarticles repositorygetpublishedarticlessortorderdesc return viewallarticles when i runt the app i get the following error any ideas,['c#'] +279806,can i cache partiallyexecuted linq queries i have the following codeienumerablekeyvaluepairt double items sequenceselectitem new keyvaluepairt doubleitem weightitemif itemsanypair pairvalue0 throw new argumentexceptionitem weights cannot be less than zerodouble sum itemssumpair pairvalueforeach keyvaluepairt double pair in items where weight is a funct doublethe problem is i want weight to be executed as few times as possible this means it should be executed at most once for each item i could achieve this by saving it to an array however if any weight returns a negative value i do not want to continue executionis there any way to accomplish this easily within the linq framework,['c#'] +279853,access to the path cinetpubwrootmyappapp data is denied i just installed iis on winxpwhen i tried to execute an app i get an erroraccess to the path cinetpubwrootmyappapp data is denied description an unhandled exception occurred during the execution of the current web request please review the stack trace for more information about the error and where it originated in the codeexception details systemunauthorizedaccessexception access to the path cinetpubwrootmyappapp data is deniedaspnet is not authorized to access the requested resource consider granting access rights to the resource to the aspnet request identity aspnet has a base process identity typically machineaspnet on iis 5 or network service on iis 6 that is used if the application is not impersonating if the application is impersonating via the identity will be the anonymous user typically iusr machinename or the authenticated request userto grant aspnet access to a file rightclick the file in explorer choose properties and select the security tab click add to add the appropriate user or group highlight the aspnet account and check the boxes for the desired accesource errorline 70 protected sub cmbsettingfiles selectedindexchangedbyval sender as object byval e as systemeventargs handles cmbsettingfilesselectedindexchanged line 71 dim doc as xmldocument new xmldocument line 72 docloadpathcombinebasepath cmbsettingfilesselectedvalue line 74 dim settingsnode as xmlnode docselectsinglenodesettingssource file cmyappinstallinstallaspxvb line 72 i have tried grating permission by doing this to grant aspnet access to a file rightclick the file in explorer choose properties and select the security tab click add to add the appropriate user or group highlight the aspnet account and check the boxes for the desired accessbut the error persistdoes this have anything to do with my codehow can i resolve thisediti have solved the probleom on my dev machine but still getting the error on web serverthanks,['asp.net'] +279855,can you access the ienumerable as you are yield returning it my code below finds all prime numbers below number by creating a list of primes and checking to see if the next potential prime is evenly divisible by any primes in the listi am trying to learn the ins and outs of yield return right now i have a listint primes that i use inside the function but i am returning the same data via yield return so my question iscan i access the ienumerable int from inside the function as i am creating it so i can remove the list int primes altogether summary finds all primes below paramref namenumber summary param namenumberthe number to stop atparam returnsall primes below paramref namenumberreturnsprivate static ienumerablelong primenumberslong number yield return 2 listlong primes new listlong2 forlong num 3 num number num 2 if any prime lower then num divides evenly into num it is not a prime what i am doing now ifprimestakewhilex x numanyx num x 0 primesaddnum yield return num madeup syntax for what i would like to do ifthisienumerablelong takewhilex x numanyx num x 0 yield return num,['c#'] +279875,ruby rails select only few columns from the data base what is the way in rails to structure sql query to only select certain columns from the database i have some large data fields which i want to avoid loading from continuous periodic ajax calls reading unnecessarily is resource consuming and slow itemlist itemfindall conditions this select all columns i am looking for select name address from users instead of select from users,"['ruby-on-rails', 'ruby']" +279904,aspnet thisableenable validator using javascript i have a complex form requiring me to switch specific validators on or off depending on selections made by the user validatorenable seems to do the job but it seems that when i call this method it actually fires the validation process as well without the user actually hitting the submit button is that how it works,"['javascript', 'asp.net']" +279906,nstimer decrease the time by secondsmilliseconds i am developing a quiz app it needs a countdown timer in that i want to start a timer at 750 mms and decrease it to 0 mms by reducing 1 millisecond i want to thisplay an alert that time up when time reaches to 0 mms i am thisplaying the time by following below linkstopwatch using nstimer incorrectly includes paused time in thisplay,"['iphone', 'objective-c']" +279918,how to stop an inprocess upload in plupload upremovefilefile works only if the upload is not in progressis this a bug or exists some other function i missed to call,"['javascript', 'jquery']" +279924,javascript check browser does anyone have a script for checking for old browsers it would have to follow this criteriaallow firefox 36 or upallow google chrome 15 and upallow safari 5 or upblock ie and operablock all other browsers,['javascript'] +279931,jsonparse unexpected nonwhitespace character after json data i wish to create a json object that is derived from the selected options of 4 select menus these menus may have options selected when loaded due to a server side technology or may have no options selected whatsoever once the page is loaded using documentready my script runsa however iam getting some problems with the json object ajsonparse unexpected nonwhitespace character after json dataai want my json to have the following structureselobj category selectedcategory we can only have 1 category this isnat giving me a problema catoptions optionvaluethiscountvalue we can have many of these optionvaluethiscountvalue optionvaluethiscountvalue tariff tariffvaluethiscountvalue we can have many of these tariffvaluethiscountvalue taroptions taroptionthiscountvalue we can have many of these okay hereas my function iave removed some items here to simplify but iam passing an original empty object into the function as an argument and then hoping to amend this as i will want to pass the json object back to the server ifwhen the select menus are changeda but for now weare just dealing with the page loadinga the function also shows the values or what is selected in a dynamic table that is created using a function called defaulttable just ignore that for now itas the populating of the json object iam interested in and having problems withvar selectmenuarray cat catopt tariff tariffopt these are the ids of the select menus selobj function setuptableselectarray theobj okay if we enter the page and and the user already has a tarif selected so it is shown in the menus we wish to show the table with the defaultoriginal values var currentselect cata catopta tara taropta catoptforobj tariforobj tariffoptforobj temp1 temp2 temp3 i loop through the 4 menus and see what is selected fori0iselectarraylengthi let us look at the options to see if any are selected by looping through the option currentselect documentgetelementbyidselectarrayi forj0jcurrentselectlengthj do we have an options with the selected attribute ifcurrentselectoptionsjselected true okay we need to make sure the table is shown then the correct values are shown we know what the menu is selectarrayi and this is the text currentselectoptionsj lets build up whets selected in arrays switchselectarrayi case cat catapushcurrentselectoptionsjvalue break case catopt catoptapushcurrentselectoptionsjvalue catoptforobj catoptforobj currentselectoptionsjvalue to come later break case tariff tarapushcurrentselectoptionsjvalue tariforobj tariforobj currentselectoptionsjvalue to come later break case tariffopt taroptapushcurrentselectoptionsjvalue tariffoptforobj tariffoptforobj currentselectoptionsjvalue to come later break default no default now we can build the table ifcatalength 0 catoptalength 0 taralength 0 taroptalength 0 show table dynamictableholder tablecssvisibilityvisiblehidefadeinslow fori0iselectarraylengthi switchselectarrayi case cat defaulttablecata dtcats theobjcat cata0 break case catopt defaulttablecatopta dttariffs temp1 catoptforobjsubstring0 catoptforobjlength1replaceundefinedg theobj jqueryparsejsoncatoptions temp1 break case tariff defaulttabletara dtcatopts temp2 tariforobjsubstring0 tariforobjlength1replaceundefinedg theobj jqueryparsejsontariff temp2 break case tariffopt defaulttabletaropta dttariffopts temp3 tariffoptforobjsubstring0 tariffoptforobjlength1replaceundefinedg theobj jqueryparsejsontaroptions temp3 break default no default iam having problems with making the json object what iam trying to do is concatenate strings whilst looping then covert these to objects using the jqueryparsejson methoda however iam not doing this correctly iave even tried changing the quotation marks when creating temp1 i know this is complicated and i may be asking a lot but can anyone see what iam doing wrong iam not that familiar with jqueryparsejson so any advice would be great as i think iam going madif i am being vague or not explaining myself well please say so i have also put this on fiddle please note this is a working progress so some items may be missing or need to be developed or i may have other bugs but i hope not,"['javascript', 'jquery']" +279946,eclipse syntax highlighting for html files with currently i am working on a project with handlebars js template engine and i am using eclipse for developmentthe problem is that eclipse does not offer syntax highlighting for my handlebarstemplates my templates are enclosed in tags syntax highlighting in works as expected screenshot is it possible that eclipse also highlights this code at the best with html syntax coloring,"['javascript', 'html']" +279971,whats the restful way to check whether the client can access a resource i am trying to determine the best practice in a rest api for determining whether the client can access a particular resource two quick example scenariosa phone directory lookup service client looks up a phone number by accessing egget httphostdirectoryentriesnumbers12345 where 12345 is the phone number to try and find in the directory if it exists it would return information like the name and address of the person whose phone number it isa video format shifting service client submits a video in one format to egpost httphostvideos and receives a video guid which has been generated by the server for this video client then checks egget httphostvideosguidflv to get the video converted into the flv format if the converted version existsyoull notice that in both cases above i did not mention what should happen if the resource being checked for does not exist that is my question here i have read in various other places that the proper restful way for the client to check whether the resource exists here is to call head or maybe get on the resource and if the resource does not exist it should expect a 404 response this would be fine except that a 404 response is widely considered an error the http11 spec states that the 4xx class of status code is intended for cases in which the client seems to have erred but wait in these examples the client has surely not erred it expects that it may get back a 404 or others maybe a 403 if it is not authorized to access this resource and it has made no mistake whatsoever in requesting the resource the 404 is not intended to indicate an error condition it is merely information this does not existand browsers behave as the http spec suggests as if the 404 response is a genuine error both google chrome and firebugs console spew out a big red 404 not found error message into the javascript console each time a 404 is received by an xhr request regardless of whether it was handled by an error handler or not and there is no way to thisable it this is not a problem for the user as they do not see the console but as a developer i do not want to see a bunch of 404 or 403 etc errors in my js console when i know perfectly well that they are not errors but information being handled by my javascript code it is line noise in the second example i gave it is line noise to the extreme because the client is likely to be polling the server for that flv as it may take a while to compile and the client wants to thisplay not compiled yet until it gets a non404 there may be a 404 error appearing in the js console every second or twoso is this the best or most proper way we have with rest to check for the existence of a resource how do we get around the line noise in the js console it may well be suggested that in my second example a different uri could be queried to check the status of the compilation likeget httphostvideosguidcompilestatus however this seems to violate the rest principle a little to me youre not using http to its full and paying attention to the http headers but instead creating your own protocol whereby you return information in the body telling you what you want to know instead and always return an http 200 to shut the browser up this was a major criticism of soap it tries to get around http rather than use it to its full by this principle why does one ever need to return a 404 status code you could always return a 200 of course the 200 is indicating that the a resources status information is available and the status information tells you what you really wanted to know the resource was not found surely the restful way should be to return a 404 status codethis mechanism seems even more contrived if we apply it to the first of my above examples the client would perhaps queryget httphostdirectoryentriesnumberstatuses12345 and of course receive a 200 the number 12345s status information exists and tells you that the number is not found in the directory this would mean that any number queried would be 200 ok even though it may not exist does this seem like a good rest interfaceam i missing something is there a better way to determine whether a resource exists restfully or should http perhaps be updated to indicate that non2xx status codes should not necessarily be considered errors and are just information should browsers be able to be configured so that they do not always output non2xx status responses as errors in the js consoleps if you read this far thanks,['javascript'] +280003,dsr is on do not send dtr on android in the logcat i am seeing this a lot dsr is on do not send dtr on android i have tethered my phone wirelessly to my mac because my internet is down i have it in dev mode also so what does that mean i have seen something about bluetooth but it is off thoughdsr dtr,['android'] +280011,check if socket is listening in c while iterating through socket file descriptors how can i check if one of them is from a passive socket listening for connections,['c'] +280017,c calling a base class constructor with a computed argument this simple example demonstrates the c syntax for calling base class constructors as far as i understand it as a c learnerclass baseclass protected int ipublic baseclassint x i x class derivedclass public baseclass int jpublic derivedclassint x int y baseclassy j x here the base class constructor can take named arguments to the derived class constructor as input now what if i want to call baseclass constructor with an input value that is not a direct input to derivedclass basically i would like to do some multiline work with x and y within derivedclass then pass a calculated value to baseclass can this be done with constructors should this be done with some kind of initializer method instead,['c++'] +280059,check volume button usage when screen is off for this question i am going to quote another user who got no response to their questioni have written an andoid app that uses the hardware volume buttons for another purposeit works fine if the app is running and visible but when i turn the screen off or let it time out the button clicks do not get into my handlersdoes anyone know if there is a way to detect these button clicks when the screen is off source av695s questioni am working on an app myself that makes use of the volume buttons but as this user also noted the normal behavior of checking buttons with onkeypress stops working once the screen is off this is because the activity gets paused on screen offis there a way to keep the activity running while the screen is off or check for the usage of the volume buttons when the screen is off i tried using a service for this before but it is impossible to check for the volume keys like that as noted by commonsware,['android'] +280076,how to detect region of large of white pixels using opencv i want to detect logo inside image in order to remove it i have an idea that is to look for objects which have the big number of pixels then remove another idea is to loop through all the white pixelsi have inverted my image and look for pixels which forms a large region and then remove this region is there is any algorithm better that this one also which methods in opencv will help me to detect object of large pixels number,['c++'] +280086,understanding pythons callbyobject style of passing function arguments i am not sure i understand the concept of pythons call by object style of passing function arguments explained here there do not seem to be enough examples to clarify this concept well or my googlefu is probably weak di wrote this little contrived python program to try to understand this conceptdef foo itnumber ittuple itlist itdict itnumber 1 print iditnumber itnumber print idittuple ittuple itlistappend34 print iditlist itlist itdictmary 23 print iditdict itdict initialize a number a tuple a list and a dictionarytnumber 1print id tnumber tnumber ttuple 1 2 3print id ttuple ttupletlist 1 2 3print id tlist tlisttdict tel jack 4098 sape 4139print invoke a function and test itfootnumber ttuple tlist tdictprint test behaviour after the function call is overprint idtnumber tnumber print idttuple ttupleprint idtlist tlistprint idtdict tdictthe output of the program is 146739376 13075201660 1 2 33075103916 1 2 33075193004 sape 4139 jack 4098146739364 23075201660 1 2 33075103916 1 2 3 343075193004 sape 4139 jack 4098 mary 23146739376 13075201660 1 2 33075103916 1 2 3 343075193004 sape 4139 jack 4098 mary 23as you can see except for the integer that was passed the object ids which as i understand refers to memeory location remain unchanged so in the case of the integer it was effectively passed by value and the other data structure were effectively passed by reference i tried changing the list the number and the dictionary to just test if the datastructures were changed in place the number was not bu the list and thedictionary were i use the word effectively above since the callbyobject style of argument passing seems to behave both ways depending on the datastructure passed in the above codefor more complicated data structures say numpy arrays etc is there any quick rule of thumb torecognize which arguments will be passed by reference and which ones passed by value,['python'] +280115,unique key vs unique index on sql server 2008 i have a table called countries and i define the country name column to be unique by creating a aindexkeya of type aunique keya on sql server 2008 r2 but i have the following questionswill creating aindexkeya of type aunique keya automatically create a nonclustered index on this columnif i change the type from being aunique keya to index and i keep the isunique value to be yes then will there be any differences so why there are two options aunique keya and index i think the two are the same,['sql'] +280122,why is console noting that i changed my prototype before i do i am learning about javascript prototypes and made a fiddle with this javascriptfunction animalname sound thisname name thissound soundvar dog new animaldog barkconsoledebugdog proto animalprototypemakesound function consolelogthissoundinterestingly aconsoledebugdog proto reveals that makesound is a method of the prototype of the animal classhowever i add that method to the prototype in a later line why is console noting that the prototype has a makesound method if the control flow had not gotten to it yet in my code,['javascript'] +280142,read the next word in a file in python i am looking for some words in a file in python after i find each word i need to read the next two words from the file i have looked for some solution but i could not find reading just the next words offsetfile file pointer searchterms list of wordsfor line in offsetfile for word in searchterms if word in line here get the next two terms after the wordthank you for your timeupdate only the first appearance is necessary actually only one appearance of the word is possible in this casefileaccept 42 2820 access 183 3145 accid 1 4589 algebra 153 16272 algem 4 17439 algol 202 6530word access algebrasearching the file when i encounter access and algebra i need the values of 183 3145 and 153 16272 respectively,['python'] +280149,what is the new pattern for releasing self with automatic reference counting using the nsobject method idawakeafterusingcodernscoder decoder as an example the documentation saysallows an object after being decoded to substitute another object for itself for example an object that represents a font might upon being decoded release itself and return an existing object having the same font description as itself in this way redundant objects can be eliminatednormally you would doself releasereturn substitutedobjectwith arc you have to leave this line out wouldnt this leak or should i just trust the nscoder object to release the original object for me if so why would you have to explicitly release self with nonarc code in the first placei do not think self nil is correct in light of what the compiler documentation says about self,['objective-c'] +280175,android opening sms activity with multiple recipients specified i am trying to start the phone set sms provider by starting an intent the code i am using below is what i am using to start the intent intent sendintent new intentintentaction view stringbuilder uri new stringbuildersms for int i 0 i contactssize i uriappendcontactsgetigetnumber uriappend sendintentputextrasms body sendintentsettypevndandroiddirmmssms sendintentsetdatauriparseuritostring startactivitysendintenti specifically want to use this method rather than sending the message myself so the user can use their preferred sms client i can get it going with just one number but not multiple i cannot find an example anywhere with multiple recipients is this possiblethank you in advance,['android'] +280181,javascript keydown event up arrow key preventing further arrowkey keydown events answered keyboard ghosting i have found a lot of related questions here and elsewhere but have not found this one specificallyi am trying to listen for keydown events for the arrow keys 3740 however when using the arrow keys in a certain order subsequent arrow do not generate keydown eventsexampleat that page click in the type here boxpress and hold right arrow key table updates to keycode 39while continuing to hold right arrow key press and hold up arrow key table updates to 38while continuing to hold right and up arrow keys press and holdleft arrow key table does not updatehowever if i do the same thing but using down arrow key instead of up arrow key then it works as expectedadditionally if i use the keypad instead of the arrow keys it works as expectedi am preventing the normal operation of the keydown event both by returning false in the event listener and by calling preventdefault but the behavior persistsi thought it might be my keyboard but it happens on a laptop as well as a friends machinedoes anyone have any insight as to what is going or some good ideas on workaroundseditheres an example of what i mean i realize this may not work on all browsers but i just threw this together on my laptop to demonstrate what is happening for me on chrome on w7 and also chrome safari on mac os 1068htmlbodyscriptvar keysdown addeventlistenerkeydown functione keysdownekeycode true documentgetelementbyidlatestkeydownvalueekeycode falseaddeventlistenerkeyupfunctione delete keysdownekeycode falsevar loop function documentgetelementbyidupinputvaluekeysdown38 documentgetelementbyiddowninputvaluekeysdown40 documentgetelementbyidleftinputvaluekeysdown37 documentgetelementbyidrightinputvaluekeysdown39setintervalloop1scriptup input idupinput typetext size10br down input iddowninput typetext size10br left input idleftinput typetext size10br right input idrightinput typetext size10br recent keydown input idlatestkeydown typetext size10br bodyhtmlagain the issue isif i hold down a then s then d then f then g you can see the recent keydown updating every single time i begin to hold a new keyhowever if i hold down right arrow then up arrow then left arrow i do not see recent keydown updating for the left arrow key,"['javascript', 'html']" +280192,google maps api not placing marker at fine location my code is supposed to find out the users location and place a marker on the map upon entering the application my location value always equals null and never receives a valueif location null lat int locationgetlatitude 1e6 longi int locationgetlongitude 1e6 geopoint ourlocation new geopointlat longi overlayitem overlayitem new overlayitemourlocation ayo whats good yo custompinpoint custom new custompinpointd campusmapthis custominsertpinpointoverlayitem overlaylistaddcustom else toastmaketextcampusmapthis could not get provider toastlength shortshow,"['java', 'android']" +280201,how do i make xpath search case insensitive i am currently making a xpath search i have got the the search working but i need to make it case insensitive the xml file i am using is 10 which from my research means i have got to use some thing called a translate function but i am unsure of how to do thishere is my search file holidaydoc simplexml load fileholidaysxml fetch data from formtxtsearch gettxtsearchqry channelitemcontainstxtsearchholidays holidaydocxpathqry do the xpath query now loop through all the studentsecho showing title search results for txtsearchforeach holidays as holiday echo pa hrefholidaylinkholidaytitleap psmallholidaypubdatesmallpany help would be greatly appreciated thanks,['php'] +280209,jpa persist many to many i have a pretty standard scenario whereby i have a table of users with user id as the pk and a table of roles with role id as the pk the two tables are related via a many to many relationship ie users can have many roles and a role can be applied to many users and subsequently i have a joining table called users has roles the only two columns in users has roles are users user id and roles role idi have generated the entity classes see below and i have no problem persisting data to the users and roles tables but i have failed miserably persist anything to the users has roles joining table so currently none of my users are being assigned a role before i go crazy could somebody put me out of my misery and show me how i should go about adding a users user id with a corresponding roles role id to the users has roles table so my users can have rolesmy usersjava entity classentitytablename usersxmlrootelementnamedqueriesnamedqueryname usersfindall query select you from users unamedqueryname usersfindbyuserid query select you from users you where uuserid useridnamedqueryname usersfindbyusername query select you from users you where uusername usernamenamedqueryname usersfindbypassword query select you from users you where upassword passwordpublic class users implements serializable private static final long serialversionuid 1lidbasicoptional falsenotnullsizemin 1 max 60columnname user idprivate string useridbasicoptional falsenotnullpatternregexpaz09 az09 az09az09az09az09az09az09 messageinvalid emailsizemin 1 max 45columnname usernameprivate string usernamebasicoptional falsenotnullsizemin 1 max 120columnname passwordprivate string passwordjointablename users has roles joincolumns joincolumnname users user id referencedcolumnname user id inversejoincolumns joincolumnname roles role id referencedcolumnname role idmanytomanyprivate collectionroles rolescollectiononetomanycascade cascadetypeall mappedby usersuseridprivate collectionuseraccount useraccountcollectiononetomanycascade cascadetypeall mappedby usersuseridprivate collectionuserdetails userdetailscollectionall the getter and setter methods etcmy rolesjava entity classentitytablename rolesxmlrootelementnamedqueriesnamedqueryname rolesfindall query select r from roles rnamedqueryname rolesfindbyroleid query select r from roles r where rroleid roleidnamedqueryname rolesfindbyrolename query select r from roles r where rrolename rolenamenamedqueryname rolesfindbyrolepermission query select r from roles r where rrolepermission rolepermissionnamedqueryname rolesfindbyroledescription query select r from roles r where rroledescription roledescriptionpublic class roles implements serializable private static final long serialversionuid 1lidbasicoptional falsenotnullsizemin 1 max 60columnname role idprivate string roleidbasicoptional falsenotnullsizemin 1 max 45columnname role nameprivate string rolenamebasicoptional falsenotnullsizemin 1 max 45columnname role permissionprivate string rolepermissionsizemax 45columnname role descriptionprivate string roledescriptionmanytomanymappedby rolescollectionprivate collectionusers userscollectionall the getter and setter methods etcthanks update new usersusers currentuser new userscurrentusersetuseriduseridcurrentusersetusernameemailcurrentusersetpasswordpasswordgetusersfacadecreatecurrentuser,"['java', 'mysql']" +280217,hibernate unknownserviceexception unknown service requested as transaction completed i have a simple class which starts 3 threads and saves a new object in each thread but i am getting exception which i cannot understand can anyone help me understand why the exceptionpackage testimport javautildateimport orghibernatesessionimport domaineventimport utilhibernateutilpublic class eventbeantest public static void mainstring args event e1 new event e1settitle1 e1setdatenew date event e2 new event e2settitle2 e2setdatenew date event e3 new event e3settitle3 e3setdatenew date thread t1 new threadnew eventrunnablee1 thread t2 new threadnew eventrunnablee2 thread t3 new threadnew eventrunnablee3 t1setnameevent 1 t2setnameevent 2 t3setnameevent 3 t1start t2start t3start class eventrunnable implements runnable private event event public eventrunnableevent event thisevent event public void run systemoutprintlnstarting thread threadcurrentthreadgetname session session hibernateutilgetsessionfactorygetcurrentsession sessionbegintransaction sessionsaveorupdateevent sessiongettransactioncommit hibernateutilgetsessionfactoryclose systemoutprintlnfinishing thread threadcurrentthreadgetname and this is the relevant part of the log file showing the exceptionhibernate select maxevent id from testeventshibernate insert into testevents event date title event id values hibernate insert into testevents event date title event id values hibernate insert into testevents event date title event id values apr 22 2012 24655 pm orghibernateservicejdbcconnectionsinternaldrivermanagerconnectionproviderimpl stopinfo h030 cleaning up connection pool jdbcmysqllocalhost3306testfinishing thread event 3apr 22 2012 24655 pm orghibernateenginetransactioninternaljdbcjdbctransaction afteraftercompletioninfo h0425 could not close session swallowing exceptionorghibernateserviceunknownserviceexception unknown service requested orghibernatestatspistatisticsimplementor as transaction completedexception in thread event 2 orghibernateserviceunknownserviceexception unknown service requested orghibernatestatspistatisticsimplementor at orghibernateserviceinternalabstractserviceregistryimplgetserviceabstractserviceregistryimpljava126 at orghibernateinternalsessionfactoryimplgetstatisticsimplementorsessionfactoryimpljava1708 at orghibernateinternalsessionfactoryimplgetstatisticssessionfactoryimpljava1704 at orghibernateenginetransactioninternaltransactioncoordinatorimplaftertransactiontransactioncoordinatorimpljava140 at orghibernateenginetransactioninternaljdbcjdbctransactionaftertransactioncompletionjdbctransactionjava138 at orghibernateenginetransactionspiabstracttransactionimplcommitabstracttransactionimpljava184 at testeventrunnableruneventbeantestjava60 at javalangthreadrunthreadjava722apr 22 2012 24655 pm orghibernateenginetransactioninternaljdbcjdbctransaction afteraftercompletioninfo h0425 could not close session swallowing exceptionorghibernateserviceunknownserviceexception unknown service requested orghibernatestatspistatisticsimplementor as transaction completedexception in thread event 1 orghibernateserviceunknownserviceexception unknown service requested orghibernatestatspistatisticsimplementor at orghibernateserviceinternalabstractserviceregistryimplgetserviceabstractserviceregistryimpljava126 at orghibernateinternalsessionfactoryimplgetstatisticsimplementorsessionfactoryimpljava1708 at orghibernateinternalsessionfactoryimplgetstatisticssessionfactoryimpljava1704 at orghibernateenginetransactioninternaltransactioncoordinatorimplaftertransactiontransactioncoordinatorimpljava140 at orghibernateenginetransactioninternaljdbcjdbctransactionaftertransactioncompletionjdbctransactionjava138 at orghibernateenginetransactionspiabstracttransactionimplcommitabstracttransactionimpljava184 at testeventrunnableruneventbeantestjava60 at javalangthreadrunthreadjava722edit 1xml version10 encodingutf8sessionfactory database connection settings property nameconnectiondriver classcommysqljdbcdriverproperty property nameconnectionurljdbcmysqllocalhost3306testproperty property nameconnectionusernamevishnuproperty property nameconnectionpasswordcon02305property jdbc connection pool use the builtin property nameconnectionpool size1property sql dialect property namehibernatedialectorghibernatedialectmysqldialectproperty enable hibernates automatic session context management property namecurrent session context classthreadproperty thisable the secondlevel cache property namecacheprovider classorghibernatecacheinternalnocacheproviderproperty echo all executed sql to stdout property nameshow sqltrueproperty drop and recreate the database schema on startup property namehbm2ddlautoupdateproperty property namedefault schematestproperty property nameshow sqltrueproperty mapping resourcedomaineventhbmxmlsessionfactory,['java'] +280221,how can i add transparency to a c form while keeping controls visible update i took a break from messing with the transparency stuff for a few days i started messing with it again tonight i got a new result using hans passants solution passants solution does solve the issue of the transparent background gradient however i am still running into the problem with the transparent colors in my icon blending with the forms backcolor you can see the fuchsia around various parts of the icon in the above imageoriginal contenti have been going at this for several hours now and i have not had much luck i have messed with controlregion formtransparencykey formopacity and a couple other random things with some funky effectslately i have been trying to customize my desktop and decided to mess with application docks after seeing what the mac dock and a few thirdparty windows implementations had to offer i decided i wanted to build my owneventually i want to move on to using the win32 api for now i just want to get something working using as much c and net framework capabilities as possiblethere are a few things i want to be able to do in this applicationthisplay a formmenu with a gradient backgroundallow the formmenu to have transparency while keeping icons opaquethisplay icons that contain transparent backgroundsthe menu and icons should be able to receive mouserelated events hover leave click dragover dragdrop and a few othersthis is the effect i am shooting forthis image shows the visual effects i am trying to achieve this was a skin i made for a program called rainmeter the image shows notepad behind the skin with a few of the skins files open in the editor the menu is transparent but the icons remain opaquemy approachusing a form to act as the menu seemed like a logical first choice to me i have a basic understanding of events i am not quite sure how to create my own click events so a form would make working with events a tad easier i considered a few options for the icons i decided i would use pictureboxes for the icons since they can hold images and receive eventsonce i finished the code for all the structural logic of my menu i started playing around with it to try to get the visual effect i wanted formopacity affected the transparency of everything on the form since i want the icons to be fully opaque i left this property alone i tried setting the backcolor to colortransparent but that gives an error i played around with a few combinationsi drew the gradient with a drawing2dlineargradientbrush into a bitmap this bitmap was then placed as the formbackgroundimage or as a pictureboximage if used the picturebox was sized to cover the entire form and sent to the backi noticed that some of the formbackgroundcolor would be mixed in with the outlines of my icons the icons have transparency along the edges for a smoother appearance since the icons are picking up the forms backgroundcolor this makes me think that the pictureboxes are creating new images when the icons are loaded into the form the semitransparent portions of the image are then merged with the forms backgroundcolor when they should merge with whatever colors are behind the formin this image you can see the fuchsia existing in the icons even though the forms fuchsia color is now completely transparent i forgot to point out that the same green to yellow gradient with an alpha value of 150 was used in every case in the images where the gradient does not look green it is because the transparent colors are blending with the fuchsia backgroundi am not really sure what to do from here i feel like i could get what i want if i could somehow make the form alone completely transparent i was also thinking i may have better luck just drawing the icons instead of using pictureboxes the problem then would be setting up the icons to receive mouse events i have never made my own events and i think it would involved some win32 api callsis there something else i can do with the pictureboxes to get the effect i want whichever the case i am open to any ideas or suggestions for the overall effect i am trying to achieve,['c#'] +280247,jsonexception value of type javalangstring cannot be converted to jsonobject i have a json file with 2 jsonarrays in itone array for routes and one array for sightsa route should consist of several sights where the user gets navigated tounfortunately i am getting the errorjsonexception value of type javalangstring cannot be converted to jsonobjecthere are my variables and the code that parses the jsonfileprivate inputstream is nullprivate string json private jsonobject jobj nulltry bufferedreader reader new bufferedreadernew inputstreamreaderis iso88591 8 stringbuilder sb new stringbuilder string line null while line readerreadline null sbappendline n isclose hier habe ich das jsonfile als string json sbtostring logijson parser json catch exception e logebuffer error error converting result etostring try parse the string to a json objecttry jobj new jsonobjectjson catch jsonexception e logejson parser error parsing data etostring return json stringreturn jobjlogijson parser jsonshows me that at the beginning of the generated string there is a strange sign but the error happens heretry jobj new jsonobjectjson catch jsonexception e logejson parser error parsing data etostring0422 140105043 ejson parser5868 error parsing data orgjsonjsonexception value strange sign here of type javalangstring cannot be converted to jsonobjectanybody has a clue on how to get rid of these signs in order to create the jsonobject,['android'] +280269,trouble updating new column after adding it given the following sqlif exists select from syscolumns where name newfieldname and object id object iddbomytablename return add newfieldname column to part of the summer 2012 release cyclealter table dbomytablename add newfieldname smallint not null constraint df mytablename newfieldname default 2update mytablename set newfieldname 1 where name findme update one specific valueproduces the following error messagemsg 207 level 16 state 1 line 10 invalid column name newfieldnamei am sure i am missing something basic but trying to put go after the alter makes the update run everytime and i do not want to do thathow can i structure this statement so that it will check to see if the column exists and if it does not add it and then set the values as stated in my update statements,['sql'] +280289,how to arrange many elements side by side with no wrap there are three div elements side by side in a container div with smaller width than children total width here you can find the fiddle of the case i want to make container div scroll horizontally in order to show other childrenhow can i arrange children not to wrap inside container divit scroll vertically now i want it to scroll horizontally,"['html', 'css']" +280290,convert int into arraylist what is best way recopying int array elements into arraylisti need to do this fast so what would be the fastest way,['java'] +280296,how does except method work in linq i have the classesclass someclass public string namegetset public int someintgetsetclass somecomparison iequalitycomparersomeclass public bool equalssomeclass s someclass d return sname dname public int gethashcodesomeclass a return anamegethashcode 251 i also have two large listsomeclass called list1 and list2before i used to have var q from a in list1 from b in list2 where aname bname select atolistand that took about 1 minute to execute now i havevar q list1exceptlist2new somecomparisontolistand that takes less than 1 second i will like to understand what does the except method do does the method creates a hash table of each list and then perform the same comparison if i will be performing a lot of this comparisons should i create a hashtable instead editnow instead of having lists i have two hashsetsomeclass called hashset1 and hashset2when i do var q from a in hashset1 form b in hashset2 where aname bname select atolistthat still takes a long time what am i doing wrong,['c#'] +280341,google area chart axis and setting full width i am trying to style and add another 2 xaxis to a google area chart a and b in the image for example the a axis should be set to 900 and b 700also trying to extend the chart to the full width of the containing div 960px but my solution seems to do nothingthis is the desired effectcurrent jsgoogleloadvisualization 1 packagescorechart googlesetonloadcallbackdrawchart function drawchart var data googlevisualizationarraytodatatable year sales expenses november 10 400 december 1170 460 january 660 1120 february 690 1120 march 780 1120 april 820 1120 may 660 1120 june 1030 540 var options title backgroundcolor none width960 legend position none haxis title year titletextstyle color grey var chart new googlevisualizationareachartdocumentgetelementbyidchart div chartdrawdata options,['javascript'] +280348,python how do i capture a variable declared in a non global ancestral outer scope givendef f x 0 def g h def h x 1 printx g ftraceback most recent call last file stdin line 1 in module file stdin line 8 in f file stdin line 4 in g file stdin line 6 in hunboundlocalerror local variable x referenced before assignmenthow can i make h see the x variablethankseditshould have mentioned it earlier i am using python 273,['python'] +280349,bitmap too large to be uploaded into a texture i am loading a bitmap into an imageview and seeing this error i gather this limit relates to a size limit for opengl hardware textures 2048x2048 the image i need to load is a pinchzoom image of about 40 pixels highi have tried turning off hardware acceleration in the manifest but no joy application androidhardwareacceleratedfalse is it possible to load an image larger than 2048 pixels into an imageview,['android'] +280351,python oauth2 login with google i have been searching for 2 days for an answer but nothing came upi am trying to make integrate oauth2 for login with google on django the code i have throws an exception the token is invalidthis happensresp content clientrequestaccess token url post if respstatus 200 print content raise exceptioninvalid response from googlecontentin google authenticateplease help memy code def google loginrequest scope request token url scope authorize url authenticate url response type code redirect uri scope oauth key settingsgoogle key oauth secret settingsgoogle secret consumer oauthconsumeroauth key oauth secret client oauthclientconsumer step 1 get a request token this is a temporary token that is used for having the user authorize an access token and to sign the request to obtain said access token resp content clientrequestrequest token url post request token dicturlparseparse qslcontent if respstatus 200 raise exceptioninvalid response from google step 2 store the request token in a session for later use requestsessionrequest token dictcgiparse qslcontent step 3 redirect the user to the authentication url url soauth tokensclient idsresponse typesredirect urisscopes authenticate url requestsessionrequest tokenoauth token oauth keyresponse typeredirect uriscope return httpresponseredirecturldef google authenticaterequest access token url oauth key settingsgoogle key oauth secret settingsgoogle secret consumer oauthconsumeroauth key oauth secret step 1 use the request token in the session to build a new client token oauthtokenrequestsessionrequest tokenoauth token requestsessionrequest tokenoauth token secret if oauth verifier in requestget tokenset verifierrequestgetoauth verifier client oauthclientconsumer token step 2 request the authorized access token from google resp content clientrequestaccess token url post if respstatus 200 print content raise exceptioninvalid response from googlecontent access token dictcgiparse qslcontent step 3 lookup the user or create them if they do not exist try user userobjectsgetusernameaccess tokenscreen name except userdoesnotexist when creating the user i just use their screen for their email and the oauth token secret for their password these two things will likely never be used alternatively you can prompt them for their email here either way the password should never be used user userobjectscreate useraccess tokenscreen name access tokenscreen name access tokenoauth token secret save our permanent token and secret for later profile profile profileuser user profileoauth token access tokenoauth token profileoauth secret access tokenoauth token secret profilesave authenticate the user and log them in using djangos prebuilt functions for these things user authenticateusernameaccess tokenscreen name passwordaccess tokenoauth token secret loginrequest user return httpresponseredirect,['python'] +280354,parsing html with nokogiri in ruby with this html codediv classone divdiv classone divdiv classone divdiv classone divhow can i select with nokogiri the second or third div whose class is one,['ruby'] +280363,java jagged array our homework assignment asks us to use a jagged array to store the values of a two dimensional boolean matrix is there a built in java class for the jagged array or am i going to have to manually create it with an array of arraylists,['java'] +280405,php regex check if two strings share two common characters i am just getting to know regular expressions but after doing quite a bit of reading and learning quite a lot i still have not been able to figure out a good solution to this problemlet me be clear i understand that this particular problem might be better solved not using regular expressions but for the sake of brevity let me just say that i need to use regular expressions trust me i know there are better ways to solve thisheres the problem i am given a big file each line of which is exactly 4 characters longthis is a regex that defines valid linesabcdefghm in english each line has either a or b at position 0 either c or d at position 1 either e or f at position 2 and either g or h at position 3 i can assume that each line will be exactly 4 characters longwhat i am trying to do is given one of those lines match all other lines that contain 2 or more common charactersthe below example assumes the following line is always a valid format bigfileoflinestxt contains only valid linesexample matches all other lines in string that share 2 or more characters in common with linefunction findmatchinglinesline subject regex magic regex i am looking for here matchinglines array preg match allregex subject matchinglines return matchinglines example usagefilecontents file get contentsbigfileoflinestxtmatchinglines findmatchinglinesacfg filecontents desired return value note this is an example set there could be more or less than this bceg adfg bcfg bdfgone way i know that will work is to have a regex like the following the following regex would only work for acfgac2cf2fgafa2gcgmthis works alright performance is acceptable what bothers me about it though is that i have to generate this based off of line where i would rather have it be ignorant of what the specific parameter is also this solution does not scale terrible well if later the code is modified to match say 3 or more characters or if the size of each line grows from 4 to 16it just feels like there is something remarkably simple that i am overlooking also seems like this could be a duplicate question but none of the other questions i have looked at really seem to address this particular problemthanks in advanceupdateit seems that the norm with regex answers is for so users to simply post a regular expression and say this should work for youi think that is kind of a halfway answer i really want to understand the regular expression so if you can include in your answer a thorough within reason explanation of why that regular expressiona worksb is the most efficient i feel there are a sufficient number of assumptions that can be made about the subject string that a fair amount of optimization can be doneof course if you give an answer that works and nobody else posts the answer with a solution i will mark it as the answer update 2thank you all for the great responses a lot of helpful information and a lot of you had valid solutions i chose the answer i did because after running performance tests it was the best solution averaging equal runtimes with the other solutionsthe reasons i favor this answerthe regular expression given provides excellent scalability for longer linesthe regular expression looks a lot cleaner and is easier for mere mortals such as myself to interprethowever a lot of credit goes to the below answers as well for being very thorough in explaining why their solution is the best if youve come across this question because it is something youre trying to figure out please give them all a read helped me tremendously,['php'] +280411,make a messagebox thisplay a variable i want a messagebox to thisplay an int variable can anybody help,['c#'] +280435,sample code for java backend in google appengine when i read doc of backend its tells how to configure etcwhat what the code of a backend looks likeis it just a servlet with extra entries in backendxml filei tried to create a servlet with class comxyzmybackend and servlet name mybackendpublic mybackend extends httpservlet public void dogethttpservletrequest req httpservletresponse resp whiletrue do something try threadsleepxyz catchexception ex then i added following lines in backendxmlbackends backend namemybackend classb1class options dynamictruedynamic options backendbackendsis that correctenoughif yeshow to i start my backend nowit it by calling the backend servlet urlhttplocalhostmybackenurl,['java'] +280437,sql conditional not null constraint i am curious to know is it possible to create a conditional not null constraint in sql in otherwords is it possible to create a constraint such that a column b can be null as long column a contains lets say new but if the contents of column a changes to something else then column b is no longer allowed to be null and to extend on that it is then possible to make it so that column b must be null or empty as long as column a says newthanks all d,['sql'] +280443,opening a link in a new tab i have created a website for a project i am doingin the content of the website there are some links for external web pages that can be visitedin the mean time when the user clicks on one of the links he will be taken to the specified link and he will not be on the current page anymorewhat i wanted to do is have the specified website in the link clicked appear in a new tab when the user clicks on the link this way the user stays on the current page he is one and also can view the other page on the new tabi have looked on the internet and found this which seemed to be usefulfunction externallinks var anchors documentgetelementsbytagnamea for var i0 ianchorslength i var anchor anchorsi ifanchorgetattributehref anchortarget blank windowonload externallinksthe problem i am facing is that the navbar of my website contains anchor tags so now if the user clicks on the links on the navbar it will open a new tab i want this to happen only if the user clicks on a link in the content of my website so if the user clicks on a link in the navbar it should not open a new tab and should just take him to the specified destinationi have tried adding a class to all the links in the content and use getelementbyclassname but it still did not workanyone can help me with this,"['javascript', 'html']" +280444,resetting storyboard on logout i am building an ios 51 web client app that uses a storyboard one of my actions is logout during which i want to reset my root view to the initial view created by the root view of the storyboard when you log in some view items are removed or added based on who you are when you log out i want to reset them to their default values which i have specified in the storyboardi realize that i could programmatically resetreadd all of the elements but then what good is the storyboard i figure there is got to be a way to get back to square one by reloading the view file right,['ios'] +280458,uitextfield clearbuttonmode color can i change the color of the clearbuttonmode on a textfieldthetextfieldclearbuttonmode uitextfieldviewmodewhileeditingshows an x that is grey dark color to delete the textfieldbut can i show this button with white colorthanks,['ios'] +280461,programmatically editing less css code with jquerylike selector syntax it is possible to use libraries in lessjs to dynamically regenerate css from less files within the browser if there was an easy way to modify less code this would be an extremely powerful method of dynamically updating a sites cssimagine you had a colour that was used 100 times throughout a large site if you wanted to change that color dynamically just using javascript you would need to update every bit of css that had that colour perhaps 50 lines of codewith what i am imagining all you would need to write is something like thismaincolourvaluef04i am thinking of having a go at this myself but it sounds like a huge project and i wonder if someone has already started something like thisedit to clarify ideally what i want to be able to do is take a string of less code programatically edit it perhaps using a jquerylike selector syntax and then spit it out as modified less ideally the code is in javascript but not necessarily client side the example i give above is one possible application but maybe not a good one where there might be better more common ways of achieving it,"['javascript', 'jquery', 'css']" +280484,how to get printf messages written in ndk application if i am defining such function in java file adds two integers returning their sum public native int add int v1 int v2 so i need to code in c file jniexport jint jnicall java com marakana nativelib add jnienv env jobject obj jint value1 jint value2 printfn this is log messge n return value1 value2then from where this printf will print it message in logcate i dont get ithow can i debug any ndk application by putting log messages,"['android', 'c']" +280493,constexpr static assert and inlining i previously asked about function overloading based on whether the arguments are constexpr i am trying to work around the thisappointing answer to that question to make a smarter assert function this is roughly what i am trying to doinline void smart assert bool condition if is constexpr condition static assert condition error else assert conditionbasically the idea is that a compiletime check is always better than a runtime check if it is possible to check at compile time however due to things like inlining and constant folding i cannot always know whether a compile time check is possible this means that there may be cases where assert condition compiles down to assertfalse and the code is just waiting for me to run it and execute that path before the i find out there is an errortherefore if there were some way to check whether the condition is a constexpr due to inlining or other optimizations i could call static assert when possible and fall back on a runtime assert otherwise fortunately gcc has the intrinsic builtin constant p exp which returns true if exp is a constexpr i do not know if other compilers have this intrinsic but i was hoping that this would solve my problem this is the code that i came up withinclude cassertundef is constexprif defined gnuc define is constexprexp builtin constant p expelse define is constexprexp falseendif todo add other compilersinline void smart assert bool const condition static assert is constexprcondition or condition error if is constexprcondition assert conditionundef is constexprthe static assert relies on the short circuit behavior of or if is constexpr is true then static assert can be used and the condition is true or condition which is the same as just condition if is constexpr is false then static assert cannot be used and the condition is false or condition which is just the same as true and the static assert is ignored if the static assert cannot be checked because condition is not a constexpr then i add a runtime assert to my code as a lastditch effort however this does not work thanks to not being able to use function arguments in a static assert even if the arguments are constexprin particular this is what happens if i try to compile with gcc maincppint main smart assert false return 0g maincpp stdc0x o0everything is fine compiles normally there is no inlining with no optimization so is constexpr is false and the static assert is ignored so i just get a runtime assert statement that fails howeverdaviddaviddesktop test g maincpp stdc0x o1in file included from maincpp10smart asserthpp in function avoid smart assertboolasmart asserthpp123 error nonconstant condition for static assertionsmart asserthpp123 error aconditiona is not a constant expressionas soon as i turn on any optimizations and thus potentially allow static assert to be triggered it fails because i cannot use function arguments in the static assert is there some way to work around this even if it means implementing my own static assert i feel my c projects could theoretically benefit quite a bit from a smarter assert statement that catches errors as early as possibleit does not seem like making smart assert a functionlike macro will solve the problem in the general case it will obviously make it work in this simple example but condition may have come from a function two levels up the call graph but still becomes known to the compiler as a constexpr due to inlining which runs into the same problem of using a function parameter in a static assert,['c++'] +280522,ide sublime2 how to find method definition i am using sublime 2 for ruby on rails programmingi need a ability to click a method name and jump to class where the method is defined there are many ide with similar capability,"['ruby-on-rails', 'ruby']" +280591,python interpreter shell with vim integration possible i love to use bpython but in ruby there is a gem called interactive editor that makes it possible to combine vim with the ruby shell which makes the development process much more comfortable a good introduction to interactive editor are there any tools like interactive editor for ruby available to combine the python shell with vim,['python'] +280595,variadic templates without function parameters can i use variadic templates without using the template parameters as function parameterswhen i use them it compilesinclude iostreamusing namespace stdtemplateclass firstvoid printfirst first cout 1 endltemplateclass first class restvoid printfirst first rest rest cout 1 endl printrestrestint main printintintint123but when i do not use them it does not compile and complains about an ambiguityinclude iostreamusing namespace stdtemplateclass firstvoid print cout 1 endltemplateclass first class restvoid print cout 1 endl printrestint main printintintintunfortunately the classes i want to give as template parameters are not instantiable they have static functions that are called inside of the template functionis there a way to do this,['c++'] +280629,why is my progressdialog listening on any key touch instead of backbutton to thismiss i have a progressdialog implemented like this show progress dialog while date is loading progressdialog progressdialogshowxyactivitythis getresourcesgetstringrstringprogress dialog please wait getresourcesgetstringrstringprogress dialog loading true progressdialogsetoncancellistenernew dialoginterfaceoncancellistener override public void oncanceldialoginterface dialog canceltrue logwlogtag loading cancelled via back button progressdialogsetcancelabletruethis progressdialog is implemented inside an asynctask preexecute so the canceltrue method stops the asynctask this all works finethe problem is that i can cancel the progressdialog with any random touch on my screen i wanna to thismiss the dialog only by pressing the backbutton please help me thank you guys,['android'] +280645,getattribute versus element object properties expressions like elementgetattributeid and elementid return the same thingwhich one should be used when we need attributes of an htmlelement objectis there any cross browser issue with these methods like getattribute and setattributeor any impact on performance between directly accessing object properties vs using these attribute methods,"['javascript', 'html']" +280651,convert double to int rounded down how to convert a double value to int doing the followingdouble if x 497542 convert to int x 4double if x 423544 convert to int x 4that is the answer is always rounding down,['java'] +280661,how can i thisable all touch events on all children of a viewgroup i have got a framelayout container containing many things including scrollview webview viewpageri would like to be able to trigger the onclick event on this container but it seems that some of scrollview webview and viewpager intercept the touch event because the onclick event is only triggered when i click on the parts of the container that do not have any of themhow can i thisable all touch events on the containers children in order to be able to trigger onclick anywhere in itupdatethe idea is to have something like the task manager in android 32 ie where the current visible screen of the app is shown as a reduced icon that can be clickedthanks,['android'] +280689,query on mongodb gridfs metadata java what i am trying to do is fetching a list of gridfs files by querying an field of the metadata for example i got a gridfs file document looking like id oid 4f95475f5ef4fb269dbac954 chunksize 262144 length 3077 md5 f24ea7ac05c5032f08808c6faabf413b filename file xyztxt contenttype null uploaddate date 20120423t121319606z aliases null metadata target field abcdefgand i want to query all files containing target field abcdefg i created my query as followsbasicdbobject query new basicdbobjectmetadata new basicdbobjecttarget field abcdefg gridfs object initialization skippedlistgridfsdbfile files gridfsfindquerythe list is allways empty otherwise querying the filename or uploaddate works perfectly is not it possible to get the gridfs files by nested attributes,['java'] +280712,how can i use underscorejs templates in conjunction with ejs they both use the same syntax for inserting variables for example if i want the following username in my underscore my main ejs breaks because it tries to replace username and no such variable exists in the main page,['javascript'] +280717,best attributes order in html for dom queries is there an order of attributes which make the dom queries faster for example in the beginningend of the elementwhen i traverse the dom up will it be better to put the attributes in the end and the other way around when i traverse the dom down,"['javascript', 'jquery', 'html']" +280718,cython installation does not find the pythonh file i wanted to install cython on my ubuntu 1204 and i entered in the terminal sudo easy install cythonin response i get the following errorsearching for cython reading reading reading best match cython 016 downloading processing cython016zip running cython016setuppy q bthist egg thistdir tmpeasy installvzj0lhcython016eggthisttmpbmjs3p compiling module cythonplexscanners compiling module cythonplexactions compiling module cythoncompilerlexicon compiling module cythoncompilerscanning compiling module cythoncompilerparsing compiling module cythoncompilervisitor compiling module cythoncompilerflowcontrol compiling module cythoncompilercode compiling module cythonruntimerefnanny warning no files found matching pyx under directory cythondebuggertests warning no files found matching pxd under directory cythondebuggertests warning no files found matching h under directory cythondebuggertests warning no files found matching pxd under directory cythonutility warning no files found matching h under directory cythonutility warning no files found matching cpp under directory cythonutility tmpeasy installvzj0lhcython016cythonplexscannersc420 fatal error pythonh el fitxer o directori no existeix compilation terminated error setup script exited with error command gcc failed with exit status 1 sorry for the catalan in here but el fitxer o directori no existeix means that the file does not exist i think that i perhaps miss something or i do not know does anyone else have the same problem or know how to install it correctly,['python'] +280725,property of a javascript class calculated from other properties in same class this is probably something pretty silly that i am missing but how do i get the property of a class to automatically recalculate based on the values of other properties in the same classegfunction test thisprop1 1 thisprop2 2 thisprop3 thisprop1 thisprop2tester new testalert testerprop1 expect 1alert testerprop2 expect 2alert testerprop3 expect 3testerprop1 1alert testerprop1 expect 2alert testerprop2 expect 2alert testerprop3 expect 4or do i need to have prop3 set to be calcprop3 and then include a function like sothiscalcprop3 function var calc thisprop1 thisprop2 return calc thanks all,['javascript'] +280727,i am getting a javascript alert in my project that i did not create threatening me this morning i woke up to a javascript alert on a project of mine that runs knockoutjs jquery and underscorejs it says i can run any javascript of my choice on your users browsers the only thirdparty javascript i am downloading is typekit and removing that does not make this go away i have searched my javascript and vendor javascript and this string does not come back up matching anythinghow would you troubleshoot this andor is this something that is known to occur,['javascript'] +280739,java converting binary to text i wrote this code for converting binary to text public static void mainstring args throws ioexception bufferedreader b new bufferedreadernew inputstreamreadersystemin systemoutprintlnenter a binary value string h breadline int k integerparseinth2 string out new charactercharktostring systemoutprintlnstring out and look at the output enter a binary value00110100110string whats the problem,['java'] +280748,how do i get a full stack trace instead of unexpected error while processing request in rails test environment when starting my rails server in test environment rails s e test something is rescuing exceptions and outputs instead unexpected error while processing request error here i get the backtrace in development modewho is it and how can i thisable that i need the full backtrace not just the error that was raisedi am using rails 323 ruby 193 rspec capybara capybarawebkit,['ruby-on-rails'] +280761,equivalent of mssql identity column in mysql what is the equivalent of mssql identity columns in mysql how would i create this table in mysqlcreate table lookupsgender genderid int identity11 not null gendername varchar32 not null,['mysql'] +280771,how to know how many event listeners there are on the page i am building a fairly large application in javascript it is a single page that can change different views all the views have their own variables events listeners elements etcwhen working with large collections and multiple events it is sometimes good to know what exactly is happening on the pagei know all the browsers have developer tools but sometimes it is hard to click trough all the elements etc and some options i can not findone thing i am interested in is to know how many events there currently listened for on the page this way i can confirm that i am not creating zombiesif the sollution is a developer tool please let me know where to look and what to do and most important which browser to choose,['javascript'] +280811,how could one refactor code involved in nested usings i have got some code that has an awful lot of duplication the problem comes from the fact that i am dealing with nested ithisposable types today i have something that looks likepublic void updatefromxmlguid innerid xdocument somexml using var a somefactorygeta uri using var b agetb id using var c bgetcinnerid var cwrapper new somewrapperc cwrapperupdatesomexml public bool getsomevaluebyidguid innerid using var a somefactorygeta uri using var b agetb id using var c bgetcinnerid return cgetsomevalue the whole nested using block is the same for each of these methods two are shown but there are about ten of them the only thing that is different is what happens when you get to the inner level of the using blocksone way i was thinking would be to do something along the lines ofpublic void updatefromxmlguid innerid xdocument somexml actoncinnerid c var cwrapper new somewrapperc cwrapperupdatesomexml public bool getsomevaluebyidguid innerid var result null actoncinnerid c result cgetsomevalue return resultprivate void actoncguid innerid actionthectype action using var a somefactorygeta uri using var b agetb id using var c bgetcinnerid actionc this works it is just kind of clunky to parse as a human does anyone have any other suggestions on how one could reduce the code duplication around nested using blocks like this if they werent ithisposable then one would likely just create a method to return the results of bgetcinnerid but that is not the case here,['c#'] +280818,curl error recv failure connection reset by peer php curl i am having this strange error curl error recv failure connection reset by peerthis is how it happens if i did not connect to the server and all of a sudden trying to connect to the server via curl in php i get the error when i run the curl script again the error thisappears and then works well the whole time if i leave the remote server idle for about 30mins or reboot the remote server and try to connect again i get the error again so it seems like the connection is idle and then all of sudden the server wakes up and then works and then sleeps againthis is how my curl script looksurl yiiaparamspdfurl body titleurlencodetitleclient urlyiiaparamspdfclienturlclient idyiiaparamspdfclientidcontenturlencodehtmlentitiescontent c curl init url body array client urlyiiaparamspdfclienturl client idyiiaparamspdfclientid titleurlencodetitle contenturlencodecontent foreachbody as keyvalue body str keyvalue rtrimbody str curl setopt c curlopt post true curl setopt c curlopt postfields body str curl setopt c curlopt returntransfer true curl setopt c curlopt connecttimeout 0 curl setopt c curlopt timeout 20 pdf curl exec c errorcode curl getinfoc curlinfo http code curlinfo curl getinfoc curlerror curl errorc curl close ci am totally out of ideas and solutions please help i will appreciate itif i verbose the output to see what happens using curl setopt c curlopt verbose truecurl setoptc curlopt stderr fp i get the following about to connect to 19641139168 port 80 0 trying 196x connected connected to 196x 196x port 80 0 post serverpdfgeneratepdf http11host 196xaccept contentlength 7115contenttype applicationxwformurlencodedexpect 100continue recv failure connection reset by peer closing connection 0012 202349 gmt server apache2215 centos xpoweredby php533 connection close transferencoding chunked contenttype texthtml charsetutf8 closing connection 0i have added in the following toe remove the default header and still no luck curl setopt c curlopt httpheader array expect accept contentlength 8414 contenttype applicationxwformurlencoded recv failure connection reset by peer closing connection 0 r apache2215 centos xpoweredby php533 connection close transferencoding chunked contenttype texthtml charsetutf8 closing connection 0,['php'] +280879,difference between jvms lookupswitch and tableswitch i have some difficulty to understand lookupswitch and tableswitch in java bytecodeif i understand well both lookupswitch and tableswitch correspond to the switch statement of java source why one java statement generates 2 different bytecodes jasmin documentation of eachlookupswitch tableswitch,['java'] +280887,php curl following redirects i am trying to be a bit sneeky and as part of a learning process try and improve my page scraping skillsone thing i have come across that i have yet to be able to solve is that certain sites will use an internal link which then redirects to an external linkwhat i want to do is modify some curl code to follow the redirects until they stop and then obtain the final resting place urlanyone recommend some code for mei have this at the moment but it is not following the redirects properly at the moment opts arraycurlopt url url curlopt returntransfer true curlopt header true curlopt followlocation true curl curl init curl setopt arraycurl opts str curl execcurl curl closecurl,['php'] +280916,php get microtime from date string i am trying to get the time passed between two datetime strings including millisecondsexamplepagetime strtotime20120423t16081490500rowtime strtotime20120423t16081610500timepassed rowtime pagetimeecho timepassed brbrwhat i want to see echoed is 12 but strtotime ignores the millisecond part of the string also apparently microtime does not let you give it a datestring is there an alternative function for calculating this or am i going to have to do some string parsing to extract the seconds and milliseconds and subtract,['php'] +280930,why is my string losing its value for some reason the value of my tocheck variable is getting erased and i have no idea why any suggestionsboolcheckstring tocheck printftocheck sn tocheckc str ifstream list listopenlisttxt string temp whilelist getlinelisttemp printftocheck s temp sntocheckc str tempc str iftemp tocheck printfusername existsn return false printfreturning truen return trueheres what it is being passed testtrevorand heres the output tocheck testtrevor tocheck temp trevor tocheck temp username exists,['c++'] +280939,how to write ios app purely in c i read here learn c before objectivecusually i then replace some objc code with pure c code after all you can mix them as much as you like the content of an objc method can be entirely pure c codeis this true is it possible to build an iphone app purely in the c programming language,"['objective-c', 'ios', 'c']" +280960,rails send email via gmail in production i want to send email via my gmail account in production it works great in local hostin my environmentrb i have configaction mailerdelivery method smtpconfigaction mailersmtp settings address smtpgmailcom port 587 domain myhostcom authentication plain user name password mypassword enable starttls auto trueand in my productionrb file configaction mailerraise delivery errors trueconfigaction mailerdefault url options host gmailcom but it does not work and i have that error errnoeconnrefused connection refused connect2any ideas my app is deployed on herokufor the host what do i have to put thanks,['ruby-on-rails'] +280964,how should i write an archive page or category index with html5 i have a link list where every item is associated with a short description and some meta info such as pubdate author etc how should i markup this in html5ul li section or article header h1titleh1 pubdate author etc header shortdesc section li repeatuldo you think it is a good idea to use sectionsarticleor are plain lis betterarticle or sectionimportant note every item does not contain full content article just a short description and the link to the page that actually contains the articlei am also interested in a seo pointofview,['html'] +280969,how can i find the number of elements in an array i have an int array and i need to find the number of elements in it i know it has something to do with sizeof but i am not sure how to use it exactly,['c'] +280971,rails drop down from an array of strings i have an array like thisnew york los angelesand i want to be able to generate a selectoption with those values in a form like this form tag filter city path method get do select tag city list of cities end but this is not working as you can see i want to pass the selection as city in the url,['ruby-on-rails'] +280980,how write a file using streamwriter in windows 8 i am having trouble when creating a streamwriter object in windows8 usually i just create an instance just passing a string as a parameter but in windows 8 i get an error that indicates that it should recieve a stream but i noticed that stream is an abstract class does anybody knows how will be the code to write an xml file btw i am using xml because i want to save the serialized object or does anyone knows how to save to a file a serialized object in windows 8any ideascurrently using windows 8 consumer previewcodestreamwriter sw new streamwriterpersonxmlerror the best overloaded method match for systemiostreamwriterstreamwritersystemiostream has some invalid arguments,['c#'] +280983,subprocess popen not working with pythonwexe i want to be able to get the contents of stdout and stderr when i run the following script on windows using pythonwexeimport subprocessimport sysimport osimport stringimport timetmpdir ctempcmd dir ctmpfile tmp f timetimetmpfile ospathnormpathospathjointmpdirtmpfiletmpfile2 tmpfilebattmpfile3 tmpfiletxtfa opentmpfile2wfawriteecho off nulnfawritecall cmdnfaclosewcmd wcmdappendtmpfile2startupinfo subprocestartupinfostartupinfodwflags subprocess subprocestartf useshowwindowfb opentmpfile3wfbwritenfbwritetmpfile2ntry procval subprocesspopenwcmd startupinfostartupinfo stdoutsubprocesspipe stderrsubprocestdoutcommunicate fbwritestrprocvaln fbwritesucess fbcloseexcept fbwritestrprocvaln fbwritefailure fbclosewhen i execute it using pythonexe i get the expected output when i run it using pythonwexei end up on the exception side if i run the popen with just the command and the startupinfo flags the command will successfully complete but no access to the data in the child proces everything that i read stated that this should work but must be missing something any help would be greatly appreciatedthanks randy,['python'] +280984,persisting a cookie based session over nodehttpproxy i have a simple express based nodejs web server that i am using for development of a javascript application i set up the server to use nodehttpproxy to proxy api requests the application makes to a jetty server that is running on a different domain and port this setup has been working flawlessly until i started to run into problems with session managementupon authentication the application server returns a cookie with an auth token representing the server session when i run the js application off of my filesystem file i can see that once client receives the cookie it is sent in all the subsequent api requests when i run the js app on the node server and api calls are proxied through nodehttpproxy routingproxy the request headers never include the cookieis there something i need to handle manually to support this type of session persistence through the proxy i have been digging through the nodehttpproxy code but it is a little over my head because i am new to node orvar express requireexpress routingproxy requirehttpproxyroutingproxy app expresscreateservervar apiversion 10 apihost myhostcom apiport 8080function apiproxypattern host port return functionreq res next if requrlmatchpattern routingproxyproxyrequestreq res host host port port else next appconfigurefunction api proxy middleware appuseapiproxynew regexp apiversion apihost apiport static content middleware appuseexpressmethodoverride appuseexpressbodyparser appuseexprestatic dirname appuseexpresserrorhandler dumpexceptions true showstack true appuseapprouterapplisten30,['javascript'] +281001,stripe recurringsubscription billing best designpractices i am coming off putting together my first site with stripe but i feel like i could have designed my stripe integration much better than i had the main issues that i came across were how do i maintain the state of the stripe account trialing and past due etc what are the important webhooks and the best ways to deal with all the events and how much data should i be duplicating in my database and how much should i just pull from stripe database would love to throw some ideas around on what would be best for reference i developed my site in ruby on rails deployed to heroku used send grid heroku add on to send email notifications about bills late payments etc also for those using stripe on ror here are some good resources that i used though i have not found one that really covers recurringsubscription billing with striperailscast ofcourse the stripe documentation and api this little piece of code for webhooksmailing,['ruby-on-rails'] +281031,httpclientgetasync with network credentials i am currently using httpwebrequest to get a website i would like to use the await pattern which is not given for httpwebrequests i found the class httpclient which seems to be the new http worker class i am using httpclientgetasync to query my webpage but i am missing the option to add clientcredientials like httpwebrequestcredentials is there any way to give the httpclient authentication information,['c#'] +281045,how to make aspnet mvc model binder treat incoming date as utc i am posting an object to an mvc controller the object contains a field called startdt and on the client it is a javascript date object in local timewhen i call jsonstringify on the object and post it to the server using jquerys ajax method i can see in firebug that whats being sent to the server is an iso string like 19001231t130z which i believe should be the local time in utc formatwhen i look at the datetime field in my controller though it looks like its back to local time and not utc how can i fix thisi want to store the utc version of the date that came from the client,['javascript'] +281047,what is the default scope of a named cdi bean is there any default scope for a named cdi bean without additional scoped annotations i have not found any relevant information in the official weld documentationa named bean can be accessed over jsf without additional annotations so some implicit scope seems likelythank you,['java'] +281088,how to find the screen size of two monitors using wxthisplaysize i want to get the screen size for two monitors using wxpythonto get the screen size of one monitor screensize is containing x and y valuescreensize wxthisplaysizebut i want something that will work for multiple monitors like the followingscreensizemonitor1 wxthisplaysizescreensizemonitor2 wxthisplaysizeif possible it would be nice to know which monitor is on the left if using two monitors and which is on the right,['python'] +281097,if you get invited to share a google play android developer console do you have to pay aswell google just opened up for sharing a developer console on androidbut if the account owner invites a person to join the developer console does this person have to pay the 25 and register as a developer before heshe can access the share developer consoleso far im unable to find the answer in the documentation,['android'] +281100,how does a full text search server like sphinx work can anyone explain in simple words how a full text server like sphinx works in plain sql one would use sql queries like this to search for certain keywords in textsselect from items where name like keywordbut in the configuration files generated by various sphinx plugins i can not see any queries like this at all they contain instead sql statements like the following which seem to divide the search into thistinct id groupsselect itemsid 5 1 as id where itemsid start and itemsid end group by itemsidselect from items where itemsid id 1 5it it possible to explain in simple words how these queries work and how they are generated,['sql'] +281108,how to set a charset in email using smtplib in python 27 i am writing a simple smtpsender with authentification heres my code smtpserver sender destination smtpgooglemailcom username password user password typical values for text subtype are plain html xml text subtype plain content hello world subjectmessage subject from smtplib import smtp ssl as smtp this invokes the secure smtp protocol port 465 uses ssl from smtplib import smtp use this for standard smtp protocol port 25 no encryption from emailmimetext import mimetext try msg mimetextcontent text subtype msgsubject subject msgfrom sender some smtp servers will do this automatically not all conn smtpsmtpserver connset debuglevelfalse connloginusername password try connsendmailsender destination msgas string finally connclose except exception exc sysexit mail failed s strexc give a error messageit works perfect untill i try to send nonascii symbols russian cyrillic how should i define a charset in a message to make it show in a proper way thanks in advanceupd i have changed my codetext subtype textcontentponn nn14pmsg mimetextcontent text subtypemsgfromsender some smtp servers will do this automatically not allmsgmimeversion10msgsubjectutf8q14 nn14msgcontenttype texthtml charsetutf8msgcontenttransferencoding quotedprintableaconnsendmailsender destination strmsgso first time i spectify text subtype text and then in header i place a msgcontenttype texthtml charsetutf8 string is it correctupdate finally i have solved my message problemyou should write smth like msg mimetextcontentencodeutf8 plain utf8,['python'] +281110,is it possible in java to override tostring for an objects array is it possible in java to override a tostring for an objects arrayfor example let us say i created a simple class user it does not really matter which class is it since this is a general question is it possible that once the client creates a user array and the client uses systemoutprintarray it would not print the arrays address but instead a customized tostringps of course i cannot just override tostring in my class since it is related to single instances,['java'] +281120,is the gideon sundback zipper doodlegoogle24th april completely javascript is the gideon sundback google doodle implemented in javascript i tried to trace through firebug but could not really get its implementation details any thoughts on how it might be implemented,"['javascript', 'css']" +281125,how to stop and restart an activity in an android instrumentation test i am trying to write an android activity instrumentation test that stops onpause then onstop and restarts the current activity i triedactivityfinishactivity getactivitybut that does not seem to work properlythe goal of the test is to assert that form data is stored during the onpause method and reread during the onstart method it works when doing it manually but the test fails from which i draw the conclusion that activityfinish seems to be the wrong way to stop and restart an activityedit my main problem seems to have been a synchronization issue after restarting the activity the test runner did not wait for all event handlers to finish the following line halts the test execution until the activity is idlegetinstrumentationwaitforidlesyncbesides that take a look at the accepted answer for more valuable information about the lifecycle,['android'] +281155,how to merge zend framework 2 module public directories some zf2 modules have public directories for thistribution of resources such as jscssimages what is best practice for making these resouces available to the applicaitoni would like it so that these resources were automatically available through modulename for example rootpublicjssitescriptjs httpmysitecomjssitescriptjsrootmodulemymodulepublicjsmodulescriptjs httpmysitecommymodulejsmodulescriptjsrootvendorvendormodulepublicjsvendorscriptjs httpmysitecomvendormodulejsvendorscriptjsshould these resources be copied to the rootpublic directory manual copying will be painful and i doubt an automated build process to merge the directories would be very practial eitherperhaps there is some magic that can be worked with httpdconf or htaccessperhaps symlinks are the solution but symlinks are not straight forward to get going on a windows platform and would need to be created manually for each individual module,['php'] +281167,matplotlib linewidth is added to the length of a line when i draw a line segment in matplotlib the linewidth seems to be added to the length of the line below my code not the most pythonic code but it should do the trick am i doing something wrong or is this just a feature of matplotlibimport matplotlibpyplot as pltimport numpy as npl1100l275l3100y3n5l prev0for lc in zipnplinspace0l1nrangen pltplotl prevl00rlinewidth20 l prevll prevl1for lc in zipnplinspacel1l1l2nrangen pltplotl prevlyyglinewidth1 l prevll prevl1for lc in zipnplinspacel1l1l3nrangen p pltplotl prevlyyblinewidth10 l prevlpltaxvspanxminl1xmaxl1pltaxis5205pltshowwhat i expected to see is three line segments 0l1 l1l2 and l1l3 but the first line 0l1 extends to l1 the diameter,['python'] +281226,remove dot character from a string c assume i have a string 236 and i want it trimmed to 236 i used trim function in examplestring amount 236string trimmedamount amounttrim the value of trimmedamount is still 236when amounttrim6 it works perfectly but with what i am doing wrong thanks a lotcheers,['c#'] +281232,what is the alternative to an enterprise portal strategy in the java space i just got my wrist slapped for not having a question that goes quite along with the spirit of stackoverflow on the suggestion of an so mod i have posted this question again over at programmers stack exchange here it is same question reposted over at programmersstackexchangei am trying to garner insight from as many sources as i can and i wanted to hear from the big brains at stackoverflowthisillusionment in the portal spacei am seeing a thisturbing number of large enterprise clients who have become thisillusioned with their enterprise portal experience especially those in the websphere portal server wps space millions have been invested yet the promise of personalized content with aggregation and integrated collaborative tools has never come to fruition the move to wps 7x is a big rip and replace move and clients are wondering if they should move somewhere else completelyportal software a horrible option that is better than all the alternativesthere are loads of portal haters out there and sometimes a portal solution is indeed overkill but when youre talking about large multinational corporations how would one recommend they architect a global solution without a portal server portals are not always as fun to work with as tomcat or jboss as but when it comes to integrating multiple applications managing content updating individual applications that are deployed as individual war files managing security down to the portlet level proving a certain amount of personalization to users and help with the overwhelming task of managing the thousands of pages large scale enterprises have as part of their internal and external websites is there a better technology out there garnering community insight and feedbacki have been trying to garner as much insight as possible i wrote a little article on tss about the issuewhich other alternatives to portal exists on marketevery enterprise needs an employee portal or do theyi am also resurrecting a thread at the coderanch to see if i can get any insight from that handsome crewupdated thread asking for an alternative to a portal software stragety circa 2012insight required a viable alternative to enterprise portal software circa 2009i am also looking for some insight from the twitterati potemcamit is not so much a crossposting as much as it is an attempt to really gather some keen insight from the community if i can get some solid responses and experiences i would like to aggregate them into an advice article over at tss so any insight or experiences would be more than helpfulinsights and experiences welcomedlooking forward to hearing your insights by the way i will be crosslinking to this thread from the other sights as well so people with the same questions will be able to bounce back and forth and see what the community is saying on this topic,['java'] +281236,what is the difference between strong in llvm and retain in gcc what is the difference between strong in llvm compiler and retain in gcc compiler,"['iphone', 'ios']" +281258,jquery bind popstate event not passed i am coding a little demo for the history api and i am struggling with this windowbindpopstate functionevent consolelogpop eventstate it logs pop undefined when i click on the previous button but if i do that instead things are working like expected windowonpopstate functionevent consolelogpop eventstateit logs pop object object this time so it is like jquery does not pass the event object to the callbackis there a problem with jquery or did i mess something,['jquery'] +281287,facebook singlesign on when user logs out of facebook app how do i log out of my app i am completely flabbergasted by the facebook sdk for androidit is quite challenging to use effectively as i understand it these are the rules for single sign onif a user has the facebook app and logs into a thirdparty app using the sdk the facebook app is logged in as wellif the user logs out of the thirdparty app using the sdk the facebook app is still signed in probably for the bestif the user logs out of the facebook app the thirdparty app using the sdk is unaffectedis there a way in an android app using the facebook sdk to check and see if the official facebook app is not signed into the same account the android app is using and if that is the case sign out of the android app in other words if you go into the facebook app and sign out then go to the thirdparty app it will be logged out,['android'] +281291,how can i add a time stamp to a file name uploaded with file before the file extension i have the following code image path filesp imagenametimeit names the file image02jpg13352798but i want it to be named image02 13352798jpghow can i achieve that,['php'] +281297,ios app with static lib always crashes on launch of ad hoc archive build cant reproduce in xcode debugger we have an app built with a static lib we are also building for thistribution the app and lib run fine in xcode debugger or when loaded on the device by xcode debugging session the app always crashes as soon as we put an ad hoc archive build on the device console log statements indicate it is crashing in lib code but crash report not symbolicating lib codecannot reproduce in xcode simulatorguard malloc guard edges show nothing but these only run in simulatorno leaksusing xcode 432app targets 43 or laterlib targets 30 or laterother linker flags objclib set as optional in target link binaries with librariesthumb support off using llvmseeing 2 exceptions on console that might be of use but so far not turning anything up on net that helps much with thisapplication x exited abnormally with signal 12 bad system call 12 mostlyapplication x exited abnormally with signal 12 bad system call 11 rarelywe saw the comment elsewhere that static libs with recursion have issues but we do not had any recursion in our libstumped need more ideas,['ios'] +281335,reading the gps data from the image returned by the camera in ios iphone i need to get the gps coordinates of an image taken with the ios devices camera i do not care about the camera roll images just the image taken with uiimagepickercontrollersourcetypecamerai have read many stackoverflow answers like get exif data from uiimage uiimagepickercontroller which either assumes you are using the assetslibrary framework which does not seem to work on camera images or use corelocaiton to get the latitudelongitude from the app itself not from the imageusing corelocation is not an option that will not give me the coordinates when the shutter button was pressed with the corelocation based solutions you either need to record the coords before you bring up the camera view or after and of course if the device is moving the coordinates will be wrong this method should work with a stationary device i am ios5 only so i do not need to support older devices this is also for a commercial product so i cannot use so what are my options for reading the gps data from the image returned by the camera in ios5 all i can think of right now is to save the image to camera roll and then use the assetslibrary but that seems hokeythanksheres the code i wrote based on calebs answer uiimage image info objectforkeyuiimagepickercontrolleroriginalimage nsdata jpeg uiimagejpegrepresentationimage10 cgimagesourceref source source cgimagesourcecreatewithdata bridge cfdatarefjpeg null nsdictionary metadatanew bridge nsdictionary cgimagesourcecopypropertiesatindexsource0null nslogmetadatanewand my console shows 20120426 141537137 ferret20601799 colormodel rgb depth 8 orientation 6 pixelheight 1936 pixelwidth 2592 exif colorspace 1 pixelxdimension 2592 pixelydimension 1936 jfif densityunit 0 jfifversion 1 1 xdensity 1 ydensity 1 tiff orientation 6 no latitudelongitude,['ios'] +281361,latest apache httpclient in android sdk android sdk 403 is currently packaging apache is httpclient 411 library i need to use some functionality which is there in the latest httpclient 413 only is there a way i can update my sdk where can i know if there are any plans in the future sdks to package the newer httpclient is there any elegant work around i have already tried the httpclientandroidlib but i want to explore other optionsany pointers appreciated thanks,['android'] +281377,confusion on cudaopencl and c amp i read that microsoft is closely working with nvidia to improve amp performancesbut my question is is amp a cudareplace by microsoft or does amp use cuda drivers when a nvidia cuda video card is available is amp an opencl substitutei am still pretty confused,['c++'] +281401,serviceloader to find implementations of an interface i tried to use the java serviceloader to find all classes that implement a specific interface like soloader serviceloaderloadoperationclasstry for operation o loader operationsaddo catch serviceconfigurationerror e loggerloglevelsevere uncaught exception eunfortunately when i run eclipse in debug mode the serviceloader does not find any classes i feel like i am missing a trivial point,['java'] +281404,live sdk try to sign in without signinbutton is there any way to login to live for an app silverlight wp7 can without having to click on signin buttoni want to log me dynamically for example when you start the app i want to log in to me how to do this without resorting to the button,['c#'] +281415,stringbyevaluatingjavascriptfromstring ios method what is android equivalent in an ios app i used stringfromjavascript webview stringbyevaluatingjavascriptfromstringdocumentgetelementbyidimagegetattributesrcto get the src directory of the image that was being thisplayed on the webview i want to do the same for android what are my optionsbasically the intent is to capture the path so that i can email this same pictureiepicturephpimagestringfromjavascriptthis way that same image would be loaded when the user clicks the link or posts it to facebook etc,"['java', 'php', 'android', 'ios']" +281421,applicationdidbecomeactive getting called twice my app delegate method applicationdidbecomeactive is getting called twice for the first time launch of the application i have some portion of code which i want to execute only once that i have put into applicationdidbecomeactivewhat should i do,"['iphone', 'objective-c', 'ios']" +281430,change default buttons in java to make them look better i am essentially trying to mimic the default windows xp simple calculator when i change the background colours of the buttons in java it makes them look very flat and boring i want to make the buttons look as close as possible to the buttons in the windows xp calculator here is an image comparing mine to winxpsis there some kind of method i can use to change the style of the buttons much like you can do in visual basic to make the buttons almost pop more or look 3d like the windows xp calculatorthe default buttons in java are sort of what i am looking for except there not white there more of a blue kind of colour in a gradientis this possible or am i stuck with ugly button,['java'] +281431,rails how can i show a block with or without a link based on a condition link to if i have a complex block of tags h3 p that i want to render with a link or without a link around it based on a conditioni know about link to if that works like that link to if condition name path if the condition is false only the name will be rendered and i know about the link to with block link to path do complex content end i want a combination of both a link to if statement that accepts a block so that the block will be rendered without a link around it if the condition is false unfortunately the link to if statement with a block works not like the link to statement does anyone have suggestion for me any help is highly appreciated,['ruby-on-rails'] +281442,how to require for the second time is there a way to force requireing of a file for the second time i am writing a library that is located in a path for ruby i am editing the file while doing a simple test of it in irbeach time i make a change to the file i want to reload it without ending the irb session using load requires typing the whole path to the file each time and restarting irb each time requires me to type all the other variable settings required for the simple test i just want something like require but that allows loading for the second time is there a simple way to do it,['ruby'] +281468,how to use webapi without aspnet mvc i would like to use webapi for an existing project of mine classic aspnet but as far as i can tell you can only use webapi with mvcis it possible to use webapi with aspnet,['asp.net'] +281470,css specificity media queries and minwidth i am redesigning my blog with responsive web design in mind and the mobile first method in short i am trying to use minwidth to avoid any kind of replication or css no thisplaynones etcmy problem is that when i do need to overwrite a css value the lower minwidth takes precedence examplemedia only screen and minwidth 600px h2 fontsize 22em media only screen and minwidth 320px h2 font normal 17em21em helvetica sansserif i would expect when i am in resolutions of 600px and above to get a 22em h2 but instead i get 17em in my dev tools i see that the 22em declaration is there but the other one takes precedence it does not make sensecould i keep using minwidths and effectively overwrite declarations in higher resolutions without using stronger selectors or maxwidth,['css'] +281474,postgres define a default value for cast failures is it possible to define a default value that will be returned in case a cast operation failsfor example so thatselect castfoo as integerwill return a default value instead of throwing an error,['sql'] +281495,mocking a return type from another mocked type using moq so i am trying to return a mocked type from another mocked type i have made some progress but i am stuck here interface names have been simplifiedconsider the interface ifoo and ifooitem calling add on an ifoo type passing in an ibar returns an ifooiteminterface ifoo ifooitem addibar barinterface ifooitem int fooitemid get setalso i have a ifoorepository which i am trying to use moq to mock so i can mock adding an itemsovar mockfoorepository new mockifoorepositorymockfoorepositorysetupm madditisanyibar returns what is the correct way to mock properties of a new ifooitem from mocked properties of ibar essentially a new mocked type of ifooitem that can read from ibar so ifooitemproperty somevalue ifooitemproperty2 ibarsomeprop,['c#'] +281502,what is the difference between qimage and qpixmap i do not understand what is the difference between qimage and qpixmap they seem to offer the same functionality when should i use a qimage and when should i use a qpixmap,['c++'] +281510,using androidemulator to test at commands by com from external application i need send at commands to a usb gsm modem whith cthe problem is that i havent no gsm modem or gsm enabled device yet to develop then i was looking for a emulatorthe only simulated gsm modem i found was that come with the android sdkmy problem now is sent at commands to android simulated gsm modem througt com port like i need to do in my real applicationthere is some way to reach com virtual usbcom port of android simulated gsm modem and sent at commands to connect to internet there is someone telling about here but it cant help me,['c#'] +281518,using as a shorthand if statement while i was killing time looking up javascript shorthand patterns i came across an interesting way of expressing an if statement here the following worksavar var1 5var var2 1var1 5 var2i think that is a totally cool and shorter cleaner way of writing an if statement that only needs to do one operation however i ran into an issue with the following code as soon as i tried something else with itavar var1 5var var2 1var1 5 var2 2instead of working like the first code snippet my test throws an erroruncaught referenceerror invalid lefthand side in assignmentwhy does not this work and why is the lefthand side of my statement being called out as incorrect as opposed to the right hand,['javascript'] +281542,can a non blocking udp write return with fewer bytes than requested i have an application that sends data point to point from a sender to the receiver over an link that can operate in simplex one way transmission or duplex modes two way in simplex mode the application sends data using udp and in duplex it uses tcp since a write on tcp socket may block we are using non blocking io ioctl with fionbio o nonblock and fcntl are not supported on this thistribution and the select system call to determine when data can be written nio is used so that we can abort out of send early after a timeout if needed should network conditions deteriorate i would like to use the same basic code to do the sending but instead change between tcpudp at a higher abstraction this works great for tcphowever i am concerned about how non blocking io works for a udp socket i may be reading the man pages incorrectly but since write may return indicating fewer bytes sent than requested does that mean that a client will receive fewer bytes in its datagram to send a given buffer of data multiple writes may be needed which may be the case since i am using non blocking io i am concerned that this will translate into multiple udp datagrams received by the clienti am fairly new to socket programming so please forgive me if have some misconceptions here thank you,['c'] +281544,python beautifulsoup iterate over table i am trying to scrape table data into a csv file unfortunately i have hit a road block and the following code simply repeats the td from the first tr for all subsequent trsimport urllibrequestfrom bs4 import beautifulsoupf openouttxtwurl proposatipaiprpreportsrapports201202atip aiprpaspxpage urllibrequesturlopenurlsoup beautifulsouppagesoupunicodetable1 soupfindtable border1table2 soupfindtbodytable3 soupfind alltrfor td in table3 rn soupfind alltd0get text sr soupfind alltd1get text d soupfind alltd2get text and soupfind alltd3get text printrn sr d filefthis is my first ever python script so any help would be appreciated i have looked over other question answers but cannot figure out what i am doing wrong here,['python'] +281549,add elements to the dom given plain text html using only pure javascript no jquery i need to be able to add elements to a page given a raw text string of html including any number of tags attributes etc ideally i would like to be able to do something like with any arbitrary string of wellformed html var theelement documentcreateelementh1 idtitlesome titleh1span stylethisplayinlineblock width100pxsome arbitrary textspandocumentgetelementbyidbodyappendchildtheelementobviously that does not work i am looking for good ways to achieve the same result i would like to avoid parsing the html if possible i am severely restricted on the tools i can use no jquery or outside includes and must be crossbrowser and backward compatible down to ie6 any help would be huge,"['javascript', 'html']" +281565,how to remove cell from static uitableview created in storyboard this should be easy but i am having troublei have a static uitableview with a cell that i would like to remove programmatically if it is not needed i have a iboutlet for itiboutlet uitableviewcell cell15and i can remove it by calling cell15hidden truethis hides it but leaves a blank space where the cell used to be and i cannot get rid of itperhaps a hack would be to change the height of it to 0 cgfloattableviewuitableview tableview heightforrowatindexpathindexpathwhat would i put herethanks so much,['ios'] +281577,set height of imageview as matchparent programatically i need to set the height of an imageview as matchparent programaticallyif it is a fixed height i know how to setbut how can i set it as matchparent editactually height of the parent layout is dynamicso i need to make the height of the imageview as the height of parent,['android'] +281607,one play 2 framework app use both java and scala i want to use morphia for my data access but i also want to try to use scala for web content is it possible to mix and match java and scala files or if i choose to use java i have to stick to javai know this is a newbie question i am coming from the pythondjango world i really like play did some java programming in the past but scala looks very interesting so while i am a bit afraid to fully jump into scala i want to be able to use it alongside javathanks for all the help,['java'] +281609,how do i work with ninject in an aspnet mvc web app i have created a new mvc web application and i have references to ninjectdll ninjectwebcommondll and ninjectwebmvcdllglobalasaxcspublic class mvcapplication ninjecthttpapplication public static void registerglobalfiltersglobalfiltercollection filters filtersaddnew handleerrorattribute public static void registerroutesroutecollection routes routesignorerouteresourceaxdpathinfo routesmaproute default route name controlleractionid url with parameters new controller home action index id urlparameteroptional protected override ikernel createkernel var kernel new standardkernel kernelloadassemblygetexecutingassembly return kernel protected override void onapplicationstarted baseonapplicationstarted arearegistrationregisterallareas registerglobalfiltersglobalfiltersfilters registerroutesroutetableroutes app startninjectwebcommonpublic static class ninjectwebcommon private static readonly bootstrapper bootstrapper new bootstrapper summary starts the application summary public static void start dynamicmoduleutilityregistermoduletypeofoneperrequesthttpmodule dynamicmoduleutilityregistermoduletypeofninjecthttpmodule bootstrapperinitializecreatekernel summary stops the application summary public static void stop bootstrappershutdown summary creates the kernel that will manage your application summary returnsthe created kernelreturns private static ikernel createkernel var kernel new standardkernel kernelbindfuncikerneltomethodctx new bootstrapperkernel kernelbindihttpmoduletohttpapplicationinitializationhttpmodule registerserviceskernel return kernel summary load your modules or register your services here summary param namekernelthe kernelparam private static void registerservicesikernel kernel i get the error the sequence contains no elements what am i doing wrongerror detailsdescription an unhandled exception occurred during the execution of the current web request examine the stack trace for more information about this error and where it originated in the codeexception details systeminvalidoperationexception sequence contains no elementssource error unhandled exception occurred during execution of the current web request information regarding the origin and location of the exception can be identified using the exception stack trace belowstack traceinvalidoperationexception 34n 342nn1234n 12 n34 n n n1412n342 systemlinqenumerablesingleienumerable1 source 320 ninjectwebmvcninjectmvchttpapplicationpluginstart in cprojectsninjectninjectwebmvcmvc3srcninjectwebmvcninjectmvchttpapplicationplugincs53 ninjectwebcommonbootstrapperinitializeb 0ininjecthttpapplicationplugin c in cprojectsninjectninjectwebcommonsrcninjectwebcommonbootstrappercs52 ninjectinfrastructurelanguageextensionsforienumerableoftmapienumerable1 series action1 action in cprojectsninjectninjectsrcninjectinfrastructurelanguageextensionsforienumerableoftcs32 ninjectwebcommonbootstrapperinitializefunc1 createkernelcallback in cprojectsninjectninjectwebcommonsrcninjectwebcommonbootstrappercs52 ninjectwebcommonninjecthttpapplicationapplication start in cprojectsninjectninjectwebcommonsrcninjectwebcommonninjecthttpapplicationcs80,['c#'] +281619,is it possible to have custom attributes in androidmanifestxml tags i would like to add a custom attribute to the application tag of my androidmanifestxml file is this possible in the android environment,['android'] +281647,opencv rotationtranslation vector to opengl modelview matrix i am trying to use opencv to do some basic augmented reality the way i am going about it is using findchessboardcorners to get a set of points from a camera image then i create a 3d quad along the z 0 plane and use solvepnp to get a homography between the imaged points and the planar points from that i figure i should be able to set up a modelview matrix which will allow me to render a cube with the right pose on top of the imagethe documentation for solvepnp says that it outputs a rotation vector that together with the translation vector brings points from the model coordinate system to the camera coordinate system i think that is the opposite of what i want since my quad is on the plane z 0 i want a a modelview matrix which will transform that quad to the appropriate 3d plane i thought that by performing the opposite rotations and translations in the opposite order i could calculate the correct modelview matrix but that seems not to work while the rendered object a cube does move with the camera image and seems to be roughly correct translationally the rotation just does not work at all it on multiple axes when it should only be rotating on one and sometimes in the wrong direction heres what i am doing so farstdvectorpoint2f cornersbool found findchessboardcorners imagebuffer cvsize54 corners cv calib cb filter quads cv calib cb fast checkiffound drawchessboardcorners imagebuffer cvsize6 5 corners found stdvectordouble thistortioncoefficients5 camera thistortion thistortioncoefficients0 0070969 thistortioncoefficients1 07647 thistortioncoefficients2 09131 thistortioncoefficients3 0013867 thistortioncoefficients4 5141519 since the image was resized we need to scale the found corner points float sw width small width float sh height small height stdvectorpoint2f board verts board vertspush backpoint2fcorners0x sw corners0y sh board vertspush backpoint2fcorners15x sw corners15y sh board vertspush backpoint2fcorners19x sw corners19y sh board vertspush backpoint2fcorners4x sw corners4y sh mat boardmatboard verts stdvectorpoint3f square verts square vertspush backpoint3f1 1 0 square vertspush backpoint3f1 1 0 square vertspush backpoint3f1 1 0 square vertspush backpoint3f1 1 0 mat squarematsquare verts transform the cameras intrinsic parameters into an opengl camera matrix glmatrixmodegl projection glloadidentity camera parameters double f x 78642938232 focal length in x axis double f y 78642938232 focal length in y axis usually the same double c x 21701358032 camera primary point x double c y 31125384521 camera primary point y cvmat cameramatrix33cv 32fc1 cameramatrixatfloat00 f x cameramatrixatfloat01 00 cameramatrixatfloat02 c x cameramatrixatfloat10 00 cameramatrixatfloat11 f y cameramatrixatfloat12 c y cameramatrixatfloat20 00 cameramatrixatfloat21 00 cameramatrixatfloat22 10 mat rvec3 1 cv 32f tvec3 1 cv 32f solvepnpsquaremat boardmat cameramatrix thistortioncoefficients rvec tvec rv0 rvecatdouble0 0 rv1 rvecatdouble1 0 rv2 rvecatdouble2 0 tv0 tvecatdouble0 0 tv1 tvecatdouble1 0 tv2 tvecatdouble2 0then in the drawing codeglkmatrix4 modelviewmatrix glkmatrix4maketranslation00f 00f 00fmodelviewmatrix glkmatrix4translatemodelviewmatrix tv1 tv0 tv2modelviewmatrix glkmatrix4rotatemodelviewmatrix rv0 10f 00f 00fmodelviewmatrix glkmatrix4rotatemodelviewmatrix rv1 00f 10f 00fmodelviewmatrix glkmatrix4rotatemodelviewmatrix rv2 00f 00f 10fthe vertices i am rendering create a cube of unit length around the origin ie from 05 to 05 along each edge i know with opengl translation functions performed transformations in reverse order so the above should rotate the cube along the z y and then x axes and then translate it however it seems like it is being translated first and then rotated so perhaps apples glkmatrix4 works differentlythis question seems very similar to mine and in particular coder9s answer seems like it might be more or less what i am looking for however i tried it and compared the results to my method and the matrices i arrived at in both cases were the same i feel like that answer is right but that i am missing some crucial detail,['ios'] +281673,theming and layout in yii framework i am a newbie in yii framework and creating a crm which is module basedusing different tutorials i am able to create my own theme but now i am stucked at one pointin my theme the upper nav and left nav remains the same throughout the app until user is logged in that is why i made it a part of my mainphp but in the login page there are no buttons to show just simple login form with 2 textfieldshow can i implement this form in my application using custom themesi have tried to define a layout in that particular action but not succeeded any help would be appreciated,['php'] +281688,how to record audio as mp3 file by using avaudiorecorder how to record audio as mp3 file by using avaudiorecorderi m using following code for recorder settingrecordsetting1 nsdictionary dictionarywithobjectsandkeys nsnumber numberwithintavaudioqualityminavencoderaudioqualitykey nsnumber numberwithint16 avencoderbitratekey nsnumber numberwithint 2 avnumberofchannelskey nsnumber numberwithfloat4410 avsampleratekeynil,['iphone'] +281700,flask url for urls in javascript what is the recommended way to create dynamic urls in javascript files when using flask in the jinja2 templates and within the python views url for is used what is the recommended way to do this in js files since they are not interpreted by the template enginewhat basically want to do is in commentsjsposturl forcommentcomment replywhich is not possiblebut naturally i can execute that in a templatescript posturl forcommentcomment replyscript,"['javascript', 'python']" +281768,how do you add an existing form to a new project i have never been able to successfully add a new form file as an existing file to a new project i read on a blog that you add just the cs file and the dependencies come in well i tried this and the file did dragin and associate the designer and resx files but the form icon does not thisplay instead the file looks like a normal cs file image and when i double click the file i get the code behind instead of the form objectis it possible to add existing forms without recreating them,['c#'] +281781,controlling the cameras autoexposure i have written a camera app in android and i have tested it on two android phones on one phone the autoexposure works well when previewing but on the other phone it does not work at all the first phone only works when i call the autofocus method on the latter phone the buildin apps autoexposure works but not my code is there any method that can start use the autoexposure manually,['android'] +281833,how does naming an anonymous function in javascript make a difference i am analyzing the following two urls from john resigs site but i am not understanding how giving a name to the anonymous function has made a differencemy understanding is that the name given to an anonymous function can only be used inside the function definition and nowhere outside of it but in the following links it is making a huge differenceany explanation or reference will be a great helpi am still confused with the following lines in 14var samurai yell ninjayell var ninja assert samuraiyell4 hiya the method correctly calls itself how is samuraiyell method still able to point ninjayell when ninja is now pointing to a blank object only difference between 13 and 14 is providing a name to the function expression in 14 is ninjayell copied to yell and not referenced or these kind of named function expression have global scope in some scenarios like this same thing happens in 13 and 14 only difference is that function is named in 14 and unnamed in 13 plus ninja in 14 and ninja null in 13 is there any hidden concept about named function expressions that i am missing which makes 14 workable and 13 not workable,['javascript'] +281845,ondestroy while waiting for onactivityresult i have an app with two activities a and ba uses startactivityforresult to spawn b ie it waits for b now assume that b is in foreground can the android system destroy activity a without also destroying b if yes then when bis finished eg after user input activity a must be recreated and put to the foreground again by the android system and i need to remember and restore a to its earlier ui statusnote that i am not talking about process kill which is different case if a process is killed all activities are killed and ondestroy is not called or not guaranteed to be called the question is merely about whether ondestroy is possible while waiting for the result of a subactivity,"['java', 'android']" +281870,turn a user input string to upper case java this may seem like a silly question but after going through pages of google i havnt been able to find the answer i wants1setnamejoptionpaneshowinputdialogenter name for the above piece fo code how would i format the data the user entered to be all capitalsany help here would be appreciated,['java'] +281924,how to play a sound using avaudioplayer when in silent mode in iphone i want to play a sound even in silent mode in iphonecan it be done by using avaudioplayer without using avaudiosessionfor ios 30thanks in advance,"['iphone', 'ios']" +281933,formwide error bubbling in symfony 2 this is how i currently activate errors on my formspublic function buildformformbuilder builder array options builder addtitle null arrayerror bubbling true addcontent null arrayerror bubbling true is there a formwide version,['php'] +281937,android app javalangnullpointerexception my app crashes sometimes on samsung phonesjavalangnullpointerexception but it does not reference to my code anywherewhat can i do to avoid this errorjavalangnullpointerexceptionat androidappactivitythreadhandlestopactivityactivitythreadjava2476at androidappactivitythreadaccess1800activitythreadjava117at androidappactivitythreadhhandlemessageactivitythreadjava952at androidoshandlerthispatchmessagehandlerjava99at androidoslooperlooplooperjava123at androidappactivitythreadmainactivitythreadjava3691at javalangreflectmethodinvokenativenative methodat javalangreflectmethodinvokemethodjava507at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava847at comandroidinternaloszygoteinitmainzygoteinitjava605at dalviksystemnativestartmainnative method,['android'] +281952,printing file permissions like ls l using stat2 in c i am trying to write a small c program that emulates the unix command ls l to do so i am using the stat2 syscall and have ran into a small hiccup writing the permissions i have a mode t variable which holds the file permissions from st mode and it wouldnt be hard to parse that value into s string representation but i was just wondering if there is a better way to be doing it than that,['c'] +281966,prefetching data to cache for x8664 in my application at one point i need to perform calculations on a large contiguous block of memory data 100s of mbs what i was thinking was to keep prefetching the part of the block my program will touch in future so that when i perform calculations on that portion the data is already in the cache can someone give me a simple example of how to achieve this with gcc i read mm prefetch somewhere but do not know how to properly use it also note that i have a multicore system but each core will be working on a different region of memory in parallel,['c'] +281992,knockout binding handler teardown function i have a knockout binding handler that uses plupload for drag and drop and ajax uploadsto use the plupload script i create an instance of plupload which in turn is binding event listeners to dom elements that works finehowever i have a list of folders and when i click a folder i thisplay a list of files in that folder i reuse the same dom elements for this by binding selectedfolderdocuments using foreachthe problem i have is that in my binding handler i do all my plupload stuff in the init function and since i reuse the dom elements they get multiple event handlers bound to them this causes the drag and drop events to be sent to alla handlers this means that if i drop a file on the rendered file list the drop event fires on all previously rendered file lists toowhat i am looking for is some sort of teardown or cleanup function in the binding handler so that i can unregister all of the events whenever a file list get unrendered is that a word maybe we cannot detect unrendering how would i then handle this i would prefer not to have a global instance since that would prevent me from using the binding on multiple places at the same timesorry about not giving you any code i am on my cell phone atmcheers,['javascript'] +282021,combine two columns in sql for where clause in my sql i am using the where and like clauses to perform a search however i need to perform the search on a combined value of two columns first name and last namewhere customersfirst name customerslast name like john smiththis does not work but i wondered how i could do something along these linesi have tried to do seperate the search by the two columns like sowhere customersfirst name like john smith or customerslast name like john smithbut obviously that will not work because the search query is the combined value of these two columns,"['php', 'mysql', 'sql']" +282041,why are the fields in struct stat named st something this is in reference to the structure for information about a file inode dev t st dev id of device containing file ino t st ino inode number mode t st mode protection nlink t st nlink number of hard links uid t st uid user id of owner gid t st gid group id of owner dev t st rdev device id if special file off t st size total size in bytes time t st atime time of last access time t st mtime time of last modification time t st ctime time of last status change blksize t st blksize blocksize for filesystem io blkcnt t st blocks number of blocks allocated i am just looking for any type of answer really i noticed all fields begin with st and can not find a good explanation on the internet,['c'] +282053,does core data impose limits on the length of strings i was wondering if there are any limits on the length of strings stored using core data in ios other than available ram or thisk space on the device,"['objective-c', 'ios']" +282090,equivalent of ios nsnotificationcenter in android is there an equivalent of the ios class nsnotificationcenter in android are there any libraries or useful code available to me,"['android', 'iphone', 'ios']" +282136,compiletime source code modification using roslyn is it possible to modify source code before compilation using roslyn within msbuild task on ci server i have succeeded to do what i want in vs but i wonder if it is possible outside vs currently i am looking at workspace apis and compiler apis and they seem to be the right tool to achieve that but i am still not sure is it possible at all in particular i am concerned about returning changes that i have done to msbuild back to allow it to continue its job,"['c#', '.net']" +282140,how to extract specific array keys and values to another array i have an array of arrays like soarray array array array array the arrays inside the main array contain 4 keys and their values the keys are the same among all arrays like thisarray id post 1 desc description 1 type type1 title title array id post 2 desc description 2 type type2 title title so i want to create another array and extract the id and type values and put them in a new array like thisarray post 1 type1 post 2 type2 and so onthe keys in this array will be the value of id key old arrays and their value will be the value of the type keyso is it possible to achieve this i tried searching phpnet array functions but i do not know which function to useand thanks in advance,['php'] +282153,python 3x using stringmaketrans in order to create a unicodecharacter transformation i would like to write the following codeimport stringfrm bacdefhnoprstuwto atrans table stringmaketransfrm tohebrew phrase fear cuts deeper than swordstranslatetrans tablethe above code does not work because the to parameter to stringmaketransfrm to has to be a byte sequence not a string the problem is that byte sequences can only contain ascii literal characters therefore i cannot make a transformation which translates english strings to hebrew strings the reason is that stringmaketrans retruns a bytes objectis there an elegant way to use the stringmaketrans and translate functions or equivalent functions that work with unicode for my task,['python'] +282189,android audiorecord which settings to record call i use audiorecord class to record the voice during a calli am intererested to record only the voice of the person who owns the phone from the microphone during the recording i would like to do some audio processing but this is offtopic for nowandroid has the following audiosources optionsmediarecorderaudiosourcevoice callmediarecorderaudiosourcemicmediarecorderaudiosourcevoice uplinkmediarecorderaudiosourcevoice downlinkcan you explain what is the differences among them ok mic is obvious but voice call vs voice uplink vs voice downlink also i should choose a sample rate 80hz 160hz 2250hz 44100hz can you please tell me what sample rate to choose and whyfor audio format i chose audioformatencoding pcm 16bitbut it also has audioformatencoding default audioformatencoding invalid audioformatencoding pcm 8bitfinally is how many channels should i use and why audioformatchannel in stereo or audioformatchannel in mono,['android'] +282195,execute javascript before dom is loading i want to develop a handle javascript class that handle used frameworks among other thingsfor examplemyclassaddframeworkjquery just an exampleit works fine and my class add the framework but if there any jquery code in it it wouldnt work because the framework is loaded after the dom is ready so a default jquery snippet like jquerydocumentreadyfunction cannot work because jquery is not already definedis there any solution to that i can script a fix that before the rest of the dom is beginning to loading all my addframework methods must be executed,"['javascript', 'jquery']" +282213,what the equivalent for gem in python possible duplicatedoes python have a packagemodule management system in ruby i can do something likegem install mycoolgemhow do i do this in python,['python'] +282221,is binding to a typeliteral a good or bad practice in google guice google guice uses new typeliteralct to overcome the fact that we cannot use ctclass now it is common to the followingbindnew typeliteralct tomycsubclasstypedtotclassimagine a different scenario however we have a generic interface that we want to inject and the implementation we have is be provided by a generic classguice allows you to do this like thisbindnew typeliteralmygenericinterfacet tonew typeliteralmygenericclasst another way of doing this would be to extend mygenericclass like thismytypedclass extends mygenericclasstand then bind it like thisbindmygenericinterfacet tomytypedclassclassif mygenericinterface is injected a lot albeit with different types and every time i do inject it i use mygenericclass the latter approach leads to overly verbose code hence i am leaning towards using the formeri would be very keen to hear other peoples opinion about the use of a typeliteral in the to clause of a guice binding i am afraid that i might a bit to short sited and thus do not see the pitfalls of this approach,['java'] +282245,random function higher values appear less often than lower i have a tricky question that i have looked into a couple of times without figuring it outsome backstory i am making a textbased rpggame where players fight against animalsmonsters etc it works like any other game where you hit a number of hitpoints on each other every roundthe problem i am using the randomfunction in php to generate the final value of the hit depending on levels armor and such but i would like the higher values like the max hit to appear less often than the lower valuesthis is an examplegraphhow can i reproduce something like this using php and the randfunction when typing rand1100 every number has an equal chance of being pickedmy idea is this make a 2nd degree or quadratic function and use the random number x to do the calculationwould this work like i wantthe question is a bit tricky please let me know if youd like more information and details,['php'] +282317,hibernate mapping not working in offline mode we are going through thisaster recovery exercise and several hibernatespring applications are not starting with following error caused by orgspringframeworkbeansfactorybeancreationexception error creating bean with name sessionfactory defined in servletcontext resource webinfapplicationcontextxml invocation of init method failed nested exception is orghibernateinvalidmappingexception could not parse mapping document from input stream at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactoryinitializebeanabstractautowirecapablebeanfactoryjava1337 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorydocreatebeanabstractautowirecapablebeanfactoryjava473 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactory1runabstractautowirecapablebeanfactoryjava409 at javasecurityaccesscontrollerdoprivilegedaccesscontrollerjava214 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorycreatebeanabstractautowirecapablebeanfactoryjava380 at orgspringframeworkbeansfactorysupportabstractbeanfactory1getobjectabstractbeanfactoryjava264 at orgspringframeworkbeansfactorysupportdefaultsingletonbeanregistrygetsingletondefaultsingletonbeanregistryjava221 at orgspringframeworkbeansfactorysupportabstractbeanfactorydogetbeanabstractbeanfactoryjava261 at orgspringframeworkbeansfactorysupportabstractbeanfactorygetbeanabstractbeanfactoryjava185 at orgspringframeworkbeansfactorysupportabstractbeanfactorygetbeanabstractbeanfactoryjava164 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactoryautowirebynameabstractautowirecapablebeanfactoryjava1029 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorypopulatebeanabstractautowirecapablebeanfactoryjava977 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorydocreatebeanabstractautowirecapablebeanfactoryjava472 55 morecaused by orghibernateinvalidmappingexception could not parse mapping document from input stream at orghibernatecfgconfigurationaddinputstreamconfigurationjava541 at orgspringframeworkormhibernate3localsessionfactorybeanbuildsessionfactorylocalsessionfactorybeanjava638 at orgspringframeworkormhibernate3abstractsessionfactorybeanafterpropertiessetabstractsessionfactorybeanjava211 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactoryinvokeinitmethodsabstractautowirecapablebeanfactoryjava1368 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactoryinitializebeanabstractautowirecapablebeanfactoryjava1334 67 morecaused by orgdom4jdocumentexception server returned http response code 504 for url nested exception server returned http response code 504 for url at orgdom4jiosaxreaderreadsaxreaderjava484 at orghibernatecfgconfigurationaddinputstreamconfigurationjava532 71 morethe hbm mapping xml file hasxml version10doctype hibernatemapping public hibernatehibernate mapping dtd 30en searching on so and hibernate forums the fix looks like we need to make dtd in the doctype to system so it reads from local system instead of public dtd hosted on sourceforgenetdoctype hibernatemapping system hibernatemapping30dtdbut with this hibernate is looking for the file on appserver root foldercaused by orghibernateinvalidmappingexception could not parse mapping document from input stream at orghibernatecfgconfigurationaddinputstreamconfigurationjava541 at orgspringframeworkormhibernate3localsessionfactorybeanbuildsessionfactorylocalsessionfactorybeanjava638 at orgspringframeworkormhibernate3abstractsessionfactorybeanafterpropertiessetabstractsessionfactorybeanjava211 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactoryinvokeinitmethodsabstractautowirecapablebeanfactoryjava1368 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactoryinitializebeanabstractautowirecapablebeanfactoryjava1334 72 morecaused by orgdom4jdocumentexception cibmsoasdp70runtimesbase v61profilesappsrvwsfp01hibernatemapping30dtd the system cannot find the file specified nested exception cibmsoasdp70runtimesbase v61profilesappsrvwsfp01hibernatemapping30dtd the system cannot find the file specified at orgdom4jiosaxreaderreadsaxreaderjava484 at orghibernatecfgconfigurationaddinputstreamconfigurationjava532 76 morehow should the system dtd reference be specified so hibernate reads dtd from hibernatejar instead of looking for it in the file system,['java'] +282333,numpy replace negative values in array can anyone advise a simple way of replacing all negative values in an array with 0i am having a complete block on how to do it using a numpy arrayega array1 2 3 4 5i need to return1 2 3 0 5a 0 givesfalse false false true falsethis is where i am stuck how to use this array to modify the original array,['python'] +282338,array list algorithm interview i was asked this question in an interview today i have tried a solution but would like to know if there is a better way to solve thisquestion i have an arraylist say of 50 elements such that the value of each element of the arraylist is same as the index for ex listget0 0 listget1 1 etc but only one element is out of sync with this ordering ie listgeti i how do you find that elementmy answer iterate over the list using multiple threads each thread handling a certain splice of the arraylist each time comparing listgeti with i when the element is found set some boolean variable to indicate to other threads that the element has been foundis there a way to solve this problem without iterating over the list or a better way,['java'] +282350,placeholder attribute on input tags for ie i know that internet explorer does not support the placeholder attribute for input tags but surely in 2012 there must be another solution for ie,['css'] +282354,how to get pictures from qwebview does anybody know how to get a picture from qwebview my situation is there is no scope to use the image url and then a qnetworkrequest i just need to extract the image from the qwebview,['c++'] +282370,why threadabortexception when trying to close a sqlconnection in net i keep getting the following exception when i dousing cnn as sqlconnection new sqlconnectionconnectionstr cnnopen i am fine up to hereend using here i am getting the following exceptionmanually called cnnthispose causes the same exception it seems to be ok in most places in my code but just in this one function i cannot close the connection that i opened because i keep getting the threadabortexception i am stumped any ideas any hints here is the exception i getsystemtypeinitializationexception the type initializer for systemdataproviderbasedbconnectionclosedpreviouslyopened threw an exception systemthreadingthreadabortexception exception of type systemthreadingthreadabortexception was thrown end of inner exception stack trace at systemdataproviderbasedbconnectioninternalcloseconnectiondbconnection owningobject dbconnectionfactory connectionfactory at systemdatasqlclientsqlinternalconnectioncloseconnectiondbconnection owningobject dbconnectionfactory connectionfactory at systemdatasqlclientsqlconnectionclose at systemdatasqlclientsqlconnectionthisposeboolean thisposing,"['c#', '.net']" +282383,service not receiving messages after message queuing service restarted we have a service that receives messages from and message queues however if the message queuing service is restarted the message retrieval service stops receiving messages even after the message queuing service has restarted successfullyi have tried to specifically catch the messagequeueexception that is thrown in the message retrieval service and invoke the queues beginreceive method again however in the 2 seconds or so that it takes the message queuing service to restart i get about 1875 instances of the exception and then the service stops functioning when another messagequeueexception is thrown in our startlistening method is there an elegant way to recover from a message queuing service restart private void onreceivecompletedobject sender receivecompletedeventargs e messagequeue queue messagequeuesender try message message queueendreceiveeasyncresult thisstartlisteningqueue if thismessagereceived null thismessagereceivedthis new messagereceivedeventargsmessage catch messagequeueexception logutilitylogerrorstringformatcultureinfoinvariantculture stringresourcelogmessage queuemanager messagequeueexception queuemachinename queuequeuename queuepath thisstartlisteningqueue public void startlisteningmessagequeue queue queuebeginreceive i need to deal with the infinite loop issue this causes and clean it up a bit but you get the ideawhen the messagequeueexception occurs invoke the recoverqueue method private void recoverqueuemessagequeue queue string queuepath queuepath bool queuerecovered false while queuerecovered try thisstoplisteningqueue queueclose queuethispose threadsleep20 messagequeue newqueue thiscreatequeuequeuepath newqueuereceivecompleted new receivecompletedeventhandlerthisonreceivecompleted thisstartlisteningnewqueue logutilityloginformationstringformatcultureinfoinvariantculture message queue 0 recovered successfully newqueuequeuename queuerecovered true catch exception ex logutilitylogerrorstringformatcultureinfoinvariantculture the following error occurred while trying to recover queue 0 error 1 queuequeuename exmessage public void stoplisteningmessagequeue queue queuereceivecompleted new receivecompletedeventhandlerthisonreceivecompleted,['c#'] +282388,which locale should i specify when i call string tolowercase in java the string tolowercase method uses the default system locale to determine how to handle lowercasing if i am lowercasing some ascii text and want to be sure that this is processed as expected which locale should i useedit i am mainly concerned about programming identifiers such as table and column names in a schema as such i want english lower casing to apply localeroot states that it is the languagecountry neutral locale for the locale sensitive operationslocaleenglish would presumably also be a safe choice,['java'] +282400,finished running on iphone i am trying to test my app on an iphone 4s when i build and run from xcode the project is successfully compiled but after that xcode saysfinished running myappapp on myiphonethe app perfectly work on the simulator and the provisioning profile works correctly i tried to load an empty app and it worksif i try to manually load the app i get this message the infoplist for application at usersdocumentsappappnamederiveddataappnamebuildproductsreleaseiphoneosappnameapp specifies a cfbundleexecutable of appname which does not existwhere is the problem,['iphone'] +282428,sencha touch 2 android performance i am hearing that sencha in general by the mere fact of using javascript has performance issues on android devicesi am familiar with limitations of the android webview object but i was wondering if these performance claims have any merit especially with sencha touch 2 being outalthough i do not have a lower end android device i was looking through the sencha touch 2 gallery and could not find free android apps very easily so perhaps you can explain your experience with sencha touch 2 on android and what you did to make it faster,"['javascript', 'android']" +282447,having difficulty installing rubyfilemagic gem on new rhel6 server it appears to be looking for the libmagicso1 file i have that file it is located in usrlib64 i am not running this installation as the root useri am also using rvm and bundler this is the result of my bundle command when it gets to the rubyfilemagic line in my gemfileservermine ext ruby extconfrb withmagiclibchecking for magic open in ltrue no error missing required library to compile this module extconfrb failed could not create makefile due to some reason probably lack ofnecessary libraries andor headers check the mkmflog file for moredetails you may need configuration optionsupdatehere are the results of the mkmfloghave library checking for magic open in ltrue nogcc o conftest i iusrlocalrvmrubiesruby187p358libruby18x86 64linux i g o2 fpic conftestc l lusrlocalrvmrubiesruby187p358lib wlrusrlocalrvmrubiesruby187p358lib l rdynamic wlexportdynamic lrubystatic ltrue lrt ldl lcrypt lm lcconftestc in function ataconftestc3 error amagic opena undeclared first use in this functionconftestc3 error each undeclared identifier is reported only onceconftestc3 error for each function it appears inchecked program was begin 1 top2 int main return 0 3 int t void volatile p p void magic open return 0 end gcc o conftest i iusrlocalrvmrubiesruby187p358libruby18x86 64linux i g o2 fpic conftestc l lusrlocalrvmrubiesruby187p358lib wlrusrlocalrvmrubiesruby187p358lib l rdynamic wlexportdynamic lrubystatic ltrue lrt ldl lcrypt lm lcusrbinld cannot find ltruecollect2 ld returned 1 exit statuschecked program was begin 1 top2 int main return 0 3 int t magic open return 0 end i cannot figure out what to do to make this work,['ruby'] +282467,entity framework stored procedure return value i am trying to get the return value of a stored procedure here is an example of such a stored procedureselect name isenabledfrom dbosomethingwhere id idif rowcount 0 return 1 returnthis is a simple select if 0 rows are found my result set will be null but i will still have a return valuethis is a bad example as this is a select so sure i could find if 0 rows were returned however on an insert delete or other calls we need this return value to know if there was a problem i have been unable to find a way to get this return value i can get output values i can get result sets but no return valuei can get the return value if i call sql manually or even if i run a sqlcommand using the entity framework but this is not what i want to dohas anyone ever been able to get the return value from a stored procedure using entity frameworkthanks for the help,"['c#', 'sql']" +282475,final array in java the following code in java uses a final array of string and there is no question about itfinal public class main public static final string constant array i can never change public static void mainstring args for int x 0 x constant arraylength x systemoutprintconstant arrayx it thisplays the following output on the consolei can never changethe following code also goes without any questionfinal public class main public static final string constant array i can never change public static void mainstring args constant arrayi can never change error can not assign to final variable constant array for int x 0 x constant arraylength x systemoutprintconstant arrayx obviously the commented line causes the specified error because we are trying to reassign the declared final array of type stringwhat about the following codefinal public class main public static final string constant array i can never change public static void mainstring args constant array2 always compiles fine for int x 0 x constant arraylength x systemoutprintconstant arrayx and it thisplays i can always change means that we could manage to modify the value of the final array of type string can we ever modify the entire array in this way without violating the rule of final,['java'] +282477,c set registry value throws unauthorizedaccessexception i have a c application and i am trying to edit a service through the registry i am using a manifest file that requires administrator privileges to run my application despite that this code throws systemunauthorizedaccessexception cannot write to the registry keyregistrykey key registrylocalmachineopensubkey systemcurrentcontrolsetservicestomcat7keysetvalue start 2 registryvaluekinddworddoes anybody have any ideas for how to fix this,['c#'] +282499,aspnet user control instance is null when referenced on page load on page code behind i have a user control that i have written and have added to an aspnet page and functions just fine however i am trying to reference a property in the that custom control from code behind on page load but cannot because the variable which is accessible for the instance is nullis this normal for user controls and page load and if so how can i make a reference to the controls instance in order to access its public properties this is something i need to do before the page is rendered in order to initialize some variables,['asp.net'] +282504,do extension methods benefit in any practical way from being a part of a static class vs theoretically a part of a namespace when it comes to extension methods class names seem to do nothing but provide a grouping which is what namespaces do as soon as i include the namespace i get all the extension methods in the namespace so my question comes down to this is there some value i can get from the extension methods being in the static classi realize it is a compiler requirement for them to be put into a static class but it seems like from an organizational perspective it would be reasonable for it to be legal to allow extension methods to be defined in namespaces without classes surrounding them rephrasing the above question another way is there any practical benefit or help in some scenario i get as a developer from having extension methods attached to the class vs attached to the namespacei am basically just looking to gain some intuition confirmation or insight i suspect it is may be that it was easiest to implement extension methods that way and was not worth the time to allow extension methods to exist on their own in namespaces,['c#'] +282519,incompatible character encoding in simple sinatra app i have a very simple sinatra app running on ruby 193 that uses erb and markdown templates i have stripped it right down to demonstrate the problem this is running sinatra 132 on mac os x snow leopard for the markdown i am using rthiscount 168the main ruby file containsget services do erb servicesendthe serviceserb file has the following in it markdown contentservice1 ainside the markdown file i have just a single line awhen i run the sinatra app and load the services page i get the exception encodingcompatibilityerror at services incompatible character encodings utf8 and ascii8bit on the second line of the erb file the one containing just the a i have done lots of googling and i cannot for the life of me figure out why this is happening the erb and markdown files are utf8 on my local thisk but obviously they are being loaded by sinatra and turned into strings and i have no idea how to tell what encoding those strings are if i force sinatra to use ascii8bit by adding settingsdefault encoding ascii8bit to the top of my main sinatra ruby file then no exception is thrown but the a characters come out looking wrongany pointers,['ruby'] +282544,c11 friendly graphics library after several years of developing in other languages i am getting back into c because of some of the nice features being introduced with iso c11 are there any libraries directxopengl based that make use of these new features in their public api shared ptrs lambda friendly etcedit the library can be in beta status too as i do not expect any library to be commerciallyready on a spec that is not fully released yet,['c++'] +282593,how can i initialize a linkedlist with entriesvalues in it so i know how to have a linked list and use add method to input entries by entrieshowever i do not want to add entries by entries is there a way to declare a linkedlist with initial values in the listfor example if i want to have 10 20 in the list is there something i can do in one linesomething likelistdouble temp1 new linkedlistdouble12,['java'] +282629,c set probing privatepath without appconfig i have a c application and to organize its files i have some dlls in a folder called data i want the exe to check this folder for the dlls just like how it checks its current directory if i created a appconfig with this informationxml version10 encodingutf8 configuration runtime assemblybinding xmlnsurnschemasmicrosoftcomasmv1 probing privatepathdata assemblybinding runtimeconfigurationit works without a problem i do not want to have an appconfig is there a way to set the probing path without using an appconfig,['c#'] +282664,nsnotificationcenter list of observers is is possible to get the list of observers objects and selectors for a given notification name nsnotificationcenter,['objective-c'] +282678,django foreign key get related model is it possible to get the related model of a foreign key through the foreign key field itselffor example if i have 3 modelsclass modelamodelsmodel field1 modelscharfieldmax length10class modelbmodelsmodel field1 modelscharfieldmax length10class modelcmodelsmodel field1 modelscharfieldmax length10 field2 modelsforeignkeymodela field3 modelsforeignkeymodelband i want to dofor field in modelc metafields if fieldget internal type foreignkey get the related model for field eg modela or modelbis this possible using just the models themselves rather than instances of the models,['python'] +282679,how should i represent a chess bitboard in clojure what are some of the possible ways of representing a chess bitboard in clojure javai need to be able to access individual bits and also perform bitwise operationsi thought of using javalanglong but this causes issues with 1x1063 because of the signage i am also not sure how i would access bits at a specific indexi also looked at bitset but i need a fixed length ideally,['java'] +282693,how to automate javascript combining and minification in groups of files for different webpages let us say my page structure is 1 onehtml includes ajs bjs cjs djs2 twohtml includes ajs bjs xjs yjs zjs3 threehtml includes ajs bjs sjs xjs yjsand so onsome pages are more visited than others say 3 pages contribute 99 of all page views of the websitei am looking for a solution toi combine and minimize files in groups which can be included in the pagesii has some logic to map files names of the group to final combined file namei includes a minifier like google closure compiler yui compressorone solution i have looked at isphp minifywhich does most of it however it has following drawbacks for mei i would be hosting my static combined files on a cdn servernot on same web server hosting php minify hence php minifys logic to server files by group name does not work for meii php minify uses php cgi to process and serve the scripts whereas i would want my minified content to be served directly from the cdn serverdoes php minify have some functions to map group name to combined file name which i can use in my webpage to directly set cdn path of the combined js file egphp groupname arrayonepage arrayajsbjscjsdjsscript typetextjavascript srcphp getmergedfilenamegroupnamescriptrather than calling php minifys php script to get files of a group which isactually a php page callwhich then serves the javascript content from previouslygenerated filesscript typetextjavascript src script i agree most of this is doable by combining different solutions with custom deployment scripts and minifying tools eg antfabric yuicompressorclosurecompiler but i am looking for a well developed configurable solution that i might have missed,['javascript'] +282700,simple javascript highlighting in a text area i have two simple textareas where in i want to highlight the javascript code being written as soon as the user types the function in the text area the keywords etc have to be thisplayed in different color or so i tried to hack this script but couldnt get what i wanted,"['javascript', 'html']" +282819,php object or an array i am writing an app that allows users to modify and change some of their site settings i am just constructing a form generator that will send various options to variuous plugins to generate the code what i am wondering is whether i should be using objects for this rather than multidimensional arrays if so how would i change my codeso right now i have made this its very long and going to get longer so i have only pasted part of it for the sake of brevityscopesettings array site background array subpanels array colour array plugins array colourchooser array tip the background colour appears underneath the background image if sethover over the around the colour chooser for extra tips on how to use it element body gradientenabled true opts array closed true advanced array tip you can paste in your own generated gradient codes in here checkbox true end advanced end opts end colour chooser end plugins end colour sub panel pattern array plugins array patternselector array tip use the pattern selector to apply effects like moire or scan lines to your background image element patimg end patternselector end plugins end pattern sub panel end subpanels end site backgroundend scope settingswhat would be best practice with this sort of thing,['php'] +282848,how to draw smooth lines in 2d scene with opengl without using gl line smooth since gl line smooth is not hardware accelerated nor supported on all gfx cards how do you draw smooth lines in 2d mode which would look as good as with gl line smooth edit2 my current solution is to draw a line from 2 quads which fade to zero transparency from edges and the colors in between those 2 quads would be the line color it works good enough for basic smooth lines rendering and doesnt use texturing and thus is very fast to render,['c++'] +282870,is there a way to deploy into a vagrant vm using capistrano i would like to setup a vagrant instance outside of my project directory is there a way to deploy rails into the vagrant vm with capistrano as i would to my real production hosti am trying to use server as localhost but i getconnection failed for localhost errnoeconnrefused connection refused connect2,['ruby-on-rails'] +282873,sencha touch 2 phonegap ipad video with base64 encoded data the operation could not be completed my application wrapped in phonegap runs both online and offline mode i store images and videos encoded in base64 in localstoragewhen i debug this on browser it runs just fine but on ipad it shouts out the operation could not be completed in a javascript promt i have tried placing the video with pure html tag and tru extvideoi am missing anything here thanksnewhtml video width320 height240 controlscontrols source srcdatavideomp4base64tmpstoregetatidatamypagesjmyproductskmyitens0filedata videoupdatetested in ipad and android 30 native browsers and the result is the same the operationtested with and without autoplay and controllers in the videosource tags,"['javascript', 'android', 'ios']" +282883,selenium extract text of a div with cselector in java i am writing a junit test for a webpage using selenium and i am trying to verify that the expected text exists within a page the code of the webpage i am testing looks like thisdiv idrecipient div 3 classlabel spacer label classnothisplay forrecipient nickname recipient field reqd info label span idrecipient nickname div 2 classrequiredfield span recipientdivi want to compare what is expected with what is on the page so i want to use assertasserttrue i know that to get everything from the div i can dostring element driverfindelementbycselectordividrecipient div 3gettextreplacealln but this will return reqd info recipientis there any way to just get the text from the div recipient using cselector without the other tags,['java'] +282953,how can i use google gson to deserialize a json array into a a collection of a generic type i am writing some code that is going to be used to retrieve resources from a website it all sort of looks like thispublic collectionproject getprojects string json getjsondatamethodsgetprojectclass gets a json list ie 1 2 3 4 gson gson new gson type collectiontype new typetokencollectionproject gettype return gsonfromjsonjson collectiontype so naturally i tried abstracting it using java generics deserialize a json list and return a collection of the given type example usage getdataaccountquotaclass collectionaccountquota suppresswarningsunchecked public t collectiont getdataclasst cls string json getjsondatamethodsgetcls gets a json list ie 1 2 3 4 gson gson new gson type collectiontype new typetokencollectiontgettype return collectiont gsonfromjsonjson collectiontypethe generic version of the code does not quite work thoughpublic void testgetitemfromgetdata throws userloginerror serverloginerror mapstringstring userdata gobblerauthenticatorauthenticate mypassword string client key userdatagetclient key gobblerclient gobblerclient new gobblerclientclient key arraylistproject machines new arraylistproject machinesaddallgobblerclientgetdataprojectclass asserttruemachinesget0getclass projectclass logimachine gobblerclientgetdataprojectclasstostring javalangclasscastexception javautillinkedhashmap cannot be cast to comgobblersynchronizationmachineat comgobblertestgobblerclienttesttestgetitemfromgetdatagobblerclienttestjava53at javalangreflectmethodinvokenativenative methodat androidtestandroidtestrunnerruntestandroidtestrunnerjava169at androidtestandroidtestrunnerruntestandroidtestrunnerjava154at androidtestinstrumentationtestrunneronstartinstrumentationtestrunnerjava545at androidappinstrumentationinstrumentationthreadruninstrumentationjava1551the class in questionimport javautilmappublic class project private int total bytes stored private string name private string user data guid private int seqnum private string guid private map current checkpoint private mapstring string upload folder todo schema version private boolean deleted todo download folders public project no args constructor used for gsoni am not quite familiar with all the details of java generics or gson internals and my search has not been particularly informative there a bunch of questions here on so but most refer to implementing methods like the original one i had and the gson docs do not seem to cover this particular case so again how can i use google gson to deserialize a json array into a a collection of a generic type,['java'] +282958,is it possible to pass cout or fout to a function i am trying to find a way to pass fout or cout to a function i realize there are logically easy ways to deal with this like put ifs in any function that outputs data or even just write the function both ways however that seems primitive and inefficient i do not believe this code would ever work i am putting it here to ensure it is easy to see what i would like to do please be aware that i am taking a algorithm design class using c i am in no way a seasoned c programmer my class is limited to using the headers you seeinclude iostreaminclude iomanipinclude fstreamusing namespace stdvoid helloworldcharofstream foutint main foutopencoutfoutdat helloworldc helloworldf return 0void helloworldchar x xout hello world return,['c++'] +282960,convert array of json object strings to array of js objects i would like to convert an array of json string to array of json object without looping through each item and parse it using jsonparseexamplevar s select11 photocount12 select21 photocount22 select31 photocount32,"['javascript', 'jquery']" +282996,javascript json comparisondiff say i have the following 2 json objectsjson afield a1field b2field dsomethingfield e6json bfield a1field b2field c3field ddifferentsample function function jsonstringa jsonstringb example if json a and json b used as parametersreturns a new json object containingfield c3 because function sees jsonstringb had no field cfield d different sees jsonstringb had a different value for field dnote that it is using jsonstringa as the base of the comparison so the function returns only the fields missing and values of jsonstringb that is why field e and its value is not returnedwhat is the best way if possible to come up with a function that returns a json object containing values that have changedwhat i have triedi have tried doing a comparison by manually specifying the fields that i am trying to check for but i would like to have something that requires me to not hardcode the fields as it is very inefficient and everytime i add a new field to json b i have to hardcode in the field i am looking for that is why i am looking for something less of a pain,['javascript'] +283023,empty method name what does this actually do i am currently learning myself objectivec and ios programming and found myself stuck with nonworking code due to this subtle error for an hourconsider the following codeproperty strong nonatomic nsstring name nsstring name return some name at first glance and for anyone new this looks like an overridden getter for the name property but theres a very subtle that should not be there you get no warningerror from the compilerparserruntime here so my question is what does this actually end up asi tried to figure a way of calling this method once i saw the error but did not succeed in my few attempts,"['objective-c', 'ios']" +283057,what defines an active thread in java concurrency what makes a thread active just the fact that it is not idling is a waiting or suspended thread still considered technically active,['java'] +283058,what to put in a default label of a switch let us say i have an enumerationenum class shapename char trianglecirclesquareand later i have a function like this void function shapename const shape switch shape case shapenametriangle dosomething1 break case shapenamecircle dosomething2 break case shapenamesquare dosomething3 break default this code block should never be executed returnalthough the default label should never be executed i want to account for the potential bugs that may arise if a programmer adds another value to shapename and it is not accounted for in the switchwhat would you recommended i do 1 assertionsi could use an assertion but what am i assertingassertfalse 2 exceptionsi could throw an exception but i do not think that would be very good practice i am under the impression that exceptions are for run time events that can not be predicted because of certain environments 3 exitsi can just exit the program immediately with an errorthat feels like the best idea but i am unsure if it is good practice i thought the advantage of assertions was that you could turn them all off when you were ready ship the program then all that assertion code would no longer existmaybe there is another way that i am not aware of i do use a compiler flag that warns about unaccounted for values but i still want to know what others recommend,['c++'] +283064,access value column index and row ptr data from scipy csr sparse matrix i have a large matrix that i would like to convert to sparse csr formatwhen i doimport scipy as spks spsparsecsr matrixaprint kswhere a is dense i get 0 0 21166890240 0 1 3946200320 0 2 5881426560 0 12 15674324480 0 14 362731640 0 24 2326080 0 25 236771920 0 26 3157833920 0 45 1579619680 0 46 1736328160etci can get vectors of row index column index and value usingknz ksnonzerosparserows knz0sparsecols knz1the nonzero value of k at each rowcol vals npemptysparserowsshapeastypenpfloatfor i in rangelensparserows valsi ksparserowsisparsecolsibut is it possible to extract the vectors supposedly contained in the sparse csr format value column index row pointerscipys documentation explains that a csr matrix could be generated from those three vectors but i would like to do the opposite get those three vectors outwhat am i missingthanks for the time,['python'] +283068,why is stringisnullorempty faster than stringlength ilspy shows that stringisnullorempty is implemented in terms of stringlength but then why is stringisnulloremptys faster than slength 0for example it is 5 faster in this benchmarkvar stopwatches enumerablerange0 4select new stopwatchtoarrayvar strings abcdefghijklmnopqrstuvwxyzsplitvar testers new funcstring bool s s stringempty s slength 0 s stringisnulloremptys s s int count 0for int i 0 i 10 i stopwatchesi 4start for int j 0 j 10 j count stringscounttestersi 4 stopwatchesi 4stopother benchmarks show similar results this one minimized the effect of cruft running on my computer also as an aside the tests comparing to empty strings came out the same at about 13 slower than isnulloremptyadditionally why is isnullorempty only faster on x86 whereas on x64 stringlength is about 9 fasterupdate test setup details net 40 running on 64bit windows 7 intel core i5 processor console project compiled with optimize code enabled however suppress jit optimization on module load was also enabled see accepted answer and commentswith optimization fully enabled length is about 14 faster than isnullorempty with the delegate and other overhead removed as in this testvar strings abcdefghijklmnopqrstuvwxyzsplitint count 0for uint i 0 i 10 i count stringsi 32length 0 1 0 replace length test with stringisnullorempty,"['c#', '.net']" +283071,how to check if a tr contains a td with a specific css class with jquery i know you can use find to find tdcontainstext but if i have a tr with say 3 tds and one of the tds might have claspecialclass someotherclass may potentially have other classes in addition to special class how do i use jquery to check if a tr contains a td of specialclass,"['jquery', 'css']" +283088,phonegap thisable screen rotate on single page i am using phonegap and am working with an android web based apphow do i thisable screen rotation for only one pagei have searched for this solution but all the solutions say to thisable screen rotation in the androidmanifestxml file however this thisables rotation for the whole app i only need to thisable rotation for one pagecan this be done using phonegap javascript code i am not using any java codethanks,"['javascript', 'android']" +283089,is there a browser event that fires when the os x scroll bar style changes os x lion and above allow the user to turn onoff iosstyle floating scroll bars either manually via system preferences or by plugging in a mousewebkitbased browsers and maybe opera switch their scroll bar style immediately is there an event that fires when this occurs webkitonly is just finesome notesos x fires nspreferredscrollerstyledidchangenotification when the user switches their scroll bar stylewebkit does not appear to subscribe to this event no hits when grepping for iti suspect that webkit is handling this via the nsviewboundsdidchangenotification event which i assume fires for the scroll views content viewwebkit handles this event within webhtmlview frameorboundschanged which seems like one potential relayouting pointthere are also references to this notification in webpdfview and the inspectors webnodehighlight both seem unrelated to this casewebdynamicscrollbarsview adjustforscrolloriginchange seems to indicate that events may not be fired if so it would be nice to see some confirmationpolling for changes is not an acceptable answer to me performance the layout jumping after the user changes the value,['javascript'] +283092,cssdefined font not found possible duplicatefontface not working on a client site i have the following font files in this folder structure in my aspnet mvc web approot publicfontsnuvowebmedieotnuvowebmediwoffin my css file i have the following font declarationfontface fontfamily nuvoweb src urlpublicfontsnuvowebmedieotfontface fontfamily nuvoweb src urlpublicfontsnuvowebmediwoff formatwoffhowever when i run the app firebug returns the following errornetworkerror 404 not found httplocalhost60194publicfontsnuvowebmediwoffplease advise as to what i am missing in order to get this to work,['css'] +283151,delete with a percentage on total count let us say i want to delete 10 of rows is there a query to do thissomething likedelete from tbl where conditions limit select count from tbl where conditions 01,"['mysql', 'sql']" +283164,libxml2 cana t get content from node i am using libxml in c and this is how i create xmlxmldocptr createxmlsegmentchar headercontent char datacontent xmldocptr doc doc xmlnewdocbad cast 10 xmlnodeptr rdt header data rdt xmlnewnodenull bad cast rdtsegment xmlsetproprdt id 1 header xmlnewnodenullbad cast header data xmlnewnodenull bad cast data xmlnodesetcontentheader bad cast headercontent xmlnodesetcontentdata bad cast datacontent xmladdchildrdt header xmladdchildrdt data xmldocsetrootelementdoc rdt return docand this is how i want get data from that xmlint getdatafromxmlsegmentchar data char header char content xmldocptr doc xmlreadmemorydata strlendata null null xml parse noblanks xmlnode rdt docchildren xmlnode headernode rdtchildren header char headernodecontent content char headernodenextcontent printfheader s content s header content return exit successwhen i test headernodename or nextname then the names are correct ita s names of that elements but content returns null anyone knows where is problem,['c'] +283190,setting value for one column of all records in table i am trying to clear one column for all records in my tablefor example if my table had three columns id comment and likes i would like to be able to clear the likes columnid commentlikes1 hi 3 2 hello 12 3 hey 1 so that afterwards it would look like thisid commentlikes1 hi 2 hello 3 hey i am guessing i would have to use mysql update to clear the likes value but how do i iterate through all records and keep the id and comment field the samedo not want to change each record manually,['mysql'] +283194,null canvas in surfaceview thread despite stopping thread in surfacedestroyed only on android 4 ics i have a surfaceview extension where the bare bones of it are implemented as in the lunar lander example that is the run method of the drawing thread is essentiallypublic void run while mrun canvas c try c msurfaceholderlockcanvas synchronized msurfaceholder dodrawc main drawing method not included in this code snippet finally do this in a finally so that if an exception is thrown during the above we do not leave the surface in an inconsistent state if c null msurfaceholderunlockcanvasandpostc and the thread is properly stopped when the surface is destroyedpublic void surfacedestroyedsurfaceholder holder we have to tell thread to shut down wait for it to finish or else it might touch the surface after we return and explode boolean retry true threadsetrunningfalse while retry try threadjoin retry false catch interruptedexception e on devices i have usually tested on to date htc desire desire hd and archos 101 which between them have os 22 and 233 if i remember right there has never been a problem with the above that is when the surface is destroyed because the user backs out of the activity or another activity is invoked on top the code within surfacedestroyed always ensures that msurfaceholderlockcanvas would never be called for it to return null the difference i have found on my new htc one x which is running android 4 ics however is that during the call to method surfacedestroyed ie code within that method is still executing my drawing thread would be given a null canvas from msurfaceholderlockcanvas this would of course cause an application crash on my one x this will happen every single time the surface is destroyed whether it be due to rotating the phone backing out of the activity etc i am confused about this because i was under the impression that msurfaceholderlockcanvas should return a nonnull canvas until surfacedestroyed has actually exited indeed this is what the javadoc saysthis is called immediately before a surface is being destroyed after returning from this call you should no longer try to access this surface if you have a rendering thread that directly accesses the surface you must ensure that thread is no longer touching the surface before returning from this functionmy solution for now is to just check for null this works fineifc null dodrawc main drawing method not included in this code snippetbut any ideas why i am suddenly having to do this for android 4 ics,['android'] +283196,binary number representation first this is not a question about precision or anything like thatmy question is how does the compiler decide how to represent a numberlet us take c for example i writedouble d 45632how does it pick its binary representation i know it is not represented exactly so how does it choose the closest representable number is it done at compile time is it done by the cpu or the osplease only answer if you know how this happens answers like do not worry about it are not helpful also it depends on the platform is not helpful also you can pick a platform and explain for that,['c'] +283234,error directory index forbidden by options directive i have been working on this server for the entire semester and have not changed any configuration options the directoriesfiles i created a couple weeks ago are still accessible however any new directories even exact duplicate of old working directories do not let me access them get error directory index forbidden by options directive what is causing this,['php'] +283281,openssl using evp vs algorithm api for symmetric crypto hi i have installed openssl on my linux machine and going through the header files and documentation which is highly insufficint i am trying to build a projectin c which uses symmetric crypto algos i am focusing on aes256cbcthe problem is i am confused as in how to use the library functions in my codefor my implementation of aes256cbc i can directly use the functions defined in the aesh header filewhich appeared to me at the first placebut on googling i came accross some tutorial for this which are using evph functions to do this aesctxtis there a specific reason for this or directly accessing the aesh functions is betterand also if someone can point me to a good documentationtutorial of any kind on using the crypto library of openssl will be much appreciatedmany thanksps forgive me if i am being naive,['c'] +283285,compare two lists in python and return indices of matched values for two lists a and b how can i get the indices of values that appear in both for examplea 1 2 3 4 5b 9 7 6 5 1 0return indices of aa bwould return 04 with a0a4 15,['python'] +283303,herokucedar node express jade clientside javascript files in subdirectory work locally with foremancurl but not when pushed to heroku i am very new to node and heroku and i suspect this is some kind of simple permission issue etc but i cannot seem to track it downi have several pure javascript files in a subdirectory one level beneath my root directory where my webjs file is sitting i have a line in my webjs file to specify the directoryappuseheatcanvasexprestatic dirnameheatcanvasif i run my app locally with heroku foreman i get the expected js response when i run the following curl command curl localhost50heatcanvasheatcanvasjshowever when i push to heroku and hit the corresponsing live url in the browserwexamplecomheatcanvasheatcanvasjsi receive the following cannot get heatcanvasheatcanvasjsif i check firebug andor the heroku logs i see i am actually getting 404 errors for those files even though the pathing should match what is being done locally it is also worth mentioning that third party javascript is coming over just fine it is only when the src attribute of the script tag points to my site that there is an issue what do i need to do to get my scripts to be available,['javascript'] +283320,structure of ruby programs i need some insight into the construction of ruby programs i am trying to learn how to write ruby independent of rails so i am translating some perl scripts i wrote in a bioinformtatics project into ruby code basically creating classes where useful and whatnotmy issue is how do i execute it the perl scripts are just long blocks of commands one after the other whats appropriate in ruby should i define my classes in their own rb files and call those and their methods in a sepearate rb file that sort of uses them to execute my programwhat is normally done any examples would be greatly apreciated i would also appreciate any tips in general on how to go about learning this kind of thing,['ruby'] +283327,abstract constants in php force a child class to define a constant i noticed that you cannot have abstract constants in phpis there a way i can force a child class to define a constant which i need to use in one of the abstract class internal methods,['php'] +283370,printing a readable matrix in ruby is there a built in way of printing a readable matrix in rubyfor examplerequire matrixm1 matrix12 34print m1and have it show 1 2 3 4in the repl instead of matrix1234the ruby docs for matrix make it look like that is what should show happen but that is not what i am seeing i know that it would be trivial to write a function to do this but if there is a right way i would rather learn,['ruby'] +283372,does session timeout reset on every request does session timeout reset on every request regardless of whether we check sessions variables or we should use atleast one session variables does ajax request cause resetting session timeout like update panel jquery ajax thanksedit 1does http get cause resetting session timeout,"['jquery', 'asp.net']" +283405,supressing output from my makefile i have default gcc o function functioncwhen i type make in terminal following message is emitted useruserlaptopdesktop make gcc o function functionc useruserlaptopdesktop but i want useruserlaptopdesktop make useruserlaptopdesktop how can i do that,['c'] +283410,generating a single entity from existing database using symfony2 and doctrine is it possible to generate a single entity from database using the symfony2 console toolin the middle of coding i had to add a table and there are modifications made to the existing entity classes so i do not want all my entities regenerated any suggestions will be appreciated,['php'] +283434,what is a rack no acceptor error while trying to run my configru i am getting an odd error i cannot seem to debug called a no acceptor errorfull error messageeventmachinerb572in start tcp server no acceptor runtimeerrordoes anyone know what this error means thanks,['ruby'] +283455,what does push do in ruby i found this in gemspec file of surveyor gem what does the following line dopush fileexpand pathlib file require surveyorversionwhy does the push thing do to me it looks like its just requires the libsurveyorversion file if so cannot i just replace that with following one linerequire fileexpand pathlibsurveyorversion file are both these same thing if not then what the difference,['ruby'] +283471,boostthreads example and heap corruption message i am quite new to boostthreads i read the documentation and but i am having some trouble applying it in practice perhaps you can help first of all i have taken the time to write a self contained code listing that demonstrates 2 types of behavior that i cannot yet understandthe program allows the user to issue 3 different commands task nameinfoquitthe purpose is that task will launch some work on a new thread but then return back to the command prompt while the work is carried out the user can give the info command to find out which tasks have completed and which have notim using a dual core win7 machine and visual studio 2008 expressproblem 1issuing the command task p1 p2 p3 starts 3 tasks running this can be checked by issuing info after a few seconds the work is complete however for some reason the completed flag is not always set true on 1 or 2 of the tasksproblem 2quiting the program then produces the following messagewindows has triggered a breakpoint in exampleexe this may be due to a corruption of the heap which indicates a bug in exampleexe or any of the dlls it has loaded this may also be due to the user pressing f12 while exampleexe has focus the output window may have more diagnostic informationhopefully you can reproduce this behavior and helpthanks in advancealex warning this code does not behave exactly as intendedinclude iostream include stringinclude sstreaminclude boostthreadhpp using namespace stdclass task public string mname bool completed void start int a 0 for int i0 i10 i for int j0 j10 j a i2 thiscompleted true taskstring name mname name completed false class taskmanager public boostthread group threads void starttask string name add new task to vector list mtaskspush back taskname execute start on a new thread threadscreate thread boostbind taskstart mtasksback int taskstotal return mtaskssize string taskinfoint i string compstrnot completed if mtasksicompleted true compstr completed return mtasksimname compstr private vectortask mtasks int mainint argc char argv string cmd temp stringstream os bool quit false taskmanager mm cout prompt while quit false wait for a valid command from user getlinecincmd reset stringstream and assign new cmd string osclear os os cmd parse input string while os temp if tempcomparetask 0 while os temp mmstarttask temp if tempcompareinfo 0 returns a list of all completed and not completed tasks for int i 0 immtaskstotal i cout mmtaskinfoic str endl if tempcomparequit 0 quit true cout prompt mmthreadsjoin all return 0,['c++'] +283473,thisplay two png images simultaneously using pylab i want to open two png image files and thisplay them side by side for visual comparisoni have this code for opening one png file which i got from unutbu on stackoverflowcomimport numpy as npimport pylabimport matplotlibcm as cmimport imagefnamefilepngimageimageopenfnameconvertlarrnpasarrayimagepylabimshowarrcmapcmgreys rpylabtitletitlepylabshowis there a way to modify this code to open and thisplay 2 png files side by side with their own titles,['python'] +283480,converting a pandas groupby object to dataframe i am starting with input data like thisdf1 pandasdataframe name alice bob mallory mallory bob mallory city seattle seattle portland seattle seattle portland which when printed appears as this city name0 seattle alice1 seattle bob2 portland mallory3 seattle mallory4 seattle bob5 portland mallorygrouping is simple enoughg1 df1groupby name city countand printing yields a groupby object city namename cityalice seattle 1 1bob seattle 2 2mallory portland 2 2 seattle 1 1but what i want eventually is another dataframe object that contains all the rows in the groupby object in other words i want to get the following result city namename cityalice seattle 1 1bob seattle 2 2mallory portland 2 2mallory seattle 1 1i cannot quite see how to accomplish this in the pandas documentation any hints would be welcome,['python'] +283503,in intellij how to set the android api level i am using the latest and greatest intellij community edition my application runs fine on the android emulator however i need the emulator to better match the kindle fire i made the configuration changes in the avd manager including setting device to api 10when i went to my project to configure the project to target the new virtual device i got the following message build target of avd dev3 is not compatible with your build targetit did not take much work to figure out that the issue is related to my choice of api 10i do not know where i tell my project to use api 10 i looked all over and did not see any references to the api level at all any ideasediti addedusessdk androidminsdkversion10 to my androidmanifestxml file and was able to select the new device i am starting it up now,['android'] +283514,storing arbitrary metadata with a plaintext file i am writing a texteditor and i would need to store a few pieces of information generally just a few strings the storage need not be particularly durable with each file the app saves without that being part of the textfile as other apps might read it and the info is only specific to my apphow would i go about this more info i have a nsdocument set up and i would like to simply store a nsstring instance variable as a per file metadatum based on the answers below i have come up with this which is currently buggy and causes the program to crash on startupimport sysxattrhinterface mydocument nsdocument nsstring metadatumimplementation mydocument boolwritetourlnsurl url oftypensstring type errornserror err bool output super writetourlurl oftypetype errorerr ifsetxattrurl path cstringusingencodingnsutf8stringencoding eugamplemanxattrsstyle metadatum cstringusingencodingnsutf8stringencoding sizeofchar stylename length 0 0 nslogwrite failure return output boolreadfromurlnsurl url oftypensstring type errornserror err char output ssize t bytes getxattrurl path cstringusingencodingnsutf8stringencoding eugamplemanxattrsstyle output 1024 0 0 if bytes 0 metadatum nsstring alloc initwithbytesoutput lengthbytes encodingnsutf8stringencoding crashes here with exc bad access return super readfromurlurl oftypetype error err fairly standard dataoftypeerror and readfromdataoftypeerror implementationsps if your answer is really good with sample code etc i will award a 100rep bounty,['objective-c'] +283516,curiously recurring template variation regarding crp if i want to implement a slight variation of it using template template parameter i get a compile errortemplate template typename t class derivedclass basepublic void callderived derived pt static castderived this ptaction instantiation invocation error here templatetypename tclass derived public basederivedpublic void action i am not exactly sure one would chose this form that does not compile for me instead of using this though this workstemplate typename derivedclass basepublic void callderived derived pt static castderived this ptaction templatetypename tclass derived public basederivedtpublic void action,['c++'] +283522,matplotlib annotating a 3d scatter plot i am trying to generate a 3d scatter plot using matplotlib i would like to annotate individual points like the 2d case herematplotlib how to put individual tags for a scatter ploti have tried to use this function and consulted the matplotlib docoment but found it seems that the library does not support 3d annotation does anyone know how to do thisthanks,['python'] +283527,google app engine strange delay i improved a lot my code and now all the api run really fast i also added memcache and i have a great hit ratio but sometimes i get meaningless delays i attached here the most significant appstats screenshot more than 20 seconds in total to run 90ms of rpcs how is it possible where should i look to find the origin of those delaysi am really stuck because i do not understand whats happening between the rpcs and i do not know what else i can do in order to get more informationsjust a thought each http call is handled by the same gae instance right because my instances took a lot of time to warmup but i do not think it is relatedbtw i am coding in java,['java'] +283546,jslints tolerate stupidity anyone know what jslints tolerate stupidity option is all about what family of warnings does it thisablei have found some reference to nodejs and sync methods including crockfords comment that it is very well named but no clear answerthanks,['javascript'] +283561,how to configure syslog so that an applications log goes to a specific file i have an application myapp which should send log files only to varlogmyapplog myapp is written in c the following sample code sends the logs to varlogsyslog only my os is linux ubuntu 1204 to be specific i also found that my machine has rsyslog than syslog installedinclude stdiohinclude unistdhinclude sysloghint mainvoid openlogmyapp log pidlog cons log user sysloglog info abc 10 closelog return 0,['c++'] +283614,how to use json encode i am dealing with highcharts with dynamic data values retrieved from databaseby writing a query i was able to retrieve the following data from the tableitem 2011 2012pen 5 7pencil 4 20eraser 6 43i want to store the above info in the following structure and pass it to another page namepen data 57 namepencil data 420 nameeraser data 643i want to push the above data to the drilldown highchartis there a way i can generate in this format i have tried using json encode but unable to succeedcan i achieve this using json encodeupdatedi have tried in this waywhilerow mysql fetch assocresult rows row echo json encoderowsand gotitempen2011520127itempencil20114201220itemeraser20116201243,"['php', 'jquery']" +283619,limit results of each in handlebarsjs i have written a small plugin that thisplays tweets following is the code that loops and thisplays the tweets script idtweetstemplate typetextxhandlebarstemplate each this li ptweetp span idauthorauthorspan li each scriptbut what i want to do is limit the number of tweets to 5 or 10 but the loop is listing all the available tweets how do i limit the tweets like in for loop like fori0i5ithisplay the tweets,"['jquery', 'html']" +283637,escape character in less css inserts unwanted spaces i am trying to write the less code corresponding to the following css code for generating gradient in iefilterprogiddximagetransformmicrosoftgradientstartcolorstrff9600endcolorstrff6900following is the less codegradientstart color end color filterprogiddximagetransformmicrosoftgradientstartcolorstrstart colorendcolorstrend colorgradientff9600ff6900on compilation it gives the following css codefilter progiddximagetransformmicrosoftgradientstartcolorstr ff9600 endcolorstr ff6900 as you can see there are spaces inserted on both sides of the color values because of which ie does not read the colors correctly i have compiled the less code using as well as and both are providing the same results is there a hack to avoid these spaces thanks,['css'] +283689,android polyline encoding algorithm in my android project i have list of geopoints i have a algorithm to decode the encoded polyline string can anyone help me for encoding the list of geopoints to polyline string inorder to save this in shared preferences,['android'] +283703,how to do background jobs in an aspnet mvc 3 site i am currently working on an ecommerce site and there is one feature that i am not very sure how to implement most of the time you just add products to your cart and buy them that is probably the simplest workflow what i am asking is a little different what if there is a time limit for a product to buy i mean some sites give you an exact time limit to buy a product like soccer manager in those sites you cannot hold a product forever there is a 15 minutes limit for it and if you dont buy in that period item will be released from your cart and most probably someone else will jump on itnow as an aspnet mvc programmer i would love to implement this feature but as i said i am not sure how to do it i think when i add item to cart i need to hold the time something like itemaddedat and i need to release that item in x minutes so something needs to run x minutes later to release that product globally thinking i think i need a service when i add an item i also need to subscribe it to this service and service runs a timerjob in the background what i dont knowhave no experience is this part how to do that in an aspnet mvc project is there a sample project article library or something like that of course i dont know if my logic is right for this problem i need some guidance if possible some source code to work on,['c#'] +283707,how to start a job every day at the same hour in quartznet i have to execute job every day at midnight pacific time i am using mvc3 with quartznet libraryhere is my codepublic static void configurequartzjobs ischedulerfactory schedfact new stdschedulerfactory ischeduler sched schedfactgetscheduler datetime dateindestinationtimezone systemtimezoneinfo converttimebysystemtimezoneiddatetimeutcnow systemtimezoneinfoutcid pacific standard timedate ijobdetail job jobbuildercreatetimejob withidentityjob1 group1 build itrigger trigger triggerbuildercreate withidentitytrigger1 group1 startatdateindestinationtimezone withsimpleschedulex xwithintervalinhours24repeatforever build schedschedulejobjob trigger schedstartthis code makes this job run only once at first midnightin pacific time i have set there withsimpleschedulex xwithintervalinhours24repeatforever but it is not working job is not repeating every day what can i do to make it work every day any help much appreciated,['c#'] +283708,openal making glitch when looping sound i am playing sounds for my game with openal and i have some problems that sometimes a small glitch is played while looping also without looping i get a small popsometimes but not alli think it has something to do with the buffer being a little too long so there is some undefined data in the end i just cannot figure out how to change this i am loading a caf file with this functionvoid mygetopenalaudiodatacfurlref infileurl alsizei outdatasize alenum outdataformat alsizei outsamplerate aldouble duration osstatus err noerr sint64 thefilelengthinframes 0audiostreambasicdescription thefileformatuint32 thepropertysize sizeofthefileformatextaudiofileref extref nullvoid thedata nullaudiostreambasicdescription theoutputformat open a file with extaudiofileopenerr extaudiofileopenurlinfileurl extrefiferr printfmygetopenalaudiodata extaudiofileopenurl failed error ldn err goto exit get the audio data formaterr extaudiofilegetpropertyextref kextaudiofileproperty filedataformat thepropertysize thefileformatiferr printfmygetopenalaudiodata extaudiofilegetpropertykextaudiofileproperty filedataformat failed error ldn err goto exit if thefileformatmchannelsperframe 2 printfmygetopenalaudiodata unsupported format channel count is greater than stereon goto exit set the client format to 16 bit signed integer nativeendian data maintain the channel count and sample rate of the original source formattheoutputformatmsamplerate thefileformatmsampleratetheoutputformatmchannelsperframe thefileformatmchannelsperframetheoutputformatmformatid kaudioformatlinearpcmtheoutputformatmbytesperpacket 2 theoutputformatmchannelsperframetheoutputformatmframesperpacket 1theoutputformatmbytesperframe 2 theoutputformatmchannelsperframetheoutputformatmbitsperchannel 16theoutputformatmformatflags kaudioformatflagsnativeendian kaudioformatflagispacked kaudioformatflagissignedinteger set the desired client output data formaterr extaudiofilesetpropertyextref kextaudiofileproperty clientdataformat sizeoftheoutputformat theoutputformatiferr printfmygetopenalaudiodata extaudiofilesetpropertykextaudiofileproperty clientdataformat failed error ldn err goto exit get the total frame countthepropertysize sizeofthefilelengthinframeserr extaudiofilegetpropertyextref kextaudiofileproperty filelengthframes thepropertysize thefilelengthinframesiferr printfmygetopenalaudiodata extaudiofilegetpropertykextaudiofileproperty filelengthframes failed error ldn err goto exit read all the data into memoryuint32 datasize thefilelengthinframes theoutputformatmbytesperframethedata mallocdatasizeif thedata audiobufferlist thedatabuffer thedatabuffermnumberbuffers 1 thedatabuffermbuffers0mdatabytesize datasize thedatabuffermbuffers0mnumberchannels theoutputformatmchannelsperframe thedatabuffermbuffers0mdata thedata read the data into an audiobufferlist err extaudiofilereadextref uint32thefilelengthinframes thedatabuffer iferr noerr success outdatasize alsizeidatasize outdataformat theoutputformatmchannelsperframe 1 al format stereo16 al format mono16 outsamplerate alsizeitheoutputformatmsamplerate else failure free thedata thedata null make sure to return null printfmygetopenalaudiodata extaudiofileread failed error ldn err goto exit alexcolombiamug get the file duration first get the audioid for the fileaudiofileid audioiduint32 audioidsize sizeofaudioiderr extaudiofilegetpropertyextref kextaudiofileproperty audiofile audioidsize audioidiferr printfmygetopenalaudiodata extaudiofilegetpropertykextaudiofileproperty audiofile failed error ldn err goto exit now the durationdouble sounddurationuint32 durationsize sizeofsounddurationerr audiofilegetpropertyaudioid kaudiofilepropertyestimatedduration durationsize sounddurationiferr printfmygetopenalaudiodata audiofilegetpropertykaudiofilepropertyestimatedduration failed error ldn err goto exit duration sounddurationprintfaudio durationf secsn sounddurationexit thispose the extaudiofileref it is no longer needed if extref extaudiofilethisposeextref return thedatait is part of this soundengine soundenginei have tried to put my caf file directly into the sample code and it is the same small glitch this caf file was doing fine with the old apple soundenginecpp but i had other issues with that so i decided to change,"['iphone', 'ios']" +283723,using group by on two fields and count in sql i have a table in my mysql db that has two columns group and subgroup see below group subgroup grpa suba grpa suba grpa subb grpb suba grpb subb grpb subbi am trying to get the number of records for each unique couple groupsubgroupthis is what i expectgroup subgroup countgrpa suba 2grpa subb 1grpb suba 1grpb subb 2after reading some posts i tried several sql queries using group by count but i do not manage to get the expected result how can i fix this,"['mysql', 'sql']" +283727,is it a bad idea to store javascript and css in a database ok so i am trying to store user custom css and javascript in mysql database to be used later the head section on the page so is it a good idea to store css and javascript in a database and if not what is the safe way to do this i am using wordpress and using esc js on javascript code i noticed it adds a backslash before quotes and adds and instead of new lines so is it enough for javascript and thanks in advance,"['javascript', 'mysql', 'css']" +283780,log javascript error i want to log all js errors in my project during the betatesting time now i do it in the following waywindowonerror myerrhandlerfunction myerrhandlermessage url line ajax cache false type post data errormessage urlurl lineline brousernavigatoruseragent url homelogjavascript async true return truebut this way could not help to get any information about call stack so information about errors inside jquery or any other outer scripts could not help a lot is there any way to improve such logging,"['javascript', 'jquery']" +283817,mediastore uri to query all types of files media and nonmedia in the class mediastorefiles class its mentioned thatmedia provider table containing an index of all files in the media storage including nonmedia filesi am interested in querying for nonmedia files like pdfi am using cursorloader to query the database the second parameter for the constructor requires an uri argument which is easy to get for the media types audio images and video as each of them have a external content uri and internal content uri constant defined for themfor mediastorefiles there is no such defined constant i tried using the getcontenturi method but could not figure out the argument value for volumename i tried giving mntsdcard and also the volume name that appears when i connect the device to my system but in vaini saw a similar question on google groups but that is not resolvededit i also tried using urifromfilenew filemntsdcard and uriparsenew filemntsdcardtostring but that did not work out either,['android'] +283826,new line in nodejs i am trying to append data to a log file using nodejs and that is working fine but it is not going to the next line and does not seem to be working in my function below any suggestions thanksfunction processinput text fsopenhlogtxt a 6 function e id fswrite id text n null utf8 function fscloseid function consolelogfile is updated,['javascript'] +283846,send an email when an error occurs currently my application is using log4net to log errors the webconfig for this is as followedlog4net appender namefileappender typelog4netappenderrollingfileappender file typelog4netutilpatternstring valuelogsgateway dateymmddlog appendtofile valuetrue rollingstyle valuedate datepattern valueymmdd layout typelog4netlayoutpatternlayout conversionpattern valuedate thread 5level logger propertyndc a messagenewline layout appender root level valuedebug appenderref refrollinglogfileappenderoutput root log4nethowever the client now wants each error to be emailled to themwhat is the easiest way to do this can you do it within the webconfig file,['c#'] +283874,using a struct in a header file unknown type error i am using kdevelop in kubuntui have declared a structure in my datasetuph fileifndef a hdefine a hstruct georeg val int p double h double hfov double vfovendifnow when i use it in my mainc fileint main georeg val gval read datagval this is in a cpp filei get the following errorgeoreg chainc73 error unknown type name georeg valthis is in the georeg val gval linei would appreciate if anyone could help me resolve this error,['c'] +283880,how to get a div to randomly move around a page using jquery or css i have been doing some googling to find an answer to this but i have had no luck it could be because i am a bit of an amateur and i do not know the proper terms to search for but maybe someone here can steer me in the right direction or help me outanyway i am looking for a way to get a div to randomly smoothly move around a page there will be a background color then this image which i want to seemingly randomly infinitely move around the page much like the background of a dvd players home screen where dvd is just floating around starting point of the div does not matter nor does the ending point it just needs to randomly move around the page for the duration a user is on that pagei have got decent html and css skills very basic js skills and some experience implementing jquery ideally i would like something which i can implement myselfthanks in advance,"['jquery', 'css']" +283899,cannot get flask running using passenger wsgi on dreamhost shared hosting i am trying to get a flask hello world application working on a dreamhost shared server following the instructions on their wiki but i am not having any luckmy flask application is the hello world one from the flask quickstart guidefrom flask import flaskapp flask name approutedef hello world return hello worldif name main apprunwhich i have got in a file called hellopy in a folder called mysite as per the dh wiki instructions my passenger wsgipy file isimport sys osinterp ospathjoinosenvironhome flask env bin pythonif sysexecutable interp osexeclinterp interp sysargvsyspathappendosgetcwdfrom mysite import hello as applicationi have tried running the commands in a python console and last import line failed until i added the init py file to the mysite directorywhen i try and access the website i just get a 500 error and nothing in the logs unfortunately unless they are in logs i cannot get to as this is a shared serveras this is the most basic of setups ie copied and pasted from a wiki i cannot help feeling that i am missing something really simple or perhaps this is not possible on a shared server,['python'] +283902,wxpython 29 on mac os x i am using enthought python thistribution 72 64bit it comes without wxpython which is quite important however wxpython29 seems to support 64bit cocoa interface so i gave it a try actually it all went good the commandpython buildwxpythonpy osx cocoa mac framework installsuccessfully compiled and even got into epd sitepackageshowever a simple wxpython code import wxwxappfails with the following errorthis program needs access to the screenplease run with a framework build of python and only when you arelogged in on the main thisplay of your maccan you give me some advice how to cure this epd is clearly a python framework ie looking at libraryframeworksepd64framework and libraryframeworkspythonframework convinces me in it but this wxpython build does not know about that the version of wxpython is 2931,['python'] +283906,is there a way to set the pygame icon in the taskbar set icon only seem to affect the small icon in the actual window while running my program the icon i configured with pygamethisplayset iconicon thisplays only in the window in the taskbar the default python icon remains the same is there a way to change that sourceimport pygamefrom pygamelocals import import sys osimport timepygameinit load imagestry bg osgetcwd imagesbackgroundpng background pygameimageloadbgconvertexcept print error could not find backgroundpngtry logo osgetcwd imageslogopng c logo pygameimageloadlogoconvertexcept print error could not find logopngtry about dialog infile osgetcwd imagesabout dialogalphapng about dialog pygameimageloadabout dialog infileconvert alphaexcept passi icon osgetcwd imagesiconpngicon pygameimageloadi iconpygamethisplayset iconiconpygamethisplayset captiontest programscreensize 640480screen pygamethisplayset modescreensize032pygamethisplayset captionmy test programwhile true for event in pygameeventget if eventtype quit pygamequit sysexit if eventtype mousebuttondown check clickabout eventposscreenblitbackground 00pygamethisplayupdate,['python'] +283911,generating google map release api key my app uses google maps i signed up for a google maps key to debug it worked but now i need a google maps key in release mode before publishing how can i get it,['android'] +283934,how to get position of keyvalue in linkedhashmap using its key hi i have a linkedhashmap called info that contains nameage stringint pairs i want to find out how can i get the position of the keyvalue if i input the key for example if my linkedhashmap looked like this bob12 jeremy42 carly21 and i was to search jeremy it should return 1 as its in position 1 i was hoping i can use something like infogetindexjeremy,['java'] +283937,no visible interface for i have gotten this error on several occasions and am unclear as to what causes the error in general after looking for over an hour on stack overflow and google i still do not have an answer could someone help i have seen several specific answers but nothing that says why the error happens only do x or do yi have not included code yet because i want to know the reason that this error happens in general so i can fix my code in the future whenever i get this error,"['objective-c', 'ios']" +283945,maven jaxb2 xjc plugin m2e plugin execution not covered i am using using the jaxb2 xjc plugin for generating java files from a xsd therefore i used to configure my pomxml as followsbuild plugins plugin groupidorgcodehausmojogroupid artifactidjaxb2mavenpluginartifactid version13version executions execution phasegeneratesourcesphase goals goalxjcgoal goals execution executions configuration packagenamecommypackagemodelpackagename schemadirectorybasedirsrcmainresourcesxsdschemadirectory configuration plugin plugin groupidorgapachemavenpluginsgroupid artifactidmavencompilerpluginartifactid configuration source16source target16target configuration plugin pluginsbuildi changed my developing environment to eclipse indigo and this does not work any more the error says plugin execution not covered by lifecycle configuration i understand i have to define the execution of my plugin differently so that it works in my new environment i followed the instructions on this page m2e plugin execution not covered but the source files are not generated when executing the generatesources phasecould anybody show me how to exactly refactor my pom so that my files are properly generatedthanks for helping,['java'] +283959,solving puzzle in python i got one puzzle and i want to solve it using pythonpuzzlea merchant has a 40 kg weight which he used in his shop once it fell from his hands and was broken into 4 pieces but surprisingly now he can weigh any weight between 1 kg to 40 kg with the combination of these 4 pieces so question is what are weights of those 4 piecesnow i wanted to solve this in python the only constraint i got from the puzzle is that sum of 4 pieces is 40 with that i could filter all the set of 4 values whose sum is 40import itertools as itweight 40full range141comb x for x in itcombinationsfull4 if sumx40length of comb 297now i need to check each set of values in comb and try all the combination of operationseg if abcd is the first set of values in comb i need to check abcdabab abcdabcd and so oni tried a lot but i am stuck at this stage ie how to check all these combination of calculations to each set of 4 valuesquestion 1 i think i need to get a list all possible combination of abcd and 2 does anyone have a better idea and tell me how to go forward from herealso i want to do it completely without help of any external libraries need to use only standard libraries of pythonedit sorry for the late info its answer is 13927 which i found a few years back i have checked and verified the answer edit at present fraxels answer works perfect with time 016 ms a better and faster approach is always welcomeregardsark,['python'] +283995,about generated serialversionuid in eclipse is there any way to generate serialversionuid in eclipse serially by serially i want to mean that if one serializable class has serialversionuid 1l then when i generate serialversionuid of another class this will be serialversionuid 2lif i manually specify 1l 2l 3l and so on will this can create any problemeclipse gave an option to choose add generated serial version id is this option safe to choose,['java'] +284009,what is the best field to store the birthday i have to store in my mysql database the userss birthday like 121990 what field type do i have to use to store it,['mysql'] +284011,fragment over another fragment issue when i am showing one fragment which is full screen with 770 background over another fragment let us call it main my main fragment still reacts to clicks we can click a button even if we do not see itquestion how to prevent clicks on first main fragmenteditunfortunately i cannot just hide main fragment because i am using transparent background on second fragment so user can see what located behind,['android'] +284027,jquery click is triggering when selectinghighlighting text i have a div with a bunch of text in it this div also has a click event on it using jquerythe problem i am having is that the click is being triggered when selectinghighlighting text even holding the mouse down for several seconds before releasinghere is a jsfiddle that shows the issue the behavior that i would expect is that highlighting text is not the same as clicking on the element,"['javascript', 'jquery']" +284048,what is the meaning of a public member of an internal class for exampleinternal class c public void m consolewritelinefoo to me that reads a method that can be accessed by anyone regardless of assembly living inside a class that can only be accessed from code in the same assemblymy experience with the compiler tells me that if i do something like that and do not get a warning there is probably a valid reason to have itso i suppose eithersomething is lacking in my understanding of protection levelsthere could be a warning but there is not one if 2 this is not an attempt to complain about it i just want to understand,['c#'] +284062,how to create a query that gets only data which has been updated in a table i have no idea where to start or how this will work and i am hoping someone has an idea or a proven methodto show an example of what i am trying to do i created a stored procedure which updates or insert new records in a local table by getting records from a link table the stored procedure runs as a job in sql server to update and insert new recordsmy question is is there a way to query the data in the local table so that initially i can get all the records but than get only new records that has been inserted or old records that are updatedi do not want to continuously get all the records just the new records added or the records updatedis this possiblehere is the stored procedure i ave created as an example to updated the local phone datacreate procedure sp update phone recordsas beginmerge dbophone rec as targetusing select member id home phone dboudf stdphonefmthome cell phone dboudf stdphonefmtcell work phone dboudf stdphonefmtworkfrom phone where member id is not null as sourceon targetmember id sourcemember idwhen matched then update set targethome phone sourcehome phonetargetcell phone sourcecell phone targetwork phone sourcework phonewhen not matched by target then insert member id home phone cell phone work phone values sourcemember id sourcehome phone sourcecell phone sourcework phoneendgois this possiblethanks everyone,['sql'] +284073,why is numberprototype a number tostringcallnumberprototype object numberthe number prototype object is itself a number object its class is number whose value is 01574why would it be useful for numberprototype to be a number the same goes for every other builtin prototype which has the class set to not objecti am picking on numberprototype specifically because i can imagine sensible legacy reasons for arrayprototype and dateprototype,['javascript'] +284075,when a response to ajax is 301 can i programmatically get the new url is there a way to get the url you are ultimately redirected to when the response to an xhr request is 301i have a site that contains numerous legacy urls from an older version which return 301 responses to the correct new urlfor utility purposes i would like to be able to make a request to an old url and be able to retrieve the new one ie send request to oldpageaspxfoosomeparam get back the new url arbitarynewpagenamesomeparami have been playing around with this in the firebug console ajax url oldpageaspxfoosomeparam success functionresponse status jqxhr poking around trying to get the new url arbitrarynewpagesomeparam consolelogjqxhrgetallresponseheaders consolelogjqxhr beforesend functionjqxhr settings consolelogjqxhr consolelogsettings i can see in firebug that when this code runs it does one get to oldpageaspxfoosomeparam and gets a 301 response then another get to arbitarynewpagenamesomeparamfor the first request i see the redirected url in the location value of the response header unfortunately the second request is what is passed to the ajaxsuccess function and it only has the redirected url in the referrer value of the request headeris there perhaps a way to intercept the response to the first response or maybe see the request headers for the second requestedit thanks everyone for the responses i think i need to give a little background to clarify what exactly i am looking fora business user has asked me to create a list that associates legacy urls with new urls since i have already implemented a means of redirecting legacy urls to new urls on the server i was hoping to piggy back off that work and create a script that placed requests to the legacy urls and got the urls that the requests were redirected to something like thisfor var i 0 i arrayoflegacyurlslength i ajax url arrayoflegacyurlsi success functionresponse status jqxhr var newurl do magic to get url that request was redirected to writetofileforbusinessuserarrayoflegacyurlsi newurl the crux of my question is this can i get the url my request was redirected to from the xhr so far the answer seems to be no,"['javascript', 'jquery']" +284135,jquery mobile not working inside uiwebview i am coming here after many many hours of looking for a solution and trying different approaches to fix this issue i am having with jquery mobile and my ipad appwhat i am trying to do is a reporting app with fusion charts i have successfully rendered the charts within web views uiwebview using different methods and following different examples but what i would like to do now is accomplishing the same task using the jquery mobile frameworki am not using phonegap and i have followed the steps to the letter regarding jquery mobile xcode integration i think the charts load without a problem on my desktop and mobile browsers ipad iphone 4 and ipod touch 2g but there is no way they load inside my uiwebview even though i am using the same exact codethis is what i am doing1 adding required files js css and html to the project to use them locally after adding them i move everything with js extension from compile sources to copy bundle resources it looks like this2 load my html test file page a1html into the web view3 check that everything is set up on the html file with correct paths and latest version of frameworks4 build and run only to get a blank web viewif i test javascript with an alert like thisit will show the alert proving javascript is workingand if i put some text on the container where the chart is supposed to be thisplayedi will get the text inside the web viewi have also tested with remote framework links instead of the local ones and older version of the libraries with no luck nothing different happensit seems obvius to me thatdocumentreadyfunctionis not being noticed or invoked by xcodethis is what i would like to accomplishi do not know what else to test if you have any idea i would be more than grateful,['ios'] +284143,is it possible to swap two variables in java possible duplicateis it possible to write swap method in java given two values x and y i want to pass them into another function swap their value and view the result is this possible in java,['java'] +284150,determining resting contact between sphere and plane when using external forces this question has one major question and one minor question i believe i am right in either question from my research but not bothfor my physics loop the first thing i do is apply a gravitational force to my totalforce for a rigid body object i then check for collisions using my totalforce and my velocity my totalforce is reset to 0 0 0 after every physics loop although i will keep my velocityi am familiar with doing a collision check between a moving sphere and a static plane when using only velocity however what if i have other forces besides velocity such as gravity i put the other forces into totalforces right now i only have gravity to compensate for that when i determine that the sphere is not currently overlapping the plane i do vector3 forces spheretotalforces spherevelocity vector3 forcesdt forces felapsedtime float denom vec3dotplanegetnormal forceshowever this can be problematic for how i thought was suppose to be resting contact i thought resting contact was computed bydenom thist 00fwhere thist isfloat thist vec3dotplanegetnormal sphereposition planedfor reference the obvious denom thist 00f meaning the sphere is moving away from the planehowever this can never be true even when there appears to be resting contact this is due to my forces calculation above always having at least a y of 98 my gravity when when moving towards a plane with a normal of 0 1 0 will produce a y of denom of 98my question is1 am i calculating resting contact correctly with how i mentioned with my first two code snippetsif so2 how should my other forces such as gravity be used is my use of totalforces incorrectfor reference my timestep is macceleration mtotalforces mmass mvelocity macceleration felapsedtime vector3 translation mvelocity felapsedtimeeditsince it appears that some suggested changes will change my collision code here is how i detect my collision statesiffabsthist sphereradius there already is a collision else vector3 forces spheretotalforces spherevelocity float denom vec3dotplanegetnormal forces resting contact ifthist 0 sphere is moving away from plane else ifdenom thist 00f there will eventually be a collision else float fintersectiontime sphereradius thist denom float r ifthist 00f r sphereradius else r sphereradius vector3 collisionposition sphereposition fintersectiontime spherevelocity r planenormal,['c++'] +284152,how to create a success message within a div upon successfull form submission the following form thisplays the success message every time on page launch in the browser logically but the form should thisplay the success message only after it is submitted successfullyeditformaction serverphp selfif isset serverquery string editformaction htmlentities serverquery stringmessage record has been updated successfullyif isset postmm update postmm update form1 updatesql sprintfupdate table set names emails getsqlvaluestring postname text getsqlvaluestring postemail textmysql select dbdatabase test testresult1 mysql queryupdatesql test or diemysql error updategoto testphpif isset serverquery string updategoto strposupdategoto updategoto serverquery stringheadersprintflocation s updategotothe html part of the form is as followingform actionphp echo editformaction methodpost nameform1 idform1 table aligncenter classtest table tr valignbaseline td alignright nowrapnowrap classtabletitlenametd td classtablecontentinput typetext namename valuephp echo htmlentitiesrow username ent compat utf8 size32 td tr tr valignbaseline td alignright nowrapnowrap classtabletitleemailtd td classtablecontentinput typetext nameemail valuephp echo htmlentitiesrow useremail ent compat utf8 size32 td tr table input typehidden namemm update valueform1 input typehidden nameid valuephp echo row userid input clasubmit nameupdaterecord typesubmit idupdaterecord valueupdate record formthis is how the success message is thisplayed within a div on the pagep php if emptymessage echo div clasuccessmessage message div pwhat i am doing wrong here,"['php', 'mysql', 'html']" +284205,are vala and genie production ready i am working with some legacy c code which i need to refactor and generally clean up to remove spaghetti type programming adhere to the dry principle etci was thinking of rewriting using c but i do not want to go that far and would like to remain as close to c as possible whilst using some oop concepts without having to hand code themi recently came across gobject vala and genie the latter two are fairly recent is anyone out there aware of either vala or genie being used in production code last but not the least is there a list of pros and cons comparisons between the two languages i am leaning a bit towards genie because i love python and am not too keen on c but genies apparent insistance on tabs could be a tad annoying in practise i would be interested in a list of pros and cons for the two languages assuming one or both of them are ready for production useas an aside i am developing on linux so any windows related issues are not relevant as far as i am concerned,['c'] +284214,how do i split my javascript into modules using googles closure compiler i want to use the google closure compiler on the javascript source were usingin development mode we tend to break functionality to lots of files but for production would like to have them combined into moduleswhen calling the compiler i can give it a list of files to include for compilation but the output of that shows that the compiler did not save the order of the files listi searched about it and found that i can use googprovidegoodrequire in order to control the dependencies between the different js filesthe problem with that is that it adds code to my js which i just do not need or want for examplegoogprovidemainfilewill add thisvar mainfile to the compiled js file something that i do not wantwere not using the google closure library at all all i want to use is the compileris there a way to tell the compiler the order of the files without including more closure library functionality which i have no need fori can of course create a tool of my own which will first take all the files combine them into one which will then be the input of the compiler but i would prefer to void that if it can be done by the compiler itselfeditthe goal is to be able to produce modules like the answer in this thread using the module option in closure compiler to create multiple output filesand so i want to add to that the ability to control which files go into which module while also having control on their orderfor now i do not use wildcards but i plan to do so in the future if it is possiblesimply cat file1js file2js combinedjs compile is fine but in our case it is a bit more complicated and well have to write a programscript that does that based on some logicif we can somehow tell the compiler the order of the files in advanced it might just save the time of implementing such a programthanks,['javascript'] +284233,how to host python cgi script with python m simplehttpserver 80 or python m cgihttpserver 80 when i run python m simplehttpserver 80 or python m cgihttpserver 80 in my shell i am hosting the content of my current directory to the interneti would like to make the following cgi scriptpy work correctly using the above command in the command line when i browse to 192x80cgi scriptpyusrbinenv pythonprint contenttype texthtmlprintprint htmlbodyh2hello worldh2bodyhtmlbut this script is thisplayed literally and not only the hello world partbtw i changed the file permissions to 755 for cgi scriptpy as well as the folder i am hosting it from,['python'] +284239,center an image with a link on it is it possible to center an image only trough setting a class to the img tag without side effects the problem is the following i have an anchor around an image if i use the following cssaligncenter clear both thisplay block marginleft auto marginright autoand this stripped down htmla hrefpathtoimagejpg classfancybox relfancybox titlesystem img srcpathtoimagejpg titlesystem classaligncenterathe link takes the whole width of the main div this means not only the image is clickable also the space around the image actually the whole width is clickable this is through the css thisplay blockhow can i center an image without using a parent div i do not want the whole area clickablebackgroundyou can read this topic it is about wordpress and the built in editor he automatically generates the class aligncenter on an image if the user pressed the center button i need this for my own theme according to the moderators there this should be only a css question and does not have to do with changing code in wordpress,['css'] +284247,upload files from folders and subfolders to webapp goalallow user to select a folder then find all files recursively that matches a file pattern and transferpost to my web server in essence just a more advanced upload dialogstandard web technology were using plupload does not support this due to security reasons afaikadditional requirementseasy to useinstall from the webapp ssl and and app user credentials are needed some other data like record id get or create from web app to associate the upload files would be nicethe web app itself is written in ruby on rails but that should not really matter if i need some kind of a native mac and windows 80 of my users desktop clientwhat are my optionscode and references to open source libs for doing this is a bonus,['ruby-on-rails'] +284254,best practice when defining instance variables i am fairly new to python and have a question regarding the following classclass configuration def init self parser safeconfigparser try if parserreadconfig file is none raise ioerrorcannot open configuration file except ioerror error sysexiterror else self parser parser selffilename config file def get sectionself p self parser result for s in psections resultappend0formats return result def get infoself config section p self parser selfsection config section selfurl pgetconfig section url selfimgexpr pgetconfig section imgexpr selfimgattr1 pgetconfig section imgattr1 selfimgattr2 pgetconfig section imgattr2 selfdestination pgetconfig section destination selfcreatezip pgetconfig section createzip selfpagesnumber pgetconfig section pagesnumberis it ok to add more instance variables in another function get info in this example or is it best practice to define all instance variables in the constructor could not it lead to spaghetti code if i define new instance variables all over the placeedit i am using this code with a simple image scraper via get section i return all sections in the config file and then iterate through them to visit each site that i am scraping images from for each iteration i make a call to get section to get the configuration settings for each section in the config fileif anyone can come up with another approach it will be fine thanks,['python'] +284263,infinite scrolling setcontentoffset stops deceleration of uiscrollview i am creating an iphone app with a large 360 degree panorama image the panorama is a catiledlayer in a uiscrollview i am attempting to implement infinite scrolling on the image horizontal only i have done this by subclassing uiscrollview and implementing setcontentoffset and setcontentoffsetanimated and this works perfectly when the user is dragging the scrollview however when the user has lifted their finger and the scrollview is decelerating changing the contentoffset causes the deceleration to stop instantly voidsetcontentoffsetcgpointcontentoffset cgpoint tempcontentoffset contentoffset if inttempcontentoffsetx 5114 tempcontentoffset cgpointmake1 tempcontentoffsety else if inttempcontentoffsetx 0 tempcontentoffset cgpointmake5113 tempcontentoffsety super setcontentoffsettempcontentoffset is there any way to change the contentoffset without affecting deceleration it was suggested here that overriding setcontentoffset not setcontentoffsetanimated fixes this issue but i cannot seem to get it workingi have also tried scrollrecttovisibleanimated with no successany ideas on how to fix this problem would be greatly appreciated thankseditcode for scrollviewdidscrollvoidscrollviewdidscrollpanoramascrollview scrollview panoramascrollview setcontentoffsetpanoramascrollviewcontentoffset i also tried thisvoidscrollviewdidscrollpanoramascrollview scrollview cgpoint tempcontentoffset panoramascrollviewcontentoffset if inttempcontentoffsetx 5114 panoramascrollviewcontentoffset cgpointmake1 panoramascrollviewcontentoffsety else if inttempcontentoffsetx 0 panoramascrollviewcontentoffset cgpointmake5113 panoramascrollviewcontentoffsety,"['iphone', 'ios', 'objective-c']" +284299,jquery mobile loading message when i linked jquery mobile to my page some sort of loading message appeard in the bottom of the page and i cannot get a rid of it i have tried mobilepageloadingtrue but it did not workhow should i remove it i have not printed it anywhere,['jquery'] +284313,what is the unsigned counterpart of ptrdiff t what is the unsigned counterpart of ptrdiff tand similarly what is the signed counterpart of size twhat i am trying to achieve is to have a unsigned type that i can use to store the positive values of ptrdiff t variable without worrying about large values this seems to be size tconversely i would like to have a signed type that i can store the values of size t again without worrying about large values,['c++'] +284341,how to set text of textview i am facing a problem of setting the text to textview in android my code is public class main extends activity override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain button button button findviewbyidridbutton1 final textview text textview findviewbyidridtextview1 final edittext input edittext findviewbyidridedittext1 final string string inputgettext buttonsetonclicklistenernew onclicklistener public void onclickview v textsettextstring if i write final editable string inputgettextthen it worksnow i want to send data of edittext to next activity like this public class main extends activity override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain button button button findviewbyidridbutton1 final textview text textview findviewbyidridtextview1 final edittext input edittext findviewbyidridedittext1 final editable string inputgettext buttonsetonclicklistenernew onclicklistener public void onclickview v intent intent new intentmainthis secondclass intentputextrathetext string startactivityintent and in secondjava class i get stringextra in this waypublic class second extends activity override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutsecond textview text textview findviewbyidridtextview2 string string getintentgetextrasgetstringthetext not found textsettextstring here the text is not shown but the default message not found is set to textview please give me way to proceed in development,['android'] +284344,best way to read rss feed in net using c what is the best way to read rss feedsi am using xmltextreader to achieve this is there any other best way to do itxmltextreader reader new xmltextreaderstrurldataset ds new datasetdsreadxmlreaderafter reading the rss feed using xmltextreader is there any way i can that data to list item instead of dataset,['c#'] +284373,is there a medium weight font between systemfontofsize and boldsystemfontofsize systemfontofsize is too thin and boldsystemfontofsize too thick i need something inbetweenwhen i create a uifont like thisuifont boldsystemfontofsize14then the debugger prints this font info fontfamily helvetica neueui fontweight bold fontstyle normal fontsize 14pxsometimes fonts have a medium font weight how can i create a font of this type but with a medium weight,"['iphone', 'ios']" +284381,remove a backbone model by id can you remove a model by id the documentation says you need to pass in the model itself to remove it so i need to fetch the model first and then remove it i cannot just remove it by id,['javascript'] +284409,take screenshot of with html2canvas and store img as js var i am attempting to let users on my site push a button to take a screenshot of the current screen everything in bodyfrom my research html2canvas seems to be a resource that makes this possiblemy issue is the documentation does not provide example code and i am struggling to get a grip on the steps involvedthe following so question how to upload a screenshot using html2canvas leaves me a bit confused i just want to know how to get an image at this pointfrom his codewindowreadyfunction bodyhtml2canvas var canvasrecord new html2canvasdocumentbodycanvas at this point does the todataurl method return a pngat this point i am lost where the image is or even howwhen to create it ill worry sending it to the server laterany information appreciated thanks html2canvas even needed,['javascript'] +284411,java systemoutprintln should write to the console but it does not i am trying to write java console application the code is quite simplepublic class consoletest public static void mainstring args systemoutprintlntest if i run this application from eclipse then i see test in eclipses console but if i export my app as a runnable jar file and run it from windows xp cmdexe then nothing is echoed to the consoleon the safe side i tried to check systemconsole it returns nullwhat can be wrong,['java'] +284413,create random serial with php i want to have a random serial created on my website everytime someone visitsthe format of the serial should be x represents a random number or capital letterunfortunately i have no idea how to do this could anybody please help me outso for example the random serial output could be 3wt4anb34oju87pb3uhsthanks a lot,['php'] +284415,symfony 2 doctrine 2 inheritance i am searching for a solution for the following problem with a database inheritance using doctrine 2 built in symfony 2 framework this is what i want to doi want to create two tables urednihodiny konzultacnihodiny with the same interface as the abstract class hodiny this is how i am trying to do itphp srccvutpwtimportbundleentityhodinyphpnamespace cvutpwtimportbundleentityuse doctrineormmapping as orm ormmappedsuperclass abstract class hodiny ormid ormcolumntypeinteger ormgeneratedvaluestrategyauto protected id ormmanytoonetargetentityosoba protected osoba ormmanytoonetargetentitymistnost protected mistnost ormcolumntypedatetime protected zacatek ormcolumntypedatetime protected konecphp srccvutpwtimportbundleentitykonzultacnihodinyphpnamespace cvutpwtimportbundleentityuse doctrineormmapping as orm ormentity ormtablenamekonzultacnihodiny class konzultacnihodiny extends hodiny php srccvutpwtimportbundleentityurednihodinyphpnamespace cvutpwtimportbundleentityuse doctrineormmapping as orm ormentity ormtablenameurednihodiny class urednihodiny extends hodiny now when i run php appconsole doctrinegenerateentities cvutpwtimportbundle symfony generates all variables more precisely columns from class hodiny as private variables to both child classes now when i am trying to create those tables with appconsole doctrineschemaupdate force i am getting errors that id must be protected or weaker when i change this protection manually i am able to create tables but there is only one column id but this is not what i was hoping for can somebody give me any advice what i am doing wrong,['php'] +284431,jquery hotkeysnot so global basically i am using jquery hotkeys plugin by mr resig to capture and handle shortcuts like ctrlo etcok maybe i do not uderstand the concept but i was under the impression that a ctrlo triggered anywhere inside the document will be captured by a document hotkey handlerfor example the following code works in generaljquerydocumentbindkeydown ctrlo fnhowever it fails miserably if the user triggers the hotkey when inside an input boxit only works if i do the followingjquerybody inputbindkeydown ctrlo fnwhich is pretty bad for my health since it involves binding the damn handler each time a new input box is added to the dom worse still i have no idea what to bind to in the case of complex widgets like codemirrordunno if my problem makes sense perhaps i am using the wrong approach i also tried binding to the following objects but it did not work window document body divcontains the whole pagenb you can try it out here,['jquery'] +284442,android how do i create file object from asset file i have a text file in the assets folder that i need to turn into a file object not into inputstream when i tried this i got no such file exceptionstring path fileandroid assetdatafiletxturl url new urlpathfile file new fileurltouri get exception herecan i modify this to get it to workby the way i sort of tried to code by example looking at the following piece of code elsewhere in my project that references an html file in the assets folderpublic static dialog dodialogfinal context context webview wv new webviewcontext wvloadurlfileandroid assethelpindexhtmli do admit that i do not fully understand the above mechanism so it is possible that what i am trying to do cannot workthx,['android'] +284443,observable network io parsing i am trying to use rx to read from a tcpclient receive stream and parse the data into an iobservable of string delimited by newline rn the following is how i am receiving from the socket streamvar messages new subjectstringvar functionreceivesocketdata observablefromasyncpatternbyte int int socketflags int clientclientbeginreceive clientclientendreceivefuncbyte int byte copy bs n var rs new bytebufferlength bscopytors 0 return rs observable defer var buffer new byte50 return from and in functionreceivesocketdatabuffer 0 bufferlength socketflagsnone select copybuffer n repeatsubscribex messagesonnextsystemtextencodingutf8getstringxhere is what i came up with to parse the string this currently does not workobsstrings messagesbufferstringstring messagesscana c a cskipwhilea acontainsrn the message subject receives the message in chunks so i am trying to concat them and test whether the concatenated string contains newline thus signaling the buffer to close and output the buffered chunks not sure why it is not working seems that i only get the first chunk out of obsstringsso i am looking for two things i would like to simplify reading of the io stream and eliminate the use of the messages subject secondly i would like to get my string parsing working i have been hacking on this for a bit and cannot come up with a working solution i am a beginner with rxedit here is the finished product after the problem was solvedvar receivedstrings socketreceiveuntilcompletedsocketflagsnone selectmanyx systemtextencodingutf8getstringxtochararray scanstringempty a b aendswithrn a b wherex xendswithrn selectbuffered stringjoin buffered selecta areplacen receiveuntilcompleted is an extension from the rxx project,['c#'] +284447,writing html in a string i am trying a write a couple small lines of html in my java class that gets some data from another api i get the data in a json string and would then like to thisplay some of it on a webpage to create the html i try stringbuilder sb new stringbuilder forint i0ileadssizei sbappendpname leadsgetigetfirstname leadsgetigetlastnamep sbappendpemail leadsgetigetemailp sbappendbr fuleaddata sbtostringbut what ends up being thisplayed is a literal interpretation of the html tags is there a way that i can create this string so that the tags will stay as tags and not the escaped charactersthe java class is a managed bean so in the html i have body div idthisplay portalviewfuleaddata divbodywhere fuleaddata is the string with the html,"['java', 'html']" +284459,why am i getting a nullreferenceexception in systemdataentitydll entity framework i have a liststate of state entity objects and each state object has collections of other objects such as licenses taxes bonds etcthere is also a collection for expiredobjects which is a list of any object which is expired and needs to be renewed for some reason this property is giving me a nullreferenceexception when i try and access it for one specific state nevada but i cannot for the life of me figure out what is actually null since i do not see any null values anywhereheres my code that throws the exception it loops through all the states and adds all the expiredobjects to a viewspecific collection which gets thisplayed my test code is still included private listexpiredobject loadallexpiredobjects var list new listexpiredobject foreach var state in states this tells me the state is not null and neither is stateexpiredobjects debugwritelinestringformat012 statename state null stateexpiredobjects null try var x stateexpiredobjects debugwritelinex null exception occurs on the for line on the nevada state only contents in for loop do not execute foreach var item in x debugwritelinestringformat0 item listadditem this used to be the only line of code before i started testing it fails on nevada listaddrangestateexpiredobjects catch exception ex debugwritelineexmessage debugwritelineexstacktrace return list the stack trace of the error is thisa first chance exception of type systemnullreferenceexception occurred in systemdataentitydllobject reference not set to an instance of an object at systemdataentitykeyaddhashvalueint32 hashcode object keyvalue at systemdataentitykeygethashcode at systemcollectionsgenericgenericequalitycomparer1gethashcodet obj at systemcollectionsgenericdictionary2findentrytkey key at systemcollectionsgenericdictionary2trygetvaluetkey key tvalue value at systemdataobjectsobjectstatemanagertrygetentityentryentitykey key entityentry entry at systemdatacommoninternalmaterializationshaperhandleentityappendonlytentityfunc2 constructentitydelegate entitykey entitykey entityset entityset at lambda methodclosure shaper at systemdatacommoninternalmaterializationcoordinator1readnextelementshaper shaper at systemdatacommoninternalmaterializationshaper1simpleenumeratormovenext at systemdataobjectsdataclassesrelatedendmergetentityienumerable1 collection mergeoption mergeoption boolean setisloaded at systemdataobjectsdataclassesentitycollection1loadlist1 collection mergeoption mergeoption at systemdataobjectsdataclassesentitycollection1loadmergeoption mergeoption at systemdataobjectsdataclassesrelatedendload at systemdataobjectsdataclassesrelatedenddeferredload at systemdataobjectsdataclassesentitycollection1getenumerator at mynamespacestatesviewmodelloadallexpiredobjects in cusersmedesktopmysolutionstatesviewmodelcsline 217i also get the exact same error when i select nevada and it tries to bind a datagrid to the expiredobjects collection if i comment out that binding the code works finedoes anyone know what could be causing this error,['c#'] +284481,when to use explicit wait vs implicit wait in selenium webdriver i am usingdrivermanagetimeoutsimplicitlywait180 timeunitsecondsbut it still fails continuously for the below element driverfindelementbyidnameclear driverfindelementbyidnamesendkeyscreate title 01i have added wait codefor int second 0 second if second 120 failtimeout try if iselementpresentbyidname break catch exception e threadsleep10 should not implicit wait take care of waiting till an element is foundalso would it be better if i use explicit wait instead of the code i have added that has threadsleep,['python'] +284489,urlbyappendingpathcomponent vs urlbyappendingpathextension i have read the documentation and it looks like some edge cases might be different trailing slashes etc but it is not clear to me what the main difference between these two method is do the terms component and extension have special meaning in the url world that people other than me understand,"['objective-c', 'ios']" +284500,c unordered map fail when used with a vector as key background i am comming from the java world and i am fairly new to c or qtin order to play with unordered map i have written the following simple programinclude qtcoreqcoreapplicationinclude qtcoreinclude iostreaminclude stdiohinclude stringinclude unordered mapusing stdstringusing stdcoutusing stdendltypedef stdvectorfloat floatvectorint mainint argc char argv qcoreapplication aargc argv floatvector c10 floatvector b10 for int i 0 i 10 i ci i 1 bi i 2 stdunordered mapfloatvector int map mapb 135 mapc 40 mapc 32 stdcout b mapb stdendl stdcout c mapc stdendl stdcout contains mapsize stdendl return aexecunfortunately i am running into the folowing error which is not inspiring there is not even a line number1 error collect2 ld returned 1 exit statusany idea of the origin of the problemthanks in advance,['c++'] +284501,socketio client respond to all events with one handler is it possible to have a socketio client respond to all events without to have specify each event individuallyfor example something like this which obviously does not work right nowvar socket ioconnecthttpmyserversocketon function listen to any and all events that are emitted from the socketio backend server and handle them here is this possible how can i do thisi want this callback function to be called when any all events are received by the clientside socketio codeis this possible how,['javascript'] +284505,create and stream a large archive without storing it in memory or on thisk i want to allow users to download an archive of multiple large files at once however the files and the archive may be too large to store in memory or on thisk on my server they are streamed in from other servers on the fly i would like to generate the archive as i stream it to the useri can use tar or zip or whatever is simplest i am using django which allows me to return a generator or filelike object in my response this object could be used to pump the process along however i am having trouble figuring out how to build this sort of thing around the zipfile or tarfile libraries and i am afraid they may not support reading files as they go or reading the archive as it is builtthis answer on converting an iterator to a filelike object might help tarfileaddfile takes an iterable but it appears to immediately pass that to shutilcopyfileobj so this may not be as generatorfriendly as i had hoped,['python'] +284543,check if something is not in a list in python i have a list of tuples in python and i have a conditional where i want to take the branch only if the tuple is not in the list if it is in the list then i do not want to take the if branchif curr x 1 0 and curr x1 curr y not in mylist do somethingthis is not really working for me though what have i done wrong,['python'] +284548,jquery indexof function i am trying to get a location of an element in a jquery setheres what i tried so fari want to be able to do something like thisulfindaindexofactiveand get the location of the active in the set of asis there something like an indexof function for jquery the index method does not work,"['javascript', 'jquery']" +284557,is there a highlevel interprocess communications api that is implemented in both c and javascript i am working on app where i need to pass messages between a c application and a javascript web appcertainly i could write sockets code myself in either language and i have done this in the past when necessarywhat i would really like is a higherlevel message posting or message queueing api that does a lot of the work for me does anyone know of such an apii have looked at ice and it does not appear to have javascript bindings i have also looked at boost message queue but it only caters for the c side of things if necessary i might roll my own javascript bindings for either of these technologiesupdate sorry should have mentioned this before i want to run this in a browserto give a more complete story what i want is a simple browserbased app that is used to configure and thisplay logging for a c application i know there are other ways of doing this but i am specifically interested in a highlevel library in both c and browserbased javascript that builds a message queue ontop of the sockets api if there is not one then i might consider implementing it myself and writing up a code project articlealso i am not bothered about portability in terms of the web browser eg if there is a highlevel ipc javascript library that only works in chrome i will be happy with that,"['javascript', 'c++']" +284563,sqlplus does not execute sql scripts that sql developer does i am facing a very annoying problem i have written in notepad some sql scripts now when i try to execute them by sqlplus through the command line on windows 7 i am getting errors like ora00933 sql command not properly endedthen i copy paste the script into the sql developer worksheet window hit the run button and the script executes without any problemerrorsafter a long investigation i came to think that sqlplus has a problem with some whitespaces including newline characters and tabs that it does not understandsince i assume that sql developer knows how to get rid of the weird whitespaces i have tried this paste the script into the sql developer worksheet window then copy it from there and paste it back in the sql script that solved the problem for some files but not all the files some files keep showing errors in places for no apparent reasonhave you ever had this problem what should i do to be able to run these scripts by sqlplus through the command lineupdatean example of a script that did not work with sqlplus but did work with sql developerset echo oninsert into mydbbook type book type id unique name description version is active date created date modifiedselect mydbseq book type idnextval booktype mydbseq book type idnextval description mydbseq book type idnextval aversion bis active sysdate sysdate from select level10 version from dual connect by level10 a select level10 is active from dual connect by level2 bthe error i getsql sql set echo onsqlsql insert into mydbbook type 2 book type id unique name description version is active date created date modified 3 4 select mydbseq book type idnextval booktype mydbseq book type idnextval description mydbseq book type idnextval aversion bis active sysdate sysdate from 5 sql select level10 version from dual connect by level10 a 2 select level10 is active from dual connect by level2 b 3 sql 1 select level10 version from dual connect by level10 a 2 select level10 is active from dual connect by level2 bas you see the error is on select level10 is active from dual connect by level2 b for some reason in all the files that get this error the error appears on the last line before the concluding semicolon,['sql'] +284574,pythonconfig missing i am installing a program that requires i have pythonconfig installed the only problem is that i do not currently have pythonconfig and i cannot seem to figure out how to get itafter searching around i can supposedly install it viayum install pythondevelhowever after doing so pythonconfig still does not existi am currently using python 24 on a cluster running centos 52any help would be greatly appreciated,['python'] +284623,why does in array wrongly return true with these large numeric strings i am not getting what is wrong with this code it is returning found which it should notlead 418176069007diff array418176069003418176057001if in arrayleaddiff echo foundelse echo not found,['php'] +284628,how to convert p12 file to pem file using terminal i already have an development certificate in apple developer portal am developing an iphone appi want to integrate apple push notification in this app i have created a new app id with used the existing certificate and enabled the push notification in this app id and i have created a new provisioning profile used the newly created app id before these steps i have created and downloaded the cer file from keychain access after done these steps i downloaded the newly created ssl apple push notification service ssl certificate file and installed in my mac keychain access once i installed this file verified green tick mark is there and got the p12 file from this ssl filei followed the apple document remotenotificationspgpdf in this document they mentioned after saved the p12 file open the terminal app and type below commendsopenssl pkcs12 in certificatesp12 out certificatespem nodesi have used this in my terminal app but the error message is appear that iserror opening input file certificatesp12certificatesp12 no such file or directorycan you please suggest or guide me where i did wrong or what i missed in these steps please help me thanks in advanceediti stored my certificatesp12 file in my desktop folder path is desktop152012 certificate2512certificatesp12i have used ls command in terminal it is not listing my certificatesp12 file i have typed cd path this returned no such file or directoryplease help me thanks in advance,"['iphone', 'ios']" +284648,generate table for mapping ipaddress as inet type in postgresql i got a mapping that maps ipaddress object field to database there is inet type in postgresql suited for this but in my case it uses bytea type instead when it generates schemais there a way to force resulting generated schema type for this column to be inet actually in dbi also happen to have this requirement on composite id whicg is requiredcompositeidkeypropertyx xdate for datekeypropertyx xaddress var varcolumnnameipaddressyou cant really use customsqltype on key property parti also tried using public class ipaddresspropertyconvention ipropertyconvention public void applyipropertyinstance instance if instancepropertypropertytype typeofipaddress instancecustomsqltypeinet but i get exception about invalid property convention,['c#'] +284682,how to send http post request with gziped content i am developing iphone app and manually constructing post requests currently need to compress json data before sending it so looking how to tell a server the content is compressed setting content type header to gzip might be not acceptable because server expects json data i am looking for transparent solution something like just to add some header telling json data is compressed into gzipi know the standard way is to tell the server that the client accepts encoding but you need to make get request with accept encoding header first in my case i want to post the data already encoded,"['iphone', 'objective-c']" +284683,android metricaffectingspan and rasterizerspan can somebody please explain how the following spanmethods work for a textview if possible please with a short examplei have not found good explanations or examples in the web so farmany thanks in advancea metricaffectingspanb rasterizerspan,"['android', 'html']" +284693,jackson multiple objects and huge json files i get the feeling that the answer might be a duplicate of this jackson json to pojo with multiple entries but i think that potentially the question is different enough also i am using raw data binding rather than full data binding so like the asker of that question i have multiple objects in a file and i am trying to turn them into pojos and stuff them into a database of my design so i can access the data quickly rather than slowlythe files here are in the order of tens of gb with up to millions of objects in each file anyway here is what i have so farobjectmapper mapper new objectmappermapstringobject data mapperreadvaluenew filefoojson mapclasystemoutprintlndatagetbarand this works great for printing the bar element of the first object in foo but i need a way to iterate through every element in a way that would not eat up all my memorythanks,['java'] +284763,date conversion from string to sql date in java giving different output i have a string form of date i have to change it to sql date so for that i have used the following code string startdate01022013simpledateformat sdf1 new simpledateformatddmmyjavautildate date sdf1parsestartdatejavasqldate sqlstartdate new javasqldatedategettime when i used the above code and run that i got the following output 20130101 here month is not converted correctlyplease tell me where is the problem and provide sample code to get correct result,['java'] +284783,python why should i use next and not objnext python 26 introduced a next functionwhy was this necessary one could always type objnext instead of nextobjis the latter more pythonic,['python'] +284789,how to prevent user to enter text in textarea after reaching max character limit i want to prevent user to enter text in textarea once it reaches a max character limit what was happening that when i reached to max limit then my textarea scrollbar moved to top i somehow prevent this with this codejquerydocumentreadyfunction textareamaxkeyupfunction var textarea this var max 400 if textareavallength max var top textareascrolltop textareavaltextareavalsubstr0 max textareascrolltoptop end if readyfnbut i also want that after reaching max limit user unable to type anything in the textarea currently what happen that after reaching max limit if user press and hold the key the characters are typing in the text area although after releasing the button it come back to original text ie textareavaltextareavalsubstr0 max but i want that once this condition become trueif textareavallength max user unable to type anything i want that cursor vanishes from the textarea but if user remove some text then cursor also available for user to type input again how can i do it,['jquery'] +284791,how to get server mysql version in php without connecting i need to echo the mysql version in a php script it is a server requirement check page for users before downloading the plugin without having them connect to their database the upload this script to their server and open it in the browser i could ask them to run php info but all i need is the mysql version and it gets formatted in the script with the rest of the resultshow should i go about this,"['php', 'mysql']" +284793,is possible to split php configuration file phpini anyone working with php knows that phpini is a big file that may cause headaches when you need to change over sshfor example i can change nginxconf using include directive to load all of the files under sitesenabled dir into the main nginxconf so my question is straightforward it is possible to do the same thing with phpini,['php'] +284820,jquery detecting div of certain class has been added to dom i am using on to bind events of divs that get created after the page loads it works fine for click mouseenter but i need to know when a new div of class myclass has been added i am looking for thismycontaineron wascreated function dosomethingthis myclasshow do i do this i have managed to write my entire app without a plugin and i want to keep it that waythanks,['jquery'] +284831,what is public new virtual void method mean when use new virtual key words to decorate the method what is the affection like define an interface and add a class to inherit the interface but use the new virtual to realize the interface method interface iprinter void print public class printerone iprinter public void print consolewritelineprinterone public class printertwo printerone public new virtual void print consolewritelineprintertwo public class printerthree printertwo public override void print consolewritelineprinterthree public class printerfour printerthree public override void print consolewritelineprinterfour static void mainstring args iprinter iprinter new printerfour iprinterprintthe output is printerone why consolereadline,['c#'] +284843,how to implement spdy with rails 322 on heroku i am hearing that spdy is where things are likely headed and i would like to try to use it with a rails site i am running i have not been able to find any tutorials however and the one gem i found does not seem to work everyone is reporting the same error on it across all browsers is it currently possible to implement spdy on heroku with a rails app,['ruby-on-rails'] +284902,css3 animations with transform causes blurred elements on webkit so i have got some native elements divs with various effects applied to them borderradius boxshadow and transform scale when i animate them two weird things happeneven though i am not trying to animate the scale if i do not put the scale in the animation it is ignoredwhen i put the scale in the animation webkit blurs the elementssee the example here the buttons at the bottom will trigger the issuesthe first issue happens in firefox too so i am guessing that it is because that is how the animation spec is supposed to work not what i wanted but ok i will live with itthe second issue is just weird i know it is to do with 3d transform because if i just for testing purposes declare webkitperspective or webkittransformstyle preserve3d on the circle elements it causes the blur issue as well my confusion is that i am not trying to transform the z index as all and i have also tried the animations using purely translatey instead of translateit happens in chrome 18 chrome canary 20 and safari 512 514so am i right in what i think is happening and how can i avoid the blurrinessworstcase scenario i can just use different sizes for the elements instead of scaling them that is not really a problem but i thought this would be a more elegant solution and now this issue has cropped up,['css'] +284949,multi line preprocessor macros how to make multi line preprocessor macro i know how to make one linedefine sqrx xxbut i need something like thisdefine somemacrox class x public otherclass int foo void dofoo how can i get this to workthis is only an example the real macro may be very long,"['c++', 'c']" +284961,reset action bar after using searchview i am using searchview widget to enable searching in my app after the initial click on the search icon the searchview widget expands into the search field and the back arrow is shown next to the application icon if i click the application icon the action bar reverts to the initial state no back arrow and the searchview reverts back to iconnow the problem after the search is executed the action bar does not change the only way to revert is to click the application icon or phones back arrow not good since i want the action bar go to the initial state when the search is done i tried searchviewseticonofiedtrue but there are 2 problemssearch icon appears at the same spot as the edit field originally it is on the far rightaction bar still thisplays back arrowi think the problem i am facing results from deviating from the regular navigation pattern in my case everything is happening inside the same activity search results are thisplayed in the same activity that hosts the action bar so for example executing activityfinish simply makes app exithow do i trigger go back one step of the action bar or simulate click on the application icon,['android'] +284962,creating an mpi datatype for a structure containing pointers i have the following structuretypedef struct int ai double ax int nzcolumni want to transfer this structure using mpi send and mpi receive how do i create an mpi datatype for this structure,['c'] +284964,jackson 20 with spring 31 is spring mvc 31 compatible with jackson 20 will spring mvcs automatic detection of jackson on the classpath and delegation to jackson for requests with a json contenttype still work,['java'] +284976,c zip variadic templates here is a simple twocontainer zip function in ctemplate typename a typename bstdliststdpaira b simple zipconst stdlista lhs const stdlistb rhs stdliststdpaira b result for stdpairtypename stdlistaconst iterator typename stdlistbconst iterator iter stdpairtypename stdlistaconst iterator typename stdlistbconst iteratorlhscbegin rhscbegin iterfirst lhsend itersecond rhsend iterfirst itersecond resultpush back stdpaira biterfirst itersecond return resulthow would i extend this to an arbitrary number of containers with variadic templatesi would like general zip to accept a tuple of lists each list can contain a different type and return a list of tuples,['c++'] +284984,how can i test a click at a certain xy coordinate for running tests on an android app how can i automate the tap on a xy coordinate of either the view or the screeni am hoping that there is some call in activityinstrumentationtestcase2 or touchutils but have not found one yet,['android'] +285004,how do i make pythons negative lookbehind less greedy i have read all related posts and scoured the internet but this is really beating mei have some text containing a datei would like to capture the date but not if it is preceded by a certain phrasea straightforward solution is to add a negative lookbehind to my regexhere are some examples using findalli only want to capture the date if it is not preceded by the phrase as of 19211 something something 15411 such and such as of 29511 here is my regular expression as of d12d12d2expected results 19211 15411 actual results19211 15411 9511 notice that is 9 not 29 if i change d12 to something solid like d2 on the first pattern bad regex for testing as of d2d12d2then i get my expected results of course this is no good because i would like to match 2digit days as well as singledigit daysapparently my negative lookbehind is quity greedy moreso than my date capture so it is stealing a digit from it and failing i have tried every means of correcting the greed i can think of but i just do not know to fix thisi would like my date capture to match with the utmost greed and then my negative lookbehind be applied is this possible my problem seemed like a good use of negative lookbehinds and not overly complicated i am sure i could accomplish it another way if i must but i would like to learn how to do thishow do i make pythons negative lookbehind less greedy,['python'] +285012,noncrud operations in a restful webapi service i am learning webapi and rest in general by converting an existing wcf service to webapi in the process i am becoming confused as to the best way to handle the noncrud operations here is my service contractservicecontractpublic interface iproxyhelper operationcontract listproxyinfo getuserscurrentusercanactasproxyforint positionid int appid operationcontract void deleteproxyint id operationcontract listproxyinfo getproxydataint appid operationcontract bool canpositionproxyint positionid int appid operationcontract void addproxy string userracf string proxyasracf int userpositionid int proxypositionid string requestedbyracf int appid operationcontract int getpositionidbyracfstring racf operationcontract string getracfbypositionidint positionidsome of the methods like deleteproxy and addproxy i can easily move to a crudbased methodology the questions arise aroundgetproxydata the proxy system is used by multiple applications and though i could do apiproxy1 i feel that is cheating because that should be for getting proxyid 1 not proxies for application 1getuserscurrentusercanactasproxyfor this one is confusing on multiple levels for me how should i handle multiple parameters and it is not falling neatly into the crud method eitherdoes this mean i should abandon the webapi conversion if not how should i tackle these nonstandard methods,"['c#', 'asp.net']" +285025,why is pretty function called pretty function i see pretty function used a lot in answers to questions on this site and i understand the usefulness of this function but why exactly is it called pretty function it is not an ugly function but it is not exactly pretty either,"['c++', 'objective-c']" +285056,classnotfoundexception httprequestinterceptor i am getting this weird exception on this linehttpsolrserver server new httpsolrserverhttplocalhost8080solrstack traceexception in thread main javalangnoclassdeffounderror orgapachehttphttprequestinterceptor at compolgardiplindexsolrindexinitsolrindexjava36 at compolgardiplindexsolrindexgetinstancesolrindexjava30 at compolgardiplmainarticleindexermainarticleindexerjava44caused by javalangclassnotfoundexception orgapachehttphttprequestinterceptor at javaneturlclassloader1rununknown source at javasecurityaccesscontrollerdoprivilegednative method at javaneturlclassloaderfindclassunknown source at javalangclassloaderloadclassunknown source at sunmisclauncherappclassloaderloadclassunknown source at javalangclassloaderloadclassunknown source 3 more,['java'] +285094,stack level too deep in activesupport callbacks i am getting the systemstackerror in a rails 3 appall the information i have is useless one line of a stacktrace taken from the logsystemstackerror stack level too deep activesupport 323 libactive supportcallbacksrb409so the question is how do i see the full stack tracenote i do not care about why this happens all i want is to see is where it happensusing rails 323 unicornthanks,"['ruby-on-rails', 'ruby']" +285131,threejs full screen issue hey first of all thanks to all the people who read threads looking to help out total strangers thank younow then to the pointi have read through the threejs api read through the questions here on stackoverflow i have debugged the code using firebug and chromes debugger i have stripped out everything i can but i am still getting this irritating full screen error where the renderer view port is larger than my screen thus causing scroll bars to appear its a visible error that does not affect rendering or other operations i am just trying to control the size of the view port so that it matches available screen real estate without scroll bars appearingi am using google chrome 18 on windows 7 and i am just starting to work with the threejs api but i have used things like opengl in the past so graphics api are not unfamiliar when i try and run this code which is the default example shown on the github main page var camera scene renderergeometry material meshinitanimatefunction init scene new threescene camera new threeperspectivecamera 75 windowinnerwidth windowinnerheight 1 10 camerapositionz 10 sceneadd camera geometry new threecubegeometry 200 200 200 material new threemeshbasicmaterial color 0xff0 wireframe true mesh new threemesh geometry material sceneadd mesh renderer new threecanvasrenderer renderersetsize windowinnerwidth windowinnerheight documentbodyappendchild rendererdomelement function animate note threejs includes requestanimationframe shim requestanimationframe animate renderfunction render meshrotationx 001 meshrotationy 002 rendererrender scene camera it renders fine i see the red wire frame box rotating around but i have noticed that the renderer view port is too big it is larger than my available screen size which causes scroll bars to appear the code uses windowinnerwidth and windowinnerheight to set the aspect ratio and the widthheight for the renderer but it seems as if it picks up 20 to 30 extra pixels somewhere and adds them to the bottom and the right of the pagei have tried adjusting the css for the body element to remove margin and padding same for the canvas element that gets created but nothing i have echoed the screen size to the page and made javascript alert functions to check the window width and height and then watch as they get passed to the threejs api during runtime operations but the error remains the canvas rendering object is resizing itself to slightly larger than the screen size the closest i get to correcting the problem is doing something like thisvar val 7trims the window size by valfunction get widthreturn windowinnerwidth valfunction get heightreturn windowinnerheight val code omitted for brevitycamera new threeperspectivecamera 75 get width get height 1 10 code omitted for brevity rendersetsizeget width get heightit works to bring the renderer size within the boundaries of the window but only to a point if i lower val to less than 7 eg 6 or less the renderer size pops back out and is again larger by 20 px approx than the screen causing the scroll bars to appear any thoughts or ideas,['javascript'] +285152,android got calledfromwrongthreadexception in onpostexecute how could it be i have an app in production for a few weeks using acra and i had zero errors until one strange error reported todayi have got androidviewviewrootimplcalledfromwrongthreadexception only the original thread that created a view hierarchy can touch its viewscoming from this method in the stack trace retracedat myappcountdownfragment1void onpostexecutejavalangobjectsourcefile1and this is the relevant source snippet private void addinstructionsifneeded if ssthisplayassist new asynctaskstring void string override protected string doinbackgroundstring params return null runs on the ui thread protected void onpostexecutestring result activity a getactivity if sshelpenabled a null in new instructionsviewagetapplicationcontext relativelayout mv relativelayout a findviewbyidridmain place mvaddviewinprepareview execute where addinstructionsifneeded is called from a handler thispatched message the ui thead onpostexecute runs on the ui thread so why i have got wrong threadthis code ran already on more than 150 devices and more than 10 times according to flurry and never had this errorthe originating device is samsung sghi997 running sdk 404my question is how could it beeditthis all happens in a fragment,['android'] +285155,how to clone an element and insert it multiple times in one go how can i clone an element and insert it 5 times right after each other this of course is the base statementcolcloneinsertaftercolheres what i need to getdiv classcol idoriginal divdiv classcol divdiv classcol divdiv classcol divdiv classcol divdiv classcol divthe selector does not need to be using an unique id it can also be a class selectori could just repeat the base statement four times but there must be a more elegant way,['jquery'] +285170,jtds stored procedures preparesql nesting level error situationi have a tomcat java web application using jtds to connect to a mssql 2008 database this java application executes 99 of its mssql stored procedures using user inputproblemthe jtds driver replies sometimes at different places in the application with error maximum stored procedure function trigger or view nesting level exceeded limit 32we can avoid this by adding preparesql0 to the jtds connection string then the error goes away everywhere but with all other values of preparesql the error stays i do not know how many stored procedure nesting levels jtds adds but apparently it is too much for our applicationquestionswith only stored procedures to execute of course using prepared statements in the java code how much effect does preparesql3 or preparesql0 have for us in other words on every website i find people say never use preparesql0 in production environments is that also applicable to this situation if preparesql0 is not a recommended solution a security issue etc we should maybe look for another driver jtds has not been updated the past 2 years and microsoft has a driver for jdbc 40 i cannot find any benchmarks or comparisons between jtds and microsofts jdbc 40 driver though with microsofts 20 and 30 drivers the general opinion seemed to be that jtds is faster better more efficient is that still the case with jdbc 40 or has microsoft passed its competitor in this,['java'] +285180,how to add headers or parameters to an http request handled with selenium webdriver i am using selenium webdriver for unit testing of a web application it is used in junit tests despite reading the available documentation extensively and searching around i could not find a way toadd headers to an http request passed by the driveradd parameters to such a request as if the driver got his target url after submitting a formit would be possible to create a test web page with an appropriate form and have webdriver bounce off it to get those parameters automatically but this is quite an ugly hack i would like to avoid it especially for the sake of test atomicity this is unit testingbefore wendriver i was using springs mockhttpservletrequest and mockhttpservletresponse to do this which worked like a charm but i would like to use the power of webdriver to assert the target pages contents,['java'] +285200,expected a type error so i created this method voidaddtoviewcontrollersecviewcontroller controller didfinishenteringitemnsstring item brand xcode keeps giving me expected a type error at secviewcontroller what does that mean secviewcontroller is not a type,['ios'] +285207,check jquery unobtrusive validation is true by jquery i use mvc 3 model validation attributes and jquery unobtrusive to show validation error message also use the script when form submitted return a confirm so i need to check if the all fields are valid then return confirm some thing like the following pseudoscriptdivformneedconfirm formsubmitfunction if thisvalidate true var message formconfirmmessageval return confirmmessage but i do not know what exactly should be in the if condition what is your suggestion,"['javascript', 'jquery']" +285214,refer to actionbarsherlock from a library possible duplicateactionbarsherlock 40 doesnt work but 351 do i am trying to use actionbarsherlock for my app but there seems to be a problem when referring to actionbarsherlock from another library projectit is because i use a ui project where i create all the activities but this project is actually a library so i need the actionbarsherlock components in this ui project but when i refer to actionbarsherlock the following errors appearactionbarsherlocklibraryresvaluesv14abs stylesxml4 error error retrieving parent for item no resource found that matches the given name androidwidgetholoactionbaractionbarsherlocklibraryresvaluesv14abs stylesxml6 error error retrieving parent for item no resource found that matches the given name androidwidgetholoactionbarsolidactionbarsherlocklibraryresvaluesv14abs stylesxml8 error error retrieving parent for item no resource found that matches the given name androidwidgethololightactionbaractionbarsherlocklibraryresvaluesv14abs stylesxml10 error error retrieving parent for item no resource found that matches the given name androidwidgethololightactionbarsolidactionbarsherlocklibraryresvaluesv14abs stylesxml12 error error retrieving parent for item no resource found that matches the given name androidwidgethololightactionbarsolidinverseactionbarsherlocklibraryresvaluesv14abs stylesxml15 error error retrieving parent for item no resource found that matches the given name androidwidgetholoactionbartabviewactionbarsherlocklibraryresvaluesv14abs stylesxml17 error error retrieving parent for item no resource found that matches the given name androidwidgethololightactionbartabviewactionbarsherlocklibraryresvaluesv14abs stylesxml19 error error retrieving parent for item no resource found that matches the given name androidwidgethololightactionbartabviewinverseactionbarsherlocklibraryresvaluesabs stylesxml89 error error no resource found that matches the given name attr androiddividerpaddingactionbarsherlocklibraryresvaluesabs stylesxml88 error error no resource found that matches the given name attr androidshowdividersactionbarsherlocklibraryresvaluesv14abs stylesxml22 error error retrieving parent for item no resource found that matches the given name androidwidgetholoactionbartabbaractionbarsherlocklibraryresvaluesv14abs stylesxml24 error error retrieving parent for item no resource found that matches the given name androidwidgethololightactionbartabbaractionbarsherlocklibraryresvaluesv14abs stylesxml26 error error retrieving parent for item no resource found that matches the given name androidwidgethololightactionbartabbarinverseactionbarsherlocklibraryresvaluesabs stylesxml101 error error no resource found that matches the given name attr androidtextallcapsactionbarsherlocklibraryresvaluesv14abs stylesxml29 error error retrieving parent for item no resource found that matches the given name androidwidgetholoactionbartabtextactionbarsherlocklibraryresvaluesv14abs stylesxml31 error error retrieving parent for item no resource found that matches the given name androidwidgethololightactionbartabtextactionbarsherlocklibraryresvaluesv14abs stylesxml33 error error retrieving parent for item no resource found that matches the given name androidwidgethololightactionbartabtextinverseactionbarsherlocklibraryresvaluesv14abs stylesxml36 error error retrieving parent for item no resource found that matches the given name androidwidgetholoactionbuttonactionbarsherlocklibraryresvaluesv14abs stylesxml38 error error retrieving parent for item no resource found that matches the given name androidwidgethololightactionbuttonactionbarsherlocklibraryresvaluesv14abs stylesxml41 error error retrieving parent for item no resource found that matches the given name androidwidgetholoactionbuttonclosemodeactionbarsherlocklibraryresvaluesv14abs stylesxml43 error error retrieving parent for item no resource found that matches the given name androidwidgethololightactionbuttonclosemodeactionbarsherlocklibraryresvaluesv14abs stylesxml46 error error retrieving parent for item no resource found that matches the given name androidwidgetholoactionbuttonoverflowactionbarsherlocklibraryresvaluesv14abs stylesxml48 error error retrieving parent for item no resource found that matches the given name androidwidgethololightactionbuttonoverflowactionbarsherlocklibraryresvaluesv14abs stylesxml51 error error retrieving parent for item no resource found that matches the given name androidwidgetholoactionmodeactionbarsherlocklibraryresvaluesv14abs stylesxml53 error error retrieving parent for item no resource found that matches the given name androidwidgethololightactionmodeactionbarsherlocklibraryresvaluesv14abs stylesxml55 error error retrieving parent for item no resource found that matches the given name androidwidgethololightactionmodeinverseactionbarsherlocklibraryresvaluesv14abs stylesxml58 error error retrieving parent for item no resource found that matches the given name androidwidgetholopopupmenuactionbarsherlocklibraryresvaluesv14abs stylesxml60 error error retrieving parent for item no resource found that matches the given name androidwidgethololightpopupmenuactionbarsherlocklibraryresvaluesabs stylesxml184 error error no resource found that matches the given name attr androiddividerpaddingactionbarsherlocklibraryresvaluesabs stylesxml183 error error no resource found that matches the given name attr androidshowdividersactionbarsherlocklibraryresvaluesabs stylesxml213 error error no resource found that matches the given name attr androidspinnermodeactionbarsherlocklibraryresvaluesv14abs stylesxml63 error error retrieving parent for item no resource found that matches the given name androidwidgetholospinneractionbarsherlocklibraryresvaluesv14abs stylesxml65 error error retrieving parent for item no resource found that matches the given name androidwidgethololightspinneractionbarsherlocklibraryresvaluesv14abs stylesxml68 error error retrieving parent for item no resource found that matches the given name androidwidgethololistviewdropdownactionbarsherlocklibraryresvaluesv14abs stylesxml70 error error retrieving parent for item no resource found that matches the given name androidwidgethololightlistviewdropdownactionbarsherlocklibraryresvaluesv14abs stylesxml73 error error retrieving parent for item no resource found that matches the given name androidwidgetholopopupwindowactionbarsherlocklibraryresvaluesv14abs stylesxml75 error error retrieving parent for item no resource found that matches the given name androidwidgethololightpopupwindowactionbarsherlocklibraryresvaluesabs stylesxml257 error error no resource found that matches the given name attr androidanimationresolutionactionbarsherlocklibraryresvaluesv14abs stylesxml78 error error retrieving parent for item no resource found that matches the given name androidwidgetholoprogressbaractionbarsherlocklibraryresvaluesv14abs stylesxml80 error error retrieving parent for item no resource found that matches the given name androidwidgethololightprogressbaractionbarsherlocklibraryresvaluesv14abs stylesxml83 error error retrieving parent for item no resource found that matches the given name androidwidgetholoprogressbarhorizontalactionbarsherlocklibraryresvaluesv14abs stylesxml85 error error retrieving parent for item no resource found that matches the given name androidwidgethololightprogressbarhorizontalactionbarsherlocklibraryresvaluesabs stylesxml305 error error no resource found that matches the given name attr androidtextallcapsactionbarsherlocklibraryresvaluesv14abs stylesxml88 error error retrieving parent for item no resource found that matches the given name androidtextappearanceholowidgetactionbarmenuactionbarsherlocklibraryresvaluesv14abs stylesxml91 error error retrieving parent for item no resource found that matches the given name androidtextappearanceholowidgetactionbartitleactionbarsherlocklibraryresvaluesv14abs stylesxml93 error error retrieving parent for item no resource found that matches the given name androidtextappearanceholowidgetactionbartitleinverseactionbarsherlocklibraryresvaluesv14abs stylesxml95 error error retrieving parent for item no resource found that matches the given name androidtextappearanceholowidgetactionbarsubtitleactionbarsherlocklibraryresvaluesv14abs stylesxml97 error error retrieving parent for item no resource found that matches the given name androidtextappearanceholowidgetactionbarsubtitleinverseactionbarsherlocklibraryresvaluesv14abs stylesxml99 error error retrieving parent for item no resource found that matches the given name androidtextappearanceholowidgetactionmodetitleactionbarsherlocklibraryresvaluesv14abs stylesxml101 error error retrieving parent for item no resource found that matches the given name androidtextappearanceholowidgetactionmodetitleinverseactionbarsherlocklibraryresvaluesv14abs stylesxml103 error error retrieving parent for item no resource found that matches the given name androidtextappearanceholowidgetactionmodesubtitleactionbarsherlocklibraryresvaluesv14abs stylesxml105 error error retrieving parent for item no resource found that matches the given name androidtextappearanceholowidgetactionmodesubtitleinverseactionbarsherlocklibraryresvaluesv14abs stylesxml108 error error retrieving parent for item no resource found that matches the given name androidtextappearanceholowidgetpopupmenuactionbarsherlocklibraryresvaluesv14abs stylesxml110 error error retrieving parent for item no resource found that matches the given name androidtextappearanceholowidgetpopupmenulargeactionbarsherlocklibraryresvaluesv14abs stylesxml112 error error retrieving parent for item no resource found that matches the given name androidtextappearanceholowidgetpopupmenulargeactionbarsherlocklibraryresvaluesv14abs stylesxml114 error error retrieving parent for item no resource found that matches the given name androidtextappearanceholowidgetpopupmenusmallactionbarsherlocklibraryresvaluesv14abs stylesxml116 error error retrieving parent for item no resource found that matches the given name androidtextappearanceholowidgetpopupmenusmallactionbarsherlocklibraryresvaluesv11abs themesxml4 error error retrieving parent for item no resource found that matches the given name androidthemeholoactionbarsherlocklibraryresvaluesv11abs themesxml6 error error no resource found that matches the given name attr androidwindowactionbaractionbarsherlocklibraryresvaluesv14abs themesxml4 error error retrieving parent for item no resource found that matches the given name androidthemeholoactionbarsherlocklibraryresvaluesv11abs themesxml8 error error retrieving parent for item no resource found that matches the given name androidthemehololightactionbarsherlocklibraryresvaluesv11abs themesxml10 error error no resource found that matches the given name attr androidwindowactionbaractionbarsherlocklibraryresvaluesv14abs themesxml6 error error retrieving parent for item no resource found that matches the given name androidthemehololightactionbarsherlocklibraryresvaluesv14abs themesxml8 error error retrieving parent for item no resource found that matches the given name androidthemehololightdarkactionbaractionbarsherlocklibraryresvaluesv14abs themesxml14 error error no resource found that matches the given name attr androidactionbarwidgetthemeactionbarsherlocklibraryresvaluesv14abs themesxml20 error error no resource found that matches the given name attr androidwindowactionbaractionbarsherlocklibraryresvaluesv14abs themesxml24 error error no resource found that matches the given name attr androidwindowactionbaractionbarsherlocklibraryresvaluesabs themesxml183 error error no resource found that matches the given name attr androidwindowactionbaractionbarsherlocklibraryresvaluesabs themesxml184 error error no resource found that matches the given name attr androidwindowactionmodeoverlayactionbarsherlocklibraryresvaluesabs themesxml185 error error no resource found that matches the given name attr androidwindowcloseontouchoutsideactionbarsherlocklibraryresvaluesv14abs themesxml28 error error retrieving parent for item no resource found that matches the given name androidthemeholodialogactionbarsherlocklibraryresvaluesabs themesxml209 error error no resource found that matches the given name attr androidwindowactionbaractionbarsherlocklibraryresvaluesabs themesxml210 error error no resource found that matches the given name attr androidwindowactionmodeoverlayactionbarsherlocklibraryresvaluesabs themesxml211 error error no resource found that matches the given name attr androidwindowcloseontouchoutsideactionbarsherlocklibraryresvaluesv14abs themesxml30 error error retrieving parent for item no resource found that matches the given name androidthemehololightdialogso it seems like it can not find the holo themes even though all the projects have androidtargetsdkversion15 is there a fix for this or is it just not possible to refer to actionbarsherlock from a library,['android'] +285222,could not find file precompiledappconfig when working with precompiled razor views and virtualpathproviders we have an application using webforms aspx files for just about everything latley we have been using precompiled razorviews as a way of getting nicley packeted functionality by simply dropping a new dll in our project but now we have thiscoverd that our precompiled views seems to conflict with our virtualpathproviderswhen loading virtualpathproviders from external dlls the application tries to load precompiledappconfig for all requests and we do not got it the providers are loaded with reflection we have some virtualpathproviders in the same project as the registration and they work fine but when we register providers from external dlls with hostingenvironmentregistervirtualpathprovider we get this problemif we add the file precompiledappconfig it tries to get appstartcshtml and so on we have to have all theese files below before getting past the exeptionprecompiledappconfig appstartcshtml pagestartcshtml viewstartcshtmlviews viewstartcshtmlviewsshared viewstartcshtmldefaultcshtml we end up in defaultcshtml and the rest of the application works since we want to use apsxfiles as the default this is not an acceptable solution we are also worried that more problems will appear from this since we have no idea of why this is happeningwe have tried this way of loading our providers but we still get the same errorthe exceptioncould not find file cmyaprecompiledappconfigdescription an unhandled exception occurred during the execution of the current web request please review the stack trace for more information about the error and where it originated in the code exception details systemiofilenotfoundexception could not find file cmyaprecompiledappconfigsource error an unhandled exception was generated during the execution of the current web request information regarding the origin and location of the exception can be identified using the exception stack trace belowstack trace filenotfoundexception could not find file cmyaprecompiledappconfig systemio errorwinioerrorint32 errorcode string maybefullpath 12899479 systemiofilestreaminitstring path filemode mode fileaccess access int32 rights boolean userights fileshare share int32 buffersize fileoptions options security attributes secattrs string msgpath boolean bfromproxy boolean uselongpath 2481 systemiofilestreamctorstring path filemode mode fileaccess access fileshare share int32 buffersize fileoptions options string msgpath boolean bfromproxy 229 systemiofilestreamctorstring path filemode mode fileaccess access fileshare share 102 systemwebhostingmappathbasedvirtualfileopen 105 systemwebwebpagesbuildmanagerwrapperisnonupdatableprecompiledapp 157 systemwebwebpagesbuildmanagerwrapperctorvirtualpathprovider vpp ivirtualpathutility virtualpathutility 48 systemwebwebpagesvirtualpathfactorymanagercctorb 6 90 systemlazy1createvalue 12776623 systemlazy1lazyinitvalue 355 systemwebwebpagesapplicationstartpageexecutestartpagehttpapplication application 131 systemwebwebpageswebpagehttpmodulestartapplicationhttpapplication application action1 executestartpage eventhandler applicationstart 98 systemwebwebpageswebpagehttpmoduleinitapplicationhttpapplication application 75 systemwebwebpageswebpagehttpmoduleinithttpapplication application 268 systemwebhttpapplicationregistereventsubscriptionswithiisintptr appcontext httpcontext context methodinfo handlers 575 systemwebhttpapplicationinitspecialhttpapplicationstate state methodinfo handlers intptr appcontext httpcontext context 352 systemwebhttpapplicationfactorygetspecialapplicationinstanceintptr appcontext httpcontext context 407 systemwebhostingpipelineruntimeinitializeapplicationintptr appcontext 375httpexception 0x804005 could not find file cmyaprecompiledappconfig systemwebhttpruntimefirstrequestinithttpcontext context 11700992 systemwebhttpruntimeensurefirstrequestinithttpcontext context 141 systemwebhttpruntimeprocessrequestnotificationprivateiis7workerrequest wr httpcontext context 4869221version information microsoft net framework version4030319 aspnet version4030319272,['asp.net'] +285238,how to start launch application at boot time android i would like to launch my app when my tablet starts so that the main activity of my app is the first thing that the user see when they start the tableti have read about launcheractivity but i do not understand how to use itcan anyone help me with suggestions links or tutorials for thisis launcheractivity the best way or are there alternatives,['android'] +285245,how to keep indent for second line in ordered lists via css i want to have an inside list with list bullets or decimal numbers being all flush with superior text blocks second lines of list entries have to have the same indent like the first roweglorem ipsum dolor sit amet consectetuer adipiscing elit aenean commodo ligula eget dolor aenean aenean massa cum sociis natoque penatibus et magnis this parturient montes nascetur ridiculus mus donec quam felis1 text2 text3 longer text longer text longer text longer text longer text longer text second line of longer text4 textlorem ipsum dolor sit amet consectetuer adipiscing elit aenean commodo ligula eget dolor css provides only two values for its liststyleposition inside and outside with inside second lines are flush with the list points not with the superior line3 longer text longer text longer text longer text longer text longer textsecond line of longer text4 textwidth outside my list is not flush with superior text blocks anymoreexperiments width textindent paddingleft and marginleft work for unordered lists but they fail for ordered lists because it depends on the listdecimals number of characters lorem ipsum dolor sit amet consectetuer adipiscing elit aenean commodo ligula eget dolor 3 longer text longer text longer text longer text longer text longer text second line of longer text 4 text11 text12 text11 and 12 are not flush with the superior text block compared to 3 and 4so wheres the secret about ordered lists and the secondlineindent thanks for your effort,"['html', 'css']" +285272,thisplay html within htmlactionlink with twitter bootstrap i am using twitter bootstrap and trying to make my links aspnet mvc look nicehowever the i class in the link below is html encoded rather than being sent as html to the browser htmlactionlinki classiconuser iconwhitei create new create new with key classbtn btnprimary is there any way of keeping the i class as html so that the button thisplays correctly,['asp.net'] +285315,nested blocks and references to self i have a block wherein i use self so i declare a weak reference to self weak myclass weakself selfnow my questionsi get an error where i define weakself and i do not understand what this should meanweak attribute can not be specified on an automatic variableinside my block i pass weakself to another block and i am not sure if i now have to do the same thing again like so weak myclass weakweakself weakselfand then pass weakweakself to that block,"['objective-c', 'ios']" +285353,i am using rbenv so why are there two gem paths on my system os x lion to clarify i am using rbenv to manage my ruby versions i was under the impression that binaries are managed as shims in their respective ruby version directoryhere is what my system shows when i run gem environment i am excluding the irrelevant parts gem paths volumesdatanathanrbenvversions193p194librubygems191 volumesdatanathangemruby191any reason for having two locations curious minds want to know,['ruby'] +285400,implementation of sequential monte carlo method particle filters i am interested in the simple algorithm for particles filter given here it seems very simple but i have no idea on how to do it practicallyany idea on how to implement it just to better understand how it works editthis is a great simple example that explain how it works i have tried to implement it in c but i am note sure if i do it the right way can you please check if i understood it well or there are some misunderstanding according to my code include iostreaminclude vectorinclude boostrandommersenne twisterhppinclude boostrandomuniform 01hppinclude boostrandomuniform int thistributionhppusing namespace stdusing namespace boostdouble uniform generatorvoiddefine and 4 number of particlesdefine evolutionproba a a 1030 px t a x t1 adefine evolutionproba a b 1030 px t a x t1 bdefine evolutionproba b b 2030 px t b x t1 bdefine evolutionproba b a 2030 px t b x t1 adefine observationproba a a 4050 py t a x t adefine observationproba a b 1050 py t a x t bdefine observationproba b b 4050 py t b x t bdefine observationproba b a 1050 py t a x t a typedef struct thistrib float pa float pb thistributiontypedef struct particle thistribution thistribution eg 05 05 char state eg a or b float weight eg 08particle int main vectorchar y data observations ypush backa ypush backb ypush backa ypush backa ypush backa ypush backb ypush backa ypush backa ypush backb ypush backa ypush backb ypush backa ypush backa ypush backb ypush backb ypush backa ypush backa ypush backb vector vectorparticle xall vector of all particles from time 0 to t step 1 initialisation vectorparticle x a vector of and particles forint i 0 i n i particle x sample particle xi from initial thistribution xthistributionpa 05 xthistributionpb 05 float r uniform generator if r xthistributionpa xstate a r 05 if xthistributionpa r r xthistributionpa xthistributionpb xstate b 05 r 1 xpush backx xallpush backx xclear observing data forint t 1 t 18 t char y yt1 current observation step 2 importance sampling float sumweights 0 vectorparticle x a vector of and particles forint i 0 i n i particle x pxi t a pxi t a xi t1 a pxi t1 a pxi t a xi t1 b pxi t1 b xthistributionpa evolutionproba a a xallt1ithistributionpa evolutionproba a b xallt1ithistributionpb pxi t b pxi t b xi t1 a pxi t1 a pxi t b xi t1 b pxi t1 b xthistributionpb evolutionproba b a xallt1ithistributionpa evolutionproba b b xallt1ithistributionpb sample the a particle from this thistribution float r uniform generator if r xthistributionpa xstate a if xthistributionpa r r xthistributionpa xthistributionpb xstate b compute weight of this particle according to the observation y if y a if xstate a xweight observationproba a a py a xi t a else if xstate b xweight observationproba a b py a xi t b else if y b if xstate a xweight observationproba b a py b xi t a else if xstate b xweight observationproba b b py b xi t b sumweights xweight xpush backx normalise weights forint i 0 i n i xiweight sumweights step 3 resampling and particles according to weights float pa 0 pb 0 forint i 0 i n i if xistate a pa xiweight else if xistate b pb xiweight vectorparticle rex new vector of particles forint i 0 i n i particle x xthistributionpa pa xthistributionpb pb float r uniform generator if r xthistributionpa xstate a if xthistributionpa r r xthistributionpa xthistributionpb xstate b rexpush backx xallpush backrex return 0 double uniform generatorvoid mt19937 gen55 static uniform 01 mt19937 double uniform gengen return uniform gen,['c++'] +285404,how to make python32 interpreter the default interpreter in debian i got both python2 and python3 installed in my debian machine but when i try to invoke the python interpreter by just typing python in bash python2 pops up and not python3 since i am working with the latter at the moment it would be easier to invoke python3 by just typing python please guide me through this,['python'] +285414,attachments name is wrong decoded if norwegian letters are used i have this piece of code which creates an attachment and sends email if name of the file contains a a or a the name is totally destroyedif i remove norwegian letters everything is ok var stream new memorystream docsavestream saveformatdocx mailfrom new mailaddress mailtoadd mailisbodyhtml true mailsubject attachments test mailbody heibr br streamseek0 seekoriginbegin var attachment new attachmentstream name a a adocx applicationvndopenxmlformatsofficedocumentwordprocessingmldocument attachmentnameencoding encodingutf8 mailattachmentsaddattachment var smtp new smtpclientsmtpservercom port 25 smtpsendmailhow to get this work properlysolutioni found a solution here,['c#'] +285416,gcc comparison is always true due to limited range of data type in template parameter i want to write a template that returns me the smallest signed integer type that can represent a given number this is my solution helper for inttypethatfits template parameters indicate whether the given number fits into 8 16 or 32 bits if neither of them is true it is assumed that it fits 64 bits template bool fits8 bool fits16 bool fits32struct inttypethatfitshelper specializations for picking the right type these are all valid combinations of the flagstemplate struct inttypethatfitshelpertrue true true typedef int8 t result template struct inttypethatfitshelperfalse true true typedef int16 t result template struct inttypethatfitshelperfalse false true typedef int32 t result template struct inttypethatfitshelperfalse false false typedef int64 t result finds the smallest integer type that can represent the given numbertemplate int64 t nstruct inttypethatfits typedef typename inttypethatfitshelper n numeric limitsint8 tmax n numeric limitsint8 tmin n numeric limitsint16 tmax n numeric limitsint16 tmin n numeric limitsint32 tmax n numeric limitsint32 tmin result resulthowever gcc does not accept this code i get an error comparison is always true due to limited range of data type werrortypelimits why does that happen and is a signed 64bit integer and all of the comparisons may be true or false for different values of n or am i overlooking somethingi will be glad for any helpedit i should mention that i am using c11,['c++'] +285461,failure saving state target not in fragment manager settargetfragment i have got a monkey crash whereby javalangillegalstateexception failure saving state fragmentb has target not in fragment manager fragmentaat androidsupportv4appfragmentmanagerimplsaveallstatefragmentmanagerjava1561at androidsupportv4appfragmentactivityonsaveinstancestatefragmentactivityjava475at comacmeparentactivityonsaveinstancestateunknown sourcebasically fragmenta loads up fragmentb and settargetfragment is called to set fragmentbs target fragment fragmentb then simply calls gettargetfragmentin its oncreate method and hangs on to the target for when needed now i am not doing anything in any of the onsaveinstancestate calls with the target fragment in terms of setting it null making any savefragmentinstancestate putfragment etc calls the question is should i be doing something with itthanks in advancepeter edit 1 i am using an old version of the support library and have a feeling that this may be fixed in the latest version will test further and provide a further update if that is the case however still interested to know whether i should be doing anything with the target fragment that i am not currently doing edit 1 fixed with version 8 of the support library have not tried others,['android'] +285463,very strange outofmemoryerror as always a lengthy problem descriptionwe are currently stress testing our product and we now we face a strange problem after one to two hours heap space begins to grow the application dies sometime laterprofiling the application shows a very large amount of finalizer objects filling the heap well we thought might be the weird finalizer thread to slow issue and reviewed for reducing the amount of objects that need to be finalized jna native handles in this case good idea anyway and reduced thousands of new objectsthe next tests showed the same pattern only one hour later and not so steep this time the finalizers originated from the fileinput and fileoutput streams that are heavily used in the testbed all resources are closed but the finalizers not cleaned up anymorei have no idea why after 1 or 2 hours no exceptions the finalizerthread seems suddenly to stop working if we force systemrunfinalization by hand in some of our threads the profiler shows that the finalizers are cleaned up resuming the test immediately causes new heap allocation for finalizers the finalizerthread is still there asking jconsole he is waitingeditfirst inspecting the heap with heapanalyzer revealed nothing newstrange heapanalyzer has some nice features but i had my difficulties at first im using jprofiler which comes along with nice heap inspection tools and will stay with it maybe i am missing some killer features in heapanalyzersecond today we set up the tests with a debug connection instead of the profiler the system is stable for nearly 5 hours now this seems to be a very strange combination of too much finalizers that have been reduced in the first review the profiler and the vm gc strategies as everything runs fine at the moment no real insightsthanks for the input so far maybe you stay tuned and interested now that you may have more reason to believe that we do not talk over a simple programming fault,['java'] +285526,what is the best way to handle an executionexception i have a method that performs some task with a timeout i use the executorserversubmit to get a future object and then i call futureget with a timeout this is working fine but my question is the best way to handle checked exceptions that can be thrown by my task the following code works and preserves the checked exceptions but it seems extremely clumsy and prone to break if the list of checked exceptions in the method signature changesany suggestions on how to fix this i need to target java 5 but i would also be curious to know if there are good solutions in newer versions of javapublic static byte dosomethingwithtimeout int timeout throws processexecutionexception interruptedexception ioexception timeoutexception callablebyte callable new callablebyte public byte call throws ioexception interruptedexception processexecutionexception do some work that could throw one of these exceptions return null try executorservice service executorsnewsinglethreadexecutor try futurebyte future servicesubmit callable return futureget timeout timeunitmilliseconds finally serviceshutdown catch throwable t exception handling of nested exceptions is painfully clumsy in java if t instanceof executionexception t tgetcause if t instanceof processexecutionexception throw processexecutionexceptiont else if t instanceof interruptedexception throw interruptedexceptiont else if t instanceof ioexception throw ioexceptiont else if t instanceof timeoutexception throw timeoutexceptiont else if t instanceof error throw errort else if t instanceof runtimeexception throw runtimeexceptiont else throw new runtimeexception t update many people posted responses that recommended either 1 rethrowing as a general exception or 2 rethrow as an unchecked exception i do not want to do either of these because these exception types processexecutionexception interruptedexception ioexception timeoutexception are important they will each be handled differently by the calling processed if i were not needing a timeout feature then i would want my method to throw these 4 specific exception types well except for timeoutexception i do not think that adding a timeout feature should change my method signature to throw a generic exception type,['java'] +285536,long running delayed job jobs stay locked after a restart on heroku when a heroku worker is restarted either on command or as the result of a deploy heroku sends sigterm to the worker process in the case of delayed job the sigterm signal is caught and then the worker stops executing after the current job if any has stopped if the worker takes to long to finish then heroku will send sigkill in the case of delayed job this leaves a locked job in the database that would not get picked up by another workeri would like to ensure that jobs eventually finish unless there is an error given that whats the best way to approach this i see two options but i would like to get other inputmodify delayed job to stop working on the current job and release the lock when it receives a sigtermfigure out a programmatic way to detect orphaned locked jobs and then unlock themany thoughts,"['ruby-on-rails', 'ruby']" +285554,how to use functions from different c projects in visual studio 2010 i would like to build two c projects in the same solution in visual studio 2010 that can interact with each other i have created a solution under directory cusersmedesktopsolutiondir the two projects have been created respectively under cusersmedesktopsolutiondirfirstproject and cusersmedesktopsolutiondirsecondprojectmy first project contains two files a header functionh and a cpp file functioncppfunctionhpragma oncevoid print stufunctioncppinclude functionhinclude iostreamvoid print stuff stdcout hello world stdendl my second project contains the main file maincppmaincppinclude firstprojectfunctionhinclude iostreamint mainvoid print stuff int stop stdcin stop return 0 i added the directory cusersmedesktopsolutiondir in my secondproject configuration properties cc general additional include directories i still get the classical error error lnk2019 unresolved external symbol when calling the function print stuffany ideas,['c++'] +285562,generifying with super i would like to write an interator like thisclass plant class tree extends plant class maple extends tree iterator class compiler error on the word superclass myiteratort super maple implements iteratort private int index 0 private listmaple list get the list from an external source public t next maple maple listgetindex do some processing return maple the other methods of iterator are easy to implementconceptually the idea is to have an iterator that looks like it returns trees or plants even though they are always maples without writing separate classes for eachbut the compiler does not like it when i generify with t super maple apparently you can only generify a class using t extends something does anyone know of a good way to accomplish the same thingmy motivation for asking is that i have a program that uses interfaces for its api i want to have one method that returns an iterator of interfaces for the api and another that returns an iterator of the implementation classes for internal use,['java'] +285571,jquery addclass and fadein so i have these h1 elements that are links and i want to add a class to them and fade that class in once the element has been hovered over and then onmouseout have the class removed whilst fading the class but using the fade function does nothing for me seeing as it hides the element any ideasjquerycategories h1 ahoverfunction jquerythisfadeinslowaddclassactivefunction jquerythisfadeoutslowremoveclassactivethankseditjqueryh1hoverfunction jquerythisstopanimate backgroundcolor a7bf51 800 function jquerythisstopanimate backgroundcolor f 800,"['javascript', 'jquery', 'html']" +285602,packet size limit for iphone games i am creating a multi player iphone game using the multi player tutorial as the skeleton in the following link with the architecture i am using gamecentre peer to peerone of the devices plays the role of the server i have a question just what is the limitation of the packet size on average i need to send out 890 bytes per go,"['iphone', 'objective-c']" +285610,count function each time or store the value and increment it by one i have a database with a user votes table and a user table i am thinking the database will get quite big in a small amount of time so i want to use the most efficient methodi am thinking i can either count the amount of votes with a where statement from the votes table every time or i can store the score in the user table and just increment it by 1 every time a vote is addedwhich would be bestquickest andor are there any other ways of doing this,['mysql'] +285618,how to programmatically set the forecolor of a label to its default i am using vs2010 c aspnetto programmatically change the forecolor of an asplabel named lblexample to red i write thislblexampleforecolor systemdrawingcolorredafter changing the forecolor how do i programmatically set the forecolor of the label to its default that comes from the css fileremarkthe label has no css entry class or id specific style the color is inherited,"['c#', 'asp.net']" +285628,what happened when i use multi ob start without ob end clean or ob end flush i have reviewed php manual about the ob start ob end clean ob end flush and i have seen a different example about the subject anyway i modified the example but i am confused at this point here is the scriptob startecho hello x ob startecho hello y ob startecho hello z ob startecho hello worldob 2 ob get contentsob end cleanecho galaxyob 1 ob get contentsob end cleanecho this is ob 1 ob 1echo br and this is ob 2 ob 2and output of this script ishello x hello y this is ob 1 hello z galaxyand this is ob 2 hello worldwhy the output is not like thatthis is ob 1 hello x hello y hello z galaxyand this is ob 2 hello world and what is the point i have missed,['php'] +285647,net xmlserializer and nested classes in c i have encountered some surprising behavior using xmlserializer in c consider the following piece of codepublic class a ienumerable public class b xmlattribute public string propa get set xmlelement public string propb get set public ienumerator getenumerator yield break class program static void main string args xmlserializer serializer new xmlserializertypeofab xmltextwriter writer new xmltextwriteretemptestxml encodingdefault serializerserializewriter new ab propa one propb two in this example i try to serialize an instance of nested class ab which itself does not make use of the container class a in any way but when i attempt to construct the xmlserializer for it the following exception is throwninvalidoperationexception was unhandledto be xml serializable types which inherit from ienumerable must have an implementation of addsystemobject at all levels of their inheritance hierarchy testa does not implement addsystemobjectxmlserializer is trying to apply serialization constraints against type a when i am actually trying to serialize type ab my understanding however is that aside from privileged access to data in instances of the outer type a nested type is not special and behaves as if it were in a namespace is this understanding incorrect and do the semantics of nested types or xmlserializer justify this behavior or does this feel like a bug in xmlserializerin specific regard to xmlserializer semantics is there any documented requirement that enforces xmlserializer constraints on all outer types when applied against a nested type,"['c#', '.net']" +285667,why are my css properties being overriddenignored i am having some issues with the css hierarchy not sure if it is proper to call it a hierarchy i am trying to style the below bit of htmlbody section idcontent article ul classpostslist li classpostitem h2post titleh2 p classitemdescriptionp p classitemmetap li ul article sectionbodysince sectioncontent changes on every page i have i wanted to maintain consistent styles across all of them so i wrote some global css rulescontent color 0 marginleft 300px maxwidth 620px padding 0px 10px position relativecontent pcontent li color 1 font 16px 24px serifi wanted to style html within a ulpostslist differently so i wrote these ruleslipostitem margin 0pxitemdescription color fitemmeta color 6however i ran into some issues here is how chrome is rendering the cssfor some reason the rules content p content li are overriding my rules for itemdescription and itemmeta my impression was that classid names are considered specific and thus higher priority however it seems that i have a misunderstanding of how css works what am i doing wrong hereedit also where can i read up more about how this hierarchy works,['css'] +285680,special characters in mysql table name apologies for asking my googlefu failed me on this questioni created a table as followscreate table if not exists e aa int11 unsigned not null auto incrementshowname text not null default startdatetime datetime not null default enddatetime datetime not null default primary key aa enginemyisam default charsetutf8then tried to insert with the queryinsert into e showname startdatetime enddatetime valuese news 20120503 190 20120503 20and it errors due to the in the table name i am assuming is a special character in mysql i tried to escape it but the query still failedso can i have special characters like or in the table name if yes then i probably have to encode them somehowthanks,"['mysql', 'sql']" +285691,remove leading and trailing spaces i am having a hard time trying to use strip with the following line of code thanks for the helpfwriteresplittech idnameaccount line1,['python'] +285720,pylint relative import should be i am checking a module with pylint the project has this structurebuilder init py entitypy productpywithin product i import entity like thisfrom entity import entitybut pylint laments that module builderproductw 50 relative import entity should be builderentityhowever from builderentity import entity does not recognize the package and from builderentity import entity does not work either what is pylint complaining about thanks,['python'] +285721,how to remove all items except the first item from dropdownlist in c i need to clear drpaddresstypes dropdown values except the first item and bind again that dropdownlist drpaddresstypesitemsclearvar lstaddresstypes repositorygetaddresstypesuseridif lstaddresstypes null foreach var item in lstaddresstypes var addresstype new listitemitem item drpaddresstypeitemsaddaddresstype when i am using drpaddresstypesitemsclear it is clearing all items how can i clear all items except the first itemthanks in advance,"['c#', 'asp.net']" +285735,ivy output the results of a resolve to an ivy file having resolved my ivyxml file i would like to create a new resolvedivyxml file consisting of all of the transitive dependencies found in the resolve is it possible to do thisthis is different to a deliver which i believe only writes out the immediate dependencies from your ivyxml not the transitive dependencies the deliver ant task does have a delivertarget attribute which looks in the documentation like it should do this in practice it works only for modules in the same organisation so not generally for all dependencies and generates a file per moduleit is also different from the ivyreport xml file that is generated during the resolve but not hugely different if what i am trying is not possible then i will just hack at this file directly i supposethe context here is trying to enable repeatable reproducible builds including in the presence of changes new libraries versions to the repository there are posts around the interwebs that try to do this and none i have found can do it properlyadditions to the ivy repository can change resolve results in particular if any dependencies anywhere in the repository not just your project have range dependencies example a depends on b2040 and b31 is later added to the repositoryidea is to resolve as normal write the resolve as a flattened ivy file save that in your projects vcs for that tag or whatever and subsequently resolve against that file with transitivefalse assuming that existing items in the repository do not change this allows repeatable buildsif anyone has any better ideas for doing this i am all ears at the moment i am expecting to have to hack some combination of the resolveengine to make the resolvereport available then add a custom deliverengine to use it,['java'] +285739,rails activating ssl support gets chrome confused there is a nice option to config for the rails appconfigforce ssl truehowever it seems that just putting that to true does not get the https connections working even more after trying and failing to connect to httpslocalhost30 with chrome i have set this option to false and chrome still tries to open https even if i write httpso couple of questionshow to force chrome not to try https anymorewhat is the proper way of enabling ssl on my rails appupdate the app is run on heroku and it seems that https is supported there automagically can i test ssl also locally like when running rails server,['ruby-on-rails'] +285768,how to change the default icon on the searchview to be use in the action bar on android i am having a bit of trouble customizing the search icon in the searchview on my point of view the icon can be changed in the item attributes right just check the code bellowcan someone tell me what i am doing wrong this is the menu i am using with my custom search icon icn lupa but when i run the app i always get the default search iconmenu xmlnsandroiditem androidididmenu search androidtitlestringmenu search androidicondrawableicn lupa androidshowasactionalways androidactionviewclassandroidwidgetsearchview menuthanks in advance,['android'] +285799,what is the difference between gravity and acceleration sensors in android what is the difference between gravity and acceleration sensors in android from my point of view the physical value is the same in both caseswhich one measures the force acting on unit mass inside the deviceadditionthe question is what physical quantity is measured by these sensors according to equivalence principle the acceleration and gravity are inthistinguishable and the only way to measure both is by usual but 3d spring balance,['android'] +285817,how to start rmi registry through java code i have written java programs for client and server but to run the program i need to start rmi registry manually how to start rmi registry through java code through server,['java'] +285833,how to define uiimageview size as uiimage resolution i have scenario in which i am getting images using web service and all images are in different resolution now my requirement is that i want resolution of each images and using that i want to define size of uiimageview so i can prevent my images from getting blurred for example image resolution if 326 pixelinch the imageview should be as size of that image can represent fully without any blurneed urgent help methanks in advance,['iphone'] +285848,how to move title of uitabbaritem can somebody tell me please how can i move title of uitabbaritem for example 2px to top,"['iphone', 'objective-c']" +285851,how to parse multiple subcommands using python argparse i am implementing a command line program which has interface like thiscmd global options command command opts command command opts i have gone through the argparse documentation i can implement global options as optional argument using add argument in argparse and the command command opts using subcommandsfrom the documentation it seems i can have only one subcommand but as you can see i have to implement one or more subcommands what is the best way to parse such command line arguments useing argparse,['python'] +285870,psychsyntaxerror could not parse yaml i am facing problem in rails application running on fedora 16 rails version 235 and ruby 192p320 the application running fine on ubuntu 10 when i run the rails server and hit any controller the following error in comingpsychsyntaxerror in controllernameactionnamecould not parse yaml i have tried the apply the following trick but it is not work for mei have added the following line in configbootrbrequire yamlyamlengineyamler syckthe error trace is rvmrubiesruby192p320libruby191psychrb148in parservmrubiesruby192p320libruby191psychrb148in parse streamrvmrubiesruby192p320libruby191psychrb119in parservmrubiesruby192p320libruby191psychrb106in loadrvmgemsruby192p320sunagogemsactivesupport235libactive supportvendori18n013libi18nbackendsimplerb189in load ymlrvmgemsruby192p320sunagogemsactivesupport235libactive supportvendori18n013libi18nbackendsimplerb176in load filervmgemsruby192p320sunagogemsactivesupport35libactive supportvendori18n013libi18nbackendsimplerb13in block in load translationsrvmgemsruby192p320sunagogemsactivesupport235libactive supportvendori18n013libi18nbackendsimplerb13in eachrvmgemsruby192p320sunagogemsactivesupport235libactive supportvendori18n013libi18nbackendsimplerb13in load translationsrvmgemsruby192p320sunagogemsactivesupport235libactive supportvendori18n013libi18nbackendsimplerb85in init translationsrvmgemsruby192p320sunagogemsactivesupport235libactive supportvendori18n013libi18nbackendsimplerb74in available localesrvmgemsruby192p320sunagogemsactivesupport235libactive supportvendori18n013libi18nrb50in available localesrvmgemsruby192p320sunagogemsactionpack235libaction viewtemplaterb226in valid localervmgemsruby192p320sunagogemsactionpack235libaction viewtemplaterb243in parse extensionsrvmgemsruby192p320sunagogemsactionpack235libaction viewtemplaterb233in splitrvmgemsruby192p320sunagogemsactionpack235libaction viewtemplaterb118in initializervmgemsruby192p320sunagogemsactionpack235libaction viewreloadable templaterb81in initializervmgemsruby192p320sunagogemsactionpack235libaction viewreloadable templaterb38in newrvmgemsruby192p320sunagogemsactionpack235libaction viewreloadable templaterb38in register template from filervmgemsruby192p320sunagogemsactionpack235libaction viewreloadable templaterb62in block in load all templates from dirrvmgemsruby192p320sunagogemsactionpack235libaction viewreloadable templaterb62in eachrvmgemsruby192p320sunagogemsactionpack235libaction viewreloadable templaterb62in load all templates from dirrvmgemsruby192p320sunagogemsactionpack235libaction viewreloadable templaterb29in rvmgemsruby192p320sunagogemsactionpack235libaction viewpathsrb48in block in find templatervmgemsruby192p320sunagogemsactionpack235libaction viewpathsrb47in eachrvmgemsruby192p320sunagogemsactionpack235libaction viewpathsrb47in find templatervmgemsruby192p320sunagogemsactionpack235libaction controllerbaserb1389in default templatervmgemsruby192p320sunagogemsactionpack235libaction controllerbaserb905in renderrvmgemsruby192p320sunagogemsactionpack235libaction controllerbenchmarkingrb51in block in render with benchmarkrvmgemsruby192p320sunagogemsactivesupport235libactive supportcore extbenchmarkrb17in block in msrvmrubiesruby192p320libruby191benchmarkrb310in realtimervmgemsruby192p320sunagogemsactivesupport235libactive supportcore extbenchmarkrb17in msrvmgemsruby192p320sunagogemsactionpack235libaction controllerbenchmarkingrb51in render with benchmarkrvmgemsruby192p320sunagogemsactionpack235libaction controllerbaserb1326in default renderrvmgemsruby192p320sunagogemsactionpack235libaction controllerbaserb1332in perform actionrvmgemsruby192p320sunagogemsactionpack235libaction controllerfiltersrb617in call filtersrvmgemsruby192p320sunagogemsactionpack235libaction controllerfiltersrb610in perform action with filtersrvmgemsruby192p320sunagogemsactionpack235libaction controllerbenchmarkingrb68in block in perform action with benchmarkrvmgemsruby192p320sunagogemsactivesupport235libactive supportcore extbenchmarkrb17in block in msrvmrubiesruby192p320libruby191benchmarkrb310in realtime,['ruby-on-rails'] +285873,how to enable with javabased annotations i am trying to set up spring aop without any xml i would like to enable aopaspectjautoproxy in a class which is annotated with configurationthis is the way it would be defined in an xmlfileaopaspectjautoproxyaopinclude namemsghandlingaspect aopaspectjautoproxyi tried to annotate my class with configuration and enableaspectjautoproxybut nothing happened,['java'] +285936,can you access ui elements from another thread get not set i see a lot of threads on googlehere on updating a ui element from another threadwhat if i want to just get the value of a checkboxam i able to do this without having to do anything special,['c#'] +285944,use of yield and return in ruby can anyone help me to figure out the the use of yield and return in ruby i am a ruby beginner so simple examples are highly appreciatedthank you in advance,['ruby'] +285997,adding panels to splitcontainer in windows forms i am having trouble finding the documentation on how to add panels to a splitcontainer i can create the splitcontainer fine but i cannot put the panels i have coded inside of the splitcontaineri have tried doingsccontaineraddmypanelsccontaineraddmyotherpanelbut container is always null does anyone know what i am doing wrong,['c#'] +285999,how to turn onoff airplane mode in ios 51 using private api i am trying to toggle onoff airplane mode in ios 51 using private frameworks in appsupportframework radiospreferences has a property to getset the airplane mode and set the valueappsupportframeworkradiospreferenceshproperty bool airplanemodeappsupportframeworkradiospreferencesh voidsetairplanemodeboolarg1how can i use these methods do i need to use dlsym somehow to create an object and call the methods can someone help me with sample code or ways to do it,"['iphone', 'ios']" +286003,python lambdas binding to local values the following code spits out 1 twice i expect to see 0 and then 1def pvv print vdef test value valueappend0 valueappend1 x for v in value xappendlambda pvv return xx testfor xx in x xxi expected python lambdas to bind to the reference a local variable is pointing to behind the scene however that does not seem to be the case i have enountered this problem in a large system where the lambda is doing modern cs equavalent of a bind boostbind for example where in such case you would bind to a smart ptr or copy contstruct a copy for the lambda so how do i bind a local variable to a lambda function and have it retain the correct reference when used i am quite gobsmacked with the behaviour since i would not expect this from a language with a garbage collector the code in question looks as follows l3 e is the variable which is causing the problem for category in cat for l2 in catcategoryentries for l3 in catcategoryentriesl2entrysub entries l3 e catcategoryentriesl2entrysub entriesl3 url l3 eentryurl selfl4 processing statusl3 e 0 l3 thiscovery requestsappend request url callback lambda response selfparse l4responsel3 e print l3 eentryurl return l3 thiscovery requests,['python'] +286011,sql select newest records that have thistinct name column i did search around and i found thissql selecting rows by most recent datewhich is so close to what i want but i cannot seem to make it worki get an error column id is invalid in the select list because it is not contained in either an aggregate function or the group by clausei want the newest row by date for each thistinct nameselect idnamepricedatefrom tablegroup by nameorder by date aschere is an example of what i want tableid name price date0 a 10 201205031 b 9 201205022 a 8 201205043 c 10 201205034 b 8 20120501desired resultid name price date2 a 8 201205043 c 10 20120503 1 b 9 20120502i am using microsoft sql server 2008 thanks for any help or points in the right direction,['sql'] +286032,matplotlib define size of a grid on a plot i am plotting using matplotlib in python i want create plot with grid here is an example from plotting tutorial in my plot range if the y axe is from 0 to 14 and if use pylabgridtrue then it makes grid with size of square of two but i want the size to be 1 how can i force it,['python'] +286043,intel avx 256bits version of dot product for double precision floating point variables the intel advanced vector extensions avx offers no dot product in 256bit version ymm register for double precision floating point variables the why question have been very briefly treated in another forum here and on so here but the question i am facing is how to replace this missing instruction with other avx instructions in an efficient way the dot product in 256bit version exists for single precision fp variables ref here m256 mm256 dp ps m256 m1 m256 m2 const int maskthe idea is to find an efficient equivalent for this missing instruction m256d mm256 dp pd m256d m1 m256d m2 const int maskthanks for your suggestionsedit to be more specific the code i would like to transform from m128 4 floats to m256d 4 doubles use the following instructions m128 val0 4 float values m128 val1 m128 val2 m128 val3 m128 val4 m128 res mm or ps mm dp psval1 val0 0xf1 mm or ps mm dp psval2 val0 0xf2 mm or ps mm dp psval3 val0 0xf4 mm dp psval4 val0 0xf8 the result of this code is a m128 vector of 4 floats containing the results of the dot products between val1 and val0 val2 and val0 val3 and val0 val4 and val0maybe this can give hints for the suggestions,['c++'] +286055,python walk but tread lightly okay heres a doosyi would like to recursively walk a directory but i want python to break from any single listdir if it encounters a directory with greater than 100 files basically i am searching for a txt file but i want to avoid directories with large dpx image sequences usually 10 files since dpxs live in directories by themselves with no sub directories i would like to break that loop asapso long story short if python encounters a file matching dpx it stops listing the subdirectory backs out skips that subdirectory and continues the walk in other subdirectoriesis this possible to break a directory listing loop before all the list results are returnedthanksjamie,['python'] +286076,can selenium web driver have access to javascript global variables hi i am writing tests for django with javascript and i was wondering if the selenium webdriver can access a javascript global variable mypage has a script that has a global variable i would like to access is it possible thanksfrom djangotest import liveservertestcasefrom seleniumwebdriverfirefoxwebdriver import webdriverclass testeditorseleniumliveservertestcase def setupself selfdriver webdriver def test mytestself selfdrivergetss selflive server url mypage,"['javascript', 'python']" +286083,what is a good shopping cart gem for rails i want to implement basic shopping cart functionality in my rails appare there any good gems that will make this process simpleie i want the shopper to be able to add products and quantities to their checkout and i want the admin to be able to add new products to the store and editdelete existing onessuggestions,"['ruby-on-rails', 'ruby']" +286102,java annotation c equivalent possible duplicatewhat are the similarities and differences between java annotations and c attributes currently we are translating an java project into c but were having problems finding out what the c equivalent is for java annotation how do we write the exact same thing as this java code into cpublic interface latitudeannotation public string author default themaopdracht 7 tester,"['c#', 'java', '.net']" +286107,what is cordovaxml for in phonegap while trying to debug a phonegap error message call to opengl es api with no current context which does not appear to be causing any problems i came across a newer version of the cordovaxml file which ships with phonegap 16 and has the following line in itpreference nameclassicrender valuetrue adding this line to my copy of cordovaxml did not do anything but then i also noticed the comments and other lines in that file regarding access origins and i noticed that my app has the access origin set to 127001 but all my code is on a remote server and this does not seem to matteri searched for documentation but did not find anyso i have to ask what is the cordovaxml file for what directives can be put in it and what are they supposed to do,['android'] +286117,jquery ajax call return json parsing error i am using jquery to call an ajax wcf method that returns a list of objects as a json string the json string looks like this when inspecting it in fiddler2 in textviewdid6b2b8c6231ce4df2982b054ff5f6be72namecarolsurnameirishwifeidd254740a0a0f4a1e9e4f08127dd5afnamewilliesurnamele rouxid660bf0dd436a4588a9c019fd6fdcee23nameemmassurnamemumid6b9403c5b7284e96bcb1203e7472eec3nameowensurnamelimaidd52c08fb44184600960f243ff43ee6nametimsurnameleeide2aacf5b885544ce93383d39f8ab3349namemarcellosurnamemtid578be087838546d689de3db31d352cbcnamecarlynsurnamehomegroupid4c8058252bee447a8b7541ead17db33enamegeorgesurnamehomegroupidae48804f5e7842c89ba04214c98a5a89nameislasurnamele rouxidf8be2f4ffedb48638a84fddea84ea9namepetersurnameandersonid15e7644dec4344ffa95947e00112da6bnamekittysurnamecorbettid8fd7fc335c4d5c93b54b00f96a9950namenataliesurnamearchibaldid09b5aad22cf1488a962b4d692b05ddeanamemikusurnameheallyidaffa369e5af34537a0f471422956da41namestevensurnamecorbettid65f57da34f884798959083b4ccecfc44nametimsurnamearchibaldid53bfb451f66f4b6eb4308d13c95b30d8namephilipsurnamemtidc7f22b9b40304f829f75b726cabb73namevincentsurnamevan der waltid232577be31654316a20dc2f2a09c5382namescottsurnamelynnid913508a15dca45048cafc8e3dc386fc0namedansurnamemtid36054a07b14d4c1cb35fe00875dde7e5namesarahsurnamemtidf14e7d98e0404ba9928ff2ff48116b0bnamejoshsurnameirishdudewhen i inspect the result in fiddlers json view it shows the following jsondid6b2b8c6231ce4df2982b054ff5f6be72namecarolsurnameirishwifeidd254740a0a0f4a1e9e4f08127dd5afnamewilliesurnamele rouxid660bf0dd436a4588a9c019fd6fdcee23nameemmassurnamemumid6b9403c5b7284e96bcb1203e7472eec3nameowensurnamelimaidd52c08fb44184600960f243ff43ee6nametimsurnameleeide2aacf5b885544ce93383d39f8ab3349namemarcellosurnamemtid578be087838546d689de3db31d352cbcnamecarlynsurnamehomegroupid4c8058252bee447a8b7541ead17db33enamegeorgesurnamehomegroupidae48804f5e7842c89ba04214c98a5a89nameislasurnamele rouxidf8be2f4ffedb48638a84fddea84ea9namepetersurnameandersonid15e7644dec4344ffa95947e00112da6bnamekittysurnamecorbettid8fd7fc335c4d5c93b54b00f96a9950namenataliesurnamearchibaldid09b5aad22cf1488a962b4d692b05ddeanamemikusurnameheallyidaffa369e5af34537a0f471422956da41namestevensurnamecorbettid65f57da34f884798959083b4ccecfc44nametimsurnamearchibaldid53bfb451f66f4b6eb4308d13c95b30d8namephilipsurnamemtidc7f22b9b40304f829f75b726cabb73namevincentsurnamevan der waltid232577be31654316a20dc2f2a09c5382namescottsurnamelynnid913508a15dca45048cafc8e3dc386fc0namedansurnamemtid36054a07b14d4c1cb35fe00875dde7e5namesarahsurnamemtidf14e7d98e0404ba9928ff2ff48116b0bnamejoshsurnameirishdudeso fiddler can parse it successfully but on the client the jquery ajax error callback function thisplays the following errorerror no conversion from text to applicationjsonthe wcf method is defined as follows operationcontract webgetresponseformatwebmessageformatjson public string getpeopleguid groupid using schedulercontext context new schedulercontext javascriptserializer ser new javascriptserializer var query from p in contextpeople where pgroup id groupid select new pid pname psurname return serserializequerytoarray and finally the calling jquery isajax type get datatype applicationjson contenttype json data groupid ae09a0805d7c4e929a87591574b7c4b8 url webapisvcgetpeople error function jqxhr textstatus errorthrown alerterror success function msg alertmsgd0name thanks in advanceupdatethanks to user1370958 one step closer to the solutionwhen changing the error callback function to the following it successfully returns the resulterror function jqxhr textstatus errorthrown var test parsejsonjqxhrresponsetext var test2 parsejsontestd alerttest20namenot sure why but i have to parse the result and then parse the nested objects inside that i am assuming if any of my returned types contained complex objects it would also have needed another parse,['jquery'] +286140,what are the pros and cons of anchor modeling i am currently trying to create a database where a very large percentage of the data is temporal after reading through many techniques for doing this most involving 6nf normalization i ran into anchor modelingthe schema that i was developing strongly resembled the anchor modeling model especially since the use case temporal data known unknowns is so similar that i am tempted to embrace it fullythe two biggest problem i am having is that i can find nothing detailing the negatives of this approach and i cannot find any references to organizations that have used it in production for warstories and gotchas that i need to be aware ofi am wondering if anyone here is familiar enough with to briefly expound on some of the negatives since the positives are very well advertized in research papers and their site and any experiences with using it in a production environment,['sql'] +286146,should i convert stored markdown to html or should i just store html markdown seems to be easier to write and edit than html all html editors i have seen output a ton of unnecessary junk markdown seems cleanerhere is what i am thinking of doing storing markdown in the database converting it to html with php markdown then outputting that to the web browserone problem is that it would have to do this every time a page is requested this seems somewhat expensiveis this a good idea or is there a more efficient way to do this,['php'] +286157,solving polynomial equations in python up to now i have always mathematica for solving analytical equations now however i need to solve a few hundred equations of this type characteristic polynomialsa 20x20a 19x19a 1xa 00 constant floats a 0a 20at once which yields awfully long calculation times in mathematicais there like a ready to use command in numpy or any other package to solve an equation of this type up to now i have used python only for simulations so i do not know much about analytical tools and i could not find anything useful in the numpy tutorials,['python'] +286167,interesting mobile safari hidden content issue so this intersting problem i am having with this web app in mobile safari that i have not been able to fix as of yeti have a thisplaynone menu div that appears on click when the menu is thisplayed the content within the div thisplays as it should the problem lies within the offscreen content when the div content is scrolled the offscreen content that is now within the viewport wont show at all until the scrolling has completely stopped it is not a loading issue because all the content has actually loaded already and this continues to happen even when you scroll back up to the topthis doesnt happen with the content that is actually on the page just the content that is loaded within the hidden menu divs i am not using any special coding or anything just standard css and the jquery click function i have tried every method i can think of to fix this using the actual page scroll instead of a scroll within the div fixed the content thisplay issue but for some reason it wouldnt scroll with momentum and the hidden div itself would take longer than it should to appear maybe like 2 seconds which of course will never be okayany ideas how to fix thisedit code belowthe cssmenu width720px height100 overflowauto webkitoverflowscrollingtouch backgroundcolor0 thisplaynone positionabsolute zindex97mainmenu width100 thisplaynone backgroundcolor0the htmldiv idmenudiv idmainmenua hreftemplatesmyaccountphp classclosediv idmenuitem img srcimagesmenuaccountpng div idmenushadowdiv div idmenuitemtitlediv classmenuitemtitleaccount settingsdivdivdivaa hreftemplatesmyaccountphp classclosediv idmenuitem img srcimagesmenuaccountpng div idmenushadowdiv div idmenuitemtitlediv classmenuitemtitleaccount settingsdivdivdivaa hreftemplatesmyaccountphp classclosediv idmenuitem img srcimagesmenuaccountpng div idmenushadowdiv div idmenuitemtitlediv classmenuitemtitleaccount settingsdivdivdivaa hreftemplatesmyaccountphp classclosediv idmenuitem img srcimagesmenuaccountpng div idmenushadowdiv div idmenuitemtitlediv classmenuitemtitleaccount settingsdivdivdivadivdivdiv idwrapper div classcontentloadingdiv div classcontentarea div classcontent pageurldiv divdivdiv idbtnmenu classbarbuttonimg srcimagesbarbtnmenupng divthe jqueryscript typetextjavascriptbtnmenuclickfunction menushow mainmenushow bottombarcloseshowscript,"['html', 'css']" +286171,how would i detect if multiple attribute is supported for file input elements internet explorer does not support the multiple attribute for input typefile however its not only ie that lacks this support also certain mobile browsers do not support the multiple attribute so simply detecting that the browser is ie is not the ideal solutionso how would i detect if the multiple attribute is supported for for input typefile with javascriptupdateit seems like modernizr has support for new html5 input element attributesthe accepted solution seems to work however since i am already using modernizr my solution is the following determines if the given attribute is supported for input elements param attribute the attribute to test for ex multiple function isinputattributesupportedattribute return modernizrinputattribute true false,['javascript'] +286193,how can i thisable phps easter egg urls i recently found out about the socalled easter egg urls in phpthese are the four query strings you can add to the end of a php web page to view a somewhat hidden image or web pagephpe9568f36d42811d2a76900aa001acf42this one is the most interesting and thisplays an easter egg image of either a rabbit in a house sterling hughes rabbit named carmella a brown dog in the grass a black scottish terrier dog a sloppy child handdrawn crayoncolored php logo a guy with breadsticks looks like pencils or french fries sticking out of his mouth like a walrus or a php elephant logoothers includephpe9568f34d42811d2a76900aa001acf42 php logophpe9568f35d42811d2a76900aa001acf42 zend logophpb8b5f2a03c9211d3a3a94c7b08c10 php creditsi was shocked to thiscover that this does work on a lot of websites including my own i think this is idiotic and want to thisable it but from what i hear the only way to do it is in phpini with expose php off and it cannot be set at runtime with ini seti do not have direct access to phpini on the live server i have however figured out how to unset the xpoweredby header by using header unset xpoweredby in htaccess or headerxpoweredby in the php codeis there any other way i can thisable these easter eggs or do i have to get this setting changed in the main phpini and is that indeed the correctonly way to thisable these urls,['php'] +286194,array walk vs array map vs foreach i am trying to compare these three but it seems only array map works input array hello whsdf lve you input2 array hello whsdf lve you input3 array hello whsdf lve you time start microtimetrueinput array maptriminputtime end microtimetruetime time end time startecho did array map in time secondsbrforeachinput as in echo in strleninbrtime start microtimetruearray walkinput2trimtime end microtimetruetime time end time startecho did array walk in time secondsbrforeachinput2 as in echo in strleninbrtime start microtimetrueforeachinput3 as in in trimintime end microtimetruetime time end time startecho did foreach in time secondsbrforeachinput3 as in echo in strleninbrwhat am i doing wrong heres the outputdid array map in 0180602722168 secondshello 5whsdf 5lve you 7 0did array walk in 014209747314453 seconds hello 10whsdf 41 lve you 37 30did foreach in 012993812561035 seconds hello 10whsdf 41 lve you 37 30it is not trimming for array walk and the foreach loop,['php'] +286204,command not found error in exec command i run this from php fileexecepm packagei got below error in error logsh epm command not foundi tested manually in terminal it works fine,['php'] +286224,uitextview scroll while editing i have got a big uitextview nearly full screen if i tap it the keyboard pops up and i can edit the text however the longer i type eventually the text runs down the view behind the keyboard i can no longer see what i am typinghow do you deal with this do you have to track the cursor position and scroll the view manually,['ios'] +286239,cstdio stdioh namespace i see this line from the c reference for cstdioevery element of the library is defined within the std namespacebut i tried the codestdprintfhello world printfhello worldis it true that c headers puts the names in both the std and the global namespace,['c++'] +286278,does printf null pointer with p always give nil i wonder if doesint a nullprintfpn awill always gives nil output does it depend on standard library implementation or it is a c99 standard specification,['c'] +286280,why is not 123 0123 in java i am developing an application in android using eclipse i wrote the following code and in tests the first and third if block is not reachable whywhen i add a leading zero to a number the equal operator returns falseint var 123if var 0123 not reachableif var 123 reachableif var int0123 not reachableif var int123 reachable,['java'] +286282,pip install and python path i am using pip install on a mac to get my python requirements for a django websitei got pip from macports port install pip27now the problem is the pip installs the packages in a location which is not in my python syspathi just copied this bogus location optlocallibraryframeworkspythonframeworkversions27libpython27 to a location present in my syspath librarypython27of course this worked ok but i will use pip in the future so i need a persistent solutionthe question is how can i alter my syspath to recognize that crap location or how do i tell pip to install dependencies somewhere else,['python'] +286341,retaining list in list fragment on orientation change i have an app using fragments all of which are contained in a single activity the activity starts with a fragment containing a menu of buttons all of which cause various listfragments to replace the original buttonmenu fragmentmy problem is that upon an orientation change if the activity is thisplaying one of the listviews it goes away and the button menu returns i understand why this is happening the activity is destroyed and recreated but not how to work around it and maintain the list viewcurrent fragment through the orientation changei have found setretaininstance and the example of use here but i cannot figure out how to apply it to my situation with the button menu or the possibility that the fragment i want to retain could be one of several different onesbelow is code simplified to show the main activity and one of the listfragmentsany pointers in what to add where to make it so that the list fragment will be retained would be greatly appreciatedactivitypublic class main extends fragmentactivity private mainmenufragment menu override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain menu new mainmenufragment getsupportfragmentmanagerbegintransactionreplaceridpane menucommit listfragmentpublic class itemlistfragment extends listfragment private textview header private textview empty private button add public static cursor itemcursor private grocerydb mdbhelper public static long mrowid public static checkcursoradapter lists override public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate view v inflaterinflaterlayoutcommon list container false header textview vfindviewbyidridheader empty textview vfindviewbyidandroidridempty headersettextrstringheader item emptysettextrstringempty items return v override public void onactivitycreatedbundle savedinstancestate superonactivitycreatedsavedinstancestate mrowid0 mdbhelper new grocerydbgetactivity mdbhelperopen itemcursor mdbhelperfetchallitems getactivitystartmanagingcursoritemcursor string from new string grocerydbitem name int to new int ridlistitem lists new checkcursoradaptergetactivity rlayoutlistlayout itemlist itemcursor from to setlistadapterlists,['android'] +286362,auto complete exact match from start using jquery autocomplete from simple array how do i enable exact match from start of string using jquery autocomplete with input from simple arrayif i have the following in an arraysmartoversmartsmartlandundersmartverysmartand if i am typing sma in the text input i must be shown only smart and smartland not the others,"['javascript', 'jquery']" +286401,ruby mocking a class method with minitest i am using minitest 2121 the latest version of the stock testing framework shipped with ruby 19 and i cannot figure out how to mock a class method with it the same way it is possible with the likes of mocha for exampleproduct productnewproductexpectsfindwith1returnsproductassert equal product productfind1i have been dabbling the internet for days and i am still to find a reasonable answer to this please help,['ruby'] +286439,mysqli prepared statement unable to get result i am totally confused by mysqli although i have been using procedural mysql calls for years i want to get used to making prepared statements for the db securitymysql injection protection it offers i am trying to write a simple select statement yes i know making a procedural call for this offers performance enhancement when run i get all the echoes until i hit the result stmtget result component it all seems fairly straightforward to me but i am at a loss after hours of reading manuals on mysqli any ideas why this would be failingnote this is a test environment and while no sanitizingescaping of characters is taking place i am only passing valid content into the variables username and email and also i have looked all over so to find the solution to my issuefunction checkusernameemailavailabilityusername email instantiate mysqli connection mysqli new mysqlic hostc userc passc base or diefailed to connect to mysql database if mysqli echo error could not connect to database please try again later exit else echo mysqli created create a prepared statement ifstmt mysqli prepareselect usernameemail from tb users where username or email echo br mysqli bind parameters s string b boolean i int etc stmt bind paramss username email echo br paramsbound execute it stmt execute echo br executed result stmtget result echo br result acquired now you can fetch the results into an array nice myrow resultfetch assoc echo br fetched close statement stmt close echo br done mysqli also do i have to instantiate a mysqli every time i call a function i am assuming they are not persistent db connects like in procedural mysql yes i am aware this is a scope issue and no i have not been able to understand the scoping of this class variable when i declared it outside of the function it was not available when i came into the functionupdateif i change line 12 fromifstmt mysqli prepareselect usernameemail from tb users where username or email to stmt mysqlistmt init ifstmt mysqli prepareselect usernameemail from tb users where username or email ifstmt echo statement prepared else echo statement not preparedi get statement not prepared now i am even more confusedupdate i contacted my hosting provider and apparently mysqli is supported and the mysqlnd driver is present perhaps there is a way to simply test this although they usually have given me pretty knowledgeable answers in the pastupdateagain i checked my server capabilities myself and thiscovered while mysqli and pdo are present mysqlnd is not thusly i understand why get result will not work mysqlnd required i think i still do not understand why the prepared statement itself will not work,['php'] +286440,making a mobile application from an existing website i have already developed a fullyfunctioning website and our team is looking to export this site to an iphone application and eventually other platforms the best example i can give is i basically have made facebook now i want to make facebooks app the one that is launched from an iphones home screen not from the browser so obviously we already have the functionality and we just need to convert it to another platform how difficult is this will we have to make a completely new piece of software and basically ignore all of the existing php code that we already have the app is basically going to be the same as the website except for a few layout changes we might want it to be able to access the camera feature and definitely be able to upload a picture which i think would rule out a mobile application i still do not understand the delineation between making a mobile application and an application that launches from the home screen of an iphone do you guys have any suggestions as to where to start and how difficult this all will be if we can get the functionality we want and make it easier on ourselves by using existing code we would be thrilledthanks,"['iphone', 'ios']" +286456,htmleditorform m lambda syntax in mvc i am just learning c and mvc and trying to understand some exampleshtmleditorform meventually i figured out that is the lambda operator and that it means something like m such that m that does not really make any sense to me why not just pass in malso i do not see m defined in any view that i am working with model is defined and allegedly that is what this method is picking up how does that workfinally i looked at the definition for htmleditorfor and do not see any overload for passing in just a single parameter where is this syntax defined,['c#'] +286458,multiple threads calling the same function suppose we have multiple threads all calling the same functiondef foo do stuff end100times do i threadnew do foo endendif two or more threads are currently inside of foo do they each share the same local variables within foothis relates to my second question do threads have individual stack frames or do they share stack frames within a single process specifically when multiple threads each invoke foo and before foo returns are there multiple copies of foo on the stack each with their own local variables or is there only one copy of foo on the stack,['ruby'] +286461,how to define constant array in glsl opengl es 20 i just want to store an array of weights that needs to every fragment calculationthisfloat weights5 float534 42 50 52 11just throws thiserror 030 syntax error syntax errorerror 030 syntax error syntax error,['iphone'] +286475,jquery sortable get index before and after sorting i am using jquerys sortable on a tagging pluginthe plugin maintains an array of objects that relate to the lis in the same order as the actual itemsi need to update the order of the items in the array when the sorting finishesi thought i would just be able to in the start event call uiindex and in the update event call the same which would give me the initial position and the final position but both calls return 1how should i do thisstructureulliherea classclosexaliliarea classclosexalilisomea classclosexalilitagsa classclosexaliularray structure label here value 36 element the li that this info is about index 0 label are value 42 element the li that this info is about index 1 label some value 21 element the li that this info is about index 2 label tags value 26 element the li that this info is about index 3javascriptulsortable start functionevent ui update functionevent ui,['jquery'] +286477,membershipuserisonline is true even after logout i am currently creating a website using visual studio 2010 i am using the default membership schema in sql server 2008 for user authentication now i am facing the following problem when a user logs out the membershipisonline property of that user should be set to false however that it is not happening membershipisonline property of that user is still true i am using the loginstatus control to provide a logout link to the useri have tried to follow userisonline true even after formsauthenticationsignout but results nothing,['asp.net'] +286493,key events processcmdkey i am trying to get some keyboard response happening on a little test windows form application and i have a rough solution which is to override processcmdkey however there are several issues i am encountering and inconsistencies i am findingdifferent events is there a way to tell in the arguments ref message msg keys keydata whether the even is a keydown a keyup or a keypresskeypress everywhere i have looked says that keypress ie a repeated keyboard input only happens for character keys which the arrow keys are not however the event handler is being called as frequently and in the same mannorwith the same behaviour for the arrow keys as character keys is this in face a keypress event or is it something elsei would ideally like a way to handle at form level all keyboard events without letting them get passed to the controls on the form however all the documentation sufficiently confused me and missed key points so that i have not been able to complete thishelp on any of these topics is appreciated thanks,"['c#', '.net']" +286500,how to limit number of characters in a textarea field processing php i am using a a textarea field in a form that is made on html and the processing is done by php i want to limit the number of characters the user can enter in the textarea is there any way by which this can be done because the textarea field is then stored into a mysql database and thus i have to limit the user data according to the varchar value of the fieldany help,"['php', 'html']" +286539,making two strings into one let us say i have 2 stringsabcandabcto make these strings as similar as possible given that i can only remove characters i shoulddelete the last c from the first stringdelete the last a and the last b from the second stringso that they becomeabcwhat would be an efficient algorithm to find out which characters to remove from each stringi am currently crushing my brain cells thinking about a sollution involving substrings of the strings looking for them in the other string,['python'] +286559,aspnet mvc 3 razor navigate to view on table tr click i have users list table how i can navigate on url usersshowprofileuseridi want to make table when user clicks on table row navigate on current user profile thanks,"['c#', 'asp.net']" +286564,compile pypy to exe i know how to compile cpython file to exe using cx freeze but is it possible to compile a simple program using pypy to exe,['python'] +286600,send mail with php phpmailer via office365 in hostgator i want to be able to send mails in hostgator via office365 i was able to do it with gmail but can not set it up to work with office365it works on my 2 other servers i have just fine the only problem is hostgatordo they have to take some actionphprequire onceclassphpmailerphpmail new phpmailertruemailissmtpmailsmtpdebug 2mailsmtpauth truemailsmtpsecure tlsmailhost pod51014outlookcommailport 587mailusername usernameheremailpassword addaddres reply subject message the usual stuff you need mailsendi just keep getting following responcesmtp error failed to connect to server connection refused 1 i was on the support chat with them and the 587 port should be open,['php'] +286607,how do i get size of the screen excluding unity side panel in gdk i am trying to make guake terminal work correctly in unity its window have width that is equal to screen width but because of unity left bar windows right border becomes invisible so i want to set proper width for window it must be smaller than actual window size and the code must work correctly with or without unitythis is how guake determines position and size of its windowdef get final window rectself gets the final size of the main window of guake the height is the window height property width is window width and the horizontal alignment is given by window alignment screen selfwindowget screen height selfclientget intkeygeneralwindow height width 100 halignment selfclientget intkeygeneralwindow halignment get the rectangle just from the firstdefault monitor in the future we might create a field to select which monitor you wanna use window rect screenget monitor geometry0 total width window rectwidth window rectheight window rectheight height 100 window rectwidth window rectwidth width 100 if width total width if halignment align center window rectx total width window rectwidth 2 elif halignment align left window rectx 0 elif halignment align right window rectx total width window rectwidth window recty 0 window rectwidth 250 return window rect,['python'] +286622,a redirect to from destroy action always gets delete verb whatever method i declare i have the following method in a controller named tareas controllerdef destroy tarea tareafindparamsid tareadestroy respond to do format formathtml redirect to tareas url formatjson head ok formatjs redirect to controller clientes action show id tareacliente format js methodget endendthe record gets deleted ok after that i get the following code on the serverredirected to completed 302 found in 174msstarted delete clientes12jsmethodget for 127001 at 20120506 192007 0200 processing by clientescontrollerdestroy as js parameters methodget id12 cliente load 00ms select clientes from clientes where clientesid limit 1 id 12 sql 20ms delete from clientes where clientesid id 12 completed 406 not acceptable in 131msit seems to send the request with a delete verb to the new controller and i cant find a way to change that to a get request to the new controllercan someone give me advise as to how to resolve this issue,['ruby-on-rails'] +286623,jsonpath query to get nodenames consider the following piece of jsonpath result typeresidence streetpiazza di spagna city40 typeresidence streettest city41 is it possible to get a list of all the nodenamesso for example i want a list like type street city,['php'] +286696,gcc g vs g3 gdb flag what is the difference when compiling c source code with either gcc or clang i always use the g flag to generate debugging information for gdbgcc g o helloworld helloworldci noticed that some people recommend g3 instead what is the difference between the g and g3 flags also is there a difference between g and ggdb,['c'] +286701,why use inotifypropertychanged with bindings in wpf i have notived that practically every example i find on the internet about bindings has a class which binds to another property that inherits the inotifypropertychanged interface and uses a method in the set part of the class property i have tried removing that part from the binding example and it worked the same as it would with the method heres the example i have altered it so it would be a twoway bindingmode and show the changed property in a messageboxi did that just to play around a little bit with bindings but now i really do not know why that interface is usededitxamlwindow xclasswpfapplication1mainwindow xmlns xmlnsx titlemainwindow height350 width525 grid gridrowdefinitions rowdefinition height30 rowdefinition height30 rowdefinition height30 rowdefinition height30 rowdefinition height30 rowdefinition height40 rowdefinition height30 rowdefinition height30 rowdefinition height30 rowdefinition height30 gridrowdefinitions gridcolumndefinitions columndefinition width30 columndefinition width30 columndefinition width30 columndefinition width30 columndefinition width30 columndefinition width100 columndefinition width30 columndefinition width30 columndefinition width30 columndefinition width30 columndefinition width30 columndefinition width30 columndefinition width30 columndefinition width30 columndefinition width30 columndefinition width30 gridcolumndefinitions button gridrow5 gridcolumn5 namebtnbinding clickbtnbinding click width100 height30 grid horizontalalignmentleft verticalalignmentcenter gridrowdefinitions rowdefinition height25 gridrowdefinitions gridcolumndefinitions columndefinition width50 columndefinition width50 gridcolumndefinitions textbox nametxtbinding width30 height25 horizontalalignmentleft label gridcolumn1 contentbind grid button button gridcolumn5 gridrow6 namebtnmessage clickbtnmessage click contentmessagebox button gridcolumn5 gridrow4 namebtnchangeproperty clickbtnchangeproperty click contentchange property gridwindowmaincsusing systemusing systemcollectionsgenericusing systemlinqusing systemtextusing systemwindowsusing systemwindowscontrolsusing systemwindowsdatausing systemwindowsdocumentsusing systemwindowsinputusing systemwindowsmediausing systemwindowsmediaimagingusing systemwindowsnavigationusing systemwindowsshapesnamespace wpfapplication1 summary interaction logic for mainwindowxaml summary public partial class mainwindow window binding bind mydata mydata public mainwindow initializecomponent private void btnbinding clickobject sender routedeventargs e mydata new mydatat bind new bindingmydataproperty source mydata mode bindingmodetwoway txtbindingsetbindingtextboxtextproperty bind private void btnmessage clickobject sender routedeventargs e messageboxshowmydatamydataproperty private void btnchangeproperty clickobject sender routedeventargs e mydatamydataproperty new binding mydata classusing systemusing systemcollectionsgenericusing systemlinqusing systemtextusing systemcomponentmodelnamespace wpfapplication1 public class mydata private string mydataproperty public mydata public mydatadatetime datetime mydataproperty last bound time was datetimetolongtimestring public mydatastring teste mydataproperty teste public string mydataproperty get return mydataproperty set mydataproperty value onpropertychangedmydataproperty public event propertychangedeventhandler propertychanged private void onpropertychangedstring info propertychangedeventhandler handler propertychanged if handler null handlerthis new propertychangedeventargsinfo,['c#'] +286716,using redirect to with a specific activerecord object to create a link to that object i am going through michael hartls tutorial at it is basically a message board app where users can post messages and others can leave replies right now i am creating users inside the userscontroller things look like this class userscontroller applicationcontroller def new user usernew end def show user userfindparamsid end def create user usernewparamsuser if usersave flashsuccess welcome to the sample app redirect to user else render new end end endthe author says that the following lines are equivalent which makes sense to me user usernewparamsuser is equivalent to user usernewname foo bar email fooinvalid password foo password confirmation barredirect to user redirects to showhtmlerb how exactly does that work how does it know to go to showhtmlerb,['ruby-on-rails'] +286747,openlayers latitude inaccurately captured in webkit mobile browsers i am programming a page with a map where i need to capture the location of the tapclick on a map and store the coordinates i am using openlayers js on desktop browsers ieffchrome this is working fine on mobile devices the tap is getting captured correctly on the default android browser both in real devices and emulators however on mobile webkit browsers iphone safari android chrome beta we are having a problem where the tap is getting captured for a few pixels higher towards the north of the actual tap the error is not fixed so i cannot just add 100 to the events xy to recalibrate the top here is the code i am using as the clickhandleropenlayerscontrolclickhandler openlayersclassopenlayerscontrol defaulthandleroptions single true double false pixeltolerance 0 stopsingle false stopdouble false initialize functionoptions thishandleroptions openlayersutilextend thisdefaulthandleroptions openlayerscontrolprototypeinitializeapply this arguments thishandler new openlayershandlerclick this click thistrigger thishandleroptions trigger functione thatinputlonlat epsg4326 null var lonlat thatinputmapgetlonlatfromviewportpxexy thatlogmessagexy exy thatlogmessagelonloat lonlat thatinputmarkersclearmarkers thatinputmarkersaddmarkernew openlayersmarkerlonlatthaticonsgreenclone lonlattransformthatinputmapgetprojectionobject new openlayersprojectionepsg4326 thatinputlonlat epsg4326 lonlat for the moderation sections alertlatitudevalthatinputlonlat epsg4326lat alertlongitudevalthatinputlonlat epsg4326lon lonlat2transformthatinputmapgetprojectionobject new openlayersprojectionepsg4326 thatlogmessagestored lat thatinputlonlat epsg4326lat thatlogmessagestored lon thatinputlonlat epsg4326lon thatcallfunctionthatinputmaplistener e should i be doing anything differently has anybody else seen the inaccuracy problem on mobile webkit browsers while using openlayers,['javascript'] +286751,proto when will it be gone alternatives mozilla claimed it would remove proto a while back 2008 and it is still in the browser is it still going to be deprecated it works in opera safari i think and chrome as well i do not need to worry about ie so i would love to keep using it however i do not want my code to stop working one day so on to my question proto allows for dead simple inheritancea proto atestis there anyway i can replicate this in a standards compliant way i know there is functional inheritance that is ugly and it overcomplicates the fact that i just want to create a prototype chain just wondering if any wizards have solved this thanks,['javascript'] +286780,list is a raw type references to generic type list should be parameterized below is my syntax list synchronizedpubliesdlist collectionssynchronizedlistpubliesdlisti am getting a syntax error of list is a raw type references to generic type liste should be parameterizedplease suggest the solution,['java'] +286820,in java can anonymous classes extend another class code likeprotected interface1 varclass1 new interface1 but i would also like that this anonymous nested class also extends the class base something likeprotected interface1 varclass1 new interface1 extends base is this possible in java,['java'] +286849,how to check whether session is expired or not in aspnet i ve specified the session time out in webconfig filewhen the session is timeout im not getting redirect to login page but i am geting error saying object reference not set to an instancecan any one tell me the solution for this,"['c#', 'asp.net']" +286851,how to select any video or movie file from uiimagepickercontroller in my app i need to select any video file and show the thisplay the url for a video file in the application voidviewdidload super viewdidload selfimgpicker uiimagepickercontroller alloc init selfimgpickerdelegate self selfimgpickersourcetype uiimagepickercontrollersourcetypesavedphotosalbum selfimgpickermediatypes nsarray arraywithobjectsnsstring kuttypemovie nsstring kuttypeimage nil selfimgpickerallowsediting no self presentmodalviewcontrollerselfimgpicker animatedyesvoidimagepickercontrollerdidcanceluiimagepickercontroller picker picker thismissmodalviewcontrolleranimatedyesvoidimagepickercontrolleruiimagepickercontroller picker didfinishpickingimage uiimage image editinginfonsdictionary editinginfo voidimagepickercontrolleruiimagepickercontroller picker didfinishpickingmediawithinfonsdictionary info value 1 image counter image counter 1 nsstring mediatype info objectforkeyuiimagepickercontrollermediatype if mediatype isequaltostringpublicmovie nslogpicked a movie at url info objectforkeyuiimagepickercontrollermediaurl nsurl url info objectforkeyuiimagepickercontrollermediaurl nslog url absolutestring else uiimage image info objectforkeyuiimagepickercontrolleroriginalimage nsdata imagedata uiimagejpegrepresentationimage 10 nsstring incrementedimgstr nsstring stringwithformat usercustompotraitpicdjpg image counter nsarray paths nssearchpathfordirectoriesindomainsnsdocumentdirectory nsuserdomainmask yes nsstring documentsdirectory paths objectatindex0 nsstring fullpathtofile2 documentsdirectory stringbyappendingpathcomponentincrementedimgstr imagedata writetofilefullpathtofile2 atomicallyno i have used the above code to thisplay image and video every thing is coming fine however when i select any video file it did not comes to uiimagepickercontroller delegate method video file directly plays i do not want to play any video file when i select any video file it should come in its delegate property,['iphone'] +286856,thismiss dialogfragment onclick i was trying to make a dialogfragment that could be thismissed when tapped after some search i decided to go with this implementationpublic class errordialogfragment extends robodialogfragment private static final string message arg messageprivate textview textpublic errordialogfragment newinstance string message errordialogfragment f new errordialogfragment bundle args new bundle argsputstringmessage arg message fsetargumentsargs return foverridepublic view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate view v inflaterinflaterlayouterror dialog fragment container false vsetonclicklistenernew onclicklistener override public void onclickview v errordialogfragmentthisthismiss text textview vfindviewbyidriderror dialog text textview textsettextgetargumentsgetstringmessage arg return voverridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate setstyledialogfragmentstyle no title 0the alert dialog can have a custom message and will be thismissed when tappeddo you think is a better way to achieve thisthanks,['android'] +286861,simple php voting system i have a simple application which allows users to submit problems and then comment on them i am attempting to make a simple voting system so users can vote up problems which in turn will push them higher up a list i have some basic knowledge of php and everything so far is working i just cannot figure out how to get this to worki have followed a tutorial online and so far have this on my problemphp pageif isset getvote getid add problem vote getid getvote a hrefvoteupampidphp echo problemid voteaand on my functionsphp pagefunction add problem voteproblemid vote problemid intproblemid vote vote up sql update problems set votes votes vote 1 where id problem id mysql querysqlall my table fields are definitely named correctly i know there are many things to consider like revoting after the session has closed but as long as i have shown the idea it does not have to be perfect at the minute when the link is clicked it redirects to a page but the votes do not change in the mysql table,"['php', 'mysql']" +286863,how to thisable any event on a view in android my question is simple how to thisable any event on a view in android including removing its focussability like i just want it to be there visually but be inexistant on everything else and does it work on a whole view tree like if i thisable events on the root all the events will be thisabled for its childrennow before you say anything i have tried all the followingsetenabledsetfocusablesetselectedsetclickablesetactivated and none of these methods appear to work seriouslyi have tried them directly on a webview as well as on the parent layout on everything but i am still able to interact with itany ideathanksedit1the solution that consists in adding a view on top of the view that needs to be thisabled does not work actually it is still possible to click on the inner view i have tried with a simple examplexml version10 encodingutf8framelayout xmlnsandroid androidlayout widthmatch parent androidlayout heightmatch parent linearlayout androidlayout widthmatch parent androidlayout heightmatch parent androidorientationvertical androidbackgroundff0 button androidididbutton androidlayout widthmatch parent androidlayout heightmatch parent androidtextclick me linearlayout framelayout androidlayout widthmatch parent androidlayout heightmatch parent androidbackground0 framelayouthere it is still possible to click on the buttonedit2the reason why i want to do this is related to the following question that i asked weeks ago what i have is a listviewacting as a navigation bar which is underneath a view that holds the content of my app the problem with this implementation is that when i try to scroll through the listview when there is a focusable view in the layer on top of it well the listview does not scroll and instead it is the top view that takes focus that is the case when there is a webview or an edittext etc so yes as mentioned in one of the answers i can thisable any click events on a webview by overriding setontouchlistener but the view remains focussed and i think this is the reason why i am still having the same issue with my navigation bar,['android'] +286896,transient sectionnamekeypath nssortdescriptor nsfetchedresultscontroller i have a list of tasks within core data i fetch them into a uitableview using an nsfetchedresultscontrolleri need custom sections in a custom order overdue active ongoing postponed completedto determine what section a task should go in i use a derived transient attribute calculated on the fly based on other attributes in the relative object unfortunately you cannot pass a derived value as a sort descriptor used by a fetch request this is because a fetch relies on already having data it is being asked to fetch chicken eggi understand why i cannot do it that does not help me solve the problemi have triedsubclassing nsfetchedresultscontroller to customise creation ofsections and index titles maybe i am doing this wrong however this just changes the names and orders of sections not how many things go in those sections which is criticalpopulating arrays per section and feeding them to the table clunky slow yet fully worksripping out ongoing postponed tasks which works but is not ideal this way i can sort by duedate and drive the sectionnamekeypath via the transient valuesdoes anyone have any better ideas there are quite a few questions already just like this one yet none of them come to a neat solutionthanks in advancecheers,"['iphone', 'objective-c']" +286900,propertygrid readonly property on objectlevel i want to thisplay multiple instances of one class in my propertygrid the class looks like thispublic class parameter descriptionthe name public string name get set descriptionthe value readonlytrue public string value get set descriptionthe description public string description get set i have many instances of that class in a treeview when i select one of them in my treeview the properties are getting thisplayed right in the propertygridand here comes my problemfor each single instance i want to be able to thisable editing so the user cannot modify a specific property by setting readonlytrue within my class all value properties will be thisabled on a classlevelafter some research i found the following solution which gives me the opportunity to enablethisable a specific property at runtime this is what i needpropertydescriptor descriptor typedescriptorgetpropertiesthisvaluereadonlyattribute attr readonlyattributedescriptorattributestypeofreadonlyattributefieldinfo isreadonly attrgettypegetfield isreadonly bindingflagsnonpublic bindingflagsinstanceisreadonlysetvalueattr falsethis solution works just fine but unfortunately also on classlevel only this means if i set the values isreadonly to false all of my parameterobjects have the value property writeable but i want this only on that one particular object thus objectlevel i really do not want to create separate classes for readwrite and readonly propertiesas i am running out of ideas your help is much appreciated thanks in advanceedit i need the readonly properties to be grayedout so the user can see that it is thisabled for editing,"['c#', '.net']" +286915,is there a way to use canvas in ie7 or ie8 is there any workaround to use canvas tag in ie7 and ie8 pls let me know input typetext idtextsign valuesign input typebutton onclickjavascriptreturn changesign valuechangesign canvas ide width150 height100canvasscript typetextjavascriptvar textsign documentgetelementbyidtextsignvalue function changesign textsign documentgetelementbyidtextsignvalue var canvas documentgetelementbyide var context canvasgetcontext2d contextfillstyle 4c4c4c contextfont 30px giddyup std contextfilltext textsign 20 50 script,"['javascript', 'html']" +286917,intellij idea gui builder a no java code generated i have designed my gui form in the intellij idea gui designer and selected the radio button in project settings a gui designer to generate source code instead of class files but my java file with code looks like thispublic class povrayemptyprojectwizardpanelvisual private jtextfield textfield1 private jtextfield textfield2 private jtextfield textfield3 private jbutton button1thatas it a no code creating the gui was generated how do i manually trigger such code generation so that i can compile the resulting java file with maven,['java'] +286920,backbone sync override append url with query string i have some trouble appending a token to the backbone url query string and hope you guys could help me out here three things to know there is a rest api that expects a token with each requestan nginx backend that does auth serves the backbone app proxy req to the api under apii am a new to javascript backbone the backbone app actually reads the token from a cookie and i need to append this to the request url everytime backbone makes a call i see this can be done by overriding backbone sync but it troubles me in a few different things like this is what i doconsolelogoverriding backbone syncvar key tokenbackboneold sync backbonesyncbackbonesync functionmethod model options if method read if modelurlindexofkey 1 modelurl modelurl key key else old url modelurl if old urlindexofkey 1 modelurl function return old url key key backboneold syncmethod model optionsmodelurl was returning a function when its not a read method and did not know how to handle it well and the other trouble is when a consecutive request is made the token is added twice i tried to remove it with that indexof stuff with no luck is there a better way to do this,"['javascript', 'jquery']" +286934,maven what is pluginmanagement this is a snippet of my pom file plugins plugin groupidorgapachemavenpluginsgroupid artifactidmavendependencypluginartifactid version24version executions execution phaseinstallphase goals goalcopydependenciesgoal goals configuration configuration execution executions plugin pluginsi use it successfully with the command mvn installbut when i try to enclose it into the pluginmanagement tag the mavendependencyplugin stops to work when i launch the install goalwhy the pluginmanagement tag change the build behavior or should i use another goal or option thank you in advance for any help,['java'] +286965,registering gpx or xml file to open in ios app i am having trouble opening gpx files in my ios app i registered the extension and some files open correctly that is when i tap on a link to gpx file in safari it shows a prompt asking me which application i want to use to open the file then i select my application and the file is processed as expected with some websites in safari and with all files from email attachments the prompt and app selection is not thisplayed and the browseremail app shows contents of the file as text i suspect this is problem with the infoplist settings or possibly with the safari and email apps if you open xml or gpx files in your ios apps correctly would you post your cfbundledocumenttypes and utexportedtypedeclarations settings from infoplist any thoughts are welcome here is the appropriate section from my infoplist i tried to add and remove some optional tags this is the latest but not most completekeycfbundledocumenttypeskeyarray dict keycfbundletypeiconfileskey array stringiconpngstring stringstring array keycfbundletypenamekey stringgps exchange formatstring keycfbundletyperolekey stringviewerstring keylshandlerrankkey stringownerstring keylsitemcontenttypeskey array stringorgelsnersindiciumgpxstring array dictarraykeyutexportedtypedeclarationskeyarray dict keyuttypeconformstokey array stringpublicxmlstring array keyuttypedescriptionkey stringgps exchange formatstring keyuttypeidentifierkey stringorgelsnersindiciumgpxstring keyuttypetagspecificationkey dict keypublicfilenameextensionkey array stringgpxstring stringgpxstring array dict dictarray,['ios'] +286970,thisabling the keyboards send button when nothing has been typed yet android i am creating a search option in an android applicationafter pressing search on the screenkeyboard an event triggers which sends the query to the serverwhat i want to do is thisable the search button on the screenkeyboard when no text has been typed in it is corresponding edittext yeti added this to the edittextandroidimeoptionsactionsearchso that is why the keyboard has got a search button in stead of the default enterdone just in case you where wondering,['android'] +287001,delegating events to a parent view in backbone my view tunebook has several child views of type closedtune i also have separate full page views for each tune opentune the same events are bound within closedtune and opentune so i have designed my app so that they both inherit from a shared abstract view tuneto make my app more scaleable i would like the events for each closedtune to be delegated to tunebook but for maintainability i would like the same handlers the ones stored in tune to be used by tunebook although they would obviously need to be wrapped in some functionthe problem i have is within tunebook finding the correct closedtune to call the handler on whats a good way to architect this or are there other good solutions for delegating events to a parent viewnote not a duplicate of backbone view inherit and extend events from parent which is about children inheriting from a parent class whereas i am asking about children which are child nodes of the parent in the dom,['javascript'] +287003,how to get the directory of an argparse file in python i use argparse to get a file from the userimport argparse osparser argparseargumentparserparseradd argumentfile typefileargs parserparse argsthen i want to know the directory where this file is something likeprintospathabspathospathdirnameargsinputfilebut of course as argsinputfile is a file object this does not work how to do it,['python'] +287013,classnotfoundexception after upgrading to adt 18 since i updated adt to 19 i started to get following errorthe problem happens whenever i start my apps i checked all the previous post related to this but it seems none of them helps any idea would be greatly appreciatedmy setupi currently have adt 18 sdk 19 elcipse in windows 7 64biti use library project which makes asharejar and all my external jars ie dropbox commons codec are in libs folder in library project asharei do not use proguardhow we see this problem create apk in eclipse myproject right click android tools export signed application packageinstall the apk in emulator or devphone using adb install xapk start the app then boom it throw the errorsome noticeable things areit started to happen after i updated to adt in my eclipse to version 18it happens only when i make signed apk and run it in emulator or devphonei do not see problem if i run my app using myproject right click run as android applicationwhen i checked inside of classesdex i see some classes are missing there i am not sure but i feel build process is not including all classes in classesdexduring the export there is no error in eclipse console i use verbose option in androidbuildbuild output settingjava exception0507 085248336 dandroidruntime3055 shutting down vm0507 085248336 wdalvikvm3055 threadid1 thread exiting with uncaught exception group0x40a3e1f80507 085248340 eandroidruntime3055 fatal exception main0507 085248340 eandroidruntime3055 javalangruntimeexception unable to instantiate activity componentinfocomacj0barcodeexpdemocomacj0barcodeexpdemolauncher javalangclassnotfoundexception comacj0barcodeexpdemolauncher0507 085248340 eandroidruntime3055 at androidappactivitythreadperformlaunchactivityactivitythreadjava18800507 085248340 eandroidruntime3055 at androidappactivitythreadhandlelaunchactivityactivitythreadjava19810507 085248340 eandroidruntime3055 at androidappactivitythreadaccess600activitythreadjava1230507 085248340 eandroidruntime3055 at androidappactivitythreadhhandlemessageactivitythreadjava11470507 085248340 eandroidruntime3055 at androidoshandlerthispatchmessagehandlerjava990507 085248340 eandroidruntime3055 at androidoslooperlooplooperjava1370507 085248340 eandroidruntime3055 at androidappactivitythreadmainactivitythreadjava44240507 085248340 eandroidruntime3055 at javalangreflectmethodinvokenativenative method0507 085248340 eandroidruntime3055 at javalangreflectmethodinvokemethodjava5110507 085248340 eandroidruntime3055 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava7840507 085248340 eandroidruntime3055 at comandroidinternaloszygoteinitmainzygoteinitjava5510507 085248340 eandroidruntime3055 at dalviksystemnativestartmainnative method0507 085248340 eandroidruntime3055 caused by javalangclassnotfoundexception comacj0barcodeexpdemolauncher0507 085248340 eandroidruntime3055 at dalviksystembasedexclassloaderfindclassbasedexclassloaderjava610507 085248340 eandroidruntime3055 at javalangclassloaderloadclassclassloaderjava5010507 085248340 eandroidruntime3055 at javalangclassloaderloadclassclassloaderjava4610507 085248340 eandroidruntime3055 at androidappinstrumentationnewactivityinstrumentationjava10230507 085248340 eandroidruntime3055 at androidappactivitythreadperformlaunchactivityactivitythreadjava18710507 085248340 eandroidruntime3055 11 moreupdate 572012all my jars are in libs folder of library project and i see all of them included in android dependenciesupdate 5182012 temporarily solvedi found temporary solution right before running export signed application package i did clean without build automatically option checked then i do not see the error anymore i do not know why it works if you have any idea please let me know,['android'] +287015,jquery change text programatically edit the solution was to add this to the profile page instead of the gender pageprofilelive pageinitfunctioneventpptesttextlocalstoragegetitemgenderi have a paragraph with som text in a listview that i want to change programatically from another page after clikcing save edit this is my listview in profilehtml when you click on the item you get to another page where you can save your gender i want to change the paragraph in this listview to the gender that was changed from the other page ul datarolelistview lia hrefgenderhtml img srcimagesgender2jpg h3genderh3 p idptestmalep ali ulthe gender html page is just basic stuff with two radio buttons and a save button here is my javascript codein a seperate file enter code heregenderlivepageinit functionevent var gender localstoragegetitemgendervar boolmale trueif gender female boolmale falseradiochoicemaleattrcheckedboolmalecheckboxradiorefreshradiochoicefemaleattrcheckedboolmalecheckboxradiorefreshsavegenderbuttonclickfunction if radiochoicemaleischecked localstoragesetitemgender male else localstoragesetitemgender female ptesthtmltest does not work pptesttexttest does not work ptesttexttest does not work mobilechangepageprofilehtmli have tried this with javascript pptesttexttestthe text does not change however i know that the save button works is this possible,"['javascript', 'jquery']" +287047,ios import vs forward declaration regarding setalpha i am trying to do some animations on an object that i have setup via ib i am adding a forward declaration to my h like soclass myspecialclassand then setup a property like soproperty nonatomic retain iboutlet myspecialclass specialclassi want to be able to hide the specialclass using setalpha but i get the following error from xcode when trying to compilereceiver type myspecialclass for instance message is a forward declarationdo i need to import my class instead of a forward declaration i would like to not have to import anything unnecessary if i do not have to,['ios'] +287083,java limiting resource usage is there a way to limit both the number of cores that java usesand in that same vein is it possible to limit how much of that core is being used,['java'] +287084,jquery val idiom whats the clearest commonly used idiom for this jquery snippetsometextareaval sometextareaval somestring it feels clunky to wrap the original code in a oneline function edit so i can pass a function which is cool but my real intentions are for jsfiddles where i currently do stuff like thisfunction lazylog str taval taval str n orfunction lazylogplain str documentgetelementbyidtavalue str n view results of little experimentslazylog test1 lazylog test2 lazylog test3 etcdo not know if that context would produce different answers or just make me seem really lazy for wanting to type even less than that consolelog does not count i want the textarea,"['javascript', 'jquery']" +287108,access web storage from server side possible i have stored some strings in web storage session andor local and am wondering if it is possible to check for such stored strings on page load or init on the serverside aspnet c in my case so for example i will know not to refetch data from the db and use what is already resident in the browser from the last page load,"['c#', 'asp.net']" +287162,call angular js from legacy code i am using angular to build html controls that interact with a legacy flex application all callbacks from the flex app must be attached to the dom windowfor example in as3externalinterfacecallsave datawill callwindowsave functiondata want to update a service or thispatch an event herefrom within the js resize function i would like to thispatch an event that a controller can hear it seems that creating a service is the way to go can you update a service from outside of angular can a controller listen for events from a service in one experiment click for fiddle i did it seems like i can access a service but updating the services data does not get reflected in the view in the example an option should be added to the selectthanks,['javascript'] +287165,operator overloading in python with the object on the right hand side of the operator i recently learned about operator overloading in python and i would like to know if the following is possibleconsider the folowing hypotheticacontrived classclass my numobject def init self val selfval val def add self other num if isinstanceother num my num return selfval other numval else return selfval other numi know that the way that is written above i can do things like thisn1 my num1n2 my num2n3 3print n1 n2print n1 n3and those will work as expected i also know that the way it is currently written i cannot do thisn1 my num1n2 2print 2 n1is there anyway around this i know this example is contrived but i have an application in which it would ve very useful if when i did operator overloading the class for which i define the operator can appear on the right hand side of operator is this possible in python,['python'] +287166,symfony2 subdomain routing different bundles editthere is now the possibility of doing this in symfony 22platformfoobundle resource platformfoobundleresourcesconfigroutingphp domain footestdomaincomplatformbarbundle resource platformbarbundleresourcesconfigroutingphp domain bartestdomaincomplatformbazbundle resource platformbazbundleresourcesconfigroutingphp domain baztestdomaincomyou can use parameters in the domain as welledit overbefore marking this as a duplicate read oni have read this article but it doesnt help me do what im trying to doi have 3 different applications that are running on the same domain name with seperate subdomains currently theya re all running in their own symfony install and i would like to get rid of thatfootestdomaincombartestdomaincombaztestdomaincomeach of these use different bundlesplatformfoobundleplatformbarbundleplatformbazbundleand they each have their own route definitionsbasically what i want is thisplatformfoobundle resource platformfoobundleresourcesconfigroutingphp subdomain wdevwplatformbarbundle resource platformbarbundleresourcesconfigroutingphp subdomain bardevbarplatformbazbundle resource platformbazbundleresourcesconfigroutingphp subdomain bazdevbazhow do i go about doing this,['php'] +287172,php implode but wrap each element in quotes assume i have an array elements arrayfoo bar tar darthen i want to build up a delete in sql query sql delete from elements where id in implode elements the problem is that the ids in the elements array are not quoted each individually ie the query looks like sql delete from elements where id in foobartardarwhats the best most elegants way to fix this,['php'] +287183,abstractaction as windowlistener i am trying to separate function from state in my gui application by the use of action objects i have been successful in using these to create menu items and buttons that have the same functionalitymy problem is this i want to have the same action for both the exit item in my menu and the close button of the framecurrently i have been able to solve it by adding the following windowlistener to the frameprivate class mainwindowlistener extends windowadapter override public void windowclosingwindowevent e new exitactionmodelactionperformednew actioneventegetsource egetid exit is not there a simpler more straightforward way to do this,['java'] +287191,ipad how to prevent the keyboard from popping up on jquery datepicker i want to thisable the keyboard popup from my ipad so i do something like this but it is not as my wishi have a text box hinputtext idtxtdate valuemydatecontrollerselecteddobi try to use readonly attribute but data can not save to the databasei also use this frmedittxtdateattrthisabled true but it is not oki searched on the web and applied my code with this link but it is also not ok ipad web application how do i prevent the keyboard from popping up on jquery datepickerfunction frmedittxtdateattrthisabled true frmedittxtdatedatetimepicker showon button showon both buttonimage imagescalendarpng buttonimageonly true constraininput true showbuttonpanel true dateformat ddmyy addslideraccess true slideraccessargs touchonly false onclose functiondatetext inst thisattrthisabled false beforeshow functioninput inst thisattrthisabled false whats wrong with my code or any other solution to do many thanks,['jquery'] +287212,starting qtimer in a qthread i am trying to start a qtimer in a specific thread however the timer does not seem to execute and nothing is printing out is it something to do with the timer the slot or the threadmaincpp include mythreadh include iostream using namespace std int mainint argc char argv mythread t tstart while1 mythreadh ifndef mythread h define mythread h include qtimer include qthread include iostream class mythread public qthread q object public mythread public slots void doit protected void run endif mythread h mythreadcpp include mythreadh using namespace std mythreadmythread movetothreadthis void mythreadrun qtimer timer new qtimerthis timersetinterval1 timerconnecttimer signaltimeout this slotdoit timerstart void mythreaddoit cout it works,['c++'] +287218,should nlog flush all queued messages in the asynctargetwrapper when flush is called i want to shut down my application and write any pending log messages so i call logmanagerflush during my shutdown process however i do not see all the messages written out instead if i wait for a few seconds using threadsleep i see the messagesafter examining nlogs code on github i find the asynctargetwrapperflushasync method is only scheduling the lazy writer thread to write all pending messages on the next batch it is not writing log messages synchronouslyis this the expected behaviour i am expecting logmanagerflush to be synchronous ie to block until all pending messages are written or the timeout is exceededcode i use on shutdownlogmanagerflushex timespanfromseconds15and then the code to initialise nlog this is a silverlight app so i am not using any config files public static void initialisenlogloglevel forlevel var config new loggingconfiguration add targets we need an async target wrapping a custom web service call back to the server var servertarget new remoteservicetarget var asyncwrapper new asynctargetwrapperservertarget 10 asynctargetwrapperoverflowactionthiscard asyncwrappertimetosleepbetweenbatches inttimespanfromseconds2totalmilliseconds asyncwrapperbatchsize 200 add rules var rule new loggingrulecompanyapplicationsilverlightapp forlevel asyncwrapper configloggingrulesaddrule activate the configuration logmanagerconfiguration config logmanagerglobalthreshold forlevel,['c#'] +287225,open popup at clicked position hi i have done a popup which is by default hidden and opened whenever a click is triggered on window popup must be shown at wherever the event is triggeredbut there are some constraintspopup must be shown at current visible windowmeaningif i clicked at right most part of the window thenpopup must be shown to right side of the clicked position to avoid scrollingif window has scrolling irrespective of scrolling it should be shown at visible part of the windoweverything is working fine in my present code except in the caseif window has scrollingif scroll down and click on the middle of the window popup is thisplayed at out of the window current thisplay areadoctype html publichtml head script typetextjavascript srcscript script typetextjavascript srcscript style div border1px solid backgroundff9 width500px height500px thisplaynone positionabsolute style script var mousexmouseywindowwidthwindowheight var popupleftpopuptop documentreadyfunction documentmousemovefunctione mousex epagex mousey epagey to get the relative position if thisoffsetleft undefined mousex epagex thisoffsetleft if thisoffsettop undefined mousey epagey thisoffsettop ifmousex 0 mousex 0 ifmousey 0 mousey 0 windowwidth windowwidth windowheight windowheight htmlclickfunction divshow var popupwidth divouterwidth var popupheight divouterheight ifmousexpopupwidth windowwidth popupleft mousexpopupwidth else popupleft mousex ifmouseypopupheight windowheight popuptop mouseypopupheight else popuptop mousey ifpopupleft 0 popupleft 0 ifpopuptop 0 popuptop 0 divoffsettoppopuptopleftpopupleft script head body brbrbr brbrbrbr brbr br br br br br br brbr br br br brbrbr brbr br brbrbrbrbrbr brbrbrbrbrbrbrbr div s dflasld fsadf sdfas dfsadf divbodyhtmlcan you please check it,"['javascript', 'jquery', 'html']" +287236,how to exactly find where memory is leaking in project of iphone while developing apps in xcode memory leaks are occurring when i checked them in extended detail view they are showing different methods that are not related to implemented how to exactly find out which object is leaking and where it is leaking memorywhen arc is enabled we have to take care of memory leaks or not,"['iphone', 'ios']" +287239,repetitive code in unittests we find ourselves coding repetitive fixturemock setups in many testcases like this casevar fixture new fixturecustomizenew automoqcustomizationvar encodingmock fixturefreezemockiencodingwrappervar httpclientmock fixturefreezemockihttpwebclientwrappervar httpresponsemock fixturefreezemockihttpwebresponsewrappervar httpheadermock fixturefreezemockihttpheadercollectionwrappervar etag fixturecreateanonymousstringbyte data fixturecreateanonymousbytestream stream new memorystreamdataencodingmocksetupm mgetbytesitisanystringreturnsdatahttpheadermocksetupgetm mitisanystringreturnsetagverifiablehttpclientmocksetupm mgetresponsereturnshttpresponsemockobjecthttpresponsemocksetupm mstatuscodereturnshttpstatuscodeokhttpresponsemocksetupgetm mheadersreturnshttpheadermockobjecthttpresponsemocksetupm mgetresponsestreamreturnsstreamas per the idea that the tests should be selfcontained and readable from start to end we dont use magical setupteardown methods can we in any way autofixture customizations helper methods reduce the grunt work of these tests,['c#'] +287273,when does a body onload gets called i need to understand when does a bodys onload gets calledi read in w3school that onloadscript to be run when a document load what does this meandoes it mean that the htmljsp page gets loaded before rendering any elements in the body like any table or jsp scriplets eg requestgetparametername or is it after the pagebody is renderedfor examplei have a bunch of params requestgetparametername so in order to use them i will place them in some hidden form item then on body load can i use them,['html'] +287296,how write stub method with nunit in c i have 2 classesfirstdeepcsseconddeepcsi did simple code for exampleclass firstdeep public firstdeep public string addastring str seconddeep sd new seconddeep bool flag sdsomethingtodostr if flag true str stringconcatstr a else str stringconcatstr b return str andclass seconddeep public bool somethingtodostring str bool flag false if strlength 10 todo something in db and after that flag should be true return flag then i want to write unit test for method addaclass tests test public void addatest string expected abca firstdeep fd new firstdeep string res fdaddaabc assertareequalexpected res and after that i have trouble i do not know how correct write stub for method somethingtodo in my test class i always have false i should just return true but how,['c#'] +287327,android internal storage vs external storage when app installed on sd card i have an app which downloads large amounts of content it varies between users but could be 200mb to 1gb or morecurrently i save all of this content on external storage as this is likely to be the area with the most space such as an sd card this works fine for the most part however there is a situation where this is not necessarily idealif the device has in built external storage like most tablets but also has an sd card slot the external storage issue gets a little complicated the app can be installed onto the sd card but the content will be saved on the built in storage not the external sd cardif the app is install on an sd card will calling getfilesdir give a path on the sd card or the internal storageand what is the best way of handling this should i save content to the internal storage on an sd card the external storage or is asking the user when starting the app the best idea,['android'] +287369,gson array of strings to jsonarray i am using gson and am trying to add a bunch of string values into a jsonarray like thisjsonarray jarray new jsonarrayjarrayaddvalue1the problem is that the add method only takes a jsonelementi have tried to cast a string into a jsonelement but that did not workhow do i do it using gson,['java'] +287379,big database backup best practice i maintain big mysql database i need to backup it every nightbut the db is active all the time there are queries from usersnow i just thisable the website and then do backup but this is very bad as the service is thisabled and users do not like thiswhat is good way to backup the data if data are changed during the backupwhat is best practice on this,['mysql'] +287386,how to install multiple ruby gems at once is is possible to install more than one gem at the same time with only one command,['ruby'] +287399,is it possible to deploy ssis 2012 package on sql server 2008 i have a package that is developed in ssis 2012 using visual studio 2010 is it possible to deployattach this package on sql server 2008 if it is possible does the licence of the sql server matter,['sql'] +287400,what are weak global references how it is different from a global reference what are weak global references in jni how it is different from a global reference and a local reference,"['java', 'c']" +287420,how to perform full outer join in oracle using operator instead of using keywords like full outer join or full join how can i perform full outer join using where clause with the help of operator,['sql'] +287476,linux getenv could not get ps1 or ps2 my home world is to write a shell and i must use ps2but when i write a code like thischar env ps2env ps2 getenvps2i just found env ps2 was point to nullhow could i get the ps2 in my program,['c'] +287556,is there a way to run a jsf page without building the whole project is there a way to just run the one page so that i can see the generated html and css as it would look to the user even if it is essentially nonfunctional standalone jsf page as it were i want to review how i am setting up forms to see if they make sense form a user standpoint before actually coding for the forms fields i am using maven and netbeans but not sure if the latter is relevant,['java'] +287595,does master page get called first i would assume this is true but wanted to throw this question up is the master page executed first in aspnet or does the page which is getting retrieved i am asking because i want some processing to be done in the master page results of which are loaded into a static object and which can then be used by the called page for instance user data,"['c#', 'asp.net', '.net']" +287639,what is el in relationship to javascripthtmljquery i could not find much from googling but i am probably googling the wrong termsi am trying to understand what the el in el is from hereeltable eltr elthfirst name elthlast name eltr eltdjoe eltdstelmachappendtodocumentbodythanks in advance,"['javascript', 'jquery', 'html']" +287643,insert line at middle of file with python is there a way to do this say i have a file that is a list of names that goes like thisalfredbilldonaldhow could i insert the third name charlie at line x in this case 3 and automatically send all others down one line i have seen other questions like this but they did not get helpful answers can it be done preferably with either a method or a loop,['python'] +287656,libpng 1510 error dereferencing pointer to incomplete type png read info png ptr info ptr png byte color type info ptrcolor type png byte bit depth info ptrbit depth for last 2 lines i geterror dereferencing pointer to incomplete typewhats wrong in libpng 14 this was always ok,['c'] +287659,mac os x daemon using objectivec launchd i am new in mac os x world but i have skills on windows devi need to develop a daemon on windows will be windows service that uploadsdownloads files from a web servicemy question is is it possible to create an app written in objectivec that will be the daemon to uploaddownload and to launch it when the os starts using launchd or there is another way to create a daemonthank you,['objective-c'] +287695,some questions around the use of concurrentdictionary i am currently writing a c application i am new to using a concurrentdictionary so have some questions around its thread safety firstly this is my dictionary summary a dictionary of all the tasks scheduled summary private concurrentdictionarystring itask tasksi instantiate this in my class and use it to track all of my objects that implement itask i want ensure my setup will work correctly in a multi threaded environment if multiple threads want to get the count of the number of items in the concurrentdictionary do i need to lock itif i want to get a particular key from the dictionary get the object of that key and call a method on it do i need to lock it eg summary runs a specific task summary param namenametask nameparam public void runstring name lock thissyncobject var task thistasksname as itask if task null taskexecute keeping mind multiple threads could call the run method looking to call the execute method of itask my aim is to have everything thread safe and as performant as possible,"['c#', 'asp.net']" +287719,difference between pymodinit func and pymodule create if i am understanding correctly a pymodinit func in python 2x has been replaced by pymodule create in python3xb both return pyobject however in python 3x the modules initialization function must return the pyobject to the module iepymodinit funcpyinit spamvoid return pymodule createspammodulewhereas in python2x this is not necessary ie pymodinit func initspamvoid void py initmodulespam spammethods so my sanity checking questions are1 is my understanding correct2 why was this change made right now i am only experimenting with very simple cases of cextensions of python perhaps if i were doing more the answer to this would be obvious or maybe if i were trying to embed python into something else,['python'] +287728,getting getrusage to measure system time in c i would like to measure the system time it takes to execute some code to do this i know i would sandwich said code between two calls to getrusage but i get some unexpected resultsinclude systimehinclude sysresourcehinclude unistdhinclude stdiohint main struct rusage usage struct timeval start end int i j k 0 getrusagerusage self usage start usageru stime for i 0 i 10 i double loop for more interesting results for j 0 j 10 j k 20 getrusagerusage self usage end usageru stime printfstarted at ldldsn starttv sec starttv usec printfended at ldldsn endtv sec endtv usec return 0i would hope that this produces two different numbers but alas after seeing my computer think for a second or two this is the resultstarted at 019sended at 019sam i not using getrusage right why should not these two numbers be different if i am fundamentally wrong is there another way to use getrusage to measure the system time of some source code thank you for reading,['c'] +287736,backbonemarionette vs backboneboilerplate i am new to backbone and trying to decide how to approach development at the moment i am wondering when people would use backbonemarionette over backboneboilerplate from what i can tell marionette is a lot more prescriptive but is this the way that most people approach development here,['javascript'] +287744,java thread pool executor monitoring the threadpoolexecutor class in the java se 6 docs has the following methodpublic int getactivecountreturns the approximate number of threads that are actively executing taskswhat is the meaning of approximate and actively executing here is there any guarantee that if before during and after the call to getactivecountn threads have been allotted from the pool for task execution andnone of these n threads are available for further task assignmentthe integer returned by getactivecount will be exactly nif getactivecount does not provide this guarantee is there any other way to obtain this information in a more precise mannerprior so questionsi have looked at thread pool executor monitoring requirement and how to tell if there is an available thread in a thread pool in java but they do not answer my queries,['java'] +287746,when stepping into class instantiation eclipse debugger goes to native code i recently upgraded to helios and now every time i step into a constructor for a class eg cat mycat new cat eclipse debugger shows the stack as to get to the actual constructor code i have to step out several times which is annoying this is happening with every class and despite the stack i never see any error messages in the console how do i fix this so it directly steps into the constructor for my classthis only happens the first time the class is used and even for classes that are in the same src file as the current one,['java'] +287755,how can i transform this backusanaur form expression into a regex net the expression isn 1 a b c d e1 e2 e3 meaning the descriptor n or one or more of the listed descriptors without repetitionthe best i have got isnabcde1e2e31but that does not prevent repetition na01b01 that prevents repetition but then requires a specific order to the elements which is not really ok eitherany ideasi am not actually sure that the bnf expression itself thisallows repetition but that is what i need,['.net'] +287759,do i really need use asqueryable on collection example codeliststudent students new liststudent new student101 hugo garcia new listint 91 88 76 93 new student102 rick adams new listint 70 73 66 90 new student103 michael tucker new listint 73 80 75 88 new student104 fadi fakhouri new listint 82 75 66 84 new student105 peter barrows new listint 67 78 70 82 var query from student in students where studentmarksasqueryableallm m 70 select studentforeach student student in query consolewriteline0 1br studentfirstname studentlastnamebut if i change the query tovar query from student in students where studentmarksallm m 70 select studentthis also works and produces the same result so whats the difference,"['c#', '.net']" +287766,sse2 integer overflow checking when using sse2 instructions such as pad ie the mm add epi32 intrinsic is there a way to check whether any of the operations overflowedi thought that maybe a flag on the mxcsr control register may get set after an overflow but i do not see that happening for example mm getcsr prints the same value in both cases below 8064include iostreaminclude emmintrinhusing namespace stdvoid main m128i a mm set epi321 0 0 0 m128i b mm add epi32a a cout mxcsr mm getcsr endl cout result bm128i i323 endl m128i c mm set epi321311 3 2 1 m128i d mm add epi32c c cout mxcsr mm getcsr endl cout result dm128i i323 endlis there some other way to check for overflow with sse2,['c++'] +287774,java 0 2 0 false the part i keep getting stuck on is boolean0 2 0 false i mean if 2 goes into 0 0 times then the remainder would be 2 and 2 does not equal 0 so it should be true yet but when i put the boolean in my java program it is treating it as false anyone know whythe only logical answer i can wrap my head around is that maybe integers go into 0 and infinite number of times and so are recognized as false anyone,['java'] +287821,c are define directives global i am somewhat confused by define statements in libraries they seem to be a means of communication across different files with lots of ifdefs and ifndefshaving said that i now have two files file1c and file2c compiled together with define test 10 inside file2c yet when i use test inside file2c the compiler gives the following error messagetest undeclared first use in this functionare define directives global,['c'] +287838,how to use yii namespace i am having i confusion in understanding the namespace from the yii documentation as their are not enough example to understand as i am new to yii framework please give some easy and detailed examples so that i can understand it is purpose,['php'] +287842,polyline snap to road using google maps api v3 in google maps api v2 it was easy var map new gmap2documentgetelementbyidmap mapsetcenternew glatlng537877 2983213 mapaddcontrolnew glargemapcontrol mapaddcontrolnew gmaptypecontrol var dirn new gdirections var firstpoint true var gmarkers var gpolys var thist 0 when the user clicks on a the map get directiobns from that point to itself gmarkerspushnew googlemapslatlng537877 29832gmarkerspushnew googlemapslatlng539007 29832gmarkerspushnew glatlng53600 2700for var i 0 i gmarkerslength1 i consoleloggmarkersi dirnloadfromwaypointsgmarkersitourlvalue6gmarkersi1tourlvalue6getpolylinetrue when the load event completes plot the point on the street geventaddlistenerdirnload function snap to last vertex in the polyline var and dirngetpolylinegetvertexcount mapaddoverlaydirngetpolyline gpolyspushdirngetpolyline thist dirngetpolylinegetthistance documentgetelementbyidthistanceinnerhtmlpath length thist10tofixed2 km thist1609344tofixed2 miles geventaddlistenerdirnerror function glogwritefailed dirngetstatuscode consolelogdirnin google api v3 this way simple doesnt work there is something like directions service but i dont have any idea how i can draw polyline through my points and polyline will be snaped to road,['javascript'] +287846,were sorry but something went wrong with rails apache passenger i have rails 323 with apache and passengeri have a project working in development modewhen i switch the project to production mode passenger standardit gives me an http error 500were sorry but something went wrongthis happens even with webrickcan somebody help meeditmy production environment file,['ruby-on-rails'] +287874,how to get platformspecific path separator in c how can i get the platformspecific path separator not directory separator in c ie the separator that is needed to combine multiple paths in a list eg path environment variableunder linux this would be under windows in other words i am looking for the cequivalent of pythons ospathsep javas pathseparator or phps path separator if boost provides such a function that would be fine as we are using it in our projects anyway if not i guess any other solution would be goodall i could find here and elsewhere were either just ways to retrieve the directory separator ie vs or related to other languages than c,['c++'] +287883,formdata is not defined firefox 3628 alternative i have the great job of having to finish off a job originally given to a contractor but was never completed not a problem however i have now been told that the system must support firefox 36 not great but not something i would lose sleep over until now the system has a ajax function that uses the formdata object and then uploads a document usually a pdf i have ran this through firefox 36 and i get the followingformdata is not defined var formdata new formdataform0that is fine as i can see that this object is not supported i just need to use a different method or means of collection i used thisvar formdata componentsclassesmozillaorgfilesformdata1 createinstancecomponentsinterfacesnsidomformdatahowever this gave me the following errorpermission denied for to get property xpccomponentsclassesi was unsure why this was is the path mozillaorgfilesformdata1 incorrect i did more research and was getting nowhere so i then thought about serializing the form changed the following tovar formdata eachform0serializearray function kv if formdatahasownpropertykvname formdatakvname makearrayformdatakvname formdatakvnamepushkvvalue else formdatakvname kvvalue although this didnt error the ajax function was not uploading i presume it was not recognizing or finding the file or it was just collecting a string for the file value does anyone have any recommendations on an alternative for formdata in older browsers especially firefox 36 that is the only old browser i have to support update this is the content of the form on the html pageform action methodpost enctypemultipartformdata nameuploadform iduploadform target label forfilefieldrechnung hochladenlabel input typefile namefilefield idfilefield progress idprogressbar classprogressbar margin hiddenprogressform,"['javascript', 'jquery']" +287892,table row background image possible duplicatecan we solve the table row background image problem in chrome in multi celled tables i am trying to have one image as the background for the first row the problem is that the background gets applied to each cell separately not as a whole is there a way around itresult should look something like thisedit the problem appears only in safari opera and chrome did not check ie yet,"['html', 'css']" +287922,why return an enumerator im curious about why ruby returns an enumerator instead of an array for something that seems like array is an obvious choice for examplefooclass stringmost people think of a string as an array of charsfoocharsclass enumeratorso why does stringchars return an enumerable instead of an array i am assuming somebody put a lot of thought into this and decided that enumerator is more appropriate but i do not understand why,['ruby'] +287944,ideas for rendering html within raphael svgvml shapes i am working on an application that uses raphael to draw primitive shapes rectangles ellipses triangles etc and lines but allows the user to moveresize these objects as well one of the main requirements is that the face of shapes can have formatted text the actual text is a subset of markdown simple things like bolding italics lists and is rendered as html fwiw i am using backbonejs views to modularize the shape logicapproach 1my initial thought was to use a combination of foreignobject for svg and direct html with vml for ie however ie9 does not support foreignobject and therefore this approach had to be abandonedapproach 2with the beside the canvas object add divs that contain the actual html then position them over the actual shape with a transparent background i have created a shape view that has references to both the actual raphael shape and the overlay div there are a couple of problems with this approachusing overlay that are not children of the svgvml container feels wrong does having this overlay element cause other issues with rendering down the roadevents that are normally trapped by raphael drag click etc need to be forwarded from the overlay to the raphael object for browsers that support pointerevents this is easily donedivshapetextoverlay position absolute background none pointerevents nonehowever other browsers like ie8 and below need forwarding of the eventsvar forwardedevents mousemove mousedown mouseup click dblclick mouseover mouseoutthiseltextonforwardedevents functione var original eoriginalevent var event if documentcreateevent event documentcreateeventhtmlevents eventiniteventetype true true else event documentcreateeventobject eventeventtype etype fyi this is the most simplistic approach to event forwarding my real implementation is much larger and uses mouseevents and uievents separately eventeventname etype extendevent original if documentcreateevent thatelnodethispatcheventevent else thatelnodefireeventon eventeventtype event overlapping shapes cause the text to be overlapped because the textshapes are on different layers although overlapping shapes would not be common this looks badthis approach is what i am currently using but it just feels like a huge hackapproach 3almost like approach 1 but this would involve writing text nodesvml nodes directly the biggest problem with this is the amount of manual conversion necessary breaking outside of raphaels api seems like it could cause stability issues with the other raphael objects questionhas anyone else had to do something similar rendering html inside of svgvml if so how did you solve this problem were events taken into account,['javascript'] +287945,scala parsingg rssatom feeds does anyone know a good libraryjar to parse rssatom feeds i would like to stuff an url in and want to get the newsitems in a homogenus way means it should not matter whether the source contains an atom or rss feed i just want items back after browsing on so i came up with rome but it seems to be chaotic at the moment no download for example and is a pure java solution scala would be preferred but java is quite okay if nothing scalaspecific exists also it should be a single jar library since i do not use maven etc ps it is not for android just for a good old desktop appedit to be more clear i already know how to get the content from resources as xml i want to parse them autodetect whether it is atom or some rss and give me back an uniform list of items,['java'] +287965,how to import local image using knitr for markdown i have an externally created png image in a local directory that i would like to import to a report using knitr the ultimate target filetype is html i have no trouble getting my own figures to appear when i create them with r code but i am at a loss what i would have thought was a simpler problemwhile i am at it how would i import a figure for which i have a url,['html'] +288005,covariance of the systemnullable struct when we have two structs and one is implicitly convertible to the other then it seems like the systemnullable versions of the two are also implicitly convertible like if struct a has an implicit conversion to struct b then a converts to b as wellhere is an examplestruct mynumber public readonly int inner public mynumberint i inner i public static implicit operator intmynumber n return ninner inside some methodmynumber nmn new mynumber42int covariantmagic nmn worksin the c language specification version 40 we read that a conversion like this shall exist for the predefined implicit identity and numeric conversionsbut is it safe to assume that it will also work for userdefined implicit conversionsthis question might be related to this bug,['c#'] +288022,how to set content size of uiscrollview dynamically i got question about uiscrollviewthe story is i have a uiview named chartsview which i redraw it myself by override method drawrect the content of drawing was generated dynamically so i do not know its size until runtime the question is howwhere can i set its super views scrollview content size dynamicallyany idea about that voidviewdidload super viewdidload not this way it is fixed size chartsview chartsview chartsview allocinitwithframecgrectmake0 0 320 800 selfscrollviewcontentsize chartsviewframesize selfscrollview addsubviewchartsview,"['iphone', 'objective-c']" +288037,how can cs stringindexof perform so fast 10 times faster than ordinary for loop find i have a very long string 60mb in size in which i need to find how many pairs of and are in therei have first tried my own way char pre int match1 0 for int j 0 j htmllength j char c htmlj if pre c find a match pre match1 else if pre c pre the above code runs on my string for roughly 10 msthen i tried using stringindexof int match2 0 int index 1 do index htmlindexof index 1 if index 1 find a match index htmlindexof index 1 if index 1 match2 while index 1the above code runs for only around 150 ms i am wondering what is the magic that makes stringindexof runs so fastanyone can inspire meeditok according to brokenglas answer i modified my code in the way that they do not check the pairing instead they check how many in the string for int j 0 j htmllength j char c htmlj if c match1 the above code runs for around 760 msusing indexof int index 1 do index htmlindexof index 1 if index 1 match2 while index 1the above code runs for about 132 ms still very very fast edit 2after read jeffrey sax comment i realised that i was running in vs with debug modethen i built and ran in release mode ok indexof is still faster but not that faster any morehere is the resultsfor the pairing count 207ms vs 144msfor the normal one char count 141ms vs 1msmy own codes performance was really improved lesson learned when you do the benchmark stuff do it in release mode,['c#'] +288060,jquery mobile delegate vs live vs bind i cannot seem to wrap my head around the differences between the following in jquery mobile document livepageshow functionevent document bindpageshow functionevent document delegatepage pageshow function how do i execute scripts in the head of my documents that are different in certain pages which methods do i use to call those scriptsupdatejquery version 171jquery mobile version 110,['jquery'] +288076,stop script execution upon noticewarning is it possible to have php stop execution upon a noticewarning globallyeg for all sites on the serverwe run a development server with a lot of sites on but want to force our developers to fix these warningsnotices or ask for help with them at least instead of ignoring and moving on,['php'] +288149,pdo were rows affected during execute statement i have found many ways to use the exec statement for pdo but i am not sure it helps me my understanding is that i have to use the execute function for prepared statements i am updating a row with data from user input so i would like to use a prepared statement instead of the query callmy code is as followsdbh builddbconnector sql update tb users set authstate1 where id and authpass q dbhpreparesqlf qexecutearrayidauthpassiff echo br successbr else echo br failurebr the issue is that the query itself is error free and executes fine so there is no failure to store in f however i need to know if it actually found the row to update then successfully updated it in other words i need the affected rows when googling and such it keeps coming to the exec statement but from my understanding exec is not for prepared statements any suggestions,"['php', 'mysql']" +288158,how to export sqlite to csv in python without being formatted as a list here is what i currently haveconn sqlite3connectdbfileconntext factory str my current failed attempt to resolve thiscur conncursordata curexecuteselect from mytablef openoutputcsv wprint f column1 column2 column3 etcfor row in data print f rowfcloseit creates a csv file with output that looks like thiscolumn1 column2 column3 etc1 u20110505 23422929877668414480522344635647681130996322 none u20110506 041i do not want the rows to be in parentheses nor have quotes nor the u before strings how do i get it to write the rows to csv without all of this thanks,['python'] +288163,can i get an unbound function from a bound function in javascript i am getting my head wrapped about currying and other techniques using functionprototypebindit seems extremely useful to change function scope ie this value in certain situationshowever it looks like you cannot change the scope with bind once you already did sofunction f objmethodbind42 function g objmethodbindhifunction f2 fbindhi athisa is still 42is it possible to retrieve the original unbound function from a bound function at all,['javascript'] +288171,boosterase all to erase multiple chars from a string if i want to remove all ones from a string using boosterase all i can do thisboosterase all a1b1c1 1 now my string is abc however if i want to remove all digits 0 9 from a string using boosterase all i have to call it once for each digit i wish to removeboosterase all a1b2c3 1 boosterase all a1b2c3 2 boosterase all a1b2c3 3 i thought i could use boostis any of to remove them all at once as that works with other boost string algorithms such as boostsplit but is any of does not seem to work with erase allboosterase all a1b2c3 boostis any of 123 compile errorboostalgorithmstringerasehpp59313 error no matching function for call to afirst finderconst boostalgorithmdetailis any offcharaperhaps i have overlooked something obvious here or there is another function within boost that is meant to do this i can do it manually with standard c but just curious how others might be using boost to do thisthanks for any advice,['c++'] +288245,what is the purpose of fnfooconstructor foo in twitter bootstrap js all of the jquery plugins for twitter bootstrap follow the same basic pattern of defining a class that controls the behavior of the plugin near the end they do thisfnalertconstructor alertwhat is this doingi assume that this is defining a prototype constructor but they use an uppercase c does case not matter here beyond that i do not really understand what this is doing and how it is getting used by the pluginas an example here is the alert plugin,"['javascript', 'jquery']" +288255,get current directory of symlinkd php script and not actual php script i have a script that is symlinked from one folder to anothervarwdefaultindexphpwhich is symlinked tovarwmysiteindexphphowever when i call dir from mysite the path resolves to the origial path under default how do i make it return the mysite path the symlinked folder not the actual folder,['php'] +288265,difference between orm and pdo i have a little confusion regarding difference between orm and pdois pdo a kind of ormorm as per my understanding is basically a kind of data mapping and pdo also provides an abstraction for the database data,['php'] +288267,android opengl es 20 text rendering there seems to be a thistinct lack of support on the web for how to thisplay text in opengl es 20 jvitelas answer at draw text in opengl es android says to use a canvas and paint the text on that to generate a bitmap and then use glutils to render the text bitmap but the answer only shows the part directly about painting the text not what else goes around iti have also been trying to go off the lessons at in this case lesson 4 which deals with basic textureshow is jvitelas method passed to a vertex or fragment shader is the section about the background necessary or will leaving the background out result in just the text over the rest of the gl surface what exactly is the textures variable he used i think it is a texture data handle comparing his bind to at that of learnopengles but why an array is it shared with other texturesi have a programme with a heap of stuff thisplayed on it already with opengl es 20 and need some basic text some static some updating every 1 to 5 hz printed over it my understanding is that texture mapping bitmap glyphs is quite expensiveare there any good tutorials to do what i need any advice from anyone,['android'] +288292,symbolic differentiation using expression templates in c how to implement symbolic differentiation using expression templates in c,['c++'] +288408,how to decide whether the default ekcalendar calendar can be hidden i am writing an app that deals with calendars in the app i am thisplaying a list of all available calendars for the user to enable or thisable i am not using the eventkitui framework for purposes of my own design and uii get a neat list of calendars by polling the calendars property of an ekeventstore object on my device however there is an ekcalendar object in that list that is not shown by the ekeventkitui this is a description of the object in the debuggerekcalendar 0xcea6b60 title agenda type local allowsmodify yes color 711a76i am running my iphone in dutch which is why the title is agenda and not calendar but if you run the iphone in english that is what youll see it looks like this is ios default calendar but since i have all my calendars set up to sync with icloud it is thisabled for the built in calendar apps i want to thisable it in my own app too but i do not know howfrom looking at the properties of ekcalendar i cannot thiscern one for deciding which calendar i should hide there is the type property that is local for this default calendar but if someone is not using icloud i imagine all the calendars are of a local type subscription is not it either nor is allowscontentmodifications i have seen examples of people hiding the default calendar based on it is title but as you can see the title is localized and thus very impractical that just feels wrongwhats the trick to decide which calendar is the default calendar and whether to hide it or not in order to parallel the list of calendars that your regular icalcalendar app thisplaysedit although the question was marked as answered the answer contains a big no you cannot i have solved this issue for my users by adding a settings panel switch to hide local calendars but it is a very very unelegant solution,['objective-c'] +288428,const references in stdvector elements is it only my compiler or is it forbidden to use cons references in stdvector elements consider following structurestruct y const int x yconst int p x xp x now when i try to push such object onto vectorstdvectory yvint x 5y yxyvpush backyi get compiler error error nonstatic reference member const intyx cannot use default assignment operator should not copy ctor be enough,['c++'] +288429,redirect stdout to logcat in android ndk i cannot get my nexus s running android 40 to redirect native stdout message to logcat i have read that i need to do this adb shell stop adb shell setprop logredirectstdio true adb shell starthowever this does not seem to work it does break junit though as mentioned here so it is not without effectfor reference heres my codepackage commayastudiosimport androidutillogpublic class jnitester public static void test loge start of test systemerrprintlnthis message comes from java void printcmessage loge end of test private static native int printcmessage static systemloadlibraryjni test and the jni c filejniexport void jnicalljava com mayastudios jnitester printcmessagejnienv env jclass cls setvbufstdout null ionbf 0 printfthis message comes from c jnin fflushstdout setvbufstderr null ionbf 0 fprintfstderr this message comes from c jnin fflushstderrand the androidmklocal path call mydirinclude clear varslocal module jni testlocal src files test jnicinclude build shared libraryi am compiling this just by calling ndkbuild the native method is called correctly but i do not get any log output from it even on verbose i do get the log output from java though this message comes from javaany hints of what i might be doing wrongps i have set up a small mercurial repository that demonstrates the problem,['android'] +288449,javafx application in maven project i have a project with structure like thismainprojectlibary1library2ineedjavafxapphereso i need a javafx 2 application in my maven project and it should use library1 and library2 with its dependencies i cannot find any maven archetypes for javafx 2 projects and i cand find any adequate information about how i can build javafx app by maven 3 i do not need any deployment to web it will only desktop appso can anybody help with this problemupdjavalangnoclassdeffounderror javafxapplicationapplication caused by javalangclassnotfoundexception javafxapplicationapplicationexception is occured when i try to run application which is builded by pgras way,['java'] +288452,how to stopinterrupt a boostthread i create a thread in a functionand in another functioni wanna stop this threadi have tried like thisclass serverprivate boostthread mptrthreadpublic void createnewthread boostthread t mptrthread t void stopthread mptrthreadinterrupt but it is not workhow could i stop the thread,['c++'] +288455,twitter bootstrap using block level labels and inputs i am using twitter bootstrap for railssass and have notice that it applies a thisplay block style to my labelslabel inputs and label textareasi am using form tags to generate a check box with a label but the block style move the two onto different line fcheck box remember me flabel remember me my question is two fold should i be doing it this way and if so how best should i override twitter bootstraps defaults i would rather not have lots of important flags in my css if i can avoid it,"['ruby-on-rails', 'css']" +288488,where is apk location for apps that are installed on sdcard i know that the location for system apps is systemapp and the location for user apps is dataappbut i cannot find the location of apk for the ones that i moved toinstalled on sdcard,['android'] +288498,data in onactivityresult is null i am trying do a simple application for android i have two activities a and b in b i only want select a datei start a and do intent intent new intent intentsetclassthis bclass startactivityforresultintent1then in b i do intent intent getintent setresultresult ok intentputextradatedateselected finishand in a i have the next methodoverride protected void onactivityresultint requestcode int resultcode intent data superonactivityresultrequestcode resultcode data ifresultcoderesult ok requestcode1 bundle bundle getintentgetextras string aux bundlegetstringnuevo but data and bundle are null when i debug the code i see that in class b intent has the extras but then when i call finish and return to class a this intent is not reachablehow can i solve this problem,['android'] +288533,c11 passing this as paramenter for stdmake shared i am trying to pass this to the constructor using stdmake sharedexample headersclass a public stdshared ptrb createbclass b private stdshared ptra apublic bstdshared ptra sourcestdshared ptrb acreateb auto b stdmake sharedbthis compiler error vs11 beta auto b stdmake sharedbstdshared ptrathis no compiler error but doenst work return bhowever this does not work properly any suggestions how i can properly pass this as an argument,['c++'] +288567,wpf datagrid binding and column thisplay i have datatable as item source for datagrid this datatable has lots of columns is it possible to thisplay few columns instead all of them without creating a new table,['c#'] +288597,forcing nvidia gpu programmatically in optimus laptops i am programming a directx game and when i run it on an optimus laptop the intel gpu is used resulting in horrible performance if i force the nvidia gpu using the context menu or by renaming my executable to bf3exe or some other famous game executable name performance is as expectedobviously neither is an acceptable solution for when i have to rethistribute my game so is there a way to programmatically force the laptop to use the nvidia gpui have already tried using directx to enumerate adapters idirect3d9getadaptercount idirect3d9getadapteridentifier and it does not work only 1 gpu is being reported the one in use,['c++'] +288598,add css class to htmlactionlink i want to style a link in my page and am using htmlactionlink to create the link the problem is i do not know how to style the resulting link how do i add a css class to the htmlactionlink in order to style it,['css'] +288602,equalizer not always supported even when api 9 before enabling equalizer capabilities i check for api level to make sure it is equal or greater than 9from the reports i am getting from my users it seems that some exceptions are thrown anyway the code eq new equalizer0 mpgetaudiosessionid can raise caused by javalangunsupportedoperationexception effect library not loadedat androidmediaaudiofxaudioeffectinitaudioeffectjava355at androidmediaaudiofxequalizerinitequalizerjava149and the code eqgetbandlevelrange can raise caused by javalangunsupportedoperationexception audioeffect invalid parameter operationat androidmediaaudiofxaudioeffectcheckstatusaudioeffectjava1182at androidmediaaudiofxequalizergetbandlevelrangeequalizerjava206i do not know if there is a solution and if not i could just catch those exceptions and thisable equalizer but i need to know whats exactly causing this so i can inform my users without frustrating themthanks for any help,['android'] +288643,how do you install jogl on windows 7 64bit for use with eclipse i have tried to follow any number of tutorialsbut i still cannot get eclipse to recognise any of my import statementsimport netjavagamesjoglanimatorimport netjavagamesjoglglimport netjavagamesjoglglcanvasimport netjavagamesjoglglcapabilitiesimport netjavagamesjoglgldrawableimport netjavagamesjoglgldrawablefactoryimport netjavagamesjoglgleventlistenerhaving said that there always seems to be something different with the tutorials and what i am able to do ie different files different packages different steps etcthis tutorial installs jogl as a user library which i like but references files nativewindowalljar newtalljar that i could not find in the jogl download i found it also talks about referencing dll files which the download helptxt and wiki state are deprecated and should not be used having said that i followed the instructions as best i could using files mentioned in wiki but it still does not work the official wiki talks about downloading different packages for different systems but they all seemed to be bundled into one jogampallplatforms7z file now it says the files you need are gluegenrtjar joglalljar gluegenjavasrczip jogljavasrczip gluegenrtnativeswindowsamd64jar joglallnativeswindowsamd64jar but it does not say what you are supposed to do with them i have referenced them in my build path but it has not workedanyway i am probably doing something very stupid but am not sure whatcan someone give step by step newbieproof instructions on how to add jogl to my eclipse projecteditheres an image of my project properties window,['java'] +288663,why extends precedes implements in class declaration why implements must always be written after extends in class declaration for example public class register extends actionsupport implements modeldrivenwhy notpublic class register implements modeldriven extends actionsupport is a compile time error,['java'] +288679,is it possible to thisable font smoothing in css i want some small fonts to look with no smoothing is it possible to thisable font smoothing using htmlcss,"['html', 'css']" +288694,crash in c code due to undefined behaviour or compiler bug i am experiencing strange crashes and i wonder whether it is a bug in my code or the compilerwhen i compile the following c code with microsoft visual studio 2010 as an optimized release build it crashes in the marked linestruct tup int x int y class c public struct tup p struct tup operator return p struct tup operatorint return p virtual void reset p 0int main c c volatile int x 0 struct tup v1 struct tup v2 0 x cp v1 c v2 struct tup i c crash dereferencing a nullpointer return ixlooking into the thisassembly it is obvious that it must crashint tmainint argc tchar argv00ce10 push ebp 00ce1001 mov ebpesp 00ce1003 sub esp0ch c c volatile int x 0ce1006 xor eaxeax 00ce1008 mov dword ptr xeax struct tup v1 struct tup v2 0 x00ce100b mov ecxdword ptr x cp v1 c v200ce100e mov dword ptr ebp8ecx struct tup i c00ce1011 mov ecxdword ptr x 00ce1014 mov dword ptr v1eax 00ce1017 mov eaxdword ptr ecx 00ce1019 mov ecxdword ptr ecx4 00ce101c mov dword ptr ebp8ecx return ix00ce101f mov espebp 00ce1021 pop ebp 00ce1022 ret at offset 00ce1008 it writes a 0 into xat offset 00ce100b it reads x the 0 into ecxat offset 00ce1017 it dereferences that 0pointeri see two possible reasonseither there is some subtle or not so subtle case of undefined behaviour in my codeand the compiler optimizes this undefined behaviour into a crashor there is a compiler bugdoes anyone see what might cause the problemthank youjonasedit to address the comments regarding pointer to invalid locationif i change v1 to be struct tup v110 and set cp v10 then there will be no pointer to an invalid location but i can still observe the same behaviour the thisassembly looks marginally different but there is still a crash and it is still caused by loading 0 into ecx and dereferencing itedit conclusionso probably it is a bug i found out that the crash vanishes if i changestruct tup operator return p tostruct tup operator p return p as bames53 tells us the crash does not occur in vs2011 and concludes that it must have been fixednontheless i decided to file that bug for two reasonsthe bug might still be present in vs2011 maybe the optimizer just has changed in a way that my code does not trigger the bug anymore the bug seems to be very subtle it does not occur when i remove the volative or the virtual void reseti want to know if my workaround is a reliable way to rule out the crashes or if code changes in other places can reintroduce the bughere is the link,['c++'] +288700,abandoned mutex exception i am trying to use a mutex for the first time and have the following code executing on two separate instances of the programpublic void asynchronouscode using var mutex new mutexfalse myspecialmutex if mutexwaitone10 false consolewritelinefirst check some one locked the mutex if mutexwaitone30 false consolewritelinesecond check some one locked the mutex else consolewritelinei got the mutex consolewritelinesleeping threadsleep30 consolewritelineawaking and releasing mutex mutexreleasemutex when i run this one of the instances the one i run first printsi got the mutexsleepingawaking and releasing mutexthe other instance prints first check some one locked the mutexand as soon as the first instance leases the mutex it crashes at the second wait statement with the exception the wait completed due to an abandoned mutexany ideas on why i am getting this exception and how i can prevent it solution i probably should have read the mdsn documentation more clearly thanks andrew for pointing me in the right directionyou can use the waithandlewaitone method to request ownership of a mutex the thread that owns a mutex can request the same mutex in repeated calls to waitone without blocking its execution however the thread must call the releasemutex method the same number of times to release ownership of the mutex the mutex class enforces thread identity so a mutex can be released only by the thread that acquired it,['c#'] +288719,copying objects using different allocators in c so i have a nice persistent allocator class persistent alloct that allows me to allocate c container objects and strings in persistent memory which is backed by an mmaped file that can persist from one run of my program to the nextmy problem comes when i want to do anything that mixes persistent and non persistent objects for example i havetypedef stdbasic stringchar stdchar traitschar persistent allocchar pstringpstring a b cstdstring x y zi want to be able to do things likeif a x a yc z band so forth but by default it does not work as pstring and stdstring are unrelated types now as far as the comparison is concerned i can definetemplatetypename alloc1 typename alloc2 inline booloperatorconst stdbasic stringchar stdchar traitschar alloc1 a const stdbasic stringchar stdchar traitschar alloc2 b return strcmpac str bc str 0and now i can compare strings for equality but adding these for every operation seems like a pain it seems like they should be provided by the standard library worse assignment operators and copy constructors must be members and cannot be defined as global inline functions like thisis there a reasonable way of doing this or do i have to effectively rewrite the entire standard library to support allocators usefully,['c++'] +288743,openmp nested parallel for loops vs inner parallel for if i use nested parallel for loops like thispragma omp parallel for scheduledynamic1for int x 0 x x max x pragma omp parallel for scheduledynamic1 for int y 0 y y max y parallelize this code here important no code in hereis this equivalent tofor int x 0 x x max x pragma omp parallel for scheduledynamic1 for int y 0 y y max y parallelize this code here important no code in hereis the outer parallel for doing anything other than creating a new task,['c++'] +288760,is the behaviour of casting a negative double to unsigned int defined in the c standard i have code that runs on different platforms that seems to get different results i am looking for a proper explanation windows double dbl 12345 int d cast unsigned intdbl d cast 123wince armdouble dbl 12345 int d cast unsigned intdbl d cast 0editthanks for pointing in the right direction fix double dbl 12345 int d cast unsignedintdbl d cast 123 works on both,['c'] +288796,easy way to test if each element in an numpy array lies between two values i was wondering if there was a syntactically simple way of checking if each element in a numpy array lies between two numbersin other words just as numpyarray12345 5 will return arraytrue true true true false i was wondering if it was possible to do something akin to this1 numpyarray12345 5 to obtain arrayfalse true true true falsei understand that i can obtain this through logical chaining of boolean tests but i am working through some rather complex code and i was looking for a syntactically clean solutionany tips,['python'] +288798,how can i get the last 7 characters of a php string possible duplicatephp cut a string after x characters how would i go about grabbing the last 7 characters of the string belowfor exampledynamicstring 2490slkj409slk5409elsnewstring some functiondynamicstringecho the new string is newstringwhich would thisplaythe new string is 5409els,['php'] +288826,why is not this linq group by aggregating the rows in vbnet i have a table that has a 2 part key an id column and a version number i am trying to select only the latest version of the recordsi am trying to use the expression style of linq to achieve a group by and pull out the aggregate max value of the version however no aggregation is taking placesummarized codefrom c in credentialsgroup join group join group ccredentialid neclientid cversion by neclientid ccredentialid into cgroup groupfrom cg in cgroupselect new with clientid cgclientid credentialid cgcredentialid maxversion cgroupmaxfunctionp pversionactual resultsclientid credentialid maxversion1196 1 3 1196 1 3 1196 1 3 1196 2 1 desired resultsclientid credentialid maxversion1196 1 3 1196 2 1 also tried same resultsgroup c by key new with key neclientid key ccredentialid into cgroup groupfrom cg in cgroupselect new with clientid keyclientid credentialid keycredentialid maxversion cgroupmaxfunctionp pversioni am looking for a solution that does not involves creating custom classes with matching properties and custom sorting grouping functions and does not use the lambda expressions on the tail end of the querythanks,['sql'] +288840,string splitting in python using regex i am trying to split a string in python so that i get everything before a certain regexexample string somefilenum10exampletxti need everything before this part num10 regex rnumdd the number will vary and possibly what comes afterany ideas on how to do this,['python'] +288850,pid for new thread i have a quick question about new thread created by pthread createwhen i print the pid get from getpid of main thread and the child thread they are the same while when i using htop linux utility to show pid they are different can any one explain this to me thankskaikait420slpi pthr createmain thread pid 4845 ppid 35child thread pid 4845 ppid 35htop shows,['c'] +288851,numpy equivalent of matlabs findpeaks function possible duplicatepeakfinding algorithm for pythonscipy i am looking to find local maxima in a vector of floatingpoint numbers as is done by matlabs findpeaks functiondoes numpy have a similar functionthanks,['python'] +288857,viewport fit screen width and big images i am trying to use a webview for thisplaying a big image with the builtin multitouch and trying to avoid memory crashes i set the webview this way setinitialscale20 websettings settings getsettings settingssetjavascriptenabledtrue settingssetusewideviewporttrue settingssetloadwithoverviewmodetrue settingssetsupportzoomtrue settingssetbuiltinzoomcontrolstrueand then load the following codeheadmeta nameviewport contentwidthdevicewidth userscalableyesheadbody stylemargin 0 padding 0 img altimage srcthe src goes here idtheimage bodythe problem is that if it loads a medium image 1600x1200 for example it works nice and the image fits the screen widthbut if the image is bigger 7300x5200 in my example it appears like zoomed in and with the zoom out thisabledif you want to test the images urls areimg1 img2note i am not the owner of that images and i am only using it for testing,"['java', 'android', 'html']" +288875,two onclick actions one button does someone know a wizards trick to make it work input typebutton valuedont show this again onclickfblikedump onclickwritecookie ps i am using it in a js file,"['javascript', 'html']" +288900,how to create sqlite database programmatically i am new to iphone development i have created the database using the terminal in mac os x now i am trying to create the database programatically in iphone application using objective c can somebody tell me a good site where i can view the sample applications which are worked and is there any site for learning the tutorial please somebody help me,['iphone'] +288915,how to tackle daylight savings using timezone in java i have to print the est time in my java application i had set the timezone to est using calendar cal calendargetinstancetimezonegettimezoneestbut when the daylight savings is being followed in this timezone my code does not print the correct timeit prints 1 hour less how to make the code work to read the correct time always irrespective of whether the daylight savings are being observed or not ps i tried setting the timezone to edt but it doesnt solve the problem,['java'] +288938,how to compile packages in java i have written a simple package program a simple package package mypack class balance string name double bal balancestring n double b namen balb void show ifbal0 systemoutprintln systemoutprintlnname bal class accountbalance public static void mainstring args balance currentnew balance3 current0new balanceakjuwatkar123123 current1new balanceapdhoke34567 current2new balanceanil sarang10098 forint i0i3i currentishow i am using ubuntu 1004 when i compile it usingjava mypackaccountbalancei get the following messageexception in thread main javalangnoclassdeffounderror mypackaccountbalancecaused by javalangclassnotfoundexception mypackaccountbalance at javaneturlclassloader1runurlclassloaderjava217 at javasecurityaccesscontrollerdoprivilegednative method at javaneturlclassloaderfindclassurlclassloaderjava205 at javalangclassloaderloadclassclassloaderjava321 at sunmisclauncherappclassloaderloadclasslauncherjava294 at javalangclassloaderloadclassclassloaderjava266could not find the main class mypackaccountbalance program will exitwhat is wrong please help me outi have installed openjdk do i need to install anything elsei am using ubuntu 1004 kindly help me out,['java'] +288992,how to create license for my java software i am having a very big problem that is how to create license for my software ok think this is my license key 12345ywwhen the user enter this license key the software should allow him to use the software all right once the user enter the license key my software must remember he has entered the valid key rightbecause from next time onwards it do not have to prompt license dialog my question is how can i make my software to remember the user had entered the license in windows based apps what most of they do is entering an entry to the windows registry can i do the same then what about ubuntu and mac i thought of writing a txt file so m software can read it and find whether license is entered or not however that is the most secureless system i can think of so if i enter the above license key how can i make my software to remember it i am really glad if you can give me a code example too ie i do not know how to edit the registry in case of windows registry etc please help me,['java'] +288993,validating and reading a word file in android i want to be able to access a word file in the sdcard of the users phone and the file will be chosen by the user i want to be able to process the file ie read its contents and modify it as the user wishes and save it when the user clicks asaveais it possible in android how can i make the program understand that the file is a word filenote that i do not want to view the word file the user will select the word file and my app should be able to make some changes to it and save it,['android'] +289006,how to get read data from response header in jqueryjavascript possible duplicatejquery and ajax response header if the server is returned data in response header how i can read it i am sending an ajax request to a server it does not return anything but the location in response header i want to read that location using javascript or jquery,"['javascript', 'jquery']" +289031,linearylayout would not resize once its height is 0 got a weird one i have managed a bring it down to a very simple example really cannot figure it outi have got a linearlayout inside a linearlayout i want to resize the child using an animation which i have working a treat sometimes here is my layout xmlxml version10 encodingutf8linearlayout xmlnsandroid androidlayout widthfill parent androidlayout heightfill parent androidorientationvertical linearlayout androidlayout widthfill parent androidlayout heightwrap content androidorientationvertical lots more controls will appear above linearlayout androidlayout widthfill parent androidlayout height0dp androidididanimation subject textview androidlayout widthfill parent androidlayout heightwrap content androidtextstringhello androidgravitycenter linearlayout lots more controls will appear below linearlayout button androidtextslide it down androidlayout widthfill parent androidlayout heightwrap content androidonclickbtndoanimdown onclick linearlayoutnow as you can see there is a button and here is the code for that buttonpublic void btndoanimdown onclickview v view pnlslider findviewbyidridanimation subject pnlslidermeasure10 10 dropdownanim anim new dropdownanimpnlslider pnlslidergetmeasuredheight true animsetduration20 pnlsliderstartanimationanim return if you were to run it now it wouldnt slide down at all however if you were to move the button into the linearlayout which i have named overview and put it after the child linearlayout it works a treat like thisxml version10 encodingutf8linearlayout xmlnsandroid androidlayout widthfill parent androidlayout heightfill parent androidorientationvertical linearlayout androidlayout widthfill parent androidlayout heightwrap content androidorientationvertical lots more controls will appear above linearlayout androidlayout widthfill parent androidlayout height0dp androidididanimation subject textview androidlayout widthfill parent androidlayout heightwrap content androidtextstringhello androidgravitycenter linearlayout lots more controls will appear below button androidtextslide it down androidlayout widthfill parent androidlayout heightwrap content androidonclickbtndoanimdown onclick linearlayoutlinearlayoutit now slides down exactly as expected clearly something is going it with the parent layout as getmeasuredheight returns the correct value it is just the animation does not actually runthis is the animation class am i missing something silly probably amimport androidutillogimport androidviewviewimport androidviewanimationanimationimport androidviewanimationtransformationpublic class dropdownanim extends animation int targetheight view view boolean down public dropdownanimview view int targetheight boolean down thisview view thistargetheight targetheight thisdown down override protected void applytransformationfloat interpolatedtime transformation t int newheight if down newheight int targetheight interpolatedtime else newheight int targetheight 1 interpolatedtime logdnew height stringvalueofnewheight viewgetlayoutparamsheight newheight viewrequestlayout override public void initializeint width int height int parentwidth int parentheight superinitializewidth height viewviewgetparentgetwidth parentheight override public boolean willchangebounds return true any help would be fantastic,['android'] +289033,how to set commandtimeout for dbcontext i am looking a way to set commandtimeout for dbcontext after searching i found the way by casting dbcontext into objectcontext and setting value for commandtimeout property of objectcontextvar objectcontext thisdbcontext as iobjectcontextadapterobjectcontextbut i have to work with dbcontext,['c#'] +289062,javascript get the text value of a column from a particular row of an html table so a user clicks on a row of a table and i want to get in javascript the innerhtml of let us say the 3d column of that rowsomething like documentgetelementbyidtblblahrowsicolumnsjinnerhtmldoes not seem achievable and i cannot find anything here or in the netany solutions would be very much appreciated no jquery thanks in advance,"['javascript', 'html']" +289081,how to do proper reflection of base interface methods i have 2 interfaces and 2 classes that i investigate via reflectioniparentichild derives from iparentparent child derives from parentstrange thing for me is the fact that when i look through reflection on ichild type i do not find iparent method same code applied to child type works as expected reflection shows parent methodinterface iparent void parentmethodinterface ichild iparent void childmethodclass parent public void parentmethodclass child parent public void childmethodvoid main investigate derived interface type t typeofichild var info tgetmethodchildmethodok consolewritelineinfo info tgetmethodparentmethodreturns null consolewritelineinfo investigate derived class t typeofchild info tgetmethodchildmethodok consolewritelineinfo info tgetmethodparentmethodok consolewritelineinfoplease explain such behaviour is there any workaround to reflect base interfaces methods from the derived interfaces type,['c#'] +289120,fast exp calculation possible to improve accuracy without losing too much performance i am trying out the fast expx function that previously was described in this answer to an so question on improving calculation speed in cpublic static double expdouble x var tmp long1512775 x 1072632447 return bitconverterint64bitstodoubletmp 32the expression is using some ie floating point tricks and is primarily intended for use in neural sets the function is approximately 5 times faster than the regular mathexpx function unfortunately the numeric accuracy is only 4 2 relative to the regular mathexpx function ideally i would like to have accuracy within at least the subpercent range i have plotted the quotient between the approximate and the regular exp functions and as can be seen in the graph the relative difference appears to be repeated with practically constant frequencyis it possible to take advantage of this regularity to improve the accuracy of the fast exp function further without substantially reducing the calculation speed or would the computational overhead of an accuracy improvement outweigh the computational gain of the original expressionas a side note i have also tried one of the alternative approaches proposed in the same so question but this approach does not seem to be computationally efficient in c at least not for the general caseupdate may 14upon request from adriano i have now performed a very simple benchmark i have performed 10 million computations using each of the alternative exp functions for floating point values in the range 100 100 since the range of values i am interested in spans from 20 to 0 i have also explicitly listed the function value at x 5 here are the results mathexp 62525 ms exp5 06737946908547empty function 13769 ms expneural 14867 ms exp5 0675211846828461 expseries8 15121 ms exp5 0641270968867667 expseries16 32046 ms exp5 06736189488182 exp1 15062 ms exp5 12325982094 exp2 15090 ms exp5 13708332516253 exp3 16251 ms exp5 12325982094 exp4 17924 ms exp5 728368055056781 exp5 20972 ms exp5 613293614238501 exp6 24212 ms exp5 3518353166184 exp7 29092 ms exp5 18271053775984 exp7 38482 ms exp5 0695945286970704expneural is equivalent to the exp function specified in the beginning of this text expseries8 is the formulation that i originally claimed was not very efficient on net when implementing it exactly like neil it was actually very fast expseries16 is the analogous formula but with 16 multiplications instead of 8 exp1 through exp7 are the different functions from adrianos answer below the final variant of exp7 is a variant where the sign of x is checked if negative the function returns 1expx insteadunfortunately neither of the expn functions listed by adriano are sufficient in the broader negative value range i am considering the series expansion approach by neil coffey seems to be more suitable in my value range although it is too rapidly diverging with larger negative x especially when using only 8 multiplications,['c#'] +289124,emberjs historyundo edit i have made my own implementation which is on githubi was wondering is there a builtin feature in ember that allows to save states of objectsarrays in our app weve built our own undohistory implementation for a particular emberarraycontroller but it seems to be buggy and slow in firefox so i am wondering if there is anything out there that would replace our scriptbasically what we use it forusers add edit modify elements in that array and sometimes they would like to undoredo their changes at the moment we limit the amount of states to 30 may not be the optimal amount any thoughtslinks are appreciated,['javascript'] +289162,fast double to string conversion with given precision i need to convert double to string with given precision stringformat3f value or decimalformat does the job but benchmarks show that it slow even in comparison to not very fast doubletostring conversion about 13 seconds to convert 1 million numbers on my machineare there any better way to do itupdate benchmarking resultsrandom numbers from 0 to 10 results are in operations per millisecond java 170 45benchmark mean mean error unitsstring format 747394 13197 opsmsbigdecimal toplainstring 1349552 31144 opsmsdecimalformat format 1890917 286 opsmsdouble tostring 3341941 85453 opsmsdoubleformatutil formatdouble 7760968 87630 opsmsso user format 14269388 168206 opsms,['java'] +289173,small edittext have a seterror with a lot of lines i have a small edittext and i want to thisplay errors using edittextseterror in it in android api 10 the message is thisplayed in a lot of lines and it is unreadable in android 15 works relatively fine i attach screenshots to illustrate the problem at the end of the questionhow i can thisplay the error messages in a appropriate modei wrote a little example to reproduce the problemthe activitypublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain edittext findviewbyidridbseterrora error description and bla bla bla bla blathe layoutxml version10 encodingutf8linearlayout xmlnsandroid androidlayout widthfill parent androidlayout heightfill parent androidorientationhorizontal edittext androididida androidlayout width0dip androidlayout heightwrap content androidlayout weight1 edittext androidididb androidlayout width0dip androidlayout heightwrap content androidlayout weight1 edittext androidididc androidlayout width0dip androidlayout heightwrap content androidlayout weight1 edittext androidididd androidlayout width0dip androidlayout heightwrap content androidlayout weight1 edittext androididide androidlayout width0dip androidlayout heightwrap content androidlayout weight1 edittext androidididf androidlayout width0dip androidlayout heightwrap content androidlayout weight1 linearlayoutdevice with android api 10tablet with android api 15related question but the answer does not work for meupdatei executed the same code on two equals simulators except the api level the results can be seen on the screens the api 15 still does not fix the error completely the text is legible but the popup is not in the correct position,['android'] +289182,converting an ip address to host name in my java application if user enters the ip we need to thisplay the host name if host name is given then we need to thisplay the ip of the hostfor example if user enters an ip address like 1731943637 application should thisplay googlecom and vice verse are there any utilities available to perform this operation,['java'] +289184,how to apply function to elements of a list i want to apply a function to all elements in the list but i want to actually change the elements which are objects not view results i think this is the problem with using map or list comprehensionsclass thingobject pass some collection of thingsmy things they are all big produces syntaxerror invalid syntaxisize big for i in my things produces syntaxerror lambda cannot contain assignmentmaplambda i isizebig i for i in my things no error but is it the preferred wayfor i in my things isizebigwhat is the way to do this,['python'] +289204,losing session state with aspnetsql server i have a aspnet mvc workflow configured as two websites managed by a load balancer the websites use sql server as the session state provider and have authentication switch off its not required now sporadically i appear to be losing session state and i believe this is because the request is being handled by the alternative server so essentially the user is jumping from server to server depending how the load balancer sees fit i am not always losing session state at the same stage in the workflow so i believe it is something related to the web farm configuration sql server session stateboth applications use the same machine key to encrypt and decrypt session state stored in sql serverthe configuration on both servers is as followsauthentication modenone sessionstate modesqlserver sqlconnectionstringconnectionstring machinekey decryptionkey7cb456774af02f7f1ac8570faf31545b156354d9e2daad validationkey89b5b536d5d17b8fe6a53cbb3ca8b8695289ba3df0b1370bc47d362d375cf91525ddb5307d8a288230dcd4b3931d23aed4e223955c45cff2af66bcc422ec7ecd i have confirmed that this is identical on both servers is there something i am missing this does not occur in my development environment when i am using a single serveri fear i am suffering from the friday blues and no doubt will figure out the answer next week sadly i do not want to waitany ideas,['asp.net'] +289226,xcode pain syntax highlight broken i have had problems with xcode 4 431 4e1019 after a few hours maybe less my code is not highlighting correctly it seems xcode loses all sense of cocoa and i end up with the example screenshot i cannot jump to methods by clicking on a method holding down cmd key this should work as expected and it does not even work for the cocoa base classesthe only way i have found to sort this out is to go to organizer project and delete the projects derived data then quit and relaunch xcode but it is not long before it goes wrong againhas anyone else had this problem it is really slowing me down if anyone has any tips that would be great,['ios'] +289233,how to get a cgpoint from a tapped location i am working on a graphing calculator app for the ipad and i wanted to add a feature where a user can tap an area in the graph view to make a text box pop up thisplaying the coordinate of the point they touched how can i get a cgpoint from this,['ios'] +289239,thisplayblock not working in chrome or safari i have a simple need to thisplay the cells of a table row vertically this works just fine in ff but not in chrome or safari on the ipadthe example below renders as expected in ff with each row cell under each other but in chrome it seems to ignore the thisplayblock altogether what is the issue or is there a better way to do thisthe reason for wanting this is that im using media in the css to render the table differently for a small screenfor a more visual examplea normal table might bedata1 data2 data3but with thisplayblock it should bedata1data2data3many thankshtmlheadstyle table thead tr td thisplayblock tabletr border 1px dotted red td border1px dashed blue thead thisplaynone styleheadbodytabletheadtr tdheading 1td tdheading 2td tdheading 3tdtrtheadtbodytr tddata 1td tddata 2td tddata 3tdtrtr tddata 1td tddata 2td tddata 3tdtrtr tddata 1td tddata 2td tddata 3tdtrtbodytablebodyhtml,['css'] +289240,unit testing asynchronous operation i want to unit test a method that i have that performs and async operation taskfactorystartnew method to test and return value var result longrunningoperation i stub the necessary methods etc in my unit test written in c but the problem is that the async operation is not finished before i assert the testhow can i get around this should i create a mock of the taskfactory or any other tips to unit testing an async operation,['c#'] +289251,how to send files to other iphones via bluetooth i am doing a little app to allow users to edit and share text fast on the iphoneso i know a little of bluetooth programing for iphone but i am not able to do what i want to dothe text of the app is saved in nsuserdefaults i want to send this to another ios device by the key text1 text2 or text3 i know that i have to convert the text that will be in a string to nsdata and tren i would like to have it in a nsmutabledictionary with its keyi also want to be looking for new ios devices arround all the timeplease help me because i do not know how i can do it and it is so hard to find tutorials of iphone bluetooth programming thank you,"['iphone', 'objective-c', 'ios']" +289275,jquery selector for div with class i tried this below i think the return object of divtab select0 is not a jquery object but i cannot even use pure javascript methodis there any way to make it jquery object for instance divtab select0i know thiss sillythank you for readingvar tmp divtab select0 alerttmp this gives me htmldivelement collectly but i cannot use any of javascriptalerttmpnodename but this give me error uncaught typeerror cannot read property nodename of undefinedtmphide neither i cannot use this,"['javascript', 'jquery']" +289278,how can i get php working again in the command line i am completely at loss here and am about to wipe my hard drive clean and start from a fresh os install i have been trying for two days to create a new yii app in the terminal and have finally figured out that the terminal or command line can not even execute php all of a sudden i had no problem in past creating an executing php from the command line but now it is not working when i type which php i get nothing when i type php v i get bash php command not foundand when i try to create a new yii application i get env php no such file or directory i am using mac osxlion and my path looks like this at the momentusrbinbinusrsbinsbinusrlocalbinusrx11binusrlocalgitbini have tried looking through the php manual and i am getting nowhere how can i reconfigure the command line to execute php any help is greatly appreciated,['php'] +289281,add labels to d3 chord diagram i am a rookie programmer so this one will probably be an easy one for most of you what lines of code do i need for labels andor mouseover text for this chord diagrami need it to thisplay the name of the category in the outer strip when you mouse over i want to thisplay the exact number and both categories something like this a 5 thing from bediti still cannot figure out how to implement it in my code can someone fill in my example code an explain whats going on doctype htmlhtml head meta httpequivcontenttype contenttexthtml charsetutf8 titleselecties ek 2010title script typetextjavascript srcd3v2jsscript link typetextcss relstylesheet hrefek2010css head body div idchartdiv script typetextjavascript srcek2010jsscript bodyhtmland from var chord d3layoutchord padding05 sortsubgroupsd3descending matrix 0 0 7 5 0 0 8 3 7 8 0 0 5 3 0 0 var width 10 height 10 innerradius mathminwidth height 3 outerradius innerradius 11var fill d3scaleordinal domaind3range4 range0 ffdd89 957244 f26223var svg d3selectchart appendsvg attrwidth width attrheight height appendg attrtransform translate width 2 height 2 svgappendg selectallpath datachordgroups enterappendpath stylefill functiond return filldindex stylestroke functiond return filldindex attrd d3svgarcinnerradiusinnerradiusouterradiusouterradius onmouseover fade1 onmouseout fade1var ticks svgappendg selectallg datachordgroups enterappendg selectallg datagroupticks enterappendg attrtransform functiond return rotate dangle 180 mathpi 90 translate outerradius 0 ticksappendline attrx1 1 attry1 0 attrx2 5 attry2 0 stylestroke 0ticksappendtext attrx 8 attrdy 35em attrtextanchor functiond return dangle mathpi end null attrtransform functiond return dangle mathpi rotate180translate16 null textfunctiond return dlabel svgappendg attrclass chord selectallpath datachordchords enterappendpath stylefill functiond return filldtargetindex attrd d3svgchordradiusinnerradius styleopacity 1 returns an array of tick angles and labels given a group function groupticksd var k dendangle dstartangle dvalue return d3range0 dvalue 1mapfunctionv i return angle v k dstartangle label i 5 null v 1 internat returns an event handler for fading a given chord group function fadeopacity return functiong i svgselectallgchord path filterfunctiond return dsourceindex i dtargetindex i transition styleopacity opacity,['javascript'] +289288,mod wsgi error class dict not accessible in restricted mode this started biting our ass on our production server really hard we saw this occasionally for 1 request per week back then we found out it is because of mod wsgi doing some funky stuff in some configs as we could not track the reason for the bug we decided that it did not require instant attentionhowever today on 1 of our production servers this really occurred for 10 of all server requests that is 10 of all server requests failed with this very same errormod wsgi pid1718 target wsgi script installationdirourprogramprodthispatchwsgi cannot be loaded as python modulemod wsgi pid1718 exception occurred processing wsgi script installationdirourprogramprodthispatchwsgitraceback most recent call last file installationdirourprogramprodthispatchwsgi line 7 in module from pyramidpaster import get app file installationdirvenvlocallibpython27sitepackagespyramid13a6py27eggpyramidpasterpy line 12 in module from pyramidscripting import prepare file installationdirvenvlocallibpython27sitepackagespyramid13a6py27eggpyramidscriptingpy line 1 in module from pyramidconfig import global registries file installationdirvenvlocallibpython27sitepackagespyramid13a6py27eggpyramidconfig init py line 61 in module from pyramidconfigassets import assetsconfiguratormixin file installationdirvenvlocallibpython27sitepackagespyramid13a6py27eggpyramidconfigassetspy line 83 in module implementeripackageoverrides file installationdirvenvlocallibpython27sitepackageszopeinterface380py27linuxx86 64eggzopeinterfacedeclarationspy line 480 in classimplementsob selfinterfaces file installationdirvenvlocallibpython27sitepackageszopeinterface380py27linuxx86 64eggzopeinterfacedeclarationspy line 445 in cl spec implementedbycls file installationdirvenvlocallibpython27sitepackageszopeinterface380py27linuxx86 64eggzopeinterfacedeclarationspy line 285 in im spec cls dict get implemented runtimeerror class dict not accessible in restricted modeubuntu precise 64bit with latest apache mod wsgi python 27 using mpm worker mod wsgi in daemon mode this is the only program running on the server and there is only one wsgi interpreter in the config is this because of mpm worker spawning new threads or what more importantly how do we fix itwe have the following to subdivide requests to 4 daemon processes based on a cookiewsgipythonoptimize 1wsgidaemonprocess sticky01 processes1 threads16 thisplaynamegroupwsgidaemonprocess sticky02 processes1 threads16 thisplaynamegroupwsgidaemonprocess sticky03 processes1 threads16 thisplaynamegroupwsgidaemonprocess sticky04 processes1 threads16 thisplaynamegroupvirtualhost 81 wsgirestrictprocess sticky01 sticky02 sticky03 sticky04 wsgiprocessgroup envprocess wsgiscriptalias installationdirourprogramprodthispatchwsgi virtualhost,['python'] +289334,increase the font size of emoji characters in a uitextview in ios 5x if i have uitextview and set the font size to say 32 when i run the application in both simulator and on the device i see a large cursor and text that i type appears just as i would assume it would but if i switch the the emoji keyboard they thisplay small like the size of the font was never increasedi know these emoji font scales as i have blown them up to giant proportions in osx lion and if i create a uibutton with an emoji character as it is label and set the font to apple color emoji and the size to 64 they look huge and gorgeous on my device it seems just the uitextview is not resizing them,['ios'] +289339,how can i build a json string in javascriptjquery i would like to build a json string programmatically the end product should be something likevar myparamsjson first name bob last name smith however i would like to do it one parameter at a time if it were an array i would just do something likevar myparamsarray myparamsarrayfirst name bobmyparamsarraylast name smithi wouldnt even mind building that array and then converting to json any ideas,['javascript'] +289356,convert pdf with 300dpi bitmaps to svg i am creating a tool to convert pdfs into svg these pdfs contain graphical data including large bitmaps at 300 dpi and a bunch of vectors as well poking around here on stackoverflow i have found pdf2svg which great works like a charm and the vector data is perfect but it looks like the bitmaps are getting downscaled to 72dpi the dimensions are still 8x10 in inches but you can tell that the dpi is not right when you zoom in soft of makes sense that the default values would presume 72 dpi but i need the full resolution bitmap imagespdf2svg uses poppler and cairo to make the conversion i have poked around in the code and i see where it is creating a poppler page and a cairo surface and i have seen in the documentation that a poppler page has a concept of scale that seems relevant but i cannot figure out where to plug it in i tried experimentally hardcoding the height and width passed into cairo svg surface create to the correct values but it made the dimensions applied to the whole svg larger without affecting the embedded bitmappoppler page get size page width height open the svg filesurface cairo svg surface createsvgfilename width heightdrawcontext cairo createsurface render the pdf file into the svg filepoppler page renderpage drawcontextcairo show pagedrawcontexti do not think what i am trying to do is very esoteric so i am hoping someone who has experience with the libraries will see my error right away any help of course would be immensely appreciated,['c'] +289369,can not get a simple bootstrap modal to work i am trying to get a simple bootstraps modal sample to work i follow this document which says you can activate modals on your page easily without having to write a single line of javascript just give an element a datacontrolsmodal attribute which corresponds to a modal element id but i have done whatever i could and had a huge amount of research still can not get this simple modal to workdiv classmodal idmymodaldiv classmodalheaderbutton classclose datathismissmodalabuttonh3modal headerh3divdiv classmodalbodypone fine bodyapdivdiv classmodalfootera href classbtncloseaa href classbtn btnprimarysave changesadivdivi have either thisa classbtn datacontrolsmodalmymodallaunch modalaor this a classbtn datatogglemodal hrefmymodal launch modalabutton to activate the modal i have loaded the bootstrapmodaljs on the page as well unless i added a javascript line to handle the launch modal click event when i click on launch modal nothing happens at all are there anything that i have missed,"['javascript', 'jquery']" +289386,fast and efficient php session i currently have the following code for every page on my website please could anyone confirm if this is a good practice to start and continue a php sessionsession settingssession name phpsessid session exp time 10 previous name session namesession nameset garbage collection parametersini setsessiongc maxlifetime session exp timeini setsessiongc probability 1ini setsessiongc divisor 100ini setsessionname session nameini setsessioncookie domain session set to not be available to subdomainsini setsessioncookie lifetime 0set the session cookie parameterssession set cookie paramssession exp time start or continue a sessionsession startif isset cookiesession namesetcookiesession name cookiesession name 2147483647 please note that this script is included in every pageanother related questionshould i set a custom session save path or should i just use the servers default session save path what are the pros and cons from what i understand if you do not set a custom session save path then chances are you might have some kind of conflict on a shared hosting please help enlightenthanks in advance,['php'] +289395,regex for check the input string is just in persian language i work with mvc and i am new on it i want to check input values is only in persian language characters by regularexpression validation so i think to use regex and need to check in range of unicodes but i do not lnow how can find range of persian characters unicode am i right about this regex what is your suggestion and how can i find range of unicode in persian,['c#'] +289400,how to enable both hardware and virtual keyboards on android ice cream sandwich i am developping a stock management application with django for a customers company and want to use an ice cream sandwich tablet as the enduser devicei use an usb barcode reader which works finemy problem is that once the barcode reader is plugged in it is recognized as a real keyboard and i cannot access the virtual keyboard anymore this is a big issue for me because i only use the barcode reader to encode ean13 codes and need the soft keyboard besideis there any way to enable both virtual and real keyboards i really need help on thisthank you,['android'] +289417,how to receive a copied image in mobilesafari i am building an ios website and i am trying to get the recently copied image using javascriptwhen you hold your finger on a photo in a website a menu will popout with the option to save the image or copy when you press copy and paste it later in a textfield you can get the url withpasteeventclipboarddatagetdatatexturilistwhen you copy an image in the camera roll facebook application or by selecting and you go to the same textfield or textarea the paste option is not available however when going to the mailapplication the paste option is available and pasts the image so does anyone have a clue how to get the url or binary data for a copied photo on an ipadapple documentationexample,"['javascript', 'iphone']" +289418,line number in google perftools cpu profiler on macosx i am trying to profile some c programs on macosx so i built googleperftools wrote a program compiled using macports g 47 with g compiler flag and linked to libprofiler then i rancpuprofilecpuprofile aoutthen i ran pprof to generate the outputhidden pprof text aout cpuprofile using local file aoutusing local file cpuprofileremoving sigtramp from all stack tracestotal 282 samples 107 379 379 107 379 0x010d729e 16 57 436 16 57 0x010d721a5f 12 43 479 12 43 0x010d721de8 11 39 518 11 39 0x010d721a4e 9 32 550 9 32 0x010d721e13 8 28 578 8 28 0x010d721a64 7 25 603 7 25 0x010d72f0 6 21 624 6 21 0x010d721a4c 6 21 645 6 21 0x010d721b1f 6 21 667 6 21 0x010d721e0c 5 18 684 5 18 0x010d721fba it looks like the perftools do not convert the addresses to function namesdoes anyone know what i am missing here what should i do to let the profiler generate the correct resultedit more information it is not a problem of pprof or googleperftools but more something like gcc or macosx because instrumentapp also shows addresses instead of line numbers i am not familiar with how debug symbols work under mac os x so i would rather think it as my missing something here instead of being bugs in gcc or mac os x i wonder whether anyone can provide some hints on how debug info works for mac os x,['c++'] +289420,customizing left right uisegmentedcontrol buttons i am trying to customize the following segmented control using a left image for the first button and a right image for the second button how would i do this using uiappearancei want to change the following segmentedcontrolto something similar like belowthe reason i want to use a custom image is so that i can change the corners of the buttons if you look at the blue segmented control it is more squared my image has it is own cornersi was thinking of something like this but no useuiimage leftimage uiimage imagenamedleftcontrolpng resizableimagewithcapinsetsuiedgeinsetsmake0 15 0 15uiimage rightimage uiimage imagenamedrightcontrolpng resizableimagewithcapinsetsuiedgeinsetsmake0 15 0 15uisegmentedcontrol appearance setbackgroundimageleftimage forstateuicontrolstatenormal barmetricsuibarmetricsdefault uisegmentedcontrol appearance setbackgroundimagerightimage forstateuicontrolstatenormal barmetricsuibarmetricsdefault,"['iphone', 'ios']" +289458,why i do not have access rights on the server i use elmah in local alrighton the server however it issues the followed error and i cannot figure out what how to gain access403 forbidden access is denied you do not have permission to view this directory or page using the credentials that you supplied,['c#'] +289460,how do i create a c program without gui i know that you can create a windows forms application and set it to be invisableand if i create a console application the console window will openand i have no use for the consoleso how do i create a simple application that has no gui at all,['c#'] +289503,is there any way to compile additional code at runtime in c or c here is what i want to dorun a program and initialize some data structuresthen compile additional code that can accessmodify the existing data structuresrepeat step 2 as neededi want to be able to do this with both c and c using gcc and eventually java on unixlike systems especially linux and mac os x the idea is to basically implement a readevalprint loop for these languages that compiles expressions and statements as they are entered and uses them to modify existing data structures something that is done all the time in scripting languages i am writing this tool in python which generates the cc files but this should not be relevanti have explored doing this with shared libraries but learned that modifying shared libraries does not affect programs that are already running i have also tried using shared memory but could not find a way to load a function onto the heap i have also considered using assembly code but have not yet attempted to do soi would prefer not to use any compilers other than gcc unless there is absolutely no way to do it in gccif anyone has any ideas or knows how to do this any help will be appreciated,"['c++', 'c']" +289505,jquery hide mouse if it is not moving i am trying to hide the mouse if it has not moved for a period of timethis is the code i am usingdocumentreadyfunction var j documentmousemovefunction cleartimeoutj htmlcsscursor default j settimeouthide 10 function hide htmlcsscursor nonewhen the hide function is called the cursor is hidden but unhides a split second later any help is appreciated,"['javascript', 'jquery', 'html']" +289516,getting the response of a asynchronous httpwebrequest im wondering if theres an easy way to get the response of an async httpwebrequesti have already seen this question here but all im trying to do is return the response which is usually json or xml in the form of a string to another method where i can then parse it deal with it accordinglyheres some codei have these two static methods here which i think are thread safe as all the params are passed in and there are no shared local variables that the methods usepublic static void makeasyncrequeststring url string contenttype httpwebrequest request httpwebrequestwebrequestcreateurl requestcontenttype contenttype requestmethod webrequestmethodshttpget requesttimeout 20 requestproxy null requestbegingetresponsenew asynccallbackreadcallback requestprivate static void readcallbackiasyncresult asyncresult httpwebrequest request httpwebrequestasyncresultasyncstate try using httpwebresponse response httpwebresponserequestendgetresponseasyncresult stream responsestream responsegetresponsestream using streamreader sr new streamreaderresponsestream need to return this response string strcontent srreadtoend manualreseteventset catch exception ex throw ex,['c#'] +289534,python overhead on looping over an iterable class i was fiddling around with pythons generators and iterable class just for fun basically i wanted test out something that i have never been too sure about that classes in pythons have some significant overhead and it is better to rely on methods that implement yield instead of classes that implement an iterator protocol if you cani could not find a satisfying explanation on this topic in google so i decided to test them out on my own using these two simple scripts func iterpy and class iterpyheres func iterpyusrbinenv pythonimport time x 0def create generatornum mylist rangenum for i in mylist yield it timetimegen create generator10for i in gen x x iprint 3f timetime tand heres class iterpyusrbinenv pythonimport timex 0class generatorobject def init self num selfstart 0 selfend num def iter self return self def nextself if selfstart selfend raise stopiteration else selfstart selfstart 1 return selfstartt timetimegen generator10for i in gen x x iprint 3f timetime ti then ran each of them 10 times using this in bash for class iterpy for examplefor i in 110 do class iterpy doneand here are the average running times for each of themclass iterpy 00864func iterpy 00307now my questions areare my methods correct is my comparison fairif so why the big difference why did class iterpy take almost three times as long as func iterpy to runif not how can i improve my methods or come up with a better comparison edit as dacav suggested i also tried running func iterpy using xrange instead of range this decreases its average running time to 00263 seconds,['python'] +289563,funnel analysis calculation how would you calculate a funnel suppose that i track an event a user takes on a website events can be things likeviewed homepageadded item to cartcheckoutpaid for ordernow each of those events are stored in a database likesession id event name created date so now i want to build a report to thisplay a particular funnel that i will define likestep1 event nstep2 event n2step3 event n3so this particular funnel has 3 steps and each step is associated with any eventhow can i build a report for this now given the above data i havenote just want to be clear i want to be able to create any funnel that i define and be able to create a report for itthe most basic way i can think of isget all events for each step i have in my databasestep1 will be x of people performed event nnow i will have to query the data for step2 who also performed step1 and thisplay the same as 3 but for step3 with the condition for step2i am curious how these online services can thisplay these types of reports in a hosted saas environment does mapreduce make this easier somehow,['java'] +289582,grails database migration plugin issues when i use the grails database migration plugin and run a dbmgormdiff for example after installing the spring security facebook plugin i have been getting problems like error error executing sql create index fk609fd5a460cfcc39 on facebook useruser id incorrect index name fk609fd5a460cfcc39it looks like the index in question is both a fk constraint and is then reused as an index later in the generated upgrade script if i change the name thus removing the duplicate everything works fine i am using mysql am i doing something wrongthanks,['mysql'] +289584,check if an array is subset of another array in ruby how can i check whether one array is a subset of another array regardless of the order of elementsa1 3 6 4a2 1 2 3 4 5 6 7 8 9a1 is a subset of a2,['ruby'] +289585,implement gethashcode for objects that contain collections consider the following objectsclass route public int origin get set public int destination get setroute implements equality operatorsclass routing public listroute paths get seti used the code below to implement gethashcode method for the routing object and it seems to work but i wonder if that is the right way to do it i rely on equality checks and as i am uncertain i thought i will ask you guys can i just sum the hash codes or do i need to do more magic in order to guarantee the desired effect public override int gethashcode return paths null paths selectp pgethashcode sum 0 i checked several gethashcode questions here as well as msdn and eric lipperts article on this topic but could not find what i am looking for,['c#'] +289595,parallel make set j8 as the default option i can set number of threads for the build process using j argument for example i have 4 cores 4 virtual when i write make j8 the speed increases 4 timesis it possible to set that value as default for example in linux gentoo in config file it is possible to set this default valueps i have arch linux,['c++'] +289606,is there a fast inmemory queue i can use that swaps items as it reaches a certain size i have been using cuda for less than a week and not familiar with all the options available in terms of librariessorry if my question is too wacky or impossible heres my problem i have a process that takes data and analyzes it then does 1 of 3 things 1 saves the results 2 thiscards the results or 3 breaks the data down and sends it back to be processed often option 3 creates a lot of data and i very quickly exceed the memory available to memy server is 16 gigs so the way i got around that was to setup a queue serverrabbitmq that i would send and receive work fromit swaps the queue once it reaches a certain size of memory this worked perfectly when i used small servers with faster nics to transfer the data but lately i have been learning and converting my code from java to cc and running it on a gpu which has made the queues a big bottleneck the bottleneck was obviously the network ioprofiling on cheap systems showed high cpu usage and similar on old gpus but new faster cpusgpus are not getting utilized as much and network io is steady at 300400mbs so i decided to try to eliminate the network totally and run the queue server locally on the server which made it faster but i suspect it could be even more faster if i used a solution that did not rely on external network serviceseven if i am running them locally it may not work but i want to experimentso my question is is there anything that i can use like a queue that i can remove entries as i read them but also swaps the queue to thisk once it reaches a certain sizebut keeps the inmemory queue always full so i do not have to wait to read from thisk when learning about cuda there are many examples of researchers running analysis on huge datasets any ideas of how they keep data coming in at the fastest rate for the system to processi imagine they are not bound by thisknetwork otherwise faster gpus wouldnt really give them magnitudes increase in performance does anything like this existps if it helps so far i have experimented with rabbitmqtoo slow for my situation apollo mqgood but still network based redthisreally liked it but cannot exceed physical memory playing with mmap and i have also compressed my data to get better throughput i know general solutions but i am wondering if there is something native to cc cuda or a library i can useideally i would have a queue in cuda global memory that swapped to the host memory that swapped to the thisk so the gpus would always be at full speed but that maybe wishful thinking if there is anything else you can think of let me know and i would enjoy experimenting with itif it helps i develop on a mac and run it on linux,"['c++', 'c']" +289608,difference between you v and s t texture coordinates whats the difference between a you v texture coordinate vs s t texture coordinatei know that you v and s t are used in opengli also know that s t are also used in java,['java'] +289631,jquery get the nth element of array buttonclickfunction alertcolumnvalhow could i get the first second or third element in column,['jquery'] +289637,how to reset to default button backcolor i was experimenting with different options for the button background color and ended up changing the backcolor property in the appearance category i then changed it back to what it is by default which is control but it still looks different from other buttonsi have tried building the project and restarting visual studio but it did not helpi know i can just drag another button and copypaste code but what causes this in the first place and how do i properly fix it,['.net'] +289641,activerecordstatementinvalid could not find table users i am learning ruby on rails tutorial i have finished the chapter 7 and it works well but come across 25 failureserrors like the followinguser failureerror user usernewname example user email activerecordstatementinvalid could not find table users specmodelsuser specrb18in new specmodelsuser specrb18inblock 2 levels in this is the users controllerrbclass userscontroller applicationcontroller def new user usernew end def show user userfindparamsid end def create user usernewparamsuser if usersave flashsuccess welcome to the sample app redirect to user else render new end endendthanks for your help,['ruby-on-rails'] +289642,djangopinax how do you use a pinax app apart from what you get with a pinax base project i am trying to understand pinax and plan to use it in my next projecti have started with a pinax basic project and now i have something to go with runservernow i understand that i can customize the initial setup that i got from pinax and customize the profiles themes etc as per my requirementsbut is that all that pinax provides i am very confused here like i want to use the pinax phileo app in my project so how does pinax helps me do that my effort i searched and found that i have to install it with pip install phileothen add it to installed apps and use it as requiredbut what did pinax do in this pinax has phileo featured on its website but why since i could have used it just like any other app on my nonpinax django projectso my question in a nutshell is what does pinax provide after a base project and default templates that come with pinax right now it feels like pinax just provides a base project with some apps already working with some default templates that is it then what about other apps featured on pinaxs website that do not come with base projects please help clear up the confusion updatemy question is somewhat what is the significance of pinaxecosystem when we already have them listed somewhere like djangopackagescom,['python'] +289664,android how do i dynamically set the package name at build time for an opensource project i am working on an opensource project as it is intended that anyone can download the source and build it themselves i do not want to hardcode the package name anywhere including the directory structurei use ant for building apparently i can modify buildxml but i believe this is overwritten by android update whatever is used will be committed to the git repo and it should not be too complicatedcurrently the process to build the code straight from the git repo is fairly simple heres an excerpt from the readme file cd srcisokeysisokeys android list targets i build against api level 10 android update project name isokeys target 1 path only needed first time ant debug adb d install r binisokeysdebugapkto me it makes sense to put the package name in localproperties because this is gitignored as the package name would not be anywhere else the build will fail without doing this so there needs to be at least 1 extra step in the readme but i want to keep it to a minimumedit of course another requirement is that diffs make sense which they do not if you manually rename the package name,['android'] +289673,how to thisableenable select field using jquery i would like to create an option in a form like i would like to order a selectbox with pizza pizzawhere selectbox is enabled only when checkbox is checked and thisabled when not checkedi come up with this codeforminput typecheckbox idpizza namepizza valueyes label forpizzai would like to order alabelselect namepizza kind optionchoose oneoption option valuemargarithamargarithaoption option valuehawaihawaioptionselectpizzaformscript srcscriptscriptvar update pizza function if pizzaischecked pizza kindremoveattrthisabled else pizza kindpropthisabled thisabled update pizzapizzachangeupdate pizzascripti tried various methods how to set thisabled attribute using prop attr and thisabled however nothing happens when applying to a input typecheckbox instead of select the code works perfectlyhow to thisableenable select using jquery,"['jquery', 'html']" +289681,for loop in scss with a combination of variables i have got a bunch of elements cp1 cp2 cp3 cp4 that i want to add a background colour to using scssmy code is colour1 rgb255255255 whitecolour2 rgb25500 redcolour3 rgb135206250 sky bluecolour4 rgb2552550 yellowfor i from 1 through 4 cpi backgroundcolor rgbacolouri 06 hover backgroundcolor rgbacolouri 1 cursor pointer,"['html', 'css']" +289705,circular sector shaped clipping mask with pathaddarc i need to create a clipping mask with a shape of a circular sectori am able to draw one using the followingpaintsetcolor0x88ff0paintsetstylestylefillcanvasdrawarcoval 0 30 true painti want to use it as a clipping path so i have triedpath path new pathpathaddarcoval 0 30canvasclippathpath opreplacehowever addarc does not have the usecenter parameter so what i get is not a sector but a segment,['android'] +289707,apns notifications not reaching devices enrolled in apple mdm apple mdm is usedit is mdm using apnsthe topic of mobileconfig is the same as the thing of subject of apspxpemthe character string of a device token and pushmagic reached the mdm server after the setup of mobileconfigi sent wording of a telegram for device tokens using apnsit is replacing by the character string of pushmagicalthough mdmx is sent via apns from the mdm serveriphone is not reached why is itplease let me know the cause considered,['ios'] +289727,how can i thisable the django celery admin modules i have no need to the celery modules in my django admin is there a way i could remove it,['python'] +289746,how to skip the dialog of printing in printdocumentprint and print page directly when i use myprintdocumentprint in a windows application written in c a dialog is shown for the windows processing print routine with a cancel button i do not want this dialog shown is it possibleif not which way should i use my program uses a thermal printer,"['c#', '.net']" +289766,implications of using stdvector in a dll exported function i have two dllexported classes a and b as declaration contains a function which uses a stdvector in its signature likeclass export a stdvectorb myfunctionstdvectorb const inputexport is the usual macro to put in place declspecdllexport declspecdllimport accordinglyreading about the issues related to using stl classes in a dll interface i gather in summaryusing stdvector in a dll interface would require all the clients of that dll to be compiled with the same version of the same compiler because stl containers are not binary compatible even worse depending on the use of that dll by clients conjointly with other dlls the instable dll api can break these client applications when system updates are installed eg microsoft kb packages reallydespite the above if required stdvector can be used in a dll api by exporting stdvectorb liketemplate class export stdallocatorbtemplate class export stdvectorbthough this is usually mentioned in the context when one wants to use stdvector as a member of a the following microsoft support article thiscusses how to access stdvector objects created in a dll through a pointer or reference from within the executable enusq172396 the above solution to use template class export seems to be applicable too however the drawback summarized under the first bullet point seems to remainto completely get rid of the problem one would need to wrap stdvector and change the signature of myfunction pimpl etcmy questions areis the above summary correct or do i miss here something essentialwhy does compilation of my class a not generate warning c4251 class stdvector ty needs to have dllinterface to be used by clients of i have no compiler warnings turned off and i do not get any warning on using stdvector in myfunction in exported class a with vs2005what needs to be done to correctly export myfunction in a is it viable to just export stdvectorb and bs allocator what are the implications of returning stdvector byvalue assuming a client executable which has been compiled with a different compilerversion does trouble persist when returning byvalue where the vector is copied i guess yes similarly for passing stdvector as a constant reference could access to stdvectorb which might was constructed by an executable compiled with a different compilerversion lead to trouble within myfunction i guess yes againis the last bullet point listed above really the only clean solutionmany thanks in advance for your feedback,['c++'] +289767,waiting for debugger to attach showing even when not running in debug mode my problemi ran upon an awkward problem as i was developing my application as mentioned in the title every time i install my application in run mode not debug at startup the waiting for debugger to connect message appears for 123 seconds and the application startswhat i wantwhat i would like is to be able to start the application without that message appearing it only started appearing in the last few days and i cannot remember changing anything related to debuggingwhat i have triedi have tried setting the androiddebuggablefalse but if i do this the debugger never attaches and the message never thisappearsi have also tried after installing to thisable usb debugging but still no resultseven if i kill the application and wake it up through an external source it uses googles c2d messaging framework it still tries to run in debug mode on wakeupi have developed several android applications and never stumbled upon this why wouldnt i be able to start the application in run mode is there any other way to install the application on the device without hitting the run button in eclipsei can post codesnippets from the androidmanifest or from other parts of the code if necessary but as i already mentioned i was not getting this kind of weird behavior several days ago,['android'] +289787,how to get main activity class or class name of my application how to get main activity class or class name of my applicationthanks a lot,['android'] +289797,generating links to youtube audio i have been for a while now as part of a larger project trying to find a way to stream youtube audio into an application without downloading the corresponding filewhat i have as of now is a program that downloads the video using a web service such as saveyoutubecom this however is not very efficient the downloading of the video itself takes around 5 minutes and the client may get tired of waiting and just use the youtube interface directly also say the user of the program wishes to access a 4hour long album however they want to listen only to a specific part of it for sake of explanation lets say the user wants to see the video from 2 hours onwards for example take this videothere is no doubt that my program works for this as well but it takes approximately 20 minutes for the music to start playing as downloading 2 hours of audio takes alot of time also i have used up around 400 megabytes of space on the useras computer by then sure i can store the file in a temporary folder and delete it after they close the program but that leads to more problemsif the program crashes at 1 minute before the download is complete because of lack of space who knows what the client has on their computer the client would have wasted around 20 minutes of their time for nothingsay the next time they load the program they wish to do the same thing then they have to wait another 20 minutes this could be countervented by adding a save audio button to the interface which would keep the program from deleting the file when it closes however the first impass remainsso here is my question is there a way to generate links to the audio of youtube videos is there a way to obtain a url like audioextension that way skipping to a part in the soundtrack would be easier and would not require downloading i have researched this for quite a while and so far the closest thing to an answer was saveyoutube a mp3 downloader is this even possible to do if not is there an alternative to youtube that this can be done to i have looked into the youtube api but that again is unfavorable as like most google services its api is limitedprogramming language is not a limitation as most code can be translated however a python or cc solution would be idealthanks in advanceps i have a server available for this but i would be very reluctant to download all youtube videos onto the server however if there is another solution involving a server that does not involve ripping off the entirety of youtube that would be great,['python'] +289806,extract json from text an ajax call is returning a response text that includes a json string i need toextract the json stringmodify itthen reinsert it to update the original stringi am not too worried about steps 2 and 3 but i cannot figure out how to do step 1 i was thinking about using a regular expression but i do not know how as my json might have multiple levels with nested objects or arrays,['javascript'] +289823,error when deploying using capistrano i was following the railscast on deploying to a vps and everything goes smooth till i try and run cap deploy it seems to fails when trying to find a directory here is the error message executing deploytriggering before callbacks for deploy executing deploycheck revision executing deployupdate transaction start executing deployupdate codeupdating the cached checkout on all serversexecuting locally git lsremote markprovandropwall railsgit mastercommand finished in 2531ms executing if d homedeployerappsdropwall railssharedcachedcopy then cd homedeployerappsdropwall railssharedcachedcopy git fetch q origin git fetch tags q origin git reset q hard 9407f1feb2ea5b1c4a06196bdcbb9ad8563e git clean q d x f else git clone q markprovandropwall railsgit homedeployerappsdropwall railssharedcachedcopy cd homedeployerappsdropwall railssharedcachedcopy git checkout q b deploy 9407f1feb2ea5b1c4a06196bdcbb9ad8563e fiservers 2096114261password 2096114261 executing command 2096114261 out the authenticity of host githubcom 20797227239 cannot be established rsa key fingerprint is 1627aca576282d36631b564debdfa648 are you sure you want to continue connecting yesno 2096114261 out yes warning permanently added githubcom20797227239 rsa to the list of known hostscommand finished in 2655mscopying the cached version to homedeployerappsdropwall railsreleases20120513204913 executing cp rpp homedeployerappsdropwall railssharedcachedcopy homedeployerappsdropwall railsreleases20120513204913 echo 9407f1feb2ea5b1c4a06196bdcbb9ad8563e homedeployerappsdropwall railsreleases20120513204913revisionservers 20961142612096114261 executing command out 2096114261 cp cannot create directory homedeployerappsdropwall railsreleases20120513204913 no such file or directorycommand finished in 482ms deployupdate code rolling back executing rm rf homedeployerappsdropwall railsreleases20120513204913 trueservers 20961142612096114261 executing commandcommand finished in 479msfailed sh c cp rpp homedeployerappsdropwall railssharedcachedcopy homedeployerappsdropwall railsreleases20120513204913 echo 9407f1feb2ea5b1c4a06196bdcbb9ad8563e homedeployerappsdropwall railsreleases20120513204913revision on 2096114261i have spent ages on this and cannot seem to find where i am going wrong,['ruby-on-rails'] +289840,python ioerror errno 13 permission denied im getting ioerror errno 13 permission denied i dont know what im doing wrongim trying to read a file given an absolute path meaning only fileasmand a relative path meaning fileasm and i want the program to write the fileto whatever path is given if it is absolute it should write it to the current dirotherwise to the path giventhe codecall to main functionif name main assemsysargv1import sysdef assemmyfilefrom myparser import parserimport codefrom symboltable import symboltabletablesymboltablemax size of each wordword size 16rom address to save torom addrs 0variable address to save tovar addrs 16new additionif myfile4 asm newfile myfile4hackoutput opennewfile w errorthe error givenioerror errno 13 permission denied usehackthe way i execute the code python assemblerpy usersdesktopuniversityaddasm what am i doing wrong over here,['python'] +289847,c windows service with awareness of system time i am thinking about writing a windows service that will turn a certain functionality on or off at times specified by the user using a configuration utility i will provide basically the user would specify certain times that the pc would go into workonly mode blocking facebook and other thistracting sites and then when those times are up the pc will return to normal mode i have already come up with a few ways to create the workonly mode but what i am struggling with is how to know when to go into and out of that mode i do not really want to work with threads and timers if i can avoid it since that seems like it would create an awful lot of overhead so what i am looking for would be some way to eitherhook in to the windows api if there is some kind of timechanged event to check againstuse some sort of prebuilt library for firing events at a specified timesome other method that i have not thought of that is elegant and wonderfuldoes anyone know the best way to do this,['c#'] +289860,ios apps why include both 2x and lowres images this has been bugging me for a while i do not understand why one should include lowres images if a 3gs for example cannot find the lowres image it just uses the 2x version anyway and thisplays it at it is native resolution so why add to the filesize of your app by including all the halfres images,['ios'] +289870,trying to check if a file exists in internal storage the following code is how i am trying to identify if a file exists in the internal storage mode privatepublic boolean issetstring filename fileinputstream fos null try fos openfileinputfilename fos openfileinputgetfilesdirfilename if fos null return true else return false catch filenotfoundexception e return false file filenew filemcontextgetfilesdirfilename boolean exists fosexists however it goes into the exception and does not continue with the code it does not do the return why,"['java', 'android']" +289894,what is difference between doubleparsedoublestring and doublevalueofstring i want to convert string to a double data type i do not know if i should use parsedouble or valueof methodswhat is the difference between these to methods,['java'] +289906,how to set view alpha in lower api than 11 i need to set alpha for a view it is imagebutton and on touch event i want to set alpha that i could see it was pressed maybe there some work around on this it do not suit me changing background color because my background is image and i want to change alpha of this image also i do not want to use selectors because my images are created dynamicallyfinally if there are no way to do this so how i could catch exception that it setalpha is not supported for api phone is using thanks,['android'] +289922,how do i set up my fixtures for a has and belongs to many relation i have the following modelsclass company activerecordbase has and belongs to many regionsclass region activerecordbase has many requests has and belongs to many companiesclass requestforproposals activerecordbase belongs to regionwhenever i get a new request i want to send a notification to the companies active in the same regionhow do i set this up in my fixtures so that i can unit test the logic of finding the right companiesi have triedregion ids 1 2regions one twoin companiesyml but neither works in assigning regions to the companieshere is a gist of the sql generated,"['ruby-on-rails', 'ruby']" +289927,algorithm for finding overlapping eventstimes while working on custom calendar i cannot figure out how to find time slots that overlaps any other time slottime slots start from 0 to 720 9am to 9pm with each pixel representing a minutevar events id 1 start 0 end 40 an event from 900am to 940am id 2 start 30 end 150 an event from 930am to 1130am id 3 start 20 end 180 an event from 920am to 1200am id 4 start 200 end 230 an event from 1220pm to 1230pm id 5 start 540 end 600 an event from 6pm to 7pm id 6 start 560 end 620 an event from 620pm to 720pmeach time slots is of one hour for example 9 to 10 10 to 11 11 to 12 and so onin the above example three events id 123 are overlapping for the 910 start time 900 930 and 920 and other events overlapping are int time slot of 6 to 7 id 5 6 with 6 and 620 start times the event with id 4 does not have any overlapping events in the time slot of 12 to 1i am looking for a way to get all overlapping event ids as well as number of events in a particular time slot this is expected output id1 eventcount 3 id2 eventcount 3 id3 eventcount 3 id5 eventcount 2 id6 eventcount 2for ids 1 to 3 there are 3 events for time slot 9 to 10 and 2 events for time slot 6 to 7i have created this formula to convert time number to actual timevar start time new date0 0 0 mathabseventsistart 60 9 mathabseventsistart 60tolocaletimestringvar end time new date0 0 0 mathabseventsiend 60 9 mathabseventsiend 60tolocaletimestringthis is what i have so farfunction getoverlapsevents sort events eventssortfunctionabreturn astart bstart for var i 0 l eventslength i l i cant figure out what should be next demo if you need,"['javascript', 'jquery']" +289971,streamreader and streamwriter on the same stream how do i manage closing streamreader and streamwriter which are using the same underlying streamvar stream var reader new streamreaderstreamvar writer new streamwriterstreami know that i could simply ignore closing the readerwriter and just close the underlying stream however that seems a bit of a hack since it is based on the assumption that the readerwriter does not have anything to thispose which might not be the case in the future i know this have been solved in net 45 with an extra constructor argument but until net 45 is released how do i solve it in a proper way,['c#'] +289975,button and drawable left i create button in xml file like this button androidididcall button androidlayout widthmatch parent androidlayout height0dp androidlayout margintop30dp androidbackgrounddrawablebutton androidlayout weight40 androiddrawableleftdrawablesymbol phone androidpaddingleft20dp androiddrawablepadding25dp androidtextcall androidtextcolorcolorwhite i would like to know how i can do drawableleft in activity i know that is stupid but i need do this in activity because i create button there how i can do the same what i have in xml file in my activity i need add drawableleft and drawable padding and padding left this is how i create button in activity button button1 new buttonthis button1setlayoutparamsnew relativelayoutlayoutparamsbuttonwidth buttonheight button1settextsystemtextsgetshowcallbutton button1setbackgrounddrawablenew button1settextcolorcolorparsecolorbuttontextcolor,['android'] +290006,fabricjs changes my canvas size to 300x150 after initalization html div classcanvaswrapper canvas idmycanvascanvas divcsscanvaswrapper width 900px minheight 600px mycanvas border1px solid red position absolute top22px left0px height 100 width 99 jsvar mycanvas new fabriccanvasmycanvasmy canvas get resized to 300x150 after it is been initialized why,['javascript'] +290042,c overloading with one parameter const why is following not allowed in cinclude iostreamclass sample public void methodchar x void methodchar const xvoid samplemethodchar x char y xvoid samplemethodchar const x char y xint main sample s return 0,['c++'] +290068,what is the meaning of svgsvg what is the meaning of thisappendsvgsvgi saw it in html and in d3 code does it add plugin of svg,['javascript'] +290091,overriding overflow hidden i have a parent container with a lot of child elements due to animation reasons child elements sliding in and out of the parent i have set it is overflow property to hiddenthis works great but there are a couple of the children who i do want to be visible outside the parents boundshow do i make it so that only certain children are visible outside the parents bounds,"['html', 'css']" +290095,character occurences in a string objective c how can i count the occurrence of a character in a stringexamplestring 1234567890i want to find the occurrence count of in given string,"['iphone', 'objective-c']" +290106,can i make vim do syntax highlighting on c headers that do not have extensions i have a project with a bunch of c header files that follow the standard c header naming convention that is a class called foo would be declared in a file called foo not fooh or foohh is there a good way to configure vim to do syntax highlighting for these files only a slightlylesspleasing fallback would be to enable cstyle highlighting for all files that do not have an extension i am not sure if there is any more sophisticated way to detect the type of file instead of relying solely on its extension,['c++'] +290141,how do i check if a template parameter is a power of two i want to create a structure that allocates statically an array of 2n bytes but i do not want the users of this structure to specify this size as the exponent examplemy stupid arraychar 32 a1 i want thismy stupid arraychar 5 a2 and not thishow do i check if this template parameter is a power of two and warn the user with a nice message about thisi have been able to check for this with a simple templatetemplateint nstruct is power of two enum val n 1 n n 1however i am unable to warn the user about this with a sane message any ideaseditfixed the ambiguous exampleedit1 is a power of two indeed fixed that editusing boost static assert i am getting this compile error for this code with gcctemplateint nstruct is power of two enum val n 1 n n 1 boost static assertvalerrormaincpp291 error invalid application of sizeof to incomplete type booststatic assertion failurefalse editoh i get it that was the message that i am supposed to get when the assert fails but that fails to give the user some sane message,['c++'] +290154,sync js time between multiple devices i am using the wonderful revealjs library to create a html slideshow my only problem is that i need it to synchronise across multiple devicesat the moment i am making a ajax request to the the time from the server and keep an internal clock for the pagefunction synctime set up our time object synced by the http date header fetch the page over js to get just the headers consolelogsyncing time var r new xmlhttprequest ropenhead documentlocation false rsendnull var timestring rgetresponseheaderdate systemtime new datetimestring set the time to the date sent from the serverwhilst this gets me within 1 or so seconds of accuracy i need to do better the difference is really noticeable when the slideshow is auto advancing the code is going to be running all on the same platform so crossbrowser compatibility is nothing to worry aboutheres what i have managed to put togetherany ideas,['javascript'] +290217,how to set default ruby with rvm it is defaulting to 187 which comes with mac os x i am trying to use rvm and use 193i tried rvm use default and is says bash rvm command not foundmy bashrc file has pathpathhomervmbin,['ruby-on-rails'] +290220,android widget not updating has incorrect widget id i have been working on a widget and making some advances i hope but still cannot get it to do what i wanti have a configurator activity which works ok when it closes i call the updateappwidget method in the wordwidget class and the widget updates the random numberwhat i cannot do it get the random number to change because of onclick according to the log i do enter the onreceive method but thats about itin the log i am printing the widget id i noticed that when run from the configurator activity it is printing appwidgetid33 but when i press the widget it prints appwidgetid24this is the codepublic class wordwidget extends appwidgetprovider override public void onupdatecontext context appwidgetmanager appwidgetmanager int appwidgetids this is run when a new widget is added or when the update period expires logvwotd in onupdate updating appwidgetidslength widgets logvwotd the array is appwidgetidstostring forint x 0 x appwidgetidslength x integer appwidgetid appwidgetidsx method that updates the random value updateappwidgetcontext appwidgetmanager appwidgetid override public void onreceivecontext context intent intent superonreceivecontext intent logvwotd in onreceive with intent intenttostring if intentgetactionequalsandroidappwidgetactionappwidget update integer mappwidgetid appwidgetmanager appwidgetmanager appwidgetmanagergetinstancecontext bundle extras intentgetextras ifextras null logvwotd in onreceive extras is valid mappwidgetid extrasgetintappwidgetmanagerextra appwidget id appwidgetmanagerinvalid appwidget id if they gave us an intent without a valid widget id just bail if mappwidgetid appwidgetmanagerinvalid appwidget id logvwotd in onreceive mappwidgetid is ok updateappwidgetcontext appwidgetmanager mappwidgetid else logvwotd in onreceive extras is invalid mappwidgetid appwidgetmanagerinvalid appwidget id static void updateappwidgetcontext context appwidgetmanager appwidgetmanager integer appwidgetid logvwotd in updateappwidget with appwidgetid appwidgetid setup onclick intent widgetintent new intentcontext wordwidgetclass widgetintentsetactionandroidappwidgetactionappwidget update widgetintentputextraappwidgetmanagerextra appwidget id appwidgetid pendingintent widgetpendingintent pendingintentgetbroadcastcontext 0 widgetintent 0 integer nextnumb new randomnextint100 logvwotd in updateappwidget nextnumb nextnumbtostring remoteviews remoteview new remoteviewscontextgetpackagename rlayoutwidgetlayout remoteviewsettextviewtextridmaintext stringvalueofnextnumb remoteviewsetonclickpendingintentridmaintext widgetpendingintent tell the widget manager appwidgetmanagerupdateappwidgetappwidgetid remoteview this is the log file from when i touch the widget note that the prefs activity also has a log printout and shows the widget id as a different number that this0514 171547453 vwotd1585 in onreceive with intentintent actandroidappwidgetactionappwidget update flg0x10 cmpcomrfxlabswordofthedaywidgetwordwidget bnds202177201 has extras 0514 171547453 vwotd1585 in onreceive extras is valid0514 171547463 vwotd1585 in onreceive mappwidgetid is ok0514 171547463 vwotd1585 in updateappwidget with appwidgetid240514 171547463 vwotd1585 in updateappwidget nextnumb 42so as you can see i am actually entering my updateappwidget method but for some reason the appwidgetid is incorrectany ideas why this is happening thanks a lot,['android'] +290229,how to avoid duplicate code when operating on dom in up and down direction i am writing a js webapp client user can edit listtree of text items say a todo list or notes i manipulate dom with jquery a lotuser can navigate the list up and down using keyboard similar to jk keys in gmail and perform several other operations many of these operations have mirror up down functionality egfnmoveitemup function var prev thisgetpreviousitem prev thisinsertbeforeprev there is a bit more code in here but the idea is pretty simple ie move the item up if there is a previous item in the listfnmoveitemdown function var next thisgetnextitem next thisinsertafternext now this pattern of having two almost identical functions is repeated in several places in my code because there are many operations on the listtree of items that are pretty much symmetricalquestion how do i refactor this elegantly to avoid code duplicationthe trivial way i came up with so far is to use applyfnmoveitem functiondirection var up direction up sibling up thisgetpreviousitem thisgetnextitem func up fninsertbefore fninsertafter if sibling return false funcapplythis sibling the benefit is easier maintenance when structure of other elements of the code requires changing moveupmovedown i have already needed to slightly change the code multiple times and i always need to keep in mind that i need to do it in two placesbut i am not happy with the unified version becauseimplementation is more complicated than simple moveupmovedown hence in the future it may not be so easy to maintain afterall i like simple code all these parameters ternary operations apply tricks in every function that is supposed to go up and downnot sure if it is safe to refer to jqueryfn functions explicitly after all they are supposed to be used by applying them to jquery object how do you solve those almost identical code situations when working with dom or similar structure,"['javascript', 'jquery']" +290265,enum not serializing i have a wcf serviceit is bound to an msmq but that is not the issue herei can serialize an object which has a base class and an interface implemented in the base class and the concrete class derives from the base class this works finehowever when i have an enum in the base class and i set that value then after it being deserializedread from the msmq that value is still set to the default value ie not the one set manually in codeany ideas whats going on i even marked the enum as a datacontract and also each of the enum members with an enummember attributehow can i serialize enums,['c#'] +290266,python versions on mac i am working on mac os 107 lion and i have some questionswhat is the preinstalled version of python on lioni have been working on this computer for some time now and i have installed lots of software in order to do college work many times i did not know what i was really doing the thing is now i hava on the libraryframeworkspythonframeworkversions a folder called 70 i am pretty sure there no python version 7 is this folder native or a thirdpart program installation can i delete it it is using 1 gb on thiskwhere is located the original python that comes with mac osi have choose homebrew as my package manager is there a easy way to manage python versions with it,['python'] +290267,syntaxerror nonascii character xa3 in file when function returns a say i have a functiondef newfunction return ai want to print some stuff with a pound sign in front of it and it prints an error when i try to run this program this error message is thisplayedsyntaxerror nonascii character xa3 in file blah but no encoding declaredsee for detailscan anyone inform me how i can include a pound sign in my return function i am basically using it in a class and it is within the str part that the pound sign is included,['python'] +290272,whats the best way to test an element in the dom there are a couple of ways i could do this that i am aware oftest css thisplayif foocssthisplay nonetest the visibilityif fooisvisiblein the visibility i can check if the element is thereelements are considered visible if they consume space in the document visible elements have a width or height that is greater than zeroelements with visibility hidden or opacity 0 are considered visible since they still consume space in the layoutsourcebut note that in both i cannot test the visibility by the user becausehiding an element can be done by setting the thisplay property to none or the visibility property to hidden however notice that these two methods produce different resultsvisibility hidden hides an element but it will still take up the same space as before the element will be hidden but still affect the layoutthisplay none hides an element and it will not take up any space the element will be hidden and the page will be thisplayed as if the element is not theresourceso in neither of the examples i test if the element is visible in all senses for the userso my question iswhatre the differences between the two ifs codes from abovewhats the best way to test if an element is visible to the usershould i have to use something likeif fooisvisible foocssopacity 0 foocssvisibility hidden,"['javascript', 'jquery', 'css']" +290291,how to tell if socket is open in php i am required to maintain a few sockets that i opened with php and check those sockets at regular intervals i am new to sockets in php i opened the sockets like thissocket socket createaf inet sock stream sol tcp socket connectsocket ip portsome of the sockets can get into a state where they do not return messages these sockets only receive messages how can i tell if a socket is opened if the socket does not respond to a message,['php'] +290312,specifying data type in pandas csv reader i am just getting started with pandas and i am reading in a csv file using the read csv method the difficulty i am having is preventing pandas from converting my telephone numbers to large numbers instead of keeping them as strings i defined a converter which just left the numbers alone but then they still converted to numbers when i changed my converter to prepend a z to the phone numbers then they stayed strings is there some way to keep them strings without modifying the values of the fields,['python'] +290313,remove orderby from an iqueryable i have a paging api that returns rows a user requests but only so many at one time not the entire collection the api works as designed but i do have to calculate the total number of records that are available for proper page calculations within the api i use linq2sql and i work a lot with the iqueryable before i finally make my requests when i go to get the count i call something like totalrecordcount queryablecount the resulting sql is interesting none the less but it also adds an unnecessary order by which makes the query very expensive exec sp executesql nselect count as valuefrom select top 1 null as empty from dbojournaleventsview as t0 where t0dataownerid p0 order by t0datatimestamp desc as t1np0 intp01because i am using the iqueryable i can manipulate the iqueryable prior to it making it to the sql server my question is if i already have an iqueryable with a orderby in it is it possible to remove that orderby before i call the countlike totalrecordcount queryablenoordercount if not no biggie i see many questions how to orderby but not any involving removing an orderby from the linq expressionthanks,"['c#', '.net']" +290315,javascript windowopener call parent function i am trying to call a javascript function defined in a parent from a child window i have two files like thisparenthtmlheadtitletesttitlescript typetextjavascriptfunction foo alert hello from parentfunction dostuff var w windowopentestahtmlscriptheadbodyinput typebutton valueopen onclickdostuff bodyhtmland childhtmlheadtitletest atitlescript typetextjavascriptfunction get windowopenerfooscriptheadbodyinput typebutton valuecall parent onclickget bodyhtmli can not for the life of me call the function foo from the child process i thought this should be possible with the windowopener object but i can not seem to make this work any suggestions,['javascript'] +290327,php file listing multiple file extensions here is my current codefiles globjpgthis works fine however i am wanting to list other image types such as png gif etccan i please have some help to modify this above code to get it working i have tried the following with no successfiles globjpgpnggiffiles globjpgpnggifand other variations,['php'] +290384,python numpy ln using numpy how can i do the followinglnxis it equivalent tonplogxi apologise for such a seemingly trivial question but my understanding of the difference between log and ln is that ln is logspace e,['python'] +290386,do not understand this block of codeit runs with no condition i am learning c and have not really seen this in any of the books i have read i wanted to read and comment code so i can learn better and came across a odd section of code that runs but does not have a condition from what i readand my experiences with other languages you need an if whilefor or something for blocks i am looking at the tbb threads package so i am not sure if its related to launching threads or c specificif you do not recognize this as something common in c then its probably tdd specifici think i understand what the code inside actually does but i am not sure how its being triggered or ran any ideas heres the section this is the graph part of the code graph g gcreate random dagnodes stdvectorcell root set gget root setroot set root set size root setsize for unsigned int trial0 trialtraversals trial parallelpreordertraversalroot set ps if it helps heres the entire filethe above code is in the middle of the maininclude cstdlibinclude tbbtask scheduler inithinclude tbbtick counthinclude commonutilityutilityhinclude iostreaminclude vectorinclude graphh some forward declarationsclass cellvoid parallelpreordertraversal const stdvectorcell root set test driverutilitythread number range threadstbbtask scheduler initdefault num threadsstatic unsigned nodes 10static unsigned traversals 500static bool silentflag false parse the command linestatic void parsecommandline int argc const char argv utilityparse cli arguments argcargv utilitycli argument pack h option for for thisplaying help is present implicitly positional argthreadsnofthreadsnumber of threads to use a range of the form lowhigh where low and optional high are nonnegative integers or auto for the tbb default positional argnodesnofnodesnumber of nodes in the graph positional argtraversalsnoftraversalsnumber of times to evaluate the graph reduce it eg to 100 to shorten example run timen argsilentflagsilentno output except elapsed time int main int argc const char argv try tbbtick count main start tbbtick countnow tbb counter start parsecommandlineargcargv start scheduler with given number of threads stdcout threads stdendl for int pthreadsfirst pthreadslast p tbbtick count t0 tbbtick countnow timer tbbtask scheduler init init4 creates p number of threads srand2 generates a random number between 02 size t root set size 0 this is the graph part of the code graph g gcreate random dagnodes stdvectorcell root set gget root setroot set root set size root setsize for unsigned int trial0 trialtraversals trial parallelpreordertraversalroot set tbbtick countinterval t interval tbbtick countnowt0 counter done if silentflag output the results stdcout intervalseconds seconds using p threads root set size nodes in root setn utilityreport elapsed timetbbtick countnowmain startseconds return 0 catchstdexception e stdcerr unexpected error occurred n error description ewhatstdendl return 1,['c++'] +290411,which color space the ios devices is used when i use the mac digital color meter to detect the rgb color of the screen the rgb values can be shown in srgb adobe rgb original rgbs spaces etc and they are slightly differenti want to use these values in the ios xcode platform and use uicolor class to represent them which color space should i choose in the digital color meterthanks,['ios'] +290441,difference between an output of a normal api and a rest api what is the difference between a rest api and a normal api which prints a json response,['php'] +290492,cast performance from size t to double tldr why is multiplyingcasting data in size t slow and why does this vary per platformi am having some performance issues that i do not fully understand the context is a camera frame grabber where a 128x128 uint16 t image is read and postprocessed at a rate of several 100 hz in the postprocessing i generate a histogram framehisto which is of uint32 t and has thismaxval 216 elements basically i tally all intensity values using this histogram i calculate the sum and squared sumdouble sum0 sumsquared0size t thismaxval 1 16forsize t i 0 i thismaxval i sum doublei framehistoi sumsquared doublei i framehistoiprofiling the code with profile i got the following samples percentage code 58228 321263 sum doublei framehistoi116760 644204 sumsquared doublei i framehistoior the first line takes up 32 of cpu time the second line 64i did some benchmarking and it seems to be the datatypecasting that is problematic when i change the code touint fast64 t isum0 isumsquared0foruint fast32 t i 0 i thismaxval i isum i framehistoi isumsquared i i framehistoiit runs 10x faster however this performance hit also varies per platform on the workstation a core i7 cpu 950 307ghz the code is 10x faster on my macbook81 which has a intel core i7 sandy bridge 27 ghz 2620m the code is only 2x fasternow i am wonderingwhy is the original code so slow and easily sped up why does this vary per platform so muchupdatei compiled the above code withg o3 wall cast testcc o cast testupdate2i ran the optimized codes through a profiler instruments on mac like shark and found two things1 the looping itself takes a considerable amount of time in some cases thismaxval is of type size tforsize t i 0 i thismaxval i takes 17 of my total runtimeforuint fast32 t i 0 i thismaxval i takes 35forint i 0 i thismaxval i does not show up in the profiler i assume it is less than 012 the datatypes and casting matter as followssumsquared doublei i histoi 15 with size t isumsquared doublei i histoi 36 with uint fast32 t iisumsquared i i histoi 13 with uint fast32 t i uint fast64 t isumsquaredisumsquared i i histoi 11 with int i uint fast64 t isumsquaredsurprisingly int is faster than uint fast32 tupdate4i ran some more tests with different datatypes and different compilers on one machine the results are as followsfor testd 0 2 the relevant code is forloop t i 0 i thismaxval i sumsquared doublei i histoiwith sumsquared a double and loop t size t uint fast32 t and int for tests 0 1 and 2for tests 35 the code is forloop t i 0 i thismaxval i isumsquared i i histoiwith isumsquared of type uint fast64 t and loop t again size t uint fast32 t and int for tests 3 4 and 5the compilers i used are gcc 421 gcc 447 gcc 463 and gcc 470 the timings are in percentages of total cpu time of the code so they show relative performance not absolute although the runtime was quite constant at 21s the cpu time is for both two lines because i am not quite sure if the profiler correctly separated the two lines of codegcc 421 447 463 470test 0 2185 2515 2205 2185test 1 219 2505 22 22test 2 2635 251 2195 192test 3 715 835 1855 1995test 4 1 845 735 71test 5 71 78 69 705orbased on this it seems that casting is expensive regardless of what integer type i use also it seems gcc 46 and 47 are not able to optimize loop 3 size t and uint fast64 t properly,['c'] +290591,weakhashmap example i create a weakhashmap asweakhashmapemployeestring map new weakhashmapemployeestringmapputemphellowhere emp is an employee object now if i do emp null or say emp object is no longer referenced then will the entry be removed from the weakhashmap ie will the size of map be zero and will it be viceversa in case of hashmapis my understanding of weakhashmap correct,['java'] +290600,module unsafe for safeseh image c i am using microsoft visual studio 2011 professional betai am trying to run the opencv c files that i have compiled using cmake the visual studio complierhowever when i go to debug the project i get 600 errors most of them beingerror lnk2026 module unsafe for safeseh imageapparently these files are in the opencv ffmpeg project but i could not find them i have had a look at the safeseh safe exception handlers page on the microsoft help page but i could not find any definitive answersi was wondering if anyone else has had this problem and if they managed to fix it,['c++'] +290624,sqlitedatabasequery method i am using the query method of sqlitedatabase how do i use the query method i tried thiscursor cursor sqlitedatabasequery tablename tablecolumns whereclause whereargs groupby having orderbytablecolumns columns parameter is constructed as follows string columns new stringkey id key contentif we need to get all the fields how should the column parameter to be constructed do we need to include all the field names in string arrayhow do i properly use the query method,['android'] +290682,deserialize xml element presence to bool in c i am trying to deserialize some xml from a web service into c pocos i have got this working for most of the properties i need however i need to set a bool property based on whether an element is present or not but cannot seem to see how to do thisan example xml snippetsomething testtrue somethingelse1somethingelse targetsomethingan example c claserializable xmlrootsomethingpublic class something xmlattributetest public bool test get set xmlelementsomethingelse public int else get set summary ctruec if target element is present otherwise cfalsec summary xmlelementtarget public bool target get set this is a very simplified example of the actual xml and object hierarchy i am processing but demonstrates what i am trying to achieveall the other questions i have read related to deserializing nullempty elements seem to involve using nullablet which does not do what i needdoes anyone have any ideas,['c#'] +290687,submitting a form when a checkbox is checked is there are way to submit a form when a checkbox is checkedform idformname actionphp echo serverphp self methodget input type checkbox namecbox value 33input input type checkbox namecbox value 44input input type checkbox namecbox value 55input input typesubmit namesubmit valuesearch formphp ifisset getsubmit include thisplayresultsphp that is what i have currently but i would like to submit the form without a submit button when the user checks or unchecks a checkbox any help,"['php', 'javascript']" +290728,very simple nodejs client throws error enobufs after many http requests i have the following set up a nodejs client makes endtoend requests to a nodejs server after less than a minute the client fails with error enobufs clientfunction var loadurlfunction var httprequirehttp var querystringrequirequerystring var options hostlocalhostport1337pathpostmethodpost var req httprequestoptions functionres ressetencodingutf8 var body resondata function chunk bodychunk resonend function chunk loadurl reqonerror functione consolelogproblem with request emessage var post data querystringstringifyid0 reqwritepost data reqend settimeoutloadurl10 servervar http requirehttphttpcreateserverfunction req res reswritehead200 contenttype textplain resendhello worldnlisten1337 127001while this question is similar i am posting this as a generalization of the original question i am using post rather than get with a test case,['javascript'] +290735,securing an api for use with javascript widget i am writing a javascript plugin which will be installed by bloggerswebsite owners it will communicate with my remote api i am wondering how to secure the api to ensure that only domains owned by users that have registered an account with the service can access resources from the api i have read up on oauth2 and understand the basics but because the plugin will run from within the browser and not from server to server i am not sure how secure this can betons of services like mixpanel google analytics olark use the same concept ie website owner install a line of js on their site so it must be a solved problem,['javascript'] +290744,do jquerys val and prop methods htmlescape values i cannot find anything in the documentation about val and prop and escapingare they intended to escape values when used as setters,"['jquery', 'html']" +290768,load and relative paths load is giving me trouble i am working on a section loader project and i just cannot seem to fetch the file that i need what i am trying to achievesectioncontainer is empty on document load but on document ready it is filled with pages1html this is done by a javascript file sectionsjs the js file and the indexhtml are not in the same folder here is the site structure i am running a lot of projects on my sitemain folderproject 1project 2 sectionloadertestindexhtmlpages1htmlpages2htmlcssjssectionsjsproject 3and the code i use to load pages1html on readydocumentreadyfunction sectioncontainerloadpages1html function response status xhr if status error var msg an error occurred status code errorhtmlmsg xhrstatus status text xhrstatustext i have tried every possible method that i know of and nothing seems to work here is the test casedoes anyone know what i am doing wrong,['jquery'] +290776,how do you take high resolution images using cameratakepicture i am implementing an inapp camera and every time i take a picture my image is 320x240 though my phones camera is capable of much higher resolutions galaxy nexus i could not find a parameter for setting the resolution so how do i up the resolution of images i am taking heres the relevant codeoverridepublic void surfacecreated surfaceholder holder setsurfaceholder holder overridepublic void surfacedestroyed surfaceholder holder setsurfaceholder null private void attachcameratosurface camera camera surfaceholder holder try camerasetpreviewthisplay holder setinpreview true catch ioexception e loge camerafragment exception in attachcameratosurface e overridepublic void surfacechanged surfaceholder holder int format int width int height camera camera getcamera if camera null return camerasize size getcamerapreviewsize camera cameraparameters params cameragetparameters paramssetpreviewsize sizewidth sizeheight camerasetparameters params attachcameratosurface camera holder startpreviewprivate camerasize getcamerapreviewsize camera camera cameraparameters params cameragetparameters listcamerasize supportedsizes paramsgetsupportedpreviewsizes rect frame getsurfaceholdergetsurfaceframe int width framewidth int height frameheight for camerasize size supportedsizes if sizewidth width sizeheight height return size return supportedsizesget 0 overridepublic void onclick view v switch vgetid case ridcamera action imageview getcameratakepicture getshuttercallback null new jpegpicturecallback break private class jpegpicturecallback implements picturecallback override public void onpicturetaken byte data camera camera bitmap bitmap null try bitmap bitmapfactorydecodebytearray data 0 datalength catch outofmemoryerror e loge camerafragment out of memory decoding image from camera e return data null if bitmap null new savepictureworker getactivity execute bitmap startpreview,['android'] +290779,remove an attribute from a backbonejs model is there a way to remove an attribute from a backbone modelreason being is i pass up extra data on save to perform certain actions but then that data gets automatically added to my modelthe documentation says to not edit the modelattributes directly so the only other method i see to do this would be to use the set method and set the attribute to null but that is not idealvar mymodel new modelmymodelsavenameholla specialattrplease remove memymodelsettempattrnullifmymodelattributesspecialattr null alertmodel does not have a specialattri have also tried removing it from the attributes property but it does not really remove it,['javascript'] +290797,how to get class name only not full path i am aware that using context and a method getclassgetname i can get a string which represent full class name like compackage1package2mainactivity how can i get only the last part class name only in this case it would be mainactivity string i can do it with a simple split method but maybe there is a better way more reliable,['android'] +290805,android canvas drawtext yposition of text i am using a canvas to create a drawable with some background and some text the drawable is used as a compound drawable inside an edittextthe text is drawn via drawtext on the canvas but i do have an issue with the yposition of the drawn text in some cases in those cases parts of some characters are cut off see image linkscharacters without positioning issue characters with positioning issue text contains g j q etcyou can find a code snippet to reproduce the issue below does any expert know how to determine the proper offset for the y positionpublic void writetestbitmapstring text string filename font size float fontsize new edittextthisgetcontextgettextsize fontsizefontsize02f paint to write text with paint paint new paint paintsetstylestylefill paintsetcolorcolordkgray paintsetantialiastrue paintsettypefacetypefaceserif paintsettextsizeintfontsize min rect of text rect textbounds new rect paintgettextboundstext 0 textlength textbounds create bitmap for text bitmap bm bitmapcreatebitmaptextboundswidth textboundsheight bitmapconfigargb 8 canvas canvas canvas new canvasbm canvasdrawargb255 0 255 0 for visualization y canvasdrawtexttext 0 textboundsheight paint try fileoutputstream out new fileoutputstreamfilename bmcompressbitmapcompressformatjpeg 100 out catch exception e eprintstacktrace,['android'] +290822,should getsystemservice result be cached the documentation of getsystemservice advises to not share the service objects between various different contextsfor a single context is it preferable to cache the service object by assigning it to a instance field in oncreate or it should be obtained at the time of use what is the idiomatic usage,['android'] +290834,requirejs text plugin adds js to the file name i am trying to work with requirejs and text plugin and i have weird problemi have two web serverslocalhost30 act as cdn and has all the static files js images css and templateslocalhost3001 server act as rest server and serve only one file the mainhtml filethe mainhtml file loads all the js files from the second server using the following linescript datamainhttplocalhost30jsmain srchttplocalhost30librequirejqueryjsscriptfor some reason when using the requirejs text plugin he adds to the templates js suffix when navigating to localhost3001i am using the following syntaxdefine jquerybackboneunderscoremodelsmodeltexttemplatesmainhtml viewsnavigation viewsplayer viewscontent viewsheaderwhen i navigate to localhost30 it works finecan you think of any reason that the text plugin would have problems serving text files from a remote server for example cdn server,['javascript'] +290845,what does this usage of apply means in javascript please can someone tell me what does thisinitapplythis arguments do in the code belowi understand what apply does in general but in the context of the code below what is it doing in therevar class function var klass function thisinitapplythis arguments i do not really get this bit klassprototypeinit function return klassvar person new classusagevar someone new personi see a lot of people using it i have got an idea of what it does but cannot really put my hands on it so i need more lighti am going up an extra level in js so i wanna know everything about it not just the simple hello world levelmany thanks,"['javascript', 'jquery']" +290852,how should i copy strings in java string s hello string backup of s s s byeat this point the backup variable still contains the original value hello this is because of strings immutability rightbut is it really safe to copy strings with this method which is of course not safe to copy regular mutable objects or is better to write this string s hello string backup of s new strings s byein other words whats the difference if any between these two snippetsedit the reason why the first snippet is safelet me just explain things with a little more detail based on the good answers already provided which were essentially focused on the question of difference of performance between the 2 snippetsstrings are immutable in java which means that a string object cannot be modified after its constructionhencestring s hello creates a new string instance and assigns its address to s s being a reference to the instanceobjectstring backup of s s creates a new variable backup of s and initializes it so that it references the object currently referenced by snote string immutability guarantees that this object will not be modified our backup is safenote 2 java garbage collection mechanism guarantees that this object will not be destroyed as long as it is referenced by at least one variable backup of s in this casefinally s bye creates another string instance because of immutability it is the only way and modifies the s variable so that it now references the new object,['java'] +290946,jquery keyup keydown keypress do not detect browser autofill i am using these events to try to evaluate form input but if the form is autofilled by the browser these events do not fire how can i make the event fire on autofill as well,['jquery'] +290953,how to set value of input text using jquery i have an input text which is thisdiv classeditorlabel htmllabelformodel modelemployeeid employee numberdivdiv classeditorfield textboxemployeenumber htmleditorformodel modelemployeeid htmlvalidationmessageformodel modelemployeeiddivi want to set the value of this input text using jquery so i did thisscript typetextjavascript languagejavascript function textboxemployeenumbervalfgg script however it is not working what is the error in my syntax,"['javascript', 'jquery', 'html']" +290956,unbalanced parenthesis using attribute in g today i tried clang on a project i have developed some time ago i was suprised when it encountered a compilation error since i had compiled my project successfully using g this short snippet reproduces the line where the error was encounteredint main attribute aligned16 char arr5which produces this errortestcpp232 error expected attribute aligned16 char arr5 as you can see there is an umbalanced parenthesis there are three and two this clearly looks like it should actually produce a compilation erroris this a valid usage of this keyword i cannot seem to find anything on the documentation that indicates it is i am using g 452 and clang 28note that this error is detected when using gcc instead of g,"['c++', 'c']" +290989,get rid of space underneath inlineblock image how do i get rid of the space between the bottom of the image and the wrapper while keeping the image as inlineblock why is this happeninghtml div idwrapperimg src images1735360254icon reasonably smalljpg divcss awrapper backgroundgreenimg thisplayinlineblock margin0a,"['html', 'css']" +291008,unable to access an error message corresponding to your field name i have a callback function that check captcha which sees if row is 0 or 1 this information is queried from sql the problem is that i can not call it from selfform validationset rulecaptcha call back check captcha due to the fact that my function takes in a row var the way i am calling it now i get a unable to access error message how can i make this workfunction check captcha row ifrow 0didnt find any thisform validationset messagecaptcha text dont match captcha return false else return true function create member past time 7200 thisdbquerydelete from captcha where captcha time past sql select count as count from captcha where word and ip address binds array postcaptcha thisinputip address past query thisdbquerysql binds row queryrow row query rows if it found an entry 1 selfcheck captcharowcount validations thisform validationset rulesfirst name first name trimrequired thisform validationset ruleslast name last name trimrequired thisform validationset rules email address email address trimrequiredvalid emailuniqueuseremail address thisform validationset rulesusername username trimrequiredmin length4uniqueuserusername thisform validationset rulespassword password trimrequiredmin length4max leng32 thisform validationset rulespassword2 password confirmationtrimrequiredmatchespassword if postcaptcha thisform validationset rulescaptcha captchatrimrequiredelse thisform validationset rulescaptcha captcha callback check captcha ifthisform validationrunfalse this to the curr objusercontroller registraion points to the the function in controller thisregistration reloads reg page so they can fill out right stuff else,['php'] +291024,undefined index error php i am new in php and i am getting this errornotice undefined index productid in varwtestmodifyformphp on line 32notice undefined index name in varwtestmodifyformphp on line 33notice undefined index price in varwtestmodifyformphp on line 34notice undefined index description in varwtestmodifyformphp on line 35i could not find any solution online so maybe someone can help mehere is the codeform actionphp echo serverphp self methodpost input typehidden namerowid valuephp echo rowid p product idbr input typetext nameproductid size8 maxlength8 valuephp echo productid p p namebr input typetext namename size25 maxlength25 valuephp echo name p p pricebr input typetext nameprice size6 maxlength6 valuephp echo price p p descriptionbr textarea namedescription rows5 cols30 php echo descriptiontextarea p p input typesubmit namesubmit valuesubmit p form php if isset postsubmit rowid postrowid productid postproductid this is line 32 and so on name postname price postprice description postdescriptionwhat i do after that or at least i am trying is to update a table in mysqli really cannot understand why rowid is defined while the other variables are notthank you for taking your time to answer mecheers,['php'] +291079,select data from a csv before loading it with javascript d3 library i want to select some data out of a csv file before i load it with javascript with the d3 librarythis is how i load the csvd3csvdatacsv functioncsv visdatumcsvcallchart and this is a sample of the csv fileclassagesexsurvivedfirst classadultmalesurvivedfirst classadultmalesurvivedfirst classadultmalesurvivedfirst classadultmalesurvivedfirst classadultmalesurvivedfirst classadultfemalesurvivedfirst classadultfemalesurvivedfirst classadultfemalesurvivedsecond classadultmaleperishedsecond classadultmaleperishedsecond classadultmaleperishedthird classadultmalesurvivedthird classadultmalesurvivedthird classadultmalesurvivedthird classadultmalesurvivedthird classadultmaleperishedthird classadultmaleperishedcrewadultmaleperishedcrewadultmaleperishedcrewadultfemalesurvivedcrewadultfemalesurvivedfor example i want only to select the second class and first class rows before i load it with d3csv i know i can just delete the other rows in the csv but i want to make a function so that the user can select what categories he want to use i hope that makes some sense,['javascript'] +291100,matplotlib add strings as custom xticks but also keep existing numeric tick labels alternatives to matplotlibpyplotannotate i am trying to produce a graph and i am having some issues annotating it my graph has a log scale on the xaxis showing time what i want to be able to do is keep the existing but not predictable numeric tick labels at 100 units 10 units 10 units etc but also add custom tick labels to the xaxis that make it clear where more human readable time intervals occurfor instance i want to be able to label one week one month 6 months etc i can use matplotlibpyplotannotate to mark the points but it does not really do what i want i do not really want text and arrows on top of my graph i just want to add a few extra custom tick marks any ideas,['python'] +291108,perl equivalent to php foreach loop i am looking for a perl equivalent to the following php code foreacharray as key valuei know i can do a foreach loop like soforeach my array value arraywhich will enable me to do things with the array values but i would like to use the keys as welli know there is a perl hash which allows you to set up keyvalue pairs but i just want the index number that the array automatically gives you,['php'] +291114,how to make ios app name localizable i am trying to find the easiest way to localize my app i am using sqlite so i need basically only to switch my database name problem is the app name can it be localized from code or i have to make x apps for x languages so anyone will have app name in hishers native language the latter one seems like already rejected app to me anyone,"['iphone', 'ios']" +291130,how to measure execution time of javascript code with callbacks i have a piece of javascript code that i am executing using the nodejs interpreterforvar i 1 i limit i dbuserssaveid i name mongouser i functionerr saved if err saved consolelogerror else consolelogsaved i want to know how to measure the time taken by these db insert operations i could compute the difference of date values after and before this piece of code but that would be incorrect because of the asynchronous nature of the code,['javascript'] +291170,how do i force compilation of aspnet mvc views i have a windows azure web role that contains a web site using aspnet mvc when an http request arrives and a page is first loaded the view aspx or cshtml is compiled and that takes some time and so the first time a page is served it takes notable longer than later serving the same pagei have enabled mvcbuildviews described in this answer to enforce compiletime validation of views but that does not seem to have any effect on their compilation when the site is deployed and runningazure web roles have socalled startup tasks and also a special onstart method where i can place whatever warmup code so once i know what to do adding that into the role is not a problemis there a way to force compilation of all views,"['asp.net', '.net']" +291205,constrained optimization for nonlinear multivariable function in java i am looking for an open source implementation of a method doing constrained optimization for nonlinear multivariable function in java,['java'] +291220,can stdasync be use with template functions is stdasync supose to work with template function i have tried to lauch stdreverse as an asynchronous task bu got compiletime errori have tried to use simpler functions foo and bar and thiscover that only the nontemplatefunction are workinginclude algorithminclude futureinclude stringvoid foostdstringiterator first stdstringiterator lasttemplateclass bidirectionaliteratorvoid barbidirectionaliterator first bidirectionaliterator lastint main stdstring str lorem ipsum dolor sit amet auto result reverse stdasyncstdreverse strbegin strend compiletime error auto result foo stdasyncfoo strbegin strend auto result bar stdasyncbar strbegin strend compiletime error result reverseget result fooget result bargetthe compiler error is as followmaincpp in function aint mainamaincpp1871 erreur no matching function for call to aasyncunresolved overloaded function type stdbasic stringchariterator stdbasic stringchariteratoramaincpp1871 note candidates areusrincludec46future135 note templateclass fn class args stdfuturetypename stdresult of functor argtypes type stdasyncstdlaunch fn args usrincludec46future13785 note templateclass fn class args typename std async sfinae helpertypename stddecay functortype fn args type stdasync fn args maincpp1871 erreur unable to deduce aautoa from aexpression erroramaincpp2062 erreur no matching function for call to aasyncunresolved overloaded function type stdbasic stringchariterator stdbasic stringchariteratoramaincpp2062 note candidates areusrincludec46future135 note templateclass fn class args stdfuturetypename stdresult of functor argtypes type stdasyncstdlaunch fn args usrincludec46future13785 note templateclass fn class args typename std async sfinae helpertypename stddecay functortype fn args type stdasync fn args maincpp2062 erreur unable to deduce aautoa from aexpression errorahowever it pass when i manually specify the template instanciation such as stdasyncstdreversestdstringiterator strbegin strendis this a compiler bug gcc 463 or a well defined behaviour,['c++'] +291236,why volatile in java 5 does not synchronize cached copies of variables with main memory according tounder the new memory model when thread a writes to a volatile variable v and thread b reads from v any variable values that were visible to a at the time that v was written are guaranteed now to be visible to band many places on the internet state that the following code should never print errorpublic class test volatile static private int a static private int b public static void mainstring args throws exception for int i 0 i 100 i new thread override public void run int tt b makes the jvm cache the value of b while a0 if b 0 systemoutprintlnerror start b 1 a 1 b should be 1 for all the threads when a is 1however i sometimes get error printed how is this possible,['java'] +291257,sass 32 media queries and internet explorer support i recently implemented this technique with sass 32 using content blocks on a project i have been working on and i have just gotten to the point where i need to include support for older browsers such as ie7 and 8exampleoverview padding 0 0 19px include respondtomediumscreens paddingtop 19px mediumscreens include respondtowidescreens paddingtop 19px mediumscreensthey both do not support media queries and i have often handled this in the past by serving up all styles to these browsers when i had my media queries separated into separate partial files such as 320scss 480scss and in my ie stylesheet loading them like soimport 320scssimport 480scssetcwhich would load all styles and always assign ie7 8 a 940px or whatever the max width is layout and styles by nesting styles in sass 32 inline like this it eliminates the need for separate partial stylesheets but totally screws up how i load styles for ieany ideas or solutions on how to combat this i could use a polyfill such as respondjs to force ie to use media queries but would prefer to just serve up a nonflexible site to ieany ideas on either how to best organize these files or a better solution,['css'] +291284,how do you query an int column for any value how can you query a column for any value in that column ie how do i build a dynamic where clause that can either filter the value or noti want to be able to query for either a specific value or not for instance i might want the value to be 1 but i might want it to be any numberis there a way to use a wild card like to match any value so that it can be dynamically inserted where i want no filterfor instanceselect int col from table where int col 1 query for a specific valueselect int col from table where int col query for any valuethe reason why i do not want to use 2 separate sql statements is because i am using this as a sql data source which can only have 1 select statement,['sql'] +291291,how do big sites do a maintenance notice page i am about to upgrade my whole site i am looking for advices on how tech startups do their maintenance processi am thinking of using htaccess however that only redirect users accessing for example indexphp to maintenancephp right if user access dashboardphp there will be no redirectionduring the maintenance i do need to access indexphp only me anyone who worked in tech startups care to share their solution appreciated it alot,['php'] +291319,is there a fully implemented rest javascript client i have been experimenting with and researching javascript clients for restful web services just about everything i have seen seems to be limited to the recreating model definitions in the client and doing crud on simple nonrelated modelswhat i am looking forability to dynamically create models andor proxies andor stores in the client given a uri to the jsonrest schema provided by the server apiability to handle relations natively that is without creating a bunch of custom functions or overriding much builtin functionality i am talking about 1n 11 n1 and nm relationsability to work relatively well with a full feature client framework like extjs or dojowhat i have triedextjs 41 great widget set able to do completely programmatic layout ajaxrest proxies work outofthebox for simple models no irc or dev community that i can find limited responsiveness on gpl forums dojo current needs custom overriding to jsonreststore to function with basic models great widgets difficuly to completely avoid htmli have also looked at various jquery based tools and a little at backbonejs is down at the moment the jquery stuff seems utterly thisjointed to me if there are good jquery rest tools i am open to them i just need pointers to documentation on how to develop coherent and manageable apps with thembasic goaldeveloping web client apps that are maintainable over time and are dry that is there is as little copypasting of param1 asdf param2 30 throughout related classes ideally if it is defined on the server the client should get it from the rest api if it is defined in the client other parts of the client should be able to inheritextend that definitionanother way of saying itmost js frameworks follow the mvc pattern which to me is silly since my m is already on the server along with some of the c i want my client to be a vc to only recreate as much of the serverside model as is necessary for asynchronous operation focusing on ui presentation and user actions which means that ideally none of the m in mvc will be hard coded into the clientis there a full featured javascript rest client that someone can point me towards thanks,['javascript'] +291323,how can i thisable model compatibility checking in entity framework 43 i am working with ef 43 and have a context which needs to talk to a database which was generated by another library using ef code first 43 the context is throwing an exception stating the model backing the context context has changed since the database was created consider using code first migrations to update the databasein ef 41 this could be diabled by removing the includemetadataconvention from the modelbuilder however in 43 this convention has been deprecated and no longer has an effecthow can i have an ef 43 context talk to an ef 43generated database built by a different context the only option i have found which is far from ideal is to delete the metadata table thereby causing both contexts to assume the database was not build by efps i know this scenario is likely to raise questions about why i need to do this i know it is far from ideal but rest assured it is a problem i need to solve and have limited options to work with laterally,"['c#', '.net']" +291330,how do you call multiple files from command line into your applicaiton i am adding a context menu item to the windows registry so when i click on a file i can call my application and have that file be set to my application as an arg but how can i do this with to have multiple files be send to my application all the files i have selectedright now i have the command asctestdll 1but this seems to call in each file separately whats the command to throw in all the files that i have selected,['c#'] +291381,most suitable python library for github api v3 i am looking for a python library for the github apiv3 suitable for me background i am a python noob with a background primarily rooted in matlab and c and have recently learned to use pythonmatplotlibi found one library pythongithub3 mentioned in the gh api docs after playing around with it in ipython for an hour or two i found it really unintuitive to explorework with i looked some more and found there is quite a number of people at least attempting to write such a library the more promisinglooking at a glance are pygithub and another pythongithub3 which apparently is different from the first onebefore i spend the next days consecutively trying out library after library i wanted to ask the so community if there is an accepted definitive obvious choice for that librarywhat i did not like about the first library was the to me unintuitive way to get at data some things you get as attributes some you get as return value of a method that return value is some complicated object which has to be paged and iterated through etc in that regard pygithub looks more attractive at first glance clearly drill down through an object hierarchy and then arrive at the attribute containing what you wantfor repo in gget userget repos print reponameso any pearls of wisdom to share i know i do not have skills enough to quickly judge library quality which is why i am turning to the so communityedit fwiw i ended up using pygithub it works well and the author is really receptive for feedback and bug reports,['python'] +291382,native ios facebook sso would not return to app ok this may seem like a duplicate but i have been through all of the questions that center around the issue and i still cannot seem to get this to work for my appi have followed the ios tutorial on the facebook developer site and i have done the followingcreated a facebook app to get the facebook app idi have assigned this app id to a constant and i use it to initialize the facebook object within my appi have made sure my app is flagged for multitaskingi have setup the fbapp id in the plist under the urls drop downi have made my appdelegate a fbsessiondelegate and implemented very simple fbdidlogin and fbdidnotlogin delegate methodsversions xcode 432 on lion ios 51 facebook ios 411all of this and i still cannot seem to get facebook to return control back to my app when it authorizes it just stays in facebook insteadcode note fb app id changed to basic number for viewing hereappdelegatehimport uikituikithimport fbconnecthdefine fb app id 1234567890interface appdelegate uiresponder uiapplicationdelegate fbsessiondelegateproperty strong nonatomic uiwindow windowproperty nonatomic strong facebook facebookendappdelegatemimport appdelegatehimplementation appdelegatesynthesize window windowsynthesize facebook facebook boolapplicationuiapplication application didfinishlaunchingwithoptionsnsdictionary launchoptions facebook facebook alloc initwithappidfb app id anddelegateself if facebook issessionvalid facebook authorizenil boolapplicationuiapplicationapplication handleopenurlnsurl url return facebook handleopenurlurl boolapplicationuiapplication application openurlnsurl url sourceapplicationnsstring sourceapplication annotationidannotation return facebook handleopenurlurl voidfbdidlogin nslogapp logged in voidfbdidnotloginboolcancelled nslogapp did not loginendrelevant infoplist porton facebook app screen mostly pinked out note i tried it with only basic settings and also with the ios native app settings with a fake itunes store id but the same bundle id from my provisioning profileno matter what i do it always loads up facebook and asks to authorize my app and then it simply closes the auth screen window and sits there on my facebook screen instead of returning to my app also note i know it will always ask because i am not checking for the auth token and expiration datethat is the next stepfor now i want to at least get it to return to my app before i worry about thathave i missed something here anything else i can try to get facebook to return to my appedit also when debugging i cannot seem to find any spot where either openurl is called for some reason edit 2 when running it on the simulator it loads up the fb dialog via safari as expected and then when i authorize safari throws an error as if the url they are trying to use to get back to my app is invalidthis still does not tell me much since my fb1234567890 is setup right as far as i know in the infoplist,"['objective-c', 'ios']" +291383,how do i pass tuples elements to a function as arguments in python i have a list consisting of tuples i want to pass each tuples elements to a function as argumentsmylist a b c d e fmyfunca bmyfuncc dmyfunce fhow do i do itbest regards,['python'] +291392,encoding apostrophe with jsonnet say i have a class likepublic class mytestclass public mytestclass testing check out public string testing get set and javascriptserializerjsonnet serializers like public ihtmlstring tojsonnetobject value return new mvchtmlstringjsonconvertserializeobjectvaluepublic ihtmlstring tojsonobject value var json new javascriptserializer return new mvchtmlstringjsonserializevaluethen in a view i have serializerstojsonnetnew mytestclass serializerstojsonnew mytestclassthe jsonnet will return testingcheck out while the javascriptserializer will return testingcheck u0027 out i wish to create a javascript object likevar model parsejsonjsonstringbut this only works if the apostrophe is encoded otherwise the apostrophe makes my javacript look likevar model parsejsontestingcheck outwhich fails because the inserted apostrophe makes parsejson escape my string too earlyjavascriptserializer encodes the apostrophe as u0027 by default while jsonnet which i want to use does not how can i change jsonnet to do this is there a setting i am missing is there a different way i can parse my json string into javascript where the apostrophe is ok,['jquery'] +291424,knockoutjs deferred databinding for modal i am using knockoutjs to thisplay a list of employees i have a single hidden modal markup on the page when the details button for a single employees is clicked i want to databind that employee to the modal popup i am using the koapplybindingsemployee element but the problem is when the page loads it is expecting the modal to start off as bound to something so i am wondering is there a trickstrategy to do a latedeferred databinding i looked into virtual bindings but the documentation was not helpful enoughthanks,['javascript'] +291445,setretaininstance fragment with ui android ok i created a fragment with some ui couple textboxes and stuff and i used setretaininstance since im running an asynctask to query a server request can only be sent once and i need the result of the asynctask so my question isis it wrong to retain the whole fragment with the ui i saw couple examples where people use an extra fragment to use the setretaininstance but is there anything wrong not using that extra oneif there is an issue with using the setretaininstance why is that could not find any info in the documentation regarding this,['android'] +291449,does the best practice of programming to interfaces apply to local variables i have been told that programming to interfaces for local variables is useless and should not be done as it only hurts performance and offers no benefit public void foo arraylistinteger numbers new arraylistinteger do listy stuff with numbersinstead ofpublic void foo listinteger numbers new arraylistinteger do listy stuff with numbersi feel like the performance hit is negligible but admittedly there is not much to gain by using list semantics of arraylist are there strong reasons to go one way or the other,['java'] +291470,eclipse plugin to view image while debugging is there an eclipse plugin that will let me view an image variable while i am paused at a breakpoint eg i would like to see the image when inspecting a bufferedimage object instead of seeing it is tostring value,['java'] +291472,get full mysql query string on insert or update need help with mysql as it is not really my forte so any help is appreciatedi have issues on my site where update or insert were done with missing values this caused some issues on other functions on the site but i am not able to find where the update or insert were done in any of the classesis there any way maybe a mysql trigger that i could add to these tables that would allow me to store the original or full query of the update or insert i have tried logging but that applies to the whole database and it takes up too much thiskspacethanks in advance for any repliesps at the moment the php classes are a bit messy as were still in the development stage so adding exceptions to the updates or inserts functions will take too much time so please focus the answer to the question thanks again,['mysql'] +291479,using rails tagged logging how can i log the log level of a message my rails logger configuration currently logs the current time and uuid like thisconfiglogger activesupporttaggedloggingnewloggernewrailsrootlogenvrails envlog dailyconfiglog tags procnew timenowstrftimeymd hmsl uuidis there a way to also log the current messages log level ie if i call loggerdebug the tag debug is added to the message,['ruby-on-rails'] +291487,successive calls to uiviewcontrollers presentviewcontroller method i recently encountered a hairpulling situation in my ios app where i was trying to successively thismiss one presented uiviewcontroller from my windows rootviewcontroller usingrootviewcontroller thismissviewcontrolleranimatedyes completionnulland present another one shortly thereafter in another method incidentally withuiviewcontroller vc2 myviewcontroller2 alloc initwithnibnamenil bundlenil autoreleaserootviewcontroller presentviewcontrollervc2 animatedyes completionnullproblem was i could never get the second view controller to show up turns out as near as i can tell thismissviewcontrolleranimatedcompletion needs that asynchronous block of completion time to pass before presentviewcontrolleranimatedcompletion will work properly again this fact is not directly documented in apples docs from what i can tellthe solution i came up with was to wrap the thismissal with a method that specifies the selector you would want to call afterwards like so voidthismissviewcontrolleruiviewcontroller presentingcontroller postactionselpostthismissalaction presentingcontroller thismissviewcontrolleranimatedyes completion self performselectoronmainthreadpostthismissalaction withobjectnil waituntildoneno and then i would callself thismissviewcontrollerselfwindowrootviewcontroller postactionselectormethodfornextmodalpresentationanyway i wanted to post as i looked around and had not seen anyone with this particular problem so i thought it might be useful for people to understand and also i wanted to verify that i am not hacking a solution that has a better design pattern for resolution,['ios'] +291491,iphone background app to update the screen when a phone call is received we are in the process of writing an iphone app that will be in the background that would be notified when an incoming phone call comes the app does some background work going to a server retrieving some data while the phone session is ongoing and then notifies the user after searching i found that i can use the private telephony headersframework to actually know who is calling in my app however i am unable to update the dialer screen with information retrieved from server also i found that the application has to be running when the phone call arrives yak i know that this would not approved in the apple store however i am looking for 2 thingshow do i put this app in the backgroundhow do i show some information while the call is going on local notification is fine but it has to show immediatelyeven if we have to jailbreak i would like to know how to get this done this app is for law enforcement officials proof of concept,"['iphone', 'ios']" +291534,carrierwave exconerrorsmovedpermanently in registrationscontrollerupdate error ive been trying to get carrierwave to work with amazon s3 instead of storage s3i have storage fogchanging it to storage s3 gives an immediate error carrierwave cant convert nil into string typeerror when using s3so i changed it to storage fog like the rdoc below sayshowever when i try to upload an image i get this crazy error im using the devise gem as wellmy full stack trace isexconerrorsmovedpermanently in registrationscontrollerupdateexconerrorsmovedpermanently expected200 actual301 moved permanently request connect timeout60 headerscontentlength95472 contenttypeimagejpeg xamzaclprivate cachecontrolmaxage3155760 datethu 17 may 2012 052855 0 authorizationaws akiain6sc3ysgbsukv4qkzog9mg01jyn48imfmybgxaaqrk hostusera7s3euwest1amazonawscom443 instrumentor nameexcon mockfalse read timeout60 retry limit4 ssl ca fileuserssasharvmgemsruby193p125gemsexcon0134datacacertpem ssl verify peertrue write timeout60 hostusera7s3euwest1amazonawscom pathuploads2fuser2fimage2f592fideajpg port443 querynil schemehttps bodyfileuserssashadesktoprails projectsblue eyespublicuploadstmp2012051628191609893ideajpg expects200 idempotenttrue methodput response exconresponse0x007fd72a146820 bodyxml version10 encodingutf8nerrorcodepermanentredirectcodemessagethe bucket you are attempting to access must be addressed using the specified endpoint please send all future requests to this endpointmessagerequestidf5f5af8e837622requestidbucketusera7buckethostidishk3githzcqyslokxnrijjihmmuutxbopfxqm4ucvjgkehfmfn43ll4owmpt82hostidendpoints3amazonawscomendpointerror headersxamzrequestidf5f5af8e837622 xamzid2ishk3githzcqyslokxnrijjihmmuutxbopfxqm4ucvjgkehfmfn43ll4owmpt82 contenttypeapplicationxml transferencodingchunked datethu 17 may 2012 052900 gmt connectionclose serveramazons3 status301 appcontrollersregistrations controllerrb30in updatei dont know what that even meansin my initializerscarrierwaverb i havecarrierwaveconfigure do config configfog credentials provider aws required aws access key id somekey required aws secret access key secretkey required region euwest1 optional defaults to useast1 configfog directory bucketname required configfog host optional defaults to nil configfog public false optional defaults to true configfog attributes cachecontrolmaxage3155760 optional defaults to endand my uploader file has storage s3 storage fog def store dir uploadsmodelclassto sunderscoremounted asmodelid endmy gem file hasgem carrierwavegem thingem fogwhen i boot my server instead of webrick it uses thin in development as wellare my configurations wronghelp would be much appreciatedive been super stuck on this carrierwaves3 issue,['ruby-on-rails'] +291561,gson not calling my typeadapter for a type which is an interface gson appears to be doing some kind of trick where it looks at the internal fields of my javabeans instead of using the publicallyaccessible property information unfortunately this would not fly for us because our magicallycreated beans are full of private fields which i do not want it to store offtestpublic void testjson throws exception player player new magicplayer beanutilscreatedefaultplayerclass playersetnamealice gson gson new gsonbuilder registertypeadapterplayerclass new playertypeadapter create systemoutprintlngsontojsonbeanprivate static class playertypeadapter implements jsonserializerplayer override public jsonelement serializeplayer player type type jsonserializationcontext context throw new runtimeexceptioni got called woohoo public static interface player extends supportspropertychanges public string getname public void setnamestring name simple implementation simulating what were doingpublic static class magicplayer implements player private final string privatestuff secret private string name override public string getname return name override public void setnamestring name thisname name this givesprivatestuffsecretnamealiceand of course never calls my type adapter which seemingly makes it impossible to get any other behaviour,['java'] +291618,how to make button non transparent i wrote custom view which draws a circle then i put it on relative layout also i put standard button there so that they overlap and i see that button is transparent how to make it non transparent,['android'] +291659,how can i view a video inside a videoview at some specific position i am currently trying to implement a videoview that will show a video on a specific position i can show a fullscreen video with no problem however whenever i try to show that video inside a frame a little rectangle for example i can only show a part of video in that view i could not fit the video into that viewi already look for lots of links about scaling a video in android however i couldnt find any way to do this any help about that issue will be helpfulwhat i am using is i have 2 different classes one of them is my video activity class and other one is a helper classpublic class videoviewcustom extends videoview private int mforceheight 0 private int mforcewidth 0 public videoviewcustomcontext context supercontext public videoviewcustomcontext context attributeset attrs thiscontext attrs 0 public videoviewcustomcontext context attributeset attrs int defstyle supercontext attrs defstyle public void setdimensionsint w int h thismforceheight h thismforcewidth w override protected void onmeasureint widthmeasurespec int heightmeasurespec superonmeasurewidthmeasurespec heightmeasurespec setmeasureddimensionmforcewidth mforceheight that class help me to set dimensions of videoview correctly however i couldnt make video fit into that region i mean i could not scale the video to fit into that region i dont know whether or not android is autoscaling into given dimensions but i couldnt do it,['android'] +291661,cocos2dx how to read plist into an array i want to read a plist using cocos2dx chere is my plist array dict keyxkey integer0integer keyykey integer0integer dict dict keyxkey integer140integer keyykey integer12integer dict dict keyxkey integer120integer keyykey integer280integer dict dict keyxkey integer40integer keyykey integer364integer dictarrayit is basically an array of dictionary that consist of x y coordinates my original code for reading is nsstring path nsbundle mainbundle pathforresourcensstring stringwithformatwi world oftypeplistnsmutablearray points nsmutablearray arraywithcontentsoffilepathbut now i need to translate it into cocos2dx in c i have googled some article but they are all about reading plist into dictionary i need an array editnow i have changed my plist formatdict key11xkey integer0integer key11ykey integer0integer key12xkey integer140integer key12ykey integer12integerdictwhat should i do i still get the same error ccdictionarystdstring ccobject dict ccfileutilsdictionarywithcontentsoffileplistpathint x intdictobjectforkey11xint y intdictobjectforkey11ywould not work please try it out first see if you can read a int from the sample plist,"['iphone', 'ios']" +291664,how to set spinner default by its value instead of postion i have 150 records in the database i am fetching those data using cursor and set those values to spinner using simple cursor adapter now what i need is i want to set one value say 39th value as default but not by its position i want to set by its valuei know how to set the spinner default by its position spinnersetselection39 will set the spinner to that valuebut i did not have any idea about setting the spinner default by its valuetext in the databasei know the values in the database for eg books is one of the value in the spinner i need to set the spinner default as booksis there any possible way to do thisthanks for you help guys,['android'] +291705,find all the numbers in the range a b that are not in the given stdset s let a and b be integers a b given an stdsetint s what is an efficient and elegant preferably without explicit loops way to find and store into a vector all the numbers from a b that are not in ssolution 1 vectorint v forint i a i b i ifsfindi send vpush backi solution 2push all the numbers from a to b into a set and use stdset differencesolution1 contains an explicit loop and solution2 does not seem very efficient at least in terms of memory what would you suggest i am looking for an elegant stlish boost is also acceptible idiomatic way to do this,['c++'] +291711,how to insert a second menu into a wordpress template so i am trying to add a second menu to a wordpress template the first i have got by writing the followingphp wp nav menu array sort column menu order container class menuheader now i have got two menus registered in the functionsphp file as followsregister nav menuheader header menuregister nav menuadmenu1 ad menu onehow do i access whatever menu is in the second nav menu registered or am i registering incorrectly i have triedphp wp nav menu array theme location admenu1 container class menuads but that only gives me a list of every category which is not what i wanthow do i merely grab the menu that is associated with ad menu oneadmenu1,['php'] +291722,check if bool is defined in mixed cc so i am having issues with some code that i have inherited this code was building fine in a conly environment but now i need to use c to call this code the header problemh containsifndef booltypedef unsigned char boolstatic const bool false 0static const bool true 1endifstruct astruct bool myvar and a bunch more when i compile it as c code i get error c2632 char followed by bool is illegali get the same error if i wrap the include problemh in extern c which i do not understand because there should be no keyword bool when compiling as ci tried removing the block from ifndef bool to endif and compiling as c and i get errorserror c2061 c requires that a struct or union has at least one membererror c2061 syntax error identifier booli just do not understand how the c compiler is complaining about a redefinition of bool yet when i remove the redefinition and try to just use bool to define variables it does not find anythingany help is greatly appreciated,"['c++', 'c']" +291725,order css based on selector specificity i have parsed a given css filestring into a json object like so header color 0 header h1 color 0 h1 color 4fb6e5 what i want to do now is reorder them based on specificty in this case the header h1 should come after the h1 in the json object as this is how they will be applied in the browserhow can i do this are there any existing libraries for this or any useful libraries to help with thisi can use both javascriptjquery or php to do this i am looking for implementation advice and hopefully this has already been done,"['php', 'javascript', 'css']" +291751,could not open input file appconsole i installed wamp server and a copy of the symfony2 framework i am trying to create a bundle using the following command php appconsole generatebundle nampespaceidpidp bundle formatymlmy php is in cwampbinphpphp5310but when i run the command it says could not open input file appconsolecan anyone tell me what is going wrong,['php'] +291769,linq group by and select collection i have this structurecustomer has many orders has many orderitemsi want to generate a list of customeritems via linq given a subset of orderitemslist of new customer listorderitem items which is a grouping of all the items a customer has ordered from the subset of itemshow can i use linq to back track through the order and group by customer to generate this objectso far i am on something likeitems groupbyi i i iordercustomer i customer new customer ibut thats obviously not a list i am guessing i need a selectmany in there somewhere but could do with some pointers,['c#'] +291775,onclick event to remove default value in a text input field i have an input fieldinput namename valueenter your namehow would i get it to remove the predefined text enter your name when the user clicks the boxas far as i am aware javascript is the best way to do this if that wrong please inform me,"['javascript', 'html']" +291783,uninstall nginx installed by passenger how do i uninstall nginx installed as part of passenger installation on ubuntu 1104should i just gem uninstall passenger will that remove nginx as wellthis is what i see when i run aptget removesudo aptget remove nginxcommon nginxfullreading package lists donebuilding dependency tree reading state information donepackage nginxcommon is not installed so not removedpackage nginxfull is not installed so not removedthe following packages were automatically installed and are no longer required nspluginwrapper linuxheaders263813generic libmysqlclientdev libaprutil1ldap libaprutil1dev libmysqlclient16 libdb48dev libaprutil1dbdsqlite3 apache22bin linuxheaders263814generic linuxheaders263812 linuxheaders263813 linuxheaders263814 mysqlcommon linuxheaders263812genericuse aptget autoremove to remove them,['ruby-on-rails'] +291792,remove delete button on first set of fields i allow the user to add multiple rows of fields but i do not want to include a delete link on the very first row of fields so they cannot delete all the fieldsalso how do i limit it to only 3 rows of fields,"['javascript', 'jquery', 'html', 'css']" +291819,command line parser with mutually exclusive required parameters i started to use the commandline parser library for a tool that will have both a gui and a command line execution launching the gui is done via a command line optioni would therefore like to have required options in case the program is executing in command line mode basically i would want option 1 and option 2 to be required if the option gui is not seti tried to combine the mutuallyexclusiveset and required attributes as shown below but it does not work as i thought did i misunderstand the concept of mutuallyexclusiveset or simply misusing it or is it something that the library is not yet supportingpublic class commandlineoptions commandlineoptionsbase optionnull gui required false helptext launch the gui mutuallyexclusiveset gui public bool gui get set optionnull opt1 helptext option 1 mutuallyexclusiveset commandline required true public string option1 get set optionnull opt2 helptext option 2 mutuallyexclusiveset commandline required true public string option2 get set,['c#'] +291864,what is the equivalent of jquerys cellfirst in d3 i have triedd3selectcellfirstd3selectallcellfilterfirstd3selectallcellselectfirstbut neither work,"['javascript', 'jquery']" +291947,unable to remove css bullets from list i am fighting with css and cannot figure out how to remove bullets yeah i know this sounds easy but hear me out i have another external css file from our corporate office that has styles that are getting in the way and i cannot for the life of me figure out how to override them i have tried the important token and it does not work either i am using chrome and the inspector has not yet helped me figure out whats causing it anyway heres my code which works great standalone but once i put the corporate css file in there the stupid bullets come back ugh ul styleliststyletypenone lifirstli lisecondli lithirdli ul,"['html', 'css']" +291966,filenotfoundexception resdrawablexhdpiv4foopng in play store crash logs only weve seen about 40 of these crashes in the past two days of our app release for 40 after reviewing crash logs weve thiscovered it is existence since version 33 of our app we have been unable to reproduce this in housefurther research has indicated this problem is prevalent in other applications but i was unable to find a resolution or an indication that google is aware of the issuethe crash itself happens on the setcontentviewrlayoutfoo method call in oncreatenoteswe limit our api to version 4 and target 15weve seen this on at least 22 403 on mdpihdpixhdpi phones and tabletsuser comments specify that the app crashes immediately expected and that the evernote icon in the application launcher turns to the default app icon cannot read any drawablesthe crash is not limited to one specific drawable we have seen many different ones in the logs however they all seem to be image drawables not colors layouts xml files etcthis is not limited to 9patches it has happened on both regular png and 9pngour drawable folders look like the picture attached we store only xml in our drawable folderstack traceandroidcontentresresourcesnotfoundexception file resdrawableics tab title unselectedxml from drawable resource id 0x7f02016fat androidcontentresresourcesloaddrawableresourcesjava1697at androidcontentresresourcesgetdrawableresourcesjava581at androidviewviewsetbackgroundresourceviewjava7533at comevernoteicsactionbartabbedtitleaactionbartabbedtitlejava103at comevernoteicsjaactivityactionbarjava150at comevernoteicsacactionbarjava731at comevernoteicsapactionbarjava440at comevernoteicsagactionbarjava423at comevernoteicsjmactivityactionbarjava68at comevernoteicsphoneswipeabletabbedactivityabstractsswipeabletabbedactivityabstractjava990at comevernoteicsphoneswipeabletabbedactivityabstractaswipeabletabbedactivityabstractjava662at comevernoteicsphoneswipeabletabbedactivityabstractbswipeabletabbedactivityabstractjava617at comevernoteicsphonephonemainactivitybphonemainactivityjava113at comevernoteuievernotefragmentaevernotefragmentjava136at comevernoteuievernotefragmentaevernotefragmentjava132at comevernoteuievernotefragmentdevernotefragmentjava128at comevernoteicsphonebonitemclickhomefragmentjava1324at androidwidgetadapterviewperformitemclickadapterviewjava284at androidwidgetlistviewperformitemclicklistviewjava3513at androidwidgetabslistviewperformclickrunabslistviewjava1812at androidoshandlerhandlecallbackhandlerjava587at androidoshandlerthispatchmessagehandlerjava92at androidoslooperlooplooperjava123at androidappactivitythreadmainactivitythreadjava3683at javalangreflectmethodinvokenativenative methodat javalangreflectmethodinvokemethodjava507at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava864at comandroidinternaloszygoteinitmainzygoteinitjava622at dalviksystemnativestartmainnative methodcaused by androidcontentresresourcesnotfoundexception file resdrawablexhdpiv4tab unselected focus9png from drawable resource id 0x7f0201e6at androidcontentresresourcesloaddrawableresourcesjava1714at androidcontentresresourcesgetdrawableresourcesjava581at androidgraphicsdrawablestatelistdrawableinflatestatelistdrawablejava162at androidgraphicsdrawabledrawablecreatefromxmlinnerdrawablejava787at androidgraphicsdrawabledrawablecreatefromxmldrawablejava728at androidcontentresresourcesloaddrawableresourcesjava1694 28 morecaused by javaiofilenotfoundexception resdrawablexhdpiv4tab unselected focus9pngat androidcontentresassetmanageropennonassetnativenative methodat androidcontentresassetmanageropennonassetassetmanagerjava406at androidcontentresresourcesloaddrawableresourcesjava1706 33 moreany recommendations would greatly be appreciatedapp thanksty,['android'] +291992,does stdruntime error copy the string passed in the constructor i wonder if this line creates a dangling pointerstring argderpthrow stdruntime errorunknown argument argdoes stdruntime error copy the string or does it store the reference,['c++'] +291995,how to change case of latin utf8 strings in c in objectivec it is dead simplenslog baao lowercasestring outputs baaoin c whats the equivalent can anyone provide valid code for this that produces the same output is there a nice stl way to do this without relying on icu boost or any other 3rd party libsmy current nonsolution isusing namespace stdstring s baaowstring wsbegin sendtransformwbegin wend wbegin towlower w contains baao,['c++'] +292011,how does rspecs expect work in ror while going through ruby on rails tutorial by michael hartlin the section where the author writes integration test to validate his signup page he has used code spinet bellow i got what the code does but could not get my head around the how part ie could not understand order of execution expect click button create my account not to changeuser countcan someone please explain the semantics of the above chain of methods and blocks and how they fit together,"['ruby-on-rails', 'ruby']" +292059,why is hierarchyviewer not working for samsung galaxy tab 70 i have used hierarachyviewer earlier but on android emulator it works absolutely fine when i use it on the emulator however it does not work with samsung galaxy tab 70 with android 234 this is the log that i get110422 ehierarchyviewer unable to get view server version from device 30359964881b00ec110422 ehierarchyviewer unable to get view server protocol version from device 30359964881b00ec110424 ehierarchyviewer unable to debug device 30359964881b00ec110505 ehierarchyviewer unable to get view server version from device 30359964881b00ec110505 ehierarchyviewer unable to get view server protocol version from device 30359964881b00ec110507 ehierarchyviewer unable to debug device 30359964881b00ec110938 ehierarchyviewer unable to get view server version from device 30359964881b00ec110938 ehierarchyviewer unable to get view server protocol version from device 30359964881b00ec110940 ehierarchyviewer unable to debug device 30359964881b00eci am also not using hierarchyviewer in the debug mode just running the applicationthanks,['android'] +292068,java compressing strings i need to create a method that receives a string and also returns a string ex input abccex output 3a4b2cwell this is quite embarrassing and i could not manage to do it on the interview that i had today i was applying for a junior position now trying at home i made something that works statically i mean not using a loop which is kind of useless but i do not know if i am not getting enough hours of sleep or something but i cannot figure it out how my for loop should look like this is the codepublic static string comprimirstring texto stringbuilder objstring new stringbuilder int count char match count textosubstringtextoindexoftextocharat1 textolastindexoftextocharat1length1 match textocharat1 objstringappendcount objstringappendmatch return objstringtostringthanks for your help i am trying to improve my logic skills,['java'] +292070,how to call magento block in phtml template i need to thisplay some more links in footer i created those links in magento admin as static blocks id sample links and then i added following code pagexml filereference namefoot lnk block typecmsblock namesample block before action methodsetblockidblock idsample linksblock idaction blockreferencei called this one in footerphtml asphp echo thisgetchildhtmlfoot lnk but it does not thisplay the cms static block content what is the issue,['php'] +292086,how to get elasticsearch to perform similar to sql like if using a sql like statement to query data it will return data even if its only partially matched for instance if i am searching for food and there is an item in my db called raisins when using sql the query would return raisins even if my search only contained rai in elasticsearch the query would not return a record unless the entire name in this case raisins is specified how can i get elasticsearch to behave similar to the sql statement i am using rails 311 and postgresql thanks,"['sql', 'ruby-on-rails']" +292091,what is stub and aidl for in java question 1i am studying android service i often see code like thisprivate isampleservicestub sampleserviceif new isampleservicestubwhat is stub question 2i checked aidl but i want to know why we have to use that instead of the java interface filethank you guys,['android'] +292098,removing first appearance of word from a string i am not familiar with regex and it would be great if someone giving a solution using regex could explain their syntax so i can apply it to future situationsi have a string ie description mary had a little lamb and i would like to remove description such that the string would read mary had a little lamb but only the first instance such that if the string was description description the new string would be descriptionany ideas thanks,['python'] +292114,automatically comparing java profiling results for a single unit test i want to run a single unit test and collect its profiling information how often every method was called how many instances of certain class were created how much time did it take to execute certain methodthread etc then i want to compare this information with some expected values are there any profilers for java than let me do this all this should be done automatically without any gui or user interaction of coursethis is how i want it to workpublic class mytest test public void justtwocallstofoo profilerstartfooclass foo foo new foo foosomemethodtoprofile profiler should collect data here assertthat profilergettotalcallsmadetofooclass barmethod equalto3,['java'] +292115,is mappermap in automapper threadsafe i am looking up automapper code now evaluating it for one of projects i am working on and frankly speaking i am quite surprisedthe library api is based on a single static access point mapper type so generally any of its methods must be thread safebut i did not find any evidence of this in code all i was able to find is this issue but even the statement made there seems incorrect if map does not use threadsafe data structures internally it cannot be considered as threadsafe as well if i am going to call createmap in nonconcurrent context but concurrently with mapie the only possible usage pattern of automapper in eg aspnet mvc application islock mapperlock mapperanymethod obviously if i am correct that is a huge lackso i have two questionsam i correctif yes whats the best alternative to automapper that does not have this issue,['.net'] +292123,ios facebook connect logout not deleting login details i have used facebook connect on another project with relatively few problems however on my current project it seems that when i call facebook logout it does not remove the users details if i then restart the app i have the following in the didfinishlaunchingwithoptions functionfacebook facebook alloc initwithappidx anddelegateselfnsuserdefaults defaults nsuserdefaults standarduserdefaultsifdefaults objectforkeyfbaccesstokenkey defaults objectforkeyfbexpirationdatekey facebookaccesstoken defaults objectforkeyfbaccesstokenkey facebookexpirationdate defaults objectforkeyfbexpirationdatekey nslogstartup login self logintofacebookattempt to login automatically on startupmy logintofacebook function is this voidlogintofacebook nsloglogging into facebook set up facebook and login in automatically if possible nsuserdefaults defaults nsuserdefaults standarduserdefaults ifdefaults objectforkeyfbaccesstokenkey defaults objectforkeyfbexpirationdatekey facebookaccesstoken defaults objectforkeyfbaccesstokenkey facebookexpirationdate defaults objectforkeyfbexpirationdatekey if facebook issessionvalid get permissions that user will need to agree to us using nsarray permissions nsarray alloc initwithobjects user likesread friendlistsoffline access publish stream nil authorise our login facebook authorizepermissions permissions release else facebook authorizenil as far as i am concerned this time i should be prompted to login with my email and passwordi am mostly using the simulator so the facebook app itself is not the cause and in the facebookh class i have changed self authorizewithfbappauthno safariauthyestoself authorizewithfbappauthno safariauthnohowever what happens is that the facebook window briefly flashes up and thisappears as i would expect it to when i am already logged in it then loads my id name friends list etc from my previous login details it is no longer possible for me to change users i should add that i have the following code which prints accordingly on logout voidfbdidlogout nsloglogged out of facebookwhich prints to the console when facebook logout is called i also have the correct url schemes in place so there is no problem thereas i say i have got this working on another app but i cannot see what i could have overlooked this time i welcome any suggestion as i suspect it is something ridiculously simple edit i have just tested it out on a device and the attempt to login to facebook causes the app to crash i suspect it is because it is attempting to login using stored info which does not exist because i have not logged in on the device yet i am still investigating but again if any can see an obvious flaw i would be very gratefuledit2i have tried removing cookies using safecases example i also print out all of the cookies during a didfinishlaunchingwithoptions and b during fbdidlogout and i get the followinga20120518 104040665 myapp1554517003 nshttpcookie version0 namec user value634361620 expiresdate20120617 093433 0 created20120518 093434 0 359026e08 sessiononlyfalse domainfacebookcom path issecuretruenshttpcookie version0 namecsm value2 expiresdate20120617 093433 0 created20120518 093434 0 359026e08 sessiononlyfalse domainfacebookcom path issecurefalsenshttpcookie version0 namedatr valuegxe2t8zybzmgb5w3ls29q0kj expiresdate20140518 093433 0 created20120518 093434 0 359026e08 sessiononlyfalse domainfacebookcom path issecurefalsenshttpcookie version0 namelocale valueen us expiresdate20120525 093643 0 created20120518 093644 0 359027e08 sessiononlyfalse domainfacebookcom path issecurefalsenshttpcookie version0 namelu valuergaya7cmilsallod2yo3g expiresdate20140518 093433 0 created20120518 093434 0 359026e08 sessiononlyfalse domainfacebookcom path issecurefalsenshttpcookie version0 namem user value03a03a03a03av 12cajax 12cwidth 3202cpxr 12cgps 13a133736733a2 expiresdate20120816 093433 0 created20120518 093434 0 359026e08 sessiononlyfalse domainfacebookcom path issecurefalsenshttpcookie version0 names valueaa4wdkuoofathmk expiresdate20120617 093433 0 created20120518 093434 0 359026e08 sessiononlyfalse domainfacebookcom path issecuretruenshttpcookie version0 namexs value1253affiwxjaxdxummw3a23a13373673 expiresdate20120617 093433 0 created20120518 093434 0 359026e08 sessiononlyfalse domainfacebookcom path issecuretrueb20120518 104116530 myapp1554517003 since it changes to empty i would assume they are deleted but on reopening the app they are all there againedit3 the only way around this i have found is to delete all cookies as soon as the application opens however this means the user has to login every time even if they left themselves logged in the last time they had the app open it is a temporary fix for the moment i am still not sure why it is not working as it should be,"['objective-c', 'ios']" +292136,android how to get selected word in edittext i am developing an app like notepad in which i want to change the selected text formatting dynamically colors changing font styles bold italic underline etchow can i format a specific word,['android'] +292152,android bitmapfactorydecodestream returns null i have tried to get the bitmap image from the path of the image but bitmapfactorydecodestream returns null valuecodeurl url new urlpathhttpurlconnection connection httpurlconnection urlopenconnectionconnectionsetdoinputtrueconnectionconnectinputstream input connectiongetinputstreambitmap mybitmap bitmapfactorydecodestreaminputconnectionthisconnectinputclosei have searched in more sites still i did not get the solution,['android'] +292154,how to use libcurl for http post i am new using libcurl i am not understanding clearly how to use it for http post requests and how to check the result how can i use it for this,['c'] +292176,starting phantomjs server from php and waiting for it is response i wanted to run a phantomjs server from my php script then do a curl request to it and read it is response which in the final version will give a path to generated pdf when running phantomjs server file from the console and then navigating to it is address in the browser everything works fine that is the serverjs file var server service page requirewebpagecreate address output html doctypehtmlheadheadbodyh1foh1bodyhtmlserver requirewebservercreatevar rasterize functionhtml callback address httplocalhost output usersmeprintpdf pageviewportsize width 600 height 600 pageopenaddress function status if status success consolelogunable to load the address else windowsettimeoutfunction pagecontent html pagerenderoutput callback 20 service serverlisten8080 function request response responsestatuscode 200 rasterizehtml function responsewriteh1barh1 responseclose phantomexit basically i am opening localhost addres switching content of the page to my html string and then saving rendered page as pdf now comes my php script function send callbackdata echo type success data data function curl posturl array post null array options array defaults array curlopt post 1 curlopt header 0 curlopt url url curlopt fresh connect 1 curlopt returntransfer 1 curlopt forbid reuse 1 curlopt timeout 5 curlopt postfields http build querypost ch curl init curl setopt arraych options defaults if result curl execch trigger errorcurl errorch curl closech send callbackresult shell execphantomjs escapeshellargdirname file serverjs wait to allow server to start sleep5 data arrayhtml foo curl posthttplocalhost8080 dataalso no magic here i execute phantomjs serverjs command in terminal and after 5s time to init the server do a curlpost request to itnow i have two cases if i run php script from console with php scriptphp the server starts as i can see the process running and the icon is visible in the dock but i never get any response from it and the pdf is not created if i run the script from the browser icon is not visible in the dock so the server starts in some other way still no response nor pdfcan anyone see anything wrong in my code or think of any ways of debugging it testing on osx 107 php 536 phantomjs latest user w running the server has admin privileges folder where i am writing files were chmoded to 7,"['php', 'javascript']" +292186,returning null if structure initialization failed in c i have this c code includestdiohtypedef struct int foo mystructmystruct init mystructvoidint mainvoid mystruct mystruct init mystruct if mystruct null error handler return0mystruct init mystructvoid mystruct mystruct int is ok 1 do something everything is ok if is ok return mystruct something went wrong else return nullit has a structure and a function to initialize that structure what i am trying to do is to return null if there was a failure in that functionthe gcc error message codec in function amainacodec13 error invalid operands to binary have amystructa and avoid acodec in function ainit mystructacodec34 error incompatible types when returning type avoid a but amystructa was expectedit looks that returning null instead of a structure is not valid so how do i express the failure of structures initialization in this case no structure pointer,['c'] +292219,how to unsubscribe the subscribed function in knockout i already subscribe the function to listen the property value change using kovar self this document ready function var postbox new kosubscribablevar myviewmodel firstname koobservable bert lastname koobservable pual var sub nullfor var i in myviewmodel var model myviewmodeli modelsubscribe selfnotifychangebind model i unsubscribebutton click function here i want to unsubscribe koapplybindings myviewmodel notifychange function propname newvalue var self this here i want to unsubscribe the notifychange from myviewmodels property one by one how to do this,['javascript'] +292262,is signalr a suitable substitute for jquery ajax or similar as per title would signalr be a suitable substitute for general ajax eg jquery ajax updates used in web pagesthanks,['jquery'] +292263,converting cmtime to human readable time in objectivec so i have a cmtime from a video how do i convert it into a nice string like in the video time duration label in the photo app is there some convenience methods that handle this thanks avurlasset videoasset avurlasset urlassetwithurlurl optionsnilcmtime videoduration videoassetdurationfloat videodurationseconds cmtimegetsecondsvideoduration,"['objective-c', 'ios', 'c']" +292277,in which versions of the c standard does i1010 have undefined behaviour in c does the following have undefined behaviourint i 0i1010there was some debate about this in the comments to my answer to whats the result of in c and c the subtlety here is that the default response seems to be yes whereas it appears that the correct answer is it depends on the version of the c standardif it does depend on the version of the standard please explain where it is ub and where it is not,['c++'] +292279,returning http status code from web api controller i am trying to return a status code of 304 not modified for a get method in a web api controllerthe only way i succeeded was something like thispublic class trycontroller apicontroller public user getuserint userid datetime lastmodifiedatclient var user new dataentitiesusersfirstp pid userid if userlastmodified lastmodifiedatclient throw new httpresponseexceptionhttpstatuscodenotmodified return user the problem here is that it is not an exception it is just not modified so the client cache is oki also want the return type to be a user as all the web api examples shows with get not return httpresponsemessage or something like this,['c#'] +292293,remove empty lines from string but allow one empty between every line i would like to remove excessive empty lines from a string but allow one empty line between every line likeline1nline2should becomeline1nnline2i did find the following regex forgot where i found itpreg replacentsnmmessagethis works but removes all empty lines without leaving an empty line between every lineedit i just created a quick example at,['php'] +292312,wrong height of div with img tag inside i have a div with an image tag inside and the div height appears to be a little larger than the imagei could fix this problem by setting a specific height for the div the same as the image but i am working with a responsive layout and i do not want to set a specific height for the div so that when the browser window scales for example in mobile devices the div will scale and maintain the ratioi need that the div height to be exactly as the image heightthis is the scenariodiv classboximg srcimagejpgdivcss isimg height auto maxwidth 100 width autodoes anybody know how to fix this problem,['html'] +292344,how to access eventtarget in ie9 the html dom object model defines an event object with a target propertylooking at msdn microsoft documents a target property they also document srcelement as an alias of target from earlier versions of internet explorerthe target property is similar to srcelement in windows internet explorer 8 and earlier versionsso here i am in internet explorer sitting at a click breakpointdiv classday onclickdivclickthisfunction divclicksender var divcell senderand at the f12 tools console i can ask for the global event object event actionurl altkey false altleft false behaviorcookie 0 behaviorpart 0 bookmarks null boundelements button 0 buttonid 0 cancelbubble false and i can ask for the eventsrcelement object eventsrcelement align nowrap false datafld dataformatas datasrc currentstyle runtimestyle accesskey classname header contenteditable inherit but eventtarget is empty eventtarget and if i watch event there is no target propertyso how do i access the target property of an event object in internet explorer 9 document mode ie9 standards browser mode ie9,['html'] +292360,show settings under accounts sync menu for android app i am implementing a syncadapter for an android app and would like to make the settings for the account available under the accounts sync menu i have seen this done in the dropbox appas shown below but i have not been able to find documentation on how to do this i have the accounted added just want to add a link to the account settings in this menu,['android'] +292369,how does aspnet webapi handle two methods with names starting with get i am looking at the following tutorial from microsoft as per this tutorialin the first example products matches the controller named productscontroller the request is a get request so the framework looks for a method on productscontroller whose name starts with get furthermore the uri does not contain the optional id segment so the framework looks for a method with no parameters the productscontrollergetallproducts method meets all of these requirementswhat happens if there are two methods like getallproducts and getsoldproducts both have no parametersyour first web api tutorial,"['c#', 'asp.net']" +292385,styling twitter bootstrap buttons twitterbootstrap buttons are awesomely beautiful try them out by scrolling over thembut they are limited in colors is there any way i could change the base color of the button while keeping the beautiful hoverover effect that bootstrap has made so beautiful and effortlessi am completely unaware of what the cssjavascript looks like that twitter uses to maintain those effects,['css'] +292388,please help me understand type attribute of webconfig custom settings i am trying to define custom settings in my webconfig file and i am pretty sure i have most of it correct and it all makes sense except the one crucial part where i do not understand what i am supposed to use the tutorial i used to create my sectionhandler did not go into an explanation of it and msdn is not really helping me fully understand it either this comes from the tutorial i usedsection nameblogsettings typefullyqualifiedtypenameblogsettings assemblyname link to tutorialthis is from msdn typesystemconfigurationsingletagsectionhandler yes i am very new to aspnet and i am trying to learn i would be happy with any good references that explain whats going on here,['asp.net'] +292407,angularjs rails problems when compressing assets i recently created an angularjs 100rc8 app with a rails 323 backend and it worked fine in development but after deploying to heroku there was a unknown provider error apparently the app could not see the service objecti know that it is now necessary to include angularresourcejs as a separate file and inject ngresource into the app module like this main app javascript fileuse strictangularmodulecontactapp ngresource configrouteprovider functionrouteprovider routeprovider whencontacts template assetsapartialscontactlisthtml controller contactlistctrl whencontactsnew template assetsapartialsnewcontacthtml controller contactlistctrl whencontactscontact id template assetsapartialscontactdetailhtml controller contactdetailctrl otherwiseredirectto contacts i also know that when files are minified that the controllers cannot tell what their dependencies are unless they are also injected into the controller objects like thiscontactlistctrlinject scope http contactsi have also tried doing it the other way that angular recommends with bracket notation and passing in a function like thisvar contactlistctrl scope http contacts functionscope http contacts constructor body however none of this seems to workthe only way my application could see the resource provided was by turning off asset compression in the productionrb file like this compress javascripts and css configassetscompress falseit took several hours for me to figure this out but i recently saw another rails angularjs app that had the same issuejens krause came to the same conclusion and explains it on his blog if i have a relatively large app and i need to compress the assets how do i get around this using angular with railsthanks,['javascript'] +292418,typeerror cannot call method getcontext of null anonymous function i am a beginner at this and have not really done any javascript before so i hope you can help me i have made a canvas that lets the user choose a shape and a colour with radio buttons which is then drawn on to the canvas i have also added a checkbox with an option of adding a gradient to the chosen colour heres the programnow i want to make it so that the shapes can be dragged and dropped around the canvas area and i have found a code that i think can be altered to work on my program but i keep getting typeerror cannot call method getcontext of null initanonymous function for the line var ctx canvasgetcontext2dand i have no idea what is wrong or how i can solve it i have tried looking for similar programs with similar problems but have not found anything that i can apply here heres the code that i am trying to incorporate with mine function init var canvas documentgetelementbyidmycanvas var ctx canvasgetcontext2d return setintervaldraw 10 function draw clear ctxfillstyle faf7f8 rectangle00widthheight ctxfillstyle 4 rectangle function mymovee if dragok x epagex canvasoffsetleft y epagey canvasoffsettop function mydowne if epagex x 15 canvasoffsetleft epagex x 15 canvasoffsetleft epagey y 15 canvasoffsettop epagey y 15 canvasoffsettop x epagex canvasoffsetleft y epagey canvasoffsettop dragok true canvasonmousemove mymove function myup dragok false canvasonmousemove null init canvasonmousedown mydown canvasonmouseup myup,['javascript'] +292422,what are my options to check for viruses on a php upload i am looking to see how i can go about checking if an uploaded file has a virus or not via php what options exist pros and cons of each etc,['php'] +292424,commandclick does not open a new tab but middleclick does on my website which is a onepage js site using sammyjs and jquery when i middleclick a link with a mouse the link opens in a new tab but when i commandclick on a mac it does not this happens in both firefox and chrome so i assume it must be according to spec in some waythis happens on a macbook air so trackpad command button most sites work just fine though with commandclick being identical to normal middleclicktry it out yourself commandclick between about home and contact and you should experience the problem they do not open in new tabs,"['javascript', 'jquery']" +292443,c server scalability issue on linux i have a c server developed on both visual studio 2010 and mono develop 28 net framework 40it looks like this server behaves much better in terms of scalability on windows than on linuxi tested the server scalability on native windows12 physical cores and 8 and 12 cores windows and ubuntu virtual machines using apache is ab toolthe windows response time is pretty much flat it starts picking up when the concurrency level approachesovercomes the number of coresfor some reason the linux response times are much worse they grow pretty much linearly starting from level 5 of concurrency also 8 and 12 cores linux vm behave similarly so my question is why does it perform worse on linux and how can i fix thatplease take a look at the graph attached it shows the averaged time to fulfill 75 of the requests as a function of the requests concurrencythe range bar are set at 50 and 100i have a feeling that this might be due to monos garbage collector i tried playing around with the gc settings but i had no success any suggestionsome additional background information the server is based on an http listener that quickly parses the requests and queues them on a thread pool the thread pool takes care of replying to those requests with some intensive math computing an answer in 10secs,['c#'] +292506,whats the difference between source and target compatibility when using the java compiler javac we can specify two kinds of compatibility one is using source and the other is using target what is the difference between these two for example source 15 and target 16also is there any case where we use a different source and target compatibility level,['java'] +292514,converting a time string to seconds in python i need to convert time value strings given in the following format to secondsi am using python26eg10 0 seconds2010 10 seconds301040 64 seconds4 0101090 3669 secondsdo i need to use regex to do this i tried to use time modulebut timestrptime0ims threw valueerror time data 0 does not match format imscan someone tell me how this can be solvedediti think pt datetimedatetimestrptimetimestringhmsf total seconds ptsecondptminute60pthour3600gives the correct valuei was using the wrong module,['python'] +292521,calling threadsleep from synchronized context in java i have read that threadsleep will pause the currently running thread for the time specified after which it goes back to runnable state waiting for it is turn to runalso if called from synchronized context sleep does not release the lock it holds so i was wondering when it will release the lock if the thread put on sleep never gets the chance to run so it will always keep the lock with itself and then how other threads get to enter synchronized methodsblocki am not sure if i am asking valid question but please help me out,['java'] +292554,listfragment how to get the listview i am porting my app from asynctasks to fragementsbut how can i access the listview id list element within my fragmentclass myfragment extends listfragment override public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate view v inflaterinflaterlayoutlist fragment container false listview listview getlistview ex listviewsettextfilterenabledtrue registerforcontextmenulistview return v xml listview androididandroididlist androidlayout widthmatch parent androidlayout heightmatch parent listviewexcaused by javalangillegalstateexception content view not yet created,"['java', 'android']" +292599,how can i check if a modal view is currently over my selfwindowrootviewcontroller i need to check if there is still a modal view over the root view controllerthe problem i am facing is that i have a second modal view coming from some thread that needs to be thisplayed i want to delay the second modal view until the first one is gonei cannot just launch it after the first is thismissed because the second modal view is conditionalselfwindowrootviewcontroller presentmodalviewcontrollervc animatedyeswhat i want to do feel free to suggest a better alternative waycheck if selfwindowrootviewcontroller currently has a modal view thisplayed on top or is still animating modal viewuse performselectorafterdelay01check again and if needed delay again,['ios'] +292614,graphingplotting a wav file java im fairly new to javai would like to plot a frequencytime graph or sample image from a wav fileto start off i am struggling to get the raw data array from the wav file using audioinputstream also referencing from reading wav file in java i also tried the wavfile class referring but when testing i was unable to find the correct packages to satisfy the wavfile cannot find symbol error the supplied import javaio for that sample did not satisfy thisto reiterate i wish to get a the raw data in array format of a wav filei would love any small examples of this as i learn from examples much easierthanks for your time,['java'] +292647,python requests throwing up sslerror i am working on a simple script that involves cas jspring security check redirection etc i would like to use kenneth reitzs python requests because it is a great piece of work however cas requires getting validated via ssl so i have to get past that step first i do not know what python requests is wanting where is this ssl certificate suppose to residetraceback most recent call last file testpy line 24 in module response requestsgeturl1 headersheaders file buildbthistlinuxx86 64eggrequestsapipy line 52 in get file buildbthistlinuxx86 64eggrequestsapipy line 40 in request file buildbthistlinuxx86 64eggrequestssessionspy line 209 in request file buildbthistlinuxx86 64eggrequestsmodelspy line 624 in send file buildbthistlinuxx86 64eggrequestsmodelspy line 300 in build response file buildbthistlinuxx86 64eggrequestsmodelspy line 611 in sendrequestsexceptionslerror errno 1 sslc503 error14090086ssl routinesl3 get server certificatecertificate verify failed,['python'] +292652,what are the risks of wrapping asyncawait iasyncoperations with taskwait code i am currently trying to port a fair amount of existing synchronous code to winrtas part of this i am hitting problems with the existing code expecting some operations to be synchronous eg for file ioto adapt this existing code to work with the iasyncoperation style api within winrt i have used a technique of wrapping the iasyncoperation with an extension method likenamespace cirriousmvvmcrosspluginsfilewinrt public static class winrtextensionmethods public static tresult awaittresultthis iasyncoperationtresult operation var task operationastask taskwait if taskexception null todo is this correct throw taskexceptioninnerexception return taskresult from mvvmcross winrt extensionmethods with a similar method for iasyncactionthese wrappers seems to work and they allow me to use the async methods in synchronous code like public ienumerablestring getfilesinstring folderpath var folder storagefoldergetfolderfrompathasynctofullpathfolderpathawait var files foldergetfilesasyncawait return filesselectx xname i understand that this is not really in the spirit of winrt but i am expecting these methods to normally only get called on background threads in the first place and i am writing this with the goal of making my code crossplatform compatible including to platforms which do not yet support awaitasync andor to developers who are not yet ready to make the jumpso the question is what risks am i running by using this type of codeand as a second question is there any better way i could achieve code reuse for areas such as file io,['.net'] +292662,difference between findviewbyidridcontent and getrootview what is the difference between findviewbyidridcontent and getrootview do not both return the root view of an activity,['android'] +292687,split the screen on android tablet i have seen several tablet apps that split the screen into two parts usually a menu and and a main window i tried to google something about it but could not find anything is there an out of the box solution for this or do i have build it on my own,['android'] +292699,efficient multiprocessing of massive brute force maximization in python 3 this is an extension of my recent question avoiding race conditions in python 3s multiprocessing queues hopefully this version of the question is more specifictldr in a multiprocessing model where worker processes are fed from a queue using multiprocessingqueue why are my worker processes so idle each process has its own input queue so they are not fighting each other for a shared queues lock but the queues spend a lot of time actually just empty the main process is running an iobound thread is that slowing the cpubound filling of the input queuesi am trying to find the maximal element of the cartesian product of and sets each with m i elements for 0 i n under a certain constraint recall that the elements of the cartesian product are lengthn tuples whose elements are are elements of the and sets i will call these tuples combinations to emphasize the fact that i am looping over every combination of the original sets a combination meets the constraint when my function is feasible returns true in my problem i am trying to find the combination whose elements have the greatest weight sumelementweight for element in combinationmy problem size is large but so is my companys server i am trying to rewrite the following serial algorithm as a parallel algorithmfrom operator import itemgetterfrom itertools import product cartesian product function from the std libdef optimizesets return the largest totalweight combination tuple from all possible combinations of the elements in the several sets subject to the constraint that is feasiblecombo returns true return max map lambda combination sumelementweight for element in combination combination filter is feasible returns true if combo meets constraint productsets keyitemgetter0 only maximize based on sum of weight my current multiprocessing approach is to create worker processes and feed them combinations with an input queue when the workers receive a poison pill they place the best combination they have seen on an output queue and exit i fill the input queue from the main thread of the main process one advantage of this technique is that i can spawn a secondary thread from the main process to run a monitoring tool just a repl i can use to see how many combinations have been processed so far and how full the queues are in q0 worker0 in q1 out q main worker1 main in q2 worker2 i originally had all the workers reading from one input queue but found that none of them were hitting the cpu figuring that they were spending all their time waiting for queueget to unblock i gave them their own queues that increased pressure on the cpu so i figured the workers were active more often however the queues spend most of their time empty i know this from the monitoring repl i mentioned this suggests to me that the main loop filling up the queues is slow here is that loopfrom itertools import cyclemain create workers each with its own input queue cycle through each workers queue and add a combination to that queue for combo worker in zipproductsets cycleworkers workerin qputcombo collect results and returni am guessing the bottleneck is workerin qput how do i make that faster my first instinct was to make the workers slower but that just does not make sense is the problem that the monitor thread is stopping the loop too often how would i be able to tellalternatively is there another way to implement this that does not involve so much waiting on locks,['python'] +292709,javascript serialization and performance with v8 and postgresql i have been experimenting with postgresql and plv8 which embeds the v8 javascript engine into postgresql using this i can query into json data inside the database which is rather awesomethe basic approach is as followscreate or replace function json stringdata json key text returns text as var data jsonparsedata return datakey language plv8 immutable strictselect id data from things where json stringdataname like zusing v8 i can parse json data into js then return a field and i can use this as a regular pg query expression but on large datasets performance can be an issue as for every row i need to parse the datathe parser is fast but it is definitely the slowest part of the process and it has to happen every time what i am trying to work out to finally get to an actual question is if there is a way to cache or preprocess the json even storing a binary representation of the json in the table that could be used by v8 automatically as a js object might be a win i have had a look at using an alternative format such as messagepack or protobuf but i do not think they will necessarily be as fast as the native json parser in any casethoughtpg has blobs and binary types so the data could be stored in binary then we just need a way to marshall this into v8,['javascript'] +292711,python class inheritance attributeerror why how to fix similar questions on so include this one and this i have also read through all the online documentation i can find but i am still quite confused i would be grateful for your helpi want to use the wand class wandtype attribute in my castspell class lumus method but i keep getting the error attributeerror castspell object has no attribute wandtype this code worksclass wandobject def init self wandtype length selflength length selfwandtype wandtype def fulldescself print this is a s wand and it is a s long selfwandtype selflength class castspellobject def init self spell thing selfspell spell selfthing thing def lumusself print you cast the spell s with your wand at s selfspell selfthing def wingardium leviosaself print you cast the levitation spellmy wand wandphoenixfeather 12 inches cast spell castspelumus door my wandfulldesc cast spelumus this code with attempted inheritance does not class wandobject def init self wandtype length selflength length selfwandtype wandtype def fulldescself print this is a s wand and it is a s long selfwandtype selflength class castspellwand def init self spell thing selfspell spell selfthing thing def lumusself print you cast the spell s with your s wand at s selfspell selfwandtype selfthing this line causes the attributeerror print the room lights up def wingardium leviosaself print you cast the levitation spellmy wand wandphoenixfeather 12 inches cast spell castspelumus door my wandfulldesc cast spelumus i have tried using the super method to no avail i would really appreciate your help understanding a why class inheritance is not working in this case b how to get it to work,['python'] +292718,calling an applicationcontroller method from console in rails in rails supposing that the file is already loaded how it is possible to call my method from this example from console some filerbclass myclass applicationcontrollerbase def my methodargs,"['ruby-on-rails', 'ruby']" +292748,restart the service even if app is forcestopped and keep running service in background even after closing the app how i am trying to run a service in the background what my app does is when user checks checkbox then service starts and when it is unchecked service is stopped which is working perfectly fine but the problem is when i closed the app from task manager it then also stops the service what i want is to keep the service running even after it is close from task manager then only way to stop that service is by user himself by unckecking the boxhow can i achieve thishere is my codemy main activitypublic class sampleserviceactivity extends activity called when the activity is first created overridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain final checkbox cb checkbox findviewbyidridcheckbox1 cbsetoncheckedchangelistenernew oncheckedchangelistener public void oncheckedchangedcompoundbutton buttonview boolean ischecked ifischecked toastmaketextgetbasecontext checked toastlength longshow startservicenew intentgetbasecontext myserviceclass else toastmaketextgetbasecontext unchecked toastlength longshow stopservicenew intentgetbasecontext myserviceclass my service classpublic class myservice extends service notify and new notifyoverridepublic ibinder onbindintent arg0 todo autogenerated method stub return nullpublic int onstartcommandintent intent int flags int startid toastmaketextthis service started toastlength longshow ninitnotificationgetbasecontext true return start stickymethod to stop servicepublic void ondestroy superondestroy ncancelnotificationgetbasecontext toastmaketextthis service stopped toastlength longshowupdatehow can we make this service so that it runs like gtalk service,"['java', 'android']" +292826,how to check if a point xy is inside a polygon in the cartesian coordinate system this question already has an answer herepoint in polygon aka hit testc point in polygon given a random polygon formulated with and line equations in the cartesian coordinate system is there any standard formula that is used to check for membership of a point xythe simple solution is to get all the line formulas and check if point x is below this line above that line and to the right of the other line etc but this will probably be tediousi should note that the polygon can be of any shape with any number of sides and may concave or convexfor convenience i have already added these utility functionsfloat slopecgpoint p1 cgpoint p2 return p2y p1y p2x p1xcgpoint pointonlinewithycgpoint p float m float y float x y pym px return cgpointmakexycgpoint pointonlinewithxcgpoint p float m float x float y mx px py return cgpointmakex y,['c'] +292863,multiple typeface in single textview i want to set the first character on textview with a typeface and the second character with a different type face and so oni read this example spannable str spannable textviewgettextstrsetspannew stylespanandroidgraphicstypefaceitalic 0 7 spannablespan exclusive exclusivebut it did not help me because i want to set multiple typeface external ttfsany idea,"['java', 'android']" +292878,threadsafe collection without lock i am preparing myself for an interview and i came across the followign question i tried but i could not find anything which can create a class containing thread safe collection without lock if know any solution then please helpcreate a c class derived from object and implements the following methodsaddstring a this method should add a given string to an internal collectiontostring a override this method and return a single commadelimited string containing all the strings in the internal collectionrequirementsmust be threadsafemust support multiple concurrent readersmust not use any preexisting threadsafe collectionsbonus donat use any type of lock,['c#'] +292881,concatenating a number of txt files in java i have a number of txt files i would like to concatenate those and generate a text file how would i do it in java following is the case file1txt file2txt concatenation results into file3txtsuch that the contents of file1txt is followed file2txt,['java'] +292895,how to close kill release a socket which is in fin wait 2 state i have a client application which uses a unmanaged dll for communicating with a serverall networkrelated operations are perormed inside the unmanaged dllafter a number of operations with the server the client is running out of tcp portsif we check the state of netwotk using netstat an we get the following resulttcp 1921681156048 192168102850 fin wait 2tcp 1921681156049 192168102850 fin wait 2tcp 1921681156050 192168102850 fin wait 2tcp 1921681156051 192168102750 fin wait 2tcp 1921681156052 192168102850 fin wait 2tcp 1921681156053 192168102750 fin wait 2tcp 1921681156054 192168102750 fin wait 2tcp 1921681156055 192168102750 fin wait 2tcp 1921681156056 192168102750 fin wait 2tcp 1921681156057 192168102850 fin wait 2tcp 1921681156058 192168102750 fin wait 2tcp 1921681156059 192168102850 fin wait 2tcp 1921681156060 192168102750 fin wait 2the ports are released only after the client is closedif i run the vs project in debug mode it never runs out the portsbut while running in release mode it is happeningand i do not have access neither to server nor client sourcehow to release or kill those ports which are in fin wait 2 state,['c#'] +292902,bash syntax error near unexpected token python from lxml import etree import module2dbk print module2dbkxsl transformetreeparsetestccapcol10614indexcnxml error bash syntax error near unexpected token,['python'] +292906,quickest way of importing 500gb text file taking only the sections wanted i have about 500gb of text file seperated in months in these text files the first 43 lines are just connection information not needed the next 75 lines are descriptors for an observation this is followed by 4 lines not needed then the next observation which is 75 lines the thing is all i want are these 75 lines descriptors are in the same place for every observation which are characterized like thisid 5523date 20052012mixed nulland i want to change it to csv format 552320052012 for each observation so that i end up with much smaller text files since the descriptors are the same i will know the first position for example is idonce i finish with the text file i will be opening the next one and appending it or would creating a new file be quickerwhat i have done is quite inefficient i have been opening the file loading it deleting these observations going line by line if it is taking a fair bit with a test sample it clearly is not the best method any suggestions would be great,['python'] +292923,how to set default port for webrick i want to set the default port when i dorails sto 3010 instead of having to sayrails s p 3010every time any ideas,['ruby-on-rails'] +292925,is there any difference between listviewinvalidateviews and adapternotifydatasetchanged is there any difference between listviewinvalidateviews and adapternotifydatasetchanged,['android'] +292936,getting location from coordinates i have given coordinates for latitude and longitude and i want make a location object with thosethere is not a constructor that takes to doubles to make a location so i tried like this location l null lsetlatitudelat lsetlongitudelonbut it crashes any different idea,['android'] +292937,java transferring big files over channels nio i have to transfer 100mb of data over serversocket using nio but i cannot figure out how to do this without transfer breaking at any place keeping the state of transfermy first idea was to send the size of file apparently i cannot send size of that big files because it wont even fit on ram at once then i thought why not just transfer til nothing is received but thats when problem comes ineven if i am writing serversided data all the time filechannel fc new fileinputstreamfgetchannel bytebuffer buffer bytebufferallocate1024 whilefcreadbuffer 0 bufferflip whilechannelwritebuffer 0 bufferclear but because there have to be breaks in file transfer some time reading the data constantly and breaking when nothing is available was bad ideai cannot figure out how could i possibly tell the client if theres still data available without having to send each slice of data as new packet with opcode etc or is it even possiblei am also wondering if theres better way to send whole buffer than belowwhilechannelwritebuffer 0,['java'] +292941,convert float to commaseparated string how would i convert a float into its accounting form 102828223 1028282231028282 102828200is there a python method that does this,['python'] +292954,android understanding heap sizes i am fairly new to android development and i cannot seem to grasp the java out of memory exception i know it means that my app has gone over the vm budget but after googling this many times i still do not seem to grasp this concept i am afraid that my app uses too much memory because i have six button selectors per screen with two bitmaps for each selector which are around 20 kb each according to the properties tab on my rooted g2x i have set the vm budget to 12mbrestarted my phone and ran my app with no problems whatsoever i am unbinding drawables on each ondestroy and hinting at the gc to run here also after using the app for a while in the emulator i click cause gc on my ddms screen and the results are id1 heap size 6133 mb allocated 2895mb free 3238 mb used 4720 objects 52623 this is where i dont understand whats happening my emulator is set to 24mb of vm where is that number the actual problem i am having is that if i set the emulator to 16mb of vm my app crashes on the second activity with the out of memory exception how come it doesnt crash on my phone with the vm set to 12 mb or on my old htc magic phone with 12 mb of vm stock also do you guys think my app is taking up too much memory i have no idea if those ddms numbers are good or not thanks for your time as for my code i have every image specified in xml layouts i do not do anything programmaticly with them except for adding listeners to them i found this bit of code on here and i have added it to every activity that i haveoverrideprotected void ondestroy superondestroy unbinddrawablesfindviewbyidridmyrootlayout systemgcprivate void unbinddrawablesview view if viewgetbackground null viewgetbackgroundsetcallbacknull if view instanceof viewgroup view instanceof adapterview for int i 0 i viewgroup viewgetchildcount i unbinddrawablesviewgroup viewgetchildati viewgroup viewremoveallviews otherwise all i do is add onclicklisteners to the buttons that have the png backgrounds i would like to learn how to specify button backgrounds programmaticly but i need to have the selector functions like on focus on press nonfocused but pressed etc to make the button backgrounds change according to user interaction i have reviewed the docs about this but it seems overwhelming that is why i figured i would start here with the basics of managing heaps and work my way up to specifying selectors in code this may not make sense but is there a healthy amount of memory allocation that an app could allocate without getting close to the out of memory exception for example if an app allocated 6mb it should be fine but 8mb would be pushing it are there bounds like that in memory allocation thanks again alex lockwood for your response i am going to read and reread it again until this stuff makes sense to me,['android'] +292958,ddl generation and general persistencexml settings openjpa summaryi am trying to run a java web application jpa 20 example the example application was written to run in glassfish using eclipselink as jpa provideri would like to convert it to run in tomee with openjpa as the jpa provider but i cannot any detailed tutorials for getting up and running with openjpaproblemi am having trouble converting persistencexml to work with openjpa instead of eclipselink more specifically the given persistencexml does not specifyentity classes are these necessarythe desired jpa provider will the container default to somethingthe jdbc driver how do i specify an inmemory db just for initial testing purposesalsohow are the ddl generation properties expressed in openjpa i was not able to find them the openjpa user guidedetailsbelow is the eclipselink persistencexmlxml version10 encodingutf8persistence version20 xmlns xmlnsxsi xsischemalocation 2 0xsd persistenceunit nameorder transactiontypejta jtadatasourcejdbc defaultjtadatasource properties property nameeclipselinkddlgeneration valuedropandcreatetables property nameeclipselinkddlgenerationoutputmode valueboth properties persistenceunitpersistencei have the following entity classesorderentitylineitemorderentitylineitemkeyorderentityorderorderentitypartorderentitypartkeyorderentityvendororderentityvendorpartquestiondoes anyone know what the equivalent persistencexml would look like for openjpaalternatively if anyone could point me to an openjpa tutorial that covers these issues that would be just as good,['java'] +292978,utc times in javascript i am trying to get the current utc date to store in my database my local time is 911 pm this equates to 1 am utc when i look in my database i notice that 1 pm is getting written to i am confused in order to get the utc time in javascript i am using the following codevar currentdate new datevar utcdate dateutccurrentdategetfullyear currentdategetmonth currentdategetdate currentdategethours currentdategetminutes currentdategetseconds currentdategetmillisecondsvar result new dateutcdatewhat am i doing wrong,['javascript'] +292979,php in netbeans is there shortcut to generate the tags i have just started using netbeans 712 php version to work on a php project netbeans is really great for editing long stretches of php codebut in my view files where html is mixed up with short bits of php i am getting really tired of manually typingphp in dreamweaver you just press a button to create these tags but in netbeans i cannot find anything like a keyboard shortcut surely there must be one does anybody know what it is,['php'] +292986,towers of hanoi solution better than o2n is there a solution for towers of hanoi whose running time is less than o2n where n is the number of thisks to move my solution takes o2n timealso the below solution is with recursion can we use dynamic programming with the concept of memoization to solve this in a lesser timepublic void towersofhanoi int num mystackinteger from mystackinteger to mystackinteger spare if num 1 int i frompop topushi systemoutprintlnmove i from fromgetname to togetname return towersofhanoinum 1 from spare to towersofhanoi1 from to spare towersofhanoinum 1 spare to frommystack is an extended version of stack class in java that adds a name field and accessoralso are there any variations of the same problem,['java'] +293004,javascript search inside a json object i had a json string object in my application list namemy nameid12typecar owner namemy name2id13typecar owner2 namemy name4id14typecar owner3 namemy name4id15typecar owner5i had a filter box in my application and when i type a name into that box we have to filter the object and thisplay the resultfor example if the user types name and hits search then we have to search full names in the json object and return the array just like a mysql search my question is to filter the json object with string and return the array,"['javascript', 'jquery']" +293025,how do i convert from systemarray to object in c i have a com function that expects object as a parameterfobject valuesi want to pass some enum fields to it so i use the followingobject fields objectenumgetvaluestypeofsomeenumtypehowever when i try to pass fields to foo ie foofields i get an errorunable to cast object of type someenumtype to type systemobjectcan anyone tell me what i am doing wrong,"['c#', '.net']" +293043,ask gdb to list all function in a program how can you list all functions in a program with gdb,['c'] +293072,showing progress in commandline application ok i am a bit embarrassed to ask such a simple thing but stilli have command line utility application and need to show progress to the useri could write progress into cout like thisstdcout 10nstdcout 20nstdcout 30n but as a result user will seesome line printed before102030 but what i really need is that percentage got updated like this at the beginningsome line printed before10 and after updatesome line printed before20 and after second updatesome line printed before30how should i achieve that,"['c++', 'c']" +293089,error setfilenullfalse call failed when using log4j i have added log4jproperties file in source folder of project but i am still getting a log4jerrorhere is my log4jproperties file rootcategorydebug r o stdout log4jappenderoorgapachelog4jconsoleappender log4jappenderolog44jlog file log4jappenderrorgapachelog4jrollingfileappender log4jappenderrfilelog4jlog control the maximum log file size log4jappenderrmaxfilesize100kb archive log files one backup file here log4jappenderrmaxbackupindex1 log4jappenderrlayoutorgapachelog4jpatternlayout log4jappenderolayoutorgapachelog4jpatternlayout log4jappenderrlayoutconversionpatterndiso86015p66rtx cmfl mn log4jappenderolayoutconversionpatterndiso86015p66rtx cmfl mn define the root logger with appender file logdir logs log4jrootlogger debug file define the file appender log4jappenderfileorgapachelog4jfileappender log4jappenderfilefilelogsfilename log4jappenderfileappendfalse define the layout for file appender log4jappenderfilelayoutorgapachelog4jpatternlayout log4jappenderfilelayoutconversionpatterndabsolute 5p c1l mn log4jappenderconsolelayoutorgapachelog4jpatternlayouthere is the java exception that i am gettinglog4jerror setfilenullfalse call failedjavaiofilenotfoundexception logs access is denied at javaiofileoutputstreamopennative method at javaiofileoutputstreaminitfileoutputstreamjava194 at javaiofileoutputstreaminitfileoutputstreamjava116 at orgapachelog4jfileappendersetfilefileappenderjava294 at orgapachelog4jfileappenderactivateoptionsfileappenderjava165 at orgapachelog4jconfigpropertysetteractivatepropertysetterjava307 at orgapachelog4jconfigpropertysettersetpropertiespropertysetterjava172 at orgapachelog4jconfigpropertysettersetpropertiespropertysetterjava104 at orgapachelog4jpropertyconfiguratorparseappenderpropertyconfiguratorjava809 at orgapachelog4jpropertyconfiguratorparsecategorypropertyconfiguratorjava735 at orgapachelog4jpropertyconfiguratorconfigurerootcategorypropertyconfiguratorjava615 at orgapachelog4jpropertyconfiguratordoconfigurepropertyconfiguratorjava502 at orgapachelog4jpropertyconfiguratordoconfigurepropertyconfiguratorjava547 at orgapachelog4jhelpersoptionconverterselectandconfigureoptionconverterjava483 at orgapachelog4jlogmanagerclinitlogmanagerjava127 at orgapachelog4jloggergetloggerloggerjava104 at libdashboardreportsinitreportsjava34 at testcasesamazondashboardtc db17maintc db17java54amazondashboardtc db17exception in thread main javalangnullpointerexception at testcasesamazondashboardtc db17maintc db17java131please let me know how to resolve this exception as i have tried placing my properties file in root folder and now i have placed in source folder but in both cases i got the above exception,['java'] +293130,jsdoc how do i document the options object literal for a parent class i am using jquerys widget base class which provides an option method since the method is not in my code i do not have a place to document the argumenti tried to put jsdoc on the fields in the default options literal but they are simply not picked up then i tried to use the class and lends tags on the same object literal but this may be quite confusing as the object literal is not really a classanother alternative i have experimented is to put something like param optionsfield description in the constructors jsdoc however this has the thisadvantage of separating the documentation from the code also the constructor do not actually have an argument called options as it is all handled by jqueryhow does you javascript gurus handle this should a new tag be proposed,['javascript'] +293151,kvo how to get a list of an objects registered observers i am registering an observer on a bunch of tableview controllers dynamically so i need to remove previous observers if they were registered on the same object to do this i need to check if the observer exists on the objectis this possible i know with nsnotification you can use the nsnotification center singleton but is this the same for kvo,"['iphone', 'ios']" +293152,python checking if a fork process is finished just wondering if some one could help me out the problem i am having is that i osfork to get several bits of information and send them to a file but checking to see if the fork process is not workingimport sysimport timeimport osimport readdress argv1sendbytes argv2proid2 osforkif proid2 0 ossystemping c 20 address teststuff2txt os exit0print proid2finn truewhile finn truetimesleep1finn ospathexistsproc strproid2print ospathexistsproc strproid2print eeup out of it strproid2i think that the ospathexists is maybe not the right thing to usethanks,['python'] +293186,set unicorn timeout i use rails 3011 ruby 193p0 nginx 104 and unicorn 362 for my project and i have got a problemi have to do longterm operation on my server it is about 150 seconds and it is okay in this casei have set up my nginx config in locationproxy read timeout 240proxy send timeout 240and set up my unicornrb file with commandtimeout 240but i always get 502 bad gateway errori think problem with unicorn i get this unicorn logse 20120521t115221052382 30423 error worker1 pid30871 timeout 104052329915s 60s killinge 20120521t115221080378 30423 error reaped procestatus pid 30871 sigkill signal 9 worker1i 20120521t115221105045 30423 info worker1 spawningi 20120521t11522148 894 info worker1 spawned pid894 i 20120521t115221659 894 info refreshing gem listcan you help me any help is appreciated thank you,"['ruby-on-rails', 'ruby']" +293236,java 7 and could not generate dh keypair i read a previous post regarding the error could not generate dh keypair fired when the server sents a key longer than 1024 bits downloading the jce unlimited jars should fix this issue in the test environment i have i encountered the following for the same web server if i use java 6 i do not get any errors when performing the https query but if i use java 7 then i get could not generate dh keypairi tried replacing the jar files for jce unlimited but still get the same error the bug is reported since 2007 but why does it run for java 6 and not for java 7 are the files to download not the proper ones i got the link from a previous post java why does ssl handshake give could not generate dh keypair exceptionat this point i do not know what to do if i try to load the bouncycastle provider i get an arrayoutofindex exception my server only allows dh algorithm so i cannot use another algorithm like suggested in the above post,['java'] +293248,how to extend an object while ignoring null values say for example i have an object ofvar user name dan age 27 hobbies null which i would like to merge onto the following base object so that my user object will have all the required propertiesvar base name null height null age null hobbies name tennis location null name football location null name rugby location null the easiest way to merge to the two objects would be to extend the base object with the user object as followsextendtrue base userwhich would modify the base object to be name dan height null age 27 hobbies nullmy question would be how can i get the extend method to not override null values for example in this instance how can i still obtain a list of hobbies if the users hobby list is null so i end up with the following name dan height null age 27 hobbies name tennis location null name football location null name rugby location null,"['javascript', 'jquery']" +293257,taskfactorystartnew or parallelforeach for many longrunning tasks possible duplicateparallelforeach vs taskfactorystartnew i need to run about 10 tasks in a threadpool on a nightly basis the number may grow in the future each task is performing a long running operation reading data from a web service and is not cpu intensive async io is not an option for this particular use casegiven an iliststring of parameters i need to dosomethingstring x i am trying to pick between the following two optionsilisttask tasks new listtaskforeach var p in parameters tasksaddtaskfactorystartnew dosomethingp taskcreationoptionslongrunningtaskwaitalltaskstoarrayorparallelforeachparameters new paralleloptions maxdegreeofparallelism environmentprocessorcount32 dosomethingwhich option is better and whynote the answer should include a comparison between the usage of taskcreationoptionslongrunning and maxdegreeofparallelism environmentprocessorcount someconstant,"['c#', '.net']" +293259,moving from multiprocessing to threading in my project i use the multiprocessing class in order to run tasks parallely i want to use threading instead as it has better performance my tasks are tcpip bound not cpu or io boundmultiprocessing has wonderful functions as poolimap unordered and poolmap async that does not exist in the threading classwhat is the right way to convert my code to use threading instead the documentation introduces the multiprocessingdummy class that is a wrapper for the threading class however that raises lots of errors at least on python 273 pool multiprocessingpoolprocesses file cpython27libmultiprocessingdummy init py line 150 in pool return threadpoolprocesses initializer initargs file cpython27libmultiprocessingpoolpy line 685 in init pool init self processes initializer initargs file cpython27libmultiprocessingpoolpy line 136 in init self repopulate pool file cpython27libmultiprocessingpoolpy line 199 in repopulate pool wstart file cpython27libmultiprocessingdummy init py line 73 in start self parent childrenself noneattributeerror dummythread object has no attribute childrenedit what actually happens is that i have a gui that runs a different thread to prevent the gui from gettint stuck that thread runs the specific search function that has the threadpool that failsedit 2 the bugfix was fixed and will be included in future releasesgreat to see a crasher fixedimport urllib2 htmllib formatterimport multiprocessingdummy as multiprocessingimport xmldomminidomimport osimport string randomfrom urlparse import parse qs urlparsefrom useful util import retryimport configfrom logger import logclass linksextractorhtmllibhtmlparser def init self formatter htmllibhtmlparser init self formatter selflinks selfignoredsites configwebparser ignoredsites def start aself attrs for attr in attrs if attr0 href and attr1endswithmp3 if not filterlambda x x in attr1 selfignoredsites selflinksappendattr1 def get linksself return selflinksdef getlinksurl returnmetaurlobjfalse function gather links from a url param url url address param returnmetaurlobj if true returns a metaurl object list else returns a string list default is false return links look up htmlparser linksextractorformatternullformatter try data urllib2urlopenurl except urllib2httperror urllib2urlerror as e logerrore return htmlparserfeeddataread htmlparserclose links listsethtmlparserget links if returnmetaurlobj links mapmetaurl links return linksdef isasciis function checks is the string is ascii try sdecodeascii except unicodeencodeerror unicodedecodeerror return false return trueretryexception loggerlogdef parsesong source function parses the source search page and returns the mp3 links in it param song search string param source search website source value can be dilandau mp3skull youtube seekasong return links mp3 url links source sourcelower if source dilandau return parse dilandausong elif source mp3skull return parse mp3skullsong elif source seekasong return parse seekasongsong elif source youtube return parse youtubesong logerrorno source s from parse function in webparser return def parse dilandausong pages1 function connects to dilandaueu and returns the mp3 links in it if not isasciisong dilandau does not like unicode logwarningsong is not ascii skipping on dilandau return links song urllib2quotesongencodeutf8 for i in rangepages url musicsdhtml songreplacereplace replaceloweri1 logdebugdilandau parsing s url linksextendgetlinksurl returnmetaurlobjtrue logdebugdilandau found d links lenlinks for metaurl in links metaurlsource dilandau return linksdef parse mp3skullsong pages1 function connects to mp3skullcom and returns the mp3 links in it links song urllib2quotesongencodeutf8 for i in rangepages i met your motherhtml url songreplacereplace replace lower logdebugmp3skull parsing s url linksextendgetlinksurl returnmetaurlobjtrue logdebugmp3skull found d links lenlinks for metaurl in links metaurlsource mp3skull return linksdef parse seekasongsong function connects to seekasongcom and returns the mp3 links in it song urllib2quotesongencodeutf8 url songreplacereplace replace lower logdebugseekasong parsing s url links getlinksurl returnmetaurlobjtrue for metaurl in links metaurlsource seekasong logdebugseekasong found d links lenlinks return linksdef parse youtubesong amount10 function searches a song in youtubecom and returns the clips in it using youtube api param song the search string param amount amount of clips to obtain return links list of links function connects to youtubecom and returns the mp3 links in it song urllib2quotesongencodeutf8 url rmaxresultsdv2 songreplace amount urlobj urllib2urlopenurl timeout4 data urlobjread videos xmldomminidomparsestringdatagetelementsbytagnamefeed0getelementsbytagnameentry links for video in videos youtube watchurl videogetelementsbytagnamelink0attributesitem0value linksappendget youtube hightest quality linkyoutube watchurl return linksdef get youtube hightest quality linkyoutube watchurl priorityconfigyoutube quality priority function returns the highest quality link for a specific youtube clip param youtube watchurl the youtube watch url param priority a list represents the qualities priority return metaurlobj metaurl object video id parse qsurlparseyoutube watchurlqueryv0 youtube embedded watchurl video id d get youtube dl linksvideo id for x in priority if x in dkeys return metaurldx0 youtube dvideoname x youtube embedded watchurl logerrorno youtube link has been found in get youtube hightest quality link return retryexception loggerlogdef get youtube dl linksvideo id function gets the download links for a youtube clip this function parses the get video info format of youtube param video id youtube video id return d a dictonary of qualities as keys and urls as values d url r video infovideo idselvevo video id urlobj urllib2urlopenurl timeout12 data urlobjread data urllib2unquoteurllib2unquoteurllib2unquotedata data datareplaceurl nurl data datasplitn for line in data if timedtext in line or statusfail in line or adbreaks in line continue try url linesplitquality0spliturl1 quality linesplitquality1split0 except continue if quality in d dqualityappendurl else dquality url try videoname joindatasplittitle1split0 except exception e logerrorcould not parse videoname out of get video info s stre videoname videoname unicodevideoname utf8 dvideoname videonamereplace replace return dclass nextlistobject a list with a next method def init self l selfl l selfnext index 0 def nextself if selfnext index lenselfl value selflselfnext index selfnext index 1 return value else return none def iseofself checks if the list has reached the end return selfnext index lenselflclass metaurlobject a url strecture data with many metadata def init self url source videoname quality youtube watchurl selfurl strurl selfsource source selfvideoname videoname youtube links only selfquality quality youtube links onlys selfyoutube watchurl youtube watchurl youtube links onlys def repr self return metaurl s s selfurl selfsourcedef searchsong n processesconfigsearch processes function searches song and returns and valid mp3 links param song search string param n number of songs param processes number of processes to launch in the subprocessing pool linksfromsources pool multiprocessingpoolprocesses args song source for source in configsearch sources imapobj poolimap unordered parse star args for i in rangelenargs linksfromsourcesappendnextlistimapobjnext15 poolterminate links next source 0 while lenlinks and and not allmaplambda x xiseof linksfromsources nextitem linksfromsourcesnext sourcenext if nextitem logdebugadded song 80s from source id d s nextitemurlsplit1 next source nextitemsource linksappendnextitem if lenlinksfromsources next source1 next source 0 else next source 1 return linksdef parse starargs return parseargs,['python'] +293269,how to perform a faceted search i would like to know how to perform a faceted search using lucenefacet i will explain exactly what i want to do i have got a taxonomy of htmlfiles similar to odp and i want that given a query thisplay results by categories and number of hits per category is there any example describing that with luceneedit i already get results as categories by adding a category field in each document what i want is that results appear ascat1 n1cat2 n2 instead ofcat1cat1 xn1 timescat1cat2 xn2 timescat2also this category field only refers to a level of the taxonomy tree and i want to exploit the taxonomy structure by for example being able to select the depth of the search in the taxonomy i do not know if this is clear thank you,['java'] +293321,get xml only immediate children elements by name my question is how can i get elements directly under a specific parent element when there are other elements with the same name as a grandchild of the parent elementi am using the java dom library to parse xml elements and i am running into trouble heres some a small portion of the xml i am usingnotifications notification groups group namezipgroupzip ziptrue file locationcvaliddirectory file locationcanothervalidfiledoc file locationcvalidfileheretxt group groups file locationcvalidfiletxt file locationcvalidfilexml file locationcvalidfiledoc notificationnotificationsas you can see there are two places you can place the file element either in groups or outside groups i really want it structured this way because it is more userfriendlynow whenever i call notificationelementgetelementsbytagnamefile it gives me all the file elements including those under the group element i handle each of these kinds of files differently so this functionality is not desirablei have thought of two solutionsget the parent element of the file element and deal with it accordingly depending on whether it is notification or grouprename the second file element to avoid confusionneither of those solutions are as desirable as just leaving things the way they are and getting only the file elements which are direct children of notification elementsi am open to impo comments and answers about the best way to do this but i am really interested in dom solutions because that is what the rest of this project is using thanks,['java'] +293336,how do i get difference between two dates in android tried every thing and post i saw all the post in here and still i cannot figure how do get difference between two android datesthis is what i dolong diff date1gettime date2gettimedate diffdate new datediffand i get the date is jan 1 1970 and the time is always bigger in two hoursi am from israel so the two hours is timeoffsethow can i get normal difference,"['java', 'android']" +293340,is it a good practice to declare variables final wherever possible possible duplicatewhen should one use final i tend to declare all variables final unless necessary i consider this to be a good practice because it allows the compiler to check that the identifier is used as i expect eg it is not mutated on the other hand it clutters up the code and perhaps this is not the java wayi am wondering if there is a generally accepted best practice regarding the nonrequired use of final variables and if there are other tradeoffs or aspects to this thiscussion that should be made aware of,['java'] +293343,activerecord argumenterror negative string size or size too big i have been working with this one for a few days heres the activerecord error and the application traceargumenterror negative string size or size too big exec sp executesql nselect ops jobs join from ops jobs join where work center id nm1053 or work center id nm1035 or work center id nm1037 or work center id nm1036 and status nc and start date n and start date n20120516 and comp date n20120527 and work order not like nla order by work center id asc start date asc starting shift num asc status asc priority asc comp date asc ending shift num asc due date asc sequence number ascit turns out if i call opall i get this erroractiverecord argumenterror negative string size or size too bigif i ignore the column that uses may contain unicode characters it works fine all the data is being stored in the database without a problem but for some reason rails3 is not having it some where clauses will return records while others result in the same erroractiverecordsqlserveradapter 324 libactive recordconnection adapterssqlserverdatabase statementsrb421in fetch allit is similar to these two postsactiverecordstatementinvalid argumenterror negative string size or size too big select from shopactiverecord doesnt work on one tableit seems like the solution in the first post is to change the gem which i would like to avoid i looked at my table and i do not think i am using any keywords as field names i use other queries similar to this one and they work fine the only difference is the values i use in the where clause work center id nm1053,['ruby-on-rails'] +293360,why does module pattern create a singleton when i try and make different instances of this module it does not workit seems to be a singleton i can only have one instance at a timewhat mechanism limits the constructor function publik to only have on instancevar module function var publik function publikprototypetest publikprototypeget function documentgetelementbyid atest innerhtml test publikprototypeset function value test value return publik var object1 new modulevar object2 new moduleobject1set1object2set2object1getobject2get,['javascript'] +293368,check user name and password on database script included i posted my question here and before i edited the post it was closed as not a real questioni have a login form like thishtml head titlepassword checking scripttitle head body form actioncheck userpassphp methodpost h3please loginh3 user name input typetext nameuser namebr password input typepassword namepassword input typesubmit namesubmit valuelogin form bodyhtmlas you see this form authenticates the user through check userpassphpit looks for those credentials on my database if they exist returns ok else returns value noso my question is exactly what code should i include in check userpassphpi tried to add more code but could not do that as well my current code isphpob starthost host name username mysql username password mysql password db name database name tbl name table name connect to server and select databsemysql connecthost username password or diemysql errorecho connected to mysqlbr mysql select dbdb name or diemysql errorecho connected to databasebr check username and password ifempty postusername echo usernamepassword is empty return falseifempty postpassword echo password is empty return false define username and password username postusername passwordmd5 postpass to protect mysql injection more detail about mysql injectionusername stripslashesusernamepassword stripslashespasswordusername mysql real escape stringusernamepassword mysql real escape stringpasswordsqlselect from tbl name where usernameusername and passwordpasswordresultmysql querysql mysql num row is counting table rowcountmysql num rowsresult if result matched username and password table row must be 1 rowif count1 echo success count else echo unsuccessful countob end flush,"['php', 'sql']" +293380,php how to check if at least one element of first array exists in second array i have two arrays arrayblue yellow and arrayblue green red purple is there a function that will check if those two arrays have at least one element value in common blue just return true or false,['php'] +293385,invoke a callback at the end of a transition i need to make a fadeout method similar to jquery using d3js what i need to do is to set the opacity to 0 using transitiond3selectmyidtransitionstyleopacity 0the problem is that i need a callback to realize when the transition has finished how can i implement a callback,['javascript'] +293407,expand macro inside doxygen comment for printing out software version i have some c code base documented with doxygen and build with gnu makeversion information is centralized in makefile where i have something likeversion1234in my makefile the cflags add the following definecflags dapp versionversionthis enables me to get the version in code like thisdefine str expandtok tokdefine strtok str expandtokint main cout software version is strapp version endlnow what i would like is to have this in the doxygenproduced html filescurrent version of software is 1234i managed to export the makefile variable into the doxygen configuration file withedit doxygen is called from makefile through a makedoc targetpredefined app versionversionbut then if i try in the doxygen mainpage command something like this it fails because of course macro names do not get expanded in commentsmainpage this is the doccurrent version is app version or is app versionquestionsdo you know of a way to expand that macro in the doxygen comments this could be done by some sed processing on the file holding the comment in the makefile but maybe this can be solved directly with doxygen how do other projects handle versioning besides automatic versioning tool that vcs provide i mean in a way that the version id is uniquely defined in a file so it can be fetched both by software build system and documentation build systemrelated how to thisplay a defined value,['c++'] +293428,source for a good simple soft modem library i a doing a weird project and looking to convert some short simple datagrams to audio send them over a physical radio then to receive and decode them on another device think embedded devices with audio out jack and gsmgprstype radiosi have to use a physical existing external radiodoes anyone know of a good simple software modem library good for such a project i am not so concerned about data rate and would prefer simplicity over functionality even something akin to a basic 1200 baud modem would be fantasticlooking at this more of a learning experience and potential building block rather than anything horribly practical,['iphone'] +293430,how to pass a boolean from javascript to python the following seems to pass a string instead of a boolean value how would i pass a booleanpostajaxwarning message active false function return def warning messagerequest active requestpostgetactive print active return httpresponse,"['javascript', 'python']" +293444,how does one upload a txt file in php and have it read line by line on another page my objective here is to upload a txt file on a form browse post the file to another php page and then have that file read line by linemy code so far is herefile 1 html uploadform actiontestparsephp methodpost enctypemultipartformdata label forfilefilenamelabel input typefile namefile idfileinput typesubmit valuesubmitformfile 2 reading the file if filesfileerror 0echo error filesfileerror br elseif filesfiletype textplainecho file must be a txtelsefile handle fopen filesfilename rbas i see it the second file would verify that there is no error and that the uploaded file is a txt it would then fopen the file and i would then be able to read with fgets i have managed to get all this to workhowever this code only works if the txt file that is being uploaded happens to be in the same directory as the php file otherwise i get lots of error messages and when you cannot upload a file that is not in the php files folder it defeats the purpose of having a file upload system in the first placecan someone tell me what is wrong with this code,['php'] +293450,ruby constant lookup this is probably a simple question but i am trying to lookup the constant name in ruby from the value for exampleclass xyz activerecordbase active 1 pending 2 canceled 3 sent 4 suspended 5endi have a status of 1 in my db i want to retrieve active based on this so that i can thisplay it in a viewwhats a good way to do that,"['ruby-on-rails', 'ruby']" +293475,less css background with relative path i am facing with a problem when using less as stylesheet for my website personally i would rather use relative path in css than an absolute path only my habit but now when i use less with importing feature i have a problem as the following demonstratesi have a mainless file in root folderimport incinclessand a file incless in folder inchomebgr background urliconshomegifthe image homegif is in folder rootincicons mainless inc incless icons homegifwith lessc output is homebgr background urliconshomegifhowever my expectation ishomebgr background urlinciconshomegifif i use lessjs as client compiler i got the output as expected however if i use lessc i do nothas anyone had the same problem and has a solution for this or really any suggestions on how to get this working thanks in advance,['css'] +293500,appears empty in chrome when browsing my website with last version of google chrome and using f12 to look into the source all the content between head and head appears emptyon last versions of firefox and ie everything appears correcylyactually the content is moved into the body on google chromeit is obviously not a css problem i am using twitter bootstrap css and js and a mvc php framework someone has a hinthere is my documenthtml pagedoctype htmlhtml langfrheadmeta httpequivcontenttype contenttexthtml charsetutf8meta nameviewport contentwidthdevicewidth initialscale10 meta httpequivxuacompatible contentieedge titlephp echo templatetitre titlephp foreachtemplatemeta as keyvalue meta namephp echo key contentphp echo value php endforeach link relshortcut icon hrefphp echo web assetsstylefaviconico typeimagexicon link relstylesheet hrefphp echo web assetsstylebootstrapmincss link relstylesheet hrefphp echo web assetsstylebootstrapresponsivemincss link relstylesheet hrefphp echo web assetsstylemaincss link href relstylesheet typetextcssif lt ie 9script srchtml5shivgooglecodecomsvntrunkhtml5jsscriptendifhead bodyphp require templatechild and the viewed source by firebughtml langfrheadheadbodymeta httpequivcontenttype contenttexthtml charsetutf8meta nameviewport contentwidthdevicewidth initialscale10meta httpequivxuacompatible contentieedgetitleveloccasion valos doccasion dans toute la francetitlemeta namekeywords contentvelos doccasion velos dans toute la france velos occasion toute la france velo occasion velometa namedescription contentpetites annonces de velos doccasion dans toute la france velo doccasion a vendre toute la francemeta nameauthor contentveloccasionlink relshortcut icon hrefassetsstylefaviconico typeimagexicon link relstylesheet hrefassetsstylebootstrapmincss link relstylesheet hrefassetsstylebootstrapresponsivemincss link relstylesheet hrefassetsstylemaincss link href relstylesheet typetextcssif lt ie 9script srchtml5shivgooglecodecomsvntrunkhtml5jsscriptendifsection idmaincontainerdiv classcontaineredit problem solved notepad was encoding in utf8 i changed to ansi and worked fine,"['php', 'html']" +293527,does spring data jpa have any way to count entites using method name resolving spring data jpa supports counting entities using specifications but does it have any way to count entities using method name resolving let us say i want a method countbyname to count entities with specific name just like a method findbyname to fetch all entities with specific name,['java'] +293529,android listview lazy loading i want to do some stuff i wanna do lazy loading in listview my listview contain more than 10 data only in textview so i cannot load all that data in first time when i launch list activity it is not efficient so i can load first 20 or 30 items in list further the rows of the listview are loaded when i scroll over them so when i reach at last index of listview on last index i will put progressbar and it will note that the new data are loaded so at that time new data will be load with last 1 index how can i do this,['android'] +293546,appdomainfirstchanceexception and stack overflow exception i am using the firstchanceexception event to log details about any thrown exceptionsstatic void mainstring args appdomaincurrentdomainfirstchanceexception sender eventargs consolewritelineinside first chance exception throw new exceptionexception thrown in mainthis works as expected but if an exception is thrown inside the event handler a stack overflow will occur since the event will be raised recursivelystatic void mainstring args appdomaincurrentdomainfirstchanceexception sender eventargs throw new exceptionstackoverflow throw new exceptionexception thrown in mainhow do i handle exceptions that occur within the event handleredit there is a few answers suggesting that i wrap the code inside the event handler in a trycatch block but this does not work since the event is raised before the exception can be handledstatic void mainstring args appdomaincurrentdomainfirstchanceexception sender eventargs try throw new exceptionstackoverflow catch throw new exceptionexception thrown in main,['c#'] +293559,force ssl with expressjs 3 i am running a nodejs express 3 server with no proxies and using ssli am trying to figure out how to force all connections to go through httpsgoogle searching shows me thistopicexpressjsbm6yozgodsythere is currently no way to force https redirects though that seems like a bit of a strange workaround we have an httpsonly app and we just have a simple 4 line node http server that redirects nothing fancywhich is what i need but he does not say what those 4 lines arehow do we do this thanks,['javascript'] +293578,upload external file to aws s3 bucket using php sdk i want to upload a file from an external url directly to an amazon s3 bucket using the php sdk i managed to do this with the following codes3 new amazons3response s3create objectbucket destination array fileupload source length remote filesizesource contenttype imagejpeg where the function remote filesize is the followingfunction remote filesizeurl ob start ch curl initurl curl setoptch curlopt header 1 curl setoptch curlopt nobody 1 ok curl execch curl closech head ob get contents ob end clean regex contentlengths09s count preg matchregex head matches return issetmatches1 matches1 unknownhowever it would be nice if i could skip setting the filesize when uploading to amazon since this would save me a trip to my own server but if i remove setting the length property in the s3create object function i get an error saying that the the stream size for the streaming upload cannot be determined any ideas how to solve this problem,['php'] +293581,android javalangsecurityexception connection refused im new to uicc and secure elements and i tried to do a simple android application using this tutorial androidwikiusingsmartcardapi to connect the secure elements when i run the application it throw an javalangsecurityexception connection refused please help thanks codepublic void oncreatebundle savedinstancestate final string log tag hellosmartcard superoncreatesavedinstancestate linearlayout layout new linearlayoutthis layoutsetlayoutparamsnew layoutparams layoutparamswrap content layoutparamswrap content button button new buttonthis buttonsetlayoutparamsnew layoutparams layoutparamswrap content layoutparamswrap content buttonsettextclick me buttonsetonclicklistenernew onclicklistener public void onclickview v try logdlog tag retrieve available readers reader readers seservicegetreaders if readerslength 1 return logdlog tag create session from the first reader session session readers0opensession logdlog tag create logical channel within the session channel channel sessionopenlogicalchannelnew byte byte 0xd2 0x76 0x00 0x01 0x18 0x00 0x02 byte 0xff 0x49 0x50 0x25 byte 0x89 byte 0xc0 0x01 byte 0x9b 0x01 logdlog tag send helloworld apdu command byte respapdu channeltransmitnew byte byte 0x90 0x10 0x00 0x00 0x00 channelclose parse response apdu and show text but remove sw1 sw2 first byte hellostr new byterespapdulength 2 systemarraycopyrespapdu 0 hellostr 0 respapdulength 2 toastmaketextmainactivitythis new stringhellostr toastlength longshow catch exception e logelog tag error occured e return layoutaddviewbutton setcontentviewlayout try logilog tag creating seservice object seservice new seservicethis this catch securityexception e logelog tag binding not allowed usespermission orgsimallianceopenmobileapismartcard catch exception e logelog tag exception egetmessage logcat0522 081149669 ehellosmartcard6691 error occured0522 081149669 ehellosmartcard6691 javalangsecurityexception connection refused 0522 081149669 ehellosmartcard6691 at orgsimallianceopenmobileapiseservicecheckforexceptionseservicejava6110522 081149669 ehellosmartcard6691 at orgsimallianceopenmobileapiseserviceopenlogicalchannelseservicejava4790522 081149669 ehellosmartcard6691 at orgsimallianceopenmobileapisessionopenlogicalchannelsessionjava1430522 081149669 ehellosmartcard6691 at comgieseckedevrientandroidhellosmartcardmainactivity1onclickmainactivityjava500522 081149669 ehellosmartcard6691 at androidviewviewperformclickviewjava24850522 081149669 ehellosmartcard6691 at androidviewviewperformclickrunviewjava90800522 081149669 ehellosmartcard6691 at androidoshandlerhandlecallbackhandlerjava5870522 081149669 ehellosmartcard6691 at androidoshandlerthispatchmessagehandlerjava920522 081149669 ehellosmartcard6691 at androidoslooperlooplooperjava1300522 081149669 ehellosmartcard6691 at androidappactivitythreadmainactivitythreadjava37680522 081149669 ehellosmartcard6691 at javalangreflectmethodinvokenativenative method0522 081149669 ehellosmartcard6691 at javalangreflectmethodinvokemethodjava5070522 081149669 ehellosmartcard6691 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava8780522 081149669 ehellosmartcard6691 at comandroidinternaloszygoteinitmainzygoteinitjava6360522 081149669 ehellosmartcard6691 at dalviksystemnativestartmainnative methodmanifestxml version10 encodingutf8manifest xmlnsandroid packagecomgieseckedevrientandroidhellosmartcard androidversioncode1 androidversionname10 usessdk androidminsdkversion10 usespermission androidnameorgsimallianceopenmobileapismartcard usespermission androidnameandroidpermissioninternet application androidicondrawableic launcher androidlabelstringapp name activity androidnamemainactivity androidlabelstringapp name intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity useslibrary androidnameorgsimallianceopenmobileapi androidrequiredfalse applicationmanifest,['android'] +293584,check if an array of objects have a key value using underscore how can check if an array of objects have a key value using underscoreexamplevar objects id1 namefoo id2 namebarcheckobjects name foo truei think it should be made using map mapobjects functionnum key consolelognumname,['javascript'] +293585,how to convert a pdf page to an image in android possible duplicatehow to convert pdf into image all i need to do is take a locally saved pdfdocument and convert one or all of it is pages to image format like jpg or pngi have tried lots of pdf renderingviewing solutions like apv pdf viewer apdfviewer droidreader androidpdf mupdf and many others but could not figure it out so far that how to convert a pdfpage into imageedit also i would rather have a pdf to image converter than a pdf renderer that i need to edit to convert pdf to image,"['java', 'android']" +293589,what happened between march 28th and march 29th 1976 with the javautilgregoriancalendar trying to use the gregoriancalendar i got stuck on a singularity while computing the number of days since a particular datein the scala interpreter i entered scalaimport javautilgregoriancalendarscalaimport javautilcalendarscalaval datetoday new gregoriancalendar2012calendarmay22gettimeinmillisdatetoday long 133763760scalaval days1 datetoday new gregoriancalendar1976calendarmarch28gettimeinmillis 10360024days1 long 13203scalaval days2 datetoday new gregoriancalendar1976calendarmarch29gettimeinmillis 10360024days2 long 13203i do not know if the fact that 1976 is a leap year matters but days1 and days2 should have been separated by 1 this is the only moment in history since 1970 that this singularity happenswanting to know what is going on i compute the difference between the two dates previously mentionned and it gives me only exactly 23 hours of difference what happened on that date wikipedia apparently says nothing about itand even more important how to compute the real number of days since a particular date,['java'] +293635,how to have multiple databind attributes on one element i need to have multiple data bindings on one element for example i want a href as well as a html databinding on one a tag i have tried thisa databindhtml name databindattr href url databindattr dataprop xyz abut this does not work it seems knockout only supports binding one databind property how to bind both the href the inner html and a custom dataprop attribute on one element,"['javascript', 'jquery']" +293662,how to validate numericality and inclusion while still allowing attribute to be nil in some cases in a rails app i have several integer attributes on a model a user should be able to create a record and leave these attributes blankor if the user enters values for these attributes they should be validated for numericality and within a certain rangein the model i have something like thisvalidates presence of name validates numericality of a only integer true message can only be whole numbervalidates inclusion of a in 19 message can only be between 1 and 9if i now test with the minimum required attributes to savefactory model do sequencename n modeln endit should save with minium attributes do model factorygirlbuildmodel modelsaveshould falseendi get validation failed a can only be whole number a can only be between 1 and 9how can i validate numericality and inclusion only if a value is given for a while still allowing a to be nil in some casesthanks,['ruby-on-rails'] +293671,phonegap android swipe navigation in phonegap i am making an phonegap app for the android platform in this app i want swipe navigation within multiple html pages please tell me how i can do thiseither it is done in single html page or i have to create multiple html page for this swipe navigationthanks in advancepreet,['android'] +293682,winrt app to enumerate files outside libraries and known folders i am working on a metro app that shows the content of a given folder in a listview controlms decided that developers do not need the systemiodirectory class and removed it entirely from the framework i am looking for a replacement to enumerate files in c in a metro style app i have checked all the enumeration samples provided by ms and they all seem to only enumerate the windows libraries using the knownfolders class something likestoragefolder picturesfolder knownfolderspictureslibraryand calling the getfilesasync or getfoldersasync methods depending on your needs these are all gold if i wanted to enumerate only inside the pictures or music library however i am looking to enumerate files on directories that are not included in a libraryanyone knows how this is possible in winrt,['c#'] +293686,recaptcha custom form parameter names is possible to customize recaptcha form parameters recaptcha challenge field and recaptcha response field so that they are called differentlybasically i want the form parameter recaptcha challenge field to be called captchaidand recaptcha response field to be called captchauserresponsei want them renamed so i can abstract the captcha implementation when a request arrives onpost mysiteusersignupi do not want to bother with captcha implementation recaptcha or something else in the future extracting the right parameters for the right captcha implementation i want to unify those parameter namesnow my request looks like thispost mysiteusersignup http11host localhost80connection keepalivecontentlength 416cachecontrol maxage0origin httplocalhost80useragent mozilla50 windows nt 61 wow64 applewebkit5365 khtml like gecko chrome190108446 safari5365contenttype applicationxwformurlencodedaccept texthtmlapplicationxhtmlxmlapplicationxmlq09q08referer httplocalhost8080mysitesignupformhtmlacceptencoding gzipdeflatesdchacceptlanguage enusenq08hrq06acceptcharset iso88591utf8q07q03emailtestuser40gmailcomusernametestuserpasswordtestpassword2testforenametestsurnameuserrecaptcha challenge fieldgoogle generated challangerecaptcha response fielduser typed captcha answersubmitsubmitbut i want it to look like thispost mysiteusersignup http11host localhost80connection keepalivecontentlength 416cachecontrol maxage0origin httplocalhost80useragent mozilla50 windows nt 61 wow64 applewebkit5365 khtml like gecko chrome190108446 safari5365contenttype applicationxwformurlencodedaccept texthtmlapplicationxhtmlxmlapplicationxmlq09q08referer httplocalhost8080mysitesignupformhtmlacceptencoding gzipdeflatesdchacceptlanguage enusenq08hrq06acceptcharset iso88591utf8q07q03emailtestuser40gmailcomusernametestuserpasswordtestpassword2testforenametestsurnameusercaptchaidgoogle generated challangecaptchauserresponseuser typed captcha answersubmitsubmitan elegant way would be to specify those form parameter names like thisscript var recaptchaoptions recaptcha challenge field formparam name captchaid recaptcha response field formparam name captchauserresponse scriptif this is not possible what workaround do you suggest,['javascript'] +293689,what does the symbol mean in css possible duplicatesize in css with slash i just saw some css code like this can some please tell me what the symbol means and if there are any best practices governing it is usage font 2px3pxedithere is the entire code block to give contextfunky font 2px3px fontfamily fantasy fontsize 30em fontweight bold,['css'] +293741,how to use generic class with specific objects in a static context i am gonna try to explain at my besti use play framework 2 and i will do a lot of crud actions some of them will be identitcal so i would like to kiss and dry so at first i was thinking about an abstract class containing the list details create update and delete methods with generic object and extend this class by specifying which object to use model form public abstract class crudcontroller extends controller protected static modelfinderlong model finder null protected static formmodel form null public static result list some code here public static result detailslong id some code here public static result create some code here public static result updatelong id some code here public static result deletelong id some code here and a class that will use crud public class cities extends crudcontroller protected static modelfinderlong city finder cityfind protected static formcity form formcityclass i can override a method in order to change it is behavior public static result list some different code here like adding some where condition this would work if i was not in a static contextbut since it is the case how can i do,['java'] +293742,check if value exists in datatable i have datatable with two columns author booknamei want to check if given string value author already exists in datatable is there some built in method to check it like for arrays arraycontains,['c#'] +293758,changing a labels text in another form in c i have a label called labelx1 this is on form2 on form1 i have a button i want the buttons text to be transferred to the other forms label i have tried form2 frm2 new form2frm2labelx1text thisbutton1textbut it does not work is there an easy straight forward way of doing this,['c#'] +293812,aspnet publish trying to copy a nonexistant file i am trying to publish an aspnet project in vs2010 and am getting the following errorcopying file binckfinderpdb to objreleasepackagepackagetmpbinckfinderpdb failed could not find file binckfinderpdbi had tried using a trial version of ckfinder with ckeditor but i backed it out i removed all references to ckfinder including the folders and the references or so i thoughti have tried looking this error up and have come up empty this is getting frustratingwhy is this error coming up ideasthanks in advance,['asp.net'] +293829,how to detect when a page exits fullscreen i am creating a 3d multiplayer game with threejs where players can join various existing games once play is clicked the renderer is appended to the page and fullscreens this works great but the problem is that when i exit the fullscreen it still stays appended i would like to remove it but i do not know whenso basically i am looking for an event that says this element exited fullscreenthis is how i append the renderer to the pagecontainer documentgetelementbyidcontainerdocumentbodyappendchildcontainervar renderer new threewebglrendererantialias truerenderersetsize width heightcontainerappendchild rendererdomelement this if how i fullscreen itthreexfullscreenrequestcontainer renderersetsizescreenwidth screenheightalso is there a way to stop that annoying header from appearing whenever someone points his mouse to the top of the page and i guess i can just prevent escape from doing what it does exiting fullscreen in firefox and chrome with preventdefaultand also does anyone know why is firefox so much slower than chrome in 3d rendering i mean i am using webgl this means that the gpu is being usededitthe fullscreenchange event is indeed fired but it has different names under different browsers for example on chrome it is called webkitfullscreenchange and on firefox it is mozfullscreenchange,"['javascript', 'html']" +293846,eclipse content assist error lately i have been having more and more issues with the content assist in eclipse in some of my projects i get no proposals from the content assist and in other projects i get some or all of the expected proposals typically there is no error in eclipse but here is an example of one when i do get an errorcontent assist did not complete normally please see the log for more information pb324 the type androidsupportv4apploadermanagerloadercallbacks cannot be resolved it is indirectly referenced from required class filesi have tried the various suggestions including but not limited to the two below from similar questions with no luck i have even gone as far as removing and reinstalling eclipse and recreating the projects without any of the eclipse metadata or settingseclipse content assist not working with androideclipsejava code completion not workingany help is greatly appreciatedeclipse sdkversion 372build id m201202080800android development toolkitversion 1800v201203301601306762error logentry orgeclipseui 4 0 20120522 092534061message pb324 the type androidsupportv4apploadermanagerloadercallbacks cannot be resolved it is indirectly referenced from required class filesstack 0orgeclipsejdtinternalcompilerproblemabortcompilation pb324 the type androidsupportv4apploadermanagerloadercallbacks cannot be resolved it is indirectly referenced from required class files at orgeclipsejdtinternalcompilerproblemproblemhandlerhandleproblemhandlerjava121 at orgeclipsejdtinternalcompilerproblemproblemhandlerhandleproblemhandlerjava179 at orgeclipsejdtinternalcompilerproblemproblemreporterhandleproblemreporterjava2062 at orgeclipsejdtinternalcompilerproblemproblemreporterisclasspathcorrectproblemreporterjava4039 at orgeclipsejdtinternalcompilerlookupunresolvedreferencebindingresolveunresolvedreferencebindingjava54 at orgeclipsejdtinternalcompilerlookupbinarytypebindingresolvetypebinarytypebindingjava122 at orgeclipsejdtinternalcompilerlookuplookupenvironmentgettypefromtypesignaturelookupenvironmentjava1335 at orgeclipsejdtinternalcompilerlookupbinarytypebindingcreatemethodbinarytypebindingjava536 at orgeclipsejdtinternalcompilerlookupbinarytypebindingcreatemethodsbinarytypebindingjava638 at orgeclipsejdtinternalcompilerlookupbinarytypebindingcachepartsfrombinarytypebindingjava365 at orgeclipsejdtinternalcompilerlookuplookupenvironmentcreatebinarytypefromlookupenvironmentjava688 at orgeclipsejdtinternalcompilerlookuplookupenvironmentcreatebinarytypefromlookupenvironmentjava667 at orgeclipsejdtinternalcodeassistimplengineacceptenginejava60 at orgeclipsejdtinternalcompilerlookuplookupenvironmentaskfortypelookupenvironmentjava142 at orgeclipsejdtinternalcompilerlookuppackagebindinggettypeorpackagepackagebindingjava183 at orgeclipsejdtinternalcompilerlookupscopegettypeorpackagescopejava2688 at orgeclipsejdtinternalcompilerlookupscopegettypescopejava2405 at orgeclipsejdtinternalcompilerastsingletypereferencegettypebindingsingletypereferencejava44 at orgeclipsejdtinternalcompilerasttypereferenceinternalresolvetypetypereferencejava132 at orgeclipsejdtinternalcompilerasttypereferenceresolvetypetypereferencejava204 at orgeclipsejdtinternalcompilerlookupsourcetypebindingresolvetypeforsourcetypebindingjava1374 at orgeclipsejdtinternalcompilerlookupsourcetypebindingfieldssourcetypebindingjava699 at orgeclipsejdtinternalcompilerlookupreferencebindingavailablefieldsreferencebindingjava166 at orgeclipsejdtinternalcodeassistinternalextendedcompletioncontextsearchvisiblefieldsinternalextendedcompletioncontextjava518 at orgeclipsejdtinternalcodeassistinternalextendedcompletioncontextsearchvisiblevariablesandmethodsinternalextendedcompletioncontextjava807 at orgeclipsejdtinternalcodeassistinternalextendedcompletioncontextcomputevisibleelementbindingsinternalextendedcompletioncontextjava179 at orgeclipsejdtinternalcodeassistinternalextendedcompletioncontextgetvisibleelementsinternalextendedcompletioncontextjava365 at orgeclipsejdtinternalcodeassistinternalcompletioncontextgetvisibleelementsinternalcompletioncontextjava318 at orgeclipsejdtinternaluitextjavaparameterguessingproposalgetassignableelementsparameterguessingproposaljava110 at orgeclipsejdtinternaluitextjavaparameterguessingproposalguessparametersparameterguessingproposaljava293 at orgeclipsejdtinternaluitextjavaparameterguessingproposalcomputeguessingcompletionparameterguessingproposaljava228 at orgeclipsejdtinternaluitextjavaparameterguessingproposalcomputereplacementstringparameterguessingproposaljava194 at orgeclipsejdtinternaluitextjavalazyjavacompletionproposalgetreplacementstringlazyjavacompletionproposaljava330 at orgeclipsejdtinternaluitextjavaabstractjavacompletionproposalapplyabstractjavacompletionproposaljava364 at orgeclipsejdtinternaluitextjavajavamethodcompletionproposalapplyjavamethodcompletionproposaljava57 at orgeclipsejdtinternaluitextjavaparameterguessingproposalapplyparameterguessingproposaljava121 at orgeclipsejdtinternaluitextjavaabstractjavacompletionproposalapplyabstractjavacompletionproposaljava477 at orgeclipsejdtinternaluitextjavalazyjavacompletionproposalapplylazyjavacompletionproposaljava488 at orgeclipsejfacetextcontentassistcompletionproposalpopupinsertproposalcompletionproposalpopupjava930 at orgeclipsejfacetextcontentassistcompletionproposalpopupaccess21completionproposalpopupjava894 at orgeclipsejfacetextcontentassistcompletionproposalpopup2runcompletionproposalpopupjava495 at orgeclipseswtcustombusyindicatorshowwhilebusyindicatorjava70 at orgeclipsejfacetextcontentassistcompletionproposalpopupshowproposalscompletionproposalpopupjava482 at orgeclipsejfacetextcontentassistcontentassistantshowpossiblecompletionscontentassistantjava1656 at orgeclipsejdtinternaluijavaeditorcompilationuniteditoradaptedsourceviewerdooperationcompilationuniteditorjava183 at orgeclipseuitexteditorcontentassistaction1runcontentassistactionjava82 at orgeclipseswtcustombusyindicatorshowwhilebusyindicatorjava70 at orgeclipseuitexteditorcontentassistactionruncontentassistactionjava80 at orgeclipsejfaceactionactionrunwitheventactionjava498 at orgeclipseuicommandsactionhandlerexecuteactionhandlerjava185 at orgeclipseuiinternalhandlerslegacyhandlerwrapperexecutelegacyhandlerwrapperjava109 at orgeclipsecorecommandscommandexecutewithcheckscommandjava476 at orgeclipsecorecommandsparameterizedcommandexecutewithchecksparameterizedcommandjava508 at orgeclipseuiinternalhandlershandlerserviceexecutecommandhandlerservicejava169 at orgeclipseuiinternalkeysworkbenchkeyboardexecutecommandworkbenchkeyboardjava468 at orgeclipseuiinternalkeysworkbenchkeyboardpressworkbenchkeyboardjava786 at orgeclipseuiinternalkeysworkbenchkeyboardprocesskeyeventworkbenchkeyboardjava885 at orgeclipseuiinternalkeysworkbenchkeyboardfilterkeysequencebindingsworkbenchkeyboardjava567 at orgeclipseuiinternalkeysworkbenchkeyboardaccess3workbenchkeyboardjava508 at orgeclipseuiinternalkeysworkbenchkeyboardkeydownfilterhandleeventworkbenchkeyboardjava123 at orgeclipseswtwidgetseventtablesendeventeventtablejava84 at orgeclipseswtwidgetsthisplayfiltereventthisplayjava1262 at orgeclipseswtwidgetswidgetsendeventwidgetjava1052 at orgeclipseswtwidgetswidgetsendeventwidgetjava1077 at orgeclipseswtwidgetswidgetsendeventwidgetjava1062 at orgeclipseswtwidgetswidgetsendkeyeventwidgetjava1104 at orgeclipseswtwidgetswidgetsendkeyeventwidgetjava1100 at orgeclipseswtwidgetswidgetwmcharwidgetjava1509 at orgeclipseswtwidgetscontrolwm charcontroljava4640 at orgeclipseswtwidgetscanvaswm charcanvasjava345 at orgeclipseswtwidgetscontrolwindowproccontroljava4528 at orgeclipseswtwidgetscanvaswindowproccanvasjava341 at orgeclipseswtwidgetsthisplaywindowprocthisplayjava4972 at orgeclipseswtinternalwin32osthispatchmessagewnative method at orgeclipseswtinternalwin32osthispatchmessageosjava2531 at orgeclipseswtwidgetsthisplayreadandthispatchthisplayjava3752 at orgeclipseuiinternalworkbenchruneventloopworkbenchjava2701 at orgeclipseuiinternalworkbenchrunuiworkbenchjava2665 at orgeclipseuiinternalworkbenchaccess4workbenchjava2499 at orgeclipseuiinternalworkbench7runworkbenchjava679 at orgeclipsecoredatabindingobservablerealmrunwithdefaultrealmjava332 at orgeclipseuiinternalworkbenchcreateandrunworkbenchworkbenchjava668 at orgeclipseuiplatformuicreateandrunworkbenchplatformuijava149 at orgeclipseuiinternalideapplicationideapplicationstartideapplicationjava123 at orgeclipseequinoxinternalappeclipseapphandleruneclipseapphandlejava196 at orgeclipsecoreruntimeinternaladaptoreclipseapplauncherrunapplicationeclipseapplauncherjava110 at orgeclipsecoreruntimeinternaladaptoreclipseapplauncherstarteclipseapplauncherjava79 at orgeclipsecoreruntimeadaptoreclipsestarterruneclipsestarterjava344 at orgeclipsecoreruntimeadaptoreclipsestarterruneclipsestarterjava179 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokeunknown source at sunreflectdelegatingmethodaccessorimplinvokeunknown source at javalangreflectmethodinvokeunknown source at orgeclipseequinoxlaunchermaininvokeframeworkmainjava622 at orgeclipseequinoxlaunchermainbasicrunmainjava577 at orgeclipseequinoxlaunchermainrunmainjava1410,"['java', 'android']" +293856,log4net not logging debug statements i am using log4net for the first time and have followed the documentation using supplied configuration samples however debug statements do not log info error warn and fatal levels all log correctly can anyone tell me what i am missing appconfig section namelog4net typelog4netconfiglog4netconfigurationsectionhandler log4net log4net appender nameconsole typelog4netappendercoloredconsoleappender mapping level valueinfo forecolor valuegreen mapping mapping level valuedebug forecolor valuecyanhighintensity mapping mapping level valuewarn forecolor valuepurplehighintensity mapping mapping level valueerror forecolor valueredhighintensity mapping mapping level valuefatal forecolor valueyellowhighintensity mapping layout typelog4netlayoutpatternlayout pattern to output the callers file name and line number conversionpattern value5level thread fileline messagenewline layout appender appender namerollingfile typelog4netappenderrollingfileappender file valueexamplelog appendtofile valuetrue maximumfilesize value100kb maxsizerollbackups value2 layout typelog4netlayoutpatternlayout conversionpattern valuelevel thread logger messagenewline layout appender root level valueinfo appenderref refconsole appenderref refrollingfile rootlog4netsome people have mentioned checking assemblyinfo for assembly log4netconfigxmlconfigurator however there is no difference with or without this line logger is declared like private static readonly ilog log logmanagergetlogger typeof cwd netsuite and is accessed like xmlconfiguratorconfigurelogdebugdebugging does not get loggedloginfo entering application logged to console and log filelogdebug debug statement does not get logged logerror error statement logged to console and log filelogwarn warning statement logged to console and log filelogfatal fatal statement logged to console and log file,['c#'] +293858,trying to track down a vague error in apache logs i am trying to stamp out errors on a new ubuntu server install and am getting errors in the logs that i have no clue on how to track downthe logs show this line over and oversh 1 cd cannot cd to sh 1 cd cannot cd to sh 1 cd cannot cd to sh 1 cd cannot cd to how do i find the source from such a vague error it does not even have a time of occurrence that most errors in the logs havethanks in advance it is going to be a long day,['php'] +293865,delegate methods vs general methods i want to know the difference between using delegate methods and using general methodswithout delegatesfor example with delegate delegate void delmethodstring strstatic void methodstring str debugwritelinestrusage delmethod dm new delmethodmethoddmstringand without delegate static void methodstring str debugwritelinestrusage methodstringwhat are the differences of these twothe method without delegate is smaller and easy but i find coders using delegated methods frequentlywhat is the reason behind this,['c#'] +293878,jquery selector for finding the first element after a given element that matches a selector let us say i have this html textareablahtextarea br div claselect thishellodivhow can i select the div with class select this when i already have the textarea identified i do not want to use a class selector on the entire document because i am working with a large document and class lookups are slow in older browsersjquery next does not seem to do the trick closest only looks up the dom tree and nextuntil qualifies on everything i need except for the select this div any other options out there,"['javascript', 'jquery', 'html']" +293908,xmlserializer how to deserialize an enum value that no longer exists i am using the xmlserializer to save this class to a file the class has a string and an enum as shown belowpublic class iopoint string name get set typeenum get setpublic enum typeenum temperature pressure humiditywhen serialized it looks like this iopoint namerelative humidityname typeenumhumiditytypeenumiopointi have been serializing and deserializing this object with no problems for several versions i no longer want to support humidity so i removed it from the enum however this causes an exception when deserializing from xml because the value in the typeenum field humidity is not a valid value for the typeenum this makes sense but how to handle thiswhat i would like to do is just ignore this error and leave the value as null i have tried implementing the onunknownelement xmldeserilizationevent class unfortunately this does not catch this error any ideas on how to catch and ignore this error i can clean up after the deserialization is complete mitch,['c#'] +293953,how to know if when using on duplicate key update a row was inserted or updated we have a database that gets updated everyday at midnight with a cronjob we get new data from an external xml what we do is that we insert all the new content and in case there is a duplicated key we update that field insert into table id col1 col2 col3values id value val1 val2 val3id value val1 val2 val3id value val1 val2 val3id value val1 val2 val3on duplicate key update col1 values col1 col2 values col2 col3 values col3what we want to know is which rows have actually been inserted meaning we want to have a list of the new items is there any query that might return the new inserts basically we will need to get all the new ids and not the number of new insertionsthanks,['mysql'] +293962,surf missing in opencv 24 for python i am trying to instantiate a surf object in python using opencv as described here but this happens import cv2 cv2 version 240 cv2surftraceback most recent call last file stdin line 1 in moduleattributeerror module object has no attribute surfdoes anyone know why this happens or if surf is missing from the python version of opencv,['python'] +293975,absent code attribute in method that is not native or abstract in class file javaxservletservletexception i am planning to use java servlets in my application i included the following in my projects pomxml file to load java servlet 30 implementation jardependency groupidorgglassfishgroupid artifactidjavaxservletartifactid version32b05versiondependency the project compiles fine however when i run it i get the following errorjavalangclassformaterror absent code attribute in method that is not native or abstract in class file javaxservletservletexceptioni searched for it here and found some good answersi figured out from them that this error happens when we include the jar which contains only interfaces defined by servlet api and not the actual implementation so i checked that the glassfish jar i am using is just interfaces or it contains implementation too i found that it is an implementation and not just interfacesso now i am wondering why i am getting this error at runtime anyoneupdatejust now i found out that it was a blatant error from my side i was adding the jar to one project while was running an altogether different project i am sorry for this adding the glassfish servlet implementation does solve the issuethankssandeep,['java'] +293984,how to detect if a java system property has changed i would like to know when a system property is changed i have an application in an application server that somehow is changing a system property systemsetproperty i think i was taking a look and i have found different approachesjpdaobserver observableproperty change listenerjmxany suggestions thanks in advance,['java'] +293989,operator in javascript i am now confused about operator in javascript my understanding was operator operates only on boolean but a comment to one of my answers says it can operate on anything and returns a boolean which happened to be true after i did some testsalertundefined truealertfunction falsealert falsealertnull truealert crashalertfalse falsealertfalsea trueacan somebody help me generalize the behavior of operatorediteven more confusing stuffaalert new string truealert truealert new string falsehowa,['javascript'] +293992,whats the standard way for getting uniformly thistributed random integers in c is there a function for obtaining uniformly thistributed pseudorandom integers in some specified range i could write my own function using rand but this seems like a common enough situation that there is probably something in the stl for it,['c++'] +294015,why is my jquery not selector not working in css i have this layoutdiv idsectors h1sectorsh1 div ids71103 classalphadiv div ids81104 classalphadiv div ids17605 classbetadiv div ids07479div div ids26528 classgammadiv div ids04divdivwith these css rulessectors width 584px backgroundcolor ffd margin 15em border 4px dashed 0 padding 16px overflow autosectors h1 fontsize 2em fontweight bold textalign centersectors div float left position relative width 180px height 240px margin 16px 0 0 16px borderstyle solid borderwidth 2pxsectors divafter thisplay block position absolute width 100 bottom 0 fontweight bold textalign center texttransform capitalize backgroundcolor rgba255 255 255 08 bordertop 2px solid content attrid attrclasectors divnthoftype3n1 marginleft 0sectors divalpha color b00 backgroundcolor ffe0d9 sectors divbeta color 05b backgroundcolor c0edff sectors divgamma color 362 backgroundcolor d4f6c3 i use jquery to add the unassigned class to sectors that do not otherwise have one of the classes alpha beta or gammasectors divnotalpha beta gammaaddclassunassignedthen i apply some different rules to that clasectors divunassigned color 808080 backgroundcolor e9e9e9 opacity 05sectors divunassignedafter content attrid unassignedsectors divunassignedhover opacity 10and everything works flawlessly in modern browsersinteractive jsfiddle previewbut seeing as the not selector in jquery is based on not in css3 i was thinking i could move it directly into my stylesheet so i wouldnt have to rely on adding an extra class using jquery besides i am not really interested in supporting older versions of ie and other browsers have excellent support for the not selectorso i try changing the unassigned portion above to this knowing i will only have sectors i i and i in my layoutsectors divnotalpha beta gamma color 808080 backgroundcolor e9e9e9 opacity 05sectors divnotalpha beta gammaafter content attrid unassignedsectors divnotalpha beta gammahover opacity 10but as soon as i do this it stops working a in all browsers my unassigned sectors are not grayed out faded out or labeled unassigned anymoreupdated but not so interactive jsfiddle previewwhy does the not selector work in jquery but fail in css should not it work identically in both places since jquery claims to be css3 compliant or is there something i am missingis there a pure css workaround for this or will i have to rely on a script,"['jquery', 'css']" +294040,undefined reference to operator i have a regular class not a template that is with a private friend operatorit is declaration isstdostream operatorstdostream out const position positionin the cpp file it is definition isstdostream operatorstdostream out const position position out positiongetxpoint positiongetypoint return outit is being compiled then linked to the main function which uses it however when i use it i get an undefined referencehowever when i add the definition to the top of the main cpp file and remove the friend declaration it works fineheres how i am using it in my main functionstdcout nodegetposition stdendlno more no lessheres the linker errorhomelukedesktoppathfinderparse worldcpp34 undefined reference to pathfinderoperatorstdostream pathfinderposition constand heres the class headerifndef pathfinder hdefine pathfinder hinclude ostreaminclude istreaminclude listinclude vectorinclude stdexceptinclude cstringnamespace pathfinderclass nodetypedef unsigned int gcosttypedef stdvectorstdvectornode worldtypedef stdvectornode worldrowclass positionpublic typedef unsigned int point typeprivate point type xpoint point type ypoint friend stdostream operatorstdostream out const position positionpublic positionconst point type xpoint 0 const point type ypoint 0 positionconst position position positionposition position position position operatorconst position position position operatorposition position point type getxpoint const point type getypoint const void setxpointconst point type xpoint void setypointconst point type ypointclass nodeprivate bool ispassable bool isstartingnode bool istargetnode position position gcost additionalgcost node parent public nodeconst bool ispassable true const bool isstartingnode false const bool istargetnode false const position position position00 const gcost additionalgcost 0 node parent nullptr nodeconst node node nodenode node node node operatorconst node node node operatornode node bool ispassable const bool isstartingnode const bool istargetnode const position getposition const gcost getadditionalgcost const node getparent const void setaspassableconst bool ispassable void setasstartingnodeconst bool isstartingnode void setastargetnodeconst bool istargetnode void setpositionconst position position void setadditionalgcostconst gcost additionalgcost void setparentnode parentclass worldhelperpublic static world fromstreamstdistream input static void syncpositionsworld world static void uninitializeworldworld world static node findstartingnodeconst world world static node findtargetnodeconst world worldclass pathfinderpublic virtual stdlistnode operatorworld world const 0endif pathfinder hnow after removing the friend declaration i am getting error messages likecannot bind astdostream aka stdbasic ostreama lvalue to astdbasic ostreamait is occuring on the same line as the stdcout statementso whats the dealthanks in advance,['c++'] +294041,directing sublime text 2 packages to the correct python installation i just want to direct a sublime text 2 package sublimerepl to the correct python installationat the moment it is picking up the wrong onethe story here is familiar to mac users the mac os comes includes a python install which it uses for various os stuff for which python is required like many others i prefer not to use this system python which resides in systemlibrary becasue it is usually out of date and of course it is not a good idea to update itit is a working python install used by the mac os and updating risks causing those os tasks that depend on that install to breakbut that is the version picked up by the package sublimereplpython 271 r27186832 jun 25 2011 050901 gcc 421 based on apple inc build 5658 llvm build 23351500 on darwintype help copyright credits or license for more information the version i use for development and which is installed in libraryframeworks and symlinked to usrlocalbin is pythonpython 273 v27370274d53c1dd apr 9 2012 205243 gcc 421 apple inc build 56 dot 3 on darwintype help copyright credits or license for more information sublime 2 text is picking up the correct version elsewhere except when using the sublimerepl package so there must be a setting in one of the config files in that package that will let me direct sublimerepl to the correct pythonbut i cannot find itit seems that i have exhausted all plausible options which looking through my sublime text 2packages directory must reside in eithersublimerepl sublimerepl osxsublimesettings sublimereplsublimesettingsoruser sublimereplsublimesettingsin fact i added the following each of the three json files above with no effect default extend env path libraryframeworkspythonframeworkversions27binusrlocalbinpython27path,['python'] +294048,java passing arraylist of interface type i have an interface damageable as followspublic interface damageable public void handlecollisionfloat impulsea class which implements this interface baseobjectpublic class baseobject implements damageablenow in a third class i have an arraylist of the type baseobjectpublic class objectmanager public arraylistbaseobject bodieswhat i am trying to do is to pass the arraylist bodies to a method of another class which accepts arraylistpublic collisionmanager arraylistdamageable bodies bodies bodiesjava does not let me do new collisionmanagerbodies where bodies is of type arraylist and baseobject implements damageablei have tried casting says cannot cast from arraylistbaseobject to arraylistalso tried using class extends damageable but then i am unable to call methods declared in the interface damageable how can i pass the arraylist,['java'] +294111,cdvpluginh file not found in cordova as component cleaver i added cordova as a component to my ios project adding a custom plugin leads to the error despite that the plugin works in a cordovaonly projectcdvpluginh file not foundphonegap cordova 170 installedchecked multiple times to correctly implement the steps adding cleaver to your xcode project cordovalib subprojectthe plugin works in a plain cordovabased application cordova xcode templateadding all load to the other linker flags in the main project does have no effectthe problematic part is as followsimport foundationfoundationhifdef cordova frameworkimport cordovacdvpluginhelseimport cdvpluginhendifwhat am i missing,['ios'] +294120,how can i lock by cache key i am trying to implement a generic threadsafe cache method and i wonder how i should implement the lock in itit should look somthing like thisprivate static readonly lockobject new objectpublic t getcachetstring key funct valuefactory try to pull from cache here lock lockobject i do not want to use static object lock here because then every time a lock is performed all cached objects in my site have to wait regarding of the cache key cache was empty before we got the lock check again inside the lock cache is still empty so retreive the value here store the value in the cache here return the cached value hereany suggestions thanks amir,"['c#', 'asp.net']" +294131,receiving rtsp stream using ffmpeg library i have an ipcamera on my lan streaming video using rtsp i have been able to capture and thisplay it successfully using ffplay commandffplay rtspadmin7070 with authenticationso i would like to achieve the same using programming in cc using ffmpeg library i guess this must be possibleso let me phrase two simple questions how do i receive the stream in a cc program using ffmpeg library just provide some urltutorial as google was not helpfulhow do i thisplay the received video same here some good url to direct me,"['c++', 'c']" +294139,entity framework web config file this code works fineconnectionstrings add nameefdbcontext connectionstringdata sourcesqlexpress initial catalogmydbintegrated securitysspi providernamesystemdatasqlclient connectionstrings entityframework defaultconnectionfactory typesystemdataentityinfrastructuresqlconnectionfactory entityframework parameters parameter valuedata sourcesqlexpress integrated securitytrue multipleactiveresultsetstrue parameters defaultconnectionfactory entityframeworkbut this code does not workconnectionstrings add nameefdbcontext connectionstringdata sourcemssqlserver2008 initial catalogmydbintegrated securitysspiuser iduseradmin passwordpass providernamesystemdatasqlclient connectionstrings entityframework defaultconnectionfactory typesystemdataentityinfrastructuresqlconnectionfactory entityframework parameters parameter valuedata sourcemssqlserver2008 integrated securitytrue multipleactiveresultsetstrue parameters defaultconnectionfactory entityframeworkthe second code must be run on a remote server with an msqserver2008 instance and when the page is loaded the following message appearsan error occurred while getting provider information from the database this can be caused by entity framework using an incorrect connection string check the inner exceptions for details and ensure that the connection string is correct,['asp.net'] +294150,is there a way to differentiate between left and right shift keys being pressed i can recognize when the user presses any shift key with this codevoidflagschangednsevent theevent if theevent modifierflags nsshiftkeymask but is there any way to thistinguish whether it was the right or left shift key that was pressed,['objective-c'] +294202,what exactly is the keyword should in rspec ruby i am a beginner in ruby and had this question nagging me for a long timein an rspec file if we write bookshould do something what is the should keyword is it a member of the book object how did it come to be the member of the book object or is it some construct of ruby is it a function where can i find the definition of this if it is a function or member,['ruby'] +294237,make text height 100 of div i am trying to make the text 100 height of a div but it does not work it just becomes 100 of the body fontsize is there any way to make it follow the div heightthe div height is 4 of the whole page and i want the text to follow it when you resizechange resolution,['css'] +294263,is there anyway to use c implicit operators from f if i have a c class with implicit conversion to double like sopublic class parameter private double value public parameterdouble value value value public static implicit operator doubleparameter p return value f does not like me trying to use it as if it were a floatlet a parameter40let b parameter20let c a mathsinb expected float here parameteris there any way to do this i am guessing there is not based on this questionanswer and if not what would be a decent workaround,['c#'] +294304,calling constexpr in default template argument in c11 i am using a constexpr function as a default value for a template parameter it looks like thistemplate int valuestruct bar static constexpr int get return value template typename a int value agetstruct fooint main typedef foobar0 type return 0g 45 and 47 compiles this but clang 31 does not the error message from clang isclang testcpp1035 error nontype template argument is not a constant expressiontemplate typename a int value aget clang testcpp1719 note while checking a default template argument used here typedef foobar3 type clang testcpp1035 note undefined function get cannot be used in a constant expressiontemplate typename a int value aget clang testcpp423 note declared here static constexpr int get 1 error generatedwhich one is correct,['c++'] +294317,where data sort should be done server or client i get from a server some datas that i thisplay using gwt on clientgwt is not the problem here you can replace gwt by ajax calls or you can transpose it to a real application instead of a web appwhere the sort action should be done on server or on client using javascript after receiving the datas and before thisplaying them,['javascript'] +294326,overriding member variables in java i am studying overriding member functions in java and thought about experimenting with overriding member variablesso i defined classespublic class a public int intval 1 public void identifyclass systemoutprintlni am class a public class b extends a public int intval 2 public void identifyclass systemoutprintlni am class b public class mainclass public static void mainstring args a a new a b b new b a aref aref a systemoutprintlnarefintval arefidentifyclass aref b systemoutprintlnarefintval arefidentifyclass the output is1i am class a1i am class bi am not able to understand why when aref is set to b intval is still of class a,['java'] +294333,fast string comparison in c i currently have this kind of loopwhile1 generate stringbuffer forint i 0 i filelines i ifstrcmpbufferlinei 0 do something i have a file with a few million stringswhich hopefully should be cut by half sometime soon the number of all these strings is stored in filelineslinei is basically where the string itself is storedcurrently due to the comparison of these million strings function generate stringbuffer is executed around 42 times per secondis there a faster way to do string comparison in c,['c'] +294340,howto validate collections in maps i have a problem with the valid annotation of jsr303 the annotation works fine for normal lists or and sets but i am trying to validate maps which contain lists ie validhashmapstring arraylistobject1 mapin this case instances of object1 class are not validated is there a convenient way to do this recursively without iterating over every object and validating it manually,['java'] +294345,jquery click event not working in mobile browsers the jquery click event does not seem to be firing in mobile browsersthe html is as follows this is the main menu ul classmenu lia hrefhomehomeali li classpublicationspublications amp projectsli lia hrefaboutaboutali lia hrefblogblogali lia hrefcontactcontactali ul this is the submenu that is to be fired on click div idfilter wrapper ul idportfoliofilter lia hrefnutritionrelatednutrition relatedali lia hrefessaysessays and nonfictionali lia hrefcommissionedcommissioned worksali lia hrefplaysplays and performanceali lia hrefnewprojectsnew projectsali ul divthis is the jquery script for mobiledocumentreadyfunction publicationsclickfunction filter wrappershow when i click the publications list item on a mobile browser nothing happensyou can view the site here not sure if there are jquery mobile specific events,"['jquery', 'android']" +294346,implementing show in finder button in objective c in my application i would like to create a show in finder button i have been able to figure out how to pop up a finder window of that directory but have not figured out how to highlight the file like the os doesis this possible,['objective-c'] +294352,most probable bits in random integer i have made such experiment made 10 million random numbers from c and c and then counted how much times each bit from 15 bits in random integer is set i chose 15 bits because c supports random integer only up to 0x7fwhat i have got is thisi have two questionswhy there are 3 most probable bits in c case bits 81012 are most probable andin c bits 6811 are most probablealso seems that c most probable bits is mostly shifted by 2 positions then compared to c most probable bits why is this because c uses other rand max constant or what my test code for cvoid accumulateresultsint random int bitset15 int i int isbitset for i0 i 15 i isbitset random 1i 0 bitseti isbitset int main int i int bitset15 0 int times 10 srand0 for i0 i times i accumulateresultsrand bitset for i0 i 15 i printfd dn i bitseti systempause return 0and test code for cstatic void accumulateresultsint random int bitset int i int isbitset for i 0 i 15 i isbitset random 1 i 0 1 0 bitseti isbitset static void mainstring args int i int bitset new int15 int times 10 random r new random for i 0 i times i accumulateresultsrnext bitset for i 0 i 15 i consolewriteline0 1 i bitseti consolereadkeyvery thanks btw os is windows 7 64bit architecture visual studio 2010editvery thanks to david heffernan i made several mistakes hereseed in c and c programs was different c was using zero and c current timei did not tried experiment with different values of times variable to research reproducibility of resultsheres what i have got when analyzed how probability that first bit is set depends on number of times random was calledso as many noticed results are not reproducible and should not be taken seriouslyexcept as some form of confirmation that cc prng are good enough,"['c#', 'c']" +294382,whats the best way to iterate an android cursor i frequently see code which involves iterating over the result of a database query doing something with each row and then moving on to the next row typical examples are as follows cursor cursor dbrawquerycursormovetofirstwhile cursorisafterlast false cursormovetonextcursor cursor dbrawqueryfor boolean hasitem cursormovetofirst hasitem hasitem cursormovetonext cursor cursor dbrawqueryif cursormovetofirst do while cursormovetonextthese all seem excessively longwinded to me each with multiple calls to cursor methods surely there must be a neater way,['android'] +294434,androidmk armlinuxandroideabig exceptions and cxa allocate exception i am rebuilding android from source to flash onto a device right now using emulator trying to add a single command line tool i have put my source in repoexernal and written androidmki get the following undefines cxa allocate exceptionbr cxa begin catchbr cxa end catchbr cxa end cleanupbr cxa free exceptionbr cxa get exception ptrbr cxa rethrowbr cxa throwbr gxx personality v0bri have searched through the other issues here with the same undefines but cannot quite seem to find the solution for androidthe final link command gets generated as prebuiltdarwinx86toolchainarmlinuxandroideabi44xbinarmlinuxandroideabig nostdlib bdynamic wltbuildcorearmelfx wldynamiclinkersystembinlinker wlgcsections wlznocopyreloc o outtargetproductgenericobjexecutableswavsender intermediateslinkedwavsender louttargetproductgenericobjlib wlrpathlinkouttargetproductgenericobjlib lc llog lcutils lnetutils lc lstdc lm outtargetproductgenericobjlibcrtbegin dynamico outtargetproductgenericobjexecutableswavsender intermediatesohsongcastwavsenderwavsendero outtargetproductgenericobjstatic librariesliblog intermediateslibloga outtargetproductgenericobjstatic librarieslibcutils intermediateslibcutilsa outtargetproductgenericobjstatic librarieslibopenhome intermediateslibopenhomea outtargetproductgenericobjstatic librarieslibgtest intermediateslibgtesta outtargetproductgenericobjstatic librarieslibstlport static intermediateslibstlport statica outtargetproductgenericobjstatic librarieslibstdc intermediateslibstdca outtargetproductgenericobjstatic librarieslibgabi intermediateslibgabia wlznoexecstack wlicfsafe wlfixcortexa8 prebuiltdarwinx86toolchainarmlinuxandroideabi44xbinlibgccarmlinuxandroideabi443armv7alibgcca outtargetproductgenericobjlibcrtend androidoandroidmk isinclude clear varsbrlocal module wavsenderbrlocal module tags engbrlocal cflags fexceptions d gnu source dplatform androidbrlocal src files wavsendercppbrlocal shared libraries libc libcutils libnetutilsbrlocal static libraries libcutils libopenhomebrlocal static libraries libopenhome libgtest libstlport static libstdc libgabibrlocal ldlibs lstdc brinclude externalstlportlibstlportmkbrinclude build executablebrcan anyone see a problem or point me in a direction to get the correct behavior from armlinuxandroideabig,['android'] +294437,windows service installed with procrun works in ts mode but does not start as a windows service saying it started and then stopped i installed a standard executable jar file as a windows service by running the following command prunsrvexe ismy service installcpathtoprunsrvexe jvmauto startupauto startmodejvm classpathcpathtomyservicejar startclasscommydomainmyservicei can now run my program fine in console mode by running the following command i am using java 16 prunsrvexe tsmy servicewhen i try to start the service through the standard windows services interface i get the following error messagethe myservice service on local computer started and then stopped some services stop automatically if they are not in use by other services or programsthere is no output in my applications log file when i attempt to start the service this way there is also no output in the windows event log windows 7 64bit what can i do to try and figure out why this service will not run,['java'] +294443,cannot find id reference no resource matches the given name at i have the following inside a relative layouttextedit androidlayout widthwrap content androidlayout heightwrap content androidlayout alignbottomidbuttona androidlayout alignparentlefttrue androidlayout alignparenttoptrue androidlayout toleftofidbuttona button androidididbuttona androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentrighttrue androidtextstringmessage buttoneclipse gives me these errors at lines androidlayout alignbottomidbuttona and androidlayout toleftofidbuttona respectivelyerror error no resource found that matches the given name at layout alignbottom with value idbuttonaerror error no resource found that matches the given name at layout toleftof with value idbuttonareplacing idbuttona with idbuttona removes this eclipse error message is that the right thing to do if so why would that work instead does not id create a new id i do not want a new id i want to use the one referenced in the button object what is the best way to deal with thisthanks guys joe,['android'] +294473,android bitmapdrawable settilemodex does not work on textview i have a textview and a bitmap that can be repeated only horizontally i want to set the background of my textview and repeat it only on the x axis after looking around i saw that you can only do that via code and not in xml i created a bitmapdrawable usingbitmapdrawable bg new bitmapdrawabler bitmapfactorydecoderesourcer rdrawablemy drawablebgsettilemodexshadertilemoderepeatsetbackgrounddrawablebghowever even with this way the drawable is also repeated on the y axis this is in honeycomb 32can someone shed some light on this perhaps provide an example of it working,['android'] +294483,initialize list with arraysaslist why does this workstring array a b cliststring list arraysaslistarraybut this does notliststring list arraysaslistabc,['java'] +294489,avassetexportsession stops progressing i am having a problem with avassetexportsession where the progress stops increasing but the status still says that it is exporting this is actually a pretty rare occurrence it works flawlessly about 9 of the time but i want to fix the problem anywayso i start the exporting exportsession avassetexportsession alloc initwithassetcomposition presetnameavassetexportpresetmediumquality exportsessionvideocomposition videocomposition exportsessionoutputfiletype comapplequicktimemovie exportsessionoutputurl outputurl exportsession exportasynchronouslywithcompletionhandler then have a timer checking the progress avassetexportsessionstatus status exportsession status float progress 0 if status avassetexportsessionstatusexporting progress exportsession progress else if status avassetexportsessionstatuscompleted progress 1 nslogd f status progress delegate processorself didprogressprogressand the output ends up looking like20120523 142859494 1899707 2 012599120120523 1428594 1899707 2 018528020120523 142900494 1899707 2 025939320120523 142900994 1899707 2 032609320120523 142901494 1899707 2 040020620120523 142901995 1899707 2 048172920120523 142902495 1899707 2 054101920120523 142902997 1899707 2 062254220120523 142903493 1899707 2 068183220120523 142903995 1899707 2 076335520120523 142904494 1899707 2 082264520120523 142904994 1899707 2 088008220120523 142905493 1899707 2 088008220120523 142905994 1899707 2 088008220120523 144322994 1899707 2 088008220120523 144323493 1899707 2 088008220120523 144323994 1899707 2 088008220120523 144324494 1899707 2 0880082note it does not stop at the same percentage every time its totally randomas you can see from the timestamps it took 5 seconds to do the first 88 and then i let it run for another 13 minutes full video processing usually does not take more then 10 seconds with no change in the progresscurrently my only option is to check if the progress has not changed in the last x seconds and just tell the user it failed and to try againanyone have any ideas,['ios'] +294500,implement a generic repository pattern using old adonet i am trying to implement the repository pattern using adonet because of platform limitation public interface igenericrepositoryt ithisposable where t class iqueryablet getall iqueryablet findbyexpressionfunct bool predicate void addt entity void deletet entity void editt entity void savehow to complete the following abstract classpublic abstract class genericrepositoryc t igenericrepositoryt where t class where c idbdataadapter new private c dbdataadapter new c protected c db get return dbdataadapter set dbdataadapter value public virtual iqueryablet getall datatable dt dbdataadapterfilldt iqueryablet query dt return query public iqueryablet findbysystemlinqexpressionsexpressionfunct bool predicate iqueryablet query dbdataadaptersettwherepredicate return query updatei will implement the domain specified repository later by inherent these two interfaceclasspublic class foorepository genericrepositoryfoobarentities foo ifoorepository public foo getsingleint fooid var query getallfirstordefaultx xfooid fooid return query,['c#'] +294508,mssql servers native odbc driver for linux and php 54 i have apache 2216 and php 543 on a linux debian 6 x64to install the mssql servers native odbc driver for linux i use the following instructionsi configured my odbcini file this waymydsndriver sql server native client 110database datbaseserver xportand my odbcinstini this waysql server native client 110descriptionmicrosoft sql server odbc driver v10 for linuxdriveroptmicrosoftsqlnclilib64libsqlncli110so17900threading1usagecount1to test i run the following command isql v mydsn dbusername dbpasswordand i got success connected sqlstatement help tablename quit sqlthen a use phpize to install unixodbc on php 54 using thisthe first command ln s is used because configure cannot find the headers of php on the default location sudo ln s usrincludephp5 usrincludephp phpize configure withpdoodbcunixodbc make make test sudo make installon my phpinfo i getpdo support enabledpdo drivers odbcpdo driver for odbc unixodbc enabledodbc connection pooling enabled strict matchingnow it is time to test everything on a php 54 scriptphp ini setthisplay errors 1 error reportinge all conn new pdoodbcdsnmydsnuidusrpwdpsw query select from my table stmt connpreparequery stmtexecute while row stmtfetch echo pre print rrow echo pre but it does not work i got this error messagefatal error uncaught exception pdoexception with message sqlstate010 sqldriverconnect 0 unixodbcdriver managercannot open lib optmicrosoftsqlnclilib64libsqlncli110so17900 file not found in varwtestemssqlphp17 stack trace 0 varwtestemssqlphp17 pdo constructodbcdsnmydsn 1 main thrown in varwtestemssqlphp on line 17so my question is what is happen what configuration i am missinghow to set up correctly the mssql servers native odbc driver on linux and php 54ps when i try to use the odbc connect php says the function does not exist,['php'] +294511,mixpanel anonymous user converts to identified user tracking i am adding mixpanel to my web application and i am curious about the process around what happens when a user transitions from anonymous not logged inregistered to identified when they register create an account on the siteif a user comes in and is new to the site they get an anonymous uuid according to the documentation the documentation also says that mixpanel can not translate between ids at this time does this mean mixpanel is incapable of handling the transition of a nonregistered user to a registered user and keep track of their events from before they became a registeredidentified userif so does anyone have experience with working around this how did you go about it,['javascript'] +294512,why can i not group browserspecific cselectors for different browsers i just tried to write the following rule to style the input placeholder for browsers that support itmain inputwebkitinputplaceholdermain inputmozplaceholder color 8 fontstyle italicthe problem is that the rule is not applied however if i break it up like this instead it works just finemain inputwebkitinputplaceholder color 8 fontstyle italicmain inputmozplaceholder color 8 fontstyle italicwhy can i not group browserspecific selectors or is there another way to do it it does not feel right to repeat the same attributes twice for the same element updatejust found this resource stating that it cannot be done but so far no information on why it seems odd that the browser should have to thiscard the entire rule just because it does not recognize one of the selectors,['css'] +294528,touchupinside on uiview with children i may be missing something here buti have a uiview with a few children a couple of uilabels and uiimageview i need to catch an event when the user clicks taps anywhere within the parent uiview visible part of the uiview or any of its childrenwhats the best way of doing this,['iphone'] +294543,iterating row by row through a pandas dataframe possible duplicatewhat is the most efficient way to loop through dataframes with pandas i am looking to iterate row by row through a pandas dataframe the way i am doing it so far is as followsfor i in dfindex do somethingdfixiis there a more performant andor more idiomatic way to do this i know about apply but sometimes it is more convenient to use a for loop thanks in advance,['python'] +294544,how would you implement a trait designpattern in c i know the feature does not exist in c but php recently added a feature called traits which i thought was a bit silly at first until i started thinking about itsay i have a base class called client client has a single property called namenow i am developing a reusable application that will be used by many different customers all customers agree that a client should have a name hence it being in the baseclassnow customer a comes along and says he also need to track the clients weight customer b does not need the weight but he wants to track height customer c wants to track both weight and heightwith traits we could make the both the weight and the height features traitsclass clienta extends client use tclientweightclass clientb extends client use tclientheightclass clientc extends client use tclientweight tclientheightnow i can meet all my customers needs without adding any extra fluff to the class if my customer comes back later and says oh i really like that feature can i have it too i just update the class definition to include the extra traithow would you accomplish this in cinterfaces do not work here because i want concrete definitions for the properties and any associated methods and i do not want to reimplement them for each version of the classby customer i mean a literal person who has employed me as a developer whereas by client i am referring a programming class each of my customers has clients that they want to record information about,['c#'] +294547,too many threads in blackberry using phonegapwebworks i am developing a blackberry app using cordovaphonegap i am fetching several images map tiles from a server also every 60 seconds i send position information to it however every now and then either when i fetch the images or send information i get an error if i am on a simulator bb 9930 os 700318 i get an apperror 104 too many threads message and my app crashes when i test my app on a device bb 8520 os 500592 not only does the app crashes but makes the bb reseti have seen other posts with the same issue like this one this one or this one however i have not found a solution when building the app using cordovaphonegap javascriptthanks,['javascript'] +294586,is there a way to stop hibernate from corrupting boolean literals in where annotations i would like to use where annotation in hibernate to remove objects which have been marked deleted by a boolean property on that object for example the following should prevent any deleted addresses from being loaded by hibernateonetomanymappedbycontactwhereclausedeletedfalseprivate setaddress addresses however when i use a clause like deletedfalse then hibernate will mangle the boolean literal by prefixing it with a table name which causes the query to fail for exampleselect from address address0 where address0 deletedaddress0 false and address0 contact idwhat i expected is something like address0 deletedfalse instead of address0 deletedaddress0 false is there a way to specify the where clause or configure hibernate to correctly output the boolean valueps note that it is possible with some databases to specify the boolean value as a string literal like thiswhereclausedeletedfalsethat will get converted to address0 deletedfalse which works just fine in for example postgresql however i am using hsqldb for this project and hsqldb does not seem to support boolean string literals on hsql i get the following exception when using deletedfalseorghsqldbhsqlexception data exception invalid character value for cast,['java'] +294595,how to show sql statements in rails console like webrick rails webrick shows raw sql statements for any activerecord activities how to enable that in the console,['ruby-on-rails'] +294616,format asa expects argument of type achar a includestdiohint main int ijk char stprintfenter stringnscanfsstprintfthe entered string is snst compiling above program gives me a warning warning format asa expects argument of type achar a but argument 2 has type ainta wformatpalindromc81 warning format asa expects argument of type achar a but argument 2 has type ainta wformatwhat is the mistake i am doing here and when i run itaoutenter stringkiathe entered string is nulledit ok i got the pointhere is another version of code which now i run after correctionincludestdiohint main int ijk char stprintfenter stringnscanfsstprintfthe entered string is snstbut the output is enter stringkidathe entered string is null,['c'] +294625,iphonesimplest way to crop image of desired shape and size i am trying to crop image according to my desirefor my cinemagram type appand use it in my applicationi have tried a lot of options but none of tham isusefull for me i read answers on stack over flow but of no use plzz help me outimage uiimage imagenamedimages2jpgimageview uiimageview alloc initwithimageimagecgsize size image sizeimageview setframecgrectmake0 0 sizewidth sizeheightself view addsubviewimageviewimageview release thanks,['iphone'] +294632,offsetting an html anchor to adjust for fixed header i am trying to clean up the way my anchors work i have a header that is fixed to the top of the page so when you link to an anchor elsewhere in the page the page jumps so the anchor is at the top of the page leaving the content behind the fixed header i hope that makes sense i need a way to offset the anchor by the 25px from the height of the header i would prefer html or css but javascript would be acceptable as well,"['javascript', 'html', 'css']" +294646,absolutebottom does not work i have a css codewhy the bottom 0 does not work when the position relativeif i give up position relative to the bottom works but float left and float right not in width 930pxsorry my bad englishstyle typetextcssmain position relative width 930px padding10px margin0 auto left positionabsolute left0right positionabsolute right0bottom position absolute bottom0stylediv idmain div idleft left div div idright right div div idbottom bottom divdiv,['css'] +294674,memory access vs memory copy i am writing an application in c that needs to readonly from the same memory many times from many threads my question is from a performance point of view will it be better to copy the memory for each thread or give all threads the same pointer and have all of them access the same memorythanks,['c++'] +294678,the best way to undelegate events once a view is no longer needed is it a bad practice to call undelegateevents in the view remove method why was not it included by default by the backbone guysi realized i am falling into so many binding issues when simply reinitializing a view variable although undelegateevents is being called automatically when a new view is created it is trying to undelegate events for the newly instantiated view not the previous one therefore unless manually calling it every time ghost event callbacks remain alive and screw up my appswhats the best way to handle this,['javascript'] +294679,rounding necessary with bigdecimal numbers i want to set scale of two bigdecimal numbers a and b as in this example bigdecimal a new bigdecimal26e1095 bigdecimal b new bigdecimal27e1105 int i 112 j1 bigdecimal aa asetscaleij bigdecimal bb bsetscaleijand when i run i have this exceptionjavalangarithmeticexception rounding necessary at javamathbigdecimaldivideandroundbigdecimaljava1439 at javamathbigdecimalsetscalebigdecimaljava2394 at javamathbigdecimalsetscalebigdecimaljava2437why rounding is necessary if i do not want to make around what is solution please thanks,['java'] +294725,convert from prototype to jquery is there a consistent and generic way to convert prototype code to jqueryi am not asking how to convert specific code likefromeventobservewindow load function code tofunctione code but how to convert any code from prototype to jqueryi am not sure this is possible but any suggestions are welcomethanksupdatei have been here but this is 4 years oldyou know a question like how to load data from the server without reloading the page in 1990 would have an obvious answer you cannot,"['javascript', 'jquery']" +294727,menu highlight in magento under admin i add submenu in admin under parent menu but when we select submenu only one submenu will highlight in admin and other would not highlighti have add following code in configxml filemenucustomersettings modulecustomersettingstitleadvance settingstitlesort order100sort order children customersettings modulecustomersettingstitlecustomer settingstitle sort order0sort order actioncustomersettingsadminhtml customersettingsaction customersettings children customersettingsmenuplease give me some suggestions thanks,['php'] +294768,how to create spinner with heading in it i am just thinking to create like below in spinner but i am not sure how to make it work fruits heading unclickable apple mango orange cars heading unclickable bmw lenovais that possible in spinner or if you know any other method to create like this then it would be greati am getting those details from the local database heading from one table and records from one tablei am looking for any example or solutionthanks for your help guys,['android'] +294772,how to rescue omniauthstrategiesoauth2callbackerror i am building a rails application with omniauth for log in serviceto authenticate google i am using omniauth google oauth2 strategywhen user clicks allow access button everything works finebut when user clicks no thanks button the below error is raisedomniauthstrategiesoauth2callbackerrori have tried adding the below rescue code in application controllerclass applicationcontroller actioncontrollerbase rescue from omniauthstrategiesoauth2callbackerror with omniauth callback error handler protected def omniauth callback error handler redirect to init sign in users path endendbut no luckany ideathank you,['ruby-on-rails'] +294776,what do i do first cancel scheduledfuture or shutdown scheduledexecutorservice my codescheduledserviceexecutor service executorsnewsinglethreadscheduledexecutorscheduledfuture future serviceschedulewithfixeddelay runnable 1 1 timeunitmilliseconds now it is time to shut it all downfuturecanceltrueserviceshutdownam i right here maybe i should doserviceshutdownfuturecanceltruewhat do you think,['java'] +294780,space between custom uitabbar and viewcontroller i took a regular uitabbar and changed it is background image to a custom one which has a lower height so i changed the height of the frameat first what i got is a blank space below the tab bar so i changed the origin of the frame too but now the blank space has moved up above the tab bar and this is the resultand this is the code declaring the tab bar in the appdelegateselftabcontoller uitabbarcontroller alloc initcustomizing the tabbaruiimage tabbackgroundimage uiimage imagenamedtabbarbgpngselftabcontollertabbarbackgroundcolor uicolor colorwithred245f255f green245f255f blue245f255f alpha255f255fselftabcontollertabbarbackgroundimage tabbackgroundimagesetting the tabbar height to the correct height of the imagecgrect tabr selftabcontollertabbarframecgfloat diff tabrsizeheight tabbackgroundimagesizeheighttabrsizeheight tabbackgroundimagesizeheighttabroriginy diffselftabcontollertabbarframe tabri guess that the problem is that the viewcontrollers draw themselves above a constant space which is the height of the regular tab bar is there any way to change it,"['iphone', 'objective-c', 'ios']" +294781,find intersecting datarows in a list of datatables i have a list i would like to filter through all the rows in the list of tables to find all the rows that are in every datatable in the listif possible the compare needs to be on the id column that is on every rowi have tried to solve this with linq but got stuck this is what i have so farlistdatatable datatables new listdatatable fill up the listlistdatarow datarows datatablesselectmanydt dtrowscastdatarowasenumerable aggregater1 r2 r1intersectr2any suggestions,"['c#', '.net']" +294798,why firefox autocomplete even with different input name or how does firefox determine where the passwordusername goesif i change name id title class of an input element firefox keeps filling it with password or email,['html'] +294831,average posts per hour on mysql i have a number of posts saved into a innodb table on mysql the table has the columns id date user content i wanted to make some statistic graphs so i ended up using the following query to get the amount of posts per hour of yesterdayselect hourfrom unixtimedate as hour countdate from fb posts where datefrom unixtimedate curdate interval 1 day group by hourthis outputs the following datai can edit this query to get any day i want but what i want now is the average of each hour of every day so that if on day 1 at 00 hours i have 20 posts and on day 2 at 00 hours i have 40 i want the output to be 30 i would like to be able to pick date periods as well if it is possiblethanks in advance,"['mysql', 'sql']" +294834,how to programmatically change volume in ubuntu how do you programmatically change volume in gnome on ubuntu either from the command line or an api python preferrablythe only answers i found to similar questions use amixer which seems to have no effect on ubuntu 1204 runningamixer set headphone 10showssimple mixer control headphone0 capabilities pvolume pswitch penum playback channels front left front right limits playback 0 115 mono front left playback 0 57 5750db on front right playback 0 57 5750db onthe x changes each time i run it unfortunately it has no effect on the actual volume eventually it says 0 but volume is still at full blastthe other downside is i have to specify the exact active output device which i might not know if there are multiple devices for example if i have a master and headphone how do i determine which one is the active device,['python'] +294901,using pythons stat function to efficiently get owner group and other permissions questionhow do i efficiently use the stat function to get meaningful file permissions user group and otherdetailsi am querying the file permissions like sostatinfo osstatpermissions stats imode osstat foobartxt st mode this returns the permissions in decimal form so if foobartxt has the octal file permissions 0700 here permissions is set to the decimal value448 what i want is to set 9 variables for each permission ownerread ownerwright ownerexecute groupread if i was going to do this i would use a brute force method like sostatinfo osstatpermissions stats imode osstat foobartxt st mode octpermissions oct permissions ownerread octpermissions 1 4ownerwrite octpermissions 1 2 or octpermissions 1 6 or octpermissions 1 3 or ownerexecute octpermissions 1 1 or octpermissions 1 5 or octpermissions 1 3is there a more efficient way to do this without having to convert to octal as this function will get called quite a bit,['python'] +294902,running command lines within your python script so i have a bunch of aliases and command line prompt programs and my main program works by inputting b into the cmdexe followed by some filepath names and what not how would i run those arguments in my python script so that it mimics the action i am doing in the cmd,['python'] +294943,custom android views in eclipse visual editor in my applications i often rely on custom build views such as in the following examplexml version10 encodingutf8linearlayout xmlnsandroidandroidorientationvertical androidbackgroundcolorlight greyandroidlayout heightmatch parent androidlayout widthfill parent textview stylestylecardtitle androidididcard title androidlayout heightwrap content androidlayout widthfill parent comwhiterabbitcardsuiaspectratioimageview androidididcard picture androidlayout widthfill parent androidlayout heightwrap content androidadjustviewboundstrue androidlayout marginleft30dip androidlayout marginright30dip androidsrcdrawableboss listview androidididcard properties androidlayout widthfill parent androidlayout heightwrap contentthe problem is i do not know how if it will be thisplayed correctly until i run it on a real device or on the emulator moreover if i found something wrong i would have to perform changes on it and deploy the app again to see if the changes worked as you expectedthis can be a long and boring process especially if the application requires some interaction to get to the activity you want to checkusing the visual editor does not work as it cannot load the custom viewis there another way to check how views are thisplayed without running across the whole application,['android'] +294960,java generics adding wrong type in collection who could me explain thisi have these couple of classesabstract class animal public void eat systemoutprintlnanimal is eating class dog extends animal public void woof systemoutprintlnwoof class cat extends animal public void meow systemoutprintlnmeow and this is the actionimport javautilarraylistimport javautillistpublic class testclass public static void mainstring args new testclassgo public void go listdog animals new arraylistdog animalsaddnew dog animalsaddnew dog doactionanimals public t extends animal void doactionlistt animals animalsaddt new cat why is it possible variable animals is listdog it is wrong that i can add a cat for animal animal animals if animal instanceof cat catanimalmeow if animal instanceof dog doganimalwoof this example compile without errors and output iswoofwoofmeowbut how can i add in list of dog a cat and how the cat is casted to dogi use java version 160 24 openjdk runtime environment icedtea6 1 6b2414ubuntu3,['java'] +294963,creating a secure file hosting server for pdfs i am working to develop a website that allows clients to log in and see various pdfs saved on the server these pdfs will be unique to the client and should not be accessible by someone who is not logged in getting the files onto the server should not be an issue i am just not sure on how to serve them to end usersi have implemented this kind of thing with data from sql servers being served instead of files so i am not entirely sure what the most effective way to go about thisthe website is on a lamp and my minimal experience is in php but if a framework or other language would make this easier i can learn iti am probably in over my head but i usually am so any input would be great,['php'] +294980,uipopover how do i make a popover with buttons like this i am wondering how i can create a popover with buttons like thisansweruiactionsheet actionsheet uiactionsheet alloc initwithtitle nil delegate self cancelbuttontitle nil destructivebuttontitle nil otherbuttontitles take photo choose existing photo nilactionsheet showfromrect buttonframe inview buttonsuperview animated yessomewhere else in your delegated object classvoidactionsheetuiactionsheet actionsheet clickedbuttonatindexnsintegerbuttonindex if buttonindex 0 take photo else if buttonindex 1 choose existing photo,['ios'] +295008,open source android libraries reusable views viewgroups adapters etc heres what i really want a site collecting reusable components for androidi have found various small lists the biggest being the open intents library list mark murphy hi mark also lists the library projects he publishesnone of this is of the same order as say cocoa controls or cocoa objectswhere do you go to grab reusable libraries for androidedit this is not just about library projects though this would be ideal on the flip side where do i publish my opensourced library projects over and above just github,['android'] +295015,does net 45 work side by side with net 40 i am interested in installing the net 45but i have heard that it is an inplace upgradesince the users at my company uses windows xp i cannot release any client side apps that use net 45i know i can target net 40 when i code but if i install net 45 is there risk of things working on my machine that will not work on a windows xp machine that only has net 40by the way i looked but did not see this question asked if it has been asked please point me to it and i will try to delete this one,['.net'] +295025,filter a list by another list c i have the following business objects public class itemcategorybo public string itemcategory get set public string title get set public class itembo public int itemid get set public string title get set public string itemcategory get set listitemcategorybo categorylist new listitemcategorybo itemcategorybo itemcategory new itemcategorybo itemcategoryitemcategorycd cars itemcategorytitle cars itemcategorybo itemcategory2 new itemcategorybo itemcategoryitemcategorycd planes itemcategorytitle planes categorylistadditemcategory categorylistadditemcategory2 listitembo itemlist new listitembo itembo item1 new itembo item1itemid 1 item1title 1st item item1itemcategorycd other itembo item2 new itembo item2itemid 2 item2title 2nd item item2itemcategorycd cars itembo item3 new itembo item3itemid 3 item3title 3rd item item3itemcategorycd planes itemlistadditem1 itemlistadditem2 itemlistadditem3if i have a list of a few categories how could i find a list of items that contain a category in the list of categories in my example i want to get back items 2 and 3,['c#'] +295041,trying to understand click events on elements when a click event handler is registered on a select element i find very inconsistent behavior across browsers i set up a jsfiddle demo heres what i seefirefox 12 on os x 107 lion event fires when the element is clicked the dropdown opens briefly does not stay open keyboard actions do not generate click actionsfirefox 12 on linux ubuntu lucid samechome 19 on os x no mouse or keyboard interaction triggers the click eventchrome 19 on linux first mouse click expands options subsequent click on either the stillpresent select or the options triggers click eventsafari 516 on os x similar to chrome on linux first click expands options subsequent click on options triggers click event unlike chrome safari hides the select element when showing optionsandroid browser on ice cream sandwich initial click triggers event options stay visible after the event and can be clicked clicking the options does not trigger another eventchrome beta for android ice cream sandwich same as android browseri would be happy if someone could tell me or point me to the standard but i guess it is not that useful since i have observed directly that no ones following it what i am suspecting is that this is an uncommon thing to try to do that maybe it is more common to listen for the change event instead is that true what about listening to clicks on the options i was not able to get that to work but it could have been a stupid bugto give a little more context i am replacing a select element built on google closures googuiselect because that component nicely mimics some desktop select renderings especially chromes but cannot do the fullscreen rendering of expanded options you see on a mobile browser and the application previously listened to that components googuicomponenteventtypeaction event which has no clear analog anywhere so i am just trying to find a consistent substitute,['javascript'] +295054,prevent click event after mousedown mouseup event is it possible with jquery to prevent a click event on the same element from being executed after a mousedown mouseup event has just been firedany helpexamples would be appreciated,"['javascript', 'jquery']" +295060,python idiomatic properties for structured data i have got a bad smell in my code perhaps i just need to let it air out for a bit but right now it is bugging mei need to create three different input files to run three radiative transfer modeling rtm applications so that i can compare their outputs this process will be repeated for thousands of sets of inputs so i am automating it with a python scripti would like to store the input parameters as a generic python object that i can pass to three other functions who will each translate that general object into the specific parameters needed to run the rtm software they are responsible i think this makes sense but feel free to criticize my approachthere are many possible input parameters for each piece of rtm software many of them overlap most of them are kept at sensible defaults but should be easily changedi started with a simple dictconfig day of year 138 time of day 360 seconds solar azimuth angle 73 degrees solar zenith angle 17 degrees there are a lot of parameters and they can be cleanly categorized into groups so i thought of using dicts within the dictconfig day of year 138 time of day 360 seconds solar azimuth angle 73 degrees zenith angle 17 degrees i like that but there are a lot of redundant properties the solar azimuth and zenith angles for example can be found if the other is known so why hardcode both so i started looking into pythons builtin property that lets me do nifty things with the data if i store it as object attributesclass configurationobject day of year 138 time of day 360 seconds solar azimuth angle 73 degrees property def solar zenith angleself return 90 selfsolar azimuth angle config configurationbut now i have lost the structure i had from the second dict examplenote that some of the properties are less trivial than my solar zenith angle example and might require access to other attributes outside of the group of attributes it is a part of for example i can calculate solar azimuth angle if i know the day of year time of day latitude and longitudewhat i am looking fora simple way to store configuration data whose values can all be accessed in a uniform way are nicely structured and may exist either as attributes real values or properties calculated from other attributesa possibility that is kind of boringstore everything in the dict of dicts i outlined earlier and having other functions run over the object and calculate the calculatable values this does not sound fun or clean to me it sounds messy and frustratingan ugly one that worksafter a long time trying different strategies and mostly getting no where i came up with one possible solution that seems to workmy classes smells a bit funcy er funky definitelyclass subconfigobject store logical groupings of object attributes and properties the parent object must be passed to the constructor so that we can still access the parent objects other attributes and properties useful if we want to use them to compute a property in here def init self parent args kwargs supersubconfig self init args kwargs selfparent parentclass configurationobject some object which holds many attributes and properties related configurations settings are grouped in subconfig objects def init self args kwargs superconfiguration self init args kwargs selfroot config 2 class aconfiggroupsubconfig sub config 3 property def sub propertyself return selfsub config selfparentroot config selfgroup aconfiggroupself stinkyhow i can use them works as i would likeconfig configuration inspect the state of the attributes and propertiesprintninitial configuration stateprintconfigrootconfig s configroot configprintconfiggroupsub config s configgroupsub configprintconfiggroupsub property s calculated configgroupsub property inspect whether the properties compute the correct value after we alter some attributesconfigroot config 4configgroupsub config 5printnstate after modificationsprintconfigrootconfig s configroot configprintconfiggroupsub config s configgroupsub configprintconfiggroupsub property s calculated configgroupsub propertythe behavior output of execution of all of the above code as expectedinitial configuration stateconfigrootconfig 2configgroupsub config 3configgroupsub property 6 calculatedstate after modificationsconfigrootconfig 4configgroupsub config 5configgroupsub property 20 calculatedwhy i do not like itstoring configuration data in class definitions inside of the main objects init does not feel elegant especially having to instantiate them immediately after definition like that ugh i can deal with that for the parent class sure but doing it in a constructorstoring the same classes outside the main configuration object does not feel elegant either since properties in the inner classes may depend on the attributes of configuration or their siblings inside iti could deal with defining the functions outside of everything so inside having things likepropertydef solar zenith angleself return calculate zenithselfsolar azimuth anglebut i cannot figure out how to do something likepropertydef solarzenith angleself return calculate zenithselfsolarazimuth anglewhen i try to be clever about it i always run into property object at 0xso what is the right way to go about this am i missing something basic or taking a very wrong approach does anyone know a clever solutionhelp my python code is not beautiful i must be doing something wrong,['python'] +295089,how to rotate a threejs vector3 around an axis how to rotate a threejs vector3 by a certain angle around an axis,['javascript'] +295102,what is the difference between typedef and using in c11 i know that in c11 we can now use using to write type alias like typedefstypedef int myintis from what i understand equivalent tousing myint intand that new syntax emerged from the effort to have a way to express template typedeftemplate class t using mytype anothertype t myallocatortype but with the first two nontemplate examples are there any other subtle differences in the standard for example typedefs do aliasing in a weak way that is it does not create a new type but only a new name conversions are implicit between those namesis it the same with using or does it generate a new type are there any differences,['c++'] +295119,php most efficient way to track if a user is online i am developing a project of mine with scalability in mind and i have come to a crossroad on my website i would like to detect if a user is online or not and i cannot quite think of the best way to handle this the way i was thinking would be something along these linesin psuedocode sql user tableuser name blah blah email online falseso whenever the user logs in i could update his online column to true however that would eventually lead to sql queries happening every time a user logs in and if it happens that i get say 10 logins per second well that is a lot of queries happening another way i figured i could do the same thing but in a different table activity tableactivity user id 2 online truefor some reason i believe that would lead to less memory consumption because of the separation from the user table however i am not sure if it would have any actual effect on performanceso if you could bless me with your insight i would be more then grateful thank you,['php'] +295122,recommended method for handling unsupportedencodingexception from stringgetbytesutf8 what is the recommended way to handle an unsupportedencodingexception when calling stringgetbytesutf8 inside a library method if i am reading correctly utf8 encoding should always be available which leads me to believe there is no reason to pass this exception on to the librarys consumer that is add a throws clause to the method signature it seems any failure mode that made utf8 encoding facilities unavailable would be catastrophic leading me to write this handler try return blahgetbytesutf8 catch unsupportedencodingexception e were assuming utf8 encoding is always available see eprintstacktrace return null prevent compiletime method must return a result errors is there a failure mode that wouldnt be addressed by this snippet,['java'] +295146,insert datetimenow to a webconfig during publishdeploy i want to have a date when an application was deployedpublished in my webconfigis there a way to achieve that with webconfig transformationswith xdttransformreplace i can replace any node with predefined value but is there a way to use some custom function to calculate that value like datetimenow,['asp.net'] +295166,yii controller cannot find the requested view i am encountering this error when rendering error viewapicontroller cannot find the requested view errorall directories are in small letters i am running yii on linux machinesample codeclass apicontroller extends api private api private placesapikeypublic function construct parent constructapi uri explode yiiapprequestgetquerystring thisapi enduri thisplacesapikey if thisapi yiiaparamsapikey thisapi errordatatitle unauthorized access errordatamessage you are not authorized to access or view this area thisrendererror error exit,['php'] +295192,xlrderror expected bof record found 0x4b50 i do not think there is something wrong with the codes can you help me i need help thank youfrom xlrd import open workbookwb open workbookpdfexexcxlsxrbfor s in wbsheets print sheetsname for row in rangesnrows values for col in rangesncols valuesappendscellrowcolvalue print joinvalues print,['python'] +295245,consuming webservice having wsdl and xsd files weve requested a company to write a webservice that we can use to get some informationthey have sent us wsdl and xsd files could you please tell me how i can use these files to query data i can do it easily if i have a link to a webservice i just provide the link and visual studio generates web reference for me after that i can use that reference just like a normal class in this case i have no link just above mentioned files thank you,['c#'] +295266,why does the ld linker allow multiple class definitions with the same methods consider this file firstcpp containing a class definition and useinclude iostreamstruct foo foo stdcout foo stdendl foo stdcout foo stdendl int main foo f return 0and another secondcpp containing a conflicting class definitioninclude iostreamstruct foo foo foofoofoo stdcout wrong foo stdendl the linker complains about duplicate symbols when there are two functions with the same names defined but these files with duplicate class methods compile without an errori compiled with these commands g c secondcpp o second g second firstcpp o firstreordering the arguments to the second g call does not change the outputand when first is run this is the output firstfoowrong foowhy does the linker allow duplicate class methods if it is apparently allowed why is wrong foo printed,['c++'] +295274,jquery tired of csscsscss i am really tired of syntax like thiscsspositionabsolutecsszindexzindexcssborder1px solid 00afcssmargin1px 0px 0px 1pxcssleftplefti wonder if there is any way to pass all parameters in one function something likefoopositionabsolutezindexzindex border1px solid 00afmargin1px 0px 0px 1px leftpleftmuch appreciate any help,"['javascript', 'jquery', 'css']" +295302,why does webkittransformstyle preserve3d make some divs thisappear the following code should show a header bar a footer bar and an image but for some reason as soon as i add div1 webkittransformstyle preserve3d i only get the header bar i know it appears to have some unnecessary divs and style applied but i do need them for effects that i have stripped out to make debugging easier my page code ishtml head titletitle style body margin 0px div1 webkittransformstyle preserve3d div2 position absolute width 100 height 100 img maxwidth 50 maxheight 50 thisplay block footer position fixed bottom 0px style head body div classdiv1 div classdiv2 div classheader header div div classimgdiv img src div div classfooter footer div div div bodyhtml,['css'] +295303,how to capture all requests made by page in webdriver is there any alternative to browsermob i am using selenium2webdriver to test my web applications all the tests are written in java and run with mavenwhile opening a page with webdriver i would like to capture all the requests made by page images js and css files etc i use this data mainly for two reasonschecking for 404 and other errors in callschecking if analytics code is working checking if it is sending proper requestsdepending on the project i use either firebug with netexport or browsermob proxy in both cases i can easily obtain a har html archive file parse it and extract the data i wantheres the problemi am not happy with neither of these solutions i have especially problems with getting har file when a page contains video that is being loaded too long i am looking for something more stableso the questions areis there any alternative to browsermob i know about fiddlercore but it is a net library and my tests are written in java i have also heard about ajax dynatrace and i know that there is some way to integrate it with selenium but the documentation i found was for seleniumrc not webdriveris there any way to integrate dynatrace with webdriver or use fiddlercore with javais there any other way to achieve the goals i mentioned i am looking for a proxy that i can easily control from my code exporting data to har would be a great plus,['java'] +295307,get current url of the popup window with javascript i had a webpage with a link which opens a new page in a popup windoweverything is fine till here the popup window contains credit card payment page held by some 3rd party server after completing the payment flow the response is shown and there is change in the urli need to get that urlis it is possible in javascript,"['javascript', 'jquery']" +295310,injectmocks behaving differently with java 6 and 7 with a very simple mockito run junit test and class i am seeing different output when the test is run with java 160 32 and java 170 04 and want to understand why this is happening i suspect there is some type erasure going on but would like a definitive answerhere is my example code and instructions on how to run from the command linefooservicetestjavaimport orgjunitimport orgjunitrunnerimport orgmockitoimport orgmockitorunnersmockitojunitrunnerimport static orgmockitomockitoimport javautilrunwithmockitojunitrunnerclasspublic class fooservicetest mock mapstring string mockstringstring mock mapstring integer mockstringinteger injectmocks fooservice fooservice public static void mainstring args new junitcorerunfooservicetestclass before public void setup mockitoannotationsinitmocksthis test public void checkinjection whenmockstringstringgetfoothenreturnbar fooserviceprintln fooservicejavaimport javautilpublic class fooservice private mapstring string stringstring new hashmapstring string private mapstring integer stringinteger new hashmapstring integer public void println systemoutprintlnstringstringgetfoo stringinteger to compile and run this examplesave the above into filesdownload and put in the same directory junit410jar and mockitoall190jarset path to include a jdkcompile with javac cp junit410jarmockitoall190jar javarun with java cp junit410jarmockitoall190jar fooservicetesti believe the output from above is null because injectmocks field injection cannot correctly resolve the types since they are both of type map is this correctnow changing one of the mock names to match the field in the class should allow mockito to find a match for example changingmock mapstring integer mockstringintegertomock mapstring integer stringintegerthen compilingrunning with java 160 32 gives imho the expected output bar stringinteger but with 170 04 gives null stringintegerhere is how i am running it from a command line in windows 7esrcmockitotestset pathcprogram files x86javajdk160 32binesrcmockitotestjavac cp junit410jarmockitoall190jar javaesrcmockitotestjava cp junit410jarmockitoall190jar fooservicetest bar stringintegeresrcmockitotestset pathcprogram files x86javajdk170 04binesrcmockitotestjavac cp junit410jarmockitoall190jar javaesrcmockitotestjava cp junit410jarmockitoall190jar fooservicetest null stringinteger,['java'] +295366,get raw json string in newtonsoftjson library i have json like this name somenameofevent type event data object age 18 petname 18 desct and i have 2 objects like thispublic class custevent jsonpropertyname public string name get set jsonpropertytype public string eventtype get set jsonpropertydata public somedata data get set public class somedata jsonpropertyobject public string someobject get set jsonpropertydsct public string somedesct get set i use to parse json to object newtonsoftnet library and how i can get raw json into someobject somedesct properties in json dataobject are complex object and i want to get only raw json string to those properties can you help me,['.net'] +295384,importing google calendar data via api v3 to google app engine with java i am in the process of writing a java rest api for a reservation system where the event data comes google calendar readonly i am currently trying to figure out the best way to obtain and store the event data from google calendar in google app engines jpa datastore i also have a few requirementsi need to save the previous calendar data simply dropping everything in the database and replacing it with new data will not suffice because i want to keep a historial view of the data for statistical purposesi need to notify users when the event data changes specifically for deletions this requires me to diff the new event data from the api with the old event data from the jpa datastoredoes anyone have any general guidance and suggestions for what to do am i approaching the problem the correct way by attempting to duplicate the data into a datastore should i just make api requests every time i need to use the data if i were do that is there a way to kick off some mail service to notify users of event changes from directly within google calendar,['java'] +295386,post to a google google plus is there anyone who knows how to post something in a google stream with an ios applicationi read everywhere that it is not possible to edit we can only read the postscan any one confirm this please,"['iphone', 'objective-c', 'ios']" +295419,a list of android apis that require certain android permissions is there a way to tell if a certain android permission is required by which android apis for example which apis will require the get tasks or reboot permissions my app inherited from someone whos long gone has these permissions listed in the manifest i do not think we are using them but i am also afraid that if i remove them there will be bad consequences any ideas on how to deal with this,['android'] +295423,requirejs in a chrome extension define is not defined i am trying to use requrejs in my chrome extensionhere is my manifest namemy extension version10 manifest version2 permissions httplocalhost web accessible resources jstestjs content scripts matcheshttplocalhost js jsrequirejs jshd initjs hd initjsconsoleloghello i am initrequireconfig baseurl chromeextensiongeturljsrequire jstest function consolelogdone loadingjstestjsconsoleloghello i am testdefinetest valtestthis is what i get in consolehello i am init chromeextensionbacjipelbpjnplcihblbcbbeahedpojshd initjs8hello i am test testjs8uncaught referenceerror define is not defined testjs2done loading so it loads the file but cannot see define functionthis looks like some kind of a scope errorif i run in on local server it works as it should any ideas,['javascript'] +295453,trouble designing recursion with limited results i am having trouble fixing this problem it is been plaguing me since yesterday sorry i posted this earlier then deleted it because i thought i solved it but it turned out to be another bug i fixed i am trying to simply take a list of items and a range and to find combinations that would allow all items to be usedheres an example imagine you have 4 items apple pear peach and orange and want a minimum of 20 of the basket to contain each and a maxium of 60 for example you could have 25 25 25 25 of each item or 30 30 20 20 and so on but 0 0 50 50 does not work because the specified min is 20the program works fine but it uses items less than the entire list instead of 4 items in every solution some solutions contain 2 or 3 items which is not what i want if i send a list of 4 items i want the combinations using all 4 items togethers and nothing less i do not want this because i plan to use large lists and i want the size to be items used to only be all and nothing less than the min heres an example using the above information4 items 2060 rangegood apples 22 pears 24 peach 25 orange 29 total 100bad apples 0 pears 0 peach 40 orange 60 total 100 although total is correct the example fails because the minimum of 20 per item was not obeyedi am really confused as to why this is happening but if i had to bet i would think it is the way my recursion is taking the number of items in the list and subtracting one before sending it back its in the method recursion partprivate static void recursion partint k int sum int coeff k is number of items in the listin this example its 403 sum is the remaining total percent to break down coeff is the template to store values this recursively takes the sum and tries to find lower values of it until it equals zero using the bounds given for int c low boundk c high boundk c coeffk c int newcoeff arrayscopyofcoeff coefflength if c sum 0 resultsaddnewcoeff printresultsnewcoeff break else if k 0 recursion partk 1 sum c newcoeff i want to work on larger lists and i think it will be a problem if it calculates a lot of results that i do not care for how can i redesign this to only process all items in the list and stay within the range limitsi thought of putting a method that checks how many zeros there are in the list and then breaks if it goes below the size of the list but the fact that i am getting blank results means its processing items less than my list and i am thinking its better to design the program so it does not waste resourcesheres the entire code it works as described but is giving zero results as mentionedimport javautilarraylistimport javautilarrayspublic class recursion percent returner static final int target percent 100 static final string names new string apples pears peach orange static int low bound new intnameslength static int high bound new intnameslength static arraylist results new arraylist queue to store results static int default coeff new intnameslength public static void mainstring args systemoutprintlnstarting systemoutprintlnlist size nameslength arraysfilow bound 20 fills the min list with default value arraysfillhigh bound 60 fills the max list with default value recursion partnameslength1target percentdefault coeff systemoutprintlntotal size of results are resultssize private static void recursion partint k int sum int coeff k is number of items in the listin this example its 403 sum is the remaining total percent to break down coeff is the template to store values this recursively takes the sum and tries to find lower values of it until it equals zero using the bounds given for int c low boundk c high boundk c coeffk c int newcoeff arrayscopyofcoeff coefflength if c sum 0 resultsaddnewcoeff printresultsnewcoeff break else if k 0 recursion partk 1 sum c newcoeff private static void printresultsint newcoeff for int x 0 xnewcoefflength x systemoutprintlnnamesx newcoeffx systemoutprintln thanks and if there is a better way to achieve the outcome i am looking for please let me know ps this is not homework and i am not a student i just have a tendency to find weird sounding proxy problemsedit i included the entire code but heres the output as well it is a snippet of the 2653 solutions which is generating more than what i need if you look at it briefly youll see that most are correct but as you get lower youll see not all values are being used i only want the solutions that are using all values there should be no 0 valueentries,['java'] +295514,jboss 71 no suitable driver found javamysql could not open connection i was looking for an answer but did not find solutioni am developing simple webapp using jsf2 and hibernate this is first time i am using hibernate and i am facing many problems with configuration my current issue isi configured mysql connector as a module in jboss71 modules then i created datasource and added mysqlconnectorjava5120binjar to the classpath it is in webinflib directory in war after starting jboss i am getting following logs234407497 info orgjbossasconnectorsubsystemsdatasources serverservice thread pool 27 jbas010403 deploying jdbccompliant driver class orgh2driver version 13234407603 info orgjbossasconnectorsubsystemsdatasources serverservice thread pool 27 jbas010404 deploying nonjdbccompliant driver class commysqljdbcdriver version 51234420348 info orgjbossasconnectordeployersjdbc msc service thread 13 jbas010404 deploying nonjdbccompliant driver class commysqljdbcdriver version 51234421532 info orghibernateservicejdbcconnectionsinternaldrivermanagerconnectionproviderimpl msc service thread 13 h0401 using driver commysqljdbcdriver at url jdbcmysqllocalhosttestdb234421535 info orghibernateservicejdbcconnectionsinternaldrivermanagerconnectionproviderimpl msc service thread 13 h046 connection properties userroot234421556 warn orghibernateenginejdbcinternaljdbcservicesimpl msc service thread 13 h0342 could not obtain connection to query metadata no suitable driver found for jdbcmysqllocalhosttestdband then application is deployed and server starts successfully when i try to invoke method trying to persist some data i obtain orghibernateexceptionjdbcconnectionexception could not open connectionandjavasqlsqlexception no suitable driver found for jdbcmysqllocalhosttestdbi am sure the mysqlconnectorjava5120binjar is in the webinflib directory in war file any ideas what am i missing here mysql server wersion is 5163 but i do not think it is relevant here thanks a lot in advanceeditport is ok i checked everything two times but now i am really confused because code is working well outside the container i created class which uses the same code hibernateutil to obtain session factory and there are no exceptions and data is inserted to db could you please explain me why it is working in that way and why it is not working under the container and how to fix this because i have no idea thank you very muchmy standalonexml file server xmlnsurnjbossdomain12 extensions extension moduleorgjbossasclusteringinfinispan extension moduleorgjbossasconfigadmin extension moduleorgjbossasconnector extension moduleorgjbossasdeploymentscanner extension moduleorgjbossasee extension moduleorgjbossasejb3 extension moduleorgjbossasjaxrs extension moduleorgjbossasjdr extension moduleorgjbossasjmx extension moduleorgjbossasjpa extension moduleorgjbossaslogging extension moduleorgjbossasmail extension moduleorgjbossasnaming extension moduleorgjbossasosgi extension moduleorgjbossaspojo extension moduleorgjbossasremoting extension moduleorgjbossassar extension moduleorgjbossassecurity extension moduleorgjbossasthreads extension moduleorgjbossastransactions extension moduleorgjbossasweb extension moduleorgjbossaswebservices extension moduleorgjbossasweld extensions management securityrealms securityrealm namemanagementrealm authentication properties pathmgmtusersproperties relativetojboserverconfigdir authentication securityrealm securityrealm nameapplicationrealm authentication properties pathapplicationusersproperties relativetojboserverconfigdir authentication securityrealm securityrealms managementinterfaces nativeinterface securityrealmmanagementrealm socketbinding nativemanagementnative nativeinterface httpinterface securityrealmmanagementrealm socketbinding httpmanagementhttp httpinterface managementinterfaces management profile subsystem xmlnsurnjbossdomainlogging11 consolehandler nameconsole level nameinfo formatter patternformatter patterndhhmms 5p c t sen formatter consolehandler periodicrotatingfilehandler namefile formatter patternformatter patterndhhmms 5p c t sen formatter file relativetojboserverlogdir pathserverlog suffix valueymmdd append valuetrue periodicrotatingfilehandler logger categorycomarjuna level namewarn logger logger categoryorgapachetomcatutilmodeler level namewarn logger logger categorysunrmi level namewarn logger logger categoryjacorb level namewarn logger logger categoryjacorbconfig level nameerror logger rootlogger level nameinfo handlers handler nameconsole handler namefile handlers rootlogger subsystem subsystem xmlnsurnjbossdomainconfigadmin10 subsystem xmlnsurnjbossdomaindatasources10 datasources datasource jndinamejavajbossdatasourcestestds poolnametestds connectionurljdbcmysqllocalhost3306testdbconnectionurl drivermysqldriver pool minpoolsize10minpoolsize maxpoolsize20maxpoolsize prefilltrueprefill pool security usernamerootusername security datasource datasource jndinamejavajbossdatasourcesexampleds poolnameexampleds enabledtrue usejavacontexttrue connectionurljdbch2memtestdb close delay1connectionurl driverh2driver security usernamesausername passwordsapassword security datasource drivers driver nameh2 modulecomh2databaseh2 xadatasourceclassorgh2jdbcxjdbcdatasourcexadatasourceclass driver driver namemysql modulecommysql drivers datasources subsystem subsystem xmlnsurnjbossdomaindeploymentscanner11 deploymentscanner pathdeployments relativetojboserverbasedir scaninterval50 subsystem subsystem xmlnsurnjbossdomainee10 subsystem xmlnsurnjbossdomainejb312 sessionbean stateless beaninstancepoolref poolnameslsbstrictmaxpool stateless stateful defaultaccesstimeout50 cacherefsimple singleton defaultaccesstimeout50 sessionbean pools beaninstancepools strictmaxpool nameslsbstrictmaxpool maxpoolsize20 instanceacquisitiontimeout5 instanceacquisitiontimeoutunitminutes strictmaxpool namemdbstrictmaxpool maxpoolsize20 instanceacquisitiontimeout5 instanceacquisitiontimeoutunitminutes beaninstancepools pools caches cache namesimple aliasesnopassivationcache cache namepassivating passivationstorereffile aliasessimplestatefulcache caches passivationstores filepassivationstore namefile passivationstores async threadpoolnamedefault timerservice threadpoolnamedefault datastore pathtimerservicedata relativetojboserverdatadir timerservice remote connectorrefremotingconnector threadpoolnamedefault threadpools threadpool namedefault maxthreads count10 keepalivetime time100 unitmilliseconds threadpool threadpools subsystem subsystem xmlnsurnjbossdomaininfinispan12 defaultcachecontainerhibernate cachecontainer namehibernate defaultcachelocalquery localcache nameentity transaction modenon xa eviction strategylru maxentries10 expiration maxidle10 localcache localcache namelocalquery transaction modenone eviction strategylru maxentries10 expiration maxidle10 localcache localcache nametimestamps transaction modenone eviction strategynone localcache cachecontainer subsystem subsystem xmlnsurnjbossdomainjaxrs10 subsystem xmlnsurnjbossdomainjca11 archivevalidation enabledtrue failonerrortrue failonwarnfalse beanvalidation enabledtrue defaultworkmanager shortrunningthreads corethreads count50 queuelength count50 maxthreads count50 keepalivetime time10 unitseconds shortrunningthreads longrunningthreads corethreads count50 queuelength count50 maxthreads count50 keepalivetime time10 unitseconds longrunningthreads defaultworkmanager cachedconnectionmanager subsystem subsystem xmlnsurnjbossdomainjdr10 subsystem xmlnsurnjbossdomainjmx11 showmodel valuetrue remotingconnector subsystem subsystem xmlnsurnjbossdomainjpa10 jpa defaultdatasource subsystem subsystem xmlnsurnjbossdomainmail10 mailsession jndinamejavajbossmaildefault smtpserver outboundsocketbindingrefmailsmtp mailsession subsystem subsystem xmlnsurnjbossdomainnaming11 subsystem xmlnsurnjbossdomainosgi12 activationlazy properties property nameorgosgiframeworkstartlevelbeginning 1 property properties capabilities capability namejavaxservletapiv25 capability namejavaxtransactionapi capability nameorgapachefelixlog startlevel1 capability nameorgjbossosgilogging startlevel1 capability nameorgapachefelixconfigadmin startlevel1 capability nameorgjbossasosgiconfigadmin startlevel1 capabilities subsystem subsystem xmlnsurnjbossdomainpojo10 subsystem xmlnsurnjbossdomainremoting11 connector nameremotingconnector socketbindingremoting securityrealmapplicationrealm subsystem subsystem xmlnsurnjbossdomainresourceadapters10 subsystem xmlnsurnjbossdomainsar10 subsystem xmlnsurnjbossdomainsecurity11 securitydomains securitydomain nameother cachetypedefault authentication loginmodule coderemoting flagoptional moduleoption namepasswordstacking valueusefirstpass loginmodule loginmodule coderealmusersroles flagrequired moduleoption nameusersproperties valuejboserverconfigdirapplicationusersproperties moduleoption namerolesproperties valuejboserverconfigdirapplicationrolesproperties moduleoption namerealm valueapplicationrealm moduleoption namepasswordstacking valueusefirstpass loginmodule authentication securitydomain securitydomain namejbosswebpolicy cachetypedefault authorization policymodule codedelegating flagrequired authorization securitydomain securitydomain namejbossejbpolicy cachetypedefault authorization policymodule codedelegating flagrequired authorization securitydomain securitydomains subsystem subsystem xmlnsurnjbossdomainthreads11 subsystem xmlnsurnjbossdomaintransactions11 coreenvironment processid uuid processid coreenvironment recoveryenvironment socketbindingtxnrecoveryenvironment statussocketbindingtxnstatusmanager coordinatorenvironment defaulttimeout300 subsystem subsystem xmlnsurnjbossdomainweb11 defaultvirtualserverdefaulthost nativefalse connector namehttp protocolhttp11 schemehttp socketbindinghttp virtualserver namedefaulthost enablewelcomeroottrue alias namelocalhost alias nameexamplecom virtualserver subsystem subsystem xmlnsurnjbossdomainwebservices11 modifywsdladdresstruemodifywsdladdress wsdlhostjbossbindaddress127001wsdlhost endpointconfig namestandardendpointconfig endpointconfig namerecordingendpointconfig prehandlerchain namerecordinghandlers protocolbindingssoap11 http soap11 http mtom soap12 http soap12 http mtom handler namerecordinghandler classorgjbosswscommoninvocationrecordingserverhandler prehandlerchain endpointconfig subsystem subsystem xmlnsurnjbossdomainweld10 profile interfaces interface namemanagement inetaddress valuejbossbindaddressmanagement127001 interface interface namepublic inetaddress valuejbossbindaddress127001 interface interface nameunsecure inetaddress valuejbossbindaddressunsecure127001 interface interfaces socketbindinggroup namestandardsockets defaultinterfacepublic portoffsetjbosocketbindingportoffset0 socketbinding namemanagementnative interfacemanagement portjbossmanagementnativeport9 socketbinding namemanagementhttp interfacemanagement portjbossmanagementhttpport90 socketbinding namemanagementhttps interfacemanagement portjbossmanagementhttpsport9443 socketbinding nameajp port8009 socketbinding namehttp port8080 socketbinding namehttps port8443 socketbinding nameosgihttp interfacemanagement port8090 socketbinding nameremoting port47 socketbinding nametxnrecoveryenvironment port4712 socketbinding nametxnstatusmanager port4713 outboundsocketbinding namemailsmtp remotedestination hostlocalhost port25 outboundsocketbinding socketbindinggroup deployments deployment namejbossashelloworldjsfwar runtimenamejbossashelloworldjsfwar content sha187e5656e4c0b15f7864df9e68328d2909a1144 deployment deploymentsserveri am using hibernate 413 i had to add hibernate jars as external jars to build path even after changes in modulesorghibernatemain i changed modulexml and replaced old jars after that changes i got different exception during deploy orghibernateserviceclassloadingspiclassloadingexception specified jdbc driver commysqljdbcdriver class not found in jbos logs there is mentioned that commysqljdbcdriver is deployed help,"['java', 'mysql']" +295533,handling database constraint hibernate my project is using hibernate with spring transaction manager and my database is postgres might be irrelevant i am trying to read big xml files and construct objects out of those objects are not big but the amount is and insert them into databaseif by some chance one of my objects violates database constraint the whole process stops how can i skip the ones which violate the database constraint alternatively log their id or whatever to a log filequestion updatei have been browsing trough so and found that for batch inserts it is best recommended to use stateless session but i still get the same issue and insert stops may 26 2012 44547 pm orghibernateutiljdbcexceptionreporter logexceptionssevere error duplicate key value violates unique constraint un fk detail key fidh1 already existshere are the relevant parts of my code for parsing xml and inserting into db for simplicity let us assume i am inserting movies class fieldautowiredprivate sessionfactory sessionfactoryoverridepublic void startdocument throws saxexception session sessionfactorygetcurrentsessionoverridepublic void endelementstring uri string localname string qname throws saxexception if qnameequalsignorecasefilm moviesetcategorycategory moviesetaddednew date sessioninsertmovie i and have this property set in the appctx hibernatejdbcbatch size to 100 is it really necessary to do select before insert in order to avoid this update 2if i use statelesession instead of session i get arround 20 inserts and than the processing stops indefinitely without any exception or anythingi assume the number 20 is because i am pooling connections with tomcat and have maxactive20bounty update i would really love to see someone offer solution without defensive select if possible using statelesession or just session,['java'] +295566,how to install python3 version of package via pip on ubuntu i have both python27 and python32 installed in ubuntu 1204the symbolic link python links to python27when i typesudo pip install packagenameit will default install python2 version of packagenamesome package supports both python2 and python3how to install python3 version of packagename via pip,['python'] +295575,thisabling bounces in uitableview also thisables scrolling on ios 5 but not ios4 i have an app with a table view in a nav controller i wanted to thisable bouncing so that when my table is in edit mode user can scroll down and find rows to delete otherwise it would bounce back and not give them the opportunity to press the delete icon next to the rowso i did thisselftableviewbouncesnowhen i run my app on ios 4 this works like a charm user can scroll and the table does not bounce backbut on ios 5 the scrolling is also not working at all for the table no scroll so to be safe i did this selftableviewbouncesno selftableviewscrollenabledyesbut this made no differencei create my table view and its nav controller programmatically everything else is working fine with them any idea why thisabling bounces would also prevent scrolling on ios 5,"['iphone', 'objective-c']" +295580,putting inside is adding an extra from in html 4 the div element cannot be inside another blocklevel element like a p element however in html5 the div element can be found inside and can contain other flow content elements like p and divi have something like this inside a formp label input pbut when rails autogenerates an error explanation div wrapping the input the one paragraph turns into two and i see this in firebugp label p div input div p palso if i just add a simplep div test div pthe same issue occurs jsfiddle and it gets rendered in the dom asp p div test div p pwhyupdate i emailed the author of the article and she made the appropriate changes,['html'] +295606,htmljavascript remote img src with automatic httphttps prefix thisplaying an image from a remote serverimg srchttpremotehostpathtoapng altimage a however if the current page is accessed via https linking images via unencrypted http will yield security warnings while i could just specify https regardless of the current protocol doing so would be wasteful since i really do not care to secure the transmission of this image unless it is necessary when the visitor is using httpsis it possible to specify a url for the src attribute of the img tag such that the protocol in the url is dynamically chosen based on the protocol used to access the current page to illustrate what i meanimg srcjavascripts windowlocationprotocolremotehostpathtoapng altimage a what if we use javascript we could give the img tag an id so that we can locate it and set the src to start with windowlocationprotocolcould also use base64 to bypass the httphttps problem altogether but this is not ideal for what i am doingwhat can you guys recommend,"['javascript', 'html']" +295620,what does this code of rendersection mean i am a beginner in aspnet mvc3 can anybody please explain what is meant by this codesection head rendersectionhead falseon scottgus articlethere is an example of rendersection but it defines section and then somewhere rendersection is used in this case section head is defined and within that itself the same head is being rendered which confused mewhat does rendersection do and how do i find what is being rendered here,"['c#', 'asp.net']" +295661,highcharts remove zero value labels i am implementing highcharts in my site however is proving challenging from a presentation point of view my data loads fine but for the series some of the values are zeros i would like to thisplay the label when not zero as otherwise it becomes hard to readi am trying to do something like thisplotoptions column stacking normal datalabels enabled thisvalue 0 false true color highchartstheme highchartsthemedatalabelscolor white but this is not working i have tried using only this instead of value but also does not pick it up i have not been able to find a default option from the library that would allow me to do this without having to create custom codei have checked a few approaches but the zeros are in one of the series so i still want to present the label for the values that are not zeros for the groupi think when one says thisy it takes the value of the entire group and not the individual seriesany suggestions clearly i am doing something wrong,['jquery'] +295678,is there a repl for c programming i am on osx i found this but the links on that page for code seem to be broken,['c'] +295686,how to install pyinstaller i am on windowsi want to use pyinstaller i could always create bin files with pyinstallerpy argsit is not a package with an init py fileit has no setuppyand it does not work to create a folder put it in my pythonpath put pyinstallerfiles in that folder and then make a call to python pyinstallerpyinstallerpypyinstallerorg only tells me something with configurepyso now i am out of ideas how to install pyinstaller so that i do not have to work with absolute paths do you have any ideas,['python'] +295716,correct way to losslessly convert to and from stdstring and qbytearray what is the correct way to convert losslessly between stdstring and qbytearray mostly for the purpose of handling binary datai am usingqbytearray qba qstringfromstdstringstdstringtoasciiandqstringqbatostdstringbut i wanted to check whether this is actually correct,['c++'] +295726,how do i declare a 2d string arraylist i want to do something like this arrayliststringstring mylisthow can i create ithow can i add to the external and internal listand how can i convert the internal list to a simple array list,['java'] +295742,graphic drawline draw line and move it in my net c program i draw few lines using values from text boxes i use drawline function i want to be able to move one of this lines by clik on it and move this line with mouse is it possible,"['c#', '.net']" +295825,using metaclasses to override methods of complex builtin as a learning exercise i am trying to implement a class which will emulate the behavior of pythons complex builtin but with different behavior of the str and repr methods i want them to print in the format1020instead of12ji first tried simply subclassing from complex and redefining str and repr but this has the problem that when nonoverridden methods are called a standard complex is returned and printed in the standard format a complexwrapper1010 a1010 b complexwrapper2030 b2030 a b34jwhen the desired output is 3040i was reading about metaclasses and thought they would solve my problem starting from the answer in python class decorator my current implementation is as followsdef complex strz return strzreal strzimag def complex reprz return reprzreal reprzimag class cmplxmetatype def new cls name bases attrs attrs str complex str attrs repr complex repr return supercmplxmeta cls new cls name bases attrsclass complexwrappercomplex metaclass cmplxmetaunfortunately this seems to have the same behavior as the previous solution eg when two complexwrapper instances are added to each other i admit i do not fully understand metaclasses maybe my problem can be solved in a different wayof course i could manually redefine the relevant methods such as add subtract etc but that would be very repetitive so i would prefer a more elegant solutionany help appreciatededit response to agfs answerso a number of things i do not understand about your codewhere does the new method of the returntypewrapper metaclass get its arguments from if they are passed automatically i would expect in this case that name complex bases complex dict is that correct is this method of automatic passing of class data specific to metaclasseswhy do you use cls type new mcs name bases dct instead of cls typemcs name bases dctis it just to avoid confusion with the other meaning of typei copied your code and added my special implementations of str and repr in your complexwrapper class but it does not work printing any object of type complex just prints in the standard python format i do not understand that as the two methods should have been picked up in the for loop of the metaclass but should have been overridden by my definitions afterwardthe relevant section of my codeclass complexcomplex metaclass returntypewrapper wrapped base complex def str self return strselfreal strselfimag def repr self return reprselfreal reprselfimag and its behavior typeaclass cmplx2complex a str bound method complexwrapper of 11j a str 11j thanks again for your answer and feel free to editremove the above if you address them in your answer,['python'] +295835,bitmaplockbits confusion msdn reference 1 from the link it says that the first argument will specifies the portion of the bitmap to lock which i set to be a smaller part of the bitmap bitmap is 500x500 my rectangle is 005050 however the returned bitmapdata has stride of 1500 5003 so basically every scan will still scan through the whole picture horizontally however what i want is only the top left 50x50 part of the bitmaphow does this work out,['c#'] +295839,abstracting dimensionality of arrays in java in java arrays of different dimensionalities have different types so a method that takes int as a parameter cannot take int or int i have a lot of code where i create methods that are quite similar but for the dimensionality of the array is there a way to handle arrays of arbitrary dimensionality and thus abstract out this common functionality,['java'] +295877,how to change page format in runtimejasperreport i created a report page with a4 format in ireport45 and use in java applicationhow to change a4 to a5 format on runtime in java application,['java'] +295902,set defualt language for html inputs how to set default keyboard layout for input boxesfor example when the page gets loaded we can type in an input text with another keyboard language else than english,['html'] +295903,searching from a range of ids in activerecord how can i do something like this in rangeuserfind14014500i need to choose a certain range of users starting and finishing on specifics ids,"['ruby-on-rails', 'ruby']" +295915,drawing 1 pixel wide paths in ios i am drawing a path in my drawrect implementation on a uiview withcgcontextsetlinewidthcontext 05cgcontextstrokepathcontextwith antialiasing on on my cgcontext i cannot seem to draw 1 px linesi tried turning antialiasing off withcgcontextsetshouldantialiascontext nobut then my corners look terriblehow do i keep antialiasing on but stop this subpixel bluring of 1 pixel lines,"['objective-c', 'ios']" +295945,what is the equivalent of androidwindowsoftinputmode for a web site i am building a web site app that will be used from android devices at the moment the browser squashes the page when the soft keyboard appears i rather want it to scroll the page upi have read that the property androidwindowsoftinputmode in androidmanifestxml can be used for android apps but i am looking for an equivalent for a web site,['android'] +295976,julias python performance example in pypy julia is a new statistical programming language that claims significantly better performance than competing languages i am trying to verify this julia has a performance test written in pythoni cannot get it to work with pypy perhaps this is due to numpypy incompatibilities with numpy but i am not getting far enough to determine that i followed the importerror advice or just write import numpypy first in your program but i get another importerror no module named numpylinalgi have near zero experience with python and i am looking for a complete solution that i can run the benefit of getting this to work is that we can we have a applestoapples jit langtojit lang comparison,['python'] +295979,how to simulate pinch on blackberry 10 simulator i am developing a project using the native sdk for blackberry 10 i am using blackberry 10 dev alpha simulator for testing purposes i cannot seem to simulate a pinch event and did some searching just to find out that this is not implemented yet in the simulatorso basically i need a method to programatically create a pinch and run it when some other event is triggered what is the easiest way to do thisediti am not looking for languageagnostic solutions i need an architectural implementation how would one go on using gesture pinch t to create a pinch event even with hardcoded parameters,"['c++', 'c']" +296000,why is xrange able to go back to beginning in python i have encountered this code from most pythonic way of counting matching elements in something iterabler xrange1 10print sum1 for v in r if v 2 0 4print sum1 for v in r if v 3 0 3r is iterated once and then it is iterated again i thought if an iterator is once consumed then it is over and it should not be iterated againgenerator expressions can be iterated only oncer 7 i for i in xrange1 10print sum1 for v in r if v 2 0 4print sum1 for v in r if v 3 0 0enumeratel toor enumeratemylistand file object toof openmyfilename rwhy does xrange behave differently,['python'] +296010,testing for equality of regular expressions i was surprised to see that a aevaluates to false in javascript reading through the specstwo regular expression literals in a program evaluate to regular expression objects that never compare as to each other even if the two literals contents are identicalsince cannot be used to test for equality how can equality of regular expressions be tested in javascript,['javascript'] +296029,beautifulsoup findall not within certain tag so i am trying to find a way to find all items within a beautifulsoup object that have a certain tag that are not within a certain other tag for exampletd classthisabled first div classdaycontainer p classday 29 p p classmorelink p divtd i want to find all iterations of classdaycontainer which is simple enough but how do i go about finding all of those that are not first within classdiabled,['python'] +296039,using groovy on android with the advent of asmdex asm for dex files and dexmaker should not it be possible to port groovy to android both frameworks allow the generation of dex bytecode at runtime as i understand it it is impossible to modify dex classes from the apk in memory but wouldnt it be possible to copy those classes to writable memory modify those copies at runtime and use them what else needs to be ported to handle dex class files cglib,['android'] +296042,questions about entity framework context lifetime i have some questions about the desired lifetime of an entity framework context in an aspnet mvc application is not it best to keep the context alive for the shortest time possibleconsider the following controller actionpublic actionresult index ienumerablemytable model using var context new myentities model from mt in contextmytable select mt return viewmodelthe code above would not work because the entity framework context has gone out of scope while the view renders the page how would others structure the code above,['c#'] +296049,jquery mobile pinch zoom image only i have a working jqm application that i would like to thisplay some images in the images currently are in their own iframe so they can be scrolled separately from the app i would like to be able to pinch zoom only the images within the iframe as well i realize if i adjust the following code snippet that i can enable pinch zoom but this enabled it for the entire application meta nameviewport contentwidthdevicewidth initialscale10 maximumscale10 userscalableno by removing maximumscale pinch zoom returns but for everything is there a way to enable pinch zoom only for an image how about adding a new viewport tag to the iframe would that work if that is even possibleupdateinjected html into the iframe added the meta tag this did not helptried extendmobilezoom lockedfalseenabledtrue on the iframe body this did nothing,"['jquery', 'html']" +296057,can i mark a field invalid from javascript from reading this post i have found that there are some pseudo classes for invalid and invalid input valuesis there a way i can mark an input field as invalidvalid from javascript or alternatively can i override the validation method used,"['javascript', 'html', 'css']" +296062,windowonload vs documentready jquery i have a site with two columns i want to have equal height on both using jqueryi am trying to get the logo column height i haddocumentreadyfunction alertlogoheightaand it did not work so i changed it towindowonload function alertlogoheightand it is working what is going on in here,['jquery'] +296075,safe c programming i have noticed that my c compiler gcc will let me do stuff likeinclude stdiohmain short m32768 short y 1 short z 1 printfun y my 12 printfdndn y mzwhen i run it it spits out42949672951212which seems a little baffling to mefirst of all is it safe for me to run programs like this is there any chance i might accidentally write over the operating system i am running os x in case it is relevantalso i had expected at least some kind of segfault error like i have encountered in the past but quietly ignoring an error like this really scares me how come this program does not segfault on meand finally out of curiosity this might be the silliest question is there a method to the madness can i expect all ansi c compilers to work this way how about gcc on different platforms is the layout of memory well defined that it is exploitable perhaps if you were out to write crossplatform obfuscated code,['c'] +296171,why datetimeaddhours does not seem to work i have same result 1338161400 when i do datetime origin new datetime1970 1 1 0 0 0 0 datetime date datetimeparse280512 0130 timespan diff datetouniversaltime origin consolewriteline mathfloordifftotalsecondstostringas well as when i use dateaddhours4 datetime origin new datetime1970 1 1 0 0 0 0 datetime date datetimeparse280512 0130 dateaddhours4 timespan diff datetouniversaltime origin consolewriteline mathfloordifftotalsecondstostringi try to get 1338168600 like updatethanks i changed to datetime origin new datetime1970 1 1 0 0 0 0 datetime date datetimeparse28052012 0130 date dateaddhours4 date datetouniversaltime timespan diff date origin consolewritelinemathfloordifftotalsecondstostring but i got 13381470 still not 1338168600,"['c#', '.net']" +296176,how to copy from one to another i am using the two sided multi select found here and need to add the selected options in the right hand multiselect to another select list with jquery has anyone had to do this before and knows a quick way of doing thisvar selectedoptions myselect0options will get the options but how to write these to the other select,['jquery'] +296179,toggle width with jquery how do i toggle the width of a div with animationhtmldiv idtogglebuttondivdiv idtoggledivacsstoggle height200px width200px backgroundredtogglebutton height20px width20px backgroundbluejquerydocumentready function togglebuttonclick function toggletogglefunction toggleanimatewidth200px function toggleanimatewidth300px aexample that does not workedit my goal is to change the width when i click on the blue div,['jquery'] +296186,dynamically crated iframe triggers onload event twice i created an iframe dynamically and found that this iframe trigger onload event twicevar i0frameonloadfunction consolelogi var ifrdocumentcreateelementiframe ifrsrcjavascriptfunctiondocumentopendocumentwritetestdocumentcloseifronloadframeonload documentbodyappendchildifrwhy i finally is 1how to prevent iframes onload twice instead of pointing onload function to null inside itself,['javascript'] +296197,how can i return json on a partialview in mvc i have this following codehttppostpublic jsonresult index2formcollection fc var goalcardwithplanneddate repositorygetusergoalcardwithplanneddate return jsongoalcardwithplanneddateselectx new goalcardviewmodelxbut i want to use it on a partialview instead how can i do that,['c#'] +296213,how are string and char types stored in memory in net i would need to store a language code string such as en which will always contains 2 charactersis it better to define the type as string or charprivate string languagecodevsprivate char languagecodeor is there another better optionhow are these 2 stored in memory how many bytes or bits for will be allocated to them when values assigned,['c#'] +296221,facebook comment box is not thisplaying in android webview in html file i have used facebook social comment plugin and it is working perfect but when i tried thisplay same file in android using webview then it is thisplaying only comments not the comment box and it is showing a button login to facebook to post a comment when i tried to login by clicking on that button instead of showing comment box the page is being redirected to facebook profileplease helphere is the codehtml code head meta contentwebsite propertyogtype meta content propertyfbadmins meta content propertyogsite name meta content415944175093180 propertyfbapp id meta contentbrowser detect propertyogtitle meta contenttells about early days propertyogdescription meta content propertyogurl meta content propertyogimage head body div idfbrootdiv script windowfbasyncinit function fbinit appid 415944175093180 status true cookie true xfbml trueoauth true function var e documentcreateelementscript etype textjavascript esrc documentlocationprotocol connectfacebookneten usalljs easync true documentgetelementbyidfbrootappendchilde functiond var js id facebookjssdk ref dgetelementsbytagnamescript0 if dgetelementbyidid return js dcreateelementscript jsid id jsasync true jssrc connectfacebookneten usalljs refparentnodeinsertbeforejs ref document script fbcomments href num posts20 width470 bodyandroid codepublic class simpleactivity extends activity webview web1viewpager awesomepager context cxt listwebview dataoverridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate thisrequestwindowfeaturewindowfeature no title setcontentviewrlayoutmain cxt this data new arraylistwebview awesomepager viewpager findviewbyidridviewpager awesomepagersetoffscreenpagelimit10 webview web1 new webviewcxt web1loadurl websettings websettings1 web1getsettings websettings1setjavascriptenabledtrue dataaddweb1 awesomepagersetadapternew awesomepageradapterthisdata,['android'] +296227,why does main method in java always need arguments why does the main method in java always need arguments why should we write string args every time instead of just writing it when we use any argumentsa method like this generates main method not found compiler error since we never use any arguments to the main method this should be allowedpublic static void mainthis is not an interview question it just came to my mind while programming,['java'] +296245,debug mode timeout tomcat i try to start my tomcat debug mode it throws the following thingserver tomcat v70 server at localhost was unable to start within 45 seconds if the server requires more time try increasing the timeout in the server editori even tried to update the timeout but still it gets times out but when i try to start the tomcat not debug mode it gets starts normally do any one knows what might be causing problem,['java'] +296275,c checking if a property startsends with in a csproj i am setting up some configurations in my csproj files that will target different framework versions ideally i want configurations of debug 35 debug 40 release 35 and release 40in my csproj file i want to do something like the followingpropertygroup condition configuration ends with 35 targetframeworkversionv35targetframeworkversionpropertygrouppropertygroup condition configuration ends with 40 targetframeworkversionv40targetframeworkversionpropertygroup check for starts with debug to define optimize etchowever i do not know how to go about checking that configuration startsends with a particular string is there an easy way to do thisedit marked answer below for pointing me in the right direction which lead me to go withpropertygroup conditionconfigurationcontainsdebug setup pdb optimize etcpropertygrouppropertygroup conditionconfigurationcontains35 set target framework to 35propertygroup and so on for release and 40 variations,['c#'] +296315,overloading across inheritance boundaries in c after reading this article that article i got confusedit says if there are two methods at different levels of the hierarchy the deeper one will be chosen first even if it is not a better function member for the callalso it turns out that if you override a base class method in a child class that does not count as declaring itnow let us go back to my question case 1 public class base public virtual void fooint x 1dump public class child base public void fobject x 3dump public override void fooint x 2dump void main child c new child cfoo10 emits 3okaccording to the article deeper one will be chosen first even if it is not a better function and it does not count the overrideso it is right and the program emits 3 fobject x is executedlet us change line order of 1 line case 2 public class base public virtual void fooint x 1dump public void fobject x 3dump line being moved here public class child base public override void fooint x 2dump void main child c new child cfoo10 emits 2 now it emits 2now lets change all int to object and all object to int case 3 public class base public virtual void fobject x 1dump public void fooint x 3dump public class child base public override void fobject x 2dump void main child c new child cfoo1 emits 3questions question1 in case 2 child inherited the fobject x from its father and he also overrides a method but didnt we just say that it turns out that if you override a base class method in a child class that does not count as declaring itin fact we didnt also declared the inherited function so what is the rule here in this situation question2 in case 3 child inherited the fooint x from its father and he also overrides a method but now he chooses its father functionit seems like override is winning only if it has exact matchagain what is the rule here in this situation,"['c#', '.net']" +296349,is there a way in javascript to time a browser reflow i need to be able to benchmark a particular build of a webkitbased browser and am measuring the length of time it takes to do certain stuff like dom manipulation memory limits etci have a test below which records the length of time it takes to simultaneously load in 10 fairly heavy png graphics in code i need to be able to time how long it takes for the load to finish i have tried settingthe onload function on the dynamic image object to produce a time in ms however as shown in the cap below it is giving an inaccurate reading because the reading it gives is a tiny amount due to it only recording the data transfer part of the load and then there is a considerable 30ms delay for when the images are viewable looped in blue this is the browser reflow cycleis there some event in webkit i can use to record when the browser has finished a reflow so that i can benchmark this i have to be able to record the time in milliseconds in code because the build of webkit i am testing has no developer tools i am able to observe the difference in chrome ok but the performance between the two builds differs drastically and i need to be able to quantify it accurately for comparison,['javascript'] +296356,change document flow on page break to fill space when printing or in general thisplaying document on paged media is it possible to reflow document elements so that when some element eg image is shifted to next page because it does not fit in available space on actual page elements following it will be moved to remaining space of actual pagei am trying to achieve effect similar to or same as latex floats but using only cssto illustrate it let us say we have this situationpage 1 paragraph a paragraph b top of image a page break page 2 rest of image a paragraph c paragraph d using some basic css see this question there is no problem achieving thispage 1 paragraph a paragraph b page break page 2 image a whole paragraph c paragraph d but whan i really need is something like thispage 1 paragraph a paragraph b paragraph c paragraph d page break page 2 image a whole so basically i just want to fill up all the remaining space that is left on actual page with elements following image a of course only if they fit into iti am making some css3 research and want to see if office editors can be fully replaced by css styling so i do not need the solution to be yet supported ie implemented in some browser at this time all i want to know is whether it is covered in any css module or construct even if it is just working draft so i can assume browsers will support it in the futurei have already searched for this incss3 paged mediacss3 regions andcss3 generated content for paged mediaspecifications and found nothing but there is still a chance i have simply overlooked something or did not understand it at all so after two days of googling i assume it is time to ask here edit just to make it clear once again i do not need the solution to be supported in any browser now i need to know if there is a standard or specification that allows this and if yes how,['css'] +296369,map with two key for a value i want to create a map that has two key mapput key1key2value1 insert into mapmapgetkey1key2 return value1i have looking into multikeymap but i do not know how i will do it,['java'] +296380,sending columns of a matrix using mpi scatter i am trying to write a matrixvector multiplication program using mpi i am trying to send columns of the matrix to separate processes and locally calculate the result in the end i do a mpi reduce using mpi sum operationsending rows of a matrix is easy as c stores arrays in rowmajor order but columns is not if you do not send them one by one i read the question herempi scatter sending columns of 2d arrayjonathan dursi suggested using new mpi datatypes and heres what i have done by adapting his code to my own needs double matrix1010 double mytype1010 int part size stores how many cols a process needs to work on mpi datatype col coltype mpi type vectorn 1 n mpi double col mpi type commitcol mpi type create resizedcol 0 1sizeofdouble coltype mpi type commitcoltype mpi scattermatrix part size coltype mypart part size coltype 0 mpi comm world calculations mpi reducelocal result global result n mpi double mpi sum 0 mpi comm worldthis works perfectly but i cannot say i really understand how it workshow is mpi type vector stored in the memoryhow does mpi type create resized work and what does it exactly doplease bear in mind that i am a total beginner in mpi thanks in advance,['c'] +296386,backslash in php what does it mean i just saw the use of a backslash in a reference to a php object and was curious about it i have never seen this before what does it meanmail new sendgridmailif youre curious heres sendgrids documentation,['php'] +296428,passing stdstring by value or reference possible duplicateare the days of passing const stdstring as a parameter over should i pass stdstring by value or by reference to a uninlined function if move semantics is supported and what about implementations using small string optimization sso,['c++'] +296437,spring singleton being called twice getting some problem into my spring applicationi have very fairly simple spring beans they are injected into various other spring beans while debugging i found they are being called twice constructor postconstruct both called two timesmy application have no front end technology its simply for backend task related spring configurationxml version10 encodingutf8beans xmlns xmlnsxsi xmlnsaop xmlnscontext xmlnslang xmlnsp xsischemalocation contextcomponentscan basepackagecomgreenintegration exposing spring bean via httpinvoker spring remoting bean nameswitch classorgspringframeworkremotinghttpinvokerhttpinvokerserviceexporter property nameservice refswitchcontroller property nameserviceinterface valuecomgreeniswitchcontroller bean load in application properties reference bean idapplicationproperties classorgspringframeworkbeansfactoryconfigpropertyplaceholderconfigurer property namelocation valueclasspathapplicationproperties bean bean idmongo classcommongodbmongo constructorarg valuemongoserver constructorarg valuemongoport bean bean idmorphia classcomgooglecodemorphiamorphia beanbeansspring bean classrepositorypublic class transactiondao extends basicdaotransaction objectid private datastore datastore autowired public transactiondaomongo mongo morphia morphia supermongo morphia itransact morphiamaptransactionclass to use mongo without security thisdatastore morphiacreatedatastoremongo itransact loggerdebug connected to mongodb successfully thisdatastoreensureindexes thisdatastoreensurecaps constructor transactiondao is being called twice i tried to watch call stack trace bythrowable t new throwablesystemoutprintlntgetstacktrace1tostringand each time it showed the following sunreflectnativeconstructoraccessorimplnewinstance0native method,['java'] +296444,whats wrong with defining operator but not defining equals or gethashcode for the code belowpublic struct person public int id public static bool operator person a person b return aequalsb public static bool operator person a person b return aequalsb why does the compiler give me these warningswhats wrong with not defining the methods belowwarning cs0660 person defines operator or operator but does not override objectequalsobject owarning cs0661 person defines operator or operator but does not override objectgethashcode,['c#'] +296464,whileelseloop of course this is an impossible statement in java todate however ideally i would like to implement it as it is at the heart of many iterations for example the first multiple times it is called i am doing it 650 times when it is creating the arraylistunfortunately the reality is that my actual code does not have the set inside the else loop thus it will pass over both the add and then the set commands and wasting timeafter that i have it also in another loop where it is only performing the set as the data is already created and this is multinested with in many others so it is a lengthy processarraylistinteger datacollinker new javautilarraylistintegerpublic void setlinkerat int value int rowindex whilerowindex datacollinkersize datacollinkeraddvalue else datacollinkersetrowindex value any ideas or theoriesi am unsure about speeds in java when it comes to if statements and arraylist commands and so on,['java'] +296525,python star unpacking for version 27 as mentioned here you can use the star for unpacking an unknown number of variables like in functions but only in python 3 a b 1 2 3 b2 3 a b 1 bin python 27 the best i can come up with is not terrible but annoyingc 1 2 3a b c0 c1 if lenc 1 else is there a way to import this from future like division or will i need my own function to do unknownlength unpacking in python 27,['python'] +296587,how to factor a matrix to a product of kernel matrices problem statementsay we have a set of kernel square matrices k1 k2 kn given a matrix a find the product involving the least amount of matrix multiplications which gives a ki kj kzexamplesay we have these two matrices in the set of kernel matricesk1 1 2 k2 5 6 3 4 7 8then we have a solution for ak1k219 22 and also for bk1k1k2105 122 43 50 229 266is there any existing c or c library which i can use to find the solution if not is there any known algorithmheuristicsps this is not a homework question or a theoretical question or some other trolly thing this is a real problem i need to solve for a side project i am working on at my day job,['c++'] +296590,why is the default capacity of arraylist 10 i saw the java doc for arraylist and found that the initial capacity of arraylist is 10 constructs an empty list with an initial capacity of ten public arraylist this10i think it would make sense if it were any power of 2 but why 10i also checked hashmaps initial capacity and it is 16 which makes sense the default initial capacity must be a power of two static final int default initial capacity 16 constructs an empty tthashmaptt with the default initial capacity 16 and the default load factor 075 public hashmap thisloadfactor default load factor threshold intdefault initial capacity default load factor table new entrydefault initial capacity initis there any specify reason behind the number 10,['java'] +296598,how much is it worth of hashing of passwords in java for security i am developing a web application in java and i want to make the authentication process secureby using hashed passwords in hashingstep1 we take the password given by the user and add a salt to itstep2 hash it using messagedigest and store the hashed value in database while authenticating a user during login process we repeat both the same steps above but instead ofstoring the hashed value we compare it with the value present in database now forgive my ignorance but what i want to say is if a hacker gets access to the database by any othermeans then it can provide security as the hacker cannot get the real text of password from the hashedvalue so easily but how can it provide security against other forms of attacks like bruteforce attack rainbow attack dictionary attack etc as we use the same steps to authenticate the user for login i do not think hashing of passwords nowadays value that muchgive me some suggestions if i am wrong,['java'] +296607,add frame or border to imageview and dropshadow what i am trying to do will work better with an example image as you can see below i have a grey background ontop of that sits a container with some padding containing an image the container also has a slight dropshadow to itwhat i want to know is if there is so nonpainstaking way of doing this in my layoutxml in a normal html document this wouldve been easy but since this is for a mobile app and for a number of screen resolutions and so on it is proving a bit difficultany adviceedit i eventually settled using a 9patch image everyting went really smooth in the creation of it but when i actually use it in my app i see these dark stripes on the right and bottom of the image the dropshadow seems to work it is a very light dropshadow but those darn stripes,['android'] +296624,splitting a java string by the pipe symbol using split the java official documentation statesthe string booandfoo for example yields the following results with these expressions regex result boo and foo and that is the way i need it to work however if i run thispublic static void mainstring args string test abcd string result testsplit forstring s result systemoutprintlns it printsabcdwhich is far from what i would expectabcdwhy is this happeningthanks in advance,['java'] +296631,should i choose or eq for comparing string in el and eq give the same result using el to do my string comparison tests cif testpersonsokande i endast usaendast usacif cif testpersonsokande i allaalla landercif cif testpersonsokande i alla utom usaalla utom usacifshould i use eq instead is for integers only but it works also for strings afaik test whether hashcodes are equal and eq means meaningfully different another question says and eq do the same thingis there no difference here is not the difference the one i am stating looks at the hashcode and eq looks at the implementation of equals,['java'] +296640,how to add phone no email website etc to existing contact i am developing an application where i have to add phone no email website address etc to my existing contact on a click of a buttonthe function on the click of the button goes hereprivate void updatecontactstring name logdtag in updatecontactlogdtagcontact name to be updated namecontentresolver cr getcontentresolver string where contactscontractdatathisplay name and contactscontractdatamimetype and stringvalueofcontactscontractcommondatakindsphonetype string params new string name contactscontractcommondatakindsphonecontent item type stringvalueofcontactscontractcommondatakindsphonetype homecursor phonecur managedquerycontactscontractdatacontent uri null where params nullarraylistcontentprovideroperation ops new arraylistcontentprovideroperationif phonecur null add new contact else phone no opsaddcontentprovideroperationnewupdatecontactscontractdatacontent uri withselectionwhere params withvaluecontactscontractcommondatakindsphonedata tel build email opsaddcontentprovideroperationnewupdatecontactscontractdatacontent uri withselectionwhere params withvaluecontactscontractcommondatakindsemaildata email build website opsaddcontentprovideroperationnewupdatecontactscontractdatacontent uri withselectionwhere params withvaluecontactscontractcommondatakindswebsitedata url build organization opsaddcontentprovideroperationnewupdatecontactscontractdatacontent uri withselectionwhere params withvaluecontactscontractcommondatakindsorganizationdata org buildphonecurclosetry crapplybatchcontactscontractauthority ops catch remoteexception e todo autogenerated catch block eprintstacktrace catch operationapplicationexception e todo autogenerated catch block eprintstacktracei am unable to update my contact,['android'] +296641,why cannot an interface implementation return a more specific type if an interface specifies a property or method to return another interface why is it not allowed for implementations of the first interface to change the return type into a more specific typelet us take an example to illustrateinterface ifoo ibar getbarinterface ibar class foo ifoo this is illegal we are not implementing ifoo properly public bar getbar return new bar class bar ibar i know how to make it work that is not my concerni can just eitherchange return type of getfoo to ibar orexplicitly implement the interface and just call getbar from the ifoogetbar methodwhat i am really asking is the reasoning for not just allowing the code above to compile is there any case where the above does not fulfill the contract specified by ifoo,['c#'] +296661,convert char to nsstring i want to show the char in the uitextfield situationchar datachar namedata6txtnametextnsstring alloc initwithcstringname encodingnsutf8stringencodingbut i am not getting the correct value,"['iphone', 'objective-c', 'ios']" +296715,convert c date time to string and back i am converting c date time to string later when i convert it back to datetime object it appears that they are not equalconst string fmt ymmdd hhmmssfdatetime now1 datetimenowstring strdate now1tostringfmtdatetime now2 datetimeparseexactstrdate fmt cultureinfoinvariantcultureconsolewritelinenow1tobinaryconsolewritelinenow2tobinaryhere is the example looks like everything is included in string format when i print date both thisplays the same but when i compare objects or print date in binary format i see the difference it looks strange to me could you please explain what is going on herehere is the output for the code above8588633131198276118634739049656490,['c#'] +296767,controllermacros cannot be seen in rspec i have a rails app and i am trying to test it i use devise to log in however i faced a problem that occurs when i want to testusersenderprojectsratingwspeccontrollerswidgets controller specrb4in block in top required undefined local variable or method login user for class0x007fe909bd5070 nameerrorfirst i want to say that i read this devise formal tutorialmy spec helperrb is this file is copied to spec when you run rails generate rspecinstall envrails env test require fileexpand pathconfigenvironment file require rspecrails require rspecautorun require capybararspec requires supporting ruby files with custom matchers and macros etc in specsupport and its subdirectoriesdirrailsrootjoinspecsupportrbeach f require frspecconfigure do config mock framework if you prefer to use mocha flexmock or rr uncomment the appropriate line configmock with mocha configmock with flexmock configmock with rr omniauthconfigtest mode true omniauthconfigmock authtwitter provider twitter uid 123545 etc omniauthconfigmock authtwitter invalid credentials configinclude devisetesthelpers type controller configextend controllermacros type controller configinclude requestmacros type request remove this line if youre not using activerecord or activerecord fixtures configfixture path railsrootspecfixtures if youre not using activerecord or youd prefer not to run each of your examples within a transaction remove the following line or assign false instead of true configuse transactional fixtures true if true the base class of anonymous controllers will be inferred automatically this will be the default behavior in future versions of rspecrails configinfer base class for anonymous controllers falseendmodule rspeccore class examplegroup include capybaradsl include capybararspecmatchers endendand also i have a controller macrosrb which is located in support filemodule controllermacros def login user beforeeach do requestenvdevisemapping devisemappingsuser user factoryuser userconfirm or set a confirmed at inside the factory only necessary if you are using the confirmable module sign in user end endendand finally my controller spec file isrequire spec helperdescribe widgetscontroller do login user describe user do beforeeach do current user mock modeluser id 1 widget mock modelwidget user id 1 widgetstubcurrent userand returncurrent user widgetstubwidgetsand returnwidget end it should have a current user do subjectcurrent usershould not be nil redirect to widgets path end it should not have a current user do redirect to widgets path new user session path end end def mock widgetstubs mock widget mock modelwidget stubsas null object end describe get index do it should get all widgets do widgetstuball mock widget get index assignswidgets widgets end end describe post widget do it creates a new widget do widgetstubnewwiththese params mock widgetsave true post create widget these params assignswidget widgets responseshould redirect to edit widget pathmock widget end it can not create a new widget do widgetstubnewwiththese params mock widgetsave false post create widget these params assignswidget widgets redirect to new widget path end end describe get widget do it shows exact widget via its uuid do widgetstubfindwith10 mock widgetsave true get show assignswidget widget end end describe put widget do it updates the widget attributes do widgetstubfind by uuidwith6and returnmock widgetupdate attributes true mock widgetshould receiveupdate attributeswiththese params put update uuid 6 widget these params responseshould redirect to edit widget pathmock widget end it can not update the widget attributes do widgetstubfind by uuidwith6and returnmock widgetupdate attributes false mock widgetshould receiveupdate attributeswiththese params put update uuid 6 widget these params end end describe delete destroy do it destroys the requested widget do widgetstubfind by uuidwith10and returnmock widget mock widgetshould receivedestroy get destroy uuid 10 end endendhow can i fix this what is the problem,['ruby-on-rails'] +296768,resourcemap not found error when referencing a resource file within a portable class library the problem i am facing has as followsi have developed a portable class library to encapsulate a service connection inside this class library there is a resourcesresw file containing strings these strings are called only by methods of the class library for example to override tostring methodsas i said this is a portable class library if i reference it as a dll or even as a project inside another solution it gets built and compiles correctly then i make a call using a method of this library within my application say clientfacadeconnector connector new clientfacadeconnector icollectionsearchresult results null string message stringempty if maxresults 1 search with max results try if contextquerytrimequalsstringempty results await connectorgetconnectedsearchasynccontextquery query maxresults message search with contextquery contextquery query query max results maxresultstostring else results await connectorgetconnectedsearchasyncquery maxresults true message using normal query search query query max results maxresultstostring catch iqserexception ex message exmessage if results null icollectionlocalsearchresult contentresults new listlocalsearchresult foreach searchresult s in results var q stostring var contentitem await connectorgetconnectedgetcontentasyncscontentid localsearchresult lcontent new localsearchresultcontentitem lcontentscore sscore lcontentrelevance srelevance lcontentmarkfulltextquery contentresultsaddlcontent at the point where i call stostring method i get an error resource map not foundto explain where this comes frompublic static class appresources private static resourceloader resourceloader static appresources load local file resourcesresw by default resourceloader new resourceloader public static string getresourcesstring key if stringisnulloremptykey throw new argumentnullexceptionkey return resourceloadergetstringkey and inside the overridden tostring method there is code that looks as follows public override string tostring stringbuilder buf new stringbuilderappresourcesgetresourcesinstrsearchresultcontent if contentid 1 bufappendappresourcesgetresourcesstringcontent id contentidtostring else bufappendappresourcesgetresourcesstringno appresourcesgetresourcesstringcontent id the resource file is called resourcesresw and is the default resw file that resourceloader calls if no other is calledstrangely enough if i copy the resource file inside the client application locally it is referenced correctly by all calls to the class library resource file and everything worksthis class library is supposed to be an sdk when finished do i need to thistribute the resource file separately such a problem i have never experienced with normal class libraries and resx files resw is giving me the creeps,['c#'] +296787,http error 50019 internal server error i am moving a pretty basic site from win 2003 to win 2008 r2 the site is getting the error listed below how can i diagnose this i moved a number of other sites between these 2 servers this is the only on that is receiving this error i have seen the other posts on this issue but none of them list a solution that works for mehttp error 50019 internal server errorerror code 0x80070dconfig source 1 0 updatehere are some notes on what i checked1 permissions via process monitor the config file is being opened correctly2 net version tried multiple settings3 integrated vs classic pipeline4 change enabled 32 bit to true5 i have not tried aspnet regiisexe yet because the other sites on the new box work finenext i am going to try comment out various items in the config file,['asp.net'] +296820,multiple installinstallfile in a single pomxml please read at least this before answering this is a temporary measure no we do not want to set up a local repository manager and manually run a scriptwe have a legacy project with a few dependencies which we have a local copy of including source and javadoc and which has been proven to work well in production but which is not available in the same quality in central we want to use those jars we already havei have found that i can manually run a suitably complex mvn installinstallfile command to get the artifacts injected in the repository of the local machine but i would like to have it work as part of the normal maven build of our various modulesgiven i have an otherwise blank module containing multiple jars which each need to be inserted with an installinstallfile how should i do this in my pomxml to be fully conformant with the normal maven buildor can i just attach multiple jars to be the output of the module and somehow attach javadoc and source tooand please no suggestion about submitting to central or setting up a local repository manager this is a temporary solution until we have an opportunity to upgrade to a newer version of the dependencies,['java'] +296829,when to attachdetach android fragments by hand i have read the fragments documentation in depth and i have not seen any references to the fragmenttransactionattach or fragmenttransactiondetach methods however i have found multiple tutorials and demos where they actually use them like fragmenttabs demo my question isin theory when are you supposed to attachdettach fragments by handwhat happens exactly when a fragment is attacheddetached is it createddestroyed pausedresumed etcis it a good practice to attachdetach your fragments by handthank you,['android'] +296831,require js backbone js global models i want to create a usersession model which loads and saves the session id into a cookie using the jquery cookie pluginthis is my code for my usersession model moduledefinejquery underscore backbonefunction backbone var usersession backbonemodelextend defaults accesstoken null userid null initialize function thisload authenticated function return booleanthisgetaccesstoken save functionauthhash cookieuserid authhashid cookieaccesstoken authhashaccesstoken load function thisuserid cookieuserid thisaccesstoken cookieaccesstoken return usersessionbut lets say i want to access it into my login viewdefinejquery underscore backbone texttemplatesloginhtml modelsuserlogin modelsusersessionfunction backbone logintemplate userlogin usersession var loginview backboneviewextend model new userlogin el screen events submit frmlogin login login functione epreventdefault lets not actually submit thismodelset username loginusernameval password loginpasswordval thismodelsavenull success functionnextmodel response do something here with usersession model error function render function thiselhtml templatelogintemplate return this return new loginviewthe thing is each time i access the usersession model in modules see the modelsave success call back function it uses default values so i need to have some kind of singleton instance of the usersession model how can i do this my first idea was to use the app namespace so in our mainjs first main module that gets loaded and there initialize the usersession module and each time another module access that module the require the main module which has a object that returns the usersession instancehow can this be done bestthanks,"['javascript', 'jquery']" +296832,skip the headers in preferenceactivity when there is only one header i added preferenceheaders to my app so that the preference screen would not look broken on honeycomb and tablet sized ics however i only have one header at the moment so you have to click through a header screen with only one entry on phone sized devices is there an easy way to tell android to skip the header screen when there is only one header but to still show it on large screensit seems that the stock contacts app does this successfully but i have browsed through its source and cannot figure out how it is doing it,['android'] +296887,is there a llvm java front end that converts java source to llvms intermediate form from what i have read there is a llvm program that converts java bytecode to llvms intermediate form called class2llvm my question is how do i access this what front end do i have to install in order to access this vmkit is their implementation of a jvm but i am looking for how to compile the java source code with llvm not how to run it,['java'] +296888,php checking user agent and ip to prevent session hijacking i am trying to figure out how to prevent session hijacking heres what i was thinking of doingalong with the user id session add a user agent and user ip session too every time a page is loaded these sessions will be checked to see if they match will this be enough for examplephpuserip sessionuseripuseragent sessionuseragentif userip serverremote addr useragent serverhttp user agent session destroythanks,['php'] +296945,is there a guid alternative for thistributed key generation my situation is i have a number of client applications which is using local db ms sql ms access sorry this is enterprise system i have to support legacyi do not know anything of trend among clients now it is 10 but it maybe 100 in a yeardata from those tables comes to my central server and is put into one common tablesometimes existing client data is changed i have to perform updatedelete operationsi do not want use guids net type systemguid it is hard to simply implement and support on ms access besides it is not good for performancei need a fast search on that common table so it would be nice to use int or long int as a pkso i wantsomething unique to avoid collisions it will be used as a pk it should hopefully be int or long int must be assignable clientside before being insertedmy current solution is to take the crc from a concatenation of processodidbios dateuser name strings hardwareuser related datadatetimenow unccurrently it works for me but maybe there is a better approach to achieve my goalsany comments suggestions examples or experience of your own update synchronization between client and server is periodic action so it can occurs 23 times per day it is config variable,"['c#', '.net']" +296951,thisplay image in java jframe whats the best way to thisplay an image at specific coordinates in a java jframei know there are a number of ways to do this i just need to know the best way to thisplay an image that i am planning on moving around the frame,['java'] +296970,generating symmetric matrices in numpy i am trying to generate symmetric matrices in numpy specifically these matrices are to have random places entries and in each entry the contents can be random along the main diagonal we are not concerned with what enties are in there so i have randomized those as wellthe approach i have taken is to first generate a nxn all zero matrix and simply loop over the indices of the matrices however given considering looping is relatively expensive in python i am wondering if i can acheive the same thing without using pythons for loops is there some things built into numpy that allow me to acheive my goal more efficientlyhere is my current codeimport numpy as npimport randomdef emptyx y return x0b npfromfunctionempty n n dtype intfor i in range0 n for j in range0 n if i j bij randomrandrange20 20 else switch randomrandom randomseed if switch randomrandom a randomrandrange20 20 bij a bji a else bij 0 bji 0,['python'] +296981,jquery uncaught typeerror property of object object window is not a function alli downloaded a prebundled jscss form application and i am trying to use it in wordpress i have got the following codedocumentreadyfunction parse the data from an dataattribute of dom elementsparsedata function data returnarray if testdata array data datasubstr1 datalength 2split if returnarray isarraydata data null data arraydata return data image preloader arguments are image paths relative to the current pagepreload function var cache args len argumentslength for var i args len i var cacheimage documentcreateelementimg cacheimagesrc argumentsi cachepushcacheimage fadeinslide by revaxartscom fades out a box and slide it up before it will get removedfnfadeinslide function speed callback if isfunctionspeed callback speed if speed speed 200 if callback callback function thiseachfunction var this this thisfadetospeed 2 1slidedownspeed 2 function callback return this fadeoutslide by revaxartscom fades out a box and slide it up before it will get removedfnfadeoutslide function speed callback if isfunctionspeed callback speed if speed speed 200 if callback callback function thiseachfunction var this this thisfadetospeed 2 0slideupspeed 2 function thisremove callback return this textfadeout by revaxartscom fades out a box and slide it up before it will get removedfntextfadeout function text delay callback if text return false if isfunctiondelay callback delay if delay delay 20 if callback callback function thiseachfunction var this this thisstoptexttextshowdelaydelayfadeout10function thistextshow callback return this leadingzero by revaxartscom adds a leding zero if necessaryleadingzero function value value parseintvalue 10 ifisnanvalue value 10 value 0 value value return valuei was assuming that the wordpress no conflict was causing an issue so i updated the very last bracket to look like the following jqueryhowever i am still getting the same error does anyone know what would be casuing this issue and how to get it resolvedthanks in advance,['jquery'] +296982,what exactly is a canvas path and what is the use of ctxclosepath i am working on an html5 game i need to draw tail lines in the canvas and check for intersections in the game which is a tronstyle gamei am actually using the drawline function from jcanvas but jcanvas did not provide me a way to check for line intersection i digged in the source and found the use the ctx object and at the end of the function i am using i returned the object so i can use the ctxispointinpath method to achieve what i need but is not working is returning false everytimei really do not understand what a path is will ctxispointinpath return true just for the points that are set using ctxmoveto after ctxbeginpath or will it return true for all the points that are between 2 consecutive ctxmovetos that are connected using ctxlinetowhat is the use of ctxclosepathand what is the difference between ctxclosepath ctxfill ctxstrokeand ctxfill ctxstroke ctxclosepath,['javascript'] +296986,jquery uncaught typeerror cannot read property fn of undefined anonymous function alli am getting an error from some of my code that i downloaded here is the code wl alert v 11 description handles alert boxes dependency jquery ui slider fadeoutslide pluginfnwl alert function method var args argumentsreturn thiseachfunction var this this if fnwl alertmethodsmethod return fnwl alertmethodsmethodapplythis arrayprototypeslicecallargs 1 else if typeof method object method if thisdatawl alert var opts extend thisdatawl alert method else var opts extend fnwl alertdefaults method thisdata else errormethod method does not exist if thisdatawl alert thisdatawl alert bind click events to hide alert box thisbindclickwl alert function event eventpreventdefault do not hide if it is sticky if thisdatawl alertsticky fnwl alertmethodsclosecallthis0 prevent hiding the box if an inline link is clicked findabindclickwl alert function event eventstoppropagation else show it if it is hidden if thisishidden thisslidedownoptsspeed 2 if opts extendthisdatawl alert optsfnwl alertdefaults speed 500sticky falseonbeforeclose function element onclose function element fnwl alertversion 11fnwl alertmethods close function var this this opts thisdatawl alert call callback and stop if it returns false if optsonbeforeclosecallthis this false return false fadeout and call an callback thisfadeoutslideoptsspeed function optsonclosecallthis0 this set function var this this options if typeof arguments0 object options arguments0 else if arguments0 arguments1 undefined optionsarguments0 arguments1 eachoptions function key value if fnwl alertdefaultskey undefined fnwl alertdefaultskey null thisdatawl alertkey value else errorkey key is not defined to create an alert box on the flywl alert function text cssclass insert after options go thru alldivalerteachfunction var this this and hide if one with the same text is allready set if thistext text thisslideupfnwl alertdefaultsspeed create a new dom element and inject itvar al div classalert cssclass text divhideafter alappendtoinsertwl alertoptions alprependtoinsertwl alertoptionsreturn the elementreturn alhas anyone seen this type of error before how would i resolve something like this thanks for any advice you have,['jquery'] +296988,stubbingmocking up webservices for an ios app i am working on an ios app whose primary purpose is communication with a set of remote webservices for integration testing i would like to be able to run my app against some sort of fake webservices that have a predictable result so far i have seen two suggestionscreate a webserver that serves static results to the client for example here implement different webservice communication code that based on a compile time flag would call either webservices or code that would load responses from a local file example and another onei am curious what the community thinks about each of this approaches and whether there are any tools out there to support this workflowupdate let me provide a specific example then i have a login form that takes a username and password i would like to check two conditions getting login denied and logging in successfullyso i need some code to check the username parameter and throw an appropriate response at me hopefully that is all the logic that i need in the fake webservice how do i manage this cleanly,['ios'] +297006,how to store bidirectional relationships in a rdbms like mysql suppose i want to store relationships among the users of my application similar to facebook per sethat means if a is a friendor some relation of b then b is also a friend of a to store this relationships i am currently planning to store them in a table for relations as follows uid friendid user1 user2 user1 user3 user2 user1however i am facing two options herethe typical case where i will store both user1 user2 and user2user1 this will take more space but at least in my head require just one pass over the rows to thisplay the friends of a particular userthe other option would be to store either user1user2 or user2user1 and whenever i want to find all the friends of user1 i will query on both columns of table to find a users friends it will take half the space but again at least in my head twice the amount of timefirst of all is my reasoning appropriate if yes then are there any bottlenecks that i am forgetting in terms of scaling throughput or anythingbasically are there any tradeoffs between the two other than the ones listed here also in industry is one preferred over the other,['mysql'] +297029,jquery mobile list item split button without link on main item let us say i have a jquery mobile site with a bunch of li with a split icon dataicongridis it possible to have the lefthand side of the list item not wrapped in a href but keep the button on the righthand sideexample i have triedselectioncontentsunwrapand this works it removes the link as requested and fixes the problem i have outlined below but it goes and breaks a whole bunch of the layout and styling on the list itemthe issue i am trying to resolve is thisi have about 100 li items on a pageeach li might have a select element in it with 510 optionswhen using the default jquery mobile styling of a select everything works finehowever this has a major performance hit an iphone 4s struggles to scroll and an ipad 2 is virtually unusuable android is actually better for once but still not perfectputting datarolenone on the select elements makes the page fast and workable againhowever it breaks on a desktop browser firefox in particular because when you click to choose an item in the select the link from behind the select is triggered and the select box is cancelledany ideas,['jquery'] +297032,java slick scale image without antialiasing in the slick library based off of lwjgl you can scale images after you load them with getscaledcopy but it will apply antialiasing i want the edges to stay rough i am making pixel art how can i do this,['java'] +297035,requesturluserinfo no value i request a url as httpsuseretcetcin controller i use requesturluserinfo get nothing empty string whyor how can i get userpass at controller,['c#'] +297036,android numberpicker hiding increment and decrement buttons i am using a numberpicker and am targeting api 11 and above 30 and up so i am using the supported numberpicker this is being used in a timer application i want to be able to hide the increment and decrement buttons at will so that the buttons will not take up space in the layout when hidden i have attempted to do thisview increment secsgetchildat0incrementsetvisibilityviewgoneview decrement secsgetchildat2decrementsetvisibilityviewgonewhere secs is my numberpicker for seconds in the timer if i try to hide the place where it thisplays the number an edittext widget it hides just fine but the above code does nothingso my question is how do i accomplish hiding the increment and decrement buttons i would really like to avoid making my own custom number picker like i have read about in some other posts but if that is truly the only way i am willing to try itthankshere is additional code as requestedcode in onclick method for when stopwatch is startedif stoppushstarttime systemcurrenttimemillis elapsedtimeelsestarttime systemcurrenttimemillismhandlerremovecallbacksstarttimermhandlerpostdelayedstarttimer 0code that handles stopwatch abilitiesprivate runnable starttimer new runnablepublic void run elapsedtime systemcurrenttimemillis starttime updatetimerelapsedtime mhandlerpostdelayedthis refresh ratecode for calculating and updating stopwatch timethismillis int elapsedtime 100thisseconds int elapsedtime 10thisminutes seconds 60thishours minutes 60millis millis 10seconds seconds 60minutes minutes 60hours hours 24runonuithreadnew runnablepublic void run hrssetvaluehoursrunonuithreadnew runnablepublic void run minssetvalueminutesrunonuithreadnew runnablepublic void run secssetvaluesecondsrunonuithreadnew runnablepublic void run millssetvalueint millis,"['java', 'android']" +297038,kindle fire hitches and texture corruption at 60 fps this appears to be a firespecific gpu issue and i would appreciate any help or suggestionsfor the most part my towerdefense game is able to run 60 fps even with dozens of enemies and towers all shooting every which way however at seemingly random times even with nothing happening like sitting on the main menu very evenly spaced 400ms hitches pause the game at an interval of around 23 seconds then suddenly the hitches will thisappear and 16x16 pixel blocks of textures will randomly not renderthese 2 glitches appear to be mutually exclusive and like i said can be triggered simply by starting the game and navigating from the main menu to the levelselect screen where minimal resources are loaded and little game logic is happening i use opensl for sound effects and i noted that thisabling sfx changed the hitch duration to 280msthen i manually forced the framerate from 60 fps to 30 fps by inserting a sleep in the frame tick loop and both glitches thisappeared completelyhere is a screen cap that demonstrates the texture not rendering this bug happens in all 32bit render surfaces regardless of depthstencil values and whether colorclear is on or offthank youedit actually apparently the texture flicker happens at any framerate however somewhere under between 40 and 45 fps the 400ms hitch goes away,['android'] +297039,what is point of ssl if fiddler 2 can decrypt all calls over https i asked a question here a while back on how to hide my http request calls and make them more secure in my application i did not want people to use fiddler 2 to see the call and set up a auto responder everyone told me to go ssl and calls will be hidden and information kept safei bought and installed a ssl certificate and got everything set up i booted up fiddler 2 and ran a test application that connect to a https web service as well as connected to a https php scriptfiddler 2 was able to not only detect both requests but decrypt them as well i was able to see all information going back and fourth which brings my questionwhat is the point of having ssl if it made 0 security differences with or without ssl i can see all information going back and fourth and still set up a auto responderis there something in net i am missing to better hide my calls going over sslediti am adding a new part to this question as of some of the response i have gotten what if a app connected to a web service to login the app sends the web service a username and a password the web service then sends data back to the app saying good login data or bad even if going over ssl the person using fiddler 2 could just set up a auto responder and the application is then cracked i understand how it could be useful to use need to see the data in debugging but my question is what exactly should one do make sure the ssl is connecting to is the one it was requesting basically saying there can not be a middle man,['c#'] +297054,drawrect circle and animate sizecolor i am drawing a circle in the drawrect method of my uiview using the standard cgcontextfillellipseinrect code however i would like to slightly pulse make larger and smaller and change the intensity of the color fill with an animation for example if the circle is filled with red i would like to pulse the circle and make the red slightly lighter and darker intime with the pulsing action not having much experience with core animation i am a bit lost about how to do this so any help would be greatly appreciated,['ios'] +297069,listen eaddrnotavail error in nodejs i installed nginx and nodejs in my serverwhen i try run my nodejs file i get an errornodejs201 throw e processnexttick error or error event on first tick error listen eaddrnotavail at errnoexception netjs61411 at array0 netjs68928 at eventemitter tickcallback nodejs19240how can i fix this problemthanks,['javascript'] +297081,javascript is there an equivalent to caniusecom for html5 apisecmascript5ecmascript6 in the various browsers is there an equivalent to caniusecom for html5 apis ecmascript5 ecmascript6 in the various browserscaniusecom does have some javascript coverage but pages like do not really tell you anything other than yesnopartially realistically i am looking for something like quirksmode crossed with caniuse where i could look in detail at any api or method and see where it is currently implemented and bug free a site where for example i could look and see which versions of which browsers will currently work with thisobjectkeysconstantstextforeachfunctionkey languagespushkey constantstextkeylanguagename,['javascript'] +297086,hide particular div onload and then show div after click i have two divs div1 and div2 i want div2 to be automatically hidden but when i click on preview div then div2 to be made visible and div1 to hide this is the code i tried but no luck script typetextjavascript srcscriptscript typetextjavascriptdocumentreadyfunction div2hide previewclickfunction div1hide div2show scriptdiv iddiv1this is preview div1 this is preview div1divdiv iddiv2this is preview div2 to show after div 1 hidesdivdiv idpreview stylecolor9 fontsize14pxpreviewdiv,"['html', 'jquery']" +297098,mvc3 add a folder to controllers i want to learn is it possible to add additional folder to controller folder my reason is pretty simple i want to divide my project administration and client sidesexample i have a controller named post that has actions index details delete create edit i want to make one controller as user controller that will consist of index details and another controller as admin controller that will consist of delte create edit then i will be able to easy thistinguish what is what and put admin validation on whole admin classanother reason is that i want my url for administrating my site to look like adminpostdelete not postdeleteso is it possible and if so then what would be the best way to implement this,['asp.net'] +297158,combine two statements with limits using union is there a way to combine these two statements into one without having duplicate entriesselect from seq where julianday20120525 190200juliandaytimep order by timep limit 50select from seq where julianday20120529 062050juliandaytimei order by timei limit 50my first obvious attempt is not supported by sqlite syntax error limit clause should come after union not beforeselect from seq where julianday20120525 190200juliandaytimep order by timep limit 50unionselect from seq where julianday20120529 062050juliandaytimei order by timei limit 50,['sql'] +297191,read a file backwards is there a way to read a file backwards line by line without having to go through the file from the beginning to start reading backwards,['c++'] +297253,fancybox oncomplete function not running for some reason it is just not running the oncomplete function it does however load the fancybox div my htmlul li classorange 1 a hreftextclick herea div idtext classtexttext text textdiv liulmy jquery jqueryli afancybox autodimensions false width 631 height 256 oncompletefunction alertrunning jqueryfancyboxskincssbackgroundcolorcolour the alert does not run i have also tried changing the event function to onclosed and the other events and nothing,['jquery'] +297255,restore back file to remote database i have a testback file in my local machine i need to restore this file to remote machines database how do i do thatwhen i try this the remote database throws an error that it is not able to find testback on the local filesystemqueryrestore database testproject from thisk cprogram filesmicrosoft sql servermssql10 50icon3mssqlbackuptestbackerrorcannot open backup device cprogram filesmicrosoft sql servermssql10 50icon3mssqlbackuptestback operating system error 2the system cannot find the file specifiedhow can i achieve this i am using microsoft sql server 2008,['sql'] +297257,undefined reference to array of constants acppconst unsigned char whatever123 ahextern const unsigned char whatever123bcppinclude ahunsigned char x whatever0 error undefined reference to whateverwhy do i get an undefined reference error without the const the error goes awayhow do i share an array of constants among multiple translation units,['c++'] +297263,c namespaces how to use in header and source files correctly consider a pair of two source files an interface declaration file h or hpp and its implementation file cpplet the h file be like the followingnamespace mynamespace class myclass public int foo i have seen two different practices for using namespaces in source filescpp showing practice 1include myclasshusing namespace mynamespaceint myclassfoo cpp showing practice 2include myclasshnamespace mynamespace int myclassfoo my question are there any differences between these two practices and is one considered better than the other,['c++'] +297265,worksheetname causes outofmemoryexception net4 c vsto4 excel addinthe following function is called very often let us say every second summary gets a unique identifier string of for the worksheet in the format workbooknameworksheetname summary param nameworkbookthe workbookparam param nameworksheetthe worksheetparam returns a unique worksheet identifier string or an empty string returns public static string getworksheetuniqueidentifierworkbook workbook dynamic worksheet if workbook null return stringempty if worksheet null return stringemptynote worksheet can also be a diagram return stringformat01 workbookname worksheetname after a while i am getting the following exception systemoutofmemoryexception at systemcollectionsgenericdictionary2resize at systemcollectionsgenericdictionary2inserttkey key tvalue value boolean add at microsoftcsharpruntimebindersemanticssymtblinsertchildnogrowsymbol child at microsoftcsharpruntimebindersemanticssymfactorybasenewbasicsymsymkind kind name name parentsymbol parent at microsoftcsharpruntimebindersemanticssymfactorycreatelocalvarname name parentsymbol parent ctype type at microsoftcsharpruntimebinderruntimebinderpopulatelocalscopedynamicmetaobjectbinder payload scope pscope argumentobject arguments ienumerable1 parameterexpressions dictionary2 dictionary at microsoftcsharpruntimebinderruntimebinderbindcoredynamicmetaobjectbinder payload ienumerable1 parameters dynamicmetaobject args dynamicmetaobject deferredbinding at microsoftcsharpruntimebinderruntimebinderbinddynamicmetaobjectbinder payload ienumerable1 parameters dynamicmetaobject args dynamicmetaobject deferredbinding at microsoftcsharpruntimebinderbinderhelperbinddynamicmetaobjectbinder action runtimebinder binder ienumerable1 args ienumerable1 arginfos dynamicmetaobject onbindingerror at microsoftcsharpruntimebindercsharpinvokememberbinderfallbackinvokememberdynamicmetaobject target dynamicmetaobject args dynamicmetaobject errorsuggestion at systemdynamicdynamicmetaobjectbindinvokememberinvokememberbinder binder dynamicmetaobject args at systemdynamicinvokememberbinderbinddynamicmetaobject target dynamicmetaobject args at systemdynamicdynamicmetaobjectbinderbindobject args readonlycollection1 parameters labeltarget returnlabel at systemruntimecompilerservicescallsitebinderbindcoretcallsite1 site object args at systemdynamicupdatedelegatesupdateandexecute3t0t1t2tretcallsite site t0 arg0 t1 arg1 t2 arg2 at callsitetargetclosure callsite object object at testaddinexcelaccessorgetworksheetuniqueidentifierworkbook workbook object worksheet at testaddinexcelaccessorgetcurrentworksheetuniqueidentifier at testaddinexcelaccessortimerexcelobserver tickobject sender eventargs ecalling code is private static timer timerexcelobserver new timer timerexcelobservertick new eventhandlerthistimerexcelobserver tick timerexcelobserverinterval 10 timerexcelobserverstart private void timerexcelobserver tickobject sender eventargs e var updatedworksheetidentifierstring getcurrentworksheetuniqueidentifier public static string getcurrentworksheetuniqueidentifier return getworksheetuniqueidentifierexcelapplicationactiveworkbook excelapplicationactivesheet i have no idea why i am getting an exceptioncan it maybe help to take a using in getworksheetuniqueidentifierusingworksheet return stringformat01 workbookname worksheetnamedoes anyone have an answer,['c#'] +297289,php soapclient request not a valid method for this service okay i think i need another pair of eyes to look over this i am making a simple php soapclient call to an echo web service on a remote server i am pretty sure i do not have any typos and that the function call is correct however i am receiving a fatal error claiming the function is not a valid method below is a var dump of the web services typesarray4 0 string88 struct espexception string code string audience string source string message 1 string71 struct arrayofespexception string source espexception exception 2 string43 struct echotestrequest string valuein 3 string45 struct echotestresponse string valueout fatal error uncaught soapfault exception client function echotestrequest is not a valid method for this service in homegrafixstpublic htmlcpaappecho testphp38 stack trace 0 homegrafixstpublic htmlcpaappecho testphp38 soapclient callechotestrequest array 1 homegrafixstpublic htmlcpaappecho testphp38 soapclientauthechotestrequestarray 2 main thrown in homegrafixstpublic htmlcpaappdrewecho testphp on line 38here is the code i am using to make the callphp require oncesoapclientauthphp ini setsoapwsdl cache enabled 0 loading the wsdl document server 165 wsdl server wsdl client new soapclientauthwsdl array login username password password types client gettypes var dumptypes echo br req clientechotestrequestarrayvaluein echo print reqvalueout echo br,['php'] +297302,c how to catch mouse clicks wherever they happen i am stuck with an application i am writing where i need to monitor for mouse clicksthe clicks may happen anywhere on the screen and not inside the app window and for each click i must pass a message perform an action or somethingi looked around and read some suggestions like usinglresult callback wndprochwnd hwnd uint message wparam wparam lparam lparambut i was unsuccessfuldoes anyone have an idea on how to implement what i need,['c++'] +297342,aspnet mvc routing not matching some file extensions i am having trouble with routes not matching when the contain certain file extensions in them i suspect it might be an iis problem but i cannot seem to track it downfirst off i have routeexistingfiles turned offroutesrouteexistingfiles falseand then i have the following routeroutesmaproute categorycategoryaspx new controller category action view and the following url does not match this routehttpmysitecategorytestaspxbut if i remove the file extension and cange the route toroutesmaproute categorycategory new controller category action view then the above url matches with category being set to testaspxi also have the same problem with this routeroutesmaproutesitemap sitemapxml new controller resource action sitemap the strange thing is that i am not having this problem with all routes with file extensions the following routes seem to be working just fine for meroutesmaproute faviconico new controller resource action favicon routesmaproute mincss new controller resource action css routesmaproute minjs new controller resource action javascript routesmaproute rsdxml new controller metaweblog action rsd is there something i should be aware of with the aspx and xml extensions could this be an iis problem is there a better way to debug this than just using routedebugger,['c#'] +297347,numpy genfromtxt column names how can i have genfromtxt to return me its list of column names which were automatically retrieved by namestrue when i do data npgenfromtxttestcsvnamestruedelimiterdtypenoneprint datacol1it prints the entire column values for col1 but i need to traverse all column names how can i do that i tried datakeys and various other methods but whatever is returned by genfromtxt does not seem to be a dictionary compatible object i guess i could pass the list of column names myself but this wont be maintainable for me in the long run any ideas,['python'] +297381,the need for parentheses in macros in c i tried to play with the definition of the macro sqr in the following codedefine sqrx xxint main int a b3 a sqrb5 ideally should be replaced with 3553 though not sure printfdna return 0it prints 23 if i change the macro definition to sqrx xx then the output is as expected 64 i know that a call to a macro in c replaces the call with the definition of the macro but i still canat understand how it calculated 23,['c'] +297398,how to create a keyeventargs object in wpf related to a so answer i have found this answer which look like what i need how can i programmatically generate keypress events in cexcept for the fact i cannot create an instance of keyeventargs i do not know how the code in question is var key keyinsert key to send var target keyboardfocusedelement target element var routedevent keyboardkeydownevent event to send targetraiseevent new keyeventargs keyboardprimarydevice presentationsourcefromvisualtarget here i cannot 0 key routedeventroutedevent the compiler says the best overloaded method match forsystemwindowspresentationsourcefromdependencyobjectsystemwindowsdependencyobject has some invalid argumentsthe ide says argument type iinputelement is not assignable to parameter type dependencyobjectand across stackoverflow i have found several answers directing to that answer but none of them address how to create the instance in first placehow can i do that,['c#'] +297406,evaluating checkbox boolean value i am sure this is a rediculously easy question but i just cannot find the answer to it anywhere i have a jcheckbox that i need to evaluate the boolean value of and then change the value with an if statement the problem is i just cannot find the syntax anywhere for evaluating the contents of a jcheckbox let alone changing it this will probably be really easy one but i just cannot seem to find anything helpful thanks,['java'] +297407,is t an instance of a template in c suppose i am in a template and i want to know if a type parameter t is an instantiation of a particular template eg stdshared ptrtemplatetypename tvoid ft param if instantiation oft stdshared ptr if t is an instantiation of stdshared ptr more likely i would want to do this kind of test as part of a stdenable if testtemplatetypename tstdenable ifinstantiation oft stdshared ptrtypeft param other overloads of f for when t is not an instantiation of stdshared ptris there a way to do this note that the solution needs to work with all possible types and templates including those in the standard library and in other libraries i cannot modify my use of stdshared ptr above is just an example of what i might want to doif this is possible how would i write the test myself ie implement instantiation of,['c++'] +297472,python simple naked objects whats the easiest way to create a naked object that i can assign attributes tothe specific use case is i am doing various operations on a django object instance but sometimes the instance is none there is on instance in this case i would like to create the simplest possible fake object such that i can assign values to its attributes eg myobjectfoo barbasically i am looking for the python equivalent of this piece of javascriptmyobject myobjectfoo bari know i can use a mock objectlibrary for this but i am hoping for a very simple solution as simple as the javascript above is there a way to create a naked object instance something likemyobject objectmyobjectfoo bar,['python'] +297500,how to create a preference that accepts only integer values is there a way to create a preference in a preferencefragment that accepts only integer values i could implement an edittextpreference and register an onpreferencechangelistener in which i could reject the change if the user enters a a string that is not a number but i would prefer something that is meant for holding only numbers and that does not allow users to enter anything else maybe showing only a dial pad keyboard i do not such a preference exist since every descendant of preference is mapped onto a boolean checkboxpreference a string edittextpreference or a string array multiselectlistpreference ie there are no preferences mapped onto integers but maybe some of you can give me an hint or at least tell me if there are better solutions than the one i have proposed abovesolution proposed by greyedittext edittext edittextpreference findpreferenceintent propertygetedittextedittextsetkeylistenernew numberkeylistener override public int getinputtype the following shows the standard keyboard but switches to the view with numbers on available on the top line of chars return inputtypetype class number return the following to show a dialpad as the one shown when entering phone numbers return inputtypetype class phone override protected char getacceptedchars return new string1234567890tochararray shorter solution which does not allow varying the keyboard to dialpad but requires less codeedittext edittext edittextpreference findpreferenceintent propertygetedittextedittextsetkeylistenernew digitskeylisteneri do not like just one thing about this solution the user can enter 0 and it is accepted and saved in the shared preference which is a string as 0 this requires you to implement a onsharedpreferencechangelistener to intercept changes to shared preferences and remove leading zeros in this preference or implement a change listener directly on this preference and return false to refuse numbers with trailing zeros tell me if there is a better solution to this last problem which does not involve implementing your own preference it would be beautiful if we could modify the newvalue in onpreferencechangelistener,['android'] +297511,generate array of random unique numbers in php i am trying to generate an array of random numbers from 0n then shuffle but ensure that the keys and values do not matchfor example0 31 22 43 04 1note that both keys and values are from 04 but none of the keys and values are the sameany thoughts,['php'] +297542,is there an alternative to stringutilsisnumeric that does what i mean stringutilsisnumeric returns true for and false for 78 this is of course it is documented behavior but really not the most convenient for me is there something else ideally in commonslang that provides an isactuallynumeric,['java'] +297549,in d3js skip append for null data i am drawing a line graph out of little circle bullets however the data has holes in it which are represented by nulls in my array naturally wherever there is no data there should not be circles but d3s append method adds them anyway how do i avoid thisheres a jsfiddle mockup reproducing my problem exactlyi am interested in not having that series of circles that lie on the x axis of my graph since those are all nullsrelevant code from the jsfiddle linksvgselectallcircledatavaluesenter appendcircle i do not want to do this for nulls attrfill c00 attrr 3 attrcx xi attrcy yflipped,['javascript'] +297576,java stringformat with currency symbol there is some existing code of the follow form which is used for format numerical valuesstringformat pattern value note that i cannot change the code itself i can only change the format pattern supplied to the codewhat is the format pattern to output a currency symbol for the default locale essentially i want to achieve the following outputstringformat 123 123,['java'] +297581,selecting alternative first view controller from story board at application startup i have just started on ios programming and so far the tutorials and answers i found here have been a great help to move forward however this particular problem has been bumming me all night and i cannot find an answer that feels righti am writing an application that connects to a remote service and the users need to sign in before they can use it when they start using the application their first view should be the sign in dialog when they have authenticated before they immediately see the overview pagethe project uses story boards which i think is a great feature so most of the code that selects and loads the root view controller is already taken care of i thought the best place to add my logic is the applicationdidfinishlaunchingwithoptions method of the appdelegate boolapplicationuiapplication application didfinishlaunchingwithoptions nsdictionary launchoptions select my root view controller here based on credentials present or not return yesbut this brought up two questionsinside this particular delegate method the root view controller has already been selected and loaded based on the story board could i move to an earlier spot in the loading process to override the first view controller selection or would that needlessly complicate mattersto override the first view controller i need a reference to the story board but i could not find a better way than to use the storyboardwithnamebundle constructor of uistoryboard that feels wrong the application should already have a reference to the story board but how can i access itupdatei worked out the second issue i was having as i found my answer hereuistoryboard whats the correctest way to get the active storyboardnsbundle bundle nsbundle mainbundlensstring sbfile bundle objectforinfodictionarykeyuimainstoryboardfileuistoryboard sb uistoryboard storyboardwithnamesbfile bundlebundlethe above will create a new story board instance to get the active instance it is a whole lot simpleruistoryboard sb selfwindow rootviewcontroller storyboardin the story board file itself you have to set an identifier for the view you wish to load eg logindialog afterwards you instantiate the view like thisloginviewcontroller login sb instantiateviewcontrollerwithidentifierlogindialogselfwindow setrootviewcontrollerloginwithin another view controller the following sufficesuistoryboard sb selfstoryboardloginviewcontroller login sb instantiateviewcontrollerwithidentifierlogindialogself presentviewcontrollerlogin animatedno completionnil,['iphone'] +297598,rails how to alias a relation in model i need to override the name of a relation here is my modelclass user activerecordbase has many class rooms member ships has many class rooms has many class rooms through class rooms member shipsendnow i need another name to use when i want to get class rooms through class rooms member shipshow can i achieve thisuserclass roomsuserclass rooms throughany idea,['ruby-on-rails'] +297626,how to use qxt libraries on pyqt first of all please excuse my bad english i hope you guys understand what i am sayingi have developed the server and client system the server side is based on qt and the client side is based on pyqt i wanted to build the client based on qt too but there were no other choices because of several issuesto communicate each other i use qlocalsocket but it is not enough i want to use signal and slot via networkfortunately i found out qxtrpcpeer it exactly supports what i want to do however unfortunately i could not find how to use qxtrpcpeer on python pyqti tried to use sip but i have no experiences about it and there is no enough time to study sip by myselfi hope there is another way to implement signalslot via network between qt and pyqt i await for your response and keep studying it too,"['c++', 'python']" +297645,entities doing too much i having an old puzzle so i thought i will share it with you may be will get right directionthing is that some of our entities in database are quite big read have many properties and rarely business logic uses all of entity properties so every time i need to think what properties must be loaded for business logic to work correctly very hypothetical samplepublic class product public string title getset public string description getset public string retailprice getset public string supplierid getset public supplier supplier getset many other propertiespublic class productthiscountservice public decimal getproduct product use only retailprice and supplier code return thiscount public class productdescriptionservice public string getsearchresulthtmlproduct product use only title and description return html it looks like i could extract interfaces ithiscountproduct and isearchresultproduct mark product as implementing those interfaces then create smaller dtos implementing each of those interfaces but that looks at the moment as overkill at least i have not seen anyone grouping properties using interfaces to split entity in database to smaller entities also does not look reasonable as all those properties belong to product and i am afraid i will be forced to use many joins to select something and if i will decide that some property belongs to another entity that move will be quite hard to implementto have every property used in particular methods business logic as method parameter also looks like bad solution,['c#'] +297648,creating progressive jpeg on ios with imageio produces blocky results on device i am trying to create a progressive jpeg from a uiimage object this is the code i am nsmutabledata data nsmutabledata datansstring path nshomedirectory stringbyappendingpathcomponent librarycachestestjpgcfurlref url cfurlcreatewithstringnull cfstringrefnsstring stringwithformatfile path nullcgimagedestinationref destination cgimagedestinationcreatewithurlurl kuttypejpeg 1 nullcfreleaseurlnsdictionary jfifproperties nsdictionary dictionarywithobjectsandkeys bridge idkcfbooleantrue kcgimagepropertyjfifisprogressive nilnsdictionary properties nsdictionary dictionarywithobjectsandkeys nsnumber numberwithfloat7 kcgimagedestinationlossycompressionquality jfifproperties kcgimagepropertyjfifdictionary nilcgimagedestinationaddimagedestination uiimageobjectcgimage bridge cfdictionaryrefpropertiescgimagedestinationfinalizedestinationcfreleasedestinationthis works great when running in simulator but unfortunately produces chunkyblocky results on deviceany ideas on whats going on i would revert to using uiimagejpegrepresentation as a last resort i really need progressive jpegs,"['iphone', 'ios']" +297650,override module method where fromimport is used i have problem to override method where fromimport statement is used some example to illustrate the problem apy moduledef print messagemsg printmsg bpy modulefrom a import print messagedef execute print messagehello cpy module which will be executedimport bbexecutei would like to override print messagemsg method without changing code in a or b module i tried in many ways but fromimport imports original method when i changed code toimport aaprint messagethan i see my changecould you suggest my how to solve this problemthanks in advance for any little examplebest regards update i tried to do that like below eg cpy moduleimport bimport aimport sysdef new print messagemsg printnew contentmodule sysmodulesamoduleprint message new print messagesysmodulea modulebut this is not working where i am using forimport statement is working only for import a but as i wrote i do not want change code in bpy and apy modules,['python'] +297698,how to upload a file to google drive using a python script i need to backup various file types to gdrive not just those convertible to gdocs formats from some linux serverwhat would be the simplest most elegant way to do that with a python script would any of the solutions pertaining to gdocs be applicable,['python'] +297747,ruby find string in file and print result it is been a very long time since i have used ruby for things like this but i forget how to open a file look for a string and print what ruby finds here is what i haveusrbinenv rubyf filenewfiletxttext freadif text string thenputs testendi want to determine what the document root routes is in configroutesrbif i print the string it prints the filei feel dumb that i do not remember what this is but i need to knowhopefully i can make it print this route isblah blah blah blah,"['ruby-on-rails', 'ruby']" +297754,input checkbox true or checked or yes i have seen the three implementations of preselecting a checkbox i started off using checkedchecked because i thought it was the proper way never did like the checkedyes however i am thinking of changing to checkedtrue as it seems more readable and is easier to code the javascript note that this same question applies to other attributes such as thisabledthisabled versus thisabledtrue as long as i am consistent is using true the preferred approach thank youinput typecheckbox checkedchecked value123 namehowdy input typecheckbox checkedtrue value123 namehowdy input typecheckbox checkedyes value123 namehowdy,"['javascript', 'html']" +297763,sending udp broadcast receiving multiple messages i have got 2 programs 1 for sending an udp broadcast message and 1 that is listening for this broadcast my problem is that sometimes when i send a broadcast the receiver receives 2 messages whyreceiver codepublic class receiver private readonly udpclient udp new udpclient150 private void startlistening thisudpbeginreceivereceive new object private void receiveiasyncresult ar ipendpoint ip new ipendpointipaddressany 150 byte bytes udpendreceivear ref ip string message encodingasciigetstringbytes startlistening sender codepublic class sender public void send udpclient client new udpclient ipendpoint ip new ipendpointipaddressbroadcast 150 byte bytes encodingasciigetbytesfoo clientsendbytes byteslength ip clientclose,['c#'] +297766,why do functionsobjects inside anonymous namespace have external linkage why do not symbols functions and variables that are defined in an anonymous namespace have internal linkage as with static keyword if a function is not visibleaccessible outside what is the reason to have external linkage,['c++'] +297784,how to change mysql primary key from signed to unsigned in my mysql innodb database with foreign keys i accidentally made some of my primary keys signed instead of unsigned as i want them to be now i want to change it with a alter table statement but it does not workalter table users change id id int11 unsigned not null auto incrementmysql errorerror on rename of db devsql478 3 to db devusers errno 150i do not understand why i am working with foreign keys and tried using a set foreign key checks 0statement before executing the alter table from above does not work either notice all my tables are still empty there is no data in it yet since the database has a lot of tables it would be much work to drop all the foreign keys and then manually add them again if this should be the reason,['mysql'] +297789,windows explorer context menus with submenus using pywin32 i am trying add some shell extensions using python with icons and a sub menu but i am struggling to get much further than the demo in pywin32 i cannot seem to come up with anything by searching google eitheri believe i need to register a com server to be able to change the options in submenu depending on where the right clicked filefolder is and the type of file etc a sample context menu handler adds a hello from python menu entry to py files when clicked a simple message box is thisplayed to demostrate execute this script to register the context menu open windows explorer and browse to a directory with a py file rightclick on a py file locate and click on hello from python on the context menuimport pythoncomfrom win32comshell import shell shellconimport win32guiimport win32conclass shellextension reg progid pythonshellextensioncontextmenu reg desc python sample shell extension context menu reg clsid ced0336cc9ee4a7f8d7fc660393c381f com interfaces shelliid ishellextinit shelliid icontextmenu public methods shellconicontextmenu methods shellconishellextinit methods def initializeself folder dataobj hkey print init folder dataobj hkey selfdataobj dataobj def querycontextmenuself hmenu indexmenu idcmdfirst idcmdlast uflags print qcm hmenu indexmenu idcmdfirst idcmdlast uflags query the items clicked on format etc win32concf hdrop none 1 1 pythoncomtymed hglobal sm selfdataobjgetdataformat etc num files shelldragqueryfilesmdata handle 1 if num files1 msg hello from python with d files selected num files else fname shelldragqueryfilesmdata handle 0 msg hello from python with s selected fname idcmd idcmdfirst items first python content menu item if uflags 0x0f shellconcmf normal check here since cmf normal0 print cmf normal itemsappendmsg elif uflags shellconcmf verbsonly print cmf verbsonly itemsappendmsg shortcut elif uflags shellconcmf explore print cmf explore itemsappendmsg normal file rightclick in explorer elif uflags cmf defaultonly print cmf defaultonlyrn else print unknown flags uflags win32guiinsertmenuhmenu indexmenu win32conmf separatorwin32conmf byposition 0 none indexmenu 1 for item in items win32guiinsertmenuhmenu indexmenu win32conmf stringwin32conmf byposition idcmd item indexmenu 1 idcmd 1 win32guiinsertmenuhmenu indexmenu win32conmf separatorwin32conmf byposition 0 none indexmenu 1 return idcmdidcmdfirst must return number of menu items we added def invokecommandself ci mask hwnd verb params dir nshow hotkey hicon ci win32guimessageboxhwnd hello wow win32conmb ok def getcommandstringself cmd typ if getcommandstring returns the same string for all items then the shell seems to ignore all but one this is even true in win7 etc where there is no status bar and hence this string seems ignored return hello from python cmdd cmddef dllregisterserver import winreg folder key winregcreatekey winreghkey classes root foldershellex folder subkey winregcreatekeyfolder key contextmenuhandlers folder subkey2 winregcreatekeyfolder subkey pythonsample winregsetvalueexfolder subkey2 none 0 winregreg sz shellextension reg clsid file key winregcreatekey winreghkey classes root shellex file subkey winregcreatekeyfile key contextmenuhandlers file subkey2 winregcreatekeyfile subkey pythonsample winregsetvalueexfile subkey2 none 0 winregreg sz shellextension reg clsid print shellextension reg desc registration completedef dllunregisterserver import winreg try folder key winregdeletekey winreghkey classes root foldershellexcontextmenuhandlerspythonsample file key winregdeletekey winreghkey classes root shellexcontextmenuhandlerspythonsample except windowserror details import errno if detailserrno errnoenoent raise print shellextension reg desc unregistration completeif name main from win32comserver import register registerusecommandlineshellextension finalize register dllregisterserver finalize unregister dllunregisterserver,['python'] +297800,how to invite friends to my application via facebook ios sdk and graph api i am writing an iphone applicationi want to give the user the option to invite friends to start using my application via facebookmore specifically i want to present a dialog that will let the user to select specific friends to invitehow can i do thisthanks,"['iphone', 'objective-c']" +297803,mvc 4 webapi with powerpivot does anyone know if mvc 4 webapi can or will be consumable in powerpivot,['.net'] +297830,how to do multiple arguments to map function where one remains the same in python lets say we have a function add as followsdef addx y return x ywe want to apply map function for an array mapadd 1 2 3 2the semantics are i want to add 2 to the every element of the array but the map function requires a list in the third argument as wellnote i am putting the add example for simplicity my original function is much more complicated and of course option of setting the default value of y in add function is out of question as it will be changed for every call,['python'] +297843,smack client user is still online although connection aborted i experience a quite strange behavior using smack to build a small xmpp clientbot i set up the connection as well as a connectionlistener and a chatmanagerlistener this works quite fine and i can then chat with my application which is running on a portable deviceto test behavior on lost connection i plugged out the ethernet cable of the portable device i expected the xmpp client to lose the connection and that the user will be set offline in the roster of the users buddies what happens is that this user is still shown as online and connectionlistener of my client fires nothing whether connectionclosed nor reconnectionfailed or elsewhen i then plug the ethernet cable back in sometimes it is like the connection has been alive all the time the offline messages are handled and i can chat again like beforeother times my client is totally inaccessible and out of order seems like all the listeners are gone but no excpetions are thrownthat is a quite strange and uncontrollable behavior that would make the whole client unusable for me as i cannot be sure that the client will come up again after connection has been arbortedhas anybody else experienced such problems or has any hints whats not happeningif needed i can provide my code but it is actually just copy paste from the smack documentation,['java'] +297844,how to change text transparency in htmlcss i am very new to htmlcss and i am trying to thisplay some text as like 50 transparent so far i have the html to thisplay the text with full opacityhtmlfont colorblack facearial size4this is my textfonthtmlhowever i am not sure how to change its opacity i have tried looking online but i am not sure exactly what to do with the code i find could someone help thanks,"['html', 'css']" +297863,requirejs using multiple datamains i am using requirejs 20 or attempting to usecurrently my assets are grouped into to parts general and custom all pages should use the general scripts while only some pages should use the custom from what i can tell requirejs accepts one datamain value which holds your config and basically your module requires this is fine if all pages use the same assets but how would i add an additional datamain script for custom pagesthank you,['javascript'] +297870,socketasynceventargs buffer is full of zeroes i am writing a message layer for my thistributed system i am using iocp ie the socketxasync methodsheres something pretty close to what i am doing in fact my receive function is based on hiswhat i have found now is that at the start of the program two test servers talking to each other i each time get a number of saea objects where the buffer is entirely filled with zeroes yet the bytestransferred is the size of the buffer 1024 in my casewhat does this mean is there a special condition i need to check for my system interprets this as an incomplete message and moves on but i am wondering if i am actually missing some data i was under the impression that if nothing was being received youd not get a callback in any case i can see in wireshark that there are not any zerolength packets coming ini have found the following when i googled it but i am not sure my problem is the same,"['c#', '.net']" +297910,adding to numbermax value the answer to this question may be painfully obvious but i cannot find it in the mozilla docs nor on google from a cursory searchif you have some code like thisnumbermax value 1 infinity rightnumbermin value 1 infinity rightthen i would expect adding anything to numbermax value would push it over to infinity the result is just numbermax value spat right back at mehowever when playing around in the chrome js console i noticed that it did not actually become infinity until i addedsubtracted enoughnumbermax value mathpow10010 now we hit infinitynumbermin value mathpow10010 infinity at lastwhat is the explanation for this buffer between numbermax value and infinity,['javascript'] +297917,how is the default ruby load path determined assuming i compile my own fresh ruby mri 193 what is the default load path and how is that computed,['ruby'] +297941,large dynamically sized html table with a fixed scroll row and fixed scroll column i need to thisplay a large table on a web page and need to prevent the first column and first row from scrolling i would like to dynamically set the vertical size of this table between some static size headerfooter page content to make it as tall as possible without forcing the browser window to have a vertical scrollbar browser window fixed static web page header fields and text size tablescrollbar colspan fixed fixed fixed fixed fixed fixed more fixed t fixed a b fixed l e set fixed dynamic multiline s size atc runtime fixed r o fixed l l fixed b a r fixed morev web page footer fields and text fixed static size this only needs to work in modern browsers using allany html css javascript jqueryorder of importance complex table with many form fields hidden values javascript collapsing of rows etc which i will add later 1st row will have colspans rows will have variable height1st row fixed from vertical scroll but can scroll horizontally1st column fixed from horizontal scroll but can scroll verticaldynamically size this table to fill the screen between the static size headerfooter htmllocation of the scroll bars as depicted in my awesome ascii art above is not criticalhere is a very basic html sample of the screen without any of the scrollsizing featuresdoctype html public w3cdtd xhtml 10 transitionalenhtmlheadtitlebig scrolling table exampletitleheadbody form namemyform methodpost action static size header junk static size header junk static size header junk table border1 width100 cellspacing1 cellpadding0 aligncenter tr td width35 alignleftheader junk lefttd td header junk middle td td width35 alignrightheader junk righttd tr table br table border0 width95 cellspacing1 cellpadding0 aligncenter tr td width60 alignleftheader junk lefttd td width40 alignrightcheck it out input typecheckbox onchangealertyour javascript here valuey namecheckitouttd tr big table here big table here big table here big table here table border1 width95 cellspacing1 cellpadding0 aligncenter tr tdfixed can be longbror shorttd td colspan4scroll atd td colspan2scroll btd td scroll ctd td colspan4scroll dtd td colspan2scroll etd td scroll ftd td colspan4scroll gtd td colspan2scroll htd td scroll itd td colspan4scroll jtd td colspan2scroll ktd td scroll ltd td colspan4scroll mtd td colspan2scroll ntd td scroll otd tr tr tdfixed 2td td1 1 1 1 1 atdtd2 2 2 2 2 atdtd3 3 3 3 3 atdtd4 4 4 4 4 atd td1 btdtd2 btd td 1 ctd td1 dtdtd2 dtdtd3 dtdtd4 dbrmoretd td1 etdtd2 etd td 1 ftd td1 1 1 gtdtd2 2 gtdtd3 gtdtd4 4 4 4 gtd td1 htdtd2 htd td 1 itd td1 jtdtd2 jtdtd3 jtdtd4 jtd td1 ktdtd2 2 kbrmorebrmoretd td 1 ltd td1 mtdtd22 mtdtd3 mtdtd4 mtd td1 ntdtd2 ntd td 1 1 1 1 1 1 1 otd tr tr tdfixed 3td td1 1 1 1 1 atdtd2 2 2 2 2 atdtd3 3 3 3 3 atdtd4 4 4 4 4 atd td1 btdtd2 btd td 1 ctd td1 dtdtd2 dtdtd3 dtdtd4 dbrmoretd td1 etdtd2 etd td 1 ftd td1 1 1 gtdtd2 2 gtdtd3 gtdtd4 4 4 4 gtd td1 htdtd2 htd td 1 itd td1 jtdtd2 jtdtd3 jtdtd4 jtd td1 ktdtd2 2 kbrmorebrmoretd td 1 ltd td1 mtdtd22 mtdtd3 mtdtd4 mtd td1 ntdtd2 ntd td 1 1 1 1 1 1 1 otd tr tr tdfixed 4td td1 1 1 1 1 atdtd2 2 2 2 2 atdtd3 3 3 3 3 atdtd4 4 4 4 4 atd td1 btdtd2 btd td 1 ctd td1 dtdtd2 dtdtd3 dtdtd4 dbrmorebrmorebrmorebrmoretd td1 etdtd2 etd td 1 ftd td1 1 1 gtdtd2 2 gtdtd3 gtdtd4 4 4 4 gtd td1 htdtd2 htd td 1 itd td1 jtdtd2 jtdtd3 jtdtd4 jtd td1 ktdtd2 2 kbrmorebrmoretd td 1 ltd td1 mtdtd22 mtdtd3 mtdtd4 mtd td1 ntdtd2 ntd td 1 1 1 1 1 1 1 otd tr tr tdfixed 5td td1 1 1 1 1 atdtd2 2 2 2 2 atdtd3 3 3 3 3 atdtd4 4 4 4 4 atd td1 btdtd2 btd td 1 ctd td1 dtdtd2 dtdtd3 dtdtd4 dbrmoretd td1 etdtd2 etd td 1 ftd td1 1 1 gtdtd2 2 gtdtd3 gtdtd4 4 4 4 gtd td1 htdtd2 hbrhbrhbrhbrhtd td 1 itd td1 jtdtd2 jtdtd3 jtdtd4 jtd td1 ktdtd2 2 kbrmorebrmoretd td 1 ltd td1 mtdtd22 mtdtd3 mtdtd4 mtd td1 ntdtd2 ntd td 1 1 1 1 1 1 1 otd tr tr tdfixed 6br6br6br6td td1 1 1 1 1 atdtd2 2 2 2 2 atdtd3 3 3 3 3 atdtd4 4 4 4 4 atd td1 btdtd2 btd td 1 ctd td1 dtdtd2 dtdtd3 dtdtd4 dbrmoretd td1 etdtd2 etd td 1 ftd td1 1 1 gtdtd2 2 gtdtd3 gtdtd4 4 4 4 gtd td1 htdtd2 htd td 1 itd td1 jtdtd2 jtdtd3 jtdtd4 jtd td1 ktdtd2 2 kbrmorebrmoretd td 1 ltd td1 mtdtd22 mtdtd3 mtdtd4 mtd td1 ntdtd2 ntd td 1 1 1 1 1 1 1 otd tr table static size footer junk static size footer junk static size footer junk static size footer junk table border1 width100 cellspacing1 cellpadding0 aligncenter tr td width35 alignleftfooter junk lefttd td footer junk middle td td width35 alignrightfooter junk righttd tr formbodyhtml,"['javascript', 'jquery', 'html', 'css']" +297968,how does stackoverflow make its tag input field how does stackoverflow create its tag system how can it format the html in a text areai just do not know where to begin if someone could guide me then i can know what direction to take so i can write some code that someone can checklike thiseditbasically when i press space how do i add a new elementdiv to the inside of the div,['html'] +297978,django post save preventing recursion without overriding model save there are many stack overflow posts about recursion using the post save signal to which the comments and answers are overwhelmingly why not override save or a save that is only fired upon created truewell i believe there is a good case for not using save for example i am adding a temporary application that handles order fulfillment data completely separate from our order modelthe rest of the framework is blissfully unaware of the fulfillment application and using post save hooks isolates all fulfillment related code from our order modelif we drop the fulfillment service nothing about our core code has to change we delete the fulfillment app and that is itso are there any decent methods to ensure the post save signal does not fire the same handler twice,['python'] +298022,android objects cache looking for a simple open source noncopyleft caching for android sdk 7 classthe purpose is primary to store the bitmaps fetched asynchronously so i do not need this functionality to be included in the cache classi was using a weaklist for this purpose that was naturally a bad solution with guava cache that is a little better but still not fineit is preferred that the cache is able to store any serializable object not just a bitmap and that i could easily purge the objects of certain tag used while the object is added to cachethe best option would be to get the filesystem cache like wrapping the sqlite databaseit would be great if the cache would be cleared by settings manage application clear cache,"['java', 'android']" +298031,linkedblockingqueue with fast containsobject o method in a nutshell i am writing an application that needs a blockingqueue implementation that provides both fifo addsremoves but also a fast contains method as i will be calling it a tonlinkedblockingqueue gets me most of the way there but it appears that its contains method runs in linear time as it is based on abstractqueues contains method i did not see anything in the java api that seemed to advertise an lbq with fast contains outoftheboxwhat makes things tougher is my project is on a really severe time crunch no this is not homework i could do a quickanddirty lbq extension with a hashset underneath for fast contains but i am still going to have to test it which could eat up a significant amount of manhours i am wondering if there are any trustedwelltested libraries out there that provide a linkedblockingqueue extension with a contains method that runs in o1 time if not any other suggestions are welcome,['java'] +298033,win32 readfile from pipe block even after child terminated i have a simple program in c that create two child process wait on an inherited pipe each and put the output in a fileeverything works well except that after some writeread cycle on the two pipe when the child ends the call to readfile block waiting for data on the pipe i use the following patterncreate pipe1createpipehreadduphwritesaattr0duplicatehandlegetcurrentprocesshreaddupgetcurrentprocesshread0falseduplicate same accessclosehandlehreaddupsicb sizeofsisidwflags startf usestdhandlessihstdoutput hwrite createprocess null const castlpwstrcmd2c str the command to execute null null true 0 null null si si pi closehandlehwrite edit this was the operation not properly donewhilecont cont readfilehreadbuf50 actualnull the last call after child process exit blockidea of why and if not how to debug this,['c'] +298036,php class datetime not found missing something when declaring a datetime object in php 538i get a json string with a determinate date time which is passed to my php controllerfor some reason i am not getting it to be mapped as a datetime object in php but sort of weirdly see the following imagesas you can see in the expressions window top right before the step i am checking that new datetimemyvariable is bringing and transforming correctly what i need in the first watch the variable to pass to datetime constructor in the second watch the expression newdatetimemyvariable already mapped as a datetimeobject apparently fine up to herebut sadly when i go forward and press f6 the following exemption see also the image below is thrownfatal error class acmestorebundlerepositorydatetime not found in userspgboninositessymfonysrcacmestorebundlerepositoryhistoryrepositoryphp on line 19call stack 00201 693568 1 main userspgboninositessymfonywebapp devphp0 00267 2106576 2 symfonycomponenthttpkernelkernelhandle userspgboninositessymfonywebapp devphp24 00377 2649176 3 symfonybundleframeworkbundlehttpkernelhandle userspgboninositessymfonyappbootstrapphpcache547 00378 2650832 4 symfonycomponenthttpkernelhttpkernelhandle userspgboninositessymfonyappcachedevclassesphp4879 00378 2650832 5 symfonycomponenthttpkernelhttpkernelhandleraw userspgboninositessymfonyappcachedevclassesphp3875 01574 5562232 6 call user func array userspgboninositessymfonyappcachedevclassesphp3905 01574 5562600 7 acmestorebundlecontrollerhistorycontrollersavetestaction userspgboninositessymfonyappcachedevclassesphp3905 01694 5739032 8 acmestorebundlerepositoryhistoryrepositorysavetestinhistory userspgboninositessymfonysrcacmestorebundlecontrollerhistorycontrollerphp33so strangely the watch expressions window from eclipse is not working just like the execution engine andor viceversaof course i would prefer it to be the opposite it worked in the execution and not in the watch window so any idea,['php'] +298049,java aes cbc decryption php encrypt functionprivatekey 1234567812345678iv 1234567812345678data test stringencrypted mcrypt encryptmcrypt rijndael 128 privatekey data mcrypt mode cbc ivechobase64 encodeencryptedresult iz1qflqjfs6ycpgcc2z4wwhen i try to decrypt this result in java using the function below all i get back is ai12aabkxnfaa am while i am expecting test string any ideas where i am wrong thankspublic static string decrypt throws exception try string base64encodedtext iz1qflqjfs6ycpgcc2z4w string decodedtext comsunxmlinternalmessagingsaajutilbase64base64decodebase64encodedtext string key 1234567812345678 string iv 1234567812345678 javaxcryptospecsecretkeyspec keyspec new javaxcryptospecsecretkeyspeckeygetbytes aes javaxcryptospecivparameterspec ivspec new javaxcryptospecivparameterspecivgetbytes javaxcryptocipher cipher javaxcryptociphergetinstanceaescbcnopadding cipherinitjavaxcryptocipherdecrypt mode keyspec ivspec byte decrypted cipherdofinaldecodedtextgetbytes string str new stringdecrypted return str catchexception e return null,['java'] +298068,android debugging with eclipse no breakpoints i am trying to debug a simple android application on either the emultor or a device and i cannot get the debugger to stop on any breakpoints i have set i have combined the other posts here and throughout the web and tried all the suggestions add debuggabletrue to the manifest stop and start adb clean all make sure i use the debug button not the run button etc etc in the debug perspective i can see the threads and in ddms it shows the debug icon next to the device i am debugging on i do see the blue dots where i set the breakpoint and the debug perspective lists them and says they are activei have put in alerts just before the breakpoints to verify the code is getting executedstarting to go crazy here any other suggestions i must be missing something simple but nonobviousupdate i appreciate the responses so far unfortunately they have not solved my problem i have followed the instruction on debugging and have debugging turned on in the phone also i do see the waiting for debugger alert on the phone when starting in general everything says i am debugging including getting logcat output that i have added it just will not stop on breakpoints that i have added and are listed in the breakpoints tab in the debug perspective also just to reiterate this happens when debugging on the device as well as on the emulator one thing i do notice is that when i launch the debugger i have it set to bring up the android device chooser in there the debug column is blank for my device but if the emulator is running the debug column does say yes also the console states that is attempting to connect to the debugger should there be a console log that states that the debugger successfully connected i do not see thisupdate 20120914 i have been away from this for some time and had given up previously back to try and tackle this it is still not resolved everything above is still current but one other thing i have noticed i set a class load breakpoint on the main activity and it does stop there it just does not stop at any line breakpoints i have just updated to the latest jdk 170 07 android sdk 20 adt plugin 2003 i have used the logcat to output a message and set a breakpoint on this line i see the message in logcat so i know the code is being executed the debug window in the debig perspective also does show the android application with a number of threads beneath it and the devices window in the ddms perspective shows the application with the green bug icon next to itone more thing when the debugger is running the line breakpoints bullets do not get a checkmark overlaid on them the class load breakpoint does i am guessing this is the root cause but i do not know why they are not getting this by the way skip breakoints is also not set breakpoints do not have lines through themany new suggestions would be appreciated i have burned a lot of time on this it must be something obvious that i am not seeing,['android'] +298081,python multiprocessing design i have written an algorithm that takes geospatial data and performs a number of steps the input data are a shapefile of polygons and covariate rasters for a large raster study area 150 million pixels the steps are as followssample points from within polygons of the shapefilefor each sampling point extract values from the covariate rastersbuild a predictive model on the sampling pointsextract covariates for target grid pointsapply predictive model to target gridwrite predictions to a set of output gridsthe whole process needs to be iterated a number of times say 100 but each iteration currently takes more than an hour when processed in series for each iteration the most timeconsuming parts are step 4 and 5 because the target grid is so large i have been processing it a block say 10 rows at a timei have a 6core cpu with 32 gb ram so within each iteration i had a go at using pythons multiprocessing module with a pool object to process a number of blocks simultaneously steps 4 and 5 and then write the output the predictions to the common set of output grids using a callback function that calls a global outputwriting function this seems to work but is no faster actually it is probably slower than processing each block in seriesso my question is is there a more efficient way to do it i am interested in the multiprocessing modules queue class but i am not really sure how it works for example i am wondering if it is more efficient to have a queue that carries out steps 4 and 5 then passes the results to another queue that carries out step 6 or is this even what queue is forany pointers would be appreciated,['python'] +298087,100 height block with vertical text i have a block of a variable height in which i want to put another block with 100 height and vertical text bottomtotop direction and stack it to the left side of the outer block is there a way to achieve it with css transforms but without width and height calculations in jsthis is what i could get so fardoctype html public w3cdtd xhtml 11en html xmlns xmllangenheadstyle typetextcssblock1 border 4px solid 8 height 120px width 200pxblock2 height 100 border 4px solid redmsg thisplay inlineblock whitespace nowrap fontfamily verdana fontsize 14pt moztransform rotate90deg moztransformorigin center center webkittransform rotate90deg webkittransformorigin center center mstransform rotate90deg mstransformorigin center centerstyleheadbody div classblock1 table classblock2 tr td div classmsghi therediv td tr table divbodyhtmlyou can see that the inner blocks computed width is the same as the text width before rotationupdatehere is the picture of what i want to get in the endit is a horizontal stripe with items stacked to its left side and with a vertical header block stripes height is variable so items should adapt and the headers text should remain centered,"['html', 'css']" +298089,how to embed symfony2 actions into wordpress i have been researching it a lot and trying it out but i am kind of stumpedi want to setup a site in wordpress which is helpful for another guy working with me the site will advertise our product and provide information then users can sign up through a series of forms i want to write this custom part forms etc in symfony2 because it has no need to be tied to wordpress and it would have reusable doctrine2 entities to thisplay the data after a user has signed up thisplaying happens outside of wordpress anywaybut designwise we would like the whole process to be uninterrupted and have the same lookandfeel so the forms should actually be rendered in wordpress pages we are using a custom nonfree theme and i would hate to just copypaste a bunch of wordpress css and headers into symfony viewsideally i want to just define pages in wordpress which can render symfony2 actions so the actions themselves might thisplay and process forms which should work independently of wordpress say at but they should normally be thisplayed in the wordpress site for example within a page like id2 or a permalinki have been researching lowpress as a way to integrate but it does way more than i want by removing the wordpress themes altogether and replacing them with twig themes i tried to borrow a few ideas from it so now i have wordpress in the web folder of the symfony project and this in my wpconfigphp code omitteddefinewp debug truedefinesymfony dir dir apprequire once symfony dirbootstrapphpcacherequire once symfony dirappkernelphprequire once symfony dirappcachephpuse symfonycomponenteventthispatchereventuse symfonycomponenthttpfoundationrequestkernel new appkernelwp debug dev prod wp debugkernelloadclasscachekernelbootglobalssf2 kernel kernel save request before wordpress messes with itglobalssf2 request requestcreatefromglobalsdoctrine kernelgetcontainergetdoctrineconn doctrinegetconnectiondoctrinegetdefaultconnectionname mysql settings you can get this info from your web host the name of the database for wordpress definedb name conngetdatabase mysql database username definedb user conngetusername mysql database password definedb password conngetpassword mysql hostname definedb host conngethost database charset to use in creating database tables definedb charset utf8 the database collate type do not change this if in doubt definedb collate code omittedso all i have got now is a shared db config via parametersini in symfony next i have been trying to make a simple plugin which uses a shortcode so i can render a symfony2 action in a wordpress page here is what i have so far as an idea it is dependent upon the above bootstrapping and it is incompleteuse symfonycomponenthttpfoundationrequestclass symfony2page public function renderatts extractshortcode attsarray controller croltsmainbundledefaultindex atts kernel globalssf2 kernel request globalssf2 request requestheaderssetxphpoblevel ob get level attributes array todo fix this kernelgetcontainerenterscoperequest kernelgetcontainersetrequest request request try response kernelgetcontainergethttp kernelrendercontroller attributesgetcontent catch exception e kernelgetcontainerleavescoperequest throw e kernelgetcontainerleavescoperequest return response add shortcodesf action arraysymfony2page rendermy first problem is i do not know how to actually render some symfony2 route which may have parameters when the given request would not have the information i need the other problem is if i want forms to submit it probably wouldnt work because it would redirect the user outside of wordpress when really i may want a series of forms which all exist in the wordpress page at the same time i want the forms to be independent of wordpress so they work on their ownso i want to know if this is just a badhacky idea which would not work or if there is some way to get it workingi was also thinking of just using ajax to load the symfony2 code in wordpress assuming that all of my users have javascript enabled as a fallback the page could just go to a symfony2only app rather than being within a wordpress page would that be bettereasier the only downside i can see is that i have to keep the ajax code in sync with my symfony2 code,['php'] +298107,css3 button background color infinite transition is there a way to make a buttons background color fade from grey to blue then back to gray using only css3 a good example is a default action button is cocoa i know this can be done in javascript but i would rather only use css for this,['css'] +298114,remove object at nsmutablearray in range i am trying to remove objects at array starting at index 5 to the end of the list i have a for loop to do this however now i thiscovered voidremoveobjectidanobject inrangensrangearangethe question is what is the anobject here i only need range as far as i know,"['iphone', 'objective-c', 'ios']" +298196,thisappointing performance with parallelfor i am trying to speed up my calculation times by using parallelfor i have an intel core i7 q840 cpu with 8 cores but i only manage to get a performance ratio of 4 compared to a sequential for loop is this as good as it can get with parallelfor or can the method call be finetuned to increase performancehere is my test code sequentialvar loops 200var perloop 10var sum 00for var k 0 k loops k var sumk 00 for var i 0 i perloop i sumk 10 i i sum sumkand parallelsum 00parallelfor0 loops k var sumk 00 for var i 0 i perloop i sumk 10 i i sum sumk the loop that i am parallelizing involves computation with a globally defined variable sum but this should only amount to a tiny tiny fraction of the total time within the parallelized loopin release build optimize code flag set the sequential for loop takes 337 s on my computer whereas the parallelfor loop takes 84 s a performance ratio of only 40in the task manager i can see that the cpu utilization is 1011 during the sequential calculation whereas it is only 70 during the parallel calculation i have tried to explicitly set paralleloptionsmaxdegreesofparallelism environmentprocessorcountbut to no avail it is not clear to me why not all cpu power is assigned to the parallel calculationi have noticed that a similar question has been raised on so before with an even more thisappointing result however that question also involved inferior parallelization in a thirdparty library my primary concern is parallelization of basic operations in the core librariesupdateit was pointed out to me in some of the comments that the cpu i am using only has 4 physical cores which is visible to the system as 8 cores if hyper threading is enabled for the sake of it i thisabled hyperthreading and rebenchmarkedwith hyperthreading thisabled my calculations are now faster both the parallel and also the what i thought was sequential for loop cpu utilization during the for loop is up to approx 45 and 100 during the parallelfor loopcomputation time for the for loop 156 s more than twice as fast as with hyperthreading enabled and 62 s for parallelfor 25 better than when hyperthreading is enabled performance ratio with parallelfor is now only 25 running on 4 real coresso the performance ratio is still substantially lower than expected despite hyperthreading being thisabled on the other hand it is intriguing that cpu utilization is so high during the for loop could there be some kind of internal parallelization going on in this loop as well,['c#'] +298222,how do the android animations work under the hood during the past few months i built an opensource tweening engine in java universal tween engine to be able to easily add smooth animations and transitions to my android games it works like a breeze for games and is successfully used by many people mostly in the libgdx community the library is generic and can be used to animate anything swing ui components opengl game objects etc now i want to create an addon to the lib dedicated to android uis since i believe it can greatly ease the creation of very complex animations compared to the builtin animation frameworkmy lib exposes a updatefloat deltatime method that has to be called each time you want to update all the running animations it was tailored for games since every game exposes an infinite loop but that is not the case for uistherefore i was wondering how the animation framework of the android api works under the hood is there a static thread dedicated to animations that runs continuously and updates animations framebyframe and get paused until there is a new animation runningi was thinking about something like that but i am not really happy with this code since it does not take the device refresh rate into account for instance,['android'] +298228,tips for using a c library from c i have got a library in c which i would like to use from c from what i have gleaned off the internet one idea is to wrap it in a c dll and dllimport thatthe problem is that the function i want to call has a fairly nasty parameter set including a reference to a function which will be a net function and a couple of arrays some write some readint lmdifint fcnint int double double int int m int n double x double ftol double xtol double gtol int maxfev double epsfcn double factorgiven an interface like this what are the nasties i should be looking out for and solutions too pleasewhy do not you rewrite in c i started but it is already machinetranslated from fortran and i do not much like coding stuff i cannot understand use an existing net library i am trying it right now but results are not exactly the same recompile in c i am thinking about it but it looks like a lot of pain,"['c#', '.net', 'c']" +298229,in http user agent header of android what does the u mean i am trying to implement a http user agent header parseri am curious to know the meaning of u in http user agent header of androidthis is a sample http user agent header of androidmozilla50 linux u android 402 kokr galaxy nexus buildicl53f applewebkit53430 khtml like gecko version40 mobile safari53430does anyone know about it,['android'] +298255,convert kinect colorimageframe to bitmap ia m using kinect microsoft sdk with xna i want to use gratf for markerrecognitionhow to convert the data of a kinect colorimageframe to a systemdrawingbitmap or aforgeimagingunmanagedimage that i can process them with gratfvoid kinectsensor colorframereadyobject sender colorimageframereadyeventargs e bitmap bitmap null colorimageframe frame eopencolorimageframe byte buffer new byteframepixeldatalength framecopypixeldatabuffer how to convert the data in buffer to a bitmap var glyphs recognizerfindglyphsbitmap,"['c#', '.net']" +298266,using dependency injection in aspnet mvc3 model binder i am working on mvc3 website trying to use ninject to resolve my dependencies i have the following scenariopublic class usermodelbinder imodelbinder inject public userdataservice userdata get set public object bindmodel controllercontext controllercontext modelbindingcontext bindingcontext guid userid guidmembershipgetuserprovideruserkey userdataservice dependencyresolvercurrent getserviceuserdataservice user user userdataservicegetuseruserid return user noticed the commented lines of codei do register the binder in globalasax as modelbindersbinderstypeofuser new usermodelbinderso i cannot really do injection through the constructionuserdataservice has a chain of dependencies userdataservice userrepository context so it would be good to use ninject herethe problem is when i uncomment inject above userdata declaration and try getting ninject to inject object as a parameter it does not work for some reason i get null reference exceptionscould it be that userdataservice does not have an interface and i am binding the object to itself kernelbinduserdataservicetoself i have another commented line in the code userdataservice dependencyresolvercurrent getserviceuserdataservicewhen this is uncommented the set up works i get correct objects inserted but now we depend on dependencyresolver and that is not much better than saying userdataservice new userdataserviceam i missing something is there another way to inject an object as a parameter and not introducing dependency on ninject or dependencyresolver,"['c#', '.net']" +298306,different wcf bindings their differences and compatibility with other platforms i am looking for some good technical details on topic of wcf bindings i am interested to know following thingslist of different wcf bindings with its special purpose and limitationcompatibilityinteroperability with other platform like consuming wcf service in java php client which binding is supported and which is notif i want to getpost secure data through service api which binding should i use if client application is in java or php i have browsed through different material over internet but it is not in detail and somewhat scattered waiting for some good responses,"['c#', 'java', 'php', '.net']" +298310,get barcode reader value form background monitoring i want to create an accounting program with c languagei want to use a barcode reader for searching products in shop this is optional for my programnow in main form if seller uses a barcode reader get barcode value for handle method or eventhow can i get barcode value in background of form without text box for handle method or event note my barcode reader is hid usb interface,"['c#', '.net']" +298330,how do i validate active directory creds over ldap ssl i am trying to use the net 35 systemdirectoryservicesaccountmanagement namespace to validate user credentials against our active directory ldap server over an ssl encrypted ldap connection heres the sample codeusing var pc new principalcontextcontexttypedomain sdexamplecom389 dcsddcexampledccom contextoptionsnegotiate return pcvalidatecredentials username passwordthis code works fine over unsecured ldap port 389 however i would rather not transmit a userpass combination in clear text but when i change to ldap ssl port 636 i get the following exceptionsystemdirectoryservicesprotocolsdirectoryoperationexception the server cannot handle directory requests at systemdirectoryservicesprotocolserrorcheckingcheckandsetldaperrorint32 error at systemdirectoryservicesprotocolsldapsessionoptionsfastconcurrentbind at systemdirectoryservicesaccountmanagementcredentialvalidatorbindldapnetworkcredential creds contextoptions contextoptions at systemdirectoryservicesaccountmanagementcredentialvalidatorvalidatestring username string password at systemdirectoryservicesaccountmanagementprincipalcontextvalidatecredentialsstring username string password at my codeport 636 works for other activities such as looking up nonpassword information for that ldapad entryuserprincipalfindbyidentitypc identitytypesamaccountname usernameso i know it is not my ldap servers ssl setup since it works over ssl for other lookupshas anyone gotten the validatecredentials call to work over ssl can you explain how or is there anotherbetter way to securely validate adldap credentials,"['c#', '.net']" +298363,how to have a a razor action link open in a new tab i trying to get my link to open in a new tab it must be in razor format a hrefurlactionrunreport performance new reportview modelreportviewtostring new target blank typesubmit idrunreport classbutton secondaryreportsrunreportathis is not working though anyone know how to do this,"['c#', 'html']" +298364,objectivec classes in structs with arc i tried making a struct with classes in it likestruct my struct nsstring string more fieldsto my surprise objectivec allowed this with arc enabledhow will it manage the stringit can easily retain in each assignment but release is the problemit can add a destructor with release in it but this will make the struct nontrivialit can also make this not retain or release but to do so there should be unsafe unretained from my observation nothing crashes when using this but i would like to know what really happens here,['objective-c'] +298408,dynamic binding in c class a public virtual void whoareyou consolewritelinei am an a class b a public override void whoareyou consolewritelinei am a b class c b public new virtual void whoareyou consolewritelinei am a c class d c public override void whoareyou consolewritelinei am a d c c new dcwhoareyou i am a da a new dawhoareyou i am a b how the reference is allocated internallyreference a contains the reference of bcan any one explain whats going on,['c#'] +298411,add participant to an event in ios in the ekparticipant class reference send attendees to an ekevent object to get an array of ekparticipant objects ok buy how can i send attendees to an ekevent object someone give example code,"['iphone', 'ios']" +298423,combining predicates in f is there a standard way of logically combining predicates in ffor example let us say i have iscar x and isblue x then i want something that gives melet isbluecar x iscar x isblue xbut using some sort of composition rather than invocation maybe likelet isbluecar x iscar isbluepreferably that something would be able to accept a largearbitrary number of predicates,['.net'] +298430,behaviour of malloc with delete in c int pint mallocsizeofintdelete pwhen we allocate memory using malloc then we should release it using free and when we allocate using new in c then we should release it using deletebut if we allocate memory using malloc and then use delete then there should be some error but in the above code there is no error or warning coming in calso if we reverse and allocate using new and release using free then also there is no error or warningwhy is it so,['c++'] +298441,start a second copy of the program with the same arguments what is the correct way for a application to restart another copy of itself with the same argumentsmy current method is to do the followingstatic void main consolewritelinestart new copy consolereadline string args environmentgetcommandlineargs will not work if using vshost uncomment the next line to fix that issue args0 regexreplaceargs0 vshostexe exe put quotes around arguments that contain spaces for int i 1 i argslength i if argsicontains argsi stringconcat argsi combine the arguments in to one string string joinedargs stringempty if argslength 1 joinedargs stringjoin args 1 argslength 1 start the new process procestartargs0 joinedargshowever it seems like there is a lot of busy work in there ignoring the striping of the vshost i still need to wrap arguments that have spaces with and combine the array of arguments in to a single stringis there a better way to launch a new copy of the program including the same arguments perhaps a way just needing to pass in enviromentcommandline or takes a string array for the arguments,['c#'] +298453,android using objectanimator to translate a view with fractional values of the views dimension it appears that the old view animations translate scale and so on are no longer accepted by the animationinflater at least as of ics i read its code in 404 and it explicitly expects only the xml elements set objectanimator animatoreven though the documentation at continues to include the view animations they appear to be deprecated trying to use them results in for instance the error javalangruntimeexception unknown animator name translateas such it becomes necessary to use androids objectanimator however it does not accept fractional values of the associated dimension of itself or its parent width for translationx for example as the old view animations did in the form 75pconstructing the objectanimator manually at runtime by programmatically fetching the size of the fragment is not feasible because the fragmenttransaction only accepts declarative animations specified by a residmy goal is to translate offscreen a fragment that is filling up an entire activity i am basically doing a shift transition between two fragments this is the existing translationanimation implementation slide in rightxml which along with its counterpart slide out leftxml is for some reason not exposed in androidranim and i therefore have to duplicate them in my codebaseset xmlnsandroidtranslate androidfromxdelta100p androidtoxdelta0 androiddurationandroidintegerconfig mediumanimtimesetmy api level is set to 14thanks,['android'] +298466,which windows service ensures network connectivity i am doing a windows service that must have network connectivity when it starts code is in c and i set the service dependent from others withserviceinstallerservicesdependedon new string tcpip i can see dependency correctly entered on windows service manager but after reboot my service fails to start because it cannot connect to network after host gets an ip the service starts correctlyi tried with tcpip and dhcp services which service should it depend onservice needs network connectivity since its purpose is to mount a unit through sshthanks,['c#'] +298482,two after pseudoelements possible duplicateadding pseudoelements after pseudoelements i would like to apply two css after pseudoelements to a single dom element each with a different colour yes i could wrap the dom element in another dom element and give each one and after pseudoelement but my preference is cleaner htmli doubt it is possible but wonder if someone can tell me betteri especially doubt the possibility of chaining after pseudoelements together so that one after pertains to another which pertains to a dom element but if anyone knows how to make that happen please do tell,['css'] +298484,wpf datagrid comexception on using includeheader clipboardcopymode in my wpf app i am using a datagrid control in the control definition i defined clipboardcopymode property as includeheaderdatagrid namedatagrid clipboardcopymodeincludeheaderdatagridat times when i try to copy any data from grid i am encountering hresult clipboard crash error systemruntimeinteropservicescomexception 0x800401d0 openclipboard failed exception from hresult 0x800401d0 clipbrd e cant openany suggestions to resolve it i looked at other posts mostly they are about how to handle this scenario when you explicitly use the clipboard related methods but none related to datagrid,['.net'] +298491,line numbers every nth line with css counters this is my first post here and i hope it flies apologize for the length i had to cut out certain referring links italicized as i do not have enough reputation yet but can perhaps replace them lateri have created a jquery plugin that thisplays incremented line numbers for poetry and drama the lines of a poem are represented as the children of an ordered list olverse when javascript is enabled the plugin generates line numbers every nth interval based on a minimum of inline list values these numbers can then be manipulated through the dom when js is thisabled numeric list markers every fifth line kick in as fallback line numbers i wonder now whether it is possible to get the plugged poem to degrade as a list powered by css counters ie 67 get served plain ordered lists with the trailing periods of the numerals but superior browsers should get counters or the numbers generated by the plugin heres the catch the css counter rules should be able to accommodate situations where the line numbering and the childindexing of the poem list do not sync i have seen a number of posts on formatting counters and skipping children as well as the right and wrong ways of formatting poems semantically and typographically the w3c proposals recommending paragraph and pre tags are questionable at best i have come up empty however on the problem of using counters to do incremented line numbers so i am sharing my own efforts towards a solution and hope you guys can help me towards a better onethe base rules i have been experimenting with limited successolverse counterreset line 0olverse li thisplay block olverse libefore counterincrement line content counterline hide lines or more precisely children that are not a multiple of 5 olverse linotnthchild5nbefore visibility hiddenas you can see from this fiddle these rules thisplay numbers every 5th line so long as every list child is to be counted as a line of the poem and so long as the passage begins from line 1 6 11 16 etc ie the counterreset is 0 or a multiple of 5 that last rule may be of interest to those wanting to do incremented line numbers for some simpler task a simple poem for a blog entry eg but these conditions are too restrictive for our needs a teistructured repository of critical editions of poetrydrama onlineproblem 1 when i have several excerpts or divisions of one or more works whose counterresets are nonmultiples of the default increment i have to reference the excerpts by id and offset the hiding rule for each idd olverse by the remainder for example an excerpt beginning from line 43 requires adjusting the counterreset to 42 and adjusting the nthchild parameter of the hiding rule to 5n3 since 42 5 3 suddenly counters become less appealing than numbering list values by hand this at least is better thanproblem 2 getting the browser to uncount certain lines such as subheadings or stage directions that may be embedded within the poem to these lines i have tried attaching a nocount class and turning off the thisplay property or the visibility property egolverse linocountbefore thisplay none orolverse linocountbefore visibility hiddenin combination with the rule hiding lines that are nonmultiples of the increment neither gives the desired results see this fiddle the first triggers incorrect line numbering on the right numbers the latter correct numbering on the wrong ones is there any way to write css counter rules that would work whether or not the automated line numbers correspond with the correct child indexes perhaps there is some other combination of css selectors that will do the job,['css'] +298499,asp mvc file upload httppostedfilebase is null in my controller i have because i wanted to be able to fill out some details about the video and actually upload it the video class does not need the actual video because it is going to be passed to another web servicepublic class videouploadmodel public httppostedfilebase vid get set public video videomodel get set post videocreate httppost public actionresult createvideouploadmodel vm if modelstateisvalid dbvideosaddobjectvmvideomodel dbsavechanges return redirecttoactionindex viewbaguserid new selectlistdbdbusers id fname vmvideomodeluserid return viewvm and in my view i havemodel lifehighlightsshoelacecontrollersvideocontrollervideouploadmodel viewbagtitle createh2createh2script srcurlcontentscriptsjqueryvalidateminjs typetextjavascriptscriptusing htmlbeginformcreate video formmethodpost new enctype multipartformdata htmlvalidationsummarytruefieldset legendvideolegend div classeditorlabel htmllabelformodel modelvideomodelkalturaid div div classeditorfield htmleditorformodel modelvideomodelkalturaid htmlvalidationmessageformodel modelvideomodelkalturaid div div classeditorlabel htmllabelformodel modelvideomodelsize div div classeditorfield htmleditorformodel modelvideomodelsize htmlvalidationmessageformodel modelvideomodelsize div div classeditorlabel htmllabelformodel modelvideomodeldate div div classeditorfield htmleditorformodel modelvideomodeldate htmlvalidationmessageformodel modelvideomodeldate div div classeditorlabel htmllabelformodel modelvideomodeluploadedby div div classeditorfield htmleditorformodel modelvideomodeluploadedby htmlvalidationmessageformodel modelvideomodeluploadedby div div classeditorlabel htmllabelformodel modelvideomodeluserid user div div classeditorfield htmldropdownlistuserid stringempty htmlvalidationmessageformodel modelvideomodeluserid div div classeditorfield input namemodelvid typefile div p input typesubmit valuecreate pfieldsetwhen i submit the form the videomodel part of vm is filled out but vid the actual file is nullany ideas,['c#'] +298529,python name space issues with ipython parallel i am starting to experiment with the ipython parallel tools and have an issue i start up my python engines withipcluster start n 3then the following code runs finefrom ipythonparallel import clientdef dopx rc client dview rc dviewblocktrue dviewexecutea 5 dviewb 10 ack dviewapplylambda x abx x return ackack dop27print ackreturns 42 42 42 as it should but if i break the code into different filesdoppyfrom ipythonparallel import clientdef dopx rc client dview rc dviewblocktrue dviewexecutea 5 dviewb 10 print dviewa ack dviewapplylambda x abx x return ackand try the followingfrom dop import dopack dop27print acki get errors from each engine0apply nameerror global name a is not defined1apply nameerror global name a is not defined2apply nameerror global name a is not definedi do not get itwhy cannot i put the function in a different file and import it,['python'] +298539,javascript encodeuricomponent and converting spaces to symbols i would like to encode my url but i want to convert spaces to plus symbolsthis is what i attempted to dovar search testing this here encodeuricomponentsearchreplace githe output from that is testing2bthis2bhere2b26 but what i would like it to be is testingthishere26 i tried replacing the space with 20 to convert it into a plus symbol but that did not seem to work can anyone tell me what it is i am doing wrong here,['javascript'] +298550,the run as android application is no longer an option in my eclipse run configuration i am running eclipse 372 on a win7 machine i have the android sdk and avd all was working well i have an android app project that i have run under the emulator on an avd and on a real android device adb worked fine as well at some point i grabbed sdk android 403 then i had to upgrade a few more things that i cannot remember perhaps my avd but ever since this upgrade there is no option to run my package as an android application anymore if i choose run it throws up a menu asking me to select a way to run it and android application is not a choice it has to be java app etc if i open run configurations there is no android application in my left columnmy sdk manager still lists android 40 and android 403 as installed my avd manager still let us me launch an android virtual device and even create a new one but eclipse does not let me run my package as an android application,['android'] +298580,learning c for objectivec i am relatively proficient in objectivec but i have been looking around some frameworks and libraries i might use in the future and i am increasingly seeing the use of c so far the only applications i have written contain only objectivec i know objectivec is a superset of c but what i mean when i say that i have only written in objectivec is that i have only used objectivec methods and the syntax of objectivec that is thistinctly different from c syntax i have been going through questions related to the relationship between c and objectivec see links below and i want to start learning c but apparently there are three types of c kr c89 and c99 and i am wondering which type i should learn to help me with objectivec i know from learning objectivec i unknowingly learned c too but i want to understand the ins and outs of c more and become familiar with its functions syntax features etc also is objectivec based off of any one of the three types of c,"['objective-c', 'c']" +298583,basic c pointer i am a beginner in c and have been trying to figure out what has gone wrong with my code code for the past hour or two i have been following through krs book and i keep looking through it but still do not understand my logic mistake while argv0 while argv0 printfcnargv argv argvtaskprint out all the arguments being fed to my program using argvto my understanding argv is a pointer to an array that contains further pointers to arrays of character pointers so i said that while argv0 or while the first array still has elements we should follow the pointers from the first array to the next array then we should print out all the elements in the next array,['c'] +298585,why use junit for testing maybe my question is a newbie one but i can not really understand the circumstances under which i would use junitwhether i write simple applications or larger ones i test them with the systemout statements and it seams quite easy to me why create testclasses with junit unnecessary folders in the project if we still have to call the same methods check what they return and we then have an overhead of annotating everything why not write a class and test it at once with systemout but not create testclassesps i have never worked on large projects i am just learning so what is the purpose,['java'] +298628,is it better to use heap or stack variables i had a thiscussion with a friend some time ago he is an experienced c user and i am not an experienced c user he told me that i should strive for using heap variables iea obj new as opposed toa objaaside from all that stuff about using pointers being nice and flexible he said it is better to put things in heap rather than stack something about stack is smaller than heap is it true if so whyedit i made a typo in saying my friend advised stack variables he was recommending heap variablesedit2 i know about issues with lifetime let us assume i have managed the lifetime of these variables appropriately ie the only criteria of concern is heap vs stack storage with no lifetime concern,['c++'] +298657,how to create user for a db in postgresql i have installed postgresql 84 on my centos server and connected to root user from shell and accessing the postgresql shelli created the database and user in postgresqlwhile trying to connect from my php script it shows me authentication failedhow do i create a new user and how to grant permissions to them for a particular db,['php'] +298659,add and remove the bootstrap typeahead dynamically can we add and remove the bootstrap typeahead dynamicallymeans in some case i need to give the typeahaed functionality to one textbox and need to remove this functionality for the same input box in another case,['jquery'] +298666,how do i properly use ccspriteframecache and ccspritebatchnode i do not understand what i do exactly when i add a ccspriteframecache or ccspritebatchnode to my cocos2d application can somebody please explain the following points it would be helpful if you could explain a few please write the corresponding letter in front of your answer according to which question you are answeringall questions imply the achievement of best performance and lowest memoryusea is it crucial to create spritesheets for every single layer for example menu own spritesheet gamelayer own spritesheetb can somebody explain why i have to add sprites to the batch node and what a batch node generally is b1so why cannot i just do something like ccspriteframecache sharedspriteframecache addspriteframeswithfilemenuspritesplist ccspritebatchnode spritesheet ccspritebatchnode batchnodewithfilemenuspritespng self addchildspritesheetand then just add sprites to my layer by calling ccsprite mysprite ccsprite spritewithspriteframename self addchildmyspritewithout adding them to the batch node because from what i understand it works like this i add my spritesheet with all the sprites on it to the screen my app then goes into the plist and looks for the coordinates of the sprite i want to thisplay and then places it on the screen so why should i call spritesheet addchildmyspritec how do i then get rid of the spritesheet for memory purposes when i do not need it anymore,['objective-c'] +298674,how to iterate over a 2d array with a single loop how can we navigate through the two dimensional array without using nested loopsie by using only one loop string arnew string 34,['java'] +298716,maven generate jar and war i have a cxf ws project that i would use it in another project i would consume this ws in a web project but i do not know how to generate jar fileplease have you any idea or an examplethank you,['java'] +298718,is it better to use jquery fadein or css3 animations i am creating a simple gallery using some php and javascript and am trying to do a fade transition between images then i wondered if there is a performance difference between using a css animation egwebkitkeyframes fadein 0 opacity 0 100 opacity 1 and a jquery fadein i would like to use the callback from the fadein but i also can just use a timer with the css i guessare either of these likely to work better with large images i cannot see a difference but wondered if it might affect slower computers,"['javascript', 'jquery']" +298723,building actionmode with custom layout in actionbarsherlock i just starting using actionbarsherlock for building some simple appin my first screen i have simple list and i added new menu item for adding new item to the listmenuitem newitem menuaddnewnewitemseticonrdrawableic compose inverse setshowasactionmenuitemshow as action if roomnow when user choose to add a new item i want to start a new action mode for adding new item this action mode should contain a simple layout with text box and a button so i created this layoutlinearlayout xmlnsandroid androidlayout widthfill parent androidlayout heightwrap content androidorientationhorizontal edittext androidididtext androidlayout width0dp androidlayout heightwrap content androidlayout weight1 androidinputtypetext edittext button androidididaddbtn androidlayout widthwrap content androidlayout heightwrap content androidtextstringadd linearlayoutso now i just need to set this layout to the bar in the new action modenewitemsetonmenuitemclicklistenernew onmenuitemclicklistener override public boolean onmenuitemclickmenuitem item actionmode startactionmodenew myactionlisteditorthis return true and in my actionprivate final class myaction implements actionmodecallback override public boolean oncreateactionmodeactionmode mode menu menu view customnav layoutinflaterfromcontextinflaterlayoutadd item null getsupportactionbarsetcustomviewcustomnav getsupportactionbarsetthisplayshowcustomenabledtrue return true so basically i need something between actionmodes and customnavigation from the sherlock example but the problem is that it set the layout to the main bar and not for the new bar that open in for actionany suggestions,['android'] +298734,getting the sh name member in a section header elf file i am trying to get the correct offset to the section name by accessing the sh name member of an elf file but it keep giving me zero or nulli am supposed to only use mmap and the elfh no helper functionsso i did void map start mmap0 fd statst size prot read prot write map shared fd 0header elf32 ehdr map start secoff headere shoff section elf32 shdr map start secoff but when i doprintfname offset dn sectionsh nameit keeps giving me 0what am i doing wrong,['c'] +298746,how to convert gettext mo file into po file is there any way to convert a mo file into a po file source when the po file is no longer available i need to edit the content of a mo file but i do not have the po file is it possible,['python'] +298758,create a lock screen of my own i want to create a lock screen for androidcan anyone provide some tutorials or guides to how to do thati tried in google but i end up in locking softwares not sample code,['android'] +298772,rails association nil in after initialize i have two models with a one to many association i want to set a default value on the child model at initialization based on some state of the parent this involves having an after initialize callback fire on the child that needs to access the parent through the belongs to association the problem is that when i instantiate the child using the build method the association to the parent is nil in the after initialize callback is this expected behaviour i am on rails 306a toy exampleclass merchant activerecordbase has many productsendclass product activerecordbase belongs to merchant after initialize set default value def set default value if merchantstate selffoo some value else selffoo some other value end endendand in a controllerproduct merchantproductsbuildin the call to set default value merchant is nil though it seems that it should not be,['ruby-on-rails'] +298785,ios get pixelbypixel data from camera i am aware of avfoundation and its capture support not too familiar though however i do not see any readilyaccessible api to get pixelbypixel data rgbperpixel or similar i do recall reading in the docs that this is possible but i do not really see how socan this be done if so howwould i be getting raw image data or data that is been jpegcompressed,"['iphone', 'ios']" +298826,loading jquery underscore and backbone using requirejs 201 and shim i am experimenting a little bit with requirejs 201 my goal is to load correctly jquery underscore and backbone from the original requirejs doc i thiscovered that the author j burke added to this new release a new config option called shimthen i wrote this stuff down hereindexhtmldoctype htmlhtml head titletesting timetitle script datamainscriptsmain srcscriptsrequirejsscript head body h1testing timeh1 bodyhtmlscriptsmainjsrequirejsconfig shim libsjquery exports libsunderscore exports libsbackbone deps libsunderscore libsjquery exports backbone define libsjquery libsunderscore libsbackbone function jquerylocal underscorelocal backbonelocal consoleloglocal jquerylocal consoleloglocal underscorelocal consoleloglocal backbonelocal consolelogglobal consolelogglobal consolelogglobal backbone everything seems to work quite fine but i have the feeling that i am missing something i know that there are amded version of jquery and underscore but if the setup is so simple i do not understand why i should use themso is this setup right or i am missing something,['javascript'] +298830,heroku push rejected failed to install gems via bundler i have tried to push an app to heroku in the same way i have always done i am using ruby 192 and rails 321 however now i am getting this error message i did what it recommendsmake sure that gem install sqlite3 v 135 succeeds before bundlingnote it is doing this even though i did in my gemfilegroup development test do gem sqlite3endgroup production do gem pgendbut doing gem install sqlite3 v 135 in the terminal but the push is still being rejected i am not sure how to check the gem files it refers to in the tmp directory but even if i did i wouldnt understand themany suggestionsgem files will remain installed in tmpbuild 1timyd7o5k59lvendorbundleruby191gemssqlite3135 for inspection results logged to tmpbuild 1timyd7o5k59lvendorbundleruby191gemssqlite3135extsqlite3gem makeout an error occurred while installing sqlite3 135 and bundler cannot continue make sure that gem install sqlite3 v 135 succeeds before bundling failed to install gems via bundler heroku push rejected failed to compile rubyrails app,['ruby-on-rails'] +298832,how do i drag a jquery slider handle from within capybara and chromedriver i am able to execute the following code to move the slider handle but the events triggered in the browser are not taking place pageexecute scriptqslider handicapslidervalues130that correctly sets the right handle to 30 but i need it to behave as if i were actually taking the mouse and dragging the handle to 30 then releasing,['jquery'] +298844,nhibernate error dehydrating property what the heck is this i am doing a fairly complex nhibernate transaction in a financial system creating a payment recording the ledger entries checking to see if the payment is the total amount of an invoice if so marking the invoice as paid in full etc lots of fun stuff naturally it has to happen inside a single transactionwhen i try to commit the change to the session i get the following errorerror dehydrating property value for c3datamodelcfaptransactionvendorgoogling this did not turn up many record can someone tell me what this means and where i need to focus my debugging effortsupdateper request here is the full error messagenhibernatepropertyvalueexception error dehydrating property v alue for c3datamodelcfaptransactionvendor nhibernatehibernateexception unable to resolve property apvendorid at nhibernatetupleentityentitymetamodelgetpropertyindexstring propertyname at nhibernatetupleentityabstractentitytuplizergetpropertyvalueobject entity string propertypath at nhibernatepersisterentityabstractentitypersistergetpropertyvalueobject obj string propertyname entitymode entitymode at nhibernatetypeentitytypegetidentifierobject value isessionimplementor session at nhibernatetypemanytoonetypenullsafesetidbcommand st object value int32 index boolean settable isessionimplementor session at nhibernatepersisterentityabstractentitypersisterdehydrateobject id object fields object rowid boolean includeproperty boolean includecolumns int32 table idbcommand statement isessionimplementor session int32 index end of inner exception stack trace at nhibernatepersisterentityabstractentitypersisterdehydrateobject id object fields object rowid boolean includeproperty boolean includecolumns int32 table idbcommand statement isessionimplementor session int32 index at nhibernatepersisterentityabstractentitypersisterinsertobject id object fields boolean notnull int32 j sqlcommandinfo sql object obj isessionimplementor session at nhibernatepersisterentityabstractentitypersisterinsertobject id object fields object obj isessionimplementor session at nhibernateactionentityinsertactionexecute at nhibernateengineactionqueueexecuteiexecutable executable at nhibernateengineactionqueueexecuteactionsilist list at nhibernateengineactionqueueexecuteactions at nhibernateeventdefaultabstractflushingeventlistenerperformexecutionsieventsource session at nhibernateeventdefaultdefaultflusheventlisteneronflushflushevent event at nhibernateimplsessionimplflush at nhibernatetransactionadotransactioncommit at c3datamodelrepositoriesnhunitofworksave in cprojectsc3c3datamodelgeneratedgeneratednhibernaterepositoriesgeneratedcsline 2659 at c3webuiareasfinancecontrollersaccountspayablecontrollercreatepaymentcreatepaymentmodel model in cprojectsc3c3webuiareasfinancecontrollersaccountspayablecontrollercsline 434updatethrowing nhibernate into debug mode i get a bunch of stuff like thisprocessing cascade nhibernateenginecascadingactionsaveupdatecascadingaction for c3datamodelapvendor cascade nhibernateenginecascadingactionsaveupdatecascadingaction for collection c3datamodelapvendortransactions done cascade nhibernateenginecascadingactionsaveupdatecascadingaction for collection c3datamodelapvendortransactions done processing cascade nhibernateenginecascadingactionsaveupdatecascadingaction for c3datamodelapvendor nhibernateeventdefaultabstractflushingeventlistener error could not synchronize database state with session nhibernatepropertyvalueexception error dehydrating property value for c3datamodelcfaptransactionvendor nhibernatehibernateexception unable to resolve property apvendorid at nhibernatetupleentityentitymetamodelgetpropertyindexstring propertyname at nhibernatetupleentityabstractentitytuplizergetpropertyvalueobject entity string propertypath at nhibernatepersisterentityabstractentitypersistergetpropertyvalueobject obj string propertyname entitymode entitymode at nhibernatetypeentitytypegetidentifierobject value isessionimplementor session at nhibernatetypemanytoonetypenullsafesetidbcommand st object value int32 index boolean settable isessionimplementor session at nhibernatepersisterentityabstractentitypersisterdehydrateobject id object fields object rowid boolean includeproperty boolean includecolumns int32 table idbcommand statement isessionimplementor session int32 index end of inner exception stack trace at nhibernatepersisterentityabstractentitypersisterdehydrateobject id object fields object rowid boolean includeproperty boolean includecolumns int32 table idbcommand statement isessionimplementor session int32 index at nhibernatepersisterentityabstractentitypersisterinsertobject id object fields boolean notnull int32 j sqlcommandinfo sql object obj isessionimplementor session at nhibernatepersisterentityabstractentitypersisterinsertobject id object fields object obj isessionimplementor session at nhibernateactionentityinsertactionexecute at nhibernateengineactionqueueexecuteiexecutable executable at nhibernateengineactionqueueexecuteactionsilist list at nhibernateengineactionqueueexecuteactions at nhibernateeventdefaultabstractflushingeventlistenerperformexecutionsieventsource session c3webuiareasfinancecontrollersaccountspayablecontroller error c3webuiareasfinancecontrollersaccountspayablecontroller no additional information nhibernatepropertyvalueexception error dehydrating property value for c3datamodelcfaptransactionvendor nhibernatehibernateexception unable to resolve property apvendorid at nhibernatetupleentityentitymetamodelgetpropertyindexstring propertyname at nhibernatetupleentityabstractentitytuplizergetpropertyvalueobject entity string propertypath at nhibernatepersisterentityabstractentitypersistergetpropertyvalueobject obj string propertyname entitymode entitymode at nhibernatetypeentitytypegetidentifierobject value isessionimplementor session at nhibernatetypemanytoonetypenullsafesetidbcommand st object value int32 index boolean settable isessionimplementor session at nhibernatepersisterentityabstractentitypersisterdehydrateobject id object fields object rowid boolean includeproperty boolean includecolumns int32 table idbcommand statement isessionimplementor session int32 index end of inner exception stack trace at nhibernatepersisterentityabstractentitypersisterdehydrateobject id object fields object rowid boolean includeproperty boolean includecolumns int32 table idbcommand statement isessionimplementor session int32 index at nhibernatepersisterentityabstractentitypersisterinsertobject id object fields boolean notnull int32 j sqlcommandinfo sql object obj isessionimplementor session at nhibernatepersisterentityabstractentitypersisterinsertobject id object fields object obj isessionimplementor session at nhibernateactionentityinsertactionexecute at nhibernateengineactionqueueexecuteiexecutable executable at nhibernateengineactionqueueexecuteactionsilist list at nhibernateengineactionqueueexecuteactions at nhibernateeventdefaultabstractflushingeventlistenerperformexecutionsieventsource session at nhibernateeventdefaultdefaultflusheventlisteneronflushflushevent event at nhibernateimplsessionimplflush at nhibernatetransactionadotransactioncommit at c3datamodelrepositoriesnhunitofworksave in cprojectsc3c3datamodelgeneratedgeneratednhibernaterepositoriesgeneratedcsline 2659 at c3webuiareasfinancecontrollersaccountspayablecontrollercreatepaymentcreatepaymentmodel model in cprojectsc3c3webuiareasfinancecontrollersaccountspayablecontrollercsline 434it does not appear this is occurring when querying the database i have a feeling it has problems with me creating a bunch of objects relating them and then trying to persist them but that is a pure guess,['c#'] +298864,installing windowbuilder on eclipse 42 i am using eclipse juno 42 downloaded from hereon previous installs i have been using 37 and i have been using windowbuilder which i find very useful i noticed it was not included this time so i used this update site provided on this page the zip file download gives a file unavailable errorhowever when i run the install it rapidly climbs to 28 then freezes after half an hour i get a very long error whose message starts with this textan error occurred while collecting items to be installed sessioncontext wasprofileepackagejava phaseorgeclipseequinoxinternalp2enginephasescollect operand actionmultiple problems occurred while downloading unable to read repository at 150r42x201205291332jarpackgzfull textdoes anyone know how i can go about installing it,['java'] +298867,sending large file with httpwebrequest growingshrinking buffer as needed i am writing an application that uploads large files to a web service using httpwebrequestthis application will be run by various people with various internet speedsi asynchronously read the file in chunks and asynchronously write those chunks to the request stream i do this in a loop using callbacks and i keep doing this until the whole file has been sentthe speed of the upload is calculated between writes and the gui is subsequently updated to show said speedthe issue i am facing is deciding on a buffer size if i make it too large users with slow connections will not see frequent updates to the speed if i make it too small users with fast connections will end up hammering the readwrite methods causing cpu usage to spikewhat i am doing now is starting the buffer off at 128kb and then every 10 writes i check the average write speed of those 10 writes and if it is under a second i increase the buffer size by 128kb i also shrink the buffer in a similar fashion if the write speed drops below 5 secondsthis works quite well but it all feels very arbitrary and it seems like there is room for improvement my question is has anybody dealt with a similar situation and what course of action did you takethanks,['c#'] +298885,how to center a nstextfield in a view i have a nstextfield label centered with ib in a view with the text drag and drop your media here in my controller a use nslocalizedstring to translate the text englishlprojlocalizablestrings drag and drop your media here drag drop your media herefrenchlprojlocalizablestrings drag and drop your media here daposer vos madia icionly the initial text drag and drop your media here is centerred in the view the translated text is not centerrd depending on is lenght all the translated text start at the same absciss x than the orignal text how can i fix this issue ps i do not want to play with setframe height width just for a simple point like this i guess there is another method to do thisthanks,['objective-c'] +298886,understanding global variable in python i came across a strange issue in python when using global variablesi have two modulesfilesmod1py and mod2pymod1 tries to modify the global variable var defined in mod2 but the var in mod2 and var in mod seems to be two different things thus the result shows that such modification does not workhere is the codecode for mod2pyglobal var var 1 def fun of mod2 print varcode for mod1pyfrom mod2 import varfun of mod2 global var commenting out this line yields the same resultvar 2 i want to modify the value of var defined in mod2fun of mod2 but it prints 1 instead of 2 modification failed any hint on why this happens and how can i modify the value of val defined in mod2 in mod1thanks,['python'] +298892,align html input fields by i have a html form like html nameinput typetextbr email addressinput typetextbr description of the input valueinput typetextbr htmlnow the labels all begin in the same column but the text boxes are beginning in different positions as per the labels text lengthis there a way to align the input fields such that all the and the text boxes will begin in the same position and the preceding text will be right aligned until the i am okay with using css if that can help achieving this,"['html', 'css']" +298893,whats ie take on htmldocument and htmlelement within javascripts scope referring to htmldocument or htmlelement raises error on ie8the error i get is htmlelement is undefinedwhat is the way to have js interacting with native dom object of this browser,"['javascript', 'html']" +298920,how do i prevent resize on ipad i have a web app running on safari on an ipad i am starting the app from the ipad home page i want the app to start in fullscreen mode and to continue running in fullscreen mode ie not showing the safari address bari want to prevent the pinchtozoom and panzoom functions so the page always remains static how do i do this,['ios'] +298922,problems with references to tpl dataflow and tpl in vs 2012 rc i just upgraded visual studio 11 beta to the new visual studio 2012 rc and have problems referencing tpl dataflowfirst i tried to reference dataflow as i did previously by adding a reference from the framework but when i try to do that i get an error boxa reference to systemthreadingtasksdataflow could not be addedand then the whole visual studio freezesafter reading mef and tpl dataflow nuget packages for net framework 45 rc i assumed the version of dataflow that showed in the references list was some kind of artifact of the previous installation so i tried using dataflow from nuget which seemed to work until i actually tried to compile my code because i got an errorthe type systemthreadingtaskstask is defined in an assembly that is not referenced you must add a reference to assembly systemthreadingtasks version40 cultureneutral publickeytokenb03f5f7f11d50a3athis is confusing because task is in mscorlib no other references should be necessary but there is a reference assembly called systemthreadingtasks in the references list so i tried to add that unfortunately a familiar error showeda reference to systemthreadingtasks could not be addedand then visual studio froze againam i doing something wrong how can i use tpl dataflow with vs 2012 rc,['.net'] +298925,best practices for enum in c enums in c have one major problem you cannot have one name in two different enums like thisenum browser none 0 chrome 1 firefox 2enum os none 0 xp 1 windows7 2so what is the best way to handle this issue in this example,['c++'] +298927,how to play videos from sd card i was creating a simple app which stream videos from net and i made it but now i want to change the code so that i can play video files from my sdcardoriginal codeuri vidfile uriparsemy site herevideoview videoview videoview findviewbyidridvideoviewvideoviewsetvideourividfilevideoviewsetmediacontrollernew mediacontrollerthisvideoviewstartso please help me with changing the code so that it can play videos from my mobile memory card,['android'] +298943,read all sms from a particular sender how do i read all smses from a particular sender to me eg i want to scan a the body and b the datetime of all smses that came from tmmyamex to the phonesome websites seem to indicate this can be read from contentsmsinbox i could not figure out exactly how also not sure if it is supported on most phones i am using a galaxy s2,['android'] +298948,write the output of a remote io audio unit to a file offline i have a program that generates sound using an ausampler connected to a remote io audio unit the ausampler is controlled by prerecorded events that are triggered in a timed loop i want to write the resulting sound to a filethere are some other questions on writing to a file in the render callback of the io unitrecording to aac from remoteio data is getting written but file unplayablehow to write output of augraph to a filerecording from remoteio resulting caf is pitch shifted slower thistortedwrite audio to thisk from io unitbut these all deal with writing the data in real time is there a way to offline render the file in less time it takes than to play it,['ios'] +298960,what is the proper way to upload a file using cuploadedfile i am following the tutorial for uploading a file i have written the following code menuitemattributes postmenuitemsmenuitemclientid yiiappuserclientidmenuitemimage cuploadedfilegetinstancemenuitem imageifmenuitemsave menuitemimagesaveas yiiappgetbasepathmenuitemimagegetname but the problem is that if a file with the same name exists on the same directory the files is neither overwritten or saved with a different namewhat i want is the new image say imagejpg if a file of the same name exists to be renamed to image 1jpgis it possible please reply,['php'] +298963,the import javaxjnlp cannot be resolved i am learning java and trying to run some examples using java web starthowever i cannot seem to find that package javaxjnlpthis same error is haunting me on both windows and linuxi have installed oracle jdk 7 on windowsopenjdk 16 is the version installed on linuxsearching the internet for the package with no luckit is no longer available on oracles website because they insist that the package is a part of the jdki have searched the installation directories for itsome claim it is in the jnlpjar file others claim in javawsjar fileneither files are part of my installation,['java'] +298974,pass a function as an explicit template parameter in the code example below the call to foo works while the call to bar failsif i comment out the call to bar the code compiles which tells me the definition of bar itself is fine so how would bar be called correctlyinclude iostreamusing namespace stdint multiplyint x int y return x ytemplate class fvoid fooint x int y f f cout fx y endltemplate class fvoid barint x int y cout fx y endlint main foo3 4 multiply works barmultiply3 4 fails return 0,['c++'] +298989,javascript logical operator i am getting back into web development and have been trying to go over the nuances of jscript recently i was pouring through the source of the threex extension library built on top of threejs and noticed this functionthreexkeyboardstateprototypepressed functionkeydesc var keys keydescsplit forvar i 0 i keyslength i var key keysi var pressed if threexkeyboardstatemodifiersindexof key 1 pressed thismodifierskey else if objectkeysthreexkeyboardstatealiasindexof key 1 pressed thiskeycodes threexkeyboardstatealiaskey else pressed thiskeycodeskeytouppercasecharcodeat0 if pressed return false return truei am looking in particular at the line hereif threexkeyboardstatemodifiersindexof key 1 i am not familiar with this operator i checked w3schools and their logical operators list does not have this one included i am not sure if this is misspelled and the browsers simply count it as or if it has some other meaning also i was wondering whether this is actually a single logical operator or whether it is some kind of combination like,['javascript'] +298995,nsuserdefaultsdidchangenotification whats the name of the key that changed this code will call the method defaultschanged when some value in userdefaults changednsnotificationcenter center nsnotificationcenter defaultcentercenter addobserverself selectorselectordefaultschanged namensuserdefaultsdidchangenotification objectnilthis code will give me the value that changed voiddefaultschangednsnotification notification get the user defaults nsuserdefaults defaults nsuserdefaults notification object do something with it nslog defaults objectforkeynameofthingiaminterestedinbut how can i get the name of the key that changed,"['objective-c', 'ios']" +299002,pros and cons of using storyboards i am planning to learn to develop applications using story boards can anyone please post some advantages and thisadvantages while using storyboards,['iphone'] +299045,rails delayed job where is the correct place to store custom job classes i am new to delayed job and i am starting to write my own custom jobs each custom job is basically just a regular ruby class but i am not sure where these custom job classes are normally stored within the projects directory structurei am thinking lib but lib seems to be a junk drawer at this point maybe that is ok thoughthanks,"['ruby-on-rails', 'ruby']" +299047,in javausing switch statement with a range of value in each case in java is it possible to write a switch statement where each case contains more than one value for example though clearly the following code would not workswitch num case 1 5 systemoutprintlntesting case 1 to 5 break case 6 10 systemoutprintlntesting case 6 to 10 breaki think this can be done in objective c are there a similar thing in java or should i just use if else if statements instead,['java'] +299050,what is the proper way to trigger a touch event on the ipad with jquery i have tried the following myviewer is a divmyviewerclick andmyviewertriggertouchstart andmyviewertriggerclickall work on a computer but not an ipad what am i doing wronghere is what the body of the html page looks likebody div classmyviewer onclickwindowopenmypdffilepdfprogrammatically clickeddivbodyand to round this out here is my jquery codedocumentreadyfunction var ismobile android function return navigatoruseragentmatchandroidi true false blackberry function return navigatoruseragentmatchblackberryi true false ios function return navigatoruseragentmatchiphoneipadipodi true false windows function return navigatoruseragentmatchiemobilei true false any function return ismobileandroid ismobileblackberry ismobileios ismobilewindows ifismobileany myviewerclck this does works on computers but not on ipadelse var markup object datamypdffilepdftoolbar1ampnavpanes1ampscrollbar0amppage1ampviewfith typeapplicationpdf width100 height100 object myviewerappendmarkup,['jquery'] +299051,robustly find and circles with the same diameter alternative to bruteforcing hough transform threshold i am developing application to track small animals in petri thishes or other circular containersbefore any tracking takes place the first few frames are used to define areaseach thish will match an circular independent static area ie will not be updated during trackingthe user can request the program to try to find thishes from the original image and use them as areashere are examplesin order to perform this task i am using hough circle transform but in practice different users will have very different settings and images and i do not want to ask the user to manually define the parametersi cannot just guess all the parameters eitherhowever i have got additional informations that i would like to usei know the exact number of circles to be detectedall the circles have the almost same dimensionsthe circles cannot overlapi have a rough idea of the minimal and maximal size of the circlesthe circles must be entirely in the picturei can therefore narrow down the number of parameters to define to one the thresholdusing these informations and considering that i have got and circles to find my current solution is totest many values of threshold and keep the circles between which the standard deviation is the smallest since all the circles should have a similar sizeat this point minrad and maxrad were calculated from the size of the image and the number of circles to findassuming circles should altogether fill more than 13 of the images but cannot be altogether larger than the imagen is the integer number of circles to findimg is the picture of the scene filteredthe vectors containing the detected circles and the so far best circles foundstdvectorcvvec3f circles bestcirclesthe score of the so far best set of circlesdouble bestssem 0 forint t5 t400 tt2apply hough circles with the threshold t cvhoughcirclesimg circles cv hough gradient 3 minrad2 t3 minrad maxrad ifcirclessize ncall a routine to give a score to this set of circles according to the similarity of their radii double ssem scoresetofcirclescirclesnif no circles are recorded yet or if the score of this set of circles is higher than the former best if bestcirclessize and ssem bestssemthis set become the temporary best set of circles bestcirclescircles bestssemssem with the methods to assess how good is a set of circle the more similar the circles are the higher is ssem double scoresetofcirclesstdvectorcvvec3f circles int n double ssem0 sum 0 double mean forunsigned int j0jnj sum sum circlesj2 mean sumn forunsigned int j0jnj double em mean circlesj2 ssem 1ssem emem return ssemi have reached a higher accuracy by performing a second pass in which i repeated this algorithm narrowing the minradmaxrad interval using the result of the first passfor instance minrad2 095 average radius of best circles and maxrad2 105 average radius of best circlesi had fairly good results using this method so far however it is slow and rather dirtymy questions arecan you thing of any alternative algorithm to solve this problem in a cleanerfaster manner or what would you suggest to improve this algorithmdo you think i should investigate generalised hough transform thank you for your answers and suggestions,['c++'] +299105,firefox invokes settimeout function too soon or dategettime is off i have run into a strange issue in firefox 12 settimeout does not seem to always wait the appropriate length or perhaps it is the dates milliseconds that do not jivecheck out this fiddle essentially a settimeout of 100ms seems to run anywhere between 80ms and 110ms more i can understand based on john resigs explanation of timers but lessyou may have to refresh it once or twice to see the issue as it sometimes works correctly on the first run it seems to work spifftacular in ie and chromeheres the code i am using in my fiddlevar txt timeout length 100 nownow datenow function return new dategettime function logtime c time 100 classerror logappendp cwaited time pfunction defer var d deferred start now settimeoutfunction dresolvenow start timeout length return dpromisefor var i 0 i 20 i deferthenlogheres a sample of the quirky outputheres my browser infoand thanks so much for reading my question i hope someone can shed some light into thismore infoi worked around the problem by using setinterval and checking each increment to see if the required time has passed see this fiddlehowever i am still very interested to hear if anyone can shed some light into the source of the issue,"['javascript', 'jquery']" +299117,leftright padding for buttonsetcompounddrawableswithintrinsicbounds i am trying to set a left icon on a button withsetcompounddrawableswithintrinsicboundsrdrawablefoo 0 0 0but the icon is placed flush up against the left edge of my button and the text string is there a way to specify some leftright padding on the supplied icon so that it is not right up against the edgesthanks,['android'] +299140,changing app widget background color programatically how do i set the background color of the home screen app widget programatically,['android'] +299151,should one never use static inline function there are two implications of using the inline keyworda 7134it hints the compiler that substitution of function body at the point of call is preferable over the usual function call mechanismeven if the inline substitution is omitted the other rulesespecially wrt one definition rule for inline are followedusually any mainstream compiler will substitute function body at the point of call if needed so marking function inline merely for 1 is not really neededfurther wrt 2 as i understand when you declare a function as static inline function the static keyword on the function forces the inline function to have an internal linkageinline functions have external linkage each instance of such a function is treated as a separate functionaddress of each function is different and each instance of these functions have their own copies of static local variables string literalsan inline function has only one copy of thesethus such a function acts like any other static function and the keyword inline has no importance anymore it becomes redundantso practically marking a function static and inline both has no use at all either it should be staticnot most preferred or inlinemost preferredso is using static and inline together on a function practically useless,['c++'] +299184,why does rvalue reference to object generator call require copy constructor i am getting trouble with the following code with visual studio 2010 cmakea is just an object generator idiom in c like stdmake pairinclude stdiohstruct a 7th line a aa printfmoven a printfanprivate aconst a printfcopyn 12th linea makea return aint main a rrefamakea 22nd line return 0error message2dtestcpp22 error c2248 aa cannot access private member declared in class a2 dtestcpp12 see declaration of aa2 dtestcpp7 see declaration of a2i expect makea to call both a constructor and aa constructor and 22nd line to call makea and nothing else if without rvothe compiler should not require aconst a constructor to be accessible am i rightcan you tell me whats wrong with the codewith recent version of g g stdc0x and g stdc0x fnoelideconstructors compiles the code without any error,['c++'] +299208,box2dweb collision contact point i use box2dweb i am trying to develop a game at some point i need to find out the contact point between a circle and box all i know is it can be done using b2contactlistener we can receive contact data by implementing b2contactlistener using postsolve event please help,['javascript'] +299212,got activerecordassociationtypemismatch on model save i got a problem on saving model with my rest api i have a card model with many tasks and one customer associated class card activerecordbase belongs to customer has many card tasks has many tasks through card tasks accepts nested attributes for tasks accepts nested attributes for card tasks accepts nested attributes for customerendclass cardtask activerecordbase belongs to task belongs to card accepts nested attributes for task accepts nested attributes for cardendclass task activerecordbase has many cards through card tasks has many card tasksendwhen i send a json like this card miscellaneous obervations diverses heater 0 water quality customer id 2 house name house name2 city city 2 lastname lastname2 sci sci2 postal code potal code 2 address line 1 address line 2 updated at 20120305 182057 0 created at 20120305 182054 0 firstname firstname2 address line 2 address line 3 water used 0 tasks title nettoyage ligne eau id 6 updated at 20120217 084047 0 created at 20120217 084047 0 title surveillance id 4 updated at 20120217 084047 0 created at 20120217 084047 0 my create action def create card cardnewparamscard if cardsave respond with card card location nil status created and return end respond with errors carderrors location nil status unprocessable entity and return endwhen doing this i got a activerecordassociationtypemismatch task70249431354580 expected got activesupporthashwithindifferentaccess70249421573300 appcontrollerscards controllerrb14in new appcontrollerscards controllerrb14in createwhat did i do wrong,['ruby-on-rails'] +299260,objectivec preprocessor directive for if not i understand how to use a preprocessor directive like thisif some variable do somethingelse do something elseendifbut what if i only want to do something if not some variableobviously i still could do thisif some variableelse do something elseendif leaving the if empty but is there a way to doif not some variable do somethingendifapple documentation here suggests not but this seems like a very basic needbasically i want to do the preprocessor equivalent ofifsome variable do something,"['ios', 'objective-c', 'iphone']" +299291,how i can change the voice synthesizer gender and age in c i am a novice in programming i would like to change the gender and age of the voice of systemspeech in c for example a girl of 10 years but can not find any simple example to help me adjust the parametersthanks in advance,['c#'] +299311,rank function in mysql with order by clause how could this oracle sqlselect a rank over partition by afield1 order by afield2 desc field rankfrom table a aorder by afield1 afield2be translated into mysqlthis question seems to be similar but there is no order by in the end of the base query also does it matter that it is ordered by the fields of partition,['mysql'] +299314,how do i get the path of the currently running script we have an ie extension implemented as a browser helper object bho we have a utility function written in c that we add to the window object of the page so that other scripts in the page can use it to load local script files dynamically in order to resolve relative paths to these local script files however we need to determine the path of the javascript file that calls our functionmyfunc written in c and exposed to the pages javascriptfilepathtosomejavascriptjsadditional stack framesfrom the top frame i want to get the information that the script calling myfunc is located in filepathtosomejavascriptjs i first expected that we could simply use the iactivescriptdebug interface to get a stacktrace from our utility function however it appears to be impossible to get the iactivescript interface from an iwebbrowser2 interface or associated document see full callstack for multiple frames js on ie8the only thing i can think of is to register our own script debugger implementation and have myfunc break into the debugger however i am skeptical that this will work without prompting the user about whether they want to break into the debuggerbefore doing more thorough tests of this approach i wanted to check whether anyone has definitive information about whether this is likely to work andor can suggest an alternative approach that will enable a function written in c to get a stack trace from the scripting engine that invoked it,['javascript'] +299324,how do i prevent custom uitableviewcells from flashing white on deselecting i have a custom uitableviewcell which changes color based on which row it is intableviewcontrollerm voidwillthisplaycellgsrsongcell cell atindexpathnsindexpath indexpath if indexpathrow 2 0 cell lighten else cell darken customtableviewcellm voidlighten selfselectedbackgroundviewbackgroundcolor uicolor whitecolor selfcontentviewbackgroundcolor uicolor whitecolor selfprimarylabelbackgroundcolor uicolor whitecolor selfsecondarylabelbackgroundcolor uicolor whitecolor voiddarken uicolor darkcolor uicolor colorwithr241 g241 b241 a1 selfselectedbackgroundviewbackgroundcolor darkcolor selfcontentviewbackgroundcolor darkcolor selfprimarylabelbackgroundcolor darkcolor selfsecondarylabelbackgroundcolor darkcolorhowever when i call deselectrowatindexpathanimatedyes the animation fades to a white color in cells where the selectedbackgroundcolor should be darkeri then realised that the deselection animation has nothing to do with the selectedbackgroundcolor in fact the deselection animation is actually based on the tableviewbackgroundcolor propertyhow can i override the deselection animation to fade to the background color of my cells,"['objective-c', 'ios']" +299334,model and instance methods session aware sqlalchemy so using and learning with sqlalchemyi have an instance i need to get a value if that value exists return itif not calculate and return itinvariably someone will say youre doing it wrong and input on improvement is appreciated in generalhowever i am looking into how i can do this without explicitly having to manage the session because what i am working on is starting to grow and constantly managing the session for when i want to update an instance is problematic it makes me think that i am in fact doing it wrongso how do i fix the method below to not have manage the session explicitly def methodself session if selfi needed this is none selfi needed this calculatecalcutron sessionaddself sessioncommit return selfi needed this else return selfi needed thismaybe this question should be titled making instances session aware so i am not always explicitly managing it and if it is a dumb question at least show me why with examples and point me to where others have asked betteredit apparently importing the session i am using works and it is available so maybe its a non issue or a future one for when i am more skilled with sqlalchemy,['python'] +299344,ace editor define is not defined i am trying to add the ace editor to my app i downloaded it from github dropped the acelibace directory into my apps directory includedscript srcacelibaceacejs typetextjavascript charsetutf8scriptin my body tag andeditor aceedit editorin my script tag i have tried to load the page in chrome and firefox and i get define is not defined in acejs46 the line in acejs isdefinefunctionrequire exports module does anyone know why ace is expecting the define function to exist and why it is not finding it heres my sourcehtml body div ideditorsome textdiv script srcacelibaceacejs typetextjavascript charsetutf8script script var editor aceediteditor script bodyhtml,['javascript'] +299381,dynamic linking with llvm i want to execute functions in a module this module will have dependencies resolved in other modules the modules might change dynamic compilation environment so i would prefer not not link all the dependencies in a single monolithic module that is if it can be avoidedi hope to use linkerlinkmodules but this is always destructive on the source module that is ok for one module depending on a single one since if that one changed is no big deal but is not it overkill to rebuild and relink n1 modules that did not change just because of a single one that changedi wonder if there is a nondestructive version of linkmodules that can work for jit execution,['c++'] +299390,how to decorate nested attributes associations with draper in rails 3 my environmentrails 32with draper gemi am using nested resources and having trouble figuring out where to declare the decoratorappcontrollersusers controllerrbdef show user userdecoratorfindparamsid items useritemsendappcontrollersitems controllerrbdef show item useritemsfindparamsidendi tried replacing items with itemdecorator and it did not work where should i be putting iti know that draper has issues with nested resources in forms but this is not a form,['ruby-on-rails'] +299442,check if a div does not exist with javascript checking if a div exists is fairly simpleifdocumentgetifdocumentgetelementbyidifbut how can i check if a div with the given id does not exist,"['javascript', 'html']" +299447,has anyone come up with a fix line continuation pythonstyle in sublime text 2 the issue i am referring to is the indentation behavior of lists and other things in python when on two lines the result i am looking for is for sublime to automatically indent like this example making the code a little prettierdef testmethodargument1 argument2 argument3 argument4 passbut in sublime when you press enter after line 1 and then type the remaining arguments this happensdef testmethodargument1 argument2 argument3 argument4 passobviously this is not very readable and uncompliant with pep 8 style conventionsi googled around and found a few unresolved threads no solutions running latest version of sublime text 2 on a mac any help would be appreciated,['python'] +299454,check if uiview is in uiscrollview visible state what is the easiest and most elegant way to check if a uiview is visible on the current uiscrollviews contentview there are two ways to do this one is involving the contentoffsety position of the uiscrollview and the other way is to convert the rect area,"['iphone', 'objective-c', 'ios']" +299456,how to maintain a websockets connection between pages on one of my scripts i have this codevar websocket windowwebsocket windowmozwebsocketwindowws new websocketws641212101402585consoleappsample myprotocolwhich works fine however when the user changes pages i have to reestablish the connection i believe this is causing problems in my code because if the client sends data to the server and then changes pages the data may not be received and race conditions are occurringi tried to put the windowws in global scope but it did not seem to fix the problem is there any way for the websockets connection to persist between pages so the connection does not need to be constantly reestablished,"['javascript', 'html']" +299459,how can i find verify the encryption strength of my jdk security providers i have this little program that prints out all of the supported providers in my jdk installation but i am wondering if anyone knows how i can change this program to also print out the strength of each of the providersimport javasecurityprovider import javasecuritysecurity public class securitylistings public static void mainstring args for provider provider securitygetproviders systemoutprintlnprovider providergetname for providerservice service providergetservices systemoutprintln algorithm servicegetalgorithm,['java'] +299476,algorithm to retrieve every possible combination of sublists of a two lists suppose i have two lists how do i iterate through every possible combination of every sublist such that each item appears once and only once i guess an example could be if you have employees and jobs and you want split them into teams where each employee can only be in one team and each job can only be in one team egliststring employees new liststring adam bob liststring jobs new liststring 1 2 3i wantadam 1bob 2 3adam 1 2bob 3adam 1 3bob 2adam 2 bob 1 3adam 2 3bob 1adam 3bob 1 2adam bob 1 2 3i tried using the answer to this stackoverflow question to generate a list of every possible combination of employees and every possible combination of jobs and then select one item from each from each list but that is about as far as i goti do not know the maximum size of the lists but it would be certainly be less than 100 and there may be other limiting factors such as each team can have no more than 5 employeesupdatenot sure whether this can be tidied up more andor simplified but this is what i have ended up with so farit uses the group algorithm supplied by yorye see his answer below but i removed the orderby which i do not need and caused problems if the keys are not comparablevar employees new liststring adam bob var jobs new liststring 1 2 3 int c 0foreach int noofteams in enumerablerange1 employeescount var hs new hashsetstring foreach var grouping in groupenumerablerange1 noofteamstolist employees generate a unique key for each group to detect duplicates var key stringjoin groupingselectsub stringjoin sub if hsaddkey continue listliststring teams from r in grouping select rtolisttolist foreach var group in groupteams jobs foreach var sub in group consolewritelinestringjoin subkey stringjoin sub consolewriteline c consolewritelinestringformat0n0 combinations for 1 employees and 2 jobs c employeescount jobscount since i am not worried about the order of the results this seems to give me what i need,['c#'] +299525,create pdf annotations in ios i have been working on a pdf viewer with support for annotations and i need to be able to save new annotations that the user has created i have seen tons of examples on how to draw textlinesimages but that is only flattened content i need to create actual annotation objectsi have found no documentation or examples about it so if anyone could point me in the right direction i would be extremely gratefulcheersedit after several months of work we could release the v1 of this we ended up using an open source c library and went through a huge pain to make it compile for ios the one in charge of that is not working in the company any more so we cannot publish how we managed to do it,"['objective-c', 'ios']" +299553,how to make moq ignore arguments that are ref or out in rhinomocks you can just tell your mocks to ignorearguments as a blanket statement in moq it seems you have to specify itisany for each argument however this does not work for ref and out arguments how can i test the following method where i need to moq the internal service call to return a specific resultpublic void mymethod dostuff ilistsomeobject errors new listsomeobject var result servicedosomethingref errors ref param1 param2 do more stufftest methodpublic void testofmymethod setup var moqservice new mockimyservice iliststring errors var model new mymodel this returns null presumably becuase errors here does not refer to the same object as errors in mymethod moqservicesetupt tdosomethingref errors ref model itisanysometype returnsnew othertype update so changing errors from ref to out works so it seems like the real issue is having a ref parameter that you cannot inject,['c#'] +299650,c regex not understanding the following outputs hut where i expect it to output hut i know that is greedy but must be matched and it is outside of the capture group so why is it in my submatchinclude stringinclude regexinclude iostreamusing namespace stdint main regex my r string temprcols64hut smatch m if regex matchtemp m my r cout m1 endl,['c++'] +299701,how can i fire onclick event programatically in android i have a custom view withe 2 lineat layouts the first is the views header and the second is the the details viewin the custom view the onclicklistener of the header linearlayout is already defined when it fires it collapsesexpandes the second linearlayoutwhat i want to do is to add more functionalities to my headers onclicklistener event ie collapseexpand the second layout and show a toasti cannot modify the source code of the custom view i tried to set a new onclicklistener but it hides the initial event collapseexpandhow should i implement thisthe source code of my custom view public class expandolayout extends viewgroup some declarations private linearlayout header private linearlayout footer some code override protected void onfinishinflate header new linearlayoutcontext headersetonclicklistenernew onclicklistener override public void onclickview v toggleexpand what i want to do is to add some code to the already defined onclicklistener event in my activitysomething like that public class myactivity extends activity private linearlayout mycustomviewoverridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutrsdetail mycustomview mycustomview findviewbyidridexpanded mycustomviewgetchildat0setonclicklistenernew onclicklistener override public void onclickview v ifv instanceof linearlayout vperformclick toastmaketextgetactivity expandoonclicklistener 20show,['android'] +299709,avoiding violation of reused abstraction principle in dependency injection we program against an abstraction from my experience i can state that most of the abstractions in an application have a 11 relationship with their implementations this is a violation of reused abstraction principle mark seeman suggested in some of his posts that we can have a null object implementation for the abstractions in order to avoid rap violation this suggestion from mark seeman could be my inference please correct me if i am wrong to quote mark on this my question here ishow to do null object implementationis it ok to violate rap,['.net'] +299730,cgbitmapcontextcreate returns null under what circumstances will a cgbitmapcontext fail to allocate i have a table view and it has multiple view options the user can see a small table cell with just previews one larger preview per line or two side by side previews per line the first two render just fine but the third one fails there are no error messages from cgbitmapcontextcreate just errors after when i try to use it ie invalid context 0x0cgcolorspaceref colorspace cgcolorspacecreatedevicergbsize is a passed parametercgcontextref c cgbitmapcontextcreatenull sizewidth sizeheight 8 sizewidth4 colorspace kcgimagealphanoneskiplastcgcolorspacereleasecolorspacei am targeting ios 50 building with 51 the only difference between the working and nonworking version is that the nonworking version attempts to do it twice size is small less than 100x100 only the right side has this problem ie the second attempt the first attempt still works,['ios'] +299752,ambiguous behavior of new line character i am uploading a large string to webservice the string contains new line character which is written as nthe data looks some thing like 05062012 113543 am db exists transferring datan05062012 114820 am loaduserspinners cursorgetcount2n05062012 114820 am battery 50n05062012 114820 am item selected 0the above data is stored in string jsonarrobj to upload the datastring i am using the following code httpparams httpparameters new basichttpparams int timeoutconnection 360 6 minutes httpconnectionparamssetconnectiontimeouthttpparameters timeoutconnection int timeoutsocket 420 7 minutes httpconnectionparamssetsotimeouthttpparameters timeoutsocket httpclient httpclient new defaulthttpclienthttpparameters jsonarray jsonparams new jsonarray object paramsipaddressdatabasedbnamedbpasswordjsonarrobj for int i 0 i paramslength i jsonparamsputparamsi jsonobject jsonrequest new jsonobject jsonrequestputid id jsonrequestputmethod functionname jsonrequestputparams jsonparams jsonentity entity new jsonentityjsonrequest entitysetcontenttypeapplicationjson charsetutf8 httppost request new httpposturl requestsetentityentity httpresponse response httpclientexecuterequest statusline statusline responsegetstatusline int statuscode statuslinegetstatuscode if statuscode 200 httpentity httpentity responsegetentity inputstream content httpentitygetcontent bufferedreader reader new bufferedreader new inputstreamreadercontentiso885918 string line while line readerreadline null builderappendline logeresult line line string strconvertstringline parsejsonstr contentclose the string is uploaded successfully the problem i am facing is while string is being converted to jsonparams the n in the string data gets converted to n as a result on the server side it shows a small box in stead of new line when i open this string in notepad application it thisplays small boxes but when i open it in wordpad app text is thisplayed on a new line according to me i might have entered incorrect contenttype or encoding please suggest a solution for the same jsonarrobj urlencoderencodejsonarrobj utf8 gave error while uploading itselfthe data which is sent in the jsonparams jsonarrobj finally looks like05062012 040552 pm db exists transferringdatan05062012 043256 pm loaduserspinnerscursorgetcountu003d2n05062012 043256 pm battery50n05062012 043256 pm item selected 0,['android'] +299795,cancel route using sammyjs without affecting history i want to intercept all route changes with sammy to first check if there is a pending action i have done this using the sammybefore api and i return false to cancel the route this keeps the user on the page but it still changes the hash in the browsers address bar and adds the route to the browsers history if i cancel the route i dont want it in the address bar nor history but instead i expect the address to stay the same currently to get around this i can either call windowhistoryback yuk to go back to the original spot in the history or sammyredirect both of which are less than idealis there a way to make sammy truly cancel the route so it stays on the current routepage leaves the address bar as is and does not add to the historyif not is there another routing library that will do thissammybefore function can cancel the route if this returns false var response routemediatorcanleaveif isredirecting responseval isredirecting true keep hash url the same in address bar windowhistoryback thisredirectspecificpreviouspage else isredirecting falsereturn responseval,['javascript'] +299802,how to replace first occurrence of string in java i want to replace first occurrence of string in the following string test see comments this is for some test help usif test contains the input as follows it should not replacesee comments with space at the endsee commentssee commentsi want to get the output as follows output this is for some test help usthanks in advance,['java'] +299806,how to reference another method of the same class in javadoc suppose your class has 2 methodscontains andcontainssamethe thistinction between them is subtle and youd like to mention it as part of javadocin javadoc how can you reference a method in the same class by name,['java'] +299823,jquery callback after slideup i have this codesomedivslideup400settimeoutfunction somefunction 400how do i rewrite this and remove the settimeout so that somefunction becomes a callback function of slideupthanks,['jquery'] +299877,iad contract expired not so says itunesconnect iad module thinks otherwise i recently updated my developer membership my new contract went into effect may 19th last week i went in and browsed my iad earnings and noticed that all of my iad apps are red and not receiving ads after expanding the details to find out why the iad module tells me that my iad contract has expired however the contracts banking and tax module reports that everything is ok and my iad contract will be in effect until may 19 2013incidentally my last day of revenue was may 19th of this yeari called apple support have had a follow up phone call where it was requested i submit screenshots but i have not heard anything back has anyone else experienced this,['ios'] +299892,select all rows using entity framework i am trying to select all the rows out of a database using entity framework for manipulation before they are sent to the formvar ptx modelnametablenameptxtablenameselectwhat goes in the,['asp.net'] +299900,my screensaver is stopping screen suspend but i do not want it to i made a screensaver in net 40 it basically just moves the bits in an image around and thisplays it using invalidate on a timer and overriding the onpaint eventso far it works great however i noticed one problem with itit is stopping the monitor from suspending after the suspend timeout since i installed it my monitor stays on 247 nowthe thing is i did not do anything to specifically stop power savings features and i have made sure that my computers power savings settings are set they are so then i chose another screensaver just to be sure the settings were still working the monitor suspended after the timeoutwhat do i need to do then to play nice with power management i searched for this answer on google and everything i found is how to block power management and i did not explicitly block it i just want the suspend to be allowed when it is time,['c#'] +299914,where can i find the yii version of my yii app i recently started to work with yii where can i find the yii version of my yii app,['php'] +299922,which is faster clear collection or instantiate new i have some number of generic lists in my code that have tens or hundreds elementssometimes i need to refill this lists with other objects so question is what will be faster to call clear method or creating a new listt,['.net'] +299928,zeromq how to access tcp message in c i am a newby to zeromq and make my way through the c helloworld example of the echo clientserver pattern requestreply the server looks like hello world server in c binds rep socket to tcp5 expects hello from client replies with worldinclude zmqhppinclude stringinclude iostreaminclude unistdhint main prepare our context and socket zmqcontext t context 1 zmqsocket t socket context zmq rep socketbind tcp5 while true zmqmessage t request wait for next request from client socketrecv request stdcout received hello stdendl do some work sleep 1 send reply back to client zmqmessage t reply 5 memcpy void replydata world 5 socketsend reply return 0now my question how can i access read the real data that socketrecv trying stdcout request stdendlresulted in an error message error no match for aoperatora in astdoperator with traits stdchar traitscharstdbasic ostreamchar stdchar traitschar stdcout const charreceived hello requestathe same goes for the client side that is sending the message i do not find a way to thisplay the real message,['c++'] +299967,find out mysql database url from phpmyadmin i have an online mysql database i want to figure out the server url so i can remotely connect to it is there a way i can check my databases url from phpmyadmin,['mysql'] +300003,defined xml layout in layoutland does not appear in android application i am developing an application according to this example i defined a landscape layout for headerxml in a layoutland folder but when i change the orientation to landscape defined layout does not appear in the screendo know why thanksupdated activity code public class acenewsfeedactivity extends listactivity progress dialog private progressdialog pdialog array list for list view arraylisthashmapstring string rssitemlist new arraylisthashmapstringstring rssparser rssparser new rssparser listrssitem rssitems new arraylistrssitem rssfeed rssfeed private static string tag title title private static string tag link link private static string tag desription description private static string tag pub date pubdate private static string tag guid guid not used called when the activity is first created override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutrss item list calling a backgroung thread will loads recent articles of a website param rss url of website new loadrssfeeditemsexecute xml layout in landscape mode xml version10 encodingutf8relativelayout xmlnsandroid androidididlayoutheader androidlayout widthfill parent androidlayout height50dip androidlayout alignparenttoptrue androidbackgroundlayoutheader gradient androidorientationhorizontal logo refresh plus button imagebutton androidididbtnaddsite androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentrighttrue androidlayout marginright5dip androidbackgroundnull androidsrcdrawableplus androidlayout centerverticaltrue imageview androidididlogo androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentlefttrue androidlayout centerverticaltrue androidsrcdrawablelogo imageview androidididrefreshlist androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentbottomtrue androidlayout centerhorizontaltrue androidsrcdrawablerefresh relativelayout,['android'] +300014,access javascript array elements from c via webbrowser using webbrowser on a form and calling into c from javascript with windowexternal passing in a javascript array of classes in the functionvar x xpushclassaxpushclassawindowexternalcsharpfunctionxi can successfully get xlength in c withint lengthintxgettypeinvokememberlength bindingflagsgetproperty null x nullmy question is how do i get x0 and x1i have triedxgettypeinvokememberstringempty bindingflagsgetproperty null x new object11andxgettypeinvokememberstringempty bindingflagsinvokemethod bindingflagsdefault null x new object10both of which fire off errors within the webbrowser controlthanks,"['c#', 'javascript']" +300019,haskell ffi how to handle c functions that accept or return structs instead of pointers to structs of course the answer is to somehow passtake a contiguous block of memory so the question is more about how to do that for now i could still avoid the issue by writing wrapper functions on the c side but that is not much of a permament solution,['c'] +300052,netbeans code highlighting for built in php functions i cannot seem to change the code highlighting for php builtin functions such as strlen or preg match is this even possible in netbeans because no matter what i try it appears in the same color as plain text in the editor,['php'] +300055,symfony2 how to change environment i have read a lot about the clear cache command for symfony2 but i have this question is php appconsole cacheclear envprod with env changes the environment or just clean the cache for that environmentif only clear the cache for that environment then what is this line mean in aphp kernel new appkernelprod false i think when i want to use symfony2 production environment i have to change that line to kernel new appkernelprod trueam i in the right spot,['php'] +300056,objectivec library cannot form weak reference to instance of class i am currently working with the xmpp library for objectivec and i am using the desktop example codeit logs in fine however when i open a new chat or someone sends me a message it crashesthis seems like where something goes wrongxmppstream116781b03 recv 20120605 150359379 xmppstream116781b03 recv 20120605 150359382 xmppstream11678403 rostercontroller xmpprosterdidchange20120605 150359387 xmppstream11678403 rostercontroller xmpprosterdidchange20120605 150401900 xmppstream11678403 tableviewshouldedittablecolumnjid row020120605 150401900 xmppstream11678403 user objc11678 cannot form weak reference to instance 0x7fcd4a498930 of class chatcontrollerandobjc11998 cannot form weak reference to instance 0x7f853bd17c70 of class chatcontrollerlldb lldbwhat does cannot form weak reference to instanceof class chatcontroller mean do you guys know how i can fix it i used an older version of this code with snow leopard and it worked lion is screwing me up thank you,['objective-c'] +300071,why does array4 in javascript boot up your interpreterconsole and try the comparison array4truewhy at first i thought maybe since you could think of as an array of four characters with a 0 terminating slice that might be why but array4returns false so why i know it is some idiosyncratic bit of duck typing in javascript but just curious what underlines this behavior gleaned this from zed shaws excellent presentation here btw,['javascript'] +300084,java 7u4 webstart security exception class does not match trust level we began to notice that with java 7 particularly with update 4 that all our users began to see this with our webstart app144258422 awteventqueue0debug javalangsecurityexception class classname does not match trust level of other classes in the same package144258422 awteventqueue0debug at comsundeploysecuritycpcallbackhandlerchildelementcheckresourceunknown source144258422 awteventqueue0debug at comsundeploysecuritydeployurlclasspathjarloadercheckresourceunknown source144258422 awteventqueue0debug at comsundeploysecuritydeployurlclasspathjarloadergetresourceunknown source144258422 awteventqueue0debug at comsundeploysecuritydeployurlclasspathgetresourceunknown source144258422 awteventqueue0debug at javaneturlclassloader1rununknown source144258422 awteventqueue0debug at javaneturlclassloader1rununknown source144258422 awteventqueue0debug at javasecurityaccesscontrollerdoprivilegednative method144258422 awteventqueue0debug at javaneturlclassloaderfindclassunknown source144258422 awteventqueue0debug at comsunjnlpjnlpclassloaderfindclassunknown source144258422 awteventqueue0debug at javalangclassloaderloadclassunknown source144258422 awteventqueue0debug at javalangclassloaderloadclassunknown sourcemorewhere classname pretty much every class at random points from several jars in the app execution breaking several behaviorif our users were to use java 6 they have no problems just 7 update 4we sign all our jars both the main application jar and it is library jars ie users launching our webstart app see the blue shield instead of yellow or redthis is obviously an issue as users are more frequently now upgrading to java 7i have tried to force our app to use java 6 on the user machine either by using a previous installationworks or installing a new onewith the j2se version16 tag around resources but this causes it is own problems that would probably be best to make into it is own thread the autojreinstallation part did oracle break webstart security with java 7u4 how do i solve this securityexception issue,['java'] +300086,gem install therubyracer fails on mac os x lion i would appreciate some help in getting gem install therubyracer to work here is the error gem install therubyracerbuilding native extensions this could take a whileerror error installing therubyracer error failed to build gem native extension usersdavidrvmrubiesruby193p194binruby extconfrbchecking for main in lobjc yes extconfrb failed could not create makefile due to some reason probably lack ofnecessary libraries andor headers check the mkmflog file for moredetails you may need configuration optionsprovided configuration options withoptdir withoptinclude withoutoptincludeoptdirinclude withoptlib withoutoptliboptdirlib withmakeprog withoutmakeprog srcdir curdir rubyusersdavidrvmrubiesruby193p194binruby withobjclib withoutobjclibextconfrb15in main undefined method include path for libv8module nomethoderrorhere are some notable steps that i ran before the error they worked fine gem install libv8 brew install v8my environment ismac os x lion 1074ruby 193p194 20120420 revision 35410 x86 64darwin1140 via rvmv8 version 3924 via homebrew,['ruby'] +300142,calculate difference between two datetimes in mysql i am storing the last login time in mysql in datetimetype filed when users logs in i want to get the difference between the last login time and the current time which i get using nowhow can i calculate it,['mysql'] +300200,containing a text in an oval shaped area i have a html page which looks like the followingi want to thisplay some text on the left pane but the problem is that the text should be inside the oval shaped area only how do i achieve this note that the oval shaped image is the background image however if required i can also use a img tag for it if it would help one lame way is to use p tags with padding but that is not an efficient way so kindly suggest some good methodsedit htmldiv idleftstage classroundedcorners div idquestionthisp aligncenter divdivcssleftstage position relativewidth 34height86float leftquestionthisp thisplaynonejs when the appropriate function is called questionthispfadein10questionthisphtmlquesarrq1 data read from xmledit what i need is a div or something above the oval background the text should fit in it i am getting the text from an xml file so it is not that i have a fixed text size to be thisplayed,"['html', 'css']" +300225,get a array of class files inside a package in java i need a class of all the class files contained in one of my source packages in javai could nt find a standard method to do it in one shot if someone can write a function to fetch that list would be really helpfulclass myclasses yourfunction return a list of class inside a source package in the currently working project in java,['java'] +300254,looping through bits in an integer ruby i am making a program where one of the problems is that i need to do some analysis of the bit pattern in some integersbecause of this i would like to be able to do something like thisdoes not worknumeach bit do i do something with iendi was able to make something that works by doingnumto s2each char do c do something with c as a charendthis however does not have the performance i would likei have found that you can do this0uptonum2 do i do something with niendthis have even worse performance than the each char methodthis loop is going to be executed millions of times or more so i would like it to be as fast as possiblefor reference here is the entirety of the functionahashmap hashnew1the method finds the length of the longes continuous chain of ones minus one 1010 2 11 1 101010101 0 1010 4def afuncn if ahashmapn 1 return ahashmapnendnum 0tempnum 0prev falsento s2each char do i if i if prev tempnum 1 if tempnum num num tempnum end else prev true end else prev false tempnum 0 endendahashmapn numreturn numend,['ruby'] +300270,named query with like in where clause is it possible to have a like in a where clause in a named query i am trying to do the following but am getting exceptionsnamedqueryname placegetplaceforcityandcountrynamequery select p from place p where lowerpcity like city and lowerpcountryname like countrynamei tried adding as you would do in normal sql but get exceptions compilingany pointers greatly appreciatedthanks,"['java', 'sql']" +300299,why double in c is 8 bytes aligned i was reading a article about data types alignment in memoryhere and i am unable to understand one point ienote that a double variable will be allocated on 8 byte boundary on 32 bit machine and requires two memory read cycles on a 64 bit machine based on number of banks double variable will be allocated on 8 byte boundary and requires only one memory read cyclemy doubt is why double variables need to be allocated on 8 byte boundary and not on 4 byte if it is allocated on 4 byte boundary still we need only 2 memory read cycleson a 32 bit machine correct me if i am wrongalso if some one has a good tutorial on membermemory alignment kindly share,['c'] +300340,are php associative arrays ordered i come from python background and the python datatype which is similar a dictionary is an unordered set of key value pairsi am wondering if php associative arrays are unordered they appear to be orderedtest array test test bar barvar dumptest var dumparray slicetest 0 1test always comes before bar and i can slice this array as you see so is this always guaranteed to be ordered across php versions is the order just the order that i have declared the array with so something is internally pointing test to place 0 in the array i have read but it does not shed too much light on this issue i appreciate your responses ty,['php'] +300342,connect two tcp sockets without defining clientserver role questioni want to connect two processes via tcp but i do not want have to specify which of them is the server and which is the client but they know the ip and host of each other they should decide on their own which is the server and which is the client and then initiating the connection backgroundi am working on a bidirectional thistributed framework where in contrast to rpc there is no clientserver model instead the thistributed components should just be able to talk to each other by specifying a host and portedit the concept goes beyond the implementation details of a socket connection this should be a new concept to simplify designing a thistributed application in terms of software engineering this is in contrast to rpc and soa which are serverclient oriented and message oriented systems which demand the usage of imo unintuitive patterns the solution must notdefining a protocol via udp because i need the tcp reliability and the possibility of ssl usageusing a framework like zeromq because i cannot use binary packages on my target platformedit a global message broker name server because it should be a lightweight solution without an additional process and adding such a node will just reintroduce the clientserver conceptupdateafter the thiscussion there seems only one useful approach every peer need to have a listing socket or you cannot do any autothiscovery of course on a connection request the node will try to connect to the other peer if there is not already an open connectionthis could be problematic if the connection is done simultaneous so we will end up with two connections between two peers the question is now how to deal with that in an async context i do not think this is as easy as said below in comments because we need to guarantee that only one connection is closed i think a protocol like 2pc is needed for this task,['python'] +300370,localization with bean validation in jsf i made a mvc based website using jsf 20 and richfaces 4 every input text validation is been done using bean validation annotations i am using hibernate validator as bean validation implementationhow can i thisplay a localized messageif i usenotnullmessagehoutputtext valuemsgmymessage then it literally thisplays houtputtext valuemsgmymessage as messagehow is this caused and how can i solve it,['java'] +300371,why is it not possible to compare intptrzero and defaultintptr i just learned the hard way that intptrzero cannot be compared to defaultintptr can someone tell me whyintptrzero new intptr0 could not evaluate expressionintptrzero defaultintptr could not evaluate expressionintptrzero intptr0 could not evaluate expressionintptrzeroequalsintptrzero enum value was out of legal range exceptionintptrzeroequalsdefaultintptr enum value was out of legal range exceptionintptrzero intptrzero truenew intptr0 new intptr0 true,"['c#', '.net']" +300413,on ios why does setting a layers sublayertransform turn itself to act like catranformlayer it is known that the zposition of the layers only determines which layer cover up which layer whether it is a zposition of 10 or 10 would not affect its positionthat is unless if we use catransformlayer to contain those layers then the zposition of those layers will affect the layers positionhowever the following code running in ios 511 does make the zposition alter the position of the layers you can try it in a new single view app and add the following code to viewcontrollerm if the zposition of layer2 is changed from 88 to 188 we can see that the layer moves accordingly so no catransformlayer is in the code why will it behave like that please quote apple docs or any referencealso related is if the line selfviewlayersublayertransform transform3d is changed to selfviewlayertransform transform3d then the zposition will have no effect on the position but according to the apple docs transform and sublayertransform only differ in whether self is transformed or nottwo layer properties specify transform matrices transform and sublayertransform the matrix specified by the transform property is applied to the layer and its sublayers relative to the layers anchorpoint the matrix specified by the sublayertransform property is applied only to the layeras sublayers rather than to the layer itselfso it is strange that why changing that will cause selfviewlayer to act like a catransformlayervoid viewdidappearboolanimated catransform3d transform3d catransform3didentity transform3dm34 10 10 transform3d catransform3drotatetransform3d m pi 4 0 1 0 selfviewlayersublayertransform transform3d calayer layer1 calayer alloc init layer1zposition 33 layer1frame cgrectmake100 100 100 100 layer1backgroundcolor uicolor orangecolor cgcolor selfviewlayer addsublayerlayer1 calayer layer2 calayer alloc init layer2zposition 88 layer2frame cgrectmake100 120 100 100 layer2backgroundcolor uicolor yellowcolor cgcolor selfviewlayer addsublayerlayer2,['ios'] +300460,fragment myfragment not attached to activity i have created a small test app which represents my problemi am using actionbarsherlock to implement tabs with sherlockfragmentsmy codetestactivityjavapublic class testactivity extends sherlockfragmentactivity private actionbar actionbar override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setuptabssavedinstancestate private void setuptabsbundle savedinstancestate actionbar getsupportactionbar actionbarsetnavigationmodeactionbarnavigation mode tabs addtab1 addtab2 private void addtab1 tab tab1 actionbarnewtab tab1settag1 string tabtext 1 tab1settexttabtext tab1settablistenernew tablistenermyfragmenttestactivitythis 1 myfragmentclass actionbaraddtabtab1 private void addtab2 tab tab1 actionbarnewtab tab1settag2 string tabtext 2 tab1settexttabtext tab1settablistenernew tablistenermyfragmenttestactivitythis 2 myfragmentclass actionbaraddtabtab1 tablistenerjavapublic class tablistenert extends sherlockfragment implements comactionbarsherlockappactionbartablistener private final sherlockfragmentactivity mactivity private final string mtag private final classt mclass public tablistenersherlockfragmentactivity activity string tag classt clz mactivity activity mtag tag mclass clz the following are each of the actionbartablistener callbacks public void ontabselectedtab tab fragmenttransaction ft sherlockfragment preinitializedfragment sherlockfragment mactivitygetsupportfragmentmanagerfindfragmentbytagmtag check if the fragment is already initialized if preinitializedfragment null if not instantiate and add it to the activity sherlockfragment mfragment sherlockfragment sherlockfragmentinstantiatemactivity mclassgetname ftaddandroidridcontent mfragment mtag else ftattachpreinitializedfragment public void ontabunselectedtab tab fragmenttransaction ft sherlockfragment preinitializedfragment sherlockfragment mactivitygetsupportfragmentmanagerfindfragmentbytagmtag if preinitializedfragment null detach the fragment because another one is being attached ftdetachpreinitializedfragment public void ontabreselectedtab tab fragmenttransaction ft user selected the already selected tab usually do nothing myfragmentjavapublic class myfragment extends sherlockfragment override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate new asynctaskvoid void void override protected void doinbackgroundvoid params try threadsleep20 catch interruptedexception ex return null override protected void onpostexecutevoid result getresourcesgetstringrstringapp name execute i have added the threadsleep part to simulate downloading data the code in the onpostexecute is to simulate use of the fragmentwhen i rotate the screen very fast between landscape and portrait i get an exception at the onpostexecute code javalangillegalstateexception fragment myfragment410f6060 not attached to activityi think it is because a new myfragment has been created in the meantime and was attached to the activity before the asynctask finished the code in onpostexecute calls upon a unattached myfragmentbut how can i fix this,['android'] +300470,accessing expressjs local variables in client side javascript curious if i am doing this right and if not how you guys would approach thisi have a jade template that needs to render some data retrieved from a mongodb database and i also need to have access to that data inside a client side javascript filei am using expressjs and sending the data to the jade template as follows var mymongodbobject name stephenresrenderhome locals data mymongodbobject then inside of homejade i can do things like p hello datanamewhich writes out hello stephennow what i want is to also have access to this data object inside a client side js file so i can manipulate the object on say a button click before posting it back to the server to update the databasei have been able to accomplish this by saving the data object inside a hidden input field in the jade template and then fetching the value of that field inside my clientside js fileinside homejade local data jsonstringifydata data coming in from expressjsinputtypehidden valuelocal datamylocaldataobjthen in my client side js file i can access local data like so inside mylocalfilejsvar localobj jsonparsemylocaldataobjvalconsoleloglocalobjnamehowever this stringify parsing business feels messy i know i can bind the values of my data object to dom objects in my jade template and then fetch those values using jquery but i would like to have access to the actual object that is coming back from express in my client side js is my solution optimal how would you guys accomplish this,['javascript'] +300474,addeventlistener not working with onbeforeunload windowaddeventlisteneronbeforeunloadfunction return are you sure this does not seem to work at all the page will simply close without thisplaying the confirmation boxi realize thatwindowonbeforeunload function return are you surewill work but i want to add to the functionality eg add many event listeners to the onbeforeunload function not rewrite the function completely,['javascript'] +300516,cpu tsc fetch operation especially in multicoremultiprocessor environment in linux world to get nano seconds precision timerclockticks one can use include systimehint foo timespec ts clock gettimeclock realtime ts snip this answer suggests an asm approach to directly query for the cpu clock with the rdtsc instruction in a multicore multiprocessor architecture how is this clock tickstimer value synchronized across multiple coresprocessors my understanding is that there in inherent fencing being done is this understanding correct can you suggest some documentation that would explain this in detail i am interested in intel nehalem and sandy bridge microarchitectureseditlimiting the process to a single core or cpu is not an option as the process is really hugein terms of resources consumed and would like to optimally utilize all the resources in the machine that includes all the cores and processors edit thanks for the confirmation that the tsc is synced across cores and processors but my original question is how is this synchronization done is it with some kind of fencing do you know of any public documentation conclusionthanks for all the inputs heres the conclusion for this thiscussion the tscs are synchronized at the initialization using a reset that happens across the cores and processors in a multi processormulti core system and after that every core is on their own the tscs are kept invariant with a phase locked loop that would normalize the frequency variations and thus the clock variations within a given core and that is how the tsc remain in sync across cores and processors,['c'] +300540,ninject bind when ancestor of type t i have got a dependency chain that looks roughly like thispublic class carsalesbatchjob public carsalesbatchjobifileprovider fileprovider public class motorcyclesalesbatchjob public motorcyclesalesbatchjobifileprovider fileprovider public class ftpfileprovider ifileprovider public ftpfileprovideriftpsettings settings public class carsalesftpsettings iftpsettings public class motorcyclesalesftpsettings iftpsettings up until now i have been using conventions based bindings but that is not good enough anymore because i have got more than one implementation for iftpsettings so i decided to use some contextual bindings at first blush kernelbindtowheninjectedinto looked promising but that only helps at the first level meaning that if i had a carsalesftpfileprovider and a motorcyclesalesftpprovider i could do thiskernelbindiftpsettingstocarsalesftpsettings wheninjectedintocarsalesftpfileproviderkernelbindiftpsettingstomotorcyclesalesftpsettings wheninjectedintomotorcyclesalesftpfileproviderbut it seems pretty stupid to create two concrete implementations of ftpfileprovider that really only differ on what settings i want them to use i saw that there is a method called whenanyanchestornamedstring name but this route requires me to put attributes and magic strings on my batch jobs which i am not thrilled abouti also noticed that there is a plain old whenfuncirequest bool method on binding statements so i came up with this as my binding statementsat this point i have already ran the conventions based bindings code so i need to unbindkernelunbindiftpsettingskernelbindiftpsettingstocarsalesftpsettings whenr hasancestoroftypecarsalesbatchjobrkernelbindiftpsettingstomotorcyclesalesftpsettings whenr hasancestoroftypemotorcyclesalesbatchjobr later on in the same classprivate static bool hasancestoroftypetirequest request if request null return false if requestservice typeoft return true return hasancestoroftypetrequestparentrequestso if a constructor asks for iftpsettings we recurse up the request tree to see if any of the requested servicestypes in the chain match the provided type carsalesbatchjob or motorcyclesalesbatchjob and if so returns true if we get all the way to the top of the chain we return falsesorry for the long background explanation here is my question is there any reason why i should not approach the problem this way is this considered bad form is there a better way of finding the ancestor request types should i restructure my classesdependency chain to a more agreeable fashion,['.net'] +300587,phonegap automatically including correct cordova i am developing a phonegap app on both ios and android and have my w directory version controlled with git i know that my html file needs to include the correct cordovajs file depending on which platform i am currently developing onit is a little annoying pulling changes to w on ios when someone was working on android it gives me the endless gap poll alertsimple solution is to remember to change the cordovajs src so it points to the ios version again the problem with that is the other developers will need to keep changing their src if the latest commit was done on another platformis there a way to automatically detect which version of cordova to include that way it would work on any platform and we wouldnt have to make tedious changes,"['javascript', 'android', 'ios']" +300625,cvxopt output suppression with mosek i am using the optional mosek solver with cvxopt quadratic programming iesol cvxoptsolversqpqpghabsolvermoseknow without using the mosek solver iesol cvxoptsolversqpqpghabterminal output generated by cvxopt can be suppressed with the commandcvxoptsolversoptionsshow progress falsehowever this does not work when using the mosek solver option the mosek solver which i have within a couple of loops produces a lot of output i am not interested in meaning i cannot see the output i am interested in ie what i choose to output using printdoes anyone know if it is possible to suppress the mosek output or if not a potential work around pipe the output to a file or somethingmany thanksdanps sorry i could not include more specific tags i am not allowed to create new tags,['python'] +300667,transformation of xml into html best practice i have xml like thisartist namesyd mead id3412 ntrack28 pop8 which i need to use in html markupa href datanamesyd mead dataid3412 datantrack28 datapop8 classpop8spansyd meadspanawhat is the right way to do this for the widest array of browsers can this be done reliably with a xslt transformation is it better to use a regex unlikely or do i have to parse out the xml and for each artist tag read each attribute and do documentcreateelement and setattribute manually the artist tags are in a parent node there is many of them is there a best practice for this,['javascript'] +300669,adding user in itunes connect team i am a newbie developer of iphone from last few months i am uploading apps behalf of my clientsso one of my client add my email id in his itunes connect account i completed the procedures and successfully login into itunesconnectapplecom and uploaded the appbut now i have other client who also wants me to upload his appi am giving him my email to add me in his team in itunes connect not in developer i got invitation in developerapplecombut now problem is when he add me as a user it gives error like thisthe email address you entered already belongs to an itunes connect account to continue enter a different email addreso if it means that i have to give different user ids to different clients how can i use single email id for different clients teamsany suggestions on it please mind that i am facing problem in itunesconnect not in developerthanks in advance,['iphone'] +300688,using javascript to detect whether the url exists before thisplay in iframe i am using javascript to pass a dynamic url to iframe src but sometimes the url does not exist how could i detect the nonexist url beforehand so that i can hide the iframe that with 404 error,['javascript'] +300690,could not read from the device i am trying to install new version of my application on the top of the last version through xcodewhenever i try to install it with the same provisional profile and details i encountered with this problemthis problem occurs after build while copying the fileshas anyone faced this issueps i have attached the error screenshot,['ios'] +300697,textarea shows extra space while retrieving from database i have a simple php file that gets info from mysql database thisplay inside textarea but when i open it from browsers it shows extra space at the beginning and end of the text inside textareathis is how it looks database text has no extra spacethis is what i did to retrieve the texttextarea nametext rows9 php echo fetcheddatafounder msg textareai used simple mysql fetch array to retrieve the value text are saved inside founder msg field in mysql database of data type text,"['php', 'mysql', 'html']" +300725,postgresql aggregate array hi i have a two tablesstudentid name1 john 2 david3 willgradestudent id mark1 a2 b2 b3 c3 ais it possible to make native postgresql select to get results like thisname array of marksjohn adavid bbwill cabut not like thisname markjohn adavid bdavid bwill cwill a,['sql'] +300730,change table name to upper case i need to change table name from lowercase to uppercase but using this statement the table name can be changed but the names are in lowercasesql rename table name to nameis there any way to convert table name to uppercase,['mysql'] +300744,organize maven multimodule project in eclipse i have a huge maven multimodule project with similar structure parenta suba1 suba3 suba3 suba2parentb subb1 subb2etcthe problem is that parenta and suba1 does not contains any code inside it but i can still see them in project explorer but i would like to hide them or organize in tree hierarchy like in an explorer right now there are over 30 projects and just 20 of them contains java code others simply contains others modules references i see all 30 projects in plain form in project explorerthe first idea was using working set but i cannot include working set in another working set what is the common practice to handle this issue for eclipse users,['java'] +300768,jquery style not being applied in safari i have an absolutely positioned element that i move with the help of jquery using the css propertly leftelementcssleft 103pxin firefox this works as expected however in safari i can see the style appearing in the web inspector under elementstyle but the style is not updated if i thisable and reenable any matched cssrules even those not applied directly to my div the style being applied with jquery is rendered i am running safari 506 on an old powermac with jquery 172,"['jquery', 'css']" +300805,thisplaying manytomany groupings in wpf i am not sure if i am on the right track with this one but essentially i am trying to thisplay a grouped list of items where each item can be a member of multiple groups ie the two entities are related on a manytomany basis i will try to explainmy question is how do i group items like this into a control i am aware of the icollectionview and the propertygroupdescription but that does not seem to serve my purpose here it seems to only work in a onetomany scenarioany ideassome points to notewhen thisplayed in a list i want to show all components grouped by kitwhen i select a component from this list i only want that particular instance of the component ie i want component the kit i selected it fromignore the fact that i am using a treeview to show the items below as i will actually be using a listbox with a groupstylei am using codefirst ef 431 and the wpf mvvm pattern,['c#'] +300807,phps strtr for python php has the strtr functionstrtraabbcc arrayaa bbz bb x cc y bbzxyit replaces dictionary keys in a string with corresponding values and important does not replace already replaced strings a naive attempt to write the same in pythondef strtrstrng replace for s r in replaceitems strng strngreplaces r return strngstrtraabbcc aa bbz bb x cc yreturns xzxy which is not we want bb got replaced again how to change the above function so that it behaves like its php counterparti would prefer an answer without regular expressions if possibleupd some great answers here i timed them and found that for short strings gumbos version appears to be the fastest on longer strings the winner is the re solution aabbcc00258 strtr thg00274 strtr gumbo00447 strtr kojiro00701 strtr aix aabbcc1001474 strtr aix02261 strtr thg02366 strtr gumbo03226 strtr kojiromy own version which is slightly optimized gumbosdef strtrstrng replace buf i 0 while i lenstrng for s r in replaceitems if strngilensi s bufappendr i lens break else bufappendstrngi i 1 return joinbufcomplete codes and timings,['python'] +300809,capture 404 status with jquery ajax i have this codeajax cache false url admincontentsgetdata data accountid accountid success function data cityidhtmldata error function ajaxcontext alertajaxcontextresponsetext i am still confused about the ajaxcontext and how to capture 404 return codes however i have another question i am reading something about coding with success and fail and no longer using error in the recent versions of jquery so should i change my code to use done and fail how then could i check for a 404,['jquery'] +300817,how to set image to uiimage how can i set image to uiimage objectfor exampleuiimage img uiimage alloc initimg setimageuiimage imagenamedanyimagenamemy uiimage object is declared in h file and allocated in init method i need to set image in viewdidload methodany ideas,"['objective-c', 'ios']" +300821,how to correctly implement mvc in java with swing if you would like more details please let me know or refer to the last lines of this question i have already read a lot and i feel i am turning something simple into something complicated and i still get stuck here and there so maybe you can help me in those very specific points i am using netbeans ide 7 and jdk 7 and no frameworks the first window is a jframe and all other windows are jdialogs with modaltruequestionshow do i correctly implement the mvc pattern with swingfrom the ideas bellow which one is better a or b or maybe another one why is it betteramain mymodel modelmyview viewmodelmyviewmycontrollerthis modelb mainmymodel modelmyview viewmycontroller controllerview modelwhen i click jbutton1 in mainframe i need it to open the settingsframe for editing settings where should i instantiate the view the model and the controller of the settingsframe in mainframe controllerin terms of mvc organization and implementation how should i handle more specific features that apparently lacks one or two of the mvc legs either model or view or controller should i create empty classes for thema the implementation of a trayiconb a url connection class an httpsurlconnection which will update data in the main jframe and also uploaddownload filesc a directory monitor which will update data in the main jframe and also use the urlconnection to download a filed my own implementation of tablemodele jsonhow to correctly keep and use an object with settings through the whole application i will need it is information in different places views models controllers but it might be altered by user during the runtime is it a good idea to make this model a singletonwhat should i do whena view needs some data from the model what i am doing using the reference of model which i keep in the viewb view needs some data from the controllerwhat i am doing using the reference of controller which i keep in the viewc model needs some data from the controllerstill did not happen but i have no idea how to do correctlyd model needs some data from the viewwhat i am doing pulling all my hair from my heade controller needs some data from the viewwhat i am doing using the reference of the view which i keep in the controllerf controller needs some data from the modelwhat i am doing using the reference of the model which i keep in the controllerg one of foomodel fooview or foocontroller needs data from one of barmodel barview or barcontrollerwhat i am doing thinking of jumping from the highest buildingany hints on how to know if i implemented mvc correctly should i process massive data in model or controlleri am also using a dao what i am doing is my model has a arraylist mymodel loadmethod which creates an instance of the dao and returns the arraylist of models returned by the dao and then sometimes i process this arraylist of models in the model and sometimes i allow the controller to process it is this a good practice or is there a better way by process i mean iterate through the arraylist and get the data from the modelsi have a passwordcheck jdialog to restrict access to some views how can i reuse it in terms of mvc so that i can use the same passwordcheck dialog for allowingrestricting access to different views without doing a mess in the codeany other tips hints ideas suggestions contexti am required to develop a java swing mvc software in a short time although by default i am not a java developer and not so used to implement the mvc pattern specially in java i get the idea but sometimes it lacks me knowledge to implement the relationship between classes the applications is basically a monitor for localonline files with a jtable in the main frame to show this data i am using the new watchservice api to keep track of the local files and saving their info in a h2 database using a dao and them reload this data in the main frame jtable i must also notify the user about new files which for i am using trayicon for the online files monitoringuploadingdownloading i am using httpsurlconnection and json it may also allow settings customizationthanks in advance for you time and help,['java'] +300858,how to print the address of a function i let gcc compile the following example using wall pedanticinclude stdiohint mainvoid printfmain pn main line 5 printfmain pn void main line 6 return 0i getmainc5 warning format apa expects type avoid a but argument 2 has type aint amainc6 warning iso c forbids conversion of function pointer to object pointer typeline 5 made my change the code like in line 6what am i missing to remove the warning when printing a functions address,['c'] +300876,profiling a dynamic pinvoke i am working on msil profiler and encountered problems with managedtounmanagedtransition and unmanagedtomanagedtransition callbacks of icorprofilercallback interfacewhat i want to retrieve is an information about method being called name and module name it resides inso far it was working fine until so called dynamic pinvoke occured described in detail at 2800 c 23002900 aspxin this scenario imetadataimportgetpinvokemap fails also imetadataassemblyimportgetassemblyprops returns dynamic pinvoke as a name of the assemblyprofiler 1 0gettokenandmetadatafromfunctionfunction id iid imetadataimport iunknown imd import md tokenimd importgetpinvokemapmd token mapping module name buffer size chars read md module ref here the fail occursprofiler 1 0gettokenandmetadatafromfunctionfunction id iid imetadataassemblyimport iunknown imd assembly import md tokenimd assembly importgetassemblyfromscopemd assemblyimd assembly importgetassemblypropsmd assembly 0 0 0 assembly name buffer size chars read 0 0 assembly name is set to dynamic pinvokehow to obtain a module name dll and a name of function being pinvoked through dynamic pinvoke,['c++'] +300879,cllocationmanager monitoring regions vs significant location changes i am currently using significant location change updates to monitor whether or not the user has entered a particular area of interest my definition of an area of interest is more broad than can be defined simply by geographic regions my requirements are that my app should be woken up periodically to check if the user is said defined area if it is not currently runningmy question is would registering for region updates since i have a number of regions that are known to fit my area of interest provide me with more updates than simply listening for all significant lcoation changes or would they simply be duplicate updates the reason i ask this question is to clairify whether or not region monitoring is simply a filter on significant location change updates since neither are documented as powering the gps or if region monitoring somehow is able to be more specific maybe it powers the gps but with more specificity in particular i would be interested to know if anyone has seen data or documentation on this issuethanks,['ios'] +300886,thisplay special characters using systemoutprintln i am having trouble sending or thisplaying text with special characters from my webservice to my database on my eclipse i have set the character encoding to utf8 but it still does not let me thisplay the characters for example a simple print like the code belowstring test n 2n systemoutprintlntestorstring test n 2nstring query insert into communication test values test preparedstatement preparedstmt1 conpreparestatementquerypreparedstmt1executeupdatethe result on the console and if i send this to my database is how do i get this to thisplay correctly on the console and hopefully in the database,['java'] +300912,wcf data services maxprotocolversion set at v2 despite service set at v3 ends up throwing error on oftype i am having a problem that when i attempt to do a linq query against my odata service with the oftype method i get an error saying that the request is not valid for a version 2 service i have created the wcf data service and have set the maxprotocolversion to v3public class testdirectorysearch dataservicetestdirectoryentities public static void initializeservicedataserviceconfiguration config configsetentitysetaccessrule entitysetrightsallread configsetentitysetpagesize 50 configuseverboseerrors true configdataservicebehaviormaxprotocolversion systemdataservicescommondataserviceprotocolversionv3 my edmx has the following lineedmxdataservices mdataserviceversion10 mmaxdataserviceversion30 xmlnsmwhen i attempt to do the following query i get an error saying that the the method oftype is not supported when maxprotocolversion is less than 30from test in contexttestsoftypeorderabletest where testtestrevisionidequalsmmtrevisionid select new reflex testreflextest shiptemp testspecimentemperature null null testspecimentemperaturethisplaydescription firstordefaultif i check the maxprotocolversion of my context it is set at v2 at what point is this failing what can i do to set this correctlyexact errorthe method oftype is not supported when maxprotocolversion is less than 30requested stack traceat systemdataservicesclientresourcebinderanalyzeoftypemethodcallexpression mce dataserviceprotocolversion maxprotocolversionat systemdataservicesclientresourcebindervisitmethodcallmethodcallexpression mceat systemdataservicesclientalinqexpressionvisitorvisitexpression expat systemdataservicesclientdataservicealinqexpressionvisitorvisitexpression expat systemdataservicesclientalinqexpressionvisitorvisitexpressionlistreadonlycollection1 originalat systemdataservicesclientalinqexpressionvisitorvisitmethodcallmethodcallexpression mat systemdataservicesclientresourcebindervisitmethodcallmethodcallexpression mceat systemdataservicesclientalinqexpressionvisitorvisitexpression expat systemdataservicesclientdataservicealinqexpressionvisitorvisitexpression expat systemdataservicesclientresourcebinderanalyzeprojectionmethodcallexpression mce sequencemethod sequencemethod expression eat systemdataservicesclientresourcebindervisitmethodcallmethodcallexpression mceat systemdataservicesclientalinqexpressionvisitorvisitexpression expat systemdataservicesclientdataservicealinqexpressionvisitorvisitexpression expat systemdataservicesclientalinqexpressionvisitorvisitexpressionlistreadonlycollection1 originalat systemdataservicesclientalinqexpressionvisitorvisitmethodcallmethodcallexpression mat systemdataservicesclientresourcebindervisitmethodcallmethodcallexpression mceat systemdataservicesclientalinqexpressionvisitorvisitexpression expat systemdataservicesclientdataservicealinqexpressionvisitorvisitexpression expat systemdataservicesclientresourcebinderbindexpression e dataservicecontext contextat systemdataservicesclientdataservicequeryprovidertranslateexpression eat systemdataservicesclientdataservicequery1translateat systemdataservicesclientdataservicequery1executeat systemdataservicesclientdataservicequery1getenumeratorat systemlinqenumerablefirstordefaulttsourceienumerable1 sourceat systemdataservicesclientdataservicequeryproviderreturnsingletontelementexpression expressionat systemdataservicesclientdataservicequeryproviderexecutetresultexpression expressionat systemlinqqueryablefirstordefaulttsourceiqueryable1 sourceat tdmixblltestdirectoryservicehandlerpopulateorderabletestinfomonitoredmixtest mmt in cdevtdmixansr tdmixtdmix2tdmixblltdmixblltestdirectoryservicehandlercsline 161at tdmixblltestdirectoryservicehandlerpopulatetestinfomonitoredmixtest test in cdevtdmixansr tdmixtdmix2tdmixblltdmixblltestdirectoryservicehandlercsline 124at tdmixblltestdirectoryservicehandlergettestint64 testrevisionid in cdevtdmixansr tdmixtdmix2tdmixblltdmixblltestdirectoryservicehandlercsline 112at tdmixblltestdirectoryservicehandlerpopulatetestslist1 teststopopulate in cdevtdmixansr tdmixtdmix2tdmixblltdmixblltestdirectoryservicehandlercsline 66at tdmix2teststestretrievalteststestpopulate in cdevtdmixansr tdmixtdmix2tdmix2teststestretrievaltestscsline 38,['c#'] +300928,c increment number and keep zeros in front i need to make a 40 digit counter variable it should begin as 01 and increment to 02 when i use the int class it cuts off all the zeros problem is i need to increment the number and then convert it to a string with the correct number of leading zeros the total size should be 40 digits so if i hit 50 for example it should look like this 050how can i do that and retain the zeros,['c#'] +300957,when to use select for update please help me understand the usecase behind select for updatequestion 1 is the following a good example of when select for update should be usedgivenroomsidtagsid nameroom tagsroom id tag idroom id and tag id are foreign keysthe application wants to list all rooms and their tags but needs to differentiate between rooms with no tags versus rooms that have been removed if select for update is not used what could happen isinitiallyrooms contains id 1tags contains id 1 name catsroom tags contains room id 1 tag id 1thread 1 select id from roomsreturns id 1thread 2 delete from room tags where room id 1thread 2 delete from rooms where id 1thread 2 commits the transactionthread 1 select tagsname from room tags tags where room tagstag id 1 and tagsid room tagstag idreturns an empty listnow thread 1 thinks that room 1 has no tags but in reality the room has been removed to solve this problem thread 1 should select id from rooms for update thereby preventing thread 2 from deleting from rooms until thread 1 is done is that correctquestion 2 when should one use serializable transaction isolation versus read committed with select for updateanswers are expected to be portable not databasespecific if that is not possible please explain why,"['mysql', 'sql']" +300974,suppress expected an identifier and instead saw default a reserved word in jslint with mongoose i am using jshint to validate my javascript fileson the serverside i am using nodejs with mongoose in mongoose i am encouraged to write schemata in a fashion likevar userschema new mongooseschema firstname type string default when running linting i get errorexpected an identifier and instead saw default a reserved wordis there a way to suppress this error i really would prefer that behaviour instead of writingvar userschema new mongooseschema firstname type string default,['javascript'] +300977,does ios app metadata rejected means binary is good i recently got a phone call from apple saying they would reject our app since there is a problem with the metadata i asked whether there is a problem with the app itself and she said she does not know because she is not part of the review team she said it should be ok so i changed my metadata and resubmit the app and the status now is in review according to itunesconnect programmer guide they will reuse the binary does that mean the binary is good is it possible that they will take a look at the app again and reject me for some reasons other than they specified in the resolution centrei know this is a question that probably only apple can answer but this is our first app so i do not really know how it works i asked apple but they did not tell me anything,['ios'] +301001,in oracle why is false this question comes from my previous posti am curious as to whyselect from tpm user where returns zero rows howeverselect from tpm user where 1 1returns every row in the table is this per sql standard or is this oracle specificoracle sql fiddlethe following work as expectedpostgresql sql fiddlesql server sql fiddlemysql sql fiddle,['sql'] +301008,show python doc strings for the current function in sublime text 2 i just found sublime text 2 and it is awesome the only thing i really miss is the ability to view the doc string of the function i am dealing with are there any plugins that can do thisfor exampledef fx a doc string for f print xf at this point either automatically or with a keystroke i would like to be able to somehow view a doc string for fedit i have already attempted to using sublimecodeintel and sublimerope neither have such supportedit2 it should also work for other modules in the open project,['python'] +301017,how to check type of files without extensions in python i have a folder full of files and these does not have an extension how can i check file types i want to check the file type and change the filename accordingly let us assume a function filetypex returns file type like png i want to do thisfiles oslistdirfor f in files osrenamef ffiletypefhow do i do this,['python'] +301032,how to run untrusted code serverside i am trying to run untrusted javascript code in linux nodejs with the sandbox module but it is broken all i need is to let users write javascript programs that printout some text no other io is allowed and just plain javascript is to be used no other node modulesif it is not really possible to do what other language do you suggest for this kind of task the minimal feature set i need is some math regexes string manipulation and basic json functionsscripts will run for let us say 5 seconds tops and then the process would be killed how can i achieve that,['javascript'] +301033,javascript digest manually authentication i read all the posts about digest authentication and i am trying but i have any problem i have a restlet with the digest authentication implemented and with a javascript api i am trying to authenticatefirst i do the xmlhttprequest post to the server from file to localhost81 so i have the cors problem but is solved well the server response with the 401 and with the wauthenticate header with thiswauthenticatedigest realmguard domain noncemtmzota5mjk1nte2ndo0nzy2njjiotgymje1zdc0owu3nzm5mtkzmwnjngqznw algorithmmd5 qopauthso i take this header and apply the authentication digest algorithmfirst create 2 vars cnonce and nctokensobjcnonce bd5fd9b093dccaa1 inventedtokensobjnc 01i create in my literal object the uri parameter in the server response there are a domain i take the value of domain and put in the uri key of my objectafter i do the algorithmvar ha1 md5loginguardmypasswordvar ha2 md5postvar authresponse md5ha1 unquotestokensobjnonce tokensobjnc tokensobjcnonce unquotestokensobjqop ha2var responsecontentheader digest usernamelogin realm tokensobjrealm nonce tokensobjnonce uri tokensobjdomain algorithm tokensobjalgorithm response authresponse qop unquotestokensobjqop nc tokensobjnc cnonce tokensobjcnonce and i do the setrequestheaderauthorizationresponsecontentheaderso the final header that send to the server isauthorizationdigest usernamelogin realmguard nonce7d0c753c2fb4cdc9480403547952f1 uri algorithmmd5 responsee9d8ad8f04e42672f2c21d70257c1072 qopauth nc01 cnoncebd5fd9b093dccaa1but not works the server returns the 401 again all the cors headers are set ok so it is not the problem the server authentication digest is tested login with chrome and the header authorization that it puts is the same of mine obviusly the nonce is different someone seems anything that i may be goingthanks,['javascript'] +301049,how to configure staging env on heroku i have a rails app on heroku using the postgres 9 beta i have tried to configure a staging environment usingheroku configadd rack envstaging remote stagingbut the app still thinks its in a production envrailsenvproductionwhat am i doing wrong,['ruby-on-rails'] +301052,how many concurrent requests does a single flask process receive i am building an app with flask but i do not know much about wsgi and it is http base werkzeug when i start serving a flask application with gunicorn and 4 worker processes does this mean that i can handle 4 concurrent requestsi do mean concurrent requests and not requests per second or anything elsethanks,['python'] +301121,crystal reports error in setdatasource i am having trouble in vs 2010 sap crystalreports using c to make a windows applicationi get the following error with the following code crystalreport1 cr1 new crystalreport1 cr1setdatasourcedt1 error could not load file or assembly filecprogram files x86sap businessobjectscrystal reports for net framework 40commonsap businessobjects enterprise xi 40win64 x64dotnet1crdb adoplusdll or one of its dependencies the system cannot find the file specified,['c#'] +301138,how to hide twitter bootstrap dropdown this is getting annoying when i click on an item in a bootstrap dropdown the dropdown does not close i have it set up to open a facebox lightbox when you click the dropdown item but there is a problem with it what i have triedwhen the item is clicked i tried doing this dropdownopenremoveclassopen dropdownmenuhidethat hides it but then for some reason it would not open againas you can see i really need the dropdown to close because it looks crappy when it stays open mainly because the zindex of the dropdown is higher than the facebox modal box overlaywhy i am not using bootstraps builtin modal boxif youre wondering why i am not using the nicelooking modal box built into bootstrap it is becauseit does not have a way to load content into it with ajaxyou have to type html each time for the modal with facebox you can do a simple faceboxajaxassetsajaxdialogsdialogtypeblockuserid1234567it uses css3 animations to animate which looks very nice but in noncss3 browsers it just shows which does not look that nice facebox uses javascript to fade in so it works in all browsers,['jquery'] +301177,how to remove the end of a string starting from a given pattern let us say i have a string like thisvar str abcdefghijklx1x2how do i using javascript andor jquery remove the part of str starting with x till the end of str,['javascript'] +301184,isset postsubmit vs serverrequest methodpost i have come across scripts that useisset postsubmitas well as code that uses serverrequest methodposti was wondering the difference between these two and which method is best,['php'] +301212,jquery ui multi dates picker data range without weekends i am using this multidate picker is it possible to use date range mode where no weekends would be selectedi have already done multidatepicker where weekends are blocked and where user can select just 5 days but this is not my goal i would like this functionality when user clicks on specific date five days in range would be highlighted without weekend daysmy code bellowjquerydeliverydatemultidatespicker mindate0 beforeshowday noweekendsorholidays mode daysrangewithoutweekends autoselectrange 05 numberofmonths 2 now i am quite near of my own solutioni count all days which have to be enabled and all new day which have to be selected if there is weekend in range of daysi add my new method in multidatepickerjs daysrangewithoutweekends where i count all new and thisabled days then i use two foreach loops where i thisable and enable new dateseachall removed dates functionindex value methodsremovedatescallobj valueeachall new dates functionindex value methodsadatescallobjvaluevalue is date object first foreach loop works perfectly and remove all highlighted weekends but second loop does not work it returns me error empty array of dates receiveddo you know whyfor all you do not understand what my goal isi have to pick 5 day in range without weekends if i click on 2162012 dates 216 226 256 266 276 have to be selectedwith upper code i manage to remove highlighted class on weekends but do not know why second loop look my code upper does not highlighted 2662012 and 2762012,['jquery'] +301231,is there a way to prevent tinymce from auto focusing on page load i have got a number of input fields on my form one of which is using tinymce version 352 once tinymce loads it sets focus to itself how can i prevent this from happening i would like to keep the first input selected by defaultthis is what my code looks like right nowvar tinymce contenttinymcetinymce theme advanced plugins theme advanced buttons1 theme advanced buttons2 theme advanced buttons3 theme advanced buttons4 theme advanced toolbar location top theme advanced toolbar align left theme advanced statusbar location bottom theme advanced resizing true content css template external list url liststemplate listjs external link list url listslink listjs external image list url listsimage listjs media external list url listsmedia listjs template replace values username some user staffid 991234 updateafter some more testing it looks like this issue is only in ie9 chrome firefox opera safari do not set focus to the editor on page load ie9 in ie7 and ie8 mode does not set focus on page load either but ie9 itself will set focus to the editor even when you try to set focus to another input this all changes once you load the page with a value in the textarea though when you do that ie9 works like the other browsers for now i am loading the page with a single space in the textarea and that is making ie9 work correctly,"['javascript', 'jquery']" +301232,testing class equality in objectivec i am having problem understanding this part of testing class equality which is defined in apple guidein a dynamicallycreated subclass the class method is typically overridden such that the subclass masquerades as the class it replaces when testing for class equality you should therefore compare the values returned by the class method rather than those returned by lowerlevel functions put in terms of api the following inequalities pertain for dynamic subclassesobject class object getclassobject classobjectyou should therefore test two classes for equality as followsif objecta class objectb class,"['iphone', 'objective-c', 'ios']" +301240,does threadmxbeangetthreadcputime include time spent in all states or just runnable like the topic says does it include time spent in blocked and waiting etc states as well or is this just runnable the docs just say cpu time which is a bit vague,['java'] +301263,is there any api for formatting sphinx text i want to use sphinx text converting in my python program for example i have a string variable which contains this text note this is a note codeblock ruby some ruby codeand i want to call magic convert functionstring that will produce a html string like this onep classnotethis is a noteppcode classrubysome ruby codecodepis there any such function in sphinx apinote that i am not satisfied with pure restructuredtext i want to use some sphinxspecific language features,['python'] +301291,xml from sql column cannot call methods on nvarcharmax i have a sql query that is kicking back with an error on my column name saying cannot call methods on nvarcharmax select learner course xml testxml exquerydeclare namespace x xcmixcorextime taken as timetaken from learner course xml testthe issue seems to centre around xml exvalue but i have tried a few things including changing the column type but i have finally come unstuck any pointers would be greatly appreciated,['sql'] +301300,is it secure to store a php crypt result in the db for example with blowfish it returns something like2a12dezgcrshpxptoahooqwur6xe9h6pxfphocovflqdnw1tvyvneothat contains info about the type of hashing alg and it contains the salt a lot of resources say to just store this value in the db and it will be secure but could not someone just test a common list of passwords against these values to crack some of them,['php'] +301327,default values for systemthreadingthreadpoolsetmaxthreads suppose i do not set any values explicitly by calling the functionsystemthreadingthreadpoolsetmaxthreadswhat are the default values,"['c#', '.net']" +301343,get text from asptextbox i am writing aspnet project in cthe updateuserinfoaspx page consists textboxes and button in pageload method i set some text to the textbox and when button is cicked i get the new value of textbox and write it into dbthe problem is even if i have changed the value of textbox textboxtext method returns the old value of textbox sometext and write this into dbhere the methodsprotected void page loadobject sender eventargs e textboxtext sometextvoid btn clickobject sendereventargs e string textbox text textboxtext this is still equals somevalue even i change the textbox value writetodbtextbox textso how to make textbox to appear with somevalue initially but when user changes this value gettext method return the new changed value and write this into db,"['c#', 'asp.net']" +301354,what algorithm does pythons sorted use possible duplicateabout pythons built in sort method name says it alli am trying to explain to someone why they should use pythons builtin sorted function instead of rolling their own and i realized i have no idea what algorithm it usesif it matters were talking python 27,['python'] +301382,is it possible to for sql output clause to return a column not being inserted i have made some modifications to my database and i need to migrate the old data to the new tables for that i need to fill a table reportoptions taking the data from the original table practice and fill a second intermediate table practicereportoptionreportoption reportoptionid int pk field1 field2practice practiceid int pk field1 field2practicereportoption practicereportoptionid int pk practiceid int fk reportoptionid int fk field1 field2i made a query to get all the data i need to move from practice to reportoptions but i am having trouble to fill the intermediate tableauxiliary tablesdeclare reportoption table practiceid int this field is not on the actual reportoption table field1 field2declare practicereportoption table practiceid int reportoptionid int field1 field2first i get all the data i need to moveinsert into reportoptionselect ppracticeid field1 field2 from practice pi insert it into the new table but somehow i need to have the repation practiceid reportoptionidinsert into reportoption field1 field2output reportoptionpracticeid this is the field i do not know how to get insertedreportoptionid into practicereportoption practiceid reportoptionidselect field1 field2 from reportoptionthis would insert the relationship if i knew how to get itinsert into practicereportoption practiceid reportoptionidselect practiceid reportoptionid from reportoptionif i could reference a field that is not on the destination table on the output clause that would be great i think i cannot but i do not know for sure any ideas on how to accoplish my needthanks in advance,['sql'] +301398,printing chars as integers i want to control whether my ostream outputting of chars and unsigned chars via writes them as characters or integers i cannot find such an option in the standard library for now i have reverted to using multiple overloads on a set of alternative print functionsostream showostream os char s return os static castints ostream showostream os unsigned char s return os static castints is there a better way,['c++'] +301418,naive implementation of decorator pattern in objectivec i have read from the book cocoa design patterns that the decorator pattern is used in many cocoa classes including nsattributedstring which does not inherit from nsstring i looked at an implementation nsattributedstringm and it was over my head but i would be interested to know if anyone on so has successfully implemented this pattern and they are willing to sharethe requirements are adapted from this decorator pattern reference and since there are no abstract classes in objectivec the component and decorator should be suitably similar enough to abstract classes and serve their original purpose ie i do not think they can be protocols because you have to be able to do super operationi would be really thrilled to see some of your implementations of decorator,"['objective-c', 'ios']" +301426,create a blank html space on the fly javascript how do i create a blank space on the fly using javascript the following is not working for mevar blank documentcreateelementnbspdivappendchildblank,['javascript'] +301442,baffled by what to do to fix these errors iosany suggestions i am completely new to ios dev and using a book to learn following the directions in one of the early chapters i wrote a short app code below it just takes some text input and changes a labels text to match it however upon running the code in the simulator i get the following error upon clicking into the textfield 20120608 112606595 hellonoun14926f803 opening usersclhulibraryapplication supportiphone simulator51librarycachescomapplekeyboardsimages1859589221 failed no such file or directory 220120608 112606702 hellonoun14926f803 insert into store values constraint failed 19then when i press the button to set the label i get these errors as well20120608 112709050 hellonoun14926f803 uiview text unrecognized selector sent to instance 0xb75ac8020120608 112709051 hellonoun14926f803 terminating app due to uncaught exception nsinvalidargumentexception reason uiview text unrecognized selector sent to instance 0xb75ac80 first throw call stack0x13c7022 0x1558cd6 0x13c8cbd 0x132ded0 0x132dcb2 0x21a7 0x13c8e99 0x1414e 0x140e6 0xbaade 0xbafa7 0xba266 0x393c0 0x395e6 0x1fdc4 0x13634 0x12b1ef5 0x139b195 0x12f2 0x12fe8da 0x12fdd84 0x12fdc9b 0x12b07d8 0x12b088a 0x11626 0x1dad 0x1d15 terminate called throwing an exceptionlldb i have looked over my connections and retraced my steps several times now and do not see anything blatantly wrong although i am definitely very new to this could anyone help point me in the right direction thanksheres the code viewcontrollerhimport uikituikithinterface viewcontroller uiviewcontrollerproperty strong nonatomic iboutlet uilabel useroutputproperty strong nonatomic iboutlet uitextfield userinput ibactionsetoutputidsenderendand viewcontrollermimport viewcontrollerhimplementation viewcontrollersynthesize useroutputsynthesize userinput voidviewdidload super viewdidload do any additional setup after loading the view typically from a nib voidviewdidunload self setuseroutputnil self setuserinputnil super viewdidunload release any retained subviews of the main view boolshouldautorotatetointerfaceorientationuiinterfaceorientationinterfaceorientation return interfaceorientation uiinterfaceorientationportraitupsidedown ibactionsetoutputidsender selfuseroutputtext selfuserinputtextend,['ios'] +301444,why make defensive copies in getters inside immutable classes this question is about good programming practices and avoiding potential holesi read joshua blochs effective java and here is what i wonderwhy should i consider making defensive copies in getter methods in my immutable class with no mutators in itand second why should i make my fields final in addition to private is this only about performance not security,['java'] +301448,plot ellipse with matplotlibpyplot python sorry if this is a stupid question but is there an easy way to plot an ellipse with matplotlibpyplot in python i was hoping there would be something similar to matplotlibpyplotarrow but i cannot find anythingis the only way to do it using matplotlibpatches with draw artist or something similar i would hope that there is a simpler method but the documentation does not offer much helpthanks for any advice,['python'] +301458,contextobtainstyledattributes warning i just wasted 3 hours on this issue so i hope this will save somebody some timepublic typedarray obtainstyledattributes attributeset set int attrs int defstyleattr int defstyleresthe second argument attrs must contain the attribute identifiers in a strictly increasing order otherwise the attribute value would not get resolved and the call will silently fail as if the attribute did not existthis is no where documented that i can see and it took me forever to figure out what was going wrong,['android'] +301460,would i really want to return the minimum date an old work colleague used to quote his father about tools you have to be smarter than itin the code below resharper is telling me value assigned is not used in any execution path pointing to the first line if i accept its offer of help dt is not assigned a value todayis this a case where i have to be smarter than it and ignore their warning or is this a case where the tool is smarter than me and i am just not understanding itmy take on the situation is that if the if statement fails the current date is returned the default value i want but if i acquiesce to resharpers demands it would return the default value for datetime which is the minimum date which i assume is something like 741776 or 110 or sodatetime dt datetimenowif datetimetryparsesubstr out dt using var dtpdlgform new returndateplease select the date that the file was created if dtpdlgformshowdialog dialogresultok dt dtpdlgformreturnval return dt,['c#'] +301472,listagg equivalent with windowing clause in oracle the listagg function allows me to use it analytically with a over partition by column clause however it does not support use of windowing with the rows or range keywordsi have a data set from a store register simplified for the question note that the register tables quantity is always 1 one item one transaction linetranid tranline itemid orderid dollars quantity 1 101 23845 23 299 11 102 23845 23 299 11 103 23845 23 299 11 104 23845 23 299 11 105 23845 23 299 1i have to match this data to a table in an special order system where items are grouped by quantity note that the system can have the same item id on multiple lines components ordered may be different even if the item is the sameitemid orderid order line dollars quantity 23845 23 1 897 323845 23 2 598 2the only way i can match this data is by order id item id and dollar amountessentially i need to get to the following resultitemid orderid order line dollars quantity tran id tran lines 23845 23 1 897 3 1 10110210323845 23 2 598 2 1 104105i do not specifically care if the tran lines are ordered in any way all i care is that the dollar amounts match and that i do not reuse a line from the register in computing the total on the special order i do not need the tran lines broken out into a table this is for reporting purposes and the granularity never goes back down to the register transaction line levelmy initial thinking was that i can do this with analytic functions to do a best match to identify the the first set of rows that match to the dollar amount and quantity in the ordering system giving me a result set liketranid tranline itemid orderid dollars quantity cumdollar cumqty 1 101 23845 23 299 1 299 11 102 23845 23 299 1 598 21 103 23845 23 299 1 897 31 104 23845 23 299 1 1196 41 105 23845 23 299 1 1495 5so far so good but i then try to add listagg to my queryselect tranid tranline itemid orderid dollars quantity sumdollars over partition by tranid itemid orderid order by tranline cumdollar sumquantity over partition by tranid itemid orderid order by tranline cumqty listagg tranline within group order by tranid itemid orderid tranline over partition by tranid itemid orderidfrom tablei thiscover that it always returns a full agg instead of a cumulative aggtranid tranline itemid orderid dollars quantity cumdollar cumqty listagg 1 101 23845 23 299 1 299 1 1011021031041051 102 23845 23 299 1 598 2 1011021031041051 103 23845 23 299 1 897 3 1011021031041051 104 23845 23 299 1 1196 4 1011021031041051 105 23845 23 299 1 1495 5 101102103104105so this is not useful i would much prefer to do this in sql if at all possible i am aware that i can do this with cursors procedural logic is there any way to do windowing with the listagg analytic function or perhaps another analytic function which would support thisi am on 11gr2,['sql'] +301515,save photos to custom album in iphones photo library i am trying to create a custom album in the photo library of an iphone and then save photos that i have taken with the camera or chosen from the phones camera roll to that custom album i can successfully create the album but the photos are not getting saved there instead they are getting saved to the simulators saved photos album i am not sure how to tell uiimagewritetosavedphotosalbum to save to the new album i have just created using addassetsgroupalbumwithnamehere is the code i have so far i have snipped out a few sections to keep my code example short voidimagepickercontrolleruiimagepickercontroller picker didfinishpickingmediawithinfonsdictionary info nsstring mediatype info objectforkeyuiimagepickercontrollermediatype ifmediatype isequaltostring bridge nsstring kuttypeimage pull gps information from photos metadata using alassetslibrary void alassetslibraryassetforurlresultblockalasset alasset asset code snipped out nsurl asseturl info objectforkeyuiimagepickercontrollerreferenceurl alassetslibrary library alassetslibrary alloc init library assetforurlasseturl resultblockalassetslibraryassetforurlresultblock failureblocknserror error code snipped out getimage from imagepicker and resize it to the max size of the iphone screen uiimage originalimage info objectforkeyuiimagepickercontrolleroriginalimage uiimage resizedimage util createthumbnailforimageoriginalimage thumbnailsizeutil determineiphonescreensize nsdata imagedata uiimagepngrepresentationresizedimage code snipped out code snipped out code snipped out code snipped out code snipped out code snipped out create a new album called my apps photos library addassetsgroupalbumwithnamemy apps photos resultblockalassetsgroup group nslogin addassetsgroupalbumwithname resultblock save file to album uiimagewritetosavedphotosalbumresizedimage self nil nil failureblocknserror error nslogin addassetsgroupalbumwithname failureblock so like i said it creates the new album but does not save the photo there how do i tell it to save into the new album perhaps i sound not use uiimagewritetosavedphotosalbumnote i am using xcode 432 ios 51 and arc,"['iphone', 'objective-c']" +301529,leftalign image and center text on uibutton i have seen posts regarding right alignment but i cannot get leftalignment to work i want the button to take up the width of the screen with the image on the left and the titletext in the centerthis does not work at least reliably buttontitlelabeltextalignment uitextalignmentcenter button setimageedgeinsetsuiedgeinsetsmake0 600 0 0 buttonframe cgrectmakeselfviewframesizewidth w 2 selfviewframesizeheight 1400 selfviewframesizewidth 100 400,['ios'] +301566,get current year and month and next month in this format ymm in ruby how do i get the current date and month in ruby in a specific formatif today is june 8th of 2012 i want to get 201206and also i would like to be able to get the next month from the one we are in taking into account that in 201212 the next month would be 201301,['ruby'] +301578,in the cpp is there a way to autoimplement all the functions from its h i think this would increase the quality of life when devving but google came up with nothing and i could not find anything specific inside inside netbeans eitherwhat i want is to start with this headerclass blapublic static void gfgsomearg asdthen i open the blank blacpp and pressed autoimplement after that it would look like thisinclude blahstatic void blagfgsomearg asd todo implement throw unimplementedvoid blagfgsomearg is unimplementedanyone know of a tool like this,['c++'] +301589,returning by reference in javascript is it true that in javascript functions return objects other than boolean and numbers by referencehow is this possible when those objects are destroyed when the function they belong to terminates,['javascript'] +301593,php is variable an array or object trying to figure out how to do the equivalent of something i did in javascript but in php but i am not sure of the operators to do it in javascript i wanted to see if a particular parameter being passed was either an object or array and if not then was it a stringint and what i did was something likeif str instanceof array str instanceof object codeelse codeanyone know of the equivalent to this for php,['php'] +301639,better element for placing advertisements than i got really excited when i read this on mozilla publisher networkin html4 every section is part of the document outline but documents are often not that linear a document can have special sections containing information that is not part of though it is related to the main flow like an advertisement block or an explanation box html5 introduces the aside element allowing such sections to not be part of the main outlinei felt equally trumped when i came across this on html5 doctornavigation ads search boxes blogrolls and so on are not directly related to the article and therefore do not justify the use of an asideas such after quite a bit of googling i realized that people have mixed opinions some agree with the use of aside for content like ads but others do notcore problem i am building a technology blog and ever since the beginning i wanted the pages including the articles to be fullwidth this gives me little chance to place an ad in it google really does not like ads in between an articles contentand when i came across the aside element i thought i struck a gold mine until i saw the mixed opinions about its use for advertisementsso the question is can someone knowledgeable shed some light on whether it is okay to use aside for advertisements also are there any semantic alternatives element or markup,['html'] +301664,how to find element in view by coordinates xy android if i know coordinatesxy pixel by ontouchevent method and getxgety how i can find element ex button or text etc by use xy,['android'] +301699,composite primary key foreign key reference to object or key i have two classes foo and bar the tables in the database look like thisfooid int pk bar id int pk fk barid int pk normally i would map it like thisentitypublic class bar id columnname id private int id onetomany private setfoo fooentitypublic class foo embeddedid private foopk key mapsidbarid manytoone joincolumnname bar id referencedcolumnname id private bar barembeddablepublic class foopk columnname id private int id columnname bar id private int baridhowever the ids in foopk are loosely mapped and need to be connected manually i would prefer a solution that maps using objects in stead of loose idsi tried the following but of course it did not work but i think it gives an idea of what i would like to achieveentitypublic class bar id columnname id private int id onetomany private setfoo fooentitypublic class foo embeddedid private foopk key mapsidbarid manytoone joincolumnname bar id referencedcolumnname id accessaccesstypefield private bar getbar return keygetbar embeddablepublic class foopk columnname id private int id transient private bar bar columnname bar id accessaccesstypeproperty private int getbarid return bargetid another problem with the latter solution is that the getbarid method in foopk needs to have a setbaridint method setting the object using the id can be done by accessing the data access layer however this in my opinion violates the separation of businessdomaindata layersso what to do go with the first solution and keep the ids in sync manually or is there another best practice,['java'] +301703,nested directory creator phonegap how can i create a nested directory in phonegap with this apifilesystemrootgetdirectoryandroiddatacomphonegapmyappdir onedir two createtrue gotdir onerrori am using phonegap 180 in android 22,['android'] +301729,android java opencv 24 convexhull convexdefect opencv 24 androidjavai have searched for contours list of matofpoint like thisimgprocfindcontoursroi mat contours hierarchy cfgretmode cfgapxmodeand then the convexhull has to be a list of matofint for int k0 k contourssize k imgprocconvexhullcontoursgetk hullgetkthe convexhull wants a matofint but the drawcontours wants a matofpoint so what to dothx in advanceedit opencv4androidfor int k0 k contourssize k imgprocconvexhullcontoursgetk hullint forint j0 j hullinttolistsize j hullpointlistaddcontoursgetktolistgethullinttolistgetj hullpointmatfromlisthullpointlist hullpointsaddhullpointmat imgprocdrawcontours mroi hullpoints 1 new scalar25500 255 1,"['java', 'android']" +301732,inheritance and composite foreign keys one part of the key in base class the other part in derived class i am having problems to create an entity framework codefirst mapping for the following sample database schema in sql serverevery table contains a tenantid which is part of all composite primary and foreign keys multitenancya company is either a customer or a supplier and i try to model this via tablepertype tpt inheritance mappingpublic abstract class company public int tenantid get set public int companyid get set public int addressid get set public address address get set public class customer company public string customername get set public int salespersonid get set public person salesperson get set public class supplier company public string suppliername get set mapping with fluent apimodelbuilderentitycompany haskeyc new ctenantid ccompanyid modelbuilderentitycustomer totablecustomersmodelbuilderentitysupplier totablesuppliersthe base table companies has a onetomany relationship to an address every company has an address no matter if customer or supplier and i can create a mapping for this association modelbuilderentitycompany hasrequiredc caddress withmany hasforeignkeyc new ctenantid caddressid the foreign key is composed of one part of the primary key the tenantid and a separate column the addressid this works as you can see in the database schema from database perspective the relationship between customer and person is basically the same kind of onetomany relationship as between company and address the foreign key is composed again of the tenantid part of the primary key and the column salespersonid only a customer has a sales person not a supplier therefore the relationship is in the derived class this time not in the base classi try to create a mapping for this relationship with fluent api the same way as beforemodelbuilderentitycustomer hasrequiredc csalesperson withmany hasforeignkeyc new ctenantid csalespersonid but when ef tries to compile the model an invalidoperationexception is thrownthe foreign key component tenantid is not a declared property on type customer verify that it has not been explicitly excluded from the model and that it is a valid primitive propertyapparently i cannot compose a foreign key from a property in the base class and from another property in the derived class although in the database schema the foreign key is composed of columns both in the derived types table customeri tried two modifications to get it working perhapschanged the foreign key association between customer and person to an independent association ie removed the property salespersonid and then tried the mappingmodelbuilderentitycustomer hasrequiredc csalesperson withmany mapm mmapkeytenantid salespersonidit does not help i did not really hope it would and the exception isschema specified is not valid each property name in a type must be unique property name tenantid was already definedchanged tpt to tph mapping ie removed the two totable calls but it throws the same exceptioni see two workaroundsintroduce a salespersontenantid into the customer classpublic class customer company public string customername get set public int salespersontenantid get set public int salespersonid get set public person salesperson get set and the mappingmodelbuilderentitycustomer hasrequiredc csalesperson withmany hasforeignkeyc new csalespersontenantid csalespersonid i tested this and it works but i will have a new column salespersontenantid in the customers table in addition to the tenantid this column is redundant because both columns always must have the same value from business perspectiveabandon inheritance mapping and create onetoone mappings between company and customer and between company and supplier company must become a concrete type then not abstract and i would have two navigation properties in company but this model wouldnt express correctly that a company is either a customer or a supplier and cannot be both at the same time i did not test it but i believe it would worki paste the full example i tested with console application reference to ef 431 assembly downloaded via nuget in here if someone likes to experiment with itusing systemusing systemdataentitynamespace eftptcompositekeys public abstract class company public int tenantid get set public int companyid get set public int addressid get set public address address get set public class customer company public string customername get set public int salespersonid get set public person salesperson get set public class supplier company public string suppliername get set public class address public int tenantid get set public int addressid get set public string city get set public class person public int tenantid get set public int personid get set public string name get set public class mycontext dbcontext public dbsetcompany companies get set public dbsetaddress addresses get set public dbsetperson persons get set protected override void onmodelcreatingdbmodelbuilder modelbuilder modelbuilderentitycompany haskeyc new ctenantid ccompanyid modelbuilderentitycompany hasrequiredc caddress withmany hasforeignkeyc new ctenantid caddressid modelbuilderentitycustomer totablecustomers the following mapping does not work and causes an exception modelbuilderentitycustomer hasrequiredc csalesperson withmany hasforeignkeyc new ctenantid csalespersonid modelbuilderentitysupplier totablesuppliers modelbuilderentityaddress haskeya new atenantid aaddressid modelbuilderentityperson haskeyp new ptenantid ppersonid class program static void mainstring args databasesetinitializernew dropcreatedatabasealwaysmycontext using var ctx new mycontext try ctxdatabaseinitializetrue catch exception e throw question is there any way to map the database schema above to a class model with entity framework,['.net'] +301751,understanding androids webview addjavascriptinterface i know that to interact from javascript to java you have to inject a java object using the addjavascriptinterface method in webviewhere is the problem i am facingi register a java object using addjavascriptinterface method to be available in my jsi inject few js in the webview using webviewloadurljavascriptxi send a js event when i am done with injecting the jsthe problem is that if immediately after step 1 if i execute the following javascript mwebviewloadurljavascriptifwindowmyobject consolelogmyobject found else consolelogmyobject not foundi get myobject not found in my consoles logi want to know that if there is some time before i can access my object and if so how do i get to know how much time should i wait to call my object,"['java', 'javascript', 'android']" +301752,is there a man for python i am wondering if there is a cli like manpy dedicated to pythonexmanpy ossystem systemcommand exit status execute the command a string in a subshell,['python'] +301754,find position of element in c11 rangebased for loop assume i have the following codevectorint listforauto elemlist int i elemcan i find the position of elem in the vector without maintaining a separate iterator,['c++'] +301834,getting wpf listviewselecteditems in viewmodel there are some posts thiscussing adding databinding ability for listviewselecteditems with nontrivial amount of code in my scenario i do not need to set it from the viewmodel just getting selected items in order to perform action on them and it is triggered by command so push update is also not necessary is there a simple solution in terms of lines of code maybe in codebehind i am fine with codebehind as long as view and viewmodel do not need to reference each other i think this is a more generic question best practice for vm to get data from the view ondemand but i cannot seem to find anything,['.net'] +301874,recreating a removed view in backbone js the viewremove function in backbone js removes the container element of the view itself from the dom preventing from recreating views that have been removed any idea how this scenario is handledhere is my code var attributeview backboneviewextend el attrs template templateattrstemplatehtml initializefunction renderfunction eventname thiselhtmlthistemplatethismodeltojson return this thisposefunctioneventname thisunbind thisremove var attrview new attributeviewattrviewthisposelater on some event i do the belowattrview new attributeviewattrviewrenderthe last two lines above do not recreate the view as the div with idattrs is not longer there,['javascript'] +301881,choppylaggy scroll event on chrome and ie i am trying to have a content block always be shown to the user even if he scrolls way down the page he should also be able to scroll up and down the content block here is a fiddle with a stripped down version to show you what i meanone should notice when scrolling down until reaching the bottom of the red block it will fix the block on the window and when scrolling back up it places it back in firefox one can scroll up and down and the fixingunfixing described above is imperceptible a smooth as silkonce one tries scrolling in chrome or ie though it seems like the scroll event lags and one can see the block glitching for a second it is not code lag a it seems to be something with the browsersis there any way to fix this i am at my wit is end i would appreciate suggestions on how i can achieve the same effect in a different waythanks,"['javascript', 'jquery']" +301952,inputting elements of unknown type into a vector i am working on a program that takes elements from a user and sorts them for this program i have to use a vector as the size of the element list is unknown prior to user input our instructions werewrite a program in c to implement sorting of a list of elements elements can be of any type but will all be of same type like all integers or all floats or all chars or all strings strings shall be sorted like in a dictionary you can implement any sorting algorithm of your choiceask the user how many elements will be thereask the user to input elementsask the user to choose the sorting order ascending or descending or bothprint both input and output listsuser will not provide any information regarding the type of elementsi am not very familiar with vectors teacher basically skimmed topic in class and my book is not giving me a whole lot of information on the subject the problem i am running into is that i do not know the type of the element list until the user begins input so far i have triedcreating a void type vector obviously not allowed now that i have researched it oopsoverloading a function called insertinvector by sending the first element to the function and letting the function determine which vector type to create based on the type of the first element which seemed like my best option when i thought of it except i need access to the vector after the function terminates so that ended up being a no go tooinclude typeinfo in program finding the type of the first element and thencreating a vector using vectortypeidfirstelementname and honestly i am notsure why that did not work but it did notlike i said i have extremely limited experience with vectors as this is my first time using them i am also a fairly new programmer so a lot of the research i have done on this has gone over my head any help that could be given in this would be greatly appreciated,['c++'] +301991,androidattrselectableitembackground when writing my android app i usedandroidbackgroundandroidattrselectableitembackgroundi tried looking for attrxml file that would be containing the source but i could not find it any ideas please on where i can find it i found one attrxml in cprogram files x86androidandroidsdkplatformsandroid13dataresvaluesbut it did not have the attribute mentioned above can anyone lead me where i can find the xml resource with the attribute above,['android'] +302000,uiscrollview setcontentoffset with non linear animation hello stackoverflow i am trying to reproduce the smooth animation of a scrollview with paging enabled when you actually scroll to the next page it seems to be uiviewanimationcurveeaseinout but i need to have a next page button and trig the scroll programmaticallyhere is my code void scrolltopageintpage uiscrollview scrollview contentview cgpoint offset cgpointmakescrollviewboundssizewidth page scrollviewcontentoffsety scrollview setcontentoffsetoffset animated yes self pagecontrolupdatevoid scrolltonextpage self scrolltopagepagecontrolcurrentpage 1i cannot manage to reproduce the smoothness of uiviewanimationcurveeaseinout either with setcontentoffset or with scrollrecttovisible it goes to the next page with an ugly linear animationi even tried to animate it manually uiview animatewithduration5 delay0 optionsuiviewanimationcurveeaseinout animations scrollviewcontentoffset offset completionbool finished where am i wrong many thanks in advance i am stuck on this for several days,"['iphone', 'ios']" +302010,libgdx setup ui gives 2 unexpected errors in new gwt project i have run the setup ui however i get two different errors in the html project than what is described in the tutorial libgdx tutorialthe tutorial error stated is as follows which is an error i do not seeto fix the error of the html5gwt project go to the problems view right click the error message the gwt sdk jar gwtservletjar is missing in the webinflib directory and select quick fix click finishthe errors i have arethe project was not built since its build path is incomplete cannot find the class file for comgooglegwtcorecliententrypoint fix the build path then try building this project the type comgooglegwtcorecliententrypoint cannot be resolved it is indirectly referenced from required class files is there anyway i can fix this i just updated my eclipse i also downloaded version 18 adt revision 19 for android sdk tools and revision 11 for android sdk platformtools,['android'] +302016,what is the best way to design a city state country table i need help designing my country city state tables i will provide sample data from my table so that you can help me better on my problemthis is my country tablecountry code nameus united statessg singaporegb united kingdomthis is my city tablecity id country city state1 us birmingham alabama2 us auburn alabama29 gb cambridge null30 gb devon nullmy problem is that the only country that has the state field is the us all other cities have a null valuemy temporary solution for this is to just create a special city table for the united states then all other countries have another city table that does not have the state fieldi think this will just complicate the matter because i have two tables for citieshow can i improve this design,['mysql'] +302032,proguard keep class names hello i am writing an android app and i have set up proguard to obfuscate my application i however use a classloader to dynamically load different extensions to my application the problem is that these do not load correctly if their names are changed how do i keep proguard from obfuscating specific class names,"['java', 'android']" +302049,pandas combine two columns in a dataframe i have a pandas dataframe that has multiple columns in itindex 239897 entries 20120511 1520 to 20120602 234451data columnsfoo 11516 nonnull valuesbar 228381 nonnull valuestime utc 239897 nonnull valuesdtstamp 239897 nonnull valuesdtypes float644 object1where foo and bar are columns which contain the same data yet are named differently is there are a way to move the rows which make up foo into bar ideally whilst maintaining the name of bar in the end the dataframe should appear asindex 239897 entries 20120511 1520 to 20120602 234451data columnsbar 239897 nonnull valuestime utc 239897 nonnull valuesdtstamp 239897 nonnull valuesdtypes float644 object1that is the nan values that made up bar were replaced by the values from foo,['python'] +302052,fragment animation difference between setcustomanimations and settransitionstyle i would like to animate the transition between two fragments which is performed thanks to fragmenttransactionreplace i would like to specify my custom animation in a xml filewhat is the difference between calling fragmenttransactionsetcustomanimations and fragmenttransactionsettransitionstyle thanks,['android'] +302073,crosscompilation for raspberry pi in gcc where to start tldr where can i find more information about building a gcc 470 crosscompiling toolchain for arm gnueabi platform intended to run on a raspberry pi devicei have just got a brand new raspberry pi and i am very eager to start programming for it i have managed to install the gcc toolchain i am using the arch linux system image and compiled some basic programs all working finei have also tried to compile the boost libraries because i often use them in my projects and everything seemed to work fine by following the instructions bootstrapsh b2 except for the fact that the compilation was painfully slow i left it on for a few hours but it barely got past the first few source files after i left it running for the night i thiscovered that the build process aborted due to ram shortageso my guess is that rasp pi is simply underpowered for compiling something of such size as boost so crosscompilation comes to my mind however even though there is a lot of information about arm cross compilation available online i find it confusing where does one even start i have a recent gcc version 470 available on my raspberry pi so i would ideally like to crosscompile with the same version where can i get the gcc 470 toolchain for arm i will be compiling on x86 centos 62editi deallocated unneeded gpu memory and set up a 4gb swap partition on a usb drive while build files are on a nfs share boost is now compiling much much faster so it is manageable i would still like to know how can i set up a gcc 47 toolchain for cross compilation on my x86 pc though since i intend to do a lot of compiling and i would like it to be as fast as possibleedit 2since gcc 470 is relatively new there does not seem to be a prebuilt crosscompiler i386arm i will probably have to build one myself which seems an nontrivial task i have tried and failed does anyone know of a tutorial to follow for building a gcc crosscompiler hopefully for one of the recent versions i have tried with this great shell script which worked great for building a samearch compiler and i have successfully built binutils and gccs prerequisites but then gcc build kept failing with many cryptic errors i am really lost here so i would greatly appreciate your helpgcc on raspberry pi was configured withprefixusr libdirusrlib libexecdirusrlib mandirusrshareman infodirusrshareinfo withbugurl enablelanguagesccfortranltoobjcobjc enableshared enablethreadsposix withsystemzlib enable cxa atexit thisablelibunwindexceptions enableclocalegnu thisablelibstdcxxpch enablelibstdcxxtime enablegnuuniqueobject enablelinkerbuildid withppl enablecloogbackendisl enablelto enablegold enablelddefault enableplugin withpluginldldgold withlinkerhashstylegnu thisablemultilib thisablelibssp thisablebuildwithcxx thisablebuildpoststage1withcxx enablecheckingrelease hostarmunknownlinuxgnueabi buildarmunknownlinuxgnueabi edit 3i managed to build a 47 gcc toolchain for arm yay using this shell script as suggested by user dwelch in the comments i also built newlib and libstdc using this article as a guide the toolchain works fine but hen i run the executable on my raspberry pi it fails with illegal instruction what could be the cause of that,['c++'] +302088,parallax getting text to scroll at 110th speed i am trying to get the text to scroll at the same speed as its parent div which is scrolling at 110 speed currently it is scrolling at normal speed what am i doing incorrectly htmldiv idblank classpage pblah blah blahpdivcss body backgroundurlimagesbackgroundgif page overflow auto width 580px color white blank background urlimages02jpg 50 0 norepeat fixed height 2300pxjsblankparallax50 0 01 trueblank pparallax50 0 01 true,"['javascript', 'jquery', 'html', 'css']" +302108,any javascript or coffeescript map function that transforms object values is there no ubiquitousstandard javascript or coffeescript function that transforms the values of an objectmaphashjquery has map but it produces arrays onlyunderscore has map but it also produces arrays onlyto be clear a function like this one is what i am looking for this example is written in coffeescript not javascript transforms the values in a map does not modify obj a returns a new map example usage mapobjvals a aa b bb key value value a aa b bb mapobjvals obj f obj2 for k v of obj obj2k f k v obj2,['javascript'] +302156,does activemodel have a module that includes an update attributes method i have set up an activemodel class in my rails app like thisclass mythingy extend activemodelnaming extend activemodeltranslation include activemodelvalidations include activemodelconversion attr accessor username favorite color stuff def initializeparams set up stuff endendi really want to be able to do thisthingy mythingynewparamsthingyupdate attributesfavorite color red stuff other stuffi could just write update attributes on my own but i have a feeling it exists somewhere does it,['ruby-on-rails'] +302187,boost check equal with pair and custom operator when attempting to do a boost check equalpair pairgcc doesnt find the stream operator for pair inspite of declaring itthe funny thing is that stdout finds the operatorostream operatorostream s const pairintint p s pfirst psecond return sboost auto test caseworks pairintint expected5 5 pairintint actual 5 5 stdcout expected stdendl stdcout actual stdendl boost checkactual expectedboost auto test caseno work pairintint expected5 5 pairintint actual 5 5 boost check equalactual expectedthis doesnt compile with the error instantiated from hereboostatpreleaseincludeboosttesttest toolshpp3269 error no match for aoperatora in aostr ta,['c++'] +302212,foursquare api for venue user image error the foursquare api has divided its photo tag for user as prefix and suffix but if i merge them to form a full image url and paste this in my browser gives me errors that says the image cannot be thisplayed because it contains errors is it because server is temporarily unavailable or anything elsei am using the api for venue detaili got the data like thisuser id 26534686firstname bobbilastname ephoto prefix suffix k4vci4mxhwfugxofjpgvisibility public but when i call this url gives me errorany clue,['php'] +302213,use coffeescriptjavascript throw error or throw new errorerror i have the following coffeescript codetry do somethingcatch error log something throw errorshould i use throw new errorerror instead of throw errorwhat is the difference,['javascript'] +302227,how to speed up jquerymobile phonegap app i developed a iphone app with jquerymobile and phoenagap i minified all files with code deleted unused files but app is still quite slow problem is if i tap on button transformation will started appdrox after 1 second i would like to do pages transitions more quick i also thisable unused part od device camera etc but is it still slow can anybody help me with this problem i testing on iphone 4g,['iphone'] +302242,compiling sqlite for windows 64bit i have mingw and i wish to compile the sqlite amalgamation source into a 64bit dll i am fairly new to this sort of compilation and my efforts so far have resulted in failure i first started using the autoconf amalgamation and used the configure make tool on linux but apparently that will never work for windows binariesanyway i have been told i need the following preprocessor defineshere are the compiler preprocessor defines i use for a 64bit release buildwin64 ndebug windows usrdllno tcl crt secure no deprecatethreadsafe1temp store1sqlite max expr depth0here are the compiler preprocessor defines i use for a 32bit release buildwin32ndebug windows usrdllno tcl crt secure no deprecatethreadsafe1temp store1sqlite max expr depth0i had no idea where to put these in i eventually took an educated guess made a new file for neatness called sqlite3w64h and pasted in the followingdefine win64 ndebugdefine windowsdefine usrdlldefine no tcldefine crt secure no deprecatedefine threadsafe 1define temp store 1define sqlite max expr depth 0i then compiled the source with the following commandgcc sqlitew64h sqlite3h sqlite3exth shellc sqlite3c o sqlite x64dllwhat resulted was a 733kb dll file nice did it actually work did it nuts i got a badimageformatexception i also then tried doing an x86 compilation using the same method once again i got a 733kb dll file that is odd and once again i got a badimageformatexceptionhelpupdateused the following command insteadgcc shared dwin64 dndebug d windows d usrdll dno tcl d crt secure no deprecate dthreadsafe1 dtemp store1 dsqlite max expr depth0 i shellc sqlite3c o sqlite x64dll wloutimplibsqlite3aresulted in a 740kb dll file which still gives a badimageformatexceptionfinal updateturns out my mingw build was 32bit only getting a 64bit version then allowed me to make sqlite for 64bit adding the flag m64 sets the compiler into 64bit mode64bitgcc shared dwin64 dndebug d windows d usrdll dno tcl d crt secure no deprecate dthreadsafe1 dtemp store1 dsqlite max expr depth0 m64 i shellc sqlite3c o sqlite3 x64dll wloutimplibsqlite3 x64a32bitgcc shared dwin32 d windows d usrdll dno tcl d crt secure no deprecate dthreadsafe1 dtemp store1 dsqlite max expr depth0 m32 i shellc sqlite3c o sqlite3 x86dll wloutimplibsqlite3 x86amingw64 precompiled i686mingw 201220zipdownloaduse mirrorignuminstallation instructions,['c'] +302261,center text android button my question is very simplehow do i center the text on a button in androidi tried to set padding to 0 gravity to center but the result when i run it still that the text is horizontal centred but not vertical the text is a bit shifted to the bottombutton androidididbtnsame androidlayout widthwrap content androidlayout heightwrap content androidlayout gravitycenter androidlayout marginbottom10dip androidlayout marginleft10dip androidlayout marginright10dip androidbackgrounddrawablelayout button different androidgravitycenter verticalcenter horizontal androidheight30dp androidpadding0dip androidtextstringequals androidtextcolordrawablelayout button different androidtextsize50dp androidwidth70dp my be also relevantin activity i do thisbtnequalssetcompounddrawableswithintrinsicboundsnullgetresourcesgetdrawablerdrawableup2 null nullbtnequalssetpadding0 5 0 0btnequalssettextsize15this works but after this i set thisbtnequalssetcompounddrawablesnull null null nullbtnequalssetpadding0 0 0 0result is a bad vertical alignment,['android'] +302290,usage of this in destructor is it valid to call some function in destructor with this argumentfunction does not store pointer but assume fullfunctional object,['c++'] +302352,should i wrap calls to debuggerlog in if debug is it necessary to wrap calls to debuggerlog in the if debug preprocessor directive for the purpose of code optimization or will the c compiler still produce optimized code when building the release configuration,['c#'] +302359,using bank accounts with authorizenet c sdk after playing around with the authorizenet cim xml api c sample code i started using the authorizenet c sdk i am able to add credit cards and bank accounts to customer profiles using the cim xml api sample code i do not see how to add bank accounts using the sdk thoughadding bank account with cim xml apicustomerpaymentprofiletype new payment profile new customerpaymentprofiletypepaymenttype new payment new paymenttypebankaccounttype new bank new bankaccounttypenew banknameonaccount xyznew bankaccountnumber 41new bankroutingnumber 325070760new paymentitem new banknew payment profilepayment new paymentcreatecustomerpaymentprofilerequest request new createcustomerpaymentprofilerequestxmlapiutilitiespopulatemerchantauthenticationanetapirequestrequestrequestcustomerprofileid profile idtostringrequestpaymentprofile new payment profilerequestvalidationmode validationmodeenumtestmodeusing the sdk i only see a addcreditcard method but no way to add a bank account when i loop through all my paymentprofiles it throws an exception when it comes across a bank account toocustomergateway cg new customergatewayx yforeach string cid in cggetcustomerids customer c cggetcustomercid foreach paymentprofile pp in cpaymentprofiles consolewritelinepptostring exceptionunable to cast object of type authorizenetapicorebankaccountmaskedtype to type authorizenetapicorecreditcardmaskedtypehow do i add a bank account to a cim profile using the authorizenet c sdkupdateproof that cim can store bank account information,['c#'] +302371,get the visual studio color scheme from a vspackage somebody know how can i get the color scheme programatically using a vspackage in ci know that i can use ivsuishell5getthemedcolor for vs2011 but i do not know how to get it from vs2005 vs2008 or vs2010thanks in advance,"['c#', '.net']" +302427,multi language localization storyboard support issue i have an issue with my project storyboard i have added two localizations more to storyboard so now i have three storyboards spanish english and basque all of them depending from the main onenow i have the issue that i have to update all changes manually to all to storyboards because if i do changes to mainstoryboard the others are not updated with this changeshow can i modify all storyboards at the same timethanks,['objective-c'] +302440,post parameter is always null since upgrading to rc for webapi i am having some real odd issue when calling post on my webapii have even gone back to the basic version generated on new project sopublic void poststring valueand calling from fiddlerheaderuseragent fiddlerhost localhost60725contenttype applicationjsoncontentlength 29body value testwhen i debug the string value is never being assigned to it is just always nullanyone having this issuei first saw the issue with a more complex typethe problem is not only bound to aspnet mvc 4 the same problem occurs for a fresh aspnet mvc 3 project after rc installation,"['c#', '.net']" +302483,memory image decrease i am running this codeinclude iostreaminclude cstddefint mainint argc char argv int a10 a20 int a3a4 int b1a1 int b2a2 intp1a1 intp2a1 size t st ptrdiff t pt int i0 whiletrue printfi di printfnni now is dni return 0why do i observe such decrease in image memory fioletlegendi made this general win32 project not clri changed the code so i will see when int has become finally negative now the while is int i0 while0i printfi di printfnni now is dniit is strange please see what happend after just 30 iterations why do we see these fluctuations in the image memory i can see now that probably this is involved with vmmap itself because it heppens only if i choose launch trace a new process but not when view a running process and point to running exe fired from vs2010 here is the screen of process launched tracedi observed also huge paging of memory which started roughly with this decline in image this paging nearly accelerated and quickly triggered ram limit that i have set to 2gband here is a running process only viewed runned from vs2010so maybe some issue subject to memory management of the net applications takes place herei am still waiting for my int to cross boundary of two complementwell i have to edit again it turns out that as previously thought the decreasing memory image effect is present when process is only viewed not launched too below is attached picture of the same process 10 minutes later still waiting for turning int into negativeand here it isso the biggest positive 2complement on my machine is 2 147 483 647 and smallest negative is 2 147 483 648 what is easy to verify this wayinclude limitsconst int min int stdnumeric limitsintminconst int max int stdnumeric limitsintmaxit gave me the same result 2 147 483 648 and 2 147 483 647back to the beginningwhen i comment everything but the while loop the same thing happens image is decreasing after process was running about 10 minutes so it is not the useless code that cause this but what,['c++'] +302488,how do you insert a template into another template i have a very basic template basic templatehtml and want to fill in the with data formatted using another partial template the basic templatehtml might contain several things formatted using the partial templatehow should i structure the code in viewspythe reason i am doing this is that later on the will be filled using ajax am i doing this right,['html'] +302499,android app a wants to track google play referral data for android app b installation let us say i have an android app a that is installed in the users device and i have an appwidget with my app where we let other android developers publish their app promotion ads on a cost per install basis so we need to track if app b is being installed on the users device through app as referrallet us also assume android app b has its advertisement running on android app as widget and the link through which we redirect app as users to app bs user to google play is with all referrer data the url looks like this as recommended here referrerutm source3dtooyoou26utm medium3dbanner26utm term3dfoursquare26utm content3dfoursquaretooyoou26utm campaign3dfoursquareandroidif you hit the above link in your browser or make a qr code out of it and launch it it will take you to app b in google play with the required referral data now when app b is installed on the users device and launched for the first time the broadcast that app a expects to receive is comandroidvendinginstall referrer if the broadcast is received and the utm source is app a then record and process the transaction this is all we aim to dohere is app as androidmanifestxml code snippetapplication androidicondrawableic launcher androidlabelstringapp name androiddebuggabletrue activity androidnamelocatemeactivity androidlabelstringapp name intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity receiver androidnamecomlocatemeandroidreferralreceiver androidexportedtrue intentfilter action androidnamecomandroidvendinginstall referrer intentfilter receiver applicationpermissions added usespermission androidnameandroidpermissionaccess network stateusespermissionusespermission androidnameandroidpermissioninternetusespermissionhere is the broadcast receiver class referralreceiverjava that is supposed to process the broadcastimport javaiounsupportedencodingexceptionimport javaneturldecoderimport javautilhashmapimport javautilmapimport androidcontentbroadcastreceiverimport androidcontentcontextimport androidcontentintentimport androidcontentsharedpreferencesimport androidosbundlepublic class referralreceiver extends broadcastreceiver override public void onreceivecontext context intent intent workaround for android security issue try final bundle extras intentgetextras if extras null extrascontainskeynull catch final exception e return mapstring string referralparams new hashmapstring string return if this is not the right intent if intentgetactionequalscomandroidvendinginstall referrer nonnls1 return string referrer intentgetstringextrareferrer nonnls1 if referrer null referrerlength 0 return try remove any url encoding referrer urldecoderdecodereferrer xwformurlencoded nonnls1 catch unsupportedencodingexception e return parse the query string extracting the relevant data string params referrersplit nonnls1 for string param params string pair paramsplit nonnls1 referralparamsputpair0 pair1 referralreceiverstorereferralparamscontext referralparams private final static string expected parameters utm source utm medium utm term utm content utm campaign private final static string prefs file name referralparamsfile public static void storereferralparamscontext context mapstring string params sharedpreferences storage contextgetsharedpreferencesreferralreceiverprefs file name contextmode private sharedpreferenceseditor editor storageedit forstring key referralreceiverexpected parameters string value paramsgetkey ifvalue null editorputstringkey value editorcommit public static mapstring string retrievereferralparamscontext context hashmapstring string params new hashmapstring string sharedpreferences storage contextgetsharedpreferencesreferralreceiverprefs file name contextmode private forstring key referralreceiverexpected parameters string value storagegetstringkey null ifvalue null paramsputkey value return params the debugging device is on android os 234through a simple textview and button in the main activity of the app i try to thisplay the referral data captured by the receiver here is the call and thisplay referraltextsettextreferralreceiverretrievereferralparamsthisgetapplicationcontexttostringwhen i launch app bs referral link shown above go to google play install it and open it for the first time logcat does not show the broadcast comandroidvendinginstall referrer at all and hence the referral data when thisplayed shows an empty stringat the same time when i use adb command below the same broadcast receiver works like a charm and thisplays the referral dataam broadcast a comandroidvendinginstall referrer n comlocatemeandroidreferralreceiver es referrer utm sourcetooyoouutm mediumbannerutm termfoursquareutm contentfoursquaretooyoouutm campaignfoursquareandroidso does that mean the google play does not broadcast the referrer data and the expected intent at allor does it mean that it broadcasts the intent only for app b that is being installedor am i doing something wrongis this possible to achieve without app b having to insert our tracking sdk or code in their app just to advertise with usthanks so much in advance for your helpadditional info we are not using the google analytics sdk so we are using our custom broadcast receiver rather than googles brthe code above works like a charm i just followed lucas advice below in the answer marked correct and replaced xwformurlencoded to utf8 why i did not do this at first is because of what a mobile analytics company called localytics posted here their code has the same issue so basically what i have right now is that the above piece of code in an android app that i published in google play and then downloaded the app from google play from my android device running ics opened it and clicked on retrieve referral and it workedtry it for free here is the link referrerutm source3dtooyoou26utm medium3dbanner26utm term3dappdownload26utm content3dimage26utm campaign3dtooyooupromoanother very important thing that i want to reiterate is that the google play campaign referral tracking this way will not work if you are installing an app remotely on your device using google play from the web i have tested it and it is an open defect with google,['android'] +302502,can i have a c macro that accepts undefined number of parameters possible duplicatehow to make a variadic macro variable number of arguments i want to have a log macro in basic c which accepts arguments similar to printf and logs them however i want how it is logged log level file vs stderr etc to be something set at compile time not runtime with the method doing nothing and hopefully being optimized out of the code if i set parameters to ignore low level loggingso far i have a macro which is defined based off of a parameter defined at compile time if the parameter is defined logging goes to my log method to log to files otherwise it goes to stderr however i can only pass a string into this macro the log method is capable of taking an indefinite number of arguments and works using printf syntax i want to know if there is a way to set my macro up so it will pass an indefinite number of arguments to the log fileand since i suspect the answer is that i cannot do that is there another method of achieving what i want in basic c i cannot use c or boost,['c'] +302517,python how to toggle between two values i want to toggle between two values in python that is between 0 and 1 for example when i run a function the first time it yields the number 0 next time it yields 1 third time it is back to zero and so onsorry if this does not make sense but does anyone know a way to do this,['python'] +302651,django get current user in model save i want to get current logged in userrequestuser in save method of modelspy i want to check the role of the user and perform some operations based on his role i have given the modelspy code belowmodelspy class timesheetmodelsmodel check in time modelstimefield check out time modelstimefield class tasksmodelsmodel time sheet modelsforeignkeytimesheet project modelsforeignkeyproject start time modelstimefield end time modelstimefield def saveself args kwargs project spenttimeobjectsgetproject project id selfprojectid start datetimedatetimestrptimestrselfstart time hms end datetimedatetimestrptimestrselfend time hms time float02fformatend startseconds360 if commonisdesignerrequestuser spenttimeobjectsfilterproject project id selfprojectidupdatedesign floatprojectdesign time if commonisdeveloperrequestuser spenttimeobjectsfilterproject project id selfprojectidupdatedevelop floatprojectdevelop time supertasks selfsaveargs kwargshere the tasks model is being used as inline in timesheet model i want to check the role of current logged in user and update another model based on the users role here i need requestuser to check role of the current user i am not using any forms or templates and completely making use of django admin so is there any method to get requestuser in models save method or to check and update the values in another model in adminpy i have checked most of the similar questions in stackoverflow and none them provide me a perfect solution so please provide me an answer to fix this thanks in advance,['python'] +302652,android how to write multiple selectors in a single xml file in my applicationi have 4 imagebuttons and each imagebutton have different source image based on their statesso maintaining 4 separate xml files for each of the button is there any way to write all the selectors in a single xml file,['android'] +302676,can jquery be relied upon i am doing a piece of jquery code that will change the attributes within hundreds of html elementscan jquery be relied upon entirely to perform such tasksis there a chance that jquery code would leave my page inconsistenteg by not quite completing the task that i expect it to,['jquery'] +302679,how to create own mask in ios duplicate so do not negative my reputation my mask image is my output is uiimagemaskimageuiimage image withmaskuiimage maskimage cgimageref maskref maskimagecgimage cgimageref mask cgimagemaskcreate cgimagegetwidthmaskref cgimagegetheightmaskref cgimagegetbitspercomponentmaskref cgimagegetbitsperpixelmaskref cgimagegetbytesperrowmaskref cgimagegetdataprovidermaskref null false cgimageref masked cgimagecreatewithmaskimagecgimage mask cgimagereleasemask return uiimage imagewithcgimagemaskedso how to create my own mask imagethanks,"['iphone', 'ios']" +302728,forward declaration of class used in template function is not compiled by clang there is this codeclass atemplate class tvoid fun a aclass a public a int main funint return 0g 45 and g 47 compiles this without error but clang 32 trunk gives this errormaincpp56 error variable has incomplete type a a a maincpp17 note forward declaration of aclass a which compiler is right then according to c standard,['c++'] +302732,run java executable without installing jre possible duplicaterunning java without installing jre i am working on a java application i created an executable jar file of my application it works fine on my machine now i want to deploy it over the client machines which do not have jre locallyis there any way to run my executable jar file without installing jre locallyalternately what minimum files are required from the jre folder so i can pack them with my installation packagesuggestions are always welcome,['java'] +302773,setting up auto compile for stylus i have installed nodejsstylusnib on my mac and i can manually compile styl file to css on the command line i also know there is this stylusmiddleware things that keeps coming up when i search for how to setup autocompiling when the styl changes however i have no idea how i am supposed to implement it i have never used nodejs beforewhat file do i put that code inhow do i start this code so it is always runi think i am missing a few things on the node side to be able to set this up,['css'] +302796,how to remove specific elements in a numpy array how can i remove some specific elements from a numpy array say i haveimport numpy as npa nparray123456789i then want to remove 347 from a all i know is the index of the values index236,['python'] +302800,top border image in css3 i have used border bordertopimage borderimage and none seem to do what i am afteri have the following cssfooter overflow hidden clear both width 100 margin 0 auto padding 26px 0 30px 0 bordertopimage url fontsize 08461538461538462em color athis does not seem to apply to the website i am trying to work on i have tried it in firefox and chromei only want the image to appear on the top border and wish to have no other borders so it is sort of like a hr,['css'] +302803,inserting gujarati text into a mysql tables results in junk characters and unreadable text i have three mysql tables and i am inserting gujarati content into them when i insert two tables they are inserted fine and are readable but in one table it is showing junk charactersunreadable text how can i fix this,['mysql'] +302813,numberpicker in alertdialog always activates keyboard how to thisable this to alli am trying to get a simple numberpicker to work in a alertdialog the problem is that whenever i increasedecrease the value in the numberpicker the keyboard activatesthere are many posts describing this problem but none of the suggestions work i have triedandroidconfigchangeskeyboardkeyboardhiddenandinputmanagerhidesoftinputfromwindowcurrentviewgetwindowtoken 0and getwindowsetsoftinputmode windowmanagerlayoutparamssoft input state always hiddeni have tried calling these functions before and after initialization dialogshow on keypress events using listeners obviously etc but no luck so farthe complete codepopupxmlxml version10 encodingutf8relativelayout xmlnsandroid androidlayout widthfill parent androidlayout heightwrap content numberpicker androidlayout widthwrap content androidlayout heightwrap content androidididmynumber androidconfigchangeskeyboardkeyboardhidden relativelayoutand the calling functionalertdialogbuilder builder new alertdialogbuilderthisbuildersetpositivebuttonandroidrstringok new dialoginterfaceonclicklistener public void onclickdialoginterface dialog int which return buildersetnegativebuttonandroidrstringcancel new dialoginterfaceonclicklistener public void onclickdialoginterface dialog int which return view view getlayoutinflaterinflaterlayoutpopup nullbuildersetview viewfinal alertdialog dialog buildercreate numberpicker picker numberpicker viewfindviewbyidridmynumberpickersetminvalue0pickersetmaxvalue9dialoggetwindow setsoftinputmodewindowmanagerlayoutparamssoft input state always hiddendialogshow any help appreciatedbarry,['android'] +302814,qwidget update events but no visual update using qt48 on a mint linux 12 i implemented a simple window containing a qtableview to show contents of a model the model data is continually updated log messages and the datachanged signal is emitted on a regular basis ie every 100msthe problem i see is stuttering visual updates on the tablei installed an event filter on the window that counts updaterequesttype events which should trigger a widget repaint also on child widgets ie the tableview these come in with an average time of 170ms between them and a standard deviation of 90ms which is rather large i guess however the perceived visual update rate is only two or three times a second and i wonder why it seems that not all updaterequest events trigger a widget repaint or that the window system swallows visual updatesas a second test i forced the window to update itself by calling repaint or update every 100ms using repaint i saw a corresponding increase in updaterequesttype events and a decrease of the standard deviation of the gaps with update the number did not increase however there was only a moderate increase of perceived update rate in both casesalso is there a good method to measure how often a widget is actually really repainted without having to overload its paintevent handler maybe something from qtestupdate i extended my event filter to also catch painteventtype events there are only a onedigit number of those versus 10 updaterequesttype events,['c++'] +302862,why i get squares instead of text i tried to install and use a font in my wpf application but all i get is like thishere is the code i tried to use the fontrichtext1fontfamily sh roqathe expected result is snap shot from ms word if i try to add the font file to the project folder and use it as a resource like thisrichtext1fontfamily sh roqai would not get the square results but i would not have the expected font either what i get is tahoma fontwhich is not the targeted font please download the targeted font file here for experimentsany help is appreciatededitthe plain text for the above captured text isau uso for those who are experts with using fonts they can experiment with,['.net'] +302864,stdthread calling method of class possible duplicatestart thread with member function i have a small classclass testpublic void runmultithreadprivate int calculateint from int to how its possible to run method calculate with two differents set of parametrsfor example calculate010 calculate1120 in two threads from method runmultithreadps thanks i have forgotten that i need pass this as parameter,['c++'] +302871,is this an example of a closure in c static void mainstring args var s 3 funcint funcint func x return x var result1 funcs func null s 5 var result2 result1 consolewritelineresult2 consolereadkeymy understanding is that x is not actually declared as a variable eg var x 3 instead it is passed into the outer function which returns a function that returns the original value at the time it is returning this it creates a closure around x to remember its value then later on if you alter s it has no effectis this rightoutput is 3 by the way which i would expectedit heres a diagram as to why i think it isx3 is passed into the func and it returns a function that simply returns x but x does not exist in the inner function only its parent and its parent no longer exists after i make it null where is x stored when the inner function is ran it must create a closure from the parentfurther clarification int s 0 funcint funcint func x return x for s 0 s 5 s var result1 funcs var result2 result1 consolewritelineresult2 output is 0 1 2 3 4however with your examplestatic void mainstring args int s 0 funcint funcint func x return s listfuncint results new listfuncint for s 0 s 5 s resultsaddfuncs foreach var b in results consolewritelineb consolereadkeythe output is 5 5 5 5 5 which is not what you want it has not captured the value of the variable it is merely retained a reference to the original sclosures are created in javascript precisely to avoid this problem,['c#'] +302900,get raw post body in python flask regardless of contenttype header so while ago i asked similar questionhow to get whole request post body in python flaskand i got an answer that actually flaskrequestdata is the raw post body but that seems to work only if the request has few additional headersheaders contenttype binaryoctetstream contentlength lenpostbody contenttransferencoding binaryif those headers are not present the flaskrequestdata will be emptyfrom flask import flaskapp flask name approute methodspostdef parse request data flaskrequestdata but data will be empty unless the request has the proper contenttype headerso now i found the request is actually applicationxwformurlencoded which is default mimetype then i could take the data like thisapp flask name approute methodspostdef parse request data flaskrequestdata but data will be empty unless the request has the proper contenttype header if not data data requestformkeys0but i am not sure that i could count on itso is there a way to be able to obtain the raw post body of any post request regardless of the headers,['python'] +302901,space out every 4 numbers i have an input box which is limited to 16 numbers what i would like to do for aesthetics would be to place a gap per 4 numberseg when a person enters 1234567891234567it should look like this 1234 5678 9123 4567how would this be possible on key up in jquery,['jquery'] +302902,how can i update top 100 rows in db2 i know that in standard sql you can do thisupdate top 100 table1 set field1 1reference how can i update top 100 records in sql serverbut this is not allowed in db2 can anyone advise me on how to accomplish the same result in db2 thanks,['sql'] +302904,strange text wrapping with styled text in jtextpane with java 7 i have two different editors using jtextpane with strange bugs in java 7 that did not occur with the previous jvm versions it happens with long lines containing styled text or componentshere is an example demonstrating this bug in this example the default style is applied for all the text each time a character is inserted i tested it with the jdk 170 04import javaawtborderlayoutimport javaxswingimport javaxswingeventimport javaxswingtextpublic class bugwrapjava7 extends jframe jtextpane jtp styleddocument doc public bugwrapjava7 setdefaultcloseoperationjframeexit on close setlayoutnew borderlayout jtp new jtextpane addjtp borderlayoutcenter jtpsettextntype some text in the above empty line and check the wrapping behavior doc jtpgetstyleddocument docadocumentlistenernew documentlistener public void insertupdatedocumentevent e insert public void removeupdatedocumentevent e public void changedupdatedocumentevent e setsize200 200 setvisibletrue public void insert swingutilitiesinvokelaternew runnable public void run style defaultstyle jtpgetstylestylecontextdefault style docsetcharacterattributes0 docgetlength defaultstyle false public static void mainstring args new bugwrapjava7 my question is is there something wrong in my code or is it indeed a new bug introduced in java 7 and if it is a new jvm bug is there a workaround it might be related to question 86727 but the problem here lies in the wrong wrapping rather than the appearance of a scrollbar,['java'] +302930,cannot install xcode 45 preview i have downloaded xcode 45 preview and i cannot install it on a lion 1074 the installation freezes at the begining after clicking on install i have rebooted and it does not work anyone have the save problem or know how to finish the install freeze on this page edit i know that preview version of xcode are under nda but we are not talking about how xcode works but just how to install it on mac so i finally achieve this so diffucult task myself after opening the dmg file just copypaste xcode45dp1 file in any folder on your mac and double click on it thanks for closing my answer,"['iphone', 'ios']" +302934,how i can check whether a page is loaded completely or not in web driver i am writing some java webdriver code to automate my application how can i correctly check whether the page has been loaded or not the application has some ajax calls tooi have declared an implicit wait for webdriver,['jquery'] +302952,java split string performances here is the current code in my applicationstring ids strsplitwhen profiling the application i noticed that a non negligeable time is spent for splitting the stringi also learned that split actually takes a regular expression which is useless for me hereso my question is what alternative can i use in order to optimize the string splitting i have seen stringutilssplit but is it fasteri wouldve tried and tested myself but profiling my application takes a lot of time so if someone already knows the answer that is some time saved,['java'] +302962,get only part of an array in java i have an array of integers in java i would like use only a part of it i know in python you can do something like this arrayindex and it returns the array from the index is something like this possible in java,['java'] +303049,ios globally change navigation bar title color using appearance this crashes the appuinavigationbar appearance settitlecoloruicolor darkgraycolor forstateuicontrolstatenormalis there a way to do this using appearance,['ios'] +303052,access skydrive using php and oauth i would like to access skydrive using phpi want to retreive list of files and folders download upload and delete filesi have got a microsoft dev clientid and clientsecretcan anybody get me started with connecting to skydrive with oauth and making use of the apithanks a lot,['php'] +303053,using after css selector to fill a space on this page i wish to have the entire space to the right of the navigation filled in white so i achieved 5px wide white block using the after css selector and am hoping there is a way to make it fit the available width although i am open to other suggestionsmenumainmenuafter content thisplayblock backgroundf width5px height30px floatright here is the simplified htmldiv classmenuul idmenumainmenulia hrefhomealilia hrefabout usalilia hrefcourses 038 pricesalilia hrefactivities in rioalilia hrefaccommodationalilia hrefnewsalilia hreffaqsalilia hrefcontactaliuldivand all the relevant cssprimarymenu ul overflowhiddenprimarymenu li liststylenone floatleftprimarymenu a color3 background f thisplayblockprimarymenu currentmenuitem a primarymenu currentpageparent a colorf backgroundnonemenumainmenubefore contentthisplayblockbackgroundfwidth20pxheight30pxfloatleft menumainmenuafter contentthisplayblockbackgroundfwidth5pxheight30pxfloatrightthanks for taking the time to check out my questioncaroline,['css'] +303066,format mysql code inside php string is there any program ide or not that can format mysql code inside php string eg i use phpstorm ide and it cannot do itit does that for php and mysql but not for mysql inside php string i am ready to use new ide because now i have to manually format hundreds of database requests that are one line and not readable only criteria for my choice is that ide can do that automaticallyphprequest1 select from tbl admin where admin id sessionadmin id and active 1 order by admin id ascshould becomephprequest1 select from tbl admin where admin id sessionadmin id and active 1 order by admin id asc,"['php', 'mysql']" +303075,performance impact of hot and inline combination for a function definition i have a function which does just few operations such as increments i have declared that as inline and with the attribute hot gcc doc suggests following for hot attribute the hot attribute is used to inform the compiler that a function is a hot spot of the compiled program the function is optimized more aggressively and on many target it is placed into special subsection of the text section so all hot functions appears close together improving localitywhich can be interpreted as for non inline hot functions they would be placed in lower address area of the process address map but inline functions calls are supposed be literally replaced by their code so question is how does combination of inline and hot really works,['c'] +303078,localhost running on mac can i view it on my android phone running a ruby on rails project on my mac i need to test it on my android phone is there a way to view my mac localhost on my android phone,['android'] +303105,jquery scrollto fixed header offset i am using the jquery scrollto plugin as you can see on the page which i am building because of the 300px fixed header the content moves under the header you can see this clearly when you click the about button in the menu is it possible to add an 300px offset to the scrollto script so everything stays positioned under the headermenu,['jquery'] +303111,how to programmingly detect if the icloud is enabled on users device when only use nsubiquitouskeyvaluestore i am using nsubiquitouskeyvaluestore to sync some preference data to icloud i found that if the user thisable document data item of icloud in setting app nsubiquitouskeyvaluestore can not synchronize its data to icloud so i want to first check if this setting is switched onafter googlingi found this code snippeti14 nsurl ubiq nsfilemanager defaultmanager urlforubiquitycontaineridentifiernil nslogurlubiq if ubiq uialertview av uialertview alloc initwithtitlenil messageplease enable icloud in setting app delegateself cancelbuttontitleok otherbuttontitlesnil nil av show return what i want to know is whether this is the only way to detect even if i just use nsubiquitouskeyvaluestore not icloud document storage is there a better alternative,['ios'] +303138,fit text into svg element using d3js i want to write text inside a rectangle i create as followsbody d3selectbodysvg bodyappendsvgattrheight 600attrwidth 200 rect svgappendrecttransitionduration500attrwidth 150 attrheight 100 attrx 40 attry 100 stylefill white attrstroke black text svgappendtexttextthis is some information about whatever attrx 50 attry 150 attrfill blackahowever as you can see the text gets cut off any nifty ways to write a paragraph inside of the svg rectangle created thanks,['javascript'] +303145,how do i dump the contents of a hash map how can i dump the contents of a java hashmapor any other for example to stdout as an example suppose that i have a complex hashmap of the following structure student1 map name tim scores map math 10 physics 20 computers 30 place miami ranking array28113 student2 map so i would like to print it to the screen in order to get an idea about the data structurei am looking for something similar to phps var dump or perls dumper,['java'] +303154,change div background based on file chooser choice i am looking for a way to have a div background image change when the user chooses an image from a form input as you can see below i have a input type of file once the user chooses the file they want i would like the divimgholder to change the background based on the file chosen any thoughtsdiv idsimpledialog stylewidth 350px height 350px thisplaynone scrolltop0 br div idimgholder stylewidth200pxheight200pxbackgroundimage urlimagesgraypngdiv br form iduserform aligncenter fieldset legendartist infolegend input typefile nameartistimage idartistimage styleborder nonefloatleftbrbr label fortext stylefloatleftenter urllabel input typetext namewebsite idwebsite value requiredrequired fieldset form input typebutton idsubmit valuesubmit input typebutton idcancel valuecancel div,"['javascript', 'html']" +303196,addclass can add multiple classes on same div jquery add multiple classthis is my current code i know its wrong codepageaddresseditaddclasstest1addclasstest2,['jquery'] +303198,delegate pattern vs delegate keyword in c from msdn doc a delegate is a type that safely encapsulates a method similar to a function pointer in c and c unlike c function pointers delegates are objectoriented type safe and securei know what it is and how to use it but i wonder whether or not it is written base on delegate pattern that i know from wikipedia what is the difference between them,['c#'] +303200,how to reorder automatically generated methods in netbeans when using netbeans features for generating event handlers from a gui for example while the body of the generated methods are editable i cannot find a way to change the order of the generated methods within the code of a class cutting for cutting and pasting is not allowed with generated code how instead might i do thisthank you very much,['java'] +303203,is there a regular expression way to replace a set of characters with another set like shell tr command the shell tr command support replace one set of characters with another set for example echo hello tr az az will tranlate hello to helloin java however i must replace each character individually like the following10 dogs are racing replaceall 0 i14 replaceall 1 i14 replaceall 2 i14 replaceall 9 i14 replaceall a i14 the apachecommonslang library provides a convenient replacechars method to do such replacement halfwidth to fullwidthsystemoutprintln orgapachecommonslangstringutilsreplacechars 10 dogs are racing 0123456789abcdefeghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz i14i14i14i14i14i14i14i14i14i14i14i14i14i14i14i14i14i14i14 i14i14ai14i14i14i14i14 i14i14i142i143i14 i14i14i14i14 i141i14oi12i12i12i12i12i12i12i12i12i12i12i12i12i12i12i12i12i12i12i12i12i12i12i12i12i12 result i14i14 i14i12i12i12 i14i12i12 i142i12i12i12i12i12but as you can see sometime the searchcharsreplacechars are too long also too boring please find a duplicated character in it if you want and can be expressed by a simple regular expression 09azazi14i14i14i14oi12i12 is there a regular expression way to achieve that,['java'] +303207,human face emotion and voice recognition i am looking for a good face emotion and voice recognition method in c for face recognition i was early using emgu cv which is not accurate and performance is very low in low light conditions also i need to find users emotion whether sad or happy like that but i found its not easy with emgu cvalso for voice recognition i am not able to find any solutions yet i found speech recognition but it is not what i needi do not want to use any online apis can anybody suggest me any sdks or algorithms using which i a implement face emotion and voice recognition,"['c#', '.net']" +303212,do we need multiple io service per thread for threaded boostasio server with a single acceptor i am not much experienced in boostasio i have some pretty basic questionsdo i need to have a different io service and a different socket under a different thread but one single acceptor to process a client in a threaded server i believe i must have a different socket for a new client but if all threads use the same io service would it be parallel i was going through in asio sectionwhich says i need to have different io services in different threads to achieve parallelization i if i plan to make a server class that creates a new tcpsession each time a new client appears in acceptorasync acceptand tcpsession ctor creates an io service and a thread and runs that io servicerun in its own thread would it be a good design however in this design where would i join all these threads do i need another io service for main so that it does not terminate even before getting a new client,['c++'] +303224,generic char based storage and avoiding strictaliasing related ub i am trying to build a class template that packs a bunch of types in a suitably large char array and allows access to the data as individual correctly typed references now according to the standard this can lead to strictaliasing violation and hence undefined behavior as were accessing the char data via an object that is not compatible with it specifically the standard statesif a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefinedthe dynamic type of the objecta cvqualified version of the dynamic type of the objecta type similar as defined in 44 to the dynamic type of the objecta type that is the signed or unsigned type corresponding to the dynamic type of the objecta type that is the signed or unsigned type corresponding to a cvqualified version of the dynamic type of the objectan aggregate or union type that includes one of the aforementioned types among its elements or nonstatic data members including recursively an element or nonstatic data member of a subaggregate or contained union a type that is a possibly cvqualified base class type of the dynamic type of the objecta char or unsigned char typegiven the wording of the highlighted bullet point i came up with the following alias cast ideainclude iostreaminclude type traitstemplate typename tt alias castvoid p typedef typename stdremove referencettype basetype union ut basetype t return reinterpret castutpttemplate typename t typename uclass data union long align char data sizeoft sizeofu public datat t t you u u first t second u t first return alias casttdata u second return alias castudata sizeoft int main dataint unsigned short test testfirst 0xdead testsecond 0xbeef stdcout testfirst testsecond n return 0the above test code especially the data class is just a dumbeddown demonstration of the idea so please do not point out how i should use stdpair or stdtuple the alias cast template should also be extended to handle cv qualified types and it can only be safely used if the alignment requirements are met but i hope this snippet is enough to demonstrate the ideathis trick silences the warnings by g when compiled with g stdc11 wall wextra o2 fstrictaliasing wstrictaliasing and the code works but is this really a valid way of telling the compiler to skip strictaliasing based optimizationsif it is not valid then how would one go about implementing a char array based generic storage class like this without violating the aliasing ruleseditreplacing the alias cast with a simple reinterpret cast like thist first return reinterpret casttdata 0 u second return reinterpret castudata sizeoft produces the following warning when compiled with galiastestso1cpp in instantiation of at datafirst with t int you short unsigned inta aliastestso1cpp2816 required from here aliastestso1cpp2158 warning dereferencing typepunned pointer will break strictaliasing rules wstrictaliasing,['c++'] +303228,unsetting an enum flag consider flags public enum state iscool 0x1 somethingelse 0x2 i have a state somestate and if some expression evaluates to true i want to unset the iscool flag of somestate regardless of it being already set or unset this means that i cannot really use somestate stateiscool but what can i use instead,['c#'] +303246,unrecognized configuration section log4net webconfig website i use log4net to log the errors in my web application and it works fine however if i place the same code in website i get error unrecognized configuration section log4nethere is my webconfig section section namelog4net typelog4netconfiglog4netconfigurationsectionhandlerlog4net requirepermissionfalse root level valuerelease appenderref reflogfileappender rootappender namelogfileappender typelog4netappenderrollingfileappender param namefile valuedessreportlogsessloglog param nameappendtofile valuetrue rollingstyle valuesize maxsizerollbackups value5 maximumfilesize value4mb staticlogfilename valuetrue layout typelog4netlayoutpatternlayout param nameconversionpattern valuenewline5pdymmdd hhmmss thread logger line newline message layoutappenderi have added dll to my website,['asp.net'] +303275,sql server for testing on the web is there a possibility to connect to a sql server database that is on the web and create there some tables queries etc for testing purposesthis would be useful when you do not want to install sql server eg you are on another os but still are interested in this technology it would be great if there would a possibility to connect to your database created there programmatically too,['sql'] +303293,regex to get text from inside the square brackets possible duplicateregular expression to find a string included between two characters while excluding the delimiters i have a function where i have to get text which is enclosed in square brackets but not brackets for examplethis is test line i want text inside square bracketsfrom the above line i want wordstestwantinsidebracketsi am trying with to do this with g but i am not getting satisfied result i get the words inside brackets but also brackets which are not what i want i did search for some similar type of question on so but none of those solution work properly for me here is one what found this works in regex coach but not with javascript here is refrence from where i got thishere is what i have done so far demoplease help,"['javascript', 'jquery']" +303318,why does comparator declare equals the comparator interface has its own equals method any class will get equals by default through object class what is the need to have equals method inside an interface,['java'] +303331,c getting parent assembly name of calling assembly i have got a c unit test application that i am working on there are three assemblies involved the assembly of the c app itself a second assembly that the app uses and a third assembly that is used by the second oneso the calls go like thisfirst assembly second assembly third assemblywhat i need to do in the third assembly is get the name of the fist assembly that called the second assemblyassemblygetexecutingassemblymanifestmodulenameassemblygetcallingassemblymanifestmodulenamereturns the name of the second assembly and assemblygetentryassemblymanifestmodulenamereturn nulldoes anybody know if there is a way to get to the assembly name of the first assembly as per the other users demand here i put the code this is not 100 code but follow of code like thisnamespace firstassemblypublic static xcass a public static stream openresourcestring name return readeropenresourceassemblygetcallingassembly resources name using firstassemblynamespace secondassemblypublic static class b public static stream filenamefromtypestring namereturn aopenresourcestring nameand test project methodusing secondassemblynamespace thirdassemblypublic class testc testmethod public void stremsiztest arrange var stream bfilenamefromtypevalidmetadataxml assert assertisnotnullstream the stream object should not be null,['c#'] +303356,android expandablelistview parent with button i am trying to achieve something like thisthe expandable list consists of the names of certain categories and when a parent is clicked it shows the list of all the children in that categorynow suppose i want dynamically add a child to any category how do i do that do i keep a button with every parent in the list clicking on which would add a new child under it but looking around in different forums i came to realize that it is not really easy to set a button click handler inside every parent but if that is the only way can anyone give me some sample code please i found this thread but was not able to implement it in my codeandroid row becomes unclickable with button,['android'] +303360,how to create a trie in python i am new to python and trying to learn and advance i am interested in tries and dawgs and i have been reading a lot about it but i do not understand what should the output trie or dawg file look likeshould a trie be an object of nested dictionaries where each letteris divided in to letters and so onwould a look up performed on such a dictionary be fast if there are 100k or 500k entrieshow to implement wordblocks consisting of more than one word separated with or spacehow to link prefix or suffix of a word to another part in the structure for dawgi want to understand the best output structure in order to figure out how to create and use onei would also appreciate what should be the output of a dawg along with triei do not want to see graphical representations with bubbles linked to each other i saw them plenty whilst readingi would like to know the output object once a set of words are turned into tries or dawgsthank you,['python'] +303384,what are inline namespaces for c11 allows inline namespaces all members of which are also automatically in the enclosing namespace i cannot think of any useful application of this can somebody please give a brief succinct example of a situation where an inline namespace is needed and where it is the most idiomatic solutionalso it is not clear to me what happens when a namespace is declared inline in one but not all declarations which may live in different files is not this begging for trouble,['c++'] +303395,an efficient sorting algorithm for almost sorted list containing time data the name says it all really i suspect that insertion sort is best since it is the best sort for mostlysorted data in general however since i know more about the data there is a chance there are other sorts woth looking at so the other relevant pieces of information are1 this is time data which means i presumable could create an effective hash for ordering of data2 the data would not all exist at one time instead i will be reading in records which may contain a single vector or dozen or hundreds of vectors i want to output all time within a 5 second window so it is possible that a sort that does the sorting as i insert the data would be a better option3 memory is not a big issue but cpu speed is as this may be a bottleneck of the systemgiven these conditions can anyone suggest an algorithm that may be worth considering in addition to insertion sort also how does one defined mostly sorted to decide what is a good sort option what i mean by that is how do i look at my data and decided this is not as sorted as i thought it as maybe insertion sort is no longer the best option any link to an article which considered process complexity which better defines the complexity relative to the degree data is sorted would be appreciatedthankseditthank you everyone for your information i will be going with an easy insertion or merge sort whichever i have already prewritten for now however i will be trying some of the other methods once were closer to the optimization phase since they take more effort to implement i appreciate the help,['c++'] +303415,efficiently initialise stdset with a sequence of numbers an obvious naive approach would bestdsetint sfor int i 0 i size i sinsertithat is reasonable readable but from what i understand not optimal since it involves repeatedly searching for the insertion position and does not take advantage of the fact that the input sequence is already sortedis there a more elegantefficient or a de facto way of initialising an stdset with a sequence of numbers or more generically how does one efficiently insert an ordered list of entries into a collectionupdatelooking through the docs i have just noticed the constructor that accepts an iterator to indicate the position for insertioniterator insert iterator position const value type x which means this would be more efficientstdsetint sstdsetintiterator it sbeginfor int i 0 i size i it sinsertit ithat looks reasonably but i am still open to more suggestions,['c++'] +303439,getting nunit selected categories programatically is there a way of programatically getting the selected test categories while executing a test something in the lines oftestcontextproperties selectcategoriesbasically i have got test cases which load the test data from a db and as i have got a lot of tests the project is taking a long time to load im trying to find a way of having the testcasesources returning nothing if the category is not selected,['c#'] +303470,templated conversion function to function pointer yay another question title composed of a random sequence of c termsusually we make a class callable by implementing operator but you can also do so by implementing a userdefined conversion to function pointer or reference type instead of using perfect forwarding a conversion function can return a pointer to a function which is then called with the original argument liststruct call printf typedef int printf t char const operator printf t return stdprintf as far as i can tell the typedef above is a syntactic necessity the name of a conversion function is formed from a typespecifierseq which does not allow a construct like int that would require an abstractdeclarator presumably the reason is that such type names get complicated and complex constructs used as object names are tough to parseconversion functions are also allowed to be templated but the template arguments must be deduced because there is nowhere to explicitly specify them that would defeat the whole point of implicit conversionquestion 1 in c03 is there was no way to specify a function conversion operator template it appears there was no way to resolve the template arguments ie name them in a deduced context in an acceptable function pointer typehere is the equivalent reference from c11 a1331122 overcallobject it is substantially the same from c03in addition for each nonexplicit conversion function declared in t of the formoperator conversiontypeid cvqualifier attributespecifierseqoptwhere cvqualifier is the same cvqualification as or a greater cvqualification than cv and where conversiontypeid denotes the type apointer to function of p1pn returning ra or the type areference to pointer to function of p1pn returning ra or the type areference to function of p1pn returning ra a surrogate call function with the unique name callfunction and having the formr callfunction conversiontypeid f p1 a1 pn an return f a1 an is also considered as a candidate function similarly surrogate call functions are added to the set of candidate functions for each nonexplicit conversion function declared in a base class of t provided the function is not hidden within t by another intervening declarationquestion 2 in c11 can such a conversion be specified using a default template argument this is useful for sfinae the only difference here from the above example is that the conversiontypeid only represents a function reference after instantiation because it is a dependent type despite invariance this trips up gcc and it skips the member templateenum call alternate true struct call switch template bool en call alternate operator typename stdenable if en decltype fn 1 type return fn 1 template bool en call alternate operator typename stdenable if en decltype fn 2 type return fn 2 we also have alias templates it seems that alias substitution occurs before instantiation given the example in a14572 where the declarations of process conflict in gcc 47 this code at least instantiates the declaration but then it produces a bizarre candidate expects 2 arguments 2 provided errortemplate typename t using fn t void t struct talk template typename t operator fn t t return fn int main talk 3,['c++'] +303477,define remote interpreter on remote linux machine using pydev and rse server i have a windows box and a linux red hat boxeclipse is installed on windows following instructions given on this eclipse page i managed to set up a rse server that runs on the linux box i am also able to create a project on the remote machineactually i am using virtual environments on linux and i would like to select them when developingis there a way to define a remote interpreter for a pydev or django project,['python'] +303505,plotting a masked surface plot using python numpy and matplotlib i am plotting a surface using matplotlib 110the plot z axis is masked like sozm mamasked whereabsz grid 109 absz grid 091 z surfacesurf axplot surfacex yzm rstride2 cstride2 cmapcolorslinewidth0 antialiasedfalsebut i am not seeing the mask applied on the plot i plotted the mask itself as a subplotsurf axplot surfacex ymagetmaskzm rstride2 cstride2 cmapcolorslinewidth0 antialiasedfalsewhich worked so i know my mask does actually contain true valuesfull codefrom pylab import import matplotlibpyplot as pltfrom matplotlibwidgets import buttonimport numpyfrom mpl toolkitsmplot3daxes3d import axes3dfrom matplotlib import patchesfrom matplotlibfigure import figurefrom matplotlib import rcparamsfig pltfigurefigsizepltfigaspect05ax figadd subplot1 2 1projection3dpole positions orig 06073jzero positions orig 029041jsurface limit 17min val surface limitmax val surface limitsurface resolution 003x numpyarangemin valmax valsurface resolutiony numpyarangemin valmax valsurface resolutionx y numpymeshgridx yz grid x y1jz surface z grid0pole positions numpyroundpole positions orig1 surface resolution2surface resolution21jzero positions numpyroundzero positions orig1 surface resolution2 surface resolution21jfor k in range0 lenzero positions z surface z surface 20log10z grid zero positionskreal zero positionskimag1j z surface z surface 20log10z grid zero positionskreal zero positionskimag1jfor k in range0 lenpole positions z surface z surface 20log10z grid pole positionskreal pole positionskimag1j z surface z surface 20log10z grid pole positionskreal pole positionskimag1j colors cmjetcolorsset badkzm mamasked whereabsz grid 109 absz grid 091 z surfacez surface zmsurf axplot surfacex yz surface rstride2 cstride2 cmapcolorslinewidth0 antialiasedfalseticks 1 1 z ticks 3020100102030 axset xticksticksaxset yticksticks axset zticksz ticksaxset xlabelreaxset ylabelimaxset zlabelmagdbhaleftpltsetpaxget zticklabels fontsize7pltsetpaxget xticklabels fontsize7 pltsetpaxget yticklabels fontsize7ax figadd subplot1 2 2projection3dsurf axplot surfacex ymagetmaskz surface rstride2 cstride2 cmapcolorslinewidth0 antialiasedfalseaxgridbnoneshowthis is what i havethis is what i want from matlabwhat am i missing,['python'] +303506,using flask extensions in flask blueprints i want to create a blueprint not an issue with the current blueprint i have i can do thisbut say i wanted to use a flask extension in my application for my case i want to integrate flaskcacheeverything i have done so far has erroredcache cachemy blueprintimporting cache and various parts of cache in varying guisesso something like flaskcache is simple enough to wrap around my appfrom flaskextcache import cachecache cacheappbut using this in a blueprint or using with a blueprint i do not quite understand how right nowedit the less obvious solution was to crib from the extension and build my own library to import into the blueprint but it is more work and i am not quite done yet extensions blueprints do not seem to be compatible from my level of understanding right now,['python'] +303516,is graphicsdrawimage too slow for bigger images i am currently working on a game and i wish to have a main menu with background imagehowever i find the method graphicsdrawimage really slow i have made some measurement let us assume that menubackground is my resource image with resolution 800 x 1200 pixels i will draw it onto another 800 x 1200 bitmap i render everything to a buffer bitmap first then i scale it and finally draw it onto screen that is how i deal with the possibility of multiple players resolutions but it should not affect it in any way see the next paragraphso i have measured the following codestopwatch sw new stopwatchswstart first let us render background image into originalsized bitmaporiginalrendergraphicsdrawimagepropertiesresourcesmenubackground new rectangle0 0 globalsoriginalscreenwidth globalsoriginalscreenheightswstopsystemwindowsformsmessageboxshowswelapsedmilliseconds millisecondsthe result is quiet surprising to me the stopwatch measures something between 40 50 milliseconds and because the background image is not the only thing to be drawn the whole menu takes about over 100 ms to thisplay which implicates observable lagi have tried to draw it to graphics object given by paint event but the result was 30 40 milliseconds not much changedso does it mean that graphicsdrawimage is unusable for drawing bigger images if so what should i do to improve the performance of my game,['c#'] +303525,parallel pip install our django project is getting huge we have hundreds of apps and use a ton of 3rd party python packages many of which need to have c compiled our deployments are taking a long time when we need to create a new virtual environment for major releases with that said i am looking to speed things up starting with pip does anyone know of a fork of pip that will install packages in parallelsteps i have taken so fari have looked for a project that does just this with little success i did find this github gist but the results are almost exactly the same as our single threaded friendi then found the pip project on github and started looking through the network of forks to see if i could find any commits that mentioned doing what i am trying to do it is a mess in there i will fork it and try to parallelize it myself if i have to i just want to avoid spending time doing thati saw a talk at djangocon 2011 from epio explaining their deployment stuff and they mention parallelizing pip shipping so files instead of compiling c and mirroring pypi but they did not touch on how they did it or what they used,['python'] +303561,finding all documents in a collection with mongoid i have been fiddling with mongo but cannot get this simple example to work i am simply trying to retrieve all documents in a collectionrequire mongoid configuration class category include mongoiddocument field name type stringendcategoryeach do test puts testinspectendi get the error undefined method each for categoryclass nomethoderrorconnection to the database is well established and a collection named categories contains a few documents,['ruby'] +303574,cannot load 64bit swt libraries on 32bit jvm replacing swt file i am trying to debug this problem but not sure where exactly i need to replace swt jar file for eclipse current system configeclipse helios 36 32 bitjdk 16 jvm 32 bit windows 7 64 biterror message javalangunsatisfiedlinkerror cannot load 64bit swt libraries on 32bit jvm at orgeclipseswtinternallibraryloadlibrarylibraryjava194 at orgeclipseswtinternallibraryloadlibrarylibraryjava174 at orgeclipseswtinternalcclinitcjava21 at orgeclipseswtwidgetsthisplayclinitthisplayjava138 at orgeclipseuiinternalworkbenchcreatethisplayworkbenchjava687 at orgeclipseuiplatformuicreatethisplayplatformuijava161 at devogellarcpintrofirstapplicationstartapplicationjava18 at orgeclipseequinoxinternalappeclipseapphandleruneclipseapphandlejava196 at orgeclipsecoreruntimeinternaladaptoreclipseapplauncherrunapplicationeclipseapplauncherjava110 at orgeclipsecoreruntimeinternaladaptoreclipseapplauncherstarteclipseapplauncherjava79 at orgeclipsecoreruntimeadaptoreclipsestarterruneclipsestarterjava369 at orgeclipsecoreruntimeadaptoreclipsestarterruneclipsestarterjava179 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava39 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava25 at javalangreflectmethodinvokemethodjava597 at orgeclipseequinoxlaunchermaininvokeframeworkmainjava620 at orgeclipseequinoxlaunchermainbasicrunmainjava575 at orgeclipseequinoxlaunchermainrunmainjava1408 at orgeclipseequinoxlaunchermainmainmainjava1384an error has occurred see the log fileworkaround link1 understood the cause of the problem and i tried to replace 64bit swt to 32 bit but i am not sure whether i am doing it right downloaded 32bit file swt361win32win32x86zip extracted the zip file have files as shown below copied swtjar file navigated to cprogram fileseclipseplugins removed 64bit swt file ie orgeclipseswtwin32win32x86 64source 362v3659c placed copied swtjar file and relaunched still throws same error also tried renaming the swtjar file to orgeclipseswtwin32win32x86 64source 362v3659c still same errorlink2 suggested the alternative solution but could not resolve the problem still same error i really do not want to uninstall 32jvm and 32bit eclipse and install corresponding 64 bit versions not an option workaround after the paulsm4 and paul webster response i am confused when i tried executing this to check jvm jre version in eclipsepackage javaversionpublic class javaversion public static void main string args systemoutprintln jre version systemgetproperty javaruntimeversion systemoutprintln jvm bit size systemgetproperty sunarchdatamodel output160 31b05jvm bit size 32however when i tried on command line for java versionso my understanding system has 64bit jvm where as eclispe is reading 32 bit jvm so how can i divert system to read 32 bit jvm,['java'] +303581,ruby if vs end of the line if behave differently why does not this code workb if b trueerror undefined local variable or method bbut this doesif b true bendshould not they be the same,['ruby'] +303658,proper way to declare multiple vars in php i have been coding personal scripts for years in php and get used to turn off error thisplay i am about to release some of these scripts and would like to do it the proper waythe only reason why i turn off error thisplay is to avoid having to test every single var prior using it thanks to issetso here is my questionis there a better way to declare multiple vars than this php at the begining of my main file if issetfoo foo if issetbar bar if issetping ping if issetpong pong etc for every single varsomething like this for instance php var foo bar ping pong,['php'] +303703,chrome javascript debugger when paused would not reload page sometimes when i am debugging some javascript in chrome and i have the javascript paused if i try to reload the page chrome instead just continues the debugger stepping to next breakpointthere does not seem to be any way to force the javascript to stop running completely and let chrome just reload the page every press of r or click of the reload button simply continues to the next breakpointmy makeshift solution right now is to copy the url bar addressclose that tabopen a new taband then open the url in the new tab this is rather bruteforce but its the only way i get chrome to actually load a fresh copy of that page instead of just continuing the existing running one emptying the cache has no affect because its not even trying to reload the page ps i also notice there is no stop button for the javascript debugger as well how do i just tell chrome to stop executing the javascript no need to continue the only controls are continue stepover stepin stepout how is there no stop or cancel,['javascript'] +303711,combine multiple sets of rows in sparql i cannot describe my problem formally due to my bad english let me tell it using an examplethe table below is actually grouped by subjectpredicatewe define a set on rows if they the same subject now i want to combine any two sets if they contain the same predicates sum the count of the same predicate and count the number of thistinct subjects which have a same setsubject predicate counts1 p1 1s1 p2 2s2 p1 3s3 p1 2s3 p2 2therefore what wanted from this table is two sets2 p1 3 p2 4 1 p13 where in the first set 2 indicates there are two subjects s1 and s3 having this setp13 is the sum from s1 p1 1 and s3 p1 2so how can i retrieve these sets and store them in javahow can i do it using sparqlor firstly store these triples in java then how can i get these sets using javaone solution might be concat predicates and countsselect counts as thistinctpropsetgroup concatcount separator t as counts select s group concatp separator as propset group concatc separator as count s p c group by s order by s group by propset order by propsetthen the counts could be decoupled then sum upit works fine on small dataset but very time consuming i think i will give up this weird problemthank you very much for answering,['java'] +303733,group by multiple tables and still have access to the original query i was trying to do a join and then a group by my grouped information that is returned is great works like a charm but i still need access to values outside the grouping if that makes sense i found an example on stackoverflow which probably explains it bettervar query from c in contextcontacts join o in contextorders on cid equals ocustomerid select new contact c order o into contactandorder group contactandorder by contactandorderorderid into g select new gkey contactwhatever gsumco cocontactwhatever orderwhatever gsumco coorderwhatever now this seems to work great problem is in my situation the coorderwhatever is a string so i get an error saying cannot convert string to int this i understand as the aggregate function sum expects a intmy question really is is there an aggregate function or something similar to i can get the value of coorderwhatever a string in my case the problem being is once the group by has been done i lose c and o i hope someone can help thanks in advance,"['c#', 'sql']" +303764,how to chk if span tag contain text or not see fiddleif patient has time slot alloted already then make color yellow using jqueryclient side in my fiddle if i allot time slot first time then color is green and at the same time when allot next time slot then previous time slot is grey i have to make it yellow for that i have to find span tag in table and check wheather contains text or not if contains text then make it yellowbut i m new in jqueryi search lot but not getting how can i do thatthis is button click code btnselectclientidclickfunction var cells tableappointment tbody tr tdnthchild3 var i 0 var topcell false cellseachfunction var cell this if cellhasclasscsstdhighlight if i 0 cellfindspantextjquerytxtpatientnameclientidval topcell cell else cellremove i if topcell i 1 topcellattrrowspan i tableappointment treachfunction td thiseachfunction var value thisfindspanval if valuei m chking like this else make it yellow return false,"['javascript', 'jquery', 'html']" +303787,jpa with jta persist entity and merge cascaded child entities i have a bidirectional onetomany relationship with the following entity classes0 or 1 client 0 or more product orderswhen persisting the client entity i want the associated product order entities to be persisted too as their foreign key to the parent client may have been updatedof course all required cascade options are set on the client side but it does not work if a newly created client is persisted for the first time while referencing an existing product order as in this scenarioproduct order 1 is created and persisted works fineclient 2 is created and product order 1 is added to its product orders list then it is persisted does not worki tried several apporaches but none of them showed the expected result see those results below i read all related questions here but they did not help me i use eclipselink 230 pure jpa 20 annotations and jta as transaction type on an apache derby javadb inmemory db on glassfish 312 entity relationships are managed by a jsf gui object level relationship management works apart from persisting i tested it with junit testsapproach 1 default based on netbeans class templatescliententitypublic class client implements serializable parententity private static final long serialversionuid 1l id generatedvaluestrategy generationtypeauto private long id onetomanymappedby client cascadecascadetypepersist cascadetypemerge cascadetyperefresh fetch fetchtypelazy private listproductorder orders new arraylist other fields getters and settersproductorderentitypublic class productorder implements serializable childentity private static final long serialversionuid 1l id generatedvaluestrategy generationtypeauto private long id manytoone owning side private client client other fields getters and settersgeneric persistence facade called when pressing save on the create new jsf pagepublic void createt entity getentitymanagerpersistentity called when pressing save on the edit jsf pagepublic void editt entity getentitymanagermergeentityresultcreate throws this exception immediatlywarning a system exception occurred during an invocation on ejb clientfacade method public void javaee6testbeansabstractfacadecreatejavalangobject javaxejbejbexception transaction aborted caused by javaxtransactionrollbackexception transaction marked for rollback caused by exception eclipselink4002 eclipse persistence services 230v20110604r9504 orgeclipsepersistenceexceptionsdatabaseexception internal exception javasqlsqlintegrityconstraintviolationexception the statement was aborted because it would have caused a duplicate key value in a unique or primary key constraint or unique index identified by sql120513133540930 defined on productorder error code 1 call insert into productorder id client id values bind 2 parameters bound query insertobjectqueryjavaee6testmodelproductorder id1 caused by javasqlsqlintegrityconstraintviolationexception the statement was aborted because it would have caused a duplicate key value in a unique or primary key constraint or unique index identified by sql120513133540930 defined on productorder caused by orgapachederbyclientamsqlexception the statement was aborted because it would have caused a duplicate key value in a unique or primary key constraint or unique index identified by sql120513133540930 defined on productorderi do not understand this exception edit works fine but i would like to add product orders to a client at its creation time so this is insufficientapproach 2 merge onlychanges to generic persistence facade called when pressing save on the create new jsf pagepublic void createt entity getentitymanagermergeentity called when pressing save on the edit jsf pagepublic void editt entity getentitymanagermergeentityresulton create the eclipselink logging output saysfine insert into client id name address id values bind 3 parameters boundbut no update on the product order table thus the relationship is not established again edit on the other hand works fineapporach 3 id generationtypeidentity on both entity typeschanges to both client and product order classidgeneratedvaluestrategy generationtypeidentityprivate long idresulton create the eclipselink logging output saysfine insert into client name address id values bind 2 parameters boundfine values identity val localfine insert into productorder orderdate client id values bind 2 parameters boundfine values identity val localthus instead of estabilshing a relationship to the product order added to the clients list a new prodcut order entity is created and persisted and a relationship to that entity is estabilshed same here edit works fineapporach 4 approach 2 and 3 combinedresult same as approach 2my question is is there any way to realize the scenario described above how can it be archieved i would like to stay with jpa no vendorspecific solution,['java'] +303832,how to determine opencv version how to determine which version of opencv i have installedi am most interested in knowing a way of doing it programatically and crossplatform but i cannot even find a way to determine the installed version from outside the codei am working with c03 on fedora,['c++'] +303849,how to instruct jackson to serialize a field inside an object instead of the object it self i have an item class there is an itemtype field inside of that class which is of type itemtyperoughly something like thisclass item int id itemtype itemtypeclass itemtype string name int somethingelsewhen i am serializing an object of type item using jackson objectmapper it serializes the object itemtype as a subobject which is expected but not what i want id 4 itemtype name coupon somethingelse 1 what i would like to do is to show the itemtypes name field instead when serialized something like below id 4 itemtype couponis there anyway to instruct jackson to do so,['java'] +303904,how to run the java class with has package name i have the two java class as follows1none package clasystemoutprintlnapp1 hello world2has packagepackage javajavapackage1systemoutprintlnapp1 hello worldtheni compile and run themthe result as followsdjavatestjavac app1javadjavatestjavac app2javadjavatestjava app1app1 hello worlddjavatestjava javajavapackage1app2exception in thread main javalangnoclassdeffounderror javajavapackage1app2caused by javalangclassnotfoundexception javajavapackage1app2 at javaneturlclassloader1rununknown source at javasecurityaccesscontrollerdoprivilegednative method at javaneturlclassloaderfindclassunknown source at javalangclassloaderloadclassunknown source at sunmisclauncherappclassloaderloadclassunknown source at javalangclassloaderloadclassunknown sourcecould not find the main class javajavapackage1app2 program will exitso how to run the app2 class,['java'] +303926,how to find sum of multiple columns in a table in sql server 2005 i have a table emp which has these rowsemp cd val1 val2 val3 total 1 123 223 343 2 2303 1223 292 3 723 905 1343 4 0321 7823 943 i want to find sum of val1 val2 val3 and which will show in the total column,['sql'] +303933,change specific value in csv file via python i need the way to change specific value of the column of csv file for example i have csv fileipsites127001101270022312700350and i need to change value 23 to 30 of the 127002i use csv library import csvappreciate any help as i am new in python thanks,['python'] +303971,temporarily bypassing implicit waits with webdriver when using implicit waits as advised here i still sometimes want to assert the immediate invisibility or nonexistence of elementsin other words i know some elements should be hidden and want my tests make that assertion fast without spending several seconds because of the otherwise useful implicit waitone thing i tried was a helper method like this nb does not seem to do what i wantprivate boolean iselementhiddennowstring id webdriverwait zerowait new webdriverwaitdriver 0 expectedconditionboolean c invisibilityofelementlocatedbyidid try zerowaituntilc return true catch timeoutexception e return false but in the above code the call to until only returns after the implicit wait time has passed ie it does not do what i wantedthis is the only way i have found so far that workstestpublic void checkthatsomethingisnotvisible turnoffimplicitwaits the actual test turnonimplicitwaits where eg turnoffimplicitwaits is a helper in common selenium superclassprotected void turnoffimplicitwaits drivermanagetimeoutsimplicitlywait0 timeunitsecondsbut that is not very elegant i think is there any cleaner way to bypass the implicit wait occasionally,['java'] +303975,how do you get raw tcp packet in c i want to received raw tcp packet and then send it back with same workloadit should look something like thisvoid onpacketreceivedtcppacket p byte body pgetbodynote i need the tcp packet and not the ethernet frame,['c#'] +304005,html5 audio behavior i have an audio element in a html5 page i start playing the audio and then pause it after that i go back to homescreen by pressing home button and make a phone call when the call ends audio element resumes automatically this happens on android 403the problem is that this is not the expected and desired behavior unfortunately when browser is running in background javascript events are not thrown and i cannot catch and prevent this behavior using javascriptany help is appreciated thanks in advance,"['javascript', 'android']" +304019,compress an inputstream with gzip i would like to compress an input stream in java using gzip compressionlet us say we have an input stream 1gb of data not compressed i want as a result a compressed inputstream from the source public inputstream getcompressedstreaminputstream uncompressedstream not working because it is uncompressing the stream i want the opposite return new gzipinputstreamuncompressedstream,['java'] +304024,double quotes within php script echo i have a line of php code that looks like thisecho scriptedit errorshtmlh3emplease correct errors before proceedingemh3scripti would like to know how to add a font color to the text correctlyif i do thisecho scriptedit errorshtmlh3emfont colorredplease correct errors before proceedingfontemh3scriptthe word red is in black text and the compiler throws an errorif i use single quotes around red then the text does not show up at allany help would be greatthanks,"['javascript', 'php']" +304057,can you use a lambda in a class initialization list i am trying to use a c11 lambda to initialize a const member variable of a classa much simplified exampleclass foopublic const int and foofoofoo and int return 42 int main foo fin msvc10 this yieldserror c2440 initializing cannot convert from anonymousnamespacelambda0 to const intin ideone this yieldsprogcpp in constructor foofooprogcpp934 error invalid conversion from int to inti am starting to get the idea that i cannot use lambdas in a class initialization list can i if so whats the proper syntax,['c++'] +304077,starting marquee on audio play i am trying to find out a way to set a time tag to the marquee tag in htmlthe whole idea is to thisplay the subtitles of a song in marquee format and starting the marquee only when the user clicks to start the audioi am using the following code to play the audio filein html5 audio controlscontrols looploop source srcsongogg typeaudioogg source srcsongmp3 typeaudiompeg your browser does not support the audio elementplease use chromeaudiowhat i am doing is set this audio file on autoplay and let the marquee start at the time the page loadswhich is the default settingbut this works nice on high speed networks for low speed networks the problem that arises is that the loading of the audio content gets delayed and hence the marquee text starts running ahead of the audiowhich is not coolplease advice me how can i accomplish a solution to this problem via javascript,['javascript'] +304083,how to create a typedef for function pointers i think it would be easier to use function pointers if i created a typedef for a function pointer but i seem to be getting myself tripped up on some syntax or usage or something about typedef for function pointers and i could use some helpi have gotint fooint i return i 1typedef gint hvarhvar g3that is basically what i am trying to accomplish i am a rather new c programmer and this is throwing me too much what replaces,['c'] +304172,how to programmatically open jquery accordion content panel i want to extend the default behavior of the jquery accordion and add a next button inside the content panels when the user clicks next button inside the content panel the accordion should open the next itemi was able to locate the next item like this thisparentnext but having trouble triggering the actual actiondiv idaccordion h3a hrefitem 1ah3 divitem 1 contentbr div onclickthisparentnextshownextdiv div h3a hrefitem 2ah3 divitem 2 contentbr divdiv,['jquery'] +304179,whole number or decimal number i am looking for a function that tests to see if an integer is a whole number so far i have got thisif is numericanswer3 echo is triangularn else echo is not triangularnbut this always returns is triangular even when answer3 is a decimalhow can i test an integer to see if it has a decimal,['php'] +304198,how can i use xaxis date with barh in the code below bdate and edate are both datetimedatetime objectspylabbarhypos edate bdate leftbdate heighttrmwidth but this throws an attributeerror way down in datespy to ordinalf file libraryframeworkspythonframeworkversions27libpython27sitepackagesmatplotlibpyplotpy line 1926 in barh ret axbarhbottom width height left kwargs file libraryframeworkspythonframeworkversions27libpython27sitepackagesmatplotlibaxespy line 4774 in barh orientationhorizontal kwargs file libraryframeworkspythonframeworkversions27libpython27sitepackagesmatplotlibaxespy line 4624 in bar width selfconvert xunits width file libraryframeworkspythonframeworkversions27libpython27sitepackagesmatplotlibartistpy line 147 in convert xunits return axxaxisconvert unitsx file libraryframeworkspythonframeworkversions27libpython27sitepackagesmatplotlibaxispy line 1312 in convert units ret selfconverterconvertx selfunits self file libraryframeworkspythonframeworkversions27libpython27sitepackagesmatplotlibdatespy line 1125 in convert return date2numvalue file libraryframeworkspythonframeworkversions27libpython27sitepackagesmatplotlibdatespy line 260 in date2num else return npasarray to ordinalfval for val in d file libraryframeworkspythonframeworkversions27libpython27sitepackagesmatplotlibdatespy line 189 in to ordinalf base floatdttoordinalattributeerror datetimetimedelta object has no attribute toordinali thought it would be great if i could just shove datetimes at xaxis and have itwork out the details not so much any suggestions as to how to make dates agreaable to xaxis,['python'] +304199,force the browser to use faux italic oblique and not the real italic i have read about a lot of people having problems with the browser not loading the real italic fontstyle i on the other want to force the browser to use a faux italicthis is my css codeh2 fontfamilybell mt georgia serif fontsize31px fontstyleoblique fontweightnormal colore19614when i set fontweight to bold or greater the resulting effect is the desired an oblique font but whenever i set the weight to normal which is the desired setting it goes back to the real italic font which in this case bell mt is very differentany suggestions,['css'] +304232,vs dot vs doublecolon for calling a method possible duplicatewhat does mean in ruby i am learning ruby from the poignant guide to ruby and in some of the code examples i came across uses of the double colon and dot that seem to be used for the same purposefileopen idea idea name txt w do f f ideaendin the above code the double colon is being used to access the open method of the file class however i later came across code that used a dot for the same purpose require wordlist print each idea out with the words fixeddirideatxteach do file name idea fileread file name code wordseach do real code ideagsub code real endputs ideaend this time a dot is being used to access the read method of the file class what is the difference betweenfilereadand fileopen,['ruby'] +304239,getting invalid client error in sample gdataobjectivecclient hey i have just downloaded and built the youtube sample project from the application builds fine and i have entered the client id and secret then when i log in with my youtube account and click the allow button i get this errorerror domaincomgooglehttpstatus code400 the operation couldnat be completed comgooglehttpstatus error 400 userinfo0x6a03a350 data7b0a2020 22657272 6f720 3a202269 6e76616c 69645f63 6c69656e 74220a7d jsoncfbasichash 0x6a01b6b0 0xac0251a0type mutable dict count 1entries 2 cfstring 0x6a01b720 0xac0251a0contents error cfstring 0x6a054b90 0xac0251a0contents invalid client or from the xcode log20120615 104930627 youtubesample976b03 error error domaincomgooglehttpstatus code400 the operation couldnat be completed comgooglehttpstatus error 400 userinfo0x6980d2c0 data7b0a2020 22657272 6f720 3a202269 6e76616c 69645f63 6c69656e 74220a7derror dataerror invalid clienti have tried creating and entering new client ids to availit looks like the secret is not being sent properly because i get the same result if i deliberately corrupt it or even leave it blank any suggestions,['objective-c'] +304312,qt with html5 or without html5 i have been programming with qt libraries for 3 years all programs have been designed by traditional widgets so far but now i noticed that you can design your user interface with html5cssjquery now these are my questionswhen should we design our interface with html5 and the core with qtlibrarieswhat will be the advantages if we use html5 in designing user interface instead of traditional widgetswould itbe reasonable if we design even our ordinary desktop applications user interfacewith html5thanks,['jquery'] +304321,springtestmvc mockservletcontext content empty in test but working on tomcat were trying to set up springtestmvc for our springmvc web app we started out using freemarker and everything was fine we decided against it though and are now trying to set it up with jsp when the test app is deployed on a tomcat it is working when we run the simple testrunwithspringjunit4classrunnerclasscontextconfigurationloader webcontextloaderclass locations filesrcmainwebappwebinfservletcontextxml public class skelletontest inject private mockmvc mockmvc test public void hometest throws exception mockmvcperformgetandexpectstatusisok andexpectcontenttypetexthtmlcharsetiso88591 andexpectcontentstringcontainsstringhello world it says content type not set or if that is removed the content will just be empty the controller will get called however so the mapping must workso this strongly suggests that the view is not rendered for our tests but i have no clue what setup i might be missing heres our servletcontextxmlcontextcomponentscan basepackagepackagetocontrollers mvcannotationdriven bean idviewresolver classorgspringframeworkwebservletviewinternalresourceviewresolver property nameviewclass valueorgspringframeworkwebservletviewjstlview property nameexposecontextbeansasattributes valuetrue property nameprefix valueviews property namesuffix valuejsp beanthe webcontextloaderpublic class webcontextloader extends genericwebcontextloader public webcontextloader supersrcmainwebapp false genericwebcontextloader is the original by springtestmvcthe mockmvc gets setup as a bean like thisconfigurationpublic class testconfig inject private webapplicationcontext wac bean public mockmvc create return mockmvcbuilderswebapplicationcontextsetupthiswacbuild so that is the setup webxml is not used by the test framework and should not matter as it was working beforei am thinking there must be an additional setup in the servletcontext it gets loaded that i checked but while for the tomcat deployed app it matters what i set for prefix and suffix it will just get ignored by the testnot sure how much the error trace will help but here it isjavalangassertionerror content type not set at orgspringframeworktestwebassertionerrorsfailassertionerrorsjava35 at orgspringframeworktestwebassertionerrorsasserttrueassertionerrorsjava57 at orgspringframeworktestwebserverresultcontentresultmatchers1matchcontentresultmatchersjava59 at orgspringframeworktestwebservermockmvc1andexpectmockmvcjava84 at ourpackageskelletontesthometestskelletontestjava30 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava57 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43 at javalangreflectmethodinvokemethodjava601 at orgjunitrunnersmodelframeworkmethod1runreflectivecallframeworkmethodjava45 at orgjunitinternalrunnersmodelreflectivecallablerunreflectivecallablejava15 at orgjunitrunnersmodelframeworkmethodinvokeexplosivelyframeworkmethodjava42 at orgjunitinternalrunnersstatementsinvokemethodevaluateinvokemethodjava20 at orgspringframeworktestcontextjunit4statementsrunbeforetestmethodcallbacksevaluaterunbeforetestmethodcallbacksjava74 at orgspringframeworktestcontextjunit4statementsrunaftertestmethodcallbacksevaluaterunaftertestmethodcallbacksjava83 at orgspringframeworktestcontextjunit4statementsspringrepeatevaluatespringrepeatjava72 at orgspringframeworktestcontextjunit4springjunit4classrunnerrunchildspringjunit4classrunnerjava231 at orgjunitrunnersblockjunit4classrunnerrunchildblockjunit4classrunnerjava47 at orgjunitrunnersparentrunner3runparentrunnerjava231 at orgjunitrunnersparentrunner1scheduleparentrunnerjava60 at orgjunitrunnersparentrunnerrunchildrenparentrunnerjava229 at orgjunitrunnersparentrunneraccess0parentrunnerjava50 at orgjunitrunnersparentrunner2evaluateparentrunnerjava2 at orgspringframeworktestcontextjunit4statementsrunbeforetestclasscallbacksevaluaterunbeforetestclasscallbacksjava61 at orgspringframeworktestcontextjunit4statementsrunaftertestclasscallbacksevaluaterunaftertestclasscallbacksjava71 at orgjunitrunnersparentrunnerrunparentrunnerjava300 at orgspringframeworktestcontextjunit4springjunit4classrunnerrunspringjunit4classrunnerjava174 at orgeclipsejdtinternaljunit4runnerjunit4testreferencerunjunit4testreferencejava50 at orgeclipsejdtinternaljunitrunnertestexecutionruntestexecutionjava38 at orgeclipsejdtinternaljunitrunnerremotetestrunnerruntestsremotetestrunnerjava467 at orgeclipsejdtinternaljunitrunnerremotetestrunnerruntestsremotetestrunnerjava683 at orgeclipsejdtinternaljunitrunnerremotetestrunnerrunremotetestrunnerjava390 at orgeclipsejdtinternaljunitrunnerremotetestrunnermainremotetestrunnerjava197and the test output20120615 104104 testcontextmanager info testexecutionlisteners is not present for class class packagetotestskelletontest using defaults20120615 104105 xmlbeandefinitionreader info loading xml bean definitions from url filesrcmainwebappwebinfservletcontextxml20120615 104105 classpathbeandefinitionscanner info jsr330 javaxinjectnamed annotation found and supported for component scanning20120615 104105 genericwebapplicationcontext info refreshing orgspringframeworkwebcontextsupportgenericwebapplicationcontext158539f startup date fri jun 15 104105 cest 2012 root of context hierarchy20120615 104105 autowiredannotationbeanpostprocessor info jsr330 javaxinjectinject annotation found and supported for autowiring20120615 104105 defaultlistablebeanfactory info preinstantiating singletons in orgspringframeworkbeansfactorysupportdefaultlistablebeanfactoryc64bc2 defining beans orgspringframeworkcontextannotationinternalconfigurationannotationprocessororgspringframeworkcontextannotationinternalautowiredannotationprocessororgspringframeworkcontextannotationinternalrequiredannotationprocessororgspringframeworkcontextannotationinternalcommonannotationprocessortestconfigfreemarkercontrollerhomecontrollertableserviceorgspringframeworkwebservletmvcmethodannotationrequestmappinghandlermapping0orgspringframeworkformatsupportformattingconversionservicefactorybean0orgspringframeworkwebservletmvcmethodannotationrequestmappinghandleradapter0orgspringframeworkwebservlethandlermappedinterceptor0orgspringframeworkwebservletmvcmethodannotationexceptionhandlerexceptionresolver0orgspringframeworkwebservletmvcannotationresponsestatusexceptionresolver0orgspringframeworkwebservletmvcsupportdefaulthandlerexceptionresolver0orgspringframeworkwebservlethandlerbeannameurlhandlermappingorgspringframeworkwebservletmvchttprequesthandleradapterorgspringframeworkwebservletmvcsimplecontrollerhandleradapterviewresolverorgspringframeworkcontextannotationconfigurationclasspostprocessorimportawarebeanpostprocessor0create root of factory hierarchy20120615 104105 requestmappinghandlermapping info mapped methodsparamsheadersconsumesproducescustom onto public orgspringframeworkwebservletmodelandview packagetocontrollerhomecontrollerindex20120615 104105 requestmappinghandlermapping info mapped testmethodsparamsheadersconsumesproducescustom onto public javalangstring packagetocontrollerhomecontrollertestorgspringframeworkuimodel20120615 104106 genericwebcontextloader1 info initializing spring frameworkservlet 20120615 104106 testthispatcherservlet info frameworkservlet initialization started20120615 104106 testthispatcherservlet info frameworkservlet initialization completed in 32 ms20120615 104106 genericwebapplicationcontext info closing orgspringframeworkwebcontextsupportgenericwebapplicationcontext158539f startup date fri jun 15 104105 cest 2012 root of context hierarchy20120615 104106 defaultlistablebeanfactory info destroying singletons in orgspringframeworkbeansfactorysupportdefaultlistablebeanfactoryc64bc2 defining beans orgspringframeworkcontextannotationinternalconfigurationannotationprocessororgspringframeworkcontextannotationinternalautowiredannotationprocessororgspringframeworkcontextannotationinternalrequiredannotationprocessororgspringframeworkcontextannotationinternalcommonannotationprocessortestconfigfreemarkercontrollerhomecontrollertableserviceorgspringframeworkwebservletmvcmethodannotationrequestmappinghandlermapping0orgspringframeworkformatsupportformattingconversionservicefactorybean0orgspringframeworkwebservletmvcmethodannotationrequestmappinghandleradapter0orgspringframeworkwebservlethandlermappedinterceptor0orgspringframeworkwebservletmvcmethodannotationexceptionhandlerexceptionresolver0orgspringframeworkwebservletmvcannotationresponsestatusexceptionresolver0orgspringframeworkwebservletmvcsupportdefaulthandlerexceptionresolver0orgspringframeworkwebservlethandlerbeannameurlhandlermappingorgspringframeworkwebservletmvchttprequesthandleradapterorgspringframeworkwebservletmvcsimplecontrollerhandleradapterviewresolverorgspringframeworkcontextannotationconfigurationclasspostprocessorimportawarebeanpostprocessor0create root of factory hierarchyso thanks for any suggestions that help me locate the problembtw did not want this to get any longer so i skipped the pom were using spring 31 springtestmvc 100buildsnapshot jspap 22 jstl 12 if you need to know more i will try to upload it somewhereeditplease let me know if you need more information or why you cannot answer my question really need to figure it out and i have no idea where to start so any thoughts or comments are welcome tooedit2used the print method with the following outputmockhttpservletrequest http method get request uri parameters headers handler type packagetocontrollerhomecontroller method public orgspringframeworkwebservletmodelandview packagetocontrollerhomecontrollerindex resolved exception type null modelandview view name index view null attribute welcome value hello world flashmapmockhttpservletresponse status 200 error message null headers content type null body forwarded url viewsindexjsp redirected url null cookies which just shows the problem better but not the solutionedit3just found out the followingjsp requires a servlet container so it seems i cannot test my pages this way if anyone has any idea how to work around this problem please let me know,['java'] +304349,creating a jquery object from a big htmlstring i have a big htmlstring containing multiple childnodesis it possible to construct a jquery dom object using this stringi have tried string but it only returns an array containing all the individual nodesimtrying to get an element which i can use the find function on,"['javascript', 'jquery', 'html']" +304368,c1 or c2 coverage tool for ruby is there any tool for c1 or c2 code coverage for ruby 19 simplecov supports only c0 but maybe there is another tooli am aware that a similar question has been asked here but it was a couple years ago and i hope that something has changed,['ruby'] +304387,oraclecommand sql parameters binding i have a problem with the binding of the below parameter the connection works because i had tested it without using parameters however the value of the query before being executed is still using username instead of jsmith for example what is the problem is this not the right way to go around binding public static string getfullnamestring domainuser datatable dt string fullname oracleconnection db databaseadaptergetconn dbopen oraclecommand oracommand new oraclecommandselect fullname from user profile where domain user name username db oracommandbindbyname true oracommandparametersaddnew oracleparameterusername domainuser oracledatareader orareader null orareader oracommandexecutereader if orareaderhasrows while orareaderread fullname orareadergetstring0 else return no rows found orareaderclose dbclose dbthispose return fullnameedit i added to the parameter field name but it still does not fix it,['c#'] +304404,detect carrier connection type 3g edge gprs how can i get the type of connection of a carrier networki am able to get if connection is wifi or wwan using reachability class i am able to get network flags reachability flag status wr t localwifistatusforflagsi am able to get wifi ssid using captivenetworksupported interfaces en0 en0 bssid x ssid mywifinetwork ssiddata x1x1x1x1 x1x1x1x1 x1 but i am not able to differenziate 3g edge or gprs connection any idea also using ios private apithanks,"['iphone', 'objective-c', 'ios']" +304408,rmi notserializableexception although it is a remote object i am writing a small rmi based chat applicationthe idea is the client registers himself on the server and everytime the server receives a message from a client he pushes this message to all other clientsbut i receive a notserializableexception although the object i am passing as a method parameter implements the remote interfacehere is some codethe problematic part is the this parameter in thischatservregistriereclientthis clientchat implementationthe clientchatinterfacepublic interface chatclient extends remoteclientchatimplementationpublic class chatclientimpl implements chatclient chatserver chatserv string clientname public chatclientimplstring clientname chatserver chatserv thischatserv chatserv thisclientname clientname try thischatservregistriereclientthis catch remoteexception e eprintstacktrace serverchat interfacepublic interface chatserver extends remote void registriereclientchatclient client throws remoteexceptionserverchat implementationpublic class lobbychatserverimpl implements chatserver arraylistchatclient clientliste null override public void registriereclientchatclient client systemoutprintlnclient registriert thisclientlisteaddclient client public static void mainstring args chatserver lobbychatserver null try registry registry locateregistrygetregistryserverrmi port lobbychatserver chatserver registrylookuplobbychatserver catch remoteexception e eprintstacktrace catch notboundexception e eprintstacktrace chatclient lobbychat new chatclientimplname lobbychatserver server public static void mainstring args try if systemgetsecuritymanager null systemsetsecuritymanagernew rmisecuritymanager registry registry locateregistrygetregistryrmi port chatserver lobbychatstub chatserverunicastremoteobjectexportobjectnew lobbychatserverimpl 0 registrybindlobbychatserver lobbychatstub catch remoteexception e eprintstacktrace catch alreadyboundexception e eprintstacktrace exceptionjavarmimarshalexception error marshalling arguments nested exception is javaionotserializableexception dexxchatchatclientimpl at sunrmiserverunicastrefinvokeunicastrefjava156 at javarmiserverremoteobjectinvocationhandlerinvokeremotemethodremoteobjectinvocationhandlerjava194 at javarmiserverremoteobjectinvocationhandlerinvokeremoteobjectinvocationhandlerjava148 at proxy0registriereclientunknown source at dexxchatchatclientimplinitchatclientimpljava19 at dexxclientmainclientjava49caused by javaionotserializableexception dexxchatchatclientimpl at javaioobjectoutputstreamwriteobject0objectoutputstreamjava1180 at javaioobjectoutputstreamwriteobjectobjectoutputstreamjava346 at sunrmiserverunicastrefmarshalvalueunicastrefjava292 at sunrmiserverunicastrefinvokeunicastrefjava151 5 moreas already said i wonder why i get this kind of exception although chatclientimpl is already remotehope you can help me,['java'] +304435,using eval with a custom global is there a way to specify which object to use for global when invoking evali am not asking how to do global evalthis is not working but this illustrates what i would likevar pseudoglobal evalx 12 pseudoglobalpseudoglobalx 12the point is that real global bindings are not affected by implicit variable declaration ie without var keywords in the code evaledas for evalcallpseudoglobal x12 or evalapplypseudoglobal x12 some interpreters wont allow it,['javascript'] +304450,nodejs c addon threading i am writing a gui addon for nodejs wxwidgets and i want to run the gui loop in an own thread as i do not think it would be a good idea to merge it with nodes main thread and event loophowever i am not sure how to create a new thread i got it running with uv queue work but it will not create an exclusive thread for the gui but use nodes thread pool and this might be a bad idea since the worker will stay during the whole runtime not sure about thisi could also use wxwidgets wxthread works too and i found a new function uv thread create in libuv git master no idea how to use that as there is no description and besides it is not yet available in nodejs stable buildmy question what is the standard way to create a multithreaded nodejs addon if any i looked at other projects but could only find shortrunning worker threads using libuv,['c++'] +304453,strict 24hour time in jformattedtextfield i am trying to create a jformattedtextfield that only accepts a 24hour time i am very close to a solution but have one case where the following code example does not workif you enter the time 2 and change focus from the field the time is corrected to 2202 i would like it to only accept a full 4 digit 24hour time this code works as i want in almost all cases except the one i just mentioned any suggestions public static void mainstring args throws parseexception dateformat dateformat new simpledateformathhmm dateformatsetlenientfalse dateformatter dateformatter new dateformatterdateformat jframe frame new jframe framesetdefaultcloseoperationjframeexit on close jformattedtextfield textfield new jformattedtextfielddateformatter frameaddtextfield borderlayoutnorth frameaddnew jtextfieldthis is here so you can change focus borderlayoutsouth framesetsize250 100 framesetvisibletrue,['java'] +304461,can i stop net 40 from encoding single quotes after switching to net 40 some javascript code from a third party gridview crashesit has got something to do with htmlencode and urlencode now encode single quotation marksso before some code on the page was inserted like thisdataitemgetmemberidvalueand now its like this dataitemgetmember39id39valuethe gridview does an eval on that line and crashes with a syntax error now i cannot change the javascript code in that gridviewis there anyway to solve this without going backwards like thispages controlrenderingcompatibilityversion35 edit the pages controlrenderingcompatiblityversion does not fix this also single quotes are still encoded,"['c#', 'javascript', '.net']" +304462,compiling only selected files in maven i want to compile only selected files or directories including subdirectories within source directory i was pretty sure i can do this using includes of mavencompilerplugins configuration but it seems to not work as i expect since it still compiles all classes into targetclasses what is really strange maven output suggest that the setting actually does its work because with plugin artifactidmavencompilerpluginartifactid version251version configuration includes includecomexampledaobeanjavainclude includes configuration plugini haveinfo compiling 1 source file to cprojectstesttargetclassesbut with no compilers configuration i haveinfo compiling 14 source file to cprojectstesttargetclassesin both cases however all 14 classes are compiled into targetclasses as i mentioned can you explain that or suggest another solution to compile only selected files,['java'] +304526,how are the cplusplus directive defined in various compilers my compiler expands it to 199711l what does that mean i read that cplusplus 199711l signifies c11 what are the possible expansions of this macro and what does it signify,['c++'] +304553,logarithm function of an arbitrary integer base in c is there a function or any other way to calculate in c the logarithm of base x where x is an integer variable of my program,['c'] +304569,html5 draganddrop how do i target the cloned and original elements i want to apply a class name to the ghost element being dragged not the original element that was cloned here is the function i have in place for the dragstart eventfunction dragstartevent eventoriginaleventdatatransfereffectallowed move eventoriginaleventdatatransfersetdatatextplain eventtargetgetattributeid consolelogevent consolelogdragging eventcurrenttargetaddclassdragging return truethe eventcurrenttargetaddclassdragging line adds the dragging class to the original element but not the cloned dragging elementhow do i properly target botheditlooking to handle this with native html5 as much as possible prefer not to use a jquery plugin,['css'] +304589,how to turn off bracketsquotes autocompletion in visual studio as it states in the title how to i turn off bracketsquotescurly braces autocompletion in msvs i am interested in c and xaml mostly but over text editors would be nice tooeditcurrently i am using msvs 11 with these extensionsankhsvnconcurrency visualizerpreemptive analytics aggregator visualizermsvs perfwatsonvsgraphicsdebuggerpkgweb tooling extensionsmost of them are preinstalled with msvs installation imho because i do not remember installing them edit2i am using msvs in this version version 110503231 qrelbedit3i found out the problem does not occur in currently available msvs11,['c#'] +304607,jquery ajax with ie8 i am attempting to implement a get request via ajax upon the user submitting a formi am not sure if what i am doing is the most efficient method binding a click to the form button so if there is a more efficient way or standard way please suggest itmy result is that the content div is filled properly in ffchrome but ie it is not ie seems to be submitting the form and reloading the page entirelyin addition i really do think i need to submit the form because i want to take advantage of jquery validate which does not work with the below implementation even in ffchromejavascriptdocumentreadyfunction theformsubmitfunction build our data to send in our request var mydata method search color colorval ajax url foophp data mydata type get datatype json success functiondata contenthtmldata error functione consolelogemessage return false html form idsearch input typesubmit formdiv idcontentdiv,['jquery'] +304613,does dequeuereusablecellwithidentifier call an initializer in my uitableviewcell subclass i have a uitableviewcontroller subclass with its prototype cells mocked up in the storyboard there is a fair amount of code in the cellforrowatindexpath delegate method that sets up the cells problem is i do not need most of it if the cell is just being dequeued from the reuse pool because it is already been done when the cell was dequeued the first time i cannot do it in the storyboard because there are some properties i can only access programmatically does the uitableviewcontroller call an initializer in my uitableviewcell subclass when it takes a prototype cell from the storyboard i tried idinitwithstyleuitableviewcellstylestyle reuseidentifiernsstring reuseidentifier but that does not appear to be part of the process,"['iphone', 'objective-c']" +304639,creating a log file in an ios app so in my app i have a bunch of data that i would like to write to a log file and then thisplay it within a uitextview when i click a button i know how to toggle the uitextview but i have no idea how to create and update a log file in the local filesystem thanks for any help,['ios'] +304646,passing member functions to stdthread possible duplicatestart thread with member function i have recently been playing around with the new stdthread library in c11 and i came across a problem when i try to pass a classes function into a new thread it gives me an error i dont have the exact error text right now since im away from homei had a class like thisclass a void functa void functb void run stdthread tfuncta stdthread rfunctb what am i doing wrong,['c++'] +304651,remove div on click i have a div which i want to be removed when i click a link contained inside that div here is what i havediv idclientseditwrapper div classclosewrapper a href classclosedivclosea divdivwhen i click close i want clientseditwrapper to be removed i am looking for a way to do this by referencing the parent div of the close link which in this case is clientseditwrapper any help would be greatly appreciatedanswer from huangism belowclosedivclickfunction thisparentparentremovethis only works if the element you would like to remove is two parents up in my case this is exactly what i needed,['jquery'] +304696,parsing a tabseparated file in python i am trying to parse a tabseparated file in python where a number placed k tabs apart from the beginning of a row should be placed into the kth array is there a builtin function to do this or a better way other than reading line by line and do all the obvious processing a naive solution would perform,['python'] +304743,android reduce image file size i have an uri image file and i want to reduce its size to upload it initial image file size depends from mobile to mobile can be 2mb as can be 500kb but i want final size to be about 200kb so that i can upload itfrom what i read i have at least 2 choicesusing bitmapfactoryoptionsinsamplesize to subsample original image and get a smaller imageusing bitmapcompress to compress the image specifying compression qualitywhats the best choicei was thinking to initially resize image widthheight until width or height is above 10px something like 1024x768 or others then compress image with decreasing quality until file size is above 200kb heres an exampleint max image size 200 1024 max final file sizebitmap bmppic bitmapfactorydecodefilefileurigetpathif bmppicgetwidth 1024 bmppicgetheight 1024 bitmapfactoryoptions bmpoptions new bitmapfactoryoptions bmpoptionsinsamplesize 1 while bmppicgetwidth 1024 bmppicgetheight 1024 bmpoptionsinsamplesize bmppic bitmapfactorydecodefilefileurigetpath bmpoptions logdtag resize bmpoptionsinsamplesizeint compressquality 104 quality decreasing by 5 every loop start from 99int streamlength max image sizewhile streamlength max image size bytearrayoutputstream bmpstream new bytearrayoutputstream compressquality 5 logdtag quality compressquality bmppiccompressbitmapcompressformatjpeg compressquality bmpstream byte bmppicbytearray bmpstreamtobytearray streamlength bmppicbytearraylength logdtag size streamlengthtry fileoutputstream bmpfile new fileoutputstreamfinalpath bmppiccompressbitmapcompressformatjpeg compressquality bmpfile bmpfileflush bmpfileclose catch exception e logetag error on saving fileis there a better way to do it should i try to keep using all 2 methods or only one thanks,['android'] +304749,extract decimal from string i am having a string like 55kg or 790gram and i want to get 55 or 790 as a decimal value how can i get such result in c and one more thing that my string will always starts with decimal my code is here but it will give error whenever it will encounter any thing except decimalstring weight attributevalueif stringisnulloremptyweight productweight converttodecimalattributevalueelse productweight 0m,"['c#', '.net']" +304764,warnings when activating the optimization options i use scanf in a c program to read an int from stdin scanfd nwhen i compile the c program with optimization enabled i get some warningsgcc mainc lm lpthread o2 o mainmainc in function amainamainc45 warning ignoring return value of ascanfa declared with attribute warn unused resultmainc50 warning ignoring return value of ascanfa declared with attribute warn unused resultbut when i remove the optimization options why do not i get those warningsgcc mainc lm lpthread o mainps i am not using wall or something similar,['c'] +304765,multisort of associative array in php consider the following associative arrayarr array banana 2 cherry 1 orange 3 grapefruit 1 apple 1i want to sort it in a way that would be similar to the plsql term a desc b asc where a is the value and b is the key meaningarr array orange 3 banana 2 apple 1 cherry 1 grapefruit 1 so that orange and banana are first because of the value but then i have apple cherry and grapefruit in alphabetical order because they have the same valuewhat i tried1 to run ksort and then asortrsort hoping that the second sort will bump up orange and banana to the beginning of the array without messing up the alphabetical sort of the other 3 items i was wrong it does messes everything up so i checked out2 sort functions and array multisort but apparently it sorts several arrays at once or a multidimensional array 3 i also tried to define the following compare functionfunction cmpa b foreach a as key1 val1 foreach b as key2 val2 ifval1 val2 return strcmpkey1key2 else if val1 val2 return 1 else val1 val2 return 1 and call it with usort but it also did not workso my question is is there a php method that implements the requested behaviorfor eugeni tried it and it does not workbefore sortingarray lamb 3 rule 1 children 1 teacher 2 eager 1and after sortingarray children 1 eager 1 rule 1 teacher 2 lamb 3,['php'] +304773,nsdateformatter in 12hour mode i have the following codensdateformatter df df settimezonenstimezone defaulttimezonedf setdateformatymmddthhmmsznsdate date df datefromstringdate string here is the problemin 24hour mode everything is ok when 12hour mode is set on device stringfromdate returns nullformat of date string is the same all the time date format too why does it happen,"['objective-c', 'ios']" +304787,java efficiently store boolean32 in java i would like to store 10 arrays of boolean values boolean with length 32 to the thisk and read them again later on for further computation and comparison since a single array will have a length of 32 i wonder whether it makes sense to store it as an integer value to speed up the reading and writing on a 32 bit machine would you suggest using bitset and then convert to int or even forget about int and use bytes,['java'] +304794,how to start an activity or service before an app application is uninstalled by the user why the same question againthis question has been asked around 100 times on so i am asking it again because all the answers say this is not possible but at least one of the app in market is doing it nq mobile security i started a bounty of 100 points on the similar question but it did not get enough attention if community does not accept i will remove the questionwhat is the app doingthe app shows an activity when user tries to uninstall itand does some processing before it is uninstalled what is my questionhow to start an activity or an intentservice before an application in uninstalled by the user who has earlier installed the app on her device,['android'] +304831,determine if uploaded file is image any format on mvc so i am using this code for viewform action methodpost enctypemultipartformdata label forfilefilenamelabel input typefile namefile idfile input typesubmit formthis for modelhttppostpublic actionresult indexhttppostedfilebase file if filecontentlength 0 var filename pathgetfilenamefilefilename var path pathcombineservermappathapp datauploads filename filesaveaspath return redirecttoactionindexworks great unless the user add a file which is not an image how can i assure the file uploaded is an image thanks,['c#'] +304856,c eigenvaluevector decomposition only need first and vectors fast i have a 30x30 covariancealike matrix on which i compute the eigenvalueeigenvector decomposition it is a opencv matrix and i use cveigen to get the job donehowever i actually only need the say first 30 eigenvaluesvectors i do not care about the rest theoretically this should allow to speed up the computation significantly right i mean that means it has 2970 eigenvectors less that need to be computedwhich c library will allow me to do that please note that opencvs eigen method does have the parameters for that but the documentation says they are ignored and i tested it myself they are indeed ignored dupdatei managed to do it with arpack i managed to compile it for windows and even to use it the results look promising an illustration can be seen in this toy exampleinclude ardsmathinclude ardssymhint and 3 dimension of the problem double eigval null eigenvalues double eigvec null eigenvectors stored sequentially int lowerhalfelementcount n 2 whole matrix 2 3 8 3 9 7 8 7 19 double lower new doublelowerhalfelementcount lower half of the matrix to be filled with column major ie one column after the other always starting from the diagonal element lower0 2 lower1 3 lower2 8 lower3 9 lower4 7 lower5 19 params dimensions ie widthheight array with values of the lower or upper half sequentially row major l or u for upper or lower ardssymmatrixdouble matn lower l defining the eigenvalue problem int noofeigvecvalues 2 int maxiterations 50 arlusymstdeigdouble dprobnoofeigvecvalues mat lm 0 05 maxiterations arlusymstdeigdouble dprobnoofeigvecvalues mat finding eigenvalues and eigenvectors int converged dprobeigenvalvectorseigvec eigval for int eigvalidx 0 eigvalidx noofeigvecvalues eigvalidx stdcout eigenvalue eigvaleigvalidx neigenvector for int i 0 i n i int idx neigvalidxi stdcout eigvecidx stdcout stdendl the results are94298 2424059for the eigenvalues and0523207 083446237 0172993460273269 0356554 0893416for the 2 eigenvectors respectively one eigenvector per rowthe code fails to find 3 eigenvectors it can only find 12 in this case an assert makes sure of that but well that is not a problem,['c++'] +304866,how can i determine if my android app has memory leak i look all over the internetgoolgestackoverflow and could not find full and simple guide that can explain to me how can i find if my android app has a memory leakcan anyone explain to me how to do it or even better give me good guide for itmy app collecting data about the battery and saves it to db on the phoneeach time that their is a change in the battery action battery changed i check if the battery precentage changed and in this case i save some datathis app takes 2530mb ram i think that this is too much for such simple appi suspect that it has a memory leak,['android'] +304868,php curl vs file get contents here is a questionhow these 2 pieces of code differ when accessing rest apiresult file get contentsapikeykeylongurlurlch curl initapikeykeylongurlurlcurl setoptch curlopt returntransfer trueresult curl execchbecause they both produce the same result judging byprint rjson decoderesult,['php'] +304869,android media player error 14 while playing an audio from assets folder i need your help i tried to play an audio file stored in assets folder but an error occurredhere are my codetry if playerisplaying playerstop playerrelease catchexception e toastmaketextthis an exception occurred toastlength longshow eprintstacktracetry assetfiledescriptor afd beedailyconvothisgetassetsopenfdsoundshello krwma playersetdatasourceafdgetfiledescriptorafdgetstartoffsetafdgetlength playerprepare playerstartcatchexception e eprintstacktraceand here are my logcat0616 2239530 wmediaplayer13490 infowarning 1 26 0616 2239530 emediaplayer13490 error 1 4could you please explain whats wrong with my codethank you in advanceregardspriska,['android'] +304873,javafx 21 tableview refresh items i have this common issue as it appears to be my table view wont refresh my items after i reset them i have checked the data and it is the new one i tried multiple solution from internet but no success cannot reset all the columns because it adds one empty one extra dont know why and the resize just breakesmy table is not editable the new data is changedthe data is refreshed if i change the ordering of the items and the rows change i am just left without ideasat the moment the refresh code is pretty simpleobservablelistuser data fxcollectionsobservablearraylistusergetresellersreseller tablesetitemsdataagain the new data is correct when i make an selection to the tableview it returns the new correct item,['java'] +304875,call nonnative java code from python i want to be able to call certain methods and such that are contained in a java jar that is already running it is guaranteed that it will be running i have found things like jython but those only seem to be able to access javas native classes and such,"['java', 'python']" +304902,why are my balls thisappearing pardon the funny title i have created a little graphic demo of 200 balls bouncing and colliding both against the walls and each other you can see what i have currently here the problem is that whenever they collide with each other they thisappear i am not sure why can someone take a look and help me outupdate apparently the balls array has balls with coordinates of nan below is the code where i push balls to the array i am not entirely sure how the coordinates are getting nan variablesvar numballs 200 number of ballsvar maxsize 15var minsize 5var maxspeed maxsize 5var balls new arrayvar tempballvar tempxvar tempyvar tempspeedvar tempanglevar tempradiusvar tempradiansvar tempvelocityxvar tempvelocityy find spots to place each ball so none start on top of each otherfor var i 0 i numballs i 1 tempradius 5 var placeok false while placeok tempx tempradius 3 mathfloormathrandom thecanvaswidth tempradius 3 tempy tempradius 3 mathfloormathrandom thecanvasheight tempradius 3 tempspeed 4 tempangle mathfloormathrandom 360 tempradians tempangle mathpi180 tempvelocityx mathcostempradians tempspeed tempvelocityy mathsintempradians tempspeed tempball x tempx y tempy nextx tempx nexty tempy radius tempradius speed tempspeed angle tempangle velocityx tempvelocityx velocityy tempvelocityy mass tempradius placeok canstartheretempball ballspushtempball,['javascript'] +304915,remove punctuation from unicode formatted strings i have a function that removes punctuation from a list of stringsdef strip punctuationinput x 0 for word in input inputx resubrazaz09 inputx x 1 return inputi recently modified my script to use unicode strings so i could handle other nonwestern characters this function breaks when it encounters these special characters and just returns empty unicode strings how can i reliably remove punctuation from unicode formatted strings,['python'] +304928,native and managed destructors i have a native object c that has a gcroot pointer to a managed object c class somenativeclass gcrootsomemanagedclass managedclassquestionwhen i delete a native instance of this class in native code deletesomenativeclass that i previously allocated will the managedclass instance get garbage collected or should i explicitly delete it in the native destructor as well,['c#'] +304936,rails 32 postgres save error activerecordstatementinvalid pgerror error syntax error near t at position 5 my app has started throwing errors when i try to save a particular class to the database i am not sure exactly what caused this to start happening i have been having all kinds of database issues for the last few daysin any case my model seems to be working fine it is properly calculating all of the before save values but then it tries to save to the database and blows upsql 08ms insert into portfolios correlation matrix created at data mean return std dev updated at weights values 1 2 3 4 5 6 7 returning id correlation matrix n 10n 04873114574375062n 04873114574375062n 10n created at sat 16 jun 2012 151235 mdt 0600 data tsx05 vustx05 mean return bigdecimal7fadb119b7500488052381e11845 std dev bigdecimal7fadb119b59807668705159 123244e11845 updated at sat 16 jun 2012 151235 mdt 0600 weights ntsx 05nvustx 05nthrows this erroractiverecordstatementinvalid pgerror error syntax error near t at position 5i have no idea what this error means or what this t is or even where to begin troubleshooting it any help would be appreciatedi can post whatever information might be necessary to figure this outrelevant migration create table portfolios do t ttext weights tdecimal mean return precision 15 scale 10 tdecimal std dev precision 15 scale 10 ttext correlation matrix thstore data ttimestamps end execute create index portfolios gin data hstore on portfolios using gindatafull stack trace activerecordstatementinvalid pgerror error syntax error near t at position 5 insert into portfolios correlation matrix created at data mean return std dev updated at weights values 1 2 3 4 5 6 7 returning id from usersbrandonrvmgemsruby193p194myappgemsactiverecord32 6libactive recordconnection adapterspostgresql adapterrb1164in get last result from usersbrandonrvmgemsruby193p194myappgemsactiverecord32 6libactive recordconnection adapterspostgresql adapterrb1164in exec cache from usersbrandonrvmgemsruby193p194myappgemsactiverecord32 6libactive recordconnection adapterspostgresql adapterrb665in block in exec query from usersbrandonrvmgemsruby193p194myappgemsactiverecord32 6libactive recordconnection adaptersabstract adapterrb280in block in log from usersbrandonrvmgemsruby193p194myappgemsactivesupport326libactive supportnotificationsinstrumenter rb20in instrument from usersbrandonrvmgemsruby193p194myappgemsactiverecord32 6libactive recordconnection adaptersabstract adapterrb275in log from usersbrandonrvmgemsruby193p194myappgemsactiverecord32 6libactive recordconnection adapterspostgresql adapterrb663in exec query from usersbrandonrvmgemsruby193p194myappgemsactiverecord32 6libactive recordconnection adaptersabstractdatabase statementsrb63in exec insert from usersbrandonrvmgemsruby193p194myappgemsactiverecord32 6libactive recordconnection adaptersabstractdatabase statementsrb90in insert from usersbrandonrvmgemsruby193p194myappgemsactiverecord32 6libactive recordconnection adaptersabstractquery cacherb14in insert from usersbrandonrvmgemsruby193p194myappgemsactiverecord326libactive recordrelationrb66in insert from usersbrandonrvmgemsruby193p194myappgemsactiverecord326libactive recordpersistencerb363in create from usersbrandonrvmgemsruby193p194myappgemsactiverecord326libactive recordtimestamprb57in create from usersbrandonrvmgemsruby193p194myappgemsactiverecord326libactive recordcallbacksrb268in block in create from usersbrandonrvmgemsruby193p194myappgemsactivesupport326libactive supportcallbacksrb403in run 772785567275930853 create 1186465801021498362 callbacks from usersbrandonrvmgemsruby193p194myappgemsactivesupport326libactive supportcallbacksrb405in run callback 11 levels from usersbrandonrvmgemsruby193p194myappgemsactiverecord326libactive recordvalidationsrb50in save from usersbrandonrvmgemsruby193p194myappgemsactiverecord326libactive recordattribute methodsdirtyrb22in save from usersbrandonrvmgemsruby193p194myappgemsactiverecord326libactive recordtransactionsrb241in block 2 levels in save from usersbrandonrvmgemsruby193p194myappgemsactiverecord326libactive recordtransactionsrb295in block in with transaction returning status from usersbrandonrvmgemsruby193p194myappgemsactiverecord32 6libactive recordconnection adaptersabstractdatabase statementsrb192in transaction from usersbrandonrvmgemsruby193p194myappgemsactiverecord326libactive recordtransactionsrb208in transaction from usersbrandonrvmgemsruby193p194myappgemsactiverecord326libactive recordtransactionsrb293in with transaction returning status from usersbrandonrvmgemsruby193p194myappgemsactiverecord326libactive recordtransactionsrb241in block in save from usersbrandonrvmgemsruby193p194myappgemsactiverecord326libactive recordtransactionsrb252in rollback active record state from usersbrandonrvmgemsruby193p194myappgemsactiverecord326libactive recordtransactionsrb240in save from irb33 from usersbrandonrvmgemsruby193p194myappgemsrailties326librailscommandsconsolerb47in start from usersbrandonrvmgemsruby193p194myappgemsrailties326librailscommandsconsolerb8in start from usersbrandonrvmgemsruby193p194myappgemsrailties326librailscommandsrb41in top required from scriptrails6in require from scriptrails6in mainupdate 1some model code as requestedmacro stuffattr accessible weightsserialize correlation matrixserialize weightshas and belongs to many securities uniq truehas and belongs to many efficient frontiersbefore validation format weights tickers add securities validate weights set weights in hstore build correlation matrix set mean return set standard deviationvalidates presence of mean return std dev securities correlation matrix weightsvalidates numericality of mean return std devvalidate uniqueness of weights before destroy check for dependentscope by std dev order std dev ascanything and everything i can find to do with the hstore columnall i really use hstore for is for a search on specific tickers this used to work i do not know what changed i might have upgraded postgres i was fiddling around with homebrew or potentially something changed with rails i did try going back to 323 but i got the same errordef selffind by hstoresearch key search value wheredata key value key search keyto s value search valueto send def set weights in hstore selfdata if selfdatanil weightseach pair ticker weight selfdatatickerto s weightendi can post the entirety of the model if this is too thisjointed let me knowupdate 2 i am getting similar errors elsewhere alsoafter a simple user signupsql 109ms insert into users admin confirmation sent at confirmation token confirmed at created at current sign in at current sign in ip data email encrypted password last email at last sign in at last sign in ip name plan remember created at reset password sent at reset password token selected portfolio id sign in count unconfirmed email updated at verified values 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 returning id admin false confirmation sent at sat 16 jun 2012 203707 mdt 0600 confirmation token 7xu15pmrv9ztnmofv8bd confirmed at nil created at sat 16 jun 2012 203707 mdt 0600 current sign in at nil current sign in ip nil data min rebalance spacing90 days max contact frequency7 days allowable drift5 email encrypted password 2a10hnumlymcvxbbsyzrfcab7e8c5mf6s9uodwrzcz10y5sg4goh8zvq last email at sat 16 jun 2012 203707 mdt 0600 last sign in at nil last sign in ip nil name joe blow plan basic remember created at nil reset password sent at nil reset password token nil selected portfolio id nil sign in count 0 unconfirmed email nil updated at sat 16 jun 2012 203707 mdt 0600 verified false203707 log1 ef4a7d55fb30e8fb82ac6c860e674bfc 127001 pgerror error syntax error near m at position 5203707 log1 insert into users admin confirmation sent at confirmation token confirmed at created at current sign in at current sign in ip data email encrypted password last email at last sign in at last sign in ip name plan remember created at reset password sent at reset password token selected portfolio id sign in count unconfirmed email updated at verified values 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 returning idudpate 3there appears to be something funky going on with my database user table i get the following error during loading the environment in a migrationrake abortedpgerror error relation users does not existline 4 where aattrelid usersregclass select aattname format typeaatypid aatypmod dadsrc aattnotnull from pg attribute a left join pg attrdef d on aattrelid dadrelid and aattnum dadnum where aattrelid usersregclass and aattnum 0 and not aattisdropped order by aattnum,"['ruby-on-rails', 'ruby']" +304969,actionviewtemplateerror is not precompiled in production heroku i am getting the following errorstarted get articles1 for 50134181231 at 20120617 003735 020120617t0037350 appweb1 actionviewtemplateerror is not precompiled20120617t0037350 herokurouter get wandrcomarticles1 dynoweb1 queue0 wait0ms service497ms status500 bytes72820120617t0037350 appweb1 20120617t0037350 appweb1 74 image tag articlefeatured photo urlsmto s20120617t0037350 appweb1 75 20120617t0037350 appweb1 77 image tag articlebackground photo urlmdto s20120617t0037350 appweb1 76 p20120617t0037350 appweb1 78 p20120617t0037350 appweb1 79 image tag articlecover photo urlmdto s20120617t0037350 appweb1 80 20120617t0037350 appweb1 appviewsarticlesshowhtmlhaml77in app views articles show html haml 1847247375488199378 4810550020120617t0037350 appweb1 20120617t0037350 appweb1 appcontrollersarticles controllerrb21in show20120617t0037350 appweb1 20120617t0037350 appweb1 processing by articlescontrollershow as html20120617t0037350 appweb1 rendered articlesshowhtmlhaml within layoutsadmin 4205ms20120617t0037350 appweb1 parameters id120120617t0037350 appweb1 completed 500 internal server error in 486msi am running rails 326 including actionpack 326 which i thought had this fix for this issue i also tried this actionviewtemplateerror isnt precompiled raised on image tag nilbasically as long as one of the images on this page do not exist it is throwing this error if i upload the images it works fine any ideasthanksmark,['ruby-on-rails'] +304971,using like in bindparam for a mysql pdo query i have read multiple examples on how these queries should be written but i am struggling to get this specific like to run when using bindparamwould this be the correct way to match usernames that begin with aterm aterm termsql select username from user where username like term limit 10 core connectgetinstancestmt coredbhpreparesqlstmtbindparamterm term pdoparam strstmtexecutedata stmtfetchall,"['php', 'mysql']" +304972,what is the most efficient way to parse a css color in javascript given a string of a valid css color valuefwhitergb255 255 255need to get an array of numbers of the following format r g bwhat is the most efficient way of doing this in javascript assuming a major browser,"['javascript', 'css']" +304979,arduino c language parsing string with delimiter input through serial interface arduino c language parsing string with delimiter input through serial interfacedid not find the answer here i want to send to my arduino through a serial interface serialread a simple string of three numbers delimited with comma those three numbers could be of range 0255 eg 2552552550120100902003what i need to do is to parse this string sent to arduino to three integers let us say r g and bso when i send 1005030 arduino will translate it toint r 100int g 50int b 30i tried lots of codes but none of them worked the main problem is to translate string bunch of chars to integer i figured out that there will probably be strtok r for delimiter purpose but that is about itthanks for any suggestions,['c'] +304984,htaccess rewritecond where uri does not contain domain i have looked around on google and stackoverflow for the answer to this question but the fact that i do not know much about htaccess does not help me decide what the correct answers for my situation are so i am asking heremy situation is that i have several sites that are using the same physical directory as their root on the serverthis is all working fine but i wanted to make sure that each site cannot access each others images etc from the browser unless they are on the correct domaincurrently i have a file structure like thisresourcesresourcefull domain nameso for example wdomaincouk would have a structure like this imagejpgbut if wdomain 2couk exists using the same physical directory for the site root then they can look at other domains resources from their own domain like this 2coukresourcesimageswdomaincouksome imagejpgthis is not really a major problem since there is absolutely no sensitive information stored in these directories but it is more of an annoyance and i would rather users were not able to do it not that anyone actually has so fari tried putting a htaccess file into the resources directory but i am stuck with the regular expressions etci basically want to make sure that the uri contains the current domain name otherwise redirect to a 403 error pagethis is what i came up withrewritecond request uri resourceshttp hostrewriterule error403phpthe reason i put in the bit is because there are several folders for exampleresourcesimagesfull domain nameresourcesscriptsfull domain nameresourcesstylesheetsfull domain namecould anybody help me with these conditionsany help would be appreciated,['php'] +304990,rails autoassigning id that already exists i create a new record like sotruck truckcreatenamename user id2my database currently has several thousand entities for truck but i assigned the ids to several of them in a way that left some ids available so whats happening is rails creates item with id 150 and it works fine but then it tries to create an item and assign it id 151 but that id may already exist so i am seeing this erroractiverecordrecordnotunique pgerror error duplicate key value violates unique constraint companies pkeydetail key id151 already existsand the next time i run the action it will simply assign the id 152 which will work fine if that value is not already taken how can i get rails to check whether an id already exists before it assigns itthankseditthe truck id is what is being duplicated the user already exists and is a constant in this case it actually is a legacy issue that i have to deal with one option is to recreate the table at let rails auto assign every id this time around i am beginning to think this may be the best choice because i am have a few other problems but the migration for doing this would be very complicated because truck is a foreign key in so many other tables would there be a simple way to have rails create a new table with the same data already stored under truck with autoassigned ids and maintaining all existing relationships,['ruby-on-rails'] +305009,how to apply 3d transition between two activities in android i have an android application and while switching between two activities i want to apply 3d transition i know the method overridependingtransition but it does not have any animation for 3d so how it can be done,['android'] +305015,click event for element nested within a button here is a simple example of the problembody button idparent onclickalertparent span idchild onclickalertchildauthenticatespan buttonbodyin chrome this alerts child then parent but in ieff we only get parentclearly this can be fixed in a number of ways change button to div remove span etc but i wanted to find out if there was a way to make this work ie alert child without changing the htmlthanksps tried jquery and that has same behaviour,"['javascript', 'html']" +305053,how can i style a part of a single character with overlays using a dynamic width questioncan i style just a part of a single charactermeaningcss attributes cannot be assigned to parts of characters but if you want to style only a certain section of a character there is no standardized way to do thatexampleis it possible to style an x which is halfway red and then blacknot working codediv classcontent xdivcontent position relative fontsize 50px color blackcontentafter content x color red width 50 position absolute overflow hiddendemo on jsfiddlepurposemy intention is styling the font awesome iconstar symbol if i have an overlay with dynamic width should not it be possible to create an exact visualization of scores,"['html', 'css']" +305065,jquery uncaught typeerror illegal invocation at ajax request when data parameter is array i have two select elements a and b when as selected option changes bs options must be updated accordingly each element in a implies many elements in b it is a onetomany relationship a contains nations b should contain cities located in the given nationthe function do ajax should run the asynchronous requestfunction do ajaxelem mydata filename ajax url filename context elem data mydata datatype html success function data textstatus xhr eleminnerhtml data in order to update bs options i have added a function call in as onchange event here is the function that runs when onchange event of a is triggeredfunction my onchangee e is element a var sel b get select element b i skipped some code here var data mode filter city id a eeselectedindex do ajaxcity sel data ajax handlerphpi have read in jquery docs that data can be an array key value pairs i get the error if i putvar data mode filter city id a eeselectedindexinstead i do not get that error if my data is a stringvar data modefilter cityampid a eeselectedindexbut i need the array version of the variable in my serverside php code the uncaught typeerror illegal invocation is located in the jquery172minjs file which is all compressed so i could not figure out what part of code raised the erroris there any setting i can change in my code so that it accepts data as an associative array,"['html', 'jquery']" +305067,conditional page break in reportlab i am creating pdfs tables with reportlab platypus i dona t know when the page is full because of the dynamic content how can i check out if i am at the end of the page is there any method in platypus to check end of pagei have list of companies and each company has multiple business units with their charges companies company1 businessunit1 500 company1 businessunit2400 company2 businessunit3200 company2 businessunit4 700 company3 businessunit5 800 the above list should generate 3 tables each for one company but if this list has multiple companies which will generates multiple tables and if any table reaches end of page which will break fields company name business unit name charge for i comp in enumeratecompanies charges documentappendparagraphbsb compi0 stylescompany name documentappendspacer1 5 chargesappendcompi0 chargesappendcompi1 chargesappendcompi2 charges table longtablefields charges colwidths30150100 charges tablesetstyletablestyle background 0 0 1 0 colorsgray fontsize 0 0 1 0 6 grid 0 0 1 1 1 colorsgray fontsize 0 0 1 1 7 textcolor01ff4500 charges tablehalign center documentappendcharges table,['python'] +305069,free memory allocated in a different function i am trying to learn c and i am currently trying to write a basic stack data structure but i cannot seem to get basic mallocfree rightheres the code i have been using i am just posting a small part here to illustrate a specific problem not the total code but the error message was generated just by running this example code in valgrindinclude stdiohinclude stdlibhtypedef struct entry struct entry previous int value entryvoid destroyentryentry entryint mainint argc char argv entry apple apple mallocsizeofentry destroyentryapple return 0void destroyentryentry entry entry entry ptr entry frentry ptr returnwhen i run it through valgrind with leakcheckfull trackoriginsyes i get the following error20674 invalid free delete delete realloc20674 at 0x4028e58 free vg replace mallocc42720674 by 0x80485b2 destroyentry testingc5320674 by 0x8048477 main testingc2620674 address 0xbecc0070 is on thread 1s stacki think this error means that the destroyentry function is not allowed to modify memory allocated explicitly in main is that right why cannot i just free the memory i allocated in main in another function and is this behavior somehow specific to main,['c'] +305093,play framework run application issue i am getting the following error whenever i am trying to run a new web application created using playerror occurred during initialization of vmcould not reserve enough space for object heaperror could not create the java virtual machineerror a fatal exception has occurred program will exit,['java'] +305101,i need to round a float to two decimal places in java possible duplicatehow to round a number to and decimal places in java i am having difficulties rounding a float to two decimal places i have tried a few methods i have seen on here including simply just using mathround but no matter what i do i keep getting unusual numbersi have a list of floats that i am processing the first in the list is thisplayed as 12975118e7 what is the e7when i use mathroundf f is the float i get the exact same numberi know i am doing something wrong i just am not sure whati just want the numbers to be in the format x the first number should be 130 etc,"['java', 'android']" +305112,using gzip compression in sinatra with ruby note i had another similar question about how to gzip data using rubys zlib which technically was answered and i did not feel i could start evolving the question since it had been answered so although this question is related it is not the samethe following code i believe is gziping a static css file and storing the results in the result variable but what do i do with this in the sense how can i send this data back to the browser so it is recognised as being gziped rather than the original file size eg when checking my yslow score i want to see it correctly marking me for making sure i gzip static resourcesz zlibdeflatenew6 31zdeflatefilereadpublicassetsstylesbuildcsszflushresult zfinish could also of done result zdeflatefile zlibfinish zcloseone thing to note is that in my previous question the respondent clarified that zlibdeflatedeflate will not produce gzipencoded data it will only produce zlibencoded data and so i would need to use zlibdeflatenew with the windowbits argument equal to 31 to start a gzip streambut when i run this code i do not actually know what to do with the result variable and its content there is no information on the internet that i can find about how to send gzip encoded static resources like javascript css html etc to the browser this making the page load quicker it seems every ruby article i read is based on someone using ruby on railsany help really appreciated,['ruby'] +305118,does check for full equality in booleans java so i have heard that if i compare 2 strings with then i will only get true back if they both refer to the same objectinstance that is strings what about booleans,['java'] +305152,stop on last element iterators c what is the most elegant way to perform a loop and stop after the second to last element in c11note i mean for bidirectional iterators random access iterators are a trivial special case of course because they have and operatorsstdlistdouble x123456for auto iter xbegin iter xend iter auto iter2 iter iter2 if iter2 xend break stdcout iter stdendl,['c++'] +305153,where to validate methods arguments i am wondering where and how often in the code validate methods arguments in the example class below a dll library what do you think is the best way suppose i want to validate that some object cannot be null but it can be any other validation required for method to run properly is it better to check it only once in point 1 in public method avaible for user and later trust myself that in other private methods it will not be null or better be a little paranoid and check it every time it is going to be used in points 2 3 and 4 checking it just before using the object in points 2 3 4 protects me in the future if i decide to change something in the class using these private methods and forget to pass valid object also i do not have to remember about validation if i add some new public method in the future on the other hand it is checking for the same condition over and over again or maybe you have some other suggestionspublic class myclass public myclass public void processobjectsomeobject obj 1 if obj null throw new argumentexceptionyou must provide valid object dosomethingobj domoreobj dosomethingelseobj private void dosomethingsomeobject obj 2 if obj null throw new argumenexceptionyou must provide valid object do something with obj private void domoresomeobject obj 3 if obj null throw new argumentexceptionyou must provide valid object do something with obj private void dosomethingelsesomeobject obj 4 if obj null throw new argumentexceptionyou must provide valid object do something with obj,"['c#', '.net']" +305160,what does universal character name conversion mean in c c98 apparently has this as one of the standards for compilation phases what does it mean and why is it executed initially,['c++'] +305185,next iterator method for associative array i want to use an associative array with the php iteratoris it possiblei defined these methods public function rewind resetthis arr this position keythis arr public function current return this arrthis position public function key return this position public function next this position public function valid return issetthis arrthis position the problem is it does not iterate correctly i only get one elementi think it is because of the this position code in the next method which does not have any effect because position is a string key of the associative arrayso how can i go to the next element of this type of array,['php'] +305208,heroku were sorry but something went wrong firstly i am quite a newbie in railsheroku so forgive the newbiness in advancei did the rails tutorial startedhtml and generated a bloglike post app pushed it into github and then pushed into herokumy app works fine locally but when i try to run it online it has the were sorry but something went wrong in red font errorhere is the heroku logs20120617t1820210 appweb1 started get postsnew for 242467591 at 20120617 182021 020120617t1820210 appweb1 processing by postscontrollernew as html20120617t1820210 appweb1 rendered posts formhtmlerb 194ms20120617t1820210 appweb1 rendered postsnewhtmlerb within layoutsapplication 328ms20120617t1820210 appweb1 completed 500 internal server error in 39ms20120617t1820210 appweb1 20120617t1820210 appweb1 13 20120617t1820210 appweb1 actionviewtemplateerror undefined method name for post0x043b8e0020120617t1820210 appweb1 14 div classfield20120617t1820210 appweb1 15 flabel name br 20120617t1820210 appweb1 18 div classfield20120617t1820210 appweb1 17 div20120617t1820210 appweb1 16 ftext field name 20120617t1820210 appweb1 19 flabel title br 20120617t1820210 appweb1 appviewsposts formhtmlerb16in block in app views posts form html erb 43933465537738631 3365120020120617t1820210 appweb1 appviewsposts formhtmlerb1in app views posts form html erb 43933465537738631 3365120020120617t1820210 appweb1 appviewspostsnewhtmlerb3in app views posts new html erb 263954971377171473 3747350020120617t1820210 appweb1 appcontrollersposts controllerrb35in new20120617t1820210 appweb1 in a nutshell fname is an object representing an entry in the database so is most of the information for fthe undefined method name error seems strange to me as it works perfectly locallymy hypothesis is that the database is not linked properly between heroku and my apphowever i do not know how i can solvecheck this problemmy app is using the shared database by default right nowany hints on what check something i missededit 1migrating database the table posts seems to be already detected here is a trace running rake dbmigrate trace attached to terminal up run1deprecation warning you have rails 23style plugins in vendorplugins support for these plugins will be removed in rails 40 move them out and bundle them in your gemfile or fold them in to your app as libmyplugin and configinitializersmypluginrb see the release notes for more on this called from top required at apprakefile7deprecation warning you have rails 23style plugins in vendorplugins support for these plugins will be removed in rails 40 move them out and bundle them in your gemfile or fold them in to your app as libmyplugin and configinitializersmypluginrb see the release notes for more on this called from top required at apprakefile7 invoke dbmigrate first time invoke environment first time execute environment invoke dbload config first time invoke rails env first time execute rails env execute dbload config execute dbmigratemigrating to createposts 20120418005214 createposts migrating create tablepostsrake abortedan error has occurred this and all later migrations canceledpgerror error relation posts already exists create table posts id serial primary key name character varying255 title character varying255 content text created at timestamp not null updated at timestamp not null appvendorbundleruby191gemsactiverecord321libactive recordconnection adapterspostgresql adapterrb640in async execappvendorbundleruby191gemsactiverecord321libactive recordconnection adapterspostgresql adapterrb640in block in executeappvendorbundleruby191gemsactiverecord321libactive recordconnection adaptersabstract adapterrb280in block in logappvendorbundleruby191gemsactivesupport321libactive supportnotificationsinstrumenterrb20in instrumentappvendorbundleruby191gemsactiverecord321libactive recordconnection adaptersabstract adapterrb275in logappvendorbundleruby191gemsactiverecord321libactive recordconnection adapterspostgresql adapterrb639in executeappvendorbundleruby191gemsactiverecord321libactive recordconnection adaptersabstractschema statementsrb170in create tableappvendorbundleruby191gemsactiverecord321libactive recordmigrationrb450in block in method missingappvendorbundleruby191gemsactiverecord321libactive recordmigrationrb424in block in say with timeappvendorruby193p0libruby191benchmarkrb280in measureappvendorbundleruby191gemsactiverecord321libactive recordmigrationrb424in say with timeappvendorbundleruby191gemsactiverecord321libactive recordmigrationrb4in method missingappdbmigrate20120418005214 create postsrb3in changeappvendorbundleruby191gemsactiverecord321libactive recordmigrationrb393in block 2 levels in migrateappvendorruby193p0libruby191benchmarkrb280in measureappvendorbundleruby191gemsactiverecord321libactive recordmigrationrb393in block in migrateappvendorbundleruby191gemsactiverecord321libactive recordconnection adaptersabstractconnection poolrb118in with connectionappvendorbundleruby191gemsactiverecord321libactive recordmigrationrb377in migrateappvendorbundleruby191gemsactiverecord321libactive recordmigrationrb512in migrateappvendorbundleruby191gemsactiverecord321libactive recordmigrationrb704in block 2 levels in migrateappvendorbundleruby191gemsactiverecord321libactive recordmigrationrb759in callappvendorbundleruby191gemsactiverecord321libactive recordmigrationrb759in block in ddl transactionappvendorbundleruby191gemsactiverecord321libactive recordconnection adaptersabstractdatabase statementsrb190in transactionappvendorbundleruby191gemsactiverecord321libactive recordtransactionsrb208in transactionappvendorbundleruby191gemsactiverecord321libactive recordmigrationrb759in ddl transactionappvendorbundleruby191gemsactiverecord321libactive recordmigrationrb703in block in migrateappvendorbundleruby191gemsactiverecord321libactive recordmigrationrb684in eachappvendorbundleruby191gemsactiverecord321libactive recordmigrationrb684in migrateappvendorbundleruby191gemsactiverecord321libactive recordmigrationrb554in upappvendorbundleruby191gemsactiverecord321libactive recordmigrationrb535in migrateappvendorbundleruby191gemsactiverecord321libactive recordrailtiesdatabasesrake153in block 2 levels in top requiredappvendorbundleruby191gemsrake0922libraketaskrb205in callappvendorbundleruby191gemsrake0922libraketaskrb205in block in executeappvendorbundleruby191gemsrake0922libraketaskrb200in eachappvendorbundleruby191gemsrake0922libraketaskrb200in executeappvendorbundleruby191gemsrake0922libraketaskrb158in block in invoke with call chainappvendorruby193p0libruby191monitorrb211in mon synchronizeappvendorbundleruby191gemsrake0922libraketaskrb151in invoke with call chainappvendorbundleruby191gemsrake0922libraketaskrb144in invokeappvendorbundleruby191gemsrake0922librakeapplicationrb116in invoke taskappvendorbundleruby191gemsrake0922librakeapplicationrb94in block 2 levels in top levelappvendorbundleruby191gemsrake0922librakeapplicationrb94in eachappvendorbundleruby191gemsrake0922librakeapplicationrb94in block in top levelappvendorbundleruby191gemsrake0922librakeapplicationrb133in standard exception handlingappvendorbundleruby191gemsrake0922librakeapplicationrb88in top levelappvendorbundleruby191gemsrake0922librakeapplicationrb66in block in runappvendorbundleruby191gemsrake0922librakeapplicationrb133in standard exception handlingappvendorbundleruby191gemsrake0922librakeapplicationrb63in runappvendorbundleruby191gemsrake0922binrake33in top requiredappvendorbundleruby191binrake19in loadappvendorbundleruby191binrake19in maintasks top dbmigrateedit 2 tried dropping te database strange error190634ed3ed3heroku run rake dbdroprunning rake dbdrop attached to terminal up run1deprecation warning you have rails 23style plugins in vendorplugins support for these plugins will be removed in rails 40 move them out and bundle them in your gemfile or fold them in to your app as libmyplugin and configinitializersmypluginrb see the release notes for more on this called from top required at apprakefile7deprecation warning you have rails 23style plugins in vendorplugins support for these plugins will be removed in rails 40 move them out and bundle them in your gemfile or fold them in to your app as libmyplugin and configinitializersmypluginrb see the release notes for more on this called from top required at apprakefile7could not drop mtstktqkyx activerecordstatementinvalid pgerror error must be owner of database mtstktqkyx drop database if exists mtstktqkyxedit 3 createposts migration from dbmigrate create postsrbclass createposts activerecordmigration def change create table posts do t tstring name tstring title ttext content ttimestamps end endend,"['ruby-on-rails', 'ruby']" +305210,how do i use popover from twitter bootstrap to thisplay an image the canonical example for twitter bootstraps popover feature is sort of a tooltip on steroids with a title html a href idblob classbtn large primary relpopover datacontentand heres some amazing content it is very engaging right dataoriginaltitlea titlehover for popoverajsscriptblobpopoveroffset 10scripti would like to use popover to thisplay an image is this possible,['javascript'] +305225,is kernelschedccontext switch guaranteed to be invoked every time a process is switched in i want to alter the linux kernel so that every time the current pid changes ie a new process is switched in some diagnostic code is executed detailed explanation below if curious i did some digging around and it seems that every time the scheduler chooses a new process the function context switch is called which makes sense this is just from a cursory analysis of schedcschedule the problem is the linux scheduler is basically black magic to me right now so i would like to know if that assumption is correct is it guaranteed that every time a new process is selected to get some time on the cpu the context switch function is called or are there other places in the kernel source where scheduling could be handled in other situations or am i totally misunderstanding all thisto give some context i am working with the marss x86 simulator trying to do some instrumentation and measurement of certain programs the problem is that my instrumentation needs to know which executing process certain code events correspond to in order to avoid misinterpreting the data the idea is to use some builtin message passing systems in marss to pass the pid of the new process on every context switch so it always knows what pid is currently in execution if anyone can think of a simpler way to accomplish that that would also be greatly appreciated,['c'] +305234,is it possible to iterate through all nodes with py2neo is there a way to iterate through every node in a neo4j database using py2neomy first thought was iterating through graphdatabaseservice but that did not work if there is not a way to do it with py2neo is there another python interface that would let meedit i am accepting nicholass answer for now but i will update it if someone can give me a way that returns a generator,['python'] +305249,what does variable declaration with multiple comma separated values mean eg var a bcd when i try to understand plugin codes i often find these kind of declarations but i do not know exactly what it meansvar a bcd,['javascript'] +305250,the bare minimum needed to write a msmq sample application i have been researching for over an hour and finding great samples of how to use msmq in c and even one full chapter of a book about message queuebut for a quick test all i need is to cover is this scenario not even in a perfect way just for a quick demoapplication a writes a message to message queue application a is a c windows servicenow i open application b it is a c winforms app and i check msmq and i see oh i have a new messagethat is it all i need for a simple democould anyone please help me with a code sample for this much appreciated,['c#'] +305270,how to change the default color of datepicker and timepicker dialog in android is there any way to change the default color of datepicker and timepicker dialogthis is the code i trieddatepicker stylestyledate picker androidbackground6495ed androidididdatepicker androidlayout widthfill parent androidlayout heightwrap content androidlayout margintop5dp androidlayout marginbottom5dp androidlayout marginleft5dip androidlayout marginright5dip timepicker androidididtimepicker androidlayout widthfill parent androidlayout heightwrap content androidlayout margintop5dp androidlayout marginbottom5dp androidlayout marginleft5dip androidlayout marginright5dip below two line only changing the background color i want to change the default silver color of both date and time picker any help pleasestylestyledate pickerandroidbackground6495ed,['android'] +305306,xmlregistry how does it work i have found some examples of jaxb2 xmlregistry over the internet but no good indepth tutorials that talk about the concept of using xmlregistry with xmlelementdecl wonder if its a concept not much explored in generalanyways here is my question first some sample classes that i am using to unmarshall an xml using jaxbthe main class i am trying to unmarshal using jaxb employeejavapackage comtestjaxbimport javautillistimport javaxxmlbindjaxbelementimport javaxxmlbindannotationxmlelementdeclimport javaxxmlbindannotationxmlregistryimport javaxxmlbindannotationxmlrootelementimport javaxxmlnamespaceqnameimport comtestjaxbdtoaddressxmlrootelementpublic class employee private int id private string name private string email private listaddress addresses public int getid return id public void setidint id thisid id public string getname return name public void setnamestring name thisname name public string getemail return email public void setemailstring email thisemail email public listaddress getaddresses return addresses public void setaddresseslistaddress addresses thisaddresses addresses suppresswarningsunused xmlregistry public static class xmlobjectfactory xmlelementdeclscope employeeclass name id jaxbelementstring createemployeeidstring value return new jaxbelementstringnew qnameid stringclass 100 xmlelementdeclscope employeeclass name name jaxbelementstring createnamestring value return new jaxbelementstringnew qnamename stringclass fake name xmlelementdeclscope employeeclass name email jaxbelementstring createemailstring value return new jaxbelementstringnew qnameemail stringclass value xmlelementdeclscope employeeclass name addresses jaxbelementlist createaddresseslist value return new jaxbelementlistnew qnameaddresses listclass value the child class addressjavapackage comtestjaxbdtoimport javaxxmlbindjaxbelementimport javaxxmlbindannotationxmlelementdeclimport javaxxmlbindannotationxmlregistryimport javaxxmlbindannotationxmlrootelementimport javaxxmlnamespaceqnameimport comtestjaxbemployeexmlrootelementpublic class address private string addressline1 private string addressline2 private string addressline3 public string getaddressline1 return addressline1 public void setaddressline1string addressline1 thisaddressline1 addressline1 public string getaddressline2 return addressline2 public void setaddressline2string addressline2 thisaddressline2 addressline2 public string getaddressline3 return addressline3 public void setaddressline3string addressline3 thisaddressline3 addressline3 suppresswarningsunused xmlregistry private static class xmlobjectfactory xmlelementdeclscope employeeclass name addressline1 jaxbelementstring createaddressline1string value return new jaxbelementstringnew qnameaddressline1 stringclass value xmlelementdeclscope employeeclass name addressline2 jaxbelementstring createaddressline2string value return new jaxbelementstringnew qnameaddressline2 stringclass value xmlelementdeclscope employeeclass name addressline3 jaxbelementstring createaddressline3string value return new jaxbelementstringnew qnameaddressline3 stringclass value the xml to be unmarshalled employeexmlxml version10 encodingutf8 standaloneyesemployee id1id namevaishaliname emailemail addresses address addressline1300addressline1 addressline2mumbaiaddressline2 addressline3indiaaddressline3 address address addressline1301addressline1 addressline2puneaddressline2 addressline3indiaaddressline3 address addressesemployeeunmarshalling code package comtestjaxbimport javaiofilereaderimport javaxxmlbindjaxbcontextimport javaxxmlbindunmarshallerpublic class objectfactorytest public static void mainstring args throws exception filereader reader new filereaderresourcesemployeexml jaxbcontext context jaxbcontextnewinstanceemployeeclass unmarshaller unmarshaller contextcreateunmarshaller object obj unmarshallerunmarshalreader systemoutprintlnobj when i unmarshal the employee xml using above code the address list does not get populated the resulting employee object only has a blank list of adresses is there anything wrong with my mappingsto find out what is going on and see if the employee objects are actually being created using the object factory having the xmlregistry annotation i changed the value of id and name in factory methods however that had no effect in the output which tells me jaxb is not actually using the objectfactory whyam i going aboout this all wrong any help would be appreciated,['java'] +305315,threadsafe circular buffer in java consider a few web server instances running in parallel each server holds a reference to a single shared status keeper whose role is keeping the last n requests from all serversfor example n3server a request id abcd status keeperabcdserver b request id xyzz status keeperabcd xyzz server c request id 1234 status keeperabcd xyzz 1234server b request id foo status keeperxyzz 1234 fooserver a request id bar status keeper1234 foo barat any point in time the status keeper might be called from a monitoring application that reads these last n requests for an sla reportwhats the best way to implement this producerconsumer scenario in java giving the web servers higher priority than the sla reportcircularfifobuffer seems to be the appropriate data structure to hold the requests but i am not sure whats the optimal way to implement efficient concurrency,['java'] +305321,what does the statement avoidstartguardbegina do possible duplicatewhat does void new mean in c i am not familiar with c and i do not understand the line right after the method signatureint ean13readerdecodemiddlerefbitarray row int startguardbegin int startguardend stdstring resultstring voidstartguardbegin whats voidstartguardbegin a method invokation,['c++'] +305354,does ie9 have a file size limit for css i am using drupal and i notice that if i have my css files aggregated that the css does not always work correctly i know there is a problem in ie7 but is there a limit to a css file size in ie9,['css'] +305362,how to thisplay the asynchronous results which one is first in aspnetweb application i have to send three asynch requests in three class files 3 requests response times are different first one is 2sec and second one is 7sec and third one is 4sec now i have to thisplay first response in browser with in 2sec and after 2sec thisplay the third response and finally thisplay the second response but now my results all responses thisplay at a time after completed three responses please give me any suggestion it is very urgent pleasemy code is public delegate string asyncmethodcallerstring name public delegate string asyncmethodcallerteststring name public delegate string natilusasynstring namebutton click event asyncmethodcaller caller new asyncmethodcallerpspennstarservice iasyncresult result callerbegininvoketxtfirsttext null null natilusasyn caller123 new natilusasyncspennstarservice iasyncresult result123 caller123 begininvoketxtthirdtext null null asyncmethodcallertest cltest new asyncmethodcallertestpstesthi iasyncresult tetsresult cltestbegininvoketxtsecondtext null null lblfirsttext callerendinvokeresult lblsecondtext cltestendinvoketetsresult lblthirdtext caller123endinvokeresult123 thank uhemanth,['asp.net'] +305367,is ruby on rails with draper or apotomo a mvvm some factsassumptionsit is said that ruby on rails follows mvc architectural patternthe mvvm model view viewmodel which derives from mvc offers an abstraction layer where all the buttons labels and links view are separated from the way models expose data viewmodelsome javascript frameworks that excel in building single page apps leverage mvvm pattern for instance knockoutjsif we check ruby toolbox we will see a several presenter solutions like draper and apotomo that work just as a viewmodel thingassuming there is no bs in my facts section there is one thing that bothers mecan we call rails with draper apotomo or other presenterdecorator a mvvm solution can we say we are following mvvm pattern with rails if we encapsulate the data from the model in a form of decoratorpresenter container with draper or is there something missing and we cannot call it a mvvm like knockoutjsthank you for your insights,['ruby-on-rails'] +305383,upload json via webclient i have a web app with that is using jquery to interact with my backend the backend successfully accepts json data for instance i can successfully send the following json id1 firstnamejohn lastnamesmith i now have a windows phone app that must hit this backend i need to pass this same json via a webclient currently i have the following but i am not sure how to actually pass the json string address webclient myservice new webclientutilityserviceuploadstringcompleted new uploadstringcompletedeventhandlerutilityservice uploadstringcompletedutilityserviceuploadstringasyncaddress stringemptycan someone tell me what i need to do,['c#'] +305386,getting type of nested enum having only string what i am trying to do is get type of enum which is nested in class having only name of that enumerator as stringexamplepublic static class myclasswithenumnested public enum nestedenum someenum1 someenum2 someenum3 i need get type type what shall i write heretype type typegettypemyclasswithenumnestednestedenumthat does not workis there any way to get this type in runtimethanks in advance,['c#'] +305404,benefit of polymorphism when i started to look for the benefits of polymorphism i found with this question here but here i was unable to find my answer let me tell what i want to find here i have some classesclass coolingmachines public void startmachine no implementationion public void stopmachine no implementationion class refrigerator extends coolingmachines public void startmachine systemoutprintlnrefrigerator starts public void stopmachine systemoutprintlnrefrigerator stop public void trip systemoutprintlnrefrigerator trip class airconditioner extends coolingmachines public void startmachine systemoutprintlnac starts public void stopmachine systemoutprintlnac stop public class polymorphismdemo coolingmachines cm new refrigerator refrigerator rf new refrigeratornow here i created two objects in the demo class and are references of refrigerator i have completely understood that from the rf object i am able to call the trip method of refrigerator but that method will be hidden for the cm object now my question is why should i use polymorphism or why should i usecoolingmachines cm new refrigeratorwhen i am ok withrefrigerator rf new refrigeratoris polymorphic objects efficiency is good or light in weight what is the basic purpose and difference between both of these objects is there any difference between cmstart and rfstart,['java'] +305439,python eigenvectors differences among numpylinalg scipylinalg and scipysparselinalg scipy and numpy have between them three different functions for finding eigenvectors for a given square matrix these are numpylinalgeigascipylinalgeiga andscipysparselinalgeiga kfocusing specifically on the situation that all the optional arguments i have left off the last two are left at their defaults and that aa is realvalued i am curious about the differences among these three which are ambiguous from the documentation especiallywhy does 3 have a note that it cannot find all eigenvectors why must the other two compute all solutions why do not they take a k argument1 has a note saying that the eigenvalues are returned in no particular order 3 has an optional argument to control the order does 2 make any guarantees about thisdoes 3 assume that a is sparse mathematically speaking rather than being represented as a scipy sparse matrix can it be inefficient or even give wrong results if this assumption does not holdare there other factors i should consider when choosing among these,['python'] +305467,specifying a send sharing intent filter for a service i am trying to filter and handle intents with androidintentactionsend actions in one of my services i wrote the following in my androidmanifestxmlservice androidnameappscreamerservice androidlabelstringapp name intentfilter action androidnameandroidintentactionsend category androidnameandroidintentcategorydefault data androidmimetype intentfilter servicenow the problem is that i do not see my application in the list of share via options when for instance trying to share a web page from the browser or a contact from the list of contacts if however i move the intent filters to the main activity tag instead of the service my application name and icon do appear on the list of share via optionswhat am i doing wrong here cannot a send action be directed to a service,['android'] +305534,jogl applets versus webgl are there any significant technical differences between using jogl in applets versus webgl i would like to focus on two things in particularperformance is there significantly more overhead in rendering 3d using webglfunctionality how well do the two support the opengl standardi am developing a 3d web application and i would like to know more about the technical capabilities of the two,"['java', 'javascript']" +305537,android finish current activity causes app close i am executing maswebview class and i would like to finish only this activity i tried maswebviewthisfinish but when executed app is been closed then if i set a new view for the tab content it is loaded properly and webviewmas thissapears but just for a while then appears again fitting fullscreen how to finish maswebview completely thank youpublic void onclickview arg0 intent intent getintent intentaddflagsintentflag activity task on home startactivityforresultintent 1 intent intentmas new intent maswebviewthis masclass intentmassetflagsintentflag activity single top intentmasaddflagsintentflag activity new task intentmasaddflagsintentflag activity clear top intentmasaddflagsintentflag activity no history view vista getlocalactivitymanagerstartactivitymaswb intentmasgetdecorview setcontentviewvista maswebviewthisfinish,"['java', 'android']" +305566,how do i find out which user is running the current php script how do we determine which user the php script is running under when i run the script on server is it running under the same user as apache or phpmyadmin by chance my question maybe wrongly framed but i want to know which user so that i set appropriate permission for different folders in var,['php'] +305568,sql select insert into generate unique id i am attempting to select a table of data and insert this data into another file with similar column names it is essentially duplicate data current syntax as followsinsert into table1 id id2 col1 col2select similiarid similiarid2 similiarcol1 similiarcol2 from table2the problem i have is generating unique key fields declared as integers for the newly inserted records i cannot use table2s keys as table1 has existing data and will error on duplicate key valuesi cannot change the table schema and these are custom id columns not generated automatically by the db,['sql'] +305575,background worker and garbage collection can i define a background worker in a method private void downloadfilestring filelocation backgroundworker worker new backgroundworker workerdowork new doworkeventhandlerobj args will be executed by back ground thread asynchronously argsresult downloadfilelocation workerrunworkercompleted new runworkercompletedeventhandlerobj args will be executed in the main thread result r argsresult as result reportresultr workerrunworkerasyncfilelocationquestion if download function takes a long time to download the file can gc kick in and collect worker object before the runworkercompleted is executed,['c#'] +305605,textarea height 100 heres my fiddle it may sound stupid but i cannot find a way to make the text area height equal to 100 it works for the width but not for heighti want the text area to resize depending of the window sizelike it works in my fiddle for the widthany ideas,"['html', 'css']" +305609,dynamically scale images to fit a specified size width and height so after extensive research and tons of jquery and javascript solutions i simply could not find a way in which to dynamically scale images to a specified size both horizontally and vertically i found tons of information on scaling to fit width wise and keep the aspect ratio or scaling to fit height wise and keep the aspect ratio but could not figure out whether the image was too tall or too short and adjust accordinglyso in my example i had a div with a set width of 460px and a set height of 280px and i need the image to fit all of itself into that area without stretching maintaining its aspect ratio,"['php', 'html']" +305641,android beam llcp protocol i am attempting to communicate with my galaxy s i and a microcontroller that features a pn532 nfc chipas this is a microcontroller there is no default llcp library that i can use so i must understand the android protocol myselfcould anyone clarify for me when i first place the phone to the device what packets to expect from the very first step assuming i am parsing correctly i am seeingdsap 3fptype 0ssap 0and alsodsap 1eptype cssap 0is this along the right lines what is android attempting to do i would have expected a connection attempt prior to an information packagemany thanks for any clarification,['android'] +305648,progress bar for avassetexportsession i have got an app that exports an avmutablecomposition into a mov file and i would like for the user to see the status of the export with a progress bar the same way that you would if you sent a text message or uploaded a filei know how to create a progress bar when i know the duration of a task such as playing an audio file but since there is no set duration for the export i am unsure how to proceedi have got an activity indicator currently but it does not provide the best user experiencedoes anyone have any pointers,['iphone'] +305657,rest api get request with body i want to implement a rest api and need a body on my get requests like thiscussed here http get with request bodyare there http clients which are not able to send a body with a get request fiddler is able to do it although the message box is red,['.net'] +305676,is it possible to make an alias for a module in ruby in python you can set an alias for a module with asimport mymodule as mmbut i cannot seem to find an equivalent for ruby i know that you can include rather than require a module but this risks namespace collisions is there any equivalent to python module aliases,['ruby'] +305681,how to pause eclipse on any exception i found the add java exception breakpoint menu item but it only seems to work on the exact exception type that i select so if i ask it to break on exception it does not break in case of a numberformatexception how do i make it break for all exceptionsmy activity is exiting for no apparent reason with no logcat output so it would be nice to find out about any exceptions that are occurring whether caught or uncaught and whether in my code or just in android,['android'] +305707,check if list contains any of another list i have a list of parameters like thispublic class parameter public string name get set public string paramtype get set public string source get setienumerableparameter parametersand a array of strings i want to check it againststring mystrings new string one twoi want to iterate over the parameter list and check if the source property is equal to any of the mystrings array i can do this with nested foreachs but i would like to learn how to do it in a nicer way as i have been playing around with linq and like the extension methods on enumerable like where etc so nested foreachs just feel wrong is there a more elegant preferred linqlambdadelegete way to do this thanks,['c#'] +305716,canvasdrawbitmap is intermittently slowed causing white flashes i am working on a live wallpaper with a scrolling background i have two bitmap objects which i alternate between in order to keep the previously drawn pixels for the next frame i draw a new line at the top of the canvas then call drawbitmap to copy the rest of the pixels onto the canvasi am using a runnable object to do the heavy lifting it does all copying and calculations required and then locks the canvas enters a synchronous block on the holder and makes a single call to canvasdrawbitmapbitmaprectrectpaint occasionally there will be a white flash on the screen which seems to correlate with high cpu activity in using traceview i found that the drawbitmap operation specifically canvasnative drawbitmap is taking much longer than normal typically it completes in 24msec but when i see a white flash it can take anywhere from 10 to 100 msecprivate void draw surfaceholder holder getsurfaceholder canvas canvas null prepareframe try canvas holderlockcanvas synchronized holder if canvas null drawframecanvas catch exception e eprintstacktrace finally if canvas null holderunlockcanvasandpostcanvas afterdrawframe handlerremovecallbacksdrawrunner if visible handlerpostdrawrunner the draw function is called in the run of the runnableprivate void prepareframe num if num2 0 mainbmp mainbmp1 maincansetbitmapmainbmp1 maincandrawbitmapmainbmp2 source destination null else mainbmp mainbmp2 maincansetbitmapmainbmp2 maincandrawbitmapmainbmp1 source destination null the prepareframe function is how i keep hold of the previous pixels i have drawn the rect called source is one row short of full screen sized at the bottom where as destination is one row short at the top the drawbitmap calls in prepareframe are never longer than 24msecprivate void drawframecanvas can candrawbitmapmainbmp source destinationnullthis single operation is done on the canvas while holding the lockprivate void afterdrawframe cacalcnextrow mainbmpsetpixelscagetrow 0 canwidth 0 0 canwidth 1then the next new row of pixels is drawn onto one of my bitmaps in memoryi have tried using the various signatures of drawbitmap but only found them slower on average and still resulting in the anomalous white flashesmy overall speed is great without the intermittent flashes it works really well does anyone have suggestions on how to eliminate the flashes,['android'] +305725,what to set cursoradaptercontext context cursor c int flags to in order to make it work with cursorloader the google docs point out not to use the cursoradapters first constructor cursoradaptercontext context cursor cthere are only two other options cursoradaptercontext context cursor c boolean autorequerywhich saysconstructor that allows control over autorequery it is recommended you not use this but instead cursoradaptercontext cursor int when using this constructor flag register content observer will always be setand cursoradaptercontext context cursor c int flagswhich says it is the recommended constructorproblem is there are only two flags to use with the last constructor here flag auto requeryint 1 and flag register content observerint 2using flag auto requery does not make sense because i am now using a cursorloader in which to manage it in the background as well as update it with flag register content observer it says its not needed when using cursorloadernow i ask what integer do i pass cursoradaptercontext context cursor c int flags in order to make it work fine with my cursoradapter whats worrying me is how to correctly manage the old cursor i am not really sure the correct way to do this if i use flag register content observer then i must do something with oncontentchanged but when using swapcursor in my loadermanager since the cursor is not closed i could just do adapterswapcursorcursorclose but would that conflict with oncontentchanged in cursoradapter goal is to not cause any memory leaks and be efficient,['android'] +305734,how can i get the auto incrementing field name or the primary key fieldname from a mysql table in php how do i get the field name of the field that is been set as to auto increment when a new rec is added to it in most cases it is the same as the primary key of the table but not necessarily always so this question has 2 parts with the second one branching into a 3rd part1 how to get the name of the autoincrementing field name2 how to get the name of the primary key field name21 how to get the primary keys info when a table uses more than one field as its primary key,"['php', 'mysql']" +305739,javascript error in webview with windows 8 metro i have a webview control on a page in my application the user can pretty much enter whatever url they like and have it thisplay in this webview this is by designthe problem is there are pages on the internet that throw javascript errors and for some reason cause an unhandled exception to bubble up through the net application as wellmy question is where do i catch javascript exceptionserrors when using a webview,['c#'] +305758,python unicode string stored as u84b8u6c7du5730 in file how to convert it back to unicode some unicode data is stored in file as u84b8u6c7du5730 without any encoding is there a way to covert them back in python,['python'] +305763,why does not stringbuilder have a trim method why does not stringbuilder have a trim method how can we trim a stringbuilder value without using stringbuildertostringtrimactually i am in a loop where i have to compare this stringbuilder string with many other values so if i call stringbuildertostringtrim each time it will create a new instance and i do not want to create a new string object each time,['java'] +305772,how do you run the tornado web server locally is it possible to run tornado such that it listens to a local port eg localhost80 i cannot seem to find any documentation explaining how to do this,['python'] +305823,replace a string located between here is my problem in a variable that is text and contains commas i try to delete only the commas located between two strings in fact and for example using the following stringinput the sun shines that is fine not for everyone and if it rains it will be betteroutput the sun shines that is fine not for everyone and if it rains it will be betteri know how to use replace for the whole variable but i can not do it for a part of itthere are some topics approaching on this site but i did not manage to exploit them for my own question eg repeatedly extract a line between two delimiters in a text file python python finding substring between certain characters using regex and replace replace string between two quotes,['python'] +305839,multithreaded rendering on opengl i have a multithreaded application in which i am trying to render with different threads first i tried to use the same rendering context between all threads but i was getting null current contexts for other threads i have read on the internet that one context can only be current at one thread at a timeso i decided to make something different i create a window i get the hdc from it and create the first rc after that i share this hdc between threads and in every new thread i create i obtain a new rc from the same hdc and i make it current for that thread everytime i do it the rc returned is always different usually the previous value 1 i make an assertion to check if wglgetcurrentcontext returns a rc and it looks like it returns the one that was just created but after making the rendering i get no rendering and if i call getlasterror i obtain error 6 invalid handleso does this mean that despite every new call of wglcreatecontext gives me a new value somehow it means that all these different values are the same connection channel to the opengl callsdoes this mean that i will always have to invalid the previous rendering context on a thread and activate it on the new one i really have to make this sync all the time or is there any other way to work arround this problem,['c++'] +305881,fitbounds shows whole earth if map is first hidden and then shown i have a bunch or markers and i want to show only the area containing them i found a long list of similar questions see at the bottom of the post for some but none of the solutions works for me the latlngbounds is built correctly but when i call fitbounds the result will be the followinginstead ofcan anybody spot an evident error in my codevar opt zoom 8 maptypeid googlemapsmaptypeidroadmapmap new googlemapsmapdocumentgetelementbyidmapoptvar box new googlemapslatlngboundsforvar i0ilistlengthi var p new googlemapslatlnglistilatlistilon var marker new googlemapsmarker position p map map boxextendpmapfitboundsboxmappantoboundsboxsome of the posts i read and tried list not comprehensivegoogle maps v3 automating zoom levelgoogle maps v3 custom marker images and fitboundsgoogle maps with fitbounds dont zoomfitbounds in google maps api v3 does not fit boundsedit this actually happens if as i do in my application the map is at first hidden and showed only lateri hide it in this waymaphideand show itmapshowfunction this is necessary because otherwise the map will show up in the upper left corner until a window resize takes place googlemapseventtriggermap resizeany clue as to why this happens and how to prevent it apart from initialising the map when first shownon a side note if i set zoom and center when declaring the map object ie i do not use fitbounds then the map will show correctly even after a hideshowi cannot set zoom and center though because the list of points is retrieved elsewhere and i do not know where they are beforehand,['javascript'] +305907,unable to get eloquent to automatically create joins apologies in advance if the answer to my question is obvious i have done my due diligence in researching this topic before i posted heremost of my framework experience comes from using codeigniter so i have never had handson experience using orm ci does have some offtheshelf orm solutions but i have never used themi would like to use builtin orm functionality in laravels eloquent orm to automatically join the tournaments and countries tables together when running a query and return the a data set that includes tournament data as well as its associated country datathat is i want eloquent to recognize the foreign key relationship automatically so that i can just run a query eg tournamentwithcountryall that will return the entire set of tournament and country dataplease stop me right now if i am using eloquent in a way that it was never intended to be used my confusion may be more about me trying to mash together an untenable solution rather than a syntax or coding errorquery that i would like to replicate in eloquentselect from tournaments left join countries on tournamentscountry id countriesidexpected result in phpi expect to receive an array of tournament objects in php where a single tournament object would look liketournamentsidtournamentsyeartournamentscountry idtournamentscreated attournamentsupdated atcountriesidcountriescodecountriesnamecountriesurlcountriescreated atcountriesupdated atfailed attemps that i have made so fari ran all of these attempts in a dummy controller method and output the result as a formatted string to the profilerfailed attempt 1php code in the dummy controllertournaments tournamentwithcountryallgenerates the following queryselect from tournamentsattempt 1 returnsan array containing tournament objects that only include the columns in the tournaments tablefailed attempt 2php code in the dummy controllertournaments tournamentwithcountryfirstgenerates the following errorsqlstate42s22 column not found 1054 unknown column tournament id in where clausesql select from countries where tournament id in bindings array 0 1other failed attemptsi have tried various combinations of naming conventions eg columns tables etc to no avail i have also tried creating the query in fluent which worked fine but required me to specify the joins which is what i am trying to avoidmy environmentphp 5313mysql 5153laravel 323relationship between tablesonetoone relationshipa tournament must have a country there is a foreign key constraint to enforce ita country can belong to many other relations eg a participant not shown here has a country of birthcountries tablecreate table countries id int11 not null auto increment code varchar4 not null name varchar25 not null url varchar25 not null created at datetime not null updated at datetime not null primary key id unique key countries code unique code key countries url index url engineinnodb auto increment28 default charsetlatin1tournaments tablecreate table tournaments id int11 not null auto increment year int11 not null country id int11 not null created at datetime not null updated at datetime not null primary key id unique key tournaments year unique year key tournaments country id foreign country id constraint tournaments country id foreign foreign key country id references countries id on update cascade engineinnodb auto increment40 default charsetlatin1countries model countriesphpclass country extends eloquent public static timestamps true public static table countriestournaments model tournamentsphpclass tournament extends eloquent public static timestamps true public function country return thishas onecountry,['php'] +305908,generic way of sorting json array by attribute i found out how to sort a json array at now i want to sort it in a generic way so that my sorting function knows which attribute to sort by for example if my array is name john age 16 name charles age 26 i want to avoid writing different if cases to know if i should sort by name or age i just want to pass a parameter name or age and my sorting function should know what to dothanks,['javascript'] +305910,explanation required regarding double destruction of exception objects in his insightful papererror and exception handlingdave abrahams saysmake your exception class immune to doubledestruction if possible unfortunately several popular compilers occasionally cause exception objects to be destroyed twice if you can arrange for that to be harmless eg by zeroing deleted pointers your code will be more robusti am not able to understand this particular guideline can someoneplease provide a code example of this double destruction scenario what is the best way to implement a custom exception class to avoid this,['c++'] +305916,100 width background image with an auto height i am currently working on a mobile landing page for a company it is a really basic layout but below the header there is an image of a product which will always be 100 width the design shows it always going from edge to edge depending on the width of the screen the height of the image will obviously adjust accordingly i originally did this with an img with a css width of 100 and it worked great but i have realised that i would like to use media queries to serve different images based on different resolutions let us say a small medium and a large version of the same image for example i know you cannot change the img src with css so i figured i should be using a css background for the image as opposed to an img tag in the htmli cannot seem to get this working properly as the div with the background image needs both a width and a height to show the background i can obviously use width 100 but what do i use for the height i can put a random fixed height like 150px and then i can see the top 150px of the image but this is not the solution as there is not a fixed height i had a play and found that once there is a height tested with 150px i can use backgroundsize 100 to fit the image in the div correctly i can use the more recent css3 for this project as it is aimed solely at mobilei have added a rough example below please excuse the inline styles but i wanted to give a basic example to try and make my question a little clearerdiv idimagecontainer div idimage stylebackground urlimagejpg norepeat width 100 height 150px backgroundsize 100divdivdo i maybe have to give the container div a percentage height based on the whole page or am i looking at this completely wrongalso do you think css backgrounds are the best way to do this maybe there is a technique which serves different img tags based on devicescreen width the general idea is that the landing page template will be used numerous times with different product images so i need to make sure i develop this the best way possiblei apologise is this is a little longwinded but i am back and forth from this project to the next so i would like to get this little thing done thanks in advance for your time it is much appreciatedregards,"['html', 'css']" +305922,octave c and vs2010 i am trying to use octave with visual ci have downloaded octave361vs2010setup1exe created a new project added octave include folder to include path octinterplib and octavelib to lib path and i added octave bin folder as running directorythe program compiles and runs fine except feval function that causes the exceptionmicrosoft c exception octave execution exception at memory location 0x0012faefand on octave sideinvalid resizing operation or ambiguous assignment to an outofbounds array elementwhat am i doing wrongcode for a standalone programinclude octaveoctavehinclude octaveocthinclude octaveparsehint mainint argc char argv if octave main argc argv true columnvector numrands2 numrands0 10 numrands1 1 octave value list f arg f ret f arg0 octave valuenumrands f ret fevalrandf arg1 matrix unisf ret0matrix value else error octave interpreter initialization failed return 0thanks in advance,['c++'] +305939,centralised java logging i am looking for a way to centralise the logging concerns of thistributed software written in java which would be quite easy since the system in question has only one server but keeping in mind that it is very likely that more instances of the particular server will run in the future and there are going to be more applications in need for this there would have to be something like a loggingserver which takes care of incoming logs and makes them accessable for the supportteam the situation right now is that several javaapplications use log4j which writes it is data to local files so if a client expiriences problems the supportteam has to ask for the logs which is not always easy and takes a lot of time in the case of a serverfault the diagnosisproblem is not as big since there is remoteaccess anyways but even though monitoring everything through a loggingserver would still make a lot of sensewhile i went through the questions regarding centralised logging i found another question actually the only one with a in this case useable answer problem being all applications are running in a closed environment within one network and securityguidelines do not permit for anything concerning internal software to go out of the environments networki also found a wonderful article about how one would implement such a loggingserver since the article was written in 2001 i would have thought that someone might have already solved this particular problem but my searchresults came up with nothingmy question is there a loggingframework which handles logging over networks with a centralised server which can be accessed by the supportteamspecification availabilityserver has to be run by usjava 15 compatibilitycompatibility to a heterogeneous networkbestcase protocol uses http to send logs to avoid firewallissuesbestcase uses log4j or logback or basically anything that implements slf4jnot necessary but nice to haveauthentication and security is of course an issue but could be set back for at least a while if it is opensoftware we would extend it to our needs ot we always give back to the projectsdata mining and analysis is something which is very helpful to make software better but that could as well be an external applicationmy worstcase scenario is that their is no software like that for that case we would probably implement this ourselves but if there is such a clientserver application i would very much appreciate not needing to do this particularly problematic bit of workthanks in advanceupdate the solution has to run on several javaenabled platforms mostly windows linux some hp unixupdate after a lot more research we actually found a solution we were able to acquire clusterlognet offline since at least mid2015 provides logging services for thistributed software and is compatible to log4j and logback which is compatible to slf4j it lets us analyze every single users way through the application thus making it very easy to reproduce reported bugs or even non reported ones it also notifies us of important events by email and has a report system were logs of the same origin are summorized into an easily accessable format they deployed which was flawless it here just a couple of days ago and it is running greatupdate 2016 this question still gets a lot of traffic but the site i referred to does not exist anymore,['java'] +306024,evaluating dbnull checking for equality or using the is operator i have got a c questioni just wanted to ask the community about the use of systemdbnull in conjunction with using a datareaderwhen querying a database and checking for null values which is more appropriatepreferredusing the is operatorreaderfieldname is dbnullor just checking the valuereaderfieldname dbnullvalueboth seem to work i just wanted to get some other opinions,"['c#', '.net']" +306049,how to create a widget system in codeigniter i am creating a custom cms in codeigniter and i would like to have a widget system similar to what is used in wordpressfor example i would like to have a widget that shows the last 5 posts thisplayed on the sidebar i would also like to be able to control what pages this widget appears on pagebypage basisi am using phil sturgeons template library so an example controller looks likethistemplateset partialheader layoutsheaderthistemplateset partialfooter layoutsfooterthistemplateset partialsidebar layoutssidebarthisdatatitle create postthistemplatebuildcreate thisdatai would like to stick with the mvc pattern so i do not want to put logic in the sidebar view which is the only thing i can think of right now is hmvc something i should be using for thishow can i tell the sidebar which widgets to thisplay,['php'] +306053,replace text while keeping case intact in c i have a set of sentences i need to use to do a replace for exampleabc cdeab df deand i have a text where to make the changeshowever i have no way to know beforehand case of said textso for example if i havea bgt abc hyi abc ab df hi must replace and geta bgt cde nyi cde de hor as close to that as possible ie keep caseedit as i am seeing to much confusion about this i will try to clarify a biti am asking about a way to keep caps after replacing and i do not think that passed through well not well explained what thaat entails so i will give a more realistic example using real wordsthink of it like a gossary replacing expressions by their sinonyms so to speak so if i mapdid not achieve success failled miserablythen the i get as input the setenceas he did not achieve success he was firedi would getas he failled miserably he was firedbut if did not was capitalized so would failled if achieve or success was capitalized so would miserably if any had more than 1 letter capitalized so would it is counterpartmy main possibilities are ones i really want to take into cosiderationonly first letter of first word capitalizedonly first letter of every word capitalizedall letters capitalizedif i can handle those three that would be acceaptable already i guess it is the easyer ones of course a more in depth solution would be better if availlableany ideas,['c#'] +306089,how to get inputs with append prepend to have matching widths with twitter bootstrap is there a way to have inputs that have append andor prepend to all have matching widthsheres an example but you can see that given multiple inputs with appendsprepends of various lengths the will all end up being different widths and it would not look very good,['css'] +306097,passing argument to jserb template i want to pass some arguments to the my javascript template in rails3 applicationwhat i try with respond to block is respond to do format formatjsidparamsid endi also tried respond to do format formatjsparamsid endam i forced to make id as an instance variable for the js template to use how to pass variables to the template here,['ruby-on-rails'] +306114,sql avg returning an int in one of my queries it appears that the avg function is returning an int select avgeemployee levelavg levelhow do i get it to return floating point values i tried casting it but all my rows for avg level were still integers,['sql'] +306129,devise instance the current user using single table inheritance i am using rails 309 and devise for authentication now i am trying to use single table inheritance because i need to use polymorphism so i have two classes usertype1 and usertype2 which inherit from user class i need that devise instance correctly the current user depending the type of user for example class user activerecordbase devise and other user logic endclass usertype1 user def get some attribute return hello my type is usertype1 endendclass usertype2 user def get some attribute return hello my type is usertype2 endendin controller class mycontroller applicationcontroller def action message current userget some attribute depending the type using polymorphism render my view endend,['ruby-on-rails'] +306137,using iphone serial connection pins 12 and 13 ok so i have never done anything with serial connections before buti just got an arduino that i am trying to use to remotely launch model rockets i have a 5 volt relay that i can control with the arduinos digital outnow i want connect my iphones tx to the arduinos rx and viceversa i would buy the iphone breakout board from spark fun so i could connect it to the arduino i was thinking something along the lines of when the phone gets a text or a call from a certain number or maybe even just a bluetooth signal it would tell the arduino but those are just ideashow can i actually send a signal from my iphone are there xcode libraries to do this my phone is jailbroken so i am open to other nonapple ways for sending signals but i am a novice programmerthank youps i am new to stack overflow and i would appreciate if you could help me the first time i posted a question someone told me it was not on the right site so please bear with me edit 1 haha i just read over this and it sounds like a cell phone bomb from a terrorist movie i swear that is not what i am doing just look at my avatar edit 2 i also have a bluetooth dongle for the arduino but i honestly have no idea how to interface that with anything it was 10 from china so i thought i would buy it to keep my options open but regardless it would be really cool to plug an iphone into an arduino,['iphone'] +306161,is there anyway to specialize a template based on the members of a parameter in c is there anyway to specialize a template like this making the specialization apply only if t has a member function hash note this is only an example of what i am trying to do i know that it would make more sense for each class that has a hash function to check it on its own in the operator member function but i just want to know if this kind of thing is possibletemplate class tbool equalsconst t x const t y return x ytemplate class t somehow check if t has a member function hashbool equalstconst t x const t y return xhash yhash x yi would prefer a prec11 solution if possible,['c++'] +306198,a curious way of passing a parameter to a method i was going through the exchange web services java api code and saw a design choice in the way the developers passed arguments to their methods may you can help explain the benefits of the technique the type that is to be processed by the method is wrapped by a generic wrapper class before being passed into the method for example if the method is to work on a string new param is passed into the method where param is defined as followsclass paramt private t param public t getparam return param public void setparamt param thisparam param here is a snippet from the source the method works on an httpwebrequest objectthe caller creates an instance of the param ie bounded by the httpwebrequest class then that instance is passed into the method as you can see in the method signature protected httpwebrequest emitoutparamhttpwebrequest request throws exception requestsetparamthisgetservicepreparehttpwebrequest outputstream urloutstream requestgetparamgetoutputstream ewsservicexmlwriter writer new ewsservicexmlwriterthisserviceurloutstream thiswritetoxmlwriter urloutstreamflush urloutstreamclose writerthispose requestgetparamexecuterequest ifrequestgetparamgetresponsecode 400 throw new exceptionthe remote server returned an errorrequestgetparamgetresponsecoderequestgetparamgetresponsetext return requestgetparamthen why not just pass the httpwebrequest object the developers use this pattern repeatedly all over the code base which makes me think there is some good reason for it but i just cannot see the benefit please enlighten,['java'] +306216,iis stackoverflow exception this is yet another variation of the same question where a stackoverflow exception occurs as a result of the 256k stack size while running under iis this issue is nothing new and it has been asked several times here and heremy question is a little different the exception is thrown when a client requests data and the wcf service running under iis 7 tries to serialize a rather large object graph it actually occurs during the serializationi can easily reproduce the issue in the development environment by running a retrieveserialize routine in a thread with a limited stack sizestatic void mainstring args thread t new threaddowork 262144 tstart tjoin consolereadlineprivate static void dowork var dataaccess new dataaccess var data dataaccessloaddata var serializer new datacontractserializertypeoflistdata null intmaxvalue false true new datacontractsurrogate var memorystream new memorystream serializerwriteobjectmemorystream data this simulates the stackoverflow exception just like in iis when i change the stacksize parameter passed to the threads constructor to 1mb it works finemy question is how can one do this inside of a wcf service method in other words in my wcf service method i do not explicitly create a serializer and call writeobject howwhere can i do this same sort of work around in a thread where i can control the stacksizethanks,['c#'] +306243,how to capture output of printf i am calling a function funcb from funcafuncb uses several printf statements to output datais there a way for me to capture that data via funcai can not modify funcbfuncb printf s my name is printf s i like ice cream funca funcb,['c++'] +306285,is it ok to have multiple html forms with the same name i have a valid reason for wanting to do this but it is a long story so i will forgot trying to explain why and just ask if it is ok to doi have a page where i need to have multiple forms with the same name but i only want the form whose submit button is click to be submitted for example the following might be on my pageform nameinput action methodgetusername input typetext nameuser input typesubmit valuesubmit formtextform nameinput action methodgetusername input typetext nameuser input typesubmit valuesubmit formtextform nameinput action methodgetusername input typetext nameuser input typesubmit valuesubmit formis this acceptable,['html'] +306286,difference between pthread spinlock and boostsmart ptrspinlock i found the following spinlock code in boostsmart ptrbool try lock return sync lock test and setv 1 0void lock for unsigned k0 try lock k if k4 spin else if k 16 asm volatile pause was rep nop memory else if k 32 k 1 sched yield else struct timespec rqtp rqtptv sec 0 rqtptv nsec 100 nanosleeprqtp 0 void unlock sync lock releasev so if i understand this correctly when the lock is contended the incoming thread will exponentially backoff first spinning wildly then pausing then yielding the remainder of its time slice and finally flipflopping between sleeping and yieldingi also found the glibc pthread spinlock implementation which uses assembly to perform the lockdefine lock prefix lock using an smp machineint pthread spin lockpthread spinlock t lock asm n 1t lock prefix decl 0nt jne 2fnt subsection 1nt align 16n 2trep nopnt cmpl 0 0nt jg 1bnt jmp 2bnt previous m lock m lock return 0i will admit that my understanding of assembly is not great so i do not fully understand what is happening here could someone please explain what this is doinghowever i ran some tests against the boost spinlock and glibc pthread spinlock and when there are more cores than threads the boost code outperforms the glibc codeon the other hand when there are more threads than cores the glibc code is betterwhy is this what is the difference between these two spinlock implementations that makes them perform differently in each scenario,['c++'] +306301,with an html5 video element on the iphone how can i detect the difference between pause and done this is an extension of this questionaccording to my research for a video element on an iphoneipad pressing both done and pause triggers a pause event so if i have some desired webpage behavior that i want to initiate upon pressing the done button i need to listen for the pause eventplayer documentgetelementbyidvideoplayerplayeraddeventlistenerpause function desired done button behavior defined here falseaccording to arvtooltwists answer to that original question the way one differentiates between done and pause is by checking for the webkitthisplayingfullscreen boolean since the done button exits out of fullscreen the boolean will return falseplayeraddeventlistenerpause function ifplayerwebkitthisplayingfullscreen desired done button behavior defined here falsehowever in the case where a user pauses the video while the player is in fullscreen mode and then presses done while the video is paused the desired done button behavior is not initiated my research is turning up littletono information on this but my assumption is that either the pause event is not getting triggered a second time or it gets triggered a second time prior to the webkitthisplayingfullscreen boolean changing to false either way the device can tell the difference between both done and pause even when the player is already paused so i am wondering how the device tells the difference and whether there is a way to detect when the player exits the fullscreen mode so that even when the player is already paused pressing the done button is still detected and the desired behavior still gets initiated,"['iphone', 'ios']" +306302,c intricate treeview design i am trying to design an idelike noneditable program with a richtextbox control basically i need the treeview which is positioned to the left side of the rtb to expandcollapse a certain portion of my code whenever the user clicks on the buttons the expandable collapsable ranges are defined as wherever the curly brackets are seen for instance in the rtb if i had something likeint main if if else if i were to click on the topmost curly bracket it would collapse everything inside the main function basically whats contained inside that curly bracket is what is folded so in summary i am trying to design something that is very similar to visual studios expandcollapse code function except it also does that with the ifelse functionsi am aware of the bracket matching algorithm and i implemented a stack to know which pairs of the brackets match line numbers stored in a list of tuple the issue i am having majorly is how to go about designing the actual treeview i need the treeview to be in a linear fashion where no nodes are added on top of another i am not aware of any approach which can add the expandcollapse button without actually adding child nodes on top of another nodealso with the exception of the buttons and a singular vertical line i need the treeview nodes to be noneditable nonvisible and nonclickablefinally and this is assuming if i fulfilled the above requirements i need the rtbs vertical scroll event to correctly scroll the treeview as well that is the treeviews collapseexpand section would update based on the portion of the code visible on the rtbhere is a section of the code i am using to initialize the treepublic partial class logicsimulationviewerform form private listtuplestringboolean visiblelines new listtuplestringboolean private listtupleint int collapserange new listtupleint int private void treeinit treenode tn stackint openbracketline new stackint int i 0 treelogiccodenodesclear foreach string s in rtblogiccodelines visiblelinesaddtuplecreates true if s openbracketlinepushi else if s collapserangeaddtuplecreateopenbracketlinepopi i here is the designersc source code although i believe this would not really be necessary but just in casenamespace ddcui partial class logicsimulationviewerform summary required designer variable summary private systemcomponentmodelicontainer components null summary clean up any resources being used summary param namethisposingtrue if managed resources should be thisposed otherwise falseparam protected override void thisposebool thisposing if thisposing components null componentsthispose basethisposethisposing region windows form designer generated code summary required method for designer support do not modify the contents of this method with the code editor summary private void initializecomponent thistreelogiccode new systemwindowsformstreeview thislabellogiccode new systemwindowsformslabel thisrtblogiccode new systemwindowsformsrichtextbox thissuspendlayout treelogiccode thistreelogiccodedock systemwindowsformsdockstyleleft thistreelogiccodelocation new systemdrawingpoint50 0 thistreelogiccodename treelogiccode thistreelogiccodescrollable false thistreelogiccodesize new systemdrawingsize40 600 thistreelogiccodetabindex 4 labellogiccode thislabellogiccodebackcolor systemdrawingcolorlightgray thislabellogiccodeborderstyle systemwindowsformsborderstylefixedsingle thislabellogiccodedock systemwindowsformsdockstyleleft thislabellogiccodeforecolor systemdrawingsystemcolorscontroltext thislabellogiccodelocation new systemdrawingpoint0 0 thislabellogiccodemargin new systemwindowsformspadding3 thislabellogiccodename labellogiccode thislabellogiccodepadding new systemwindowsformspadding3 thislabellogiccodesize new systemdrawingsize50 600 thislabellogiccodetabindex 3 thislabellogiccodetextalign systemdrawingcontentalignmenttopright rtblogiccode thisrtblogiccodedock systemwindowsformsdockstylefill thisrtblogiccodelocation new systemdrawingpoint90 0 thisrtblogiccodename rtblogiccode thisrtblogiccodesize new systemdrawingsize510 600 thisrtblogiccodetabindex 5 thisrtblogiccodetext thisrtblogiccodevscroll new systemeventhandlerthisrtblogiccode vscroll logicsimulationviewerform thisautoscaledimensions new systemdrawingsizef7f 12f thisautoscalemode systemwindowsformsautoscalemodefont thisclientsize new systemdrawingsize600 600 thiscontrolsaddthisrtblogiccode thiscontrolsaddthistreelogiccode thiscontrolsaddthislabellogiccode thisformborderstyle systemwindowsformsformborderstylenone thisname logicsimulationviewerform thistext logicsimulationviewerform thisresumelayoutfalse endregion private systemwindowsformstreeview treelogiccode private systemwindowsformslabel labellogiccode private systemwindowsformsrichtextbox rtblogiccode i would really appreciate any guidance on solving this matter thanks in advance,"['c#', '.net']" +306304,getting lines from gl10 drawing images next to one another solution i have a background image i am drawing with open gl 10 esthe problem is when i draw this small image to the big screen i get thisthe lines breaks in pattern are not suppose to be there i have tried a lot of things i thought maybe my atlas was wrong doubt it i draw it from 0 0 50 50 which is x y width height checked this a lot and still get the same result it is as it should betried different things with my for loop which is belowgl10 gl thisglgraphicsgetgl glglcleargl10gl color buffer bit guicamsetviewportandmatrices glglenablegl10gl texture 2d set background color batcherbeginbatchassetsmainmenuatlas forint x assetsmmbackgroundpatternwidth 2 x thisscalegetwidth assetsmmbackgroundpatternwidth 2 x assetsmmbackgroundpatternwidth forint y assetsmmbackgroundpatternheight 2 y thisscalegetheight assetsmmbackgroundpatternheight 2 y assetsmmbackgroundpatternheight batcherdrawspritex y assetsmmbackgroundpatternwidth assetsmmbackgroundpatternheight assetsmmbackgroundpattern the viewport matrices ispublic void setviewportandmatrices gl10 gl glgraphicsgetgl glglviewport0 0 glgraphicsgetwidth glgraphicsgetheight glglmatrixmodegl10gl projection glglloadidentity glglorthofpositionx frustumwidth zoom 2 positionx frustumwidth zoom 2 positiony frustumheight zoom 2 positiony frustumheight zoom 2 1 1 glglmatrixmodegl10gl modelview glglloadidentity when i draw spritespublic void endbatch verticessetverticesverticesbuffer 0 bufferindex verticesbind verticesdrawgl10gl triangles 0 numsprites 6 verticesunbind public void drawspritefloat x float y float width float height textureregion region float halfwidth width 2 float halfheight height 2 float x1 x halfwidth float y1 y halfheight float x2 x halfwidth float y2 y halfheight verticesbufferbufferindex x1 verticesbufferbufferindex y1 verticesbufferbufferindex regionu1 verticesbufferbufferindex regionv2 verticesbufferbufferindex x2 verticesbufferbufferindex y1 verticesbufferbufferindex regionu2 verticesbufferbufferindex regionv2 verticesbufferbufferindex x2 verticesbufferbufferindex y2 verticesbufferbufferindex regionu2 verticesbufferbufferindex regionv1 verticesbufferbufferindex x1 verticesbufferbufferindex y2 verticesbufferbufferindex regionu1 verticesbufferbufferindex regionv1 numsprites here are my texture and texture regionspublic textureregiontexture texture float x float y float width float height thisu1 x texturewidth thisv1 y textureheight thisu2 thisu1 width texturewidth thisv2 thisv1 height textureheight thistexture texture thiswidth int width thisheight int height public class texture glgraphics glgraphics fileio fileio bitmap img string filename int textureid int minfilter int magfilter public int width public int height public textureglgame glgame string filename thisglgraphics glgamegetglgraphics thisfileio glgamegetfileio thisfilename filename try loadbitmapfactorydecodestreamthisfileioreadassetfilename catchexception e eprintstacktrace public textureglgame glgame bitmap img thisglgraphics glgamegetglgraphics thisfileio glgamegetfileio thisimg img loadimg private void loadbitmap bitmap gl10 gl glgraphicsgetgl int textureids new int1 glglgentextures1 textureids 0 textureid textureids0 glglbindtexturegl10gl texture 2d textureid glutilsteximage2dgl10gl texture 2d 0 bitmap 0 setfiltersgl10gl linear gl10gl linear glglbindtexturegl10gl texture 2d 0 width bitmapgetwidth height bitmapgetheight bitmaprecycle public void reload iffilenameequalsnull loadthisimg else try loadbitmapfactorydecodestreamthisfileioreadassetfilename catchexception e eprintstacktrace bind setfiltersminfilter magfilter glgraphicsgetglglbindtexturegl10gl texture 2d 0 public void setfiltersint minfilter int magfilter thisminfilter minfilter thismagfilter magfilter gl10 gl glgraphicsgetgl glgltexparameterfgl10gl texture 2d gl10gl texture min filter minfilter glgltexparameterfgl10gl texture 2d gl10gl texture mag filter magfilter public void bind gl10 gl glgraphicsgetgl glglbindtexturegl10gl texture 2d textureid public void thispose gl10 gl glgraphicsgetgl glglbindtexturegl10gl texture 2d textureid int textureids textureid glgldeletetextures1 textureids 0 i have tried adding and subtracting from the width added and height added but makes it look worsemy question is what would you look at to try and fix this problem i feel very stumped but i feel like i may have set something wrong in opengl what could i have setup wrongi can always provide more code up top but not exactly sure what you may needthe image i am re pasting over the whole screen isalso the tool i am using to make atlas is found here and i am using the one under the beta tree which is considered build 4 however i checked the atlas over and it seems just finepublic class spritebatcher final float verticesbuffer int bufferindex final vertices vertices int numsprites public spritebatcherglgraphics glgraphics int maxsprites thisverticesbuffer new floatmaxsprites44 thisvertices new verticesglgraphics maxsprites4 maxsprites6 false true thisbufferindex 0 thisnumsprites 0 short indices new shortmaxsprites6 int len indiceslength short j 0 for int i 0 i len i 6 j 4 indicesi 0 shortj 0 indicesi 1 shortj 1 indicesi 2 shortj 2 indicesi 3 shortj 2 indicesi 4 shortj 3 indicesi 5 shortj 0 verticessetindicesindices 0 indiceslength public void drawspritefloat x float y float width float height textureregion region boolean corner ifcorner float x1 x float y1 y float x2 x width float y2 y height verticesbufferbufferindex x1 verticesbufferbufferindex y1 verticesbufferbufferindex regionu1 verticesbufferbufferindex regionv2 verticesbufferbufferindex x2 verticesbufferbufferindex y1 verticesbufferbufferindex regionu2 verticesbufferbufferindex regionv2 verticesbufferbufferindex x2 verticesbufferbufferindex y2 verticesbufferbufferindex regionu2 verticesbufferbufferindex regionv1 verticesbufferbufferindex x1 verticesbufferbufferindex y2 verticesbufferbufferindex regionu1 verticesbufferbufferindex regionv1 numsprites else drawspritex y width height region public void presentfloat deltatime gl10 gl thisglgraphicsgetgl glglcleargl10gl color buffer bit guicamsetviewportandmatrices glglenablegl10gl texture 2d set background color batcherbeginbatchassetsmainmenuatlas forfloat x 0 x thisscalegetwidth x assetsmmbackgroundpatternwidth forfloat y 0 y thisscalegetheight y assetsmmbackgroundpatternheight batcherdrawspritex y assetsmmbackgroundpatternwidth assetsmmbackgroundpatternheight assetsmmbackgroundpattern true,"['java', 'android']" +306322,left outer join vs subselect in mysql i have a table say table1 which has 3 columns column1 column2 and column3the column1 and column2 are a foreign key with 2 other tables however the data in column3 is from and number of tables for eg let us consider facebook to thisplay the activities it might maintain a table which could have user1 photoliked photo1 or user1 statusliked status1 so in this case column3 cannot be a foreign key with a specific tablenow there are 2 ways of getting real data 1st way select user id verb id case when verb id photoliked then select photo name from photos where photo id column3 getting the desired data from the third column when verb id statusliked then select status from statustable where status id column3 else end as performedonfrom table1 join table2 on user id user id joining the first column join table3 on verb id verb id joining the second column2nd way select user id verb id case when verb id photoliked then pphoto name when verb id statusliked then sstatus else end as performedonfrom table1 join table2 on user id user id joining the first column join table3 on verb id verb id joining the second column left join photos p on pphoto id column3 joining the column3 with specific table left join statustable s on sstatus id column3questionwhich of the 2 ways is better to retrieve data and which of the 2 queries is less expensive,"['mysql', 'sql']" +306366,video with iframe does not thisplay on android webview i am working on android project api level 8 thisplaying webview from another website which i cannot change the code of these website i am having trouble with video clip in webview on some devices that does not enable force gpu rendering in settings developer options the following codes are the codes that i read from the websitecenteriframe width500 height315 src frameborder0 allowfullscreeniframecenter br andcenter iframe frameborder0 width480 height323 srciframe centerbr on android side i already enable several settings which arewebviewsetwebchromeclientnew webchromeclient webviewsetwebviewclientnew webviewclient webviewgetsettingssetjavascriptenabledtruewebviewgetsettingssetpluginsenabledtruei believe i cannot use androidhardwareacceleratedtrue since i am working on api level 8when i turn off force gpu rendering the error on logcat are shown as follows0620 140424455 wwebview28201 at androidwebkitwebviewcheckthreadwebviewjava94680620 140424455 wwebview28201 at androidwebkitwebviewloaddatawithbaseurlwebviewjava21860620 140424455 wwebview28201 at comtssonemaindetail1runmaindetailjava1440620 140424455 wwebview28201 at javalangthreadrunthreadjava8560620 140424533 vphonestatusbar10977 setlightsontrue0620 140424697 iactivitymanager10909 thisplayed comtssonemaindetail 614ms0620 140427197 dlibegl28201 loaded systemlibegllibgles androidso0620 140427205 dlibegl28201 loaded vendorlibegllibegl powervr sgx540 120so0620 140427221 dlibegl28201 loaded vendorlibegllibglesv1 cm powervr sgx540 120so0620 140427229 dlibegl28201 loaded vendorlibegllibglesv2 powervr sgx540 120so0620 140427729 eweb console28201 unsafe javascript attempt to access frame with url aboutblank from frame with url domains protocols and ports must match0620 140427729 eweb console28201 at null10620 140427838 elibegl28201 call to opengl es api with no current context logged once per thread0620 140427838 dshaderprogram28201 could not load the vertex shader0620 140427838 dshaderprogram28201 could not load the vertex shader0620 140427838 dshaderprogram28201 could not load the vertex shader0620 140427838 dshaderprogram28201 could not load the vertex shader0620 140427838 dshaderprogram28201 could not load the vertex shader0620 140428213 ddalvikvm28201 gc concurrent freed 3468k 17 free 20475k24519k paused 3ms2ms0620 140429783 eweb console28201 uncaught error index size err dom exception 1 at 0620 140429791 dmediaplayer28201 could not open file on client side trying server side0620 140429791 iawesomeplayer108 setdatasource lhelper00620 140429791 vchromiumhttpdatasource108 connect on behalf of uid 101240620 140429791 ichromiumhttpdatasource108 connect to helper0 00620 140433291 isampletable108 there are reordered frames present0620 140433299 iomxcodec108 omxtiducati1videodecoder avc profile 66 baseline level 300620 140433299 iomxcodec108 omxtiducati1videodecoder video dimensions are 512 x 3440620 140433299 iomxcodec108 omxtiducati1videodecoder crop rect is 512 x 344 0 00620 140434432 iomxcodec108 omxtiducati1videodecoder video dimensions are 640 x 4480620 140434432 iomxcodec108 omxtiducati1videodecoder crop rect is 512 x 344 0 00620 140434604 iomxcodec108 omxtiducati1videodecoder video dimensions are 640 x 4480620 140434604 iomxcodec108 omxtiducati1videodecoder crop rect is 512 x 344 32 240620 140434612 wsoftaac108 sample rate was 44100 hz but now is 22050 hz0620 1404396 inucachedsource2108 error end of stream,['android'] +306403,nuget exited with code 1 a build failing as a result i have installed dotless via package manager in vs2012 in to an existing mixed c solution class libraries and mvc2 apps however now when i build it f5 i get the following two errorsthe command cgitreposebssolutionfilesnugetnugetexe install cgitreposebspackagesconfig source o cgitreposebssolutionfilespackages exited with code 1and the system cannot find the path specifiedafter adding dotless to the solution a nuget folder with nugetexe and nugettargets has been addedi have also tried adding dotless to a new mvc2 project and other than having to add a mime type to the webconfig it all works well there is not however a nuget folderi also noticed that the same happens if i create a new nservicebus solution after installing it the paths in the message change but the error is the sameif i take cgitreposebssolutionfilesnugetnugetexe install cgitreposebspackagesconfig source o cgitreposebssolutionfilespackagesand run it via a command prompt then i getall packages listed in packagesconfig are already installed,['c#'] +306409,clone entire javascript scriptengine i need to somehow deep clone the entire set of bindings of my scriptengine objectwhat i have triedi have tried so far the cloner library to clone the entire bindings structure this would be great if it worked because it would have ensured a precise copy including private variables but this leads to jvm heap corruption the jvm just crashes with exit code 1073740940 sometimes it does not crash but weird things happen like the systemoutprintln stops working as it shouldi have also looked into cloning the objects using js code inside the scriptengine so that i can get those as nativeobjects and manage them in some java maps but all cloning methods which i found have flaws i want a precise snapshot of the objects for instance if each of two objects a and b contain fields say afa and bfb which reference the same object c when cloned using jqueryextend for instance the fields afa and bfb of the cloned a and b will reference different clones of c instead of referencing one same clone and many other edge issuesi also tried to clone the entire scriptengine using cloner not only the bindings and i also tried using rhinos js engine and clone the entire scope instead of the bundeled scriptengine wrapper but the heap corruption issue persistswhy i need to do iti need this because i must be able to restore the values of the entire scriptengine bindings to some previous point i need to make precise snapshots of the bindingsthe application is part of my doctoral research project which consists of running state machines with nodes implemented in java which have js code attached the js code is typed in by the end user and it is being evaled at runtime when final state cannot be reached through a path the algorithm makes steps backwards trying to find alternative paths on each step backward it must undo any changes that might have occurred in the js engine bindingsall the global variables names are known before js evaling and are objects the user types in code for the nodes and this is then organized within java into js objects with certain name patterns but their content can be anything because that is controlled by the user js codeso i guess my only sollution now is to clone js object using js code,"['javascript', 'java']" +306410,unicode characters in ruby 193 irb with rvm update i found almost exact similar question yet it has slightly different prerequisites and thus does not help muchgivenmacos lion 1073rvm 1142ruby 193p194 20120420 revision 35410 x86 64darwin1130ruby was installed with the following line rvm install 193 withreadlinedirusrlocalcellarreadline622when i fire up irb or rails c and start typing unicode characters i get uffd0uffbfuffd1uffd0uffb8uffd0uffbcuffd0uffb5uffd1how do i get unicode characters thisplayed correctly when typing on rubyrails consolesps typing same characters in bash session of terminal result in proper outputpps just to be clear in console i am typing russian characters are they considered unicode symbols,['ruby'] +306453,default constructor for int possible duplicatewhy is it an error to use an empty set of brackets to call a constructor with no arguments in an answer to this question it is said that ints are defaultconstructed as 0 as if you initialized them with int other primitive types are initialized similarly eg double long bool etcjust while i was explaining this to a colleague of mine i made up the following code compiled gcc434 and ran and observed unexpected behaviorinclude iostreamint main int i stdcout i stdendl output is 1why is the output 1 but 0,['c++'] +306458,how to get webconfig appsettings as configurationsection not namevaluecollection configurationmanagerappsettings propertyreturns a namevaluecollection object that contains the contents of the appsettingssection object for the current applications default configurationbut i need appsettingssection object because i need to change it configsource property in runtime,"['asp.net', '.net']" +306472,removing white spacing between images in a table i know this has been covered before but the solutions did not help me i am not a programmer but i can handle basic html code i am trying to send a html email out that has 11 images placed in a table to become one big image however white lines appear between rows when i send iti have the table style set with border0 cellpadding0 cellspacing0 but this does not help can anyone please give me advice also as i am not a programmer i may not understand any complex answersdoctype html public w3cdtd xhtml 10 transitionalen htmlheadtitleuntitled documenttitleheadbody save for web slices toast offer mailer 2jpg table styleheight 920px idtable 01 width650 border0 cellpadding0 cellspacing0tbodytrtd colspan2a href img src 01jpg width236 height201 border0 styleborder 0atdtd colspan3a href img src 02jpg width177 height201 border0 styleborder 0atdtd colspan2a hrefimg src 03jpg width237 height201 border0 styleborder 0atdtrtrtdimg src 04jpg width152 height155tdtd colspan3a href img src 05jpg width173 height155 border0 styleborder 0atdtd colspan2a href img src 06jpg width180 height155 border0 styleborder 0atdtdimg src 07jpg width145 height155tdtrtrtd colspan7img src 08jpg width650 height237tdtrtrtd colspan7img src 09jpg width650 height231tdtrtrtd colspan3a href img src 10jpg width314 height95 border0 styleborder 0atdtd colspan4a hrefmailto img src 11jpg width336 height95 border0 styleborder 0atdtrtrtdimg srcimagesspacergif width152 height1tdtdimg srcimagesspacergif width84 height1tdtdimg srcimagesspacergif width78 height1tdtdimg srcimagesspacergif width11 height1tdtdimg srcimagesspacergif width88 height1tdtdimg srcimagesspacergif width92 height1tdtdimg srcimagesspacergif width145 height1tdtrtbodytable end save for web slices bodyhtml,['html'] +306475,describe the transition to saas model what is the organic growth process from a standalone solution into a software as a service clearlyscalability is not a feature tacked on at the end of developmentso i am interested in high level code and architecture changes requireddoes one pick an existing platform and overnormalize itdoes one start over with bare bones cloud architecture then migrate legacy functionalitydo aggressive technology upgrades ie web forms mvc fit into the processupdatei have been asked for some clarification on the current project architecture without going into too much detail think of a net webforms application that plugs into a layer of business logic and integrates with multiple thirdparty vendors whenever new platform instances are required i lack the terminology here what i mean is when a new client requires business logic adjustments integration with different thirdparty providers hot new branding etc existing code is branched and a new environment is set up any changes are effectively very lowlevel whether or not they happen directly in aspx files component code or db configthis scenario seems perfectly suitable to have a proper saas model implemented but i am having difficulty constructively contributing to the migration process to rephrase the original questions asked which would be an efficient strategy to followovernormalize an existing platform and make everything configurable effectively suspending this simulated scalability and not bringing on new clients until the architecture is refactored the downside to this imho is continuing to rely on code and structure not built for scalability details belowstart from scratch with whatever is deemed to be subjectievly the best architecture for the solution going forward then migrate legacy functionality as needed this allows for almost any desired technology upgrade but lacks visibility until completed and being an aggressive change will be seen as inherently high risk by the managementpersonally i am leaning towards the second option because of the amount of legacy code present and lack of sufficient db normalization at the same time the existing solution is mature and functional if it is not broken do not fix it and there are likely many more ways to scale other than the two approaches i have listed aboveif the context above allows for scenariospecific advice i will take it however i am stil open to more general dos and donts and pointers suitable for a wider audience,['.net'] +306477,buiding hadoop with eclipse maven missing artifact jdktoolsjdktoolsjar16 i am trying to import clouderas orgapachehadoophadoopclient200cdh400 from cdh4 maven repo in a maven project in eclipse 381 m2e plugin with oracles jdk 170 05 on win7 using dependency groupidorgapachehadoopgroupid artifactidhadoopclientartifactid version200cdh400versiondependencyhowever i get the following errorthe container maven dependencies references non existing library cusersmyuseridm2repositoryjdktoolsjdktools16jdktools16jarmore specific maven states that the following artifact is missingmissing artifact jdktoolsjdktoolsjar16any idea on how to solve thismany thanks in advance,['java'] +306499,hartls rails tutorial chapter 9 exercise 6 updating showing and deleting users exercisesis there a way to create an rspec test for user controller actions such as create and new i am not quite clear on the difference between the two actions create and new themselves either could someone please be so kind as to elaborateafter creating the test how would i go about implementing the redirect to root path i think i am supposed to include the new and create actions in the before filter signed in section but this does not automatically redirect to the rooti tried to get the tests to pass by modifying the users controllerrb file as follows def create if signed in redirect to root path else user usernewparamsuser if usersave sign in user flashsuccess welcome to the sample app redirect to user else render new end end end,['ruby-on-rails'] +306508,google charts full html in tooltips i am trying to make google charts thisplay custom tooltips with full html in themi know how to enable tooltips and pass appropriate data the problem is even when allowhtml option is enabled the tooltips are rendered as plain text so for example i cannot show a picture in the tooltiphere is a little example of what i am going for what i have now what i want one way to solve this problem is to thisable tooltips capture onmouseover events and use another library like cluetip to thisplay tooltips at cursor but i was wondering if there is a cleaner native way to enable this kind of functionality in google charts also please check out my other question about images as point markers in google chartseditin the meantime i found a very good and quite inexpensive 60 per website license library that covers this functionality highcharts libraryas you can see in the example it is possible to pass a function that will format the tooltips easily enough we could add a special property to each datapoint containig an url that could be used to dynammically load the tooltips content the tooltips can then be cached by adding an extra property to each data point in a serie i have implemented it this way and it works perfectly hope the latest edit will help someone,['javascript'] +306527,net covariance i have this simple code public interface ireaderout t ienumerablet getdatathis interface should be covariant on t and i am using it this way private static funcbool makesynchrofunctireadert reader where t icomposite return synchronizereadernote the constraint for t to implement icompositethe synchronization method takes an ireadericomposite in input private static bool synchronizeireadericomposite reader the compiler tells me it cannot convert from ireadert to ireadericomposite despite the constraint on t and the covariance of ireaderis there something i am doing wrong here the compiler should be able to verify the constraint and the covariance should let me use my ireadert as an ireadericomposite is not it thanks,"['c#', '.net']" +306531,spinning progress bar in every listview item i have been scratching my head over this for a long time now and searched for an answer without any luckit seems to be trivial but as far as i know it is noti use a listview in my android application where every item view thisplays a spinning progressbar before thecontent is loaded and thisplayed the content is retrieved through http calls and json so it may take a while to processthe problem is that the spinning progress bars rotates independently of each other thus creating the effect of a whirlingchaos instead of a syncronised row of goodlooking loading markersi have tried everything i could come up with not recycling the progressbar in getview have only one instance of the same progressbarresetting the progressbars androidprogress whenever the list items gets visible via onscroll in the activity etcbut since they start to spin in creation time when getview gets called in the adapter they will never have the same cycle syncany suggestions are welcome,['android'] +306534,why do web sites tend to use random ids on database tables i wonder why many web sites choose to use random ids instead of incrementing from 1 on their database tables ia ve searched without finding any good reasons are there anyalso which is the best method to use it seems quite inefficient to check if an id already exists before inserting the data takes a second querythanks for your help,"['php', 'mysql']" +306543,how to make difference between textfieldsettext and adding text to textfield manually in java i have a textfield in my application which will be initiated programmatically textfieldsettext when user clicked in an item in jlist later user will change this value manuallyi get stuck with using documentlistener to detect changes in this text fieldwhen changes happens programmatically it must do nothing but if manually happens it should change the background to redhow to detect whether textfield has been filled out manually or by textfieldsettexttxtmodegetdocumentadocumentlistenernew documentlistener public void insertupdatedocumentevent e if modeequalsegetdocument txtmodesetbackgroundcolorred public void removeupdatedocumentevent e if modeequalsegetdocument txtmodesetbackgroundcolorwhite public void changedupdatedocumentevent e to change body of implemented methods,['java'] +306548,programming android apps in jython the other day i came across a python implementation called jythonwith jython you can write java applications with python and compile them to pure java i was wondering android programming is done with javaso is it possible to make android apps with jython,"['android', 'python']" +306565,merge static libraries into single how to merge the static libraries into single onei do have three static libraries libsignaturelibary armv6a libsignaturelibary armv7a and libsignaturelibary i368anow i want to merge this three file into one single library which may be named has libsignaturelibaryawhile googling i found lipo which is open source tooldo i need to run any extra scripting language to merge or in terminal lipo and pass the parameter for the lipocan any on advice me to build the common library for these threethanks in advance kiran,['iphone'] +306710,jquery unobtrusive validation attributes reference where i can find the reference for unobtrusive jquery validation attributes like datavallength datavalrequired etci want the full list of these attributes is there any single place where i can find this,"['javascript', 'jquery']" +306714,creating link to an url of flask app in jinja2 template in my flask app i have a view which thisplays a postpost blueprintroutepostintyearintmonthtitledef get postyearmonthtitle my codeto thisplay the last 10 entries i have following viewpost blueprintroutepostsdef get all posts my code return render templatephtmlpostspostsnow when i thisplay the last 10 posts i want to convert the title of a post into a hyperlinkcurrently i have to do the following in my jinja template to achieve thisa hrefpostyearmonthtitletitleais there any way to avoid hard coding the url like url for function which is used to create flask urls like thisurl forview nameargumentsi have tried searching for one but im not able to find it,['python'] +306772,how to set div position to 200 pixels to left of the center i want to position a div 200 pixels to left of the centeri am currently using the following code but on higher resolution thisplays eg 1920a1080 the div was slipping out of positionhsonuc position absolute top 20px marginauto marginleft200px thisplaynonewhat i want to achieve,['css'] +306782,support for xna in wp8 after watching a little bit of the summit keynote i kind of heard conflicting reports about it but is it official that xna is being dropped for wp8 i am guessing since the future version of wp supports previous generation of apps that this is probably not true if it is though is using c even an option for games or is c with directx the only way to go,"['c#', 'c++']" +306784,uptodate chef cookbook for ruby is there an uptodate cookbook for ruby i was not able to find one on the opscode cookbook site ie ruby 193 or 192p280,"['ruby-on-rails', 'ruby']" +306798,is it possible to write data into own stdin in linux i want to debug my cgi script c from ide so i would like to create a debug mode read file from thisk push it to own stdin set some environment variables that correspond this file and run the rest of the script as it was called by the web server is it possible and if it is then how can i do that,['c++'] +306806,select text in javascript can we make that a text is highlighted i tried but it does not work,['javascript'] +306827,create a and fill it based on a passed array i have managed to generate a series of listitems based on one specified array within a matrix ie an array within an arrayi would like to be able to pass a variable representing an array to a function so that it can spit out an unordered list filled with listitems based on the array passed into itproblemsthe function only works with one array at a timeit also produces commas in the markup presumably because it is converting the array to a stringthe solution needs toassume that the unordered list does not exist in the dombe able to accept different arrays passed into it options0 options1 etcgenerate the listitems without commasjavascriptvar options set0 option 1option 2 set1 first optionsecond optionthird option function makeul var a ul b ul m right now this loop only works with one explicitly specified array options0 aka set0 for i 0 i options0length i 1 mi li options0i li documentgetelementbyidfooinnerhtml a m b my goal is to be able to pass a variable here to utilize this function with different arraysmakeuljsfiddle,['javascript'] +306829,static objects in aspnet a waste of memory i was just wondering this the other day i am not exactly sure how aspx manages the garbage thisposal but as far as i can tell the finished loading does not remove static memory values or after the page has been reloaded static at least in terms of c means that the memory allocation follows your program until the program itself is shut down is this the same way in aspx if i have a static value and i go from page a to page b is that static value still persistent in the ram until they leave the application or is that value removed once i am no longer on page a go to a different website removing their instance off the application pool in the serverfrom what i have experienced public static class foo public static int x protected void page loadobject sender eventargs e foox this will continue to increment from the last value before reload,"['c#', 'asp.net']" +306841,is it possible to symbolicate c code i have been running into trouble recently trying to symbolicate a crash log of an ios app for some reason the uuid of the dsym was not indexed in spotlight after some manual search and a healthy dose of command line incantations i managed to symbolicate partially the crash logat first i thought the dsym might be incomplete or something like that but then i realized that the method calls missing were the ones occurring in c code this project is an objectivec app that calls into c libraries via objectivec which call back to objectivec code again via objectivec code the calls that i am missing are specifically the ones that happen in c landso my question is is there some way that the symbolication process can resolve the function calls of c code which special options do i need to set if any,"['c++', 'objective-c']" +306876,how do i change the java version of my installed project facet in eclipse i just installed eclipse 37 and the google plugin for eclipse because i want to teach myself how to use google app enginewhen i create a new web application and run i got an error that noted that annotations were not allowed in my jre version 14 hence i set my jre to 16 and my compiler compliance level to 16however i now get this new errordescription resource path location typejava compiler level does not match the version of the installed java project facetmyprojectname unknown faceted project problem java version mismatchhow do i change the version of the installed java project facetthere is no item called project facet to the left of my projects properties menu,['java'] +306882,why does ruby punct miss some punctuation characters ruby punct is supposed to match all punctuation characters according to wikipedia this means per posix standardit matches however it does not match at least in ruby 193p194what gives,['ruby'] +306896,string formatting strformat with a dictionary key which is a str of a number python neophyte here i was wondering if someone could help with the keyerror i am getting when using a dictionary for string interpolation in strformatdictionary key1 val1 1 val2string1 interpolating 0key1formatdictionaryprint string1the above works fine and yieldsinterpolating val1however doing the followingdictionary key1 val1 1 val2string2 interpolating 01formatdictionaryprint string2results in traceback most recent call last file testpy line 3 in module string2 interpolating 01formatdictionarykeyerror 1lso the problem seems to be in the interpretation of the numeric key as a list index imho is there any way to work around this ie convey that this is instead a dictionary keytia and apologies if this question has been asked beforecould not find anything relevant with my searchfu edit 1 the key is not numeric as was erroneously noted earlier instead it is a string representation of a number as was pointed out by brenbarn,['python'] +306908,how can i save an image to the camera roll i am new to xcode using 43 and am not sure how to save an image to the devices camera roll all that i have done so far is set up an ibaction for the button to save the image what library method or function can i use to save an image to the users camera roll,"['iphone', 'ios', 'objective-c']" +306963,why does my mouse cursor change to a plus sign in eclipse i just see strange behaviour in eclipse i am developing one android project in one activity my cusrsor change to plus sign except this it works fine can you tell me how to solve this how to change to arrow sign in that particular activity,['android'] +306967,export sqlite data to excel in ios programmatically in my applicationi am using sqlite as a backendto store data lociallyi am able to insert data into my tablebut what i want to do iswant to import all my sqlite data into excel programmaticallyand i do not want to use server for this apponce the excel sheet is generate user should be able to mail that sheetis this possible in iphoneplease help me out following is my code to insert data into tableibactionloginsqlite3 stmt stmt char errormsg char update1 insert into login1 values int x sqlite3 prepare v2database update1 1 stmt nil if x sqlite ok sqlite3 bind textstmt 1 null1 null sqlite3 bind textstmt 2 userid utf8string1 null sqlite3 bind textstmt 3 str1 utf8string1 null sqlite3 bind textstmt 4 str4 utf8string1 null if sqlite3 stepstmt sqlite done nslogerror errormsg sqlite3 finalizestmt,"['iphone', 'objective-c', 'ios']" +306987,search structure with history persistence i need a maplike data structure in c for storing pairs keyt with the following functionalityyou can insert new elements keyt into the current structureyou can search for elements based on key in the current structureyou can make a snapshot of the current version of the structureyou can switch to one of the versions of the structures which you took the snapshot of and continue all operations from therecompletely remove one of the versionswhat i do not needelement removal from the structuremerging of different versions of the structure into oneiteration over all or some of elements currently stored in the structurein other words you have some search structure that you can build up but at any point you can jump in history and expand the earlierdifferent version of the structure in a different way later on you may jump between those different versionsin my project key and t are likely to be integers or pointer values but not strings the primary objective is to reduce the time complexity space consumption is secondary but should be reasonable as well to clarify for me lognlogs where nnumber of elements snumber of snapshots would be enough although faster is better i have some rough idea how to implement it for example being the structure a binary search tree the insertion of a new element can clone the path from the root to the insertion location while keeping the rest of the tree intact switching tree versions would be equivalent to picking a different version of the root node for which some changes are simply not visiblehowever to make this custom tree efficient eg selfbalancing it will require some additional effort and careful coding of course i can do it myself but perhaps there are already existing libraries to do exactly thatalso there is probably a proper name for this kind of data structure that i simply do not know making my google searches or so searches total failuresthank you for your help,['c++'] +306988,mysql convert datetime to unix timestamp how do i convert the following format to unix timestampapr 15 2012 1200amthe format i get from db seems to have am at the end i have tried using the following but it did not workconvertdatetime salessalesdate 103 as dtsalesdate converttimestamp salessalesdate 103 as tssalesdatewhere salessalesdate value is apr 15 2012 1200am,['mysql'] +307005,cannot find libmysqlclient under usr while build php 52 from source on ubuntu 124 i was trying to build php 5217 from source on ubuntu 124 64bit using this configurationconfigure prefixoptphp52 withconfigfilepathoptphp52 withmysql but i keep getting this errorconfigure error cannot find libmysqlclient under usrnote that the mysql client library is not bundled anymoreany idea how to resolve thisedit1 i minimized the configure command so it just focuses to mysql also i am running a 64bit version of ubuntuedit2 tried running ldconfig v grep mysql and here is the output ldconfig v grep mysqlsbinldconfigreal path libx86 64linuxgnu given more than oncesbinldconfigreal path usrlibx86 64linuxgnu given more than oncesbinldconfigreal cannot stat usrlibx86 64linuxgnulibnss dbso no such file or directorylibmysqlclientso18 libmysqlclient rso1800libmysqlppso3 libmysqlppso310,['php'] +307037,elliptic curve cryptography with sjcl in js and openssl in ruby i am working on a web application which must be able to encrypt data with ecc on the server side and decrypt it in the browser the only library i have found that is capable of this in js is sjcl however since ecc support in sjcl seems a bit abandoned at the moment i have used a fork which has key serialization support and a demo for easier understandingfirst i generate an ecc key pair in jskeypair sjcleccelgamalgeneratekeys384 10documentwritelnjsonstringifykeypairpubserializethis outputs something likepoint10230655241884220775652849225963883815628198429821073634643113875195941810604283123563848913140841219216530614640565114874238110386702601013716131758346573116227800312324018641948620456533899535147857795918538461801553049184curve384then i have tried to convert this public key to a format understandable by opensslar 10230655241884220775652849225963883815628198429821073634643113875195941810604283123563848913140841219216530614640565114874238110386702601013716131758346573116227800312324018641948620456533899535147857795918538461801553049184 ugly bit magic to somehow convert the above array into a proper byte array in form of a stringkstr armap i i008ito s16lengthito s1608x 2321i1 upcasepackh opening a public key generated with the openssl cli tool showed a structure like thisalgokey opensslasn1objectid idecpublickeyalgovalue opensslasn1objectid secp384r1algo opensslasn1sequencenew algokeyalgovalue for some reason openssl seems to prepend 0x04 to all public keyskey opensslasn1bitstringnew x04kstrroot opensslasn1sequencenew algokeypub opensslpkeyreadrootto deruntil this point my code works fine that is it does not produce any exceptionshowever when generating a shared secret with both libraries i found that sjcl generated a tag that was 96 bytes long while openssl emitted 48 bytesturns out my problem is that sjcl does not use plain ecdh it uses something that seems to be ecmqv based on a quick google search therefore the tag sjcl output was a point on the curve x and y coordinates of a point 248 bytes while what openssl output was a shared secret x coordinate of a point as dictated by ecdhmy problem is that i do not know if there is any support for ecmqv in openssl there are some patent problems if i am correct even if there was the ruby binding does not seem to support itso my actual questionsare my findings documented above correctif yes does anyone know any other ruby library which i could use instead of openssl that supports ecmqv,"['javascript', 'ruby']" +307038,how to get isotope to avoid gaps with variable size tiles is there a way to get isotope to order the grid in the way that there are no gaps i see the elements changing places in few of the demos but cannot achieve the effect myself like here heres my fiddleas you can see when you resize the result the grid changes alright but at certain widths white gaps appear in the mosaic which is highly unfortunate,"['javascript', 'jquery']" +307067,dropdownlistfor callback or if statement in my mvc3 application i have a dropdown list in there i have to show all the results but some results must be thisabled so that they are not selectable how can i do thatthis is what i have right now it simply does not show the players that have thisabled set to truehtmldropdownlistform mposition1 modelselectedteamteamplayers wherec cplayerthisabled false orderbyt tplayerlastname toselectlistm mfullname m mplayeridso is there another way to also show the thisabled players but that the output would be like this instead of just hiding them completelyselect optionplayer 1option option thisabledthisabledplayer 2option optionplayer 3option optionplayer 4option option thisabledthisabledplayer 5option optionplayer 6optionselectis that possible with a dropdownlistfor,['c#'] +307088,rbenv irb history is not saving i install ruby via rbenvinstaller when i use irb console i can use history by pressing up and down on keyboard and when i exited from console and start it again i cannot use prewious history when i press uparrowbutton nothing was happenedwhen i used rvm this option was working how can i switch on it in rbenv,['ruby'] +307090,how can i pass touch listeners to custom view for drag and drop i have a question concerning handling touch events for customviewi am adding custom views dynamically to layout ie framelayout those custom views having touchlisteners for pulling points at corners it shows in the below image along with that i have to drag and drop the total view on the screen if user touches other than those corner points color area in the image have to drag and drop of the view otherwise not and also if user touches outside of that view i do not want trigger any touch listeners i am able to pull those points by using this code overridepublic boolean ontoucheventmotionevent event switch eventgetaction case motioneventaction down if toptouchareacontainseventgetx eventgety currenttouch touch top else if righttouchareacontainseventgetxeventgety currenttouch touch right else if lefttouchareacontainseventgetxeventgety currenttouch touch left else return false return false if user touches none of the corners return true case motioneventaction move switch currenttouch case touch top topx eventgetx topy eventgety invalidate return true case touch right rightx eventgetx righty eventgety invalidate return true case touch left leftx eventgetx lefty eventgety invalidate return true case motioneventaction up switch currenttouch case touch top topx eventgetx topy eventgety invalidate currenttouch none return true case touch right rightx eventgetx righty eventgety invalidate currenttouch none return true case touch left leftx eventgetx lefty eventgety invalidate currenttouch none return true return false return falsehow can i achieve this drag and drop along with above characters of the customview,['android'] +307107,html email in outlook i am making a template for email in html it works fine in apple email clients gmail hotmail and windows mail 2006 it does not work in outlook it stretches out the font family is not working and because it stretches out it does not center on the pagethis is my codedoctype html public w3cdtd xhtml 10 transitionalen html xmlnsheadmeta httpequivcontenttype contenttexthtml charsetutf8 meta nameviewport contentinitialscale05meta nameformatdetection contenttelephoneyestitleuntitled documenttitlestyle typetextcssbody margin 0 padding 0 width 100 important overflowy hidden backgroundcolor f webkittextsizeadjust 100 mstextsizeadjust 100 fontfamily helvetica verticalalign top borderspacing 0pxul ol dl padding 0 margin 0h1 h2 h3 h4 h5 h6 p margintop 0 paddingright 0px paddingleft 0px a img border nonealink color 42413c textdecoration underlineavisited color 6e6c64 textdecoration underlineahover aactive afocus textdecoration nonecontainer width 600px background f margin 0 auto content padding 0px paddingleft 10px border none backgroundcolor e9e9e9 lineheight 16px fontsize 14px width 590pxfooter padding 0px 0 background 0 textalign center color white fontsize 12px marginbottom 10px height 45px width 600pxactie backgroundcolor 69696dicons fontsize 12pxcontact textalign centertable borderspacing 0pxcontact a color whitedevices backgroundcolor 2f2f31 height 253px border 0header backgroundcolor 2f2f31 height 87px border 0p fontcolor blackstyleheadbodydiv classcontainer width600px height900px div classheaderimg src 201206logopng width600 height87px div div classdevices backgroundcolor2f2f31 height220px border0img src 201206devices2png div div classcontent table width590 border0 tr td width55h3strongwerkt you al met appsstrongh3 phet gebruik van applicaties oftewel apps is namelijk booming steeds meer merken en bedrijven zien het gemak van een app in het is de ideale optie voor het versterken van uw merk zowel extern als intern of het opzetten van een geheel nieuw product ook de enorme groei in gebruik van mobiele apparaten zorgt er voor dat een sterk merk niet meer kan achter blijvenp pmocht you gea nteresseerd zijn in onze service van op maat gemaakte applicaties en backend oplossingen neem dan gerust contact met ons op you bent van harte welkom voor een kop koffie bij ons in de suikersilos tijdens een verkennend gesprek of een demonstratie van de mogelijkheden van apps voor mobiel tablets tv en het webp palvast bedankt en hopelijk tot ziensptd td width45 valigntop table heightauto border0 cellpadding5px classicons margintop0 tr td colspan2h3no matter what devicebr we build nativelyh3td tr tr tdimg src 201206applepngtd td width199div aligncenterapple ios is the operatingbr system that powers the br iphone ipad and ipod touchdivtd tr tr tdimg src 201206androidpng td tddiv aligncenterwith partners like googlebr htc and motorola android isbr the fastest growing mobile osdivtd tr tr tdimg src 201206windowspng td tddiv aligncentertogether microsoft and nokiabr support conventional users br with windows phonedivtd tr tr tdimg src 201206html5png td tddiv aligncenterlooking for other platformsbr like blackberry samsung br bada or html5 amp css3br we can build itdivtd tr tabletd tr tablediv div classactie div aligncentera hrefimg src 201206actie2png adiv div div classfooter backgroundcolor0 haligncenter height40px table classcontact border0 haligncenter tr aligncenter td aligncenter width189pxfont colorwhitesuikersilowest 23 br 1165 mp halfwegfonttd td aligncenter width189pxa hreftel0031238200140tel 31 23 820 0140abr a hrefmailtoatd td aligncenter width189pxa hrefwmediabunkercomabr a hreftwittercommediabunkeratd tr tableimg src 201206footerpng width600divdivbodyhtmlcan someone help me with fixing this for outlook have i used any elements that are not supported by outlook do i need more inline css,['html'] +307121,generating ddl statements of database from google cloud sql using eclipse cause issue in script i connected to a google cloud sql database from eclipse using data source explorer but when i generate ddl of that database using its option generate ddl i cannot get the auto increment in my script but get the corresponding primary key how would i go about getting the auto increment in my script,['mysql'] +307155,python join a list of integers i am trying to get list of numbers fromnumbers 12to12i tried joinstrn for and in numbers but it wont give the targeted format,['python'] +307178,add help button but keep maximize and minimize i would like to be able to add the help button onto my winform but keep the maxmimize and minimize buttons but windows standard is to thisable both to be able to show the help buttonthere is already a question similarhow to include help in title bar of winform but in that question the one who asked the question is content with removing those 2 buttons for the help to showis there away that i can have help max min and close buttons all there at the same timethanks,['c#'] +307209,how to get quarter from a date in tsql i have a different dates in a column for example 2008010220070821i want to convert this date in year and quarter below is the output year quarter2008 2008q12007 2007q3 select leftdate4 as year from table how can i get the quarter level details,['sql'] +307246,how to serializedeserialize a c wcf datacontract tofrom xml i am developing a wcf service which will be consumed by multiple different client applications in order to make one functionality work the server needs to read an xml file into a c datacontract which is then passed on to the concerned client as far as i understand from the msdn website this is possible but i could not find any complete examples in particular the website talks about a stream parameter which i do not quite get yetmy data contract has one property field which is a list of another data contract which has multiple simple property fieldseg datacontract public class myclass1 datamember public string name datamember public int age datacontract public class myclass2 datamember public listmyclass1 myclass1list my classes look something like this,['c#'] +307249,why does boxsizing borderbox still show the border with a width of 0px when using boxsizing borderbox in css i assume that the total width of an element will be defined in its width value so if i say that the width of a division is 20px and the right border is 10px i will end up with a box that takes up the space of 20px and half of it is the right border pushing it to the point where i set the width to 10px and the right border too like herebox overflow hidden width 10px boxsizing borderbox height 100px background black borderright 10px solid redathe box will only consist of the red border what should happen when i set the width to 0px i thought it would make the whole thing thisappear but no the result is exactly the same like the one above jsfiddlemy question is if this is the expected behavior seems inconsistent to me i would like to make a box thisappear only manipulating the widthheight thanks for any input,['css'] +307273,signalr groups filtering handled on client or server i have been reading a decent amount regarding signalr hubs and groups in particular i have noticed that you cannot get a count of the connections in a particular groupis the filtering for groups handled on the client or server if the server why cannot signalr expose a count if on the client is there a way to send messages only to particular clients,"['c#', 'asp.net']" +307277,ssl certificate verification in java say i have two java apps that i wrote pingjar and pongjar and they get deployed and ran on two separate servers pingjar deploys to srv01myorgcom and pongjar deploys to srv02myorgcom and these two apps need to communicate with each other 2way via ssl let us also assume that each app has its own ssl certificatehow do i a java programmer code ping and pong to verify each others ssl cert does each ca provide some kind of restful api that i can hit with say httpclient does java have its own certificateverifying api are there open source third party jars or services i can usei was surprised by how little turned up when i searched for this online,['java'] +307295,why does inetaddressgetlocalhostgethostname return a value different from bash hostname i have got a buildgradle task that works like a champ on my dev box at producing a properties file that records the name of the machine that the build was generated on the logic is simple enoughdef hostname inetaddressgetlocalhostgethostnameon my dev box this always produces the same value as if i did hostname from the bash shellbobkmbpdm server bobk hostnamebobkmbplocalon our jenkins ci server however bash hostname returns one thing but my call to inetaddressgetlocalhostgethostname returns something else what needs to change on the jenkins machine to get these two returning the same value,['java'] +307300,using multiple input fields for one attribute i am new to rails so sorry if this one is too easyi have a datetime attribute in my model and i try to put the values in it with 3 form elementsthe first one is for the date and is a inputform i use bootstrapdatepickerrails and i would like to stick with it in the second one i would like to have a selectbox for the hours and the third one is for the minutesso i saw i could use datehelpers datetime select but then i cannot use bootstrapdatepicker anymoreso whats the proper way to to fill up a attribute datetime by using more then one form input element i saw that there is something like assign multiparameter attributes but the doc does not quite help thanks,['ruby-on-rails'] +307311,how do i learn to write a console emulator possible duplicatehow do emulators work and how are they written i would like to try writing a basic gameboy emulator or maybe even nes i know the basics of c and i am fairly good at java so i know the necessary basics of programming what i do not know though is how people process all the data into a c program and create an emulator out of it i know i should learn from source but it is kind of hard to see a bunch of lines of code without knowing why they are there and what they are supposed to do where am i supposed to start if i wanted to learn how to write such an emulator i have searched the internet but i have only found unclear tutorials that contain too many errors to figure out by myself where am i supposed to start,['c'] +307315,using mousedown event on mobile without jquery mobile i have built a webapp and for a little bit of polish i wanted to add mousedown and mouseup handlers to swap out images in this case to make a button look like it is being pressedmy code is something like thiswindowonload function preload mouse down image here via image button imgmousedownfunctionbutton imgattrsrcbutton onpng button imgmouseupfunctionbutton imgattrsrcbutton offpngthis works swimmingly on the desktop but on mobile testing in ios safari the mousedown and mouseup events happen at the same time so effectively nothing happensi tried to use the vmousedown and vmouseup events in jquerymobile however this codeinclude jquerymobilejs and jquerymobilecss windowonload function preload mouse down image here via image button imgvmousedownfunctionbutton imgattrsrcbutton onpng button imgvmouseupfunctionbutton imgattrsrcbutton offpngjust gave me the errors that vmousedown and vmouseup do not exist also jquerymobile overrides the css i have already written for the pageso is there a way to get vmousedown and vmouseup to work and to do so without jquery mobiles cssthanks in advanceesa,"['javascript', 'jquery']" +307332,how to change slf4j level at runtime i have using slf4j as my logging framework backed by log4j my problem is that i am looking for a way to change the logging level for my logger at runtimei understand that slf4j does not permit this directly through its own api and hence i have to access the logging provider directly personally i find this to be a huge deficiency in slf4j so now my question is how can i determine programatically through slf4j which provider i am using the biggest purpose of using slf4j is that you become provider agnostic you can easily switch between your favourite logging system without having to recode anything but now if i have to make direct calls to log4j i am losing that abilityat the very least i would like to be able to determine if i am using log4j as the provider and if so then allow the user to switch log levelsif i do loggerfactorygetloggerloggerroot logger name the result is an instance of orgslf4jimpllog4jloggeradapter and not even orgapachelog4jlogger as i would have hopedexpectedis there any way to find this outthankseric,['java'] +307344,rotating an image in android without outofmemoryerror or downscaling basically i am trying to rotate a bitmap from an image in an android app the reason why i want to do this is that a picture taken from the camera through an intent is thisplayed horizontally even if it is captured vertically and the orientation is kept as metadata on the image correct me if in wrong the problem is however that the image will take up a lot of memory when loaded in if taken on a phone with a reasonably good camera and i have not found a way to rotate and save it without the risk of getting outofmemoryerror the code below is where iload in the imagecheck if it needs to be rotatedloads a scaleddown version for thisplay in an imageviewrotates the small image if necessaryin a seperate thread load rotate and save the image so it does not need to in the futureit is important for the application to keep the images in the resolution but any tricks with encodings are welcome i have searched the internet for a few days unable to find anything more than what i already have implemented there is another thread on the subject here but there does not seem to be any solutions hope you can help public bitmap getbitmapfinal context c if bitmap null return bitmap final int rotate necessaryrotationc file ifrotate 0 rotateimagefilec rotate try get scaled version bitmapfactoryoptions options new bitmapfactoryoptions optionsinjustdecodebounds true bitmapfactorydecodefilefile options optionsinsamplesize calcinsamplesizeoptions 1024 1024 optionsinjustdecodebounds false bitmap bitmapfactorydecodefilefile options rotate bitmap rotateimagecbitmaprotate systemoutprintlnbitmap loaded from file size bitmapgetwidth bitmapgetheight systemgc catch exception e systemerrprintlnunable to load image file thisgetfilename if rotation is needed do it in worker thread for next time ifrotate 0 thread t new threadnew runnable public void run load entire image try file imagefile new filegetfilename bitmap huge mediagetbitmapcgetcontentresolver urifromfileimagefile huge rotateimagechugerotate save bitmap properly fileoutputstream out new fileoutputstreamimagefile hugecompressbitmapcompressformatpng 100 out outflush outclose hugerecycle huge null out null systemgc catchioexception e eprintstacktrace tstart return bitmapprivate bitmap rotateimagecontext c bitmap bitmap int rotate if rotate 0 rotate matrix m new matrix mpostrotaterotate bitmap rotimage bitmapcreatebitmapbitmap 0 0 bitmapgetwidth bitmapgetheight m true bitmaprecycle systemoutprintlnimage id getid rotated successfully systemgc return rotimage return bitmapprivate int necessaryrotationcontext c string imagefile int rotate 0 exifinterface exif try exif new exifinterfaceimagefile int orientation exifgetattributeint exifinterfacetag orientation exifinterfaceorientation normal switch orientation case exifinterfaceorientation rotate 270 rotate 270 break case exifinterfaceorientation rotate 180 rotate 180 break case exifinterfaceorientation rotate 90 rotate 90 break catch ioexception e todo autogenerated catch block eprintstacktrace return rotateprivate int calcinsamplesizebitmapfactoryoptions options int reqwidth int reqheight int height optionsoutheight int width optionsoutwidth int insamplesize 1 while height reqheight width reqwidth height 2 width 2 insamplesize 2 return insamplesizeif there is anything you need to know or have any optimizations i might be able to use to reduce memory usage please write thanks,['android'] +307355,get id of master page object in content page if the master page has a label with the id label1 how do i control that id in the content page the id is not passed down so i cannot control it inherently for example if i have a control with the id contentlabel i can access it code by just typing contentlabelwhatever i am doing,['asp.net'] +307356,jqueryui sortable on table rows shrinks them while being dragged this issue of table rows shrinking while dragged in the sortable function troubles me for a long time any asnwer qaps in order for sortable to work at all on tables you must use tbody around the table rows you wish to sort and then call the sortable function on the containing tbody,['jquery'] +307362,python typeerror not enough arguments for format string heres the output these are utf8 strings i believe some of these can be nonetype but it fails immediately before ones like thatinstr s s d s s s s softname procversion intpercent exe description company procurltypeerror not enough arguments for format stringits 7 for 7 though,['python'] +307363,nginx uwsgi flask thisabling custom error pages is it possible to thisable nginxs custom error pages if i may call them that to thisplay my frameworks exception pagesi cannot really see my werkzeug debugger tool rendered in htmlupdateok i got to make a very very simple flask application to work and i will post the bitshomemy uservirtualenvsnginxtestetcnginxconfworker processes 1events worker connections 1024 http server listen 50 server name localhost access log homemy uservirtualenvsnginxtestlibnginxaccesslog error log homemy uservirtualenvsnginxtestlibnginxerrorlog location include uwsgi params uwsgi pass unixtmpuwsgisock homemy userdevnginx test init pyfrom flask import flaskapp flask name approutedef index raise exceptionif name main apprun0 debugtruepythonpath environment variable echo pythonpathhomemy userdevhow i run uwsgi uwsgi s tmpuwsgisock module nginx test callable apphow i run nginx nginx c virtualenvsnginxtestetcnginxconf p virtualenvsnginxtestlibnginxif i hit the root pageif i run nginx manually likepython homemy userdevnginx test init pyi will see instead and what i want to seeof course i made sure it would work when i did not raise the exception but returned hello world for example on my index functionthis is referred to custom error pages in net i want to thisable this and let nginxuwsgi pass the html generated by the debugger directly to the browser instead of the internal server error thingupdate 2now if i change my flask app to enable debugging mode byhomemy userdevnginx test init pyfrom flask import flaskapp flask name appconfigupdatedebugtrueapproutedef index raise exceptionif name main apprun0 debugtruethen i get 502 errorbut if i instead of raise exceptionhomemy userdevnginx test init pyfrom flask import flaskapp flask name appconfigupdatedebugtrueapproutedef index return hello worldif name main apprun0 debugtruei get hello world on my browser when i hit the page httplocalhost50,['python'] +307396,how do i use the direct3d device manager i would like to share one direct3d device between multiple threads and objects in my direct3d application i came across the direct3d device manager which looks like what i want although i am not doing any video processing or video accelerationvvs85aspxin my code i am doing the following create the device manager uint resettoken 0 idirect3ddevicemanager9 devicemanager null if faileddxva2createdirect3ddevicemanager9resettoken devicemanager return false add the device to the device manager if faileddevicemanagerresetdevicedevice resettoken return false devicemanageraddrefmy question is once i have created the direct3d device manager how do i share the direct3d device manager with other objects without passing around a pointer to the device manager microsoft has specifically said to do the following but i have no clue what is really meant by the followingthe device owner must provide a way for other objects to get a pointer to the idirect3ddevicemanager9 interface the standard mechanism is to implement the imfgetservice interface the service guid is mr video acceleration servicecan someone out there show me how to share the device manager by using the imfgetservice interface,['c++'] +307415,two assignments in single python list comprehension for examplea 123x 2i for i in ay 3i for i in awould it be more efficient to combine the list comprehensions into one if possible if the size of a is large if so how do you do this something like xy 2i 3i for i in awhich does not work if using list comprehension is not more computationally efficient than using a normal for loop let me know too thanks,['python'] +307469,net interview code structure and the design i have been given the below net question in an interview i donat know why i got low marks unfortunately i did not get a feedbackquestionthe file hockeycsv contains the results from the hockey premier league the columns afora and aagainsta contain the total number of goals scored for and against each team in that season so alabama scored 79 goals against opponents and had 36 goals scored against themwrite a program to print the name of the team with the smallest difference in afora and aagainsta goalsthe structure of the hockeycsv looks like this it is a valid csv file but i just copied the values here to get an ideateam for againstalabama 79 36washinton 67 30indiana 87 45newcastle 74 52florida 53 37new york 46 47sunderland 29 51lova 41 64nevada 33 63boston 30 64nevada 33 63boston 30 64solutionclass program static void mainstring args string path cusersvalid csv path var resultevaluator new resultevaluatorstringformat01path hockeycsv var team resultevaluatorgetteamsmallestdifferenceforagainst consolewriteline stringformatsmallest difference in afora and aagainsta goals team 0 goals dif 1 teamname teamdifference consolereadline public interface iresultevaluator team getteamsmallestdifferenceforagainstpublic class resultevaluator iresultevaluator private static datatable leaguedatatable private readonly string filepath private readonly icsvextractor csvextractor public resultevaluatorstring filepath thisfilepath filepath csvextractor new csvextractor private datatable leaguedatatable get if leaguedatatable null leaguedatatable csvextractorgetdatatablefilepath return leaguedatatable public team getteamsmallestdifferenceforagainst var teams getteams var lowestteam teamsorderbyp pdifferencefirst return lowestteam private ienumerableteam getteams ilistteam list new listteam foreach datarow row in leaguedatatablerows var name rowteamtostring var for intparserowfortostring var against intparserowagainsttostring var team new teamname against for listaddteam return list public interface icsvextractor datatable getdatatablestring csvfilepathpublic class csvextractor icsvextractor public datatable getdatatablestring csvfilepath var lines filereadalinescsvfilepath string fields fields lines0splitnew int columns fieldsgetlength0 var dt new datatable always assume 1st row is the column name for int i 0 i columns i dtcolumnsaddfieldsitolower typeofstring datarow row for int i 1 i linesgetlength0 i fields linesisplitnew char row dtnewrow for int f 0 f columns f rowf fieldsf dtrowsaddrow return dt public class team public teamstring name int against int for name name against against for for public string name get private set public int against get private set public int for get private set public int difference get return for against outputsmallest difference in for andagainst goals team boston goals dif 34can someone please review my code and see anything obviously wrong here they were only interested in the structuredesign of the code and whether the program produces the correct result ie lowest difference much appreciated,['c#'] +307547,initializing a struct to 0 if i have a struct like thistypedef struct unsigned char c1 unsigned char c2 mystructwhat would be the easiest way to initialize this struct to 0would the following sufficemystruct m1 0or would i need to explicitly init each member to 0mystruct m2 00,['c'] +307600,why does nstextstorage setattributedstring crash with nsmutableattributedstring when i run the following code it crashes at the last line i do not have any idea why this function gets called in awakefromnib voidsetmotdtextnsstring text nsstring boldfontname nsfont boldsystemfontofsize12 fontname nsmutableattributedstring attrstr nsmutableattributedstring alloc initwithstringtext attrstr beginediting attrstr addattributensfontattributename valueboldfontname rangensmakerange0 16 attrstr endediting selfmotdtextviewtextstorage setattributedstringattrstri get this crash log20120622 1132348 msmplan20785403 nscfconstantstring isdefaultface unrecognized selector sent to instance 0x7f79b9f38020120622 1132349 msmplan20785403 an uncaught exception was raised20120622 1132349 msmplan20785403 nscfconstantstring isdefaultface unrecognized selector sent to instance 0x7f79b9f38020120622 1132351 msmplan20785403 0 corefoundation 0x07f8a5bef56 exceptionpreprocess 198 1 libobjcadylib 0x07f8ae19d5e objc exception throw 43 2 corefoundation 0x07f8a64b1be nsobject doesnotrecognizeselector 190 3 corefoundation 0x07f8a5abe23 forwarding 371 4 corefoundation 0x07f8a5abc38 cf forwarding prep 0 232 5 appkit 0x07f8e0b060c nsmutableattributedstringnsmutableattributedstringkitadditions fixfontattributeinrange 1249 6 appkit 0x07f8e0afeb7 nsmutableattributedstringnsmutableattributedstringkitadditions fixattributesinrange 64 7 appkit 0x07f8e19b521 nstextstorage processediting 107 8 appkit 0x07f8e0c2564 nstextstorage editedrangechangeinlength 385 9 foundation 0x07f8d6f4497 nsconcretemutableattributedstring replacecharactersinrangewithattributedstring 328 10 appkit 0x07f8e1dfd19 nsconcretetextstorage replacecharactersinrangewithattributedstring 81 11 msmplan 0x010206af5a msm planappdelegate setmotdtext 314 12 msmplan 0x010206c455 msm planappdelegate awakefromnib 1701 13 corefoundation 0x07f8a5b5fb1 nsobject performselector 49 14 corefoundation 0x07f8a5b5f32 nsset makeobjectsperformselector 274 15 appkit 0x07f8e0369ff nsibobjectdata nibinstantiatewithownertoplevelobjects 1245 16 appkit 0x07f8e02cf73 loadnib 322 17 appkit 0x07f8e02c470 nsbundlensnibloading loadnibfilenametablewithzoneownerbundle 217 18 appkit 0x07f8e02c38b nsbundlensnibloading loadnibfileexternalnametablewithzone 141 19 appkit 0x07f8e02c2ce nsbundlensnibloading loadnibnamedowner 364 20 appkit 0x07f8e29d06f nsapplicationmain 398 21 msmplan 0x010206adf2 main 34 22 msmplan 0x010206adc4 start 5220120622 1132416 msmplan20785403 terminating app due to uncaught exception nsinvalidargumentexception reason nscfconstantstring isdefaultface unrecognized selector sent to instance 0x7f79b9f380 first throw call stack 0 corefoundation 0x07f8a5bef56 exceptionpreprocess 198 1 libobjcadylib 0x07f8ae19d5e objc exception throw 43 2 corefoundation 0x07f8a64b1be nsobject doesnotrecognizeselector 190 3 corefoundation 0x07f8a5abe23 forwarding 371 4 corefoundation 0x07f8a5abc38 cf forwarding prep 0 232 5 appkit 0x07f8e0b060c nsmutableattributedstringnsmutableattributedstringkitadditions fixfontattributeinrange 1249 6 appkit 0x07f8e0afeb7 nsmutableattributedstringnsmutableattributedstringkitadditions fixattributesinrange 64 7 appkit 0x07f8e19b521 nstextstorage processediting 107 8 appkit 0x07f8e0c2564 nstextstorage editedrangechangeinlength 385 9 foundation 0x07f8d6f4497 nsconcretemutableattributedstring replacecharactersinrangewithattributedstring 328 10 appkit 0x07f8e1dfd19 nsconcretetextstorage replacecharactersinrangewithattributedstring 81 11 msmplan 0x010206af5a msm planappdelegate setmotdtext 314 12 msmplan 0x010206c455 msm planappdelegate awakefromnib 1701 13 corefoundation 0x07f8a5b5fb1 nsobject performselector 49 14 corefoundation 0x07f8a5b5f32 nsset makeobjectsperformselector 274 15 appkit 0x07f8e0369ff nsibobjectdata nibinstantiatewithownertoplevelobjects 1245 16 appkit 0x07f8e02cf73 loadnib 322 17 appkit 0x07f8e02c470 nsbundlensnibloading loadnibfilenametablewithzoneownerbundle 217 18 appkit 0x07f8e02c38b nsbundlensnibloading loadnibfileexternalnametablewithzone 141 19 appkit 0x07f8e02c2ce nsbundlensnibloading loadnibnamedowner 364 20 appkit 0x07f8e29d06f nsapplicationmain 398 21 msmplan 0x010206adf2 main 34 22 msmplan 0x010206adc4 start 52terminate called throwing an exceptionlldbhas anybody an idea if i call it with a nsattributedstringobject therea s no error,['objective-c'] +307602,accessing a web service and a http interface using certificate authentication it is the first time i have to use certificate authenticationa commercial partner expose two services a xml web service and a http service i have to access both of them with net clientswhat i have tried0 setting up the environmenti have installed the sslcacertificates on root and two intermediate and the client certificate in my local machine win 7 professional using certmgrexe1 for the web servicei have the client certificate derthe service will be consumed via a net proxyheres the codeorderwsservice proxy new orderwsservicestring certfile clientcert dercerproxyclientcertificatesaddnew systemsecuritycryptographyx509certificatesx509certificatecertfileordertrackingto ot new ordertrackingto order id 80 tracking id 82 status stateordertypein preparation resultresponseto res proxyinsertordertrackingotexception reported at last statement the request failed with an empty response2 for the http interfaceit is a https interface i have to call through post methodthe https request will be send from a net client using httpwebrequestheres the codestring postdata mypostdatasetting the requesthttpwebrequest reqreq httpwebrequesthttpwebrequestcreateurlrequseragent myuseragentreqmethod postreqcontenttype applicationxwformurlencodedreqclientcertificatesaddnew systemsecuritycryptographyx509certificatesx509certificatecertfile mypassword setting the request contentbyte bytearray encodingutf8getbytespostdatastream datastream reqgetrequeststreamdatastreamwritebytearray 0 bytearraylengthdatastreamcloseobtaining the responsewebresponse res reqgetresponser new streamreaderresgetresponsestreamexception reported at last statement the request was aborted could not create ssltls secure channel3 last try using the browserin chrome after installing the certificates if i try to access both urls i get a 107 errorerror 107 neterr ssl protocol errori am stuck,['c#'] +307617,get last visible element using jquery table tr classhere idt1 number1 td1tdtr tr classhere idt2 number2 td2tdtr tr classhere idt3 number3 stylethisplaynonetd3tdtr tr classhere idt4 number4 stylethisplaynonetd4tdtrtablespan idcheckcheckspancheckclickfunction check alertcheckdemo how can i get the attribute number from last visible tr in this example this is an example all tr could be visible,"['javascript', 'jquery', 'html']" +307618,applying style to views dynamically in java code i have following custom button view public class prayertimelabel extends button int hoursint minutesstring dayhalf am or pmcontext parentactivityprayercontrol parentcontrolpublic prayertimelabelcontext contextprayercontrol parent supercontext initcontextparent0public prayertimelabelcontext context int defstyle prayercontrol parent supercontext null rstylebutton prayertimebutton supercontext null defstyle initcontextparentdefstyleprivate void initfinal context context prayercontrol parent int defstyle parentactivity context parentcontrol parent typeface tf typefacecreatefromassetcontextgetassetsfontsdigitalttf thissettypefacetf thissettextfalse thissetonclicklistenernew onclicklistener public void onclickview v timedialog dialogbox parentcontrolgetdialogbox dialogboxsettimehours minutes dayhalf dialogboxshow public void settimeint hrs int min string halfboolean signalparent hours hrs minutes min dayhalf half thissettextsignalparentpublic void settextboolean signalparent supersettextstringformat02d hoursstringformat02d minutes dayhalf ifsignalparent parentcontrolsetprayertimehours minutes dayhalf and i have the following style defined in my stylexml style namebuttonprayertimebutton parentandroidstyletextappearancewidgetbutton item nameandroidbackground0item item nameandroidtextsize18dpitem item nameandroidtextcolorf00itemstylethe extended button is not getting this style can some on point our what i am doing wrong i searched for the solution and found this can some one suggest some thingnote i cannot use xml to apply styles it has to be constructor editfollowing is the class where this custom button is created and used i have deleted many irrelevant lines of codepublic class prayercontrol extends linearlayout protected prayertimelabel prayertimebuttonprotected string prayernameprotected static int counter0public prayercontrolcontext context supercontext initcontextpublic prayercontrolcontext context attributeset attrs supercontext attrs getxmlattributescontext attrs initcontext protected void getxmlattributescontext context attributeset attrs typedarray a contextobtainstyledattributesattrsrstyleableprayercontrol prayername agetstringrstyleableprayercontrol name dayhalf agetstringrstyleableprayercontrol dayhalf hours agetintegerrstyleableprayercontrol hours 4 minutes agetintegerrstyleableprayercontrol minutes 30 ltrprogress agetintegerrstyleableprayercontrol postnamazinterval 0 rtlprogress agetintegerrstyleableprayercontrol prenamazinterval 0 intervalmax agetintegerrstyleableprayercontrol intervalmax 30 arecycleprotected void initcontext context counter parentactivity context thissetorientationlinearlayouthorizontal thissetidcounter prayertimebuttonstyle rstylebutton prayertimebutton initializeprayertimebuttonprotected void initializeprayertimebutton linearlayoutlayoutparams params new linearlayoutlayoutparams linearlayoutlayoutparamswrap content 40 paramsgravity gravitycenter paramsweight 10f prayertimebutton new prayertimelabelparentactivityprayertimebuttonstylethis prayertimebuttonsettimehours minutes dayhalffalse prayertimebuttonsetlayoutparamsparams thisaddviewprayertimebutton,['android'] +307638,javalangillegalaccesserror class ref in preverified class resolved to unexpected implementation getting while running test project i have implemented project by using third party libraryzxing after implementation project is working fine then after i have written one test project to unit test my projectafter running the test project the main project classes and it is methods are not giving any errors but if any zxing framework class is utilyzed within that method of the main project there getting the above error at run time not yet compile timeplease tell me how to resolve this issue,['android'] +307646,how to get current theme name in magento in magento i am trying to get current theme or package name but not found anythingi used getskinurl but it is return skin path not package or theme nameplease help me how i can get theme or package name,['php'] +307659,click this or that then do something i suppose the title is quite selfexplanatoryi want to close a div when a user clicks on an overlay or on a link i know you can just write two functions like soclosesearchclickfunction branding searchformfadeoutfast globaloverlayfadeoutfastglobaloverlayclickfunction thisfadeoutfast branding searchformfadeoutfastor you can write one function like sofunction closesearch thisfadeoutfast branding searchformfadeoutfastclosesearchclickfunction closesearchglobaloverlayclickfunction closesearchi tried this but it did not workclosesearch globaloverlayclickfunction branding searchformfadeoutfast globaloverlayfadeoutfast but is it possible to write this in one line something like closesearch or globaloverlay,['jquery'] +307665,jmeter thread sequence i have a jmeter test plan with following http request samplerslogincall some functionality which needs a logged in userlogoutwhen i execute the test plan with 5 parallel threads i see that the sampler 2 is called before calling sampler 1 for some threads which then fails the response assertionsis there any way to specify a sequence of samplers to be executed,['java'] +307695,wpf stack panel align centrally i want to be able to align buttons within a stack panel centrally the number of buttons is dynamic and generated when the control is loadedfor example if 1 button is generated then this button should be placed in the center of the control if 5 buttons are thisplayed then all 5 should be horizontally aligned next 2 each other but central to the controlan alternative approach would be to have the control dynamically resize based on its content so it would be wider with more buttons and then horizontally align the user control on the page but i am not sure how to approach either solution does anybody have any ideas,['.net'] +307707,c timespanparse invalid format returns incorrect value instead of exception timespanparse230 returns 23 hourstimespanparse240 returns 24 daysi realize that i made a mistake in that the allowable range of hours is 023 but for minutes and seconds if you attempt to parse an out of range value you get an exception in the case of hours with an out of range value the parser incorrectly assumes you meant days instead of hourscan someone explain thisthis example here covers this very topic and indicates that the same appears to be true about tryparse i get 24 days despite the docs stating that the parse should fail string to parse timespan 0 0 14 140 123 010203 0250 0250 1020304050 1020304050 99235959 99235959 0023005900590099 23595900990 2300 230 2400 parse operation failed 0590 005900 0600 parse operation failed 0059 059 0060 parse operation failed 10 parse operation failed 100 10 10 parse operation failed 010 0010 1020 parse operation failed 10200 1020 123 parse operation failed 01200 120 10 parse operation failed 1012 parse operation failed 101200 10120did i find a bug or am i doing something wrongediti have tested this in linqpad and using a console app in net4 on windows 7 64bit var result timespanparse240 consolewritelineresult result timespanparse240 cultureinfoinvariantculture consolewritelineresultthis results in240240,['c#'] +307730,android app not compatible with devices that sideload google play i have an app which has been deployed to play and is compatible with any device running 21 or later no special restrictions or requirements defined in androidmanifestxmlthere have been several complaints from users trying to install the app via google play but getting messages that it is not compatible in all of these cases sideloading the app works perfectlydigging a little deeper into the problem it appears that in all cases the people reporting the problem are using a device that did not ship with google play installed ie the device probably failed googles cts having said that they are able to install other apps via google play but not ours again sideloading our app onto these devices works fine does anybody know why this might be i assume it must be something i am doing incorrectly in androidmanifestxml but i see nothing suspiciousedit heres the androidmanifestxml altered to protect the names of the innocentxml version10 encodingutf8manifest xmlnsandroid packagecomfoobar androidversioncode1 androidversionnamestringglobal app version usessdk androidminsdkversion7 androidtargetsdkversion10 usespermission androidnameandroidpermissionwrite external storage application androidlabelstringglobal app short name androidicondrawableapp activity androidnamehomeactivity androidthemeandroidstylethemeblacknotitlebar intentfilter androidlabelstringglobal app short name action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity activity androidnameaactivity androidthemeandroidstylethemeblacknotitlebar intentfilter androidlabelstringglobal app short name action androidnameandroidintentactionview intentfilter activity activity androidnamebactivity androidthemeandroidstylethemeblacknotitlebar intentfilter androidlabelstringglobal app short name action androidnameandroidintentactionview intentfilter activity activity androidnamecactivity androidlaunchmodesingletask androidthemeandroidstylethemeblacknotitlebar androidwindowsoftinputmodestatehidden intentfilter androidlabelstringglobal app short name action androidnameandroidintentactionview intentfilter activity activity androidnamedactivity androidlaunchmodesingletask androidthemeandroidstylethemeblacknotitlebar intentfilter androidlabelstringglobal app short name action androidnameandroidintentactionview intentfilter activity activity androidnameeactivity androidthemeandroidstylethemeblacknotitlebar intentfilter androidlabelstringglobal app short name action androidnameandroidintentactionview intentfilter activity activity androidnamefactivity androidthemeandroidstylethemeblacknotitlebar intentfilter androidlabelstringglobal app short name action androidnameandroidintentactionview intentfilter activity this activity is invoked whenever an x is opened activity androidnamegactivity androidthemeandroidstylethemeblacknotitlebar intentfilter androidlabelstringglobal app short name action androidnameandroidintentactionview action androidnameandroidintentactionedit category androidnameandroidintentcategorydefault category androidnameandroidintentcategorybrowsable data androidmimetypeapplicationx data androidmimetypeapplicationy data androidmimetypeapplicationz data androidmimetypeapplicationa data androidmimetypeapplicationb intentfilter activity applicationmanifest,['android'] +307731,how to reverse generate an absolute url from a route on play 2 java i would like to get the absolute url from a controller in play 2 java i found the exact same question for scala but i cannot make it work in javapublic class mycontroller extends controller public static result mymethod return ok public static result test loggerinforoutesmycontrollermymethodurl does not work loggerinforoutesmycontrollermymethodabsoluteurl does not work loggerinforoutesmycontrollermymethodabsoluteurltrue does not work return ok thanks for your help,['java'] +307732,hartl chapter 10 undefined local variable or method object i made the form partial for creating microposts as shown in listing 1033 with render sharederror messages object fobject and updated the respective views files as instructed however i cannot get the rspec tests to pass as i keep getting undefined local variable or method object for class any ideasappviewsshared micropost formhtmlerb form formicropost do f render sharederror messages object fobject div classfield ftext area content placeholder compose new micropost div fsubmit post class btn btnlarge btnprimary end appviewsshared error messageshtmlerb if objecterrorsany div iderror explanation div classalert alerterror the form contains pluralizeobjecterrorscount error div ul objecterrorsfull messageseach do msg li msg li end ul div end appviewsusersnewhtmlerb providetitle sign up h1sign uph1div classrow div claspan6 offset3 form foruser do f render sharederror messages object fobject render fields f f fsubmit create my account class btn btnlarge btnprimary end divdivappviewsusersedithtmlerb providetitle edit user h1update your profileh1div classrow div claspan6 offset3 form foruser do f render sharederror messages object fobject render fields f f fsubmit save changes class btn btnlarge btnprimary end gravatar for user a href target blankchangea divdivauthentication specrequire spec helperdescribe authentication do subject page describe signin page do before visit signin path it should have selectorh1 text sign in it should have selectortitle text sign in end describe signin do before visit signin path describe with invalid information do before click button sign in it should have selectortitle text sign in it should have error messageinvalid it should not have linkusers href users path it should not have linksign out href signout path describe after visiting another page do before click link home it should not have selectordivalertalerterror end end describe with valid information do letuser factorygirlcreateuser before sign in user it should have selectortitle text username it should have linkusers href users path it should have linkprofile href user pathuser it should have linksettings href edit user pathuser it should have linksign out href signout path it should not have linksign in href signin path describe followed by signout do before click link sign out it should have linksign in end end end describe authorization do describe for nonsignedin users do letuser factorygirlcreateuser describe in the users controller do it should not have linkprofile href user pathuser it should not have linksettings href edit user pathuser describe visiting the edit page do before visit edit user pathuser it should have selectortitle text sign in end describe submitting to the update action do before put user pathuser specify responseshould redirect tosignin path end describe visiting the user index do before visit users path it should have selectortitle text sign in end end describe when attempting to visit a protected page do before do visit edit user pathuser fill in email with useremail fill in password with userpassword click button sign in end describe after signing in do it should render the desired protected page do pageshould have selectortitle text edit user end describe when signing in again do before do visit signin path fill in email with useremail fill in password with userpassword click button sign in end it should render the default profile page do pageshould have selectortitle text username end end end describe in the microposts controller do describe submitting to the create action do before post microposts path specify responseshould redirect tosignin path end describe submitting to the destroy action do before delete micropost pathfactorygirlcreatemicropost specify responseshould redirect tosignin path end end end end describe as wrong user do letuser factorygirlcreateuser letwrong user factorygirlcreateuser email before sign in user describe visiting usersedit page do before visit edit user pathwrong user it should not have selectortitle text full titleedit user end describe submitting a put request to the usersupdate action do before put user pathwrong user specify responseshould redirect toroot path end end describe as nonadmin user do letuser factorygirlcreateuser letnon admin factorygirlcreateuser before sign in non admin describe submitting a delete request to the usersdestroy action do before delete user pathuser specify responseshould redirect toroot path end end end enduser specrequire spec helperdescribe user pages do subject page describe index do letuser factorygirlcreateuser beforeall 30times factorygirlcreateuser afterall userdelete all beforeeach do sign in user visit users path end it should have selectortitle text all users it should have selectorh1 text all users describe pagination do it should have selectordivpagination it should list each user do userpaginatepage 1each do user pageshould have selectorli text username end end end describe delete links do it should not have linkdelete describe as an admin user do letadmin factorygirlcreateadmin before do sign in admin visit users path end it should have linkdelete href user pathuserfirst it should be able to delete another user do expect click linkdelete to changeuser countby1 end it should not have linkdelete href user pathadmin end end end describe signup page do before visit signup path it should have selectorh1 text sign up it should have selectortitle text sign up end describe profile page do letuser factorygirlcreateuser letm1 factorygirlcreatemicropost user user content foo letm2 factorygirlcreatemicropost user user content bar before visit user pathuser it should have selectorh1 text username it should have selectortitle text username end describe microposts do it should have contentm1content it should have contentm2content it should have contentusermicropostscount end describe signup do before visit signup path letsubmit create my account describe with invalid information do it should not create a user do expect click button submit not to changeuser count end describe after submission do before click button submit it should have selectortitle text sign up it should have contenterror end end describe with valid information do before valid signup it should create a user do expect click button submit to changeuser countby1 end describe after saving the user do before click button submit letuser userfind by email it should have selectortitle text username it should have success messagewelcome it should have linksign out end end end describe edit do letuser factorygirlcreateuser before do sign in user visit edit user pathuser end describe page do it should have selectorh1 text update your profile it should have selectortitle text edit user it should have linkchange href end describe with invalid information do before click button save changes it should have contenterror end describe with valid information do letnew name new name letnew email before do fill in name with new name fill in email with new email fill in password with userpassword fill in confirm password with userpassword click button save changes end it should have selectortitle text new name it should have success message it should have linksign out href signout path specify userreloadnameshould new name specify userreloademailshould new email end end end,['ruby-on-rails'] +307757,how do i add a simple jquery script to wordpress i read the codex and a few blog posts about using jquery in wordpress and its very frustrating i have got as far as loading jquery in functionsphp file but all of the guides out there are crappy because they assume you already have a ton of wordpress experience for instance they say that now that i am loading jquery through the functionsphp file now all i have to do is load my jqueryhow exactly do i do this what files specifically do i add code to how exactly do i add it for a single wordpress page,['jquery'] +307770,can javascript change the value of page css the following css affects whether a page prints in portrait or landscape by defaultpage size landscapei realize that this only works on a very limited set of browsers and that the user can override it that is okay i am just trying to provide a good defaultthis works fine as a static value in css but i would like to switch dynamically between portrait landscape based on on user choices is it possible to use javascript to change this value,"['javascript', 'css']" +307796,whats the point of methodimploptionsinternalcall many methods in the bcl are marked with the methodimplmethodimploptionsinternalcall attributethis indicates that the method is implemented within the common language runtime itselfwhat was the point of designing the framework in this way over having specified explicit cil instructions that the runtime would be forced to implement ultimately the attribute is creating contractual obligations for the runtime but in a way that appears to me to be confusing and not immediately obviousfor example mathpow could have been written this way excuse my informal mixture of c il and the il itself if it is bad this is only a sample to explain my pointpublic static double powdouble x double y ldarg0 ldarg1 pow dedicated cil instruction retinstead of the current waymethodimplmethodimploptionsinternalcallpublic static double powdouble x double ywhy does methodimploptionsinternalcall exist,['.net'] +307821,heroku toolbelt breaks rails i am in the middle of learning rails and i am trying to get heroku up and running when i install the heroku toolbelt though produces a number of errors if i try to run any rails command i get something like thiscusersezradesktopsitesdemo apprails v cprogram files x86ruby193librubysite ruby191rubygemsrb926in report activate error could not find rubygem railties 0 gemloaderror from cprogram files x86ruby193librubysite ruby191rubygemsrb244in activate dep from cprogram files x86ruby193librubysite ruby191rubygemsrb236in activate from cprogram files x86ruby193librubysite ruby191rubygemsrb1307in gem from crailsinstallerruby193binrails18in mainadditionally running ruby v gives me ruby 192p290 even though i have ruby 193 installed in trying to fix this i found that uninstalling ruby 192p290 would cause my ruby version to simply revert to 193p125 but after doing so heroku no longer works cusersezradesktopsitesdemo appheroku logincprogram files x86ruby193binrubyexe is not recognized as an internal or external command operable program or batch file gem environment after installing heroku toolbelt rubygems environment rubygems version 172ruby version 192 20110709 patchlevel 290 i386mingw32 installation directory cprogram files x86ruby193librubygems191 ruby executable cprogram files x86ruby193binrubyexe executable directory cprogram files x86ruby193bin rubygems platformsruby x86mingw32 gem pathscprogram files x86ruby193librubygems191 cusersezragemruby191 gem configurationupdate sources true verbose true benchmark false backtrace false bulk threshold 10 remote sources gem environment after uninstalling ruby192p290rubygems environmentrubygems version 1816ruby version 193 20120216 patchlevel 125 i386mingw32installation directory crailsinstallerruby193librubygems191ruby executable crailsinstallerruby193binrubyexeexecutable directory crailsinstallerruby193binrubygems platforms rubyx86mingw32gem paths crailsinstallerruby193librubygems191cusersezragemruby191gem configuration update sources trueverbose truebenchmark falsebacktrace falsebulk threshold 10remote sources i am running windows 7 and i am not using rvm because cygwin makes me cryany and all suggestions would be much appreciated,"['ruby-on-rails', 'ruby']" +307841,401 unauthorized on a directory i assume this is an iis error as this does not happen if i run the project on my local machinei have my stylesheets at contentcssany files in that directory would not load on the page and when i navigate to them directly i get a server error401 unauthorized access is denied due to invalid credentialsyou do not have permission to view this directory or page using the credentials that you suppliedthis only happens with that directory i have no problem accessing any other files is there something i need to do in iis7 to stop this,['asp.net'] +307865,cannot set property innerhtml of null i have a simple html page with no code in the body tagi want to insert the html in the body tag through javascriptmy javascript file looks like thisvar global userwallfunction return a very long html code var globalobjectobjectcreateglobal documentgetelementsbytagnamebodyitem0innerhtmlglobalobjectuserwallnow i want this very long html code to be auto inserted in the body tag on page loadbut it is giving me the error i have mentioned in the titlewhyand also is this the correct way to create ajax based websiteno page reloads meaning that if i called server side script to update this very long html code and appended it to the body of the page,"['javascript', 'html']" +307916,strange python function scope behavior i am confused about this scope behaviorclass bar def init self for fn in openopenwremovemkdirexistsisdirlistdir print register fn def func wrapperfilename print called func wrapper fn filename setattrself fn func wrapperbar barbaropenabarremovebbarlistdircthis gives the outputregister openregister openwregister removeregister mkdirregister existsregister isdirregister listdircalled func wrapper listdir acalled func wrapper listdir bcalled func wrapper listdir cbut i would have expected that func wrapper would always be the correct function i know that the scope of func wrapper is to the whole function but i redefine it in every loop iteration and the last instance got saved away in the attrib i also tried to add func wrapper none below the setattr but that does not help would also have wondered meam i blind i do not even really see how to work around fix this,['python'] +307917,crawling using nutchshows an ioexception i have started using nutch and everything was fine until i encountered an ioexception exception nutch crawl urls dir mycrawl depth 2 topn 4cygpath cannot convert empty pathsolrurl is not set indexing will be skippedcrawl started in mycrawlrooturldir urlsthreads 10depth 2solrurlnulltopn 4injector starting at 20120623 033751injector crawldb mycrawlcrawldbinjector urldir urlsinjector converting injected urls to crawl db entriesexception in thread main javaioioexception failed to set permissions of path tmphadooprahulmapredstagingrahul255889423staging to 0700 at orgapachehadoopfsfileutilcheckreturnvaluefileutiljava682 at orgapachehadoopfsfileutilsetpermissionfileutiljava655 at orgapachehadoopfsrawlocalfilesystemsetpermissionrawlocalfilesystemjava509 at orgapachehadoopfsrawlocalfilesystemmkdirsrawlocalfilesystemjava344 at orgapachehadoopfsfilterfilesystemmkdirsfilterfilesystemjava189 at orgapachehadoopmapreducejobsubmissionfilesgetstagingdirjobsubmissionfilesjava116 at orgapachehadoopmapredjobclient2runjobclientjava856 at orgapachehadoopmapredjobclient2runjobclientjava850 at javasecurityaccesscontrollerdoprivilegednative method at javaxsecurityauthsubjectdoassubjectjava415 at orgapachehadoopsecurityusergroupinformationdoasusergroupinformationjava1083 at orgapachehadoopmapredjobclientsubmitjobinternaljobclientjava850 at orgapachehadoopmapredjobclientsubmitjobjobclientjava824 at orgapachehadoopmapredjobclientrunjobjobclientjava1261 at orgapachenutchcrawlinjectorinjectinjectorjava217 at orgapachenutchcrawlcrawlruncrawljava127 at orgapachehadooputiltoolrunnerruntoolrunnerjava65 at orgapachenutchcrawlcrawlmaincrawljava55jeffery i downgraded my nutch version and encountered a new problemwhich is out of my scope to understandplzz help nutch crawl urls dir mycrawl depth 4 topn 5cygpath cannot convert empty pathsolrurl is not set indexing will be skippedcrawl started in mycrawlroot urldir urlsthreads 10depth 4solrurlnulltopn 5injector starting at 20120623 223028injector crawldb mycrawlcrawldbinjector urldir urlsinjector converting injected urls to crawl db entriesexception in thread main javaioioexception job failed at orgapachehadoopmapredjobclientrunjobjobclientjava1252 at orgapachenutchcrawlinjectorinjectinjectorjava217 at orgapachenutchcrawlcrawlruncrawljava127 at orgapachehadooputiltoolrunnerruntoolrunnerjava65 at orgapachenutchcrawlcrawlmaincrawljava55whats the problem this tym,['java'] +307924,list view getlistitemxmlattributes method fails with child publication items i have created a js class to populate sgfolder list view data when items are modified as per jaimes approacheverything works great when i operate on items in the publication they are created inex i open a component or page and the custom locked by column immediately updates and shows my user namehowever when i go to a child publication and repeat that process i get the window asking if i want to localize or edit the parent item if i select to edit the parent window the code does not work i have not quite figured it out yet with initial debugging chrome seems to swallow the error firefox gives me a cryptictimestamp 62012 34254 pmerror uncaught exception exception component returned failure code 0x804002 ns nointerface nsiwebprogressdomwindow nsresult 0x804002 ns nointerface location js frame chromebrowsercontenttabbrowserxml line 545 data nodoes anyone have any initial ideas i will try to post some code later oncode from pageexjstyperegisternamespacemycompanytridionrtfextensions constructormycompanytridionrtfextensionspageex function id typeenableinterfacethis mycompanytridionrtfextensionspageex thisaddinterfacetridioncontentmanagerpage id var p thisproperties pversionnumberstring undefined pmodifiedby undefined plockedby undefined papprovalstatus undefined ppublishdate undefined ppreviousversion undefined ppreviousapprovalstatus undefined pcustommodifieddate undefined pinitialmodifierusername undefined sends the list xml string for the item mycompanytridionrtfextensionspageexprototypegetlistitemxmlattributes function customattributes var attribs extutilsgetlistitemxmlattributescustomattributesthis attribs return thiscallbasetridioncontentmanagerpage getlistitemxmlattributes attribs this method gets called when an item is opened from list view node parameter has the information thisplayed in the list view as attributes we are getting cutom data extender column information from this xml node and storing it in this class member for returning it from getlistitemxmlattributes methodmycompanytridionrtfextensionspageexprototypesetdatafromlist function node parentid timestamp extutilssetdatafromlistnodeparentidtimestampthis thiscallbasetridioncontentmanagerpage setdatafromlist node parentid timestamp gets item icon mycompanytridionrtfextensionspageexprototypegetitemicon function var icon thiscallbasethisdefaultbase getitemicon return iconcode from utilsjs reloads the list view for the given id used in list view data refresh when js cant get the required data without reloadingmycompanytridionrtfextensionsutilitiesreloadlistview function listtcmid var registry modelsgetlistsregistry forvar key in registry var entry modelsgetitemregistrykey if entry entrygetparentid listtcmid entryunload return true return false this method gets called when an item is opened from list view node parameter has the information thisplayed in the list view as attributes we are getting cutom data extender column information from this xml node and storing it in this class member for returning it from getlistitemxmlattributes methodmycompanytridionrtfextensionsutilitiessetdatafromlist function node parentid timestamp itemclicked var p itemclickedproperties if timestamp timestamp itemclickedgettimestamp var tmp if tmp nodegetattributeversion pversionnumberstring tmp ppreviousversion tmp if tmp nodegetattributemodifiedby pmodifiedby tmp pinitialmodifierusername tmp if tmp nodegetattributelockedby plockedby tmp if tmp nodegetattributeapprovalstatus papprovalstatus tmp ppreviousapprovalstatus tmp if tmp nodegetattributepublishdate ppublishdate tmp if pcustommodifieddate undefined if tmp nodegetattributemodified pcustommodifieddate tmp sends the list xml string for the item in the list viewmycompanytridionrtfextensionsutilitiesgetlistitemxmlattributes function customattributes listviewobjectattribs var p listviewobjectproperties extutilsgetlistviewitemlockedbynameplistviewobject if customattributes for var attr in customattributes attribsattr customattributesattr attribsversion extutilsgetlistviewitemupdatedversionplistviewobject modified name has to come after the version update extutilsgetlistviewitemmodifiedbynameplistviewobject attribsapprovalstatus extutilsgetlistviewitemapprovalstatusplistviewobject attribspublishdate extutilsgetlistviewitempublishdateplistviewobject set default values if pversionnumberstring undefined var iresult pversionnumberstringlocalecompareppreviousversion if ppreviousversion undefined iresult 0 it is been updated ppreviousversion pversionnumberstring ppreviousapprovalstatus papprovalstatus also need to update modified date pcustommodifieddate extutilsgetlistviewitemupdatedmodifieddateplistviewobject pinitialmodifierusername pmodifiedby attribsmodified pcustommodifieddate attribslockedby plockedby attribsmodifiedby pmodifiedby this method sets the property of the revisor owner on the item in the list view however if it is not the current user we have no way to look that up in js so we have to reload the list viewmycompanytridionrtfextensionsutilitiesgetlistviewitemmodifiedbyname function plistviewobject var p listviewobjectproperties var xmldoc listviewobjectgetxmldocument if xmldoc modifier should always exist var modifierid xmlgetinnertextxmldoc tcmtcminfotcmversioninfotcmrevisorxlinktitle if modifierid undefined var you tridionuiusersettingsgetjsonusersettingstrue if modifierid uuserdataname var strdescription uuserdatadescriptionsplit pmodifiedby strdescription0 return else were in trouble let us hope it is the initial modifier we had if ppreviousversion pversionnumberstring whew pmodifiedby pinitialmodifierusername return if extutilsreloadlistviewlistviewobjectgetorganizationalitemid hrm something failed on the reload not sure what else to do pmodifiedby modifierid else should not ever happen pmodifiedby return this method sets the property of the lock owner on the item in the list view however if it is not the current user we have no way to look that up in js so we have to reload the list viewmycompanytridionrtfextensionsutilitiesgetlistviewitemlockedbyname function plistviewobject var xmldoc listviewobjectgetxmldocument if xmldoc this will be user id no sense getting tcmid cannot look it up without async call var lockeduserid xmlgetinnertextxmldoc tcmtcminfotcmversioninfotcmitemlocktcmuserxlinktitle if lockeduserid undefined see if it is the current user most likely var you tridionuiusersettingsgetjsonusersettingstrue if lockeduserid uuserdataname var strdescription uuserdatadescriptionsplit plockedby strdescription0 return it is not the current user no synch way to do what we want plus the js call does not get the workflow version anyway refresh the parent view if extutilsreloadlistviewlistviewobjectgetorganizationalitemid hrm something failed on the reload not sure what else to do plockedby lockeduserid else clear it out since there is no lock owner plockedby gets the approvalstatus from the item this makes absolutely no sense but for some reason the approval status gets wiped out when this method enters so i had to use a previous approval status variable to maintain it no idea why i do not see anything else that should be touching it but clearly something clears it outmycompanytridionrtfextensionsutilitiesgetlistviewitemapprovalstatus function plistviewobject check if the item has actually been modified if pversionnumberstring ppreviousversion var xmldoc listviewobjectgetxmldocument if xmldoc papprovalstatus xmlgetinnertextxmldoc tcmtcminfotcmdatatcmapprovalstatusxlinktitle else papprovalstatus ppreviousapprovalstatus if papprovalstatus undefined papprovalstatustouppercase unapproved var foo papprovalstatus papprovalstatus wip return papprovalstatus gets the publishdate from the item list viewmycompanytridionrtfextensionsutilitiesgetlistviewitempublishdate function plistviewobject modification would not alter publish date var p listviewobjectproperties return ppublishdate get the modified date for the workflow version overwrite oob since that uses last major versionmycompanytridionrtfextensionsutilitiesgetlistviewitemupdatedmodifieddate function plistviewobject var xmldoc listviewobjectgetxmldocument var moddate xmlgetinnertextxmldoc tcmtcminfotcmversioninfotcmrevisiondate return moddate gets the updated version information from the itemmycompanytridionrtfextensionsutilitiesgetlistviewitemupdatedversion function plistviewobject var p listviewobjectproperties var xmldoc listviewobjectgetxmldocument var newversionstring undefined if xmldoc newversionstring stringformat01 xmlgetinnertextxmldoc tcmtcminfotcmversioninfotcmversion xmlgetinnertextxmldoc tcmtcminfotcmversioninfotcmrevision if newversionstring undefined want to ensure were getting a later version than we had because it will try to load the nonworkflow version afterwards var iresult newversionstringlocalecompareppreviousversion if ppreviousversion undefined iresult 0 pversionnumberstring newversionstring else pversionnumberstring ppreviousversion else pversionnumberstring ppreviousversion return pversionnumberstringfunction launchpopupwinurl winname winfeatures winobj this will hold our opened window var thewin first check to see if the window already exists if winobj null the window has already been created but did the user close it if so then reopen it otherwise make it the active window if winobjclosed winobjfocus return winobj otherwise fall through to the code below to reopen the window if we get here then the window has not been created yet or it was closed by the user thewin windowopenwinurl winname winfeatures return thewinvar extutils mycompanytridionrtfextensionsutilities,['javascript'] +307933,logging warnings not errors in a rails application and managing them i am looking for a good process to handle warningsinfo type messages in rails applications for example how many times users type in the wrong password how many times validations for models fail etc particularly i am looking for an efficient way to operationalize these metrics since they are not exceptions but could indicate potential bugs or issues in functionality solutions i am kicking around arelogging warning or info messages and using splunk to parse them unfortunately splunk is ver expensivesending airbrake errors in a warning environment,"['ruby-on-rails', 'ruby']" +307936,actionbarsherlock library is full of errors after being imported okay i am trying to get actionbarsherlock working so i imported the library by creating new project create project from existing source choosing library from the actionbarsherlock folderafter that i imported a example project from the samples folder using the same method both the library and the sample are set to android 15 build pathmy problem is over 100 errors come up in the library all kinds of stuff about call requires api level 11 and i have no idea whats wrongthings i have tried cleaning projectsetting build path to 13 14 and 15most of the errors saycall requires api level 11 current min is 8 androidappsomethingupdate i tried right clicking on the lib file and clicking add to build path that didnt work these are a few of the errors that i am gettingdescription resource path location typethe method addcharsequence of type menuwrapper must override a superclass method menuwrapperjava com actionbarsherlocksrccomactionbarsherlockinternalviewmenu line 33 java problemthe method addint int int charsequence of type menuwrapper must override a superclass method menuwrapperjava com actionbarsherlocksrccomactionbarsherlockinternalviewmenu line 43 java problemthe method addint int int int of type menuwrapper must override a superclass method menuwrapperjava com actionbarsherlocksrccomactionbarsherlockinternalviewmenu line 48 java problemthe method addint of type menuwrapper must override a superclass method menuwrapperjava com actionbarsherlocksrccomactionbarsherlockinternalviewmenu line 38 java problemthe method addintentoptionsint int int componentname intent intent int menuitem of type menuwrapper must override a superclass method menuwrapperjava com actionbarsherlocksrccomactionbarsherlockinternalviewmenu line 81 java problemthe method addonattachstatechangelistenerview onattachstatechangelistener of type actionmenuitemview must override a superclass method actionmenuitemviewjava com actionbarsherlocksrccomactionbarsherlockinternalviewmenu line 84 java problemthe method addonattachstatechangelistenerview onattachstatechangelistener of type actionmenupresenteroverflowmenubutton must override a superclass method actionmenupresenterjava com actionbarsherlocksrccomactionbarsherlockinternalviewmenu line 627 java problemthe method addsubmenucharsequence of type menuwrapper must override a superclass method menuwrapperjava com actionbarsherlocksrccomactionbarsherlockinternalviewmenu line 61 java problemthe method addsubmenuint int int charsequence of type menuwrapper must override a superclass method menuwrapperjava com actionbarsherlocksrccomactionbarsherlockinternalviewmenu line 71 java problemthe method addsubmenuint int int int of type menuwrapper must override a superclass method menuwrapperjava com actionbarsherlocksrccomactionbarsherlockinternalviewmenu line 76 java problemthe method addsubmenuint of type menuwrapper must override a superclass method menuwrapperjava com actionbarsherlocksrccomactionbarsherlockinternalviewmenu line 66 java problemthe method clear of type menuwrapper must override a superclass method menuwrapperjava com actionbarsherlocksrccomactionbarsherlockinternalviewmenu line 101 java problemthe method clearheader of type submenuwrapper must override a superclass method submenuwrapperjava com actionbarsherlocksrccomactionbarsherlockinternalviewmenu line 49 java problemthe method close of type menuwrapper must override a superclass method menuwrapperjava com actionbarsherlocksrccomactionbarsherlockinternalviewmenu line 157 java problemthe method collapseactionview of type actionmenuitem must override a superclass method actionmenuitemjava com actionbarsherlocksrccomactionbarsherlockinternalviewmenu line 264 java problemthe method collapseactionview of type menuitemimpl must override a superclass method menuitemimpljava com actionbarsherlocksrccomactionbarsherlockinternalviewmenu line 612 java problemthe method collapseactionview of type menuitemwrapper must override a superclass method menuitemwrapperjava com actionbarsherlocksrccomactionbarsherlockinternalviewmenu line 254 java problemthe method collapseitemactionviewmenubuilder menuitemimpl of type actionbarviewexpandedactionviewmenupresenter must override a superclass method actionbarviewjava com actionbarsherlocksrccomactionbarsherlockinternalwidget line 1497 java problemthe method describecontents of type actionmenupresentersavedstate must override a superclass method actionmenupresenterjava com actionbarsherlocksrccomactionbarsherlockinternalviewmenu line 557 java problemthe method expandactionview of type actionmenuitem must override a superclass method actionmenuitemjava com actionbarsherlocksrccomactionbarsherlockinternalviewmenu line 259 java problemthe method expandactionview of type menuitemimpl must override a superclass method menuitemimpljava com actionbarsherlocksrccomactionbarsherlockinternalviewmenu line 598 java problemthe method expandactionview of type menuitemwrapper must override a superclass method menuitemwrapperjava com actionbarsherlocksrccomactionbarsherlockinternalviewmenu line 249 java problemthe method expanditemactionviewmenubuilder menuitemimpl of type actionbarviewexpandedactionviewmenupresenter must override a superclass method actionbarviewjava com actionbarsherlocksrccomactionbarsherlockinternalwidget line 1471 java problemthe method finditemint of type menuwrapper must override a superclass method menuwrapperjava com actionbarsherlocksrccomactionbarsherlockinternalviewmenu line 127 java problemthe method flagactionitems of type actionbarviewexpandedactionviewmenupresenter must override a superclass method actionbarviewjava com actionbarsherlocksrccomactionbarsherlockinternalwidget line 1466 java problemthe method flagactionitems of type menupopuphelper must override a superclass method menupopuphelperjava com actionbarsherlocksrccomactionbarsherlockinternalviewmenu line 280 java problemthe method getactionprovider of type actionmenuitem must override a superclass method actionmenuitemjava com actionbarsherlocksrccomactionbarsherlockinternalviewmenu line 243 java problemthe method getactionprovider of type menuitemwrapper must override a superclass method menuitemwrapperjava com actionbarsherlocksrccomactionbarsherlockinternalviewmenu line 240 java problemthe method getactionview of type menuitemwrapper must override a superclass method menuitemwrapperjava com actionbarsherlocksrccomactionbarsherlockinternalviewmenu line 229 java problemthe method getalphabeticshortcut of type menuitemwrapper must override a superclass method menuitemwrapperjava com actionbarsherlocksrccomactionbarsherlockinternalviewmenu line 123 java problem,"['java', 'android']" +307982,template onload event for meteorjs i know meteor exposes events such as click for dom element but i am wondering if there is a load event that is fired when a template or partial is loaded how would i accomplish thisthanks,['javascript'] +308035,android remove button dynamically i have a button and when i press it i want to remove it not make it invisible i read that i can do that using layoutremoveviewmybutton but what is the layout and how can i get it in my activitybutton showquestionprivate void initialize showquestion button findviewbyidridbanswerquestionshowquestionpublic void onclickview v switch vgetid case ridbanswerquestionshowquestion showquestionsetvisibilityviewinvisible here i want to delete the button questionsetvisibilityviewvisible theanswersetvisibilityviewvisible answerquestionsetvisibilityviewvisible showchoicessetvisibilityviewvisible showhintsetvisibilityviewvisible break,['android'] +308039,is there a performance difference between cte subquery temporary table or table variable in this excellent so question differences between cte and subqueries were thiscussedi would like to specifically ask in what circumstance is each of the following more efficientfasterctesubquerytemporary tabletable variabletraditionally i have used lots of temp tables in developing stored procedures as they seem more readable than lots of intertwined subqueriesnonrecursive ctes encapsulate sets of data very well and are very readable but are there specific circumstances where one can say they will always perform better or is it a case of having to always fiddle around with the different options to find the most efficient solutionediti have recently been told that in terms of efficiency temporary tables are a good first choice as they have an associated histogram ie statistics,['sql'] +308053,objects with no behavior i am thinking about a situation where i have an object transaction that has quite a few properties to it like account amount date currency type etci never plan to mutate these data points and calculation logic will live in other classes my question is is it poor python design to instantiate thousands of objects just to hold data i find the data far easier to work with embedded in a class rather than trying to cram it into some combination of data structures,['python'] +308099,beginning creating windows 8 metro apps with c and xaml i am looking to develop a game for windows 8 using c and xaml simply because i have a small amount of experience with c and xna 40 am i right in thinking i need to move on from xna for win8 with it being such a fresh topic a quick search on amazon for a book to learn to create such apps only yielded a very small number of results most of which have no reviews yet i was just wondering if anyone can recommend a book for a sort of newbie probably based on the quality of previous titles by the authoralternatively any good web resources i am a student so do not have much money after allapologies for asking such an openended question i am just struggling to find where to begin,['c#'] +308148,can one partially apply the second argument of a function that takes no keyword arguments take for example the python built in pow functionxs 12345678from functools import partiallistmappartialpow2xs 2 4 8 16 32 128 256but how would i raise the xs to the power of 2to get 1 4 9 16 25 49 64listmappartialpowy2xstypeerror pow takes no keyword argumentsi know list comprehensions would be easier,['python'] +308162,ios 5 json parsing results in cocoa error 3840 i am having a hard time parsing the below json string on ios 5states name arizonacities name phoenixname californiacities name orange countyname riversidename san diegoname san francisconame nevadacities name las vegasand heres my code void parsejson nserror jsonerror nilnsdata jsondata nsdata datawithcontentsoffilensbundle mainbundle pathforresourcelocationsjson oftypertfif jsondata nsdictionary jsonobjects nsjsonserialization jsonobjectwithdatajsondata optionsnsjsonreadingmutablecontainers errorjsonerror if jsonerror nslogjson error jsonerror localizeddescription return nslog jsonobjectsi keep getting this errorjson error the operation couldnat be completed cocoa error 3840i would appreciate some help on this because i clearly and incapable of fixing this,['ios'] +308163,js invalid lefthand side expression in postfix operation i am playing with a javascript and am running into an error the error is thisinvalid lefthand side expression in postfix operationand the script is long but i think this is this issue the weird thing is this works when i run it locally but when it is packaged using asset packager it failsany ideas why i might be getting this errorupdate after doing more research i found this function the error seems to happen after in the while statement and i assume it is the a this is a plugin so i did not want to go messing with the codebut do you thing this could be itmgetinternetexplorermajorversion function var a mgetinternetexplorermajorversioncached typeof mgetinternetexplorermajorversioncached undefined mgetinternetexplorermajorversioncached function var a 3 b dcreateelementdiv c bgetelementsbytagnamei while binnerhtml if gt ie a iiendif c0uncaught referenceerror invalid lefthand side expression in postfix operation return a 4 a 1 return a,['javascript'] +308176,uiimagepickercontroller no overlay on preview i am working on an iphone app that makes use of the camera overlay view of the uiimagepickercontroller however the problem i am running into is that my overlay is still on the screen when the picture is taken and the preview screen pops up this looks very weird so i need to do one of two things both of which are proving more difficult than i would have hopedremove the overlay when the preview screen is activedo not show the preview screeni know that i can accomplish 2 by setting showscameracontrols no however i am not currently creating my own camera controls i still want to use the default controls it seems like a sledgehammer approach to say that i need to recreate a perfectly fine ui with a custom built interface just to get around the preview screenon a side rant i find it annoying that the built in camera does not use a preview screen but apple apparently forces apps to go to great lengths to avoid using it seems weird,['iphone'] +308184,convert unicode string to byte string i get a string from a function that is represented like uxd0xbcxd0xb0xd1x80xd0xbaxd0xb0 but to process it i need it to be bytestring like xd0xbcxd0xb0xd1x80xd0xbaxd0xb0 how do i convert it without changes my best guess so far is to take sencodeunicode escape which will return xd0xbcxd0xb0xd1x80xd0xbaxd0xb0 and process every 5 characters so that xd0 becomes one character represented as xd0,['python'] +308233,angularjs how to send auth token with resource requests i want to send an auth token when requesting a resource from my apii did implement a service using resourcefactorytodo resource functionresource return resourcehttplocalhostporttodosjson port3001 query method get isarray true and i have a service that stores the auth tokenfactorytokenhandler function var tokenhandler var token none tokenhandlerset function newtoken token newtoken tokenhandlerget function return token return tokenhandleri would like to send the token from tokenhandlerget with every request send via the todo service i was able to send it by putting it into the call of a specific action for example this workstodoquery access token tokenhandlerget but i would prefer to define the access token as a parameter in the todo service as it has to be sent with every call and to improve drybut everything in the factory is executed only once so the access token would have to be available before defining the factory and it cant change afterwardsis there a way to put a dynamically updated request parameter in the service,['javascript'] +308243,uibezierpath stroke 1px line and fill 1px width rectangle different results here is a simple drawing voiddrawrectcgrectrect vertical line with 1 px stroking uibezierpath vertline uibezierpath alloc init vertline movetopointcgpointmake200 100 vertline addlinetopointcgpointmake200 40 vertlinelinewidth 10 uicolor blackcolor setstroke vertline stroke vertical rectangle 1px width uibezierpath vertrect uibezierpath bezierpathwithrectcgrectmake400 100 10 3900 uicolor blackcolor setfill vertrect fillon non retina 3gs and simulator the first line is blurry and looks wider than 1 px but the second line is crispunfortunately i have neither iphone4 nor the new ipad to test but on retina simulator both lines look the samequestion is rectangle instead of stroke the only way to obtain the same result for non retina and retina devices,['ios'] +308246,gradient radius as percentage of screen size i am trying to create a shape drawable with radial gradient background with radius that will adjust to the screen size take a look at the relevant documentationthis is my codexml version10 encodingutf8shape xmlnsandroid androidshaperectangle gradient androidendcolor0 androidgradientradius50p androidstartcolor5d2456 androidtyperadial shapebut it doenst seem to work if i remove the p it works but then the radius will be static thus not adjusting to the screen sizeany idea whats wrong,['android'] +308273,change locale for djangoadmintools in my settingspy file i havelanguage code rurualso i have installed and working djangoadmintools but admin language still english what i am doing wrongps cat settingspy grep use grep v useruse i18n trueuse l10n trueuse tz true,['python'] +308299,is httpclient safe to use concurrently in all the examples i can find of usages of httpclient it is used for one off calls but what if i have a persistent client situation where several requests can be made concurrently basically is it safe to call clientpostasync on 2 threads at once against the same instance of httpclienti am not really looking for experimental results here as a working example could simply be a fluke and a persistent one at that and a failing example can be a misconfiguration issue ideally i am looking for some authoritative answer to the question of concurrency handling in httpclient,['.net'] +308307,dynamically unload a processing js sketch from canvas i am using some javascript to allow users to dynamically load a sketch on click to a canvas element usingprocessingloadsketchfromsourcescanvas id sketchpdeif i call processingloadsketchfromsources a second or third time it loads a second or third pde file onto the canvas which is what i would expecti would like for the user to be able to click another link to load a different sketch effectively unloading the previous one is there a method i can call or a technique i can use to check if processing has another sketch running and if so tell it to unload it firstis there some sort of processingunloadsketch method i am overlooking i could simply drop the canvas dom object and recreate it but that 1 seems like using a hammer when i need a needle and 2 it results in a screenflicker that i would like to avoidi am no js expert but i have done my best to look through the processingjs source to see what other functions may exist but i am hitting a wall i thought perhaps i could look at processingsketcheslength to see if something is loaded already but simply poping it off the array does not seem to work did not think it wouldi am using processingjs 136,['javascript'] +308332,sort numbers in nsarray this is driving me up the wall and i cannot piece together how to do thisi fetch my array from a plist this array is full of numbers as set in the plist now al i need to do is sort them so they are descending but i cannot work it outhope someone can help out thanks,"['objective-c', 'ios']" +308336,pass additional parameters to post save signal hey i have a user registration form in my django application which collects additional data while a user is trying to register such as address city country phone number etcthis data is saved in the account model class through post save signal the user creation process goes something like this function to create user accountprofiledef create user accountsender instance created kwargs if created modelsaccountobjectscreateuserinstance create user user registrationdef userregistrationrequest if requestmethod post username requestpostfncapitalize requestpostlncapitalize create user newuser userobjectscreate userusernameusername emailrequestpostemail passwordrequestpostpw newuserfirst name requestpostfncapitalize newuserlast name requestpostlncapitalize newusersave return httpresponseusernamepost save handler to create user accountprofilepost saveconnectcreate user account senderuserhere the userregistration function is called when a user posts a form and under this function i can get the post data what i want is to pass that data to create user account method so that it fills in the fields in the account modelright now i do see account objects created in the database but all the fields except the user field are empty obviously because the post variables are not being passed to the create user account method,['python'] +308349,number of open connections and the meaning of sleeping status of a connection i ran this query in my database select db namedbid as dbname countdbid as numberofconnections loginame as loginname from syssysprocesses where dbid 0 group by dbid loginame select countdbid as totalconnections from syssysprocesses where dbid 0 exec sp who2 active i want to know the total number of connections to my database the sum of first query and amount of second query are equal but the third query returns a different number of rowsi want to know what the third query returns i see some of the status in the result of the third query are sleeping what does this mean is the connection idle or it is ready in the pool what does it mean if i have many sleeping connections in my resultthanks,['sql'] +308407,how do i wrap text in a span i have got a span that is 350 pixels wide if there is more text than that it just goes straight out to the right off to the side of the span how do i force the text to wrap down into a paragraph i have tried a variety of things which i have found on the web and nothing seems to workthis needs to work for ie 6 onward it would be good if it worked in firefox tooupdateheres a little more info i am trying to implement a tooltip heres my codehtmltd styletextalignleft nowrapnowrap classtlast a classhtooltip href notesspan styletop 40px left 1167px ul lilorem ipsum dolor sit amet consectetuer adipiscing elit maecenas porttitor congue massa fusce posuere magna sed pulvinar ultricies purus lectus malesuada libero sit amet commodo magna eros quis urna nunc viverra imperdiet enim fusce est vivamus a tellus pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas proin pharetra nonummy pede mauris et orcili ul span atdcsshtooltip htooltipvisited tooltipactive color 0077aa textdecoration nonehtooltiphover color 0099cchtooltip span thisplay inlineblock mswordwrap normal wordwrap breakword backgroundcolor black color f padding 5px 10px 5px 40px position absolute textdecoration none visibility hidden width 350px zindex 10htooltiphover span position absolute visibility visible,"['html', 'css']" +308416,understanding fragments setretaininstanceboolean starting with the documentationpublic void setretaininstance boolean retaincontrol whether a fragment instance is retained across activity recreation such as from a configuration change this can only be used with fragments not in the back stack if set the fragment lifecycle will be slightly different when an activity is recreatedondestroy will not be called but ondetach still will be because the fragment is being detached from its current activityoncreatebundle will not be called since the fragment is not being recreatedonattachactivity and onactivitycreatedbundle will still be calledi have some questionsdoes the fragment also retain its view or will this be recreated on configuration change what exactly is retainedwill the fragment be destroyed when the user leaves the activitywhy does not it work with fragments on the back stackwhich are the use cases where it makes sense to use this method,['android'] +308468,how revisions control works on quora database design well i have seen some plugins to create a versions table to keep track of modifications on specific models but cant do easily like quora shows what i have so far is a table like thatiditem type especifies what model revision refers topicitem idevent if it was edited added reverted removedwho who triggered the eventcolumn what column in topic the value has changed topicphoto urlnew new value old old value revision rel points to the past revisiontimestampsomeone could give me some help and guidelines with this design im worried about performance wrong columns missing columns etcid item type item id event who column new old revision rel date 1 topic 2 edit luccas photo picpng oldpicpng null mdy2 topic 2 revert chris photo oldpicpng picpng 1 mdy,['ruby-on-rails'] +308473,audio glitch when playing two avplayer audio files simultaneously i have an ios app that plays a background soundtrack with one avplayer and plays other sound clips on top with a second avplayer the sound clips are streamed from the internet hence the requirement for avplayer the problem is that when the second avplayer starts playing it causes the background avplayer to stop for a fraction of a second similar to whats described in this commentplay multiple audio files with avplayeri am preparing the audio clips with this method voidprepareaudionsurl asseturl asset avurlasset urlassetwithurlasseturl optionsnilplayeritem avplayeritem playeritemwithassetassetplayer replacecurrentitemwithplayeritemplayeritemplayeritem addobserverself forkeypathplaybackbufferempty optionsnskeyvalueobservingoptionnew contextnilplayeritem addobserverself forkeypathplaybacklikelytokeepup optionsnskeyvalueobservingoptionnew contextnilnsnotificationcenter defaultcenter addobserverself selectorselectorplayeritemdidreachend nameavplayeritemdidplaytoendtimenotification objectplayer currentitemnsnotificationcenter defaultcenter addobserverself selectorselectorplayeritemfailedtoreachend nameavplayeritemfailedtoplaytoendtimenotification objectplayer currentitem and then invoking player play when i want to hear each soundis there something i need to do when i set up the audio session or each instance of the avplayer so that the sounds blend without the glitch,['ios'] +308477,spring integration our application has been designed using spring integration framework complete message action flow starts with listening to queues for which jms message driven adapters has been used after which channel based ie queue endpoints have been defined and each endpoint is processed by serviceactivatorswe are currently into performance phase we are spawning 200 message request initially we observed that messages were not executing in parallel after doing some reading figured out that by adding concurrentconsumer and maxconcurrentconsumer property to jms message driven listener adapter will help to enable multithreading mode indeed this helped but still somewhere in between the process i still see single thread effect is this due to way the endpoint has been defined what is the advantage of adding queue capacity to each endpoint do you think by adding queuecapacity to each channel endpoint definition will again help to run in mutlithreading modethe design snapshot as requested,['java'] +308479,why does c allow an implicit conversion from long to float when this could lose precision a similar question long in float why here does not answer what i am searching forc standard allows implicit conversion from long to floatbut any long greater than 224 when represented as a float is bound to lose its valuec standard clearly states that long to float conversion may lose precision but will never lose magnitudemy questions arein reference to integral types what is meant by precision and magnitude is not number and totally different from number n1 unlike real numbers where 3 and 329 may be considered close enough for a calculation ie depending on what precision programmer wantsis not allowing implicit conversion from long to float an invitation to subtle bugs as it can lead a long to silently lose value as a c programmer i am accustomed to compiler doing an excellent job in guarding me against such issuesso what could have been the rationale of c language design team in allowing this conversion as implicit what is it that i am missing here that justifies implicit conversion from long to float,"['c#', '.net']" +308494,fontface giving ultraheavy font weight andor bad antialiasing i found an open font i liked crete round and designed some screens in photoshop with it when it came time to set up the css i tried using both google fonts and fontsquirrelcoms downloadable kit a zip file with four different types of fonts and a readymade stylesheet but both gave me strange results on macphotoshop what i want it to look likeyuck chrome and safari on mac using an fontface kit from fontsquirrelcomchrome and safari on mac using google fonts basically identicalgood chrome on windows fontsquirrelgood hack i found out that with any opacity not text color alpha less than 10 chrome gave me good results but safari was still badchrome on mac using fontsquirrel with opacity09does anyone have any ideas on what is going on here or what i might be doing wrong,['css'] +308513,how can i change the font of layout xml editor in eclipse i know how to change the font of java editor in eclipse in windows preferences appearance colors and fonts but i could not find option for changing the font of layout editor for files like mylayoutxml or stringsxmlwhere is itthanks,['java'] +308557,modify a running python program i launched a python program with many nested loops and the program will take days i just realized that one of the loops values is wrong and makes a infinite loop i do not want to restart the program from zero is there a way to interrupt the current program and modify the loop range so it will work properly and also if it was trapped with the infinite loop to break itmany thanks for your help,['python'] +308563,memory leak risk in javascript closures solvedthere is a lot of contradictory information on the web regarding this subject thanks to john i managed to work out that the closures as used below are not the cause of memory leaks and that even in ie8 they are not that common as people claim in fact there was only 1 leak that occurred in my code which proved not that difficult to fix from now on my answer to this question will beafaik the only time ie8 leaks is when events are attachedhandlers are set on the global object windowonloadwindowonbeforeunload to get around this see my answer belowhuge updatei am completly lost now after some time digging through articles and tuts both old and new i am left with at least one humongous contradiction while one of the javascript gurus douglas crockford sayssince ie is unable to do its job and reclaim the cycles it falls on us to do it if we explicitly break the cycles then ie will be able to reclaim the memory according to microsoft closures are the cause of memory leaks this is of course deeply wrong but it leads to microsoft giving very bad advice to programmers on how to cope with microsofts bugs it turns out that it is easy to break the cycles on the dom side it is virtually impossible to break them on the jscript sideand as freakish pointed out that my snippets below are similar to jquerys internal workings i felt pretty secure about my solution not causing memory leaks at the same time i found this msdn page where the section circular references with closures was of particular interest to me the figure below is pretty much a schematic representation of how my code works is not itthe only difference being that i have the common sense of not attaching my event listeners to the elements themselves all the same douggie is quite unequivocal closures are not the source of memleaks in ie this contradiction leaves me clueless as to whos right i have also found out that the leak issue is not completely solved in ie9 either cannot find the link atm one last thing i have also come to learn that ie manages the dom outside the jscript engine which puts me in a spot of bother when i change the children of a select element based on an ajax request function changeseasone var xhrsendvaltargetid e e windoweventie targetid thisidreplacecommonsourcefragmentcommontargetfragmentfoohomeselect barhomeselect sendval thisoptionsthisselectedindexinnerhtmltrimsubstring01 xhr prepareajaxfalsefunctiont return function reusablecallbackapplythist documentgetelementbyidtargetidindexajax xhrdatanewselectsendvalfunction reusablecallbackelem if thisreadystate 4 thisstatus 200 var data jsonparsethisresponsetext eleminnerhtml option datathearrayjoinoptionoption option if ie really does manage the dom as though the jscript engine werent there what are the odds that the option elements are not deallocated using this code i have deliberately added this snippet as an example because in this case i am passing variables that are part of the closure scope as an argument to a global function i could not find any documentation on this practice but based on the documentation provided by miscrosoft it should break any circular references that might occur does not it warning lengthy question sorryi have written a couple of fairly large javascripts to make ajax calls in my web application in order to avoid tons of callbacks and events i am taking full advantage of event delegation and closures now i have written a function that has me wondering as to possible memory leaks though i know ie 8 deals with closures a lot better then its predecessors it is company policy to support ie 8 all the same below i have provided an example of what i am on about here you can find a similar example though it does not use ajax but a settimeout the result is pretty much the same you can of course skip the code below to the question itselfthe code i have in mind is this function prepareajaxcallbackmethodurl method method post callback callback successa default cb just logsalerts the response url url geturlmakes default url currentcontrollerajax var xhr createxhrobjecttrycatch etc xhropenmethodurltrue xhrsetrequestmethodxrequestedwithxmlhttprequest xhrsetrequestheadercontenttypeapplicationxwformurlencoded xhrsetrequestheaderaccept xhronreadystatechange function callbackapplyxhr return functiondata do some checks on data before sending datahasownpropertyuser etc xhrsenddata all pretty straightforward stuff except for the onreadystatechange callback i noticed some issues with ie when binding the handler directly xhronreadystatechange callback hence the anonymous function do not know why but i found this to be the easiest way to make it work as i said i am using a lot of event delegation so you can imagine it may prove useful to have access to the actual elementevent that fired the ajax call so i have some event handlers that look like thisfunction handleclicke var targetparentdatai e e windowevent target etarget esrcelement if targettagnametolowercase input targetclassname delegateme return true parent target whileparenttagnametolowercase tr parent parentparentnode data fori0iparentcellsi dataparentcellsiclassname parentcellsiinnerhtml data looks something like namebarfirstnamefootitlemr i prepareajaxfunctiont return function if thisreadystate 4 thisstatus 200 check responsetext and if ok tsetattributethisabledthisabled target idataas you can see the onreadystatechange callback is the return value of a function that provides the reference to the target element when the callback is called thanks to event delegation i no longer have to worry about events that might be bound to that element when i decide to remove it from the dom which i do sometimes to my mind however the call object of the callback function might prove too much for ies jscript engine and its garbage collectorevent handler prepareajax is a pretty normal call sequence but the callback argumentanon func argument t target returns anon f has access to t which in turn refs back to target passed to a anon callback function called using apply method to the xhr object in turn a private variable to the prepareajax functioni have tested this construction in ff and chrome it works just fine there but would this kind of callstack of closure upon closure upon closure on each occasion passing a reference to a dom element be an issue in ie especially versions prior to ie9no i am not going to use jquery or other libs i like pure js and want to know as much as i can about this seriously underrated language the code snippets are not actual copypaste examples but provide imo a good representation of how i am using delegation closures and callbacks throughout my script so if some syntax is not quite right feel free to correct it but that is not what this question is about of course,['javascript'] +308572,getonclicklistener in android views i need a getonclicklistener for views in android this way i can assign a temporary onclicklistener to my views i want to use it like thisprivate viewonclicklistener oldlistenerpublic void assigntemplistenerview view oldlistener viewgetonclicklistener does not exist viewsetonclicklistenernew viewonclicklistener override public void onclickview v some code vsetonclicklisteneroldlistener the problem is that this function doent exist i also cannot inherit from view to create this method because all kind of views can be passed to assigntemplistener is there another way to use thisedit made a small mistake in my code,['android'] +308585,finding repeated occurrences with ranking functions please help me generate the following query i have been struggling with for some time now lets say i have a simple table with month number and information whether there were any failed events in this particular monthbelow a script to generate sample datawith datamonth success as select 1 0 union all select 2 0 union all select 3 0 union all select 4 1 union all select 5 1 union all select 6 0 union all select 7 0 union all select 8 1 union all select 9 0 union all select 10 1 union all select 11 0 union all select 12 1 union all select 13 0 union all select 14 1 union all select 15 0 union all select 16 1 union all select 17 0 union all select 18 0given the definition of a repeated failure when event failure occurs during at least 4 months in any 6 months period then the last month with such failure is a repeated failure my query should return the following outputmonth success repeatedfailure1 0 2 0 3 0 4 1 5 1 6 0 r17 0 r28 1 9 0 10 1 11 0 r312 1 13 0 14 1 15 0 16 1 17 018 0 r1where r1 1st repeated failure in month no 6 4 failures in last 6 months r2 2nd repeated failure in month no 7 4 failures in last 6 months r3 3rd repeated failure in month no 11 4 failures in last 6 monthsr1 again 1st repeated failure in month no 18 because repeated failures should be again numbered from the beginning when new repeated failure occurs for the first time in last 6 reporting periods repeated failures are numerated consecutively because based on its number i must apply appropriate multiplier1st repated failure x2 2nd repeated failure x4 3rd and more repeated failure x5,['sql'] +308591,does objectivec support class variables i know it supports automatic variables but what about class variables,['objective-c'] +308613,automatic scaling of multipage tiff nsimage in a calayer problem i have a multipage tiff image generated with tiffutil that contains the same image at multiple pixel dimension from 256x128 px all the way up to 4096x2048 px i want to thisplay this image in a calayer so that the system automatically chooses the best representation of the image depending on the layers size at the moment the layer always uses the 256x128 representation of the image regardless of its sizeheres what i do i load the image withnsimage image nsimage imagenamedmapmultipagetifflogging the image object confirms that it contains multiple representations with different pixel sizes but all representations are the same size in points 256x128 afaik this is how apple recommends multiresolution images to be constructednslog imagensimage 0x100623060 namemapmultipage size256 128 reps nsbitmapimagerep 0x10064d330 size256 128 colorspacenot yet loaded bps8 bppnot yet loaded pixels256x128 alphano planarno formatnot yet loaded currentbackingnil faulting cgimagesource0x10014fdb0 nsbitmapimagerep 0x10064e1b0 size256 128 colorspacenot yet loaded bps8 bppnot yet loaded pixels512x256 alphano planarno formatnot yet loaded currentbackingnil faulting cgimagesource0x10014fdb0 nsbitmapimagerep 0x100530bd0 size256 128 colorspacenot yet loaded bps8 bppnot yet loaded pixels4096x2048 alphano planarno formatnot yet loaded currentbackingnil faulting cgimagesource0x10014fdb0i then assign the nsimage instance directly to the layers contents propertyselflayerviewlayercontents imageas mentioned the result is that the layer uses the first representation 256x128 px to thisplay the image regardless of the layers size in points or pixelswhen i assign the same image to an nsimageview it works as expected the image view transparently selects the best image representation depending on its size i would expect that calayer would work the same way but apparently this is not the case can anybody confirm that calayer does not support this automatic selection or am i doing something wrongnote that this question is not directly related to hidpiretina graphics in fact if i move the layer to a thisplay in hidpi mode it does render a little sharper indicating that it now uses the second bitmap representation 512x256 px for rendering this suggests that the automatism to select a higher resolution on a hidpi thisplay works while the fundamental selection of the best bitmap representation fails,['objective-c'] +308652,get width of last line of multiline uilabel i have a dynamic multi line uilabel and need to know the end of the text x coordinate of the visible text not the label so i can show something after the textis this possiblethank you,"['iphone', 'objective-c']" +308653,knockoutjs binding value of select with optgroup and javascript objects i found an example here to create a select list with optgroups using knockoutjs this works fine but i want to bind the value of the dropdown to my own javascript object then access a particular property of that objectselect databindforeach groups valueselectedoption optgroup databindattr label label foreach children option databindtext labeloption optgroupselectfunction grouplabel children thislabel koobservablelabel thischildren koobservablearraychildrenfunction optionlabel property thislabel koobservablelabel thissomeotherproperty koobservablepropertyvar viewmodel groups koobservablearray new groupgroup 1 new optionoption 1 a new optionoption 2 b new optionoption 3 c new groupgroup 2 new optionoption 4 d new optionoption 5 e new optionoption 6 f selectedoption koobservable specialproperty kocomputedfunction thisselectedoptionsomeotherproperty koapplybindingsviewmodela,"['javascript', 'jquery']" +308667,django getlist i just posted this question jquery passing arrays in post request where i do not to send arrays in post request but there is no problem in jquery codethe problem is with receiving the post request in django i did like thisdef portfolio addrequest ukeys requestpostgetlistukeys etcbut i am getting ukeys values as u when i checked with just requestpost i got the values as uquerydict uukeys u68c04 u16149so how to get those values as a list in djangothanks,['python'] +308683,checking a checkbox in listview makes other random checkboxes checked too whenever i check a checkbox in my listview other random checkboxes get checked too it could be due to item recycling by listviewi also tried setting androidfocusablefalse to checkbox in my layout as suggested in some places but still the onlistitemclick is not called for a row when its checkbox is checkedonly when i click somewhere else it gets calledwhat i want is that only the userchecked checkboxes should remain checked until the user unchecks themi give below the code which is complete and could be run directlyactivity code projactivityjavapublic class projactivity extends listactivity called when the activity is first created overridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate packagemanager pm getpackagemanager listapplicationinfo packages pmgetinstalledapplicationspackagemanagerget meta data final copyofmycustomadapter a new copyofmycustomadapterthis packages getlistviewsetadapteraand finally the custom layout file testlayoutxmllinearlayout xmlnsandroidandroidlayout widthmatch parentandroidlayout heightmatch parentandroidorientationhorizontal checkbox androidididcheckbox1 androidlayout widthwrap content androidlayout heightwrap content androidlayout marginleft20dp androidtextcheckbox androidfocusablefalse imageview androidididimageview1 androidlayout widthwrap content androidlayout heightwrap content androidsrcdrawableic launcher androidfocusablefalse update my customadapter after the suggestion in an answer belowpublic class mycustomadapter extends arrayadapterapplicationinfo private listapplicationinfo appinfolistprivate layoutinflater minflaterprivate packagemanager pmarraylistboolean positionarrayprivate context ctxint visibleposarrayprivate volatile int positioncheck public mycustomadaptercontext context listapplicationinfo mylist supercontext no selection appinfolist mylist ctxcontext minflater layoutinflatercontextgetsystemservicecontextlayout inflater service pm contextgetpackagemanager positionarray new arraylistbooleanmylistsize forint i 0imylistsizei positionarrayaddfalse overridepublic int getcount todo autogenerated method stub return appinfolistsizeoverridepublic view getviewfinal int position view convertview viewgroup parent view row convertview holder holder null ifrownull row minflaterinflaterlayouttestlayout null visibleposarraypositionvisibleposarraylengthposition holder new holder holderappicon imageviewrowfindviewbyidridimageview1 holderckbox checkboxrowfindviewbyidridcheckbox1 rowsettagholder else holder holder convertviewgettag holderckboxsetfocusablefalse holderappiconsetimagedrawableappinfolistgetpositionloadiconpm holderckboxsetcheckedpositionarraygetposition holderckboxsettextappinfolistgetpositionloadlabelpm holderckboxsetoncheckedchangelistenernew oncheckedchangelistener override public void oncheckedchangedcompoundbutton buttonview boolean ischecked ifischecked systemoutprintlnposition positionarrayaddposition true else positionarrayaddposition false return rowstatic class holder imageview appicon checkbox ckboxwhen i scroll up and down i could see random indices changed to true in my boolean arraylist when in syso them,['android'] +308684,find the closest point out of a vector of points i have vector of pointers to a very simple point classclass pointpublic float x float y float zhow do i find the closest object to a referent point using stldo i need first sort the vector first or is there a more efficient way,['c++'] +308697,jquery not recognizing classes added to page dynamically i am working on a project where i would like to add many elements of the same class to a page and make all of these classes accessible to a selectorclick event handler what is happening though is none of the dynamically added elements of the same class are responding to clicksto give you a better picture of what i mean i made up a sample jsfiddle which is very similar to the actual problem in my projectlink to jsfiddle one element of the class added element is on the page already when it loads this element is clickablea button is clicked and it adds other elements of class added element to the page dynamically using append none of these elements are clickablehow can i make all of the elements of class added element clickable i am guessing it has to do with the selector i use in the event handler but i have not been able to figure it outany help is much appreciated,"['jquery', 'html', 'css']" +308701,android javalangclasscastexception androidwidgetimageview cannot be cast to androidwidgettextview i cannot fix this problem on my listview template i have the error as in the title of my post but i would not cast imageview to textview heres my codexml version10 encodingutf8relativelayout xmlnsandroidandroidlayout widthmatch parentandroidlayout height200dipandroidlayout weight1androidpaddingbottom10dip textview androidididmq androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentbottomtrue androidlayout alignparentrighttrue androidtextmetri quadri androidtextcolor33b5e5 androidtextsize14sp androidtextstylebold textview androidididcitta androidlayout widthwrap content androidlayout heightwrap content androidlayout alignbaselineidmq androidlayout alignbottomidmq androidlayout centerhorizontaltrue androidtextcitta androidtextcolor33b5e5 androidtextsize14sp androidtextstylebold textview androidididprezzo androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentbottomtrue androidlayout alignparentlefttrue androidtextprezzo androidtextcolore1e1e1 androidtextsize14sp androidtextstylebold textview androidididnome androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentlefttrue androidlayout alignparenttoptrue androidpadding5dip androidscrollhorizontallytrue androidsinglelinetrue androidtextstringtestolungo androidtextcolore1e1e1 androidtextsize20sp androidtextstylebold imageview androidididfoto androidlayout width80dip androidlayout height60dip androidlayout alignparentlefttrue androidlayout centerverticaltrue androidcontentdescriptionrelease androidpadding5dip androidscaletypecentercrop androidsrcdrawablestub textview androidididdescsplash androidlayout widthwrap content androidlayout heightwrap content androidlayout centerhorizontaltrue androidlayout centerverticaltrue androidtextsmall text androidtextsize16sp androidtextstyleitalic relativelayoutthe error for the java code is on line 58 of my file where i assign the textview id to textview mq view viconvertview ifconvertviewnull vi inflaterinflaterlayoutlistlay null textview nometextviewvifindviewbyidridnome textview mqtextviewvifindviewbyidridmq heres the error textview cittatextviewvifindviewbyidridcitta textview prezzotextviewvifindviewbyidridprezzo imageview imageimageviewvifindviewbyidridfoto textview descrizione textviewvifindviewbyidriddescsplash nomesettextdatagetpositiongetnome mqsettextdatagetpositiongetmetriquadri cittasettextdatagetpositiongetcitta prezzosettextdatagetpositiongetprezzo descrizionesettextdatagetpositiongetdescrizione imageloaderthisplayimagedatagetpositiongetforourl imageand here is the logcat0625 160832497 ddebug14642 prendo textview mq 0625 160832497 dandroidruntime14642 shutting down vm 0625 160832497 wdalvikvm14642 threadid1 thread exiting with uncaught exception group0x40a561f8 0625 160832497 eandroidruntime14642 fatal exception main 0625 160832497 eandroidruntime14642 javalangclasscastexception androidwidgetimageview cannot be cast to androidwidgettextview 0625 160832497 eandroidruntime14642 at comprovalistviewlazyadaptergetviewlazyadapterjava58does anyone know how i can fix this problem,['android'] +308708,should you catch all exceptions this is not how to catch all exceptions but rather should you catch all exceptions in c net i have noticed a tremendous amount of exceptions is it advisable to plan on catching every exceptionfor example the directoryinfo constructor throws 4 exceptions should i plan on catching these or only catch the ones that i can handle maybe let the others bubble up to main where i have a catchall that then tells the user there is an uncaught exception it just seems with all these possible exceptions your code could become more exceptionhandling than actual code,['c#'] +308718,why do python pyc files contain the absolute path of their source code why do python pyc files contain the absolute path of their source code instead of a relative path or something elsea typical init pyc from python 27 on ubuntuufdufdufdocsddltdsiufdufdufdufdtntdbapi2susrlibpython27sqlite3 init pymodules,['python'] +308732,thisplay blob image through jsp i have a code to show a chart o employeesthe data name phone photo etc are stored in sqlserver and thisplayed through jspshowing the data is ok except the image jpg stored in imageblob columnby the way i have already got the image thisplayed see code below but i dontt know how to put it in the area defined in a css see code below too since the image got through the resultset is loaded in the whole page in the browserdoes anyone knows how can i frame the image connection con factoryconnection sql servergetconnectionempchartstatement stsuper concreatestatementstatement stsetor concreatestatementblob image nullbyte imgdata nullresultset rssuper stsuperexecutequeryselect from funchart where dept mydeptif rssupernext image rssupergetblob12imgdata imagegetbytes1 int imagelengthresponsesetcontenttypeimagegifoutputstream o responsegetoutputstreamowriteimgdata even here we got the same as belowoflushoclosetable stylemargin 0px margintop 15pxtrtd idphotoimg titlerssupergetstringempnametrim src owiteimagedata oflush oclose tdtdtd idempdatah3rssupergetstringempnameh3prssupergetstringpositionppidbrrssupergetstringidphonebrrssupergetstringphoneppemailbrrssupergetstringemailptdtableand here is the fragment supposed to frame the imagephoto padding 0px verticalalign middle textalign center width 170px height 220pxthanks in advance,['java'] +308738,set border around uiimageview i want to apply two types of border on a uiimageviewone is the border on the layer of the uiimageviewsecond is the border around the layer of the uiimageviewhow can i do this,"['iphone', 'objective-c', 'ios']" +308769,get the ten minute intervals from a range of datetimes i have a datetime column with range of datetime values i want to create another column with all this datetime values but to round down to ten minute periodso something like thisdatetimesent ten minute column20120611 1827580 20120611 182020120615 1519080 20120615 1510 the farthest i have got is playing around with is getting it in minute bucket slotsi got this by doingselect datetimesent dateaddminute datediffminute 0 datetimesent 0 as minute bucketfrom allrequestsbut i need ten minute bucket slots,['sql'] +308782,c bit operations copy one bit from one byte to another byte i know how to set a bit clear a bit toggle a bit and check if a bit is setbut how i can copy bit for example nr 7 of byte 1 to bit nr 7 in byte 2 it is possible without an if statement without checking the value of the bit include stdiohinclude stdinthint main int byte 1 0b01 int byte 2 0b01010101 byte 2 whats next return 0,['c'] +308792,int object has no attribute getitem import mathimport osclass collection col 0 for col in range5 for row in range6 thist 0 for col in range6 for row in range6 filename result def init selfarg1 selffilename arg1 def collself for i in range6 try ifi0 f openselffilenamer elifi1 f openchap1txtr elifi2 f openchap2txtr elifi3 f openchap3txtr elifi4 f openchap4txtr elifi5 f openchap5txtr for j in range5 selfresult freadline selfcolij selfresult finally print file handling error def thistanceself for i in range6 for j in range6 this 0 for k in range5 this mathfabsselfcolikselfcoljkji selfthistij this selfthistii sysmaxdouble return selfthistclass profile thist 0 for col in range6for row in range6 filename pque 0 for col in range6for row in range6 d 0 for col in range6for row in range6 par 0 for col in range6for row in range6 st 0 def init selfarg1 selffilename arg1 def beginself ob collectionselffilename obcoll thist obthistance def spself for i in range6 pquei sysmaxdouble di sysmaxdouble d0 0 pque0 0 while isempty0 you extract min for i in range6 if diduthistui di duthistui pque deckeyidi pariu if u0 print u print n for i in range6 print pari def extract min ret 0 shift 0 minimum pque0 for i in range6 if pqueiminimum minimum pquei ret i pqueret sysmaxdouble return ret def isemptyself count 0 for i in range6 if pquei sysmaxdouble countcount1 if count6 return 1 else return 0 def pque deckeyselfimdi pqueimdiclass main filename raw inputenter name of studentn filename filename txt ifospathexistsfilename1 f filefilenamer else f filefilenamew att1 raw inputatt1 scoren att2 raw inputatt2 scoren att3 raw inputatt3 scoren att4 raw inputatt4 scoren att5 raw inputatt5 scoren fwriteatt1 fwriten fwriteatt2 fwriten fwriteatt3 fwriten fwriteatt4 fwriten fwriteatt5 fwriten stud profilefilename studbegin studspit shows a runtime error file cpython27winculumpy line 33 in coll selfcolij selfresulttypeerror int object has no attribute getitem i am just a beginner at python and i am unable to rectify this even after searching on the net,['python'] +308798,block incoming texts android i am working on an app that will hopefully have the ability to block incoming text messages depending on user settings but i am having trouble detecting incoming messageswould you mind looking at my codes and let me know what i am doing wrongi have looking through the other questions that are similar to this one but i cannot find any with a detailed answer or enough information for me to referenceimport androidcontentbroadcastreceiverimport androidcontentcontextimport androidcontentintentimport androidosbundle public class smsreceiver extends broadcastreceiver public void onreceivecontext context intent intent ifintentgetactionequalsandroidprovidertelephonysms received bundle bundle intentgetextras if bundle null abortbroadcast heres my manifestreceiver androidnamelistenersmsreceiver intentfilter androidpriority100 action androidnameandroidprovidertelephonysms received intentfilterreceiveri have been following the tutorial on mobiforge as well as the questions herehow to block an incoming message in androidandroid a listen for incoming sms messagescan anyone point me in the right direction herei would appreciate it,['android'] +308803,where do sequence points come from i know that writing something likea ais not only unreadable but also violates the cc sequence pointswhere do these limitations come from how can one see those problems before finding them as bugs,"['c++', 'c']" +308805,how can i reorder multiindexed dataframe columns at a specific level i have a multiindexed dataframe with names attached to the column levels i would like to be able to easily shuffle the columns around so that they match the order specified by the user since this is down the pipeline i am not able to use this recommended solution and order them properly at creation timei have a data table that looks something likeexperiment base iwwgcw iwwgdwlead time 24 48 24 48 24 4820101127 120 0997 0991 0998 0990 0998 099020101128 120 0998 0987 0997 0990 0997 099020101129 120 0997 0992 0997 0992 0997 099220101130 120 0997 0987 0997 0987 0997 098720101201 120 0996 0986 0996 0986 0996 0986i want to take in a list like iwwgcw iwwgdw base and reorder this to beexperiment iwwgcw iwwgdw base lead time 24 48 24 48 24 48 20101127 120 0998 0990 0998 0990 0997 0991 20101128 120 0997 0990 0997 0990 0998 0987 20101129 120 0997 0992 0997 0992 0997 0992 20101130 120 0997 0987 0997 0987 0997 0987 20101201 120 0996 0986 0996 0986 0996 0986 with the caveat that i do not always know at what level experiment will be i tried where df is the multiindexed frame shown abovedf2 dfreindex axisiwwgcw iwwgdw base axis1 levelexperimentbut that did not seem to work it completed successfully but the dataframe that was returned had its column order unchangedmy workaround is to have a function likedef reorder columnsframe column name new order shuffle the specified columns of the frame to match new order index level framecolumnsnamesindexcolumn name new position lambda t new orderindextindex level new index sortedframecolumns keynew position new frame framereindex axisnew index axis1 return new framewhere reorder columnsdf experiment iwwgcw iwwgdw base does what i expect but it feels like i am doing extra work is there an easier way to do this,['python'] +308822,break or exit out of with statement i would just like to exit out of a with statement under certain conditionswith openpath as f print before condition if condition break syntax error print after conditionof course the above does not work is there a way to do this i know that i can invert the condition if not condition print after condition any way that is like above,['python'] +308857,how to efficiently deal with a large amount of html5 canvas pixel data over websockets possible duplicatereceiving image through websocket using imagedata contextgetimagedata0 0 width heightjsonstringifyimagedatadatai grab the pixel data convert it to a string and then send it over the wire via websockets however this string can be pretty large depending on the size of the canvas object i tried using the compression technique found here javascript implementation of gzip but socketio throws the error websocket message contains invalid characters is there an effective way to compress this data so that it can be sent over websockets,['javascript'] +308870,mathpow taking an integer value from int value 2for int power 0 power 32 power consolewriteline01 2n0 value power long mathpowvalue powermathpow takes doubles as arguments yet here we are passing in intsquestion is there any danger of floating point rounding errors if there is an implicit conversion to double happeningif yes it is better to use something likepublic static int intpowint x uint pow int ret 1 while pow 0 if pow 1 1 ret x x x pow 1 return ret,['c#'] +308918,passing variables to jquery ajax success or error functions i am using jquery ajax to loop through a set of json urls and download results into an array some of the urls return a 404 which i am handling showing as a div message however i cannot seem to pass the url more precisely it always only passes the last url in the array i assume that is because ajax is asynchronous and takes longer to complete but i am not sure how else to make sure only the current json url or variable is being shown on success or errormy code for every url loop through baseitems array for var i 0 i baseitemslength i this is where i am hoping to store the current url as a variable to pass to the enduser on success or error var caturl baseurl baseitemsi get the data via json ajax type get url caturl datatype json async true set so that the variables caturl get updated below success function result success store the object into catalog array catunshiftresult showdataprependloaded caturl br still buggy here probably async json issue error function xhr textstatus error error write out error consolelogxhrstatustext consolelogtextstatus consolelogerror showdataprependerror error trying to access caturl br still buggy here probably async json issue update working code the completed working code with charlietfl help a few nice things like success error code count of urls loaded is below thanks charlietfl peacemaker ajax type get url caturl datatype json async true set so that the variables caturl get updated below beforesend function jqxhr settings add url property and get value from settings or from caturl jqxhrurl settingsurl success function result textstatus jqxhr success store the object into catalog array var url jqxhrurl catunshiftresult showdataprependfont size1loading url status textstatus fontbr successcount 1 error to be deprecated in jquery 18 superseded by fail error function jqxhr textstatus error var url jqxhrurl replace caturl with url in your append showdataprependfont size1 colorrederror error trying to access url fontbr complete function jqxhr textstatus showdataprependfont size3loaded b successcount b of baseitemslength total catalogsfontbr,['jquery'] +308942,signalr connection is undefined i admit it i do not know what i am doingi am attempting to learn how to use signalr and i am following various samples online almost verbatim and i cannot get pasted connection being undefined i am working in mvc 40 and trying to use either nugetdownloaded signalr js files or those from sample projects these are my script referencesscriptsrenderscriptsjquery172minjsscriptsrenderscriptsknockout200jsscriptsrenderscriptsjquerysignalrjsscriptsrendersignalrhubsthe scripts seem to load i have even put alerts at the start of them which fire but connection is always undefined in a bizarre turn of events i have a different project where i am trying to use a different jquery library and it uses and that object is also always undefined i am just looking for any possible explanation of what i might be doing wrong thanks very much in advance,"['javascript', 'jquery']" +308943,php weird undefined index error i have a really frustrating issue where i cannot retrieve any of the headers here is my codeheaders getallheadersechoheaderssystemtime doesnt workkeys array keysheadersechoheaderskeys4 doesnt workboth lines produce the error undefined index systemtimei cannot for the life of me figure out why i cant get the value if i go print rheaders i get thisarray contenttype applicationxwformurlencoded contentlength 0 host localhost referer systemtime 20120626093a203a27var dump of headersarray5 contenttype string33 applicationxwformurlencoded contentlength string1 0 host string9 localhost referer string0 systemtime string23 20120626103a103a08var dump of keysarray5 0 string12 contenttype 1 string14 contentlength 2 string4 host 3 string7 referer 4 string10 systemtimeforeach headers as name value echo name value from array headersnamen returnedconnection keepalive from array keepalivecontenttype applicationxwformurlencoded from array applicationxwformurlencodedcontentlength 0 from array 0host localhost from array localhostreferer from array notice undefined index systemtime in clientdataapachewadxcomwadminrequestgetpclicencephp on line 22systemtime 20120626103a103a08 from array im stuck and i seriously cannot figure out what is going wrong it should workps i know that the systemtime header is nonstandard i provide that from my http request,['php'] +308954,error message for virtualenvwrapper on os x lion i have used homebrew to install python on a new mac lion installation and have been trying to install virtualenv and virtualenvwrapper with pip but when i start a new terminal session i get this tracebacktraceback most recent call last file string line 1 in moduleimporterror no module named virtualenvwrapperhook loadervirtualenvwrappersh there was a problem running the initialization hooks if python could not import the module virtualenvwrapperhook loadercheck that virtualenv has been installed forvirtualenvwrapper pythonusrbinpython and that path isset properlythe python and pip used are from homebrew but it seems to want me to use apples default python i get the following which python xargs ls llrwxrxrx 1 beard admin 33 jun 24 1611 usrlocalbinpython cellarpython273binpython echo virtualenvwrapper pythonusrlocalbinpython which pip xargs ls lrwxrxrx 1 beard admin 301 jun 24 1618 usrlocalsharepythonpip which virtualenvwrappersh xargs ls lrwxrxrx 1 beard admin 327 jun 24 1619 usrlocalsharepythonvirtualenvwrappershhowever it seems to think that i have installed pip and virtualenv with the system python in usrbinpythonedit in my bashrcexport workon homehomepyenvexport virtualenvwrapper log dirhomepyenvexport virtualenvwrapper hook dirhomepyenvsource usrlocalsharepythonvirtualenvwrappershexport virtualenvwrapper pythonusrlocalbinpython,['python'] +308964,add laravel support in aptana i wish to add autocomplete with documentation for laravel in aptana 30tough i managed to create autocomplete just by mapping a few methods in it helperphpthis does not seem to be quite effective how to we add method documentation for it too,['php'] +308983,kaminari rails pagination undefined method current page i searched and searched but nothing solved my problem heres my controllerdef show topic topicfindparamsid topicposts topicpostspageparamspageper2 2 for debuggingendthat functions just fine because the topic view is reduced to two posts however when i add this to showhtmlerb paginate topicposts i am given this errorundefined method current page for activerecordrelation0x69041c9b2d58,"['ruby-on-rails', 'ruby']" +308987,how can my chameleon template accept message flashes from the pyramid framework i am learning pyramid and it seems they are trying to get people to use chameleon instead of mako so i thought i would give chameleon a chance i like it so far and i can do basic things in the template such as if and for loops but i am not sure how to get message flashes to appearin the pyramid tutorial they do this in a todo list but in the wiki example they do not according to the instructions about sessions and using the todolist tutorial as a example i have been able to get my app to create messages but i am unable to receive them in my template in a nutshell i am wondering if chameleon has a equivalent of this mako code if requestsessionpeek flash div idflash flash requestsessionpop flash for message in flash messagebr endfor div endif,['python'] +308988,apple reject because of in app purchase not implement restore i got rejected by apple with a message saying additionally we found that while your app offers inapp purchases that can be restored it does not include the required restore feature to allow users to restore the previously purchased inapp purchases as specified in restoring transactions section of the inapp purchase programming guideif your application supports product types that must be restorable you must include an interface that allows users to restore these purchases this interface allows a user to add the product to other devices or if the original device was wiped to restore the transaction on the original deviceto restore previously purchased inapp purchase products it would be appropriate to provide a restore button and initiate the restore process when the restore button is tapped by the userfor more information about restoring transactions and verifying store receipt please refer to the inapp purchase programming guide and i found this page and i followed the sample code but after i called void checkpurchaseditems skpaymentqueue defaultqueue restorecompletedtransactionsanother delegate was not fired void paymentqueuerestorecompletedtransactionsfinishedskpaymentqueue queueit only popups an alert view to let you enter your apple id and nothing happenedi set a break point but it wouldnt stop as the example saidany ideas on whats wrong with my code,"['iphone', 'objective-c']" +308991,how to simulate abnormal case for sockettcp programming in linux such as terminating one side of connection i am learning to use so sndtimeo and so rcvtimeo to check the timeoutit is easy to use with read socket but when i want to check write timeout it always return successful here is what i didall in blocking modeclose the client read socket and exit before server start writeterminate the client before server start writeunplug the cable of server after accept but before writewell it seems all these case write just return sucessfullyi think the reason should be that port is resource managed by os and at the client side after program gone the tcp connection still shows fin wait2 stateso is there any convenient way to simulate some cases that write can receive errors such as epipe eagain,['c'] +309017,which exception to throw if list is empty in java i have the following doubt concerning which exception to throw if list is emptypublic class xyz implements runnable private listfile contractfilelistoverridepublic void run contractfilelist some method that will return the listnow i want to check if returned contractfile is empty or not if yes then raise the exceptionifcontractfilelistisemptythrow new i am runing this code inside a batch i want to throw some exception that will stop the batch execution,['java'] +309049,performance optimization of forloop switchstatement please help me to identify which of these following is more optimized codeforint i0icounti switchway case 1 dowork1i break case 2 dowork2i break case 3 dowork3i break orswitchway case 1 forint i0icounti dowork1i break case 2 forint i0icounti dowork2i break case 3 forint i0icounti dowork3i breakin the first case there happens to be an overhead of always checking the switch case condition in every iteration in second case the overhead is not there i feel the second case is much better if anyone has any other workaround please help me out in suggesting it,['c#'] +309059,2 ios developer certificates with same names we have a little problem here and i hope you guys can help me outsituationwe are enrolled in apples developer program for thistributing apps in the app store since last week were also enrolled in the enterprise program for inhouse app thistributionproblemwe proceeded with the development and building of the apps but we did not knew that we have to use two different developer certificates for the different programs we have now 2 certificates with the same name and xcode is producing an error message each time we want to build the app saying the certificate cannot be assigned exactlyquestionhow do we change the name of one of the developer certificatesmany thanks for your help in advance,"['ios', 'iphone']" +309062,circular radial progress bar do you know of any jquery plugins or css techniques for creating a circular radial progress bar such as,"['javascript', 'jquery', 'html', 'css']" +309081,updating a large number of entities in a datastore on google app engine i would like to perform a small operation on all entities of a specific kind and rewrite them to the datastore i currently have 20 entities of this kind but would like a solution that would scale to any amount what are my options,['python'] +309083,ssrs dataset not refreshed after changing mysql stored procedure ssrs dataset not refreshed after changing mysql stored procedurei created an ssrs report in which the dataset gets data from mysql stored procedure in this scenario the output is generated correctly and so is the reportlater i modify some content in the stored procedure i run the stored proc in query designer in query designer it gives the correct outputbut when going to report if i see the report in preview tab it gives old values changed are not coming in presenting reportplease tell me whats wrong,['mysql'] +309098,email keyboard for edit text the following code does not seem to worki want the email keyboard with and com to get thisplayed for the edit textemailedittextsetinputtypeinputtypetype text variation email addressthanking you in advance for your valuable responses,['android'] +309106,the touchmove event on android system transformer prime i am working on a transformer pad and developing a drawing plate i use phonegapjavascript to write the code instead of java but the touchmove event is quite weird i think as i move my finger on the pad it will continuously to collect the coordinates which i touch on the canvas but it does notit is ridiculous it only collect 1 coordinate the first point on the canvas my finger moves to here are my code about the touch move eventfunction touchstartevent if eventtargettoucheslength 1 var touch eventtargettouches0 if eventtype touchstart line start x touchpagex canvas org x line start y touchpagey canvas org y contextbeginpath contextmovetoline start x line start y if if 1functionfunction touch moveevent line end x eventtouches0pagex canvas org x line end y eventtouches0pagey canvas org y contextlinetoline end x line end y contextstroke test i do not know why each time i move my finger on the pad trying to draw a line curve or anythingi want as the finger moves only a very short segment appears so i declare a variablevar test0 in the beginning of this js file i found that although i move my finger on the pad without leaving it or stopping the value of test remains 1 it means that i move my finger on it but it does notcontinuously to trigger the event touch movewhat can i do now i need a corresponding event to mousemove on touch pad at least the event has to continuously be triggered thank you,"['javascript', 'android']" +309119,how can i stop addmigration checking my database has no pending migrations when using codebased migrations i am investigating using codebased ef migrations for a product that does not use ef everything generally works well except that the commandaddmigration mytestmigrationoutputs the following messageunable to generate an explicit migration because the following explicit migrations are pending 201206260845338 dannytest apply the pending explicit migrations before attempting to generate a new explicit migrationthe reason for this is that the connection string is not known at build time and ef has randomly created a database called mycontextname on sqlexpress i cannot apply the pending migration because it references database tables that do not exist in this database were just trying to use migrations as a way of executing our scriptsso the questions areif were not using automatic migrations we have enableautomaticmigrationsfalse why does addmigration require that the database is uptodate even though it has absolutely no impact on the generated empty migration i find it hard to believe ms do not intend this use case when so much of it works the only broken thing is validation that does not affect any behaviouris there any way around this other than creating our own addmigration command that just duplicates what the ef one does but skips the seemingly needless db uptodate check i have tried passing various arguments but so far not managed to make it workediti actually found a better way to solve this problem but it is not really an answer to these questions so adding it here hopefully will get time to turn this into a blog postthe only reason i wanted to use addmigration was because of all the guff that went along with the dbmigration but i realised that with a base class we could basically eliminate the need for all this by having the base class autogenerate the migration id from an attribute the target is identical for all our migrations as the model state does not change now we just manually create our migrations like this the date is required to build the id such that ef will apply them in the correct ordermigration2012 6 27 12 00 add new x fields for yinternal class mynewmigration mydbmigration public override up public override down the mydbmigration class has the targetsourceid properties target is hardcoded the same value that addmigration created with the first migration source is null and id is some reflection that reads the migrationattribute this means we can now just manually create these classes which is not a lot of effort now we do not have to worry about all the imigrationmetadata stuff,"['c#', '.net']" +309124,how can i detect which layout is selected by android in my application assume i have an activity with three different layouts in different resource folders for examplelayoutlandmy actxmllayoutxlargemy actxmllayoutxlargelandmy actxmlin different devices and different positions one of them is selected by androidhow can i find out which one is selected programmaticallydoes android have any api that returns these layouts to the programedit graham borlands solution has a problem in some situations that i mentioned in the comments,['android'] +309162,hibernate referencedcolumnnames not mapped to a single property i am getting the below exception on my spring 3 web application using hibernate 4 orgspringframeworkbeansfactorybeancreationexception error creating bean with name mysessionfactory defined in url filewarwebinfdatasourceconfigxml invocation of init method failed nested exception is orghibernateannotationexception referencedcolumnnamesthiscussion id of comjrfreedomthiscusionmessagethiscussion referencing comjrfreedomthiscusionthiscussion not mapped to a single property at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactoryinitializebeanabstractautowirecapablebeanfactoryjava1455 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorydocreatebeanabstractautowirecapablebeanfactoryjava519 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorycreatebeanabstractautowirecapablebeanfactoryjava456 at orgspringframeworkbeansfactorysupportabstractbeanfactory1getobjectabstractbeanfactoryjava294 at orgspringframeworkbeansfactorysupportdefaultsingletonbeanregistrygetsingletondefaultsingletonbeanregistryjava225 at orgspringframeworkbeansfactorysupportabstractbeanfactorydogetbeanabstractbeanfactoryjava291 at orgspringframeworkbeansfactorysupportabstractbeanfactorygetbeanabstractbeanfactoryjava193 at orgspringframeworkbeansfactorysupportdefaultlistablebeanfactorypreinstantiatesingletonsdefaultlistablebeanfactoryjava567 at orgspringframeworkcontextsupportabstractapplicationcontextfinishbeanfactoryinitializationabstractapplicationcontextjava913 at orgspringframeworkcontextsupportabstractapplicationcontextrefreshabstractapplicationcontextjava464 at orgspringframeworktestcontextsupportabstractgenericcontextloaderloadcontextabstractgenericcontextloaderjava96 at orgspringframeworktestcontextsupportabstractgenericcontextloaderloadcontextabstractgenericcontextloaderjava44 at orgspringframeworktestcontexttestcontextbuildapplicationcontexttestcontextjava198 at orgspringframeworktestcontexttestcontextgetapplicationcontexttestcontextjava233 at orgspringframeworktestcontextsupportdependencyinjectiontestexecutionlistenerinjectdependenciesdependencyinjectiontestexecutionlistenerjava126 at orgspringframeworktestcontextsupportdependencyinjectiontestexecutionlistenerpreparetestinstancedependencyinjectiontestexecutionlistenerjava85 at orgspringframeworktestcontexttestcontextmanagerpreparetestinstancetestcontextmanagerjava231 at orgspringframeworktestcontextjunit4springjunit4classrunnercreatetestspringjunit4classrunnerjava95 at orgspringframeworktestcontextjunit4springjunit4classrunnerinvoketestmethodspringjunit4classrunnerjava139 at orgjunitinternalrunnersjunit4classrunnerrunmethodsjunit4classrunnerjava51 at orgjunitinternalrunnersjunit4classrunner1runjunit4classrunnerjava44 at orgjunitinternalrunnersclassroadierununprotectedclassroadiejava27 at orgjunitinternalrunnersclassroadierunprotectedclassroadiejava37 at orgjunitinternalrunnersjunit4classrunnerrunjunit4classrunnerjava42 at orgeclipsejdtinternaljunit4runnerjunit4testreferencerunjunit4testreferencejava50 at orgeclipsejdtinternaljunitrunnertestexecutionruntestexecutionjava38 at orgeclipsejdtinternaljunitrunnerremotetestrunnerruntestsremotetestrunnerjava467 at orgeclipsejdtinternaljunitrunnerremotetestrunnerruntestsremotetestrunnerjava683 at orgeclipsejdtinternaljunitrunnerremotetestrunnerrunremotetestrunnerjava390 at orgeclipsejdtinternaljunitrunnerremotetestrunnermainremotetestrunnerjava197caused by orghibernateannotationexception referencedcolumnnamesthiscussion id of comjrfreedomthiscusionmessagethiscussion referencing comjrfreedomthiscusionthiscussion not mapped to a single property at orghibernatecfgbinderhelpercreatesyntheticpropertyreferencebinderhelperjava205 at orghibernatecfgtoonefksecondpassdosecondpasstoonefksecondpassjava116 at orghibernatecfgconfigurationprocessendofqueueconfigurationjava1514 at orghibernatecfgconfigurationprocessfksecondpassinorderconfigurationjava1437 at orghibernatecfgconfigurationsecondpasscompileconfigurationjava1355 at orghibernatecfgconfigurationbuildsessionfactoryconfigurationjava1724 at orghibernatecfgconfigurationbuildsessionfactoryconfigurationjava1775 at orgspringframeworkormhibernate4localsessionfactorybuilderbuildsessionfactorylocalsessionfactorybuilderjava184 at orgspringframeworkormhibernate4localsessionfactorybeanafterpropertiessetlocalsessionfactorybeanjava314 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactoryinvokeinitmethodsabstractautowirecapablebeanfactoryjava1514 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactoryinitializebeanabstractautowirecapablebeanfactoryjava1452 29 morebelow is the message pojo that is using the thiscission pojoentitytablename messagepublic class message id columnname message id private string id columnname message text nullable false private string messagetext foreign key for user table id onetoone joincolumnname from user nullable false private user fromuser foreign key for thiscussion table id manytoone joincolumnname thiscussionreferencedcolumnnamethiscussion id nullable false private thiscussion thiscussion public message id uuidrandomuuidtostring public string getmessagetext return messagetext public void setmessagetextstring messagetext thismessagetext messagetext public user getfromuser return fromuser public void setfromuseruser fromuser thisfromuser fromuser public thiscussion getthiscussionid return thiscussion public void setthiscussionidthiscussion thiscussion thisthiscussion thiscussion public string getid return id here is the thiscussion pojoentitytablename thiscussionpublic class thiscussion id columnname thiscussion id private string id columnname title nullable false private string title columnname catagory nullable false private string catagory id onetoone joincolumnname thiscussionowner nullable false private user thiscussionowner public thiscussion id uuidrandomuuidtostring public string gettitle return title public void settitlestring title thistitle title public string getcatagory return catagory public void setcatagorystring catagory thiscatagory catagory public user getthiscussionowner return thiscussionowner public void setthiscussionowneruser thiscussionowner thisthiscussionowner thiscussionowner public string getid return id what am i missing the relationship between these two entities is that a thiscussion entity can contain many messages and a message can only belong to one thiscussionthanks in advance,['java'] +309189,html5 vs html4 h1 tag rendered with extra space how to remove i took a page whose dtd was html4 transitional and changed the doctype to doctype html and extra space appeared between the h1 and div beneath it i didnt make any other changes to markup or cssjsfiddle example if you change the doctype from html5 to html4 transitional you can see the extra space appear and thisappear even though the markup and css is exactly the sameany idea how to get rid of that space,['css'] +309193,how to delete lots of mongodb collections at once there are a lot of mongodb collections in my database that i need to delete they all have similar names and it would be easy to delete them if only wildcard characters could be used but it does not look like they canis there a way to select a bunch of collections at once to delete them,['javascript'] +309217,what does cvhaardetectobjects method do please can some expert person explain me whether we can use the cvhaardetectobjects method to detect squares and get width and heights i found a code that use this method for facedetection but i need to know whether i can use it for rectangle detection string srcsrcsquiredetectionmyjpg iplimage grabbedimage cvloadimagesrc iplimage grayimage iplimagecreategrabbedimagewidth grabbedimageheight ipl depth 8u 1 cvcvtcolorgrabbedimage grayimage cv bgr2gray cvseq faces cvhaardetectobjectsgrayimage cascade storage 11 3 0 for int i 0 i facestotal i cvrect r new cvrectcvgetseqelemfaces i cvrectanglegrabbedimage cvpointrx ry cvpointrxrwidth ryrheight cvscalarred 1 cv aa 0 hatpoints0x rxrwidth10 hatpoints0y ryrheight10 hatpoints1x rxrwidth10 hatpoints1y ryrheight10 hatpoints2x rxrwidth2 hatpoints2y ryrheight2 cvfillconvexpolygrabbedimage hatpoints hatpointslength cvscalargreen cv aa 0 when i use above method it throws following exception opencv error bad argument invalid classifier cascade in unknown function file cslavewininstallermegapacksrcopencvmodulesobjdetectsrchaarcpp line 1036exception in thread main javalangruntimeexception cslavewininstallermegapacksrcopencvmodulesobjdetectsrchaarcpp1036 error 5 invalid classifier cascade at comgooglecodejavacvcppopencv objdetectcvhaardetectobjectsnative method at comgooglecodejavacvcppopencv objdetectcvhaardetectobjectsopencv objdetectjava243 at squiredetectiontest2maintest2java52 i have put on this lineplease be kind enough to give simple code example for that,['java'] +309220,change parent url from iframe need help with a simple problem which has the following criteria1 click on images link in iframe changes parent page click on another iframe image link changes parent to another page see belowit may sound simple but i am being googled it for days now and looked over many forums code can be in html css or js but please keep any answers simple as possible and post a full working example to work as i am new to coding or recode the test site,['javascript'] +309226,getting a 404 on wdhubsession when i try to connect to selenium grid remotely via python i can see two remotes under the console but when i try to connect remotely and execute something it fails with a 404from selenium import webdriverbrowser webdriverremote command executor desired capabilitiesbrowsername firefoxbrowsergetbrowserquitthrows this exceptiontraceback most recent call last file browsershotpy line 16 in module desired capabilitiesbrowsername firefox file usrlocallibpython26thistpackagesseleniumwebdriverremotewebdriverpy line 62 in init selfstart sessiondesired capabilities browser profile file usrlocallibpython26thistpackagesseleniumwebdriverremotewebdriverpy line 104 in start session desiredcapabilities desired capabilities file usrlocallibpython26thistpackagesseleniumwebdriverremotewebdriverpy line 155 in execute selferror handlercheck responseresponse file usrlocallibpython26thistpackagesseleniumwebdriverremoteerrorhandlerpy line 125 in check response raise exception classvalueseleniumcommonexceptionswebdriverexception message htmlnheadnmeta httpequivcontenttype contenttexthtml charsetiso88591ntitleerror 404 titlenheadnbodyh2http error 404h2prenot foundprenprequesturiwdhubsessionppismalla hrefpowered by jettyasmallipbr nbr nbr nbr nbr nbr nbr nbr nbr nbr nbr nbr nbr nbr nbr nbr nbr nbr nbr nbr nnbodynhtmln,['python'] +309227,correct way to use phonegap jquery mobile with multiple html pages i have an application which uses jquery mobile and consists of a few html pages each with a few jquery page elements within them on a desktop browser it all works fine but when i load it on my android device running 23 the first page looks fine but whenever you click a link lets say from indexhtml loggedinmenuhtml jquery mobile does not seem to kick in and no stylings are applied if i then go back to indexhtml from the current page then indexhtml is left unstyledso is there a correct way to move between separate html pages i do not get any browser errors so everything seems to be working fine but none of the styles or features of jqm are appliedjust so everyone is on the same page the links use dataajaxfalse so they cause a complete page refresh as this is required the app can not work as a single page application so putting everything into one big html file is not an option,['jquery'] +309238,why md5 is required for jce initialization i am experimenting on enabling fips 1803 on my java application fips 1803 allows only usage of 5 secure hashes finalpdf md5 is not one among them hence i am trying to programatically remove md5 algorithms from the sun provider this is the sample codepublic static void mainstring args throws exception securityremoveprovidersun sun sun new sun sunremovemessagedigestmd5 comment and it will work securityaddprovidersun cipher ciph ciphergetinstanceaes but this is throwing the following exception if you comment sunremove the program works fine if i remove md2 instead of md5 then also it works fineto me it looks like the jre libs are using md5 for their signing but i checked jrelibextsunjce providerjar signer and its using sha1any idea why my code is failing with this errorexception in thread main javalangexceptionininitializererror at javaxcryptociphergetinstancedashoa13 at testremovemd5maintestremovemd5java20caused by javalangsecurityexception cannot set up certs for trusted cas at javaxcryptosunjce bdashoa13 3 morecaused by javalangsecurityexception signature classes have been tampered with at javaxcryptosunjce bddashoa13 at javaxcryptosunjce bcdashoa13 at javaxcryptosunjce b1rundashoa13 at javasecurityaccesscontrollerdoprivilegednative method 4 more,['java'] +309289,too few arguments i am trying to get some javascript working in my rails app i want to have my index page allow me to edit individual items on the index page and then reload the index page upon edit my indexhtmlerb page looks likediv idindex render index divin my indexjserb i haveindexhtmlj render index and in my holders controllerdef edit holder holderfindparamsid enddef update holder holderfindparamsid if holderupdate attributesparamsholder formathtml redirect to holders path flashsuccess holder updated line 28 in error formatjs else render edit endendwhen i load the index page it is fine as soon as click the edit button and it submits the form i get the following but if i go back and refresh the index page the edits are saved what am i doing wrong,['ruby-on-rails'] +309305,why does zip drop the values of my generator i was writing an answer to this question when noticed that my simple implementation did not produce correct results while hunting down the bug i noticed the followingin 1 import itertoolsin 2 gen itertoolscycle012in 3 zipgen range3out3 0 0 1 1 2 2in 4 zipgen range3out4 1 0 2 1 0 2for whatever reason gens next method is called one additioinal timeto illustrate this i used the followingclass loudcycleitertoolscycle def nextself and superloudcycle selfnext print n return nin 6 gen loudcycle012in 7 zipgen range30120out7 0 0 1 1 2 2,['python'] +309372,do net design guidelines suggest returning list over ienumerable context i sent an email to my colleagues telling them about enumerableemptyt as a way to return empty collections without doing something like return new listt i got a reply saying that the downside is that it does not expose a specific typethat does present a tiny issue itas always good to be as specific as possible about your return type so if youare returning a list make that your return type thatas because things like lists and arrays have extra methods that are useful plus it also can be useful in making performance considerations when using the collection from the calling methodthe trick below unfortunately forces you to return an ienumerable which is about as nonspecific as possible right this is actually from the net design guidelines stated reasons in the guidelines are the same as iam mentioning here i believethis seemed to be the complete opposite of what i had learned and try as i might i could not find this exact advice in the design guidelines i did find one small piece like thisdo return a subclass of collectiont or readonlyconnectiont from very commonly used methods and propertieswith a code snippet following but no more justification at allso that being said is this a real and accepted guideline the way it was described in the first block quote or has it been misinterpreted all other so questions i could find have answers preferring ienumerablet as the return type maybe the original net guidelines are just outdatedor maybe it is not so clear cut are there some tradeoffs to consider when would it be a good idea to return a more specific type is it ever recommended to return a concrete generic type or only to return a more specific interface like ilistt and readonlycollectiont,['.net'] +309395,sending utf8 values in http headers results in mojibacke i want to send arabic data from servlet using httpservletresponse to clienti am trying thisresponsesetcharacterencodingutf8responsesetheaderinfo arabicwordand i receive the word like thisstring arabicword responsegetheaderinfoin clientreceiving also tried thisbyted responsegetheaderinfogetbytesutf8arabicword new stringdbut seems like there is no unicode because i receive strange english wordsso please how can i send and receive arabic utf8 words,['java'] +309412,spree as multilingualbilingual site is spree suitable for multibilingual ecommerce siteby default it supports internationalization i18n it gives an impression that spree is bilingual friendly but i am missing one piece of the puzzle translation of product names descriptions attributes categorieswhat is your good practice when it comes to translation of products and categories including metadatagem version spree 1,"['ruby-on-rails', 'ruby']" +309425,behavior of line in inline functions i have a macro that passes the line number and file name to an error handlerdefine system failure error code comment system failureerror code comment line file how will the line be resolved when used inside an inlined functionfilehinline int divideint x int y if y 0 system failureenum divide by zero divide by zero error return xywill line contain the line number within the header file or the line number of the source file where the inline function is called assuming compiler does a paste in the source code,"['c++', 'c']" +309430,wrong value in consolelog possible duplicateis chromes javascript console lazy about evaluating arrays i have the following snippets in javascript whose output makes me feel that something is going wrong1a2consolelogaa2consolelogaoutput2 4 as expected2t02consolelogtt02consolelogtoutput 22 22should not the output be 02 22 and whats the difference between the above two cases that results in the different answers in both the cases,['javascript'] +309437,gson expected begin object but was string i am getting a gson error trying to unmarshal json into an object the error expected begin object but was string at line 3 column 22 is pointing to line 3 of the input belowhave i not mapped the json correctly with respect to the beanimport javaxxmlbindjaxbelementpublic class businesspartnercreate protected jaxbelementstring partnertype protected person person protected company company protected string email protected string phone protected addressdata addressdata protected addressclean addressclean protected string city protected string state protected string zipcode protected jaxbelementstring externalidand my input json looks is this businesspartnercreate partnertype 1 person firstname dirk lastname wintermill title email phone 2193852946 addressclean housenumber 10218 streetname park streetabbr rd city somerset state nj zipcode 01955,['java'] +309482,javascript in ten minutes what is going on in this example code illustrating lazy scoping i have been rereading spencer tippings excellent javascript in ten minutes and for the life of me cannot figure out what is going on in this example of using lazy scoping to create syntactic macrosvar f function return 0 1 var g eval ftostring replace dg function digits return arguments digits g56 11 except on iein particular0 and 1 are being replaced by a function definition how does that function get evaluated presumably by eval but i am not seeing thiswhat is the purpose of the single underscore argument in the function if i take it out the code no longer works presumably it is just a place holder but why is it needed,['javascript'] +309528,java making a window clickthrough including textimages i want to create an overlay in java that is transparent always on top and that i can clickthrough i have found some similar posts about this issue but even after following their answers i am having one issuemy problem is making the whole window clickthrough i am not having any problem making it work with a jframe but once i add any components to it jlabel or an imagepanel the clickthrough attribute does not carry over to themas i want to have a background image for my application this basically makes the code i have useless seeing how the window gets focused whenever i click the area the textimage coversbefore i show the code i am using i would first like to refer to these threads which essentially describes precisely what i want except in cmy goal is to create an overlay with a transparent pngimage and some text ontop that will change on key events if it uses jframe or any other library does not matter i only need it compatible with windowsi would also like to mention that i have got some experience with java but am a novice in using jframeimport javaawtborderlayoutimport javaxswingjframeimport javaxswingjlabelimport javaxswingswingconstantsimport comsunjnaplatformwindowutilspublic class overlay public static void mainstring args jframe frame new jframeoverlay window framesetundecoratedtrue framesetalwaysontoptrue framegetrootpaneputclientpropertyappleawtdraggablewindowbackground false framesetlocation400 400 framegetcontentpanesetlayoutnew javaawtborderlayout jlabel textlabel new jlabeli am a label in the window swingconstantscenter framegetcontentpaneaddtextlabel borderlayoutcenter framepack systemsetpropertysunjava2dnoddraw true windowutilssetwindowtransparentframe true windowutilssetwindowalphaframe 10f using awtutilities gives the same result as windowutils awtutilitiessetwindowopaqueframe false awtutilitiessetwindowopacityframe 10f framesetvisibletrue note that the problem is not about the window being focused though that is a result of the issue but about the jlabel and imagepanel not being clickthrough,['java'] +309535,building library with cmake i apologize for bothering you all but i have a little compilation problem with cmakei have a cmakeliststxt file i am using to build a test executable and a shared library they both have dependency to another library sfmli am using cmake on window with mingwi know the name of the lib i am building is kinda confusing with the sfml one but it is supposed to be a sfml wrapper so i did not find a better namehere the cmakeliststxtcmake minimum requiredversion 26projectprojectnamesetexecutable name testsfmlsetlibrary name sfmlwindowsetexecutable output path cmake current source dirbininclude directoriescmake current source dirinclude cmake current source dirincludelink directoriescmake current source dirlibfile glob recurse src files srcfile glob recurse include files includeadd executableexecutable namemaincppsrc filesinclude filestarget link libraries executable name sfmlmain sfmlsystem sfmlwindowadd librarylibrary namesharedsrc filesand what i get in the terminal cmingwbinmingw32makeexe configuring done generating done build files have been written to cusersiksemeldocsworkbenchprogrammingprojetstestsfmlcmakelinking cxx shared library libsfmlwindowdllcreating library file libsfmlwindowdllacmakefilessfmlwindowdirobjectsasfmlwindowcppobjsfmlwindowcpptext0x59undefined reference to imp zn2sf9videomodec1ejcmakefilessfmlwindowdirobjectsasfmlwindowcppobjsfmlwindowcpptext0xda undefined reference to imp zn2sf6windowc1ens 9videomodeerkssjrkns 15contextsettingsecmakefilessfmlwindowdirobjectsasfmlwindowcppobjsfmlwindowcpptext0x163 undefined reference to imp zn2sf6window5closeevcmakefilessfmlwindowdirobjectsasfmlwindowcppobjsfmlwindowcpptext0x1bd undefined reference to imp zn2sf6window9polleventerns 5eventecmakefilessfmlwindowdirobjectsasfmlwindowcppobjsfmlwindowcpptext0x1d8 undefined reference to imp zn2sf6window7thisplayevcollect2 ld a retourna 1 code datat dexacutionmingw32makeexe2 libsfmlwindowdll error 1mingw32makeexe1 cmakefilessfmlwindowdirall error 2mingw32makeexe all error 2if anybody have a clue on whats happening i would be very gratefull,['c++'] +309547,what is the difference between a container and a data structure what is a container as i understand it an abstract data type is merely a logical description of the way the data will be stored and the operations that will be permitted on that data for example a stack is defined as a data type with the operations push pop etc and lifo accessa data structure is the actual implementation of this abstract definition in some computer programming language for example a stack in c is implemented in the standard library as stdstackfirstly please correctenhance my current understanding of the aforementioned thistinctionsecondly what exactly is a container i hear this word thrown around quite often is it the same as my definition of a data structurealso wikipedia has three separate entries for these terms,['c++'] +309581,why does not everything default to utf8 i am just curious that there are modern systems out there that default to something other than utf8 i have had a person block for an entire day on the multiple locations that a mysql system can have different encoding very frustrating is there any good reason not to use utf8 as a default and storage space seems like not a good reason not trying to be argumentitive just curiousthx,"['python', 'mysql', 'ruby']" +309583,backbone call an extended views overridden render function i have a workoutexerciserowview which extends exerciserowview the render functions are extremely similar except the workoutexerciserowview must add a few parameters to exerciserowviews render how can i call exerciserowviews render function inside workoutexerciserowviews render functionvar workoutexerciserowview exerciserowviewextend render function return thisconstructorrender does not work return thisrender does not work workoutexercise thismodel exercise thismodelgetexercise workoutsection thismodelgetsection iseditable true number thisnumber workoutexercise workoutexercise workoutsection workoutsection thanks,['javascript'] +309586,maximum speed from iosipadiphone i done computing intensive app using opencv for ios of course it was slow but it was something like 200 times slower than my pc prototype so i was optimizing it down from very first 15 seconds i was able to get 04 seconds speed i wonder if i found all things and what others may want to share what i didreplaced double data types inside opencv to float double is 64bit and 32bit cpu cannot easily handle them so float gave me some speed opencv uses double very oftenadded mpfuneon to compiler options sideeffect was new problem that emulator compiler does not work anymore and anything can be tested on native hardware onlyreplaced sin and cos implementation with 90 values lookup tables speedup was huge this is somewhat opposite to pc where such optimizations does not give any speedup there was code working in degrees and this value was converted to radians for sin and cos this code was removed too but lookup tables did the jobenabled thumb optimizations some blog posts recommend exactly opposite but this is because thumb makes things usually slower on armv6 armv7 is free of any problems and makes things just faster and smaller to make sure thumb optimizations and mfpuneon work at best and do not introduce crashes i removed armv6 target completely all my code is compiled to armv7 and this is also listed as requirement in app store this means minimum iphone will be 3gs i think it is ok to drop older ones anyway older ones have slower cpus and cpu intensive app provides bad user experience if installed on old deviceof course i use o3 flagi deleted dead code from opencv often when optimizing opencv i see code which is clearly not needed for my project for example often there is a extra if to check for pixel size being 8 bit or 32 bit and i know that i need 8bit only this removes some code provides optimizer better chance to remove something more or replace with constants also code fits better into cacheany other tricks and ideas for me enabling thumb and replacing trigonometry with lookups were boost makers and made me surprise maybe you know something more to do which makes apps fly,"['iphone', 'ios']" +309592,problems with scrollbar in ie9 position fixed overflow auto i have encountered a strange issue with the vertical scroll bar on ie9 when using a div with a fixed position and overflow auto set on the divsee the case here using ie9 and shrink the window height down to a small size div testhtmli can confirm that this does not occur on ie8 does anyone know a reasonable hack around this i have tried setting the width to the window width but it seems that it purposesfully subtracts a scrollbar width from the size of the div i would like to see if there is a solution that does not have to calculate this constant or hardcode it and adding this back to the calculated widthcheersedit jsfiddle does not seem to exhibit the problem so that can be a big hint as to what might be going on,['html'] +309595,rendering an action with notice that depends on a url param i have an action approval that renders a view which thisplays some content from a model class within the view i have a link to that calls accept with a url parameter id after the accept action completes sets approve to true i would like to render approval again with a message saved however unlike a static login page the approval action requires a param the first time it is called the second time it is rendered an runtime error occurs obviously what is the best way to call approval with the flash noticedef approval c classfindparamsidenddef accept c classfindparamsid capprove true csave render approval notice savedend,['ruby-on-rails'] +309621,how do i profile a mexfunction in matlab i have a mexfunction a function in c that you can call from matlab that i have written and i want to profile it using valgrindkcachegrind i know how to use valgrindkcachegrind if you are running a c program directly but is there a way to do this profiling if i am calling the c program from matlab,['c++'] +309639,unable to call bootstrap modal window using javascript in chrome works in firefox i have included the sample code from twitterbootstrap for a modal window if i click on the button it opens up the modal window however if i try to show the modal window through javascript i get the following error mymodalmodalshowtypeerror object object object has no method modalthis error is only coming in chrome and works in firefox below is the html projectaddmodal is the id of the modal box navigate to project add to see the modal button html class js flexbox canvas canvastext nowebgl notouch geolocation postmessage websqldatabase indexeddb hashchange history draganddrop websockets rgba hsla multiplebgs backgroundsize borderimage borderradius boxshadow textshadow opacity cssanimations csscolumns cssgradients cssreflections csstransforms nocsstransforms3d csstransitions fontface generatedcontent video audio localstorage sessionstorage webworkers applicationcache svg inlinesvg smil svgclippaths langenendifhead meta charsetutf8 meta httpequivxuacompatible contentieedgechrome1 titleproject managementtitle meta namedescription content meta nameauthor content meta nameviewport contentwidthdevicewidth link relstylesheet hrefcstylecss link relstylesheet hrefcssbootstrapmincss link relstylesheet hrefcssbootstrapresponsivemincss link relstylesheet hrefcssdocscss script srcwgoogleanalyticscomgajsscriptscript srcjslibsmodernizr253minjsscriptheadbody classdiv idheaderdiv idtopnavbar div classnavbar navbarfixedtop div classnavbarinner div classcontainer a classbtn btnnavbar datatogglecollapse datatargetnavcollapse span classiconbarspan span classiconbarspan span classiconbarspan a div classnavcollapse ul datanavlinksleft classnav li classdropdown a href classdropdowntoggle datatoggledropdownprojectsb classcaretba ul classdropdownmenu lia href idaddnewproject bindclick pmclienttemplatinghello add ali ul li li classdropdown a href classdropdowntoggle datatoggledropdownadminb classcaretba ul classdropdownmenu lia hrefinvite usersali ul li ul ul classnav pullright li classdropdown a href classdropdowntoggle datatoggledropdownusernameb classcaretba ul classdropdownmenu lia hreflogoutali ul li ul div navcollapse div div navbarinner div divdivdiv classcontainer cljsmaindiv idprojectaddsectiona classbtn datatogglemodal hrefprojectaddmodallaunch modala div classmodal hide fade idprojectaddmodal stylethisplay none div classmodalheader button typebutton classclose datathismissmodalabutton h3add new projecth3 div div classmodalbody form classformhorizontal fieldset div classcontrolgroup label classcontrollabel forinput01project namelabel div classcontrols input typetext classinputxlarge idprojectname div div div classcontrolgroup label classcontrollabel fortextareaproject descriptionlabel div classcontrols textarea classinputxlarge idprojectdesc rows3textarea div div label classcontrollabelinvite people to collaborate on your projectlabel div classcontrolgroup label classcontrollabel forprependedinputlabel div classcontrols div classinputprepend span classaddonspaninput claspan2 idprependedinput size16 typetext div p classhelpblockheres some help textp div div fieldset formdiv div classmodalfooter a href classbtn datathismissmodalclosea a href classbtn btnprimarysave changesa div div divdivfooterfooterscript srcajaxgoogleapiscomajaxlibsjquery172jqueryminjsscriptscriptwindowjquery documentwritescript srcjslibsjquery172minjsscriptscript scripts concatenated and minified via ant build scriptscript srcjsbootstrapminjsscriptscript srcjspluginsjsscriptscript srcjsscriptjsscriptscript srccljsclientjsscriptscript typetextjavascript srcdepsjsscriptscriptfunction cljsbindingbootscript end scriptsscript var gaq setaccountuax trackpageview functiondtvar gdcreateelementtsdgetelementsbytagnamet0 gsrchttpslocationprotocolsslwgoogleanalyticscomgajs sparentnodeinsertbeforegsdocumentscriptscriptiframe namexpcpeer7x7y idxpcpeer7x7y stylethisplay none srchttplocalhost90replxpc7b22cn223a22pmcincjdvc2c22tp223anull7diframebodyhtmlthanksmurtaza,['jquery'] +309647,the method showdialogint from the type activity is deprecated in android the method showdialogint from the type activity is deprecatedwhats the reason and how to solve it,['android'] +309670,c implicit conversion from base class i have a collection class like thispublic class somedatacollection listisomedata some method but i cannot do thissomedatacollection somedatas new listisomedatacannot implicitly convert type listisomedata to somedatacollection an explicit conversion exists are you missing a castso i try to create an implicit coverter inside somedatacollection collection classpublic static implicit operator somedatacollectionlistisomedata l var somedatas new somedatacollection somedatasaddrangel return somedatasbut it said that i cannot create such convertersomedatacollectionimplicit operator somedatacollectionlistisomedata userdefined conversions to or from a base class are not allowedand when i cast it like thissomedatacollection somedatas somedatacollectionnew listisomedatait throws an error that saidsysteminvalidcastexception unable to cast object of type listisomedata to type somedatacollectionhow can i do thissomedatacollection somedatas new listisomedatawithout getting an error please help thanks in advance,['c#'] +309671,c calling overloaded operator from object pointer consider the followingclass mydummy something beforepublic int toperator int a int b something afterconsider to have an implementation of the prototype defined before and consider that you havemydummy m new mydummyi want to access the operator so i couldm12but can i do thism12thankyou,['c++'] +309691,cboost mpl structure code likewise haskells let where as c metaprogramming is functional is there any way of doing something comparable to any functional programming languages eg haskells let or where constructi am using boostmpl but would like to have more structure for longer metafunctions splitting into several functions is fine but i would prefer letwhere in some cases,['c++'] +309693,python variable reference assignment in the codey 7x y x 8now y will be 7 and x will be 8 but actually i wanna change y can i assign the reference of y and do that for example in c the same thing can be achieved asint y 8int x yx 9now both y x will be 9,['python'] +309697,rich domain model with behaviours and orm after watching ndc12 presentation crafting wicked domain models from jimmy bogard i was wandering how to persist that kind of domain modelthis is sample class from presentationpublic class member listoffer offers public memberstring firstname string lastname firstname firstname lastname lastname offers new listoffer public string firstname get set public string lastname get set public ienumerableoffer assignedoffers get return offers public int numberofoffers get private set public offer assignofferoffertype offertype ioffervaluecalc valuecalc var value valuecalccalculatevaluethis offertype var expiration offertypecalculateexpiration var offer new offerthis offertype expiration value offersaddoffer numberofoffers return offer so there are some rules contained in this domain model member must have first and last name number of offers cannot be changed outside member is responsible for creating new offer calculating its value and assignment if if try to map this to some orm like entity framework or nhibernate it will not workso whats best approach for mapping this kind of model to database with ormfor example how do i load assignedoffers from db if there is no setter only thing that does make sense for me is using commandquery architecture queries are always done with dto as result not domain entities and commands are done on domain models also event sourcing is perfect fit for behaviours on domain model but this kind of cqs architecture is not maybe suitable for every project specially brownfield or noti am aware of similar questions here but could not find concrete example and solution,"['c#', '.net']" +309747,spinlock throwing synchronizationlockexception i am trying to use spinlock but even this most basic code in a single threaded console app throws the following exception when i callspinlockexitsystemthreadingsynchronizationlockexception was unhandled by user code messagethe calling thread does not hold the lock sourcemscorlibhere is the entire source codeusing systemusing systemcollectionsgenericusing systemlinqusing systemtextusing systemthreadingnamespace consoleapplication48 class program static readonly spinlock spinlock new spinlock static void mainstring args bool locktaken false try spinlockenterref locktaken if locktaken consolewritelinelock taken finally if locktaken spinlockexit consolewritelinedone,['.net'] +309754,test redirection with rspec and capybara rails i just have learnt how cool rspec and cabybara is and now working around it to learn writing actual testi am trying to check if after clicking a link there is a redirection to a specific pagebelow is the scenario1 i have a page projectslist i have an anchor with html back and it links to projectsshowbelow is the test i wrote in rspecdescribe sample do describe get projectslist do it sample test do visit projectslist click link back assert redirected to projectsshow end endendthe test fails with a failure message like below failureerror assert redirected to projectsshow argumenterror request must be an actionthispatchrequestplease suggest me on how i should test the redirection and what am i doing wrong,['ruby-on-rails'] +309851,drop trailing zeros from decimal i have a long list of decimals and that i have to adjust by factors of 10 100 10 10 depending on certain conditions when i multiply them there is sometimes a useless trailing zero though not always that i want to get rid of for examplefrom decimal import decimal outputs 250 problem i would like it to output 25print decimal25 10 outputs 256780 problem i would like it to output 25678print decimal25678 10is there a function that tells the decimal object to drop these insignificant zeros the only way i can think of doing this is to convert to a string and replace them using regular expressionsshould probably mention that i am using python 265editsenderles fine answer made me realize that i occasionally get a number like 2500 which when normalized produces 25e2 i guess in these cases i could try to sort them out and convert to a int,['python'] +309859,store an ordering of enums in java in java an enumset stores the items it contains in a bitmask bit vector using a long regularenumset or long jumboenumset i have now come across a use case where i have many thousand domain objects let us call them node each of which will show all items of an enum let us call that flag in an order that will vary per objectcurrently i am storing the order as guava immutableset because that guarantees to retain insertion order however i have used the methods explained on this page to compare memory usage in an enumsetflag an immutablesetflag and a flag here are the results when a flag has 64 enum items and b all three variants contain all 64 itemsenumset 32 bytes immutableset 832 bytes array 272 bytesso my question is is there a clever way to pack the enum ordering into a numeric value to get a memory footprint smaller than that of the array if it makes a difference in my use case i would assume that the ordering always contains all enum itemsto clarify my enum is much smaller than that and i do not have any memory problems as of now nor is it likely that this situation will ever give me memory problems it is just that this inefficiency bugs me even on this microscopic levelupdateafter suggestions from the various answers and comments i came up with this data structure that uses a byte array caveat it does not implement the set interface does not check for unique values and it would not scale to large enums beyond what a byte can hold also the complexity is pretty awful because enumvalues has to be queried repeatedly see here for a thiscussion of this problem but here goespublic class enumorderinge extends enume implements iterablee private final classe type private final byte order public enumorderingfinal classe type final collectione order thistype type thisorder new byteordersize int offset 0 for final e item order thisorderoffset byte itemordinal override public iteratore iterator return new abstractiteratore private int offset 1 private final e enumconstants typegetenumconstants override protected e computenext if offset orderlength 1 return enumconstantsorderoffset return endofdata the memory footprint isenumordering104that is a pretty good result so far thanks to bests and jb nizetupdate i have changed the code to only implement iterable because anything else would require sensible implementations for equals hashcode contains etc,['java'] +309883,how to get the position of element transformed with css rotate i am having a problem with getting the position of a div after rotate filter is applied to it i have the position of one end its height and the angle by which it is rotated but after checking what this filter actually does on mdn cosangle sinangle sinangle cosangle 0 0 i still do not know how to crack itexample the div i am interested in is the dashed line its styling at that moment was left 80px top 12px height 695122px width 2px moztransform rotate121366radtopleft describe the position of its beginning i am trying to get the topleft position of its end,"['javascript', 'css']" +309924,rails routes based on condition i have three roles instuctor student admin and each have controllers with a home viewso this works fineget instructorhome to instructorhomeget studenthome to studenthomeget adminhome to adminhomei want to write a vanity url like below which will route based on the role of the user id to the correct home pageget user idhome to instructorhome or studenthome or adminhomehow do i accomplish this,['ruby-on-rails'] +310004,logging to two files with different settings i am already using a basic logging config where all messages across all modules are stored in a single file however i need a more complex solution nowtwo files the first remains the samethe second file should have some custom formati have been reading the docs for the module bu they are very complex for me at the moment loggers handlers so in shorthow to log to two files in python 3 ieimport logging loggingfile1infowrite this to file 1loggingfile2infowrite this to file 2,['python'] +310006,how can i use jquery validation with the chosen plugin i have some select inputs using the chosen plugin that i want to validate as required on the client side since chosen hides the actual select element and creates a widget with divs and spans native html5 validation does not seem to work properly the form would not submit which is good but the error message is not shown so the user has no idea whats wrong which is not goodi have turned to the jquery validation plugin which i planned on using eventually anyways but have not had any luck so far heres my test caseform labelname input nametest1 requiredlabel labelfavorite color select nametest2 required option valueoption option valueredredoption option valueblueblueoption option valuegreengreenoption select label input typesubmitformdocumentreadyfunction selectchosen formvalidatethis is letting the select through with an empty value without validating or showing the error message when i comment out the chosen line it works finehow can i validate chosen inputs with the jquery validation plugin and show the error message for invalid ones,['jquery'] +310030,how do i detect a max recursion depth exceeded exception in python try recursive functionexcept runtimeerror e is this a max recursion depth exceeded exceptionhow do i tell when the maximum recursion depth has been reached,['python'] +310047,update has no effect on scores prediction api i am experimenting with the language idtxt dataset from the google prediction example right now i am trying to update the model with the following methoddef updatelabel data input predictiontrainedmodelsupdaterequest schemanew inputlabel label inputcsv instance data result clientexecute api method predictiontrainedmodelsupdate parameters id model id headers contenttype applicationjson body object input assemble json bodyresultendthis method is based on some google sample codemy problem is that these updates have no effect here are the scores for this is a test sentence regardless of how many updates i run response kindpredictionoutput idmymodel selflink outputlabelenglish outputmulti labelenglish score0420937 labelfrench score0273789 labelspanish score0305274 statussuccessper the thisclaimer at the bottom of creating a sentiment analysis model i have made sure to update at least 100 times before expecting any changes first i tried using a single sentence and updating with it 10 times second i tried using 150 unique sentences drawn from simple wikipedia and updated with each once each update was successfulresponsekindpredictiontrainingidmymodelselflinkstatussuccessbut neither approach changed my resultsi have also tried using the apis explorer prediction v15 and updating 300 times that way there is still no difference in my results those updates were also successful200 okkind predictiontrainingid mymodelselflink i am quite sure that the model is receiving these updates get and analyze both show that the model has numberinstances 2024 oddly though list shows that the model has numberinstances 406at this point i do not know what could be causing this issue,['ruby'] +310074,nsset how to extract object randomly i am not sure about how nssets anyobject work what does it mean that the object returned is chosen at the setas convenience from the nsset class reference further how can i best extract objects randomly from a nsset i was thinking about getting allobjects in an array and then myarrayarc4random uniformx where x is the number of objects in the array,"['iphone', 'objective-c', 'ios']" +310083,changing css class in knockoutjs on mouse click the knockoutjs documentation shows the css binding like thisdiv databindcss profitwarning currentprofit 0 profit informationdivi need to adapt it to change the css class on mouseclick how can i do thisbased on answers below i am using some code like this css class to be appliedstyle bigclass width 200px style select list inside a jquery tmplscript idcriteriarowtemplate typetexthtml tr td select databindclick makebig css bigclass selecthasfocus 0 td trscript knockoutjs viewmodelvar criterialine function thissearchcriterion koobservable thisselecthasfocus koobservable0 this method is called makebig functionelement thisselecthasfocus1 however this is not expanding the width of the select list what am i doing wrong,"['javascript', 'jquery', 'css']" +310091,android emulator does not take keyboard input sdk tools rev 20 i have upgraded the sdk tools to revision 20 from 18 and since the upgrade the emulator does not seem to accept input from laptops keyboard but only using the emulators own soft keyboard that appears when an input field is focusedi have tried reinstalling the sdk tools and the whole sdk for that matter uninstalled and reinstalled eclipse android plugins recreated emulator devices but none of that seem to help and its driving me mad its hopeless to keyin using a laptops trackpadhas anyone encountered this problem,['android'] +310103,custom ios uilocalnotification sound does not play possibly related to xcode update i am trying to get a custom sound working on a uilocalnotification and i am just getting no sound at all if i use uilocalnotificationdefaultsoundname i indeed get the default sound but when the custom sound is specified there is no sound just the message the sound is less than 30 seconds and it is in the right format as far as i can tell heres a screenshot of the file infoi have inspected the app directory in xcodes deriveddata directory and the alarmcaf file is at the root of the app which i believe means it is in the bundle righti am pretty sure this was working a while ago and i have since upgraded xcode maybe that is a hinti have also tried deletingreinstallingrebooting as mentioned in other answers as you can see i am calling cancelalocalnotifications firstdoes anyone have any idea what could be wronguiapplication sharedapplication cancelalocalnotificationsnsloginstalling alarmarguments pop namearguments pop titlealarmalertbody arguments popalarmfiredate nsdate date addtimeintervalarguments pop intvalue10alarmsoundname uilocalnotificationdefaultsoundnamealarmsoundname alarmcafuiapplication sharedapplication schedulelocalnotificationalarm,"['objective-c', 'ios']" +310107,setuppy not installing data files i have a python library that in addition to regular python modules has some data files that need to go in usrlocallibpython27thistpackagemylibraryunfortunately i have been unable to convince setuppy to actually install the data files there note that this behaviour is under install not sthisthere is a slightly redacted version of setuppymodule list list of filessetupname modules version 1337 description my sweet module author pn author email email url url packages my module i tried this it got installed in usrmy module not ok data files my module my moduledata1 my moduledata2 this does not install it at all package data my module my moduledata1 my moduledata2 this is in python 27 will have to run in 26 eventually and will have to run on some ubuntu between 1004 and 12 developing it right now on 1204,['python'] +310114,can ruby threads not collide on a write from past work in c and java i am accustomed to a statement such as this not being threadsafex yhowever i have not been able to observe any collision among threads when running the above code in parallel with rubyi have read that ruby automatically prevents multiple threads from writing to the same data concurrently is this true is the operator therefore threadsafe in ruby,['ruby'] +310119,nginx php5fpm failed 2 no such file or directory question what am i missing or doing wrongi am trying to migrate fully functional zend framework application from apache2 with mod php5 to nginx with php5fpm i get this kind of errors20120627 120804 error 19860 1 open varwpublicsaleslivetrialsjson failed 2 no such file or directory client server wmydomaincom request post saleslivetrialsjson http11 host wmydomaincom referrer here are my configuration filesa etcnginxsitesenabledwserver listen 80 listen 443 default ssl server name wmydomaincom root varwpublic ssl certificate etcnginxsslmydomaincrt ssl certificate key etcnginxsslmydomainkey access log varlognginxaccesslog error log varlognginxerrorlog error index indexphp indexphtml indexhtml location faviconicorobotstxt access log off log not found off location cssjsjpegjpggifpngicoxml access log off expires 30d location try files uri uri indexphp location ht deny all location php fastcgi pass 12700190 fastcgi split path info php fastcgi intercept errors on include etcnginxfastcgi params b etcnginxfastcgi paramsfastcgi param query string query stringfastcgi param request method request methodfastcgi param content type content typefastcgi param content length content lengthfastcgi param script filename request filenamefastcgi param script name fastcgi script namefastcgi param request uri request urifastcgi param document uri document urifastcgi param document root document rootfastcgi param server protocol server protocolfastcgi param gateway interface cgi11fastcgi param server software nginxnginx versionfastcgi param remote addr remote addrfastcgi param remote port remote portfastcgi param server addr server addrfastcgi param server port server portfastcgi param server name server namefastcgi param https https php only required if php was built with enableforcecgiredirectfastcgi param redirect status 200c etcphp5fpmpooldwconfwuser wdatagroup wdatalisten 12700190pm dynamicpmmax children 20pmstart servers 4pmmin spare servers 2pmmax spare servers 6chdir d ls al varwdrwxrxrx 7 wdata wdata 4096 jun 27 1052 applicationdrwxrxrx 5 wdata wdata 4096 jun 27 1052 librarydrwxrxrx 10 wdata wdata 4096 jun 27 1205 publice nginx vnginx version nginx19tls sni support enabledconfigure arguments prefixetcnginx confpathetcnginxnginxconf errorlogpathvarlognginxerrorlog httpclientbodytemppathvarlibnginxbody httpfastcgitemppathvarlibnginxfastcgi httplogpathvarlognginxaccesslog httpproxytemppathvarlibnginxproxy httpscgitemppathvarlibnginxscgi httpuwsgitemppathvarlibnginxuwsgi lockpathvarlocknginxlock pidpathvarrunnginxpid withdebug withhttp addition module withhttp dav module withhttp geoip module withhttp gzip static module withhttp image filter module withhttp realip module withhttp stub status module withhttp ssl module withhttp sub module withhttp xslt module withipv6 withsha1usrincludeopenssl withmd5usrincludeopenssl withmail withmail ssl module addmodulebuildbuilddnginx19debianmodulesnginxauthpam addmodulebuildbuilddnginx19debianmodulesnginxecho addmodulebuildbuilddnginx19debianmodulesnginxupstreamfair addmodulebuildbuilddnginx19debianmodulesnginxdavextmodulef php v this is cli version but i swear i am running nginx with fpmphp 53101ubuntu3 with suhosinpatch cli built apr 11 2012 172533 copyright c 19972012 the php groupzend engine v230 copyright c 19982012 zend technologies,['php'] +310128,can apple push notifications send more parameters than alert and sound i have several pieces of metadata that i need to associate with a push notificationfor example user no message idcan i send more parameters than what apple supports aps alert joetheman sound defaultis this possible,['ios'] +310133,actionbarsherlock viewpager caching more then just prevnext view on the pageoncreate called for two tabs each time one tab is selectedthere is explained how the absactually viewpager is working in order for viewpager to be able to do a scrolling it is clear that at least a prevnext page need all to be created at the same timewould it be possible to cache more than just prevnext viewsfragments in a wayi am on page 1 and there i have a network call to fetch some datadoing this in activity not in fragment btw is this okswitch to page 2 and thenswitch to page 3 and thenswitch to page 1 here my page is recreated using some caching though but i do not need any recreation if possibleso it would be nice to cache all the pages how to accomplish this if possible in current version 4 or this would be some new featureor even better question how to postpondthisable destroying of views,['android'] +310138,what is the equivalent of javascripts settimeout on qtscript not much to add what is the equivalent of javascripts settimeout on qtscript,['javascript'] +310146,multiple databases or many many tables i have done some research on this question both via google and on here but have not found anything i felt matched my situation so am askingi have a project that currently has a one account one environment model and is looking to expand to one account many environments the environments will be identical at least as far as table structure is concerned and will require around 100 tables i am torn between two possible approachesuse a single database with table prefixing to separate each environment and an unprefixed account tableuse many databases a central account database and a separate one for each environment the central one will likely have other central onceonly data such as tables for our forum softwareare there any significant performance gainsconcerns with either approach the data will at least for now all reside on the same physical server queries should only ever need to access a single environment except in very rare circumstances and of course the main accounts record,['mysql'] +310147,why does not rsdebug work i have inserted an rsdebug method in the android renderscript sample fountain but i am getting no messages out of logcatheres a code snippet to demonstrate what i have triedint root float dt minrsgetdt 01f rsdebugdt dt,['android'] +310162,finding the index value of the smallest number in a list say i have a list of numbers 20 15 27 30 how would i return the index number of the smallest value in this list 15 obviously minlst will return the smallest number itself but how do i instead return it is index 1,['python'] +310169,first drop down menu to auto change the options of a second dropdown i have two drop down menus where the options are not get from the databasethe first one lets the user to select a categoryselect namecategory option value0noneoption option value1firstoption option value2secondoption option value3thirdoption option value4fourthoptionselectthe options of the second are depended from the choice in the first dropdown menu for example if the user chooses the first option then the second dropdown will showselect nameitems option value3smartphoneoption option value8chargeroptionselectbut when the user change his mind or select the second option first then the second dropdown will now show select nameitems option value1basketballoption option value4volleyballoptionselectmy question is how can i achieve this can this be done without using a database thank you,"['php', 'javascript', 'jquery', 'html']" +310222,how can i clear the jquery dom cache how can i clear the jquery dom cache i am still in the middle of developing and testing a jquery mobile application and i keep seeing old versions of my code pop up and try to be executed maybe it is because i used datadomcachetrue in some places i have restarted my web server but that does not fix it any ideas,['jquery'] +310230,aspnet webapi selfhost service fails on http url registration i am trying to host an aspnet webapi endpoint on an azure worker role using the new microsoftaspnetwebapiselfhost nuget package my workers run code looks roughly like this endpoint is defined as in servicedefinitioncsdef as http external port 8080 internal port 8080 or 8081 error both waysroleinstanceendpoint externalendpoint roleenvironmentcurrentroleinstanceinstanceendpointsendpoint string baseaddress stringformathttp0 externalendpointipendpointvar maxsize 1024 1024 var config new httpselfhostconfigurationbaseaddress maxbuffersize maxsize maxreceivedmessagesize maxsize configroutesmaphttproute name defaultapi routetemplate apicontrollerid defaults new id routeparameteroptional create and open the servervar server new httpselfhostserverconfigserveropenasyncwait keep the worker thread alivewhile true threadsleeptimeoutthis works fine in the dev fabric but when deploying to azure i get an aggregateexception from the serveropenasync call containing the following exception stack0 one or more errors occurred1 http could not register url http8081 your process does not have access rights to this namespace see for details2 access is deniedi am just running a vanilla worker role and this seems to be the hello world of selfhost the endpoint part of my servicedefinitioncsdef looks like thisendpoints inputendpoint nameendpoint protocolhttp port8080 localport8081 endpointsthe baseaddress that i get from the roleenvironment instanceendpoint looks legit xy8081i see the failure whether i use the same portlocalport 8080 or when i do a mapping like the aboveit is clear that it is possible to host a conventional wcf service in a worker role in this way is there any reason why aspnet webapi selfhost wouldnt work in this configuration,['c#'] +310286,regex for checking if a string is strictly alphanumeric how can i check if a string contains only numbers and alphabets ie is alphanumeric,['java'] +310290,how to pipe inputstream to processbuilder please move down to the 2nd update i did not want to change the previous context of this questioni am using wkhtmltoimage from a java appthe standard way of using it is pathtoexe imagepngaccording to their docs if we write a instead of an input url the input shifts to stdini am starting the process using processbuilder processbuilder pb new processbuilderexe path image save pathprocess process pbstartnow i am unable to figure out how to pipe an input stream to this processi have a template file read into a datainputstream and i am appending a string at the enddatainputstream this new datainputstream new fileinputstream currentdirectorybintemplatetxtbyte datainbytes new bytethisavailable thisreadfullydatainbytes thisclose string content new stringdatainbytes 0 datainbyteslength content bodydiv idchartcontainersmaloading chartsmalldivbodyhtmlhow do i pipe content to the stdin of the processupdatefollowing the answer by andrzej doylei have used the getoutputstream of the processprocessbuilder pb new processbuilderfull path image save path pbredirecterrorstreamtrue process process pbstart systemoutprintlnreading bufferedwriter bw new bufferedwriternew outputstreamwriterprocessgetoutputstream bwwritecontentdoing so gives an error sayingexception in thread main javaioioexception the pipe has been ended2nd updatethe current code block is as such try processbuilder pb new processbuilderfull path cropw width croph height image save path systemoutprintfull path cropw width croph height currentdirectorytemphtml image save path pbredirecterrorstreamtrue process process pbstart processwaitfor outputstream stdin processgetoutputstream bufferedwriter writer new bufferedwriternew outputstreamwriterstdin content is the string that i want to write to the process writerwritecontent writernewline writerflush writerclose catch exception e systemoutprintlnexception e eprintstacktrace running the above code gives me an ioexception the pipe is being closedwhat else do i need to do to keep the pipe open,['java'] +310308,can i wrap around a collection of elements in an array let us say i have a collection of items like sop classitemitem 1pp classitemitem 2pp classitem groupitem 3pp classitem groupitem 4pp classitemitem 5pi want to loop through the items and wrap a containing div around any that have the group class to result in something like this grouped items will always be right next to one anotherp classitemitem 1pp classcommentitem 2pdiv classwrapper p classitem groupitem 3p p classitem groupitem 4pdivp classitemitem 5pthis is the script i have gotvar group itemeachfunctioni item if itemhasclassgroup grouppushitem groupwrapdiv classwrapper what happens is that the wrapping div is wrapped around each element separately in the array which makes sense but i need it to wrap all elements together is there any way i can do this heres a jsfiddleeditthere is a more complex variation of this problem that is possible this would be a situation where there are several sets of these groups each to be wrapped in their own group div initial statep classitemitem 1pp classitemitem 2pp classitem groupitem 3pp classitem groupitem 4pp classitemitem 5pp classitem groupitem 6pp classitem groupitem 7pp classitem groupitem 8pp classitemitem 9pdesired statep classitemitem 1pp classitemitem 2pdiv classwrapper p classitem groupitem 3p p classitem groupitem 4pdivp classitemitem 5pdiv classwrapper p classitem groupitem 6p p classitem groupitem 7p p classitem groupitem 8pdivp classitemitem 9psorry i did not mention that before thanks,"['javascript', 'jquery']" +310316,usb device attached only startsactivity of galaxy s3 ics recently i have been trying to receive the intent androidhardwareusbactionusb device attached using a broadcast receiver as per all the samples and examples that i have seen i have declared a reciever in the manifestreceiver androidnameusbdevicereceiver intentfilter action androidnameandroidhardwareusbactionusb device attached action androidnameandroidhardwareusbactionusb device detached category androidnameandroidintentcategorydefault intentfilter receiver metadata androidnameandroidhardwareusbactionusb device attached androidresourcexmldevice filteri have also done similar in the activity code onstart and onstop registerunregister the receiver intentfilter filter new intentfilter filteraddactionusbmanageraction usb device attached registerreceivermusbreceiver filterhowever i am finding that the intent is just caught observing logcat i can see that attaching a usb device looks for activities to start while detaching broadcasts the detatch intent according to the aforementioned samples this should not be the caseam i missing something drastic concerning metadata i have no problems at all with androidhardwareusbactionusb device detached perhaps this is a bug with the android version installed on the galaxy s3 perhaps this is an ics featureany relavent information is welcome,['android'] +310367,adding two numbers without using i have this code which does the trickinclude stdiohint main int a 30 b 20sum char p pchar a sum intpb adding a b printfdsum return 0can someone please explain what is happening in the codep charasum intpb adding a b,['c'] +310385,how to handle no data in jqplot is there a best approach to handle no data with jqplotassuming that i am consuming json data with an ajax call and eventually no data is available egnorth0south0east0west0,['jquery'] +310399,items inside gridview getting repeated when screen scrolls i am using a gridview to show a set of categories that user can chose each item of the grid is consisted by an imageview and a textview both retrieved from server when an item is touched another activity is startedi thought everything was going right until i have noticed that some itens were getting repeated when i scrolls the screen whenever i scroll down trough the grid and then back itens change ita position and get duplicated but even when i touch the messed up itens the right values are send to the next activity looking in logcat any repeated request to server occurs in fact i have got this while scrolling0628 123638554 ddalvikvm358 gc external alloc freed 2061 objects 156024 bytes in 51ms0628 123642915 ddalvikvm358 gc for malloc freed 6590 objects 737528 bytes in 57ms0628 123826725 ddalvikvm358 gc external alloc freed 5426 objects 468176 bytes in 71ms0628 123826875 ddalvikvm358 gc external alloc freed 409 objects 17480 bytes in 68mslooks like everytime i scroll itens get redrawupdate it only redraw itens on the first time i scroll down the gridview after this all itens including repeated ones keeps on its placesmy java classpublic void proccess int qtdcategorias jsonlength imagens new drawableqtdcategorias categorias new stringqtdcategorias for int i0 iqtdcategorias i jsonarray c jsonoptjsonarrayi string urlamigavel null string imagemsite null string nomecategoria null try urlamigavel cgetstring6 imagemsite cgetstring3 nomecategoria cgetstring2 catch jsonexception e logecategoriasjogaractivity etostring eprintstacktrace categoriasi nomecategoria imagensi getimagemurlamigavel imagemsite gridview gridview findviewbyidridinclude3 imageadapter imageadapter new imageadapterctx imagens categorias gridviewsetadapterimageadapter gridviewsetonitemclicklistenernew onitemclicklistener public void onitemclickadapterview parent view v int position long id string name null string idt null try jsonarray c jsonoptjsonarrayposition name cgetstring2 idt cgetstring0 catch jsonexception e logecategoriasjogaractivity jsonexception etostring intent in new intentgetapplicationcontext jogaractivityclass inputextratag name name inputextratag id idt inputextratag primeirapergunta true startactivityin public drawable getimagemstring urlamigavel string img string url urlamigavel img inputstream is null try url urlimagem new urlurl is inputstream getobjetourlimagem catch malformedurlexception e1 logecategoriasjogaractivity e1tostring e1printstacktrace drawable d drawablecreatefromstreamis src return dprivate object getobjetourl url object content null try content urlgetcontent catch ioexception e logecategoriasjogaractivity etostring eprintstacktrace return contentimageadapter classpublic class imageadapter extends baseadapterprivate context mcontextprivate final drawable mthumbidsprivate final string mtextidspublic imageadaptercontext c drawable d string s mcontext c mthumbids d mtextids spublic int getcount return mthumbidslengthpublic object getitemint position return nullpublic long getitemidint position return 0create a new imageview for each item referenced by the adapterpublic view getviewint position view convertview viewgroup parent imageview imageview view v if convertview null if it is not recycled initialize some attributes layoutinflater inflater layoutinflater mcontextgetsystemservice contextlayout inflater service v inflaterinflaterlayoutgridview item layout null textview text textviewvfindviewbyidridgrid item text textsettextmtextidsposition imageview image imageviewvfindviewbyidridgrid item image imagesetimagedrawablemthumbidsposition else v view convertview return vgridview item layout xmlxml version10 encodingutf8linearlayout xmlnsandroidandroidididgridview item layoutandroidlayout widthwrap contentandroidlayout heightwrap contentandroidorientationverticalandroidgravitycenter horizontal imageview androidididgrid item imageandroidlayout widthwrap contentandroidlayout heightwrap contentandroidscaletypefitcenterandroidminheight100dipandroidminwidth100dipimageviewtextview androidididgrid item textandroidlayout widthmatch parentandroidlayout heightmatch parentandroidtexttextviewandroidgravitycenterandroidtextcolorf9a512androidtextstyleboldandroidtextsize18dptextviewlinearlayoutgridview xmlxml version10 encodingutf8gridview xmlnsandroid androidididgridviewandroidlayout widthfill parent androidlayout heightfill parentandroidnumcolumnsauto fitandroidverticalspacing10dipandroidhorizontalspacing10dipandroidstretchmodecolumnwidthandroidgravitycenterandroidbackgroundfandroidpadding5dipi saw other questions about this same issue but none of them answered any ideas of whats happening,['android'] +310489,custom name for params hash from rails form for ordinarily using form forfoo means that on the back end of the forms action youll have the form data in paramsfoo but in my case i would like to have a custom namespace applied to these params ie paramsbar not paramsfooi am not talking about making the namespace longer by supplying the namespace argument to the form for method to the contrary my current name is overlong and i want to shorten it more importantly i am actually swapping a new model in place of an existing one so the controller is filled with calls to paramsquoter whereas our new model supplies paramscompany quoter intf quoter any ideasspecs ruby 193 rails 323,['ruby-on-rails'] +310544,in c is a constructor with only default arguments a default constructor in the following codestruct foo fooint x0does the constructor count as a default constructor,['c++'] +310547,access net field from f when the field name is a reserved keyword i have a struct that has a field called typehow do i access it in fcstruct a int typeflet a alet mything atype error because type is a reserved keywordhow do i access the type field of a,"['c#', '.net']" +310565,jquery ajax call not found error hi i have been trying to make a ajax call to a jsp page heres the piece of js functionscriptfunction function myajaxcall ajax type post url jspcommonmyjavascriptpagejsp datatype text success function result alertgot the result result error function xhrstatuserror alertstatus status alerterror error alertxhr xhrreadystate statuscode 404 function alertpage not found scripti am constantly getting file not found even though jsp exists in the url mentioned please note that i am calculating the jsp file location relative to that of webapp directoryi tried using the normal ajax calls without jquery but ended up with same errorcould you please help me understand why is it not able to locate the jsp,"['javascript', 'jquery']" +310568,convert between uiimage and base64 string does anyone know how to convert a uiimage to a base64 string and then reverse iti have the below code the original image before encoding is good but i only get a blank image after i encode and decode itnsdata imagedata uiimagepngrepresentationviewimagensstring b64encstr self encode imagedatansstring base64string self encodebase64imagedata,['ios'] +310580,wifi direct android 40 with multiple 3 devices like here automatic authentication for android wifi direct i want to create a mobile adhoc wifi network with android devices but unlike the linked question above i want to use the official android wifi direct api which is availabe since android 40so is there a way to not only connect 2 devices via wifi direct but also three or more so messages could be passed from one device to another using several other devices in between therefore spanning a larger thistance between the sender and receiver the wifi direct demo only works for pairing two devices and i could not find a way to do anything else thanks,['android'] +310622,rails redirect to https while keeping all parameters i am redirecting to https like soredirect to protocol https status moved permanentlyhowever the parameters do not go through like this i can pass specific parameters through like thisredirect to protocol https status moved permanently param1 paramsparam1 param2 paramsparam2how would i make it so that it just passes through every parameter on the url instead of having to explicitly declare each parameter,['ruby-on-rails'] +310626,multiple inheritance pointer comparison i have a class derived that inherits directly from two base classes base1 and base2 i would like to know if it is safe in general to compare pointers to the base classes to determine if they are the same derived objectbase1 p1base2 p2 stuff happens here p1 and p2 now point to valid objects of either their base type or derived assertp1 p2 this is illegalassertp1 static castbase1p2 is this okassertstatic castderivedp1 static castderivedp2 how about thisthe pointers are guaranteed to be valid but not necessarily to point to a derived object my guess is that this is probably fine but i wanted to know if it was ok from a technical c perspective i actually never do any operations on the pointers i just want to know if they point to the same objectedit it seems to be safe if i can guarantee that p1 and p2 point to derrived objects i basically want to know if it is safe if they do not if one or both point to a base object will the comparison necessarily fail again i can guarantee the pointers are valid ie p1 would never point at a base2 object or vice versa,['c++'] +310646,how do i combine a timezone aware date and time in python i have a date and a time that i am attempting to combine in python the time is timezone awarehowever when i try and combine them i get the wrong timeimport pytzfrom datetime import time datenyc time pytztimezoneamericanew yorkstart date date2012 7 7start time timehour 0 tzinfo nyc timecombined datetimecombinestart date start timeprint combinedprint nyc timenormalizecombinedthis prints 20120707 0500 which normalizes to 20120707 010400 why is this happening how can i avoid it,['python'] +310670,fopen of an url breaks for domain names not for numerical addresses after hours of trying to debug a thirdparty application having trouble with fopen i finally thiscovered thatphp r echofile get contentsfails butphp r echofile get contentssucceedsnote that as the webserver user i can ping wgooglecom and it resolves just finei straced both executions of php and they diverge like thisfor the numerical v4 urlsocketpf inet sock stream ipproto ip 3fcntl3 f getfl 0x2 flags o rdwrfcntl3 f setfl o rdwro nonblock 0connect3 sa familyaf inet sin porthtons80 sin addrinet addr173194pollfd3 eventspollout 1 0 0 timeoutbunch of pollselectrecvfromclose3 0for the domain namesocketpf inet6 sock dgram ipproto ip 3close3 0php did not even try to do anything with that socket it seems or even resolve the domain for that matter wtf recompiling php with or without ipv6 support did not seem to matter thisabling ipv6 on this system is not desirablegentoo linux php 5314 currently giving a try to php 54 and see if it helps anyone has an idea editphp r echo gethostbynamewgooglecomworks and yield an ipv4 whilephp r echofile get contentshttp2a00145040078031011seems to return a blank resultedit 2i did not even notice the first time that the v6 socket opened when the name is used is a sock dgram is this php trying to resolve the domain name i tried switching my resolver from 127001 to 1 in resolvconf and it did not help,['php'] +310692,mongodb embedded objects have no id null value i have a question regarding mongodb with spring data i have these domain classesdocumentpublic class deal id private objectid id private location location private user user private string description private string title private string price private boolean approved private date expirationdate private date publisheddatedocumentpublic class location id private objectid id private double latitude private double longitude private string country private string street private string zipdocumentpublic class user id private objectid id private string email private string password private string profile image url private collectiondeal deals new arraylistdealwith these domains i can successfully crud there is only one problem when saving a user with deals the deals and location get id set to null when saving them to mongodbwhy cana t mongodb generate unique ida s for embedded objects the result after saving a user with one deal id objectid 4fed0591d17011868cf9c982 class user email password mimi deals id null location id null latitude 2 longitude 323445 country denmark street denmark road 77 zip 2933 description the new nexus 7 tablet a 7 inch tablet from google title nexus 7 price 1300 approved false expirationdate date 134351280 publisheddate date 1340933521374 as you can see from the result deal and location id is set to null,['java'] +310726,are there any downsides to using doubleslashes in urls i have written my own mvc framework in php which uses urls in the format ofcontrollermethodparam1param2parami have made it so that default methods can be ignored by default index so this results in urls like controllerparam1param2param for example a url of viewpanelglide3 will call indexpanelglide 3 in the view controllerthis works fine and dandy but i am concerned that search engines or some older browsers might freak out when they see the double slashes as i do not think i have actually seem them ever be used beforeis anyone aware of any issues i might come across by using this,['php'] +310759,errorlogging for javascript on client side my project which contains a lot of pages with forms this is a backend of banking crm system so any error during working process is to be captured and investigated on the server side we have enhanced java exceptions system but if error occurs on client side javascript the only info we now get is an jserror window in ie or sometimes a screenshot of page made by advanced userjavascript code contains both jquerypowered ui extensions and hardcoded inline event handlers and functions so i am asking whether any approach for capturing jserrors of any kind could be used some additional library or something that could give me a stacktrace like firebug in mozilla or webconsole in chrome,"['javascript', 'jquery']" +310768,net native extension for nodejs i want to make use of net dlls in nodejs does that mean i need to make those dlls available with cc using clr hosting a la net framework 4 hosting interfaces orhosting the common language runtimeunfortunately the example creating a nodejs native net extension over at github was a bit of a thisappointment just scroll down to the last stepchange the common language runtime support option to no common language runtime supportand you know what i mean correction to do that article justice it suggests to change that option to no common language runtime support only for the file sharpaddoncpp so other cppfiles you add will have clr support enabled the default for a clr project which means you can in fact use net dlls from those other cpp filesthis question is actually a duplicate of using a net dll in nodejs serverside javascript which was written at a time when there was not even a native windows port of node so times might have changed although google makes me doubt it,"['c#', 'c++', '.net']" +310771,enumerating folders and files using google drive sdk v2 i am a little confused by the v2 google drive sdkthere seems to be 2 methods to retrieve information about files and foldersfileslist and childrenlistusing fileslist i do not seem to be able to narrow my search to files in a specific folder but using childrenlist only returns very basic file information such as id there are no filenamesit looks like i have to retrieve a list of children and then perform a request for each child to find out its filename which seems very inefficientwhat is the normalcorrect way to enumerate folders and their contents using google drive,['android'] +310777,mvc4 partial view javascript bundling issue i am working on a project aspnet 4 mvc4rc using visual studio 11i am trying to render an mvc4 razor view that renders a partial view i have some javascript required for my partial viewon my partial view when i include my javascript inside the scripts section as follows it does not seem to loadsection scripts script typetextjavascript function alerttest scriptif i remove the scripts section it fails as the jquery libraries which are bundled and rendered on my layoutcshtml page have not yet loaded when the document ready code runsscript typetextjavascript function alerttest script layout page code to load jquery librariesscriptsrenderbundlesjqueryrendersectionscripts required falsedoes anyone know of a solution for this or am i simply going about it the wrong way its wrecking my head,['javascript'] +310817,rails mountable engine and overriding another engine i am in the proces of converting my standard rails app to an mountable engine the app is comparable to a standard blogging app and i want every model controller and view to be extendable hence my choice for a mountable engineone of the gems i use is devise which is as far as i understand a sort of a mountable engine itself it can be used inside a mountable engine as stated herei am able to use it partially within my engine everything is working fine including some devise controller i override like this one configroutesrbronlineengineroutesdraw do devise for users class name bbronlineuser module devise controllers registrations bbronlinedevise overridesregistrations controllersbbronlinedevise overridesregistrations controllerrbrequire dependency bbronlineapplication controllermodule bbronlineclass deviseoverridesregistrationscontroller deviseregistrationscontroller def new intermediair user usernew end the correct view viewsbbronlinedevise overridesregistrationsnew intermediairhtmlhaml is also correctly loading as expectedhowever my issue is that the views that i override without a custom controller are not properly loaded for example the view that should the login view is located in viewsbbronlinedevisesessionsnewhtmlhaml and is not loaded instead the standard devise login view gets loaded ie devise210appviewsdevisesessionsnewhtmlerbof course i could solve this problem by overriding every controller with my own controller like i did with the registrations controller above but this seems very ugly is overriding every controller the way to do this is there a more convenient way to override views from an mountable engine from within another mountable engine,['ruby-on-rails'] +310838,how to best pass methods into methods of the same class i have this c class that one big complicated method compute that i would like to feed with a compute kernel a method of the same class i figure i would do something along the lines ofclass test int classvar 42int compute addint a int b computeint a int b thisadd int compute multint a int b computeint a int b thismult int compute int a int b pass in add or multiply as f int c0 some complex loops c fab return cint add int a int babclassvar int multiply int a int babclassvar but i am not sure how i would pass in add or multiplyan alternative to this approach would be to pass in an enum of some sort to specify add or multiply but i wanted to avoid a switch or if inside the loopswhats best practice here,['c++'] +310861,how to setup google cloud messaging for android i am trying to implement google cloud messaging for android gcm by following the demo but i am unable to execute some command like ant war android update project name gcmdemo p target android16i am using wamp server and targetting android 8any help would be highly appreciated,['android'] +310864,ios get play count for items in the media library i am currently trying to categorise a users music collection and the ability to get the users most played songsartists would greatly improve the user experience in the app is it possible to get the play count and how would i go about doing it,"['iphone', 'objective-c', 'ios']" +310866,c and maths fast approximation of a trigonometric function i know this is a recurring question but i have not really found a useful answer yet i am basically looking for a fast approximation of the function acos in c i would like to know if i can significantly beat the standard onebut some of you might have insights on my specific problem i am writing a scientific program which i need to be very fast the complexity of the main algorithm boils down to computing the following expression many times with different parameterssin acost 1 acost 2 acost n where the t i are known real double numbers and n is very small like smaller than 6 i need a precision of at least 1e10 i am currently using the standard sin and acos c functionsdo you think i can significantly gain speed somehow for those of you who know some maths do you think it would be smart to expand that sine in order to get an algebraic expression in terms of the t i only involving square rootsthank you your your answers,['c++'] +310870,css position element fixed inside scrolling container i wonder if anyone has found a solution for thisi am looking for a solution to attach an element to the top of a scrolling containerhtmldiv classcontainer div classheadertitlediv div classelementdiv about 1020 elements div classelementdiv divall elements have positionrelativethe container has the following csscontainer positionrelative width200px height400px overflowyscrolli want the header to stay on top of the container independant of its scrolling position and the elements scrolling underneaththe css so farheader positionabsolute scrolling out of view zindex2 backgroundcolorfelement position relativeall elements are block elements and i can not move the header outside of the containerjquery is no option at this point,"['html', 'css']" +310897,getting the currentuserid from websecurity directly after login caspnet i have this website caspnet with a form where the user can register for an account it is the default template of vs11 and after everything is filled in and the user clicks to register it creates the account and logs in the user which works great after this step i want to get the userid which he was assigned but it does not work i have put a breakpoint there to see the values of both currentuserid and websecuritycurrentuserid but they only have a 1 value next step is the user gets redirected to the next page and on that page these functions work i thought i would be able to get the userid as the user has already gotten logged in in the first line of the code i provided hereso my question is why does not it work here i am very noobish with this so i am obviously missing somethingwebsecurityloginusername passwordint currentuserid websecuritycurrentuserid this does not work only returns 1here i wish to update other tables but i need the user idresponseredirectwelcomecshtmlthanks,"['c#', 'asp.net']" +310927,update just one gem with bundler i use bundler to manage dependencies in my rails app and i have a gem hosted in a git repository included as followedgem gemname git pathtomygemgitto update this gem i execute bundle update but it also updates all the gem mentioned in gemfile so what is the command to update just one specific gem,['ruby'] +310966,add inset boxshadow on google maps element i am willing to add some inset boxshadow to a tag that is containing a google maps element however it seems nothing happens probably because google loads some other divs in the original element hence covering the generated boxshadowhow can i achieve this effectheres the code i havesection idmapcontainer figure idmapfiguresectionmapcontainer position relative float right width 700px backgroundcolor f9fafc bordertoprightradius 5px borderbottomrightradius 5pxmap position relative height 400px bordertoprightradius 5px borderbottomrightradius 5px boxshadow 0 1px 0 0 f6f7fb inset 0 1px 0 0 e0e5e1 inset 0 2px 0 0 ebebed inset 0 3px 0 0 f4f4f6 insetthank you,['css'] +311005,require ssl in webapi is there a way to require ssl for webapi an attributei do not see an applicable attribute under systemwebhttp something like the requirehttps attribute we have for mvc i am just trying to avoid rolling my own attribute message handler if there is a built in solution,['.net'] +311028,when should i use make heap vs priority queue i have a vector that i want to use to create a heap i am not sure if i should use the c make heap function or put my vector in a priority queue which is better in terms of performance when should i use one vs the other,['c++'] +311034,error importing maven android android project to eclipse with adt 20 i am updated the adt plugin to the last version 20 and the androidsdk tool now when i try to import an existent android maven to eclipse raise the exception an internal error occurred during importing maven projectscomandroidiostreamexception and creates the eclipse project but not like android project as before the previous existent maven android projects in the workspace works finethe eclipse full exception trace when import the project is the followingentry orgeclipseosgi 2 1 20120629 190234421message nls unused message lifecyclemappingpropertypage this message in orgeclipsem2ecoreuiinternalmessagesentry orgeclipsecorejobs 4 2 20120629 190303953message an internal error occurred during importing maven projectsstack 0javalangnoclassdeffounderror comandroidiostreamexception at megladwelleclipsem2eandroidprojecteclipseandroidprojectfactorycreateandroidprojecteclipseandroidprojectfactoryjava17 at megladwelleclipsem2eandroidprojecteclipseandroidprojectfactorycreateandroidprojecteclipseandroidprojectfactoryjava1 at megladwelleclipsem2eandroidandroidmavenprojectconfiguratorconfigureandroidmavenprojectconfiguratorjava62 at orgeclipsem2ecoreprojectconfiguratorabstractlifecyclemappingconfigureabstractlifecyclemappingjava109 at orgeclipsem2ecoreinternalprojectprojectconfigurationmanagerupdateprojectconfigurationprojectconfigurationmanagerjava414 at orgeclipsem2ecoreinternalprojectprojectconfigurationmanagerconfigurenewmavenprojectprojectconfigurationmanagerjava240 at orgeclipsem2ecoreinternalprojectprojectconfigurationmanagerimportprojectsprojectconfigurationmanagerjava156 at orgeclipsem2ecoreuiinternalwizardsmavenimportwizard1docreatemavenprojectsmavenimportwizardjava164 at orgeclipsem2ecoreuiinternalwizardsabstractcreatemavenprojectsoperationrunabstractcreatemavenprojectsoperationjava73 at orgeclipsem2ecoreuiinternalwizardsmavenimportwizard3runinworkspacemavenimportwizardjava249 at orgeclipsecoreinternalresourcesinternalworkspacejobruninternalworkspacejobjava38 at orgeclipsecoreinternaljobsworkerrunworkerjava54caused by javalangclassnotfoundexception comandroidiostreamexception at orgeclipseosgiinternalloaderbundleloaderfindclassinternalbundleloaderjava513 at orgeclipseosgiinternalloaderbundleloaderfindclassbundleloaderjava429 at orgeclipseosgiinternalloaderbundleloaderfindclassbundleloaderjava417 at orgeclipseosgiinternalbaseadaptordefaultclassloaderloadclassdefaultclassloaderjava107 at javalangclassloaderloadclassclassloaderjava247 12 morecan anybody solves it is needed an update of the m2e android connectorupdatethis my pomxmlproject xmlns xmlnsxsi xsischemalocation 0 0xsd modelversion400modelversion groupidyourcompanygroupid artifactidmyandroidapplicationartifactid version10snapshotversion packagingapkpackaging namemyandroidapplicationname dependencies dependency groupidcomgoogleandroidgroupid artifactidandroidartifactid version233version scopeprovidedscope dependency dependencies build finalnameprojectartifactidfinalname sourcedirectorysrcsourcedirectory pluginmanagement plugins plugin groupidcomjaywaymavenpluginsandroidgeneration2groupid artifactidandroidmavenpluginartifactid version320version extensionstrueextensions plugin plugins pluginmanagement plugins plugin groupidcomjaywaymavenpluginsandroidgeneration2groupid artifactidandroidmavenpluginartifactid configuration sdk platform or api level api level 4 platform 16 platform10platform sdk configuration plugin plugins buildprojectprojectthanks,['android'] +311067,how to log specific request details to rails server logs i typically do not like to ask directly how to do something without much understanding of whats going on but i am fairly new to rails and i am having a hard time accomplishing thisbasically i need to capture the following information for each request in a single log statement if possibledate of log entrytime of log entryhttp methodurl requestedportip address of requestoruser agent of the requestorreferring urlhttp response codehostnamewhats the preferred way of customizing the log format is it possible to just modify the existing logs and pass it this information or would i need to extend and overwrite the behavior i needi do not need this to be saved to a different log file or anything just output to stdout on each requestany help with this would be greatly appreciatedthanks,"['ruby-on-rails', 'ruby']" +311088,strange c memory allocation i created a simple class storer in c playing with memory allocation it contains six field variables all of which are assigned in the constructorint xint yint zchar clong ldouble di was interested in how these variables were being stored so i wrote the following codestorer snew storer543a528015465coutlongsendlendlcoutlongsxendlcoutlongsyendlcoutlongszendlcoutlongscendlcoutlongslendlcoutlongsdendli was very interested in the output386512386512386516386520386524386528386536why is the char c taking up four bytes sizeofchar returns of course 1 so why is the program allocating more memory than it needs this is confirmed that too much memory is being allocated with the following codecoutsizeofscendlcoutsizeofstorerendlcoutsizeofintsizeofintsizeofintsizeofcharsizeoflongsizeofdoubleendlwhich prints13229confirming that indeed 3 bytes are being allocated needlessly can anyone explain to me why this is happening thanks,['c++'] +311115,how could i implement a fuzzy time date replacer using knockout i would like to implement what this plugin does using jquerya short description of that pluginthis will turn all abbr elements with a class of timeago and an iso8601 timestamp in the title conforming to the datetime design patternmicroformatabbr classtimeago title201217t092417zdecember 17 2011abbrinto something like thisabbr classtimeago titledecember 17 2011about 1 day agoabbrexcept using knockout my markup looks like thisabbr databindattr title posted classtimeagoabbri think something is not synced up because nothing is happening even if i put the call to timeago within the viewmodel itself i am guessing i need a subscriber that is attached to the observable posted but i am not sure how to set that up,['jquery'] +311190,should i use linq to sql directly in code behind or use some other approach we are developing a project in aspnetc which is a not a very large project but a sizeable one currently we have developed few pages i am talking from point of view of a single page right nowthe approach is followed for every pages that has been developed so farin the code behind of my page we use linq to sql queries directly the insert operation is done queries to fill dropdownlists and other database related operations are used in code behind itselfwe use functions thoughthe same goes for other pages as wellmy question is should i include them in class files and then create objects and call appropriate methods to do my stuffif yes should we create a single class or create one class per page is this called creating data access layercan anyone help me suggest a proper way to do thisis this approach a good programming practicethis is a simple function that we are using in our code behindpublic void accounttypefill get the types of account ie entity and individual var acc from type in dtmem types select typecustcategory if acc null newcustomerddlaccounttypedatasource accthistincttolist newcustomerddlaccounttypedatabind can anyone point a simple example referring to this queryi hope my question makes senseany suggestions are welcome,"['c#', 'asp.net']" +311192,is it possible to override a constructor in c is it possible to override the constructor of the base class in the derived class if so the how can it be accomplished and in what use case would this be practical if not why not,['c#'] +311212,basic unit test vs unit test i am working on an mvc project and was wondering whether to use basic unit test or unit test i read articles explanations about both but cannot see much difference between the two what are the main differences and which one is preferable for a large scale app with db backend,['c#'] +311214,mapping hibernate entity for unknown thiscriminatorvalue for inheritancetypesingle table i have a classic hibernate inheritancestrategyinheritancetypesingle table with thiscriminatorformula it works fine however there are about 500 different values for the thiscriminatorvalue in the database and i need map just about 30 of them to java classes children and the rest of them to map to the parent java classthe problem can be modelled as an example inheritance on animal classentityinheritancestrategyinheritancetypesingle tablethiscriminatorformulapublic class animal implements serializable column public string getname so i have have about 30 subclasses of animal defined in the java code with thiscriminatorvalue when hibernate founds unknown value for the thiscriminator then it throws wrongclassexception however i need to map these unknown thiscriminator values to one entity the best it the animal class i need to use only the method getname in such casesi know one solution is to put a sql case into the thiscriminatorformula but then i have to state there all 30 known thiscriminator values plus more when i will need to add others so i am looking for more flexible solutionps it is a legacy code so i cannot change the model,['java'] +311237,adding one list to another list in java i have below java codelistsomepojo list new arraylistsomepojoadd 100 somepojo objects to listnow list has 100 objectsif i create one more instance as belowlistsomepojo anotherlist new arraylistsomepojoanotherlist addalistthanks,['java'] +311243,javascript attach event to class name if i have 10 items with the class name keyworddiv classkeyworddivhow can i attach an event for example click on this elementi tried the following but with no luck no alert comes updocumentgetelementsbyclassnamekeywordonclick function alerttrue searchaddkeythisgetelementsbyclassnamename0innerhtmlrequirementswithout the onclick attributeno jquery or any other librarynote the elements are not generated on page load their number can be different each times you click a button for egi need a way to attach to all tags with the class keyword in the future,['javascript'] +311254,osgetcwd vs ospathabspathospathdirname file i am using the os module to have relative paths in my django projects settingspy file the variable site root is set to the current working directory of the settingspy file and then used to reference all of the staticmedia directories also located in that same directory heres my issueprint osgetcwdprint ospathabspathospathdirname file in settingspy the above statements both have identical outputs but my template will only load if i use site root ospathabspathospathdirname file django looks for the templates heretemplate dirs ospathjoinsite root templatessite root set to osgetcwd seems to make django look for the templates folder in the directory above the settingspy filei can just as easily not use osgetcwd and my site runs fine but i am curious what may be going on here anyone know,['python'] +311268,determine the user language in pyramid i want to make internationalization for my project i followed how it is described in official documentation but localization still does not work here is how i try get user localedef get locale namerequest return the termlocale name associated with the current request possibly cached locale name getattrrequest locale name none if locale name is none locale name negotiate locale namerequest requestlocale name locale name return locale namebut request does not have attr local name but it has acceptlanguage and so when function get local name does not find local name in the request it calls another functiondef negotiate locale namerequest negotiate and return the termlocale name associated with the current request never cached try registry requestregistry except attributeerror registry get current registry negotiator registryqueryutilityilocalenegotiator defaultdefault locale negotiator locale name negotiatorrequest if locale name is none settings registrysettings or locale name settingsgetdefault locale name en return locale namehow can i see negotiator try to get local from global environment but if it cant to do that its set value from configand i cant understand why pyramid does not get locale directly from requests field acceptlanguageand how can i make a correct determination of the locale,['python'] +311313,how to increase heap size of an android application i am writing an android application which uses several 3d models such a model with textures can take up a lot of memory i found out the manufacturer sets a limit on the heap size an application can use for example my tablet samsung galaxy tab 89 p7310 can take up 64mb of memoryis there a way to increase this size of memory an application can use,['android'] +311341,can angularjs autoupdate a view if a persistent model server database is changed by an external app i am just starting to familiarize with angularjs but i would like to build a web app that has a view that gets autoupated in realtime no refresh for the user when something changes in the serverside databasecan angular handle this mostly automatically for me and if so what is the basic mechanism at workfor example do you somehow setup angular to poll the db regularly for model changes or use some sort of cometlike mechanism to notify angular clientside code that the model has changedin my application the challenge is that other nonweb serverside software will be updating the database at times but this question applies equally to pure webapps where you might have multiple clients changing the database through angular web clients and they each need to be updated when one of them makes a change to the db model,['javascript'] +311350,php debug backtrace bitmask usage trying to understand this entry in the php manual on debug backtracei do not understand what they mean by this parameter is a bitmask for i have done web searches on bitmasks and my head is spinning round so i have decided i do not really want to learn the detail about it but just to know how i can supposed to add the options to that functiondo i put in both options as indebug backtracedebug backtrace provide object debug backtrace ignore argsif i want both and one of them if i only want that one,['php'] +311452,share fruits fairly dynamic programming i am having a very hard time trying to figure out how to solve this problem efficiently let me describe how it goesa hard working mom bought several fruits with different nutritional values for her 3 kids amelia jessica and bruno both girls are overweight and they are very vicious and always leave poor bruno with nothing so their mother decided to share the food in the following manner amelia being the heaviest one gets the most amount of nutritional valuejessica gets an amount equal or less than ameliabruno gets an amount equal or less than jessica but you need to find a way to give him the highest possible nutritional value while respecting the rule a j b note the original problem is described differently but the idea is the same i do not want my classmates to find this post when they google for help hehe one of the test cases given by my teacher is the followingthe fruit list has the following values 4 2 1 8 11 5 1input7 number of fruits4 2 1 8 11 5 1 fruits nutritional valuesoutput1 11 one fruit their nutritional values sum for amelia5 position of the fruit in the list3 11 three fruits their nutritional values sum for jessica1 2 6 position of the fruits in the list3 10 three fruits their nutritional values sum for bruno3 4 7 position of the fruits in the listnote i am aware that there are several ways of diving the fruits among the kids but it does not really matter as long as it follows the rule a j bat first i made an algorithm that generated all the subsets each one had their sums and the positions that were in use that method was quickly thiscarded because the list of fruits can have up to 50 fruits and the subset algorithm is o2n i ran out of memorythe second idea that i have is to use dynamic programming in the columns header i would have the positions of the fruit is list in the row header the same it is kind of hard to explain with letters so i will ahead an do the table for the previous example 4 2 1 8 11 5 1 00 01 02 03 04 05 06 0700 01020304050607each time we advance to the row below we add the positions 1237 00 01 02 03 04 05 06 0700 00 no positions in use 01 04 rowposition 1 column positioncolumn 0 4002 06 rowposition 1 rowposition 2 column position 42003 07 rp1 rp2 rp3 cp0 421004 15 4218005 2606 3107 32 421811510now that you know how it goes lets add the first row 00 01 02 03 04 05 06 0700 00 04 02 01 08 11 05 01 sum of rp cp 01 04 00 06 05 12 15 09 05 sum of rp01 cp 02 06 03 07 04 15 05 2606 3107 32 i put the 00 because the 1st position is already in use the completed table would look like this 00 01 02 03 04 05 06 0700 00 04 02 01 08 11 05 01 01 04 00 06 05 12 15 09 05 02 06 00 00 07 14 17 11 07 03 07 00 00 00 15 18 12 08 04 15 00 00 00 00 26 20 16 05 26 00 00 00 00 00 31 2706 31 00 00 00 00 00 00 3207 32 00 00 00 00 00 00 00 now that we have the table i divide the sum of the nutritional values by the amount of kids 323 1067 the ceiling would be 11 i try to check for 11 if it is in the table i choose it and mark the position of the row and columns of the tables as used then i would try to check for 11 again if it is in the table i choose it otherwise look the 10 or 9 etc until i find it afterwards i would mark the respective positions as used then sum the unused positions to get brunos fruits i know that there has to be better way to do this because i found a flaw in my method the table only has the sum of a few subsets so maybe that will be detrimental in a few test cases maybe a 3d memoization cube i think it would consume too much memory and i have a limit too 256mbwow i did not realize i typed this much xx i hope i do not get a lot of tl dr any help guide would be greatly appreciated d edit i made the code that generates the table in case anyone wants to try it out static void tablegenint fruits int and fruitslength 1 int memo new intn n for int i 1 i n i memo0 i fruitsi 1 memoi 0 memoi 1 0 fruitsi 1 for int j i 1 j n j memoi j memoi 0 fruitsj 1 for int i 0 i n i for int j 0 j n j consolewrite0 memoi j consolewriteline,['c#'] +311470,how to thisable issueing queries against edmmetadata table i am using ef code first in my new project i am not going to use auto migration feature and have not migrationhistory table in db but with looking at profiler i can always see ef issues a query like this before any other queryselect groupby1a1 as c1from select count1 as a1 from dbo migrationhistory as extent1 as groupby1haw can i thisable this feature,['c#'] +311491,how can i get external sd card path for android 40 samsung galaxy s3 has an extrenal sd card slot which is mounted to mntextsdcardmy question is how to get this path by something like environmentgetexternalstoragedirectory this will return mntsdcard and i cannot find api for external sd card or removable usb storage on some tabletsthank you,['android'] +311502,emulate nexus 7 i want to emulate the nexus 7 but i cannot figure out what values to useskin builtin or custom resolution what hardware properties should i use,['android'] +311564,memory error in python traceback most recent call lastfile run13411447661067082874solutionpy line 27 in mainfile run13411447661067082874solutionpy line 11 in mainif lensij1 0memoryerrorerror in sysexcepthooktraceback most recent call lastfile usrlibpython27thistpackagesapport python hookpy line 64 in apport excepthookfrom apportfileutils import likely packaged get recent crashesfile usrlibpython27thistpackagesapport init py line 1 in from apportreport import reportmemoryerrororiginal exception wastraceback most recent call lastfile run13411447661067082874solutionpy line 27 in mainfile run13411447661067082874solutionpy line 11 in mainif lensij1 0memoryerrorthe above errors appeared when i tried to run the following program can someone explain what is a memory error and how to overcome this problem the program takes strings as input and finds all possible sub strings and creates a setin a lexicographical order out of it and it should print the value at the respective index asked by the user otherwise it should print invaliddef main no str intraw input sub strings for k in xrange0no str s raw input alens for i in xrange0 a for j in xrange0 a if j i if lensij1 0 sub stringsappendsij1 sub strings listsetsub strings sub stringssort queries intraw input resul for i in xrange0queries resulappendintraw input for p in resul try print sub stringsp1 except indexerror print invalidif name main main,['python'] +311611,address in c number i do not understand the output of this programint arr174258int xarrarr1arr4arrprintfd xarrarr1arr4 is equal to 4 what does it mean 4 why does it print 2,['c'] +311630,imap get attached file how do i get the attached file from this emailthis email is sent from an apple computer and the email struture is not like any other surprise here the part with the thisposition is one dimension deeper than elsethe script works with every other email where the part with the file is in the first dimension but not with this onepartdparameters0value returns the file name but strlendata returns 0imap streamstructure imap fetchstructurethisstream thismsgnoifissetstructureparts print rstructureparts thisparse partsstructurepartsfunction parse partsparts foreachparts as section part ifissetpartparts some mails have one extra dimension thisparse partspartparts elseifissetpartthisposition ifin arraystrtolowerpartthisposition arrayattachmentinline data imap fetchbodythisstream thismsgno section1 echo partdparameters0value strlendatan print rarray 0 stdclass object type 0 encoding 0 ifsubtype 1 subtype plain ifdescription 0 ifid 0 lines 15 bytes 173 ifthisposition 0 ifdparameters 0 ifparameters 1 parameters array 0 stdclass object attribute charset value usascii 1 stdclass object type 1 encoding 0 ifsubtype 1 subtype mixed ifdescription 0 ifid 0 bytes 23420 ifthisposition 0 ifdparameters 0 ifparameters 1 parameters array 0 stdclass object attribute boundary value applemail 800896e0a9c9456eb06379ced9dd4fd7 parts array 0 stdclass object type 0 encoding 0 ifsubtype 1 subtype html ifdescription 0 ifid 0 bytes 136 ifthisposition 0 ifdparameters 0 ifparameters 1 parameters array 0 stdclass object attribute charset value usascii 1 stdclass object type 3 encoding 3 ifsubtype 1 subtype pdf ifdescription 0 ifid 0 bytes 17780 ifthisposition 1 thisposition inline ifdparameters 1 dparameters array 0 stdclass object attribute filename value 057 lpj stik og labelspdf ifparameters 1 parameters array 0 stdclass object attribute name value 057 lpj stik og labelspdf 2 stdclass object type 0 encoding 4 ifsubtype 1 subtype html ifdescription 0 ifid 0 lines 75 bytes 4931 ifthisposition 0 ifdparameters 0 ifparameters 1 parameters array 0 stdclass object attribute charset value usascii,['php'] +311637,crash after m xmmatrixidentity aligment memory in classes i was looking at the tutorials in directx sdk tutorial 5 works fine but after i have copied and separated the code to my own classes i got strange error during launching my applicationthe line isg world1 xmmatrixidentitybecause of it i got error in xnamathmatrixint operator which looks like thatxmfinline xmmatrix xmmatrixoperator const xmmatrix m r0 mr0 r1 mr1 r2 mr2 r3 mr3 return thisand the error message isaccess violation reading location 0xfi have read somewhere that it could be caused by something connected to xmfloat4x4 xmmatrixhave you considered using xmfloat4x4 to store the matrix and only using xmmatrixbut i think i already use xmmatrixmyclasshprivate xmmatrix g world1myclasscppvoid init g world1 xmmatrixidentityi do not think i should change xmmatrix g world1 to xmfloat4x4 g world1 because it produces errors likeerror c2679 binary no operator found which takes a righthand operand of type xmmatrix or there is no acceptable conversionso whats the problem,['c++'] +311671,devise with omniauth for multiple models without sti is there any way to configure devise omniauth for multiple models without stiwe have the models students and professors and we did not want to use sti but now we realized that devise with omniauth does not play well with multiple modelsrvmgemsruby193p125gemsdevise210libdeviserailsroutesrb384in devise omniauth callback wrong omniauth configuration if you are getting this exception it means that either runtimeerror1 you are manually setting omniauthconfigpath prefix and it does not match the devise one2 you are setting omniauthable in more than one model3 you changed your devise routesomniauth setting and have not restarted your server,['ruby-on-rails'] +311683,android billing exception about a trailing character i get this exception from my crash reportsjavalangruntimeexception unable to start service comproblemiobillingservice4132b868 with intent actcomandroidvendingbillingpurchase state changed cmpcomproblemiobillingservice has extras javalangillegalargumentexception utilsbase64decoderexception single trailing character at offset 19at androidappactivitythreadhandleserviceargsactivitythreadjava2376at androidappactivitythreadaccess1900activitythreadjava123at androidappactivitythreadhhandlemessageactivitythreadjava1210at androidoshandlerthispatchmessagehandlerjava99at androidoslooperlooplooperjava137at androidappactivitythreadmainactivitythreadjava4424at javalangreflectmethodinvokenativenative methodat javalangreflectmethodinvokemethodjava511at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava784at comandroidinternaloszygoteinitmainzygoteinitjava551at dalviksystemnativestartmainnative methodcaused by javalangillegalargumentexception utilsbase64decoderexception single trailing character at offset 19at utilssecuritygeneratepublickeysecurityjava199at utilssecurityverifypurchasesecurityjava118at comproblemiobillingservicepurchasestatechangedbillingservicejava545at comproblemiobillingservicehandlecommandbillingservicejava421at comproblemiobillingserviceonstartbillingservicejava398at androidappserviceonstartcommandservicejava438at androidappactivitythreadhandleserviceargsactivitythreadjava2359 10 morecaused by utilsbase64decoderexception single trailing character at offset 19at utilsbase64decodebase64java529at utilsbase64decodebase64java4at utilsbase64decodebase64java390at utilssecuritygeneratepublickeysecurityjava189 16 morejavalangillegalargumentexception utilsbase64decoderexception single trailing character at offset 19at utilssecuritygeneratepublickeysecurityjava199at utilssecurityverifypurchasesecurityjava118at comproblemiobillingservicepurchasestatechangedbillingservicejava545at comproblemiobillingservicehandlecommandbillingservicejava421at comproblemiobillingserviceonstartbillingservicejava398at androidappserviceonstartcommandservicejava438at androidappactivitythreadhandleserviceargsactivitythreadjava2359at androidappactivitythreadaccess1900activitythreadjava123at androidappactivitythreadhhandlemessageactivitythreadjava1210at androidoshandlerthispatchmessagehandlerjava99at androidoslooperlooplooperjava137at androidappactivitythreadmainactivitythreadjava4424at javalangreflectmethodinvokenativenative methodat javalangreflectmethodinvokemethodjava511at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava784at comandroidinternaloszygoteinitmainzygoteinitjava551at dalviksystemnativestartmainnative methodcaused by utilsbase64decoderexception single trailing character at offset 19at utilsbase64decodebase64java529at utilsbase64decodebase64java4at utilsbase64decodebase64java390at utilssecuritygeneratepublickeysecurityjava189 16 moreutilsbase64decoderexception single trailing character at offset 19at utilsbase64decodebase64java529at utilsbase64decodebase64java4at utilsbase64decodebase64java390at utilssecuritygeneratepublickeysecurityjava189at utilssecurityverifypurchasesecurityjava118at comproblemiobillingservicepurchasestatechangedbillingservicejava545at comproblemiobillingservicehandlecommandbillingservicejava421at comproblemiobillingserviceonstartbillingservicejava398at androidappserviceonstartcommandservicejava438at androidappactivitythreadhandleserviceargsactivitythreadjava2359at androidappactivitythreadaccess1900activitythreadjava123at androidappactivitythreadhhandlemessageactivitythreadjava1210at androidoshandlerthispatchmessagehandlerjava99at androidoslooperlooplooperjava137at androidappactivitythreadmainactivitythreadjava4424at javalangreflectmethodinvokenativenative methodat javalangreflectmethodinvokemethodjava511at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava784at comandroidinternaloszygoteinitmainzygoteinitjava551at dalviksystemnativestartmainnative methodbut i do not quite understand what the problem was any suggestionsit points to this method decodes base64 content using the supplied decodabet and returns the decoded byte array param source the base64 encoded data param off the offset of where to begin decoding param len the length of characters to decode param decodabet the decodabet for decoding base64 content return decoded data public static byte decodebyte source int off int len byte decodabet throws base64decoderexception int len34 len 3 4 byte outbuff new byte2 len34 upper limit on size of output int outbuffposn 0 byte b4 new byte4 int b4posn 0 int i 0 byte sbicrop 0 byte sbidecode 0 for i 0 i len i sbicrop byte sourcei off 0x7f only the low seven bits sbidecode decodabetsbicrop if sbidecode white space enc white space equals sign or better if sbidecode equals sign enc an equals sign for padding must not occur at position 0 or 1 and must be the last bytes in the encoded value if sbicrop equals sign int bytesleft len i byte lastbyte byte sourcelen 1 off 0x7f if b4posn 0 b4posn 1 throw new base64decoderexception invalid padding byte at byte offset i else if b4posn 3 bytesleft 2 b4posn 4 bytesleft 1 throw new base64decoderexception padding byte falsely signals end of encoded value at offset i else if lastbyte equals sign lastbyte new line throw new base64decoderexception encoded value has invalid trailing byte break b4b4posn sbicrop if b4posn 4 outbuffposn decode4to3b4 0 outbuff outbuffposn decodabet b4posn 0 else throw new base64decoderexceptionbad base64 input character at i sourcei off decimal because web safe encoding allows non padding base64 encodes we need to pad the rest of the b4 buffer with equal signs when b4posn 0 there can be at most 2 equal signs at the end of four characters so the b4 buffer must have two or three characters this also catches the case where the input is padded with equals sign if b4posn 0 if b4posn 1 throw new base64decoderexceptionsingle trailing character at offset len 1 b4b4posn equals sign outbuffposn decode4to3b4 0 outbuff outbuffposn decodabet byte out new byteoutbuffposn systemarraycopyoutbuff 0 out 0 outbuffposn return out the error seems to be pointing to these lines in my billingservicejavaat comproblemiobillingservicepurchasestatechangedbillingservicejava585at comproblemiobillingservicehandlecommandbillingservicejava461at comproblemiobillingserviceonstartbillingservicejava438the line on 585 is the linepurchases securityverifypurchasesigneddata signaturein this methodprivate void purchasestatechangedint startid string signeddata string signature arraylistsecurityverifiedpurchase purchases purchases securityverifypurchasesigneddata signature if purchases null return and the line 461 is this linepurchasestatechangedstartid signeddata signaturein this methodpublic void handlecommandintent intent int startid string action intentgetaction if constsdebug logitag handlecommand action action if constsaction confirm notificationequalsaction string notifyids intentgetstringarrayextraconstsnotification id confirmnotificationsstartid notifyids else if constsaction get purchase informationequalsaction string notifyid intentgetstringextraconstsnotification id getpurchaseinformationstartid new string notifyid else if constsaction purchase state changedequalsaction string signeddata intentgetstringextraconstsinapp signed data string signature intentgetstringextraconstsinapp signature purchasestatechangedstartid signeddata signature else if constsaction response codeequalsaction long requestid intentgetlongextraconstsinapp request id 1 int responsecodeindex intentgetintextraconstsinapp response code responsecoderesult errorordinal responsecode responsecode responsecodevalueofresponsecodeindex checkresponsecoderequestid responsecode and line 438 is this linehandlecommandintent startidin this methodoverridepublic void onstartintent intent int startid handlecommandintent startidthanks,['android'] +311685,using the javascript slice method with no arguments i am currently reading through this jquery masking plugin to try and understand how it works and in numerous places the author calls the slice function passing no arguments to it for instance here the buffer variable is sliced and bufferslice and buffer seem to hold the same valuesis there any reason for doing this or is the author just making the code more complicated than it should be functionality fn function unmaskedvalueinput skipdatepickercheck var input input0 if tests skipdatepickercheck true inputhasclasshasdatepicker var buffer bufferslice checkvalinput buffer return mapbuffer functionelement index return ismaskindex element getbufferelement bufferslice index element null join else return input valueget,"['javascript', 'jquery']" +311793,simple html project type for visual studio 2010 we are developing a rest based application using visual studio 2010 using aspnet web api and we want to host it using iisfor the client side we want to use pure html css and javascript to access and using this rest based applicationbut we could not find any project type html web application or site in vs 2010we do not want to use aspnet or mvc empty projectis there is any project type available or any other best way to do this,['html'] +311800,how to prevent double code running by clicking twice fast to a button in android if i click fast to my button in my android app it seems that code behind it runs twiceif i click my menu button twice the activity that has to be launch onclick just starts twice and i have to quit from it twicethis is really annoying because if i click too fast for menu buttons i can load up a whole bunch of activities in the background and i must quit them one by one so this is clearly a buggy state of my app i want to fix thiswhat can i do with this issuei use simple onclicklisteners and buttonsedit regarding to answers and comments my menu buttons look like thistop20buttonsetonclicklistenernew onclicklistener public void onclickview v favbuttonsetclickablefalse nearbuttonsetclickablefalse highlightedbuttonsetclickablefalse top20buttonsetclickablefalse intent i new intent iputextrashowdialog false iaddflagsintentflag activity single top isetclasearchthis top20class startactivityi finish after all this correction its still the same swhen i click like a mad person multiple activites are on the history stack and i must quit multiple timesany suggestions what m i doing wrong,['android'] +311807,how to reset database migrations using ef code first i have a class library project with my dbcontext and migration enabled with following config fileconfiguration configsections for more information on entity framework configuration visit section nameentityframework typesystemdataentityinternalconfigfileentityframeworksection entityframework version4310 cultureneutral publickeytokenb77a5c561934e089 configsections connectionstrings add namedatacontext connectionstringdata sourcedatasdf providernamesystemdatasqlserverce40 connectionstrings entityframework defaultconnectionfactory typesystemdataentityinfrastructuresqlconnectionfactory entityframework parameters parameter valuesystemdatasqlserverce40 parameters defaultconnectionfactory entityframeworkconfigurationsome time before i played with migrations for this project and getmigrations command always returns following to mepm getmigrations startupprojectname dataretrieving migrations that have been applied to the target database201207012104355 initial201207012031234 initial201207012024250 initialthe problem is that command always returns these items even if i delete datasdf or delete all project and make new one the only way i can create new database is changing database file name in connection string from datasdf to data1sdf for exampleso how can i reset migration history without changing database name,"['c#', '.net']" +311817,how to loop over the child divs of a div and get the ids of the child divs i have a div with id testand through the foreach loop i am creating some inner divs inside the test div so it becomes like thisdiv idtestdiv idtest1divdiv idtest2divdiv idtest3divdiv idtest4divdivi am getting the parent div id test in the javascript function now i want to loop through the inner divschild divs of the test div and get the id of the each div one by one and style them through javascriptany idea about this,"['javascript', 'jquery']" +311833,hibernate does not create tables automatically i have maven project with hibernate orm and spring frameworki want hibernate to create tables automatically but he just drops all existed tables and does not creates required tableshe does not throw any exception during sessionfactory initialization but when i try save player entity exception is thrown commysqljdbcexceptionsjdbc4mysqlsyntaxerrorexception table billboarddbplayer does not existif i create tables manually and change property hibernatehbm2ddlauto to validate value everything works finedo you have any idea why hibernate does not create tablesspring configuration file contextcomponentscan basepackageorgmelukbillboardbusinesscontroller txannotationdriven transactionmanagertxmanager bean idpropertyconfigurer classorgspringframeworkbeansfactoryconfigpropertyplaceholderconfigurer property namelocations list valuewebinfconfigjdbcpropertiesvalue list propertybeanbean iddatasource classorgspringframeworkjdbcdatasourcedrivermanagerdatasource property namedriverclassname valuehibernateconnectiondriver class property nameurl valuehibernateconnectionurl property nameusername valuehibernateconnectionusername property namepassword valuehibernateconnectionpassword beanbean idsessionfactory classorgspringframeworkormhibernate3annotationannotationsessionfactorybean property namedatasource refdatasource property nameconfiglocation valuewebinfhibernatecfgxml property namepackagestoscan valueorgmelukbillboardjpa property namehibernateproperties props prop keyhibernatedialecthibernatedialectprop prop keyhibernateshow sqlhibernateshow sqlprop prop keyhibernatehbm2ddlautohibernatehbm2ddlautoprop prop keyhibernatec3p0min sizehibernatec3p0min sizeprop prop keyhibernatec3p0max sizehibernatec3p0max sizeprop prop keyhibernatec3p0timeouthibernatec3p0timeoutprop prop keyhibernatec3p0max statementshibernatec3p0max statementsprop props propertybeanbean idtxmanager classorgspringframeworkormhibernate3hibernatetransactionmanager property namesessionfactory refsessionfactory beanjdbcproperties file hibernateconnectiondriver classcommysqljdbcdriver hibernateconnectionurljdbcmysql1270013306billboarddb hibernateconnectionusernameroot hibernateconnectionpassword1234 hibernatedefault schemabillboarddb hibernatedialectorghibernatedialectmysqlinnodbdialect hibernatehbm2ddlautocreate hibernateshow sqltrue hibernatec3p0min size5 hibernatec3p0max size20 hibernatec3p0timeout1800 hibernatec3p0max statements50hibernate dependencies dependency groupidorghibernategroupid artifactidhibernateentitymanagerartifactid versionhibernateversionversion dependency dependency groupidorghibernategroupid artifactidhibernatec3p0artifactid versionhibernateversionversion dependency dependency groupidorghibernategroupid artifactidhibernatetoolsartifactid versionhibernatetoolsversionversion dependency,['java'] +311868,push up content when clicking in edit text i have searched everywhere for a solution to my problem but cannot find a answer heres the problem i have a layout that looks like thisnow when i click in the edit textsearch bar i want the following to happenthe soft keyboard basically needs to push up the whole screens content so that the search bar is at the top and its listview is beneath it so that when the content is searched the results are thisplayed i have tried setting androidwindowsoftinputmodeadjustpan to the activity in the manifest but this did not work i set a scroll view as the main container in the main layout that contains the fragments but that also did not work i have tried adding the edit textsearch bar as a header to the list view but this also did not work every time the keyboard pushed up the edit text but covered the list view is there any way to make this work,['android'] +311884,determine when a viewpager changes pages i have three pages fragments inside a viewpager however i only want to thisplay a menu item for two of those pagesthe code given in a previous so answer does not seem to workoverridepublic void setuservisiblehintboolean isvisibletouser supersetuservisiblehintisvisibletouser if isvisibletouser true else if isvisibletouser false eclipse says override is not needed and super cannot be set it is never called by the system and even if it was how would i determine which page was being shown at the moment could i have some help here,['android'] +311888,django catching integrity error and showing a customized message using template in my django powered app there is only one obvious case where integrityerror can arisesohow can i catch that error and thisplay a message using templates,['python'] +311931,progressive video download on ios i am trying to implement progressive downloading of a video in my ios application that can be played through avplayer i have already implemented a downloader module that can download the files to the ipad however i have thiscovered i cannot play a file that is still being written toso as far as i can tell my only solution would be through downloading a list of file chunks and then keep playing through every file as they are ready ie downloaded probably using hlssearching i have come across this question which implements the progressive download through hls but other than that i can find no other wayhowever i keep coming across search results that say how to configure web servers to leverage the ios support for http progressive downloading but with no mention of how to do it from the ios sideso any one have any ideas andor experience about thisedit i have also found there could be a way of doing it other way around ie streaming then writing streamed data to thisk which was suggested by this question but still cannot get it to work as it seems it does not work with nonlocal assets,['ios'] +311936,android wrap content is not working with listview i am working on android i want my list view to wrap its content horizontally and not to fill all the width the wrap content properties is not working what to do,['android'] +311964,iterate through class members in order of their declaration i got this problem writing a little gui lib that maps classes to simple table views every class member of a certain type column and order of columns is important butclass personobject name none date of birth none nationality none gender none address none comment nonefor member in person dict iteritems if not member1 print member0outputcommentdate of birthnameaddressgendernationalityugh the oder got all mixed updesired outputnamedate of birthnationalitygenderaddresscommentis there a way to do it without maintaining additional ordereddict of columns,['python'] +311974,assigning hashmap to hashmap i have a hashmap which i want to copy for other use but whenever i copy it and reuse it it also changes the original onewhy is that do mapinteger mapstring object map1 originalmap at the second iteration originalmap is the same as map1 of the last iteration eventhough the change was nog accepted do something with map1 change value ifchange is accepted originalmap map1 whileiteration 10thanks in advance public static integerstring schedulemapinteger mapstring schedule deepcopymapinteger mapstring schedule original mapinteger mapstring schedule copy new hashmapinteger mapstring schedule for mapentryinteger mapstring schedule entry originalentryset copyputentrygetkey deepcopy2entrygetvalue return copypublic static string schedulemapstring schedule deepcopy2mapstring schedule original mapstring schedule copy new hashmapstring schedule for mapentrystring schedule entry originalentryset copyputentrygetkey entrygetvalue return copy,['java'] +311976,jquery onclick vs click and delegateclick i am used to using click and delegateclick so when i read both were deprecated in recent versions of jquery i thought i would read up on it but i am scratching my head a bitthe documentation here seems to suggest that this is a dropin replacement for live and delegate but click and bind had a different behavior namely binding to currently existing objects where the others bound to any objects that matched the selector pattern througout the lifespan of the domin most cases this wouldnt make a big difference but when adding elements to your dom dynamically this is an important thistinction new objects matching the old pattern would not have listeners tied to the click event using click but would with delegatemy question is how does one use the on method to duplicate the behavior of both the preexisting delegate and bind or is everything in the future going towards the delegate style,['jquery'] +311980,encoding a png with javascript i have some arbitrary pixel data that i want to save as a png how can i encode a png with javascript to accomplish thisthe data is a series of 1s and 0s that i want to use to create a qr code it is qr code arbitrary datai am not using the dom so jquery and createelements are out,['javascript'] +311982,how do i implement ienumerable i know how to implement the non generic ienumerable like thisusing systemusing systemcollectionsnamespace consoleapplication33 class program static void mainstring args myobjects myobjects new myobjects myobjects0 new myobject foo hello bar 1 myobjects1 new myobject foo world bar 2 foreach myobject x in myobjects consolewritelinexfoo consolewritelinexbar consolereadline class myobject public string foo get set public int bar get set class myobjects ienumerable arraylist mylist new arraylist public myobject thisint index get return myobjectmylistindex set mylistinsertindex value ienumerator ienumerablegetenumerator return mylistgetenumerator however i also notice that ienumerable has a generic version ienumerablet but i cannot figure out how to implement itif i add using systemcollectionsgeneric to my using directives and then changeclass myobjects ienumerabletoclass myobjects ienumerablemyobjectand then right click on ienumerablemyobject and select implement interface implement interface visual studio helpfully adds the following block of codeienumeratormyobject ienumerablemyobjectgetenumerator throw new notimplementedexceptionreturning the non generic ienumerable object from the getenumerator method does not work this time so what do i put here the cli now ignores the non generic implementation and heads straight for the generic version when it tries to enumerate through my array during the foreach loopthanks,"['c#', '.net']" +311985,translate animation works perfectly when defining with xml and only once perfectly by code android i am getting this weird issue basically i am animating a view with translate animation translate into the screen and out via 2 different events my code for translate animation is final animation animtopout new translateanimation0 0 0 mainheaderlayoutgetmeasuredheight animtopoutsetduration500 animtopoutsetfillaftertruemainheaderlayoutsetanimationanimtopoutand the xml code isset xmlnsandroid androidfillaftertrue androidinterpolatorandroidanimaccelerate interpolator translate androidfromydelta0p androidtoydelta99p androidduration600 androidfillaftertruetranslatesetsetting it using the codefinal animation animtopout animationutilsloadanimationmcontext ranimheader animate outwhen i trigger the animation it works fine if i use the xml animation properties the problem is when i use it via code which is what i want it runs with translate animation only for the first time the second time when it is triggered the view is inside the screen without animation please some one help me if i am missing any properties thanksedit extra infothere are actually two different animations that are triggered on the same view via two different events i have actually posted one animation property the other is almost the same with just values are different,['android'] +311987,matplotlib stepped histogram with already binned data i am trying to get a histogram with already binned data i have been trying to use bar for this but i cannot seem to figure out how to make it a stepped histogram like this one from the examples instead of a filled histogram,['python'] +312027,jdbc batch insert exception handling i am performing a jdbc batch insert inserting 10 rows approx at a time each time my program is executed but i am not able to handle the exception thrown by some of the records properlysuppose the 100th record out of 10 records is throwing an exception because of an invalid data or size of some value exceeds the column size once the exception has occured the remaining records are not getting inserted and the program fails in betweenwhat i want is even if the 100th record is throwing exception the remaining insertions should happen as usual before my program ends i am not able to understand how to achieve this please suggestedithere is a sample code i am using in my app for batch insert assume that the result set has got approx 10 recordspreparedstatement ps nullwhilersnext retrieve the value and set it to a prepared statement string name rsgetstringname int age rsgetintage pssetint1 age pssetstring2 name finally invoke addbatch psaddbatchfinally call the executebatch methodpsexecutebatchif the 100th record is throwing an exception then i want to trigger the process only from the 100th too 10th record is there some way to do this such that i can restart the process from the record which threw exception onwards till the end again how to achieve this,"['java', 'sql']" +312035,reordering variadic parameters i have come across the need to reorder a variadic list of parameters that is supplied to the constructor of a struct after being reordered based on their types the parameters will be stored as a tuple my question is how this can be done so that a modern c compiler eg g47 will not generate unnecessary load or store instructions that is when the constructor is invoked with a list of parameters of variable size it efficiently pushes each parameter into place based on an ordering over the parameters typeshere is a concrete example assume that the base type of every parameter without references rvalue references pointers or qualifiers is either char int or float how can i make it so that all the parameters of base type char appear first followed by all of those of base type int which leaves the parameters of base type float last the relative order in which the parameters were given should not be violated within sublists of homogeneous base typeexample foofoo is called with arguments float a char b const float c int d char e the tuple tupe is stdtuplechar char int float float and it is constructed like so tuple typestdmoveb e stdmoved a cconsider the struct defined below and assume that the metafunction deduce reordered tuple type is already implemented how would you write the constructor so that it works as intended if you think that the code for deduce reodered tuple type would be useful to you i can provide it it is a little longtemplate class args struct foo assume that the metafunction deduce reordered tuple type is defined typedef typename deduce reordered tuple typeargstype tuple type tuple type t fooargs args t reorder and forward parametersargsargs edit 1the technique i describe above does have applications in mathematical frameworks that make heavy use of expression templates variadic templates and metaprogramming in order to perform aggressive inlining suppose that you wish to define an operator that takes the product of several expressions each of which may be passed by reference reference to const or rvalue reference in my case the expressions are conditional probability tables and the operation is the factor product but something like matrix multiplication works suitably as wellyou need access to the data provided by each expression in order to evaluate the product consequently you must move the expressions passed as rvalue references copy the expressions passed by reference to const and take the addresses of expressions passed by reference using the technique i describe above now poses several benefitsother expressions can use uniform syntax to access data elements from this expression since all of the heavylifting metaprogramming work is done beforehand within the classwe can save stack space by grouping the pointers together and storing the larger expressions towards the end of the tupleimplementing certain types of queries becomes much easier eg check whether any of the pointers stored in the tuple aliases a given pointerthank you very much for your help,['c++'] +312102,how to captured selected text range in ios after text selection expansion i am working on a web app that allows a user to select some text click a button and save the highlighted text this works great in desktop browsers chrome for this example but in ios i am having issues with the native text selection where the user can change the selected text here is the jsfiddle showing the issue issue only exists in ios user starts text selectionuser expands their text selection and clicks show the selected text aboveonly the first selected word the shows up even though i want the path of the righteous man1 begin 2 select text and hit button 3 only the here is the js i am usingfunction actionbuttonclickfunction resulttextselectedrangetostring slipsumonmouseup touchendp function getselectedrange var selectedrange nullvar getselectedrange function if windowgetselection selectedrange windowgetselectiongetrangeat0 else selectedrange documentgetselectiongetrangeat0 ahtml h3selected texth3p idresultpbrp input typebutton idactionbutton valueshow the selected text above p start slipsum code div idslipsumh1is she dead yes or noh1pdo you see any teletubbies in here do you see a slender plastic tag clipped to my shirt with my name printed on it do you see a little asian child with a blank expression on his face sitting outside on a mechanical helicopter that shakes when you put quarters in it no well that is what you see at a toy store and you must think youre in a toy store because youre here shopping for an infant named jeb ph1so you coldh1pthe path of the righteous man is beset on all sides by the iniquities of the selfish and the tyranny of evil men blessed is he who in the name of charity and good will shepherds the weak through the valley of darkness for he is truly his brothers keeper and the finder of lost children and i will strike down upon thee with great vengeance and furious anger those who would attempt to poison and destroy my brothers and you will know my name is the lord when i lay my vengeance upon thee ph1i am serious as a heart attackh1pdo you see any teletubbies in here do you see a slender plastic tag clipped to my shirt with my name printed on it do you see a little asian child with a blank expression on his face sitting outside on a mechanical helicopter that shakes when you put quarters in it no well that is what you see at a toy store and you must think youre in a toy store because youre here shopping for an infant named jeb ph1is she dead yes or noh1plike you i used to think the world was this great place where everybody lived by the same standards i did then some kid with a nail showed me i was living in his world a world where chaos rules not order a world where righteousness is not rewarded that is cesars world and if youre not willing to play by his rules then youre gonna have to pay the price ph1is she dead yes or noh1pyour bones do not break mine do that is clear your cells react to bacteria and viruses differently than mine you do not get sick i do that is also clear but for some reason you and i react the exact same way to water we swallow it too fast we choke we get some in our lungs we drown however unreal it may seem we are connected you and i were on the same curve just on opposite ends pdiv please do not remove this line div stylethisplaynonea hreflorem ipsumadiv end slipsum code a,"['javascript', 'jquery', 'ios']" +312106,how to scale axes in mplot3d i cannot seem to find documentation regarding the ability to scale axes in a 3d image using matplotlibfor example i have the imageand the axes have different scales i would like them to be uniform,['python'] +312108,how to prevent jframe from closing i have a java gui application from which another java gui application is invoked using reflection and loading it works fine the only problem faced is on closing the jframe of invoked application the main gui application frame also closes how can i prevent the main application frame from closingi cannot change the defaultcloseoperation of the invoked application however a change to the main application can be made does it have any thing to do with threadsthis is my applications code that executes a target applicationpublic class classexecutor private classloaderofextclass classloader private byte arrayofclasses private string arrayofbinarynames suppresswarningsrawtypes private arraylistclass loadedclasses private arrayliststring loadedclasesnames private object parameters suppresswarningsrawtypes public classexecutor classloader new classloaderofextclass new arraylistclass loadedclasses new arraylistclass loadedclasesnames new arrayliststring suppresswarningsunchecked public void executefile file string binarypaths object actuals new string method m null try field classesxclassloaderofextclassclassgetdeclaredfieldclasses classesxsetaccessibletrue catch securityexception e1 e1printstacktrace catch nosuchfieldexception e1 e1printstacktrace for int i 0 i filelength i for int j 0 j filelength j try suppresswarningsrawtypes class c classloaderloadclasscustomfilei binarypathsi fied classexclassloadergetresourceclasses catchexception e classclassesxx getloadedclassesclassloader systemoutprintlnloaded classes have size classesxxlength for int i 0 i filelength i try suppresswarningsrawtypes class c classloaderloadclasscustomfilei binarypathsi try if cgetmethodmain new class stringclass null m cgetmethodmain new class stringclass else systemoutprintlnthis class does not contain main continue catch nosuchmethodexception e systemoutprintlnmain not found systemoutprintlnm here eprintstacktrace not printing stack trace catch securityexception e eprintstacktrace catch classnotfoundexception e systemoutprintlnno such class definition exist todo autogenerated catch block eprintstacktrace try minvokenull actuals callstackprint catch illegalargumentexception e todo autogenerated catch block eprintstacktrace catch illegalaccessexception e todo autogenerated catch block eprintstacktrace catch invocationtargetexception e todo autogenerated catch block eprintstacktrace suppresswarnings unchecked rawtypes public void executearraylistbyte stuffedfiles arrayliststring binarypaths converttoarraystuffedfiles binarypaths loadallclassesarrayofclasses arrayofbinarynames object actuals new string method m null method m1 new method10 for class c loadedclasses m1cgetmethods formethod m2 m1 systemoutprintlnm2getname systemoutprintlnloadedclassessize for class c loadedclasses systemoutprintlnctostring systemoutprintlncgetconstructors for int i 1 i filesize i formethod meth cgetmethods methsetaccessibletrue try if cgetmethodmain new class stringclass null m cgetmethodmain new class stringclass break else systemoutprintlnthis class does not contain main continue catch nosuchmethodexception e systemoutprintlnprogram does not contain main catch securityexception e eprintstacktrace try ifparametersnull minvokenull actuals else try systemoutprintlnit fails here minvokenull parameters catch exception e systemoutprintlnillegal arguments callstackprint catch illegalargumentexception e todo autogenerated catch block eprintstacktrace catch illegalaccessexception e todo autogenerated catch block eprintstacktrace catch invocationtargetexception e todo autogenerated catch block eprintstacktrace,['java'] +312113,implementing async timeout using poor mans asyncawait constructs in net 40 motivationc 50 asyncawait constructs are awesome unfortunately yet microsoft only shown a release candidate of both net 45 and vs 2012 and it will take some time until these technologies will get widely adopted in our projects in stephen toubs asynchronous methods c iterators and tasks i have found a replacement that can be nicely used in net 40 there are also a dozen of other implementations that make it possible using the approach even in net 20 though they seem little outdated and less featurerich exampleso now my net 40 code looks like the commented sections show how it is done in net 45private async task processmessageasyncprivate ienumerabletask processmessageasync var udpreceiveresult await udpclientreceiveasync var task taskudpasyncreceiveresult factory fromasyncudpclientbeginreceive udpclientendreceive null yield return task var udpreceiveresult taskresult blah blah blah if message is bootstraprequest var typedmessage bootstraprequestmessage net 40 has no overload for cancellationtokensource that takes timeout parameter var cts new cancellationtokensourcebootstrapresponsetimeout error here blah blah blah saymessageipendpoint responsemessage ctstoken taskfactoryiteratesaymessageipendpoint responsemessage ctstoken looks little ugly though it does the jobthe questionwhen using cancellationtokensource in net 45 there is a constructor that takes timespan as a timeout parameter so that resulting cancellationtokensource cancels within specified period of timenet 40 is not able to timeout so what is the correct way of doing that in net 40,['c#'] +312115,why use gemspec gemfile when checking for dependencies whenever developing gems i do not see any reasons why gemfile is not directly inspected for dependenciesindeed why use a gemspec file in order to list them is there a real benefit,"['ruby-on-rails', 'ruby']" +312132,uiimage to ciimage size is halved i am creating a ciimage from a uiimage as follows ciimage someciimage ciimage imagewithcgimagesomeuiimagecgimagecomparing someciimageextentsizewidthheight with someuiimagesizewidthheight i find that sometimes the ciimage is double size in dimensions and sometimes its the same size as the uiimage it seems like if the uiimage is slightly larger the ciimage is double the size whereas if the uiimage is slightly smaller this is not the case has anyone seen this beforeknow why this is this is causing me real trouble as i am trying to draw a ciimage from a loaded uiimage,"['objective-c', 'ios']" +312159,input type for html form for integer the code below is from an html form if the input is supposed to be an integer do i need to change the typediv classfriend2title label forurladd pointslabeldiv div classfriend2field input namestate typetext idstate maxlength150div,['html'] +312197,adapting model view presenter patter to android with fragment tabs i am working on porting an application from windows mobile to android and i have run into a bit of a problem the existing application uses the mvp pattern and has thistinct presenter classes which are to be reused in the port it is quite an extensive application and rewriting it just is not possible and the c code is all being reused using mono for android these take a view implementing an interface which in android i have achieved by creating activities which implement the appropriate interface instantiating a presenter and passing themselves as an argument this all seems to work fine for our purposes or was until ice cream sandwich came out and i tried to implement it using fragmentsquite a few of the activities utilise tabs and in order to use the action bar and some of the other new features i am trying to convert the tabbed activities to tabbed fragments with a viewpager and this is where i am hitting some problems from what i have read implementing each tab as a fragment seems to be the preferred method but i am confused as to how exactly i can allow the presenter to communicate with the fragment through the activity at the moment the presenter calls the activitys interface methods which then directly access spinners textviews etc to get and set values as requiredas each of these ui elements are declared in the activity this is trivial if i move all of these ui elements to fragments however it does not seem i can access them without implementing a whole new set of interfaces between each activity and fragment i have tried generating a reference in the activity to ui elements in the fragments by getting the fragment root view and then finding the view i want inside that however the viewpager does not always load the fragments so this would not work and even when it has loaded them the layout does not get inflated until the activity is in the running state so i always get null values returned i know it is a bit of a strange question but how can i go about allowing my presenter classes to interact with the ui elements now stored in separate fragment tabs i feel like i must be going about it in completely the wrong way but i just cannot see how it should be done so if anyone could offer some advice on how i could go about it that would be greatthanks very much,['android'] +312200,elasticsearch edgengram highlight term vector bad highlights when i use an analyzer with edgengram min3 max7 front term vectorwith positions offsetswith document having text couchdbwhen i search for coucmy highlight is on cou and not coucit seems my highlight is only on the minimum matching token cou while i would expect to be on the exact token if possible or at least the longest token foundit works fine without analyzing the text with term vectorwith positions offsetswhats the impact of removing the term vectorwith positions offsets for perfomances,['java'] +312211,what is the crossplatform method of enumerating serial ports in python including virtual ports note i am using python 27 and pyserial for serial communicationsi found this article which lists two ways a list of available serial portsthis method works on windows and linux but sometimes misses virtual ports on linuximport serialdef scan scan for available ports return a list of tuples num name available for i in range256 try s serialseriali availableappend i sportstr sclose except serialserialexception pass return availableprint found portsfor ns in scan print d s nsand this one that only works on linux but includes virtual portsimport serial globdef scan scan for available ports return a list of device names return globglobdevttys globglobdevttyusbprint found portsfor name in scan print namei suppose i could do platform detection to use the second method the one that includes virtual ports when running on linux and the first method when running windows but what about machow should i enumerate serial ports virtual too regardless of platformediti found a few pertinent questionsmacpython programmatically finding all serial portsmacos whats the difference between devtty and devcuhow to find all serial devices ttys ttyusb on linux without opening them,['python'] +312231,quick html table sorting yes i know there are a lot of jsjquery programs out there to do this i am currently using it is very easy just a js file add a few class attributes to your table and youre off in particular you do not actually need to know js to use it and you can add custom sort keys without needing to write your own js to extend it i like it a lot for those two reasons the main problem my table is 9300 rows long and sorting takes 1020 seconds so i am wondering are any other scripts out there faster than this these are the ones i have found not even sure what this uses really really nice but not easy to extend requires knowing jsjquery overkill i just need a table sorter not a whole data manipulation program overkill requires jsjquery to extendi am sure there is 50 other programs that can do what i want but i do not have the time to figure out and test them all to see if they are fast thus i would like to know if someone out there on stackoverflow can point me to whichever library they know to be fast so i only have to figure out how to use one programbtw i have seen java sort hundreds of thousands of numbers in milliseconds with quicksort does anyone know what algorithm jssort uses,"['javascript', 'jquery']" +312254,alternative for mysql num rows using pdo right now i have a php file that does a mysql query and then counts rows like thiscountmysql num rowsresultif count 1 message arraystatus ok else message arraystatus errorthis works fine but i am trying to change all my php files to use pdo so how can this be done with pdo,"['php', 'mysql']" +312271,pickle incompatability of numpy arrays between python 2 and 3 i am trying to load the mnist dataset linked here in python 32 using this programimport pickleimport gzipimport numpywith gzipopenmnistpklgz rb as f l listpickleloadf printlunfortunately it gives me the errortraceback most recent call last file mnistpy line 7 in module train set valid set test set pickleloadfunicodedecodeerror ascii codec cannot decode byte 0x90 in position 614 ordinal not in range128i then tried to decode the pickled file in python 27 and reencode it so i ran this program in python 27import pickleimport gzipimport numpywith gzipopenmnistpklgz rb as f train set valid set test set pickleloadf printing out the three objects reveals that they are all pairs containing numpy arrays with gzipopenmnistxpklgz wb as g pickledump train set valid set test set g protocol2 i also tried protocol 0it ran without error so i reran this program in python 32import pickleimport gzipimport numpy note the filename changewith gzipopenmnistxpklgz rb as f l listpickleloadf printlhowever it gave me the same error as before how do i get this to workthis is a better approach for loading the mnist dataset,['python'] +312306,how to chart real time streaming data using areachart in javafx 2 concurrency animation charting requirement build an animated areachart with real time streaming data maybe plot 300 data points every 1 secdetailsso i need to read real time streaming data from a medical device of a patients breathing pattern and thisplay it in a waveform fashion using areachart in javafxi am new to javafx and so i built a small poc to see how concurrency and animation works in javafxthe concept works and i am happy with the basic test as far as implementing the functionality but i am not happy with the performance i am getting from the code belowin the working code below i create a separate thread to simulate data fetching from the medical device the thread just generates a random number and adds it to a concurrentlinkedqueuethe javafx application thread pulls this data out from queue via the timeline and adds it to an areachart seriesthis sort of gives me the animation i need and the data is being added in run time you can copypaste this code and test itit should workbut the performance is not impressive cpu goes to 56 usage i have a intel core 2 duo 253 ghz and 4gb ram on my laptop my graphics card is mobile intel 4 series express with latest driverhow can i improve this animation or plotting of real time data in order to get better performancenote i am willing to compromise on the animation if its the bottle neck i am open to an implementation like shown here where the waveform is just prebuilt and just streaming from right to left import javautilconcurrentconcurrentlinkedqueue import javautilconcurrentexecutorservice import javautilconcurrentexecutors import javautillogginglevel import javautillogginglogger import javafxanimationanimation import javafxanimationkeyframe import javafxanimationsequentialtransition import javafxanimationtimeline import javafxapplicationapplication import javafxeventactionevent import javafxeventeventhandler import javafxscenegroup import javafxscenescene import javafxscenechartareachart import javafxscenechartnumberaxis import javafxscenechartxychartseries import javafxstagestage import javafxutilduration a chart that fills in the area between a line of data points and the axes good for comparing accumulated totals over time see javafxscenechartchart see javafxscenechartaxis see javafxscenechartnumberaxis related chartslinelinechart related chartsscatterscatterchart public class areachartsample extends application private series series private int xseriesdata0 private concurrentlinkedqueuenumber dataq new concurrentlinkedqueuenumber private executorservice executor private addtoqueue addtoqueue private timeline timeline2 private sequentialtransition animation private void initstage primarystage group root new group primarystagesetscenenew sceneroot numberaxis xaxis new numberaxis xaxissetautorangingtrue numberaxis yaxis new numberaxis yaxissetautorangingtrue chart final areachartnumbernumber sc new areachartnumbernumberxaxisyaxis scsetidliveareachart scsettitleanimated area chart chart series seriesnew areachartseriesnumbernumber seriessetnamearea chart series seriesgetdataaddnew areachartdatanumber number5d 5d scgetdataaddseries rootgetchildrenaddsc override public void startstage primarystage throws exception initprimarystage primarystageshow prepare executor services executor executorsnewcachedthreadpool addtoqueuenew addtoqueue executorexecuteaddtoqueue prepare timeline preparetimeline public static void mainstring args launchargs private class addtoqueue extends thread public void run try threadcurrentthreadsetnamethreadcurrentthreadgetiddataadder add random numbers to q dataqaddmathrandom threadsleep50 executorexecuteaddtoqueue catch interruptedexception ex loggergetloggerareachartsampleclassgetnameloglevelsevere null ex timeline gets called in the javafx main thread private void preparetimeline second slower timeline timeline2 new timeline this timeline is indefinite timeline2setcyclecountanimationindefinite timeline2getkeyframesadd new keyframedurationmillis100 new eventhandleractionevent override public void handleactionevent actionevent adatatoseries set animation timeline is created now animation new sequentialtransition animationgetchildrenaddalltimeline2 animationplay private void adatatoseries forint i0i20i add 20 numbers to the plot ifdataqisemptyfalse seriesgetdataaddnew areachartdataxseriesdatadataqremove get rid of a bunch from the chart if seriesgetdatasize 10 seriesgetdataremove09 else return,['java'] +312328,dialogfragment thisappears on rotation despite setretaininstancetrue i have a hello worldish sample app that uses the androidsupportv4 fragments apithe activity consists of a button clicking it will show a dialogfragmenthowever configuration changes like rotation cause the dialog to vanish even if setretaininstancetrue is usedany idea how to fix thisretfragmentjavapackage melocalhellofroyoimport androidosbundleimport androidsupportv4appimport androidutillogimport androidviewpublic class retfragment extends dialogfragment override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setretaininstancetrue override public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate return inflaterinflaterlayouthello dialog fragment container override public void ondestroy superondestroy logeret ondestroy mainactivityjavapackage melocalhellofroyoimport androidosbundleimport androidsupportv4appfragmentactivityimport androidviewviewpublic class mainactivity extends fragmentactivity private static final string tag dlg myfragdlg public void oncreatebundle savedinstancestate superoncreatesavedinstancestate thissetcontentviewrlayoutactivity main public void onshowclickview v retfragment ret new retfragment retshowgetsupportfragmentmanager tag dlg,['android'] +312334,set gesturedetector to all child views i would like to add a gesturedetector to all views view groups of an activity without assigning it manually to every single view right now onfling is only activated when swiping over the background but not when swiping on eg button1package comappexampleimport androidappactivityimport androidcontentcontextimport androidgraphicscolorimport androidosbundleimport androidutillogimport androidviewgesturedetectorimport androidviewmotioneventimport androidviewgesturedetectorsimpleongesturelistenerimport androidviewviewimport androidviewviewontouchlistenerimport androidwidgetbuttonimport androidwidgetlinearlayoutpublic class exampleactivity extends activity context mcontext null override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate mcontext this linearlayout parent new linearlayoutmcontext parentsetorientationlinearlayoutvertical parentsetbackgroundcolorcolorred button button1 new buttonmcontext button1settextbutton 1 button button2 new buttonmcontext button2settextbutton 2 parentaddviewbutton1 parentaddviewbutton2 final gesturedetector gesturedetector new gesturedetector new mygesturedetector parentsetontouchlistenernew ontouchlistener override public boolean ontouchview v motionevent event gesturedetectorontoucheventevent return true setcontentviewparent class mygesturedetector extends simpleongesturelistener override public boolean onflingmotionevent e1 motionevent e2 float velocityx float velocityy right to left ife1getx e2getx 10 mathabsvelocityx 20 logionfling right to left return false left to right else if e2getx e1getx 10 mathabsvelocityx 20 logionfling left to right return false return false,['android'] +312335,reset ef codefirst database in localdb i am using entity framework 50 rc with the localdb database that comes preconfigured with vs 2012 rc for some prototyping and testing of codefirst databaseafter a few cycles of changing my codefirst database and running updatedatabase i did a huge breaking change and automatic migration failed bad i do not care about resolving this conflict since this is just prototyping so losing data is finehow do i reset or delete the database reset must also reset the migration table which seems to be hidden from server explorer in visual studio,['c#'] +312368,retweet reply and favorite in ios 5 twitter with the accounts framework i have integrated ios 5 twitter in my application i am able to send tweets by twtweetcomposeviewcontroller with the integration of twitter and accounts frameworknow i want to retweet reply and favorite in ios 5 with the help of accounts framework,"['iphone', 'objective-c', 'ios']" +312370,replinteractive shell with proper php 53 support i have been using phpsh for a while now and it is worked great in the past but its namespace support still is not very good and this can be pretty frustratingthings like somespacesomeclasomestaticfunction do not work without thisabling the check whether or not a method exists which leads to frequent fatal errors on typos that reset your environmentthere are multiple php repls out there including the php builtin shell php a which is horrible to use does anyone know of an alternative or perhaps a phpshfork with proper namespace support or perhaps an easy configuration fix i have overlookedan examplethis testfilenamespace testingfunction echosome echo somethingtestingechosomeproduces this output in phpsh as expectedphp include pathtestphpsomethingphpbut trying the same call again does not workphp testingechosomenot executing input possible call to undefined function echosomesee etcphpshconfigsample to thisable undefinedfunctioncheckwithout namespaces the function is still availablefunction echosome echo somethingechosomein phpshphp include pathtestphpsomethingand the call still worksphp echosomesomething,['php'] +312381,mysql byte array storage i have a byte array created in java it represents content of some file i do not know exactly the maximum size of this array it can be different sizes i want to store it in mysql what type should i use in mysql,"['java', 'mysql']" +312399,how to apply the textchange event on edittext i developed one simple app like subtraction additionin this app i use three edittexts one for answer and other two for questioni want to calculate the answer of question on text change event but when i apply the text change event on both of this the event occur but not properly work because when i enter in the text in first edittext of question the event occur but it throws this exception0703 163948844 eeduapp log 12537 error in text change event javalangnumberformatexception unable to parse as integerwhat do i doi use the textwatcher for text change eventtxtoneaddtextchangedlistenerthistxttwoaddtextchangedlistenerthispublic void aftertextchangededitable s public void beforetextchangedcharsequence s int start int count int after public void ontextchangedcharsequence s int start int before int count,['android'] +312439,eclipse juno does not start when i launch eclipse it does not startan error appears and tells me to see the log filesee the log file usersmaxworkprojectsmetadatalogos macos 1074eclipse 42 junoadt 20my old version of eclipse starts without issuesession 20120703 162248261 eclipsebuildidi201206081400javaversion160 33javavendorapple incbootloader constants osmacosx archx86 64 wscocoa nlru ruframework arguments product orgeclipseepackagejavaproduct keyring usersmaxeclipse keyring showlocationcommandline arguments os macosx ws cocoa arch x86 64 product orgeclipseepackagejavaproduct keyring usersmaxeclipse keyring showlocationentry orgeclipsecoreresources 2 10035 20120703 162250101message the workspace exited with unsaved changes in the previous session refreshing workspace to recover changesentry orgeclipseequinoxpreferences 4 2 20120703 162256457message problems occurred when invoking code from plugin orgeclipseequinoxpreferencesstack 0javalangexceptionininitializererrorat orgeclipsewbinternalcorepreferencespreferenceinitializerinitializedefaultpreferences preferenceinitializerjava50at orgeclipsecoreinternalpreferencespreferenceserviceregistryhelper1runpreferenceserviceregistryhelperjava300at orgeclipsecoreruntimesaferunnerrunsaferunnerjava42at orgeclipsecoreinternalpreferencespreferenceserviceregistryhelperruninitializerpreferenceserviceregistryhelperjava303at orgeclipsecoreinternalpreferencespreferenceserviceregistryhelperapplyruntimedefaultspreferenceserviceregistryhelperjava131at orgeclipsecoreinternalpreferencespreferencesserviceapplyruntimedefaultspreferencesservicejava368at orgeclipsecoreinternalpreferencesdefaultpreferencesapplyruntimedefaultsdefaultpreferencesjava166at orgeclipsecoreinternalpreferencesdefaultpreferencesloaddefaultpreferencesjava237at orgeclipsecoreinternalpreferenceseclipsepreferencescreateeclipsepreferencesjava410at orgeclipsecoreinternalpreferenceseclipsepreferencesinternalnodeeclipsepreferencesjava663at orgeclipsecoreinternalpreferenceseclipsepreferencesnodeeclipsepreferencesjava805at orgeclipsecoreinternalpreferencesabstractscopegetnodeabstractscopejava38at orgeclipsecoreruntimepreferencesdefaultscopegetnodedefaultscopejava76at orgeclipseuipreferencesscopedpreferencestoregetdefaultpreferencesscopedpreferencestorejava250at orgeclipseuipreferencesscopedpreferencestoregetpreferencenodesscopedpreferencestorejava285at orgeclipseuipreferencesscopedpreferencestoreinternalgetscopedpreferencestorejava475at orgeclipseuipreferencesscopedpreferencestoregetbooleanscopedpreferencestorejava387at orgeclipsewbinternalcoreeditordescriberjavasourceuidescriberisguisourcejavasourceuidescriberjava65at orgeclipsewbinternalcoreeditordescriberjavasourceuidescriberdescribejavasourceuidescriberjava52at orgeclipsecoreinternalcontentcontenttypecatalogdescribecontenttypecatalogjava218at orgeclipsecoreinternalcontentcontenttypecatalogcollectmatchingbycontentscontenttypecatalogjava190at orgeclipsecoreinternalcontentcontenttypecataloginternalfindcontenttypesforcontenttypecatalogjava403at orgeclipsecoreinternalcontentcontenttypecataloginternalfindcontenttypesforcontenttypecatalogjava450at orgeclipsecoreinternalcontentcontenttypecataloggetdescriptionforcontenttypecatalogjava346at orgeclipsecoreinternalcontentcontenttypecataloggetdescriptionforcontenttypecatalogjava360at orgeclipsecoreinternalcontentcontenttypematchergetdescriptionforcontenttypematcherjava86at orgeclipsecoreinternalresourcescontentdescriptionmanagerreaddescriptioncontentdescriptionmanagerjava445at orgeclipsecoreinternalresourcescontentdescriptionmanagergetdescriptionforcontentdescriptionmanagerjava355at orgeclipsecoreinternalresourcesfileinternalgetcharsetfilejava246at orgeclipsecoreinternalresourcesfilegetcharsetfilejava207at orgeclipsecoreinternalresourcesfilegetcharsetfilejava194at orgeclipsejdtinternalcoreutilutilgetresourcecontentsaschararrayutiljava1156at orgeclipsejdtinternalcorebuildersourcefilegetcontentssourcefilejava79at orgeclipsejdtinternalcompilerreadmanagerrunreadmanagerjava173at javalangthreadrunthreadjava680caused by orgeclipseswtswtexception invalid thread accessat orgeclipseswtswterrorswtjava4361at orgeclipseswtswterrorswtjava4276at orgeclipseswtswterrorswtjava4247at orgeclipseswtwidgetsthisplayerrorthisplayjava1068at orgeclipseswtwidgetsthisplaycheckdevicethisplayjava621at orgeclipseswtgraphicsdevicegetsystemfontdevicejava476at orgeclipsejfacepreferencepreferenceconverterclinitpreferenceconverterjava84 35 moreentry orgeclipseosgi 4 0 20120703 162259978message application errorstack 1javalangnoclassdeffounderror could not initialize class orgeclipsejfacepreferencepreferenceconverterat orgeclipseuiinternalthemesthemeelementhelperinstallfontthemeelementhelperjava103at orgeclipseuiinternalthemesthemeelementhelperpopulateregistrythemeelementhelperjava59at orgeclipseuiinternalworkbench27runwithexceptionworkbenchjava1550at orgeclipseuiinternalstartupthreadingstartuprunnablerunstartupthreadingjava31at orgeclipseswtwidgetsrunnablelockrunrunnablelockjava35at orgeclipseswtwidgetssynchronizerrunasyncmessagessynchronizerjava135at orgeclipseswtwidgetsthisplayrunasyncmessagesthisplayjava3944at orgeclipseswtwidgetsthisplayreadandthispatchthisplayjava3621at orgeclipseuiinternalworkbenchrunuiworkbenchjava2478at orgeclipseuiinternalworkbenchaccess7workbenchjava2386at orgeclipseuiinternalworkbench5runworkbenchjava583at orgeclipsecoredatabindingobservablerealmrunwithdefaultrealmjava332at orgeclipseuiinternalworkbenchcreateandrunworkbenchworkbenchjava540at orgeclipseuiplatformuicreateandrunworkbenchplatformuijava149at orgeclipseuiinternalideapplicationideapplicationstartideapplicationjava124at orgeclipseequinoxinternalappeclipseapphandleruneclipseapphandlejava196at orgeclipsecoreruntimeinternaladaptoreclipseapplauncherrunapplicationeclipseapplauncherjava110at orgeclipsecoreruntimeinternaladaptoreclipseapplauncherstarteclipseapplauncherjava79at orgeclipsecoreruntimeadaptoreclipsestarterruneclipsestarterjava353at orgeclipsecoreruntimeadaptoreclipsestarterruneclipsestarterjava180at sunreflectnativemethodaccessorimplinvoke0native methodat sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava39at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava25at javalangreflectmethodinvokemethodjava597at orgeclipseequinoxlaunchermaininvokeframeworkmainjava629at orgeclipseequinoxlaunchermainbasicrunmainjava584at orgeclipseequinoxlaunchermainrunmainjava1438entry orgeclipsecorejobs 4 2 20120703 162305824message an internal error occurred during android library updatestack 0javalangnullpointerexceptionat comandroidideeclipseadtadtplugingetoutstreamadtpluginjava1714at comandroidideeclipseadtinternalprojectlibraryclasspathcontainerinitializerallocatelibrarycontainerlibraryclasspathcontainerinitializerjava264at comandroidideeclipseadtinternalprojectlibraryclasspathcontainerinitializerupdateprojectslibraryclasspathcontainerinitializerjava81at comandroidideeclipseadtinternalsdksdk31runsdkjava1197at orgeclipsecoreinternaljobsworkerrunworkerjava54entry comandroidideeclipseadt 4 0 20120703 162305998message parsesdkcontent failedstack 0javalangnullpointerexceptionat comandroidideeclipseadtadtplugingetthisplayadtpluginjava334at comandroidideeclipseadtadtplugin7runadtpluginjava1422at orgeclipsecoreinternaljobsworkerrunworkerjava54entry orgeclipsecorejobs 2 2 20120703 162306504message job found still running after platform shutdown jobs should be canceled by the plugin that scheduled them during shutdown comandroidideeclipseadtinternalsdksdk5entry orgeclipsecorejobs 2 2 20120703 162306505message job found still running after platform shutdown jobs should be canceled by the plugin that scheduled them during shutdown comandroidideeclipseadtinternalsdksdk5,['android'] +312450,visualization of calendar events algorithm to layout events with maximum width i need your help with an algorithm it will be developed on client side with javascript but does not really matter i am mostly interested in the algorithm itself laying out calendar events so that each event box has maximum width please see the following picturey axis is time so if test event starts at noon for example and nothing more intersects with it it takes the whole 100 width weekly review intersects with tumbling ymca and annaamelia but the latter two are not intersecting so they all fill up 50 test3 test4 and test5 are all intersecting so max width is 3 for each but test7 is 66 since test3 is 33 fixed see above so it takes all available space which is 66 i need an algorithm how to lay this outthanks in advance,['javascript'] +312454,decimaltryparse does not parse my decimal value when i tried to convert something like 01 from user in textbox my value b is always false bool b decimaltryparse01 out valuehow can it be here to work,['c#'] +312460,oneditoraction is not called after enter key has been pressed on jelly bean emulator i am having a problem with the behavior of the latest jelly bean emulator i have several edittexts in my app an oneditoractionlistener provides special handling when a user presses the enter key on the keyboard this worked up until ics but now on jelly bean the listener callback method oneditoraction no longer gets called only a new line is inserted into the edittextthis can be reproduced this wayedittext testedittext new edittextcontexttestedittextsetoneditoractionlistenernew oneditoractionlistener public boolean oneditoractiontextview v int actionid keyevent event logdtag oneditoraction called return false addviewtestedittextis this a bug in jelly bean or in the emulator or has the behavior been changed intentionallycuriously someone else writes that the method gets called but with unexpected parameters on a nexus 7 running jelly bean here null keyevent and actionid 0 in oneditoraction jelly bean nexus 7,['android'] +312493,call a function in one javascript file from another javascript file i need to call a function in an external js file from another js file without referencing the external file in the head tagi know that it is possible to dynamically add an external js file to the which allows access to that file i can do that like sovar appfile testtestapp 1js var newscriptdocumentcreateelementscriptvar headid documentgetelementsbytagnamehead0 newscriptsrc appfileheadidappendchildnewscripthoweverthis is no use to me as the external files need to be standalone files that run startup procedures ondocumentreadyfunctionso adding the full file dynamically has an unwanted affect also i cannot prereference the external file in the head tag as it needs to be dynamicso this external file testtestapp 1js contains a function that returns a string variablefunction setapplogo var logofile testtestapp 1 logopng return logofile i need access to either this function or i could store the string as a global var in the external file either way is fine i just need access to the value in logofile without loading the whole external filethis one has had me stumped for a few hours now so any ideas would be greatly appreciated,"['javascript', 'jquery']" +312494,how to set combined color for overlapped area of two different color objects i am creating different custom views with two different colors according to my app features user will drag those objects on the screen when dragging objects will overlap each other i want to differentiated the overlapped area how to set the combined color for overlapped arealook at the below image here i am using canvas for creating those custom views two circles are two different views edit if i use opacity 128 i am able to see the background color but i want the combination color of overlapped objects colors,['android'] +312504,passing array of parameters through get in rails how do i pass array of parameters through get method in rails currently my url loocs like thishttplocalhost30jobs1017editing job suites1017editing member jobsnewids1025ids1027how can i pass the array with get method but avoid ids1025ids1027 partrequest is being sent with javascript windowopen method is there any workaround to send not ajax post request,['ruby-on-rails'] +312524,thisable g note candidates are compiler message many times when i compile something with a typo or some other typing mismatch i get the standard error no match for functionname in error this is great then especially in the case of overloaded functions and operators g goes on and list like 10 pages of candidates which are just hideous and massive template definitionsthe error message is great but is there any way to thisable it from suggesting other functions variants,['c++'] +312556,in c11 how do i specify that the implicit this parameter carries dependency in dclattrdepend1 i readthe attribute carries dependency may be applied to the declaratorid of a parameterdeclaration in a function declaration or lambda in which case it speciies that the initialization of the parameter carries a dependency to 110 each lvaluetorvalue conversion 41 of that object the attribute may also be applied to the declaratorid of a function declaration in which case it specifies that the return value if any carries a dependency to the evaluation of the function call expressionwhat i am missing is a way to apply the attribute to the implicit this parameterby way of example consider this free functionvoid funint i foo carries dependency fand it is equivalent but for the attribute member versionvoid foofunint i cannot add carries dependency here,['c++'] +312569,how to recursively call a macro in jinja2 this is my jinja template to generate c code from my data modelusing systemnamespace domainns for class in domaincontent public class classname region inners classinnerclass endregion region props for field in classcontent if fieldreadonly true set readonlyprivate else set readonly endif public fieldtype fieldname get readonly set if fieldconstraint fieldname value else throw new exceptioninserted value for fieldname is not valid endfor endregion endfor this is my question for generate inner classes i want to recursively loop on my data model how i can pass the classinnerclass as a parameter to my first for statement,['python'] +312575,table row borders in html5 without gaps this seems trivial enough but i cannot seem to stumble upon the answeri want to have lines separating my rows in an html table and nothing more simple enough right some googling brought me upon the table attribute rules but apparently this is not supported in html5so i searched deeper into css and realized i could put borders around the trs right well no not only does that not work but many so threads assured me its a bad idea logically i played with their solutions which involved different combinations of tr borderbottom but i always end up with this tiny obnoxious gap what gap there is about a pixel or two gap between the two tds where a line separating columns would be this may not seem like a big deal but it seems unnecessary and i cannot stop noticing it for whatever reason however it does not appear in jsfiddle so i suggest trying this in notepad and opening it in the browseram i making a silly mistake is it a typo just my computer any help would be greatly appreciated i have been staring at this for too long heres my test file that i have been mostly testing in chrome and android it really needs to work in both as this will also run in a phonegap app that renders html5 in the phone browserhtmlhead style td th borderbottom 1px solid black important styleheadbody table tr thitemth thaisleth tr tr tdcookiestd td2td tr tr tdcrackerstd td6td tr tr tdmilktd td8td tr tr tdcerealtd td2td tr tablebodyhtml,['css'] +312582,default case in a switch condition i have this code includestdioh int main int a10 switcha case 1 printfonen break case 2 printftwon break defalut printfnonen return 0 the program does not print anything not even none i figured out that default had a typo defaluti want to know why this syntax error is not detected by the compiler,['c'] +312595,c not releasing memory after task complete the following code is a simplified example of an issue i am seeing this application consumes approx 4gb of memory before throwing an exception as the dictionary is too big class program static void mainstring args program program new program whiletrue programmethod consolereadline public void method wasteofmemory memory new wasteofmemory task tast new taskmemorywastememory taststart public class wasteofmemory public void wastememory dictionarystring string amassivelist new dictionarystring string try long i 0 while true amassivelistadditostring i am a line of text designed to waste space i am exceptionally useful i catchexception e consolewritelinei have broken myself this is all as expected although what we cannot currently work out is when this memory should be released from the clr we have let the task complete and then simulated a memory overload situation but the memory consumed by the dictionary is not released as the os is running out of memory is it not putting pressure on the clr to release the memoryhowever and even more confusing if we wait until the task has completed then hit enter to run the task again the memory is released so obviously the previous dictionary has been garbage collected has not itso why is the memory not being released and how can we get the clr to release the memory any explanations or solutions would be greatly appreciatededit following replies particularly beskas it is obvious my description of the issue is not the the clearest so i will try to clarifythe code may not be the best example sorry it was a quick crude piece of code to try to replicate the issuethe dictionary is used here to replicate the fact we have a large custom data object which fills a large chunk of our memory and it is not then released after the task has completedin the example the dictionary fills up to the limit of the dictionary and then throws an exception it does not keep filling forever this is well before our memory is full and it does not cause an outofmemoryexception hence the result is a large object in memory and then the task completesat this point we would expect the dictionary to be out of scope as both the task and the method method have completed hence we would expect the dictionary to be garbage collected and the memory reclaimed in reality the memory is not freed until method is called again creating a new wasteofmemory instance and starting a new taskhopefully that will clarify the issue a bit,"['c#', '.net']" +312617,sharedpreferences from different activity i load from activity a the sharedpreferences in following wayprivate void savepreferencesstring key string value sharedpreferences sharedpreferences preferencemanagergetdefaultsharedpreferencesthis sharedpreferenceseditor editor sharedpreferencesedit editorputstringkey value editorcommitat activity b i want to load the sharedpreferences following was a nullpointerexceptionprivate void loadpreferences sharedpreferences sharedpreferences preferencemanagergetdefaultsharedpreferencesthis data sharedpreferencesgetstringname 0800 if i try following i get this compilation error no enclosing instance of the type a is accessible in scopeprivate void loadpreferences sharedpreferences sharedpreferences preferencemanagergetdefaultsharedpreferencesathis data sharedpreferencesgetstringname 0800 how can i access the data,['android'] +312632,creating a mongodb capped collection using c api using the c mongodb driver we currently create our collection like somongoserver mongoserver mongoservercreatesome conn strmongodatabase db mongoservergetdatabasemydbmongocollection logs dbgetcollectionmycolli would like to use mycoll as a capped collection i have not seen any examples or documentation specifics on how to create a capped collection using the c driver i have found tons of js examples and even a java example here creating a mongodb capped collection in java has anyone had to do this before or know if it is possible in c,"['c#', '.net']" +312684,split array into chunks of and length how to split an array which has 10 items into 4 chunks which contain a maximum of n itemsvar a a b c d e f g h i ja function splits it to four arraysconsolelogb c d eand it printsa b cd e fj h ijthe above assumes n 3 however the value should be dynamicthanks,['javascript'] +312686,change actionbar tabs background color is there a way to change the background color of the tab bar in the actionbar without changing it in the one line versionto clarify what i want in portrait mode the actionbar is split in two lines the actionbar itself and the tabs below in landscape mode the tabs are in the actual actionbari want to change the background color of the portrait mode if i change the background in the tabview it will be changed for both modes do i have to create separate styles for those which brings up a second question is there a way to know when it will be two lines and when notor am i just missing somethingi am using actionbarsherlock btw,['android'] +312700,avaudiosessioncategoryplayandrecord with airplay my app uses the microphone and outputs audio so i am setting my audio session to the play and record category but this seems to thisable airplay if i set the category to play airplay works fine with my output but obviously the input does not worki have tried overriding the output route to speaker in case it needed that to output over airplay but no joyany ideas,['ios'] +312701,c as principal class or a cocoa app without objc for those who question my sanitytimewastingabilitymotives this thing is a port of the foundation with a spoon project now infamous for being an allc ios app so i have got a c file raring to go and be the main class behind an allc macapp however a combination of limiting factors are preventing the application from being launched as it currently stands the project is just a mainm and a class called appdelegatec so i entered appdelegate as the name of the principal class in the infoplist and to my complete surprise the log printedunable to find class appdelegate exitingthis would work perfectly well in ios because the main function accepts the name of a delegate class and handles it automatically but nsapplicationmain takes no such argumentnow i know this stems from the fact that there are no interfaceimplementation directives in c and that is really what the os seems to be looking for so i wrote a simple nsapplication subclass and provided it as the principal class to the plist and it launched perfectly well my question is how could one go about setting a c file as the principal class in a mac application and have it launch correctlyedit solved the file may be a m framework errors for some reason but the allocation of class pairs is enough to slip by you can download the source for the cbased mac app here happy diggingthe codes been written signed sealed and stamped but all i need is a way around the nsprincipalclass requirement in the plist,"['objective-c', 'c']" +312708,how to obtain application context from broadcast receiver i have an extension of the application class that i need to obtain reference in a broadcastreceiver i have created the context passed into the onreceive is a restricted context is there a way to obtain reference to the actual application context,['android'] +312712,php posting json via file get contents i am trying to post json content to a remote rest endpoint however the content value appears to be empty on delivery all other headers etc are being received correctly and the web service tests successfully with a browser based test clientis there a problem with my syntax below where i specify the content fielddata arrayusername duser firstname demo surname user email data string json encodedataresult file get contents null stream context createarrayhttp arraymethod postheader arraycontenttype applicationjsonrn authorization usernamekeyrn contentlength strlendata string rncontent data stringecho result,['php'] +312713,cannot get the facebook publish action permission on ios i have spent hours on this and cannot get it to work basically i just want a button in my app that will like itself on facebooki have created the app on dev facebook and have an associated app pagein my code i request these permissions permissions nsarray arraywithobjectspublish stream publish actions user birthday nili can retrieve a profile picture fine but when i try to like using this codensmutabledictionary params nsmutabledictionary dictionarywithobjectsandkeys facebookaccesstoken access token nil facebook requestwithgraphpath329756493773381oglikes andparamsparams andhttpmethodpost anddelegateselfi get this error responsefacebookerrdomain error 10 userinfo0x20090590 error code 200 message 200 requires extended permission publish actions type oauthexceptionwhen logging in on the app facebook asks me for permission to see my birthday and tells me it will post on my behalf but it seems to not get the publish actions permissionis there something i am missing that i need to doi see temple run has a facebook like button and offers bonus coins for pressing it this is what i wish to achieveedit i have changed my permissions to just publish actions user birthday and now the auth dialogue saysthis app may post on your behalf including objects you liked and morewhich seems to be the publish actions permission however i was still getting the errormessage 200 requires extended permission publish actionsi have changed this line facebook requestwithgraphpath329756493773381oglikes andparamsparams andhttpmethodpost anddelegateselrfto this facebook requestwithgraphpath329756493773381oglikes anddelegateselfand i do now get a response back although it does not post a likethis is the result response data paging next sdk version2access tokenbaageap3zbgwobapicjlgb5zk0yecyp8yelf8hjomrx8qs4vjezak5plxfavbgm1jyxhe0wzbvu0abeczcutzbejqgoj44caiqsrg64tfrhdxjmqwdformatjsonoffset25limit25 any idea what to try nextedit 2 i am making progress with thisi have added the users id to the graph request like thisnsstring graphpath nsstring stringwithformatoglikesfacebookidand used these parametersnsmutabledictionary params nsmutabledictionary dictionarywithobjectsandkeys ageap3zbgwobabvkjspzaoqqng9cdpji2v2ti8acyypsntm9zbkfydhqvzajskwsbluvfwxyxsrcts7kfzcnh7y6f5pfnlwb6smf8xf33wlrzbgflyht1 access token object niland now i get a like showing up on my timeline i was using the accesstoken supplied by the facebook login but it seems the one supplied by the graph object is differentnow the like that i am seeing has this patterndarren likes object on myappis it even possible to have it asdarren likes myapp with it linking to the app facebook pagethanks,['ios'] +312717,getting fonts to work in rails 31 i do not know whats wrong it seems like i am doing this right i am trying to use font awesome in my application but the font does not appear i have a folder called fonts and in my applicationrb included the line class application railsapplication enable the asset pipeline configassetsenabled true this line configassetspaths railsrootjoinapp assets fontsand than instead of having the 2 css files that come with fontawesome changed see below did not need the ie7 one i just put the main css inside of my applicationcss than i change the urls to detect the font files fontface fontfamily fontawesome src url asset pathfontawesomewebfonteot src url asset pathfontawesomewebfontwoff formatwoff url asset pathfontawesomewebfontf formattruetype url asset pathfontawesomewebfontsvgfontawesome formatsvg fontweight normal fontstyle normali turned off the server and restarted after each change to the code but still no good what am i missingupdatei am not using sass or less maybe the fontface is the issue i never seen this type of code use beforeupdatei am now using the fontawesomecss file but its not showing up in my source codehead link hreffaviconico relshortcut icon typeimagevndmicrosofticon link hrefassetsapplicationcssbody1 mediascreen relstylesheet typetextcss link hrefassetschosencssbody1 mediascreen relstylesheet typetextcss script srcassetsjqueryjsbody1 typetextjavascriptscriptstyle typetextcstyle script srcassetsjquery ujsjsbody1 typetextjavascriptscript script srcassetsapplicationjsbody1 typetextjavascriptscript script srcassetschosenjqueryminjsbody1 typetextjavascriptscriptheadfull answerthis is how you can get it fontawesome working with inserting it normallyquote from 1 download fontawesome from 2 put the font folder font folder in the appassets i renamed the folder from font to fonts to make it clearer3 add configassetspaths railsrootappassetsfonts to configapplicationrb this is to include the appsassetsfonts folder in the asset pipeline4 put the fontawesomecss file in the appassetsstylesheets folder5 the first part of the css should befontface fontfamily fontawesome src urlfontawesomewebfonteot src urlfontawesomewebfonteotiefix formatembeddedopentype urlfontawesomewebfontwoff formatwoff urlfontawesomewebfontf formattruetype urlfontawesomewebfontsvgzfontawesomeregular formatsvg urlfontawesomewebfontsvgfontawesomeregular formatsvg fontweight normal fontstyle normalyou should then be able to usediv stylefontsize 24px i classiconcameraretroi iconcameraretrodiv,"['ruby-on-rails', 'ruby']" +312719,cmd click to move status item the built in battery wifi sound etc apple supplied status items can be dragged to any position on the menu by using cmd click and draghow can i support similar functionality in my own status item,['objective-c'] +312803,python how to send post request i found this script onlineimport httplib urllibparams urlliburlencodenumber 12524 type issue action showheaders contenttype applicationxwformurlencoded accept textplainconn httplibhttpconnectionbugspythonorgconnrequestpost params headersresponse conngetresponseprint responsestatus responsereason302 founddata responsereaddataredirecting to a hrefaconnclosebut i do not understand how to use it with php or what everything inside the params variable is or how to use it can i please have a little help with trying to get this to work also i am using python 32,['python'] +312810,custom progress bar android i want to use this type of progress bar in android i have tried with many horizontal progress bars they are all looking like default progress bars with different colors dont know how to use this type,['android'] +312824,need for separate interface and impl for dao we have a typical ntier java application and i noticed that our data access layers has daos that are of the type foodao and foodaoimpl i was looking to justify the need for the two and here is my analysisif you had multiple implementation for the same interface the abstraction is helpful but given that we have already made the choice of the framework to be used for the daoimpl say ibatis is it really requiredhelp in proxying via spring from what i gather classes that have interfaces can be proxied easily going the jdkproxy route rather than classes that have no interfaces where the cglib route is chosen and one has the subclass the class to be proxied subclassing has its problems where the class to proxied is final or has none default constructors both of which are highly unlikely at the data access layer performance used to be a factor but from what i hear it is no longer a cause of concernhelp in mocking classes with interfaces are more suited to be mocked by mocking frameworks i have only heard this but not seen it in practice so cannot really count on it but maybe because of the same factors as mentioned in 2 abovewith these points i do not feel the real need for a separate foodao and foodaoimpl where a simple foodao should suffice feel free to correct any of the points that i have mentionedthanks in advance,['java'] +312833,google maps api version difference i am trying to show route between two places i want to used google places api v3 for route steps between two pointsbefore i was using old google maps api and following request gives perfect resulthlensaddr195217608992615823daddr1953122499248262ieutf80om0outputkmloutput now i try to replace this with new google maps api and following request gives wrong result in both case i am using same source and destination but result gives different behavior on google mapdestination1953122499248262sensorfalsemy problem is that new google maps api return less number of steps between source and destination therefore the route not showing perfect on google mapplease help to resolve this problem for new google maps api v3thanks in advance,['android'] +312872,use highchart and highstock on the same page i have this pagescript typetextjavascript srcjqueryhighchartshighstock116jsscriptscript typetextjavascript srcjqueryhighchartshighcharts214jsscriptand in the page i use getjson serverindiceserverphprow row item item null functiondata chartindice new highchartschart chart renderto graph defaultseriestype line zoomtype x moore setting series type area name titleindice data indice showinlegend false thisable the the showhide icon and an highstock graphwindowchart new highchartsstockchart chart renderto charthistory rangeselector selected 2 series data history type spline tooltip valuedecimals 2 and they cannot work together just one or the other what can i do,"['javascript', 'jquery']" +312876,why swapping integer variable by xor does not work in a single line i want to swap the value of two integer variables in java using the xor operatorthis is my codeint i 24int j 17i jj ii jsystemoutprintlni i t j jit will work fine but the following equivalent code does not workint i 24int j 17i j i jsystemoutprintlni i t j joutput is like thisi 0 j 24first variable is zero whats wrong with java,['java'] +312894,get data from gcm notification is there a way to get data from gcm notification here is a part of my json string which i send with gcm dataid123 i need get value of id in my app but i do not know how thanks a lot,['android'] +312902,how to test boot completed broadcast receiver in emulator i want to check the broadcast receiver with action boot completed in the emulatoris there any way to check that broadcast receiver in emulator how can i restart emulator to check that receiver is there any direct commandthanks in advance,['android'] +312927,jquery validator validate alphanumeric space and dash i have jquery validation plugins installed on my websitei am using this code to validate alphanumeric from text field and it works but it does not allow space and dash validatoraddmethodtitlealphanum functionvalue element param return valuematchnew regexp param how to make it works with space and dash thanks,"['php', 'jquery']" +312942,the perfect way to validate and test rails 3 associations using rspecremarkable i am still pretty new to testing in rails 3 and i use rspec and remarkable i read through a lot of posts and some books already but i am still kind of stuck in uncertainty when to use the associations name when its idclass project activerecordbase has many tasksendclass task activerecordbase belongs to projectendbecause of good practice i want to protect my attributes from mass assignmentsclass task activerecordbase attr accessible project or is it project id belongs to projectendfirst of all i want to make sure that a project never exists without a valid taskclass task activerecordbase validates project presence true which one is the validates project id presence true right way to goendi also want to make sure that the assigned project or project id is always validclass task activerecordbase validates project associated true again which one is validates project id associated true the right way to goendand do i need the validation on presence when i use associatedthanks a lot for clarifying it seems that after hours of reading and trying to test stuff using rspecshouldaremarkable i do not see the forest because of all the trees anymore,['ruby-on-rails'] +312956,multilingual wpf application i have a wpf application in english and i would like to let users to select different languages i have read some possibilities to change languages in runtime applications but i only want to choose a language during installation time and never change itdo you think the fastest and easiest way to do it is developing different versions of the program changing only text language and let the user to select one of them during the installation probably to repeat code only changing textbox or labels is not very elegant but notice that i have the application finished in english and i dona t need to change language at runtime,"['c#', '.net']" +312986,performance of uiview removefromsuperview vs hide this question is really basic what is the performance difference between removing a uiview from the view hierarchy and hiding a uiviewi have read that views that are not needed should be removed from the view hierarchy i currently have the situation that a uibutton should sometimes be visible when do i hide the uibutton and when do i remove it from it is superviewis it expensive to change the view hierarchy,"['ios', 'objective-c']" +312990,is python strongly typed i have come across links that say python is a strongly typed languagehowever i thought in strongly typed languages you could not do this bob 1bob bobi thought a strongly typed language did not accept typechanging at runtime maybe i have got a wrong or too simplist definition of strongweak typesso is python a strongly or weakly typed language,['python'] +312992,check if list item contains items from another list i have a listsmy list abc123 def456 ghi789 abc456 def1 qwe1bad abc defand want to search for items that contain the string abc and def and others in bad how can i do thatalmost same question here,['python'] +313030,core data is it possible to use custom function in group by is it possible to use custom function strftime in group by part when crafting nsfetchrequest in objectivec the sql statements is perfectly valid in sqliteselect date count from note group by strftimeymd datehowever after a day of digging and trying various ways and solutions i came to the conclusion it is impossible to do it with core data in single sql fetch i am using nsfetchrequest with setpropertiestogroupby ios 50 only update there is an example for getting such behavior with core data provided by apple however i have enabled comapplecoredatasqldebug 1 for showing sql performed by core data it appears core data is not performing my desired sql it just selects them all with a first sql query and then loops through the groups performing multiple selec where id in sql queries an excerpt from console20120705 103457244 datesectiontitles1139fb03 coredata sql select 0 t0z pk from zevent t0 order by t0ztimestamp20120705 103457245 datesectiontitles1139fb03 coredata annotation sql connection fetch time 010s20120705 103457246 datesectiontitles1139fb03 coredata annotation total fetch execution time 015s for 52 rows20120705 103457247 datesectiontitles1139fb03 coredata sql select 0 t0z pk t0z opt t0ztimestamp t0ztitle from zevent t0 where t0z pk in order by t0ztimestamp limit 2020120705 103457248 datesectiontitles1139fb03 coredata annotation sql connection fetch time 012s20120705 103457249 datesectiontitles1139fb03 coredata annotation total fetch execution time 022s for 20 rows20120705 103457250 datesectiontitles1139fb03 coredata sql select 0 t0z pk t0z opt t0ztimestamp t0ztitle from zevent t0 where t0z pk in order by t0ztimestamp limit 2020120705 103457281 datesectiontitles1139fb03 coredata annotation sql connection fetch time 00303s20120705 103457281 datesectiontitles1139fb03 coredata annotation total fetch execution time 00310s for 20 rows,"['iphone', 'objective-c']" +313033,porting libcurl on android with ssl support i am trying to port libcurl to android with ssl support step one would be to port the curl without ssl support i guess so i started doing that but i run into a problemas i read on the dev website and in the androidmk file the hard part is configuring the make first so what i did is download android source code and compile it since some of the intermediate libs are neededdownload curl unpack curl under android srcexternalcurlmake the configure script for curl by creating a sh file in the externalcurl folder with this content export ahomeuserdevelopmentaosp233 export ccaprebuiltlinuxx86toolchainarmeabi421binarmeabigcc export ndkhomeuserdevelopmenttoolssdkandroidndkexport ndklibsndkplatformsandroid4archarmusrincludeexport sysrootandkbuildplatformsandroid4archarm export cppflagsi asystemcoreincludeexport ldflagslaouttargetproductgenericobjlib laouttargetproductgenericsystemliblsysrootusrlib wlgcsections nostdlib lc lm ldl llog lgcc wlnoundefinedznocopyreloc wldynamiclinkersystembinlinker lndkouttargetproductgenericobjlib export cflagsfnoexceptions wnomultichar mthumb mthumbinterwork nostdlib lc ldl lm marcharmv5te mtunexscale msoftfloat mandroid fpic mthumbinterwork mthumb mlongcalls ffunctionsections fstackprotector fnoshortenums fomitframepointer fnostrictaliasing finlinelimit64 d arm arch 5 d arm arch 5t d arm arch 5e d arm arch 5te dandroid dos android d new d sgi stl internal pair h isysrootusrinclude i asystemcoreinclude i ndklibs configure hostarmeabi withsslaexternalopenssland the output summary is this one configure configured to build curllibcurl curl version 7260 host setup armunknowneabi install prefix usrlocal compiler hometancodevelopmentaosp233prebuiltlinuxx86toolchainarmeabi421binarmeabigcc ssl support no withsslgnutlsnsspolarsslcyasslaxtls ssh support no withlibssh2 zlib support enabled krb4 support no withkrb4 gssapi support no withgssapi spnego support no withspnego tlssrp support no enabletlssrp resolver default enableares enablethreadedresolver ipv6 support no enableipv6 idn support no withlibidn build libcurl sharedno staticyes builtin manual enabled libcurl option enabled thisablelibcurloption verbose errors enabled thisableverbose sspi support no enablesspi ca cert bundle etcsslcertscacertificatescrt ca cert path no ldap support no enableldap withldaplib withlberlib ldaps support no enableldaps rtsp support enabled rtmp support no withlibrtmp protocols dict file ftp gopher http imap pop3 rtsp smtp telnet tftp soname bump yes warning this library will be built with the soname number bumped due to a detected abi breakage see libreadmecurl off t for details on thisfirst strange thing that comes to mind is why is ssl not included in the config since the linker shows to the intermediate libs and ssl support flag is called but after when i use the same curl configh file in the jni project which i created for the build since it has a standalone androidmk file it can be compiled simply by unzipping in the jni folder of a android project copying the config file created in the aosp source and calling ndkbuild so i compile and i get ndkbuildcompile thumb curl urlcin file included from projectstemptestndkjniliburlc320toolssdkandroidndkplatformsandroid14archarmusrincludeunistdh in function getpagesizetoolssdkandroidndkplatformsandroid14archarmusrincludeunistdh1713 warning nested extern declaration of page size wnestedexternstoolssdkandroidndkplatformsandroid14archarmusrincludeunistdh in function getpageshifttoolssdkandroidndkplatformsandroid14archarmusrincludeunistdh1753 warning nested extern declaration of page shift wnestedexternsprojectstemptestndkjniliburlc at top levelprojectstemptestndkjniliburlc572 error error we cannot compile without socket supportmake projectstemptestndkobjlocalarmeabiobjscurlliburlo error 1,['android'] +313042,strip php variable replace white spaces with dashes how can i convert a php variable from my company my name to mycompanymynamei need to make it all lowercase remove all special characters and replace spaces with dashes,['php'] +313058,international chars using rspec with ruby on rails i have just started using rspec and i copied the very simple test on the rspec github repo just to make sure things are working as expectedrequire spec helperdescribe home page do it welcomes the user do visit products pageshould have contentwelcome endendthe problems begin when i change the string to something like ola or camba any string with a special character when i do that i get the following errorinvalid multibyte char usascii syntaxerrorinvalid multibyte char usasciisyntax error unexpected end expecting pageshould have contentolaany ideas on how to fix it maybe some configuration option thanks a lot,"['ruby-on-rails', 'ruby']" +313073,fann error 11 unable to allocate memory in the python implementation of fann i got this error fromfrom pyfann import libfannann libfaneural netanncreate standard4 2 8 9 1fann error 11 unable to allocate memoryany suggestion,['python'] +313096,how to right align preferencesactivity in android i have preferencesactivity which i need it to be right aligned because i want to use arabic language i tried to use androidlayout gravityright for preferencescreen but it did not workthis is my xmlpreferencescreen xmlnsandroid androidlayout gravityright preferencecategory androidtitlegeneral settings checkboxpreference androidtitlefull screen androiddefaultvaluefalse androidsummaryalways view as full screen androidkeyfullscreenpref preference androidtitlereport bugs androidsummarynotify us for any bugs or errors androidkeybugs preference androidtitleabout androidsummaryversion 100 androidkeyabout preferencecategorypreferencescreenthis is how i use the xml inside preferencesactivityaddpreferencesfromresourcerlayoutpreferences,"['java', 'android']" +313118,twitter bootstrap how to remove gradient mixin in subclass i want to subclass navbarinner in my custom theme but i cannot figure a nonhackish way to thisable gradient apart from setting both gradient colors to same color which seems dirty any idea how can i override thisable a mixin from a subclass in less,['css'] +313121,how to run composer from anywhere i have just installed composer in my usrbin folder so when from that folder i run php composerphar i get the help info about composer but when i try to run the same from other folder i get could not open input file composerphar how to call php composerphar from every where without problems,['php'] +313126,firefox ignores outline and focus styles on select elements when using tab contextfirefox 14 and 13 specific css styles being ignored under certain conditionsthe problemusing the following css outlinenone mozoutlinenone mozuserfocusignore jsfiddlefirefox 14 and 13 ignore these styles when using tab to switch between select elements clicking these elements after using tab still thisplays the outlinenotesspecifically styling select instead of has no effectthis only occurs with select elementsthe questionis this a bug or intended behaviorare there any other css styles that need to be used to prevent the outline from appearing indefinitely,['css'] +313151,using websocket on apache server with all the buzz around websockets it is pretty hard to find a good walkthrough on how to use them with an apache server on googlewere developing a plugin in php symfony2 which will run from time to time kind of a chat instance and we find websockets more interesting standard and quick than ajax for this matter the thing is we do not have much sysadmin ressources in our group and we find hard to gather good informations on the following matterscan we run a websocket instance on a traditional apache dedicated server and if yes do you have useful links for usif we need to mod the server what kind of tools would you recommend knowing that we are not too skilled in sysadmin so we cannot afford to have a high maintenance b on thisthank you very much ps well link back to your blogsite as well make a technicalinformational post on our devblog about this part of our appthank you again,['php'] +313171,what is the difference between configaction mailersmtp settings and actionmailerbasesmtp settings in rails i set up an exchange compatible mail server in a ror application i used the following setup in developmentrbconfigaction mailersmtp settings address mailservercom port 5870 user name username password password authentication loginthis setup does not work i get netsmtpauthenticationerror 504 unrecognized authentication typehowever if i apply the exact same configuration in environmentrb it works perfectlyactionmailerbasesmtp settings address mailservercom port 5870 user name username password password authentication login why is this should not configaction mailersmtp settings set the same settings is this a bug does it have a reasoni tried it with gmail as told here and it works so smtp settings does have effect on the mailer but it seems to me like not all the options countwork,['ruby-on-rails'] +313186,how to build a thistributed java application first of all i have a conceptual question does the word thistributed only mean that the application is run on multiple machines or there are other ways where an application can be considered thistributed for example if there are many independent modules interacting togehter but on the same machine is this thistributedsecond i want to build a system which executes four types of tasks there will be multiple customers and each one will have many tasks of each type to be run periodically for example customer1 will have task type1 today task type2 after two days and so on there might be customer2 who has task type1 to be executed at the same time like customer1s task type1 ie there is a need for concurrency configuration for executing the tasks will be stored in db and the outcomes of these tasks are going to be stored in db as well the customers will use the system from a web browser html pages to interact with system basically configure tasks and see the outcomes i thought about using a rest webservice using jaxrs where the html pages would communicate with and on the backend use threads for concurrent execution questions this sounds simple but am i going in the right direction or i should be using other technologies or concepts like java beans for example 2if my approach is fine do i need to use a scripting language like jsp or i can submit html forms directly to the rest urls and get the result using json for exampleif i want to make the application thistributed is it possible with my idea if not what would i need to usesorry for having many questions but i am really confused about this,['java'] +313201,when to call obtainpermanentidsforobjects i am currently having an issue where creating a new object on a background child thread whose parent is the main ui thread context and saving causes my nsfetchedresultscontroller to show two new objects one with a temporary objectid and one with a permanent objectid this seems to be a bug of some sort unless i am missing something so i thought i would manually obtain permanent ids for any new objects i create this fixes the duplicate row issue but introduces new random errors such as could not fulfill fault for object refering to the new object i created if anyone has any ideas as to why any of the previously mentioned is happening please sharei am guessing obtainpermanentids is a step in the right direction but when do i call this method before saving to the child context after saving the child and before the parent after the parentcurrently my setup is thismastermoc private queue tied to the persistent store so physical saves happen heremainmoc main queue tied to the ui child of mastermocbackgroundmoc private queue child of mainmocso if i create a new object on backgroundmoc and i intend to immediatly save to thisk which means i will have to call save on all three contexts where should i be calling obtainpermanentidsor if anyone has a different solution other than calling obtain permanent ids what problem was this method introduced to solve anyway why would i want to call this methodupdatei think i figured out whats going on it is only a theory though though not how to solve it core data apparently generates permanent ids for objects when they are saved physically to thisk so in my case this would not happen until i call save on the mastermoc currently what i do when creating a new object on the backgroundmoc issave on backgroundmoc so that changes are pushed up one level to the mainmoc and the my table view can insert the new rowssave on mainmoc so that i can prepare for saving to thisksave on mastermoc which finally saves to thiskwhats happening here is that calling save on the backgroundmoc triggers a ui update and causes the fetched results controller to insert a new object that still has only a temporary id but then calling save on mastermoc causes all objects to get assigned permanent ids which causes another ui update inserting another row for this new object by commenting out the last mastermoc save i no longer see duplicate entries am i doing something wrong here or is this some kind of buganother update i think i have pretty much confirmed the bug i call save on the backgroundmoc and then set up a timer to call save on the mainmoc and mastermoc 5 seconds later immediatley upon saving to the backgroundmoc a new row is inserted into my table 5 seconds later upon saving main and master another new row is inserted the row inserted first has a temp id and the newest insert has permanent id,"['iphone', 'objective-c', 'ios']" +313208,deactivate bodys scrolling but keep scroll bar how do i thisable bodys scroll bar but let it stay visible on screen as an example see facebooks theatre mode,"['html', 'css']" +313240,changing heroku repo for preexisting app i created a heroku repo some time ago for my rails app but deleted it because i was never using it now i have come to the point where i need to use heroku but i am encountering the following error no such app as furiousmist2295 which was the old repo name so it is clearly not pushing to the new stack i created this is what i was considering trying but am concerned about causing unnecessary changes to my git repogit remote rm origingit remote add origin url to new heroku appgit push u origin master,"['ruby-on-rails', 'ruby']" +313253,preventing session fixation in ruby sinatra most of the session fixation topics in ruby are mostly related to rails are there any session fixation vulnerabilities in sinatra in rails we are mostly recommended to do reset session before assigning sessions how can we prevent session fixation in sinatra,['ruby'] +313254,rails rspec how to check for a model constant how can i do something likeit should have constantfixed list in my model active record i have fixed list a stringit is not a db attribute or a method and i have not been able to use responds to or has attribute to test for it they fail what can i use the to check for it btw i have the shouldamatchers installed,['ruby'] +313258,aspnet mvc 4 async controller callback i am just using the new async controller features in mvc 4 as described here if i have an action that may take 1020 seconds to run i would like to provide some kind of status bar to notify the user of progress do the async features have anything to help this outedit i will take a stab at how i will try and do it and see if there are any better wayspublic async taskactionresult gizmosasync return viewgizmos await getgizmosasyncprivate void getgizmosasync forint i0 i10 i lock locker statusmessage stringformat0 of 10 i dosomethinglongrunning public actionresult status return jsonnew status statusmessage static readonly object locker new objectstatic string statusmessage scriptsettimeoutthisplaystatus 10function thisplaystatus postcontrollerstatus functiondata alertdatastatus script,"['c#', 'asp.net']" +313284,unable to cast the type systemnullable1 to type systemobject aspnet mvc errorunable to cast the type systemnullable1 to type systemobject linq to entities only supports casting entity data model primitive typesthis is the error i am gettingcontroller public actionresult fixturesall teammgr new teammanager fixturemgr new fixturemanager var team teammgrgetteams var viewmodel new teamindexviewmodel teams teamtolist numberofteams teamcount var fixtures from fixtures in oritia entitiesfixtures where fixturesseasonid seasionid select new fixturemodel team1 team2 winners fixturesteamwon firstbattingteam fixturesfirstbattingteam secondbattingteam fixturessecondbattingteam team1score fixturesteam1score team1wickets fixturesteam1wickets team2score fixturesteam2score team2wickets fixturesteam2wickets viewdatafixtures fixtures return viewviewmodel partial view control languagec inheritssystemwebmvcviewusercontrolienumerabledataaccessfixturemodel table foreach var item in viewdatafixtures as ienumerabledataaccessfixturemodel here i am getting the error tr td itemteam1 td td itemteam2 td tr tableview page title languagec masterpagefileviewssharedsitemaster inheritssystemwebmvcviewpagefunboxviewmodelsteamindexviewmodel ul foreach string team in modelteams lia href teamtostring teamtostring a li uldiv htmlrenderpartialfixturesallviewdatafixtures divcomplex classes public class teamindexviewmodel public int numberofteams get set public liststring teams get set public class fixturemodel public string team1 get set public string team2 get set public string winners get set public string team1score get set public string team1wickets get set public string team2score get set public string team2wickets get set public string firstbattingteam get set public string secondbattingteam get set output of sp help fixturesid bigint pkteamid1 bigintteamid2 bigintteamwon bigintdate datetimeseasonid bigintmanofthematch bigintfirstbattingteam bigintsecondbattingteam bigintresultdescription nvarcharteam1score bigintteam2score bigintteam1wickets bigintteam2wickets bigintthis is my overall structure and i am getting the above errori googled but i did not get an exact solution for this any help is highly appreciatedthanks all for helping me and my special thanks to jon skeet for giving the ideaplease see my updated query var data from fixtures in oritia entitiesfixtures join t1 in oritia entitiesteams on new id fixturesteamid1 equals new id t1id join t2 in oritia entitiesteams on new id fixturesteamid2 equals new id t2id where fixturesseasonid seasionid select new fixturemodel team1 t1teamname team2 t2teamname winners sqlfunctionsstringconvertdoublefixturesteamwon 1 firstbattingteam sqlfunctionsstringconvertdoublefixturesfirstbattingteam 1 secondbattingteam sqlfunctionsstringconvertdoublefixturessecondbattingteam 1 team1score sqlfunctionsstringconvertdoublefixturesteam1score 1 team1wickets sqlfunctionsstringconvertdoublefixturesteam1wickets 1 team2score sqlfunctionsstringconvertdoublefixturesteam2score 1 team2wickets sqlfunctionsstringconvertdoublefixturesteam2wickets 1 i used sqlfunctionsstringconvert for converstion to string and nows it working thanks all,['c#'] +313309,canvas pinchzoom to point within bounds i have been stuck on this problem for eight hours so i figured it was time to get some helpbefore i begin my problem i will just let it be known that i have been through this site and google and none of the answers i have found have helped this is one another and anotherheres the deal i have a class that extends surfaceview let us call it mysurface and overrides many methods in it normally it draws several squares and text boxes which is all fine as soon as a user starts touching it converts to a bitmap then draws each frame that until the user releasesheres the rub i want to implement such a functionality that the user can place two fingers on the screen pinch to zoom and also pan around but only with two fingers downi found a few implementations of pinchtozoom and adapted them to my canvas object in mysurface via the followingpublic void ondrawcanvas canvas superondrawcanvas canvassave canvasscalemscalevectorz mscalevectorz this is the scale factor as seen below canvastranslatemscalevectorx mscalevectory these are offset values from 00 both working fine start draw code end draw code canvasrestoreprivate class scalelistener extends scalegesturedetectorsimpleonscalegesturelistener override public boolean onscalescalegesturedetector detector float factor detectorgetscalefactor if mathabsfactor 10f 075f mscalevectorz factor mscalevectorz mathmaxmin zoom mathminmscalevectorz max zoom invalidate return true public boolean ontoucheventmotionevent event int action eventgetaction motioneventaction mask int pointerindex eventgetaction motioneventaction pointer index mask motioneventaction pointer index shift if eventgetpointercount 2 if action motioneventaction pointer down pointerindex 1 the various pivot coordinate codes would belong here detectorontoucheventevent calls the scale gesture detector return truewhile both elements work finethe scrolling back and forth and the pinchtozoomthere is one large problem the pinchtozoom when used zooms into the point 00 instead of zooming into the finger pointi have tried a lot of ways to fix thisusing canvasscalemscalevectorz mscalevectorz mscalevectorx mscalevectory obviously this produces unwanted results as the mscalevector x and y values are 0offsetsmanaging a pivot coordinate that uses the same offset as the translate method but this produces either the same 00 issue or jumping around when the view is touchednumerous other things i have done a lot with the aforementioned pivot coordinate trying to base its location on the users first touch and moving it relative to that touch each successive gestureadditionally this canvas must be bounded so the user cannot scroll forever however when i use the scalesx sy px py method it pushes things beyond any bounds i set in translatei am pretty much open to anything at this point i know this functionality can be added as it is seen in the android 40 gallery when viewing a single image i have tried to track down the source code that handles this to no avail,['android'] +313311,how to get integer values from a string in python suppose i had a stringstring1 498results should get now i need to get only integer values from the string like 498 here i do not want to use list slicing because the integer values may increase like these examplesstring2 49867results should get string3 497543results should get so i want to get only integer values out from the string exactly in the same order i mean like 49849867497543 from string1string2string3 respectivelycan anyone let me know how to do this in a one or two lines,['python'] +313312,exit the loop after specific time in c i have a requirement in my project c vs2010 net 40 that a particular for loop must finish within 200 milliseconds if it does not then it has to terminate after this duration without executing the remaining iterations the loop generally goes for i 0 to about 50 to 70 so the total loop time varies i have read following questions which are similar but they did not help in my case what is the best way to exit out of a loop after an elapsed time of 30ms in chow to execute the loop for specific timeso far i have tried using a stopwatch object to track the elapsed time but it is not working for me here are 2 different methods i have tried so far method 1 comparing the elapsed time within for loopstopwatch sw new stopwatchswstartfor i 0 i nentries i nentries is typically more than 50 do some stuff if swelapsed timespanfrommilliseconds200 breakswstopthis does not work because if swelapsed timespanfrommilliseconds200 takes more than 200 milliseconds to complete hence useless in my case i am not sure whether timespanfrommilliseconds generally takes this long or it is just in my case for some reason method 2 creating a separate thread to compare timestopwatch sw new stopwatchswstart bool bdoexit falseint mslimit 200systemthreadingthreadpoolqueueuserworkitemx while bdoexit false if swelapsedmilliseconds mslimit bdoexit true swstop systemthreadingthreadsleep10 for i 0 i nentries i nentries is typically more than 50 do some stuff if bdoexit true breakswstopi have some other code in the for loop that prints some statistics it tells me that in case of method 2 the for loop definitely breaks before completing all the iterations but the loop timing is still 280300 milliseconds any suggestions to break a for loop strictly within 200 milliseconds or less thanks,['c#'] +313349,select only unique array values from this array i have the following variable rowsarray 0 stdclass object product sku pch20 1 stdclass object product sku pch20 2 stdclass object product sku pch19 3 stdclass object product sku pch19 i need to create second array second containing only unique valuesarray 0 stdclass object product sku pch20 1 stdclass object product sku pch19 but when i run array unique on rows i receivecatchable fatal error object of class stdclass could not be converted to string on line 191,['php'] +313401,could someone suggest a test automation tool to automate java applet window could someone suggest a test automation tool to automate java applet windowrequire this to identify various buttons within the applet window too,['java'] +313423,how to convert string of datetime to date using gwt in mysql i have a field time entered of type datetime sample data 20120620 160047 i also have a method gettimeentered that returns the value as string i want to thisplay the date in this format 20120620 using datetimeformat from gwtheres my codestring date aprheaderdwgettimeentereddatetimeformat fmt datetimeformatgetformatmmddydateenteredsettext fmtformatdatethe problem is the format method does not accept arguments as string so if there is only a way i could convert the date from string to date type it could probably work i tried typecasting but did not work,['java'] +313430,keep xmpp connectionusing smack alive throughout application i am using the xmpp connectionusing smack for chat in android applicationi have made the connection with openfire and also i can send and receive the messagebut the problem is that when i go in the xmppclientjava activity then it made the connectionso i cant get any message till not go in that activityso how can made the connection at the starting and then reuse at other activitycode is in this 2 links connectionsettings file and the chatscreen in which we can do chatin this link the comment line is also my questions so please also see that comment,['android'] +313453,android create a spinner with items that have a hidden value and thisplay some text i am sure this is asked plenty and i have found some questions on here similar but none really got the coin dropping for me i am hoping someone can help me outwhat i want to do is present the user with a dropdown spinner with a list of flavours vanilla chocolate strawberrywhen the user selected the flavour of their choice the i want the value of strawberry which is 10 to be returnedstrawberry 10chocolate 20vanilla 30i come from a vbnet background so finding this incredibly hard to work with the fact i need arrayadapters and stuff to do itcould anyone simplify things for me and perhaps share some code,['android'] +313463,favor composition over inheritance favor composition over inheritanceis very popular phrase i read several articles and at the end each article says use inheritance when there is pure isa relationship between classesan example from this articlehere between apple and fruit there is clear isa relationship ie apple isa fruit yet the author has also shown it as apple hasa fruit composition to show the pitfall when implemented with inheritancei became somewhat confused here that what is the meaning of statementuse inheritance when there is pure isa relationship between classesdoes using composition over inheritance mean that always try to apply composition even if there is a pure isa relationship and leave inheritance only for those cases where composition does not make sense,['java'] +313503,how to determine height of the toolbar in uinavigationcontroller i have a view with a toolbar presented by a uinavigationcontrollerwhen i am handling uikeyboardwillshownotification i am scrolling the entire screen upwards by the height of the keyboardthe thing is when the keyboard is shown the bottom toolbar is not so i need to scroll the screen upwards by only keyboardheight toolbarheightbut how to get the height of the toolbarthanks,"['iphone', 'objective-c', 'ios']" +313517,how to debug android application built with maven i am currently trying to debug android application on my device from eclipse device has been added i can see it both in console and in eclipse console windows adb deviceslist of devices attached0019cca27f2e6e deviceand the eclipse i can run the app without any issues on both devicesimulator i just do clean install and androiddeploy followed by androidrun and works like a charm but i cannot figure out yet how to debug it but when i actually run the app on the devicesamsung galaxy sii i can only see these two processes executing comvibervoip and comvibervoipkeepalivereceiver i do not see my app even if i run it however on the simulatoremulator i can see my app runningi have gone trough this materialdebugging an app startup with android maven pluginhow to start application in command line with mavencannot break the code even tried with mavenexecplugin to start debugging by calling the script underneath here is that plugin in pom plugin artifactidexecmavenpluginartifactid groupidorgcodehausmojogroupid configuration executablebasedirscriptsdebug appcmdexecutable configurationpluginthe contents of debug appcmd adb shell am start d androidintentactionmain n mypackagenamehelloandroidactivitywhen i execute this plugin i get the following error starting intent actandroidintentactionmain catandroidintentcategorylauncher pkgandroidintentactionmain error activity not started unable to resolve intent actandroidintentactionmain catandroidintentcategorylauncher flg0x10 pkgandroidintentactionmain here is my manifestxml if that is needed usespermission androidnameandroidpermissionwrite external storage usespermission androidnameandroidpermissionaccess network state usespermissionusespermission androidnameandroidpermissionread phone state usespermissionusespermission androidnameandroidpermissionset debug app usespermission usespermission androidnameandroidpermissioninternet application androidicondrawableicon androidlabelstringapp name activity androidnamehelloandroidactivity intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity activity androidnamethisplaymessageactivity activityapplicationhas anyone manage to debug the device using maven to build the appquestion update after adding the androiddebuggabletrue my app appeared on the devices tab but i encounter different issuewhen i click on the green debug icon belowplease see below i have found this workaround solution in addition to the correct answer and i have accepted answer below might come useful as well topicandroiddevelopersdftp5gycwyi,"['java', 'android']" +313533,servlet javalangclassnotfoundexception orgjsonsimpleparserparseexception i am implementing google cloud messaging service for android i have created a test server which sends push notifications to application users but the server i have created is generating following error i am using java servlet at server side and have included gcmserverjar file in projecthere is the logjavalangclassnotfoundexception orgjsonsimpleparserparseexception at orgapachecatalinaloaderwebappclassloaderloadclasswebappclassloaderjava1680 at orgapachecatalinaloaderwebappclassloaderloadclasswebappclassloaderjava1526 at commgcmsendgcmmessageprocessrequestsendgcmmessagejava48 at commgcmsendgcmmessagedopostsendgcmmessagejava40 at javaxservlethttphttpservletservicehttpservletjava637 at javaxservlethttphttpservletservicehttpservletjava717 at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava290 at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava206 at orgapachecatalinacorestandardwrappervalveinvokestandardwrappervalvejava233 at orgapachecatalinacorestandardcontextvalveinvokestandardcontextvalvejava191 at orgapachecatalinacorestandardhostvalveinvokestandardhostvalvejava127 at orgapachecatalinavalveserrorreportvalveinvokeerrorreportvalvejava102 at orgapachecatalinacorestandardenginevalveinvokestandardenginevalvejava109 at orgapachecatalinaconnectorcoyoteadapterservicecoyoteadapterjava298 at orgapachecoyotehttp11http11processorprocesshttp11processorjava859 at orgapachecoyotehttp11http11protocolhttp11connectionhandlerprocesshttp11protocoljava588 at orgapachetomcatutilnetjioendpointworkerrunjioendpointjava489 at javalangthreadrununknown sourceany idea whats wrong with this,"['java', 'android']" +313534,reading pem rsa public key only using bouncy castle i am trying to use c to read in a pem file that contains only a rsa public key i do not have access to the private key information nor does my application require it the file myprivatekeypem file begins with begin public keyand ends with end public keymy current code is as follows orgbouncycastlecryptoasymmetriccipherkeypair keypair using var reader fileopentextckeysmyprivatekeypem keypair orgbouncycastlecryptoasymmetriccipherkeypairnew orgbouncycastleopensslpemreaderreaderreadobjecthowever the code throws an invalidcastexception with the message unable to cast object of type orgbouncycastlecryptoparametersdsapublickeyparameters to type orgbouncycastlecryptoasymmetriccipherkeypairhow can i use bouncy castles pemreader to read only a public key when no private key information is available,['c#'] +313536,requirejs shim for loading jquery ui and other jquery packages i am trying to load jqueryui with a shim but jqueryui keeps timing out when i try to load it even when i know the path is correctrequireconfigpaths jquery libsjquerywrapper jqueryui libsjqueryuimin jqueryselectmenu libsjqueryuiselectmenu underscore libsunderscorewrapper backbone libsbackbonewrappershim backbone these script dependencies should be loaded before loading backbonejs deps underscore jquery once loaded use the global backbone as the module value exports backbone jqueryui deps jquery jqueryselectmenu deps jquery jqueryui require jquery underscore backbone jqueryui jqueryselectmenu functionapp requireordersrcapp function app appinitialize,"['javascript', 'jquery']" +313543,lxml add namespace to input file i am parsing an xml file generated by an external program i would then like to add custom annotations to this file using my own namespace my input looks as belowsbml xmlns xmlnscelldesigner level2 version4 model metaiduntitled iduntitled annotationannotation listofunitdefinitionslistofunitdefinitions listofcompartmentslistofcompartments listofspecies species metaids1 ids1 namegena compartmentdefault initialamount0 annotation celldesignerextensioncelldesignerextension annotation species species metaids2 ids2 names2 compartmentdefault initialamount0 annotation celldesignerextensioncelldesignerextension annotation species listofspecies listofreactionslistofreactions modelsbmlthe issue being that lxml only declares namespaces when they are used which means the declaration is repeated many times like so simplifiedsbml xmlnsnamespace xmlnscelldesignermorenamespace level2 version4 listofspecies species kjwtest xmlnskjw namespace celldesignerdatasome important data which must be keptcelldesignerdata species species kjwtest xmlnskjw namespace species listofspeciessbmlis it possible to force lxml to write this declaration only once in a parent element such as sbml or listofspecies or is there a good reason not to do so the result i want would besbml xmlnsnamespace xmlnscelldesignermorenamespace level2 version4 xmlnskjw namespace listofspecies species kjwtest celldesignerdatasome important data which must be keptcelldesignerdata species species kjwtest species listofspeciessbmlthe important problem is that the existing data which is read from a file must be kept so i cannot just make a new root element i thinkedit code attached belowdef annotatesbmlsbml input from lxml import etree checksbmlsbml input makes sure the input is valid sbmlxml ns namespace etreeregister namespacekjw ns sbml doc etrelementtree root sbml docparsesbml input etreexmlparserremove blank texttrue nsmap rootnsmap nsmapsbml nsmapnone makes code more readable but seems ugly any alternatives to this nsmapkjw ns ns ns sbmlns nsmapsbml for species in rootfindallsbmlmodelsbmllistofspeciessbmlspecies nsmap speciesappendetrelementns test sbml docwritetestsbmlxml pretty printtrue xml declarationtrue return,['python'] +313553,reading rss feed with jquery using the jquery rss pluging jfeed and using their example code on their website i have created the following code which does not seem to workjquerygetfeed url success functionfeed alertfeedtitle i get a message sayingxmlhttprequest cannot load origin httpintranet is not allowed by accesscontrolalloworiginanyone know why i am getting this access control message this rss feed works fine in my desktop and online rss readers,['jquery'] +313575,avaudiorecorder proper mpeg4 aac recording settings i have got a live app with an estimated 15 of users reporting that the record feature is not working this is not happening on our test devices but the reports show that the problem is that preparetorecord is returning no i have had trouble finding sample settings for aac format are any of my settings off app requires ios5 and uses arc avaudiosession audiosession avaudiosession sharedinstanceaudiosession setcategoryavaudiosessioncategoryrecord errornilnsdictionary recordsettings nsdictionary dictionarywithobjectsandkeys nsnumber numberwithintkaudioformatmpeg4aac avformatidkey nsnumber numberwithfloat4410 avsampleratekey nsnumber numberwithint1 avnumberofchannelskey nsnumber numberwithintavaudioqualityhigh avsamplerateconverteraudioqualitykey nsnumber numberwithint1280 avencoderbitratekey nsnumber numberwithint16 avencoderbitdepthhintkey nilnsstring filename nsstring stringwithformatcaf verseguid brecordingreference ref nsurl url nsurl fileurlwithpathnsstring stringwithformat utilities sharedinstance documentsdirectorypath filenamenserror error nilaudiorecorder avaudiorecorder alloc initwithurlurl settingsrecordsettings errorerrorifaudiorecorder preparetorecord audiorecorder recordelse int errorcode cfswapint32hosttobigerror code nslogerror 44s error localizeddescription charerrorcode,['ios'] +313619,python file openclose everytime vs keeping it open until the process is finished i have about 50 gb of text file and i am checking the first few characters each line and writing those to other files specified for that beginning textfor example my input containscow ilovecowdog whreismydogcat thatcatshouldgotoredditdog gotitfromshelterso i want to process them in cow dog and cat about 200 categoriesso if writeflag1 writefile1openwritefilea writefile is somedirdogtxt writefile1writeremlinen writefile1closeso what is the best way should i close otherwise if i keep it open is writefile1openwritefilea doing the right thingthanks,['python'] +313625,test output to command line with rspec i want to do is run ruby sayhellorb on the command line then receive hello from rspeci have got that with thisclass hello def speak puts hello from rspec endendhi hellonew brings my object into existencehispeaknow i want to write a test in rspec to check that the command line output is in fact hello from rspecand not i like unixnot working i currently have this in my sayhello specrb filerequire relative sayhellorb points to file so i can see itdescribe sayhellorb do it should say hello from rspec when ran do stdoutshould receiveputswithhello from rspec endendcan someone point me in the right direction please,['ruby'] +313635,activity not showing in list of recent apps when launched from a widget i have created an app widget which when clicked launches an activity in my applicationthe activity it launches is not the main launcher activity as set in the application manifestintentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilterthe activity i am launching has launchmodesingletop may be relevantif i launch the app from the app launcher then press home and then the recent apps button the app is there i then remove the app from recent activities list or force close itif i then click on my widget the activity launches finei then press home and then the app does not appear in the list of recent appsany ideas,['android'] +313652,thisplaying a 3d model in javascripthtml5 i am looking at rendering a 3d model in a browser what tools should i usewhat places should i look ati do not know what data format the model will be i can likely request that data to formatted in any way i wanti am looking at threejs but it seems that it needs webgl to work which appears to be unsupported in iedoes a crossbrowser compatible html 3d rendering engine exists,['javascript'] +313663,ruby hash keys and values safe to assume same order rudimentary irb testing suggests that ruby hash returns keys and values in matching order is it safe to assume that this is the case,['ruby'] +313673,pandas dataframe select by partial string i have a dataframe with 4 columns of which 2 contain string values i was wondering if there was a way to select rows based on a partial string match against a particular columnin other words a function or lambda function that would do something like researchpattern cell in question returning a boolean i am familiar with the syntax of dfdfa hello world but cannot seem to find a way to do the same with a partial string match say hellowould someone be able to point me in the right direction,['python'] +313675,play constantly writes to thisc causing higher bill on amazon ec2 i have got myself an amazon ec2 micro instance a vpn server to play around withthe problem is that amazon charge you for every thisc io you do in a micro instancethe instance is running amazon linux a flavor of centosi have started a scala application in play 202 framework on the server and i am the only one who connects to the applicationi have observed that every few second something on the server commits io transactions to narrow it down i installed a linux program called iotophere is an output after a couple of secondstid prio user thisk read thisk write swapin io 23 be4 root 0 bs 1191 ks 0 0 command java dsbtivyhomeusrplay202frameworkrepository djavaruntimenameopenjdk jarsslf4japijarusrplay202repositorylocalorgslf4jjultoslf4j164jarsja cat from the log filecat homeec2usersockettestlogsapplicationlog20120705 114331881 info from play in mainlistening for http on port 90so play does not write anything to the log filefirst question have i understood the iotop correct and that play indeed is the thisc io thiefif so why do play use iomy application is a simple websocket example in essence it echos the input to the output the io occurs even thou nothing is pushed thru websockets,['java'] +313694,nltk tokenization and contractions i am tokenizing text with nltk just sentences fed to wordpunct tokenizer this splits contractions eg do not to don t but i want to keep them as one word i am refining my methods for a more measured and precise tokenization of text so i need to delve deeper into the nltk tokenization module beyond simple tokenization i am guessing this is common and i would like feedback from others whove maybe had to deal with the particular issue beforeedit yeah this a general splattershot question i knowalso as a novice to nlp do i need to worry about contractions at alledit the sexprtokenizer or treebankwordtokenizer seems to do what i am looking for for now,['python'] +313708,multiple buttons on navigation bar ios 5 i know there is a lot on this topic but i cannot get any code to work im running ios5 and building for the ipad and i just cannot get two buttons on one side of my navigation barany help would be appreciated thankseditsome code i have tested its in viewdidload does not do anything thoughuibarbuttonitem savebutton uibarbuttonitem alloc initwithtitlesave styleuibarbuttonitemstyleplain targetself actionselectorsave uibarbuttonitem deletebutton uibarbuttonitem alloc initwithtitledelete styleuibarbuttonitemstyleplain targetself actionselectordelete selfnavigationitemrightbarbuttonitems nsarray arraywithobjectssavebuttondeletebuttonnil,"['objective-c', 'ios']" +313722,why do images lose quality after the context has been rotated i am making a topdown shooter game that relies on the avatar always being rotated pointing to the mouse cursor i achieve rotation like thisrenderingcontextsave save the context state were about to change it a lotcontexttranslateposition0 picturewidth2 position1 pictureheight2 translate the context to the center of the imagecontextrotatephi rotate the context by the objects phicontextdrawimagepictureimage picturewidth2 pictureheight2 draw the image at the appropriate position center of the image 0 0contextrestore get the state backwhen the phi is zero the image is rendered in its normal quality with sharp edges and detectable pixels but when i set the phi to a nonzero value actually when it is not 0 pi2 pi pipi2 or 2pi the image looses it is sharpness and the individual pixels cannot be seen anymore because they are blurred outheres a screenshot sorry about the general bad quality of the screenshot but i think that the difference is more than noticeablethis is well a bit unacceptable i cannot have the images always blurred out why is this happening and can i solve it,['javascript'] +313735,regular expression to match specific string regex has always been my achilles heel i am writing web app where user will input his identifier i am using regexvalidator to validate this input the identifier should be something like thistninplkw20121234and this is how the identifier is builtfirst two letters are always tnfollowed by hyphenthen two letters that are either in te yo or ethyphentwo uppercase lettersanother hyphenanother two uppercase lettershyphenfour digits that are a year so something between 1970 and 2012 i can ignore that as long as there are 4 digitshyphenordinal number that can have from 1 to 4 digitsplease help me writing regex to match this identifier,['asp.net'] +313739,how to mock ruby module functions how can i mock module functions of a selfwritten module inside my projectgiven the module and functionmodule moduleamoduleb def selfmy function arg endendwhich is called likemoduleamodulebmy function with args how should i mock it when it is used inside a function i am writing specs fordoubling it obj doublemoduleamoduleb makes no sense for me as the function is called on the module and not on an objecti have tried stubbing it moduleamodulebstubmy functionwithargand returnsomething obviously it did not work stub is not defined therethen i have tried it with should receive again nomethoderrorwhat is the preferred way of mocking a module and it is functions,['ruby'] +313761,serializer for hashmaps for jersey use i am trying to post the following payload to my jerseybased web service firstnamejimmy lastnamejohns addresses street19 mayberry drive citymayberry statenc postalcode27043 countryus addresstype1 data eyesblue hairbrown sandwichroast beef my jersey codepostpublic response create person person createbo person stopped here in debugger stopped just as jersey calls me i see addresses in person flushed out with exactly what i am looking for whats in the json above however my data tuples are not there i know jersey is calling my noarg constructor for address es and its setters are getting called but i am up in the night as far as what jersey might or might not be trying to do with these random data tuples in my json i say random because in a different invocation these might be cavedeep dark mountainhigh wide etc this is part and parcel of my interfaceto flesh out what i am talking about consider these pojos as context for the abovexmlaccessortype xmlaccesstypefield xmlrootelementpublic class person implements serializable xmlelement private list address addresses new arraylist address xmlelement private map string string data new hashmap string string xmlrootelementpublic class address implements serializable private string street private string city private string state private string country private string postalcode private integer addresstype note i cannot do the random tuples as i have done address because i do not actually know beforehand what the keys will be whereas i limit address to street city etcwhat i need is some kind of magic serializer for hashmaps in jersey and i cannot seem to interpret the docs well enough to understand how to write one or work around this problem while still maintaining the flexibility of my interfacei would appreciate any indication as to how to accomplish thisruss batemanps note sadly that javautilmap to json object with jersey jaxb jackson was not helpful though it showed great promise,['java'] +313777,jquery and hiding after before pseudo classes possible duplicatejquery and pseudoclasses i tried hiding the after pseudo class via jquery in a number of ways but with no success i have found another solution by adding a sort of empty div under my div that contains the after content and then hiding the div entirely so it gives the same effecthowever i was just curious if anyone had managed to find a way to hide the after or before stuff here is what i tried that did not worksearch boxafterhidesearch boxaftercssthisplay nonejust to give you the context i have a div that contains the search form etc and when the search is active i want to enable a little arrow indicator under the div pointing like to the list of found items built with after via css and when nothing is found or it defaults to the full out list since nothing was found then i want to hide it,['jquery'] +313789,creating a generic list of objects in c by way of an intro i am creating a basic quadtree engine for personal learning purposes i am wanting this engine to have the capability of working with many different types of shapes at the moment i am going with circles and squares that will all move around in a window and perform some sort of action when collision occurshere are my shape objects as i have them so farpublic class qshape public int x get set public int y get set public string colour get set public class qcircle qshape public int radius public qcircleint theradius int thex int they string thecolour thisradius theradius thisx thex thisy they thiscolour thecolour public class qsquare qshape public int sidelength public qsquareint thesidelength int thex int they string thecolour thissidelength thesidelength thisx thex thisy they thiscolour thecolour now my question is how do i create a generic list listt qobjectlist new listt in c so i can have one list containing all these various shapes that may have different properties eg qcircle has the radius property while qsquare has the sidelength property an example of implementation would be helpful as welli just know that there is a stupidly obvious answer to this question but i would appreciate any help anyway i am trying to get back into c it has obviously been a while,['c#'] +313801,how to run my code on the specific thread how to run my code on the specific threadif the specific thread is main ui thread i can do use runonuithread methodbut the specific thread is not ui thread and the specific thread is not made by methe specific thread is made by some librarybut i can access the specific threadlike this thread thespecificthread getthreadhow to run my code on the specific thread like runonuithreadnew runnable,"['java', 'android']" +313804,debugging python ctypes segmentation fault i am trying to port some python ctypes code from a windowsspecific program to link with a linux port of my library the shortest python code sample that describes my problem is shown below when i try to execute it i receive a segmentation fault in examine arguments in python i placed a printf statement in my library at the crashing function call but it is never executed which leads me to think the problem is in the ctypes codeimport ctypesavidll ctypescdlibavxsynthsoclass avs valuectypesstructure object def init self valnone selftypectypesc short105 i selfarray size 5 selfdi 99class uctypesunion fields c ctypesc void p b ctypesc long i ctypesc int f ctypesc float s ctypesc char p a ctypespointeravs valueavs value fields type ctypesc short array size ctypesc short d uavs create script environment avidllavs create script environmentavs create script environmentrestype ctypesc void pavs create script environmentargtypes ctypesc intavs set var avidllavs set varavs set varrestype ctypesc intavs set varargtypes ctypesc void p ctypesc char p avs valueenv avs create script environment2val avs valueres avs set varenv btest valmy library has the following in its headers and a plainc program doing what i describe above calling create script environment followed by set var runs fine looking at logging information my library is putting onto the console the crash happens when i try to enter avs set vartypedef struct avs scriptenvironment avs scriptenvironmenttypedef struct avs value avs valuestruct avs value short type array clip bool int float string void or long for some function error short array size union void clip do not use directly use avs take clip char boolean int integer float floating pt const char string const avs value array davs scriptenvironment avs create script environmentint versionint avs set varavs scriptenvironment const char name avs value vali tried backtracing the call from gdb but i do not understand how to interpret the results nor really much about using gdb0 0x07f61d6490 in examine argument from usrlibpython27libdynload ctypesso1 0x07f61d65ba in ffi prep cif machdep from usrlibpython27libdynload ctypesso2 0x07f61d3447 in ffi prep cif from usrlibpython27libdynload ctypesso3 0x07f61c7275 in ctypes callproc from usrlibpython27libdynload ctypesso4 0x07f61c7aa2 in pycfuncptr call2798 from usrlibpython27libdynload ctypesso5 0x04c7c76 in pyobject call 6 0x042aa4a in pyeval evalframeex 7 0x04317f2 in pyeval evalcodeex 8 0x054b171 in pyrun fileexflags 9 0x054b7d8 in pyrun simplefileexflags 10 0x054c5d6 in py main 11 0x07f68e576d in libc start main from libx86 64linuxgnulibcso612 0x041b931 in start i am at a loss as to how to approach this problem i have looked at the details of the calling types but i do not see anything obviously incorrect there am i falling into any platformspecific usages of typesedit it seems there is a problem with 32bit vs 64bit architectures in the ctypes module when i tested this again with a 32bit build of my library and 32bit python it ran successfully on 64bit it segfaults at the same place,"['c++', 'python']" +313805,how to send text message in android via sip i am developing a application in android in which i want to send text message using sipxmppsession initiation protocol can anyone give me code for it and any guidelines about its development and testing on any free sip provider,"['java', 'android']" +313812,400 bad request in yahoo authentication i am trying to integrate yahoo into my application i want users to login using their yahoo accounts but whenever i request for a token i receive the following errorsgetrequesttoken exception oauthsignpostexceptionoauthcommunicationexception communication with the service provider failed service provider responded in error 400 bad requesthere is my code request token activityjava import oauthsignpostoauthimport oauthsignpostoauthconsumerimport oauthsignpostoauthproviderimport oauthsignpostcommonshttpcommonshttpoauthconsumerimport oauthsignpostcommonshttpcommonshttpoauthproviderimport oauthsignpostsignaturehmacsha1messagesignerimport androidappactivityimport androidcontentintentimport androidcontentsharedpreferencesimport androidcontentsharedpreferenceseditorimport androidneturiimport androidosbundleimport androidpreferencepreferencemanagerimport androidutillogpublic class request token activity extends activity private oauthconsumer consumer private oauthprovider provider private sharedpreferences prefsoverridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate try consumer new commonshttpoauthconsumermy consumer key my consumer secret consumersetmessagesignernew hmacsha1messagesigner provider new commonshttpoauthprovider request token token auth catch exception e loge oncreate exception etostring getrequesttokenprivate void getrequesttoken try string url providerretrieverequesttokenconsumer yahooapicallback logi yahoo url url intent intent new intentintentaction view uriparseurlsetflagsintentflag activity single top intentflag activity no history intentflag from background thisstartactivityintent catch exception e logi getrequesttoken exception etostring overridepublic void onnewintentintent intent superonnewintentintent prefs preferencemanagergetdefaultsharedpreferencesthis final uri uri intentgetdata if uri null urigetschemeequalsyahooapi getaccesstokenuri private void getaccesstokenuri uri final string oauth verifier urigetqueryparameteroauthoauth verifier try providerretrieveaccesstokenconsumer oauth verifier final editor edit prefsedit editputstringyahoo oauth token consumergettoken editputstringyahoo oauth token secret consumergettokensecret editcommit string token prefsgetstringyahoo oauth token string secret prefsgetstringyahoo oauth token secret consumersettokenwithsecrettoken secret logi yahoo oauth token token logi yahoo oauth token secret token catch exception e logi getaccesstoken exception etostring and this is a snapshot of my androidmanifestxml activity androidnamerequest token activity androidlaunchmodesingletask intentfilter action androidnameandroidintentactionview category androidnameandroidintentcategorydefault category androidnameandroidintentcategorybrowsable data androidschemeyahooapi androidhostcallback intentfilter activityi have setup my yahoo project as a web application and put read and write access to social and contacts what am i doing wrong,['android'] +313832,jquery validation on inputappend twitter bootstrap i am using twitter bootstrap for a site and we use jqueryvalidatei have a input element with button appended to input element this is a required field within our js validationthe code isdiv classcontrolsdiv classinputappend input tabindex1 nameurl classinputlarge idurl typetext placeholder autocapitalizeoff button classbtn typebutton nameattach idattach fetchbuttondivdivvalidation error class uses jquery validation rules and works perfectly on every other element but seemingly the span for the error is appended right after the input element which in most cases is absolutely fine but in this instance on this input field it cocks the thisplay up because it detaches the appended buttonbelow is image of what i mean before and after i really need to apply a different class to the error message for this one element but buggered if i can figure out howerrorclass helpinline errorelement span highlightfunctionelement errorclass validclass elementparentscontrolgroupaddclasserror unhighlight functionelement errorclass validclass elementparentscontrolgroupremoveclasserror elementparentscontrolgroupaddclasuccess for the input field the error event isurlrequiredtrueand message ismessagesurl requiredenter url beginning with http,['jquery'] +313875,books and articles on netty are there some good articlesbooks about how to use nettythe documentation is short and it is not simple for me to learn from the javadocthanks,['java'] +313881,java vertical alignment within jpanel i am trying to vertically align center both jlabels inside one jpaneljpanel panel new jpanelpanelsetpreferredsizesizejlabel label1 new jlabeliconjlabel label2 new jlabeltextpaneladdlabel1paneladdlabel2i have tried using setaligmenty with no success both labels always appear on the top of jpanelupd labels should be located next to each other like using flowlayout but in the middle of the jpanel,['java'] +313900,why is requirejs trying to append a js to jst template files that are loaded with the text plugin i use a jst extension for template files and load these with the requirejs text plugin eg define jquery backbone underscore texttemplatesmyviewjstfunction backbone templatetext return backboneviewextend template templatetemplatetext initialize function render function this works swell when i test locally however when i try to do this after i have deployed my static files to aws the dynamic portions of the app run on heroku it fails to load the jst files and appears to be trying to append a js to their urls for reference heres my requirejs config from mainjs requirejsconfig paths directories plugins libplugins libs jquery libjquery171jquery underscore libunderscore133underscore backbone libbackbone092backbone moment libmoment date lib require plugins text librequirepluginstext domready librequirepluginsdomready shim specify all nonamd javascript files here backbone deps underscore jquery exports backbone underscore exports moment exports moment pluginsjquerycolorbox jquery utiljquerydroptreejquery utilcommonjquery,['javascript'] +313904,making the inapp store for newsstand apps basically the app needs to see what magazine issues inapp purchases are available and thisplay their covers graphically in multiple rows the catalog of issues you see when you open a newsstand appthe issues themselves are html with supporting files css imagesdo you know how to do thishave you already done itis there such code available that one can adapt to their own case,"['objective-c', 'ios']" +313946,why is getattribute not invoked on an implicit getitem invocation while trying to wrap arbitrary objects i came across a problem with dictionaries and lists investigating i managed to come up with a simple piece of code whose behaviour i simply do not understand i hope some of you can tell me what is going on class clobject simple class that prints and suppresses each attribute lookup def getattribute self name print access name i cl instance of class itest test that getattribute override worksaccess test i getitem test that it works for special functions tooaccess getitem ifoo but why does not this worktraceback most recent call last file stdin line 1 in moduletypeerror cl object has no attribute getitem,['python'] +313953,how accurate is iphone gps in radius i want to know how accurate our gps on iphone 44s because my new project is using gps for tracking something i mean accurate is about meter i have search other question like mine but i do not have the answer is it possible to track radius just say for 1 meter how long accuracy that the gps iphone 44s have in minimum 10 meter how about 1 meter can it track for 1 meter radius oh again my next project for my company is outdoor application i know i can test it by myself but it more quick to get the answer from here thank you,['iphone'] +313977,java project admin privileges windows 7 i am building a swing application a file explorer that has to copymove filesfolders around when i try to copy to some folders such as program files it throws an exception access denied i can solve by running netbeans as administrator is there anyway i can give admin rights to my project only without running the whole virtual machine as admin,['java'] +313992,can indices actually decrease select performance possible duplicatedegraded performance of a query after adding index after reading some stuff about indices on sql server and their performance advantages for selects and thisadvantages for updates inserts i was wondering if badly used indices could actually also hurt performance for selectswhat conditions would have to be fulfilled to have an index decrease performance of a pure select query do such situations existthanksalthough i always try to include code examples i cannot think of anything that would support this question,['sql'] +314010,how to get mobile numbers if my android phone have two sim cards i have implemented an application for get the sim cards mobile numbers from my google ebony qwerty touchscreenin this device i have two sim cardsi have used telephonymanager for get mobile number from device as followstelephonymanager tmgr telephonymanager artnewactivitygetsystemservicecontexttelephony servicestring getsimserialnumber tmgrgetline1numberlogvdevice mobile numbersgetsimserialnumberfrom the above code it will return a single mobile number but if i run in case of ebony qwerty dual sim phone then can i get two sim card serial numbersplease any body help me,['android'] +314012,java fullscreen window with transparency i am trying to create a fullscreen window that cover the whole screen using java this window must also have some transparency about 3050 transparent when saying whole screen i do mean it cover everything including the docktaskbarmenubar in osxlinuxwindows and when i say with transparancy i mean a realtime transparancy and not just a hacked screenshot here is what i am awareoftriedusing java fullscreen api while it creates a true fullscreen you cannot have some transparency with it only opaque color one hack is to take a screenshot of the whole desktop and set it as background for the window but this mean it is not realtime transparencysetting window size to match screen dimension while it fills the whole screen in certain oses eg mac os x the window will be rendered behind the dockmenubar and not above it however transparency do work hereusing setwindowopacity api it work in the second case but not in the first fullscreen apiusing setbackground with alpha it work like the setwindowopacity but only in certain oses but also does not work with fullscreen apiuse jframejwindowjdialogframewindow tried every window model i could without any luckso i am asking if this is possible through a another hack that i am not aware of then i would be happy to hear aboutthe goal is to overlay a semitransparent fullscreen over the desktop,['java'] +314074,hidden property of button in html i am trying to show three buttons on one button click before a button click all three buttons are hidden i set the hidden property and i am also calling a function on a button click the problem is when i load the page all the button are visible it was working perfectly before i added cssi do not understand where the problem is here is the html codehtml xmlnsheadmeta httpequivcontenttype contenttexthtml charsetutf8 link relstylesheet typetextcss hrefdba stylebuttonscss titleuntitled documenttitleheadscript typetextjavascriptfunction changedocumentgetelementbyidsavehidden documentgetelementbyidchangehidden documentgetelementbyidcancelhidden scriptbodyform nameform1 methodpost actiondiv classbuttons button classregular nameedit idedit onclickchange img srcdba imagestextfield keypng alt edit button button typesubmit classpositive namesave idsave hiddenhidden img srcdba imagesapply2png alt save button button classregular namechange hiddenhidden idchange img srcdba imagestextfield keypng alt change button button classnegative namecancel idcancel hiddenhidden img srcdba imagescrosspng alt cancel buttondivformbodyhtmland here is the css i am usingbuttons a buttons buttonthisplayblockfloatleftmargin0 7px 0 0backgroundcolorf5f5f5border1px solid dededebordertop1px solid eborderleft1px solid efontfamilylucida grande tahoma arial verdana sansseriffontsize12pxlineheight130textdecorationnonefontweightboldcolor565656cursorpointerpadding5px 10px 6px 7px links buttons buttonwidthautooverflowvisiblepadding4px 10px 3px 7px ie6 buttons buttontypepadding5px 10px 5px 7px firefox lineheight17px safari firstchildhtml buttontype padding4px 10px 3px 7px ie7 buttons button img buttons a imgmargin0 3px 3px 0 importantpadding0bordernonewidth16pxheight16px standard buttonhover buttons ahoverbackgroundcolordff4ffborder1px solid c2e1efcolor336699buttons aactivebackgroundcolor6299c5border1px solid 6299c5colorf positive buttonpositive buttons apositivecolor529214buttons apositivehover buttonpositivehoverbackgroundcolore6efc2border1px solid c6d880color529214buttons apositiveactivebackgroundcolor529214border1px solid 529214colorf negative buttons anegative buttonnegativecolord12f19buttons anegativehover buttonnegativehoverbackgroundfbe3e4border1px solid fbc2c4colord12f19buttons anegativeactivebackgroundcolord12f19border1px solid d12f19colorf regular buttonregular buttons aregularcolor336699buttons aregularhover buttonregularhoverbackgroundcolordff4ffborder1px solid c2e1efcolor336699buttons aregularactivebackgroundcolor6299c5border1px solid 6299c5colorfwhat changes i can make so that when i click on edit it sets the hidden property of three buttons false thanks in advance,['html'] +314136,run c in command prompt windows i know that everyone uses an ide nowadays but i just find it simpler to write my code in notepad compile it using a command prompt command and run it from there too at least that works for java and python i have tried to get my head around how to do that with c and have not been able to find anything good is there any compiler like javas jdk that i can stick into my path and use the c equivalent of javac and java to run and compile my code from cmdnote please do not post answers and comments about how ides are better i know they are i am just used to doing it the old way d,['c++'] +314148,waiting for multiple swingworkers please consider the following code fragmentimport javaawtflowlayoutimport javaawteventactioneventimport javaawteventactionlistenerimport javalangreflectinvocationtargetexceptionimport javaxswingpublic class testapplet extends japplet override public void init try swingutilitiesinvokeandwaitnew runnable override public void run creategui catchinterruptedexception invocationtargetexception ex private void creategui getcontentpanesetlayoutnew flowlayout jbutton startbutton new jbuttondo work startbuttonaddactionlistenernew actionlistener override public void actionperformedactionevent ae jlabel label new jlabel new workerlabelexecute getcontentpaneaddstartbutton private class worker extends swingworkervoid void jlabel label public workerjlabel label thislabel label override protected void doinbackground throws exception do work return null override protected void done getcontentpaneremovelabel getcontentpanerevalidate here is add a label to the applet that thisplays some intermediate results of the worker thread using publishprocess methods at the end the label is removed from the applet us pane my question is how could i create several labels each with its own worker thread and remove them when they are all donethanks in advanceupdatei hope this will clarify my question i would like the labels to be removed all at once when all of the workers have finished their tasks not immediately after each worker has finishedupdate 2the following code seems to be doing what i need please comment whether i did it the right way i have a feeling there is something wrong one problem is that the labels to the right of the button remain visible although they are removed setvisiblefalse seems to solve this issue is that the way to do itimport javaawtflowlayoutimport javaawteventactioneventimport javaawteventactionlistenerimport javalangreflectinvocationtargetexceptionimport javautillinkedlistimport javautillistimport javautilqueueimport javautilrandomimport javautilconcurrentexecutorserviceimport javautilconcurrentexecutorsimport javaxswingpublic class testapplet extends japplet private queuejlabel labels new linkedlist private static final random rand new random override public void init try swingutilitiesinvokeandwaitnew runnable override public void run creategui catchinterruptedexception invocationtargetexception ex private void creategui getcontentpanesetlayoutnew flowlayout jbutton startbutton new jbuttondo work startbuttonaddactionlistenernew actionlistener override public void actionperformedactionevent ae executorservice executor executorsnewfixedthreadpool10 forint i 0 i 10 i jlabel label new jlabel getcontentpaneaddlabel executorexecutenew counterlabel getcontentpaneaddstartbutton private class counter extends swingworkervoid integer private jlabel label public counterjlabel label thislabel label override protected void doinbackground throws exception forint i 1 i 100 i publishi threadsleeprandnextint80 return null override protected void processlistinteger values labelsettextvaluesgetvaluessize 1tostring override protected void done labelsaddlabel iflabelssize 10 whilelabelsisempty getcontentpaneremovelabelspoll getcontentpanerevalidate,['java'] +314153,how does one test a function that has no return value i had visual studio create a test for each member in my class heres one example summarya test for closecurrenttextlogfilesummarytestmethodpublic void closecurrenttextlogfiletest loggerclosecurrenttextlogfile assertinconclusive a method that does not return a value cannot be verified based on the assert string i am wondering how to test this any ideas,['c#'] +314173,concrete code example of mvp can someone provide a concrete actual java code example of mvp in action this would include the following 3 types of classes and how they call each others methods to achieve the pattern and processrespond to a clientside responsemodel some kind of value object voview represents or generates the uipresenters business logicthanks in advance,['java'] +314189,how to find full name of calling method c how can i find the full name of a calling method in c i have seen solutionshow i can get the calling methods in chow can i find the method that called the current methodget calling function name from called function in cbut they only give me the top level consider the examplenamespace sandbox class program static void mainstring args test static void test var stacktrace new stacktrace var methodbase stacktracegetframe1getmethod consolewritelinemethodbasename this simply outputs main how can i get it to print sandboxprogrammainbefore anyone starts asking why i need to use this its for a simple logging framework that i am working oneditadding onto matzis answerhere is the solutionnamespace sandbox class program static void mainstring args test static void test var stacktrace new stacktrace var methodbase stacktracegetframe1getmethod var class methodbasereflectedtype var namespace classnamespace added finding the namespace consolewritelinenamespace classname methodbasename produces sandboxprogrammain like it should,"['c#', '.net']" +314190,jquerys css implementation i was looking through the jquery code and found this lineelemruntimestyleleft elemcurrentstyleleftati am not sure why this is done is not this uselesetting the runtimestyle to the currentstyle would override nothing except make the runtimestyle readable the next time you read it which does not seem needed nowi understand the overall concept here and why that code block exists to convert numeric nonpixel values to the appropriate pixel value by setting the left to the nonpixel value and reading its pixel value and then reverting the left back to the original valueedit see my answer below for why i think this is done with jsfiddle illustration,"['javascript', 'jquery', 'css']" +314203,instant messaging on android with google cloud messaging i was just looking at the new google cloud messaging gcm and i was wondering if it is possible to use gcm for instant messaging on your android applicationi saw you can send data like a message from a server but is it also possible to send from one device to another oneand how would this worksome example code would be really helpfultnx,['android'] +314235,how to properly set up a pdo connection from time to time i see questions regarding connecting to databasemost answers is not the way i do it or i might just not get the answers correctly anyway i have never thought about it because the way i do it works for mebut heres a crazy thought maybe i am doing this all wrong and if that is the case i would really like to know how to properly connect to a mysql database using php and pdo and make it easy accesableheres how i am doing itfirst off heres my filestructure stripped downpublic htmlindexphp initialize loadinitializephp configurephp sessionsphp indexphpat the very top i have requireinitializeloadinitializephp loadinitializephp site configurations requireconfigurephp connect to database requirerootsomewhereconnectphp this file is placed outside of public html for better security include classes foreach globassetsclassesclassphp as class filename includeclass filename include functions foreach globassetsfunctionsfuncphp as func filename includefunc filename handle sessions requiresessionsphpi know there is a better or more correct way to include classes but cannot remember what it was have not gotten the time to look into it yet but i think it was something with autoload something like thatconfigurephphere i basically just override some phpiniproperties and do some other global configuration for the siteconnectphpi have put the connection onto a class so other classes can extends this oneclass connect pdo protected dbh public function construct try db host hostname db name databasename db user username user pw password con new pdomysqlhostdb host dbnamedb name db user user pw consetattribute pdoattr errmode pdoerrmode exception conexecset character set utf8 return all sql requests as utf8 catch pdoexception err echo harmless error message if the connection fails errgetmessage br file put contentspdoerrorstxterr file append write some details to an errorlog outside public html die terminate connection public function dbh return thisdbh put database handler into a var for easier access con new connect pdo con condbhhere i do believe there is room for massive improvement since i recently started learning oop and using pdo instead of mysqlso i have just followed a couple of beginners tutoraials and tried out different stuffsessionsphpbeside handeling regular sessions i also initialize some classes into a session like this if isset sessionsqlquery session start sessionsqlquery new sqlquerythis way this class is avalible all over the place this might not be good practiceanyway this is what this approch allows me to do from everywhereecho sessionsqlquerygetareanamecounty9 outputs austagder the county name with that id in the databaseinside my sqlqueryclass which extends my connect pdoclass i have a public function called getareaname which handles the request to my databasepretty neat i thinkworks like a charmso that is basically how i am doing italso whenever i need to fetch something from my db from not whitin a class i just do something similar to thisid 123sql select whatever from mytable where id idqry conpreparesqlqry bindparamid id pdoparam intqry executeget qryfetchpdofetch assocsience i put the connection into a variable inside connect pdophp i just have refering to it and i am good to go it works i get my expected resultsbut regardless of that i would really appreciate if you guys could tell me if i am way off here what i should do instad areas i could or should change for improvement etc i am eager to learn,"['php', 'sql']" +314268,how do i get the template type of a given element at runtime in c i am designing a simple array class with the capability of holding any type of object like a vector that can hold multiple types of data in one object this is for learning purposesi have an empty base class called containerclass container and a templatized subclass called objecttemplate class tclass object public container t objectpublic objectt obj nullptr objectobj i have an array class which holds a vector of pointers to containers which i use to hold objectsclass array stdvectorcontainer vecpublic template class t void add elementconst t auto get elementintadd element stores elements into objects and puts them into vectemplate class tvoid arrayadd elementconst t element vecpush backnew objecttelementget element removes the element from it is object and passes it back to the caller this is where my problem lies in order to remove the element from the object i need to know what type of object it isauto arrayget elementint i return object veciobjectis there some way for me to find out what sort of object i am storingedit since people are claiming that this is not possible how about this is there some way of actually storing type information inside of a class i know you can do that in ruby if i could do that i could store the return type of get element in each object,['c++'] +314307,change hover css properties with javascript i need to find a way to change css hover properties using javascriptfor example suppose i have this html codetable tr tdhover 1td tdhover 2td trtableand the following css codetable tdhover backgroundff0i would like to use javascript to change the td hover properties to say background00ff00 know i could access the style background property using javascript asdocumentgetelementsbytagnametdstylebackground00ff00but i do not know of a javascript equivalent for hover how do i change these tds hover background using javascriptyour help is greatly appreciated,"['javascript', 'html', 'css']" +314328,python 2 and python 3 dual development i am just starting a new python project and ideally i would like to offer python 2 and 3 support from the start with minimal developmental overhead my question is what is the best way of doing this for brand new projectsi have come across projects that run 2to3 or even 3to2 as part of their installation script this seems to be a very common way however there seems to be several different ways of doing this i also came across thistributethere is also the option of trying to write polyglot python 2python 3 code even though this seems like a horrible idea i have noticed that i tend to write code lately that is more idiomatic as python 3 code even though i still run it as python 2 i have a feeling this only helps my own transition when the day finally arrives and does not do much for offering or at least helping dual support thoughmost of the projects offering dual support that i have seen added python 3 support late so i am especially curious if there is a better way that is more suited for new projects where you have the benefit of a clean slatethanksupdate thanks everyone heres a summary of the suggestionspolyglot same source code files run on python 2 and 3use sixespecially viable if you do not require support for low versions of 2no one suggested this but use from future import to give you python 3 behavior with usually a modest python 2 requirement for instance python 3style division has been available since python 22 this is especially applicable for brand new project since it helps if you make this decision early onif your python 3specific code is very rare you can check for sysversion info 3 and basically do what six does but in an adhoc fashionautomatic conversion run 2to3 or 3to2 automatically in setuppyuse thistribute to do this for you thistribute is a onefile project that can easily be included in your project so as to avoid another requirement as mentioned hererely on unit tests to make sure the conversion is soundfor videos about how to deal with unicode and timedate check out paulo scardines answer,['python'] +314336,csv remove field value wrap quotes i am attempting to write a list to a csv however when i do so i get wrapper quotes around my field valuesnumber1number2123423451235789023455687using this codewith openctemptestcsv wb as out file csv writer csvwriterout file delimiter csv writerwriterownumber1number2 for f in mylist csv writerwriterowfafter further research i found that you can remove the writing of quotes by usingquotechar quotingcsvquote nonewhen i apply this to my code i get this errortraceback most recent call last file line 4 in error need to escape but no escapechar setwith openctemptestcsv wb as out file csv writer csvwriterout file delimiterquotechar quotingcsvquote none csv writerwriterownumber1number2 for f in mylist csv writerwriterowfhow do i remove these quoteseditmylist looks like 12342345 12357890 23455687,['python'] +314345,autocorrect spell checker i have a tsv tabseparated value file that i need to spellcheck for misspellings and combined words ie i love you vs iloveyoui have installed aspell on my machine and can run it through r using the aspell functionfiles train2tsv res aspellfiles strres summaryreshowever the output from running it in r is just a list of misspelled words and possible suggestions summaryrespossibly misspelled words 1 amant contaneir creat ddition essayset essaytext experiament expireiment expirement 10 fipst infomation inorder measureing mintued neccisary officialy renuminering rinsen 19 sticlenx sucessfully tipe vineager vinigar yar strresclasses aaspella and dataframe 27 obs of 5 variables original chr essayset essaytext expirement expireiment file chr train2tsv train2tsv train2tsv train2tsv line int 1 1 3 3 3 3 3 3 6 6 column int 4 27 27 108 132 2 226 280 120 156 suggestionslist of 27 chr essay set essayset essayist essays chr essay text essaytext essayist sedatest chr experiment excrement excitement experiments chr experiment experiments experimenter excrement chr amandy am ant amant amanda chr year ya yard yard is there are way to have aspell or any other spellchecker automatically correct misspelled words,['python'] +314369,button clicklistener is not working in libgdx game i am developing android game using libgdx there are 4 button in menu screen but click listener of these button is not working retrieve the custom skin for our 2d widgets skin skin supergetskin create the table actor and add it to the stage table new table skin tablewidth stagewidth tableheight stageheight stageaddactor table retrieve the tables layout tablelayout layout tablegettablelayout register the button start game textbutton startgamebutton new textbutton start game skin startgamebuttonsetclicklistener new clicklistener override public void clickactor actorfloat xfloat y systemoutprintlnhi assetsload gamegetsoundmanagerplay tyriansoundclick gamesetscreen new gamescreengame layoutregister startgamebutton startgamebutton how to handle clicklistener of button in libgdx not image button but its layout button,"['java', 'android']" +314375,gdb program exited with code 030375 i am teaching myself to use gdb and am running some random tests it may be worth mentioning that i am using a portable installation of mingw on windows 7 x64 i have created a program which i know results in a stack overflow and as i run through it in gdb i first get two sigsegv signals no surprise and then it exits again no surprise with code 030375program received signal sigsegv segmentation faultprogram received signal sigsegv segmentation faultprogram exited with code 030375curiosity getting the best of me what the heck is that code i googled it and found very littlethanksupdate for reference i tried the same program on ubuntu and the results are slightly differentprogram received signal sigsegv segmentation faultprogram terminated with signal sigsegv segmentation faultthe program no longer exists,['c'] +314396,what are the parameters passed to cvfindcontours in javacv please can some one explain about cvfindcontours method and what are the parameters that it required for example heres code using opencvhierarchy cv2findcontoursthresh cv2retr list cv2chain approx simpleplease can some one explain how to write this using javacv,"['java', 'c++']" +314405,insert item in combobox after binding it from a dataset in c i have to insert select at top after combobox is bound from dataseti tried this but it is not workingthrows error dataset does not have any definition for casti think i am not using it properlycommented code is the part i tried but not workingcmbcategorydatasource dscattables0cmbcategorythisplaymember categorynamecmbcategoryvaluemember id cmbcategoryitemsaddselect cmbcategoryselectedtext select cmbcategorydatasource new object select concatthislivereportingdalcgetcategoriesbytypecategorytyperegistrationtypecastobject,['c#'] +314413,skewing a text view in android i am looking to replicate the following within my applicationas you can see its basically a button which increasesdecreases the value of the text view contained within it this button will have three visual states unpressed decrease and increase as seen in the image above the user taps the increase arrows and the button appears pressed in on that sidehere are my 3 button states currentlyas you can see the problem i have is being able to correctly skewrotate the text view so it looks visually correct and appears slanted along with the button when its being increased or decreasedi have tried two different approaches so farcreate a custom text view class which overrides the ondraw method to skew the canvasoverridepublic void ondrawcanvas canvas canvassave canvasskew02f 0f superondrawcanvas canvasrestoreintegrate the rotate3danimation class source here and used many different variations to get the desired result such as rotate3danimation skew new rotate3danimation 30 0 centerx centery 0 false txtamountstartanimationskew unfortunately i am not quite getting the exact result that mirrors the first image above i am getting confused with setting values with the zaxis skew rotate etci would greatly appreciate any help from anyone who has experience with this stuff thanks in advance,['android'] +314420,cron command to run url address every 5 minutes i am newbie in cron commands and i need helpi have a script on whats is command for cron to run this url every 5 minutesi tried 5 hometestcheckphp but i want to run url not relative script address how to do it,['php'] +314444,plot numpy datetime64 with matplotlib i have two numpy arrays 1d one is time of measurement in datetime64 format for examplearray2015 010811 2016 020804 20120707 110800 dtypedatetime64usand other array of same length and dimension with integer datai would like to make a plot in matplotlib time vs data if i put the data directly this is what i getplottimeseries datais there a way to get time in more natural units for example in this case monthsyear would be fineediti have tried gustav larssons suggestion however i get an errorout128matplotliblinesline2d at 0x419aad0overflowerror traceback most recent call lastusrlibpython27thistpackagesipythonzmqpylabbackend inlinepyc in showclose 100 try 101 for figure manager in gcfget all fig managers 102 send figurefigure managercanvasfigure 103 finally 104 show to draw usrlibpython27thistpackagesipythonzmqpylabbackend inlinepyc in send figurefig 209 210 fmt inlinebackendinstancefigure format 211 data print figurefig fmt 212 print figure will return none if there is nothing to draw 213 if data is noneusrlibpython27thistpackagesipythoncorepylabtoolspyc in print figurefig fmt 102 try 103 bytes io bytesio 104 figcanvasprint figurebytes io formatfmt bbox inchestight 105 data bytes iogetvalue 106 finallyusrlibpymodulespython27matplotlibbackend basespyc in print figureself filename dpi facecolor edgecolor orientation format kwargs 1981 orientationorientation 1982 dryruntrue 1983 kwargs 1984 renderer selffigure cachedrenderer 1985 bbox inches selffigureget tightbboxrendererusrlibpymodulespython27matplotlibbackendsbackend aggpyc in print pngself filename or obj args kwargs 467 468 def print pngself filename or obj args kwargs 469 figurecanvasaggdrawself 470 renderer selfget renderer 471 original dpi rendererdpiusrlibpymodulespython27matplotlibbackendsbackend aggpyc in drawself 419 420 try 421 selffiguredrawselfrenderer 422 finally 423 rendereragglockreleaseusrlibpymodulespython27matplotlibartistpyc in draw wrapperartist renderer args kwargs 53 def draw wrapperartist renderer args kwargs 54 beforeartist renderer 55 drawartist renderer args kwargs 56 afterartist renderer 57 usrlibpymodulespython27matplotlibfigurepyc in drawself renderer 896 dsusortkeyitemgetter0 897 for zorder a func args in dsu 898 funcargs 899 900 rendererclose groupfigureusrlibpymodulespython27matplotlibartistpyc in draw wrapperartist renderer args kwargs 53 def draw wrapperartist renderer args kwargs 54 beforeartist renderer 55 drawartist renderer args kwargs 56 afterartist renderer 57 usrlibpymodulespython27matplotlibaxespyc in drawself renderer inframe 1995 1996 for zorder a in dsu 1997 adrawrenderer 1998 19 rendererclose groupaxesusrlibpymodulespython27matplotlibartistpyc in draw wrapperartist renderer args kwargs 53 def draw wrapperartist renderer args kwargs 54 beforeartist renderer 55 drawartist renderer args kwargs 56 afterartist renderer 57 usrlibpymodulespython27matplotlibaxispyc in drawself renderer args kwargs 1039 rendereropen group name 1040 1041 ticks to draw self update ticksrenderer 1042 ticklabelboxes ticklabelboxes2 self get tick bboxesticks to draw renderer 1043 usrlibpymodulespython27matplotlibaxispyc in update ticksself renderer 929 930 interval selfget view interval 931 tick tups t for t in selfiter ticks 932 if self smart bounds 933 handle inverted limitsusrlibpymodulespython27matplotlibaxispyc in iter ticksself 876 iterate through all of the major and minor ticks 877 878 majorlocs selfmajorlocator 879 majorticks selfget major tickslenmajorlocs 880 selfmajorformatterset locsmajorlocsusrlibpymodulespython27matplotlibdatespyc in call self 747 def call self 748 return the locations of the ticks 749 selfrefresh 750 return self locator 751 usrlibpymodulespython27matplotlibdatespyc in refreshself 756 def refreshself 757 refresh internal information based on current limits 758 dmin dmax selfviewlim to dt 759 self locator selfget locatordmin dmax 760 usrlibpymodulespython27matplotlibdatespyc in viewlim to dtself 528 def viewlim to dtself 529 vmin vmax selfaxisget view interval 530 return num2datevmin selftz num2datevmax selftz 531 532 def get unitselfusrlibpymodulespython27matplotlibdatespyc in num2datex tz 287 288 if tz is none tz get rc timezone 289 if not cbookiterablex return from ordinalfx tz 290 else return from ordinalfval tz for val in x 291 usrlibpymodulespython27matplotlibdatespyc in from ordinalfx tz 201 if tz is none tz get rc timezone 202 ix intx 203 dt datetimedatetimefromordinalix 204 remainder floatx ix 205 hour remainder divmod24remainder 1overflowerror signed integer is greater than maximumcould this be an bug or am i missing something i also tried something simpleimport matplotlibpyplot as pltimport numpy as npdatesnparray2013 2014 2015 2016 2019 dtypedatetime64usdatanparray1 2 3 4 5pltplot datedates datapltshowi still get this erroroverflowerror signed integer is greater than maximumi do not understand what am i doing wrong ipython 013 matplotlib 11 ubuntu 1204 x64final editit seems that matplotlib does not support dtypedatetime64 so i needed to convert the timeseries to ordinary datetimedatetime from datetime,['python'] +314502,adding spinner to actionbar not navigation i have added a spinner to my actionbar using the second option from the answer here how to i add a spinner adapter to the spinner i tried using a spinner object as google describes here but get a null spinner objectanybody know how to do this i do not want the spinner to be in the navigation area of the action bar but in with the other action items i am using the split action barthanks for the help,['android'] +314503,find all embedded resources in another assembly ia m currently working on localization for my project for this i have a class which should load an embedded resource from another assembly and then read out the stringsbut also i need to know which resourcefiles this assembly containsthe number and which languages those are is unknownso how do i find out how the resx file in this assembly is namedthose all have the same scheme dederesx enusresx and so oni need to know how many of those files are contained in this assemblyand which languages they areis there any possibility i only know the resourcemanager who has access to themso there must be a way to access them manually toothanks,['c#'] +314548,php spl is it worth using or raw array functions are better i am examining the standard php library spl i used only arrays before and just now found that php has so many standard classes but there is no any words in the manual whether it is recommended to use it or not for example they explicitly recommend to use foreach construction to iterate arrays because it is faster and what about this library if i need to store some data in an object should i use some concrete spl class for my situation or using standard arrays is better anyway,['php'] +314552,csv reader behavior with none and empty string i would like to thistinguishing none and empty strings when going back and forth between python data structure and csv representation using pythons csv modulemy issue is that when i runimport csv cstringiodata nullnone valuenone empty stringf cstringiostringiocsvwriterfwriterowsdataf cstringiostringiofgetvaluedata2 e for e in csvreaderfprint input dataprint output data2i get the following output input nullnone value none empty string output nullnone value empty string of course i could play with data and data2 to thistinguish none and empty strings with things likedata d if dnone else none for d in datadata2 d if dnone else none for d in data2but that would partly defeat my interest of the csv module quick deserializationserialization implemented in c specially when you are dealing with large listsis there a csvdialect or parameters to csvwriter and csvreader that would enable them to thistinguish between and none in this usecaseif not would there be an interest in implementing a patch to csvwriter to enable this kind of back and forth possibly a dialectnone translate to parameter defaulting to to ensure backward compatibility,['python'] +314558,what ecmascript 5 use strict string costs exist what is meant by use strict string costs in almondjs line 6a google returns no information on the issue the author seems to be implying,['javascript'] +314567,how do i change the font size of the scale in matplotlib plots while plotting using matplotlib i have found how to change the font size of the labelsbut how can i change the size of the numbers in the scalefor clarity suppose you plot x2 from x0y0 00 to x1y1 2020the scale in the xaxis below maybe something like 0 1 2 20i want to change the font size of such scale of the xaxis,['python'] +314616,nsnumber arithmetic i want to perform some simple arithmetic on nsnumbers and preserve the type is this possiblefor example nsnumber addnsnumber firstnumber tonsnumber secondnumberis my method definition and firstnumber and secondnumber are integers then i would like to return an integer that is the integer addition of them both equally if both are doubles then to return the result as a doubleit looks like i can get the type except for boolean using nsnumber objctype as found in this question get type of nsnumber but i cannot seem to extract those types and do the calculation without lots of code to extract the values do the calculation and return the result for every possible typeis there a short and concise way of doing this,['ios'] +314623,classnotfoundexception when unmarshalling androidsupportv4viewviewpagersavedstate i am seeing the following error in my android crash reportsandroidosbadparcelableexception classnotfoundexception when unmarshalling androidsupportv4viewviewpagersavedstateat androidosparcelreadparcelableparceljava1971at androidosparcelreadvalueparceljava1859at androidosparcelreadsparsearrayinternalparceljava2128at androidosparcelreadsparsearrayparceljava1581at androidosparcelreadvalueparceljava1916at androidosparcelreadmapinternalparceljava2099at androidosbundleunparcelbundlejava223at androidosbundlegetsparseparcelablearraybundlejava1225at androidsupportv4appfragmentmanagerimplmovetostatefragmentmanagerjava806at androidsupportv4appfragmentmanagerimplmovetostatefragmentmanagerjava1083at androidsupportv4appbackstackrecordrunbackstackrecordjava635at androidsupportv4appfragmentmanagerimplexecpendingactionsfragmentmanagerjava1431at androidsupportv4appfragmentmanagerimplexecutependingtransactionsfragmentmanagerjava431at androidsupportv4appfragmentstatepageradapterfinishupdatefragmentstatepageradapterjava160at androidsupportv4viewviewpagerpopulateviewpagerjava895at androidsupportv4viewviewpagerpopulateviewpagerjava772at androidsupportv4viewviewpagercompletescrollviewpagerjava1539at androidsupportv4viewviewpagercomputescrollviewpagerjava1422at androidviewviewgroupdrawchildviewgroupjava3028at androidviewviewgroupthispatchdrawviewgroupjava2788at androidviewviewgroupdrawchildviewgroupjava3184at androidviewviewgroupthispatchdrawviewgroupjava2788at androidviewviewgroupdrawchildviewgroupjava3184at androidviewviewgroupthispatchdrawviewgroupjava2788at androidviewviewgroupdrawchildviewgroupjava3184at androidviewviewgroupthispatchdrawviewgroupjava2788at androidviewviewdrawviewjava11017at androidwidgetframelayoutdrawframelayoutjava450at comandroidinternalpolicyimplphonewindowdecorviewdrawphonewindowjava2175at androidviewviewrootimpldrawviewrootimpljava2234at androidviewviewrootimplperformtraversalsviewrootimpljava1810at androidviewviewrootimplhandlemessageviewrootimpljava2695at androidoshandlerthispatchmessagehandlerjava99at androidoslooperlooplooperjava154at androidappactivitythreadmainactivitythreadjava4977at javalangreflectmethodinvokenativenative methodat javalangreflectmethodinvokemethodjava511at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava784at comandroidinternaloszygoteinitmainzygoteinitjava551at dalviksystemnativestartmainnative methodit appears to happen intermittently when resuming an activity i do not directly access the savedstate class in any code,['android'] +314632,metro style apps with html and c according to this slidedoes it mean i have to use xaml view with c if i want to develop a metro styled applicationcan i use a htmljscss c combination with event handlers and all something like aspnet webformsmvc i know it is not the same client server architecture but since metro styled apps support htmljs i was wondering i can use winjs but can i rather write c than javascript and use html rather than xamli dont know xaml and i like call the c samples i found online use xaml,['c#'] +314661,pretty print 2d array in java i am looking for a util which will print a rectangular string into a humanreadable table with correct column lengths,['java'] +314713,what are good resolution values to use with media queries recently i have been playing around with css media queries because it is a great way to make my website adapt to various screen sizes i am planning to implement them into the live versionmy question is are there any recommended resolution values at which the layout changes,['css'] +314739,passing arguments to tp new and tp init from subtypes in python c api i originally asked this question on the python capisig list how to pass arguments to tp new and tp init from subtypesi am reading the python pep253 on subtyping and there are plenty of good recommendations on how to structure the types call tp new and tp init slots etcbut it lacks an important note on passing arguments from sub to super typeit seems the pep253 is unfinished as per the notex there should be a paragraph or two about argument passing hereso i am trying to extrapolate some strategies well known from the python classes subtyping especially techniques that each level stripsoff arguments etci am looking for techniques to achieve similar effect to this but using plain python c api 3xclass shape def init self shapename kwds selfshapename shapename super init kwdsclass coloredshapeshape def init self color kwds selfcolor color super init kwdswhat would be the equivalent in python c apihow to deal with similar situation but with arguments specific to derived class expected in different orderit is arguments given at the end of the args tuple or kwds dict i assume principle would be samehere is some pseudocode that illustrates the situationclass base def init self x y z selfx x selfy y selfz zclass derivedbase def init self x y a selfa a super init x y nonenote if the a was expected firstderived init self a x yit would be similar situation to the shape and coloredshape aboveit would also be easier to deal with i assumecould anyone help to figure out the missing x comment mentioned above and correct technique for passing arguments from subtype up to super types on constructionupdate 20120717inspired by ecatmurs answer below i looked through python 3 sources and i found defdict init constructor of collectionsdefaultdict type object interesting the type is derived from pydictobject and its constructor takes additional argument of default factory the constructor signature in python class is thisclass collectionsdefaultdictdefault factory now here is how the default factory is stripped from original args tuple so the rest of arguments is forwarded to the tp init of base type it is pydictobjectint resultpyobject newargspy ssize t and pytuple get sizeargsnewargs pysequence getsliceargs 1 nresult pydict typetp initself newargs kwdsnote this snipped presence only the relevant part of the defdict init function,['python'] +314746,ckeditor with autocomplete is it possible to implement jquery autocomplete somehow into ckeditor creating a button is not that hard but is it possible to hardwire that to autocomplete so the next word that is being typed until the button is pressed againanyone who did remotely something like that please let me know or if that is not possible a popup window of an autocomplete search and then on clickselect it would add that selected item to ckeditor textareacurrent cursor position maybe as a linktrying not to overreach of course,['jquery'] +314758,unit test custom route in web api i have spent already half day on this without any success how do you unit test routes in web apii mean given the following uritestget2i want to unit test that the above url is captured by the test controller and get action accepting an int parameter,['c#'] +314769,whats the best design for a restful uri with multiple mandatory parameters i am looking to see if more of the seasoned web service veterans can comment on the best way to design a restful uri in where i need mandatory parameters case in point i would like to design an uri that requests dataexamplecomrequestthistributionhowever from my understanding is that the approach is that more data should return at the higher levels while more detailed data would be returned if applying more specific uri keywords but in my case i need at least 3 values for that to happen those 3 values would be a date value an account value and proprietary thistribution code values for exampleexamplecomrequestthistributionacct123date20030102thistcode1a1b1cis that considered an restful url or is there a better approach that would make more sense any input is greatly appreciatedbtw python is the language of choice thanks,['python'] +314773,attempting to install libv8 failed to build gem native extension i am using w7 64bit simply put when i entercsitesgem install libv8i get this resulttemporarily enhancing path to include devkitbuilding native extensions this could take a whileerror error installing libv8error failed to build gem native extension crailsinstallerruby193binrubyexe extconfrbcreating makefilewhich no gmake in my path is here and as far as i know it should include everything i needusrbinenv python no such file or directorycrailsinstallerdevkitbinmakeexe outmakefileia32 error 127using compiler crailsinstallerdevkitmingwbingexegyp generatorsmake buildgypgyp generatoroutputout buildallgyp ibuildstandalonegypi depth dv8 target archia32 sia32 dhost archia32gem files will remain installed in crailsinstallerruby193librubygems191gemslibv831183 for inspectionresults logged to crailsinstallerruby193librubygems191gemslibv831183extlibv8gem makeoutuninstalling and reinstalling does not worki am trying to install libv8 because it is a dependency for twitterbootstraprailsedit as i said i am on windows and i am realizing now that there is a filepath listed in this error as usrbinenv so that is weird,"['ruby-on-rails', 'ruby']" +314783,uiimage resize with hard edges i need a method for resizing uiimage like in photoshop with nearest neighbour resampling i was looking for some but everything i found was about coregraphics thicks to improve bicubic resampling quality i have pixelstyle design in my app and a lot of stuff i create by pixel and then enlarge it with x5 multiplier and it takes a lot of time so i even close to writing a script for photoshop for example but i really do not need this like result of resamplingmaybe anyone will show me the right way,"['objective-c', 'ios']" +314809,keeping a socket connection alive in ios i have the following code written in objectivec that writes data to a socket the server is running nodejs on top of ubuntunsstring url anipaddress cfreadstreamref readstreamcfwritestreamref writestream cfstreamcreatepairwithsockettohostnull cfstringrefurl 90 readstream writestreamselfinputstream nsinputstream readstream selfoutputstream nsoutputstream writestreamselfinputstream setdelegateself selfoutputstream setdelegateself selfinputstream scheduleinrunloopnsrunloop currentrunloop formodensdefaultrunloopmode selfoutputstream scheduleinrunloopnsrunloop currentrunloop formodensdefaultrunloopmode selfinputstream open selfoutputstream openi am able to connect to the server and send information however i noticed the connection times out after a few minutes i think 5 minutes or so how can i keep this connection alive i know there is a thisconnect because the same thing happens if i connect to the server under terminal i have to keep that connection alive i imagine the same thing is happening in my code thanks for your help,['objective-c'] +314812,wherehow to getintentgetextras in an android fragment with activities i used to do thisin activity 1intent i new intentgetapplicationcontext myfragmentactivityclass iputextraname itemsgetarg2 iputextracategory category startactivityiin activity 2item getintentgetextrasgetstringnamehow do you do this using fragments i am using the compatibility library v4 alsodoes it go in the fragmentactivity or the actual fragmentand which method does it go in oncreate oncreateview anotherand can i see example code pleaseedit it is worth noting i am trying to keep activity 1 as an activity or actually listactivity where i am passing the intent of the listitem when clicked and then pass to a set of tabbedfragments through a fragment activity and i need either tab to be able to get the extras i hope this is possible,['android'] +314829,ruby restclient file upload as multipart form data with basic authenticaion i understand how to make an http request using basic authentication with rubys restclientresponse restclientrequestnewmethod get url base url path user sid password tokenexecuteand how to post a file as multipart form datarestclientpost data myfile filenewpathtoimagejpg rbbut i cannot seem to figure out how to combine the two in order to post a file to a server which requires basic authentication does anyone know what is the best way to create this request,['ruby'] +314855,java compiled classes contain dollar signs i have been using eclipse as my development ide i also use it to export my application into a jar file when i look at my classes in the jar file a few of my classes contain the name of that class a dollar sign then a number examplefind1class find2classfind3classfindclassi have noticed it does this on bigger classes is this because the classes get so big it compiles it into multiple classes i have googled and looked on multiple forums and search the java documentation but have not found anything even related to it could someone explain,['java'] +314867,peculiar use of c macros reading the code of the c librarys sockets interface i found this types of sockets enum socket type sock stream 1 sequenced reliable connectionbased byte streams define sock stream sock stream sock dgram 2 connectionless unreliable datagrams of fixed maximum length define sock dgram sock dgramthis idiom is used all over bitssocketh i am just curious what is the purpose of those macros,['c'] +314916,is it possible to listen image load event in svg is it possible to listen for an image load event in svg if yes how to do this,['javascript'] +314925,mocking virtual members in moq for unit testing i am using nunit 26 and moq 40 there is a particular case concerning virtual members where moqs proxy objects do not relay method calls to the actual implementation probably by design for instance if i had a classpublic class myclass protected virtual void a protected virtual void b and i use moq to override getsomethingelses a method in my test fixturevar mock new mockmyclassmockprotectedsetupacallbacksomesortofcallbackusing the mocks a method works splendidly however if anything in said method would call notmocked method b the method will do nothing andor return default values even if an actual implementation exists in myclassis there a way to work around this am i using moq wrongthanks in advancemanny,['c#'] +314931,how to convert month number to full month name in oracle i have a month column in my table the month numbers are stored in this month column like 1 for january 2 for feb and so on how do i convert the numbers into month names such as january february march etc,['sql'] +314965,generics what does actually mean possible duplicatewhat does list mean in java genericswhat does the question mark in java generics type parameter mean apologies but it was difficult trying to search for what does mean in regards to java generics i understand a extends b and a super b but i have never seen this question mark on its own before,['java'] +314972,how to run my nodejs project on android i have a working php server on my android tablet so i hope it is available somehow to run nodejs also the source code is available on github and it can be build on linux also but i cannot really understand how to build itthanks in advance,"['javascript', 'android']" +314975,register null as instance in unity container i have a repository class with optional dependencyclass myrepository baserepository imyrepository public myrepositoryidatacontext datacontext icacheprovider cacheprovider null basedatacontext cacheprovider athe existence of cacheprovider parameter acts as strategy for the repositoryi want setup unity container like thiscontainerregistertypeidatacontext mydatacontextnew perresolvelifetimemanager new injectionconstructor registerinstanceicacheprovidernull registertypeimyrepository myrepositoryie not pointing out particular injectionconstructor with one parameter for myrepository but use default constructor with null as cacheprovider parameteris there any way to do this,"['c#', '.net']" +314982,vectors emplace back can you please explain how perfect forwarding worksi read that vectors emplace back does not need to copy nor move objects because its argument is implemented as variadic templatestdvectortemplace back args argscan you describe it in more detail why would not it copy nor move,['c++'] +314989,my own method used in list thisplay and value as boolean icon i wrote my own method used in list thisplay admin class like thisclass myclassadminadminmodeladmin list thisplay my own method def my own methodself obj if condition return true else return falsebut this value is thisplayed on list as text true or false not as default django boolean icons like this what should i do to change this,['python'] +314995,how to find value using key in javascript dictionary i have a question about javascripts dictionary i have a dictionary in which keyvalue pairs are added dynamically like thisvar dict var addpair function mykey myvalue dictpush key mykey value myvalue i will call this function and pass it different keys and values but now i want to retrieve my value based on the key but i am unable to do so can anyone tell me the correct wayvar givevalue function my key return dict my key not working return dict my key value not workingas my key is a variable i cannot use dictmy keythanks,['javascript'] +314999,does usage of a pointer cancel the register property of the associated variable in c does usage of a pointer cancel the register property of the associated variableincludestdiohincludestdlibhint main register int clk0 maybe register maybe not int adrclk not a register now i have its address adr1 if i use this 10 times does it exist in l1 at least printfdclk return 0gives compiler error cannot take address of register variable but it is not register 100 it is only a chanceis this the slowest loopincludestdiohincludestdlibhint main int p int i0 piforp0p100p do nothing printfd i return 0if i make nearly all variables pointerstyle and only three variables only primitive type with register keyword does compiler make those three variables really register with a higher chanceok problem solved i learned some assembly and found out that this depends on optimization level and also variables volatility using asm makes sure it computes in a registerthanks,['c'] +315004,javascript oop lost this in asynchronous callback i have problem which still bothers me on js oop i am sure i am doing it bad but i cant get how to do it rightfor example i have this codeauthprototypeauth function var request new xmlhttprequest requestopenget thisgetauthserverurl token true requestsend requestonloadend function var response jsonparserequestresponsetext consolelogresponse ifresponseresult found var token responsetoken thissettokentoken thisissigned true else consolelognot logged yet the problem is that i cant access to function settoken from context of requestonloadend function its probably because i lost reference to thiswhats a solution of this problem can i somehow pass the this var to context of this functionthanks,['javascript'] +315012,replace the last element in a list with another list for example i have two arrays a array1 and array2array1 a b c d e farray2 g h inow i want the output asarray1 a b c d e g h ihow can i do this in python,['python'] +315028,how to install and run osgi bundle in apache karaf i have a simple questioni followed this tutorial and created a helloworld osgi bundlehow can i install and start this bundle using apache karafhow can i refer to the bundle using the osgiinstall command thank you,['java'] +315063,c error expected primaryexpression before aa token i looked at the earlier questions but still i was not satisfied hence i am posting thisi was trying to compile the c code written by someone elsefile1hinclude stdiohinclude stdlibhtypedef struct struct unsigned member1 unsigned member2 str1 struct unsigned member3 unsigned member4 str2 struct unsigned member5 unsigned member6 str3 config t file1cconfig t cfg str1 0x01 0x02 str2 0x03 0x04 str3 0x05 0x06 compiled with std c11 and i get below error why the has been used in code while assigning values home g c stdgnu0x initialze listcppinitialze listcpp34 error expected primaryexpression before aa tokeninitialze listcpp35 error expected primaryexpression before aa tokeninitialze listcpp36 error expected primaryexpression before aa tokeni was not able to understand the reason for error please help,['c++'] +315084,how to generate an xml file from a set of xpath expressions i want to be able to generate a complete xml file given a set of xpath mappingsthe input could specified in two mappings 1 one which lists the xpath expressions and values and 2 the other which defines the appropriate namespacescreatearticle1id 1createarticle1description barcreatearticle1name1 foocreatearticle1price1amount 0createarticle1price1currency usdcreatearticle2id 2createarticle2description some namecreatearticle2name1 some descriptioncreatearticle2price1amount 01createarticle2price1currency usdfor namespacescreate xmlnsns1createarticle xmlnsns1createarticleprice xmlnsns1createarticleid xmlnsns1note also that it is important that i also deal with xpath attributes expressions as well for example i should also be able to handle attributes such ascreatearticletype richtextthe final output should then look something likens1create xmlnsns1 ns1article xmlnsns1 typerichtext namefooname descriptionbardescription ns1price xmlnsns1 amount0amount currencyusdcurrency ns1price ns1id xmlnsns11ns1id ns1article ns1article xmlnsns1 typerichtext namesome namename descriptionsome descriptiondescription ns1price xmlnsns1 amount01amount currencyusdcurrency ns1price ns1id xmlnsns12ns1id ns1articlens1createps this is a more detailed question to a previous question asked although due to a series of further requirements and clarifications i was recommended to ask a more broader question in order to address my needsnote also i am implementing this in java so either a javabased or xsltbased solution would both be perfectly acceptable thnxfurther note i am really looking for a generic solution the xml shown above is just an example,['java'] +315109,better way than if else if else for linear interpolation question is easy lets say you have functiondouble interpolate double xand you have a table that has map of known x yfor example 5 15 7 18 10 22note real tables are bigger ofc this is just example so for 8 you would return 18871072218193one cool way i found is long story short it uses stdmap key x value y for xy data pairsif somebody asks what is the if else if else way in title it is basicallyif x5 x7interpolateelse ifx7 x10 interpolate so is there a more clever way to do it or map way is the state of the art btw i prefer soutions in c but obviously any language solution that has 11 mapping to c is nice,['c++'] +315129,how do i build my linux c app to link to an old version of libc i have built an app on ubuntu 1204 and have tried running it on an embedded system i ran aptcache show libc6 on my dev machine which shows amongst other thingspackage libc6priority requiredsection libsarchitecture i386source eglibcversion 2150ubuntu10replaces belocslocalesbin libc6i386provides glibc2131 libc6i686the version of libc6 that exists on the embedded device is 2890 in the lib directory on the device i have 2 libslibc2890solibcso6when i copy my application onto the embedded device i get the following errorsusrliblibcso6 version glibc 215 not found required by serversocketappi know that if possible i when i build the application on my dev maching i need to force it to link to the same version of libc6 as exists on the embedded device the problem i have is that i simply do not know how to do this any answers that i have found are meaningless to me right now is there some option that i need to pass to g to get this to link to version 2890 in desperation i am thinking is it possible to copy the libc on my dev machine onto the embedded device in place of what is there already and hope for the best i just cannot seem to find any documentation online that explains in simple terms how you even go about this so any advice at all would be really really welcome as i am tearing my hair out here,['c++'] +315151,google cloud messaging gcm service not available i am trying to implement the new gcm i am following google get stated i getting stuck at getting my device registration id my app keep trying to connect with google server here my error logs onreceive comgoogleandroidgcmintentretrygcm intentservice class comdomboxappgcmintentserviceacquiring wakelockgcmintentservice startregistering app comdomboxapp of senders my sender id releasing wakelockonreceive comgoogleandroidc2dmintentregistrationgcm intentservice class comdomboxappgcmintentserviceacquiring wakelockgcmintentservice starthandleregistration registrationid null error service not available unregistered nullregistration error service not availablescheduling registration retry backoff 912617 7680releasing wakelockhere is my activity code asking for an id try logitag checknotifregistration checkdevice gcmregistrarcheckdevicethis logitag checknotifregistration checkmanifest gcmregistrarcheckmanifestthis if gcmregistrarisregisteredthis logitag checknotifregistration reg id gcmregistrargetregistrationidthis final string regid gcmregistrargetregistrationidthis if regidequals sender id is my project id into google account url gcmregistrarregisterthis sender id logitag checknotifregistration reg id gcmregistrargetregistrationidthis else logitag checknotifregistration already registered as regid catchexception e logetag checknotifregistration exception egetmessage eprintstacktrace here my service codepublic class gcmintentservice extends gcmbaseintentservice private static final string tag gcmintentservicepublic gcmintentservice supersender id sender id is my project id into google account url todo autogenerated constructor stub logdtag gcmintentservice startpublic gcmintentservicestring senderid supersenderid todo autogenerated constructor stub logdtag gcmintentservice start sender id senderidand here is my android manifest permission androidnamecomdomboxapermissionc2d message androidprotectionlevelsignature usespermission androidnamecomdomboxapermissionc2d message usespermission androidnamecomgoogleandroidc2dmpermissionreceive usespermission androidnameandroidpermissionwake lock usespermission androidnameandroidpermissionwrite settings usespermission androidnameandroidpermissioninternet usespermission androidnameandroidpermissionaccess network state usespermission androidnameandroidpermissionaccess wifi state application androidicondrawableicon androidlabelstringapp name receiver androidnamecomgoogleandroidgcmgcmbroadcastreceiver androidpermissioncomgoogleandroidc2dmpermissionsend intentfilter action androidnamecomgoogleandroidc2dmintentreceive action androidnamecomgoogleandroidc2dmintentregistration category androidnamecommyappapp intentfilter receiverservice androidnamegcmintentservice androidenabledtrue activity androidnameactivitymyapp androidlabelstringapp name intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activityi am following googles instruction but i stuck with this service not available errorwhat am i doing wrong,['android'] +315182,is it possible to phpunit mock object to replace one created in class i have been trying to get the phpunit mock objects working for some legacy code i am working on but i am having issues getting it to sub in for the object i am after and i am pretty sure it must be because i am using it wrong currently we have a class which is used purely for creating queries when another class wants to make a query it creates an object of this class and passes it the sql and database details what i want to do is have phpunit replace this object with a mock version which i can testwhat i have been finding though is if i create the mock object in the test script the method being tested just bypasses it i am guessing this is because the method is creating and then using the object locally rather than it being passed as a parameter in which case i could just reference the method with the mock object passed as a parameter below is an example of what the code might look likeclass sampleclass function loaddata sql select from users query new query queryquerysql whilerow queryget row ifrowemail thiserrors email missing from user rowuser id result queryget row thisusers result ifcountusererrors 1 return usererrors else return true class query function querysql thisresult mysql querysql function get row return mysql fetch assocthisresult is there a way to create a mock object in the phpunit test file which will replace the query object in sampleclass with a mock object which i can use to test the parameters being passed to and control the response of i would not be able to replace the query class or change how it is referenced as it is used extensively throughout our application but i would like to at least be able to create some form of test framework for it would appreciate any help you can giveedited to clarify that there is more than just the query happening in the loaddata method which is the part of the method i am trying to test i am hoping to sub in a double of the query class method get row which will return a preset array of sample data for the method to work with rather than it hitting an actual database,['php'] +315195,why is the c initializer list behavior for stdvector and stdarray different codestdvectorint x1234stdarrayint 4 y1234why do i need double curly braces for stdarray,['c++'] +315209,difference between mvp mvc and mvvm folks i have gone through many linksblogs i see most of them not able to clearly communicate in layman language and as well technical difference between mvp mvvm and mvc i know what every character stands for and also worked on mvp but dont really understand if someone asks me the same question why cant i use controller in mvp instead of presenter and why view model in mvvm instead of presenter and how does it differs i can in a single sentense saymvc is optimized for aspnet and also has templates in vs mvp is optimized for winforms and mvvm for slwpf as it supports inbuilt binding features etc but i feel that its not what i have to understand but in detail and deep could some one throw light on this with detailed explanation and usage and actual reason to choose one thank you all,['asp.net'] +315253,jquery find by two attr values i have table cells with attributes datapositionx and datapositiony with integer values i want to find one certain cell by x and y values is it possible in jquery at the moment i cannot figure out how i can pass two predicates to construction datapositionx0,['jquery'] +315263,in python how can i turn this format into a unix timestamp mon jul 09 092028 0 2012if i have a format like that as a string how can i turn it into a unix timestampnote i am getting this format from twitters api timelinejsoninclude entitiestrueinclude rtstruescreen nametwitter,['python'] +315269,graphics2d transformation result does not match manual transformation i am using javas graphics2d to draw on a component using affinetransforms to manipulate my drawinggraphics2d offers an method transform for this which takes an affinetransformsometimes i need to manipulate a point manually without using the builtintransformationbut when i try to transform a point using the same transformation i gave to graphics2dtransform sometimes the resulting point is not the samethe following code reproduces the problem it is scala code but i think you can imagine the java code var transformationmatrix new affinetransform transformationmatrix is modified throughout the program override def paintcomponentg graphics2d superpaintcomponentg 1 transform using graphics transform gtransformtransformationmatrix gsetcolorcolorred gfillnew rectangle0 0 1 1 2 transform point manually gsettransformnew affinetransform reset transformation to standard val p0 new point0 0 val pdest new point transformationmatrixtransformp0 pdest gsetcolorcolorblue gfillnew rectanglepdestx pdesty 1 1 expected behaviourthe blue rectangle manually calculated overdraws the red one calculated by transformexperienced behaviouri admit that my transformationmatrix is not really integer but that shouldnt be the problem should it affinetransform 11 00 52055 00 11 1825495 00 00 10is this a bug or am i missing some deep insightedit you can reproduce the bug if you set transformationmatrix totransformationmatrix new affinetransform11 00 00 11 52155 1835495at the beginning of paintcomponent please note that g is of type graphics2d,['java'] +315302,inlinable constant c array with no memory duplication i want to declare a constant array which can be accessed from multiple c files and whose content can be inlined by the compiler without duplicating the memory in multiple compilation units performance is critical in my applicationexhibit 1headerhstatic const int arr2 1 2 file1cinclude headerhvoid file1 printfdn arr0 file2cinclude headerhint file2 for int i 0 i 2 i printfdn arri in that case the compiler can replace arr0 by 1 in file1 however since arr is declared static const its memory is duplicated in both c files afaik the c standard requires the array addresses to be different in both files i have verified this under linux by printing out the addresses no linker consolidation occurs even with fmergeallconstants in gccexhibit 2headerhextern const int arr2file1cinclude headerhvoid file1 printfdn arr0 file2cinclude headerhconst int arr2 1 2 int file2 for int i 0 i 2 i printfdn arri in that case no memory duplication occurs but arr0 is not inlinedi consider the visibility scope defined by the c standard to be flawed as such a working solution under linuxgcc which violates the c standard is acceptable to me,['c'] +315311,how do i login as root on mysql on os x i have just set up mysql on my computer os x 107 and it seems to be working judging by the mysqld in the activity monitor and the new icon in my system preferenceshowever i am having trouble doing anything with mysql as i need to login at least as the root user but it does not let me so let us run through what i have been doing and what error messages i am gettingfirstly i start up mysql via the mysql unix executable file this seems to work as my entries are now preceded with mysql also i can type helpand i get mysqls help list so then i go to do something like create a database create database booksbut i get the following error error 1044 420 access denied for user localhost to database booksso then i figure i need to login and that logging in as the root user should be enough i enter the following mysql u root pbut i get the 1064 error saying my syntax is wrong i have had a look around through a number of websites and this never seems to be a problematic step any clues on whats going wrong for me,['mysql'] +315318,how to implement the apispi pattern in java i am creating a framework that exposes an api for developers to usepublic interface myapi public void dosomestuff public int getwidgetsboolean hasrunall the developers should have to do is code their projects against these api methods i also want them to be able to place different driversapi bindings on the runtime classpath the same way jdbc or slf4j work and have the api method calls dosomestuff etc operate on different 3rd party resources files servers whatever thus the same code and api calls will map to operations on different resources depending on what driverbinding the runtime classpath sees ie myapiftp myapissh myapiteleportationhow do i write and package an spi that allows for such runtime binding and then maps myapi calls to the correct concrete implementation in other words if myapiftp allows you to getwidgetsboolean from an ftp server how would i could this up to make use of both the api and spibonus points for concrete working java code example thanks in advance,['java'] +315325,launch installed app on tethered iphone i am working on trying to launch an automated testing solution for some ios applications i am using fruitstrap to transfer and install a compiled app over to the connected iphone but i am struggling to find a way to automatically launch the application after the installation is completefruitstrap has an option to run the app in the gdb debugger which works unfortunately there are some test cases which will require the app to be run without the debugger attached special crash handling i have spent a good amount of time muddling through the resources available on mobiledevice library which is what fruitstrap uses but i have not been able to turn anything up on launching an appany ideas,"['iphone', 'ios']" +315334,boostasio async condition the idea is to be able to replace multithreaded code with boostasio and a thread pool on a consumerproducer problem currently each consumer thread waits on a boostcondition variable when a producer adds something to the queue it calls notify onenotify all to notify all the consumers now what happens when you potentially have 1k consumers threads would not scale i decided to use boostasio but then i ran into the fact that it does not have condition variables and then async condition variable was bornclass async condition variableprivate boostasioio service service typedef boostfunctionvoid async handler stdqueueasync handler waiters public async condition variableboostasioio service service service service void async waitasync handler handler waiters pushhandler void notify one service postwaiters front waiters pop void notify all while waiters empty notify one basically each consumer would call async condition variablewait then a producer would eventually call async condition variablenotify one or async condition variablenotify all each consumers handle would be called and would either act on the condition or call async condition variablewait again is this feasible or am i being crazy here what kind of locking mutexes should be performed given the fact that this would be run on a thread pool ps yes this is more a rfc request for comments than a question,['c++'] +315335,cannot install aptana plugin on eclipse 42 i have installed eclipse 42 juno now i want to install aptana for developing ruby but i get the following errorunable to read repository at unable to read repository at read timed out,['ruby'] +315344,php code is suddenly showing up in my web page rather than executing was not doing this before blocks or pieces of php code are showing up in my web page suddenly as though they are not being recognized as php code i had it working just find before and i cannot think of anything i have changed or done that would have stopped it from working i spent so long getting apache mysql and php working together in the first place and now this i am ready to tear my hair outexample 1example 1 codenote that one php code block is showing up in the web page while the other is notfieldset legendenter select statementlegend textarea nameselect stylewidth 100 marginbottom 10px php if isset postselect echo postselect textarea input typesubmit valuesearch thisplay any sql errors here php echo hello world if isset postselect if results mysql query postselect dieerror mysql error fieldsetexample 2example 2 codefieldset legendtagslegend table classtagstable tr classtagsrow tr php query show columns from recipes like tags if ret mysql queryquery dieerror could not show columns mysql error ifmysql num rowsret0 rowmysql fetch rowret optionsexplodepreg replaceenumset2row1 foreach options as tag echo script typetextjavascriptaddtag tag falsescript table br input typetext idaddtaginput typesubmit valueaddfieldsettroubleshootingmy phpinfo page works as expectedfolder containing phpexe is included in my pathtried restarting apachefollowed all steps in the answer to this questionusing apache 2 mysql server 5524 php 543 windows 7apache httpdconf containsloadmodule php5 module cwebsitesphpphp5apache2 2dllifmodule dir module directoryindex indexhtml indexhtm indexphpifmoduleaddtype applicationxhttpdphp phpphpinidir cwebsitesphpanything left that i have not thought ofthank you,"['php', 'mysql', 'html']" +315392,listfield without duplicates in python mongoengine i must be missing something really obvious but i cannot seem to find a way to represent a set using mongoengine class itemdocument name stringfieldrequiredtrue description stringfieldmax length50 parents listfieldreferencefieldselfi itemobjectsget or createnametest item0i2 itemnameparents1i2savei3 itemnameparents3i3saveiparentsappendi2iparentsappendi2iparentsappendi3isavethe above code will create a duplicate entry for i2 in the parents field of i1 how do you express a foreign key like relationship in mongoengine,['python'] +315394,measure time in ruby how can i measure the time taken by a method and the individual statements in that method in ruby if you see the below method i want to measure the total time taken by the method and the time taken for database access and rethis access i do not want to write benchmarkmeasure before every statement does the ruby interpreter gives us any hooks for doing this def foo code to access database code to access rethis end,"['ruby-on-rails', 'ruby']" +315427,linking the pressing of enter to a button click with jquery i have some bottons on a modal formdiv classblockfooter alignrightbutton typebuttonsubmitbuttonbutton typebuttonsubmit amp closebuttonbutton typebuttonclosebuttondivhow can i make it so the when a user clicks on the enter key then the first of the buttons submit is clicked it is important for the click action as i want the user to visually see the color of the button change as it is clickednote that i already did the following and tied the execution of a function to that buttonmodal buttoncontainssubmitclickfunction submithandlerdobjlink mainform false,['jquery'] +315488,java stringtokenizernexttoken skips over empty fiels i am using a tab t as delimiter and i know there are some empty fiels in my data egonetwothreewhere equals the tab as you can see an empty field is still correctly surrounded by tabsdata is collected using a loop while strline brreadline null stringtokenizer st new stringtokenizerstrline t string test stnexttoken yet java ignores this empty string and skips the fieldis there a way to circumvent this behaviour and force java to read in empty fields anyway,['java'] +315502,how to solve this error in c i am getting an error when using the following codevar v1 from p in db1quranwordsnews where paye perid select pvar vv v1lastordefault the error occurs herethe messagelinq to entities does not recognize the method tashihquranquranwordsnew lastordefaultquranwordsnew method and this method cannot be translated into a store expression,['c#'] +315531,load rsa public key from file i have generated a private key withopenssl genrsa out file ades3after this i have generated a public key withopenssl rsa apubout in privatekey out filei want to sign some messages with my private key and verify some other messages with my public key using code like thispublic string signstring message throws signatureexception try signature sign signaturegetinstancesha1withrsa signinitsignprivatekey signupdatemessagegetbytesutf8 return new stringbase64encodebase64signsignutf8 catch exception ex throw new signatureexceptionex public boolean verifystring message string signature throws signatureexception try signature sign signaturegetinstancesha1withrsa signinitverifypublickey signupdatemessagegetbytesutf8 return signverifybase64decodebase64signaturegetbytesutf8 catch exception ex throw new signatureexceptionex i found a solution to convert my private key to pkcs8 format and load it it works with some code like thispublic privatekey getprivatekeystring filename throws exception file f new filefilename fileinputstream fis new fileinputstreamf datainputstream this new datainputstreamfis byte keybytes new byteint flength thisreadfullykeybytes thisclose pkcs8encodedkeyspec spec new pkcs8encodedkeyspeckeybytes keyfactory kf keyfactorygetinstancersa return kfgenerateprivatespecand finally my question is how do i load my rsa public key from a filei think maybe i need to convert my public key file to x509 format and use x509encodedkeyspec but how can i do this,['java'] +315535,javascript library to simulate internet explorer javascript environment this is not a duplicate of the js library to simulate internet explorer question about simulating internet explorers css support this is about javascript functionsdoes a javascript library exist which can simulate an environment like internet explorers whereas javascript functions are concernedbasically it would removeoverwrite the functions not supported by older versions of ie like indexof etc or at least force any call to them to be ignored somehoweffectively what i am looking for is something almost like the opposite of underscorejs and which theoretically could even be used to test in nonie browsers that underscorejs is doing what it is meant to do or is the amount of effort needed to simulate the environment so small that i can do it quickly myself if so howthe use case i am imaginingusing this script to simulate an ie7 environment in phantomjss webkit browser for automated by jenkins javascript unittesting with jasmine qunit etc undecided,['javascript'] +315549,loading local data for visualization using d3js i am working on a project which requires me to visualize a rather complicated type of data see this older question in short i have a large chunk of data which i can export to json csv or some other arbitrary flat format although i prefer to avoid xml if possible see the linked question above for indetail explanation of the underlying datai have started working on a visualization using d3 the layout i wrote seems to work ok so far when i test it with some very simple data that i hardcode in the javascript as an array the tutorials i read on data binding in d3 have been a bit confusing in the sense that some use json and some use txtcsv format while some others use hardcoded arraysmatrices in the case of json i watched a tutorial where the narrator firmly advises to host the json file on a webserver and get it using a http request instead of a local file read i realize that this is due to cross domain request limitations which i believe i have to workaround somehow at this point i am not sure how to proceed since the d3powered visualization will be on a series of html reports which are created as results of an analysis tool i wrote the analysis is done on the users computer and the html reports are also created locally on the clientsidethe intended users are most definitely not techsavvy so it is not an option to instruct them to run an webserver on their computer to be able to serve json or any other type or resource via localhostfor the record i have tried running the python simplehttpserver module to try it out and again everything works fine i then tried to hardcode the data in the generated html reports then call on the json object from my script which uses d3 d3jsonmydatajson functionjsond3jsonmyjson functionjson nodedata jsonelementswhich fails since in that case i end up sending in a json object while d3js is expecting a urlwhat can i do to avoidsolve this problem,['javascript'] +315585,angularjs losing scope when using nginclude i have this module routesvar mainmodule angularmodulelpconnect configrouteprovider function routeprovider routeprovider whenhome templateviewshomehtml controllerhomectrl whenadmin templateviewsadminhtml controlleradminctrl otherwiseredirecttoconnecthome htmldiv nginclude srcviewspartial1divpartial1 htmlform ngsubmitaddline input typetext ngmodellinetext size30 placeholdertype your message hereformhomectrlfunction homectrlscope location window http common scopeviews partial1viewspartial1html scopeaddline function scopechataddlinescopelinetext scopelinespushtextscopelinetext scopelinetext in the addline function scopelinetext is undefined this can be resolved by adding ngcontrollerhomectrl to partial1html however it causes the controller to be called twice what am i missing here,"['javascript', 'html']" +315612,eclipse 37 cannot resolve types in c editor i recently changed from eclipse 36 to eclipse 37 which i am using for c development in ubuntu 1104 with version 36 i had no big troubles except that i always had some issues with the indexernow with version 37 it begins marking unresolved types as errors since the indexer seems to thislike me even more my eclipse apparently does not know types like uint16 t or size tin contrary to the thisplayed errors in the code editor my compiler has no problems with compiling the code and resolving all symbols and types so this seems to be a problem of the ide itself are there any ways to avoid this behavior because all the red underlines make my code more and more unreadableupdateokay with some research and the answer from dennis i found out that i need to add some paths toproject properties cc general paths and symbols since i am building for a powerpc instead of a i32 target i can not just add usrinclude instead i needed to addusrpowerpclinuxgnulibcusrinclude for all the standard headers like stdinthalso i neededusrlibgccpowerpclinuxgnu451include for the stdargh now almost all the errors are gone the only function which still troubles me is printf from the header stdioh i looked it up and the header file itself lies within the included paths still i get an error which says function printf could not be resolved i want to note again that these are just errors thisplayed by eclipse the compiling itself works fineso this actually throws up 3 questionsin the project properties the paths and symbols section coheres with the include paths out of the c buildsettingsc includes section this means addingdeleting a path in one of those sections directly affects the entry of the others since the c includes directly coheres with the compiler i wonder why the compiler can compile correcty and finds the headers even if they arent passed to him as a path is there some kind of standard path gcc uses which i do not know aboutwhy does not he find printf in eclipse the headerfile stdioh is included and it also contains the declaration of printf so why does the eclipse code editor tell me that it cannot resolve itwhy are the header files divided so much i am aware that i need other header files if i am building for another traget eg powerpc but why does the gnu gcc separate those headers in different dirs,['c++'] +315641,highcharts remove renderer path here is how it is addedchartrendererpathm 1200 10 v 1500 0 attr strokewidth 2 stroke red addbut how to delete itvar x somevaluechartrendererpathm x 10 v 1500 0 attr strokewidth 2 stroke red add,['jquery'] +315674,c strange behavior return value changes on the return statement i am facing a very very strange behavior my applicationi am going to describe my situation and then explain what is going wrongsituationi have a method with a signature like thisconst structuredef getstructureconst stdstring theme int indexand i call it in this piece of codeconst structuredef sdef 0do sdef ssgetstructuretheme rand ssavailablestructurecount while sdefi am using this dowhile structure because the return value of the getstructure method might be null depending on the combination of theme and index so basically what it does is asking random structures until we get a valid one if you want to know the detail take a look at the screenshotsthe method iterates over a stdvectorstructuredef using it is iterator and for each structuredef it checks if the structure belongs to that theme if so postincrease the counter and check if it is equal to the requested index like this inside the loopif i indexwhen this if succeeds the current structuredef is returnedreturn sdefwhat is going wrongi am using xcode 44 it is debugger to see step by step what is going on which is basically gdbthe method i explained first find a structuredef that matches my needs so it returns that pointer here is a screenshot of the moment just before it is going to return in the debuggerthe line after the forloop is simply return 0here the pointer sdef points to 0x1d563270 which is where the correct instance of the structuredef is locatednext screenshot is what we get in the piece of code where i called that methodas you can see the pointer sdef which got the return value of the method now points to 0x2fe03804 this is not what the method returned at all i am thinking that this is pointer points to somewhere on the stack instead of the heap it should be the heap since the stdvector class stores its objects on the heap righti cannot use valgrind yet since i am on mac os x 108 which is not supported by valgrindi am totally surprised by this behavior i cannot see why this is happening can it be that my compiler is broken or is it doing some strange optimizationthanks in advancemartijnto clarify deadmgs commenti am using different themesironwoodiceetcmy identifiers look like thisiron downside touch and goiron platform 700 65iron wall bangwood platform 600 40etc what i want to do is pick the structure with a specific index within one theme so not the index the set of structures of all themes together but the index of the subset of one theme take a look at the piece of code again updatei gave wrong info the vector is of the type stdvectorstructuredef it stores objects not pointersso what i think i am doing with the operator call is the same as it and it looks like it is working to me it looked a bit stupid to write and after each otherben voigtarchitectureoptimisation,['c++'] +315685,how to enable the java keyword assert in eclipse programwise how can i enable the assert keyword in eclipsepublic class a public static void mainstring args systemoutprintln1 assert false systemoutprintln2,['java'] +315698,directory path types with argparse my python script needs to read files from a directory passed on the command line i have defined a readable dir type as below to be used with argparse for validating that the directory passed on the command line is existent and readableadditionally a default value tmpnon existent dir in the example below has also been specified for the directory argumentthe problem here is that argparse invokes readable dir on the default value even in a situation where a directory argument is explicitly passed in on the command line this causes the script to crap out as the default path tmpnon existent dir does not exist in a context where a directory is explicitly passed in on the command linei could get around this by not specifying a default value and making this argument mandatory or by deferring the validation until later in the script but is a more elegant solution that anyone is aware ofusrbinpythonimport argparseimport osdef readable dirprospective dir if not ospathisdirprospective dir raise exceptionreadable dir0 is not a valid pathformatprospective dir if osaccessprospective dir osr ok return prospective dir else raise exceptionreadable dir0 is not a readable dirformatprospective dirparser argparseargumentparserdescriptiontest fromfile prefix charsparseradd argumentl launch directory typereadable dir defaulttmpnon existent dirargs parserparse args,['python'] +315734,execution time of consecutive executeupdate sql statements how safe is it to use multiple consecutive executeupdate methods on sql databaseconsidering 2 statementsstexecuteupdateinsert table select col1col2 from table where id var idstexecuteupdatedelete from table where id var idhow does they behave does the 2nd statement wait for the completion of 1st or should we check for the returned value number of rows affected and act accordingly with 2nd statement,"['java', 'sql']" +315751,copy or do not copy extra variables in php reading the google developers php performance tips i saw that it is not recommended to make an extra copy of a varibleinstead of thisdescription strip tags postdescriptionecho descriptionit recommends thisecho strip tags postdescriptionthe reason is a possible unnecessary consumption of memorybut doing some searches i saw some rebuttals saing that php implements acopyonwritea memory management this basically means that we can assign a value to as many variables as we like without having to worry about the data actually being copiedso i would like to know if in more complex situations where for example post or get variables will be used in many places of the code whether it is better practice to use or not use extra variables considering these criteria1 security2 maintenance readability3 performanceedit 1i will use the below example to better ilustrate the questionis it better this kind code considering the criteria aboveuser anti injection postuserpass anti injection postpass continue the code using user and passor this postuser anti injection postuser postpass anti injection postpass continue the code using postuser and postpass,['php'] +315796,jtextfield issues with numpad i have recently run into a strange issue with the java jtextfield when i run the following code see below typing a 0 into the text field first sends a paste action then types 0 for example if text is copied to the clipboard text0 is typed when i type 0 similarly typing a 4 replaces the previous character with a 4 i am guessing this is a delete action then the 4 is typed typing 7 clears the text field before typing 7here is the codeimport javaxswingjframeimport javaxswingjtextfieldpublic class main public static void mainstring args jframe frame new jframe jtextfield text new jtextfield frameaddtext framesetsize500 500 framesetvisibletruethe problem is occurring on red hat linux accessed using vnc from windows xp everything runs as expected on window xpupdate no problems with the program on ubuntu either i have also tried using different keyboards and vnc viewersupdate 2 java versionsfor red hat java version 160 17 openjdk runtime environment icedtea6 177 rhel117b17el5x86 64 openjdk 64bit server vm build 140b16 mixed modefor xp java version 170 05 javatm se runtime environment build 170 05b05 java hotspottm client vm build 231b03 mixed mode sharingupdate 3 tried running the program on three different red hat machines all in the same group at work and additionally tried running it from a different xp computer and restartingupdate 4 today i arrived at work to find that the problem had magically gone away however it would really be nice to know why it happened in the first place so that i and anyone else who many encounter this strange issue know how to fix it in the future,['java'] +315802,create a webserver in php without apache i just tried this codephpset time limit0address 1769117136port 90sock socket createaf inet sock stream 0socket bindsock address port or diecould not bind to addresswhile1 socket listensock client socket acceptsock input socket readclient 1024 echo input output url httpipofmyserver90http11 200 okdate tue 10 jul 2012 165823 gmtserver testserver100 phpservlastmodified fri 06 jul 2012 142958 gmtetag 13c008e1b94c42a193de580acceptranges bytescontentlength 441vary acceptencodingcontenttype texthtml socket writeclient output socket closeclientsocket closesockbut there is a problem instead of using the content of output as the headers apache returns its own headersi do not know why because i execute the script via this command php webservphphowever it practically works because when i load the page httpipofmyserver90 from my browser it shows me the headers sent by the client on the server and returns the content of output to the client my browseri want to create my own webserver only in php if it is possible i just want to know how to run it without apache so i can manage my own http headers,['php'] +315841,using both front and back cameras simultaneously android i know this question has been asked many times before i had looked for it over a year ago but did not find anything so posting this question again to gather if there are any new thoughts approaches or hacksi want to be able to capture video from both cameras front and back in an android device my only thought as of now is to some how switch between front and back every 01 sec however i have never been able to code this any help from anyone on this pleasealso another thought is videos are generally captured at 15 or 30 frames per second assume it is at 30 frames per second what if there is a way to alternate these frames to front and back then we could have 15 frames per second of front and 15 frames per second of back video is this possible if yes then how please suggest what happens to the audio maybe we could restrict audio to only one of the video recordings front or back,['android'] +315853,how to send a list of files over a socket in java i have used the code here to send an individual file over a socket however i need to be able to send multiple files basically all files in a directory over the socket and have the client recognize how the separation between files frankly i am at a complete loss for what to do any tips would be helpfulnote 1 i need a way to send the files in one continuous stream that the client can segregate into individual files it cannot rely on individual requests from the clientnote 2 to answer a question i am pretty sure i will get in the comments no this is not homeworkedit it has been suggested that i could send the size of the file before the file itself how can i do this as sending a file over the socket is always done in either a predetermined array of bytes or a single byte individually rather than the long returned by filelength,['java'] +315858,using jshint with expressjs delete a reserved word i am using expressjs ontop of nodejs to create restful api and using grunt to watch my files and automatically lint my javascriptevery time i use the delete function it gets flagged by jshintl218c9 expected an identifier and instead saw delete a reserved wordappdeleteapiusersuserid function deleteuserreq res next i understand that delete is a reserved word but it is chosen by expressjs is there a better way to go about linting my expressjs app any way to turn off this check,['javascript'] +315862,php variables in anonymous functions i was playing around with anonymous functions in php and realized that they do not seem to reach variables outside of themis there any way to get around this problemexamplevariable nothingfunctionnamesomeargument function variable somethingecho variablewill output nothing is there any way that the anonymous function can access the variable,['php'] +315890,efficient way of updating list of entities i am working on a project which allows the user to edit a list of entities i map these entities to view models and thisplay them with editor fields when the user presses the submit button i go through each model and update it like soforeach var viewmodel in viewmodels find the database model and set the value and update var entity unitentityrepositorygetbyidfieldmodelid entityvalue viewmodelvalue unitentityrepositoryupdateentitythe above code works however as you can see we need to hit the database twice for every entity once to retrieve and another to update is there a more efficient way of doing this using entity framework i noticed that each update generates a separate sql statement is there a way of committing all the updates after the loop has finished,"['c#', 'sql']" +315916,c abstract class parameter error workaround the code snippet below produces an errorinclude iostreamusing namespace stdclass apublic virtual void print 0void testa x error abstract class cannot be a parameter type cout hello endlis there a solutionworkaround for this error otherbetter than replacingvirtual void print 0 with virtual void print edit i want to be able to pass any class extendingimplementing the base class a as parameter by using polymorphism ie a x new b testx cheers,['c++'] +315917,is stringiterator necessarily a random access iterator this page states that stringiterator and stringconst iterator are compiler specific iterator types does this mean that that stringiterator made be in a category other than random access iterator,['c++'] +315919,android how to programmatically set the button style in a linearlayout i am programmatically creating a linearlayout for an alertdialog with some buttonsi want to do thislinearlayout androidididfooter androidlayout widthfill parentstyleandroidstylebuttonbarbut with code like thislinearlayout buttons new linearlayoutparentcontextbuttonssetorientationlinearlayouthorizontallinearlayoutlayoutparams buttonsparams new linearlayoutlayoutparamslayoutparamsfill parent layoutparamswrap contenttoplayoutaddviewbuttons buttonsparamsbuttonssetlayoutparamsbuttonsparamsbutton btnadd new buttoncontextbtnaddsettextaddhow can i set the style of the buttons use a button bar programmitically,['android'] +315952,identify label and button control in each page of the web project i am trying one more time to reach out to aspnet experts and hoping to get an answer i am really stuck here and asking for help hopefully my question will not get down voted and i could get an answer purely from technical point of view instead of people simply being judgmental on my approach earlier i posted question as followsaspnet convert aspnet page into page variablethen i looked at following page but still its not working for meload an aspnet 20 aspx page using systemreflectioninside my web application i would like to be able to reference web pages any where in my code like webform1aspx and get a listing of the controls on that page please just look at it from this point of view and not over analyze it is it possible in my page variable p i do not seem to have any controls for webform1aspxhere is my code please help protected void page loadobject sender eventargs e string filepaths directorygetfilesservermappath searchoptionalldirectories foreach string filepath in filepaths if filepathendswithaspx responsewritefilepath br string folders filepathsplit string filename foldersfolderscount 1 string fullpath filename page p buildmanagercreateinstancefromvirtualpathfullpath typeofpage as page liststring controllist new liststring resourcemanageraddcontrolspcontrols controllist foreach string str in controllist responsewritestr br,"['c#', 'asp.net']" +315953,new lines in text within a div i have a little issue related to when i place a text loaded via ajax calli take the contect from a textarea and store it in my database and when i want to show the text in a div it does not respect the new lines so all the text is continuousthe next link show a small example if you type some text with some new lines once you click on the button the text is show into the div and will see that new lines are not showhow can i solve thisthanks,['html'] +315958,why are redundant class name qualifiers allowed i came across some code like thisstruct a a aint struct b a void initint ivoid binitint i aai what is thisint main b b binit2this compiled and ran using vc11 beta with no errors or warnings with w4the apparent intent is for calling binit to reinitialize the bs a base subobject i believe it actually parses as a variable declaration for a new variable named i with type a compiling with clang produces diagnosticsconsoleapplication1cpp14 warning declaration shadows a local variable aai consoleapplication1cpp1022 note previous declaration is here void binitint i consoleapplication1cpp14 error redefinition of i with a different type aai consoleapplication1cpp1022 note previous definition is here void binitint i it seems curious that the type can be referred to with the redundant class qualificationalso aai appears to be parsed differently by vs11 and clanggcc if i do aab clang and gcc create a variable b of type a using the default constructor vs11 errors out on that saying b is an unknown identifier vs11 appears to parse aai as the creation of a temporary a using the constructor aaint with i as the parameter when the redundant qualifier is eliminated vs parses the source as a variable declaration like clang and gcc do and produces a similar error about shadowing the variable ithis difference in parsing explains why vs11 will choke on more than a single extra qualifier ai and why given that clang and gcc can accept one extra qualifier any number more than one extra has the same result as one extraheres another example with the redundant qualifiers in a different context all compiler seem to parse this as a temporary constructionclass foo void barfoo const int main barfoofoowhy are redundant qualifiers allowed at allthere are some contexts where constructors can be referred to such as the syntax for inheriting constructors class d b using bb but vs seems to be allowing it anywhere is vs wrong and are clang and gcc right in how redundant qualifiers are parsedi know vs is still a fair bit behind in terms of standards compliance but i do find it a bit surprising that modern actively developed compilers could be so divergent in this case resolving a redundant qualifier as the name of a constructor even though constructors do not have names vs resolving redundant qualifiers simply to the type resulting in vs constructing a temporary where the others declare a variable it can be made even worse where b baai is parsed by clang and gcc as the most vexing parse but vs sees it as declaring a variable b of type b with an initializer are there still many differences this severeclearly redundant qualifiers should be avoided in portable code is there a good way to prevent this construct from being used,['c++'] +316018,actionbar in a dialogfragment in the calendar app on my galaxy tab 101 when creating a new event a dialog comes up with done and cancel buttons in the title baraction bar areai would like to implement this in my app i have tried using sethasoptionsmenutrue in addition to overriding oncreateoptionsmenu in my dialogfragment subclass but my action items do not appear i have also tried calling getdialoggetactionbar from within oncreateview but it always returns nulli am able to get this working if i start an activity rather than showing a dialog but that takes up the whole screen is there a standard way to do this using a dialogfragment,['android'] +316021,objectivec on linux compile error there seem to be quite a few tutorials on how to do this each slightly different i am hoping someone can recognize the error messages i am getting and point me in the right directionmy code hm isimport foundationfoundationhint main int argc const char argv nsautoreleasepool pool nsautoreleasepool alloc init nslog hello world pool drain return 0before i compile i enter in the console usrsharegnustepmakefilesgnustepshi try to compile withgcc gnustepconfig objcflags lgnustepbase hm o helloand gettmpccglonpyo in function mainhomegeobjectivechm4 undefined reference to objc get classhomegeobjectivechm4 undefined reference to objc msg lookuphomegeobjectivechm4 undefined reference to objc msg lookuphomegeobjectivechm5 undefined reference to nsloghomegeobjectivechm6 undefined reference to objc msg lookuptmpccglonpyo in function objc gnu inithomegeobjectivechm8 undefined reference to objc exec classtmpccglonpyodatarel0x0 undefined reference to objc class name nsconstantstringtmpccglonpyodatarel0x8 undefined reference to objc class name nsautoreleasepoolcollect2 ld returned 1 exit statuscan somebody point me in the right directiontia,['objective-c'] +316025,override css media queries i work with a page every day that uses css media queries i do not like i would rather use the full page most of them are related to the twitter bootstrap menu collapsing when narrower than 768pxis there a way to override bootstraps media queries with css preferably without defining my own media queries to override all of the rules individually as i feel like this would take a pretty long time edit i do not have control of the source code otherwise i would just kill the bootstrapresponsive code,['css'] +316044,change color of the overflow button on actionbar is it possible to change the color of the overflow button3 vertical dots on the action barif so how do we do that i did not find any style for overflow buttonthanks,['android'] +316048,how to create and project with adt r20 without including the android support library i have recently update my adt to rev 20 but now i find that newly created project always included the android support library i do not want to use the fragmentactivity class which is defined in the support library i just want to use the pure fragment classi tried to delete the support library via the sdk manager tool but now i cannot create any projects since the adt is reporting this template depends on the android support library which is either not installed is there any method to by pass this except for create a project by shell command,['android'] +316061,android camera recording video but plays upside down i record a video using the below code and it records perfectly but when it plays the video it plays it upside downi tried settings mrecsetorientationhint180 before mrecprepare but it was useless any hintsimport javaiofileimport javaioioexceptionimport javalangreflectinvocationtargetexceptionimport javalangreflectmethodimport androidappactivityimport androidhardwarecameraimport androidmediamediarecorderimport androidosbundleimport androidosenvironmentimport androidutillogimport androidviewmenuimport androidviewmenuitemimport androidviewsurfaceimport androidviewsurfaceholderimport androidviewsurfaceviewimport androidviewwindow author sana hassan public class camerasurfaceview extends activity private preview mpreview private mediarecorder mrec new mediarecorder private int cameraid 0 private camera mcamera override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate requestwindowfeaturewindowfeature no title mpreview new previewthis setcontentviewmpreview override public boolean oncreateoptionsmenumenu menu menuadd0 0 0 start menuadd0 1 0 stop return superoncreateoptionsmenumenu override public boolean onoptionsitemselectedmenuitem item switch itemgetitemid case 0 try startrecording catch exception e eprintstacktrace mrecrelease break case 1 mrecstop mrecrelease mrec null break default break return superonoptionsitemselecteditem protected void startrecording throws ioexception mrec new mediarecorder mrecsetcameramcamera mcameraunlock file directory new fileenvironmentgetexternalstoragedirectorynicuvideos directorymkdirs mrecsetaudiosource mediarecorderaudiosourcemic mrecsetvideosourcemediarecordervideosourcecamera mrecsetoutputformatmediarecorderoutputformatmpeg 4 mrecsetoutputfileenvironmentgetexternalstoragedirectorynicuvideossystemcurrenttimemillismp4 mrecsetpreviewthisplaympreviewgetholdergetsurface mrecsetvideosize640 480 method methods mrecgetclassgetmethods for method method methods try ifmethodgetnameequalssetaudioencodingbitrate methodinvokemrec 12200 else ifmethodgetnameequalssetvideoencodingbitrate methodinvokemrec 80 else ifmethodgetnameequalssetaudiosamplingrate methodinvokemrec 80 else ifmethodgetnameequalssetvideoframerate methodinvokemrec 20 catch illegalargumentexception e eprintstacktrace catch illegalaccessexception e eprintstacktrace catch invocationtargetexception e eprintstacktrace mrecsetaudioencodermediarecorderaudioencoderamr nb mrecsetvideoencodermediarecordervideoencodermpeg 4 sp mrecsetmaxduration60 60 seconds mrecsetmaxfilesize10 approximately 10 megabytes mrecprepare mrecstart protected void stoprecording mrecstop mrecrelease mcamerarelease class preview extends surfaceview implements surfaceholdercallback surfaceholder mholder activity activity previewactivity activity superactivity mholder getholder mholderaddcallbackthis mholdersettypesurfaceholdersurface type push buffers public void surfacecreatedsurfaceholder holder cameracamerainfo infonew cameracamerainfo for int i0 i cameragetnumberofcameras i cameragetcamerainfoi info if infofacing cameracamerainfocamera facing front mcameracameraopeni cameraid i try mcamerasetpreviewthisplayholder catch ioexception exception mcamerarelease mcamera null public void surfacedestroyedsurfaceholder holder mcamerastoppreview mcamerarelease mcamera null public void surfacechangedsurfaceholder holder int format int w int h setcamerathisplayorientationmcamera mcamerastartpreview public void setcamerathisplayorientationcamera camera cameracamerainfo info new cameracamerainfo cameragetcamerainfocameraid info int rotation camerasurfaceviewthisgetwindowmanagergetdefaultthisplaygetrotation int degrees 0 switch rotation case surfacerotation 0 degrees 0 break case surfacerotation 90 degrees 90 break case surfacerotation 180 degrees 180 break case surfacerotation 270 degrees 270 break int result if infofacing cameracamerainfocamera facing front result infoorientation degrees 360 result 360 result 360 compensate the mirror else backfacing result infoorientation degrees 360 360 logdvarstag result result camerasetthisplayorientationresult,['android'] +316073,amazon s3 boto how to delete folder i have create a folder in s3 named test and i push test 1jpg test 2jpg into testnow i want to use boto to delete folder testwhat should i do,['python'] +316125,hibernate 400final where is the sessionfactoryopensessioninterceptor interceptor i try some code from hibernate 40 interceptors which gives this code for use sessionlevel interceptorssession session sfopensession new auditinterceptor however i check both the hibernatecore 40 source code and onlie hibernate 40 javadoc the class sessionfactory does not have method opensessioninterceptor interceptor but hibernate 36 javadoc do have this methodanyone knows where is the method move to if deprecated why the document still keeps it in tutorial document and how should i use sessionlevel interceptor in 40,['java'] +316130,android how to open a mail composer view i just want to know how to open mail composer in androidwith ios i would do something like this mfmailcomposeviewcontroller controller mfmailcomposeviewcontroller alloc initcontroller setsubjectmail subjectcontroller setmessagebodymail body ishtmlboolcontroller settorecipientsrecipientslistifcontroller self presentmodalviewcontrollercontroller animatedyeshow about android thanks a lot,['android'] +316161,consuming restful service over https with certficate using java i am a new user to rest services i need to consume a restful api service generated with jersey the problem comes because that service is hosted on remote host and it requires https access with certificatei got my certificate from the organization and i am able to access that rest api service with any of my browsers with certificate set on themi have read lot of posts over here and i have followed the answer on this topicusing https with rest in javanow i have my certificate setup on my java keystore but i do not know how to use that on my java program so it uses exactly the certificate i need to do the https connectionthis is my simple connection code for local testspackage resttestfirstimport javaneturiimport javaxwsrscoremediatypeimport javaxwsrscoreuribuilderimport comsunjerseyapiclientclientimport comsunjerseyapiclientclientresponseimport comsunjerseyapiclientwebresourceimport comsunjerseyapiclientconfigclientconfigimport comsunjerseyapiclientconfigdefaultclientconfigpublic class testclientpublic static void mainstringargs clientconfig config new defaultclientconfig client clientclientcreateconfig webresource serviceclientresourcegetbaseuri fluentinterfaces systemoutprintlnservicepathrestpathhelloacceptmediatypetext plaingetclientresponseclasstostring getplaintext systemoutprintlnservicepathrestpathhelloacceptmediatypetext plaingetstringclass getxml systemoutprintlnservicepathrestpathhelloacceptmediatypetext xmlgetstringclass thehtml systemoutprintlnservicepathrestpathhelloacceptmediatypetext htmlgetstringclassprivate static uri getbaseuri return uribuilderfromurihttplocalhost8080resttestbuildiv read about using system set properties to specify path to keystore with this codesystemsetpropertyjavaxnetsslkeystore pathtokeystorejkssystemsetpropertyjavaxnetsslkeystorepassword passwordi still get 401 error on connection to the remote serverbut then i do not know how to make ssl connection using my certificate on keystorei have been also reading about using sslsocketfactory for this purpose but i could not make it work as explained on this post how do i accept a selfsigned certificate with a java httpsurlconnectioni have managed to retrieve my cert from keystore with this code now i just need to know how to use it in connectionpackage resttestfirst import javaiofileinputstream import javasecuritykeystore import javasecuritycertcertificate public class keystore public static void mainstring args throws exception string keystorefilename usrlibjvmjdk160 32jrelibsecuritycacerts char password changeittochararray string alias remote https server fileinputstream fin new fileinputstreamkeystorefilename keystore keystore keystoregetinstancejks keystoreloadfin password certificate cert keystoregetcertificatealias systemoutprintlncert ok that is the last script i have wrote i can connect to https sites but i still cannot connect to https sites which require to send my certificate to authenticate package resttestfirstimport javaioimport javanetimport javasecurityimport javaxnetsslhttpsurlconnectionimport javaxnetsslsslcontextimport javaxnetsslsslsocketfactoryimport javaxnetssltrustmanagerimport javaxnetssltrustmanagerfactorypublic class urlconnection public static void mainstring args throws exception systemsetpropertyjavaxnetssltruststore usrlibjvmjdk160 32jrelibsecuritycacerts systemsetpropertyjavaxnetssltruststorepassword changeit securityaddprovidernew comsunnetsslinternalsslprovider truststore char passphrase changeittochararray password keystore keystore keystoregetinstancejks keystore keystore keystoregetinstancekeystoregetdefaulttype keystoreloadnew fileinputstreamusrlibjvmjdk160 32jrelibsecuritycacerts passphrase path trustmanagerfactory tmf trustmanagerfactorygetinstancesunx509 instance trustmanagerfactory tmf trustmanagerfactorygetinstancetrustmanagerfactorygetdefaultalgorithm tmfinitkeystore sslcontext context sslcontextgetinstancetls trustmanager trustmanagers tmfgettrustmanagers contextinitnull trustmanagers null sslsocketfactory sf contextgetsocketfactory url url new url httpsurlconnection httpscon httpsurlconnection urlopenconnection httpsconsetsslsocketfactorysf httpsconsetrequestmethodget inputstream instrm httpscongetinputstream systemoutprintlnncontent at url int ch while ch instrmread 1 systemoutprintchar ch instrmclose systemoutprintlnresponse message is httpscongetresponsemessage,['java'] +316168,how can i obtain the named arguments from a console application in the form of a dictionary i have a console application called mytoolexewhat is the simplest way to collect the named arguments passed to this console applicaiton and then to put them in a dictionartystring string which will have the argument name as the key and the value as the argument for examplemytool foo123432 baralora barfoo459i should be able to obtain a dictionary which will bemyargumentsfoo123432 myargumentsbaraloramyargumentsbarfoo459,"['c#', '.net']" +316182,why is oftype faster than cast in answer to the following questionhow to convert matchcollection to string arraygiven the two linq expressionsvar arr regexmatchesstrtext bazazb oftypematch oftype selectm mgroups0value toarrayandvar arr regexmatchesstrtext bazazb castmatch cast selectm mgroups0value toarrayoftype was benchmarked by user alex to be slightly faster and confirmed by myselfthis seems counterintuitive to me as i would have thought oftype would have to do both an is comparison and a cast tany enlightenment would be appreciated as to why this is the case,['c#'] +316259,what does error code 0xc0135 mean when starting a net application symptom is that the application starts correctly on the majority of pcs windows 7 and xp at the users site but on one machine it consistently fails to start with the error the application failed to initialize properly 0xc0135 whats the issue,['.net'] +316282,how to facebook style transition want to implement a view controller transition similar to used in facebook and many other apps snapshot is attached will it require playing with coreanimation framework or is it available in the toolkit,['ios'] +316311,php long integers for thrift my thrift service expects to receive a long integer representing a timestamp in milliseconds but coming from php i know php thrift is supposed to automagically turn my php types into thrift types but which php type does it expect for long integers i think my computer is 64bit but since i think that php integers length is platform dependent i do not really want to depend upon a platformdependent length for my integersi am currently grabbing microtime and multiplying by 10 then converting to integer is this the correct way to work with php thrift long ints,['php'] +316312,how to hide the actionbar before the activity is loaded my goal is to show a splash screen on my applications startup right now what it will do is briefly show the actionbar with an otherwise blank page then jump to the splash screen i am trying to figure out how to not show the beginning screen and just start with the splash screen i am trying to use these links for information on how to solve thisactionbar lag in hiding titlein this one i am assuming i can use the same type of method for hiding the actionbar by changing the theme but i do not know what i would actually use as my style to do sohow to hide action bar before activity is created and then show it againand here it talks about adding a line to the manifest that would do it where in the manifest anywhere i put it did not do anything,['android'] +316314,is it possible to optimize maven dependencies automatically i am working on a big project that consists of about 40 subprojects with very not optimized dependencies there are declared dependencies that are not in use as well as used but undeclared dependencies the second case is possible when dependency is added via other dependency i want to remove redundant and add required dependencies i ran mvn dependencyanalyze and got a long list of warnings i have to fix now i wonder whether there is maven plugin or any other utility that can update my pomxml files automatically i tried to do it manually but it takes a lot of time it seems it will take a couple of days of copypaste to complete the task in worse case i can write such script myself but probably ready stuff existshere is how mvn dependencyanalyze reports dependency warningswarning used undeclared dependencies foundwarning orgapachehttpcomponentshttpcorejar41compilewarning unused declared dependencies foundwarning commonslangcommonslangjar24compilewarning orgjsonjsonjar20090211compile,['java'] +316318,code generation tool for sql schema to korma entities is there a tool to convert a sql schema to korma entities,['sql'] +316333,why does my c gzip produce a larger file than fiddler or php if i gzip this texthello worldthrough c using this codestream stream new memorystreamencodingdefaultgetbyteshello worldvar compressedmemorystream new memorystreamusing var gzipstream new gzipstreamcompressedmemorystream compressionmodecompress streamcopytogzipstream gzipstreamclose the resulting stream is 133 bytes longrunning the same string through either fiddlers utilitiesgzipcompress or this php page the result is only 31 bytes longin both cases the input is 11 bytes so i would imagine the php result is correct but obviously this means that i cannot decompress the php zip from within net or visaversa why is the net output so much largeractually it turns out that while the result from php and fiddler are the same length that they are not the same i can decompress the php version in net but not the fiddler version the php page decompresses all three so it looks like there may be an incompatibility between fiddlers and nets implementations of gzip as requested i have uploaded the three outputs to dropbox hereand these are the raw hexdumps of those files not sure if they are really any use like this but i think it shows that the difference between the fiddler and php version is in the header rather than the compressed data itselffiddler010 1f 8b 08 00c2 e6 ff 4f00 ff f3 48cd c9 c9 57 o hw01f 08 cf 2f ca49 01 00 56b1 17 4a 0b00 00 00 iv jphp010 1f 8b 08 0 00 00 0 03 f3 48cd c9 c9 57 hw01f 08 cf 2f ca49 01 00 56b1 17 4a 0b00 00 00 iv jc010 1f 8b 08 0 00 00 04 00 ec bd07 60 1c 49 i020 96 25 26 2f6d ca 7b 7f4a f5 4a d7e0 74 a1 08 m jjt030 80 60 13 24d8 90 40 10ec c1 88 cde6 92 ec 1d 040 69 47 23 29ab 2a 81 ca65 56 65 5d66 16 40 cc ig evef050 ed 9d bc f7de 7b ef bdf7 de 7b efbd f7 ba 3b 060 9d 4e 27 f7df ff 3f 5c66 64 01 6cf6 ce 4a da n fdlj070 c9 9e 21 80aa c8 1f 3f7e 7c 1f 3f22 be 9d 97 080 65 95 7e b7aa cb d9 ff13 00 00 f 56 b1 17 e v085 4a 0b 00 0,['c#'] +316347,rails asset pipleline compile to multiple stylesheets due to a specific setup i would like to split the compiled stylesheets in two files this is because a part of the css is needed for a java application which can parse the css but it is a bit buggy and cannot handle some csshacksyntax because i am unable to modify this java application i want to feed it only the css which it needs and of which i can make sure it is correctso normally the assets pipeline would produce just one assetsapplicationcss file it would to let it also generate assetscustomcss based on a file selection i make this still can be precompiledis there a way to do this although i understand this is not the ideal setup,['ruby-on-rails'] +316356,python callback from swig pyobject call segfault i have a wxpyshellshell widget which lets the user execute python code that interacts with my program i want to be able to pass a function that the user defines in this space to my c code through the wxswig generated wrapper around my custom widgetand execute itin my c code i am using a stdfunction class to invoke bound functions c or pythonso i created a simple class to wrap the pyobject with the function call operator however i get a segfault when i try to call the pyobject class pymenucallback pyobject funcpublic pymenucallbackconst pymenucallback op2 pymenucallbackpyobject func pymenucallback void operator int idpymenucallbackpymenucallbackpyobject func funcfunc py xincref func ifpycallable checkfunc cout not a callable callback endl throw an exception or somethingpymenucallbackpymenucallbackconst pymenucallback op2 func op2func py xincref func ifpycallable checkfunc cout not a callable callback endlpymenucallbackpymenucallback py xdecref funcvoid pymenucallbackoperator int id cout calling callback endl if func 0 func py none pycallable checkfunc return cout building args endl pyobject arglist py buildvalue iid cout func funcob typetp name funcob refcnt endl pyobject result pyobject callfuncarglist0 segfaults here cout executed endl py decrefarglist py xdecrefresultin my attempts to find what was going on i put a bunch of print statements one of which prints the type name and reference count the line before the segfault this results in function 3 so i have to assume the function has not been destroyed yeti am passing the following to swigvoid addoption stdstring name pyobject pycallbackin which i construct a pymenucallbacki am at a loss for whats causing the segfault any ideas,"['c++', 'python']" +316379,why are the first characters in my asp login labels in italics i cannot work out why the first characters of all the labels on my asp login forms are showing in italicsthe code looks like thisasplogin destinationpageurlblahaspx runatserver usernamelabeltextemail address asploginwhen i inspect it using firebug it shows that the first characters are being enclosed in tags like solabel forctl00 ctl00 ctl00 contentplaceholderdefault wwcontentarea ctl03 usernameemeemmail addresslabellabel forctl00 ctl00 ctl00 contentplaceholderdefault wwcontentarea ctl03 passwordempemasswordlabeldoes anyone know what may be causing this i thought it might have been something to do with access keys if i press alte then it focuses to the email text box but i cant work out how to stop this,"['asp.net', '.net']" +316383,copy contents of one directory to another using ruby how can i copy the contents of one directory to another for example given nonempty directories a and ba bar foob jam jimi want to copy everything from a into b resulting ina bar foob bar foo jam jimi cannot use fileutilscp r because it copies the directory itselfirbmain0010 require fileutils trueirbmain0020 dir a abar afoo b bjam bjimirbmain0030 fileutilscp rab nilirbmain0040 dir a abar afoo b ba babar bafoo bjam bjimis there a better shorter more efficient answer than the followingdiraeach f fileutilscpfb,['ruby'] +316388,best hosting for ruby on rails as of 2012 i was wondering what people think is currently the best host for ruby on rails i found some older posts on here on the subject but i wanted to know what the current agreement is shared hosting is ok for now but i would like an option from dedicated hosting laterthanks,['ruby-on-rails'] +316393,use method other than unicode in modelchoicefield django i am working on some forms in django one field is a foreignkey in the model so represented as a modelchoicefield in the form the modelchoicefield currently uses the unicode method of the model to populate the list which is not my desired behavior i would like to be able to use another method of the model from the docs it looks like i can force my own queryset but i cannot see how this would help me use a method other than unicode i would really rather avoid divorcing this from the default form methods if at all possibleany suggestions,['python'] +316398,acaccountstore error 5 when attempting to save an account into an acaccountstore i sometimes receive this error later if i attempt to access this account i find that it is actually been saved so far i have yet to find any information about this nondescript error does anyone know what it meanserror domaincomappleaccounts code5 the operation could not be completed comappleaccounts error 5,['ios'] +316422,uiview round corners with shadow i am trying to thisplay a uiview with round corners and with a drop shadow but the problem is that masktobounds property only works for either of the case if masktobounds is yes then round corners show up and when no then shadow shows up here is the implementation but it only thisplays round corners with no shadow selfview setbackgroundcoloruicolor colorwithpatternimageuiimage imagenamedblue gradientjpeg selfviewlayermaskstobounds yes selfviewlayeropaque no selfviewlayercornerradius 150f selfviewlayershadowcolor uicolor blackcolorcgcolor selfviewlayershadowradius 50 selfviewlayershadowoffset cgsizemake30 30 selfviewlayershadowopacity 09fideasnote i have read and implemented the code in the following thread but it does not work uiview with rounded corners and drop shadowupdate 1 i tried to create two separate views one will represent the radius and one will represent the shadow the problem is that is creates the shadow on top of the radius view as shown in the screenshot below here is the code selfviewlayermaskstobounds yes selfviewlayeropaque no selfviewlayercornerradius 150f selfviewbackgroundcolor uicolor clearcolor selfviewbackgroundcolor uicolor colorwithpatternimageuiimage imagenamedblue gradientjpeg uiview shadowview uiview alloc initwithframecgrectmake0 0 100 100 shadowviewlayershadowcolor uicolor blackcolorcgcolor shadowviewlayershadowradius 20 shadowviewbackgroundcolor uicolor clearcolor shadowviewlayershadowoffset cgsizemake30 30 shadowviewlayershadowopacity 09f shadowviewlayershadowpath uibezierpath bezierpathwithrectcgrectmake0 0 100 100cgpath selfview addsubviewshadowviewupdate 2 inverted still does not work no round corners are created uiview roundcornerview uiview alloc initwithframecgrectmake0 0 100 100 roundcornerviewlayermaskstobounds yes roundcornerviewlayeropaque no roundcornerviewlayercornerradius 150f selfviewlayershadowcolor uicolor blackcolorcgcolor selfviewlayershadowradius 20 selfviewbackgroundcolor uicolor clearcolor selfviewlayershadowoffset cgsizemake30 30 selfviewlayershadowopacity 09f selfviewlayershadowpath uibezierpath bezierpathwithrectcgrectmake0 0 100 100cgpath selfview addsubviewroundcornerviewsolution uiview roundcornerview uiview alloc initwithframecgrectmake0 0 100 100 roundcornerviewlayermaskstobounds yes roundcornerviewlayeropaque no roundcornerviewlayercornerradius 150f roundcornerviewbackgroundcolor uicolor colorwithpatternimageuiimage imagenamedblue gradientjpeg selfviewlayershadowcolor uicolor blackcolorcgcolor selfviewlayershadowradius 20 selfviewbackgroundcolor uicolor clearcolor selfviewlayershadowoffset cgsizemake30 30 selfviewlayershadowopacity 09f selfviewlayershadowpath uibezierpath bezierpathwithrectcgrectmake0 0 100 100cgpath selfview addsubviewroundcornerview,['ios'] +316437,highlight a section inside pdf using pdfjs i am currently using pdfjs for my project for rendering pdf now there is this tricky task to highlight a section of pdf page given the coordinate example given a boundary section like 3135403540403140 i should highlight the given section with nay primary color of choicehow to write a javascript to actually using pdfjs api to accomplish this taskis it possible or am i sounding over ambitions,['javascript'] +316440,center text larger than container without using separate child element using css it is easy to horizontally center text in a container using textaligncenter but if any single word of that text is larger than the width of the container the browser automatically clips to the left boundary of the container as in the oversized word aligns with the left side of the toosmall container and without the css wordbreakhyphenate property setting or similar the oversized word sticks out past the right edge of the containerany way to float this pic left of my text here to save vertical space oh well anywaywithout using a child container element to hold the text is there a way to center the oversized word so that it hangs over both left and right sides of the container equallyagain i do not want to use a text container within the container i could do this in 5 seconds by using a child divtext to be centereddiv with fixed width and negative marginleft or with absolute positioning of a container element inside a relative div but i am looking for a css attribute that will center text even when the word is too long to fit the width by default textaligncenter does not do thisthoughts thanks slink,['css'] +316455,how to thisplay items sidebyside without using tables for example you want to thisplay an image beside a text usually i would do thistable tr tdimg td tdtexttd trtableis there a better alternative,"['html', 'css']" +316464,whats the easiest way to remove empty nsstrings from an nsarray in php it is one line of codearray without empty strs array filterarray with empty strswhats the objective c equivalentupdate added the following test code to illustrate the use of nikolai ruhe is solution solution test codensmutablearray myarray nsmutablearray alloc init myarray addobjectnsnumber numberwithint5myarray addobjectmyarray addobjecttestnslog myarraymyarray removeobjectnslog myarray solution test code output20120712 081816271 calculator1527f803 5 test20120712 081816273 calculator1527f803 5 test,"['iphone', 'objective-c']" +316479,how can i mock dependencies for unit testing in requirejs i have an amd module i want to test but i want to mock out its dependencies instead of loading the actual dependencies i am using requirejs and the code for my module looks something like thisdefinehurp durp functionhurp durp return foo function consoleloghurpbeans bar function consolelogdurpbeans how can i mock out hurp and durp so i can effectively unit test,['javascript'] +316518,how to change the group id of a file on rooted android device i am trying to give access to a file i have written in one app to another appchgrp is not available in the adb shell command chgrp not foundi have installed busybox but in order to get access to chgrp for example i use the command chown app 79 filetxt and it works but when i try chgrp app 79 filetxt it always returns something like chgrp unknown group app 79i googled a bunch and found that most linux systems have a file etcgroup which stores the group information for that system but it is not present in android,['android'] +316559,safe to change base class in python questions like this exist but none exactly like this and i found no completely satisfactory answersi am doing an agentbased biological model suppose i have a class of cell type a and one of type b they age according to a clock suppose when a cell of type a reaches a certain age it changes to a cell of type bi have an inventory of cells i do not want to just create new b cells and add them to the inventory and leave the a cells still in the inventorythis appears to work but is it safeclass bobject passclass aobject def changetobself self class bor is there a better approach,['python'] +316575,combining multiple regex substitutions i am trying to delete some things from a block of text using regex i have all of my patterns ready but i cannot seem to be able to remove two or more that overlapfor exampleimport rer1 ri amr2 ram footext i am fooresubr1 text returns fooresubr2 text returns i how do i replace both of the occurrences simultaneously and end up with an empty stringi ended up using a slightly modified version of ned batchelders answerdef cleanself text mask bytearraylentext for pattern in patterns for match in refinditerpattern text r rangematchstart matchend maskr x lenr return joincharacter for character bit in ziptext mask if not bit,['python'] +316585,how to set up pylint to only do some inspections i am trying to set up pylint to only do certain inspections and no others eg only check for w0601 and w0612 i have tried using an enable line the the messages control section of my pylintrc but that does not seem to do what i wanti am using pylint 0251,['python'] +316589,numpy and scipy for preinstalled python 267 on mac os lion is there anyway to install numpy and scipy on python 267 that comes with mac os lion i am aware that lion has python 27 as well but i need to stick with python 26 cause i am using a module that does not work on python 27,['python'] +316614,using tor and python to scrape google scholar i am working on a project to analyse how journal articles are cited i have a large file of journal article names i intend to pass them to google scholar and see how many citations each hashere is the strategy i am followinguse scholarpy from this is a pre written python script that searches google scholar and returns information on the first hit in csv format including number of citationsgoogle scholar blocks you after a certain number of searches i have roughly 30 article titles to query i have found that most people use tor tor with python and prevent custom web crawler from being blocked to solve this problem tor is a service that gives you a random ip address every few minutesi have scholarpy and tor both successfully set up and working i am not very familiar with python or the library urllib2 and wonder what modifications are needed to scholarpy so that queries are routed through tori am also amenable to suggestions for an easier and potentially considerably different approach for mass google scholar queries if one existsthanks in advance,['python'] +316621,android billing in the file securityjava should the base64encodedpublickey be the encoded value should i paste the actual public key of my app right into the value of this variableor should i encode it and then whatever the encoded string is i would make that string into the value of this variablewhich should it be,['android'] +316627,redmine deploy on heroku cedar i have been banging my head against the wall trying to deploy redmine 203 on heroku cedari had lots of problems with deploying with sqlite gem so i removed all sqlite references from my gemefile deleted gemfilelock ran bundle install and happily pushed to herokui ran heroku run rake dbmigrate and i browsed to my app and i see the followingupdate when i run heroku run rake dbmigrate i get the following warning messages running rake dbmigrate attached to terminal up run1deprecation warning you have rails 23style plugins in vendorplugins support for these plugins will be removed in rails 40 move them out and bundle them in your gemfile or fold them in to your app as libmyplugin and configinitializersmypluginrb see the release notes for more on this called from top required at apprakefile7deprecation warning you have rails 23style plugins in vendorplugins support for these plugins will be removed in rails 40 move them out and bundle them in your gemfile or fold them in to your app as libmyplugin and configinitializersmypluginrb see the release notes for more on this called from top required at apprakefile7plugins in vendorplugins appvendorplugins are no longer allowed please put your redmine plugins in the plugins directory at the root of your redmine directory apluginsapplication erroran error occurred in the application and your page could not be served please try again in a few momentsif you are the application owner check your logs for detailsi checked the logs and i see the following message20120712t0134470 herokurun1 starting process with command bundle exec rake dbmigrate 20120712t0134470 herokurun1 state changed from starting to up 20120712t0134530 herokurun1 process exited with status 1 20120712t0134530 herokurun1 state changed from up to complete20120712t0136030 herokurouter error h10 app crashed get bloomingriver8784herokuappcom dyno queue wait service status503 bytesi googled this last line without sucess so that is why i am posting here hoping somebody will help here is my gemfile source gem rails 326 gem prototyperails 321 gem i18n 060 gem coderay 106 gem fastercsv 150 platforms mri 18 mingw 18 jruby gem builder optional gem for ldap authenticationgroup ldap do gem netldap 031 end optional gem for openid authentication group openid do gem rubyopenid 214 require openid gem rackopenid end database gems platforms mri mingw do group postgresql do gem pg 0110 end end platforms jruby do gem jrubyopenssl group postgresql do gem activerecordjdbcpostgresqladapter end end group development do gem rdoc 242 gem yard end group test do gem shoulda 211 gem mocha end local gemfile filejoinfiledirname file gemfilelocal if fileexistslocal gemfile puts loading gemfilelocal if debug ruby d or bundle v instance eval filereadlocal gemfile end load plugins gemfiles dirglob fileexpand pathpluginsgemfile file do file puts loading file if debug ruby d or bundle v instance eval filereadfile end,['ruby-on-rails'] +316638,add a class to a div with javascript example htmldiv idfoo classclass onedivhow can i add the class class two without replacing class oneend resultdiv idfoo classclass one class twodiv,"['javascript', 'html', 'css']" +316668,easy way to integrate jasmine javascript unit testing with tfs build ci i have been writing javascript unit tests using jasmine however those tests run inside a browser not as part of mstest i want my tfs continuous integration builds to break when a javascript unit test fails i know there is a solution for this in visual studio 2012 but i am on 2010 and will be for a long time in the future probablyis there an easy way to integrate jasmine based javascript unit tests with tfs build,['javascript'] +316688,parse a string to date in java i am trying to parse a string to a date this is what i havesimpledateformat sdf new simpledateformate m dd y hhmmss zz zdate date new datetry date sdfparsetime catch parseexception e eprintstacktracethe string to parse is thissun jul 15 2012 1200 gmt0300 fle daylight timei followed the pretty sure i have done everything by the book but it is giving me parseexceptionjavatextparseexception unparseable date sun jul 15 2012 1200 gmt0300 fle daylight timewhat am i doing wrong patterns i have triede m dd y hhmmss ze m dd y hhmmss zz z,['java'] +316727,convert two dimensional array to list in java i have am x n two dimensional array of an object say foo so i have foo foosarray what is the best way to convert this into a listfoo in java,['java'] +316730,simulate color transparency i have rgb color value and alpha value how can i get new rgb value assuming that i have white backgound and alpha is applied,['java'] +316731,eclipse juno why no warning on unused annotated private field in the previous version of eclipse this works fine in errorswarnings i checked unused private field warning but it does not seem to work for examplepublic class main resource private int a i see no warning here,['java'] +316733,integrate google protocol buffers proto files to visual c 2010 i have added a custom build step to my visual studio project files which generates the google protobuf hcc files from the proto input files but i have been wondering if it is possible to start a compile only if the content of the proto files has changedis there a way to tell visualstudio from a custom build step exactly that what is the optimal way to integrate proto files into a visual studio build solutionat the moment at every build the proto file is updated which then also updates the time stamp of the output hcc files which then issues a recompile of everything dependent from that is there a better way around it while still building them directly from visual studio,['c++'] +316746,how to get duration in weeks with momentjs i use momentjs to format durations in human readable formatfor example d is a date objectmomentdsubtractdays 3fromd returns 3 days agonow i would like to get 2 weeks ago but the code below returns the durations in daysmomentdsubtractweeks 2fromd returns 14 days ago io 2 weeks agohow can i get 2 weeks ago with momentjs,['javascript'] +316755,is it okay to set instance variables in a django class based view i trying out djangos class based views cbvsclass blahviewtemplateview template name blahblahhtml def get context dataself kwargs code def getself request kwargs more codenow i know that i can get the request params from selfrequest now say i want to parse these request params and store them within the class can i store those in selfx now obviously based on how classes work this seems straightforwardbut i cannot make out the flow of control looking at the definition of view superclass of templateview the source mentions as view to be the entrypointi thought of setting my instance variables at the beginning of get context data but that does not seem right to do initialization therecan i define an init for my cbvif so will there be threading issues or something where multiple pageaccesses possibly work with a global instance of my parsed datai know this sounds a bit messy but i am just a bit confused with the code flow in cbvs,['python'] +316765,control does not come back to application after uploading photo to instagram what i have done with my applicationimplementedin the application i code for instagram integration in that i successfully open instagram and upload an image to the instagram server also i show the uploaded photoproblemafter the inapp image shares through the instagram integration which is similar to facebook integration the control does not come back to my applicationis it possible to return control to my application after sharing a photo through instagram,"['objective-c', 'ios']" +316796,making highchartsjs charts look good on mobile and desktop i am wondering if anyone has successfully implemented a responsive design using highcharts to make their charts look good on both mobile and desktopby default highcharts do rescale when you resize the browser screen its just that the xaxis get cluttered by the tick mark text and bar graphs look tall and too skinny too compressedto get a sense of what i mean you can go to this page and resize the browser i think these issues could possibly be addressed by reducing the amount of data points say to 13 of the original number though i am wondering how that would be accomplished programmatically using highchartss api if that does not sound like a good idea i am also interested in other thoughts or solutions people might have come up with to use highcharts on mobile or perhaps even different js charting libraries where a multidevice solution might be easier to implement,"['javascript', 'jquery']" +316815,sencha touch 2 android performance we are developing a sencha touch 2 application which makes use of phonegap to be able to install it as an application and access the storage of a device this works really well on the ipad 2 and the ipad 3 however when we tried to run the application on an android device the performance was very slow the main elements which slowed down the system were lists and carousels when we tried to test the same application through the chrome browser the performance was onpar with that of the ipaddo you have any suggestions on what we can do to improve the performance on android maybe even ditching phonegap for something which works better or if we can force phonegap to run as a chrome browserthank you for your time help,"['javascript', 'android']" +316827,customize uipickerviews skin with images i am developing an iphone application where in i want to have uipickerview as in the image is it possible to change the appearance of uipickerview like this please guide me to do this i am creating it without xibor is there a way to make uipickerview skin transparent sample uipickerview imagethanks in advance,"['iphone', 'objective-c']" +316828,send data from phone to phone over internet is there any way to actually communicate between two android devices over internet without having to have any service between the two devices like posting something to device2 from device1 without having to middleland on any other server or whateveranother question i tried to ping my phone over the internet simply using the ip address which did not work since it seems like my isp shares the same wanip for all the phones or at least a few of them so is there any way to actually ping or send data to my specific phone just by using the ip or my google account or something,['android'] +316830,your php installation appears to be missing the mysql extension which is required by wordpress trying to install wordpress in debian server serverwhere mysql already exist which is running fine in local server but when i am opening my wordpress blog showing this erroryour php installation appears to be missing the mysql extension which is required by wordpressis any one know what is the problem,['mysql'] +316835,is it possible to use mozilla persona browserid with mobile apps is it possible to easily use mozilla persona browser id for native ios and android apps or is it just too much of a hassle getting the information out of the web view,"['android', 'ios']" +316841,handling headset buttons before voice search on jelly bean android jelly bean introduced a voice search which activates with a longpress on the playpause button of a headset as my app requires being able to utilise these longpresses i was wondering if there is any way to either thisable the voice search or make android play fair with the button events,['android'] +316860,custom listview with pinned header causing jank when setting padding i have a custom listview which contains one pinned header and x amounts of pushup views which can be pushed up and hidden above the list viewi have attached image to explain them sorry for the black censorship just to hide customers logo etcmy problem is that if i add a padding to the pinned header view i will get the listview items floating behind it the pinned header view is implemented with the same technique as youll find if you search for pinnedheaderlistview that is a static view and a header in the listviewi have a found a way to enable padding and that is by applying the same padding as the pinned header to the actual listview but only when the static header is visible however the calling of setpadding causes a quite visible jank which i would like to remove does anyone have any idea how to remove this janki have a simple application with simple views and dummy data which does not show this jank so maybe the amount of jank depends on the complexity of cell layoutsprivate void updateifshouldshowstaticheaderview unfortunately setting the padding of the listview causes jank any ideas int bottomoffloatingheader floatingheadergetbottom if bottomoffloatingheader mheaderviewheight staticheaderviewisvisible true staticheadersetvisibilityviewvisible need to set padding of listview to avoid having listview items float behind my padded static header setpadding0 staticheadergetpaddingtop 0 getpaddingbottom else staticheaderviewisvisible false staticheadersetvisibilityviewinvisible need to set padding of listview to avoid having listview items float behind my padded static header setpadding0 0 0 getpaddingbottom first here is the image showing the pushedup headershere is an image showing how things get drawn behind the padded static pinned viewit is worth noticing that it works as intented if i adjust the padding of the listview but i will get jank slowdown at the time it switches onoff the static header view,['android'] +316866,warning nokogiri was built against libxml version 273 but has dynamically loaded 278 after making a fresh install of mac os x 108 mountain lion and after installing ruby 193 and ruby on rails 326 i started the rails console and i got this warning messagewarning nokogiri was built against libxml version 273 but has dynamically loaded 278how can i fix it,['ruby-on-rails'] +316878,how to cast int to enum in c possible duplicate generic way to cast int to enum in chow do i cast an int to an enum in cfor exampleenum test a bint a 1how do i convert a to type testa,['c++'] +316960,tool for generating graph from xml data i want to generate graph from large xml files it is actually a calling context tree generated by an execution of the program a small file looks like belowfrom this xml i would like to have a graph which contains 4 nodesone node for each method tag ie main methoda methodb and method c as the tree shows from the indentation main calls methoda then methoda calls methodb and methodc so the i want a graphfigure like something like beloware there any open source tools which can do this for me the xml files are extremely large around 7 mb so the graph would really be huge i want the tool to handle this properly it is good if the tool works on linux otherwise on windows will also be ok but first preference is linuxi can also consider some good library in java through which i can do thisthanks,['java'] +316981,alternatives to django for python based web development i am about to start a new personal web iphone app project which requries the followingstoring data on the backendauthenticating the user via openidgenerate json based apis for reading and writing datai normally use django for all of my projects but thought i would take this opportunity to learn something new so are their any python based web development frameworks that are good alternatives to django ideally ones that are strong on the points listed abovebonus points if the framework islightweighteasy to install deploy and developwithany recommendations,['python'] +317006,split a string by commas but ignore commas within doublequotes using javascript i am looking for a b c d e f g hto turn into an array of 6 elements a b c def g h i am a bit of a noob with regex so any help is great i am trying to do this through javascript this is what i have so farstr strsplitg but right now it is splitting out everything that is in the doublequotes which is incorrectthanks for any helpedit okay sorry i worded this question really poorly i am being given a string not an arrayvar str a b c d e f g hand i want to turn that into an array using something like the split function,['javascript'] +317013,us eastern standard time vs eastern standard time in net in listing all the id properties of the timezoneinfos returned by timezoneinfogetsystemtimezones two versions of est appear us eastern standard time and eastern standard time whats the differencei also see both us mountain standard time and mountain standard time but i am pretty sure that is because the us version is for arizona which does not observe dst i would assume the regular mountain standard time applies for the rest of the us states in the mountain time zone am i correcthelpful link on us time zones zoneshtml,"['c#', '.net']" +317014,jquery select all if not thisabled i am using the following script to select all checkboxes with a given classdocumentreadyfunction 1 2 checkboxselectallonclick function 3 checkboxclass thisdatacheckboxname propchecked thispropchecked checkboxclass thisdatacheckboxname triggerchange however i am having a problem as the deselect all checkbox is able to deselect checkboxes which are thisabledi tried thisdocumentreadyfunction 1 2 checkboxselectallonclick function 3 checkboxclass thisdatacheckboxname thisabled propchecked thispropchecked checkboxclass thisdatacheckboxname thisabled triggerchange but it does not work i have made a jsfiddle to showcase the problem,['jquery'] +317028,excute a function after all images whithin a div loaded i want to get height of a div with jquery and in this div there is some images that change the size of this div when loadedbut with code below it gives me height of div before images were loadeddocumentreadyfunction link moduleeach function maxheight mathmaxmaxheightthisheight heightmaxheighti have changed my code to this but nothing changedocumentreadyfunction link module imgload function link moduleeach function maxheight mathmaxmaxheightthisheight heightmaxheight can anyone help me change the code to reach my goalthanks in advance,['jquery'] +317058,observabledefer need some clarification as to what exactly it does say i want to generate an asynchronous stream of random numbers that pumps out a new value every 100 milliseconds while trying to come up with a solution my first attempt looked something like this var random new random observablestart randomnext delaytimespanfrommilliseconds100 repeat subscribeconsolewritelineif you try and run this youll notice that it just keeps repeating the same value over and over again ok i guess i misunderstood how repeat works after playing around for a bit i came up with this and it worked var random new random observabledefer observablestart randomnext delaytimespanfrommilliseconds100 repeat subscribeconsolewritelineso i went to the msdn documentation to understand what defer is actually doing and this is what it saysreturns an observable sequence that invokes the observable factory whenever a new observer subscribesi guess my confusion is this in my code sample i am only ever subscribing to the observable once so why is it seemingly invoking the observablestart over and over or am i misunderstanding repeat any clarification would be awesome,"['c#', '.net']" +317059,string formatting with a0da does not convert to integer this is about the same issue as in this question about floatswhen youve got a value that could get converted to an integer the old d would convert it but format does notclass myintegertenclass def int self return 10 def str self return tenten myintegertenclassprint d 02x s ten ten ten okprint 0formatten okprint 0d 002xformatten valueerror unknown format code d for object of type stris there a way to modify the behaviour of format without touching the class of the value to be formatted without adding a format method to that classedit my goal is to get the formatting dependent on the format string but not on the valueso if the format string says d or x convert the value to int and then to decimal or hexadecimal representationif the format string says s convert it to string directly as the old didactually i could even add a format method to the class of the value but how do i check in that method if the given format specification is an integer format specification without reimplementing the format specification parser of the builtin formatedit heres a solution with format and exceptions any better ideasclass myintegertenclass def int self return 10 def str self return ten def format self spec fmt 0sspec try return fmtformatstrself except return fmtformatintselften myintegertenclassprint d 02x s ten ten ten ok prints 10 0a tenprint 0d 002x 0formatten ok prints 10 0a ten,['python'] +317096,corresponding rotated object to numeric values i have a combination lock rotating in a 360 degrees circlethe combination lock has numerical values on it these are purely graphicali need a way to translate the images rotation to the 099 values on the graphicin this first graphic the value should be able to tell me 0in this graphic after the user has rotated the image the value should be able to tell me 72here is the code package costscombinationlockimport androidosbundleimport androidappactivityimport androidgraphicsbitmapimport androidgraphicsbitmapfactoryimport androidgraphicsmatriximport androidutillogimport androidviewgesturedetectorimport androidviewmenuimport androidviewmenuitemimport androidviewmotioneventimport androidviewviewimport androidviewgesturedetectorsimpleongesturelistenerimport androidviewviewontouchlistenerimport androidviewviewtreeobserverongloballayoutlistenerimport androidwidgetimageviewimport androidsupportv4appnavutilspublic class combolock extends activity private static bitmap imageoriginal imagescaled private static matrix matrix private imageview dialer private int dialerheight dialerwidth private gesturedetector detector needed for detecting the inversed rotations private boolean quadranttouched private boolean allowrotating override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity combo lock load the image only once if imageoriginal null imageoriginal bitmapfactorydecoderesourcegetresources rdrawablenumbers initialize the matrix only once if matrix null matrix new matrix else not needed you can also post the matrix immediately to restore the old state matrixreset detector new gesturedetectorthis new mygesturedetector there is no 0th quadrant to keep it simple the first value gets ignored quadranttouched new boolean false false false false false allowrotating true dialer imageview findviewbyidridlocknumbers dialersetontouchlistenernew myontouchlistener dialergetviewtreeobserveraddongloballayoutlistenernew ongloballayoutlistener override public void ongloballayout method called more than once but the values only need to be initialized one time if dialerheight 0 dialerwidth 0 dialerheight dialergetheight dialerwidth dialergetwidth resize matrix resize new matrix resizepostscalefloatmathmindialerwidth dialerheight floatimageoriginalgetwidth floatmathmindialerwidth dialerheight floatimageoriginalgetheight imagescaled bitmapcreatebitmapimageoriginal 0 0 imageoriginalgetwidth imageoriginalgetheight resize false translate to the image views center float translatex dialerwidth 2 imagescaledgetwidth 2 float translatey dialerheight 2 imagescaledgetheight 2 matrixposttranslatetranslatex translatey dialersetimagebitmapimagescaled dialersetimagematrixmatrix rotate the dialer param degrees the degrees the dialer should get rotated private void rotatedialerfloat degrees matrixpostrotatedegrees dialerwidth 2 dialerheight 2 need to print degrees dialersetimagematrixmatrix return the angle of the unit circle with the image views center private double getangledouble xtouch double ytouch double x xtouch dialerwidth 2d double y dialerheight ytouch dialerheight 2d switch getquadrantx y case 1 return mathasiny mathhypotx y 180 mathpi case 2 case 3 return 180 mathasiny mathhypotx y 180 mathpi case 4 return 360 mathasiny mathhypotx y 180 mathpi default ignore does not happen return 0 return the selected quadrant private static int getquadrantdouble x double y if x 0 return y 0 1 4 else return y 0 2 3 simple implementation of an link ontouchlistener for registering the dialers touch events private class myontouchlistener implements ontouchlistener private double startangle override public boolean ontouchview v motionevent event switch eventgetaction case motioneventaction down reset the touched quadrants for int i 0 i quadranttouchedlength i quadranttouchedi false allowrotating false startangle getangleeventgetx eventgety break case motioneventaction move double currentangle getangleeventgetx eventgety rotatedialerfloat startangle currentangle startangle currentangle break case motioneventaction up allowrotating true break set the touched quadrant to true quadranttouchedgetquadranteventgetx dialerwidth 2 dialerheight eventgety dialerheight 2 true detectorontoucheventevent return true simple implementation of a link simpleongesturelistener for detecting a fling event private class mygesturedetector extends simpleongesturelistener override public boolean onflingmotionevent e1 motionevent e2 float velocityx float velocityy get the quadrant of the start and the end of the fling int q1 getquadrante1getx dialerwidth 2 dialerheight e1gety dialerheight 2 int q2 getquadrante2getx dialerwidth 2 dialerheight e2gety dialerheight 2 the inversed rotations if q1 2 q2 2 mathabsvelocityx mathabsvelocityy q1 3 q2 3 q1 1 q2 3 q1 4 q2 4 mathabsvelocityx mathabsvelocityy q1 2 q2 3 q1 3 q2 2 q1 3 q2 4 q1 4 q2 3 q1 2 q2 4 quadranttouched3 q1 4 q2 2 quadranttouched3 dialerpostnew flingrunnable1 velocityx velocityy else the normal rotation dialerpostnew flingrunnablevelocityx velocityy return true a link runnable for animating the the dialers fling private class flingrunnable implements runnable private float velocity public flingrunnablefloat velocity thisvelocity velocity override public void run if mathabsvelocity 5 allowrotating rotatedialervelocity 75 velocity 106f post this instance again dialerpostthis i think i need to translate some information from the matrix to a 099 value,"['java', 'android']" +317101,aspnet mvc 3 partial view in layout page i am working on setting up a shared content navigation for an aspnet mvc layout pagehere is my partial view layoutpartialcshtml with code to pull navigation data from a modelmodel myappmodelsviewmodellayoutviewmodelp foreach var item in modelnavheader test dump of navigation data htmlencodeitemname htmlencodeitemurl phere is how the code for my controller layoutcontrollercs looks likeusing systemusing systemcollectionsgenericusing systemlinqusing systemwebusing systemwebmvcusing myappmodelsviewmodelnamespace myappcontrollers public class layoutcontroller controller get layout layoutviewmodel layout new layoutviewmodel public actionresult index return viewlayout here is the code for the layoutcshtml page i am attempting to call the partial view here using htmlrenderactionactioncontroller methoddoctype htmlhtmlhead meta charsetutf8 headbody p htmlrenderactionindexlayout p renderbodybodyhtmlwhen the layout page executes the htmlrenderactionindexlayout line it throws out an error message error executing child request for handler systemwebmvchttphandlerutilserverexecutehttphandlerasyncwrapper what am i missing friends how can i call a partial view in a layout pagethank you all in advance,['asp.net'] +317166,read logs permission on jelly bean api 16 since android jelly bean does not support the logs reading permission according to this google io 2012 video and this one too i would like to know if it is possible for rooted devices or nonrooted devices to be able to bypass this restriction and be able to read the logshow do i do that do i really need to make the app a system app or is rooting enough,['android'] +317176,line detection angle detection with java i am processing some images that my ugv unmanned ground vehichle captures to make it move on a linei want to get the angle of that line based on the horizon i will try to explain with a few examplesthe image above would make my ugv to keep straight ahead as the angle is about 90 degrees but the following would make it turn left as the angle compaired to the horizon rounds about 120i could successfully transform those images into the image below using otsu for thresholdingand also used an edge detection algorithm to get thisbut i am stuck right now trying to find an algorithm that detecs those edgeslines and outputs or helps me to output the angle of such line,['java'] +317189,can i detect that a method has been overridden suppose heres some arbitrary library code that i do not know aboutclass foo def hi endendclass bar foo def hi endendand suppose i have some code where i am passed bar as a parameterdef checkx do something withxmethodhiendin the above example can i know that xhi where x references an instance of bar is different from foohibased on gareths answer this is what i have got so fardef is overriddenmethod name methodnameto sym return false if methodownersuperclassmethod definedname methodowner methodownersuperclassinstance methodnameownerendhideous gorgeous,['ruby'] +317242,rails geocoder and near i am having a slight issue trying to thisplay certain locations based on proximity to a user in my controller i have this if userfindcurrent user user userfindcurrent user locations locationnearparamslatitude userlatitude longitude userlongitude 50 order thistance endusers have a latitude and longitude stored i am thinking i have not got the right parameters in the locationnear line but i cannot figure out what they should beany help would be appreciatedcheers,"['ruby-on-rails', 'ruby']" +317247,django model field by variable quick question i am trying yo access one of the fields of a model using a variableclass examplemodelmodelsmodel the field modelscharfield the field two modelscharfieldhow would access the field dynamically i triedmodel examplemodelobjectsgetpk1fieldtoget the fieldtest var modelfieldtogetbut it does not seem to work any ideas how i would do thisupdate thought i would update my question i am trying to write a function as part of larger function that can not only get the value of the field but also update it from a variable fieldname for examplemodelfieldtoget yomodelsavein php you can use the wrapper modelfieldtoget as an example for dynamic variable names was hoping there was something similar in python cheers,['python'] +317259,html5 creating a viewport for canvas i have a 2d array that is 30 across 20 down however the viewport only paints 15 across and 10 down i had a game like that originally and i have been trying to achieve something like thisheres my fiddle,"['javascript', 'jquery']" +317270,first char to upper case possible duplicatehow to upper case every first letter of word in a stringmost efficient way to make the first character of a string lower case i want to convert the first letter of a string to upper case i am attempting to use replacefirst as described in javadocs but i have no idea what is meant by regular expressionhere is the code i have tried so farpublic static string cap1stcharstring useridea string betteridea userideauc char char1 userideauc userideatouppercase char1 userideauccharat0 betteridea userideareplacefirstchar1 return betterideaend cap1stcharthe compiler error is that the argument lists differ in lengths i presume that is because the regex is missing however i do not know what that is exactly,['java'] +317283,implementing polygon2d in java 2d i am creating a 2d game in java using the java2d library for drawing and i really need a floatprecision polygon object that i can use both to draw game objects and to do collision detection on them unfortunately javas polygon object comes in int precision only and there is no equivalent polygon2d like there is with rectangle and rectangle2d i have already done enough research to see that i have a few options but none of them seem very gooduse path2d according to a java developer posting in this forum the lack of polygon2d was an oversight but its suggested replacement is path2d unfortunately path2d does not provide a way to access its individual vertices or edges which i need in order to do collision detection specifically i need to get a vector orthogonal to each edgeimplement my own polygon2d that implements the shape interface so that i can still pass it to graphics2ddrawshape this looks like it would be pretty difficult the shape interface requires trickytoimplement methods like containsrectangle2d and getpathiteratoraffinetransform for getpathiterator in particular it seems that in order to implement it i would need to return an object of type pathiterator but there are no concrete implementations of the pathiterator interface available in the public awt packageswrap path2d in an object that remembers the individual vertices and provides them to the client this worked for me when i needed an area that remembered its component shapes i wrapped it in a compoundshape class that implemented the shape interface and forwarded all the shape methods to areas implementation of them while keeping track of each shape that was added to the area in an arraylist the problem with this is that if i keep track of the individual vertices in two arrays of floats there is no way to expose them to the user without the possibility of the user changing the vertices and since that would happen by direct array access the internal path2d wouldnt get notified of the changescopy polygonjava the actual source code of javas polygon class is available on grepcodecom and i could simply replace the vertexrelated ints with floats throughout to get a polygon2d unfortunately when i tried this the line import sunawtgeomcrossings threw a compiler error saying the type crossings is not accessible due to restriction on required library cprogram filesjavajre7librtjar according to this question that happens because suns license agreement prevents you from replacing core java classes with your own but polygon does not try to do that it simply creates an object of type sunawtgeomcrossings no replacing or extending happens and i made sure to put my copy of polygon in a package not called javawhats the best way to proceed with this i would appreciate either suggestions for how make one of these options work or an idea for another option that does not have the problems these encounter,['java'] +317323,thisabling logging on pdfbox we are using pdfbox to do some pdf reading and manipulations but during the parsing i get a bunch of messages like this onechanging font on m from arial bold to the default fontnow how can i thisable these because a message like this is output on every character of the input if the font is embedded and the log files therefore become pretty unusablenow changing the overall log level is not an option because i need the statements from other components i am using tomcat 55 log4j 1216 and pdfboxapp 160and here is my log4j config file root logger optionlog4jrootloggerinfo file stdout direct log messages to a log filelog4jappenderfileorgapachelog4jdailyrollingfileappenderlog4jappenderfilefilehomepdfwspdfloglog4jappenderfilefileclogingloglog4jappenderfilemaxfilesize5mblog4jappenderfilemaxbackupindex1log4jappenderfilelayoutorgapachelog4jpatternlayoutlog4jappenderfilelayoutconversionpatterndiso8601 5p c2 mn direct log messages to stdoutlog4jappenderstdoutorgapachelog4jconsoleappenderlog4jappenderstdouttargetsystemoutlog4jappenderstdoutlayoutorgapachelog4jpatternlayoutlog4jappenderfilelayoutconversionpatterndiso8601 5p c2 mneditafter modifying my log4j file this is how it looks root logger optionlog4jrootloggerinfo file stdoutlog4jrootloggerorgapachepdfboxerror direct log messages to a log filelog4jappenderfileorgapachelog4jdailyrollingfileappenderlog4jappenderfilefilehomepdfwspdfloglog4jappenderfilefileclogingloglog4jappenderfilemaxfilesize5mblog4jappenderfilemaxbackupindex1log4jappenderfilelayoutorgapachelog4jpatternlayoutlog4jappenderfilelayoutconversionpatterndiso8601 5p c2 mn direct log messages to stdoutlog4jappenderstdoutorgapachelog4jconsoleappenderlog4jappenderstdouttargetsystemoutlog4jappenderstdoutlayoutorgapachelog4jpatternlayoutlog4jappenderfilelayoutconversionpatterndiso8601 5p c2 mnno matter where i put the log4jrootloggerorgapachepdfboxerror line errors still keep popping up like this in the log files20120716 153646652 warn fontpdsimplefont changing font on r from arial bold to the default font20120716 153646652 warn fontpdsimplefont changing font on o from arial bold to the default font20120716 1536467 warn fontpdsimplefont changing font on c from arial bold to the default font20120716 1536467 warn fontpdsimplefont changing font on e from arial bold to the default font20120716 1536467 warn fontpdsimplefont changing font on s from arial bold to the default font20120716 1536467 warn fontpdsimplefont changing font on u from arial bold to the default font20120716 1536467 warn fontpdsimplefont changing font on from arial bold to the default font20120716 1536467 warn fontpdsimplefont changing font on p from arial bold to the default fontedit 2after consulting log4j packagespecific logging i thiscovered the right syntaxlog4jloggerorgapachepdfboxerror,['java'] +317324,why is is open nonconst i have a function similar to below which is const and needs to check that a file stream is open prior to continuingbool myclasschecksomestuff const where outputfile is a stdofstream if outputfile is open throw stdruntime error output file not open do more stuffhowever it seems i cannot do this as is open is declared asbool is open ie nonconstto me it seems a bit odd that a function like this which is clearly a pure accessor should be nonconst is there a logic behind it which makes sense,['c++'] +317339,how to set a popup on markers with google maps api i have this code where i thisplay and set all my markers how can i add a popup with some information on markers with this code i add i variable on text but it sets on all markers popup with test 723 where 723 is last value of the i variable what is wrongfor var i 0 i arraylnglength1 i var marker new googlemapsmarker position new googlemapslatlngarraylngi arraylati var infowindow new googlemapsinfowindow content googlemapseventaddlistenermarker click function infowindowsetcontenttest i infowindowopenmap this markerspushmarker,['javascript'] +317346,how to use streamwriter class properly i have code like this where i am using streamwriter class for file operation is there any problems in this code do i need to put try catch block closing should be in finally block or this code is sufficient streamwriter sr new streamwriterstreamfolder srwritedetails filesetattributesstreamfolder fileattributeshidden srclose,['c#'] +317350,python generator with check for empty condition python generators are good replacements for lists in most cases expect where i would like to check for empty condition which is not possible with plain generators i am trying to write a wrapper which will allow checking for empty condition but is still lazy and gives the benefit of generatorsclass mygen def init selfiterable selfiterable x for x in iterable selfpeeked false selfpeek none def iter self if selfpeeked yield selfpeek selfpeeked false for val in selfiterable if selfpeeked yield selfpeek selfpeeked false yield val if selfpeeked yield selfpeek selfpeeked false def nonzero self if selfpeeked return true try selfpeek selfiterablenext selfpeeked true return true except return falsei think it behaves correctly like a plain generator is there any corner casei am missing this does not look elegant is there a better more pythonic way of doing the samesample usagedef get oddl return mygenx for x in l if x2def print oddodd nums if odd nums print odd numbers foundlistodd nums else print no odd numbers foundprint oddget odd2468print oddget odd24687,['python'] +317369,apply twitter bootstrap validation style and message to aspnet mvc validation how can i integrate aspnet mvc unobtrusive validation and twitter bootstrap i want to have all those validation messages and styles appropriately,['css'] +317401,numberofrowsinsection not called on reloaddata i have a uitableview that uses an array to list data this works finei also have an uisearchbar for searching in that tableview when data is matched in the tableviews array those rows are added to another mutable array and cellforrowatindexpath thisplays data from that mutable array insteadbut numberofrowsinsection is never called when i call reloaddata therefore the tableview crashes when scrolling because it is trying to get data from the mutable array but for rows that are in the original array which has more itemsi have debugged for quite a while now but can not for the love of god find the reasons for this datasource and delegate are hooked up in the tableview because it can show the data from the original array nsintegertableviewuitableview tableview numberofrowsinsectionnsintegersection nslogissearching d issearching return the number of rows in the section ifissearching return originalarray count nslogissearching return searchcopylistofitems return searchcopylistofitems count uitableviewcell tableviewuitableview tableview cellforrowatindexpathnsindexpath indexpath static nsstring cellidentifier cell uitableviewcell cell tableview dequeuereusablecellwithidentifiercellidentifier ifcell nil cell uitableviewcell alloc initwithstyleuitableviewcellstylesubtitle reuseidentifiercellidentifier ifsearching celltextlabeltext originalarray objectatindexindexpathrow else celltextlabeltext searchcopylistofitems objectatindexindexpathrow return cell,"['iphone', 'objective-c']" +317413,asynchronous delegates vs threads replacing threads not threadpool thread with asynchronous delegates callbacksmy scenario spawn a threaddelbegininvoke per clientaccording to mereasonsneed for notification via callback call delegate again in callbackavoid thread overhead delegates use threadpool threadpassing arguments avoid casting to object and need return value from the method correct me if above reasons are wrong is any other reasons what scenario i exactly need to do some stuff with asynchronous delegates that threads cannot3performance example public delegate void sendcallbacktype sendcallbacktype senderdel new sendcallbacktypesenddata public void startsend this method could be called more than 700 times thread per client senderdelbegininvokesendcallbacknull or thread t new threadnew threadstartthreadsend tisbackground true tstart async delegate void senddata string data quedatadequeue raiseondatadata raise to event void sendcallbackiasyncresult ar senderdelbegininvokesendcallback null thread void threadsend while true string data quedatadequeue raiseondatadata raise to event from the above which option would be the best performance,['c#'] +317440,what in ttsservice could explain the lack of onutterancecompleted for playearcon a while ago i thiscovered that playearcon never produces onutterancecompletedat the time i just interpreted the documentation that said called when an utterance has been synthesized as onutterancecompleted being not applicable for earcons because an earcon is not really a result of tts synthesizationbut looking again androids source code i simply cannot find an explanation that would justify my interpretationa few facts about my test jigonutterancecompleted always arrives for utterance id preceding the earcon that utterance is an ordinary tts utterance not an earconthe earcon after that does play out ie exactly as intendedonutterancecompleted for that earcon never shows up this is very consistent and reproducible behaviordelving deep into the ttsservice source code there seem to be only 2 methods that could affect the arrival or absence of onutterancecompletedttsserviceprocespeechqueuettsserviceoncompletionif you examine that code you will see that a 3rd candidate ttsservicegetsoundresource is ruled out as being responsible for the lack of onutterancecomplete for my earcon because of fact 2 above the earcon always plays hence getsoundresource cannot possibly return nullusing the same logic the 1st candidate ttsserviceprocespeechqueue can also be ruled out for the same fact 2 the earcon always plays hence the following 2 critical statements are always executed1108 mplayersetoncompletionlistenerthis1 mplayerstartso we are left with the 2nd candidate only ttsserviceoncompletion as a possible explanation for why a playearcon never produces onutterancecompletedpublic void oncompletionmediaplayer arg0 mcurrentspeechitem may become null if it is stopped at the same time it completes speechitem currentspeechitemcopy mcurrentspeechitem if currentspeechitemcopy null string callingapp currentspeechitemcopymcallingapp arrayliststring params currentspeechitemcopymparams string utteranceid if params null for int i 0 i paramssize 1 i i 2 string param paramsgeti if paramequalstexttospeechenginekey param utterance id utteranceid paramsgeti 1 if utteranceidlength 0 thispatchutterancecompletedcallbackutteranceid callingapp procespeechqueuein there there are only 2 conditions that would fail to produce thispatchutterancecompletedcallback currentspeechitemcopy nullutteranceidlength 0but i know for sure that condition 2 can be ruled out because i log all utteranceids and the earcons are definitely therealso examining the entire system loglogvservice tag tts callback thispatch startedthe missing onutterancecompleted could be the result of thispatchutterancecompletedcallback not being called but it could also be the result of mcallbacksmapgetpackagename returning nullso we are left again with 2 possibilities both of which do not make to me much senseby the time an earcons oncompletion is called earcons mcurrentspeechitem is null but whymcallbacksmap is empty what is it and when does it ever get populatedany suggestions or other explanations for solving this mystery,['android'] +317441,android application current activity bring to front issue i have a basic question for which i do not think attaching any codesnippet may help when we press home button while an app is in front we go to the home page and the app loses its focusnow my application has to have notification icon in the status bar and as in my application there is a possibility of having 23 activity visibleone above another in dialogue view in certain situation i am not really sure as to how could i resume such state when i press notification icon in the status barbut when i press home button and then press the application icon in the home screen i get everything as expectedso is there any way by which i can do the same with notification bar icon,['android'] +317473,curlh no such file or directory i installed curl this command i use ubuntusudo aptget install curlwhen i test simple program using g testcppinclude stdiohinclude curlcurlhint mainvoid curl curl curlcode res curl curl easy init ifcurl curl easy setoptcurl curlopt url perform the request res will get the return code res curl easy performcurl check for errors ifres curle ok fprintfstderr curl easy perform failed sn curl easy strerrorres always cleanup curl easy cleanupcurl return 0g shows mefatal error curlcurlh no such file or directorycompilation terminatedcan anyone help me,['c++'] +317503,how to specify version ranges in install requires setuptools thistribute i want to make a package to depend the particular version range eg 050 070 is it possible in install requires option and if so how should it be,['python'] +317524,log4net database logging with custom parameters i have database logging in place using the adonetappender what i would like to do is log the user identity on each log statement however i do not want to use the standard log4net identity parameter for two reasonslog4net warn that its extremely slow as it has to look up the context identityin some service components the standard identity is a service account but we have already captured the user identity in a variable and i would like to use thati have seen code where some people use the log4netthreadcontext to add additional properties but i understand that this is unsafe due to thread interleaving and it is also a performance drainmy approach has been to extend the adonetappenderparameter class thuspublic class useradonetappenderparameter adonetappenderparameter public useradonetappenderparameter dbtype dbtypestring patternlayout layout new patternlayout layout2rawlayoutadapter converter new layout2rawlayoutadapterlayout layout converter parametername username size 255 public override void prepareidbcommand command commandparametersaddthis public override void formatvalueidbcommand command loggingevent loggingevent string data loggingeventrenderedmessagesplit string username data0 commandparametersusername username and then programmatically add this to the current appender like soilog mylog logmanagergetloggerconnectionserviceiappender appenders mylogloggerrepositorygetappendersadonetappender appender adonetappenderappenders0 appenderaddparameternew useradonetappenderparametermyloginfoformat0123 username classname class method messagethe intention here is to use a standard format for messages and parse the first part of the string which should always be the username the formatvalue method of the custom appender parameter should then use only that part of the string so that it can be written to a separate field in the log databasemy problem is that no log statements are written to the database oddly when debugging a breakpoint in the formatvalue method is only hit when i stop the servicei have trawled through loads of stuff relating to this but have not yet found any answershas anyone managed to do this or am i on the wrong trailps i have also tried extending the adonetappender but it doesnt give you access to set the parameter values,['c#'] +317549,change css class properties with jquery is there a way to change a css class properties not the element propertieshere is a practical examplei have a div with class redredbackgroundredi want to change class red background property not elements that have class red background assignedif i do it with simple jqueryredcssbackgroundgreenit will affect the elements that actually have class red up to here is finebut if i make an ajax call and introduce more divs with red class those would not have a green background they will have the initial red backgroundof course i could call the simple jquery again but i would like to know if there is a way to change the class itself with jquery consider this is just a basic example,"['jquery', 'css']" +317562,hoverbefore textdecoration none has no effects as title i am adding icons using icon when adding an icon to an hyperlinka href classiconemail iconlargeemail meathe content inserted by content property shows the underline textdecoration on hover i would like to thisable the textdecoration only for the content beforeclassiconbefore class iconbefore fontfamily icomoon fontstyle normal speak noneiconmailbefore content 37classiconlargebefore class iconlargebefore fontsize 48px lineheight 48pxaclassiconbefore aclass iconbefore marginright 5px verticalalign middlei have tried this but it is not working decoration is still visibleaclassiconhoverbefore aclass iconhoverbefore textdecoration none color white,['css'] +317565,optimization to find complex number as input i am wondering if there is a cc library or matlab code technique to determine real and complex numbers using a minimization solver here is a code snippet showing what i would like to do for example suppose that i know utilde but not x and u variables i want to use optimization fminsearch to determine x and u given utilde note that utilde is a complex number x 15u 50 1i25x0 1 20 starting valuesutilde you 1 exp2 x exp 1i 2 xxout fminsearchvoptimv utilde x0function diff optimv utildex v1u v2diff abs utildeu 1 exp2 x exp 1i 2 x the code above does not converge to the proper values and xout 17318 8760 however if u 50 which is not a complex number then xout 150 50 which are the proper valuesis there a way in matlab or cc to ensure proper convergence given utilde as a complex number maybe i have to change the code above if there is not a way to do this natively in matlab then perhaps onegist of the question is this is there a multivariate ieneldermead or similar algorithm optimization library that is ableto work with real and complex inputs and outputsyet another question is whether the function is convergent or not ido not know if it is the algorithm or the function might i need to change something in the utilde you 1 exp2 x exp 1i 2 x expression to make it convergent,"['c++', 'c']" +317593,recover sa password i have a computer which was used by another employeesql server 2008 r2 was installed but i do not know the sa passwordwhen i try to alter the login it gives below errorcannot alter the login sa because it does not exist or you do not have permissionwhen i try to restore a database it gives a different permission errorwhen i enter the security logins sa properties windows authentication is thisabledcan i change itps password is not password,['sql'] +317600,why 06 is 6 false possible duplicatepython is operator behaves unexpectedly with integers today i tried to debug my project and after a few hours of analysing i would got this 06 is 6falsebut 05 is 5truecould you explain to me whymaybe this is some kind of bug or very strange behavior python 273 default apr 24 2012 054 gcc 470 20120414 prerelease on linux2 type06 type int type6 type int type06 is 6type bool,['python'] +317602,getting site matching query does not exist error after creating django admin i am going through the standard django tutorial to create an admin for an app after commenting the admin related stuff in settings and running syncdb i am getting this messagedoesnotexist at admin site matching query does not existcan anyone help me figure this out,['python'] +317626,framework guide to image recognition augmented reality is there any existing framework or guide that gives or explains how to have your app recognize an image so basically suppose the image was a specific bottle is there framework that allows you to scan the bottle and then recognize that it is a bottle i do not need the whole image overlay stuff or geolocationsso basically only the image recognition half of augmented reality,['android'] +317632,algorithm analysis am i analyzing these algorithms correctly how to approach problems like these 1 x 25 for int i 0 i myarraylength i if myarrayi x systemoutprintlnfound i think this one is on2for int r 0 r 10 r for int c 0 c 10 c if c r 0 systemoutprintlnblahi think this one is o1 because for any input n it will run 10 10 times not sure if this is right3 a 0for int i 0 i k i for int j 0 j i j ai think this one is oi k i do not really know how to approach problems like this where the inner loop is affected by variables being incremented in the outer loop some key insights here would be much appreciated the outer loop runs k times and the inner loop runs 1 2 3 k times so that sum should be k2 k1 which would be order of k2 so would it actually be ok3 that seems too large again do not know how to approach this4int key 0 key may be any valueint first 0int last intarraylength1int mid 0boolean found falsewhile found first last mid first last 2 ifkey intarraymid found true ifkey intarraymid last mid 1 ifkey intarraymid first mid 1this one i think is olog n but i came to this conclusion because i believe it is a binary search and i know from reading that the runtime is olog n i think it is because you divide the input size by 2 for each iteration of the loop but i do not know if this is the correct reasoning or how to approach similar algorithms that i have not seen and be able to deduce that they run in logarithmic time in a more verifiable or formal way5int currentminindex 0for int front 0 front intarraylength front currentminindex front for int i front i intarraylength i if intarrayi intarraycurrentminindex currentminindex i int tmp intarrayfront intarrayfront intarraycurrentminindex intarraycurrentminindex tmpi am confused about this one the outer loop runs and times and the inner for loop runs n n1 n2 n k 1 times so is that on3,['c++'] +317643,415 unsupported media type calling wcf service from ajax i am attempting to call a wcf web service from an aspx page like sovar payload applicationkey 40868578ajax url servicesajaxsupportservicesvcrenotify type post data jsonstringifypayload contenttype applicationjson datatype jsondoing so results in the web server returning the error 415 unsupported media type i am sure this is a configuration issue with the wcf service which is defined as followsoperationcontractwebinvokemethod post requestformat webmessageformatjsonvoid renotifyint applicationkeythere are no entries in the webconfig file so assume that the service uses the default configuration,"['jquery', 'asp.net']" +317658,backbone routing with subviews i am curious how people deal with a situation like this i have an application that at a route like categories thisplays a list of categories when each category is clicked on a list of products in that category appears and the route updates to something like categories1products if i navigate some and then click the back button i should be able to just render the products list view for the previous category without rerendering the categories viewhowever i also need to ensure that when i navigate directly to categories2products the categories list as well as the products list is renderedbasically it means the router would have to respond differently to backforward history navigation than to accessing a url directly is there a common solution to this type of problem,['javascript'] +317677,execute code when visualstudio debugger is exiting i had assumed that when terminating debugging such as by hitting the stop button or hitting shiftf5 that any class implementing a finalizer or ithisposable would be well thisposedi have some classes that implement ithisposable there are a few things i would like to try and do as the application exits from the debugger or from crashing in production right now thispose does not appear to be called nor a finalizer myclassis there a way to do this,"['c#', '.net']" +317687,shared uitableviewdelegate i am writting a subclass of uitableview and i want my subclass to handle some of the uitableviewdelegate methods itself before passing them along to the real delegate as well as forward all the uitableviewdelegate methods not implemented by my subclass in the subclass i have a private propertyproperty nonatomic assign id uitableviewdelegate truedelegatewhich holds the real delegate that all the unimplemented methods should forward to in both my init methods i set selfdelegate selfand i override voidsetdelegateid like thisvoidsetdelegateiduitableviewdelegatedelegate if delegate self truedelegate delegate else super setdelegateself then i override these to handle the message forwardingnsmethodsignature methodsignatureforselectorselaselector nsmethodsignature sig sig selfdelegate class instancemethodsignatureforselectoraselector if sig nil sig nsmethodsignature signaturewithobjctypesvc return sig voidforwardinvocationnsinvocation aninvocation sel selector aninvocationselector if self respondstoselectorselector aninvocation invokewithtargetself else aninvocation invokewithtarget truedelegate the problem is that the unimplemented delegate methods never get called on the tableview therefore they are not given a chance to be forwarded along to the truedelegate object i tried checking for them here boolrespondstoselectorselaselector but that method is never called for the uitableviewdelegate methods although it catches other methods just fine,"['objective-c', 'ios']" +317698,javascript fuzzy time eg 10 minutes ago that is in exact seconds i am making a javascript counter that counts seconds ago i have my time in a js time object and i found a time difference function snippet here on stack overflow but it thisplays 2 hours ago how can i get it to thisplay 5 hours 10 minutes and 37 seconds agoheres what i am working withthis function converts the current time and the timestamp of something into 20 seconds ago instead of a cryptic datefunction timedifferencecurrent previous var msperminute 60 10 var msperhour msperminute 60 var msperday msperhour 24 var mspermonth msperday 30 var msperyear msperday 365 var elapsed current previous if elapsed msperminute return mathroundelapsed10 seconds ago else if elapsed msperhour return mathroundelapsedmsperminute minutes ago else if elapsed msperday return mathroundelapsedmsperhour hours ago else if elapsed mspermonth return approximately mathroundelapsedmsperday days ago else if elapsed msperyear return approximately mathroundelapsedmspermonth months ago else return approximately mathroundelapsedmsperyear years ago and heres what i am using to count up the time each second i would like it to say 5 hours 3 minutes 10 seconds ago and then 1 second later 5 hours 3 minutes 11 seconds agovar newtime new datedatapopularitimestamp10var reltime timedifferencenew datenewtimesetintervalfunction var thetimeel timestamplargefilterfunction return thishtml reltime newtimesetsecondsnewtimegetseconds 1 var reltime timedifferencenew date newtime thetimeelhtmlreltime consolelogreltime 10the variable newtime is the time in the utc javascript date format reltime is that in seconds ago format the interval loops through a bunch of timestamp elements and picks the right one for each time stamp then it adds a second to the time converts it back into fuzzy time seconds ago replaces the html with the new time and logs it in the consolehow do i change 5 hours ago to 5 hours 37 mintues 10 seconds ago the time difference function needs to be modified,"['javascript', 'jquery']" +317702,what do i need to do to get hashfrom xml to work i installed activesupport and required active support in my code but i get a no method error when i try to use the hashfrom xml methodwhat am i missing gem listreturns local gems activesupport 326 bundler 114 i18n 060 json 173 mimetypes 119 multi json 136 rake 0922 restclient 167 rubygemsbundler 103 rvm 135and ruby vreturnsruby 193p194 20120420 revision 35410 x86 64darwin1140the contents of filerb arerequire active support require restclient require json token x user x survey id x responses from api restclientget userusertokentokenversion20surveyidsurvey idformatxml responses hashfrom xmlresponses from apito json puts responsesand ruby filerbreturnsfilerb8in main undefined method from xml for hashclass nomethoderror,['ruby'] +317711,custom textview in android with different color words is it possible to have a textview to have different color for every word or even every letter i tried extending textview and creating it but however i thought of the problem is how would i draw all the the text out at the same time with different colors,['android'] +317712,how do i buildrun this simple mahout program without getting exceptions i would like to run this code which i found in mahout in actionpackage orghelpimport javaioioexceptionimport javautilarraylistimport javautillistimport orgapachehadoopconfconfigurationimport orgapachehadoopfsfilesystemimport orgapachehadoopfspathimport orgapachehadoopiosequencefileimport orgapachehadoopiotextimport orgapachemahoutmathdensevectorimport orgapachemahoutmathnamedvectorimport orgapachemahoutmathvectorwritablepublic class seqprep public static void mainstring args throws ioexception listnamedvector apples new arraylistnamedvector namedvector apple apple new namedvectornew densevectornew double011 510 1 small round green apple applesaddapple configuration conf new configuration filesystem fs filesystemgetconf path path new pathappledataapples sequencefilewriter writer new sequencefilewriterfs conf path textclass vectorwritableclass vectorwritable vec new vectorwritable fornamedvector vector apples vecsetvector writerappendnew textvectorgetname vec writerclose sequencefilereader reader new sequencefilereaderfs new pathappledataapples conf text key new text vectorwritable value new vectorwritable whilereadernextkey value systemoutprintlnkeytostring valuegetasformatstring readerclose i compile it with javac classpath usrlocalhadoop103hadoopcore103jarhomehdusermahouttrunkcoretargetmahoutcore08snapshotjarhomehdusermahouttrunkcoretargetmahoutcore08snapshotjobjarhomehdusermahouttrunkcoretargetmahoutcore08snapshotsourcesjar d myjavac seqprepjavai jar it jar cvf seqprepjar c myjavac now i would like to run it on my local hadoop node i have tried hadoop jar seqprepjar orghelpseqprepbut i getexception in thread main javalangnoclassdeffounderror orgapachemahoutmathvector at javalangclassforname0native method at javalangclassfornameclassjava247 at orgapachehadooputilrunjarmainrunjarjava149so i tried using the libjars parameter hadoop jar seqprepjar orghelpseqprep libjars homehdusermahouttrunkcoretargetmahoutcore08snapshotjar libjars homehdusermahouttrunkcoretargetmahoutcore08snapshotjobjar libjars homehdusermahouttrunkcoretargetmahoutcore08snapshotsourcesjar libjars homehdusermahouttrunkmathtargetmahoutmath08snapshotjar libjars homehdusermahouttrunkmathtargetmahoutmath08snapshotsourcesjarand got the same problem i do not know what else to trymy eventual goal is to be able to read a csv file on the hadoop fs into a sparse matrix and then multiply it by a random vectoredit looks like razvan got it note see below for another way to do this that does not mess with your hadoop installation for reference find usrlocalhadoop103 grep mahusrlocalhadoop103libmahoutcore08snapshottestsjarusrlocalhadoop103libmahoutcore08snapshotjarusrlocalhadoop103libmahoutcore08snapshotjobjarusrlocalhadoop103libmahoutcore08snapshotsourcesjarusrlocalhadoop103libmahoutmath08snapshotsourcesjarusrlocalhadoop103libmahoutmath08snapshottestsjarusrlocalhadoop103libmahoutmath08snapshotjarand thenhadoop jar seqprepjar orghelpseqprepsmall round green apple small round green apple0015100210edit i am trying to do this without copying the mahout jars into the hadoop lib rm usrlocalhadoop103libmahoutand then of coursehadoop jar seqprepjar orghelpseqprepexception in thread main javalangnoclassdeffounderror orgapachemahoutmathvector at javalangclassforname0native method at javalangclassfornameclassjava247 at orgapachehadooputilrunjarmainrunjarjava149caused by javalangclassnotfoundexception orgapachemahoutmathvector at javaneturlclassloader1runurlclassloaderjava202 at javasecurityaccesscontrollerdoprivilegednative method at javaneturlclassloaderfindclassurlclassloaderjava190 at javalangclassloaderloadclassclassloaderjava306 at javalangclassloaderloadclassclassloaderjava247and when i try the mahout job filehadoop jar mahouttrunkcoretargetmahoutcore08snapshotjobjar orghelpseqprepexception in thread main javalangclassnotfoundexception orghelpseqprep at javaneturlclassloader1runurlclassloaderjava202 at javasecurityaccesscontrollerdoprivilegednative method at javaneturlclassloaderfindclassurlclassloaderjava190 at javalangclassloaderloadclassclassloaderjava306 at javalangclassloaderloadclassclassloaderjava247 at javalangclassforname0native method at javalangclassfornameclassjava247 at orgapachehadooputilrunjarmainrunjarjava149if i try to include the jar file i made hadoop jar mahouttrunkcoretargetmahoutcore08snapshotjobjar seqprepjar orghelpseqprepexception in thread main javalangclassnotfoundexception seqprepjaredit apparently i can only send one jar at a time to hadoop this means i need to add the class i made into the mahout core job filemahouttrunkcoretarget cp mahoutcore08snapshotjobjar mahoutcore08snapshotjobjar backupmahouttrunkcoretarget cp workspaceseqprepbinorghelpseqprepclass mahouttrunkcoretarget jar uf mahoutcore08snapshotjobjar seqprepclassand thenmahouttrunkcoretarget hadoop jar mahoutcore08snapshotjobjar orghelpseqprepexception in thread main javalangclassnotfoundexception orghelpseqprepedit ok now i can do it without messing with my hadoop installation i was updating the jar wrong in that previous edit it should bemahouttrunkcoretarget jar uf mahoutcore08snapshotjobjar orghelpseqprepclassthenmahouttrunkcoretarget hadoop jar mahoutcore08snapshotjobjar orghelpseqprepsmall round green apple small round green apple0015100210,['java'] +317736,billing aliens via pos printer and image print i am trying to create a prototype to print bitmap data for a text file to my lan enabled epson pos printer tmt88v while i have no problems to send text and text formatting instructions i dont understand what i have to do to make my printer print the data of the arecibo messagefirst few lines0101010101010101010010101010010110010101010101010101001001011011010110101010101011010110110101100101101011011011010101010101010101the message has 73 rows and 23 columns resulting in 1679 picture elements each of this elements is defined by either a 1 for black or a 0 as white and should be printed as a square of 8x8 or 16x16 dots the result would result in from the printers specificationswhile a as i said a the connecting and sending to the printer is no problem i just dont get what this instruction want to tell me what would in the case of the arecibo message be what numbers do i have to send to the printer do i need to send every dot what does nl nh specify the number of dots of the image data in the horizontal direction as nl nh a 256 meanhere is my simple python program i use for prototyping coding utf8 import structimport socketdef sendinstructionsmysocketl for x in l mysocketsendstructpackh x1def emphasizeonmysocket sendinstructionsmysocket273348def emphasizeoffmysocket sendinstructionsmysocket27330def linefeedmysocketnumber for i in rangenumber sendinstructionsmysocket0x0adef papercutmysocket sendinstructionsmysocket29860def sendtextmysocketstring mysocketsendstringencodeutf8def main mysocket socketsocket socketaf inet socketsock stream mysocketconnect1921681159100 lines helloworld emphasizeoffmysocket linefeedmysocket2 for l in lines if linesindexl 0 emphasizeonmysocket else emphasizeoffmysocket sendtextmysocketl linefeedmysocket2 linefeedmysocket4 papercutmysocket mysocketcloseif name main main,['python'] +317757,slim framework base url i am new to slim framework how to get the base url like with the codeigniter function base urlthanks,['php'] +317770,how to create cfarrayref i am trying to convert just one iphone contact to a vcard using the build in methods the docs say to useabpersoncreatevcardrepresentationwithpeoplecfarrayref people but my delegate method gives me this boolpeoplepickernavigationcontrollerabpeoplepickernavigationcontroller peoplepicker shouldcontinueafterselectingpersonabrecordrefpersoni cannot figure out how to create a cfarrayref with just a single abrecordrefthe docs pointed me to cfarraycreate which confused me even more i do not know enough c to figure this out on my own i read in so that nsarray had something called tollfree bridging and should be interchangeable with cfarrayrefbut did not quite understand how to use it since the compiler complained when i tried just swapping them,['ios'] +317794,ios 5 data encryption aes256 encryptwithkey not found question is about ios5 application i have a view controller where i have some uitextfieldsi would like to encrypt data using aes256 in fact i do not know what are the prerequisite packages that i have to add to do encryption and decryption i have gone trough other posts but too much explanation messed it upkindly let me know what and all packages header files i have to include to encrypt data using aes256chandra,"['iphone', 'ios']" +317800,is unique ptr thread safe is unique ptr thread safe is it impossible for the code below to print same number twiceinclude memoryinclude stringinclude threadinclude cstdiousing namespace stdint main unique ptrint work thread t1 while true const unique ptrint localwork movework if localwork printfthread1 dn localwork this threadyield thread t2 while true const unique ptrint localwork movework if localwork printfthread2 dn localwork this threadyield for int i 0 i workresetnew inti while work this threadyield return 0,['c++'] +317813,sonata admin add custom triggersactions to listedit action i am using sonataadminbundle for managing entities in my application the admins of the site can add videos and some of them first need to be approved by their speakers there is an authorization system working already i have working code which will generate a special link and notify the speaker who can approve or thisapprove the video and notify back the admins automaticallyi would like to customize my admin section so there will be a button ask for authorization next to the videos i am okay having it either in the list action adminacmevideoslist or in the edit action somewhere in the rightnav adminacmevideosxedit whats the best approach to do this the documentation says very little about blocks customization but i found this example which may be the thing i am looking for but i could not figure out how to use itone option is to use the preupdate hook and add a checkbox to the edit action but a button would be much nicer,['php'] +317817,access denied for user rootlocalhost with phpmyadmin when i set the root password in phpmyadmin i get this error1045 access denied for user rootlocalhost using password noi cannot open the phpmyadmin panel what am i doing wrong,"['php', 'mysql']" +317819,stdnext permutation implementation explanation i was curious how stdnext permutation was implemented so i extracted the the gnu libstdc 47 version and sanitized the identifiers and formatting to produce the following demoinclude vectorinclude iostreaminclude algorithmusing namespace stdtemplatetypename itbool next permutationit begin it end if begin end return false it i begin i if i end return false i end i while true it j i i if i j it k end while i k pass iter swapi k reversej end return true if i begin reversebegin end return false int main vectorint v 1 2 3 4 do for int i 0 i 4 i cout vi cout endl while next permutationvbegin vendthe output is as expected my questions are how does it work what is the meaning of i j and k what value do they hold at the different parts of execution what is a sketch of a proof of its correctnessclearly before entering the main loop it just checks the trivial 0 or 1 element list cases at entry of the main loop i is pointing to the last element not one past end and the list is at least 2 elements longwhat is going on in the body of the main loop,['c++'] +317841,c typeid used on derived class does not return correct type maybe i am misunderstanding how inheritance works here but heres my problemi have a class option and a class roomoption that derives from it i have another class room which holds a vector of shared ptrs in main i add a roomoption to that vector then using typeid i check the type and it tells me its an option from what i have read typeid is supposed to return derived types and shared ptrs dont cause slicing so i am not sure what i am doing wrong heres the coderoomhvectorshared ptroption optionsvoid addoptionshared ptroptionshared ptroption getoptionintroomcppvoid roomaddoptionshared ptroption option optionspush backoptionshared ptroption roomgetoptionint i return optionsimainshared ptrroom outsidenew room0 outsideaddoptionshared ptrroomoptionnew roomoption0 go inside hallwaycouttypeidplayergetroomgetoption0namegetendl this line prints class stdtr1shared ptrclass optionit occurs to me that maybe when adding or getting an option the roomoption is casted as an option due to the returnargument type if that is the case then how am i supposed to store a vector of more than one type or am i getting this all wrong,['c++'] +317861,python example for reading multiple protobuf messages from a stream i am working with data from spinn3r which consists of multiple different protobuf messages serialized into a byte streama protostream is a stream of protocol buffer messages encoded on the wire as length prefixed varints according to the google protocol buffer specification the stream has three parts a header the payload and a tail markerthis seems like a pretty standard use case for protobufs in fact protobuf core thistribution provides codedinputstream for both c and java but it appears that protobuf does not provide such a tool for python the internal tools are not setup for this kind of external usetopicprotobufxgmuqxvskoso before i go and cobble together a python varint parser and tools for parsing a stream of different message types does anyone know of any tools for this why is it missing from protobuf or am i just failing to find itthis seems like a big gap for protobuf especially when compared to thrifts equivalent tools for both transport and protocol am i viewing that correctly,['python'] +317870,table column wont take full size of the table view in javafx i am trying to create a table with two columnsi am using the scene builder included in netbeans 72in all the examples i have seen all you need to do is drag the table column to the table and it will take the full size this is not true in my casethis is the fxml file generated by the scene builderjust to be clear i am not changing the table properties from the javathe fxmlxml version10 encodingutf8import javalangimport javanetimport javautilimport javafxgeometryimport javafxsceneimport javafxscenecontrolimport javafxsceneimageimport javafxscenelayoutimport javafxscenetextanchorpane idanchorpane prefheight7580 prefwidth9560 styleclascreen xmlnsfx fxcontrollerbgudcrazcpuuiexpbexperimentbuilderscreen children gridpane idgridpane1 prefheight5170 prefwidth60 anchorpanebottomanchor00 anchorpaneleftanchor00 anchorpanerightanchor00 anchorpanetopanchor00 children label idlabel1 alignmentcenter contentthisplaycenter prefheight380 prefwidth90 styleclasscaption textcreate new experiment textfill990 gridpanecolumnindex0 gridpanerowindex0 font font nameconsolas bold size200 font label hbox idhbox1 alignmentcenter prefheight10 prefwidth20 spacing50 gridpanecolumnindex0 gridpanerowindex1 children label idlabel2 graphictextgap00 styleclassfieldlabel textexperiment name font font nameconsolas size150 font hboxmargin insets top30 hboxmargin label textfield idtextfield1 prefwidth20 hboxhgrowalways button idbutton2 fxidsavebutton styleclassdialogbutton textsave button idbutton3 styleclassdialogbutton textthismiss children padding insets bottom50 left50 right50 top50 fxidx3 padding hbox vbox idvbox alignmentcenter spacing50 gridpanecolumnindex0 gridpanerowindex2 children label idlabel3 prefwidth90 styleclassfieldlabel textexperiment tests vboxmargin insets left50 top50 vboxmargin label hbox idhbox alignmentcenter spacing50 children button idbutton1 prefheight90 styleclassaddbutton textnew hboxmargin insets bottom50 left50 right50 top50 fxidx3 hboxmargin button listview idlistview1 fxidtests orientationhorizontal prefheight90 prefwidth20 hboxhgrowalways hboxmargin insets bottom40 right50 top40 hboxmargin listview children hbox children vbox vbox idvbox1 prefheight20 prefwidth10 gridpanecolumnindex0 gridpanerowindex3 children gridpane idgridpane2 vboxvgrowalways children vbox idvbox2 prefheight3210 prefwidth1500 styleclasswithdashedborder gridpanecolumnindex0 gridpanerowindex0 gridpanerowspan4 children label idlabel4 textalgorithms graphic imageview idemptyimageview1 fitheight320 fitwidth320 preserveratiotrue image image url algopng preserveratiofalse smoothfalse image imageview graphic label button idbutton1 fxidnewalgorithmbutton prefwidth90 styleclassaddbutton textnew vboxmarginx3 children gridpanemargin insets bottom100 left100 right100 top100 fxidx2 gridpanemargin vbox vbox idvbox2 prefheight3210 prefwidth1500 styleclasswithdashedborder gridpanecolumnindex1 gridpanemarginx2 gridpanerowindex1 children label idlabel4 textproblem generator graphic imageview idemptyimageview1 fitheight320 fitwidth320 preserveratiotrue image image url pgenpng preserveratiofalse smoothfalse image imageview graphic label button idbutton1 maxheight90 prefheight90 prefwidth90 styleclassaddbutton textnew vboxmarginx3 vboxvgrowalways children vbox vbox idvbox2 prefheight3210 prefwidth1500 styleclasswithdashedborder gridpanecolumnindex2 gridpanemarginx2 gridpanerowindex1 children label idlabel4 prefwidth90 textcorrectness tester graphic imageview idemptyimageview1 fitheight320 fitwidth320 preserveratiotrue image image url ctestpng preserveratiofalse smoothfalse image imageview graphic label button idbutton1 maxheight90 maxwidth90 prefheight90 prefwidth90 styleclassaddbutton textnew vboxmarginx3 vboxvgrowalways children vbox vbox idvbox2 prefheight3210 prefwidth1500 styleclasswithdashedborder gridpanecolumnindex1 gridpanemarginx2 gridpanerowindex2 children label idlabel4 prefwidth1300 textmessage delayer graphic imageview idemptyimageview1 fitheight320 fitwidth320 preserveratiotrue image image url mdelpng preserveratiofalse smoothfalse image imageview graphic label button idbutton1 maxheight90 maxwidth90 prefheight90 prefwidth90 styleclassaddbutton textnew vboxmarginx3 vboxvgrowalways children vbox vbox idvbox2 prefheight3210 prefwidth1500 styleclasswithdashedborder gridpanecolumnindex2 gridpanemarginx2 gridpanerowindex2 children label idlabel4 prefwidth1300 textlimiter graphic imageview idemptyimageview1 fitheight320 fitwidth320 preserveratiotrue image image url limiterpng preserveratiofalse smoothfalse image imageview graphic label button idbutton1 maxheight90 maxwidth90 prefheight90 prefwidth90 styleclassaddbutton textnew vboxmarginx3 vboxvgrowalways children vbox vbox idvbox2 prefheight3210 prefwidth1500 styleclasswithdashedborder gridpanecolumnindex3 gridpanemarginx2 gridpanerowindex0 gridpanerowspan4 children label idlabel4 prefwidth90 textstatistic collectors graphic imageview idemptyimageview1 fitheight320 fitwidth320 preserveratiotrue image image url scolpng preserveratiofalse smoothfalse image imageview graphic label button idbutton1 prefwidth90 styleclassaddbutton textnew vboxmarginx3 children vbox hbox idhbox1 alignmentcenter prefheight10 prefwidth20 spacing50 gridpanecolumnindex1 gridpanecolumnspan2 gridpanerowindex0 children label idlabel2 graphictextgap00 styleclassfieldlabel textname hboxmargin insets top70 hboxmargin label textfield idtextfield1 maxheight280 minheight280 prefheight280 prefwidth20 textempty test hboxhgrowalways children padding insets bottom50 left50 right50 top50 fxidx3 padding hbox vbox idvbox3 prefheight20 prefwidth10 gridpanecolumnindex1 gridpanerowindex3 children columnconstraints columnconstraints hgrowsometimes minwidth100 prefwidth10 columnconstraints hgrowsometimes minwidth100 prefwidth10 columnconstraints hgrowsometimes minwidth100 prefwidth10 columnconstraints hgrowsometimes minwidth100 prefwidth10 columnconstraints rowconstraints rowconstraints minheight100 prefheight300 vgrowsometimes rowconstraints minheight100 prefheight300 vgrowsometimes rowconstraints minheight100 prefheight300 vgrowsometimes rowconstraints minheight100 prefheight300 vgrowsometimes rowconstraints gridpane children vbox vbox idvbox4 alignmentcenter styleclasswithdashedborder gridpanecolumnindex0 gridpanehalignmentcenter gridpanehgrowalways gridpanerowindex4 gridpanevalignmentcenter gridpanevgrowalways children tableview idtableview1 prefheight540 prefwidth8370 vboxvgrowalways columns tablecolumn prefwidth750 textcolumn x tablecolumn prefwidth750 textcolumn x columns tableview children gridpanemargin insets bottom100 left100 right100 top100 fxidx2 gridpanemargin vbox children columnconstraints columnconstraints hgrowsometimes minwidth100 prefwidth10 columnconstraints rowconstraints rowconstraints maxheight380 minheight380 prefheight380 vgrownever rowconstraints maxheight320 minheight320 prefheight320 vgrownever rowconstraints maxheight10 minheight10 prefheight10 vgrowsometimes rowconstraints vgrowsometimes rowconstraints maxheight10 prefheight10 valignmentcenter vgrowalways rowconstraints gridpane children stylesheets url value stylecss url value stylecss stylesheetsanchorpane,['java'] +317873,allow uiscrollview and its subviews to both respond to a touch i want both my uiscrollview and its subviews to receive all touch events inside the subview each can respond in its own wayalternatively if tap gestures were forwarded to subviews all would be wella lot of people are struggling in this general area here are a few of the many related questionshow does uiscrollview steal touches from its subviewshow to steal touches from uiscrollviewhow to cancel scrolling in uiscrollviewincidentally if i override hittestwithevent in the scroll view i do see the touches as long as userinteractionenabled is yes but that does not really solve my problem because1 at that point i do not know if it is a tap or not2 sometimes i need to set userinteractionenabled to noedit to clarify yes i want to treat taps differently from pans taps should be handled by subviews pans can be handled by the scroll view in the usual way,['ios'] +317887,how to mock localstorage in javascript unit tests are there any libraries out there to mock localstoragei have been using sinonjs for most of my other javascript mocking and have found it is really greatmy initial testing shows that localstorage refuses to be assignable in firefox sadface so i will probably need some sort of hack around this my options as of now as i see are as followscreate wrapping functions that all my code uses and mock thosecreate some sort of might be complicated state management snapshot localstorage before test in cleanup restore snapshot for localstoragewhat do you think of these approaches and do you think there are any other better ways to go about this either way i will put the resulting library that i end up making on github for open source goodness,['javascript'] +317933,nsoperationqueue designated thread i want to use an nsoperationqueue to thispatch coredata operations however operation queue behavior is not always the same eg it thispatches using libthispatch on ios 40os 106 which uses thread pools and a queue might not always use the same thread as nsmanagedobjectcontext requirescan i force a serial nsoperationqueue to execute on a single threador do i have to create my own simple queuing mechanism for that,['objective-c'] +317947,no thisk error using gdal from cnet i am using tamas szekeres builds of gdal including the c bindings in a desktop gis application using c and net 40i am including the entire gdal thistribution in a subdirectory of my executable with the following folder structure pluginsgdalpluginsgdalgdalpluginsgdalgdaldatapluginsgdalprojwe are using epsg4326 and the software is built using 32bit target since the gdal c api is using pinvoke to the 32bit libraries could try 64 bit since tamas provides these have not gotten around to it yetwhen i run my application i get the following errorthis error typically happens when software tries to access a device that is no longer attached such as a removable drive it is not possible to catch this exception because it pops up a system dialogafter thismissing the dialog using any of the buttons the software continues to execute as designedthe error occurs the first time i call the following methodosgeoosrcoordinatetransformationtransformpointdouble inoutthe strange stuffthe error occurs on one and only one computer so fari have run this software in several other computers both 32 and 64 bit without problemsthe error does not ocurr on the first run after compiling the gdal shim library i am using it only occurrs on each subsequent runit happens regardless of release or debug buildsit happens regardless of whether the debugger is attached or notit happens regardless of whether i turn on or off gdaluseexceptions or osruseexceptionsthisabling removable drives causes the bug to thisappear this is not what i consider a real solution as i will not be able to ask a customer to do thisi have tried the followingcatching the errorchanging gdal directories and environment settingschanging computers and operating systems this workedused sysinternals procmon to trace what files are being opened with no luck they all appear to be files that existi rebuilt the computer in question when the hard drive failed to no availcleaning the registry using ccleanerfiles in gdal directory are unchanged on executionassumptionserror is happening in unmanaged codeduring gdal initialization some path is referring to a drive on the computer that is no longer attachedi am also working on the assumption this is limited to a computer configuration errorconfigurationwindows 7 prointel core i7 920 267ghz120 gb ram64bit osdrive c 120 gb ssd with os development visual studio 10 etcdrive d 1 tb wd 10k with data not being accessed for data the questioni either need a direction to trap the error or a tool or technique that will allow me to figure out what is causing it i do not want to release the software with the possibility that some systems will have this behaviour,"['c#', '.net']" +317949,number of downloads in google play i have had an app published on google play for a few months i can see from the developer console that it is had a few downloads but the number of downloads is not shown beside the app icon on the app page as it is for all other appswhy is this do i need to configure something i am not aware ofthanks,['android'] +317950,css transition on hover for child element im trying to pause the thisplay of a child element when it is parent is hovered overhtmlspan divthis is the childdiv some text in the spanspancspan position relative span div thisplay none width 0px opacity 0 transition width 5s webkittransition width 5s transition opacity 5s webkittransition opacity 5sspanhover div thisplay inlineblock width 150px opacity 1aas of right now when the span is hovered the div has no delay before it is shown how would i go about fixing it so there is a pausefiddle here a few notesi originally tried to transition the thisplay but as edward pointed out that is not possible and have sense tried the above which also is not workingsolvedit would appear that any thisplay property in the transition to styling will stop any transition animations from happening to work around this i set the width of the child to be thisplayed to 0px and have it be completely transparent then in the transition to styling i set the correct width and make the div solidhtmlspan divthis is the childdiv some text in the spanspancspan position relative span div position absolute width 0px opacity 0 transition opacity 5s webkittransition opacity 5sspanhover div width 150px opacity 1afiddle here,['css'] +317977,vectorpush back insists on using copy constructor though a move constructor is provided i was receiving a strange error from gcc and cannot figure out why i made the following example code to make the problem more clear basically there is a class defined for which i make its copy constructor and copy assignment operator private to prevent calling them accidentallyinclude vectorinclude cstdiousing stdvectorclass branch public int thprivate branch const branch other const branch operator const branch other public branch th0 branch branch other printf called otherthdn otherth const branch operator branch other printf called otherthdn otherth return this int main vectorbranch v branch a vpush back stdmovea return 0i expect this code to compile but it fails with gcc actually gcc complains that branchbranchconst branch is private which as i understand should not be calledthe assignment operator works since if i replace the body of main withbranch abranch bb ait will compile and run as expectedis this a correct behavior of gcc if so whats wrong with the above codeany suggestion is helpful to me thank you,['c++'] +317978,copy prototype for inheritance i was playing around with javascript in particular simulating object oriented programming with classes and whatnoti knew about this way of achieving inheritancemyclassprototype new anotherclassbut i was not satisfied i did not like how i needed to call the constructor of anotherclass so i was playing around and i came up with something that seemed to work and basically want a second opinionfunction clone obj function clonefactory clonefactoryprototype obj return new clonefactorymyclassprototype cloneanotherclassprototypeby cloning the prototype we get a new copy of it and assign that to myclas prototype so that changing the inherited properties will not affect the parents prototypes properties like this would myclassprototype anotherclassprototypei ran stress tests and this is more efficient under certain circumstances ie when there is a lot of code in the parents constructor otherwise it is about the same another benefit or at least i find it to be beneficial is that it allows to some extent information hiding from the subclasses any privileged methods and members will not be inheritedis there some major pitfall that i am overlookingi am not an expert with javascript actually i am fairly new to javascript so i would like to have a second opinion on this because i cannot seem to find anything through google i do not want to implement bad code,['javascript'] +317991,how do i put my websites logo to be the icon image in browser tabs the image next to the page title in the browser tab how can you link an image here,['html'] +318021,no autoincrement for integer primary key in sqlite3 in the sqlite3 faq it is mentioned that an integer primary key being fed a null value would autoincrement but this is not happening for meto replicate a table in sqlite3 create table dummy serial num integer primary key name text and fill it using python import sqlite3 as litecon liteconnectsomedbcurconcursordata someones namecurexecuteinsert into dummy valuesnull dataconcommitthe first attribute serial num is being shown blank while the name attribute is fine when i do select serial num from dummy i just get a bunch of blank spaces what am i doing wrong,['python'] +318026,java temporary iterators are slowing my android game this question involves memory management in java for performance reasons because i am developing this program as an android game and memory gcs kill my performance so i have done a large amount of work so far and it turns out that i am doing a great job of optimizing the memory usage of my game but i have one problem iteratorshere is what i am doingstart game levelstart allocation tracker this way we ignore all of the allocations that will remain for as long as the level runs i have many objects that only get created once at the beginning of the level and they are not the problemdo a few things in the level and get the allocationsmy allocations are full of this466 24 javautilabstractlistsimplelistiterator 12 javautilabstractlist iterator 465 24 javautilabstractlistsimplelistiterator 12 javautilabstractlist iterator 464 24 javautilabstractlistsimplelistiterator 12 javautilabstractlist iterator 463 24 javautilabstractlistsimplelistiterator 12 javautilabstractlist iterator 461 24 javautilabstractlistsimplelistiterator 12 javautilabstractlist iterator 456 24 javautilarraylistarraylistiterator 12 javautilarraylist iterator 454 24 javautilarraylistarraylistiterator 12 javautilarraylist iterator 453 24 javautilarraylistarraylistiterator 12 javautilarraylist iterator 452 24 javautilarraylistarraylistiterator 12 javautilarraylist iterator so the only objects that are being allocated while my game is running are iterators okay well now to fix it thenwhat code is causing the problem i askedhere it isfor segment side listofsidesgetsides do stuffyes it turns out that foreach syntax calls iterator behind the scenes to populate each element which makes perfect sense and exactly what i expected it to do but i did not realise that it could build up so horribly and cause a performance problem for games if i could get rid of this problem then it would really make my game run like lightning no matter what phone it was on so my question is what would you do to make it so that all of these temporary iterators were not created and then immediately thiscarded resulting in nasty gc runs bonus points for doing so in a way that does not make my code completely ugly and using ndk on android is not an optionps i was thinking that for all of my arraylists i could start using the getint i function as they are arrays behind the scenes and the integer i would use to index that would be placed on the stack and not the heap but for the other objects like a hashmap and linkedlist i am not sure what to do,"['java', 'android']" +318028,algorithm for duplicated but overlapping strings i need to write a method where i am given a string s and i need to return the shortest string which contains s as a contiguous substring twicehowever two occurrences of s may overlap for example aba returns ababax returns xabracadabra returns abracadabracadabramy code so far is thisimport javautilscannerpublic class twicestring public static string getshorteststring s int index 1 i j slength 1 char arr stochararray string res s for i 0 i j i j if arri arrj index i else break if index 1 for i index 1 i j i string tmp new stringarr i i res res tmp else res res res return res public static void mainstring args scanner inp new scannersystemin systemoutprintlnenter the string string word inpnext systemoutprintlnthe requires shortest string is getshortestword i know i am probably wrong at the algorithmic level rather than at the coding level what should be my algorithm,['java'] +318035,c app config does not change i want to save some settings on a config file for future usei am trying to use the regular code that i see on all the tutorials configuration config configurationmanageropenexeconfigurationconfigurationuserlevelnone configappsettingssettingsusernamevalue m strusername i also tried configappsettingssettingsremoveusername configappsettingssettingsaddusername m strusername configsaveconfigurationsavemodemodified configurationmanagerrefreshsectionappsettingsnow i can see that on runtime the file vshostexeconfig on debug folder is changes nut when i close my application all the changes are deletedwhat can i do,['c#'] +318057,create a commonused functions module i have a big projects with dozens of different modulesi do have lots of commonlyused functions which i use in many places in my project for examplechecking if a string contains hebrew charactersgenerating a random 8letters stringguessing binary datas image mime typeconverting html entitlesetcmy questions areis it conventional to put all these functions in a specific module that will be loaded from every code filewhat name should this module have commonpymy code is separated into different packages it is conventional to put the file in the root code folder and load a file that is outside of the packages scope,['python'] +318062,how to create temp table with select into temptable from cte query i have a ms sql cte query from which i want to create a temporary table i am not sure how to do it as it gives an invalid object name errorbelow is the whole query for referenceselect into tempblockeddates from with calendar as select eventid eventtitle eventstartdate eventenddate eventenumdayseventstarttimeeventendtime eventrecurring eventstartdate as planneddate eventtype from eventcalender where eventactive 1 and languageid 1 and eventblockdate 1 union all select eventid eventtitle eventstartdate eventenddate eventenumdayseventstarttimeeventendtime eventrecurring datead 1 planneddate eventtype from calendar where eventrecurring 1 and datead 1 planneddate eventenddate select eventid eventstartdate eventenddate planneddate as eventdates castplanneddate as datetime as dt casteventstarttime as time as stcasteventendtime as time as et eventtitleeventtype from calendarwhere planneddate getdate and eventenumdays like castdatepartdw planneddate as char1 or eventenumdays is nullorder by eventid planneddateoption maxrecursion 0i would appreciate a point in the right direction or if i can create a temporary table from this cte query,['sql'] +318102,undefined symbols for architecture armv7 while integrating speechkit of nuance dragon mobile i integrating my app with speechkit of naunce dragon mobile when run i am below errorundefined symbols for architecture armv7 kcfstreampropertysslpeercertificates referenced from l469 in speechkitlibspeechkitaarmv7mastero l642 in speechkitlibspeechkitaarmv7mastero l643 in speechkitlibspeechkitaarmv7mastero kcfstreamsslvalidatescertificatechain referenced from l469 in speechkitlibspeechkitaarmv7mastero kcfstreamsslallowsanyroot referenced from l469 in speechkitlibspeechkitaarmv7mastero objc class avaudioplayer referenced from objcclassref in speechkitlibspeechkitaarmv7mastero kcfstreamsslpeername referenced from l469 in speechkitlibspeechkitaarmv7mastero kcfstreamsslallowsexpiredroots referenced from l469 in speechkitlibspeechkitaarmv7mastero kcfstreamsslallowsexpiredcertificates referenced from l469 in speechkitlibspeechkitaarmv7mastero seccertificatecopysubjectsummary referenced from l642 in speechkitlibspeechkitaarmv7mastero seccertificatecopydata referenced from l643 in speechkitlibspeechkitaarmv7mastero kcfstreampropertysslsettings referenced from l469 in speechkitlibspeechkitaarmv7masterold symbols not found for architecture armv7clang error linker command failed with exit code 1 use v to see invocationplease suggest me to sort out this error,['ios'] +318107,does filesystemwatcher create its own thread i want this work to be done in a different thread but do i have to create a thread or does it do all the work on different threadslike thread filethread new thread filewatcher new filesystemwatcher filewatchercreated onfileevent filewatcherdeleted onfileevent filewatcherrenamed onrenameevent filewatcherenableraisingevents truefilethreadstart,"['c#', '.net']" +318124,why does listforeach implement a for loop i do not understand why the listtforeach extension method implements a for loop under the hood this opens up the possibility of the collection being modified a normal foreach will throw an exception in this case so surely foreach should react the same wayif you must mutate a collection for whatever reason then surely you should be manually iterating through the collection in a for loopthere seems to be a bit of a semantic contradiction here between foreach and listtforeach am i missing something,"['c#', '.net']" +318145,can periods be used in aspnet web api routes i am working on moving an api project from raw http handlers where i am using periods in the pathshttpservercollectionidformati would like to follow the same url schema in a web api selfhosted version and tried thisvar c new httpselfhostconfigurationbcroutesmaphttproute name defaultapiroute routetemplate controlleridformat defaults new id routeparameteroptional format routeparameteroptional constraints nullunfortunately that does not seem to resolve consistent 404s on foo foobar and foobartxt a similar pattern using a slash before format works finevar c new httpselfhostconfigurationbcroutesmaphttproute name defaultapiroute routetemplate controlleridformat defaults new id routeparameteroptional format routeparameteroptional constraints nulli have not yet delved into the code for the web api and before i do thought i would ask here to see if this is a known or perhaps even justified limitation in web apiupdate i neglected to mention that id and format are strings which turns out to be important for the solution to this question adding a constraint to exclude periods from the id token solves the 404 problem,['c#'] +318147,briefly hiding actionbar without resizing activity i am using a viewpager to scroll between different fragments there are two types of fragments using two different menu resources i am invalidating the menu to switch between those resources when necessary that is all working pretty well but the menu is redrawn without an animationto prevent having to mess with individual menuitems i was hoping i could briefly hide the actionbar while the new menu is loaded showing it when that is done that is working as expected as well but the activity is resized when the actionbar is toggledis there any way to prevent this from happening or otherwise hide the ugly transition between menu resources,['android'] +318150,how do i access the webcam on a macbook what is the proper way in mac os x lion to access the facetimeisight camera built into the macbookmacbook pro and imac i have to imagine there is a way to access this outside of using xcode what libraries do i need to feed to g and how would i compile it i know people have done this i am just not sure how i would go about doing it,['c++'] +318164,keyboard size returning wrong values on ipad after subscribing to uikeyboarddidshownotificationnsdictionary info anotification userinfocgsize kbsize info objectforkeyuikeyboardframebeginuserinfokey cgrectvaluesizenslog nsstringfromcgsizekbsizeprints 352 1024is not this wrong not only is height of keyboard so large how can height be larger than widthor am i missing something,"['objective-c', 'ios']" +318166,escaping in ics preferences do i really have to write version specific string handling i have an app that crashes on ics worked fine up to then though i am not sure if i ever really got a honeycomb platform to test on all of our test phones are either gingerbread or lower and now i have a couple ics phones to play withthe following code called from onresume and onpreferencechangelistener from my preferences page has worked fineprotected void setbatteryalarmsummarystring newvalue preference batteryalarm preference findpreference getstringrstringbattery low alarm stringbuilder summary new stringbuilder summaryappendgetstringrstringbattery alarm summary label summaryappend summaryappendnewvalue summaryappend batteryalarmsetsummarysummarythis sets the pref summary to low battery alarm at 10 now with ics it crashes not when it does the setsummary and not when the page thisplays but when you scroll the preferences even a little bit obviously triggering a render this item is about 8 or so items down so it is below the fold on the list fixing ics is easy just escape the percent signsummaryappendhowever that code on gingerbread thisplays low battery alarm at 10i can write it to change based on version but that is just silly did they really break backward compatibility on their preferences rendering or is this just a samsung thing which unfortunately is the only test platform i have for ics right now,['android'] +318173,mysql insert on duplicate key delete is there a way of removing record on duplicate key in mysqlsay we have a record in the database with the specific primary key and we try to add another one with the same key on duplicate key update would simply update the record but is there an option to remove record if already exists it is for simple inout functionality on click of a button,['mysql'] +318178,how do negative margins in css work and why is margintop5 marginbottom5 a common trick for vertical positioning elements is to use the following cssitem positionabsolute top50 margintop8px half of height height 16pxwhen seen in the metric view as in chrome this is what you seehowever there is no visual margin depicted when you hover over the element ie the margin is outside the border and can be visualized but negative margins do not show up how do they look and what is it that makes it differentwhy is margintop8px not the same as marginbottom8pxso just how do negative margins work and whats the intuition behind them how do they bump up in case of margintop 0 an item,['css'] +318201,why cannot errnos value be printed i am looking at the following code in an so low quality post to make sure the sample works and my question is why cannot i print errnos valueinclude stdiohinclude stdlibhinclude errnohint main file fp errno 0 fpfopennot existtxtr iffp null errno enoent perrorfile not exist return 0here is what happens when i try to print the valuegdb p errnocannot find threadlocal variables on this targetgdbi can print fps value just fine as you would expect it is value is 0x00i looked at usrincludeerrnoh and a lot of the other include files included as part of errnoh and i cannot figure out how errno is defined any pointers or help would be appreciated i am just curious about it nothing is broken thank you,['c'] +318203,unit testing a class that uses a timer i have got a class that has a private member that has for type systemwindowsformstimer there is also a private method that is being called every time my timer ticksis it worth testing the method since it is privatehow can i test it i know i can have my test class inheriting the class i want to testshould i be mocking my timer because if i have to test a class that uses an internal timer my tests may take a lot of time to complete righteditactually the method has a dependency on timing heres the code private void alerttickobject sender eventargs e if getremainingtimeseconds 0 thisplayexecutename warningstateending null alerttimerstop else var warning warningsfirstx x getremainingtime if warningtotalseconds 0 thisplayexecutename warningstaterunning warning as you can see if the timer is running it calls thisplayexecute with different parameters from when it is ending when the remaining time equals 0 would that be a problem of design,['c#'] +318211,how should resources in a compiled jar be accessed first of all i have read through many so questions regarding this topic and i have tried the things suggested in them here is my situation i am writing a java app using the processing framework and i am in the final stages where i need to begin thinking about packaging the app a jar file that is executable from the command line is what i am attempting to build using the export feature in eclipse the structure of my project looks like this src multiple packageslibs jar files and nativesdata fonts and imagesconfig json fileswhen i export the jar file and uzip the jar to inspect it is contents i find that the contents of these dirs have been dumped in the top level of the jar which looks like thisjar packages jar files fonts json filesso when i attempt to load a config file with something like bufferedreader reader new bufferedreader new filereader path everything works just file when i run the app in eclipse but the jar file throws a filenotfoundexceptionmany of the questions that i have seen on so regarding problems like these recommend using using classgetclassgetresource or classgetresourceasstream i have tried both of these using relative paths and just the file name as in classgetresource configjson classgetresources cfgconfigjson classgetresourceasstream configjson all of these methods return null when run from either eclipse or the jar using java jar myjarfilejari am also open to using an ant file in fact i am now using the ant file generated by the export feature to build the jar if there is something i can add to that to add the directories into the jar that would be great too,['java'] +318230,how to use printwriter and file classes in java i am trying to understand printwriter for a small program i am making and i cant seem to get java to make the file and then write on it when i execute the program below it gives me a filenotfoundexeption error on line 9 it also fails to make the file in the directory that i specified i am new to this so please try and keep the answers simple i am using eclipseimport javaioprintwriterimport javaiofilepublic class testing public static void mainstring args file file new file cusersmedesktopdirectoryfiletxt printwriter printwriter new printwriter filetxt printwriterprintln hello printwriterclose,['java'] +318232,how to mount a sinatra application inside another sinatra app i am trying to write a sinatra application that groups components together sort of like controllers so for the blog related things i want an app called blog mounted at blog all of the routes contained in the blog app would be relative to its mounted path so i could simply define an index route without having to specify the mount path in the routei originally handled this by using a configru file and maping the routes to the different apps the problem with this that i ran into was that i was using various sinatra gemsextensionshelpers that needed to be included in all of the apps so there was a lot of duplicate codehow can i mount one sinatra app inside of another so that the routes defined in the app are relative to where the app is mounted if this is not possible outofthebox can you show a code sample of how this could be doneheres a simplified example of what it might look likeclass app mount blog at blog mount foo at barendclass blog get do index action endendclass foo get do index action endend,['ruby'] +318233,is this a valid use case for javascript closure i have looked through all the other excellent answers on so especially this how do javascript closures work but i wanted your feedback on my understanding of the concepti understand that one use case is to hide the implementation of private methods from public accessthe other one that i think of is having it as a factory generatorscriptfunction carfactory make var m make return manufacture function model consoleloga m model has been created toyotafactory carfactorytoyotahondafactory carfactoryhondatoyotafactorymanufacturecorollatoyotafactorymanufacturecorollahondafactorymanufacturecivicscriptthis outputsa toyota corolla has been createa toyota corolla has been createda honda civic has been created so do you think its a valid use case for closures ie creating multiple factories using the same code base or can i achieve the same thing using something much betterplease note that the question is less about the technical implementation of closures and more about valid use cases in application design developmentthanks,['javascript'] +318235,getting previous value of the combobox i want my application to grab the value of a combobox and then to set the one chosen by the user or to somehow get the previously selected value the thing is that within my form there are four lists and a combobox which contains all the values from the lists and i want to repopulate the value of the combobox back to the list it was taken from and then remove the newly selected item from othersame list,['c#'] +318239,java generics wildcard extends number vs what is the difference between these 2 functionsstatic void gprintlist extends number l for number and l systemoutprintlnn static t extends number void gprintalistt l for number and l systemoutprintlnn i see the same output,['java'] +318240,why does not this code close jdbc connections java 7 autocloseable unexpected behavior using java 7u5 with the trywithresources construct the following code appears to leak jdbc connectionstry connection connection preparedstatement stmt stmtsetstring return stmtexecuteupdate 0the next piece of code works as expected and intendedint ret 0try connection connection preparedstatement stmt stmtsetstring ret stmtexecuteupdatereturn ret 0it seems that in the first case the connectionclose method is not being invokedi am using the latest mysql connector this is unexpected behavior correcttestthe following test will not print closedpublic class test implements autocloseable public static void mainstring args throws exception systemoutprintlndotestprivate static boolean dotest throws exception try test test new test return testexecute 0 private int execute return 1overridepublic void close throws exception systemoutprintlnclosedstrangely if execute is modified to return 0 then closed will be printedjavap p c testclass output compiled from testjavapublic class test implements javalangautocloseable public test code 0 aload 0 1 invokespecial 10 method javalangobjectinitv 4 return public static void mainjavalangstring throws javalangexception code 0 getstatic 21 field javalangsystemoutljavaioprintstream 3 invokestatic 27 method dotestz 6 invokevirtual 31 method javaioprintstreamprintlnzv 9 return private static boolean dotest throws javalangexception code 0 aconst null 1 astore 0 2 aconst null 3 astore 1 4 new 1 class test 7 dup 8 invokespecial 39 method initv 11 astore 2 12 aload 2 13 invokespecial 40 method executei 16 ifle 21 19 iconst 1 20 ireturn 21 iconst 0 22 aload 2 23 ifnull 30 26 aload 2 27 invokevirtual 44 method closev 30 ireturn 31 astore 0 32 aload 2 33 ifnull 40 36 aload 2 37 invokevirtual 44 method closev 40 aload 0 41 athrow 42 astore 1 43 aload 0 44 ifnonnull 52 47 aload 1 48 astore 0 49 goto 62 52 aload 0 53 aload 1 54 if acmpeq 62 57 aload 0 58 aload 1 59 invokevirtual 47 method javalangthrowableaddsuppressedljavalangthrowablev 62 aload 0 63 athrow exception table from to target type 12 22 31 any 30 31 31 any 4 42 42 any private int execute code 0 iconst 1 1 ireturn public void close throws javalangexception code 0 getstatic 21 field javalangsystemoutljavaioprintstream 3 ldc 55 string closed 5 invokevirtual 57 method javaioprintstreamprintlnljavalangstringv 8 return,['java'] +318256,best way to load a obj file on ios since opengl does not have any function like glloadobjfilemymodelobj whats the best tutorial to load a 3d model file like obj in a ios appi have tried the wavefront loader but it does not seem to be working,['ios'] +318275,why my android sdk source is not complete recently i found my android sdk source is not complete i have downloaded the android sdk api 16 only from sdk manager when i want to generate the javadoc from source it warns me that some classes are not found i have read the website below but i get confused whether the higher level api contains the lower level apis is it enough to install the highest api only or do some of the android sdk source depend on the jdk source thanks a lotandroid api leve helpa piece of javadoc warnings javalangstringjava31 warning package libcoreutil not existimport libcoreutilemptyarray,"['java', 'android']" +318276,java setfullscreenwindow keep on top i am writing an application that is intended to be run on a dual monitor setup with a thisplay jframe going fullscreen on one monitor and a control jframe on the other monitor sending instructions to the thisplay i have tried two separate methods of setting the thisplay fullscreen the success of each seems to depend on the osthisplaysetundecoratedtruethisplaysetextendedstatejframemaximized bothworks in windows but the jframe gets hidden under the dockpanels in os x and linuxmy other method utilizinggraphicsdevicesetfullscreenwindowthisplayworks in all three oses that i tried but in windows focusing the control window on the other monitor makes the thisplay window hide and callingthisplaysetalwaysontoptruedoes not fix the problem i am kind of partial to the graphicsdevice method because i do not have to deal with the issues in os x or linux and i am hoping that the windows problem is a simple fix is it,['java'] +318318,increment vs 1 i have a picture model that contains a variable for a view count integerthe view count is incremented by 1 every time someone views the picture objectin getting this done what is the difference between pictureview count 1 picturesaveand pictureincrementview count by 1also if i use increment is save necessary,"['ruby-on-rails', 'ruby']" +318326,font size for fontface alternative i am using fontface that has to be given a large fontsize for example the fontsize of the title is 54px which is normally so big but in this font it appears mediumso the problem is while the page loads the alternative font appears very big and breaks the whole layoutis there a way i can specify a fontsize for alternative font,"['html', 'css']" +318331,android without proxy not working i need the condition of setting no proxy in my application for that i used the following codeurl url nulltry url new urluritourltostring catch malformedurlexception e3 e3printstacktracetry client httpurlconnection urlopenconnectionjavanetproxyno proxy properties systemproperties systemgetproperties systempropertiessetpropertyhttpnonproxyhostsserverip systempropertiessetproperty proxyset false systempropertiessetpropertyhttpproxyhost systempropertiessetpropertyhttpproxyport urlconnection conn urlopenconnectionproxyno proxy connconnect catch ioexception e3 e3printstacktracebut i got network unreachable exceptionany help,['android'] +318342,significance of question mark in java cron source wikipedia question mark is used instead of for leaving either dayofmonth or dayofweek blankthe above statement is not making much sense to meso if i write some cron as 0 0 0 then does it mean first of every month or it means it will execute dailyit is a bit confusing as java crons start with seconds while other crons start with minute,['java'] +318356,use jelly beans simple secure pairing bluetooth to pair with nfc as of io2012 and jellybean doc there is now a way to pair bluetooth devices via nfc that sounds really nice but i cannot find any documentation about it i am especially interested to know if that works with spp modules that do not support sdp can i simply write some nfc tag with the pininfo and the device gets paired would help a lot as a lot of users that have problems with the pinpairing process,['android'] +318357,mysql left join how do i select null values this is a follow up question to my last question about table joins in mysqli need to be able to select the null values from the left joined tableheres my jointable1id table1name table2id table2surname 1 john 1 doe 2 michael 2 anderson 3 anna null null 4 sue null nulli would want to select where table2surname null but a query like this doesnt workselect table1table2from table1left join table2 on table1idtable2idwhere table2surnamenulli can somewhat understand the logic behind it not giving me any results but there must be a way to grab them resultsappreciate any help,"['mysql', 'sql']" +318396,how can i remove the margins around text in a wpf label i am trying to make a little virtual keyboard out of labels the following is my keyboard in xaml but with more than just 3 keysstackpanel orientationvertical stackpanel orientationhorizontal horizontalalignmentcenter border borderthickness1 borderbrushdarkgray label contenta fontsize12 mousedownkeybutton click border border borderthickness1 borderbrushdarkgray label contentb fontsize12 mousedownkeybutton click border stackpanel stackpanel orientationhorizontal horizontalalignmentcenter border borderthickness1 borderbrushdarkgray label contentc fontsize12 mousedownkeybutton click border stackpanelstackpanelthe problem with this is that there is too much space surrounding the text in the labels causing the keyboard to be much bigger than it needs to be if i manually set the height and width of the labels that will 1 not account for differences in fonts and 2 will cut of part of the letter rather than the top and left margins is there any other way to shrink these margins to be just about the same size as the text itself,"['c#', '.net']" +318404,importerror no module named mock so i am trying to use unittestmock to mock some of my methods in my unit tests i dofrom unittestmock import magicmockf opendatastaticmock ffprobe responsesubprocesscheck output magicmockreturn valuefreadfclosebut i am gettingimporterror no module named mocki triedpip install mockit is still not working,['python'] +318430,modifying a text file in a zip archive in java my use case requires me to open a txt file say abctxt which is inside a zip archive which contains keyvalue pairs in the formkey1value1key2value2 and so on where each keyvalue pair is in a new linei have to change one value corresponding to a certain key and put the text file back in a new copy of the archive how do i do this in javamy attempt so far zipfile zipfile new zipfiletestzip final zipoutputstream zos new zipoutputstreamnew fileoutputstreamoutzip forenumeration e zipfileentries ehasmoreelements zipentry entryin zipentry enextelement ifentryingetnameequalsignorecaseabctxt zosputnextentryentryin inputstream is zipfilegetinputstreamentryin byte buf new byte1024 int len whilelen isreadbuf 0 zoswritebuf 0 len else i am not sure what to do here tried a few things and the file gets corrupt zoscloseentry zosclose,['java'] +318439,user based filteringrecommendation system i know this is not a coding specific problem but this is the most suitable place for asking such questionsso please bear with mesuppose i have a dictionary like given belowlisting ten liked items of each personlikes rajatmusicxmenprogramminghindienglishhimeshlil wayneraptravellingcoding stevetravellingpophanging outfriendsfacebooktvskatingreligionenglishchocolate tobyprogrammingpoprapgardensflowersbirthdaytvsummeryoutubeeminem raviskatingoperasonyappleiphonemusicwintermango shakeheartmicrosoft katymusicpicsguitarglamourparisfunlip stickscute guysrapwinter paulofficewomendresscasualsaction moviesfunpublic speakingmicrosoftdeveloper sheilaheartbeachsummerlaptopsyoutubemovieshindienglishcute guyslove saifwomenbeachlaptopsmovieshimeshworldearthrapfuneminem markpilgrimageprogramminghouseworldbookscountry musicbobtom hanksbeautytigers stuartrapsmart girlsmusicwrestlingbrock lesnarcountry musicpublic speakingwomencodingiphone groverskatingmountaineeringracingathleticssportsadidasnikewomenapplepop anitaheartsunidhihindilovelove songscookingadidasbeachtravellingflowers kellytravellingcomedytvfacebookyoutubecookinghorrormoviesdublinanimals dinowomengamesxboxxmenassassins creedpoprapoperaneed for speedjeans priyaheartmountaineeringsky divingsonyapplepopperfumesluxuryeminemlil wayne brendacute guysxboxshowerbeachsummerenglishfrenchcountry musicofficebirdshow can i determine persons who have similar likesor maybe who two persons resemble the mostalso it will be helpful if you can point me to the appropriate example or tutorial for user based or item based filtering,['python'] +318460,support url for app submission in appstore does support url is necessary for the app submission in the appstore i am registered as an individual developer and i do not have a web page for support url what can i do,['ios'] +318509,what is the difference between the states selected checked and activated in android i would like to know what differs those states i did not find any webpage clarifying this,['android'] +318510,what does the new keyword in net actually do i know that the new keyword is calling the class constructor but at which stage do we allocate memory for the classin my understanding it should correspond to the gchandleallocobject method but i am unable to find the connection,"['c#', '.net']" +318534,inheritance in java collection interfaces there are some inheritance relationship in java collection interfaces for example collectiont interface will extend iterableti checked the source code in jdk some methods defined in base class get repeated in sub classes several times for example interablet interface defined a method iteratore iterator but in interface collectione and listt also contain the same method in my understanding since inheritance is used to reduce duplication why should we define the same method in subclasses,['java'] +318539,the best battery saving method for location updates i am trying to write an adroid application that should run in background and notify the user when he will be close to the place given in the database should i do it by requestlocationupdates in the extended intentservice class what is the best way to make it as least battery draining as possible,"['java', 'android']" +318554,web audio api resume from pause i often read that it is not possible to pauseresume audio files with the web audio apibut now i saw a example where they actually made it possible to pause and resume it i tried to figure out what how they did it i thought maybe sourcelooping falseis the key but it was notfor now my audio is always replaying from the startthis is my current codevar context new windowaudiocontext windowwebkitaudiocontextfunction audioplayer thissource contextcreatebuffersource thisanalyser contextcreateanalyser thisstopped trueaudioplayerprototypesetbuffer functionbuffer thissourcebuffer buffer thissourcelooping falseaudioplayerprototypeplay function thissourceconnectthisanalyser thisanalyserconnectcontextdestination thissourcenoteon0 thisstopped falseaudioplayerprototypestop function thisanalyserthisconnect thissourcethisconnect thisstopped truedoes anybody know what to do to get it work,"['javascript', 'html']" +318558,valgrind reports unitialized values on empty c program i have this c program compiled with either gcc testc or clang testcint main void return 0valgrind aout gives me this9232 memcheck a memory error detector9232 copyright c 20022011 and gnu gpld by julian seward et al9232 using valgrind370 and libvex rerun with h for copyright info9232 command aout9232 9232 conditional jump or move depends on uninitialised values9232 at 0x4017876 index in usrlibld216so9232 by 0x4007902 expand dynamic string token in usrlibld216so9232 by 0x4008204 dl map object in usrlibld216so9232 by 0x400180d map doit in usrlibld216so9232 by 0x400e785 dl catch error in usrlibld216so9232 by 0x40010db do preload in usrlibld216so9232 by 0x4004546 dl main in usrlibld216so9232 by 0x4014b5d dl sysdep start in usrlibld216so9232 by 0x4004dfd dl start in usrlibld216so9232 by 0x4001627 in usrlibld216so9232 9232 conditional jump or move depends on uninitialised values9232 at 0x401787b index in usrlibld216so9232 by 0x4007902 expand dynamic string token in usrlibld216so9232 by 0x4008204 dl map object in usrlibld216so9232 by 0x400180d map doit in usrlibld216so9232 by 0x400e785 dl catch error in usrlibld216so9232 by 0x40010db do preload in usrlibld216so9232 by 0x4004546 dl main in usrlibld216so9232 by 0x4014b5d dl sysdep start in usrlibld216so9232 by 0x4004dfd dl start in usrlibld216so9232 by 0x4001627 in usrlibld216so9232 9232 9232 heap summary9232 in use at exit 0 bytes in 0 blocks9232 total heap usage 0 allocs 0 frees 0 bytes allocated9232 9232 all heap blocks were freed no leaks are possible9232 9232 for counts of detected and suppressed errors rerun with v9232 use trackoriginsyes to see where uninitialised values come from9232 error summary 2 errors from 2 contexts suppressed 0 from 0gcc version 471 and clang version 31 what is up with this is there something wrong with my memory there is some time since i last used valgrind but this i think is not normal behaviour yelpsolutionit is possible from what i learned from shawn to suppress these linker errors using a valgrind supp file what i did was running valgrind on my program using the gensuppressionsall optionvalgrind gensuppressionsall aout then i extract the new chunks enclosed in brackets and put them directly into a file mysupp linker memcheckcond funindex funexpand dynamic string token fun dl map object funmap doit fun dl catch error fundo preload fundl main fun dl sysdep start fun dl start objusrlibld216so now i can run valgrind with the suppressions option to point to my new file and the messages will be suppressedvalgrind suppressionshomefoomysupp aout,['c'] +318563,ajax file uploadform submit without jquery or iframes is it possible to do an ajax form submit without jquery or iframes so just pure javascript i am currently sending to a struts fileuploadaction that works would the actions code still work with the asynchronous submit or are there additions required to pick up the async form submiti am using struts 1x and current my form ishtmlform actionfileuploadaction methodpost enctypemultipartformdata form elements htmlfile propertythefile other elementshtmlformcan this form be submitted and thus the file uploaded with ajax,['javascript'] +318578,when to catch runtimeexceptions in code while programming in java is there any time that i as the programmer should be considering to catch runtimeexceptions,['java'] +318631,how can i supply a list to a sql parameter i have a sql statement like the followingconst string sql update platypusset duckbillid newduckbillidwhere platypusid in listofintsocmdparametersaddlistofints whatnowhow can i provide the comma separated list of ints which could be any reasonable number of valuesby reasonable in this case i mean between one and a couple dozen,"['c#', 'sql']" +318635,detecting out of memory errors i would like to provide my system with a way of detecting whether out of memory exception has occurred or not the aim for this exercise is to expose this flag through jmx and act correspondingly eg by configuring a relevant alert on the monitoring system as otherwise these errors sit unnoticed for daysnaive approach for this would be to set an uncaught exception handler for every thread and check whether the raised exception is instance of outofmemoryerror and set a relevant flag however this approach is not realistic for the following reasonsthe exception can occur anywhere including 3rd party libraries there is nothing i can do to prevent them catching throwable and keeping it for themselveslibraries can spawn their own threads and i have no way of enforcing uncaught exception handlers for these threadsone of possible scenarios i see is bytecode manipulation eg attaching some sort of aspect on top of outofmemoryerror however i am not sure if that is right approach or whether this is doable in generalwe have xxheapdumponoutofmemoryerror enabled but i do not see this as a solution for this problem as it was designed for something else and it provides no java callback when this happenshas anyone done this how would you solve it or suggest solving it any ideas are welcome,['java'] +318684,haml parameter with dash how can i convert this line body dataspyabcdto haml syntaxthis one returns me an error bodydataspy abcd,['html'] +318688,run show slave status with php pdo i am trying to get the slave status of my mysql server using phps pdo implementation running fetchall returns an empty array db ip name username and password are fake here i can connectdb new pdomysqlhost19216800dbnameproduction username passwordresult dbqueryshow slave statusresultexecuteif result false slave resultfetchallpdofetch associ have also tried removing the execute call but it is the same result is there something completely obvious that i am missing here i have looked up and down the pdoquery documentation and it is not helping much,"['php', 'mysql']" +318696,sort backbone collection based on model attributes i have a backbone collection which is rendered in a table i would like to make the table sortable based on certain attributes the collection has like task statustask group i have being reading the backbone documentation about collectioncomparatornd collectionsorthow can i get this done,['javascript'] +318708,python facebook api need a working example ok so i have googled around i have found threads here on stackoverflow and i have checked the official facebook wiki and and what noti now hope that one of you guys sits on a facebook api sample code for pythonthis is what i have got so far and all i get is invalid signature via pyfacebook which appears to be a dead projectfrom facebook import facebookapi key 123456789 secret proper secret keyotk x you get this from genphpv10api key123456789 long term key nonefb facebookapi key secretdef generate session from onetime codefb code fbauth token code return fbauthgetsessionif not long term key long term key generate session from onetime codefb otksession key print replace none with this in the py file for long term key print long term keyfbsession key long term keyfbuid 01 your useridfbsignature api key this does not work at all md5 of whatfbvalidate signaturefb does not work either prob need to pass md5 handleprint fbfriendsget generates invalid signatureall i want is to retrieve my friends list for nowif there is a better api point me in the right direction but facebook has officially declared their own python sdk dead and pyfacebook is almost working for me but not quiteso please help,['python'] +318710,listagg in oracle to return thistinct values i am trying to use the listagg function in oracle i would like to get only the thistinct values for that column is there a way in which i can get only the thistinct values without creating a function or a procedure col1 col2 created by 1 2 smith 1 2 john 1 3 ajay 1 4 ram 1 5 jack i need to select col1 and the listagg of col2 column 3 is not considered when i do that i get something like this as the result of listagg 22345 i need to remove the duplicate 2 here i need only the thistinct values of col2 against col1,['sql'] +318732,googles soa architecture aggregating content for googles web user interface when logged into to google the google homepage links to multiple other services eg gmail play driveq1 is there a soa pattern that describes the way that they loosely couple the uis for each service but at the same time also providing a standard menu bar standard look and feel and single sign on across their applicationsq2 is there any documentation available that describes their architecture for linking the ui contentediti have taken a look with firebug and it seems like there is a two way relationship between the menubar and the application the menubar has a link to each application but each application also has the menu bar included i can relate this to the eclipse ui where an application can contribute to the application menu but each menu lives in the context of the eclipse application which aggregates all the separate ui pluginsso how does google do this in their ui it looks like there is some javascript wizardry going on with the menu bar being injected into each application,['javascript'] +318734,wrong results when appending vector to itself using copy and back inserter inspired by this question asking how to append a vector to itself my first thought was the following and yes i realize insert is a better option nowinclude algorithminclude iostreaminclude iteratorinclude vectorint main stdvectorint vec 1 2 3 stdcopy stdbegin vec stdend vec stdback inserter vec for const auto v vec stdcout v however this prints1 2 3 1 3the is a different number every time the program is run the fact that it is only the 2 being replaced is peculiar and if there actually is an explanation for that i would be interested to hear it continuing if i append to a different vector a copy of the original it outputs correctly it also outputs correctly if i add the following line before the copy onevecreserve 2 vecsizei was under the impression stdback inserter was a safe way to add elements onto the end of a container despite not reserving memory beforehand if my understanding is correct whats wrong with the copying linei assume it is nothing to do with the compiler but i am using gcc 471,['c++'] +318751,issue converting python pandas dataframe to r dataframe for use with rpy2 i am having trouble converting a pandas dataframe in python to an r object for future use in r using rpy2the new pandas release 080 released a few weeks ago has a function to convert pandas dataframes to r dataframes the problem is in converting the first column of my pandas dataframe which consists of python datetime objects successively in a time series the conversion into an r dataframe returns an strvector of the dates and times rather than a vector of r datetimetype objects which i believe are called posixct objectsi know the command to convert a string of the type returned to a posixct using the command asposixctymmdd hhmmss unfortunately i have not been able to figure out the way to convert all these strings in the strvector to posixct using python and rpy2 the dates need to be in the posixct format to be used with the ttr library in r below is the relevant python codeimport pandasfrom pandas import import pandasrpycommon as comimport rpy2robjects as robjectsr robjectsrrlibraryttr library contains the function adx to be used laterdataframe read csvfile name parse dates 0 names datecol1col2col3 command makes 1st column into datetimedatetime objectr dataframe comconvert to r dataframedataframeadx radx creating a name for an r function in pythonadx adxr dataframe will not work because the dates in r dataframe are in a strvectorfurther i do not believe that the strvector can be iterated through to convert each object to a posixct object individually due to the definition of a strvector maybe there is a way to cast a strvector to a generic oneany helpinsight into this matter is greatly appreciated i am a novice programmer and have been working on this for a couple hours now to no availthank you,['python'] +318757,whats the difference between thiselhtml and thiselhtml whats the difference betweenthiselhtmland thiselhtmlreading a few backbone examples and some do it one way and other another way,"['javascript', 'jquery']" +318764,net 4 equivalent of taskwhenall in net 4 is there any functional equivalent to net 45s systemthreadingtaskstaskwhenallthe goal is to wrap up multiple async tasks into a single one that is completed when all of its constituent tasks are done,['c#'] +318770,boxing and unboxing is also casting when we convert the data types between primitive data types it is called as data type castingbut when convert between valuetype and referencetype we call it as boxing and unboxing can boxing and unboxing also be called casting,['c#'] +318800,generic methods and type inferencing in java given the following notveryuseful codepackage comsomethingimport javautilarraylistimport javautilcollectionnot a generic classpublic class test public t void plaint param1 t param2 public t void fancyt param1 collectiont param2 public void testmethod no error fancy new arrayliststring compiler error here fancy new arraylistinteger no error plain new arraylistinteger please correct my understanding if it is wrongthe 2nd call to fancy is a compiler error because java cannot infer any common type between the two arguments cannot infer object since the second parameter must be a collectionthe call to plain is not a compiler error because java infers the common type of object between the two argumentsi recently came across code that had a method signature similar to plainmy question is thisis plains signature useful for anythingperhaps the person who wrote that code thought that plains signature would enforce that both parameters have the same type at compile time which is obviously not the caseis there any difference from or benefit to writing a method with a signature like plain rather than just defining both parameters to be objects,['java'] +318817,xframeoptions allowfrom a specific site allows from all i am using a rails application to serve a page from abccom in it i set the response headers in my application controller for every request through before filter so that it can be accessed through an iframe only from a specific site xyzcom through the following codedef set x frame options responseheadersxframeoptions allowfrom endthe problem is not only am i able to access the page from abccom on xyz but also on any other website i want to limit the access to only xyzcom when i examine the response headers in chrome console i can see the xframeoptions is being passed on correctly this is happening across all browsers am i missing something,['ruby-on-rails'] +318900,how to change background color of cell in table using java script i need to change background color of single cell in table using java script during document i need style of all cell should be same so used style sheet to add this but on button click i need to change color of first cellfollowing is the sample codehtml langen head script typetextjavascript function btnclick var x documentgetelementbyidmytablecells x0innerhtml i want to change my cell color x0bgcolor yellow script head style div textalign left textindent 0px padding 0px 0px 0px 0px margin 0px 0px 0px 0px tdtd borderwidth 1px backgroundcolor 99cc00 textaligncenter style body div table id mytable width100 border1 cellpadding2 cellspacing2 stylebackgroundcolor f tr valigntop td class tdbr td td class tdbr td tr tr valigntop td class tdbr td td class tdbr td tr table div input typebutton valueclick onclick btnclick bodyhtml,"['javascript', 'html']" +318911,android network radio off before action shutdown eventevents order changed in ics i was sending logout to my server when user did a power off on the devicethe order of events in 23 and 403 are as followsso now log out is faileddevice samsung galaxy s2android 231receive action shutdown 2 send logout eventsleep for 5 secslog out sent successfully3data network radio off event4device power offandroid 4031 data network radio off event2receive action shutdown 3 send logout eventlog out fail as network is downany way around to get action shutdown before data network radio off,['android'] +318960,what is alternative performance tuning tool of yourkitjprofiler well i have to say that yourkitjprofiler is a best java performance tuning tool but it need licence so it do not fit me at this moment could you guys have alternative performance tuning tool if it is free that would be deeply appreciatedit need having some features like yourkit that can capturizemonitor all methods which are invoked in a certain period time and reports all details with calling structurei tried oracle jrockit mission control to me it seems having some lacks especially you must add these methods that need to be monitored its not a good idea since many times i do not even know which methods are being called and who is the caller so it didnot give me comprehensive view to tuning performance issue,['java'] +318999,is logback mature enough to replace log4j i have read similar questions on so like this and this but they are about four years oldalso i have read this logback page which has some really good info on why to choose logback over log4ji am looking to implement a logging framework for a project with the following technology stack springhibernatemaventomcatresti have already decided to use slf4j as the facade so this question is on whether to use slf4j log4j or slf4j logback i know that logback natively uses slf4jwhat i am looking for is following has anyone had an experience with logback that would prove it to be not as mature or efficient as log4jhow does it fair as compared to log4j in a multithreaded environmentability to replace tomcatdefault jul logging with logbacklog4j loggingability to consolidate logging configuration into a common file for a maven multimodule projectlogback claims it is 10 times faster than log4j has anyone validated that claim as part of my research i do plan to run some tests to measure performance and will post back my resultsedit i have read at many places one of the answer below states this as well that log4j is deaddeprecated contrary to that log4j just released an alpha version of its 20 release so i do not buy that argument,['java'] +319021,how to know callee is answered the call what is the phone state when he lift the call i am trying to know how to alert when the callee lifts the call i have used phonestatelistener along with broadcastreceivergenerally it has three states call state idle call state offhook call state ringingcall state offhook state was calling when call is connecting no state of the above three states was called after callee answered callhere is my broadcastreceiverpublic class phonestatebroadcastreceiver extends broadcastreceiver override public void onreceivecontext context intent intent telephonymanager telephonymanager telephonymanager contextgetsystemservicecontexttelephony service telephonymanagerlistennew customphonestatelistenercontext phonestatelistenerlisten call state public class customphonestatelistener extends phonestatelistener context context context to make toast if required activitymanager activitymanager public customphonestatelistenercontext context super thiscontext context override public void oncallstatechangedint state string incomingnumber superoncallstatechangedstate incomingnumber logvphonestatebroadcastreceiver oncallstatechanged statestate switch state case telephonymanagercall state idle toastmaketextcontext call state idle toastlength longshow break case telephonymanagercall state offhook toastmaketextcontext call state offhook toastlength longshow break case telephonymanagercall state ringing toastmaketextcontext call state ringing toastlength longshow break default break i have seen some applications there are recording a voice when call was accepted i want to know the state of accepting callis there any other state or listener to know when the callee is answered the call,['android'] +319162,uninitialized constant error when including a module i am trying to reference an association extension but it errors withnameerror uninitialized constant userlisterextension appmodelsuserrb2in classuserhere is my implementationappmodelsuserrbclass user activerecordbase include listerextension has and belongs to many roles uniq true extend listerliblisterrbmodule listerextension def lister selfmapto sjoin endendi am using rails v313,"['ruby-on-rails', 'ruby']" +319182,what can cause createfile calls on a serial port to be extremely slow i have got a qt app qt 481 that is doing some windows serial port tasks i am finding that occasionally the createfilea call that i do to open the serial port is taking up to 30 seconds to complete obviously i am doing something to trigger this odd behavior and i want to know what it is i might be doing to cause thism porthand createfilea portdevicec str generic read generic write 0 must be opened with exclusiveaccess null default security attributes open existing must use open existing file flag overlapped overlapped io null htemplate must be null for comm devicesm porthand is a handle and portdevice is an stdstring and contains com5this call is triggered by a button push in the main thread of my app at the time it happens the app has at most one other thread but those threads if any are idle the only major thing going on in the system is a vm running linux but the system is a quadcore and 3 of the cores are as near to idle as you see on a windows box with only one doing anything with the vmthe serial ports are on an 8 port usb serial box could that be relatedis this related to the overlapped io in some wayin response to commentsport is not open by another app port was previously open by a previous invocation of this app which was properly closed and the port closed with closehandlei have not been able to determine any correlations between it taking 30 seconds and not sometimes i start the app up click the button and were off to the races sometimes it takes up to 30 seconds the vm is intercepting some other usb devices on the same serial boxother than the serial box with the vm polling 4 ports looking for devices the usb bus is unloaded i have not seen the behavior in other apps i will try switching to a builtin port com1 on the motherboard to see if that has any effecta thought just occurred to me can the form of the port addressing have anything to do with it other similar apps i work on use the qestserialport library which opens ports using the com notation is there some way that the notation used could affect the timingthe usb serial device says vscom on it and normally it opens up right away 10 milliseconds for the createfile call it is just an occasional issue where things get stuffed up and i have got other programs that never seem to exhibit this behaviorthe device i am talking to is a medical monitor using the ie 11073 protocol anyway i have the connection to the device working just fine it is only the serial port open that is problematic could the state of the serial control lines at open time have something to do with this the device at the other end is polling it is ports looking for various things to talk to so i have no idea what the serial lines look like at the exact moment things go wrong,['c++'] +319184,can you modify an existing mysql trigger after it has been created in mysql i can create a trigger and then show information about it like thismysql show triggers like footriggerthis command gives output that looks an awful lot like a select statement with a row showing the matching trigger is it possible to update a column on the row it shows mefor example one column is named statement and it defines what happens when the trigger is activated is it possible to change the statement field for footrigger so the trigger does something different or do i need to drop and recreate the trigger,['mysql'] +319197,get window handle intptr from selenium webdrivers current window guid i am trying to capture a screenshot of whole browser screen eg with any toolbars panels and so on not only an entire page so i am got this codeusing firefoxdriver driver new firefoxdriver drivernavigategotourlurl screencapture sc new screencapture how can i find natural intptr handle of window here using guidlike identifier returning by drivercurrentwindowhandle image img sccapturewindow memorystream ms new memorystream imgsavems imageformatjpeg return new filestreamresultms imagejpeg,"['c#', '.net']" +319208,is there an established pattern for sql queries which group by a range i have seen a lot of questions on so concerning how to group data by a range in a sql querythe exact scenarios vary but the general underlying problem in each is to group by a range of values rather than each thiscrete value in the group by column in other words to group by a less precise granularity than youre storing in the database tablethis crops up often in the real world when producing things like histograms calendar representations pivot tables and other bespoke reporting outputssome example data tables unrelated orderhistory staff date quantity age name 01jul2012 2 19 barry 02jul2012 5 53 nigel 08jul2012 1 29 donna 10jul2012 3 26 james 14jul2012 4 44 helen 17jul2012 2 49 wendy 28jul2012 6 62 terry now let us say we want to use the date column of the orderhistory table to group by weeks ie 7day ranges or perhaps group the staff into 10year age ranges week qtycount agegroup namecount 01jul to 07jul 7 1019 1 08jul to 14jul 8 2029 2 15jul to 21jul 2 3039 0 22jul to 28jul 6 4049 2 5059 1 6069 1 group by date and group by age on their own would not do itthe most common answers i see none of which are consistently voted correct are to use one or more of a bunch of case statements one per groupinga bunch of union queries with a different where clause per groupingas i am working with sql server pivot and unpivota twostage query using a subselect temp table or view constructis there an established generic pattern for dealing with such queries,['sql'] +319253,interrater agreement in python cohens kappa i have ratings for 60 cases by 3 raters these are in lists organized by document the first element refers to the rating of the first document the second of the second document and so onrater1 878625rater2 353322rater3 421002is there a python implementation of cohens kappa somewhere i could not find anything in numpy or scipy and nothing here on stackoverflow but maybe i missed it this is quite a common statistic so i am surprised i cannot find it for a language like python,['python'] +319282,scroll to the center of viewport i would like to center a div by clicking it so if i am clicking a div i want it to scroll to the center of the browser viewport i do not want to use anchor points like the guides and examples i have seen how can i achieve this,"['javascript', 'jquery']" +319294,how to find index of object in php array here is print r output of my arrayarray0 stdclass object itemid 560639019 name item no1 code 01 qty 5 id 2 1 stdclass object itemid 470639763471 name second item code 76347 qty 9 id 4 2 stdclass object itemid 56939399632 name item no 3 code 39963 qty 6 id 7 how can i find index of object with id 4 in order to remove it from array,['php'] +319317,cell style alignment on a range i am having a problem fromatting cells in an excel sheet for some reason my code seems to be changing the style of all cells when i just want to change the style of a few specified or a specified rangeheres some of the code that i am usingapp new microsoftofficeinteropexcelapplicationworkbook appworkbooksadd1worksheet microsoftofficeinteropexcelworksheetworkbooksheets1change all cells alignment to centerworksheetcellsstylehorizontalalignment microsoftofficeinteropexcelxlhalignxlhaligncenterbut then this line changes every cell style back to left alignmentworksheetcellsy 1 x 2stylehorizontalalignment microsoftofficeinteropexcelxlhalignxlhalignleftwhy would it change the style of multiple cells when i set it to just work on one is it not supposed to work how i want it to is there another way of doing this,['c#'] +319324,perform ui changes on main thread using thispatch async or performselectoronmainthread possible duplicategrand central thispatch gcd vs performselector need a better explanation to execute stuff on the main thread should i use thispatch async or performselectoronmainthread is there a preferred way rightor wrong andor best practiceexample i am performing some logic within the block of an nsurlconnection sendasynchronousrequesturlrequest method because i am doing stuff to the main view such as presenting a uialertview i need to show the uialertview on the main thread to do this i am using the following codensurlconnection sendasynchronousrequesturlrequest queuequeue completionhandlernsurlresponse response nsdata data nserror error code snipped out to keep this question short ifnsthread ismainthread thispatch asyncthispatch get main queue uialertview alertview uialertview alloc initwithtitleoops messagesome message delegateself cancelbuttontitleok otherbuttontitlesnil alertview show within that same ifnsthread ismainthread statement i also call some custom methods the question is should i use the thispatch async method that i am using above or is it better to use performselectoronmainthread instead for example full code belownsurlconnection sendasynchronousrequesturlrequest queuequeue completionhandlernsurlresponse response nsdata data nserror error code snipped out to keep this question short ifnsthread ismainthread thispatch asyncthispatch get main queue uialertview alertview uialertview alloc initwithtitleoops messagesome message delegateself cancelbuttontitleok otherbuttontitlesnil alertview show call custom methods in thispatch async self hideloginspinner or call them here using performselectoronmainthread self performselectoronmainthreadselectorhideloginspinner withobjectnil waituntildoneno fyi if i do not perform these actions on he main thread i see a few second delay when presenting the uialertview and i receive the following message in the debugger wait fences failed to receive reply 104003 i have learned that this is because you need to make changes to the ui on the main thread in case someone is wondering why i am doing what i am doing,"['ios', 'objective-c']" +319362,nthoftype alternative for ie8 i have rows of product divs need to add a clear div after every fourth item 4 to a row i am using jqueryproductnthoftype4n2afterdiv classcleardiv right now but that does not support ie8 and since were using jquery selectivizrs fix would not work in this casei have also tried adynamicrow function var divs productsection product forvar i 0 i divslength i4 divsslicei i4wrapalldiv classrowdiv rowafterdiv classcleardiv adynamicrowbut that grabs all of the product divs in the other productsection wrappers as well and puts them into groups of four regardless of where they are atanyone know a workaround i havnt been able to find a solutionthanks11513 update jquery 19 now supports the following css3 selectors across all browsers all the way back to ie6 nthlastchild nthoftype nthlastoftype firstoftype lastoftype onlyoftype target root and lang,"['javascript', 'jquery', 'css']" +319379,ios static library debug symbols not being in included in dsym i am working on a series of ios apps which will share a common codebase i have developed the common codebase as a static library and want it is debug symbols included in the primary apps dsym file my understanding is that this is possible but i have not gotten it working yetthe common codebase in its own project which has a static library as a target this project is dragged into the primary apps project in the primary apps targets build phases i have added the static library as a target dependency and under link binary with libraries the project builds and runs as desirednow if i generate a archive from the main project i can view that archive in finder and it contains a dsym file that can be used to symbolicate crash logs however the dsym only contains symbols for the primary app not for the static library to overconfirm this i ran the following dwarfdump pathtoappdsymand the output mostly did not contain any symbols from the static library the only exception i have found is that my primary projects appdelegate is a subclass of an object in the static library and there are entries for that super class in the dsym however none of the other classes are present in the static librarys projects targets build settings i have set the followingstrip debug symbols during copy nostrip linked product nogenerate debug symbols yessymbols hidden by default noif anyone can offer some guidance i would greatly appreciate it,['ios'] +319396,adding an attribute to a python dictionary from the standard library i was wondering if you could add an attibute to a python dictionaryclass myclass def init selfmydict initialize a regular dict selfmydictnewattribute a description of what this dictionary will hold attributeerror dict object has no attribute newattribute setattrselfmydictattributea description of what this dictionary will hold attributeerror dict object has no attribute newattributeis there anyway to quickly add my description attribute without having to copy the dict class and overloading the constructor i thought it would be simple but i guess i was wrongthanksj,['python'] +319430,reproduce the unix cat command in python i am currently reproducing the following unix commandcat commandinfo fort13 commandfort13in python with the followingwith opencommandfort13 w as outfile with openfort13 r as fort13 opencommandinfo r as com for line in comreadsplitn if linestrip print outfile line for line in fort13readsplitn if linestrip print outfile linewhich works but there has to be a better way any suggestionsedit 2016this question has started getting attention again after four years i wrote up some thoughts in a longer jupyter notebook here the crux of the issue is that my question was pertaining to the unexpected by me behavior of readlines the answer i was aiming toward could have been better asked and that question would have been better answered with readsplitlines,['python'] +319434,has anyone implemented a regex andor xml parser around stringbuilders or streams i am building a stresstesting client that hammers servers and analyzes responses using as many threads as the client can muster i am constantly finding myself throttled by garbage collection andor lack thereof and in most cases it comes down to strings that i am instantiating only to pass them off to a regex or an xml parsing routine if you decompile the regex class youll see that internally it uses stringbuilders to do nearly everything but you cannot pass it a string builder it helpfully dives down into private methods before starting to use them so extension methods are not going to solve it either youre in a similar situation if you want to get an object graph out of the parser in systemxmllinq this is not a case of pedantic overoptimizationinadvance i have looked at the regex replacements inside a stringbuilder question and others i have also profiled my app to see where the ceilings are coming from and using regexreplace now is indeed introducing significant overhead in a method chain where i am trying to hit a server with millions of requests per hour and examine xml responses for errors and embedded diagnostic codes i have already gotten rid of just about every other inefficiency that is throttling the throughput and i have even cut a lot of the regex overhead out by extending stringbuilder to do wildcard findreplace when i do not need capture groups or backreferences but it seems to me that someone would have wrapped up a custom stringbuilder or better yet stream based regex and xml parsing utility by now ok so rant over but am i going to have to do this myselfupdate i found a workaround which lowered peak memory consumption from multiple gigabytes to a few hundred megs so i am posting it below i am not adding it as an answer because a i generally hate to do that and b i still want to find out if someone takes the time to customize stringbuilder to do regexes or viceversa before i doin my case i could not use xmlreader because the stream i am ingesting contains some invalid binary content in certain elements in order to parse the xml i have to empty out those elements i was previously using a single static compiled regex instance to do the replace and this consumed memory like mad i am trying to process 300 10kb docssec the change that drastically reduced consumption wasi added the code from this stringbuilder extensions article oncodeproject for the handy indexof method i added a very crude wildcardreplace method that allows one wildcard character or per invocation i replaced the regex usage with a wildcardreplace call to empty the contents of the offending elementsthis is very unpretty and tested only as far as my own purposes required i would have made it more elegant and powerful but yagni and all that and i am in a hurry heres the code summary performs basic wildcard find and replace on a string builder observing one of two wildcard characters matches any number of characters or matches a single character operates on only one wildcard per invocation 2 or more wildcards in paramref namefind will cause an exception all characters in paramref namereplacewith are treated as literal parts of the replacement text summary param namefindparam param namereplacewithparam returnsreturnspublic static stringbuilder wildcardreplacethis stringbuilder sb string find string replacewith if findsplitnew char length 2 findsplitnew char length 2 findcontains findcontains throw new argumentexceptiononly one wildcard is supported but more than one was supplied find are we matching one character or any number bool matchonecharacter findcontains string parts matchonecharacter findsplitnew char stringsplitoptionsremoveemptyentries findsplitnew char stringsplitoptionsremoveemptyentries int startitemidx int enditemidx int newstartidx 0 int length while startitemidx sbindexofparts0 newstartidx 0 enditemidx sbindexofparts1 startitemidx parts0length 0 length enditemidx parts1length startitemidx newstartidx startitemidx replacewithlength with wildcard find parameter length should equal the length of its match if matchonecharacter length findlength break sbremovestartitemidx length sbinsertstartitemidx replacewith return sb,['c#'] +319435,how to solve calayerinvalidgeometry reason calayer position contains nan nan nan i have an error where it crash the application when it is starting upthis is the error that i got terminating app due to uncaught exception calayerinvalidgeometry reason calayer position contains nan nan nan first throw call stack0x250b022 0x2709cd6 0x24b3a48 0x24b39b9 0x217ec0d 0x2174f55 0x158f3f7 0xbc74e 0xbe512 0xbfa26 0xbe4ad 0x224ffda 0x224f956 0x224e449 0x224ab9a 0x24df970 0x247f1c1 0x2442967 0x2441d84 0x2441c9b 0x2c0a7d8 0x2c0a88a 0x1559626 0x2aed 0x2a65terminate called throwing an exceptioni tried using exception breakpoint and it does not show which part of the code has gone wrongit only stop at this point 0xbc74e movl 0 eax how can i solve it please help editi found the part which throws the exception but i cannot see what is wrong voidviewdidload super viewdidloadselfactivityview startanimatingselfmapviewlayerdelegate selfselfmapviewtouchdelegate selfselfmapviewcalloutdelegate selfnsurl mapurl nsurl urlwithstringktiledmapserviceurlagstiledmapservicelayer tiledlyr agstiledmapservicelayer tiledmapservicelayerwithurlmapurlselfmapview addmaplayertiledlyr withnametiled layer voidmapviewdidloadagsmapview mapview agsenvelope envelope agsenvelope allocinitwithxmin29757610204117 ymin400550379682464 xmax298846992302249 ymax402366028660071 spatialreferenceselfmapviewspatialreferencecall method to set extent pass in envelopeselfmapview zoomtoenvelopeenvelope animatedyesselfmapviewcalloutwidth 1950fselfmapviewcalloutaccessorybuttonhidden yesselfmapviewgps startselfmapview centeratpointselfmapviewgpscurrentpoint animatedyes selfactivityview stopanimatingselfactivityviewhidden yesthis line is causing the error selfmapviewlayerdelegate self which by default call the method mapviewdidload,"['objective-c', 'ios']" +319489,how to do a jquery callback after form submit i have a simple form with remotetrue this form is actually on an html dialog which gets closed as soon as the submit button is clickednow i need to make some changes on the main html page after the form gets submitted successfully i tried this using jquery but this doesnt ensure that the tasks get performed after some form of response of the form submissionmyformsubmitfunctionevent do the task here how do i attach a callback so that my code gets executed only after the form is successfully submitted is there anyway to add some success or complete callback to the form,"['javascript', 'jquery', 'html', 'asp.net']" +319491,angularjs how to use routeparams in generating the templateurl our application has 2level navigating we want to use angularjs routeprovider to dynamically provide templates to an ngview i was thinking of doing something along the lines of thisangularmodulemyapp configrouteprovider functionrouteprovider routeproviderwhenprimarynavsecondarynav templateurl resourcesangulartemplatesnavprimarynavheresecondarynavherehtml i just do not know how to populate the parts within the i know the primarynav and secondarynav get bound to the routeparams but how do i access routeparams here in order to dynamically serve up the template,['javascript'] +319494,what is jquery unobtrusive validation i know what the jquery validation plugin is i know the jquery unobtrusive validation library was made by microsoft and is included in the aspnet mvc framework but i cannot find a single online source that explains what it is what is the difference between the standard jquery validation library and the unobtrusive version,"['javascript', 'jquery', 'asp.net']" +319516,thisplaying svg files in android i want to create an app that will thisplay position on some floor plan navigation is implementing via wifi in certain way i have done it and so now i have a problem of thisplaying floor plan it might be in some vector format after surfing internet for some time i have decided that it must be svg filei found some solutions but it is not working for me1 library svgandroidthere is opportunity to thisplay svg files but only simple files it works fine only for file in tutorial but not for any other svg file for example some other file that youll create with inkscapeso i decided that i will parse svg file make dom from it somehow get objects and attributes and draw it via opengl es 2 apache batikat first glance very good solution but there is a problem android has some native apache libraries and when i try to do something with batik it throws noclassdeffounderror because it is searching not in batik libraries but in native libraries of course we can add source code in our project take only batik parser for svg files and edit it in some way but there is a lot of work with same success we can write our own parser3 tiny line there is no trial version but if well see description of how it works for svg files and android well see that there is only rasterization of such files and that is all is there any solution better than writing own parser did anyone come across this problem,['android'] +319523,using transparent window in both java 6 and java 7 i am developing application in java 6 160 24 which using transparent jframe to get thisappearing animation here is my codepublic static void slowthisappearwindowactionwindow source int milisslow int milisfast throws interruptedexception float level 10f slow effect 50 forint i0 i8 i levellevel005f awtutilitiessetwindowopacitysourcelevel threadsleepmilisslow fast effect 0 forint i0 i8 i levellevel005f awtutilitiessetwindowopacitysourcelevel threadsleepmilisfast awtutilitiessetwindowopacitysource01fit works fine on my machine but when i tested it on another pc with java 7 installed i have fallowing error exception in thread awteventqueue0 javaawtillegalcomponentstateexception the frame is decorated at javaawtframesetopacityunknown source at javaawtwindow1setopacityunknown source at comsunawtawtutilitiessetwindowopacityunknown source at pldesignbeadpatternmodelwindowwindowhelperslowthisappearwindowactionwindowhelperjava21 at pldesignbeadpatternformsmainformexitcontrollerwindowclosingmainformjava123 at javaawtawteventmulticasterwindowclosingunknown source at javaawtwindowprocesswindoweventunknown source at javaxswingjframeprocesswindoweventunknown source at javaawtwindowprocesseventunknown source at javaawtcomponentthispatcheventimplunknown source at javaawtcontainerthispatcheventimplunknown source at javaawtwindowthispatcheventimplunknown source at javaawtcomponentthispatcheventunknown source at javaawteventqueuethispatcheventimplunknown source at javaawteventqueueaccess0unknown source at javaawteventqueue3rununknown source at javaawteventqueue3rununknown source at javasecurityaccesscontrollerdoprivilegednative method at javasecurityprotectiondomain1dointersectionprivilegeunknown source at javasecurityprotectiondomain1dointersectionprivilegeunknown source at javaawteventqueue4rununknown source at javaawteventqueue4rununknown source at javasecurityaccesscontrollerdoprivilegednative method at javasecurityprotectiondomain1dointersectionprivilegeunknown source at javaawteventqueuethispatcheventunknown source at javaawteventthispatchthreadpumponeeventforfiltersunknown source at javaawteventthispatchthreadpumpeventsforfilterunknown source at javaawteventthispatchthreadpumpeventsforhierarchyunknown source at javaawteventthispatchthreadpumpeventsunknown source at javaawteventthispatchthreadpumpeventsunknown source at javaawteventthispatchthreadrununknown sourcei think it is because in java 7 i should use windowsetopacity instead of awtutilities methods it is possible to use transparency in java 6 app that will run on java 7,['java'] +319528,convert a completed project to a dll how can i convert a completed c project to a dll in order to use it in other projectsi have googled but lots of results say to open the class library write your code there then build solution and everything will be okbut my question is how can i convert a completed project to a dll the project can include lots of forms etc,['c#'] +319556,less css abusing the operator when nesting less uses the operator to enhance the possibilities for nestingheader color black navigation fontsize 12px class textdecoration none which causes a substitution of the with the parent selector and results in a concatentation of the actual selector right to the parent selector header navigationclass instead of the normal appending which would result in class being a decendant header navigation classnow what also is possible is the following see also hereheader color black navigation fontsize 12px someid foo textdecoration none which would result in the following someid header navigation foo try here the substition takes place and i have prepended a selector someid to my parent selectorbesides the fact that i would never code this way since this probably messes up your stylesheet in no time my questionas this functionality is not documented is it a feature or more likely a bugwhich are possible sideeffects,['css'] +319587,ruby on rails allow the user to enter a new information or click on drop down menu to select existing info new ror programmer here i am trying to build a web application that allows a user to complete a form where they enter a companies information and by clicking submit it adds the input to a databaseat the moment if the user was to create a new entry they would see a few fields for example company name there is a blank box for them to put in a new company and next to that there is a drop down menu that the user can use to see existing companies in the databasediv classfield flabel company name br ftext field company name flabel company name br fselect company name companyallmap p pcompany nameuniq prompt select a company i am looking for a way to allow the user to enter a new company or click on the drop down menu and select an existing companyat the momentif nothing is entered into textbox and no option from dropdown selected it is saved as blankif something is entered and no option is selected it is saved as blankhowever if something is entered and something is picked from the dropdown the dropdown option is savedhopefully i have not made it too confusing any help at all will be appreciatedthanks in advanceeditmy create action now looks like this def createcompany companynewparamscompanycompanycompany name paramsnew company name unless paramsnew company nameemptyrespond to do format if companysave formathtml redirect to company notice company was successfully created formatjson render json company status created location company else formathtml render action new formatjson render json companyerrors status unprocessable entity endendendand form view label company name br text field new company name flabel company name br fselect company name companyallmap p pcompany nameuniq prompt select a company the new error is nowwrong number of arguments 1 for 2extracted source label company name thanks for your help,"['ruby-on-rails', 'ruby']" +319590,storyboards and svn conflicts this is a problem we never had to deal with until storyboards were introduced whenever there was a chance of conflict in ui we just made sure that no 2 developers ever worked on the same xib file simultaneously the reason we refrained from resolving xib conflicts is that there may be problematic sideeffects xib is represented in xml format so there is not a good way to merge 2 versionsnow we are facing this issue because all of our ui elements are within the same storyboard file prevention of simultaneous work on any 2 ui elements in the project makes working in parallel very difficultany suggestions as to how to tackle this issue thanks in advance for your efforts,['ios'] +319625,javaxpersistenceentitymanager remove method does removeobject entity method of entitymanager work only on those objects got from find methodi have following code snippetpublic void deleteperson entitymanager em getentitymanager person p new personx y 200 emremovepbut it is not removing the particular entry from databasewhen i tried something like belowpublic void deleteperson entitymanager em getentitymanager person p emfindpersonclass 200 emremovepit is working fine,['java'] +319633,webdriver wait for one of a multiple elements to appear is there a way to get a webdriverwait to wait for one of a number of elements to appear and to act accordingly based on which element appearsat the moment i do a webdriverwait within a try loop and if a timeout exception occurs i run the alternative code which waits for the other element to appear this seems clumsy is there a better way here is my clumsy codetry selfwaitforelementacontainstext s mime do stuff except timeoutexception selfwaitforelementlicontainstext that file already exists do other stuff it involves waiting an entire 10 seconds before it looks to see if the message that the file already exists on the systemthe function waitforelement just does a number of webdriverwait calls like sodef waitforelementself xpathlocator untilelementappearstrue selflogdebugwaiting for element located bynsnwhen untilelementappears is set to s xpathlocatoruntilelementappears if untilelementappears if xpathlocatorstartswithtitle webdriverwaitselfdriver 10untillambda driver selfdriverfind element by xpathxpathlocator else webdriverwaitselfdriver 10untillambda driver selfdriverfind element by xpathxpathlocatoris thisplayed else webdriverwaitselfdriver 10untillambda driver lenselfdriverfind elements by xpathxpathlocator0anybody got any suggestions to accomplish this in a more efficient way,['python'] +319665,data out of sync between a custom cursorloader and a cursoradapter backing a listview backgroundi have a custom cursorloader that works directly with sqlite database instead of using a contentprovider this loader works with a listfragment backed by a cursoradapter so far so goodto simplify things lets assume there is a delete button on the ui when user clicks this i delete a row from the db and also call oncontentchanged on my loader also on onloadfinished callback i call notifydatasetchanged on my adapter so as to refresh the uiproblemwhen the delete commands happen in rapid succession meaning the oncontentchanged is called in rapid succession bindview ends up to be working with stale data what this means is a row has been deleted but the listview is still attempting to thisplay that row this leads to cursor exceptionswhat am i doing wrongcodethis is a custom cursorloader based on this advice by ms diane hackborn an implementation of cursorloader that works directly with sqlite database cursors and does not require a contentprovider public class videosqlitecursorloader extends cursorloader this field is private in the parent class hence redefining it here forceloadcontentobserver mobserver public videosqlitecursorloadercontext context supercontext mobserver new forceloadcontentobserver public videosqlitecursorloadercontext context uri uri string projection string selection string selectionargs string sortorder supercontext uri projection selection selectionargs sortorder mobserver new forceloadcontentobserver main logic to load data in the background parent class uses a contentprovider to do this we use dbmanager instead nonjavadoc see androidsupportv4contentcursorloaderloadinbackground override public cursor loadinbackground cursor cursor appglobalsinstancegetdbmanagergetallcameras if cursor null ensure the cursor window is filled int count cursorgetcount registerobservercursor mobserver return cursor this mirrors the registercontentobserver method from the parent class we cannot use that method directly since it is not visible here hence we just copy over the implementation from the parent class and rename the method void registerobservercursor cursor contentobserver observer cursorregistercontentobservermobserver a snippet from my listfragment class that shows the loadermanager callbacks as well as a refresh method that i call whenever user addsdeletes a recordoverridepublic void onactivitycreatedbundle savedinstancestate superonactivitycreatedsavedinstancestate mlistview getlistview initialize the loader mloader getloadermanagerinitloaderloader id null thisoverridepublic loadercursor oncreateloaderint id bundle args return new videosqlitecursorloadergetactivityoverridepublic void onloadfinishedloadercursor loader cursor data madapterswapcursordata madapternotifydatasetchangedoverridepublic void onloaderresetloadercursor loader madapterswapcursornullpublic void refresh mloaderoncontentchangedmy cursoradapter is just a regular one with newview being overridden to return newly inflated row layout xml and bindview using the cursor to bind columns to views in the row layoutedit 1after digging into this a bit i think the fundamental issue here is the way the cursoradapter handles the underlying cursor i am trying to understand how that workstake the following scenario for better understandingsuppose the cursorloader has finished loading and it returns a cursor that now has 5 rowsthe adapter starts thisplaying these rows it moves the cursor to the next position and calls getviewat this point even as the list view is in the process of being rendered a row say with id 2 is deleted from the databasethis is where the issue is the cursoradapter has moved the cursor to a position which corresponds to a deleted row the bindview method still tries to access the columns for this row using this cursor which is invalid and we get exceptionsquestionis this understanding correct i am particularly interested in point 4 above where i am making the assumption that when a row gets deleted the cursor does not get refreshed unless i ask for it to beassuming this is right how do i ask my cursoradapter to thiscardabort its rendering of the listview even as it is in progress and ask it to use the fresh cursor returned through loaderoncontentchanged and adapternotifydatasetchanged insteadps question to moderators should this edit be moved to a separate questionedit 2based on suggestion from various answers it looks like there was a fundamental mistake in my understanding of how loaders work it turns out thatthe fragment or adapter should not be directly operating on the loader at allthe loader should monitor for all changes in data and should just give the adapter the new cursor in onloadfinished whenever data changesarmed with this understanding i attempted the following changes no operation on the loader whatsoever the refresh method does nothing nowalso to debug whats going on inside the loader and the contentobserver i came up with thispublic class videosqlitecursorloader extends cursorloader private static final string log tag cursorloader protected cursor mcursor public final class customforceloadcontentobserver extends contentobserver private final string log tag contentobserver public customforceloadcontentobserver supernew handler override public boolean deliverselfnotifications return true override public void onchangeboolean selfchange utilslogdebuglog tag onchange called selfchange selfchange oncontentchanged this field is private in the parent class hence redefining it here customforceloadcontentobserver mobserver public videosqlitecursorloadercontext context supercontext mobserver new customforceloadcontentobserver main logic to load data in the background parent class uses a contentprovider to do this we use dbmanager instead nonjavadoc see androidsupportv4contentcursorloaderloadinbackground override public cursor loadinbackground utilslogdebuglog tag loadinbackground called cursor cursor appglobalsinstancegetdbmanagergetallcameras mcursor appglobalsinstancegetdbmanagergetallcameras if cursor null ensure the cursor window is filled int count cursorgetcount utilslogdebuglog tag count count registerobservercursor mobserver return cursor this mirrors the registercontentobserver method from the parent class we cannot use that method directly since it is not visible here hence we just copy over the implementation from the parent class and rename the method void registerobservercursor cursor contentobserver observer cursorregistercontentobservermobserver a bunch of methods being overridden just for debugging purpose we simply include a logging statement and call through to super implementation override public void forceload utilslogdebuglog tag forceload called superforceload override protected void onforceload utilslogdebuglog tag onforceload called superonforceload override public void oncontentchanged utilslogdebuglog tag oncontentchanged called superoncontentchanged and here are snippets of my fragment and loadercallbackoverridepublic void onactivitycreatedbundle savedinstancestate superonactivitycreatedsavedinstancestate mlistview getlistview initialize the loader getloadermanagerinitloaderloader id null thisoverridepublic loadercursor oncreateloaderint id bundle args return new videosqlitecursorloadergetactivityoverridepublic void onloadfinishedloadercursor loader cursor data utilslogdebuglog tag onloadfinished madapterswapcursordataoverridepublic void onloaderresetloadercursor loader madapterswapcursornullpublic void refresh utilslogdebuglog tag cameraslistfragmentrefresh called mloaderoncontentchangednow whenever there is a change in the db row addeddeleted the onchange method of the contentobserver should be called correct i do not see this happening my listview never shows any change the only time i see any change is if i explicitly call oncontentchanged on the loaderwhats going wrong hereedit 3ok so i rewrote my loader to extend directly from asynctaskloader i still do not see my db changes being refreshed nor the oncontentchanged method of my loader being called when i insertdelete a row in the db just to clarify a few thingsi used the code for cursorloader and just modified one single line that returns the cursor here i replaced the call to contentprovider with my dbmanager code which in turn uses databasehelper to perform a query and return the cursorcursor cursor appglobalsinstancegetdbmanagergetallcamerasmy insertsupdatesdeletes on the database happen from elsewhere and not through the loader in most cases the db operations are happening in a background service and in a couple of cases from an activity i directly use my dbmanager class to perform these operationswhat i still do not get is who tells my loader that a row has been addeddeletedmodified in other words where is forceloadcontentobserveronchange called in my loader i register my observer on the cursorvoid registercontentobservercursor cursor contentobserver observer cursorregistercontentobservermobserverthis would imply that the onus is on the cursor to notify mobserver when it has changed but then afaik a cursor is not a live object that updates the data it is pointing to as and when data is modified in the dbheres the latest iteration of my loaderimport androidcontentcontextimport androiddatabasecontentobserverimport androiddatabasecursorimport androidsupportv4contentasynctaskloaderpublic class videosqlitecursorloader extends asynctaskloadercursor private static final string log tag cursorloader final forceloadcontentobserver mobserver cursor mcursor runs on a worker thread override public cursor loadinbackground utilslogdebuglog tag loadinbackground cursor cursor appglobalsinstancegetdbmanagergetallcameras if cursor null ensure the cursor window is filled int count cursorgetcount utilslogdebuglog tag cursor count count registercontentobservercursor mobserver return cursor void registercontentobservercursor cursor contentobserver observer cursorregistercontentobservermobserver runs on the ui thread override public void deliverresultcursor cursor utilslogdebuglog tag deliverresult if isreset an async query came in while the loader is stopped if cursor null cursorclose return cursor oldcursor mcursor mcursor cursor if isstarted superdeliverresultcursor if oldcursor null oldcursor cursor oldcursorisclosed oldcursorclose creates an empty cursorloader public videosqlitecursorloadercontext context supercontext mobserver new forceloadcontentobserver override protected void onstartloading utilslogdebuglog tag onstartloading if mcursor null deliverresultmcursor if takecontentchanged mcursor null forceload must be called from the ui thread override protected void onstoploading utilslogdebuglog tag onstoploading attempt to cancel the current load task if possible cancelload override public void oncanceledcursor cursor utilslogdebuglog tag oncanceled if cursor null cursorisclosed cursorclose override protected void onreset utilslogdebuglog tag onreset superonreset ensure the loader is stopped onstoploading if mcursor null mcursorisclosed mcursorclose mcursor null override public void oncontentchanged utilslogdebuglog tag oncontentchanged superoncontentchanged,['android'] +319704,skype starts dialing and hangs up after 2 seconds android i have skype 280920 installed on two android devices the first device comes with android 22 second with 404 when i initiate a call by executing the following codeintent skype intent new intentandroidintentactioncall privileged skype intentsetclassnamecomskyperaider comskyperaidermain skype intentaddflagsintentflag activity new task skype intentsetdatauriparsetelpassportcard actstartactivityskype intentskype starts dialing and hangs up after 2 sechowever the code works fine if i replace the current 280920 skype version by the previouswhy is this any help,"['java', 'android']" +319715,secure websocket wss does not work on firefox i have a working websocket non secure application but my website uses https and i need a secure websocket connection to avoid firefox to complain about the fact that the connection is insecurei am using phpwebsocketserver for my websocket server with php 529 so when i use websocket secure i cannot decrypt packets with the openssl decrypt function that is why i used stunnel in order to decrypt packets sent by the client using wss to do that i binded client websocket to 12345 port an server websocket to 54321 port then i added a stunnel in server mode wsserveraccept 12345connect 192168122754321with this configuration my application works fine on chrome through https wss but on firefox there is a problem during the handshake it seems that secwebsocketversion and secwebsocketkey are missing in the header i do not understand because it works on firefox through http wsthanks in advance for your helpedit i added an exception for the certificate on the port 12345 now the handshake is going well because i think firefox now have the secwebsocketkeyhere the working header request with firefox bigger than chrome requestget http11host 192168122712345useragent mozilla50 windows nt 61 wow64 rv140 gecko20100101 firefox1401accept texthtmlapplicationxhtmlxmlapplicationxmlq09q08acceptlanguage frfrfrq08enusq05enq03acceptencoding gzip deflatednt 1connection keepalive upgradesecwebsocketversion 13origin secwebsocketprotocol hybi00secwebsocketkey 65nhn33m6dripjqhcgk8papragma nocachecachecontrol nocacheupgrade websocket,['php'] +319718,using junit categories with maven failsafe plugin i am using junit categories to separate integration tests from unit tests the surefire plugin configuration works it skips the tests annotated with my marker interface integrationtesthowever the failsafe plugin does not pick the integration tests i have even tried to specify the junit47 provider but zero tests are run in the integrationtest phasehere is the pomxml fragment plugin groupidorgapachemavenpluginsgroupid artifactidmavenfailsafepluginartifactid version212version executions execution goals goalintegrationtestgoal goals execution executions configuration groupscommycompanytestintegrationtestgroups excludedgroupscommycompanytestunittestexcludedgroups configuration dependencies dependency groupidorgapachemavensurefiregroupid artifactidsurefirejunit47artifactid version212version dependency dependencies pluginhere is the failsafe part of the loginfo mavenfailsafeplugin212integrationtest default myprojectwar info failsafe report directory homestoupamyprojectwartargetfailsafereportsinfo using configured provider orgapachemavensurefirejunitcorejunitcoreprovider t e s t sconcurrency config is parallelnone percorethreadcounttrue threadcount2 useunlimitedthreadsfalseresults tests run 0 failures 0 errors 0 skipped 0is the provider orgapachemavensurefirejunitcorejunitcoreprovider that can be seen in the log output the right one,['java'] +319744,type conversion from c to java i did my best to google this but could not find a clean answer in a tablelike form that shows type conversionsthe reason i would like to convert these types is because i am using the android ndk to call functions from native code the problem is that the native code calls different types that do not exist in javai actually have no experience in c and have found these few types from looking at code quickly please feel free to edit this post to add different types to be convertedfrom c to javalong short char unsigned long unsigned short unsigned char byte int8 int16 int32 uint8 uint16 uint32 also if any of these cannot convert into a java type please explain why,"['java', 'android', 'c']" +319765,rails3 asset pipeline controller specific stylesheets on the topic of the asset pipeline rails guides suggest that rails can link to controller specific css files simply by calling stylesheet link tag paramscontroller the excerpt from rails guidesfor example if you generate a projectscontroller rails will also add a new file at appassetsjavascriptsprojectsjscoffee and another at appassetsstylesheetsprojectscscss you should put any javascript or css unique to a controller inside their respective asset files as these files can then be loaded just for these controllers with lines such as javascript include tag paramscontroller or stylesheet link tag paramscontroller pipelinehtmlhowtousetheassetpipelinethats works just fine in development where we allow rails to fall back on the asset pipeline in production however i get an error saying that the stylesheet is not precompiledfrom what i have read you have to add any assets that you want to be manifested as independent files to the precompile array like thisconfigassetsprecompile adminjs admincss swfobjectjsif i want controller specific stylesheets that are linked as per the rails guide example above do i have to enumerate each one in the precompile array,['ruby-on-rails'] +319767,why are my ef code first pregenerated views having no effect i have 300 dbsets in my context and the first query after app load a firstordefault where on an indexed field takes 40 secondsto improve this i am attempting to use pregenerated views in ef 431 code first using the t4 template herei compile it in but i see no performance difference i was hopingassuming it would help the painful slow startup i am experiencing but no luck should it help if not what exactly are pregenerated views used for and is there anything i can do to improve startup time splitting my context up is painful to say the least,"['c#', 'asp.net']" +319782,how to get a backtrace from a systemstackerror stack level too deep often i get hard to debug infinite recursions when coding ruby is there a way to get a backtrace out of a systemstackerror to find out where exactly the infinite loop occursexamplegiven some methods foo bar and baz which call each other in a loopdef foo barenddef bar bazenddef baz fooendfoowhen i run this code i just get the message testrb6 stack level too deep systemstackerror it would be useful to get at least the last 100 lines of the stack so i could immediately see this is a loop between foo bar and baz like thistestrb6 stack level too deep systemstackerror testrb2in foo testrb10in baz testrb6in bar testrb2in foo testrb10in baz testrb6in bar testrb2in foo is there any way to accomplish thiseditas you may see from the answer below rubinius can do it unfortunately some rubinius bugs prevent me from using it with the software i would like to debug so to be precise the question ishow do i get a backtrace with mri the default ruby 19,['ruby'] +319867,layoutsubviews called twice on uitableviewcell i am overriding layoutsubviews in my subclass of uitableviewcell i noticed that layoutsubviews is called twice for each cell on the second call the content view frame height is 1 less than the height on the first callimplementation myuitableviewcellcell nsstring asstringcgrect rect nsstring res nsstring alloc initwithformatf f f f rectoriginx rectoriginy rectsizewidth rectsizeheight res autorelease return res voidlayoutsubviews super layoutsubviews nsloghere i am frame cvframe selftext myuitableviewcellcell asstringselfframe myuitableviewcellcell asstringselfcontentviewframeendheres how the controller creates the table cells nsstringdataatindexnsintegerindex nsstring data nsstring alloc initwithformatrow d index return data autorelease cgfloattableviewuitableview tableview heightforrowatindexpathnsindexpath indexpath return 30 uitableviewcell tableviewuitableview tableview cellforrowatindexpathnsindexpath indexpath static nsstring cellidentifier alex nsinteger index indexpath row myuitableviewcellcell cell tableview dequeuereusablecellwithidentifiercellidentifier if cell nil cell myuitableviewcellcell alloc initwithstyleuitableviewcellstyledefault reuseidentifiercellidentifier autorelease celltext self dataatindexindex return celloutputhere i am row 0 frame0 0 320 30 cvframe0 0 320 30here i am row 1 frame0 30 320 30 cvframe0 0 320 30here i am row 0 frame0 0 320 30 cvframe0 0 320 290here i am row 1 frame0 30 320 30 cvframe0 0 320 290are 2 call per cell expected or am i doing something wrong,['ios'] +319873,spring creating multiple instances of a singleton i have a graph of spring beans which autowire each other heavily simplified illustrationcontextannotationconfigbean classfoobean classbarbean classbazpublic class foo autowired bar bar autowired baz bazpublic class bar autowired foo foopublic class baz autowired foo fooall of these beans do not have scope specified which imply they are singletons making them explicit singletons does not change anything i have triedthe problem is that after the instantiation of a single application context instances of bar and baz contain different instances of foo how could this happeni have tried to create public no args constructor for foo and debugging has confirmed foo is created more than once the stack trace for all of these creations is herei have also tried to enable debug logging for spring and among all other lines got the followingdebug orgspringframeworkbeansfactorysupportdefaultlistablebeanfactory creating shared instance of singleton bean foodebug orgspringframeworkbeansfactorysupportdefaultlistablebeanfactory creating shared instance of singleton bean foodebug orgspringframeworkbeansfactorysupportdefaultlistablebeanfactory creating shared instance of singleton bean fooi understand that my beans are crossreferencing each other but i would expect spring framework to respect singleton scope and initialize a singleton bean once and then autowire it to whoever wants itthe interesting fact that if i use old school private constructor with public static foo getinstance accessor this works just fine no exceptions are thrown during the context setupfwiw i am using spring version 305 also tried with 312 same results with oscsclasspathxmlapplicationcontextstring configlocations constructori can easily convert my code to use static initializer but i want to understand why would spring behave this way is this a bugedit some additional investigation showed thatafter the application context is initialized all subsequent requests to contextgetbeanfooclass always return the same instance of fooreplacing autowired with setters about 20 usages of this bean still results multiple constructions of this object but all dependencies are injected with the same referenceto me above suggests that this is a spring bug pertaining to autowired implementation i am going to post to spring community forums and post back here if i manage to obtain anything useful,['java'] +319953,how can i read a environmental variable in cocoa how could i read an environmental variable that a user has seti am new to desktop development on the mac cocoa and i am building a little tool that i can use to access amazons s3 servicei set my environmental variables in my bash profile but i want this to work regardless of where the user entered it bashrc bash profile or profile etc,['objective-c'] +319979,jersey returns http status 405 method not allowed i have a very simple endpoint using jersey my url is static it does not require any request parameters it looks like this getpathmydataproducesjavaxwsrscoremediatypeapplication json public string getdata return name valuehowever whenever i request this url i always receive a http status code of 405 method not allowedthe weird thing is that if i change the path annotation and define a path variable eg pathchartblah it works finedoes anyone have an idea why i have to define a path variable to get this to work i do not need a path variable and it seems silly to add one just to get a 200 response,['java'] +320021,correct way to pause python program i have been using the input function as a way to pause my scriptsprintsomethingwait inputpress enter to continueprintsomethingis there a formal way to do this,['python'] +320024,how to automatically crop and center an image given any arbitrary image i want to crop a square from the center of the image and thisplay it within a given squarethis question is similar to this css thisplay an image resized and cropped but i do not know the size of the image so i cannot use set margins,['css'] +320026,check if a hashs keys include all of a set of keys i am looking for a better way to doif hashkey a hashkey b hashkey c hashkey dpreferably something likehashincludes keys a b c d i came up with hashkeys a b c d a b c dbut i dont like having to add the array twice though,['ruby'] +320034,from swf to air to ios application i have existing flash application which compiles to swf and runs on web i am looking at converting that application to work on mobile devices such as iphoneipad i see that there is now a way to publish adobe air applications on mobile devices my thought is why not convert swf to air application and then use that air application to publish on mobile devices does it make sense is this even possible or doablewhat are people doing to convert their existing flash swf applications to work on mobile devices,"['iphone', 'ios']" +320060,how to inject css using content script file in chrome extension i am trying to inject my css from javascript which is injected as content scriptcontent scripts matches js scriptjs i found similar question about injecting css but i encountered a problem while using code from accepted answer heres my scriptjs contentsvar link documentcreateelementlinklinkhref chromeextensiongeturlstylecsslinktype textcsslinkrel stylesheetdocumentgetelementsbytagnamehead0appendchildlinkafter i load some page this message appears in consoledenying load of chromeextensionphkgaaiaakklogbhkdnpjncedlbamanifixcss resources must be listed in the web accessible resources manifest key in order to be loaded by pages outside the extensionis there any way to fix this or maybe some other way to inject a css from that javascript filenote i cannot include style sheet directly from manifest,['javascript'] +320065,why does jsonnet deserializeobject change the timezone to local time i am using jsonnet to deserialize a datetimeoffset but it is ignoring the specified timezone and converting the datetime to the local offset for example givenvar content startdatetime20120719t1430930when deserialised usingvar jsonserializersettings new jsonserializersettings dateformathandling dateformathandlingisodateformat dateparsehandling dateparsehandlingdatetimeoffset datetimezonehandling datetimezonehandlingroundtripkind var obj jsonconvertdeserializeobjectcontent jsonserializersettingsthe obj will contain a property containing a datetimeoffset but the value will be 20120719t15301030 ie converted to the local timezone instead of preserving the original timezoneis there a way to get the value to be parsed as expected so that the resulting datetimeoffset property will match the supplied value,['c#'] +320107,objectivec sort keys of nsdictionary based on dictionary entries ok so i know that dictionaries cannot be sorted but say i have nsmutablearray keys somedictionary allkeys now i want to sort those keys based on the corresponding values in the dictionary alphabetically so if the dictionary contains keysomestring then i want to sort keys based on the strings they correspond to i think its some application of sortusingcomparator but its a little out of my reach at this point,['objective-c'] +320119,android gcm same sender id for more application is it possible to use same sender id for more applications now i have 18 application different language and some functionality which use same backend now i am implementing push notifications with gcm but backend team preffer to have only one google project sender id for all applications did anyone try it is this scenario possible what are the drawbacksthanks,['android'] +320193,corebluetooth central manager callback didthiscoverperipheral twice i scan for my peripheral like thisnsdictionary scanoptions nsdictionary dictionarywithobjectnsnumber numberwithboolno forkeycbcentralmanagerscanoptionallowduplicateskey scan for peripherals with given uuid cm scanforperipheralswithservicesnsarray arraywithobjecthelicontrollerserviceuuid optionsscanoptionsno problem there i find the peripheral and are able to connect to it as you can see i give it cbcentralmanagerscanoptionallowduplicateskey with bool no to not allow for more than one peripheral but sometimes the didthiscoverperipheralcallback fires twice void centralmanagercbcentralmanager central didthiscoverperipheralcbperipheral peripheral advertisementdatansdictionary advertisementdata rssinsnumber rssi ifthiscovered thiscovered yes nslogthiscovered cm stopscan scanbutton settitleconnect forstateuicontrolstatenormalelse ifthiscovered thiscovered yes nslogalready thiscoveredsome times i get thiscoveredalready thiscoveredas output in my console and most of the times only the thiscoveredmessage shows in my peripheral delegate i first thiscover services which then call peripheral thiscovercharacteristics and the callback always occurs void peripheralcbperipheral peripheral didthiscovercharacteristicsforservicecbservice service errornserror errornslogdid thiscover characteristic for service serviceperipheral uuidforcbcharacteristic c in service characteristics we never get here when peripheral is thiscovered twice ifc uuid isequalmycharacteristicuuid nslogfound characteristic selfthrottlecharacteristic c when didthiscoverperipheral occur twice service becomes nilin this method even though peripheral is not uuid name is still correct rebooting the phone or resetting the network settings fixes the problem temporarily i really need to get this fixed thank you,"['iphone', 'objective-c']" +320199,why does not string class implement ienumerable in portable library i have created a pcl project that targets net framework 4 and silverlight 5 i use an extension for visual studio 2010 not portable project template from visual studio 2012 if that mattersi am trying to reverse a string using systemlinqenumerablereversetsource extension method but it does not work because compiler thinks that systemstring does not implement ienumerablechar,['.net'] +320204,tastypie filtering many to many relationships i have two models that are linked by another model through a many to many relationshipheres the models themselvesclass postsmodelsmodel id modelscharfieldmax length108 primary keytrue tags modelsmanytomanyfieldtags throughposttagsclass tagsmodelsmodel id modelscharfieldmax length108 primary keytrue posts modelsmanytomanyfieldposts throughposttagsclass posttagsmodelsmodel id modelscharfieldmax length108 primary keytrue deleted modelsintegerfield post id modelsforeignkeyposts db columnpost field tag id modelsforeignkeytags db columntag fieldand the tastypie resourcesclass postsresourcemodelresource tags fieldstomanyfielddjango appapitagsresource tags nulltrue class meta queryset postsobjectsfilterdeleted0 resource name postsclass tagsresourcemodelresource posts fieldstomanyfielddjango appapipostsresource posts nulltrue class meta queryset tagsobjectsfilterdeleted0 resource name tagson the posttags table there is a deleted flag is it possible to only return linked results when the deleted flag in posttags is 0 i have tried this filter attribute in tastypie but it only seems to care about the flag in the linked tableie tags or posts not the actual table doing the linking,['python'] +320216,java stringcontains in switch statement how can i convert the following code to switch statementstring x user inputif xcontainsa condition a else if xcontainsb condition b else ifxcontainsc condition c else condition d,['java'] +320221,ios detect when my uiview is add in other view customview customview selfview addsubviewcustomviewi need to detect in my customview class when it is added in other views or when my superview changes,['ios'] +320231,c why is a fprintfstdout so slow i still often use console output to get ideas whats going on in my codei know this may be a bit old fashion but i also use this to pipe stdoutinto log files etchowever it turns out that the output to the console is slowed down for some reason i was wondering if someone can explain why an fprintf to a consolewindow appears to be sort of blockingwhat i have donediagnosed so fari measured the time a simple fprintfstdoutquick fprintfnit needs 082ms in average this is considered by far too long since a vsprintf s writes the same output into a string in just a few microseconds therefore there must be some blocking specifically to the consolein oder to escape from the blocking i have used vsprintf s to copy my output into a fifo alike data structure the data structure is protected by a critical section object a separate thread is then unqueing the data structure by putting the queued output to the consoleone further improvement i could obtain by the introduction of pipe servicesthe output of my program supposed to end up in a console window goes the following waya vsprintf s formats the output to simple stringsthe strings are queued into a fifo alike data structure a linked list sructure for example this data structure is protected by a critical section objecta second thread dequeues the data structure by sending the output strings to a named pipea second process reads the named pipe and puts the strings again into a fifo alike datastructure this is needed to keep the reading away from the blocking output to the consolethe reading process is fast at reading the named pipe and monitors the fill level of the pipes buffer continuously a second thread in that second process finally dequeues the data structure by fprintfstdout to the consoleso i have two processes with at least two threads each a named pipe between them and fifo alike data structures on both sides of the pipe to avoid blocking in the event of pipe buffer fullthat is a lot of stuff to just make sure that console output is nonblocking but the result isnot too bad my main program can write complex fprintfstdout within just a few microsecondsmaybe i should have asked earlier is there some other easier way to have nonblocking console output,['c'] +320253,what is the main difference between require and define function in dojo and when would we use either i am new to learning dojo and i have come across the require and define functions and i can not get my head around either of them also when would i use either of them a small demo or example would be beneficial many thanks,['javascript'] +320318,javascript how to get keys of associative array to array variable let us have an associative array like thisvar aarray aarrayid testaarrayx1 123aarraystackoverflow whats upaarrayx2 456var keys forvar key in aarray if aarrayhasownpropertykey keyspushkey consolelogkeysis there any easyshort way how to get array of keys to array variable without loopif so additionally is possible to apply some regular expression to key list to get just keys that match such pattern let us say x without another loop,['javascript'] +320326,setting up log4net to log output from a class library i am trying to setup log4net this is my first time using log4net to log to a text file in an assembly i am not getting any errors but it is also not working i can breakpoint the lines where i am logging my output and see that they are reached but like i say nothing happenswhere am i going wrongi have added the following to my packagesconfig file inside the packages attribute log4net appender namefileappender typelog4netappenderfileappenderlog4net file valuecctilogtxt appendtofile valuetrue lockingmodel typelog4netappenderfileappenderminimallock layout typelog4netlayoutpatternlayout conversionpattern valuedate thread level logger messagenewline layout filter typelog4netfilterlevelrangefilter levelmin valueinfo levelmax valuefatal filter appender root level valuedebug appenderref reffileappender root log4netconfigurationi have added the following line to assemblyinfocsassembly log4netconfigxmlconfiguratorwatchtruei added the log4net assembly using nuget and i am logging like thisprivate log4netilog log log log4netlogmanagergetloggersystemreflectionmethodbasegetcurrentmethoddeclaringtype logdebugfoobarlike i say no errors but nothing happens eitherwhat am i missing,['c#'] +320374,php remote debugging xdebug cannot connect to jetbrains php storm client is like to get remote debugging to work with the following software configurationwin 7 pro 64bitwamp server 22 32bit incl apache 2 php 543 xdebug php xdebug22154vc9dlljetbrains phpstorm 4031 wamp is up and running my site can be found under localhostfox2 php storm has a project where there is a mapping between my sourcefiles and the apache alias localhostfox2 i installed the php extension xdebug and added the following lines to my phpinixdebugzend extensioncwampbinphpphp543zend extphp xdebug22154vc9dllxdebugremote enableonxdebugremote hostlocalhostxdebugremote port90xdebugremote connect backonxdebugremote autostartonxdebugprofiler enableonxdebugprofiler enable triggeroffxdebugprofiler output namecachegrindouttpxdebugprofiler output dircwamptmpxdebugremote logcwamptmpxdebuglogxdebugremote cookie expire time60this should configure the remote debugging xdebug and the call back address i check already my installation here xdebugorgwizardphp 3 i configured phpstorm first i added the local serverand then checked my settings here i tried 127001fox as server address as well and localhost insteadhier my debug settings now i restart my apache i go into phpstorm set a break point it is red click the function run start listen to php debug connectionsthe telephone receiver is turing into green what ever that exactly could mean but it is a positiv signal to mewhen i now run my php script on the local webserver absolutley nothing happens the programm runs over the break point and does not stopin the xdebuggers log cwamptmpxdebuglog i find loads of these messages like these i checking remote connect back address i remote address found connecting to 190 e could not connect to client log closed at 20120719 142108somewhere in the internet i found the hint that the windows firewall could block the communication so i turned it off completley but that did not helpi also tried to connect via telnet to localhost90 and i got a response from phpstorm has anybody an idea where to search the error or what else i could try to get this stuff working thank you very much for your help in advance michaelps sorry i am not allowed to post more than two links because i am new here so therefor no hyperlink to the xdebug wizard,['php'] +320381,printing stuff in rails literally to a printer i am wondering if there was any library or gem available in rails for printing the contents of a web page as in literally on to paper via a printer i was also wondering if there was any way you can specify that only a specific part of the page eg a div or something would be printed any pointers advice or links to tutorials would be appreciated editso i have made a stab at creating a stylesheet which will create a print friendly view let us call it printcssdivtransposekeys diveditsong divnavigation divdebug thisplay noneand i was wondering if there was any way i could apply it only when my application fires the print action so that when the following is link is clicked the application applies the css above before it prints heres the link in my embedded ruby html link to print onclick printpage and finally my javascript calling the print functionfunction printpage windowprint,"['javascript', 'html', 'ruby-on-rails']" +320388,what does int1 stands for in mysql int1 i know 1 does not mean 1 digit it represents client output thisplay format onlybut what does this signify i have declared year as int1 i still see all 4 bytes please tell me what does int1 means select from test userdb id name year 1 abc 2012 2 stack 99,['mysql'] +320476,dynamic smart date mask while inserting date is there a way in javascript or jquery to detect and change dynamically while typing a date for both a key input and a copy and paste to a text boxi am trying to create a functional text box which has two digits such as a month since the month can be a number from 1 12 i want to enforce the first digit to be a 1 or a 0the trick that i am trying to do however is when the text box first gains focus and a user beging to type a number if that number is 2 9 i want a zero to automatically fill the first spot and then but the 9 in the second spotbefore i type anything this date input would look like so if i type a 11 if i type 2 should get02 if i type 22 should get022 if i type 77 should get0707 i would be very interested for in an answer with code or a link to a tool that already does this or a link to a previous post eventually i want to put it in a masked so 772011 or 7711 or 07072011 will alway fill to 07072011 in the final final version i am trying to get the year to default to the current decade but have a drop down to each 10 year,"['javascript', 'jquery']" +320489,can i allow multiple programs to read from the same file at the same time i have an application that reads a set of data files and performs some model computations the program does not need to modify the data files themselves so i am currently opening them with the readonly flag as shown belowfile fileif wfopen sfile fnamec str lr 0i would like to have several instances of my program running at the same time using the same set of data but performing different computations on the data none of my programs need to modify the data files as the data files are very large i cannot make separate copies of the data to use with each programi assumed that because i am opening the files with readonly permissions two programs could be reading from the same file at the same time instead i get various errors along the lines of the file could not be open because it is being used by another processas my development environment is windows 7 this question suggests it might be a matter of enabling read sharing however all of the answers in that thread rely on createfile whereas i am dealing with legacy code that was written with stdiohis there a way i can have several programs concurrently read from a file using the fopen class of functions,"['c++', 'c']" +320503,variable generic return type in c is there any way to have a method return any one of a number of generic types from a method for example i have the followingpublic static t parseattributevaluetthis xelement element string attribute iftypeoft typeofint32 return int32parseelementattributeattributevalue iftypeoft typeofdouble return doubleparseelementattributeattributevalue iftypeoft typeofstring return elementattributeattributevalue iftypeoft typeofitemlookuptype return enumparsetypeoft elementattributeattributevalue this is only a very quick mockup i am aware that any production code would need to be significantly more thorough in null checks etcbut the compiler does not like it complaining that int32 cannot be implicitly converted to t it does not work with a cast either i can understand that at compile time it has no way to know what t is but i am checking it beforehand is there anyway i can make this work,['c#'] +320505,remove first line from a file possible duplicateremoving the first line of a text file in c what would be the fastest and smartest way to remove the first line from a huge think 23 gb filei think that you probably cannot avoid rewriting the whole file chunkbychunk but i might be wrongcould using memorymapped files somehow help to solve this issueis it possible to achieve this behavior by operating directly on the file system ntfs for example say update the corresponding inode data and change the file starting sector so that the first line is ignored if yes would this approach be really fragile or there are many other applications except the os itself that do something similiar,"['c#', 'c++']" +320621,get dom elements by tag name with domdocumentloadhtml and getelementsbytagname sorry if this is reposted but i cannot wrap my mind around it and i have tried all the available documentation and examples i could findi am trying to get the first img element of a string containing htmlphphtml pimg src alt width200 height300 pdom new domdocumentdomloadhtmlhtmlimgs domgetelementsbytagnameimgvar dumpimgsthis spits objectdomnodelist57 0 when it should find the one occurrencei have tried with xpath with no luck either,['php'] +320627,catransform3drotate rotate for 360 degrees i have started using catransform3d lately and it seems very nice i just have 1 issue with the rotation though i am trying to rotate my view for 360e degrees to the right but if i just put pass 360 to catransform3drotate it does not work it just does not move at allheres my code calayer layer docklayer catransform3d r catransform3didentity rm34 10 500 r catransform3drotater degreestoradians3600f 10f 10f 10f layertransform rdoes anyone know how to fix this issue thanks in advance,"['iphone', 'objective-c']" +320696,eventdatatransferfiles is empty when ondrop is fired okay i have an element set up to receive a filedrop event but when i look in eventdatatransfer it is blank i have not gotten around to learning the dragndrop html5 api just yet and am still a little foggy on it i am working on it at my site if you wouldnt mind poking around my code and seeing whats going on it would be highly appreciated the entire event object is being logged,['javascript'] +320702,android eclipse issue failed to create buildconfig class i am getting failed to create buildconfig class error while cleaning android project in eclipse i have recently installed eclipse juno for mobile developers and while i was trying to import my existing android applications eclipse started giving me this kind of error eclipse is working fine if i create new android projects what could be the possible cause and probable solution for this issuei am using os windows server 2008,['android'] +320731,jsonp web service with python i am writing an ajax function that requests data from my json python webservice my ajax request looks like url httplocalhost8001blah ajax url url type get datatype jsonp success functiondata consoleloghi for now my python web service has a function that handles the request to blah that has the following return statement return jsondumpsa1 b2 my ajax function is not successfully retrieving a response from my python webservice but i do not get any errors in firebug what is my webservice or javascript doing wrong,['python'] +320753,undefined reference to boostchronosystem clocknow boost and cppnetlib i come here to ask for a fix to a situation that has been frustrating me a lotfirst of all i am on windows i use mingw as a compiler ci have been having some problems with getting a program to work with the use of cppnetlib and ssl trying to post to a https site i believe everything is in order except this one error that keeps evading mecboost 1 50 0boost 1 50 0stageliblibboost threadmgw46mt1 50athreadothreadcpp undefined reference to boostchronosystem clocknowi am sure that i have linked to chrono as well as all the a libs in boost rootstagelib i have tried reordering so chrono is linked before thread nothing helpedi have tried definining the boost chrono inlined in my ide settings and multiple confhpps to make it header only which did not helpi am pretty sure this is a newbie question and i hope that someone can give me a quick fix i have written this in a rush because i have to be somewhere but if you need more info please say so and i can write it more carefully when i get home thanks,['c++'] +320785,in an openmp parallel code would there be any benefit for memset to be run in parallel i have blocks of memory that can be quite large larger than the l2 cache and sometimes i must set them to all zero memset is good in a serial code but what about parallel code has somebody experience if calling memset from concurrent threads actually speed things up for large arrays or even using simple openmp parallel for loops,['c'] +320808,fatal error 11 content is not allowed in prolog i am using java and i am trying to get xml document from some http link code i am using isurl url new urllinkhttpurlconnection connection httpurlconnectionurlopenconnectionconnectionsetrequestmethodgetconnectionconnectdocument doc nullcountinputstream in new countinputstreamurlopenstreamdoc documentbuilderfactorynewinstancenewdocumentbuilderparseindo not pay attention at countinputstream it is some special class acting like regular input stream using the code above i sometimes got error fatal error 11 content is not allowed in prolog i assume that is has something to do with bad format of xml but i have no idea how to fix it,['java'] +320842,sqlalchemy instrumentedlist object has no attribute filter i have the following 3 classesclass resource id columninteger primary keytrue path columntext data columnbinary type columntext def set resourceself path data type selfpath path selfdata data selftype typeclass environmentresourcebase resource tablename environment resources parent id columninteger foreignkeyenvironmentsid ondeletecascade def init self path data type selfset resourcepath data typeclass environmentbase tablename environments id columninteger primary keytrue identifier columntext uniquetrue name columntext description columntext resources relationshipenvironmentresource cascadeall deleteorphan passive deletestrue tools relationshiptool cascadeall deleteorphan passive deletestrue def init self name identifier description selfname name selfidentifier identifier selfdescription description def get resourceself path return self resourcesfilterenvironmentresourcepathpathfirston calling get resource i am told that instrumentedlist object has no attribute filter i have gone through the documentation and cannot quite figure this out what am i missing so that i may be able to filter the resources corresponding to an environment inside my get resource methodps i know get resource will throw an exception that is what i would like it to do,['python'] +320848,what exactly does normalization in css do i was trying some code with unordered lists in html on jsfiddle and i was irritated to death to find out that the bullets in the ul would not show for no apparent reason on trying different things on my code i finally came to realize that i needed to uncheck the normalized css option on the jsfiddle pageafter that i googled what it actually was and read this page from w3corg this page only talks about diacritics and accents i get it but why werent the bullets showing up with the normalized css option checked what are the other things that are affected if you select that optionthank you for looking in,"['html', 'css']" +320865,matplotlib control capstyle of line collectionlarge number of lines similarly to a previous question of mine i would like to control the capstyle of lines being drawn using matplotlib however i have an extremely large number of lines and drawing with anything other than a line collection takes way too long are there any workarounds to control the capstyle of lines in a line collection in a generic way or alternatively super fast ways of drawing a large number of line2d lines for instance i have tried using the matplotlib rc settings viaimport matplotlib as mplmplrcparamslinessolid capstyle roundmplrcparamslinessolid joinstyle roundbut this does not appear to have any affect from the docstring for collectionspythe classes are not meant to be as flexible as their single element counterparts eg you may not be able to select all line styles but they are meant to be fast for common use cases eg a large set of solid line segemntswhich explains why i cannot seem to control various parameters but i still want to do it i have had a look at the code for the agg backend backend aggcpp not that i really understand it and it appears that line cap and line join are controlled by gccap and gcjoin where gc comes from the gcagg class does anyone know how one can control this from python am i asking the right question here perhaps that are easier ways to control these parametersany help is greatly appreciated i am desperate to get this working so even crazy hacks are welcomethankscarson,['python'] +320874,how to format timespan to string before net 40 i am compiling in c using net 35 and am trying to convert a timespan to a string and format the string i would like to use mystring mytimespantostringchowever the timespantostring method does not take a format string as an argument until net 40 and i am using net 35how then would you format a timespan as a string my final goal is to thisplay the timespan in format hhmmss but am currently receiving hhmmssfi have tried usingmystring stringformat0hhmmss mytimespanbut stringformat is only formatting my datetime and passing different format strings does not work when trying to format a timespan,['c#'] +320905,opening procnettcp in c from a posix thread fails most of the time when i try to open procnettcp from a child posix thread in c it fails with a no such file or directory error if i try to open it from the parent thread it succeeds every time and the process of openingclosing it in the parent thread then makes it succeed about a third of the time in the child thread too i can open procuptime in the child thread 100 of the time without issue heres some example code which can be compiled with g wall testcc o test pthreadinclude iostreaminclude fstreaminclude cstringinclude cerrnoinclude pthreadhusing namespace stdvoid open test void ifstream in inopenprocnettcp if infail cout failed strerrorerrno endl else cout succeeded endl inclose return 0int main int argc char argv open testnull pthread t thread pthread createthread null open test null pthread exit0i am running this on an ubuntu 1204 box with an intel i52520m 2 cores 2 virtual cores on linux kernel 320 here is the output of me running the above code 6 times in a rowmikeungtmp testsucceededfailed no such file or directorymikeungtmp testsucceededsucceededmikeungtmp testsucceededfailed no such file or directorymikeungtmp testsucceededfailed no such file or directorymikeungtmp testsucceededsucceededmikeungtmp testsucceededfailed no such file or directorymikeungtmpit is probably worth noting that i do not have this problem if i use fork instead of posix threads if i use fork then the child process has no problems reading procnettcpjust a couple of data points to throw in it looks like this is a regression in linux as 2635 seems to work 100 of the time 320 pukes most of the time even on my slow old pentium m based laptop,['c++'] +320949,check two arrays have elements with same values possible duplicatesimplest code for array intersection in javascript let us say i have arrays01and 123i need to verify whether these arrays have common elements for this case it would be 1using jquery i check it following way1 get length of 1st array2 get length of 2nd array3 merge arrays4 get length of merged array5 if lenght of merged array not equal lenghts 2 initial arraysthat they have common elementsone line code isevent2zone0lengthevent2zone1lengthuniquemergeevent2zone0zoevent2zone1zolengthis there more standard or gracefull way to do the same operation,"['javascript', 'jquery']" +320951,status bar notification plugin error with cordova i am trying to add the status bar notification plugin for cordova to my android app but i get an error with it is codeheres the problematic code notification noti new notificationbuildercontext setcontenttitlecontenttitle setcontenttextcontenttext setsmalliconicon buildthe error is on the build eclipse tells methe method build is undefined for the type notificationbuilder,['android'] +320976,customize java editor in eclipse i was wondering if there was a simple way to extend the features of the java editor in eclipse for some custom projectexample when i write in eclipse deprecatedpublic void foofoo will be automatically crossedout and thus easy to noticein some projects i would like to do the same with custom annotations like untested or verified to have a better dev environment but of course there are plenty of examples like this special class colours etci wanted to create a simple eclipse bundle that extend this kinds of rules but i am unable to find an adequate extension point for thisdo i have to create a new text editor from scratch thanks for any help or comments,['java'] +320977,getting blank page instead of 401 error page i have an aspnet mvc3 application with windows authentication deployed to iis6 when an authenticated user clicks on a link that they are not authorized to view they are prompted to enter their username and password in a browser dialog not a page as expected however after clicking cancel or entering invalid credentials three times instead of seeing the a 401 unauthorized page i see a blank white pagelooking at fiddler there are three requestsresponses after clicking cancel here are the response summaries and headersaspnet access is denied message 4012http11 401 unauthorizeddate fri 20 jul 2012 143421 gmtserver microsoftiis60wauthenticate negotiatewauthenticate ntlmxpoweredby aspnetxaspnetversion 4030319cachecontrol privatecontenttype texthtml charsetutf8contentlength 1701proxysupport sessionbasedauthenticationiis you are not authorized to view this page 4011http11 401 unauthorizedcontentlength 1539contenttype texthtmlserver microsoftiis60wauthenticate ntlm tlrmtvntuaacadaamadgaf omitted for brevityxpoweredby aspnetdate fri 20 jul 2012 143421 gmtproxysupport sessionbasedauthenticationempty responsehttp11 401 unauthorizeddate fri 20 jul 2012 143421 gmtserver microsoftiis60wauthenticate negotiatewauthenticate ntlmxpoweredby aspnetxaspnetversion 4030319xaspnetmvcversion 30cachecontrol privatecontentlength 0proxysupport sessionbasedauthenticationhow do i get this to thisplay a 401 error pageupdate 1here is my webconfig errors section customerrors moderemoteonly defaultredirecterror i am also using handleerrorattributei suspect that iis is returning the blank page rather than aspnet but i am not sure how to prove thatupdate 2this is interesting if i refresh the blank page i see the aspnet access is denied message,['asp.net'] +320979,why would urlconnection timeout after 6 minutes instead of 5 seconds i am copying this method verbatim from my application which is not complete yet but it does attempt to provide me with a timeout stack trace if things do not go smoothlyprotected boolean ishttpalive boolean ishttpok false httpurlconnection httpconnection null try url gurl new url urlconnection connection gurlopenconnection connectionsetconnecttimeout5 10 5 seconds httpconnection httpurlconnection connection int responsecode httpconnectiongetresponsecode if responsecode httpurlconnectionhttp ok ishttpok true catch exception e eprintstacktrace finally if httpconnection null httpconnectionthisconnect return ishttpoknow on one of my test devices droid when there is a problem i do get the exception but only after 6 minutes and 36 seconds not 5 seconds as i set in the code abovethe timeout exception is thrown for the getresponsecodewhywhat am i missing,['android'] +320981,android device not seen by adb but accessible from windows xp i just bought a new nexus 7 tablet and i am trying to put my first java application on it however i am stuck at a very basic point adb does not see my device when i check on my working station windows perfectly detects the tablet i switched the usb port and every one make appear the device but adb still cannot see it i rebooted and it is still not working any idea about thisupdatethere was actually two problems first i had not activated the usb debugging mode this was the reason why i could use the tablet from the working station as a simple multimedia player even though the correct usb driver was not installedsecond the driver was not detected by windows xp even we i specified the correct repository to search for it the problem was solved by following the procedure described by adamp,['android'] +320985,xlarge vs sw720dp screen size confusion for reference supporthtmlthe old style size quantifiers are deprecateda set of four generalized sizes small normal large and xlarge note beginning with android 32 api level 13 these size groups are deprecated in favor of a new technique for managing screen sizes based on the available screen width if youre developing for android 32 and greater see declaring tablet layouts for android 32 for more informationi was hoping that devices with 32 would still use resources declared in drawablelargemdpi or layoutxlarge but this does not seem to be the casei have a test project that contains a layout file for each of these sizeslayoutsw600dplayout720dplayoutxlargelayouton a 10 motorola xoom running android 40x the device picks the layout in the layout720dp folder if that folder does not exist it picks the layout in the layoutsw600dp folder why does not it pick the layout in layoutxlargeeven more strange is i have drawables in these foldersdrawablesw600dpmdpidrawablexlargemdpithe 10 motorola xoom from above picks the image from drawablesw600dpmdpi why does not it pick the drawable in drawablexlargemdpishould we not expect the xlarge quantifier to work at all above android 32does this mean i have to duplicate all assets in the drawablexlargemdpi folder into the drawablesw720dpmdpi folder to support android 30 31 and 32hopefully i am just missing something simple here please advise,['android'] +321048,classcastexception when using linearlayoutlayoutparams this is the exception0720 195214193 eandroidruntime3908 fatal exception main0720 195214193 eandroidruntime3908 javalangclasscastexception androidviewviewgrouplayoutparams cannot be cast to androidwidgetlinearlayoutlayoutparams0720 195214193 eandroidruntime3908 at androidwidgetlinearlayoutmeasureverticallinearlayoutjava6340720 195214193 eandroidruntime3908 at androidwidgetlinearlayoutonmeasurelinearlayoutjava5530720 195214193 eandroidruntime3908 at androidviewviewmeasureviewjava128920720 195214193 eandroidruntime3908 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava46980720 195214193 eandroidruntime3908 at androidwidgetframelayoutonmeasureframelayoutjava2930720 195214193 eandroidruntime3908 at androidviewviewmeasureviewjava128920720 195214193 eandroidruntime3908 at androidsupportv4viewviewpageronmeasureviewpagerjava12490720 195214193 eandroidruntime3908 at androidviewviewmeasureviewjava128920720 195214193 eandroidruntime3908 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava46980720 195214193 eandroidruntime3908 at androidwidgetframelayoutonmeasureframelayoutjava2930720 195214193 eandroidruntime3908 at androidviewviewmeasureviewjava128920720 195214193 eandroidruntime3908 at androidwidgetlinearlayoutmeasureverticallinearlayoutjava8120720 195214193 eandroidruntime3908 at androidwidgetlinearlayoutonmeasurelinearlayoutjava5530720 195214193 eandroidruntime3908 at androidviewviewmeasureviewjava128920720 195214193 eandroidruntime3908 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava46980720 195214193 eandroidruntime3908 at androidwidgetframelayoutonmeasureframelayoutjava2930720 195214193 eandroidruntime3908 at comandroidinternalpolicyimplphonewindowdecorviewonmeasurephonewindowjava22650720 195214193 eandroidruntime3908 at androidviewviewmeasureviewjava128920720 195214193 eandroidruntime3908 at androidviewviewrootimplperformtraversalsviewrootimpljava12400720 195214193 eandroidruntime3908 at androidviewviewrootimplhandlemessageviewrootimpljava26280720 195214193 eandroidruntime3908 at androidoshandlerthispatchmessagehandlerjava990720 195214193 eandroidruntime3908 at androidoslooperlooplooperjava1370720 195214193 eandroidruntime3908 at androidappactivitythreadmainactivitythreadjava45070720 195214193 eandroidruntime3908 at javalangreflectmethodinvokenativenative method0720 195214193 eandroidruntime3908 at javalangreflectmethodinvokemethodjava5110720 195214193 eandroidruntime3908 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava9800720 195214193 eandroidruntime3908 at comandroidinternaloszygoteinitmainzygoteinitjava7470720 195214193 eandroidruntime3908 at dalviksystemnativestartmainnative methodi cannot see a line where the exception is thrown so i cannot figure it out quite good i do know it is in these linespublic class todayfragment extends fragment listview listviewstring urlsactionbar mactionbarspinner spinner1public todayfragment overridepublic view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate linearlayout linear new linearlayoutgetactivity linearsetorientationlinearlayoutvertical spinner1 new spinnergetactivity spinner1setlayoutparamsnew layoutparams linearlayoutlayoutparamswrap content linearlayoutlayoutparamswrap content linearaddviewspinner1 listview new listviewgetactivity spinner1setlayoutparamsnew layoutparams linearlayoutlayoutparamsmatch parent linearlayoutlayoutparamswrap content linearaddviewlistview new parsehtmlexecute return linear the fragment i am using is androidsupportv4appfragment what causes this,['android'] +321051,constructor overloading with default parameters i accidentally overloaded a constructor in c as followspublic myclastring mystring some code goes here public myclastring mystring bool myparameter false some different code herewith this code my project compiled fine if i call the constructor with just a string argument how does c decide which constructor i want to use why is this functionality syntactically allowed,['c#'] +321053,code flow misunderstanding after looking at json syntax just for curiosity ive noticed a different flow tags edges so what is the difference between vs,['javascript'] +321055,how to organize unit tests and do not make refactoring a nightmare my current way of organizing unit tests boils down to the followingeach project has its own dedicated project with unit tests for a project businesslayer there is a businesslayerunittests test projectfor each class i want to test there is a separate test class in the test project placed within exactly the same folder structure and in exactly the same namespace as the class under test for a class customerrepository from a namespace businesslayerrepositories there is a test class customerrepositorytests in a namespace businesslayerunittestsrepositoriesmethods within each test class follow simple naming convention methodname condition expectedoutcome so the class customerrepositorytests that contains tests for a class customerrepository with a get method defined looks like the followingtestfixturepublic class customerrepositorytests test public void get whenx thenrecorthisreturned test public void get wheny thenexceptionisthrown this approach has served me quite well because it makes locating tests for some piece of code really simple on the opposite site it makes code refactoring really more difficult then it should bewhen i decide to split one project into multiple smaller ones i also need to split my test project when i want to change namespace of a class i have to remember to change a namespace and folder structure of a test class as wellwhen i change name of a method i have to go through all tests and change the name there as well sure i can use search replace but that is not very reliable in the end i still need to check the changes manuallyis there some clever way of organizing unit tests that would still allow me to locate tests for a specific code quickly and at the same time lend itself more towards refactoringalternatively is there some uh perhaps visual studio extension that would allow me to somehow say that hey these tests are for that method so when name of the method changes please be so kind and change the tests as well to be honest i am seriously considering to write something like that myself,['c#'] +321064,ajax error handling in cakephp i want to do something very similar to this but in the cakephp world for ajax requests at the moment i am doing thisthisautorender falsethisresponsestatuscode500it is based off of this however this solution does not allow me to include a custom message like in the rails example so that way in my clients side error handler i can thisplay the message included in the 500 error response how would i implement the same functionality in cakephp like the ruby on rails example,['php'] +321068,what are the limits of compiling dart to javascript i know that dart is still in technical preview dart can also be compiled to javascriptbut what are the limits of compiling dart to javascript dart has to have some specific features or concepts within the language that can not just be translated to javascript codethe reason is that a friend asked me if dart can compile everything possible to javascript or that eg 5 of the languageelements you know the really cool improved stuff will not be compileable,['javascript'] +321089,how to setup remote debugging on a machine without visual studio is there a way to setup remote debugging msvscomexe on a machine that does dot have visual studio installedi would like to attach to the service running on the vm so i can debug an issue in the code i have done this before but both machines have had vs installedthe dev box is running visual studio 2010widnows 7 the vm is running windows 7 without visual studio,"['c#', '.net']" +321115,programming to an interface avoiding the later cast so as i understand one should always program to an interface as inlistinteger list new linkedlistintegerso later in my program i havepublic listinteger getintegers return listpublic void processintegers i need an arraylist here arraylistinteger list arraylistinteger getintegers can i do this better without a castcan i follow a better pattern here or somehow do something to avoid the cast casting seems very ugly in this scenariothanks,['java'] +321156,mysql update query with sub query can anyone see what is wrong with the below querywhen i run it i get1064 you have an error in your sql syntax check the manual that corresponds to your mysql server version for the right syntax to use near a where acompetitionid competitioncompetitionid at line 8update competitionset competitionnumberofteams select count as numberofteamsfrom pickspointswhere usercompetitionid is not nullgroup by competitionid awhere acompetitionid competitioncompetitionid,"['mysql', 'sql']" +321182,textalign justify inlineblock elements properly a few other questions have already addressed how best to apply textalign justify to get inlineblock elements to spread out evenlya for example how do i really justify a horizontal menu in htmlcsshowever the 100 width element that clears the line of inlineblock elements is given its own line by the browser i cannot figure out how to get rid of that empty vertical space without using lineheight 0 on the parent elementfor an example of the problem see this fiddlefor my solution that uses lineheight 0 see this fiddlethe solution i am using requires that a new lineheight be applied to the child elements but any previously set lineheight is lost is anyone aware of a better solution i want to avoid tables so that the elements can wrap when necessary and also flexbox because the browser support is not there yet i also want to avoid floats because the number of elements being spaced out will be arbitrary,['css'] +321221,how to take the screenshot of part of google maps use javascript on my page there is a container which use google maps api to thisplay a map there is a button below it user can drag the map to a position then click the button i would like to take the screenshot of the map thisplayed in the container now and show it in a canvas is it possible to do this with pure javascriptjust need to support chrome,['javascript'] +321223,multichoicemode before api 11 i implement the actionmode in my android app with actionbarsherlockwith abs it is possible to build a actionmode before api 11 but the easy way withlistviewsetmultichoicemodelistener new multichoicemodelistener is not for app before api 11has anybody a good way to build a action mode context menu before api 11i want to make a long click on a list item and start the actionmode in which i can click multiple items on a simple click i show a detail site of the list itemi use the registerforcontext method but this make a simple and long clickhas anybody a good tip for meeditthe solution for my question was following on a long item click i active the action mode and save this in a variable in the on item click method i implement a ifelse statement withif actionmode null open new activity or update second fragment showdetails itemposition else update ui or close cab if no item selected showcab itemposition the method showcab position update the selecteditem count highlight item background and so on,['android'] +321231,systemcurrentimeinmillis vs systemnanotime i know that systemnanotime is now the preferred method for measuring time over systemcurrenttimeinmillis the first obvious reason is nanotime gives more precise timing and the other reason i read that the latter is affected by adjustments to the systemas realtime clock what does getting affected by systems realtime clock mean,['java'] +321232,undefined reference to cryptoppalignedallocateunsigned int i am using crypto in c linuxhere is my simple codeinclude iostreaminclude fstreaminclude stringhinclude cryptocryptlibhinclude cryptomodeshinclude cryptofiltershinclude cryptoaeshinclude cryptoosrnghinclude cryptostrciphrhusing namespace stdusing namespace cryptoppifstreampos type sizechar memblockint lengthchar ivaesblocksizechar keysaesmax keylengthvoid encriptctrbyte outbyte const byte inbyte const byte key const byte ivvoid encriptctrbyte outbyte const byte inbyte const byte key const byte iv size t inbyte len strlenconst char inbyte ctr modeaesencryption ctr encriptionkey strlenconst charkey iv ctr encriptionprocessdataoutbyte inbyte inbyte lenint main ifstream file fileopentestaja iosbinary if fileis open fileseekg 0 iosend length filetellg memblock new char length fileseekg 0 iosbeg fileread memblock length if file int a a intfilegcount fileclear else fileclose for int i 0 i length i cout hex intmemblocki when i run it some error occured undefined reference to cryptoppalignedallocateunsigned int undefined reference to cryptoppunalignedallocateunsigned int undefined reference to cryptoppaligneddeallocateunsigned int undefined reference to cryptoppunaligneddeallocateunsigned intthen i used commandgcc o test testcpp lusrlibcrypto lcryptobut this error still there undefined reference to cryptoppalignedallocateunsigned intundefined reference to cryptoppunalignedallocateunsigned intundefined reference to cryptoppaligneddeallocateunsigned intundefined reference to cryptoppunaligneddeallocateunsigned inthow can i fix this erroris there something wrong with my codei am installing crypto using synaptic package manager for this packagelibcryptoutilslibcrypto8libcrypto8dbglibcryptodevlibcryptodocand libcryptoa and libcryptoso can be found in usrlibthanks in advance,['c++'] +321256,parsing numbers safely and localesensitively javas numberformat is 1 non threadsafe which can be worked around with a threadlocal 2 inconvenient to use correctly for the simplest use case when i know whether the string should contain int long or double and want an api likeint parseintstring str locale locale throws parseexception int parseintstring str int defaultvalue locale localelong parselongstring str locale locale throws parseexceptionlong parselongstring str long defaultvalue locale localedouble parsedoublestring str locale locale throws parseexceptiondouble parsedoublestring str double defaultvalue locale localewhere the exception is thrown when the string is not completely parsed obviously such a wrapper is easy to write but i could not find one in guava or apache commons lang did i just miss it or is there another moreorless standard solution for this,['java'] +321263,ios equivalent to android fragmentslayouts in android you can use fragments to develop only one app targeted to phones and tables so you can have different ui you can even use only layouts and have some condition on the code to run tablet or phone logici need to develop an app for iphone and ipad and i wonder if there is something similar for implementing different uis and slighty different behavior in my case the iphone app would use tabs at the bottom of the screen but the ipad one should use the menu on the left side,"['iphone', 'ios']" +321290,writing backwards compatible android code i am writing an app that uses some functions and classes only available in the latest api level 16 but i want it to run with no errors on devices with api level 15let us use a couple of examples a new class androidwidgetadvanceable and a newrenamed method viewsetbackgroundi can do something like thisadvanceable myadvanceable if androidosbuildversionsdk int 16 myviewsetbackground myadvanceableadvanceelse myviewsetbackgrounddrawable the old function name do not bother advancing advanceablesand if i set a minsdk of 15 but a build target of 16 ie in project propertiesandroid it will actually compile with no errors at least some of the time eclipse is a bit stochastic about the errors and will sometimes say setbackground is only available in api level 16 or similar but if i just clean the project those errors magically go awayso my question is am i allowed to do this would not the code crash if i run it on an api level 15 device will it only crash if it actually gets to the 16 code why does not eclipse stop me from building itedit 1thanks for the answers i guess the question should really be why would not lint warn me about using new apisi have this in my manifest and am using api level 16 functions but it still does not warn meusessdk androidminsdkversion15 androidtargetsdkversion16also i am still not sure about when entire classes are new to an api level such as advanceable specifically if i use them as member variablesedit 2the answer turned out to be eclipse is buggy as hell but nicos answer was also very helpful,['android'] +321295,application hangs using plinq asparallel no problems with linq i am new to linq and plinq and i am building a project to test themstubclass stub private boolean mytf public stub random generator new random if generatornextdouble 05 mytf false else mytf true public boolean tf get return mytf stubcollectionclass stubcollection ienumerable stub stubs public stubcollectionint n stubs new stubn for int i 0 i n i stubsi new stub ienumerator ienumerablegetenumerator return new stubiteratorthis public class stubiterator ienumerator private stubcollection sc private int index 1 public stubiteratorstubcollection sc sc sc public bool movenext index if index scstubslength return true else index 1 return false public object current get if index 1 throw new invalidoperationexception return scstubsindex public void reset index 1 then i have some methods to iterate the stubcollection and count how many stubs have the boolean set to trueforeachstopwatch sw new stopwatchint32 and 0swstartforeach stub s in sc if stf nswstopmessageboxshown ntostring timer swelapsedmillisecondstostringit workslinqstopwatch sw new stopwatchint32 and 0swstartvar truestubs from stub s in sc where stf select sn truestubscountswstopmessageboxshown ntostring timer swelapsedmillisecondstostringit works little slower than foreachplinqstopwatch sw new stopwatchint32 and 0swstartvar truestubs from stub s in scasparallel where stf select sn truestubscountswstopmessageboxshown ntostring timer swelapsedmillisecondstostring100 cpu no resultwhy the only difference is the asparallel,['c#'] +321300,add a library to silex i know this question has already been asked but it seems that autoloading process changed a little bit with composeri just want to add a class library to my silex projectso i made this filevendorlibpicturephpphpnamespace mynamespaceclass picture function testage echo hiha aa marche exit in vendorcomposerautoload namespacesphp i added this line to the big arraymynamespace vendordir liband in the main file i addeduse mynamespacepicture as pictureand called it like thatappregisternew picturewhich gives me this errorfatal error class mynamespacepicture not foundi just do not know how to add a class that i can use from any controller easily without command line i do not use composer i downloaded silex preconfigured any idea,['php'] +321327,uiwebview stringbyevaluatingjavascriptfromstring hangs on ios5051 when called using gcd i have the following code in viewdidload which works properly on ios 43 but it hangs on ios 551 on ios 551 the alert dialog is shown but can not be thismissed the ui thread freezes the ok button just can not be clickedthispatch asyncthispatch get global queuethispatch queue priority default 0 thispatch syncthispatch get main queue selfwebview stringbyevaluatingjavascriptfromstringalerthello world is this a bug,"['ios', 'objective-c']" +321344,css transparency gradient on an image i would like my background image to go from 100 opacity to 0 opacity i could choose to use another image asset where i use an image editor to make the image fade opacity however i want to use as little assets as possible can this be done with css i know i could make several divs in which i change the opacity on each one however this would require a lot of divs to make it look goodthis is what my code currently looks like with the solution i do not want to usediv classcontentfadeaway idcfa1divdiv classcontentfadeaway idcfa2divdiv classcontentfadeaway idcfa3divdiv classcontentfadeaway idcfa4divdiv classcontentfadeaway idcfa5divdiv classcontentfadeaway idcfa6divdiv classcontentfadeaway idcfa7divdiv classcontentfadeaway idcfa8divdiv classcontentfadeaway idcfa9divdiv classcontentfadeaway idcfa10divand the csscontentfadeaway thisplay block position fixed top 160px padding 0px width 100 height 5px background urlassetsshapeimage 3 intpng fixed backgroundsizecover zindex 1cfa1 top 160px opacity 1 cfa2 top 165px opacity 9 cfa3 top 170px opacity 8 cfa4 top 175px opacity 7 cfa5 top 180px opacity 6 cfa6 top 185px opacity 5 cfa7 top 190px opacity 4 cfa8 top 195px opacity 3 cfa9 top 200px opacity 2 cfa10 top 205px opacity 1 for those that do not understand what that code is doing it is here i have a background image and i want the content to fade away when it scrolls up so i would have the same image with an opacity from 1 to 0 to give that effect if the background was a solid color i could just use a rgba gradient but its an image,['css'] +321433,uniquely identifying an ios user i would like to create a user account on the server for new users of an app but i would also like to not ask the user to type in anything ideally i would like this to be automatic like with game centerbut i am wondering if it is possible is there anything i can use to uniquely identify the user it is highly unlikely that i can find out the users apple id also the device id uniquely identifies the device not the user so it would be useless if the user has more devicesis there anything else i can useabout privacy i do not want to find out anything behind the users back i have absolutely no problem with asking the user for access to their information and if there is an api that grants me this information it would be great if the api asks this itself as steve jobs himself said this is what privacy is all about forcing apps to ask the user for permission before doing anything with their private data,['ios'] +321435,omniauthfacebook keeps reporting invalid credentials i am trying to implement omniauthfacebook as described in railscast 360 and have run into quite a roadblock when i click on the signin link i get the desired popup asking me to input my facebook credentials but when i submit i get an omniauthstrategiesoauth2callbackerror error in the apache logs this is printed facebook authentication failure invalid credentials omniauthstrategiesoauth2callbackerror omniauthstrategiesoauth2callbackerrorhere is the relevant codeomniauthrbomniauthconfiglogger railsloggerrailsapplicationconfigmiddlewareuse omniauthbuilder do provider facebook envfacebook app id envfacebook secretendsessions controllerrbclass sessionscontroller applicationcontroller def create user userfrom omniauthenvomniauthauth sessionuser id userid redirect to root url end def destroy sessionuser id nil redirect to root url endendapplicationhtmlerbdiv idfbrootdivscript windowfbasyncinit function fbinit appid my app id app id status true check login status cookie true enable cookies to allow the server to access the session sign inclickfunctione epreventdefault return fbloginfunctionresponse if responseauthresponse return windowlocation authfacebookcallback return sign outclickfunctione fbgetloginstatusfunctionresponse if responseauthresponse return fblogout return true scriptam i missing something simple i have been searching for a solution for the last few days,['ruby-on-rails'] +321460,phantomjs ensuring that the response object stays alive in serverlisten i am using serverlisten from phantomjs i realize that it is largely experimental and that it should not be used in production i am using it for a simple screenshotserver that accepts generates screenshots for a url it is a toy project that i am using to play around with phantomjs i have noticed an issue with longrunning requests in particular where the response object is unavailable here are the relevant snippets from my codevar service serverlisten8080 function request response responsestatuscode 200 if loglevel levelverbose logrequest else consolelogincoming request with querystring requesturl var params parsequerystringrequesturl if paramsscreenshotoptionsaction actionscreenshot getscreenshotparams function screenshot responseheaderssuccess screenshotsuccess here is where i get the error that responseheaders is unavailable execution pretty much stops at that point for that particular request responseheadersmessage screenshotmessage if screenshotsuccess responsewritescreenshotbase64 else responsewritehtmlbodythere were errorsbr br responsewritescreenshotmessagereplaceng br responsewritebodyhtml responseclose else responsewritehtmlbodyh1welcome to the screenshot serverh1bodyhtml responseclose getscreenshot is an asynchronous method that uses the webpageopen function to open a webpage this function is also asynchronous so what seems to be happening is that when the callback that is passed in as an argument to getscreenshot is finally called it appears that the response object has already been deleted i basically end up with the following error from phantomjserror cannot access member headers of deleted qobjecti believe this is because the request times out and so the connection is closed the documentation mentions calling responsewrite at least once to ensure that the connection stays open i tried calling responsewrite at the beginning of serverlisten and i even tried a pretty hacky solution where i used setinterval to perform a responsewrite every 500 milliseconds i even lowered it down to as little as 50 i also made sure to clear the interval once i was done however i still seem to get this issueis this something that i am just going to have to deal with until they make the webserver module more robust or is there a way around it,['javascript'] +321477,partial render in htmljavascript i try to clarify what i want to do i have an some html files and each one of them i want to partially render another html file for example headerhtml and footerhtml in order to observe dry concepthtml files should look like thisrender headerhtmldiv contentdivrender footerhtmlhow can i do that,"['javascript', 'html']" +321490,is stdstoi actually safe to use i had a lovely conversation with someone about the downfalls of stdstoi to put it bluntly it uses stdstrtol internally and throws if that reports an error according to them though stdstrtol should not report an error for an input of abcxyz causing stoi not to throw stdinvalid argumentfirst of all here are two programs tested on gcc about the behaviours of these casesstrtolstoiboth of them show success on 123 and failure on abc i looked in the standard to pull more infoa 215throws invalid argument if strtol strtoul strtoll or strtoull reports that no conversion could be performed throws out of range if the converted value is outside the range of representable values for the return typethat sums up the behaviour of relying on strtol now what about strtol i found this in the c11 drafta72214 if the subject sequence is empty or does not have the expected form no conversion is performed the value of nptr is stored in the object pointed to by endptr provided that endptr is not a null pointergiven the situation of passing in abc the c standard dictates that nptr which points to the beginning of the string would be stored in endptr the pointer passed in this seems consistent with the test also 0 should be returned as stated by thisa72214 if no conversion could be performed zero is returnedthe previous reference said that no conversion would be performed so it must return 0 these conditions now comply with the c11 standard for stoi throwing stdinvalid argumentthe result of this matters to me because i do not want to go around recommending stoi as a better alternative to other methods of string to int conversion or using it myself as if it worked the way youd expect if it does not catch text as an invalid conversionso after all of this did i go wrong somewhere it seems to me that i have good proof of this exception being thrown is my proof valid or is stdstoi not guaranteed to throw that exception when given abc,['c++'] +321522,jqueryjshtml5 change page content when keyboard is visible on mobile devices possible duplicateipad web app detect virtual keyboard using javascript in safari i am building a mobile version for a website and i am interested if i can create using jqueryjshtml5 or any other technology the same split screen effect that can be made on mobile apps when virtual keyboard is visiblefor example if a user enters my webpage and clicks on an input text field the virtual keyboard is showed and the browser automatically zooms to the area where the input text field iswhat i want is to be able to change my page content the moment the virtual keyboard is visible based on the new resolution screen height keyboard height by moving the input text field on top of the screen followed by some tips depending on what the user enters in the text fieldhere are some sketches to see what i am talking aboutthis is the page view without keyboard results based on the searchpage with portrait keyboard the logo thisappears the text input moves to top and a max 4 items are showedpage with landscape keyboard the logo thisappears thext input moves to top and is enlarged only 2 items are showedis the keyboard is hidden the page should go to faze 1hope this helps,"['javascript', 'jquery']" +321542,synchronized vs reentrantlock on performance i have been through a set of few surprises when it comes to queue implementation for a multithreading system here isthe scenario1 producer 1 consumer a producer puts an integer into a queue a consumer simply removes it from the queuethe underlying data structure of the queue treeset which i never thought i will use linkedlist linkedblockingqueuewith indefinite sizethe code of treeset as a queuewhile i 20 synchronized objqueue if objqueuesize 0 try objqueuewait catch interruptedexception e todo autogenerated catch block eprintstacktrace integer x objqueuefirst if x null objqueueremovex i edit while i 20 synchronized objqueue objqueueaddi i objqueuenotify for linkedblockingqueue while i 20 try objqueueputi i catch interruptedexception e todo autogenerated catch block threadcurrentthreadinterrupt while i 20 try objqueuetake i catch interruptedexception e todo autogenerated catch block threadcurrentthreadinterrupt for linkedlist similar code with synchronizedthe questions 1 when i measured the performance via visual vm i observed that the for the producer code treeset performs better than linkedblockingqueue and linkedlist even though it takes olog n time the creation of objects in linked structures is a significant overhead why is the theory quite different to the practice why do we prefer linked array structures over tree structures in queue implementations 2 the synchronized comes out as a clear winner vs the rentrantlock because treeset performed better than linkedlist which performed better than linkedblockingqueue i wish i could attach the visual vm results it is not in votes with the article the operations are performed ondell vostro 1015 core 2 duo 210 2gb ram with 32 bit operating system and with jvm java hotspottm client vm 201b02 mixed modejava version 160 26 vendor sun microsystems inc,['java'] +321562,search text contains with queryover i am trying to do this var list sessionqueryoverperson wherex xlastnamecontainssearchtext listpersonbut i get this error unrecognised method call systemstringboolean containssystemstringdo you have an idea update public class person public virtual string firstname get set public virtual string lastname get set,['c#'] +321630,is there a free service to get a certificate to sign java webstart jars i am wanting to find a free service to sign a jar which is part of a java web start appi can sign it myself with the keytool and jarsigner but the publisher is untrusted and people are still advised not to run the application which kind of defeats the pointanyway i have read about free email signing certificate and how it can be done but have not found an up to date guidedoes anybody know of a service to help mei am simply trying to get a signed and trusted certificate for the java web start application such that java doesnt issue an advisor saying dont run the application because we cannot trust the publisher,['java'] +321644,meaning after variable type possible duplicatewhat are the differences between pointer variable and reference variable in cwhats the meaning of and when applied to variable names trying to understand meaning of in this situationvoid afint g g coutgif you call this function and pass variable name it will act the same like normal voidint g i know when you write g that means you are passing address of variable g but what does it means in this sample,['c++'] +321677,autosave ignored on has many relation what am i missing i have a pair of classesclass collection activerecordbase has many items autosave trueendclass item activerecordbase belongs to collectionendfrom the docswhen autosave is true all children is saved no matter whether they are new recordsbut when i update an item and save its parent collection the items upated attributes do not get saved c collectionfirst collection id 1 name collection created at 20120723 010 updated at 20120723 010 i citemsfirst item id 1 collection id 1 name item1 created at 20120723 025 updated at 20120723 025 iname new name new name csave true collectionfirstitems item id 1 collection id 1 name item1 created at 20120723 025 updated at 20120723 025so what am i missingi am using rails 325 and ruby 192so i have done some digging about in the source of activerecord we can get hold of cs autosave assocations cclassreflect on all autosave associations activerecordreflectionassociationreflection0x007fece57b3bd8 macrohas many nameitems optionsautosavetrue extend active recordcollectionid integer name string created at datetime updated at datetime plural nameitems collectiontrue class nameitem klassitemid integer collection id integer name string created at datetime updated at datetime foreign keycollection id active record primary keyid typenili think this illustrates that the association has been set up for autosavingwe can then get the instance of the association corresponding to c a csend association instance get items activerecordassociationshasmanyassociation0x007fece738e920 targetitem id 1 collection id 1 name item1 created at 20120723 025 updated at 20120723 025 reflectionactiverecordreflectionassociationreflection0x007fece57b3bd8 macrohas many nameitems optionsautosavetrue extend active recordcollectionid integer name string created at datetime updated at datetime plural nameitems collectiontrue class nameitem klassitemid integer collection id integer name string created at datetime updated at datetime foreign keycollection id active record primary keyid typenil ownercollection id 1 name collection created at 20120723 010 updated at 20120723 010 updatedfalse loadedtrue association scopeitem id 1 collection id 1 name item1 created at 20120723 025 updated at 20120723 025 proxyitem id 1 collection id 1 name item1 created at 20120723 025 updated at 20120723 025 stale statenil we can then find the actual objects that are associated via this association atarget item id 1 collection id 1 name item1 created at 20120723 025 updated at 20120723 025the object found here does not have update that i would made earlier,['ruby-on-rails'] +321773,exporting data from php to excel i need to export data from php data retrieved from mysql database to excel i am using zend framework i need to do some changes to my data before exporting to excel actually what i really need is to generate a monthly cash book i have read a lot of documents but ended up in a mess i really cannot understand how i should begin do i really need pear do i need to download any class libraryis not there a simple way to do thisthanks in advance,['php'] +321801,will apps that use telprompt be rejected in order to return to app after call i use telprompt instead of tel codes like thisuiapplication sharedapplication openurlnsurl urlwithstringtelprompt10086somebody says that it will be rejected by apple because telpromt is not the public url scheme but i did not find a certain answer yes or no can anybody help me,['ios'] +321806,ef code first migrations migratedatabasetolatestversion without nuget i need help to clarify how ef code first migrations works on production machinei have some entity classes and dbcontextderived class to access entities now i want to perform these several thingswhen my application starts it must create database if database does not existsthen database schema must be adjusted to the modelif database was created just now i want to create some indexesalso if database was created just now it must be seeded by some initial dataall of these things must be performed automatically without any nuget commands or external toolsi have read some articles about migrations but they are focused mostly on nuget usage or pure automatic database updates at runtime via migratedatabasetolatestversion i know about dbmigration class but i cannot understand how to glue together migratedatabasetolatestversion strategy and dbmigrationupdatein fact i cannot use nuget in the project and i need possibility to make a migration by hand,['c#'] +321827,toast not showing up in uncaughtexceptionhandler i am using this code to handle any uncaught exceptions which might cause my application to crashpublic class exceptionhandler implements javalangthreaduncaughtexceptionhandler private final context mycontext public exceptionhandlercontext context mycontext context public void uncaughtexceptionthread thread throwable exception toastmaketextmycontext the application has crashed and a report is sent to the admin toastlength shortshow stringwriter stacktrace new stringwriter exceptionprintstacktracenew printwriterstacktrace systemerrprintlnstacktrace you can use logcat too intent intent new intentmycontext crashactivityclass mycontextstartactivityintent processkillprocessprocessmypid systemexit10 when i run it with a known but uncaught exceptionjust to test activity crashactivity is called but the toast which must come before it is not showing upactually i wanted to show only toast and then call mycontextfinish instead of going to the crashactivity but that toast in not visiblewhere am i wrong,['android'] +321839,how to measure file read speed without caching my java program spends most time by reading some files and i want to optimize it eg by using concurrency prefetching memory mapped files or whateveroptimizing without benchmarking is a nonsense so i benchmark however during the benchmark the whole file content gets cached in ram unlike in the real run thus the runtimes of the benchmark are much smaller and most probably unrelated to the realityi would need to somehow tell the os linux not to cache the file content or better to wipe out the cache before each benchmark run or maybe consume most of the available ram 32 gb so that only a tiny fraction of the file content fits in how to do iti am using caliper for benchmarking but in this case i do not think its necessary it is by no means a microbenchmark and i am not sure it is a good idea,['java'] +321858,convert mysql script to h2 i have an init script for my mysql database but for test purposes i want to use a h2 database anyone knows how to convert the file or at least has a list of the syntax differences thanks,"['mysql', 'sql']" +321865,how to thisable status bar or notification bar but not thisable title bar in android i want to thisable status bar or notification bar in android i use androidthemeandroidstylethemenotitlebarfullscreen for thisable it but it makes my title bar thisable too how can i only thisable status bar,['android'] +321889,under which circumstances do equal strings share the same reference i have searched the web and stack overflow questions but been unable to find an answer to this question the observation that i have made is that in python 273 if you assign two variables the same single character string eg a a b a c d then the variables will share the same reference a is btrue c is dtruethis is also true for some longer strings a abc b abc a is btrue is true 1 is 1truehowever there are a lot of cases where the reference is unexpectantly not shared a a c b a c a is bfalse c d c is dfalse 2 is 2falsecan someone please explain the reason for thisi suspect there might be simplificationssubstitutions made by the interpreter andor some caching mechanism that makes use of the fact that python strings are immutable to optimize in some special cases but what do i know i tried making deep copies of strings using the str constructor and the copydeepcopy function but the strings still inconsistently share referencesthe reason i am having problems with this is because i check for inequality of references to strings in some unit tests i am writing for clone methods of newstyle python classes,['python'] +321914,how do i use jcifs with apache vfs to access an smb url i am trying to access a folder on my local computer using an smb urlmy project is using the jars commonsvfs220jar and jcifs1317jar and all the other required jarsthe code in it is entirety ispublic static void mainstring args throws filesystemexception jcifsconfigregistersmburlhandler staticuserauthenticator auth new staticuserauthenticatordomainuserpassword filesystemoptions opts new filesystemoptions defaultfilesystemconfigbuildergetinstancesetuserauthenticatoropts auth filesystemmanager fs vfsgetmanager fileobject smbfile fsresolvefilesmb10022timeout systemoutprintlnsmbfileexists smbfilegetcontentgetlastmodifiedtimei am receiving the exceptionexception in thread main orgapachecommonsvfs2filesystemexception could not determine the type of file smb10022timeout at orgapachecommonsvfs2providerabstractfileobjectgettypeabstractfileobjectjava505 at orgapachecommonsvfs2providerabstractfileobjectexistsabstractfileobjectjava477 at comnewswaytestsvfstestmainvfstestjava23 caused by jcifssmbsmbauthexception logon failure account currently thisabled at jcifssmbsmbtransportcheckstatussmbtransportjava546 at jcifssmbsmbtransportsendsmbtransportjava663 at jcifssmbsmbsessionsessionsetupsmbsessionjava390 at jcifssmbsmbsessionsendsmbsessionjava218 at jcifssmbsmbtreetreeconnectsmbtreejava176 at jcifssmbsmbfiledoconnectsmbfilejava911 at jcifssmbsmbfileconnectsmbfilejava954 at jcifssmbsmbfileconnect0smbfilejava880 at jcifssmbsmbfileopen0smbfilejava972 at jcifssmbsmbfileopensmbfilejava1006 at jcifssmbsmbfileinputstreamsmbfileinputstreamjava73 at jcifssmbsmbfileinputstreamsmbfileinputstreamjava65 at jcifssmbsmbfilegetinputstreamsmbfilejava2844 at orgapachecommonsvfs2providerurlurlfileobjectdogettypeurlfileobjectjava89 at orgapachecommonsvfs2providerabstractfileobjectgettypeabstractfileobjectjava496from which i understand that the relevant part is logon failure account currently thisabledthis is despite the fact that my userpassworddomain are fine and i am doing exactly what is defined in the vfs documentation pagewhat am i missing,['java'] +321956,remove all files folders and their subfolders with php i need a script which can remove a whole directory with all their subfolders files and etc i tried with this function which i found in internet before few months ago but it not work completely function deletefiledir ifsubstrdir strlendir1 1 dir ifhandle opendirdir whileobj readdirhandle ifobj obj ifis dirdirobj ifdeletefiledirobj echo dirobjbr return false elseifis filedirobj ifunlinkdirobj echo dirobjbr return false closedirhandle ifrmdirdir echo dirbr return false return true return truefor the test i use a unpacked archive of prestashop and i try to delete the folder where archive is unpacked but it does not work homepublic htmlprestashopimgp3homepublic htmlprestashopimgp3homepublic htmlprestashopimgphomepublic htmlprestashopimgthese are the problem folders at the first time i think may is a problem with the chmod of the files but when i test with all files chmod permission 755 after that with 7 the result was the same,['php'] +321990,convert rgba to rgb taking background into consideration possible duplicateconvert rgba color to rgb i am trying to convert a rgba color with a alpha 1 into a solid rgb representation taking into account the background colorusing the algorithm provided at this question i manage to get correct conversion to a solid rgb color but only when alpha 05heres my test codedoctype htmlhtmlheadheadbody script typetextjavascript basic rgba to css property value function tostringobj var type rgb out objred objgreen objblue if objalpha undefined type a out objalpha return type out background color assume this is always rgb var bg red 255 green 51 blue 0 rgba color var rgba red 0 green 102 blue 204 alpha 0 output rgb var rgb red null green null blue null just a cache var alpha while rgbaalpha 1 alpha 1 rgbaalpha rgbred mathroundalpha rgbared 255 1 rgbaalpha bgred 255 255 rgbgreen mathroundalpha rgbagreen 255 1 rgbaalpha bggreen 255 255 rgbblue mathroundalpha rgbablue 255 1 rgbaalpha bgblue 255 255 documentwritediv stylethisplay block width 150px height 100px backgroundcolor tostringbg div stylecolor f width 50px height 50px backgroundcolor tostringrgba smallrgbabr rgbaalpha smalldiv div stylecolor f width 50px height 50px backgroundcolor tostringrgb smallrgbbr rgbaalpha smalldiv div increment alpha rgbaalpha 025 scriptbodyhtmlrunning the above in both chrome and firefox results in successful rgbargb when alpha is 05 any deviation away from 05 results in a mismatch very subtle if the deviation is very small ie it is possible to notice the issue when alpha is 055i have rewritten the logic several times fully expanding the logic into its most basic parts but i have failed to be successful,['javascript'] +322013,data is not being inserted into second table mysqli i am using the code below that uploads a file and inserts data into the image table using mysqliphpsession startusernamexpasswordxdatabasemobile appmysqli new mysqlilocalhost username password database check connection if mysqli connect errno printfconnect failed sn mysqli connect error dieresult 0upload image filemove uploaded file filesfileimagetmp name imagefiles filesfileimagenameresult 1insert into image database tableimagesql insert into image imagefile values if insert mysqliprepareimagesql handle errors with prepare operation heredont pass data directly to bind param store it in a variableinsertbind params imgassign the variableimg imagefiles filesfileimagenameinsertexecuteretrieve imageid from image tablelastid mysqliinsert idinsert into image question database tableimagequestionsql insert into image question imageid sessionid questionid values if insertimagequestion mysqliprepareimagequestionsql handle errors with prepare operation heresessid sessionid sessioninitial count 1 sessionsessioncount insertimagequestionbind params lastid sessid postnumquestioniinsertimagequestionexecuteif any error while inserting data into either of the tablesif inserterrno handle query error hereinsertcloseif insertimagequestionerrno handle query error hereinsertimagequestioncloseso for example if i insert 2 images catpng and dogpng into image database table it will insert it like thisimageid imagefile220 catpng221 dogpngimageid is an auto incrementanyway what i want to do is that when a file is uploaded not only is the data inserted into the table above but i want to also be able to retrieve the imageid that was inserted above and place it in the image question table below so it would be like this imageid sessionid questionid 220 catpng 1 221 dogpng 4the problem is that it is not inserting any data into the second table image question does anyone know why it is not inserting any data there is no errors in the php fileto upload a file the user selects a file for the ajax uploader in the qandatablephp page when the user clicks on upload using ajax it will go onto the imageuploadphp page and does the uploading there so the problem i have is that no errors will appear as they are on seperate pages,"['php', 'mysql']" +322035,jsonstringify avoid typeerror converting circular structure to json i have a big object i want to convert to json and send however it has circular structure i want to toss whatever circular references exist and send whatever can be stringified how do i do thatthanksvar obj a foo b obji want to stringify obj intoafoo,['javascript'] +322056,how to properly import a selfsigned certificate into java keystore that is available to all java applications by default i do want to import a self signed certificate into java so any java application that will try to establish a ssl connection will trust this certificateso far i managed to import it inkeytool import trustcacerts noprompt storepass changeit alias remhost file remhostpemkeytool import trustcacerts noprompt keystore cacerts storepass changeit alias remhost file remhostpemstill when i try to run httpsclientclass i still getjavaxnetsslsslhandshakeexception sunsecurityvalidatorvalidatorexception pkix path building failed sunsecurityprovidercertpathsuncertpathbuilderexception unable to find valid certification path to requested target,['java'] +322059,parse date string in ruby i have a string 20120119 which represents a date in the format ymmddi want to parse this string into a ruby object that represents a date so that i can do some basic date calculation such as diff against todays datei am using version 186 requirement,['ruby'] +322098,nested case statements in mysql my first time working with case logic in sql statements everything works if i remove the case statements so the sql is valid without iti need to calculate the total item price based on a couple of thingsif sales price is active and option upcharge has a value the total is qty sales price option upchargeif sales price is inactive and option upcharge has a value the total is qty price option upchargeif sales price is active and option upcharge has no value the total is qty sales priceif sales price is inactive and option upcharge has no value the total is qty priceif no option was added the value for tblproduct optionsoption upcharge is null in the outputthanks for the helpbretthere is my sql select tblshopping cartsession id tblshopping cartproduct id tblshopping cartproduct qty tblshopping cartproduct option tblproductsproduct title tblproductsproduct price tblproductsproduct sale price status tblproductsproduct sale price tblproduct optionsoption text tblproduct optionsoption upchargecasewhen tblproductsproduct sale price status y case when tblproduct optionsoption upcharge is not null then tblshopping cartproduct qty tblproductsproduct sale price tblproduct optionsoption upcharge else tblshopping cartproduct qty tblproductsproduct sale price endelse case when tblproduct optionsoption upchage is not null then tblshopping cartproduct qty tblproductsproduct price tblproduct optionsoption upcharge else tblshopping cartproduct qty tblproductsproduct price endend as product totalfrom tblshopping cartinner join tblproducts on tblshopping cartproduct id tblproductsproduct idleft join tblproduct options on tblshopping cartproduct option tblproduct optionsoption product idorder by tblshopping cartproduct qty ascit fails with with messagecase when tblproduct optionsoption upcharge is not null then tblshopping at line 4,['mysql'] +322110,php sorting issue arsort vs asort array reverse i was recently working on one of the project euler problem sets and came across this strange issue i have solved the problem correctly with the first solution but i do not know why the other version does not work as expectedhere is the code that worksasortcard count sort numericcard count array reversecard count trueand here is the code that does notarsortcard count sort numericthis is the only line i change and it makes a huge difference in the end result any ideas whats up with this,['php'] +322140,how to open existing project in eclipse i kind of feel stupid but i just cannot get it to worki have an existing android project copied from my other pc in the foldercprojectstrunkandroidemergencyi created that project on the other pc copied it to my new pc and the other pc is given awaynow i want to open the project in eclipse so i think i tried everything but i cannot seem to get it to worki looked for something like open project but did not find itthen i tried import but that wouldnt let me import it because it was the same workspace i use the same filelocations and workspace location as on the other pcthen i tried creating a new workspace and import it there then it complained about have no project that i first had to create one so i did create a dummy one in the new workspace imported the project and it copied everything to the new workspace and placed it below the dummy projecti am so stuck can you help mebtw this is the eclipse i am usingeclipse sdkversion 420build id i201206081400,['android'] +322150,about list sorting and delegates lambda expressions func stuff listbool test new listbooltestsortnew funcbool bool intb1 b2 1what am i missingerror 2 argument 1 cannot convert from systemfunc to systemcollectionsgenericicomparererror 1 the best overloaded method match for systemcollectionsgenericlistsortsystemcollectionsgenericicomparer has some invalid argumentswhen i haveprivate int funcbool b1 bool b2 return 1private void something listbool test new listbool testsortfuncit works fine are they not the same thing,['c#'] +322158,regex match keywords that are not in quotes how will i be able to look for kewords that are not inside a stringfor example if i have the texthello this text is an examplebla bla bla this text is inside a stringrandom string more text bla bla bla fooi will like to be able to match all the words text that are not inside in other i will like to matchnote i do not want to match the text that is highlighted on red because it is inside a stringpossible solutioni been working on it and this is what i have so farsqtextq note that regex uses the if statement as predicate true alternativefalse alternativeso the regex will readfind or text if you find then continue selecting until you find again if you find text then do nothingwhen i run that regex i match the whole string though i am asking this question for purposes of learning i know i can remove all strings then look for what i need,['c#'] +322194,how to determine whether a year is a leap year in python i am trying to make a simple calculator to determine whether or not a certain year is a leap year by definition a leap year is divisible by four but not by one hundred unless it is divisible by four hundredhere is my codedef leapyrn if n40 and n10 if n40 print n is a leap year elif n40 print n is not a leap yearprint leapyr1900when i try this inside the python idle the module returns none i am pretty sure that i should get 1900 is a leap year,['python'] +322195,are arrays faster than arraylist my intuition says arrays are faster than arraylist because arraylists are implemented using arrays that resize as it fills uploses elementsi just wanted to confirm if this is true or not implying there is never a reason to use an arraylist if you know the number of elements you want to hold,['java'] +322197,databases character encoding pdfs and xml i am having little trouble with character encodingthe situationa file is uploaded that is converted into xml the character encoding of this file varies however smart quotes entities and various ascii may appear once this file is converted into xml it is stored in a database upon user request the xml may extracted from the database and converted into an array where it is then created into a pdf the problemcharacter encoding right from the beginning character encoding has played a major issue i would like to knowwhat character encoding generally covers the entire spectrum for instance a deg which is unrecognised when parsing the xml or a smart quote a the smart quote will turn into a etc etchow to store xml in a database encryption is a possibility however database encoding is where i am getting lost athow to get the entities smart quotes and other characters which may cause a problem to appear correctly in a database and with a a in front of stuffattempts at a work aroundi have made various functions which attempt to solve my problem converting some characters into another however i assume this is the entirely wrong way of doing it and i should be changing the character encoding converts smart quotes to ascii function convert smart quotesstring string iconvutf8 utf32 string string mb convert encodingstring htmlentities utf32 string str replace65279 string search arraylsquo rsquo ldquo rdquo mdash replace array string str replacesearch replace string return string converts some entities to an iso format example deg a function entity to isostring return html entity decodestring ent quotes ent compat iso88591ultimately my problem resides in the fact that i do not know the encoding of the file that is uploaded i had an idea of a switch that attempts to convert characters into something more database and pdf friendly however much googling has resulted in bitter work arounds or arrays that str replace one thing to another is this really the solutionany advice solutions or fingers pointed in a better direction are all helpful and much appreciated thank you,"['php', 'mysql']" +322245,how to have two jpanels which always take up half the screen each split horizontally as described in the title i have got two jpanels one on top of the other using a borderlayoutimport javaawtimport javaxswingpublic class myform public static void mainstring args jframe myframe new jframesingsong myframesetlocation100100 myframesetsizenew dimension1024800 myframesetlayoutnew borderlayout jpanel jp new jpanel jpsetbackgroundnew color0x00ff00ff jpanel jp2 new jpanelnew borderlayout jp2setbackgroundnew color0x0 jpsetpreferredsizenew dimension100400 jp2setpreferredsizenew dimension100400 jp2setlocation0 512 myframeaddjp2 borderlayoutsouth myframeaddjp borderlayoutnorth they each take up half but how can i go about setting it so that they always take up half the jframe each even when resizedps i normally use better variable names i just whipped up that as an sscce,['java'] +322274,python convert string to byte array say that i have a 4 character string and i want to convert this string into a byte array where each character in the string is translated into its hex equivalent egstr abcdi am trying to get my output to be arrayb 41 42 43 44is there a straightforward way to accomplish this,['python'] +322275,java adding elements to list while iterating over it i want to avoid getting concurrentmodificationexception how would i do it,['java'] +322305,htmlfromhtml line breaks thisappearing i am taking spanned text from an edittext box and converting it to a html tagged string using htmltohtml this works fine i have verified that the string is correct and contains a in the appropriate location however when i got to convert the tagged string back to a spanned text to populate a textview or edittext using htmlfromhtml the or multiple ones if they are present at the end of the first paragraph thisappear this means that if a users entered text with multiple line breaks and wanted to keep that formatting it gets lost i attached a picture to help illustrate this the first edittext is the user input the textview below it is the htmltohtml result of the edittext above it the edittext below it is populated using htmlfromhtml using the string in the textview above it as you can see the line breaks have thisappeared and so have the extra lines furthermore when the spanned text of the second edit text is run through the htmltohtml it now produces a different html tagged stringi would like to be able to take the html tagged string from the first edittext and populate other textviews or edittexts without losing line breaks and formatting any suggestions would be helpfulthanks,"['android', 'html']" +322307,in aspnet how do i add a cors header for only ttf files i have a page with an iframe that shows an external page the external page is configured to download a css file from my serverin the css i added a fontface selectorfontface fontfamily special font src url requesturlgetleftparturipartialauthority fontsspecialfontf this downloads and shows the font fine in chrome but in firefox it downloads the font but refuses to use it doing a little bit of research shows that this problem is a crossorigin policy issue one of the solutions mentioned hereis to enable the cors header however the solution it provided is sitewidexml version10 encodingutf8 configuration systemwebserver httpprotocol customheaders add nameaccesscontrolalloworigin value customheaders httpprotocol systemwebserverconfigurationwhereas i would only like to enable it for only ttf files is there a way to do this either through using a httphandler or some other method,"['c#', 'asp.net']" +322315,ios app behaviour after installing new version from app store i have an ios app installed in iphone from app store now if i have an updated version 11 for the same app at app store and i am getting some sort of informative alert from the older version 10 new version is availableif i click on alertviews ok button it redirects me to the new app link in browser i download my new version thenplease provide answers of following questions will it replace old versionwill it replace sqlite and image folder on the document path both version is having same named sqlite file say abcsqlite10 and same folder name say imagestobecopiedwill it append the sqlite entitie rows with new rows for same entityhow can i install version 10 again from app store is it possible to get it anyhowplease provide your valuable answers on it which can help me out to reach to some solutionthanks,['ios'] +322330,robolectric android testing events i have written a few tests using robolectric and i now i want to do some real test classesone i notice is that i cannot test the events like oncreate onlocationchanged etcwhat is the standard practice for testing the eventsshould i extract the code thats inside the events and place them in a method the event would call the method and also robolectro could call the method of course the method would need to be public rightalso if i wish to test something within my method that is normally a private variable then i would need to add a public getter right so i can check this from robolectricis there a better way to expose data to robolectric thanks in advance,['android'] +322341,i can not find qstring in pyside 110 i want to use qstring and qstringlist but in pyside 110 they are not in modules and not in documentsso what can i do to use themthank younot just qstring and qstringlist i can not find qtablemodel qlistmodel and etc too,['python'] +322368,regex c extract substring i would like to extract a substring between two othersex hometotofile mysymbol eventdator just file othersymbol eventdatand i would like to get mysymbol and othersymboli do not want to use boost or other libs just standard stuffs from c except cerns root lib with tregexp but i do not know how to use it,['c++'] +322423,what does external code in the call stack mean i call a method in visual studio and attempt to debug it by going over the call stacksome of the rows in it are marked external codewhat exactly does this mean methods from a dll have been executedstupid question but need a definitive answer,"['c#', '.net']" +322431,combining dependencies with data providers i have one test method that depends on another method that itself uses a data provider in phpunit dataprovider getfields public function testcandosomestuffparm1 parm2 result my funcparm1 parm2 thisassertnotnullresult return result depends testcandosomestuff public function testcandosomemorestuffresult thisassertnotnullresulti also have a getfields data provider function no need to show that herethe first test that relies on the data provider passes result is not nulli expect that the result of the test will be passed to the dependent test as the result parameter however the testcandosomemorestuff function receives a null parameter and the test failsupdatethis simple test case demonstrates the problemclass mytest extends phpunit framework testcase dataprovider myfunc public function testcandosomestuffvalue thisassertnotnullvalue return value depends testcandosomestuff public function testcandosomemorestuffvalue thisassertnotnullvalue data provider function public function myfunc values array22 return arrayvalues as a workaround for now i have stored the result in a static property between tests,['php'] +322435,why am i getting correct output even though the code is logically incorrect following is the code for reducing a given number to a single digit by adding the digits of the number recursivelyfor example if the input is 845 the output is 8 845 17 17 8 outputinclude stdiohdefine true 1int reducetosingleint numbint main int numb scanfdnumb printforiginal d single digit dn numb reducetosinglenumb return true int reducetosingleint numb int sum 0 digit 0 for digit numb 10 numb 0 numb numb 10 digit numb 10 sum digit if sum 9 reducetosinglesum else return sumin the above code in the if sum 9 block i have not returned the function value i just called the function instead logically this function should give an incorrect value but when i ran the above program in my system i got the correct sum of digits in output i am unable to comprehend the logic behind this behaviour,['c'] +322440,handle tap event by subview of uiscrollview while scrolling i have custom uiscrollview subclass with some content views inside in some of them i have uitapgesturerecogniser all works fine when scroll view is not scrolling but when it scrolling content views does not receive tap action what is the simplest solution to handle tap action by subview while scroll view is scrollingdetailsmyscrollview scrolls horizontally it contains a lot of content views eg mycontentview each mycontentview has width about one third of myscrollview width so there are about 34 visible mycontentview elements at a moment the main behavior of myscrollview is to 1make sure that after scrolling one of mycontentview elements will be at center of screen and 2to scroll to center of mycontentview if user taps on it so the main answer i hope to get is how to properly implement handling of tap action in mycontentview while myscrollview is deceleratingi found some same questions and answers but none of them satisfied me the best was to implement gesturerecognizershouldrecognizesimultaneouslywithgesturerecognizer of uitapgesturerecogniser delegate but in this case i sometimes when i tap make smal drag and release finger so tap is steel recognizablelets called it quasi tap have both tap and scroll events and it leads to bugs for me even if scroll view is not scrolling when i begin tap when user make quasi tap my application tries to scroll to tapped mycontentview element and than immediately handle normal scrolling it seems even more terrible due to some other functionality start to perform after handling tap it must not perform when normal scrollingi need solution where scroll view wait enough to decide it is not tap event and only then make scroll otherwise if tap event had recognized scroll must not happen,"['objective-c', 'ios']" +322461,how to handle screen orientation changes when there is an asyntask running with android 4x i tried to implement the following code to handle screen orientation changesdatabaseupdateservicejavapublic class databaseupdateservice extends activity override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate updatetask task new updatetaskthisgetapplicationcontext iftaskgetstatus asynctaskstatuspending taskexecute override public void onconfigurationchangedconfiguration newconfig superonconfigurationchangednewconfig override public void onpause superonpause override public void onresume superonresume androidmanifestxml activity androidnamedatabaseupdateservice androidconfigchangeskeyboardhiddenorientationthose codes work perfectly with android 3x or lower however it does not work properly for android 4xdo you have any idea what the problem is,['android'] +322466,how can i make tesseract on ios faster i am struggling with tesseract ocr on ios everything works fine but it is really slow2 3 seconds recogintion time for a single line of digitsi am reading from a video streami am using tesseract 301 with a custom training file for my fonthere is what i dosetting up tesseract only to find numbers 09shrink deskew and binarize imageuse getlines to find the line i want the text ofsetrectangle to only recognize the line i wantgetutf8text to get my text this alone takes 23 secondsare there any suggestions to speed up the process,['ios'] +322498,how to draw something with your finger in an android app and save it to the web this question was successfully answered and has become a blog post click hi i am a php developer i want to do a simple thing i want to draw something drawn on a blank page on an android phone with a finger with a largeish emulated pen nib and store the bitmap as a jpeg on a server by http posthere is what i have so far but this is taken from a tutorial that is involved with writing sprites for a game and i cant adapt itpackage commyexampleimport androidappactivityimport androidcontentcontextimport androidgraphicsbitmapimport androidgraphicsbitmapfactoryimport androidgraphicscanvasimport androidosbundleimport androidviewmotioneventimport androidviewsurfaceholderimport androidviewsurfaceviewimport androidviewviewimport androidviewviewontouchlistenerpublic class drawcapture extends activity implements ontouchlistener ourview v bitmap ball float xy override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutdraw capture v new ourviewthis vsetontouchlistenerthis ball bitmapfactorydecoderesourcegetresources rdrawableblueball x y 0 setcontentviewv override protected void onpause superonpause vpause protected void onresume superonresume vresume public class ourview extends surfaceview implements runnable thread t null surfaceholder holder boolean isitok false public ourviewcontext context supercontext holder getholder public void run while isitok true try threadsleep50 catch interruptedexception e eprintstacktrace perform canvas drawing if holdergetsurfaceisvalid continue canvas c holderlockcanvas ondrawc holderunlockcanvasandpostc public void ondrawcanvas c cdrawargb255 210 210 210 cdrawbitmapball x ballgetwidth2 y ballgetheight2 null public void pause isitok false whiletrue try tjoin catchinterruptedexception e eprintstacktrace break t null public void resume isitok true t new threadthis tstart public boolean ontouchview v motionevent me switch megetaction case motioneventaction down x megetx y megety break case motioneventaction up x megetx y megety break case motioneventaction move x megetx y megety break return true and here is the xmlxml version10 encodingutf8surfaceview xmlnsandroid androidlayout widthmatch parent androidlayout heightmatch parent surfaceviewcan someone please help me i feel i am close i use the blueball as a pen nib i just want to save this and possibly i will need to have a button or menu on the xml page to do this i know it is a bit of a beg but there are a lot of people online asking how to draw with your finger and save something to the cloud if people could respond with examples of the code not references i promise i will compile this into a proper tutorial piece of code for the eventual benefit of all including the php server side code that i already am really happy with,['android'] +322507,any type casting done by javac to my understanding if type checking can be done during compilation the type casting will be done during compilation and will not incur any runtime overhead for examplepublic child getchild parent o new child return child ois the type casting done during compilation or during runtimeand is there any general rule to decide if a type casting is done by javac compiler or by the vm,['java'] +322513,why so red intellij seems to think every declarationmethod cannot be foundresolved just reinstalled installed intellij every java file is coming up red i checked the jsdk it is at 16 the maven clean install worked just fine how do i fix these false errors it is very annoying not being navigate around with a click of buttons,['java'] +322539,reuse uiviewcontroller instances when using storyboard i decided to give the use of storyboards a go in my current iphone app i am facing a bit of a problem i really need to reuse my uiviewcontroller instances what do i mean by that well for example i have a table view controller when i tap a cell another view controller is loaded from the storyboard and pushed onto the navigation controller stack this all works well but it takes about half a second to a second each time this view controller is loaded before i was using story boards i simply solved this problem by caching the created instance so the second time you tap a cell the view controller can be immediately shownby caching the created instance i mean something like thisif cachedinstance cachedinstance myviewcontroller newselfnavigationcontroller pushviewcontrollercachedinstancedoes anyone know how to accomplish this using the storyboard thanks in advance,"['objective-c', 'ios']" +322552,setting header for date to lower spamassassin score i have used a testing service verifierport25com to check what was happening when emails were getting sent from my php script for some reason they were ending up in my gmail spam folder even though spf and dkim are enabledit turns out that the spamassassin score was 53 thus above the 50 benchmark below you can see why the biggest problem is that i have a domain with 12 letters in it it seems crazy to me that i should be punished for this but apparently 12 letter domains are popular among spammers as i do not want to have to change my domain it looks like the next best option is to set a header for the date but i am not sure how to do this could someone help with this10 missing headers missing to header00 html message body html included in message05 bayes 05 body bayes spam probability is 1 to 5 score 0034501 dkim valid au message has a valid dkim or dk signature from authors domain01 dkim signed message has a dkim or dk signature not necessarily valid01 dkim valid message has at least one valid dkim or dk signature14 missing date missing date header35 from 12ltrdom from a 12letter domainexisting array headers array from from returnpath sender subject subject,['php'] +322560,sonar picolifecycleexception while running analyzing source code with sonar i am getting picolifecycleexception following is the stacktraceorgpicocontainerpicolifecycleexception picolifecycleexception method public void orgsonarbatchcomponentsembedderphasesstart instance orgsonarbatchcomponentsembedderphases1f4e9be javalangruntimeexception wrapper at orgpicocontainermonitorsnullcomponentmonitorlifecycleinvocationfailednullcomponentmonitorjava77 at orgpicocontainerlifecyclereflectionlifecyclestrategymonitorandthrowreflectionlifecycleexceptionreflectionlifecyclestrategyjava132 at orgpicocontainerlifecyclereflectionlifecyclestrategyinvokemethodreflectionlifecyclestrategyjava115 at orgpicocontainerlifecyclereflectionlifecyclestrategystartreflectionlifecyclestrategyjava89 at orgpicocontainerinjectorsabstractinjectionfactorylifecycleadapterstartabstractinjectionfactoryjava84 at orgpicocontainerbehaviorsabstractbehaviorstartabstractbehaviorjava169 at orgpicocontainerbehaviorsstoredrealcomponentlifecyclestartstoredjava132 at orgpicocontainerbehaviorsstoredstartstoredjava110 at orgpicocontainerdefaultpicocontainerpotentiallystartadapterdefaultpicocontainerjava996 at orgpicocontainerdefaultpicocontainerstartadaptersdefaultpicocontainerjava989 at orgpicocontainerdefaultpicocontainerstartdefaultpicocontainerjava746 at orgsonarbatchmodulestartmodulejava88 at orgsonarbatchsonareclipseruntimeanalysesonareclipseruntimejava44 at orgsonarideeclipsecorejobsanalyseprojectjobrunanalyseprojectjobjava107 at orgeclipsecoreinternaljobsworkerrunworkerjava55caused by javalangruntimeexception wrapper at orgpicocontainerlifecyclereflectionlifecyclestrategymonitorandthrowreflectionlifecycleexceptionreflectionlifecyclestrategyjava130 13 morecaused by orgsonarapiutilssonarexception can not execute checkstyle at orgsonarpluginscheckstylecheckstyleexecutorexecutecheckstyleexecutorjava87 at orgsonarpluginscheckstylecheckstylesensoranalysecheckstylesensorjava43 at orgsonarbatchphasessensorsexecutorexecutesensorsexecutorjava58 at orgsonarbatchcomponentsembedderphasesstartembedderphasesjava64 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokeunknown source at sunreflectdelegatingmethodaccessorimplinvokeunknown source at javalangreflectmethodinvokeunknown source at orgpicocontainerlifecyclereflectionlifecyclestrategyinvokemethodreflectionlifecyclestrategyjava110 12 morecaused by compuppycrawltoolscheckstyleapicheckstyleexception cannot initialize module header property headerfile is missing or invalid in module header at compuppycrawltoolscheckstylecheckersetupchildcheckerjava177 at compuppycrawltoolscheckstyleapiautomaticbeanconfigureautomaticbeanjava207 at orgsonarpluginscheckstylecheckstyleexecutorexecutecheckstyleexecutorjava81 20 morecaused by compuppycrawltoolscheckstyleapicheckstyleexception property headerfile is missing or invalid in module header at compuppycrawltoolscheckstylechecksheaderabstractheadercheckfinishlocalsetupabstractheadercheckjava192 at compuppycrawltoolscheckstyleapiautomaticbeanconfigureautomaticbeanjava203 at compuppycrawltoolscheckstylecheckersetupchildcheckerjava156 22 more,['java'] +322565,django how does view get multiple values from url it is about passing values from url to view in djangourl like thishttpboardsboardpictureboardgirlsi want get both values picture and girls that all belongs to boardstore these values to a list or somethingobviously requestgetgetboard cannot get two valuesdoes anybody get a workaroundthank you in advance,['python'] +322568,how to remove text without removing inner elements from a parent element using jquery imagine that i have something like the following modified from div idfoo first div idbar1 jumps over a lazy dog div second div idbar2 another jumps over a lazy dog div thirddivhow can i remove just only text first second and third from dom without affecting any of the child elements,"['javascript', 'jquery']" +322580,how can a site instantly detect that javascript has been thisabled normally when a page is loaded and the browser has javascript thisabled we use the noscript tag to write something like a warning and tell the client to enable javascript however facebook even after you load the page with js enabled the moment it is thisabled you get a notification how can i do something like thisupdate this mechanism is no longer available in facebook but it was before i was too late in asking this question but if any answer is found i would really appreciate itwhat i have triedi thought about having a segment inside my page which keeps checking if javascript is thisabled if yes show the contents of noscriptto achieve this i created a page checkjshtmldoctype htmlhtmlhead meta httpequivrefresh content0headbody noscript js is thisabled noscriptbodyhtmlthis page will keep on refreshing when js is thisabled js is thisabled will appearto add this page inside my original page i tried the following1 loadi used jquery to loadcheckjshtml inside a div however it seems that load only loads the contents of the body of checkjshtml means the head element and whats inside it will not be loaded inside the div2 iframeafter some searching i found that the only possible way to load a full html page including head is to use an iframeiframe srccheckjshtmliframehowever the meta httpequivrefresh content0 of checkjshtml affects the parent page the original page itself started refreshingif we are able to use this iframe without forcing the original page to refresh then this could be a solution but even if this solution is found i feel its more of a trick rather than a real solutionupdateantony s answer proved that i was wrong about that the iframe refreshes the original page the browser shows that its refreshing but actually its not if this is it then javascript can be avoided the checkjshtml that i provided does the job and even better the noscript will be hidden when js is reenabled still this whole iframe approach is not so user friendly could freeze the browser unless refresh occurs every 10 seconds or so which is not an instant detection,"['javascript', 'html', 'css']" +322609,get positionoffset of element relative to a parent container i am used to working with jquery in my current project however i use zeptojs zepto does not provide a position method like jquery does zepto only comes with offsetany idea how i can retrieve the offset of a container relative to a parent with pure js or with zepto,['javascript'] +322713,what language do i need to write macros in libre office calc i have written a bunch of vba code for various things in excel i am looking at migrating to libreoffice under toolmacrosorganize macros the two choices are libreoffice basic and pythonshould i learn one of those both or something else am i wasting my time altogether any suggestions appreciated,['python'] +322717,android portrait camera reliability i am developing and app targeted sdk 8 with min sdk 7 that uses a camera viewobviously there is this issue of rotating the camera for portrait that has had a fair amount of thiscussion already i currently have the following fix that separates sdk 7 and 8if androidosbuildversionsdk int androidosbuildversion codesfroyo thecamerasetthisplayorientation90 else parameterssetorientation portrait parameterssetrotation90which works on both a 21update1 device and a sgs2 i have running icsmy question is what kind of reliability do these solutions have across devices i have seen a few solutions to the prefroyo situation so im dubious of this solution working for all devices i am also wondering how well setthisplayorientation is respected on different devicesi would be really grateful to hear of others experience with thisso some more info how to set android camera orientation properlythis explains that these methods work some of the time so further question from what point sdk version did setthisplayorientation start working all of the time,['android'] +322749,changing afnetworking baseurl i am using afnetworking with the singleton model suggested in their example sgstockroomhttpclient sharedclient static sgstockroomhttpclient sharedclient nil static thispatch once t oncepredicate thispatch onceoncepredicate nsstring baseurlstring nsuserdefaults standarduserdefaults stringforkeyserver root url preference sharedclient self alloc initwithbaseurlnsurl urlwithstringbaseurlstring return sharedclient idinitwithbaseurlnsurl url self super initwithbaseurlurl if self return nil self registerhttpoperationclassafjsonrequestoperation class self setdefaultheaderaccept valuetexthtmlreturn selfinitialization is done with a baseurl taken from the user defaultsmy problem is that the baseurl property is readonly if the user goes to settings and changes the baseurl user default how can i change it in my clientanother similar case i have with a need to change the baseurl is an api which requires multiple calls and logic to determine to the right baseurl and the base url can still change while the app is running eg user changes networking environment requiring a change from local connection to 3g connection via external proxy serveri see why the baseurl property is readonly there are things like networkreachabilitystatus that run in the background and are tied to that setting this said it seems fairly easy to have a setbaseurl method that stops monitoring changes the value then starts monitoring againi guess my design is not right should i giveup the singleton in this case and recreate the client each time the baseurl should change,['objective-c'] +322756,sencha touch 2 native build not loading after generating the default app withsencha generate app sencha senchai decided to test the app on the ios simulatorcd senchasencha app build nativeit loads the app but gets stuck on the loading iconbelow is the code for the main application appjsextapplication name sencha requires extmessagebox views main icon 57 resourcesiconsiconpng 72 resourcesiconsiconipadpng 114 resourcesicons 144 resourcesiconsicon isiconprecomposed true startupimage 320x460 resourcesstartup320x460jpg 640x920 resourcesstartup640x920png 768x1004 resourcesstartup768x1004png 748x1024 resourcesstartup748x1024png 1536x2008 resourcesstartup1536x2008png 1496x2048 resourcesstartup1496x2048png launch function destroy the apploadingindicator element extflyapploadingindicatordestroy initialize the main view extviewportaddextcreatesenchaviewmain onupdated function extmsgconfirm application update this application has just successfully been updated to the latest version reload now functionbuttonid if buttonid yes windowlocationreload below is the code for the main view mainjsextdefinesenchaviewmain extend exttabpanel requires exttitlebar extvideo config tabbarposition bottom items title welcome iconcls home stylehtmlcontent true scrollable true items docked top xtype titlebar title welcome to sencha touch 2 html youve just generated a new sencha touch 2 project what youre looking at right now is the contents of a target blank hrefappviewmainjsappviewmainjsa edit that file and refresh to change whats rendered here join title get started iconcls action items docked top xtype titlebar title getting started xtype video url f9b698fea38cd408d52a2393240c896c posterurl 640jpg,"['javascript', 'ios']" +322777,thread objects not garbage collected after being finished i noticed that my application is leaking memory this can be seen in ddms and i managed to get a outofmemoryerrori found the source of the leak one of the activities has a thread running in the background this thread is stopped in ondestroy it finishes running as it can be seen in ddmsnow if thread is started the leak occurs activity is not garbage collected after being destroyed because it is referenced by the threadif thread is not started at all everything is okheres simple example demonstrating thispublic class mainactivity extends activity override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main override public boolean oncreateoptionsmenumenu menu getmenuinflaterinflatermenuactivity main menu return true volatile boolean finished false byte memoryeater new byte4 1024 1024 thread thread new threadnew runnable override public void run while finished try threadsleep100 catch interruptedexception e todo autogenerated catch block eprintstacktrace logdgetclassgetname thread finished override protected void ondestroy superondestroy finished true public void startactivityview view startactivitynew intentthis mainactivityclass public void startthreadview view threadstart add one button for starting new activity and one for starting a thread start new activity after going back the memory will be cleaned only if thread has not been startedwhat is the cause of this behaviour,['android'] +322813,mysql select all columns where one column is thistinct i am very sorry if the question seems too basici have surfed entire internet and stackoverflow for a finished solution and did not find anything that i can understand and cannot write it myself so have to ask it herei have a mysql databaseit has a table named postedit has 8 columnsi need to output this resultselect thistinct link from posted where adkey order by day monthbut i need not only the link column but also other columns for this rowlike for every row returned with this query i also need to know its id in the table day and month values etcplease tell me what should i read to make it or how to make itplease keep it as simple as possible as i am not an expert in mysqlediti tried thisselect thistinct linkiddaymonth from posted where adkey order by day monthit does not work it returns too many rows say there are 10 rows with same links but different daymonthid this script will return all 10 and i want only the first one for this link,"['mysql', 'sql']" +322828,similar function swingutilitiesinvokelater in android sometime i feel that using asynctask is quite overkill for the task i am looking for similar function like swingutilitiesinvokelater in android because i just want to execute one line of code no point to create a new class for that,"['java', 'android']" +322864,fast and reliable alternatives to bonecp connection pool i was using bonecp for my java projects but unfortunately i thiscovered that this pool is unable to recover after the database failure i am not the only one with such problem just look at the official forums if you want as i and many others never got answer on bonecp forums it seems that this project is no longer supported and my issue is unlikely to be fixedso i am looking for an alternative actively developed and supported connection pooling library which is able to handle database outages correctly and recover as soon as database is available again,['java'] +322914,access denied for user debiansysmaint i have had problem with mysql i tried to execute thisecho show databases mysql b nbut i goterror 1045 280 access denied for user debiansysmaintlocalhost using password yesbut when i execetcinitdmysql restart i got an oki didgrant all privileges on to debiansysmaintlocalhost identified by password your password with grant option flush privilegeswhere password is from etcmysqldebiancnf but it did not help of course i flushed priv and restarted mysql,['mysql'] +322915,gxt combo box selection arrow is not properly aligned in firefox and safari i am using gxt223s combox box when it is rendering in ie7 there is no problem with the alignment but when it comes to firefox401 have got some selection arrow alignment issues as followsby ran the application is firebug mode came to know that there some default style is applied to this div elementstyle with value paddingleft80px so can any one suggest me why this incompatibility in browsers and how do i override this stylecodeprivate comboboxtestmodel combomodel new comboboxtestmodel combomodelsetfieldlabelwrapalignmentspanstate liststoretestmodel store new liststoretestmodel storeaddgetmodelsnew arraylisttestmodel combomodelsetthisplayfieldtestmodelstate combomodelsetvaluefieldtestmodelstate combomodelsetlabelstylefontweightboldwidth120 combomodelsetwidth100 combomodelsetstorestoreand finally i am adding this one to formpanel as follows mainpaneladdcombomodelthanks in advance,['css'] +323053,setting environment variables in rails 3 devise omniauth i have been trying to figure out how ryan bates in his facebook authentication screencast is setting the following facebook app id and facebook secret environment variablesprovider facebook envfacebook app id envfacebook secretthere are similarish questions around but no answers that i have been able to get to work on rails 321updateas of may 2013 my preferred way to handle env variables is via the figaro gem,['ruby-on-rails'] +323082,why cannot i create an array of a generic type in short this would not compilepublic a void test a temp new ais it because of problems with backward compatibility or is it something fundamental in the language design that prevents it,['java'] +323095,epplus pivot tablescharts i have been using epplus for net for a while now but only for simple data manipulationare there any examples somewhere on how to use it to create pivot tableschartsit seems to support it as i can see pivottable in the intellisense but just unsure on the syntaxi could only find the likes of piebar charts in the samples provided,"['c#', 'asp.net']" +323098,ios delegate naming conventions should will did i am looking into naming conventions for ios controls delegates i am familiar with the should will did pattern for delegate methods i can see this naming convention used extensively by the apple apis my question is are there any delegates supplied by apple that have should will did methods for a single action eg for row selectionshouldselectrowwillselectrowdidselectrowi have not found a delegate that defines all three my feeling is that will methods are often used in place of should ie they can return a value in order to cancel the actionare there any counterexamples,"['objective-c', 'ios']" +323110,why is not serverhttps set to 1 my site has an ssl cert and i am hitting but under the php variables section serverhttps is not being reported i believe this is causing a problem with a drupal site where some urls are being written to the page as https where others are being written as httpwhat determines if serverhttps is setedit this may be the answer to my problem detecting https vs http on server sending back nothing useful could be a load balancer issue,['php'] +323158,how to recursively copy entire directory including parent folder in java i am currently coping folders from one place to another it is working fine out but it is not copying the original folder that all the rest of the files and folders are in over as well this is the code i am usingpublic static void copyfolderfile src file dest throws ioexception if srcisdirectory if directory not exists create it if destexists destmkdir list all the directory contents string files srclist for string file files construct the src and dest file structure file srcfile new filesrc file file destfile new filedestsrcgetname file recursive copy copyfoldersrcfiledestfile else if file then copy it use bytes stream to support all file types inputstream in new fileinputstreamsrc outputstream out new fileoutputstreamdest byte buffer new byte1024 int length copy the file content in bytes while length inreadbuffer 0 outwritebuffer 0 length inclose outclose systemoutprintlnfile copied from src to dest so i have the folder src ctestmytestall foldersi want to copy it to ctestmyfilesbut instead of getting ctestmyfilesmytestall folders im getting ctestmyfilesall folders,['java'] +323188,looking for an elgant way to check if a key exsists in a dictionary possible duplicatehow to check if an nsdictionary or nsmutabledictionary contains a key i can get the an array of the keys strings from the dictionary then loop through it doing a string compare with the key i want to check for and see if that dictionary contains the key i seekbut is there a more elegant want to check if the key exists in the dictionary nsarray keys taglistdict allkeys for nsstring key in keys do string compare etc code,"['iphone', 'objective-c', 'ios']" +323218,issue building cx oracle libclntshso1 not found i am trying to build cx oracle for a python 272 and oracle 11g installation but the built cx oracleso cannot find libclntshso1 so importing cx oracle in python failsmypathcx oracle511buildliblinuxx86 642711g ldd cx oracleso libclntshso1 not found libpthreadso0 lib64libpthreadso0 0x02ae9be290 libcso6 lib64libcso6 0x02ae9be4ab0 lib64ldlinuxx8664so2 0x0389b60i have libclntshso1 in my oracle client installation directoryappsoracleclient11201home1lib ls l libclntshsolibclntshso appsoracleclient11201home1liblibclntshso1libclntshso1and the cx oracle setuppy is picking this lib dir upmypathcx oracle511 python27 setuppy buildappsoracleclient11201home1running buildrunning build extbuilding cx oracle extensiongcc pthread fnostrictaliasing g o2 dndebug g fwrapv o3 wall wstrictprototypes fpic iappsoracleclient11201home1rdbmsdemo iappsoracleclient11201home1rdbmspublic iappsbwebpython272includepython27 c cx oraclec o buildtemplinuxx86 642711gcx oracleo dbuild version511in file included from appsoracleclient11201home1rdbmspublicocih3024 from cx oraclec10appsoracleclient11201home1rdbmspublicociaph10788 warning function declaration is not a prototypeappsoracleclient11201home1rdbmspublicociaph10794 warning function declaration is not a prototypegcc pthread shared buildtemplinuxx86 642711gcx oracleo lappsoracleclient11201home1lib lclntsh o buildliblinuxx86 642711gcx oraclesois something obviously wrong with this setupthanksupdatemy ld library path contains the lib directory above with libclntshso1 echo ld library pathappsoracleclient11201libthis does not seem to make any difference i rebuild the cx oracleso file and it still shows libclntshso1 not found when i run ldd cx oraclesopython failing to load the built modulepython 272 default jan 19 2012 143832gcc 346 20060404 red hat 34611 on linux2type help copyright credits or license for more information import cx oracletraceback most recent call last file stdin line 1 in moduleimporterror libclntshso1 cannot open shared object file no such file or directorysolvedthe issue was related to the ld library path environment variable due to restrictions on the setup i am working with corp env i had to build cx oracle as another user system account ie i was running this sudo u username python27 setuppy buildso even though ld library path was set correctly for me my version was not used when command was executed as a different user i was able to build successfully by moving the source code to a location where i had permissions and running the build as my user,['python'] +323221,ienumerable to string i have never stumbled across this before but i have now and am surprised that i cannot find a really easy way to convert an ienumerablechar to a stringthe best way i can think of is string str new stringmyenumerabletoarray but to me it seems like this would create a new char and then create a new string from that which seems expensivei wouldve thought this would be common functionality built into the net framework somewhere is there a simpler way to do thisfor those interested the reason i would like to use this is to use linq to filter stringsstring allowedstring new stringinputstringwherec allowedcharscontainsctoarray,"['c#', '.net']" +323233,how to restart jvm when it runs out of memory by using jmx monitoring i want to create a nagios watchdog for jvm that looks when the jvm runs out of memory and restarts itcurrently i was able to setup the jvm be allow jmx but i do not know how to detect outofmemory condition and restart it check jmx u servicejmxrmijndirmi12700100jmxrmi o javalangtypememory a heapmemoryusage k used i heapmemoryusage j used v jmx ok heapmemoryusageused957414288committed2415984640init2147483648max286376used957414288,['java'] +323253,why does a trycatch block create new variable scope for exampletry someobject someobject new someobject someobjectdangerousmethodcatchexception esomeobjectanothermethod cannot access someobjectbut you can declare it before the trycatch block and then it works finesomeobject someobjecttry someobject new someobject someobjectdangerousmethodcatchexception esomeobjectanothermethod works finei am just wondering the design reason for this why are objects created within the trycatch block not in scope with the rest of the method maybe i am not understanding deep down how a trycatch works besides just watching for exceptions thrown,['java'] +323279,how do i edit the css of the htmlthisplayfor method in mvc 3 i am using the following code to thisplay text from my view model in my viewhtmlthisplayform mnamewhen i look at the html details in ie9 which i have to use at work there is no class associated with the name it just uses the body css styling instead of the thisplayfield class styling does anyone know what might be causing this issue or how i might edit the css for the text created,"['c#', '.net', 'css']" +323282,jpa 2 criteriaquery using a limit i am using jpa 2 for safety reasons i am working type safe with criteriaquerys and thus i am not searching for any solutions of typed queries and so oni have recently come across an issue in which i need to set a sqllimitafter a lot of searching i have still not been successful in finding a solutioncriteriaqueryproduct query getentitymanagergetcriteriabuildercreatequeryproductclassrootproduct product queryfromproductclassqueryselectproductreturn emcreatequeryquerygetresultlistcan anyone help me,"['java', 'sql']" +323289,rake task to backup and restore database i am working on a rails project and sometimes i program at home and sometimes at work in my development process i add data to the database and i really need a way to synchronize the databases at home and worki am thinking about a rake task to backuprestore the whole database in a rails appis there anyway to do that,['ruby-on-rails'] +323304,signing binaries of opensource projects i tried to use servicestack in my current project but found the binaries released were not strong named so i could not use it out of the box when asking on github why i got the following answerit is virally toxic and hinders binding upgrading development deployment etcmythz was very laconic so i did not want to bother him more and asking here i use a lot of opensource net projects like automapper nunit moq log4net ninject etc and their releases are all strong named found similar question here on so but it does not help me is it normal practice in oss why not release both signed and unsigned binaries,['.net'] +323326,why are stored procedures still not supported in rails 3 i am familiar with the long standing lovehate relationship between ruby on rails dbmsdrivers and stored procedures and i have been developing rails applications since version 232however every once in a while a situation arises where a sp is simply a better choice than combining data on the much slower application level specifically running reports which combines data from multiple tables is usually better suited for a spwhy are stored procedures still so poorly integrated into rails or the mysql gem i am currently working on a project with rails 3010 and mysql2 gem 0213 but as far as i can see even the latest edge rails and mysql gem 03 still throw tantrums when you use spsthe problem which has been and still is is that the database connection is lost after a sp is called activerecordbaseconnectionexecutecall stored proc mysqlresult0x103429c90 activerecordbaseconnectionexecutecall stored procactiverecordstatementinvalid mysqlerror commands out of sync activerecordbaseconnectionactive false activerecordbaseconnectionreconnect nil activerecordbaseconnectionexecutecall proc01 mysqlresult0x1034102e0 activerecordbaseconnectionactive falseis this a really difficult problem to tackle technically or is this a design choice by rails,"['mysql', 'ruby-on-rails']" +323375,css boxshadow is not working with textarea in webkit this simple code is not working in chrome or safaridoctype htmlhtmlheadmeta httpequivcontenttype contenttexthtml charsetutf8titleuntitled documenttitleheadstylerequired boxshadow0 0 5px redstylebodyformtextarea requiredtextareaformbodyhtmlit works just fine in firefox and opera also border1px solid red works just fine in webkit browsers whats the deal i even tried textarea thisplayblock thinking that it could have been an inline issue,['css'] +323388,jerseyjaxrs return contentlength in response header instead of chunked trasnfer encoding i am using jersey to create restful api resources and responsebuilder to generate the responseexample code for the restful resourcepublic class inforesource get pathserviceid producesmediatypeapplication json mediatypeapplication xml public response getcompanypathparamidstring id company is just a pojo company company getcompanyid return responsestatus200entitycompanybuild in the response it is returning chunked transfer encoding in the response headers what is the proper way in the jersey world to have it return the contentlength header instead of the transferencoding chunked header in the response headers,['java'] +323392,get header information from php curl post request i have been searching for hours and cannot find anything on this i am doing a php curl post request to the sugarsync api and it returns a location in the headers that i need i have no idea how to get this information i have to keep it as a post because i post an xml file to their api and all they do is return header information i have no clue how i can access the location in the headers according to them i need to put it into another xml file and post that as well any help is appreciated,['php'] +323430,css transition fade in so i have used css transitions before but i have a unique case with this one i am writing a custom plugin for creating modals essentially i create a div on the fly documentcreateelementdiv and append it to the body with a few classes these classes define color and opacity i would like to use strictly css to be able to fade in this div but making the state change seems difficult bc they require some user interaction tried some advanced selectors hoping it would case a state change tried media query hoping to change statelooking for any ideas and suggestions i really want to keep this in css if possible,['css'] +323442,drawable selector not working in jelly bean i have a drawable selector as a background for each item in a listview to highlight the selected row eveything works fine in ice cream sandwich but does not seem to work in jelly bean cannot find any documentation saying what changes could have caused it to stop working and what i need to do to fix itby not working i mean when i click on a row in the listview the items background color is not turning the colorblue color but it does in icsthis is the selector code i am using listing selectorxmlselector xmlnsandroid item androidstate focusedtrue androiddrawablecolorblue item androidstate pressedtrue androiddrawablecolorblue item androidstate activatedtrue androiddrawablecolorblue selected item androidstate selectedtrue androiddrawablecolorblue selected item androiddrawableandroidcolortransparent selectorthis is the layout of the listview itemrelativelayout xmlnsandroid androidlayout widthwrap content androidlayout heightfill parent androidorientationhorizontal androidbackgroundcolorlisting selector textview androidididtext androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentlefttrue relativelayoutthis the blue color resourceresources color nameblueff33b5e5color resourcesupdate 1tried moving the selector from the color folder to the drawable folder and updating the code to thisandroidbackgrounddrawablelisting selectorupdate 2also on the listview tried adding this listview androididandroididlist androidlayout widthwrap content androidlayout heightfill parent androidlistselectordrawablelisting selector update 3i thought it might be something in my code but i removed all the code from onlistitemclick of the listview and still the selector is not workingupdate 4i have narrowed it down to state selected or state activated not working as state pressed seems to be workingupdate 5i think i was mistaken i do not think the selector is being recognized at all i was confusing the builtin listview highlighting as my selector i am now wondering if it has something to do with the way my project is setup i have the selector in a library class maybe something changed with that from ics to jb however moving the selector to my apps project did not seem to fix itupdate 6ok after some more hair pulling i have narrowed it down again to either state selected or state activated not being recognized as changing the color for state pressed does work which means my selector is being recognized from the comments in seems to be something with my app specifically as others have been able to get selectors working with jelly beanthough something else that is interesting is that changing the drawable value for the default state is not recognized where i have colortransparent i would think changing that to a color would cause the listing to change to that color but it does notalso this is not working in ics eitherupdate 7after even more hair pulling i have thiscovered that longpressing on a menu item results in that items color being changed just clicking on an item still does not work not even sure what the means final updatei give up i removed the selector and am just refreshing the listview on click and remembering the position clicked and highlighting it from code not ideal but not worth the effort to try to fix,['android'] +323445,does backbonemodels thisget copy an entire array or point to the same array in memory person backbonemodelextend defaults name fetus age 0 children initialize function alertwelcome to this world adopt function newchildsname var children array thisgetchildren children arraypush newchildsname thisset children children array var person new person name thomas age 67 children ryan personadoptjohn resig var children persongetchildren ryan john resigin this example code we havechildren array thisgetchildreni was thinking this would just point to the same array in memory and so would be o1 however then i thought that would be a design floor because one could manipulate the array without using thisset and then event listeners wouldnt fireso i am guessing it somehow magically copies the arraywhat happensedit i just found the implementation in the backbone source code at i have pasted relevant code at bottomget returnsreturn thisattributesattrso this would just point to the same array in memory right so one could change the array without using set and that would be bad am i correctget functionattr return thisattributesattr get the htmlescaped value of an attribute escape functionattr var html if html this escapedattributesattr return html var val thisgetattr return this escapedattributesattr escapeval null val returns true if the attribute contains a value that is not null or undefined has functionattr return thisgetattr null set a hash of model attributes on the object firing change unless you choose to silence it set functionkey value options var attrs attr val handle both key value and key value style arguments if isobjectkey key null attrs key options value else attrs attrskey value extract attributes and options options options if attrs return this if attrs instanceof model attrs attrsattributes if optionsunset for attr in attrs attrsattr void 0 run validation if this validateattrs options return false check for changes of id if thisidattribute in attrs thisid attrsthisidattribute var changes optionschanges var now thisattributes var escaped this escapedattributes var prev this previousattributes for each set attribute for attr in attrs val attrsattr if the new and current value differ record the change if isequalnowattr val optionsunset hasnow attr delete escapedattr optionssilent this silent changesattr true update or delete the current value optionsunset delete nowattr nowattr val if the new and previous value differ record the change if not then remove changes for this attribute if isequalprevattr val hasnow attr hasprev attr thischangedattr val if optionssilent this pendingattr true else delete thischangedattr delete this pendingattr fire the change events if optionssilent thischangeoptions return this,['javascript'] +323464,opengl vao vbo ibo gldrawelements not thisplaying i am having trouble getting my level data to appear on the screen i have my shader in use rendering a cube correctly but not the levelhere is the setup for my vbo vao and ibovoid zonemeshbuilddata create the vbo for this mesh glgenbuffers1 vbo glbindbuffergl array buffer vbo glbufferdatagl array buffer sizeofvertices vertices gl static draw create the ibo glgenbuffers1 ibo glbindbuffergl element array buffer ibo glbufferdatagl element array buffer numpoly 3 sizeofshort indices gl static draw create the vao glgenvertexarraysapple1 vao glbindvertexarrayapplevao bind the vbo to the buffer and set up the attributes glbindbuffergl array buffer vbo glvertexattribpointer0 3 gl float gl false sizeofvertex buffer offset0 glvertexattribpointer1 2 gl float gl false sizeofvertex buffer offsetsizeoffloat3 glvertexattribpointer2 3 gl float gl false sizeofvertex buffer offsetsizeoffloat5 bind the ibo to the vao glbindbuffergl element array buffer ibohere is my vertex structurestruct vertex float x float y float z float u float v float normx float normy float normzhere are the relevant data items in the zonemesh classvertex verticesshort indicesgluint vbogluint vaogluint ibovertex shaderversion 120attribute vec3 positionuniform mat4 cameravoid main gl position camera vec4position 10ffragment shaderversion 120void mainvoid gl fragcolor vec400 06 07 10rendering shaderuse testing render the first 50 meshes forint i 0 i 50 i gluniformmatrix4fvshadercamera 1 gl false glmvalue ptrmvpmatrix glenablevertexattribarrayshaderposition glbindvertexarrayapplezonegetvaoi gldrawelementsgl triangles 500 gl unsigned short null shaderunusethe renderingshader use is not the problem the mvpmatrix is correct i have a cube rendering correctly above it the zone does not render though,['c++'] +323499,inherit from multiple partial implementations of an abstract base class is it possible to have a number of partial implementations of an abstract interface and then collect these partial implementations into a single concrete class by using multiple inheritencei have the following example codeinclude iostreamstruct base virtual void f1 0 virtual void f2 0struct d1 base void f1 override stdcout func stdendl struct d2 base void f2 override stdcout func stdendl collection of the two partial implementations to form the concrete implementationstruct deriv d1 d2 using d1f1 i added these using clauses when it first did not compile they do not help using d2f2int main deriv d return 0this fails to compile with the following errorsmaincpp in function aint mainamaincpp2711 error cannot declare variable ada to be of abstract type aderivamaincpp198 note because the following virtual functions are pure within aderivamaincpp518 note virtual void basef1maincpp618 note virtual void basef2,['c++'] +323502,ioerror errno 22 invalid argument when readingwriting large bytestring i am gettingioerror errno 22 invalid argumentwhen i try to write a large bytestring to thisk with fwrite where f was opened with mode wbi have seen lots of people online getting this error when using a windows network drive but i am on osx 107 when i originally asked the question but 108 now with a standard hfs local filesystem i am using python 322 happens on both a pythonorg binary and a homebrew install i do not see this problem with the system python 272i also tried mode wb based on this windows bug workaround but of course that did not helpthe data is coming from a large numpy array almost 4gb of floats it works fine if i manually loop over the string and write it out in chunks but because i cannot write it all in one pass npsave and npsavez fail since they just use fwritearytostring i get a similar error when i try to save it into an existing hdf5 file with h5pynote that i get the same problem when reading a file opened with filefilename rb fread gives this ioerror while freadchunk size for reasonable chunk size worksany thoughts,['python'] +323524,mysql connect localhost 127001 slow on windows platform i am using windows 7 apache 2 php 5 mysql 5 all are on the same machinei have found an interesting issue i have the following code sql select from user1 conn mysql connectlocalhost root x mysql select dbtest1 mysql queryset names utf8 result mysql querysql conn while row mysql fetch assocresult foreach row as key value echo key value echo br mysql free resultresult mysql closeconnthe running time for the above code is over 1 secondwhen i use 127001 instead of localhost the running time is around 10 msi tried to find the underlying reason on the internet and this is the resulti recently moved my development from xp to windows 7 and found that webpages i had developed were taking 5 seconds long to load this was unacceptable of course so i had to track down the problem i eventually tracked down the offending functionmethod pdoconstruct i also found that mysql connect was taking about 1 second to make a connection after a little googling i found an explaination that php had issues with ipv6 and that you could fix the problem by either thisabling ipv6 or switching to the ipaddress 127001 when making your connectioni wonder what the issue of ipv6 on php is just want to get a deeper understaning thanks,"['php', 'mysql']" +323613,xcode 44 permission denied when trying to download application data after updating my xcode to version 44 it seems to be impossible to retrieve application data from my devicesin xcode 43 and all previuos version i downloaded my application data like sqlite databases and files i created through the organizer organizer devices device applications application downloadwith xcode 44 i get an error permission denied when i try to download the documents from the sandboxis there anything new maybe a new setting i have to change to obtain the application data from my device again,['iphone'] +323615,how to give priority to privileged thread in mutex locking first of all i am completely a newbie in mutexmultithread programming sosorry for any error in advancei have a program that runs multiple threads the threads usually one percpu core do a lot ofcalculation and thinking and then sometimes they decide to call aparticular shared method that updates some statisticsthe concurrency on statistics updates is managed through the use of a mutexstats mutexlockcommon areaupdate thread stats stats mutexunlocknow to the problemof all those threads there is one particular thread that need almostrealtime priority because it is the only thread that actually operateswith almost realtime priority i meanlet us suppose thread t0 is the privileged one and t1t15 are the normaloneswhat happens now isthread t1 acquires lockthread t2 t3 t0 call the lock method and wait for it to succeedthread t1 calls unlockone at random as far as i know of the threads t2 t3 t0 succeeds in acquiringthe lock and the other ones continue to waitwhat i need isthread t1 acquire lockthread t2 t3 t0 call the lock method and wait for it to succeedthread t1 calls unlockthread t0 acquires lock since it is privilegedso whats the best possibly simplest method to do this thingwhat i was thinking is to have a bool variable calledprivileged needs lockbut i think i need another mutex to manage access to this variable i dontknow if this is the right wayadditional infomy threads use c11 as of gcc 463code needs to run on both linux and windows but tested only on linux at the momentperformance on locking mechanism is not an issue my performance problem are in internal thread calculations and thread number will always be low one or two per cpu core at maximumany idea is appreciatedthanksthe below solution works three mutex wayinclude threadinclude iostreaminclude unistdhstdmutex mstdmutex nstdmutex lvoid lowpriolock llock nlock mlock nunlockvoid lowpriounlock munlock lunlockvoid highpriolock nlock mlock nunlockvoid highpriounlock munlockvoid hptconst char s using namespace std cout hpt trying to get lock here endl highpriolock cout s endl sleep2 highpriounlockvoid lptconst char s using namespace std cout lpt trying to get lock here endl lowpriolock cout s endl sleep2 lowpriounlockint mainstdthread t0lptlow prio t0 working herestdthread t1lptlow prio t1 working herestdthread t2hpthigh prio t2 working herestdthread t3lptlow prio t3 working herestdthread t4lptlow prio t4 working herestdthread t5lptlow prio t5 working herestdthread t6lptlow prio t6 working herestdthread t7lptlow prio t7 working herestdcout all threads created stdendlt0joint1joint2joint3joint4joint5joint6joint7joinreturn 0tried the below solution as suggested but it does not work compile with g stdc0x o test testcpp lpthreadinclude threadinclude mutexinclude timehinclude pthreadhstdmutex lvoid waiter llock printfhere i am waiter startsn sleep2 printfhere i am waiter endsn lunlockvoid privilegedint id usleep20 llock usleep20 printfhere i am privileged dnid lunlock void normalint id usleep20 llock usleep20 printfhere i am normal dnid lunlock int main stdthread twwaiter stdthread t1normal1 stdthread t0privileged0 stdthread t2normal2 sched param sch int policy pthread getschedparamt0native handle policy sch schsched priority 19 pthread setschedparamt0native handle sched fifo sch pthread getschedparamt1native handle policy sch schsched priority 18 pthread setschedparamt1native handle sched fifo sch pthread getschedparamt2native handle policy sch schsched priority 18 pthread setschedparamt2native handle sched fifo sch twjoin t1join t0join t2join return 0,['c++'] +323659,css how to change the color of the bottom right square of the scrollbar in webkit questionhow can i change the color of the bottomright square of the scrollbar to black in webkit googlechrome this is what i have so farwebkitscrollbar width 13px height 13px webkitscrollbarhover height 18px webkitscrollbarbuttonstartdecrementwebkitscrollbarbuttonendincrement height 15px width 13px thisplay block background 101211 backgroundrepeat norepeat webkitscrollbarbuttonhorizontaldecrement backgroundimage urlimageshorizontaldecrementarrowpng backgroundposition 4px 3px webkitscrollbarbuttonhorizontalincrement backgroundimage urlimageshorizontalincrementarrowpng backgroundposition 3px 3px webkitscrollbarbuttonverticaldecrement backgroundimage urlimagesverticaldecrementarrowpng backgroundposition 3px 4px webkitscrollbarbuttonverticalincrement backgroundimage urlimagesverticalincrementarrowpng backgroundposition 3px 4px webkitscrollbarbuttonhorizontaldecrementactive backgroundimage urlimageshorizontaldecrementarrowactivepng webkitscrollbarbuttonhorizontalincrementactive backgroundimage urlimageshorizontalincrementarrowactivepng webkitscrollbarbuttonverticaldecrementactive backgroundimage urlimagesverticaldecrementarrowactivepng webkitscrollbarbuttonverticalincrementactive backgroundimage urlimagesverticalincrementarrowactivepng webkitscrollbartrack webkitboxshadow inset 0 0 6px rgba03 borderradius 10pxwebkitscrollbartrackpiece backgroundcolor 151716 webkitscrollbarthumbvertical height 50px background webkitgradientlinear left top right top colorstop0 4d4d4d colorstop100 3 border 1px solid 0d0d0d bordertop 1px solid 6 borderleft 1px solid 6 borderradius 10px webkitboxshadow inset 0 0 6px rgba05 webkitscrollbarthumbhorizontal width 50px background webkitgradientlinear left top left bottom colorstop0 4d4d4d colorstop100 3 border 1px solid 1f1f1f bordertop 1px solid 6 borderleft 1px solid 6 borderradius 10px webkitboxshadow inset 0 0 6px rgba05,"['html', 'css']" +323663,how to deal with branch prediction when using a switch case in cpu emulation i recently read the question here why is processing a sorted array faster than an unsorted array and found the answer to be absolutely fascinating and it has completely changed my outlook on programming when dealing with branches that are based on datai currently have a fairly basic but fully functioning interpreted intel 8080 emulator written in c the heart of the operation is a 256 long switchcase table for handling each opcode my initial thought was this would obviously be the fastest method of working as opcode encoding is not consistent throughout the 8080 instruction set and decoding would add a lot of complexity inconsistency and oneoff cases a switchcase table full of preprocessor macros is a very neat and easy to maintainunfortunately after reading the aforementioned post it occurred to me that there is absolutely no way the branch predictor in my computer can predict the jumping for the switch case thus every time the switchcase is navigated the pipeline would have to be completely wiped resulting in a several cycle delay in what should otherwise be an incredibly quick program there is not even so much as multiplication in my codei am sure most of you are thinking oh the solution here is simple move to dynamic recompilation yes this does seem like it would cut out the majority of the switchcase and increase speed considerably unfortunately my primary interest is emulating older 8bit and 16bit era consoles the intel 8080 here is only an example as it is my simplest piece of emulated code where cycle and timing keeping to the exact instruction is important as the video and sound must be processed based on these exact timingswhen dealing with this level of accuracy performance becomes an issue even for older consoles look at bsnes for example is there any recourse or is this simply a matteroffact when dealing with processors with long pipelines,['c'] +323666,decorator pattern vs inheritance with examples i have been experimenting with the decorator pattern to extend functionality of code you do not want to touch for example and i see how to implement it however i am now unsure why you do not just inherit from the original class and extend that wayi have read that the decorator pattern allows you to add functionality at runtime whereas inheritance means its there at compile timei do not understand thiscould someone explain this provide examples and explain when its better to use decorator vs inheritancethanks,"['c#', '.net']" +323671,why do not child vertical margins expand parent container i have come across a case where i need a childs margin to expand a parent container i found that the space outside of the parent is allocated but the parent itself is not expanded i then found that by adding overflow hidden to the parent i could fix this issuecan anyone shed any light on why this is the caseupdatei have found that adding any padding or border value to the parent also fixes thisupdated example,['css'] +323679,log4j log file in user home directory i am working on an application that will run on osx and windows i want the logs to be written to the users home directory for osx it will be under the userslibraryapplication supportmyapplog directory and under windows depending on the version under usersappdatamyapplog directory what is the best way i can do this i have looked around for solutions for this but nothing helpful or a solution i am comfortable using has come up look forward to your inputs edit since the location of the log file depends on the os i am hoping to find a run time solution possibly something like belowif systemgetpropertyosnamecontainsmac logfilelocation systemgetpropertyuserhome libraryapplication supportmyapplogselse logfilelocation systemgetenvappdata myapplogsthanks,['java'] +323687,place 3 buttons in a linearlayout to occupy equal amount of space i would like to have three buttons taking equal amount of available space horizontally in a rowi used androidlayout gravity what is the problemlayout xml linearlayout xmlnsandroid androidlayout widthfill parent androidlayout heightwrap content androidorientationhorizontal androidweightsum10 button androidididbutton androidlayout widthwrap content androidlayout heightwrap content androidtextstringbg androidbackgrounddrawablebutton red androidlayout weight2 androidlayout gravityleft button androidididbutton androidlayout widthwrap content androidlayout heightwrap content androidtextstringbm androidbackgrounddrawablebutton red androidlayout weight2 androidtextcolorf androidlayout gravitycenter button androidididbutton androidlayout widthwrap content androidlayout heightwrap content androidbackgrounddrawablebutton red androidlayout weight2 androidtextstringbf androidlayout gravityright linearlayoutif someone see whats wrong thanks,['android'] +323690,how to print java bean completely using reflection or any other utility i have an java bean class person containing 3 variablesname stringage stringaddress object address contains 3 variablesstreetdoor nocityi would like to have a utility which should print all variables in person by this i mean it should print person also the address object contained in iti could create a hashmap and put the variable names values using reflection and print keyvalue ui in jsp but the issue is i have to apply reflection for address to add variablevalue in the hashmapis there a utility available to do this,['java'] +323702,default scope in sequel in activerecord there is a default scope class method to specify a default scope for exampleclass user activerecordbase default scope wheredeleted falseenduserall select from users where deleted 0how can i do this in sequelmodeleditafter some googling i eventually found some useful informationclass user sequelmodel define some scopes filters on the dataset dataset module do def existing filterdeleted false end def active filterthisabled false end end this is the equivalent to a default scope set one of the datasets as the default dataset for this model set datasetselfactiveendthe generated query then looks like thisuserall select from users where deleted is falseby the way the equivalent to unscoped is unfiltereduserunfilteredall select from usersbut there is one problem if you try to update a user you got from an unfiltered dataset it tries to update the user using the given datasetusercreatethisabled true deleted trueuserall u userunfilteredfirst given useruthisabled falseusave update users set where thisabled is false and id 1 sequelnoexistingobject attempt to update object did not result in a single row modificationso i am back at the beginning any workaround for this,['ruby'] +323732,where is specified how opengl es 20 represents float texture values in the fragment shader i am trying to do some gpgpu using opengl es 20it seems to me that the gl nv draw buffers and the gl oes texture float extensions are some of the essentials herethis question relates to the gl oes texture float extension from the desktop world i am used to textures being in the 01 range when accessed in the shader if the format is fixed point like gl rgbaconsulting the respective oes extension page it says if the internal format of the texture is fixedpoint components are clamped to 01 otherwise values are not modifiednow i have heard several times on the web for example the answer here do opengl glsl samplers always return floats from 00 to 10 that es 20 supports access to unclamped values in the fragment shader too but where is this functionality specified the extension says otherwise values are not modified but since the opengl es specification only knows fixedpoint formats it does not make sense to mealso as i understand it the extension only specifies that float values can be read from client memory into a texture but does not specify how ie how many bits per channel the texture is represented in graphics memory is there any official spec on thisfinally i would like to write unclamped floating point values to an fbo color attachment in my fragment shader preferably using 32 bits per channel is this possible,['android'] +323744,flushing denormalised numbers to zero i have scoured the web to no availis there a way for xcode and visual c to treat denormalised numbers as 0 i would have thought there is an option in the ide preferences to turn on this option but cannot seem to find iti am doing some crossplatform audio stuff and need to stop certain processors hogging resourcescheers,['c++'] +323804,requirejs optimizer does not include nested require calls i am reading through the optimizer documentation for quite a while but it seems like i cannot figure it the doc saysthe optimizer will only combine modules that are specified in arrays of string literals that are passed to toplevel require and define calls or the requirename string literal calls in a simplified commonjs wrapping so it will not find modules that are loaded via a variable nameok so far so good this basically means rjs would not include nor crawl nested dependencies now lets assume we have a main application file which looks like the followingrequire es5shim tools function consolelogfictive app entry point require domready function doc consolelogdomready loading gui modules require guiwindow guiheader guicontent i guess the problem becomes pretty obvious here rjs the optimizer creates that file by only linking es5shimjs and toolsjs into it is there any good way workaround to tell that optimizer that it also should link the windowjs headerjs and contentjs files in this example of course the domready plugin in this instance will get loaded and it will eventually execute the callback but the structure itself here it seems prevents the optimizer from doing its jobquestion areif i just would list all modules in the top require call would rjs also includelink all top require and define calls from nested and nestednested modules into the mainapp file they are mentioning the include option for rjs in the docs does it make sense here and if so how to properly invoke it of course you do not want to lose the option to lazyload modules lateron but for this kind of dependency waiting for domcontentloaded i hope there is a way to workaround that,['javascript'] +323813,is it good practice for java class names to be plural is it good to have java class name like extractionutilsin naming conventions i no where found anything about plural name of the java classi have seen classes like this in one of the project,['java'] +323836,net c best way to wait for async events to complete and still have a synchronous flow in your code my generalized question is this how do you write asynchronous code that is still clear and easy to follow like a synchronous solution would bemy experience is that if you need to make some synchronous code asynchronous using something like backgroundworker you no longer have a series of easy to follow program statements that express your overall intent and order of activities you end up instead with a bunch of done event handlers each of which starts the next backgroundworker producing code that is really hard to follow i know that is not very clear something more concretelet us say a function in my winforms application needs to start up some amazon ec2 instances wait for them to become running and then wait for them to all accept an ssh connection a synchronous solution in pseudo code might look like thisinstances startnewinstances instances startinstances waitforinstancestobecomerunninginstances waitforinstancestoacceptsshconnectioninstances return instances that is nice what is happening is very clear and the order of program actions is very clear no white noise to thistract you from understanding the code and the flow i would really like to end up with code that looks like that but in reality i cannot have a synchronous solution each of those functions can run for a long time and each needs to do things like update the ui monitor for timeouts being exceeded and retry operations periodically until success or timeout in short each of these needs to be happening in the background so the foreground ui thread can continue onbut if i use solutions like backgroundworker it seems like i do not end up with nice easy to follow program logic like the above instead i might start a background worker from my ui thread to perform the first function and then my ui thread goes back to the ui while the worker thread runs when it finishes its done event handler might start the next background worker when it finishes its done event handler might start the last backgroundworker and so on meaning you have to follow the trail of the done event handlers in order to understand the overall program flowthere has to be a better way that a lets my ui thread be responsive b let us my async operations be able to update the ui and most importantly c be able to express my program as series of consecutive steps as i have shown above so that someone can understand the resultant codeany and all input would be greatly appreciatedmichael,"['c#', '.net']" +323856,does linux allow any system call to be made from signal handlers my understanding is that in general the behavior is undefined if you call a nonasync signal safe function from a signal handler but i have heard that linux allows you to call any system call safely is this true also the only portable behavior for a sigsegv handler is to abort or exit but i understand linux will actually resume execution if you return true,['c'] +323876,python class properties i am trying to find the best way to extend a class variable hopefully an example of the method i have come up with so far will make this clearclass aobject foo thing another thingclass ba foo afoo stuff more stuffso i am trying to make the subclass inherit and extend the parents class variable the method above works but seems a bit kludgey i am open to any suggestion including accomplishing something similar using a completely different approachobviously i can continue to use this method if need be but if there is a better way i would like to find it,['python'] +323915,robolectric and intentservices using robolectric how would one go about testing an intentservice that broadcasts intents as a responseassuming the following classclass myservice extends intentservice override protected void onhandleintentintent intent localbroadcastmanagergetinstancethissendbroadcastnew intentaction in my test case i am attempting to do something like thisrunwithrobolectrictestrunnerclasspublic class myservicetest test public void testpurchasehappypath throws exception context context new activity register broadcast receiver broadcastreceiver br new broadcastreceiver override public void onreceivecontext context intent intent test logic to ensure that this is called contextregisterreceiverbr new intentfilteraction this does not work contextstartservicenew intentcontext myserviceclass myservice is never started using this approach i am relatively new to robolectric so i am probably missing something obvious is there some sort of binding i have to do before calling startservice i have verified that broadcasting works by just calling sendbroadcast on the context any ideas,['android'] +323918,after xcode 44 and osx 108 installation failed to build gem native extension when installing libv8 i have recently upgraded osx to mountain lion 108 and xcode 44 and ran into issues when trying to get my rails environment working i started with running bundle install and ran into an error when installing the libv8 library below is a paste of the full error i have search around and looked for similar issues but what i found on stackoverflow so far has not applied to my problem here are the few things i have tried so far with no availinstall xcode command line toolsinstall mysqlinstall x11install different versions of libv8 via the gemfilenow i am at a point where the problem seems to be exceeding my ruby skills if anyone has some ideas on what i can try or are experiencing a similar issue i would love your help thanksheres what my gemfile looks likesource gem rails 326gem bundlergem rakegem sqlite3gem hamlgem nokogirigem whenevergem mysqlgem mysql2gem jqueryrailsgem capistrano gems used only for assets and not required in production environments by defaultgroup assets do gem sassrails 323 gem coffeerails 321 see for more supported runtimes gem therubyracer platforms ruby gem uglifier 103endand heres the error log when trying to install gemssudo bundle installpasswordfetching source index for using rake 0922 using i18n 060 using multi json 136 using activesupport 326 using builder 300 using activemodel 326 using erubis 270 using journey 104 using rack 141 using rackcache 12 using racktest 061 using hike 121 using tilt 133 using sprockets 213 using actionpack 326 using mimetypes 119 using polyglot 033 using treetop 1410 using mail 244 using actionmailer 326 using arel 302 using tzinfo 03 using activerecord 326 using activeresource 326 using bundler 1015 using highline 1613 using netssh 252 using netscp 104 using netsftp 205 using netsshgateway 110 using capistrano 2120 using chronic 067 using coffeescriptsource 133 using execjs 140 using coffeescript 220 using rackssl 132 using json 173 using rdoc 312 using thor 0154 using railties 326 using coffeerails 322 using haml 316 using jqueryrails 202 installing libv8 33104 with native extensions systemlibraryframeworksrubyframeworkversions18usrlibruby18rubygemsinstallerrb482in build extensions error failed to build gem native extension geminstallerextensionbuilderrorsystemlibraryframeworksrubyframeworkversions18usrbinruby extconfrb extconfrb failed could not create makefile due to some reason probably lack ofnecessary libraries andor headers check the mkmflog file for moredetails you may need configuration optionsprovided configuration options withoptdir withoutoptdir withoptinclude withoutoptincludeoptdirinclude withoptlib withoutoptliboptdirlib withmakeprog withoutmakeprog srcdir curdir rubysystemlibraryframeworksrubyframeworkversions18usrbinrubyextconfrb13 uninitialized constant gem nameerrorchecking for pythongem files will remain installed in libraryrubygems18gemslibv833104 for inspectionresults logged to libraryrubygems18gemslibv833104extlibv8gem makeout from systemlibraryframeworksrubyframeworkversions18usrlibruby18rubygemsinstallerrb445in each from systemlibraryframeworksrubyframeworkversions18usrlibruby18rubygemsinstallerrb445in build extensions from systemlibraryframeworksrubyframeworkversions18usrlibruby18rubygemsinstallerrb197in install from libraryrubygems18gemsbundler1015libbundlersourcerb101in install from libraryrubygems18gemsbundler1015libbundlerrubygems integrationrb78in preserve paths from libraryrubygems18gemsbundler1015libbundlersourcerb91in install from libraryrubygems18gemsbundler1015libbundlerinstallerrb58in run from libraryrubygems18gemsbundler1015libbundlerrubygems integrationrb93in with build args from libraryrubygems18gemsbundler1015libbundlerinstallerrb57in run from libraryrubygems18gemsbundler1015libbundlerspec setrb12in each from libraryrubygems18gemsbundler1015libbundlerspec setrb12in each from libraryrubygems18gemsbundler1015libbundlerinstallerrb49in run from libraryrubygems18gemsbundler1015libbundlerinstallerrb8in install from libraryrubygems18gemsbundler1015libbundlerclirb2in install from libraryrubygems18gemsbundler1015libbundlervendorthortaskrb22in send from libraryrubygems18gemsbundler1015libbundlervendorthortaskrb22in run from libraryrubygems18gemsbundler1015libbundlervendorthorinvocationrb118in invoke task from libraryrubygems18gemsbundler1015libbundlervendorthorrb246in thispatch from libraryrubygems18gemsbundler1015libbundlervendorthorbaserb389in start from libraryrubygems18gemsbundler1015binbundle13 from usrbinbundle19in load from usrbinbundle19,"['ruby-on-rails', 'ruby']" +323920,how to convert utc date string to local time systemtimezone input string june 14 2012 010 utcoutput local string jun 13 2012 210 edti like to get the offset from nstimezone destinationtimezone nstimezone systemtimezone nslogtime zone destinationtimezoneabbreviationany suggestion,"['iphone', 'objective-c', 'ios']" +323923,when exactly are we supposed to use public static final string i have seen much code where people write public static final string mystring and then just use a valuewhy do they have to do that why do they have to initialize the value as final prior to using itupdateok thanks all for all your answers i understand the meaning of those key public static final what i dont understand is why people use that even if the constant will be used only in one place and only in the same class why declaring it why dont we just use the variable,['java'] +323928,subtract values in one list from corresponding values in another list python i have two listsa 2 4 6 8 10b 1 3 5 7 9how do i subtract each value in one list from the corresponding value in the other list and create a list such thatc 1 1 1 1 1thanks,['python'] +323967,using gentask with tornado for a simple function just trying to use the async functions of tornado i want to invoke a method from my handler but it keeps telling me that it got an unexpected keyword argument callbackclass myhandlertornadowebrequesthandler asynchronous genengine def getself response yield gentaskselfdosomething argument selfwriteresponse selffinish def dosomethingself myargument pass,['python'] +324011,binding to a weak ptr is there a way to stdbind to a stdweak ptr i would like to store a weak function callback that automatically thisconnects when the callee is destroyedi know how to create a stdfunction using a shared ptrstdfunctionvoid myclassgetcallback return stdfunctionvoidstdbindmyclasscallbackfunc shared from thishowever the returned stdfunction keeps my object alive forever so i would like to bind it to a weak ptrstdfunctionvoid myclassgetcallback stdweak ptrmyclass thisweakptrshared from this return stdfunctionvoidstdbindmyclasscallbackfunc thisweakptrbut that does not compile stdbind will accept no weak ptr is there any way to bind to a weak ptri have found thiscussions about this see below but there seems to be no standard implementation what is the best solution for storing a weak function in particular if boost is not availablethiscussions research all of these use boost and are not standardizedweak functionweak ptr bindingweak binding and a fix for itweak fnanother weak fn,['c++'] +324013,should i use meteorstartup or function do they do the same thing which one should i use inside clientif meteoris client meteorstartupfunction my code here orif meteoris client function my code here,['javascript'] +324031,how to implement saml sso using java java ee i am newbie to saml 20 i was unable to find a book on saml on amazon which will guide you how to get started with saml especially saml20what i am looking for an end to end sso demo app development using saml and an identity provider open source so that i can simulate end to sso so what i mean by that is generate a token from identity provider process saml messagesend response back etc and then create 2 or more domainlogins to simulate sso with success or error messageany tutorialbookresource you know for novice to intermediate or advance on sso with saml will be appreciatedlastly how to use saml in wssecurity,['java'] +324041,how to get value from xml attribute using sqlvariable in xquery i want to get attribute value from xml using xquerymy xml isanswers answerset answer questionidnodeid155answer answer questionidparentnode selectedvalue12productanswer answersetanswersbelow is my querydeclare field varchar100declare attribute varchar100set fieldparentnodeset attribute selectedvalueselect isnullpropertyxmlvalueanswersanswersetanswerquestionidsqlvariablefield1varcharmax isnullpropertyxmlvalueanswersanswersetanswerquestionidsqlvariablefieldsqlvariableattribute 1varcharmax from node where id155below line is working fine with sqlvariableisnullpropertyxmlvalueanswersanswersetanswerquestionidsqlvariablefield1varcharmaxbut i am getting error in below lineisnullpropertyxmlvalueanswersanswersetanswerquestionidsqlvariablefieldsqlvariableattribute 1varcharmaxi want to get provided attributeattribute value in result,['sql'] +324065,ios horizontal slideview with vertical menu nowadays lots of ios iphone application got a vertical menu and sliding viewsit looks like thisi cannot find any examples in inernet need your help thnx,['ios'] +324078,facebook fbeventsubscribeauthauthresponsechange not working for the life of me i cant get eventsubscribeauthauthresponsechange to work see code below div idfbroot div script windowfbasyncinit function fbinit appid x app id channelurl channel file status true check login status cookie true enable cookies to allow the server to access the session xfbml true parse xfbml fbeventsubscribeauthauthresponsechange function response alertthe status of the session is responsestatus load the sdk asynchronously function d var js id facebookjssdk ref dgetelementsbytagnamescript0 if dgetelementbyidid return js dcreateelementscript jsid id jsasync true jssrc connectfacebookneten usalljs refparentnodeinsertbeforejs ref document script div classfbloginbutton datasizexlarge scopeemail datashowfacesfalse datawidth400 datamaxrows1 autologoutlinktrue login with facebookdivthe login button renders and i can logout too only problem is that the authresponse change is not firing and i am not getting the message popup,"['javascript', 'html']" +324080,android mediacontroller play pause controls not refresh properly i have used mediacontroller in my activity its working fine but when i play video for first time then there should b pause button visible but instead there is play and when i press that button then the video is paused correctly and state remains the same and after that its working properly and same thing happens when video completedis this a bug or i am doing any thing wrongvideoviewsetonpreparedlistenernew onpreparedlistener override public void onpreparedmediaplayer mp mediacontroller new mediacontrollervideoplayeractivitythis public void hide public void show ifisplayingad superhide else supershow videoviewsetmediacontrollermediacontroller mediacontrollersetmediaplayervideoview mediacontrollershow,['android'] +324137,fixtures in rspec i am new to using rspec for writing tests in a rails application which uses a mysql database i have defined my fixtures and am loading them in my spec as followsbeforeall do fixtures studentenddoes this declaration save the data defined in my fixtures in the students table or does it just load the data in the table while the tests are running and remove it from the table after all the tests are run,['ruby-on-rails'] +324182,keystore error on java server bks not found i get an error on this linefinal keystore keystore keystoregetinstancebksthe error i get isjavasecuritykeystoreexception bks not found at javasecuritykeystoregetinstanceunknown source at applisteninitapplistenjava84i added bcprovjdk16146jar to the referenced libraries but still no luckmy overall program allows an android phone to be used as mouse and keyboard for a computer using an ssl socket connection the android app has the same line with no errorswhat am i doing wrongeditmaybe this is common knowledge for most but it was not for me so for those like me this is what i did the reason i was using bks was because that is the only format allowed by android but i didnt know that you only needed it on the android side you can use another format on the server and then make a copy of the key and convert it to bks to use on the android eliminating the need for bouncycastlei used a jks key for the server and than converted a copy of that key to bks to use on the android using a program called portecle,['java'] +324194,returning jint array from c to java through jni i have created an integer array in java and passed the array to a cpp programme through jnimy code isimport javautilclass sendarray native method declaration native int loadfileint name load the library static systemloadlibrarynativelib public static void mainstring args int arr 12345678910 create class instance sendarray mappedfilenew sendarray call native method to load sendarrayjava int buf mappedfileloadfilearr print contents of sendarrayjava forint i0ibuflengthi systemoutprintbufi in cpp programme i am reversing the array and returning the array back to java programeemy code isinclude iostreamusing namespace stdjniexport jintarray jnicall java sendarray loadfile jnienv env jobject jobj jintarray array coutorignal array isendl int i jboolean j int ar100 fori 0 i 10 i int p envgetintarrayelementsarray j jint arrayenvgetintarrayelementsone 0 ari arrayi fori 0 i 10 i cout pi fori 10 i 0 i ar10i pi jintarray ret envnewintarray10 fori 0 i 10 i retiari return reterror i am gettin iserror no match for operator in ret long unsigned intlong unsigned inti ariwhat should i do to return the array back to java programme please help,['java'] +324207,how can i populate a class from the results of an sql query in c i have got a class like thispublic class product public int productid get private set public int supplierid get private set public string name get private set public decimal price get private set public int stock get private set public int pendingstock get private set i can fetch those details from my database like thisselect product id supplier id name price total stock pending stock from productswhere product id i do not want to have to manually run through a dataset or datatable to set the valuesi am sure there is a way to populate the class using some kind of binding mapping mechanism but the only stuff i could find was for binding to winforms components or using xamlis there some kind of attribute i can apply to my properties class to have the class automatically populated from a query row,['c#'] +324210,handle modelstate validation in aspnet web api i was wondering how i can achive model validation with aspnet web api i have my model like sopublic class enquiry key public int enquiryid get set required public datetime enquirydate get set required public string customeraccountnumber get set required public string contactname get set i then have a post action in my api controllerpublic void postenquiry enquiry enquiryenquirydate datetimenow contextdaybookenquiriesaddenquiry contextsavechangeshow do i add ifmodelstateisvalid and then handle the error message to pass down to the user,['c#'] +324211,is there a numpy builtin to reject outliers from a list is there a numpy builtin to do something like the following that is take a list d and return a list filtered d with any outlying elements removed based on some assumed thistribution of the points in dimport numpy as npdef reject outliersdata m 2 you npmeandata s npstddata filtered e for e in data if u 2 s e you 2 s return filtered d 24516540 filtered d reject outliersd print filtered d245165i say something like because the function might allow for varying thistributions poisson gaussian etc and varying outlier thresholds within those thistributions like the m i have used here,['python'] +324226,python how to use first class object constructor value in another object class myclassobject def init self xnone if x selfx x def do somethingself print selfxnow i have two objectsmy class1 myclassxmy class2 myclassi want to use x when this my class2 object is calledas other languages support static variable like javac etc,['python'] +324227,check for ajax request in code igniter i am in a php script and i want to check whether the request is an ajax request basically so as not to allow direct script access other than ajax call that isso i am defining is ajax somewhere in the main indexphp file defineis ajax isset serverhttp x requested with strtolower serverhttp x requested with xmlhttprequestand then checking it at the top of my script if is ajax exitno direct script access allowedsince i am new to codeigniter i am not really sureis there any such builtin functionalityis there a more elegant way to do it,['php'] +324259,setting equal heights for divs with jquery i want to set equal height for divs with jquery all the divs may have different amount of content and different default height here is a sample of my html layoutdiv classcontainer div classcolumnthis isbr the highestbr columndiv div classcolumnone linediv div classcolumntwobr linesdivdivdiv classcontainer div classcolumnone linediv div classcolumntwobrlinesdiv div classcolumnone linedivdivi am setting the height with the next jquery functiondocumentreadyfunction var highestbox 0 container columneachfunction ifthisheight highestbox highestbox thisheight container columnheighthighestboxthis works fine but not in my case because i want all the columns equal only inside one container this means that in the first container all the boxes must be as high as the first div but in the second one they must be equal to second columnso question is how should i modify my jquery to reach thisthank you,"['jquery', 'html']" +324291,linq list of tuples to tuple of lists i have a listtupleab and would like to know if there is a way in linq to return tuplelistalistbthis is similar to the following python question unpacking a list tuple of pairs into two lists tuples,['c#'] +324300,how to add conditional where clauses in rails i am a rails newbie and am trying to perform a search on a table with rails and i am just using my sql knowledge to do this but this just does not seems like rails or ruby evenis there any better way to do what i am doing below basically only pass date arguments to sql if they are filleddef searchbegin datenil end datenil subject and created at if begin datenil end datenil where part subject between begin date and end date else if begin datenil end datenil where part else ifbegin datenil where part subject end date else if end datenil where part subject begin date end end end end userjoinsplaces containers label userwhereusersid user id where part user id selfid begin datebegin date end dateend dategroupselectendedituserrbhas many containershas many user placeshas many places through user placeshas many labelsplacerbhas many containershas many user placeshas many users through user placescontainerrbbelongs to labelbelongs to placebelongs to userlabelrbbelongs to userhas many containersbasically i want to get a count of the number of containers within a given users labels or with a direct relationship per location and want to be able to filter it by begin and end dateseither of this dates may be nil and so i would need to address this in my querymy question is how can i do this the rails way i took a look at record queryinghtml and perhaps i could use the except command here somewherebut this relationship model just seems a bit complex to do this with activerecordhow may i i really think i should use activerecord but howthank you,"['sql', 'ruby-on-rails', 'ruby']" +324305,extra white space between tables in html email for gmail client my code is atthe problem is in gmail it leaves an extra white space between 2 tables inside the same celli have tried thisplayblock margin0 padding0 lineheight0however it does not seem to go awayis there a fix to this,"['html', 'css']" +324339,in scikit learn how to deal with the data mixed with numerical and nominal value i know that the computation in scikitlearn is based on numpy so everything is a matrix or arrayhow does this package handle mixed data numerical and nominal valuesfor example a product could have the attribute color and price where color is nominal and price is numerical i notice there is a model called dictvectorizer to numerate the nominal data for example two products areproducts colorblackprice10 colorgreenprice5and the result from dictvectorizer could be1010 015if there are lots of different values for the attribute color the matrix would be very sparse and long features will degrade the performance of some algorithms such as decision trees is there any way to use the nominal value without the need to create dummy codes,['python'] +324389,how do you determine your permissions in aws s3 through the java sdk i know you can try to read the acls or bucket policies through the java sdk but is there any easy way to just check if you have read andor write permissions to a bucket andor its contents i do not see any havereadpermissions method or anything in the amazons3 class but maybe i am missing something i find it hard to believe there is no easy way to check permissions,['java'] +324404,rounding to nearest 50 cents i have the following code that rounds my amounts to the nearest dollar switch amazonresultsalesrank case amazonresultsalesrank 1 trimamazonresultsalesrank issetamazonresultsalesrank amazonresultsalesrank null pricefloat lowestamazonprice 005 payprice roundprice 0 to round the price up or down to the nearest break case amazonresultsalesrank 0 amazonresultsalesrank 150 pricefloat lowestamazonprice 020 payprice roundprice 0 to round the price up or down to the nearest breaki understand that if i use roundprice 2 that i will have 2 decimal places but is there a way to round to the nearest 50 cents,['php'] +324413,would this google lvl policy implementation be reasonably secure the default servermanagedpolicy that google provides in their license verification library relies on the server responses to determine the license revalidation interval this results in requiring a revalidation every few days in perpetuity this is not only a nuisance to users it can be a serious problem for users who go extended periods with no connectivity we just had an inquiry from a user who expects to be without internet connectivity for several weeks which is what motivates this questionin summary i am looking for an algorithm that will accomplish two things drastically reduce the connectivity requirements compared to servermanagedpolicyprovide the same level of antipiracy protectionin an answer to this question the suggested policy algorithm is to ignore the times provided in the response from googles server and instead to use a licensed expiration period of about a month with license checks being attempted every few days to extend the expiration period if a licensed response is receivedwhile this approach partially addresses the first goal it still requires users to be connected once a month while using the app so it would not work for at least one of our usersthe following algorithm accomplishes the first goal but i do not know about the second any comments pointing out weaknesses of this algorithm or suggestions for another approach would be welcomeon first run do a license check and insist on a licensed response before providing full functionality once received set a relatively short expiration period but longer than the refund period that google play provides currently 15 minutes also register a grace period of a few days beyond thatthe app would start checking again after the license expiration period if it failed to connect airplane mode etc it would still function until the expiration of the grace periodafter expiration of the grace period insist on a second licensed response before allowing normal app functioningafter receiving the second licensed response permanently enable all features of the app and never bother checking againif an unlicensed response is received at any point permanently thisable full functionality the user can of course revert to step 1 by deleting all app dataadditional points a suggestion was made to forgo the first license check and wait until the expiration of the return period before doing a license check the purpose of insisting on the first licensed response is to prevent the exploit where after a license check fails the user simply stops the app process clears the app data and restarts the app the app provides value even if usable for only 15 minutes at a timethe purpose of insisting on a second licensed response is to get around the buyrunbackupreturnrestore exploiti am not asking whether callback license checking is a good idea or not that is what google offers in place of their deprecated copy protection mechanism i am also well aware that no antipiracy protection is foolproof and googles entire licensing mechanism can be circumvented in which case all questions about design of a policy algorithm are irrelevant the main point of this question is the relative risks to us and benefits to the user of the above algorithm as compared to other policies such as the servermanagedpolicy,['android'] +324422,mysql2 gem cannot build native extensions our interns computer is having problems installing the mysql2 gem we just upgraded his computer from os x 106 to 108 mountain lion i have tried installing mysql through homebrew and through the 64 bit dmg installer i also tried symlinking to the dev tools as pointed out here not able to install some gems after mountain lion upgrade we have xcode 44 installed and the command line tools installed we tried a reboot after installing the command line toolsthis is his path declaration from bashrcpathusrlocalbinpathhomervmbinusrlocalmysqlbin add rvm to path for scriptingsymlinkdiegoblantonsmacbookpro3 lmrunner07 sudo ln s usrbinllvmgcc42 usrbingcc42passwordtry to install gemdiegoblantonsmacbookpro3 lmrunner07 gem install mysql2building native extensions a this could take a whileerror a error installing mysql2 a a error failed to build gem native extension a a a a userslmrunner07rvmrubiesruby193p194binruby extconfrbchecking for rb thread blocking region yeschecking for rb wait for single fd yeschecking for mysqlh yeschecking for errmsgh yeschecking for mysqld errorh yescreating makefilemakecompiling clientcin file included from userslmrunner07rvmrubiesruby193p194includeruby191rubyh32 a a a a a a a a from mysql2 exth8 a a a a a a a a from clientc1userslmrunner07rvmrubiesruby193p194includeruby191rubyrubyh105 error size of array aruby check sizeof longa is negativeuserslmrunner07rvmrubiesruby193p194includeruby191rubyrubyh109 error size of array aruby check sizeof voidpa is negativein file included from userslmrunner07rvmrubiesruby193p194includeruby191rubyinternh34 a a a a a a a a from userslmrunner07rvmrubiesruby193p194includeruby191rubyrubyh1382 a a a a a a a a from userslmrunner07rvmrubiesruby193p194includeruby191rubyh32 a a a a a a a a from mysql2 exth8 a a a a a a a a from clientc1userslmrunner07rvmrubiesruby193p194includeruby191rubysth67 error size of array ast check for sizeof st index ta is negativeclientc in function arb raise mysql2 erroraclientc98 warning iso c90 forbids mixed declarations and codeclientc in function arb mysql client socketaclientc590 warning iso c90 forbids mixed declarations and codemake cliento error 1gem files will remain installed in userslmrunner07rvmgemsruby193p194gemsmysql20311 for inspectionresults logged to userslmrunner07rvmgemsruby193p194gemsmysql20311extmysql2gem makeouti have removed the homebrew installed mysql as well as the launch agent also rm rf the gem directory userslmrunner07rvmgemsruby193p194gemsmysql20311,['ruby-on-rails'] +324430,linear gradient in chrome and safari browsers i am having trouble showing a linear gradient in safari and chrome in firefox it shows up finei am tryingbackground webkitlineargradientcenter top 9e9e9e 454545 repeat scroll 0 0 transparent background mozlineargradientcenter top 9e9e9e 454545 repeat scroll 0 0 transparentbackground mslineargradientcenter top 9e9e9e 454545 repeat scroll 0 0 transparentbackground olineargradientcenter top 9e9e9e 454545 repeat scroll 0 0 transparentthanks you for your help,['css'] +324432,const array declaration in c header file i have a class called appsettings where i have an array with a range of note frequencies i am getting several errors with the code below and i am not sure what the problem isthe error messages arestatic data member of type const float 36 must be initialized out of linea brace enclosed initializer is not allowed here before tokeninvalid inclass initialization of static data member of nonintegral typeand the codeclass appsettingspublic static const float notefrequency36 c c d d e f f g g a a b 13081 13859 14683 156 16481 17461 18500 19600 20765 220 22308 24694 26163 27718 29366 313 32963 34923 369 39200 41530 440 46616 49388 52325 55437 58733 625 65925 69846 739 78399 83061 880 93233 987 as the name suggests this is just a header file with some settings and values i need throughout the app,['c++'] +324468,msgpack c implementation how to pack binary data i am making use of c msgpack implementation i have hit a roadblock as to how to pack binary data in terms of binary data i have a buffer of the following typeunsigned char datathe data variable points to an array which is actually an image what i want to do is pack this using msgpack there seems to be no example of how to actually pack binary data from the format specification raw bytes are supported but i am not sure how to make use of the functionalityi tried using a vector of character pointers like the followingmsgpacksbuffer temp sbufferstdvectorchar vecmsgpackpacktemp sbuffer vecbut this results in a compiler error since there is no function template for tstdvectori have also simply tried the followingmsgpackpacktemp sbuffer hellobut this also results in a compilation error ie no function template for tconst char 6thus i was hoping someone could give me advice on how to use msgpack c to pack binary data represented as a char array,['c++'] +324472,how do you use object initializers for a list of key value pairs i cannot figure out the syntax to do inline collection initialization forvar a new listkeyvaluepairstring string,['c#'] +324491,how do i get java to exit when piped to head i have a java process which prints out a lot of text sometimes i just want to see a bit of the text with normal programs i can just do myprog headi will just see 10 lines of output from myprog and it will exit immediately but with java if i do java myclass headi get the first 10 lines of output but the java process would not exit until it is done with all of its processing it is like java does not care that stdout systemout is gone and the head process is dead and goneall other programs either exit silently like cat cat etcgroup headrootx0daemonx1binx2sysx3admx4ttyx5thiskx6lpx7mailx8newsx9or exit with a broken pipe errorexception like python python c while true print hi headhihihihihihihihihihitraceback most recent call last file string line 1 in moduleioerror errno 32 broken pipehow can get java to raise an exception when calling systemoutprintln when i pipe output to something like head i would love to be able to do something liketry whiletrue systemoutprintlnhi catchbrokenpipeexception e exit gracefully,['java'] +324506,android listview updating of image thumbnails using asynctask causes view recycling i have been trying to get thumbnails to work with an asynctask for image files in a listviewi have been having the common problem of row recycling and thus on scrolling thumbnails are being assigned to wrong rows i have tried adding tags to the imageview and then confirming the tags in the onpostexecute in the asynctask but however have been unsuccessful in my attempts someone please helpthe custom adapter is as follows public class mysimpleadapter extends simpleadapter public mysimpleadaptercontext context list extends mapstring data int resource string from int to supercontext data resource from to todo autogenerated constructor stub public view getviewint position view convertview viewgroup parent final view v supergetviewposition convertview parent thumbnail imageview vfindviewbyidridthumbnail checker checkbox vfindviewbyidridcheckbox filenametext textview vfindviewbyidridtext1 string pathtoimage startlocationconcat filenametextgettexttostring desctext textview vfindviewbyidridtext2 string temp desctextgettexttostring if tempequalsdirectory true checkersetenabledfalse switch theme case 0 thumbnailsetimageresourcerdrawablefolder light break case 1 thumbnailsetimageresourcerdrawablefolder dark break else checkersetenabledtrue if filenametextgettexttostringendswithjpg filenametextgettexttostringendswithpng filenametextgettexttostringendswithbmp boolean hashmapfound false for hashmapentrystring bitmap entry thumbnaillist entryset string key entrygetkey if keyequalsfilenametextgettexttostring logdtag hashmapkey found thumbnailsetimagebitmapentrygetvalue hashmapfound true if hashmapfound logdtag no hashmapkey found adding to hashmap switch theme case 0 thumbnail setimageresourcerdrawableunknown image light break case 1 thumbnail setimageresourcerdrawableunknown image dark break thumbnailsettagfilenametextgettexttostring new getbitmapsthumbnailexecutepathtoimage filenametextgettexttostring else switch theme case 0 thumbnailsetimageresourcerdrawablefile light break case 1 thumbnailsetimageresourcerdrawablefile dark break return v the asynctask is as follows class getbitmaps extends asynctaskstring void bitmap private imageview thumbnail private string imagename public getbitmapsimageview thumb todo autogenerated constructor stub thumbnail thumb override protected bitmap doinbackgroundstring pathtoimage bitmap bmp createthumbnailpathtoimage0 thumbnaillistputpathtoimage1 bmp imagename pathtoimage1 return bmp override protected void onpostexecutebitmap bmp if string thumbnailgettagequalsimagename thumbnailsetimagebitmapbmp private bitmap createthumbnailstring filepath bitmap bmp bitmapfactorydecodefilefilepath int w bmpgetwidth int h bmpgetheight if w h w 80 h 40 else if w h w 40 h 80 bmp bitmapcreatescaledbitmapbmp w h true return bmp i still cannot figure out what else to do in order to get the thumbnails to thisplay at the correct rows while scrollingplease note after scrolling away from the affected rows and scrolling back down things work fine but the scrolling problem is not going away,['android'] +324513,how to validate datetime format i am suppose to let the user enter a datetime format but i need to validate it to check if it is acceptable the user might enter ymmdd and it would be fine but they can also enter mmymmd or any other combination is there a way to validate this,['c#'] +324541,calculating text width with php gd i am simply trying to get the width of a dynamic line of text for addition to an image generated with gd php i am a little unsure how though i know how to load a font using imageloadfont but can i use a ttf file i want to know the width of text using size 12 arial font when i try to use my ttf file i get the error error reading font invalid font header if i need a gdf file where can i find a font size 12 gdf file heres my codenewfont imageloadfontfontsarialttffont width imagefontwidthnewfontfont height imagefontheightnewfont,['php'] +324566,cllocationmanager startupdatinglocation not working so now i am at least getting callbacks with the following code voidviewdidload super viewdidloadmapviewmkmapview alloc initwithframeselfviewframemapviewshowsuserlocationtruemapviewdelegateselfselfview insertsubviewmapview atindex0nsloglocationservicesenabled cllocationmanager locationservicesenabled yesno cllocationmanager newlocationmanager cllocationmanager alloc init newlocationmanager setdesiredaccuracykcllocationaccuracybest newlocationmanager setthistancefilterkclthistancefilternone self setlocationmanagernewlocationmanagerself locationmanager setdelegateselfself locationmanager startupdatinglocationnslogstarted updating location voidlocationmanagercllocationmanager manager didupdatetolocationcllocation newlocation fromlocationcllocation oldlocation nslogdid update to locationmstorelocationbuttonhiddenfalselocationnewlocationcoordinatemkcoordinateregion regionregioncenterlocationmkcoordinatespan spanspanlatitudedelta001spanlongitudedelta001regionspanspanmapview setregionregion animatedtruei can set breakpoints in the second method and nslog is reporting continual location updates but for some reason the zoom with span is not working any idea why it is got my coordinates and everything sort of scratching my head on this one,"['iphone', 'ios']" +324570,how to use date and time predefined macros in as two integers then stringify want to use date and time as integer for giving automated version to my code in compile timedefine stringizerarg argdefine str valuearg stringizerargdefine date as int str used date what can be done define time as int str uset time what can be done define version 14define complete version str valueversion date as int str time as int strand get complete version as string in a const unsigned char const unsigned char completeversion complete versionshould output 14143234 somethingone of the possible solution could be but did not work convertdatetounsignedint in context of compile time convertintdateandtimestringtojustintegersinc one can refer expanssionandstringificationhowtogetthemarconamenotitsvalue,['c'] +324588,two python modules require each others contents can that work i have a bottle webserver module with the following linefrom foobarformtools import auto process form insertand the foobarformtools module contains this linefrom foobarwebserver import redirect redirect backof course both result in the following errors respectivelyimporterror cannot import name auto process form insert importerror cannot import name redirectis it simply a fact that in python two modules cannot import each other and all module imports must be hierarchical in nature or am i doing something wrong alternatively is there a workaround short of placing all these nice functions in new modules,['python'] +324633,android cookiemanager setcookie does not set anything in my application i am getting two cookies from an httpget request and store them in the cookiemanager like thisclear old cookiescookiemanagergetinstanceremoveallcookiecookiesyncmanagergetinstancesyncsave the two cookies auth token and session infolistcookie cookies httpclientgetcookiestoregetcookiesif cookies null for cookie cookie cookies string cookiestring cookiegetname cookiegetvalue domain cookiegetdomain cookiemanagergetinstancesetcookie cookiestring systemoutprintlncookiemanagergetinstancehascookies prints false in 23 true in 403 cookiesyncmanagergetinstancesync systemoutprintlncookiemanagergetinstancehascookies also prints false in 23 and true in 403i am testing the same code in two different devices and the funny thing is the cookies are set and also transferred between launches of the application correctly in 403 but not in 233 when i say they are not set i mean that hascookies returns false and also getcookie returns null when i provide the urli have tried every possible combination for the cookie url when calling setcookie mydomainnamecom alphamydomainnamecom mydomainnamecom wmydomainnamecom none of them works please help,['android'] +324634,is string literal pool a collection of references to the string object or a collection of objects i am all confused after reading the article on javaranch site by corey mcglone the author of the scjp tip line named strings literally and thescjp java 6 programmer guide by kathy sierra cofounder of javaranch and bert batesi will try to quote what mr corey and ms kathy sierra have quoted about string literal pool1 according to mr corey mcglone string literal pool is a collection of references that points to the string objectsstring s hello assume there is no object on the heap named hello will create an string object hello on the heap and will place an reference to this object in the string literal pool constant tablestring a new stringbye assume there is no object on the heap named bye new operator will oblige the jvm to create an object on the heapnow the explanation of new operator for the creation of a string and its reference is bit confusing in this article so i am putting the code and explanation from the article itself as itis belowpublic class immutablestrings public static void mainstring args string one somestring string two new stringsomestring systemoutprintlnoneequalstwo systemoutprintlnone two in this case we actually end up with a slightly different behavior because of the keyword new in such a case references to the two string literals are still put into the constant table the string literal poolbut when you come to the keyword new the jvm is obliged to create a new string object at runtime rather than using the one from the constant tablehere is the diagram explaining itso does it mean that string literal pool too have a reference to this object here is the link to the article by corey mcglone2 according to kathy sierra and bert bates in scjp bookto make java more memory efficient the jvm set aside a special area of memory called the string constant pool when the compilerencounters a string literal it checks the pool to see if an identical string already exits or not if not then it creates a new string literal object string s abc creates one string object and one reference variable thats fine butnow the below statement got me confusedstring s new stringabc creates two objects and one reference variableit says in the book that a new string object in normalnonpool memory and s will refer to it whereasan additional the literal abc will be placed in the poolthe above lines in the book collides with the one in the article by corey mcgloneif string literal pool is a collection of references to the string object as mentioned by corey mcglone then how comeliteral object abc will be placed in the pool as mentioned in the bookand where do this string literal pool residesplease clear this doubt though it would not matter too much while writing a code but is very important from the aspect of memory management andthats the reason i want to clear this funda,['java'] +324647,unicode characters string i have the following string of charactersstring s u0625u0647u0644when i print the above sequence i getu0625u0647u062how can i get the real printable unicode characters instead of this ux representationi have found the answers systemtextregularexpressionsregexunescapes,['c#'] +324671,detecting sni server name indication browser support in javascript i want to be able to detect if the browser support sni server name indication i am hoping to redirect non compliant clients to a different addressi was thinking of loading some content through ssl and make sure it was transfered securely otherwise the browser does not support sni can this be done,['javascript'] +324694,css line height bottom only ok i am quite new to frontend development so please be nice if this is a dumb question i understand that this may not be possible but when applying lineheight to an element say an h1 the lineheight applies extra space to both the top and bottom of that elementthis kind of makes sense but i only want lineheight to be applied to the bottom of the element so the tops of my h1 h2 etc can be alined perfectly with other elementsthis jsfiddle shows the problem this jsfiddle shows what i want to achieve but am forced to use negative margins the h1 with background colour of red aligns correctly to the top of the left div but the text doesntmy question is therefore is there a way toapply lineheight to only the bottom of an element or align an element to the top of the space created by applying lineheight somehow,"['html', 'css']" +324708,why would not bundler install the json 174 gem on os x 108 i am on os x 108 with xcode 44 ruby 193 and rails 32when i clone my rails project from git and runbundle installi getinstalling json 174 errnoeperm operation not permitted usersmyuserrvmgemsruby193p0gemsjson174gitignorean error occurred while installing json 174 and bundler cannot continuemake sure that gem install json v 174 succeeds before bundlingthen i trygem install json v 174and geterror while executing gem errnoeperm operation not permitted usersscalessecrvmgemsruby193p0gemsjson174gitignoreokay permissions issue right let us trysudo gem install json v 174no go heres what i getbuilding native extensions this could take a whileerror error installing jsonerror failed to build gem native extensionusersmyuserrvmrubiesruby193p0binruby extconfrbcreating makefilemakecompiling generatorcmake usrbingcc42 permission deniedmake generatoro error 1what the heck,['ruby-on-rails'] +324743,php fatal error i am trying to implement a formabstracttype in my symfony2 application i get the following error fatal error declaration of beanoauthserverbundleformtypeauthorizeformtypebuildform must be compatible with symfonycomponentformformtypeinterfacebuildformsymfonycomponentformformbuilderinterface builder array options in srcbeanoauthserverbundleformtypeauthorizeformtypephp on line 25not sure why i am getting this error abstracttypebuildform takes a formbuilderinterface and symfony2 implements formbuilderinterface for formbuilder heres the content of my sourcephpnamespace beanoauthserverbundleformtypeuse symfonycomponentformformbuilderuse symfonycomponentformabstracttypeclass authorizeformtype extends abstracttype public function buildformformbuilder builder array options some code more code,['php'] +324746,union all with queries that have a different number of columns i have run into a case where a sqlite query i am expecting to return an error is actually succeeding and i was wondering if anyone could point out why this query is validcreate table test table k integer v integerinsert into test table k v values 4 5 select from select from select k v from test table where 1 0 union all select from select rowid k v from test table sqlfiddle of abovei would think that unioning two selects which have a different number of columns would return an error if i remove the outermost select then i receive the error i am expecting selects to the left and right of union all do not have the same number of result columns,['sql'] +324780,modifying bootstrap variables when using bootstrapsass here are all the less bootstrap variables i have used the bootstrapsass gem to add twitter bootstrap to my rails app which means i am using sass how do i modifyedit these less variables in my bootstrap and overridescscss filewhen i try to do something like thisnavbarbackground 3d368bi getsasyntaxerror in pageshomeshowing usersjustmemyprojectappviewslayoutsapplicationhtmlerb where line 5 raisedinvalid css after navbarbackground expected pseudoclass or pseudoelement was 3d368b,['ruby-on-rails'] +324788,anchor android dialog to a view i wanted to know if it is possible to anchor a dialog to a view in android or in general just to thisplay the dialog at a certain location on the screenpsi do not want to use a popupmenu because it is my understanding that one cannot customize the items thisplayed in the menu i am ultimately trying to have text and put an image next to it to alert the user that they have a message or something new to see herethanks for your time,['android'] +324794,crossover two integers bitwise i am currently trying to realize a very simple example of genetic algorithmsat one point you have to do a crossover biology with two numbers parents to get a childyou can find an explanation of crossover here how to crossover two strings 1234 abcd 12cd ab34the second illustration the easier onepoint crossover is the one i am trying to dothe chromosomes parents and child are numbers but the crossover will be a bit operationi found a solution for one of the chromosomes which is the following move the bits x amount to the right operator and then move the bits again x positions but this time to the left operatorso this would keep the end of one of the chromosomes and fill the beginning with 0sbut i do not really know how to solve the problem of the other chromosome and then also do the crossoverprobably a xor once i kept the beginning end of the chromosomes and filled the rest with 0sor should i even approach this problem from another angle,['javascript'] +324803,whats the difference between assignment operator and copy constructor i do not understand the difference of assignment constructor and copy constructor in c it is like thisclass a public a cout aa endl the copy constructora a b the assignment constructora cc a is it righti want know how to allocate memory of the assignment constructor and copy constructorthank you,['c++'] +324828,phpexe is not recognizedcreate webapp i am toying with my new install of yii framework and trying to compile my first webapp through the command line when i run yiic webapp testdrive i receive this error in my consolephpexe is not recognized as an internal or external command operable program or batch filedo i need to edit my phpini filei am currently running on wamp webserver on windows 7,['php'] +324839,is it bad to use html inside a php class is there anything wrong with using html inside a class function i call it in the dom so i do not need a string returnedpublic function the contact table div some html here div phpalso when i do need the string i use this method is there a better way or is this relatively standardpublic function get single ob start div clastaffmember single div classcol left div classthumbnail thumbnail div php thisthe contact table div div classcol right div div php content ob get contents ob end clean return contentupdatei should have explained why i am doing this i am making a wordpress plugin and want to control a post types output so i am using a filter like belowpublic function filter singlecontent global post if postpost type staffmember sm new jm staff memberpost content smget single return contentso as you can see i must return a string to the wordpress core,['php'] +324844,select onclick onchange not working i have been trying to figure this out for hours now and i cannot understand why my javascript is not working i have a select button like thisselect onclickpopulatelist option1option option2optionselectmy javascript is in the same folder and is linked asscript srcscriptjsscriptin that file the function is so simple justfunction populatelist consolelogtestand it would not work any ideas as to whyediti have tried doing the onchange onchange onclick onclick onclick ect and still nothing edit2i did not change a thing but it started working thank you all much loveedit 3 nevermind i have determined at least that it works when the script is directly in the html but not when it is in scriptjs,"['javascript', 'html']" +324905,why does not google guava preconditionss checkargument return a value i really love how guava library allows simple oneliners for checking for nullpublic void methodwithnullcheckstring couldbenull string definitelynotnull checknotnullcouldbenull sadly for simple argument check you need at least two lines of codepublic void methodwithargcheckstring couldbeempty checkargumentcouldbeemptyisempty string definitelynotempty couldbeempty however it is possible to add method which could do argument check and return a value if check successful below is an example of check and how it could be implementedpublic void methodwithenhancedargcheckstring couldbeempty string definitelynotempty enhancedpreconditionscheckargumentcouldbeempty couldbeemptyisempty static class enhancedpreconditions public static t t checkargumentt reference boolean expression if expression throw new illegalargumentexception return reference i just was wondering is that by design and if it is worth to put feature request for thatedit nizet yeah checks in methods could be clumsy however checks in constructors for nulls looks really good and saves a lot of time spent on debugging npespublic class someclasswithdependency private final somedependency somedependency public someclasswithdependencysomedependency somedependency thissomedependency checknotnullsomedependency edit accepting nizets answer because i agree with him on sideeffects and consistency reasoning also if you take a look into xaerxess comment it looks like that causing confusion amongst other developers as well,['java'] +324908,regex to detect invalid utf8 string in php we can use mb check encoding to determine if a string is valid utf8 but that is not a portable solution as it requires the mbstring extension to be compiled in and enabled additionally it would not tell us which character is invalidis there a regular expression or another other 100 portable method that can match invalid utf8 bytes in a given string that way those bytes can be replaced if needed keeping the binary information such as when building a test output xml file that includes binary data so converting the characters to utf8 would lose information so we may want to convertfoo chr128 chr255into foo128255so just detecting that the string is not good enough wed need to be able to detect which characters are invalid,['php'] +324911,capi does not support password based encryption pbe encryption i am trying to port a unix code using openssl pkcs5 pkcs7 to windowsin the case of openssl all the encodingdecoding certificates orpasswords is done transparently to the caller in the functioncms encrypt as it should becapi does the same thing in the case ofcertificate based encryption inside the function cryptencryptmessageno asn details are revealed to the caller after some googling i found out the following key generation implementation now how am i supposed to use it in capi because capi does notsupport pbe encryption at the high level pbkdf2 my guessis that the encoding has to be done somehow manually and by manually i mean writingand reading the binary representations of various asn tags how am i supposed to do this i cannot access the msasn1h api since msasn1lib is never thistributed has anyone been able to use capi interface for doing anything else other than certificates based encryption,['c++'] +324912,size of bitmap returned by camera via intent how do i get a bitmap with a certain memory friendly size from the camerai am starting a camera intent withintent cameraintent new intentandroidprovidermediastoreaction image capture cameraintentputextrareturndata truephotouri urifromfilenew fileenvironmentgetexternalstoragedirectory mytmpimgjpgcameraintentputextraandroidprovidermediastoreextra output photouri startactivityforresultcameraintent request code camerai handle the result here bitmap photo bitmap intentgetextrasgetdatabitmap photo getbitmapphotourinow if i use the commented line get the bitmap directly i get always a 160 x 120 bitmap and that is too small if i load it from the uri using some standard stuff i found method getbitmap it loads a 2560 x 1920 bitmap and that consumes almost 20 mb memoryhow do i load let us say 480 x 800 the same size the camera preview shows mewithout having to load the 2560 x 1920 into memory and scaling down,['android'] +324919,how can i put two different textures on the front and back of a plane problem i am trying to create just for fun a simple poker card with a card back and a card fronti have two different images for back and fronti easily created a plane geometry with a single texture for both sides but i really do not know how to assign a texture for a side and the other texture for the other sidei tried this without success var textureback new threeimageutilsloadtexture imagescardbackpng var texturefront new threeimageutilsloadtexture imagescardfrontpng var material1 new threemeshbasicmaterial map textureback var material2 new threemeshbasicmaterial map texturefront var geometry new threeplanegeometry 90 110 1 1 geometryfaces 0 materialspush material1 geometryfaces 1 materialspush material2 var card new threemesh geometry new threemeshfacematerialany help please,['javascript'] +324978,how to monitor focus changes well sometimes i am typing and very rarely it happens that something steals focus i read some solution even a vb watch but they do not apply to me is there any windowswide handle which handles any focus changesit does not matter in which language c c vbnet c anything net or windows related batch poweshell vbs script as long as i am able to monitor every focus change and log it into a filecmd windowvisual windowsomething like void event onwindowsfocuschangeint oldprocid int newprocidwould be very usefull or maybe there are tools for this already which i cannot find,"['c#', 'c++']" +324998,how to implement multithread safe singleton in c11 without using now that c11 has multithreading i was wondering what is the correct way to implement lazy initialized singleton without using mutexesfor perf reasonsi came up with this but tbh im not really good at writing lockfree code so im looking for some better solutions consoleapplication1cpp defines the entry point for the console application include atomic include thread include string include iostreamusing namespace stdclass singletonpublic singleton static bool isinitialized return flag2 static bool initizalizeconst string name if flag2 return false already initialized if flag1 return falsesomebody else is initializing if flag0 int exp0 int desr1 bool atomic compare exchange strongstdatomict obj t exp t desr bool willinitializestdatomic compare exchange strongflag exp desr if willinitialize some other thread cased before us stdcoutsomebody else cased at aprox same time endl return false else initialize implname assertflag1 flag2 return true static void clear nameclear flag0privatestatic void initialize implconst string name namename static atomicint flagstatic string nameatomicint singletonflag0string singletonnamevoid mythreadfunction singleton s bool initializedbyme sinitizalize1701 if initializedbyme sclearint main while true stdthread t1mythreadfunction stdthread t2mythreadfunction t1join t2join return 0note that clear is just for testing real singleton wouldnt have that function,['c++'] +325003,why does zindex 1 appear above zindex 1 explain this behaviordiv stylezindex 1divdivdivdivdivdivdivdiv position relative background red width 100px height 100px divbefore position absolute background blue width 100px height 100px zindex 1 content left 5px top 5pxonly difference is the first div has zindex 1 set,['css'] +325053,bug in arrayistructuralequatablegethashcode while writing my own immutable bytearray class that uses a byte array internally i implemented the istructuralequatable interface in my implementation i delegated the task of calculating hash codes to the internal array while testing it to my great surprise i found that my two different arrays had the same structural hash code ie they returned the same value from gethashcode to reproduceistructuralequatable array11 new int 1 1 istructuralequatable array12 new int 1 2 istructuralequatable array22 new int 2 2 var comparer equalitycomparerintdefaultconsolewritelinearray11gethashcodecomparer 32consolewritelinearray12gethashcodecomparer 32consolewritelinearray22gethashcodecomparer 64istructuralequatable is quite new and unknown but i read somewhere that it can be used to compare the contents of collections and arrays am i wrong or is my net wrongnote that i am not talking about objectgethashcodeeditso i am apparently wrong as unequal objects may have equal hash codes but is not gethashcode returning a somewhat randomly thistributed set of values a requirement after some more testing i found that any two arrays with the same first element have the same hash i still think this is strange behavior,['c#'] +325127,python beautifulsoup extract text from anchor tag i want to extract text from following src of the image tag and text of the anchor tag which is inside the div class data i successfully manage to extract the img src but i am having trouble on extracting the text from the anchor taga classtitle hrefnikon coolpix l26 161 mp digital camera with 5x zoom nikkor glass lens and 3inch lcd reda here is the link for the entire html pagehere is my codefor div in soupfindalldiv attrsclassimage print n for data in divfindnextsiblingdiv attrsclassdata for a in datafindalla attrsclasstitle print atext for img in divfindallimg print imgsrcwhat i am trying to do is extract the image src link and the title in side the div classdataso for example a classtitle hrefnikon coolpix l26 161 mp digital camera with 5x zoom nikkor glass lens and 3inch lcd reda i want to extract nikon coolpix l26 161 mp digital camera with 5x zoom nikkor glass lens and 3inch lcd red,"['python', 'html']" +325147,unexpected return value from fread include stdiohinclude stdinthinclude stdlibhint main file bmp null uint32 t offset uint8 t temp null size t read unsigned int x dim 600 y dim 388 bmp fopentest colourbmp r if bmp return 1 get the image data offset fseekbmp 10 seek set fgetscharoffset 4 bmp printfoffset un offset temp malloc3x dimy dimsizeofuint8 t if temp return 1 go the the position where the image data is stored fseekbmp offset seek set copy image data to array printfu bytes requestedn 3x dimy dim read freadvoidtemp sizeofuint8 t 3x dimy dim bmp printfiu bytes readn read fclosebmp freetemp return 0i am using the above code to read the rgb data of a 24bit per pixel bmp image to an array the offset from the start of file where the image data starts after the bmp header is given at offset 10 according to the bmp specification i get the following output when executing the above codeoffset 54698400 bytes requested33018 bytes readthe offset output seems to be correct because the file size is 698454 bytes 69840054 however the value returned by fread seems to indicate that not the entire image data could be read however i am subsequently using the data in the temp array to convert the rgb data to greyscale and writing this data to a bmp file again visually checking the output image does not indicate any errors ie it seems as if i actually read the entire input image in the first place although fread seems to indicate differentlycan someone explain this behaviour,['c'] +325224,dbwritetable append t is overwritng in r i am using rjdbc for accessing mysql from r earlier i used to work with rmysql which is not available for r 215 there were so many thiscussions around so but still i could not able to use rmysql package in r 215 so switched to rjdbcwhen i am using dbwritetable append t command for appending records into mysql table it is simply overwriting please see the code below setting environment variable for mysql serversyssetenvmysql homecprogram files x86mysqlmysql server 51libraryrjdbcmysql connectiondrv jdbccommysqljdbcdrivermysqlconnectorjava505jar conn dbconnectdrv retail userroot passwordabcdbwritetableconn customer tbl x rownamesfappend tcustomer tbl is overwriting everytime instead of appendingcan somebody help in how to tackle this issuethankssuresh,['mysql'] +325236,how to change the mailer contenttransferencoding settings in rails the contenttransferencoding setting is set to 7bit by defaultthe mail server postfix is breaking down the email header by bunch of 10 caracteres meaning that if you have a long email using html for example you end up having spaces in the middle of your text or links see this thread for more info following the rails actionmailer documentation adding the following code to my app file should make it but it does not workactionmailerbasedefault contenttransferencoding quotedprintable i still end up with the defaultmimeversion 10contenttype multipartalternative boundary mimepart 50166adf1e043 1b9810829142282d charsetutf8contenttransferencoding 7bitmy email look like thatdef new registered useruser id user userfinduser id set locale userlocale mail subject i18n subject to useremail with name do format formattext render layout text email formathtml end endany idea on what else should i change,['ruby-on-rails'] +325239,tool to analyze size of elf sections and symbol i need a way to analyze output file of my gcc compiler for arm i am compiling for bare metal and i am quite concerned with size i can use armnoneeabiobjdump provided by the crosscompiler but parsing the output is not something i would be eager to do if there exists a tool for this task do you know of such a tool existing my search turned out no resultsone more thing every function in my own code is in its own section,['c'] +325253,ifstreamread does not tell how many bytes it really reads i am using ifstreamread to read a file ifstream ifsatxtchar buf1024ifsreadbuf 1024but atxts size might be less than 10 bytes so how am i supposed to know how many bytes have been read from ifs,['c++'] +325267,knockout nested foreach let us i have humans with cats with kittens class master string mastername cat cats class cat string catname kitten kittensclass kitten string kittenname now i want show all my kittens with cats with masters in html i use ko foreach humans ko foreach cats ko foreach kittens p databinddatakittennamepp databindparentcatnamepp databindp how get masters name ko ko ko,['javascript'] +325288,create a nonowning shared ptr i am pretty new to c11 and am now working on improving my c skills by trying to avoid direct usage of pointers i am trying to write a sprite manager that keeps track of previously loaded sprites and frees unused ones i am trying to use shared ptr pointer to the bitmap for this but the manager also has to keep a shared ptr to create the sprites with so the reference count does not drop to 0 can i somehow declare the parent shared ptr in my manager nonowning so it does not count as a reference and still create owning copies of that shared ptr,['c++'] +325302,programmatically change the src of an img tag how can i change the src attribute of an img tag using javascriptimg srctemplateeditpng nameeditsaveat first i have a default src which is templateeditpng and i wanted to change it with templatesavepng onclickupdatedheres my html onclicka href onclickeditimg srctemplateeditpng ideditsaveaand my jsfunction edit var inputs documentmyform forvar i 0 i inputslength i inputsithisabled false i have tried inserting this inside the edit it works but need to click the image twicevar edit save documentgetelementbyideditsave edit saveonclick function thissrc templatesavepng,['javascript'] +325315,how to convert javascript date to date in java i need to convert jsdate to javautildate i searched but i could not find anything so could you help me with this problemedit i do this convertion process on gwt secreen i have datepicker on screen and it gives me jsdate value when i use it is getvalue method so i am suppose to put this value into property of an object which has date typeobjectnamesetdatepickernamegetvaluei hope my edit will be more clear edit2 this line is the solution of my problemmyobjectsetdatenew datelong mypickergetvaluegettime,"['java', 'javascript']" +325342,chrome setselectionrange not work in oninput handler i am working with some autocompletion code setselectionrange is used to select text been completed in oninput event handler it works at least in firefox 14 but not in chrome6 17simplified code snippet demonstrating the problem is like thisinput typetext oninputselect function selecte var s thisvalue if slength thissetselectionrangeslength1 slengthi debugged the code in chrome and it turns out that text has been selected at first right after the setselectionrange been executed but the selection thisappeared laterif i bind the handler to onclick instead of oninput like thisinput typetext onclickselect then both browsers work finecan anyone please give me some clue to make selection work in chrome,['javascript'] +325378,align 2 table column widths with each other i have 2 tables one on top of the other and i would like to align their column widths exactly with each other is there a way to do this tried fixed table col widths etc no joyyou can see on fiddle the columns are slightly off each otherhtmltable classtblresults txtblack tr classtblresultshdr bold td classcol1companytd tdcurrencytd tdbidtd tdasktd tdytd voltd tr tr td classcol1abctd tdgbptd td94td td16td td3567900td tr tr td classcol1deftd tdgbptd td3td td46td td10td tr tr td classcol1ghitd tdgbptd td3td td46td td10td tr tr td classcol1jklmtd tdgbp td td7td td46td td560td trtable table classtblresults txtblack margintop10 tr td colspan5 classbold investmentstd tr tr td classcol1ghjktd tdgbptd td13td td6td td130td tr tr td classcol1asdsatd tdgbptd td120td td46td td160td tr tr td classcol1dfdsfsdf td tdgbptd td1td td4td td130td tr tableacsstabletblresults width100 width995 border 1px solid b9b8b8 top 0tabletblresults trtblresultshdr background lightgreytabletblresults trtblresultshdr td padding 6pxtabletblresults td padding 8px border 1px solid b9b8b8tabletblresults tdcol1 width 70a,"['html', 'css']" +325409,php scrape article excerpt like readability i have seen this question but it does not really satisfy what i am looking for that questions answers were either lift from the meta description tag and the second was generating an excerpt for an article you already have the body fromwhat i want to do is actually get the first few sentences of an article like readability does whatt the best method for this html parsing heres what i am currently using but this is not very reliablefunction guessexcerpturl html file get contents curlurl doc new domdocument docloadhtmlhtml metas docgetelementsbytagnamemeta for i 0 i metaslength i meta metasitemi ifmetagetattributename description description metagetattributecontent return descriptionfunction file get contents curlurl ch curl init curl setoptch curlopt header 0 curl setoptch curlopt returntransfer 1 curl setoptch curlopt timeout 5 curl setoptch curlopt url url curl setoptch curlopt followlocation 1 data curl execch curl closech return data,['php'] +325410,fragment compatability onactivityresult not working i have been working on an application for android that utilizes the android comparability library androidsupportv4 before sdk 20 i was able to compile my application with the following usessdk entry in my manifest usessdk androidminsdkversion7 all my fragments that started an activity for result received their results properlyone day before i updated to sdk 20 i was fixing lint issues and i added androidtargetsdkversion to the manifest per the lint flags request and i soon realized that none of my fragments were receiving their onactivityresilt callsnow every since i have updated to sdk 2001 i am forced to utilize the androidtargetsdkversion in usessdk entry in my manifest otherwise rjava is never generatedhere is my current usessdk manifest entryusessdk androidminsdkversion7 androidtargetsdkversion16 currently because of this odd bug my application is currently still broken i have tryied updating my compatibly library the the latest version r9also i have double checked all my startactivityforresult calls in the fragments they all use the proper calls through the fragments method ie thisstartactivityforresultintent requestcodenot thisgetactivitystartactivityforresultintent requestcodemy current development environmentandroid sdk 2001android sdk platform tools 13adt 2002any help would be greatly appreciated as this bug is currently the brick wall that is preventing my final beta testseditheres my output of ant debug ant debug buildfile homerickydevelopmentworkspacelocation ringerlocationringerbuildxmlsetmodechecksetdebugfilescheckenv checkenv android sdk tools revision 2001 checkenv installed at appandroidsdklinux 86setup echo project name listactivity gettype project type applicationsetdebugmodedebugobfuscationcheckbuildsetup echo resolving build target for listactivity gettarget project target google apis gettarget vendor google inc gettarget platform version 41 gettarget api level 16 echo echo creating output directories if needed echo echo resolving dependencies for listactivity dependency library dependencies dependency dependency dependency ordered libraries dependency dependency dependency api15 adding annotationsjar to the classpath echo echo building libraries with debugnodepssetmodechecksetdebugfilescheckenv checkenv android sdk tools revision 2001 checkenv installed at appandroidsdklinux 86setup echo project name locationlib gettype project type android librarysetdebugmodedebugobfuscationcheckbuildsetup echo resolving build target for locationlib gettarget project target google apis gettarget vendor google inc gettarget platform version 41 gettarget api level 16 echo echo creating output directories if needed echo echo resolving dependencies for locationlib dependency library dependencies dependency no libraries dependency dependency dependency api15 adding annotationsjar to the classpathprebuildcodegen mergemanifest no changes in the androidmanifest files echo handling aidl files aidl no aidl files to compile echo echo handling renderscript files renderscript no renderscript files to compile echo echo handling resources aapt no changed resources rjava and manifestjava untouched echo echo handling buildconfig class buildconfig no need to generate new buildconfigprecompilecompile echo creating library output jar filepostcompileobfuscatedex echo library project do not convert bytecodecrunch crunch crunching png files in source dir homerickydevelopmentworkspacelocation librarylocationlibres crunch to destination dir homerickydevelopmentworkspacelocation librarylocationlibbinres crunch crunched 0 png files to update cachepackageresources echo library project do not package resourcespackage echo library project do not package apkpostpackagedodebug echo library project do not create apk propertyfile updating property file homerickydevelopmentworkspacelocation librarylocationlibbinbuildprop propertyfile updating property file homerickydevelopmentworkspacelocation librarylocationlibbinbuildprop propertyfile updating property file homerickydevelopmentworkspacelocation librarylocationlibbinbuildprop propertyfile updating property file homerickydevelopmentworkspacelocation librarylocationlibbinbuildproppostbuilddebugnodepssetmodechecksetdebugfilescheckenv checkenv android sdk tools revision 2001 checkenv installed at appandroidsdklinux 86setup echo project name exceptionhandlerlib gettype project type android librarysetdebugmodedebugobfuscationcheckbuildsetup echo resolving build target for exceptionhandlerlib gettarget project target android 41 gettarget api level 16 echo echo creating output directories if needed echo echo resolving dependencies for exceptionhandlerlib dependency library dependencies dependency no libraries dependency dependency dependency api15 adding annotationsjar to the classpathprebuildcodegen mergemanifest no changes in the androidmanifest files echo handling aidl files aidl no aidl files to compile echo echo handling renderscript files renderscript no renderscript files to compile echo echo handling resources aapt no changed resources rjava and manifestjava untouched echo echo handling buildconfig class buildconfig no need to generate new buildconfigprecompilecompile echo creating library output jar filepostcompileobfuscatedex echo library project do not convert bytecodecrunch crunch crunching png files in source dir homerickydevelopmentworkspaceexception handler libraryexceptionhandlerlibres crunch to destination dir homerickydevelopmentworkspaceexception handler libraryexceptionhandlerlibbinres crunch crunched 0 png files to update cachepackageresources echo library project do not package resourcespackage echo library project do not package apkpostpackagedodebug echo library project do not create apk propertyfile updating property file homerickydevelopmentworkspaceexception handler libraryexceptionhandlerlibbinbuildprop propertyfile updating property file homerickydevelopmentworkspaceexception handler libraryexceptionhandlerlibbinbuildprop propertyfile updating property file homerickydevelopmentworkspaceexception handler libraryexceptionhandlerlibbinbuildprop propertyfile updating property file homerickydevelopmentworkspaceexception handler libraryexceptionhandlerlibbinbuildproppostbuilddebugprebuildcodegen mergemanifest merging androidmanifest files into one mergemanifest merging manifests from project and 2 libraries mergemanifest warning androidmanifestxml3 androidmanifestxml3 main manifest has but library uses targetsdkversion16 mergemanifest note main manifest lacks a declaration which defaults to value minsdkversion or 1 mergemanifest warning androidmanifestxml3 androidmanifestxml13 main manifest has but library uses targetsdkversion16 mergemanifest note main manifest lacks a declaration which defaults to value minsdkversion or 1build failed appandroidsdklinux 86toolsantbuildxml616 nulltotal time 2 secondsediti looked into appandroidsdklinux 86toolsantbuildxml616 and found that the following line threw the null enabledmanifestmergerenabled here is the entire block i am going to try to thisable the manifest merger option an see what happenseditit would seem that removing manifestmergerenabledtrue from projectproperties has solved my problem the project now compiles and works perfectly i think i should report this bug to the android team my manifest has the following entry usessdk androidminsdkversion7 however onactivityresult still is not called if i raise the targetsdkversion higher than 7 so this does not really solve the root problem but my project is now working properly,['android'] +325426,why would application sometimes restart on killprocess ordinarily exiting my application by callingandroidosprocesskillprocessandroidosprocessmypidperforms well without incidentbut every once in a while the application will restart again after exitingthe relevant log snippet shows631 iprocess15495 sending signal pid 15495 sig 9641 waudioflinger121 write blocked for 252 msecs 1279 delayed writes thread 0xdc18651 iactivitymanager164 process comefmyapp pid 15495 has died651 iwindowmanager164 win death window463659e8 comefmyappcomefmyappmainactivity pausedfalse661 iaudioservice164 audiofocus abandonaudiofocus from androidmediaaudiomanager460b2b98701 iactivitymanager164 start proc comefmyapp for activity comefmyappmainactivity pid15589 uid10077 gids3003i know that by the design of the android os killprocess is not the proper way to terminate an application this is because killprocess stops the process immediately without giving any way or chance for the app to prevent it or prepare for it i know that when i call finish the application stack is just pushed to the background and still exists in the memory android itself decides when to close the application ie remove its instance from the memory and generally this is done when the application becomes the oldest not used for the longest time its behavior is actually more predictable if it is really the last onethe problem is that finish only stops and destroys the activity for which it was called it does not stop other activities spawned by the application or other activities so for ease of test debug during development i am using killprocess as a convenient shortcutbut now i see that this has the side effect of the application sometimes restarting immediately after killing itself all within 30 millisecondsa straightforward solution would be to iterate through all applications activities and finish them but before proceeding with this i am dying to understand what in the android os makes an application resurrect itselfwhy would android make a killed application restart and why inconsistently ie sometimes,['android'] +325428,php 54 installation on mac osx lion from homebrew mysqli extension missing i installed php 54 from homebrewand also mysql i am using the inbuilt apache server with websharingi have phpmyadmin installed and it tells me the mysqli extension is missingi did the following stepsin the phpini i set extension mysqlisomysqlidefault socket tmpmysqlsockthen restarted apachewhen i check with phpinfo i do not see any mysql extension the error in phpmyadmin is still therei basically do not really see how i could check if mysqli has come with my php install or not,['php'] +325433,missing run as php script in eclipse i have eclipse 42 juno pdt 311 freshly installed and i have selected php perspective i have created empty test project php project and added testphp file to it now i want to run this file as php script but i simply do not have it in my run as context menu when i right click on testphp file please help i am exhaustedadditional informationi have php5 installed on my pc and i can run php files in my windows command line window using php filenamephp syntaxi have tried same thing in socalled allinone eclipsepdt package same problem,['php'] +325466,how to reduce the variability in android camera shutter lag given a known periodic motion eg walking i would like to take a full resolution snapshot at the same point in the motion ie the same time offset within different periods however on the nexus s currently running os 411 but the same was true of previous os versions i am seeing so much variability in the shutter lag that i cannot accurately plan the timing of the snapshot here is a histogram of the shutter lags of 50 photographs i measured the shutter lag with one systemnanotime just before cameratakepicture and another systemnanotime at the beginning of the shutter callback the camera lens was consistently covered to remove any variability due to lightingis there anything i can do in the application to reduce this shutter lag variability in this application the mean lag can be any duration but the standard deviation must be small much smaller than the 05 s standard deviation of the shutter lags shown in the above histogram i am hoping someone has a clever suggestion if i do not get any suggestions i will post a feature request in the android bug trackerupdatei turned off autofocus by setting focus to infinity following richardcs suggestion at fromgroupstopicandroiddeveloperswahhtickra0it helped as shown in the following histogram any ideas to reduce the shutter lag variability even moreupdate 2i thisabled the remaining auto parameters white balance scene mode flash the following histogram of shutter lag time variability seems to be about as good as it gets for a nexus s running os 411 it would be nice to have much less variability in the shutter lag time perhaps by specifying an optional minimum shutter lag time in cameratakepicture which would delay the shutter if it were ready before the specified minimum i have posted a feature request to the android issue tracker if you are also interested in getting the feature star it at,['android'] +325486,nav bar wrapping on smaller resolutions i am trying my hand at html5css3 as a learning process but i am struggling to create a navigation bar for links to other sections across my pagesi adapted the code from a tutorial found and it works but only when viewed on a resolution of 1080p if the width is smaller the bar wraps onto other lines how do i ensure that the nav bar only takes up one line shrinks to fit no matter what resolution the user is usinghere is my css code for the nav bar please note under nav i have set width to 3 and padding to the same in order to centre the buttons i do not know if this is the cause nav thisplayblock position absolute left0 whitespacenowrap margin 0 auto width 3 backgroundcolorff6600 paddingleft 3 paddingright 3 nav ul margin 0 auto width 100 liststyle none thisplay inline whitespacenowrap nav ul li float left position relative whitespacenowrap nav ul li a thisplay block margin 0 auto width 150px fontsize 16px fontfamily century gothic lineheight 44px textalign center textdecoration none color575757 whitespacenowrap nav ul ul width 200px positionabsolute top9px left0 opacity 0 webkittransition opacity 4s easeinout moztransition opacity 4s easeinout otransition opacity 4s easeinout transition opacity 4s easeinout zindex497 background3 padding 2px border1px solid 4 bordertopnone boxshadow1 0 3px 4px nav ul ul li a thisplay block width 200px textalign left paddingleft 3px fontsize 14px nav ul lihoverul opacity 1 positionabsolute top98 left0nav ul li ahover color f backgroundcolor cc3300 nav ul liselected a color f backgroundcolor cc3300,['css'] +325538,postgresql equivalent of mysql memory tables does postgresql have an equivalent of mysql memory tables these mysql memory tables can persist across sessions ie different from temporary tables which drop at the end of the session i have not been able to find anything with postgresql that can do the same,['mysql'] +325583,how do i install the libv8 ruby gem on a fresh mountain lion install i have been racking my head on this one i have followed suggestions in several related posts but to no availi am starting from a fresh install of mountain lion installed the command line tools and have ruby 187 successfully installed based on a few other posts i have found for installing gcc42 via homebrew and adding a symlink to usrbingcc42now however i am unable to successfully install libv8 the error below is as far as i have gotten off of the existing suggestions any additional inputgeminstallerextensionbuilderror error failed to build gem native extension usersericrbenvversions187p352binruby extconfrb creating makefileunable to find a compiler officially supported by v8it is recommended to use gcc v44 or highertraceback most recent call last file buildgypgyp line 18 in module sysexitgypmainsysargv1 file buildgyppylibgyp init py line 480 in main generatorgenerateoutputflat list targets data params file buildgyppylibgypgeneratormakepy line 2085 in generateoutput part of allqualified target in needed targets file buildgyppylibgypgeneratormakepy line 756 in write selfxcode settings selfabsolutify selfpchify file buildgyppylibgypgeneratormakepy line 1132 in writesources cflags selfxcode settingsgetcflagsconfigname file buildgyppylibgypxcode emulationpy line 258 in getcflags sdk root self sdkpath file buildgyppylibgypxcode emulationpy line 247 in sdkpath return ospathjoinself getsdkbasedir ssdk sdk root file buildgyppylibgypxcode emulationpy line 233 in getsdkbasedir raise exceptionerror d running xcodeselect jobreturncodeexception error 2 running xcodeselectmake outmakefilex64 error 1using compiler ggyp generatorsmake buildgypgyp generatoroutputout buildallgyp ibuildstandalonegypi depth dv8 target archx64 sx64 dhost archx64xcodeselect error no xcode is selected use xcodeselect switch pathtoxcode or see the xcodeselect manpage man xcodeselect for further informationgem files will remain installed in usersericdevelopmentpar8ovendorbundleruby18gemslibv831183 for inspectionresults logged to usersericdevelopmentpar8ovendorbundleruby18gemslibv831183extlibv8gem makeoutan error occured while installing libv8 31183 and bundler cannot continuemake sure that gem install libv8 v 31183 succeeds before bundling,['ruby'] +325593,flash screen white at moment of camera capture i would like to flash and then fade out the screen right at the moment of camera capture to give the user the indication that a picture has been taken besides just an auditory cluewhere would such an animation be placed also how would it be implemented such that i can control the duration of the fadeout note i have created a custom overlay for my particular camera pickeranything indicating that a picture has been taken is what i am looking for,['ios'] +325600,uitextposition to nsrange i need to use nsstringfromrange but i only have a start and end uitextpositions how do you convert uitextposition to nsrangensmutablearray wordarray nsmutablearray allocinitiduitextinputtokenizer tokenizer tvtokenizeruitextposition start tvbeginningofdocumentwhile start isequaltvendofdocument uitextposition end tokenizer positionfrompositionstart toboundaryuitextgranularityword indirectionuitextstoragedirectionforward nsstring word tv textinrangetv textrangefrompositionstart topositionend wordarray addobjectnsstringfromrangensrange range start end,['ios'] +325641,getting url parameter in java and extract a specific text from that url i have a url and i need to get the value of v from this urlhere is my url rcip6orqreany useful and fruitful help is highly appreciated,['java'] +325665,check for null in foreach loop is there a nicer way of doing the followingi need a check for null to happen on fileheaders before proceeding with the loop if fileheaders null foreach var h in fileheaders set lots of properties some other stuff in short it looks a bit ugly to write the foreach inside the if due to the level of indentation happening in my codeis something that would evaluate to foreachvar h in fileheaders null do stuffpossible,['c#'] +325669,how does one use resourcesgetfraction how do i store a fractional value like 31416 in resources what to write in the xml and how to retrieve it in java codethe documentation for getfraction statespublic float getfraction int id int base int pbaseretrieve a fractional unit for a particular resource idparametersbase the base value of this fraction in other words a standard fraction is multiplied by this valuepbase the parent base value of this fraction in other words a parent fraction nnp is multiplied by this valuereturns attribute fractional value multiplied by the appropriate base valuethis answer shows a simple example of percentages without going into the details of what the arguments mean,['android'] +325691,collapsing margins in android layouts is it possible to make margins collapse in android let us say i have a linearlayout and add three textviews each with an androidlayout margin of 10dp i get the following resulthowever i would like to get this resulti know that i could workaround this by setting different topbottom margins for the different itemsset the top margin of the first item and the bottom margin of the last item to 10dp set the remainding topbottom margins to 5dpbut that makes the design more complicated especially if the textviews are dynamically created is there some way to make the margins behave like in css for an explanation of why this makes sense see what is the point of css collapsing margins,['android'] +325710,optimize javascript css download i have a number of pages for my website all use jquery and json and the same css except for a few pages the first page is user login as the user will take time to type in his username and password i want to download all the required javascript and css files for the entire user session during login how can this be done the header is the same for all pages how do i optimize it,"['php', 'javascript', 'jquery', 'css']" +325717,how to read all files in a folder using c i wish to read all the text files in a particular folder the files names do not have any common pattern in them else the task would have been easierread a file from the directory perform a common operation write output to a common file read the next fileit will be good if i could work around with subfolders as well but even the basic implementation is sufficienti tried looking at the previously asked related questions here here here and here but none of them give a c and linux specific answer which i need edit so this is what i wrote based on the answers receivedinclude stdiohinclude stdlibhinclude stringhinclude systypeshinclude direnthinclude unistdhinclude errnohint mainint argc char argv dir fd struct dirent in file file output file file entry file char bufferbufsiz opening common file for writing output file fopenhomepnpsnort rules folderrulesoutputtxt a if output file null fprintfstderr error failed to open output filen return 1 scanning the in directory if null fd opendir homepnpsnort rules folderrules fprintfstderr error failed to open input directoryn fcloseoutput file return 1 while in file readdirfd on linuxunix we do not want current and parent directories if youre on windows machine remove this two lines if strcmp in filed name continue if strcmp in filed name continue open directory entry file for common operation todo change permissions to meet your need entry file fopenin filed name r if entry file null fprintfstderr error failed to open entry filen fcloseoutput file return 1 doing some stuff with entry file while fgetsbuffer bufsiz entry file null use fprintf or fwrite to write some stuff into common file fprintfoutput file reading file s in filed name when you finish with the file close it fcloseentry file do not forget to close common file before leaving fcloseoutput file return 0 and the error received pnppnplaptopsnort rules folder aout error failed to open entry file,['c'] +325719,is a qtbased ui reliable enough to be used in a medical device i work for a small company developing a complex medical device with a rich ui we are currently at the early stages of design the application is targeted for windows desktop only and preferably should be written only in cafter some research done we tend to choose qt to develop the ui it seems to answer all our needs namely a modernlooking and highly responsive ui can be developed the development is rather fast after getting familiar memory usage is somehow reasonable free for commercial use bonus for usmy question is is it reliable enough for a medical device we absolutely cannot accept any crash in the middle of an examination i understand that first of all it depends of course on the quality of code we write but still i would like to know if anyone has encountered any mysterious crashrelated problems that were particularly hard to resolve especially when using qml that is a scripting language and it can naturally result in errors hard to predict and explainthe cost of encountering such an issue in production will be very high for us so we extremely need a right decision to be made before we go for any specific package if you know any other qtrelated problem that could arise in our particular context i admit that it was impossible to do a very extensive package testing i will highly appreciate mentioning it too,['c++'] +325768,show dropdown programatically in actionbar actionbarsherlock i have an activity using actionbarsherlock with actionbarnavigation mode listwhen entering the page i want the spinner in the action bar to expand programmatically after it is populated with items so the user needs to pick an item as of now the first item in the adapter is selected automaticallyi cannot figure out a nice way to expand the spinner in the action bar programmatically do i need to use a cutom view to achieve this behaviori have looked on the action bar with the hierarchyviewer and the spinner does not have an id set any ideas,['android'] +325780,substr with japanese characters issue i am echoing japanese characters fine but when i try to substr and echo out part of the string it just turn to question marks i12i12i12note i set my header to utf8 headercontenttype texthtml charsetutf8and made the meta meta httpequivcontenttype contenttexthtml charsetutf8 word aecho word works just fineecho substrword1 now it just echoes i12this one also failedecho word0 echoes i12,['php'] +325788,hadoop cannot use jps command the problem is hdusersaketk53smusrlocalhadoop jps the program jps can be found in the following packages openjdk6jdk openjdk7jdk try sudo aptget install selected packagemy configuration is hdusersaketk53smusrlocalhadoop java versionjava version 160 33javatm se runtime environment build 160 33b04java hotspottm 64bit server vm build 208b03 mixed modeset up confhadoopenvshhdusersaketk53smusrlocalhadoop cat confhadoopenvsh grep java home the only required environment variable is java home all others are set java home in this file so that it is correctly defined onexport java homeusrlibjvmjdk160 33i know there is a question similar to this onebut i have installed sun jdk here so any help would be appreciated,['java'] +325820,how can i tell magicalrecord to not use the file based core data but an in memory setup i followed this great article to get into unit testing regarding core data the setup seems simple and involves just some view lines of code voidsetup magicalrecord setdefaultmodelwithclaself class magicalrecord setupcoredatastackwithinmemorystore voidteardown magicalrecord cleanup voidtestsomecalculationonmyentity nsnumber count myentity mr numberofentities stasserttestentity customcalculation expectedvalue expected a good calculationendthe problem is that each time i for example check for the amount of entities in the in memory set up of core data by calling myentity mr numberofentities like above i get the amount of objects which are stored in the file based setup which are a couple of thousand objects how does this happen i mean the second line in setup indicates the in memory one does not it and this case should return 0 as the amount of objects storedthanks for any suggestionseditcasademora put me on the right track the following works setup works fine for me now voidsetup magicalrecord cleanup this solved the mystery i do not now why i had to remove this line though magicalrecord setdefaultmodelwithclaself class magicalrecord setupcoredatastackwithinmemorystore voidteardown magicalrecord cleanup voidtestsomecalculationonmyentity nsnumber count myentity mr numberofentities stasserttestentity customcalculation expectedvalue expected a good calculationend,['objective-c'] +325838,check for file exists or not in sql server solution made a post about this question using stackoverflow question to help othersid filepath1 cvishwanath21776656docx2 cvishwanathvishs srv req 2009txt3 cusersdalvidwdw20sharedamd64exe4 cusersdalvi1txti have table like this created in my db server i have stored file paths in it filepath column now i have to check using sql whether the file exists in my machine if it exists i need to add temporary column in my table showing yes if exists and no it does not existsi wrote this code which works for 1 file but i do not know how to use it for my tabledeclare isexists intexec masterdboxp fileexist cvishwanath21776656docx isexists outputselect case isexists when 1 then yes else no end as isexiststhe final output should like thisid filepath isexists1 cvishwanath21776656docx yes2 cvishwanathvishs srv req 2009txt yes3 cusersdalvidwdw20sharedamd64exe yes4 cusersdalvi1txt no,['sql'] +325869,js how to get the element clicked on how would you check to see which item was clicked in the document given this codeif documentaddeventlistener documentattachevent documentfireevent documentattachevent onclick function,"['javascript', 'jquery']" +325876,android sharedpreferences in fragment i am trying to read sharedpreferences inside fragment my code is what i use to get preferences in any other activity sharedpreferences preferences getsharedpreferencespref 0i get error cannot make a static reference to the nonstatic method getsharedpreferencesstring int from the type contextwrapper i have tried to follow these links but with no luck accessing sharedpreferences through static methods and static sharedpreferences thank you for any solution,['android'] +325929,how do i encode and decode a base64 string how do i return a base64 encoded string given a stringhow do i decode a base64 encoded string into a string,['c#'] +325936,thisplaying unix color on windows cmd eg a31m i have recently started doing some ruby on rails development on windows 7 and have found a number of commands rspec guard etc output colour codes that just show up in text on the windows command line or through console2 which i use ega31mrspec specviewsusersindexhtmlerb specrb21a0m a36m usersindex renders a list of usersa0ma31mrspec specrequestshomes specrb9a0m a36m homes get homes a0ma31mrspec specviewsusersnewhtmlerb specrb13a0m a36m usersnew renders new user forma0ma31mrspec specviewsusersshowhtmlerb specrb13a0m a36m usersshow renders attributes in pa0mi am aware you can turn the color off for most tools by taking the color command out out of the config files eg the respc file but it is a pain to have to do this for everything and colour coding would be nice any ideas how i can get these to thisplay properly in windows,['ruby-on-rails'] +325947,stop safari 6 js debugger from being so verbose i am finding the safari 6 debugger to be extremely verbose and pauses execution of js for every minor exception does anyone know how to thisable thisexampleopen web inspector in safari 6visit notice how even if you were in the js console youd be switched into debug view to see the error this is not very good and slows debugging down considerably,['javascript'] +325951,why are not windows constants included in net every time i see code calling into say kernel32dll or user32dll the snippet always even on msdn requires the developer to hard code any required constants wm setredraw 11 for example into the routine since these constants never change by definition and have one standard definition always why does not net provide them somewhere i feel like we all end up creating our own libraries of constants and standard windows dll calls as we need them it seems like this duplication of effort is wasteful and prone to errorperhaps i have not looked hard enough and they are all in there somewhere if so could someone please provide their location,['.net'] +325969,resharper line breaks and wrapping so thiscmd new odbccommand stringformat select from bobby tables where name 0 little bobby drop tables odbcconnection gets formatted tocmd new odbccommand stringformat select from bobby tables where name 0 little bobby drop tables odbcconnection i have looked at each of the options for line breaks and wrapping but i have not been able to find the one to keep things on the same line as long as possible i am assuming that i missed the correct option my right margin columns option is set to 100 which is plenty bigquestion is there a way to make it look like the original and still get smart formatting on other things that actually do need to be wrappedi can manually put the cmd new odbccommand stringformat back on the first line and it will leave the verbatim string on the next line happily that is an alright compromise i guess,['c#'] +325970,java parallel file proccessing i hav following codeimport javaioimport javautilconcurrent public class examplepublic static void mainstring args try fileoutputstream fos new fileoutputstream1dat dataoutputstream dos new dataoutputstreamfos for int i 0 i 20 i doswriteinti dosclose two sample files created fileoutputstream fos1 new fileoutputstream2dat dataoutputstream dos1 new dataoutputstreamfos1 for int i 20 i 40 i dos1writeinti dos1close examplesscreatearray20 create a shared array exampless ex1 new exampless1dat exampless ex2 new exampless2dat executorservice executor executorsnewfixedthreadpool2 exexuted parallaly to cont number of matches in two file long starttime systemnanotime long endtime futureinteger future1 executorsubmitex1 futureinteger future2 executorsubmitex2 int count1 future1get int count2 future2get endtime systemnanotime long duration endtime starttime systemoutprintlnduration with threadsduration executorshutdown systemoutprintlnmatches count1 count2 starttime systemnanotime ex1call ex2call endtime systemnanotime duration endtime starttime systemoutprintlnduration without threadsduration catch exception e systemerrprintlnerror egetmessage class exampless implements callable public static int arr new int20public string namepublic examplestring name this name namestatic void createarrayint z for int i z i z 20 i shared array arri z i public object call try int cnt 0 fileinputstream fin new fileinputstream name datainputstream din new datainputstreamfin read file and calculate number of matches for int i 0 i 20 i int c dinreadint if c arri cnt return cnt catch exception e systemerrprintlnerror egetmessage return 1 where i am trying to count number of matches in an array with two files now though i am running it on two threads code is not doing well because running it on single thread file 1 file 2 reading time file 1 file 2 reading time in multiple thread can anyone help me how to solve this i have 2 core cpu and file size is approx 15 gb,['java'] +325979,how to set auto for upper limit but keep a fixed lower limit with matplotlibpyplot i want to set the upper limit of the yaxis to auto but i want to keep the lower limit of the yaxis to always be zero i tried auto and autorange but those do not seem to work thank you in advancehere is my codeimport matplotlibpyplot as pltdef plotresults plttitlefilename plot results mirror result table such that each parameter forms an own data array pltcla print results plt xy results xy results zip results plt pltplotxy results0 xy results2 marker plttitles title pltxlabelinput voltage v pltylabelinput current ma pltgridtrue pltxlim30 42 i want to keep these values fixed pltylim0 80 change i want to change 80 to auto but still keep 0 as the lower limit pltsavefigpathfilenamepng,['python'] +325980,return group concat data as array i want to return values i retrieve from the db using group concat as an array of data is it possible to do this in the mysql query or do i need to explode the data into an arraygroup concatshhold id as holdsreturns this holds 34i want it to returnholds array34,"['php', 'mysql']" +325989,what operations are atomic in c is there a systematic way to know whether an operation in c will be atomic or not or are there any general guidelines or rules of thumb,"['c#', '.net']" +325995,isdate function in sql evaluates invalid dates as valid i am running a sql statement against imported data from excel filesin this sql i am checking if the users have entered dates properly by using isdate function since this is a raw data that has not been converted yet all dates are stored in a varchar data type fieldin some circumstances isdate returns 1 valid date when there is clearly an incorrect date format entered by the userfor example0700120122012070020070022012any suggestions on how to handle this problemselect from tblimport where isdatedt 0 and dt is not null and dt thanksps smacking users did not help,['sql'] +326012,how can i access this helper function in production i am using private pub for pushing notifications to subscribed clients to my users in my applicationhtmlhaml i have javascript include tag application subscribe to useraccess tokennotificationsthe subscribe to helper works fine in development when deployed to production the following error is loggedactionviewtemplateerror undefined method subscribe to for class0x01f372e80x01fded90 5 stylesheet link tag application media all 6 include goninit true 7 javascript include tag application 8 subscribe to useraccess tokennotifications 9 csrf meta tags 10 11 body appviewslayoutsapplicationhtmlhaml8in app views layouts application html haml 1867651381877570337 14592040how can i get access to this helper method in my production environment,['ruby-on-rails'] +326035,error type parameters of t cannot be determined during maven install i have this function throwing weird error when i try to do a mvn installpublic t t getfinal an enum key return some mapgetkeythis is the line where i get the error final int value getan enuma fieldand this is the error in mavenxjava2541 type parameters of tt cannot be determined no unique maximal instance exists for type variable t with upper bounds intjavalangobjecti know already how to fix it i just need to change the int to integer in my last code sample and the bug goes away it tell me that maven for some sort of reason is not able to cast an integer as an int when i use a type parametermy question is why in eclipse using the same jdk i have been able to run my application without any kind trouble nor warningjdk 16eclipse indigo service release 2maven 304,['java'] +326048,jackson how to process deserialize nested json vendors vendor id 367 name kuhnpollich company id 1 vendor id 374 name sawaynhermann company id 1 i have a vendor object that can properly be deserialized from a single vendor json but i want to deserialize this into a vendor i just cannot figure out how to make jackson cooperate any tips,['java'] +326050,call the hardware back button programatically i know that one can overwrite the back button functionality in android but i was wondering if there was a method or anything i could call that would functionally do the same thing as pressing the hardware button,['android'] +326051,wait for callback in javascript i am trying to create a function that returns a object with information of a callbackvar geolocvar successful function position geoloc longitude positioncoordslongitude latitude positioncoordslatitude var getlocation function navigatorgeolocationgetcurrentpositionsuccessful function alertfail return geolochow can i do this the function getlocation return null value before successful is executedthanks,['javascript'] +326060,find an element with a specific data attribute jquery i understand that i can always iterate down the dom tree and check every element for a data field and if the value is correct but i would like a cleaner solution for example div idthediv div span datanum3 span other html div div divspan datanum23spandiv other html div div span datanum3span other html div divis there a jquery one liner to find all spans with datanum3 i know i can find all spans by thedivfindspaneachfunctione but i would like something like thedivfindspan datanum3eachfunctione,"['javascript', 'jquery']" +326137,is there any way to make my function return a dynamic array so at the moment i have a function i made returning a static array is there any way to make it return a dynamic array for the sake of efficiencyinclude stdiohinclude stdlibhinclude headerhint charposchar str char ch int bff bc ec i strln static int ret255 bc 0 ec 0 fori 0 stri 0 i strln i fori 0 i strln i ifstri ch ec bff mallocsizeofintec ifsizeofbff sizeofret freebff return 0 fori 0 i 255 i reti 0 fori 0 i strln i ifstri ch retbc i bc freebff return ret,['c'] +326149,does geocoder gem work with google api key i am using ruby geocoder gem for my project and as the project is growing i am starting to look into connecting to the google api key after adding this to the projectgeocoderconfigure do config geocoding service see below for supported optionsconfiglookup google to use an api keyconfigapi key my key geocoding service request timeout in seconds default 3configtimeout 5end i get google geocoding api error request denied when i start the application from reading around it seems like others switch over to yahoo if they choose to continue using the gem can i configure the gem to work with google api key mainly i would like to keep an eye out for the amount of daily queries to avoid going over the limit,['ruby-on-rails'] +326170,perform insert for each row taken from a select i have a number of records that i need to insert into multiple tables every other column will be a constantpoor pseudo code below this is what i want to docreate table temp buildings building id varchar20insert into temp buildings building id values 11070insert into temp buildings building id values 11071insert into temp buildings building id values 20570insert into temp buildings building id values 21570insert into temp buildings building id values 22570insert into propertyportfolio property xref portfolio id building id created date last modified date values 34 select building id from temp buildings getdate null intent perform an insert into propertyportfolio property xref for each record on temp buildingsi think i could do this with a cursor but believe this would be horribly slow as this exercise will be repeatable in future i would rather tackle this in a faster method but i am unsure how any feedback would be appreciated,['sql'] +326211,exporting apk from eclipse adt silently crashes every time i try to export an apk from eclipse tried juno and indigo on mac eclipse crashes after a few secondsthis used to work fine on my current setuprunning the app straight debug mode on my phone works finethe error from the console isinvalid memory access of location 0x10073f113 rip0x101f656f7bus error 10i am using mac os x 1074 on a 2010 macbook pro with the following javajava version 160 33javatm se runtime environment build 160 33b0342411m3720java hotspottm 64bit server vm build 208b03424 mixed modei am using adt 20i have tried reinstalling eclipse and the android sdk and redownloading adtthe eclipse error view does not show anythingany ideas of different methods i can try or other ways to investigate whats going wrongcheersupdate for anyone coming along post2014 you should be using android studio which does not have this problem,['android'] +326215,mpnowplayinginfocenter not reacting properly when pausing playback i am trying to get mpnowplayinginfocenter to work properly when pausing playback i have a streaming music app that uses avplayer for playback and i am playing back in my apple tv over airplay everything but pausing seems to be reflected correctly in the apple tv ui i am initializing it like thismpnowplayinginfocenter center mpnowplayinginfocenter defaultcenternsdictionary songinfo mpmediaitempropertytitle title mpmediaitempropertyartist artistcenternowplayinginfo songinfosince i am streaming i do not have duration info upon starting the playback when i get areadya signal from the stream i update the duration that shows up correctly on my apple tvmpnowplayinginfocenter center mpnowplayinginfocenter defaultcenternsmutabledictionary playinginfo nsmutabledictionary dictionarywithdictionarycenternowplayinginfoplayinginfo setobjectnsnumber numberwithfloatlength forkeympmediaitempropertyplaybackdurationcenternowplayinginfo playinginfoi can also seek with this technique when the user seeks the trackplayinginfo setobjectnsnumber numberwithfloatlength targetprogress forkeympnowplayinginfopropertyelapsedplaybacktimethe one thing i can not figure out is how to pause the playhead on my apple tv when user taps pause in my ui i am trying to do something likempnowplayinginfocenter center mpnowplayinginfocenter defaultcenternsmutabledictionary playinginfo nsmutabledictionary dictionarywithdictionarycenternowplayinginfo playinginfo setobjectnsnumber numberwithfloat00f forkeympnowplayinginfopropertyplaybackrate centernowplayinginfo playinginfoinstead of pausing this seeks the playhead back to zero and keeps advancing ithow do i get the playhead to pause correctly in my apple tv ui,['ios'] +326218,carrierwave uploading a file from a string users in my site can upload their own photos for a model or choose from a library when the users choose from the library i send the file name as a string to the server file url urljpg i have not find a way in which carrierwave can just update a model file without uploading it i can write a condition in my model that checks for the existence of that parameter and then modelfile fileopenstrjpg is that bad from a security view how can i upload files or just update the file attribute to reference a file that is already available on the serverthanks,"['ruby-on-rails', 'ruby']" +326227,spring mvc localechangeinterceptor annotation based does not work import javautillocaleimport orgspringframeworkcontextmessagesourceimport orgspringframeworkcontextannotationbeanimport orgspringframeworkcontextannotationconfigurationimport orgspringframeworkcontextsupportreloadableresourcebundlemessagesourceimport orgspringframeworkwebservlethandlermappingimport orgspringframeworkwebservletlocaleresolverimport orgspringframeworkwebservleti18ncookielocaleresolverimport orgspringframeworkwebservleti18nlocalechangeinterceptorimport orgspringframeworkwebservletmvcannotationdefaultannotationhandlermappingconfigurationpublic class config bean public localeresolver localeresolver final cookielocaleresolver ret new cookielocaleresolver retsetdefaultlocalenew localeen us return ret bean public messagesource messagesource final reloadableresourcebundlemessagesource ret new reloadableresourcebundlemessagesource retsetbasenameclasspathlang retsetdefaultencodingutf8 return ret bean public handlermapping handlermapping final localechangeinterceptor interceptor new localechangeinterceptor interceptorsetparamnamelanguage final defaultannotationhandlermapping ret new defaultannotationhandlermapping retsetinterceptorsnew object interceptor return ret the above is my annotation configuration i have basically translated this tutorials xmlstrangely it does not work when i go to languagefrhowever the following does work in appservletxml notice here it is using localemvcinterceptors bean classorgspringframeworkwebservleti18nlocalechangeinterceptor property nameparamname valuelocale beanmvcinterceptorsanother important thing to note is that when i put breakpoints on the above methods all of the three of them every breakpoint does break which implies that someone is reading the valuesso why wouldnt my annotation based interceptor does not work,['java'] +326229,ends with suffix and contains string search using match in sqlite fts i am using sqlite fts extension in my ios applicationit performs well but the problem is that it matches only string prefixes or starts with keyword searchie select from tablename where columnname match searchtermworks butselect from tablename where columnname match searchtermorselect from tablename where columnname match searchtermdoes notis there any workaround for this or any way to use fts to build a query similar to like searchterm queryeditas pointed out by retterdesdialogs storing the entire text in reverse order and running a prefix search on reverse string is a possible solution for ends withsuffix search problem which was my original question but it wont work for contains search i have updated the question accordingly,"['iphone', 'ios']" +326235,how to open the google play store directly from my android application i have open the google play store using the follwing code intent i new intentandroidcontentintentaction viewisetdatauriparse packagename startactivityibut it shows me a complete action view as to select the option browserplay store i need to open the application in playstore directly,['android'] +326239,use c with android ndk i am trying to develop a android project that makes a simple call from java code to native c codei refer this link for my guidance when i am compiling the nativec using ndkbuildit showsndkbuild command not foundcould anyone give the reason for thisthanks,['android'] +326254,sorting python dictionary based on nested dictionary values how do you sort a python dictionary based on the inner value of a nested dictionaryfor example sort mydict below based on the value of contextmydict age context 2 address context 4 name context 1the result should be like this name context 1 age context 2 address context 4,['python'] +326259,lineheight affecting spacing above first line and after last line i have a text in side heading with multiple lines want the spacing the two lines to increase so i set a lineheight when i do this not only does it increase space between the two lines it also increases spacing above the first line and maybe below the second how can i increase spacing between the two lines only without increasing above and belowi know it is a behavior of lineheight but just curious if there is any good solution for thisthis is just en example to what i am asking jsfiddle,['css'] +326298,jquery clear input default value how can i clear the default value of an input form onfocus with jquery and clear it again when tha submit button is pressedhtml form method action input typetext nameemail valueemail address classinput input typesubmit valuesign up classbutton formhtmlscriptdocumentreadyfunction hide input text inputclickfunction if inputattrvalue inputattrvalue email address alert1 if inputattrvalue email address inputattrvalue script,['jquery'] +326306,how to draw jms queue is there any symbol for jms queue i know eg databases files classes should be drawn in the same way but what about jms elements,['java'] +326321,how to sniff https traffic from android emulator to remote server i want to monitor https traffic from my application to remote server i am trying to follow this instruction and it works for http without s but not for https what is wrong should i write some custom code in my application to use httpsproxy,['android'] +326375,path to a file without basename how can i get the path of a file without the file basename something like apathtomyfiletxt apathtomytried with split without success,['python'] +326388,jquery mobile icon count badges bubbles how to add a count bubble or badge on top of a icon dataicon in jquery mobile is there a better way to add it as widget rather than manipulating with css i expect the count to be updated dynamically from the server,['javascript'] +326405,ipad 3 shouldrasterize yes makes uilabel text cut off i have a problem when setting shouldrasterize to yes on layer on ipad3 the labeltext has the text cut off from the bottom for about 15 of the size anyone know whats the problem is cellviewlayercornerradius 120 cellviewlayerbordercolor uicolor blackcolorcgcolor cellviewlayerborderwidth 10 cellviewlayerframe rect cellviewlayershouldrasterize yes cellviewlayermaskstobounds yeson ipad 2 it works fine,"['objective-c', 'ios']" +326425,injection of autowired dependencies failed nested exception is orgspringframeworkbeansfactorybeancreationexception i am creating web application using spring hibernate struts and maven i get the below error when i run mvn clean install commandorgspringframeworkbeansfactorybeancreationexception error creating bean with name comprojectactionpasswordhintactiontest injection of autowired dependencies failed nested exception is orgspringframeworkbeansfactorybeancreationexception could not autowire field private comprojectactionpasswordhintaction comprojectactionpasswordhintactiontestaction nested exception is orgspringframeworkbeansfactorynosuchbeandefinitionexception no matching bean of type comprojectactionpasswordhintaction found for dependency expected at least 1 bean which qualifies as autowire candidate for this dependency dependency annotations orgspringframeworkbeansfactoryannotationautowiredrequiredtruethe following is the class that has the autowired dependency import comopensymphonyxwork2actionimport orgprojectmodeluserimport orgproejctserviceusermanagerimport orgjunittestimport orgspringframeworkbeansfactoryannotationautowiredimport orgsubethamailwiserwiserimport static orgjunitassertpublic class passwordhintactiontest extends baseactiontestcase autowired private passwordhintaction action autowired private usermanager usermanager test public void testexecute throws exception start smtp server wiser wiser new wiser wisersetportgetsmtpport wiserstart actionsetusernameuser assertequalssuccess actionexecute assertfalseactionhasactionerrors verify an account information email was sent wiserstop asserttruewisergetmessagessize 1 verify that success messages are in the request assertnotnullactiongetsessiongetattributemessages my applicationcontextxmlxml version10 encodingutf8beans xmlns xmlnsxsi xmlnscontext xsischemalocation defaultlazyinittrue activates scanning of autowired contextannotationconfig activates scanning of repository and service contextcomponentscan basepackagecomproject compass search section compass bean automatically scanning for searchable classes within the model hooks into spring transaction management and stores the index on the file system bean idcompass classorgcompaspringlocalcompassbean property namemappingscan valueorgproject property namepostprocessor refcompasspostprocessor property nametransactionmanager reftransactionmanager property namesettings map entry keycompassengineconnection valuetargettestindex map property beani have added to my context configuration to scan autowired dependencies but i am not sure why it is still giving this exceptioni tried adding it in following way also but i still get the same exceptioncontextcomponentscan basepackagecomprojectupdate following is the password hint actionimport orgprojectmodeluserimport comprojectwebapputilrequestutilimport orgspringframeworkmailmailexceptionimport orgspringframeworksecuritycoreuserdetailsusernamenotfoundexceptionimport javautilarraylistimport javautillistpublic class passwordhintaction extends baseaction private static final long serialversionuid 40375146071012025l private string username param username the username to set public void setusernamestring username thisusername username execute sending the password hint via email return success if username works input if not public string execute listobject args new arraylistobject ensure that the username has been sent if username null logwarnusername not specified notifying user that it is a required field argsaddgettextuserusername addactionerrorgettexterrorsrequiredfield args return input if logisdebugenabled logdebugprocessing password hint look up the users information try user user usermanagergetuserbyusernameusername string hint usergetpasswordhint if hint null hinttrimequals logwarnuser username found but no password hint exists addactionerrorgettextloginpasswordhintmissing return input stringbuffer msg new stringbuffer msgappendyour password hint is appendhint msgappendnnlogin at appendrequestutilgetappurlgetrequest mailmessagesettousergetemail string subject gettextwebappname gettextuserpasswordhint mailmessagesetsubjectsubject mailmessagesettextmsgtostring mailenginesendmailmessage argsaddusername argsaddusergetemail savemessagegettextloginpasswordhintsent args catch usernamenotfoundexception e logwarnegetmessage argsaddusername addactionerrorgettextloginpasswordhinterror args getsessionsetattributeerrors getactionerrors return input catch mailexception me addactionerrormegetcausegetlocalizedmessage getsessionsetattributeerrors getactionerrors return input return success update 2applicationcontextstrutsxmlbean idpasswordhintaction classcomprojectactionpasswordhintaction scopeprototype property nameusermanager refusermanager property namemailengine refmailengine property namemailmessage refmailmessagebean,['java'] +326427,python json loadsdumps break unicode when i print a json string from google it prints unicode foreign characters correctlyhowever if i do jsonloads and jsondumps it prints abcub098ub178ud14 which is clearly not what the original json string from google looked likedef get google placerequest keyword request url keygoogle api key location375129912705354 radius500 sensorfalse keywordkeyword r requestsgetrequest url return httpresponsertext this would print unicode strings correctly json string rtext json dict jsonloadsjson string json string jsondumpsjson dict return httpresponsejson string this prints something like abcub098ub178ud14d,['python'] +326430,issue in using composition for ais a a a relationship i have system being developed for an hr system there are accountant employees and programmer employees for the first month of joining the company the employee is not given any role one employee can be an accountant and a programmer at the same time i have a design shown by the following codenow i need to enhance the system by implementing a new functionalityterminate all accountants terminate means set status of employee as isactive false the issue is i cannot set all accountants directly as inactive without checking i need to check whether he has got any other role how to remodel these classes in order to do the terminate function more natural oo updatei am looking for an answer that has ef database first solution model and database schema for alexdev answerc codelistaccountant allaccountants get all accountants from databasepublic class employee public int empid get set public datetime joineddate get set public int salary get set public bool isactive get set public class accountant employee public employee employeedata get set public class programmer employee public employee employeedata get set alexdev answerpublic class employeeilistrole rolesbool isactivepublic void terminaterolerole role rolesremoverole ifrolescount 0 isactive false public class role abstract string name getpublic class programmerrole role override string name get return programmer referenced approach to access external informationprefer composition over inheritanceinheritance vs enum properties in the domain modelentity framework get subclass objects in repository,['c#'] +326447,upload android app to google play step by step 1i am new bee to android thistributionmy application is ready and now i want to thistribute it through google play but i cannot find how to create certificate because default debug certificate not use for thistributecan any one help me to create self signed certificatei am using os mac and eclipse as ide for development2afte creating appropriate apk with self signed certificate what is the process to upload it and where like is there any account i have to create on google play through which i can upload and manage my applike in iphone developer account,['android'] +326450,cross product using mathnet numerics with c i have two vectors mathnetnumericslinearalgebragenericvectordouble like the followingvectordouble v1 new densevectornew double 1 2 3 vectordouble v2 new densevectornew double 3 2 1 i basicly want to crossproduct them however could not find an official function i know cross product is a very easy function which i can write myself but i want to use the apis functionboth of the below works for me could not find such functions in the apivectordouble result v1crossproductv2vectordouble result vectorcrossproductv1v2i found this however could not find the function when i tried to write it api reference,['c#'] +326466,resharper unit test runner gives inconclusive to the outer class i have unit tests written using nunit and tests are structured in a similar way as in phil haacks postnamespace mynamespace testfixture public class classtotest testfixture public class methodtotest test public void throwsargumentnullexception onnullindex more tests for the method testfixture public class anothermethodtotest test public void throwsargumentnullexception onnullindex more tests for the method my problem is that i get inconclusive for the outer class that is used to group unit tests i have tried with and without testfixture on the outer andor inner class but it is always giving me inconclusivei think the correct behavior should be to thisplay unit test states from the inner class tests any ideas updateone ugly fix seems to be creating a dummy test to the outer class and then put attribute ignore on ittest ignorepublic void dummytest assertistruetrueupdate 2channs wayne are correct outer class is just used for grouping so changing from class to namespace is the best solution,['c#'] +326563,how can i add item to the top actionbar i would like to add new icon to the top action bar bet instead of adding to the top the icon appear on the bottom of the screen how can i add item to the top actionbarxmlmenu xmlnsandroid item androidididpreferences androidicondrawablepreferences androidtitlepreferences androidshowasactionalwayswithtext item androidididhelp androidtitlehelp androidicondrawableic action search menujavapublic boolean oncreateoptionsmenumenu menu menuinflater inflater getmenuinflater inflaterinflatermenuactivity ygo main menu return true,['android'] +326577,python for loop access two elements at a time i am adding into the value section of a dictionary a name and the value of properties of an item valuechildgetname t childtext t each piece of text is separated by a tab so then when i process this value string later i split on the tabs and have a for loop to iterate over the listhow can i access both the name and value in the for loop as for each property i want to get the name and value in one go and write it to a file currently the list looks likeababababand for each ab i want to write tag namea b tag,['python'] +326587,how to find the minimum value in a numpy matrix hey this is a quick and easy questionhow would i find the minimum value of this matrix excluding 0as in 8arr numpyarray 0 56 20 44 68 0 56 8 32 56 0 44 68 20 56 0,['python'] +326588,multiple signalr connectionshubs on your website if i have multiple pages that could use multiple hub classes what is the best way to manage thisis it bad to navigate to another page in the website and essentially reopen the connection to the same hub class that was open on the previous pagemultiple hub connections on a page is ok because they are all unified in one connection even if they are different hub classes,"['c#', 'asp.net']" +326593,scrolling a gallery enables pressed state and removes click listener from subitems i have a gallery of fairly complicated items each item is composed of an image and 2 buttons when the gallery loads everything works the buttons do what they are supposed to and the pressed state for the buttons happens only on actual press of the buttons however as soon as i scroll the gallery the buttons stop working and clicking anywhere enables the pressed state for the buttonsi have tried embedding everything in a linearlayout that does not pass on ondown events as per this answer however this just blocks click eventsi am aware that gallery is not the ideal widget for complicated layouts like this but i am wondering if there is a better workaround for this issue updatei will try to explain the architecture a bit i have a fragmentactivity which contains a listfragment which is made up of just a listviewthe listview is made up of groups of smaller elementsbettable along with some meta information these groups are implemented as gallerys specificallyi have extended gallery called onegallery that does several things it makes sure that only one item is scrolled at a time and alsotransforms the gallery items as the scrolling is happening here is the code for thathere is the adapter for the galleryand here is the code for the bettable layout,['android'] +326603,using locals and format method for strings are there any caveats are there any thisadvantages caveats or bad practice warnings about using the following patterndef buildstringuser name john age22 userid usergetuserid return name name age age useriduseridformatlocalsi had a very repetitive string generation code to write and was tempted to use this but something about using locals makes me uncomfortable is there any danger of unexpected behavior in thisedit contexti found myself constantly writing stuff likename age userid etcformatnamename ageage useriduserid etcetc,['python'] +326610,how to use routevalues using mvcpaging20 in mvc3 html helper htmlpager from mvcpaging 20 has optionso oroutevaluesobject routevalues which can return model back to controllerbut mvcpaging requires this helper to be filled with ipagedlistmodel in view that he lives in this is the model that generates table and paging what is the best way to implement mvcpaging 20 using searchmodel for search and model to thisplay resultsexamplemodelspublic class searchmodel public string firstname get set public string lastname get set public class person key public int id get set public string firstname get set public string lastname get set public datetime dob get set public string city get set view indexcshtmlusing ajaxbeginformsearch searchperson new ajaxoptions httpmethod get insertionmode insertionmodereplace updatetargetid main search result table id htmltextboxform mfirstname htmltextboxform mlastname input typesubmit valuesearch div idmain search result table id htmlrenderpartial initpartialempty div resultpartialcshtmlusing mvcpagingmodel ipagedlistmodelspersontableforeach var p in modeltr tdpfirstnametd tdplastnametd tdpdobtd tdpcitytdtrtable htmlpagermodelpagesize modelpagenumber modeltotalitemcount new ajaxoptions updatetargetid main search result table id optionso oroutevaluesmodel ipagedlistmodelspersoncontrollerpublic actionresult searchpersonint pagesearchmodel person listperson result adaptergetpersonsperson int currentpageindex pagehasvalue pagevalue 1 0 return partialview resultpartial resulttopagedlistcurrentpageindex 10 resultcountthe question is how to implement mvcpaging20 using model for searchor is there another way a better way to have complex searches and not using model to transfer data query any thoughtsi am using mvcpaging 20 docseditthanks darin for answer but i manage to pull it of like this resultpartialcshtmlhtmlpagermodelpagesize modelpagenumber modeltotalitemcount new ajaxoptions updatetargetid main search result table id optionso oactionajaxpagingcontrollerpublic actionresult searchpersonint pagesearchmodel person iqueryableperson query adaptergetpersonsperson sessionsearchquery query int currentpageindex pagehasvalue pagevalue 1 0 listperson persons querytolist return partialview resultpartial personstopagedlistcurrentpageindex 10 personscountpublic actionresult ajaxpagingint page iqueryableperson query sessionsearchquery as iqueryableperson int currentpageindex pagehasvalue pagevalue 1 0 listperson persons querytolist return partialview resultpartial personstopagedlistcurrentpageindex 10 personscount,"['c#', 'asp.net', '.net']" +326617,generating custom thumbnail from alassetrepresentation my main problem is i need to obtain a thumbnail for an alasset objecti tried a lot of solutions and searched stack overflow for days all the solutions i found are not working for me due to these constrainti cannot use the default thumbnail because it is too littlei cannot use the fullscreen or fullresolution image because i have a lot of images on screeni cannot use uiimage or uiimageview for resizing because those loadsthe fullresolution imagei cannot load the image in memory i am working with 20mpx images i need to create a 200x200 px version of the original asset to load on screenthis is the last iteration of the code i came withimport assetslibraryalassethimport imageioimageioh alasset asset alassetrepresentation assetrepresentation asset defaultrepresentationnsdictionary thumbnailoptions nsdictionary dictionarywithobjectsandkeys idkcfbooleantrue kcgimagesourcecreatethumbnailwithtransform idkcfbooleantrue kcgimagesourcecreatethumbnailfromimagealways idnsnumber numberwithfloat200 kcgimagesourcethumbnailmaxpixelsize nilcgimageref generatedthumbnail assetrepresentation cgimagewithoptionsthumbnailoptionsuiimage thumbnailimage uiimage imagewithcgimagegeneratedthumbnailproblem is the resulting cgimageref is neither transformed by orientation nor of the specified max pixel sizei also tried to find a way of resizing using cgimagesource butthe asset url cannot be used in the cgimagesourcecreatewithurli cannot extract from alasset or alassetrepresentation a cgdataproviderref to use with cgimagesourcecreatewithdataprovidercgimagesourcecreatewithdata requires me to store the fullresolution or fullscreen asset in memory in order to workam i missing somethingis there another way of obtaining a custom thumbnail from alasset or alassetrepresentation that i am missingthanks in advance,['ios'] +326655,coldfusion cfhttp to php i have designed a website im running for a sports team i coach in wordpress more specifically php for the past few years we have used an online web service that runs a stats based program in coldfusion they recently opened up a feed so users can use there own customized websites with their data implemented in itthey provided me with a feed like so not going to provide my details for security reasonscfhttp urlhttpdatafeed methodpost resultresult cfhttpparam typeformfield nameseasonid value29725 cfhttpparam typeformfield namecodekey valuemycodekeycfhttpparam typeformfield nameshowgametype valuerscfhttpi have no experience with coldfusion what so ever and i have tried to do some reading about using this in a php environment but everything i tend to find is php to coldfusion not the oppositebecause of this i come to stack im not entirely sure how this would work within php but would curl be the answer ideally id like to just create a couple wordpress functions and call them on my template pages,['php'] +326683,how to stop the viewforannotation method from overriding the default user location blue beacon in ios right now i am populating a map view with annotations and also thisplaying the users current location with the viewforannotation method it overrides all annotations with the default red pin but i want to return the views for the other annotations but keep the user location the default blue beacon is there a way to do this simply or do i have to create a new annotation view and return the right one depending on the annotationright now i have something like mkannotationview mapviewmkmapview mapview viewforannotationid mkannotationannotation if annotationcoordinate locationmanagerlocationcoordinate return nil else mkannotationview annotationview mkpinannotationview alloc initwithannotationannotation reuseidentifierbeacon button uibutton button uibutton buttonwithtypeuibuttontypedetailthisclosure buttonframe cgrectmake0 0 23 23 annotationviewrightcalloutaccessoryview button annotationviewcanshowcallout yes return annotationviewbut i cannot equate the two because i cannot get the coordinate property out of the annotation argumentanybody know any solutions to this,['ios'] +326707,transform url string into normal string in python 20 to space etc is there any way in python to transfrom this ceb1cebb20 into this ii which is its real representationthanks in advance,['python'] +326729,how to load resources from external framework i have build an external framework and i am trying to utilize some images which are in the resource directory of the framework the framework is not being copied within the application but rather just referenced to it how can i utilize uiimage accordingly from xyzframework resource folderthanks,"['iphone', 'objective-c', 'ios']" +326779,date default timezone setutc not working this seems to be weird but i already check everything and still a weird thing happensi cannot change the timezone of my php scriptsfirst things first what i did was something like thisphpdate default timezone setutcecho brecho dateymd histhis seems to be working fine when i tried this on a test my servers timezone is set to utc800 taipei but when i tried the code above it is not really working it still shows my current date time in my servers timezone not following the code aboveand this is the phpini configuration of my serverdatetime support enabledolson timezone database version 20123timezone database internaldefault timezone europeberlin why this is happening is this already a bug or mistake on server setup or i just missed something in my codethank younotemy environment is a windows 7n running in vm using php 544fixi got the fix by changing manually the phpini,['php'] +326803,deleting android sqllite rows older than x days i want to delete all rows in table mytable which are older than x days column save date long is the time when the row was inserted in tablei tried this but apparently it deletes all my rowslong daysinmilisec new dategettime x 24l 60l 60l 10lreturn dbdeletemytable save date new string daysinmilisec what is wrong thank you for helping me out,['android'] +326865,wysihtml5 image src and href are stripped i am using wysihtml5 wysiwyg editorthe problem is that image src attribute and link href attribute are stripped from html at server i am already getting stripped htmlhow i can fix this problemi am using advancedjs rulest with all ruleseditorupdate 1well editorgetvalue and jqueryval for textarea give same values on form submit means that form should be sent correctlybut iv watched post request which is sent from the browser and it is without urls something wrongupdate 2if i remove from ruleset everything connected with img nevertheless it works inproperlyupdate 3in response to marrowmaw commenti am expectinga href titlelink linkabut i geta href titlelink nulinkaupdate 4div idwysihtml5toolbar stylethisplay none button classbtn datawysihtml5commandbold boldtrans button button classbtn datawysihtml5commanditalic italictrans button button classbtn datawysihtml5commandcreatelink linktrans unlinktrans button button classbtn datawysihtml5commandinsertunorderedlist button button classbtn datawysihtml5commandinsertorderedlist 123 button button classbtn datawysihtml5commandformatblock datawysihtml5commandvalueh1 headingtrans button button classbtn datawysihtml5commandinsertimage imagetrans button div datawysihtml5dialogcreatelink stylethisplay none label linktrans input datawysihtml5dialogfieldhref valuehttp label a datawysihtml5dialogactionsave savetrans anbspa datawysihtml5dialogactioncancel canceltrans a div dialog div datawysihtml5dialoginsertimage stylethisplay none label url input datawysihtml5dialogfieldsrc valuehttp label label alternative text input datawysihtml5dialogfieldalt value label label aligntrans select datawysihtml5dialogfieldclassname option value defaulttrans option option valuewysiwygfloatleft lefttrans option option valuewysiwygfloatright righttrans option select label a datawysihtml5dialogactionsave savetrans anbspa datawysihtml5dialogactioncancel canceltrans a div div form action path save homepage methodpost textarea idwysihtml5textarea placeholder enter your texttrans autofocus namehomepage stylewidth700pxheight400px homepageraw textarea input typesubmit value savetrans classbtn formand js initscript typetextjavascriptjquerydocumentreadyfunction var editor new wysihtml5editorwysihtml5textarea id of textarea element toolbar wysihtml5toolbar id of toolbar element parserrules wysihtml5parserrules defined in parser rules set script,['javascript'] +326896,compare date with a specific one and datetime to string in twig how can i compare two dates in twig when the first one comes from the dababase and the second is clear 20121231 i tried with if domduedatedateymd 20121231 but i do not get the result i want i have a datetime field but i could not find a filter for datetime in twig and when i use dateymd it prints only the date without the hour i would be really happy and grateful if someone helps me to solve the problems,['php'] +326926,less firstchild why is not my firstchild selector working in lessleftpanel margin20px floatleft thisplayinline width620px marginleft10px select width300px firstchild marginright 30px,['css'] +326927,in meteor how can i create a generic event handler i want to create a generic event handler that i can reuse on dom elements so i do not have to write boiler plate over and over again i thought i had it figured out but i am getting errorsthe problem i am having is that i think the event handlers are bound at a different time than i need maybe at documentready where i think i need to attach them with the live method though i may have no idea what i am talking about herehere is what i am trying to domulti page applicationmultiple collections where data needs to be insertedbutton code to show the insert formbutton idbtnshowinsert classbtn btnsuccess reltooltip titleadd group i idbtnicon classiconplussign iconwhiteibuttontemplate that shows the form based on the page controller groups inserthere is the form template namegroups insert if acl check alert p form classformhorizontal well hide idinsert fieldset div classcontrolgroup label classcontrollabel fornamenamelabel div classcontrols input typetext classinputxlarge idname namename div div div classformactions well button idbtnreset typereset classbtn btnlargeresetbutton button idbtnsubmit typebutton classbtn btnprimary btnlargesubmitbutton div fieldset form p if templatehere is the client code to implement the button that shows the form on the pagetemplategroupsevents meteoreventhandlerbtn eventsbtnshowinsert meteoreventhandlermake btn show insert form click handlerhere is my generic event handlervar eventhandler baseextend btn events functionselector return click selector keydown selector focusout selector make btn show insert form click handler function var click optionsclick function return function event if eventtype click eventstoppropagation eventpreventdefault try if btniconhasclassiconplussign btniconremoveclassiconplussign btniconaddclassiconminussign else btniconremoveclassiconminussign btniconaddclassiconplussign insertslidetoggleslow swing catcherror alertsetalerterror critical error error alerterror meteoreventhandler new eventhandlerthe erroruncaught typeerror cannot call method btn events of undefinedbut if i define the event handler this way and call it this way it workstemplategroupsevents btn eventsbtnshowinsert make btn show insert form click handlervar btn events function selector return click selector keydown selector focusout selectorvar make btn show insert form click handler function var click optionsclick function consolelog meteorrequestcontroller return function event if eventtype click eventstoppropagation eventpreventdefault try if btniconhasclassiconplussign btniconremoveclassiconplussign btniconaddclassiconminussign else btniconremoveclassiconminussign btniconaddclassiconplussign insertslidetoggleslow swing catcherror alertsetalerterror critical error error alerterror the problemi do not want to have to replicate code all over my site in order to implement a nice button that can slidetoggle and form on any page if i could get it abstracted then i should be able to have a show form type of button on all pages for any collection that i am rendering that allows data entry as well this leads into being able to create one form handler for all forms as well and then tying them to the controller through an action to the model any ideas,['javascript'] +326966,javascript child node count ul liarray1li liarray2li li idelementarray3liulscript var temp documentgetelementbyidelementparentnode child tempchildnodes consolelogtemplengthscripti need to get the child node length using element id my code returns 7 as a result but i have only 3 nodes,['javascript'] +326997,using asynctask to load images into a custom adapter although there are many tutorials out there i have found it really difficult to implement an asynctask to load images from uris obtained from a content provider into a custom adapteri get the basic gist which is to have a class containing an asynctask do the bitmap creation in the doinbackground and then set the imageview in the onpostexecutethe problem for me being new to android programming is that i do not know how to pass in my uris to the asynctask for each item how to create the bitmap and how to return it to the adapteri have only gotten this far with the actual asynctask class imageloaderpackage anothermusicplayerimport androidgraphicsbitmapimport androidosasynctaskimport androidwidgetimageviewpublic class imageloader extends asynctaskstring string bitmap private imageview imageview private bitmap bitmap null override protected bitmap doinbackgroundstring uri create bitmap from passed in uri here return bitmap override protected void onpostexecutebitmap bitmap if bitmap null imageview null imageviewsetimagebitmapbitmap and my custom adapter looks like thispackage anothermusicplayerimport androidcontentcontenturisimport androidcontentcontextimport androiddatabasecursorimport androidneturiimport androidproviderbasecolumnsimport androidprovidermediastoreaudioalbumcolumnsimport androidprovidermediastoreaudioaudiocolumnsimport androidviewlayoutinflaterimport androidviewviewimport androidviewviewgroupimport androidwidgetcursoradapterimport androidwidgetimageviewimport androidwidgettextviewclass albumadapter extends cursoradapter public albumadaptercontext context cursor c int flags supercontext c flags private static uri currentsonguri override public void bindviewview view context context cursor cursor imageview albumart imageview viewgettagridalbumart textview text1 textview viewgettagridartisttitle textview text2 textview viewgettagridalbumtitle textview text3 textview viewgettagridtotalsongs albumartsetimagebitmapnull text1settextcursorgetstringcursor getcolumnindexaudiocolumnsartist text2settextcursorgetstringcursor getcolumnindexaudiocolumnsalbum text3settextcursorgetstringcursor getcolumnindexalbumcolumnsnumber of songs string currentalbumid cursorgetstringcursor getcolumnindexbasecolumns id integer currentalbumidlong integerparseintcurrentalbumid uri artworkuri uriparsecontentmediaexternalaudioalbumart currentsonguri contenturiswithappendedidartworkuri currentalbumidlong run imageloader asynctask here and somehow retrieve the imageview set it override public view newviewcontext context cursor cursor viewgroup parent layoutinflater inflater layoutinflaterfromcontext view view inflaterinflaterlayoutalbumitem null viewsettagridalbumart viewfindviewbyidridalbumart viewsettagridartisttitle viewfindviewbyidridartisttitle viewsettagridalbumtitle viewfindviewbyidridalbumtitle viewsettagridtotalsongs viewfindviewbyidridtotalsongs return view i would be very grateful if somebody could show me how to proceed with thisthanks,['android'] +326999,do we still need in javascript block possible duplicateusing html comment tag still relevant around javascript code kind of remember is used to prevent javascript code from being thisplayed in a lower version of ie anyone can provide a link to the article explaining this hard to search in google because it is got stripped offand do we still need this in javascript blockthanks,['javascript'] +327021,empty using statement in thispose recently i have seen some code written as followspublic void dipose using mythisposablefield this seems pretty strange to me i would prefer to see mythisposablefieldthisposewhat reasons are there for using using to thispose your objects over explicitly making the call,['c#'] +327032,see action bar across all activities android in my main activity i have my action bar how can this stay visible even if i launch a new activitydoes the new activity have to extend my main activity for this to work,['android'] +327035,mouse events and brush in d3 i am currently attempting to customize the example of a time serie chart found at this is implemented using nvd3 a library on top of d3 i would like to have tooltips for data points as in the top graph but would also like be able to select a range in the same graph like in the bottom view finder graph in the exampleto that end i have added a brush to the example of a basic line chart see the range selection works like a charm however tooltips for data points do not work anymore except for points which are just out of the range of the axes it seems that the data points lying in the brush area do not get the mouse events anymore and that the brush absorbs them allwhat needs to be changed that the data points of the lines receive mouse events in particular mouseover i do not care about clickan attempt would be to catch all events usingd3selectwindowon function and then trigger some mouseover event over data points if applicable how could this be achieved i do not want go through all data points and then check which one is closest to the mouseevent is there a more straightforward way,['javascript'] +327053,standard intent uri broken i am having problems with intent uris on a particular device so i tried the commonsware urlhandler sample as suggested here launching my app using the intent uri and the intent uri hyperlink on its sample page also fails to invoke the application the sample declares its intentfilter like thisintentfilter action androidnamecomcommonswareandroidmy action category androidnameandroidintentcategorydefault category androidnameandroidintentcategorybrowsable intentfilterand the hyperlink in the sample web page isa hrefintentintentactioncomcommonswareandroidmy actionendlink back to urlhandler via intent urlathis works on most devices but not on the htc amaze 4g running android 403 when i touch the link the logcat givesiprime9029 callbackproxy send to webviewclientiprime9029 browser send to htclinkifythispatcheriactivitymanager262 start intent from pid 9029dmpdecision891 aggress decision engine offdmpdecision891 switch back to normal parameters nw270 tw180 ns210 ts270 decision ms100 poll ms10vnfcservice600 setforegroundndefpush msg null callback nulldhtctelephony561 requestsetfastdormancy module0 mode0dwebviewtimerscontrol9029 onbrowseractivitypausedwebviewtimerscontrol9029 pausing webview timers viewcomandroidbrowserbrowserwebview40e562f8iactivitymanager262 start proc comhtchtclinkifythispatcher for activity comhtchtclinkifythispatcherhtclinkifythispatcheractivity pid11087 uid10 gids1015 3002 3001 3003 5001 5003 3007 3006 2001 1007dconnectivityservice262 onuidruleschangeduid10 uidrules0vbrowser9029 browseractivityonwindowfocuschangeddhtclinkifythispatcheractivity11087 receive actioncomcommonswareandroidmy actionihtcappassociationsutils thispatcher11087 enable by 2 trueihtcappassociationsutils thispatcher11087 method 0ihtcappassociationsutils thispatcher11087 check enable truedmpdecision891 aggress decision engine ondactivitymanager262 config after reevaluted by window manager nulldmpdecision891 switch to aggressive parameters nw1990 tw140 ns140 ts190 decision ms50 poll ms10vbrowser9029 browseractivityonwindowfocuschangeddhtctelephony561 requestsetfastdormancy module0 mode1winputmanagerservice262 window already focused ignoring focus gain of comandroidinternalviewiinputmethodclientstubproxy40e75100dwebviewtimerscontrol9029 onbrowseractivityresumedwebviewtimerscontrol9029 resuming webview timers viewcomandroidbrowserbrowserwebview40e562f8wbaseui9029 mmainview is already attached to wrapper in attachtabtocontentviewwbaseui9029 mcontainer is already attached to content in attachtabtocontentviewvnfcservice600 setforegroundndefpush msg null callback androidnfcindefpushcallbackstubproxy40e73470dmemalloc9029 devpmem unmapping buffer base0x569c50 size4386816 offset4177920dbrowser9029 browseractivityconnectivity type 1iactivitymanager262 no longer want comhtcproviderssettingsremote pid 10935 hidden 16 adj15dprocess262 killprocessquiet pid10935dprocess262 dalviksystemvmstackgetthreadstacktracenative methoddconnectivityservice262 onuidruleschangeduid10 uidrules0dprocess262 javalangthreadgetstacktracethreadjava599dprocess262 androidosprocesskillprocessquietprocessjava823dprocess262 comandroidserveramactivitymanagerserviceupdateoomadjlockedactivitymanagerservicejava15132dprocess262 comandroidserveramactivitymanagerservicetrimapplicationsactivitymanagerservicejava15294dprocess262 comandroidserveramactivitystackactivityidleinternalactivitystackjava3450dprocess262 comandroidserveramactivitymanagerserviceactivityidleactivitymanagerservicejava4303dprocess262 androidappactivitymanagernativeontransactactivitymanagernativejava362dprocess262 comandroidserveramactivitymanagerserviceontransactactivitymanagerservicejava1706dprocess262 androidosbinderexectransactbinderjava338dprocess262 dalviksystemnativestartrunnative methoddoes someone know what is going on with intent uris here why is it failing to work and is there a workaroundthankssimon,['android'] +327090,c open xml 20 numberformatid range working with open xml 20 using c to parse large excel files issue i am running into is the cell i am parsing does not have a datatype i then check the numberformatid to determine if it is decimal number or date i am looking for the exact numberformatid range for numbersdecimals vs dates they seem to be all over the place some numbersdecimals have formats of 189212214305 and dates having values of 185 194 278 etc does anyone know if the specification defines these rangesedited more informationbelow is an example of the number format of 194 from the stylexml file inside the xl folderthe excel sheets are from different regions of the world so i am thinking the number formats are different but do they overlap will numfmtid 194 be something other than a date on different culture settingsbelow is how i am converting ccellvalues like 40574 to dates but the issue is how do i know if 40574 is a date and not a number datetimefromoadateconverttodoubleccellvaluetextcurrently i am doing this by checking if there is no datatype than check the cellformat but there are issues when some of the numberformatid are not in my check private object formatcellvaluecell c sharedstringtable sstable cellformats cellformats if ccellvalue null if there is no data type this must be a string that has been formatted as a number if cdatatype null cellformat cf if cstyleindex null cf cellformatsdescendantscellformatelementatcellformat0 else cf cellformatsdescendantscellformatelementatcellformatconverttoint32cstyleindexvalue if cfnumberformatid 14 cfnumberformatid 22 cfnumberformatid 165 cfnumberformatid 180 cfnumberformatid 278 cfnumberformatid 185 cfnumberformatid 196 cfnumberformatid 217 cfnumberformatid 326 dates try datetime dt dt datetimefromoadateconverttodoubleccellvaluetextcode continueseditin my updated post i forgot to post the value i found in the stylexml filenumfmt numfmtid323 formatcodemyyso with this my question would be how do i get the formatcode and parse it to determine if it is a datebelow is the output from the immediate debug window of the numberformat 323documentformatopenxmlspreadsheetcellformat base documentformatopenxmlopenxmlcompositeelement documentformatopenxmlspreadsheetcellformat alignment documentformatopenxmlspreadsheetalignment applyalignment 1 applyborder 1 applyfill 1 applyfont 1 applynumberformat 1 applyprotection 1 borderid 64 extensionlist null fillid 0 fontid 83 formatid 37992 localname xf numberformatid 323 pivotbutton null protection documentformatopenxmlspreadsheetprotection quoteprefix 1,['c#'] +327091,echo integer on the same output line while it is being incremented i have always wondered if it is possible to do the following in phpforx 1 x 50 x echo xthis would output1234 etcobviously it wouldnt be this code specifically since it would be almost instantaneous and you wouldnt even be able to see the incrementation take placenow to my question would it be possible to echo it remove it repeat simply put the output should be on the same line from start to finish i do not know how to explain it or show but here is an example somewhat1 backspace 2 backspace etci hope you can understand it i do not know how else to explain it thank you for the helpedit this is for console by the way sorry i forgot to include that this is not for the web,['php'] +327092,what is the difference between getdir and getfilesdir on android i would like to save a picture in internal storage of my app to make it private so i did a little research and saw 2 ways to get the directory1with getdir file dir getdirenvironmentdirectory pictures contextmode private2with getfilesdir file dir getfilesdirwhich is best which returns the location in internal storage the way of writing files depends on the way you get your dir i am a bit lost since there are many ways to write files in android,['android'] +327110,d3 sort function always passes undefined arguments using d3 242 i create a number of path elements like sofor var i 0 i pathindiceslength i graphappendsvgpath stylestroke colorspathindicesi stylestrokewidth 25px stylefill none attrclass path class attrid path id prefix pathindicesi attrd linefuncdata0they all draw to the screen as expected later on i want to bring one of them to the front when the user makes some input so i have an event handler that does thisvar pathtohighlight selectpathpathindexvar paths d3selectall path classpathssort functiona b if a pathtohighlight return 1 else if b pathtohighlight return 1 else return 0 setting breakpoints in chrome indicates that my path selections here are successful paths is an array of svgpathelements but the code does nothing and setting breakpoints inside the sort function shows that a and b are always undefined going up into the d3 code i see that when the internal function d3 selection sortcomparator calls my comparator with the appropriate arguments except they are anded with their own undefined data members which causes undefined to be passed in a and b are correct but a data and b data are undefinedreturn comparatora a data b b data what am i doing wrong here my paths draw correctly to the screen so it seems like they should have the correct data rightedit images,['javascript'] +327119,where can i get the old free version of anjlabs sql profiler note although this question probably does not fit in with so is usual programming questions out of stackoverflow serverfault superuser and programmers exchange only so has any questions that make mention of this software which is why i decided to post herei used to use anjlabs open source sql profiler tool and found it to be invaluable unfortunately it looks like the software has been converted to a paid version with the all access to the open source version completely removed since this software is mentioned several times in questions here on so i was wondering if anyone still has a copy of the old free open source version and would be willing to share it,['sql'] +327196,encrypting appsettings in file external to webconfig i currently use this method to encrypt the appsettings section of my applications webconfig file aspnet regiisexe pe appsettings site mysite app but now i have moved some settings out to another file using the element appsettings fileindividualappsettingsconfig i can still encrypt the app setting in the webconfig but is there any way to encrypt the content of the additional individualappsettingsconfig file,['asp.net'] +327208,how can i get the current milliseconds from the current time note i do not want millis from epoch i want the number of milliseconds currently on the clockso for example i have this bit of codedate date2 new date long time2 long date2gethours 60 date2getminutes 60 date2getseconds 10is there a way to get milliseconds with dateis there another way to do thisnote systemcurrenttimemillis gives me millis from epoch which is not what i am looking for,['java'] +327215,how does python iterate a for loop i tried the following code on python and this is what i gotit seems like for many changes i try to make to the iterables by changing elem it does not work lis 12345for elem in lis elem 3print lis1 2 3 4 5however if the iterables are objects with its own methods like a list they can be modified in a for loop lis 12for elem in lis elemappend8print lis 1 8 2 8in the for loop what exactly is the elem term thanks in advance,['python'] +327252,can python threads access variables in the namespace i have a script that creates a bunch of threads runs a program to use the threads to run tasks from a queue and returns something from each thread i want to count how many of these returned successfully so i set a variable successful0 and increment it every time the queue reports a task completed successfullyhowever i am getting unboundlocalerror local variable successful referenced before assignmentwhats going onheres some example codesuccessful 0q queue200for i in range100 tthreadtargetfoo tdaemontrue tstartdef foo while true taskqget do some work print task successful1 triggers an error qtask donefor i in range100 qputfooqjoinprint successful,['python'] +327281,is it possible in sass to inherit from a class in another file the question pretty much says it allfor instance if i were using say twitter bootstrap could i define classes in my own sass stylesheet that inherit from bootstraps css classes or does inheritance in sass only work within the scope of a single file,['css'] +327293,strlen performance implementation this is a multipurpose questionhow does this compare to the glibc strlen implementationis there a better way to to this in general and for autovectorizationrandom filler crap because stackoverflow somehow knows better than me about code to summary ratioinclude stdinthinclude stdlibhinclude stringhinclude limitshinclude stdboolhinclude stdlibh todo document define word ones low size t1 uchar maxdefine word ones high size t1 uchar max char bit 1doc desc see if an arch word has a zero param w string aligned to word size static inline bool word has zeroconst size t w return w word ones low w word ones highdoc desc see posix strlen param s string size t strlenconst char s const char z s align to word size for uintptr ts sizeofsize t 1 s 0 s if s 0 const size t w for w const size t s word has zerow w for s const char w s 0 s return s z,['c'] +327325,importerror no module named statsmodels hi i downloaded the statsmodels source from i then untarred to usrlocallibpython27thistpackagesand per the documentation at did this sudo python setuppy installit installed but when i try to importimport statsmodelsapi as smi get the following errortraceback most recent call last file homeastrophysicshistogram fastpy line 6 in moduleimport statsmodelsapi as smimporterror no module named statsmodelsapii read a few post that have had a similar problem and checked that setuptools was installed and it was also in usrlocallibpython27thistpackagesi am kinda at a loss on this and would appriceate any helpi am also running numpy 16so thats not the problem,['python'] +327353,what does signify in a java exception what does init signify in a java exceptionfor exampleblahblahexceptionat javaiofileinputstreaminitfileinputstreamjava20,['java'] +327381,how to handle device back button on sencha touch application in sencha touch if i use navigation view i can get back button this is pretty fine but what if user hit device backbutton it is direct exiting the applicaiton in my requirement it should not exit the application it has to go back to previous screenhow can i do this,['android'] +327383,how to start using chainsaw for log4j i would like to start using chainsaw v2 there is almost no information about it i have found only this but links cannot be opened so it is not clear i use socketappender log4jrootloggerdebug serverlog4jappenderserverorgapachelog4jnetsocketappenderlog4jappenderserverport4712log4jappenderserverremotehostlocalhostlog4jappenderserverreconnectiondelay10i created file log4jxmlxml version10 encodingutf8 doctype log4jconfiguration log4jconfiguration xmlnslog4j debugtrue appender namea2 classorgapachelog4jconsoleappender layout classorgapachelog4jsimplelayout appender plugin namesocketreceiver classorgapachelog4jnetsocketreceiver param nameport value4712 plugin root level valuedebug rootlog4jconfigurationand selected it in let me search for configuration file but there are no logs what should i do next,['java'] +327386,how to use android native code in phonegap i am developing an android application using phonegap and i came across some things which are quite easy to implement in android native code when compare to phonegap so i want to know is there any way in which i can make use of android code by not changing my phonegap cross platform,['android'] +327390,ajax submit various input values with jquery ui next button click i am currently working with jquery ui tabs and ajaxpost submit without page refresh with some guidance i have been able to get the div wmdpreview submited when clicking the next button the issue is that i also have other fields i will like to submit at the same time when the next button is clicked in various tabs how can i submit the input values of various input fields in different tabs when clicking the next button examplefor some testing i currently have the other input fields submit with keyup and timer setupjs nextprevious button merged with submitajaxscript var currenttab 0 function var tabs tabstabs thisabled 0 1 2 select function if currenttab 0 ajax type post url test1php data wmdval wmdpreviewhtml success functionresult wmd resulthtml resultval resulthtml show functionevent ui currenttab uiindex uitabspaneleachfunctioni var totalsize uitabspanelsize 1 if i totalsize next i 2 thisappenda href classnexttab mover rel next next page 187a if i 0 prev i thisappenda href classprevtab mover rel prev 171 prev pagea nexttab prevtabclickfunction var tabindex thisattrrel tabstabsenable tabindex tabsselect tabindex tabsoptionthisabled 0 1 return false scripthtmldiv idtab1 classuitabspanel uitabshide label fortitletitlelabel input typetext idtitle nametitle size60 autocompleteoff value title div idwmdeditor classwmdpanel div idwmdbuttonbardiv textarea idwmdinput namewmdinputtextarea div div idwmdpreview classwmdpaneldiv div idwmd resultdiv div idtitle inputstylepadding20pxdivdivdiv idtab2 classuitabspanel uitabshide label fornamenamelabel input typetext idname namename size60 autocompleteoff value name div idname inputdiv divphp if isset posttitle wmdval posttitle echo div idtitle inputspan idresultvalh2title echo resulth2wmdvalspandivif isset postwmdval wmdval postwmdval echo div idwmd resultspan idresultvalh2description echo resulth2wmdvalspandivif isset postname name postname echo div idname inputspan idresultvalh2description echo resulth2namespandiv,"['javascript', 'jquery']" +327409,in preferences select my sound just like with ringtonepreference i have sounds in my raw folder and i would like my user to be able to choose one sound in preferences exactly like ringtonepreference does but only with my sounds,['android'] +327431,how to use single quote inside an echo which is using single quote first of all i have gone through the related questions have not found any answeri m using this code to thisplay a messageecho here goes your message with an apostrophe s like this how can i make this work as any quote inside this echo will break the statement,['php'] +327447,retry a jquery ajax request which has callbacks attached to its deferred i am trying to implement a system of retrying ajax requests that fail for a temporary reason in my case it is about retrying requests that failed with a 401 status code because the session has expired after calling a refresh webservice that revives the sessionthe problem is that the done callbacks are not called on a successful retry unlike the success ajax option callback that is called i have made up a simple example belowajaxsetupstatuscode 404 function thisurl existent url ajaxthis ajax url inexistent url success function alertsuccess donefunction alertdoneis there a way to have donestyle callbacks called on a successful retry i know a deferred cannot be resolved after it was rejected is it possible to prevent the reject or maybe copy the donelist of the original deferred to a new deferred i am out of ideasa more realistic example below where i am trying to queue up all 401rejected requests and retry them after a successful call to refreshvar refreshrequest null waitingrequests nullvar expiredtokenhandler functionxhr textstatus errorthrown only the first rejected request will fire up the refresh call ifrefreshrequest waitingrequests deferred refreshrequest ajax url refresh success functiondata session refreshed good refreshrequest null waitingrequestsresolve error functiondata session cannot be saved waitingrequestsreject alertyour session has expired sorry put the current request into the waiting queue functionrequest waitingrequestsdonefunction retry the request ajaxrequest thisajaxsetupstatuscode 401 expiredtokenhandlerthe mechanism works the 401failed requests get fired a second time the problem is their done callbacks do not get called so the applications stalls,['jquery'] +327463,custom django admin templates not working i have been trying to get custom templates for the admin page for django working but have been unsuccessful i have read the django documentation and several blogs which explain it as being such an easy step which i assumed it wasas of right now the admin page works but my own rewrite of the css or templates is not working my setup is as followsproject folder managepy settingspy urlspy init py app viewspy modelspy init py templates admin base sitehtmlin the urlspy i haveradmin includeadminsiteurlswhich works since i cannot login etc so i am assuming the adminbase sitehtml would overwrite the default one but it is not doing a thinganyone know what is going on here i followed it from the django tutorialsguides and went onto some blogs to see if they had answers but they all said the same thingedit 1i do have my templates directory setup correctlytemplate dirs ospathjoinproject path templatesthis works correctly as i have the rest of my site working with a media directory for css etc the only thing not seeming to accept the templates is the admin section,['python'] +327517,sql wildcard search efficiency there has been a debate at work recently at the most efficient way to search a ms sql database using like and wildcards we are comparing using abc abc and abc one person has said that you should always have the wildcard at the end of the term abc so according to them if we wanted to find something that ended in abc it would be most efficient to use reversecolumn like reverseabci set up a test using sql server 2008 r2 to compare each of the following statementsselect from clmaster where address like streetselect from clmaster where address like street select from clmaster where address like reverseteerts select from clmaster where reverseaddress like reversestreetclmaster holds about 50 records there are about 7400 addresses that end street and about 8500 addresses that have street in it but not necessarily at the end each test run took 2 seconds and they all returned the same amount of rows except for street which found an extra 900 or so results because it picked up addresses that had an apartment number on the endsince the sql server test did not show any difference in execution time i moved into php where i used the following code switching in each statement to run multiple tests quicklyphp require onceconfigphp connection odbc connect connection string u p for i 0 i 500 i m time explode microtime m time m time0 m time1 starttime m time messageodbc execconnectionselect from clmaster where address like street messageodbc resultmessage1 m time explode microtime m time m time0 m time1 endtime m time totaltime endtime starttimeodbc closeconnectionecho btest took and average ofb roundarray sumtotaltimecounttotaltime8 seconds per runbrecho btest took a total ofb roundarray sumtotaltime8 seconds to runbrthe results of this test was about as ambiguous as the results when testing in sql serverstreet completed in 1665823 seconds 31 average per query and averaged 500 results found in 0228street completed in 1494500 seconds 2989 average per query and averaged 500 results found in 0177 faster time per result because it finds more results than the others in similar timereverseaddress like reversestreet completed in 1340115 seconds 2680 average per query and averaged 500 results found in 0183 secondsreversetreets completed in 1676960 seconds 3354 average per query and averaged 500 results found in 0229we expected this test to show that street would be the slowest overall while it was actually the fastest to run and had the best average time to return 500 results while the suggested reversestreet was the fastest to run overall but was a little slower in time to return 500 resultsextra fun a coworker ran profiler on the server while we were running the tests and found that the use of the double wildcard produced a significant increase cpu usage while the other tests were within 12 of each otherare there any sql efficiency experts out that that can explain why having the wildcard at the end of the search string would be better practice than the beginning and perhaps why searching with wildcards at the beginning and end of the string was faster than having the wildcard just at the beginning,['sql'] +327528,transform javascript xpath in valid php query xpath normalize js xpath php this is valid xpath in javascriptidpriceinfodivclastandardprodpricinggroupspan1and this turned into valid php xpath to be used with domxpathquery isidpriceinfodivclastandardprodpricinggroupspan1do you know any libraries or custom components that already do this transformation do you know available documentation that lists the two syntax differencesmy main concern is that there could be a lot of differences and i am looking to identify these differences and i have problems to identify these the question could be put also in different way since javascript can have different valid xpath formats how to normalize them to work with the phpone of the updates also mention that the id function is valid xpath if there is a valid dtd that contains this definition i do not have power over the input dtd and if there is a way to find a solution that works without any specific dtd it would be awesomeupdatei want to transform the first format into the second with an algorithm my input is the first one and not the second one cannot change thisas nison maal pointed out the 2nd format is valid javascript xpath as presented here this unfortunately just adds to the problem of javascript xpath fragmentationsalathe pointed out that the valid javascript xpath query works fine in php if the input documented has valid dtd dimitre novatchev mentioned this in a comment but overlooked the importance unfortunately i do not have control of the input dtd so now i have to investigate a way to overcome this or to find a solution that works even without valid dtd,"['php', 'javascript']" +327532,how can i call a sql function in c i have created a function in sql now i need to use that function in my c applicationi tried using something like this but it seems i am doing it wrong since i am gettingmust declare the scalar value 2064734117when i give 2064734117 as the first parameter and 1 as the second parameter here is the code i am talking aboutsqlconnection con new sqlconnectionclsdbconnectionstringstring query stringformatselect function101 intparseecurrentrowcellscodemelivaluetostring1conopensqlcommand cmd new sqlcommandqueryconsqldataadapter reader new sqldataadapterreaderselectcommand cmddatatable table new datatablereaderfilltableradgridview1datasource tableconcloseand my function takes two integer parameters and returns a table i checked it in visual studio and it worked but i could not get it to work in my applicationand this is my function declaration alter function dbofunction1parameter1 int 5parameter2 datatypeid intclstypeid int returns table table variable table column1 datatype column2 datatype as begin insert into table variable select from return select from tblclass2 where stnid id and classtypeid clstypeid end gocan someone please help me get through this,"['c#', 'sql']" +327552,how to test multiple properties of an object i am getting a json structure from an api and need to check whether the successfull response has two specific attributes with specific valueskey problemsi cannot compare the whole object as there are some properties which may vary with each requesti cannot write two tests for each attribute because it can be considered as successful response only when both attributes matches the right valuesexample successful response success true user ip 212203040 id 7629428643dirty solution would bephppublic function testaddaccount response thisapiaddaccount 7629428643 thisasserttrue responsesuccess true responseid 7629428643 but i think there must be better and cleaner solution is there,['php'] +327556,why do html adhere to the old ie5 box model in all modern browsers i have had a weird issue with a button and some css i noticed that it was behaving as if it adhered to the old ie5 box model where height height paddingafter some browsing i came across this article which confirmed my assumptions but did not explain why this is the casedoes anybody know why all modern browsers firefox chrome ie9 treat button elements like this and does anybody know of a workaround to make button elements use the box model that as far as i can tell ever other element in those browsers uses,"['html', 'css']" +327561,ruby on rails put method on update ajax could someone tell me why this put method does not work pleaseajax type put datatype script url resources35 data resource pos y 45 pos x 50 donefunction msg alert data saved msg server says that i have used the get method but in my ajax request i have type putstarted get resources35resource5bpos y5d45resource5bpos x5d50 1344001820350 for 192168189 at 20120803 155020 0200processing by resourcescontrollershow as parameters resourcepos y45 pos x50 1344001820350 id35 user load 03ms select users from users resource load 01ms select resources from resources where resourcesid limit 1 id 35 rendered resourcesshowhtmlerb within layoutslogin 23mscompleted 200 ok in 238ms views 2359ms activerecord 04msresources controllerrb put resources1 put resources1json def update resource resourcefindparamsid respond to do format if resourceupdate attributesparamsresource formathtml redirect to resource notice successfully updated formatjs else formathtml render action edit formatjs end end endi have tried adding method put but it is still the sameajax type put datatype script url resources35 data resource pos y 45 pos x 50 method put donefunction msg alert data saved msg server resource5bpos y5d45resource5bpos x5d50methodput1344004390840started get resources35resource5bpos y5d45resource5bpos x5d50 methodput 1344004390840 for 192168189 at 20120803 163310 0200processing by resourcescontrollershow as parameters resourcepos y45 pos x50 1344004390840 id35 user load 03ms select users from users resource load 01ms select resources from resources where resourcesid limit 1 id 35 rendered resourcesshowhtmlerb within layoutslogin 08mscompleted 200 ok in 93ms views 905ms activerecord 04msi would appreciate any help,"['javascript', 'jquery', 'ruby-on-rails', 'ruby']" +327576,curl getting http code im using curl to get the status of a site if its updown or redirecting to another site i want to get it as streamlined as possible but it is not working wellphpch curl initurlcurl setoptchcurlopt returntransfer1curl setoptchcurlopt timeout10output curl execchhttpcode curl getinfoch curlinfo http codecurl closechreturn httpcodei have this wrapped in a function it works fine but performance is not the best because it downloads the whole page thing in if i remove output curl execch it returns 0 all the timedoes anyone know how to make the performance better,['php'] +327607,floats vs rationals in arbitrary precision fractional arithmetic cc since there are two ways of implementing an ap fractional number one is to emulate the storage and behavior of the double data type only with more bytes and the other is to use an existing integer apa implementation for representing a fractional number as a rational ie as a pair of integers numerator and denominator which of the two ways are more likely to deliver efficient arithmetic in terms of performance memory usage is really of minor concerni am aware of the existing cc libraries some of which offer fractional apa with floats and other with rationals none of them features fixedpoint apa however and of course i could benchmark a library that relies on float implementation against one that makes use of rational implementation but the results would largely depend on implementation details of those particular libraries i would have to choose randomly from the nearly ten available ones so it is more theoretical pros and cons of the two approaches that i am interested in or three if take into consideration fixedpoint apa,"['c++', 'c']" +327618,casting parent to child bufferedimage object i am get a classcastexception whenever i try to cast a bufferedimage parent to an advancedbufferedimage child which i extended myself i have not overridden any methods and i have implemented all the contractors without modifying themi am gettign this exception whenever i try to create an advancedbufferedimage out of file using imageioread methodfile file new filepathadvancedbufferedimage image advancedbufferedimage imageioreadfileit seems there should not be any problem what could be the problem,['java'] +327634,get function callers information in python i want to get information about the callers of a specific function in python for exampleclass someclass def init self x selfx x def callerself return special funcselfxdef special funcx print my caller is the caller function in an someclass classis it possible with python,['python'] +327635,sysstdinreadlines hangs python script everytime i am executing my python script it appears to hang on this linelines sysstdinreadlineswhat should i do to fixavoid thiseditheres what i am doing with lineslines sysstdinreadlinesupdates linesplit for line in linesedit 2i am running this script from a git hook so is there anyway around the eof,['python'] +327684,applicationintegrated send feedback i am looking for an jar or library project that will allow users of my application to easily send feedback from inside the application about their experienceas asked in this question i am looking for something similar to the crash reporting tool used in google plus that allows the user to get in contact with me besides leaving bad reviewssome notquite there solutions that came up in answers to other questionsacra application crash report for android functions as a crash reporting toolhockey kit helps thistribute betas nothing related to send feedback to developerdoes a library like this exist is there an easy way to gather user feedback from within the application,['android'] +327705,how can i convert image url to systemdrawingimage i am using vbnet i have an url of an image let us say httplocalhostimagegifi need to create a systemdrawingimage object from that filenotice save this to a file and then open it is not one of my options also i am using itextsharphere is my code dim rect as itextsharptextrectangle rect itextsharptextpagesizeletter dim x as pdfdocument new pdfdocumentchart rect 1 1 1 1 xusername objcurrentuserfullname xwritepageheader1 for i 0 to chartobjcount 1 dim chartlink as string httplocalhostimagegif xwritechart it only accept systemdarwingimage next xwritepagefooter xfinishfalse,"['c#', 'asp.net', '.net']" +327736,ie7only stylesheet for xsl document how do i add an ie7andloweronly stylesheet to an xsl page i tried adding it into the template for header information like soxsltemplate nameheaderif lte ie 7link relstylesheet typetextcss hrefrcmverisignstyle2012ie7cssendifxsltemplateand the conditional never gets executed in my document even though i use the same snippet in htmlonly documents and it works fine what gives,['css'] +327748,acitverecord would not accepts nested attributes for new associated records with nested existing records activerecord does not seem to understand that given a set of params for an existing record with nested attributes it can create a new nested record that itself has a nested existing record relations tree existing new existingis this a bug or am i missing somethinglet me show you a simple examplehere are my modelsclass user activerecordbase has many posts attr accessible name posts attributes accepts nested attributes for postsendclass post activerecordbase belongs to group belongs to user attr accessible content title group attributes accepts nested attributes for groupendclass group activerecordbase has many posts attr accessible nameendi have made one record in each table and related them accordingly so each table has a record in it with an id1this is known now if i have an existing user a new post and an existing group and try to update that record using accepts nested attributes for it does not like it193p125 044 params id 1 name billy posts attributes 0 title title content some magnificent content for you group attributes id 1 name group 1 193p125 045 uuser0x02f7f380 id 1 name billy created at fri 03 aug 2012 202137 utc 0 updated at fri 03 aug 2012 202137 utc 0193p125 046 uupdate attributes params 01ms begin transaction 01ms rollback transactionactiverecordrecordnotfound could not find group with id1 for post with id from hometrevorrvmgemsruby193p125gemsactiverecord327libactive recordnested attributesrb462in raise nested attributes record not found from hometrevorrvmgemsruby193p125gemsactiverecord327libactive recordnested attributesrb332in assign nested attributes for one to one association from hometrevorrvmgemsruby193p125gemsactiverecord327libactive recordnested attributesrb288in group attributes from hometrevorrvmgemsruby193p125gemsactiverecord327libactive recordattribute assignmentrb94in block in assign attributes from hometrevorrvmgemsruby193p125gemsactiverecord327libactive recordattribute assignmentrb93in each from hometrevorrvmgemsruby193p125gemsactiverecord327libactive recordattribute assignmentrb93in assign attributes from hometrevorrvmgemsruby193p125gemsactiverecord327libactive recordbaserb498in initialize from hometrevorrvmgemsruby193p125gemsactiverecord327libactive recordreflectionrb183in new from hometrevorrvmgemsruby193p125gemsactiverecord327libactive recordreflectionrb183in build association from hometrevorrvmgemsruby193p125gemsactiverecord327libactive recordassociationsassociationrb233in build record from hometrevorrvmgemsruby193p125gemsactiverecord327libactive recordassociationscollection associationrb112in build from hometrevorrvmgemsruby193p125gemsactiverecord327libactive recordnested attributesrb405in block in assign nested attributes for collection association from hometrevorrvmgemsruby193p125gemsactiverecord327libactive recordnested attributesrb400in each from hometrevorrvmgemsruby193p125gemsactiverecord327libactive recordnested attributesrb400in assign nested attributes for collection association from hometrevorrvmgemsruby193p125gemsactiverecord327libactive recordnested attributesrb288in posts attributes from hometrevorrvmgemsruby193p125gemsactiverecord327libactive recordattribute assignmentrb85in block in assign attributes from hometrevorrvmgemsruby193p125gemsactiverecord327libactive recordattribute assignmentrb78in each from hometrevorrvmgemsruby193p125gemsactiverecord327libactive recordattribute assignmentrb78in assign attributes from hometrevorrvmgemsruby193p125gemsactiverecord327libactive recordpersistencerb216in block in update attributes from hometrevorrvmgemsruby193p125gemsactiverecord327libactive recordtransactionsrb295in block in with transaction returning status from hometrevorrvmgemsruby193p125gemsactiverecord327libactive recordconnection adaptersabstractdatabase statementsrb192in transaction from hometrevorrvmgemsruby193p125gemsactiverecord327libactive recordtransactionsrb208in transaction from hometrevorrvmgemsruby193p125gemsactiverecord327libactive recordtransactionsrb293in with transaction returning status from hometrevorrvmgemsruby193p125gemsactiverecord327libactive recordpersistencerb215in update attributes from irb15 from hometrevorrvmgemsruby193p125gemsrailties327librailscommandsconsolerb47in start from hometrevorrvmgemsruby193p125gemsrailties327librailscommandsconsolerb8in start from hometrevorrvmgemsruby193p125gemsrailties327librailscommandsrb41in top required from scriptrails6in require from scriptrails6in main193p125 047 it thinks it cannot find a group with a known id related to a new postit works when i remove the id from the group attributes but it creates a new group recordit works when i give the posts attributes an id and remove the id from the group attributes and again creates a new groupit also works when they all have idsthe relationship is working193p125 059 p postnew group attributes name testing post0x04212380 id nil title nil content nil group id nil user id nil created at nil updated at nil193p125 060 pgroup 0 group0x04211868 id nil name testing created at nil updated at nil it also completely works when using posts attributes and group attributes during user creation if all of the records are newshould not it work still in the first example activerecord should be smart enough to figure this out,['ruby-on-rails'] +327754,using async await inside void method i have method with signature i cannot change it should beprotected override void oninitializeusing windows 8 metro api i need to check if file exists and read it inside this nosignaturechange methodusing plainoldcsharp i would write something likeprotected override void oninitialize try var file folderopenfilefilename fileexiststrue catchfilenotfoundexception fileexistsfalse remember in windows 8 api only way to check if file exists is handling filenotfoundexceptionalso in windows 8 api all fileio api is async so i have only fileopenfileasync methodso the question is how should i write this code using folderopenfileasync method in windows 8 api without changing signature of containing method,['c#'] +327803,networkx add node with specific position i am still a beginner with networkxi want to add multiple types of nodes in different position i used the following code pos 0 40 20 1 20 30 2 40 30 3 30 10 xnxgraphnxdraw networkx nodesxposnode size30nodelist0123node colorrbut when i want to access the graph x if i type xnode it returns an empty listand if i want to add more nodes i have to set their positions in the beginning using pos dictionary how can i add nodes to a graph in a specific location x and y using add node,['python'] +327823,socketio how to send javascript object how to send javascript object with socketio from server to client i am using socketio as websocketsending with send and listen with message eventwhen i am trying to do something like on serversidevar myobject message hello worldsocketsendmyobjecton clientside i am getting only this string object object,['javascript'] +327828,facebook web app development error i keep getting the following error on the debug console on chromeblocked the page at httpsmyurlcanvas ran insecure content from blocked the page at httpsurlcanvas ran insecure content from usalljsblocked the page at httpsurlcanvas ran insecure content from these are the js scripts attached to the headthis is a facebook app that makes get request to my own server this was working and just stopped working without any change in my code i am not sure if facebook is blocking my requests,"['javascript', 'jquery']" +327848,android how can i implement first time tutorial like go launcher in my app go launcher have a nice first time tutorial it is very similar to stock ics first time run i want to learn my app to user at first time of launchhow can i implement this transparent view which interacts with screen objects in my android app,['android'] +327873,android opengl es 2 drawing squares edit problem solvedso i have been going through the official opengl es 2 tutorials for android and i have gotten to the part that involves drawing shapes but i cannot seem to get a square to work it draws a right triangle insteadi have included the code that i am using to define and draw the shape which is copied almost exactly from the tutorial the renderer class simply creates an instance of this shape and calls the draw methodfor some reason the tutorial does not give the valuesdeclaration for vertexstride and vertexcount so the ones i have in there are educated guesses i have tried several values for vertexcount 1 thru 12 and none workthanks in advance public class square private floatbuffer vertexbuffer private shortbuffer drawlistbuffer number of coordinates per vertex in this array static final int coords per vertex 3 static float squarecoords 05f 05f 00f top left 05f 05f 00f bottom left 05f 05f 00f bottom right 05f 05f 00f top right private short draworder 0 1 2 0 2 3 order to draw vertices float color 063671875f 076953125f 0265625f 10f private final string vertexshadercode attribute vec4 vposition void main gl position vposition private final string fragmentshadercode precision mediump float uniform vec4 vcolor void main gl fragcolor vcolor int mprogram static final int vertexstride coords per vertex 4 static final int vertexcount 4 public square initialize vertex byte buffer for shape coordinates bytebuffer bb bytebufferallocatedirectsquarecoordslength 4 of coordinate values 4 bytes per float bborderbyteordernativeorder vertexbuffer bbasfloatbuffer vertexbufferputsquarecoords vertexbufferposition0 initialize byte buffer for the draw list bytebuffer dlb bytebufferallocatedirectdraworderlength 2 of coordinate values 2 bytes per short dlborderbyteordernativeorder drawlistbuffer dlbasshortbuffer drawlistbufferputdraworder drawlistbufferposition0 int vertexshader loadshadergles20gl vertex shader vertexshadercode int fragmentshader loadshadergles20gl fragment shader fragmentshadercode mprogram gles20glcreateprogram create empty opengl es program gles20glattachshadermprogram vertexshader add the vertex shader to program gles20glattachshadermprogram fragmentshader add the fragment shader to program gles20gllinkprogrammprogram creates opengl es program executables public static int loadshaderint type string shadercode create a vertex shader type gles20gl vertex shader or a fragment shader type gles20gl fragment shader int shader gles20glcreateshadertype add the source code to the shader and compile it gles20glshadersourceshader shadercode gles20glcompileshadershader return shader public void draw add program to opengl es environment gles20gluseprogrammprogram get handle to vertex shaders vposition member int mpositionhandle gles20glgetattriblocationmprogram vposition enable a handle to the triangle vertices gles20glenablevertexattribarraympositionhandle prepare the triangle coordinate data gles20glvertexattribpointermpositionhandle coords per vertex gles20gl float false vertexstride vertexbuffer get handle to fragment shaders vcolor member int mcolorhandle gles20glgetuniformlocationmprogram vcolor set color for drawing the triangle gles20gluniform4fvmcolorhandle 1 color 0 draw the triangle gles20gldrawarraysgles20gl triangles 0 vertexcount thisable vertex array gles20glthisablevertexattribarraympositionhandle,['android'] +327898,nonqt base classes i am using qt which i am new to 482 with visual studio and i have created a base class named contact i do not want this class to be qtexclusive so my intention was to make another class qcontact that will inherit contact and qobject and deal with all the qtrelated business such as the q object macro etcunfortunately when i inherited the build failed sayingmoc qcontactcpp53 error c2039 staticmetaobject is not a member of contactmoc qcontactcpp75 error c2039 qt metacast is not a member of contactmoc qcontactcpp80 error c2039 qt metacall is not a member of contacti did a little research on the web and found out that you cannot derive a qt class from nonqt class so to fix it contact could inherit qobject i tried it worked but doing so will make it exclusive to qt which is my problemso what i ask is this how can you make a nonqt base class for a qt classthank you,['c++'] +327931,what is link to t in rails 3 i watched railscast 328 this morning and i am having difficulty finding docs for a method link to tedit default thelperslinksedit edit boy scout pathboy scout class btn btnmini i understand the link to method but i am confused about the tedit parameter and it is in this method call twice an explanation or even pointing me to some docs would be great thanks for all the help,['ruby'] +327947,ios sdk getting clipboard text on application load i would like to get the text copied to clipboard when application launchingi can use following text to get the available text from clipboard but i need to use this value in a different viewcontroller how can i pass this value to my viewcontroller voidapplicationdidbecomeactiveuiapplication application nsloguipasteboard generalpasteboardstring,['ios'] +327984,how to add line break into xml file with java how to add line break after the do not edit this file comment i have tried to add textnode with line break but it does not workcodeimport javaiofileimport javaxxmlparsersdocumentbuilderfactoryimport javaxxmltransformoutputkeysimport javaxxmltransformtransformerimport javaxxmltransformtransformerfactoryimport javaxxmltransformdomdomsourceimport javaxxmltransformstreamstreamresultimport orgw3cdomdocumentimport orgw3cdomelementpublic class main public static void mainstring args try final document doc documentbuilderfactorynewinstance newdocumentbuildernewdocument docappendchilddoccreatecomment do not edit this file final element rootelement doccreateelementprojects docappendchildrootelement final transformer transformer transformerfactorynewinstancenewtransformer transformersetoutputpropertyoutputkeysindent yes transformersetoutputpropertyindentamount 2 transformertransformnew domsourcedoc new streamresultnew filecabcxml catch exception e eprintstacktrace output do not edit this file projects,['java'] +327991,image vs bufferedimage whenever dealing with the loading and rendering of images in java i have previously always used bufferedimages to store and manipulate the images in memoryhowever i have recently come across a few different sites that use the image class instead of bufferedimage and this got me wondering what are the differencesi am aware that a bufferedimage has a largeroptimised toolset but does come at any cost if so when does this cost become noticeable in which situations would you use an image over a bufferedimage or viceversa,['java'] +327996,access member variables directly or pass as parameter i noticed that even when paying respect to the single responsibility principle of ood sometimes classes still grow large sometimes accessing member variables directly in methods feels like having global state and a lot of stuff exists in the current scope just by looking at the method currently working in it is not possible anymore to determine where invidiual variables accessible in the current scope come from when working together with a friend lately i realized i write much more verbose code than him because i pass member variables still as parameters into every single method is this bad practiceedit exampleclass addnumbers public int a b int addnumbers i could have called this without arguments like this return internalalgorithmaddnumbers because the data needed to compute the result is in members return internalalgorithmaddnumbersab private int internalalgorithmaddnumbersint sum1 int sum2 return sum1sum2,['c++'] +328011,select thistinct by two properties in a list i have a listmessage that contains properties of type guid and datetime as well as other properties i would like to get rid of all of the items in that list where the guid and datetime are the same except one there will be times when those two properties will be the same as other items in the list but the other properties will be different so i cannot just use thistinctlistmessage messages getlistthe list now contains many objects it is ordered by the datetime propertymessages from p in messagesthistinct what goes here this is what i have right now but it seems like there ought to be a better waylistmessage messages getlistforint i 0 i messagescount 1 use messagescount 1 because the last one has nothing after it to compare to ifmessagesiid messagesi1id messagesidate messagei1date messagesremoveati1 else i,['c#'] +328072,does arduino use c or c coming from python the whole cc thing is kind of alien to begin with and then i see in one place that arduino uses standard c and in another that it uses standard c so on and so forth which is it my admittedly crude understanding of the difference between the two is that c is roughly c with classesobjects how does that affect which language or dialect c or c should i concentrate on learning for use primarily with arduino,"['c++', 'c']" +328111,possible to use type traits sfinae to find if a class defines a member type i have seen this question which allows one to check for the existence of a member function but i am trying to find out whether a class has a member typein the example below both evaluate to false but i would like to find a way so that has barfoo1value evaluates to false and has barfoo2value evaluates to trueis this possibleinclude iostreamstruct foo1struct foo2 typedef int bar template typename tclass has bar typedef char yes typedef long no template typename c static yes check decltypecbar template typename c static no checkpublic enum value sizeofcheckt0 sizeofyes int main stdcout has barfoo1value stdendl stdcout has barfoo2value stdendl return 0edit implementing a specialisation in response to the answers belowif you use cbar in the target template the template will be thiscarded automatically for types that do not have that nested typei have tried to do this but am clearly missing somethinginclude iostreamstruct foo1struct foo2 typedef int bar template typename t typename you voidstruct target target stdcout default target stdendl templatetypename tstruct targett typename tbar target stdcout specialized target stdendl int main targetfoo1 targetfoo2 return 0,['c++'] +328128,access variables by name in a loop i am working on an android project and i have a lot of drawables these drawables are all named like icon 0png icon 1png icon 100png i want to add all the resource ids of these drawables to an arraylist of integers for those who do not know android only java i am talking about static variables in a static inner class of a class like rdrawableicon 0 all of this static variables are integersis there a more efficient way to do this than adding them one by one likearraylistinteger list new arraylistintegerlistaddrdrawableicon 1listaddrdrawableicon 2listaddrdrawableicon 100can i loop through them somehow likeforint i0 i100 i listaddrdrawableicon i i know this does not worki have no control over the file where these static integers are and i cannot create the drawables in runtimeany help would be appreciatededitokay i read the answers but i have one major problem i do not have access to any context instances where i need to create this arraylist of ids i do it in a static initialzer block so the getresources method what two of the answers suggested wont work is there any other way of doing this,"['java', 'android']" +328148,android hebrew rtl string with numeric value flipped i would like to thisplay a string with my app name and it is current versionthe app name is in hebrew for some when i combine hebrew text with numeric value the numeric value is flippedversiontextviewsettext thisgetresourcesgetstringrstringapp versionfor example app version is 10 being thisplay as 01 on emulator,"['java', 'android']" +328204,jruby gems with c extensions does anyone has the same error with jruby when i trying to install gem with c extension i have the next errorgem install serialport building native extensions this could take a while error error installing serialport error failed to build gem native extension homeusernamervmrubiesjrubyheadbinjruby extconfrb notimplementederror c extension support is not enabled pass xcextenabledtrue to jruby or set jruby opts or modify jrubyrc to enableroot at homeusernamervmrubiesjrubyheadlibrubysharedmkmfrb8 require at orgjrubyrubykerneljava1021 root at homeusernamervmrubiesjrubyheadlibrubysharedrubygemscustom requirerb1 root at extconfrb1any arguments declared in errors explanation does not give any successinfo about installed jruby versionjruby 170preview2dev 193p203 20120805 22cd6f9 on java hotspottm server vm 170 05b05 linuxi386 platform linuxgem serialport,['ruby'] +328215,nullpointerexception when creating a new dialog i have a dialogfragment that creates a listview dialog and on a list item click i want to thisplay an alert dialog but when i create the dialog it gives me a nullpointerexception with an error that i have never seen before0805 114042315 eandroidruntime4693 javalangnullpointerexception0805 114042315 eandroidruntime4693 at androidappalertdialogresolvedialogthemealertdialogjava1420805 114042315 eandroidruntime4693 at androidappalertdialogbuilderinitalertdialogjava3590805 114042315 eandroidruntime4693 at comtyczjbowlingdialogsseasontype11onclickseasontypejava600805 114042315 eandroidruntime4693 at comandroidinternalappalertcontrollerbuttonhandlerhandlemessagealertcontrollerjava1660805 114042315 eandroidruntime4693 at androidoshandlerthispatchmessagehandlerjava990805 114042315 eandroidruntime4693 at androidoslooperlooplooperjava1370805 114042315 eandroidruntime4693 at androidappactivitythreadmainactivitythreadjava47450805 114042315 eandroidruntime4693 at javalangreflectmethodinvokenativenative method0805 114042315 eandroidruntime4693 at javalangreflectmethodinvokemethodjava5110805 114042315 eandroidruntime4693 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava7860805 114042315 eandroidruntime4693 at comandroidinternaloszygoteinitmainzygoteinitjava5530805 114042315 eandroidruntime4693 at dalviksystemnativestartmainnative methodhere is my dialogs oncreateoverridepublic dialog oncreatedialogbundle state final dialog d new dialoggetactivity dsetcontentviewrlayoutdialog layout dsettitleselect a season listview lv listviewdfindviewbyidriddialog list string list getresourcesgetstringarrayrarrayseason dialog type lvsetadapternew arrayadapterstringgetactivityrlayoutstats list layoutlist lvsetonitemclicklistenernew onitemclicklistener override public void onitemclickadapterview arg0 view arg1 int arg2long arg3 dthismiss fragmenttransaction ft getfragmentmanagerbegintransaction ifarg2 0 dialogfragment df new seasonsdialogtrue dfshowftnull else ifarg2 1 alertdialogbuilder builder new alertdialogbuildergetactivity final view v getactivitygetlayoutinflaterinflaterlayoutadd season layout null false buildersettitleadd a seasonsetviewvsetpositivebuttonadd new onclicklistener override public void onclickdialoginterface arg0 int arg1 arg0thismiss alertdialogbuilder builder2 new alertdialogbuildergetactivity error here builder2settitlewarningsetmessageadding a new season will cause all new games to be under this season do you wish to continue setpositivebuttonyes new onclicklistener override public void onclickdialoginterface dialogint which dialogthismiss edittext et edittextvfindviewbyidridedittext1 contentvalues values new contentvalues valuesputgamesseason etgettexttostring uri uri getactivitygetcontentresolverinsertgamesseasons uri values etsettext sharedpreferences pref preferencemanagergetdefaultsharedpreferencesgetactivity sharedpreferenceseditor edit prefedit editputlongpreferencesselected season contenturisparseiduricommit setnegativebuttonno new onclicklistener override public void onclickdialoginterface dialogint which dialogthismiss createshow setnegativebuttoncancel new onclicklistener override public void onclickdialoginterface dialog int which dialogthismiss createshow return dit errors out at this line in my onclickalertdialogbuilder builder2 new alertdialogbuildergetactivitywhat does that error mean,['android'] +328218,what is data serialization first of all i could not able to get clear definition of it from wikipedia or even from serialize function in the php manual i need to know some cases we need the term serialization and how things are going without it in other word where you must need serialization and without it your code will be missing some important feature,"['php', 'javascript']" +328256,how to write compile time warning for user i would like to write a pragma warning in gnu g for every user that compile my codeshow can i do thisi am using gnu g compiler,['c++'] +328272,rake tests running very slow after running some tests i am convinced there has to be something wrong with my setup windows rubymine and latest ruby versions my times right now arefinished tests in 14289817s 00700 testss 03499 assertionss1 tests 5 assertions 0 failures 0 errors 0 skipsprocess finished with exit code 0with 5 very easy tests just checking if validation on empty fields works the total time for these 5 unit tests is 160 seconds over 2 minuteswhat could i do to improve this speedhere are the testsrequire test helperclass itemtest activesupporttestcase test item attributes must not be empty do item itemnew assert iteminvalid assert itemerrorsnameany assert itemerrorsdescriptionany assert itemerrorsimage urlany assert itemerrorsratingany endend,['ruby'] +328280,threadpoolexecutor and the queue i thought that using threadpoolexecutor we can submit runnables to be executed either in the blockingqueue passed in the constructor or using the execute methodalso my understanding was that if a task is available it will be executedwhat i do not understand is the following public class mythreadpoolexecutor private static threadpoolexecutor executor public mythreadpoolexecutorint min int max int idletime blockingqueuerunnable queue executor new threadpoolexecutormin max 10 timeunitminutes queue executorprestartallcorethreads public static void mainstring main blockingqueuerunnable q new linkedblockingqueuerunnable final string names abcdef forint i 0 i nameslength i final int j i qaddnew runnable override public void run systemoutprintlnhi namesj new mythreadpoolexecutor10 20 1 q try timeunitsecondssleep5 catch interruptedexception e todo autogenerated catch block eprintstacktrace executorexecutenew runnable override public void run systemoutprintln forint i 0 i 100 i final int j i qaddnew runnable override public void run systemoutprintlnhi j this code does not do absolutely anything unless i either uncomment the executorprestartallcorethreads in the constructor or i call execute of the runnable that prints systemoutprintln it is also commented out whyquote my emphasis by default even core threads are initially created and started only when new tasks arrive but this can be overridden dynamically using method prestartcorethread or prestartallcorethreads you probably want to prestart threads if you construct the pool with a nonempty queue ok so my queue is not empty but i create the executor i do sleep and then i add new runnables to the queue in the loop to 100does not this loop count as new tasks arrivewhy does not it work and i have to either prestart or explicitely call execute,['java'] +328303,is servlet the singleton reading some book that said the servlet is singleton from the container side is this truehowever even it is a singleton we need to handle data synchronization etc,['java'] +328331,array diff with multidimensional arrays using array diff i can compare and remove similar items but what if i have the following arraysarray1array 0 array item 1 1 array item 2 2 array item 3 array2array 0 array item 2 1 array item 3 2 array item 1 3 array item 4 i want to filter out the similar items result should return 4 how can i rearrange my array so that i can use array diff,['php'] +328338,cannot get location in ios geoerrordomain code204 i am trying to thisplay a map and drop a pin using mkmapview this is my codemkcoordinateregion region 00 00 00 00 regioncenterlatitude 3747 regioncenterlongitude 126regionspanlongitudedelta 001fregionspanlatitudedelta 001fmapview setregionregion animatedyesbut i get the error belowgeotilesource 0x8e4c160 error downloading tiles server error error domaingeoerrordomain code204 the operation couldnat be completed geoerrordomain error 204 userinfo0x88990f0 underlyingerrorserror domaingeoerrordomain code204 the operation couldnu2019t be completed geoerrordomain error 204 userinfo0x885b570 incompleteresponseasked for 2 tiles but only got 0 backerror domaingeoerrordomain code204 the operation couldnu2019t be completed geoerrordomain error 204 userinfo0x8890a50 incompleteresponseasked for 6 tiles but only got 0 backi am not finding any reference to what geoerrordomain code204 is please help me out,"['objective-c', 'ios']" +328374,what is the difference between onclickjavascript functionvalue and onclickfunctionvalue what is the difference between the followingonclickjavascript functionvalueonclickfunctionvaluewhen do i use the javascript before the function call and whycan i call the function without using javascript prefixplease help me understand the difference,['javascript'] +328435,jvm over clr and viceversa i use java and net since many years now and i see many implementations of the jvm and the clr around many oss many vendors etc but i am asking here if anyone knows about implementing a clr on a jvm or a jvm on a clrif such a bridge could be done it should make thing really more runtime portablei know there are few differences and many similarities between clr and jvm but there are also crosscompilers between the two runitimes like xmlvm and maybe it is possible to give this functionality at runtimeis this possible if not what are the principal technical obstacles,"['java', '.net']" +328445,looking for a modern comparison between aspnet mvc and monorail i am coming from ruby on rails and i need to create a c web application currently i am looking at aspnet mvc and monorail most of the comparisons i find are from 20082009 when aspnet mvc was still new and most of the points against mvc was that it is too raw not nearly as refined as monorailwell several years have past since then and microsoft did alot of work on aspnet mvc how do the modern versions of the two frameworks compare to each other,"['c#', '.net']" +328478,profile junit in eclipse indigo using visualvm how can i profile a junit test preferentially with eclipse integrated support i am trying to do it using visualvm but apparently it cannot be donei am using windows 7 x64 eclipse indigo jdk 16 jrej9 and junit 3 i could use v4,['java'] +328486,interleaving two numpy index arrays one item from each array i have two ordered numpy arrays and i want to interleave them so that i take one item from the first array then another from the second then back to the first taking the next item that is larger than the one i just took from the second and so onthose are actually arrays of indices to other arrays and i will be ok with operating on the original arrays as long as the operation is vectorized but of course working on the index array as a vector operation will be awesomeexample ok to assume that the intersection of arrays is emptya array12347891017b array56131415192123i would like to get 157131719,['python'] +328510,why does self class super class i expected super class to return the superclas class however i found using this code that it returns this clas classcodenslogobjectself classnslogobjectsuper classnslogobjectself superclassnslogboolself class super classoutputself class mainmenuscenesuper class mainmenusceneself superclass ccsceneself class super classyescan somebody explain why this happens please i expect it to return the same value as self superclassmacrosdefine nslogbooli nslogs i i yes nodefine nslogobjecto nslogs o o,"['ios', 'objective-c']" +328515,cannot convert type anonymoustype1 do you know how fix this error it s show error in this line foreach int s in itemcollwhat i have to doerror 1 cannot convert type anonymoustype1 to int cusersrafaldesktopmvc ksiazkamoj projektsklepsportsstorewebuicontrollersproductcontrollercs 37 21 sportsstorewebuivar itemcoll from p in rekategorie where pnazwa category select new pid kat foreach int s in itemcoll consolewritelines,['c#'] +328531,differences between functoolspartial and a similar lambda in python suppose i have a function f that i want to pass around with some secondary arguments assume for simplicity that it is just the first argument that remains variablewhat are the differences between doing it these two ways if any assume secondary args and secondary kwargs have been definedimport functoolsg1 functoolspartialf secondary args secondary kwargsg2 lambda x fx secondary args secondary kwargsin the doc page for partial for example there is this quotepartial objects defined in classes behave like static methods and do not transform into bound methods during instance attribute lookupwill the lambdamethod suffer from this if used to make a class method from arguments supplied to the class either in the constructor or through a function later on,['python'] +328546,lazy lazy loading error a field initializer cannot reference the nonstatic field method or property i am trying to use lazy loading for the first time to initialize a progress object in my class however i am getting the following errora field initializer cannot reference the nonstatic field method or propertyprivate lazyprogress m progress new lazyprogress long totalbytes m transfermanagertotalsize return new progresstotalbytesin net 20 i can do the following but i would prefer to use a more up to date approachprivate progress m progressprivate progress progress get if m progress null long totalbytes m transfermanagertotalsize m progress new progresstotalbytes return m progress can anyone helpmany thanks,"['c#', '.net']" +328579,c passing an array pointer as a function argument i am trying to use pointers of arrays to use as arguments for a function which generates an arrayvoid generatearrayint a int si srandtime0 for int j0jsij aj0rand9 end generatearrayint main const int size5 int asize generatearraya size return 0 end mainbut when i compile this this message appearscannot convert int 5 to int for argument 1 to void generatearrayint int,['c++'] +328593,combobox items empty but datasource full after binding a list to combobox its datasourcecount is 5 but combobox item count is 0how can it be i am used to web programming and this is in windows formsso no combodatabind method existsthe problem here is i am trying to set the selected item programmatically since i do not see the comboitems collection filled i cannot set the desired itemupdatea total update is needed i guessdatasource contains 7 itemswhen bound to combobox thisplaymember and valuemember are appropriately implementedafter databound through the gui i can clearly see the 7 items in the comboboxcomboboxdatasourcecount 7 and comboboxitemscount 0so the problem is here since after databound no items are there in the itemcollection of combobox i cannot search for one to match and set the appropriate onehere is a image for better understanding but i am pretty sure i am missing sth simple,['c#'] +328611,in eclipse is it possible to find all methods in project that take a certain parameter type so that is basically my question i am converting all methods arraylists to hashmaps in parameterized methods but i do not want to convert all arraylists to hashmaps since there are a few that are used locally this is more of a curiosity than anything but it would be usefulso in eclipse is it possible to find all methods in project that take a certain parameter type,"['java', 'android']" +328619,sqlalchemy simple example of sum average min max for sqlalchemy who can gently give simple examples of sql functions like sum average min max for a column score in the following as an exampleas for this mapperclass scorebase name columnstring score columninteger,"['python', 'sql']" +328621,responsive image max height 100 doesnt work in firefox i am currently trying to make an image resize depending on the browser dimensions i have managed to get the image to resize horizontally if i make the browser window narrow the image will resize proportionally just fine however when i resize the window vertically firefox just does not seem to want to do it the code is pretty simplebody div idcontent img srcimagesabcjpg div bodyand the csscontent height 100 padding 50pxcontent img maxheight100 maxwidth 100another issue is that the image does seem to resize vertically in chrome but i have to drag the bottom of the browser well over the image before it start doing this i would rather the image start to rezise as soon as the bottom content padding hits the bottom of the image so to speak hope this is making senseany help much appreciated,"['html', 'css']" +328623,implementing functoolspartial that prepends additional arguments the documentation for functoolspartial says that it is roughly equivalent todef partialfunc args keywords def newfuncfargs fkeywords newkeywords keywordscopy newkeywordsupdatefkeywords return funcargs fargs newkeywords line to change newfuncfunc func newfuncargs args newfunckeywords keywords return newfuncif i wanted to implement a version that prepends the additional argumentsit seems like i would just have to change the indicated lineare there any other featuresgotchas that i should be worried about in just copying this code,['python'] +328642,django using annotate count and thistinct on a queryset heres my database queryresults attachmentsobjectsfiltercurrencycurrentannotatenum attachmentscountarticle idorder bynum attachmentsthistinctarticle idthe query broken down as follows as i understand itfirst filter is current attachments that are currentthen to count the number of those attachments with a certain article idthen to annotate each attachment with the number of attachment with the number of those that have article id in commonthen to rank based on the number of attachmentsthen paring down the list with thistinct so that there is one attachment object for each article id valuei am running this on postgresql so according to the django docs i am fine to run thistinct based on a fieldthere is no error when i execute the query but when i try to iterate or even print the results the following error is thrown by django debugnotimplementederror at functionannotate thistinctfields not implementedthe more detailed traceback from the interactive prompt is file console line 1 in module file userspatvirtualenvsenvsplibpython27sitepackagesdjangodbmodelsquerypy line 118 in result iter self fill cache file userspatvirtualenvsenvsplibpython27sitepackagesdjangodbmodelsquerypy line 875 in fill cache self result cacheappendself iternext file userspatvirtualenvsenvsplibpython27sitepackagesdjangodbmodelsquerypy line 291 in iterator for row in compilerresults iter file userspatvirtualenvsenvsplibpython27sitepackagesdjangodbmodelssqlcompilerpy line 763 in results iter for rows in selfexecute sqlmulti file userspatvirtualenvsenvsplibpython27sitepackagesdjangodbmodelssqlcompilerpy line 808 in execute sql sql params selfas sql file userspatvirtualenvsenvsplibpython27sitepackagesdjangodbmodelssqlcompilerpy line 107 in as sql annotate thistinctfields not implementednotimplementederror annotate thistinctfields not implementedanyone know whats going on here,['python'] +328669,css bootstrap thisplay button inline with text i am using twitter bootstrapi am trying to create a button with dropdown that should be thisplayed right after a textthe button and everything are created but it appears on the next line instead of being on the same line as my textethis is more or less the codeh1 some title div classbtngroup xmlns button classbtn btnminieditbutton button classbtn btnmini dropdowntoggle datatoggledropdown span classcaretspan button ul classdropdownmenu li my menusli ul divh1the h1 tag has no special positioning assigned i have tried to add a float left to the h1 tag but it does not work because there is a clearboth in the btngroups csswhats wrong thxupdatei also tried to add a pullright class to the div this brings it to the right line but it is on the right of the page not just after the text this is too far away,['css'] +328673,why i do i fall into all of the hurdles for a simple update in ef i have an id with me and i have name with me so in essence my method just has these parameterspublic void fooint id string nameand i have this piece of logic inside methoduser user new user id id name name dbentryuserstate systemdataentitystatemodifieddbsavechangesthat is it nothing fancy i get this error an object with the same key already exists in the objectstatemanager the objectstatemanager cannot track multiple objects with the same keyand this answer by lathislav mrnka an object with the same key already exists in the objectstatemanager the objectstatemanager cannot track multiple objects with the same keysuggests to use contextentryoldentitycurrentvaluessetvaluesnewentity but i do not really have oldentity with me can anybody just please tell me how do i update just 1 property of user i am getting nuts,"['c#', 'asp.net']" +328678,stanford core nlp java output i am a newbie with java and stanford nlp toolkit and trying to use them for a project specifically i am trying to use stanford corenlp toolkit to annotate a text with netbeans and not command line and i tried to use the code provided on using the stanford corenlp api question is can anybody tell me how i can get the output in a file so that i can further process iti have tried printing the graphs and the sentence to the console just to see the content that works basically what i would need is to return the annotated document so that i can call it from my main class and output a text file if that is possible i am trying to look in the api of stanford corenlp but i do not really know what is the best way to return such kind of information given my lack of experiencehere is the codeproperties props new properties propsputannotators tokenize ssplit pos lemma ner parse dcoref stanfordcorenlp pipeline new stanfordcorenlpprops read some text in the text variable string text the quick fox jumps over the lazy dog create an empty annotation just with the given text annotation document new annotationtext run all annotators on this text pipelineannotatedocument these are all the sentences in this document a coremap is essentially a map that uses class objects as keys and has values with custom types listcoremap sentences documentgetsentencesannotationclass forcoremap sentence sentences traversing the words in the current sentence a corelabel is a coremap with additional tokenspecific methods for corelabel token sentencegettokensannotationclass this is the text of the token string word tokengettextannotationclass this is the pos tag of the token string pos tokengetpartofspeechannotationclass this is the ner label of the token string ne tokengetnamedentitytagannotationclass this is the parse tree of the current sentence tree tree sentencegettreeannotationclass this is the stanford dependency graph of the current sentence semanticgraph dependencies sentencegetcollapsedccprocesseddependenciesannotationclass this is the coreference link graph each chain stores a set of mentions that link to each other along with a method for getting the most representative mention both sentence and token offsets start at 1 mapinteger corefchain graph documentgetcorefchainannotationclass,['java'] +328697,html inputfile accept attribute file type csv i was hoping someone can help me out i have a file upload object on my page input typefile idfileselect with the following excel files on my desktopfile1xlsx file1xlsfilecsvi want the file upload to only show xlsx xls csv files using the accept attribute i found these contenttypes took care of xlsx xls extensions accept applicationvndopenxmlformatsofficedocumentspreadsheetmlsheet xlsxaccept applicationvndmsexcel xlshowever i cannot find the correct contenttype for an excel csv file any suggestions example,['html'] +328701,when is the use of stdref necessary considerstdtupleint const a func const a a return stdmake tuple 0 stdrefa is the stdref required for writing correct and portable code it compiles fine without itbackgroundif i remove stdref my code builds fine without any warnings g46 wall but does not run correctlyin case of interest the definition of astruct a stdarrayint2 vec typedef int type t templatetypename opstypename vals a operatorconst stdpair stdtuplevals stdtupleops e for int i 0 i vecsize i veci eval extractiefirst esecond,['c++'] +328751,ios look inside provisioning profile is it possible to inspect the insides of a provisioning profile i am dealing with a code signing error because the entitlements do not match fixing this is rather difficult as i do not know how to inspect the entitlements in the provisioning profile hence i am shooting in the darkrelated questions here here and here none of which seem to help in my case,"['iphone', 'ios']" +328752,python subprocess set shell var and then run command how i need to do this export pyro hmac key123 python m pyro4namingso i found that the second one is possible to do with subprocesspopenpythonmpyro4namingbut how export shell variable before that,['python'] +328779,i need to run two funcions onclick i cannot get them both to work even when nested together the html isinput namesubmit typesubmit classbutton valueclick here tabindex13 onclickreturn validateform the validateform function has all the usual form validating codethe other function i cannot get to run except by itself it works fineexample input namesubmit typesubmit classbutton valueclick here tabindex13 onclickthisdelaythis i tried putting them both after the onclickexample input namesubmit typesubmit classbutton valueclick here tabindex13 onclickreturn validateform thisdelaythis i also tried putting one the code in the same function with no successthe function thisdelay isfunction thisdelayobj objsetattributethisabledthisabled settimeoutfunctionobjremoveattributethisabled10it is to be used as a delay to keep the form from getting duplicate submissions from multiple clicks the delay is at 10 seconds right now just for testing purposesi need the validation and delay to work together,['javascript'] +328781,storing cookies windows store app as i thiscovered here when i make a call to a server to ask for authentication in the form of a cookie the cookie in the response is handled automatically by the underlying metro framework however this means i do not have access to the cookie and therefore cannot store it when the app is suspended for later use how are we supposed to sstore cookie information in the metro frameworkall help is greatly appreciated and i always accept an answer,['javascript'] +328787,is my method working effectively i am writing a code for a deck of cards which shuffles the deck of cards i tested the code but i do not really know if it is actually doing what it is supposed to be doing correctly what do you thinkthis is the code for the shuffle methodpublic void shuffle for int x mydecksize x 0 x random rn new random int index1 rnnextint52 card c mydeckremoveindex1 mydeckaddc my output seems shuffled in its numbers but not by the name of the card like spades hearts etc for example this is my output when i test the code deuce of spadesseven of spadeseight of spadesace of spadesthree of heartsfive of heartssix of heartsseven of heartsnine of heartsten of heartsqueen of heartsking of heartsace of heartsseven of diamondseight of diamondsjack of diamondsking of diamondsthree of clubsseven of clubsnine of clubsjack of clubsqueen of clubsking of clubsace of clubsqueen of spadesdeuce of clubsthree of spadesnine of diamondsfour of spadesfour of clubsdeuce of heartsjack of spadesten of clubssix of diamondsjack of heartssix of clubsfour of diamondsfive of diamondsace of diamondsfour of heartsnine of spadesten of spadesfive of spadesthree of diamondssix of spadesfive of clubsdeuce of diamondseight of heartsking of spadesten of diamondseight of clubsqueen of diamondslike there is always repeated names is it wrong since the point of shuffling is to mix it upthis is the actual question when playing cards it is of course important to shuffle the deck that is toarrange things so that the cards will be dealt in a random order there areseveral ways to achieve this one strategy involves repeatedly picking a cardat random out of the deck and moving it to the end the following code usesthe random class which you met on page 8 of the aarraylistsa section of theonline course to perform one such apick and move to the enda operationrandom rn new randomint index1 rnnextint 52 card c mydeckremove index1 mydeckadd c to shuffle the deck effectively this operation should be repeated many timessay 500 times create a new instance method shuffle for the deck classthat uses a single random object and a for loop to shuffle mydeck aftersuitably modifying the main method use it to test your new codeso my main question is am i doing this wrong,['java'] +328793,how does androidnohistorytrue work lets say i have a base activity with a menu when i click on menu item a it goes to activity a i open the menu again and go to b from b i go back to a and back and fourth like this for a whileso the stack would be a b a b a b and when i hit the back button it goes backwards through the stack as expectedhowever lets say i do not want this functionality so i add to my manifest androidnohistorytrue so when i hit the back button it exits the application instead of going though the stacknow the illusion makes it seem lets say if i am in activity a i use the menu and go to activity b the stack would just be b because i cannot go back to abut when using nohistorytrue does the true stack of a b a b a b exist rather is every call to an activity by using the menu instantiating a new copy of that activity but the user cannot see it would this be causing resource issuesor when nohistoryfalse does the back button just call something like startacitvityintent again or is it going through each new copy that was instantiated i am concerned with resource issues and not slowing down a users android device,['android'] +328804,unable to cmdclick on java method in eclipse in mountain lion yesterday i upgraded from lion to mountain lion and today my productivity went down i cannot perform cmd click on a method or variable to go its declaration because the popup shown in eclipse contains a horizontal scrollbar which overflows the last option does anyone have a solution how to fix this update just to be clear neither when scrolling nor automatically based on mouse or trackpad options remove the problem for me only always does work but its consequences to the whole system ux are not acceptable,['android'] +328827,is there a way to search the ios app store online i want to programmatically track my apps search ranking on apples app store is there any api or website to do this outside of the app store app on my iphone,['ios'] +328834,rename a build in buildbot is there a way to rename a build in buildbot without losing all of the logsfor instance i have several windows slaves which all might build windows 2008 debug but i want to rename this build to windows 2008r2 debughow do i set compare attr if that is even what i need to do so that all of the logsetc are included from the previous builds in the new onecan i manually rename the directories and expect everything to work experimentation has told me that will not work but maybe i can write a command to change certain things,['python'] +328894,find and replace text in the entire table using a mysql query usually i use manual find to replace text in a mysql database using phpmyadmin i am tired of it now how can i run a query to find and replace a text with new text in the entire table in phpmyadmin example find keyword domaincom replace with wdomaincomthanks,['mysql'] +328898,how to use curl in javascript i am writing a chrome extension and i want to use curl to get me the download links of the gmail attachments how should i do it i am new to curl and i do not know how would i able to use the curl library in javascript,['javascript'] +328912,how do i use the old javadoc style theme with jdk 7 the new theme in jdk 7 for javadoc is hard for me to read it may not be pretty but i really would prefer the old theme aside from installing the old jdk and switching between them can i somehow use the old doclet,['java'] +328939,high performance jms messaging i read slides from this years uberconf and one of the speakers is making the argument that spring jms adds a performance overhead to your message queue system however i do not see any evidence to support that in the slides the speaker also makes the case that pointtopoint is faster than the traditional publishsubscribe method because each message is sent only once instead of being broadcasted to every consumeri am wondering if any experienced java messaging gurus can weighin here and clarify a few technicalitiesis there actually a performance overhead incurred by using spring jms instead of just pure jms if so how and where is it introduced is there any way around itwhat actual evidence is there to support that p2p is faster than the pubsub model and if so are there ever any cases when you would want to pubsub over p2p ie why go slower,['java'] +328957,event order capturingbubbling i am trying to understand what determines the order in which event handlers are triggered when clicking a nested div what i am seeing seems to be at odds with documented behaviour so i am looking for a little help to understand iti have 2 nested divs and i have 2 event handlers attached to each one for the capturing phase and one for the bubbling phasehtml head script function setup var outer documentgetelementbyidouter outeraddeventlistenerclick functionconsolelogouter false false outeraddeventlistenerclick functionconsolelogouter true true var inner documentgetelementbyidinner inneraddeventlistenerclick functionconsoleloginner false false inneraddeventlistenerclick functionconsoleloginner true true script style div border 1px solid padding 1em style head body onloadsetup div idouter div idinner click div div bodyhtmlaccording to what i have read the output should beouter trueinner trueinner falseouter falsebut what i actually see on chrome and firefox isouter trueinner falseinner trueouter falsecan anyone explain the thiscrepancy,['javascript'] +328963,setting the useragent header for a webclient request what is the proper way of setting the useragent header for a webclient request for windows phone 7i found 2 options but not sure which one is the correct one considering a webclient objectwebclient client new webclienti saw 2 optionsset the useragent using clientheadersuseragent myuseragentstringset the useragent using the webheadercollectionwebheadercollection headers new webheadercollectionheadershttprequestheaderuseragent useragentstringclientheaders headerscan you please advise which of the 2 methods above is the proper one,['c#'] +329013,logoutsession timeout catching with spring security i am using springspringsecurity 31 and want to take some action whenever the user logs out or if the session is timed out i managed to get the action done for logout but for session timeout i cannot get it workingin webxml i only have the contextloaderlistener specified can this be the issue and of course the delegatingfilterproxyi use the auto config like this securityhttp autoconfigfalse useexpressionsfalse securityintercepturl patterndialog accessrole users securityintercepturl patternboa accessroleusers securityintercepturl patternhtml accessroleusers securityformlogin loginpageauthloginhtml defaulttargeturlindexhtml securitylogout logouturllogout invalidatesessiontrue deletecookiesjsessionid successhandlerreflogouthandler securityhttpbean idlogouthandler classcomblablablalogouthandler property namelogouturl valueauthlogouthtmlbeanthe logout handler is called when user clicks logout which will make some calls to a database but how do i handle the session timeout one way to handle it would be to inject the username into the session when user logs in and then use an ordinary httpsessionlistener and do the same thing on session timeout is there a similar way with spring security so that when spring thiscovers that the session is to timeout i can hook in there access the authentication and get the userdetails from there and do the clean up,['java'] +329055,back button fails after windowlocationreplacehref i made simple function which makes all container behave like link a element function allhotelementelementclick function var href thisfindaattrhref windowlocationreplacehrefhover function thiscsstextshadow 0px 1px 0px d6d6d6 function thiscsstextshadow none function works great instead of clicking the more button user can click everywhere on container and is properly redirectedhowever if user after redirection clicks back button browser goes back two steps instead of one as it should whats more weird history looks oksimple scheme to better descriptionpage1 page2page2 user clicks on allhot container allhot redirects to page3page3 user clicks on browser back button page1this is major bug for website i am working on right now i do not really have a clue to prevent it bug tested on firefox chrome and opera tested also on opera no javascript mode if javascript is thisabled issue does not occurethanks in advance for any clue or solution,"['javascript', 'jquery']" +329086,rails devise authentication csrf issue i am doing a singepage application using rails when signing in and out devise controllers are invoked using ajax the problem i am getting is that when i 1 sign in 2 sign out then signing in again does not work i think it is related to csrf token which gets reset when i sign out though it should not afaik and since it is single page the old csrf token is being sent in xhr request thus resetting the sessionto be more concrete this is the workflowsign in sign outsign in successful 201 however prints warning cannot verify csrf token authenticity in server logssubsequent ajax request fails 401 unauthorisedrefresh the website at this point csrf in the page header changes to something elsei can sign in it works until i try to sign out and in againany clues very much appreciated let me know if i can add any more details,['ruby-on-rails'] +329090,mysql sorting by 3 columns or union them i have a problem understandint order by in mysql i have to sort a table by 3 criteria1 first i want to sort by type of work so all data must be alphabetical likedech rap busdech rap busger dem dech busger dem dech busger dem stp ppresult 2b2a85862 second i want to sort by project version so all data must be alphabetical but respecting the 1 criteria likedech rap bus v123v1234dech rap bus v300ger dem dech bus v123v1234 ger dem dech bus v300ger dem stp pp v123v1234 result 2b2a8587so 1 and 2 are working perfectly3 and after this i want to sort by the column not existingresult 2b2a8585and i do not know what it really do but i see no results i just want that thedech rap bus v300where the not existing column is 1 to be at the end and when are more of not existing 1 to sort them all but at the end of the tablei tought to myself that a union of 2 selects would help me selecting all data where not existing is not 1 or null working good select from atm mti view where project functionfrs01 and on big project id 12 and not existing 1 or not existing is null order by type of work asc project version ascunion selecting all data where not existing is 1 working good select from atm mti view where project functionfrs01 and on big project id 12 and not existing 1 order by type of work asc project version ascbut what this piece of code does is putting the not existing dech rap bus at the end good but it messes up the version sorting whysee result here 2b2a8588why is that i just want to merge two select results what i am doing wrongthank you,"['mysql', 'sql']" +329131,animate the clip rect property i want to animate the css property clip rect with jquerys animate but cannot find if this is possible anywhere have tried img1animate clip rect1px 945px 499px 1px 300without any luck does anyone know thanks,"['jquery', 'html', 'css']" +329159,php encrypt other sites username and password i am programming a php site that allows users to register and both registered and unregistered users can enter their respective usernames and passwords for example smith8h4ft j9hsbnuio for school site then my php script sends some post variables downloads and parses the marks page making an array called marksdb arraysubject arraya b a c and writes it reformattedmy question ishow should i keep the username and passwords safefor unregistered users i currently forget username and password and put the marksdb into session when user is inactive for eg 30 minutes marksdb is deleted how safe are these data in session and how about users that log in view page once and never view it again so the script does not delete the marksdb from session is the session deleted automatically gcmaxlifetimeand what about registered users i want to have everything safe but i do not want to annoy user with password prompts every 30 minutes of inactivity is it safe to encrypt credentials like described here but without the third userset password or have i to ask the user for his password every timeeditthanks for quick repliesjustin a i doubt they have some api but i can ask them just for caseabid hussain thanks for very useful links thanks both for answers tooi will throw users credentials away and have only parsed markdb which i will probably throw away too after logout or inactivity it is cheap to retrieve marks again when needed,['php'] +329166,how include static files to setuptools python package it is impossible to include static files i tried everything that i have found in tutorials and the documentation but all in vaini want to include the staticdatatxt there is my code setuppyimport osglobfrom setuptools import setupfind packagessetup name potatoproject version 011 author master splinter author email description the potatoproject url license bsd adding packages packagesfind packagessrc package dir src trying to add files include package data true package data txt statictxt static txt scriptssrcstartpotato classifiers development status 3 alpha topic utilities license osi approved bsd license the file systema setuppya src a thistutils setuppy a potato aa a a init py aa a a potatodatatxt aa a a printerpy a startpotato a static aa a a datatxt a tomato a bigpy a init pythe output when running python setuppy sthistrunning sthistrunning egg infocreating srcpotatoprojectegginfowriting srcpotatoprojectegginfopkginfowriting toplevel names to srcpotatoprojectegginfotop leveltxtwriting dependency links to srcpotatoprojectegginfodependency linkstxtwriting manifest file srcpotatoprojectegginfosourcestxtreading manifest file srcpotatoprojectegginfosourcestxtwriting manifest file srcpotatoprojectegginfosourcestxtwarning sthist standard file not found should have one of readme readmetxtcreating potatoproject011creating potatoproject011srccreating potatoproject011srcpotatocreating potatoproject011srcpotatoprojectegginfocreating potatoproject011srctomatomaking hard links in potatoproject011hard linking setuppy potatoproject011hard linking srcstartpotato potatoproject011srchard linking srcpotato init py potatoproject011srcpotatohard linking srcpotatoprinterpy potatoproject011srcpotatohard linking srcpotatoprojectegginfopkginfo potatoproject011srcpotatoprojectegginfohard linking srcpotatoprojectegginfosourcestxt potatoproject011srcpotatoprojectegginfohard linking srcpotatoprojectegginfodependency linkstxt potatoproject011srcpotatoprojectegginfohard linking srcpotatoprojectegginfotop leveltxt potatoproject011srcpotatoprojectegginfohard linking srctomato init py potatoproject011srctomatohard linking srctomatobigpy potatoproject011srctomatowriting potatoproject011setupcfgcreating thistcreating tar archiveremoving potatoproject011 and everything under itand no txt added no staticdatatxt nor potatopotatodatatxtwhat am i missingthanks,['python'] +329190,how to run python script with one icon click sorry for the vague question do not know actually how to ask this nor the rightful terminologies for ithow to run a python scriptbytecodepyc any compiled python code without going through the terminal basically on nautilus on double click of the python script it will run or on select then enter it will run that is my goal at leastwhen i check the allow executing of file as a program then press enter on the file it gives me this messagecould not thisplay homeghelomusicarrangepyc there is no application installed for python bytecode files do you want to search for an application to open this fileusing ubuntu 1204 by the way and has to be python 2 one of the packages does not work on python 3 if there is a difference between how to do it on the two version include it if it is not to much t ask thank youi know it does not matter but it is a script auto renaming arranging my music files guide me accordingly stupid idiot here,['python'] +329230,if statements for checkboxes i wanted to know how to write if statements to see if one or another check box is checked or noti have two check boxes i wanted it to check to see if checkbox 1 is checked and checkbox 2 is null then call this function and if checkbox 2 is checked and checkbox 1 is null then call another function pretty bad with if statements and not sure how to convert the checkbox into a readable value,['c#'] +329245,how to download image from http only if the image is newer i would like to implement the following functionalitya c client connects to an http server and downloads an image to thiskthe next time the client starts checks if the image on the server is newer than the image on thisk and in this case the client overrides the image on thiskfor me it is easy to download the image but i am not sure how to check if the image on the server is newer how could i implement it i guess that i could check the timestamp or the image size or both but i do not know how to do itany help would be appreciated,"['c#', '.net']" +329249,where are chrometampermonkey userscripts stored on the filesystem where are chrometampermonkey userscripts stored on the filesystemi want to edit user scripts directly instead of using the hokey inbrowser editor,['javascript'] +329262,javascript blob object to base64 i am trying to implement a paste handler to get an image from users clipboard i want this to run only on google chrome i am not worried with other browsersthis is a part of a method that i found on internet and i am trying to adapt it get the items from the clipboardvar items eclipboarddataitems if items loop through all items looking for any kind of image for var i 0 i itemslength i if itemsitypeindexofimage 1 we need to represent the image as a file var blob itemsigetasfile and use a url or webkiturl whichever is available to the browser to create a temporary url to the object var urlobj windowurl windowwebkiturl var source urlobjcreateobjecturlblob createimagesource the method works and i can show the image if i use my source as the src of a image object the problem is that the image source in google chrome will be something like this blobhttplocalhost8080d1328e65ade245b3a814107cc2842ef9i need to send this image to the server so i want to convert it to a base64 version for example dataimagepngbase64ivborw0kggoansuheugargajcaiadwno7rakmwldq1bjq0mguhjvzmlszqaasimdlnduu9kwh89n71qkhcklnbraficsa29sjeukjejeerakaainkrucerrkayimijggkndkbeiioububhrbble1hfwfbuwswstgd8eenm98f935rn73p3wfvfda6ajd8gwxctfgjgayhwbth58wijytnyacbdpa2wa4hczs0iweycmqj82ixsmrp4f726did5yrtp4zbapflzijeaujim5l42vwzf8k4pvecjbdpyzi2ne3omeroilmcmlatcisw3z2mwupofmyhdwzy3po4mxw5nwn4405er6mkwazfcilkyvizjg3rjhkdgbsxgxxongaoktwu5nntzgwty5iomoit43ka4ejjxdsl1jmzxpld8xozfoueisnibkmxfogjzmtihpz03ni8xmicibwnhp9w9c9emzvhcl1ioelk09ruc2wqghfhukev30fljkmrzjklydfuwfdwhyfckcbbggqjeusgwc4fcrikcbbggqzlmcgecrikcbbggqzlmcgecrikcbbggqzfmzhwoxxwoygqyiecrikyhuk5vf4rrumqyiecriksjdrfhlktyocbacksjeiqipnklt37wmgt5thlstwosjeiq7zxyseuhyjwxbdu2u1plesrikcbbvl6csx6cbacksjeiqimpy3dkmosg3t7a5kkiqieg8wqdhsbxtjbqcbiksjdvpmguhybbggqjeitisfwxlqr9h6bojtyep2monboj2hut9y6xnljsbcqnxkgg3brh8q4lqbopampdqugshex9lpdlfb4su5i97b8kuevygyugysaksapg9fkbdqne1knvvw76nfyeitcg6sjld5fv58rsfmxrcbiksjdvpp8fhtxbdvrpi8asuvork5cyin the first piece of code i have a blob object representing the file how i can use it to create a base64 representation i have tried a couple of methods but i am not getting the correct representation please anyone can help me,['javascript'] +329265,a qwidget like qtextedit that wraps its height automatically to its contents i am creating a form with some qtextedit widgetsthe default height of the qtextedit exceeds a single line of text and as the contents height exceeds the qtextedit is height it creates a scrollbar to scroll the contenti would like to override this behaviour to create a qtextedit that would rather wrap its height to its contents this means that the default height would be one line and that on wrapping or entering a new line the qtextedit would increase its height automatically whenever the contents height exceeds the qtextedit is height the latter should not create a scroll bar but simply increase in heighthow can i go about doing this thanks,['python'] +329268,entity framework code first virtual property column naming i am using ef code first 431 on a personal aspnet mvc 3 project with a very simple domain model and i am almost at the point where ef will generate the db schema the way i want it tothe domain model has two classes painting and gallery each painting belongs to a single gallery and the gallery has two virtual properties pointing to painting one to indicate which of the painting is it is cover image and one for which of the paintings is the slider image thisplayed on the home pagethe classes are as follow i have removed some annotations and irrelevant properties to make it readablepublic class gallery public gallery paintings new listpainting scaffoldcolumnfalse key public int galleryid get set public string name get set scaffoldcolumnfalse columnlacover public painting cover get set scaffoldcolumnfalse columnelslider public painting slider get set scaffoldcolumnfalse public virtual listpainting paintings get set and paintingpublic class painting scaffoldcolumnfalse key public int paintingid get set public string name get set public int galleryid get set columngalleryid foreignkeygalleryid inversepropertypaintings public virtual gallery gallery get set public string filename get set it generates a correct db schema for both classes and its relationships the only small issue i have is that i have not found a way to control the column names it gives to the virtual properties of cover and slider in the gallery tableit will name them cover paintingid and slider paintingidi tried using the columncolumnnamehere attribute but that does not affect it at all as in i typed a certain non related word and it didnt show up in the schemai would like to name it coverpaintingid without the underscoreany help is greatly appreciated thanks,"['c#', '.net']" +329282,c operator not for string literals what does the in this mean i know it is using an obsolete net framework 11 configurationsettingsappsettingsconfigurationsettingsappsettingssome settingthis is not a string literal using the literal with a string variablethe actual code scale id regex configurationsettingsappsettingsscaleidregexin a regular cs file which is part of a windows service and scale id regex is just a private string in the class so aspnet and razor are not involved,['c#'] +329289,spline interpolation with python i wrote the following code to perform a spline interpolationimport numpy as npimport scipy as spx1 1 088 067 050 035 027 018 011 008 004 004 002y1 0 1399 2799 4198 5598 6997 8397 9797 196 12596 13995 15395x nparrayx1y nparrayy1new length 25new x nplinspacexmin xmax new lengthnew y spinterpolateinterp1dx y kindcubicnew xbut i am gettingvalueerror a value in x new is below the interpolation rangein interpolatepyany help would be appreciated,['python'] +329309,override woocommerce frontend javascript can someone guide me as to what is the proper method of overriding woocommerce core javascript files specifically frontend files i have not found any documentation on this and looking at the code the path to the frontend script files is hard coded in the plugin so i doubt that placing an assets folder in my theme will do anything what is the cleanest way to to this so that i can load a file located in my theme dirthanks,['javascript'] +329317,how to best map results from an sql query to a nonentity java object using hibernate i have a hibernate managed java entity called x and a native sql function myfunc that i call from a hibernate sql query along these linessqlquery q hibernatesessioncreatesqlquery select myfuncparam as result from x table name what i want to do is to map the everything returned from this query to a class not necessarily managed by hibernate called y y should contain all propertiesfields from x plus the result returned by myfunc eg y could extend class x and add a result fieldwhat i have triedi have tried using qaddentityyclass but this fails withorghibernatemappingexception unknown entity commycompanyyqsetresulttransformertransformersaliastobeanyclass but this fails with orghibernatepropertynotfoundexception could not find setter for some property x has a field called someproperty with the appropriate getter and setter but in this case it does not seem like hibernate maps the column name some property to the correct field nameqsetresulttransformercriteriaalias to entity map returns a map but the values are not always of the type expected by the corresponding field in x for example fields in x of type enum and date cannot be mapped directly from the map returned by the sql query where they are stringswhats the appropriate way to deal with this situation,['java'] +329318,cannot use getdeclaredfields to retrieve fields of a scala class i am trying to use a java library johm with scala and noticed it fails when the lib tries to read the fields of my scala classes with something like modelgetclassgetdeclaredfieldsthen i decided to try to do the same with simple examples in the scala interpreterscala import javalangreflectfieldimport javalangreflectfieldscala class myclassattribute1 string attribute2 string attribute3 stringdefined class myclascala val myinstance new myclassvalue1 value2 value3myinstance myclass myclass7055c39ascala myinstancegetclassgetdeclaredfieldsres0 arrayjavalangreflectfield arrayindeed we get no field at allnow what if i try thisscala class myclass2attribute1 string attribute2 string attribute3 string override def tostring thisattribute1 defined class myclass2scala val myinstance2 new myclass2value1 value2 value3myinstance2 myclass2 value1scala myinstance2getclassgetdeclaredfieldsres1 arrayjavalangreflectfield arrayprivate final javalangstring myclass2attribute1so if use one of the fields in one of the class methods it is found by getdeclaredfields what am i missing here,['java'] +329334,c object instantiation vs assignment what is the difference between thistestclass tand thistestclass t testclassi expected that the second might call the constructor twice and then operator but instead it calls the constructor exactly once just like the first,['c++'] +329353,what does unexpected precompiled header error mean i was trying to build a simple solution involving a windows and a console application after using the wizard to generate the code skeleton for the projects i did not add any code and just built the generated code in both cases i got the same error1ccwinprwinprwinprcpp4 fatal error c1859 debugwinprpch unexpected precompiled header error simply rerunning the compiler might fix this problemwhat is wrong any thoughts,['c++'] +329374,pytest logging control we have recently switched to pytest for python testing which is fantastic btw however i am trying to figure out how to control the log output ie the builtin python logging module we have pytestcapturelog installed and this works as expected and when we want to see logs we can pass nologcapture optionhowever how do you control the logging level eg info debug etc and also filter the logging if youre only interested in a specific module is there existing plugins for pytest to achieve this or do we need to roll our ownthanksjonny,['python'] +329406,css to center a image horizontally i am trying to center a image horizontally using cssi am thisplaying my image on the screen with the following html codediv idloading classloadinginvisible img classloading srclogopngdivi am croping my image as i only want to thisplay some of the image and i am using the following cssimgloading positionabsolutecliprect0px681px75px180pxhowever i cannot work out how to center the image once it has been cropedanyone able to help,"['html', 'css']" +329441,functionality of void operator i am confused about the functionality of void operatorcould you tell me about that for instanceclass background taskpublic void operator const do something do something else background task fstdthread my threadfhere why we need operator what is the meaning of the first and second actually i know the operation of normal operator but this operator is confusing,['c++'] +329449,how do i render jinja2 output to a file in python instead of a browser i have a jinja2 template html file that i want to render replace the tokens with values from my py file instead of sending the rendered result to a browser however i want to write it to a new html file i would imagine the solution would also be similar for a django templatehow can i do this,['python'] +329481,find the largest possible difference in an array with the smaller integer occuring earlier this is an interview question find the largest possible difference in an array of integers such that the smaller integer occurs earlier in the arrayconstraintnumbers are not uniquethe range is integer range of java or any other languageexampleinput 1 1 100 2 105 10 30 100the largest difference is between 10 and 100 110 here 10 is at the 5th index and 100 is at 7th indexinput 2 1 100 2 105 10 30 80the largest difference is between 1 and 105 104 here 1 is at the 1st index and 105 is at 4th indexpossible solutionone approach is check for all possible differences and keep a track of the biggest difference found till now on2 complexitycan this be done in better than on2 time,['java'] +329491,replacing iis rewrite rules in webconfig transform i have some iis rewrite rules that i want to vary by environment the development rewrite rules are in the webconfig file then at the end of the webtestconfig file i have appsettings some app settings tranforms here appsettings systemwebserver rewrite xdttransformreplace rules rules here rules rewrite systemwebserver configurationmy app settings are getting transformed when i deploy to test but by iis rewrite rules are not i was hoping the entire rewrite section would simply be replaced with the one in the transform file as per but nothing is changingi have tried putting xdttransformreplace xdtlocatormatchname on the individual rules toorule nametest rule stopprocessingtrue xdttransformreplace xdtlocatormatchnamebut again this makes no differenceis it even possible to replace rewrite rules in the webconfig and if so what am i missing,['asp.net'] +329510,why does jquery cssleft and positionleft return different values the values i am getting for elcssleft and elpositionleft are different if i go elcssleft 100px then elcssleft it returns 110px instead of 100px yes it is always 10 more and if i evaluate elpositionleft it gives me 100 why does chrome behave this way you can see how this would affect jquery animations using the left propertyi am using chrome 210118057 on ubuntu edit 1 seems to be only affecting chrome ff 1401 is giving me the same values,['jquery'] +329527,grouping overloads in doxygen in my library i have a lot of function overloads of the form brief does thing details the thing that is done is very specialtemplatetypename tvoid do stuffconst t t brief does thing repeatedly copydetails do stufftemplatetypename tvoid do stuffconst t t stdsize t xthis in general works and is quite nice but creates the samedocumentation section multiple times what i want is to group thosefunctions together have on detail description and each of theoverloads annotated with it is brief description i am also not averseto aliases that could do something like this or input filtersone way i could imagine this would bethe documentation result should look like thistemplatetypename tvoid do stuffconst t t 1templatetypename tvoid do stuffconst t t stdsize t x 2the things that is done is very special1 does thing2 does thing repeatedlyof course i can create a new page and write that kind of documentationby hand but it would require me to repeat the function declarationsonto the page and then punch links into the actual functiondocumentation but that is more a hack than anything elseis there a way to achieve this easily even hints to hack it intodoxygen would be appreciated,['c++'] +329536,byte array to nsdata in a webservice json response is coming in the response there is image is coming as a byte array i have to show the image in a uiimageview i am trying to convert the byte array to nsdata but not getting how to do that any help would be appreciatedi am confident that the byte array has image data in itsample byte array for your reference 137 80 78 71 66 96 130thanks,"['iphone', 'ios', 'objective-c']" +329541,how can i make a future of future into one future object env akka 21 scala version 210m6 jdk 17u5now is my problem i have future1 futuresfuturenew callablefutureobjectfuture2 extends objectfuturesequencefuture1 future2oncompletenow in first line i have a future of future of object is there any way to convert it into a future while not blocking my current threadis there any method in akka as far as i checked i havnt found any yetfirst time to have a postsry for bad format and organize p,['java'] +329544,repeat pdfptable header in all the continuation pages using itext how can i repeat the headings of a pdfptable in all the pages if the length of the table exceeds one page,['java'] +329576,absolute positioning and its parent element i have always heard that when you use absolute positioning that the element you want to act as its parent needs to have a position of relativei was trying to build a css dropdown menu and i was struggling to get the dropdown menu items stretch beyond the width of the main menu item when i had its parent element i wanted it to use set as relative the text in the drop down menu items would just wrapso i looked around at other example menus to see how they did it and one i found was not even using any parent elements with a position of relative even though they were using absolute positioning like i wasthat example is here so i tried removing my relative positioning and bingo my problem went away however now i am using absolute positioning with none of it is parents using relative positioning they are all set to staticso i am wondering how that makes sense with no relative parents wouldnt it fall back to the browser windowif need be here is my html div classnavwrapper div classleftdiv div classnav ul li classhomea hrefhomeali li claspacerli li classabouta hrefabout usabout usali li claspacerli li classtrademarka hreffreetrademarksearchfree trademark searchali li claspacerli li claservices a hrefservicesservicesa ul clasub lia hreftrademark searchali lia hrefprepare amp file trademarkali lia hreftrademark infringementali ul li li claspacerli li classtestimonialsa hreftestimonialstestimonialsali li claspacerli li classmorea hrefjavascriptvoid0more informationali li claspacerli li classcontacta hrefcontactuscontact usali ul div classcontentcleardiv div nav ends div classrightdiv div nav wrapper ends cssheader navwrapper width 1004pxheader navwrapper left float left width 4px minwidth 4px height 47px minheight 47px background urlimagesnavleftbgpng left top norepeatheader navwrapper nav float left width 994px bordertop 1px solid e0d0b4 borderleft 1px solid e0d0b4 borderright 1px solid e0d0b4 borderbottom 1px solid e8dcc8 background urlimagesnavbuttonbgpng left top repeatxheader navwrapper nav ul margin 0 1px thisplay blockheader navwrapper nav li float left thisplay block height 45px fontfamily opensansbold arial fontsize 16px lineheight 29 textalign center color 646464header navwrapper nav lispacer width 2px minwidth 2px height 45px minheight 45px background urlimagesnavbuttonspacerbgpng left top norepeatheader navwrapper nav li aheader navwrapper nav li avisited thisplay block height 45px padding 0 20px color 646464 textdecoration noneheader navwrapper nav li ahoverheader navwrapper nav li aactiveheader navwrapper nav li afocus color f background urlimagesnavbuttonbgpng left bottom repeatxheader navwrapper nav lihome maxwidth 86px textindent 1pxheader navwrapper nav li ulsub position absoluteheader navwrapper nav li ulsub li float none thisplay block fontfamily opensanssemibold arial fontsize 14px lineheight 23 height auto textalign center backgroundcolor f4771d color fheader navwrapper nav li ulsub li aheader navwrapper nav li ulsub li a color f height autoheader navwrapper nav li ulsub li ahoverheader navwrapper nav li ulsub li afocusheader navwrapper nav li ulsub li aactive background d627header navwrapper right float right width 4px minwidth 4px height 47px minheight 47px background urlimagesnavrightbgpng left top norepeat,['css'] +329592,c how to execute a http request using sockets i am trying to make a http request using sockets my code is as followsusing systemusing systemnetusing systemnetsocketsusing systemtextclass test public static void mainstring args string hostname 127001 int hostport 9887 int response 0 ipaddress host ipaddressparsehostname ipendpoint hostep new ipendpointhost hostport socket sock new socketaddressfamilyinternetwork sockettypestream protocoltypetcp sockconnecthostep string request url titlemy20test20app response socksendencodingutf8getbytesrequest url response socksendencodingutf8getbytesrn bytes sockreceivebytesreceived bytesreceivedlength 0 page page encodingasciigetstringbytesreceived 0 bytes consolewritelinepage sockclose now when i execute the above code nothing happens whereas when i enter my request url in browser i get a notification from snarl saying that application registered and the response i get from browser is snp200ok556the response i get from my code is snp30107badpacketso what is wrong with my codesnarl request format specification,['c#'] +329608,is there a way to find the event handlers of an element with javascript say you have this divdiv idfoobardivand you do thisfooclicksomefunctionsomewhere inside your javascript codeonce the page has been loaded is there a way to find out via firebug or inspect element in chrome or anything else that the click event for foo is bound to somefunction ie find this out without having to look through all your code,"['javascript', 'jquery']" +329620,why code in static block does not execute here i did a program when i prints the constant in main static block does not executesbut when i print stat which executes is there any importance to static final in javaplease explainpackage comtestdoubtclass doubt public static final int constant 123 public static int stat 123 static systemoutprintlnstatic block public class myprogram public static void mainstring args systemoutprintlndoubtconstant,['java'] +329676,imagemagick brew installation with php module in mac os x i have installed imagemagick using brew install imagemagick this all worked fine and i can run any imagemagick command from the terminal command linenow when i try to use the imagemagick classes in php i get an error class imagick not found in i guess this is because the imagemagick module is not loadedcould anyone help me to get this thing working in php thanksadditional infomac os x version 108 mountain lionphp version 5313,['php'] +329689,ie not resending cookies when printing i have an image rendered on the fly by a php page requestphp this image cannot be cached because of the nature of the data it contains the image that is rendered by requestphp depends on the users cookies when i go to print from both ie8 and ie9 these cookies are not being sent in the request headers when attempting to download the image returned by requestphp i determined this by using fiddler and monitoring requestresponse headersmy first idea was to just put the cookie information in the url of requestphp but there is a problem with this the cookies i set are created with the httponly flag set for security reasons in other words i cannot access this cookie from a script i do use jquery to set the source for the image using something like myimageattrsrc requestphpd dynamically set data string there is no way to append any cookie information to this jquery call because of the httponly flagi cannot use base64 to contain the image data directly in the src attribute because the images are too large ie8 has a 32kb limitis there a trick to force ie to send cookies in requests for uncached images made during printingprint preview,"['php', 'jquery']" +329715,check for missing default case in switch statement for resharper 61 there is no builtin inspection item for missing default statements within a switch for c however the custom patterns seem generally robust i have messed around with them a bit for cases like missing else statements for if blocks but i am not sure how to do a check for missing defaultheres what i have so farsearch patternswitchexpr case val statement break missingdefaultreplacement patternswitchexpr case val statement break default breakwhere expr is an expression val is an expression statement is any number of statements and missingdefault is a maximum of 0 statementsthe problems here are the followingwe can have any number of cases which are themselves a collection made up of one or more statements case break etc and any number of expressionsfor search pattern matching we should only match against occurrences where there is nothing after the last case ie no defaultwe need the break in the search pattern such that we can define nonexistence of statements thereafter this break is required by the compiler anywayobviously this search pattern only matches against occurrences containing a single case and no default so is relatively useless i need a pattern that will match against switches with any number of cases any number of which may or may not contain a break except the last case and can contain any number of statements and no defaultthanks for your help,['c#'] +329720,how to force a html5 form validation without submitting it via jquery i have this form in my app and i will submit it via ajax but i want to use html5 for clientside validation so i want to be able to force the form validation perhaps via jqueryi want to trigger the validation without submitting the form is it possible,['jquery'] +329723,how to remove empty strings from list then remove duplicate values from a list lets say i have a list of some column values coming from a table how do i remove empty strings and duplicate values please see the following codeliststring dtlist dtreportslistasenumerableselectdr drfieldstringcolumn1tolistthis is what i have coded just now but but amirams code is way more elegant so i will choose that answer here is how i did itdatatable dtreportslist someclassgetreportslist if dtreportslistrowscount 0 liststring dtlist dtreportslistasenumerableselectdr drfieldstringcolumn1tolist dtlistremoveallxx dtlist dtlistthistincttolist rcbomoduledatasource dtlist rcbomoduledatabind rcbomoduleitemsinsert0 new radcomboboxitemall all,['c#'] +329752,using curl as an alternative to fopen file resource for fgetcsv is it possible to make curl access a url and the result as a file resource like how fopen does itmy goalsparse a csv filepass it to fgetcsvmy obstruction fopen is thisabledmy chunk of codes in fopenurl fsl1d1t1necsvf fopenurl rprint rfgetcsvfthen i am trying this on curlcurl curl initcurl setoptcurl curlopt verbose truecurl setoptcurl curlopt returntransfer falsecurl setoptcurl curlopt post truecurl setoptcurl curlopt postfields paramcurl setoptcurl curlopt url urlcontent curl execcurlcurl closecurlbut as usual content already returns a stringnow is it possible for curl to return it as a file resource pointer just like fopen using php 51x something i mean not using str getcsv since it is only 53my errorwarning fgetcsv expects parameter 1 to be resource boolean giventhanks,['php'] +329768,is it better do to a union in sql or separate queries and then use php array merge i have a sql query that has 4 unions and 4 left joins it is layed out as suchselect from table1 left join other table1union select from table2 left join other table2union select other table3 left join other table3union select from table4 left join other table4would it be better to run 4 separate queries and then merge the results with php after the fact or should i keep them together which would provide that fastest execution,"['php', 'mysql']" +329789,coffeescript do pass argument the following coffeescript code do a consolelog agenerates thisfunctiona return consolelogaahow do i pass a value to a like thisfunctiona return consolelogahello,['javascript'] +329792,ios sdwebimage fade in new image i have been using sdwebimage on my iphone app to handle all of the image loading i am using a placeholder image and i want to crossfade or fade in the new image once it loads i am using a success block to set the image and it is working great no matter what i try the image will not fade in though i have tried sending the animation code back to the main thread but that did not help either it just loads instantly no animationhere is my code any thoughts load placeholder imagensurl url imageview uiimageview alloc init imageview setimageuiimage imagenamedloadingjpg request imagesdwebimagemanager manager sdwebimagemanager sharedmanagermanager downloadwithurlurl delegateself options0 successuiimage image uiview transitionwithview imageview duration30 optionsuiviewanimationoptiontransitioncrossthissolve animations imageview setimageimage completionnullfailurenil,['ios'] +329805,jira rest api login using c i have written below c code to login to jira rest apivar url new urihttplocalhost8090restauthlatestsessionos usernametempusernameos passwordtemppwdvar request webrequestcreateurl as httpwebrequestif null request return requestmethod postrequestcontenttype applicationjsonrequestcontentlength 200requestkeepalive falseusing var response requestgetresponse as httpwebresponsewhen i execute this application just goes on running without returning any response please suggest if this is the right way of calling jira login using rest api,['c#'] +329819,tfidf simple use nltkscikit learn okay so i am a little confused this should be a simple straightforward question however after calculating the tfidf matrix of the document against the entire corpus i get a result very similar to thisarray 085 0 052 1 0 0 1 0 0 1 0 0 055 083 0 063 0 077how do i use this result to get the most similar document against the search query basically i am trying to recreate a search bar for wikipedia based on a search query i want to return the most relevant articles from wikipedia in this scenario there are 6 articles rows and the search query contains 3 words columnsdo i add up all the results in the columns or add up all the rows is the greater value the most relevant or is the lowest value the most relevant,['python'] +329855,java time since the epoch in java how can i print out the time since the epoch given in seconds and nanoseconds in the following format javatextsimpledateformatymmdd hhmmsmy input islong mnsecondslong mnnanosecondswhere the total of the two is the elapsed time since the epoch 19700101 0,['java'] +329860,drag custom view onto window in interface builder i am coming from the world of c and winforms where i can build a custom usercontrol and drag it onto a form as if it were a common control is there a way to do that in xcode and interface builderi have only seen how to set the view at runtime but i would like to see it on my window at design time for example i would expect my custom view to be listed in the available controlsthankssimon,['objective-c'] +329866,how can i read input from the console using the scanner class in java how could i read input from the console using the scanner class something like thissystemoutprintlnenter your username scanner input or something like this i do not know the codebasically all i want to do is have the scanner read an input for the username and assign the input to a string variable,['java'] +329889,executorcompletionservice why do need one if we have invokeall if we use an executorcompletionservice we can submit a series of tasks as callables and get the result interacting with the completionservice as a queue but there is also the invokeall of executorservice that accepts a collection of tasks and we get a list of future to retrieve the results as far as i can tell there is no benefit in using one or over the other except that we avoid a for loop using an invokeall that we would have to submit the tasks to the completionservice and essentially they are the same idea with a slight difference so why are there 2 different ways to submit a series of tasks am i correct that performance wise they are equivalent is there a case that one is more suitable than the other i cannot think of one,['java'] +329891,how to pass django request object in user passes test decorator callable function i am using django user passes test decorator to check the user permissionuser passes testlambda u has add permissionu projectdef create projectrequesti am calling a callback function has add permission which takes two arguments user and a string i would like to pass the request object along with it is that possible also can anyone please tell me how are we able to access the user object inside the decorator directly,['python'] +329903,jpeg decompression inconsistent across windows architectures i am testing jpeg decompression on a bunch of computers with different versions of windows all of these computers have net 4 installed and i am compiling against net 2 and the any cpu platform target the following code produces different output on different systemsbitmap bmp bitmapimagefromfiletestjpglong datasum 0for int y 0 y bmpheight y for int x 0 x bmpwidth x datasum datasum bmpgetpixelx yr bmpgetpixelx yg bmpgetpixelx ybconsolewritelinedatasumall the win7 64bit and winxp 32bit machines produce one result and all the win7 32bit machines produce another resultany ideas why the output would be different,"['c#', '.net']" +329935,c global namespace access from within another namespace in the c code below foobar is defined first for a single double parameter and then again for a single parameter of type foo both are defined within the global namespacewithin the one namespace a further overload of foobar is defined with a single parameter of type bar from this version of foobar an unqualified call to foobar with a double argument 420 will fail a similar call to foobar this time qualified with the scope resolution operator also with a double argument will though succeedon the other hand an unqualified call to foobar with an argument of type foo succeeds a call to foobar with a foo argument qualified by the scope resolution operator also succeedswhy do the two scenarios behave differently i use both gcc 47 and clang 32struct foo struct bar double foobardouble x return x foo foobarfoo f return f namespace one bar foobarbar b foobar420 error cannot convert to bar foobar420 foo f foobarf no problem foobarf return b,['c++'] +329949,nsinvalidargumentexception receiver has no segue with identifier i have been trying everything for hours and nothings worked i am trying to segue between two view controllers from one tableviewcontroller to another tableviewcontroller the segue is hooked up to the top level view not the tableviewcell the identifier that was set in xcode is identical to the one used in the code copy and pasted it was working fine last night but now i cannot seem to get it to segue without crashinghere are the methods in which the segue is called voidtableviewuitableview tableview didselectrowatindexpathnsindexpath indexpath selfphotolist flickrfetcher photosinplaceselftopplaceslist objectatindexindexpathrow maxresults50 nslogphotolist selfphotolist nsloghere self performseguewithidentifiersegue1 senderself nslogherevoidprepareforsegueuistoryboardsegue segue senderidsender ifsegueidentifier isequaltostringsegue1 photostableviewcontroller photostvc seguedestinationviewcontroller photostvcphotolist selfphotolist here is the error report20120808 152839093 top places512f803 terminating app due to uncaught exception nsinvalidargumentexception reason receiver placestableviewcontroller 0x6887ff0 has no segue with identifier segue1 first throw call stack0x13c0052 0x1551d0a 0xde24b 0x3efd 0xa771d 0xa7952 0x92f86d 0x1394966 0x1394407 0x12f77c0 0x12f6db4 0x12f6ccb 0x12a9879 0x12a993e 0x17a9b 0x2778 0x26d5terminate called throwing an exception,['objective-c'] +329951,convert php variable 1100 am to mysql time format trying to convert standard time variable from form input to time format acceptable for mysql insert i might be going about it all wrong and could use some help i have read through the mysql time functions and php time functions but have not found a solution yetheres what i have tried as an examplephptime input 1100 amstrtotime strtotimetime inputmysql time datehmsstrtotimeecho ptime input time inputpecho pstrtotime strtotimepecho pmysql time mysql timepthe result is changing the time to 110800 not sure where the 8 minutes is coming fromtime input 1100 amstrtotime 134380mysql time 110800any help is much appreciated,"['php', 'mysql']" +329973,how to capture network packet in android without using any root permissions i want to capture network data packets on android app do you have any suggestions or source code to help me understand if this is possible,['android'] +329998,which data type is used to store datetime in oracle 10g which data type is used to store date time not only date but also time in oracle 10g database i have read some where that may be mistakenly the date data type in oracle 10g can store date time but the thing does not seem to happen when i try to do so the date datatype is a datetime datatype it stores a date and a time the date portion is based on the number of days since january 1 4712 bc the time portion is based on the number of seconds since midnight the linki tried it through java as a frontend and directly on the oracle terminal using the following sqlinsert into thiscount values7 code 125 to date11aug2012 060523 ddmony hhmiss to date20aug2012 075023 ddmony hhmissit works but in both the cases oracle simply ignores the time portion and inserts only the dates specified in the sql without any errorwhich data type is used to store date time in oracle 10g is it timestamp,['java'] +330000,how to overcome datetimedatetime not json serializable in python i have a basic dict as followssample sampletitle stringsamplesomedate somedatetimeherewhen i try to do jsonifysample i gettypeerror datetimedatetime2012 8 8 21 46 24 8620 is not json serializablewhat can i do such that my dictionary sample can overcome the error abovenote though it may not be relevant the dictionaries are generated from the retrieval of records out of mongodb where when i print out strsamplesomedate the output is 20120808 2146248620,['python'] +330001,checking exec runs successfully or not i have been trying to let know know if the exec command in php executes successfully or not so i can echo certain messages accordinglyi tried the following piece of code but the problem with it is that whether exec runs successfully or not it always echo pdf not created and never echo pdf created successfully kindly let me know how can i perform the check on the execution of exec so i can echo messages accordingly thanksphpif execcabcwkhtmltopdf homehtml samplepdfecho pdf created successfullyelseecho pdf not created,['php'] +330017,c fastest way to read only last line of text file i would like to read only the last line of a text file i am on unix can use boost all the methods i know require scanning through the entire file to get the last line which is not efficient at all is there an efficient way to get only the last linealso i need this to be robust enough that it works even if the text file in question is constantly being appended to by another process,['c++'] +330062,any symfony2 project tutorials for beginners i am new to symfony2 now i am working a symfony2 project so i need some sample tutorials for creating websites using symfony2 and xampp with mysql no need any hello world type tutorials,['php'] +330072,how to create a next button that switches tabs using java script and twitter bootstrap i have the following code i am using html to create a basic form this form has two sections each section is contained within a tab tabs created with twitter bootstraphow do i create a next button which switches from the first tab to the second tab when i try doing it right now it only submits the form does twitter bootstrap already provide a function that lets you switch tabs via an external button if so how do you use it,"['javascript', 'html']" +330077,serializing and deserializing lambdas i would like to serialize on machine a and deserialize on machine b a python lambda there are a couple of obvious problems with thatthe pickle module does not serialize or deserialize code it only serializes the names of classesmethodsfunctionssome of the answers i found with google suggest the use of the lowlevel marshal module to serialize the func code attribute of the lambda but they fail to describe how one could reconstruct a function object from the deserialized code objectmarhshallfunc code will not serialize the closure associated with the lambda which leads to the problem of detecting when a given lambda really needs a closure and warning the user that he is trying to serialize a lambda that uses a closurehence my questionshow would one reconstruct a function from the deserialized demarshaled code object how would one detect that a given lambda will not work properly without the associated closure,['python'] +330116,object getting wrong time stamp from hibernate saved to database i am new to hibernate and working on a web project that uses iti have an object called area that has a date objectjavasqltimestamp attribute modifieddate when i create a new object modifiedate is null and after send it down to gethibernatetemplatesaveorupdatearea in my own class that extends orgspringframeworkormhibernate3supporthibernatedaosupport it is set with current timestamp and saved in the database in the database it is saved as a datetimemy problem is most of the time the object is updated with a date that is 1 millisecond off compared to what it is saved as in the database this leads to this exception if anything is attempted updated without reloading the pagean orghibernatestaleobjectstateexception row was updated or deleted by another transaction or unsavedvalue mapping was incorrectthere are no problems with the correct date when getting the object from database subsequent it is only at creation it gets the wrong valueis there a way to get the correct modifieddate at saveorupdateincase it is needed the mapping uses timestamp namemodifieddate columnmodifieddate and all test are run on localhost with everything running on the same machinei already have a work around by calling gethibernatetemplaterefresharea right after the saveorupdate i get the right timestamp but i would still like to know if there is a way to get the correct modifieddate at saveorupdate,['java'] +330135,how to implement a bitmask in php i am not sure if bitmask is the correct term let me explainin php the error reporting function can be called multiple ways report simple running errorserror reportinge error e warning e parse reporting e notice can be good too to report uninitialized variables or catch variable name misspellings error reportinge error e warning e parse e notice report all errors except e notice this is the default value set in phpinierror reportinge all e noticei got the term bitmask from the phpnet page hereanyway the point of this is i have implemented a simple method called ls which returns the contents of a directorythis function takes 3 args include hidden false return absolute false ext false so when i call the function i set how i want the results whether i want the results to return hidden directories whether i want basenames only etcso when i call the function i am writing lstrue false truelsfalse false truelstrue true trueetci thought it would be much more readable if i could just flag how i want the data returnedso something likels include hidden hide exts ls show absolute paths hide exts etchow would i implement this in terms of testing which flags have been called,['php'] +330138,how to write inline if statement for print i need to print some stuff only when a boolean variable is set to true so after looking at this i tried with a simple example a 100 b true print a if b file stdin line 1 print a if b syntaxerror invalid syntax same thing if i write print a if btruewhat am i missing here,['python'] +330168,enumerations in c negative side effects of using a negative number in a c enumeration are there any negative side effects of using a negative numberi am modelling response codes and one of the codes in negative this compiles but i want to know if there are any negative side effects to thispublic enum responsecodes invalidserveruserpasswordcombo 1 etc,['c#'] +330178,upgrade avalondock from 13 to 20 i am trying to upgrade avalondock in a application from 13 to 20 but there exist little to no documentation on thisi look at the simple imported it by doing thisxmlnsavalondockhowever this did not workerror the tag dockingmanager does not exist in xml namespace line 41 position 10i also tried it the old wayxmlnsavalondockclrnamespaceavalondockassemblyavalondockneither did this workerror the tag resizingpanel does not exist in xml namespace clrnamespaceavalondockassemblyavalondock line 71 position 22if they have renamed the controls it would be useful to have a list of the controls now existing in 20i tried to compile the simple code as it was but without success,['c#'] +330193,how to avoid singletons when making an oop state machine design i am in the midst of trying to teach myself programming i started the same way that i am sure most people start making small messy apps and games that do simple things in notsosimple ways recently i have been trying to take the next step by writing a slightly more complex game that uses oop design to write better more modular codethe main issue i have been having is the design of my main statemanager fsm class to switch between intromenugameetc screen states i have looked high and low and i have only really seen two methods of designing themuse a switchcase statement an enum to switch between statesmake a singleton fsm class that handles pushingpopping states tofrom a vectornow my problem is the switch case statement is very repetitive and clunky and it kind of works against my goal of using this project to teach myself oopmy second and bigger problem is the singleton suggestionas i said before i am trying to teach myself and i still have a lot to learn when it comes to programming especially in the field of oop and design patterns and all that stuff i have run into an issue where for every single singletons are evil thread and thiscussion that i find i find just as many tutorials and references where people use singletons in their code to make engine classes and fsms it is a very consistent mixed messagei suppose i just do not understand why even if you only wantintend to have a single object of a class why is it necessarybeneficial to make the constructor private and create a singleton i have read a lot about how singletons are bad how they are essentially global how they get in the way of multithreading and how many programmers consider them overused or just plain bad design yet i see example after example of people using them and very few counter examples showing alternate methodscould not the same type of thing be done with just a regular class whats the purpose of explicitly restricting the creation of instances i have heard only negative things about singletons yet people seem to use them constantly am i completely missing something about singletons and oopis the use of singletons just a trend or is it just a trend when people call singletons evil how do i get around this is not there something between the switchcase fsm and the singleton fsm could not someone design their programs state system the exact same way without making any of their classes singletons would that change something confused,['c++'] +330245,wsimport two declarations cause a collision same line given trying to use wsimport to generate a client for a soap endpoint the wsdl and all xsd files used are local copiesthis is the command being executedwsimport bwwsdlxml p comgenerated xnocompile d src extension keep xadditionalheaders bxautonameresolutionwhich gives this errorerror two declarations cause a collision in the objectfactory class line 16 of fileschemasnewschemaxsderror related to above error this is the other declaration line 16 of fileschemasnewschemaxsdnote the line number is the same for the reported collisionheres the schemaxml version10 encodingutf8xsschema xmlnsxs elementformdefaultqualified version2004 idota2003a2009a xscomplextype nametpa extensionstype xsannotation xsdocumentation xmllangendescription here xsdocumentation xsannotation xssequence xsany processcontentsskip minoccurs0 maxoccursunbounded xssequence xscomplextype xselement nametpa extensions typetpa extensionstype xsannotation xsdocumentation xmllangenmore description herexsdocumentation xsannotation xselementxsschema i have tried removing the type definition but it is referenced in a slew of other placescould anyone please offer any advice for how to get this to work thanksedit heres the lines where the wsdl imports these schemasdefinitions namereslookupget targetnamespace xmlns xmlnshttp xmlnsmime xmlnsns xmlnsrq xmlnsrs xmlnssoap xmlnstns xmlnsxsd types xsdschema targetnamespace xmlnstns xmlnsxsd xsdimport namespace schemalocationschemasfooaffiliateheaderrqxsd xsdimport namespace schemalocationschemasfooreslookupgetrqxsd xsdimport namespace schemalocationschemasfooreslookupgetrsxsd xsdschema typesmessage namereslookupgetrq part elementrqfooreslookupgetrq namefooreslookupgetrqpart message message namereslookupgetrs part elementrsfooreslookupgetrs namefooreslookupgetrspart message,['java'] +330257,python csv unicode ascii codec cannot encode character uxf6 in position 1 ordinal not in range128 i have copied this script from python web site1 this is another question but now problem with encodingimport sqlite3import csvimport codecsimport cstringioimport sysclass utf8recoder iterator that reads an encoded stream and reencodes the input to utf8 def init self f encoding selfreader codecsgetreaderencodingf def iter self return self def nextself return selfreadernextencodeutf8class unicodereader a csv reader which will iterate over lines in the csv file f which is encoded in the given encoding def init self f dialectcsvexcel encodingutf8 kwds f utf8recoderf encoding selfreader csvreaderf dialectdialect kwds def nextself row selfreadernext return unicodes utf8 for s in row def iter self return selfclass unicodewriter a csv writer which will write rows to csv file f which is encoded in the given encoding def init self f dialectcsvexcel encodingutf8 kwds redirect output to a queue selfqueue cstringiostringio selfwriter csvwriterselfqueue dialectdialect kwds selfstream f selfencoder codecsgetincrementalencoderencoding def writerowself row selfwriterwriterowsencodeutf8 for s in row fetch utf8 output from the queue data selfqueuegetvalue data datadecodeutf8 and reencode it into the target encoding data selfencoderencodedata write to the target stream selfstreamwritedata empty queue selfqueuetruncate0 def writerowsself rows for row in rows selfwriterowrowthis time problem with encoding when i ran this it gave me this errortraceback most recent call last file makecsvpy line 87 in module uwwriterowd file makecsvpy line 54 in writerow selfwriterwriterowsencodeutf8 for s in rowattributeerror int object has no attribute encodethen i converted all integers to string but this time i got this errortraceback most recent call last file makecsvpy line 87 in module uwwriterowd file makecsvpy line 54 in writerow selfwriterwriterowstrsencodeutf8 for s in rowunicodeencodeerror ascii codec cannot encode character uxf6 in position 1 ordinal not in range128i have implemented above to deal with unicode characters but it gives me such error what is the problem and how to fix it,['python'] +330268,preference screen thisplay text block i am trying to make a preference screen that just has an about contact and legal option all of which when click just show text blurb and icon in a seperate page no shared preferences or anything i am having trouble understanding the heirarchy in order to thisplay the text i would like the flow to be settings about the about text currently i have this which gives me the categorey and option but i do not know what to make it in order to thisplay new textpreferencescreen xmlnsandroid preferencecategory androidtitleinfo preference androidtitleabout preferencecategorypreferencescreeni do not know what option to use to make the about clickable into a textview,['android'] +330276,segments within a executable c program i was reading about sections and segments seems you could list the mapping between sections and segments as below readelf l testelf file type is exec executable fileentry point 0x8048330there are 9 program headers starting at offset 52program headers type offset virtaddr physaddr filesiz memsiz flg align phdr 0x034 0x08048034 0x08048034 0x00120 0x00120 r e 0x4 interp 0x0154 0x08048154 0x08048154 0x013 0x013 r 0x1 requesting program interpreter libldlinuxso2 load 0x0 0x080480 0x080480 0x0065c 0x0065c r e 0x10 load 0x0f14 0x08049f14 0x08049f14 0x00104 0x00110 rw 0x10 dynamic 0x0f28 0x08049f28 0x08049f28 0x0c8 0x0c8 rw 0x4 note 0x0168 0x08048168 0x08048168 0x044 0x044 r 0x4 gnu eh frame 0x0564 0x08048564 0x08048564 0x034 0x034 r 0x4 gnu stack 0x0 0x0 0x0 0x0 0x0 rw 0x4 gnu relro 0x0f14 0x08049f14 0x08049f14 0x0ec 0x0ec r 0x1 section to segment mapping segment sections 00 01 interp 02 interp noteabitag notegnubuildid gnuhash dynsym dynstr gnuversion gnuversion r reldyn relplt init plt text fini rodata eh frame hdr eh frame 03 ctors dtors jcr dynamic got gotplt data bss 04 dynamic 05 noteabitag notegnubuildid 06 eh frame hdr 07 08 ctors dtors jcr dynamic gotmy questionsi could not understand what the program headers mean how are they related to segmentssection to segment mapping is clear but could someone name it i see only numbers i identified the code seg 03 data seg 02 and stack 07,['c'] +330290,how to get index in handlebars each helper i am using handlebars for templating in my project is there a way to get the index of the current iteration of an each helper in handlebarstbody each item tr tdhow to get array index heretd tdthiskeytd tdthisvaluetd tr eachtbody,['javascript'] +330294,how to shade points in scatter based on colormap in matplotlib i am trying to shade points in a scatter plot based on a set of values from 0 to 1 picked from one of the already defined color maps like blues or reds i tried thisimport matplotlibimport matplotlibpyplot as pltfrom numpy import from scipy import fig pltfiguremymap pltget cmapredsx 84808517662594909 11749082788323497 59075039082855652 36156231827873615 12536817102137768 11749082788323497 59075039082855652 36156231827873615 12536817102137768spaced colors linspace0 1 10print spaced colorspltscatterx x colorspaced colors cmapmymap this does not work eitherpltscatterx x colorspaced colors cmappltget cmapgraybut it does not work using either the reds or gray color map how can this be doneedit if i want to plot each point separately so it can have a separate legend how can i do it i triedfig pltfiguremymap pltget cmapredsdata nprandomrandom10 2colors listlinspace01 1 5 listlinspace01 1 5print colors colorspltsubplot1 2 1pltscatterdata 0 data 1 ccolors cmapmymappltsubplot1 2 2 attempt to plot first five points in five shades of red with a separate legend for each pointfor and in range5 pltscatterdatan 0 datan 1 ccolorsn cmapmymap labelpoint d npltlegendbut it fails i need to make a call to scatter for each point so that it can have a separate label but still want each point to have a different shade of the color map as its colorthanks,['python'] +330322,difference between eventoriginaleventdatatransferfiles and eventdatatransferfiles in html 5 what is the difference between eventoriginaleventdatatransferfilesandeventdatatransferfilesbecause in drag and drop second code does not work and it is undefined and i had to use first code because it works,['jquery'] +330338,vfy unable to find class referenced in signature i have a simple android application which uses a modbus library jamod on its build path it crashes immediately as i run it i have basically the same problem in this question getting caused by javalangverifyerrorbut i cannot really fix the problem my application was working fine before now no matter what i do it does not seem to work below is logcat output thanks in advance0809 143647753 wdalvikvm396 vfy unable to find class referenced in signature lnetwimpimodbusnettcpmasterconnection0809 143647823 wdalvikvm396 vfy unable to resolve exception class 510 lnetwimpimodbusmodbusioexception0809 143647823 wdalvikvm396 vfy unable to find exception handler at addr 0x180809 143647854 wdalvikvm396 vfy rejected lcomexamplexmlparsertestjavamodbustcpdriverinit ljavalangstringiv0809 143647854 wdalvikvm396 vfy rejecting opcode 0x0d at 0x00180809 143647854 wdalvikvm396 vfy rejected lcomexamplexmlparsertestjavamodbustcpdriverinit ljavalangstringiv0809 143647854 wdalvikvm396 verifier rejected class lcomexamplexmlparsertestjavamodbustcpdriver0809 143647854 dandroidruntime396 shutting down vm0809 143647854 wdalvikvm396 threadid1 thread exiting with uncaught exception group0x4001d80809 143647873 eandroidruntime396 fatal exception main0809 143647873 eandroidruntime396 javalangverifyerror comexamplexmlparsertestjavamodbustcpdriver0809 143647873 eandroidruntime396 at comexamplexmlparsertestmainactivityinitmainactivityjava130809 143647873 eandroidruntime396 at javalangclassnewinstanceimplnative method0809 143647873 eandroidruntime396 at javalangclassnewinstanceclassjava14290809 143647873 eandroidruntime396 at androidappinstrumentationnewactivityinstrumentationjava10210809 143647873 eandroidruntime396 at androidappactivitythreadperformlaunchactivityactivitythreadjava25770809 143647873 eandroidruntime396 at androidappactivitythreadhandlelaunchactivityactivitythreadjava26790809 143647873 eandroidruntime396 at androidappactivitythreadaccess2300activitythreadjava1250809 143647873 eandroidruntime396 at androidappactivitythreadhhandlemessageactivitythreadjava20330809 143647873 eandroidruntime396 at androidoshandlerthispatchmessagehandlerjava990809 143647873 eandroidruntime396 at androidoslooperlooplooperjava1230809 143647873 eandroidruntime396 at androidappactivitythreadmainactivitythreadjava46270809 143647873 eandroidruntime396 at javalangreflectmethodinvokenativenative method0809 143647873 eandroidruntime396 at javalangreflectmethodinvokemethodjava5210809 143647873 eandroidruntime396 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava8680809 143647873 eandroidruntime396 at comandroidinternaloszygoteinitmainzygoteinitjava6260809 143647873 eandroidruntime396 at dalviksystemnativestartmainnative method,['android'] +330341,use the xmlinclude or soapinclude attribute to specify types that are not known statically i have got a very strange problem when working with nets xmlserializer take the following example classespublic class order public paymentcollection payments get set everything else is serializable including other collections of nonabstract typespublic class paymentcollection collectionpaymentpublic abstract class payment abstract methodspublic class bankpayment payment method implementationsafaik there are three different methods to solve the invalidoperationexception that is caused by the serializer not knowing about the derived types of payment1 adding xmlinclude to the payment class definitionthis is not possible due to all classes being included as external references over which i have no control of2 passing the derived types types during creation of the xmlserializer instancedoes not work3 defining xmlattributeoverrides for the target property in order to override the propertys default serialization as explained in this so postalso does not work xmlattributeoverrides initialization followstype bankpayment typeofbankpaymentxmlattributes attributes new xmlattributesattributesxmlelementsaddnew xmlelementattributebankpaymentname bankpaymentxmlattributeoverrides overrides new xmlattributeoverridesoverridesaddtypeoforder payments attributesthe appropriate xmlserializer constructor would then be usednote by does not work i mean the invalidoperationexception bankpayment was not expected is throwncan anyone shed some light on the subject how would one go about and debug the issue further,"['c#', '.net']" +330349,why must exec and not eval be used for python import statements i am trying to run a snippet of python from within java using jython if i use an exec statement to import everything workspythoninterpreter pi new pythoninterpreterpiexecimport repythonobject o pievalrematchabc abc123 returns a matchobjecto pievalrematchabc def123 returns pynoneif however i try to combine the two lines all hell breaks loose thispythoninterpreter pi new pythoninterpreterpievalimport re exceptionpythonobject o pievalrematchabc abc123 never gets hereo pievalrematchabc def123 throws an exception no viable alternative at input import string10import renthis matters because ideally i would like to be able to eval a whole script as a single string without having to break the imports out into a separate part am i doing something wrong is there another way to tell jython take this whole blob of script including imports and run it then give me back a result this needs to be at runtime precompiling the python into class files is not an option,['python'] +330350,encoding video to support mulitple screens i am using ffmpeg to encode videos with h264avc codec and mpeg4 containerfrom now i have always been trying to make the same effort for videos than for drawables providing the proper resolution for each kind of devicesthat is why i used to add videos in rawmdpi rawhdpi rawxhdpi folders respectively with resolutions 240x320 480x800 720x1280i was thinking to be right until i thiscovered videos encoded in 480x800 located in my rawhdpi folder were unsupported on nexus s for this device i need to use 480x720reading supporthtmlrange i thought the solution was rather to use rawnormal rawlarge rawxlarge folders with minimum resolutions 320x470 480x640 720x960 but then i saw that most of my hdpi devices where using videos in the rawnormal folderso i think i am totally misunderstanding the proper way to do that is why i would really appreciate some explanations and most of all your practices with video encoding do you only provide videos with the minimum resolution to be certain to support all devices or the proper resolution for each kind of devicesthank you very much for your help,['android'] +330379,full screen dialogfragment i am trying to create a dialogfragment with a width of match parent so the dialog is nearly full screen leaving the padding around the edges for the floating look i have seen this solution full screen dialogfragment in android but am trying to avoid the hack of setting the width to 10dp with my current layout whether i use fill parent or match parent it seems to be setting the width and height to wrap contentlinearlayout xmlnsandroid androidlayout widthmatch parent androidlayout heightmatch parent androidorientationvertical i have used this solution for dialog not dialogfragment and it works as expectedgetwindowsetflagswindowmanagerlayoutparamsflag fullscreen windowmanagerlayoutparamsflag fullscreen,['android'] +330385,each vs for loop and performance these are mainly just some things i have been wondering maybe someone can give me a little more insight on them i will share what i have noticed so far as wellfirst thing i have been wondering is there any difference good or reason to useelementeachfunction i el versus eachelement function i el looking at the jquery docs i cannot see any rhyme or reason for one or the other maybe you know an instance or additional things one can do over the otherbut more importantly i am concerned with speed here as opposed to each looping through a jquery object 8x faster for var i 0 whateverlength i len i whateveri do stuffif you check out this jsfiddle demo here youll see the difference in speed is basically equivalent with either of them but more importantly i feel like i should always be using for loopsi was just unit testing looping through each of 5 different scenario functions 50 times simply looping through a bunch of list items and setting a datanewattr nothing specialquestion i guess my biggest question is why not always use for loops while iterating through an object is there even a point to using each do you always use for loops even when going through jquery objectsjsfiddle demo herefunction type execution time testareaeach this 1947 using this slows it down tremendouslyeach this 1940 testareaeach elplain js 458 using the element speeds things upeach elplain js 452for loop plainjs0 iteration 236 over 8x fasterjust my 2cents,"['javascript', 'jquery']" +330405,c port of atomiclonglazyset i am trying to port some java code to windows c and am confused about how to implement atomiclonglazyset the only information i can find talks about what it does but not how to implement it and the available source code ends up in a private native library owned by sun sunmiscunsafeclassi currently just set a member variable to the passed parameter but i am not sure if it is correctclass atomiclongpublic inline void lazyset int64 avalue todo is this correct ivalue avalue inline void set int64 avalue interlockedexchange64ivalue avalue private declspecalign64 volatile int64 ivaluei cannot use boostedit i am compiling to x64 but perhaps solutions for 32bit code would be of help to othersi do not have access to c11,"['java', 'c++']" +330428,get http status code in android webview i am developing an android app that loads a website in a webview but sometimes the website returns http code 500my question is is there any way to get the http status code from a webview with a listener or with another classi tried to implement an webviewclient but i could not get the http status code which webview received,['android'] +330456,alter keyboard appearance in native phonegapcordova built ios app i want to change the background color of all the keyboards appearing in my phonegapcordova built native ios app as shown belowi have googled this thoroughly of course and found mainly 2 relevant answers the answerer here says that objectivec code can be added to the phonegap projects appdelegatem file as shown on this page i have located the appdelegatem file but cannot seem to figure out how to set the keyboard appearance to that of uikeyboardappearancealert on all textfields code example provided by the answerer mytextfieldkeyboardappearance uikeyboardappearancealertwriting an app based on cordova i cannot thistinguish any textfield ids to connect to the above example is there a file in xcode cordova in which all the textfield ids are listed or even better is there a way in which i can set the keyboard appearance to dark through uikeyboardappearancealert or similar approaches that applies to all textfields and is compatible with cordovathanks,['ios'] +330488,minwidth maxwidth css use smallest width alright so what i am hoping to do is to create a div that will autosize based on the content that is in it but it should use the smallest width possible i have not a clue as to how to do this so if i have a div tag that has 3 characters which is no doubt under 200px wide what i want is for the div to be 200px then if there is a lot more text i would like it to auto size up so that the text will fit is this possible with just css update let me see if i can explain this better i have a divtext this longer textwhat i am hoping to have happen is if the text is changed it will still be at least 200px wide like thistextbut if it was even longer text then the first example it would continue to expand outward past 200px widetext this longer texttext this longer texthowever i do have a limit limited amount of space that it can go so i need to put a maximum width to it does that make sense or do i need to clarify things more,"['html', 'css']" +330531,symfony2 redirecting to last route and flash a message i am having a small problem when trying to flash a message and redirect the user back to the previous page in symfony 2 i have a very simple crud when new or edit i want to flash a message if something goes wrong in the respective createupdate methods souser get new post create fails redirect new flash messagei am doing the following thiscontainergetsessionsetflasherror myerror referer thisgetrequestheadersgetreferer return new redirectresponserefererhowever it is not redirecting to the correct referrer even though the value of referrer is correct eg httplocalhostdemo2edit it redirects to the index why,['php'] +330539,connecting to and uploading tracks with soundcloud api using c net i am trying to upload an audio track to the soundcloudcom using cnet but there are not any resources for net anywhere could someone post a link or an example of how to upload an audio file to my soundcloudcom account using netthank youarman,"['c#', '.net']" +330550,xcode 44 build app with arc for ios 42 xcode 44 mountain lion llvm 40 compiler i build my app it works on ios5 ios6 devices but on iphone 3g with ios 42 i have such errordyld lazy symbol binding failed symbol not found objc storestrongreferenced from varmobileapplications68b78a1971e64bdab997b7ded4d02429iguidesappiguidesexpected in usrliblibobjcadylibdyld symbol not found objc storestrongreferenced from varmobileapplications68b78a1971e64bdab997b7ded4d02429iguidesappiguidesexpected in usrliblibobjcadylibon xcode 43 everything was working because i use only strong and unsafe unretained modifiersi see that no arc libs were linked to my appi was trying to link manually with libarclite iphoneosa no reactioni added fobjarc to link flags no reactioni thought that iphone 3g support will be dropped in xcode 45 not 44 is it so,['ios'] +330604,general error 1005 cannot create table using laravel schema build and foreign keys essentially i am having the same issue as this guy minus the table prefix because i have no table prefix his fix does not work i am trying to build a table using laravels schema builder like thisschemacreatelessons functiontable tableincrementsid tablestringtitlenullable tablestringsummarynullable tabletimestampsschemacreatetutorials functiontable tableincrementsid tableintegerauthor tableintegerlesson tablestringtitlenullable tablestringsummarynullable tablestringtaglinenullable tabletextcontentnullable tabletextattachmentsnullable tabletimestampsschematabletutorials functiontable tableforeignauthorreferencesidonusers tableforeignlessonreferencesidonlessonsthe issue is when i run this code in a setup route i get the following errorsqlstatehy0 general error 1005 cannot create table tutorialssql2cff da errno 150sql alter table tutorials add constraint tutorials author foreign foreign key author references users idbindings array based on posts around the web and the limited documentation available on how to setup laravels eloquent relationships i am not sure what i am doing wrongusers already exists and it does have an id field that is auto increment i am also setting up my models with the proper relationships belongs to and has many but as far as i can tell this is not the issue it is the database setup the db is innodbwhat exactly am i doing wrong with the foreign key,['mysql'] +330653,does ndb have a list property instead of a single stringpropertyi want to store a list of stringsclass blogpostndbmodel s1 ndbstringpropertyrequiredtrue s2 ndbstringpropertyrequiredtrue s3 ndbstringpropertyrequiredtruei would rather goclass blogpostndbmodel my strings ndbstringlistproperty does this exist,['python'] +330673,any way to identify browser tab in javascript i need to be able to identify what tab i am in within the browser is not there some bit of information i can get from the browser to identify the tab i do not need to know anything about any other tabs i just need an id for the tab i am in it could be a random or sequenced number or a datetime stamp as long as it remains the same for the life of the tabi have a client side app that makes a bosh over http connection to a remote server and if i open it in multiple tabs each instance needs its own unique id or the app fails so i just need some unique number that is associated with the tab for as long as that tab exists ie something that survives page refresh as i navigate the site that provides this app seems like a nobrainer that should just be available in the browser like windowtabid that is all i need i have got a serious development block because i cannot get past this simple simple simple solution that does not seem to exist there must be a way a crossbrowser solution at thatany ideas,['javascript'] +330693,result of html5 canvas getimagedata or todataurl which takes up more memory part of my app includes html5 photo editing using a mixture of standard 2d context canvases and webglanyway i am saving undo states while the user is manipulating their photo these are all stored in a javascript object as base64 image dataeverything works fine and performance is goodhowever i am wondering if storing the data from getimagedata might take up less memory or offer better performanceso to summarise my question iswhich takes more space in memory a base64 jpeg generated by todataurl or the result of getimagedata and are there any performance differences between the two with regards to loading onto a canvas and pulling the data off of a canvasthanks in advance,['javascript'] +330699,custom allocator in stdvector is it possible to use custom allocator for stdvector internal allocations if yes how,['c++'] +330745,yield keyword for c how to return an iterator from my function consider the following codestdvectorresult data do processing pqxxresult input data get data from database return process datainput datastdvectorresult data process datapqxxresult const input data stdvectorresult data ret pqxxresultconst iterator row for row input databegin row inpupt dataend row somehow populate output vector return retwhile i was thinking about whether or not i could expect return value optimization rvo to happen i found this answer by jerry coffin emphasis mineat least imo it is usually a poor idea but not for efficiency reasons it is a poor idea because the function in question should usually be written as a generic algorithm that produces its output via an iterator almost any code that accepts or returns a container instead of operating on iterators should be considered suspectdo not get me wrong there are times it makes sense to pass around collectionlike objects eg strings but for the example cited i would consider passing or returning the vector a poor ideahaving some python background i like generators very much actually if it were python i would have written above function as a generator ie to avoid the necessity of processing the entire data before anything else could happen for example like thisdef process datainput data for item in input data somehow process items yield result dataif i correctly interpreted jerry coffins note this is what he suggested is not it if so how can i implement this in c,['c++'] +330778,bootstrap in a modal dialog how do i make the dropdown menu expand outside the dialog example codei would like to have the menu that drops down from the button expand over the modals borders as you see the current state is unusable is there some way to achieve this,['html'] +330788,is numberformatgetinstance guaranteed to create a new instance consider the following codenumberformat format numberformatgetinstanceformatsetminimumfractiondigitsspotdecimalplacesformatsetmaximumfractiondigitsspotdecimalplacesis it safe is numberformatgetinstance guaranteed to return a new numberformat object each timeor is there a possibility that getinstance returns the same instance in which case this code would affect everywhere else in the jvm that happens to use getinstancelooking at the source code it seems like it returns a new instance each time the javadoc is frustratingly vague on the matterif the above code really is safe then it seems to me that getinstance is a poor name for this method that it should have been called createinstance is numberformatgetinstance guaranteed to always return a new instance,['java'] +330794,javascript caret position i am developing a mobile banking application and i am interested in formatting the currency amount inputs in real timei have already tested autonumeric plugin and jquery format currency plugin but both have cursor position issues on android 2 browsersdoes anyone have a javascript solution compatible with this browsers,"['javascript', 'android', 'jquery']" +330799,oracle subtract millisecond from a datetime i thought it was really simple but it is notselect to timestamp10082012ddmmy 124506010 data from dualit simply does not workother detailsselect to timestamp10082012ddmmy numtodsinterval124506010hour data from dualdoes not workthe right seems to beselect to timestamp10082012ddmmy numtodsinterval124256010hour data from dualwhy how does it work,['sql'] +330849,why does my ios app no longer run in the ios 50 simulator in mountain lion i was forced to upgrade to mountain lion so that i could use keynotenow my ios app does not run under the simulator i was using iphonesimulator50sdk earlier now when i run the app it gives the errorthe simulated application quit click relaunch to try againthere is an option to switch sdk but there is only one sdk installed and nothing to switch towhat am i doing wrong,['ios'] +330860,binding member functions in a variadic fashion i have a member function with a variable number of parameters stored in a stdfunction and i want to bind the instance and get an independent function objecttemplate class t class r class argsvoid connectconst t t stdfunctionrconst t args f stdfunctionrargs bind the instance c into the function class cconnectc classfoofor a fixed number of arguments i would use stdbind but i do not see how to do this for variadic parameters,['c++'] +330863,rails passing a block to a helper method viget labs posted an article and gist detailing a rails helper method for adding a particular class like selected or active to a navigation link if it is url matches the current pathyou can use it in your layout like so nav link news articles path class btn btnsmall which creates the following html a hrefarticles classbtn btnsmall selectednewsanice i am using bootstrap and want to have an icon in my button so i need to generate the following htmla hrefarticles classbtn btnsmall selectedi classiconhome i newsai forked the gist and figured out a simple way of doing it my fork lets the developer pass inner html and inner class to the helper like so nav link news articles path class btn btnsmall inner html i inner class iconhomeit works fine but i do not like my underlying implementationdef link if optionsinner html link topath html options do content tagoptionsinner html class optionsinner class title end else link totitle path html options endendas you can see i am passing the new options to content tag inside the block of a link to method i was hoping i would be able to refactor it in a few ways first of all i would prefer to be able to do this in my view nav link news articles path class btn btnsmall do iiconhomei want to give the inner html as a block and not as attributes of the option hash can anyone give me any pointers on how to achieve thisi thought it would a simple case of telling the nav link method to accept a blockdef nav linktitle path html options options block linkgeneratornewrequest title path html options options blockto htmlendclass linkgenerator include actionviewhelpersurlhelper include actionviewcontext def initializerequest title path html options options block request request title title path path html options html options options options block block end def link if blockpresent link to path html options do blockcall title end end endbut this fails to output the icon and instead inserts a number 4 i do not get it clearly anyone got any advice where can i go to read more about this sort of thing as i really want to be able to figure stuff like this out without having to ask on stackoverflow,['ruby-on-rails'] +330925,how to get the module from which the currently executing function was called this is my best solution so far to the problem of accessing the calling module from within a functionimport inspectimport sysdef calling modulelevel0 filename inspectstacklevel21 modulename inspectgetmodulenamefilename try return sysmodulesmodulename except keyerror return sysmodules main but implicit in the handling of the keyerror is the largely unfounded assumption that it can happen only if filename is being run as main does the python standard library provide a more robust way to do this,['python'] +330931,php pass variable to include i am trying to pass a variable into an include file my host changed php version and now whatever solution i try does not worki think i have tried every option i could find i am sure it is the simplest thingthe variable needs to be set and evaluated from the calling first file it is actually serverphp self and needs to return the path of that file not the included secondphpoption onein the first fileglobal variablevariable appleincludesecondphpin the second fileecho variableoption twoin the first filefunction passvariable variable apple return variablepassvariableoption threevariable appleinclude myfilephpvarvariable and i tried with http and full site address toovariable getvarecho variablenone of these work for me php version is 5216what am i missingthanks,['php'] +330932,why does the jvm heap usage max as reported by jmx change over time my jvm heap max is configured at 8gb on the name node for one of my hadoop clusters when i monitor that jvm using jmx the reported maximum is constantly fluctuating as shown in the attached image i only see this behavior on one the most active of my hadoop clusters on the other clusters the reported maximum stays fixed at the configured value any ideas why the reported maximum would changeupdatethe java version is 160 20the heap max value is set in hadoopenvsh with the following lineexport hadoop namenode optsxmx8g dcomsunmanagementjmxremoteport8004 jmx shared propsps showshadoop 27605 1 99 jul30 11072313 usrlibjvmjrebinjava xmx10m xmx8gupdate 2added the xms8g switch to the startup command line last nightexport hadoop namenode optsxms8g xmx8g dcomsunmanagementjmxremoteport8004 jmx shared propsas shown in the image below the max value still varies although the pattern seems to have changedupdate 3heres a new graph that also shows nonheap max which stays constant,['java'] +330947,java superclone method and inheritance i have a quick question regarding the clone method in java used as superclone in regard to inheritance where i call the clone method in the parent class all the way up from the buttonthe clone method is supposed to return a copy of this object however if i have three classes in an inheritance heirachy and call superclone three times why does not the highest class in the inheritance heirachy just under class object get a copy of that class returnedsuppose we have three classes a b and c where a b c inherit then calling superclone in class c invokes clone in b which calls superclone invoke clone in a which call superclone this time objectclone gets called why is it not a copy of the this object with respect to class a that gets returned from objectclone that sounds logical to me,['java'] +331047,how would you order tiles on a dashboard this question may be a little longwinded and the images make it pretty large but stick with me i am tasked with creating a dashboard interface in our aspnet mvc 3 web application first i will list the features that are required for this project and then i will do my best to illustrate what i intend to create to accommodate all of these featuresrequired featuresthe dashboard will contain widgets or tiles that will be draggable within the dashboard interfacewhen dragging widgets the surrounding widgets will reorder themselves appropriatelywidgets are not resizable or collapsible but they will be removable the user will add widgets back through a menu if they desirethe widgets must accommodate variable width browser windows vertical space is pretty much unlimitedthe widgets heights and widths will be in increments of 300 pixels maxing out at 900 pixels in other words a widget could be 300 x 300 600 x 300 300 x 900 900 x 900 and so onwhat i plan to buildhere are a couple illustrations of what i hope to buildthe dimensions are not perfect but this shows a dashboard with 9 widgets on it all widgets are snug and do their best to fill the width of the screen elegantly however the widgets do not have to form a perfect square or rectangle danglers are ok as pictured belownote how the widths and heights of the widgets are all in increments of 300 pixels as noted in the requirements above this should hopefully make it easier to do the math for reordering the tiles which brings me to my problemmy questioni have the concept down but i am having trouble figuring out where to begin i am not as proficient with math as i wish i was and i need some help getting pointed in the right direction the people on so always seem to be amazing at this sort of problem solvinghow do i get from an array of widgets of all shapes and sizes that is sorted in no particular order into a neatly laid out absolutely positioned grid of tiles that takes up space as elegantly as possiblehow do i get from thisto thisor at least a similarly elegant layout the tiles do not have to be in their exact places as pictured above i just want them to play a perfect game of tetris and fall into place without awkward gapsi need to take the width of the browser window into account and then somehow loop through the array of widgets and start adding them to some sort of virtual grid i want it to look as elegant as i can make itthen after solving how i order the widgets on the page after the initial page load i need to allow the user to move hisher widgets around and have the other widgets reorder themselves as neatly as possible to accommodate the moved widgets new position i also need an elegant way to reorder widgets if the browser is resizedi know this is a tall order but any help is appreciated i am not expecting fullblown solutions or implementations i just need a push in the right direction i think perhaps a simple brain storm description of the logic for looping through the widgets and what things to calculate to arrive at the best configurationthanks for reading my extremely long question,"['javascript', 'jquery', 'asp.net', 'css']" +331079,exec string contains null byte argumenterror cmd snv co rep username svn user password pxs puts cmd this code wotks and prints all vars values normallyexeccmd xptorb69in exec string contains null byte argumenterror from xptorb69 ruby vruby 187 20100110 patchlevel 249 i686linux gem v137whats going on how can i solve this,['ruby'] +331119,python pil has no attribute image i am using python26 and got a problem this morning it said module has no attribute image here is my input why the first time i can not use pilimage import pil pilimagetraceback most recent call last file stdin line 1 in moduleattributeerror module object has no attribute image from pil import image imagemodule pilimage from usrlibpython26thistpackagespilimagepyc pilimagemodule pilimage from usrlibpython26thistpackagespilimagepyc,['python'] +331123,redirect consolewriteline from windows application to a string i have an external dll written in c and i studied from the assemblies documentation that it writes its debug messages to the console using consolewritelinethis dll writes to console during my interaction with the ui of the application so i do not make dll calls directly but i would capture all console output so i think i got to intialize in form load then get that captured text lateri would like to redirect all the output to a string variablei tried consolesetout but its use to redirect to string is not easy,"['c#', '.net']" +331164,what is the recommended way of setting up an sqlalchemy connection for view callables i am using the sqlalchemy expression language for its notation and connection pooling to create dao objects for communicating with the persistence layer i wanted to get some opinions on how i should approach setting up the metadata and engine so that they are available to the applications view callables according to sqlalchemys documentation 0 7coreconnectionshtml they are typically bound and declared global however i have neither this or the singleton approach are good ideas any thoughts would be appreciatedthis is what my init py file looks like inside my projects directoryfrom pyramidconfig import configuratorfrom sqlalchemy import engine from config metadata create enginefrom pyramid beaker import session factory from settingsdb url postgresqluserpasswordlocalhostdbnameengine create enginedb urlmeta metadatadef mainglobal config settings metabind engine other configuration settings,['python'] +331185,what is the state of the art tooling for spring context analysis at runtime assuming you have a rather big spring application including sources at hand and you want to gather all kinds of information about the contexts beans at runtime bean names types classes child application contexts property values annotations proxies structure etcwhat kind of tools would one use to find out,['java'] +331213,generate and run llvm code from native cc is it possible to do these things from a native c or ccompiled program gcall clang and compile given c code of a function passed as const char obtain a pointer and run it in the llvm virtual machineacquire the result in the native program and continue how,"['c++', 'c']" +331238,retrieving which tabs are open in chrome is there a way to retrieve all the tabs open and sort them in to an array in chrome so if gmail and youtube were open there would be two entries in the array entitled gmailcom and youtubecom,['javascript'] +331275,using own enum in settings i would like to use my own enum in a project setting from visual studio menu project properties tab settingsi can select a lot of default types there but even types from other projects in my solution but not the project itsselfis it possible to use an enumeration type from the project itsself as type for a setting,['c#'] +331289,changing getjson to jsonp i have this codescript srcscriptscript documentreadyfunction getjson cats functionfbresults documentwritefbresultscats0title scripthow can i change this codescript documentreadyfunction getjson cats functionfbresults documentwritefbresultscats0title scriptfor it to work as jsonp is this totally different,"['javascript', 'jquery']" +331314,how can i sometimes require password and sometimes not with has secure password my app lets people register using a password or with facebookeven when i remove the password validations from my user model i get password digest cannot be blank on the user modeli use has secure passwordhow can i make password digest not required,['ruby-on-rails'] +331326,change preference item summary text color in android 4 i have the below sample of preference items checkboxpreference androidkeychksound androidsummarysound is off androidtitlesound i use a theme in the resvalues to change the summary text color style namethemedarktext item nameandroidtextcolor0item styleand in the code i write this line setthemerstylethemedarktextits working fine in android 21 but when i tried to run it on a different os ex android 40it did not change the summary text color just the title color onlyany help,['android'] +331402,ideal way to create a python library i want to create a library of python modules which i will be able to access from several separate project folders for example i want the python scripts in proj1 and proj2 to have access to liblibhelppylibmore helppyproj1scriptpyproj1script2pyproj2this scriptpyproj2another scriptpyi do not want a single directory with all the python scripts as this seems rather thisorganized i also definitely do not want to copy the same lib script into each of the different projectswhat is the ideal way to handle this in python is it appending to pythons path or is this more of a hack this seems to have the thisadvantage of making the files less portable or is it this questionanswer about using relative paths or something elsei should add that i am interested in python 2x rather than 3x if it matters,['python'] +331416,secure system calls with php for an online code checker while i do know that system calls and security do not go hand in hand there is a project for which i do need it i am writing a small code checker and i need to compile and execute the user submitted code to test against my test casesbasically i want to run the code in a sandbox so that it cannot touch any files outside of the temporary directory and any files that it creates cannot be accessed by the outside worldrecently i came across an exploit with with which the user could create a file say shellphp with the following contentsphp echo system getxthis gives the attacker a remote shell and since the owner of the file is apache the attacker could basically move around my entire varw where mysql passwords were stored along with other configuration informationwhile i am aware of threats like sql injections and have sanitized the user input before any operations that involve the db i have no idea as to how i can set up the sandbox what are the techniques that i can use to thisable system calls right now i am searching for the word system in the user submitted code and not executing those snippets where it is found and restrict the access to the files that the user submitted code creates as of now my code checker only works for c and i plan to add support for other languages like c java ruby and python after i can secure it also i would like to learn more about this problem that i have encountered so pointers to a place where i could learn more about web security would also be appreciatedmy development machine is running mac os lion and the deployment machine is a linux server so if a solution that was cross platform would be most appreciated but one that dealt with just the linux machine would do too,['php'] +331418,how do i run oswalk in parallel in python i wrote a simple app in java that takes a list of paths and generates a file with all the file paths under that original listif i have pathstxt that hascfolder1cfolder2cfolder10my app runs the recursive function on each path multithreaded and returns a file with all the file paths under these foldersnow i want to write this app in pythoni have written a simple app that uses oswalk to run through a given folder and print the filepaths to outputnow i want to run it in parallel and i have seen that python has some modules for thismultithreaded and multiprocessingwhat is the best what to do this and within that way how is it performed,['python'] +331436,using interpreter pattern on a composite structure i have been asked to make an expression evaluator using composite recursive descendent parser and interpreterheres the grammar cond a termb or termbtermbafactband factbfactbaexpr relop expr not factb opar cond cparexpr a plus minus term plus term minus termterm a termp mult termp div termp rem termptermp a fact power factfact a id num opar1 expr cpar1terminalsid a a z a z a z a z 0 9num a 0 9 0 9opar a cpar a opar1 a cpar1 a relop a eq neq gt ge lt leeq a neq a gt a ge a lt a le a power a div a rem a mult a minus a aplus a and a aanda or aaor a aora or aanot a anota or aathe assignment isthe goal of the project based on composite recursive builder and interpreter is to get a conditional expression do a syntax analysis and build its composite tree starting from the tree youve got to evaluate the result of the condition based on an external context read from a properties file that contains the value of the internal variablesnow the first thing that i noticed is that interpreter uses a composite structure so it seemed a good idea to extend my composite structure with an evaluatecontext methodi have asked around but i have been told that this is not the way to do the assignmentseems like i have got build the interpreter tree starting from the composite one which is quite nonsens for me as i have already got a tree to work withso i have built my tree using composite recursive builder it recognizes the input and it build the tree without any kind of problembut the question is how do i apply interpreter to my structureheres my class diagram something is italian but it is quite understandableif i got it right interpreter uses a class for each grammar rule so i have got to make a cond class then a termb and so onbut ho do i link them to my composite,['java'] +331447,can anyone help condense this python code i am writing a script in python and have a bit of a problemclass lightdmuserqobject def init self user superlightdmuser self init selfuser user pyqtpropertyqvariant def backgroundself return selfuserget background pyqtpropertyqvariant def thisplay nameself return selfuserget thisplay name pyqtpropertyqvariant def has messagesself return selfuserget has messages pyqtpropertyqvariant def home directoryself return selfuserget home directory pyqtpropertyqvariant def imageself return selfuserget image pyqtpropertyqvariant def languageself return selfuserget language pyqtpropertyqvariant def layoutself return selfuserget layout pyqtpropertyqvariant def layoutsself return selfuserget layouts pyqtpropertyqvariant def logged inself return selfuserget logged in pyqtpropertyqvariant def nameself return selfuserget name pyqtpropertyqvariant def real nameself return selfuserget real name pyqtpropertyqvariant def sessionself return selfuserget sessionas you can see this code is horribly redundant i tried condensing it like thisclass lightdmuserqobject attributes background thisplay name has messages home directory image language layout layouts logged in name real name session def init self user superlightdmuser self init selfuser user for attribute in selfattributes setattrself attribute pyqtpropertyqvariant getattrselfuser get attributepyqt4 however expects the class methods to be present for the class itself not an instance moving the setattr code out of the init block did not work either because self was not defined for the class so i do not really know what to docan anyone see a way to condense this code,['python'] +331463,why does not php print truefalse possible duplicatephp get bool to echo false when false given the following testphpphpecho true n prints 1necho false n prints nwhy does not php f testphp print true or false more importantly in the false case why does not it print anything,['php'] +331514,what is the point of allowing an identifier for enum why does not the compiler complain when i try to assign incorrect values to variable a of type enum answerinclude stdiohint main enum answer no yes enum gender male female enum answer a 5 assign an invalid value printfanswer dn a a male assign a value of wrong type printfanswer dn a return 0here is the output gcc stdc99 pedantic wall wextra enumc aoutanswer 5answer 0if enum does not lead to typechecking then what is the point of having the syntax asenum identifier enumeratorlisti used answer and gender as the identifier for my enum what is the point of allowing this syntaxi mean this code could be very well written asenum no yesenum male femalewhat is the point of allowing this syntaxenum answer no yesenum gender male female,['c'] +331521,android ssl javaxnetsslsslpeerunverifiedexception no peer certificate yet again i have got a web site that i am enabling ssl on for a restful service we have registered with rapidssl installed the certs and it passes the rapidssl checker i am able to access the site with various browsers including the android browsers built in firefox and opera with no problems no warningshowever when i try to access it with my android app i get the following exception0811 200405586 363 381 e httpprovider error executing request no peer certificate0811 200405586 363 381 e httpprovider javaxnetsslsslpeerunverifiedexception no peer certificate0811 200405586 363 381 e httpprovider at orgapacheharmonyxnetproviderjssesslsessionimplgetpeercertificateslsessionimpljava2590811 200405586 363 381 e httpprovider at orgapachehttpconnsslabstractverifierverifyabstractverifierjava930811 200405586 363 381 e httpprovider at orgapachehttpconnsslsslsocketfactorycreatesocketsslsocketfactoryjava3810811 200405586 363 381 e httpprovider at orgapachehttpimplconndefaultclientconnectionoperatoropenconnectiondefaultclientconnectionoperatorjava1640811 200405586 363 381 e httpprovider at orgapachehttpimplconnabstractpoolentryopenabstractpoolentryjava1640811 200405586 363 381 e httpprovider at orgapachehttpimplconnabstractpooledconnadapteropenabstractpooledconnadapterjava1190811 200405586 363 381 e httpprovider at orgapachehttpimplclientdefaultrequestdirectorexecutedefaultrequestdirectorjava3590811 200405586 363 381 e httpprovider at orgapachehttpimplclientabstracthttpclientexecuteabstracthttpclientjava50811 200405586 363 381 e httpprovider at orgapachehttpimplclientabstracthttpclientexecuteabstracthttpclientjava4870811 200405586 363 381 e httpprovider at orgapachehttpimplclientabstracthttpclientexecuteabstracthttpclientjava4650811 200405586 363 381 e httpprovider at comxnetlibhttphttpproviderexecuterequesthttpproviderjava75this occurs on android 233 on the emulator and on a 32 tablet i have seen lots of hits on this but nothing i have found helps me to fix the issuemore data openssl s client cafile wxcompem connect wxcom443connected03depth3 c us o equifax ou equifax secure certificate authorityverify return1depth2 c us o geotrust inc cn geotrust global caverify return1depth1 c us o geotrust inc cn rapidssl caverify return1depth0 serialnumber 17wartejdtwj94d5ivdoodmmc4mxyvj ou gt82425783 ou see wrapidsslcomresourcescps c12 ou domain control validated rapidsslr cn wxcomverify return1certificate chain0 sserialnumber17wartejdtwj94d5ivdoodmmc4mxyvjougt82425783ousee wrapidsslcomresourcescps c12oudomain control validated rapidsslrcnwxcom icusogeotrust inccnrapidssl ca1 scusogeotrust inccnrapidssl ca icusogeotrust inccngeotrust global ca2 scusogeotrust inccngeotrust global ca icusoequifaxouequifax secure certificate authoritysnipthe code i am running to set up the clientpublic class httpprovider implements inetworkprovider private static final string log httpprovider protected defaulthttpclient client public httpprovider schemeregistry registry new schemeregistry registryregisternew schemehttp plainsocketfactorygetsocketfactory 80 final sslsocketfactory sslsocketfactory sslsocketfactorygetsocketfactory sslsocketfactorysethostnameverifiersslsocketfactorybrowser compatible hostname verifier registryregisternew schemehttps sslsocketfactory 443 client new defaulthttpclient new threadsafeclientconnmanagernew basichttpparams registry new basichttpparams snipi have also tried with strict hostname verifier and still no joyfrom what i understand i should not need to set up any custom truststores or keystores since i am registered with a recognized cert provideri am very new with ssl and find i am swimming in a sea of three letter acronyms and i was hoping someone here may be able to give me a shove in the right direction,['android'] +331532,reason for c member function hiding possible duplicatename hiding and fragile base problem i am familiar with the rules involving member function hiding basically a derived class with a function that has the same name as a base class function does not actually overload the base class function it completely hides itstruct base void fooint x const struct derived public base void fooconst stdstring s int main derived d dfooabc dfoo123 will not compile basefoo is hiddenso you can get around this with a using declaration but my question is what is the reason for base class function hiding is this a feature or just a mistake by the standards committee is there some technical reason why the compiler cannot look in the base class for matching overloads when it does not find a match for dfoo123,['c++'] +331537,android the following classes could not be found edittext change to androidwidgetedittext fix build path edit xml when trying to view the graphical layout view i am getting the following errorthe following classes could not be found edittext change to androidwidgetedittext fix build path edit xmlthe app works fine and i can edit the xml without any problems i just cannot load the graphical layout view anymore in the mainjava file there are no problems or errors importing the edittext widget from the android libraryi am using eclipse indigo service release 2 got all the recent updatesi am also using the latest android sdk tools 2001here is the source i have tried the option to source cleanup document and format just to make sure the xml was correctxml version10 encodingutf8relativelayout xmlnsandroid androidlayout widthmatch parent androidlayout heightmatch parent button androidididbutton1 androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparenttoptrue androidlayout centerhorizontaltrue androidlayout margintop63dp androidtextstringbutton1 edittext androidididedittext1 androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentlefttrue androidlayout alignparentrighttrue androidlayout alignparenttoptrue androidlayout margintop16dp androidems10 androidinputtype requestfocus edittextrelativelayouti managed to fix the problemi had to change androidinputtype to androidinputtypetextthe graphical layout view now works again,['android'] +331539,layout algorithm that understands compass rose i want to visualize a graph that represents some geographical map as such the edges of my graph are associated with the compass rose north south east west the graph itself is directed and can be made acyclic for example i have nodes house1 house2 house3 with edges house1 northof house2 house2 eastof house3 i am looking for a layout algorithm that can be made to understand the compass rose perhaps as hintsi have gone through jung jgraph graphviz and none seem to do what i want but i may have missed somethingany suggestions,['java'] +331540,how to reduce textview line spacing i am trying to reduce the line spacing in a textview by setting a negative add to textviewsetlinespacing it works well except that the bottom line get truncated main layouttextview androidididtext view androidpaddingdp androidlayout widthwrap content androidlayout heightwrap content androidlayout centerhorizontaltrue androidlayout centerverticaltrue toolscontextmainactivity main activity notice the package comfont testimport androidappactivityimport androidgraphicstypefaceimport androidosbundleimport androidwidgettextviewpublic class mainactivity extends activity override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main final typeface typeface typefacecreatefromassetgetassets fontscustom fontsttf final textview tv textview findviewbyidridtext view tvsettypefacetypeface tvsettextsize60 tvsetlinespacing30f 1f 30 to reduce line spacing tvsetbackgroundcolor0x280ff tvsettextgkik n gikgikgik n kigkigkig this results in truncation at the bottom of the view notice the g at the bottom lineit seems that the problem is related to incorrect layout measurement if i set the textview to androidlayout heightfill parentit does render properlyany idea how to fix it i do not mind to have ugly workarounds if it helps i also have access to fontforge and i can modify the font file if needed,['android'] +331562,css can i use text as a mask so the background image shows inside the text only i have a nice background on my page and i want my text header to act as a mask to cut through its containing div and have the background as a texture can i do this in css or do i have to open up photoshop,"['html', 'css']" +331603,how to pass a c object to another c object with boostpython i have some c code that defines two classes a and b b takes an instance of a during construction i have wrapped a with boostpython so that python can create instances of a as well as subclasses i want to do the same with bclass a public along n long x long y nn xx yy long get n return n long get x return x long get y return y private long n x yclass b public ba a aa dosomething private a awhile wrapping b i needed to work out how to pass an instance of a to bs constructor i did some digging and the solution i found was to write a converter clastruct a from python a static void convertiblepyobject obj ptr assume it is for now return obj ptr convert obj ptr into an a instance static void constructpyobject obj ptr boostpythonconverterrvalue from python stage1 data data extract n pyobject and ptr pyobject callmethodobj ptr charget n char long and val 0 if n ptr null cout an exception occurred get n endl else and val pyint aslongn ptr py decrefn ptr snip also do the same for x y grab pointer to memory into which to construct the new a void storage boostpythonconverterrvalue from python storagea datastoragebytes inplace construct the new a using the data extracted from the python object new storage an val x val y val stash the memory chunk pointer for later use by boostpython dataconvertible storage register converter functions a from python a boostpythonconverterregistrypush back convertible construct boostpythontype ida then i register this withboost python moduleinterpolation ext register the frompython converter for a a from python a class aa initlong long long class bb initobject convertible and construct are methods that answer the is this convertible and how to convert questions respectively i have observed that the construct method is nontrivial it has to reach into as pyobject extract all relevant fields then rebuild a c instance that it then passes to bs constructor because a contains some private fields it has to do this via public access mechanisms whereas with a pure python object it wouldnt have to right this seems to workhowever is the field extraction in the construct function really necessary it seems laborious if a is a compound object it could get very complicated and possibly require one converter to invoke another i perhaps understand the requirement if a is a python class but if the a instance originated from the c side is there a way to determine that this is the case and then simply get a handle eg pointer to this native object as a shortcutheres the associated python codefrom my ext import a ba a123b babdosomething,"['c++', 'python']" +331612,why does my program fail to link when i change the order of gs arguments possible duplicatewhy does the order of l option in gcc matter i am starting to learn the boost unit test framework i have a minimal test suitedefine boost test maindefine boost test dyn link include boosttestunit testhppboost auto test case test1 boost check 2 1 first i compile the sourceg c srctestscc o srctestsothis completes with no errors i can then link as followsg o tests srctestso lboost unit test frameworkthis also completes with no errors the resulting binary executes with the expected results however if i swap the order of srctestso and lboost unit test framework i get linker errorsg o tests lboost unit test framework srctestsosrctestso in function maintestscctext0x29 undefined reference to boostunit testunit test mainbool int charsrctestso in function test1test methodtestscctext0x9d undefined reference to boostunit testunit test log tset checkpointboostunit testbasic cstring unsigned int boostunit testbasic cstringtestscctext0x146 undefined reference to boosttest toolstt detailcheck implboosttest toolspredicate result const boostunit testlazy ostream const boostunit testbasic cstring unsigned int boosttest toolstt detailtool level boosttest toolstt detailcheck type unsigned int srctestso in function static initialization and destruction 0int inttestscctext0x24d undefined reference to boostunit testut detailauto test unit registrarauto test unit registrarboostunit testtest case unsigned longsrctestso in function boostunit testunit test log tunit test log ttestscctext zn5boost9unit test15unit test log tc2ev zn5boost9unit test15unit test log tc5ev0x21 undefined reference to vtable for boostunit testunit test log tsrctestso in function boostunit testmake test caseboostunit testcallback0 const boostunit testbasic cstringtestscctext zn5boost9unit test14make test caseerkns0 9callback0ins0 9ut detail6unusedens0 13basic cstringikceeboostunit testmake test caseboostunit testcallback0 const boostunit testbasic cstring0x1d undefined reference to boostunit testut detailnormalize test case nameboostunit testbasic cstringtestscctext zn5boost9unit test14make test caseerkns0 9callback0ins0 9ut detail6unusedens0 13basic cstringikceeboostunit testmake test caseboostunit testcallback0 const boostunit testbasic cstring0x5d undefined reference to boostunit testtest casetest caseboostunit testbasic cstring boostunit testcallback0 constsrctestso in function boostunit testunit test log tunit test log ttestscctext zn5boost9unit test15unit test log td2ev zn5boost9unit test15unit test log td5ev0xb undefined reference to vtable for boostunit testunit test log tcollect2 ld returned 1 exit statuswhy does the order of my arguments cause linker errors,['c++'] +331614,declaring a python function with an array parameters and passing an array argument to the function call i am a complete newbie to python and attempting to pass an array as an argument to a python function that declares a listarray as the parameteri am sure i am declaring it wronghere goesdef dosomethinglistparam do something heredosomethinglistargumentclearly this is not working what am i doing wrongthanks,['python'] +331615,turn on the internet on android when in sleep i have an android app that needs to sync to the internet but as soon as the phone goes to sleep i cannot access the internet it only happens when the user uses the battery mode when it turns off the data after 15 minutes i wrote a test app and its turning the data on but it still does connect to the serverwhat i tried when i turn the data manually off then the app is turning it on and it worksi also tried wakelock but it did not help the alarm works as expected even when the phone goes to sleep for hourstested on motorola atrix android 233 i cannot rely on wifi in real life it will sync every week how can we make it possiblealarmmanageralarm manager alarmmanagergetsystemservicecontextalarm serviceintent intent new intentthis alarmreceiverclasspendingintent pending pendingintentgetbroadcastthis 0 intent pendingintentflag update currentalarm managersetrepeatingalarmmanagerrtc wakeup systemcurrenttimemillis 150 pendingalarmreceiverpublic class alarmreceiver extends broadcastreceiver override public void onreceivecontext context intent intent logdmytag received getmobiledataenabled getmobiledataenabledcontext if isonlinecontext logdmytag no inet if turnoninetcontext logdmytag inet is on httpclient httpclient new defaulthttpclient httppost httppost new httppost try listnamevaluepair namevaluepairs new arraylistnamevaluepair1 namevaluepairsaddnew basicnamevaluepairshort code rofl httppostsetentitynew urlencodedformentitynamevaluepairs httpclientexecutehttppost logdmytag post finished catch exception e logemytag mytag e public boolean isonlinecontext context connectivitymanager cm connectivitymanagercontextgetapplicationcontextgetsystemservicecontextconnectivity service networkinfo netinfo cmgetactivenetworkinfo if netinfo null logdmytag isavailable netinfoisavailable if netinfo null netinfoisconnectedorconnecting return true return false public boolean turnoninetcontext context connectivitymanager mgr connectivitymanagercontextgetapplicationcontextgetsystemservicecontextconnectivity service if mgr null logdmytag connectivitymanager null return false try method setmobiledataenabledmethod mgrgetclassgetdeclaredmethodsetmobiledataenabled booleanclass if null setmobiledataenabledmethod logdmytag setmobiledataenabledmethod null return false setmobiledataenabledmethodinvokemgr true catchexception e logemytag mytag e return false return true private boolean getmobiledataenabledcontext context connectivitymanager mgr connectivitymanagercontextgetapplicationcontextgetsystemservicecontextconnectivity service if mgr null logdmytag getmobiledataenabled connectivitymanager null return false try method method mgrgetclassgetmethodgetmobiledataenabled return boolean methodinvokemgr catch exception e logemytag mytag e return false androidmanifestxmlusespermission androidnameandroidpermissioninternet usespermission androidnameandroidpermissionaccess network state usespermission androidnameandroidpermissionchange network state,['android'] +331617,how do i select all inputs except under a specific id what i want to do is to select all the inputs buttons on the document except those that reside under a specific idexamplebodyinput typebuttondiv idsomething input typebuttondivdiv idsomething2 input typebuttondivinput typebuttoninput typebuttoninput typebuttonbodyfor example i would like to select all the inputs except those that resides under the div whose id is somethingwhat i have tried1 inputtypebuttonnotparentsomethingaddcss2 inputtypebutton notsomething inputtypebuttonand other similar approaches,"['jquery', 'html']" +331640,setting the license for modules in the linux kernel i have written some kernel modules in ada and i have hit a bit of a problem license is defined as a c macro and i cannot work out what it actually is is it a suitable solution to simply have some c reexporting all the c functions which require gpl if both the c and the ada module have gpl compatible licenses is there a better way to do this,['c'] +331671,use of thispatchdrawcanvas canvas what is the use of thispatchdrawcanvas canvas method in viewgroup class,['android'] +331686,does incrementing a mutable input iterator invalidate old iterator values iterators that further satisfy the requirements of output iterators are called mutable iterators nonmutable iterators are referred to as constant iterators 24214this suggests you could have a mutable input iterator which meets the requirements of both input and output iterators after incrementing an input iterator copies of its old value need not be dereferenceable 2423 however the standard does not say the same for output iterators in fact the operational semantics for postfix increment are given as x tmp r r return tmp suggesting that output iterators may not invalidate copies of old iterator valuesso can incrementing a mutable input iterator invalidate old iterator copiesif so how would you support code like x ar a t or xreference pr p t with eg a proxy objectif not then why does boostiterator claim it needs a proxy object link is code scroll down to read the comments on structs writable postfix increment proxy and postfix increment result that is if you can return a dereferenceable copy of the old iterator value why would you need to wrap this copy in a proxy,['c++'] +331716,reading a downloaded file from ftp server is not shoing data after using fgetcsv function i am using a curl request for downloading a csv file from an ftp serveri have downloaded my file in my webroot folder in my given pathbut when i am trying to read the csv data from the file it is not showing anythingleaddir is path of my downloaded fileif fp fopenleaddir r echo fp echo come after fopen while csvdata fgetcsvfp echo br echo come after fgetcsv it is not going inside the while loopi have also checked the file permissions i have given it 7 permissionswhere is it going wrong,['php'] +331717,finding js memory leak in chrome dev tools iam using the chrome dev tools to work out if there is a memory leak in some js code the memory timeline looks good with memory being reclaimed as expectedhowever the memory snapshot is confusing because it appears like there is a leak because there are entries under adetached dom treea is the stuff under adetached dom treea just waiting to be garbage collected or are these real leaks also does anyone know how to find out what function is holding on to a reference to a detached element,"['javascript', 'jquery']" +331718,accepting the animation editin my word game there is a grid with 3 letter words the aim of the game is to spell the words by clicking on the corresponding letters on the side when an area in the grid is highlighted it indicates to the user the word to spell the user clicks the letters on the side of the grid and they move to the highlighted areaat the moment i have the styles to show if the individual letters are correct but when a word is completed i need it to recognize this so i can apply the styles to itcan someone show me some code that recognizes the correct and wrong wordswhen it was a drag and drop game i did it like this if guesseswordlength 3 if guesseswordjoin word tddataword word addclasswordglow2 else tddataword word addclasswordglow4 targetsplice0 guesseswordlength here is the code for the click to animate functionif targetlength minibuttonpropthisabled true bcloneaddclass bdataletter targetdataletter wordglow3 wordglowappendtotablecss background transparent position absolute top currentpostop left currentposleft animate top targetpostop left targetposleft slow function thiscss top 0 left 0 appendtotarget targetaddclassoccupied i have tried this if targetlength 3 if targetjoin word thisaddclasswordglow2 else tddataword word addclasswordglow4 guesseswordsplice0 guesseswordlength and thisif wordglow3length 3 tddataword word addclasswordglow2 else if wordglowlength 3 tddataword word addclasswordglow4 guesseswordsplice0 guesseswordlength thanksif it helps here is a fiddle,"['javascript', 'jquery']" +331740,spring security conditional defaulttargeturl i have noticed that there are a couple of questions asking about this topic i looked through them and i was unable to apply them to my specific spring setup i would like to configure my login redirect to be conditional based on the users role this is what i have so farhttp autoconfigtrue useexpressionstrue customfilter reffiltersecurityinterceptor beforefilter security interceptor accessdeniedhandler refaccessdeniedhandler formlogin loginpagelogin defaulttargeturladminindex authenticationfailureurlindexerrortrue logout logoutsuccessurlindex invalidatesessiontruehttpi thought this question might be in the same line as what i am trying to do anyone know how i can apply it thoughedit 1bean idauthenticationprocessingfilter classorgspringframeworksecuritywebauthenticationusernamepasswordauthenticationfilter property nameauthenticationmanager refauthenticationmanager property nameauthenticationsuccesshandler refauthenticationsuccesshandlerbeanbean idauthenticationsuccesshandler classorgspringframeworksecuritywebauthenticationsimpleurlauthenticationsuccesshandler property namedefaulttargeturl valueloginjspbeanedit 2currently i do not have a class like public class test implements authenticationsuccesshandler as shown in this example,['java'] +331751,android intentservice instantiation error possible duplicateandroid runtimeexception unable to instantiate the service i am downloading my data using intentservice my intentservice class definition is as followspublic class downloadservice extends intentservicesuperdownloadserviceoverride protected void onhandleintentintent intent download tasks androidmanifestxmlappilcationservice androidnamedownloadserviceapplicationlauncheractivityjavaoverridepublic void oncreatebundle savedinstancestate intent dwnldservice new intentthis downloadserviceclass startservicedwnldservicebut still i am getting this error0813 085709416 eandroidruntime942 fatal exception main0813 085709416 eandroidruntime942 javalangruntimeexception unable to instantiate service comappandroiddowloadservice javalanginstantiationexception cannot instantiate class comappandroiddowloadservice no empty constructor0813 085709416 eandroidruntime942 at androidappactivitythreadhandlecreateserviceactivitythreadjava22370813 085709416 eandroidruntime942 at androidappactivitythreadaccess1600activitythreadjava1230813 085709416 eandroidruntime942 at androidappactivitythreadhhandlemessageactivitythreadjava12010813 085709416 eandroidruntime942 at androidoshandlerthispatchmessagehandlerjava990813 085709416 eandroidruntime942 at androidoslooperlooplooperjava1370813 085709416 eandroidruntime942 at androidappactivitythreadmainactivitythreadjava44240813 085709416 eandroidruntime942 at javalangreflectmethodinvokenativenative method0813 085709416 eandroidruntime942 at javalangreflectmethodinvokemethodjava5110813 085709416 eandroidruntime942 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava7840813 085709416 eandroidruntime942 at comandroidinternaloszygoteinitmainzygoteinitjava5510813 085709416 eandroidruntime942 at dalviksystemnativestartmainnative method0813 085709416 eandroidruntime942 caused by javalanginstantiationexception cannot instantiate class comappandroiddowloadservice no empty constructor0813 085709416 eandroidruntime942 at javalangclassnewinstanceimplnative method0813 085709416 eandroidruntime942 at javalangclassnewinstanceclassjava13190813 085709416 eandroidruntime942 at androidappactivitythreadhandlecreateserviceactivitythreadjava2234,['android'] +331774,quickly calculating the dirtied areas between two similar images i have two very similar images specifically two screenshots and i am trying to find the best quickest way of finding which areas of the image have changed as an array of rectangles representing the differing areasa few criteriait does not need to be pixelaccurate but must include all changes however small ie it would be acceptable for a singlepixel change to have a large margin of error around itit needs to be fast ideally 2x 1920x1080 images should take 20ms on a typical consumer machine purchased todayit does not require a configurable threshold but if there is a solution that allows for this it would be a nice bonusit can be assumed that the input images are always perfect lossless imagesi have two working solutions as is but one is a brute force pixelbypixel calculation which of course is very slow and for the other i tried splitting up the two images into chunks of varying sizes and calculating checksums for each chunk but this is also quite slowjust for those wondering what i am building it is a kind of dumber and slower remote desktop that can be used in a browser without any plugins,"['c#', '.net']" +331780,php can array of numbers add up to number this is more of a puzzle than anything i have actually found a solution but it is so slow i thought i lost my internet connection see belowheres the problemlet us say i have an array of numbers like sonumbers array array1 2 3 4 5 6 7 8 9let us also say that i have a number some numbers stored in variables like sosum 15sum2 24sum3 400i am trying to create a function that will return true if any of the numbers in numbers array can be added together each only used once to form the sumsfunction is summablearray of nums sum to check what to put herevar dumpis summablenumbers array sumvar dumpis summablenumbers array sum2var dumpis summablenumbers array sum3the above should outputbooltruebooltrueboolfalsebecause 7 8 15 7 8 9 24 but no combination of 19 can create 200heres my extremely slow solutionfunction is summablenumbers sum sort provided numbers and assign numerical keys asortnumbers numbers array valuesnumbers var for additions and var for number of provided numbers total 0 numbers length countnumbers empty var to fill below code loop and add for loops for i 0 i numbers length i code for n i 0 n i numbers length n i if i 0 code if n i n i 1 code total intvalnumbersn i code if total sum code return true code add ending bracket for for loops above for l 0 l numbers length l code total intvalnumbersn i if l 0 code code finally eval the code evalcode if true not returned above return false return falsenum arr array123456789var dumpis summablenum arr 24as always help is appreciated,['php'] +331845,change c dllimport target code depending on x64x86 possible duplicatepreprocessor directivec i have an external c dll to import using dllimport if my application is compiling in x64 i need to import the x64 version of this dll if it is an x86 build i need the x86 dll what is the best way to achieve thisideally i would like some preprocessor directive but i understand this does not work in cmore info the dll is being imported by a project which is set to anycpu a parent project is the one which determines whether the application compiles as x64 or x86 we compile both versions for different customers and i want to share the child project in both versions,['c#'] +331861,use of c ref keyword compared to c i have mainly worked in c and i am now using c at my new job and after doing some reading on here about the ref keyword and c value vs reference types i am still finding some confusion with themas far as i am understanding these if you were passing these to a method these would be analogous c stylesvalue typespublic void csharpfuncvalueand public void cplusplusfuncvaluereference typespublic void csharpfuncreferenceand public void cplusplusfuncreferenceref pointerpublic void csharpfuncref barandpublic void cplusplusbaris this a correct analogy,"['c#', 'c++']" +331883,gcmregistrarondestroycontext crashing receiver not registered how should i call gcmregistrarondestroy currently my main activity contains this protected void ondestroy gcmregistrarondestroythis superondestroyand after doing a registration or unregistration and then killing the main activity i am getting this0813 154356459 eandroidruntime2389 fatal exception main0813 154356459 eandroidruntime2389 javalangruntimeexception unable to destroy activity comtestandroidcomtestandroidactivitiesmainactivity javalangillegalargumentexception receiver not registered comgoogleandroidgcmgcmbroadcastreceiver40673a100813 154356459 eandroidruntime2389 at androidappactivitythreadperformdestroyactivityactivitythreadjava30900813 154356459 eandroidruntime2389 at androidappactivitythreadhandledestroyactivityactivitythreadjava31550813 154356459 eandroidruntime2389 at androidappactivitythreadaccess2100activitythreadjava1320813 154356459 eandroidruntime2389 at androidappactivitythreadhhandlemessageactivitythreadjava10710813 154356459 eandroidruntime2389 at androidoshandlerthispatchmessagehandlerjava990813 154356459 eandroidruntime2389 at androidoslooperlooplooperjava1500813 154356459 eandroidruntime2389 at androidappactivitythreadmainactivitythreadjava42770813 154356459 eandroidruntime2389 at javalangreflectmethodinvokenativenative method0813 154356459 eandroidruntime2389 at javalangreflectmethodinvokemethodjava5070813 154356459 eandroidruntime2389 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava8390813 154356459 eandroidruntime2389 at comandroidinternaloszygoteinitmainzygoteinitjava5970813 154356459 eandroidruntime2389 at dalviksystemnativestartmainnative method0813 154356459 eandroidruntime2389 caused by javalangillegalargumentexception receiver not registered comgoogleandroidgcmgcmbroadcastreceiver40673a100813 154356459 eandroidruntime2389 at androidapploadedapkforgetreceiverthispatcherloadedapkjava6340813 154356459 eandroidruntime2389 at androidappcontextimplunregisterreceivercontextimpljava8800813 154356459 eandroidruntime2389 at androidcontentcontexttesterunregisterreceivercontexttesterjava3310813 154356459 eandroidruntime2389 at comgoogleandroidgcmgcmregistrarondestroygcmregistrarjava2490813 154356459 eandroidruntime2389 at comtestandroidactivitiesmainactivityondestroymainactivityjava4070813 154356459 eandroidruntime2389 at androidappactivitythreadperformdestroyactivityactivitythreadjava30720813 154356459 eandroidruntime2389 11 moreedit from the mainfestreceiver androidnamereceiverspushreceiver androidpermissioncomgoogleandroidc2dmpermissionsend intentfilter action androidnamecomgoogleandroidc2dmintentreceive action androidnamecomgoogleandroidc2dmintentregistration category androidnamecomtestandroid intentfilterreceiverservice androidnameservicespushservice,['android'] +331907,jackson deserialising json string typereference vs typefactoryconstructcollectiontype to deserialise json string to a list of class different ways listed at stackoverflow questiontype 1 docs linklistsomeclass someclasslist mapperreadvaluejsonstring typefactoryconstructcollectiontypelistclass someclassclasstype 2 docs linklistsomeclass list mapperreadvaluejsonstring new typereferencelistsomeclass though both 2 types above do the job what is the difference between these implementations,['java'] +331910,do i still get default copy constructor and operator if i define ones with nonconst arguments in c if i define a copy constructor and operator that take a nonconst reference to the class is the compiler supposed to still supply default versions for const referencestruct test testtest rhs test operatortest rhsprivate do i still need to declare these to avoid automatic definitions testconst test rhs test operatorconst test rhs,['c++'] +331915,problems with stream interface in c so i have a virtual streaming interface in cclass kxstreampublic virtual kxstream operator u32 num 0it has a ton of basic operators for all the builtin types i have just listed onethen i have a few classes that implement the streaming interface like thisclass kxcbuf public kxstreampublic kxstream operator u32 num so there is an implementation of the streaming interface in kxcbuf so far so good then i have some classes that overload the stream interfaceclass kxsymbol operator u32 const friend kxstream operator kxstream os kxsymbol sym note that this class has cast operator to a builtin type now when i try to stream one of these classes into one of the classes that implements the streaming interface i get an errorkxcbuf bufkxsymbol symbuf sym errorthe compiler gets confused about which functions to use gcc compiles fine but says that there are multiple ways do this this msvc does not compile saying there are multiple overloadssrcvariablecpp524 error c26 kxcbufoperator 15 overloads have similar conversionsi know what is happening just not how to solve it satisfactorily so the compiler can either cast kxcbuf kxstream and then call the friend function which is the right thing to do or it can cast kxsymbol u32 and then call the u32 operator in kxcbuf inherited from kxstreami can solve it two bad waysi can start by streaming in something unambiguousbuf symthis way the return value of the first stream operator for return kxstream and all is well or i can implement a redundant stream operator for the implementation class eg i can add the following to kxsymbolfriend kxstream operator kxcbuf os kxsymbol sym the first answer always works but it sure is ugly the second answer is also ugly in that i have to create redundant stream operators and does not always work in that the kxstream implementations are not always visible in places where i need to define new stream operatorsideally i would like implementations of the kxstream interface to work just like kxstream objects and avoid implicit casts that cause ambiguous conversions how do i solve thisps i need to create my own streaming operators for a custom serialization scheme for my library i cannot use boost or similar third party libraries that have their own serialization classes edit there are several good answers related to controlling the compilers use of the implicit conversion like the conversion to kxsymbol u32 unfortunately that implicit conversion is important to the code for example kxsymbol is a class that stores strings in a table and returns them as numbers so that i can compare strings as numbers eg if two symbols are not equal then the strings are not the same i also store symbols as numbers in some data structuresis there a way to solve this from the other side somehow make the compiler understand that implementations of kxstream should be cast to kxstream objects by preference to other implicit castsfor example what if i would somehow force the compiler to have to first cast kxcbuf to kxstream before using the operator for the builtin types this would make it always prefer the overload operators over the kxstream ones the overloads would require one cast and the kxstream ones would require two,['c++'] +331956,jquery and append without adding space i have the codediv classmessage spanmenu 1spanspanmenu 2spandivnote between the span tags do not have spaces if i usemessageappendspanmenu 3spanthe append adds a space in the line is there any other way to put a tag without having to add spacei need the jquery generates a code like thisdiv classmessage spanmenu 1spanspanmenu 2spanspanmenu 3spandivthank you,['jquery'] +331967,overriding backbones parse function i am trying to use backbone with an apithe default api response format issomemetadatasx resultsywhether it is a fetch for a single model or a collectionso as far as i know i can override the backbone parse function withparse function response return responseresultsbut i have seen in the documentationparse collectionparseresponseparse is called by backbone whenever a collections models are returned by the server in fetch the function is passed the raw response object and should return the array of model attributes to be added to the collection the default implementation is a noop simply passing through the json response override this if you need to work with a preexisting api or better namespace your responses note that afterwards if your model class already has a parse function it will be run against each fetched modelso if i have a response for a collection fetch like thatsomemetadatasx resultsuser1user2the first parse function on the collection will extract user1user2but the doc saysnote that afterwards if your model class already has a parse function it will be run against each fetched modelso it will try to find responseresults on user1 and user2i need both parse functions on the model and collection because both model and collection datas will be under the result attributebut if i fetch on a collection i do not want the model parse function to be used againt a single array elementso is there a solution to this problemi think of a solution where my collection parse function will transform something like thissomemetadatasx resultsuser1user2into something like this resultsuser1 resultsuser2 so that the model parse function will not fail on a collection fetchbut it is a bit hacky is there any elegant solution to this problemby the way as my api will always produce results of this form is it possible to override by default the parse function of all my models and collections sorry i am a js noob,['javascript'] +331991,rails nginx needs to be restarted after deploying with capistrano i am using capistrano to deploy my rails application whenever i deploy changes would not be reflected on the browser and i still need to restart nginx to update the site running sudo etcinitdnginx restart i am not really sure why but is not it supposed to be updated after restarting application using touch apptmprestarttxtheres my deployrbrequire rvmcapistranoset rvm ruby string ruby193p194app nameset rvm type userrequire bundlercapistranoset application app nameset user meset deploy to homeuserapplicationset deploy via copyset use sudo falseset scm gitset repository sitesapplicationgitset branch masterrole web 1234role app 1234role db 1234 primary truerole db 1234namespace deploy do task start do end task stop do end task restart roles app except no release true do run try sudo touch filejoincurrent pathtmprestarttxt endend,['ruby-on-rails'] +332039,why is this an invalid variance exact code i am trying to build public interface imapcontainerout t where t maproombase string getname ienumerablet getrooms i am getting this errorinvalid variance the type parameter t must be invariantly valid on maplibraryimapcontainergetrooms t is covarianti was under the impression that this would be valid since ienumerable simply returns the items and none can be added why is this not safe valid,['c#'] +332043,available keyboard shortcuts for web applications i am working on a web application and i would like to add some keyboard shortcuts things like ctrln or ctrlspace however i do not want to use a keyboard shortcut that is already used by the browser for example using the ctrlspace shortcut in google chrome on os x is fine but in firefox on os x it brings up a rightclick menu in the browser is there a known list of cross browseros keyboard shortcuts that are safe or unsafe to use for web applications,['javascript'] +332081,do i have to declare both write external storage and read external storage is it enough to declare usespermission androidnameandroidpermissionwrite external storage or do i also have to declare usespermission androidnameandroidpermissionread external storage the javadocs omit this important information,['android'] +332085,how to make force layout graph in d3js responsive to screenbrowser size i have a graph using force layout but it has a fixed width w and height hvar svg d3selectvizappendsvg attrid playgraph attrwidth w attrheight hvar force d3layoutforce nodesnodes linkslinks charge1600 linkthistance45 sizew h which results in a svg graph that does not scale or down despite of changes in screen or browser window size in order to make it responsive ie automatically resizes itself i tried using viewbox and preserveaspectratio attributesvar svg d3selectvizappendsvg attrid playgraph attrwidth w attrheight h attrviewbox 0 0 600 400 attrpreserveaspectratio xmidymid meetunfortunately this did not work as nothing happens when i adjust the browser window size i wonder if the sizew h of the force graph has anything to do with thisplease shed some light on how to use viewbox and preserveaspectratio attributes with force layout graphs,['javascript'] +332104,html canvas interval vs requestanimationframe so maybe total brainfart here the syntax for setinterval is pretty clear do something every x miliseconds how is this best translated to using the requestanimationframe i have about 300 objects and each is supposed to perform an animation sequence at a certain interval every 8 6 2 etc seconds how can i best accomplish this using requestanimationframe which gets called 60 times a second there is probably an easy answer i just for the life of me cannot figure it out,['javascript'] +332199,difference between char and lpstr in windows i apologise if it is a basic or silly question what is the difference between char and lpstr where the sizeof both gives 4 bytes in my compiler can someone explain me in detail thanks,['c'] +332245,how to use as a wild card in sql query safely i need to implement a search where user can input as a wild card the database they are searching is a sql server i was thinking of just replacing the with a userinput userinputreplace i am worried that since i am doing this by hand i might introduce some bugs or security flaws do you see any problems doing it like this is there any library to do this for mei use hibernate as an orm mapper and criteria api to create the query if it helps with answers,"['java', 'sql']" +332260,how to use select debug app and wait for debugger new feature in jelly bean allselect debug app and wait for debugger are new feature in jelly bean does someone know how to use these new feature what do they dothanks,['android'] +332287,setting up the value in viewbag using jquery i just want to ask is there a way to set up the viewbag value dynamically using jqueryi try this code in my script btnonclickfunctionviewbagid thisattridi dont know if its correct but when i try to run my mvc 3 project this error appear in my firebugsyntax error thisattridplease help thanks,['jquery'] +332305,schedule number of web dynos by time of day is there a way to use the heroku scheduler to start and stop web dynos for specific periods of the day like say during business hours 2 dynos and at night only 1 dynoi really would like to avoid putting the normal userpass credentials into the app itself so i am looking for a secure way to do this apart from doing it manually each day for each app using the heroku psscale web2 directly would naturally be nice but as far as i know this is not supportedthanks for any feedback in advance,['python'] +332306,how to resize nsimage i have nsbitmapimagerep which is wxh size and i create nsimage and do addrepresentation then i need to resize nsimage i tried setsize method but it does not works what should i do,['objective-c'] +332309,bigdecimal multiply by zero i am performing a simple multiplication with bigdecimal and i have found some strange behaviour when multiplying by zero multiplying by zero is correct in this usecasebasic maths tells me that anything multiplied by zero will equal zero seezero product property and multiplication propertieshowever the following code will consistently fail with the same errorassertequalsnew bigdecimal0 new bigdecimal223multiplynew bigdecimal0javalangassertionerror expected 0actual 0e48is this an inaccuracy with bigdecimal or is there some niche branch of maths that i am missing somewherenotes jdk 160 27 running in intellij 11,['java'] +332333,get same result for php str len as for jquery vallength i use jquery to count the value of a textarea on the flyfunction count chars count charstext textareavallengththen on submit serialize the form send the text of the textarea via ajax to a php file which then validates the text on the server side however i got problems with newlines and spacesof course if i just get the text as it is from the textarea php will count each new line as two or 4 characters n so i tried to replace them with something like thisstrlenstr replacearrayr n textor thisstrlenpreg replaces trimtexthowever if i got eg 10 paragraphs and jquery returns 2500 characters php will either return 2510 or 2490 depending if i replace new lines with a space or remove them completely so the difference is 20 but there are only 10 new lineswhat am i missing how can i get php to return the same result as jquery where is the problem in php or in jquery,"['php', 'javascript', 'jquery']" +332336,where to put helper methods for controllers only i am looking to write certain methods for processing strings and other tasks that take place in numerous of my controllers i know its bad practice to include helpers in your controller so i was just wondering where is the best place to put application wide methods used in controllers i realize some of you will say to put them in models but you have to realize that not all my controllers have an associated model any and all input would be appreciated,['ruby-on-rails'] +332349,how to unlock android phone through code remotely i have written an application that locks android phone remotely that is when a special code is sent from server then application locks the phone based on the special code this is the code i am usingif mdpmisadminactivemdeviceadminsample try to become active a must happen here in this activity to get result intent intent new intentdevicepolicymanageraction add device admin intentputextradevicepolicymanagerextra device adminmdeviceadminsample intentputextradevicepolicymanagerextra add explanationadmin is added to do security operation startactivityforresultintent 0 else already is a device administrator can do security operations now mdpmlocknow the above code is working and it is locking the phone i am able to unlock the phone by entering password from soft keypad is there any way to unlock it through codemy question is how to unlock the phone through codethis unlocking should be done remotely in the manner i explained for locking,['android'] +332360,html keyboard shortcuts in sublime text 2 i switched from textmate to sublime in the past few months and have been busy trying to retrain my brain and fingers to use the new shortcut keysin textmate when editing an html documents i could highlight text and do commandb to wrap the selected text in bb tags or commandi to wrap in iiamong various other commandstagsso is there a way to do that in sublime i know i can type b tab to create an empty set of bb tags but i want to be able to wrap selected text in various tags,['html'] +332371,mysql create user with a variable i would like to do thisvariablesset usernamejdoe passwordsecret insert a new mysql usercreate user usernamelocalhost identified by passwordgrant usage on to usernamelocalhost identified by password with max queries per hour 120 max connections per hour 60 max updates per hour 60 max user connections 2but get1064 you have an error in your sql syntax check the manual that corresponds to your mysql server version for the right syntax to use near usernamelocalhost identified by password at line 2how do i use a variable in the create user statement,['mysql'] +332404,how to see jquery validation list of elements with errors sometimes the form would not submit because jquery has some invalid elements that will not show up in an error messagehow can we see these errors in order to debug more easily,['jquery'] +332410,how to use parallelfor i want to use parallel programming in my project wpf here is my for loop codefor int i 0 i resultscount i product p new product commonselectedoldcolor pbackground pvideoinfo resultsi commonproductsaddp false pvisibility systemwindowsvisibilityhidden pdrop event new productdragdropeventp drop event mainchildrenaddpit works without any problem i want to write it with parallelfor and i wrote thisparallelfor0 resultscount i product p new product commonselectedoldcolor pbackground pvideoinfo resultsi commonproductsaddp false pvisibility systemwindowsvisibilityhidden pdrop event new productdragdropeventp drop event mainchildrenaddpbut an error occours in constructor of producd class is the calling thread must be sta because many ui components require thiswell then i used a thispatcher here is codeparallelfor0 resultscount i thisthispatcherbegininvokenew action product p new product commonselectedoldcolor pbackground pvideoinfo resultsi commonproductsaddp false pvisibility systemwindowsvisibilityhidden pdrop event new productdragdropeventp drop event mainchildrenaddpi get error because of my p object it expect and also it says for product class class name is not valid at this point then i created product object above parallelfor but still i get errorhow can i fix my errors,['c#'] +332431,mvp with cdi avoiding circular dependency i try to build a webapp with the mvp paradigm because i want the api to be clean and make everything easy testable i try to inject everything possible via contructor injection now i came to a point where i have a view with multiple textfields these textfields get filled by the presenter when there are values for it in the db so my presenter needs a reference of the view but the vie obviously needs a reference of the presenter too cdi tells me that injection of presenter into the view and otherwise is not possible because of circular dependencies ist it possible to avoid setteing the presenter in the view via a setter method the code looks something like thisviewpublic class viewimpl implements view private presenterimpl presenterprivate user userinjectpublic viewimplpresenterimpl presenter user user super thispresenter presenter thisuser userpublic void attach superattach presenterfetchnames showuser public void setuseruser user thisuser user presenterpublic class presenterimpl implements presenter private viewimpl viewprivate user userinjectpublic presenterimplviewimpl view user user thisview view thisuser userpublic void fetchnames fetchfromdb viewsetuseruserhere i get the cyclic dependency to avoid that i tried to use the instance interface and changed the presenter to thispresenterpublic class presenterimpl implements presenter private viewimpl viewprivate instanceviewimpl instanceviewprivate user userinjectpublic presenterimplinstanceviewimpl instanceview user user thisinstanceview instanceview thisuser user bindpublic void bind thisview instanceviewgetpublic void fetchnames fetchfromdb viewsetuseruserbut when i do that i get an javalangnoclassdeffounderror orgjbossweldinjectionexceptionsupdate here is the stack tracecomvaadinapplication httplocalhost12700180802 terminal error javalangreflectinvocationtargetexceptionat sunreflectnativemethodaccessorimplinvoke0native method rtjar170 05at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava57 rtjar170 05at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43 rtjar170 05at javalangreflectmethodinvokemethodjava601 rtjar170 05at comvaadinterminalgwtserverserverrpcmanagerapplyinvocationserverrpcmanagerjava141 vaadin700alpha3jar700alpha3at comvaadinterminalgwtserverserverrpcmanagerapplyinvocationserverrpcmanagerjava89 vaadin700alpha3jar700alpha3at comvaadinterminalgwtserverabstractcommunicationmanagerhandleburstabstractcommunicationmanagerjava1660 vaadin700alpha3jar700alpha3at comvaadinterminalgwtserverabstractcommunicationmanagerhandlevariablesabstractcommunicationmanagerjava1543 vaadin700alpha3jar700alpha3at comvaadinterminalgwtserverabstractcommunicationmanagerhandleuidlrequestabstractcommunicationmanagerjava577 vaadin700alpha3jar700alpha3at comvaadinterminalgwtserverabstractapplicationservletserviceabstractapplicationservletjava461 vaadin700alpha3jar700alpha3at comvaadinterminalgwtserverabstractapplicationservletserviceabstractapplicationservletjava350 vaadin700alpha3jar700alpha3at dememainwebmeappservletservicemeappservletjava60 classesat javaxservlethttphttpservletservicehttpservletjava847 jboservletapi 30 spec100finaljar100finalat orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava329 jbossweb7013finaljarat orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava248 jbossweb7013finaljarat orgjbossweldservletconversationpropagationfilterdofilterconversationpropagationfilterjava62 weldcore115as71finaljar20120210 1531at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava280 jbossweb7013finaljarat orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava248 jbossweb7013finaljarat orgapachecatalinacorestandardwrappervalveinvokestandardwrappervalvejava275 jbossweb7013finaljarat orgapachecatalinacorestandardcontextvalveinvokestandardcontextvalvejava161 jbossweb7013finaljarat orgjbossasjpainterceptorwebnontxemcloservalveinvokewebnontxemcloservalvejava50 jbossasjpa711finaljar711finalat orgjbossaswebsecuritysecuritycontextassociationvalveinvokesecuritycontextassociationvalvejava153 jbossasweb711finaljar711finalat orgapachecatalinacorestandardhostvalveinvokestandardhostvalvejava155 jbossweb7013finaljarat orgapachecatalinavalveserrorreportvalveinvokeerrorreportvalvejava102 jbossweb7013finaljarat orgapachecatalinacorestandardenginevalveinvokestandardenginevalvejava109 jbossweb7013finaljarat orgapachecatalinaconnectorcoyoteadapterservicecoyoteadapterjava368 jbossweb7013finaljarat orgapachecoyotehttp11http11processorprocesshttp11processorjava877 jbossweb7013finaljarat orgapachecoyotehttp11http11protocolhttp11connectionhandlerprocesshttp11protocoljava671 jbossweb7013finaljarat orgapachetomcatutilnetjioendpointworkerrunjioendpointjava930 jbossweb7013finaljarat javalangthreadrunthreadjava722 rtjar170 05caused by comvaadineventlistenermethodmethodexception invocation of method click in demeloginviewloginviewimpl1 failedat comvaadineventlistenermethodreceiveeventlistenermethodjava530 vaadin700alpha3jar700alpha3at comvaadineventeventrouterfireeventeventrouterjava164 vaadin700alpha3jar700alpha3at comvaadinuiabstractcomponentfireeventabstractcomponentjava1035 vaadin700alpha3jar700alpha3at comvaadinuiembedded1clickembeddedjava97 vaadin700alpha3jar700alpha3 30 morecaused by javalangnoclassdeffounderror orgjbossweldinjectionexceptionsat orgjbossweldinjectionconstructorinjectionpointnewinstanceconstructorinjectionpointjava125 weldcore115as71finaljar20120210 1531at orgjbossweldbeanmanagedbeancreateinstancemanagedbeanjava3 weldcore115as71finaljar20120210 1531at orgjbossweldbeanmanagedbeanmanagedbeaninjectiontargetproducemanagedbeanjava200 weldcore115as71finaljar20120210 1531at orgjbossweldbeanmanagedbeancreatemanagedbeanjava289 weldcore115as71finaljar20120210 1531at orgjbossweldcontextunbounddependentcontextimplgetdependentcontextimpljava61 weldcore115as71finaljar20120210 1531at orgjbossweldmanagerbeanmanagerimplgetreferencebeanmanagerimpljava616 weldcore115as71finaljar20120210 1531at orgjbossweldmanagerbeanmanagerimplgetreferencebeanmanagerimpljava681 weldcore115as71finaljar20120210 1531at orgjbossweldinjectionparameterinjectionpointgetvaluetoinjectparameterinjectionpointjava120 weldcore115as71finaljar20120210 1531at orgjbossweldinjectionconstructorinjectionpointgetparametervaluesconstructorinjectionpointjava170 weldcore115as71finaljar20120210 1531at orgjbossweldinjectionconstructorinjectionpointnewinstanceconstructorinjectionpointjava117 weldcore115as71finaljar20120210 1531at orgjbossweldbeanmanagedbeancreateinstancemanagedbeanjava3 weldcore115as71finaljar20120210 1531at orgjbossweldbeanmanagedbeanmanagedbeaninjectiontargetproducemanagedbeanjava200 weldcore115as71finaljar20120210 1531at orgjbossweldbeanmanagedbeancreatemanagedbeanjava289 weldcore115as71finaljar20120210 1531at orgjbossweldcontextunbounddependentcontextimplgetdependentcontextimpljava61 weldcore115as71finaljar20120210 1531at orgjbossweldmanagerbeanmanagerimplgetreferencebeanmanagerimpljava616 weldcore115as71finaljar20120210 1531at orgjbossweldmanagerbeanmanagerimplgetreferencebeanmanagerimpljava681 weldcore115as71finaljar20120210 1531at orgjbossweldinjectionparameterinjectionpointgetvaluetoinjectparameterinjectionpointjava120 weldcore115as71finaljar20120210 1531at orgjbossweldinjectionconstructorinjectionpointgetparametervaluesconstructorinjectionpointjava170 weldcore115as71finaljar20120210 1531at orgjbossweldinjectionconstructorinjectionpointnewinstanceconstructorinjectionpointjava117 weldcore115as71finaljar20120210 1531at orgjbossweldbeanmanagedbeancreateinstancemanagedbeanjava3 weldcore115as71finaljar20120210 1531at orgjbossweldbeanmanagedbeanmanagedbeaninjectiontargetproducemanagedbeanjava200 weldcore115as71finaljar20120210 1531at orgjbossweldbeanmanagedbeancreatemanagedbeanjava289 weldcore115as71finaljar20120210 1531at orgjbossweldcontextunbounddependentcontextimplgetdependentcontextimpljava61 weldcore115as71finaljar20120210 1531at orgjbossweldmanagerbeanmanagerimplgetreferencebeanmanagerimpljava616 weldcore115as71finaljar20120210 1531at orgjbossweldmanagerbeanmanagerimplgetreferencebeanmanagerimpljava681 weldcore115as71finaljar20120210 1531at orgjbossweldinjectionparameterinjectionpointgetvaluetoinjectparameterinjectionpointjava120 weldcore115as71finaljar20120210 1531at orgjbossweldinjectionconstructorinjectionpointgetparametervaluesconstructorinjectionpointjava170 weldcore115as71finaljar20120210 1531at orgjbossweldinjectionconstructorinjectionpointnewinstanceconstructorinjectionpointjava117 weldcore115as71finaljar20120210 1531at orgjbossweldbeanmanagedbeancreateinstancemanagedbeanjava3 weldcore115as71finaljar20120210 1531at orgjbossweldbeanmanagedbeanmanagedbeaninjectiontargetproducemanagedbeanjava200 weldcore115as71finaljar20120210 1531at orgjbossweldbeanmanagedbeancreatemanagedbeanjava289 weldcore115as71finaljar20120210 1531at orgjbossweldcontextunbounddependentcontextimplgetdependentcontextimpljava61 weldcore115as71finaljar20120210 1531at orgjbossweldmanagerbeanmanagerimplgetreferencebeanmanagerimpljava616 weldcore115as71finaljar20120210 1531at orgjbossweldmanagerbeanmanagerimplgetreferencebeanmanagerimpljava681 weldcore115as71finaljar20120210 1531at orgjbossweldinjectionparameterinjectionpointgetvaluetoinjectparameterinjectionpointjava120 weldcore115as71finaljar20120210 1531at orgjbossweldinjectionconstructorinjectionpointgetparametervaluesconstructorinjectionpointjava170 weldcore115as71finaljar20120210 1531at orgjbossweldinjectionconstructorinjectionpointnewinstanceconstructorinjectionpointjava117 weldcore115as71finaljar20120210 1531at orgjbossweldbeanmanagedbeancreateinstancemanagedbeanjava3 weldcore115as71finaljar20120210 1531at orgjbossweldbeanmanagedbeanmanagedbeaninjectiontargetproducemanagedbeanjava200 weldcore115as71finaljar20120210 1531at orgjbossweldbeanmanagedbeancreatemanagedbeanjava289 weldcore115as71finaljar20120210 1531at orgjbossweldcontextunbounddependentcontextimplgetdependentcontextimpljava61 weldcore115as71finaljar20120210 1531at orgjbossweldmanagerbeanmanagerimplgetreferencebeanmanagerimpljava616 weldcore115as71finaljar20120210 1531at orgjbossweldmanagerbeanmanagerimplgetreferencebeanmanagerimpljava681 weldcore115as71finaljar20120210 1531at orgjbossweldinjectionparameterinjectionpointgetvaluetoinjectparameterinjectionpointjava120 weldcore115as71finaljar20120210 1531at orgjbossweldinjectionconstructorinjectionpointgetparametervaluesconstructorinjectionpointjava170 weldcore115as71finaljar20120210 1531at orgjbossweldinjectionconstructorinjectionpointnewinstanceconstructorinjectionpointjava117 weldcore115as71finaljar20120210 1531at orgjbossweldbeanmanagedbeancreateinstancemanagedbeanjava3 weldcore115as71finaljar20120210 1531at orgjbossweldbeanmanagedbeanmanagedbeaninjectiontargetproducemanagedbeanjava200 weldcore115as71finaljar20120210 1531at orgjbossweldbeanmanagedbeancreatemanagedbeanjava289 weldcore115as71finaljar20120210 1531at orgjbossweldcontextabstractcontextgetabstractcontextjava107 weldcore115as71finaljar20120210 1531at orgjbossweldbeanproxycontextbeaninstancegetinstancecontextbeaninstancejava90 weldcore115as71finaljar20120210 1531at orgjbossweldbeanproxyproxymethodhandlerinvokeproxymethodhandlerjava79 weldcore115as71finaljar20120210 1531at dememainlayoutmainlayouterproxy weldclientproxygomainlayouterproxy weldclientproxyjava mainservice005snapshotjarat demecontrollermaincontrollershowmainviewmaincontrollerjava81 mainservice005snapshotjarat demecontrollermaincontrolleraccess0maincontrollerjava80 mainservice005snapshotjarat demecontrollermaincontroller1onloginmaincontrollerjava48 mainservice005snapshotjarat demepresenterloginpresenterimpldologinloginpresenterimpljava69 usermanagement005snapshotjarat demeviewloginviewimpl1clickloginviewimpljava60 usermanagement005snapshotjarat sunreflectnativemethodaccessorimplinvoke0native method rtjar170 05at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava57 rtjar170 05at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43 rtjar170 05at javalangreflectmethodinvokemethodjava601 rtjar170 05at comvaadineventlistenermethodreceiveeventlistenermethodjava510 vaadin700alpha3jar700alpha3 33 more,['java'] +332447,devise install from existing modeldatabase i am wondering how can i add devise to an existing database with a different user here i already have a customer model define and i want to change to allow devise to work on iti have created a new migration and inserted the code has followclass adevisetocustomer activerecordmigration def change change table customers do t tdatabase authenticatable tstring encrypted password null false default limit 128 tconfirmable trecoverable trememberable ttrackable ttoken authenticatable ttimestamps end endendaccording to this it should work but when running rake dbmigrate i get the followingundefined method confirmable for activerecordconnectionadapterstable0x9286a28i have run the following line rails g deviseinstallany reason devise would not recognize it do i need to do something to say customer is a devisethanks in advance,"['ruby-on-rails', 'ruby']" +332456,how did groupme verify my number i am working on an iphone application where i need the users phone number from what i have read here for instance programmatically get own phone number in iphone os the devices phone number is not available within your applications container i have always had the user enter his or her own number but when i joined groupme the other day after clicking the get started button my phone opened up a drafted text message to some us area code number send this text to verify your phone numberb2bd308eb7 after i sent the text the app knew my numberhow does one implement a system like this,"['iphone', 'ios']" +332469,mocking behaviour resets after each test with powermock i am writing unit tests using powermock mocking behaviour of some util classes defining behaviour once for test class by beforeclass annotation causesfirst test invocation to return mocked valuesecond test invocation to return real method return valuesample codeimport orgjunitassertimport orgjunitbeforeclassimport orgjunittestimport orgjunitrunnerrunwithimport orgpowermockapimockitopowermockitoimport orgpowermockcoreclassloaderannotationspreparefortestimport orgpowermockmodulesjunit4powermockrunnerrunwithpowermockrunnerclasspreparefortest aclass bclasspublic class testmockedmethods private static b bbeforeclasspublic static void setup powermockitomockstaticaclass powermockitowhenagetvalthenreturnx b powermockitomockbclass powermockitowhenbgetvalthenreturnytestpublic void test1 pass assertassertequalsx agetval assertassertequalsy bgetvaltestpublic void test2 fail assertassertequalsx agetval actuala assertassertequalsy bgetval actualbclass a static string getval return a class b string getval return b any ideas why second test is failing,['java'] +332473,how to send larger than 4k queries from sql buffer to sqlmysql buffer in emacs i have frequently run into an annoyance in emacss sqlmysql mode and i am wondering if anyone has a solution or better workaround anytime i try to send a query from an sqlmode buffer to an active sql process buffer that query cannot be larger than 4k if it is larger than 4k it appears that some sort of break perhaps a newline is inserted and this causes the mysql interpreter to throw an error on the following linesqlmysql is implemented by sqlel and uses the function sqlsendregion to send query regions or whole buffers to the selected sql process buffer sqlsendregion calls comintsendregion which in turn calls procesendregion procesendregion is a c function that calls send process both in srcprocessc in the emacs sourceit looks like this may just be a limitation produced by the 4k buffer on an ipc pipe since it appears that kernel hacking is necessary to change this size that is not a great answerwhat i guess i am puzzled by is why the sql sent through the pipe is not properly reassembled by the mysql client if it is larger than 4k any ideasemacs version gnu emacs 2331 x86 64pclinuxgnu gtk version 22410 of 20120325 on allspice modified by debianmysql v mysql ver 1414 thistrib 5524 for debianlinuxgnu x86 64 using readline 62sql mysql options a c n nb i have tried both with and without n unbuffered and neither fixed this issue,['mysql'] +332479,windows azure ends connection and returns a 324 error code i have tried some labs in windows azure and it works fine so i start developing my application with azure emulatori perform my first deployment test today in windows azure and have a first issueno connection could be made because the target machine actively refused it 12700110description an unhandled exception occurred during the execution of the current web request please review the stack trace for more information about the error and where it originated in the code exception details systemnetsocketssocketexception no connection could be made because the target machine actively refused it 12700110source error an unhandled exception was generated during the execution of the current web request information regarding the origin and location of the exception can be identified using the exception stack trace belowstack trace socketexception 0x274d no connection could be made because the target machine actively refused it 12700110 systemnetsocketssocketendconnectiasyncresult asyncresult 2724507 systemnetservicepointconnectsocketinternalboolean connectfailure socket s4 socket s6 socket socket ipaddress address connectsocketstate state iasyncresult asyncresult int32 timeout exception exception 392webexception unable to connect to the remote server microsoftwindowsazurestorageclienttaskstask1get result 96 microsoftwindowsazurestorageclienttaskstask1executeandwait 271 microsoftwindowsazurestorageclientcloudblobcontainerdeleteblobrequestoptions options 213 myprojectwebmvcapplicationinitblobs in csitesmyprojectmyprojectmyprojectwebglobalasaxcs85 myprojectwebmvcapplicationapplication start in csitesmyprojectmyprojectmyprojectwebglobalasaxcs52it was the first deployment so i tried to delete a container that does not existi now handle the exceptioni redeploy my project and does not get any server error it just ends the connection and leave me this error error 324 neterr empty responsei assume i miss something in my configuration but i was not able to find what it is exactlythank you for your helpeditthe deployment itself is the first one for this application but it is not the first one i perform on windows azure i already deployed some msdn labs when i start developing for windows azure,['c#'] +332480,accepting invalid ssl certificates using winrt there are scenarios where you want your application to accept invalid ssl certificates testing environment self signed certificates etcin the net world one would use the servercertificatevalidationcallback class to do so unfortunately the class does not exist in a winrt contexti need to consume a web api using winrt which is hosted on a server without a valid ssl certificate how do you accept invalid ssl certificates in winrt using the httpclient class or any other appropriate classany help or alternatives would much appreciated,['c#'] +332509,python intersection of nested lists where order matters i would like to find the intersection between nested lists while maintaining the order taxa e pyrifoliae ep1 96 bacteria proteobacteria gammaproteobacteria enterobacteriales enterobacteriaceae erwinia e amylovora cfbp1430 bacteria proteobacteria gammaproteobacteria enterobacteriales enterobacteriaceae erwinia e amylovora atcc49946 bacteria proteobacteria gammaproteobacteria enterobacteriales enterobacteriaceae erwiniato find the intersection i havesetintersectionmapset taxaorsettaxa0intersectiontaxabut the original order is not kept seterwinia gammaproteobacteria enterobacteriaceae enterobacteriales proteobacteria bacteriabasically what i need to do is find the last common element between the nested lists they are taxanomic classifications so i do not need to find all the intersections just the last one or all of them when i can just call on the last entry intersection lst1in this instance i want the output to be erwiniathanks for your help,['python'] +332532,prevent generation of proxy classes in referencecs when addingupdating a web reference i have a web service and a client the classes used in parameters and return types are in a common dll shared by both however whenever i update the web reference visual studio generates copies of the classes with the same names and public properties and methods then the solution would not compile because the client code tries to use the versions in the common dll i can solve the problem by deleting the duplicate classes every time i update the web reference and adding a using statement to point at the common dlls namespace is there a way to fix this permanently update see my comments below this is a feature of asmx web services there is no way around it other than one of the following1 use a more modern type of web service2 do not use a common dll3 manually fix every time you update the web reference as in the original question above,['asp.net'] +332550,how to thisable windows 8winrt appbar my goal is to only have an appbar available under a certain circumstance i am attempting to accomplish this by creating an appbar but leaving it thisabled until that circumstance arises however if you set the isenabled attribute on an appbar to false when you launch your app and rightclick which typically opens the appbar the application crashes is this a bug in the framework what is the proper way to thisable an appbaredit it also occurs when you set visibility to collapsedmore info i am running it through the visual studio debugger but a separate visual studio justintime debugger window is popping up with the message an unhandled win32 exception occurred in appexe 2596 a warning box pops up on top of that that says a debugger is attached to appexe but not configured to debug this unhandled exception to debug this exception detach the current debuggeredit 2 it is not just my code it also crashes if you just add isenabledfalse to the appbar in microsofts own sample appbarcontrol project found here edit 3 g andrew duthie devhammer provided the answer i am using i just wanted to add that i found that it is best to use thisbottomappbar null to thisable it as opposed to setting the isenabled or visibility properties if you just set visibility to collapsed then when you rightclick the app still thinks an appbar is present even though it is not visible so your next regular click will be interpreted as the click that typically thismisses the appbar so youll have to click a second time to actually carry out the action you were attempting,['c#'] +332600,what is the point of using an id attribute in a script tag basically what i am asking is what is the point of giving my script tags an id attribute can the routines inside of them be called or referenced differently because of this identification could this cause any problems making the scriptpage act funnythanks,"['javascript', 'html']" +332618,resume playing videoview from onresume i have a videoview and it is pause when i start an email intent when the email intent is done i want the videoview to continue playing however it restarts from the beginningoverridepublic void onpause logdtag onpause called superonpause videoviewpauseoverridepublic void onresume superonresume logdtag onresume called videoviewstartresume doesnt workhow can i get the videoview to resume from where it left off,['android'] +332633,load src content to svg image dynamically i have a svg image rendered in the browser i would like to change its content dynamically as attempted on in consoledebug the content is changed however in the browser it is the samesvg image x20 y20 width300 height80 xlinkhref svgavar srcairline dataimagepngbase64ivborw0kggoansuheugad0a9cayaeymhpadd0leqvr42u2aq3lrmbcg0oh9huopk9qwfhyembhywhhywbpygbgqgyduv039mq65lsy7sjxjcs62pw1e6vd6ez9hevgh46nsfhdalqv5oxzpordtpr5bf3xfdp9wedf1qo8pl686689xdamudw2kluvvfnqsnqw47kuh1rstqv46hnv4l99unrrxcnnxwadpuas9lw50hdppnquzzyl9o670g36e5jsllq3xowsfxzozlxbzx6rfwenzy8omsaivjdi1bfxnmjfzikflz5lj2ebbqc6decttvdmxy6auxolvpiftjoghpzwf3k2hkfbjog1vx4eeqxt2qz0epl3faiw8npybpaacut8hyef5og1hl4r5h7yggqti2m00xoyqelbiqgstvih7n3hqyil8lgzigssnoahiba2dutjgq9x7qcfkzo0vaiakjmjtuyirnomql0py3ov6nbhcttv2qhkyawma3ctp7quqfeclsu59500ekxpkgeq3ccdxf0koedyosu0n6avejrxyuvs0n74xvxavphqwdewu5afhjsmnupn1iuepidtmihtl9bnhaahcwbmlohrk3e8n7bmcrju6nnkbqt5gk5qsxwsz7njztthngz0alzldepdzlfb04aw5lrlm7srsi4kp8vxtt0ncnseq1ktqwoere8yriyavpt6sdiesdcca7yl4nrpwjf0ahfzb31egthef7qihnt2nugddhxvewhsptqr4etapwofhakbfc1q0ipq9izwwd40jmzba8sgsbqgjkehjsznuqqnc70lthmlfpkhp4jolfzwn2qmasqiqh3noshmdduwxau31rl0xweuvsw3q3kotanjj2glazlbmewgjm3b4bqbtpsczdj0kd0beec1ojsism18bppumbtoyknjunlyb6emgmlpdyqvdvn8yrcngg7lrybbuwavg9afjzttjmrwpxewfvjbvzjfbi8wxa0nqotbfpersfhbv0bl049jrkb2sq02r4bqjaelftksuqmccdocumentreadychange imagefunction change image var images image var image images0 imageremoveattrxlinkhref imageattrsrc srcairline consoledebugimagei read somewhere that it might be possible with ajax requests however the page needs to be thisplayable offline i also have the constraint that the image content needs to be stored in a variable and cannot be saved as an external resourceis there any simple way to change the content of a svg image dynamically,"['javascript', 'jquery']" +332653,fft and ifft in c i am using cc to perform forwards and reverse fft on some data which is supposed to be the pulsed output of a laserthe idea is to take the output use a forward fft to convert to the frequency domain apply a linear best fit to the phase first unwrapping it and then subtracting this best fit from the phase informationthe resulting phase and amplitude are then converted back to the time domain with the ultimate aim being the compression of the pulses through phase compensationi have attempted to do this in matlab unsuccesfully and have turned to c as a result the forwards fft is working fine i took the basic recipe from numerical recipes in c and used a function to modify it for complex inputs as followingvoid fftcomplex datain complex dataout int fftsize int inversetransform int fftshift double data new double2fftsize3 data0 00 forint i0 ifftsize i datai21 realdataini datai22 imagdataini fft basicdata fftsize inversetransform forint i0 ifftsize i dataouti complexdata2i1 data2i2 swap the fft halfes iftshift1 complex temp new complexfftsize forint i0 ifftsize2 i tempifftsize2 dataouti forint ifftsize2 ifftsize i tempifftsize2 dataouti forint i0 ifftsize i dataouti tempi delete temp delete datawith the function ftt basic taken from numerical recipes cmy issue is that the form of input seems to affect the output of the reverse fft this could be a precision issue but i have looked around and it does not seem to have affected anyone else beforefeeding the output of the forwards fft directly back into the reverse fft yields pulses identical to the intputhowever taking the power output taken asreal2imag2 of the forwards fft and copying it to an array such thatreverse fft inputicomplexrealforwardsoutputiimagforwardsoutputiand then using this as the input for the reverse fft yields the followingand finally taking the output of the forwards fft and copying such thatreverse fft inputicomplex amplitudeicosphasei amplitudeisinphaseiwhere the amplitudeireal2imag205 and phaseiatanimagreal yields the following power output when converting back to the time domainwith a closer look at the pulse structurewhen the first picture yielded nice regular pulses my question is is it the precision of the cos and sin functions which cause the output of the reverse fft to become like this why is it that there is such a massive a difference between the different methods of inputting the complex data and why is it that only when the data is directly fed back into the reverse fft that the data in the time domain is identical to the original input into the forwads fftthank youedit here is the implemenntation of the functions void ttwlmspectralanalysis complex fieldspectrummax fft double powerfftmax fft double dlambda double phaseinfomax fft added 07082012 for inverse fft double fftamplitudemax fft added 07082012 for inverse fft after correction double phasecorrectmax fft added 07082012 for inverse fft after correction double lambdaarraymax fft added 07082012 for inverse fft after correction complex compressedfftmax fft complex correctedoutputmax fft calc the wavelength step size dlambda lambdalambdaconst cdtfftsize calculate the spectrum fftfftfielddata fieldspectrum fftsize forward shift forward fft of the output data fftfielddata into frequency domain get power spectrum forint i0 ifftsize i powerffti normfieldspectrumi phaseinfoi atan2imagfieldspectrumirealfieldspectrumi fftamplitudei sqrtpowerffti added 07082012 for inverse fft after correction added 07082012 for inverse fft after correction this loop subtracts line of best fit from the phase forint i0 ifftsize i lambdaarrayidlambdaifftsize21e2 phasecorrectiphaseinfoi1902e10lambdaarrayi29619 correction from best fit in matlab done manually with phase unwrapping compressedfftifftamplitudeicosphaseinfoifftamplitudeisinphaseinfoi fftcompressedfft correctedoutput fftsize reverse shift reverse fft of corrected phase back to time domain final output is correctedoutputthanks again,['c++'] +332696,javascript variable is undefined first let us see the codevar a0b1documentwriteafunction run documentwriteb var b1runi think the result is 01 but in fact the result is 0undefined then i modify this codevar a0b1documentwriteafunction run documentwritethisb or documentwritewindowb var b1runyeah this time it runs as expected 01 i cannot understand whymore interesting i modify the code again var a0b1documentwriteafunction run documentwriteb var b1 i comment this linerunthe result is 01so can anyone explain thisthanks for share your viewpointsi simplify this code b1function run consolelogb 1twob1function run var b2 consolelogb 2threeb1function run consolelogb undefined var b2,['javascript'] +332697,purpose of clientsettingsproviderserviceuri in appconfig what doesappsettings add keyclientsettingsproviderserviceuri valueappsettingsdosince the value is empty string can i remove the element,['.net'] +332724,list comprehension vs generator expressions weird timeit results i was answering this question i preferred generator expression here and used this which i thought would be faster as generator does not need to create the whole list first lisabcdef d in y for x in lis for y in xtrueand levon used list comprehension in his solution lis abcdef d in j for i in mylist for j in itruebut when i did the timeit results for these lc was faster than generator python m timeit s lisabcdef d in y for x in lis for y in x 10 loops best of 3 236 usec per loop python m timeit s lisabcdef d in y for x in lis for y in x 10 loops best of 3 151 usec per loopthen i increased the size of list and timed it againlisabcdef1234567891012131415161718this time for searching d generator was faster than lc but when i searched a middle element11 and the last element then lc again beats the generator expression and i cannot understand why python m timeit s lisabcdef1234567891012131415161718 d in y for x in lis for y in x 10 loops best of 3 296 usec per loop python m timeit s lisabcdef1234567891012131415161718 d in y for x in lis for y in x 10 loops best of 3 74 usec per loop python m timeit s lisabcdef1234567891012131415161718 11 in y for x in lis for y in x10 loops best of 3 561 usec per loop python m timeit s lisabcdef1234567891012131415161718 11 in y for x in lis for y in x10 loops best of 3 976 usec per loop python m timeit s lisabcdef1234567891012131415161718 18 in y for x in lis for y in x10 loops best of 3 894 usec per loop python m timeit s lisabcdef1234567891012131415161718 18 in y for x in lis for y in x10 loops best of 3 713 usec per loop,['python'] +332746,how to create a visual diff view like stack overflow does stack overflows diff view is very good i want to do this using javascript but i do not know how to start who can give some suggestionsuch as,['javascript'] +332769,idiomatic way of signaling unimplemented methods in c i am building the skeleton for a c app and intend to leave a bunch of methods without implementation returning dummy values i intend to get back to them but do not want to accidentally forget to implement any of themi would like to signal when i reach a method that is not implemented and continue execution with the dummy valuewhats the idiomatic way of doing this,['c#'] +332775,how do i manually autowire a bean with spring i have a bean b which i have to create myself using new b and which has autowire and postconstruct annotationshow do i make spring process these annotations from my bean arelated questionin spring can i autowire new beans from inside an autowired bean,['java'] +332807,what is causing error there is no unique constraint matching given keys for referenced table below example table structure gives an error there is no unique constraint matching given keys for referenced table and having stared at it for while now i cannot figure out why this error arises in this situation begincreate table foo name varchar256 primary keycreate table bar pkey serial primary key foo fk varchar256 not null references fooname name varchar256 not null unique foo fknamecreate table baz pkey serial primary key bar fk varchar256 not null references barname name varchar256commitrunning the above code gives the following error which does not make sense to me can anyone explain why this error arises i am using postgres 91 notice create table primary key will create implicit index foo pkey for table foonotice create table will create implicit sequence bar pkey seq for serial column barpkeynotice create table primary key will create implicit index bar pkey for table barnotice create table unique will create implicit index bar foo fk name key for table barnotice create table will create implicit sequence baz pkey seq for serial column bazpkeynotice create table primary key will create implicit index baz pkey for table bazerror there is no unique constraint matching given keys for referenced table bar error error there is no unique constraint matching given keys for referenced table barsql state 42830,['sql'] +332811,how to find prime numbers between 0 100 in javascript how would i find prime numbers between 0 100 i have thought about it and i am not sure how to find them i thought about doing x x but i found the obvious problem with thatthis is what i have so farbut unfortunately it is the worst code evervar prime function var numfor num 0 num 101 num if num 2 0 break else if num 3 0 break else if num 4 0 break else if num 5 0 break else if num 6 0 break else if num 7 0 break else if num 8 0 break else if num 9 0 break else if num 10 0 break else if num 11 0 break else if num 12 0 break else return num consolelogprime,['javascript'] +332818,text never appears with icons in portrait mode on sherlockactionbar i have a question regarding sherlock actionbar in portrait mode ics does not thisplay text next to menu items in the action bar no matter how much space is available rotating to landscape mode yields the expected behavior icons text if i remove the icon from the menu item it thisplays the text only in portrait mode is it possible to thisplay text icon in portrait mode if space available i use the code below to add menu items into actionbaroverridepublic boolean oncreateoptionsmenumenu menu menuaddmenunone 1 0 postsettitlepostseticonandroidrdrawableic menu savesetshowasactionmenuitemshow as action always menuitemshow as action with text return truethanks in advance,['android'] +332823,difference between call instance vs newobj instance in il i am delving into c in depth and playing with nullable value types just for experimental purposes i wrote a piece of code private static void hownullableworks int test 3 int implicitconversion test nullableint test2 new nullableint3 methodthattakesnullableintnull methodthattakesnullableint39 and i was supprised to see that implicitconversion test2 variables are initialized withcall instance void valuetype mscorlibsystemnullable1int32ctor0instruction whereas when methodthattakesnullableint is called i can seeil 0017 initobj valuetype mscorlibsystemnullable1int32and il 0026 newobj instance void valuetype mscorlibsystemnullable1int32ctor0which i understand i thought that i will see newobj instruction for implicitconversion test2 as well this is full il codemethod private hidebysig static void hownullableworks cil managed code size 50 0x32 maxstack 2 locals init 0 int32 test 1 valuetype mscorlibsystemnullable1int32 implicitconversion 2 valuetype mscorlibsystemnullable1int32 test2 3 valuetype mscorlibsystemnullable1int32 cs0 il 0 nop il 01 ldci43 il 02 stloc0 il 03 ldlocas implicitconversion il 05 ldloc0 il 06 call instance void valuetype mscorlibsystemnullable1int32ctor0 il 0b nop il 0c ldlocas test2 il 0e ldci43 il 0f call instance void valuetype mscorlibsystemnullable1int32ctor0 il 0014 nop il 0015 ldlocas cs0 il 0017 initobj valuetype mscorlibsystemnullable1int32 il 001d ldloc3 il 001e call void csharpindepth 2ndprogrammethodthattakesnullableintvaluetype mscorlibsystemnullable1int32 il 0023 nop il 0024 ldci4s 39 il 0026 newobj instance void valuetype mscorlibsystemnullable1int32ctor0 il 002b call void csharpindepth 2ndprogrammethodthattakesnullableintvaluetype mscorlibsystemnullable1int32 il 0030 nop il 0031 ret end of method programhownullableworks,['c#'] +332826,why does swing draw simple component twice here is simple example of drawing an ovalpublic class swingpainter extends jframe public swingpainter superswing painter setdefaultcloseoperationwindowconstantsexit on close getcontentpaneaddnew myswingcomponent setsize200 200 setvisibletrue public static void mainstring args new swingpainter class myswingcomponent extends jcomponent public void paintcomponentgraphics g systemoutprintlnpaintcomponent superpaintcomponentg gsetcolorcolorred gfilloval10 10 50 50 override protected void paintbordergraphics g systemoutprintlnpaint border superpaintborderg override protected void paintchildrengraphics g systemoutprintlnpaint children superpaintchildreng but in debug mode or adding some info to console before drawing as in example you can see that swing draws components twicepaintcomponentpaint borderpaint childrenpaintcomponentpaint borderpaint childreni cannot understand why it happens but i think it can affect performance in a difficult gui,['java'] +332840,facebook programming challenge mastermind is a game of two players in the beginning first player decides a secret key which is a sequence s1s2sk where 0 si n then second player makes guesses in rounds where each guess is of form g1g2 gk and after each guess first player calculates the score for the guess score for a guess is equal to number of is for which we have gi sifor example if the secret key is 42531 and the guess is 12371then the score is 2 becauseg2 s2 and g5 s5 given a sequence of guesses and scores for each guess your program must decide if there exists at least one secret key that generates those exact scoresinputfirst line of input contains a single integer c 1 c 100 c testcases follow first line of each testcase contains three integers n k and q 1 nk 11 1q8 next q lines contain the guesseseach guess consists of k integers gi1 gi2gik separated by a single space followed by the score for the guess bi 1 gij n for all 1 i q 1 j k and 0 bi k outputfor each testcase output yes without quotes if there exists at least a secret key which generates those exact scores otherwise output nosample input24 4 22 1 2 2 02 2 1 1 14 4 21 2 3 4 44 3 2 1 1sample outputyesnoi am not able to think anything else except brute force ie by generating all the possible keys and checking the respective score for all the guesses the complexity is a very high will do approx 18 operations plz suggest something how to do this in timetime limit 3 sec,['c++'] +332848,cannot call the same static method from identical method from the same class i have this error controller in my codeigniter 210 applicationphpclass error extends ci controller public function construct parent construct public function index set status header404 datamenuitems main menu datatitle 404 error datapageview templates404 thisloadviewtemplatesmain data public function facebook set status header404 datamenuitems main menu datatitle facebook error datapageview templatesfacebook error thisloadviewtemplatesmain data the maincontroller menuphpclass main extends ci controller a lot of methods here public static function menu static menuitems array just a simple array facebook method is totally the same as the index however index works fine facebook throw this messagefatal error class main not found in varwmyapplicationnameapplicationcontrollerserrorphp on line 22how the earth is that possible how can i reach main menu from facebook method,['php'] +332858,create a temporary compressed file i need to create a temporary file to send it i have tried create a temporary file i think it is ok file not seentemporaryfile namedtemporaryfiledeletefalse dircompressed root the path to archive it is okroot dir something create a compressed file it bugsdata openfwritemake archivefname zip root dirread send the file its okresponse httpresponsedata mimetypeapplicationzipresponsecontentthisposition attachment filenames unicodedownloadedassignmentname zipreturn responsei do not know at all if it is the good approach,['python'] +332871,implementing and troubleshooting background audio in ios there are a lot of questions relating to background music playback in ios on stackoverflow none fully explore all edge cases the aim of this question is to be the final word in background audio question on iosdefinitions assumptionsall the code questions and examples refer to ios5background a the state an app is put into when the user presses the home button or the power button so the devices thisplays the lock screen the app can also be put into background using the multitasking switcher or the multitasking gestures on ipadaudio a audio played back using audioqueue including avaudioplayerprerequisitesas i understand it there are 2 requirements to get an app to play audio in the backgroundset uibackgroundmodes to audio in the infoplistavaudiosession sharedinstance setcategoryavaudiosessioncategoryplayback errornilrequirementsmy usecase is playing relatively long audio in the background music there are potentially hundreds of tracks and the app will play them sequentially it can be considered that the audio will play indefinitely the app will handle interruptions by pausing the playbackquestionsi have had mixed success withuiapplication sharedapplication beginbackgroundtaskwithexpirationhandlerallowing audio to play in the background but i am confused as to if its required and how it differs toavaudiosession sharedinstance setcategoryavaudiosessioncategoryplayback errorniledge casesinterruptions if you register to be notified of audio interruptions phone calls etc by becoming the delegate of avaudioplayer for example if you then pause or stop your audio when an interruption starts and resume when it ends is your app suspended if the interruption exceeds 10 minutes max time allowed for background tasks to completethe simulator will stop the audio if lock or home are invoked while usingavaudiosession sharedinstance setcategoryavaudiosessioncategoryplayback errornilhowever this works on a device is this a known issue,['iphone'] +332879,override annotation in eclipse i know there are many people asking the same question and many answering it but none of their answers are helping mei always get override annotation errors if i am anonymously implementing a method from an interface listviewsetonitemclicklistenernew adapterviewonitemclicklistener override this will give error message public void onitemclickadapterview adapterview view view int i long l menu menu mainmenulistmenugeti tabssetcurrenttabmenupos 1 i am developing my android application in a team my team are using idea whilst i am using eclipsemy team never get this error could it be eclipses bugour java version is the same 16my eclipse version is 37the error is multiple markers at this line the method onitemclickadapterview view int long of type new adapterviewonitemclicklistener must override a superclass method implements androidwidgetadapterviewonitemclicklisteneronitemclickcan anyone suggest someting that could be done to remove this erroredit more information i would not get error in this case override public view getviewint position view v viewgroup parent try menu menu menugetlistmenugetposition if menu null catch exception e return v,['android'] +332896,jquery mobile thisplays hidden select element see this select element with thisplaynone in jquery mobile it is thisplayed despite this select id named dataminitrue datanativemenufalse datathemec onchange stylethisplaynone option value1an optinosoptionselecti am trying to showhide jquery mobile select elements dependent on other user actions hence why i am doing the above any ideas,['jquery'] +332898,difference between jcomponentisshowing and isthisplayable whats the difference between componentisshowing and componentisthisplayable i want to use them to decide wheter i should stopstart a timer,['java'] +332926,concurrentdictionary object reading and writing via different threads i want to use a concurrentdictionary in my app but first i need to make sure i understand correctly how it works in my app i will have one or more threads that write to or delete from the dictionary and i will have one or more threads that read from the dictionary potentially all at the same time am i correct that the implementation of concurrentdictionary takes care of all the required locking for this to happen and i do not need to provide my own locking in other words if one thread is writing to or deleting from the dictionary a reading thread or another write thread will be blocked until the update or delete is finishedthanks very much,['c#'] +332952,puts within method in rspec test my file specrbrequire spec helperrequire my filemodule m describe c do it should print everything do c cnew cmethshould something end endendmy filerbmodule m class c puts class text label1 def meth puts method text label2 return something end endend the output isclass textmc should print everythingfinished in 075 seconds1 example 0 failuresand finally the question why was not the label2 method text printed after the test had been runpsruby192 rspec2,['ruby'] +332988,sethomebuttonenabled on preferenceactivity and nested preference i have preference screen extended preferenceactivity for targeting os 403 i wanted to add icon on action bar so i did this in oncreateactionbar actionbar getactionbaractionbarsethomebuttonenabledtrueactionbarsetthisplayhomeasupenabledtrueit worked was added to left of app icon but when i tap the item which goes into the next level more detail screen the would not be thisplayed returning to the top level the appears againi have never thought about a mechanism of nested preference since smart the preferenceactivity hides it now my question is why would not preferenceactivity thisplay the on nested preferencei do not want to argue that i do not need to add to the preference screen even some of googles app add some do not so i think there is no solid rule for thisif there is a simple solution for this i want to solve this issue,['android'] +333026,how to properly learn android testing what are good ways to learn android testingi am interested in learning android testing i do not actually do tdd but write the tests and code togetheri read all the information at and the android application testing guide book and understand the basic concepts but there is almost no information or examples out there that i can findthe book and examples are very basic and showing how to test a pretty simple activity with 2 edittext boxesi need to test more complicated stuff such as intentservice asynctask resultreceiver etc i am interested in building my apps in a tdd or almost tdd wayis there any way i can learn those things books blogs examples or android testing is something very uncommon,['android'] +333073,nexus 7 not visible over usb via adb devices from windows 7 x64 i have done the obvious the usb driver was installed from the latest android sdk and usb debugging was turned on in the tabletwhen the nexus 7 is connected the device shows up in the windows device manager as android phone android composite adb device with the properties showing driver version 60 so the correct driver is installed and workingthis also proves the device is in usb debugging mode because if it is not it shows up in windows under portable devices nexus 7the problem is that adb devices shows no devices and eclipse also not surprisingly also does not offer the nexus 7 as a hardware device to run an app oni have rebooted both devices without effectthe only debugging i can figure out is enable adb traceall but this tells me nothingmkhmule appdatalocalandroidandroidsdkplatformtools export adb traceallmkhmule appdatalocalandroidandroidsdkplatformtools adb devicessystemcoreadbadbcmainhandling commandlinesystemcoreadbadb clientcadb queryadb query hostdevicessystemcoreadbadb clientc adb connect adb connect hostversionsystemcoreadbsysdeps win32csocket loopback clientsocket loopback client port 5037 type tcp fd 100systemcoreadbtransportcwritexwritex fd100 len4 30303063 0csystemcoreadbtransportcwritexwritex fd100 len12 686f73743a76657273696f6e hostversionsystemcoreadbtransportcreadxreadx fd100 wanted4systemcoreadbtransportcreadxreadx fd100 wanted4 got44f4b4159 okaysystemcoreadbadb clientc adb connect adb connect return fd 100systemcoreadbadb clientcadb connectadb connect service hostdevicessystemcoreadbtransportcreadxreadx fd100 wanted4systemcoreadbtransportcreadxreadx fd100 wanted4 got430303034 04systemcoreadbtransportcreadxreadx fd100 wanted4systemcoreadbtransportcreadxreadx fd100 wanted4 got430303164 001dsystemcoreadbsysdeps win32cadb closeadb close 100loclient5037systemcoreadbadb clientc adb connect adb connect hostdevicessystemcoreadbsysdeps win32csocket loopback clientsocket loopback client port 5037 type tcp fd 101systemcoreadbtransportcwritexwritex fd101 len4 30303063 0csystemcoreadbtransportcwritexwritex fd101 len12 686f73743a64657669636573 hostdevicessystemcoreadbtransportcreadxreadx fd101 wanted4systemcoreadbtransportcreadxreadx fd101 wanted4 got44f4b4159 okaysystemcoreadbadb clientc adb connect adb connect return fd 101systemcoreadbadb clientcadb connectadb connect return fd 101systemcoreadbtransportcreadxreadx fd101 wanted4systemcoreadbtransportcreadxreadx fd101 wanted4 got430303030 0systemcoreadbtransportcreadxreadx fd101 wanted0systemcoreadbtransportcreadxreadx fd101 wanted0 got0systemcoreadbsysdeps win32cadb closeadb close 101loclient5037list of devices attachednothing shownwhat am i doing wrong,['android'] +333090,why hidden input is affecting my layout lf explanation i needed to use an hidden input to transfer some ids to the page for each block whateveri have the following code div idshipping box classformsep well div iddefault shipping box clashipping box rowfluid div claspan1 input typehidden nametracking id value div divdivthis code work well and the result is what i expected if i do this div idshipping box classformsep well div iddefault shipping box clashipping box rowfluid input typehidden nametracking id value div claspan1 div divdivthe layout is not respected see this picture for the demostration can someone explain why to me hidden input are not suppose to be hidden so they should not affect the layout jsfiddle near line 285,"['php', 'html', 'css']" +333192,android device chooser shows red x in target column i have recently built an android app with a minsdkversion of 7 and targetsdkversion of 10 i am now making the app tablet compatible and adding action bars so i updated by targetsdkversion to 15 and in my project properties moved my project build tarket to android 403 api 15 i also doublechecked that my java compiler is 16without making any other changes to my code i try to run my app and in the android device chooser my two physical devices versions 234 and 31 both have a red x in the target column instead of the green check marki am also working with the actionbarcompat sample app and a sample app from actionbarsherlock and when i run one of those apps both of my devices show a green check mark both of these sample apps have their project build target set to 403 and the same sdkversion settings that i have in my app as far as i can tell my app is setup the same as the others why does my app then have a red x next to my device versions in the target columnthanks,['android'] +333206,understanding the validatorunobtrusiveadaptersaddbool method i am trying to understand somethingfrom this blogpost bridging html and jquery validate adapterswriting a clientside validator involves two steps writing the validator for jquery validate and writing the adapter which takes the parameter values from the html attributes and turns it into jquery validate metadata the former topic is not in the scope of this blog post since itas really not mvc specificthere is an adapter collection available at jqueryvalidatorunobtrusiveadapters hanging off the adapter collection is the adapter registration method add and three helpers that can be used to register very common types of adapters addbool addsingleval and addminmaxnotice that it says two stepsbut if you take a look at this post mvc3 make checkbox required via jquery validate you only need the second step writing the adapter for the validation to work by adding this line of codevalidatorunobtrusiveadaptersaddboolmandatory requiredi tested out the code in a new mvc 4 internet app and it works fine heres the supersimple sample view modelpublic class simpleviewmodel mandatoryerrormessage you must agree to the terms to register thisplayname terms accepted public bool istermsaccepted get set validation attributepublic class mandatoryattribute validationattribute iclientvalidatable public override bool isvalidobject value return value is bool boolvalue public ienumerablemodelclientvalidationrule getclientvalidationrulesmodelmetadata metadata controllercontext context modelclientvalidationrule rule new modelclientvalidationrule ruleerrormessage formaterrormessagemetadatagetthisplayname rulevalidationtype mandatory yield return rule viewmodel mvcapplication2modelssimpleviewmodel viewbagtitle using htmlbeginform htmlvalidationsummary htmlcheckboxformodel modelistermsaccepted htmlvalidationmessageformodel modelistermsaccepted input typesubmit valuesend section scripts scriptsrenderbundlesjqueryval script typetextjavascript validatorunobtrusiveadaptersaddboolmandatory required scriptso basically i have got three questionsis validatorunobtrusiveadaptersaddboolmandatory required really the only thing you need besides writing an attribute classwhat exactly does it do behind the sceneswhere can i find good documentation about addbool,['jquery'] +333300,how to lose the focus of a edittext when done button in the soft keyboard is pressed i have 7 edittext boxes in my xml i am using the onfocuschangelistener to read the value from edittext and i am using that value for my calculationi want to make my edittext to lose its focus when i click on the done button in the soft keyboardso that i can get the value in the edittext,['android'] +333322,use keywordword in rubyrailsrack code recently i happened to see this word in ruby code use when i was going through some code related to goliath middleware etc looks like it is different from includeextend and requirecan somebody explain why this use keyword exists and how it is different from includerequire how does it work when to use it,"['ruby-on-rails', 'ruby']" +333392,how to sort a datagrid using stable sorting i have got a wpf datagrid and i have got it so that you can sort it by clicking on the column headers it works but it is unstable how do i make it do stable sortingby this i mean if i have this tableclass student gradeart james aart amy bart charlie ascience james dscience amy ascience charlie chistory james bhistory amy ahistory charlie cif i sort by student it works like youd expectclass student gradeart amy bscience amy ahistory amy aart charlie ascience charlie chistory charlie cart james ascience james dhistory james bbut if i now sort by classclass student gradeart james aart amy bart charlie ahistory james bhistory amy ahistory charlie cscience james dscience amy ascience charlie cit is destroyed the sort order of the students unstable sorting what i want is stable sorting where it preserves the orderclass student gradeart amy bart charlie aart james ahistory amy ahistory charlie chistory james bscience amy ascience charlie cscience james dseems like it should work like this by default or at least be a toggle does anyone have any suggestions eiriks idea of shiftclicking works and that shows that the behaviour is present however what i would really like is for to work like that without any modifiers it should not be a cause of sort by this then this then this it should be case of swapping the algorithm for a different onesee this algorithmstability,['c#'] +333424,should i use the same csr for both devproduction ios push notification cert updatedi found that i can submit the same csr for both dev and production when creating certs for ios push notificationfor a single app i need to create 2 certs devproduction so for 10 app i need to create 20 certs which is a nightmare for certs management and pollute my keychains so i am thinking by submitting the same csr hence same private keyjust more easy to maintain the stuffs i want to know if any drawbacks and are you also doing the same way to reduce the effort in keyscerts management,"['iphone', 'objective-c', 'ios']" +333430,nodejs read and write file lines i tried to read a file line by line and output it to another file using nodejsmy problem is the sequence of lines sometimes messed up due to async nature of nodejseg my input file is likeline 1line 2line 3but output file could be likeline 1line 3line 2below is my codevar fs requirefsvar index 1fsreadfilesyncinputtxttostringsplitnforeachfunction line consolelogline fsopenoutputtxt a 06 functionerr fd fswritesyncfd linetostring n null undefined functionerr written any thoughts would be appreciated thanks,['javascript'] +333462,java code changeset in liquibase is there a way in liquibase to create java code change set ie provide a java class which will receive a jdbc connection and will perform some changes in the database i know that flyway has such feature,['java'] +333469,android syntax highlighting does anyone know of syntax highlighting libraries which work on android i have looked at jsyntaxpane but that does not seem to support android,['android'] +333541,are java classes objects i have read before that java classes are instances of the class class but now my computer science teacher says that java classes are not objects which is true,['java'] +333574,interacting with a coin changer using com port i have a coin changer mei cashflow e7900 and an mdb adapter to connect the device to a serial port the shop which sold me the adapter also provided a test application which is written in delphi compiled with borland delphi v60 it works perfectly but my code for some reason does notwhen you use mdb you have to send poll command every 200ms if everything is ok the coin changer sends ack when i send it using delphi application the session looks like this 0x0b 0x0b the star character means parity set to mark by default parity is space 0x00so everything is ok that is what i am expecting when i send poll with the c application it is like 0x0b 0x0b 0x3f 0x00sometimes the coin changer sends me 0x3f 0x11 after poll which makes no sense there is no any valid response like this when i get such a response i run the delphi application and it gets a valid ack response i was using a com port sniffer to make sure that there is no any difference in the data sent including the port configuration itself and i keep getting different responsehere goes the source code for the test application delphithe component used it called bcomportform1bcomport1baudratebr9600form1bcomport1paritypaspaceform1bcomport1portport name goes hereform1bcomport1openprocedure setmodebitmodebitbooleanbeginif modebit then begin form1bcomport1beginupdate form1bcomport1paritypamark form1bcomport1endupdateend else begin form1bcomport1beginupdate form1bcomport1paritypaspace form1bcomport1endupdate endprocedure tform1polltimersender tobjectvar sbufbuf2string ileninteger xadrdat1ackchkbyte crcintegeradr08 or 0bsetmodebittrueform1bcomport1writeadr1dat10crcadr dat1try sinttohexcrc10 sslengths1slengths chkstrtointsexceptendsetmodebitfalseform1bcomport1writechk1full code listing available here but the code provided here should be enough my code c private const byte p address 0x8 static void mainstring args port new serialportportsindex portbaudrate 9600 portstopbits stopbitsone portdatabits 8 portdtrenable true portrtsenable true portparity parityspace private static void ondatareceivedobject sender serialdatareceivedeventargs e byte datareceived new byteportbytestoread setmodebitfalse portreaddatareceived 0 datareceivedlength consolewritelinedata received foreach byte b in datareceived consolewritebtostringx consolewriteline private static void setmodebitboolean mode portparity mode paritymark parityspace private static void senddatabyte cmd byte data byte adr bytep address cmd byte crc adr foreach var b in data crc b setmodebittrue portwritenew byte adr 0 1 setmodebitfalse if datalength 0 portwritedata 0 datalength portwritenew byte crc 0 1 poll command with the delphi application17082012 180518 com8 capture started17082012 180538 com8 opened by process id287217082012 180538 baud rate 960017082012 180538 rts signal true17082012 180538 dtr signal true17082012 180538 line control change space8117082012 180538 baud rate 960017082012 180538 rts signal true17082012 180538 dtr signal true17082012 180538 line control change mark8117082012 180538 write 1 bytes 0b 17082012 180538 baud rate 960017082012 180538 rts signal true17082012 180538 dtr signal true17082012 180538 line control change space8117082012 180538 write 1 bytes 0b 17082012 180538 getcommstatus result1617082012 180538 parity error true17082012 180538 baud rate 960017082012 180538 rts signal true17082012 180538 dtr signal true17082012 180538 line control change space8117082012 180538 read 1 bytes00 poll command with my application17082012 181208 com8 capture started17082012 181211 com8 opened by process id316417082012 181211 baud rate 960017082012 181211 rts signal true17082012 181211 dtr signal false17082012 181211 line control change space8117082012 181211 baud rate 960017082012 181211 rts signal true17082012 181211 dtr signal true17082012 181211 line control change space8117082012 181211 dtr signal true17082012 181211 baud rate 960017082012 181211 rts signal true17082012 181211 dtr signal true17082012 181211 line control change mark8117082012 181211 write 1 bytes 0b 17082012 181211 baud rate 960017082012 181211 rts signal true17082012 181211 dtr signal true17082012 181211 line control change space8117082012 181211 write 1 bytes 0b 17082012 181211 getcommstatus result1617082012 181211 parity error true17082012 181211 read 1 bytes3f 17082012 181211 read 1 bytes00 the data received seems to be almost the same except 0x3f in the beginning but the device behaviour is different too it does not seem to be connected to the pc it says thisabled by machine when i use c application and status ok when i use delphi application may this be happening because of the net framework any names of libraries for com port interaction are appretiatedi have idea why i get different response may be i hope someone here would help me thanks in advance also thanks for reading this huge question,['c#'] +333601,nokogiri text node contents is there any clean way to get the contents of text nodes with nokogiri right now i am usingsome nodeat xpath whatever firstcontentwhich seems really verbose for just getting text,['ruby'] +333602,how many runs of java program do we need to warmup the jvm suppose i have a java program testclass i want to measure its execution time i wrote a wrapper to do this as belowclass runtest public static void mainstring args long sum 0 int iterations 20 int warmupnum 10 forint i0 iiterations i long start systemnanotime testmainargs long end systemnanotime if i warmupnum sum end start systemoutprintlnave sumiterationswarmupnum here how to choose warmupnum the larger the better how large is enough is this a standardcommon way to measure java programs performance,['java'] +333619,php concatenation of strings and arithmetic operations i started learning php not too long ago and i ran into this issuephpa 1b 2echo a b a becho br echo a b a becho br echo a b a becho br echo a b a becho br i get the following output1 2 21 2 0531the last two lines in the output are not what i would expectwhy is this how are these expressions evaluated i am trying to get a better understanding of the language,['php'] +333621,truly custom font in tkinter i am making an interface in tkinter and i need to have custom fonts not just say helvetica at a certain size or whatever but fonts other than what would normally be available on any given platform this would be something that would be kept with the program as an image file or preferably truetype font file or similar i do not want to have to install the desired fonts on every machine that is going to use the program i just want to carry them around with the program in the same directorythe tkfont module looks like it ought to do something like this but i cannot see where it would take a filename for a font not normally accessible to the system running the program thanks in advance for your help,['python'] +333660,fix 3gp file after streaming from android media recorder i am trying to stream video from android camera through local unix socket and write file from stream to sdcard everything works fine except file is not playable with any player it is because android not filling some gaps in the file because socket is not seekable as i understand i need to make some modifications after video stream is over i read several articles here here and here but none of them helped me i am playing with hex editor to learn how to do it manually so afterwards it will be trivial to do the same in the android codehere is sample file that saved from stream not playable3gpcan anyone fix to make it playable and tell how he done itedit i erase header of the 3gp file and write new one as follows00 00 00 18 66 74 79 70 33 67 70 34 00 00 03 00 33 67 70 34 33 67 70 36 00 00 00 00then i find starting location of mdat and moov atoms with following commandgrep aobe ftypmdatmoov sample not playable3gpand it gives me following output4ftyp28mdat1414676moovthen make 1414676 28 1414648 0x1595f8then i write 0x1595f8 as 2528 bytes just prior mdat atom so my header now looks like this00 00 00 18 66 74 79 70 33 67 70 34 00 00 03 00 33 67 70 34 33 67 70 36 00 15 95 f8and when i try to play it with mplayer i get some damaged video and audio output heres some part from mplayer outputamrwb 0x7f72ad652380frame too small 33 bytes truncated fileamrwb 0x7f72ad652380encountered a bad or corrupted frameamrwb 0x7f72ad652380encountered a bad or corrupted frameamrwb 0x7f72ad652380frame too small 33 bytes truncated fileamrwb 0x7f72ad652380encountered a bad or corrupted frameamrwb 0x7f72ad652380encountered a bad or corrupted frameamrwb 0x7f72ad652380encountered a bad or corrupted framea 110 v 14 av 9650 ct 0023 0 0 10 1 16 0 0 movmp4m4a3gp3g2mj2 0x7f72adeafc40stream 1 offset 0x15e62b partial fileh263 0x7f72ad652380bad picture start codeh263 0x7f72ad652380header damagederror while decoding frameh263 0x7f72ad652380bad picture start codeh263 0x7f72ad652380header damagederror while decoding frameh263 0x7f72ad652380bad picture start codeh263 0x7f72ad652380header damagederror while decoding framea 1 v 15 av 9558 ct 0027 0 0 9 1 14 0 0 h263 0x7f72ad652380bad picture start codeh263 0x7f72ad652380header damagederror while decoding framewhat i am doing wrong,['android'] +333666,c get process output while running is there anyway to redirect standard output of a spawned process and capture it as its happening everything i have seen just does a readtoend after the process has finished i would like to be able to get the output as it is being printededit private void converttompeg start the child process process p new process redirect the output stream of the child process pstartinfouseshellexecute false pstartinforedirectstandardoutput true setup filename and arguments pstartinfoarguments stringformaty i 0 target ntscdvd sameq s 720x480 1 tempdir outavi tempdir outmpg pstartinfofilename ffmpegexe handle data received poutputdatareceived new datareceivedeventhandlerp outputdatareceived pstart void p outputdatareceivedobject sender datareceivedeventargs e debugwritelineedata,['c#'] +333671,parse time of format hhmmss how can i parse a time of format hhmmss inputted as a string to obtain only the integer values ignoring the colons in java,['java'] +333685,why is the constructor of a generic class with a defaultvalued enum parameter not able to call protected methods of that class a simple test caseusing systempublic class testt public enum testenum a b public test testenum a testenuma dosomething protected void dosomething the compiler this is using mono in a unity3d project net40 target gives an error on the call in test to dosomething if i remove the default parameter on testenum a it builds just fine monodevelop wants to call the default parameter testenuma but that does not compile neither does testenumta obviously i wouldnt have expected these to work but using monodevelops autocomplete that is what i getedit the specific error is the name dosomething does not exists in the current context,['c#'] +333686,error webviewdestroy called while still attached i am getting this error when the device changes orientationerror webviewdestroy called while still attachedwith this codeprotected void ondestroy if adview null adviewdestroy what is the reason for this how do i avoid this error,['android'] +333747,how to compress json with gzip in rails for android i am running rails 327 with ruby 193p194 to output json data from an sqlite database render json resultto jsonan android application consumes the json file which gets loaded via httpgethttpclient httpclient new defaulthttpclienthttpget httpget new httpgeturlpathhttpresponse response httpclientexecutehttpgethttpentity entity responsegetentitystring result entityutilstostringentity httputf 8jsonobject jsonobject new jsonobjectresultplatform supporti read in the api that rails offers gzip support as followsactivesupportgzipcompressresulti also guess from http11 rfc2626 section 143 that i can configure the header of a http requesthttppostsetheaderacceptencoding gzipi also found the information quite interesting that are contained in section 35 content codingsall contentcoding values are caseinsensitivehttp11 uses contentcoding values in the acceptencoding section 143 and contentencoding section 1411 header fieldsthe internet assigned numbers authority iana acts as a registry for contentcoding value tokens initially the registry contains the following tokens gzip an encoding format produced by the file compression program gzip gnu zip as described in rfc 1952 25this post further explains how to handle gzip encoded content with androidserver testingthus i have no clue how i can find out if the data has been compressed by the serverto test whether rails outputs gzip i tried to use curl as suggested here curl head h acceptencoding gzip httplocalhost30postsjsonthe output however does not reveal to me whether gzip is supported or nothttp11 200 ok contenttype applicationjson charsetutf8xuacompatible ieedgeetag f6f6732c747466f75052f88b1eff393bcachecontrol maxage0 private mustrevalidatexrequestid 74ee0562c05adea679deb701f1b8fd88xruntime 04205contentlength 0server webrick131 ruby19320120420date thu 16 aug 2012 2325 gmtconnection keepalivei also tried the compressed parameter of curl curl compressed head h acceptencoding gzip httplocalhost30postsjsonwhich outputs the same header information as the previous command when i run curl compressed h acceptencoding gzip httplocalhost30postsjsonthe json data is printed to the console as readable text i cannot see if compression has happened maybe because curl already decompresses the responseonline testingi also tried the online test http compression test mentioned here it confirmed that the json content is not gzipped the second website gidziptest linked here acknowledged the negative test resultquestionshow can i output gzip compressed json from railshow do i configure the http client to request gzip compressed datadoes the same configuration still work when i run the rails server on heroku postgresql lessons learnedas i learned all i have to configure for the rest server is use rackdeflater to be clear i do not use activesupportgzipcompress in my code in case someone is interested this is what the header looks like when gzip compression is enabledhttp11 200 ok contenttype applicationjson charsetutf8xuacompatible ieedgeetag 8170a04be41673bf25824256740a9460cachecontrol maxage0 private mustrevalidatexrequestid 700b9536f6a20164d31b8528bde423afxruntime 0369337vary acceptencodingcontentencoding gzipserver webrick131 ruby19320120420date tue 21 aug 2012 121048 gmtcontentlength 20connection keepalivenow that i know the magic keyword it is easy to search and find articles on use rackdeflater,['android'] +333749,delegatinghandler not executing aspnet web api today i encountered a strange behavior in my web api applicationprotected void application start filterconfigregisterglobalfiltersglobalfiltersfilters routeconfigregisterroutesroutetableroutes globalconfigurationconfiguration messagehandlersaddnew dummymessagehandlerand my delegatinghandler looks like thispublic class dummymessagehandler delegatinghandler protected override taskhttpresponsemessage sendasync httprequestmessage request cancellationtoken cancellationtoken if requestheadersauthorizationscheme basic threadcurrentprincipal new genericprincipal new genericidentityauthenticated new string0 return basesendasyncrequest cancellationtoken the problem i encountered was that the delegating handlers are not being executed i have a breakpoint in the line marked with a and the execution of my code never stops theremy nuget packagesconfig is the followingxml version10 encodingutf8packages package idmicrosoftaspnetmvc version40207100 targetframeworknet40 package idmicrosoftaspnetrazor version20207100 targetframeworknet40 package idmicrosoftaspnetweboptimization version100 targetframeworknet40 package idmicrosoftaspnetwebapi version40207100 targetframeworknet40 package idmicrosoftaspnetwebapiclient version410alpha120809 targetframeworknet40 package idmicrosoftaspnetwebapicore version40207100 targetframeworknet40 package idmicrosoftaspnetwebapiwebhost version40207100 targetframeworknet40 package idmicrosoftaspnetwebpages version20207100 targetframeworknet40 package idmicrosoftnethttp version20207100 targetframeworknet40 package idmicrosoftwebinfrastructure version10 targetframeworknet40 package idnewtonsoftjson version458 targetframeworknet40 package idwebgrease version110 targetframeworknet40 packagesi am looking at this for a long time can you point me to something i am missing thank you,"['c#', 'asp.net']" +333756,why is 0 0 true in javascript in a recent post on an author writes following without explanation which happens to be true0 0 returns truemy understanding about operator is it returns true if operands point to same objectalso operator returns a reference to negative value of operand with this rule 0 and 0 should not be the sameso why is 0 0,['javascript'] +333792,get combobox value in java swing i need to get the integer value of the combobox in swingi have set an integer value as id for the comboboxi tried comboboxgetselecteditem and comboboxgetselectedindex but it cant get the int valuebelow is my codecommonbean commonbeannew commonbeancommonresponsegetcommonbeanlength1 forint i0icommonresponsegetcommonbeanlengthi commonbeani new commonbeanplease select a project 0 commonbeani1 new commonbeancommonresponsegetcommonbeanigetprojectname commonresponsegetcommonbeanigetprojectid jcombobox combobox new jcomboboxcommonbeanpublic commonbeanstring projectnameint projectid thisprojectname projectname thisprojectid projectid any help is appreciated,['java'] +333831,include opencv in android application package i need to work on detecting edges from an image i am using canny algorithm for thatsince opencv for android is available 242 while i am trying to run examples it saysopencv manager is not installed please try to install it after install it from the market it is working finebut if i want the users to install my application so that they do not have to install another apk for using my application how to use opencv without without asking for another application ie manger should be pre installed is there any way i can use canny algorithm for edge detection without opencv any good angorithm tutorials for implementing in in android,['android'] +333839,android activity has leaked window comandroidinternalpolicyimplphonewindowdecorview issue i am working with android application to show network error neterrorpagejavapackage expappimport androidappactivityimport androidappalertdialogimport androidcontentcontextimport androidcontentdialoginterfaceimport androidcontentintentimport androidnetconnectivitymanagerimport androidnetnetworkinfoimport androidosbundleimport androidviewkeyeventimport androidviewviewimport androidviewviewonclicklistenerimport androidwidgetbuttonpublic class neterrorpage extends activity implements onclicklistener override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutneterrorlayout button reloadbuttonfindviewbyidridbtnreload reloadsetonclicklistenerthis showinfomessagedialogplease check your network connectionnetwork alert public void onclickview arg0 ifisnetworkavailable intent myintent new intentactivityneterrorpagethis mainactivityclass myintentaddflagsintentflag activity clear top activityneterrorpagethisstartactivitymyintent finish else showinfomessagedialogplease check your network connectionnetwork alert public void showinfomessagedialogstring messagestring title alertdialog alertdialog new alertdialogbuilderneterrorpagethiscreate alertdialogsettitlenetwork alert alertdialogsetmessagemessage alertdialogsetbuttonok new dialoginterfaceonclicklistener public void onclickdialoginterface dialogint which dialogcancel alertdialogshow private boolean isnetworkavailable networkinfo activenetwork suppresswarningsunused string isnetworkconnected suppresswarningsunused string connectiontype connectivitymanager connectivitymanager connectivitymanagerconnectivitymanagergetsystemservicecontextconnectivity service try activenetworkconnectivitymanagergetactivenetworkinfo connectiontypeactivenetworkgettypename isnetworkconnectedstringvalueofactivenetworkgetstate return true catchexception error return false but i am getting the error as below0817 115908019 ewindowmanager16460 activity expappneterrorpage has leaked window comandroidinternalpolicyimplphonewindowdecorview40534a18 that was originally added here0817 115908019 ewindowmanager16460 androidviewwindowleaked activity expappneterrorpage has leaked window comandroidinternalpolicyimplphonewindowdecorview40534a18 that was originally added here0817 115908019 ewindowmanager16460 at androidviewviewrootinitviewrootjava2630817 115908019 ewindowmanager16460 at androidviewwindowmanagerimpladdviewwindowmanagerimpljava1480817 115908019 ewindowmanager16460 at androidviewwindowmanagerimpladdviewwindowmanagerimpljava910817 115908019 ewindowmanager16460 at androidviewwindowlocalwindowmanageraddviewwindowjava4240817 115908019 ewindowmanager16460 at androidappdialogshowdialogjava2410817 115908019 ewindowmanager16460 at syncdirecttracneterrorshowinfomessagedialogneterrorpagejava1140817 115908019 ewindowmanager16460 at syncdirecttracneterroroncreateneterrorpagejava260817 115908019 ewindowmanager16460 at androidappinstrumentationcallactivityoncreateinstrumentationjava10470817 115908019 ewindowmanager16460 at androidappactivitythreadperformlaunchactivityactivitythreadjava16150817 115908019 ewindowmanager16460 at androidappactivitythreadhandlelaunchactivityactivitythreadjava16670817 115908019 ewindowmanager16460 at androidappactivitythreadaccess1500activitythreadjava1170817 115908019 ewindowmanager16460 at androidappactivitythreadhhandlemessageactivitythreadjava9350817 115908019 ewindowmanager16460 at androidoshandlerthispatchmessagehandlerjava990817 115908019 ewindowmanager16460 at androidoslooperlooplooperjava1300817 115908019 ewindowmanager16460 at androidappactivitythreadmainactivitythreadjava36870817 115908019 ewindowmanager16460 at javalangreflectmethodinvokenativenative method0817 115908019 ewindowmanager16460 at javalangreflectmethodinvokemethodjava5070817 115908019 ewindowmanager16460 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava8670817 115908019 ewindowmanager16460 at comandroidinternaloszygoteinitmainzygoteinitjava6250817 115908019 ewindowmanager16460 at dalviksystemnativestartmainnative methodi have searched more but i do not have any right idea to clear thiswhat i want is when loading this page layout should be added and dialog should be shownplease help me to clear this errornote i have tried this alsooverride protected void onresume superonresume runonuithreadnew runnable public void run showinfomessagedialogplease check your network connectionnetwork alert,['android'] +333855,what is the reason behind cbegincend i wonder why cbegin and cend were introduced in c11 what are cases when calling these methods makes a difference from const overloads of begin and end,['c++'] +333881,what is system out println in systemoutprintln in java possible duplicatewhats the meaning of systemoutprintln in java i was looking for the answer of what system out and println are in systemoutprintln in the java i searched and found a different answer like thesesystem is a builtin class present in javalang package this class has a final modifier which means that it cannot be inherited by other classes it contains predefined methods and fields which provides facilities like standard input output etcout is a static final field ie variablein system class which is of the type printstream a builtin class contains methods to print the different data values static fields and methods must be accessed by using the class name so systemout out here denotes the reference variable of the type printstream classprintln is a public method in printstream class to print the data values hence to access a method in printstream class we use outprintln as non static methods and fields can only be accessed by using the refrence varialblein another page i find another contrasting definition as systemoutprint is a standard output function used in java where system specifies the package name out specifies the class name and print is a function in that classi am confused by these could anybody please exactly tell me what they are,['java'] +333884,manually specify the value of a primary key in jpa generatedvalue column i am having an entity which has a primary key id field like the followingidgeneratedvaluestrategy generationtypeidentityprivate long idthis works well i am using eclipselink to create the ddlschema and the column is correctly created like soid bigint20 not null auto incrementhowever i have got several entities for which i do want to specify the pk myself it is a little application that transfers data from an old database to the new one were building if i specify the id for the pojo using setidlong id and persist it eclipselink does not save it ie the record is saved but the id is auto generated by eclipselinkis there a way to manually specify the value of a column which has a generatedvalue here some thoughts on the issuei tried to work around the problem by not using generatedvalue at all but simply manually define the column to be auto incremented however this forces me to manually provide an ids always since eclipselink validates the primary key so it may not be null zero or a negative number the exception message reads that i should specify eclipselinkid validation however this does not seem to make any difference i annotated primarykeyvalidation idvalidationnone but still got the same messageto clarify i am using eclipselink 240 as persistence provider and i cannot switch away from it large portions of the project depend on eclipselink specific query hints annotations and classesedit in response to the answerscustom sequencing i tried to implement my own sequencing i tried subclassing defaultsequence but eclipselink will tell me internal exception orgeclipsepersistenceplatformdatabasemysqlplatform could not be found but i have checked the class is on the classpathso i subclassed another class nativesequencepublic class mynativesequence extends nativesequence public mynativesequence super public mynativesequencefinal string name supername override public boolean shouldalwaysoverrideexistingvalue return false override public boolean shouldalwaysoverrideexistingvaluefinal string seqname return false however what i get is the followingjavaxpersistencerollbackexception exception eclipselink7197 eclipse persistence services 240v20120608r11652 orgeclipsepersistenceexceptionsvalidationexceptionexception description null or zero primary key encountered in unit of work clone dedfvdatenbankdomainmitarbeiter idnull primary key null set descriptors idvalidation or the eclipselinkidvalidation property at orgeclipsepersistenceinternaljpatransactionentitytransactionimplcommitinternalentitytransactionimpljava102 caused by exception eclipselink7197 eclipse persistence services 240v20120608r11652 orgeclipsepersistenceexceptionsvalidationexceptionexception description null or zero primary key encountered in unit of work clone dedfvdatenbankdomainmitarbeiter idnull primary key null set descriptors idvalidation or the eclipselinkidvalidation property at orgeclipsepersistenceexceptionsvalidationexceptionnullprimarykeyinunitofworkclonevalidationexceptionjava1451 stack trace shortened for clarity this is the same message which i got before should not i subclass nativesequence if so i do not know what to implement for the abstract methods in sequence or standardsequenceit may also be worth noting that simply subclassing without overriding any methods the class works as expected however returing false in shouldalwaysoverrideexistingvalue will not generate a single value at all i stepped through the program and getgeneratedvalue is not called oncealso when i insert like 8 entities of a certain kind within a transaction it resulted in 11 records in the database what the helledit 20120901 i still do not have a solution for the problem implementing my own sequence did not solve it what i need is a way to be able to not set an id explicitly so it will be auto generated and to be able to set an id explicitly so it will be used for the creation of the record in the databasei tried to define the column as auto increment myself and ommit generatedvalue however validation will kick in and not allow me to save such an entity if i specify a value 0 and zero mysql will complain for a duplicate primary keyi am running out of ideas and options to try any starting a bounty,"['java', 'mysql']" +333890,how to interrupt an infinite loop though i know it will be a bit silly to ask still i want to inquire more about the technical perspective of ita simple example of an infinite looppublic class loopinfinite public static void mainstring args for systemoutprintlnstack overflow how can i interrupt stop this infinite loop from outside of this class eg with the help of inheritance,['java'] +333946,how to run background process on the ios using private apis to sync email items without jailbreaking the phone i am working on an enterprise application which is similar to contacts calendar i would like to sync my calendar and contact even when my application is in background i am good to use private apis also as i am not going to submit to the app store note here is i wanted to make this work without jailbreaking the deviceaalready a similar question posted here i am creating this new thread since the already posted one has a solution suggested for jailbreaked device,"['iphone', 'ios']" +333950,zend framework 2 notempty validator message i am having a form with an element username there are two validators notempty and stringlength the custom error messages for stringlength are working but somehow it does not use the custom error message for the notempty validator in zf1 the notempty validator was added automatically when making an element required which could be turned off i cannot find such an option in zf2 and maybe my notempty validator is not used because it was already added by the required flag inputfilteraddfactorycreateinputarray name username required true filters array array name stringtrim validators array array name notempty options array messages array notemptyis empty bitte geben sie ihren benutzernamen ein array name stringlength options array min 3 max 45 messages array stringlengthtoo short der benutzername muss mindestens 3 zeichene lang sein stringlengthtoo long der benutzername darf maximal 45 zeichen lang sein,['php'] +333990,javascript c binding i have some c code that i want to expose to client side of a web app ideally i want to write javascript wrapper objects for my c classes so that i can use them clientsidehas this been done before does anyone have a link to show how this may be achieved,"['javascript', 'c++']" +333998,how to receive a file via http put with php this is something that has been bugging me for a while i am building of a restful api that has to receive files on some occasionswhen using http post we can read data from post and files from fileswhen using http get we can read data from get and files from fileshowever when using http put afaik the only way to read data is to use the phpinput streamall good and well untill i want to send a file over http put now the phpinput stream does not work as expected anymore since it has a file in there as wellheres how i currently read data on a put requestwhich works great as long as there are no files postedhandle fopenphpinput rrawdata while chunk freadhandle 1024 rawdata chunkparse strrawdata datawhen i then output rawdata it showszendhttpclient44cf242ea3173cfa0b97f80c68608c4ccontentthisposition formdata nameimage 01 filenameloremipsumpngcontenttype imagepng charsetbinaryi12pngi12i12i12etc etci12i12i12zendhttpclient8e4c65a6678d3ef287a07eb1da6a5380contentthisposition formdata nametestkeytestvaluezendhttpclient8e4c65a6678d3ef287a07eb1da6a5380contentthisposition formdata nameotherkeyothervaluedoes anyone know how to properly receive files over http put or how to parse files out of the phpinput stream update 1 i have tried only the above method do not really have a clue as to what i can do elsei have gotten no errors using this method besides that i do not get the desired result of the posted data and files update 2 i am sending this test request using zend http client as followshave not had any problems with zend http client so farclient new zend http clientclientsetconfigarray strict false maxredirects 0 timeout 30clientseturi http clientsetmethodzend http clientputclientsetfileupload dirname file filesloremipsumpng image 01clientsetparameterpostarraytestkey testvalue otherkey othervalueclientsetheadersarray api key identity credential solution turns out i made some wrong assumptions mainly that http put would be similar to http post as you can read below daverandom explained to me that http put is not meant for transferring multiple files on the same requesti have now moved the transferring of formdata from the body to url querystring the body now holds the contents of a single filefor more information read daverandoms answer it is epic,['php'] +334000,can i export part of an html page to an svg image i need a vector image of a wikipedia navbox unfortunately inkscape cannot open the html file and neither opera nor chromium can save the page as svg googling googling and yet more googling turned up nothing in particular html2svg seems to mean functionality where the html talks to an svg image inside it does anybody how to turn html into svg either the entire page or a div on the page i need the styled html css and all,['html'] +334017,how to use separate php version for different php files i have a site based on zend framework and hosted on 1and1 server1and1 server uses php version 5217 and 545 i need to use php version 545 for a few files only this is because some of my other files show a errors if i use php 545 but they execute fine using php 5217on my htaccess file the line below was written earlier to use php 5217addtype xmaphp5 phpto use php 545 i have to use the the line below instructions to use this code will be found on the 1and1 faq pageaddhandler xmaphp6 phpfaq urls languages supportedphp7html languages supportedphp6htmlis there any way to use php 545 for those specific files onlyi tried to use the line below in htaccess but it is not workingaddtype xmaphp5 phpaddhandler xmaphp6 filenamecontrollerphpediti tried to edit the 52 code i am using pear packages to create excel sheet which is working fine with php 5217 but thisplaying the error below on php 545fatal error cannot redeclare pear call destructorsaddendumthis change to the htaccess fileaddtype xmaphp5 php addhandler xmaphp6 php6 setenv application env development options multiviews ifmodule mod rewritec rewriteengine on rewritebase rewriterule filenamecontrollerphp filenamecontrollerphp6 l rewritecond request filename s or rewritecond request filename l or rewritecond request filename d rewriterule ncl rewriterule indexphp ncl ifmodulegenerates 404 page not found error if i change the filename of filenamecontrollerphp to filenamecontrollerphp6 and when i am trying to visit the page its generating,['php'] +334019,python nosetests skip certain tests i am working on tests for a web application written in pythonsuppose i have 5 tests in my test loginpy moduleevery single test is a classthere is often one base test that extends testflow class which is our predefined test classand then other tests in this module extend that base test for instance the base test testlogintestflow do login test stuff hereanother test in the same moduletestaccountdetailstestlogin do account details test stuff hereit is actually quite handy because in order to test for example accountdetails user has to be logged in so i can just inherit from testlogin test and i am ready to test other functionality as a logged userall tests are in projectprojecttests folderwe use nosetests with option withpylons to run testsand my question is if there is a way to mark certain testclass as do not test this onebecause i do not want to waste time to execute these base tests directly because they will be execute by other tests that iherit from themthere will be probably tones of these tests and i want to save every single second where it is possiblei have already found something like skip skiptest or nottest but these only work for test methods within a ceratin testclass so i do not think it will work here were i have a single class for each test case,['python'] +334056,better ways to get nth element from an unsubscriptable iterable sometimes an iterable might be not subscriptable say the return from itertoolspermutationsps permutationsrange10 10print ps10python will complain that itertoolspermutations object is not subscriptableof course one can perform next by n times to get the nth element just wondering are there better ways to do so,['python'] +334065,consolelog timestamps in chrome is there any quick way of getting chrome to output timestamps in consolelog writes like firefox does or is prepending new dategettime the only option,['javascript'] +334080,a ternary in templates how do you do a ternary with angularjs in the templatesit would be nice to use some in html attributes classes and style instead of creating and calling a function of the controller,"['javascript', 'html']" +334092,html5 javascript parallax effect on single elements div tags i have created a few sites in the past with the scrolldeckjs that have the standard full screen background with one layer ontop and text the standard scroll parallax style this is not what i am looking forim looking for a script or tutorial or examples for having a single div tag image in the foreground animatemove as you scroll i will be using this on a one page vertical scrolling site so as your scrolling i would like the odd image to scroll in at a different speed and have a start and stop position i dont want the entire background on parallaxthanks a bunch in advanceedit here is a better explanation of what im looking forpicture scrolling down a page as you scroll you see a bottle thats floating transparent png you continue to scroll down reading content and at a certain point that bottle rests nicely on a table part of background as you keep scrolling it will no longer move pretty well the goal is to have elements images move into predetermined positions based on scrolling and then stay put once they get to their final resting positionedit 2 here are some example sites this site does exactly what i want about 23 of the way down at this point see screenshot the burger pretty well does the effect i want minimal but it moves into position as you scroll,"['javascript', 'jquery']" +334098,smooth scroll does not work in viewpager support library i am writing application that uses viewpager to host fragmentswhen i change fragment programmatically the smooth scroll function does not work i use viewpagersetcurrentitemint item boolean smoothscroll methodmaybe anyone know a workaround this bug maybe with animationsediti am using support package and the issue is that whether i use viewpagersetcurrentitem2 true or viewpagersetcurrentitem2 false the result is the same the view switches really fast not smoothly,['android'] +334143,search in rails i have a table of posts with attributes that include title and body posts controllerrbclass postscontroller applicationcontroller def index posts postsearchparamssearch paramsid endendindexhtmlerb form tag posts path method get do text field tag search paramssearch submit tag search name nil end hr table tr thtitleth thtextth tr tr tdhrtd tdhrtdtr postseach do post tr td posttitle td td posttext td td link to show action show id postid td td link to edit action edit id postid td td link to destroy action destroy id postid method delete confirm are you sure td tr tr tdhrtd tdhrtd tr end tableand postrbdef selfsearchsearch id if search wherename like search else scoped endendwhen i submit the search params i get an error messageactiverecordstatementinvalid in postsindex sqlite3sqlexception no such column name select posts from posts where name like lorem extracted source around line 2323 postseach do post apd i want to search by title,['ruby-on-rails'] +334221,celery creating a new connection for each task i am using celery with rethis to run some background tasks but each time a task is called it creates a new connection to rethis i am on heroku and my rethis to go plan allows for 10 connections i am quickly hitting that limit and getting a max number of clients reached errorhow can i ensure that celery queues the tasks on a single connection rather than opening a new one each timeedit including the full tracebackfile appherokuvenvlibpython27sitepackagesdjangocorehandlersbasepy line 1 in get response response callbackrequest callback args callback kwargs file appherokuvenvlibpython27sitepackagesnewrelic140137newrelicapiobject wrapperpy line 166 in call self nr instance args kwargs file appherokuvenvlibpython27sitepackagesnewrelic140137newrelichooksframework djangopy line 447 in wrapper return wrappedargs kwargs file appherokuvenvlibpython27sitepackagesdjangoviewsdecoratorscsrfpy line 77 in wrapped view return view funcargs kwargs file appfeedbackviewspy line 264 in zencoder webhook handler tasksprocess zencoder notificationdelaywebhook file appherokuvenvlibpython27sitepackagesceleryapptaskpy line 343 in delay return selfapply asyncargs kwargs file appherokuvenvlibpython27sitepackagesceleryapptaskpy line 458 in apply async with aproducer or acquireproducer as p file usrlocallibpython27contextlibpy line 17 in enter return selfgennext file appherokuvenvlibpython27sitepackagesceleryappbasepy line 247 in producer or acquire with selfamqpproducer poolacquireblocktrue as producer file appherokuvenvlibpython27sitepackageskombuconnectionpy line 705 in acquire r selfpreparer file appherokuvenvlibpython27sitepackageskombupoolspy line 54 in prepare p p file appherokuvenvlibpython27sitepackageskombupoolspy line 45 in lambda return lambda selfcreate producer file appherokuvenvlibpython27sitepackageskombupoolspy line 42 in create producer return selfproducerself acquire connection file appherokuvenvlibpython27sitepackagesceleryappamqppy line 160 in init supertaskproducer self init channel exchange args kwargs file appherokuvenvlibpython27sitepackageskombumessagingpy line 83 in init selfreviveselfchannel file appherokuvenvlibpython27sitepackageskombumessagingpy line 174 in revive channel selfchannel maybe channelchannel file appherokuvenvlibpython27sitepackageskombuconnectionpy line 879 in maybe channel return channeldefault channel file appherokuvenvlibpython27sitepackageskombuconnectionpy line 617 in default channel selfconnection file appherokuvenvlibpython27sitepackageskombuconnectionpy line 610 in connection self connection self establish connection file appherokuvenvlibpython27sitepackageskombuconnectionpy line 569 in establish connection conn selftransportestablish connection file appherokuvenvlibpython27sitepackageskombutransportvirtual init py line 722 in establish connection self avail channelsappendselfcreate channelself file appherokuvenvlibpython27sitepackageskombutransportvirtual init py line 705 in create channel channel selfchannelconnection file appherokuvenvlibpython27sitepackageskombutransportrethispy line 271 in init selfclientinfo file appherokuvenvlibpython27sitepackagesnewrelic140137newrelicapiobject wrapperpy line 166 in call self nr instance args kwargs file appherokuvenvlibpython27sitepackagesnewrelic140137newrelicapifunction tracepy line 81 in literal wrapper return wrappedargs kwargs file appherokuvenvlibpython27sitepackagesrethisclientpy line 344 in info return selfexecute commandinfo file appherokuvenvlibpython27sitepackageskombutransportrethispy line 536 in execute command connsend commandargs file appherokuvenvlibpython27sitepackagesrethisconnectionpy line 273 in send command selfsend packed commandselfpack commandargs file appherokuvenvlibpython27sitepackagesrethisconnectionpy line 256 in send packed command selfconnect file appherokuvenvlibpython27sitepackagesnewrelic140137newrelicapiobject wrapperpy line 166 in call self nr instance args kwargs file appherokuvenvlibpython27sitepackagesnewrelic140137newrelicapifunction tracepy line 81 in literal wrapper return wrappedargs kwargs file appherokuvenvlibpython27sitepackagesrethisconnectionpy line 207 in connect selfon connect file appherokuvenvlibpython27sitepackagesrethisconnectionpy line 233 in on connect if selfread response ok file appherokuvenvlibpython27sitepackagesrethisconnectionpy line 283 in read response raise responseresponseerror max number of clients reached,['python'] +334252,python tkinter app adding a right click context menu i have a pythontkinter gui app that i have been trying to find some way to add in some functionality i was hoping there would be a way to rightclick on an item in the apps listbox area and bring up a context menu is tkinter able to accomplish this would i be better off looking into gtk or some other guitoolkit,['python'] +334286,how do i automatically get the timezone offset for my local time zone i am trying to automate getting the local timezone offset but am having trouble i have triedprint timetimezone3600this gets the currently wrong offset as it does not automatically adjust for daylight savings time and nondsti have also triednow utc pytzutclocalizedatetimedatetimenownow mst now utcastimezonepytztimezoneusmountainthis gets the correct offset value but i would like to set usmountain part automatically so i do not have to manually input anything to get the offsetis there a way to get the correct offset that automatically adjusts with dst nondsti will be running this script on multiple servers in different geographies and i want to get the tz offset automatically if i can,['python'] +334300,consolelog does not work in safari 60 web inspector consoleloghiundefinedis there any similar implementation in 60 or did i do something wrong,['javascript'] +334314,arraysaslist confusing source code according to this source code for the arrays class the method aslist passes an array to the constructor of new arraylist but there is no such constructor does not varargs generate an array so how is this possiblehere is the aslist sourcepublic static t listt aslistt a return new arraylistta,['java'] +334364,c build systems what to use i am looking at starting a new project in c just in my own time initially and i am investigating the build systems that are available it would appear that the answer is many and they are all awful the features that i specifically need for this arec11 supportcross platform linux as main target but able to build on at least windows as welldecent unit testing supportsupport for multiple modules for separating code outsupport for code generation using asn1c or protobuf not 100 sure yeteasy to maintainnow i know i can do 14 of those using cmake and autotools easily enough probably also with scons and waf and the couple of others too the problem is that i have never worked out how to correctly do code generation using them that is source files that do not exist until the build process is first run so source files that the build system must be able to convert into executable code but does not actually know about until the build starts asn1c in particular generates dozens of header and source files that must be able to work together and the actual set of files generates depends on the contents of your asn file there is also the fact that none of these are especially easy to maintain cmake and autotools have their own huge set of scripts that you need to manage for them to work and waf and scons require that anybody working with them has decent knowledge of python i do not to work with themso what build systems are recommended for something like this or will i be stuck with make files and shell scripts for now,['c++'] +334414,play 20 java bind an array from request i stuck ooi have params in foreign requestparam62537abcparam20356cdeparam92837fghand i am looking for any way for binding them ie with dynamicform i can get param withdynamicform dynamicform formbindfromrequeststring firstparam dynamicformfieldparam62537valuebut of course i dont know the indexes as they are selected within the clientside form created by the independent appwhen i am trying to usestring firstparam dynamicformfieldparamvalue it is nullstring firstparam dynamicformgetparam it is nullor evenstring params requestbodyasformurlencodedgetparam it is still nulldid i miss something really basic or play just cannot do that,['java'] +334418,what is pixel and points in iphone from uiimage referencesizethe dimensions of the image taking orientation into account readonlypropertynonatomic readonly cgsize sizethiscussionin ios 40 and later this value reflects the logical size of the image and is measured in points in ios 3x and earlier this valuealways reflects the dimensions of the image measured in pixelswhats the difference between pixel and points,"['iphone', 'ios']" +334441,selenium and python to find elements and text when i go to a certain webpage i am trying to find a certain element and piece of textspan classbold orange large0spanthis did not work it gave an error of compound class nameselem browserfind elements by class namebold orange largeso i tried this but i am not sure it worked because i do not really understand the right way to do css selectors in seleniumelem browserfind elements by css selectorspanclassbold orange largeonce i find the span element i want to find the number that is inside the contentnum elemwhat to put hereany help with css selectors class names and finding element text would be greatthanksoh and my other problem is that there are multiple of those exact span elements but with different numbers inside how can i deal with that,['python'] +334447,i returns lvalue below code gives error on compilation in a c compilerierror lvalue required as increment operandit means that i returns rvaluewhile codeido not give any error why so this link says that i do not result in lvalue,['c'] +334449,how to list specific nodeedge in networkx suppose one below treelike structure in networkx graphnn1n11 n12 n13 n131 n2 n21 x n22 n221 n3 n4n41 n5how to list all nodes with subnode and its depth here nn1n13n2n22n4how to list all nodes without subnode here n11n12n21n41n5how to list orphan node here n5 and how to list orphan edge not belongs to root and edge here n4n41 how to list node with more than 2 subnode here nn1how to deal with if n131n221 have an edge exists in nodes traversal will infinity loop happenthanks,['python'] +334471,amazon video on demand api i am trying to write a cnet application that can get results from amazons vod service i found this articleamazon api instant video resultsit suggests that i use the amazon product advertising api to get this information i have been looking at amazons getting started guide and various places around the internet and i am having no luck a lot of the information seems to be way out of date it looks like the latest api version is aug 2011 maybe of the examples are way before thatdoes anyone have any uptodate examples of how to use this api from c vbnet will be fine as well,['c#'] +334508,can pandas handle variablelength whitespace as column delimeters i have a textfile where columns are separated by variable amounts of whitespace is it possible to load this file directly as a pandas dataframe without preprocessing the file in the pandas documentation the delimiter section says that i can use a s construct but i could not get this to work sample datahead sampletxt full sequence this domain hmm coord ali coord env coord target name accession tlen query name accession qlen evalue score bias of cevalue ievalue score bias from to from to from to acc description of target abc membrane pf0066418 275 aaf674942 af170880 615 8e29 1007 114 1 1 3e32 1e28 1004 79 3 273 42 313 40 315 095 abc transporter transmembrane regionabc tran pf0522 118 aaf674942 af170880 615 26e20 728 00 1 1 19e23 64e20 715 00 1 118 402 527 402 527 093 abc transportersmc and pf0246314 220 aaf674942 af170880 615 38e08 327 02 1 2 036 12 49 00 27 40 391 404 383 408 086 recfrecnsmc and terminal domainsmc and pf0246314 220 aaf674942 af170880 615 38e08 327 02 2 2 18e09 61e06 254 00 116 210 461 568 428 575 085 recfrecnsmc and terminal domaina 16 pf131911 166 aaf674942 af170880 615 31e06 275 03 1 1 2e09 7e06 264 02 20 158 386 544 376 556 072 a atpase domainyceg pf0261811 297 aaf674951 af170880 284 34e64 2166 00 1 1 29e68 4e64 2163 00 68 296 53 274 29 275 085 yceglike familypyr redox 3 pf137381 203 aaf674962 af170880 352 29e28 991 00 1 2 28e30 48e27 952 00 1 201 4 198 4 200 085 pyridine nucleotidethisulphide oxidoreductaseload datafrom pandas import data read tablesampletxt skiprows3 headernone sep valueerror expecting 83 columns got 91 in row 4load data part 2data read tablesampletxt skiprows3 headernone seps this mushes some of the columns into the first column and drops the rest x11 abc tran pf0522 118 aaf674942 2 smc and pf0246314 220 aaf674942 3 smc and pf0246314 220 aaf674942 4 a 16 pf131911 166 aaf674942 5 yceg pf0261811 297 aaf674951 6 pyr redox 3 pf137381 203 aaf674962 7 pyr redox 3 pf137381 203 aaf674962 8 fmolike pf0074314 532 aaf674962 9 fmolike pf0074314 532 aaf674962 while i can preprocess the files to change the whitespace to commastabs it would be nice to load them directlyfyi this is the hmmdomtblout output from the hmmscan program,['python'] +334511,jtextarea word wrap resizing so i have jtextarea on a jpanel boxlayout i also have box filler that fills the rest of the jpanel i need my jtextarea to start of with singlelineheight i can manage that and to expand and reduce when that is neededword wrap is enabled i just need it to adjust it is height when new line is addedremovedi tried with documentlistener and getlinecount but it does not recognize wordwrapnewlinesi would like to avoid messing with the fonts if it is possibleand no scroll panes it is essential that jtextarea is thisplayed fully at all times,['java'] +334553,what are the advantages of using an amd like requirejs or commonjs modules in javascript i have read a lot of articles on amd solutions like requirejs or module loaders that follow commonjs style in javascriptlet us say i have an app splitted in this partsapp definition that rely on the framework i usemodel 1 that rely on app definition and frameworkmodel 2 that rely on app definition model 1 and my frameworki may write each part as a requirejs module or a common js module and split my project in how many files i want but whats the advantage of writing each part as a module or splitting them in many files and then load them in the right order to avoid dependency problems maybe concatenatening all the files in a big one to reduce http requets as done by rjs optimizer,['javascript'] +334571,control an arduino with java i am looking to turn an led on and off with a java program i did the project in c in roughly 5 minutes but it seems to be somewhat more challenging in java i had the arduino wait for a 1 or 0 to be written to the com port and would change the led based on that the code i am using for the arduino is as followsint ledpin 13char datavoid setup serialbegin9600 pinmode ledpin output void loop data serialread if serialavailable 0 ifdata 1 digitalwriteledpinhigh else ifdata 0 digitalwriteledpinlow else if serialavailable0 digitalwriteledpinhigh delay500 digitalwriteledpinlow delay500 how would i do this with a java application,['java'] +334582,let us solve the failed to find style mapviewstyle in current theme error sorry to post yet another one of these but it seems we have yet to document every solution to this issueheres what happened i added a mapview everything was working peachy i added a slidingdrawer and moved buttons into it then changed the root node from a linear to a relative since then i get an error in the graphical layout of my mainxml class that reads missing styles is the correct theme chosen for this layout use the theme combo box above the layout to choose a different layout or fix the theme style references failed to find style mapviewstyle in current themetoggling the root node to linear and back to relative has gotten the map to thisplay but the error is still in the graphical layout so far i have done the following solutions which may resolve the issue for most casesadded a stylexml to create a mapview styleverified my build target is api 233 10made sure useslibrary androidnamecomgoogleandroidmaps is a child node of applicationcleanrebuilt my applicationdeleted rdeleted and rebuilt mainxmlrestarted the adb server eclipse my computer and my devicetoggled between android 30 and android 233 in the graphical layouthowever my problem persists heres my layout xmlxml version10 encodingutf8relativelayout xmlnsandroidandroidididrelativelayout1androidlayout widthfill parentandroidlayout heightfill parentandroidorientationvertical comgoogleandroidmapsmapview xmlnsandroid androidididmapview stylestylemapview androidlayout widthfill parent androidlayout heightfill parent androidlayout alignparentbottomtrue androidlayout alignparentlefttrue androidlayout alignparenttoptrue androidapikeyasdf not my real key androidclickabletrue todo update the api key with release signature slidingdrawer androidididslidingdrawer1 androidlayout widthmatch parent androidlayout heightmatch parent androidcontentidcontent androidhandleidhandle button androidididhandle androidlayout widthwrap content androidlayout heightwrap content androidtextstringmenu linearlayout androidididcontent androidlayout widthmatch parent androidlayout heightmatch parent button androidididabout androidlayout widthfill parent androidlayout heightwrap content androidtextstringabout button androidididrecord androidlayout widthfill parent androidlayout heightwrap content androidtextstringrecord button androidididstart androidlayout widthfill parent androidlayout heightwrap content androidtextstringstart linearlayoutslidingdrawerrelativelayouthere is my manifest xmlxml version10 encodingutf8manifest xmlnsandroidpackageedumyschoolhereandroidversioncode1androidversionname10 usessdk androidminsdkversion10 usespermission androidnameandroidpermissioninternetusespermission androidnameandroidpermissionaccess fine locationapplication androidicondrawableic launcher androidlabelstringapp name useslibrary androidnamecomgoogleandroidmaps activity androidnamegeotagactivity androidlabelstringapp name androidthemeandroidstylethemenotitlebar intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activityapplicationmanifestif anyone has a solution please let me know i will do my best to post back if i ever figure it out,['android'] +334589,example for a correctly synchronized program with data races in java memory model in jls a1745 happensbefore order it says that a program is correctly synchronized if and only if all sequentially consistent executions are free of data racesaccording to thiscussion in does a correctly synchronized program still allow data racepart iwe get following conclusiona program can be correctly synchronized and have data races the combination of two conclusions means that it must exists such an exampleall sequentially consistent executions of a program are data race free but the normal executions executions other than sequentially consistent executions of such a program contain data raceafter heavy consideration i still can not find such a code sample so how about you,['java'] +334590,nspredicate to compare integer using contains i am using a nspredicate to search numbers in the list using uisearchbar it works in case of strings but does not work for an integeri am using the following predicatepredicate nspredicate predicatewithformatnsstring stringwithformat containsc d number searchbartext intvalueobjectarray filterusingpredicatepredicatetableview reloaddatafor example if i type 1 then all the ones in the array must be listed i have tried it works only for the exact number if tried any work around for this any bodynow i get an error if i use this method cannot use incontains operator with collection,"['iphone', 'objective-c']" +334604,access camera from a browser is it possible to access the camera builtin on apples from a browser optimal solution would be clientside javascript looking to avoid using java or flash,['javascript'] +334605,danger of mixing numpy matrix and array the scienceengineering application i am working on has lots of linear algebra matrix multiplications therefore i use numpy matrices however there are many functions in python that interchangeably accept matrix or array types nice no well not really let me demonstrate the problem with an examplefrom scipylinalg import expmfrom numpy import matrix setup input variable as matrixa matrix 0 10 0 0 0 0 0 10 0 0 0 0 0 0 10 0 do some computation with that inputb expmab1 b02 24b2 b24 24t compute and print the desired outputprint the innocent but wrong answerprint b2 b1print the answer i should getprint matrixb2 matrixb1when run you getthe innocent but wrong answer0167 05 0 1 the answer i should get since i expected everything to still be matrices 03 05 05 1 any tips or advice on how to avoid this sort of a mix up its really messy to keep wrapping variables in matrix calls to ensure they still are matrices it seems there is no standard in this regard and so it can lead to bugs that are hard to detect,['python'] +334646,trying to serve django static files on development server not found i have followed the instructions in this question the documentation and i have even looked at this one but so far i am unable to get at my static files using python managepy runserverthese are my relevant settingsstatic root homewayneprogrammingsomesitestaticstaticfiles dirs homewayneprogrammingsomesitestaticstyles homewayneprogrammingsomesitestaticadminin my urlspyfrom djangocontribstaticfilesurls import staticfiles urlpatterns the rest of my urls hereif settingsdebug urlpatterns staticfiles urlpatternsi have the following code in my basehtml link relstylesheet typetextcss href static stylesmaincss block styles for sheet in styles link relstylesheet typetextcss href static sheet endfor and i promise i am not hallucinatingenvwayneprogrammingsomesitestatic pwd homewayneprogrammingsomesitestatic envwayneprogrammingsomesitestatic ls admin styles however when navigate to httplocalhost80 my site is missing its stylesheets and when i go to httplocalhost80staticstylesmaincss i get stylesmaincss could not be found and trying to navigate to localhost80static or localhost80staticstyles it tells me that directory indexes are not allowedwhat am i missing here,['python'] +334647,weaknesses and forces of doctrine 2 and propel 16 i would like to know what are the forces and weaknesses of doctrine 2 and propel 16for instance doctrine 2 is really user friendly but limits you if you want to go beyond conformism doctrine 2 documentation lack of updates if possible you can share your experience on where doctrine2 was doing good or where propel was perfectthanks in advance,['php'] +334664,java bigdecimal without e i have a bigdecimal variablebigdecimal x new bigdecimal552101formulax xaddnew bigdecimal1 multiplyxdividetointegralvaluenew bigdecimal10i want to remove the integer part to get the value x 01 but my new value is 1e10 and not the 01,['java'] +334672,do unused usings in net affect performance possible duplicatewhy should you remove unnecessary c using directiveshow is performance affected by an unused using statement do unused usings in c affect runtime performance if yes how do sousing systemusing systemcollectionsgenericusing systemcomponentmodel unusedusing systemdataunusedusing systemdrawingunusedusing systemtextunusedusing systemwindowsformsusing systemthreadingunusedusing systemlinqunusedusing systemiounusedusing systemdiagnosticsunusedusing systemdataoledbusing obid,"['c#', '.net']" +334709,how can i create a sliding drawer with menu items how can i create a horizontal sliding drawer like the youtube and facebook app hasmany other apps seem to use use the same style so i am guessing that this is a part of the default androind ui framework but i cannot seem to piece it together you can see some more samples herethanks,['android'] +334734,windows 8 collectionviewsource observablecollection binding not updating i have a collectionviewsource that is binding to an subset of an observable collection to show the top and articles on the main pagecollectionviewsource xnamegroupeditemsviewsource sourcebinding groups issourcegroupedtrue itemspathtopitems in my code i do the followingprotected async override void loadstateobject navigationparameter var feeddatasource feeddatasourcenavigationparameter thisdefaultviewmodelgroups feeddatasourcefeedsmy feeddatasource contains an observablecollectionfeedcategory feeds which has an observablecollectionfeeditem items and topitems public observablecollectionfeeditem topitems get return new observablecollectionfeeditemthisitemstake5 now i have added a refresh method which adds more feeditems to the items collection however when i refresh it has no effect on the grid view on my main page which uses the groupeditemsviewsource for it is itemssource propertyitemssourcebinding sourcestaticresource groupeditemsviewsourceif i navigate away from the page and then back again so the page gets rebuilt the new items are there why is not my gridview showing these changes as they happen i thought that by binding the collection and grid view they should reflect these changes i have tried changing them to two one one way but it makes no differencecan anyone shed some light as to why this is not working,['c#'] +334739,when syncing with an underscored backend convert to camelcase for use in javascript tldr whats a good way to use an underscored naming convention serverside ror with a camelcased naming convention clientside jsserverside programming environments like ruby on rails use underscored variables conventionally javascript uses camelcased variables this is problematic when sending data from the client to the serverfor example consider sending user information to the client there may be a property in the database called num times ordered yet in javascript youd traditionally want to refer to this as numtimesorderedhas anyone come up with an elegant way of dealing with this here are some options none particularly niceconvert data to camelcase when fetched from serveruse camelcase when sending it from the serveruse an underscored naming convention in your javascript although then youre inconsistent with any third party libraries like jqueryuse a camelcased naming convention on your backend although then youre inconsistent with your backends conventionsi am leaning towards 3 and using underscores in my javascript it will look weird when i use camelcased third party libraries though,"['javascript', 'ruby-on-rails']" +334745,ruby bcrypt hash comparison i am trying to implement what seems like a very simple authentication approach using sinatra and bcrypt but clearly i am missing somethingusers are preassigned a temporary password which is stored in plaintext in the dbi authenticate against the temp password and then create both a salt and password hash and write them as strings to the db mongo in this caseto authenticate i fetch the salt from the db and user password to comparepost password reset do user userfirstemail paramsemail temp password paramstemp password if dealer nil then password salt bcryptenginegenerate salt password hash bcryptenginehash secretparamspassword password salt usersetpassword hash password hash usersetpassword salt password salt endendpost auth do user userfirstemail paramsemail user hash bcryptpasswordnewuserpassword hash because the password hash is stored in the db as a string i cast it as a bcryptpassword for comparison if user hash bcryptenginehash secretparamspassword userpassword saltto s then auth true else auth false endendthe value returned by bcryptenginehash secretparamspassword password salt is different than what is stored in the db both are of class bcryptpassword but they do not matchwhat am i missing here many thanks in advance for any insightmarc,['ruby'] +334754,how to reduce recording noise when recording with audio sessions i got some recording code working but the recorded audio from the ipod touch internal microphone is very noisythis is my configuration avaudiosession audiosession avaudiosession sharedinstance nserror err nil audiosession setcategoryavaudiosessioncategoryplayandrecord errorerr if err nslogaudiosession d err domain err code err userinfo description return audiosession setactiveyes errorerr err nil if err nslogaudiosession d err domain err code err userinfo description return recordsetting nsmutabledictionary alloc init we can use kaudioformatappleima4 41 compression or kaudioformatlinearpcm for nocompression recordsetting setvaluensnumber kaudioformatlinearpcm forkeyavformatidkey we can use 44100 320 240 160 or 120 depending on sound quality recordsetting setvaluensnumber numberwithfloat4410 forkeyavsampleratekey we can use 2 if using additional hw or 1 iphone only has one microphone recordsetting setvaluensnumber numberwithint1 forkeyavnumberofchannelskey these settings are used if we are using kaudioformatlinearpcm format recordsetting setvaluensnumber numberwithint16 forkeyavlinearpcmbitdepthkey recordsetting setvaluensnumber numberwithboolno forkeyavlinearpcmisbigendiankey recordsetting setvaluensnumber numberwithboolno forkeyavlinearpcmisfloatkeydo i have bad config here or is there a different way to reduce noise in the recorded audio there are some voice recorder apps out there that are noise free as far as i can tell,['ios'] +334760,can a locked row in postgres still be read from if i select for update a row in a transaction it will obviously block the row from being written to but will it thisallow reads as well i would prefer to still be able to read from the row so if the answer is yes can you provide a solution to work this,['sql'] +334770,guidelines for using properties vs methods i often have a hard time deciding if certain data should be exposed through a property or a method you can say use properties for object state but that is not very satisfying take this example for instance nsstring stringone return stringone nsstring stringtwo return stringtwo nsstring mainstring return stringone length 0 stringone stringtwoit is clear that stringone and stringtwo should be properties because they are clearly object state it is not clear however if mainstring should be a property to the end user mainstring acts like state to your object mainstring is not statethis example is contrived but hopefully you get the idea yes properties are nothing more than a convenient way to create getters and setters but they also communicate something to the user does anyone have decent guidelines for deciding when to use a property vs a method,['objective-c'] +334790,when is stdweak ptr useful i started studying smart pointers of c11 and i do not see any useful use of stdweak ptr can someone tell me when stdweak ptr is usefulnecessary,['c++'] +334793,changelog changeloggroovy not found i have created new grails project in intellijidea 13 and try to run itwhen i open httplocalhost8080applicationdbdoc accessing default action of controller grailsplugindatabasemigrationdbdoccontroller i keep getting messagechangelog changeloggroovy not foundalthough file changeloggroovy exists in file system of my project in folder grailsappmigrations i have generated it using commandgrails dbmcreatechangelog changeloggroovy and now it has the following contentdatabasechangelog changesetauthor edward generated id changelog todo add changes and preconditions here what i need to do to make it work,['java'] +334796,php date validation im trying to to set up a php date validation mmddy but i am having issues here is a sample of what i gotdate regex a0191012 0191209301 1920ddz test date 032010 if preg matchdate regex test date postbirthday true errors user name most have no spaces,['php'] +334803,calling a qobject function from qml across threads i am trying to determine how calling qobject slots or q invokable methods from qml for a qobject that lives in another thread works and whether or not its safe to do soassume there is a mainthread and threada qobjecta lives in threada the qml engineguieverything lives in the mainthread i expose qobjecta to the qml engine using declarativeviewsetcontextpropertysomeobjobjectanow in a qml file i callsomeobjsomemethodwhere somemethod is a slot or is q invokable i would like to know which thread actually executes the function if it is mainthread that would be a bad thing and calling a method like that across threads would be dangerous if it was executed by threada however all would be wellbased on this documentation i am assuming that qmetaobjectinvokemethod is used to call the qobject function that documentation shows that there are different connection types available just like with qt signals and slots i would like to know if qts qml engine automagically chooses the right type for the situation when invoking c methods from qml across threads and if so calling methods for objects that live in other threads from qml is an acceptable practice,['c++'] +334856,entityframework cannot see connectionstring in the appconfig i am studying code first entityframework together with aspnet mvc 3at first my trivial efdbcontext class was placed in the webui mvc project in a concrete folder public class efdbcontext dbcontext public dbsetproduct products get set and it was consumed through public class efproductrepository iproductrepository private efdbcontext context new efdbcontext public iqueryableproduct products get return contextproducts where public interface iproductrepository iqueryableproduct products get so i added the following code to the root webconfig connectionstrings add namewebuiconcreteefdbcontext connectionstringdata sourcehorghsqlserver2008initial catalogsportstoreintegrated securitytruepoolingfalseprovidernamesystemdatasqlclient connectionstringsand it workedthen i decided to take it into a separate domain class library project there i have an appconfig file so i decided to move my connection string there and it became to beconnectionstrings add namedomainconcreteefdbcontext connectionstringdata sourcehorghsqlserver2008initial catalogsportstoreintegrated securitytruepoolingfalseprovidernamesystemdatasqlclient connectionstringsbut eventually ef stopped seeing itefproductrepository and efdbcontext moved to the domain project with their root folder concrete so the code calling the constructor is in efproductrepository ie in domain project i tried to rename appconfig to webconfig tried to return the connection string back to the webconfig of the webui project it does not work neitherwhat am i doing wrong,['c#'] +334858,android googlemap map does not show only grid sometimes so i have been working on getting this up and running for some time now problem is i have my map key from google placed correctly in mainxml but i cannot seem to get a provider information as the map does not thisplay at all i have run it a couple of times and the fail us at the same place i tried to debug and noticed that there is a provider string returned however after that a null the code fails at overrideprotected void onresume superonresume locationmanager requestlocationupdatesgetbestprovider 10 1 thiswith the following error message 0820 051443573 eandroidruntime239 uncaught handler thread main exiting due to uncaught exception0820 051443583 eandroidruntime239 javalangruntimeexception unable to resume activity comshawnbemallfindercomshawnbemallfindermallfinderactivity javalangnullpointerexception0820 051443583 eandroidruntime239 at androidappactivitythreadperformresumeactivityactivitythreadjava29500820 051443583 eandroidruntime239 at androidappactivitythreadhandleresumeactivityactivitythreadjava29650820 051443583 eandroidruntime239 at androidappactivitythreadhandlelaunchactivityactivitythreadjava25160820 051443583 eandroidruntime239 at androidappactivitythreadaccess2200activitythreadjava1190820 051443583 eandroidruntime239 at androidappactivitythreadhhandlemessageactivitythreadjava18630820 051443583 eandroidruntime239 at androidoshandlerthispatchmessagehandlerjava990820 051443583 eandroidruntime239 at androidoslooperlooplooperjava1230820 051443583 eandroidruntime239 at androidappactivitythreadmainactivitythreadjava43630820 051443583 eandroidruntime239 at javalangreflectmethodinvokenativenative method0820 051443583 eandroidruntime239 at javalangreflectmethodinvokemethodjava5210820 051443583 eandroidruntime239 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava8600820 051443583 eandroidruntime239 at comandroidinternaloszygoteinitmainzygoteinitjava6180820 051443583 eandroidruntime239 at dalviksystemnativestartmainnative method0820 051443583 eandroidruntime239 caused by javalangnullpointerexception0820 051443583 eandroidruntime239 at comshawnbemallfindermallfinderactivityonresumemallfinderactivityjava610820 051443583 eandroidruntime239 at androidappinstrumentationcallactivityonresumeinstrumentationjava11490820 051443583 eandroidruntime239 at androidappactivityperformresumeactivityjava37630820 051443583 eandroidruntime239 at androidappactivitythreadperformresumeactivityactivitythreadjava29370820 051443583 eandroidruntime239 12 moreoccasionally the code seems launches the grid but no map while on other runs it simply fails out below is my activity code package comshawnbemallfinderimport javautillistimport comgoogleandroidmapsgeopointimport comgoogleandroidmapsmapactivityimport comgoogleandroidmapsmapcontrollerimport comgoogleandroidmapsmapviewimport comgoogleandroidmapsoverlayimport comgoogleandroidmapsoverlayitemimport androidcontentcontextimport androidgraphicsdrawabledrawableimport androidlocationcriteriaimport androidlocationlocationimport androidosbundleimport androidwidgettextviewimport androidwidgettoastpublic class mallfinderactivity extends mapactivity implements androidlocationlocationlistener called when the activity is first created private mapcontroller mapcontroller private mapview mapview private androidlocationlocationmanager locationmanager private geopoint currentpoint private location currentlocation null private textview latitutefield private textview longitudefield private string bestprovider override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain mapview mapview mapview findviewbyidridmapview mapviewsetbuiltinzoomcontrolstrue location location getbestprovider ifbestprovider null location locationmanagergetlastknownlocationbestprovider listoverlay mapoverlays mapviewgetoverlays drawable drawable thisgetresourcesgetdrawable rdrawableandroidmarker mapitemizedoverlay itemizedoverlay new mapitemizedoverlaydrawable this localgeopoints loc new localgeopoints for overlayitem a locoverlayitems itemizedoverlayaddoverlaya mapoverlaysadditemizedoverlay override protected void onresume superonresume locationmanager requestlocationupdatesgetbestprovider 10 1 this public void getlastlocation string provider getbestprovider currentlocation locationmanagergetlastknownlocationprovider if currentlocation null setcurrentlocationcurrentlocation else toastmaketextthis location not yet acquired toastlength long show public void animatetocurrentlocation if currentpoint null mapcontrolleranimatetocurrentpoint public string getbestprovider locationmanager androidlocationlocationmanager getsystemservicecontextlocation service criteria criteria new criteria criteriasetpowerrequirementcriteriano requirement criteriasetaccuracycriteriano requirement bestprovider locationmanagergetbestprovidercriteria false return bestprovider public void setcurrentlocationlocation location int currlatitude int locationgetlatitude 1e6 int currlongitude int locationgetlongitude 1e6 currentpoint new geopointcurrlatitude currlongitude currentlocation new location currentlocationsetlatitudecurrentpointgetlatitudee6 1e6 currentlocationsetlongitudecurrentpointgetlongitudee6 1e6 override protected boolean isroutethisplayed return false remove the locationlistener updates when activity is paused override protected void onpause superonpause locationmanagerremoveupdatesthis override public void onlocationchangedlocation location int lat int locationgetlatitude int lng int locationgetlongitude latitutefieldsettextstringvalueoflat longitudefieldsettextstringvalueoflng override public void onproviderenabledstring provider toastmaketextthis enabled new provider provider toastlength shortshow override public void onproviderthisabledstring provider toastmaketextthis thisabled provider provider toastlength shortshow override public void onstatuschangedstring provider int status bundle extras todo autogenerated method stub and below is my mainxml ccomplete with the key i obtained from the google map registeration site xml version10 encodingutf8linearlayout xmlnsandroid androidlayout widthfill parent androidlayout heightfill parent androidorientationvertical framelayout androidlayout widthfill parent androidlayout heightfill parent comgoogleandroidmapsmapview androidididmapview androidlayout widthfill parent androidlayout heightfill parent androidclickabletrue androidapikey0steid872feggae0eo2dhdyei37sfphg65t7n6xa framelayoutlinearlayout,"['java', 'android']" +334870,use of mbprogresshud globally make it singleton in my project each of the user interaction events make a network call which is tcp not http i need activity indicator to be global to show from a random uiviewcontroller and hide from networkactivitymanager class a custom class to handle network activities which is not a subclass of uiviewcontroller or uiviewafter searching the web i found out that mbprogresshud is used for the same purpose but i was not able to find out an example on how would i use it globally by saying global i mean a singleton object of mbprogresshud and class methods to show and hide itfollowing is what i have tried yet but failedin appdelegatehproperty nonatomic retain mbprogresshud hudin appdelegatemsynthesize hudin some random uiviewcontroller objectappdelegatehud mbprogresshud showhudaddedtoappdelegatenavigationcontrollertopviewcontrollerview animatedyesappdelegatehudlabeltext this will take some timeand while hiding it from networkactivitymanager classmbprogresshud hidehudforviewappdelegatenavigationcontrollertopviewcontrollerview animatedyesthis makes the project to crash after some time due to memory issuesi am using arc in my project and also i am using the arc version of mbprogresshudam i missing somethingimportant questioncan i make mbprogresshud work like uialertview saying that i mean implementation of mbprogresshud independent of uiview sa it uses showhudaddedto to present itself please note in the above code of hiding mbprogresshud view may be changed from what it was when showing mbprogresshudany help greatly appreciated,"['iphone', 'ios']" +334883,generic way to deduce the return type of a functor this question is a followup of how to deduce the type of the functors return valuei am reformulating it in a more abstract way given the pseudocode of a template functiontemplate typename arg typename fnauto computesomethingarg arg fn fn decltypedeclexpr do something return fnretexprwhere retexpr is an arbitrary expression which involves arg what shall i use for declexpr to set the return type of computesomething equal to the return type of the functorthe functor may be a class a lambda or a function pointerpartial solutions i found so fara the answer for my linked question done by ecatmur essentially it is repeating the return statement in declexpr problems it is errorprone and wouldnt work if contains local variablesb it works only for function pointerstemplate typename arg typename retret computesomethingarg arg retfnargc it assumes that the argument of the functor is of type arg which may not hold in general and requires arg to be defaultconstructibletemplate typename arg typename fnauto computesomethingarg arg fn fn decltypefnargd using stddeclval which is supposed to lift the defaultconstructible restriction as suggested in how to deduce the return type of a function in template could anybody explain how it workstemplate typename arg typename fnauto computesomethingarg arg fn fn decltypefnstddeclvalarg,['c++'] +334887,locknew object cargo cult or some crazy language special case i am reviewing some code written by a consultant and while dozens of red flags have already popped up i cannot wrap my head around the following snippetprivate void foo if invokerequired lock new object if m bar null invokenew foodelegatefoo new object else ifonbazchanged null onbazchanged what is locknew object doing here should have no effect whatsoever as it is always locking on another object but this kind of locking is persistent throughout the code even in noncopyandpasted parts is this some special case in the c language that is compiled to something i do not know about or has the programmer simply adopted some cargo cult that happened to work some time ago,['c#'] +334917,handling onpropertychanged i am not well versed in eventbased programming basically i am still stumbling around with it i am trying to get something set up but even with the tutorials i cannot wrap my head around it what i would like to do in words is the followingi have a dataobject where a property changes i notice this in the setter of the property and want to raise an event that the property has changedelsewhere in a different class entirely i want to know that the property on this object has changed and take some actionnow i am sure this is a common enough scenario but my googlefu is letting me down i am simply not understanding i have thispublic class chattyclass private int somemember public event propertychangedeventhandler propertychanged public int somemember get return thissomemember set if thissomemember value somemember value raise eventfire handlers but how public class nosyclass private listchattyclass mychatters public void addchatterchattyclass chatter mychattersaddchatter start listening to property changed events private void listner i want this to be called when the propertychangedevent is called consolewritelinehey hey listen a property of a chatter in my list has changed what do i do to wire this upconcerning the comment pointing me back to the linkin the example i seeprotected void onpropertychangedstring name propertychangedeventhandler handler propertychanged if handler null handlerthis new propertychangedeventargsname what i am not understandingwhy is not this just calling propertychangedthis new propertychangedeventargsnamewhere does propertychanged get assignedwhat does the assignment look like,['c#'] +334934,how can i remove the no file chosen tooltip from a file input in chrome i would like to remove the no file chosen tooltip from a file input in google chrome i see that no tooltip is thisplayed in firefoxplease notice that i am talking not about the text inside the input field but about the tooltip that appears when you move the mouse over the inputi have tried this with no luckmyfileinputattrtitle,"['javascript', 'jquery', 'html', 'css']" +334936,what is div style for html center tag what is div style for html center tag,"['css', 'html']" +335005,multicore java program with native code i am using a native c library inside a java program the java program is written to make use of manycore systems but it does not scale the best speed is with around 6 cores ie adding more cores slows it down my tests show that the call to the native code itself causes the problem so i want to make sure that different threads access different instances of the native library and therefore remove any hidden memory dependency between the parallel tasksin other words instead of the static blockstatic systemloadlibrarythenativelibi want multiple instances of the library to be loaded for each thread dynamically the main question is if that is possible at all and then how to do itnotes i have implementations in java 7 forkjoin as well as scalaakka so any help in each platform is appreciated the parallel tasks are completely independent in fact each task may create a couple of new tasks and then terminates no further dependencyhere is the test program in forkjoin style in which processnatively is basically a bunch of native callsclass repeater extends recursivetasklong final int n final processor mol public repeaterfinal int m final processor o nm mol o override protected long compute processnativelymol final listrecursivetasklong tasks new arraylist for int in i9 i tasksaddnew repeatern1mol long count 1 forfinal recursivetasklong task invokealltasks count taskjoin return count private final static forkjoinpool forkjoinpool new forkjoinpoolpublic void repeatprocessor mol final long middle systemcurrenttimemillis final long count forkjoinpoolinvokenew repeater0 mol systemoutprintlncount is count final long after systemcurrenttimemillis systemoutprintlntime elapsed aftermiddleputting it differentlyif i have and threads that use a native library what happens if each of them calls systemloadlibrarythenativelib dynamically instead of calling it once in a static block will they share the library anyway if yes how can i fool jvm into seeing it as and different libraries loaded independently the value of and is not known statically,['java'] +335012,how to define unidirectional onetomany relationship in jpa i have a following problem with entity mapping in jpa i have two entities first one is lookup and the second is text which represents translations for entities now i need to bound lookup to the text but i do not want text to have reference to lookup to make this more complicated text does not use its primary key in this relationship but a metacode defined in a txthead code column lookupjavaentitytablename datregpublic class lookup implements persistableentity id columnname datreg meta code private string metacode onetomany jointablenametxt joincolumnsjoincolumnnamedatreg meta code referencedcolumnnametxthead code inversejoincolumnsjoincolumnnamedatreg meta code private listtext texttextjavaentitytablename txtpublic class text id columnname txt id private long id columnname txthead code private string codeso i have tried this and few other variations but with no result i also cannot create join table in the db and i do not want bound lookup to my text class so can anyone please tell me if there is some other way,['java'] +335023,list view adapter not working getview not called i think i am turning crazy something so simple has bind a custom adapter to a listview is giving me a headachepost the code and explain thenmainactivityjavapackage comexamplepruebalistimport androidappactivityimport androidosbundleimport androidutillogimport androidwidgetarrayadapterimport androidwidgetlistviewpublic class mainactivity extends activity private static string data new string 0123 public void oncreatebundle savedinstancestate todo autogenerated method stub superoncreatesavedinstancestate logvmainactivityinside mainactivity setcontentviewrlayoutmain listview lstview listviewfindviewbyidridlistnoticias arrayadapterstring adapter new lstadapterthis rlayoutrow data lstviewsetadapteradapter lstadapterjavapackage comexamplepruebalistimport androidappactivityimport androidcontentcontextimport androidutillogimport androidviewlayoutinflaterimport androidviewviewimport androidviewviewgroupimport androidwidgetarrayadapterimport androidwidgettextviewpublic class lstadapter extends arrayadapterstring private string mdata private context mcontext int layoutresourceid public lstadaptercontext context int textviewresourceid string values supercontext textviewresourceid values mcontext context mdata values layoutresourceid textviewresourceid logvlstadapterinside lstadapter override public int getcount todo autogenerated method stub return 0 override public long getitemidint arg0 todo autogenerated method stub return 0 override public view getviewint position view convertview viewgroup parent todo autogenerated method stub view v convertview logvlstadapterinside getview ifvnull layoutinflater inflater activitymcontextgetlayoutinflater v inflaterinflatelayoutresourceid parentfalse string item mdataposition ifitemnull textview txtitem textviewvfindviewbyidridtexto iftxtitemnull txtitemsettextitem return v the listview is never show and getview is never used logcat does not show inside getviewwhats wrong,"['java', 'android']" +335024,how can i add momentum inertia to a drag using css transform i am trying to add a momentum inertia effect to a zoomed image drag like in this example or just like ios does it and i am having a tough time with iti have been struggling with this for a while and found some helpful resources like this one but most of the solutions involve jquery and i would prefer to stick to plain javascript no frameworks involvedi am working on a html5 css3 zoom image code with all the standard features doubletap zoom pinch zooming dragging panning etc and everything is done using css3s transform translation combined with the scaling extransform translate100px 100pxtransition 100msi looked at how others are doing it and it involves consecutive animations of the leftright properties with decreasing duration thistance to create a sort of easein effecti tried to recreate it using translations using a sort of recursive function you can see a fiddle here works with webkit browsers please ignore the coding style it was not meant to be best practice just a demo in this case the animation is not fluid it all the consecutive translations do not connecti have a somewhat basic understanding of the principle and i did take a look at some algorithms available online but i just cannot figure out how can i achieve this using css translations the first part of the dragging done on mousemovetouchmove moves the image with the cursorfinger but the continuing translation after the end is not continuous it is like a separate animation after the first one and does not resemble a natural momentum inertia effect,['javascript'] +335027,create multiple tables for one class in ormlite i am using ormlite on android and have the following questionis it possible to create many tables based on a single java classthe tables should only differ in their names and the access to them should be by namefor example if i have a classpublic class order databasefield public string name databasefield public string amountand i have a dynamic number of modules that can create orders i want every module to have its own table but all tables should have a similar schemai know i can add a field in the order class that indicates the source module name and have all the orders live in one table but i was wondering if there is a way to separate the tables for faster queries faster deletion of orders from the same module and so onthanks,"['java', 'android']" +335032,implementing floggy framework in j2me i am creating an application with j2me for connecting with database i am using recordstore this is first get all records and traverse through it to search a record but i have thousands of records and i just need some based on criteria is there any way to resolve this problem i do not want to traverse through thousands of records to get ten recordsi have found floggy framework at i think it will be better but i am not able to find any proper reference to configure it outdoes anyone know to may i configure floogy in my j2me application i just want a rms that has criterion like thing see my other question database query j2me including criteriaserror stack tracecreated dir netbeansprojectslogin 1buildpreverifysrccopying 798 files to netbeansprojectslogin 1buildpreverifysrccreated dir netbeansprojectslogin 1buildpreverifiedpreverifying 798 files into netbeansprojectslogin 1buildpreverified directoryerror preverifying class netsourceforgefloggypersistenceweavertask javalangnoclassdeffounderror orgapachetoolsanttasknetbeansprojectslogin 1nbprojectbuildimplxml431 preverification failed with error code 1build failed total time 12 seconds,['java'] +335033,how to return multiple values from a webservice i am very new to the world of web services so please bear with mei am creating a very simple web service in visual studio 2010 using asmx fileshere is the code i am usingnamespace mywebservice webservicenamespace webservicebindingconformsto wsiprofilesbasicprofile1 1 systemcomponentmodeltoolboxitemfalse public class service1 systemwebserviceswebservice webmethod public string simplemethodstring str return hello str when i invoke this and enter a value john smith for the the str parameter it returnsxml version10 encodingutf8string xmlnshello john smithstringmy question is what is the best practice for returning more than 1 value for a web service method if the values are all the same data type should i use an array if the the values contain different data types would i need to create a custom class,['c#'] +335070,partial declarations must not specify different base classes i know there is information about this on the internet and i have searched for it but i am still getting the error can anyone point out to me what i am doing wrongbase classusing systemusing systemcollectionsgenericusing systemlinqusing systemtextusing systemwindowscontrolsnamespace programmanagementv2screens public abstract class ascreenusercontrol usercontrol public string getscreendescriptionname return no name yet mainusercontrolxamlusercontrol xclassprogrammanagementv2screensmainusercontrol xmlnsweclrnamespaceprogrammanagementv2screens xmlns xmlnsx xmlnsmc xmlnsd mcignorabled ddesignheight300 ddesignwidth300 grid textblock height23 horizontalalignmentcenter nametextblock1 textasdfasdf verticalalignmentcenter gridusercontrolmainusercontrolxamlcsusing systemusing systemcollectionsgenericusing systemlinqusing systemtextusing systemwindowsusing systemwindowscontrolsusing systemwindowsdatausing systemwindowsdocumentsusing systemwindowsinputusing systemwindowsmediausing systemwindowsmediaimagingusing systemwindowsnavigationusing systemwindowsshapesusing systemcomponentmodelnamespace programmanagementv2screens summary interaction logic for mainusercontrolxaml summary public partial class mainusercontrol ascreenusercontrol public mainusercontrol initializecomponent as you can see i am addingxmlnsweclrnamespaceprogrammanagementv2screensto the user control xml but i am still getting the errorpartial declarations of programmanagementv2screensmainusercontrol must not specify different base classescan anyone explain to me what i am doing wrong,['c#'] +335097,find active tab using jquery and twitter bootstrap i have been racking my brain for a little while now and i would like to know if anyone out there knows how i can find the active tab using jquery and twitters bootstrap pulling the hash from the url is not my first option i am using the datatoggle attribute in the a link so there is no need to produce a url hashany insight heres an example of my markupul classnav navlist idsampletabs lia hrefexample datatoggletabtab 1aliuldiv classtabcontent div classtabpane fade active in idexample example tab divdivscriptsampletabs afirsttabshowscripti am open to any suggestion using a php session js cookie etcedit this is the real issue i have a pagination system using php so when a page number or nextprev arrow is clicked it will reload the page this is why i need to find the active tab before loading the next page since ill just pass it in the url or session etc,['jquery'] +335100,how to avoid blocking code in python with gevent i am playing around with gevent and i am trying to understand why my code is blocking and how i can fix iti have a pool of greenlets and each of them talk to a thrift client which gathers data from a remote thrift server for the purpose of the exercise the thrift server always take 1s to return any datawhen i spawn the greenlets and run join they do not execute all in parallel but instead one after the other my understanding is that this is happening because my code is blocking since when i run monkeypatch all all greenlets magically run in parallelso how do i make the code nonblocking myself rather that monkey patching everything and not understanding what it is doingan example here of what i do not understand import timefrom geventpool import pooldef hello print hello d timetime timesleep1 def main pool pool5 for in xrange5 poolspawnhello pooljoinif name main mainoutputhello 1345477112hello 1345477113hello 1345477114hello 1345477115hello 1345477116i know i could be using geventsleep but how to make that function non blocking with the regular timesleepthanks,['python'] +335106,an avplayeritem cannot be associated with more than one instance of avplayer ibactionplayidsender thumbimageviewalpha00 nsstring stringvideonsstring stringwithformathttpstreamingservicensuserdefaults standarduserdefaultsvalueforkeyvideoidselected nsstring videourlstring stringvideo nsurl url nil url nsurl urlwithstringvideourlstring selfmovieplayercontroller mpmovieplayercontroller alloc initwithcontenturlurl if selfmovieplayercontroller save the movie object self setmovieplayercontrollerselfmovieplayercontroller self installmovienotificationobservers specify the url that points to the movie file selfmovieplayercontroller setcontenturlurl selfmovieplayercontroller setmoviesourcetypempmoviesourcetypestreaming for streaming selfmovieplayercontrollercontrolstyle mpmoviecontrolstyleembedded selfvideoplayer setmoviesourcetypempmoviesourcetypestreaming selfmovieplayercontrollershouldautoplay yes selfmovieplayercontrollerview setframe cgrectmake0 0 320160 selfmovieplayercontroller setfullscreenno animatedyes selfmovieplayercontroller viewbackgroundcolor uicolor lightgraycolor selfview addsubviewselfmovieplayercontrollerview selfview bringsubviewtofrontselfmovieplayercontrollerview selfmovieplayercontroller preparetoplay selfmovieplayercontrolleruseapplicationaudiosession no selfmovieplayercontroller play hi i am trying to stream a video on my iphone app the code plays a local file but crashes with an error terminating app due to uncaught exception nsinvalidargumentexception reason an avplayeritem cannot be associated with more than one instance of avplayer when used to stream a video from a server also the link streams the video absolutely fine in a browser but however i am not able to play the video in the app please help thanks,"['iphone', 'ios']" +335134,how to use the javascript module pattern in a real example i am trying to understand the javascript module pattern i have seen examples of what it should look like but i do not understand how to use itfor example a few things are happening hereinputshareonclick function loadinghtmlimg classremove loading srcgraphicsloadinggif var message wallmessageval if message messageemptyjmnotify remove loadingremove else addmessagemessage return falsefunction addmessagemessage ajax url test type post datatype json data message message success functiondata error function how can i use the above example withvar mytest function var selectid function addmessage return public interface publicmethod1 function all private members are accesible here var start mytestwhere do i add the click event declare my vars add the addmessage function with the ajax call and call the addmessage function do i have to wrap everything in documentreadyfunctioncan anyone shed some light on this for methanks,"['javascript', 'jquery']" +335141,how to create has and belongs to many relationship with emberjs emberdata is it possible to create a hasandbelongstomany relationship with emberjs emberdataedit added activerecord model examples to clarifyclass project activerecordbase has and belongs to many tagsendclass tag activerecordbase has and belongs to many projectsendi have an associative table projects tags linking project id tag id,['ruby-on-rails'] +335187,jquery chosen plugin dynamically populate list by ajax im trying to build my dropdown menu using the plugin chosen for multiple select heres to behavior i am based onso instead of having 3 harcoded option in my select i want this list to be the values of a json array populated by an ajax request this will be triggered by autocompleteso if the user type car im sending the letter via an ajax call and im getting back an array like thatid2489namecarrieid2490namecarolineid2491namecarolethe codefunction chznselectchosenchznselectdeselectchosenallow single deselecttruechznchoices inputautocomplete source function request response ajax url changenameautocompleterequestterm datatype json success function data response map data function item ulchznresultsappendli classactiveresult itemname li resulti type car in the dropdown im getting no result for car and then i have all my results as i want1 why i am i getting the no result message cause i can see in my json array and inside my list that i am getting results when i delete car and enter sam the results for sam are showing after the car results basically i see the result for both instead of just having the result of my current search2 im i suppose to clear the ul on keyup thought the plugin was doing that already when i click on a name to actually select it and add it into the select im getting a javascript error inside the chosenjs fileitem is undefineditemselected true line 732the link to the pluginand it is not adding anything inside the select3 no idea why this is happening do you guys have any idea on what i am i doing something wrong i am completly stuck hereoh and by the way i dont mind changing the plugin source as it is the only place where i am using it,"['javascript', 'jquery']" +335189,case insensitive checking of suffix of nsstring i would like to check if a string has a certain suffix but would like to do a case insensitive checking i would need an alternative for thisif selectedfile hassuffixjpg selectedfile hassuffixjpg or jpg jpg jpg is there any short way to do this i do not see how i could apply caseinsensitivecompare in this situation,['objective-c'] +335192,saving word docx files as pdf i am using openxml to create word docx files i would like to save these documents once they are created as pdf files is there a way i can do this in openxml i assume the answer is no if it is no is there a recommended library or tool i can use to save print docx files as pdf programatically in net i looked at sharppdf pdfsharp and it seems this library is only for generating pdfs from scratch not saving docx as pdfcan i somehow print to an installed pdf printer either cute pdf or the pdf printer built in to windows 7 in a fully automated fashionupdate looking for free with nonviral license and preferably does not require additional installations,"['c#', '.net']" +335213,difference between documentaddeventlistener and windowaddeventlistener what is the difference between documentaddeventlistener and windowaddeventlistener in javascriptwhile using phonegap it has some default js code that uses documentaddeventlistener but i have my own code which uses windowaddeventlistener and i am wondering which one is better to use an example of thisfunction onbodyload documentaddeventlistenerdeviceready ondeviceready false documentaddeventlistenertouchmove preventbehavior false windowaddeventlistenershake shakeeventdidoccur false,['javascript'] +335262,when is it possible to call finalize in thispose i was browsing the decompiled source code for a dll in reflector and i came across this c codeprotected virtual void thisposemarshalasunmanagedtypeu1 bool flag1 if flag1 thisclassname else basefinalize my first reaction was what i thought you could not call the finalizer manuallynote the base type is objectto be sure it was not a reflector quirk i opened up the method in ilspy it generated similar codei went to google to confirm my new thiscovery i found the documentation for objectfinalize and this is what it saidevery implementation of finalize in a derived type must call its base types implementation of finalize this is the only case in which application code is allowed to call finalizenow i do not what to think it might be because the dll was compiled with c note i could not find the implementation of thispose maybe it is autogenerated it might be a special allowance for the ithisposablethispose method it might be a flaw in both decompilerssome observationsi could not find the implementation of thispose in the source code maybe it is autogeneratedreflector shows a method named classname it seems as though this method might not actually be the finalizer but the c destructor or even an ordinary methodis this legal c if so what is different about this case if not what is actually happening is it allowed in ccli but not c or is it just a glitch in the decompiler,"['c#', '.net']" +335298,android how to animate an activity transition when the default back button is pressed in my activity i have a button with the following click listener that is working greatfinal imagebutton startoverbutton imagebutton findviewbyidridstart over buttonstartoverbuttonsetonclicklistenernew viewonclicklistener override public void onclickfinal view v finishgo back to the previous activity overridependingtransitionranimcomming in ranimcomming out it animates the return to the previous activity the way i want however when the user presses the android default back button the animation is not triggered my question is where should i put the animation code overridependingtransitionranimcomming in ranimcomming out so that this animation will be triggered both when the user clicks on my button and in the default android back buttonas a naive try i have tried to put the overridependingtransitionranimcomming in ranimcomming out line of code in the ondestroy method but it did not workthank you in advance,['android'] +335305,getqueuedcompletionstatus cannot dequeue io from iocp if the thread which originally issued the io is blocking in readfile under windows 8 my app stop working after switching to windows 8 i spend hours to debug the problem found out iocp behave differently between windows 8 and previous versions i extract the necessary code to demonstrate and reproduce the problemsocket slistendword winapi workerproclpvoid lpparam ulong ptr dwkey dword dwtrans lpoverlapped lpol whiletrue getqueuedcompletionstatushandlelpparam dwtrans dwkey lpoverlappedlpol wsa infinite printfdequeued an ion dword winapi startproclpvoid lpparam wsadata wsadata if wsastartup0x202wsadata0 return 1 slisten wsasocketaf inet sock stream 0 null 0 wsa flag overlapped sockaddr in si zeromemorysisizeofsi sisin family af inet sisin port ntohs19 sisin addrs uns addr inaddr any ifbindslisten sockaddrsi sizeofsi socket error return 1 listenslisten somaxconn handle hcompletion createiocompletionportinvalid handle value 0 0 0 createiocompletionporthandleslisten hcompletion dword0 0 createthreadnull 0 workerproc hcompletion 0 null return 0dword winapi acceptproclpvoid lpparam dword dwbytes lpoverlapped pollpoverlappedmallocsizeofoverlapped zeromemorypolsizeofoverlapped socket sclient wsasocketaf inet sock stream 0 null 0 wsa flag overlapped bool b acceptexslisten sclient malloc sizeofsockaddr in 16 2 0 sizeofsockaddr in 16 sizeofsockaddr in 16 dwbytes pol ifb wsagetlasterror wsa io pending return 1 handle hpipecreatenamedpipeapipetestpipepipe access duplexpipe type byte pipe readmode byte pipe waitpipe unlimited instances409640969null byte chbuf1024 dword cbread createfileapipetestpipe generic read generic write 0null open existing 0 null readfilehpipechbuf1024 cbreadnull return 0int main printf starting server on port 19 waitforsingleobjectcreatethreadnull 0 startproc null 0 nullinfinite createthreadnull 0acceptproc null 0 null printf donen sleep10 return 0this program listen on port 19 and issue an async accpet then reading a blocking pipe i have tested this program on windows 7 8 xp 2003 2008 after telnet 127001 19 dequeued an ion will printed on console except windows 8 the point is the thread which originally issued the async operation must not blocking in readfile or getqueuedcompletionstatus will never dequeue that io until readfile returns on windows 8i also tested using scanf instead of reading pipe the results are same since scanf will call readfile to read console eventually i do not know if readfile is the only function affected or there may be other functionswhat i can think of is using a dedicated thread to issue async operations and all business logic communicate with that dedicated thread to perform acceptsendrecv but extra layer means extra overhead is there any way to achieve the same performance as previous versions of windows on windows 8,['c++'] +335381,jquery when behaves differently depending on number of arguments when behaves differently depending on whether one or more deferred object are passed to it this behaviour is documented in the docs but the problem is that it is forcing me to write two different code paths function foo dfds whenapplythis dfdsdonefunction consolelogarguments case ifoogetjson getjson output what i would come to expect array3 array3case iifoogetjson output the original unwrapped deferreds arguments object success objectany way to elegantly handle this without resorting to checking the length of dfd or the type of arguments,"['javascript', 'jquery']" +335389,neural network training with pybrain would not converge i have the following code from the pybrain tutorialfrom pybraindatasets import superviseddatasetfrom pybrainsupervisedtrainers import backproptrainerfrom pybraintoolsshortcuts import buildnetworkfrom pybrainstructuremodules import tanhlayerds superviseddataset2 1dsaddsample00 0dsaddsample01 1dsaddsample10 1dsaddsample11 0net buildnetwork2 3 1 biastrue hiddenclasstanhlayertrainer backproptrainernet dsfor inp tar in ds print netactivateinp tarerrors trainertrainuntilconvergencefor inp tar in ds print netactivateinp tarhowever the result is a neural network that is not trained well when looking at the error output the network gets trained properly however it uses the continueepochs argument to train some more and the network is performing worse again so the network is converging but there is no way to get the best trained network the documentation of pybrain implies that the network is returned which is trained best however it returns a tuple of errorswhens etting continueepochs to 0 i get an error valueerror max arg is an empty sequence so continueepochs must be larger than 0is pybrain actually maintained because it seems there is a big difference in documentation and code,['python'] +335424,how to configure remote hbase server to my java application i am very new to hadoop and hbase hbase is completely different from rdmsi need to create a table and load it in hbase using mapreduce my6 hadoop and hbase are in diiferent server i will access to that server using putty using ip address username and password in normal java api we can configure usingdriver nameusernamepassword but in hbase how i can configure ip address usernamepassword to my application which is in my machinei checked with hbasesitexml please can any one help me to configure my application with the ipaddress username and passowrd,['java'] +335432,inserting sheets in spreadsheet through c i have created a a project that reads different files and puts then in different sheets with a spreadsheet i have used open office calc spreadsheet therefore used the following code to open a blank file public xspreadsheet getspreadsheetint nindex xcomponent xcomp xspreadsheets xsheets xspreadsheetdocumentxcompgetsheets xindexaccess xsheetsia xindexaccessxsheets xspreadsheet xsheet xspreadsheetxsheetsiagetbyindexnindexvalue return xsheet i call a sheet to be used like soxspreadsheet newsheet getspreadsheetsheetindex xcompwhere xcomp isstring filepathway filectempblankods propertyvalue propvals new propertyvalue0xcomponent ocalcudoc odesktoploadcomponentfromurlfilepathway blank 0 propvalshowever my problem is that file blankods needs to be set up with the number of sheets that will be required already inserted into the spreadsheet before the application is run this is not ideal as the number of sheets needed is not always known is there a way of inserting sheets from within my applicationany help would be appreciated,['c#'] +335447,getright getleft gettop returning zero i am using following code but all methods are returning zero value i know that to get the coordinates of the view our view should be drawn that why i am using the code in onresume method but still not working any idea overridepublic void onresume superonresume systemoutprintlnonresume systemoutprintlntab1 left btn tab7 getleft systemoutprintlntab1 top btn tab7gettop systemoutprintlntab1 right btn tab7getright systemoutprintlntab1 bottom btn tab7getbottom,['android'] +335486,cannot detect sony xperia in eclipse i am totally new at testing apps on devices especially the sony xperia i am testing apps using the android emulator but i have now a sony xperia first i have connected the device to the laptop via usb but the laptop could not detect my phone is a driver necessary for eclipse to detect the phone,['android'] +335533,switching avcapturesession preset when capturing a photo my current setup is as follows based on the colortrackingcamera project from brad larsoni am using a avcapturesession set to avcapturesessionpreset640x480 for which i let the output run through an opengl scene as a texture this texture is then manipulated by a fragment shaderi am in need of this lower quality preset because i want to preserve a high framerate when the user is previewing i then want to switch to a higher quality output when the user captures a still photofirst i thought i could change the sessionpreset on the avcapturesession but this forces the camera to refocus which break usabilitycapturesession beginconfigurationcapturesessionsessionpreset avcapturesessionpresetphotocapturesession commitconfigurationcurrently i am trying to add a second avcapturestillimageoutput to the avcapturesession but i am getting an empty pixelbuffer so i think i am kinda stuck heres my session setup code add the video frame outputcapturesession beginconfigurationvideooutput avcapturevideodataoutput alloc initvideooutput setalwaysthiscardslatevideoframesyesvideooutput setvideosettingsnsdictionary dictionarywithobjectnsnumber numberwithintkcvpixelformattype 32bgra forkeyidkcvpixelbufferpixelformattypekeyvideooutput setsamplebufferdelegateself queuethispatch get main queueif capturesession canaddoutputvideooutput capturesession addoutputvideooutputelse nslogcould not add video outputcapturesession commitconfiguration add still outputcapturesession beginconfigurationstilloutput avcapturestillimageoutput alloc initifcapturesession canaddoutputstilloutput capturesession addoutputstilloutputelse nslogcould not add still outputcapturesession commitconfiguration start capturingcapturesession setsessionpresetavcapturesessionpreset640x480ifcapturesession isrunning capturesession startrunningand here is my capture method voidprepareforhighresolutionoutput avcaptureconnection videoconnection nil for avcaptureconnection connection in stilloutputconnections for avcaptureinputport port in connection inputports if port mediatype isequalavmediatypevideo videoconnection connection break if videoconnection break stilloutput capturestillimageasynchronouslyfromconnectionvideoconnection completionhandler cmsamplebufferref imagesamplebuffer nserror error cvimagebufferref pixelbuffer cmsamplebuffergetimagebufferimagesamplebuffer cvpixelbufferlockbaseaddresspixelbuffer 0 int width cvpixelbuffergetwidthpixelbuffer int height cvpixelbuffergetheightpixelbuffer nslogi x i width height cvpixelbufferunlockbaseaddresspixelbuffer 0 width and height turn out to be 0i have read through the documents of the avfoundation documentation but it seems i am not getting something essential,"['iphone', 'ios']" +335577,expand shrink div on hover out with jquery i am looking for a jquery plugin to expand div elements so as to reveal their overflow if any on hover illustrationthe plugin should work on relatively positioned divs which i guess implies that you create a copy of the div set its positioning to absolute then figure out where to place itis there such a plugin already available out there,"['jquery', 'html']" +335589,java programming test for interview here is a programming test used in a job interview i find it has a very strange nonoo perspective and wonder why anyone would approach a constructor from this perspective as a very experienced java programmer i immediately question the ability of the individual who wrote this code and the strange perspective of the questioni find these strange out of context questions on interviews thisturbing i would love feedback from other experienced oo java programmerscomplete the solver constructor so that a call to solveall return a list with 2 values including the square root and the inverse of the integer passed as parameterpublic interface mathfunction double calculatedouble xpublic class solver private listmathfunction functionlist public solver complete here public listdouble solvealldouble x listdouble result new arraylistdouble for mathfunction function thisfunctionlist resultaddnew doublefunctioncalculatex return result,['java'] +335603,fake user agent for iframe i am new to javascript i have found this code to change user agent using javascriptvar originalnavigator navigatornavigator new objectnavigator definegetter useragent function return customvar iframeiframe idframe namewidget src width100 height400 marginheight0 marginwidth0 frameborderno scrollingnoiframe documentwriteuseragent header sent navigatoruseragent iframe this code works returns fake user agent though how will i set same fake user agent for iframe here is fiddle of what i am up to,"['javascript', 'jquery']" +335639,undocumented gcc extension vla in struct while reading the clang documentation i came across the following intriguing tidbit 1clang does not support the gcc extension that allows variablelength arrays in structures this is for a few reasons one it is tricky to implement two the extension is completely undocumented and three the extension appears to be rarely used note that clang does support flexible array members arrays with a zero or unspecified size at the end of a structurehow can this extension be used my understanding is that using alloca within a constructor causes the stack pointer to be restored at the end of the calling function which in this case would be the constructor not at the end of the enclosing structthanks for the help,['c++'] +335643,how should deep copy work ok when doing a deep copy obviously references should not be copied however if the object being copied contains objects that themselves are references to to the same object should that be maintained or should the data just be copiedexamplepublic class program public void mainstring args person person new person personsetnamesimon listperson people new arraylistperson peopleaddperson peopleaddperson peopleaddperson listperson otherpeople magicdeepcopyfunctionpeople otherpeopleget0setnameadam should this output adam or simon systemoutprintlnotherpeopleget1 i can see arguments for both but i am wondering what the consensus was,['java'] +335659,download file html content with servicestack i am using service stack for a simple web applicationin this app i need to export some content to excel so this is the approach i tooki get the html content of a table with jquery a get the html contentof a table and send to the servicethe service write the content to a file with some cssusing the same service but with a get method i read the file andmake the download with contenttypeapplicationvndmsexceli used this approach without service stack in other times and worked well the xls file had the right content and some colorsnow when i get the file using get method ie visiting the url with the browser the file contents are badservicestack let download with some formats html csv jsv json xmlthe html format shows up a default report page the only format that works a little is jsvmy question is how can i download the file like plain html filesome codepublic class excelservice restservicebaseexcel public override object onget excel request string file requestnombre responseclear httpresult res new httpresult resheadershttpheaderscontenttype applicationvndmsexcel resheadershttpheaderscontentthisposition attachment filenamefilexls string archivo systemiofilereadalltexttmpfilehtml resresponse archivo return res thanks in advance,['c#'] +335662,how to implement fluid font size using pure css i have text wrapped in divs and would like to make the whole thing fluid including the fontsize of the text ie the text resizes itself in response to the size of the containing elementi came across a javasript css solution but just wondering if it is possible to do so with pure css,"['html', 'css']" +335708,why am i getting mimetype of csv file as applicationoctetstream i am working on a php application that must import an excel file into mysql so i need to convert the excel file to csv format but when i want to get its type using filesomethingtype i get applicationoctetstream as its mimetypei think there is something wrong here because i gathered the list below as a csv file mimetype textcommaseparatedvalues textcsv applicationcsv applicationexcel applicationvndmsexcel applicationvndmsexcelwhats the matter,['php'] +335757,how do i create an image in pil using a list of rgb tuples suppose i have a list of pixels represented as tuples with 3 rgb values in a list that looks like listimgetdata like this0255255255382958how do i create a new image using rgb values each tuple corresponds to a pixel in this format thanks for your help,['python'] +335758,handling presence in strophejsbased chat application is there any existing solution which provides the presence handling for chat app based on strophejsi have simple chat application based on strophejs i would like to show only the users who are online and dynamicaly alter the list i was wondering whether there is any existing solution possibly strophe plugin which handles this if there is no such thing whats the bestsimplest way to implement it,['javascript'] +335762,how to avoid duplicate interface code since interfaces cannot contain implementation that seems to me to lead to code duplication in the classes that inherit from the interface in the example below pretend that let us say the first 10 or so lines that setup reading from a stream are duplicated try not to focus on the wording here but instead focus on the concept of how easy it is to create duplicate code between each class for examplepublic interface idatabaseprocessor void processdatastream streampublic class sqlserverprocessor idatabaseprocessor void processdatastream stream setting up logic to read the stream is duplicated code public class db2processor idatabaseprocessor void processdatastream stream setting up logic to read the stream is duplicated code i realize that using an abstract base class for processdata and adding nonabstract members is one solution however what if i really really want to use an interface instead,['c#'] +335763,ruby code not in any method general ruby questionin ruby i frequently see code that is inside a class but not part of a method for exampleclass doodad attr accessor fooendorclass teacher activerecordbase has many studentsendi think attr accessor and has many are methods getting invoked with the foo or students arguments respectively is that right if so when do these kinds of statements get executed i tried thisclass doodad attr accessor foo puts i happened foo 7endit does not seem to run these a part of the new method doodadnewddfoutputs nil and never spits out any puts stuffhow exactly does all that work,['ruby'] +335780,how do i create a cgrect from a cgpoint and cgsize i need to create a frame for a uiimageview from a varying collection of cgsize and cgpoint both values will always be different depending on users choices so how can i make a cgrect form a cgpoint and a cgsize thank you in advance,"['ios', 'objective-c']" +335796,alternative to dex2jar and jdgui it seems that either dex2jar andor jdgui gives bad deobfuscation even for the simplest code of ifelse condition they show a whiletrue loop which has a return on its first line are there any other freeware apps that do the same work of deobfuscation maybe something that can also use the mapping file of proguard,"['java', 'android']" +335800,javascript what is the best method when creating chainable functions edit here is an attempt to make my question simplerreturn thissomefunc return xthissomefunc what do i have to put in for x to make this statement truei am trying to create a function that can be chained let me write some hypothetical code any syntax errors just ignore i am typing this fast and this is just concept code assume that all functions are either defined locally or globally test function thissomefunc function thisretest function code code thissomefunc2 function code return thissomefuncthis function allows me to chain testretest but what i want to do is return more than one itemtest function thissomefunc function thisretest function code code thissomefunc2 function code return xthissomefunc what do i put for x nextthis i want to do this to access another function that test offers testnextsomefunc2 so my problem is this i still want to be able to chain like this testretest but i have to do it like this testxretest in my code what is the name that i can put instead of x to accomplish this and is this even possible i have tried 0 and default already thanks for the help,['javascript'] +335849,mysql database connection management in pdo i am very new to phpmysql and i am learning things as i go one of the newer things i have learned is that there is a maximum number of connections that can be made to a database for a given username when i first started building my website on wordpress i was using the old mysql query commands i never had to make a connection to the mysql database because wordpress keeps an active connection just by being logged in on the website when i decided to switch all my mysql queries over to the pdo extension i could no longer take advantage of wordpress active connection and had to start my own database connections i did this in a separate php config file that i included in every page that ran a script the php code looks like thistry dbh new pdomysqlhosthostdbnamedbname user passcatchpdoexception e echo select db error egetmessage brunfortunately now i constantly get the following error sqlstate420 1203 user already has more than max user connections active connectionsbased on some online research i tried various different methods to fix this first i tried to set the database connection to null at the end of each script though this should be php pdos default then i tried to set each statement handle to null after each query of the database this was a hopeless endeavor and finally i tried using a persistent connection by changing the following line in my config filedbh new pdomysqlhosthostdbnamedbname user pass arraypdoattr persistent truenone of this seems to work and i still get the same exact error the site when ready needs to be able to handle 100200 people per day entering a myriad of different data even if i can figure out how to take advantage of wordpress active connection using pdo that would be a good start i would appreciate any help i can getupdatei am running show full processlist as a mysql query in one of my codes and i am getting very strange behavior this is the first part of my script not including the show full processlist queryphpinclude configphpifisset postsubmitget current user loginglobal current usercurrent user wp get current userulog current useruser logintablename cc cc ulogtablename db db ulogtablename misc misc ulogtablename cash cash ulogtry dbhexeccreate table if not exists tablename cc id bigint100 not null auto increment primary keyid accnt text20 cc num text4 cc amnt decimal82 cc app text20 cc date varchar10 cc time varchar10 dbhexeccreate table if not exists tablename db id bigint100 not null auto increment primary keyid accnt text20 db num text20 db amnt decimal82 db date varchar10 db time varchar10 dbhexeccreate table if not exists tablename misc id bigint100 not null auto increment primary keyid accnt text20 misc item text10 misc amnt decimal82 misc date varchar10 misc time varchar10 dbhexeccreate table if not exists tablename cash id bigint100 not null auto increment primary keyid accnt text20 cash amnt decimal82 cash time varchar10catchpdoexception e echo create tables error egetmessage if i try to run the show process list query outside of the if statement i get a result stating that i have one active connection however if i try to run the show full processlist query inside the if statement i get the error that i have exceeded my number of connections based on this result i figured perhaps my include line on the very top of the page may be causing an issue when the user submits their form essentially trying to connect to the database twice so i moved it inside the if statement but that made no difference either i am at a loss as to why this happeningupdateanswer still some questionsi figured out what my issue was upon completion of one of my scripts there is a javascript command to pop up a window where another script will print out an invoice for them that second script also tries to make a connection to the database using the config file the form the user is working with is dynamic they can put in as little or as many data sets as they wish so when the user inserts a small number of data the pdo queries are performed very fast and there is no conflict between the number of connections however if the user inputs a lot of data then it takes a significant more amount of time and the maximum number of connections is reached by the server the issue really resides in a combination of poor server environment and inefficient queries on my part still learning php the only solution i can think of at this point is to put a longer sleep on my second script already using a 3 second sleep to let the other script catch up but at some point this will just take too long i am not sure if you guys have any better suggestions,"['php', 'mysql']" +335858,what is the originalpackage androidmanifest attribute used for i used apktool to extract the manifest of the default browser on jelly bean and this line appeared in the manifest manifest packagecomgoogleandroidbrowser originalpackage androidnamecomandroidbrowser manifestany idea what this is used for the,['android'] +335860,decorator in java i see about decorator example in pythondef makeboldfn def wrapped return b fn b return wrappeddef makeitalicfn def wrapped return i fn i return wrappedmakeboldmakeitalicdef hello return hello worldprint hello returns bihello worldiband got some curious how it can be implement in java so i search and got some example using decorator design patternpublic class main public static void mainstring args wrapper word new boldwrappernew italicwrapper thisplay bihello worldib systemoutprintlnwordmakehello world public interface wrapper public string makestring strpublic class boldwrapper implements wrapper private wrapper wrapper public boldwrapper public boldwrapperwrapper wrapper thiswrapper wrapper override public string makestring str ifwrapper null str wrappermakestr return b str b public class italicwrapper implements wrapper private wrapper wrapper public italicwrapper public italicwrapperwrapper wrapper thiswrapper wrapper override public string makestring str ifwrapper null str wrappermakestr return i str i how do i make this like the python example above using a java annotation like this onepublic class main public static void mainstring args boldwrapper italicwrapper string str hello world thisplay bihello worldib public interface boldwrapper public void wrap default b str bpublic interface italicwrapper public void wrap default i str ii got some problem when i tried to make the sample the problem is i do not know how i can pass the str value from the main method to the boldwrapper and italicwrapper so it can concatenate and how to return it so the main method can thisplay the result that has been concatenate please advise if there is something wrong with my understanding of annotation,['java'] +335880,javaxnamingcommunicationexception simple bind failed when trying to connect to the ldap server using a simple ldap application i am gettina error which says simple bind failed i am assuming this is realted to some sort of bind i have a bind property in on of the propery file for a differeent application but am not sure how to pass on that property to this programdo i need to add any further detailscode import javaxnamingdirectory import javaxnaming import javautilvector import javautilenumeration import javautilproperties public class searchldap public static void mainstring args string base string filter objectclass properties env new properties envputdircontextinitial context factorycomsunjndildapldapctxfactory envputdircontextprovider urlldapsmisguidedcomau343 try systemoutprintln11 dircontext dc new initialdircontextenv systemoutprintln22 searchcontrols sc new searchcontrols scsetsearchscopesearchcontrolsobject scope namingenumeration ne null ne dcsearchbase filter sc while nehasmore searchresult sr searchresult nenext systemoutprintlnsrtostringn dcclose catch namingexception nex systemerrprintlnerror nexgetmessage nexprintstacktrace the error which i am getting is error 11error simple bind failed xnet808javaxnamingcommunicationexception simple bind failed misguidedcomau343 root exception is javaxnetsslsslhandshakeexception sunsecurityvalidatorvalidatorexception pkix path building failed sunsecurityprovidercertpathsuncertpathbuilderexception unable to find valid certification path to requested target at comsunjndildapldapclientauthenticateldapclientjava215 at comsunjndildapldapctxconnectldapctxjava2740 at comsunjndildapldapctxinitldapctxjava316 at comsunjndildapldapctxfactorygetusingurlldapctxfactoryjava193,['java'] +335884,set the headers using pandasread csv i have a csv file that i read into a dataframe using the pandas api i intend to set my own header instead of the default first row i also get rid of some of the rows how do i best achieve thisi tried the following but this did not work as expectedheader rowcol1col2col3col4 col1 col2 note the header has duplicate column valuesdf pandasread csvcsv file skiprows012345 namesheader rowthis gives following error file third partypypandasioparserspy line 187 in read csvfile third partypypandasioparserspy line 160 in readfile third partypypandasioparserspy line 628 in get chunkfile third partypypandascoreframepy line 302 in init file third partypypandascoreframepy line 388 in init dictfile third partypypandascoreinternalspy line 1008 in form blocksfile third partypypandascoreinternalspy line 1036 in simple blockifyfile third partypypandascoreinternalspy line 1068 in stack dictindexerror index out of boundsi then tried settings the columns via dfcolumns header rowbut this errored out probably because of duplicate column valuesfile enginespyx line 101 in pandas enginesdictindexengineget loc third partypypandassrcenginesc2498file enginespyx line 107 in pandas enginesdictindexengineget loc third partypypandassrcenginesc2447exception index values are not unique occurred at index entityi am using pandas 073 versionfrom the documentation names arraylike list of column namesi am sure i am missing something simple here thanks for any help here,['python'] +335892,how to check if an element is overlapping other elements i have two div elements each of them have 450px width and height how do i check if the first div is overlapping the second divi have tried to use javascript hittest but it is a little bit complicated since i am trying to find out how it actually work i would like to get started with a simpler codei found out that i can use getclientrects to get the boundary of an element but i am not exactly sure how to compare boundariesplease advise me,['javascript'] +335896,boost context library in the most recent version of the boost the new library context appeared after reading the documentation i understood what it does but can hardly see the usecases what are the benefits of using this library for which tasks you could recommend to use it,['c++'] +335907,nlog hangs in trace multithreading issue symptoms is hanging of application hosted in iis 7when attaching with debuging found that there are 100 threads with stacks like thisnlogdllnlogtargetstargetwriteasynclogeventnlogcommonasynclogeventinfo logevent 0x54 bytes nlogdllnlogloggerimplwritetotargetwithfilterchainnloginternaltargetwithfilterchain targetlisthead nloglogeventinfo logevent nlogcommonasynccontinuation onexception 0x8b bytes nlogdllnlogloggerimplwritesystemtype loggertype nloginternaltargetwithfilterchain targets nloglogeventinfo logevent nloglogfactory factory 0xee bytes nlogdllnlogloggerwritetotargetsnlogloglevel level string message object args 0x14 bytes nlogdllnlogloggertracesystem canonlongstring message system canon argument1 long argument2 0x90 bytes my app code one withmscorlibdllsystemcollectionsgenericdictionarynloglayoutslayoutstringfindentrynloglayoutslayout key 0xd0 bytes mscorlibdllsystemcollectionsgenericdictionarysystem canonsystem canontrygetvaluesystem canon key out system canon value 0x14 bytes nlogdllnloglayoutssimplelayoutgetformattedmessagenloglogeventinfo logevent 0x81 bytes nlogdllnlogtargetsfiletargetgetbytestowritenloglogeventinfo logevent 0x1c bytes nlogdllnlogtargetsfiletargetwritenlogcommonasynclogeventinfo logevents 0x308 bytes nlogdllnlogtargetstargetwriteasynclogeventsnlogcommonasynclogeventinfo logevents 0x258 bytes nlogdllnlogtargetswrappersasynctargetwrapperprocesspendingeventsobject state 0x1e6 bytes mscorlibdllsystemthreadingexecutioncontextrunsystemthreadingexecutioncontext executioncontext systemthreadingcontextcallback callback object state bool ignoresyncctx 0xdc bytes mscorlibdllsystemthreading timercallbackperformtimercallbackobject state 0x97 bytes my app code and one withmscorlibdllsystemcollectionsgenericdictionarynloglayoutslayoutstringinsertnloglayoutslayout key string value bool add 0x1e0 bytes nlogdllnloglogeventinfoaddcachedlayoutvaluenloglayoutslayout layout string value 0x6c bytes nlogdllnloglayoutslog4jxmleventlayoutgetformattedmessagenloglogeventinfo logevent 0xf5 bytes nlogdllnlogtargetstargetprecalculatevolatilelayoutsnloglogeventinfo logevent 0xb8 bytes nlogdllnlogtargetswrappersasynctargetwrapperwritenlogcommonasynclogeventinfo logevent 0x23 bytes nlogdllnlogtargetstargetwriteasynclogeventnlogcommonasynclogeventinfo logevent 0x151 bytes nlogdllnlogloggerimplwritetotargetwithfilterchainnloginternaltargetwithfilterchain targetlisthead nloglogeventinfo logevent nlogcommonasynccontinuation onexception 0x8b bytes nlogdllnlogloggerimplwritesystemtype loggertype nloginternaltargetwithfilterchain targets nloglogeventinfo logevent nloglogfactory factory 0xee bytes nlogdllnlogloggerwritetotargetsnlogloglevel level string message object args 0x14 bytes nlogdllnlogloggerdebugwerpcontrollercommoninterfacesentityeventactionsystem canonstring message werpcontrollercommoninterfacesentityeventaction argument1 system canon argument2 0x8d bytes my app code this situation occurs some times may be one time a week and i do not have exac scenario to reproduce ithow can i fix this is it bug in nlog or maybe some my misuses or misconfigure,"['c#', '.net']" +335909,glassfish 312 jdbcrealm configuration hi i have read glassfish 312s jdbcrealm has a new password encryption algorithm field what is it for and googled for similar topics but it seems no definitive answer has been publishedin short i have a jdbc realm working in glassfish 3 when i upgrade to 312 same configuration does not work according to the previous thread i have set the jaascontext to jdbcdigestrealm in addition to jdbcrealm which also does not work set the digest algorithm to md5 i used md5 in v 3 and it worked for password encryption algorithm i tried blank and hex both do not workcould someone please tell me how i should configure my credentials table is based on mysql with md5 hashed passwords according to,['java'] +335915,jsoup remove nested tags but keep text i have html in a set of elements so there may be other items like this ba titlesan franciscotwin peakslake mercedtwin peaksabbut i would like to clean it up with jsoup like thisbtwin peaksbwould using a whitelist be the best idea,"['java', 'html']" +335927,whats the reason of fimgapistretchstretch failed in android in logcat it always log out fimgapistretchstretch failedit appears especially when i am using listviewbut it never crash or force closeanyone knows what the reasons,['android'] +335954,c destructors with vectors pointers as far as i know i should destroy in destructors everything i created with new and close opened filestreams and other streamshowever i have some doubts about other objects in cstdvector and stdstrings are they destroyed automaticallyif i have something likestdvectormyclass of pointers to classes what happens when the vector destructor is calledwould it call automatically the destructor of myclass or only the vector is destroyed but all the objects it contains are still existant in the memorywhat happens if i have a pointer to another class inside a class sayclass a classb band class a is destroyed at some point in the code will class b be destroyed too or just the pointer and class b will be still existent somewhere in the memory,['c++'] +335989,how to optimise below query select r uusername from reservation as r join users as you where uid ruser id and daterbx date date20120822 and daterbx date date20120822 and rstatus1 order by rid descbx date booked dateit takes more than 8 secs to run this query i have more than 50 records in reservation table and 40 records in users tablei have not done any optimization to my database tables nothing at all just pks only how can i optimize this query what are the options to increase the performance of this databasethankstable reservationcreate table reservation id int10 unsigned not null auto increment user id int10 unsigned not null comment user id tx id varchar15 not null comment transaction id tx date datetime not null comment transaction date bx date date not null comment booking date theater id int10 unsigned not null comment theater id movie id int10 unsigned not null comment movie id showtime id int10 unsigned not null comment show time id category id int10 unsigned not null comment category id full tickets tinyint2 unsigned not null comment number of full tickets half tickets tinyint2 unsigned not null comment number of half tickets no seats tinyint3 unsigned not null comment no of seats full ticket price decimal102 unsigned not null default 0 comment full ticket price half ticket price decimal102 unsigned not null default 0 comment half ticket price amount decimal102 unsigned not null default 0 comment total amount method tinyint1 unsigned not null comment payment method 1web 2mobile 3theater paymentgateway id int10 unsigned not null comment payment gateway id payment type tinyint1 unsigned not null default 0 comment 0 cash 1credit card status tinyint1 unsigned not null comment status 0provisional 1booked 2canceled 3auto canceld comment text reservation type tinyint1 unsigned not null comment reservation type 0complimentary 1advamce booking 2mobile booking 3 theater offline booking complimentary type tinyint1 unsigned not null comment 0none 1loyalty rewards 2marketing 3promotional 4show blocking 5vip description mediumtext not null comment complimentary description title varchar10 default null comment title fname varchar255 default null comment first name lname varchar255 default null comment last name gender tinyint1 unsigned default null comment gender 0male 1female dob date default 0 comment date of birth nic varchar10 default null comment nic no address text comment address line 1 city varchar255 default null comment city thistrict varchar50 default null comment thistrict country varchar255 default null comment country mobile varchar15 default null comment mobile no contact phone varchar15 default null comment fixed land phone number email varchar255 default null comment email address timer int4 unsigned not null primary key id key user id index user id engineinnodb auto increment5706 default charsetutf8table userscreate table users id int11 not null auto increment title varchar100 not null name varchar255 not null default last name varchar255 not null username varchar150 not null default email varchar100 not null default password varchar100 not null default usertype varchar25 not null default block tinyint4 not null default 0 sendemail tinyint4 default 0 registerdate datetime not null default 0 0 lastvisitdate datetime not null default 0 0 activation varchar100 not null default params text not null gender varchar6 not null date of birth date not null nic no varchar10 not null address varchar255 not null city varchar100 not null thistrict varchar100 not null mobile varchar15 not null subscribe sms tinyint1 not null contact phone varchar15 not null newsletter subscribe tinyint1 not null primary key id unique key username username key usertype usertype key idx name name key idx block block key email email engineinnodb auto increment34265 default charsetutf8,"['mysql', 'sql']" +335992,emberjs techstack for search engine crawlable apps i read quite some stuff about clientside javascript apps and search engine bot crawling approachesi found two general approachesworkflow 1preconditionthe whole web app degrades gracefully and is usable without javascript so it is visible for search engine bots to crawluser comes from a google search to a specific topicthe topic is loaded as fast as possible in plain htmljs app framework is loaded in the backgroundas soon as it is ready js app framework takes over all the actions and routes and so onworkflow 2preconditionthe server backend is designed after googles ajaxcrawling guides and returns to escaped fragment urls eg wexamplecomajaxhtml escaped fragment keyvalue plain html as far as i understood something like could be used for that to make sure there is no frontend code duplicationgoogle shows the ajax url in their resultsa request is made using the ajax url the emberjs application is initialized and depending on the url the desired state is loaded questionwhat should a crawlable emberjs application stack look like to offer server side rendering for search engine bots and frontend jsframework goodnesswhat is recommended by the emberjs core developers to achieve thiseg node emberjs phantomjs x or rails emberjs y or playframework zi know there might be a lot of ways to get there but i feel it would be good to use stackoverflow to filter out common approachessidenotei already had a look at some js frameworks that want to create such a full stack out of the box to name these here nice approach but still alpha not clear how production ready specially the backend somehow different but also interesting if they get security right also preview statei especially ask about emberjs because i like their approach and i think the team behind it is definitely capable of building one of the best frameworks,"['javascript', 'ruby-on-rails']" +336022,how to use the new affix plugin in twitters bootstrap 210 the bootstrap documentation on that topic is a little confusing to me i want to achieve similar behaviour like in the docs with the affix navbar the navbar is below a paragraph page heading and upon scrolling down it should first scroll along until reaching the top of the page and then stick there fixed for further scrolldownsas jsfiddle does not work with the navbar concept i have set up a separate page for usage as a minimal example drrnavbarhtmli use this as my navbardiv classnavbar affixtop dataspyaffix dataoffsettop50 div classnavbarinner div classcontainer div claspan12 a classbrand hrefmy branda this is my navbar div div container div navbarinner div navbar i thinkg i would want dataoffsettop to be of value 0 since the bar should stick to the very top but with 50 there is at least some effect watchableif also put the javascript code in place script documentready function navbaraffix scriptany help appreciated,['css'] +336033,boxing the same enum member produces a larger integer when it is passed to a method i am using clangs primitiveboxing feature to pack an enumeration member into nsnumberthe boxed enums section of the clang doc about this says that the compiler boxes enumeration members into integers unless the type is specifiedfunnily enough i get different sizes of integers depending on the way i am passing the enumeration member to the method i have been able to isolate the case down to the following codetypedef enum myenum myenummember1 10 myenum voidtestenumerationboxing nsnumber numbera self testa nsnumber numberb self testbmyenummember1 cfnumbertype numbertypea cfnumbergettype bridge cfnumberref numbera cfnumbertype numbertypeb cfnumbergettype bridge cfnumberref numberb nslogcf number type for a lu b lu numbertypea numbertypeb nsnumber testa return myenummember1 nsnumber testbmyenumenummember return enummemberthe console output is cf number type for a 3 b 4 the first one is kcfnumbersint32type the second one is kcfnumbersint64typeif i change declaration to typedef enum myenum int i see the same result for both kcfnumbersint32typewhy does the size of the integer differ between the two methods of boxing,['objective-c'] +336049,move an applet without reloading it i want to move an applet from a div element to another div element without reloading it i do not want to use absolute positioning is there a way to do this i try this but it is not workinghtml head script typetextjavascript function todiv1 var appletelt documentgetelementbyidmyapplet documentgetelementbyiddiv1appendchildappletelt function todiv2 var appletelt documentgetelementbyidmyapplet documentgetelementbyiddiv2appendchildappletelt script head body div id myapplet applet width200 height200 codebase codesmileyclass namesmiley applet div div iddiv1div div iddiv2div div button onclicktodiv1todiv1button button onclicktodiv2todiv2button div bodyhtmlyou can try your answer on this fiddlethe solution proposed by goldenparrot with outerhtml works but not on all the browser at least firefox esr as stated in the kritzikratzi answer and in the biziclop answer there are known problems on firefox with the reloading of iframe flash object plugin in firefoxi think but i am not sure that the sole solution is to use absolute positionning cuzzea however i asked this question because i wanted to find another way i do not want to use absolute positioning this is why i will award no answer thanks for your contributions,"['java', 'javascript', 'html']" +336071,apache cxf none of the policy alternatives can be satisfied i am trying to create client of 3rd party ws my app is running on jboss as 6 with its apache cxf 231 stack i generated client code by wsconsume wsdl2java when i tried to connect to ws a got exceptionno assertion builder for type basicauthentication registered exception in thread main orgapachecxfwspolicypolicyexception none of the policy alternatives can be satisfiedauth part of wsdl looks likewsppolicy wsuidabc ssl policy wspexactlyone wspall httpbasicauthentication xmlnshttp sptransportbinding xmlnssp wsppolicy sptransporttoken wsppolicy sphttpstoken requireclientcertificatefalse wsppolicy sptransporttoken spalgorithmsuite wsppolicy spbasic256 wsppolicy spalgorithmsuite splayout wsppolicy spstrict wsppolicy splayout wsppolicy sptransportbinding wspall wspexactlyonewsppolicyclient codewebserviceclientname abc wsdllocation targetnamespace public class abc extends service public final static url wsdl locationpublic final static qname service new qname abcpublic final static qname abcssl new qname abc sslstatic authenticatorsetdefaultnew authenticator override protected passwordauthentication getpasswordauthentication return new passwordauthenticationuser pastochararray url url null try url new url catch malformedurlexception e javautilloggingloggergetloggerthistrinfoclassgetname logjavautillogginglevelinfo can not initialize the default wsdl from 0 wsdl location urlexception is thrown whe i try get conduit client client clientproxygetclientport httpconduit con httpconduit clientgetconduit exceptioni suspect that is because of nonstandard ms policy and i need proper intercerptor to handle this policy but can somebody show me a way how to do iti dont even no where i should put my https credentials to auth i cannot get conduit,['java'] +336073,why main in c is not overloaded to use stdstring i was trying to create a program that takes arguments by command line using main function arguments as a basic c programmer even if i know quite well pointers and array in cstyle i hardly ever used char strings and carrays i spent some to take main arguments and transform it in stdstring so asked myself why in c the main function is not overloaded to take an stdvectorstdstring argv instead of the old char argvfor overload i mean the coexistence of main functions like int main and int mainint argc char argv not the overloading of a normal function made by the programmer,['c++'] +336080,jqueryautocomplete makes the tab key select the first item if no item is selected the goal of this question is by using jqueryautocomplete makes the tab key able to select the first item if no item is selectedthe code i have implemented 1 works but i have some doubts and i would like to clarify them or if it is possible improvechange the code 1 in order to achive my goalmy doubts are i am triggering enter too early the event thispatching is asynchronous the different listeners are called synchronously but it is asynchronous of the trigger so i may trigger it before the listener handled donethus i am still using the same object for both events here so i may have nasty side effects if i prevent the default during the first thispatching it will be prevented for the second one too as it is the same object for instanceany suggestioncomment thanks ps1 here is the jsfiddle link 2 this question is related to this one how to avoid to modify the event object in this situation1boxkeydownfunctionevent var newevent eventkeydown keycode eventkeycode if neweventkeycode uikeycodetab return neweventkeycode uikeycodedown thistriggernewevent neweventkeycode uikeycodeenter thistriggernewevent,"['javascript', 'jquery']" +336098,sorting options elements alphabetically using jquery i am trying to get my head around sorting the option elements within a select alphabetically ideally i would like to have this as a seperate function where i can just pass in the select element since it needs to be sorted when the user clicks some buttonsi have searched high and low for a good way of doing this but have not been able to find anything that worked for me the option elements should be sorted alphabetically by their text and not their valueis this possible in some waythanks a lot in advanceall the bestbo,"['javascript', 'jquery', 'html']" +336116,javascript semicolonless code style and minification i am trying to decide if it worth to go with javascript semicolonless styleif i have javascript code without semicolonfunction var first 1 var second 2 sum 1 2 return sumit will work in browser and nodejsbut will minified by uglify or closure compiler code work in browser and nodejsi have read the article semicolons in javascript are optional it says that it should work,['javascript'] +336140,android horizontalscrollview inside scrollview i have multiple horizontalscrollviews inside a scrollview horizontal scroll is not smooth at all i have to scroll almost perfectly horizontally for scrolling to work is there a simple fix to tweak this thanks,"['java', 'android']" +336142,bring application to front after user clicks on home button my application is in running modeforeground and user clicks on home button which puts application to backgroundand still running i have alarm functionality in my application which fires up i want is when my alarm goes off i want to bring my background running application in foreground and from last state in which it was application androidnamenlziggoandroidstatemanagementmainepgapp androidicondrawableicon androidlabelstringapp name androidlargeheaptrue androidlogodrawableapp logo activity androidnamesplashscreen androidlabelstringapp name androidlaunchmodesingletop androidscreenorientationnosensor androidthemestylethemesherlock intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity activity androidnamestarter androidconfigchangesorientationscreensize androidscreenorientationbehind androidlaunchmodesingletop androiduioptionsnone androidwindowsoftinputmodeadjustpan application,['android'] +336152,visual studio 2012 installshield le net framework 45 prerequisites we have an application that was built using visual studio 2010 targeting the net framework 40 we are upgrading the application to use net framework 45 and is being written with visual studio 2012 microsoft no longer provides a setup project type of their own so we are forced to use this installshield le however there appears to be a glaring omission in installshields prerequisites section there is no option to declare that net framework 45 must be installed only net framework 40 options i have spent days trying to location the information to resolve this issue to no resolve flexera software seems virtually unapproachable also as i cannot seem to get a hold of anyone from that company to assist it is not instilling me with much confidence in their product how do i get net framework 45 to be a prerequisite,['.net'] +336177,most pythonic way to get the previous element i would like an enumeratelike functional on iterators which yields the pair previous element current element that is given that iter is i0 i1 i1 i would like offsetiter to yieldnone i0 i0 i1 i1 i2,['python'] +336201,cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type having done nothing more than install visual studio 2012 our existing application now crashes when attempting to create a delegate why would we be getting this error when running our application not running in debugjust running the exe normallynot having recompiled or done anything other than install visual studio 2012does visual studio 2012 update net 40 windowsformsintegration in some wayany suggestions on how to get around thisthe invocation of the constructor on type mywindowsformshost that matches the specified binding constraints threw an exceptionwith internal exceptioncannot bind to the target method because its signature or security transparency is not compatible with that of the delegate typethe offending class and lineinternal class mywindowsformshost windowsformshost private delegate void notifychildfocusref message m private readonly notifychildfocus childgotfocus public mywindowsformshost this line crashes now and did not before vs2012 install thischildgotfocus delegatecreatedelegatetypeofnotifychildfocus this notifyactivateapp as notifychildfocus update thiscovered that the notifyactiveateapp method no longer exists on windowsformshost what i do not understand is how installing net 45 with visual studio 2012 has affected my existing 40 applicationupdate in order to get around this i have used reflection to check if the notifyactivateapp method exists if it does not exist then the app is running in the patched net versionand i do not have to worry about the activation bug this child focus code was written to fix methodinfo methodinfo typeofwindowsformshostgetmethodnotifyactivateapp bindingflagsnonpublic bindingflagsinstanceif methodinfo null thischildgotfocus delegatecreatedelegatetypeofnotifychildfocus this notifyactivateapp as notifychildfocusnote to microsoft thanks for fixing your bugi just wish you would have rolled it out in a way that did not break existing code,['c#'] +336208,rails comparison of status with status failed i need to fetch all current userfriends statuses and then sort them by created atclass user activerecordbase has many statusesendclass status activerecordbase belongs to userendand in the controllerdef index statuses current userfriendsmap friend friendstatuseseach status statuses status current userstatuseseach status statuses status statusessort ab bcreated at acreated at endcurrent userfriends returns an array of objects userfriendstatuses returns an array of objects statuserrorcomparison of status with status failedappcontrollerswelcome controllerrb10in sortappcontrollerswelcome controllerrb10in index,"['ruby-on-rails', 'ruby']" +336228,how to thisplay both normal and split actionbar i have more then a few actionbar items and i am using splitactionbarwhennarrow option latest gmail app also uses it but it also have a custom item on upper right that shows the current number of unread emails when i use splitactionbar it sends all my action items to the bottom how can i send some of them to bottom and force some of them to be in the upper side,['android'] +336235,change slickgrid cell data after edit i am using slickgrids with alot of success i have ajax edits all working but i am trying to add a piece of functionalitybelow is my code which allows me to update cells it works as intended but i want to be able to change the cell after it has been editted with the returned value from the json data see my code below i have put in capitals where i need a command to update the editted cell with the new returned data gridoncellchangesubscribefunctione args var datastring colgridgetcolumnsargscellnamerowargsitemnew training calendar idvaluedataargsrowgridgetcolumnsargscellfield ajax type post url mydomainupdate cell data datastring datatype json success functiona ifastatus ok alertamsg undo else alertamsg change cell here to anewdata return false,['javascript'] +336276,idtech unimag card swiper on android i have been working on android v23 for a couple of weeks now and i have stumbled upon some problems with the unimag card swiper from idtechthe unit comes with a scarce documentation and the demo app from the sdk implements the firmware update and a few classes for dialogs and such which really offuscate how to achieve basic functionality added to the few and not so good comments in the codei have implemented the interface in a basic activity and tried to detect when the unit is connected or thisconnected but it seems the listener catches both events connectionthisconnection as thisconnect let alone trying to read a cardhas anyone worked with this unit on android and has some clear examplesby the way here is my classpackage comcardswipeimport javaiofileimport javaiofileoutputstreamimport javaioinputstreamimport idtechmsrunimagunimagreaderimport idtechmsrunimagunimagreadermsgimport androidappactivityimport androidosbundleimport androidutillogimport androidviewviewimport androidwidgettextviewimport androidwidgettoastpublic class cardswipetestactivity extends activity implements unimagreadermsg private unimagreader myunimagreader null private textview etcarddata private string strmsrdata null private byte msrdata null private string strstatus null private int ngetchallengeresult 0 override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain initializeui initializereader string strmanufacture myunimagreadergetinfomanufacture string strmodel myunimagreadergetinfomodel string strsdkverinfo myunimagreadergetsdkversioninfo string strosverinfo androidosbuildversionrelease etcarddata textviewfindviewbyidridtext view etcarddatasettextphone strmanufacturenmodel strmodelnsdk ver strsdkverinfonos version strosverinfo override protected void onpause todo autogenerated method stub ifmyunimagreadernull you should stop swipe card and unregister when the application go to background myunimagreaderstopswipecard myunimagreaderunregisterlisten myunimagreaderrelease superonpause override protected void onresume todo autogenerated method stub you should register to listen the headset event when the application resumed ifmyunimagreadernull myunimagreaderregisterlisten if bcheckedsavelogitemtrue myunimagreadersetsavelogenabletrue else myunimagreadersetsavelogenablefalse ifitemstartscnull itemstartscsetenabledtrue waitingcommandresultfalse superonresume override protected void ondestroy myunimagreaderrelease superondestroy androidosprocesskillprocessandroidosprocessmypid override public boolean getusergrantint arg0 string arg1 todo autogenerated method stub return false override public void onreceivemsgautoconfigprogressint arg0 todo autogenerated method stub override public void onreceivemsgcarddatabyte arg0 byte arg1 todo autogenerated method stub logdswipe card swiped toastmaketextgetapplicationcontext card swiped toastlength shortshow override public void onreceivemsgcommandresultint arg0 byte arg1 todo autogenerated method stub override public void onreceivemsgconnected logdconnectionswiper connected toastmaketextgetapplicationcontext swiper connected toastlength shortshow override public void onreceivemsgthisconnected logdconnectionswiper thisconnected toastmaketextgetapplicationcontext swiper thisconnected toastlength shortshow override public void onreceivemsgfailureinfoint arg0 string arg1 todo autogenerated method stub logdconnectionswiper failure override public void onreceivemsgsdcarddfailedstring arg0 todo autogenerated method stub override public void onreceivemsgtimeoutstring arg0 logdtimeouttimed out toastmaketextgetapplicationcontext timed out toastlength shortshow override public void onreceivemsgtoconnect logdconnectionswiper powered up toastmaketextgetapplicationcontext swiper powered up toastlength shortshow override public void onreceivemsgtoswipecard logdswipeready to swipe toastmaketextgetapplicationcontext ready to swipe toastlength shortshow private void initializereader ifmyunimagreadernull myunimagreader new unimagreaderthisthis myunimagreadersetverboseloggingenabletrue myunimagreaderregisterlisten load the xml configuratin file string filenamewithpath getxmlfilefromraw ifisfileexistfilenamewithpath filenamewithpath null myunimagreadersetxmlfilenamewithpathfilenamewithpath myunimagreaderloadingconfigurationxmlfiletrue myunimagreadersettimeoutofswipecard5 private boolean isfileexiststring path ifpathnull return false file file new filepath if fileexists return false return true private string getxmlfilefromraw the target filename in the application path string filenamewithpath null filenamewithpath idt unimagcfg defaultxml try inputstream in getresourcesopenrawresourcerrawidt unimagcfg default int length inavailable byte buffer new bytelength inreadbuffer inclose deletefilefilenamewithpath fileoutputstream fout openfileoutputfilenamewithpath mode private foutwritebuffer foutclose to refer to the application path file filedir thisgetfilesdir filenamewithpath filedirgetparent javaiofileseparator filedirgetname filenamewithpath filenamewithpathjavaiofileseparatoridt unimagcfg defaultxml catchexception e eprintstacktrace filenamewithpath null return filenamewithpath public void swipeview v ifmyunimagreadernull myunimagreaderstartswipecard ifmyunimagreaderisswipecardrunningtrue logdswipeswipe card running private string gethexstringfrombytesbyte data ifdatalength0 return null stringbuffer hexstring new stringbuffer string fix null for int i 0 i datalength i fix integertohexstring0xff datai iffixlength1 fix 0fix hexstringappendfix fix null fix hexstringtostring return fix public byte getbytesfromhexstringstring strhexdata if 1strhexdatalength2 return null byte bytes new bytestrhexdatalength2 for int i0istrhexdatalength2i bytesi byte integerparseintstrhexdatasubstringi2 i12 16 return bytes there are some unimplemented methods there as well,['android'] +336282,what exactly does a jar file contain as an intern i use company code in my projects and they usually send me a jar file to work with i add it to the build path in eclipse and usually all is fine and dandyhowever i got curious to know what each class contained and when i try to open one of the classes in the jar file it tells me that i need a source filewhat does this mean i come from a cc background so is a jar similar to an already compiled o file and all i can see is the h stuff or is there actual code in the jar file that i am using that is encrypted so i cannot read itthanks for all the answersedit thanks guys i knew it was a sort of like an archive but i was confused to why when i tried to open the class files i got a bunch of random characters the output was similar when i tried to open a o file in c so i just wanted to make surethanks,['java'] +336330,httpservletrequest getremoteaddr not working how i would expect the following code is returning incorrectly from what i understandhttpservletrequest httprequest httpservletrequest requeststring useripaddress httprequestgetremoteaddr actual 010 expected 01any idea why the 0 is there when i loop through inetaddressgetallbynamelocalhosti get the following 1921681001 127001 01how would i test for localhost if getremoteaddr is returning invalid format or am i doing something wrongthanks,['java'] +336347,simulating virtual worlds continuous or thiscrete steps i am making something similar to polyworld which means i will be simulating virtual worlds where little creepers run around eat and evolve i am making that with nodejs and i plan to use physics and neural networks but i am not sure whats the best way to update the world more specifically should the update functions be recieving delta time as an argument or do the same thing each time independent of when they were last called what are the benefits of both waysedita point that i have against continous updates is that i want to implement some kind of intervals for example each 20 simulation seconds a food block spawns if the dt gets different than 1 or a fraction of 1 this will never work preciselythen again if i go with thiscrete updates where updates do not care about how much time has passed i would not be able to slow time down as i made this to work on a powerful server and render in the browser i figure that the updates will happen pretty often and i need a way of slowing time down without affecting the simulation so i can see whats happening,['javascript'] +336349,string pool test faster than test i am trying some performance benchmark regarding string pool however the outcome is not expectedi made 3 static methodsperform0 method creates a new object every time perform1 method string literal testperform2 method string constant expression testmy expectation was 1 fastest 3 slowesttest because of string poolingtest because of string pooling but bit slower than 1 because of operatornew string because of no string poolingbut the benchmark shows that test is slighty faster than testnew string 1416770 ns test 11480 ns test 10590 nsnew string 1412530 nstest 11770 nstest 10890 nsnew string 1423070 nstest 18780 nstest 10820 nsnew string 1421270 nstest 11550 nstest 10780 nsheres the codeimport javautilconcurrenttimeunitpublic class stringpoolperformance public static long perform0 long start systemnanotime for int i0 i10 i string str new stringtest return systemnanotimestart public static long perform1 long start systemnanotime for int i0 i10 i string str test return systemnanotimestart public static long perform2 long start systemnanotime for int i0 i10 i string str test return systemnanotimestart public static void mainstring args long time00 time10 time20 for int i0 i100 i result time0 perform0 time1 perform1 time2 perform2 systemoutprintlnnew string time0 ns systemoutprintlntest time1 ns systemoutprintlntest time2 ns can someone explain why test performs faster than test is jvm doing some optimizations here thank you,['java'] +336354,python module to change system date and time how can i change system date time timezone in python is there any module available for this i do not want to execute any system commandsi want one common solution which should work on both unix and windows,['python'] +336365,bootstrap onclick button event this seems a silly question but just got bootstrap and it doesnt gives any examples on the website about adding a javascript callback to a buttontried setting my button an id flag and thendiv classbtngroup button idrectbutton classbtnrectanglebutton button classbtncirclebutton button classbtntrianglebutton button classbtnlinebutton button classbtncurvebutton button classbtnpicbutton button classbtntextbutton button classbtngradientbuttondivi want to add a callback to rectangle buttonrectbuttononclick function e actioncant get the point of bootstrap callbacksall i could found on the web is oriented to rails bootstrap no bootstrap and js only,['javascript'] +336367,gdb run until specific breakpoint in gdb debugging c code i have 15 breakpoints strategically set but i do not want any of them to activate until i have hit breakpoint 2 is there any rununtilbreakpointn command in gdbi find myself doing one of two things insteaddelete all other breakpoints so that 2 is all that exists run readd all breakpoints orrun and repeatedly continue past all breaks until i see the first break at 2i want something like rununtil 2 that will ignore all other breakpoints except 2 but not delete them does this exist does anyone else have a better way to deal with this,"['c++', 'c']" +336368,converting synchronous moq mocks to async i am working on converting a body of synchronous aspnet code to net 45 and the new async syntaxi have a lot of test code that looks likevar retval new foobarbaz mymocksetupx xdosomething123returnsretvalwhen i convert the signature of dosomething from foo dosomething to async taskfoo dosomething all of my test code has to be rewritten my current workaround is to convert the original code to something likevar retval new foobarbaz mymocksetupx xdosomething123 returnsnew taskfooretvalthis is not a particularly hard transform but it is tedious when i have thousands of tests that need to be updated i tried making an extension method called returnsasync to do some of that form m but i was having some type inferrence issues that i could not quite nail down is there a standard or easier way to convert this kind of mock to handle the async method better,['c#'] +336394,override function declaration in autodoc for sphinx i have a module that goes something like thisusrbinenv python documentation here blah blah blahfoobar rsome really long regex heredef myfuncvalfoobar blah blah blah passand i have a rst file that goes something like thismodmy module moduleautomodule my module members privatemembers showinheritancewhen i build the documentation i get an html file with a snippet that goes like thismymodulefoobarfoobar some absurdly long and ugly regex here extra documentation heremymodulemyfuncvalsome absurdly long and ugly regex hereblah blah blahbased on this stackoverflow post i thought i could change it by altering my module tousrbinenv python data my modulefoobar extra documentation herefoobar some really long regex heredef myfuncvalfoobar function my modulemyfuncvalfoobar blah blah blah passbut that did not do the trick and just appended the signature i wanted under the ugly one as part of the body does anybody know how i can properly override this i am using sphinx v113 btw,['python'] +336424,detect delete button in soft keyboard i have two edittext each only only accepts one character and i want to handle both fields like i had only onei am using a textwatcher to set the focus in the second one when the user writes a character in the first one but i do not know how to do the oppositeif the user press the delete button in the second edittext being this edittext empty i want to move the focus to the first edittext and delete the character therethe problem is that textwatcher does not work when the user tries to delete an empty field because in fact nothing is changing and onkeydown event only works with hard keyboards so i do not have any idea of how to deal with this problemthanks,['android'] +336441,decltype vs auto as i understand it both decltype and auto will attempt to figure out what the type of something isif we defineint foo return 34then both declarations are legalauto x foocout x endldecltypefoo y 13cout y endlcould you please tell me what the main difference between decltype and auto is,['c++'] +336462,nsstring boundingrectwithsize slightly underestimating the correct height why i am attempting to resize a text field view automatically depending on its current width in other words i want the width to stay constant but resize the height according to the text supplied to itit seems to be working but for some reason is aligning to the bottom of my window despite efforts to manually move it back can anybody see what i am doing wrong herensstring temp lorem ipsum dolor sit amet consectetur adipiscing elit integer vel felis nec massa ultricies blandit non id arcu sed enim est facilisis a feugiat in consectetur eget arcu aenean rutrum lacus id euismod congue nisl erat vulputate lectus non faucibus tortor purus sed sem donec tempor dui egestas velit auctor vitae faucibus diam facilisis morbi convallis nulla quis est pulvinar quis ultricies sem sollicitudinmytextstringvalue tempnsdictionary attributes nsdictionary dictionarywithobjectsandkeys nsfont systemfontofsize12 nsfontattributename nsparagraphstyle defaultparagraphstyle nsparagraphstyleattributename nilnssize size nsmakesizewindowframesizewidth 200mytextframe temp boundingrectwithsizesize optionsnslinebreakbywordwrapping nsstringdrawinguseslinefragmentorigin attributesattributesedit even when manually moving the frame it is clear that the text is still getting cut off the newly adjusted size is not quite therethis is in reference to nsstring boundingrectwithsize slightly underestimating the correct width whyand nstextview or nstextfield automatically resize bounds frame,['objective-c'] +336498,detecting ios orientation change instantly i have a game in which the orientation of the device affects the state of the game the user must quickly switch between landscape portrait and reverse landscape orientations so far i have been registering the game for orientation notifications viauidevice currentdevice begingeneratingdeviceorientationnotificationsbut it is far too slow there seems to be about a second delay between rotating the phone and the notification actually being fired i need a way to instantly detect changes in the devices orientation i have tried experimenting with the gyroscope but am not yet familiar enough with it to know whether or not it is the solution i am looking for,"['iphone', 'objective-c', 'ios']" +336526,reorganize all elements after hiding a element using jquery masonry i am hiding a li and after hiding it there is a gap left in the html and i want to reload masonry and rearrange the contents i tried masonry reload but i did not work any helpfiddle jsdocumentreadyfunction containermasonry options itemselector item columnwidth 240 isanimated true animationoptions duration 750 easing linear queue false butn1clickfunction container ul lieq2hide containermasonryreload,['jquery'] +336530,file download by calling ashx page i am requesting ashx page from master page client side script jquery which has a code to download a pdf file when i debug it i can see the execution of file download code but file is not downloading ajax type post url filedownloadashx datatype html success function data public class filedownload ihttphandler public void processrequesthttpcontext context contextresponsecontenttype textplain contextresponsewritehello world string filename busprojectcardpdf string filepath contextservermappathprint contextresponseclear contextresponsecontenttype applicationpdf contextresponseaddheadercontentthisposition attachment filename filename contextresponsetransmitfilefilepath filename contextresponseend,"['asp.net', 'jquery']" +336543,check if the sdcard is present boolean is always true in my splash screen i want to check if the phone has a sdcard the boolean statement is beneath boolean issdpresent androidosenvironmentgetexternalstoragestate equalsandroidosenvironmentmedia mounted so if i have the sdcard in the slot on my phone this boolean will return true so far so good when i go to the unmount sdcard from the settings menu and removes the sdcard then kill the app and launching it again the boolean will also be true and if i launches the astro file manager after unmounting and removing the sdcard i can still access the mntsdcard path whyhow can i manage to accomplish this thanks in advanceedittesting with the following codefile path environmentgetexternalstoragedirectory string paths pathgetpathwhen the sdcard is in the slot the paths contains mntsdcard but when i removes the sdcard the paths is still mntsdcard,['android'] +336545,vs2012 code coverage only analyzes the test dll i am trying to get code coverage working in vs2012 premium and i am having some troublei have a c solution with a few different projects but most notably a kerneldll to be tested and a kerneltestsdll that tests using nunit and rhino mocksusing the nunit test adapter beta 2 getting the tests into the test explorer works fine as does running them but when it comes to code coverage i only get analysis from the test dll itself not the code that is tested this is when i do not use a runsettings filei have also tried using a runsettings file like here with this specificationinclude modulepathdllmodulepathincludeexclude modulepathtestsdllmodulepathexcludebut this just gives me an empty result because now the test dll does not get included eitherthe problem seems to be that it does not find the other parts of the solution but i am not sure where exactly it looks or what i need to set up in order for it to be foundhas anyone run into the same issue any ideas on how to fix it,['c#'] +336549,jquery offset top does not work correctly i am trying to create an script draw something in an element by mouse and i am using raphaeljs to do thatfor correct drawing i need to find top and left of ainputaa element i am using var offset inputoffset to get left and topbut the top value is not correct it is 10px lower than aathe real top thistance i think the 10px maybe change in different resolutions then i cannot add 10px to it normally then i want to know how can i fix the problemi uploaded my test here,"['javascript', 'jquery']" +336556,how to detect when a switch is slided not clicked i managed to capture when a switch view is clicked so the main activity responds accordingly but whenever i slide it instead of clicking it is as if nothing has happened how can i detect this,['android'] +336579,using on and estoppropagation on dynamic elements i have been experimenting with capturing click events outside of elements using stoppropagation containerchildrenonclickfunctione estoppropagation containeronclickfunction alertoutside the box ahere is a jsfiddle set up to demonstrate it functioning an alert should fire when you click anywhere outside of the white boxnow i am trying to have the same principle applied to dynamically created elements as far as i understand the on method of event assignment in jquery should allow this to function without changing the scripthere is a second jsfiddle where you must first click a link to create the elements once you have done this the theory is that the same script will work but it does not what am i missing about this method,"['javascript', 'jquery']" +336626,is the gamekit is communication reliable with gkmatchsenddatareliable i am working with gamekitframework and i am trying to create a reliable communication between two iphonesi am sending packages with the gkmatchsenddatareliable modethe documentation saysgkmatchsenddatareliablethe data is sent continuously until it is successfully received by the intended recipients or the connection times out reliable transmissions are delivered in the order they were sent use this when you need to guarantee deliveryavailable in ios 41 and later declared in gkmatchhi have experienced some problems on a bad wifi connection the gamekit does not declare the connection lost but some packages never arrivecan i count on a 100 reliable communication when using gkmatchsenddatareliable or is apple just using fancy names for something they did not implement,"['objective-c', 'ios']" +336634,how do you build complex queries with mongodb and the c driver i have developed a simple api which allows you to build up an array of search criteria within a mongodb collection i now need to be able to convert this array into an actual mongo query and this part is where i am having extreme difficultyideally i am after some syntax that will allow me to do the following pseudo codevar query new querybuilderforeach var group in groups switch groupcondition case groupconditionor queryorgroupqueries break case groupconditionand queryandgroupqueries break return mycollectionfindastype queryi actually want to build up slightly more complex queries but ultimately i am after the functionality to dynamically build up my queries with objects as seen in my pseudo code abovefeel free to ask me for additional details if i have not made myself clear enough about what i am trying to achieve,['c#'] +336734,reading files in a particular order in python lets say i have three files in a folder file9txt file10txt and file11txt and i want to read them in this particular order can anyone help me with thisright now i am using the code import glob osfor infile in globglobospathjoin txt print current file being processed is infileand it reads first file10txt then file11txt and then file9txtcan someone help me how to get the right order,['python'] +336739,download files from server php i have a url where i save some projects from my work they are mostly mdb files but some jpg and pdf are there toowhat i need to do is to list every file from that directory already done and give the user the option to download ithow is that achieved using php,['php'] +336772,amazon cloudfront private thistribution links to images inside css i created a private thistribution in cloudfront to prevent hotlinking i managed to create links to my objects with signed url which is working fine nowmy only concerns is that images link inside my css stylesheets are not working because they are not signed so if i have for instancebackgroundimage urlimgbgpngthe background image is not going to show up since the stylesheet does not include a signed url and therefore cloudfront refuses to serve the contentis there anything i can do to prevent this,['php'] +336786,what is the purpose of membershipvalidateuser i have been learning about the membershipprovider class and i thought that the membershipvalidateuser method was supposed to be used to to log a user inhowever i just learned that there is a formsauthenticationauthenticatewhat is the purpose of validateuser within membership,"['c#', 'asp.net']" +336818,why to use foreign keys with no action on delete or update i have a question of interesti have 2 tables in mysql with innodbtable tbl a has a primary key named a idtable tbl b has a primary b id and a foreign key on tbl aa id with on delete no action table name primary key foreign key tbl a a id tbl b b id a id why should i still use innodb and foreign keys if i do not really use the magic of foreign keys in the end in anywayis there still a point of usinginnodb and foreign keysinstead ofmyisam and no foreign keysif i just do no action on deletes or updatesi hope you got my point of interest,['mysql'] +336847,how to store a string var greater than varcharmax i am trying to do thisdeclare myvar varcharmaxloop with cursorselect myvar myvar bla bla blaend loopwhen the loop ends myvar is incomplete containing only 80 charactersi have tryed to use text but is not allowed to local varswhat would be a good solution to this case xml vari have just looked this postshow do i pass a string parameter greater than varchar80 in sql server 20check if concatenating to a varcharmax will go beyond max allowable charactersand others through the webregards,['sql'] +336849,accessing error messages for nested attribute field i have a form created using the simple form gem which populates 2 models using nested attributes i want to check if there are any errors and thisplay a new block however i am not sure how to correctly access the error message for the location attribute of the booking modelclass booking activerecordbase belongs to customer attr accessible date wanted locationendandclass customer activerecordbase has many bookings accepts nested attributes for bookings attr accessible name phone bookings attributes validates presence of name phoneendform viewsimple form for customer html class formhorizontal do f finput name finput phone fsimple fields for bookings do b binput date binput location if customererrorsappointments attributeslocation insert code if any validation errors for the date field were found fbutton submit,['ruby-on-rails'] +336854,gson automatically add classname lets say i have the following classespublic class dog public string name edvardpublic class animal public dog maddog new dogif i run this trough a gson it will serialize it as followinggson gson new gsonstring json gsontojsonnew animalresult maddog nameedvard this far so good but i would like to have added the classname for all classes automatically with gson so i get the following result maddog nameedvard classnamedog classname animaldoes anyone know if this is possible with some kind of interceptors or something with gson,['java'] +336855,returning 0 everytime when fetching keychain saved passcode from keychain access for ios app i am using keychainitemwrapper classintegrated h and m file in project for saving passcode in keychain for ios app also imported security framework and keychianitemwrapperh class in the project wherever it is neededimport import keychainitemwrapperh i am using below code in app delegate method for saving passcode in keychain access iftextfieldpassword1text isequaltextfieldpassword2text nslogcongrats passcode matched converting textfieldpassword1 to nsnumber nsnumber textfieldpasscode1num nsnumber numberwithinttextfieldpassword1text intvalue saving passcode to the keychain access keychain setobjecttextfieldpasscode1num forkey bridge idksecvaluedata keychain setobjectnsnumber numberwithinttextfieldpassword1text intvalue forkey bridge idksecattraccount if passcode matches then load show lock screen page selfwindow uiwindow alloc initwithframeuiscreen mainscreen bounds selfviewcontroller viewcontroller alloc init selfwindow addsubviewselfviewcontrollerview selfwindow makekeyandvisible and here am resetting passcode using below code if isresetpasscode nslogcode here for update passcode in keychain access isresetpasscode false keychain is object of keychainitemwrapper class keychain resetkeychainitem again setting the new passcode entered by user in keychain access it is not saving in keychain access where above the same line of code was working for saving passcode in keychain access keychain setobjectresetpasscodenum forkey bridge idksecvaluedata nslogpasscode resetted nresetpasscodenum when i am printing keychain passcode in console every time it is printing 0please guide me where i am doing wrong your help would be appreciated thanks in advance,['objective-c'] +336900,where can i find the source for systemweboptimization i am trying to figure out why when i create a scriptbundle that is referencing files that are in an iis virtualdirectory under my main sites application folder why it would not output anythingi found this postwhy does resolvebundleurl not work for custom foldersbut it no longer seems valid with the latest beta build of systemweboptimization,['.net'] +336911,comparison of different ways to have private members in objective c i came from cjava world where it is quite obvious how to create private members however i saw several ways to do this in objective c and i would like to hear cons and pros1 declare them as private in h fileinterface myclass nsobject private int somemember end2 declare them in interface inside m filesinterface myclass int somemember endimplementation myclassend3 declare them in implementationimplementation myclass int somemember end what is the preferred method and why did i miss any other methods,['objective-c'] +336933,using prepared statement multiple times efficiently below is the code which i am using to insert multiple records around 5070 in the oracle database using prepared statementthe way i am doing currently is good or it can be improve more using some batch thingpstatement db connectionpreparestatementpdslnpconstantsupsert sqlfor entryinteger linkedhashmapinteger string entry mappingentryset pstatementsetint1 entrygetkey pstatementsetstring2 entrygetvaluegetlnpconstantscguid id pstatementsetstring3 entrygetvaluegetlnpconstantspguid id pstatementsetstring4 entrygetvaluegetlnpconstantssguid id pstatementsetstring5 entrygetvaluegetlnpconstantsuid id pstatementsetstring6 entrygetvaluegetlnpconstantsuloc id pstatementsetstring7 entrygetvaluegetlnpconstantssloc id pstatementsetstring8 entrygetvaluegetlnpconstantsploc id pstatementsetstring9 entrygetvaluegetlnpconstantsaloc id pstatementsetstring10 entrygetvaluegetlnpconstantssite id pstatementexecuteupdate pstatementclearparametersudpated code that i am usingpublic void runnextcommand connection db connection null preparedstatement pstatement null int batchlimit 10 boolean autocommit false try db connection getdbconnection autocommit db connectiongetautocommit db connectionsetautocommitfalse turn off autocommit pstatement db connectionpreparestatementlnpconstantsupsert sql create a statement for entryinteger linkedhashmapinteger string entry guid id mappingentryset pstatementsetint1 entrygetkey pstatementsetstring2 entrygetvaluegetlnpconstantscguid id pstatementsetstring3 entrygetvaluegetlnpconstantspguid id pstatementsetstring4 entrygetvaluegetlnpconstantssguid id pstatementsetstring5 entrygetvaluegetlnpconstantsuid id pstatementsetstring6 entrygetvaluegetlnpconstantsuloc id pstatementsetstring7 entrygetvaluegetlnpconstantssloc id pstatementsetstring8 entrygetvaluegetlnpconstantsploc id pstatementsetstring9 entrygetvaluegetlnpconstantsaloc id pstatementsetstring10 entrygetvaluegetlnpconstantssite id pstatementaddbatch batchlimit ifbatchlimit 0 pstatementexecutebatch pstatementclearbatch batchlimit 10 pstatementclearparameters catch sqlexception e getloggerlogloglevelerror e finally try pstatementexecutebatch db connectioncommit db connectionsetautocommitautocommit catch sqlexception e1 getloggerlogloglevelerror e1getmessage e1fillinstacktrace if pstatement null try pstatementclose pstatement null catch sqlexception e getloggerlogloglevelerror egetmessage efillinstacktrace if db connection null try db connectionclose db connection null catch sqlexception e getloggerlogloglevelerror egetmessage efillinstacktrace,"['java', 'sql']" +336984,send win api paste cmd from background c app goal write a c app that runs in the background listens for the key combination winv and when that occurs pastes the clipboard contents into the current active window some arbitrary app essentially i am trying to mimic puretext but i am not bothering to convert the text to plain text firstproblem pasting into the currently active windows is not workingdetails to listen in the background for key presses i am using the globalkeyboardhook class from a simple c global low level keyboard hook i am able to catch winv events but i am not able to send the paste command properly i can send the paste by using the functions sendkeyssend or keybd event however they send another v press down the pipeline which gets caught by the gkh keydown event and causes multiple paste events to firei am expecting that i need to use sendmessage or postmessage but all my attempts to do that have failed so far below is the full code with the last function sendctrlv being the one of interest the comments explain everything i have tried so far can you see what i am missingusing systemusing systemiousing systemruntimeinteropservicesusing systemwindowsformsusing utilitiesnamespace keyhooktest public partial class form1 form private bool lwin down private bool v down globalkeyboardhook gkh new globalkeyboardhook dllimportuser32dll charset charsetauto static public extern intptr getforegroundwindow dllimportuser32dll static extern void keybd eventbyte bvk byte bscan uint dwflags uint dwextrainfo dllimportuser32dll private static extern int sendmessageintptr hwnd int msg int wparam int lparam dllimportuser32dll public static extern intptr postmessageintptr hwnd uint msg intptr wparam intptr lparam public form1 initializecomponent private void form1 loadobject sender eventargs e gkhhookedkeysaddkeysv gkhhookedkeysaddkeyslwin gkhkeydown new keyeventhandlergkh keydown gkhkeyup new keyeventhandlergkh keyup void gkh keyupobject sender keyeventargs e if ekeycode keyslwin lwin down false else v down false void gkh keydownobject sender keyeventargs e if ekeycode keyslwin lwin down true else v down true if lwin down v down logdebugenter winv try sendctrlv catch private void sendctrlv uint keyeventf keyup 2 int keydown 0x0100 int keyup 0x0101 byte key lcontrol1 0x11 intptr key lcontrol2 new intptr0x11 byte key v1 0x56 intptr key v2 new intptr0x56 int wm paste1 0x302 uint wm paste2 0x302 intptr hwnd getforegroundwindow works but causes multiple gkh keydown to fire so it is slow and buggy keybd eventkey lcontrol1 0 0 0 keybd eventkey v1 0 0 0 keybd eventkey v1 0 keyeventf keyup 0 keybd eventkey lcontrol1 0 keyeventf keyup 0 works but causes multiple gkh keydown to fire so it is slow and buggy sendkeyssendv does not work causes uac prompt sendkeyssendv does not work nothing gets pasted to the foregroundwindow sendmessagehwnd wm paste1 0 0 does not work nothing gets pasted to the foregroundwindow postmessagehwnd wm paste2 intptrzero intptrzero does not work nothing gets pasted to the foregroundwindow sendmessagehwnd keydown key lcontrol1 0 sendmessagehwnd keydown key v1 0 sendmessagehwnd keyup key v1 0 sendmessagehwnd keyup key lcontrol1 0 does not work nothing gets pasted to the foregroundwindow postmessagehwnd 0x0100 key lcontrol2 intptrzero postmessagehwnd 0x0100 key v2 intptrzero postmessagehwnd 0x0101 key v2 intptrzero postmessagehwnd 0x0101 key lcontrol2 intptrzero private void logdebugstring msg string logpath environmentgetenvironmentvariableuserprofile desktopkeyhooktesttxt fileappendalltextlogpath datetimenowtostringhhmmssf msg rn,['c#'] +336992,get records with max value for each group of grouped sql results how do you get the rows that contain the max value for each grouped set i have seen some overlycomplicated variations on this question and none with a good answer i have tried to put together the simplest possible examplegiven a table like that below with person group and age columns how would you get the oldest person in each group a tie within a group should give the first alphabetical resultperson group agebob 1 32 jill 1 34 shawn 1 42 jake 2 29 paul 2 36 laura 2 39 desired result set shawn 1 42 laura 2 39,"['mysql', 'sql']" +337010,how to convert gps coordinates to locality i am programming an android app to convert the dynamically available latitude and logitude coordinates to a humanly readable locationfor example 122 45 is located in central london uk regarding the granularity i want to be able to atleast locate the citytown or if not at least the citycan someone please advise on what solutions are available for this problem,['android'] +337011,how to scroll to a specific location in a jscrollpane i have a jscrollpane which contains a jpanel which has large height this large jpanel contain more jpanels in it as in the image some of those panels contains a jlabel which i used to show titles at the top there are jlabels which have numbers matching the title numbers in the title labels what i need to do is when i click a label from the top label list the jscrollbar should scroll to the position where that label is placedi do not know whether this is possible or not but if anyone know how to scroll to a specific position in a jscrollpane please assist me,['java'] +337016,android unit testing with junit testing networkbluetooth resources i am slowly becoming obsessed with unit testing i am trying to develop as much software as i can using testdriven development i am using junit to unit test my android applicationsi have been working on an app that uses bluetooth and am having a hard time unit testing it i have an activity that uses bluetoothadapter to obtain a list of paired and thiscovered devices although it works i would like to know how to unit test itto get the list of paired devices i call getbondeddevices on the instance of bluetoothadapter the problem is i do not know how to stub or mock this method or any other bluetoothadapter method that my activity calls so i cannot test my activity against different lists of paired devices i thought about using mockito or trying to subclass bluetoothadapter to somehow stub out the methods i am interested in but it is a final class so i cannot do either any ideas on how i could test programs that use bluetoothadapter or other resources that are as far as i know difficult or impossible to stub or mock as another example how would you test a program that uses socketsthanks in advance for any helpaleph null,['android'] +337023,does pointer arithmetic still work outside the array i am always reading that pointer arithmetic is defined as long as you do not leave the bounds of the array i am not sure i completely understand what this means and i was a little worried hence this questionsuppose i start with a pointer to the beginning of an arrayint p int malloc4 sizeofintnow i create two new pointers that lie outside the bounds of the arrayint q p 10int r p 2now the pointers q10 q9 r2 r3 and so on all lie inside the bounds of the array are they valid for example is r3 guaranteed to give the same result as p1i have done some testing and it works but i want to know if this is covered by the usual c specifications specifically i am using visual studio 2010 windows and i am programming in native c not c am i covered,['c'] +337032,entity framework 50 benchmark test i am doing an internship and i have been asked to evaluate the performance changes for the new entity framework 50i have personally never used the entity framework nor do i have any kind of big database or queries to do a proper benchmark testi have been doing some simple tests targeting to net 45 using for loops of linq queries in order to try getting the query automatically compiled and see some kind of performance change from when i target to net 40 but i have not been able to see any kind of performance change at allis there any kind of already done benchmark test for entity framework which could show when the new version of entity framework has a better performancethanks,['.net'] +337085,rhino mocks verifyallexpectations i would like to track a call to a method with rhino mocks let us assume i have this codepublic class a protected ib b public aib b b b public void run string name bsomecallnew c name name public interface ib void somecall c c public class c public string name get set more attributes hereand the test looks like preparevar bmock rhinomocksmockrepositorygeneratestrictmockibbmockexpectx xsomecallnew c name myname var sut new abmock executesutrunmyname assertbmockverifyallexpectationsthe test fails with a expectedviolationexception because rhino mocks framework detects 2 thistinct c classeshow do i check the call if the subject under tests creates the object parameter into the method under test any chance to tell rhino mocks to check the parameter as equalsthanks a ton,['c#'] +337097,why is typing in a textarea in firefox causing the screen to scroll i am experiencing an incredibly bizarre issue with the isotope plugin in firefox only i have a textarea in each of my isotope elements and when i scroll down to the bottom and type in one of the textareas the screen jumps to the top i have reproduced this in jsfiddlei have been looking at this for hours and cannot figure out what is causing this scroll even to fire would love some helpthanks,['javascript'] +337122,remove html node from htmldocument htmlagilitypack in my code i want to remove the img tag which does not have src value i am using htmlagilitypacks htmldocument object i am finding the img which does not have src value and trying to remove it but it gives me error collection was modified enumeration operation may not execute can anyone help me for this the code which i have used isforeach htmlnode node in docdocumentnodedescendantnodes if nodenametolower img string src nodeattributessrcvalue if stringisnulloremptysrc nodeparentnoderemovechildnode false else i am performing other operations on document,['c#'] +337125,how to scroll an element inside parent when a fixed element passes this is a bit too tricky for my jquery javascript knowledge so i am sorry to say i have not really tried anything yet i need some hints to get pointed in the right directionthe problem is that i have a fixed element on my page and when scrolling down this element will enter different wrappers and while in that wrapper i need a smaller child element to snap to my fixed element and while it is in the elementkind of hard to explain i made a static mockup herewhen fixed cart button reaches a price i need it to attach and scroll with the cart button as long as it is inside the prices productdiv when it leaves and enters the next the price should stay in the bottom of it is product and then snap to the cartbutton again when the users is reaching it by scrolling upwell again sorry for not having tried anything but i am lost if i had to do this without any help i think i would go with waypointsjs but it feels far from optimalany help much appreciated the fixed element will always have the same position so i guess offset from the browser top could be used instead of keeping track of it is position always something updatebeen working on it myself and got it working downwards but not upwardsshould clarify what i meanwhen scrolling by the price it joins the button downwards and snaps loose when leaving the container my problem now is making it snap to it and scroll back to its original position when scrolling upwards,"['javascript', 'jquery']" +337144,how to see my eclipse version how do i find out which version of eclipse is currently installed on my system,['java'] +337167,python quicksort list comprehension vs recursion partition routine i watched the talk three beautiful quicksorts and was messing around with quicksort my implementation in python was very similar to c select pivot partition around it and recursing over smaller and larger partitions which i thought was not pythonic so this is the implementation using list comprehension in python def qsortlist if list return pivot list0 l qsortx for x in list1 if x pivot you qsortx for x in list1 if x pivot return l pivot ulets call the recursion metho qsortr now i noticed that qsortr runs much slower than qsort for larger lists actually maximum recursion depth exceeded in cmp even for 10 elems for recursion method which i reset in syssetrecursionlimitsome numberslistcompr 10 elems 0491770029068recursion 10 elems 224620914459listcompr 20 elems 0992327928543recursion 20 elems 772630095482all the code is herei have a couple of questionswhy is list comprehension so much fastersome enlightenment on the limit on recursion in python i first set it to 10 in what cases should i be careful what exactly is meant by optimizing tail recursion how is it donetrying to sort 10 elements hogged memory of my laptop with the recursion method what should i do if i want to sort so many elements what kind of optimizations are possible,['python'] +337181,how to setcontentview in a fragment now i have got this fragment which i want to use setcontentview with but so far i cant find how you can see my case in the code below im not trying to inflate a layout im trying to use it with the view called sampleview so how can i do thatthanks in advancepublic class largeimagescroller extends sherlockfragment physical thisplay width and heightprivate static int thisplaywidth 0private static int thisplayheight 0 called when the activity is first created public view oncreateviewlayoutinflater inflater viewgroup group bundle saved getactivity thisplaywidth and thisplayheight will change depending on screen orientation to get these dynamically we should hook onsizechanged this simple example uses only landscape mode so it is ok to get them once on startup and use those values throughout thisplay thisplay windowmanagergetactivitygetsystemservicecontextwindow servicegetdefaultthisplay thisplaywidth thisplaygetwidth thisplayheight thisplaygetheight sampleview constructor must be constructed last as it needs the thisplaywidth and thisplayheight we just got setcontentviewnew sampleviewthisprivate static class sampleview extends view private static bitmap bmlargeimage bitmap large enough to be scrolled private static rect thisplayrect null rect we thisplay to private rect scrollrect null rect we scroll over our bitmap with private int scrollrectx 0 current left location of scroll rect private int scrollrecty 0 current top location of scroll rect private float scrollbyx 0 x amount to scroll by private float scrollbyy 0 y amount to scroll by private float startx 0 track x from one action move to the next private float starty 0 track y from one action move to the next public sampleviewcontext context supercontext destination rect for our main canvas draw it never changes thisplayrect new rect0 0 thisplaywidth thisplayheight scroll rect this will be used to scroll around over the bitmap in memory initialize as above scrollrect new rect0 0 thisplaywidth thisplayheight load a large bitmap into an offscreen area of memory bmlargeimage bitmapfactorydecoderesourcegetresources rdrawableground floor b override public boolean ontoucheventmotionevent event switch eventgetaction case motioneventaction down remember our initial down event location startx eventgetrawx starty eventgetrawy break case motioneventaction move float x eventgetrawx float y eventgetrawy calculate move update this will happen many times during the course of a single movement gesture scrollbyx x startx move update x increment scrollbyy y starty move update y increment startx x reset initial values to latest starty y invalidate force a redraw break return true done with this event so consume it override protected void ondrawcanvas canvas our move updates are calculated in action move in the opposite direction from how we want to move the scroll rect think of this as dragging to the left being the same as sliding the scroll rect to the right int newscrollrectx scrollrectx intscrollbyx int newscrollrecty scrollrecty intscrollbyy do not scroll off the left or right edges of the bitmap if newscrollrectx 0 newscrollrectx 0 else if newscrollrectx bmlargeimagegetwidth thisplaywidth newscrollrectx bmlargeimagegetwidth thisplaywidth do not scroll off the top or bottom edges of the bitmap if newscrollrecty 0 newscrollrecty 0 else if newscrollrecty bmlargeimagegetheight thisplayheight newscrollrecty bmlargeimagegetheight thisplayheight we have our updated scroll rect coordinates set them and draw scrollrectsetnewscrollrectx newscrollrecty newscrollrectx thisplaywidth newscrollrecty thisplayheight paint paint new paint canvasdrawbitmapbmlargeimage scrollrect thisplayrect paint reset current scroll coordinates to reflect the latest updates so we can repeat this update process scrollrectx newscrollrectx scrollrecty newscrollrecty,['android'] +337183,c11 compile time calculation of array suppose i have some constexpr function fconstexpr int fint x and i have some const int and known at compile timeeitherdefine and orconst int and as needed by your answeri want to have an int array xint xn f0 f1 f2 fn1 such that the function is evaluated at compile time and the entries in x are calculated by the compiler and the results are placed in the static area of my application image exactly as if i had used integer literals in my x initializer listis there some way i can write this for example with templates or macros and so onbest i have thanks to flexoinclude iostreaminclude arrayusing namespace stdconstexpr int and 10constexpr int fint x return x2 typedef arrayint n atemplateint i constexpr a fs return a fi templateint struct stemplateint i struct s0i static constexpr a gs return fs0i templateint i int j struct sij static constexpr a gs return si1ijgs constexpr auto x sn1gsint main cout x3 endl,['c++'] +337192,update table from another table and different database basically what i want to do is the following i have a table users in my first database prc like this prcuser id user 45 name user test login user test pwd user testand in my second database named prc test prc testuserid user 45 name user test login user test pwd user testthe thing i want to do is update all the pwd user fields in prc testuser with the values from pwd user from prcuserbut in the prc testuser the id are not the same as in prcuser so i thought of doing it with the name user there are no doublesany clue in how i can do it i searched on google but what i found is always for some specific cases or for insert statementsi am using mysql55thanks,"['mysql', 'sql']" +337194,how to pass list in redirecttoaction i want to pass more then one parameter from redirecttoaction methodhow can i passmy one action method httppost actionnameselectquestion public actionresult selectquestionstring emaillistquestionclasstabelfields model listquestionclasstabelfields fadd new listquestionclasstabelfields for int i 0 i modelcount i if modeliselectedcheckbox true listquestionclasstabelfields f new listquestionclasstabelfields faddaddmodeli return redirecttoactionquestion new email email model faddtolist my another action method httpget public actionresult questionstring emaillistquestionclasstabelfields model i am not getting values in model,['c#'] +337219,gksession with mac os x i am using gksession part of game kit to connect multiple ios devices together over bluetooth andor wifi send data etc which all works fine and i am happy with iti was thinking though it would be cool to have a mac os x app that could connect to the ios devices as well share data and so ongksession sadly does not seem to be part of game kit for mac os x 108 obviously i was wondering is anybody knows of a way to do this or has any ideasthanks again,['ios'] +337271,what are the most important posix functions not available in android i am about to port a large c project some sort of library project it contains absolutely no gui to android it is actually a visual c project but it will be ported to linux as intermediate step i know that android is not a full linux and does not claim to provide all posix functions but i also know there are a lot of posixish functions on android by using the ndknow my actual question iswhich are the biggestmost important functions that are not available on android compared with the full posix set so that i can keep that in mind when doing the porting from visual c to linux gcci tried to find something on google but found nothing really helpful just here and there some stuff that mentioned that there are some posix functions on android,"['android', 'c++']" +337276,jquery appending an array of elements for the purpose of this question lets say we need to append 10 objects to the body elementyou could go about it like thisforx 0 x 10 x var element divxdiv bodyappendelementthis works however it seems inefficient to me as afaik this will cause 10 document reflows a better solution would bevar elements forx 0 x 10 x var element divxdiv elementspushelementbodyappendelementshowever this is not an ideal world and this throws an error could not convert javascript argument arg 0 nsidomdocumentfragmentappendchild i understand that append cannot handle arrayshow would i using jquery i know about the documentfragment node but assume i need to use other jquery functions on the element such as css add a bunch of objects to the dom at once to improve performance,"['javascript', 'jquery']" +337277,accessing azure mysql service i am having problem trying to access the mysql server i would like to replace a table with another provided as part of the windows azure service i have downloaded the publishsettings xml file and the closest thing that i can find is data sourceuscdbrazureeastacloudappnet however it is not accessible from the web browser so i am not sure what to do next,['mysql'] +337285,how to validate formate for stringformat method stringformate has following method signaturestringformatformat params i want to pass custom format each time like string custformat hi 0 n i only care about numbers here and want avoid abdbstring name foostring message processmessagecustformat namepublic string processmessagecustformat name return stringformatcustformat namei want to validate the value in custformat before passing to processmessage to avoid exceptionany idea,['c#'] +337315,how to automatically destroy django test database i am currently trying to automate django tests using hudson and am struggling to find an option that will automatically destroy the test database if it already exists typically it will ask for confirmation to destroy it which the automatic testing obviously cannot provide forany suggestions would be much appreciatedcheersr,['python'] +337326,compiling qt 48x for visual studio 2012 what steps should i take to compile qt version 48x for visual studio 2012i already carefully followed the instructions in the accepted answer of this question which is for vs 2010 but webkit module failed to compile i am not sure if the error message was logged anywhere during compilationi also saw this question which asks the same but for vs 2012 rc which is why i thought this wouldnt be a duplicate question furthermore the answerer says he has compiled qt for vs 2011 beta so there is a chance it may not work for vs 2012 rtm the compilation takes a lot of time which is why i have not tried it yetat least one problem i realized is that there is no win32msvc2012 directory in qtmkspecs should i just create that directory and copy the files from win32msvc2010 possibly with some modificationsanother subquestion is whether i should make some modifications to qt sources before starting compilation,['c++'] +337339,how to cast a generic type to fit another generic method i have a method in class apublic ilistt mymethodt where taobjecti want to invoke this method in another generic class b this t is without any constraintspublic mehtodinclassb if typeofaobjecttypeoft compile error here how can i cast the t to a aobject type get the mymethod data a a new a amymethodt class c is inherited from class aobjectbc b new bcbmehtodinclassb any thoughtsafter urs remindingupdateyes what i actually want to do is typeofaobjectisassignablefromtypeoftnot typeofaobjecttypeoft,['c#'] +337361,how to align texts inside of a input for all default inputs the texts you fill starts on the left how do you make it start on the right,"['html', 'css']" +337393,using java as a backend and php as a front end there are already a few posts on so thiscussion whether this architecture is a good idea or bad idea for many reasons within our company including the existing programming talent weve decided to use java for the backend and php for the front end our objective is something likejava modelscontrollersphp viewswere working on building a prototype of the interaction between glassfish and apache one thing were still working on is when a user visits and they login that login will be sent to the glassfish controller which exists somewhere like loginjava we can do that no problem the trouble is getting the view to be rendered at that urlhas anyone does this with php or any other technologies,"['java', 'php']" +337416,numpy thistutils howto i spent almost an hour googling for the solution but the documentation for numpythistutils is very sparsei have a f2pywrapped module it consists basically of 3 filesaf90apyfliba this is a static library that contains most of the computational codethe module is well compiled with the following shellscript commandf2py builddir temp c apyf af90 liba fcompilergnu95 fcompilerflagszillions of compiler optionsas a result i have the python module aso the name is specified in the pyf filehow do i do that with numpythistutils or some other pythonoriented building tools a less important question is can i also include the dependence from liba and rebuild it when necessary,['python'] +337427,command line error d8036 not allowed with multiple source files i was working in visual studio and i made a few changes to one of my projects changed a few include directories when i tried to build that project later on i got the following error messagecl command line error d8036 foobjms100 r not allowed with multiple source filesi do not see how that is relevant to what i changed at all i even rolled my vcxproj file back to the previous version and that error still persists i am clueless as to what is causing it are not command line parameters supposed to be managed by visual studio anyway,['c++'] +337430,how to get the value on extjs combo box i have a following code for combo box how can i get the value that is selected in the combobox and load that value into a variable and use it laterthank you extdefinecolumn extend extdatamodel fields data1 data2var store extcreateextdatastore model column autoload true proxy type ajax url dataxml reader type xml record result var simplecombo extcreateextformfieldcombobox store store thisplayfield data1 valuefield data1 width 250 labelwidth 120 fieldlabel select a value renderto simplecombo querymode local typeahead true,['javascript'] +337441,numpy slice of arbitrary dimensions i would like to slice a numpy array to obtain the ith index in the last dimension for a 3d array this would beslice myarrayibut i am writing a function where i can take an array of arbitrary dimensions so for a 4d array i would need myarrayi and so on is there a way i can obtain this slice for any array without explicitly having to write the array dimensions,['python'] +337444,python create dict from other dict what is the best way to create a dict with some attributes from other dict with pythonexamplefrom this dictdict1 name jaime last name rivera phone number 1 email password x token x secret stuff y i want to getdict2 name jaime last name rivera phone number 1 email,['python'] +337448,what does this mean inside a template class function there is a code like thisconst stdstring devicetypestrings a b c d e enum devicetypes a 0 b c d e template devicetypes t class devicetypetemplate devicetypes t stdostream operator stdostream output const devicetypet devtemplate devicetypes t class devicetype public static const int value t static const stdstring string friend stdostream operator stdostream output const devicetypet devicetype template devicetypes t const stdstring devicetypetstring devicetypestringsttemplate devicetypes t stdostream operator stdostream output const devicetypet devicetype if devicetypetstringfind stdstringnpos return output devicetypetstring else return output devicetypetstring int main devicetypea mytype stdcout mytype stdendl return 0 note there is a after the operator inside class devicetype what does mean if you could why does it has to be there,['c++'] +337450,how to set background color of layer in cocos2dx i have been writing a game using cocos2dx and ran into an issue with changing the background color i found an example in cocos2d but apparently this only applies to cocos2d which is written in objc basically the idea is to use a cclayercolor instead of cclayer and when the constructor gets fired set the colordoes anyone know how to change the background color in cocos2dx seems like it would be pretty simple i am pretty sure i am missing something obvious,['c++'] +337499,python tfidfcosine to find document similarity i was following a tutorial which was available at part 1 part 2 unfortunately author did not have time for the final section which involves using cosine to actually find the similarity between two documents i followed the examples in the article with the help of following link from stackoverflow i have included the code that is mentioned in the above link just to make answers life easyfrom sklearnfeature extractiontext import countvectorizerfrom sklearnfeature extractiontext import tfidftransformerfrom nltkcorpus import stopwordsimport numpy as npimport numpylinalg as latrain set the sky is blue the sun is bright documentstest set the sun in the sky is bright querystopwords stopwordswordsenglishvectorizer countvectorizerstop words stopwordsprint vectorizertransformer tfidftransformerprint transformertrainvectorizerarray vectorizerfit transformtrain settoarraytestvectorizerarray vectorizertransformtest settoarrayprint fit vectorizer to train set trainvectorizerarrayprint transform vectorizer to test set testvectorizerarraytransformerfittrainvectorizerarrayprintprint transformertransformtrainvectorizerarraytoarraytransformerfittestvectorizerarrayprint tfidf transformertransformtestvectorizerarrayprint tfidftodenseas a result of above code i have following matrixfit vectorizer to train set 1 0 1 0 0 1 0 1transform vectorizer to test set 0 1 1 1 070710678 0 070710678 0 0 070710678 0 070710678 0 057735027 057735027 057735027i am not sure how to use this output to calculate cosine similarity i know how to implement cosine similarity respect to two vectors with similar length but here i am not sure how to identify the two vectors,['python'] +337502,compile gwt via ant is it possible to run the gwt compiler java to javascript and perhaps run other gwt tools such as compile reports run in dev mode etc from an ant buildfile if so where are these ant tasks defined i do not see anything in the sdki cannot imagine google would make something as powerful as gwt and force developers to only run builds out of their local eclipse instanceshow do ci builds kick this stuff off,['java'] +337509,converting float vector to 16bit int without saturating i want to convert a floating point value to a 16bit unsigned integer without saturating wraparoundoverflow insteadinclude iostreaminclude xmmintrinhvoid satur wrap const float bigval 990f const m128 bigvalvec mm set1 psbigval const m64 outvec64 mm cvtps pi16bigvalvecif 0 const m128i outvec mm movpi64 epi64outvec64else if 1 const m128i outvec mm packs epi32 mm cvttps epi32bigvalvec mm cvttps epi32bigvalvec else const m128i outvec mm cvttps epi32bigvalvec endifendif uint16 t outvals null posix memalignvoid outvals sizeof m128i sizeof m128i mm store si128reinterpret cast m128i outvals outvec for int i 0 i sizeofoutvec sizeofoutvals i stdcout outvals i outvalsi stdendl stdcout stdendl tbigval bigval stdendl tunsigned short bigval unsigned short bigval stdendl tunsigned shortint bigval unsigned shortint bigval stdendl stdendlsample execution rowoutvals0 32767outvals1 32767outvals2 32767outvals3 32767outvals4 32767outvals5 32767outvals6 32767outvals7 32767 bigval 990 unsigned short bigval 65535 unsigned shortint bigval 33464the unsigned shortint bigval expression works as desired but it is probably ub right but i cannot find something quite similar with sse i must be missing something but i could not find a primitive to convert four 32bit floats to four 32bit intsedit oops i figured it would be normal for 32bit integer 16bit unsigned integer conversion to use wraparound but i have since learned that mm packs epi32 uses signedsaturate and there does not appear to be a mm packus epi32 is there a way to set the mode or another primitive besides mm packus epi32,"['c++', 'c']" +337530,crawl dynamic web page using htmlunit i am crawling data using htmlunit from a dynamic webpage which uses infinite scrolling to fetch data dynamically just like facebooks newsfeed i used the following sentence to simulate the scrolling down eventwebclientsetjavascriptenabledtruewebclientsetajaxcontrollernew nicelyresynchronizingajaxcontrollerscriptresult srmyhtmlpageexecutejavascriptwindowscrollby0600webclientwaitforbackgroundjavascript10myhtmlpagehtmlpagesrgetnewpagebut it seems myhtmlpage stays the same with the previous one ie new data is not appended in myhtmlpage as a result i can only crawl the first few data on the web page thanks for your help,['javascript'] +337538,android set link with in textview i create a textview dynamically and want to set the text as linkable text value is google i referred to internet blogs like which shows the same way but i could not produce the expected resultsi tried different ways but the output i see is the whole text with text only the code i have tried with is textview tv1 new textviewthistv1setlayoutparamstextoutlayoutparams make linkabletv1setmovementmethodlinkmovementmethodgetinstancetv1settexthtmlfromhtmllgetleftstringspannablestring s new spannablestringlgetleftstringlinkifyaddlinkss linkifyweb urlstv1settexts tv1setmovementmethodlinkmovementmethodgetinstancedialoglayoutaddviewtv1in my output i see google and no link i also tried clean project building it again but no successi am looking to see only google as underlined with blue color as default and on clicking google the browser open with what is lacking in my code to get the output btw for ref i use 64bit win 7 java eclipse android api 822any help is highly appreciated,"['android', 'html']" +337549,what is the best separator to separate multiple emails i am using mailto link to populate bcc of users default email programmem email sqlselect email address from employeecontacts dbquerysqlwhilecontact dbfetchbyassoccontacts ifcontactemail address contactemail addressnull mem emailcontactemail address headerlocation mailtobccmem email my question is what is the best separator to separate multiple emails in bcc field or in my case i am using,['php'] +337558,how do i identify my server name for server authentication by client in c i have recently been trying to make a ssl encrypted serverclient in ci have followed this tutorial on msdn however it required a certificate to be created for the server and client usage using makecertexe so i found an example and it created the certificate finemakecert sr localmachine ss my n cntest sky exchange sk 123456 ctestcerbut now the problem is the server starts and waits for clients when the client connects it uses the machine name which as far as i can gather is my ip in this case127001 and then it requires the servers name which must match the servers name on the certificate testcer i have tried multiple combinations such as test localmachine127001 but cant seem to get the clients given server name to match thus allowing the connection the error i get iscertificate error remotecertificatenamemismatch remotecertificatechainerrors exception the remote certificate is invalid according to the validation procedurehere is the code i am using it differs from the msdn example only in the fact that i assign the certificate path for the server in the app and the machine name and server name of the client toossltcpservercsusing systemusing systemcollectionsusing systemnetusing systemnetsocketsusing systemnetsecurityusing systemsecurityauthenticationusing systemtextusing systemsecuritycryptographyx509certificatesusing systemionamespace examplessystemnet public sealed class ssltcpserver static x509certificate servercertificate null the certificate parameter specifies the name of the file containing the machine certificate public static void runserverstring certificate servercertificate x509certificatecreatefromcertfilecertificate create a tcpip ipv4 socket and listen for incoming connections tcplistener listener new tcplisteneripaddressany 8080 listenerstart while true consolewritelinewaiting for a client to connect application blocks while waiting for an incoming connection type cntlc to terminate the server tcpclient client listeneraccepttcpclient processclientclient static void processclienttcpclient client a client has connected create the sslstream using the clients network stream sslstream sslstream new sslstream clientgetstream false authenticate the server but do not require the client to authenticate try sslstreamauthenticateasserverservercertificate false sslprotocolstls true thisplay the properties and settings for the authenticated stream thisplaysecuritylevelsslstream thisplaysecurityserviceslstream thisplaycertificateinformationsslstream thisplaystreampropertieslstream set timeouts for the read and write to 5 seconds sslstreamreadtimeout 50 sslstreamwritetimeout 50 read a message from the client consolewritelinewaiting for client message string messagedata readmessagesslstream consolewritelinereceived 0 messagedata write a message to the client byte message encodingutf8getbyteshello from the servereof consolewritelinesending hello message sslstreamwritemessage catch authenticationexception e consolewritelineexception 0 emessage if einnerexception null consolewritelineinner exception 0 einnerexceptionmessage consolewritelineauthentication failed closing the connection sslstreamclose clientclose return finally the client stream will be closed with the sslstream because we specified this behavior when creating the sslstream sslstreamclose clientclose static string readmessagesslstream sslstream read the message sent by the client the client signals the end of the message using the eof marker byte buffer new byte2048 stringbuilder messagedata new stringbuilder int bytes 1 do read the clients test message bytes sslstreamreadbuffer 0 bufferlength use decoder class to convert from bytes to utf8 in case a character spans two buffers decoder decoder encodingutf8getdecoder char chars new chardecodergetcharcountbuffer 0 bytes decodergetcharsbuffer 0 bytes chars 0 messagedataappendchars check for eof or an empty message if messagedatatostringindexofeof 1 break while bytes 0 return messagedatatostring static void thisplaysecuritylevelsslstream stream consolewritelinecipher 0 strength 1 streamcipheralgorithm streamcipherstrength consolewritelinehash 0 strength 1 streamhashalgorithm streamhashstrength consolewritelinekey exchange 0 strength 1 streamkeyexchangealgorithm streamkeyexchangestrength consolewritelineprotocol 0 streamsslprotocol static void thisplaysecurityserviceslstream stream consolewritelineis authenticated 0 as server 1 streamisauthenticated streamisserver consolewritelineissigned 0 streamissigned consolewritelineis encrypted 0 streamisencrypted static void thisplaystreampropertieslstream stream consolewritelinecan read 0 write 1 streamcanread streamcanwrite consolewritelinecan timeout 0 streamcantimeout static void thisplaycertificateinformationsslstream stream consolewritelinecertificate revocation list checked 0 streamcheckcertrevocationstatus x509certificate localcertificate streamlocalcertificate if streamlocalcertificate null consolewritelinelocal cert was issued to 0 and is valid from 1 until 2 localcertificatesubject localcertificategeteffectivedatestring localcertificategetexpirationdatestring else consolewritelinelocal certificate is null thisplay the properties of the clients certificate x509certificate remotecertificate streamremotecertificate if streamremotecertificate null consolewritelineremote cert was issued to 0 and is valid from 1 until 2 remotecertificatesubject remotecertificategeteffectivedatestring remotecertificategetexpirationdatestring else consolewritelineremote certificate is null public static void mainstring args string certificate ctestcer ssltcpserverrunservercertificate ssltcpclientcsusing systemusing systemcollectionsusing systemnetusing systemnetsecurityusing systemnetsocketsusing systemsecurityauthenticationusing systemtextusing systemsecuritycryptographyx509certificatesusing systemionamespace examplessystemnet public class ssltcpclient private static hashtable certificateerrors new hashtable the following method is invoked by the remotecertificatevalidationdelegate public static bool validateservercertificate object sender x509certificate certificate x509chain chain sslpolicyerrors sslpolicyerrors if sslpolicyerrors sslpolicyerrorsnone return true consolewritelinecertificate error 0 sslpolicyerrors do not allow this client to communicate with unauthenticated servers return false public static void runclientstring machinename string servername create a tcpip client socket machinename is the host running the server application tcpclient client new tcpclientmachinename 8080 consolewritelineclient connected create an ssl stream that will close the clients stream sslstream sslstream new sslstream clientgetstream false new remotecertificatevalidationcallbackvalidateservercertificate null the server name must match the name on the server certificate try sslstreamauthenticateasclientservername catch authenticationexception e consolewritelineexception 0 emessage if einnerexception null consolewritelineinner exception 0 einnerexceptionmessage consolewritelineauthentication failed closing the connection clientclose return encode a test message into a byte array signal the end of the message using the eof byte mesage encodingutf8getbyteshello from the clienteof send hello message to the server sslstreamwritemesage sslstreamflush read message from the server string servermessage readmessagesslstream consolewritelineserver says 0 servermessage close the client connection clientclose consolewritelineclient closed static string readmessagesslstream sslstream read the message sent by the server the end of the message is signaled using the eof marker byte buffer new byte2048 stringbuilder messagedata new stringbuilder int bytes 1 do bytes sslstreamreadbuffer 0 bufferlength use decoder class to convert from bytes to utf8 in case a character spans two buffers decoder decoder encodingutf8getdecoder char chars new chardecodergetcharcountbuffer 0 bytes decodergetcharsbuffer 0 bytes chars 0 messagedataappendchars check for eof if messagedatatostringindexofeof 1 break while bytes 0 return messagedatatostring public static void mainstring args string servercertificatename null string machinename null user can specify the machine name and server name server name must match the name on the servers certificate machinename args0 if argslength 2 servercertificatename machinename else servercertificatename args1 machinename 127001 servercertificatename davidpc tried test localmachine and 127001 ssltcpclientrunclientmachinename servercertificatename consolereadkey editthe server accepts the clients connection and everything but it times out while waiting for the client to send a message the client wont authenticate with server due to the server name in the certificate being different from the one i supplied in the client well thats my thoughts on it just to clarifyupdateaccording to an answer i have changed the certficiate maker tomakecert sr localmachine ss my n cnlocalhost sky exchange sk 123456 ctestcer and in my client i have machinename 127001 servercertificatename localhost tried test localmachine and 127001 ssltcpclientrunclientmachinename servercertificatenamenow i get the exceptionremotecertificatechainerrors exception the remote certificate is invalid according to the validation procedurewhich is occuring here the server name must match the name on the server certificate try sslstreamauthenticateasclientservername catch authenticationexception e consolewritelineexception 0 emessage if einnerexception null consolewritelineinner exception 0 einnerexceptionmessage consolewritelineauthentication failed closing the connection emessage clientclose return,['c#'] +337567,responsively change div size keeping aspect ratio when i give an image a percent width or height only it will growshrink keeping its aspect ratio but if i want the same effect with another element is it possible at all to tie the width and the height together using percentage,"['html', 'css']" +337586,how to load a pixel struct into an sse register i have a struct of 8bit pixel datastruct attribute aligned4 pixels char r char g char b char ai want to use sse instructions to calculate certain things on these pixels namely a paeth transformation how can i load these pixels into an sse register as 32bits unsigned integers,['c'] +337598,cannot union all on a temporary table i am trying to run the following simple test creating a temp table and then unioning two different selectionscreate temporary table tmp select from peopleselect from tmpunion allselect from tmpbut get a 1137 cannot reopen table tmpi thought temp tables were supposed to last the session whats the problem here,"['mysql', 'sql']" +337630,how to run a wxpython gui app in sublime text 2 i just started to use sublime text 2i use sublime for python but when i use ctrlb it does not run my wxpython gui app it can run a tkinter appwhy is this what do i need to do to run a wxpython app from sublime,['python'] +337658,what does comparison being consistent with equals mean what can possibly happen if my class does not follow this principle from the javadoc of treemap note that the ordering maintained by a sorted map whether or not an explicit comparator is provided must be consistent with equals if this sorted map is to correctly implement the map interface see comparable or comparator for a precise definition of consistent with equals this is so because the map interface is defined in terms of the equals operation but a map performs all key comparisons using its compareto or compare method so two keys that are deemed equal by this method are from the standpoint of the sorted map equal the behavior of a sorted map is welldefined even if its ordering is inconsistent with equals it just fails to obey the general contract of the map interfacecan some one give an concrete example to demonsrate the problem that might occur if ordering is not consistent with equals take for example user defined class that has a natural ordering ie it implements comparable also do all internal classes in jdk maintain this invariant,['java'] +337686,how to remove the vertical scrollbar syntaxhighlighter block i am newbie in webdeveloping and possibly has a primary questioni have installed joomla 25 cms on my site downloaded installed and turned on the syntaxhighlighter plugin then enabled the bash syntax and added nothing more the following code to my pagepre classbrush bash uname alinux laptop 263241generic 89ubuntu smp fri apr 27 209 utc 2012 i686 gnulinuxprei got this resultit is ok but i have no idea why the highlighted vertical scrollbar appears it scrolls only for a one or two pixels so what i have tried is to add a following code to the beginning of my templates css filesyntaxhighlightersyntaxhighlighter divsyntaxhighlighter codesyntaxhighlighter tablesyntaxhighlighter table tdsyntaxhighlighter table trsyntaxhighlighter table tbody overflowy hiddenit does not helped me and i think the problem is deeper do you have any ideas about how to remove this vertical scrollbarupdate if i use the important declaration in templates css the scrollbar thissappear but the block with highlighted code behaves very strange on page scaling,['css'] +337700,what do the c and c standards say about bitlevel integer representation and manipulation i know the c and c standards do not dictate a particular representation for numbers could be twos complement signandmagnitude etc but i do not know the standards well enough and could not find if it is stated to know if there are any particular restrictionsguaranteesreserved representations made when working with bits particularlyif all the bits in an integer type are zero does the integer as whole represent zeroif any bit in an integer type is one does the integer as a whole represent nonzero if this is a yes then some representations like signandmagnitude would be additionally restrictedis there a guaranteed way to check if any bit is not setis there a guaranteed way to check if any bit is set 3 and 4 kind of depend on 1 and 2 because i know how to set for example the 5th bit see 5 in some variable x and i would like to check a variable y to see if it is 5th bit is 1 i would like to know if if x y will work because as i understand this relies on the value of the representation and not whether nor not that bit is actually 1 or 0is there a guaranteed way to set the leftmost andor rightmost bits at least a simpler way than taking a char c with all bits true set by c c c and doing c c char bit 1 for setting the highbit and c c c 1 for the lowbit assuming i am not making any assumptions i shouldt be given these questionsif the answer to 1 is no how could one iterate over the bits in an integer type and check if each one was a 1 or a 0i guess my overall question is are there any restrictionsguaranteesreserved representations made by the c and c standards regarding bits and integers despite the fact that an integers representation is not mandated and if the c and c standards differ in this regard whats their differencei came up with these questions while doing my homework which required me to do some bit manipulating note these are not questions from my homework these are much more abstractedit as to what i refer to as bits i mean value forming bits and am not including padding bits,"['c++', 'c']" +337702,custom url scheme for new facebook ios app does anyone know what the custom url scheme is to open a facebook page in their new ios app i was using fbpagepage id however this does not seem to be working in the recently updated facebook ios app it just opens the app but does not go to the required page,['ios'] +337707,changing default x range in histogram matplotlib i would like to change the default x range for the histogram plot the range of the data is from 7 to 12 however by default the histogram starts right at 7 and ends at 13 i want it to start at 65 and end at 125 however the ticks should go from 7 to 12how do i do it import asciitable import numpy as npimport matplotlibpyplot as pltimport matplotlibmlab as mlabimport pylabfrom pylab import xticksdata asciitablereadfilehmag datacol8visits datacol14origin datacol13n bins patches plthisthmag 30 facecolorgray alignmidxticksrange713pylabrcaxes linewidth80pylabrclines markeredgewidth20 pltxlabelh mag fontsize14pltylabel of targets fontsize14pylabxticksfontsize15pylabyticksfontsize15pltgridtruepltsavefighmag histogrameps facecolorw edgecolorw formatepspltshow,['python'] +337720,isset php isset getsomething getsomething i am looking to expand on my php knowledge and i came across something i am not sure what it is or how to even search for it i am looking at phpnet isset code and i see isset getsomething getsomething i understand normal isset operations such as ifisset getsomething if something is exists then it is set and we will do something but i do not understand the repeating the get again the or the can someone help break this down for me or at least point me in the right direction,['php'] +337741,autofac instanceperhttprequest vs instanceperlifetimescope what are the differences between the two scopesi am building modules in each layer repository service mvc app but in order to have instanceperhttprequest you need the autofacmvc assemblywhich scope should i be using in my repository and service layer,['c#'] +337742,c variable new function within c is it possible to create a new function on the fly to define a variablei know thatstring getresult if a return a return bstring result getresultis possible but i am looking for something likestring result new string getresult if a return a return bis this possible if so would someone demonstrateeditit is possible edit final solutionthis is the end result of what i barbarically hacked togetherfuncstring getresult switch scstatus case servicecontrollerstatusrunning return running case servicecontrollerstatusstopped return stopped case servicecontrollerstatuspaused return paused case servicecontrollerstatusstoppending return stopping case servicecontrollerstatusstartpending return starting default return status changing trayicontext service status getresult,['c#'] +337796,determine if the page has changed using webdriver sometimes web pages visible content depends on the page input elements state for example input element choose your university may appear only after you have chosen student in job field or on clicking some page elements like dropdown menu buttons i am trying to automate the process of finding out such page elements dependencies using selenium webdriver the first idea is to enter some stuff in text input fields set checkedunchecked checkboxes click some buttonslinks etc and see if any elements on the page have appearedthisappeared the problems areis there an easy way to find out if something on the page has appeared well i could make a map from web page elements to visible invisible states after each change and find out if something has changed but is there something builtin for this purposeclicking some buttons might cause loading another page and i want to stay in withing the page i am testing is there a way to determine if click method will cause loading another page and prevent it,['java'] +337800,does gps require internet is it necessary to turn both internet and gps on before i can read my current locationcountry city locality etc in my app if they are then any alternative way to get the location only from gps since the internet availability is an issue,['android'] +337807,get current month and date using jquery i have two dropdownlist that hold months and years documentreadyfunction months optioneq new dategetmonth propselected true alertnew dategetmonth years optioneq new dategetfullyear propselected true alertnew dategetfullyeari wrote the jquery script as above so that when my program runs the dropdown selected value must be the current month and yearbut when i execute the programthe alert gives 7 and 2012 but in my view the current month is selected but the current year is not why and how can i make my dropdown to select current year,"['javascript', 'jquery']" +337826,using emplace with algorithms such as stdfill i have used vectoremplace back in order to avoid constructing temporal objects while filling a vector here you have a simplified versionclass foo public fooint i double d i i d d stdvectorfoo vvreserve10for int i 0 i 10 i vemplace back1 10but i wanted to use stdfill n insteadvreserve10stdfill nstdback inserterv 10 foo1 10in this way temporal copies will be created though i do not know how to use emplace in this situation i guess i would need something like stdback emplacer but i could not find such a thing is that part of c11 but not implemented in gcc yet if it is not part of c11 is there any other way to do that,['c++'] +337832,stdout and stdin relationships possible duplicatedoes reading from stdin flush stdout c standard guarantees that all data contained in the buffer will be printed before next call to stdcin like thisinclude iostreamvoid bar int x stdcout enter an integer 1 stdcin x 2 because of thisisoiec 1488220112742 narrow stream objects narrowstreamobjects2 after the object cin is initialized cintie returns cout its state is otherwise the same as required for basic iosinit 275522743 wide stream objects widestreamobjects2 after the object wcin is initialized wcintie returns wcout its state is otherwise the same as required for basic iosinit 27552but in c there are really no guarantees that everything contained in the stdout buffer will be printed before any attempt to stdininclude stdiohvoid bar int x printfenter an integer 1 scanfd x 2 i know that stdout is line buffered but i do not want to put n character in such situations is using fflush fclose etc is the only right way to get output right before input request in c,"['c++', 'c']" +337839,gridview content thisappears during scrolling i have a gridview in my application in which i want to show text and check boxes just like emails inbox page i use an adapter for that but when i show more than 15 elements the text and check boxes of top rows thisappear so when i scroll upside again they are not visible here is my code public class employeeadaptor extends baseadapter context contextstring tableint posint formatoftablepublic employeeadaptorcontext cstring tabint numberofitemsint format boolean sel context c table tab items numberofitems formatoftable format ifformat is 0 then show text view in first column if it is 1 then show radio button in first column if it is 2 then show check box in first column pos 0public int getcount return itemspublic object getitemint position return positionpublic long getitemidint position return positionpublic view getviewfinal int position view convertview viewgroup parent view v textview text new textviewcontext radiobutton radio new radiobuttoncontext checkbox check new checkboxcontext ifconvertview null v new viewcontext else v convertview ifformatoftable2 position50 position50 checksetidposition5 v check else ifformatoftable0 position50 position50 textsettext v text to set blank text at first position when no need of check else ifposition50 try v text textsettexttablepos textsettextcolorcolorblack textsettextsize20 pos catchexception e ifposition50 textsettypefacetypefacedefault bold return v call to adapter class is astablesetadapternew employeeadaptorthis emptable numberofboxes 0 selectedortablesetadapternew employeeadaptorthis emptable numberofboxes 1 selectedlayout xml file isgridview androidididgridview1 androidlayout widthwrap content androidlayout height360dp androidlayout margintop40dp androidnumcolumns5 androidverticalspacing35dpgridview,['android'] +337840,how to read text files with ansi encoding and nonenglish letters i have a file that contains nonenglish chars and was saved in ansi encoding using a nonenglish codepage how can i read this file in c and see the file content correctlynot workingstreamreader srnew streamreadercapplicationsxmlencodingasciivar ags srreadtoendsrnew streamreadercapplicationsxmlencodingutf8ags srreadtoendsrnew streamreadercapplicationsxmlencodingunicodeags srreadtoendworking but i need to know what is the code page in advance which is not possiblesrnew streamreadercapplicationsxmlencodinggetencoding1252ags srreadtoend,"['c#', '.net']" +337849,signalr getting username i am using signalr and aspnet mvc3 to build a sample chat application here is what my signalr hub looks likepublic class myhubhubithisconnect public task join string username httpcontextcurrentuseridentityname find group based on username string group getgroupusername return groupsaddcontextconnectionid group public void dostuff string group getgroup clientsgroupdostuffonbrowser my problem is that my app crashed when the page loads on stepping through with the debugger i found that httpcontextcurrentuseridentityname is null even though the user has already been authenticated how can i get the username in my task join method,['c#'] +337858,why the exception is not triggered here this is a follow up question of why is this exception is not printed why its showing an errorhere in below code why the arithmeticexception is not triggeredclass exp public static void mainstring args float da1 try d0 a44d no exception triggered here why systemoutprintits not gonna printed aa catcharithmeticexception e systemoutprintlnprint exceptione instead the output comes as followsits not gonna printed ainfinitywhat happens,['java'] +337872,php simple html dom parse img html5 attributes how to use simple html dom parse img html5 attribute dataoriginalhtmls img classlazy altnubifragio a verbania ferite 2 turiste gravi danni chiesto stato di calamita foto titlenubifragio a verbania ferite 2 turiste gravi danni chiesto stato di calamita foto dataoriginal src width130 height98 stylethisplay inline html str get htmlhtmlsfata htmlfindimg foreachfata as newimage echo newimagedataoriginal 0 echo newimagesrc i could get the attribute src but dataoriginal return 0,['php'] +337882,could not load file or assembly this assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded i hvea 3 projects in my solution bl dl and the ui all three projectshave a target framework of net 4 i have doublechecked this by looking at the property page for each project i am receiving the following error message when i try run the website at the hosting environment but not when i run it locallycould not load file or assembly bl or one of its dependencies this assembly is built by a runtime newer than the currently loaded runtime and cannot be loadedthanks in advance,['c#'] +337897,is there any difference between getlayoutinflater and getsystemservicecontextlayout inflater service simple no answer will calm meif there is any difference then what it is,['android'] +337916,why there is no hashable interface in java object in java has hashcode method however it is being used only in associative containers like hashset or hashmap why was it designed like that hashable interface having hashcode method looks as much more elegant solution,['java'] +337942,in git removing dll and pdb files that have accidently been committed i have a git repo that i need to get working without conflicts it is netc mvc repo the problem is dll and pdb files these files have been accidentally committed to the repo so when i do my initial git pull i get all these files committed by another developer i have setup the gitignore like sobinobjapp datafrom other posts i believe that is all i should need to do however if i build my project and run git status it shows numerous dll and pdb files that are going to be committed is this because those files existed in the repo when i cloned it if so what is the best way to go about removing those files,['.net'] +337967,how to integrate d3js chart in c application i am a big fan of mike bostocks d3js chart library d3jsorgi would like to use it to thisplay charts in a c net application but i do not know if it is possibleit may be possible by generating htmjs codes and rendering it in a webbrowser windowhowever i understood d3js library cannot be used locally without a webserver however i did not understood what works without a webserver and what requires a webserver therefore a simple solution does not work has anybody tried to develop that kind of deployment of d3js chartsdo you have an idea on where to start in order to have the most simple solution,"['c#', '.net']" +338000,how to access a linux framebuffer in mono monocairo gtk i am starting to write a small application for linux under the mono framework the application will essentially be a small kiosk frontend with very minimal user interaction this is to replace a previous version of the same application which was 100 text console basedas this will run on a raspberry pi i want to avoid running x and have my application talk to the framebuffer directly i am set on using the mono framework and c as my development language since i know c very well portability is not an issue in this instancei am having some trouble finding appropriate libraries and bindings to let me access the framebuffer from mono however the gtk libraries all bind explicitly to the x11 interface and in any case there do not appear to be prebuilt gtkfb libraries in debian wheezy for the arm softfloat armel architecturethe monocairo library exposes a directfbsurface type however the constructor for that surface takes two intptr arguments and is not documented so i do not know what should be passed into the constructor to properly initialise the framebuffer as a cairo surfacehas anyone worked with mono and c to talk to the linux framebuffer and if so can you provide basic examples to initialise and start drawing onto the fb or point to online documentation to assistupdate 1i thought i would try instantiating the directfbsurface with null for both constructor parameters with the following codepublic static void mainstring args directfbsurface surface new directfbsurfaceintptrnull intptrnull i expected this to generate an exception indicating that null parameter values were not permitted however it instead looks as if the directfbsurface is either not implemented in monocairo or is not compiled into the library shipped with debian wheezy armelunhandled exception systementrypointnotfoundexception cairo directfb surface create at wrapper managedtonative caironativemethodscairo directfb surface create intptrintptr at cairodirectfbsurfacector intptr dfb intptr dfb surface 0x0 in filename unknown0 at infoinschsandboxtestcairoprogrammain systemstring args 0x0 in filename unknown0so it appears that the monocairo approach probably would not work for my needs and as noted above gtk framebuffer library does not seem to be part of debian wheezy for armel is there another set of libraries which i could use to access the linux framebuffer from mono,['c#'] +338004,if i never call new do i ever have to call delete if i manage to construct objects in c by doing object oinstead of object o new objectin every case do i ever need to call delete or will all memory be managed automatically,['c++'] +338034,how can you block or filter ip addresses on heroku is there a way to implement ip filtering or ip access rules much like i would with nginxapache to restrict or block certain ips on herokunote i know this can be done from within my application rails 32 very easily but i do not think this is the most efficient use of my resources on heroku also a rack based solution would be better than implementing the filtering in rails,['ruby-on-rails'] +338050,resteasy mock vs exception mapper vs context resteasy mock framework works fine without exception mapperrequest is received and entity is returned with expected contentsafter registering exception mapper and forcing an exception call fails when innards of resteasy call resteasyproviderfactorygetcontextdatatype which returns null resulting in unexpected error message unable to find contextual data of type javaxservlethttphttpservletrequestcould not find any examples anywhere online of resteasy mock plus an exception mapper and could not find anything useful about the error eitherclient classpackage comfooimport javaxxmlbindannotationxmlaccesstypeimport javaxxmlbindannotationxmlaccessortypeimport javaxxmlbindannotationxmlrootelementimport javaxxmlbindannotationxmltypexmlaccessortypexmlaccesstypefieldxmltypename footype proporder namexmlrootelementname foopublic class foo protected string name public string getname return name public void setnamestring value thisname value object factorypackage comfooimport javaxxmlbindannotationxmlregistryxmlregistrypublic class objectfactory public objectfactory public foo createfoo return new foo validation exceptionpackage comfoopublic class validationexception extends runtimeexception private static final long serialversionuid 8100360206713223313l public validationexceptionstring message supermessage public validationexceptionexception innerexception superinnerexception public validationexceptionstring message exception innerexception supermessage innerexception service endpointpackage comfooimport javaxwsrsgetimport javaxwsrspathimport javaxwsrsproducespathrestv1public class fooservice get pathfoo producesapplicationxml public foo alwaysblowup throws validationexception if systemcurrenttimemillis 0 throw new validationexceptionfoo return null exception mapperpackage comfooimport javaxservlethttphttpservletrequestimport javaxwsrscorecontextimport javaxwsrscorehttpheadersimport javaxwsrscoremediatypeimport javaxwsrscoreresponseimport javaxwsrscoreresponseresponsebuilderimport javaxwsrscoreresponsestatusimport javaxwsrsextexceptionmapperimport javaxwsrsextproviderproviderpublic class fooexceptionmapper implements exceptionmappervalidationexception context private static httpservletrequest request context private static httpheaders headers override public response toresponsevalidationexception exception mediatype mediatype nullset breakpoint on line belowstep over line and you get the exception in the logsstep into the line and the problem is in resteasyproviderfactorypublic static t t getcontextdataclasst type return t getcontextdatamapgettype type javaxservlethttphttpservletrequestthe type is not in the map so it returns nullthe null results in this error in contextparameterinjectorprivate class genericdelegatingproxy implements invocationhandler public object invokeobject o method method object objects throws throwable try object delegate resteasyproviderfactorygetcontextdatatype if delegate null throw new loggablefailureunable to find contextual data of type typegetname error in logs string acceptheader requestgetheaderaccept if mediatypeapplication xmlequalsacceptheader mediatype mediatypeapplication xml type else if mediatypeapplication jsonequalsacceptheader mediatype mediatypeapplication json type else mediatype headersgetmediatype if mediatype null mediatype mediatypeapplication xml type responsebuilder builder responsestatusstatusbad request buildertypemediatype return builderbuild testpackage comfooimport javaneturisyntaxexceptionimport orgjbossresteasycorethispatcherimport orgjbossresteasymockmockthispatcherfactoryimport orgjbossresteasymockmockhttprequestimport orgjbossresteasymockmockhttpresponseimport orgjbossresteasypluginsserverresourcefactorypojoresourcefactorypublic final class testfooexceptionmapper public static void mainstring args throws urisyntaxexception thispatcher thispatcher mockthispatcherfactorycreatethispatcher thispatchergetregistryaddresourcefactorynew pojoresourcefactoryfooserviceclass thispatchergetproviderfactoryaddexceptionmapperfooexceptionmapperclass mockhttprequest request mockhttprequestgetrestv1foo mockhttpresponse response new mockhttpresponse thispatcherinvokerequest response erroraug 26 2012 104426 pm orgjbossresteasycoresynchronousthispatcher severe failed executing get restv1forgjbossresteasyspiloggablefailure unable to find contextual data of type javaxservlethttphttpservletrequest at orgjbossresteasycorecontextparameterinjectorgenericdelegatingproxyinvokecontextparameterinjectorjava56 at proxy18getheaderunknown source at comfoofooexceptionmappertoresponsefooexceptionmapperjava51 at comfoofooexceptionmappertoresponsefooexceptionmapperjava1 at orgjbossresteasycoresynchronousthispatcherexecuteexceptionmappersynchronousthispatcherjava330 at orgjbossresteasycoresynchronousthispatcherunwrapexceptionsynchronousthispatcherjava359 at orgjbossresteasycoresynchronousthispatcherhandleapplicationexceptionsynchronousthispatcherjava348 at orgjbossresteasycoresynchronousthispatcherhandleexceptionsynchronousthispatcherjava220 at orgjbossresteasycoresynchronousthispatcherhandleinvokerexceptionsynchronousthispatcherjava196 at orgjbossresteasycoresynchronousthispatchergetresponsesynchronousthispatcherjava551 at orgjbossresteasycoresynchronousthispatcherinvokesynchronousthispatcherjava513 at orgjbossresteasycoresynchronousthispatcherinvokesynchronousthispatcherjava125 at comfootestfooexceptionmappermaintestfooexceptionmapperjava20,['java'] +338053,tabdelimited file using csvreader not delimiting where i expect it to i am trying to loop through a tabdelimited file of election results using python the following code does not work but when i use a local file with the same results the commented out line it does work as expectedthe only thing i can think of is some headers or content type i need to pass the url but i cannot figure it outwhy is this happeningimport csvimport requestsr requestsget data rtextdata opendatamediaresultstxt rreader csvreaderdata delimitertfor row in reader print rowresults in 23118 david frazie,['python'] +338057,removing multiple spaces in nsstring i have a nsstring this has multiple spaces i want to trim those spaces and make a single space for eghowareyou into how are youdots are simply spacesi have tried withnsstring trimmedstring user ids stringbytrimmingcharactersinset nscharacterset whitespacecharactersetit not seems to work any idea,"['ios', 'objective-c', 'iphone']" +338068,can i develop net 45 app using vs2010 i have installed net 45 framework from after installing the 45 framework i restarted the machine in vs 2010 if any new project is created by default 40 framework is assigned in project properties applicationtarget framework is assigned as net framework 40 but i want to change to 45 framework but 45 framework is not listed my question is should i do some settings changes to list 45 framework in vs2010 or i cannot develope any app using net 45 in vs2010thanks saran,['.net'] +338073,getting the android context in an adapter in many of the code samples that i find on the internet the context is obtained in the constructor of an adapterthis context is used to get an inflater to inflate the views in getview methodmy question is why bother getting the context in the constructor when it can easily be obtained like so layoutinflater inflater override public view getviewint position view convertview viewgroup parent ifinflater null context context parentgetcontext inflater layoutinflater contextgetsystemservicecontextlayout inflater service return convertview also is there any reason not to use the above method because it till now i have not faced any problem in using it,['android'] +338074,javascript sort sparse array keep indexes what is the best method to sort a sparse array and keep the elements on the same indexesfor example a0 3 a1 2 a2 6a7 4a8 5i would like after the sort to have a0 2 a1 3 a2 4 a7 5 a8 6,['javascript'] +338079,why pointer type cast does not work on template nontype parameters i have the following codetemplate const char pstruct atemplate int istruct eextern constexpr int i 0constexpr float f 0fextern constexpr char c 0int mainint argc const char argv ac b works aconst char i a error could not convert template argument aconst char ia to aconst chara eintf e works return 0why the line aconst char i a is wrong i compiled it with g461 with stdc0xedit as charles suggested that reinterpret cast is not permitted in a constant expression i change the above code to the followingstruct basestruct derived public base template const base pstruct aextern constexpr base base extern constexpr derived derived abase a worksaconst basederived b error could not convert template argument aconst base deriveda to aconst baseatherefore not only reinterpret cast is not allowed using astatic castconst basederived yields the same errorto b342 n aconst base0 b error could not convert template argument a0ua to aconst basea,['c++'] +338117,inner class access to outer class method same method names i got a class and a subclass01 public class a02 void test03 public class b04 void test05 test06 07 08 ok in line 05 id like to access the method test of class a but i go into a loop because i dont know how to specify to use the method of class aany ideas,['java'] +338122,remove dom element from variable with jquery please help me solve thisi have got thisvar textli idjob1job 1li li idjob2job 2li li idjob3job 3liand i want to remove one element something like thisjob2textremovethis doesnt work is there a way how to do it thankseditand i want to save result back to text textli idjob1job 1lili idjob3job 3li,"['jquery', 'html']" +338125,how to convert json into pojo in java using jackson i am using spring 312 and i need to parse a json object into pojothis is the json that i need to parseperson id 2 dog dateofbirth 20120820 0 price 10 i need to convert this json object which is combined from two objects into one pojo here it ispublic class myclass public myclass public myclastring personsid timestamp dogsdateofbirth bigdecimal dogsprice assign each parameter to the appropriate field private string personsid private timestamp dogsdateofbirth private bigdecimal dogsprice getters and setters for each fieldfor that matter i used objectmapper mapper new objectmapper now since i have several json objects my code looks like this string json a json with several objects as above jsonnode tree mapperreadtreejson iteratorjsonnode iter treepathdatagetelements while iterhasnext jsonnode node iternext myclass myclass mapperreadvaluenode myclassclass do something with myclass object when i run this i get the following exceptionorgcodehausjacksonmapjsonmappingexception no suitable constructor found for type simple type class myclass can not instantiate from json object need to addenable type informationi tried to create a simple pojo personpublic class person private string id public person public personstring id thisid id getter and setter and do the followingperson person mapperreadvaluenodepathperson personclassi get this same exceptionorgcodehausjacksonmapjsonmappingexception no suitable constructor found for type simple type class person can not instantiate from json object need to addenable type informationi tried to read some about the type information but could not understand how it can help me herehow can i convert this json into my pojothanks,['java'] +338131,use progress dialog in footer i am making an app in which i have to add progress dialog in footer view but i am unable to get any progress dialog in footer viewmain activityi want to add progress dialog in footer in this classpublic class mainactivity extends activity implements onscrolistener all variablesxmlparser parserdocument docstring xmllistview lvlistviewadapter adapterarraylisthashmapstring string menuitemsprogressdialog pdialogprivate string url pagingpage1 xml node keysstatic final string key item item parent nodestatic final string key id idstatic final string key name nameprogressdialog dialog flag for current pageint current page 1overridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain lv listview findviewbyidridlist menuitems new arraylisthashmapstring string parser new xmlparser xml parsergetxmlfromurlurl getting xml doc parsergetdomelementxml getting dom element nodelist nl docgetelementsbytagnamekey item looping through all item nodes item for int i 0 i nlgetlength i creating new hashmap hashmapstring string map new hashmapstring string element e element nlitemi adding each child node to hashmap key value mapputkey id parsergetvaluee key id id not using any where mapputkey name parsergetvaluee key name adding hashlist to arraylist menuitemsaddmap loadmore button dialognew progressdialogthis button btnloadmore new buttonthis btnloadmoresettextload more adding load more button to lisview at bottom lvaddfooterviewdialog i want to use progress dialog in footer lvaddfooterviewdialog getting adapter adapter new listviewadapterthis menuitems lvsetadapteradapter lvsetonscrolistenerthis lvaddfooterviewdialoggetlistview listening to load more button click event ifdialogisshowing btnloadmoresetonclicklistenernew viewonclicklistener public void onclickview arg0 starting a new async task new loadmorelistviewexecute listening to listview single row selected lvsetonitemclicklistenernew onitemclicklistener public void onitemclickadapterview parent view view int position long id getting values from selected listitem string name textview viewfindviewbyidridname gettexttostring starting new intent intent in new intentgetapplicationcontext test123class inputextrakey name name startactivityin async task that send a request to url gets new list view data appends to list view private class loadmorelistview extends asynctaskvoid void void override protected void onpreexecute showing progress dialog before sending http request ifdialogisshowing dialogcancel else pdialog new progressdialog mainactivitythis pdialogsetmessageplease wait pdialogsetindeterminatetrue pdialogsetcancelablefalse pdialogshow protected void doinbackgroundvoid unused runonuithreadnew runnable public void run increment current page current page 1 next page request url pagingpage current page xml parsergetxmlfromurlurl getting xml doc parsergetdomelementxml getting dom element nodelist nl docgetelementsbytagnamekey item looping through all item nodes item for int i 0 i nlgetlength i creating new hashmap hashmapstring string map new hashmapstring string element e element nlitemi adding each child node to hashmap key value mapputkey id parsergetvaluee key id mapputkey name parsergetvaluee key name adding hashlist to arraylist menuitemsaddmap get listview current position used to maintain scroll position int currentposition lvgetfirstvisibleposition appending new data to menuitems arraylist adapter new listviewadapter mainactivitythis menuitems lvsetadapteradapter setting new scroll position lvsetselectionfromtopcurrentposition 1 0 return null protected void onpostexecutevoid unused closing progress dialog pdialogthismiss public void onscrollabslistview arg0 int arg1 int arg2 int arg3 todo autogenerated method stub dialogshow lvsetonscrolistenerthis lvaddfooterviewdialoggetlistview new loadmorelistviewexecutepublic void onscrollstatechangedabslistview arg0 int arg1 todo autogenerated method stub new loadmorelistviewexecuteadapterpublic class listviewadapter extends baseadapter private activity activityprivate arraylisthashmapstring string dataprivate static layoutinflater inflaternullpublic listviewadapteractivity a arraylisthashmapstring string d activity a datad inflater layoutinflateractivitygetsystemservicecontextlayout inflater servicepublic int getcount return datasizepublic object getitemint position return positionpublic long getitemidint position return positionpublic view getviewint position view convertview viewgroup parent view viconvertview ifconvertviewnull vi inflaterinflaterlayoutlist item null textview name textviewvifindviewbyidridname hashmapstring string item new hashmapstring string item datagetposition setting all values in listview namesettextitemgetname return vixmlparserpublic class xmlparser constructorpublic xmlparser public string getxmlfromurlstring url string xml null try defaulthttpclient defaulthttpclient httpclient new defaulthttpclient httppost httppost new httpposturl httpresponse httpresponse httpclientexecutehttppost httpentity httpentity httpresponsegetentity xml entityutilstostringhttpentity catch unsupportedencodingexception e eprintstacktrace catch clientprotocolexception e eprintstacktrace catch ioexception e eprintstacktrace return xml return xml getting xml dom element param xml string public document getdomelementstring xml document doc null documentbuilderfactory dbf documentbuilderfactorynewinstance try documentbuilder db dbfnewdocumentbuilder inputsource is new inputsource issetcharacterstreamnew stringreaderxml doc dbparseis catch parserconfigurationexception e logeerror egetmessage return null catch saxexception e logeerror egetmessage return null catch ioexception e logeerror egetmessage return null return doc getting node value param elem element public final string getelementvalue node elem node child if elem null if elemhaschildnodes for child elemgetfirstchild child null child childgetnextsibling if childgetnodetype nodetext node return childgetnodevalue return getting node value param element node param key string public string getvalueelement item string str nodelist and itemgetelementsbytagnamestr return thisgetelementvaluenitem0 any help will be appreciated,['android'] +338132,bootstraps javascript works locally but not when deployed to a server i downloaded the barebone example of twitters bootstrap and customized it i tested it locally with wamp server and everything works perfectly both the css and the jscripti uploaded the files to my webhosting service and the jscript just does not work i noticed it because dropdown boxes stopped workingi searched and found other persons with the same problem but they all are using ruby and i am not just the play cssjscript provided by bootstrap besides they said the solution was to include the bootstrapjs first and then the jqueryjs well i tried it and it did not work i even included the not minified js and still it did not worki am using the same browser chrome for local and remote testing i also tried different hosting services and the problem occurred in bothhelp is much appreciatedother similar questionsjavascript features work on localhost but not when deployed to herokutwitter bootstrap drop down suddenly not working,"['javascript', 'jquery']" +338163,different declarations of the same functionglobal variable in two files i have 2 questions regarding different declarations of the same function and global variable in two files in case of c and c as welldifferent function declarationsconsider the following code fragmentsfile 1cvoid fooint aint mainvoid fooafile 2cinclude stdiohvoid foochar a printfc a prints a gccas we can see the prototype differs from the definition located infile 2c however the function prints expected valueif it comes to c the above program is invalid due to undefinedreference to fooint at link time it is probably caused bypresence of other function signatures in comparison with c wherea function name does not contain any extra characters indicating thetype of function argumentsbut when it comes to c then what since the prototypes with the samename have the same signature regardless of the number of argumentsand its types linker would not issue an error but which typeconversions are performed in here does it look like this a int back to char or maybe this behavior isundefinedimplementationdefined different declarations of a global variableweve got two files and two different declarations of the sameglobal variablefile 1cinclude stdiohextern int aint mainvoid printfd a prints 65 g and gccfile 2cchar a aboth in c and c the output is 65though i would like to know what both standards say about that kind ofsituationin the c11 standard i have found the following fragmentj511 multiple external definitions annex j5 common extensions there may be more than one external definition for the identifier of an object with or without the explicit use of the keyword extern if the definitions thisagree or more than one is initialized the behavior is undefined 692notice that it refers to presence of two and more definitions inmy code there is only one so i am not sure whether this article is a good point of reference inthis case,"['c++', 'c']" +338174,from list of integers get number closest to a given value given a list of integers i want to find which number is the closest to a number i give in input mylist 4188443 mynumber 5 takeclosestmylist mynumber4is there any quick way to do this,['python'] +338238,gracefully shutting down sidekiq processes does anyone know how to find sidekiqs pidfile to gracefully shut it downrunning ps ax grep sidekiq and then running sidekiqctl stop pid from grep consistently gives a no such pidfile errorcntlc and cntld also seem to have no effectclosing the process window and reopening a new window does not kill the process as it appears to be running as a daemonthe only consistent fix i have found is rebooting,['ruby'] +338240,change direction of actionbar i am using actionbar in my project i want to change direction of actionbar items means locate tab icons and logo in the right side of screen and locate menu items in the left side of screen i googled but i did not find any useful thing aslo i read xml resource of theme and style in api 14 but again i did not find any solution,['android'] +338246,javascript equality triple equals but what about greater than and less than i was explaining to a colleague that you should use and and and of course when comparing variables in javascript so that it does not coerce the arguments and get all froopy and confusing but they asked me a two part question that i did not know the answer to and thought i would ask the experts here specifically it iswhat about and when they compare do they also coerce the arguments or not why is not there some sort of and operator probably need to be some other syntax as i would guess they would be bit shift operators if it is going along the whole c style but you get the gistso i can write a test to find the answer to the first part which i did here it is demo the difference between and alert5 5alert5 5 check out what happens with alert5 4 alert5 4and it returnedtruefalsetruetrueso it does look like the is doing the coercion since 4 and 4 return the same result so how about the second partis there some sort of operator for and that do not coerce the type or how can i change my test to perform the test safely,['javascript'] +338256,mvc3 date validation using globalize library script i am trying to get my mvc3 ef4 project to work with the javascript datepicker but i am running into issues as i want the date to be in the uk format ddmmyi have spent several hours researching this issue and i have decided to implement the globalize library scripts as i have seen in this linkhowever i am getting a uncaught typeerror cannot read property methods of undefined in the javascript coming from the validatormethodsdate line when i run it my knowledge of javascript is pretty limited and all the examples i have found that use the globalize library have no mention of this error and therefore i am quite stumpedi have shown the relevant code from my view belowscript srcurlcontentscriptsjqueryvalidateminjs typetextjavascriptscriptscript srcurlcontentscriptsjqueryvalidateunobtrusiveminjs typetextjavascriptscriptscript srcurlcontentscriptsjquery151js typetextjavascriptscriptscript srcurlcontentscriptsjquery151minjs typetextjavascriptscriptscript srcurlcontentscriptsjqueryui1811js typetextjavascriptscriptscript srcurlcontentscriptsjqueryui1811minjs typetextjavascriptscriptscript srcurlcontentscriptsjqueryglobalizeglobalizejs typetextjavascriptscriptscript srcurlcontentscriptsjqueryglobalizeculturesglobalizecultureengbjs typetextjavascriptscriptlink hrefcontentthemesbasejqueryuiallcss relstylesheet typetextcss script typetextjavascript globalizecultureengb validatormethodsdate function value element return thisoptionalelement globalizeparsedatevalue scriptscript typetextjavascript documentreadyfunction datedatepicker dateformat ddmmyy scriptsnipdiv classeditorfield htmltextboxexpires modelexpires new class date htmlvalidationmessageformodel modelexpiresdivcould someone please help me fix this issuethanks very much,['javascript'] +338258,using custom fonts using css i have seen some new websites that are using custom fonts on their sites other than the regular arial tahoma etcand they support a nice amount of browsershow does one do that while also preventing people from having free access to download the font if possible,['css'] +338300,msbuild build order issue prebuild steps first or dependent projects first i have a project a depending on project b project a has some prebuild tasks that is dependent of some generated files from project b when i build in visual studio no problem but when using msbuildexe then there is problem because the build order is as prebuild steps failed because b has not been compiledb is compiled expected to be executed firsta is compiledis it the expected behaviour using msbuildis there a way to tell msbuild to do b first before as prebuild stepsi am using vs2010 c and ccli i do not think if offeres additional info but here is how it is calledrunning process cwindowsmicrosoftnetframeworkv4030319msbuildexe devbuildmyprojsln tclean pconfigurationreleaseplatformwin32,['c#'] +338302,custom sections for enumerated objects of array in nsoutlineview i am trying to create a nsoutlinevew with a custom header group parent node for listed objects note i have cellbased nsoutlineview for example it look like as the xcode navigator or numbers sidebar i used the default groups for the separation properties per category but it is looks like not as what i want i need a parent node cell which i will can visually adjust add a controls elements and imagei tried to do this by passing an array of objects to nsdictionary giving each group a certain specific key and a result via nslog everything is thisplayed correctly but the transfer of this variable as the source for the program nsoulineview failsprojectviewcontrollerhinterface projectviewcontroller nsviewcontroller nsoutlineviewdatasource nsobject iboutlet nsoutlineview outlineview fsentity contentproperty readonly assign nsmutablearray objectsendprojectviewcontrollermimplementation projectviewcontroller idinitwithnibnamensstring nibnameornil bundlensbundle nibbundleornil self super initwithnibnamenibnameornil bundlenibbundleornil if self initialization code here setting default path to the local file or directory nsstring home nshomedirectory nsurl url nsurl alloc initfileurlwithpathhome content fsentity alloc initwithurlurl self definecontentnsoutlineview nslogarray objects basic nonfiguration an instance nsoutlineview self configurationnsoutlineview return selfsynthesize objects objects idoutlineviewnsoutlineview outlineview childnsintegerindex ofitemiditem return item nil contentchildren objectatindexindex fsentity itemchildren objectatindexindex booloutlineviewnsoutlineview outlineview isitemexpandableiditem return item nil contentchildrencount 0 fsentity itemchildrencount 0 nsintegeroutlineviewnsoutlineview outlineview numberofchildrenofitemiditem return item nil contentchildrencount fsentity itemchildrencount idoutlineviewnsoutlineview outlineview objectvaluefortablecolumnnstablecolumn tablecolumn byitemiditem if item iskindofclassfsentity class return fsentity item title return nil voidoutlineviewnsoutlineview outlineview willthisplaycellidcell fortablecolumnnstablecolumn tablecolumn itemiditem if cell iskindofclassimageandtextcell class imageandtextcell textfield imageandtextcell cell textfield setimageitem icon voiddefinecontentnsoutlineview nsmutablearray objects nsmutablearray arraywithobjectsnsdictionary dictionarywithobjectsandkeysfinder title nsarray arraywithobjectsnsdictionary dictionarywithobjectcontentchildren forkeytitle nil childrennsnumber numberwithboolyes header nil nil objects objects voidconfigurationnsoutlineview outlineview sizelastcolumntofit outlineview setfloatsgrouprowsno outlineview reloaddata outlineview expanditemnil expandchildrenyesendto easier would imagine how it would look i showed it on the scheme a14 finder files aa a 03143553file a desktop a documents a downloads a movies a music a pictures and what i have now nsoulineview without using nstreecontroller 03143553file a desktop a documents a downloads a movies a music a pictures i know about the example apple sourceview but i do not know how to add to the created group array of objects files and folders nstreecontoller thisplay only the first elements of the hierarchy without includes a14 finder files 03143553file desktop documents downloads movies music pictures modified method of sourceview example voidaddfindersection self addfolderfinder files nserror error nil nsenumerator urls nsfilemanager defaultmanager contentsofdirectoryaturlselfurl includingpropertiesforkeysnsarray arraywithobjects nil optionsnsdirectoryenumerationskipshiddenfiles errorerror objectenumerator for nsurl url in urls bool isdirectory if nsfilemanager defaultmanager fileexistsatpathurl path isdirectoryisdirectory if isdirectory self addchildurl path withnameno selectparentyes else self addchildurl path withnameno selectparentyes self selectparentfromselectionthis method thisplays only the first objects as shown it on the latter schemeand one more question as i said before how to add to the node finder files button to the right side of the cellcan you help me with this i know maybe is not so hard but i just began learn objectivec and i do not know how to do this thanks,['objective-c'] +338307,how to set downloading file name in aspnet mvc web api in my apicontroller class i have following method to download a file created by server public httpresponsemessage getint id try string dir httpcontextcurrentservermappath location of the template file stream file new memorystream stream result servicegetmyformid dir file if result null return requestcreateresponsehttpstatuscodenotfound resultposition 0 httpresponsemessage response new httpresponsemessage responsestatuscode httpstatuscodeok responsecontent new streamcontentresult return response catch ioexception return requestcreateresponsehttpstatuscodeinternalservererror everything is working perfect except that default downloading file name is its id so user might have to type hisher own file name at save as dialog each time is there any way to set a default file name in the code above,['c#'] +338312,how to fail a test that is stuck in an infinite loop i have some code that produces an infinite loop now i need to write a test that will fail after about 200ms 200ms will indicate that the code is in the infinite loopfor examplepublic void codeundertest whiletrue,"['c#', '.net']" +338355,where cfbundlename is being used from this old question whats the difference between bundle thisplay name and bundle name in cocoa applications info plistit points to the official docs which saycfbundlenamecfbundlename string ios os x identifies the short name of the bundle this name should be less than 16 characters long and be suitable for thisplaying in the menu bar and the appas info window you can include this key in the infopliststrings file of an appropriate lproj subdirectory to provide localized values for it if you localize this key you should also include the key acfbundlethisplaynameacan anyone tell how to show this name in ios i was never able to show this value in my iphone,"['iphone', 'objective-c', 'ios']" +338359,invoke a function after right click paste in jquery i know we can use bind paste event as belowidbindpaste functione alertpasting but the problem is that it will call before the pasted text paste i want a function to be triggered after the right click paste text pasted on the input field so that i can access the pasted value inside the event handler functionchange event also does not help currently i use keyup event because i need to show the remaining characters count while typing in that input field,"['javascript', 'jquery']" +338406,evaluation order of named parameters possible duplicateare parameters evaluated in order when passed into a method say i have void foo int x int yand call it byfooy gennum x gennumdoes c guarantee the evaluation order of x and y in this case,['c#'] +338411,ios game kit turn based match programatic rematch i have a 2player ios turnbased game that uses the game center and gkturnbasedmatchis there a way to programmatically rematch an opponent after a match has finishedi would like to give the players onebutton access to starting a new match with each otherif there is not a one button approach what are some potential alternatives,['ios'] +338457,java 8 prerelease interface member variables are public members variables in java 8 interfaces a feature or an implementation sideeffectdefectthis question pertains to the prerelease java 8 build lambda8b50linuxx6426 jul 2012targzjava 8 introduces new features to interfaces in the form of default methods casual testing with the jdk8 lambda compiler allows interfaces of this formpublic interface foo public int foo 0 int foo default return foo sample implementing typepublic class fooimpl implements foo public int foo 1this code follows the standard conventions for variable shadowingfoo f new fooimplsystemoutprintlnffoosystemoutprintlnffoosystemoutprintlnnew fooimplfoutput001the documentation jsr 335 lambda expressions for the javaa programming language version 051 does not mention member variables i am inclined to think the compiler is being too tolerant but perhaps i have missed something,['java'] +338459,thisable same origin policy in mobile safari i have an html5javascript app that was originally written to run in certain cars basically i need to set up my app to run in the browser for a simple demo to a customeri am using jquery ajax which is causing problems due to the same origin policy i have found plenty of ways to thisable this in desktop browsers but not mobile onesmy goal is to demo the app on an ipad in mobile safari is there any way to temporarily thisable the same origin policy on an ipad,"['javascript', 'html']" +338466,javascript eventemitter multiple events once i am using nodes eventemitter though other event library suggestions are welcomedi want to run a function once if several events are fired multiple events should be listened to but all of them are removed if any one of the events fires hopefully this code sample demonstrates what i am looking forvar game new eventemittergameonceplayerquit playerthisconnect function endgamewhat is the cleanest way to handle thisnote need to remove bound functions individually because there will be other listeners bound,['javascript'] +338511,database design for posts and comments if one post has many comments and the comments are essentially the same as posts eg they have a title pictures and audio etc should i create two tables or just onefor example if i only use one table i can have a parent id column so if it is not a reply to anything it would be null otherwise it would have the id of the parent post on the other hand i can create a post table and a comments table comments can also reply back to other comment so this could get confusing quick post id title content image audio parent idorpost commentsid idtitle titlecontent contentimage author id audio post idauthor id image audiowhat the second option would allow is creating indexes infact i would not even have to add author id or post id if i use indexes from the start will iwhat are you thoughts on this so which would be more efficient i thinking of using redbeanphp for this,"['php', 'mysql']" +338529,iphone how to create a custom album and give custom names to photos in camera roll programmatically i am developing an iphone photo application so i need to create a separate album with a name my album in camera roll and i need to save my uiimageview image with custom name for example my imagepng inside the newly created directory how can i do this,"['iphone', 'ios']" +338567,how to center a view using relativelayout i wanted to know how to center a view between two other views or between a view and the parent edge using relativelayout for example if i have the followinghow do i vertically center the button between the imageview and the bottom of the screen using relativelayouti am looking for a solution wherethe button is not stretched in any way there are no nested layoutsand i am trying to do this in the xml layout not programmatically,['android'] +338583,angle attribute in android gradient i am going through test example where for some image background they are using gradientthe code goes like this xml version10 encodingutf8 shape xmlnsandroid gradient androidstartcolorff0 androidcentercolor00ff00 androidendcolor0ff androidangle180 corners androidradius5dp shapein the above xml i did not get angle attribute but when i change the value of angle slightly the pattern slants can any one explain me how exactly it works,['android'] +338596,fpdf error this document testcopypdf probably uses a compression technique which is not supported by the free parser shipped with fpdi i am running the following code and giving me this error fpdf error this document testcopypdf probably uses a compression technique which is not supported by the free parser shipped with fpdi i used another pdf named testpdf and that works fine but it is giving me error in testcopypdf i think this is parser problem anyone know any other parser that can be used with fpdf to avoid this errormy coderequirefpdf17fpdfphp requirefpdf17fpdiphp initiate fpdi pdf new fpdi while ob get levelob end cleanheadercontentencoding none true set the sourcefile pagecount pdfsetsourcefiletestcopypdfi want to split pdf in two pdfs and want to attach both pdfs in file attachments fieldhow to save pdf to server can it be possible with fpdf,['php'] +338604,how to set up my personal keyboard as standard input in my app i created a small keyboard to replace the standard android keyboard what should i do to set my keyboard as standard input in my appthanks,['android'] +338611,viewpager onpageselected for first page so it appears that when using a viewpager the onpageselected listener does not get called for the first page same issue as thisi have some logic that populates some more expensive ui elements for the currently selected page and this works when page is changed but it does not work for the first page if i set the current item after the listener the callback gets fired for the first page but the view has not been initialized yet so i cannot manipulate it inside pageradapterinstantiateitemviewholder vh new viewholdercursormovetopositionpositionvhview adapternewviewcontext cursor null set position as tag so we can retrieve it with findviewbytagvhviewsettagposition viewpager collectionaddviewvhview0 return vh inside myactivityoncreatepageradapter new singlemessagepageradapterthis cursorpager viewpagerfindviewbyidridmessage pagerpagersetadapterpageradapterpagersetonpageselectedlistenerthispagersetcurrentitemselecteditem inside myactivityonpageselected retrieve tagged viewview view pagerfindviewwithtagposition here view ends up being null because pageradapterinstantiateitem has not yet been run so i guess my question is at which point in the activity lifecycle can i be certain that the viewpager has initialized the view i tried doing this inside activityonattachedtowindow and activityonresume but it appears both of these get fired before pageradapterinstantiateitem,['android'] +338614,how to make a beep in android i would like my app beep with a specific frequency and duration in the windows equivalent of this app written in c i used a c dll with the functionbeepfrequency duration is this the same in android or at least how can i put my c dll in the projecti would prefer not to use prebuilt mp3s or system sound because i would like to give the user the choice of the frequency and duration,['android'] +338617,jquery etargethasclass not working i dynamically create a new div with a textbox class and id and some other elements inside of it and later on in my code i bind that div to the click event and thisplay the element clicked like sotextbox ibindclick functionevent alerteventtargetclassnamethis is fine and it will give me textbox as one of the classes thisplayedbut eventtargethasclass does not seem to work so when i do the following nothing happenstextbox ibindclick functionevent ifeventtargethasclasstextbox alertgot it i tried it a few different ways and it appears to me that eventtargethasclass just does not work is there another way to deal with events or am i doing something wrong,['jquery'] +338645,how to convert hashmap to json object in java how to convert or cast hashmap to json object in java and again convert json object to json string,['java'] +338675,how to add concatenate multiple nsstring in one string in iphone i have 5 string i want that they must be store in singe nsstring all the values separate with sign nsstring firstali nsstring secondimran nsstring thirdaliimran nsstring fourthimranali nsstring fifthali imran jamshedi want to all these in single nsstring to store and all values separated by given sign,"['objective-c', 'ios']" +338686,internet listener android example i am working on android app that will continuously remains connected with internet if internet is down that it should give appropriate message to useris there any thing like internet listener or how to implement this event that when ever internet connection is not available it should give alert,"['java', 'android']" +338692,clone or arrayscopyof in an effort to reduce mutability should we rather use public void setvaluesstring newvals thisvals newvals null null newvalsclone orpublic void setvaluesstring newvals thisvals newvals null null arrayscopyofnewvals newvalslength,['java'] +338705,chrome caching css but not loading images inside css file were having a weird problem at work that happens only in chrome it looks like the css file is getting cached and the content of this file is not getting redownloaded the problem is that when using a fresh session for example private session the image mainspritepng is not getting thisplayedafter some tests i believe the problem is related to us doing redirects at the beginning if the user is not authenticated from what i understand it might not complete the download of the sprites linked inside the css files it will cache an invalid object as soon as the redirect starts and then on the following pages it will fail to thisplay a correct image since it cached something wrong the strange thing is that it actually loads the image completely at some point but it looks like it is not refreshing it in memory i did a timeout of one second before starting redirects on first load and images correctly thisplay this is a quick fix and i cannot expect every computer to load in 1 second every images contained in the css editas far as i can say it really looks like a race condition i changed the order of loading we use requirejs instead of loading js after css i start js loading before and images are getting loaded correctly now on my local server if someone is interested to look into it edit 2when images are not visible opening new tabs will have the same problem closing the browser and reopening it will work on first load and images is not being downloaded but loaded from cache which means that before closing the browser the image was indeed downloaded,['css'] +338715,codeigniter how can i encrypt password before submitting the form to the controller hi i have a simple html login formform methodpost actioninput typetext nametext box input typepassword namepass word input typesubmit namesubmitformwhen i submit the form and in the controller public function loginpass word thisinputpostpass worddiepass wordthe problem here it shows the plain password if i type 123456 in controller i get 123456is this a security issue can any one get my password through a network monitoring tool like wireshark how to avoid this can i encrypt the password in view before send to the controller please help thanks in advance,['php'] +338728,does thisplaynone prevent an image from loading every responsive website development tutorial recommends using the thisplaynone css property to hide content from loading on mobile browsers so the website loads faster is it true does thisplaynone not load the images or does it still load the content on mobile browser if so is there a way to not load the unnecessary content on mobile browsers,['css'] +338771,how to limit number of lines in jtextarea i am trying to make a gui for a service which have a jtextarea to view messages in each message is written on a single line and wordwrapped if neededthe messages arrive via a socket so it is merely an appendmessage that i am using to update the jtextarea i need to limit these lines to 50 or 100 and i have no need to limit character count on each lineif there is a method to limit the number lines in the jtextarea or if there is an alternative method of doing iti could really use the assistance in this mattereditthe problem is that each client can send infinite lines all these lines have to be readable so this is not a simple check of the number of lines in the jtextarea i need to remove older lines in order to view newer lines,['java'] +338786,java logging with abstract classes i am working on a project and am currently working on implementing some logging with log4j and i was curious about how i should go about implementing the logs the two implementations i am kicking around are as followsfirst option use single log from super class for that class and all sub classespublic abstract class abstractfoo protected static log log logfactorygetlogabstractfooclass public class foo extends abstractfoo public void somemethod loginfousing abstract log second option use individual logs for each class super and subspublic abstract class abstractfoo private static log log logfactorygetlogabstractfooclass public class foo extends abstractfoo private static log log logfactorygetlogfooclass public void somemethod loginfousing own log what makes more sense and why,['java'] +338811,setting request headers in ruby i have the rest client gem and i am defining a request like thisurl httpsomeurlrequest data datato jsonresponse restclientposturlrequestcontent type json accept jsonhowever i need to set the http header to something for example an api key which could be done in curl ascurl xhead h xauthuser myusername h xauthkey mykey urlwhats the best way to do this in ruby using this gem or can i do it manually to have more control,['ruby'] +338812,remove duplicates from tree i have the classclass node public string name public string address public int id public listnode children new listnode public node parentto represent a node in a tree now i will like to remove the duplicate nodes from a tree take for instance the treenote green foo purple foowhat algorithm will enable me to remove the duplicates from the tree in order to end up with in order to determine that the green foo is not equal to purple foo i guess i need to have another property that stores the height of the node or some other property that will enable me to enable me to compare nodes this is the property i think i need compareid class node public string name public string address public int id public listnode children new listnode public node parent public string compareid property i need to compare get var temp thisname thisaddress thisid if thisparent null return temp else return temp thisparentcompareid if you wish to create the same tree i have here is the codenode root new node name root id 12 address 0x0a1f12 node tom1 new node name tom id 15 address 0x0f1a17 parentroot rootchildrenaddtom1node tom2 new node name tom id 15 address 0x0f1a17 parent root rootchildrenaddtom2node foo new node name foo id 99 address 0x4c0012 parentroot rootchildrenaddfoonode foo1 new node name foo id 99 address 0x4c0012 parent tom1 tom1childrenaddfoo1node foo2 new node name foo id 99 address 0x4c0012 parent tom1 tom1childrenaddfoo2node foo3 new node name foo id 99 address 0x4c0012 parent tom2tom2childrenaddfoo3node foo4 new node name foo id 99 address 0x4c0012 parent tom2tom2childrenaddfoo4node joe1 new node name joe id 99 address 0x605c2c parent foo foochildrenaddjoe1node joe2 new node name joe id 99 address 0x605c2c parent foo foochildrenaddjoe2,['c#'] +338840,how can i render line faster than cgcontextstrokepath i am plotting 768 points for a graph using cgcontextstrokepath the problem is that every second i get a new data point and thus redraw the graph this is currently taking 50 cpu in whats already a busy app graph drawing is done in drawrect in a uiview the graph is time based so new data points always arrive on the right hand side i am thinking a few alternative approachesdraw with glkit at cost of not supporting older devices and seems like a lot of workdo some kind of screen grab renderincontext shift left by 1 px blit and only draw a line for the last two data pointshave a very wide calayer and pan along itsmooth the data set but this feels like cheating it is also possible i am missing something obvious here that i am seeing such poor performance cgcontextbeginpathcontextcgcontextsetlinewidthcontext 20uicolor color uicolor whitecolorcgcontextsetstrokecolorwithcolorcontext color cgcolora cgcontextaddlinescontext points index cgcontextmovetopointcontext startpointx startpointy cgcontextclosepathcontext cgcontextstrokepathcontext,['ios'] +338853,avaudiorecorder record aacm4a i am trying to record audio on the device using avaudiorecorder that file is transmitted to a web server and i want to play that resulting file in a web browser i have tried various combinations of settings on the devicenothing seems to encode the file into the correct aac formatquicktime says that it does not know how to play this filesample code private void initializerecordingsession string filename stringformat0m4a guidnewguid string tmpdir environmentgetfolderpathenvironmentspecialfolderpersonal audio if directoryexiststmpdir directorycreatedirectorytmpdir audiofilepath pathcombinetmpdir filename consolewritelineaudio file path audiofilepath var url nsurlfromfilenameaudiofilepath var settings new avaudiorecordersettings audioformat audioformattypempeg4aac samplerate 44100 numberchannels 1 audioquality avaudioqualityhigh recorder avaudiorecordertourlurl settings out error set recorder to prepare to record recorderpreparetorecord editby putting this code in before the line recorder avaudiorecordertourlurl settings out erroreverything workednserror error avaudiosession audiosession avaudiosessionsharedinstanceaudiosessionsetcategoryavaudiosessioncategoryrecord out erroraudiosessionsetactivetrue out error,['ios'] +338854,proguard obfuscation is breaking simplexml i am using simplexml in my android project and everything works fine until i obfuscate the code then errors start pouring inpart of the xml is as followscategories successtrue category id102 captionmagazin parent0 num mags114 category id15 captionkunst parent102 num mags13 category id17 captiondesign parent15 num mags10 category category id18 captionhautecouture parent15 num mags2 i have two classes categoryitemlistrootname categoriespublic class categoryitemlist private final listcategoryitem mcategoryitems create a new category items list param categoryitems the list of category items public categoryitemlistelementlistname category inline true final listcategoryitem categoryitems mcategoryitems categoryitems elementlistname category inline true public listcategoryitem getcategoryitems return mcategoryitems and categoryitemrootname categorypublic class categoryitem private final int mid private final string mcaption private final int mparent private final int mnumberofmagazines private final arraylistcategoryitem msubcategoryitems creating a new category item param id the category id param caption the name of category param parent the parent category param nummags the number of magazines from that category public categoryitemattributename id final int id attributename caption final string caption attributename parent final int parent attributename num mags final int nummags elementlistname category inline true required false final arraylistcategoryitem subcategoryitems mid id mcaption caption mparent parent mnumberofmagazines nummags msubcategoryitems subcategoryitems attributename id public int getid return mid attributename caption public string getcaption string categoryname null try categoryname urldecoderdecodemcaption utf8 catch final unsupportedencodingexception e eprintstacktrace return categoryname attributename parent public int getparentid return mparent attributename num mags public int getnumbersofmagazines return mnumberofmagazines elementlistname category inline true required false public arraylistcategoryitem getsubcategory return msubcategoryitems now when i obfuscate the code if i leave out keepattributes annotation i get a persistenceexception constructor not matched for class if i include it i get an unable to determine generic type for parameter 1 of constructor exception all these at runtimeas you can see the names are there and i tried to keep the entire class holding them all to no availhow can i configure proguard to work with simplexmledit my proguardcfg file is as follows it is a bit stuffed with all the things i have tried but this is the current versiondontusemixedcaseclassnamesdontskipnonpubliclibraryclassesdontpreverifyverboseprintseedsdontoptimizekeepattributes annotationkeepattributes enclosingmethodlibraryjars javahomelibrtjar javaxxmlstream keep public class extends androidappactivitykeep public class extends androidappapplicationkeep public class extends androidappservicekeep public class extends androidcontentbroadcastreceiverkeep public class extends androidcontentcontentproviderkeep public class extends androidappbackupbackupagenthelperkeep public class extends androidpreferencepreferencekeepclasseswithmembers class native methodskeepclasseswithmembers class public initandroidcontentcontext androidutilattributesetkeepclasseswithmembers class public initandroidcontentcontext androidutilattributeset intkeepclassmembers enum public static values public static valueofjavalangstringkeep class implements androidosparcelable public static final androidosparcelablecreator dontwarn androidsupportdegreenrobotorgsimpleframeworkxmlkeep class comcrittercism keepclassmembernames class comcrittercism keepclasseswithmembers class comcrittercism keep class orgsimpleframework keepclassmembernames class orgsimpleframework keepclasseswithmembers class orgsimpleframework keep class crittercismandroidkeepclassmembers public class comcrittercism keep public class database public static fieldskeep class androidsupportkeepclasseswithmembers class androidsupport keep class orgsimpleframeorkkeepclasseswithmembers class orgsimpleframeork keep class javaxkeepclasseswithmembers class javax keep class comtestcategorykeepclassmembernames class comtestcategory keepclasseswithmembers class comtestcategory keep class comtestdownloadkeepclassmembernames class comtestdownload keepclasseswithmembers class comtestdownload keep class orgsimpleframework keep class orgsimpleframeworkxml keep class orgsimpleframeworkxmlcore keep class orgsimpleframeworkxmlutil keep class orgsimpleframeworkxmlstream keepclassmembers class implements javaioserializable private static final javaioobjectstreamfield serialpersistentfields private void writeobjectjavaioobjectoutputstream private void readobjectjavaioobjectinputstream javalangobject writereplace javalangobject readresolve,['android'] +338859,ora03135 connection lost contact when inserting large file i am trying to do an insert with a potentially large amount of binary data into a remote oracle 11g database using entity framework odpnet it works fine for really small files 5 kb but for larger ones eg 44 kb i get an error ora03135 connection lost contacti do not think it is timing out as the exception occurs within a second of executing the commandi tried setting both of the following in my connection string but to no availvalidate connectiontruepoolingfalsei also looked in the listenerlog file on the remote machine it shows the connections being made but no sign of exceptions or terminated connectionsi am up for suggested fixes or troubleshooting methodseditthe same sql operations work when accessing an oracle instance on the local network,['c#'] +338891,python ftp implicit tls connection issue i have a need to connect to ftps server to which i am able to connect successfully using lftp however when i try with python ftplibftp tls it times out the stack trace shows that it is waiting for the server to send welcome message or like does anyone know what the issue is and how to overcome i wonder if there is something needs to be done on server side but how come lftp client is working fine any help is greatly appreciatedhere is the stack trace ftp ftplibftp tls ftpconnectcfghost cfgport timeout60 file cusersusernamesoftwarespython27libftplibpy line 135 in connect selfwelcome selfgetresp file cusersusernamesoftwarespython27libftplibpy line 210 in getresp resp selfgetmultiline file cusersusernamesoftwarespython27libftplibpy line 196 in getmultiline line selfgetline file cusersusernamesoftwarespython27libftplibpy line 183 in getline line selffilereadline file cusersusernamesoftwarespython27libsocketpy line 447 in readline data self sockrecvself rbufsize sockettimeout timed out a successful login using lftp to the same ftps server lftplftp open ftpsip address990lftp ip address set ftpsinitialprot plftp ip address login ftps user id ftps user passwdlftp sftp user idip address lsls fatal error ssl connect self signed certificatelftp ftps user idip address set sslverifcertificate offlftp ftps user idip address lslftp ftps user idip addressbtw i am using python 273 i did quite a bit of search using google but have not found anything helpfuli am still having this issue appreciate if someone can help on looking closely the ftpconnect the connection to server is not a problem but getting acknowledgement or the welcome message from server is an issue lftp does not have this issue and filezilla does not have any issue either as in the log here status connecting to x990 status connection established initializing tls status verifying certificate status tlsl connection established waiting for welcome message response 220 vous allez vous connecter sur un serveur prive response 220 seules les personnes habilitees y sont autorisees response 220 les contrevenants sexposent aux poursuites prevues par la loi command user x response 331 password required for x command pass response 230 login ok proceed command pbsz 0 response 200 pbsz command ok protection buffer size set to 0 command prot p response 200 prot command ok using private data connection status connected status retrieving directory listing command pwd response 257 is current folder command type i response 200 type set to i command pasv response 227 entering passive mode 8193201994206 command mlsd response 150 opening binary mode data connection for mlsd response 226 transfer complete 0 bytes transferred 0 bps status directory listing successful,['python'] +338907,can semaphoreacquire throw interruptedexception due to a spurious wakeup a seemingly straightforward problem i have a javautilconcurrentsemaphore and i want to acquire a permit using acquire the acquire method is specified to throw interruptedexception if the thread is interruptedif the current threadhas its interrupted status set on entry to this method oris interrupted while waiting for a permitthen interruptedexception is thrown and the current threads interrupted status is clearedhowever the usual pattern with methods that may throw interruptedexception is to call them in a loop since threads can be subject to spurious wakeups that look the same as being interrupted for example the documentation for objectwaitlong saysa thread can also wake up without being notified interrupted or timing out a socalled spurious wakeup while this will rarely occur in practice applications must guard against it by testing for the condition that should have caused the thread to be awakened and continuing to wait if the condition is not satisfied in other words waits should always occur in loopsso the question is is semaphoreacquire subject to the same kind of spurious wakeup the logical answer would be no but i cannot find any evidence for that and in fact the evidence seems to point in the other directionlooking at the source for semaphore it appears that it delegates the actual acquire to an abstractqueuedsynchronizer which according to its source delegates to locksupportparkthe documentation for locksupportpark explicitly mentions spurious wakeup but the implementation of abstractqueuedsynchronizerdoacquireinterruptably appears to just check threadinterrupted and then throw interruptedexceptionso unless i am missing something which is very possible it appears that semaphoreacquire can throw interruptedexception spuriouslyis that correct more importantly is there anything i can do about that i could use semaphoreacquireuninterruptably but i do not want an uninterruptable wait just one that does not get interrupted spuriously is there any alternative,['java'] +338910,order of unordered python sets question from a noob mei understand that sets in python are unordered but i am curious about the order they are thisplayed in as it seems to be consistent they seem to be outoforder in the same way every time set 1 set5 2 7 2 1 88 set 2 set5 2 7 2 1 88 set 1set88 1 2 5 7 set 2set88 1 2 5 7and another example set 3 setabracadabra set 4 setabracadabra set 3seta r b c d set 4seta r b c di am just curious why this would be any help,['python'] +338914,fuzzy thistinct values i have a database of real estate listings and need to return a list of neighborhoods right now i am using mysql thistinct which returns all of the thistinct values my probelm is that there is a lot of neighborhoods that have similar names example park view sub 1park viewpark view sub 2park view sub 3great lake sub 1great lake sub 2great lake great lake sub 3i am looking for an easy php or mysql solution that would recognize that park view and great lake already exists and only return park view and great lake my initial thought is to some how get the sort order by length so that the short values are at the top and then loop through using strstr this sound like a large task i am wondering if there is a function either in mysql or php that would easily do this,"['php', 'mysql']" +338928,how to thisable output buffering in nginx for php application we have code similar to thisphp ob implicit flushtrue ob end flush foreach arrayofstrings as string echo time expensive functionstring in apache this would send each echo to the browser as it was output in nginxfastcgi however this does not work due tot he way nginx works by defaultis it possible to make this work on nginxfastcgi and if so how,['php'] +338948,execute triggers stored procedures on sqlfiddle mysql do sqlfiddle provides execution of triggersstored proceduresi have been unable to execute even the simplest form of stored procedure on sqlfiddledelimiter drop procedure if exists myproc create procedure myprocbeginenddelimiter sqlfiddle does not allow executing thisabove sql in build schema but allows create table etcnote the same syntax is working for me on my localhost using wamp with mysql 5524can anyone guide please,['mysql'] +338965,in python using flask how can i write out an object for download i am using flask and running foreman i data that i have constructed in memory and i want the user to be able to download this data in a text file i do not want write out the data to a file on the local thisk and make that available for download i am new to python i thought i would create some file object in memory and then set response header maybe,['python'] +338972,pointers of several functions is there any guarantees that the functions which differs only by its names not parameters and return type also cannot share the same address in c and c i do not see anything about it in the standardinclude cassertvoid foo void bar int main assertfoo bar,"['c++', 'c']" +338999,setting folder permissions in windows using python i am using python to create a new personal folder when a users ad account is created the folder is being created but the permissions are not correct can python add the user to the newly created folder and change their permissions i am not sure where to begin coding this,['python'] +339015,how to represent arrays within emberdata models is it necessary to use dshasmany pointing to a dsmodel when a model contains an array even if the array elements are not really models no ids or endpoints of their own is there a better wayi am using dshasmany but my extended dsrestadapter is throwing me a 404 trying to access the model even though i am never calling find on it and hasmany is called with embedded true i am seeing this error for the first time apparently in connection with this model since it goes away without ituncaught error assertion failed emptying a view in the inbuffer state is not allowed and should not happen under normal circumstances most likely there is a bug in your application this may be due to excessive property change notifications emberlatestjs43what does this mean and what might be causing itheres the stack traceemberassert emberlatestjs43emberviewstatesinbufferempty emberlatestjs13644emberviewemberobjectextendinvokeforstate emberlatestjs12257embercollectionviewembercontainerviewextendarraywillchange emberlatestjs14477invokeaction emberlatestjs3193iterateset emberlatestjs3175sendevent emberlatestjs3323emberarrayembermixincreatearraycontentwillchange emberlatestjs6963emberarrayproxyemberobjectextendarrangedcontentarraywillchange emberlatestjs9281emberarrayproxyemberobjectextend arrangedcontentwillchange emberlatestjs9235invokeaction emberlatestjs3193iterateset emberlatestjs3175sendevent emberlatestjs3323notifyobservers emberlatestjs1872embernotifybeforeobservers emberlatestjs2016propertywillchange emberlatestjs2594iterdeps emberlatestjs2077dependentkeyswillchange emberlatestjs2092propertywillchange emberlatestjs2592set emberlatestjs1416dsmodelemberobjectextenddatadidchange emberdatalatestjs3145mapforeach emberlatestjs1273orderedsetforeach emberlatestjs1145mapforeach emberlatestjs1271dsmodelemberobjectextenddatadidchange emberdatalatestjs3128invokeaction emberlatestjs3193iterateset emberlatestjs3175sendevent emberlatestjs3323notifyobservers emberlatestjs1872embernotifyobservers emberlatestjs19propertydidchange emberlatestjs2632emberobservableembermixincreatepropertydidchange emberlatestjs7917emberobservableembermixincreatenotifypropertychange emberlatestjs7930didchangedata emberdatalatestjs2053emberstatemanageremberstateextendsendrecursively emberlatestjs15446emberstatemanageremberstateextendsend emberlatestjs15431dsmodelemberobjectextendsend emberdatalatestjs3058dsstoreemberobjectextendload emberdatalatestjs1737dsstoreemberobjectextendloadmany emberdatalatestjs1763embeddedfindrecord emberdatalatestjs3434hasassociation emberdatalatestjs3459computedpropertyprototypeget emberlatestjs2968get emberlatestjs1362getpath emberlatestjs1484get emberlatestjs1355getwithglobals emberlatestjs4041bindingconnect emberlatestjs4140connectbindings emberlatestjs4600finishpartial emberlatestjs4610class emberlatestjs8315embermixincreatecreate emberlatestjs8457emberviewemberobjectextendcreatechildview emberlatestjs13179emberviewstatesinbufferappendchild emberlatestjs13622emberviewemberobjectextendinvokeforstate emberlatestjs12239emberviewemberobjectextendappendchild emberlatestjs13058emberhandlebarsviewhelperemberobjectcreatehelper emberlatestjs18687anonymous function emberlatestjs18844anonymous function emberlatestjs19043anonymous function emberlatestjs19208anonymous functionanonymous function handlebars100beta6js1512emberviewemberobjectextendrender emberlatestjs123emberviewemberobjectextendrendertobuffer emberlatestjs12872emberviewstatesinbufferappendchild emberlatestjs13625emberviewemberobjectextendinvokeforstate emberlatestjs12239emberviewemberobjectextendappendchild emberlatestjs13058emberhandlebarsviewhelperemberobjectcreatehelper emberlatestjs18687anonymous function emberlatestjs18844program2anonymous function handlebars100beta6js1529emberviewemberobjectextendrender emberlatestjs123ember handlebarsboundviewember metamorphviewextendrender emberlatestjs18075emberwrapnewfunc emberlatestjs949emberviewemberobjectextendrendertobuffer emberlatestjs12872emberviewstatesinbufferappendchild emberlatestjs13625emberviewemberobjectextendinvokeforstate emberlatestjs12239emberviewemberobjectextendappendchild emberlatestjs13058bind emberlatestjs18129anonymous function emberlatestjs18199anonymous function emberlatestjs18271program1anonymous function handlebars100beta6js1529emberviewemberobjectextendrender emberlatestjs123emberviewemberobjectextendrendertobuffer emberlatestjs12872embercontainerviewemberviewextendrender emberlatestjs14078emberviewemberobjectextendforeachchildview emberlatestjs12486embercontainerviewemberviewextendrender emberlatestjs14077emberwrapnewfunc emberlatestjs949emberviewemberobjectextendrendertobuffer emberlatestjs12872emberviewstatesinbufferappendchild emberlatestjs13625emberviewemberobjectextendinvokeforstate emberlatestjs12239emberviewemberobjectextendappendchild emberlatestjs13058emberhandlebarsviewhelperemberobjectcreatehelper emberlatestjs18687anonymous function emberlatestjs18844anonymous function emberlatestjs19043anonymous function emberlatestjs19208anonymous functionanonymous function handlebars100beta6js1512emberviewemberobjectextendrender emberlatestjs123emberviewemberobjectextendrendertobuffer emberlatestjs12872embercontainerviewemberviewextendrender emberlatestjs14078emberviewemberobjectextendforeachchildview emberlatestjs12486embercontainerviewemberviewextendrender emberlatestjs14077emberwrapnewfunc emberlatestjs949emberviewemberobjectextendrendertobuffer emberlatestjs12872emberviewstatesinbufferappendchild emberlatestjs13625emberviewemberobjectextendinvokeforstate emberlatestjs12257emberviewemberobjectextendappendchild emberlatestjs13058emberhandlebarsviewhelperemberobjectcreatehelper emberlatestjs18687anonymous function emberlatestjs18844anonymous function emberlatestjs19624anonymous function emberlatestjs18167anonymous functionanonymous function handlebars100beta6js1512emberviewemberobjectextendrender emberlatestjs123emberviewemberobjectextendrendertobuffer emberlatestjs12872emberviewemberobjectextendcreateelement emberlatestjs12669emberviewstatesprerenderinsertelement emberlatestjs13558emberviewemberobjectextendinvokeforstate emberlatestjs12257invoke emberlatestjs3428iter emberlatestjs3475runloopflush emberlatestjs3531runloopend emberlatestjs3447emberrunend emberlatestjs3639autorun emberlatestjs3705thanks for any helpupdate this fiddle works with example from docs but how could those objects be represented if the tags are not real models ie do not have ids,['javascript'] +339030,how should i take the max of 2 columns in a dataframe and make it another column i have a dataframe with columns ab i need to create a column c such that for every record rowc maxa bhow should i go about doing thisthanks,['python'] +339065,c initialization of member variables i have a confusion on class member variable initializationsuppose in my h file isclass test int int var 1float float var 2public testmy cpp would betesttest int var 1100 float var 215f now when i instantiate a class the variables get initialized to 100 and 15but if that is all i am doing in my constructor i can do the following in my cppint testint var 1 100float testfloat var 2 15fi am confused as to the difference between initializing the variables in constructors or with the resolution operatordoes this way of initializing variables outside constructor with scope resolution only apply to static variables or is there a way it can be done for normal variables too,['c++'] +339075,adding a field specific error from the controller in symfony2 i have some complex validation going on with my symfony form and i need to be able to assign an error to a specific field from my controller right now i have global errors working like thiserror new formerrorthere is an error with the formformadderrorerrorbut that creates a global error not one bound to a specific fieldis there a way to throw an error on a specific field from my controller,['php'] +339080,get facebook profile pic using 30 sdk i am having trouble getting the users profile pic with the new facebook sdk all the answers on here use methods from the old sdk that no longer work i have tried using the fbprofilepictureview recommended in facebooks tutorial but this picture does not get cached and i do not think it can be converted into a uiimagecan anyone please provide some help thanks,"['iphone', 'ios']" +339102,save the state when back button is pressed i am developing an android app if i press a back button the state of my application should be saved what should i use to save the state am confused with all of these onpauseonresume or onrestoresavedinstance which of these should i use to save the state of my application for eg when i press exit button my entire app should exit i have used finish public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain s1buttonfindviewbyidridsn1 s1setonclicklistenerthis loadpreferences s1setenabledfalse public void savepreferences sharedpreferences sharedpreferences getpreferencesmode private sharedpreferenceseditor editor sharedpreferencesedit editorputbooleanstate s1isenabled public void loadpreferences systemoutprintlnloadprefe sharedpreferences sharedpreferences getpreferencesmode private boolean state sharedpreferencesgetbooleanstate false s1setenabledstate override public void onbackpressed systemoutprintlnbackbutton savepreferences superonbackpressed,['android'] +339106,how to send millions of apple push notification like urban airship within several seconds i need to send millions of apple push notification like urban airship within several secondsi used the followingi have several dedicated servers i can send thousands of push notification within several seconds but how can i send millions of apple push notification like urban airship within several seconds,"['php', 'iphone', 'ios']" +339124,place holder or watermark in textbox windows 8 i want to show a placeholder text in textbox when user has not typed anything and textbox is idlein andriod it can be done using androidhintsome textin iphone it can be done as textfildplaceholder some texthow can i do it in windows 8 metro appsthanks,['c#'] +339138,change browser address bar url with jquery ajax without reloading page change browser address bar url with jquery without reloadingfor example wmywebsitelistphppage1a hrefpagephp rowid this link aon click change address bar id123 etc,"['php', 'jquery']" +339160,css filter not working in firefox i am trying css filter but it does not work in my firefox 150 browser htmldiv classgoogle img srcdivcssgoogle mozfilter grayscale100 filter grayscale100demo,"['html', 'css']" +339175,refresh current page after set timeout function call is there a way to refresh page after settimeout function call is executedhere is the code of settimeout function callsettimeoutfunction alertsucceslideupslowfadeout 50,['jquery'] +339207,what is the operator before a variable in javascript i was looking into raphael js library but i see thisanimationprototypedelay function delay var a new animationthisanim thisms atimes thistimes adel delay 0 return awhat is the operator before the delay variablethanks,['javascript'] +339248,mercury editor in rails not saving changes i want to improve my pages with some visual editor and have find this railcast about mercury editor all dones but when i pressed save i had redirected to my page without any changes no errors no warnings just unsaved formatting can anybody helps mesome code routesmount mercuryengine resources tasks do resources comments member post mercury update end my controllerdef mercury update task taskfindparamsid tasktitle paramstitlevalue taskbody task paramsbody taskvalue tasksave render text end in viewslayoutsmercuryhtmlerbnew mercurypageeditorsaveurl savestyle form form or json default json savemethod null put or post create vs update default put visible true boolean if the interface should start visible or not when using post i have alert mercury was unable to save to the urlps rails 328 mercuryrails 080,['ruby-on-rails'] +339284,openid in a win8 metrostyle app authenticating with steam i have been thinking of making a windows 8 metro winrt style application that would allow the user to loginauthenticate with the steam webapi so i could use their stats etc that they provide however i am not sure how to approach this almost every answer to authenticating against an openid provider says to use dotnetopenauth but when installing this with nuget it fails saying that a dependency codecontractsunofficial 1002 does not have any assemblies compatible with my projects target net framework 45 so i am guessing that either has not been updated yet for windows 8 apps or would not be due to some winrt restrictioni have also looked in to using the net librarys webauthenticationbroker class but i am not sure how to use this with an openid provider the samples for it seem to only be for oauth and on the steam webapi page the only information provided is just download an openid library for your language and platform of choice and use as the provider the returned claimed id will contain the users 64bit steamidi tried simply using the given url by passing it straight to authenticateasyncwebauthenticationoptions uri but this just gives a white screen with a spinner on itdoes anyone have any advice for me on how to either get an openid library working with a metro application or how to use the webauthenticationbroker to auth via the openid protocol preferably against steam specifically,"['c#', '.net']" +339292,how to set css style to aspnet button i have a aspbutton i used css styles with cssclass property in aspbutton but those styles are not working when i use asplinkbutton those styles are working welli do not want any themes or skins for styles this is my asp pageaspbutton cssclasmallbutton textsign in runatserver idsubmitaspbuttonthis is my csmallbutton styleswhen i change aspbutton to asplinkbuttonasplinkbutton textsign in runatserver idsubmit cssclasmallbuttonasplinkbuttonor span clasmallbuttonasplinkbutton textsign in runatserver idsubmitasplinkbuttonspanstyles are working well only problem with the aspbutton control,"['asp.net', 'css']" +339338,address of the pointed element whatever the iterator typepointer is passed what would be the most generic syntax for the following function templateiteratortype void myfunctionconst iteratortype myiterator ptr myiterator0it take an iterator myiterator it can be a raw pointer and the goal is to assign the address of the object pointed by myiterator to a raw pointer ptr currently i use myiterator0 but i realized that only random access iterators have the operator so is there a syntax that will work with all type of standard iterators and pointers,['c++'] +339347,mysql 1062 duplicate entry 0 for key primary i have following table in mysql version 5524drop table if exists momento thistributioncreate table if not exists momento thistribution momento id int11 not null momento idmember int11 not null created at datetime default null updated at datetime default null unread tinyint1 default 1 accepted varchar10 not null default pending ext member varchar255 default null primary key momento id momento idmember key momento thistribution fi 2 momento idmember key accepted accepted ext member engineinnodbdefault charsetlatin1it have lot of data with manytoone relation with two other table with ondeleterestrict and onupdaterestrictnow i need to change the structure and introduce separate primary key in the table while keeping existing relation and data for that i executed following queryalter table momento thistribution add id int 11 not null firstalter table momento thistribution drop primary key add primary key id unfortunately second query failed with following error1062 duplicate entry 0 for key primarycan someone please point out the issue i guess issue is the existing relation but i do not want to loose existing relation or data which have several thousand rows is there any way to do this without loosing dataedit by kapilby viewing data i got that newly created column have value 0 in it probably this is not allowing to change the pk due to duplicate records in new pki have more that 80 rows so cant change it manually is there any way to assign rowid to new pk,"['mysql', 'sql']" +339363,exclude files from syntax checking in netbeans i am developping a website using netbeans and i wondered the followinghow do i thisable the error checking of a particular file i am using some css hacks and some css3 stuff that does not seem to be support by netbeans and it shows a couple hundred errors and warnings in the action items so i wanted to know if there was a way to remove these specific files from being debugged by netbeans so i could oversee the real errors and warnings,['css'] +339369,set logging levels in ruby on rails i am using following code to configure logging in my ruby on rails applicationenvironmentrbrailslogger loggernewstdoutclass logger def format messageseverity timestamp progname msg timestampto formatted sdb severity msgn endendi am trying to set the logging level to warn now usingconfiglog level warnin my productionrb but it doenst seem to work am i missing something hereif i put railsloggerlevel 4 in my environmentrb it does seem to work but i would like to configure things in my environment initializers,['ruby-on-rails'] +339371,defining methods via prototype vs using this in the constructor really a performance difference in javascript we have two ways of making a class and giving it public functions method 1function myclass var privateinstancevariable foo thismyfunc function alertprivateinstancevariable method 2function myclass myclassprototypemyfunc function alerti cannot use private instance variables i have read numerous times people saying that using method 2 is more efficient as all instances share the same copy of the function rather than each getting their own defining functions via the prototype has a huge thisadvantage though it makes it impossible to have private instance variables even though in theory using method 1 gives each instance of an object its own copy of the function and thus uses way more memory not to mention the time required for allocations is that what actually happens in practice it seems like an optimization web browsers could easily make is to recognize this extremely common pattern and actually have all instances of the object reference the same copy of functions defined via these constructor functions then it could only give an instance its own copy of the function if it is explicitly changed later onany insight or even better real world experience about performance differences between the two would be extremely helpful,['javascript'] +339381,storage of the hidden array behind initializer list in the c11 standard there is a note regarding the array backing the uniform initialisation that statesthe implementation is free to allocate the array in readonly memory if an explicit array with the same initializer could be so allocateddoes gclangvs take advantage of this or is every initialisation using this feature subject to additional data on the stack and additional initialisation time for this hidden arrayfor instance given the following examplevoid function stdvectorstdstring values first second would each of the compilers mentioned above store the backing array to the uniform initialisation in the same memory as a variable declared static const and would each of the compilers initialise the backing array when the function is called or on application initialisation i am not talking about the stdinitializer liststdstring that would be created but rather the hidden array it refers to,['c++'] +339400,free pascal for android on mips trying to port a delphi library to android free pascal has androidarm support a prebuilt compiler for windows is available however android ndk now supports mips and x86 as well whats the status of support for those in fpc for now my project is more or less cpu agnostic the native bits are built for all four supported architectures do not want to let go of thati am not after the full cycle of android development in pascal just an algorithm library that does no io i tried translating it into c with p2c but the translator chokes on the sourcesshould i just try and build crosscompiler for the relevant cpu with linux and then link against the ndk librariesedit i have built the crosscompiler for intellinux from the sources of the android branch it works except you have to invoke ppcross386 to compile not fpc the latter it seems ignores the tlinux option and invokes the intelwin32 compileredit2 with a small change to the makefile and sources the mips crosscompiler builds however as building moves on to the crosscpu rtl it errors out almost right away,['android'] +339404,return object from cursoradapterget i am overriding cursoradapter and i need to get the last item problem is that cursoradapter has actually a get methodbut source is a db and it returns a plain object i do not even know what is it i would expect it returning a cursor object insteadneverthless how can i make it return an instance of my wrapper db row classexamplesay my db has rows like theseidfirst name surnamei would make a class person from thatnow i would like to have a person getint i method from cursor adapter,['android'] +339407,twitter bootstrap print content of modal window i am developing a site using bootstrap which has 28 modal windows with information on different products i want to be able to print the information in an open modal window each window has an id firecell panel radio hub div classmodal hide fade idfcpanelhub div classmodalheader button typebutton classclose datathismissmodalxbutton h350 control panel radio hubh3 div div classmodalbody img srcsiteimgfirecellfirecellpanelinfo1png althr img srcsiteimgfirecellfirecellpanelinfo2png althr img srcsiteimgfirecellfirecellradiohubinfo1png althr img srcsiteimgfirecellfirecellradiohubinfo2png alt div div classmodalfooter a href classbtn datathismissmodalclosea div divso if i add in a new button in modalfooter print and it is clicked i want that modal to print would i be right in saying javascript would be used if so how do i tell javascript to print only the open modal and not the othersall help appreciated,['javascript'] +339423,regexp how can i match the shortest amount possible i have my regular expression ssand my test code he said youre cool rawrmy test code simulates parameters being passed into a function i will explain my regular expression as i understand it and hopefully a few of you can shed some light on my problem 1 means at the beginning of the matched string there needs to be 2 means capture any character except n 0 or more times 345 means do not capture but try to do step 4 and if it does not work try step 5 4ss means do not capture but there needs to be a with 0 or more whitespace characters followed by a with 0 or more whitespace characters 5 means do not capture but there needs to be so it seems that it should return this and this is what i want he said youre cool but it returns he said youre cool rawr if i change my test code to he said youre cool rawr no end parenthesis it returns what i want but as soon as i add that last parenthesis then it seems that my or operator does whatever it wants to i want it to test first if there is a comma and break there if there is one and if there is not one check for a parenthesis i have tried switching the spots of step 4 and step 5 but still the or operator seems to always default to the side how can i match the shortest amount possible,['javascript'] +339465,can i specify db column names for dapperdotnet mappings is there a way with dapperdotnet to use an attribute to specify column names that should be used and not the property namepublic class code public int id get set public string type get set this is called code in the table public string value get set public string description get set i would like to be able to name my properties whatever i choose our database has no consistent naming conventionif not with dapper are there any additional similar options,['c#'] +339490,2d balls not colliding properly i am just trying to code a nice looking physics gamethe ball collision looks nice but if the balls are colliding too slow they stick in each other i have no clue why they doheres my collision functionprivate void checkforcollisionarraylistball balls for int i 0 i ballssize i ball ball ballsgeti if ball this ballintersectsthis thiscollideball false public boolean intersectsball b double dx mathabsbposx posx double dy mathabsbposy posy double d mathsqrtdx dx dy dy return d radius bradiusprivate void collideball ball boolean b double m1 thisradius double m2 ballradius double v1 thismotionx double v2 ballmotionx double vx m1 m2 v1 m1 m2 2 m2 v2 m1 m2 v1 thismotiony v2 ballmotiony double vy m1 m2 v1 m1 m2 2 m2 v2 m1 m2 if b ballcollidethis true systemoutprintlnvx vy motionx vx bounceobject motiony vy bounceobjectbut this is what happens when they collide with a low speedso do you have an ideaeditthe update of alnitak works very nice but one problem is still there if i add gravity like thispublic void physic motiony gravity this part gravity is set to 03d checkforcollisionscreenballs keymove bouncewalls posx motionx posy motionythey still move into each other i think this is the wrong way to add gravity or is not itand i think i did something wrong with the collision formula because they do not fall rightand then they slowly sink into the groundeditfound an amazing tutorial gameintrobouncingballshtml,['java'] +339541,using jquery to hide div scrollbar but retain scrolling i am trying to be able to scroll inside one div but without showing the actual scrollbari need the user to be able to scroll using the scrollwheeldoes anyone have ideas as to how i can accomplish thisthanks,"['jquery', 'css']" +339623,set default selected item of listview alert dialog in android i have created a dialog with a custom listview that models a spinner thisplay and originally it starts out with the value select genderwhen the dialog opens it prompts for a selection just like a spinner if the selection gets selected again it shows the same options but does not indicate which option has already been selectedexampledefault value select genderdialog opens with no selectionuser selects maleuser reopens dialogdialog opens with no selectioni would like it to have male selected since that was their last selectionheres my code so fargenderitems getresourcesgetstringarrayrarraygender arraygenderadapter new arrayadapterstringthis androidrlayoutsimple spinner dropdown item genderitemsgenderdropsetontouchlistenernew viewontouchlistener public boolean ontouchview v motionevent event ifeventgetaction motioneventaction down builder genderbuilder new alertdialogbuilderregisterthis settitlerstringgender prompt setadaptergenderadapter new dialoginterfaceonclicklistener public void onclickdialoginterface dialog int which inputgendersettextgenderitemswhich dialogthismiss alertdialog genderalert genderbuildercreate genderalertshow genderalertgetlistviewsetselection0 return false genderalertgetlistviewsetselection0 does not set the default selected as malegenderalertgetlistviewsetselection1 does not set the default selected as female,['android'] +339642,why structs cannot be assigned directly suppose i have a fully defined struct with tag mystruct and suppose that x y z are allowed values for its fields why isstruct mystruct q xyzallowed butstruct mystruct qq xyzis not allowed i find this very annoying in the second case where i have previously declared q i need to assign a value to each field one by oneqx x qy y qz zwhere x y z are the fields of mystruct is there a reason behind this,['c'] +339657,rename mysql database i created a database with the name of hrms now i need to change database name to sunhrm but it is thisabled in mysql workbench can i do that on the linux server itself,['mysql'] +339705,thread count growth when using task parallel library i am using c tpl and i am having a problem with a producerconsumer code for some reason tpl does not reuse threads and keeps creating new ones without stoppingi made a simple example to demonstrate this behaviorclass program static blockingcollectionint m buffer new blockingcollectionint1 static cancellationtokensource m cts new cancellationtokensource static void producer try while m ctsiscancellationrequested consolewritelineenqueuing job m bufferadd0 threadsleep10 finally m buffercompleteadding static void consumer parallelforeachm buffergetconsumingenumerable run static void runint i consolewriteline job processedtthread 0tprocess thread count 1 threadcurrentthreadmanagedthreadid processgetcurrentprocessthreadscount static void mainstring args task producer new taskproducer task consumer new taskconsumer producerstart consumerstart consolereadkey m ctscancel taskwaitallproducer consumer this code creates 2 tasks producer and consumer produces adds 1 work item every second and consumer only prints out a string with information i would assume that 1 consumer thread is enough in this situation because tasks are processed much faster than they are being added to the queue but what actually happens is that every second number of threads in the process grows by 1 as if tpl is creating new thread for every itemafter trying to understand whats happening i also noticed another thing even though blockingcollection size is 1 after a while consumer starts getting called in bursts for example this is how it startsenqueuing jobjob processed thread 4 process thread count 9enqueuing jobjob processed thread 6 process thread count 9enqueuing jobjob processed thread 5 process thread count 10enqueuing jobjob processed thread 4 process thread count 10enqueuing jobjob processed thread 6 process thread count 11and this is how it is processing items less than a minute laterenqueuing jobjob processed thread 25 process thread count 52enqueuing jobenqueuing jobjob processed thread 5 process thread count 54job processed thread 5 process thread count 54and because threads get thisposed after finishing parallelforeach loop i do not show it in this example but it was in the real project i assumed that it has something to do with foreach specifically i found this artice and i thought that my problem was caused by this default partitioner so i took custom partitioner from tpl examples that is feeding consumer threads item one by one and although it fixed the order of execution got rid of delayenqueuing jobjob processed thread 71 process thread count 140enqueuing jobjob processed thread 12 process thread count 141enqueuing jobjob processed thread 72 process thread count 142enqueuing jobjob processed thread 38 process thread count 143enqueuing jobjob processed thread 73 process thread count 143enqueuing jobjob processed thread 21 process thread count 144enqueuing jobjob processed thread 74 process thread count 145it did not stop threads from growingi know about paralleloptionsmaxdegreeofparallelism but i still want to understand whats happening with tpl and why it creates hundreds of threads for no reasonin my project i a code that has to run for hours and read new data from database put it into a blockingcollections and have has data processed by other code there is 1 new item about every 5 seconds and it takes from several milliseconds to almost a minute to process it and after running for about 10 minutes thread count reached over a 10 threads,['c#'] +339715,tomcat7 could not load jdbc driver class commysqljdbcdriver i have seen several similar questions on stackoverflow but they did not solved my problem this one is specially useful since it points to official tomcat documentation and specially this sectionthe solutions provided there is in short tomcat needs jdbc database drivers to be copied to catalina homelib because it will not find them under webinflib ok but it still does not work for me and i am becoming madlet us see if you can provide any further ideathe environment is windows xp tomcat7 eclipse indigo java6 and spring3mysqlconnector has been copied to catalina homelibcdir cprogram filesapachetomcat7012libmysql2012 1339 877094 mysqlconnectorjava5121jarcyou probably know that eclipses tomcat integration creates a wtpspecific directory for its deployments catalina base so i copied mysqlconnector also there i have unsuccessfully tried with the mysqlconectorjar in catalina home in catalina base and in both of themcdir csharegenesiswseclipseindigometadatapluginsorgeclipsewstservercoretmp0lib29082012 1339 877094 mysqlconnectorjava5121jarcas far as i understand tomcats catalinaproperties file they are both added to the classpath so i did not expect any difference but i tried just in casemy spring datasource definition is very simple bean idsecuritydatasource classorgspringframeworkjdbcdatasourcedrivermanagerdatasource property namedriverclassname valuecommysqljdbcdriver property nameurl valuejdbcmysqllocalhost3306venus property nameusername valueroot property namepassword value beanbut when i restart tomcat i get the following errorerror orgspringframeworkwebcontextcontextloader context initialization failedorgspringframeworkbeansfactorybeancreationexception error creating bean with name securitydatasource defined in servletcontext resource webinfspringrootcontextxml error setting property values nested exception is orgspringframeworkbeanspropertybatchupdateexception nested propertyaccessexceptions 1 arepropertyaccessexception 1 orgspringframeworkbeansmethodinvocationexception property driverclassname threw exception nested exception is javalangillegalstateexception could not load jdbc driver class commysqljdbcdriver at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactoryapplypropertyvaluesabstractautowirecapablebeanfactoryjava1396 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorypopulatebeanabstractautowirecapablebeanfactoryjava18 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorydocreatebeanabstractautowirecapablebeanfactoryjava517 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorycreatebeanabstractautowirecapablebeanfactoryjava456 at orgspringframeworkbeansfactorysupportabstractbeanfactory1getobjectabstractbeanfactoryjava294 at orgspringframeworkbeansfactorysupportdefaultsingletonbeanregistrygetsingletondefaultsingletonbeanregistryjava225 at orgspringframeworkbeansfactorysupportabstractbeanfactorydogetbeanabstractbeanfactoryjava291 at orgspringframeworkbeansfactorysupportabstractbeanfactorygetbeanabstractbeanfactoryjava193 at orgspringframeworkbeansfactorysupportdefaultlistablebeanfactorypreinstantiatesingletonsdefaultlistablebeanfactoryjava585 at orgspringframeworkcontextsupportabstractapplicationcontextfinishbeanfactoryinitializationabstractapplicationcontextjava913 at orgspringframeworkcontextsupportabstractapplicationcontextrefreshabstractapplicationcontextjava464 at orgspringframeworkwebcontextcontextloaderconfigureandrefreshwebapplicationcontextcontextloaderjava384 at orgspringframeworkwebcontextcontextloaderinitwebapplicationcontextcontextloaderjava283 at orgspringframeworkwebcontextcontextloaderlistenercontextinitializedcontextloaderlistenerjava1 at orgapachecatalinacorestandardcontextlistenerstartstandardcontextjava4701 at orgapachecatalinacorestandardcontext1callstandardcontextjava5204 at orgapachecatalinacorestandardcontext1callstandardcontextjava5199 at javautilconcurrentfuturetasksyncinnerrununknown source at javautilconcurrentfuturetaskrununknown source at javautilconcurrentthreadpoolexecutorworkerruntaskunknown source at javautilconcurrentthreadpoolexecutorworkerrununknown source at javalangthreadrununknown sourcecaused by orgspringframeworkbeanspropertybatchupdateexception nested propertyaccessexceptions 1 arepropertyaccessexception 1 orgspringframeworkbeansmethodinvocationexception property driverclassname threw exception nested exception is javalangillegalstateexception could not load jdbc driver class commysqljdbcdriver at orgspringframeworkbeansabstractpropertyaccessorsetpropertyvaluesabstractpropertyaccessorjava102 at orgspringframeworkbeansabstractpropertyaccessorsetpropertyvaluesabstractpropertyaccessorjava58 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactoryapplypropertyvaluesabstractautowirecapablebeanfactoryjava1393 21 more30ago2012 83811 orgapachecatalinacorestandardcontext listenerstartgrave excepcia3n enviando evento inicializado de contexto a instancia de escuchador de clase orgspringframeworkwebcontextcontextloaderlistenerorgspringframeworkbeansfactorybeancreationexception error creating bean with name securitydatasource defined in servletcontext resource webinfspringrootcontextxml error setting property values nested exception is orgspringframeworkbeanspropertybatchupdateexception nested propertyaccessexceptions 1 arepropertyaccessexception 1 orgspringframeworkbeansmethodinvocationexception property driverclassname threw exception nested exception is javalangillegalstateexception could not load jdbc driver class commysqljdbcdriver at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactoryapplypropertyvaluesabstractautowirecapablebeanfactoryjava1396 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorypopulatebeanabstractautowirecapablebeanfactoryjava18 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorydocreatebeanabstractautowirecapablebeanfactoryjava517 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorycreatebeanabstractautowirecapablebeanfactoryjava456 at orgspringframeworkbeansfactorysupportabstractbeanfactory1getobjectabstractbeanfactoryjava294 at orgspringframeworkbeansfactorysupportdefaultsingletonbeanregistrygetsingletondefaultsingletonbeanregistryjava225 at orgspringframeworkbeansfactorysupportabstractbeanfactorydogetbeanabstractbeanfactoryjava291 at orgspringframeworkbeansfactorysupportabstractbeanfactorygetbeanabstractbeanfactoryjava193 at orgspringframeworkbeansfactorysupportdefaultlistablebeanfactorypreinstantiatesingletonsdefaultlistablebeanfactoryjava585 at orgspringframeworkcontextsupportabstractapplicationcontextfinishbeanfactoryinitializationabstractapplicationcontextjava913 at orgspringframeworkcontextsupportabstractapplicationcontextrefreshabstractapplicationcontextjava464 at orgspringframeworkwebcontextcontextloaderconfigureandrefreshwebapplicationcontextcontextloaderjava384 at orgspringframeworkwebcontextcontextloaderinitwebapplicationcontextcontextloaderjava283 at orgspringframeworkwebcontextcontextloaderlistenercontextinitializedcontextloaderlistenerjava1 at orgapachecatalinacorestandardcontextlistenerstartstandardcontextjava4701 at orgapachecatalinacorestandardcontext1callstandardcontextjava5204 at orgapachecatalinacorestandardcontext1callstandardcontextjava5199 at javautilconcurrentfuturetasksyncinnerrununknown source at javautilconcurrentfuturetaskrununknown source at javautilconcurrentthreadpoolexecutorworkerruntaskunknown source at javautilconcurrentthreadpoolexecutorworkerrununknown source at javalangthreadrununknown sourcecaused by orgspringframeworkbeanspropertybatchupdateexception nested propertyaccessexceptions 1 arepropertyaccessexception 1 orgspringframeworkbeansmethodinvocationexception property driverclassname threw exception nested exception is javalangillegalstateexception could not load jdbc driver class commysqljdbcdriver at orgspringframeworkbeansabstractpropertyaccessorsetpropertyvaluesabstractpropertyaccessorjava102 at orgspringframeworkbeansabstractpropertyaccessorsetpropertyvaluesabstractpropertyaccessorjava58 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactoryapplypropertyvaluesabstractautowirecapablebeanfactoryjava1393 21 moreone more hint using sysinternals process explorer i can see that the mysqlconnectorjavajar is being open by tomcatcprogram filesjavajre6binjavawexe dcatalinabasecsharegenesiswseclipseindigometadatapluginsorgeclipsewstservercoretmp0 dcatalinahomecprogram filesapachetomcat7012 dwtpdeploycsharegenesiswseclipseindigometadatapluginsorgeclipsewstservercoretmp0wtpwebapps djavaendorseddirscprogram filesapachetomcat7012endorsed dfileencodingcp1252 classpath cprogram filesapachetomcat7012binbootstrapjarcprogram filesapachetomcat7012bintomcatjulijar orgapachecatalinastartupbootstrap startany further ideaedit1 i have tried to use oracle and it workscdir cprogram filesapachetomcat7012liboci02102006 2236 1545954 ocijdbc10jarcthe datasource bean idsecuritydatasource classorgspringframeworkjdbcdatasourcedrivermanagerdatasource property namedriverclassname valueoraclejdbcdriveroracledriver property nameurl valuejdbcoracleocibarvdb002d1545tfsdb0 property nameusername valueme property namepassword valueqwerty beanwhat am i doing wrong for mysql,['mysql'] +339720,what are the differences between helper and utility classes how determine how call a class xhelper or xutils to my mind helper class is a class that can be instantiate and do some business workutils class is a static class that perform small and repetitive operations on a kind of instance example of utils classes arrayutils or ioutils from apache,['java'] +339735,how to do a noncached 301 redirect a while ago all browsers changed their behaviour and started caching 301 redirects i would like to know how to do a 301 redirect that is not cached in php,['php'] +339757,whats the purpose of using braces ie for a singleline if or loop i am reading some lecture notes of my c lecturer and he wrote the following use indentation oknever rely on operator precedence always use parentheses ok always use a block even for a single line not ok why const object on left side of comparison ok use unsigned for variables that are 0 nice trick set pointer to null after deletion double delete protection not badthe 3rd technique is not clear to me what would i gain by placing one line in a for example take this weird codeint j 0for int i 0 i 100 i if i 2 0 j and replace it with int j 0for int i 0 i 100 i if i 2 0 jwhats the benefit of using the 1st version,"['c++', 'c']" +339843,asp net web api rc multipart fileupload to memorystream i am trying to save an uploaded files to a databasememorystream but i cannot figure it outall i have right now is thispublic taskhttpresponsemessage answerquestion if requestcontentismimemultipartcontent throw new httpresponseexceptionhttpstatuscodeunsupportedmediatype var root httpcontextcurrentservermappathapp data var provider new multipartformdatastreamproviderroot var task requestcontentreadasmultipartasyncprovider continuewithhttpresponsemessaget if tisfaulted tiscanceled requestcreateerrorresponsehttpstatuscodeinternalservererror texception foreach var file in providerfiledata tracewritelinefileheaderscontentthispositionfilename tracewritelineserver file path filelocalfilename return requestcreateresponsehttpstatuscodeok return taskbut of course this only saves the file to a specific location i think i have to work with a custom class derived from mediatypeformatter to save it to a memorystream but i do not see how to do itplease help thanks in advance,['c#'] +339853,how to add variable at the start of the url in zend framework i am trying here to create url likeadminloginmoderatorloginboth the request would be served by same controller action made for login ie accountlogintypecurrently all i am able to make the following urlloginadminloginmoderatormy current config file looks like the followingresourcesrouterroutesloginroute logintyperesourcesrouterrouteslogindefaultscontroller accountresourcesrouterrouteslogindefaultsaction logini cannot figure out on how to put the type variable at the start of url i tried it but it gives server errorediti got this done but cannot understand why this did not work earlierresourcesrouterroutesloginroute typeloginresourcesrouterrouteslogindefaultscontroller accountresourcesrouterrouteslogindefaultsaction logineditis it possible to make this arrangement more flexible so thatlogin adminlogini am not looking for solution via htaccess,['php'] +339946,how to implement boost typeof here i would like to understand the general idea of implementing boost typeof i mean the code may be ok but i guess the code will not be simple as it is in real boost implementation therefore i would like to understand the idea of boost typeof implementation does it use compiler functions some api to understand the type of an expression in compile time,['c++'] +339957,legality of cow stdstring implementation in c11 it had been my understanding that copyonwrite is not a viable way to implement a conforming stdstring in c11 but when it came up in thiscussion recently i found myself unable to directly support that statementam i correct that c11 does not admit cow based implementations of stdstringif so is this restriction explicitly stated somewhere in the new standard whereor is this restriction implied in the sense that it is the combined effect of the new requirements on stdstring that precludes a cow based implementation of stdstring in this case i would be interested in a chapter and verse style derivation of c11 effectively prohibits cow based stdstring implementations,['c++'] +339973,numpy function for simultaneous max and min numpyamax will find the max value in an array and numpyamin does the same for the min value if i want to find both max and min i have to call both functions which requires passing over the very big array twice which seems slowis there a function in the numpy api that finds both max and min with only a single pass through the data,['python'] +339986,remove from observablearray knockoutjs i am sure this will be an easy answer for somebody i have the following viewmodel var initialdata new javascriptserializerserializemodelvar data htmlrawinitialdatafunction viewmodeldata var self this selfname koobservabledataname selfitems koobservablearraydataitems selfadditem function selfitemspush selfremoveitem functiondata selfitemsremovedata documentreadyfunction koapplybindingsnew viewmodeldata and the following viewdiv name span databindtext namespandivdiv items button databindclick additemadd itembuttondivdiv table tbody databindtemplate name itemtemplate foreach items tbody tabledivscript typetexthtml iditemtemplate tr td input databindvalue data a href databindclick function parentremoveitemdataremove itema td trscripteverything seems to work correctly except for removeitem when new rows have been added and remove item is clicked on an empty new row all of the new rows will be removed with it i have looked at tons of knockout tutorials trying to get this to work and my method seems to be a valid attempt but obviously i must be missing something any suggestions,['javascript'] +339989,reading data from matlab files into c i am trying to learn how to use the c api to reading matlab mat files but it is not working as i expectedi would like to just open a very simple mat file called testmat read a value from the file and store it in a c variable i have created testmat in matlab using the following commands value 3 save testmat valuebelow is my c code which does not even compile the compiler does not seem to find the header files see below the code for compiler output what am i doing wrong herecodeinclude stdlibhinclude stdiohinclude mathinclude matrixhint mainint argc char argv double value matfile datafile datafile matopentestmat r mxarray mxvalue mxvalue matgetvariabledatafile value matclosedatafile value mxgetprmxarray mxfreemxarray printfthe value fetched from the mat file was f value return 0compiler output make animate shotcc iusrlocalmatlabr2011aexterninclude animate shotc o animate shottmpcczrh1vto in function mainanimate shotctext0x1a undefined reference to matopenanimate shotctext0x2f undefined reference to matgetvariableanimate shotctext0x3f undefined reference to matcloseanimate shotctext0x4b undefined reference to mxgetpranimate shotctext0x5e undefined reference to mxfreecollect2 ld returned 1 exit statusmake animate shot error 1the i flag is specified with the line cppflagsiusrlocalmatlabr2011aexterninclude in my makefile and i have verified that the directory exists and contains the header files math and matrixhupdatei have found that the libraries i need to link in are libmatso and libmxso according to this mathworks help article residing in usrlocalmatlabr2011abinglnxa64 on my system i have therefore updated my makefile to thiscppflags iusrlocalmatlabr2011aexternincludeldflags lusrlocalmatlabr2011abinglnxa64 l mat l mxnow running make gives the following commandcc iusrlocalmatlabr2011aexterninclude lusrlocalmatlabr2011abinglnxa64 l mat l mx animate shotc o animate shothowever i still get the same errors any ideas,['c'] +340014,playback and recording simultaneously using core audio in ios i need to play and record simultaneously using core audio i really do not want to use avfoundation api avaudioplayer avaudiorecorder to do this as i am making a music app and cannot have any latency issuesi have looked at the following source code from appleauriotouchmixerhosti have already looked into the following postsios sample code for simultaneous record and playbackrecord and play audio simultaneouslyi am still not clear on how i can do playback and record the same thing simultaneously using core audio any pointers towards how i can achieve this will be greatly appreciable any pointers to any sample source code will also be of great help,"['iphone', 'ios']" +340016,portable class library and net concurrentdictionary looking at vvs110aspx it seems that concurrentdictionary and all of its friends in the systemcollectionsconcurrent namespace are available for use in a portable class libraryhowever when i create either an f or c portable class library even if i explicitly add a reference to mscorlibdll the compilation fails when using concurrentdictionarywhy,['.net'] +340020,how can i automatically test the functionality of ios and android applications i have to regularly test the availability and functioning of a movie rental website i wrote a windows program which is able to automate a web browser according to a script so this task is basically solved now i have to automate the mobile version of this web application a native ios app and a native android app these apps are closed source so cannot be modified in any way i think the test app should be deployed on the test devices iphone ipad galaxy tab galaxy s ii but i must be able to remote control it i mean i would like create a connection between the test devices and a pc upload test scripts from the pc to the devices run them and download the test results to the pc the test script should start the app to be tested manipulate its gui fill editboxes push buttons etc and follow its response somehow for example by analyzing the gui the existence of some gui elements their caption etc analyzing screenshots andor inspecting ip packetsi wrote lots of similar test programs for windows i used shellexecute postmessage findwindow the winpcap library etc so i know how such a program should work but since i never wrote applications for mobile oss i do not even know whether there are similar apis and libraries for ios and android i would like to know where to start i mean which sdks and developer tools could be used to write such an application i am also interested in commercial solutions i would really appreciate any help,"['android', 'ios']" +340052,how to assign application to all desktops spaces of mac os x lion using objective c i am trying to create an application on mac os x lion which requires application to be assigned to all desktops spaces this can be manually done by right clicking on applications dock icon and selecting options assign to all desktops but i need to find a way to do this via objective c is there a way to achieve this programmatically,['objective-c'] +340073,startup ejb bean does not work i am trying to do something at startup using a startup ejb but my bean is never calledthis is my beanimport javaxannotationpostconstructimport javaxejbstartupimport javaxinjectsingletonsingletonstartuppublic class startupbean postconstruct public void dosomething systemoutprintlnwhy i am using jboss 711what am i doing wrong you can find my source code at bitbucket,['java'] +340094,cmake and order dependent linking of shared libraries i have a few small components that i am building as shared libraries for my main application lets use an example of liba and libb each is built within their own subdirectory as followsadd libraryliba shared acppthen in the root project folder i need to link my main application to bothinclude directoriesainclude directoriesbadd executabledummy dummycpptarget link librariesdummy a bcmake runs fine with this and my application compiles but fails to link the problem is that b references a if i supply the order of the libraries while linking astarget link librariesdummy b athe program compiles and links just finewhen this sort of system starts involving more complex inter dependency of the libraries it starts to be impossible even if the dependencies are acyclic how do i manage the linking step here is there a trick to ordering libraries for linking in cmake,['c++'] +340108,ios 5 notification center api i am talking about this 720120625233ios5notificationsadeeperlookthose pulldown menus on ios i for the love of life cannot find any documentation on how to make a notification so that it shows an update while in another application i do not know if i just am using the wrong terminology or what but is it nsnotificationcenter and where is any documentation on itthanks,"['iphone', 'objective-c', 'ios']" +340117,using syncadapter without creating an account my app allows people to use and manage their data regardless they are logged in though as i uniquely identify each device i want to sync data from my anonymous users not logged ones as well so i was wondering if it is a good practice to create an anonymous account in this case since syncadapters only work with accountsshould i create an account for my anonymous users or should i sync their data with threadsasynctasksloaders in particular is there any way to make contentresolverrequestsync work without the need of an account,['android'] +340121,aggregate with mongoid mongodb has a new aggregation framework and i am trying to figure out how to use it with mongoid it appears there is a branch of moped with this functionality as thiscussed here i have updated to mongodb 22 and tried installing this branch of moped on my app like thisgem moped git gitgithubcommongoidmopedgit branch aggregationsupportbut aggregation is still not working this is the call i am using to test it postallaggregate group id id updatein the mongo shell this worksdbusersaggregate group id id so i am thinking it is a mongoid issueany word on this would be great,['ruby-on-rails'] +340139,gsoapvalgrind no leaks but memory errors i am writting a web service client with gsoap and using valgrind to check for memory issuesvalgrind reports no leaks but shows this strange at least for me memory error messages3529 conditional jump or move depends on uninitialised values3529 at 0x405d6dc soap reference stdsoap2c69263529 by 0x405305d soap serialize string sepomexcc49823529 by 0x404af5e soap serialize ns1 asentamientosporcodigopostalrqtype sepomexcc26293529 by 0x40500f3 soap serialize pointertons1 asentamientosporcodigopostalrqtype sepomexcc41033529 by 0x4046 soap serialize sep consultarasentamientosporcodigopostal sepomexcc123529 by 0x4053a7d soap call sep consultarasentamientosporcodigopostal sepomexclientc1863529 by 0x40417ca consultarasentamientosporcodigopostal mainc733529 by 0x804870c main sepomexmainc313529 3529 conditional jump or move depends on uninitialised values3529 at 0x4061aa5 soap element id stdsoap2c95833529 by 0x4068b0c soap outstring stdsoap2c126813529 by 0x4052dae soap out xsd integer sepomexcc49183529 by 0x404b062 soap out ns1 asentamientosporcodigopostalrqtype sepomexcc26433529 by 0x4050179 soap out pointertons1 asentamientosporcodigopostalrqtype sepomexcc413529 by 0x4046698 soap out sep consultarasentamientosporcodigopostal sepomexcc12383529 by 0x4046818 soap put sep consultarasentamientosporcodigopostal sepomexcc12743529 by 0x4053af6 soap call sep consultarasentamientosporcodigopostal sepomexclientc1933529 by 0x40417ca consultarasentamientosporcodigopostal mainc733529 by 0x804870c main sepomexmainc313529 3529 heap summary3529 in use at exit 0 bytes in 0 blocks3529 total heap usage 160 allocs 160 frees 16161 bytes allocated3529 3529 all heap blocks were freed no leaks are possible3529 3529 for counts of detected and suppressed errors rerun with v3529 use trackoriginsyes to see where uninitialised values come from3529 error summary 3 errors from 2 contexts suppressed 21 from 8the no leaks are good news but are this errors important as i understand they are generated in stdsoap2c a gsoap filethanksedit thanks for your answers as some of you told me i had uninitialized stuff it was my request struct variable i fixed it this waystruct ns1 myrequesttype requestmemsetrequest 0 sizeofstruct ns1 myrequesttypenow valgrinds output is clean thanks a lot,['c'] +340140,window vs page vs usercontrol for wpf navigation i wondered if someone could help me i am new to wpf and am currently writing a desktop application but i cannot seem to get my head around what to use when redirecting someone to a new section of the applicationmy options appear to bewindowpageusercontrolbut i do not understand what the difference between them is and when i should use each onecould someone explain the differences for me and give an example of what situationsapplications you may use each one for,['c#'] +340154,how to speed up insertion performance in postgresql i am testing postgres insertion performance i have a table with one column with number as its data type there is an index on it as well i filled the database up using this queryinsert into anumber id values 5644353634560 i inserted 4 million rows very quickly 10 at a time with the query above after the database reached 6 million rows performance drastically declined to 1 million rows every 15 min is there any trick to increase insertion performance i need optimal insertion performance on this projectusing windows 7 pro on a machine with 5 gb ram,['sql'] +340159,how to retrieve value from elements in array using jquery i have multiple input fields like soinput typetext namecardinput typetext namecardinput typetext namecardusers can add or remove these fields as required therefore the name of the fields is an array to get length of the array this works finevar and inputname cardlengthhow can i read value from the arrayi have tried this which did not workvar and inputnamecardlengthvar array inputnamecardfori0ini card value arrayival alertcard valuethis did not work eithervar and inputnamecardlengthfori0ini card value inputnamecardival alertcard valuehow can i read value from this arrayhelp,"['jquery', 'html']" +340170,uibutton not resizing fontsize automatically i am programmatically adding a uibutton to my view and i want that font size into the button resize it automatically eg if the text is long resize to a smaller font to fit the buttonthis code is not working the font is always the samemybutton uibutton buttonwithtype uibuttontyperoundedrectmybutton settitlensstring stringwithformathello forstateuicontrolstatenormalmybutton setframe cgrectmake0 0 180 80mybuttontitlelabel setfont uifont boldsystemfontofsize160mybuttontitlelabeladjustsfontsizetofitwidth truetheview addsubviewmybutton,"['ios', 'objective-c']" +340177,trying to check get for empty parameters i am putting together a script that pulls through several get variables which are then used within the script for the purposes of calculating a quote etcthe nightmare i am having is simply being able to determine if any of them are without a value for example var1500var2var3yes with var2 being the culprint there depending on whether or not all of the get variables have a value or not i will take different actions accordinglyi researched and came up with this as an optionphp foreach get as name value if value proceed 0 else proceed 1 i am echoing a simple bit of text using proceed at the moment just for testing purposesthis does not work and i have considered isset and empty but i believe both options are useless in this case i have read in a number of sources that get parameters that are not given values default to so i am puzzled as to why this is not workingi cannot use empty here due to the fact that sometimes the parameters will be set to 0it goes without saying that i have printed the contents of get and get satisfactory results so the data is all goodany help greatly appreciated,['php'] +340235,jrbeancollectiondatasource how to show data from the javautillist from javabean possible duplicatehow do i print a list of strings contained within another list in ireport my javabean contains the javautillistuserinfo private string username private string password listaddress listaddresshow to show the data of this list in the detail band,['java'] +340237,which is more efficient selectorlast or selectorlast i have a parent element with a real lot of child elements 10s i am looking for the fastest possible way to get a handle to the last child element the options i have found areparent childlastand parent childlastany opinions on which one is reliably faster across browsersediti wrote a test in jsfiddle to measure this out and it turns out the difference is pretty much negligible though last was performing better the difference is negligible so i think even with the last selector it is actually getting the whole list of elements and then returning the last element unbelievablefiddle,"['javascript', 'jquery']" +340241,in python how do i inspect and then reraise an exception while maintaining the original call stack i have got a situation where i am catching a specific exception type inspecting the exceptions message to check if it is actually an exception i want to catch and then reraising the exception if nottry do something exceptionproneexcept fooexception as e if emessage something i want to handle handle the exception else raise ethis works fine with one problem in the case i reraise the exception that exception now occurs at the line i reraised it ie at raise e rather than at the location the exception originally occurred this is not ideal for debugging where you want to know where the original exception happenedthus my question is there any way to reraise or otherwise pass on an exception after catching it while maintaining the original exception locationnote in case you are wondering what the actual situation is i am dynamically importing some modules using import i am catching importerror to gracefully deal with the case that any of these modules do not exist however in the case that any of these modules themselves contain an import statement that raises importerror i want those real from the point of view of my application exceptions to be raised and at the original location as far as debugging tools are concerned,['python'] +340292,capturing method parameter in jmock to pass to a stubbed implementation i wish to achieve the following behaviormy class under test has a dependency on some other class i wish to mock this dependency with jmock most of the methods would return some standard values but there is one method where i wish to make a call to a stubbed implementation i know i can call this method from the will but i want the method to be called by the exact same parameters that were passed to the mocked method testtestpublic void mytest mockery context new mockery setimposteriserclassimposteriserinstance idependency mockobject contextmockidependencyclass expectations exp new expectations allowingmockobjectmethodtoinvoke willstubmethodtobeinvokedinstead interfacepublic interface idependency public int methodtoinvokeint argmethod to be called insteadpublic int stubmethodtobeinvokedinsteadint arg return argso how do i capture the parameter that were passed to the method being mocked so i could pass them to the stubbed method insteadedit just to give another example let us say i wish to mock the inamesource dependency in the following c code to test the class speakerpublic class speaker private readonly string firstname private readonly string surname private inamesource namesource public speakerstring firstname string surname inamesource namesource thisfirstname firstname thissurname surname thisnamesource namesource public string introduce string name namesourcecreatenamefirstname surname return stringformathi my name is 0 name public interface inamesource string createnamestring firstname string surnamethis is how it can be done in rhino mocks for c i understand it cannot be as easy as this since delegates are missing in java,['java'] +340309,what difference does asnotracking make i have a question regarding the asnotracking extension as this is all quite new and quite confusingi am using a perrequest context for a websitea lot of my entities do not change so do not need to be tracked but i have the following scenario where i am unsure of whats going to the database or even whether it makes a difference in this casethis example is what i am currently doingcontextsetuserasnotracking step 1 get usercontextsetuser step 2 update userthis is the same as above but removing the asnotracking from step 1contextsetuser step 1 get usercontextsetuser step 2 update userthe steps 1 2 use the same context but occur at different times what i cannot work out is whether there is any difference as step 2 is an update i am guessing both will hit the database twice anywaycan anyone tell me what the difference is,"['c#', '.net']" +340315,is it possible to know the sourceeg google play of android app is it possible to check whether an application was installed via android market google play store or by other meansbasically what i want to know is whether an application is genuine or not if the source of installation of an app is play store then we know that the application named comdropboxandroid is the actual dropbox application but if the source is not play store then anyone could have created an android app with same package name and installed it on device,['android'] +340342,android performance flat file vs sqlite there are few questions related to this topic on stackoverflow but i did not get the proper answer i have some doubts on performance of flat files is it better to use flat files instead of sqlite can anybody have performance statistics or example of proper way to code flat file in android,['android'] +340350,thisable scrolling of a listview contained within a scrollview i want to show a profile screen for my usersit must have three views 2 buttons and a imageview and a listview to show the content made by that userhowever i do not want the listview to scroll instead i want it to be as big as needed and to put all my views inside a scrollview so the three first views scroll out with the listview this of course does not work as intendedall my three items are inside a linearlayout i thought of making them the first item in the listview but this leads to them being selectable as the first item and having to do some unneeded coding is there a way to do this the easy way or will i have to stick with making the layout the first item in my listview,['android'] +340368,what does variable or 0 mean in python what is the meaning of the following statement in pythonx variable 1 or 0variable 1 is an object what value does x have above and what is the type of x,['python'] +340457,what a strange behavior in autocomplete in datagridviewcombobox column i am using the editingcontrolshowing event to enable autocomplete in datagridviewcombobox columnprivate void datagridview1 editingcontrolshowingobject sender datagridvieweditingcontrolshowingeventargs e if econtrol is datagridviewcomboboxeditingcontrol combobox combo comboboxecontrol comboboxecontroldropdownstyle comboboxstyledropdown comboboxecontrolautocompletesource autocompletesourcelistitems comboboxecontrolautocompletemode systemwindowsformsautocompletemodesuggestappend but it has a strange behavior when i type some characters then i leave the cell tab or right key the value did not changebut if i repeat that the value will changefrom here you can download the source code and exe video that explains the problemcould you please help me to make it work correctly,['c#'] +340458,how to test for equality of functions in javascript how would i get a positive test for bar and foos equality foo function a 1 bar function a 1 if foo bar alertbaz if foo bar alertquxboth the above conditionals are false updated as requested the reason i need to test for function equalityi am building a publishsubscribe framework and need to pass the callback inorder to unsubscribe to a topicplease see the fiddle,['javascript'] +340541,call net assembly from object tag in ie8 i have a web page that calls a net assembly everything works fine in windows xp and ie7 the relevant partshtmlhead script languagejavascript typetextjavascript function doscript mycontrol1govalue1value2 scriptheadbody onloadjavascriptdoscript object idmycontrol1 namemycontrol1 codebasecabsmyassemblydll classidcabsmyassemblydllmynsmyclass width1 height1objectbodyhtmli cannot get this to work in windows 7 with ie8 some notesthe assembly is strong namedi am hosting this on localhost right nowon the machine that is working virtualboxhosted winxp ie7 it is using an ip address to my local machine and that ip is in the trusted sites of ieon the machine that is not working windows 7 ie8 it is using httplocalhost and localhost is in the trusted sites of iethe assembly is being served from httplocalhostcabsmyassemblydllthe error message is a javascript error object does not support this property or methodfiddler shows a 200 ok response when the file is requested however it does not appear that the dll is making it to the temporary internet files locationthe site is running in ie 7 compatibility modei have dropped all ie permissions to the most insecure it will let you in all zones and the behavior is exactly the samedoes anyone have any ideas to try to get this to work or troubleshoot where the problem is atthisclaimer yes i realize it is 2012 and the world has moved past ie7 ie8 activex etc let us just say were a little bit behind technologically this is the problem i have to solve upgrading to modern solutions is not going to be an optionupdate i did get it to work in a windows xp virtualbox running ie8 so it appears the problem is specific to windows 7 it fails both on my local machine and a virtualbox running windows 7 ie8,"['asp.net', '.net']" +340548,how do i modify the entire default trycatch template in settings of idea i can not find where to the trycatch template in settings of idea i want to modify the entire template not just what is in the catch statement body templatefor example renaming the reference to the exception from e to ex,['java'] +340556,integrate a rails application into a site made in wordpress i am currently building an application an analyzer tool in rails 32 i am just about done with it in the development phase i am having our designer begin work on designing our new website where this application will be integratedi had an idea though and wanted to get a feedback badlywhat if the website is built on wordpress but that that analyzer tool which is built in rails which has its own backendreporting system and that element of the site accounted for the custom coding so it was a hybrid of wordpress and this analyzer tool is this possible and if it is possible do you foresee any challenges with thatany help would be very appreciatedthanks in advance,['ruby-on-rails'] +340589,mysql php storing a formula the dilemmai have options that need to store pricing dataeach option can have a different formula to determine it is costeg one options total cost will be cost sq feet but another option will be cost perimeter feet while another option still will simply be a fixed costthese options are being pulled from the database by several sites that my company ownseach one of those sites needs to be able to calculate the options pricing in the exact same waywe currently have php code on each site that pulls data from the database and then determines how to calculate itthe problem with this method is that we will sometimes change how a price is calculated and when that happens we have to edit the pricing module repository and then update it to each server that hosts one of these sitesi am looking for a better solutioni am toying with the idea of storing a formula in the option record in the database then each site would simply need to call the option apply data to the formula stored there and then run the formulanow this can be done with eval but i do not really want to do it that wayeval example to give you a clearer idea of what i am trying to doproductwidth 3productlength 4formula optioncost formula productwidth productlength optioncostevalformuladoes anyone else have any other solution,"['php', 'mysql']" +340623,php 53 enable dl not enabling dl i am trying to install a 3rd party php extension so into php 53613 on ubuntu 10 and use it in a web environment the vendors documentation suggests using the dl function to dynamically load the librarywhen i try their example code i find the dl is not available fatal error call to undefined function dl as dl function was deprecated in php 53 but there is an enable dl config rule in phpini and other sources say that i should be able to use dl simply by changing the phpini variables enable dlon safe modeoff not listed in thisable functions and restarting apache when i try that dl is still undefinedso i dig into the php 53 sapi change notes and find this the dl function is now thisabled by default and is now available only under the cli cgi and embed sapisdoes this mean that dl is not only thisabled by default in php 53 using a web sapi but actually completely unavailable no matter what i do even with modifying php config options that is what it appears to me to be since i cannot get dl to work no matter what i tweakto clarify i can modify phpini and load the extension directly so this is not a question about how to get the extension working rather about the function dl and its state in php 53 if it is no longer available under any circumstance i want to be able to tell the vendor so they can update their documentation but if it should be available and i am just missing something i would like to hear that too,['php'] +340627,exclude javascript libraries from sonar if you look at this site analysing javascript with sonar you see that there are lots of errors reported on the javascript librariesseveritymajorhow can i prevent sonar reporting the errors in the javascript libraries that i am using since i cannot fix any issuesat the same time if i do manage to exclude the library i do not want errors like undefined variables to appear in my files because they are referencing the javascript libraryif it makes any difference i am using extjs 40,['javascript'] +340628,save and restore collapsed state of expandablelistactivity with simplecursortreeadapter after spending some days now on research for this problem i am finally giving up and post this question similar questions have been answered here partly and solutions were proposed but non of them finally helped me the difference to the thiscussed topics and my problem seems to be non of the others seems to use a simplecursortreeadapter to feed the listproblem when changing the orientation of my device samsung galaxy s the expand state of the groups is not preserved and restored all groups appear closed and the list is scrolled to the topthe problem already is visible in the android api demos in case you have them installed navigate toviews expandable lists 2 cursor people start the sample expand any group turn your device and the result shows the group in collapsed statein the code below i did the following took the code from the the api demo expandablelist2java and extended it with implementations for onsaveinstantstate onrestoreinstancestate and onresume implementations for these methods was taken from another thiscussion thread here how to preserve scroll position in an expandablelistviewimport androidappexpandablelistactivityimport androidcontentasyncqueryhandlerimport androidcontentcontenturis import androidcontentcontextimport androiddatabasecursorimport androidneturiimport androidosbundleimport androidosparcelableimport androidprovidercontactscontractcommondatakindsphoneimport androidprovidercontactscontractcontactsimport androidviewviewimport androidwidgetcursortreeadapterimport androidwidgetexpandablelistviewimport androidwidgetsimplecursortreeadapterpublic class mainactivity extends expandablelistactivity private static final string list state key levelselectliststateprivate static final string list position key levelselectlistpositionprivate static final string item position key levelselectitempositionprivate static final string contacts projection new string contacts id contactsthisplay name private static final int group id column index 0private static final string phone number projection new string phone id phonenumber private static final int token group 0private static final int token child 1private static final class queryhandler extends asyncqueryhandler private cursortreeadapter madapter public queryhandlercontext context cursortreeadapter adapter supercontextgetcontentresolver thismadapter adapter override protected void onquerycompleteint token object cookie cursor cursor switch token case token group madaptersetgroupcursorcursor break case token child int groupposition integer cookie madaptersetchildrencursorgroupposition cursor break public class myexpandablelistadapter extends simplecursortreeadapter note that the constructor does not take a cursor this is done to avoid querying the database on the main thread public myexpandablelistadaptercontext context int grouplayout int childlayout string groupfrom int groupto string childrenfrom int childrento supercontext null grouplayout groupfrom groupto childlayout childrenfrom childrento override protected cursor getchildrencursorcursor groupcursor given the group we return a cursor for all the children within that group return a cursor that points to this contacts phone numbers uribuilder builder contactscontent uribuildupon contenturisappendidbuilder groupcursorgetlonggroup id column index builderappendencodedpathcontactsdatacontent directory uri phonenumbersuri builderbuild mqueryhandlerstartquerytoken child groupcursorgetposition phonenumbersuri phone number projection phonemimetype new string phonecontent item type null return null private queryhandler mqueryhandlerprivate cursortreeadapter madapterprivate parcelable liststateprivate int listpositionprivate int itempositionoverridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate set up our adapter madapter new myexpandablelistadapter this androidrlayoutsimple expandable list item 1 androidrlayoutsimple expandable list item 1 new string contactsthisplay name name for group layouts new int androidridtext1 new string phonenumber number for child layouts new int androidridtext1 setlistadaptermadapter mqueryhandler new queryhandlerthis madapter query for people mqueryhandlerstartquerytoken group null contactscontent uri contacts projection contactshas phone number 1 null nulloverrideprotected void ondestroy superondestroy null out the group cursor this will cause the group cursor and all of the child cursors to be closed madapterchangecursornull madapter nulloverrideprotected void onsaveinstancestatebundle outstate superonsaveinstancestateoutstate expandablelistview listview thisgetexpandablelistview liststate listviewonsaveinstancestate outstateputparcelablelist state key liststate listposition listviewgetfirstvisibleposition outstateputintlist position key listposition view itemview listviewgetchildat0 itemposition itemview null 0 itemviewgettop outstateputintitem position key itempositionoverrideprotected void onrestoreinstancestatebundle state superonrestoreinstancestatestate liststate stategetparcelablelist state key listposition stategetintlist position key itemposition stategetintitem position keyoverrideprotected void onresume superonresume expandablelistview listview thisgetexpandablelistview if listview null if liststate null yes this code is reached listviewonrestoreinstancestateliststate listviewsetselectionfromtoplistposition itemposition with the debugger i made sure all these methods are actually called in the right order when the device orientation is changed however restoring the state is without effectfurther debugging into it i found that the content of the restored liststate in onrestoreinstancestate contains an empty array while the liststate in onsaveinstancestate contains data in its array when put into the outstateso my assumption is that the liststate parcelable is not persisted or retrieved correctly by the systemcan anybody point out what is going wrong or provide a working example using the simplecursortreeadapter with working restore of expandcollapsed statenote to reproduce this problem with the activity code above you need to provide androidpermissionread contacts permission,['android'] +340649,bootstrap tooltip on method delete link in rails i am using method delete on a link in rails and trying to get a bootstrap tooltip on itthis does not show a tooltiplink to destroy blog pathblog dataoriginaltitle delete your answer dataplacement top rel tooltip method deletehowever if i remove the method delete the tooltip workshow can i get a tooltip on a delete link,['ruby-on-rails'] +340653,can mysql use multiple indexes for a single query imagine a table with multiple columns say id a b c d e i usually select by id however there are multiple queries in the client app that uses various conditions over subsets of the columnswhen mysql executes a query on a single table with multiple where conditions on multiple columns can it really make use of indexes created on different columns or the only way to make it fast is to create multicolumn indexes for all possible queries,['mysql'] +340667,how do i fix add mybundle to the asseticbundle config symfony2 exception when i am trying to use the twig javascript tag to link to my js file it return me with the following exception an exception has been thrown during the compilation of a template you must add competitiongamebundle to the asseticbundle config to use the javascripts tag in competitiongamebundlegameindexhtmltwig in competitiongamebundlegameindexhtmltwigmy indexhtmltwig looks like javascripts competitiongamebundleresourcesviewspublicjs script typetextjavascript src asset url script endjavascripts hello name a href nexturl loginamy bundle is already present in the config file when i do php appconsole configdumpreference assetichow can i fix this,['php'] +340702,why is glclear blocking in opengles i am trying to profile my renderer and i am seeing some weird profiling behavior that i cannot explaini am using a glsurfaceview which i have set to render continuouslythis is how my ondrawframe is structuredpublic void ondrawframegl10 unused gles20glcleargles20gl color buffer bit gles20gl depth buffer bit executealldrawcommandsthis was behaving slowly under light load so i created a timer class and started to profile this some i was quite surprised by what i sawi put some probes on my ondrawframe method like sopublic void ondrawframegl10 unused swaptimerend cleartimerstart gles20glcleargles20gl color buffer bit gles20gl depth buffer bit cleartimerend drawtimerstart executealldrawcommands drawtimerend swaptimerstartcleartimer measures the time it takes to call glclear drawtimer measures the time it takes to run all my draw calls and swaptimer measures the time from when ondrawframe exits and when it returns the time taken to call eglswapbufferswhen i ran a very lightly loaded scene i got some really strange numbers i cannot explainswaptimer 20ms averagecleartimer 11ms averagedrawtimer 2ms averagei expected the swap time to be somewhat largish as i believe the device has vsync forced enable at 30fps though i do not know why the actual clear call is blocking for 11 milliseconds i thought it was just supposed to issue an asynchronous command and returnwhen i draw a much more busy scene the numbers change quite a bitswaptimer 2ms averagecleartimer 0ms averagedrawtimer 44ms averagein this scene my draw calls are taking so much time that it looks like its hiding a lot of the vsync period and the block on the clear call totally goes awayis there any explanation for why glclear is blocking on my lightly loaded scenelink to my timer class source code in case someone is suspicious of my measuring technique,['android'] +340750,count how many hashmap entries have a given value public final static hashmapstring integer party new hashmapstring integerpartyputjan1partyputjohn1partyputbrian1partyputdave1partyputdavid2how can i return a number of how many people has the value 1,['java'] +340763,unable to load the native components of sql server compact corresponding to the adonet provider in my project i use sql ce 35 database with entity framework and followed this article but i have this exception unable to load the native components of sql server compact corresponding to the adonet provider of version 8080 install the correct version of sql server compact refer to kb article 974247 for more detailsall details systemdatasqlservercesqlceexception was unhandled messageunable to load the native components of sql server compact corresponding to the adonet provider of version 8080 install the correct version of sql server compact refer to kb article 974247 for more details source hresult1 nativeerror1 stacktrace at systemdatasqlservercenativemethodsloadnativebinaries at systemdatasqlservercesqlceconnectionctor at systemdatasqlservercesqlceproviderfactorycreateconnection at systemdataentitycliententityconnectiongetstoreconnectiondbproviderfactory factory at systemdataentitycliententityconnectionchangeconnectionstringstring newconnectionstring at systemdataobjectsobjectcontextctorstring connectionstring string defaultcontainername at daloimdbentitiesctor at daloimrepositoryctor at microsoftrtccollaborationsamplesubscribepresenceviewucmasamplesubscribepresenceviewsubscribe at microsoftrtccollaborationsamplesubscribepresenceviewucmasamplesubscribepresenceviewrun at systemthreadingexecutioncontextrunexecutioncontext executioncontext contextcallback callback object state boolean ignoresyncctx at systemthreadingexecutioncontextrunexecutioncontext executioncontext contextcallback callback object state at systemthreadingthreadhelperthreadstart innerexception systemdllnotfoundexception messageunable to load dll sqlceme35dll the specified module could not be found exception from hresult 0x8007007e sourcesystemdatasqlserverce typename stacktrace at systemdatasqlservercenativemethodsgetsqlceversioninfointptr pwszversion at systemdatasqlservercenativemethodsloadvalidlibrarystring modulepath int32 moduleversion at systemdatasqlservercenativemethodsloadnativebinaries innerexception,['c#'] +340775,using folder pathname save all image files and file names i trying to create a 360 degree animation from in designtohtml conversioni get the folder name and inside that folder are 50 to 80 images i need to save those images in my folder and to save each image name inside the scriptheres my codevar doc appactivedocumentfor var j 0 j docrectangleslength j var nav docrectanglesjextractlabel alertnav length navlength forvar nav get name 0 nav get name navlength nav get name alertnavnav get name0navnav get name1 var path name nav21,['javascript'] +340816,what is objc msgsend fixup exactly i am messing around with the objectivec runtime trying to compile objectivec code without linking it against libobjc and i am having some segmentation fault problems with a program so i generated an assembly file from it i think it is not necessary to show the whole assembly file at some point of my main function i have got the following line which by the way is the line after which i get the seg faultcallq l objc msgsend fixup allocand here is the definition for l objc msgsend fixup allochidden l objc msgsend fixup alloc 01l objc msgsend fixup alloc type l objc msgsend fixup allocobject section data objc msgrefs coalescedawprogbits weak l objc msgsend fixup alloc align 16l objc msgsend fixup alloc quad objc msgsend fixup quad l objc meth var name size l objc msgsend fixup alloc 16i have reimplemented objc msgsend fixup as a function id objc msgsend fixupid self sel op which returns nil just to see what happens but this function is not even being called the program crashes before calling itso my question is what is callq l objc msgsend fixup alloc supposed to do and what is objc msgsend fixup after l objc msgsend fixup alloc supposed to be a function or an objecteditto better explain i am not linking my source file against the objc library what i am trying to do is implement some parts of the libray just to see how it works here is an approach of what i have doneinclude stdiohinclude objcruntimehinterface myclass id allocendimplementation myclassid alloc alloc the object return nilendid objc msgsend fixupid self sel op printfcalling objc msgsend fixupn looks for the method implementation for sel in selfs method list return nil since this is just a test this function does not need to do thatint mainint argc char argv myclass m m myclass alloc at this point according to the assembly code generated objc msgsend fixup should be called so the program should at least print calling objc msgsend fixup on the screen but it crashes before objc msgsend fixup is called return 0if the runtime needs to access the objects vtable or the method list of the obects class to find the correct method to call what is the function which actually does this i think it is objc msgsend fixup in this case so when objc msgsend fixup is called it receives an object as one of its parameters and if this object has not been initialized the function failsso i have implemented my own version of objc msgsend fixup according to the assembly source above it should be called it does not matter if the function is actually looking for the implementation of the selector passed as parameter i just want objc msgsend lookup to be called but it is not being called that is the function that looks for the objects data is not even being called instead of being called and cause a fault because it returns a nil which by the way does not matter the program seg fails before objc msgsend lookup is callededit 2a more complete assembly snippetglobl main align 16 0x90 type mainfunctionmain mainltmp20 cfi startproc bb0 pushq rbpltmp21 cfi def cfa offset 16ltmp22 cfi offset rbp 16 movq rsp rbpltmp23 cfi def cfa register rbp subq 32 rsp movl 0 eax leaq l objc msgsend fixup alloc rcx movl 0 4rbp movl edi 8rbp movq rsi 16rbp movq l objc classlist references rsi movq rsi rdi movq rcx rsi movl eax 28rbp 4byte spill callq l objc msgsend fixup alloc movq rax 24rbp movl 28rbp eax 4byte reload addq 32 rsp popq rbp retfor l objc msgsend fixup alloc we havehidden l objc msgsend fixup alloc 01l objc msgsend fixup alloc type l objc msgsend fixup allocobject section data objc msgrefs coalescedawprogbits weak l objc msgsend fixup alloc align 16l objc msgsend fixup alloc quad objc msgsend fixup quad l objc meth var name size l objc msgsend fixup alloc 16for l objc classlist references type l objc classlist references object 01l objc classlist references section data objc classrefs regular no dead stripawprogbits align 8l objc classlist references quad objc class myclass size l objc classlist references 8objc class myclass is a pointer to the myclass struct definition which has been also generated by the compiler and it is also present in the assembly code,['objective-c'] +340847,in visual studio 2010 search for two strings within single lines of c code i am using visual studio 2010 with c i need to search my codebase for find all lines of code where two strings are found in the single line of code the line of code could span multiple lines which c allows the two strings are not connected and i do not know what will be between them i just want to find all occurances where it finds both strings in the line of code is there anyway to do this is there another tool outside of visual studio that would allow this type of search,"['c#', '.net']" +340851,python importing a subapackage or subamodule having already use flat packages i was not expecting the issue i encountered with nested packages here isadirectory layoutdir testpy package init py subpackage init py modulepycontent of initpyboth package init py and packagesubpackage init py are emptycontent of modulepy file packagesubpackagemodulepyattribute1 value 1attribute2 value 2attribute3 value 3 and as many more as you wantcontent of testpy 3 versionsversion 1 file testpyfrom packagesubpackagemodule import print attribute1 okthat is the bad and unsafe way of importing things import all in a bulk but it worksversion 2 file testpyimport packagesubpackagemodulefrom packagesubpackage import module alternativefrom module import attribute1a safer way to import item by item but it fails python do not want this fails with the message no module named module howevera a file testpyimport packagesubpackagemodulefrom packagesubpackage import module alternativeprint module surprise hereaa says module packagesubpackagemodule from so that is a module but that is not a module p 8o uhversion 3 file testpy v3from packagesubpackagemodule import attribute1print attribute1 okthis one works so you are either forced to use the overkill prefix all the time or use the unsafe way as in version 1 and thisallowed by python to use the safe handy way the better way which is safe and avoid unecessary long prefix is the only one which python reject is this because it loves import or because it loves overlong prefixes which does not help to enforce this practicesorry for the hard words but that is two days i trying to work around this stupidalike behavior unless i was totally wrong somewhere this will leave me with a feeling something is really broken in pythons model of package and subapackagesnotes i do not want to rely on syspath to avoid global side effects nor on pth files which are just another way to play with syspath with the same global effets for the solution to be clean it has to be local only either python is able to handle subpackage either it is not but it should not require to play with global configuration to be able to handle local stuffi also tried use imports in packagesubpackage init py but it solved nothing it do the same and complains subpackage is not a known module while print subpackage says it is a module weird behavior againmay be i am entirely wrong tough the option i would prefer but this make me feel a lot thisappointed about pythonany other known way beside of the three i tried something i do not know aboutsigh edit conclusion so far after peoples commentsthere is nothing like real subapackage in python as all package references goes to a global dictionnary only which means there is no local dictionary which implies there is is no way to manage local package referenceyou have to either use full prefix or short prefix or alias as infull prefix versionfrom packagesubpackagemodule import attribute1 an repeat it again an again but after that you can simplyuse of attribute1short prefix version but repeated prefixfrom packagesubpackage import module short but then you have to douse of moduleattribute1 and repeat the prefix at every use placeor else a variation of the abovefrom packagesubpackage import module as muse of mattribute1 m is a shorter prefix but you could as well define a more meaningful name after the contextfactorized versionif you do not mind about importing multiple entity all at once in a batch you canfrom packagesubpackagemodule import attribute1 attribute2 and etcnot in my first favorite taste i prefer to have one import statement per imported entity but may be the one i will personally favorupdate 20120914finally appears to be ok in practice except with a comment about the layout instead of the above i usedfrom packagesubpackagemodule import attribute1 attribute2 attribute3 and etc,['python'] +340866,use composer without packagist say for instance you want to use a bundle from someone else but want to do some modifications so you do your modifications in some new branch and configure comspoerjson like require syliusassortmentbundle devsoftdeleteableproductsthisabled repositories type package package name syliusassortmentbundle version 10 autoload psr0 syliusbundleassortmentbundle targetdir syliusbundleassortmentbundle source url type git reference softdeleteableproductsthisabled this works with master branch but with custom branch it gives the requested package syliusassortmentbundle devsoftdeleteableproductsthisabled could not be foundany idea,['php'] +340872,attributeerror module object has no attribute argv when using pythonh when messing around with pythonh i got this error attributeerror module object has no attribute argvc code include stdafxh include cpython27includepythonh include iostream using namespace std int main py initialize pyrun simplestringimport sysnprint sysargv0which in python isimport sysprint sysargv0what am i missing,"['c++', 'python']" +340910,correct way to take absolute value of int min i want to perform some arithmetic in unsigned and need to take absolute value of negative int something likedo some arithmetic in unsigned modeint some signed value unsigned int magnitude int negative ifsome signed value0 magnitude 0 some signed value negative 1 else magnitude some signed value negative 0 snipbut int min might be problematic 0 int min is ub if performed in signed arithmeticwhat is a standardrobustsafeefficient way to do this in ceditif we know we are in 2complement maybe implicit cast and explicit bit ops would be standard if possible i would like to avoid this assumptiondo some arithmetic in unsigned modeint some signed value unsigned int magnitudesome signed value int negativesome signed value0 if negative magnitude magnitude 1 snip,['c'] +340933,resizing base64 images i have multiple images saved as base64 strings and now i want to resize these images to get thumbnails of thembest would be using javascript nodeserver to resize them but it would be possible to resize them with php too thanks in advance,['php'] +340949,in postgresql whats the difference a database and a relation error relation x does not exist error database x already exists i see the juxtaposition of these two errors and given the dearth of google search results had to ask what is the difference and what do i need to be doing heredeploy grant select on angel research production to angel researcherror relation angel research production does not existdeploy create database angel research productionerror database angel research production already existsmy guess is that i need to be doing this grant select business from some other userso i run this on postgres dbroot and get thispostgres grant select on angel research production to angel researcherror relation angel research production does not existso it does exist as a database but not as a relation how might i rectify this and what are the underlying issues here i am a little overwhelmed thanks,"['sql', 'ruby-on-rails']" +340950,do i always have a b b a b a when b is not zero for int a b i know that when there is exactly one of a and b is negative the result of a b and a b is machine dependent but do i always have a b b a b a when b is not zero,"['c++', 'c']" +340978,how do i use the ostringstream properly in c i am attempting to return some information when my tostring method is called which include an integer and some floats i learned about ostringstream works great but when the class that contains this method is called over and over again the information gets stacked onto my previous output here is my code ostringstream int buffer float buffer float buffer2is introduced at the beginning of my class then string tostring int buffer on hand float buffer price float buffer2 generated revenue string stron hand int bufferstr string strprice float bufferstr string strrev float buffer2str string output product name description units left stron hand price strprice revenue strrev return output i know my coding is awful i am still fairly new to this but an example of my output isproduct name movie ticket units left 49 price 9 revenue 9product name movie ticket units left 4926 price 9 revenue 923976where the second one should thisplayproduct name movie ticket units left 26 price 9 revenue 23976i know it is just a matter of updating but that is where i am lost,['c++'] +341010,which python module you use for simple data validation i am writing a python module that will contain some functions that will manipulate a mongodb database i am looking for a data validation module that can help me in validating input data passed to that function before saving it in database which python modulepackage you use for this purposefor example lets say one of the function in module is createuseruser which accepts a python dictionary as argument this dictionary contains user information to save in the database is there any modulepackage i can use to validate the data supplied in dictionary and return any errors,['python'] +341021,how to create a blank transparent png in objective c how can i create a blank png uiimage in objective c programmatically let us say 36x36 pxthanks,"['objective-c', 'ios']" +341119,getting started with speech recognition and python i would like to know where one could get started with speech recognition not with a library or anything that is fairly black boxed but instead i want to know where i can actually make a simple speech recognition script i have done some searching and found not much but what i have seen is that there are dictionaries of sounds or syllables that can be pieced together to form text so basically my question is where can i get started with thisalso since this is a little optimistic i would also be fine with a library for now to use in my program i saw that some speech to text libraries and apis spit out only one results this is ok but it would be unrealiable my current program already checks the grammar and everything of any text entered so that way if i were to have say the top ten results from the speech to text software than it could check each and rule out any that do not make sense,['python'] +341155,better way to say x fooa x foob x fooc let us say i have a bunch of wellknown values like this but const char is just an example it could be more complicatedconst char a a b b c c d d e e f f g gnow let us say i want to behave in a particular way if the result of some expression is in a subset of thoseif some complicated expression with ugly return type a some complicated expression with ugly return type c some complicated expression with ugly return type e some complicated expression with ugly return type g i find myself typing this sort of thing often enough that i would like a shorthand for itif the language was python i could easily sayif some complicated expression with ugly return type in a c e g is there a wellknown portable way for me to express this similarly in c03note that the return type is itself ugly almost as ugly as the return type of lambda expressions so i certainly do not want to store it in a local variable but the return type does not have to match that of the constants for example if the return type was stdstring it would not be implicitly convertible to const char but operator would be perfectly fine for the comparisonso far the best solution i have is to say something likeconst char items a c e g if stdfinditems items sizeofitems sizeofitems some complicated expression with ugly return type items sizeofitems sizeofitems but it is pretty darn ugly is there a better way which also works for nonpods,['c++'] +341160,umlauts in regexp matching via locale i am surprised that i am not able to match a german umlaut in a regexp i tried several approaches most involving setting locales but up to now to no availlocalesetlocalelocalelc all de deutf8refindallrw abc def gxfci jkl relrefindallrw abc def gxc3xbci jkl relrefindallrw abc def ga14i jkl relrefindallrw uabc def ga14i jkl relnone of these versions matches the umlautu a14 correctly with w also removing the rel flag or prefixing the pattern string with u to make it unicode did not help meany ideas how is the flag rel used correctly,['python'] +341169,what is a context it seems to me that a context class is a control console that its object can invoke any included functions such as datacontext and doamincontext in wcf ria service do i understand this concept correctly if so in what circumstances do i need to create a context class in my own class hierarchybeside datacontext what other wellknown context classes do the net framework have,['c#'] +341173,what prior knowledge does android development assume i am looking into doing some android app development just for my own pleasure i have taken a look at some of the developer articles the basics etc and it really sounds like there is a hidden basic assumption about ones prior knowledge in relation to app developmenta lot of what was talked about even in the basics seemed to go over my head i am relatively new to programming i have mainly done c and a little java i have not gotten fully into object oriented still just doing basic programminghonestly i am a little overwhelmed as where i need to go next in order to make this work so what direction can you give me in terms of what to learn first i get that java will be a big part of it but is there anything else that would helpthanksandy,['android'] +341267,write sent sms to contentsmssent table i am working on an android sms applicationi can send sms to single contact by using the following codesmssendtextmessagephonenumber null message sentpi deliveredpinow i want to send sms to multicontactssome suggest to use loopso now i am using loops to send sms to multicontactafter sending each sms i write those values to sent table contentvalues values new contentvalues valuesputaddress mobno valuesputbody msg getcontentresolverinserturiparsecontentsmssent values every new address will create a new thread idfor example if my receivers address is x then thread id 1 for y thread id 2and if i want to send sms to both x and y then how can i write in to smssent tableif i use loopthen it would not create any new thread id because send address x already have thread id 1 and y already have thread id 2so messages will listed under thread id 1 and 2 never creates a new thread idi tried to manualy insert thread id byvaluesputthread id 33but then the messages under new thread id do not listed in default app but in my aplease help me friendsediti tried using 0 and then reading the thread id that was generated then place the next sms with this thread id still does not works,['android'] +341275,contentobserver for contact update manually i have registered a contentobserver from service and i get the onchange function when there is update in phone like call or contact update but i want the onchange function to be called only when add update or delete happens but i do not want when call is incoming or outgoing so can anybody tell me which uri i can register in contentobserver my code is heregetcontentresolverregistercontentobservercontactscontractcontactscontent uri truenew contact changeand contact changejava class is likepublic class contact change extends contentobserver public contact service supernull override public void onchangeboolean selfchange logicontact serviceonchange superonchangeselfchange override public boolean deliverselfnotifications return true edit i have one more problem is that after stop the service if i made change in contact then also onchange function is called so how can i stop that or un register the contentobserver,['android'] +341334,can i check the size of a collection as it is being populated i am listing the files on a file system in java using the following apache commons classcollectionfile allfiles fileutilslistfilesrootdirectory null recursivethis is a very long process and can take up to 5 minutesis there any way i can check the size of the collection while it is being populatedi tried accessing it from a separate thread but simply got zero until the process was ready,['java'] +341343,registration in processed on google play in android possible duplicateunable to parse response error while uploading screenshots on google play android market i just signed up with market and uploaded my app on the next screen it is asking me to upload assets after i choose screen shots for the app and hit uploadi tried using firefox chrome and ie but i am getting the same erroron the home page it saysyour registration to google play is still being processedyou can upload applications to google play but you cannot publish until your registration is completedi guess this error has something to do with my registration as it is still in the pending stage i dont know what do they want me to do in order to complete the registration,['android'] +341355,rails passing form for object to partial i would like to pass the form for object to a partial form for price do f render partial price page object price as f end when i callfradio buttonbrings the errorundefined method radio button for price0x3cb1ed0how can i use f as i usually would in this partial,['ruby-on-rails'] +341361,joining two numpy matrices if you have two numpy matrices how can you join them together into one they should be joined horizontally so that 0 1 01 1 0 10 4 1 41 0 1 01for example with these matricestypextypeyxshapeyshapeclass numpymatrixlibdefmatrixmatrixclass numpymatrixlibdefmatrixmatrix53 153 1i have tried hstack but get an errorz hstackxytraceback most recent call last file labelspy line 85 in module z hstackx y file cpython27libsitepackagesscipysparseconstructpy line 263 in hstack return bmatblocks formatformat dtypedtype file cpython27libsitepackagesscipysparseconstructpy line 329 in bmat raise valueerrorblocks must have rank 2valueerror blocks must have rank 2,['python'] +341370,error 5209 account is restricted i get a 5209 error account is restricted when trying to make a parallel payment my code worked fine using the sandbox but i switched to the live endpoint and it began failing the account in question is a valid paypal account and i am using feespayersender am i missing something should not the pay call go through even if the payee is a basic account why would this occurhere is my code for referencefunction depositconfig try if issetconfigreturn url thisreturn url configreturn url else return return url should be set if issetconfigreturn url thiscancel url configcancel url else return cancel url should be set if issetconfigemail thissender email configemail else return email should be defined if issetconfigamount thisamount configamount else return amount should be defined returnurl thisreturn url cancelurl thiscancel url currencycode usd memo deposit to thisciconfigitemsite name feespayer sender payrequest new payrequest payrequestactiontype pay payrequestcancelurl cancelurl payrequestreturnurl returnurl payrequestclientdetails new clientdetailstype payrequestclientdetailsapplicationid thisciconfigitemapplication id payrequestclientdetailsdeviceid thisciconfigitemdevice id payrequestclientdetailsipaddress thisciinputip address payrequestcurrencycode currencycode payrequestsenderemail thissender email payrequestrequestenvelope new requestenvelope payrequestrequestenvelopeerrorlanguage en us receivers array receiver new receiver receiveremail thisciconfigitemmoneyfan account receiveramount thisamount receiverprimary false receivers receiver payrequestreceiverlist receivers payrequestfeespayer feespayer payrequestmemo memo ap new adaptivepayments response appaypayrequest if strtoupperapissuccess failure thiscisessionset userdatafaultmsg apgetlasterror return json encodearraystatus false msg apgetlasterrorerrorerrorid apgetlasterrorerrormessage redirectsite urlhomeapi error else thiscisessionset userdatapaykey responsepaykey if responsepaymentexecstatus completed redirectreturnurl else token responsepaykey paypalurl paypal redirect url appaymentpaykey token return json encodearraystatus true msg paypalurl headerlocation paypalurl catch exception ex fault new faultmessage errordata new errordata errordataerrorid exgetfile errordatamessage exgetmessage faulterror errordata thiscisessionset userdatafaultmsg fault redirectsite urlhomeapi error,['php'] +341374,jquery text shows double text have a strange situation happening i have a h3 with text in it when i extract this text with text and then put this into a textarea the text appears twicehere is jsfiddlehtmlh3 classprofilerightaboutmetextheya this is all the texth3 textarea classprofilerightaboutmetextareatextareajquerydocumentonclickh6editmyprofilesection function var originaltext h3profilerightaboutmetexttext h3profilerightaboutmetextfadeoutfast function textareaprofilerightaboutmetextareatextoriginaltextfadeinfast alertoriginaltextboth the alert and textarea show the text double as followsheya this is all the textheya this is all the text,"['javascript', 'jquery', 'html']" +341375,mysql illegal mix of collations after viewing my prod logs i have some error mentionning 20120831 155643 requestcritical doctrinedbaldbalexception an exception occurred while executing select t0username from fos user t0 where t0username with params 1nrvu29e7kasisqlstatehy0 general error 1267 illegal mix of collations latin1 swethish ciimplicitand utf8 general cicoercible for operation alghout i have utf8 default under the doctrine cfg doctrine dbal charset utf8it seems that all my mysql tables are in latin1 swethish ci so my question is can i manually change the collation to utf8 general ci for all my tables without any complicationsprecautions,['mysql'] +341393,how to use default php classes in my namespace i am using namespaces to resolve class name conflicts in two of the sdks i am using in my projecti have declared a name space in one of the file like namespace tempclass abc extends stdclass my class def when i am hitting this code i get error says tempstdclass not found so i need to use all default php structures interfaces like iterators etc so how can i import the default namespace of php or do any another setting i am missing,['php'] +341405,why does strtotimex return tomorrows date i cant understand this why does the following occurecho datedmy strtotimestrstr 214454 produces todays datestr 3 produces 1970str a or any single char produces tomorrows datestr aa or any double char produces 1970or just returning the strtotime functionecho strtotimestrstr 214454 produces todays datestr 3 returns falsestr a or any single char produces tomorrows datestr aa or any double char returns falsethese values came from some testing i was doing to try and work out howwhy certain values were being returned from a specific function its causing my function to fail because you would assume a or any single char to be returned as a false incorrect date,['php'] +341406,outlook interop printout document name we use outlook interop method mailitemprintout to print a mail message from outlookit is always printed with name microsoft outlook memo stylememo style here is a print style which outlook automatically picks for printingis there any way to give a document any custom name so we can track it in printer queueit can either be creating a new print style with custom name or explicitly specifying a custom document namebasically we just need emails printed from outlook to appear in printer queue with unique names please advise,['.net'] +341432,how to log memory usage of an django app per request do you know about an efficient way to log memory usage of a django app per request i have an apachemod wsgidjango stack which runs usually well but sometimes one process ends up eating a huge lot of memory the servers ends up being short on mem swapping a lot and services are dramatically slowed downthis situation is quite hard to fix because i do not know which request is to be blamed for this behavior i cannot reproduce iti would like to have something deployed in production which logs the memory usage of the process before and after each request with minimal overheadbefore i start reinventing the wheel do the community of my fellow djangoists know any existing solution to address this problem advices middleware snippet or maybe apache log configuration appreciatedwhat i think i do not need isa set of devstage profilingdebugging tools i already know some and i would use them if i knew what to profiledebug it looks a little bit too much to be forever monitoring services running in production on top of that what is usually thisplayed by those tol is a mem usage report of the code shred to pieces it would really be helpful to just pinpoint the faulty requestgeneric advices on how to optimize mem usage of a django app well it is always good to read but the idea here is rather ahow to efficiently track down requests which need to be optimizedamy closest search resultsdjango wsgi how to profile partial request my profiling tools are perrequest but app runs out of memory before thendjango memory usage going up with every requestaverage php memory usage per request,['python'] +341449,c create file in memory i am writing little program in plain c herewhat i need is to create a file directly inside memory not written on hard thiskcurrently i can use fopenfilenametxtwb to write to the filei know that in linux you can use fmemopen is there a similar solution for win32,['c'] +341454,visual studio 2012 partial publish when i publish my aspnet webforms website with visual studio 2012 always all files are uploaded even imagesis there a way to only publish changed files,"['c#', 'asp.net']" +341477,parse birth and death dates from wikipedia i am trying to write a python program that can search wikipedia for the birth and death dates for people for example albert einstein was born 14 march 1879 died 18 april 1955i started with fetch a wikipedia article with pythonimport urllib2opener urllib2build openeropeneraddheaders useragent mozilla50infile openeropenproprevisionsrvpropcontentrvsection0titlesalbert einsteinformatxmlpage2 infilereadthis works as far as it goes page2 is the xml representation of the section from albert einsteins wikipedia page and i looked at this tutorial now that i have the page in xml format but i do not understand how to get the information i want birth and death dates out of the xml i feel like i must be close and yet i have no idea how to proceed from hereeditafter a few responses i have installed beautifulsoup i am now at the stage where i can printimport beautifulsoup as bssoup bsbeautifulsouppage2print soupgettextinfobox scientist name albert einstein image einstein 1921 portrait2jpg caption albert einstein in 1921 birth date birth datedfyes1879314 birth place ulm kingdom of wa14rttemberg german empire death date death date and agedfyes19554181879314 death place princeton new jerseyprinceton new jersey united states spouse mileva mariaampnbsp1903a1919ltbrgtnowrapelsa lawenthalampnbsp1919a1936 residence germany italy switzerland austria belgium united kingdom united states citizenship plainlist kingdom of wa14rttembergwa14rttemberggermany 1879a1896 statelessnestateless 1896a1901 switzerland 1901a1955 austriaahungaryaustria 1911a1912 german empiregermany 1914a1933 united states 1940a1955so much closer but i still do not know how to return the death date in this format unless i start parsing things with re i can do that but i feel like i would be using the wrong tool for this job,['python'] +341503,stdu16string stdu32string stdstring length size codepoints and characters i am happy to see the stdu16string and stdu32string in c11 but i am wondering why there is no stdu8string to handle the utf8 case i am under the impression that stdstring is intended for utf8 but it does not seem to do it very well what i mean is does not stdstringlength still return the size of the strings buffer rather than the number of characters in the stringso how is the length method of the standard strings defined for the new c11 classes do they return the size of the strings buffer the number of codepoints or the number of characters assuming a surrogate pair is 2 code points but one character please correct me if i am wrong and what about size is not it equal to lengthsee stringlength for the source of my confusionso i guess my fundamental question is how does one use stdstring stdu16string and stdu32string and properly thistinguish between buffer size number of codepoints and number of characters if you use the standard iterators are you iterating over bytes codepoints or characters,['c++'] +341515,whats the pythonic way to wrap several functions in the same with statements i am using the python library fabric to do some remote server maintenance fabric automatically outputs all of the responses to remote and local commands unless you wrap the command in a couple with statements like so on a local machinewith settingswarn onlytrue with hiderunning stdout stderr warnings output localuname a trueor like this on a remote machinewith settingswarn onlytrue with hiderunning stdout stderr warnings output rununame ai am writing a long and complex task and find myself repeating those two with statements over and over again i want to write a function called mute to prevent that repetition it would let me do something like thisdef mutefabric cmd args with settingswarn onlytrue with hiderunning stdout stderr warnings output fabric cmdargs return outputdef some remote task run a remote task silently muteremote uname adef some local task run a local task silently mutelocal uname a truei have looked into some solutions and know that eval could do this for me but every page i read about eval suggests that it is almost always a bad idea because of security issues i looked into partials but i could not figure out how to make an argument in my mute function callable i am guessing there is a higher level python concept i am missing here whats the pythonic way to go about doing this thanks for any direction you might be able to provide,['python'] +341519,can media queries resize based on a div element instead of the screen i would like to use media queries to resize elements based on the size of a div element they are in i cannot use the screen size as the div is just used like a widget within the webpage and its size can varyupdatelooks like there is work being done on this now sourcedlvritutm mediumtwitter404,['css'] +341534,what are these numbers in goto anything of sublime text 2 i have googled a lot but unfortunately i cannot find out what these numbers aside the file names means when you ctrlp goto anything in sublime text 2ideas,"['ruby-on-rails', 'ruby']" +341537,udp rate limits in python update to original post a colleague pointed out what i was doing wrong i will give the explanation at the bottom of the post as it might be helpful for othersi am trying to get a basic understanding of the limits on network performanceof python programs and have run into an anomaly the code fragmentwhile 1 socksendtoatargetsends udp packets to a target machine as fast as the host will sendi measure a sending rate of just over 40 packets per second or 250 usper packet this seems slow even for an interpreted language like pythonthe program is running on a 2 ghz amd opteron linux python version 266i have seen much better performance in python for tcp so i find this a bit weirdif i run this in the background and run top i find that python is usingjust 25 of the cpu suggesting that python may be artificially delayingthe transmission of udp packetshas anyone else experienced anything similar does anyone know if pythondoes limit the rate of packet transmission and if there is a way to turnthis offbtw a similar c program can send well over 20 packets per secondso it is not an intrinsic limit of the platform or osso it turns out i made a silly newbie mistake i neglected to call gethostbynameexplicitly consequently the target address in the sendto command containeda symbolic name this was triggering a name resolution every time a packet wassent after fixing this i measure a maximum sending rate of about 120 psmuch better,['python'] +341542,find rank of a decimal number based on function f and rank i found this question here but this is not the answer i am looking for hence posting againa function of the form f and rankmeans that given a number n in decimal representation its rank is given asstarting from 0 to n how many numbers are there with same number of set bits in itsbinary representationi will go through an example to make it more clearn 6 0110 its rank is 31 3 0011 2 5 0101 3 6 0110 now given a number find its rankthe obvious approach is to start from 0 and check for number of set bits for each number till n1the question isis there any logn solution,['c'] +341543,android draw on camera preview i am making a virtual reality application where the camera should detect faces locate them and show their location on the camera previewi know of 3 ways to do it i would like to use glsurfaceview to be as fast as possible according to this post but currently i am trying to draw on the same surfaceview where the camera is using for its preview my callback to draw on it would be onfacedetection like sopublic class myactivity extends activity implements surfaceholdercallback camerafacedetectionlistener camera camera surfaceview svpreview surfaceholder previewholder textview tvinfo paint red override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain svpreview surfaceview findviewbyidridsvpreview tvinfo textview findviewbyidridtvinfo red new paint redsetstylepaintstylestroke redsetstrokewidth3 previewholder svpreviewgetholder previewholderaddcallbackthis previewholdersettypesurfaceholdersurface type push buffers public void surfacecreatedsurfaceholder arg0 camera cameraopen try camerasetthisplayorientation90 camerasetfacedetectionlistenerthis camerasetpreviewthisplaypreviewholder catch ioexception e eprintstacktrace public void surfacechangedsurfaceholder holder int format int width int height camerastartpreview cameraautofocusnull camerastartfacedetection public void surfacedestroyedsurfaceholder arg0 camerastopfacedetection cameracancelautofocus camerastoppreview camerarelease camera null public void onfacedetectionface faces camera camera tvinfosettextfaces stringvalueoffaceslength canvas canvas previewholderlockcanvas forint i0 i faceslength i point lefteye facesilefteye point righteye facesirighteye this is not working canvasdrawpointlefteyex lefteyey red previewholderunlockcanvasandpostcanvas with this code i keep getting this error0903 193542743 esurfaceholder19394 exception locking surface0903 193542743 esurfaceholder19394 javalangillegalargumentexception0903 193542743 esurfaceholder19394 at androidviewsurfacelockcanvasnativenative method0903 193542743 esurfaceholder19394 at androidviewsurfacelockcanvassurfacejava760903 193542743 esurfaceholder19394 at androidviewsurfaceview4internallockcanvassurfaceviewjava7440903 193542743 esurfaceholder19394 at androidviewsurfaceview4lockcanvassurfaceviewjava7200903 193542743 esurfaceholder19394 at combluetoothactivitiesmyactivityonfacedetectionmyactivityjava900903 193542743 esurfaceholder19394 at androidhardwarecameraeventhandlerhandlemessagecamerajava7290903 193542743 esurfaceholder19394 at androidoshandlerthispatchmessagehandlerjava990903 193542743 esurfaceholder19394 at androidoslooperlooplooperjava1370903 193542743 esurfaceholder19394 at androidappactivitythreadmainactivitythreadjava44240903 193542743 esurfaceholder19394 at javalangreflectmethodinvokenativenative method0903 193542743 esurfaceholder19394 at javalangreflectmethodinvokemethodjava5110903 193542743 esurfaceholder19394 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava7840903 193542743 esurfaceholder19394 at comandroidinternaloszygoteinitmainzygoteinitjava5510903 193542743 esurfaceholder19394 at dalviksystemnativestartmainnative method0903 193542743 wdalvikvm19394 threadid1 thread exiting with uncaught exception group0x40a561f80903 193542766 eandroidruntime19394 fatal exception main0903 193542766 eandroidruntime19394 javalangillegalargumentexception0903 193542766 eandroidruntime19394 at androidviewsurfaceunlockcanvasandpostnative method0903 193542766 eandroidruntime19394 at androidviewsurfaceview4unlockcanvasandpostsurfaceviewjava7750903 193542766 eandroidruntime19394 at combluetoothactivitiesmyactivityonfacedetectionmyactivityjava990903 193542766 eandroidruntime19394 at androidhardwarecameraeventhandlerhandlemessagecamerajava7290903 193542766 eandroidruntime19394 at androidoshandlerthispatchmessagehandlerjava990903 193542766 eandroidruntime19394 at androidoslooperlooplooperjava1370903 193542766 eandroidruntime19394 at androidappactivitythreadmainactivitythreadjava44240903 193542766 eandroidruntime19394 at javalangreflectmethodinvokenativenative method0903 193542766 eandroidruntime19394 at javalangreflectmethodinvokemethodjava5110903 193542766 eandroidruntime19394 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava7840903 193542766 eandroidruntime19394 at comandroidinternaloszygoteinitmainzygoteinitjava5510903 193542766 eandroidruntime19394 at dalviksystemnativestartmainnative methodis there a problem with the camera trying to draw its preview on the same surfaceview the face detection callback how can i do this without layering surfaceviews,['android'] +341548,stdset difference on list container i am trying to call the set difference function and put the result on a stdlist in theory it is possible to do this on any sorted container rightlistint v listint l1 listint l2 listintiterator itl1 and l2 are filled herel1sortl2sortitset difference l1begin l1end l2begin l2end vbeginv is returning as an empty list however is it because i cannot use it on the list container,['c++'] +341569,how is lisps readevalprint loop different than pythons i have encounter a following statement by richard stallmanwhen you start a lisp system it enters a readevalprint loop most other languages have nothing comparable to read nothing comparable to eval and nothing comparable to print what gaping deficiencies now i did very little programming in lisp but i have wrote considerable amount of code in python and recently a little in erlang my impression was that these languages also offer readevalprint loop but stallman thisagrees at least about pythoni skimmed documentation of python after people told me it was fundamentally similar to lisp my conclusion is that that is not so when you start lisp it does read eval and print all of which are missing in pythonis there really a fundamental technical difference between lisps and pythons readevalprint loops can you give examples of things that lisp repl makes easy and that are difficult to do in python,['python'] +341604,how do i use drools planner i have a scheduling problem where each student expresses his preferences for a lecture and a course timetable is generated for all of the students at the same time in a batch mode if i may from what i read around and understand drools planner is very well suited to solve this type of problem i installed drools and gef into my eclipse ide everything loads just fine unfortunately i can not figure out how to build a simple project i looked online for references and found drools planner examples which look and work great however i did not find any good tutorial that walks people through the simple cases besides some code snippets how do i model a matchingscheduling problem where 3 students with unique time and course preferences are looking to sign up for 4 courses how do i start the code where do i put the constraints which classes i call upon etc any help will be greatly appreciated thanks,['java'] +341607,use rails admin forms in custom views i am making my own custom view that i need to make the process of creating associated models less painful for my users i want to thisplay all of the models associated pieces inline with controls to edit them this is quite easy to roll my own for the basic fields but i would rather use a form filtering select partial for the inline models associations but i cannot find any documentation to do this,['ruby-on-rails'] +341627,using nsjsonserialization to parse json too many thiscussions have happened on this and yet i cannot figure out how to solve my problem heres the json data i get from worldweatheronline the json is valid but i cannot figure out how to parse it this is my code followed by the json please helpnserror errorinfonsdictionary parsedjson nsjsonserialization jsonobjectwithdataselfwwoweatherdata optionskniloptions errorerrorinfonsarray temp parsedjson objectforkeytemp cnslog temp data current condition cloudcover0 humidity82 observation time1107 pm precipmm00 pressure1024 temp c16 temp f61 visibility10 weathercode113 weatherdesc valueclear weathericonurl value png 64wsymbol 08 clear sky nightpng winddir16pointnne winddirdegree30 windspeedkmph11 windspeedmiles7 request querylat 4885 and lon 235 typelatlon weather date20120904 precipmm00 tempmaxc25 tempmaxf77 tempminc14 tempminf57 weathercode113 weatherdesc valuesunny weathericonurl value png 64wsymbol 01 sunnypng winddir16pointn winddirdegree5 winddirectionn windspeedkmph13 windspeedmiles8 date20120905 precipmm00 tempmaxc22 tempmaxf72 tempminc10 tempminf50 weathercode113 weatherdesc valuesunny weathericonurl value png 64wsymbol 01 sunnypng winddir16pointnne winddirdegree25 winddirectione windspeedkmph20 windspeedmiles13 date20120906 precipmm00 tempmaxc22 tempmaxf71 tempminc11 tempminf51 weathercode113 weatherdesc valuesunny weathericonurl value png 64wsymbol 01 sunnypng winddir16pointne winddirdegree42 winddirectionne windspeedkmph15 windspeedmiles10 date20120907 precipmm00 tempmaxc24 tempmaxf75 tempminc13 tempminf55 weathercode116 weatherdesc valuepartly cloudy weathericonurl value png 64wsymbol 02 sunny intervalspng winddir16pointene winddirdegree56 winddirectionene windspeedkmph13 windspeedmiles8 date20120908 precipmm00 tempmaxc26 tempmaxf78 tempminc16 tempminf61 weathercode113 weatherdesc valuesunny weathericonurl value png 64wsymbol 01 sunnypng winddir16pointene winddirdegree76 winddirectionene windspeedkmph9 windspeedmiles6,"['iphone', 'ios']" +341720,aspectj expression gives formal unbound in pointcut error i have within aspectj the expressionpointcutwithincomparamcpmsdaoimplprojectmetadaoimplpublic void daoexceptionhandle at spring 30 startup i am getting the following error nested exception is javalangillegalargumentexception error at 0 formal unbound in pointcut,['java'] +341725,capturing photos with specific resolution using the uiimagepickercontroller i would like to take photos of a4 pieces of paper with writing on importantly i want the text to be readable but i do not want images with resolutions like 2592x1936 pixel or 3264x2448 pixel as that would be too big also i assume that rescaling the photo after capturing takes extra time so i would like to avoid this toowe can choose between the following qualitiesuiimagepickercontrollerqualitytypehigh 0 uiimagepickercontrollerqualitytypemedium 1 default value uiimagepickercontrollerqualitytypelow 2 uiimagepickercontrollerqualitytype640x480 3 uiimagepickercontrollerqualitytypeiframe1280x720 4 uiimagepickercontrollerqualitytypeiframe960x540 5 if we were using the avfoundation we could choose resolutions from this nice table under headline capturing still imagesbut is there a similar table for uiimagepickercontroller which for example says that uiimagepickercontrollerqualitytypehigh equals 1920x1080 on iphone 3gs,"['iphone', 'ios']" +341760,decompling an android apk possible duplicateandroid getting source code from an apk file is it possible for someone to decompile my android apk file and see the public variables or constants declared in my packages my shared key that i have defined as public static constant will then get exposed,['android'] +341806,nodejs library for generating indexed pngs does anyone know of a nodejs module for creating indexed pngsi have looked through this list of node graphics modules and some of them allow png creation but none seem to allow you to specify an indexpallete schemejust some extra info i have a 2d array representing pixels each referring to an index of a 1d palette array from this i would like to generate a valid indexed png file 1 channel with 4 bits per channel,['javascript'] +341846,django haystack autocompletion on two multiple fields i use haystack 126 with whoosh 24 and django 13let us say that we have the below model describing an hypothetical postpostmodelsmodel title modelscharfield body modelstextfieldwe built our post index like this for autocompletion on body fieldpostindexsearchindex text charfielddocumenttrue use templatetrue content auto indexesedgengramfieldmodel attrbodyhaving read the haystack documentation thoroughly i cannot find if is possible to have autocompletion on both title and body fieldsso is it possible or,['python'] +341899,setting breakpoint in different file has no effect the ruby debugger does not halt on breakpoints i set in files different from the on the execution starts in for example consider these two files foorb foorbclass foo def bar puts baz endendand mainrb mainrbrequire foofoonewbari start debugging using ruby r debug mainrb now when i try to set a breakpoint on a specific line in another file using b foorb4 i get the message set breakpoint 1 at foorb4 but when i cont the program executes to the end and the debugger never halts however if i break on a line in mainrb eg b mainrb3 or a method eg b foobar the debugger halts as expected why does not the debugger halt at breakpoints in files other than the main fileupdate i have tried this with ruby 193 on windows 7 as well as os x 108 it does not work in either environmenti have also just realized that the debugger quits after the script has run till the end i start debugging mainrb use cont then baz is printed on the console and i am right back in the shell is this the expected behaviour or might the debugger have crashed,['ruby'] +341928,why is my program slow when looping over exactly 8192 elements here is the extract from the program in question the matrix img has the size sizeasize and is initialized atimgji 2 j ithen you make a matrix res and each field in here is made to be the average of the 9 fields around it in the img matrix the border is left at 0 for simplicityfori1isize1i forj1jsize1j resji0 fork1k2k forl1l2l resji imgjlik resji 9that is all there is to the program for completeness sake here is what comes before no code comes after as you can see it is just initializationdefine size 8192float imgsizesize input imagefloat ressizesize result of mean filterint ijklfori0isizei forj0jsizej imgji 2ji8196basically this program is slow when size is a multiple of 2048 eg the execution timessize 8191 344 secssize 8192 720 secssize 8193 318 secsthe compiler is gccfrom what i know this is because of memory management but i do not really know too much about that subject which is why i am asking herealso how to fix this would be nice but if someone could explain these execution times i would already be happy enoughi already know of mallocfree but the problem is not amount of memory used it is merely execution time so i do not know how that would help,['c++'] +341948,aspnet mvc how to prevent a session lock i have an application which has some controllers actions calling slow 3rd party web services these actions are called using ajax calls from the pagei can use async controllers to free aspnet thread pool that is great but what about session if i use inproc session and a request made to slow action the particular user cannot make any request to the application because his session is locked by first slow call in php there is a method session write close which i can use as followingaccept users request to slow actioncheck rights of the user to access controlleraction based on session datawrite something to the session if neededcall session write close from this point session is closed by this request and any other request from the same user can access itmake my slow call maybe in some async wayi know that i can thisable session state on the controller level using sessionstate attribute but that is not the solutionany ideas,['asp.net'] +341982,html5 app database syncing i currently am working on a project that involves storing data in an html5 sqllite database currently i have a schema as follows 4 tablestransdata tid username transcolor date note 6 brendan red 7 brendan red 1 fulldata tid username transcolor date note 1 brendan red start brendan red 40 brendan red end salamanderdata sid salamandername length tid 1 northernslimy 16 6 2 twolined 26 6 3 twolined 12 7 salamanderdata sid salamandername length tid 1 northernslimy 16 6 2 twolined 26 6 3 twolined 12 7 note the note column in transdata is used to point to the beginning data point of a collection in the fulldata field the database between my app and the server should not be in sync i am merely trying to dump all of these tables into the database on the server and by dump i mean update the references to other tables and then insert into the server databasei was going to use maxtidserver tidapp new tidserver and cascade the updates down the tables how would you go about doing this,"['javascript', 'sql']" +341987,how can i detect whether an iframe is loaded i am trying to check whether an iframe has loaded after the user clicks a buttoni havemainpopupiframeloadfunction consolelogload the iframe the console would not show anything even if the iframe is loadedhtmlbutton idclickclick mebuttonthe iframe is created after the user clicks the buttoniframe idmainpopupiframe srchttp iframeany suggestionsby the way my iframe is created dynamically it doesnat load with the initial page load,"['javascript', 'jquery', 'html']" +341995,difference between func with delegate and lambda expression while deepening myself to more advanced features of c i came across some code which i did not exactly know the difference of it is about these two linesfuncstring int givelength text textlengthandfuncstring int givelength delegatestring text return textlength this can be used in the same wayconsolewritelinegivelengtha random stringso basically what is the difference of these two lines and are these lines compiling to the same cil,['c#'] +342010,iad banner is not working i am trying to get a banner in my app but since i added the banner the app would not starti get an error sayingterminating app due to uncaught exception nsinvalidunarchiveoperationexception reason could not instantiate class named adbannerviewcode in h fileimport iadiadhinterface firstviewcontroller uiviewcontroller adbannerviewdelegate adbannerview banner property nonatomicassign bool bannerisvisibleproperty nonatomicretain iboutlet adbannerview bannercode in m filesynthesize banner bannerisvisiblevoidbannerviewdidload adbannerview abanner ifselfbannerisvisible uiview beginanimationsanimatedadbanneron contextnull bannerframecgrectoffsetbannerframe 00 500 uiview commitanimations selfbannerisvisibleyes voidbannerviewadbannerview abanner ifselfbannerisvisible uiview beginanimationsanimatedadbanneroff contextnull bannerframecgrectoffsetbannerframe 00 3200 uiview commitanimations selfbannerisvisibleno what do you think is wrong,['ios'] +342018,make requirejs not reload jquery if already on page i am writing a script that is meant to be embedded on 3rd party sites to add functionality to them i recently ripped out my rather messy custom loader code and started replacing it with requirejs one of the libraries that optionally gets loaded for me depends on some parameters passed in is jquerythis works well until my script is included on a page that jquery is already on in which case what appears to happen is some plugins partway load requirejs loads jquery over the pages version and the plugins promptly breakasking clients to rewrite their pages just to use this script is out of the question so what i would like to do is detect if jquery is already loaded if it is skip loading it through requirejs and just use the already loaded one this will possibly open me up to odd edge cases and bugs when they are using a much older version of jquery but i do not have much choicewhat i thought i would do is write a new module that would first see if jquery is loaded if it is just export the jquery object if it is not then load it then do the export however i appear to be stymied as the definition function for the module appears to need to be synchronous to work so i cannot go off and load another script which would be asynchronous then stuff the export into requirejsam i missing something in the docs is what i am attempting impossible,['jquery'] +342024,how to implement scrollview in pythonkivy i have made some code to thisplay some content in pythonkivy and it seems i didnt write the scrollview goodi have tried some variations in the program but the program doesnt thisplay the scrollbarthis is my codedef buildself root boxlayoutorientationvertical box boxlayoutorientationvertical lists rss feed for lista in lists temp boxlayoutorientationvertical for entry in lista tempadd widgetlabeltextentry boxadd widgettemp sv scrollviewsize hinttrue true size400 400 rootadd widgetsv svadd widgetbox return rootmy question is what i need to do to thisplay scroolbarthanks,['python'] +342039,java processbuilder to start execute multiple commands sequentially in linux i would like to execute 2 or more commands sequentially through my java application using processbuilder class i have tried multiple options as suggested in other responsesforums but no luckhere are the things i have tried processbuilder processbuilder new processbuilderls pwdgives me following error errors ls no such file or directoryerrors ls pwd no such file or directory processbuilder processbuilder new processbuilderls pwdgives me similar errorerrors ls no such file or directoryerrors ls pwd no such file or directory liststring command new arrayliststring commandaddls commandadd commandaddpwd processbuilder processbuilder new processbuildercommandgives me following errorerrors ls no such file or directoryerrors ls pwd no such file or directorymy os is linuxmacosx,['java'] +342065,selectbox thisabled or enabled by an option of an other selectbox i try to create a relationconnexion beetwen 2 selectboxform idcreation namecreationselect nameselect01 idselect01 option value0101option option value0202option option value0303optionselectselect nameselect02 idselect02 option valueaoption option valueboption option valuecoptionselectformi want that my selectbox select02 be thisabled at the begening and when i click on value02 or value03 we enable it and when we click on value01 thisable itthere is my code js for the moment i try to adapt it from an other function radiobutton enabling a selectbox but it does not seem to work my list is thisable at the beging but the onclick is not working some body can help mevar oui documentcreationselect010documentgetelementbyidselect02thisabledtrueouionclick function documentgetelementbyidselect02thisabledfalseok so now i am with this codescriptvar oui documentselect01documentgetelementbyidselect02 thisabledtrueouionchange functiondocumentgetelementbyidselect02 thisabledfalsescripti change the value of my selec01 then my select02 is now enable but how can i target only 2 options of my select01,"['javascript', 'html']" +342068,javascript editor plugin for eclipse is there an eclipse plugin available for javascript that allows for syntax checking and autosuggestions for js files in eclipse,['javascript'] +342077,emulating a java enum in c i have been porting an application that i wrote some time ago from java over to c one thing that i quickly realized was that javas rich enums which were introduced in java 5 were far superior to those provided in c c0x and later c11s strongly typed enums aka enum classes still do not provide the richness that java enums provide and i could not find anything to emulate this facility here i set out to try to emulate some of the features as stand along classes and i would like some help to implement this perhaps using templates if appropriate it just seems like there should be a more generic way to implement this you will see that the ability to look up a particular enum through a string name is rather verbosely implemented this is an emulation of the java enums valueofstring str method it works but i am sure that it is far from optimal the way i have implemented the enum instances are using static const instances of within the class i found this somewhere on stack overflow but i cannot recall exactly where sorryfyi the the application is an nmea string parser and here are a few of the more interesting enum classeshere is the headerifndef nmeasentence h define nmeasentence h system includesinclude stdinthinclude string application includes defines macros external functions external variables constants structs typedefs forward declarations name nmeasentence class nmeasentencepublic static const int max len static const char start static const char cksm delim static const char cr static const char lf nmeasentence const stdstring rprefix const stdstring rparams mprefixrprefix mparamsrparams make the class abstract virtual nmeasentence 0protected stdstring mprefix stdstring mparamsendif nmeasentence h here is the cpp system includes application includesinclude vcdunmeasentenceh external functions external variables constants static variable initializationsconst int nmeasentencemax len 82const char nmeasentencestart const char nmeasentencecksm delim const char cr rconst char lf n implementation of the pure virtual dtor allowed its a trick to allow class to be abstractnmeasentencenmeasentencehere is a subclass of the generic nmeasentence class ifndef cdumessage h define cdumessage h system includesinclude application includesinclude vcdunmeasentencehinclude vcducduenumconstantsh defines macros external functions external variables constants structs typedefs forward declarations cdumessage class cdumessage public nmeasentencepublic 5 classifications of message types the type specifies the number and type of each parameter typedef enum cdumessagesubtype alive thisplay xythisplay status keyboard configuration cdumessagesubtype enumeration of the supported message types their arg count static class cdumessagetype public static const cdumessagetype cdualive the following 3 messages are associated with the title line static const cdumessagetype cduthisplaydatastatusblock static const cdumessagetype cduthisplaytitle static const cdumessagetype cduthisplaypagenumber these messages are associated with the active thisplay area static const cdumessagetype cduthisplayscratchpad static const cdumessagetype cduthisplayls1text static const cdumessagetype cduthisplayls2text static const cdumessagetype cduthisplayls3text static const cdumessagetype cduthisplayls4text static const cdumessagetype cduthisplayls5text static const cdumessagetype cduthisplayls6text static const cdumessagetype cduthisplayls1stext static const cdumessagetype cduthisplayls2stext static const cdumessagetype cduthisplayls3stext static const cdumessagetype cduthisplayls4stext static const cdumessagetype cduthisplayls5stext static const cdumessagetype cduthisplayls6stext static const cdumessagetype cduthisplayrs1text static const cdumessagetype cduthisplayrs2text static const cdumessagetype cduthisplayrs3text static const cdumessagetype cduthisplayrs4text static const cdumessagetype cduthisplayrs5text static const cdumessagetype cduthisplayrs6text static const cdumessagetype cduthisplayrs1stext static const cdumessagetype cduthisplayrs2stext static const cdumessagetype cduthisplayrs3stext static const cdumessagetype cduthisplayrs4stext static const cdumessagetype cduthisplayrs5stext static const cdumessagetype cduthisplayrs6stext this is a special message to clear the screen buffer static const cdumessagetype cduthisplaycls static const cdumessagetype cduthisplayputstring static const cdumessagetype cdustatus static const cdumessagetype cdukeyboard static const cdumessagetype cduset static const cdumessagetype cduget inline stdstring getprefix const return mprefix inline cdumessagesubtype getmesagesubtype const return msubtype inline virtual int gettextrowindex const return mtextrowindex inline justifystyle getjustifystyle const return mjustifystyle static stdvectorcdumessagetype getvalues static stdvectorcdumessagetype gvalues if gvaluesempty gvaluespush backcdualive gvaluespush backcduthisplaydatastatusblock gvaluespush backcduthisplaytitle gvaluespush backcduthisplaypagenumber gvaluespush backcduthisplayscratchpad gvaluespush backcduthisplayls1text gvaluespush backcduthisplayls2text gvaluespush backcduthisplayls3text gvaluespush backcduthisplayls4text gvaluespush backcduthisplayls5text gvaluespush backcduthisplayls6text gvaluespush backcduthisplayls1stext gvaluespush backcduthisplayls2stext gvaluespush backcduthisplayls3stext gvaluespush backcduthisplayls4stext gvaluespush backcduthisplayls5stext gvaluespush backcduthisplayls6stext gvaluespush backcduthisplayrs1text gvaluespush backcduthisplayrs2text gvaluespush backcduthisplayrs3text gvaluespush backcduthisplayrs4text gvaluespush backcduthisplayrs5text gvaluespush backcduthisplayrs6text gvaluespush backcduthisplayrs1stext gvaluespush backcduthisplayrs2stext gvaluespush backcduthisplayrs3stext gvaluespush backcduthisplayrs4stext gvaluespush backcduthisplayrs5stext gvaluespush backcduthisplayrs6stext gvaluespush backcduthisplaycls gvaluespush backcduthisplayputstring gvaluespush backcdustatus gvaluespush backcdukeyboard gvaluespush backcduset gvaluespush backcduget return gvalues private cdumessagetypeconst stdstring rprefix const cdumessagesubtype rsubtype const justifystyle rjustifystyle const int rtextrowindex mprefix rprefix msubtype rsubtype mjustifystylerjustifystyle mtextrowindexrtextrowindex stdstring mprefix cdumessagesubtype msubtype justifystyle mjustifystyle int mtextrowindex cdumessagetype getmessagetype const return mmessagetype virtual cdumessageprotected alternative simplified constructor param amessagetype param aparams cdumessageconst cdumessagetype rmessagetype const stdstring rparams nmeasentence rmessagetypegetprefix rparams mmessagetype rmessagetype cdumessagetype mmessagetypeendif cdumessage h and the corresponding cpp system includesinclude application includesinclude vcducdumessageh external functions external variables constants static variable initializations this is the heartbeat message not associated with any line 1 for last paramterconst cdumessagecdumessagetype cdumessagecdumessagetypecdualive pcdualive cdumessagealive justifystyleleft 1 the following 3 messages are associated with the title lineconst cdumessagecdumessagetype cdumessagecdumessagetypecduthisplaydatastatusblockpcdudsb cdumessagethisplay justifystyleleft 0const cdumessagecdumessagetype cdumessagecdumessagetypecduthisplaytitlepcdutit cdumessagethisplay justifystylecenter 0const cdumessagecdumessagetype cdumessagecdumessagetypecduthisplaypagenumberpcdupge cdumessagethisplay justifystyleright 0 these messages are associated with the active thisplay areaconst cdumessagecdumessagetype cdumessagecdumessagetypecduthisplayscratchpadpcduspd cdumessagethisplay justifystyleleft 13const cdumessagecdumessagetype cdumessagecdumessagetypecduthisplayls1textpcdul1t cdumessagethisplay justifystyleleft 2const cdumessagecdumessagetype cdumessagecdumessagetypecduthisplayls2textpcdul2t cdumessagethisplay justifystyleleft 4const cdumessagecdumessagetype cdumessagecdumessagetypecduthisplayls3textpcdul3t cdumessagethisplay justifystyleleft 6const cdumessagecdumessagetype cdumessagecdumessagetypecduthisplayls4textpcdul4t cdumessagethisplay justifystyleleft 8const cdumessagecdumessagetype cdumessagecdumessagetypecduthisplayls5textpcdul5t cdumessagethisplay justifystyleleft 10const cdumessagecdumessagetype cdumessagecdumessagetypecduthisplayls6textpcdul6t cdumessagethisplay justifystyleleft 12const cdumessagecdumessagetype cdumessagecdumessagetypecduthisplayls1stextpcdul1s cdumessagethisplay justifystyleleft 1const cdumessagecdumessagetype cdumessagecdumessagetypecduthisplayls2stextpcdul2s cdumessagethisplay justifystyleleft 3const cdumessagecdumessagetype cdumessagecdumessagetypecduthisplayls3stextpcdul3s cdumessagethisplay justifystyleleft 5const cdumessagecdumessagetype cdumessagecdumessagetypecduthisplayls4stextpcdul4s cdumessagethisplay justifystyleleft 7const cdumessagecdumessagetype cdumessagecdumessagetypecduthisplayls5stextpcdul5s cdumessagethisplay justifystyleleft 9const cdumessagecdumessagetype cdumessagecdumessagetypecduthisplayls6stextpcdul6s cdumessagethisplay justifystyleleft 11const cdumessagecdumessagetype cdumessagecdumessagetypecduthisplayrs1textpcdur1t cdumessagethisplay justifystyleright 2const cdumessagecdumessagetype cdumessagecdumessagetypecduthisplayrs2textpcdur2t cdumessagethisplay justifystyleright 4const cdumessagecdumessagetype cdumessagecdumessagetypecduthisplayrs3textpcdur3t cdumessagethisplay justifystyleright 6const cdumessagecdumessagetype cdumessagecdumessagetypecduthisplayrs4textpcdur4t cdumessagethisplay justifystyleright 8const cdumessagecdumessagetype cdumessagecdumessagetypecduthisplayrs5textpcdur5t cdumessagethisplay justifystyleright 10const cdumessagecdumessagetype cdumessagecdumessagetypecduthisplayrs6textpcdur6t cdumessagethisplay justifystyleright 12const cdumessagecdumessagetype cdumessagecdumessagetypecduthisplayrs1stextpcdur1s cdumessagethisplay justifystyleright 1const cdumessagecdumessagetype cdumessagecdumessagetypecduthisplayrs2stextpcdur2s cdumessagethisplay justifystyleright 3const cdumessagecdumessagetype cdumessagecdumessagetypecduthisplayrs3stextpcdur3s cdumessagethisplay justifystyleright 5const cdumessagecdumessagetype cdumessagecdumessagetypecduthisplayrs4stextpcdur4s cdumessagethisplay justifystyleright 7const cdumessagecdumessagetype cdumessagecdumessagetypecduthisplayrs5stextpcdur5s cdumessagethisplay justifystyleright 9const cdumessagecdumessagetype cdumessagecdumessagetypecduthisplayrs6stextpcdur6s cdumessagethisplay justifystyleright 11 these messages are not associated with a paricular line which is why we specify 1 for the last parameterconst cdumessagecdumessagetype cdumessagecdumessagetypecduthisplayclspcducls cdumessagethisplay justifystyleleft 1const cdumessagecdumessagetype cdumessagecdumessagetypecduthisplayputstringpcduputs cdumessagexythisplay justifystylenone 1const cdumessagecdumessagetype cdumessagecdumessagetypecdustatuspcdusid cdumessagestatus justifystyleleft 1const cdumessagecdumessagetype cdumessagecdumessagetypecdukeyboardpcdukey cdumessagekeyboard justifystyleleft 1const cdumessagecdumessagetype cdumessagecdumessagetypecdusetpcdusetv cdumessageconfiguration justifystyleleft 1const cdumessagecdumessagetype cdumessagecdumessagetypecdugetpcdugetv cdumessageconfiguration justifystyleleft 1and just to show the general pattern of how the enums are used here we have some other enum c classes that i needed to use throughout the application they all look pretty similar and i cannot help but feel that there must be an easier less verbose way of implementing this any help or ideas would be really welcomeclass justifystyle public static const justifystyle left center right none inline stdstring getname const return mname private justifystyleconst stdstring rname mnamername stdstring mnameclass fontsize public static const fontsize f1 f2 f3 f4 f5 f6 inline stdstring getname const return mname static stdvectorfontsize getvalues static stdvectorfontsize gvalues if gvaluesempty gvaluespush backf1 gvaluespush backf2 gvaluespush backf3 gvaluespush backf4 gvaluespush backf5 gvaluespush backf6 return gvalues private fontsizeconst stdstring rname mnamername stdstring mnameclass fontstyle public static const fontstyle s b i u n inline stdstring getname const return mname static stdvectorfontstyle getvalues static stdvectorfontstyle gvalues if gvaluesempty gvaluespush backs gvaluespush backb gvaluespush backi gvaluespush backu gvaluespush backn return gvalues inline bool operatorconst fontstyle rhs const return mname rhsmname private fontstyleconst stdstring rname mnamername stdstring mnameclass fontcolor public static const fontcolor black cyan red yellow green magenta amber white inline int getvalue const return mvalue inline stdstring getvaluestr const return utlstringutilsintegertostringmvalue static stdvectorfontcolor getvalues static stdvectorfontcolor gvalues if gvaluesempty gvaluespush backblack gvaluespush backcyan gvaluespush backred gvaluespush backyellow gvaluespush backgreen gvaluespush backmagenta gvaluespush backamber gvaluespush backwhite return gvalues private constructor fontcolorconst int rvalue mvaluervalue int mvalueclass cdufontchar public constructor cdufontchar const char cduchar 0 const fontsize rsize fontsizef3 const stdsetfontstyle rstyles stdsetfontstyle const fontcolor rcolor fontcolorwhite mcduchar cduchar msize rsize mfontstylesrstyles mcolorrcolor inline char getcduchar const return mcduchar inline fontsize getsize const return msize inline stdsetfontstyle getstyles const return mfontstyles inline fontcolor getcolor const return mcolor private char mcduchar fontsize msize stdsetfontstyle mfontstyles fontcolor mcolor,"['java', 'c++']" +342133,tvs rp45 roll paper printing i have a receipt made using crystal reports where the page is 4 inch wide and the height should be dynamic i set the height to 2 inches because i do not know how to make it dynamic the printer is a tvs rp45 justbill printerthe printer is ejecting paper after printing how do i stop this from happeningany solution besides crystal reports would be helpful the program is written in c net 20 winforms and connects to a sql server 2005 databasereport header section bill no 101 detail sectionitem code qty amountitemcode qty amount report footer sectiongrand total grandtotal the report footer section is using around 2 inches so i set the height of the paper to 2 inches this did not solve the problem the paper height is now 2 times what it should be if there is more than 1 itemthe printer uses roll paper and it should feed more paper proportionally with the number of items soldplease help me solve this without wasting paper,"['c#', 'sql']" +342140,how to check if a variable is both null and or undefined in javascript possible duplicatedetecting an undefined object property in javascripthow to determine if variable is undefined or null in my code i have a condition that looks likeif variable null variable undefined but instead of doing it in two steps ie checking if it is not defined and not null is there a one step checking that replaces this check,"['javascript', 'jquery']" +342182,apply bootstraps tr hover effect to a div i am using bootstrap for my css themes the themes are compiled and saved into the database for use later on this means that the pages only have access to the compiled css and not the less filesgiven that how can i apply bootstrapas trhover effect to various divs i need the color to be the same as what is defined for trhover and i canat use less variablesbootstraps styletable tbody trhover tdtable tbody trhover th backgroundcolor f5f5f5is it possible to define a css element based on another one that is assigned to a tr is there a way to grab the style using jqueryany suggestions,['css'] +342193,ie 9 compresses white space within xml dom i have a javascript routine that grabs an xml stream via ajax and then parses it it works fine in ff and chrome but in ie 9 if there are consecutive line feeds within a node ie compresses them into a space and one line feedspecifically where retnode is an xml node retnodetext has the compressed white space in ie but includes all the characters in ff and chromei have tried writing my own routine to parse the xml but that seems fragile and a waste of time i tried using the preservewhitespace property but that does not seem to be available in javascript i tried using retnodenodevalue instead of retnodetext but nodevalue had no valuei would prefer a solution that does not use jquery because i do not know jquery and i am not sure what other code i would need to add to make jquery workthanks in advance,['javascript'] +342200,does python use linked lists for lists why is inserting slow just learning python reading through the official tutorials i ran across thiswhile appends and pops from the end of list are fast doing inserts or pops from the beginning of a list is slow because all of the other elements have to be shifted by onei would have guessed that a mature language like python would have all sorts of optimizations so why does not python seem to use linked lists so that inserts can be fast,['python'] +342214,argumentdependent lookup in c how does this work is it related to adlinclude iostreamtemplate typename tstruct a friend void ft x stdcout an int main fnew avoidcan somebody tell me why i cannot use something likefaint,['c++'] +342286,clientspeers communication with wifidirect on android platform i have three android devices aband c they are connected via wifidirect assuming b is the group owneri just have two questions1 a want send a message to c does the message have to pass the group owner b to reach c2 if the group owner b accidentally thisconnected will a still be able to send messages to cthanks,['android'] +342295,does my unit test care about too much i have 2 concerns about my unit test methoddo i test too much in one test methodhow can my test method name reflect all test expectationsi asked myself when my method name says returninvalidmodelstate then my 2 other asserts are not correct at least concerning the method nametestpublic void create templatealreadyexists returninvalidmodelstate arrange templateviewmodel templateviewmodel new templateviewmodel name mytest mockitemplatedataprovider mock1 new mockitemplatedataprovider mockimappingengine mock2 new mockimappingengine templatecontroller controller new templatecontrollermock1object mock2object mock1setupm mtemplateexistsmytestreturnstrue set modelstateisvalid to false controllermodelstateaddmodelerrorname this name already exists act actionresult result controllercreatetemplateviewmodel assert assertisfalsecontrollermodelstateisvalid assertisinstanceoftypetypeofpartialviewresult result assertareequaltemplateviewmodel partialviewresultresultmodelhttppostpublic actionresult createtemplateviewmodel templateviewmodel if modelstateisvalid templatedataprovidertemplateexiststemplateviewmodelname template template mappermaptemplateviewmodel templatetemplateviewmodel templatedataprovideraddtemplatetemplate return new jsonnetresultnew success true modelstateaddmodelerrorname this name already exists return partialviewtemplateviewmodel,['c#'] +342316,android fragment layout i have below error when create simple fragment example0905 075728570 eandroidruntime1138 caused by androidappfragmentinstantiationexception unable to instantiate fragment comexamplefragment onef one make sure class name exists is public and has an empty constructor that is public0905 085703058 eandroidruntime1477 fatal exception main0905 085703058 eandroidruntime1477 javalangruntimeexception unable to start activity componentinfocomexamplefragments onecomexamplefragments onemainactivity androidviewinflateexception binary xml file line 5 error inflating class fragment0905 085703058 eandroidruntime1477 at androidappactivitythreadperformlaunchactivityactivitythreadjava19560905 085703058 eandroidruntime1477 at androidappactivitythreadhandlelaunchactivityactivitythreadjava19810905 085703058 eandroidruntime1477 at androidappactivitythreadaccess600activitythreadjava1230905 085703058 eandroidruntime1477 at androidappactivitythreadhhandlemessageactivitythreadjava11470905 085703058 eandroidruntime1477 at androidoshandlerthispatchmessagehandlerjava990905 085703058 eandroidruntime1477 at androidoslooperlooplooperjava1370905 085703058 eandroidruntime1477 at androidappactivitythreadmainactivitythreadjava44240905 085703058 eandroidruntime1477 at javalangreflectmethodinvokenativenative method0905 085703058 eandroidruntime1477 at javalangreflectmethodinvokemethodjava5110905 085703058 eandroidruntime1477 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava7840905 085703058 eandroidruntime1477 at comandroidinternaloszygoteinitmainzygoteinitjava5510905 085703058 eandroidruntime1477 at dalviksystemnativestartmainnative method0905 085703058 eandroidruntime1477 caused by androidviewinflateexception binary xml file line 5 error inflating class fragment0905 085703058 eandroidruntime1477 at androidviewlayoutinflatercreateviewfromtaglayoutinflaterjava6970905 085703058 eandroidruntime1477 at androidviewlayoutinflaterrinflatelayoutinflaterjava7390905 085703058 eandroidruntime1477 at androidviewlayoutinflaterinflatelayoutinflaterjava4890905 085703058 eandroidruntime1477 at androidviewlayoutinflaterinflatelayoutinflaterjava3960905 085703058 eandroidruntime1477 at androidviewlayoutinflaterinflatelayoutinflaterjava3520905 085703058 eandroidruntime1477 at comandroidinternalpolicyimplphonewindowsetcontentviewphonewindowjava2510905 085703058 eandroidruntime1477 at androidappactivitysetcontentviewactivityjava18350905 085703058 eandroidruntime1477 at comexamplefragments onemainactivityoncreatemainactivityjava120905 085703058 eandroidruntime1477 at androidappactivityperformcreateactivityjava44650905 085703058 eandroidruntime1477 at androidappinstrumentationcallactivityoncreateinstrumentationjava10490905 085703058 eandroidruntime1477 at androidappactivitythreadperformlaunchactivityactivitythreadjava19200905 085703058 eandroidruntime1477 11 more0905 085703058 eandroidruntime1477 caused by androidsupportv4appfragmentinstantiationexception unable to instantiate fragment comexamplefragment onef one make sure class name exists is public and has an empty constructor that is public0905 085703058 eandroidruntime1477 at androidsupportv4appfragmentinstantiatefragmentjava3950905 085703058 eandroidruntime1477 at androidsupportv4appfragmentinstantiatefragmentjava3630905 085703058 eandroidruntime1477 at androidsupportv4appfragmentactivityoncreateviewfragmentactivityjava2640905 085703058 eandroidruntime1477 at androidviewlayoutinflatercreateviewfromtaglayoutinflaterjava6690905 085703058 eandroidruntime1477 21 more0905 085703058 eandroidruntime1477 caused by javalangclassnotfoundexception comexamplefragment onef one0905 085703058 eandroidruntime1477 at dalviksystembasedexclassloaderfindclassbasedexclassloaderjava610905 085703058 eandroidruntime1477 at javalangclassloaderloadclassclassloaderjava5010905 085703058 eandroidruntime1477 at javalangclassloaderloadclassclassloaderjava4610905 085703058 eandroidruntime1477 at androidsupportv4appfragmentinstantiatefragmentjava3850905 085703058 eandroidruntime1477 24 moremain activitypackage comexamplefragments oneimport androidosbundleimport androidsupportv4appfragmentactivityimport androidviewmenupublic class mainactivity extends fragmentactivity override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main override public boolean oncreateoptionsmenumenu menu getmenuinflaterinflatermenuactivity main menu return true activity mainxmllinearlayout xmlnsandroid androidlayout widthfill parent androidlayout heightfill parent fragment androidididf one androidnamecomexamplefragment onef one androidlayout width0px androidlayout heightmatch parent androidlayout weight1 fragment androidididf two androidnamecomexamplefragment onef two androidlayout width0px androidlayout heightmatch parent androidlayout weight1 linearlayoutfragment layouts 1f onexmlxml version10 encodingutf8linearlayout xmlnsandroid androidlayout widthfill parent androidlayout heightfill parent androidbackground00ff00 androidorientationvertical textview androidlayout widthfill parent androidlayout heightwrap content androidtextthis is fragment 1 androidtextcolor0 androidtextsize25sp linearlayoutf twoxmlxml version10 encodingutf8linearlayout xmlnsandroid androidlayout widthfill parent androidlayout heightfill parent androidbackgroundfe00 androidorientationvertical textview androidlayout widthfill parent androidlayout heightwrap content androidtextthis is fragment 2 androidtextcolor0 androidtextsize25sp linearlayoutmy fragment classpackage comexamplefragments oneimport androidappfragmentimport androidosbundleimport androidviewlayoutinflaterimport androidviewviewimport androidviewviewgrouppublic class f one extends fragment override public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate inflate the layout for this fragment return inflaterinflaterlayoutf one container false package comexamplefragments oneimport androidappfragmentimport androidosbundleimport androidviewlayoutinflaterimport androidviewviewimport androidviewviewgrouppublic class f two extends fragment override public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate inflate the layout for this fragment return inflaterinflaterlayoutf two container false,['android'] +342340,what is the difference between short int and int in c how is short int or short and int different in c they have the same size and range if they are essentially the same what is the use of having two data types,['c'] +342370,sending cookie with http post android hello guys i am trying to send a cookie with http post in androidheres my codeweburl x webview webview findviewbyidridwebview try cookiestore cookiestore new basiccookiestore cookie cookie new basicclientcookiesession id 1234 cookiestoreaddcookiecookie defaulthttpclient httpclient new defaulthttpclient basichttpcontext mhttpcontext new basichttpcontext mhttpcontextsetattributeclientcontextcookie store cookiestore httpget httpget new httpgetx httpresponse response httpclientexecutehttpget httpentity entity responsegetentity logitag login form get responsegetstatusline if entity null entityconsumecontent logitag initial set of cookies listcookie cookies httpclientgetcookiestoregetcookies if cookiesisempty logitag none else for int i 0 i cookiessize i logitag cookiesgetitostring httppost httpost new httppostx list namevaluepair nvps new arraylist namevaluepair nvpsaddnew basicnamevaluepairsession id 1234 nvpsaddnew basicnamevaluepairselected cid 1234 nvpsaddnew basicnamevaluepairselected kaisai id 1234 nvpsaddnew basicnamevaluepairiid 1234 nvpsaddnew basicnamevaluepairtid 1234 httpostsetentitynew urlencodedformentitynvps response httpclientexecutehttpost entity responsegetentity logitag login form get responsegetstatusline if entity null entityconsumecontent logitag post logon cookies cookies httpclientgetcookiestoregetcookies if cookiesisempty systemoutprintlnnone else for int i 0 i cookiessize i logitag cookiesgetitostring httpclientgetconnectionmanagershutdown catchexception e logitag egetmessage websettings websettings webviewgetsettings websettingssetjavascriptenabledtrue string postdata session id1234 webviewposturlweburl encodingutilsgetbytespostdata base64i can post the data from postdata but not the cookiethe cookie is not showed in the webviewheres the php sidepublic function cookietestaction echo mixi for netrecorder testerbrn echo brcookiesbrnn request new zend controller request http sessionid requestgetcookiesession id echo brnsessionid sessionidbrn selected cid requestgetcookieselected cid echo nselected cid selected cidbrn selected kaisai id requestgetcookieselected kaisai id echo nselected kaisai id selected kaisai idbrn iid requestgetcookieiid echo niid iidbrn tid requestgetcookietid echo ntid tidbrn ifthisgetrequestispost echo brpost data onlybrnn post thisgetrequestgetpostsession id echo brnsession idpostbrn post thisgetrequestgetpostselected cid echo selected cidpostbrn post thisgetrequestgetpostselected kaisai id echo selected kaisai idpostbrn post thisgetrequestgetposttid echo tidpostbrn post thisgetrequestgetpostiid echo iidpostbrn can anyone tell me whats wrongthank you,['android'] +342380,how does it work with bean validation messages and i18n in jsf2 i created validation messagesvalidationmessagesproperties file to make the i18n possible in my projectit looks likepwtnumbererrorpwt number error i defined it in facesconfigxmlmessagebundlecommycompanywebi18nvalidationmessagesmessagebundlein my code i used it in this way nullmessage pwtnumbererror public string getpwtnummer return pwtnummer but the problem is i do not get the error message but the key from the properties file it is the error message that i getmyformpwtnummer pwtnumbererrorhow can i solve it,['java'] +342383,how to customize fbloginview in order to connect to facebook in my ios app i am using fbloginview from facebook sdk for iosit shows a nice fb login button but i want to use my own image and text for the login buttonthe problem is that i do not see anywhere how to customize thati have managed to change the login button background image by overriding the images in facebooksdkresourcesbundlefbloginviewimages but i could not find where to change the login button text and position so it is stays log insolution anyonethank you,"['objective-c', 'ios']" +342385,typeerror ocolumn is undefined when using jquery datatables library i am having a problem getting the jquery datatables library to show up properly on my joomla website tablethe script is half styling my table and then giving up i am getting the table header colour changed and text colour but no datatables controls etcfirebug is also throwing the following error typeerror ocolumn is undefinedin my joomla templates indexphp i have the following in the headscript srcdatatablesjsjqueryjs typetextjavascriptscriptscript srcdatatablesjsjquerydatatablesjs typetextjavascriptscriptscript typetextjavascript jquerynoconflict jquerydocumentreadyfunction jquerystaff tabledatatable blengthchange true bfilter true bsort true binfo true bautowidth true scriptthe html php looks like thish3members of staffh3pif youre looking for a member of staff at tower road academy youll find their details hereptable clastaff table idstaff table tr clastaff table head thnameth thjob titleth themail addressth tr php result mysql queryselect from itsnb chronoforms data addstaffmember whilerow mysql fetch arrayresult echo tr echo td rowstaff name tdtd rowstaff job tdtda hrefmailto rowstaff email rowstaff email a td echo tr table,"['php', 'jquery', 'html']" +342409,android debugger error monodroid i am developping an android app in visual studio 2010 with monodroid i am already pretty far and was able to run and debug my app on the emulator aswell as a android device for some reason my visual studio is not debugging the app properly to my device anymore the error i sometimes get ismicrosoft visual studiothe application could not be started ensure that the application has been installed to the target device and has a launchable activity mainlauncher trueadditionally check buildconfiguration manager to ensure this project is set to deploy for this configurationokall of the solutions above i have already checkedother times there is no error at all and visual studio just stops running or the app starts fine but visual studio is non responsive the error just started recently while almost nothing has changed on the application i was hoping someone had this error before and knew if it was because of some property setting or somethingps i also believe it could be caused by my camera i use it in my app and when my app decides to deploy 1 in 5 times it crashed on the camera screen heres the cameracode private void createcameraisurfaceholder holder try if holder null camera androidhardwarecameraopen androidhardwarecameraparameters p cameragetparameters ppictureformat imageformattypejpeg camerasetparametersp camerasetthisplayorientation90 camerasetpreviewcallbackthis cameralock camerasetpreviewthisplayholder camerastartpreview if packagemanagerhassystemfeatureandroidhardwarecameraautofocus cameraautofocusthis catch systemexception e androidutillogdebugsimplecamera emessage systemconsolewritelineemessage,['android'] +342436,android how to calculate network usage packetdata now a days internet access is very costlythe provider used charges like hellwe do not use unlimited plan for internetthat is why i would like to develop an that can facilities to calculatemanage network packagedata usagesuppose i have activated 5gb data planso i need to check before surfing netuploaddownload thingsi know some data provider provides these facility i want to capture network data packets on my android device by my app but how can i do that into my own codeany help will be appreciatedthank you advance,"['java', 'android']" +342453,serializing a decimal to json how to round off i have a classpublic class money public string currency get set public decimal amount get set and would like to serialize it to json if i use the javascriptserializer i getcurrencyusdamount100310because of the api i have to conform to needs json amounts with maximum two decimal places i feel it should be possible to somehow alter the way the javascriptserializer serializes a decimal field but i cannot find out how there is the simpletyperesolver you can pass in the constructor but it only work on types as far as i can understand the javascriptconverter which you can add through registerconverters seems to be made for dictionaryi would like to getcurrencyusdamount10031after i serialize also changing to double is out of the question and i probably need to do some rounding 100311 should become 10031 does anyone know how to do this is there perhaps an alternative to the javascriptserializer that lets you control the serializing in more detail,['c#'] +342492,php code to exclude indexphp using glob problemi am trying to thisplay a random page from a file called health in this file there is a indexphp file and 118 other files named php filesi would like to randomly thisplay a file from the health folder but i would like it to exclude the indexphp filethis following code includes the indexphp file sometimesi have also tried altering the exclude line to show healthindexphp but still no luckphpexclude arrayindexphp can add more here lateranswer array diffglobhealthphpexcludewhatanswer answermt rand0 countanswer 1include whatansweranother code i have tried is the followingphpexclude arrayhealthindexphp can add more here laterhealth globhealthphpforeach health as key filename foreach exclude as x if strstrfilename x unsetwhathealthkeywhathealth healthmt rand0 counthealth 1include whathealththis code also includes the indexphp file but rather than showing the page it thisplays the page as an error,['php'] +342523,why does sitecore publish draft items from the c api and how do i stop it doing so i am running a scheduled publish of my sitecore master db using the sitecore publishing api i call a web service at scheduled intervals during the day which runs the following code slightly condensed for readability grab the root content node from sitecoreitem contentnode dbsourceitemsidparse0de95ae441ab4d019eb067441b7c2450publishoptions options new publishoptionssourcedatabase targetdatabase publishmodesmart lang datetimenowoptionsrootitem contentnodeoptionsdeep truepublisher p new publisheroptionsppublishasyncwhen we run the above code it publishes everything in the content node including all descendants regardless of workflow state it is like it is ignoring the workflow completely this is not what we are after and is causing lots of problems on our live websiteif we run the same action from within sitecore desktop it publishes everything in the content node including all descendants that are publishable ie in the final workflow stage it does not publish any items in the tree that are still in draft mode this is the required bahaviouri have tried implementing the code as a nonadmin user by surrounding the above code with the following using statementstring username sitecoresitecoresecurityaccountsuser user sitecoresecurityaccountsuserfromnameusername trueuserruntimesettingsisadministrator falseusing new sitecoresecurityaccountsuserswitcheruser unfortunately this has had no effectis there something obvious i have missed or am i doing it right and sitecore is doing it wrong can anyone help pleasethe strange thing i noticed also is that the draft items that were published when viewed on the live database were showing absolutely nothing in the sitecore desktop in terms of fields or meta data they were also showing a warning that the current item does not have a version in english english,['c#'] +342604,how do i check for user role in symfony2 for urls not falling under patterns defined securityyml i have a admin panel and i have defined a role for it role admin in my securityyml file i am using a pattern admin so every thing under admin requires role admin now in frontend of my app i need to check user role and if role is role admin render one file and otherwise render another file this url does not fall under the pattern defined in securityymlso how do i check whether the user is admin or a normal user on the homepage which does not fall under the pattern defined in securityyml,['php'] +342626,c linux binary terminated with signal sigkill why loaded in gdb so i fire up my c application in gdb and when it quits i basically getthread 0x7f76e07700 lwp 6170 exitedthread 0x7f76f08700 lwp 6169 exitedthread 0x7f77009700 lwp 6168 exited program terminated with signal sigkill killed the program no longer existsgdbi literally have no idea why this is occuring why cannot i do a backtrace to see how it exited anyone have any ideas it should never end thanks,['c++'] +342630,pypy memory usage grows forever i have a complicated python server app that runs constantly all the time below is a very simplified version of it when i run the below app using python python mainpy it uses 8mb of ram straight away and stays at 8mb of ram as it should when i run it using pypy pypy mainpy it begins by using 22mb of ram and over time the ram usage grows after a 30 seconds its at 50mb after an hour its at 60mb if i change the bsomething to be pass it does not gobble up memory like that i am using pypy 19 on osx 1074i am okay with pypy using more ram than python is there a way to stop pypy from eating up memory over long periods of timeimport sysimport timeimport tracebackclass boxobject def init self selfcounter 0 def somethingself selfcounter 1 if selfcounter 100 selfcounter 0try print starting boxes for i in range10 boxesappendbox print running while true for b in boxes bsomething timesleep002except keyboardinterrupt print print print keyboardinterrupt exception sysexit1except exception as e print print print main level exception s e print tracebackformat exc sysexit1below is a list of times and the ram usage at that time i left it running over night wed sep 5 225754 2012 22mb ram wed sep 5 225754 2012 23mb ram wed sep 5 225756 2012 24mb ram wed sep 5 225756 2012 25mb ram wed sep 5 225758 2012 26mb ram wed sep 5 225758 2012 27mb ram wed sep 5 225759 2012 29mb ram wed sep 5 225759 2012 30mb ram wed sep 5 225800 2012 31mb ram wed sep 5 225802 2012 32mb ram wed sep 5 225803 2012 33mb ram wed sep 5 225805 2012 34mb ram wed sep 5 225808 2012 35mb ram wed sep 5 225810 2012 36mb ram wed sep 5 225812 2012 38mb ram wed sep 5 225813 2012 39mb ram wed sep 5 225816 2012 40mb ram wed sep 5 225819 2012 41mb ram wed sep 5 225821 2012 42mb ram wed sep 5 225823 2012 43mb ram wed sep 5 225826 2012 44mb ram wed sep 5 225828 2012 45mb ram wed sep 5 225831 2012 46mb ram wed sep 5 225833 2012 47mb ram wed sep 5 225835 2012 49mb ram wed sep 5 225835 2012 50mb ram wed sep 5 225836 2012 51mb ram wed sep 5 225836 2012 52mb ram wed sep 5 225837 2012 54mb ram wed sep 5 225941 2012 55mb ram wed sep 5 225945 2012 56mb ram wed sep 5 225945 2012 57mb ram wed sep 5 230058 2012 58mb ram wed sep 5 230220 2012 59mb ram wed sep 5 230220 2012 60mb ram wed sep 5 230227 2012 61mb ram thu sep 6 001800 2012 62mb ram,['python'] +342657,generate all combinations for pair of bits set to 1 i am trying to generate all possible combinations for pair of 1s within given bit widthlet us say the bit width is 6 ie number 32 this is what i would like to generate011011011010110110110101101100101101001if i have variablesvar a 1 b 2 num a band create a loop that i will loop over width 1 times and where i shift both a 1 and b 1 i will get all combinations for one pair after that i am pretty much stuckcould someone please provide some helpupdate working examplebased on barmars mathematical approach this is what i managed to implementvar arr arrbits function getcombspairs startidx var i j val 0 tmpval idx if startidx 2 pairs startidx arrlength 1 pairs 1 if pairs 2 return for i 0 i pairs1 i idx startidx i 2 val arridx for j 0 j idx 1 j arrbitspushval arrjtostring2 getcombspairs startidx1function initarrbits var i val pairs startidx for i 1 i bits i val i 1 3 val 2 arrpushval arrbitspushvaltostring2 pairs mathfloorbits 2 startidx arrlength 1 getcombspairs startidx consolelogarrbits9working example on jsfiddle,['javascript'] +342697,under what circumstances will the ctl00 prefix render as something else ex ctl01 i have inherited an application that contains a ton of javascript with hardcoded client idsin the past when i did load testing i seem to remember that sometimes the generated client id would start with ctl01under what circumstances will this occur,['asp.net'] +342704,how to cause c throw to dump core if the exception would be handled by a particular catch block is there a way to cause a throw in c to dump core at the throw site if the thrown exception would be handled by a certain catch block i would like something similar to what happens with g when an exception reaches the top levelfor example i would like something like thistry bar try foo catch pragma dump at throw site catch stdcerr there was a problem stdendlthis way if any exception thrown from foo or its callees that reaches the callsite of foo would cause a core dump at the throw site so one can see who threw the exception that made it to the to this levelon the other hand exceptions thrown by bar would be handled normally,['c++'] +342731,jquery deferred changes this i am attempting to have a javascript object run a deferred method and when it is done call a function in that same object i am having issues because this becomes the deferred object instead of the object that called itpageobjectprototypesuccessfunction function consolelogarguments return consolelogthisname success function calledpageobjectprototypeloadpage functionurl return whenmobileloadpagepages url donethissuccessfunctionvar pg new pageobjectpgloadpagetesthtmlhow do i send this into the successfunction this pageobject is going to be extended by others as well so knowing this when running successfunction will be very handyit seems simple and probably has a simple answer i was looking into apply but i am not sure it helped this post on stack overflow was helpful a little bit but it broke the minute i put it into the done functionfunctions as parameters with parameters javasript,"['javascript', 'jquery']" +342734,connection pooling and prepared statements with groovysqlsql or jdbc in grails after running into this question today grails query not using gorm i wonder if using groovysqlsql or jdbc comes with the benefits of connection poolingi can see under some circumstances how going gormless could be beneficial but lack of conn pooling would eliminate it as an optionwould we also get the benefits of prepared statements,['sql'] +342738,import cv2 works but import cv2cv as cv not working i think the sys path is correct cvpyd and cvpyd reside in copencv23buildpython27libsitepackages import sys syspath cpython27libidlelib cpython27libsitepackagespil117py27win32egg cpython27libsitepackagescython017py27win32egg cpython27libsitepackagespip12py27egg copencv23buildpython27libsitepackages cpython27python27zip cpython27dlls cpython27lib cpython27libplatwin cpython27liblibtk cpython27 cpython27libsitepackages cpython27libsitepackagesipythonextensionsand import cv or cv2 seems to be ok but import cv2cv not import cv import cv2cv as cvtraceback most recent call last file pyshell4 line 1 in module import cv2cv as cvimporterror no module named cv import cv2 cvnamedwindowcamera 1what could be the reason of the importerror,['python'] +342775,jquery inarray is not working with ascii characters as you can see in jsfiddle i have taken two black coins if i place a black coin on another black coin then it should show alert that cannot kill your own kind and place the coins in their previous positions but as you can see it is not working,"['jquery', 'html']" +342796,algorithm to get all possible string combinations from array up to certain length what is the best algorithm to get all possible string combinations from a given array with a minimum maximum length valuenote this adds complexity since the value is variable unlike the questions these are linked tofor exampleletters arrayabc123min length 1max length 4abc123a123b123c123,['php'] +342914,how to remove default chrome style for select input how do i remove the default yellow box border of selected input and select fields in chrome or any browser like safarii want to customize input with custom box shadow css how do i remove the default browser select border,"['html', 'css']" +342918,server sent events work but with a massive time delay ill start off by saying this works perfectly on my local machine the js example below connects to streamphp and receives a continuous update of the servers current time every secondindexphpvar source new eventsourcestreamphpsourceaddeventlistenermessage functione consoleloge falsesourceaddeventlisteneropen functione consoleloge falsesourceaddeventlistenererror functione if ereadystate eventsourceclosed consolelogclosed falsestreamphpwhiletrue headers must be processed line by line headercontenttype texteventstream headercachecontrol nocache set data line print data date ghs time php eol php eol toilet flush wait one second sleep1i did expect a bit of a delay after uploading to the live dev server but there is a time delay of about 15 to 20 min before i even see the first entry the connection does not drop prob been going 40 min now is this just an apache looping problem means it time to look at web sockets or is there something i can do to fix this,['php'] +342951,is it bad practice to comment out single lines of css with i have recently started using to comment out single lines of css code i understand that i am not actually commenting out the line i am just breaking it i should use but it has the same effect the line is then terminated by the and the following code works finei could delete it but often i prefer not to in case i want to put it back in later or see what i had been using if i come back to itexampleli floatleft liststyletypenone textindent0pxcan i get away with this or is it likely to cause me problems,['css'] +343020,how to get the actionbar height i am trying to get the height of the actionbar using sherlock every time an activity is created specially to handle configuration changes on rotation where the actionbar height might changefor this i use the method actionbargetheight which works only when the actionbar is shownwhen the first activity is created for the first time i can call getheight in the oncreateoptionsmenu callback but this method is not called afterso my question is when can i call getheight and be assured that it does not return 0or if it is not possible how can i set the height of the actionbar,['android'] +343022,javaxannotation nullable vs checkfornull what is the difference between the two both seem to mean that the value may be null and should be dealt with accordingly ie checked for nullupdatethe two annotations above are part of jsr305findbugs,['java'] +343043,track all outbound links in google analytics i have been using a script to track outbound links for a couple of months now the script works but in the report generated by google analytics many urls are having a trailing 80 default port number at their end read on for more detailsit is maybe important to mention that the website tracking these outbound links has a tremendous amount of outbound traffic multiply your fantasy by athe scripts purposeit tracks all outbound links and tag them as outbound links in google analyticsthe script is heavily commented and has a few instances of consolelog to help debugging these are kept commented outoutbound links show on ga alright undercontent events top events outbound links click on it report showing all urls clickedthe problemunder the outbound links report where i get all the links that were clicked i get 80 at the end of at least 23 of all links reported probably more ga treats and as different links separating them in the report that is of course not desiredworth mentioninglinks that end with 80 always have more hits than their equivalent without 80 anything from 40 to 60 more hitsthe wanted solutionmerge the links that end with 80 with those without it oravoid appending 80 to links if possiblebonus understand why we get links ending with 80 at allthe script outbound link tracking with google analytics requires jquery 17 or higher use live if using a lower versionfunction aonclickfunctione var url thisattrhref console logs shows the domain name of the link being clicked and the current window consolelogecurrenttargethost ecurrenttargethost consolelogwindowlocationhost windowlocationhost if the domains names are different it assumes it is an external link be careful with this if you use subdomains if ecurrenttargethost windowlocationhost consolelogexternal link click outbound link fires the google tracker code gat gettrackerbyname trackeventoutbound links ecurrenttargethost url 0 checks to see if the ctrl or command key is held down which could indicate the link is being opened in a new tab if emetakey ectrlkey consolelogctrl or meta key pressed var newtab true if it is not a new tab we need to delay the loading of the new link for a just a second in order to give the google track event time to fully fire if newtab consolelogdefault prevented epreventdefault consolelogloading link after brief timeout settimeoutdocumentlocation url 100 else consoleloginternal link click,"['javascript', 'jquery']" +343048,requirejs is there a way to achieve multiple base urls i want to use a separate domain as a javascript framework and it will create a base require config which i can augment from the appfooexamplecom mainjs libfoospecificjsframeworkexamplecom frameworkjs entry point libjqueryjs libetcoptimally i would like to be able to require libfoospecific andor libjquery and have the paths just resolve nicely but from what i have found there is no way to do this unless i use a specific path keyvalue for every js file in the framework at the moment i have got a custom plugin to load the given path with a different base url eg fwlibjquery though if i wanted to use the text plugin it would not work as plugin chaining is unsupported see for what i have currently got and also for a use caseis there a clean way to solve this or to achieve multiple base urls note i have also looked into multiple require instances though i do not think that would work as i would like the the app to be able to access the frameworks config,['javascript'] +343088,restricting file types in jquery file upload demo i am using jquery file upload demo for my next project with codeigniter can anyone tell me how do i achieve the following restricting upload file types to zip and rarrestricting file sizeclearing the list of uploaded files jquery file upload plugin thisplays the list of already uploaded fileshelp appreciated,['jquery'] +343101,django tutorial generic views attribute error i am at the last part of this tutorialfrom djangoconfurls import patterns include urlfrom djangoviewsgeneric import detailview listviewfrom pollsmodels import pollurlpatterns patterns urlr listviewas view querysetpollobjectsorder bypub date5 context object namelatest poll list template namepollsindexhtml urlrppkd detailviewas view modelpoll template namepollsdetailhtml urlrppkdresults detailviewas view modelpoll template namepollsresultshtml namepoll results urlrppoll iddvote pollsviewsvotethe listview works but when i visit a url with detailview i getattributeerror at polls2generic detail view detailview must be called with either an object pk or a slugrequest method getrequest url django version 141exception type attributeerrorexception value generic detail view detailview must be called with either an object pk or a slugexception location homeyasithcodingdjangodjangotutoriallibpython27sitepackagesdjangoviewsgenericdetailpy in get object line 46python executable homeyasithcodingdjangodjangotutorialbinpython2python version 273i am not sure what i am doing wrong any help would be appreciatededit add the main urlspyfrom djangoconfurls import patterns include urlfrom djangocontrib import adminadminautothiscoverurlpatterns patterns urlrpolls includepollsurls urlradmin includeadminsiteurls,['python'] +343105,razor view isauthenticated not working as expected i have created a simple mvc application that is using the net membership provider that is supplied with the new projecti am trying to get the tabs to show correctly i might not understand this right but heres my codedoctype htmlhtmlhead titleviewbagtitletitle link hrefurlcontentcontentsitecss relstylesheet typetextcss script srcurlcontentscriptsjquery151minjs typetextjavascriptscriptheadbody div classpage div idheader div idtitle h1suburban customer portalh1 div div idloginthisplay htmlpartial logonpartial div div idmenucontainer ul idmenu if requestisauthenticated lihtmlactionlinkchangepassword changepassword accountli else lihtmlactionlinklogon logon accountli lihtmlactionlinkregister register accountli lihtmlactionlinkcontactus contactus homeli ul div div div idmain renderbody div div idfooter div divbodyhtmlat this lineif requestisauthenticatedi am trying to show the right tabs pending on if they are already authenticated this is always coming out as truehow should i be doing this i apparently am not doing it the right waythanks again,['c#'] +343111,is bind peeking thisabled on thistributed queries i am having trouble optimizing an oracle query after an upgrade to oracle 11g and this problem is starting to drive me a little mad note this question has been now fully edited because i have more information after creating a simple test case the original question is available here this issue is that when joining two tables one of which has a between condition on a date column if the query joins to a remote table bind peeking does not happen here is a test case to help reproduce the problem first set up two source tables the first is a list of dates being the first of the month going back thirty yearscreate table mike temp etl controlas select add monthstruncsysdate mm 1row count as reporting datefrom select level as row count from dual connect by level 360then some data sourced from dba objectscreate table mike temp dba objects asselect owner object name subobject name object id createdfrom dba objectsunion allselect owner object name subobject name object id createdfrom dba objectsthen create an empty table to run the data in tocreate table mike temp 1asselect aowner aobject name asubobject name aobject id acreated breporting datefrom mike temp dba objects a join mike temp etl control b on breporting date between add monthsacreated 24 and acreated where 12then run the code you may need to create a larger version mike temp dba objects to slow the query down or use some other method to get the execution plan while the query is running i get an execution plan from the session by running select from tabledbms xplanthisplay cursorsql id x from a different sessiondeclare pv report start date date date 20020101 v report end date date date 20120701begin insert append into mike temp 5 select aowner aobject name asubobject name aobject id acreated breporting datefrom mike temp dba objects a join mike temp etl control b on breporting date between add monthsacreated 24 and acreated cross join dualemirrl this line causes problemswhere breporting date between add monthspv report start date 12 and v report end date rollback endby having a remote table in the query the cardinality estimate for the mike temp etl control table is completely wrong and bind peeking does not seem to be happening the execution plan for the query above is shown below id operation name rows bytes cost cpu 0 insert statement 373 100 1 load as select 2 filter 3 merge join 5 655 373 21 4 sort join 1096 130k 370 20 5 merge join cartesian 1096 130k 369 20 6 remote dual 1 2 0 7 buffer sort 1096 130k 367 20 8 table access full mike temp dba objects 1096 130k 367 20 9 filter 10 sort join 2 18 3 34 11 table access full mike temp etl control 2 18 2 0if i then replace the remote dual with the local version i get the correct cardinality 139 instead of 2 id operation name rows bytes cost cpu 0 insert statement 10682 100 1 load as select 2 filter 3 merge join 152k 19m 10682 3 4 sort join 438k 51m 10632 2 5 nested loops 438k 51m 369 20 6 fast dual 1 2 0 7 table access full mike temp dba objects 438k 51m 367 20 8 filter 9 sort join 139 1251 3 34 10 table access full mike temp etl control 139 1251 2 0so i guess the question is how can i get the correct cardinality to be estimated is this an oracle bug or is this the expected behaviour,['sql'] +343119,extjs get selected value of radio button in form not returning the value i have followed the basic procedures for obtaining the selected value of my radio button form xtype radiofield name timespan id timespan value 7 checked true fieldlabel time span boxlabel 7 days xtype radiofield name timespan value 30 fieldlabel labelseparator hideemptylabel false boxlabel 30 days xtype radiofield name timespan value 60 fieldlabel labelseparator hideemptylabel false boxlabel 60 days xtype radiofield name timespan value all fieldlabel labelseparator hideemptylabel false boxlabel all i have used methods likeextgetcmpfilter formgetformgetvaluestimespanbut when i run this to the console instead of getting the value of the selected button i get the word on what gives i have tried several different combos of getvalues getform etc but i always end up with on or true or false whats going on here,['javascript'] +343122,initializer element is not a compiletime constant why i have this code nsstring calculate uint position static nsarray localarray nsarray arraywitharray selfcontainerobjects some un related code return objthe compiler complains saying initializer element is not a compiletime constant it happened when i added static to localarray but why,"['objective-c', 'ios']" +343136,unique contact id does android assign unique constant ids to every contactif not is there a way to assign such information to themcould i sync this id to google contactsthanks,['android'] +343192,how to check if part of a string equals another string in android how do i check if part if one string is equal to anotherfor example if i have one string with the value of hello and a string with the value of he how can i compare them to check that hello contains heif that was not explained very well tell me and i will try to clear it up,['java'] +343229,what does it mean to leak a service connection i am writing a service for my android app and i am trying to understand how the binding mechanism worksif i bind my service in the oncreate of an activity but i do not unbind it in onstop or ondestroy i get the error androidappserviceconnectionleaked service comgoogleipcinvalidationticlandroidandroidinvalidationservice has leaked serviceconnection comgoogl eipcinvalidationexternalclientandroidserviceservicebinder14177f8f8 that was originally bound hereso my question is what is the problem exactly with leaking a connection what am i preventing by unbinding my service,['android'] +343247,visual studio c 2010 express debug running faster than release i have a windows forms application with exactly 2 threads these threads have zero interaction with each other ala the first thread runs without messing with the second thread there is no synchronization between them as there is no need for that to be happening the first thread deals with the ui of the application changing colors and labels and has one timer running to catch some user input this timer fires every 200 milliseconds the second thread is more involved and runs through its coding constantly until shutdown by the user by exiting the application the second thread first reads from memory and stores the data into a list then uses this data to make some calculations i have a stopwatch class timer to measure the time it takes to complete one iteration of the second thread this timer is reset and started at the very beginning of the thread and then stopped and printed to console once the thread has completed an iteration this is where i have been getting my performance data i have been allowing the thread to run for at least 10 iterations and then doing an average excluding the first run the debug version of the build that is the build that is run by the vshost or when one would hit f5 in visual studio c 2010 express the timings average in at 035s that is 035ms when the application is run outside of the vshost either by hitting ctrlf5 or by running the application from the exe that is produced when hitting build i have also used rebuild to test this with absolutely zero change the timings average in at 365s that is 365ms that is roughly 10x slower with the release build i am at a complete loss as to what is going on what is the vshost doing that is allowing the program to run so quickly i have made sure that all variable initialization is accounted for and correct that being said i have no clue why something like this would be happening any insight as to why i am getting such a performance dipas a side note the computer i am using is 64bit has a quad core i7 with hyper threading 16 gigabytes of ram and twin hd6750s so it does not seem to be an issue of having too many threads the only thing here that may be an issue is the hyper threadinga snippet of code in the form of what my application does however it is not possible to give working code as the memory address read is where the slow down occurs namespace test snippetpublic struct data public float x public float y public float z public float dx public float dy public dataint c thisx readfloatbase 0x50 c 0x10 thisy readfloatbase 0x50 c 0x10 thisz readfloatbase 0x50 c 0x10 if thisz 1 targetindex c thisdx 0 thisdy 0 class class1 public int base new int public listdata data new listdata public int targetindex new int public data targetdata new data public void getdata while true dataclear for int c 0 c 64 c data tempdata new data teampdata new datac dataaddtempdata if datacount 0 targetdata datatargetindex dataremoveattargetindex targetdatadx readfloatbase 0x66 targetdatady readfloatbase 0x65 data tempdatarray new datadatacount for int j 0 j tempdatarraylength j tempdatarrayjdx floatmathacostargetdatadx 10 tempdatarrayjdy floatmathacostargetdatady 10 edit i have tried the same procedure but without using threading i had the thread function called by the timer i was using to catch user input i am getting the same results so that means that threading does not seem to be the issue i have also done the test on a different computer and for some reason i am not getting the massive difference which leads me to believe there may be something wrong with my computer or something dealing with how my processor deals with threads due to its hyper threading ability anyone know if hyper threading causes issues with a multithreaded application that is not utilizing it explicitly from within the program which honestly i would not have a clue how to set up,['c#'] +343256,prism unsubscribe with subscription token not working i am subscribing and unsubscribing to prism events using the code below in classa the problem i am having is after i unsubscribe and another completely different class say classb with a different handler registers for the same event classa handler is still invoked why is thisi have tried both unsubscribing using a token as well as the method delegate used when registering both to no availsubscriptiontoken subscriptiontokenregister subscription handlervar pevent geteventaggregatorgeteventpricesubscriptionevent subscriptiontoken peventsubscriber datahandlerr return threadoptionbackgroundthread false nullunsubscribevar pevent geteventaggregatorgeteventpricesubscriptioneventpeventunsubscribe subscriptiontoken,"['c#', '.net']" +343276,css selector with period in id the html spec allows for periods in an idimg idsomeid however using a css id selector rule will not match correctlysomeid color f00 the css spec for id selectors does not mention this case so i assume it is using the combination of a tag name and class selector for example a css rule of aclassname would apply to all anchor tags a with a class name of classname like a classclassnameais it possible to have an external css file rule that references an html element by its id that has a period in iti expect not since the css spec specifies that a css identifier does not include the period as a valid character so is this a fundamental mismatch between html and css specs is my only alternative to use a different type of css selection can anyone smarter than i confirm or deny thisi would remove the period from the html id attribute to simplify things but it is a systemgenerated id so i do not have the ability to change it in this case,"['html', 'css']" +343305,custom uitableviewcell content not animated when hiding delete button i want to know what i am missing as my cell does not animate when hiding the delete button the label jumps back to the original position before the delete button finish animatingwhen i tap the round editing view to show the delete button the label animation workshowever when i tap it again to hide the delete button the movement of the label is not animatednote these screenshot are not created from the following code but they show the problem customize the appearance of table view cells uitableviewcell tableviewuitableview tableview cellforrowatindexpathnsindexpath indexpath static nsstring cellidentifier cell homecell cell tableview dequeuereusablecellwithidentifiercellidentifier if cell nil cell homecell alloc initwithstyleuitableviewcellstylesubtitle reuseidentifiercellidentifier set up the cell consumed drinkobj selfappdelegateconsumeddrinksarray objectatindexindexpathrow celltitlelabeltext drinkobjdrinkname nsstring detailtexttime nsdate stringfromdatedrinkobjdateconsumed withformathmma nsstring detailtextrelative relativedatetransformer transformedvaluedrinkobjdateconsumed nsstring detailtext nsstring stringwithformat detailtexttimedetailtextrelative celltimelabeltext detailtext cellstddlabeltext 90 nsstring stringwithformat drinkobjstandarddrinks cellstddlabelautoresizingmask uiviewautoresizingflexibleleftmargin uiviewautoresizingflexiblerightmargin celltitlelabelautoresizingmask uiviewautoresizingflexiblewidthuiviewautoresizingflexibleleftmargin uiviewautoresizingflexiblerightmargin celltimelabelautoresizingmask uiviewautoresizingflexiblewidthuiviewautoresizingflexibleleftmargin uiviewautoresizingflexiblerightmargin cellselectionstyle uitableviewcellselectionstylenone return cell,"['iphone', 'ios']" +343314,python error name admin is not defined i am creating a python application in django for the first time i know that i must uncomment the admin tools in the urlspy i have done that i have also added autothiscover everytime i try to add a new feature to the administration panel i get this error nameerror name admin is not definedhere is the code i am using in my model to add to the admin panelclass choiceinlineadminstackedinline model choice extra 3 class polladminadminmodeladmin fieldsets none fields question date information fields pub date classes collapse inlines choiceinlinehere is the code in the python terminal i am usingadminsiteregisterpoll polladminand here is the code from my urlspyfrom djangoconfurls import patterns include url uncomment the next two lines to enable the adminfrom djangocontrib import adminadminautothiscoverurlpatterns patterns examples urlr ifriendsviewshome namehome urlrifriends includeifriendsfoourls uncomment the admindoc line below to enable admin documentation urlradmindoc includedjangocontribadmindocsurls uncomment the next line to enable the admin urlradmin includeadminsiteurls anyone have any idea why it cannot find the admin nameedithere is my entire model filefrom djangodb import modelsclass pollmodelsmodel question modelscharfieldmax length200 pub date modelsdatetimefielddate published def unicode self return selfquestion def was published recentlyself return selfpub date timezonenow datetimetimedeltadays1 class choicemodelsmodel poll modelsforeignkeypoll choice text modelscharfieldmax length200 votes modelsintegerfield def unicode self return selfchoice textcommented out until i fix the admin namefrom djangoconfig import adminclass choiceinlineadminstackedinline model choice extra 3 class polladminadminmodeladmin fieldsets none fields question date information fields pub date classes collapse inlines choiceinlineadd this to the main python functionadminsiteregisterpoll polladmin,['python'] +343397,zend framework 1 vs zend framework 2 performance zend framework 2 was just released and zend offers support for zf1 for only 18 months from now i know they were working for new features in zf2 and then they were going to do some major speed improvements to it since it was 5 times slower than zf1i would like to know how slower is zf2 than zf1 from benchmarks or tests you did and not pure speculationthe latest benchmark i found is from february 22 2012 and it concludes that zf2 is 4 times slower than zf1link here,['php'] +343403,catch unhandled exceptions from async when an async method that is awaited upon throws an exception the exception is stored somewhere and throwing it is delayed in a winforms or wpf application it uses synchronizationcontextcurrent to post throwing of the exception however in eg a console application it throws the exception on a thread pool and it brings down the applicationhow can i prevent exceptions thrown from an async method from bringing down the applicationeditappearantly the issue i am describing is because i have void async methods see comments,"['c#', '.net']" +343420,override method implementation declared in an interface i have got an interface with a several methods in itinterface imyinterface void onitemclicked and an implementationclass myclass imyinterface other methods public void onitemclicked now i want to have a class that behaves like myclass except of onitemclicked i want some modifications for this methodi thought to inherit an override but i do not want to change the myclass like public virtual void onitemclicked because its not my implementation i do not want to implement imyinterface again because the onitemclicked is the only part of myclass to modifydo i have any other way to do it,['c#'] +343460,how to do pattern shape match recognition on a board 20x20 the board is int and i would like to find this shape 1 1 1with all 4 of it is symmetric rotational variants from the board and log the positionseg x x x x x x x x 1 1 x x x 1 x x x x x x x x x x is it better to use f to deal with these kinds of problemsbelow is my c code for checking patterns vertically only the code to check horizontally is simillar listposition getmatchverticalint reelid listposition ret new listposition var myreel boardreelid var leftreel reelid 1 0 boardreelid 1 null var rightreel reelid 1 boardsize boardreelid 1 null int currentcolor myreel0 for int reelposition 1 reelposition boardsize reelposition int nextcolor myreelreelposition if currentcolor nextcolor if leftreelnull if reelposition 1 boardsize leftreelreelposition 1 currentcolor retaddlogposition if rightreelnull if reelposition 2 0 rightreelreelposition 2 currentcolor retaddlogposition else currentcolor nextcolor return ret,['c#'] +343485,actionmailer pass local variables to the erb template i know i could define instance variables egdef user registerusername email username username email email mailto email subject welcome template name reg i18nlocaleendbut is there a way to use local variables instead just like passing locals to partials,"['ruby-on-rails', 'ruby']" +343508,how can i test inappbilling with a nonpublished app i have an android app that uses inappbilling to sell account managed items i tested the app with the static response ids and everything seems to work i now want to test the app with real product ids i created the app in the google play store and uploaded a draft version of the app with the correct permissions i now created an inappbilling item and published the item at the moment the app is unpublished the item is created and published and i have a test account that is registered in the profile of the developer account and is the only account on the device that i use for testing the app is signed with the same key as the uploaded draft editi am testing with android 41 403 at the momentif i try to buy the item the google play store pops up but shows a dialog with the following method the item you requested is not available for purchasehow can i test buying the item without publishing the app,['android'] +343513,python threading can i sleep on two threadingevents simultaneously if i have two threadingevent objects and wish to sleep until either one of them is set is there an efficient way to do that in python clearly i could do something with pollingtimeouts but i would like to really have the thread sleep until one is set akin to how select is used for file descriptorsso in the following implementation what would an efficient nonpolling implementation of wait for either look likea threadingeventb threadingeventwait for eithera b,['python'] +343514,android numberpicker set min max default from xml is there a way to set the minimum maximum and default values of a numberpicker from the xml layouti am doing it from within the activity codenp numberpicker findviewbyidridnpnpsetmaxvalue120npsetminvalue0npsetvalue30xml is obviously more appropriate because it defines property not behaviour is there a way to set these using the xml layout,['android'] +343517,is play framework 20 suitable for creating a rest api i have developed a rest api using play framework 124 and i have a strong liking for the framework the simplicity and the rapid development cycle helped me achieve this in a fraction of the time i would have taken had i gone the traditional java ee routenow that i am exploring using play 203 for my next project i see that while the framework has been enhanced and makes it even easier to develop webapps the same cannot be said about rest apis my app will not have any html whatsoever i will just respond with xml or json or whatever data exchange format i decide to use in futureso the question is has anyone here used play 20x for exposing nonhtml pure rest apismore detailshere are some of the factors i feel make it more difficult to develop pure rest apis in play 20x compared to 12x please correct my understanding if i am wrongcontent negotiation is harderin play 124 i content negotiation was build in to the framework there were options to define right in the routes file what contenttype a request expectsget friends userlistfriendsformatxmlthen in the controllerpublic static void getfriends renderthis would result in the viewsxmluserlistfriendsxml template being rendered automatically to add support for json tomorrow all i needed to do was to add a viewsjsonuserlistfriendsjson templatei do not see how this can be done in play 20xcreating nonhtml templates is less intuitiveafter some trial and error i figured out that one can create for example a listfriendsscalaxml in the views folder in play 20 then it needs to be invoked in the controller code as followsreturn okviewsxmllistfriendsrenderhowever eclipse does not like this because eclipse does not know about the viewsxmllistfriends since it is generated only after play compilation completes is there anything i am missing here,['java'] +343542,parseint08 returns 0 possible duplicateworkarounds for javascript parseint octal bug i have been working on a javascript function setting date objects by declaring the year month date however when the month has a value of 08 or 09 0 is returned when using parseint see belowparseint01 returns 1parseint02 returns 2parseint03 returns 3parseint04 returns 4parseint05 returns 5parseint06 returns 6parseint07 returns 7parseint08 returns 0parseint09 returns 0parseint10 returns 10i have created a jsfiddle to demonstrate this issuewhy does parseint08 and parseint09 return 0,['javascript'] +343560,how should i use guavas hashingconsistenthash i am looking into using a consistent hash algorithm in some java code i am writing the guava hashing library has a consistenthashhashcode int method but the documentation is rather lacking my initial hope was that i could just use consistenthash for simple session affinity to efficiently thistribute load across a set of backend serversdoes anyone have a realworld example of how to use this method in particular i am concerned with managing the removal of a bucket from the target rangefor exampletestpublic void testconsistenthash liststring servers listsnewarraylistserver1 server2 server3 server4 server5 int bucket hashingconsistenthashhashingmd5hashstringsomeid serverssize systemoutprintlnfirst time routed to serversgetbucket one of the back end servers is removed from the middle of the pool serversremove1 bucket hashingconsistenthashhashingmd5hashstringblah serverssize systemoutprintlnsecond time routed to serversgetbucketleads to the outputfirst time routed to server4second time routed to server5what i want is for that identifier someid to map to the same server after removal of a server earlier in the list so in the sample above after removal i guess i would want bucket 0 to map to server1 bucket 1 to map to server3 bucket 2 to map to server4 and bucket 3 to map to server5 am i supposed to maintain a separate more complicated than a list data structure to manage bucket removal and addition i guess i had envisioned perhaps a more complicated hashing api that would manage the remapping after adding and removal of particular buckets for menote i know the sample code is using a small input and bucket set i tried this with 10s of input across 100 buckets and the result is the same inputs that map to buckets 098 stay the same when i change the buckets to 99 and bucket 99 gets thistributed across the remaining 99 buckets,['java'] +343572,efficiently send large int over sockets in java i am working on a java application where i need to send an array of 50 integers from one android phone to another android phone over a socket connection as quickly as possible the main bottleneck seems to be converting the integers so the socket can take them whether i use objectoutputstreams bytebuffers or a low level maskandshift conversion what is the fastest way to send an int over a socket from one java app to anotherhere is the code for everything i have tried so far with benchmarks on the lg optimus v i am testing on 600 mhz arm processor android 22low level maskandshift 02 secondspublic static byte inttobyteint input byte output new byteinputlength4 forint i 0 i inputlength i outputi4 byteinputi 0xff outputi4 1 byteinputi 0xff00 8 outputi4 2 byteinputi 0xff0 16 outputi4 3 byteinputi 0xff0 24 return outputusing bytebuffer and intbuffer 075 secondspublic static byte inttobyteint input bytebuffer bytebuffer bytebufferallocateinputlength 4 intbuffer intbuffer bytebufferasintbuffer intbufferputinput byte array bytebufferarray return arrayobjectoutputstream 31 seconds i tried variations of this using dataoutputstream and writeint instead of writeobject but it did not make much of a differencepublic static void sendserialdatatcpstring address int array throws ioexception socket sendersocket new socketaddress 46 outputstream os sendersocketgetoutputstream bufferedoutputstream bos new bufferedoutputstream os objectoutputstream oos new objectoutputstreambos ooswriteobjectarray oosflush bosflush osflush oosclose osclose bosclose sendersocketcloselastly the code i used to send byte takes an addition 02 seconds over the inttobyte functionspublic static void senddatatcpstring address byte data throws ioexception socket sendersocket new socketaddress 46 outputstream os sendersocketgetoutputstream oswritedata 0 datalength osflush sendersocketclosei am writing the code on both sides of the socket so i can try any kind of endianness compression serialization etc there is got to be a way to do this conversion more efficiently in java please help,"['java', 'android']" +343611,javascript splice not working correctly when i do thisvar testarray abcconsolelogtestarrayconsolelogsize testarraylengthi this this printed in my consolea b csize3 which is good but now when i start splicing with thisvar testarray abcconsolelogtestarrayconsolelogsize testarraylengthtestarray testarraysplice01this happens to show in my consoleb c undefined a 1size3 so first question is why does it mess up my printing of the array even though the splice was after the printing the size is shown correctly but the a is gone and i get an undefined at the end so what i wanted to do was to remove the first item in the array basically a shift so i do thisvar testarray abcconsolelogtestarrayconsolelogsize testarraylengthtestarray testarraysplice01consolelogtestarrayconsolelogsize testarraylengthand this is what gets outputtedb c undefined a 1size3asize1 not only did the size decrease by 2 it deleted everything but the a what is going on,['javascript'] +343695,cannot implicitly convert derived type to its base generic type i have the following classes and interfacespublic interface ithing string name get public class thing ithing public string name get set public abstract class thingconsumert where t ithing public string name get set now i have a factory that will return objects derived from thingconsumer likepublic class mythingconsumer thingconsumerthingmy factory currently looks like thispublic static class thingconsumerfactoryt where t ithing public static thingconsumert getthingconsumer if typeoft typeofthing return new mythingconsumer else return null i am getting tripped up with this error error 1 cannot implicitly convert type consoleapplication1mythingconsumer to consoleapplication1thingconsumertanyone know how to accomplish what i am attempting herethankschris,"['c#', '.net']" +343732,set java exit code without exiting yet in a highly concurrent program with lots of shutdown operations wondering how to set the exit code without prematurely calling systemexit possible to set an execute this code when everything else is done method but i would really just like to prematurely set the exit code,['java'] +343751,nullpointerexception in webviewjava androidwebkitwebviewprivatehandlerhandlemessage every few days i get a crash report for my application with the following stack trace or small variants thereof with different line numbers based on different android versionsjavalangnullpointerexception atwebviewjava8241in androidwebkitwebviewprivatehandlerhandlemessagehandlerjava99in androidoshandlerthispatchmessagelooperjava150in androidoslooperloopactivitythreadjava4293in androidappactivitythreadmainmethodjava2in javalangreflectmethodinvokenativemethodjava507in javalangreflectmethodinvokezygoteinitjava849in comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava607in comandroidinternaloszygoteinitmainnativestartjava2in dalviksystemnativestartmainthis specific stack was on android 234 on a htc evo 3d pg86100 devicemy app does host several webviews for some oauthrelated login scenarioshow should i go about trying to figure out how to fix this i have tried looking on grepcode to find the source but i am unable to find a matching line number that makes sense is my grepcodefu weak,['android'] +343764,codemirror dynamic syntax validation been trying to decide between using codemirror or ace editor i have been leaning towards codemirror however there is one feature of ace that i really like and that is how it does syntax validation so as i am typing there can appear a warning or error icon in the left gutter area beside the line number and when i hover over it it gives me a little descriptionis there any way to get this functionality in codemirror specifically i am using the css mode for codemirrorit would also be nice to be able to add in my own custom validationthanks,['javascript'] +343777,rails how to get the current users time zone when using heroku i set the time zone of our site on heroku to pacific standard time pst usingheroku configadd tzamericalos angelestimes for users are now always in pstwhether or not they are in the pst time zonewhats the best way to get the users actual time zone ie the time zone of where they are physically locatedi am guessing that this can be solved using rails or javascript as opposed to heroku,"['javascript', 'ruby-on-rails']" +343787,animateslow down elements filling space left by removed element here is my example when you click the first picture it is removed and all the following images move back to fill the space left by it but they move too fast and you do not even get the notion that they movedmy question is how do i make these elements move smoothly basically like an iphone when you move or delete an icon like this i am not worried about ie678 or any other compatibility issues,"['javascript', 'jquery', 'css']" +343829,how to get dtmf value in dailpan i have one dialplan in which what i want isif user press any key then play file again but i can not understand how to get dtmf value in dialplanthis is my dialplancallme exten s1answer exten snplaybackdemofilename1first how to get dtmf value and also if user press any key then playback should be executed 2 timesbut i want to manage all this things using dialplan,['php'] +343864,randomnumbergenerator vs rngcryptoserviceprovider according to msdn documentation for randomnumbergeneratorapplication code does not directly use this class this abstract class is provided as the base class for all cryptographic random number generatorsfor an implementation of a cryptographic random number generator use the derived class rngcryptoserviceproviderhowever i have seen the following code used on a few occassions in different code basesbyte bytes new byterandomnumbergenerator rng randomnumbergeneratorcreaternggetbytesbytesmost notably with stackexchange which i assume includes so and also with bcryptnet therefore i am a little confused what type of randomnumbergenerator is the above code returning also is it a bit of a flaw that some code bases are using randomnumbergenerator rather than rngcryptoserviceprovider i assume randomnumbergeneratorcreate is doing under the hood which i am completely missing here but technically as it is an abstract class should not the above code throw an error,['c#'] +343880,how to cast lambdas i would like a family of functions to be kept in a dictionary that derive from some base type lets call the base class object for example sake so it it possible to keep f1 in f2funcbool f1 truefuncobject f2 f1error 1 cannot implicitly convert type systemfuncbool to systemfuncobjectis this the best we can dofuncbool f1 truefuncobject f2 objectf1errors nonei guess what it needs to be generic friendly is a where statement but i am not sure if you can do that with lamdasfollowing up on armens info i dug into the definitions of string and boolpublic sealed class string icomparable icloneable iconvertible ienumerable icomparablestring ienumerablchar iequatablestring public struct boolean icomparable iconvertible icomparableboolean iequatablebooleanhe is right about ref vs value does string derive from object implicitly looks like that is the behaviour for structs according to peterks linkvaluetype overrides the virtual methods from object with more appropriate implementations for value types see also enum which inherits from valuetypeobject systemobject all classes structures enumerations and delegates from which in turn makes funcbool not being assignable to funcobject a little bit dumb ie the inheritance hierarchy was correct from that point of view,['.net'] +343897,whats the equivilent of getcheckeditemcount for api level 11 i am using this method to check how many items on a list a checked and i get this error that this method is not available for any sdk older than 11what is the equivalent this in api level 8,['android'] +343903,where should i store constant data and then how to reference it in rails i have a array of data for example times 700am 730am etc that i want stored and referenced in a couple places1 where should i store this data i was originally thinking in my db i am using mongoid but i am not sure if that is over kill2 how would i go about referencing it let us say from a drop down menu,['ruby-on-rails'] +343914,gzip css completely breaks page thanks for stopping by i really tried this on my own but once again it seems too much for me to handlethe situationi am live with my own website on a shared hoster when i came to the point of wanting to compress my tons of cmsgenerated js and css to make pagespeedinsights and myself happy i read into it and at last found out that my hoster does not have neither mod gzip nor mod deflate installed what is installed is zlib so i searched found the typical php append solution and did not like it found a few neat lines of code for htaccess which made me happy cause they worked right awayaddhandler applicationxhttpdphp html htm php jsphp flag output buffering onphp value output handler ob gzhandlerphp flag zliboutput compression offi confirmed it is working by using gidziptest this is all fine and i love itbut as soon as i put css to the addhandler list my page completely breaksi tried to use the php solution with ob gzhandler for only css files but it ended up not working at all just does plain nothingworkaround not reallyi manually minified all the css and uploaded a cssgz version of each file serving it withrewritecond httpacceptencoding gziprewritecond request filenamegz srewriterule css 1cssgz qsarewriterule cssgz ttextcssenogzip1this works fine as wellquestionswhat do i need to definespecifiy for css compression to work i feel i am just missing some conversion stuffwhen i am serving my manually minified cssgz files to a client will they still be compressed extrawould this have any further advantages in filesize or should i rather just stick to the manually served versions and give a about google pagespeedgidziptest still shows awhat ifa scenarios even for the minified files which are impressive numbers to be honest i would like thatthank you in advance for any comment givenyours sincerelymarian,['css'] +343917,in html5 to set a checkbox as checked should i simply use checked as a property or checkedchecked as an attribute currently in our plugin we were setting the checkboxes as checked by settinginput typecheckbox checkedchecked this was to preserve xhtml compatibility i am more used to setting checked as a propertyinput typecheckbox checked what is the correct way to proceed in html5should we still care about xhtml compatibility,['html'] +343994,audiofocus loss called after a phone call in android i am trying to pause media player when the phone rings i use the sample code from android site it is like thispublic void onaudiofocuschangeint focuschange switch focuschange case audiomanageraudiofocus gain resume playback if mmediaplayer null mmediaplayerisplaying mmediaplayerstart mmediaplayersetvolume10f 10f break case audiomanageraudiofocus loss lost focus for an unbounded amount of time stop playback and release media player stopmediaplayer break case audiomanageraudiofocus loss transient lost focus for a short time but we have to stop playback we do not release the media player because playback is likely to resume if mmediaplayerisplaying mmediaplayerpause break case audiomanageraudiofocus loss transient can duck lost focus for a short time but it is ok to keep playing at an attenuated level if mmediaplayerisplaying mmediaplayersetvolume01f 01f break when the phone rings audiofocus loss transient is sent which is ok and when the call ends the audiofocus gain is sent and the player continue to play which is also ok but right after sending audiofocus gain audiofocus loss is sent have any ideas why it is losing audio focus thx in advance,"['java', 'android']" +344034,unresolved in eclipse ubuntu yes it is this question againsomehow i cannot get this issue resolved believe it or not i have experience with eclipse but only for java development i have programmed in c using vi but not with eclipsei have installedubuntu 1204eclipse 372gcc 463eclipse cdt 802i created an empty makefile project and selected the linux gnu toolchaini get the standard unresolved inclusion iostream error and i have some references to various include directories in the projecti did notice that while my paths and symbols setting for gnu c contains various paths the same setting for gnu c is emptyalso i have the gnu elf parser under my cc build settingswhat am i doing wrong herecheerseditheres an updated photo of my a projects build path that is working correctly,['c++'] +344041,opencv for android do i need to install opencv manager separately just started looking into opencv for android i noticed that i need to install something called opencv manager before i can run the apps that use itis there any way to bundle this manager with my app so that users would not have to install it separately it would really help if this was possiblei have not written an app that uses opencv yet but i am just looking aheadmany thanks,['android'] +344047,c algorithm like pythons groupby are there any c transformations which are similar to itertoolsgroupbyof course i could easily write my own but i would prefer to leverage the idiomatic behavior or compose one from the features provided by the stl or boostinclude cstdlibinclude mapinclude algorithminclude stringinclude vectorstruct foo int x stdstring y float zbool lt by xconst foo a const foo b return ax bxvoid list by xconst stdvectorfoo foos stdmapint stdvectorfoo foos by x ideas int mainint argc const char argv stdvectorfoo foos stdmapint stdvectorfoo foos by x stdvectorfoo sorted foos stdsortfoosbegin foosend lt by x list by xsorted foos foos by x return exit success,['c++'] +344054,how to install nokogiri ruby gem with mkmflog saying libiconv not found i am installing the ruby nokogiri gem and finding the error belowhow to diagnose this and solve it gem install nokogiribuilding native extensions this could take a whileerror error installing nokogirierror failed to build gem native extensionoptruby193p194binruby extconfrbchecking for libxmlparserh extconfrb failed could not create makefile due to some reason probably lack ofnecessary libraries andor headers check the mkmflog file for moredetails you may need configuration optionsoptruby193p194libruby191mkmfrb381in try do the compiler failed to generate an executable file runtimeerroryou have to install development tools firstfrom optruby193p194libruby191mkmfrb506in try cpp,['ruby'] +344088,conditional where in linq hi any suggestions on building a linq statement based on search criteriai will be passing in an instance of a searchcriteria class with all parameters nullablei then want to if sca null add to whereif scb null add to wherethe key thing is these are to be ors not andsany tipsand for bonus points i would like to use contains on an int but i can only get equals or not equals,['c#'] +344093,update an existing installation using installshield le weve got a a quite simple winforms application i have created an installation using installshield le which works fine on the first install i would like that users will be able to run the installation also for updating an existing copy the problem is that i cannot figure out what is the right way to create this update package i have triedchanging the product code the installation works but a new entry is being created in addremove programs and the old entry is not removedkeeping the product code windows installer shouts another version of this product is already installedtried to play with other codes upgrade code product version does not helpis there any easy way to create this maybe something to tell the installer to remove its previous version if exist,['.net'] +344141,whats the difference between contenttype and enctype for html forms i am confused i am trying to set enctypeapplicationoctetstream but the server receives the request with contenttype applicationxwformurlencoded the default value,['html'] +344164,c move memory parts inplace i am implementing several datastructures and one primitive i want to use is the following i have a memory chunk an it has a variable length but i take 100 for my examples and inside this chunk there is a smaller part c of length k lets say 30 which i want to move without using any additional memorythe additional difficulty is that a wraps that is c can start at a80 and then the first 20 elements of c are the elements a80100 and the last 10 elements are the elements a010 furthermore the target range may also wrap and overlap with c in any possible way additionally i do not want to use more than a constant amount of additional memory everything should happen in place also the part of a which is neither in the target range nor in the source range may contain something important so it cannot be used either so one case would be the followinga looks like this 456789abcdef0123456789ab0123and should be transformed to this89ab0123456789abcdef01234567just delegating it to a library or use another datastructure from a library is not an option here i want to understand the problem myself on the first sight i thought that it might not be trivial but as soon as you thistinguish a few cases it becomes clear but now i am having serious trouble of course there are the trivial cases if they do not overlap or do not wrap but at least if both happens at the same time it gets messy you could start with one free place and move the part that belongs there but then you create another free part somewhere else and it gets hard to keep track of which parts you can stil usemaybe i am missing something completely but even my special case if the target range does not wrap has almost 100 lines half of it are assertions and comments though and i could update it so that it also handles the general case with some additional index calculations but if someone has an elegant and short solution i would appreciate some help intuitively i think that this should somehow be trivial but i just do not see the best solution yetnote the interesting case is of course if c is almost as big as a if c n2 it is trivialedit using more than a constant amount of additional flagsindices counts as additional memory and i want to avoid that if possibleedit some people wanted to see my code my question is rather abstract so i did not want to post it but maybe someone sees how to improve it it is terrible it only works for the case that the target starts at the beginning however that can easily be changed and terribly long but it does the job without additional memory in oninclude stddefhinclude stdiohinclude stringhinclude asserthvoid move partint a size t n size t target size t source size t size int show steps assertsource size n asserttarget size n if show steps printfmoving size d from d to dn size source target memmovea target a source size sizeofintvoid swap partsint a size t n size t first begin size t second begin size t size int show steps if show steps printfswapping size d at d and dn size first begin second begin assertfirst begin size n assertsecond begin size n size t i for i 0 i size i int x afirst begin i afirst begin i asecond begin i asecond begin i x void move to beginningint a size t n size t begin size t size int show steps assertbegin n assertsize n denotes the start of our working range increases during the algorithm and becomes n size t part start 0 note keeping the size is crucial since begin end could mean that the range is empty or full size t end begin size n while part start n size t i if show steps for i 0 i n i printfd ai printfn printfpart start d begin d end d size dn part start begin end size loop invariants assertpart start n the two pointers are in our range assertpart start begin begin n assertpart start end end n size is valid wrapped case nonempty nonfull case assertbegin end n begin end part start size size is valid non wrapped case nonempty nonfull case assertbegin end end begin size size is valid working range is full or empty case assertbegin end size 0 part start size n if size 0 begin and begin part start 1234 1234 if show steps printfcase 1nterminatingn 12 12 12 12 break not necessary any more but would be the correct transformation part start n begin n end n size 0 else if end part start 123 123 if show steps printfcase 2n printfsetting end to dn n end n else if begin end 1234 1234 if show steps printfcase 3n move parta n part start begin size show steps break not necessary any more but would be the correct transformation part start n begin n end n size 0 else size t end size end part start size t begin size and begin assertbegin size end size size if end size begin size 34512 12 534 if show steps printfcase 4n swap partsa n part start begin begin size show steps assertbegin size 0 necessary for progress part start begin size size end size begin end remain unchanged else if begin part start begin size 561234 123 564 size t size moved begin part start assertsize moved end size else the next step would be more efficient if show steps printfcase 5n swap partsa n part start begin end size show steps move parta n end begin end size begin end show steps assertend size begin end size moved size size moved part start begin begin size moved end size moved else if end size begin size 45123 123 45 if show steps printfcase 6n swap partsa n part start begin end size show steps move parta n end begin end size begin size end size show steps part start begin size size end size end begin end size begin remains unchanged else no case applies this should never happen assert0 int main int and 20 int a20 size t size 17 size t begin 15 size t i for i 0 i size i abegin i n i move to beginninga n begin size 0 for i 0 i size i printfd ai printfn return 0,['c'] +344172,how to upload files using put instead of post with php i am building my first rest api and it is going well so far i am just having an issue with files uploads via put request method i need to be put because i am updating a user and their avatar image from an ios app and put is specifically for update requestsso when i put and file upload the files array is actually empty but when i print the put dataparse strfile get contentsphpinput put vars data put vars print rdatai get the following responsearray webkitformboundarykwxboho69mmtfs61contentthisposition formdata name avatar filenameavatarfilenamepngcontenttype imagepngi12pngnow i do not really understand this put data because i cannot just access it like an array or anything so my question is how do i access the uploaded file from the put datathanks for your help,['php'] +344176,using custom deleter with stdshared ptr i am trying to work out how to use stdshared ptr with a custom deleter specifically i am using it with sdl surface asstdshared ptrsdl surfacesdl loadbmpsdl freesurfacewhich compiles and runs fine however i would like to try out my own deleter and cannot work out how to do so the documentation for sdl freesurface is found here freesurfacein which i find the sdl freesurface is declared asvoid sdl freesurfacesdl surface surfaceas a test and going by that information i tried the following functionvoid deletesurfacesdl surface surface stdcout deleting surfacen sdl freesurfacesurfacehowever compiling with g gives me the following errorerror no matching function for call to stdshared ptrsdl surfaceshared ptrsdl surface unresolved overloaded function typei have looked at the gnu documentation for the gcc stdshared ptr implementation but cannot make much sense of it what am i doing wrongedit i have since narrowed down the problem but will leave the original question above what i had was a game class which if i strip it down to a basic implementation was something likeclass game public various functions private void deletesurfacesdl surface surface bool cacheimages stdvectorstdshared ptrsdl surface mcachedimages various member variables and other functions with the implementation of deletesurface as above and the implementation of cacheimages asbool cacheimages mcachedimagespush backstdshared ptrsdl surfacesdl loadbmpdeletesurface return truewhich game me the error i listed above however if i move the deletesurface function outside the game class without otherwise altering it the code compiles what is it about including the deletesurface function in the game class that is causing problems,['c++'] +344201,android progress bar on imageview i am developing an app in which user will take picture from camera and thisplay it on preview screen having image viewcameracapturejavaclass buttonclickhandler implements viewonclicklistener public void onclick view view myvibvibrate50 startcameraactivity protected void startcameraactivity file filenew new file path uri outputfileuri urifromfile filenew intent intent new intentandroidprovidermediastoreaction image capture intentputextra mediastoreextra output outputfileuri intentaddflagsintentflag activity no animation startactivityforresult intent 0 overrideprotected void onactivityresultint requestcode int resultcode intent data switch resultcode case 0 break case 1 pictaken onphototaken break protected void onphototaken pictakentrue intent i new intentcameracapturethispreviewclass startactivityiin my preview class the captured picture is thisplayed on imageviewpreviewjavafile imgfile new filesdcarddcimcameratestjpgifimgfileexists bitmap mybitmap bitmapfactorydecodefileimgfilegetabsolutepath imageview myimage imageview findviewbyidridimage bitmap mybitmap bitmapfactorydecodefileimgfilegetabsolutepath matrix mat new matrix string degree90 matpostrotateintegerparseintdegree bitmap bmaprotate bitmapcreatebitmapmybitmap 0 0mybitmapgetwidthmybitmapgetheight mat true myimagesetimagebitmapbmaprotate myimagesetimagebitmapmybitmap image imageview findviewbyid ridimage is there is any way to show progress bar on the imageview till it load the captured image from sd cardthnx in advance,['android'] +344247,set variable inside val this appears to work and is valid but is there any reason i should not do this it saves me a line of code and lets me set a variable and the value of a text area pricevaldefault price 29it is equivalent to thisdefault price 29pricevaldefault price,"['javascript', 'jquery']" +344286,how to select unique keywords from a comma separated tags i want to retrieve some tags from my database they are in the formtopic id tags 1 tag1tag2tag3 2 tag1tag4tag5 3 tag2tag4tag5 4 tag6tag7tag2i want to have something like thistag1 tag2 tag3 tag4 tag5 tag6 tag7ie all unique tagsso that i can wrap each tag in a link in order to group news articles that has such specific tagsthis following query i have written so far is not workingtags mysql queryselect tags topic id from forum topics where topic id 0 or die mysql error whiletag mysql fetch assoctags split tags tag pieces explode split tags echo pieces when i did print rpiecesi got array 0 array array 0 array array 0 array array 0 array which was not what i was looking for as it is now my table structure looks like this topic id topic head topic body topic tag topic date topic owner how can i further make the topic tag normal,"['php', 'mysql']" +344296,building python from source with zlib support when building python 323 from source on ubuntu 1204 the zlib module is not availablei downloaded the official source thistribution from pythonorg and attempted to build and install it with the following commandstar xfa python323tarbz2cd python323configure prefixoptpython32makesudo make installthe make command output includes the followingpython build finished but the necessary bits to build these modules were not found curses curses panel dbm gdbm sqlite3 ssl tkinter bz2 readline zlib after running make install and starting the interpreter the zlib module cannot be importedi confirmed that the zlib1gdev package is installed on my systemi also found this similar question which suggests adding the withzlib flag to the configure command however that returns an error that it is an unrecognized option and has no effect,['python'] +344334,c date and time i am developing an appointment application in c and want to use some date and time featuresis it easier to just use strings when talking about date and time or should i write or get a datetime classi am wanting to code an appointment class that holds both the time and date of an appointment once i have coded the class file i am wanting to integrate it into a forms application in c builderi see that there is a tmonthcalendar control i would like to use this control when making the forms application as such what format for the date does this control use i would like to use the same type as the control when making the class so that i can easily integrate it togetherupdatei have found that it uses the tdatetime type my question is this what include statement do i need to use to use this in a console application,['c++'] +344348,how to write from scratch an lcd driver for an android tablet i would like to write a driver for the lcd screen of asus tf700 what should i study to be able to do it from the very beginning how should i get start to go into it,"['android', 'c']" +344378,android adb shell am startservice error not found i am trying to start the service from adb shell there already is similar question how to start and stop android service from a adb shell however when i start service withadb shell am startservice commypackagecommypackageservicemyservicei receive this messagestarting service intent actandroidintentactionview datcommypackagecommypackageservicemyservice error not found no service startedi declare service in androidmanifestxmlapplication service androidnamecommypackageservicemyservice androidlabelstringlocal service label androidicondrawableic launcher serviceapplicationdo you have any idea how to solve thisthank you,['android'] +344385,difference between outlookfolder and outlokmapifolder i am not clear on the difference between the classes folder and mapifolder in the namespace outlook when i review the code in the net some use the first while others use the other syntax and i cannot really determine ifit is just because of their ignorance and even less i can tell which group is the right oneit is some kind of legacy usage for different versions of outlookit is the very same thing something i am fairly sure is not true but one never knowsit is an inheritance structure and what to use whenit is simply a way to avoid type issues casting and asingit is other reasons entirely and if so whichheres the code i am using for obtaining those twooutlookfolder defaultcontactsfolder 1 thisapplicationsessiongetdefaultfolder outlookoldefaultfoldersolfoldercontacts as outlookfolderoutlookmapifolder defaultcontactfolder 2 thisapplicationgetnamespacemapigetdefaultfolder outlookoldefaultfoldersolfoldercontacts,['c#'] +344401,what is wrong with my config severe ioexception while loading persisted sessions javaioeofexception i have a web program using struts2 spring3 and hibernate 4 running in tomcat it can work but tomcat reports a javaioeofexceptionthe following is the tomcat loginfo deploying web application directory dapachetomcat7029webappsmanagera1 10 2012 42702 a a orgapachecatalinasessionstandardmanager doloadsevere ioexception while loading persisted sessions javaioeofexceptionjavaioeofexception at javaioobjectinputstreampeekinputstreamreadfullyobjectinputstreamjava2298 at javaioobjectinputstreamblockdatainputstreamreadshortobjectinputstreamjava2767 at javaioobjectinputstreamreadstreamheaderobjectinputstreamjava798 at javaioobjectinputstreaminitobjectinputstreamjava298 at orgapachecatalinautilcustomobjectinputstreaminitcustomobjectinputstreamjava58 at orgapachecatalinasessionstandardmanagerdoloadstandardmanagerjava246 at orgapachecatalinasessionstandardmanagerloadstandardmanagerjava204 at orgapachecatalinasessionstandardmanagerstartinternalstandardmanagerjava491 at orgapachecatalinautillifecyclebasestartlifecyclebasejava150 at orgapachecatalinacorestandardcontextstartinternalstandardcontextjava5294 at orgapachecatalinautillifecyclebasestartlifecyclebasejava150 at orgapachecatalinacorecontainerbaseaddchildinternalcontainerbasejava901 at orgapachecatalinacorecontainerbaseaddchildcontainerbasejava877 at orgapachecatalinacorestandardhostaddchildstandardhostjava618 at orgapachecatalinastartuphostconfigdeploydirectoryhostconfigjava1100 at orgapachecatalinastartuphostconfigdeploydirectoryrunhostconfigjava1618 at javautilconcurrentexecutorsrunnableadaptercallexecutorsjava471 at javautilconcurrentfuturetasksyncinnerrunfuturetaskjava334 at javautilconcurrentfuturetaskrunfuturetaskjava166 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava10 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava603 at javalangthreadrunthreadjava722a1 10 2012 42702 a a orgapachecatalinasessionstandardmanager startinternalsevere exception loading sessions from persistent storagejavaioeofexception at javaioobjectinputstreampeekinputstreamreadfullyobjectinputstreamjava2298 at javaioobjectinputstreamblockdatainputstreamreadshortobjectinputstreamjava2767 at javaioobjectinputstreamreadstreamheaderobjectinputstreamjava798 at javaioobjectinputstreaminitobjectinputstreamjava298 at orgapachecatalinautilcustomobjectinputstreaminitcustomobjectinputstreamjava58 at orgapachecatalinasessionstandardmanagerdoloadstandardmanagerjava246 at orgapachecatalinasessionstandardmanagerloadstandardmanagerjava204 at orgapachecatalinasessionstandardmanagerstartinternalstandardmanagerjava491 at orgapachecatalinautillifecyclebasestartlifecyclebasejava150 at orgapachecatalinacorestandardcontextstartinternalstandardcontextjava5294 at orgapachecatalinautillifecyclebasestartlifecyclebasejava150 at orgapachecatalinacorecontainerbaseaddchildinternalcontainerbasejava901 at orgapachecatalinacorecontainerbaseaddchildcontainerbasejava877 at orgapachecatalinacorestandardhostaddchildstandardhostjava618 at orgapachecatalinastartuphostconfigdeploydirectoryhostconfigjava1100 at orgapachecatalinastartuphostconfigdeploydirectoryrunhostconfigjava1618 at javautilconcurrentexecutorsrunnableadaptercallexecutorsjava471 at javautilconcurrentfuturetasksyncinnerrunfuturetaskjava334 at javautilconcurrentfuturetaskrunfuturetaskjava166 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava10 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava603 at javalangthreadrunthreadjava722,['java'] +344435,read only table in mysql i am using mysql database in that i have table called tbl user i need to change this as read only table to every user how to change the table as read only,['mysql'] +344436,wcf netmsmqbinding vs nettcpbinding i was going through this article to choose binding options where i got an unusual doubt of what is mean by offline or thisconnected interaction choose the netmsmqbinding does that mean the even if service is not running still client using the service can you share some real time example,['c#'] +344498,redeclaration of a variable in a forloop in c when trying to compile the following simplified code for multiple platforms i found that it was failing on some namely ibms xlc r further investigation has found that it also fails on comeau and clang it compiles successfully with g and solariss cchere is the codeint main int a11 bool a21 for int it a1 end a11 it end it bool jt a2 end a21 xlc r errormaincpp line 825 15400400 s end has a conflicting declarationmaincpp line 625 15400425 i end is defined on line 6 of maincppclang errormaincpp825 error redefinition of end with a different type bool jt a2 end a21 maincpp625 note previous definition is here for int it a1 end a11 it end it comeau errorcomeautestc line 8 error end declared in forloop initialization may not be redeclared in this scope bool jt a2 end a21 the question is why is this an errorlooking through the 2003 standard it says the following 653the for statement for forinitstatement condition expression statementis equivalent to forinitstatement while condition statement expression except that names declared in the forinitstatement are in the samedeclarativeregion as those declared in conditionhere there are no names declared in conditionfurther it says 651when the condition of a while statement is a declaration the scopeof the variable that is declared extends from its point of declaration331 to the end of the while statement a while statement of the form while t t x statementis equivalent to label t t x if t statement goto label again i am not sure this is relevant as there is no declaration in the condition so given the equivalent rewrite from 653 my code should be the same asint main int a11 bool a21 int it a1 end a11 while it end bool jt a2 end a21 it which obviously would allow end to be redeclared,['c++'] +344543,linker errors when integrating admob sdk into ios app i integrated googles admob sdk into a working iphone app i am getting 12 errors that all start with apple macho linker id error the text of the error messages typically refer to a low level objective c object called from a google library for exampleundefined symbols for architecture i386 nsinmemorystoretype referenced from anon in libgoogleanalyticsagaidatastoreo gaidatastore memorycontextwithmodelwitherror in libgoogleanalytics debugagaidatastoreoi thought i might not be linking a necessary framework but that all seems to be in order i followed the instructions at and my linked libraries tab looks like thisunless i am mistaken it includes the frameworks that admob needs any suggestions much appreciated,['ios'] +344553,measure view in fragment i need to know imageview width and height is there a way to measure it in fragment in standard activity i use this overridepublic void onwindowfocuschangedboolean hasfocus superonwindowfocuschangedhasfocus imagegetwidth imagegetheightbut where can i use imagegetwidth and imagegetheight in fragment,['android'] +344565,codeigniter flash data i am struggling with flash data in codeigniteri basically want toadd a category to a databaseredirect user back to a pageshow a success popup message your category has been createdso far i can add the category successfully to the db and the user input is validated correctly only thing is i do not know how to create the pop up success message i do not want to load a success view just redirect back to where they came from and show small message in the top corner or somethingis flash data the right way to go,['php'] +344603,android gcm time to live issue i have a problem related to time to live i get messages when the device is on but when it is offline i do not get the message or at least it is not sent in the first 15 minutes i am sending the message with delay while idle true and time to live 2419200 any ideas what is happening maybe i misread the documentation,['android'] +344623,edgelines vanish in mplot3d surf when facecolors are specified i have produced the following surface plot in matlaband i need to create this in net instead i am hoping to use ironpython to do this but first i am just trying to create the plot in python pylab this is what i have so farplease have a look at my code and tell me how i can get python to show the black edge lines it appear that these thisappear when i add the facecolorsuwrheatmap property to the surf is this a bug in mplot3d or is it by design either way how do i get the lines backhere is my code apologies for the huge data matricesfrom mpl toolkitsmplot3d import axes3dfrom matplotlib import cmfrom matplotlibticker import linearlocator formatstrformatterimport matplotlibpyplot as pltimport matplotlibfrom pylab import import numpy as npfig pltfigureax figgcaprojection3dsample colour dataheatmap nparray0304 0288 0284 026 0248 0224 0204 0184 018 018 0156 0148 0144 0136 0136 0128 0124 0124 0128 0124 0124 0356 0348 0332 0328 0308 0292 0288 0272 0252 0232 0216 0204 016 0148 0152 0148 0132 0124 0124 0132 0144 0396 0384 0372 036 034 0316 0312 0312 03 0272 0244 0236 0216 0192 0176 0168 0148 0148 0156 0156 016 0452 04 0428 0408 0388 0376 0364 0348 0336 0336 03 0284 0264 0256 024 0244 0212 02 022 0224 0224 0488 0476 0464 04 0424 04 04 0384 038 0372 0356 0324 0312 0312 0312 0312 0308 0292 0304 0332 0344 0492 0492 048 0468 0452 0432 0424 0412 0404 0396 0396 0392 0376 0356 0356 036 0368 0372 0392 0404 042 05 05 05 0484 046 0452 04 0436 044 044 044 0452 044 0436 0424 042 0404 044 0452 0468 05 0484 048 046 04 044 044 044 044 04 044 0456 0456 046 0448 0448 0448 0436 0456 0468 0492 0492 0405737704918033 0401639344262295 0409836065573771 0418032786885246 0434426229508197 0438524590163934 0438524590163934 044672131147541 0454918032786885 0471311475409836 0467213114754098 0479508196721311 0487704918032787 0487704918032787 0479508196721311 0483606557377049 0495901639344262 0516393442622951 0520491803278689 0532786885245902 0536885245901639 0320987654320988 0329218106995885 0349794238683128 0362139917695473 0374485596707819 0395061728395062 042798353909465 0440329218106996 0465020576131687 0477366255144033 048559670781893 0493827160493827 0506172839506173 0518518518518519 051440329218107 0518518518518519 0547325102880658 056 056 0584362139917696 0580246913580247 0282700421940928 029535864978903 030379746835443 0320675105485232 0337552742616034 0354430379746835 0383966244725738 0434599156118144 0464135021097046 0485232067510549 0493670886075949 0514767932489452 0527426160337553 0535864978902954 0544303797468354 0561181434599156 0594936708860759 059915611814346 0590717299578059 060337552742616 0607594936708861 0230434782608696 0256521739130435 0273913043478261 0304347826086957 0334782608695652 0360869565217391 0373913043478261 0408695652173913 0469565217391304 0504347826086957 0521739130434783 0539130434782609 0552173913043478 0560869565217391 0578260869565217 06 0617391304347826 061304347826087 061304347826087 0617391304347826 0643478260869565 0161137440758294 0175355450236967 0218009478672986 028436018957346 0327014218009479 03412327488152 0388625592417062 0436018957345972 04881516587673 05165876725119 0549763033175356 0573459715639811 0578199052132701 0592417061611374 0611374407582938 0649289099526066 06587672511848 06587672511848 06725118483412 066824644549763 0691943127962085 0224719101123596 0269662921348315 0303370786516854 0365168539325843 0382022471910112 0404494382022472 0443820224719101 048876404494382 05 0556179775280899 0567415730337079 0612359550561798 0612359550561798 0629213483146067 0634831460674157 0646067415730337 0662921348314607 0685393258426966 0707865168539326 0707865168539326 0724719101123596 03 0363636363636364 0401515151515152 0431818181818182 0446969696969697 046969696969697 0515151515151515 053030303030303 0553030303030303 0583 0613636363636364 0621212121212121 0636363636363636 0643939393939394 0651515151515152 0651515151515152 067 067 0674242424242424 0681818181818182 0696969696969697 0373626373626374 0406593406593407 0483516483516484 0505494505494506 0527472527472528 054945054945055 0571428571428571 0582417582417583 0593406593406593 0637362637362637 0659340659340659 0681318681318681 0692307692307692 0692307692307692 0703296703296703 0692307692307692 0703296703296703 0736263736263736 0736263736263736 0703296703296703 067032967032967 0484375 05625 0578125 0578125 0578125 0625 0625 0640625 065625 0671875 0703125 0734375 075 0734375 0734375 075 0734375 0640625 065625 0625 0609375 0617647058823529 0617647058823529 0617647058823529 0617647058823529 0617647058823529 0588235294117647 0588235294117647 0588235294117647 0617647058823529 0647058823529412 0676470588235294 0705882352941177 0676470588235294 0705882352941177 0705882352941177 0735294117647059 0705882352941177 0705882352941177 0735294117647059 0705882352941177 0647058823529412 06 06 06 06 06 06 06 05 05 05 05 05 04 04 04 04 03 03 03 04 04sample z datavolatility nparray02964396 028628612 027630128 026648508 025683752 02473586 023804832 022890668 021993368 0212932 02024936 019402652 018572808 017759828 016963712 01618446 015422072 014676548 0139478 013236092 01254116 02979793 02879745093 0278154 0268519104 02590684893 02498026 0240721436 02318249973 0223113284 0214586296 020624403 0198086496 0190113684 01823255973 01747236 01673036 01600696893 0153020504 0146156044 01394763093 01329813 0299519 028966289867 02807608 0270553128 026129945867 02522466 0243394552 023474331467 02262928 0218043272 02094467 0202146472 0194499288 018705291467 0179807352 01727626 016591865867 0159275528 0152833208 014659169867 0140551 03010587 0291351288 0281860772 0272587152 0263530428 02546906 0246067668 0237661632 0229472492 0221500248 02137449 0206206448 01984892 0191780232 0184892468 01782216 0171767628 0165530552 0159510372 0153707088 01481207 03025984 02930396773 0283713936 0274621176 02657613973 02571346 0248740784 02405799493 0232652096 0224957224 02174953 0210266424 0203270496 01965075493 0189977584 01836806 01776165973 0171785576 0166187536 01608224773 01556904 03041381 0294728067 02855671 02766552 0267992367 02595786 02514139 0243498267 02358317 02284142 0221245767 02143264 02076561 0201234867 01950627 01891396 0183465567 01780406 01728647 0167937867 01632601 03056778 0296416456 0287420264 0278689224 02702236 02620226 0254087016 0246416584 0239011304 0231871176 02249962 0218386376 0212041704 0205962184 0200147816 01945986 0189314536 0184295624 0179541864 0175053256 01708298 03008828768 02924245670213 02841872838667 0276171025752 02683757942613 02608015867 0253448409568 02463162563653 0239405129258667 0232715028248 0226245953 02197904514667 0213970881792 02081648851653 0202579914634667 01972159702 01920730518613 0187151159618667 0182450293472 01779704534213 0173711639467 02960879536 0288432678042667 02809543026773 0273652827504 0266528252522667 0259580573 0252809803136 0246215928730667 02397989545173 02335580496 02274957067 02216094330293 02159059584 0210367586330667 02050120132693 019983404 0194831567722667 019066952373 0185358722944 0180887650842667 017659347893 02912930304 02840789064 02721322016 0271134629256 0264680710784 025835956 0252171196704 0246115601096 0240192779776 0234402732744 022874546 0223220961544 0217829237376 0212570287496 020741904 02024507106 0197590083584 0192862230856 0188267152416 0183804848264 01794753184 02864981072 028044890853 0274488341354667 0268616431008 02628331690453 02571385467 0251532590272 02460152734613 0240586605034667 0235246584992 02295213 0224832490058667 0219758415168 02147729886613 0209876210538667 02050680808 02003485994453 0195717766474667 01911755818 01867220456853 0182357157867 0281703184 027645701067 0271255360693 026609823276 02609856273067 02559175443 025089398384 02459149458267 0240980430293 023609043724 0231244967 02264018573 022168759296 02169756898267 0212308309173 0207685451 02031071153067 0198573302093 019408401136 01896392431067 01852389973 02769082608 0272465122128 0268022380032 0263580034512 0259138085568 02546965332 0250255377408 0245814618192 0241374252 0236934289488 023249472 02280547088 0223616770752 0219178390992 0214740407808 02103028212 0205865631168 0201428837712 0196992440832 0192556440528 01881208368 02791321753 027446485122 026979833968 0265132640713 026046775432 02558036805 0251140419253 024647797058 024181633448 02371510953 02324955 022783630162 0223177915813 021852034258 021386358192 020920763383 020455249832 019989817538 0195244665013 019059196722 0185940082 0281356089867 0276464580312 0271574299328 02685246914667 0261797423072 02569108278 0252025461098667 0247141322968 0242258413408 0237376732418667 023249628 0227617056152 02739060874667 0217862294168 0212986756032 0208112446467 0203239365472 0198367513048 0193496889194667 0188627493912 01837593272 028358044 0278464309404 0273350258976 0268237853116 0263127091824 02580179751 0252910502944 0247804675356 0242700492336 0237597953884 023249706 0227397810684 02300205936 0217204245756 0212109930144 02070172591 0201926232624 0196836850716 0191749113376 01863020604 01815785724 028580391893 0280464038496 0275126218624 02697904593173 0264456760576 02591251224 02537955447893 0248468027744 0243142571264 02378191753493 023249784 0227178565216 02218613509973 0216546197344 0211233104256 020592207173 0200613099776 0195306188384 019013375573 0184698547296 01793978176 0288027833467 0282463767588 0276902178272 0271343065518667 0265786429328 02602322697 0254680586634667 0249131380132 0243584650192 0238040396814667 023249862 0226959319748 0221422496058667 02158148932 0210356278368 0204826884367 01992966928 0193775526052 0188253561738667 0182734073988 01772170628 0290251748 028446349668 027867813792 027289567172 026711609808 0261339417 0256562848 024979473252 024402672912 023826161828 02324994 022674007428 022098364112 021523010052 020947945248 0203731697 019798683408 019224486372 018650578592 018076960068 0175036308create x and y datax nparange80 121 2y nparange3 1201 05x y npmeshgridx ycreate a color map that goes from blue to white to redcdict red 0 0 0 ie at value 0 red component is 0 first parameter is the value second is the color component ignore the third parameter it is for thiscontinuities 05 1 1 at value 05 red component is 1 1 1 1 at value 1 red component is 1 green 0 0 0 05 1 1 1 0 0 blue 0 1 1 05 1 1 1 0 0make the color map and register it cmap1 matplotlibcolorslinearsegmentedcolormapuwrcdict256cmregister cmapnameuwr cmapcmap1uwr cmget cmapuwrcreate a variable for the colorbarm cmscalarmappablecmapuwrmset arrayheatmapcreate the surface multiply vol by 100 so axis label can be in units of surf axplot surfacex y volatility100 rstride1 cstride1 facecolorsuwrheatmap linewidth1 shadefalse edgecolors0 antialiasedtrueaxis limitsaxset xlim3d80 120axset ylim3d0 12tick locations 7 ticks for y axis 5 ticks for x for z axis maximum 6 ticks only allow integers and only in steps of either 2 5 or 10axyaxisset major locatorlinearlocator7axxaxisset major locatorlinearlocator5axzaxisset major locatormaxnlocator6 interger true steps2 5 10format x and z axis tick labels as percentages and as integersaxxaxisset major formatterformatstrformatterdaxzaxisset major formatterformatstrformatterdcreate a color bar with 11 tickscbar pltcolorbarm tickslinearlocator11 shrink085make the tick label go from 0 to 1 in steps of 01cbaraxset yticklabelsarange010101axxaxisset label textmoneyness strike futureaxyaxisset label textterm monthsaxzaxisset label textimplied volatilitycbaraxyaxisset label textpercentile of current volatility compared with historical levelsset view angleaxview init20 40 show the plotpltshow,['python'] +344662,how to post a form using jersey 20 i am trying to get some data from a form with jersey and i though it would be an easy task to accomplish however i am getting an error when i try to post somethingcaused by javalangillegalstateexception the formparam is utilized when the content type of the request entity is not applicationxwformurlencodedat orgglassfishjerseyserverinternalinjectformparamvaluefactoryproviderformparamvaluefactoryensurevalidrequestformparamvaluefactoryproviderjava126at orgglassfishjerseyserverinternalinjectformparamvaluefactoryproviderformparamvaluefactorygetformformparamvaluefactoryproviderjava1at orgglassfishjerseyserverinternalinjectformparamvaluefactoryproviderformparamvaluefactorygetformparamvaluefactoryproviderjava94at orgglassfishjerseyserverinternalinjectabstracthttpcontextvaluefactoryprovideabstracthttpcontextvaluefactoryjava65at orgglassfishjerseyserverspiinternalparametervaluehelpergetparametervaluesparametervaluehelperjava80 36 morei think this is the relevant part of the stack tracenow for the code i am usingpostpathdeleteproducesapplicationjsonpublic string deleteformparamidstring idand i am trying to post using a test html page like thisform actionpath to the serverdelete methodpost primary id input typetext nameprimary id br input typesubmit valuesubmit formi have been trying to make it work but no chance i have tried adding the consumes annotation with multipartformdata but cannot really make it work i hope someone can give me a hand,"['java', 'html']" +344674,how to create moveresize animations in android does someone know about android animations i want to create something like followingi have a big image in the center of my device screenthis image becomes small by animation and goes to the corner of my device screenits something like in this bellow sequenceany hints would be very appreciated thanks in advance,['android'] +344715,python pandas order column according to the values in a row how do i order columns according to the values of the last row in the example below my final df will have columns in the following order d a p f df dataframenprandomrandn10 4 columnsd f a p df d f a p0 0177438 0102561 1318710 13212521 0980348 0786721 0374506 14110192 0405112 0514216 1761983 05294823 1659710 1017048 0737615 03881454 04723 1407655 0129119 09129745 1221324 0656599 0563152 09007106 1816420 2898094 0232047 06489047 2793261 0568760 0850100 06547048 2180891 2054178 1050897 14614589 1123756 1245987 0239863 0359759,['python'] +344724,ios 5 make nsstring category include nscfconstantstring i have an nsstring category class nsstringurlencodinghi am running into and unknown selector crash because the string i am calling the category method has been optimized into an nscfconstantstring by ios nscfconstantstring urlencodedstring unrecognized selector sent to instance 0x290174i learned of the nscfconstantstring vs nscfstring optimizations in ios 5 fromis anyone aware of how i can get the nsstring category to include the constant strings or even force the var to be an nsstringnscfstring and not an nscfconstantstringcheerszeditlinker flags objc all load are both already implementednsstringurlencodingm is included in the targets compile sourcesnsstringurlencodingm implements the urlencodedstring methodchecked for zombiesi am adding a sharing service to sharekit 20headerinterface nsstring oaurlencodingadditions nsstring urlencodedstringimplementationimplementation nsstring oaurlencodingadditions nsstring urlencodedstring nsstring result nsstring cfurlcreatestringbyaddingpercentescapeskcfallocatordefault cfstringrefself null cfstr kcfstringencodingutf8 result autorelease return result,"['objective-c', 'ios']" +344735,checking if a datatable is null the following code is what i have been using to retrieve user information from a sql database string username loginuserusername string password loginuserpassword string comm select usernamepasswordclientnamerole from users where username username bool rememberusername loginuserremembermeset sqlconnection conn new sqlconnectionconnstring connopen sqlcommand command new sqlcommandcomm conn sqldataadapter da new sqldataadaptercommand datatable dt new datatable dafilldt datarow dr dtnewrow if dt null logic however dt null does not return false when there is no entry in the database with the username equal to loginuserusername is there a different way to check whether or not the sqlcommand is successful,"['c#', 'sql']" +344738,what would cause curl to return false when trying to access a local file this site has been up for several months now and has been working fine i have a php page that creates an invoice from data in the url eg viewinvoicephpid250 builds an invoice based on record 250 this page is accessible via a web browser and works fineon a completely different page ie testphp i am trying to access that file via curl however when i make the call and var dump the results i get boolfalse heres the function that makes the curl callfunction file get contents curlurl ch curl initcurl setoptch curlopt header 0curl setoptch curlopt returntransfer 1curl setoptch curlopt url urldata curl execchcurl closechreturn datahome is a constant that denotes the full url eg invoice contents file get contents curlhomeviewinvoicephpid242echo invoice contentsvar dump invoice contents i have tried changing the url to an external url ie and the page loads just fine i get googles home page but any page that is in the same domain would not load is there a reason that this would happeni am not the server admin but i have root access to the server i have not changed any settings recently but the server admin may have upgraded the version of apache or phpin any case is there a setting i can modify to make this work againps i just tried making this exact call from an external server different domain and it works just fine,['php'] +344749,what is the exact use of classes in javautilconcurrentatomic package in java i am relatively new java i am trying understand what are the usage of classes in the package javautilconcurrentatomici tried to understand the javadoc for this package to get a grasp of it but couldnt really make any sense out of it to when i should use these classes can someone give examples and more descriptions in simple words thx,['java'] +344751,failed to load resource frame load interrupted agian i have code which downloads a picture from a fake link i have looked at others comments sites but nothing has helped me find the solution to the annoying failed to load resource frame load interrupted my php headers are after i read the get value headerpragma public required headerexpires 0 headercachecontrol privatefalse required for certain browsers headercontentlength filesizeidheadercontenttype mimheadercontentthisposition attachment filenamedatebasenamefilenameheadercontenttransferencoding binaryheadercachecontrol mustrevalidate postcheck0 precheck0readfilefilenameand i have jquery script which calls an iframe to download the file bodyappendiframe classdownload srcdownloadphpiddownloading stylevisibilityhidden width0 height0iframei downloads the file correctly but shows an error in the console please let me know if its fixable,"['php', 'jquery']" +344769,getting countstotals at each level of a hierarchical query using connect by i am having a heck of a time with this i am trying to write a query using oracle against a table with a recursive relationship hierarchical and get the total number of records stored in another table at and below each node in the tree the other table only has records associated with the leaf nodes however i want to get totals at and below each node in the tree for example say i have two tables dirs contains the directory names and a recursive relationship identifying the structure of the directories and files contains file information with a foreign key to dirs indicating the directory the file resides indirsdir id parent dir iddir namefilesfile idfile namedir idfile sizeif dirs containsdir id parent dir id dir name 1 root2 1 dir1 13 1 dir1 24 2 dir2 15 2 dir2 2and files containsfile id file name dir id file size 1 test1txt 5 1002 test2txt 5 2003 test5txt 5 50 4 test3txt 3 3005 test4txt 3 3006 test6txt 4 100i want a query that returns the path along with the number of files in or below each node in the hierarchy basically a rollup of the number of files so the query result would look something likepath file count root 6rootdir1 1 4rootdir1 1dir2 1 1rootdir1 1dir2 2 3rootdir1 2 2update sql script to create the tables with example data to match the abovecreate table dirs dir id number38 primary key parent dir id number38 null references dirsdir id dir name varchar2128 not nullcreate table files file id number38 primary key file name varchar2128 not null dir id number38 not null references dirsdir id file size number not null unique dir id file nameinsert into dirs select 1 null root from dualunion all select 2 1 dir1 1 from dual union all select 3 1 dir1 2 from dual union all select 4 2 dir2 1 from dual union all select 5 2 dir2 2 from dualinsert into filesselect 1 test1txt 5 100 from dualunion all select 2 test2txt 5 200 from dualunion all select 3 test5txt 5 50 from dualunion all select 4 test3txt 3 300 from dualunion all select 5 test4txt 3 300 from dualunion all select 6 test6txt 4 100 from dualcommit,['sql'] +344780,bind button in datatemplate to command in the forms viewmodel my problem is similar to the one described in this questionwpf mvvm button control binding in datatemplatehere is my xamlwindow xclassmissilesharplaunchermainwindow xmlns xmlnsx titlemissilesharp launcher height350 width525 grid when i put the button here outside the list the binding works button contenttest commandbinding pathfirecommand listbox itemssourcebinding commandsets listboxitemtemplate datatemplate i need the button here inside the list and here the binding does not work button contentbinding commandbinding pathfirecommand datatemplate listboxitemtemplate listbox gridwindowit is just a listbox bound to an observablecollectionstring named commandsets which is in the viewmodelthis binding works it thisplays a button for each item in the collectionnow i want to bind the button to a command firecommand which is also in the viewmodelheres the relevant part of the viewmodelpublic class mainwindowviewmodel inotifypropertychanged public icommand firecommand get set public observablecollectionstring commandsets get set public mainwindowviewmodel thisfirecommand new relaycommandnew actionobjectthisfiremissile private void firemissileobject obj systemwindowsmessageboxshowfire the binding of this button does not workfrom what i have understood from the question i linked above the binding does not work becausecorrect me if i am wrongthe button is inside the listbox so it only knows the binding of the listbox the observablecollection in this case but not the binding of the main windowi am trying to bind to a command in the main viewmodel of the main window which the button does not knowthe command itself is definitely correct because when i put the button outside the listbox see the xaml above for an example the binding works and the command is executed apparently i just need to tell the button to bind to the main viewmodel of the formbut i am not able to figure out the right xaml syntaxi tried several approaches that i found after some googling but none of them worked for mebutton contentbinding commandbinding relativesourcerelativesource window pathdatacontextfirecommand button contentbinding commandbinding pathfirecommand sourcestaticresource mainwindow button contentbinding commandbinding pathfirecommand relativesourcerelativesource ancestortypextype window could someone pleasegive me the proper xaml to bind the button inside the listbox to a command in the forms mainviewmodelpoint me to a link where this advanced binding stuff is explained in a way that a wpfmvvm beginner can understandi am feeling like i am just copying and pasting arcane xaml incantations and so far i do not have any clue and cannot find any good documentation how i would figure out by myself in which cases i would need relativesource or staticresource or whatever instead of a normal binding,['c#'] +344786,how do you prevent uitextfields autocorrect bubble from overlapping with the inputaccessoryview first of all thanks for your time in advance i am struggling with an annoying glitchi have built a quick sample project just to make sure i do not have anything around messing up with thisas you can see the autocorrect bubble overlaps the inputaccesoryview of my uitextfielddoes anybody know if there is a way to specify that the bubble should be thisplayed above the fieldit seems to me that this is an uikit glitch in the routine that calculates the bubbles position it is clearly not accounting for the inputaccesoryview in fact if i remove the uitoolbar and place the uitextfield right above the keyboard the bubble will be thisplayed upwardsany idea will be very welcomethank you,['ios'] +344799,server name indication sni on java can anyone help me get started on carrying out http connections with server name indication in javai am trying to request content from a site i am adminstering i have been using apache is httpclient library but my request for secure content fails because the website only uses sni for https and sni is not enabled in the defaulthttpclient i have looked for instruction on how to approach this within apache is httpclient library but i see end up with this document which is out of date referring to code back when httpclient and httpcore were part of apache is commons packageso any help,['java'] +344805,how to round down to nearest integer in mysql how would i round down to the nearest integer in mysqlexample 123457344 rounds to 12345mysqls round function rounds upi do not know how long the values nor the decimal places will be could be 10 digits with 4 decimal places could be 2 digits with 7 decimal places,"['mysql', 'sql']" +344813,yeoman livereload vs yeoman watch i am trying out yeoman server for the first time and see that it offers a native watch tool as a fallback to livereload heres how the docs explain the fallbackyeoman server automatically fires up the yeoman watch process so changes to any of the applications files cause the browser to refresh via livereload should you not havelivereload installed locally a fallback reload process will be used insteadso far the fallback process is working perfectly and i like that it does not require installing anything in the browsermenu barhas anyone tried both watch tools with yeoman how is the workflow different and what additional features do you get if you upgrade to livereloadupdate a quick inspection of the api revealed that yeomans live reload feature is in fact livereload they are one and the same the reason it works without the browser extensions is because they are using livereloads snipvr snippet instead it is possible there are some additional features accessible via the livereload gui and perhaps for mobile device testing but more likely the functionality is identical,['javascript'] +344822,illegalstateexception when using curl to verify app store receipt i have an inapp purchase for which i want to verify the store receipt i would like to verify this from a random machine on the internet by using apples itunes api the receipt is stored in parse after the transaction is completed i am following the guide on the apple developer website first i get the transaction from parsecurl x get h xparseapplicationid h xparserestapikey which looks like transactionreceipt typebytesbase64asdfqwertyasdfqwerty transactiontypepurchased transactionidentifier transactiondate typedateiso20120910t065844071z createdat20120910t065837234z updatedat20120910t065837234z objectidhypwjblwzt i then take the base64 value inside transactionreceipt and curl it against the apple endpoint to get the receiptcurl h accept applicationjson h contenttype applicationjson x post d receiptdataasdfqwertyasdfqwerty and all i get back is a not tremendously helpfulstatus21002 exceptionjavalangillegalstateexceptionwhich i believe corresponds to a the data in the receiptdata property was malformed getting curl to dump the entire operation with traceascii did not reveal anything i thought was relevant i am sure the issue is not with the connection itselfslightly stumped here it does look like the transaction was found on their end tweaking a few bytes in the receiptdata throws a javalangillegalargumentexception so i am guessing it is got something to do with the transaction itself has anybody seen this beforethanks,"['iphone', 'ios']" +344830,what is difference between xib and nib possible duplicatewhats up with the nib xib i want to know what is difference between xib and nibi know some thing like xib xml interface builder and nib is next interface builderbut i am not clear with difference between both please help me for itthanks in advance,['ios'] +344841,how to escape in javascript underscore template when using underscore template i want to interpolate a value in anchors href attribute likeahref id classproducts underscore template in jadebut the out put is a hreflt id gt classproducts so how to escape the and sign and interpolate the value correctly,"['javascript', 'html']" +344856,to view profilepicture in xcode of facebook user when i am using selfprofilepicprofileid useridi end up with this erroruiview setprofileid unrecognized selector sent to instance 0x69626f020120911 094950535 tweetapp992c07 terminating app due to uncaught exception nsinvalidargumentexception reason uiview setprofileid unrecognized selector sent to instance 0x69626f0can anyone help on this topic,"['objective-c', 'ios']" +344887,how many activities vs fragments introthe basic fragments tutorial pattern goes something like thison a tablet have a list on the left details on the right both are fragments and both reside in the same activity on a phone have alist fragment in one activity launch a new activity with the details fragmenteg android 30 fragments api by dianne hackborn and the fragments api guideon both devices functionality is in the fragments simpleon the tablet the whole app is 1 activity on the phone there are many activitiesquestionsis there a reason to split the phone app into many activitiesone problem with this method is that you duplicate a lot of the logic in the main tablet activity and in the separate phone activitieswould it not be easier to retain the 1 activity model in both casesusing the same logic of switching fragments in and out just using a different layoutthis way most of the logic resides in the fragments themselves and there is only a single activity less duplication of codealso what i have read about the actionbarsherlock is that it seems to work best with fragments instead of activities but i have not worked with it yetare the tutorials oversimplified or have i missed something major in this approachwe have tried both approaches successfully in the office but i am about to start a bigger project and want to make things as easy for myself as possiblesome links to related questionsdilemma when to use fragments vs activitiespatterns when to use activity transition vs dynamic fragmentsandroid need some clarifications of fragments vs activities and viewsactivities or fragments in androidmultiple fragments and activities interaction designso what are the exact advantages of fragments in android 30updatesstarted bounty on question still not convinced about why i need to duplicate my app logic in my tablet activity and in each phone activityalso found an interesting article by the guys at square which is well worth readingadvocating against android fragments,['android'] +344977,in xcode how to thisplay text merging englisharabic and beginning with arabic i want to set a label to string just bought thisguise kitbut when i run the test the label show just bought thisguise kit if the text is not begin with arabic it will show as what i setwhats the problemdoes anybody know how to deal with this issue,['iphone'] +344982,alternative for documentready function i am using fancybox in an aspx page the document ready function does not work in this page for a lightbox someone told me to write a new javascript code for loading the lightbox in that page,"['jquery', 'asp.net']" +345001,osgetenv returns none instead correct value i have a complex piece of software i am not able to post nor do i have a concrete working example i will try to explain the problem maybe someone encountered this before on the linux shell i have defined an environment variable export my test env4711 echo my test env 4711within the complex code i want to obtain this variable withprint osgetenvmy test envwhich always returns none if i create a testscript to test this behavior even with classes in different files i always get the desired behavior ie osgetenvmy test env returns the correct value 4711 the code is started as sudo any ideas what could be the reason,['python'] +345049,can i incorporate both signalr and a restful api i have a single page web app developed using aspnet i recently converted many of the web methods to be push based using the signalr library this really sped up the page considerably and reduced a lot of the server calls from the pageat the same time i have also been looking at the restful aspnet webapi for some of the serverside methods with the real beauty being that it allows to create an api for external applications at the same time that i develop the core application which will be important for what i am doing it seems however after looking at several articles and these two questions that push and webapi methods seem like two entirely different paradigms for clientserver communication i am sure that i can create various methods that can be accessed via either protocol but i am uncertain if there are pitfalls to this or if this is considered sloppy maybe there is a more elegant way to achieve what i am aiming for there are certainly situations in which i want the restful webapi to broadcast events via a signalr hub the opposite signalr ever needing to access the webapi seems less likely but i suppose still possiblehas anyone done this does anyone have any advice or tips on how to proceed what would be the most elegant way forward here,['asp.net'] +345054,html thisplay image after selecting filename possible duplicatepreview an image before it is uploaded i have a form that allows me with input typefile namefilename acceptimagegif imagejpeg imagepngto browse and select a filewhat i want to do is thisplay that image immediately after the image has been selectedand this is before the submit button on the form has been pressed so the image almost certainly resides client side can this be done,['html'] +345057,how to detect if atof or wtof failes how to detect if atof or wtof failes to convert the string to double but not by trying to check if the result is different form 00 because my input can be 00 thanks,['c++'] +345059,android how to track if softkeyboard is openned in my application the device softkeyboard is covering the edittextviews so user cannot see what he is typingso i want to hide other viewslike a button in my case to make the edittextviews visiblebut instead on doing something likeedittextonfocushide buttonfor every edittext i want to do something likeifsoftkeyboardisopennedhide buttonhow to track if softkeyboard is openned or closededitactually my layout is this xml version10 encodingutf8relativelayout xmlnsandroid androidlayout widthfill parent androidlayout heightfill parent linearlayout androidlayout width0dp androidlayout height0dp androidbackgroundandroidcolortransparent androidfocusabletrue androidfocusableintouchmodetrue linearlayout imageview androidididlogo androidlayout width45dp androidlayout height45dp androidsrcdrawablewic logo small button androidididgobutton iwant androidlayout width35dp androidlayout height45dp androidlayout alignparentrighttrue androidbackgroundcolorblack androidgravitycenter verticalcenter horizontal androidtextstringgo autocompletetextview androidididsearchautocompletetextview iwant androidlayout widthfill parent androidlayout heightwrap content androidlayout toleftofidgobutton iwant androidlayout torightofidlogo androidhintstringsearch androidtextcolorcolorwhite textview androidididiwantlabel androidlayout widthfill parent androidlayout heightwrap content androidlayout belowidiwantpagelogo androidbackgroundcolorgrey androidgravitycenter verticalcenter horizontal androidtextstringiwant androidtextcolorcolorwhite scrollview xmlnsandroid androidididscrollviewiwant androidlayout widthwrap content androidlayout heightwrap content androidlayout belowidiwantlabel androidscrollbarsvertical relativelayout androidlayout widthfill parent androidlayout heightwrap content androidorientationvertical textview androidididineedtobuy androidlayout widthfill parent androidlayout heightwrap content androidlayout belowidiwantlabel androidgravitycenter verticalcenter horizontal androidpadding5dp androidtextstringineedtobuy androidtextcolorcolorwhite androidtextsize20dp autocompletetextview androidididineedtobuyedittext androidlayout widthfill parent androidlayout heightwrap content androidlayout belowidineedtobuy androidhintstringproduct androidimeoptionsactionnext androidsinglelinetrue androidtextcolorcolorwhite androidtextsize15dp textview androidididerror1 androidlayout widthfill parent androidlayout heightwrap content androidlayout belowidineedtobuyedittext androidheight0dp androidtext androidtextcolorcolorerror color androidtextsize12dp textview androidididpricewillingtopay androidlayout widthfill parent androidlayout heightwrap content androidlayout belowiderror1 androidgravitycenter verticalcenter horizontal androidtextstringpricewillingtopay androidtextcolorcolorwhite androidtextsize20dp edittext androidididpricewillingtopayedittext androidlayout widthfill parent androidlayout heightwrap content androidlayout belowidpricewillingtopay androidhintstringprice androidinputtypenumber androidsinglelinetrue androidtextcolorcolorwhite androidtextsize15dp textview androidididerror2 androidlayout widthfill parent androidlayout heightwrap content androidlayout belowidpricewillingtopayedittext androidheight0dp androidtext androidtextcolorcolorerror color androidtextsize12dp textview androidididneedtobuyitby androidlayout widthfill parent androidlayout heightwrap content androidlayout belowiderror2 androidgravitycenter verticalcenter horizontal androidtextstringneedtobuyitby androidtextcolorcolorwhite androidtextsize20dp edittext androidididdate iwant androidlayout widthfill parent androidlayout heightwrap content androidlayout belowidneedtobuyitby androidclickabletrue androidcursorvisiblefalse androidfocusablefalse androidhintstringdate androidinputtypenone androidsinglelinetrue androidtextcolorcolorwhite androidtextsize15dp textview androidididerror3 androidlayout widthfill parent androidlayout heightwrap content androidlayout belowiddate iwant androidheight0dp androidtext androidtextcolorcolorerror color androidtextsize12dp datepicker androidididdatepicker iwant androidlayout width0dp androidlayout height0dp androidlayout belowiderror3 androidhintstringdate androidpadding5dp androidtextcolorcolorblack androidtextsize15dp textview androidididiamin androidlayout widthfill parent androidlayout heightwrap content androidlayout belowiddate iwant androidgravitycenter verticalcenter horizontal androidtextstringiamin androidtextcolorcolorwhite androidtextsize20dp spinner androidididcity spinner iwant androidlayout widthfill parent androidlayout heightwrap content androidlayout belowidiamin androidpromptstringcityspinner androidtextcolorcolorwhite androidtextsize20dp button androidididsubmitbutton iwant androidlayout widthfill parent androidlayout heightwrap content androidlayout belowidcity spinner iwant androidgravitycenter verticalcenter horizontal androidtextstringsubmit androidtextcolorcolorwhite androidtextsize20dp textview androidididemptyspace androidlayout widthwrap content androidlayout height50dp androidlayout belowidsubmitbutton iwant androidgravityleft relativelayout scrollview linearlayout xmlnsandroid androidididbuttons iwant androidlayout widthfill parent androidlayout heightwrap content androidlayout alignparentbottomtrue button androidididfeedbutton iwant androidlayout widthwrap content androidlayout height30dp androidlayout margin0dp androidlayout weight1 androidbackgroundcolorwhite androidtextstringfeed androidtextcolorcolorblack button androidididiwantbutton iwant androidlayout widthwrap content androidlayout height30dp androidlayout margin0dp androidlayout weight1 androidbackgroundcolorwhite androidtextstringiwant androidtextcolorcolorblack button androidididsharebutton iwant androidlayout widthwrap content androidlayout height30dp androidlayout margin0dp androidlayout weight1 androidbackgroundcolorwhite androidtextstringshare androidtextcolorcolorblack button androidididprofilebutton iwant androidlayout widthwrap content androidlayout height30dp androidlayout margin0dp androidlayout weight1 androidbackgroundcolorwhite androidtextstringprofile androidtextcolorcolorblack linearlayoutrelativelayoutthe problem comes when i am typing text in the edittextviews in the scrollview,['android'] +345084,when i delete my ios application push notification state remains when i install my ios application using xcode for the first time my iphone asks whether i want to enable push notifications i am able to send a notification and the badge shows a number that i sent when i delete the application from my iphone and rebuild it in xcode and reinstall it again on my iphone using xcodethe device does not ask if i want to enable push the badge is there and remembers the last number i tried the same application on a fresh device installed the ipa and it asked me for permissions how can i completely make my device forget the applicationthanks,"['iphone', 'ios']" +345087,dialog open twice on fast click of button i have button which on clicking thisplays a dialog everything works like a charm but if i double click the button or click the button fast the dialog opens twice or three times i have to click the back button twice or thrice to thismiss the dialogi have searched for related questions on so but most of the answers suggest thisabling the button or use of variable and set to true and false which is not my requirementif anyone knows how to solve this problem please help mecode i have used delete item on click of delete buttonholderbutdeletesetonclicklistenernew onclicklistener override public void onclickview v dialog passworddialog new dialogsettingsactivitythis passworddialogshow,['android'] +345092,sorting objects in nsmutablearray with sortusingcomparator i have the following mutable arraynsmutablearray persons nsmutablearray allocinitwithobjectsperson1 person2 person3 nilwhere every person is an object which contains nsinteger personage and nsstring personname propertiesnow i want to sort this array by personage so i tried the followingpersons sortusingcomparator nscomparisonresultid obj1 id obj2 person p1 personobj1 person p2 personobj2 return p1personage compare p2personage nslogld persons componentsjoinedbystring but i am getting a bad receiver type nsinteger aka long error message in the return line also i have a warning in the nslog line format specifies type long but the argument has type nsstring how do i fix it,['objective-c'] +345104,gradient support for ie 8 and below i found a great css gradient code generator for a page my friend is making but there are some comments below it that worry me for internet explorer 55 7 filter progiddximagetransformmicrosoftgradientstartcolorstrc endcolorstrf for internet explorer 8 msfilter progiddximagetransformmicrosoftgradientstartcolorstrc endcolorstrf backgroundcolor cand in replyi strongly recommend against these they do not act the same are limited hurt performance and can cause layout issues simply put since ie does not support gradients and many other css features natively without filter either use images for the same effect background image or convince your client that ie users get less of an experience who seriously cares about gradients vs single colours besides insane designers because their browser just does not match up to what we as developers want it is called graceful degradation and ie should not be any exception to thatso what i do not know is should i suggest they dodo not use any of this code is getting ie to use this code uselesshopeless,['css'] +345130,how are variable arguments implemented in gcc int maxint n i am using cdecl calling convention where the caller cleans up the variable after the callee returns i am interested in knowing how do the macros va end va start and va arg workdoes the caller pass in the address of the array of arguments as the second argument to max,['c'] +345137,spring mvc checking if user is already logged in via spring security i have a spring mvc applicationit uses its own custom login page upon successful login a logged in user object is placed in the httpsessioni want to allow only authenticated users to access urls i know i can achieve this by using a web filter but this part i want to do using spring security my check will remain the same look for logged in user object in httpsession if present you are logged inmy constraint is i cannot change login behavior at present that will not use spring security yetwhat aspect of spring security can i use to achieve this part alone check if the request is authenticated from logged in user,['java'] +345165,how to run custom rule in androidmk before compilation in android ndk i build jni files generated automatically by swig callmanager wrapcpp is part of a shared librarylocal src files callmanager wrapcppinclude build shared librarybut i would like to appendedit callmanager wrapcpp before compiling to be more explicitcat jnistufftxt callmanager wrapcppcontent i need to add is known in advance but callmanager wrapcpp is not it is generated by swig ultimately my custom rule will have to run following command to generate callmanager wrapcppswig c java package compackagemy o callmanager wrapcpp callmanageriaccording to this post it is not possible to add custom rules to androidmk but in android sources i believe there are some androidmk handling steps after built or installed i tried the followingmy jni wrapcallmanager wrapcppinclude clear varslocal src files callmanager wrapcpplocal intermediate targets myjnimyjni echo in myjni target swig c java package compackagemy o my jni wrap callmanageri cat jnistufftxt my jni wrapinclude build shared librarybut myjni target is never calledwhat is local intermediate targets used forcan i possibly achieve what i want to do here without writing an external script or makefile,['android'] +345167,how can i rewrite the glcameraripple sample with image as background i am trying to rewrite the apple sample glcameraripple code with image as a background actually i am trying to create ripple effect on water image using this code but code is working for camera instead i just want to use a simple water image as background instead of camera any direction or any sample code will be a great help thanks in advance,"['iphone', 'objective-c', 'ios']" +345209,3 digit currency code to currency symbol in c is it possible to get a currency symbol like a from the 3 character currency code in this case gbpis this possible either in sql server or in c,"['c#', '.net']" +345217,eclipse not releasing console log memory after clearing my eclipse footprint is steadily increasing from 500mb to 1gb without me doing anything in particular just running some log heavy programs doing a manual gc closing and reopening projects does not help at all once it is over 1gb it stays therei have run jvisualvm and found out from the heapdump that hundreds of megabytes are char representing log outputi make it a habbit to close all the consoles of stopped processes so it is not thatconsole buffer is set to 1mb characters i have closed the console view and reopened it againi can paste my particular eclipseini but i have tried different gc and memory settings different jvms different eclipse versions behavior is still the sameto me it seems that the logs are getting stuck with a reference somewhere and never get released is anyone else having this problem is there a setting somewhere to release memory from old console views,['java'] +345294,integrate indentation content changes in git during merge best practices i am using git to track some matlab code a toy example best illustrates the problem the project so far looks like this c a bcontents of a are x5we make commit c where the line is changed to x6we then make commit b where our content becomes as belowif flag1 x5endif we attempt a merge with the goal of the project looking like c a d bwith the merge result in d well get a conflict because the main line has been changed in both indentation added in b 5 changed to 6 in c is there a best practice way for integrating indentation changes from one branch and content changes from another branch to get a merge resulti have read about one strategy in and while that would avoid the conflict it would thiscard the indent in favor of the content change which is an improvement but still makes for harder to read codei suppose i could just suck it up and not change indentation when writing my code this makes it less readable but is not a huge deal in matlab however in python indentation really matters so how do python folks deal with it this gets much uglier if there are large blocks of code that we later change to be inside of control structures so the diff touches many lines and makes merge conflicts a huge headacheis there a merge strategy that will handle spacing changes and content changes separately and then integrate them i would like the result of the merge to beif flag1 x6end,['python'] +345305,create an array of characters from specified range i read some code where someone did this in rubyputs azto ajoinoutputabcdefghijklmnopqrstuvwxyzis there something in javascript that will allow this to be done just as easy if not is there node module that allows for something similar,"['javascript', 'ruby']" +345307,delayed job how to set a priority for a user mailerrb method i am using delayed job w rails 3 to delay user mailers example usermailerdelayemail digestfromemailsubjecthtmltexthow can i add a priority by default all delayed jobs are set to priority 0 for this mailer i would like to make it less important with a priority of 1possible thanks,['ruby-on-rails'] +345419,migrating existing access tokens to facebook ios sdk 30 i just overhauled my codebase to use the new facebookiossdk 30 from the previous version 2x or whatnoteverything worked great until i realized i had not accounted for users who had already granted the app permissionlogged in with the previous implementation of the sdk so i tried checking to see if the accesstoken was saved in nsuserdefaults and if so make a call to open a session if nsuserdefaults standarduserdefaults objectforkeyfbaccesstokenkey nsuserdefaults standarduserdefaults objectforkeyfbexpirationdatekey fbsession openactivesessionwithpermissionspermissions allowloginuiallowloginui completionhandlerfbsession session fbsessionstate status nserror error deal with state change my assumption was that the user wouldnt have to fast app switch for sso since they already had however that is indeed what happensi would rather not have every existing user need to relogin when upgradinghas anyone successfully upgraded without having to reloginthanks,['objective-c'] +345425,call to undefined function curl init error in wamp 22 i am having below error when i try to implement google and facebook authentication in windows 7 using wamp serverfatal error call to undefined function curl init in ewampwmysiteprotectedextensionseautheauthservicebasephp on line 273i am usingwampserver 22php version 5313i have enabled php curl module as well i checked in phpini for confirm and it is uncommented as belowextensionphp bz2dllextensionphp curldllextensionphp dbadllthe code has worked in ubuntu with xampp but not in wamp in windows i have done everything i can find i have tried replacing the php curldll also according to the comment on this thread call to undefined function curl init with wampmy phpinfo looks like belowi have installed wamp in the partition e but the configuration file phpini path seems different it is cwindowsplease help me to fix the issue,['php'] +345447,how to extend redcarpet to support auto linking user mentions on my rails3 application i want to use redcarpet to handle users posts and the user comment section as such i would like to extend redcarpet to support turning username into a link to a user on my site i know redcarpet is written in c but is there anyway easy way to extend it in ruby how hard would it be to write it in c should i just do this outside of redcarpetalso i am intrested in some other extensions of redcarpet that would be shorthand for linking to other models in my app i am not sure the syntax yet but i am guessing it would be similar to how github handles linking to issues,['ruby'] +345456,how can i retrieve the name of the printer chosen in acrobat i want to get the name of the printer chosen in acrobat printdialog using sendmessage windows apithis is sample codestatic string getwindowtext hwnd printdialog in acrobat int comboboxcount 0 int hwnd printer name 1 listintptr childptrlist getchildwindowshwnd printdialog in acrobat for i0 i childptrlistsize i getclassname childptrlisti sclass 100 if sclasstostring combobox comboboxcount if comboboxcount hwnd printer name hwnd childptrlisti break childptrlistclear int ssize ssize sendmessagew hwnd wm gettextlength intptrzero intptrzero 1 stringbuilder sbtitle new stringbuilder ssize sendmessagew hwn wm gettext intptrssize sbtitle return sbtitletostringthe return value of ssize is 4the value of sbtitletostring is etcthe expected resuwhat is wrong,['c#'] +345483,mysql delete order by i have a table and i only thisplay the latest 30 rows by order by idi am trying to delete any rows after the 30 newest rows by using this query belowdelete from table where type test order by id desc limit 30 60i keep getting this error below1064 you have an error in your sql syntax check the manual that corresponds to your mysql server version for the right syntax to use near 60 at line 1what am i doing wrongthank you,"['mysql', 'sql']" +345501,iphone camera how to detect movement of object on camera screen i have an application which requires functionality to detect the movement of object or image which is shown on camera screen is it be possible with iphone,['ios'] +345550,allow only positive decimal numbers within my django models i have created a decimal field like thisprice modelsdecimalfield uprice decimal places2 max digits12obviously it makes no sense for the price to be negative or zero is there a way to limit the decimal number to only positive numbers or do i have to capture this using form validation,['python'] +345661,yielding spellchecker the title is a bit misleading maybe my spellchecker focuses more on format than spelling caps punctuation and spaces apostrophes converting internet slang to full words oftscrambled words etc however the basic principles applybasically the jsjquery checker i am building would correct words as they are typed after a space or punctuation has been typed after the wordhowever much like any autocorrecting it is bound to run into mistakes i am not even considering creating functionality that would determine whether its or it is is more appropriate in a given case though if such a plugin or code snippet exists do point me to oneso i want to make it a yielding autocorrect for the lack of the knowledge of a better name basicallyuser types in a word that would set off the checker and types aspacethe checker corrects the wordthe user deems this a mistakeand corrects it back by backspacing the whole word or parts of itor highlighting it or however they feel comfortable editing ittheuser continues typing and the checker does not touch that instance of that word againnow easiest of course would be to thisable the check for that word entirely but i want the checker to correct future instances of it what i am looking for would detect a user editing an autocorrected word regardless whether right after typing or later back to what it was before being autocorrected and then learning to leave that specific instance of that word alonei do not even know where to begin with this i am thinking a contenteditable with each word wrapped in a span autocorrected ones having a special class and a data attribute containing the original one listen for edits on the autocorrected words and if it is edited back to equaling the data value add a class that leaves it out of future autocorrect roundsi am thinking though that this might be unnecessarily complicated or at least not the path of least resistance what would be the smartest way of doing this,"['javascript', 'jquery']" +345718,why java does not support equality comparison on the lines of comparator java provides way to define comparison of object outside scope object using comparatornow my questions is why java does not allow do same for equals and hashcodenow each collection contains method can easily use this external equality provider to check objects are equal,['java'] +345730,passing an object to overloaded operator somebody gave me a a program having an error yesterday working in mvs 2010 i found the problem and an alternative for it as well the problem was the overloaded insertion operator the class its prototype was as followsvoid matrix operator matrix it was called from somewhere like thismatrix m moperator m i worked out that compiler does not allow to send the same object as a reference parameter upon which the function was called but i do not understand the reason behind that and that what problem does it create i would appreciate if anybody could explain thatthankseditwhat is actually happening is that upon debugging it goes inside the function comes out and at execution of main goes into the external dependency file dbgdelcpp and stops at this line asserte block type is validpheadnblockuse,['c++'] +345740,datatables scroll issue only in ie9 i have an issue with datatables not using its xaxis scroll correctlyi was previously faced with the ie9 ghost cell issue which i was able to fix however now i am running into a problem where my overflowx is shown instead of hiding it and making the window scrollablemy datatables initialization var otable tablebpdatatable bjqueryui true sscrollx 100 sscrollxinner 200 sscrolly 300 bscrollcollapse false bfilter true bsort false binfo false bpaginate false this is a datatables plugin the issue occurs whether i comment this part or not new fixedcolumnsotable ileftwidth 225 this is what i am faced with it works in ie9 compatibility mode though unfortunately other parts of the page do not allow me te run this is a lower version compatibility but this clearly marks it as a ie9 only issue no issues in chrome safari opera firefoxi am not going to post the table here because of its sheer size 20 td fields in some cases it is a perfectly valid html table with a theadtbody and all whitespaces between the tags have been removed this is what fixed my previous ghost cell issueanyone have any experience with datatables and know the root cause of this issueps this is an mvc2 app cnet but this issue seems unrelated to the application that generated this webpageupdatei forgot to mention the following partthe table used to be thisplayed properly but due to ie9s ghost cell issue in large tables i was forced to clean all whitespaces from between my tabletheadtbodytrtd tagsi resolved this by forcing a regex replace on my aplications html output response is the string with my html output which will be written to the browser after thisstring expression trnvftd response regexreplaceresponse expression tdif i comment out the regex replace the overflow of datatables works perfectly but i am faced with the ghost cell issue which cause misalignment and allround uglinesswhen uncommented all cells are perfectly aligned but the overflow stops workinglike i said the issue only pertains to ie9 all other browsersincluding ie9 in compatibility mode render the table perfectly in both commenteduncommented states,['jquery'] +345790,android throw inflateexception binary xml file line error inflating class fragment i got a activity class which implement a actionbar with two tabs each tab is calling a other fragmentclass over the tablistener if i start the application the fragmentxyclass is called i can switch to the second tab without any problem but if i switch back to the first tab which contains the two other fragments as a splitscreen the application crashed and throw the error inflateexception binary xml file line error inflating class fragmenttab actionbar newtab settextmy box seticonandroidrdrawableic menu help settablistenernew mytablistenerfragmentxythis myxyfragmentxyclass actionbaraddtabtabtab actionbar newtab settextqrcode seticonandroidrdrawableic menu add settablistenernew mytablistenerfragmentxyzthis barcodefragmentxyzclassactionbaraddtabtabeach fragmentclass is calling a xml resource which contain once two other fragments or only one fragmentfragmentxyclassoverride public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate view view inflaterinflaterlayoutfirst tab container false return view first tabxmlxml version10 encodingutf8linearlayout xmlnsandroid androidlayout widthmatch parent androidlayout heightmatch parent androidorientationhorizontal fragment androidnamecomfebromyfragmenttestlistfragment androidididlistfragment androidlayout width250dp androidlayout heightmatch parent androidlayout margintopandroidattractionbarsize classcomfebromyfragmenttestlistfragment fragment fragment androidnamecomfebromyfragmenttestdetailfragment androidididdetailfragment androidlayout widthmatch parent androidlayout heightmatch parent classcomfebromyfragmenttestdetailfragment fragmentlinearlayoutis it a problem with the callbackmethodehere is the full error report from logcat0912 195706300 dandroidruntime2799 shutting down vm0912 195706300 wdalvikvm2799 threadid1 thread exiting with uncaught exception group0x4015d7600912 195706310 eandroidruntime2799 fatal exception main0912 195706310 eandroidruntime2799 androidviewinflateexception binary xml file line 6 error inflating class fragment0912 195706310 eandroidruntime2799 at androidviewlayoutinflatercreateviewfromtaglayoutinflaterjava6880912 195706310 eandroidruntime2799 at androidviewlayoutinflaterrinflatelayoutinflaterjava7240912 195706310 eandroidruntime2799 at androidviewlayoutinflaterinflatelayoutinflaterjava4790912 195706310 eandroidruntime2799 at androidviewlayoutinflaterinflatelayoutinflaterjava3910912 195706310 eandroidruntime2799 at comfebromyfragmenttestfragmentxyoncreateviewfragmentxyjava260912 195706310 eandroidruntime2799 at androidappfragmentmanagerimplmovetostatefragmentmanagerjava7760912 195706310 eandroidruntime2799 at androidappfragmentmanagerimplattachfragmentfragmentmanagerjava11330912 195706310 eandroidruntime2799 at androidappbackstackrecordrunbackstackrecordjava6280912 195706310 eandroidruntime2799 at androidappfragmentmanagerimplexecpendingactionsfragmentmanagerjava13090912 195706310 eandroidruntime2799 at androidappfragmentmanagerimpl1runfragmentmanagerjava3980912 195706310 eandroidruntime2799 at androidoshandlerhandlecallbackhandlerjava5870912 195706310 eandroidruntime2799 at androidoshandlerthispatchmessagehandlerjava920912 195706310 eandroidruntime2799 at androidoslooperlooplooperjava1320912 195706310 eandroidruntime2799 at androidappactivitythreadmainactivitythreadjava41260912 195706310 eandroidruntime2799 at javalangreflectmethodinvokenativenative method0912 195706310 eandroidruntime2799 at javalangreflectmethodinvokemethodjava4910912 195706310 eandroidruntime2799 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava8440912 195706310 eandroidruntime2799 at comandroidinternaloszygoteinitmainzygoteinitjava6020912 195706310 eandroidruntime2799 at dalviksystemnativestartmainnative method0912 195706310 eandroidruntime2799 caused by javalangillegalargumentexception binary xml file line 6 duplicate id 0x7f0908 tag null or parent id 0xf with another fragment for comfebromyfragmenttestlistfragment0912 195706310 eandroidruntime2799 at androidappactivityoncreateviewactivityjava41820912 195706310 eandroidruntime2799 at androidviewlayoutinflatercreateviewfromtaglayoutinflaterjava6640912 195706310 eandroidruntime2799 18 more0912 195706320 wactivitymanager302 force finishing activity comfebromyfragmenttestactionbarmain0912 195706400 ddalvikvm302 gc for alloc freed 13157k 52 free 12567k26055k paused 68ms,['android'] +345798,animate of pseudo elements using jquery i am using aafter it contains right ypxi want to use animate method in jquery to move the element aafter from ypx to zpx how can i do itfor examplelinktextafterlinktext moving afteri know how to do it without animation just doing ahoverafter right zpx but how with animation,"['javascript', 'jquery', 'css']" +345804,use a fork of restkit on github via cocoapod restkit is using in a different way the oauth2 protocol i need to change the code to be able to use it in my way from oauth 2 valid requestif selfauthenticationtype rkrequestauthenticationtypeoauth2 nsstring authorizationstring nsstring stringwithformatoauth2 selfoauth2accesstoken urlrequest setvalueauthorizationstring forhttpheaderfieldauthorizationto oauth 2 valid requestif selfauthenticationtype rkrequestauthenticationtypeoauth2 nsstring authorizationstring nsstring stringwithformatbearer selfoauth2accesstoken urlrequest setvalueauthorizationstring forhttpheaderfieldauthorizationuse of bearer instead of oauth2 i am using coacoapod to import restkit in my projectcan i fork restkit repository on github and use the fork via cocoapod instead of the official version,"['objective-c', 'ios']" +345808,why some arithmetic operations take more time than usual i have detected an unusual computational time when performing arithmetic operations with floating numbers of small precision the following simple code exhibit this behaviorinclude timehinclude stdlibhinclude stdiohconst int max iter 10int mainint argc char argv double x 10 y int i clock t t1 t2 scanflf y t1 clock for i 0 i max iter i x y t2 clock printfx lfn x printftime 5lfsegsn double t2 t1 clocks per sec return 0here are two different runs of the programwith y 05 x 0 time 1320segswith y 09 x 0 time 190segsi am using a laptop with the following specs to test the codecpu intela corea2 duo cpu t5800 200ghz a 2ram 4 gbos ubuntu 1204 64 bitsmodel dell studio 1535could someone explain in detail why this behavior occurs i am aware that with y 09 the x value goes to 0 more slowly than with y 05 so i suspect the problem is directly related to this,['c'] +345833,how can i draw a single sprite at random positions 10 times im totally new at this and have a question i worked with an exercise in school and at home but i cannot figure out how to do it the thing is i want to draw a single sprite at 10 random positions on the screen without using a special sprite class my problem is that after they are drawn they vanish againsolved it thanks for all the help public class game1 microsoftxnaframeworkgame graphicsdevicemanager graphics spritebatch spritebatch texture2d turtletexture int counter 0 random randomera new random int x int y public game1 graphics new graphicsdevicemanagerthis contentrootdirectory content protected override void initialize baseinitialize summary summary protected override void loadcontent spritebatch new spritebatchgraphicsdevice turtletexture contentloadtexture2dimagesturtle 50x38 protected override void unloadcontent protected override void updategametime gametime if gamepadgetstateplayerindexonebuttonsback buttonstatepressed thisexit ifcounter 10 x randomeranext600 y randomeranext400 counter baseupdategametime protected override void drawgametime gametime graphicsdeviceclearcolorwhite spritebatchbeginspritesortmodefronttoback blendstatealphablend if counter 10 for int i 0 i 10 i spritebatchdrawturtletexture new vector2randomeranext600 randomeranext400 colorblack counter spritebatchend basedrawgametime,['c#'] +345850,how to develop or migrate apps for iphone 5 screen resolution the new iphone 5 thisplay has a new aspect ratio and a new resolution 640 x 1136 pixelswhat is required to develop new or transition already existing applications to the new screen sizewhat should we keep in mind to make applications universal for both the older thisplays and the new widescreen aspect ratio,"['ios', 'iphone']" +345862,does android ndk give speedup for sending large int over sockets i need to send an array of 50 ints over a socket between two android devices currently i am spending a lot of time converting the int to a byte so that javas socket will accept it see my previous question efficiently send large int over sockets in java where we determined there is no faster way to do the typecasting in java my question now is if i take the int and pass it through jni to the android ndk can i expect the typecasting to byte to go any faster in native code i know typecasting int to char is quite simple in plainold c however i am wondering if the jni will negate any performance gains furthermore once i have a byte in my native code can i efficiently pass it back to my java code or do i need to implement the socket in c as welledit 1 people have been posting a lot of answers without clicking on the link using bytebuffers is not a good option its actually way slower than maskandshift which is still way slower than my performance critical code needs that is why i am asking about the ndkedit 2 i changed the text above to say that c code can cast from int to char instead of int to byte hopefully that clarifies the questionedit 3 to clarify my usecase this is a research problem where i thistribute a large array of ints across multiple devices and sort the list in parallel assume that i have 50 ints in java does not matter where they come from and i need to get them off the device via a socket as quickly as possible answers that say do not start with an array of ints are not helpful additionally my application code needs to be as close to 100 java as possible if native typecasting and sockets improve performance that is ok but i cannot do anything else ie the sort natively,"['java', 'android']" +345903,is x more efficient than x in java during a programming class the professor was teaching us about x and x with x being an integerhe said that in the scenario we are able to just put either x or x x is more efficient by little but still in theory more efficient nonethelessbut i forgot why anyone knows this was with java,['java'] +345940,android how to change size of logcat buffer i noticed that the size of the logcat buffer varies on different devices assuming i have root permissions on my device is there a way to change the buffer size of the main buffer at runtime if not then assuming i can rebuild the android image how do i change it at compile time i am looking to enlarge it for diagnostic purposes,['android'] +345948,spring and mvc proper project structure i am developing swing standalone application using maven i try to follow mvc pattern i am confused with my project structure i have something like thissrcmainjavamynameappname srcmainjavamynameappnamemodel srcmainjavamynameappnameviewsrcmainjavamynameappnamecontrollernow i want to incorporate spring framework what makes me place somewhere dao and bo interfaces and implementations i have read this article link and the suggested project structure does not suit mine what crosses my mind is to add thissrcmainjavamynameappnamedaosrcmainjavamynameappnamebothe content of dao directory would look like this with client and customer classes in model directorysrcmainjavamynameappnamedaoclientdaojavasrcmainjavamynameappnamedaoclientdaoimpljavasrcmainjavamynameappnamedaocustomerdaojavasrcmainjavamynameappnamedaocustomerdaoimpljavais this bad i want to learn good practices,['java'] +345981,how to run android application in background possible duplicatehow to run application in background in android i am doing project using location manager if my location latitude and longitude equal to the same which is in database mobile profile should go to silent modeso i need to keep on update my location using location manageri did it but if i close my app it is not workingbut my app should be working even though i close my appi tried with async task its working when i close the app but after i switch to loud mode manually it is not changing to silenti should also get notified when my app runs and backgroundplease helptks in advancehere is my codepublic class showlocationactivity extends activity implements locationlistener private textview latitutefield private textview longitudefield private locationmanager locationmanager private string provider double latlng location location audiomanager mobilemode private boolean flag false override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutlocation latitutefield textview findviewbyidridtextview02 longitudefield textview findviewbyidridtextview04 mobilemode audiomanager thisgetsystemservicecontextaudio service get the location manager locationmanager locationmanager getsystemservicecontextlocation service define the criteria how to select the locatioin provider use default criteria criteria new criteria provider locationmanagergetbestprovidercriteria false location locationmanagergetlastknownlocationprovider initialize the location fields flag thisplaygpsstatus if flag if location null systemoutprintlnprovider provider has been selected onlocationchangedlocation iflat12905478lng80093358 mobilemodesetringermodeaudiomanagerringer mode vibrate toastmaketextgetbasecontextvibrate profile activated toastlength shortshow else if lat1290080625lng8009210655 mobilemodesetringermodeaudiomanagerringer mode silent toastmaketextgetbasecontextsilent profile activated toastlength shortshow notificationsetlatesteventinfoshowlocationactivitythis changed to silent mode because you r in office pendingintent notificationmanagernotifyi notification else mobilemodesetringermodeaudiomanagerringer mode normal toastmaketextgetbasecontextloud profile activated toastlength shortshow else latitutefieldsettextlocation not available longitudefieldsettextlocation not available else alertboxgps status your gps is off override public boolean oncreateoptionsmenumenu menu getmenuinflaterinflatermenulocation menu return true public boolean onoptionsitemselectedmenuitem item handle item selection switch itemgetitemid case ridmenu settings intent intent new intent showlocationactivitythissetpreferenceclass startactivityforresultintent 0 checkpref return true default return superonoptionsitemselecteditem private void checkpref sharedpreferences mypref preferencemanagergetdefaultsharedpreferencesshowlocationactivitythis string pref option 1 myprefgetbooleanpref opt1 true override protected void onactivityresultint requestcode int resultcode intent data todo autogenerated method stub superonactivityresultrequestcode resultcode data checkpref override public void onlocationchangedlocation location todo autogenerated method stub lat double locationgetlatitude lng double locationgetlongitude latitutefieldsettextstringvalueoflat longitudefieldsettextstringvalueoflng override public void onproviderthisabledstring provider todo autogenerated method stub toastmaketextthis thisabled provider provider toastlength shortshow override public void onproviderenabledstring provider todo autogenerated method stub toastmaketextthis enabled new provider provider toastlength shortshow override public void onstatuschangedstring provider int status bundle extras todo autogenerated method stub override protected void onresume superonresume locationmanagerrequestlocationupdatesprovider 400 1 this override protected void onpause superonpause locationmanagerremoveupdatesthis public void rview v downloadtask n new downloadtask ndoinbackground public void ondestroy superondestroy logvhon destroy downloadtask n new downloadtask ndoinbackground public boolean thisplaygpsstatus contentresolver contentresolver getbasecontextgetcontentresolver boolean gpsstatus settingssecureislocationproviderenabled contentresolver locationmanagergps provider if gpsstatus return true else return false method to create an alertbox protected void alertboxstring title string mymessage alertdialogbuilder builder new alertdialogbuilderthis buildersetmessageyour devices gps is thisable setcancelablefalse settitle gps status setpositivebuttongps on new dialoginterfaceonclicklistener public void onclickdialoginterface dialog int id finish the current activity alertboxadvancethisfinish intent myintent new intent settingsaction location source settings startactivitymyintent dialogcancel setnegativebuttoncancel new dialoginterfaceonclicklistener public void onclickdialoginterface dialog int id cancel the dialog box dialogcancel alertdialog alert buildercreate alertshow public class downloadtask extends asynctaskinteger integer void override protected void doinbackgroundinteger params logvhback oncreatenull onlocationchangedlocation lat double locationgetlatitude lng double locationgetlongitude latitutefieldsettextstringvalueoflat longitudefieldsettextstringvalueoflng if location null systemoutprintlnprovider provider has been selected onlocationchangedlocation iflat12905478lng80093358 mobilemodesetringermodeaudiomanagerringer mode vibrate toastmaketextgetbasecontextvibrate profile activated toastlength shortshow else if lat1290080625lng8009210655 mobilemodesetringermodeaudiomanagerringer mode silent toastmaketextgetbasecontextsilent profile activated toastlength shortshow notificationsetlatesteventinfoshowlocationactivitythis changed to silent mode because you r in office pendingintent notificationmanagernotifyi notification else mobilemodesetringermodeaudiomanagerringer mode normal toastmaketextgetbasecontextloud profile activated toastlength shortshow else latitutefieldsettextlocation not available longitudefieldsettextlocation not available todo autogenerated method stub return null,['android'] +345996,sql count duplicate row as single i have table id state thistrict stationcode status 1 gujarat banaskantha 12345 0 2 gujarat banaskantha 12345 0 3 mp bhopal 22315 1 4 gujarat banaskantha 12349 0 5 gujarat banaskantha 12345 1i need result like state thistrict active inactivegujarat banaskantha 2 1mp bhopal 0 1here active and inactive fields are sum of status fields based on 0 or 1that means here state for gujarat there three times 0 occured but two duplicate rows for stationcode 12345 it means it will be considered as one i have query like below select thistinct state thistrict sum case when status0 then 1 else 0 end as active sum case when status1 then 1 else 0 end as inactive from station master group by state thistrictbut i am unable to count duplicate stationcode row as singlehow can i do that,['sql'] +346024,activerecord includes specify included columns i have model profile profile has one user user model has field email when i callprofilesome scopeincludesuserit callsselect users from users where usersid in some idsbut my user model has many fields that i am not using in rendering is it possible to load only emails from users so sql should look likeselect usersemail from users where usersid in some ids,['ruby-on-rails'] +346044,layoutawarepage does not exist in namespace vs2012 bug i am trying to get a search contract working on my win 8 app but after adding a search contract to my project i get the following namespace errorlayoutawarepage does not exist in namespace app1commoni do have the correct namespace declarations in the xamlxmlnscommonusingapp1commonand the layoutawarepage is in the correct namespace app1commonrestarting vs2012 or doing a delete and rebuild does not helpto replicate this problem try the following1 create new blank metro app2 add references to visual c runtime3 add a search contract to the project click yes to automatically add other stuff like layoutawarepage etc4 rebuild and open searchresultspage1xamlif you follow the above steps you should see the error and also note that the searchresultspage1 does not thisplay in the designerthis problem only occurs when you add the reference to the visual c runtime without this reference adding a search contract works fineany ideas what am i missing here can you replicate the issue using the above steps,['c#'] +346094,how to fix the code for e 1 11 12 13 1n this is what i came up withinclude stdiohint main void int n i j float e 10 nfact 10 printf please enter the number scanf d n for i 1 i and i for j 1 j i j nfact j e e 10 nfact printf the value of e is f e return 0this is what i get from this codeinput 3output 2583 which is close to 26but for n3 e should give 26 as a valueam i doing something wrong here how can i get the proper output,['c'] +346118,apple macho linker error armv7s libgoogleadmobadsa i have just upgraded my app to run on the new iphone5 simulator however when i try to build it for my iphone 4s device i get this apple macho liner errorld file is universal 3 slices but does not contain an armv7s slice usersdarrendocumentsdev stuffmy appgoogleadmobadssdkios505libgoogleadmobadsa for architecture armv7s clang error linker command failed with exit code 1 use v to see invocationcan someone shed some light on what this error it and how to fix iti am using adwhirl with admobthanksedit i am also getting this error in another project for the file libfacebook ios sdka,['ios'] +346121,initializing a stdunique ptr by passing the address of the pointer i am creating a class which interops with some windows api code now one of the pointers i have to initialize is done by calling a native function which initializes itmy pointers are of type stdunique ptr with a custom deleter which calls the winapi deleter function provided however i cannot pass the unique ptr with the addressof operator to the initfunction whyi have created a sample that demonstrates my probleminclude memorystruct foo int xstruct custom deleter void init foofoo init init new fooint main stdunique ptrfoo custom deleter foo ptr init foofoo ptrthe compiler barks and sayssourcecpp in function int mainsourcecpp1921 error cannot convert stdunique ptrfoo custom deleter to foo for argument 1 to void init foofoo,['c++'] +346129,using stdfunction as a delegate in c11 say i have these 3 different functions that i may want to point tofloat test1int a int b return 70fstruct testclass float test2int a int b return 50f struct testclass2 float test3int a int b return 30f notice how all three use the same arguments and return value i want to abstract away whether or not it is a member function and which class it belonged to i want a delegate type that could be referring to any of these 3 functions depending only on how it was initializedhere is my first attempttypedef stdfunctionfloatint int mydelegate is this rightint main testclass obj testclass2 obj2 mydelegate a test1 mydelegate b stdbindstdmem fntestclasstest2 obj is this right mydelegate c stdbindstdmem fntestclass2test3 obj2 is this right return 0the idea is i want to also store the this pointer inside the wrapper too this way it is like a fully functional delegatefor example invoking bx y should be like calling objtest2x yi just cannot even make it compile i am probably not fully grasping this i am kind of new to these libraries and the errors in vs2012 are catastrophically unhelpful any help would be appreciated,['c++'] +346151,selenium junit test orderflow i am using selenium to test my java web apps html pages jsps actually my web app requires a flow to access each pages it is a small online game web app as in to get to page b youd need to go to page a enter some text and press a button to get to page b obviously i already have some tests to verify that page a is working properlyi would like to be able to write more tests in order to check that after the tests for page a run i will get my tests for page b running and so on for the rest of the app so in short define some order in my tests somehowafter doing lots of reading about testing in the last few days i cannot find anything interesting on this specific subject hence i am asking for advice nowpossible solutions i have identifieddefine in the same test class test methods for page a then test methods for test b then order the execution of the test methods but we know junit but testng does does not allow test methods execution ordering see so question seleniumjunittestshowdoiruntestswithinatestinsequentialordergrouping all the tests for page a page b so on under one test method but i have read it is bad see so question junitonetestcasepermethodormultipletestcasespermethod is it that bad when doing selenium test i have seen some code doing it so i assume it may not begrouping all the tests for page a page b so on under one test method but use the junit is errorcollector class errorcollector allows you to execute ordered checks in the same method and yields a specific error message if one fails but let the method hence the checks running until the end this solution seems too brutal to meuse junit is testsuite class it runs test listed in the suite in the order test classes are defined in the suite so that would involve having independent test methods to test page a in a test class let us say testa then all the test methods to test page b in a test class let us say testb and so on then insert those in a test suite such as suiteclasses testaclass testbclass testcclass use junit is testsuite class in combination with junit is errorcollector class oh well since we can you may want to group test per page in different classes on top of that group page tests zones using errorcollector this solution may be very usefull if you have a very dense web page or other reasonsquite radical use another tool such as testng to have access to features such as test method orderingnote i imagine some would recommend the last solution migrate to testng but i would like to hear other ideasopinions tied to junit too as in if i am working in a team that is not able for some reason to migrate to another testing framework then how would they address this test ordering issue,['java'] +346158,assert an object is a specific type is it possible in junit to assert an object is an instance of a class for various reasons i have an object in my test that i want to check the type of is it a type of object1 or a type of object2currently i haveasserttruemyobject instanceof object1asserttruemyobject instanceof object2this works but i was wondering if there is a more expressive way of doing thisfor example something likeassertobjectisclassmyobject object1i could do thisassertequalsmyobjectclass object1getclassis there a specific assert method that allows me to test a type of an object in a more elegant fluid manner,['java'] +346216,find an item in a generic list by specifying multiple conditions most often we find generic list with code likecartitem item itemsfindc cproductid productiditemquantity quantityitemprice priceso the above code finds and updates with other data but if i want to find by multiple conditions then how do i write the codei want to write code likecartitem item itemsfindc cproductid productid and cproductname abs001please guide me for multiple conditions when we find generic list,['c#'] +346269,how to change the current tab highlighter color in android viewpager here is my layout inside viewpager i would like to change the color of the current tab highlighter which is below the text actually it is showing in black color but i do not know whether it is a color by default or not and also i have one more doubt if i use pagertitlestrip this tab highlighter does not appear is there a way to bring that with titlestriphere is my layout androidsupportv4viewpagertabstrip androidididpager title strip androidlayout widthmatch parent androidlayout heightwrap content androidlayout gravitytop androidbackgroundcolorpager titlestrip bg androidtextcolorcolorpager titlestrip text androidpaddingtop5dp androidpaddingbottom4dp androidsupportv4viewpagertabstrip,['android'] +346275,how to unit test methods that use systemwebsecuritymembership inside i want to test a method to check that it saves a transaction correctly inside it calls membershipgetuser to verify the user which causes the test to fail each time is there any way to mock this so that membershipgetuser always returns a valid namei am using moq c and aspnet 45 mvc,['c#'] +346294,how to share a connection between ef dbcontext and aspnet membership to avoid transactions escalating to dtc i have an aspnet mvc3 application that uses an ef 41 dbcontext databasefirst data layer the edmx approach works fine as i tend to make changes to my data model before adapting the application to them the application works fine with the special ef connection string that includes metadata referenceshowever there is one fly in the ointment the application also uses aspnet membership and roles which require a standard connection string i have several use cases that involve both the membership tables and other ef managed tables as the two use separate connection strings transactions that involve both need dts to handle them i do not want to go that route if i can help it i would rather all parts of the application simply use the same connectiongetting ef to run with a plain connection string however is eluding me can anyone tell me how it is done please,['asp.net'] +346313,error request header field contenttype is not allowed by accesscontrolallowheaders i created an mvc4 web api project using vs2012 i used following tutorial to solve the crossorigin resource sharing it is working successfully and i post data from client side to server successfullyafter that for implementing autherization in my project i used the following tutorial to implement oauth2 communitybtdupontarchive20110318oauth20formvctwoleggedimplementationaspx this is help me for getting requesttoken on client sidebut when i post data from client side i got the error xmlhttprequest cannot load http request header field contenttype is not allowed by accesscontrolallowheadersmy client side code look like function postlogin var emp empusername txtusernameval var pass txtpasswordval var hash sha1requesttoken pass txtpasswordvalhash emppassword hash emprequesttokenrequesttoken var createurl httplocalhost54apilogin ajax type post url createurl contenttype applicationjson charsetutf8 data jsonstringifyemp statuscode 200 function txtmsgvaldone toastrsuccesuccess error function res toastrerrorerror sorry either your username of password was incorrect my api controller look like allowanonymous httppost public loginmodeloauth postloginfrombodyloginmodeloauth model var accessresponse oauthservicebaseinstanceaccesstokenmodelrequesttoken user modelusername modelpassword modelrememberme if accessresponsesuccess oauthservicebaseinstanceunauthorizetokenmodelrequesttoken var requestresponse oauthservicebaseinstancerequesttoken modelerrormessage invalid credentials return model else to do return accessresponse return model my webconfig file look like configuration configsections section nameentityframework typesystemdataentityinternalconfigfileentityframeworksection entityframework version4400 cultureneutral publickeytokenb77a5c561934e089 requirepermissionfalse section nameoauth typemillionnodesconfigurationoauthsection millionnodes version10 cultureneutral sectiongroup namedotnetopenauth typedotnetopenauthconfigurationdotnetopenauthsection dotnetopenauthcore section namemessaging typedotnetopenauthconfigurationmessagingelement dotnetopenauthcore requirepermissionfalse allowlocationtrue section namereporting typedotnetopenauthconfigurationreportingelement dotnetopenauthcore requirepermissionfalse allowlocationtrue sectiongroupconfigsectionsoauth defaultproviderdemoprovider defaultservicedemoserviceproviders add namedemoprovider typemillionnodesoauthdemoprovider millionnodes providersservices add namedemoservice typemillionnodesoauthdemoservice millionnodes servicesoauthsystemweb httpmodules add nameoauthauthentication typemillionnodesmoduleoauthauthenticationmodule millionnodes version10 cultureneutral httpmodules compilation debugtrue targetframework40 authentication modeforms forms loginurlaccountlogin timeout2880 authenticationpages namespaces add namespacesystemwebhelpers add namespacesystemwebmvc add namespacesystemwebmvcajax add namespacesystemwebmvchtml add namespacesystemweboptimization add namespacesystemwebrouting add namespacesystemwebwebpages namespacespagessystemwebsystemwebserver validation validateintegratedmodeconfigurationfalse modules add nameoauthauthentication typemillionnodesmoduleoauthauthenticationmodule millionnodes version10 cultureneutral precondition modules httpprotocol customheaders add nameaccesscontrolalloworigin value customheaders httpprotocolsystemwebserverdotnetopenauthmessaging untrustedwebrequest whitelisthosts uncomment to enable communication with localhost should generally not activate in production add namelocalhost whitelisthosts untrustedwebrequestmessaging allow dotnetopenauth to publish usage statistics to library authors to improve the library reporting enabledtrue,['jquery'] +346333,rotate an avasset with avassetexportsession i am trying to rotate a video to its correct orientation using an avassetexportsession and i always get the following errorerror domainavfoundationerrordomain code11841 the operation couldnat be completed avfoundationerrordomain error 11841that translates to averrorinvalidvideocomposition but i cannot see anything wrong with my video composition heres the codeavassettrack sourcevideo avasset trackswithmediatypeavmediatypevideo lastobjectavassettrack sourceaudio avasset trackswithmediatypeavmediatypeaudio lastobjectcgaffinetransform preferredtransform sourcevideo preferredtransformavmutablecomposition composition avmutablecomposition alloc initavmutablecompositiontrack compositionvideotrack composition addmutabletrackwithmediatypeavmediatypevideo preferredtrackidkcmpersistenttrackid invalidavassetexportsession exporter avassetexportsession alloc initwithassetcomposition presetnameavassetexportpresetmediumquality autoreleasecompositionvideotrack inserttimerangecmtimerangemakekcmtimezero avassetduration oftracksourcevideo attimekcmtimezero errornilif cgaffinetransformisidentitypreferredtransform avmutablevideocomposition videocomposition avmutablevideocomposition videocomposition videocompositionrendersize cgsizemakeavasset naturalsizeheight avasset naturalsizewidth videocompositionframeduration cmtimemake1 compositionvideotracknaturaltimescale avmutablevideocompositionlayerinstruction instruction avmutablevideocompositionlayerinstruction videocompositionlayerinstructionwithassettracksourcevideo instruction settransformpreferredtransform attimekcmtimezero avmutablevideocompositioninstruction videotrackinstruction avmutablevideocompositioninstruction videocompositioninstruction videotrackinstructiontimerange cmtimerangemakekcmtimezero avassetduration videotrackinstructionlayerinstructions nsarray arraywithobjectinstruction videocomposition setinstructionsnsarray arraywithobjectvideotrackinstruction exportervideocomposition videocompositionavmutablecompositiontrack compositionaudiotrack composition addmutabletrackwithmediatypeavmediatypeaudio preferredtrackidkcmpersistenttrackid invalidcompositionaudiotrack inserttimerangecmtimerangemakekcmtimezero avassetduration oftracksourceaudio attimekcmtimezero errornilexporteroutputurl temppathurlexporteroutputfiletype avfiletypequicktimemovieexporter exportasynchronouslywithcompletionhandler what could be wrong with the composition i have been through the documentation and cannot see anything wrong with it so far,['iphone'] +346344,c outlook get companyname property from recipient i am currently writing an outlook 2010 addin using c what i want is to get the companyname property from a recipient object that i pull from an appointmentitem so having the recipients of an appointmentitem i want to find out the companyname of each recipient which might be an exchangeusermy code is thisrecipients recipients appointmentitemrecipientsforeach recipient rec in recipients resolved recresolve if resolved contactitem contactitem recaddressentrygetcontact string companyname contactitemcompanyname where contactitem is always nulldoing something like this also results in a null pointerexchangeuser you recaddressentrygetexchangeusercompanyname ucompanynamei simply cannot get to the companyname information i know the information does exist however also a lot of other attributes besides companyname seem to result in null pointers as wellcan someone give me a hint on thatthanks in advance,['c#'] +346362,installing and importing javafx on windows 7 i have installed jdk170 07 and changed path but i still cannot import javafx is there something that i should do fix this,['java'] +346400,enabling auto layout in ios 6 while remaining backwards compatible with ios 5 what is the best way to take advantage of the new auto layout features of ios 6 while still providing compability with older devices on earlier versions of ios,['ios'] +346407,ios bounds change after rotating to landscape then back to portrait when my application launches an nslog of my views bounds shows the followingnslogmy view frame nsstringfromcgrectselfviewboundsmy view frame 0 0 320 548i then rotate the simulator and get the followingnslogmy view frame nsstringfromcgrectselfviewboundsmy view frame 0 0 320 548then when i rotate the simulator back to portait i get thisnslogmy view frame nsstringfromcgrectselfviewboundsmy view frame 0 0 568 300the two methods i am using to adjust elements are these they are not done yet as i am currently in the middle of fixing them for the new iphonevoid resizeforlandscape newslabel uilabel selfview viewwithtag50 weatherlabel uilabel selfview viewwithtag51 sportslabel uilabel selfview viewwithtag52 entertainmentlabel uilabel selfview viewwithtag53 videoslabel uilabel selfview viewwithtag54 morelabel uilabel selfview viewwithtag55 nslogresizeforlandscape called webviewframe cgrectmake0 31 selfviewframesizewidth selfviewframesizeheight 75 buttonframe cgrectmake0 0 imagesizewidth 30 imagesizeheight 15 mylabelframe cgrectmake230 100 80 21 labelframe cgrectmake0 0 selfviewboundssizeheight 15 30 nslogmy view frame nsstringfromcgrectselfviewbounds nslogmy status bar height is f uiapplication sharedapplicationstatusbarframesizeheight nslogmy status bar width is f uiapplication sharedapplicationstatusbarframesizewidth newslabelframe cgrectmakeselfviewboundssizeheight 346 2 12 selfviewboundssizewidth 38 43 21 weatherlabelframe cgrectmakenewslabelframeoriginx 64 selfviewboundssizewidth 38 42 21 sportslabelframe cgrectmakenewslabelframeoriginx 126 selfviewboundssizewidth 38 42 21 entertainmentlabelframe cgrectmakenewslabelframeoriginx 185 selfviewboundssizewidth 38 66 21 videoslabelframe cgrectmakenewslabelframeoriginx 269 selfviewboundssizewidth 38 42 21 morelabelframe cgrectmakenewslabelframeoriginx 325 selfviewboundssizewidth 38 42 21 spacer1width selfviewboundssizeheight 346 2 spacer2width 40 spacer3width 28 spacer4width 42 spacer5width 35 spacer6width 24void resizeforportrait newslabel uilabel selfview viewwithtag50 weatherlabel uilabel selfview viewwithtag51 sportslabel uilabel selfview viewwithtag52 entertainmentlabel uilabel selfview viewwithtag53 videoslabel uilabel selfview viewwithtag54 morelabel uilabel selfview viewwithtag55 nslogresizeforportrait called webviewframe cgrectmake0 44 selfviewframesizewidth selfviewframesizeheight 88 buttonframe cgrectmake0 0 imagesizewidth imagesizeheight mylabelframe cgrectmake145 152 80 21 labelframe cgrectmake0 0 315 40 nslogmy view frame nsstringfromcgrectselfviewbounds nslogmy status bar height is f uiapplication sharedapplicationstatusbarframesizeheight nslogmy status bar width is f uiapplication sharedapplicationstatusbarframesizewidth float mywidth minselfviewboundssizeheight selfviewboundssizewidth float myheight maxselfviewboundssizeheight selfviewboundssizewidth newslabelframe cgrectmakenewslabelframeoriginx myheight 18 43 21 weatherlabelframe cgrectmakenewslabelframeoriginx 43 myheight 18 42 21 sportslabelframe cgrectmakenewslabelframeoriginx 97 myheight 18 42 21 entertainmentlabelframe cgrectmakenewslabelframeoriginx 138 myheight 18 66 21 videoslabelframe cgrectmakenewslabelframeoriginx 213 myheight 18 42 21 morelabelframe cgrectmakenewslabelframeoriginx 258 myheight 18 42 21 spacer1width mywidth 346 2 spacer2width 20 spacer3width 18 spacer4width 25 spacer5width 28 spacer6width 14called byvoidwillrotatetointerfaceorientationuiinterfaceorientationtointerfaceorientation durationnstimeintervalduration if tointerfaceorientation uiinterfaceorientationlandscapeleft tointerfaceorientation uiinterfaceorientationlandscaperight self resizeforlandscape else self resizeforportrait void getorientationandresize if uideviceorientationislandscapeuiapplication sharedapplicationstatusbarorientation self resizeforlandscape else self resizeforportrait voidviewdidappearboolanimated super viewdidappearanimated self getorientationandresizemy head is about to explode not only are the views reversed but 20 pixels have been robbed from the width and given to the height can anyone explain this to me and how i couldshould code the elements in my view to account for itmy storyboard is as followsmy initial viewafter first rotation still goodrotating back to portrait all screwed up because of the bounds values,"['objective-c', 'ios']" +346416,cast of indirect pointer to an objectivec pointer i have the following code osstatus status secitemcopymatching bridge cfdictionaryrefattrdictionary cftyperef valuewhich causes an error ofimplicit conversion of an indirect pointer to an objectivec pointer to cftyperef aka const void is thisallowed with arcany idea on how to fix this i have tried changing cftyperef to an id but it did not work outheres the full method nsdata keychainvalueforkeynsstring key if key nil return nil nsmutabledictionary attrdictionary self attributesdictionaryforkeykey only want one match attrdictionary setobjectidksecmatchlimitone forkeyidksecmatchlimit only one value being searched only need a bool to tell us if it was successful attrdictionary setobjectidkcfbooleantrue forkeyidksecreturndata nsdata value nil osstatus status secitemcopymatchingcfdictionaryrefattrdictionary cftyperef value if status errsecsuccess dlogkeychainutils keychainvalueforkey error finding keychain value for key status code d status return value autorelease,"['iphone', 'objective-c', 'ios']" +346432,bootstrap twitter datepicker modal calendar coming up in parent screen instead of modal screen i have a form paymentphp which i am thisplaying in a modal screen using twitter bootstrap in the form i have a date field for which i found this bootstrap pluginbut the problem is the calendar is loaded in the parent screen indexphp and not on the modal form where it is actually required can anyone suggest a solution to thisfollowing is the code that i have triedimportslink hrefcssbootstrapcss relstylesheetlink hrefcssdatepickercss relstylesheetscript srcjsbootstrapdatepickerjsscriptscript typetextjavascript srcjsbootstrapjsscriptscript typetextjavascript srcjsjquery180jsscriptphpdiv classcontrols input datadatepickerdatepicker claspan3 value20120913 datadateformatymmdd iddp2 divjsdp2datepicker,"['php', 'javascript', 'jquery']" +346440,domdocument getnodevalue returns null contains an output escaped string i am processing a domdocument which is basically the xml result of a soap web service to give you an idea this is what it looks likeparentnodechildnodeltoutputgtltescapedltstringchildnodeparentnodeyes the value of childnode is a string that has been output escaped and is xml that is packed within this xml i do the usual run of domdocument processing such as nodelist rows domgetelementsbytagnamechildnodeforint i0irowslengthi systemoutprintlnrowsigetparentnode returns parentnode systemoutprintlnrowsigetnodename returns childnode systemoutprintlnrowsigetnodevalue returns nullafter you inspect the above code you realize that even though the node returns correct values for parentnode and the nodename node it returns a null value upon accessing getnodevalue there is a string here and i can see it in my console output but i am not sure what trick i am missing here does the output escaping mess it up in any particular waythanksparijat,['java'] +346441,cocos2d 20 screenshots on ios 6 i have an application that takes a screenshot of a scene and saves it to a file i have this working and the application is on the store today i have downloaded ios 6 and the method i am using is not working anymore i tested all i know to make it work googled around and found thisusers seem to agree that this is working on ios 5 but i have tested this on ios 6 and it is producing black screenshotsi am not a specialist in cocos2d so i cannot say exactly what is wrong with this guys code the author has a sample project on github and even his project is producing black screenshots on ios 6any clues thanksthanks,"['iphone', 'ios']" +346454,mvc 4 simplemembership haslocalaccount method not found when attempting to access accountmanage on the production server i get this errorsystemmissingmethodexception method not found boolean webmatrixwebdataextendedmembershipproviderhaslocalaccountint32 at microsoftwebwebpagesoauthoauthwebsecurityhaslocalaccountint32 userid at projectcontrollersaccountcontrollermanagenullable1 message at lambda methodclosure controllerbase object at systemwebmvcactionmethodthispatcherexecutecontrollerbase controller object parameters at systemwebmvcreflectedactiondescriptorexecutecontrollercontext controllercontext idictionary2 parameters at castleproxiesasynccontrolleractioninvokerproxyinvokeactionmethod callbackcontrollercontext controllercontext actiondescriptor actiondescriptor idictionary2 parameters at castleproxiesinvocationscontrolleractioninvoker invokeactionmethodinvokemethodontarget at castledynamicproxyabstractinvocationproceed at glimpsemvc3interceptorinvokeactionmethodinterceptorinterceptiinvocation invocation at castledynamicproxyabstractinvocationproceed at castleproxiesasynccontrolleractioninvokerproxyinvokeactionmethodcontrollercontext controllercontext actiondescriptor actiondescriptor idictionary2 parameters at systemwebmvcasyncasynccontrolleractioninvokerc thisplayclass42begininvokesynchronousactionmethodb 41 at systemwebmvcasyncasyncresultwrapperc thisplayclass81beginsynchronousb 7iasyncresult at systemwebmvcasyncasyncresultwrapperwrappedasyncresult1end at systemwebmvcasyncasynccontrolleractioninvokerendinvokeactionmethodiasyncresult asyncresult at systemwebmvcasyncasynccontrolleractioninvokerc thisplayclass37c thisplayclass39begininvokeactionmethodwithfiltersb 33 at systemwebmvcasyncasynccontrolleractioninvokerc thisplayclass4finvokeactionmethodfilterasynchronouslyb 49 at systemwebmvcasyncasynccontrolleractioninvokerc thisplayclass37begininvokeactionmethodwithfiltersb 36iasyncresult asyncresult at systemwebmvcasyncasyncresultwrapperwrappedasyncresult1end at systemwebmvcasyncasynccontrolleractioninvokerendinvokeactionmethodwithfiltersiasyncresult asyncresult at systemwebmvcasyncasynccontrolleractioninvokerc thisplayclass25c thisplayclass2abegininvokeactionb 20 at systemwebmvcasyncasynccontrolleractioninvokerc thisplayclass25begininvokeactionb 22iasyncresult asyncresult at systemwebmvcasyncasyncresultwrapperwrappedasyncresult1end at systemwebmvcasyncasynccontrolleractioninvokerendinvokeactioniasyncresult asyncresult at systemwebmvccontrollerc thisplayclass1dbeginexecutecoreb 18iasyncresult asyncresult at systemwebmvcasyncasyncresultwrapperc thisplayclass4makevoiddelegateb 3iasyncresult ar at systemwebmvcasyncasyncresultwrapperwrappedasyncresult1end at systemwebmvccontrollerendexecutecoreiasyncresult asyncresult at systemwebmvcasyncasyncresultwrapperc thisplayclass4makevoiddelegateb 3iasyncresult ar at systemwebmvcasyncasyncresultwrapperwrappedasyncresult1end at systemwebmvccontrollerendexecuteiasyncresult asyncresult at systemwebmvccontrollersystemwebmvcasynciasynccontrollerendexecuteiasyncresult asyncresult at systemwebmvcmvchandlerc thisplayclass6c thisplayclassbbeginprocessrequestb 4iasyncresult asyncresult at systemwebmvcasyncasyncresultwrapperc thisplayclass4makevoiddelegateb 3iasyncresult ar at systemwebmvcasyncasyncresultwrapperwrappedasyncresult1end at systemwebmvcmvchandlerc thisplayclasseendprocessrequestb d at systemwebmvcsecurityutilgetcallinapptrustthunkb 0action f at systemwebmvcsecurityutilprocessinapplicationtrustaction action at systemwebmvcmvchandlerendprocessrequestiasyncresult asyncresult at systemwebmvcmvchandlersystemwebihttpasynchandlerendprocessrequestiasyncresult result at systemwebhttpapplicationcallhandlerexecutionstepsystemwebhttpapplicationiexecutionstepexecute at systemwebhttpapplicationexecutestepiexecutionstep step boolean completedsynchronouslyit works fine from the localhost a google search revealed nothingit also should be noted that i am trying to get this blasted simple membership provider to work on a sql server instead of letting it create a database ps i am on shared hostingedit added the full stack,['c#'] +346478,how to implement a twofinger doubleclick in android i know how to detect a doubleclick and a twofinger touch event but how can i combine these to react so somebody needs to double click with two fingersby default android has the long press to act as a second form of clicking but i am specifically looking for a twofinger doubleclick,['android'] +346481,is there something like a zip function in postgresql that combines two arrays i have two array values of the same length in postgresqlabc and defand i would like to combine them intoadbecfis there a way to do that,['sql'] +346504,is there any way to draw lines with subpixel precision in swing this question has been asked before but the answers do not solve the problem so i ask it again it was suggested that instead of using g2drawline you could use g2drawline where line is a line2ddouble however as you can see from the screenshot the lines are still drawn as if they ended on an integer pixel each set of 10 lines is exactly parallelimport javaxswingimport javaawtimport javaawtgeomline2dpublic class frametestbase extends jframe public static void mainstring args frametestbase t new frametestbase taddnew jcomponent public void paintcomponentgraphics g graphics2d g2 graphics2d g g2setrenderinghintrenderinghintskey antialiasing renderinghintsvalue antialias on for int i 0 i 50 i double delta i 100 double y 5 5i shape l new line2ddouble5 y 200 y delta g2drawl base case with ints looks exactly the same g2drawline5 inty 200 inty delta tsetdefaultcloseoperationexit on close tsetsize220 300 tsetvisibletrue so is it impossible in swing to correctly render lines that do not end exactly on a pixel,['java'] +346507,getting duplicate interface definition error definitely has to import ing header files i am helping on an ios project with lots of methods and definitions common to many different classes in the appdelegate so in each of those classes in the h file i use import appdelegateh this works fine until i need access to one of those classes that already imports the appdelegate into another class that imports appdelegate at this point i get a duplicate interface definition error for appdelegateok so that seems fair i am already importing appdelegate into a file that i am importing so appdelegate is getting imported from two different places so i remove the appdelegate line and everything is finebut what happens when i need to import two classes that both need to import appdelegatei have a very specific problem that i am trying to wrap my head around and i know it is being caused by something that has to do with this but i am not sure what so i am hoping if i figure out how i am supposed to be handling this sort of importing and sort everything else out and hope that this solves my problem so to put this in more concrete termsi have classah classbh and classch all have import appdelegateh when i need to use import classbh in classa i remove the import appdelegateh line from classa everything works smoothly but what happens if i also need to import classch into classa and but classb and classc need to have the import appdelegatehediti tried the exact scenario i described above in a clean project and it built fine so there is something else at play but what i can say with certainty is that when this issue came up previously with this project it was a duplicate interface definition of appdelegate and when i removed the import appdelegateh line the error went away and i still had access to the appdelegateh methods and enums through other imported files,"['objective-c', 'ios']" +346516,german characters in jtextfield i am working on a java application for people learning german and i have run into a problem with the special characters of this language i want to make a subclass of jtextfield that will interpret alt a as a alt o as a and so on while behaving as usual for all ascii characters my attempts so farpublic class germantextfield extends jtextfield implements keylistener public germantextfield init other constructors private void init addkeylistenerthis public void keypressedkeyevent arg0 public void keyreleasedkeyevent arg0 public void keytypedkeyevent evt ifevtgetkeychar o evtisaltgraphdown settextgettext a evtconsume code above does not work germantextfield behaves like standard jtextfield and when i print evtgetkeychar to console this is what i getthis may be due to my own language because alt o produces a3 on my system of course i could have done it like that public void keytypedkeyevent evt ifevtgetkeychar a3 settextgettext a evtconsume but it probably would not work on any systems other than polish my question is is there any solution to this problem that will behave as expected on systems with different language settingsfull solution to this problem based on mvgs answerpackage daswortguiimport javaawteventkeyeventimport javaawteventkeylistenerimport javautilhashmapimport javautilmapimport javaxswingjtextfieldpublic class germantextfield extends jtextfield implements keylistener private mapinteger string transform new hashmapinteger string public germantextfield init public germantextfieldint columns supercolumns init public germantextfieldstring text int columns supertext columns init public germantextfieldstring text supertext init private void init transformputkeyeventvk a aa transformputkeyeventvk u a14a transformputkeyeventvk o aa addkeylistenerthis public void keypressedkeyevent evt ifevtisaltgraphdown string umlaut transformgetevtgetkeycode ifumlaut null int idx evtisshiftdown 1 0 settextgettext umlautcharatidx public void keyreleasedkeyevent arg0 public void keytypedkeyevent evt ifevtisaltgraphdown evtconsume,['java'] +346519,xcode 45 storyboard exit i have just installed xcode 45 for ios6 support and i have seen a new icon called exit in my storyboard listed under my view controllers along with first responder etc a little green icon labeled exiti can find anything on it nor work out how it can be usedanyone know anything about it how it works what its for,"['iphone', 'objective-c']" +346548,what pattern is being done in the globalasaxcs file in aspnet mvc 4 i have never come across this pattern of code right here would anyone care to explain it to me or is there even a pattern here is there a reason why this was done like this what benefits is this giving i am new at general programming and this is a very interesting one to meglobalasaxcs protected void application start arearegistrationregisterallareas webapiconfigregisterglobalconfigurationconfiguration routeconfigregisterroutesroutetableroutes webapiconfigcspublic static class webapiconfig public static void registerhttpconfiguration config configroutesmaphttproute name defaultapi routetemplate apicontrollerid defaults new id routeparameteroptional routeconfigcspublic class routeconfig public static void registerroutesroutecollection routes routesignorerouteresourceaxdpathinfo routesmaproute name default url controlleractionid defaults new controller home action index id urlparameteroptional,['c#'] +346558,how does vlc play videos on the desktop a while back i noticed that vlc has the ability to play videos directly on the desktop when i did so at my school on windows xp it played underneath the icons when i tried at home on windows 7 it hid the icons i am not sure if it is the operating system or if it is an update of vlc but i am interested in playing it underneath the iconsafter noticing this i had an idea to make an animated desktop of sorts nothing special just a few select videos for my own use the idea i started with was to play a video in my own window using mcisendstring and do a printwindow of each frame save it to a file and set the desktop wallpaper as the file i have since lost the specific code but it was not quite working and needless to say would perform horribly coming back to it i realized there must be a much more efficient way than that anyway but i cannot quite grasp what that is i tried all in windows 7 now setting the videos parent window to getdesktopwindow to the effect of minimizing all windows leaving behind a new window on the taskbar playing the video but being able to see the desktop through clicking the aero peek button or hitting windi then tried the same with a parent window of the desktops folder view window the result was the same dimensioned window playing the video but this time the desktop could not be accessed and no new window was created it is like it was playing over top of most of the desktop but the gadgets go over top and the areas toward the right and bottom still show due to the smaller playing window size what does vlc do to play it on the desktop itself looking as if it is a dynamic wallpaper is it significantly harder to make it play underneath the icons and gadgets if you add in windows 7 i suppose the program itself will be used on windows xp i am not sure if directshow has anything that might help but i am willing to use it among other windows api areas besides just mci i would prefer the solution to be in c if it makes a difference net would also work well but might take a bit of extra time working in,['c++'] +346561,how do i make a html input box default text remove after starting to type say i have an input box with default text name in it i would like for the user to click the box the text stays in the box until the user starts to type i am not looking for code to clear the input box after focusing itthanks,['html'] +346568,how to convert unsigned char to qstring i know this is a very basic question but sometimes it happens that you loose your basic concept tried goggling but not enough support on that tooi am using predefined library from one of our device owner they have a declaration as unsigned char familyserialnum08this variable gets the serial number of the device in hexadecimal now i am using this library in qt to thisplay the serial number in qlineedit for that i need to convert it to qstringtried using qstringutf8 strcpy sprintf etc but getting garbage dataso can anyone suggest me some way to get it done,['c'] +346570,application crash on nsindexpath use in ios5 define property section 0define subtotal row 0uitableviewcell subtotalcell selftableview cellforrowatindexpathnsindexpath indexpathforitemsubtotal row insectionproperty sectionwhen i debug it in ios 6 it working perfect but in ios 5 app crashed with following reason terminating app due to uncaught exception nsinvalidargumentexception reason nsindexpath indexpathforiteminsection unrecognized selector sent to class 0x1d41f20 first throw call stack0x26b4022 0x2083cd6 0x26b5aad 0x261aed0 0x261acb2 0xc956a 0xc9d4a 0xca3e9 0x12af38f 0x12af5eb 0x12bdb2b 0x12af38f 0x12af5eb 0x12b04ed 0x121da0c 0x26b5e99 0x121e464 0x121e495 0x12fc1 0x121d14b 0x16864ce 0x162bd61 0x16114d0 0x12ae5ab 0x4ab35 0x14ade29 0x14ad133 0x14ae3bf 0x14b0a21 0x14b097c 0x14a93d7 0x268899e 0x261f640 0x25eb4c6 0x25ead84 0x25eac9b 0x2d167d8 0x2d1688a 0x11e6626 0x248d 0x23b5terminate called throwing an exceptionlldb,"['iphone', 'ios']" +346589,objc retain exc bad access i have been having a bit of a bug while testing on ios 6 with my current ios 5 appwe have experienced a lock up on a method return for an innocuous method that internally used blocks but not as properties the issue is that calling the method works so does every line of code within the method including the block utilizing code i tried using block copy before calling the block but there was absolutely no change,['ios'] +346591,fragmenttransaction not doing anything i am learning fragments and below given is my first fragment program a simple project where i have 2 screens when i click the next button of first screen second button needs to be shown i am targeting android 21 and above and using compatibility packageappmainfragmentactivityjavapublic class appmainfragmentactivity extends fragmentactivity override protected void oncreatebundle arg0 superoncreatearg0 setcontentviewrlayoutapp main layout app main layoutxmlxml version10 encodingutf8linearlayout xmlnsandroid androidlayout widthfill parent androidlayout heightfill parent androidorientationvertical androidididfragment container fragment classcomresearchfragmentstudyfirstfragment androidlayout widthfill parent androidlayout heightfill parent androidididid first fragmentlinearlayoutfirstfragmentjavapublic class firstfragment extends fragment override public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate view view inflaterinflaterlayoutfirst fragment layout containerfalse button nextbutton button viewfindviewbyidridbutton nextbuttonsetonclicklistenernextlistener return view private onclicklistener nextlistener new onclicklistener override public void onclickview v fragmentmanager fm appmainfragmentactivityfirstfragmentthis getactivitygetsupportfragmentmanager secondfragment fragment new secondfragment fragmenttransaction ft fmbegintransaction ftaddridfragment container fragment ftcommit first fragment layoutxmlxml version10 encodingutf8linearlayout xmlnsandroid androidlayout widthfill parent androidlayout heightfill parent androidorientationvertical androidididfirst fragment root textview androidlayout heightwrap content androidlayout widthfill parent androidtextfragment 1 androidgravitycenter horizontal button androidlayout heightwrap content androidlayout gravitycenter horizontal androidlayout widthwrap content androidididbutton androidtextnext linearlayoutsecondfragmentjavapublic class secondfragment extends fragment override public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate view view inflaterinflaterlayoutsecond fragment layout containerfalse return view second fragment layoutxmllinearlayout xmlnsandroid androidlayout widthfill parent androidlayout heightfill parent androidorientationvertical androidididfirst fragment root textview androidlayout heightwrap content androidlayout widthfill parent androidtextfragment 2 androidgravitycenter horizontal linearlayoutwell i am getting the first screen alright nowwhat i expected from my understanding of fragmentwhen i click the next button in screen 1 secondfragment is createdits oncreate and oncreateview gets calledsecondfragment is shown and firstfragment gets destroyed since i amnot adding it to backstack there would not be any animation sincedefault fragment transaction does not have animationwhat is happeningsecondfragment is getting created alright its oncreate and oncreateview gets calledbut firstfragment remains on the screen and second one never showingnow my understanding of fragment can be wrong but i believe when we commit a fragment transaction first fragment should be replaced by second one first one either gets hidden or destroyed well nothing seems to be happening why is that should we manually destroyhide first fragmentnote i know it is a long question for such a basic thing but i put my entire code since i am not sure where i messed it up,['android'] +346602,how are strings passed to sqlalchemys like method i am building an interface on flask using sqlalchemy and part of it is a search api essentially a typeahead input is calling the server with its value for example an email and then the server is performing a sqlalchemy query using like in a filter like belowq sessionqueryuserfilteruseremailliketermallthis query is not really returning anything useful and after the first few characters nothing at all but if i perform the same query with the term hardcoded like soq sessionqueryuserfilteruseremaillikemysearchtermallit will return results perfectly fine so there is something with how i am putting the term into the like method but i really cannot figure out what the issue is the term is coming in from an ajax post and the value is there on the serverside just like is not using it correctlyby nothing useful i mean that the first sets of results coming back have nothing to do with the actual term being inputted after a term of length higher than 34 no results are returned back despite matching items existing in the dbany help greatly appreciated,['sql'] +346606,how do you determine if an sqlite or sqback is corrupt in java i have been given a directory of directories each containing a collection of sqlite and sqback files that i must parsethe problem is that i believe some of these files to be corrupt when i receive them because i get the error err sqlite corrupt the database thisk image is malformed database thisk image is malformedon my console when i try to process them this only happens with some of the files i have isolated a few and tried running my program on fresh copies of these bad files individually and they cause errors most of the files are fine though i realized that there is a chance that i may indeed be given corrupt files to begin with so i would like a way to determine prior to trying to parse them which files are good and which are noti am writing in java i am only interested in the sqlite and sqback validation as i know my parser works i am reusing it from a previous project hint suggestions answersmany thanks for the knowledge transfer,"['java', 'android']" +346653,read an excel file uploaded using fileupload control without saving it on the server need to be able to read an excel file uploaded using fileuploadcontrol in aspnet the solution will be hosted on a server i do not want to store the excel file on the server i would like to directly convert the excel content into a dataset or a datatable and utilizebelow are the two solutions i already found but would not work for melinqtoexcel this method works when you have an excel file on your local machine and you are running your code on the local machine in my case the user is trying to upload an excel file from his local machine using a webpage hosted on a server exceldatareader i am currently using this one but this is a third party tool i cannot move this to our customer also if a rowcolumn intersection is carrying a formula then that rowcolumn intersections data is not being read into the datasetmost of the suggestions i found on google and stackoverflow work when both the excel and the net solution are on the same machine but in mine i need it to work when the solution is hosted on a server and users are trying to upload excel using the hosted webpage on their local machineif you have any other suggestions could you please let me know,"['c#', '.net']" +346679,stringlastindexof bug does anyone know why exceptionlastindexof0 returns 1 wrongwhile exceptionlastindexof returns 2 rightandexceptionlastindexof0 returns 0 rightis this a bug or am i misunderstanding the lastindexofmethod,['c#'] +346711,how to serialize an object collection dictionary into value is there a way to serialize keyvalue pairs preferably strongly typed but possibly also sourced from a dictionary into the desired format belowpublic listidentifier identifiers new listidentifierspublic class identifier public string name get set public string description get set this normally serializes to the followingidentifiers identifier namesomenamename descriptionsomedescriptiondescription identifier identifier identifieridentifiersthe other possible approach we were thinking about is to use a hashtabledictionarypublic dictionarystring string identifiers new dictionarystringstring somename somedescription anothername anotherdescription but this will either require a custom serialized dictionary or a custom xmlwriterthe output we would like to achieve isidentifiers somenamesomedescriptionsomename anothernameanotherdescriptionanothernameidentifiersso were looking for code samples as to how best approach this to get the output we desireedit maybe i should explain better we already know how to serialize objects what we are looking for is the answer to a particular type of serialization i will expand the question above,"['c#', '.net']" +346719,traverse through layers of array using pointer to layer of array 4 4 4 4 3 3 3 4 3 2 2 2 3 2 1 1 1 2 1 1 1 1 1 1 double arr433 1234i consider that this array consists of 4 layersi want to create pointer to layer of array and traverse through layers of that array using pointeri try double pp1sizeofarr0 sizeofar0 pp1 arr0 and get error from intelisensevalue of type double 3 cant be assigned to double9,['c'] +346732,jersey servlet mapping causes 404 error for static resources if i map jerseys urlpattern to in the 20 release it causes 404 for all static resources eg indexhtml my webxml hasservlet servletnamejerseyappservletname servletclassorgglassfishjerseyservletservletcontainerservletclass initparam paramnamejavaxwsrsapplicationparamname paramvalueorgfrogjumpjerseyaparamvalue initparam loadonstartup1loadonstartupservletservletmapping servletnamejerseyappservletname urlpatternurlpatternservletmappinghow do i serve static content with same url pattern,['java'] +346734,how to get clicked cell column in devexpress xtragrid i cannot get column name of clicked cell in gridcontrol of xtragrid how can i do that i am handling gridviewclick event,['c#'] +346796,php finding latitude and longitude boundaries based on a central latlng and thistance i was working with the solution to a very similar question and upon implementation i thiscovered that it was producing a tall rectangle with the returned coordinates instead of a square please see matthias answer to the other questioni only needed an array to be returned as this is to work with wordpress which has it is own preferred query methodheres my implementationfunction bar get nearby lat lng limit 50 thistance 50 unit mi radius of earth note the earth is not perfectly spherical but this is considered the mean radius if unit km radius 6371009 elseif unit mi radius 3958761 latitude boundaries maxlat float lat rad2deg thistance radius minlat float lat rad2deg thistance radius longitude boundaries longitude gets smaller when latitude increases maxlng float lng rad2deg thistance radius cos deg2rad float lat minlng float lng rad2deg thistance radius cos deg2rad float lat max min values array max latitude maxlat min latitude minlat max longitude maxlng min longitude minlng return max min valuesif i give i geocode via google maps api my desired postcode of g2 1qx and a thistance of 5 miles i get a latlng of 42556347558620472 with the function returning this arrayarray max latitude 418326890233 min latitude 4328049767 max longitude 559346130696 min longitude 557894813304any ideas many thanks in advancecheersrobert,['php'] +346834,which membership provider implements users stored in webconfig having a codeblind momentaspnet 40webconfigxml version10configuration systemweb authentication modeforms forms namedataviewer loginurlloginaspx credentials passwordformatclear user namedevuser passwordtest credentials forms authentication authorization deny users authorization systemweband a login control asplogin idlogin runatserver if i enter a username and password and click login it hangsif i break i can see in the call stack that loginauthenticateusingmembershipprovider is in the middle of calling sqlmembershipprovidervalidateuser there is no database defined or involved in this project at all and i have not specified that sqlmembershipprovider should be usedso my question is what membership provider should i use to get aspnet to use the usernames and passwords in the credentials element of webconfig,['asp.net'] +346840,conditional css rules with less based on variable the variable can take percentage or px values likesomevar 50px or somevar 46how can i define a certain set of css rules if the value is in pixels and a different set of rules if the values is in percentagesis there something likeifisvalueinpixelssomevar css rules hereelse other rules here,['css'] +346841,random sqliteconnectionpool error on android how to avoid recently i started to get following error in my application this is not in any specific place and i can reproduce only when loop through all data readwrite functionality it comes up pretty much anywhere0914 085215089 warnsqliteconnectionpool19268 the connection pool for database datadatacomndatabasesdatadb has been unable to grant a connection to thread 1 main with flags 0x5 for 302 seconds connections 0 active 1 idle 0 availableis there any way to avoid this i understand that somehow i exhause all connections to database i am using approach 1 and my database code looks like thispublic class databasehelper extends sqliteopenhelper private final static string log tag comndatadatabasehelper private static final string database name datadb private static final int database version 260 private static sqlitedatabase databaseinstance public databasehelper supermyapplicationme database name null database version public static synchronized sqlitedatabase getdatabase if databaseinstance null databaseinstance new databasehelpergetwritabledatabase return databaseinstance,['android'] +346848,how do i set the default schema for a user in mysql is there a way to set a default schema for each user in mysql and if so how where user x would default to schema y and user z would default to schema a,['mysql'] +346860,how to automatically modify versionname in manifest during build so far i have been focusing on my applications programming and paid little attention to making the build process smarter thus i have been doing things pretty much manually the dumb way including updating by hand androidversioncode and androidversionname in androidmanifestxmli would like now to automatically ie upon build or upon exportfetch from git the latest tagbranch containing build and version codesparse them so that i can assign them to the respective fields in androidmanifestxmlmodify androidmanifestxml accordinglyproceed with the normal build process eclipseadt no ant whatsoever as if i did 123 by handi found a few clues about a prebuild step builders and buildxml but i have no idea where to find those and where to startany tips or pointers on where i could find more information on the subject a stepbystep tutorial would be idealupdate 1 i found this thread to be suggesting that irightclick on the project properties buildersadd a builder that points to the projects ant build fileorder that builder to be invoked before the java builderfine but where is the projects ant build file where do i find it update 2 apparently it is possible to export the entire project into an ant file but i am not sure that is i want must a prebuild step always include an ant build fileupdate 3 is building an ant file only for the prebuild step the right approach,['android'] +346864,eclipse would not start no java virtual machine was found eclipse was running fine yesterday and has been since i installed it about a year ago now all the sudden i am getting the following error on startupa java runtime environment jre or java development kit jdk must be available in order to run eclipse no java virtual machine was found after searching the following locationscprogram fileseclipsejrebinjavawexejavawexe in your current pathi have not changed anyhing eclipsejava related on my machine but a windows update was applied to my machine yesterday so maybe that has something to do with it but i do not see anything that would affect java i have looked at all the other posts about adding something to your path or adding the vm option to the eclipse ini could not get this to work or copying the jre folder to eclipsejre this worked but does not seem like a good long term solution so i am really trying to figure out how to get things back to the default setup without messing stuff upi am running windows 7 eclipse helios and java 160 26,['java'] +346915,eliminate temporary files in visual studio solution folder i am cleaning up a bunch of visual studio projects solutions from different sources and there are an incredible amount of temporary files and temporary folders stored in each solutioni am wondering what file types are safe to delete so that i can write a script to take care of the heavy lifting so there is less junk to push around when i am trying to get the whole folder structure organized and linked up to the proper shared file locationsas far as i can see the following files and folders are temporary and can be safely deletedfilessdfslndocstatessuoupgradelogxmluservcxprojfiltersslnoldsuooldupgradelogxmlwixprojvspscsprojvspsccsccncboptplgapsclwfolders upgradereport files folderipch folderbin obj debug release and other build output folders though there could be files copied into here during buildbackup backup1 etci am not even sure what some of these file types really are i just know they are regenerated when you open the solution and i know there are many more file types that i have missed from older and newer versions of visual studioare there any file types that should be preserved in the list above if so for what reason and are there further file types that can be cleaned out without any serious side effectsthe overall idea is to minimize the size and complexity of the solution when it is to be migrated moved or reorganized or otherwise shuffled around enough for this solution fat to be a serious performance and management problemtypically i see this problem if i need to check something into a new source control system zip and send sample code by email or put third party or peer code into an existing hierarchy of shared folders and files,"['c#', 'c++']" +346965,radial pie menu with raphael js thanks for looking at my dilemma i am trying to make an svg menu with raphael and i am terrible with geometry the below image shows what i am making i already created the blue center part with css but it seems that there is really no other good way to get the white outer part images css kind of fail in this regard due to the block nature of these elements i would like to generate a series of arcs that could range in size depending on the number of elementsso any advice on how to go about getting a series of clickable arcs that form a quarter circle and can have hover effects i am going to want to place icons on these things as well if that mattersi have seen a few examples of using the pie chart in raphael and i just do not see how to adapt it ugh i should have paid attention in geometrythanks for your time,"['jquery', 'html', 'css']" +346992,accessing clicked element in angularjs i am relatively new to angularjs and suspect i am not grasping a concept i am also using twitter bootstrap and i have got jquery loadedworkflow user clicks a link from a list master section is updated and link user clicked on gains active classbasic html markupul classlistholder ngcontrolleradmincontroller lia ngclicksetmasterclientclientsli lia ngclicksetmasteremployeesemployeesli lia ngclicksetmasteretcetcliuldoing this in jqueryjquerylistholderonclick a functionevent eventpreventdefaultjquerylistholder liremoveclassactivejquerythisparentliaddclassactivebut i cannot figure out how to integrate angular and jquery to get this done because i am using angular to fetch the master list in json form from the server and update a list on the pagehow do i integrate this i cannot seem to find the element i have clicked on once i am inside the angular controller functioncontrollerfunction admincontrollerscope scopesetmaster functionobj how do i get clicked elements parent li consolelogobj,['jquery'] +347017,nsfetchedresultscontroller does not see new inserts removes fetched values after update after reading dozens of similar questions i would like to start with this statement i did set the delegate of the nsfetchedresultscontroller it did not workso i have a simple tableviewcontroller whose cells are filled with nsfetchedresultscontroller heres the frc init codeproperty strong nonatomic nsfetchedresultscontroller frc nsfetchedresultscontroller frc if frc nserror error nil nsfetchrequest request nsfetchrequest alloc initwithentitynamee product requestsortdescriptors nsarray arraywithobjects nssortdescriptor sortdescriptorwithkeyproduct groupproduct group name ascendingyes nssortdescriptor sortdescriptorwithkeyf product name ascendingyes nil frc nsfetchedresultscontroller alloc initwithfetchrequestrequest managedobjectcontextdtgglobalsettings sharedinstancemoc sectionnamekeypathproduct groupproduct group name cachenamenil frcdelegate self frc performfetcherror if error nslogerror while fetching products erroruserinfo return frci also have nsfetchedresultscontroller delegate methods implemented with some debugging labels voidcontrollerwillchangecontentnsfetchedresultscontroller controller the fetch controller is about to start sending change notifications so prepare the table view for updates nslogcontrollerwillchangecontent selftableview beginupdates voidcontrollernsfetchedresultscontroller controller didchangeobjectidanobject atindexpathnsindexpath indexpath forchangetypensfetchedresultschangetypetype newindexpathnsindexpath newindexpath uitableview tableview selftableviewswitchtype case nsfetchedresultschangeinsert nslogdidchangeobject insert tableview insertrowsatindexpathsnsarray arraywithobjectnewindexpath withrowanimationuitableviewrowanimationfade break case nsfetchedresultschangedelete nslogdidchangeobject delete tableview deleterowsatindexpathsnsarray arraywithobjectindexpath withrowanimationuitableviewrowanimationfade break case nsfetchedresultschangeupdate nslogdidchangeobject update self configurecelltableview cellforrowatindexpathindexpath atindexpathindexpath break case nsfetchedresultschangemove nslogdidchangeobject move tableview deleterowsatindexpathsnsarray arraywithobjectindexpath withrowanimationuitableviewrowanimationfade tableview insertrowsatindexpathsnsarray arraywithobjectnewindexpath withrowanimationuitableviewrowanimationfade break voidcontrollernsfetchedresultscontroller controller didchangesectionid sectioninfo atindexnsuintegersectionindex forchangetypensfetchedresultschangetypetype switchtype case nsfetchedresultschangeinsert nslogdidchangesection insert selftableview insertsectionsnsindexset indexsetwithindexsectionindex withrowanimationuitableviewrowanimationfade break case nsfetchedresultschangedelete nslogdidchangesection delete selftableview deletesectionsnsindexset indexsetwithindexsectionindex withrowanimationuitableviewrowanimationfade break voidcontrollerdidchangecontentnsfetchedresultscontroller controller the fetch controller has sent all current change notifications so tell the table view to process all updatesnslogcontrollerdidchangecontentselftableview endupdatesin my navigationbar i have the refresh button its function is to fire up the product catalog method who does the following1 fetches products from remote mysql server2 if the product with id does not exists creates it and fills all the fields3 if it exists all the fields are updated according to the fetched valuesafter row 2 and 3 the store is savedi use single nsmanagedobjectcontext for all coredata operations across the appwhen i start the app for the first time tvc is empty because there was no products fetched yet when i press refresh the new products are fetched and inserted into managedobjectcontext but nsmanagedobjectcontext does not seehear any changes no delegate methods are called so no new rows are added to tvcwhen i restart the app the new products are in place fetched into tvc with no problemif i press refresh button once again when there are some products there after short delay they all thisappear some debugging showed me that if happens after updating the fields of the entities actually values are the same and saving the store delegate methods this time work like a charm and for every updated and saved entity controllerdidchangeobjectatindexpathforchangetypenewindexpath is called with forchangetype nsfetchedresultschangedeletequestion 1 why nsfetchedresultscontroller does not see inserted entities without app restartquestion 2 why nsfetchedresultscontroller marks already fetched entities as non existing and removes them from tvc after store savei would appreciate any help and ideas being fighting with this issue for whole last week upd1 for jodyhere are some details i use custom class dtgglobalsettings to share some vars across the app that is how i init its sharedinstance propertydtgglobalsettings sharedinstance static dtgglobalsettings myinstance nil if nil myinstance myinstance self class alloc init set values here try to acces moc to init coredata myinstance moc myinstancebaseurl return myinstanceto init coredata stack i used an example from apple documentation because for some reason i do not see the checkbox use coredata when creating a new project i am sure that i have seen it before in xcode but now i do not xcode 441pragma mark core data stack nsmanagedobjectcontext moc if moc nil return mocnspersistentstorecoordinator coordinator self persistentstorecoordinatorif coordinator nil moc nsmanagedobjectcontext alloc init moc setpersistentstorecoordinator coordinatorreturn moc nsmanagedobjectmodel managedobjectmodel if managedobjectmodel nil return managedobjectmodel managedobjectmodel nsmanagedobjectmodel mergedmodelfrombundlesnil return managedobjectmodel nspersistentstorecoordinator persistentstorecoordinator if persistentstorecoordinator nil return persistentstorecoordinatornsurl storeurl nsfilemanager defaultmanager urlsfordirectorynsdocumentdirectory indomainsnsuserdomainmask lastobjectstoreurl storeurl urlbyappendingpathcomponentdoc namenserror error persistentstorecoordinator nspersistentstorecoordinator alloc initwithmanagedobjectmodel self managedobjectmodelif persistentstorecoordinator addpersistentstorewithtypenssqlitestoretype configurationnil urlstoreurl optionsnil errorerror nslogerror adding a store to the coordinator error erroruserinfo return persistentstorecoordinatorvoidsavedatastore nserror error if selfmoc saveerror nslogunresolved error error error userinfothe moc managedobjectcontext property of dtgglobalsettings is then used everywhere in the app where i need access to coredatanow to the second part updating the database i am getting some new entities in json format from remote webserver going through the resulting dictionary and calling createfromdictionary method for each entity found in request results heres the codeproduct createfromdictionarynsdictionary entitydata incontextnsmanagedobjectcontext moc performupdateboolupdateproduct resultif update nsfetchrequest request nsfetchrequest alloc initwithentitynamee product requestpredicate nspredicate predicatewithformatk f product id entitydata objectforkeyf product id result dtgglobalsettings sharedinstancemoc executefetchrequestrequest errornillastobject if result nslogerror updating product id cannot fetch entity entitydata objectforkeyf product id return nil else result nsentitydescription insertnewobjectforentityfornamee product inmanagedobjectcontextdtgglobalsettings sharedinstancemocresultproduct id dtgglobalsettings sharedinstancenumformatter numberfromstringentitydata objectforkeyf product idresultproduct image nsdata datawithcontentsofurlnsurl urlwithstringdtgglobalsettings sharedinstancebaseurl stringbyappendingstringentitydata objectforkeyf product imageresultproduct name entitydata objectforkeyf product namereturn resultwhen i run out of fethed entities i call dtgglobalsettings sharedinstance savedatastore see above at this point the existing rows in tvc if there were any thisappearing in case if i was adding some new entities at the point of save nothing happens ie tvc does not update its rows,['ios'] +347021,html5 formdata file upload with rubyonrails i using this script to upload file one by one with html5 formdata in rails 328 applicationuploader inputfileonchange function this this alertremove eachthis0files functionkey file filesappendli filename li data new formdata dataappendfilename file ajax url uploaderattraction contenttype multipartformdata type post datatype json data data processdata false but when i upload a file i get this error in consolewebrickserverrb191in block in start thread error argumenterror invalid encoding filenamejpeg contenttype imagejpeghow can i solve this error,['ruby-on-rails'] +347069,determining the current state of a cell i know that a subclass of uitableviewcell can implement willtransitiontostate and execute custom code at the time of transition but is there any way to find the current state of a cellif not should i subclass uitableviewcell and define a property currentstate which i always update in my willtransitiontostate i will then always have a way to know the state of any particular cellseems strange that i cannot ask a cell what its current state is 0 1 2 or 3,['ios'] +347071,how can make bootstraps horizontal form labels smaller with css bootstrap has a lot of examples for types of forms i am interested in using the horizontal form which looks like thisthis is what it looks like after outlining some elements with the web inspector toolbari am working inside of a popup modal and space is already a bit tight i tried adding bootstraps grid systems span1 and span2 to the labels as a class but it is not giving the desired behavioris there a way to use some other aspect of bootstrap to get the desired behavior ie tighten up the amount of space that labels on a horizontal form take up what is the proper way to do this i am using bootstrap version 21,['css'] +347077,missing dotnetopenauthapplicationblock in openidoauth i am implementing openidoauth in my aspnet webform using net framework 35 application found example on net topicdotnetopenidxqyke6suzyubut i am missing dotnetopenauthapplicationblock namespace i included these libraries in my projectdotnetopenauthdlldotnetopenauthoauth2dlldotnetopenauthoauth2clientdllcan any one suggest me where i am doing wrong,"['c#', 'asp.net']" +347132,testing directory exist with rspec i am testing libpdf helperrb so i create speclib directory then i create a file pdf helper specrb in speclib directory as i am testing that pdf folder should be in public folder and here is my coderequire spec helperrequire pdf helper describe pdfhelpers do it should be in public folder do file filenew railsrootpublicpdf if fileexistfile true puts success else putsfailed end end endam i right i am new on rspec,"['ruby-on-rails', 'ruby']" +347149,block home button in ice cream sandwich and jelly bean i am developing lock screen where i want to thisable home button in ice cream sandwich and in jelly bean i can block it using following methods in android 22 23 overridepublic void onattachedtowindow todo autogenerate method stub thisgetwindowsettypewindowmanagerlayoutparamstype keyguard superonattachedtowindowalso tried this getwindowsettypewindowmanagerlayoutparamstype system alerthere i am also not getting event info via onpause method or onkeydownbut these methods donet work for me in icsjelly bean if is there any method that can replace it then let me know,['android'] +347155,how to filter only my application log in intellijs logcat on intellij i am trying to read the logcat for seeking errorsthe problem is that all the applications log are present in the android windowhow to only thisplay the log that is relevant i am not looking for tags since i want to view exception throws segfaults from jni etcthanks,['android'] +347192,how to intercept packets sent by a application and check what they have i would like to know how can i intercept packets sent by a certain application and then to check what those packets containi need some advice what to do because i never did that i want to learn for myself,['c#'] +347225,select records from postgres where timestamp is in certain range i have arrival column of type timestamp in table reservations i am using postgres how would i select all dates within this year for examplei know i could do something like thisselect from reservations where extractyear from arrival 2012but i have ran analyze and it looks like it require a sequence scan is there a better optionps 1 hmm both ways seem to require seq scan but the one by wildplasser produces results faster whycmm explain analyze select from reservations where extractyear from arrival 2010 query plan seq scan on vrreservations cost016578 rows14 width4960 actual time02134509 rows49 loops1 filter date partyeartext arrival 2010double precision total runtime 5615 ms3 rowscmm explain analyze select from reservations where arrival 20100101 0 and arrival 20110101 0 query plan seq scan on reservations cost016578 rows51 width4960 actual time01262491 rows49 loops1 filter arrival 20100101 0timestamp without time zone and arrival 20110101 0timestamp without time zone total runtime 3144 ms3 rows ps 2 after i have created index on arrival column second way got even faster since it looks like query uses index mkey i guess i will stik with this one query plan bitmap heap scan on reservations cost47710127 rows51 width4960 actual time03590791 rows49 loops1 recheck cond arrival 20100101 0timestamp without time zone and arrival 20110101 0timestamp without time zone bitmap index scan on arrival idx cost0476 rows51 width0 actual time01770177 rows49 loops1 index cond arrival 20100101 0timestamp without time zone and arrival 20110101 0timestamp without time zone total runtime 1265 ms,['sql'] +347251,how can i troubleshoot mysql lock timeout errors with rails all of a sudden without any changes to related code we are getting lock errors through active record such asactiverecordstatementinvalid mysql2error lock wait timeout exceeded try restarting transaction update items set state reserved updated at 20120915 175821 where itemsid 248220and activerecordstatementinvalid mysql2error lock wait timeout exceeded try restarting transaction delete from sessions where sessionsid 41997883we are not doing our own transactions in either of these models so the only transactions are the built in rails ones there has not been a surge in traffic or request volumethese errors appear to be when a new query tries to run on a locked table and has to wait how do we see what it is waiting for how do we figure out which part of our code is issuing queries that lock the tables for extended periods of timeany ideas on where we can look or how to investigate the cause of this,"['mysql', 'ruby-on-rails']" +347264,create a json object in javascript i am in process to validate a form where i need to show certain radio buttons and user need to select them based on some ruleshow many number of radio buttons can be created is dynamic so i can not do validation on server side not can write a predefined javascript code for thateach of the radio buttons will be divided in to groups say required and than further down they can be grouped like centerleft right etc so from each group user need to select one value so the structure comes out like thismain group if block needs to validate based on this eg if keyrequired should validate subgroup say left right etc number of radio buttons based on the subgroupso the main group key can be used to decide if validation should be done on that or not and based on the subgroup key i can decide what all values will be there and needs to be validatei was planning to create a json object on page rendering time likerequired center id1id2id3 left id1id2id3 optional center id1id2id3 left id1id2id3 i am not sure if the structure i am thinking is right and how to create it in java scriptlike i have a external loop for key and than one more loop for the subgroup and finally for the buttons in the subgroup formain group key forsubgroup key forlist of radio button under subgroup key but not sure how to create a right structure so that i can parse it later with jquery and use that for validationany help in this will really be appreciated,"['javascript', 'jquery']" +347284,using jquerys on function how do i get the originating element for the event i had code like thisremovegroupclickfunction thisclosesttrremovethis worked fine until i needed to use delegated event handler to capture clicks for elements that will be added to the page in the futuredocumentonclick removegroup function thisclosesttrremovethis no longer works because the this keyword does not refer to the originating elementany ideasupdateit would seem that in my efforts to simplify the code for my question i actually made it work i was actually passing in a wrapped set that was assigned to a variable instead of the string selectorvar removegroup removegroupdocumentonclick removegroup function thisclosesttrremovethat does not seem to work when i do it that way,"['javascript', 'html', 'jquery']" +347310,how to parse a string without regular expressions i am currently trying to create a software component that would be able to interprete dynamic strings such asto lowerdelete whitespacesa sample textwhich would result in this stringasampletexti would like to be able to define a set of available functions with semantical parameters etci already know more or less how to do it using regular expressionsmy questions areis lexingparsing way better than regexp for such a purpose or should i just go with regexp and forget about thatdoes such a library already exist in javado you know any tutorial showing some sample parsinglexing algorithmsthanks,['java'] +347317,performance swapping integers vs double for some reason my code is able to perform swaps on doubles faster than on the integers i have no idea why this would be happeningon my machine the double swap loop completes 11 times faster than the integer swap loop what property of doublesintegers make them perform this waytest setupvisual studio 2012 x64cpu core i7 950build as release and run exe directly vs debug hooks skew thingsoutputprocess time for ints 1438 secsprocess time for doubles 0125 secsinclude iostreaminclude ctimeusing namespace stddefine and 20void swap iint x int y int tmp x x y y tmpvoid swap ddouble x double y double tmp x x y y tmpint main int a 1 b 2 double d 10 e 20 itime dtime clock t c0 c1 time int swaps c0 clock for int i 0 i n i swap ia b c1 clock itime doublec1c0clocks per sec time double swaps c0 clock for int i 0 i n i swap dd e c1 clock dtime doublec1c0clocks per sec cout process time for ints itime secs endl cout process time for doubles dtime secs endlit seems that vs only optimized one of the loops as blastfurnace explained when i thisable all compiler optimizations and have my swap code inline inside the loops i got the following results i also switched my timer to stdchronohigh resolution clockprocess time for ints 1449 msprocess time for doubles 1248 ms,['c++'] +347353,what is the use of movetofirst in sqlite cursors i am a programming newbieand i found this piece of code in the internet and it works finecursor cdbquerydatabasetb name new string databasekey rowiddatabasekey rate databasekey rowid 1 null null null null ifcnull cmovetofirst but i am not able to understand the use of theifcnull cmovetofirst part what does it do exactly and if i remove theifcnull cmovetofirst part the code does not work,['android'] +347357,thismissmodalviewcontrolleranimated deprecated i have just upgraded to xcode 45 to update my ios app to run on the 4 inch thisplay for the iphone 5 but i am getting a build error saying thismissmodalviewcontrolleranimated is deprecated on the lineself thismissmodalviewcontrolleranimatednoi have tried updating to the recommended overload with a completion handler but set to null like thisself thismissmodalviewcontrolleranimatedno completionnullbut then this line throws two errorswarning tabbarcontroller may not respond to presentmodalviewcontrolleranimatedcompletioninstance method presentmodalviewcontrolleranimatedcompletion not found return type defaults to idthanks,['ios'] +347368,focus input element with jquery but the cursor does not appear i want to focus an input element when a div is clickedmy html looks like thisdiv classplaceholder input input typetext idusername maxlength100 div classplaceholder container div classplaceholderusernamediv divdivand my script isusernamefocusfunction thisnexthideplaceholder inputmousedownfunction thischildrenfirstfocuswhen i click into the textbox the placeholder text thisappears correctly but the blinking cursor does not show in the textbox and i cannot type any text into the textboxinside of the mousedown event handler the thischildrenfirst expression selects the correct input element so i have no idea why the focus call does not work,"['javascript', 'jquery', 'html']" +347387,sqlalchemy would not update my database i am making a pyramid app using sqlalchemy078 i am using 64bit python32the question is why does the following function not commit anything to the databasedef create cardstextscard create a wildcard instance if all is well iescard match in stext return ocard dcard otherwise return falsefalse omatch researchscardstext if omatch ocard wildcard set up some stuff about the wildcard dbsessionaddocard dbsessionflush dcard id ocardid span omatchspan card ocardcard string return ocarddcard return falsefalse i import dbsession form another script it is defined as followsdbsession scoped sessionsessionmakerextensionzopetransactionextensionheres some background infothe app i am making is to be used to characterize large blocks of html through use of regular expressions if the app gets stuck and thinks there should be a wilcard match for a piece of text then the user is given a little form to fill in once the form is committed create card is called if the wildcard is matched against the string then a wildcard instance is createdthe wildcard class is nothing special it just stores a string and a few integers if i print out dcard it looks like the wildcard was sucessfully committed because it has an integer id if i do not call flush on the database session then dcardid is nonethe id field looks likeid columnintegersequencewild seq primary keytruethe add and flush lines cause the following console output20120916 123034845 info sqlalchemyenginebaseenginedummy2 insert into wildcard wildcards card string range id brand id category id group cat map id heading group id heading to grp map id heading id value map id igneore match values 20120916 123034845 info sqlalchemyenginebaseenginedummy2 scard contents none none none none none none none none 0so up until this point everything is behaving pretty as is expectedheres the problemeven though the wildcard instance looks like it has been committed to the database and no exceptions are raised direct examination of the database shows that no changes are madereplacing flush with commit raises the following exceptionassertionerror transaction must be committed using the transaction manager,['python'] +347406,how to compare multidimensional arrays in c how to compare multidimensional arrays just truefalsedouble data1 new double 1 2 3 4 5 6 7 8 double data2 new double 1 2 3 4 5 6 7 8 bool compare data1sequenceequaldata2is there way to compare 2d arrays like 1d array data1sequenceequaldata2 i have to compare every second so easiest way will be great thanks a lot,['c#'] +347411,how to detect iphone 5 widescreen devices i have just upgraded to xcode 45 gm and found out that you can now apply the 4 retina size to your view controller in the storyboardnow if i want to create an application that runs on both iphone 4 and 5 of course i have to build every window twice but i also have to detect whether the user has an iphone with 35 or 4 screen and then apply the viewhow should i do that,"['iphone', 'ios', 'objective-c']" +347415,php date format remove time and more possible duplicateconvert one date format into another in php starting fromdate 20120909 030900i would like to do two thingsremove the time from the string so it will become 20120909calculate how many years days and hours have passed since this dateusing the server current datetimetimezonecould anyone help me figure this out,['php'] +347498,reload content in modal twitter bootstrap i am using twitter bootstraps modal popup div idmymodal classmodal hide fade in div classmodalheader a classclose datathismissmodalaa h3headerh3 div div classmodalbodydiv div classmodalfooter input typesubmit classbtn btnsuccess valuesave divdivi can load content using ajax with this aelementa datatogglemodal datatargetmymodal hrefeditaspxopen modalanow i have to open the same modal but using a different url i am using this modal to edit an entity from my database so when i click edit on an entity i need to load the modal with an id a datatogglemodal datatargetmymodal hrefeditaspxid1open modalaa datatogglemodal datatargetmymodal hrefeditaspxid2open modalaa datatogglemodal datatargetmymodal hrefeditaspxid3open modalaif i click on link number 1 it works fine but if i then click on link number 2 the modal content is already loaded and therefor it will show the content from link number 1 how can i refresh or reset the ajax loaded content in a twitter bootstrap modal popup,['javascript'] +347500,handling failures with either where is the stacktrace i heard from some people that in scala we tend like other functional languages to not break the control flow instead by convention we return the error in an either leftbut how do we get the stracktrace from that exceptionfor now i return in the left a simple error case class with a code message and cause error too but if i have an error i cannot get the stacktraceif my application become complexe it may be hard to find the code block that returned that error the root cause is essentialso what do we do in practice should i return instead of a custom error the java type exception or throwable in my left whats the best practice for scala exception handling without loosing important informations such as the stacktrace and the cause,['java'] +347501,python randomsetstate seed is there guarantee of same results across implementations is there guarantee that pyhon2python3 script with random generator initialized with randomsetstate or randomseed will produce same sequence of pseudorandomness across different versions and platforms for example python 31 on mac the same as python 32 on linux 64bitquestion is about both python2 and python3 with assumption that python3 scripts will run on python3 interpreters and vice versa,['python'] +347512,why is it so easy to decompile java code so i have just realized how easy it is to decompile my java code i have been searching around the net and i cannot seem to figure out why its so easy every time i google something like why can i decomilple class files or why does java decompile so easily all i get is links to software that can easily deompile my code so i turn to you stackoverflow why is it that java can be converted back to easlily readable source code while c and other languages are not very friendly to decompilingthanks,['java'] +347514,jade set base directory depending on environment i have a jade page and the first thing i do is set a variable which determines the base directory used by all linksif base base klog base websiteclearklogthis is actually for a github page so every time i render the page to html i have to remember to change the base and then change it back again for local editingthere must be a better way of doing it currently i am thinking to have an untracked file in the local copy that includes the base but is that really necessarywhat is the best way to handle this issue,['javascript'] +347554,switch between php versions on os x mountain lion is it possible to have multiple versions of php installed on os x mountain lion and freely change between them similar to the way mamp allows you to i am wanting to get out of using mamp and this is really the only feature holding me back,['php'] +347568,cython nesting a union within a struct in cython glue declarations how do i represent a c struct type containing an anonymous union for example if i have a c header file mystructh containingstruct mystruct union double da uint64 t ia then in the corresponding pyd filecdef extern from mystructh struct mystruct what goes herei tried thiscdef extern from mystructh struct mystruct union double da uint64 t iabut that only gave me syntax error in c variable declaration on the union line,"['python', 'c']" +347587,is grouptableviewbackgroundcolor deprecated on ios 6 i was just testing my app with ios 60 and xcode 45gm and i have set up a view like thisselfview setbackgroundcoloruicolor grouptableviewbackgroundcolorso the view has the same pattern than a common table viewthis works fine on ios 4 and 5 but in ios 6 it just gives me a white backgroundis this deprecated if so how can i replace itthanks,['ios'] +347589,try to get ussd response in android i want to find a way to get response from ussd codes i have already found these links android implementing ussd features binding a service to the phoneutils without restarting the phone on every update andhleni found so many related questions about getting ussd response but there was no complete answers for questionsi am using sony ericsson xperia rayi only found the pop up message on the phone screen i did not get any response code from background,['android'] +347590,what is passive data structure in androidjava from the android developer web link you can find that it says it intent is basically a passive data structure holding an abstract description of an action to be performed but i do not understand what is passive data structure could anyone help to explain it thanks,"['java', 'android']" +347612,concatenate item in list to strings is there a simpler way to concatenate string items in list into a single stringcan i use the strjoin function to join items in listeg this is the input thisisasentence and this is the desired output thisisasentencesentence thisisasentencesent str for i in sentence sent str stri sent str sent str1print sent str,['python'] +347633,cannot reinitialise jquery datatable i am using jquery datatables to thisplay data inside grid on init page load script take datetimetoday and process them further problem is after init page load when i am trying to take users input date for further process i am having following error datatables warning table id datatable cannot reinitialise datatableto retrieve the datatables object for this table pass no arguments or see the docs for bretrieve and bdestroyfunction getdate var date inputnamemydateval return datemydateclickupdatedatefunction updatedate datatabledatatable bserverside true sajaxsource homeajax fnserverparams function aodata var date getdate aodatapush name mydate value date there is moreupdatedatescript is put on the bottom of the page,"['javascript', 'jquery']" +347634,generate java class from xml file using xstream i have many xml files and i would like to use xstream to manage them is it possible to generate java classes corresponding to my xml files using xstream,['java'] +347649,are cursor urls relative to the css file i know paths are supposed to be relative to the css file but that does not seem to be the case for an image that i am trying to use as a cursorthe file structure is contentsitecsscontentimagesbutteryflyanicontentimagesuserpngsitecss butterfly cursor urlimagesbutterflyani pointer this worksuiiconuser backgroundimage urlimagesuserpng important backgroundposition 0 0it works if i change it tobutterfly cursor urlcontentimagesbutterflyani pointer why does not the relative url work for the cursor edit does not work in chrome firefox or ie9 in all browsers it thisplays the hand cursor instead of the custom oneedit2 to follow up how do i actually get this to work on my site as the html pages sit at different levels is there a way to specify a relative url somehow in css or should i just put a copy of the cursor at the same level as each page which sucks,['css'] +347657,how to specify spacing between elements of linearlayout only once i recently ran into a problem again that i already had several times in the last years linearlayout is a very convenient layout manager but what i totally miss is the possibility to add a certain space between the elements like padding in a single xml tag what i mean by one tag is that i can define in the declaration of the linearlayout the spacing between the elements eg in a vertical linearlayout the vertical space between two elements in this layout i know that i can do it by adding the xml tag androidlayout margintop or something similar to every element in the linearlayout but i would like to be able to define it in only one point as the spacing is the same for all elements does anybody know an easy way to do this not implementing a custom linearlayout or something like that i prefer a solution that works directly in xml without the need for coding,['android'] +347706,zend framework 2 need php version 533 they declare php version533 however in its code something like trait which was introduced in 54 appear everywherei am confused,['php'] +347709,for each link where href equals myvalue why is the following not changing the text to it workedjavascriptjqueryaeachfunctioni ifiattrhref mywebsitecouk iinnerhtml it worked htmla hrefmywebsitecoukadebugging it does not seem to pick up the href valueattr but i may be getting it all wrong can someone please make sure i have the above correctly done,"['jquery', 'html']" +347739,reading numbers as text format with phpexcel i have an array that can store numbers in such as 01 01a 01b 02 2 and when i get this value using phpexcel it is being removed the 0s in case of 01 02 for example to solve this problem i tried to format the row where these values will be stored in excel and set it as text type just like in the following code objphpexcelsetactivesheetindexbynameblockslist objphpexcelgetactivesheetfromarrayblocknames null a2 latestblcolumn objphpexcelgetactivesheetgethighestdatacolumn column a row 1 for column a column latestblcolumn column objphpexcelgetactivesheetgetstylecolumnrowgetnumberformatsetformatcode phpexcel style numberformatformat text objphpexcelgetactivesheetfromarrayblocknames null a1so by doing this i get the array with numbers like 01 01a 02 02b and i store it in the row a2 i get the highest column to use this value in the condition for in this condition i set for the row 1 in the range a until the highest column to be formated as text my template is generated and all the numbers are in text format but the problem is that i think when i use the fromarray method it transforms the numbers of the array before i can get it right in exceldo you have any idea of how can i solve this problem,['php'] +347771,embed java applet through url data i am trying to explore url data capabilities to embed in html java appletthe documentation for html tags to instantiation a java applet 1 do not exclude this option but i do not seem to be able to to thisi have different variations of html tags values using object and applet and what i think came close to my goal was thisobject typeapplicationxjavaapplet width100 height100 param namearchive valuedataapplicationjavaarchivebase64base64 of jar param namecode valuetestclass h1not workingh1objectthis variation result in an ilegalargumentexception with text name i check this clicking on the error icon on the browser on the java console the whole stack trace isjavanetmalformedurlexception unknown protocol data at javaneturlinitunknown source at javaneturlinitunknown source at sunpluginutilprogressmonitoradaptersetprogressfilterunknown source at sunplugin2appletplugin2managersetupprogressunknown source at sunplugin2appletplugin2managerappletexecutionrunnablerununknown source at javalangthreadrununknown sourcedoes anyone have an idea about how to do this or if it is not possibleps there is an example of how to embed an jnlp in html by oracle here,"['java', 'html']" +347784,mastering event bubbling lets say we have a html structure like thisdiv idcontainer div idnested span idsomeelementspan divdivand our goal is to have an event listener on the container only so we bind a listener jquery codecontaineronclick functionevent alertcontainer was clickedthat works of course but my problem with this approach is that since events usually bubble up that listener will also fire if we actually click on nested or someelement my current solution to only handle the click when the container is clicked is to compare this with eventtargetcontaineronclick functionevent ifthis eventtarget alertcontainer was clicked my question is that considered best practice is there a better way with jquery to accomplish the same result out of the box example in action,"['javascript', 'jquery']" +347846,rotated text using courier font not thisplayed in opera i have the following htmldiv classboxtextdivaand cssbox nonessential thisplay inlineblock margin 2em background plum essential transform rotate45deg fontfamily courieraand this is the fiddle i have omitted the prefixes here but they are in the fiddleexpected resultit is also the result i get in chrome firefox ie9 safarihowever in opera it looks like thisif i take out the transform that is the div is not rotatedanymore then the text is shownif i replace the font with another one then the text is shownso why is this happening and what other solutions do i havein case this helps,['css'] +347858,how can i import a csv file via a rake task i know this question has been asked a lot on this forum but i am under a strict deadline and i need some help so any advice is much appreciated i am new to ruby on rails so please keep that in mind when responding i want to create a rake task that when run updates multiple tables in mysqlite db this is a migration file that creates a new incident in my db how do i create a rake task that will input all this info via a csv file can someone please give me some help in writing the rake file from start to finish obviously you do not need to write every task for every string just give me a few examples and besides the actual rake file do i need to add code to any other part of my app i know thats a very general question but if i do need to add code i would appreciate a general description of where i am sorry for the newbie question but i feel a little bit of guidance will go along way so thank you to anyone that responds if anyone needs any more information from me please just ask thank you this forum has helped me a lot in the past but this is my first time postingclass createincidents activerecordmigrationdef selfupcreate table incidents do t tdatetime incident datetime tstring location tstring report nr tstring responsible party tstring area resident tstring street tstring city tstring state tstring home phone tstring cell phone tstring insurance carrier name tstring insurance carrier street tstring insurance carrier city tstring insurance carrier state tstring insurance carrier phone tstring insurance carrier contact tstring policy nr tstring vin nr tstring license nr tstring vehicle make tstring vehicle model tstring vehicle year ttimestampsendenddef selfdown drop table incidents endend,['ruby-on-rails'] +347860,how do arrays implement ilist without implementing the property count in c for a very long time i was curious about the followingint array new int1int iarraylength arraylength 1since arrays implement the ilist interface the following is allowedint iarraycount ilistintarraycount still 1butint iarraycount arraycount compile error whyint iarraylength arraylength this is what we learned at schoolthe questionhow can an array implement ilistt especially the int count get property from ilistt without allowing it to be used on the base class,['c#'] +347869,jquery parallax scrolling effect multi directional i need to build a multidirectional jquery parallax page for a client they basically want it to work in a similar way to this i have the artwork ready and have found many jquery libraries that will allow me to scroll horizvertical but i am not sure how to combine both together at a specific coordinate could anyone please point me in a the right directionedit i did originally sign this post off having looked into superscrolarama and thinking all was solved but having struggled with implementing it i dont think its quite the saviour i thought it was i need both horizontal and vertical parallax as well as scrolling to achieve above which it does not seem to support so any other tips i would be very grateful for,"['javascript', 'jquery']" +347886,default value for required fields in entity framework migrations i have added required data annotation to one of my models in aspnet mvc application after creating a migration running updatedatabase resuilts in the following errorcannot insert the value null into column director table movies cf7bad808fa94f89afa2e5dae1161e78dbomovies column does not allow nulls update fails the statement has been terminatedthis is due to some records having null in their director columns how can i automatically change those values to some default say john doe directorhere is my model public class movie public int id get set required public string title get set datatypedatatypedate public datetime releasedate get set required public string genre get set range1100 datatypedatatypecurrency public decimal price get set stringlength5 public string rating get set required new public string director get set and here is my latest migrationpublic partial class adataannotationsmig dbmigration public override void up altercolumndbomovies title c cstringnullable false altercolumndbomovies genre c cstringnullable false altercolumndbomovies rating c cstringmaxlength 5 altercolumndbomovies director c cstringnullable false public override void down altercolumndbomovies director c cstring altercolumndbomovies rating c cstring altercolumndbomovies genre c cstring altercolumndbomovies title c cstring,['c#'] +347898,what to do first feature selection or model parameters setting this is more of a theoretical question i am working with the scikitlearn package to perform some nlp task sklearn provides many methods to perform both feature selection and setting of a model parameters i am wondering what i should do firstif i use univariate feature selection it is pretty obvious that i should do feature selection first and with the selected features i then tunne the parameters of the estimator but what if i want to use recursive feature elimination should i first set the parameters with grid search using all the original features and just then perform feature selection or perhaps i should select the features first with the estimators default parameters and then set the parameters with the selected featuresthanks in advance for any help you could give meediti am having pretty much the same problem stated here by that time there was not a solution to it does anyone know if it exists one now,['python'] +347934,issue with character encoding in post requests sent with firefox recently i have come across some very strange behavior related to character encoding for ajax calls made using the post methodto make a long story short i have an html form with text fields that can accept diacritics eg a when the form is submitted the form data is wrapped in an xml block and sent to a server which stores that information in a mysql database subsequently that information is retrieved from the database and thisplayed to regular users as isif the request is sent from chrome or ie everything is fine this means that the data including the diacritics is sent stored then retrieved and thisplayed correctly however when i use firefox for this the xml appears to submit the form data right but when i reload the web page the previously sent diacritics do not appear in other words they seem to get lost somewhere along the way for example if the xml contains the word tasta when i load the page i see tst why is this happening is firefox encoding the post messages differently from ie and chromein case it helps i have attached the request and response headers from chrome and firefox for exactly the same form content only one exampleby the way i am not encoding the data before sending it to the server just simply retrieving the value of the form fields as ischromethe xml data blockrequestsessionhidden by mesessionbuilderhem i stan taastaabuilderrequestthe request headersacceptacceptcharsetiso88591utf8q07q03acceptencodinggzipdeflatesdchacceptlanguageenusenq08connectionkeepalivecontentlength562contenttypeapplicationxwformurlencodedcookiephpsessidrlne2d787j0np52ec5rtn04dm1host8315087220originrefererhttpuseragentmozilla50 windows nt 61 wow64 applewebkit5371 khtml like gecko chrome210118089 safari5371xrequestedwithxmlhttprequestthe response headersconnectionkeepalivecontentencodinggzipcontenttypeapplicationxmldatemon 17 sep 2012 162158 gmtkeepalivetimeout5 max100serverapache2211 win32 php5291transferencodingchunkedvaryacceptencodingfirefoxthe xml data blockrequestsessionhidden by mesessionbuilderhem i stan tastabuilderrequestthe request headersaccept acceptencoding gzip deflateacceptlanguage enusenq05connection keepalivecontentlength 562contenttype applicationxwformurlencoded charsetutf8cookie phpsessidkvfg4fp2trorllim19dmn241c7host hiddenbymereferer useragent mozilla50 windows nt 61 wow64 rv140 gecko20100101 firefox1401xrequestedwith xmlhttprequestthe response headersconnection keepalivecontentencoding gzipcontenttype applicationxmldate mon 17 sep 2012 162123 gmtkeepalive timeout5 max100server apache2211 win32 php5291transferencoding chunkedvary acceptencoding,['javascript'] +347963,facebook like button in webview with sdk i am trying to implement facebook like button which is not part of android facebook sdk using webview the idea is very simple i use sdk to log into user account using sso so user do not need to type loginpassword again if user is already logged in android fb app then i want to use webview to insert standard like buttoni already have user auth token permission for sending status on the wall etc the problem is how to tell webview that user is already signin i was trying to use webview with enabled js with this url webviewloadurl generated by fb sendfalselayoutbutton countwidth450show facestrueactionlikecolorschemelightfontheight21appidmyid token mfacebookgetaccesstokenexpiresmfacebookgetaccessexpires or auth token insteadbrobviously this is wrongor is not enought to send autorization in this way because after click on like button user is redirected to login page in web browserso the question is how to edit this url or how to set cookies what to set to url in cookiemanager and which cookies in webview to sign user inthanks for any help,['android'] +347987,slider inside google map info window problem i am trying to integrate a slider carousel inside an info window of google map1 jquery code for the sliderhead script srcjsjqueryanythingsliderjsscript script set up sliders function myslideranythingslider mode f fade mode new in v18 resizecontents false if true solitary imagesobjects in the panel will expand to fit the viewport expand true navigationsize 3 set this to the maximum number of visible navigation tabs false to thisable onslidebegin functioneslider keep the current navigation tab in view slidernavwindow slidertargetpage script head2 html code this is how would the slider work inside a regular html page div stylewidth450pxheight150px ul idmyslider id corresponds to id used in jquery code li content of slide 1 li li content of slide 2 li li content of slide 3 li ul divnow i do not have much experience with javascript so how do i make the jquery code accessible inside an info window in other words where should i put he slider code edit this is what i tried so far but no luckfunction defining variables that need to be available to some functionsvar map infowindowwindowonload function creating a map var options zoom 3 center new googlemapslatlng3709 9571 maptypeid googlemapsmaptypeidroadmap map new googlemapsmapdocumentgetelementbyidmap options adding a marker to the map var marker new googlemapsmarker position new googlemapslatlng40756054 73986951 map map title click me googlemapseventaddlistenermarker click function add some content to userli1 var userli1 lisome awesome content for the 1st list itemli add some content userli2 var userli2 lisome awesome content for the 2nd list itemli check to see if an infowindow already exists if infowindow infowindow new googlemapsinfowindow setting the content of the infowindow to the detail map infowindowsetcontentdetaildiv infowindowsetcontentdiv style width450pxheight150pxul idmyslider userli1 userli2 uldiv opening the infowindow infowindowopenmap marker initiate slider here myslideranythingslider mode f fade mode new in v18 resizecontents false if true solitary imagesobjects in the panel will expand to fit the viewport expand true navigationsize 3 set this to the maximum number of visible navigation tabs false to thisable onslidebegin functioneslider keep the current navigation tab in view slidernavwindow slidertargetpage when i run the code the jquery does not get triggered at alledit 2 solution i solved the problem by using mcmaster code and wrapping the relevant jquery code with googlemapseventaddlistenerinfowindow domready function so this is the entire code documentreadyfunction runs jquery when document is readyfunction initialize var mapdiv documentgetelementbyidmap map new googlemapsmapmapdiv zoom 3 center new googlemapslatlng3709 9571 maptypeid googlemapsmaptypeidroadmap infowindow new googlemapsinfowindow content holding looks for map when tiles are loaded fire function addmarkers googlemapseventaddlisteneroncemap tilesloaded addmarkersfunction addmarkers var lat 3709 var lng 9571 var latlng new googlemapslatlng lat lng var marker new googlemapsmarker position latlng map map add some content to userli1 var userli1 lisome awesome content for the 1st list itemli add some content userli2 var userli2 lisome awesome content for the 2nd list itemli set marker content markerhtml div style width450pxheight150pxul idmyslider userli1 userli2 uldiv add listener googlemapseventaddlistenermarker click function infowindowsetcontentmarkerhtml infowindowopenmap marker initialize googlemapseventaddlistenerinfowindow domready function initiate slider here myslideranythingslider mode f fade mode new in v18 resizecontents false if true solitary imagesobjects in the panel will expand to fit the viewport expand true navigationsize 3 set this to the maximum number of visible navigation tabs false to thisable onslidebegin functioneslider keep the current navigation tab in view slidernavwindow slidertargetpage,"['javascript', 'jquery']" +348016,how to exclude classes from an opencover report in generating coverage reports with opencover and then generating an html report with reportgenerator for an mstest suite i am trying to exclude framework generated classes in particular classes generated under the projects namespace by a service referencethe command i am using to generate the xml files looks likeopencoverconsoleexe registeruser targetmyprojecttestsdll targetargstestcontainermycontainer outputcoveragexml mergebyhash filterawebservicei have also tried to exclude by fileopencoverconsoleexe registeruser targetmyprojecttestsdll targetargstestcontainermycontainer outputcoveragexml mergebyhash excludebyfilereferencecs but the service reference classes still show up in the xml fileis there a way to exclude only those specific classes generated by visual studio,['c#'] +348017,how to thisplay the tabs inline in the action bar is there any way to instead of icons and labels of activities thisplay the tabs i would like to have done it but could not find any solution i am trying thisplay the navigation tabs inside the activity bar not under at a vertical thisplay orientation portrait i looked android library actionbarsherlock an example of styled but there are tabs thisplay exactly the same as in the standard packageexamples of activity bar portrait orientationstandard thisplay the tabs in the activity bar e example section 1 section 2 section 3 an example of how it would look like activity bar without icon and label with tabs inside e tab 1 tab 2 tab 3 it would be great if someone could tell me how i can implement this in the range versions 22 to 40 please help me with this problem,['android'] +348026,is the hash necessary in svg fontface declarations fontface fontfamily allerregular src urlfontsalleraller rgwebfonteot src urlfontsalleraller rgwebfonteotiefix formatembeddedopentype urlfontsalleraller rgwebfontwoff formatwoff urlfontsalleraller rgwebfontf formattruetype urlfontsalleraller rgwebfontsvgallerregular formatsvg fontweight normal fontstyle normalin the example above i am adding an svg version of this font but i am not sure the id is correct if there is only one font included in this svg is it necessary to have the correct id,['css'] +348038,why urlliburlopenread does not correspond to source code i am trying to fetch the following webpageimport urlliburlliburlopenorderauthorcatalog01searchaction1readthe result does not correspond to what i see when inspecting the source code of the webpage using google chrome for examplecould you tell me why this happens and how i could improve my code to overcome the problemthank you for your help,['python'] +348045,determine if javascript ekeycode is a printable noncontrol character i would just like to know the ranges of javascript keycodes that correspond to typeable characters or alternatively the range of nontypeable control characters like backspace escape command shift etc so i can ignore themthe reason i ask is calling stringfromcharcode is resulting in odd characters for control keys for example i get for left command for left arrow weirdness like that,['javascript'] +348050,how to process image pixelbypixel with winapi in a fast way so i make some simple imageprocessing program with gui c for example i want to change image colors in hsv color model converting each pixel from rgb and back againmy program loads some picture by user choice and shows it in one of forms panel using its graphics context then user can do something with this picture by moving scrollbars clicking buttons selecting some image area etc when he do that i need in realtime change all the picture pixelbypixel so i write something likefor int x 0 x imagewidth x for int y 0 y imageheight y color c ggetpixelx y c some process color function depending on user controlsc gsetpixelx yand even if i work with graphics in memory not on the screen functions getpixel and setpixel works very slow so as my program works so slow i profiled it and explained that these two functions are slowing down my program at most so i cannot process big pictures in a few time as user moving slider or checking checkboxplease help what can i do to make my program be fast i nay agree to use other thirdparty libraries for graphics or change programming language,"['c#', '.net']" +348058,python way to speed up a repeatedly executed eval statement in my code i am using eval to evaluate a string expression given by the user is there a way to compile or otherwise speed up this statementimport mathimport randomresult count 10expression mathsinvx vyvariable dictvariablex randomrandom for in xrangeresult countvariabley randomrandom for in xrangeresult count optimize anything below this lineresult 0 result countprint evaluating d instances of the given expression result countprint expressionv dictfor index in xrangeresult count for name in variablekeys vname variablenameindex resultindex evalexpression option one resultindex mathsinvx vy option twofor a quick comparison option one takes 2019 seconds on my machine while option two takes only 0218 seconds surely python has a way of doing this without hardcoding the expression,['python'] +348068,specify publish version with msbuild command line as assembly version of project i have a simple batch file that i am running from a dos command line that is used for building a small c application that publishes a clickonce project one line is thismsbuild myappcsproj tpublish propertypublishdirdeploythis currently publishes the application but it uses the publish version that i set up in visual studios publish tab i am hoping to be able to set the publish version at the command line and specifically i would like to use the assembly version of the project something likemsbuild myappcsproj tpublish propertypublishdirdeploy propertypublishversionprojassemblyversioni am hoping to do without creating a custom task since this is just an interim solution and i will replace it with a more proper build system lateralternatively i have looked at updating the published manifest version using the mage command line tool with the update flag but i did not know how to retrieve the assembly version number from the project or built assembly without using powershell or some program that would need to be downloaded if i could use something that comes with visual studio that would work as well,['.net'] +348111,getting ruby 187 installed on mountain lion 108 i am having a lot of trouble getting ruby 187 installed on my clean install of mountain lion i have looked around on stack overflow and do not see anything that specifically addresses this issue and hope that someone might have encountered this beforei am using the command line tools that can be downloaded with xcodei have not had any problems installing ruby 193 via rvm and homebrew when i try to install 187 i get the following message after it tries to compile i first ran the commandrvm install 187this gave me this errorthe provided compiler usrbingcc is llvm based it is not yet fully supported by ruby and gems please read rvm requirementsafter digging around a bit i tried rvm install 187 withgclangerror running make please read userspaulzaichrvmlogruby187p370makelogthere has been an error while running make halting the installationruby ruby187p370 was built using clang but it is not fully supported expect errorsplease be aware that you just installed a ruby that requires 2 patches just to be compiled on up to date linux systemthis may have known and unaccounted for security vulnerabilitiesplease consider upgrading to ruby 193194 which will have all of the latest security patchesat this point i did some more searching and found something about needing compile my own readline rvm does not install ruby 192 on snow leopard error running make this unfortunately seemed to corrupt my entire rvm install including 193 i tried to reinstall 193 and got the same errors i as i was getting with 187 i completely deleted rvm at this point and reinstalled had no problem installing 193 againi also tried updating all versions of rvm based off of this post rvm issue with mountain lion no luck there either update i also tried using this walkthrough for ree 187 which recommended installing gcc42 no luck unfortunately update 2 i reference rvm requirements and installed the following packagesbrew updatebrew tap homebrewdupes brew install autoconf automake applegcc42 rvm pkg install opensslso far so good then i referenced this post on needing to reference the gcc compiler i determined that the links referenced might not be correct because i am using homebrew i found the compiler in my cellar folder and used the following commandccusrlocalcellarapplegcc42421563bingcc42 rvm install 187no luck same error messages as before,['ruby'] +348119,confusion on yuv nv21 conversion to rgb according to nv21 is the default used formatthere are quite a number of code on web regarding yuv nv21 to rgb conversion however when i go through the code i doubt on the correctness of the codethe first component v should come first followed by first component uaccording to nv21 is like nv12 but with you and v order reversed it starts with v however when i went through the code implementation it assumes you comes first it assumes you comes first too it assmes you comes first toor should be the most significant positionaccording implementation of int argb in colorjava r suppose to be at the most significant position however i went through the following code implementation it assumes r is in least significant position it assumes r is in least significant positioni was wondering are they making common mistake or i have overlooked something currently my implementation is as followpublic static void yuv nv21 to rgbint argb byte yuv int width int height final int framesize width height final int ii 0 final int ij 0 final int di 1 final int dj 1 int a 0 for int i 0 ci ii i height i ci di for int j 0 cj ij j width j cj dj int y 0xff int yuvci width cj int v 0xff int yuvframesize ci 1 width cj 1 0 int you 0xff int yuvframesize ci 1 width cj 1 1 y y 16 16 y int r int 1164f y 16 1596f v 128 int g int 1164f y 16 0813f v 128 0391f u 128 int b int 1164f y 16 2018f u 128 r r 0 0 r 255 255 r g g 0 0 g 255 255 g b b 0 0 b 255 255 b argba 0xff0 r 16 g 8 b,['android'] +348131,underscore js extend method looks like underscore library would not treat functions in json as first class citizens why does not this fiddle work var a f1 functionvar ssuccess var b foo barvar c extendb aalertjsonstringifycvar d extendname moe age 50alertjsonstringifydwhy is not c the right value d seems to have the right value if we only use strings as keys and valueshow can i get around this limitation,['javascript'] +348151,combine two sql queries on one table i have a tablea with different values data 10 15 20 40 40 50 60also i need to get some statistic information on that data and i want to do it in one query for exampleselect countdata from tablea where data 100union allselect countdata from tablea where data 100as result i receive no column name43but i want to receive results in one row like thissmall big4 3 how to do it is it possible,['sql'] +348159,how to draw custom window controls close minimize and zoom buttons i have made an attempt to draw custom nsbuttons but it seems i am reinventing the wheel here is there a way to just replace the default images used for the close minimize and zoom buttonsseveral apps already do itosx 108s reminders app they appear dark grey when the window is not key vs most appear light greytweetbot all buttons look totally custommore infoi can generate the system defaults as such standardwindowbuttonnswindowclosebutton but from there the setimage setter does not change the appearance of the buttons,['objective-c'] +348167,frequently http 500 internal error with google drive api drivefilesget we have a service which highly depends on google drive uses python sdk got from our service goes through google drive collections and fileschecked production log we found there are many http 500 server internal errors when we call google drive api drivefilesget the http 500 error rate about 05 when i did investigation the extreme case is continuous 9 http 500 failure in one hour with drivefilesget apibtw our service is hosted on amazon web service us west2 data center any one has similar issue any help are appreciated exception call stack like below file homexstoragepy line 1185 in get file gdrive file selfclientfilesgetfileid0bxn2gmqxr4zhylnvaulfnjl6mke fieldsidtitlemodifieddatecreateddatefilesizemimetypedownloadurllabelsexecute file usrlibpython27thistpackagesapiclienthttppy line 389 in execute raise httperrorresp content selfuri httperror altjson returned internal error,['python'] +348184,cxf rest apis documentation using swagger according to swaggers tutorial seems swagger only support jersey framework see does anybody have experience on making swagger work with cxf jaxrs implementation could you share your suggestions here,['java'] +348188,what vs debugger does so that increment operator performs faster than doing nothing here is the selfexplanatory code performing an operation a billion timesint k 0stopwatch sw new stopwatchswstartfor int a 0 a 10 a for int b 0 b 10 b for int c 0 c 10 c kswstopconsolewritelineswelapsedmillisecondssw new stopwatchswstartfor int a 0 a 10 a for int b 0 b 10 b for int c 0 c 10 c noopswstopconsolewritelineswelapsedmillisecondsthe results are at least on my computer somewhere around in milliseconds21682564the second is always about half a second longerhow is it possible that incrementing a variable a billion times runs longer than doing a noop the same number of timesedit this happens only on debug release does this correctly the first one lasts longer at least on my computer as pointed in comments someone experienced this problem even in release build but what happens on debug that creates this effect,"['c#', '.net']" +348217,signalr and httpcontextsession i understand why signalr does not give you access to the httpcontext however this is quite problematic for us let me explainour application is a multitenant application where the user chooses the environment while logging in this basically registers the connectionstringname in the httpsession in our signalr hub we need to access the database on thisconnect but this is not possible because we have no httpcontext at this point and cannot determine the environment to write tocan anyone provide us with a suggestion how to solve this problem were a bit stuck on this oneedit bonus point if your solution works in a loadbalanced environment,['asp.net'] +348231,how should i escape commas and speech marks in csv files so they work in excel i am generating a csv file delimited by commas rather than tabs my users will most likely open the csv file in excel by double clicking it my data may contain commas and speech marks so i am escaping those as followsreference title description1 my little title my description which may contain speech marks and commas2 my other little title my other description which may also contain speech marks and commasas far as i know that is always been the way to do it heres my boggle when i open this file in excel 2010 my escaping is not respected speech marks appear on the sheet and the comma causes new columns,['java'] +348232,is there any ways to detect the roaming status on ios 6 my application using below methods to detect roamming in ios 4 and 5 nsstring carrierplistsymlinkpath varmobilelibrarypreferencescomapplecarrierplist nsstring operatorplistsymlinkpath varmobilelibrarypreferencescomappleoperatorplist nsfilemanager fm nsfilemanager defaultmanager nserror error nil nsstring carrierplistpath fm destinationofsymboliclinkatpathcarrierplistsymlinkpath errorerror nsstring operatorplistpath fm destinationofsymboliclinkatpathoperatorplistsymlinkpath errorerrorreturn operatorplistpath isequaltostringcarrierplistpath but this code always return false on ios6 even i am not roaming it always return false i think it maybe the plist file location changed by apple does any one face the same issue can anyone help me on thisthanks,['ios'] +348235,how to convert string date to long millseconds i have a date inside a string something like 12december2012how can i convert this into milliseconds long,"['java', 'android']" +348254,antialiasing in textureview i tried to play the same video with a surfaceview and a textureview and noticed that the image rendered with the textureview is more aliased less smooth than with the surfaceviewwhat is the reason for this is there any way to configure rendering of textureview to look better the textureview is used like this textureview textureview new textureviewthis textureviewsetsurfacetexturelistenernew surfacetexturelistener override public void onsurfacetextureavailablesurfacetexture surfacetexture int width int height logitest onsurfacetextureavailable mediaplayer player mediaplayercreatetestactivitythis uriparsevideo url surface surface new surfacesurfacetexture playersetsurfacesurface playerstart override public void onsurfacetextureupdatedsurfacetexture surface logitest onsurfacetextureupdated override public void onsurfacetexturesizechangedsurfacetexture surface int width int height logitest onsurfacetexturesizechanged override public boolean onsurfacetexturedestroyedsurfacetexture surface logitest onsurfacetexturedestroyed return false setcontentviewtextureviewand for the surfaceview surfaceview surfaceview new surfaceviewthis surfaceviewgetholderaddcallbacknew callback override public void surfacecreatedsurfaceholder holder logitest surfacecreated override public void surfacedestroyedsurfaceholder holder logitest surfacedestroyed override public void surfacechangedsurfaceholder holder int format int width int height logitest surfacechanged mediaplayer player mediaplayercreatetestactivitythis uriparsevideo url playersetsurfaceholdergetsurface playerstart setcontentviewsurfaceview,['android'] +348267,opensource thistribued cache for java what is the best open source thistributed cache that can be used in javai thought it was ehcache but apparently it can be scaled on multiple nodes only when using terracotta server array which is a commercial productmy goal is to build caches for streaming data in realtime with a certain delay and my actual estimated size of the data lies is in the order of 8gb while the production rate is much slower in the order of 3mb per secondsince there is an initial delay i would like my cache also to be replicated because when starting from 0 my cache would require a warm up period which i am seriously interested in avoiding,['java'] +348299,prevent thispatch after background task from being executed this is my issue when my application enters background i want it to perform a function after certain period of time this is what i do voidapplicationdidenterbackgrounduiapplication application isrunninginbackground yes taskidentifier uiapplication sharedapplication beginbackgroundtaskwithexpirationhandlernil int64 t delayinseconds 30 thispatch time t poptime thispatch timethispatch time now delayinseconds nsec per sec thispatch afterpoptime thispatch get global queuethispatch queue priority default 0 void self dosomething voiddosomething nsloghellotaskidentifier variable is declared in myappdelegateh file like thisuibackgroundtaskidentifier taskidentifiereverything works as it supposed to i see that console prints hello just right after 30 seconds are gone but i do not want dosomething to be executed if the app enters foreground until 30 seconds are over so i need to cancel it this is how i do that voidapplicationwillenterforegrounduiapplication application isrunninginbackground no self stopbackgroundexecution voidstopbackgroundexecution uiapplication sharedapplication endbackgroundtasktaskidentifier taskidentifier uibackgroundtaskinvalidbut unfortunately it does not cancel dosomething it is still performed what am i doing wrong how do i cancel that function,['ios'] +348303,how can i use action voice search hands free in android 41 i am trying to use action voice search hands free in android 41i use this wayintent intent new intentrecognizerintentaction voice search hands freeintentputextrarecognizerintentextra secure truestartactivityforresultintent record codeit works fine with action recognize speech but with action voice search hands free i has thisandroidcontentactivitynotfoundexception no activity found to handle intent actandroidspeechactionvoice search hands free has extras how can i use action voice search hands free,['android'] +348319,how can an sql query return data from multiple tables i would like to know the followinghow to get data from multiple tables in my databasewhat types of methods are there to do thiswhat are joins and unions and how are they different from one another when should i use each one compared to the othersi am planning to use this in my for example php application but do not want to run multiple queries against the database what options do i have to get data from multiple tables in a single querynote i am writing this as i would like to be able to link to a well written guide on the numerous questions that i constantly come across in the php queue so i can link to this for further detail when i post an answerthe answers cover off the followingpart 1 joins and unionspart 2 subqueriespart 3 tricks and efficient codepart 4 subqueries in the from clausepart 5 mixed bag of johns tricks,"['mysql', 'sql']" +348350,manually create framework from static library i have question about creating framework manually from static library for example libraryname i tested this solutioncreated folder librarynameframeworkcreated subfolder librarynameframeworkheaders and copied headers from source libraryrenamed librarynamea to file librarynameframeworklibrarynameand it is working under xcode but i have question is it good way to do it like this regards adam,"['objective-c', 'ios']" +348371,security header is not valid using paypal sandbox in net i am using the paypal sandbox in aspnet c 40 i added the following web references when i run this codepaypalapihelperpaypalsandboxwssetexpresscheckoutreq req new paypalapihelperpaypalsandboxwssetexpresscheckoutreq setexpresscheckoutrequest new paypalapihelperpaypalsandboxwssetexpresscheckoutrequesttype version version setexpresscheckoutrequestdetails reqdetails query paypal and get token paypalapihelperpaypalsandboxwssetexpresscheckoutresponsetype resp buildpaypalsandboxwebservicesetexpresscheckoutreqin my resp object the error message sayssecurity header is not validi was told to give it correct api credentials i signed up on developerpaypalcom and i am assuming the email address and password i used are my valid credentials how and where do i give it my api credentials thanks,['c#'] +348374,is there any documentation for building xcode 4 plugins recently i have noticed a couple of projects on github that extend the functionality of xcode 4 via pluginstwo projects as examples by olemoritz minixcode changes the main toolbarcolorsense provides overlays to help pick coloursboth projects are installed into libraryapplication supportdevelopersharedxcodeplugins and xcode just picks them up are there any sources of documentation officlal or user generated on extending xcodeedit ping olemortiz,['ios'] +348402,how to set dialogfragments width and height i specify the layout of my dialogfragment in an xml layout file let us call it layout mydialogfragmentxml and its layout width and layout height attributes particularly to be 100dp each let us say i then inflate this layout in my dialogfragments oncreateview method as followsview view inflaterinflaterlayoutlayout mydialogfragment container falseunfortunately i find that when my dialog dialogfragment appears it does not respect the layout width and layout height specified in its xml layout file and my dialog shrinks or expands variably depending on content anyone know whether or how i can get my dialog to respect the layout width and layout height specified in its xml layout file at the moment i am having to specify the width and height of my dialog again in my dialogfragments onresume method as followsgetdialoggetwindowsetlayoutwidth height and thus undesirably have to remember to make any future changes to the dialogs width and height in two places,['android'] +348443,given a torrent file how do i generate a magnet link in python i need a way to convert torrents into magnet links would like a way to do so in python are there any libraries that already do this,['python'] +348469,where to put user defined functions in angular js in my view i want to renderp say pwhere say is defined as such say function return hello worldi can define it in my controllerfunction testctrlscope scopesay function but then it is only accessible within that controllerif i define the function outside the angular file structure it renders nothing same if i define it in my controllersjs file but outside a controller function scopewhere is the proper place to put my function so i can render it in any controller,['javascript'] +348476,jquery validation plugin check if field is valid but not show the validation message i am using jquery validation plugin and have defined a form validation function as shown below based on some user action i am running a custom js function and in that function i just want to check whether the email and phone fields are valid but i do not want to validate them ie i do not want to show the validation errors i just need to check if their value is validsomething likeemailisvalidi have checked out the element method of validator but that validates the element rather than just checking if it is value is valid so in other words i am looking for a way to run the rules programmatically any help is appreciatedform validator function belowvar validator olformvalidate rules email required true email true phone required true digits true minlength 9 maxlength 11,['jquery'] +348531,default date 0 0 or null is it better practice to use default date 0 0 or null on mysql databasei have read best to use default date 0 0 for the reason of calculationsie than a date less than a datealso on time best to store 0 or null if time not known,['mysql'] +348535,is faster than full thisclosure i was inspired by is xa quicker than xxathat aside i decided to test vs simple tests reveal they are about the same then i tried something similar tostdvectorint xfor int i 0 i 10 i xpush backrand10and call and proportionally to a given numberlong long sum 0for each number in the array if xj k sum xj else sum xjso if k is say small would get called more often duh i tried with k 2 which would give a higher proportion of called and with k 5 which should yield about the same number of and the punchline calling is about twice as faster than calling why would it be more efficient in this case,['c++'] +348568,adb how to reinstall an app without retaining the data adb install fooapkwhen using this command if the apk exists i should get the error failure install failed already exists adb install r myappreleaseapkin this casethe existing apk will be replaced by retaining old dataaccording to the docs r means reinstall the app keeping its datanow how do i reinstall the app but all previous data should be erasedediti know we can do thisadb uninstall compackagefoo adb install fooapki just wanted to know if there is a command or something in adb itself,['android'] +348590,scipy and scikitlearn valueerror dimension mismatch i use scipy and scikitlearn to train and apply a multinomial naive bayes classifier for binary text classification precisely i use the module sklearnfeature extractiontextcountvectorizer for creating sparse matrices that hold word feature counts from text and the module sklearnnaive bayesmultinomialnb as the classifier implementation for training the classifier on training data and applying it on test datathe input to the countvectorizer is a list of text documents represented as unicode strings the training data is much larger than the test data my code looks like this simplifiedvectorizer countvectorizerkwargs sparse matrix with training datax train vectorizerfit transformlist of documents for training vector holding target values classes either 1 or 1 for training documents this vector has the same number of elements as the list of documentsy train numpyarray1 1 1 1 1 1 1 1 1 1 1 1 1 sparse matrix with test datax test vectorizerfit transformlist of documents for testing training stage of nb classifierclassifier multinomialnbclassifierfitxx train yy train prediction of log probabilities on test datax log proba classifierpredict log probax testproblem as soon as multinomialnbpredict log proba is called i get valueerror dimension mismatch according to the ipython stacktrace below the error occurs in scipypathtomycodepyc 177 x log proba classifierpredict log probax testsklearnnaive bayespyc in predict log probaself x 76 in the model where classes are ordered arithmetically 77 78 jll self joint log likelihoodx 79 normalize by px pf 1 f n 80 log prob x logsumexpjll axis1sklearnnaive bayespyc in joint log likelihoodself x 345 calculate the posterior log probability of the samples x 346 x atleast2d or csrx 347 return safe sparse dotx selffeature log prob t 348 selfclass log prior 349 sklearnutilsextmathpyc in safe sparse dota b dense output 71 from scipy import sparse 72 if sparseissparsea or sparseissparseb 73 ret a b 74 if dense output and hasattrret toarray 75 ret rettoarrayscipysparsebasepyc in mul self other 276 277 if othershape0 selfshape1 278 raise valueerrordimension mismatch 279 280 result self mul multivectornpasarrayotheri have no idea why this error occurs can anybody please explain it to me and provide a solution for this problem thanks a lot in advance,['python'] +348701,why the entry point address in my executable is 0x8048330 0x330 being offset of text section i wrote a small program to add to integers and on using readelf a executable name it showed the entry point address in elf header as entry point address 0x8048330how my executable knows this address beforehand even before loader loads it in memory elf formatpdf says this member gives the virtual address to which the system first transfers control thus starting the process can anyone please explain what is the meaning of this statement and what is the meaning of virtual address here also let me know from where the executable file gets the value of 0x8048330 as entry point address just for cross check i compiled another program and for that also the entry point address remains the same value 0x8048330 offset of text section being 0x330 in both the cases,['c'] +348712,is there a modern list of websafe fonts if they are on an ancient browser let them burn,"['html', 'css']" +348743,get all jobs in quartznet 20 i have setup my adojobstore on the server and all my jobs are running perfectly now i am writing a remote client to manage all my jobsscheduling new jobs is straightforward enough but i cannot seem to retrieve a list of existing jobs in version 20 all the resources i found did something like the followingvar groups schedjobgroupnamesfor int i 0 i groupslength i string names schedgetjobnamesgroupsi for int j 0 j nameslength j var currentjob schedgetjobdetailnamesj groupsi the problem i am facing is that getjobnames has been removed and looking at the source code has been moved to the base class jobstoresupport which jobstorecms inherits from the method has however been marked as protected so it is inaccessible from the outsidehow would one go about retrieving a job list in 20,['c#'] +348760,ef 5 sql ce 4 how to specify custom location for database file i am developing a client system that needs a small local databasei want to avoid installation of sql express and have decided to go with sqlce 4i use entityframework 5 for data access and have created my custom contexteverything works fine in development where i can use appconfig to either set specific file location or dynamic data sourcedatadirectorymydatabasesdfbut on deploy i want the database to be located in the users documents folder my documentsapplicationnamemydatabasesdfhow can i do thatall i need is actually to be able to set custom connection string in codethis is what i tried so farprivate myapplicationdatacontextstring connectionstring baseconnectionstringpublic static myapplicationdatacontext createinstance var directory environmentgetfolderpathenvironmentspecialfoldermydocuments var path pathcombinedirectory applicationnamemydatabasesdf var connectionstring stringformatprovidersystemdatasqlserverce40provider connection stringdata source0 path var connectionstring stringformatdata source0 path return new myapplicationdatacontextconnectionstringas you can see i tried two kinds of connection strings but both caused exceptionskeyword not supported providerandthe provider did not return a providermanifesttoken string,['c#'] +348849,what does travisci actually do in php development i am new to opensource project some projects which i browse use travis i have read the manual but still cannot get what actually this travis ci doing could anyone explain it or give some links,['php'] +348893,class path contains multiple slf4j bindings my application server ibm webspherei am getting the following error in the application server logswhere can i websphere settings19092012 145654940 eest 0a systemerr r slf4j class path contains multiple slf4j bindings 19092012 145654940 eest 0a systemerr r slf4j found binding in wsjarfileclibslf4jlog4j12161jarorgslf4jimplstaticloggerbinderclass 19092012 145654941 eest 0a systemerr r slf4j found binding in bundleresource217fwk3735691orgslf4jimplstaticloggerbinderclass 19092012 145654941 eest 0a systemerr r slf4j see bindings for an explanation,['java'] +348913,pendingintent scheduled using alarmmanagerrtc type is still invoked in the sleep mode here is the code that i used to set an alarm for my widget private static void setalarmcontext context intent myintent new intentcontext widgetclass myintentsetactionauto update pendingintent pendingintent pendingintentgetbroadcastcontext 0 myintent pendingintentflag update current alarmmanager alarmmanager alarmmanager contextgetsystemserviceservicealarm service calendar calendar calendargetinstance calendarsettimeinmillissystemcurrenttimemillis calendaraddcalendarsecond 8 alarmmanagersetinexactrepeatingalarmmanagerrtc calendargettimeinmillis 80 pendingintent but the problem is that even in the sleep mode onreceive is still triggered by the intentalthough after using setinexactrepeating instead of setrepeating the delays between calls get increased up to 1 minute in sleep mode but that is still battery consuming,['android'] +348924,how to junit test that two list contain the same elements in the same order contexti am writing a simple junit test for the myobject classa myobject can be created from a static factory method that takes a varargs of stringmyobjectofcomponentsuno dos tresat any time during the existence of myobject clients can inspect the parameters it was created by in the form of a liste through the getcomponents methodmyobjectofcomponents liststring uno dos tres in other words a myobject both remembers and exposes the list of parameters that brought it into existence more details about this contractthe order of getcomponents will be the same as the one chosen for object creationduplicate subsequent string components are allowed and retained in orderbehaviour on null is undefined other code guarantees no null gets to the factorythere are no ways to alter the list of components after object instantiationi am writing a simple test that creates a myobject from a list of string and checks that it can return the same list via getcomponents i do this immediately but this is supposed to happen at a thistance in a realistic code pathcodehere my attemptliststring argumentcomponents listsnewarraylistone two threeliststring returnedcomponents myobjectofcomponents argumentcomponentstoarraynew stringargumentcomponentssize getcomponentsasserttrueiterableselementsequalargumentcomponents returnedcomponentsquestionis google guava iterableselementsequal the best way provided i have the library in my build path to compare those two lists this is something i have been agonizing about should i use this helper method which goes over an iterablee check size and then iterate running equals or any other of the methods that an internet search suggests whats the canonical way to compare lists for unit testsoptional insights i would love to getis the method test designed reasonably i am not an expert in junitis toarray the best way to convert a liste to a varargs of e,['java'] +348937,convert from ilist to nongeneric ilist i am implementing ilistsource that requires a method getlist with the following signatureilist getlisti am using net framework 2 and i am wanting to return an object that implements ilist as followspublic systemcollectionsilist getlist return this mydata implements ilistmydatarow but i get a compile error saying cannot implicitly convert type mydata to systemcollectionsilistif i create a new list of type listmydatarow populate it and return this list object then it works so in other words this workspublic systemcollectionsilist getlist listmydatarow list new listmydatarow foreach mydatarow row in this mydata listaddrow return listbut it seems very inefficient to have to recreate the list just to get it from type ilistt to ilist why is it that i can return a listmydatarow from getlist but not an ilistmydatarow does anyone know of a way for me to return the ilistmydatarow without repopulating a new listupdatethe mydata member variable is declaredprivate mydata mydataand mydata is declaredpublic class mydata ilistmydatarow,"['c#', '.net']" +348960,how to stock and use a shiros salt from database i use shiro in application for the authenticate i use hashed password with a salt and i store them in my database like this private user createuserwithhashedpasswordstring inname string infirstname string inlastname string inpassword bytesource salt randomnumbergeneratornextbytes32 byte bytetabsalt saltgetbytes string strsalt bytearraytohexstringbytetabsalt string hashedpasswordbase64 new sha256hashinpassword salt 1024tobase64 return new userinnameinfirstnameinlastnamehashedpasswordbase64strsalti store the salt with a string in my database now in my realm i want to get back my datas from the database i use a transactionnal service for this but my salt is a strong so i want it to turn back as bytesource type with the static method bytesource bytesourcesalt utilbytessalt where the salt is a stringbut when i create my saltedauthenticationinfo it does not authi think my problem is from my convert method private string bytearraytohexstringbyte barray stringbuffer buffer new stringbuffer forbyte b barray bufferappendintegertohexstringb bufferappend return buffertostringtouppercase thanks for your help,['java'] +348964,maximum length of intent putextra method force close i need some help with debugging my application first of all in emulator and on some other devices my app is running fine on my device i got a force close without a force close messagethe crash happens if the activity of the app is changedhere is some code of the mainactivity class it just reads html content from a web page over webview and no it is not possible to do this over httprequest because i was not able to simulate the post requestpublic class mainactivity extends activity public final static string extra html comexamplecomtesthtml private webview mwebview private progressdialog mdialog override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main mwebview webview findviewbyidridwebview1 cookiesyncmanagercreateinstancethis cookiemanager cookiemanager cookiemanagergetinstance cookiemanagerremoveallcookie mwebviewsetbackgroundcolor0 mwebviewsetwebchromeclientnew webchromeclient public boolean onconsolemessageconsolemessage cmsg if cmsgmessagestartswithmagic mdialogcancel hashmapstring string message new hashmapstring string string msg cmsgmessagesubstring5 intent intent new intentmainactivitythis readdataactivityclass messageputmessage msg intentputextraextra html message intentputextraextra html msg startactivityintent return false mwebviewgetsettingssetjavascriptenabledtrue mwebviewgetsettingssetpluginstatepluginstateoff mwebviewgetsettingssetloadsimagesautomaticallyfalse mwebviewgetsettingssetblocknetworkimagetrue mwebviewgetsettingssetappcacheenabledtrue mwebviewgetsettingssetsavepasswordtrue mwebviewgetsettings setcachemodewebsettingsload normal mwebviewsetwebviewclientnew webviewclient public void onpagefinishedwebview view string address if addressindexofmysession 1 viewloadurljavascriptconsolelogmagicdocumentgetelementsbytagnamehtml0innerhtml mwebviewloadurlso in the onconsolemessage method i just pass the html code to another activity class which read parse and thisplay the contentthe problem is now that at this point when the readdataactivity class should be loaded the application just close and go back to the home screen without any message or user dialogis it possible that the html code which is passed as a string to the readdataactivity is to big i also try to add the html code as a string in a hashmap but the problem is the samesome ideas what i can do to debug the problem maybe i should try to create a parceable objectin the emulator everything is working fineregardssandro,"['java', 'android']" +348971,ios strip from nsstring a html string so i have an nsstring which is basically an html string with all the usual html elements the specific thing i would like to do is to just strip it from all the img tagsthe img tags may or may not have maxwidth style or other attributes so i do not know their length up front they always end with how could i do thisedit based on nicolasthenozs answer i came up with a solution that requires less codensstring htmltagss img regex to remove img tagnsstring stringwithoutimage htmlstring stringbyreplacingoccurrencesofregexhtmltagss withstring,"['html', 'objective-c', 'ios']" +348985,doctrine 12 hydrate method array to model object i have a little problem with doctrine model hydrate method i use this method to hydrate an object of conrete model from a given array like somodel new doctrinemodelmodelmodelhydratemodel arrayeverything works perfect when hydrating simple objects withou nested submodels now the problem is i need to hydrate using this method an object that has nested objects and some of them have also a nested objectsif i were using hydrate record that would be fine but all the records from query would be returned as objects which means more memory consumption therefore i am using hydrate array and on demand hydrate that concrete array to an objectlet us suppose i have a model a that has nested models ab ac by one to many ad and ac has another nested model ace after print r of the a array we could see this structurea array ab array ac array ac array ace array ac array ace array ad array normally after using hydrate i would assume that this would be my objecta object ab object ac array ac object ace object ac object ace object ad object but instead of this i get this structurea object ab array ac array ac array ace array ac array ace array ad array so only the main model got converted to an objectdo you know about a way how to get all the nested model arrays got converted to an objects like the supposed resultand no i cannot use hydrate record when querying the db,['php'] +348987,pjsip receive sms anyone know any good examples on how to setup a pjsip client to receive messagesi can send messages from the client usingpjsua im sendsip acc id to null msgbody null nullto any numberbut i have no idea what to do to receive messages into the already registered sip accountany info would be greatly appreciatednote i can only use pjsip and no other libraryedit some new stuff i found however all this document says about incoming msgs is this 1612 receiving messageincoming message requests outside any dialogs will be received by applicationmoduleincoming message requests inside a dialog will be notified to dialog usage viaon tsx state callback of the dialogwhich still does not shine much light on how to handle incoming messages message buffer eventedit2 i have been told that on pager function needs to be used for this functionality so i tried but still no success unfortunatelyhere is what i did initialize application callbacks app configcfgcbon call state on call state app configcfgcbon call media state on call media state app configcfgcbon incoming call on incoming call app configcfgcbon reg state on reg state app configcfgcbon pager on pagerand the on pager implementationstatic void on pagerpjsua call id call id const pj str t from const pj str t to const pj str t contact const pj str t mime type const pj str t body nslog on pager called appdelegate app appdelegate appdelegate sharedapplication pjsua call info ci pjsua call get infocall id ci pj unused argcall id pj unused argto pj unused argcontact pj unused argmime type app ring pj log3this file message from s s s intfromslen fromptr inttextslen textptr intmime typeslen mime typeptr postmessagestatenotificationcall id cii was expecting the application to call on pager when a message is received but it did noton incoming call however does get called,['ios'] +348995,how do you handle asynchronous data in directives for angularjs this is a similar question to this one i am still seeing some issues with asynchronous data in my directives basically i have directives that i want to pass data into and this data is fetched asynchronously i started doing this with the scope property on the directive like thisscope myasyncdata in the link function i added a watch so i could update my model based on a value is in the scope something like thisscopewatchscopefoo function logic based on myasyncdatawhen i did this i started getting javascript errors because the asynchronous data had not returned yet this is what prompted me to post the question linked above so i then changed my watch to something like thisscopewatchscopefoo function if angularisdefinedscopemyasyncdata logic based on myasyncdata when i do this i do not get the javascript errors however the watch does not get run again when the data is returned and so my view does not reflect the model correctly i tried assigningscopefoo in a timeout to trigger the watch after the data is returned but that seems too dependent on timing and is not very robustmy question is just what is the correct way of interacting with asynchronous data in the directive i have seen some examples that get the data in the directive like thisscopeevalattrsmyasyncdatathis does not seem to change anything is there anything fundamentally different with this than the myasyncdata abovei have started to wonder if i should just get the data through services but it seems like there would be the exact same issues i have also had the thought of getting the data directly in the directive but i do not want to directive to be responsible for getting the data i only want the directive to be responsible for thisplaying the data and updating the view as the user interacts with iti may be missing something obvious on how this should be done so any input would me much appreciated,['javascript'] +349009,uirefreshcontrol without uitableviewcontroller just curious as it does not immediately seem possible but is there a sneaky way to leverage the new ios 6 uirefreshcontrol class without using a uitableviewcontroller subclassi often use a uiviewcontroller with a uitableview subview and conform to uitableviewdatasource and uitableviewdelegate rather than using a uitableviewcontroller outright,"['objective-c', 'ios']" +349107,is there a way to exclude some files from submitting to the ios app store i am working on an app that i would like to submit to the store and i have some files that is part of the project that i do not want to be part of the archive for example some viewcontroller files that i made but are not going to use for this version of the app or some data files that i am reading into the database that not needed in the release do i have to delete everything before creating the archive or i can some how choose for them not to be included also some of the viewcontrollers on the storyboard are extras would i have to delete them alsothanks in advance,"['objective-c', 'ios']" +349113,junit testing two boolean arrays i just noticed that junit 481 does not include support for testing two boolean arrays for equality there are tons of other assertarrayequals but none to take in two boolean arraysis there a proper way to do this my current thinking is that i would have to iterate over an array and use something likeassertasserttruearrayonei arraytwoiis there a cleaner way to do this,['java'] +349181,how to do nulls last in sqlite i would like to sort my result with all null columns last nulls last as specified in the sql2003 extension t611 sadly sqlite seems to not support it is there a clever workaround,['sql'] +349214,java generics creating collections of class objects extending throwable why does the first line work but the second one does notcollectionclass extends throwable exs new arraylistclass extends throwable addmyownexceptionclass collectionclass extends throwable exs arraysaslistmyownexceptionclass,['java'] +349261,processing http response in service i recently posted a detailed description of the issue i am facing here at so as i could not send an actual http request i used timeout to simulate asynchronous behavior data binding from my model to view is working correct with the help of gloopynow when i use http instead of timeout tested locally i could see the asynchronous request was successful and data is filled with json response in my service but my view is not updatingupdated plunkr here,['javascript'] +349341,what sense does it make to flush a stringwriter in java stringwriter has a flush function what does it mean to flush a string buffer,['java'] +349354,clearing a responsive jquery cycle i have created a responsive image slider using jquery cyclethe following setup i have used works fine apart from the containing cycle div is not cleared correctly making any content after it sit underneath itthis is due to the fact the div is relative and its children are absolute cyclecycle slideresize true containerresize false fit 1 width fit my question is how can i clear the responsive cycle div without having a fixed height or using some event heavy javascripthere is my code on jsfiddle updatei wrote some code to fix the height of the cycle which works as expected although it can bug out sometimes but its event heavy and not very slick id love to see can be done in pure css or a change in the cycle setup,"['jquery', 'css']" +349376,does each request access the same servlet object does each http request access the same servlet object but in a different thread or does it create a new thread and new servlet instance,['java'] +349510,excel 2007 minimize the ribbon programatically but not the menu bar in excel 2007 we can just right click on ribbon and select minimize the ribbon minimize iti have triedapplicationexecuteexcel4macroshowtoolbarribbonfalsewhich hides the whole ribbonbut i do not wish to hide whole ribboni have even tried applicationsendkeysf1 truebut it is not reliable as sometimes it does not work properlyis there any way to do it using c vsto code i read a lot about toggleribbon function but could not find way to use iteditthere is way you can actually find if the ribbon is already minimized i used officecommandbars cbs null cbs applicationcommandbars foreach officecommandbar cb in cbs if cbname ribbon if cbheight 90 thisapplicationactivewindowactivate to get focus on current workbook so that sendkeys will work applicationsendkeysf1 true,['c#'] +349553,cannot change datagridview cell color when using a datasource i have got an interesting issue i am trying to use a datatable as a data source for a datagridview i want to color some of the cells of the table to indicate various things but for some reason the color will not thisplay so the following code shows an uncolored celldatagridview1datasource tabledatagridview1rows0cells0stylebackcolor coloryellowi can only get a color to thisplay after the initial form load for example setting a cell color on the onclick event however if i explicitly create the rows and columns for the view as in the code below the coloring works foreach datacolumn col in tablecolumns datagridview1columnsaddcolcolumnname colcolumnnamefor int i 0 i tablerowscount i var row tablerowsi object values new objecttablecolumnscount for int x 0 x tablecolumnscount x valuesx rowxtostring datagridview1rowsaddvaluesdatagridview1rows0cells0stylebackcolor coloryellowi do not want to have the code in this manner does anyone know what is happening here that is preventing me from coloring the cells,"['c#', '.net']" +349580,systemcomponentmodeldataannotationsdll available for android and ios i got the the attached error message when tried to compile velocitydb for android as velocitydb support said it really needs the data annotationsis the referred systemcomponentmodeldataannotationsdll available for android and iosthanks jozseferror messageerror 1 exception while loading assemblies systemiofilenotfoundexception could not load assembly systemcomponentmodeldataannotations version40 cultureneutral publickeytoken31bf3856ad364e35 perhaps it does not exist in the mono for android profilefile name systemcomponentmodeldataannotationsdll at monodroidtunermonodroidresolverresolveassemblynamereference reference readerparameters parameters at xamarinandroidtasksresolveassembliesaddassemblyreferenceslist1 assemblies assemblydefinition assembly at xamarinandroidtasksresolveassembliesexecute,['.net'] +349586,no sound on ios 6 web audio api i was really excited to see ios 6 supports the web audio api since we make html5 games however i cannot get ios 6 to play any sound at all using the web audio api with examples that work fine in desktop chromehere is a html5 game with touch controls and playing audio via the web audio api if present if not it will fall back to html5 audioedit srikumar suggested some workarounds i applied them at the version below it still does not workeverything plays just fine on desktop chrome but ios 6 emits no sound at all i am having trouble debugging it because i only do windows development and ios 6 replaced the debug mode with remote web inspector which apparently is not available on safari for windows using a few alerts i did find it correctly identifies the web audio api uses it detects no vorbis support so falls back to aac audio decodes a buffer and then plays it and no errors are thrown but i hear nothing and of course i tried turning the volume up to max there should not be a codec problem because ios 6 can play aac just fine you can browse to one of the m4as the game plays and it plays fine visited direct from safari looking at the web audio api examples here on ios 6 some of them work and others do not for example the chrome audio visualizer works but javascript drone does notthere must be some subtle incompatibility between web audio on ios 6 and desktop chrome what am i missing,['javascript'] +349603,avassetwriter finishwriting fails on ios 6 simulator it seems that finishwriting is broken on ios 6 simulator it hangs forever it is now deprecated and replaced by the new finishwritingwithcompletionhandler which also never calls the handleron real devices running ios 6 this works just fine as it always did also in previous ios simulators it works just fine seems like a bug in ios 6 simulatoranyone else experiencing this or can prove me wrong,['ios'] +349605,the nearly best way to manage a list with shifting items here is the situationi have list which store strings which are actually numbers and can become pretty big hundreds of millions of itemsi store the numbers as string because there is a option to thisplay some additional information which is textbecause this takes a lot of memory to store i decided that i will store only a maximum of 5 million items this will only take about 250300mbthe list is filled by the output of a calculation if a number is found it will be added to the list this number is always bigger than the existing itemswhen the list reached 5 mil i want to remove the first item and add the new item to the listlike why is this so freaking slow if resultcount 50 resultremoveat0 resultaddresultas you can read in the comment this is very very very slow it just cut down my performance by 15 times where it took 2 minutes it now takes about 30i tried a few things with linq like skip1tolist but that will recreate the list and is therefore even more slowthe list must stay in the right order so overwriting by index is not an option unless you could explain a nice work aroundmy questionis there any decent way to do thisi really need the performance here since it may need to check up about 10 numbers this may take a day ofcourse but a month is a bit too much need additional information feel free to ask i will be happy to supplysolutionthis performs o1 set the result queueobject result new queueobject50 inside the method if the count has reach it is max dequeue the first item if resultcount 50 resultdequeue resultenqueueresult,['c#'] +349639,what to name images for iphone 5 screen size what is the new naming convention for images for the 4inch retina thisplayfor an image named backgroundpng you add 2x to the name to tell ios to use that one for devices with the retina thisplaywhat would the suffix be for iphone 5s screen size,"['ios', 'iphone']" +349666,how to force a uiviewcontroller to portait orientation in ios 6 as the shouldautorotatetointerfaceorientation is deprecated in ios 6 and i used that to force a particular view to portrait only what is the correct way to do this in ios 6 this is only for one area of my app all other views can rotatethank you,['ios'] +349730,optionally serialize a property based on its runtime value fundamentally i want to include or omit a property from the generated json based on its value at the time of serializationmorespecifically i have a type that knows if a value has been assigned to it and i only want to serialize properties of that type if there has been something assigned to it so i need to inspect the value at runtime i am trying to make it easy for my api to detect the difference between has the default value and was not specified at alla custom jsonconverter does not seem sufficient i tried it and i believe the property name is already serialized before the converter is called in my case i want to omit even the property namei have looked at extending defaultcontractresolver but createproperty and createproperties which return jsonproperty serialization metadata take only the type being serialized so i cannot inspect the instance itself in general i do not see anything on the defaultcontractresolver allowing me to control if an instance is serialized maybe i missed iti also thought maybe i needed to create a contractresolver that returned a custom jsonobjectcontract for my type but again i do not see anything on jsonobjectcontract that makes decisions based on an instanceis there a good way to accomplish my goal am i just missing something simple any help you can provide is greatly appreciated since jsonnet is so extensible i thought this wouldnt be too hard but i am starting to think i am way off in the weeds here,"['c#', '.net']" +349758,catch exception thrown in foreach condition i have a foreach loop that breaks during the loop in the condition of the foreach itself is there a way to try catch the item that throws the exception and then continue the loopthis will run a few times until the exception hits and then endtry foreachb in bees exception is in this line string b catch errorthis will not run at all because the exception is in the condition of the foreachforeachb in bees exception is in this line try string b catch error i know some of you are going to ask how this is happening so here is thisexception principaloperationexception is being thrown because a principal b in my example cannot be found in groupprincipal beesedit i added the code below i also figured out that one group member was pointing to a domain that no longer exists i easily fixed this by deleting the member but my question still stands how do you handle exceptions that are thrown inside the condition of a foreachprincipalcontext ctx new principalcontextcontexttypedomaingroupprincipal gp1 groupprincipalfindbyidentityctx gp1groupprincipal gp2 groupprincipalfindbyidentityctx gp2var principals gp1membersuniongp2membersforeachprincipal principal in principals error is here do stuff,['c#'] +349770,error upload testflight invalid ipa dsym not found this shown on testflight web after uploadedinvalid ipa could not find executable specified in infoplist check the value of your cfbundleexecutable keywhile on testflight desktop application shows dsym not found hence could not uploadthis issue suddenly appear after i upgraded xcode 45 with ios6 anyone has experienced before kindly share and any solutions would be appreciate thanks in advance,['ios'] +349782,how to write a mysql case when statement with multiple search conditions i know languages like php has switch case control structure that supports multiple validations in a single case statement likeswitch x case 123 a 0 break case 56 a 1 breaksimilarly can this be done in mysql i tried below which really did not work though case vc shape when 02 or 51 then set dc square 1 dc square 1 dc row total when 06 or 30 or 83 then set dc square 2 dc square 2 dc row total else begin endend case any ideas how can i achieve this,"['mysql', 'sql']" +349793,why does stdfunction accept a this reference in the signature member functions have an implicit this pointer parameter why does stdfunction accept this signature then where s is a simple class complete samplestdfunctionvoids func sfoocalling it works too and thistinguishes objectss s1 5s s2 6funcs1 prints 5funcs2 prints 6what i would normally expect is that it needs a pointer which works as well complete samplestdfunctionvoids const func sfoos s1 5s s2 6funcs1 prints 5funcs2 prints 6why does the first one work when i pass a reference into the member function when the implicit this parameter is a pointer,['c++'] +349810,how do you implement ifdef in python programming in c i used to have code sections only used for debugging purposes logging commands and the like those statements could be completely thisabled for production by using ifdef preprocessor directives like this ifdef macro controlled text endif macro what is the best way to do something similar in python,['python'] +349817,epub reader performance issue i have developed book reader application using aepubreader regarding english books there is no issue at all it work fine but regaring arabic book i have faced some performance issue the page are loading too slow please suggest me some idea to over come this problemthanks in advance,['ios'] +349826,set text color for textview android in the stringxml file i use the following tag string namecodecolor 0ffstringif i use textview1settextcolorcolorredit works but when i use textview1settextcolortextviewstylesthisgetresourcesgetcolorrstringcodecolor or textview1settextcolorrstringcodecolorit doent workany suggestionsthanks in advance,['android'] +349869,how to write with a single byte character encoding i have a webservice that returns the config file to a low level hardware devicethe manufacturer of this device tells me he only supports single byte charactersets for this config fileon this wiki page i found out that the following should be single byte character setsiso 8859isoiec 646 i could not find this one herevarious microsoftibm code pagesbut when i call encodinggetmaxbytecount1 on these character sets it always returns 2i also tried various other encodings for instance ibm437 but getmaxbytecount also returns 2 for other character setsthe method endodingissinglebyte seems unreliable according to thisyou should be careful in what your application does with the value for issinglebyte an assumption of how an encoding will proceed may still be wrong for example windows1252 has a value of true for encodingissinglebyte but encodinggetmaxbytecount1 returns 2 this is because the method considers potential leftover surrogates from a previous decoder operationalso the method encodinggetmaxbytecount has some of the same issues according to thisnote that getmaxbytecount considers potential leftover surrogates from a previous decoder operation because of the decoder passing a value of 1 to the method retrieves 2 for a singlebyte encoding such as ascii your application should use the issinglebyte property if this information is necessarybecause of this i am not sure anymore on what to usefurther reading,['c#'] +349930,should i test tostring with junit can such tests have a good reason to exist,['java'] +349932,problems with xtext in eclipse i am working on a java project in eclipse trying to open a file through ctrlmouse click i got a popup that asked me if i want to add xtext nature to my project i said ok and now i tried to put on a css file the following lineimport myfilecssas first line but i get this error because of xtext check fast missing eof at can anybody help me on how to deal with this kind of errorthanks,['java'] +349934,spinner focus to first item i use dropdown spinner with cursor adapter it contains eg 1 100 items i select eg item 50 item is selected next time when i open spinner first visible row is item 50 how can i achieve that when i open spinner it will focus to first itemfirst visible item will be item 1i mean like autoscroll up in the list so first visible item in dropdown is 1st one and not selected one,['android'] +349953,non resizable window border and positioning if i create nonresizable jframes and windows aero is enabled setlocation does not seem to take account of the window border correctlyin the following code i would expect the second frame to be positioned to the right of the first frame instead the borders are overlapping if aero is thisabled or if i remove the calls to setresizable this is done as expectedimport javaawtrectangleimport javaxswingjframepublic class frameborders public static void mainstring args jframe frame1 new jframeframe 1 jframe frame2 new jframeframe 2 frame1setresizablefalse frame2setresizablefalse frame1setvisibletrue rectangle bounds frame1getbounds frame2setlocationboundsxboundswidth boundsy frame2setvisibletrueam i doing something wrong or is this a bug how can i thisplay 2 unresizable dialogs side by side without having overlapping bordersedit added screenshots also changed frame2 to a jdialog instead of a jframeaero onaero offaero on but resizable,['java'] +349954,avassetexportsession outputfile how should the avassetexportsession output file look like i am trying to compress a video from an alasset item and it does not work i am guessing the output file has something to do with itheres the code i am usingnsstring destinationpath nshomedirectory stringbyappendingpathcomponentdocumentsmovieself convertvideotolowqualitywithinputurlassetdefaultrepresentationurl outputurlnsurl urlwithstringdestinationpath voidconvertvideotolowqualitywithinputurlnsurlinputurl outputurlnsurloutputurl ifnsfilemanager defaultmanager fileexistsatpathnsstring stringwithcontentsofurloutputurl encoding 0 errornil nsfilemanager defaultmanager removeitematurloutputurl errornil avurlasset assetav avurlasset urlassetwithurlinputurl optionsnil nslogurl string from asset assetavurl nslogoutput url outputurl absolutestring nsfilemanager defaultmanager createfileatpathoutputurl path contentsnil attributesnil nslogduration lld assetavdurationvalue it logs a valid value so it is all good so far avassetexportsession exportsession avassetexportsession alloc initwithassetassetav presetnameavassetexportpresetlowquality exportsessionoutputurl outputurl exportsessionoutputfiletype avfiletypequicktimemovie exportsession exportasynchronouslywithcompletionhandlervoid if exportsessionstatus avassetexportsessionstatuscompleted nslogsuccess else nslogerror exportsession error error error domainavfoundationerrordomain code11800 the operation could not be completed userinfo0x2023b720 nslocalizeddescriptionthe operation could not be completed nsunderlyingerror0x2023bb70 the operation couldnat be completed osstatus error 12780 nslocalizedfailurereasonan unknown error occurred 12780 can someone please help meupdatefound the solution as i thought the problem was the output file so here is the code for generating a valid one nsuinteger count 0 nsstring filepath nil do nsstring extension nsstring uttypecopypreferredtagwithclass cfstringrefavfiletypequicktimemovie kuttagclassfilenameextension nsstring filenamenoextension assetdefaultrepresentationurl urlbydeletingpathextension lastpathcomponent nsstring filename nsstring stringwithformatufilenamenoextension avassetexportpresetlowquality count filepath nstemporarydirectory filepath filepath stringbyappendingpathcomponentfilename filepath filepath stringbyappendingpathextensionextension count while nsfilemanager defaultmanager fileexistsatpathfilepath nsurl outputurl nsurl fileurlwithpathfilepath,"['iphone', 'ios']" +349961,boost unit testing main function how do i define my own main function when testing with boostboost is using it is own main function but i am using a custom memory manager and it needs to be initialized before any memory is allocated otherwise i will get errors,['c++'] +349997,best way to write arrays to a file i want to avoid writing to db and use constantsarray for lang files etcielang array hello hello worldand be able to edit it from the back officethen instead of fetching it from the poor db i would just use langhellowhat are you suggesting for the best and efficient way to pull it of,"['php', 'mysql']" +350037,queue data structure supporting fast kth largest element finding i am faced with a problem which requires a queue data structure supporting fast kth largest element findingthe requirements of this data structure are as followsthe elements in the queue are not necessarily integers but they must be comparable to each other ie we can tell which one is greater when we compare two elementsthey can be equal as wellthe data structure must support enqueueadds the element at the tail and dequeueremoves the element at the headit can quickly find the kth largest element in the queue pls note k is not a constantyou can assume that operations enqueue dequeue and kth largest element finding all occur with the same frequency my idea is to use a modified balanced binary search tree the tree is the same as ordinary balanced binary search tree except that every nodei is augmented with another field ni ni denotes the number of nodes contained in the subtree with root nodei the aforementioned operations are supported as followsfor simplicity assume that all elements are thistinctenqueuex x is first inserted into the tree suppose the corresponding node is nodet we append pairxpointer to nodet to the queuedequeue suppose e1 node1 is the element at the head node1 is the pointer into the tree corresponding to e1 we delete node1 from the tree and remove e1 node1 from the queuekth largest element finding suppose root node is noderoot its two children are nodeleft and noderightsuppose they all exist we compare k with nroot three cases may happenif k nleft we find the kth largest element in the left subtree of nrootif knrootnright we find the knrootnrightth largest element in the right subtree of nroototherwise nroot is the node we wantthe time complexity of all the three operations are ologn where and is the number of elements currently in the queuehow can i speed up the operations mentioned above with what data structures and how,"['java', 'c++']" +350077,uipageviewcontroller gesture is calling viewcontrollerafter but does not animate i have a really interesting issue with uipageviewcontrollermy project is set up very similarly to the example page based application templateevery now and then but reproducible to a certain extent a certain pan gesture will call out to uiviewcontroller pageviewcontrolleruipageviewcontroller pageviewcontroller viewcontrollerafterviewcontrolleruiviewcontroller viewcontroller i return the viewcontroller for the next page but a page flip animation is never ran and my delegate method is never calledhere is the code for viewcontrollerafterviewcontrolleruiviewcontroller pageviewcontrolleruipageviewcontroller pageviewcontroller viewcontrollerafterviewcontrolleruiviewcontroller viewcontroller pagethisplayviewcontroller vc pagethisplayviewcontroller viewcontroller nsuinteger index selfpagefetchcontrollerfetchedobjects indexofobjectvcpage ifindex selfpagefetchcontrollerfetchedobjectscount 1 return nil return self getviewcontrollerforindexindexhere is the getviewcontrollerforindexpagethisplayviewcontroller getviewcontrollerforindexnsuintegerindex pagethisplayviewcontroller newvc selfstoryboard instantiateviewcontrollerwithidentifierpagethisplaycontroller newvcpage selfpagefetchcontrollerfetchedobjects objectatindexindex newvcviewframe cgrectmake0 0 1024 604 nslogi index ifindex 0 were moving to the first animate the back button to be hidden uiview animatewithduration05 animations selfbackbuttonalpha 0f completionbool finished selfbackbuttonhidden yes else ifindex selfpagefetchcontrollerfetchedobjectscount 1 uiview animatewithduration05 animations selfnextbuttonalpha 0f completionbool finished selfnextbuttonhidden yes else bool eitherishidden selfnextbuttonhidden selfbackbuttonhidden ifeitherishidden uiview animatewithduration05 animations ifselfnextbuttonhidden selfnextbuttonhidden no selfnextbuttonalpha 1f ifselfbackbuttonhidden selfbackbuttonhidden no selfbackbuttonalpha 1f return newvcbasically i create the view controller set it is data object then fade a nextback button out depending on the indexdelegate methodvoidpageviewcontrolleruipageviewcontroller pageviewcontroller didfinishanimatingboolfinished previousviewcontrollersnsarray previousviewcontrollers transitioncompletedboolcompleted pagethisplayviewcontroller vc previousviewcontrollers lastobject nsuinteger index selfpagefetchcontrollerfetchedobjects indexofobjectvcpage if completed selfpagepreviewview setcurrentindexindex nsloganimation did not complete reverting pagepreview else pagethisplayviewcontroller curr pageviewcontrollerviewcontrollers lastobject nsuinteger i selfpagefetchcontrollerfetchedobjects indexofobjectcurrpage selfpagepreviewview setcurrentindexi nsloganimation compeleted updating pagepreview index u i i only noticed this issue because randomly my back button would reappear on screen after tossing some nslog statements in there i notice that my datasource method gets called for an index of 1 but no animation ever plays or delegate gets called whats even scarier is that if i try to pan the next page index 1 gets called for againi fear this may be a bug with the uipageviewcontroller,['ios'] +350111,unable to install testflight access profile ios since upgrading to ios 6 i have been unable to install the testflight access profile and my clients running 60 are experiencing the same issues i have googled the issue but i am not finding any results the error message is just after you enter your device password and readsprofile installation faileda network error has occurredi have verified i have a good network connection and the error is happening at multiple physical locations different service providers and internet accessthanks in advance,['ios'] +350150,is it always necessary to use float literals when performing arithmetic on float variables in c i see a lot of c code that has lines likefloat a 2float x a 10ffloat b 30f afloat c 20f 10f aare these 0f after these literals really necessary would you lose numeric accuracy if you omit thesei thought you only need them if you have a line like thisfloat a 10float x 1 awhere you should use 10f right,['c++'] +350161,ruby limiting a utf8 string by bytelength this rabbitmq page statesqueue names may be up to 255 bytes of utf8 charactersin ruby 193 how would i truncate a utf8 string by bytecount without breaking in the middle of a character the resulting string should be the longest possible valid utf8 string that fits in the byte limit,['ruby'] +350168,what is the best way to avoid negative zero in output as in this question is said there is some differences between negative and positive zero in floating point numbers i know it is because of some important reasons what i want to know is a short code to avoid negative zero in outputfor example in the following codecout fixed setprecision3cout 01 endl0 is printed but i want 0,['c++'] +350176,fatal error nonstatic method in php using pdo for mysql i am inserting using pdo a row into the table and i need the id of the new row so i can redirect to the new page based off that rowwhen i useid pdolastinsertidi get fatal error nonstatic method pdolastinsertid cannot be called statically in cxampphtdocscreateimagephp on line 16heres the php that results in an errorphp title posttitlecaption postcaptionconn new pdomysqlhostlocalhostdbnameimagesite root stmt connprepareinsert into images idlinktitlecaption values nulinktitlecaptionstmtexecutearray link fake title title caption caption id pdolastinsertidheaderlocation localhostimageididcan anyone tell whats going wrong or another way to achieve that i am looking to do,['php'] +350223,linking to a facebook page with ios6 so i am trying to link to a facebook page on ios6 from my app usingnsstring urlstring uiapplication sharedapplication openurlnsurl urlwithstring urlstringthis opens up the facebook app successfully but it does not go on my page anyone has an idea on how to link properly on ios6,['iphone'] +350236,at least one object must implement icomparable for an int as far as i know it does ok i have a simple ienumerablehtmlstring things and i want to divide it up into four equal groups var quarter thingscount 4should do the trick but instead i get this funkineserver error in application at least one object must implement icomparable description an unhandled exception occurred during the execution of the current web request please review the stack trace for more information about the error and where it originated in the codeexception details systemargumentexception at least one object must implement icomparableline 36 int quarter thingscount 4anyone know what the heck is going on here why would i need to implement icomparable to get a simple count,['c#'] +350263,how do i get the quotient as int and remainder as a floating point in javascript on my calculator when i do 187 i get 25714285714285714285714285714286from my super limited math skills 2 is the quotient and 5714285714285714285714285714286 is the remainderhow can i model this in javascriptthanks,['javascript'] +350299,backbone bootstrapped collection does not initialize correctly i have an issue that was really hard to notice because for the most part everything works it was only when i tried to manipulate my data in my collections initialize function that i found a problemthe backbone docs at if you define an initialize function it will be invoked when the collection is createdso i interpreted that as my initialize function would not run until after my models are set that sounds ideal said i but then i ran into thismy bootstrap code is as followsnew mycollectionphp if data echo json encodedata my collectionvar mycollection backbonecollectionextend model mymodel initialize function consolelogthis consolelogthislength thiseachfunctionmodel consolelogmodel i got strange results the first consolelogthis was a collection object as expected models 3 length 3 and the second consolethislength printed out the number 0the console inside thiseach did not show upwhats happening,['javascript'] +350300,c mvc 4 controllername attribute i am working on providing friendly names for my mvc 4 controllers and i want to do something like the actionnamemyfriendlyname style but for the whole controlleri could not find any information about such an attribute so how would i go about doing that also will i need to add a new maproute to handle iteditfor example i would like to route the following url be routed to the following controllercontrollerclassmyreports this attribute is made up i would like to know how to make this functionalitypublic class reportscontroller controller get reports public actionresult index return view public viewresult detailsint id report report dbreportssingleg gid id return viewreport public actionresult create return view httppost public actionresult createreport item try if modelstateisvalid itemid guidnewguid contextreportsaddobjectitem contextsavechanges return redirecttoactionindex return viewitem catch exception return viewitem,['c#'] +350308,how to organize multiple python files into a single module without it behaving like a package is there a way to use init py to organize multiple files into a modulereason modules are easier to use than packages because they do not have as many layers of namespacenormally it makes a package this i get problem is with a package import thepackage gives me an empty namespace users must then either use from thepackage import frowned upon or know exactly what is contained and manually pull it out into a usable namespacewhat i want to have is the user do import thepackage and have nice clean namespaces that look like this exposing functions and classes relevant to the project for usecurrent module doit tools class hidden resource pool class jobinfo class cachedlookup class threadedworker fn util a fn util b fn gather stuff fn analyze stuffthe maintainers job would be to avoid defining the same name in different files which should be easy when the project is small like mine isit would also be nice if people can do from doit stuff import jobinfo and have it retrieve the class rather than a module containing the classthis is easy if all my code is in one gigantic file but i like to organize when things start getting big what i have on thisk looks sort of like thisplace in my python path doit tools init py jobinfopy class jobinfo networkaccessorspy class hidden resource pool class cachedlookup class threadedworker utility functionspy def util a def util b data functionspy def gather stuff def analyze stuffi only separate them so my files are not huge and unnavigable they are all related though someone possible me may want to use the classes by themselves without importing everythingi have read a number of suggestions in various threads heres what happens for each suggestion i can find for how to do thisif i do not use an init py i cannot import anything because python does not descend into the folder from syspathif i use a blank init py when i import doit tools it is an empty namespace with nothing in it none of my files imported which makes it more difficult to useif i list the submodules in all i can use the frowned upon from thing import syntax but all of my classes are behind unnecessary namespace barriers again the user has to 1 know they should use from x import instead of import x 2 manually reshuffle classes until they can reasonably obey line width style constraintsif i add from thatfile import x statements to init py i get closer but i have namespace conflicts and extra namespaces for things i did not want to be in there in the below example youll see thatthe class jobinfo overwrote the module object named jobinfo because their names were the same somehow python can figure this out because jobinfo is of type class doit toolsjobinfojobinfo doit toolsjobinfo is a class but doit toolsjobinfojobinfo is that same class this is tangled and seems very bad but does not seem to break anythingeach filename made its way into the doit tools namespace which makes it more confusing to look through if anyone is looking at the contents of the module i want doit toolsutility functionspy to hold some code not define a new namespacecurrent module doit tools module jobinfo class jobinfo class jobinfo module networkaccessors class cachedlookup class threadedworker class cachedlookup class threadedworker module utility functions fn util a fn util b fn util a fn util b module data functions fn gather stuff fn analyze stuff fn gather stuff fn analyze stuffalso someone importing just the data abstraction class would get something different than they expect when they do from doit tools import jobinfocurrent namespace jobinfo module jobinfo classinstead ofcurrent namespace jobinfo claso is this just a wrong way to organize python code if not what is a correct way to split related code up but still collect it in a modulelike waymaybe the best case scenario is that doing from doit tools import jobinfo is a little confusing for someone using the packagemaybe a python file called api so that people using the code do the followingimport doit toolsapifrom doit toolsapi import jobinfoexamples in response to commentstake the following package contents inside folder foo which is in python pathfoo init py all doitdataholdergetsomestuffhold more dataspecialcasefrom another class import doitfrom another class import dataholderfrom descriptive name import getsomestufrom descriptive name import hold more datafrom specialcase import specialcasefoospecialcasepyclass specialcase passfoomorepydef getsomestuff passclass hold more dataobject passfoostuffpydef doit print i am a functionclass dataholderobject passdo this import foo for thing in dirfoo print thing specialcase builtins doc file name package path another classdataholderdescriptive namedoitgetsomestuffhold more dataspecialcaseanother class and descriptive name are there cluttering things up and also have extra copies of eg doit underneath their namespacesif i have a class named data inside a file named datapy when i do from data import data then i get a namespace conflict because data is a class in the current namespace that is inside module data somehow is also in the current namespace but python seems to be able to handle this,['python'] +350330,how to export html table to excel or pdf in php in my php page i have a table and if the user requires he has to export that table to excel sheet the code for thisplaying the table is sqlmysql queryselect from attendance where year mysql real escape string sessionyear and branch mysql real escape string sessionbranch and sem mysql real escape string sessionsem and sec mysql real escape string sessionsec print body backgroundbgjpg print brbrbrcentertable border cellpadding3trthidnoththnameththsubjectththheld classesththattended classesthtr whiledatamysql fetch array sql echo trtddataidno tdtddataname tddatasubject tdtddataheldcls tddataattendcls td print tablebrbrform action excelphp method postinput type submit name submit value export to excelformcenterhow do i export this table to excel sheet and what should b the code in excelphp please help me thank you in advance,['php'] +350333,using bootstrap side navbar i have implemented bootstrap if you goto im tyring to apply an affix to the left side bar where when i scroll down the side bar stays with the scroll in view i cannot get this to work i tried everything any ideas or tricks i need to do to get this working i tried the data element and javascript way neither work i do have the bootstrapjs bootstrapcs and bootstrapresponsivecs implemented as welldiv classcontainer docs nav div classrow div claspan3 bsdocssidebar dataspyaffix dataoffsettop200 ul classnav navlist bsdocssidenav lia hrefaccountidi classiconchevronrightimy accountali lia hreftutorialidi classiconchevronrightimy tutorialsali lia hrefbuttondropdownsi classiconchevronrightimy articlesali lia hrefnavsi classiconchevronrightihelpali ul div div claspan9 typography section idaccountid div classpageheader h1my accounth1 div div classbsdocsexample h3bchange passwordbh3 div labelcurrent passwordlabel input typetext labelnew passwordlabel input typetext labelconfirm passwordlabel input typetext br input typebutton classbtn btnprimary valuesubmit div h3btutorial settingsbh3 div labelcurrent passwordlabel input typetext labelnew passwordlabel input typetext labelconfirm passwordlabel input typetext br input typebutton classbtn btnprimary valuesubmit div h3barticle settingsbh3 div labelcurrent passwordlabel input typetext labelnew passwordlabel input typetext labelconfirm passwordlabel input typetext br input typebutton classbtn btnprimary valuesubmit div div section tutorials section idtutorialid div classpageheader h1my tutorialsh1 div div classbsdocsexamplediv section div divdiv,['html'] +350364,regex match integers 6 through 10 i want to find integers any integers between 6 and 10 i have tried61012but this throws a mysql error this is for a mysql query how do you match numbers between 6 and 10,"['php', 'mysql', 'sql']" +350392,cannot set volume on blackberry playbook i have an issue in changing the volume of blackberry play book first i am repacking my android app to palybook app i need to change the volume of blackberry playbook using seekbar and in seeklistener i am setting the audio manager volume here is the codeaudiomanager audiomanagergetsystemservicecontextaudio serviceseekbarsetonseekbarchangelistenernew onseekbarchangelistener public void onstoptrackingtouchseekbar seekbar todo autogenerated method stubpublic void onstarttrackingtouchseekbar seekbar todo autogenerated method stubpublic void onprogresschangedseekbar seekbar int progressboolean fromuser todo autogenerated method stub audiomanagersetstreamvolumeaudiomanagerstream music progress 0but when i run my app and change the seekbar the volume of the systemblackberry playbook does not changeis it due to blackberry palybook security,"['java', 'android']" +350409,how can i select specific columns with createquerybuilder in orm symfony2 i am using createquerybuilder to construct queries in symfony2 but i do not want to take all columns in this entity how can i select only the id and namequery thisgetentitymanagercreatequerybuilder query selectd fromacmebundledemo d leftjoindotherentity o querysetmaxresults10 results querygetquerygetresultthank you so much,['php'] +350434,parsing apache log files i just started learning python and would like to read an apache log file and put parts of each line into different listsline from the file1721603 25sep2002140419 0200 get http11 401 mozilla50 x11 u linux i686 enus rv11 gecko20020827according to apache website the format is h l u t r s b refereri useragentii am able to open the file and just read it as it is but i do not know how to make it read in that format so i can put each part in a list,['python'] +350446,use the salt when using simplemembershipprovider possible duplicatewebmatrix websecurity passwordsalt is there a way to have simplemembershipprovider use the saltwhen i create my mvc4 web project and set the default connection to sqlexpress then register my users do not have a password salti would like for it to be as secure as it can without too much trouble,['asp.net'] +350457,how to tell abpeoplepickernavigationcontroller to list only contacts that have an email address i want my users to fill an email field by selecting a contacts email from their address books i do not want them to scroll all the contacts whose emails are not set so i want to filter the ones that have email addresses this is the code i have written so far i can figure out who has an email address and who has not but i could not tell the abpeoplepickernavigationcontroller to list only the right contacts is it impossible to achieve this i mean do i have to implement my own contact picker class by using a table view or is there something wrong with this piece of codeabaddressbookref addressbook abaddressbookcreatensarray peoplelist nsarray abaddressbookcopyarrayofallpeopleaddressbooknslogld people exist in the addressbook abaddressbookgetpersoncountaddressbookfor id peoplerecord in peoplelist abmultivalueref mv abrecordcopyvalueabrecordrefpeoplerecord kabpersonemailproperty cfindex numberofaddresses abmultivaluegetcountmv ifnumberofaddresses 0 cferrorref err abaddressbookremoverecord addressbook abrecordrefpeoplerecord err peoplelist releasenslogld people have an email abaddressbookgetpersoncountaddressbookabpeoplepickernavigationcontroller peoplepicker abpeoplepickernavigationcontroller alloc initnsnumber emailprop nsnumber numberwithintkabpersonemailpropertypeoplepicker setaddressbookaddressbookpeoplepickerthisplayedproperties nsarray arraywithobjectemailproppeoplepicker setpeoplepickerdelegateselfself presentmodalviewcontrollerpeoplepicker animatedyes,['ios'] +350520,why am i getting the error a is not an accessible base of s for a base clas base class i am trying to call the class function aff from within class s but i am getting the following errors when i instantiate an s object sints and call it is f member function sf sourcecpp in instantiation of int sff with f int sourcecpp3021 required from here sourcecpp25 error aint is not an accessible base of sintnote that this works when i replace return aff inside the declaration of class s with return ca ff but i am wondering why i cannot do it the other wayinclude iostreamtemplate typename t class a public int ftemplate typename t int atf return sizeofttemplate template typename class e typename d class c ed public int f return edf template typename f class s ca f public int f return aff int main sints stdcout sfany help is appreciated and if you require further clarification please feel free to commentupdatesince this questions is resolved i guess i should post the code that actually workedinclude iostreamtemplate typename t class a public int ftemplate typename t int atf return sizeofttemplate template typename class e typename d class c public ed public int f return edf class s public ca int int main s s stdcout sf 4,['c++'] +350524,log messages i did not asked for in xcode 45 with ios 60 since i updated xcode to version 45 and started building for ios 6 log messages like this keep appearingaddresponse adding to memory onlyi never asked for that at least not consciouslywhat do i need to do to stop these messages and what is their origin,['objective-c'] +350529,borders thisappear in chrome when i zoom in i have this really simple form sometimes when i zoom in or out using chrome the input borders thisappear for example when i zoom to 90 i getnaturally your mileage may varyin case youre wondering about those span tags i added them following the recommendation at how do i make an input element occupy all remaining horizontal spaceis there a problem with my css or is this a chrome bug it seems to work fine on firefox what can i do to avoid this behaviorthanks,"['html', 'css']" +350562,how do i write a c header file that can be used in c programs possible duplicatehow to check via the preprocessor if a c source file is being compiled as c code i am trying to find a standard macro which will test whether a header file is being compiled as c or as c the purpose of this is that the header may be included by either c or c code and must behave slightly differently depending on which specificallyin c i need this to be the codeextern size t insert const charin c i need this to be the codeextern c size t insert const charadditionally is there a way to avoid putting ifdefs around every declaration in the header,"['c++', 'c']" +350575,any equivalent of extended for c i am working on a new version of my mandelbrot screensaver and i am running out of floating point accuracy simple double values do not have enough significant figures for my needsmore significant figures greater levels of zooming into the fractalback when i wrote a version of this screensaver in delphi 7 i used the extended floating point type 80 bits in sizein net i could switch to decimal but the performance hit for this is terrible slowing down fractal generation by a factor of 20 or sois there any equivalent of extended for net or alternatively are there any numeric types with higher precision than double that still use the fpu for evaluation and therefore do not have the high performance hit of decimalupdatemy screensaver already manages to zoom into the fractal by many many orders of magnitude currently it resets to the base fractal only when the numeric type in use is unable to separate the ordinates for adjacent pixels the extra 16 bits of precision from the doubleextended improvement would give me close to 16 more doublings of sizeas to performance my algorithm already manages to eliminate 9599 of the math required as compared to a naive implementation that calculates many pixels while retaining the integrity of the fractal,['c#'] +350599,count the number of selections in a multipleselect box i have a multiple selection list which have more than 5 options and i want to count the number of selection of the options selected by the user how to do it using java scripti tried the following but it did not work for mevar x documentgetelementbyidpreferencecountthanks in advance,"['javascript', 'html']" +350621,get absolute url for paperclip attachment is it possible to get the absolute uri for a paperclip attachment right now the problem is that the production environment is deployed in a suburi on passenger rackbaseuri but paperclip attachmenturl returns the railsapp relative uri systemimages is there a way to get the absolute uri for paperclip attachmentsi am using paperclip v27 and rails 328,['ruby-on-rails'] +350627,2 js functions with same name conflict shortusing 2 libraries at same page jquery ui and twitter bootstrap jquery ui very important for me because nearly all ui things built based on ittwitter bootstrap only for split button with dropdown menu functionality now the problem is both libraries has same named functions which conflicts with each otherdetailedhere is example of conflict between jquery ui and twitter bootstrap button functionsplease enter to this website press recommend button on tablejquery ui modal window will appear i used jquery ui combobox inside modal window the problem is there is no down arrow button as shown on jquery ui combobox demo i tried to find what causes the problem looked through combobox code and when it called button it went into bootstrapminjs not jquijs as you see it is proof of conflict between 2 js librariesbtw here is jsfiddle where it works well without bootstrap problemi have multiple ways to solve this conflict problem without touching functionality of the website i need to get exactly same functionality as split button with dropdown menu twitter bootstrap if possible in jqueryui something like this but with dropdown menuelse in css html onlyand get rid off twitter bootstrap any solutions greatly appreciated i am ready to give 200 reps to good answer as bounty thx in advance,"['javascript', 'jquery']" +350643,xcode 45 symbols not found for architecture i386 zbar i have a project which uses the zbarsdk a barcode scanning libraryafter updating my machine to xcode 45 and ios6sdk i am having some troublesi was able to build to the simulator without touching anything about my project this is using the latest zbar 12 libraryi then wanted to build to my ios6 device for testing and thats when i got an errorafter some googling on the zbar developer forum i seen that i needed to get the zbar source and build the libzbara for armv7 and armv7s as this has not yet been done by the zbar developer see so i did this reimported the updated libzbara into my project i then built for my device and it worked i was able to get my app onto my testing device and the zbar barcode library worked finei thought that was the end of it but unfortunately not i then tried to build to the simulator ios6 again and thats when it failsno matter what i cannot get this project to build for both the device and simualtor at the same time and with the same settings my libzbara project settings when building my own libzbara filearchitecture standard armv7 armv7s archs standard 32 bitbuild active architecture only novalid architectures armv7 armv7sand my project settings for myapp asarchitecture standard armv7 armv7s archs standard 32 bitbuild active architecture only novalid architectures armv7 armv7sbase sdk ios6ios deployment target ios 50and the error when trying to build to the simulatorld warning ignoring file usersblahios appmyappzbarsdklibzbara missing required architecture i386 in file usersblahios appmyappzbarsdklibzbara 2 slicesundefined symbols for architecture i386 objc class zbarreaderviewcontroller referenced from objcclassref in mycontrollero zbarreadercontrollerresults referenced from mycontroller imagepickercontrollerdidfinishpickingmediawithinfo in mycontrollerold symbols not found for architecture i386clang error linker command failed with exit code 1 use v to see invocationi have tried tweaking the libzbara project settings eg build active architecture set to yes but this just results in neither the simulator or device workingthe fact that it works on the device but not the simulator makes me thing there is some weird architectureproject setting causing thisany help much appreciated,['ios'] +350660,capturing all the click event i am thinking of to add a javascript function to capture all the a click events inside a html pageso i am adding a global function that governs all the a click events but not adding onclick to each neither using onclick nor attacheventonclick nor inline onclick i will leave each a as simple as a hrefsomeurl within the html without touching them i tried windowonclick function e but that just captures all the clickshow do i specify only the clicks on a and to extract the links inside a that is being clickedthank you,['javascript'] +350671,play 20java vs play 20scala i am thinking about migrating to play 20 after play 12 one thing that bothers me is that people say scala is more preferred for a play 20 application i know the differences over 12 and 20 but i am unsure if there are differences between play 20 with java and play 20 with scalaso there are questions in my mind is there anything that i cannot do with java over scala in a play20 applicationwhat advantages do i have if i start to learn and use scala in aplay 20 application,['java'] +350703,getting visitors country from their ip i want to get visitors country via their ip right now i am using this here is my codephpif isset serverhttp client ip real ip adress serverhttp client ipif isset serverhttp x forwarded for real ip adress serverhttp x forwarded forelse real ip adress serverremote addrcip real ip adressiptolocation cipcreatorlocation file get contentsiptolocationwell it is working properly but the thing is this returns the country code like us or ca and not the whole country name like united states or canadaso is there any good alternative to hostipinfo offers thisi know that i can just write some code that will eventually turn this two letters to whole country name but i am just too lazy to write a code that contains all countriesps for some reason i do not want to use any ready made csv file or any code that will grab this information for me something like ip2country ready made code and csv,['php'] +350726,using resources with custom controller names i am using nested resources however i come across controller names that should be more descriptivefor instance i have a controller productscontroller and imagescontrollerresources products do resources imagesendthis works fine but later i might need to use the imagecontroller for other than products images therefore it should be named productsimagescontrollerbut how can i specify the controller name on resources without falling back to something ugly likematch productsimages products imagesindexmatch productsimagesnew products imagesnew,['ruby-on-rails'] +350744,producerconsumer multithreading backgroundlacking money for school i am working night shifts at a tollbooth and using the internet to teach myself some coding skills hoping for a better job tomorrow or the online sale of some app i make long nights few customersi am tackling multithreading as a topic as i encounter a lot of code in literature eg android sdk which uses it but i still find it obscurespiritmy approach at this point is try to code the most basic multithreading example i can think of bang my head against the wall a little and see if i can stretch my brain into accomodating some novel way of thinking i am exposing myself to my limits to hopefully surpass them feel free to criticise wildly to the point of nitpicking and point out better ways of doing what i am trying to doobjectiveget some advice on how to do the above based on my efforts so far code providedthe exerciseheres the scope i definedefinitioncreate two classes which work in tandem on the production of data objects and consumption thereof one thread creates objects and delivers them to a shared space for the other to pick up and consume let us call the producing thread producer the consuming thread consumer and the shared space sharedspace the act of producting objects for consumption by the other could be assimilated by means of analogy to this scenarioproducer a busy mum making chocolatecovered cakes for his child up to a limitconsumer a hungry child waiting to eat all cakes the mum makes until told to stopsharedspace a kitchen table on which the cakes are put as soon as they become readydatavalue a chocolatedripping cake which must be eaten immediately or elseto simplify the exercise i decide not to allow the mum to be cooking as the child eats his cake she will just wait for the child to finish his cake and instantaneously make another one up to a certain limit for good parenting the essence of the exercise is to practise the signalling of the threads over achieving any concurrency at all on the contrary i am focussing on perfect serialisation with no polling or can i go yet checks i suppose i will have to code the followon exercise in which mother and child work in parallel next approachhave my classes implement the runnable interface so they have a code entry point of their own use my classes as constructor arguments to thread objects which are instantiated and started from the programs main entry point ensure the main program does not terminate before the threads do by means of threadjoin set a limit to the number of times the producer will create data for the consumeragree on a sentinel value the produce will use to signal end of data productionlog acquisition of locks on the shared resource and data productionconsumption events including final signing off of worker threadscreate a single sharedspace object from the programs main and pass it to each worker before startstore a private reference to the sharedspace object internally to each workerprovide guard against and messages to describe the condition of a consumer being ready to consume before any data has been producedstop the producer after a given number of iterationsstop the consumer after it reads the sentinel valuecodeimport orgslf4jloggerimport orgslf4jloggerfactoryclass consumer extends threaded public consumersharedspace sharedspace supersharedspace override public void run superrun int consumeddata 0 while consumeddata 1 synchronized sharedspace loggerinfoacquired lock on sharedspace consumeddata sharedspacedatavalue if consumeddata 0 try loggerinfodata production has not started yet releasing lock on sharedspace until notification that it has begun sharedspacewait catch interruptedexception interruptedexception loggererrorinterruptedexceptiongetstacktracetostring else if consumeddata 1 loggerinfoconsumed end end of data production token else loggerinfoconsumed consumeddata loggerinfowaking up producer to continue data production sharedspacenotify try loggerinforeleasing lock on sharedspace until notified of new data availability sharedspacewait catch interruptedexception interruptedexception loggererrorinterruptedexceptiongetstacktracetostring loggerinfosigning off class producer extends threaded private static final int and iterations 10 public producersharedspace sharedspace supersharedspace override public void run superrun int niterations 0 while niterations and iterations synchronized sharedspace loggerinfoacquired lock on sharedspace niterations if niterations and iterations sharedspacedatavalue niterations loggerinfoproduced niterations else sharedspacedatavalue 1 loggerinfoproduced end end of data production token loggerinfowaking up consumer for data consumption sharedspacenotify if niterations and iterations try loggerinforeleasing lock on sharedspace until notified sharedspacewait catch interruptedexception interruptedexception loggererrorinterruptedexceptiongetstacktracetostring loggerinfosigning off class sharedspace volatile int datavalue 0abstract class threaded implements runnable protected logger logger protected sharedspace sharedspace public threadedsharedspace sharedspace thissharedspace sharedspace logger loggerfactorygetloggerthisgetclass override public void run loggerinfostarted string workername getclassgetname threadcurrentthreadsetnameworkername public class producerconsumer public static void mainstring args sharedspace sharedspace new sharedspace thread producer new threadnew producersharedspace producer thread consumer new threadnew consumersharedspace consumer producerstart consumerstart try producerjoin consumerjoin catch interruptedexception interruptedexception interruptedexceptionprintstacktrace execution logconsumer startedconsumer acquired lock on sharedspaceconsumer data production has not started yet releasing lock on sharedspace until notification that it has begunproducer startedproducer acquired lock on sharedspaceproducer produced 1producer waking up consumer for data consumptionproducer releasing lock on sharedspace until notifiedconsumer acquired lock on sharedspaceconsumer consumed 1consumer waking up producer to continue data productionconsumer releasing lock on sharedspace until notified of new data availabilityproducer acquired lock on sharedspaceproducer produced 2producer waking up consumer for data consumptionproducer releasing lock on sharedspace until notifiedconsumer acquired lock on sharedspaceconsumer consumed 2consumer waking up producer to continue data productionconsumer releasing lock on sharedspace until notified of new data availabilityproducer acquired lock on sharedspaceproducer produced 3producer waking up consumer for data consumptionproducer releasing lock on sharedspace until notifiedconsumer acquired lock on sharedspaceconsumer consumed 3consumer waking up producer to continue data productionconsumer releasing lock on sharedspace until notified of new data availabilityproducer acquired lock on sharedspaceproducer produced 4producer waking up consumer for data consumptionproducer releasing lock on sharedspace until notifiedconsumer acquired lock on sharedspaceconsumer consumed 4consumer waking up producer to continue data productionconsumer releasing lock on sharedspace until notified of new data availabilityproducer acquired lock on sharedspaceproducer produced 5producer waking up consumer for data consumptionproducer releasing lock on sharedspace until notifiedconsumer acquired lock on sharedspaceconsumer consumed 5consumer waking up producer to continue data productionconsumer releasing lock on sharedspace until notified of new data availabilityproducer acquired lock on sharedspaceproducer produced 6producer waking up consumer for data consumptionproducer releasing lock on sharedspace until notifiedconsumer acquired lock on sharedspaceconsumer consumed 6consumer waking up producer to continue data productionconsumer releasing lock on sharedspace until notified of new data availabilityproducer acquired lock on sharedspaceproducer produced 7producer waking up consumer for data consumptionproducer releasing lock on sharedspace until notifiedconsumer acquired lock on sharedspaceconsumer consumed 7consumer waking up producer to continue data productionconsumer releasing lock on sharedspace until notified of new data availabilityproducer acquired lock on sharedspaceproducer produced 8producer waking up consumer for data consumptionproducer releasing lock on sharedspace until notifiedconsumer acquired lock on sharedspaceconsumer consumed 8consumer waking up producer to continue data productionconsumer releasing lock on sharedspace until notified of new data availabilityproducer acquired lock on sharedspaceproducer produced 9producer waking up consumer for data consumptionproducer releasing lock on sharedspace until notifiedconsumer acquired lock on sharedspaceconsumer consumed 9consumer waking up producer to continue data productionconsumer releasing lock on sharedspace until notified of new data availabilityproducer acquired lock on sharedspaceproducer produced 10producer waking up consumer for data consumptionproducer releasing lock on sharedspace until notifiedconsumer acquired lock on sharedspaceconsumer consumed 10consumer waking up producer to continue data productionconsumer releasing lock on sharedspace until notified of new data availabilityproducer acquired lock on sharedspaceproducer produced end end of data production tokenproducer waking up consumer for data consumptionproducer signing offconsumer acquired lock on sharedspaceconsumer consumed end end of data production tokenconsumer signing offquestionis the above correct eg does it use the correct language tools the right approach does it contain any stupid code but it looks righti ask about correctness even if the output looks good because you cannot imagine how many times things went wrong in my testing one time and not the other eg when the consumer started first when the producer never quit after producing the sentinel etc i have learnt not to claim correctness from a successful run on the contrary i have become very suspicious of pseudoparallel code this one is not even parallel by definition0extended answersa good question focuses on just one requested piece of advice the one above but feel free to mention any insights into the following other topics in your answer if you likehow could i test parallel code as i code my next attempts which tools can help me in both development and debugging consider i use eclipsewould the approach change if i allowed the producer to continue producing with each production taking some variable amount of time whilst the consumer consumes anything that becomes available would locking have to be moved elsewhere would signalling need to change from this waitnotify paradigmis this method of doing things obsolete and should i rather be learning something else from this tollbooth i have no idea of what happens in the real world of javanext stepswhere should i go from here i have seen the notion of futures mentioned somewhere but i could use a numbered list of topics to work through in sequence pedagocially ordered with links to associated learning resourcestino sino,['java'] +350752,instructions reordering in java jvm i was reading this blogpost and the author was talking about breaking the hashcode in string in multithread environmentby havingpublic int hashcode int h hash if h 0 int off offset char val value int len count for int i 0 i len i h 31h valoff hash h return h changed topublic int hashcode if hash 0 int off offset char val value int len count int h 0 for int i 0 i len i h 31h valoff hash h return hash which the author says and i quotewhat i have done here is to add an additional read the second read of hash before the return as odd as it sounds and as unlikely as it is to happen the first read can return the correctly computed hash value and the second read can return 0 this is allowed under the memory model because the model allows extensive reordering of operations the second read can actually be moved in your code so that your processor does it before the firstso further going through comments someone says it can be reordered toint h hashif hash 0 return hhow is that possible i thought reordering only involves moving program statements up and down what rules is it following i have googled read the jsr133 faq checked the java concurrency in practice book but i cannot seem to find a place that helps me to understand particularly on reordering if anyone can point me to the right direction i would really appreciate itedit thanks to louis clarifying the meaning of reordering i was not thinking in terms of bytecodehowever i still do not understand why is it allowed to move the 2nd read to the front this is my naive attempt to translate it to somewhat bytecode formatfor simplification purpose operations that are used to calculate the hashcode are express as calchash therefore i express the program asif hash 0 h calchash hash hreturn hashand my attempt to express it in bytecode formr1r2r3 are in the operands stack or the registersh is in the array of local variablesin program orderif hash 0 r1 read hash from memory 1st read compare r1 0 h calchash r2 calchash h r2 storing the r2 to local variable h hash h hash h write to hashreturn hash r3 read hash from memory again2nd read return r3reordered transformationmy version based on comments r3 read hash from memory 2nd read movedif hash 0 r1 read hash from memory 1st read compare r1 0 h calchash r2 calchash h r2 storing the r2 to local variable h hash h hash h write to hashreturn hash return r3edit checking the comments again i found this answered by the authorreordered transformationfrom the blogr1 hashif hash 0 r1 hash calculate hashreturn r1this case actually works on single thread but it is possible to fail with multiple threadsit seems that the jvm are making simplifications based onh hash and it simplifies the use of r1 r2 r3 to single r1therefore jvm does more than reordering instructions it also seems reducing the amount of registers being used any thoughts,['java'] +350766,android save array of custom objects i have a question about saving an arraylist of custom objects i have a class called notitiepublic class notitie implements serializableprivate string titel private string type private string datum public void settitel string titel thistitel titelpublic string gettitel return titelpublic void settype string type thistype typepublic string gettype return typepublic void setdatum string datum thisdatum datumpublic string getdatum return datumi create some objects of notitie and add them to my arraylist called notitiesarraylistnotitie notities new arraylistnotitienotitie notitie1 new notitienotitie1settitelmetingnotitie1settypewatermetingnotitie1setdatum220912notitiesaddnotitie1notitie notitie2 new notitienotitie1settitelmeting2notitie1settypewatermeting2notitie1setdatum230912notitiesaddnotitie2notitie notitie3 new notitienotitie1settitelmeting3notitie1settypewatermeting3notitie1setdatum240912notitiesaddnotitie3now i want to save the filled arraylist on the devices storage so it can be accessed anytime i used to save data as a string or some integers with sharedpreferences but i cannot save this arraylist with that does anybody have a solutionthanks in advance,['android'] +350772,showing hiding then reshowing layouts breaks events having trouble showing hiding and then reshowing marionette layouts i believe this problem also applies to regular backbone views and marionette itemviews as well thoughin summary i have a parent view when it is initialized it creates two child layouts that are meant to be used as tab content the problem is that when tab content from one tab is shown then content from another tab is shown instead when the original tab content is shown again the events do not work anymorethe child layouts are created in the initialize function of the parent layout and reused because their states need to be preserved when navigation moves back to themhere is a sample application that demonstrates what i am talking abouthere is a video showing the broken events video linkthanks so much,['javascript'] +350780,how to get a uri object from bitmap on a certain tap event i ask the user to add an image so i provide two options to add from galleryto click a new image from cameramy aim is to keep a list of uris related to those imagesif the user chooses gallery then i get the image uri which is quite simplebut if he chooses camera then after taking a picture i am getting the bitmap object of that picturenow how do i convert that bitmap object to uri or in other words how can i get the relative uri object of that bitmap objectthanks,['android'] +350800,java countdown timer without gui basically i am making a text based game not so much a game more of a way to improve basic java skills and logic however as part of it i wish to have a timer it would count down on the time i wish from the variable to 0 now i have seen a few ways to do this with a gui however is there a way to do this without a guijframe etcso what i am wondering is can you make a count down from x to 0 without using a guijframe if so how would you go about thisthanks once i have some ideas will edit with progressedit start timerrunnable r new timereggamelengthnew threadrstartabove is how i am calling the threadtimerpublic static void mainint count if i then have this in the timereg class the timer complies however when compiling the main in the other thread i getnow am i completely missunderstanding threads and how this would work or is there something i am missingerror constructor timereg in class timereg cannot be applied to given typesrequired no arguments found int reason actual and formal arguments differ in lengthfound on line runnable r new timereggamelength,['java'] +350803,javamail setdebugtrue how can i setdebugtrue on a javamail session but capture the stream and use it in my logging framework short of downloading the source changing the method to accept a stream as a parameter recompiling it more generally is there a standard way in java to hijackandredirect generic stream output in this fashion note that systemout may be already polluted with other output and i have no idea how to filter that,['java'] +350824,something if expression syntax in javascript ff i have seen some examples that show that firefox supports some kind of javascript syntax along the lines of something if expressionas an example of what i am talking about see this mdn article which contains the following examplevar evens i for each i in range0 21 if i 2 0my questions arewhat name would be given to describe this kind of syntax i mainly want to know this so that i can google it and read more about it i have tried googling the best i can come up with but have not been able to put the right terms together to get helpful resultscan this syntax exist in other places outside of an array comprehension i feel like i have seen other examples of this being used outside of an array such as in the example above but i am not surewhere can i read more about this syntaxdo any other browsers support this besides firefoxis this feature in es5 or planned for esharmony,['javascript'] +350844,does dalvik androids jvm support hot code replace i tried with as simple replacing as changing value of string but it does not work i tried running my test app in debug mode but always get hot code replace failed warning message box some sources says that it works but it is very limited and occasionaly ignore all changes other says it does not work at allupdatethis behavior is exactly the same does not work on device and emulator,['android'] +350849,weird namespace pollution when importing submodule in a packages init py mainpy import packagepackage init py use function to split local and global namespace def do import print globalskeys print localskeys import foo as mod print localskeys print globalskeys do importpackagefoopy print hello from fooexecute mainpy will output like this builtins file package path name do import doc hello from foomod builtins file package path name foo do import doc the import in init py did not work as expectednotice that the global namespace has a foo which should bind to local mod onlyeven aexec import foo as mod in name name path path cannot stop global namespace from being modifiedhow could this happen,['python'] +350855,duplicate keys in javautilproperties what is the defined behaviour when there are duplicate keys in a java properties filethingvaluea 1thingvalueb 2thingvaluea 99which value is guaranteed to be used for thingvaluea 1 99 or undefined is this behaviour documented anywherenb i am not asking whether duplicate keys are considered best practice,['java'] +350929,android app restarts upon crashforce close my android app is getting restarted after force close through my entire application which consist of 20 activities i am relying on static data created on a main activity so once the app is getting crashed all my static data is getting lost and when the app auto restarts practically it does not have any essential data to operate uponmy question is upon crash i want this things to happenif the app crashes i do not want the app to restart rather i want all the stacktask related with this app to be wiped out of memory a user can restart it from the beginning againif i cannot prevent app from restart at least i want to preserve essential data so that when the app restarts i can assign them back also when it restarts i want my app to start from the main activityi know when activity crashes android system will bring next activity in stack to foreground and this is reason for my app producing redundant results also i went through the android developers but only thing i got to know was setting up an attribute in manifest androidfinishontasklaunchtrue but unfortunately this is of no help to me i would appreciate your help on solving this issue and also letting me know the cause and analysis,['android'] +350968,adding optgroups dynamically using jquery select idmyelement multiplemultiple option value1category typeoption option value158itemoneoption option value157itemtwooption option value7my typeoption option value20itemthreeoption option value21itemfouroption option value22itemfiveoption option value8category yet anotheroption option value31itemcheeseoption option value32itembrainoptionselecti need to dynamically convert this so that category options anything that does not start with item is an optgroup wrapping whaterver comes after it until the next category option so the above would end up looking likeselect idmyelement multiplemultiple optgroup labelcategory type option value158oneoption option value157twooption optgroup optgroup labelmy type option value20threeoption option value21fouroption option value22fiveoption optgroup optgroup labelcategory yet another option value31cheeseoption option value32brainoption optgroupselecthow can i iterate over this and change values to acheive the desired effect using jquery,['jquery'] +350973,interpretation of results of energy usage instrument tool i am running energy usage instrument over ios application using a device i wanted to use it to check how much battery is getting drained because of the app i am testing it shows energy usage level which is giving me numbers like 1320 1220 etc over different points of time how to interpret the resultsi know it gives relative energy usage on a scale of 020 in terms of 1 how much battery is getting drained because of the app and particular operation2 which operation function is causing this drain3 what number is considered as safe and what number should be considered as high too high4 any other conclusion that we can make i would appreciate if some one can answer above questions or give me link for reference i have searched around and could not find answers to above questions i just found how to find out those relative energy usage numbers only,['ios'] +351081,how to check for null list in freemarker say my java code has liststring lists null and i pass this to my template filenow i want to make sure that if list has some data then only do something i have triedif lists nullandif listsandif listssize0but none of these seem to be working i have some logic i my java code through which if some condition is true then i new this lists and populate it hence i need to know if the lists has been populated or is null only in my template filehow do i do this thanksedit also i have a list of structures each containing this listspopulated or not is a different issue and i am passing the entire list of structure hence passing a boolean value to the template file along with my list of structures is not possible since i will have to traverse within each list and that traversal i want to do in the template file itselfedit 2 for those who know whats java null freemarker 23x treats them as missing values simply the template language does not know the concept of null for example if you have a bean that has a maidenname property and the value of that property is null then that is the same as if there were no such property at all as far as the template is concerned assuming you did not configured freemarker to use some extreme object wrapper that is the result of a method call that returns null is also treated as a missing variable again assuming that you use some usual object wrapper see more in the faqfreemarker manualbut i still havent got the answer for how to make it work if at all i can,['java'] +351085,uipageviewcontroller in ios6 in ios6 in the methods viewcontrollerafterviewcontroller and viewcontrollerbeforeviewcontroller if i return nil for block the page navigation when i am in the first or last page the app crash with this exceptionthe number of view controllers provided 0 does not match the number required 1 for the requested transitionin ios5 all works good,"['iphone', 'ios', 'objective-c']" +351101,selecting both min and max from the table is slower than expected i have a table mytable with a date column sdate which is the primary key of the table and has a unique index on it when i run this queryselect minsdate from mytableit gives answer instantly the same happens for select maxsdate from mytablebut if i query both togetherselect minsdate maxsdate from mytableit takes much more time to execute i analyzed the plans and found when one of min or max is queried it uses index full scanminmax but when both are queried at the same time it does a full table scan whytest dataversion 11gcreate table mytable sdate date not null cell varchar210 data numbertablespace chips pctfree 10 pctused 40 initrans 1 maxtrans 255 storage initial 64k minextents 1 maxextents unlimited alter table mytable add constraint pk sdate primary key sdate using index tablespace system pctfree 10 initrans 2 maxtrans 255 storage initial 64k minextents 1 maxextents unlimited load tabledeclare i integerbegin for i in 0 10 loop insert into mytablesdate cell data valuessysdate i24 t i i commit end loopendgather stats begin dbms statsgather table statstabname mytable ownname sysendplan1plan2,['sql'] +351108,iphone 5 tabbar not working after adding possible duplicateiphone 5 tabbar not functioning in proper position i added the magic default568hpng to my project and my app resized itself so far so good but my uitabbar is not working anymore it is delegate is not called i first thought it is covered by another view but it is not the delegate is there and it is all working on my old iphone 4 any ideas,['iphone'] +351128,presentviewcontroller not supporting orientation in ios 6 i am using this codeif self respondstoselectorselectorpresentviewcontrolleranimatedcompletion self presentviewcontrollernavigationcontrollercustom animatedyes completionnil else self presentmodalviewcontrollernavigationcontrollercustom animatedyes my application has two orientation portrait and portrait upside down this code works well with ios 51 but orientation does not work on ios 6i have also added this code on my navigationcontrollercustom class boolshouldautorotatetointerfaceorientationuiinterfaceorientationinterfaceorientation return interfaceorientation uiinterfaceorientationportrait interfaceorientation uiinterfaceorientationportraitupsidedownnsuintegersupportedinterfaceorientations return uiinterfaceorientationmaskportrait uiinterfaceorientationmaskportraitupsidedownplease help me to solve this issuethanks in advance,"['iphone', 'ios']" +351147,equivalent of div thisplay inlineblock for ie8 ie7 and older browsers this is a fairly generic question about crossbrowser compatibilityat various points in a design i am currenly working on the only way to achieve the layout and style that i want without resorting to using images is to use the thisplayinlineblock css style option however this is not supported by ie8 and other older browsers and this results in my design beign brokenso there are two parts to my question1 is there a method of achieving a similar or equivalent effect for ie82 if not how best can i make my design degrade smoothlyfor your reference heres an example of where this is being used in my designdiv stylewidth20px height20px thisplayinlineblock backgroundcolorrgb200120120 marginright10pxdivdirectit is a 20x20 pixel colour block to explain the colours in a chartmore generally this issue arises whenever i want greater formatting layout control over a particular bit of text etc within a body of textin the design i am currently working on i will be dropping support for the older browser types anyway since it is heavily reliant on the canvas element however i thought this would be a good question to ask as i have come across the problem several times before thanks,"['html', 'css']" +351148,how to detect ios 6 and all minor versions by user agent possible duplicatewhat is the ios 6 user agent string has anybode ideas to do this with a simple regex or something would be nice to thistinct between iphone and ipad as wellany help in building some regexes is appreciated edit user agent strings what is the ios 6 user agent stringthis questions differs from the possible duplicate since i wanted help in building a regex based on the information i already know which can be found in the possible duplicate,['ios'] +351162,opencv using hough circle transformation to detect iris i am newbie to opencv but i want to create iris recognition program although the system with webcam can detect the eyes it cannot however detect the circular iris i am using the hough circle transformation but in case iris in an image is not circular enough system cannot detect it any solution for itthe algorithm used is hough circle transformationiplimage capturedimg cvloadimagecirclejpg1iplimage grayscaleimg cvcreateimagecvgetsizecapturedimg 8 1cvcvtcolorcapturedimg grayscaleimg cv bgr2gray gaussian filter for less noisecvsmoothgrayscaleimg grayscaleimg cv gaussian9 9 detect the circles in the imagecvseq circles cvhoughcirclesgrayscaleimg storage cv hough gradient 2 grayscaleimgheight4 200 100 for i 0 i circlestotal i float p floatcvgetseqelem circles i cvcircle capturedimg cvpointcvroundp0cvroundp1 3 cv rgb02550 1 8 0 cvcircle capturedimg cvpointcvroundp0cvroundp1 cvroundp2 cv rgb00255 3 8 0 cvcircle imgcvpoint rx ry 67 cv rgb25500 3 8 0 cvnamedwindow circles 1 cvshowimage circles capturedimg,['c++'] +351164,ios 6 state preservation and restoration i have implemented ios 6 api for state saving it works after i quit the app and launch back in for some milliseconds the restored view controller fly in but then it is replaced by the main view controller i thisplay at launchi am setting every time the app launch the root view of the main window so this must be the issuehere is my code boolapplicationuiapplication application willfinishlaunchingwithoptionsnsdictionary launchoptions self commoninitializationlaunchinglaunchoptions return yes boolapplicationuiapplication application didfinishlaunchingwithoptionsnsdictionary launchoptions self commoninitializationlaunchinglaunchoptions return yes voidcommoninitializationlaunchingnsdictionary launchoptions static thispatch once t oncetoken thispatch onceoncetoken selfwindow uiwindow alloc initwithframeuiscreen mainscreen bounds override point for customization after application launch static nsstring const kkeychainitemname oauthgooglereader selfviewcontroller viewcontroller alloc initwithnibnameviewcontroller bundlenil selfnavcontroller uinavigationcontroller alloc initwithrootviewcontrollerselfviewcontroller gtmoauth2authentication auth auth gtmoauth2viewcontrollertouch authforgooglefromkeychainfornamekkeychainitemname clientidkclientid clientsecretkclientsecret selfwindowrootviewcontroller selfnavcontroller selfwindow makekeyandvisible bool issignedin auth canauthorize if issignedin nslogsigned else nsstring scope gtmoauth2viewcontrollertouch viewcontroller viewcontroller gtmoauth2viewcontrollertouch alloc initwithscopescope clientidkclientid clientsecretkclientsecret keychainitemnamekkeychainitemname delegateself finishedselectorselectorviewcontrollerfinishedwithautherror selfnavcontroller pushviewcontrollerviewcontroller animatedyes selfwindowrootviewcontroller viewcontroller you can see that in voidcommoninitializationlaunchingnsdictionary launchoptionsi am setting my windows root view i do not know what to put in there perhaps check if there is saved state and then load this method but howthankshere is what i have tried following robs advice boolapplicationuiapplication application didfinishlaunchingwithoptionsnsdictionary launchoptions if selfisrestored selfwindow uiwindow alloc initwithframeuiscreen mainscreen bounds self commoninitializationlaunchinglaunchoptions selfwindow makekeyandvisible return yeswith nothing in willfinishlaunchingi also removed by window code from my commoninitializationlaunching method,['iphone'] +351176,how would a register volatile int i behave in c i understand that a register keyword will assign a register for computing the value and a volatile keyword will read the value from the memory every time when we perform some computation on the variable and basically not optimize the code so if a variable is assigned both these keywords then would it mean that it would essentially be volatile itself i cannot understand the behavior by writing a sample code can anybody shed some light,['c'] +351177,text leftside of a radiobutton with a margin on android i want to have the label the text you set in your radiobutton to show left of the button and have some padding in betweenadding an additional textview into the layout does not work because my radiogroup does not work i can choose multiple buttons if i add anything other then a radiobutton into the radiogroupso how can i change the radiobutton to be textbuttondrawable instead of buttondrawabletext,['android'] +351179,connecting to oracle database through c i need to connect to a oracle db external through visual studio 2010 but i dont want to install oracle on my machine in my project i referenced systemdataoracleclient but its not fulfilling the need i have an oracle sql developer ide in which i run sql queries against oracle db i have this code so far private static string getconnectionstring string connstring host servernamedatabasemydatabaseuidusernamepwdpassword return connstring private static void connectingtooracle string connectionstring getconnectionstring using oracleconnection connection new oracleconnection connectionconnectionstring connectionstring connectionopen consolewritelinestate 0 connectionstate consolewritelineconnectionstring 0 connectionconnectionstring oraclecommand command connectioncreatecommand string sql select from mytablename commandcommandtext sql oracledatareader reader commandexecutereader while readerread string myfield stringreadermyfield consolewritelinemyfield so far i read these blogs so far i have not downloaded anything from oracle what steps should i take to make this happen,['c#'] +351183,how to attach javadoc for jar in eclipse is there any way to attach javadoc for strutsjar in eclipse like we attach it for core java which is a zip file thistributed under jdk,['java'] +351187,add custom message to thrown exception while maintaining stack trace in java i have a small piece of code that runs through some transactions for processing each transaction is marked with a transaction number which is generated by an outside program and is not necessarily sequenced when i catch an exception in the processing code i am throwing it up to the main class and logging it for review later i would like to add the transaction number to this thrown exception is it possible to do this while still maintaining the correct stack tracefor examplepublic static void mainstring args try processmessage catchexception e eprintstacktrace private static void processmessage throws exception string transnbr try transnbr 2345 throw new exception catchexception e iftransnbrequals stack trace originates from here not from actual exception throw new exceptiontransction transnbr else stack trace gets passed correctly but no custom message available throw e,['java'] +351191,whats the difference between colorwithsrgbred vs colorwithdevicered vs colorwithcalibratedred there are several convenience class methods for creating a nscolor however i cannot seem to identify when to use the different class methods belowcolorwithsrgbredgreenbluealpha vs colorwithdeviceredgreenbluealpha vs colorwithcalibratedredgreenbluealpha,['objective-c'] +351196,iphone 5 support with base sdk ios51 is is possible to submit the app with base sdk ios51 and with so that application will not leave an extra black spaceour normal application is working fine on iphone5 leaving a black space from top and bottom but if we just include will it work fine the view thisplayed in complete area of iphone5there are lots of dependencies to support ios6 so is it possible to submit the app with and base sdk ios51,['iphone'] +351214,mapview in ios6 would not show certain zoom levels at latitude 75 north this code sets a default zoom level centered around a specified location in viewdidloadthe code works fine in previous versions of ioscllocationthistance visiblethistance 10 100 kilometersmkcoordinateregion region mkcoordinateregionmakewiththistancelocation visiblethistance visiblethistancemkcoordinateregion adjustedregion mapview regionthatfitsregionmapview setregionadjustedregion animatednohowever in ios6 for locations with latitude above 75 751 the app crashes with the following message terminating app due to uncaught exception nsinvalidargumentexception reasoninvalid region centernan nan spannan nani found that for the given zoom level mapview cannot set a proper mkcoordinateregion internally mapview regionthatfitsregion returns all values as nan if i use the region variable directly it just shows the default map the whole world after some testing i found that by adjusting the visiblethistance i can get the code to work properly the magic thistance seems to be slightly above 20 kilometers somewhere between 22 and 23 km for a series of latitudes and latitudedelta valuesthis happens only on northern latitudes 80 works just finethe maps work at any location after the initial positioning it looks like apple changed the way visible map regions are initialized i am using a higher zoom level for the affected region as a workaround is there any other way to make it work properly,['ios'] +351238,sum all columns with a wildcard name search using python pandas i have a dataframe in python pandas with several columns taken from a csv filefor instance data day p1s1 p1s2 p1s3 p2s1 p2s2 p2s31 1 2 2 3 1 22 2 2 3 5 4 2and what i need is to get the sum of all columns which name starts with p1 something like p1 with a wildcardsomething like the following which gives an errorp1sum datap1is there any why to do this with pandas,['python'] +351296,catching all javascript unhandled exceptions i am trying to find or figure out a way to thisplay in an alert box all of the unhandled javascript exceptions in an application i would want all of this to be done on the client side without using any server side code i am using mvc3 as an environment i have been researching for the last few days and have not found exactly what i am looking for i found 2 ways below that seem like they are almost what i am looking for except these ways are set up so that you have to pass a function name into a custom method to print the stack trace of all unhandled exceptions within that one specific function i am looking for a way to not have to manually pass a function name to a custom method that prints the stack trace of all of the unhandled exceptions i would want these custom method to just listen for all unhandled exceptions within the whole applicationalso something similar to the previous linkheres the basic code from the 2nd link above that prints the stack trace of a specified javascript functioninstrumentfunction function context functionname callback context context window var original contextfunctionname contextfunctionname function instrumented callbackcallthis printstacktraceslice4 return contextfunctionname instrumentedapplythis arguments contextfunctionname instrumented originalfunction printstacktraceoptions options options guess true var ex optionse null guess optionsguess var p new printstacktraceimplementation result prunex return guess pguessanonymousfunctionsresult resultso to sum this up do you all know of any way to have some sort of listener to listen for all javascript unhandled exceptions and then print them to the screen in an alert box thanksjason,['javascript'] +351304,create a group box around certain controls on a web form using css i have three controls on my web form of three drop down listsi want to create a graphical box around these controls the reason for this is that selecting these controls would be step 1 of my process so i want to put a box around these controls and call it step 1how would i go about doing this with cssexample,"['html', 'css']" +351343,q assert release build semantics i cannot find a clear statement on the semantics of q assert under release builds if there is no assertion checking then is the asserted expression evaluated at allconsider the following codeq assertdo something report false if failedwill do something report false if failed run under all potential qt build configurations would it be safer even though a bit more verbose and less readable to do this insteadbool is ok do something report false if failedq assertis okthe latter approach has the downside that assert failures are less verbose but perhaps it shows more clearly that the statement is executed,['c++'] +351348,why does quicksort use ologn extra space i have implemented the below quicksort algorithm online i have read that it has a space requirement of ologn why is this the case i am not creating any extra data structuresis it because my recursion will use some extra space on the stack if this is the case is it possible to do it with less memory by not having it be recursive instead making it iterativeprivate static void quicksort int array int left int right int index partitionarray left right sort left half if left index 1 quicksortarray left index 1 sort right half if index right quicksortarray index rightprivate static int partition int array int left int right int pivot arrayleft right 2 pick pivot point while left right find element on left that should be on right while arrayleft pivot left find element on right that should be on left while arrayright pivot right swap elements and move left and right indices if left right int temp arrayleft arrayleft arrayright arrayright temp left right return left,['java'] +351355,django on heroku dumpdata incomplete output i have been trying to dump a relatively small amount of data 80 rows or so of djangocms text plugin1 remotely via heroku toolbeltheroku run python managepy dumpdata textbut i get random incomplete output that gets closer to eof every run presumably cached1109 pm heroku run python managepy dumpdata text wc c10835109 pm 1206291109 pm 12269310 pm 12294910 pm 15341913 pm 120877anyone run into something similar i am using django 14 with postgresql1 although it is blobs of html o 0 see docsedit assume this is just a limitation pg dumps restore was my backup plan,['python'] +351361,backbone id not being set to model i have tried the following to set an id to my modelvar globalcounter 1var model backbonemodelextend initialize function thisid globalcounter globalcounter 1 mymodel new modelconsolelogmymodegetid prints undefinedhow can i set an id to my models,['javascript'] +351366,how to test a timer i would like to write a test for a method that calls observers in a specific intervall so that they will execute a method the timerobject runs in its own threadmethod of timer to be testedprivate long waittimepublic metronomeint bpm thisbpm bpm thiswaittime calculatewaittime thisrunning falsepublic void run long starttime 0 estimatedtime 0 threadsleeptime 0 running true while running starttime systemnanotime tick notify observers here estimatedtime systemnanotime starttime threadsleeptime waittime estimatedtime threadsleeptime threadsleeptime 0 0 threadsleeptime try threadsleepthreadsleeptime 10l catch interruptedexception e sth went wrong snippet from my testclassprivate int ticksprivate long starttimeprivate long stoptimetestpublic void ticktest metronomesetbpm600 starttime systemnanotime metronomerun long duration stoptime starttime long lowthreshold 80 long highthreshold 90 systemoutprintlnduration asserttruelowthreshold duration asserttrueduration highthreshold overridepublic void updateobservable o object arg ticks ifticks 10 metronomestop stoptime systemnanotime right now my testclass registers as an observer at the object in question so that i can count the number of times tick was executed the test measures the time before and after the execution but it feels awkward to me to test the behaviour this way any suggestions for improving the test,['java'] +351398,using arc is it fatal not to have an autorelease pool for every thread i read thisif you ever create a secondary thread in your application you need to provide it with its own autorelease pool autorelease pools and the objects they contain are thiscussed further inin the ios 5 developer cookbooki am compiling with arc i have been creating many background threads and it seems that i am doing fine none of my background threads are longrunning will all those objects ever be released by say the main threads autorelease pool or whatthis is what i do to call background threadvoiddobackgroundvoid block thispatch queue priority high thispatch asyncthispatch get global queuethispatch queue priority background0 thispatch asyncthispatch get global queue20 block should i change that tovoiddobackgroundvoid block thispatch queue priority high thispatch asyncthispatch get global queuethispatch queue priority background0 thispatch asyncthispatch get global queue20 autoreleasepool block,['ios'] +351432,calendar date to ymmdd format in java how to convert calendar date to ymmdd formatcalendar cal calendargetinstancecaladdcalendardate 1date date calgettime simpledateformat format1 new simpledateformatymmddstring date1 format1formatdate date inactivedate nulltry inactivedate format1parsedate1 catch parseexception e1 todo autogenerated catch block e1printstacktracethis will produce inactivedate wed sep 26 0 ist 2012 but what i need is 20120926 my purpose is to compare this date with another date in my database using hibernate criteria so i need the date object in ymmdd format,['java'] +351452,how to logout facebook using code in rails application ruby on rails omniauth i tried to add more than one twitter and facebook accounts from my page via omniauth in railstwitter working fine using force login parameterbut facebook not supporting thisi can add only one facebook account using authfacebook after i tried to add new facebook account using authfacebook path then it returns to my home page onlyif i browse wfacebookcom in same browser then the login page not appearing the lastly added facebook account page is openingwhen i logout from facebook in browser then i tried authfacebook path its working finesoneed to logout already opened facebook accounts in browser tabs before i hit add facebook link in my pagecan anyone helpthanks,"['javascript', 'jquery', 'ruby-on-rails']" +351457,is httpwebrequestgetresponse required to complete a post for post requests using httpwebrequest when i write to a request stream at what point does the data get sent is it when i close the request stream or when i call getresponse is the getresponse call requiredthe net documentation does not seem to be very clear about what is really happeningheres the code i am curious abouthttpwebrequest request httpwebrequestcreateurl as httpwebrequestrequestmethod postrequestcontentlength jsondatalengthrequestcontenttype applicationjsonstream requeststream requestgetrequeststreamrequeststreamwritejsondata 0 jsondatalengthrequeststreamclosevar response requestgetresponse as httpwebresponsethanks,"['c#', '.net']" +351473,radial menu android with button click i want to design menu like thisi have tried animation but it does not retains position of buttonsif any one have done this type of menu please guide meany help will be appreciated,['android'] +351483,out of memory when allocating cursors i have a memory problem that i cannot figure out i have one class that does all my database retrieving work the error i have is the followingandroiddatabasecursorwindowallocationexception cursor window allocation of 2048 kb failed open cursors733 cursors opened by this proc733the memory allocation error occurs when i do thismdatabaseinterfacegetgraphforlevelleveli know it is a leak because i call this method every 25 seconds roughly and the 5 or 6 first calls go through easily now here are the methods in my databaseinterface classpublic graph getgraphforlevellevel level get the nodes arraylistnode nodes new arraylistnodearraysaslistthisgetnodeswithlevellevel get the edges arraylistedge edges new arraylistedgearraysaslistthisgetedgeswithnodesnodes return new graphnodes edgespublic node getnodeswithlevellevel level listnode l new arraylistnode cursor cursor mdatabasequerynodes null level wrapsqlstringvalueoflevelgetid null null null null while cursormovetonext laddparsenodefromcursorcursor cursorclose return ltoarraynew nodelsize private node parsenodefromcursorcursor cursor level l getlevelwithidcursorgetint2 return new nodecursorgetint0 cursorgetstring1 l cursorgetint4 cursorgetint5i have a lot of methods that call each other but i know it is not a recursion problem because this class works in another app my main question is why does not cursorclose liberate the cursor if i do something likecursor mdatabasequerycursormovetonextnode node new nodecursorgetintcursorcloseis the cursor retained in that casethanks in advance,['android'] +351545,regular expression with exclamation marks on both sides d i have seen the regular expression d inside the php preg match function what the heck is this,['php'] +351566,select thistinct values from a list using linq in c i have a collection of employeeclass employee empname empid emploc emppl empshiftmy list contains empnameempidemplocempplempshift e11l1epl1s1 e22l2epl2s2 e33l3epl3s3 e44l1epl1s1 e55l5epl5s5 e66l2epl2s2i need to take the employees having thistinct values emplocempplempshiftis there is any way to achieve this using linq,"['c#', '.net']" +351584,abstract method in non abstract class i want to know the reason behind the design of restricting abstract methods in non abstract class in c i understand that the class instance would not have the definition and thus they wont be callable but when static methods are definedthey are excluded from the instance too why abstract methods are not handled that way any specific reason for the same they could be allowed in concrete class and the deriving class can be forced to implement methods basically that is what is done in case of abstract methods in an abstract class,['c#'] +351599,how to search for famous logo in scanned image i have following scanned document with the logo on it and i have another black and white image with same logo and style shown in black and white color belowhow do i make sure that the logo is present on this image or notusually i will have many scanned documents ocr will pickup mtnl but sometimes these logos are just made up of symbols not recognized easily by ocrsize and position of logos change they are not fixed many times they may be placed anywhere on the documenti want to organize and catalog scanned images based on the logos and symbols present most documents may or may not be in english may or may not contain any bar codes in such case logo match will helpi have seen aforgenet library but i am not very much sure which methods to combine to do search pixels search is very slow and fails if source destination are of different sizei have heard that youtube does some sort of histogram or heat signature match to see if the video contains any copyrighted material i will be helpful if someone can guide me in this casemy ideal choice would be c and aforgenet otherwise some command line tool will be appreciated,['c#'] +351614,understanding double thispatch c i try to understand how double thispatch works i created an example where a monster and a warrior derived from the abstract class creature could fight the class creature has method fight which is defined in derived classes and in each derived class is defined what happens if warrior fights with warrior or with monster etc i wrote the following codeincludeiostreamusing namespace stdclass monsterclass warriorclass creaturepublic virtual void fightcreature 0class monster public creature void fightwhowarrior w coutmonster versus warriorendl void fightwhomonster m coutmonster versus monsterendl public void fightcreature c cfightwhothisclass warrior public creature void fightwhowarrior w coutwarrior versus warriorendl void fightwhomonster m coutmonster versus warriorendl public void fightcreature c cfightwhothisint mainwarrior wmonster mwfightmthis results in compiler error which i foresex12 10cpp in member function avirtual void monsterfightcreaturea ex12 10cpp1730 error aclass creaturea has no member named afightwhoa ex12 10cpp in member function avirtual void warriorfightcreaturea ex12 10cpp2429 error aclass creaturea has no member named afightwhoabut i do not know how to proceed from here please help,['c++'] +351622,java arrayindexoutofboundsexception null but why is there no stack trace we have the problem that in our logfiles there is the following error20120924 0932590 0utc error host server1 somepackagesomeclass unknown v3raqpadvvaexexhdwgyh pjsqwtghzxcae5j4ydgvwv threadname some error happened javalangarrayindexoutofboundsexception nullthere is only this single line and no exception stack trace the try block in which this exception happens is executing dynamically generated java byte code which was created using javassisti am wondering about two thingsthe javalangarrayindexoutofboundsexception nullno stack trace although it is logged with loggererrormessage theexception inside the catch block which should normally results in a full stack trace my questionswhat kind of code can cause a logging output javalangarrayindexoutofboundsexception null i try to reproduce this with a test programm with no luck i always get something like javalangarrayindexoutofboundsexception index 3 or so could the reason for the fact that there is no stack trace that this code is dynamically generated at runtime and the logger jvm does not know the stack trace or the line number we are currently debugging and investigating to get more infos but maybe this sounds familiar to somebody,['java'] +351632,how to check in python that a file in a folder has changed i need to know in python whenever a new file was addedremovedmodified in a particular directory is there a way for that i am looking for an inofitylike function from posixthanks,['python'] +351637,x509 serial number using java i need to get some data from x509 certificate if i open a certificate file in windows its showing its serial number in this formatex 39 65 70 eb d8 9f 28 20 4e c2 a0 6b 98 48 31 0d the same data i am trying to obtain using java after get it loaded i use x509getserialnumberand result is 76292708057987193002565060032465481997so what is the difference between both of these i want the result as upper one,['java'] +351663,timeout expired on sql azure cannot be reproduced onpremise sql server in our line of business we are hosting a rest based api that is hosted by windows azure and with sql azure as database storageboth the web role windows 2008r2 iis 75 wcf large instance and sql azure is hosted in north europe regionthe problem is that when we do intensive sql work we often get a timeout expired the timeout period elapsed prior to completion of the operation or the server is not respondingwhat troubles me here is that no matter what we do we cannot provoke this on our onpremise sql servers sql server 2008r2any help in clarifying this mystery is appreciated as it seems that the web role instance is not directly talking to the sql azure instance although both are located in north europea more detailed exceptionsqlexception messagetimeout expired the timeout period elapsed prior to completion of the operation or the server is not respondingmessage stacktrace lineat systemdatasqlclientsqlconnectiononerrorsqlexception exception boolean breakconnectionline lineat systemdatasqlclienttdsparserthrowexceptionandwarningline lineat systemdatasqlclienttdsparserrunrunbehavior runbehavior sqlcommand cmdhandler sqldatareader datastream bulkcopysimpleresultset bulkcopyhandler tdsparserstateobject stateobjline lineat systemdatasqlclientsqldatareaderconsumemetadataline lineat systemdatasqlclientsqldatareaderget metadataline lineat systemdatasqlclientsqlcommandfinishexecutereadersqldatareader ds runbehavior runbehavior string resetoptionsstringline lineat systemdatasqlclientsqlcommandrunexecutereadertdscommandbehavior cmdbehavior runbehavior runbehavior boolean returnstream boolean asyncline lineat systemdatasqlclientsqlcommandrunexecutereadercommandbehavior cmdbehavior runbehavior runbehavior boolean returnstream string method dbasyncresult resultline lineat systemdatasqlclientsqlcommandrunexecutereadercommandbehavior cmdbehavior runbehavior runbehavior boolean returnstream string methodline lineat systemdatasqlclientsqlcommandexecutescalarline lineat syncinvokeaddcollaboratorfieldinstanceobject object object line lineat systemservicemodelthispatchersyncmethodinvokerinvokeobject instance object inputs objectamp outputsline lineat systemservicemodelthispatcherthispatchoperationruntimeinvokebeginmessagerpcamp rpcline lineat systemservicemodelthispatcherimmutablethispatchruntimeprocessmessage5messagerpcamp rpcline lineat systemservicemodelthispatcherimmutablethispatchruntimeprocessmessage31messagerpcamp rpcline lineat systemservicemodelthispatchermessagerpcprocessboolean isoperationcontextsetline stacktrace userdefinedinformation helplinkprodnamecdatamicrosoft sql serverhelplinkprodname helplinkprodvercdata11002065helplinkprodver helplinkevtsrccdatamssqlserverhelplinkevtsrc helplinkevtidcdata2helplinkevtid helplinkbasehelpurlcdatahelplinkbasehelpurl helplinklinkidcdata20476helplinklinkid userdefinedinformationsqlexception,['sql'] +351674,java compiler error puzzler inner classes cannot have static declarations except for simple types while coding i have encountered a strange java compiler behaviourwhen compiling the class source below the compiler emits an error inner classes cannot have static declarations on the null class variable this is as expectedhowever no error is generated on the zero class variable this i do not understandwhy this difference which seems to allow static declarations of simple types but not objects in inner classesjavac version 160 24public class outer public static final runnable hello new runnable no compiler error public static final int zero 0 causes compiler error inner classes cannot have static declarations public static final object null null override public void run systemoutprintlnhello zero null,['java'] +351703,i am not getting a warning when i import a void pointer to a struct that has a pointer to a function in a shared object yesterday i was doing some research on dynamic loading of shared objects and about getting pointers to functionsi have been told many times that sharing pointers to functions through void pointers is forbidden by the iso c standard and is still and issue to resolveafter reading johan pettersonas artitle aabout the problem with dlsyma i understand better the reasons and i also understand that being forbidden by the standard does not mean you absolutely must not use it otherwise how do all c programmers work with functions from shared objects with correct iso c code just guessing i might be wrong i am not very expert in cwhile experimenting with my code i found that by sharing a pointer to a struct which contains a reference to the function i want to invoke my compiler will not complain i use wall and pedantic while compilingmy code looks as followsmyclasshppclass myclass public virtual void dosomething void0apihppinclude myclasshppstruct api myclass funcvoidsohppinclude iostreaminclude myclasscppinclude apihppclass childclass public myclass void dosomething void stdcout did itn function to return a new instance of childclass extern c myclass make void return new childclass struct that contains a pointer to the function extern c api interfaceapi interface makehostcppinclude iostreaminclude dlfcnhinclude myclasshppinclude apihppint main void void th dlopensoso rtld lazy error checking was here ifndef usefunction api api static castapi dlsymth interface myclass inst apimake instdosomething else myclass funcvoid reinterpret castmyclass void dlsymth make will never get to this point endif return 0having already compiled soso i then compile my hostcpp fileg ldl wall pedantic hostcpp o hostcompiles fine program correcly prints did it when rung ldl wall pedantic hostcpp o host dusefunctioncomplainsin function aint mainint charawarning iso c forbids casting between pointertofunctionand pointertoobject enabled by defaulti know it is just a warning but why is not the warning print in the first case when using the struct if in the end i am indirectly being able to reference a pointer to a function that resides in a shared objectspeaking of which anybody knows a way to achieve all this in a totally correct iso c manner does it even exist,['c++'] +351709,maven unable to locate the javac compiler in when i try to generate a war file it is showing some error like error unable to locate the javac compiler inerror cprogram filesjavajre7libtoolsjarwhen i do echo path it shows cwindowssystem32dnamename1softwaresmavenapachemaven304bincprogram filesnotepadjdk homewhen i do echo jdk homednamenamecore javasoftwarejavajava 160 04 winjdk160 04bini do not know why maven is refering to jre when my environmental variable is jdk i also changes installed jre to jdk16,['java'] +351732,how to programmatically ignore some acceptance tests using techtalkspecflow and c i have several feature files with some scenarios i need to ignore several scenarios or features marked with some tag depending on some condition i have read specflow documentation but did not find there something that can be useful for my solution i want to use something likebeforescenariosometagpublic static void beforescenario ifignoretests this is the hot spot scenariodosomethingtoignorescenarioifconditionbutrunscenarioifconditionfalse also i tried dynamically add or remove tagsbeforescenariosometagpublic static void beforescenario ifignoretests scenariocontextcurrentscenarioinfotagstolistaddignore but it did not work maybe is there some other way to dynamically add or remove tags or some methods in scenariocontext class which will ignore current scenario,['c#'] +351756,how center modal dialog in scrolled window with position absolute i am trying to center a modal dialog in scrolled window this modal are position absolute because must be draggable in screen i use this plugin for draggable functionmy problem is that this modal has position absolute if i put top 50 it thisplay modal in center window but not considering all scrolled window,"['jquery', 'css']" +351794,how to remove an appended element with jquery and why bind or live is causing elements to repeat now i know this basic question has been asked before but i must be doing something wrong i know that an appended element must bound before i can do anything to it however try as i might i cannot get it to worki am pulling in a message and thisplaying when people click a radio select when ever i try to bind the new element it stacks in odd ways it will start to stack the elements eg click 1message 1 click 2 message 1 and 2 and so oni have tried a whole bunch of different ways to bind it my hope was the remove would strip feedback and then create and bind the next message i must be doing something terribly wrong i know this is very similar to other posts but i went through all of them and was not able to find a clear enough answer to help thank you in advancethe htmldiv classanswers ul li input idanswer typeradio onclickfeedbackthe message htmllabellabellabel li uldivjavascriptfunction feedbackmessage answerliveclick function feedbackremove answerliveclick function answersappenddiv idfeedbackmessagediv,['jquery'] +351814,how do i programmatically drop a milestone onto a block timeline in visio i am trying to programmatically create a timeline and markers using the visio 2010 com interops my code is based off of chris castillos 2 part blog posting part 1 part 2 which is the only semicomplete example i have been able to find on how to do this however his blog from 2004 does not seem to work right the milestones are not really connected to the timeline and updating their date does not get them to move to the right placeany suggestions or fixesimports microsoftofficeinteropvisioimports systemdiagnosticscodeanalysisimports systemruntimeinteropservicesdim visioapp as new applicationdim mydoc as document visioappdocumentsadim mypage as page mydocpagesitem1dim timelinestencils as document visioappdocumentsaddtimeline shapesvssdim thetimeline as shapedim themilestone as shapevisioappalertresponse 1thetimeline mypagedrop timelinestencilsmastersitemublock timeline 5610236 5511811thetimelinecellsuuservisbegindateformulau visioappconvertresult 112004 visunitcodesvisdate visunitcodesvisinchesthetimelinecellsuuservisenddateformulau visioappconvertresult 12312004 visunitcodesvisdate visunitcodesvisinchesvisioappaddonstsruncmd3themilestone mypagedrop timelinestencilsmastersitemuline milestone 5610236 5511811themilestonecellsuuservismilestonedateformulau visioappconvertresult 712004 visunitcodesvisdate visunitcodesvisinchesvisioappalertresponse 0,['c#'] +351863,why are extra parenthesis in file read function i understand that the following code from here is used to read the contents of a file to stringinclude fstreaminclude string stdifstream ifsmyfiletxt stdstring content stdistreambuf iteratorcharifs stdistreambuf iteratorchar however i do not understand why such seemingly redundant parentheticals are required for example the following code does not compileinclude fstreaminclude string stdifstream ifsmyfiletxt stdstring contentstdistreambuf iteratorcharifs stdistreambuf iteratorchar why are so many parentheses are needed for this to compile,['c++'] +351867,avcaptureoutput capturestillimageasynchronouslyfromconnection never completes on iphone5 in my application i am thisplaying a avcapturevideopreviewlayer and then capturing a still image when the user clicks a button using the capturestillimageasynchronouslyfromconnection function in avcaptureoutput this has worked well for me up until the iphone 5 on which it never completes my setup code isselfimageoutput avcapturestillimageoutput alloc initnsdictionary outputsettings nsdictionary alloc initwithobjectsandkeys avvideocodecjpeg avvideocodeckey nilselfimageoutput setoutputsettingsoutputsettingsselfcapturesession avcapturesession alloc init autoreleaseselfcapturesession addinputselfrearfacingdeviceinputselfcapturesession addoutputselfimageoutputselfcapturesession setsessionpresetavcapturesessionpresetphotoselfpreviewlayer avcapturevideopreviewlayer alloc initwithsessionselfcapturesessionselfpreviewlayerframe cgrectmake0 0 320 427selfpreviewlayervideogravity avlayervideogravityresizeaspectselfcapturesession startrunningoutputsettings releasemy capture method isavcaptureconnection videoconnection nilfor avcaptureconnection connection in selfimageoutputconnections for avcaptureinputport port in connection inputports if port mediatype isequalavmediatypevideo videoconnection connection break if videoconnection break code to abort if not return soonselfimageoutput capturestillimageasynchronouslyfromconnectionvideoconnection completionhandler cmsamplebufferref imagesamplebuffer nserror error use image herecapturestillimageasynchronouslyfromconnection never completes for me using an iphone5 i have testedit is not os 6 as this code works on both an iphone 4s and an ipod ipod touch 4th generation that have been updatedthe capturesession is runningvideoconnection is not nilimageoutput is not nilalsoi am using this method and not uiimagepickercontroller because i need to put the preview as a subviewcalling stoprunning on the capture session takes several seconds on the iphone 5 as well,['ios'] +351870,convert numbers written as words to integers is there an opensource java library for converting string numbers into their equivalent integers for example converting ten into 10 i know how to do it but i would rather not waste my customers time writing one from scratch if there is already a library available,['java'] +351890,initialising double with an expression of incompatible type id im trying to assign a value to a double using the following codedouble thistanceformat selfrunsarrayindexpathrow valueforkeyrunthistancebut i keep getting the following errorinitialising double with an expression of incompatible type idhowever i know the value is a double is there a way to do this,"['objective-c', 'ios']" +351906,how to get the id of the clicked child view added dynamically to a linearlayout i am adding a child view to a linear layout the child views itself has some textview and imageviews in a relativelayout the child view is added dynamically in the linearlayout on clicking a button right now i am able to add the child view as shown in this picwhat i have to do is uniquely identify which child view has been clicked in order to show appropriate actions my code where i am adding the child viewaddbuttonsetonclicklistenernew viewonclicklistener override public void onclickview v todo autogenerated method stub inflater layoutinflater getsystemservicecontextlayout inflater service customview1 inflaterinflaterlayoutpeople null peoplename textview customview1findviewbyidridpeoplename peoplenamesettextautocompletegettext customview1setidpeopleinvitedrelativelayoutgetchildcount 1 params4 new linearlayoutlayoutparamsviewgrouplayoutparamswrap content viewgrouplayoutparamswrap content customview1setlayoutparamsparams4 peopleinvitedrelativelayoutaddviewcustomview1 params4 any help or suggestions would be appreciated thanks,['android'] +351914,flask broken pipe with requests i would like to send a local rest request in a flask app like thisfrom flask import flask url for requestimport requestsapp flask name approutenamehi methodspostdef hi personname form name name return requestsposturl forhi externaltrue dataformapproutehi methodspostdef hi return hi s requestformnamesending curl x post httplocalhost50johnhi causes the entire flask app to freeze when i send a kill signal i get a broken pipe error is there a way to prevent flask from freezing here,['python'] +351964,where can i check tornados log file i think there was a default log filebut i did not find them yetsometimes the http request process would throw an exception on the screen but i suggest it also go somewhere on the thiskor i wouldnt know what was wrong during a long run testps write an exception handler is another topicfirst i would like to know my questions answeri found something heretopicpythontornadopx4r8tkfa9cbut it also did not mention where can i find those log,['python'] +351973,why is require once echoing entire file contents i have a class in a file evalmathphpif i require it like this require onceevalmathphp the entire contents of that file is echoed out to the screenif i do it like this require once evalmathphp it does nothuhedit source code of evalmathphpevalmath php class to safely evaluate math expressionscopyright c 2005 miles kaufmann name evalmath safely evaluate math expressionssynopsis includeevalmathclassphp m new evalmath basic evaluation result mevaluate22 supports order of operation parentheses negation builtin functions result mevaluate85221sqrt48 create your own variables mevaluatea elnpi or functions mevaluatefxy x2 y2 2xy 1 and then use them result mevaluate3f42a description use the evalmath class when you want to evaluate mathematical expressions from untrusted sources you can define your own variables and functions which are stored in the object try it it is funmethods mevaluteexpr evaluates the expression and returns the result if an error occurs prints a warning and returns false if expr is a function assignment returns true on success meexpr a synonym for mevaluate mvars returns an associative array of all userdefined variables and values mfuncs returns an array of all userdefined functionsparameters msuppress errors set to true to turn off warnings when evaluating expressions mlast error if the last evaluation failed contains a string describing the error useful when suppress errors is onauthor information copyright 2005 miles kaufmannlicense rethistribution and use in source and binary forms with or without modification are permitted provided that the following conditions are met 1 rethistributions of source code must retain the above copyright notice this list of conditions and the following thisclaimer 2 rethistributions in binary form must reproduce the above copyright notice this list of conditions and the following thisclaimer in the documentation andor other materials provided with the thistribution 3 the name of the author may not be used to endorse or promote products derived from this software without specific prior written permission this software is provided by the author as is and any express or implied warranties including but not limited to the implied warranties of merchantability and fitness for a particular purpose are thisclaimed in no event shall the author be liable for any direct indirect incidental special exemplary or consequential damages including but not limited to procurement of substitute goods or services loss of use data or profits or business interruption however caused and on any theory of liability whether in contract strict liability or tort including negligence or otherwise arising in any way out of the use of this software even if advised of the possibility of such damageclass evalmath var suppress errors false var last error null var v arraye271pi314 variables and constants var f array userdefined functions var vb arraye pi constants var fb array builtin functions sinsinharcsinasinarcsinhasinh coscosharccosacosarccoshacosh tantanharctanatanarctanhatanh sqrtabslnlog function evalmath make the variables a little more accurate thisvpi pi thisve exp1 function eexpr return thisevaluateexpr function evaluateexpr thislast error null expr trimexpr if substrexpr 1 1 expr substrexpr 0 strlenexpr1 strip semicolons at the end is it a variable assignment if preg matchsazwss expr matches if in arraymatches1 thisvb make sure were not assigning to a constant return thistriggercannot assign to constant matches1 if tmp thispfxthisnfxmatches2 false return false get the result and make sure it is good thisvmatches1 tmp if so stick it in the variable array return thisvmatches1 and return the resulting value is it a function assignment elseif preg matchsazwssazwssazws expr matches fnn matches1 get the function name if in arraymatches1 thisfb make sure it is not built in return thistriggercannot redefine builtin function matches1 args explode preg replaces matches2 get the arguments if stack thisnfxmatches3 false return false see if it can be converted to postfix for i 0 icountstack i freeze the state of the nonargument variables token stacki if preg matchazw token and in arraytoken args if array key existstoken thisv stacki thisvtoken else return thistriggerundefined variable token in function definition thisffnn arrayargsargs funcstack return true else return thispfxthisnfxexpr straight up evaluation woo function vars output thisv unsetoutputpi unsetoutpute return output function funcs output array foreach thisf as fnndat output fnn implode datargs return output here be internal methods convert infix to postfix notation function nfxexpr index 0 stack new evalmathstack output array postfix form of expression to be passed to pfx expr trimstrtolowerexpr ops array ops r array01 rightassociative operator ops p array0011 12 operator precedence expecting op false we use this in syntaxchecking the expression and determining when a is a negation if preg matchws expr matches make sure the characters are all good return thistriggerillegal character matches0 while1 1 infinite loop op substrexpr index 1 get the first character at the current index find out if were currently at the beginning of a numbervariablefunctionparenthesisoperand ex preg matchazwd substrexpr index match if op and expecting op is it a negation instead of a minus stackpush put a negation on the stack index elseif op we have to explicitly deny this because it is legal on the stack return thistriggerillegal character but not in the input expression elseif in arrayop ops or ex and expecting op are we putting an operator on the stack if ex are we expecting an operator but have a numbervariablefunctionopening parethesis op index it is an implicit multiplication heart of the algorithm whilestackcount 0 and o2 stacklast and in arrayo2 ops and ops rop ops pop ops po2 ops pop ops po2 output stackpop pop stuff off the stack into the output many thanks polish notationthe algorithm in detail stackpushop finally put our operator onto the stack index expecting op false elseif op and expecting op ready to close a parenthesis while o2 stackpop pop off the stack back to the last if is nullo2 return thistriggerunexpected else output o2 if preg matchazw stacklast2 matches did we just close a function fnn matches1 get the function name arg count stackpop see how many arguments there were cleverly stored on the stack thank you output stackpop pop the function and push onto the output if in arrayfnn thisfb check the argument count ifarg count 1 return thistriggertoo many arguments arg count given 1 expected elseif array key existsfnn thisf if arg count countthisffnnargs return thistriggerwrong number of arguments arg count given countthisffnnargs expected else did we somehow push a nonfunction on the stack this should never happen return thistriggerinternal error index elseif op and expecting op did we just finish a function argument while o2 stackpop if is nullo2 return thistriggerunexpected oops never had a else output o2 pop the argument expression stuff and push onto the output make sure there was a function if preg matchazw stacklast2 matches return thistriggerunexpected stackpushstackpop1 increment the argument count stackpush put the back on well need to pop back to it again index expecting op false elseif op and expecting op stackpush that was easy index allow neg true elseif ex and expecting op do we now have a functionvariablenumber expecting op true val match1 if preg matchazw val matches may be func or variable w implicit multiplication against parentheses if in arraymatches1 thisfb or array key existsmatches1 thisf it is a func stackpushval stackpush1 stackpush expecting op false else it is a var w implicit multiplication val matches1 output val else it is a plain old var or num output val index strlenval elseif op miscellaneous error checking return thistriggerunexpected elseif in arrayop ops and expecting op return thistriggerunexpected operator op else i do not even want to know what you did to get here return thistriggeran unexpected error occured if index strlenexpr if in arrayop ops did we end with an operator bad return thistriggeroperator op lacks operand else break while substrexpr index 1 step the index past whitespace pretty much turns whitespace index into implicit multiplication if no operator is there while is nullop stackpop pop everything off the stack and push onto output if op return thistriggerexpecting if there are s on the stack s were unbalanced output op return output evaluate postfix notation function pfxtokens vars array if tokens false return false stack new evalmathstack foreach tokens as token nice and easy if the token is a binary operator pop two values off the stack do the operation and push the result back on if in arraytoken array if is nullop2 stackpop return thistriggerinternal error if is nullop1 stackpop return thistriggerinternal error switch token case stackpushop1op2 break case stackpushop1op2 break case stackpushop1op2 break case if op2 0 return thistriggerdivision by zero stackpushop1op2 break case stackpushpowop1 op2 break if the token is a unary operator pop one value off the stack do the operation and push it back on elseif token stackpush1stackpop if the token is a function pop arguments off the stack hand them to the function and push the result back on elseif preg matchazw token matches it is a function fnn matches1 if in arrayfnn thisfb builtin function if is nullop1 stackpop return thistriggerinternal error fnn preg replacearc a fnn for the arc trig synonyms if fnn ln fnn log evalstackpush fnn op1 perfectly safe eval elseif array key existsfnn thisf user function get args args array for i countthisffnnargs1 i 0 i if is nullargsthisffnnargsi stackpop return thistriggerinternal error stackpushthispfxthisffnnfunc args yay recursion if the token is a number or variable push it on the stack else if is numerictoken stackpushtoken elseif array key existstoken thisv stackpushthisvtoken elseif array key existstoken vars stackpushvarstoken else return thistriggerundefined variable token when were out of tokens the stack should have a single element the final result if stackcount 1 return thistriggerinternal error return stackpop trigger an error but nicely if need be function triggermsg thislast error msg if thissuppress errors trigger errormsg e user warning return false for internal useclass evalmathstack var stack array var count 0 function pushval thisstackthiscount val thiscount function pop if thiscount 0 thiscount return thisstackthiscount return null function lastn1 return thisstackthiscountn,['php'] +351992,ussd service not working i am trying to develop an application which silently thismiss the ussd responsesi have used the code from with minor changes i have created the iextendednetworkserviceaidl in the package comandroidinternaltelephony and ussddumbextendednetworkservice inside the package comcommandusussd the problem is nothing happens after running the application even after restarting the phonecan someone point out what am i doing wrong should i write any additional code for making it workiextendednetworkserviceaidlpackage comandroidinternaltelephony interface used to interact with extended mmiussd network serviceinterface iextendednetworkservice set a mmiussd command to extendednetworkservice for further process this should be called when a mmi command is placed from panel param number the dialed mmiussd number void setmmistringstring number return the specific string which is used to prompt mmiussd is running charsequence getmmirunningtext get specific message which should be thisplayed on popup dialog param text original mmiussd message response from framework return specific user message correspond to text null stands for no popup dialog need to show charsequence getusermessagecharsequence text clear timeout message and preset mmiussd command this should be called when user cancel a predialed mmi command void clearmmistringussddumbextendednetworkservice package comcommandusussd import androidappservice import androidcontentbroadcastreceiver import androidcontentcontext import androidcontentintent import androidcontentintentfilter import androidneturi import androidosibinder import androidospatternmatcher import androidosremoteexception import androidutillog import comandroidinternaltelephonyiextendednetworkservice service implements iextendednetworkservice interface ussddumbextendednetworkservice service must have name comandroidussdiextendednetworkservice of the intent declared in the android manifest file so comandroidphonephoneutils class bind to this service after system rebooted please note service is loaded after system reboot your application must check is system rebooted see utilsysloghaslinestring string string boolean public class ussddumbextendednetworkservice extends service public static final string tag mobileservices public static final string log stamp ussdtestextendednetworkservice bind successfully public static final string uri scheme ussd public static final string uri authority g elnet public static final string uri path public static final string uri par return public static final string uri paron on public static final string uri paroff off public static final string magic on on public static final string magic off off public static final string magic retval retval private static boolean mactive false private static charsequence mretval null private context mcontext null private string msgussdrunning g testingfinal broadcastreceiver mreceiver new broadcastreceiver override public void onreceivecontext context intent intent if intentaction insertequalsintentgetaction mcontext context if mcontext null msgussdrunning ussd blocker running mactive true logdtag activate else if intentaction deleteequalsintentgetaction mcontext null mactive false logdtag deactivate private final iextendednetworkservicestub mbinder new iextendednetworkservicestub override public void setmmistringstring number throws remoteexception logdtag setmmistring number override public charsequence getmmirunningtext throws remoteexception logdtag getmmirunningtext msgussdrunning return msgussdrunning override public charsequence getusermessagecharsequence text throws remoteexception if magic oncontentequalstext mactive true logdtag control on return text else if magic offcontentequalstext mactive false logdtag control off return text else if magic retvalcontentequalstext mactive false logdtag control return return mretval if mactive logdtag getusermessage deactivated text return nulluse this in order to cancel the output on the screen return text string s texttostring store s to the uri uri new uribuilderschemeuri schemeauthorityuri authoritypathuri pathappendqueryparameteruri partexttostringbuild sendbroadcastnew intentintentaction get content uri mactive false mretval text logdtag getusermessage text s return null override public void clearmmistring throws remoteexception logdtag clearmmistring put stamp to the system log when phoneutils bind to the service after android has rebooted application must call link utilsysloghaslinestring string string boolean to check is phone rebooted or no without reboot phone application does not bind tom this service overridepublic ibinder onbindintent intent intentfilter filter new intentfilter filteraddactionintentaction insert filteraddactionintentaction delete filteradataschemeuri scheme filteradataauthorityuri authority null filteradatapathuri path patternmatcherpattern literal registerreceivermreceiver filter do not localize logitag log stamp return mbinderpublic ibinder asbinder logdtag asbinder return mbinderoverridepublic boolean onunbindintent intent unregisterreceivermreceiver return superonunbindintent manifest fileservice androidnamecomcommandusussdussddumbextendednetworkservice intentfilter action androidnamecomandroidussdiextendednetworkservice category androidnameandroidintentcategorydefault intentfilter service,['android'] +351993,javafx 20 and qt for crossplatform application i need a bit of advice from you developers who deal with crossplatform applications specifically programs with a guii will be creating an application soon that needs to be crossplatform and so i have done some preliminary research on two different frameworks javafx 20 and qthonestly both would more than suit my needs so then i asked myself why i would choose one over the other spoiler alert i do not know the answer p i do know that javafx 20 is rather new as of 2012 and is not fully supported across platforms but it will be eventuallythe question i pose is this which one of these would you use for a crossplatform application and what criteria did you look at when making that decisionthank you for taking the time to read this editfor your reference when considering this question the application i will be writing involves readingwriting xml files thisplaying images and creating some small widgets with custom functionality i have written a similar application in c with net but would like advice when considering javafx 20 or qt for crossplatform usabilitythanks again,"['java', 'c++']" +352008,css add background to some columns in grid ok i am new with css and this is just causing me trouble how do i add a background color to multiple columns but not all columns i want one background color on span2 and a different color on span10 the problem i run into is issues with padding when i apply the background to certain columns it would not have a nice even padding around the content does this make sense how do i add a background to certain columns with nested columns and still maintain nice even padding htmldiv classrow bg div claspan10 main hero unit for a primary marketing message or call to action div clasidebar div classherounit h1joinh1 pthis is a template for a simple marketing or informational website it includes a large callout called the hero unit and three supporting pieces of content use it as a starting point to create something more uniquep pa classbtn btnprimary btnlargeregister now raquoap div div example row of columns div classrow div claspan5 div classbotpad h2we are funh2 pdonec id elit non mi porta gravida at eget metus fusce dapibus tellus ac cursus commodo tortor mauris condimentum nibh ut fermentum massa justo sit amet risus etiam porta sem malesuada magna mollis euismod donec sed odio dui p pa classbtn hrefview details raquoap div div div claspan5 div classrightpad botpad h2learn more about yourselfh2 pdonec id elit non mi porta gravida at eget metus fusce dapibus tellus ac cursus commodo tortor mauris condimentum nibh ut fermentum massa justo sit amet risus etiam porta sem malesuada magna mollis euismod donec sed odio dui p pa classbtn hrefview details raquoap div div div divdivcssbg background urlassetsimggridpng borderradius5px less mixin for creating border radiusrightpad paddingright 20pxbotpad paddingbottom 20pxexplanationso the bg class is applying the background then my nested columns have weird padding so i went through and added classes like rightpad to the columns that need right padding and botpad to columns that need padding on the bottom i know how incredibly wrong this is semantically i just do not know how else to get my needed results thankshere is another example of what i am trying to do however they do not provide a solution either,['css'] +352028,how to drag listview item into other tab i have a tab activity that has 3 tabs each tab is a listview i wanted to drag any list item from tab1 and drop it into tab2 i tried a lot but could not find any such example if anyone has an idea please let me know,['android'] +352037,animate the removal of a listview item i am attempting to animate the removal of a listview item using this mlistviewsetonitemclicklistenernew adapterviewonitemclicklistener override public void onitemclickadapterview adapterview final view view final int i long l viewanimatesetduration500xviewgetwidthalpha0f adapterremovetasksgeti adapternotifydatasetchanged it does not work i basically followed the advice of the 4th answer from the top of this post how to animate addition or removal of android listview rowshowever there is some funny drawing stuff going on or recycling or something because while the animation occurs the item below the one that slides off screen also gets deleted for some reason the answer that the question asker eventually marked as correct is unfortunately an rtfm towards the whole of androids source i have looked through there and i cannot find the notifications pulldown in jellybean which i am trying to emulatetiajohn,['android'] +352041,using linkedblockingqueue good enough for multi thread java program i have a consumer and a producer that adds and deletes item objects from the queue if i use the put and take methods is there any thread safety issues i need to still cover this is similar to the bounded buffer problem and i was just wondering if using the blocking queue instead replaces the need for semaphores or monitors the item object itself would probably need synchronization setters but getters do not need lock am i right and lastly i am not quite sure how to test if it is thread safe since i cannot simultaneously make both threads call the take because to order of execution is underterministic any ideas thanks,['java'] +352044,iphone change keyboard language programmatically i am trying to provide a different language support on my ios 5x application whenever native keyboard is opened provide this language in native keyboard programmatically could someone guide me how can i support it i saw a carbon framework but looks like its for mac appsthanks,['iphone'] +352052,crypt difference between ios5 and ios6 i have got a decryptionencryption method using crypt which worked really well on ios5 now i am working with the ios6 sdk and never changed my code but it seems that something is broken i can still encrypt a string with a key and decrypt it but if i use another key to decrypt the same string the cryptstatus coming back from crypt is still 0kccsuccess even when the decryption fails because after that my nsdata is not filled on ios5 i got the error message 4303 which i could handle then any ideas what can be wrong nowmy codechar keyptrkcckeysizeaes2561 bzerokeyptr sizeofkeyptr fill with zeroes for padding fetch key datakey getcstringkeyptr maxlengthsizeofkeyptr encodingnsutf8stringencodingif encryptordecrypt kccdecrypt data gtmbase64 decodedatadatansuinteger datalength data lengthsize t buffersize datalength kccblocksizeaes128void buffer mallocbuffersizesize t numbytesdecrypted 0cryptorstatus cryptstatus cryptencryptordecrypt kccalgorithmaes128 kccoptionpkcs7padding keyptr kcckeysizeaes256 null data bytes datalength buffer buffersize numbytesdecryptedif cryptstatus kccsuccess do something but cryptstatus is always 0edittested it on ipad simulator 5 when i make a decryption with another key the status i receive is 4303 only in ios6 the status coming back is 0,"['objective-c', 'ios']" +352055,how can i implement jquery datatables plugin using c aspnet sql server side processing how can i implement jquery datatables plugin using c aspnet sql server side processing with ajax and webserviceswould like to implement a datatables grid using c and aspnet but it is difficult to find a working example,"['c#', 'jquery', 'asp.net']" +352076,solutions for css based responsive multilevel drop down menus without js dependencies i have been looking at the available responsive drop down menusnavigation bars but nothing seems to be working right i primarily need a css based menu that does not rely on javascript hackswhy not use js js based solutions fail to work on proxy browsers like opera mini a majority of our audience uses that and blackberry browsers do not show work that well with jsa lot of people advocate the use of select menus for mobile navigation an interesting solution but this is again dependent on js and is very tedious for nested multi level menusso then what navigation systems have you come across that might work for you,['css'] +352087,python replace string pattern with output of function i have a string in python say the quick red fox jumps over the lame brown dogi am trying to replace each of the words that begin with with the output of a function that takes the word as an argumentdef my replacematch return match strmatchindexepsuedocodestring the quick red fox jumps over the lame brown dogstringreplacematch my replacematch resultthe quick red2 fox jumps over the lame4 brown dogis there a clever way to do this,['python'] +352106,how to reorder segues in initial views tabbar controller in xcode 45 how do i reorder the initial views tabbar controller elements without having to delete all the segues and re connect them manually in the desired order is there a way to change the order of these after they have been hooked up i was able to do this by just dragging them around in xcode 44 but that option seems to be non available in xcode 45hopefully this is possible from within the storyboard mode but if it is only possible programmatically that is ok too just looking for any proper way to accomplish this without having to delete them all and re hook them up for example how would i move the home item to first position,['ios'] +352116,mysql pivot table query with dynamic columns i am using the following tables for storing product datamysql select from product id name description stock 1 product1 first product 5 2 product2 second product 5 mysql select from product additional id fieldname fieldvalue 1 size s 1 height 103 2 size l 2 height 13 2 color black using the following query to select the records from both tablesmysql select pid pname pdescription maxifpafieldname size pafieldvalue null as size maxifpafieldname height pafieldvalue null as height maxifpafieldname color pafieldvalue null as colorfrom product pleft join product additional as pa on pid paidgroup by pid id name description size height color 1 product1 first product s 103 null 2 product2 second product l 13 black and everything is working correctly because i fill the additional table dynamically it would be nice if the query would also be dynamic in that way i dont have to change the query everytime i put in a new fieldname and fieldvalue,['mysql'] +352126,format an xml string in ruby given an xml string like this somenestedxmlvaluexmlnestedsomewhats the best optionusing ruby to format it readable like some nested xmlvaluexml nestedsomei have found an answer here whats the best way to format an xml string in ruby which is really helpful but it formats xml likesome nested xml value xml nestedsomeas my xml string is a little big in length so it is not readable in this formatthanks in advance,['ruby'] +352146,requesturl always returns http even though ssl is enabled i have prepared an aspnet web application aspnet v20 and i configured it in my iis v75 i used requesturlabsoluteuri in my application and it works fine in my server i deployed the web application on my clients server machine 2008 r2 server but in my clients environment requesturlabsoluteuri always return http url even though they enabled ssl whether any iis settings configured on my clients server machine please guide me,"['c#', 'asp.net']" +352151,what does acme stand for in symfony2 the standard bundle in symfony2 is acme but what does that stand for,['php'] +352187,pop back return value why does not pop back have a return value i have googled regarding this and found out that it makes it more efficient is this the only reason for making it so in the standard,['c++'] +352194,where can i see a gallery of standard library wpf controls where can i see a gallery of wpf controls there must be at least thirty in the standard library i would like to see what they all look like do google autocomplete tells me this is a very popular search but i cannot find squat for comparison here is a gallery of gtk widgets from gnome documentation,['c#'] +352208,how to download file via jquery ajax and c i want to download a file using jquery ajax web method but it is not working here is my jquery ajax call to web methodfunction generateexcel var resulttable jquerydivappendjquerytableappendhdivboxfindtheadcloneappendbdivfindtbodyclone var list resulttablehtml var jsontext jsonstringify list list ajax type post url generatematrixaspxgenerateexcel data jsontext contenttype applicationjson charsetutf8 datatype json success function response failure function response alertresponsed and this is the web method definitionsystemwebserviceswebmethodpublic static string generateexcelliststring list httpcontextcurrentresponseappendheadercontentthisposition attachmentfilenamefileenamexls httpcontextcurrentresponsecharset httpcontextcurrentresponsecachesetcacheabilityhttpcacheabilitynocache httpcontextcurrentresponsecontenttype applicationvndmsexcel httpcontextcurrentresponsewritelist0 httpcontextcurrentresponseend return how to get it done please help me outone more thing i want to download it on client pc not to save it on server,"['c#', 'jquery']" +352214,mysql workbench with sqlite possible duplicateis there a good ide for sqlite is it possible to use mysql workbench with sql lite or is there any other alternatives and similar software,['mysql'] +352217,qml change views on click i am working on a project with my teammy job is to create a gui with qml and c for an embedded systemi have for each view a qml filebut now i want to navigate between themthis mean when i am clicking on a button the view should switchevery view will have a back button so i could go back to my main viewis this possible in qmlif not i have to solve it with c,['c++'] +352228,compare json and bson i am comparing json and bson for serializing objects these objects contain several arrays of a large number of integers in my test the object i am serializing contain a total number of about 120 integers i am only interested in how the sizes compare of the serialized results i am using jsonnet as the library which does the serialization i am using json because i also want to be able to work with it in javascriptthe size of the json string is about 43kb and the size of the bson result is 161kb so a difference factor of about 4 this is not what i expected because i looked at bson because i thought bson is more efficient in storing dataso my question is why is bson not efficient can it be made more efficient or is there another way of serializing data with arrays containing large number of integers which can be easily handled in javascriptbelow you find the code to test the jsonbson serialization read file which contain json string string jsonstring readfile object object newtonsoftjsonjsonconvertdeserializeobject jsonstring filestream fs fileopenwritebsonfilename using newtonsoftjsonbsonbsonwriter bsonwriter new bsonwriter fs closeoutput false newtonsoftjsonjsonserializer jsonserializer new jsonserializer jsonserializerserialize bsonwriter object bsonwriterflush edithere are the resulting files362authkeyakuzzp8c 0gcr0,"['javascript', '.net']" +352323,how do i replace part of a string in php i am trying to get the first 10 characters of a string and want to replace space with i have text substrtext 0 10 text strtolowertextbut i am not sure what to do nexti want the stringthis is the test for stringbecomethis is th,['php'] +352369,when is the appropriate moment in rotation to change the layout parameters of a uicollectionview hopefully a simple question for a relatively new uikit controli have a uicollectionview that has a viewlayout with a single row of cells that are the exact height of the uicollectionview bounds in portrait modetherefore when the ipad is flipped to landscape mode that row becomes taller than the screen itself at which point the layout almost silently fails and complains that the row is taller than the boundswhat is the ideal way to manipulate the characteristics of the viewlayout particularly as it relates to responding to rotation in a viewcontroller,"['iphone', 'ios']" +352373,how can i change the background color of a spinner popup i am trying to set the background color of a spinner popup but everything i have tried did not work properlythis is the spinner controlspinner androidididmyspinner androidlayout widthfill parent androidlayout heightwrap content androidbackgroundnull androiddrawselectorontoptrue when i click on it it shows a popup with a white background and i want to change thatthe xml line wich i use to populate the popup isrelativelayout xmlnsandroid androidlayout widthwrap content androidlayout heightwrap content androidbackgrounddrawablelist selector androidpaddingbottomdimenpadding medium androidlayout marginbottomdimenpadding medium androidorientationvertical relativelayoutand the drawable background list selectorxmlselector xmlnsandroid pressed item androidstate pressedtrue androiddrawablecolorgreen drawabletab press selected item androidstate selectedtrue androiddrawablecolorgreen drawabletab press selector adding a default state to the above xml is ok but the spinner main control shows the item with that background color and i do not want thatanother thing i have tried is to set the application background color to black in stylesxmlstyle nameapptheme parentandroidthemelight item nameandroidbackground0item item nameandroidtextcolorfitem item nameandroidtypefacesansitem stylethat overrides the popup background too but it has undesirable collateral effects is there any way to accomplish this in a simple waythanksps i am using api level 10 233 and the attribute androidpopupbackground does not exist,['android'] +352427,how to open ssrs report from asp web page using report viewer i am trying to open an ssrs report on my web pages using reportviewer for the report serverl url i have httpdb serversreportsserver sensorsqlserverand for my report path i havehttpdb serversreportsserver sensorsqlserverpagesreportvieweraspx2fcustomer1rscommandrenderi have looked through many sites and tutorial on how to add url but i still get an error saying the length of my link must be below 260 characters long rsinvaliditempath i also want to mention that my report server is in native mode my report server is located in another computer so i made sure the processing mode on my report viewer is remote whenever i go to the surver url i can clearly see the list of my reports and when i click on a report i can see it as well so i know my urls are correct i have tried including a slash in front of my report path url replacing 2f with a space nothing seems to work any idea thanks,"['c#', 'asp.net']" +352467,responsive css background images i have a website gfloorseu and i want to make the background in css i have defined a bgimage for the content also responsive unfortunately i really do not have any idea on how to do this except for one thing that i can think of but it is quite a workaround creating multiple images and then using css screen size to change the images but i wanna know if there is a more practical way in order to achieve thisbasically what i wanna achieve is that the image with the watermark g automatically resizes without thisplaying less of the image if it is possible of courselink gfloorseucode i have so far content partcontent backgroundimage urlimagesbgpng backgroundrepeat norepeat position relative width 85 height 610px marginleft auto marginright auto,['css'] +352525,find the avplayer associated with an avplayeritem an avplayeritem can only ever be assigned to one avplayer once an avplayeritem has been added to an avplayer future attempts to add it to a different avplayer will sigabrt the appso given an avplayeritem how can you determinewhat avplayer it is currently associated with andif it has ever been inserted into an avplayer at any point in the pastthe following code demonstrates the problem reliablyavplayeritem item avplayeritem playeritemwithurlnsurl urlwithstringavplayer firstplayer avplayer alloc initfirstplayer replacecurrentitemwithplayeritemitemavplayer secondplayer avplayer alloc initsecondplayer replacecurrentitemwithplayeritemitemand heres the error message terminating app due to uncaught exception nsinvalidargumentexception reason an avplayeritem cannot be associated with more than one instance of avplayer,['ios'] +352535,started process hangs when redirected output is relatively big i ran into this problem today and it took me quite a while to figure it out i was starting a process from within iis redirecting it is standard output and error output so when the process exited i would be able to generate a log with it everything was running fine on my machine but not so well after i published itthe process was supposed to work for just a while and then exit however it just wouldnt it would simply stop responding holding resources like sockets after quite a while i was able to identify the cause of the problem the log generated was too big after commenting consolewriteline from the running process everything worked just finejust for clarifying how i started the processprocess process new processprocestartinfofilename pathprocestartinfoarguments argumentsprocestartinfouseshellexecute falseprocestartinforedirectstandardoutput trueprocestartinforedirectstandarderror trueprocessenableraisingevents trueprocessexited process exitedprocestartand how i handled it is exitprivate static void process exitedobject sender eventargs e process process procesender filewritealltextpath procestandardoutputreadtoend rnexceptionsrn procestandarderrorreadtoendeven though i already know how to fix it i would still like to know what really happened and why since there must be a way for me to create a log as big as i would like,"['c#', 'asp.net']" +352558,properly thisplaying instagram date this is a dirty jsfiddle version of my web app however i do not understand how to properly adjust the date from the unix timestamp all i want to thisplay is the month day and yearany help would be greatly appreciated ithere is the code function ajax type get datatype jsonp cache false url token167410821b07669121a338d0cbe4ff6a5e04543158a4f82 success functiondata consolelogdata okay now lets get to the pretty stuff instagram peektars for var i 0 i 5 i instagramappend div classinstagramfeed img classinstagramimage src datadataiimagesstandard resolutionurl width325px div classighover2 posted by datadataiuserusernamebr posted on datedatadataicreated timetostringbr div div a,['javascript'] +352567,celery versus djcelery i am confused between the differences between these two applications while trying to setup celery on my django projectwhat are the differences between the two if any when reading tutorials online i see them both used and i am not sure which would be best for me it appears that djcelery is kinda like celery but tailored for django but celery does not need to be included in intalled apps while djcelery does thank you,['python'] +352609,how do i use configassetsprecompile for directories rather than single files how do i use configassetsprecompile in production to only include the files in libassetsjavascripts libassetsstylesheets vendorassetsjavascripts and vendorassetsstylesheetsbasically something likeconfigassetsprecompile w pagespecificjs anotherpagejs but used to auto include files in specific directories that are not appassetsjavascripts or appassetsstylesheetsedit adding the solution i ended up using for page specific jsconfigassetsprecompile pagesjs,['ruby-on-rails'] +352637,how to run android system app without root permisson is there any way to run android system app without root permission i can execute system app via adb such asadb shell systembinscreencap p sdcardscreenpngin my own application i wanna run a shell command like that without su command is there any way how does android prevent user apps to execute system app,['android'] +352678,is ios6 simulator buggy when deleting applications frequently when i try to delete an app on the ios 6 simulator that comes with xcode 45 the simulator freezes what i do is just long press on the app delete dialog does not come up and the icons keep on wiggling quitting and reopening the simulator does not help to delete the app i have tried to delete the apps folder from libraryapplication supportiphone simulator51applications folder sometimes this helps but sometimes even this does not delete the icon from the simulator this behavior is independent of the ios version or the device model it is the same whichever modelios i choose the only thing that helps is using the reset contents and settings option of the simulator do you experience the same frustration if so have you figured out a workaround besides resetting the simulator completely,['ios'] +352690,how to check a digital signature from broswer with php i have a javascript that is signing a text string in the browser it uses capicom under internet explorer and windowcrypto under mozilla browsers after the signing process i receive a base64 encoded signatureusing https i upload the signature and the text string to a webserver with a php application from the ssl https i receive the users certificate from this certificate i can extract the users public keynow i want to verify that the signature against the signed text string and the users certificate and public key i have tried with openssl verify php function with no successi always receive an error error0408d077rsa routinesfips rsa verifywrong signature lengthi have the certificate and it is oki have the public key extracted from the certificate and it is also verified and oki have the signature base64 decodedunfortunately i cannot verify the signature i cannot provide a demo or sample because it is only in the local network at the moment,"['php', 'javascript']" +352700,is modern objectivec really a new version ie objectivec 21 in wwdc 2012 apple introduced new syntax for nsnumber literals and collection literals in talk 405 named modern objectivec i have learned objectivec from the book on objectivec 20 by stephen g kochanis modern objectivec going to be objectivec 21 or should the new syntax of apple be considered as an alternative applespecific syntax shorthand for existing constructs that are processed by the compileri did some research online but found the terms modern and legacy only in the context of the objectivec runtime i would like to understand what exactly is in the language what are preprocessor instructions and what are compiler directives,['objective-c'] +352705,twitter post ios6 cancel button issue i am in the process of changing my app for ios6 and iphone use i cannot seem to figure out why when i post from twitter using the new social framework i have to press cancel twice to close anybody else have this issue or a fix here is the code for the button ibactiontwitterpostidsenderifslcomposeviewcontroller isavailableforservicetypeslservicetypetwitter myslcomposersheet slcomposeviewcontroller alloc init myslcomposersheet slcomposeviewcontroller composeviewcontrollerforservicetypeslservicetypetwitter myslcomposersheet setinitialtextnsstring stringwithformatthis is my tweet hellomyslcomposersheetservicetype self presentviewcontrollermyslcomposersheet animatedyes completionnilmyslcomposersheet setcompletionhandlerslcomposeviewcontrollerresult result nslogdfsdf switch result case slcomposeviewcontrollerresultcancelled break case slcomposeviewcontrollerresultdone break default break,"['iphone', 'ios']" +352730,ocmock why cannot i expect method on a protocol consider this code which works the loginwithemail method gets expected as well expected authenticationservice ocmockobject mockforclassauthenticationservice class retain authenticationservice expect loginwithemailocmarg any andpasswordocmarg anyversus this code authenticationservice ocmockobject mockforprotocolprotocolauthenticationserviceprotocol retain authenticationservice expect loginwithemailocmarg any andpasswordocmarg anythe second code example fails on line 2 with the following error nsproxy doesnotrecognizeselectorloginwithemailandpassword called unknownm0 error migratortest methodredacted nsproxy doesnotrecognizeselectorloginwithemailandpassword calledauthenticationserviceprotocol declares the methodprotocol authenticationserviceprotocol nsobjectproperty nonatomic retain idauthenticationdelegate authenticationdelegate voidloginwithemailnsstring email andpasswordnsstring password voidlogout voidrefreshtokenendand it is implemented in the classinterface authenticationservice nsobject authenticationserviceprotocolthis is using ocmock for ioswhy does expectfail when the mock is a mockforprotocol,"['objective-c', 'ios']" +352750,how does javascripts indexof resolve references i was confusing myself a little with a thought experiment and now i am looking for some advice its about ecmascript references and the arrayprototypeindexof methodlets start easyvar container more codecontainerpush 5 containerpush 7 containerpush 10 so now we pushed some primitive values into our ecmascript array whether or not that statement is true i will come back for at least i imagined it like this so far a call tocontainerindexof 7 will return 1 as expected the big question i am having is if indexof really compares the primitive value or if in reality a number object is created stored and its reference is getting compared this becomes a little more obvious if we rewrite that like sovar a 5 b 7 c 10var container containerpush a containerpush b containerpush c containerindexof b until this point one could still easily argue that all indexof needs to do is to compare values but now lets look at something like thisvar a name a value 5 b name b value 10 c name c value 15 var container more codecontainerpush a containerpush b containerpush c here we filled that container array with objectreferences and still indexof works as expectedcontainerindexof b 1while a call like thiscontainerindexof name b value 10 obviously returns 1 since we are creating a new object and get a new reference so here it must internally compare references with each other rightcan some ecmascript spec genius confirm that or even better link me some material about that a side question on this would be if there is any possibly way to access an internally stored objectreference within a lexicalenvironment respectively activation object,['javascript'] +352798,cstring to lpctstr conversion i have a cstring variable that i a need to convert to lpctstrconst char i need this conversion so that i can use it as an argument in a function the cstring look like cstring sqltemp tinsert into sw1 filename sw2 value sw7 sw3 it contains an query the prototype of the function is int writebloblpctstr szsqlstat lpctstr szfilepathso could you show me an exemple of how to convert to lpctstr it may be trivial but i am a c beginner and i still get a hang of itthanks,['c++'] +352821,rounding a variable to two decimal places c possible duplicatehow do you round a number to two decimal places in c i am interested in how to round variables to two decimal places in the example below the bonus is usually a number with four decimal places is there any way to ensure the pay variable is always rounded to two decimal places pay 200 bonus consolewritelinepay,['c#'] +352849,why does uiscrollview pause my cathisplaylink i have a view backed by a caeagllayer which is inside a uiscrollview when i begin scrolling the cathisplaylink that calls the draw method of opengl view stops getting calledi verified that my runloop start stop methods do not get called when scrolling the draw method simply does not get called as soon as scrolling begins and resumes getting called as soon as scrolling endsdoes uikit stop a cathisplaylink from firing as soon as scrolling startsthe thisplay link is added to the run loop like thisdl addtorunloopnsrunloop currentrunloop formodensdefaultrunloopmodemaybe there is a conflict with this run loop mode and uiscrollview are there other run loop modes or alternative solutions to keep a cathisplaylink firing even when a uiscrollview is scrollingi thought there can be more than just one cathisplaylink in any application is that wrong,['ios'] +352862,how do i set recipients for uiactivityviewcontroller in ios 6 i am using the new uiactivityviewcontroller class in ios6 to provide the user with various sharing options you can pass an array of parameters to it such as text links and images and it does the rest how do i define recipients for example sharing via mail or sms should be able to accept recipients but i cannot figure out how to invoke this behaviouri do not want to have to have to use mfmessagecomposeviewcontroller and uiactivityviewcontroller separately as that just defeats the purpose of the share controllerany suggestionsuiactivityviewcontroller class referenceedit this has now been submitted apple and subsequently merged with a duplicate bug reportbug report on openradar,"['iphone', 'objective-c']" +352957,virtualenv shell errors i have just installed virtualenv with python 272 on my mac and i followed the guide here but i now get the following errors when i start up my shell every timestevedoreextension could not load user scripts thistributestevedoreextension thistributetraceback most recent call last file librarypython27sitepackagesstevedoreextensionpy line 62 in init invoke kwds file librarypython27sitepackagesstevedoreextensionpy line 74 in load one plugin plugin epload file librarypython27sitepackagessetuptools06c11py27eggpkg resourcespy line 1953 in load if require selfrequireenv installer file librarypython27sitepackagessetuptools06c11py27eggpkg resourcespy line 1966 in require working setresolveselfthistrequiresselfextrasenvinstaller file librarypython27sitepackagessetuptools06c11py27eggpkg resourcespy line 565 in resolve raise thistributionnotfoundreq x put more info herethistributionnotfound thistributestevedoreextension could not load project thistributestevedoreextension thistributetraceback most recent call last file librarypython27sitepackagesstevedoreextensionpy line 62 in init invoke kwds file librarypython27sitepackagesstevedoreextensionpy line 74 in load one plugin plugin epload file librarypython27sitepackagessetuptools06c11py27eggpkg resourcespy line 1953 in load if require selfrequireenv installer file librarypython27sitepackagessetuptools06c11py27eggpkg resourcespy line 1966 in require working setresolveselfthistrequiresselfextrasenvinstaller file librarypython27sitepackagessetuptools06c11py27eggpkg resourcespy line 565 in resolve raise thistributionnotfoundreq x put more info herethistributionnotfound thistributestevedoreextension could not load user scripts thistributestevedoreextension thistributetraceback most recent call last file librarypython27sitepackagesstevedoreextensionpy line 62 in init invoke kwds file librarypython27sitepackagesstevedoreextensionpy line 74 in load one plugin plugin epload file librarypython27sitepackagessetuptools06c11py27eggpkg resourcespy line 1953 in load if require selfrequireenv installer file librarypython27sitepackagessetuptools06c11py27eggpkg resourcespy line 1966 in require working setresolveselfthistrequiresselfextrasenvinstaller file librarypython27sitepackagessetuptools06c11py27eggpkg resourcespy line 565 in resolve raise thistributionnotfoundreq x put more info herethistributionnotfound thistributei do not know if it is affecting this problem but i am using zshi tried to install stevedore through pip sudo pip install stevedore but i get the following errorsudo sh setuptools06c11py27eggprocessing setuptools06c11py27eggremoving librarypython27sitepackagessetuptools06c11py27egg and everything under itcopying setuptools06c11py27egg to librarypython27sitepackagessetuptools 06c11 is already the active version in easyinstallpthinstalling easy install script to usrlocalbininstalling easy install27 script to usrlocalbininstalled librarypython27sitepackagessetuptools06c11py27eggprocessing dependencies for setuptools06c11finished processing dependencies for setuptools06c11txslsmacbookpro sudo pip install stevedore upgraderequirement already uptodate stevedore in librarypython27sitepackagesdownloadingunpacking thistribute from stevedore running setuppy egg info for package thistributeinstalling collected packages thistribute running setuppy install for thistribute before install bootstrap scanning installed packages setuptools installation detected at librarypython27sitepackagessetuptools06c11py27egg egg installation patching renaming librarypython27sitepackagessetuptools06c11py27egg into librarypython27sitepackagessetuptools06c11py27eggold13487644504 patched done relaunching traceback most recent call last file string line 1 in module nameerror name install is not defined complete output from command usrbinpython c import setuptools file tmppipbuildthistributesetuppyexeccompileopen file readreplacern n file exec install record tmppipfapgyhrecordinstallrecordtxt singleversionexternallymanaged before install bootstrapscanning installed packagessetuptools installation detected at librarypython27sitepackagessetuptools06c11py27eggegg installationpatchingrenaming librarypython27sitepackagessetuptools06c11py27egg into librarypython27sitepackagessetuptools06c11py27eggold13487644504patched donerelaunchingtraceback most recent call last file string line 1 in modulenameerror name install is not definedcommand usrbinpython c import setuptools file tmppipbuildthistributesetuppyexeccompileopen file readreplacern n file exec install record tmppipfapgyhrecordinstallrecordtxt singleversionexternallymanaged failed with error code 1 in tmppipbuildthistributestoring complete log in userstxsllibrarylogspiplogi manually installed setuptools as i could not install anything through pip without itwhat has gone wrong here and how can i fix it the internet does not seem to have many cases of the error with stevedore i feel rather stuck at the momentmany thanks,['python'] +352996,ember data saving a model with an association in one request i have two ember models with a relationship like thisappfoo dsmodelextend bar dsbelongstoappbar embedded trueappbar dsmodelextend primarykey blah blah dsattr stringif i create and save a new record like thisfoo appstorecreaterecord appfoofooset bar appbarcreaterecordblah blahblahappstorecommiti see 2 post requests to the serverurl foospayload foobarnullandurl barspayload barblahblahblahthe association is embedded so i would like to seeurl foospayload foobarblahblahblahcan i achieve this with the emberdata rest adapter or do i need to write my own code to do this,['javascript'] +352999,safely using magentos preconfiguration events in the magento ecommerce system there are three events that fire before the system is fully bootstrappedresource get tablename core collection abstract load beforecore collection abstract load afterthese events also fire after magento has bootstrapped whats a safe and elegant and maybe event mage core team blessed way to detect when magento has fully bootstrapped so you may safely use these events if you attempt to use certain features in the prebootstrapped state the entire request will 404 the best i have come up with selflink for context so far is something like thisclass packagename modulename model observer public function observermethodobserver is safe true try store mageappgetsafestore catchexception e is safe false ifis safe return if were still here we could initialize store object and should be well into router initialization but that is a little unwieldy,['php'] +353034,changing the child divs font colors on parent hover i have a question and i am not sure if it is possible but i thought i would try askingsay i had three divsdiv idparent div div idchild div 1bluediv div idchild div 2reddivdivif all text inside parent div is set to black how would i make the child div 1 and child div 2 change fontcolor to blue and red respectively when the parent div is hovered oversorry if this is a bit confusing but is there a way to do this preferably with css only,"['html', 'css']" +353037,java synchronized block vs concurrenthashmap vs collectionssynchronizedmap say if have a synchronized method and within that method i update a hashmap like thispublic synchronized void method1 myhashmapclear populate the hashmap takes about 5 secondsnow while the method1 is running and the hashmap is being repopulated if there are other threads tring to get the value of the hashmap i assume they will get blockednow instead of using sync method if i change hashmap to concurrenthashmap like below whats the behaviourpublic void method1 myconcurrenthashmapclear populate the hashmap takes about 5 secondswhat if i use collectionssynchronizedmap is it the same,['java'] +353065,how to customize aspnet web api authorizeattribute for unusual requirements i am inheriting from systemwebhttpauthorizeattribute to create a custom authorizationauthentication routine to meet some unusual requirements for a web application developed using aspnet mvc 4 this adds security to the web api used for ajax calls from the web client the requirements arethe user must logon each time they perform a transaction to verifysomeone else has not walked up to the workstation after someone haslogged on and walked awayroles cannot be assigned to the web service methods at program timethey must be assigned at run time so that an administrator canconfigure this this information is stored in the system databasethe web client is a single page application spa so the typical forms authentication does not work so well but i am trying reuse as much of the aspnet security framework as i can to meet the requirements the customized authorizeattribute works great for requirement 2 on determining what roles are associated with a web service method i accept three parameters application name resource name and operation to determine which roles are associated with a methodpublic class dothiscontroller apicontroller authorizeapplication myapp resource dothis operation read public string getdata return we did this i override the onauthorization method to get the roles and authenticate the user since the user has to be authenticated for each transaction i reduce the back and forth chatter by performing authentication and authorization in the same step i get the users credentials from the web client by using basic authentication which passes the encrypted credentials in the http header so my onauthorization method looks like thispublic override void onauthorizationhttpactioncontext actioncontext string username string password if getusernameandpasswordactioncontext out username out password if membershipvalidateuserusername password formsauthenticationsetauthcookieusername false baseroles getresourceoperationroles else formsauthenticationsignout baseroles else formsauthenticationsignout baseroles baseonauthorizationactioncontext getusernameandpassword retrieves the credentials from the http header i then use the membershipvalidateuser to validate the credentials i have a custom membership provider and role provider plugged in to hit a custom database if the user is authenticated i then retrieve the roles for the resource and operation from there i use the base onauthorization to complete the authorization process here is where it breaks downif the user is authenticated i use the standard forms authentication methods to log the user in formsauthenticationsetauthcookie and if they fail i log them out formsauthenticationsignout but the problem seems to be that base onauthorization class does not have access to principal that is updated so that isauthenticated is set to the correct value it is always one step behind and my guess is that it is using some cached value that does not get updated until there is a round trip to the web clientso all of this leads up to my specific question which is is there another way to set isauthenticated to the correct value for the current principal without using cookies it seems to me that cookies do not really apply in this specific scenario where i have to authenticate every time the reason i know isauthenticated is not set to the correct value is i also override the handleunauthorizedrequest method to this protected override void handleunauthorizedrequesthttpactioncontext filtercontext if systemwebhttpcontextcurrentuseridentityisauthenticated filtercontextresponse new httpresponsemessagesystemnethttpstatuscodeforbidden else basehandleunauthorizedrequestfiltercontext this allows me to return a status code of forbidden to the web client if the failure was because of authorization instead of authentication and it can respond accordinglyso what is the proper way to set isauthenticated for the current principle in this scenario,['asp.net'] +353110,compiling for ios with cmake i have compiled a c static library by using cmake as my building tool and i want to link it to my ios appi created a simple empty application in xcode and linked my library called libenginea to iti tried to compile my ios project and the linker gave me this warningignoring file usersbuildenginelibenginea file was built for archive which is not the architecture being linked i386usersbuildenginelibengineaas i understand it i need to compile my library for arm processors the problem is i do not know howi think cmake really lacks good tutorialsanyways my cmake scripts are attached belowany help would be greatly appreciatedthanks talhere is my main cmake scriptcmake minimum requiredversion 28projectmovienightif defined platform includetoolchainsioscmakeendifadd definitionswallsetdebugif defined debug add definitionsgendifif defined release add definitionso3endifadd subdirectoryengineadd subdirectoryuiadd subdirectorytesthere is my toolchainsioscmake filesetcmake system name darwinsetcmake system processor arm,"['c++', 'ios']" +353122,xml columns in a codefirst application i am trying to create an xml column in code first i am well aware entity framework does not fully support xml columns and that it reads them as a string that is fine i would still like the column type to be xml though heres my classclass content public int contentid get set columntypenamexml public string xmlstring get set notmapped public xelement xml get set problem is that code first migrations completely ignores the column attribute and creates the field as an nvarcharmax i tried using datatypexml but that too did not workis this a migration bug,['c#'] +353149,entityframework update or insert chinese or nonenglish text actually before i did not use framework or linq just type in sql statement with sqlcommand class i type in insert into table valuesnsampleactually i donot know what is n but it works for chinese and other language otherwise it will insert some question markbut when i use entityframeworkthis kind of framework always insert some question mark can i ask how to tackle the issuen means unicodecan you give me one example that entityframework use that sort of thing,"['c#', 'asp.net']" +353157,making div content responsive my content is not responsive at the moment i have tested it on iphone and the text goes over the screeni have changed the css of my container tocontainer2 width 960px maxwidth 90position relativeleft 50marginleft 480pxlineheight 14emwhen i test it after the change the content thisappears i read that putting maxwidth90 would allow it to not exceed the boundary width but obviously it did not work what am i doing wrong,"['html', 'css']" +353208,understanding stdaccumulate i want to know why stdaccumulate aka reduce 3rd parameter is needed for those who do not know what accumulate is it is used like sovectorint v123 int sum accumulatevbegin vend 0 sum 6call to accumulate is equivalent tosum 0 0 value of 3rd paramfor auto x v sum xthere is also optional 4th parameter which allow to replace addition with any other operation rationale that i have heard is that if you need let say not to add up but multiply elements of a vector we need other nonzero initial valuevectorint v123int product accumulatevbegin vend 1 multipliesintbut why not do like python set initial value for vbegin and use range starting from vbegin1 something like this int sum accumulatevbegin1 vend vbeginthis will work for any op why is 3rd parameter needed at all,['c++'] +353224,what is a adb daemon while running an application apk file is formed and that apk file is installed in the emulator for installing the apk file in the emulator we need android debug bridgeadb service daemon is a part of this service my question is what is the work of the daemon what does it do,['android'] +353229,what do the fields of rubys gcstat mean i am using gcstat to profile memory usage in our rails app gcstat returns a hash with the following keyscountheap usedheap lengthheap incrementheap live numheap free numheap final numdoes anybody know exactly what these values mean there is no documentation of them in the ruby source gcc just a comment the contents of the hash are implementation defined and may be changed in the futuresome of these fields make sense from context eg count is the number of heaps ruby has allocated but what is heap final num what is heap increment is heap length the minimum heap sizei am fiddling with ruby min heap slots ruby free min and ruby gc malloc limit but changing those env vars does not seem to have any effect on heap count or heap length i would expect that heap count would go down if i radically increase min heap slots so i really would like to know exactly what all the gcstat values representi am using ruby 193,['ruby'] +353257,what are the benefits of migrating our application over to wcf as opposed to continuing to use net remoting alright so i have asked several questions on stackoverflow about net remoting and there is always at least one person who just has to chime in net remoting is deprecated use wcf instead i understand that it is deprecated and there is no guarantee of future support with new versions of the net framework but what are some other good reasons we would want to move over to wcf i have seen a few mostly minor annoyances with net remoting however this is not enough to change the minds the powers that be who believe firmly in if it am not broke do not fix it at this time the only reason that attitude will change is if net remoting is removed from a future version of the net framework so who knows how long that will bedoes anybody have any insight as why exactly wcf is better than net remoting or why remoting is inferior to wcf what are the pros and cons of each technology are there additional things you can do with wcf and not with remotingi mean it would be great if i could convince them to let us migrate our software over to wcf just to allow a configurable tcpchannel timeout to be set on the client side this seems to have been broken for a while no matter what steps or troubleshooting i try and when this happens it makes our software look like absolute shitethanks in advance for helping to shed some light on this,['c#'] +353263,tagbuildermergeattributes does not work as expected i am trying to make a htmlhelper and i need to allow users to add their own custom attributes to the html tagi tried to do this using the tagbuilder class but it seems that instead of merging the attributes it just replaces themthis is what i did in cpublic static mvchtmlstring listhtmlhelper helper object htmlattributes var attributes htmlhelperanonymousobjecttohtmlattributeshtmlattributes var tag new tagbuilderdiv tagaddcssclassmyclass tagmergeattributesattributes false tag class property has value myclass not myclass testclass return new mvchtmlstringdivthis is my viewhtmllistnew class testclass what am i doing wrong,['c#'] +353270,what is bios in android in pc machines we have bios to identify hardware like audio cpu hdd etc but in android devices what does the replacement of bois as we just have kernel rom and clockworkmodso the bios is embedded in kernel or something else,['android'] +353333,create a progress bar on ajax call i want to thisplay a progress bar when i click on a button to load content through ajax as soon as i create the ajax call the communication goes to a php file on the server which scrapes data from another file on the server and it takes a good 78 seconds to bring in the data i want to thisplay a progress loader at the time of making the ajax request i was looking on the internet and couldnt find a simple solution all i could find were complex upload file scripts which would take an awful while to customize to perform this simple operation if anybody can help that would be great else i would have to make do with the spinner,"['php', 'javascript', 'jquery']" +353350,nhibernate race condition when loading entity i have a problem with a nhibernate race condition in my webappi am aware of this happening when using older versions of log4net should be fixed in 1210 although i have also experienced this because of this we have thisabled log4net for now since the race condition crashes iis and it is unacceptable for this to happen in production this happened when loading an entity see stacktrace below besides this a similar problem seems to have occurred in ravendb see this link and an example without nhibernate here linkstacktraceserver error in applicationprobable io race condition detected while copying memory the io package is not thread safe by default in multithreaded applications a stream must be accessed in a threadsafe way such as a threadsafe wrapper returned by textreaders or textwriters synchronized methods this also applies to classes like streamwriter and streamreaderdescription an unhandled exception occurred during the execution of the current web request please review the stack trace for more information about the error and where it originated in the codeexception details systemindexoutofrangeexception probable io race condition detected while copying memory the io package is not thread safe by default in multithreaded applications a stream must be accessed in a threadsafe way such as a threadsafe wrapper returned by textreaders or textwriters synchronized methods this also applies to classes like streamwriter and streamreadersource errorline 105line 106 ifwebuserid 0 logged inline 107 user sessiongetuserwebuseridline 108 if user null session exists but no user in db with this idline 109 new sessioninitremovesource file app codesessioninitcs line 107stack traceindexoutofrangeexception probable io race condition detected while copying memory the io package is not thread safe by default in multithreaded applications a stream must be accessed in a threadsafe way such as a threadsafe wrapper returned by textreaders or textwriters synchronized methods this also applies to classes like streamwriter and streamreader systembufferinternalblockcopyarray src int32 srcoffsetbytes array dst int32 dstoffsetbytes int32 bytecount 0 systemiostreamwriterwritechar buffer int32 index int32 count 117 systemiotextwriterwritelinestring value 204 systemiosynctextwriterwritelinestring value 63 nhibernateadonetabstractbatcherexecutereaderidbcommand cmd 71 nhibernateloaderloadergetresultsetidbcommand st boolean autothiscovertypes boolean callable rowselection selection isessionimplementor session 580 nhibernateloaderloaderdoqueryisessionimplementor session queryparameters queryparameters boolean returnproxies 275 nhibernateloaderloaderdoqueryandinitializenonlazycollectionsisessionimplementor session queryparameters queryparameters boolean returnproxies 205 nhibernateloaderloaderloadentityisessionimplementor session object id itype identifiertype object optionalobject string optionalentityname object optionalidentifier ientitypersister persister 590genericadoexception could not load an entity apresentationuser338sql select user0 userid as userid24 0 user0 instituteid as institut2 24 0 user0 email as email24 0 user0 password as password24 0 user0 username as username24 0 user0 mod remarks as mod6 24 0 user0 lastlogin as lastlogin24 0 user0 active as active24 0 user0 isacademic as isacademic24 0 user0 created as created24 0 select pfirstname from ej profile p where puserid user0 userid as formula11 0 select plastname from ej profile p where puserid user0 userid as formula12 0 select ptimezone from ej profile p where puserid user0 userid as formula13 0 from ej user user0 where user0 userid nhibernateloaderloaderloadentityisessionimplementor session object id itype identifiertype object optionalobject string optionalentityname object optionalidentifier ientitypersister persister 960 nhibernateloaderentityabstractentityloaderloadisessionimplementor session object id object optionalobject object optionalid 76 nhibernateloaderentityabstractentityloaderloadobject id object optionalobject isessionimplementor session 32 nhibernateeventdefaultdefaultloadeventlistenerloadfromdatasourceloadevent event ientitypersister persister entitykey keytoload loadtype options 173 nhibernateeventdefaultdefaultloadeventlistenerloadloadevent event ientitypersister persister entitykey keytoload loadtype options 181 nhibernateeventdefaultdefaultloadeventlisteneronloadloadevent event loadtype loadtype 1019 nhibernateimplsessionimplfireloadloadevent event loadtype loadtype 403 nhibernateimplsessionimplgetstring entityname object id 469 nhibernateimplsessionimplgettype entityclass object id 374 nhibernateimplsessionimplgetobject id 391 sessioninitgetcurrentuserisession session in jdevappapp wrootapp codesessioninitcs107 dynamicpageonpreiniteventargs e in jdevappapp wrootapp codedynamicpagecs24 memberpageonpreiniteventargs e in jdevappapp wrootapp codememberpagecs20 members stocks defaultonpreiniteventargs e in jdevappapp wrootmembersdefaultaspxcs28 systemwebuipageperformpreinit 49 systemwebuipageprocessrequestmainboolean includestagesbeforeasyncpoint boolean includestagesafterasyncpoint 1716the mapping for userpublic class userviewmapping classmapuser public userviewmapping tableej user ids sid useridgeneratedbynative maps sinstituteid instituteid maps semail email maps spassword password maps sname username maps smodremarks mod remarks maps slastlogin lastlogin maps sactive active maps sisacademic isacademic maps screated created maps sfirstnameformulaselect pfirstname from ej profile p where puserid userid maps slastnameformulaselect plastname from ej profile p where puserid userid maps stimezoneformulaselect ptimezone from ej profile p where puserid userid hasmanyprofileviewmodels sprofiles tableej profile keycolumnuserid cascadeall inversesome details i use two sessions for queries and commands and two session factories since i use a somewhat cqrslike pattern one session for reading objects one for making changes this helps me keep my domain model simple and view models and mapping possibly different from the command model the race condition occurred when loading the user viewmodel in my development environment single user but we make sure that this will never happen in production since it crashed iis 7 also in production there will be multiple users so maybe the error will possibly occur more oftenalso we have a lot of legacy code which uses systemdata and mysqldatamysqlclientmysqldataadapter to readwrite to the database could this be of influence i am using nhibernate 310 will upgrade to 331ga but this is difficult to reproduce and fluentnhibernate for my mappingsthe sessionfactories are created in the globalasaxvoid application startobject sender eventargs e querysessionfactorycreateconnectionstring commandsessionmanagerinitializeconnstringmy pages inherit from my dynamicpage where the query session is opened and closedpublic class dynamicpage systemwebuipage protected override void onpreiniteventargs e session querysessionfactoryinstanceopensession protected override void onunloadeventargs e baseonunloade sessionclose in the sessioninit reads userid from httpcontextsession and creates a webuser a user with some simple information like userid later i have put the lock around and done the user get request in a transaction not sure if it would be useful public iuser getcurrentuserisession session if user null var webuser new sessioninitget ifwebuserid 0 logged in lock lock usingvar tx sessionbegintransaction user sessiongetuserwebuserid txcommit if user null session exists but no user in db with this id new sessioninitremove user user currentuser webuser else ifwebuser is currentuser webuserid 0 ifhttpcontextcurrentsession null httpcontextcurrentresponsecookiesremoveaspsessid httpcontextcurrentrequestcookiesremoveaspsessid httpcontextcurrentsessionremoveall httpcontextcurrentsessionabandon ifhttpcontextcurrentrequesturlhostcontainsmembers httpcontextcurrentresponseredirectlogin else ifwebuserid 0 var userid webuserid var username webuserusername var loginurl webuserloginurl var clientip webuserclientip var isadmin webuserisadmin return new elabpresentationvisitoruserid username loginurl clientip isadmin webusertheme if user null return new elabpresentationvisitorwebuserid webuserusername webuserloginurl webuserclientip false webusertheme return usercommand sessions are opened and closed in a using block when neededaccording to the stacktrace the problem occurs in the streamwriter systembuffer which is again called by systemiosynctextwriter which is supposed to be threadsafe wrapper around systemiotextwriter since this happened in the textwriter is there a way to get around this to use a threadsafe textwriteris it safe to open and close the session the way i do it in dynamicpagesince this is obviously difficult to reproduce any ideas on how to do that are welcome tooupdatethe nhibernate profiler told that we also opened and closed a session in a using block in a master page since it was needed to check some permissions for the current user so two sessions were opened per request i have refactored it so it now instead of opening a session in a page superclass it opens the session in the globalasax on application beginrequest and closes it again on application endrequest where the session is put in httpcontextcurrentitemsbut no sure way of testing if this fixes it,['.net'] +353356,get the list of stored procedures created and or modified on a particular date i want to find which stored procedure i have created and also i want to find which stored procedure i have modified in my sql server on a particular date like 27 september 2012 27092012is there any query which will list these procedures that are created and also modified on this date,['sql'] +353359,php memory get usagetrue vs top mem i have a script written in php that uses the aws dynamo php api it runs a long loop where it pulls lots of data from dynamo and then it processes itwhen i watch the process using top i can see the memory usage used by the php processinside my scripts loop i print the result of memory get usagetrue when i run my test these two value are not even remotely similarshould they be if not why notin my test i have a server with 17gb of ram and i have set my phpinis memory limit to 64m i also call gc enable at the start of my script and between each loop call gc collect cycles in the hope of forcing a garbage collectionwhen i watch my php script using top i can see the mem going up and up until it eventually gets over 95 and linux kills the php process which i know from looking at dmesg when i look at the print outs from each iteration of the loop the memory usage reported by memory get usagetrue never gets above 50mblinux thinks the script is using almost 17gb php thinks it is only using 50mbwhat goings oneven if the script has memory leaks i do not understand why memory get usagetrue does not account for the memoryupdateafter spending some time commenting out various parts of the processing i am running inside my loop i found that if i remove the following codeclass cmyclass public static function static cmp fna b if aatt batt return 0 ret aatt batt 1 1 return ret function doprocessing sort fn arraycmyclass static cmp fn usortthism dicttosort sort fn unsetsort fn php never eats all of the system memory it seems to me that the usort is leaking memory i do not know why what i do not understand is why php reports the wrong information about how much memory it is usingany ideas,['php'] +353401,specifying limit offset for contentprovider queries i am trying to get my contentresolver to run this query select from mytable limit 1 offset 2the only query method in contentresolver isresolverqueryuri projection selection selectionargs sortorderi have tried final cursor c resolverquery mytablecontent uri mytableprojection new string 1 2 nullwhich just throws an illegalargumentexception what is the correct way of achieving this,['android'] +353411,thismissmodalviewcontrolleranimated is deprecated first deprecated in ios 6 i have just updated ios 6 and run my old code which is created in ios 43 they give me number of warnings in my applicationi used presentmodelviewcontroller and then i thismiss it but it gave me warningthismissmodalviewcontrolleranimated is deprecated first deprecated in ios 6why they show warning to that code here is the codepicker thismissmodalviewcontrolleranimatedyesthis line gets yellow and show the error please give me guideline to remove the warning,['iphone'] +353413,ios 6 force device orientation to landscape i gave an app with say 10 view controllers i use navigation controller to loadunload them all but one are in portrait mode suppose the 7th vc is in landscape i need it to be presented in landscape when it gets loaded please suggest a way to force the orientation go from portrait to landscape in ios 6 and it will be good to work in ios 5 as wellhere is how i was doing it before ios 6 voidviewwillappearboolanimated super viewwillappearanimated uiviewcontroller c uiviewcontroller allocinit autorelease self presentmodalviewcontrollerc animatedno self thismissmodalviewcontrolleranimatedno boolshouldautorotatetointerfaceorientationuiinterfaceorientationinterfaceorientation return interfaceorientation uiinterfaceorientationportraitpresenting and thismissing a modal vc was forcing the app to review its orientation so shouldautorotatetointerfaceorientation was getting calledwhat i have have tried in ios 6 boolshouldautorotate return yesnsuintegersupportedinterfaceorientations return uiinterfaceorientationmasklandscape uiinterfaceorientationpreferredinterfaceorientationforpresentation return uiinterfaceorientationlandscapelefton load the controller keeps staying in portrait after rotating the device the orientation changes just ok but i need to make the controller to rotate automatically to landscape on load thus the user will have to rotate the device to see the data correctlyanother problem after rotating the device back to portrait the orientation goes to portrait although i have specified in supportedinterfaceorientations only uiinterfaceorientationmasklandscape why it happensalso none of above 3 methods are getting calledsome useful datain my plist file i have specified 3 orientations all but upside downthe project was started in xcode 43 ios 5 all classes including xibs were created before xcode 45 ios 6 now i use the last versionin plist file the status bar is set to visiblein xib file the one i want to be in landscape the status bar is none the orientation is set to landscapeany help is appreciated thanks,"['iphone', 'objective-c']" +353422,arc app crashes when accessing property form arc static lib i have a arc automaticreferencecounting app that builds a static library also arc the app will launch fine but when the an action is performed that reads or writes to a property in the static library the app will crash with this errordyld lazy symbol binding failed symbol not found objc setproperty nonatomic a referenced from varmobileapplications0e7adbb4ffe54cebb4188a35a92e99d4myappappmyapp a expected in usrliblibobjcadylibdyld symbol not found objc setproperty nonatomic a referenced from varmobileapplications0e7adbb4ffe54cebb4188a35a92e99d4myappappmyapp a expected in usrliblibobjcadyliball the advice has been about linking nonarc libraries to arc apps or viceversa but these are both arc,['iphone'] +353424,android calendarview ondatechangelistener i have already implemented this listener in order for me to thisplay something when a certain date is clicked but the problem is that when i scroll the calendarview down it automatically thisplayed something but i did not click anything i just scrolled down to anther month in calendarview and then there goes a say a toast or a log whichever i guess it makes sense since the listener itself fires ondatechange and since scrolling down the calendar also changes the date currently selected so my question is that is there any listener for calendarview that i might use just a alternative to ondatechange listener inorder to avoid the situation that when i scroll down the calendarview to go to another month it automatically fired the lisntener anyone who knows an alternative listner to calendarview or anyone knows a workaround please do share,['android'] +353469,view vimeo private video with an oauth token can anyone give a help in vimeo api using scribe my goal is to access a private video which i uploaded without having to force the user to put password this process should be done in backgroundfrom what i understand deduce from research is necessaryrequest for application authorization using oauth protocol and via the following link tokenxthis operation is performed successfully and response data are sent to callback urlsomething like tokenauth token exampleoauth verifierverifiier exampleaccording to brad dougherty vimeo api staff ita s possible do something like thatif you go through the oauth process as yourself you can save that token and use that to make the callsi am using this codeservice new servicebuilderprovidervimeoapiclass apikeyapi key example apisecretapi secret example buildoauthrequest request new oauthrequestverbget id50305416requestaddquerystringparameterformat jsonrequestaddquerystringparametermethod vimeovideosgetinfostring oauth verifierverifier exampleverifier verifier new verifieroauth verifieri have tried differents combination to create this tokeni believe that my problem is hereone unsuccessfully try token requesttoken servicegetrequesttokentoken requesttoken new token auth token example api secret exampletoken token servicegetaccesstokenrequesttoken verifierservicesignrequesttoken request response response requestsendi have the following errorresponse body is incorrect cannot extract token and secret from this 401 unauthorized invalid signature the oauth signature passed was not validwhats escaping me this is the correct way to do it right,['java'] +353478,load method deprecated i was browsing through the jquery api and noticed that the load method is on the deprecated listcategories deprecated events document loadingi usually use this method to check if images are completly loaded why is it deprecated and what am i supposed to be using instead,['jquery'] +353481,improving css3 transition performance does anyone have cheats or tips for how to improve the smoothness of css3 animation i am sliding the entire page to the left using a css transition and it is a bit more juttery than i would like it is a single element but it contains numerous rounded corners gradients drop shadows etc as it is a complicated pagein flash actionscript there is a handy property cacheasbitmap which converts the animating element into a bitmap before the animation begins this is a godsend and significantly speeds up certain types of animation is there anything like this for css are there any other tips out there to improve performance without simplifying the page design i am thinking things like enabling hardware acceleration or flagging the animation as high priority for the browser,['html'] +353491,how do i use 3 and 4byte unicode characters with standard c strings in standard c we have char and wchar t for storing characters char can store values between 0x00 and 0xff and wchar t can store values between 0x0 and 0xf stdstring uses char so it can store 1byte characters only stdwstring uses wchar t so it can store characters up to 2byte width this is what i know about strings in c please correct me if i said anything wrong up to this pointi read the article for utf8 in wikipedia and i learned that some unicode characters consume up to 4byte space for example the chinese character ii12 has a unicode code point 0x24b62 which consumes 3byte space in the memoryis there an stl string container for dealing with these kind of characters i am looking for something like stdstring32 also we had main for ascii entry point wmain for entry point with 16bit character support what entry point do we use for 3 and 4byte unicode supported codecan you please add a tiny examplemy os windows 7 x64,['c++'] +353497,get absolute path with boostfilesystempath my current working directory is located at homemyuserprogram i created a boostfilesystempath object pointing to it i appended somedir so it becomes homemyuserprogramsomedir but i need to get its resolved absolute path which would be homemyusersomediri have been trying for long time and i do not find any method in their reference to do this there is a method called make absolute which seems to be supposed to do what i expect but i have to give it a aroota path argument which should it be do i really need to do this to get the real absolute path is there any other way,['c++'] +353500,internet explorer 10 is ignoring xmlhttprequest xhrwithcredentials true iam currently having an issue with a crossdomain ajax call using ie10 in ie10 mode not compatibilitysituationi have two domains httpa and httpb i have a cookie set for httpb i am currently on page httpai want to do a cors request to httpb using xmlhttprequest which should work according to and include the cookie in the requestthe js is as followsvar xhr new xmlhttprequestxhropenget httpb truexhrwithcredentials truexhrsendthis should ensure that the cookie is attached to the request however the fiddler trace shows that no cookie is attached and i get 401 access deniedthe server is configured to work with cors it includes the accesscontrol headersaccesscontrolalloworigin httpaaccesscontrolallowcredentials truethis should not make any difference since there is no options preflight request and the first request ie sends is a get and the cookie is not present thus causing a 401furthermore the js snippet works fine in both firefox and opera,['javascript'] +353513,am i getting these steps right for checking a users inapp billing subscription i am making an android app that sells an inapp monthly subscription before i dive into it too much does this outline of how this should be done seem about right i am using the google play android developer apithe first time the app is installed send the following in sendbillingrequestcheck billing supported if not do not bother making the buy uirestore transactions if there were transactions save the users purchase tokenwhen the user makes a purchasesave the purchase tokensend a get request with the purchase token to the google play developer api to verify the subscriptionif subscription is valid save the subscription expiration and initiation dates provide access to purchased dataif subscription is not valid remove the purchase token do not provide access to purchased data and draw not purchased version of the uieach time the app is started up check if you have a saved purchase tokenif the purchase token does not existdo not provide access to purchased data and draw not purchased version of the uiif the purchase token exists check the expiration date and initiation timeif expired or initiation was over one month agosend a get request with the purchase token to the google play developer api to verify the subscriptionif purchase is valid update the saved expiration and initiation dates provide access to purchased dataif purchase is not valid remove saved purchase token and expiration and initiation data do not provide access and draw not purchased version of the uielseprovide access to purchased data,['android'] +353530,getting an svg to keep it is aspect ratio in an html page i have html like that below i create a svg with a viewbox of 100x100 when rendered in chrome the svg is rendering itself as 200px wide good but 500px high and the text is pushed off the bottom of the page making my window bigger or smaller has no affect the svg simply grows or shrinks in height accordinglywhy is the svg not constrained in height in any way is there a way to make it automatically keep it is 11 aspect ratio the content inside of the svg is fine it scales appropriately this is causing some major headacheshtml head titlesvg ahoytitle meta nameviewport contentwidthdevicewidth initialscale10 head body div stylewidth 200px svg xmlns viewbox0 0 100 100 preserveaspectratioxminymin meet version11svg divcontent belowdiv div bodyhtml,['html'] +353574,is there any way to provide a default value for an isolated scope alias say i have the following as part of my directive definitionscope prop1 is there any way for prop1 to get a default value if the directive does not have a prop1 attribute sure i can check if it is defined myself and set it but the property is not always set when you would expect i am just wondering if there is any syntax i missed in the documentation or if there is a good standard way of doing this thanks,['javascript'] +353583,stepping into a function in ipython is there a way to step into the first line of a function in ipython i imagine something that would look likestep foo1 2which runs ipdb and sets a breakpoint at the first line of fooif i want to do this now i have to go to the functions source code and add an import ipdb ipdbset trace line,['python'] +353604,reading and writing rsa keys to a pem file in c i am writing a c program to generate keys for rsa and write them to a file and then read from them the homework requires me to generate the files in a openssl format so i chose pem now i have the following function for creating the filersa rsa new these 3 keys are generated beforehandrsae ersan nrsad dfp fopenpubkey file wifpem write rsapublickeyfp rsa printfnsn error writing public keyfflushfpfclosefpfp fopenprivkey file w prsakey evp pkey new evp pkey assign rsaprsakey rsaifpem write rsaprivatekeyfp rsa null 0 0 null null if pem write privatekeyfp prsakey null null 0 0 null printfnsn error writing private keyfflushfpfclosefpand this is the function to read the filesrsa rsa newfp fopenpubkey file rifpem read rsapublickeyfp rsa null null null printfnsn error reading public key returnfclosefpbn bn2binrsan unsigned char modulusbn bn2binrsae unsigned char expprintfnsnsn exp modulusrsa freersa prsakey evp pkey newfp fopenprivkey file riffp ifpem read privatekeyfp prsakey null null null ifpem read rsaprivatekeyfp rsa null null null printfnsn error reading private key return rsa rsa new rsa evp pkey get1 rsaprsakeyfclosefpthe public key is written and read as required but the provate key fails i have tried writing using both the rsa and the evpwhich is commented in the above code but both fail i cannot get my head around why this is happening or try and find where to look to debug this issue can anyone please provide some pointers for this,['c'] +353632,could anyone please guide me in my homework so i need to write a program that asks for 2 numbers and loops until all three assertions are true program has no outputassertx0 y0whileassertsum ix1assertsum yx1this is what i have so far im not really sure how to go about making the while statement please help thanks int main int x int y int i1 int sum0 cout please enter 2 numbers cin x y assertx0 y0 whileyi assertsum ix1 cout please enter 2 numbers cin x y i assertsum yx1 return 0here are the full instructionsgiven below is the outline of a loop a loop invariant and the condition which must be true when the loop terminates write a complete program that reads in two numbers x and y validating them prompting the user until valid numbers are entered and runs such that the three given assertions will always be true and the program will terminate provided the user enters appropriate values for x and y include the loop invariant assertion at the four points in your program where it must be true part 1 of your program may not use the multiplication operator except in assert statementsassertx0 y0while assertsum ix1 assertsum yx1extend your program by including the following code after the code for part 1 and include the loop invariant and post condition assertion after the loop as comments not assert statements that most specically describe what the loop does and what is known about the relationship among the three variables when the loop terminates you should analyze what is going on with these variables and what is known about them before you enter the loop after each iteration of the loop when the loop will terminate and after the loop terminates you may assume the user enters a positive value for ccin cassertc0a 1b 0whilec a 0 a a 5 b b 1,['c++'] +353637,vertica data validation of duplicateprimary key i am trying to create a validation procedure during a load that checks to make sure data is not duplicated vertica does not support this natively vertica checks for constraint violations when queries are run not when data is loaded to detect constraint violations as part of the load process use a copy page 667 statement with the no commit option by loading data without committing it you can run a postload check of your data using the analyze constraints function if the function finds constraint violations you can roll back the load because you have not committed itthe problem is that i cannot figure out how to do this programmatically i suspect that i need a stored procedure but i am not familiar with the stored procedure syntaxlimitations for vertica can you help heres what i have create a new table id is autoincremented and name must be uniquecreate table if not exists my table id identity name varchar50 unique not null type varchar20 description varchar200insert a recordbegin copy my table from stdinabort on errorno commit this begins the loadname1type1description1 this is the load this closes the loadcommit insert the duplicate recordbegin copy my table from stdinabort on errorno commit this begins the loadname1type1description1 this is the load this closes the loadcommit surprisingly the load executes successfully whats going on check constraints we see that there is a failed constraintsselect analyze constraintsmy tablemy thinking is to do some conditional logic psudocode is below can you help me prepare it for verticabeginload dataif select count from select analyze constraintsmy table sub 0commitelse rollback,['sql'] +353665,java forloop best practice what is the best way to loop through an array when you need the indexoption 1int len arraylengthfor int i 0 i len i arrayi fooioption 2for int i 0 i arraylength i arrayi fooior does it not matter or is there a better way to do itjust to point out the differences in one case the length of the array is evaluated as part of the test in the loop although the compiler should normally optimize that secondly is i any different here from i i definitely prefer i if it is c but am not sure for java,['java'] +353666,convert javaneturi to androidneturi i am able to find how to convert androidneturi to javaneturi here but not viceversa so after spending some time i figured it out here is the solutionif there is another solution then please post that as wellfirst convert javauri to string and then use androidneturis parse functionandroidneturi androiduri androidneturiparsejavauritostring,['android'] +353674,building an html diffpatch algorithm a description of what i am going to accomplish input 2 n is not essential html documents standardize the html formatdiff the two documents external styles are not important but anything inline to the document will be included determine delta at the html block element level expanding the last point imagine two pages of the same site that both share a sidebar with what was probably a common ancestor that has been copypasted each page has some minor changes to the sidebar the diff will reveal these changes then i can walk up the dom to find the first common block element shared by them or just default to body in this case i would like to walk it up and find that oh they share a common div idsidebar i am familiar with daisydiff and the application is similar in the cms world i have also begun playing with the google diffpatch library i wanted to give ask this kind of nonspecific question to hopefully solicit any advise or guidance that anybody thinks could be helpful currently if you put a gun to my head and said code it i would rewrite daisydiff in python and addin this blocklevel logic but i thought maybe there is a better way and the answers to anyone have a diff algorithm for rendered html made me feel warm and fuzzy,"['python', 'html']" +353686,how to scroll down jquery i am not a programmer but i use the code below to scroll the page to the tophow can i adapt it to make a scroll downscript srcscripta classbtnmedio hrefjavascript img srcfilenamedeixeseuemailpngreslandingascript btnmedioclickfunction html bodyanimatescrolltop1050 script,"['javascript', 'jquery']" +353691,rename a table in mysql renaming a table is not working in mysqlrename table group to memberthe error message is1064 you have an error in your sql syntax check the manual that corresponds to your mysql server version for the right syntax to use near group rename to member at line 1the query is working fine on other tables for me but not with the table group,['mysql'] +353692,is using the smiley ao in fontface still relevant this might be a bit of hasty conclusion but my question arose when i find that fontsquirrelcom does not generate the smiley ao with their fontface generatorinstead of the usual bulletproof standard as laid out by paul irish regarding the smiley the fontsquirrels fontface generator generates only thisfontface fontfamily sansationregularsrc urlsansation regularwebfonteotsrc urlsansation regularwebfonteotiefix formatembeddedopentype urlsansation regularwebfontwoff formatwoff urlsansation regularwebfontf formattruetype urlsansation regularwebfontsvgsansationregular formatsvgfontweight normalfontstyle normali realize it might be too hasty to conclude that by fontsquirrel abandoning the smiley means the smiley is no longer relevant but considering fontsquirrels fontface generator seem to be the most popular and the most used generator out there it makes me wonder why they do not include the smiley anymore especially because they seem to have included it beforejust in case anyones not familiar with the smiley there is a good explanation here,['css'] +353762,combine show and edit actions in ruby on rails i was just wondering if anybody has ever built a rails application without any show actionsin my application if a user picks say a project from the list he will probably want to not just show it but also edit itso is it good practice to not implement any show actions and instead link all records to edit formsthe only caveat i see is that a user might accidentally edit a project but this could be prevented by setting a default attribute thisabled on all form fields using jquery that way a user will have to click a button edit in order to unlock the form fields for editingdoes that make sense or am i completely nutswho knows maybe this causes conflicts with rails restful architecture,"['ruby-on-rails', 'ruby']" +353778,how can i make a numpy function that accepts a numpy array an iterable or a scalar suppose i have thisdef incrementelementsx return x1but i want to modify it so that it can take either a numpy array an iterable or a scalar and promote the argument to a numpy array and add 1 to each elementhow could i do that i suppose i could test argument class but that seems like a bad idea if i do thisdef incrementelementsx return numpyarrayx1it works properly on arrays or iterables but not scalars the problem here is that numpyarrayx for scalar x produces some weird object that is contained by a numpy array but is not a real array if i add a scalar to it the result is demoted to a scalar,['python'] +353834,is it possible to check if a notification is visible or canceled i would like to update notification data but the only way i found is to launch a new one with the same idthe problem is that i do not want to raise a new one if the original has beed canceledis there a way to tell if a notification is visible or canceled or a way to update a notification only if it exists,['android'] +353844,images downloaded asynchronously only appear in uitableview after tap or scroll i am successfully loading thumbnail images from blog posts asynchronously into my uitableviewthe issue i am having is that the images only appear if i tap the cell or if i scroll downwhen i tap the cell the image appears on the left pushing the title and subtitle to the rightwhen i scroll down the images appear where they should in the cells as they are revealedheres my code i am using afnetworkingimport uiimageviewafnetworkingh nsintegertableviewuitableview tableview numberofrowsinsectionnsintegersection return postscount uitableviewcell tableviewuitableview tableview cellforrowatindexpathnsindexpath indexpath static nsstring cellidentifier cell uitableviewcell cell tableview dequeuereusablecellwithidentifiercellidentifier if cell nil cell uitableviewcell alloc initwithstyleuitableviewcellstylesubtitle reuseidentifiercellidentifier nsdictionary post posts objectatindexindexpathrow nsstring postpictureurl post objectforkeypicture cellimageview setimagewithurlnsurl urlwithstringpostpictureurl celltextlabeltext post objectforkeypost text celldetailtextlabeltext post objectforkeypost author name return celli am seeing this in the iphone 60 simulator xcode 45 osx mtlionany ideas why the images are not drawn on the initial screen,"['objective-c', 'ios']" +353875,how can i make my web app iphone 5 compatible i have a website optimized as a web app with ios safari so that adding to home screen opens the app in a separate webview however it always opens in the 35 letter boxed mode instead of stretching to fill the screen i know that with native apps you just have to add the iphone 5 sized launch image how can i do this for a web app,"['ios', 'iphone']" +353886,returning array from d3json as a jqueryd3noob it seems i cannot figure out how to make this work supdog d3jsondatapath functionjsondata return jsondata consolelogsupdogthanks in advance,['javascript'] +353930,ios 6 corebluetooth pairing forgetting 2 questions we have a bondable when we connect we are asked to pair see question 2 bluetooth 40 peripheral that we have manufactured and have written an ios app forquestion 1is it possible in ios 6 with corebluetooth to remove our peripheral from the ios bluetooth settings from within our app or is this restricted to only going to ios settings bluetooth our peripheral and forget this devicewhat we are trying to do is when we remove our peripheral from within our app we expect this peripheral to be removed from the ios bluetooth list as wellquestion 2my second question is does ios sdk provide a way to determine if a user has chosen pair or cancel on the pairing request alert as of now we determine the user pressed pair by reading our services characteristics when the device is connected,['objective-c'] +354026,how to limit number of deployed snapshots artifacts in nexus we are using nexus to deploy our snapshot artifacts our build server deploys them during each build using the following command mvn deployas result on each build the newer version of the artifact is deployed the problem that already about dozens of artifacts are deployed to the repository and of course we need only the last artifactis any way to limit number of deployed snapshots artifacts in nexusthanks for your help michael,['java'] +354028,associativity of in in python i am making a python parser and this is really confusing me 1 in in afalse 1 in in atypeerror in string requires string as left operand not bool 1 in in atypeerror in string requires string as left operand not listhow exactly does in work in python with regards to associativity etc why do no two of these expressions behave the same way,['python'] +354063,how to make app fully working correctly for autorotation in ios 6 in ios6 shouldautorotatetointerfaceorientation is deprecated i tried to use supportedinterfaceorientations and shouldautorotate to make app working correctly for autorotation but failedthis viewcontroller i donat want to rotate but it does not work boolshouldautorotatetointerfaceorientationuiinterfaceorientationinterfaceorientation return interfaceorientation uiinterfaceorientationportraitboolshouldautorotate return nonsuintegersupportedinterfaceorientations return uiinterfaceorientationmaskportraitany ideas thanks for any help in advance,['ios'] +354069,preload cells of uitableview i acknowledge that uitableview load dynamically a cell when user scrolls i wonder if there is a way to preload all cells in order not to load each one while scrolling i need to preload 10 cells is this possible,['objective-c'] +354072,is it possible to extract preprocessor information from clangs parse tree consider the following simple header demohdefine persiststruct serialised int sometransientvalue persist int anumbertopersist i use the following code and clangs python api to iterate over the headerimport sys clangcindexdef callexpr visitornode parent userdata if nodelocationfile print nodelocationfile nodethisplayname nodekind return 2tu clangcindexindexcreateparsesysargv1 argsx cclangcindexcursor visittucursor clangcindexcursor visit callbackcallexpr visitor nonethis prints out the elements of clangs ast producing the following outputdemoh serialised cursorkindstruct decl demoh sometransientvalue cursorkindfield decl demoh anumbertopersist cursorkindfield decldoes anyone know how i can extract the preprocessor declaration associated with the member variable called anumbertopersist is there a better way to tag variables in a manner that manifests clearly in the parse treexubuntu 1204 clang version 31 tagsrelease 31final target x86 64unknownlinuxgnuthread model posix,['c++'] +354079,rearranging tab bar controller order in storyboard in my app iphone app i have a tab bar controller with 4 relationships to 4 different table view controllers is there a way to rearrange the order of the relationship in the storyboard graphically i cannot find a way to do this and i am sure i must be missing something,['ios'] +354145,linear regression reduce degrees of freedom i have a pandas dataframe with columns likeorder balance profit cum i am doing a linear regressionmodel profit tr pdolsydf closedprofit cum xdf closedorderthe problem with this is that standard model is like equation of a line that does not pass through the originy a x bthere is 2 degrees of freedom a and bslope aamodel profit trbetaxand intercept bbmodel profit trbetaintercepti would like to reduce degree of freedom for my model from 2 to 1 and i d like to have a model likey a x,['python'] +354180,numpyshape gives inconsistent responses why i am a newbie to python what i would like to know is why does the programimport numpy as npc nparray12printcshaped nparray12transposeprintdshapegive212as its output should not it be1212instead i got this in both python 273 and python 323thanks,['python'] +354239,cannot create a file when that file already exists when using directorymove i am trying to move the directory from one location to another location on the same drive i am getting cannot create a file when that file already exists error below is my codecould any one suggest on this string sourcedirectory fsource string destinationdirectory fdestination try if directoryexistssourcedirectory if directoryexistsdestinationdirectory directorymovesourcedirectory destinationdirectory else directorycreatedirectorydestinationdirectory directorymovesourcedirectory destinationdirectory catch exception ex logexmessage,['c#'] +354327,submitting a background task from spring mvc app i have got working spring mvc app and what i am trying to do next is to start or submit a background task from my appbasically i would like to keep the task going until it completes even if the user decides to do something else on the appbut also i would like to stopkillpause the task if i needed to since i have not done this before i am looking for a goodbetter way to do thisi found these to be usefulhow do you kill a thread in javajava threads is it possible viewpausekill a particular thread from a different java program running on the same jvmso i wanted to use async task to submit my background task but wanted to use threads id to obtain it later on and stop it if neededis this the right approach i do not have any experience with multithreading so i am here to listencode update public interface worker public void work public void cancelimplementation componentasyncworkerpublic class asyncworker implements worker async public void work string threadname threadcurrentthreadgetname systemoutprintln threadname beginning work try threadsleep10 simulates work catch interruptedexception e systemoutprintlni stopped systemoutprintln threadname completed work public void cancel threadcurrentthreadinterrupt controller for testing purposes responsebodyrequestmappingjobstartpublic string start asyncworkerwork return startresponsebodyrequestmappingjobstoppublic string stop asyncworkercancel return stopwhen i visit jobstart i cannot execute more that one task simultaneously the other one starts to execute only after first one has completedalso when i visit jobstop the process is not stopped what am i missing here,['java'] +354350,ios 6 facebook posting procedure ends up with remote app id does not match stored id this is my third question about posting on facebookalthough this may be a duplicate of mac os x facebook login failed no stored remote app id for app but i decided to post separate question because we have ios here but not mac osa few days ago i posted a question ios 6 facebook posting procedure ends up with remote app id does not match stored id error the problem is still the same i cannot perform a post but now i have got an errorerror is error domaincomappleaccounts code7 the facebook server could not fulfill this access request remote app id does not match stored id userinfo0xa260270 nslocalizeddescriptionthe facebook server could not fulfill this access request remote app id does not match stored idthe code you may find in my previous questiondoes anyone know whats going onwhat is remote and stored app ids,"['ios', 'iphone', 'objective-c']" +354370,how to maintain a jquery reference using replacewith if we have an example structure like thishtmldiv idfoohello foodivjsvar foo fooand we need to replace the entire html markup for that given jquerynode reference using jquerys replacewith method what is the best practice to maintain respectively get a new node reference the problem replacewith returns the reference to the old jquery object which sounds more or less unreasonable to me from the docshowever it must be noted that the original jquery object is returned this object refers to the element that has been removed from the dom not the new element that has replaced itif i go likefoo fooreplacewithdivnew contentdivi would like to have that new node referencedcached in that same variable yes you could requery that newly inserted dom node but that seems very clunky in my mindis there any tricky way to achieve that without the need to requery the dom example,"['javascript', 'jquery', 'html']" +354377,504 gateway timeout media temple i am constantly getting 504 gateway errors when my php script needs to run for longer than 60 secsi am on media temple on a dedicated server i have contacted media temple and they have been helpful but none of their suggesion seem to work for me i was told to edit this fileetchttpdconfdfcgidconfwhich i have to belowloadmodule fcgid module modulesmod fcgidsoifmodule mod fcgidcifmodule mod fastcgic addhandler fcgidscript fcg fcgi fplifmodule fcgidipcdir varrunmod fcgidsock fcgidprocesstablefile varrunmod fcgidfcgid shm fcgididletimeout 300 fcgidmaxrequestlen 1073741824 fcgidprocesslifetime 10 fcgidmaxprocesses 64 fcgidmaxprocessesperclass 15 fcgidminprocessesperclass 0 fcgidconnecttimeout 600 fcgidiotimeout 600 fcgidinitialenv rails env production fcgididlescaninterval 600ifmoduleso i have tried to max everything as much as i can to test this i am just running the function belowfunction test504 set time limit0 sleep60 echo true sleep will work on any value below 60 seconds returning true but on 60 i get 504 gateway errormy phpinfo outputsmax execution time 600max input time 180i have seen a few post on increasing this fastcgi connect timeout but have no idea where to find this on media templecan anyone help thanksupdate still cant fix thisafter chatting with support i have been told i need to edit nginxconf and was directed to this post cant fine any of the values on my hostingclient header timeoutclient body timeoutsend timeoutfastcgi read timeoutmy nginxconf file looks like thiserror log varlognginxerrorlog infopid varrunnginxpidevents worker connections 1024http include mimetypes default type applicationoctetstream log format main remote addr remote user time local request status body bytes sent http referer http user agent http x forwarded for access log varlognginxaccesslog main sendfile on tcp nopush on keepalive timeout 0 keepalive timeout 120 tcp nodelay on gzip on gzip thisable msie 16sv1 server tokens off include etcnginxconfdconfthis is driving me crazy any suggestions update i managed to get this sorted in the end after lots of headache added a blog post on how i fixed this herehope this helps someone,['php'] +354381,capture mac media control keys in a chrome extension two part questionis there a way to capture react to the pressing of the media playback control keys on a mac keyboard previous playpause next in a google chrome extension using strictly javascriptif answertoquestion1 no is there a way to do it using some sort of native plugin cci know that this should be possible as unity music media keys does it albeit i know that they are using a native pluginwhat i have looked at so far is this plugin which claims to do it but actually requires functionflip to make the keys act as function keys and reacts to the pressing of f7 f8 and f8,['javascript'] +354413,how can i check whether a struct has been instantiated i have a struct that for the purposes of this question pretty much mimics the built in point typei need to check that it has been instantiated before using it when it was point i could do thisif thisp nullbut that now generates the following erroroperator cannot be applied to operands of type proportionpoint and nullhow can i compare my struct against null is there another way to check for instantiation,['c#'] +354487,hashset as datasource i am trying to optimize the code for sharepoint webpart i have a repeater controlasprepeater idcountryoptionsrepeater runatserver itemtemplate option valueevalcountryname evalcountryname option itemtemplateasprepeateri am filling it with datatablecountrieslist countrieslistthistinctstringtoliststringcountrieslistsortvar nodupscountrieslist new hashsetstringcountrieslistdatatable dt new datatabledtcolumnsaddcountrynameforeach string countryname in countrieslist datarow dr dtnewrow drcountryname countryname dtrowsadrcountryoptionsrepeaterdatasource dtcountryoptionsrepeaterdatabindthisdatabindis there a way to directly bind hashset object nodupscountrieslist to datasource with same configuration of repeater in order to bring about optimizationsomething likecountrieslist countrieslistthistinctstringtoliststringcountrieslistsortvar nodupscountrieslist new hashsetstringcountrieslistcountryoptionsrepeaterdatamember countryname countryoptionsrepeaterdatasource nodupscountrieslistcountryoptionsrepeaterdatabindthisdatabind,"['c#', 'asp.net', '.net']" +354495,how to copy matrix in c i am trying to write the function matricopy that should copy a matrix but the compiler complains minmatrixc test rows and columns of a matrix copyright abandoned this file is in the public domain include stdiohdefine rowcount 3define columncount 4int imat rowcount columncount char cmat rowcount columncount double dmat rowcount columncount int rmat rowcount columncount void matriscopy int destmat int srcmat int rowcount int columncount int i j for i0 irowcount ii1 radnr for j0 jcolumncount jj1 kolumnnr destmatij srcmatijint main int i int j int ip char cp double dp for i 0 i rowcount i i 1 for j 0 j columncount j j 1 imat i j 10 100i j cmat i j 10i j dmat i j 10 i10 j10 rmat i j 0 printf n examining imatn for ip imat 0 0 ip imat rowcount 1 columncount 1 ip ip 1 printf memory at lx contains value dn unsigned long ip ip printf n examining cmatn for cp cmat 0 0 cp cmat rowcount 1 columncount 1 cp cp 1 printf memory at lx contains value dn unsigned long cp cp printf n examining dmatn for dp dmat 0 0 dp dmat rowcount 1 columncount 1 dp dp 1 printf memory at lx contains value fn unsigned long dp dp add a statement here to call your matriscopy function printf n examining rmatn for ip rmat 0 0 ip rmat rowcount 1 columncount 1 ip ip 1 printf memory at lx contains value dn unsigned long ip ip return 0 i get this error cc minmatrixcminmatrixc in function amatriscopyaminmatrixc1817 error subscripted value is neither array nor pointer nor vectorminmatrixc1832 error subscripted value is neither array nor pointer nor vectorcan you help me understand,['c'] +354507,how to call a template member function possible duplicatec template member function of template class called from template function templateclass t1class a templateclass t0 void foo templateclass t0class t1void bar const at1 b bfoot0 this throws expected primaryexpression before aa tokeni can change it to bat1template foot0which compiles fine however i can also change it tobat1template foot0which compiles fine too ehhow does one correctly call the template member function in the sense of the original code,['c++'] +354526,iboutlet link to embedded view controller i have a complex ipad view that i manage by having several view controllers i previously before ios6xcode 45 did this by allocating my view controllers in code and hooked up the various views to them though links to the master view what i would like to do is use the new container views to embed the view controllers in the storyboard file i do not seem to be able to make an iboutlet link to the embedded view controller to the master controller is it possible to do this or to retrieve the embedded controller via a tag or something in the codethis question is specifically about using container views,['ios'] +354542,write bytes into a file without erasing existing bytes possible duplicatebest way to write bytes in the middle of a file in java i have a file in which i need to write bytes i know at which position in the file i need to insert specific bytes to make things clear i need to write bytes in the middle of the file without erasing any existing bytes the whole operation should then increase the length of the filewhat is the best way to do so,['java'] +354558,in custom c powershell cmdlet identify if verbose was specified i have a custom c powershell cmdlet inheriting from the cmdlet base class and i want to be able to identify if the verbose parameter was specified when running the cmdlet i realize that writeverbose will output when the verbose parameter is specified but i would like to actually do some other code when verbose is specified ie not output the consolewrite values when verbose is specifiedthanksjohn,['c#'] +354594,expression is always true in c a simple c code bool result if booltryparsefalse out result result consolewritelineresult and bool result if booltryparsetrue out result result consolewritelineresult resharper says that result in consolewritelineresult is always true why,"['c#', '.net']" +354599,ignoring mysql fulltext stopwords in query i am building a search for a site which utilizes a fulltext search the search itself works great that is not my problem i string together user provided keywords match against with ands so that multiple words further narrow the results now i know that certain stop words are not indexed and that is fine with me i do not really want to use them as selection criteria but if a stopword is provided in the keyword set by the user it kills all the results as expected even if the word actually is in a certain text block my question is there any way to check to see if a certain word is a stop word at the time of the query my preferred solution would just be to exclude the relevant word from the search criteria i do not care if a user can narrow results by the word neither i just do not want mysql to return an empty result set because the user provided it even though neither does exist in the results or am i just going to have to empty the stopword list thanks very much for any helpedit i am sorry but there is really no code snippets to provide for this one the code works fine actually exactly as expected it is more of a logical problem i am dealing with but as an example in the way of explanationlets say there are three records which include the words but are not limited to1 apple orange mango banana2 grape orange pineapple mango3 potato mango melon keira knightlyif the search word entered by the user is mango all results are returned correctly if the words are orange and mango results 1 and 2 are returned correctly now let us say banana is a stop word it is not but let us assume it is if the search is for orange mango and banana no results are returned because banana is not in the fulltext index what i am looking for is if anyone else has encountered this problem and has a way to work around it sort of anif banana not stop word match banana against words obviously not real codeor am i just going to have to drop the stopword list,['mysql'] +354603,difference between formsauthentication and websecurity i am exploring the possibilities of aspnet mvc in the example webapplication of visual studio the webmatrixwebdatawebsecurity is used for membership creating accounts and specify that a user is logged in to view a specific page etc but after some searching i found that there is also a systemwebsecurityformsauthentication class that can be used for membershipdoes anybody know the differencespros and cons between these two classes and when to use websecurity and when to use formsauthentication and maybe a clear example of formsauthenticationthanks in advance,['c#'] +354652,validate a list of nested objects with spring validator i want to know how to validate a list of nested objects in my form with spring validator not annotation in spring mvc application class myform string myname listtypea listobjectsclass typea string number string valuehow can i create a myformvalidator to validate the listobjects and add error message for number and value of typea,['java'] +354709,how to detect if the scroll viewer reaches bottom in winrt i am wondering whats the best approach to detect if a scrollviewer reaches the bottom right etci think i can achieve that by using both pointerwheelchanged for mouse and manipulationdelta for touch in these event handlers i can record the horizontaloffset to find out when will the scroller reach the end but i think there could be a better way to do iti have found this article but the compression visual states seem not working in winrt the currentstatechanging event method is not getting called i also checked another article but it just works for scroll bar not a generic approachanyone knows whats the best way to solve this problem,['c#'] +354710,how can a controller manually set validation errors for a certain field i have a form with 3 activerecord fields one of those fields has kind of goofy and statedependent validation requirements for example i only validate the field if the object is being created on a setup wizard formin my post handler to create the object i thought i could call errorsadd to insert a special error condition foo foonewparamsfooif goofy conditionsparamsfoogoofy field fooerrorsaddgoofy field does not meet the goofy conditions endrespond to do format if foosave else redirect back to form with error fields hilitedhowever doing fooerrorsadd in the controller does not seem to do anything it doesnt prevent the save if the other fields pass validationsan alternative is to put a custom validation handler into the model i know using errorsaddfield msg works fine there but in that case how can my controller pass info to the validator telling it whether or not the field needs to be validated,['ruby-on-rails'] +354725,ios 6 safari setinterval does not get fired it seems if i am scrolling the window the windowsetinterval does not get attached fired while the scrolling is happening or after has anyone else seen the same issuei meanwhat could be causeing thiswhat can i do to fix this,"['javascript', 'ios']" +354726,origin httplocalhost is not allowed by accesscontrolalloworigin i have a problem i try to get json api in token90d2fad44172390b11527557e6250e50secretkey83e2f0484edbd2ad6fc98c1e30ea44outputjsonwhen i try to offline modethis means i copy that json api in notepad and call it in my localhost with this codefunction getlast ajax urlhttplocalhostticketsjsonapi airportjson typeget datatypejson successfunctiondataconsolelogdataresultsresult1category it runs perfectlybut when i try to real url token90d2fad44172390b11527557e6250e50secretkey83e2f0484edbd2ad6fc98c1e30ea44outputjson with this codeajax urltoken90d2fad44172390b11527557e6250e50secretkey83e2f0484edbd2ad6fc98c1e30ea44outputjson typeget crossdomaintrue beforesend functionx ifx xoverridemimetype xoverridemimetypeapplicationjsoncharsetutf8 successfunctiondataconsolelogsuccess then in my google chrome javascript consolethere is an error like this xmlhttprequest cannot load token90d2fad44172390b11527557e6250e50secretkey83e2f0484edbd2ad6fc98c1e30ea44outputjson origin httplocalhost is not allowed by accesscontrolalloworigini know it must be cross domain problem can someone help menbsome pieces of code i got from stack overflow communitythank you,['jquery'] +354771,how can i ensure that an overridden method is synchronized i have a class of common code that is thread safeone of the methods in that class is abstract and needs to be overridden for different implementationsi need to ensure or at least flag to other developers that all implementations of this method need to be threadsafewhat is the best way to do thisis there a keyword or annotation to this effecti have already tried abstract synchronized but that combination of keywords is not allowed,['java'] +354866,the definitive php url parser before you tell me to use parse url it is not nearly good enough and has too many bugs there are many questions on the subject of parsing urls be found on here but nearly all are to parse only some specific class of urls or are otherwise incompletei am looking for a definitive rfccompliant url parser in php that will reliably process any url that a browser is likely to encounter in this i includepageinternal links titlepagerelative urls blahthingphpsiterelative urls blahthingphpanonymousprotocol urls ajaxgoogleapiscomajaxlibsjquery181jqueryminjscallto urls callto442079460123file urls fileusersmethisfiletxtmailto urls mailtosubjecthello mailtosubjecthelloand support for all the usual schemeauthenticationdomainpathqueryfragment etc and break all of those elements out into an array with extra flags for relativeschemaless urls ideally it would come with a url reconstructor like http build url supporting the same elements and i would also like validation to be applied ie it should be able to make a bestguess interpretation of a url if it is invalid but flag it as such just like browsers dothis answer contained a tantalising fermatstyle reference to such a beast but it does not actually go anywherei have looked in all the major frameworks but they only seem to provide thin wrappers around parse url which is generally a bad place to start since it makes so many mistakesso does such a thing exist,['php'] +354896,save uiimage to photo album with writeimagetosavedphotosalbum i am trying to save a uiimage to photo album i have tried severl methods the last one isibactioncapturelocalimageidsenderphotocapturebutton setenabledno save to assets libraryalassetslibrary library alassetslibrary alloc initlibrary writeimagetosavedphotosalbum imageviewimagecgimage metadatanil completionblocknsurl asseturl nserror error2 report memoryafter writing to library if error2 nslogerror the image failed to be written else nslogphoto saved asseturl asseturl runonmainqueuewithoutdeadlocking report memoryoperation completed photocapturebutton setenabledyes imageview is a uiimageview which contain the image i want to saveon log i got photo saved asseturl null and the photo does not save to librarywhat am i doing wrong,"['iphone', 'objective-c', 'ios']" +354934,how to send mail in joomla i am using the following code to send mailfunction sendmailfilemailto mailer jfactorygetmailer var dumpmailer exit config jfactorygetconfig sender array configgetvalue configmailfrom configgetvalue configfromname mailersetsendersender recipient arraymailto maileraddrecipientrecipient body your body stringnin double quotes if you want to parse the nnewlines etc mailersetsubjectyour subject string mailersetbodybody optional file attached maileraddattachmentjpath basedscsvdsfile send mailersend if send true echo error sending email sendmessage else echo mail sent at email from extensionsthat is function sendmail in joomla with file is path full of a file zip and mailto is a my gmailwhen i send mail i receive the error could not instantiate mail function fatal error cannot access protected property jexceptionmessage in varwhtmldaicomponentscom servicemanagerviewsi0602viewhtmlphp on line 142why can you help me thanks,['php'] +354945,checking if touchend comes after a drag i have some code which changes the class of a table on a phone sometimes the table will be too wide for the screen and the user will dragscroll about to see the contents however when they touch and drag the table around it triggers touchend on every drag how do i test to see whether the touchend came as a result of a touchdrag i tried tracking dragstart and dragend but i could not get that to work and it seems an inelegant approach is there something i could add to below which would essentially determine did this touchend come at the end of a dragresulttableontouchendresulttable tdfunction thistoggleclastaymy thanks in advance for your helpps using latest jquery and while a regular click works it is very slow in comparison to touchend,"['javascript', 'jquery', 'ios']" +355005,why embed the javascript class in an anonymous function call i was reading about the new javascriptlike language from microsoft called typescript in the playground example section there is a simple class in typescript syntax converted to javascript code coming from a java programming background it was interesting for me to learn how oop is done in javascript as compiled from typescriptthe typescript codeclass greeter greeting string constructor message string thisgreeting message greet return hello thisgreeting var greeter new greeterworldvar button documentcreateelementbuttonbuttoninnertext say hellobuttononclick function alertgreetergreetdocumentbodyappendchildbuttonand the equivalent javascript codevar greeter function function greetermessage thisgreeting message greeterprototypegreet function return hello thisgreeting return greetervar greeter new greeterworldvar button documentcreateelementbuttonbuttoninnertext say hellobuttononclick function alertgreetergreetdocumentbodyappendchildbuttonthe typescript part is very similar to java so i understand that now my question is why in javascript the body of the greeter class is embedded in a an anonymous function callwhy not write it like thisfunction greetermessage thisgreeting messagegreeterprototypegreet function return hello thisgreetingwhat is the advantagethisadvantage of each method,['javascript'] +355012,with as in sql navigator the following query worksselect count from everything where num not in select num from sometablethe following query is supposed to be equivalent to the above but results in an invalid identifier errorwith unwanted as select num from sometableselect count from everything where num not in unwantedwhat is wrong with the second query,['sql'] +355026,filter out nonlaunchable apps when getting all installed apps im working on a app where i want to present the user with all installed apps and let himher choose one and then do something with it i followed a tutorial this although i am having some issues after following the tutorial i only got apps that werent preinstalled like all background apps that are not launchable which is great if you want the apps that the user has downloaded from the play store the problem is that in my app i want to thisplay the launchable system apps like youtube and browser but not the nonlaunchable ones like search application providerheres the code that i am using when to get the appsprivate listapp loadinstalledappsboolean includesysapps listapp apps new arraylistapp the package manager contains the information about all installed apps packagemanager packagemanager getpackagemanager listpackageinfo packs packagemanagergetinstalledpackages0 packagemanagerget meta data forint i0 i packssize i packageinfo p packsgeti applicationinfo a papplicationinfo app app new app appsettitlepapplicationinfoloadlabelpackagemanagertostring appsetpackagenameppackagename appsetversionnamepversionname appsetversioncodepversioncode charsequence description papplicationinfoloaddescriptionpackagemanager appsetdescriptiondescription null descriptiontostring appsaddapp return apps now my question is what is the best way to filter out the nonlaunchable appsany help is appreciated,['android'] +355031,entitlement applicationidentifier has value not permitted by a provisioning profile testflight i am aware that questions have been asked regarding the following error entitlement applicationidentifier has value not permitted by a provisioning profile however none of the solutions have solved my problem here is the situation i have an app that downloads files and works great in dev mode when i testflight the app i get the error belowentitlement applicationidentifier has value not permitted by a provisioning profilein my console even though this error appears the application runs properly except it would not download anything all of the other functionality works after the app is downloaded through testflight if i run it and get the above error if i kill the app and restart it i do not get the error and the downloads work fineok heres what i have tried to do to fix iti deleted all provisioning profiles on developerapple and on my machine and recreated them after redownloading the new provisioning profiles i tried again no lucknext i added an entitlementsplist file with the gettaskallow set to false and set the entitlements file for ad hoc builds this also did nothingdoes anyone have an ideaeditadditionally i have made a new version of the app and copied all of the files over under a new app id made all new provisioning files and it still did not work the final thing i tried was making a wildcard ad hoc provisioning profile so that it would sign any app and i still got the same error i really need to figure this out,['iphone'] +355036,how to run a php project from within sublime text 2 is there a way to set up sublime text 2 to build or run a php script i am editing,['php'] +355045,boost compile error mac os x 1074 i want to use boost on my macmac os x 1074xcode 45i installed boost by homebrewbrew install boostboost version is 1490and i set up my xcode projectadd header search pathusrlocalcellarboost1490includeadd librarieslibboost dylibwhen i compile my project i have many errors clang llvm 10 error i want to upload an image but i cannot upload becase i do not have more than 10 reputation use of undeclared identifier nullptr t did you mean nullptruse of undeclared identifier nullptr t did you mean nullptrtoo few template arguments for class template is functionuse of undeclared identifier nullptr t did you mean nullptrfield has incomplete type stdexception ptrexpected at end of declaration listno member named memcpy in namespace std 1 did you mean memcpyno member named memcpy in namespace std 1 did you mean memcpyexpected at end of declaration listexpected at end of declaration listc requires a type specifier for all declarationsoperator cannot be the name of a variable or data memberuse of undeclared identifier nullptr t did you mean nullptrexpected at end of declarationexpected unqualifiedidexpected at end of declaration listunknown type name nullptr tunknown type name nullptr tqualified reference to shared ptr is a constructor name rather than a type wherever a constructor can be declaredtoo many errors emitted stopping nowi checked this questionxcode with boost semantic issue undeclared identifier va startbut i could not find answersplease let me know if there is a solutionthe header file using boost is like thisgltexturehpragma onceifndef gl texture hpp define gl texture hpp standard librariesinclude iostreaminclude fstreaminclude stringifdef win32pragma warning pushpragma warning thisable4819endif smart pointersinclude boostshared ptrhppinclude boostscoped ptrhppinclude boostshared arrayhpp foreach macrosinclude boostforeachhpp regular expressioninclude boostregexhpp image iodefine png infopp null png infoppnulldefine int p null intnullinclude boostgilgil allhppinclude boostgilextensioniojpeg iohppinclude boostgilextensioniopng iohpp file operationsinclude boostfilesystemhpp linear algebrainclude boostnumericublasvectorhppinclude boostnumericublasmatrixhppinclude boostnumericublasiohpp string functionsinclude boostalgorithmstringhpp serializationinclude boostserializationserializationhppinclude boostserializationstringhppinclude boostserializationvectorhppinclude boostarchivexml iarchivehppinclude boostarchivexml oarchivehppinclude boostserializationversionhppifdef win32pragma warning popendif opengl and opengl utility toolkitifdef win32include glglewhinclude glgluthelif defined apple include openglopenglhinclude glutgluthendifinclude texturemanagerhppinclude timehclass texturemanagerusing namespace std function to convert rgb image to rgba image filling its alpha channel with 255 this function is called from boostgilcopy and convert pixelsnamespace boost namespace gil template void color convertrgb8 pixel trgba8 pixel tconst rgb8 pixel t srcrgba8 pixel t dst class gltexturepublic destructor gltexture return instance of gltexture static boostshared ptrgltexture getinstanceconst stdstring filename bool isvolatile true load image file and generate texture bool loadfromfileboostshared ptrgltexture texture bind texture when the texture exists if the texture does not exist this method generates a texture static void bindtextureboostshared ptrgltexture texture setter of texfilename void settexturefileconst stdstring filename setter of volatile flag void setisvolatilebool isvolatile getter of texture id inline const gluint gettextureidvoidconst return thistexture overload of operator to sort list friend bool operator const boostshared ptrgltexture texture1 const boostshared ptrgltexture texture2 friend stdostream operator ostream os const boostshared ptrgltexture texturepublic gluint texture texture id stdstring texfilename image file path int width width of image int height height of image clock t start end start is the timing of bindtexture end is the timing of delete these are used to sort list bool isvolatile the flag whether this texture is volatile or not true is volatile and false is not volatile to keep texture this is false bool isread the flag whether this texture already exists in texturelist true means exists false means not exists boostshared ptrboostgilrgba8 image t pixeldata ptr smart pointer to contain pixeldata boostshared ptrboostgilrgba8 image tconst view t viewwithalpha ptr smart pointer to contain viewdataprivate forbid copy constructor gltexture gltextureconst stdstring imagefilepath bool isvolatile false gltextureconst gltexture gltexture gltexture operator const gltexture gltexture load image from ssd bool loadimageconst stdstring filenameendiftexturemanagerhpragma onceifndef texture manager hpp define texture manager hpp standard librariesinclude iostreaminclude fstreaminclude stringifdef win32pragma warning pushpragma warning thisable4819endif smart pointersinclude boostshared ptrhppinclude boostshared arrayhpp foreach macrosinclude boostforeachhpp regular expressioninclude boostregexhpp image iodefine png infopp null png infoppnulldefine int p null intnullinclude boostgilgil allhppinclude boostgilextensioniojpeg iohppinclude boostgilextensioniopng iohpp file operationsinclude boostfilesystemhpp linear algebrainclude boostnumericublasvectorhppinclude boostnumericublasmatrixhppinclude boostnumericublasiohpp string functionsinclude boostalgorithmstringhpp serializationinclude boostserializationserializationhppinclude boostserializationstringhppinclude boostserializationvectorhppinclude boostarchivexml iarchivehppinclude boostarchivexml oarchivehppinclude boostserializationversionhppifdef win32pragma warning popendif opengl and opengl utility toolkitifdef win32include glglewhinclude glgluthelif defined apple include openglopenglhinclude glutgluthendifinclude gltexturehppclass gltextureclass texturemanagerpublic texturemanagervoid texturemanagervoid generate texture static void gentextureboostshared ptrgltexture texture static void settextureconst boostshared ptrgltexture texture static void deletetexture static bool checklistconst stdstring filenameprivate forbid copy constructor texturemanagerconst texturemanager texmanager texturemanager operator const texturemanager texmanager endif,['c++'] +355070,ios 6 iphoneipad image upload request body stream exhausted with ntlmwindows authentication i am working on trying to get ios 6 to use xmlhttprequest posts to upload images this works on desktop and android web browsers but with ios 6 i am getting an error on the page being posted to request body stream exhausted using ios simulator with the safari web inspectorhere is the basic code of the pagefunction fileselected var file documentgetelementbyidfiletouploadfiles0 if file var filesize 0 if filesize 1024 1024 filesize mathroundfilesize 100 1024 1024 100tostring mb else filesize mathroundfilesize 100 1024 100tostring kb documentgetelementbyidfilenameinnerhtml name filename documentgetelementbyidfilesizeinnerhtml size filesize documentgetelementbyidfiletypeinnerhtml type filetype function uploadfile var fd new formdata fdappendfiletoupload documentgetelementbyidfiletouploadfiles0 var xhr new xmlhttprequest xhruploadaddeventlistenerprogress uploadprogress false xhraddeventlistenerload uploadcomplete false xhraddeventlistenererror uploadfailed false xhraddeventlistenerabort uploadcanceled false xhropenpost uploadhandlerashx xhrsendfdfunction uploadprogressevt if evtlengthcomputable var percentcomplete mathroundevtloaded 100 evttotal documentgetelementbyidprogressnumberinnerhtml percentcompletetostring documentgetelementbyidprogvalue percentcomplete else documentgetelementbyidprogressnumberinnerhtml unable to compute function uploadcompleteevt this event is raised when the server send back a response alertevttargetresponsetextfunction uploadfailedevt alertthere was an error attempting to upload the filefunction uploadcanceledevt alertthe upload has been canceled by the user or the browser dropped the connectionwhen doing this on any other browser the handler returns correctly and uploads the file however with ios the ashx page has the error request body stream exhausted here is a screenshot of the inspectorany ideasupdate this issue only occurs when ntlmwindows authentication is enabled for the application in iis with forms or anonymous authentication the upload works finethanksjohn,['ios'] +355077,what is typescript and why would i use it in place of javascript can you please describe what the typescript language iswhat can it do that javascript or available libraries cannot do that would give me reason to consider it,['javascript'] +355112,does java 7 se have support for ejb if i want ejb 30 support and want to run java 7 do i need java ee or can i stick with se in the past many jdk versions ago one needed the j2ee version of the jdk to run ejb it would appear this is no longer true please adviseupdate i should have mentioned that the application will be running inside oracle weblogic 1036,['java'] +355124,cython and fortran how to compile together without f2py final updatethis question is about how to write a setuppy that will compile a cython module which accesses fortran code directly like c would it was a rather long and arduous journey to the solution but the full mess is included below for contextoriginal questioni have an extension which is a cython file which sets up some heap memory and passes it to the fortran code and a fortran file which is a venerable old module that i would like to avoid reimplementing if i canthe pyx file compiles fine to c but the cython compiler chokes on the f90 file with the following error python setuppy build ext inplacerunning build extcythoning delaunay init pyx to delaunay init cbuilding delaunay extensionerror unknown file type f90 from delaunaystripackf90heres the top half of my setup filefrom thistutilscore import setup extensionfrom cythonthistutils import build extext modules extensiondelaunay sourcesdelaunay init pyx delaunaystripackf90setup cmdclass build ext build ext ext modules ext modules note i originally had the fortran files location incorrectly specified without the directory prefix but this breaks in exactly the same way after i fixed thatthings i have triedi found this and tried passing in the name of the fortran compiler ie gfortran like this python setuppy config fcompilergfortran build ext inplaceusage setuppy global opts cmd1 cmd1 opts cmd2 cmd2 opts or setuppy help cmd1 cmd2 or setuppy helpcommands or setuppy cmd helperror option fcompiler not recognizedand i have also tried removing inplace in case that was the problem it was not same as the top error messageso how do i compile this fortran can i hack it into a o myself and get away with linking it or is this a bug in cython which will force me to reimplement thistutils or hack around with the preprocessorupdateso having checked out the numpythistutils packages i understand the problem a bit more it seems that you have touse cython to convert the pyx files to cpython c filesthen use an extensionsetup combination that supports fortran like numpyshaving tried this my setuppy now looks like thisfrom numpythistutilscore import setupfrom cythonbuild import cythonizefrom numpythistutilsextension import extensioncy modules cythonizedelaunayspherepyxe cy modules0ext modules extensiondelaunaysphere sourcesesources delaunaystripackf90setup ext modules ext modules namedelaunay note that i have also restructured the module a bit since seemingly an init pyx is thisallowednow is where things become buggy and platformdependent i have two testing systems available one mac os x 106 snow leopard using macports python 27 and one mac os x 107 lion using the system python 27on snow leopard the following appliesthis means that the module compiles hurray although there is no inplace for numpy it seems so i had to systemwide install the testing module but i still get a crash on import as follows import delaunay traceback most recent call last file input line 1 in module file snipsitepackagesdelaunay init py line 1 in module from sphere import delaunay mesh importerror dlopensnipsitepackagesdelaunaysphereso 2 no suitable image found did find snipsitepackagesdelaunaysphereso macho but wrong architectureand on lion i get a compile error following a rather confusing looking compile linegfortranf77 buildsrcmacosx107intel27delaunayspheref2pywrappersfusrlocalbingfortran wall arch i686 arch x86 64 wall undefined dynamic lookup bundle buildtempmacosx107intel27delaunaysphereo buildtempmacosx107intel27buildsrcmacosx107intel27delaunayspheremoduleo buildtempmacosx107intel27buildsrcmacosx107intel27fortranobjecto buildtempmacosx107intel27delaunaystripacko buildtempmacosx107intel27buildsrcmacosx107intel27delaunayspheref2pywrapperso lgfortran o buildlibmacosx107intel27delaunayspheresold duplicate symbol initsphere in buildtempmacosx107intel27buildsrcmacosx107intel27delaunayspheremoduleo ldand build tempmacosx107intelduplicate 27symbol delaunaysphereo initsphere in forbuild architecture i386tempmacosx107intel27buildsrcmacosx107intel27delaunayspheremoduleo and buildtempmacosx107intel27delaunaysphereo for architecture x86 64now let us just step back a moment before we pore over the details here firstly i know there are a bunch of headaches over architecture clashes in 64bit mac os x i had to work very hard to get macports python working on the snow leopard machine just to upgrade from system python 26 i also know that when you see gfortran arch i686 arch x86 64 you are sending mixed messages to your compiler there are all manner of platformspecific problems buried in there that we do not need to worry about in the context of this questionbut let us just look at this linegfortranf77 buildsrcmacosx107intel27delaunayspheref2pywrappersfwhat is numpy doing i do not need any f2py features in this build i actually wrote a cython module in order to avoid dealing with f2pys insanity i need to have 4 or 5 output variables as well as neitherinnorout arguments neither of which is well supported in f2py i just want it to compile c o and f90 o and link them i could write this compiler line myself if i knew how to include all the relevant headersplease tell me i do not need to write my own makefile for this or that there is a way to translate fortran to outputcompatible c so i can just avoid python ever seeing the f90 extension which fixes the whole problem note that f2c is not suitable for this as it only works on f77 and this is a more modern dialect hence the f90 file extensionupdate 2the following bash script will happily compile and link the code in placepython h locationoptlocallibraryframeworkspythonframeworkversions27includepython27cython spherepyxgcc arch x86 64 c spherec ipython h locationgfortran arch x86 64 c stripackf90gfortran arch x86 64 bundle undefined dynamic lookup loptlocallib o o spheresoany advice on how to make this kind of hack compatible with a setuppy i do not anyone installing this module to have to go find pythonh manually,"['python', 'c']" +355201,convert foreigncollection to arraylist ormlite gson and android i apologize if i am not super clear with my explanation but i will add to and edit this question for clarity if requestedi am developing an android app which receives data through an external api and stores data locally using ormlite prior to storing data locally and using ormlite i had models which retrieved json from the server and parsed it viagson gson new gsonstring result apiclienthttppostuser routeuser user gsonfromjsonresult userclassthe user class was defined public class user int id string name arraylistimage mediaand the image classpublic class image int id int creator id string urlthis is a simplified representation of the models and methods but i believe i have kept all the relevant information btw media is a json object which contains the images now i am trying to also store the data locally in order to have the relationship between users and images using ormlite it seems you have to employ foreigncollection class and foreigncollectionfield annotation i do not believe gson can directly parse the json for the media field in the user class as a foreigncollection object so i thought i needed to create two fields mediacollection and media using ormlite the user class now looks like thisdatabasetabletablename userspublic class user databasefieldgeneratedid true int id databasefield string name foreigncollectionfield foreigncollectionimage mediacollection arraylistimage mediathe image class with ormlite looks like thisdatabasetabletablename imagespublic class image databasefieldgeneratedid true int id databasefieldforeigntrue foreignautocreatetrue foreignautorefreshtrue private user user databasefield int creator id databasefield string urlhow the flow of the app works is first i hit the local database for a user i perform some logic which then determines if i need to actually hit the server to update or refresh the user datawhether the data comes locally or from the remote server i need to thisplay the image in the same view as it stands now the url for the image is stored in different types of objects depending on whether the data is local or remote what i would like to do is if the image is stored in a foregincollection object convert that object into an arraylist and then proceed with the rest of my code which extracts the image url and thisplays iti guess there are two questionsis this a good plan or should i write two completely separate ways of extracting the image url from the data not converting the object from foreigncollection to arraylistif it is a good plan how do i convert a foregincollection to an arraylist,['android'] +355204,move google map center javascript api in my project i want to move the center of the map to new coordinates this is the code i have for the map function initialize var mapoptions center new googlemapslatlng0 0 zoom 4 maptypeid googlemapsmaptypeidroadmap var map new googlemapsmapdocumentgetelementbyidmap canvas mapoptions function movetolocationlat lng var center new googlemapslatlnglat lng var map documentgetelementbyidmap canvas mappantocenter the movetolocation function does get called but the map does not re center any idea what i am missing,['javascript'] +355222,smarter word break in css if i just put wordbreak breakall on an element i often end up with thishello people i am typing a mes sage that is too long to fitobviously this would be much better ashello people i am typing a message that is too long to fitbut at the same time if someone writesblarghthen i would want it to beblar rghi cannot seem to find a way to actually do thisnote that the width of the element is not fixed and may change,['css'] +355265,how to identify leaflet us marker during a popupopen event when a marker is clicked i need to execute some code that finds the id corresponding to the marker being clicked retrieves data from backend api then adds the newly retrieved data to the content of the popup that will openthe only way that is able to listen to a click event on the marker is maponpopupopen functione how to retrieve marker eg assign an id on creation retrieve it now during popupopenhow can i find out which marker this is is it possible to add an id attribute to each marker then retrieve this id during the popupopen event,"['javascript', 'jquery']" +355327,shortcomings of mysql real escape string i have seen a few people on here state that concatenating queries using mysql real escape string will not protect you entirely from sql injection attacks however i am yet to see an example of input that illustrates an attack that mysql real escape string would not protect you from the majority of examples forget that mysql query is limited to one query and use mysql real escape string incorrectlythe only example i can think of is the followingmysql querydelete from users where user id mysql real escape stringinputthis would not protect you from the following input5 or 11i would see this as incorrect usage of mysql real escape string rather than a shortcoming it is designed for strings not numeric values you should either cast to a numeric type or if you are going to treat the input as a string when sanitising you should do the same in your query and wrap quotation marks around itcan anyone provide an example of input that can get around mysql real escape string that does not rely on incorrect handling of numeric values or forget that mysql query can only execute one queryedit i am interested in the limitations of mysql real escape string and not comparing it to alternatives i realise there are better options for new projects and am not thisputing that,"['php', 'mysql']" +355334,an explicit value for the identity column in table customers can only be specified when a column list is used and identity insert is on possible duplicatecannot insert explicit value for identity column in table atablea when identity insert is set to off i am new to sql i am trying to write a insert query in sql server 2008 express edition the query is insert into customersvalues201 singh rajnish 101 bhandup mumbai mp 321 0 null 12389 2500but i am getting following erroran explicit value for the identity column in table customers can only be specified when a column list is used and identity insert is oni searched stackoverflow found some similar type of questions but unable to understand the explanation kindly help me to understand the error and rectify itedit i tried to do set identity insert customers oninsert into customersvalues201 singh rajnish 101 bhandup mumbai mp 321 0 null 12389 2500set identity insert customers offbut again i am getting the same error,['sql'] +355356,to regex with a string or to not regex with a string i have started using the matchregex method in my java program but for now i am just using a string string regexstring new stringazaz09azaz09 which is what i have so far as an example i know however i can use an actual regex regex pattern new regex the pattern class then compile it some howis there an advantage to using regex as a class and not just a string in java i am quite used to bash scripting and there regexes are just strings in the loosest sense and there is no abilityneed for a separate class so i am struggling to see where there is one here,['java'] +355412,resizing breaks the position of my divs i created a basic clock using only divs no images and when rezing the clock arrows breaks and is off position as show here why is this happening can someone fix this for me it is a single file no external files,"['jquery', 'html', 'css']" +355470,how to set the holo dark theme in a android app how can i set the dark holo theme in my appat this time i got thisstyle nameapptheme parentandroidthemehololight but when i change it tostyle nameapptheme parentandroidthemeholodark i get an error error error retrieving parent for item no resource found that matches the given name androidthemeholodarkhow to solve the problem,['android'] +355479,memoryfailpoint throws insufficientmemoryexception unconditional i have a very strange issue in our rest application we have introduced an option for upload of a webpackage since these can be rather large when unpacked we wanted to assure a successful experience with memory check by memoryfailpointon my local iis 75 this works flawlessly even up to a max expected value of 2gbon our virtual windows server 2008r2 x64 with iis 75 this fails unconditionally even if only trying 1mbthe virtual server is hosted on vmware esxi 410 348481here is the sample code that fails on the virtual machineusing memoryfailpoint failpoint new memoryfailpoint1 deliberately excluded webpackage codeand the exception in xmlinsufficientmemoryexception messageinsufficient memory to meet the expected demands of an operation and this system is likely to never satisfy this request if this is a 32 bit system consider booting in 3 gb modemessage stacktrace lineat systemruntimememoryfailpointctorint32 sizeinmegabytesline lineat systemservicemodelthispatchersyncmethodinvokerinvokeobject instance object inputs objectamp outputsline lineat systemservicemodelthispatcherthispatchoperationruntimeinvokebeginmessagerpcamp rpcline lineat systemservicemodelthispatcherimmutablethispatchruntimeprocessmessage5messagerpcamp rpcline lineat systemservicemodelthispatcherimmutablethispatchruntimeprocessmessage31messagerpcamp rpcline lineat systemservicemodelthispatchermessagerpcprocessboolean isoperationcontextsetline stacktrace userdefinedinformation failpointsizeinmegabytes100failpointsizeinmegabytes gctotalmemorybeforeinmegabytes15334gctotalmemorybeforeinmegabytes userdefinedinformationinsufficientmemoryexceptionand a similiar exception from my machine take note that i needed to allocate 64gb before i could trigger the exceptioninsufficientmemoryexception messageinsufficient available memory to meet the expected demands of an operation at this time please try again latermessage stacktrace lineat systemruntimememoryfailpointctorint32 sizeinmegabytesline lineat systemservicemodelthispatchersyncmethodinvokerinvokeobject instance object inputs objectamp outputsline lineat systemservicemodelthispatcherthispatchoperationruntimeinvokebeginmessagerpcamp rpcline lineat systemservicemodelthispatcherimmutablethispatchruntimeprocessmessage5messagerpcamp rpcline lineat systemservicemodelthispatcherimmutablethispatchruntimeprocessmessage31messagerpcamp rpcline lineat systemservicemodelthispatchermessagerpcprocessboolean isoperationcontextsetline stacktrace userdefinedinformation failpointsizeinmegabytes6553600failpointsizeinmegabytes gctotalmemorybeforeinmegabytes15063gctotalmemorybeforeinmegabytes userdefinedinformationinsufficientmemoryexceptionthis is driving me nuts for real but hey take note of the two very different exceptionsserver insufficient memory to meet the expected demands of an operation and this system is likely to never satisfy this request if this is a 32 bit system consider booting in 3 gb modeusing dotpeek from jetbrains and this website tfsdev10releasesrtmrelndpclrsrcbclsystemruntimememoryfailpointcs1305376memoryfailpointcs we can see what might be the issue although i am still clueless check to see that we both have enough memory on the system and that we have enough room within the user section of the proces address space also we need to use the gc segment size not the amount of memory the user wants to allocate consider correcting this to reflect free memory within the gc heap and to check both the normal large object heaps ulong num1 ulong sizeinmegabytes 20 this reservedmemory num1 ulong size ulongmathceilingdoublenum1 doublememoryfailpointgcsegmentsize doublememoryfailpointgcsegmentsize if size memoryfailpointtopofmemory throw new insufficientmemoryexceptionenvironmentgetresourcestringinsufficientmemory memfailpoint toobiglocal insufficient available memory to meet the expected demands of an operation at this time please try again lateredithans and i had a thiscussion about vm size but since i have now concluded that it is more or less equal on the development server and my machine i will rule this part out for now any hints suggestions etc is more than welcomeprocess infoprocess name w3wppid 5716user name nt authoritynetwork serviceworking set 376456 kpeak working set 432400 kprivate working set 320684 kcommit size 538552 khandles 919threads 39operating system wmibootdevice devicehardthiskvolume1buildnumber 7601buildtype multiprocessor freecaption microsoft windows server 2008 r2 standard codeset 1252countrycode 45creationclassname win32 operatingsystemcscreationclassname win32 computersystemcsdversion service pack 1csname some name modifiedcurrenttimezone 120dataexecutionprevention 32bitapplications truedataexecutionprevention available truedataexecutionprevention drivers truedataexecutionprevention supportpolicy 3debug falsedescription development serverthistributed falseencryptionlevel 256foregroundapplicationboost 2freephysicalmemory 5366516 kfreespaceinpagingfiles 8368456 kfreevirtualmemory 12985412 kinstalldate 17012011 150155largesystemcache nulastbootuptime 11092012 1433localdatetime 03102012 141347locale 0406manufacturer microsoft corporationmaxnumberofprocesses 4294967295maxprocessmemorysize 8589934464 kmuilanguages systemobjectname microsoft windows server 2008 r2 standard cwindowsdevicehardthisk0partition2numberoflicensedusers nullnumberofprocesses 70numberofusers 7operatingsystemsku 7organization osarchitecture 64bitoslanguage 1033osproductsuite 272ostype 18othertypedescription nullpaeenabled nullplusproductid nullplusversionnumber nullprimary trueproducttype 3registereduser windows userserialnumber 1 modifiedservicepackmajorversion 1servicepackminorversion 0sizestoredinpagingfiles 8388152 kstatus oksuitemask 272systemdevice devicehardthiskvolume2systemdirectory cwindowssystem32systemdrive ctotalswapspacesize nulltotalvirtualmemorysize 16774452 ktotalvisiblememorysize 8388152 kversion 617601windowsdirectory cwindowsvmmap screenshot from development serverbeing curious about the virtual size i download vmmap from sysinternals vmmap screenshot from my local machine where memoryfailpoint works as expectedit is still not clear to me why the memoryfailpoint fails and it is important especially when talking windows azure or other cloud providers to make sure there is enough memory for the operation to take an example then an extrasmall instance will fail even it is x64 architecture somewhere in the process because of the very limited resources this could be prevented by the memoryfailpoint hence assuring a valid state of dataany help is most appreciated,['.net'] +355482,is generics runtime or compile time polymorphism i read that the following format comes under parametric polymorphism but can we classify it in one either runtime or compile time polymorphismpublic class stackt items are of type t which is known when we create the object t items int count public void pusht item type of method pop will be decided when we create the object public t pop,['c#'] +355505,youtube video not playing in webview android i am tying to play youtube video in webview webview showing first look of video with play button but after click on play button start progress bar and after 23 seconds stop progress bar and screen blank with black color image1 video first look with play buttonimage2 after click on play button screen goes blankplease help me why video not starting image1 image2this is my source code to play youtubevideo in webview please help me public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain webview wv webview findviewbyidridwebview1 wvgetsettingssetjavascriptenabledtrue wvgetsettingssetpluginsenabledtrue final string mimetype texthtml final string encoding utf8 string html gethtml wvloaddatawithbaseurl html mimetype encoding public string gethtml string html iframe classyoutubeplayer styleborder 0 width 100 height 95 padding0px margin0px idytplayer typetexthtml src j2fb5xwj6ie fs0 frameborder0n iframen return html,['android'] +355523,whats the difference between bitmapclone and new bitmapbitmap as far as i can tell there are two ways of copying a bitmapbitmapclonebitmap a new bitmapsomefilepngbitmap b bitmapaclonenew bitmapbitmap a new bitmapsomefilepngbitmap b new bitmapahow do these approaches differ i am particularly interested in the difference in terms of memory and threading,['c#'] +355526,android where to store selector xml file for customed design controls i tried to make a custom linearlayout and button stylesi am just wondering where to place my selector xml filesselector xmlnsandroiditem shape gradient androidangle90 androidstartcolor534e4e androidendcolor0 androidtypelinear shapeitemin my mono project i put the files at drawable folder but in my javanative development i do not know maybe i miss the basic in storing files but still have no idea where to put my selector since the latest eclipse plugin has 4 drawables ldpihdpi mdpi and xhdpi,"['java', 'android']" +355557,how to make shaking animation in my xcode project i have an uiimage i want to make it shaking animation from left to right a little bit i wrote this code however its not workingvoiderrorshake uiview beginanimationsnil contextnull uiview setanimationduration10 lockimage settransformcgaffinetransformmakerotation5 m pi 1800 lockimage settransformcgaffinetransformmakerotation10 m pi 1800 lockimage settransformcgaffinetransformmakerotation15 m pi 1800 lockimage settransformcgaffinetransformmakerotation20 m pi 1800 lockimage settransformcgaffinetransformmakerotation15 m pi 1800 lockimage settransformcgaffinetransformmakerotation10 m pi 1800 lockimage settransformcgaffinetransformmakerotation5 m pi 1800 lockimage settransformcgaffinetransformmakerotation0 m pi 1800 lockimage settransformcgaffinetransformmakerotation5 m pi 1800 lockimage settransformcgaffinetransformmakerotation10 m pi 1800 lockimage settransformcgaffinetransformmakerotation15 m pi 1800 lockimage settransformcgaffinetransformmakerotation20 m pi 1800 lockimage settransformcgaffinetransformmakerotation15 m pi 1800 lockimage settransformcgaffinetransformmakerotation10 m pi 1800 lockimage settransformcgaffinetransformmakerotation5 m pi 1800 lockimage settransformcgaffinetransformmakerotation0 m pi 1800 uiview commitanimationscould you tell me please how can i make my image shake,"['iphone', 'objective-c', 'ios']" +355572,codelite formatting i use the codelite ide for c development but i have not found any way to selectformat the text properlythisif1 1return 1should be formatted as if1 1 return 1does anyone know if there is a way to select a block of code and then format it using the codelite ide,['c++'] +355593,can i use typed factory facility to return implementation based on enum parameter not sure if this is possible or noti need to return the correct implementation of a service based on an enum value so the handcoded implementation would look something likepublic enum myenum one two public class myfactory public itypeiwanttocreate createmyenum type switch type case myenumone return new typeiwanttocreate1 break case myenumtwo return new typeiwanttocreate2 break default return null the implementations that are returned have additional dependencies which will need to be injected via the container so a handrolled factory would not workis this possible and if so what would the registration look like,['c#'] +355601,how to read a connectionstring in net 45 how do i read a value from the webconfig file for a connectionstring in the 45 net frameworki am using systemconfiguration which i have a reference to and a using statement but the only thing coming up after that to use is configurationsettingsappsettingsno connectionstringsettings,"['c#', '.net']" +355608,storing authentication token on ios i am building an ios application and the user authenticates with my web service i do not want them to login every time the app launches the token lasts a month so i would like to cache this on the device somewhere whats the best way to do this securelycan i just rely on the app remaining suspended and keeping the token in memory,"['iphone', 'ios']" +355617,sql query to test if string value contains carriage return trying to figure out the right way to test if a varchar column value ends with a carriage return tried this but it does not work database is oracle 11gselect name from mytable where name like r or name like n,['sql'] +355622,can a smart app banner launch an app installed from xcode i am trying to prototype the integration between a smart app banner and an ios app is it possible for a smart app banner to launch an ios app that was installed from xcode instead of the app store on either a device or in the simulatorthank you,['ios'] +355634,ios 60 quicklook qlpreviewcontroller errors with cannot find preview item for loaded proxy my application has been using the qlpreviewcontroller to thisplay files of all types and in ios 5x it seemed to do so just fine now in ios 60 i get an error and it shows the controller but with a constant loading indicator and never actually loads anythingthe error in the log is cannot find preview item for loaded proxy qlpreviewitemproxy 0x8dbf480 filelocalhostusersmelibraryapplication20supportiphone20simulator60applicationse6a58f8d71f34c7ab16e4ba017e318e5documentstempwelcomedocxanyone else have this or other issues with the quicklook in ios 60 or any suggestions of what to try i have tried it via iphone and ipad with both pushing the controller and presenting itedit also just noticed that the url in question the one they say is bad starts with not just file but filelocalhost whereas the original file just started with an actual path ie fileusers,"['objective-c', 'ios']" +355654,ruby 193 how does csvtable know if no headers are in a csv file i have been doing some testing with csvtable i have two small and almost identical csv files however one is missing the header rowwhen i run csvtable against the csv file with the header row everything works as expectedwhen i run it against the csv file without the header row i getnomethoderror undefined method encode for nilnilclassi tried this with different types of data with different types of headers and get the same resultsi am curious to the magic of csvtable if i use csvparse with headers set to true then it always makes the first row be headers no matter what so i have been using csvtable to check if a csv file being imported has a header row but i am not too comfortable with this because i do not understand if or when it will or will not work the way i am using itbegin csvtablecsv file pathrescue add error to log or somethingenddoes anyone knowps i have already read through this and the source code it provides on each method,['ruby'] +355660,how can i standardize helvetica neue line heights crossbrowser not about bold text so i am developing a site thatll need to function across a multitude of browsers be they desktop mobile or what have you the designers as mac designers will often do have used helvetica neue as the font for the entire site i am trying to get it working via font inclusion and it is showing up just fine but the lineheights are giving me an ulcersee the below image this is arial helvetica neue std and helvetica neue pro windows chrome handles all three like a champ but the rest here are wildly inconsistent they are all set to lineheight 18px right now i also tried lineheight 1 but to no availthe htmlcss i am using for the purposes of this teststyle typetextcss fontface fontfamily helvetica neue std src url helveticaneueltstdmdotf format opentype fontface fontfamily helvetica neue pro src url helveticaneueltpromdotf format opentype box float left padding 10px border 1px solid red fontsize 18px lineheight 18px box text 1 fontfamily arial box text 2 fontfamily helvetica neue std box text 3 fontfamily helvetica neue pro stylediv classbox span classtext 1aw nutsspandivdiv classbox span classtext 2aw nutsspandivdiv classbox span classtext 3aw nutsspandivam i just out of luck here i am considering just using arial at this point because trying to make toolbars and buttons where the text is vertically centered is proving to be a nightmare i certainly do not want to sniff for os and browser and write custom lineheights for every single element,"['android', 'css']" +355663,returning multiple files from mvc action so i have got an mvc 3 application that has a couple places where a text file gets generated and returned in an action usingreturn filesystemtextencodingutf8getbytessomestring textplain filenameextensionand this works fabulously now i have got a situation where i am trying to return a pair of files in a similar fashion on the view i have an action link like click here to get those 2 files and i would like both files to be downloaded much like the single file is downloaded in the above code snippethow can i achieve this been searching around quite a bit and have not even seen this question posed anywhere,['asp.net'] +355670,tan in java returning a strange value my code passes an angle in radians to the cos tan and sin everything seems to work fine except tan of 90 which gives the value 16331239353195370 for some odd reason example codeimport javatextdecimalformatpublic class mathtable public static void mainstring args systemoutprintlnangle sin cos tan systemoutprintln for double angle 00 angle 180 angle 5 double angle rad mathtoradiansangle double sin mathsinangle rad string sin 4 new decimalformatformatsin double cos mathcosangle rad string cos 4 new decimalformatformatcos double tan mathtanangle rad string tan 4 new decimalformatformattan systemoutprintlnangle sin 4 cos 4 tan 4 why is the value returned not strictly equal to ie infinity,['java'] +355717,using directives sorted in wrong order i am using the power commands extension with visual studio 2012 i have the option checked to remove and sort usings on save the problem is that the systemx directives are being sorted last and that is causing a style analysis errorsa1208 system using directives must be placed before all other using directivesbefore saveusing systemusing systemdiagnosticscodeanalysisusing fooafter saveusing foousing systemusing systemdiagnosticscodeanalysisthis worked correctly systemx first with vs 2010 anyone know how to correct thisnote even if it did not cause an sa error i would still prefer the system directives to be first,['c#'] +355726,how do i return multiple result sets with sqlcommand can i execute multiple queries and return their results executing a sqlcommand just once,['c#'] +355733,lightening a uicolor i ran into a situation yesterday where i needed to lighten a uicolor so i created a category and added a lighten method i thought it would be straight forward to just multiply the value by each component of the color but my greens started turning yellow so i knew it had to be more complicatedthe solution i came up with was to convert from srgb to linear multiply the color and then convert back this seems to work but i am not sure if it is correct i could not find anything in the docs that stated that uicolor was in srgb space i am also no color scientist so i only have a rudimentary knowledge of the math involvedanyway here is my code i am asking for some peer review and to see if anyone has a better understanding of modifying uicolorscgfloat srgb2linearcgfloat x cgfloat a 0055 ifx 004045 return x 10 1292 else return powx a 10 1 a 24 cgfloat linear2srgbcgfloat x cgfloat a 0055 ifx 031308 return x 1292 else return 1 a powx 1 24 a uicolor lightencgfloatvalue const cgfloat components cgcolorgetcomponentsself cgcolor cgfloat newr srgb2linearcomponents01value cgfloat newg srgb2linearcomponents11value cgfloat newb srgb2linearcomponents21value newr max0 min1 linear2srgbnewr newg max0 min1 linear2srgbnewg newb max0 min1 linear2srgbnewb return uicolor colorwithrednewr greennewg bluenewb alphacomponents3,['objective-c'] +355769,android update textview in thread and runnable i want to make a simple timer in android that updates a textview every second it simply counts seconds like in minesweeperthe problem is when i ignore the tvtimesettext make it tvtimesettext in logcat will be printed the following number every secondbut when i want to set this number to a textview created in another thread the program crashesdoes anyone have an idea how to solve this easilyheres the code method is called on startupprivate void starttimerthread thread th new threadnew runnable private long starttime systemcurrenttimemillis public void run while gamestate gamestateplaying systemoutprintlnsystemcurrenttimemillis thisstarttime 10 tvtimesettext systemcurrenttimemillis thisstarttime 10 try threadsleep10 catch interruptedexception e eprintstacktrace thstarteditfinally i got ithere is the solution for those who are interested inprivate void starttimerthread thread th new threadnew runnable private long starttime systemcurrenttimemillis public void run while gamestate gamestateplaying runonuithreadnew runnable override public void run tvtimesettextsystemcurrenttimemillisstarttime10 try threadsleep10 catch interruptedexception e eprintstacktrace thstart,['android'] +355784,how to position an x in an input widget to clear the content with twitter bootstrap it is quite straight forward to create a search style input widgetalso the x is doable with twitter bootstrap but positioning the x in that spot requires some css finetuningi managed to get the x in that position but it is not very reliable with a responsivedesign and different resolutions the x gets completely thisplacedfilterclose float none position relative left 5em top 125em zindex 3form action methodget classformsearch a classclose filterclose hrefxa div classinputappend filter formlast namebutton typesubmit classbtni classiconfilter ibutton div formbefore trying to reinvent the wheel is there any existing javascript library that could turn an input in an inputwithanxbutton something like chosenjs for this purposeor any advice how i could do this in a better way many thanks,"['javascript', 'jquery']" +355801,intellisense with mvc4 style bundling so far i cannot find a question or fix for this i am sure it is something simple i am missingi have a style bundle with a bunch of minified css and i am decorating html elements with the classes inside everything is working greatintellisense and resharper however are both bugging me about the css the classes being unknown i am guessing this is because they cannot peek inside the bundlesquestion is there a way to fix this style bundles in head tagstylesrenderbundlestylecssrendersectionstyles false html elements in body tag row is an unknown css class div classrow plorem ipsumpdivupdate visual studio 2012 less conversion and intellisense works for single directly referenced files my situation is that intellisense breaks when referencing a less bundleupdate 2 heres the code showing the bundleconfigcs since it isnt clearvar customstyles new bundlebundlestylecss includecontentnormalizecsscontentlessbootstrapstylestransformsaddnew lesstransformbootstrapstylestransformsaddnew cssminifybundlesaddcustomstylesnotice we are using bundle not stylebundle which is necessary because we want to specify the lesstransform class and skip the built in css transformer the lesstransform object is a custom object that simply reads in all the less content and concatenates it on a stringbuilder and then calls dotles converter out comes a huge css string that is minified and returned the question is why cant vs or resharper peek at the returned css and help check class styles,['css'] +355870,initializing static variable with a function call gives compilation error include stdiohint foo return 1int mainvoid static int q foo return 0here is a link for the same this is a c code and not c it compiles and run fine in c but not cthis code was getting compilation error can someone please explain why is it getting error can static members only be initialized by constant values in c we need to define static members after declaring them why is it not required in c i could not find any thread with similar query or a good answer,['c'] +355873,unpacking arguments only named arguments may follow expression the following works beautifully in pythondef fxyz return xyza12f3athe elements of a get unpacked as if you had called it like f312 and it returns 312 wonderfulbut i cannot unpack the elements of a into the first two argumentsfa3instead of calling that like f123 i get syntaxerror only named arguments may follow expressioni am just wondering why it has to be that way and if there is any clever trick i might not be aware of for unpacking arrays into arbitrary parts of argument lists without resorting to temporary variables,['python'] +355939,c unsafe function a floatresult vs floatresult can anyone explain in a simple way the codes belowpublic unsafe static float sample int result 154 153 8 25 16 64 24 return floatresult do not know what for please explainnote the above code uses unsafe functionfor the above code i am having hard time because i do not understand whats the difference between its return value compare to the return value belowreturn floatresultis it necessary to use unsafe function if your returning floatresult,['c#'] +355967,how do i properly handle exceptions in constructors possible duplicatehow to clean initialized resources if exception thrown from constructor in c how do i handle exception in constructors if i am creating 6 objects and those objects create 5 object and fails while creating the 6th onethanks,['c++'] +356050,build error while add revmob ad in ios app i want to add revmob add in my app but there are some errors undefined symbols for architecture i386 objc class skstoreproductviewcontroller referenced from objcclassref in revmobadsrevmobstorecontrollero skstoreproductparameteritunesitemidentifier referenced from revmobstorecontroller openstorewithitunesitemid in revmobadsrevmobstorecontrollerold symbols not found for architecture i386clang error linker command failed with exit code 1 use v to see invocationi have added storekitsystemconfiguration and revmob frameworks alreadyi am using xcode43 and ios42 plz help me thanks in advance,['ios'] +356051,android animation reduce stutterchoppylag so i have been having animation issues especially when two animations happen at once or right when an activity loads i understand it is probably a resource problem and a lot of things are going on in the main thread causing the animations to stutteri have found a couple interesting suggestions1 threads threadpoolexecutorhere how do i make my animation smoother android2 setdrawingcacheenabledtruehere how does androids setdrawingcacheenabled work3 viewgroup animationcache truehere however i have not been able to find any sort of examples to implement these things any ideas,['android'] +356055,android how to detect the image orientation portrait or landscape picked from gallery while setting on an imageview i am setting an image on the imageview picked from the gallerycamera album if the picked image has landscape orientation it thisplays perfectly but if the image in in portrait modeie the image was clicked in portrait mode it is thisplaying the image with a 90 degree rotation now i am trying to find out the orientation just before setting on imageview but all the images are giving same orientation and same widthheight here is my code uri selectedimage intentgetdataif selectedimage null bitmap bitmap mediastoreimagesmediagetbitmapthisgetcontentresolver selectedimage int str new exifinterfaceselectedimagegetpathgetattributeintorientation 10 toastmaketextthis value str toastlength longshow toastmaketextthis width bitmapgetwidth height bitmapgetheight toastlength longshow,['android'] +356113,php mysql percentage my question is about percentages i am not an expert so i will try to explain in the better possible wayi have a table with let say 700 records in my mysql server something like this name country language birth lucy uk en 1980 mari canada fr 1990 gary canada en 1982 stacy jamaica en 1986 joao brasil pt 1984 so i query all the records that are between 1980 and 1985 and the result will be name country language birth lucy uk en 1980 gary canada en 1982 joao brasil pt 1984 and from this result i would like to obtainthe percentage of appearance of every languages between those yearsen 75 3 is the total in this casept 25the percentage of appearance of every country that is seen in the resulting tableuk 33canada 33brasil 33i mean how can i convert the results in variables to use them in the final function,"['php', 'mysql']" +356119,strange integer behavior with gcc o2 include stdiohinclude limitshvoid sanity checkint x if x 0 x x if x int min printfd dn x int min else printfd dn x int min if x 0 printfnegative number dn x else printfpositive number dn x int mainvoid sanity check42 sanity check97 sanity checkint min return 0when i compile the above program with gcc wtfc i get the expected output42 2147483648positive number 4297 2147483648positive number 972147483648 2147483648negative number 2147483648however when i compile the program with gcc o2 wtfc i get a different output42 2147483648positive number 4297 2147483648positive number 972147483648 2147483648positive number 2147483648note the last two lines what on earth is going on here is gcc 463 optimizing a bit too eagerlyi also tested this with g 463 and i observed the same strange behavior hence the c tag,"['c++', 'c']" +356123,how to make a div align to the right side of the parent while maintaining its vertical position please refer to this handy diagram i drew div1s height is unknown div3s width is fluid it should never overlap div2 both div1 and div2 have the same width and are horizontally centered via margin auto how can i position div3 so that it aligns to the right side of body no matter how wide body is while sharing vertical position with div2 using css,['css'] +356127,junit how to check if string is equal to one of two strings this seems like a super simple question but i just cannot figure it outi am just trying to assert that a string is equal to string1 or string2heres what i have tried but neither obviously does not workassertequalsdgetformtype string1 assertequalsdgetformtype string2assertequalsdgetformtype string1 string2,['java'] +356145,expand listview item with animation i have a listview initially the listview contains some data when the user clicks on an item another layout will be dynamically added to that item so it is height will be increasedright now when the items height is increased it shows the modified item instantly however what i want is for this to be animated so it increases the items height gradually,['android'] +356159,rails mysql2 undefined method accept for nilnilclass i know that was a milion times here but tried everything and i am still getting this error rake dbmigraterake abortedundefined method accept for nilnilclasstasks top dbmigratesee full trace by running task with tracethis is the gem list not allactivemodel 328activerecord 328activerecordmysql2adapter 003builder 313 303bundler 121mysql2 032rails 328rails apps composer 2210railties 328rake 0922rdoc 312sqlite3 136therubyracer 0102thor 0160tilt 133treetop 1410twitterbootstraprails 213tzinfo 03uglifier 130i have tried with all versions of mysql2 from 027 to 032edit database filedevelopment adapter mysql2 database tripwall username root password pass host localhost pool 5 timeout 50,"['mysql', 'ruby']" +356169,copy table structure to new table in sqlite3 is there an easy way to copy an existing table structure to a new one dont need the data only the structure like id integer name varchar20 thx,['sql'] +356177,edittext inside listview will not stay focused i have an edittext inside each row of a listview for some reason when i tap the edittext it briefly gains focus but then immediately loses iti have tried these thingslistviewsetitemscanfocustrueedittextsetfocusabletruewhile the edittext is briefly focused the enter key says next and the autocorrect bar is present when it loses focus the soft keyboard stays up but the enter key becomes a return arrow and the autocorrect bar thisappears,['android'] +356182,resourcemanagergetstring method returns wrong string from different assemblies i have 2 resource files one with english and another foreign when i callresourcemanagergetstringhello from the designercs file it is always returning the english translation i have checked my locale and language etc and everything is correctit returns properly translated strings from my main assembly but from loaded assemblies it is always returning the english,['c#'] +356237,delete current preference screen and go back to main preference screen i have a preferenceactivity launched where i add some preference screens programmatically so i have a list with my preference screensexampletototititataso i iterate and call a function board is a custom objectprivate preferencescreen createpreferencescreenboard b preferencescreen p getpreferencemanagercreatepreferencescreenthis psetpersistenttrue psetkeypreferencescreen bgetid preferencecategory general new preferencecategorythis generalsettitlegeneral paddpreferencegeneral preference delete new preferencethis deletesettitledelete final preferencescreen pfinal p deletesetonpreferenceclicklistenernew preferenceonpreferenceclicklistener override public boolean onpreferenceclickpreference arg0 string delid boardgetid preferencecategory themes preferencecategory findpreferencethemes preferencescreen screen preferencescreenfindpreferencepreferencescreen delid themesremovepreferencescreen go back to preferenceactivity here or kill this screen return true generaladdpreferencedelete return pif i click on toto it opens the preference screen of toto and on this screen i have an option delete if i click on delete it removes this preference screen from the preferenceactivity the previous screen but i am still on the preference screen totoi would like to go back to the previous screen when i use deletei cannot use finish on my preference screen toto because it exits the appif i click on my back button i go back to the preferenceactivity previous screen and my toto preferences screen has been removed yata that function worked,['android'] +356292,jgit how to add all files to staging area i tried in a lot of ways to clone a repo with jgit it worksthen i write some archive in the repository and tried to add all a git add git add a or something like it but it do not work the files simple are not added to the staging areamy code is like this filerepositorybuilder builder new filerepositorybuilder repository repository buildersetgitdirnew filefolder readenvironmentfindgitdirsetupbuild clonecommand clone gitclonerepository clonesetbarefalsesetcloneallbranchestrue clonesetdirectoryfseturitestgit try clonecall catch gitapiexception e eprintstacktrace fileswritetesting it new filefolder test2txt charsetsutf 8 git g new gitrepository gaddaddfilepatterncallwhat am i doing wrongthanksexception while trying what with addfilepatternexception in thread main orgeclipsejgiterrorsnoworktrexception bare repository has neither a working tree nor an index at orgeclipsejgitlibrepositorygetindexfilerepositoryjava850 at orgeclipsejgitdircachedircachelockdircachejava264 at orgeclipsejgitlibrepositorylockdircacherepositoryjava906 at orgeclipsejgitapiaddcommandcalladdcommandjava138 at netciphersecgitgittestsmaingittestsjava110,['java'] +356308,how do i find a specific table in my edmx model quickly i was wondering if anyone knows a quicker way to find a table in the edmx model than just scrolling through the diagram and looking for the thing our database has around 50 tables in it and when i am looking for a specific one it is just a chore to see where vs put the thingi am using vs 2010 for the purpose of this questionthank you in advance,['c#'] +356326,quartznet how to create a daily schedule that does not gain 1 minute per day i am trying to build a repeating daily schedule in quartznet but having a few issuesfirst off i build a daily schedule repating at 1245using quartznet code like thisvar trigger triggerbuildercreate withdailytimeintervalschedules soneverydaystartingdailyatnew timeofday13 00buildvar times triggerutilscomputefiretimestrigger as ioperabletrigger null 10foreach var time in times consolewritelinetimethis is being executed in new zealand dst so utc1300and the output i get is rather strange5102012 10 pm 13005102012 120100 am 05102012 120200 am 05102012 120300 am 05102012 120400 am 05102012 120500 am 05102012 120600 am 05102012 120700 am 05102012 120800 am 05102012 120900 am 0the first datetime is thisplayed using local timezone then the rest are thisplayed with utc and each time value is incremented by 1 minute and the date never changesi feel like i might be missing something fundamental here with the daily time interval schedule but i just do not know what it iseditas an update to do this i have now switched to using a cron expression based triggertriggerbuildercreate withcronschedulestringformat0 0 1 0 13 buildand it gave me the results i would expect5102012 120 am 06102012 120 am 07102012 120 am 08102012 120 am 09102012 120 am 010102012 120 am 0102012 120 am 012102012 120 am 013102012 120 am 014102012 120 am 0but i would still like to know why the dailytimeintervale schedule is not working,['c#'] +356335,populating a database in a laravel migration file i am just learning laravel and have a working migration file creating a users table i am trying to populate a user record as part of the migrationpublic function up schemacreateusers functiontable tableincrementsid tablestringemail 255 tablestringpassword 64 tablebooleanverified tablestringtoken 255 tabletimestamps dbtableusersinsert array email verified true but i am getting the following error when running php artisan migratesqlstate42s02 base table or view not found 1146 table vantageusers does not existthis is obviously because artisan has not yet created the table but all the documentation seems to say that there is a way of using fluent query to populate data as part of a migrationanyone know how thanks,['php'] +356386,python requests and persistent sessions i am using the requests module version 0100 with python 25i have figured out how to submit data to a login form on a website and retrieve the session key but i cannot see an obvious way to use this session key in subsequent requestscan someone fill in the ellipsis in the code below or suggest another approach import requests login data formposted1 login email passwordpw r requestsposthttpslocalhostloginpy login data rtextuyou are being redirected a hrefprofilepage ck1349394964herea rcookiessession id myapp 127001825ff22a6ed1453baebc5d3cf2987065 r2 requestsgethttpslocalhostprofile datajson,['python'] +356391,assertion failure in dequeuereusablecellwithidentifierforindexpath so i was making an rss reader for my school and finished the code i ran the test and it gave me that error here is the code it is referring to uitableviewcell tableviewuitableview tableview cellforrowatindexpathnsindexpath indexpath static nsstring cellidentifier cell uitableviewcell cell tableview dequeuereusablecellwithidentifiercellidentifier forindexpathindexpath if cell nil cell uitableviewcell alloc initwithstyleuitableviewcellstylesubtitle reuseidentifiercellidentifier heres the error in the output20121004 201305356 reader4390c07 assertion failure in uitableview dequeuereusablecellwithidentifierforindexpath sourcecacheuikit simuikit2372uitableviewm4460 20121004 201305357 reader4390c07 terminating app due to uncaught exception nsinternalinconsistencyexception reason unable to dequeue a cell with identifier cell must register a nib or a class for the identifier or connect a prototype cell in a storyboard first throw call stack 0x1c91012 0x10cee7e 0x1c90e78 0xb64f35 0xc7d14 0x39ff 0xd0f4b 0xd101f 0xb980b 0xca19b 0x6692d 0x10e26b0 0x228dfc0 0x228233c 0x228deaf 0x1058cd 0x4e1a6 0x4ccbf 0x4cbd9 0x4be34 0x4bc6e 0x4ca29 0x4f922 0xf9fec 0x46bc4 0x47311 0x2cf3 0x137b7 0x13da7 0x14fab 0x26315 0x2724b 0x18cf8 0x1becdf9 0x1becad0 0x1c06bf5 0x1c06962 0x1c37bb6 0x1c36f44 0x1c36e1b 0x147da 0x1665c 0x2a02 0x2935 libcabidylib terminate called throwing an exceptionand heres the code it shows in the error screenint mainint argc char argv autoreleasepool return uiapplicationmainargc argv nil nsstringfromclassappdelegate class please help,"['ios', 'objective-c', 'iphone']" +356399,how to group mysql inner join results from rows into columns maybe my question is not so clear please let me explainwhat i need is to get a list of all users along with a corresponding client numberwholesaler combination every client has 1 up to 4 different client numberwholesaler comboin my db i have 2 tablesusersid name1 a2 bclient numbersid user id number wholesaler1 1 ac1 aw12 1 ac2 aw23 2 bc1 bw1using a simple inner join i got client rows duplicated one for each corresponding client numberwholesaleri have managed to fix the results using group concat in this queryselect aid as user id aname as name group concatbclient no bwholesaler separator as client no wholesaler from users as a inner join client numbers as b on aid buser id group by iduser id name client no wholesaler1 a ac1 aw1 ac2 aw2 2 b bc1 bw1so far so good but i need to explode the client numberwholesaler combination into different columns so my results can look like thisuser id name client no wholesaler1 client no wholesaler2 up to 41 a ac1 aw1 ac2 aw2 2 b bc1 bw1 doing this after getting the query results with a simple php explode is not an option because i am using a class to generate a xls file and its based on my query result columns any ideas will be appreciated,['mysql'] +356451,turbolinks issues with bootstrap modal i doing a modal like thislink that shows the modal link to versao resumida resumed rep life animal pathanimal partial true datatoggle modal datatarget mymodal datanoturbolink true modal html itselfdiv classmodal hide fade idmymodal tabindex1 roledialog arialabelledbymymodallabel ariahiddentrue div classmodalbodydiv div classmodalfooter button classbtn btnprimary datathismissmodal ariahiddentruefecharbutton divdivbut the datanoturbolink dont work as expected if i refresh the page it works ok but when i browse the pages with turbolinks looks like the datanoturbolink is just ignoredam i doing something wrong i have some modals like the example in my app do not want to remove them and dont want to remove turbolinks neitherthanks in advance,['ruby-on-rails'] +356471,how to check for slowlow network in ios app can anyone suggest how to handle a slow network when streaming video in a web viewwhen the network strength is poor a blank screen appears or video does not streamis there a way to detect this condition so that we can alert the user apart from using private api,['ios'] +356529,c hyperlink in textblock nothing happens when i click on it in my c standalone application i want to let users click on a link that would launch their favorite browsersystemwindowscontrolstextblock text new textblockrun run new runlink texthyperlink link new hyperlinkrunlinknavigateuri new uritextinlinesaddlinkthe link is thisplayed correctlywhen i move the mouse over it the link becomes redproblem when i click it nothing happensdid i forget something do i need to implement some kind of method to really let the link be opened,['c#'] +356532,retrieving a nested object inside a json string using rapidjson i need to retrieve a nested object inside a json string and i am trying to do it using rapidjson all i have found is how to retrieve arrays and basic types but not subobjects i have created the following toy example which gives an errorrapidjsondocument documentstdstring test a z 21 stdcout test stdendlif documentparse0 testc str hasparseerror stdcout parsing error stdendl else if document a isobject stdcout ok stdendl stdcout document a getstring stdendl this is the output when executed a z 21 okjsontest rapidjsondocumenth441 const typename encodingch rapidjsongenericvalueencoding allocatorgetstring const with encoding rapidjsonutf8char allocator rapidjsonmemorypoolallocatorrapidjsoncrtallocator assertion isstring failed abortedhow do i retrieve the inner object to continue my parsing thanksedit what i need is to obtain the string representation of the inner object so i can call another function that is going to parse itedit 2 code that allows to retrieve the inner object as a stringrapidjsondocument documentstdstring test az21 if documentparse0 testc str hasparseerror stdcout error parsing stdendl else if document a isobject rapidjsonstringbuffer sb rapidjsonwriterrapidjsonstringbuffer writer sb document a accept writer stdcout sbgetstring stdendl,['c++'] +356613,unable to compile using java 17 in jetbrains intellij after moving from 16 to 17 maven based project using jetbrains 112 project based on a maven project then i required to move to 17 i have 17 installed i updated my pomxml and i can rebuild the whole package using maven okayi have modified every setting i can see in intelli projects settings regarding java version project sdk project language levelmodules languagessourceslanguage levelmodules languagesdependenciesmodule sdkbut i cannot get it to compile a file it complainserrorjavac target release of 16 conflicts with source release 17i then tried on my other dev machine using the same codebase but a different intellij project and on this i get a similar errorerrorjavac source release 17 requires target release 17i cannot see anything else to change in order to get this working,['java'] +356627,how to remove null values from an array using jquery possible duplicateremove empty elements from an array in javascript i want to remove null or empty elements from an array using jqueryvar clientname new arrayclientname0 jackclientname1 clientname2 johnclientname2 peterplease give some suggestions,['jquery'] +356641,rails define a unique primary key based on 2 columns i would like to define a unique key for records based on 2 columns id and languageto let the user submits the following strings id1 languageen valueblabla english id1 languagefr valueblabla frenchi tried to use set primary key and also add index but it did not work add index words id language id unique true i have the following model class word activerecordbase belongs to dictionnary belongs to language attr accessible lang rev value dictionnary id language id validates value uniqueness trueend and thisclass language activerecordbase has many words attr accessible langend,['ruby-on-rails'] +356684,creating a search form in php to search a database i am currently trying to complete a project where the specifications are to use a search form to search through a packaging database the database has lots of variables ranging from sizes names types and meats i need to create a search form where users can search using a number of different searches such as searching for a lid tray that is 50 cm long i have spent all day trying to create some php code that can search for info within a test database i created i have had numerous amounts of errors ranging from mysql fetch array errors boolean errors and now currently my latest error is that my table does not seem to exist although i can enter data into it html and php pages where i can enter data i do not know what is causing this and i have started again a few times now can anyone give me some idea or tips of what i am going to have to do currently here is just my small tests at the moment before i move onto the actual sites sql database creation of database body php con mysql connectlocalhost root if con diecould not connect mysql error if mysql querycreate database db test con echo database created else echo error creating database mysql error mysql select dbdb test con sql create table liam code varchar 30 description varchar 30 category varchar 30 cutsize varchar 30 mysql querysql con mysql closecon bodyhtml search form page body form actionformphp methodpost search input typetext nameterm br input typesubmit namesubmit valuesubmit formbodythe php code i am using to attempt to gather info from the databasei have rewritten this a few times this code also thisplays the tableliam does not exist body php con mysql connect localhost root mysql select db db test con if con die could not connect mysql error sql mysql queryselect from liam where description like term or die mysql error while row mysql fetch arraysql echo primary key rowprimarykey echo br code rowcode echo br description rowdescription echo br category rowcategory echo br cut size rowcutsize mysql closecon bodyif anyone has any insight or can help me with this i would be very grateful thanks in advance,"['php', 'html', 'mysql', 'sql']" +356769,programatically close win8 app i have begun tinkering with making windows 8 apps and i want to make an exit buttonthe problem is that environmentexit and thisclose that i would use in winforms is not in scope here anyone know how to close the app programatically,['c#'] +356770,best practices for inline sql queries i am working with an aspnet website that uses a lot of inline sql queries and i am wondering if it is best to create the inline queries on the flyint i 500 using sqlconnection conn new sqlconnectionconnstr sqlcommand com new sqlcommandconn comcommandtext select from table where column parameter or to have a class to hold all queries needed for the application something like thisclass sqlqueries private string query1 select from tblemployees where employeename employeename private string query2 select from tblvacation where employeename employeename public string querystring s string str stringempty switch s case query1 str query1 break case query2 str query2 break return str thank you,"['c#', 'asp.net']" +356828,how to create a c template to pass a value in the best way i seem to remember i way to select valuepass or referencepass of a parameter using the size of the typesomething likevoid fun checka a generates orvoid fun a a orvoid fun a a depending of the size of type a and the architecture where you compile the applicacion,['c++'] +356835,gradle war task has conflicting includesexcludes i am trying to build a war file with gradle but i am having an issue excluding one directory and including another that happen to have the same names but different parent directories please notice in the first code example below that neither of the css directories are being included in the final war file i assume because gradle thinks that i want to exclude any directory named css regardless of its absolute pathbasically i want to exclude srcmainwebappcss and include buildtmpcss because the latter contains the minified code how can i achieve this i have tried specifying an absolute path in various ways but have not had any successwar dependson minify frombuildtmp include css excludewebinfclasses cssif i do not exclude css like sowar dependson minify frombuildtmp include css excludewebinfclassesthen the result is that both the minified and nonminified code is included,['java'] +356848,drupal form api dynamically hide or show fields based on input i am building a form module one of the early fields is a set of radio buttons by default the first button is selected next i will have a series of select boxes one needs to be visible the others invisible then as the user selects a different radio button i want different select boxes to show or hide how can i hide the field and label by default and show it later dependent upon which radio button or another select box option for that matter is chosen,['php'] +356866,sqlalchemy mixins and event listener i am attempting 2 new things at once so assistance in both simplifying and clarifying is appreciatedfrom sqlalchemyextdeclarative import declared attrfrom sqlalchemy import column float eventclass timestampmixinobject declared attr def tablename cls return cls name lower created columnfloat modified columnfloat def init self created none modified none selfcreated created selfmodified modifieddef create timemapper connection target targetcreated timedef modified timemapper connection target targetmodified timeeventlistentimestampmixin before insert create timeeventlistentimestampmixin before update modified timeso i want to create a mixin i can apply in any classclass myclasstimestampmixin base etc etc etcthis class inherits functionality that creates a timestamp on creation and createsmodifies a timestamp on updateon import i get this errorraise excunmappedclasserrorclass sqlalchemyormexcunmappedclasserror class dbdatabasetimestampmixin is not mappedand i am stumped at this point,['python'] +356869,push notifications on android google gcm vs amazon sns my android app needs simple push notifications to be informed about the appearance of new data on a server android provides google cloud messaging gcm which would seem to fithowever devices running lower than android 404 require a google account to be present on the phone per google platform stats as of 1012012 this is currently about 75 of android phones and it does not seem to be a good experience to be asking users to set up a google account in the middle of an unrelated application activityare there any suggestions for a more universal push mechanism that can be used on the android platform for example what are the pros cons of amazon sns any other candidates,['android'] +356878,how do i fix the error the currentthread needs to have its apartmentstate set to apartmentstatesta to be able to initiate internet explorer i have the following code in c namespace tests setupfixture requiressta public class setup public ie window new iewebpage setup public void setup teardown public void teardown when i try to run it with my website it returns the error the currentthread needs to have its apartmentstate set to apartmentstatesta to be able to initiate internet explorernormally when using anything except setupfixture requiressta it the solution but for some reason it is not working now,['c#'] +356884,adtlike polymorphism in java without altering class in haskell i can define following data type data tree empty leaf int node tree treeand then write polymorphic function like this depth tree intdepth empty 0depth leaf n 1depth node l r 1 max depth l depth rin java i can emulate algebraic data types with interfaces interface tree class empty implements tree class leaf implements tree int n class node implements tree tree l tree r but if i try to use haskelike polymorphism i get an error int depthempty node return 0int depthleaf node return 1int depthnode node return 1 mathmaxdepthnodel depthnoder error cannot resolve method depthtreecorrect way to overcome this is to put method depth to each class but what if i do not want to put it there for example method depth may be not directly related to tree and adding it to class would break business logic or even worse tree may be written in 3rd party library that i do not have access to in this case what is the simplest way to implement adtlike polymorpism just in case for the moment i am using following syntax which is obviously illfavored int depthtree tree if tree instanceof empty depthemptytree if tree instanceof leaf depthleaftree if tree instanceof node depthnodetree else throw new runtimeexceptiondo not know how to find depth of treegetclass,['java'] +356885,is there any difference between backgroundclip and backgroundorigin the css3 declarations backgroundclip and backgroundorigin seem to have the same effect on the background they both appear to restrict the background to a certain area relative to the html element so i was wondering if there really is a difference in function of these two declarations,['html'] +356900,mysql update case whenthenelse i am trying to update a large myisam table 25 million records using a cli script the table is not being lockedused by anything elsei figured instead of doing single update queries for each record i might as well utilize the case featurethe id field is primary i suspect the following query should take millisecondsupdate table set uid case when id 1 then 2952 when id 2 then 4925 when id 3 then 1592 endlo and behold the query hogs the cpu and does not finish in foreverthen to my surprise i found out that the query is updating all the 25 million rows placing a null on rows that i did not specifywhat is the purpose of that can i just do a mass update on specific rows without updating 25 million rows every time i execute this query or do i have to do individual updates and then commit,['mysql'] +356906,modulo operator in python what does modulo in the following piece of code dofrom math import 314 2 pihow do we calculate modulo on a floating point number,['python'] +356932,jpa persisting a unidirectional one to many relationship fails with eclipselink i am trying to persist a very simple unidirectional one to many relationship but eclipselink 231 fails is this a bug or just a stupid mistake my code is very simpleservice class parententitytablename tbl service2public class service implements serializable id generatedvaluestrategy generationtypeidentity columnnameservice id public long serviceid columnnamename public string name onetomanycascadecascadetypeall joincolumnnameservice id referencedcolumnnameservice id public setparameter parametersparameter class childof course there is service id foreign key field in the database which is not represented in the class as it is unidirectional relationentitytablename tbl service parameters2public class parameter implements serializable id generatedvaluestrategy generationtypeidentity columnnameparam id public long parameterid columnnamename public string nameand this is the code service service new service serviceparameters new hashsetparameter servicename test parameter param new parameter paramname test serviceparametersaddparam empersistservice emflushi get this excaptioninternal exception javasqlsqlexception field service id does not have a default valueerror code 1364call insert into tbl service parameters2 name values bind testedit the database field service id has and should have notnull constraint due the nature of the data,['java'] +356994,c arrays string vs string possible duplicatewhat is differences between multidimensional array and array of arrays in c can anybody explain me the difference between string and string,['c#'] +357012,rails bootstrapsass redefineoverload mixins with bootstrapsass you can overload variables by defining them before importing bootstrap as in documentationbtnprimarybackground f00import bootstrapsadly it does not work with mixins since in sass they can be redefined overloadedwhat would be the best approach to overload a twitter bootstrap mixins so far the only way to do it seems to clone the gem in lib and add modify mixinsscss or include my custom mixinsscss afterany idea to make this more maintainable,['ruby-on-rails'] +357017,pyopengl passing transformation matrix into shader i am having trouble passing projection and modelview matrices into the glsl shader from my pyopengl code my understanding is that opengl matrices are column major but when i pass in projection and modelview matrices as shown i do not see anything i tried the transpose of the matrices and it worked for the modelview matrix but the projection matrix does not work either way here is the codeimport openglfrom openglgl import from openglglshaders import from openglglu import from openglglut import from openglglutfreeglut import from openglarrays import vboimport numpy math sys strvs attribute vec3 avertuniform mat4 umvmatrixuniform mat4 upmatrixuniform vec4 ucolorvarying vec4 vcolvoid main option 1 fails gl position upmatrix umvmatrix vec4avert 10 option 2 works gl position vec4avert 10 set color vcol vec4ucolorrgb 10strfs varying vec4 vcolvoid main use vertex color gl fragcolor vcol 3d sceneclass scene initialization def init self create shader selfprogram compileprogramcompileshaderstrvs gl vertex shader compileshaderstrfs gl fragment shader gluseprogramselfprogram selfpmatrixuniform glgetuniformlocationselfprogram upmatrix selfmvmatrixuniform glgetuniformlocationselfprogram umvmatrix selfcoloru glgetuniformlocationselfprogram ucolor attributes selfvertindex glgetattriblocationselfprogram avert color selfcol0 10 10 00 10 define quad vertices s 02 quadv s s 00 s s 00 s s 00 s s 00 s s 00 s s 00 vertices selfvertexbuffer glgenbuffers1 glbindbuffergl array buffer selfvertexbuffer vertexdata numpyarrayquadv numpyfloat32 glbufferdatagl array buffer 4lenvertexdata vertexdata gl static draw render def renderself pmatrix mvmatrix use shader gluseprogramselfprogram set proj matrix gluniformmatrix4fvselfpmatrixuniform 1 gl false pmatrix set modelview matrix gluniformmatrix4fvselfmvmatrixuniform 1 gl false mvmatrix set color gluniform4fvselfcoloru 1 selfcol0 enable arrays glenablevertexattribarrayselfvertindex set buffers glbindbuffergl array buffer selfvertexbuffer glvertexattribpointerselfvertindex 3 gl float gl false 0 none draw gldrawarraysgl triangles 0 6 thisable arrays glthisablevertexattribarrayselfvertindex class renderer def init self pass def reshapeself width height selfwidth width selfheight height selfaspect widthfloatheight glviewport0 0 selfwidth selfheight glenablegl depth test glthisablegl cull face glclearcolor08 08 0810 glutpostrethisplay def keypressedself args sysexit def drawself glcleargl color buffer bit gl depth buffer bit build projection matrix fov mathradians450 f 10mathtanfov20 zn zf 01 10 a selfaspect pmatrix numpyarrayfa 00 00 00 00 f 00 00 00 00 zfznznzf 10 00 00 20zfznznzf 00 numpyfloat32 modelview matrix mvmatrix numpyarray10 00 00 00 00 10 00 00 00 00 10 00 05 00 50 10 numpyfloat32 render selfscenerenderpmatrix mvmatrix swap buffers glutswapbuffers def runself glutinitthisplaymodeglut rgba glutinitwindowsize400 400 selfwindow glutcreatewindowminimal glutreshapefuncselfreshape glutthisplayfuncselfdraw glutkeyboardfuncselfkeypressed checks for key strokes selfscene scene glutmainloopglutinitsysargvprog rendererprogrunwhen i use option 2 in the shader without either matrix i get the following outputwhat am i doing wrong,['python'] +357024,minimal example of using select for update to isolate rows i want concurrent transactions to select a row from the table marking it as dirty so that other transactions cannot select it then performing the rest of the transactioni had trouble using select for update for this purpose as the second transaction contends for the same please provide a minimal example for different transactions to select thistinct rowsmy data ismysql select from solrcorespreallocated id used status sid cid 1 0 0 400 2 0 0 401 3 0 0 402 4 0 0 403 5 0 0 404 6 0 0 405 6 rows in set 0 secand this stuff is not working as expectedmysql beginquery ok 0 rows affected 0 secmysql select from solrcorespreallocated order by id limit 1 for update id used status sid cid 1 0 0 400 1 row in set 0 secset the used status to 1perform the rest of the operationsas the second transaction onwardmysql beginquery ok 0 rows affected 0 secmysql select from solrcorespreallocated order by id limit 1 for updateerror 1205 hy0 lock wait timeout exceeded try restarting transactionmysql rollbackquery ok 0 rows affected 0 sec,['mysql'] +357046,should i use lvalue reference qualifiers for assignment operators recently i have followed a thiscussion about assignments to expressions in c as shown in the following examplestring s1 s2 s3s1 s2 s3with c11 it is possible to restrict the assignment operator to lvalue references on the left side when declaring the assignment operators as follow the compiler clang rejects the code with an error message due to incompatible typesauto operatorconst string rhs stringauto operatorstring rhs stringi have not seen this anywhere is there a good reason for not using lvalue reference qualifiers for assignment operators besides missing support in most compilers,['c++'] +357059,does using design patterns makes java code slow does using design patterns makes java code slow if i use extra interfaces and syntax constructions like class wrap will i get well organized but slow code or that would not make my code significantly slower,['java'] +357129,get the maximum value of a variable in c is there a function in c that returns the maximum value of a variable like this i will name the function maxvalue in example belowint aprintfd maxvaluea 32767unsigned int bprintfd maxvalueb 65535so basically the function returns values like int max when the variable is signed int uint max when unsigned int etc,['c'] +357146,example of javascript duck typing some programmers advise against using pseudo classical inheritance in javascript but advise using ducktyping and giving each object a set of capabilitiesis there a good example of how that is done i have an example down below but it only assign function one at a time can we assign a whole group of methods to an object such as can we set a prototype of oceananimal which can swim dive and rise a prototype of landanimal for run walk and jump and let an object inherit from one or both of them so a fish object can inherit or get the capabilities of oceananimal and a turtle can get the capabilities of both oceananimal and landanimalvar yoyo name yoyo type turtlevar simba name simba type lionvar dolphy name dolphy type dolphinfunction swimn consolelogmy name is thisname i am a thistype and i just swam n feetfunction runn consolelogmy name is thisname i am a thistype and i just ran n feetobjectprototyperespondto functionmethod return thismethod typeof thismethod functionyoyoswim swimyoyoswim10dolphyswim swimdolphyswim80simbarun runsimbarun200yoyorun runyoyorun2yoyowalk runyoyowalk1consolelogsimbarespondtoswimconsolelogsimbarespondtorunconsolelogsimbarespondtowalkconsolelogyoyorespondtorunconsolelogyoyorespondtowalkconsolelogyoyorespondtoflyifdolphyrespondtorun dolphyrun10ifdolphyrespondtoswim dolphyswim10outputmy name is yoyo i am a turtle and i just swam 10 feet my name is dolphy i am a dolphin and i just swam 80 feet my name is simba i am a lion and i just ran 200 feet my name is yoyo i am a turtle and i just ran 2 feet my name is yoyo i am a turtle and i just ran 1 feet false true false true true false my name is dolphy i am a dolphin and i just swam 10 feet,['javascript'] +357189,zf2 how to use the hydratorexchangearray to populate a nested object i have got an object with values that are stored in my database my object also contains another object which is stored in the database using just the id of it foreign keybefore the hydratorexchangearray functionality in zf2 you would use a mapper to grab everything you need to create the object now i am trying to eliminate this extra layer by just using hydrationexchangearray to populate my objects but am a bit stuck on creating the nested objectshould my entity have the inner objects table injected into it so i can create it if the id of it is passed to my exchangearray here are example entities as an example villageid name position square id map squareid name typeupon sending square id to my villages exchangearray function it would get the maptable and use hydrator to pull in the square using the id i haveit does not seem right to be to have mapper instances inside my entity as i thought they should be thisconnected from anything but it is own entity specific parameters and functionality,['php'] +357218,getting full property name using modelmetadata i am trying to create an htmlhelper that will create bootstrapcompatible form fields my first goal was to create an htmlhelper that will create the surrounding divdiv classcontrolgroup divfollowing the excellent advice here and also here i managed to get it to work relatively quickly but it does not always worki have a viewmodel with a complex property so in my form i access the field mmcomplexelement in my helper i check the element for validation errors i use modelmetadatafromlambdaexpressionexpression htmlviewdata the metadata i get back has the property name element and not complexelementwhen i check the modelstate for this property i cannot find it because the modelstate keeps the full name complexelementi can look for partial matches hoping there is no other element but that seems like a nasty bug waiting to happen how can i get the full property name from the expression,['c#'] +357226,how to store ruby code blocks i want to store a code block in a variable to be reused something likeblock dotest puts testend3upto8 blockcan someone show me what am i doing so obviously wrong or if it is just impossible,['ruby'] +357233,integer to boolean conversion in count method 1 1 1 2 2 3counttrue 3why does this return 3 instead of 6 if booli returns true for all values i not equal to 0,['python'] +357259,how can i create a custom uiactivity in ios how can i create a custom uiactivity in ios the reason i want this is to add a review app button in one of my apps that takes the user to the review section in the app store how can i create such a custom uiactivity,"['ios', 'objective-c']" +357269,get and least significant bits from an int this seems fairly straightforward but i cant find an answer if i have an int x what is the best way to get and least significant bits from this int in java,['java'] +357277,native typeface cannot be made only for some people i have an app that changes the font typeface for some elements it works well for most of the people but maybe a 05 get an exception when trying to change the font the significant part of the stack trace is thiscaused by javalangruntimeexception native typeface cannot be madeat androidgraphicstypefaceinittypefacejava147at androidgraphicstypefacecreatefromassettypefacejava121as i say it works for most of the people so i do not think it is a problem with the font file or my code any suggestions about how to solve thisedit this is my codetypeface phoneticfont typefacecreatefromassetgetassets fontscharissilrttftextview tvtv textview findviewbyidridsearchpronunciationtitletvsettypefacephoneticfont,['android'] +357298,sort dict in jinja2 loop i am still learning jinja2 and flask and i am having a difficulty using dictsort in jinja2so i am passing this dict into a jinja2 templatepedd united id 37828 rank 12 totalpts 307fc mbonabushia id 205633 rank 6 totalpts 356fc slurp id 933573 rank 11 totalpts 312kfc overijse id 38861 rank 5 totalpts 362fc paris id 1538051 rank 2 totalpts 396what i want is create a table that is sorted by the value of the key totalpts i tried all sort of things and it just does not take totalpts into account when sortingheres one of my code table classtable tablebordered for team in league tr tdteamtd for data in leagueteamdictsortleagueteamtotalpts td leagueteamtotalpts td endfor tr endfor tableby it does not sort anything in this case just print the value in the table without any orderanyone can help me outthanks,['python'] +357357,why is char not compatible with signed char or unsigned char i have found that the c99 standard have a statement which denies the compatibility between the type char and the type signed charunsigned charnote 35 of c99 standardchar min defined in limitsh will have one of the values 0 or schar min and this can be used to thistinguish the two options irrespective of the choice made char is a separate type from the other two and is not compatible with eithermy question is that why does the committee deny the compatibility what is the rationale if char is compatible with signed char or unsigned char will something terrible happen,['c'] +357402,flask requestremote addr is wrong on webfaction and not showing real user ip i just deployed a flask app on webfaction and i have noticed that requestremote addr is always 127001 which is of course is not of much usehow can i get the real ip address of the user in flask on webfactionthanks,['python'] +357420,best way of creating and using an anonymous runnable class i want to use anonymous class for runnable there are two way but i do not know if they do the same thing or not method one using directly runnable and call runnew runnable override public void run runmethod two create an anonymous runnable and paste to thread using start method instead of run new thread new runnable override public void run starti think method two is obvious true but i do not know if it does the same as method one can we call run method on runnable directly thanks,['java'] +357445,whats is the difference between actionbar and tabhosttabactivity quick question whats the difference between actionbar and tabhost i used to use tabhost and add tabs to itthen i was asked to use actionbar and reading about it it seems it is just another way of having tabs so when would use each whats the differencethank you,['android'] +357534,how do i create a new swing app in intellij idea community edition i have created a new project using the create new project wizard by choosing create project from scratch but it is completely empty no java classes at all so i manually created a new swing form inside the empty project in many other ides i have used there is a way to click once and get a new new gui project and i usually expect it in the file new project wizard or something comparablethere is a new project wizard in the intellij idea ide but it only seems it can create a blank project and then i can manually add a form to it so i did that but then that lacks any of the usual java code that you would expect it to have to open up that form and show it as an application i am trying to understand the features and capabilities of intellij idea and it seems strong as a very fast and efficient editor and debugger and build system gui wrapper around the ant build system but i was wondering if there are more rad features that i have merely overlooked i have done a bit of googling and reading the docs but i have not found much about using intellij idea to build a gui application in javawhere i am currently stuck is when i tried to build and run my empty project with an empty form in it and i get to some kind of run target configuration screen and i tried clicking the icon and adding myform01 which is the empty swing form i created and it says in a dialog box myform01 is not acceptable i know enough java to know that the basic gui app skeleton code is not being autogenerated by the ide i could go and copy and paste something from the internet but my interest here is in knowing whether the tool can automatically be used to build a gui with a workflow as simple as other radstyle gui builder tools including netbeans which is the java tool i am most comfortable using or delphi which is my main everyday tool which is pascal based rather than java,['java'] +357584,sample code to create pdf programmatically i am new to iphoneis there any sample code or tutorialalso need a sample code for plistplease help me,"['iphone', 'objective-c', 'ios']" +357609,how can i join an array of strings but first remove the elements of the array that are empty i am using the followingreturn stringjoinn partsparts has 7 entries but two of them are the empty string how can i first remove these two entries and then join the remaining five,['c#'] +357661,magento how to check if the shopping cart is empty or not i am trying to check if the shopping cart is empty or noti am trying to do this from a static block and from a phtml fileanyone know how to do thisthanks in advance,['php'] +357665,fastest way to find minimum thistance of one point to points on a curve i am looking for a fast solution for the following problemi have a fixed point let us say the upper right on the white measurement line and need to find the closest point on a curve made of equally spaced points the lower curve additionally i do this for every point on the upper curve to draw the thistances between the curves with different colours three levels below minimum red between minimum and maximum orange and above maximum greenmy current solution is a tradeoff i take the fixed point iterate through an arbitrary interval e g 50 units to the left and right of the fixed point and calculate the thistance of each pair this saves some cpu power but it is neither elegant nor accurate since i could miss a minimum thistance outside my chosen interval any proposals for a faster algorithmedit equally spaced means all points have the same thistance on the xaxis this is true for both curves also i do not need to interpolate between the points this would be too time consuming,['c'] +357713,cannot make startactivity with chooser asking just once per app when you do startactivity with chooser android would list all apps entitled to handle your intent along with options to set this assignment permanent or oncetime on ics its always and just once action button on 2x it is checkbox however for this codepublic class redirector public static void showactivitywithchooser context context int chooserlabeltitleid intent intent try contextstartactivity intentcreatechooser intent contextgetresourcesgetstring chooserlabeltitleid catch exception e eprintstacktrace public static void viewinexternalapplication context context string url intent intent new intent intentaction view intentsetdata uriparse url intentaddflags intentflag activity clear when task reset showactivitywithchooser context rstringopen chooser title intent i see no alwaysjust once buttons and cannot make my selection permanent i got apps listed only and can fire any by tapping it what elementary i overlooked that made android unable to make user choice persistentsee the pics left dialog is what i would like to see but right is what i get now different number of applications in both dialogs is irrelevant,['android'] +357751,make maven parent project test all modules before deploying any of them i have a traditional maven setup with parent project and a number of modules what are subprojects when i do mvn deploy it runs the full lifecycle including test up to deploy for each project in sequence depthfirst i would like to avoid deploying any subprojects if any of projects fails to build in other words i would like the deploy of the whole parent project to be all or nothing is there any way to achieve this,['java'] +357778,is there a way to register a search result callback when using google cse v2 in version one v1 of googles custom search engine code there was a method called setsearchcompletecallback which would allow you to call some javascript when the search results had returned the documentation for that code can be found herethe search engine object has been moved from googlesearchcustomsearchcontrol in v1 to googlesearchcseelement in v2the current version v2 does not seem to have the setsearchcompletecallback method and i cannot see a way to register a callback for when the search results are finished i have experimented to varying degrees of success with jquerys ajaxstart and ajaxend methods but i wondered if there was an official way to do this built into the google cse code,['javascript'] +357819,parallelfor and break misunderstanding i am investigating the parallelism break in a for loopafter reading this and this i still have a questioni would expect this code parallelfor0 10 istate consolewritelinei if i 5 statebreak to yield at most 6 numbers 06not only he is not doing it but have different result length 023514860135420135642very annoying where the hell is break after 5 here so i looked at msdnbreak may be used to communicate to the loop that no other iterations after the current iteration need be run if break is called from the 100th iteration of a for loop iterating in parallel from 0 to 10 all iterations less than 100 should still be run but the iterations from 101 through to 10 are not necessaryquesion 1 which iterations the overall iteration counter or per thread i am pretty sure it is per thread please approvequestion 2 lets assume we are using parallel range partition due to no cpu cost change between elements so it divides the data among threads so if we have 4 cores and perfect divisions among them core 1 got 0250core 2 got 251500core 3 got 501750core 4 got 75110so the thread in core 1 will meet value100 sometime and will breakthis will be his iteration number 100 but the thread in core 4 got more quanta and he is on 900 now he is way beyond his 100th iterationhe doesnt have index less 100 to be stopped so he will show them allam i right is that is the reason why i get more than 5 elements in my example question 3 how cn i truly break when i 5 psi mean come on when i do break i want things the loop to stopexcactly as i do in regular for loop,"['c#', '.net']" +357844,how can you add query parameters in the zf2 url view helper i am attempting to create a url with a query string using a route like sothisurlusers usersthisurlusers sort desc userssortdeschowever this does not seem to work the second helper actually outputs users according to this unofficial outofdate documentation there was once a way to do this by appending query to the route name however this gives a routenotfound exceptioncan this be done using the current url helper,['php'] +357893,array size not static can someone please explain to me why this works i thought arrays were static and could not expand this piece of code defies my prior knowledgeinclude iostreamusing namespace stdint main int test10 int e 14forint i 0 i e i testi i cout testi return 0this code outputs this 0 1 2 3 4 5 6 7 8 9 10 11 12 13so basically this program uses array spaces that should not existtried setting e as 15 does not work,['c++'] +357904,using thistinct and then an aggregate function in postgresql this is a pretty basic problem and for whatever reason i cannot find a reasonable solution i will do my best to explainsay you have an event ticket section row seat each ticket belongs to an attendee multiple tickets can belong to the same attendee each attendee has a worth ex attendee 1 is worth 10 that said heres what i want to do1 group the tickets by their section2 get number of tickets count3 get total worth of the attendees in that sectionheres where i am having problems if attendee 1 is worth 10 and is using 4 tickets sumattendeesworth is returning 40 which is not accurate the worth should be 10 yet when i make the result thistinct on the attendee the count is not accurate in an ideal world it would be nice to do something likeselect ticketssection counttickets as count sumthistinct on attendeesid attendeesworth as total worth from tickets inner join attendees on attendeesid ticketsattendee id group by ticketssectionobviously this query does not work how can i accomplish this same thing in a single query or is it even possible i would prefer to stay away from sub queries too because this is part of a much larger solution where i would need to do this across multiple tablesalso the worth should follow the ticket divided evenly ex 10 4 each ticket has an attendee worth of 50 so if the tickets are in different sections they take their prorated worth with themthanks for your help,['sql'] +357908,visual studio 2012 network shares i emulate windows 8 on a vm using parallels i store all of my developer projects on my macs partition for simplicity and coherencewhen i try to build an app visual studio 2012 running off this network share i get the following compiletime errorerror 1 error dep0700 registration of the app failed rejecting a request to register from filezusersmy user namesitesapp1app1bindebugappxappxmanifestxml because the files are on a network share copy the files to the local computer before registering the package 0x80073cf9 app1does anyone know how to solve this issue i need to tell visual studio 2012 that my network share is a trusted device or at least dupe it into thinking the project is in a local drive is there anyway to create symbolic links in windowsin visual studio 2010 i solved this issue as outlined on this website thanks for the help,['c#'] +357909,hover on element and highlight all elements with the same class i have many elements with the same class on a web page i would like to highlight all these elements when i hover one of them how can i do that in cssright now i have this csspunhover backgroundcoloryellowand my htmldiv classbook div classpage left p classunkarenap div div classpage right p classunkaren ne se retourne pas mme tilford reste la apparemment confuse et abattuep div,['css'] +357926,jquery windowheight function does not return actual window height i have a page that i need to dynamically load ajax content when the user scrolls to the bottom the problem is that jquery is not returning the correct window height i have used this function before and have never seen it fail but for some reason it will return the same value as the document height i have the test page here bangstylecomtestimagesi have coded the alert to thisplay at page load and also whenever the user scrolls 500px below the topfunction scroller ifwindowscrolltop 500 delayfunction 200ms wait pagecounter sideshow alertwindow height windowheight scrolltop windowscrolltop document height documentheight return false 200 i tried posting this before but i deleted it as i did not get a solution i hope it is ok to post a link to my test page btw i have tested this on mac safari and mac ff i have run this same code on other pages and it works fine i feel there must be something in the dom of this page that causes js to fail but no idea what that would be,"['javascript', 'jquery']" +357934,finding the index of and biggest elements in python array list efficiently i am sorry in advance if this is a duplicated question i looked for this information but still could not find itis it possible to arrange a numpy array or python list by using the indexes of the and biggest elements in decreasing order very efficientlyfor instance the arraya array4 1 0 8 5 2the indexes of the biggest elements in decreasing order would give considering and 6 all the elements are included8 35 44 02 51 10 2result 3 4 0 5 1 2i know how to make it using a somewhat silly approach like sorting the array and searching for each of the and numbers for their indexes but i was wondering if is there any efficient library like bottleneck or heapq or maybe a pythonic approach to make this very fast i have to apply it in several arrays with 300k elements each so that is why performance is an issuethanks in advanceupdatei read the answers and decided to timeit them using a 300k of random integers here are the resultssolution 1 sortedrangelena keylambda iai time 230 mssolution 2 heapqnlargestlena zipa itertoolscount time 396 mssolution 3 heapqnlargestlena enumeratea keyoperatoritemgetter1 time 864 mssolution 4 def fan return npargsorta1n n lena time 104 msthanks a lot for the fast and very good answers,['python'] +357988,sql server table type clash operand i have a the same table type defined in two diferent database schemas when i try to call a sp from one schmema to another passing the type as parameter i got the folowing erroroperand type clash mycustomtype is incompatible with mycustomtypethe idea is aproximatly thesethe type definitioncreate type mycustomtype as tablesomevalue int somevalue2 intthe stored procedure definitionuse db1gocreate proc1 myvar mycustomtype readonlyasbegin exec db2dboproc2 myvarendgouse db2gocreate proc2 myvar mycustomtype readonlyasbegin do something with myvar endthe executionuse db1godeclare myvar mycustomtypeinsert into myvar12exec proc1 myvarhow can i fix this problem,['sql'] +357999,criteria eager fetchjoined collection let us say item and bid are entities an item has many bids they are mapped in hibernate 3610 in a typical parentchild relationshipclass nameitem tableitem set namebids inversetrue key columnitem id onetomany classbid setclasshow can i avoid n1 selects when trying to access the bids of each item after this query is executedlistitem items sessioncreatecriteriaitemclass createaliasbids b addrestrictionsgtbamount 100 listnote i need an eager fetching for bids but with a further restriction on the collection bamount 100i have tried the following unsuccessfullylistitem items sessioncreatecriteriaitemclass setfetchmodebids fetchmodejoin createaliasbids b addrestrictionsgtbamount 100 list listitem items sessioncreatecriteriaitemclass createcriteriabids addrestrictionsgtamount 100 list,['java'] +358003,why cannot i register multiple django modeladmin with same model i have the following modeladminclass eventadminadminmodeladmin modeladmin config def querysetself request queryset supereventadmin selfquerysetrequest return querysetexcludedate end ltdatetodayadminsiteregisterevent eventadminnow i want to add a model to manage archived older than today eventsclass eventarchiveadminadminmodeladmin modeladmin config def querysetself request queryset supereventarchiveadmin selfquerysetrequest return querysetfilterdate end ltdatetodayadminsiteregisterevent eventarchiveadminbut if i try to do so i get alreadyregistered exceptionwhy cannot i implement another modeladmin with same model and how can i get different admin views of the same modeli know i can implement a custom list filter in my class but i would like to keep things separated in different pages,['python'] +358065,how to declare a constant in java we always write public static final int a 0 question 1 is static final the only way to declare a constant in a class 2 if i try this public final int a 0 this time is a still a constant or just an instance field 3 what is an instance variable whats the difference between an instance variable and an instance field,['java'] +358111,delivery notification in smtp below code is workin fine however i need get failure or success notification to specific address but i am receiving delivery notification mail to frommail address can you please help me to resolve this problemsmtpclient smtpclient new smtpclientmailmessage message new mailmessagemailaddress fromaddress new mailaddress balamailaddress adminaddress new mailaddresmtpclienthost mail server namesmtpclientport 25smtpclientusedefaultcredentials true messagefrom fromaddressmessagetoadd sendto recipent emailmessagesubject subjectmessagebody detailsmessageisbodyhtml truemessageheadersaddthispositionnotificationto messagedeliverynotificationoptions deliverynotificationoptionsonsuccessmessagereplyto adminaddresmtpclientdeliverymethod smtpdeliverymethodnetworksmtpclientsendmessage,"['c#', '.net']" +358157,can users modify nsuserdefaults key values in an ios app i have a question about securityi am making an ios app with in app purchase following this tutorial and i store what products were bought in nsuserdefaults that is why i wonder can a user with a jailbroken device modify nsuserdefaults key and values for an appthank you very much if you know about itjer,['ios'] +358158,gemspec how can i specify dependencies which do not have to be autorequired i wrote a gem with a certain array of dependencies and some of them i would like not to have implicitly required when bundled into another project an example is the uuidtools gem which i only want to require in files using it gemadd dependencyuuidtools213 require falsethis syntax is false since require false is unexpected there but this more or less sums up what i would like to do with it can someone help me on this,['ruby-on-rails'] +358210,static variable for each derived class possible duplicateoverriding static variables when subclassing i have a set of classes that are all derived from a base class any of these derived classes declare the same static variable it is however specific to each of the derived classesconsider the following codeclass base todo somehow declare a virtual static variable here bool fooint y return x y error axa was not declared in this scope class a public base static int xclass b public base static int xclass c public base static int xint ax 1int bx 3int cx 5int main in my base class i wanted to implement some logic that requires the knowledge of the derivedclaspecific x any of the derived classes has this variable therefore i would like to be able to refer to this variable at base class scope this wouldnt be a problem if it were a simple member variable however semantically the variable is indeed not a property of the derived class instance but rather of the derived class itself therefore it should be a static variable update i need the class hierarchy to preserve its polymorphic nature that is all my derived class instances need to be members of a common base class then however how can i get my hands on this variable from the base class method,['c++'] +358212,writing c modules for nodejs can anyone can give me a very small framework example of how to impliment a c module in nodejs,"['javascript', 'c++']" +358238,android asynctask for long running operations quoting the documentation for asynctask found here it says asynctasks should ideally be used for short operations a few seconds at the most if you need to keep threads running for long periods of time it is highly recommended you use the various apis provided by the javautilconcurrent pacakge such as executor threadpoolexecutor and futuretasknow my question arises why the doinbackground function runs off the ui thread so what harm can we have by have long running operation here,['android'] +358239,commandline tool to find java heap size and memory used linux is there a commandline tool linux to check heap size and used memory of a java applicationi have tried jmap but it gives info about internal memory areas like edenpermgen etc which is not useful to me i am looking for something like max memory 1gb min memory 256 mb heap memory 700 mb used memory 460 mbthats all i know i can see this in jconsole etc but i need a commandline tool cannot enable jmx etcany such toolcommand,['java'] +358246,jquery detect change in input field possible duplicatejquery how to detect a textboxs content has changed i want to detect when a users keyboard actions alter the value of a text field it should work consistently across modern browsersthe jquery page for the keypress event says it is not consistent also it does not work for backspace delete etci cannot use keydown as it is because it reacts to shift alt and arrow keys etc also it does not fire more than once when the user holds down a key and multiple characters are insertedis there a concise method i am missing or should i use keydown and filter out events that are triggered by arrow keys shift and so on my main concern is there will be keys that i am not aware should be filtered i nearly forgot about alt and ctrl i suppose there could be others but then how would i detect the key being held down and inserting multiple charactersas a bonus it would detect changes due to pasting including rightclicking but i have the solution to that from here,['jquery'] +358271,including native library in netbeans i am trying to read portable devices from java signed appleti found a jmtp library on to get access to portable devices but when i run it in netbeans it gives error exception in thread main javalangunsatisfiedlinkerror no jmtp in javalibrarypath at javalangclassloaderloadlibraryclassloaderjava1860 at javalangruntimeloadlibrary0runtimejava845 at javalangsystemloadlibrarysystemjava1084 at jmtpportabledevicemanagerimplwin32portabledevicemanagerimplwin32java38 at jmtpportabledevicemanagerportabledevicemanagerjava34 at jmtpjmtpmainjmtpjava23 java result 1 i searched and found that i have to include dll file as native library in project of jmtpi rightclicked on project and navigated to properties and then selected run and selected vm option as djavalibrarypathcjmtpnativewindowsand placed that jmtpdll file in cjmtp folderbut same error appears constantly my code is package jmtpimport jmtpportabledeviceimport jmtpportabledevicemanagerimport jmtpportabledeviceobjectimport jmtpportabledevicestorageobjectpublic class jmtp public static void mainstring args portabledevicemanager manager new portabledevicemanager portabledevice device managergetdevices0 connect to my mp3player deviceopen systemoutprintlndevicegetmodel systemoutprintln iterate over deviceobjects forportabledeviceobject object devicegetrootobjects if the object is a storage object ifobject instanceof portabledevicestorageobject portabledevicestorageobject storage portabledevicestorageobjectobject forportabledeviceobject o2 storagegetchildobjects systemoutprintlno2getname managergetdevices0close please tell me what is the issue,['java'] +358286,ios install ssl certificate programatically i am writing a phonegap plugin that installs both ca root certificate and user certificate in the app keychainhere is the code used to install the certificatensdata pkcs12data nsdata alloc initwithcontentsoffilecertpathcfdataref inpkcs12data cfdatarefpkcs12datacfstringref password cfstringrefcertpasswordconst void keys ksecimportexportpassphrase const void values password cfdictionaryref optionsdictionary cfdictionarycreatenull keys values 1 null nullcfarrayref items cfarraycreatenull 0 0 nullosstatus securityerror secpkcs12importinpkcs12data optionsdictionary itemsif securityerror 0 nslog certificate install success else nslog certificate install failure the code above works fine securityerror equals 0 however i am obtaining those errorsunknown apsd59 warning apscourier 0xee1ba80 stream error occurred for apstcpstream 0x126940 tls error code9844 peer dropped connection before respondingunknown securityd638 error cfreadstream domain 12 error 8that indicates that the device does not accept the installed certificate so i am wondering that the certificate is not validated against the ca root certificate installed on the devicedo i have to install the ca root certificate for the app any ideas ps i am new to objectivec and xcode environmenteditthe code below is used to store ca root certificat in keychainnsstring rootcertpath nsbundle mainbundle pathforresourcerootca oftypecernsdata rootcertdata nsdata datawithcontentsoffilerootcertpathosstatus err noerrseccertificateref rootcert seccertificatecreatewithdatakcfallocatordefault cfdataref rootcertdatacftyperef resultnsdictionary dict nsdictionary dictionarywithobjectsandkeysidksecclasscertificate ksecclassrootcert ksecvaluerefnilerr secitemaddcfdictionaryrefdict resultif err noerr nsloginstall root certificate success else if err errsecduplicateitem nslogduplicate root certificate entry else nsloginstall root certificate failureeditit seems that the certificate is not sent to server i think that i have to send manually the certificate each time an https request is madei am looking for a way to catch every https call in phonegapplease feel free to post any ideas,"['objective-c', 'ios']" +358364,count how many files in directory php i am working on a slightly new project i wanted to know how to make it so it counts how many files are in a certain directorydiv idheaderphp dir opendiruploads this is the directory it will count from i 0 integer starts at 0 before counting while false is not equal to the filedirectory while false file readdirdir if in arrayfile array and is dirfile i echo there were i files prints out how many were in the directorydivthis is what i have so far from searching however it is not appearing properly i have added a few notes so feel free to remove them they are just so i can understand it as best as i canif you require some more information or feel as if i have not described this enough please feel free to state so,['php'] +358427,android debug enabled device is not showing up on eclipse i have gone through a lot of threads before posting this here i am facing an issue with android device debugging the device is not getting listed on devices tab in eclipse ide to get devices tab windows show view devices so while starting to debug there is no way to choose a device as device listing shows blank the strange thing is that it used to work fine before and under windows explorer i can browse the filesi am using windows vista home premium 32bit oswhat all i have triedin phoneusb debugging is enabled in phone under settings developeroptionsthisabled and enabled usb debuggingrestarted the phonein eclipseunder debug configurationstargettab always prompt to pickdevice is selected it prompts but does not show any device on thedevice listtried resting adb under devices tab to get devices tab windows show view devicesreinstalled latest android sdk along with adbinstalled eclipse junoin windows cmd under platformtools directory where the android sdk tools is installed ran the following commands without getting any positive outcomeshut down eclipse unplugged the device and tried running adb killserver adb startserverplugged it back in and ran adb devicesmobile device detailsmodel galaxy s2 gti9100rooted yesos ver 403kernel ver 3015hardcorespeedmods2ics k327beclipse version indigo service release 1build id 201109160149edit1 i am ending up getting this error message on eclipse console20121009 123922 devicemonitor adb connection erroran existing connection was forcibly closed by the remote host20121009 123923 devicemonitor connection attempts 1i believe the problem is with the adb driver i have installed the latest sdk so the driver is also latest is there any other way to install the adb driver,['android'] +358450,change css class for all elements with said class with javascript basically i am trying to find all the elements with a particular class name and switch it to another i have another function that switches this back to the original class name heres my function that is triggered with an onclickfunction showeventsappliedto var myobj documentgetelementsbyclassnamenotapplied while myobjlength 0 myobj0classname mbllistitem notappliedout appliedtobuttonsetstyle thisplaynone eventlistingbuttonsetstyle thisplayblocki am getting an error saying myobj0 is undefined any idea why this is happening as a note were using dojo hence the last line of the function i know i could easily do this with jquery but were not using it and it does not make sense to load another framework thanks in advance for your help editthanks to the help from abhishek mishra i modified how i am handling this loop and found a way to do it with just dojo which is what i preferred heres the code function listingclasstoggle dojoquerynotappliedaddclassnotappliedout dojoquerynotappliedremoveclassnotappliedmuch simpler code and a lot lighter than my previous solution thanks for all your help i hope this helps someone else,"['javascript', 'css']" +358456,android 4 html5 canvas not redrawing i am currently developing an android application using phonegap i have an html5 canvas that i am drawing and animating objects on it works great on android 23 but on android 4 it is not redrawing the canvas i tried using both kineticjs and easeljstweenjs for my animations and the problem with not clearing the canvas occurred for both of these libraries i experienced some success showing and hiding a div over the canvas but it does not work all the time i can only assume that this is an android 4 specific bug or some type of feature to enhance the html5 canvas performance does anyone know if there is some setting i can change or method i can call in android 4 or javascript which would allow me to force the redraw of my html5 canvas during animationsit should also be noted that the animations seem to work with easeljstweenjs in the 41 google api emulator the canvas clears and redraws but not on phones running 411 i have done some further research into what is happening essentially it appears that the shape at the very beginning of an animation is leaving an artifact which clearrect does not clear i have a big circle that i am shrinking to a small circle the animation still happens but the big circle is not affected by calling clearrect on the canvas,['android'] +358468,connecting to external database android application i am writing an application for my third year project the application will require interaction with an external mysql database the application will retrieve data from the database and thisplay it to the user in a listviewi have a good idea of what sort of functionality the application is going to have i also have spent a lot of time working with listviews and the local sqlite database i also did a bit of reserach into the httpurlconnection classi am just wondering would anyone be able to offer me a little bit more guidance as to how i might go about accessing this external database will it involve me having to write a web service to handle the transactions and if so what would that involve as i have not encountered web services in my course just yetany advice would be much appreciated also my application is intended for use on ics v404thanks everyone,"['java', 'android', 'sql']" +358506,equivalent of consolereadline in c my teacher just gave me an assignment in c and i am trying to get a string with scanf but it only get the last characters typed can anyone help me please i am looking for the equivalent of consolereadline in cedit i must also be able to store the value through a pointerso the picture show the code currently runnign in the background and it should have stoped at no assurance maladie and waited for an input but it skipped itgetlinecin ptravnam works but it skip a line for some reason,['c++'] +358534,why is not adminautothiscover called automatically in django when using the admin why was it designed to be called explicitly without putting adminautothiscover in urlspy the admin page shows you do not have permission to edit anything see so thread why is this so if you always need to add adminautothiscover to edit information using the admin even though you have a superuser name and password for security why did not the django developers trigger adminautothiscover automatically,['python'] +358551,hibernate exception lockacquisitionexception could not update in my application i am using java hibernateannotations and mysqlit is working fine most of the time but this error happens occasionallysevere could not synchronize database state with sessionorghibernateexceptionlockacquisitionexception could not update mypackanalysistestrun5191 at orghibernateexceptionsqlstateconverterconvertsqlstateconverterjava107 at orghibernateexceptionjdbcexceptionhelperconvertjdbcexceptionhelperjava66 at orghibernatepersisterentityabstractentitypersisterupdateabstractentitypersisterjava2596 at orghibernatepersisterentityabstractentitypersisterupdateorinsertabstractentitypersisterjava2478 at orghibernatepersisterentityabstractentitypersisterupdateabstractentitypersisterjava2805 at orghibernateactionentityupdateactionexecuteentityupdateactionjava114 at orghibernateengineactionqueueexecuteactionqueuejava268 at orghibernateengineactionqueueexecuteactionsactionqueuejava260 at orghibernateengineactionqueueexecuteactionsactionqueuejava180 at orghibernateeventdefabstractflushingeventlistenerperformexecutionsabstractflushingeventlistenerjava321 at orghibernateeventdefdefaultflusheventlisteneronflushdefaultflusheventlistenerjava51 at orghibernateimplsessionimplflushsessionimpljava1206 at orghibernateimplsessionimplmanagedflushsessionimpljava375 at orghibernatetransactionjdbctransactioncommitjdbctransactionjava137 at mypackanalysisfilehelperanalysisjava977 at mypackanalysisdirhelperanalysisjava702 at mypackanalysisdirhelperanalysisjava714 at mypackanalysisdirhelperanalysisjava714 at mypackanalysisdirhelperanalysisjava714 at mypackanalysisdirhelperanalysisjava714 at mypackanalysisdirhelperanalysisjava711 at mypackanalysisparseloganalysisjava682 at mypackanalysismainanalysisjava614the most suspicious line in analysisjava isdbperson person sessiongetpersonclass dbpersonid lockoptionsreadwhat i did is grab the row with the dbpersonid and updatechange the row contents as needed for exampledbpersonname jackdbpersonage sessionsaveorupdatedbpersoni am guessing somethings wrong with the lockoptions andi tried using different lockoptions such as none upgrade but still no luckthe most frustrated thing is i cannot even reproduce this error manually it only happens once a while when analysisjava are called multiple timesi know session is not threadsafe but i am not sure whether this is related to thatany idea would be appreciated thank you very much,['java'] +358564,split items in list how can i turn the following list12abcd78into12abcd78in the most pythonic wayi have very unpythonic code that creates nested list and then flatterenssum wordsplit for word in words,['python'] +358573,add css to form type is symfony2 i have an edit form the form is made through symfony2 form types i checked the documentation but could not find any option for adding css to the form the form thisplay the data correctly and everything is fine what i want to do is to add styling to each field my edit type is public function buildformformbuilder builder array options builder addid hidden addpatent name text arraylabel patent name adescription textarea arraylabel description required false addappln authtext arraylabel application authorization anyone has any idea ho i can add css thanks,"['php', 'css']" +358575,parsing of html string using jquery i am trying to parse this html through jquery to get data1 data2 data3 while i do get data2 and data3 i am unable to get data3 with my approach i am fairly new to jquery so please pardon my ignorancehtmlbody div classclass0 h4data1h4 p classclass1data2p div idmydividpdata3pdiv divbodyhtmlhere is how i am calling this in my jqueryvar datahtml htmlbodydiv classclass0h4data1h4p classclass1data2pdiv idmydividpdata3pdivdivbodyhtmlalertdatahtmlfindclass0text does not workalertdatahtmlfindclass1text work alertdatahtmlfindmydividtext workonly alertdatahtmlfindclass0text is not working the rest are working as expected i am wondering it may be because class0 has multiple tag inside it or what how to get data1 in such scenario,['jquery'] +358619,android ndk static library debugging merge projects i am looking for a better way to debug a large project i am working on that has a very large ndk core the ndk code consists of a large cc static library that is built and then linked through ndk code to the main android application the ndk portion of the project is itself also in an android library project so in total that makes three projects android ndk glue project native c libit is my understanding that ndk debugging works poorly or not at all when attempting to interface with a library project i suspect i could merge the ndk glue code project with the main android project with relatively little pain but the bigger problem is the cc project that contains the core of the projectis there a feasible way to merge a cc project and an android ndk project without having to rewrite the buildmake scripts for the cc project the current build scripts for the static library are quite complicated and will probably be quite difficult to convert to androidmk filesare there any better ways to do this that i have not considered,['android'] +358631,joptionpane input dialog box program write a program that uses input dialog boxes to read three test marks each out of 100 the program thiscards your lowest mark and shows the average of the two higher marks in a message dialog box this is how far i got and i dont know where to do from here any help would be appreciatedimport javaxswingjoptionpane public class average public static void main string args string test1 test2 test3 avg test1 joptionpaneshowinputdialogplease input mark for test 1 test2 joptionpaneshowinputdialogplease input mark for test 2 test3 joptionpaneshowinputdialogplease input mark for test 3,['java'] +358655,c compiletime offsetof inside a template i have the need to use offsetof from a template with a member selector i have come up with a way if youll excuse the awkward syntaxtemplate typename t typename r r tm constexpr stdsize t offset of return reinterpret caststdsize tt0musage is not perfect annoying at beststruct s int x int ystatic assertoffset ofs int sx 0 static assertoffset ofs int sy sizeofint the nonconstexpr form is easier to usetemplate typename t typename rstdsize t offset ofr tm return reinterpret caststdsize tt0mat the obvious thisadvantage that it is not done at compiletime but easier to useint main stdcout offset ofsx stdendl stdcout offset ofsy stdendlwhat i am looking for is syntax like the nonconstexpr variety but still fully compiletime however i cannot come up with the syntax for it i would also be happy with an offset ofsxvalue like the rest of the type traits but cannot figure out the syntax magic for it,['c++'] +358711,less importing css and relative paths i am using less to organize and import all my css files i am also using twitter bootstrap which i integrated inside my styleless it works fine like below however when i use lessc to minify the less file and compress it to one all hell breaks loose with my twitter bootstrap css the reason is that my bootstrapmincss has a relative path to images as img so when i minify all these files and dump my output file it no longer finds this path how exactly should i fix this i do not want to be hardcoding absolute urls in my cstyleless import folder onefile one import folder onefile two import folder twofile one import folder threefile one this bootstrap css references images relatively img import bootstrapbootstrapmincss,['css'] +358802,javascript typeerror x is not a function friends i came to a bit of problem everything was working fine before but i cannot rectify why it starts giving me such errorhere is my javascript codefunction newsupplier divaddsupplier divmsghtmlhide divaddsupplier divloadershow registersupplierdivaddsupplier tablefrm inputserializedonefunction a if amsg divaddsupplier divmsghtmlamsgremoveclasuccessaddclasserrorfadein else if asupid divaddsupplier divmsghtmlsupplier span classl2 asupid span registeredremoveclasserroraddclasuccessfadein divaddsupplier tablefrm inputval alwaysfunction divaddsupplier divloaderhide failfunction divaddsupplier divmsghtmlerrmsgnetremoveclasuccessaddclasserrorfadein and here is the code of registersupplier functionfunction registersupplierdatatopost return ajax type post url jsonpath jsonashxmethodregistersupplier data datatopost and here is the complete js file related html div idvieworder h2view order detailsh2 div classtabcontent table classfrm tr tdlabelenter order numberlabeltd tdinput typetext nameordernumber onkeyupvieworderdivdivfadeout input typebutton classbut1 mside valueok onclickloadmaterialordertd td div classprocessnbspdiv td tr table div div classborder shadow mtb h2 classheaderorder detailsh2 div idorderdetails classtabcontent table classfrm tr tdlabelsupplierlabeltd tdselect idnewsupplier namesupplierselecttd td classraligninput typebutton valueload suppliers onclickloadsuppliersnewsupplier td tr tr tdlabelorder datelabeltd tdinput typetext nameorderdate td tr tr tdlabeldelivery datelabeltd tdinput typetext namedeliverydate td tr tr tdlabelcancel datelabeltd tdinput typetext namecanceldate td tr tr tdlabelpayment due marklabeltd tdinput idpaydue2 typecheckbox nameispaydue label forpaydue2yeslabeltd tr tr tdlabelremember marklabeltd tdinput idremark2 typecheckbox nameismarked label forremark2yeslabeltd tr table div table classfooterbuttons tr td div classmsgdiv div classloader stylethisplaynoneimg altloader srccssimagesloadergif div td tdinput typebutton classbut1 subbut valuesave changes onclickinput typereset valuereset td tr table div br div classborder shadow mtb h2 classheaderpayment recordsh2 div idpaymenthistory classtabcontent table classtab payhis tr classth tdtd tdtranstd tddatetd tdcommenttd tdtypetd tdcredittd tddebittd tdbalancetd tdassociated agenttd tr tr tdinput typeradio namepayselect td td1011td td121212td tdabclk lask aatd tdcredittd td500td tdtd td50td tdshashwat tripathitd tr tr tdinput typeradio namepayselect td td1012td td121212td tdshashwat tripathitd tddebittd tdtd td500td td50td tdsudhirtd tr tr tdinput typeradio namepayselect td td1013td td121212td tdshashwat tripathitd tdcredittd td500td tdtd td50td tdsudhir gaurtd tr table br input typebutton classbut2 valueedit onclickvieworder payeditslidedownfunction html bodyanimate scrolltop paymenthistoryoffsettop20 500 input typebutton classbut2 mside valuedelete div idpayedit classborder mtb shadow stylethisplaynone h2 classheaderedit paymenth2 div classtabcontent table classfrm tr tdlabeldatelabeltd tdinput typetext namedate placeholderddmmyytd tr tr tdlabeltypelabeltd td select nametype optioncreditoption optiondebitoption optionexpenseoption select td tr tr tdlabelamountlabeltd tdinput typetext nameamount placeholderaa aa34aa td tr tr tdlabelcommentlabeltd tdtextarea namecomment rows4 cols10textareatd tr tr tdtd tdinput typebutton classbut1 valuesave changes input typebutton classbut2 mside onclickpayeditslideup valuecancel td tr table div div br h2register new paymenth2 hr div idnewmatorderpayment table classfrm tr tdlabeldatelabeltd tdinput typetext namedate placeholderddmmyy td tr tr tdlabeltypelabeltd td select nametype optioncreditoption optiondebitoption optionexpenseoption select td tr tr tdlabelamountlabeltd tdinput typetext nameamount placeholderaa aa34aa td tr tr tdlabelcommentlabeltd tdtextarea namecomment rows4 cols10textareatd tr table div div table classfooterbuttons tr td div classmsgdiv div classloader stylethisplaynoneimg altloader srccssimagesloadergif div td tdinput typebutton classbut1 valueregister payment onclickinput typebutton classbut2 onclicknewmatorderpayment textval valuereset td tr table div div divdivdiv idaddsupplier h2register new suppilerh2 div classtabcontent table classfrm tr tdlabelsupplier idlabeltd tdinput typetext namesupid td tr tr tdlabelcontact numberlabeltd tdinput typetext namecontact td tr tr tdlabeladdresslabeltd tdtextarea nameaddress cols10 rows4textareatd tr tr tdlabelemail addresslabeltd tdinput typetext nameemail td tr tr tdlabelcitylabeltd tdinput typetext namecity td tr table div table classfooterbuttons tr td div classmsgdiv div classloader stylethisplaynoneimg altloader srccssimagesloadergif div td tdinput typebutton classbut1 subbut valueregister onclicknewsupplierinput typereset valuea aa td tr tabledivif i am calling this function directly from ff and firebug console then it is getting calledbut on button click i am getting error typeerror newsupplier is not a functionplease ask me if you need additional code,"['javascript', 'jquery']" +358812,could not open the editor android xml editor cannot process this input i got this error whenever i tired to view previous version of xml file via svn team show history how can i able to solve this problem could not open the editor andriod xml editor cannot process this input,['android'] +358821,get screen size in pixels in windows form in c possible duplicatehow to retrieve the screen resolution from a c winform app how can i get the screen size in windows forms,['.net'] +358834,stdmap of iterators to itself my goal is to map elements of a type to other elements of the same type suppose they are size t for simplicitystdmapsize t size t mymappingthis would do it but if i want to follow a bunch of such links they are all the same map each step is a logn lookupsize t k whatevermymappingmymappingmymappingk 3 logni want to make use of the fact that map iterators remain valid and have a map that maps size t to iterators into itselftypedef mymaptemplateiterator map iterstdmapsize t map iter mymappingsize t k whatevermap iter entrypoint mymappingfindkentrypointsecondsecondfirst logn 2 constant time operationshow would i write this typei know copying would keep iterators to old map and plan to take care of this myself,['c++'] +358880,using composers autoload i have been looking around the net with no luck on this issue i am using composers autoload with this code in my composerjsonautoload psr0 appname srcbut i need to autoload at a higher level than the vendor folderdoing something like this does not workautoload psr0 appname srcdoes anyone know a fix or how i can do this,['php'] +358882,should i leave the bluetooth reflection hack in production code i am working in a project where i need to connect via bluetooth to a printer the printer manufacturer states that only android phones having spp serial port profile are going to be able to connect with the printerthis is how i opened the connection initially uuid uuid uuidfromstring0110101080805f9b34fb spp long uuid bluetoothsocket socket devicecreaterfcommsockettoservicerecorduuidusing uuids is the only way to open rfcomm connections using android public api as of jellybean having worked before with spp connections in blackberry and javame where uuids are not required i found this a bit odd uuids are about service thiscovery that is using sdp to query about the services present in the device i do not really need to initiate a thiscovery since i have my printer paired in advance and i know it supports spp however that is exactly what the bluetoothdevicecreaterfcommsockettoservicerecord method and the insecure version do this is the spp stack where we can see how sdp is a different protocol at the same layer and thus it should be possible to use rfcomm without initiating a thiscovery first my application serial port emulation or other api rfcomm sdp lmp l2pcap baseband i started testing my app in a few old htc devices without problems later testing on samsung phones several devices were unable to open a connection these phones allegedly do not support spp profile according to both manufacturer and 3rd party specsedit 3rd party specs list spp as supported and the manufacturer specs are not accurate enough an ioexception service thiscovery failed was thrown and i followed the approach shown in this questionservice thiscovery failed exception using bluetooth on android the solution proposed there is to use a reflection hack as follows method m devicegetclassgetmethodcreaterfcommsocket new class intclass bluetoothsocket socket socket bluetoothsocket minvokedevice 1the hack worked for me amazingly this method in bluetoothdevice class is public but it is removed from the api by means of the hide annotation this is the source code as of jellybean create an rfcomm link bluetoothsocket ready to start a secure outgoing connection to this remote device on given channel pthe remote device will be authenticated and communication on this socket will be encrypted p use this socket only if an authenticated socket link is possible authentication refers to the authentication of the link key to prevent maninthemiddle type of attacks for example for bluetooth 21 devices if any of the devices does not have an input and output capability or just has the ability to thisplay a numeric key a secure socket connection is not possible in such a case use link createinsecurerfcommsocket for more details refer to the security model section 52 vol 3 of bluetooth core specification version 21 edr puse link bluetoothsocketconnect to initiate the outgoing connection pvalid rfcomm channels are in range 1 to 30 prequires link androidmanifestpermissionbluetooth param channel rfcomm channel to connect to return a rfcomm bluetoothserversocket ready for an outgoing connection throws ioexception on error for example bluetooth not available or insufficient permissions hide public bluetoothsocket createrfcommsocketint channel throws ioexception return new bluetoothsocketbluetoothsockettype rfcomm 1 true true this channel null i cannot understand why a public method is removed from the api in this manner but letting this appart both this method and the officially supported one using uuids are thin envelopes calling the same bluetoothsocket constructor with different parameters public bluetoothsocket createrfcommsockettoservicerecorduuid uuid throws ioexception return new bluetoothsocketbluetoothsockettype rfcomm 1 true true this 1 new parceluuiduuid digging a bit more in the sources i realized that both open a rfcomm connection but the uuid method initiates a thiscovery and the hidden one notall in all the reflection hacks work flawlessly in every device i have tested it from os 22 to 41 edit the faulty devices do support spp it is just that their custom implementation of bt stack is messing up with the thiscovery process there are also other bugs like the the one showing pairing dialog for already paired devices in ics calling this hidden api using reflection enables a workaround to all these bugs or different behaviour introduced by the different manufacturersshould i keep the hack in production code is there a way to achieve the same with the public apithanks in advance,['android'] +358968,rails engine how to use seed i have created a rails engine i am having trouble using the seed command if i run rake dbseed i get the error uninitialized constantin the engine i got a seedsrbpagecreatetitle frontpage order 1 then in my dummy app i got a seedsrb with cmsengineload seed cms being the name of the engine i got an error now though that uninitialized constant how do i reference the constant from the dummy app,['ruby-on-rails'] +358972,what does this warning mean setting the first responder view of the collection view but we do not know its type cellheaderfooter i have a uicollectionview with a uitextview in each cell when i tap on one of the text views and the keyboard comes up i get this warning in the output panelsetting the first responder view of the collection view but we do not know its type cellheaderfooter text input works fine though however i would really like to know what this warning means before i use this code in production,"['iphone', 'ios']" +358984,dialogfragment callback on orientation change i am migrating my dialogs currently using activityshowdialogdialog id to use the dialogfragment system as thiscussed in the android referencethere is a question that arose during my development when using callbacks to deliver some event back to the activityfragment that opened the dialogheres some example code of a simple dialogpublic class dialogtest extends dialogfragment public interface dialogtestlistener public void ondialogpositiveclickdialogfragment dialog use this instance of the interface to deliver action eventsstatic dialogtestlistener mlistenerpublic static dialogtest newinstanceactivity activity int titleid int messageid udatelisteneractivity dialogtest frag new dialogtest bundle args new bundle argsputinttitleid titleid argsputintmessageid messageid fragsetargumentsargs return fragpublic static void udatelisteneractivity activity try instantiate the noticedialoglistener so we can send events with it mlistener dialogtestlistener activity catch classcastexception e the activity does not implement the interface throw exception throw new classcastexceptionactivitytostring must implement dialogtestlistener overridepublic dialog oncreatedialogbundle savedinstancestate int titleid getargumentsgetinttitleid int messageid getargumentsgetintmessageid alertdialogbuilder builder new alertdialogbuildergetactivity dialog title buildersettitletitleid dialog message buildersetmessagemessageid dialog negative button buildersetnegativebuttonno new onclicklistener public void onclickdialoginterface dialog int id dialog positive button buildersetpositivebuttonyes new onclicklistener public void onclickdialoginterface dialog int id mlistenerondialogpositiveclickdialogtestthis create the dialog object and return it return buildercreateand heres some activity code calling itpublic class someactivity extends fragmentactivity implements dialogtestlistener private edittext musernameoverridepublic void oncreatebundle savedinstancestate setup ui superoncreatesavedinstancestate setcontentviewrlayoutui user edit name input musername edittext findviewbyidriduseredit edittextnameoverridepublic void ondialogpositiveclickdialogfragment dialog logdtag thistostring musernamesettextmusernamegettext 1private void showdialog dialogtest test dialogtestnewinstancesomeactivitythis rstringsometitletext rstringsomemessagetext testshowgetsupportfragmentmanager testdialogthe code is pretty much what you see the reference problem is that once you do a orientation change when a dialog is shown it stops working as expected due to the activity lifecycle both the activity and the dialog are rebuild and the dialog now does not have the proper reference to the new rebuilt activityi added the following code to my activitys onresume method overrideprotected void onresume superonresume dialogtestudatelistenerthisdoing this i get the expected behavior and the dialog sends events back to the new rebuilt activity when an orientation change occuredmy question is what is the best practice to handle the callbacks between the dialogfragment which was opened by a fragmentactivity during an orientation changebest regards,['android'] +358988,ios how to use mpmovieplayercontroller i have created a blank project ios and put this in my viewdidloadnsstring moviepath nsbundle mainbundle pathforresourcemovie oftypem4vmpmovieplayerviewcontroller playercontroller mpmovieplayerviewcontroller alloc initwithcontenturlnsurl fileurlwithpathmoviepathself presentmovieplayerviewcontrolleranimatedplayercontrollerplayercontrollermovieplayer playwhen the app starts all i get is a white screen with error messages in the log error cgcontextsavegstate invalid context 0x0 error cgcontextcliptorect invalid context 0x0 error cgcontexttranslatectm invalid context 0x0 error cgcontextdrawshading invalid context 0x0 error cgcontextrestoregstate invalid context 0x0warning attempt to present mpmovieplayerviewcontroller 0x821e3b0 on viewcontroller 0x863aa40 whose view is not in the window hierarchyand a bunch of lines regarding thisabling autoplayi especially do not understand the line about the view not being part of the hierarchy since it is a blank single view application ios project and the code is in viewcontrollerm it is in the view hierarchyi know for a fact that the movie file itself is not the problem because i got it from apples sample code on mpmovieplayer and although i seemingly tried everything written in the sample i just could not get the player to workhere is another try this time with mpmovieplayercontroller not mpmovieplayerviewcontrollermpmovieplayercontroller player mpmovieplayercontroller alloc initwithcontenturlurlplayer setcontenturlurlplayer setmoviesourcetypempmoviesourcetypefileplayer view setframeselfviewboundsplayer viewbackgroundcolor uicolor greencolorplayerscalingmode mpmoviescalingmodenoneplayercontrolstyle mpmoviecontrolmodedefaultplayerbackgroundviewbackgroundcolor uicolor whitecolorplayerrepeatmode mpmovierepeatmodenoneselfview addsubview player viewplayer playsimilar result with white screen and errorsplease help,"['objective-c', 'ios']" +359002,structuring css sass less files by elements by function and by media queries 3d code structure zerodeverybody starts using css with a single file that contains all the stylesstylecss1dsoon it becomes bulky and one decides to group css in a number of files by page elementshtml elementscssheadercssmainareacssfootercsome may find this not convenient enough and group styles by functiontypographycsslayoutcstickyfootercss contains declarations for many elements not footer only2dwhen a project has a lot of css it might require using both groupings simultaneously css files structure becomes twodimensionallayoutgridsystemcssheadercsidebarscsslooktypographymaincssheaderscsslistscssbackgroundshtml elementscssheadercssmainareacssfootercssokay the example is fabricated but you sure do understand what i meanup to this point everything is fineenter media querythis is where my css structure gets funked upin addition to the 2d structure described above i have to structure my code by media queriessome of my styles are universal applied everywheresome are applied to certain screen size onlysmallmediumlargeextra largesome are applied to certain groups of screen sizeseverything except small nonmobile stylessmall and medium where sidebars are not at the sideslarge and xlarge where you do have sidebarsi tried to overcome the issue by scattering media queried styles among existing css files the breakpoint compass extension helps a lot but the stylesheets become too messy finding a certain style when it is not portrayed in the files structures a lot of paini tried grouping by media queries then by elements and function but files structure is two dimensional so you cannot add a new dimension you can only add another level of hierarchy so it is not graceful also it is very bulkyso i end up with a 2d structure with media queries on one axis and an ugly mix of elements and functions on the other axisi am absolutely not satisfied with that but i just fail to come up with a graceful solution please suggest one,['css'] +359005,fading uiview allows subviews to be seen i have a uiscrollview which contains various subviews uiimageviews uilabels and standard uiviews some of the uiimageviews are partially covered by other uiviews however when i fade out the uiscrollview the partially covered parts of the uiimageviews are being exposed for the brief moment of the animation i want to be able to fade the scrollview and all it is contents at the same time in the same animation ie not revealing any of the partially covered imagesif it is not possible i can always add a uiview on top of all the other controls and fade it from alpha 0 upto 1 to hide everything but i am sure there is a way to perform a complete fade on a view and all it is subviewsi tried thisuiview beginanimationsnil contextnullscrollviewresults setalpha00fuiview commitanimationsand i have tried this ibactionquestiongroupchangeduibuttonsender uiview beginanimationsnil contextnull self fadeviewhierarchyscrollviewresults toalpha00f uiview commitanimations voidfadeviewhierarchyuiviewparentview toalphafloatalpha parentview setalphaalpha for uiview subview in parentviewsubviews self fadeviewhierarchysubview toalphaalpha but i have still not cracked it any ideas,"['objective-c', 'ios']" +359018,race condition between application oncreate and resources loaded i have the following application class for my app when the application starts i want to get some settings from preferences and start a background servicepublic class myapplication extends application public void oncreate sharedpreferences preferences preferencemanagergetdefaultsharedpreferencesthis string key getresourcesgetstringrstringprefkey updateinterval this normally works fine but occasionally when starting my program from eclipse run i get this error1010 082547016 eandroidruntime26402 caused by androidcontentresresourcesnotfoundexception string resource id 0x7f0a041010 082547016 eandroidruntime26402 at androidcontentresresourcesgettextresourcesjava2161010 082547016 eandroidruntime26402 at androidcontentresresourcesgetstringresourcesjava2691010 082547016 eandroidruntime26402 at comkarwostsmyaportfoliostoreoncreateportfoliostorejava401010 082547016 eandroidruntime26402 at androidappinstrumentationcallapplicationoncreateinstrumentationjava9691010 082547016 eandroidruntime26402 at androidappactivitythreadhandlebindapplicationactivitythreadjava3395this id is from my rjavapublic static final int prefkey updateinterval0x7f0a04since this works fine most of the time i have to assume that there is some kind of race condition between oncreate and the resources being loaded if that is the case is it recommended not to read resources in application oncreate if so is there a better place to initialize a service when application launches,['android'] +359077,css3 vs javascript what is the advantage it seems with html5css3 there is a larger push towards cssonly animations effects navigations etc is this purely because of the tendency of cjavaetc developers to use javascript incorrectly mostly in a semantic sense i guess or is there an advantage of css over javascript if so why would css be better is it fasteralso semanticallyspeaking should not css only be used for stylingpositioning so is css starting to go outside the bounds of what it was designed for,"['javascript', 'html', 'css']" +359088,how to store 800 billion gps markers in database i need to store gps tracks that users record into a database the tracks will consist of a marker every 5 meter of movement for the purpose of drawing a line on a map i am estimating 200 km tracks which means 40 lnlt markers i estimate 50 users minimum and 20 pieces of 200 km tracks for each that means at least 40 billion lnlt markers this needs to scale too so for 1 million users i need capacity for 800 billion gps markerssince each set of 40 markers belong to a single track we are talking 1 20 million recordssets of gps tracksrequirementsusers will request to view these tracks on top of a google map in a mobile applicationrelationsi currently have 2 tables table one hastrackid userid comment thistance time top speed table 2 has trackid longitude latitude and this is where all gps markers are stored what is an efficient way of storing this volume of gps data while maintaining read performancenew informationstoring the gps data in a kml file for the purpose of thisplaying them as a track on top of a google map is a good solution that saves database space compressing the kml into a kmz basically a zipped kml wit a kmz extension greatly reduces file size further kmz loads much quicker than gpx and can be integrated with the google maps api as a kml layer see this information from google for further assistance this seems to be the best solution so far for the intended requirement,['mysql'] +359112,printing 2d array in matrix format i have a 2d array as followslong arr new long4 4 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1 i want to print the values of this array in matrix format like0 0 0 01 1 1 10 0 0 01 1 1 1how can i do this,['c#'] +359119,winforms app uses lowquality title bar icon on 16bit thisplay on thisplays with 16bit color depth including remote desktop sessions set to 16bit color windows forms applications use a lowcolordepth version of the assigned titlebar icon formicon wpf applications and windows explorer however use the 24bit color depth if it existsi first saw this in a windows forms application i am currently working on the icon i was using had 4bit 24bit and 32bit variants defined on 16bit thisplays windows forms was using the ugly 4bit version in the title bar instead of the nicelooking 24 or 32bit versionto test and illustrate the behavior i created a test icon with obviously different designs for each size and color format i included 4bit 8bit 24bit and 32bit variantshere are the results on both 32bit and 16bit thisplayson 32bit thisplays all is wellwindows explorerwpf applicationwindows forms applicationon 16bit thisplays windows forms thisplays a lowercolordepth variant of the icon than does wpf or windows explorerwindows explorerwpf applicationwindows forms applicationon 16bit thisplays windows explorer and wpf use the 24bit format but windows forms does not in this case it used the 8bit format my real application icon did not have an 8bit variant but i am going to make one now so windows forms used the 4bit varianthow can i make my windows forms application thisplay the 24bit version of an icon in its title bar on a 16bit thisplay,['.net'] +359142,nsrange rangelocation nsnotfound vs rangelength 0 i am going through some older code in one of my apps and fixing up the code in areas that could be potentially problematici am seeing a lot of old code usingnsrange range determine range hereifrangelength 0 do stuffis that code fine or should i change it to thisnsrange range determine range hereifrangelocation nsnotfound do stuffare these two methods identical essentially or not,"['ios', 'objective-c']" +359151,authentication with nsurlconnection sendasynchronousrequest with completion handler generally i like to just fire and forget with nsurls sendasynchronousrequest class method using the completion handler block but it seems that might not be an option when authentication is neededwhen using a completion handler style request like thisnsurlconnection sendasynchronousrequestnsurlrequest requestwithurlnsurl urlwithstring queuensoperationqueue mainqueue completionhandlernsurlresponse response nsdata data nserror error do stuff what is the proper way to handle authentication do i need to alloc and init the nsurlconnection and set a delegate instead of doing using this class method style i think i understand how to authenticate correctly with the delegate function but i am trying to figure out if i can include that in the completionhandler block or if there is a better way to do this voidconnectionnsurlconnection connection willsendrequestforauthenticationchallengensurlauthenticationchallenge challenge if challenge previousfailurecount 0 nslogauthentication failure connection cancel else nsurlcredential credential nsurlcredential credentialwithuserselfusername passwordselfpassword persistencensurlcredentialpersistenceforsession challenge sender usecredentialcredential forauthenticationchallengechallenge,['ios'] +359172,interview hash function sine function i was asked this interview question i am not sure what the correct answer for it is and the reasoning behind the answeris sinx a good hash function,['c'] +359196,android unit testing bundleparcelable how do you unit test parcelable i created a parcelable class and wrote this unit testtestclass test new testclassbundle bundle new bundlebundleputparcelabletest testtestclass testafter bundlegetparcelabletestassertequalstestaftergetstuff event1getstuffi purposely try to fail the test by returning null in the createfromparcel but it seems to succeed it looks like it does not get parceled until it is needed how do i force the bundle tobundle,['android'] +359259,is the before pseudoelement allowed on an inputtypecheckbox this stackoverflow answer describes how to style checkboxes using css3 without requiring a labelinputtypecheckboxbefore content thisplayinlineblock width12px height12px backgroundred fiddlethis works in chrome 22 but not in firefox 15 or ie 9given the lack of support in the latter two browsers is chromes behavior valid according to the css3 specification,['css'] +359260,jquery ajax multipartformdata not sending data i am at a loss for why i cannot get jquery to pass upload data seeing as the ajax object appears to be configured correctly and the correct contenttypemimetype headers are being senti have tried two separate forms of requestone with a formdata object contained within a literal and also just passing the formdata object directlyunfortunately either way i cannot get anything to pass and both files and post are empty arraysthe ideal request i wish to use is as followsalong with the following codevar files new formdataeachcontextprototypefiledata functioni obj filesappendi objvaluefiles0 var request action upload id responseobjid data files ajax type post url contextcontroller data request processdata false contenttype multipartformdata mimetype multipartformdata success functionr consolelogr if errors null else contextclose error functionr alertjquery error once again the only response looking at both the network tab console when i try to export both files and post is simply two empty arrays,['jquery'] +359323,increment uislider by 1 in range 1 to 100 i am new to iphonehow do i have my uislider go from 1 to 100 in increments of 1 slider uislider alloc init slider addtargetself actionselectorsliderchange forcontroleventsuicontroleventvaluechanged slider setbackgroundcoloruicolor clearcolor sliderminimumvalue 1 slidermaximumvalue 100 slidercontinuous yes slidervalue 00 ibactionsliderchangeidsender nslogslidervaluefslidervaluewhen i slide my log showsslidervalue 10slidervalue 1123440slidervalue 1234550slidervalue 1345670slidervalue 1567890i want slider value as 10 20 30 and so onany help will be appriciated,"['ios', 'objective-c']" +359327,oauth facebook authentication with aspnet web api so i guess this question is sort of two foldswhat should i store when granted facebook oauth rights into my user domain entity facebook userid or token or both or something elsecan i just generally secure the aspnet web api with a delegatinghandler to read for the access tokencurrently my core architecture is as followsmyappdomain my domain models in a class library projectmyappdataaccess my repositories and entity framework contextsmyappwebapi aspnet web api project for a restful servicemy clients aremyappwebsite aspnet mvc 4 website myappiphoneapp native ios app for the iphone myappandroidapp native android app,['.net'] +359343,eclipse content assist validation key i am unable to find any documentation about changing the shortcut that validates the content assist selectioni mean for my exact case when the content assist is opened i want to validate its proposal by hitting enter which works but never with any other key like or i would like to choose what key validates the proposaleven if i need to manually edit a config file if anyone have this answer it would be perfect i looked at orgeclipsejdtuiprefs and orgeclipsewstjsdtuiprefs but with no successthanks,['java'] +359357,whitespace in the format string scanf consider the following codeincludestdiohint main int i3 j4 scanfd c dij printfd dij return 0it works if i give 2c3 or 2 c 3 or 2c 3 as input if i have to change the value of variables what should i do if i want the user to enter the same pattern as i want means if dcd then only 2c3 is acceptable and not 2 c 3 and vice versa if it is d c d,['c'] +359363,how to store objects of different types in a container i am wondering if i can have an array or basically a table with each of its element being a set of objects of different types i mean i want to create something like this i know it is incorrect in syntax just wanna demonstrate my idea liststring int double date etc list namei am doing this to ensure that when i save all these information to my database i will have all these information in the same entry in the database this is because i did some web scraping from different sites to gather all these data ie in the list string may be from site a int may be from site b etc i found some information may be missed for some reasons say for a particular element of the list string from site a may be missing other data are just there perfectly fine if i store these data into seperated lists i am afraid there will be some mismatch of datanow my solution is to create a class say classa classapublic string info1public int info2public double info3public wtever infoand then i will have a of list of classai am wondering if there is a better way to achieve this,['java'] +359365,how to use a buttons data attribute to call a selected javascript function i am trying to set some data on my buttons such that it can be accessed onclick i am having no problem using json in a buttons data attribute where the key value is a string however i cannot figure out how to set the values to be a functionwhat i would like to happen upon clicking the button in this demo code is for the click event to call the function option1 which will alert the string hello outsidethe error i am getting is thisuncaught typeerror property option1 of object object is not a functionhtml jsfiddle is here button typebutton databuttonoption1 option1 option2 option2click1buttonjsvar datahello outsidevar option1functiondata alertdata buttonclickfunction var datahello inside thisdatabuttonoption1data should alert hello outsidethoughts,"['javascript', 'jquery', 'html']" +359381,debug core data migration to compare hash values i read this post click about fixing a nasty core data migration problemthe author victor bogdan wrote that he enabled data migration debug to get the hash values for the entities what does it mean is it possible to enable more debug output for a migration or did he wrote a migration process with debug outputmy problem is that i cannot get the entity hashes for the mapping model to compare them with the source and destination entity hashesi am on xcode 451 and use ios6 but i had the same migration problems with older versions,"['objective-c', 'ios']" +359393,organize android src folder in subfolders eclipse sorry for the noob question but i am pretty new to the android sdkeclipse environmentthe application i am developing is getting pretty big with several classes i would like to organize it better having folders for views models dialogs ecthow can i create a subfolder of the src folder if i right click on the src folder i do not have that optionshould i create a new packagei tried to add a new src folders but that goes to the same level of the main src folder with default package path and eclipse does not see my files therewhat is the best way to have a folder structure for all my classes in a projectthanks,['android'] +359395,mysql trigger before insert value checking i have a table staff with office column currently the office column do not accept null values the application persisting onto this table has a bug which meant that when the staff has not been assigned an office it tries inserting a null value onto the tablei have been asked to used a trigger to intercept the insert onto the staff table and check if the office value is null and replace it with value na below is my attempt so far but do have error in attempt to implement any ideas on how to resolve thiscreate trigger staffofficenullreplacertrigger before insert on staff for each row begin if newoffice is null insert into staff set officena end if endthe errormysql database error you have an error in your sql syntax check the manual that corresponds to your mysql server version for the right syntax to use near insert into staff set officena end,['mysql'] +359405,best practices for data providing phpunit i am currently writing units tests for a library after refactoring business logic from the data i am now in a bit of confused state over how to now test the logicfor example i have a quite complex process which an array of data gets passed through i am going to use a data provider for this so i can make sure it will work for all sorts of caseswith the data that i am going to be passing in through the data provider should i also be passing an expected outcome or should this be calculated in the testas said the process for the calculating is quite a complicated process not quite a b,['php'] +359449,android set the gridview to have 2 columns per row only here is my code in my activitypublic class gridviewactivity extends activity gridview gridview static final string mobile os new string android ios windows blackberry override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain gridview gridview findviewbyidridgridview1 gridviewsetadapternew imageadapterthis mobile os gridviewsetonitemclicklistenernew onitemclicklistener public void onitemclickadapterview parent view v int position long id toastmaketext getapplicationcontext textview vfindviewbyidridgrid item label gettext toastlength shortshow and in my image adapterpublic class imageadapter extends baseadapter private context context private final string mobilevalues private textview t public imageadaptercontext context string mobilevalues thiscontext context thismobilevalues mobilevalues public view getviewint position view convertview viewgroup parent layoutinflater inflater layoutinflater context getsystemservicecontextlayout inflater service view gridview if convertview null gridview new viewcontext get layout from mobilexml gridview inflaterinflaterlayoutmobile null set value into textview textview textview textview gridview findviewbyidridgrid item label textviewsettextmobilevaluesposition button b button gridviewfindviewbyidridgrid item button button b2 button gridviewfindviewbyidridgrid item button2 t textview gridview findviewbyidridgrid item number bsetonclicklistenernew myonclicklistenert b2setonclicklistenernew myonclicklistenermt set image based on selected text imageview imageview imageview gridview findviewbyidridgrid item image string mobile mobilevaluesposition if mobileequalswindows imageviewsetimageresourcerdrawablewindows logo else if mobileequalsios imageviewsetimageresourcerdrawableios logo else if mobileequalsblackberry imageviewsetimageresourcerdrawableblackberry logo else imageviewsetimageresourcerdrawableandroid logo else gridview view convertview return gridview private void clickedbuttontextview tv int num integerparseinttvgettexttostring num tvsettextintegertostringnum private void clickedbuttonmtextview tv int num integerparseinttvgettexttostring ifnum0 num tvsettextintegertostringnum override public int getcount return mobilevalueslength override public object getitemint position return null override public long getitemidint position return 0 class myonclicklistener implements onclicklistener public final textview tv public myonclicklistenertextview tv thistvtv override public void onclickview v todo autogenerated method stub clickedbuttontv class myonclicklistenerm implements onclicklistener public final textview tv public myonclicklistenermtextview tv thistvtv override public void onclickview v todo autogenerated method stub clickedbuttonmtv and my mobilexmlxml version10 encodingutf8linearlayout xmlnsandroid androidlayout widthwrap content androidlayout heightwrap content androidpadding5dp imageview androidididgrid item image androidlayout widthwrap content androidlayout height74dp androidlayout marginright10px androidlayout weight144 androidsrcdrawableandroid logo imageview linearlayout androidlayout widthwrap content androidlayout heightmatch parent androidorientationvertical button androidididgrid item button androidlayout width30dp androidlayout height23dp androidtext textview androidididgrid item number androidlayout widthwrap content androidlayout heightwrap content androidlayout gravitycenter androidtext0 button androidididgrid item button2 androidlayout width30dp androidlayout height23dp androidtext linearlayout textview androidididgrid item label androidlayout widthwrap content androidlayout heightwrap content androidlayout margintop5px androidtextidlabel androidtextsize15px textviewlinearlayouti find it a bit troubling not to be able to pout 2 items per row i would like to know how to format my gridview to be able to fulfill such ideahere is my source code,['android'] +359463,ways to bring an android app in background to foreground here is the scenarioandroidmanifestxml defines a single activity with androidlaunchmodesingletask this means there should be a single activity in the stack throughout the entire application lifecycle right during activityoncreate a broadcast receiver is programmatically created and listens for incomming sms the receiver remains active even after activityonpause by designwhen the user is done with the application he presses the device home button which calls activityonpause and the application thisappears the device shows then the android home screen upon receiving sms the broadcast receivers receives sms and tries to show up the activity viaintent it new intentcontext akamiclassitsetactionintentaction mainitaddcategoryintentcategory launcheritsetcomponentnew componentnamecontextgetpackagename myactivityitsetflagsintentflag activity new taskcontextstartactivityithowever the activity is not showed up to the usera why b what are the possible ways to bring an activty to foreground,['android'] +359513,what are skipped tests in visual studio i tried to run visual studio tests in aspnet mvc by pressing run all but all tests were skipped why did this happen and how can i run all tests here is a screenshot,['c#'] +359522,how to get a cookie from an ajax response i have a ajax request on the same domain and i want to read the cookie it keeps returning nullajax type get url myurl success functionoutput status xhr alertxhrgetresponseheadermycookie cache falseany ideas i am using chrome for this,"['jquery', 'html']" +359526,how can i pass data from activity to the dialogfragment that activity invoked in my application i have a form the user fills in pressing save the data will be saved to the local database i want to add a confirm dialog for the user to review the details he entered before moving on since those details are crucialin my dialogfragment instance i would have something like you are entering these details abc do you confirmabc are the values of my edittext fields in the activity which calls the dialogfragmenthow can i access those values from the dialogfragment i am usingnew confirmsaveprojectdetailsshowgetfragmentmanagerconfirmin my activity confirmsaveprojectdetails is my dialogfragment classi am not using an intent otherwise i would send a bundleany suggestion,['android'] +359527,overwriting javascript keywords i know that delete is a keyword in javascript so i have this code for examplevar user create function create a user account delete function delete a user account the above works barring older versions of ie so my question is is it a good idea obviously the call userdelete is much clearer to someone utilizing the code than something like userdelete oneobviously keywords are important but on a case by case basis is it alright granted i do not need legacy ie support to use this method or is there a better solution,['javascript'] +359543,how to define a 2d array in c and stl without memory manipulation there are several ways to define a 2d array in c and stl without memory manipulation and the following codes illustrate two different methodsint main 1 2 3 4 5 6 method 1 const int row 2 const int col 3 int array1rowcol forint i0 irow i forint j0 jcol j array1ij icolj1 method 2 typedef vectorvectorint array array array2 vectorint rowvector forint i0 irow i rowvectorclear forint j0 jcol j rowvectorpush backicolj1 array2push backrowvector return 0my question is are there other ways to define the 2d array which one is the most efficient one thanks,['c++'] +359547,android pass parameter to native activity my android application compirises two activities mainactivity and androidappnativeactivity the latter is implemented purely in c on button click in mainactivity i start a native one trying to pass some parameterspublic void pressedbuttonview view intent intent new intentthis androidappnativeactivityclass intentputextramy param 1 123 intentputextramy param 2 321 startactivityintenthow do i get my param 1 and my param 2 from within androidappnativeactivitys entry point that is a cfunction void android mainstruct android app state,['android'] +359568,using vim is there a command to have pasted text automatically linewrapped context part of a job i am doing involves pasting paragraphs of text from a word doc into a ruby fileproblem these paragraphs are getting pasted in as a single very long line of text and i have to manually insert newlines to make the lines of reasonable length solution is there a way to make the pasting function aware of reasonable margin limits and wrap the text when i paste it in,['ruby'] +359573,faraday vs httparty faraday is the ruby http client library of choice why is it preferable to use it over httpartysome things that i would like compared areperformancearchitectureease of usefeatures existing in faraday that is not in httparty or vice versaanything else that makes faraday the library of choice,"['ruby-on-rails', 'ruby']" +359588,java http post request i have to do post request to a webservice to authenticating the user with username and passwordi have a problem with following post requestpublic string postteststring action connectionparametrdata parameters uribuilder builder new uribuilderschemeschemeauthorityauthoritypathaction uri builderbuild bufferedreader in null string ans null httppost request new httpposturitostring httpclient defaultclient new defaulthttpclient try requestsetheadercontenttype applicationxwformurlencoded requestsetentitynew urlencodedformentitygetvaluepairsparameters httpresponse response defaultclientexecuterequest in new bufferedreadernew inputstreamreaderresponsegetentitygetcontent utf8 8192 stringbuffer sb new stringbuffer string line string newline systemgetpropertylineseparator whileline inreadline null sbappendline newline ans sbtostring catch unsupportedencodingexception e todo autogenerated catch block eprintstacktrace catch clientprotocolexception e todo autogenerated catch block eprintstacktrace catch ioexception e todo autogenerated catch block eprintstacktrace return ans when i executed this method server throws error telling the request is not a post requestbut this method work perfectlyprivate string makepoststring action connectionparametrdata parameters throws ioexception stringbuilder urlbuild new stringbuilder urlbuildappendschemeappendwappendauthorityappendaction url url new urlurlbuildtostring urlconnection urlconnection urlopenconnection urlconnectionsetdoinputtrue urlconnectionsetdooutputtrue urlconnectionsetusecachesfalse urlconnectionsetrequestpropertycontenttype applicationxwformurlencoded dataoutputstream printout new dataoutputstreamurlconnectiongetoutputstream string content getparametersparameters printoutwritebytescontent printoutflush printoutclose bufferedreader in null in new bufferedreadernew inputstreamreaderurlconnectiongetinputstream 8192 stringbuffer sb new stringbuffer string line string newline systemgetpropertylineseparator whileline inreadline null sbappendline newline inclose return sbtostring i prefer to use httpclient than urlconecctiondoes anybody know why first method is not approved as post,['java'] +359627,integer division is ab intab true for all integers ab i know that integer division will always return the same answer as truncation of a floating point result if the numbers are both positive is it true if one or both of them are negativei was just curious to know if there was an integer division expression that would return the same results in python 2 and python 3 and yes i know about from future import divisionps let us ignore floating point overflow for the moment,['python'] +359629,loading youtube iframe api with requirejs i am trying to use the youtube iframe api inside a module definded with require js as this api is loaded async and calls a function once is loaded i used a requirejs plugin called async that worked before with google maps apihowever this time something is not working my module starts this waydefinetextfmwkwidgetsvideovideohtmlfmwkutilsbrowserasync api function videotplroot and chrome console fires this erroruncaught error load timeout for modules async api unnormalized3async apiif i do not use async plugin the object yt or its functions are undefinded and the same happens if i download the api code the api is loaded sometimes if i put an script tag in the head tag of the html file all this is expected but i do not understand because async plugin failsthank you for your attention and help,['javascript'] +359665,when rotating shape it stays together with the rotated one i am a student and i am new around here i have a course project to make a paintlike program i have a base class shape with drawself contains ect methods and classes for rectangle ellipse and triangle for now also i have two other classed thisplayproccesor which is class for drawing and dialogprocessor which controls the dialog with the user theese are requirements for the project public class thisplayprocessor public thisplayprocessor summary list of shapes summary private listshape shapelist new listshape public listshape shapelist get return shapelist set shapelist value summary redraws all shapes in shapelist summary public void redrawobject sender painteventargs e egraphicssmoothingmode smoothingmodeantialias drawegraphics public virtual void drawgraphics grfx int and shapelistcount shape shape for int i 0 i and 1 i shape shapelisti drawshapegrfx shape public virtual void drawshapegraphics grfx shape item itemdrawselfgrfx and heres the other onepublic class dialogprocessor thisplayprocessor public dialogprocessor private shape selection public shape selection get return selection set selection value private bool isdragging public bool isdragging get return isdragging set isdragging value private pointf lastlocation public pointf lastlocation get return lastlocation set lastlocation value public void addrandomrectangle random rnd new random int x rndnext100 10 int y rndnext100 600 rectangleshape rect new rectangleshapenew rectanglex y 100 200 rectfillcolor colorwhite shapelistaddrect so i want to rotate one shape which is selected by the useri try like this it rotates it but i get this public class rectangleshape shape public override void drawselfgraphics grfx grfxtranslatetransformrectanglex rectanglewidth 2 rectangley rectangleheight 2 grfxrotatetransformbaserotationangle grfxtranslatetransform rectanglex rectanglewidth 2 rectangley rectangleheight 2 grfxfillrectanglenew solidbrushfillcolor rectanglex rectangley rectanglewidth rectangleheight grfxdrawrectanglepensblack rectanglex rectangley rectanglewidth rectangleheight grfxresettransform,['c#'] +359669,zurb foundation 3 full width sections change max width im using zurb foundation 3 on a project of mine i love grid systems and responsive sites but my issue is i still strongly believe they should be built wider then 10pxi have a few questions1 first off i would love to make certain sections divs full width now i have read i can just replace div classrow with div classcontainer for instance and it will generate that effect now for some reason this does not feel right should i just create my own class thats full width or what would be the proper way to do this2 i would love to have it based for a larger resolution maybe a max 1440px wide or even a fluid 100 full width how could i go about doing this andor is foundation not the correct framework for me i love the fact it comes with all the templates so is super quick and friendly to do mockupsthanks in advance,['css'] +359694,how to debughandle intermittent authorization denied and thisk io errors when adding sql store to an nspersistentstorecoordinator i have an app in the app store and am using a logging service to get crash logs and associated log data i am seeing an intermittent crash low of users affected and low of crashes per user but it is baffling mewhat happens in these crashes is the followingapp launches and initializes core data stackapp attempts to add a sql store to the nspersistentstorecoordinator with the following code storeurl is validnsdictionary options nsmigratepersistentstoresautomaticallyoption yes nsinfermappingmodelautomaticallyoption yessqlstore persistentstorecoordinator addpersistentstorewithtypenssqlitestoretype configurationnil urlstoreurl optionsoptions errorerrorone of the following errors occur when adding this storenserrordomainnscocoaerrordomain code256 the operation couldnat be completed cocoa error 256 userinfo0x1dd946a0 nsunderlyingexceptionauthorization denied nssqliteerrordomain23ornserrordomainnscocoaerrordomain code256 the operation couldnat be completed cocoa error 256 userinfo0xc6525d0 nsunderlyingexceptionthisk io error nssqliteerrordomain10after this condition the app will crash bc the sql store is required for the app to function i could attempt to gracefully handle this failure by trying a new storeurl but i do not want the user to lose existing data also i have never personally reproduced this issue and based on the low number of users affected and crash logs i believe it is a low impact problem and does not recur on a subsequent app launchi am hoping there is a core data guru out there with some suggestions on how to debug and preventhandle these conditions my core data stack initialization code is straight from the xcode project generator and i have ruled out any concurrency issues in that the persistent store coordinator is only initialized once on launch and this error occurs in this initializationhappy to provide more codeinfo if relevantthanks,['ios'] +359697,turning ckeditor 4 inline editing on and off with javascript i need to be able to toggle inline editing onoff with a button see here for example of inline editing my markup is as sodiv contenteditabletruemycontentdivusing jquery i want to be able to turn onoff the editori have tried setting contenteditable to false but this does not work the editor is not loading back into the page on toggling the contenteditable settingaddendum i also needed to destroy all ckeditor inline instances on a button click here is how i did that kill all ckeditors fork in ckeditorinstances var instance ckeditorinstancesk instancedestroy,"['javascript', 'jquery']" +359708,jquery check for empty tds and if all empty hide the parent tr i would like to check for empty tds classes ah only and if all are empty then i would like to hide the parent tr the issues i am running into are my empty tds contain i am not sure how to test for thosetable tr td classrequirementrightrequirementtd td classanbsptd td classbnbsptd td classcnbsptd td classdnbsptd td classenbsptd td classfnot emptytd td classgnbsptd td classhnbsptd tr tr td classrequirementrightrequirementtd td classanbsptd td classbnbsptd td classcnbsptd td classdnbsptd td classenbsptd td classfnbsptd td classgnbsptd td classhnbsptd traif tdaempty tdbempty tdcempty tddempty tdeempty tdfempty tdgempty tdhempty hide the parent tr a,"['jquery', 'html', 'css']" +359731,ninject bindings for a thispatcher implementation of an interface i have an interfacepublic interface iservice void dostuffint parm1 string parm2 guid gimmeabreakitsanexampleki would like to configure ninject v3 bindings so that i can have a thispatcher shuffle method calls out to multiple instances of iservice like sopublic sealed class thispatcherservice iservice private ienumerableiservice children public thispatcherserviceienumerableiservice children this children childrentolist public void dostuffint parm1 string parm2 guid gimmeabreakitsanexamplek foreachvar child in this children childdostuffparm1 parm2 gimmeabreakitsanexamplek however my bindings that look like this wind up throwing an exception at runtime indicating a cyclic dependencythisbindiservicetothispatcherservicethisbindiservicetosomeotherservice wheninjectedexactlyintothispatcherservicethisbindiservicetoyetanotherservice wheninjectedexactlyintothispatcherserviceis this possible if so what am i doing wrong can the ninja escape this cyclical dependency doom,"['c#', '.net']" +359766,java regex pattern matching first occurrence of aboundarya after any character sequence i want to set a pattern which will find a capture group limited by the first occurrence of the aboundarya but now the last boundary is usedegstring text this should match from a to the first b and not 2nd b got thatpattern ptrn patterncompilebabbmatcher mtchr ptrnmatchertextwhilemtchrfind string match mtchrgroup systemoutprintlnmatch match printsmatch a to the first b and not 2nd band i want it to printmatch a to the first bwhat do i need to change within the pattern,['java'] +359803,determine if date range falls between another date range sql i am trying to find out if there is a way in sql tsql preferred to identify if a date range falls between another date rangefor purposes of my exampledaterange1 i have a defined date range dates are 112012 152012daterange2 i have two other dates to work with lets say 132012 and 142012i am trying to have this to use in a case statement for something like thiscase when daterange1 0 then result1 when daterange2 falls within daterange1 then result2 end as datestuff is this possible in sql i am really stumped on this one i know how to figure out if a single date falls between a range but how can it be done with a date range the answer doesnt necessarily need to be in a case statement but it is preferred,['sql'] +359892,can memset be parallelized on 4 cores i am not sure to that can i write a large memset for example 10 mb on four cores to gain speedup with this is such ramchip parallelization possible at all and also how big are time costs of firing other threads is it more than a millisecond or less,['c'] +359965,actionbarsherlock androidridhome when i used actionbarsherlockpublic boolean onoptionsitemselectedmenuitem item switch itemgetitemid case androidridhome thisfinish return true default return superonoptionsitemselecteditem i notice that androidridhome is from api 11how can we make sure androidridhome is right on api 8,['android'] +360018,naming restrictions of variables in java why are special characters except not allowed in java variable names,['java'] +360037,skip ordered list item numbering i have an ordered list and i would like to skip the number output from a particular itemtraditional output1 list item2 list item3 list item4 list item5 list itemdesired output1 list item2 list item skipped list item3 list item4 list item5 list itemis this achievable in css i thiscovered an ol start attribute that i did not know about before but does not seem to help me,"['html', 'css']" +360042,difference between invoke and dynamicinvoke what is the difference between invoke and dynamicinvoke in delegates please give me some code example which explain difference between that two methods,"['c#', '.net']" +360075,how to put gridview inside scrollview i have to design layout such that whole layout should scroll and inside layout i have to thisplay related content in grid form so i decided to use gridviewbut problem is that iam unable to use gridview inside scrollview i have read documentationdocumentation also saying that we should not use gridview inside scrollview alsobut i have to do thisso can any please give me some idea about thisthanks,['android'] +360106,why the hashes in dapper sample i am just reading this sample from the dapper manualconnectionexecute set nocount on create table ti int set nocount off insert t select a a union all select b set nocount on drop table t new a1 b2 isequalto2are the ts a special syntax for something or are they just there to confuse me,['c#'] +360108,why does cpplint thiscourage streams i was just playing around with cpplint and tried running it on some code i had written for fun i realized that the following lines were flagged with the error message include iostreaminclude fstreamyoohoocpp3 streams are highly thiscouraged readabilitystreams 3yoohoocpp5 streams are highly thiscouraged readabilitystreams 3i am curious about why using streams is thiscouraged,['c++'] +360138,kernel module init and exit functions being called in wrong order i am making a very simple hello world kernel module and getting some crazy behavior this worked until i upgraded to kernel 338 and now it well it is calling the init function on exit and the exit function on initialize i have made sure my names are correct needed for module definitionsinclude linuxmoduleh needed for initilization modulesinclude linuxinith must declare some licensemodule licensedual bsdgpl function to be called on insmod returns 0 on succestatic int init mymod initvoid prints kernel alert check varlogsyslog printkkern alert module was loaded this is the printk return 0 function to be called on rmmodstatic void exit mymod exitvoid prints kernel alert check varlogsyslog printkkern alert module was unloaded this is the printk register these functionsmodule initmymod initmodule exitmymod exitsample outputrootcop4610homecop4610downloadslinux338mymodule insmod mymoduleko rootcop4610homecop4610downloadslinux338mymodule tail varlogsyslog oct 12 100820 cop4610 kernel 633567832 module was unloaded this is the printkthe following is a video of this happening livefeatureyoutube,['c'] +360143,how to see full exception stack trace when running java app from console while running java app from console i got an exception that contains following line 5 moreis it possible to see a full trace is there any cmd argumentthanks,['java'] +360175,is there a way to get thistinct partionkeys from a table currently i am using the partitionkey to differentiate devices that are storing data into azure table services i would like to build a viewer that allows me to browse that data but it would be nice to be able to structure it so i can view data by device or by partitionkey the viewer app would not have any knowledge of what devices exist so it would be great if i could somehow get back a list of thistinct partionkeys in a given table is this possible or am i going to be relegated to creating a metadata table into which i insert a new row for each device then use that for querying,['.net'] +360209,strange borderwidth behavior in chrome floating point borderwidth certain fluid designs especially those involving width iframes seem to cause some strange roundingtype errors in chrome i have got version 21this fiddle demonstrates the problem set the border to an integer pixel value and the values you get back when you ask for them are floating point numbers slightly smaller than the expected valuetrying the exact same code in codepen does not yield the same results presumably because the iframe and other styles around it are not set up the same wayi have also seen this behavior for the basic width and height attributes although i was unable to replicate that part of the problem in jsfiddlethis does not seem to be a problem in firefox or in ie8any ideas as to what specifically is causing this strange behavior and how i can work around it to get at the real valuesthe plot thickens in an attempt to shim around the problem i found that values over 10px do not appear to be subject to the issuealso based on gionafs comment it appears to work properly in chrome 22,['css'] +360242,android logcat does not show anything in intellij idea logcat output is emtpy in intellij idea what to doan application is running live wallpaper log level is verbose device is chosen correctly adb and usb debugging are enabled,['android'] +360256,nslayoutconstraints and setting the widthheight of a view dynamically i have a question about setting the size of a view to which i am applying some layout constraintshow can i define the size of the view without defining its framei am trying to create a view that has its height fixed and has an origin at the screen origin it fills the width of the view so that when the device rotates the view extends to the width of the screen this is what i have got so farselfcontainerview hittestcontainerview alloc initselfcontainerview setbackgroundcoloruicolor redcolorselfview addsubviewselfcontainerviewnsdictionary viewsdictionary viewselfcontainerviewnsarray verticalconstraints nslayoutconstraint constraintswithvisualformatv50view250 options0 metricsnil viewsviewsdictionarynsarray horizontalconstraints nslayoutconstraint constraintswithvisualformathview options0 metricsnil viewsviewsdictionaryselfview addconstraintsverticalconstraintsselfview addconstraintshorizontalconstraintsthe problem is i cannot get anything to show up on the screen unless i set the frame of that containerview what is the correct way to do this without using interface builder,"['objective-c', 'ios']" +360276,using requirejs without datamain can i use requirejs in development without using the datamain attribute to load in my initial script ie script datamainscriptsmain srcscriptsrequirejsscript i am finding it difficult for me to work with this attribute in my development environment,['javascript'] +360277,mod rewrite exception for a specific file my page is not redirecting as it should due to my htaccess file which is set asrewriteengine on rewritecond 1 indexphpresourcesrobotstxt rewritecond request filename f rewritecond request filename d rewriterule indexphp1 lqsa i use this setup for my mvc framework so i get urls like controllermethodargument however when i redirect to forumloginphp it cuts to forumhow can i add this as an exception so that i will be able to redirect to forumloginphpi found another htaccess in my forum directory could this be causing the problem as well begin punbbifmodule mod rewritec multiviews interfers with proper rewriting options multiviews rewriteengine on uncomment and properly set the rewritebase if the rewrite rules are not working properly rewritebase rewritecond request filename f rewritecond request filename d rewriterule rewritephp lifmodule,['php'] +360303,duplicate apple apns push notifications weve been using apns on our app without much incident for some time now and suddenly our users are reporting receiving the same push notification multiple timesi have confirmed tediously that our servers are only sending the notification payloads to apple once and yet the notification produces 2 and sometimes 3 identical alerts both in the banner and notification centerthis has been observed in both ios5 and ios6has anybody seen this phenomenon before am i perhaps missing some opportunity to add a unique identifier to the payload that will prevent apple from sending duplicate notifications to the device googles c2dm has collapse key for this sort of thing but i can find no reference to a similar functionality in apns,"['php', 'iphone', 'ios']" +360312,complex query with django posts from all friends i am new to python and django so please be patient with mei have the following modelsclass usermodelsmodel name modelscharfieldmax length 50 class postmodelsmodel userby modelsforeignkeyuser related namepost user userwall modelsforeignkeyuser related namereceive user timestamp modelsdatetimefield post modelstextfieldclass friendmodelsmodel user1 modelsforeignkeyuser related namerequest user user2 modelsforeignkeyuser related nameaccept user isapproved modelsbooleanfield class meta unique together user1 user2 i know that this may not be the besteasiest way to handle it with django but i learned it this way and i want to keep it like thisnow all i want to do is get all the post from one person and it is friends the question now is how to do it with the django filtersi think in sql it would look something like thisselect p form post p friend f where puserbytheuser or fuser1theuser and fuser2puserby or fuser2theuser and fuser1puserbywith no guarantee of correctness just to give an idea of the result i am looking for,['python'] +360313,how to remove surrogate characters in java i am facing a situation where i get surrogate characters in text that i am saving to mysql 51 as the utf16 is not supported in this i want to remove these surrogate pairs manually by a java method before saving it to the databasei have written the following method for now and i am curious to know if there is a direct and optimal way to handle this thanks in advance for your helppublic static string removesurrogatesstring query stringbuffer sb new stringbuffer for int i 0 i querylength 1 i char firstchar querycharati char nextchar querycharati1 if characterissurrogatepairfirstchar nextchar false sbappendfirstchar else i if characterishighsurrogatequerycharatquerylength 1 false characterislowsurrogatequerycharatquerylength 1 false sbappendquerycharatquerylength 1 return sbtostring,['java'] +360318,long to xmlgregoriancalendar and back to long i am trying to convert from millisecond time stamp to xmlgregoriancalendar and back but i seem to be getting wrong results am i doing something wrong it seems i am gaining days time stamp 01jan01 0 long ts 6213574080l systemoutprintlnts systemoutprintlnnew datets sat jan 01 0 pst 1 cool to gregorian calendar gregoriancalendar gc new gregoriancalendar gcsettimeinmillists to xml gregorian calendar xmlgregoriancalendar xc datatypefactorynewinstancenewxmlgregoriancalendargc back to gc gregoriancalendar gc2 xctogregoriancalendar to timestamp long newts gc2gettimeinmillis systemoutprintlnnewts 621355680 uh systemoutprintlnnew datenewts mon jan 03 0 pst 1 where did the extra days come from,['java'] +360319,python mysqldb get the result of fetchall in a list i would like to get the result of the fetchall operation in a list instead of tuple of tuple or tuple of dictionaries for example cursor connectioncursor cursor could be a normal cursor or dict cursorquery select id from bscursorexecutequeryrow cursorfetchallnow the problem is the resultant row is either 123234 or id123 id234what i am looking for is 123234 or 123234 i am trying to avoid the manually looping over the items thanks in advance,['python'] +360339,fragment removeglobalonlayoutlistener illegalstateexception i am trying to get the height and width of an imageview in a fragment with the following viewtreeobserverimport androidviewviewtreeobserverimport androidviewviewtreeobserverongloballayoutlistenerprivate imageview imageviewpictureoverridepublic view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate view view inflaterinflaterlayoutfragment general activity add recipe container false sethasoptionsmenutrue final viewtreeobserver observer imageviewpicturegetviewtreeobserver observeraddongloballayoutlistener new ongloballayoutlistener override public void ongloballayout observerremoveglobalonlayoutlistenerthis return viewrunning this code results in the following exception1012 234526145 eandroidruntime12592 fatal exception main1012 234526145 eandroidruntime12592 javalangillegalstateexception this viewtreeobserver is not alive call getviewtreeobserver again1012 234526145 eandroidruntime12592 at androidviewviewtreeobservercheckisaliveviewtreeobserverjava5091012 234526145 eandroidruntime12592 at androidviewviewtreeobserverremoveglobalonlayoutlistenerviewtreeobserverjava3561012 234526145 eandroidruntime12592 at comthimmeyrezepteaddrecipeactivity generalfragment1ongloballayoutaddactivity generalfragmentjava831012 234526145 eandroidruntime12592 at androidviewviewtreeobserverthispatchongloballayoutviewtreeobserverjava5661012 234526145 eandroidruntime12592 at androidviewviewrootimplperformtraversalsviewrootimpljava17361012 234526145 eandroidruntime12592 at androidviewviewrootimplhandlemessageviewrootimpljava26441012 234526145 eandroidruntime12592 at androidoshandlerthispatchmessagehandlerjava991012 234526145 eandroidruntime12592 at androidoslooperlooplooperjava1371012 234526145 eandroidruntime12592 at androidappactivitythreadmainactivitythreadjava45171012 234526145 eandroidruntime12592 at javalangreflectmethodinvokenativenative method1012 234526145 eandroidruntime12592 at javalangreflectmethodinvokemethodjava51012 234526145 eandroidruntime12592 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava9931012 234526145 eandroidruntime12592 at comandroidinternaloszygoteinitmainzygoteinitjava7601012 234526145 eandroidruntime12592 at dalviksystemnativestartmainnative methodthe documentations says that removeglobalonlayoutlistener is deprecated but if i use removeongloballayoutlistener as suggested i get an undefined error what i am doing wrong,['android'] +360341,programmatic access to java documentation is there an api to programmatically access to the java documentation something similar to what editorsides like eclipse do for intellisense surely the javadoc generated html can be parsed and indexed but would be great to know if something already exists as a standalone package updateto be clear i am trying to get a programmatic access to the documentation for the java language implementation however there is not an easy way out but you have to get the openjdk from oracles site and then do make docs and supply some doclet to get the output in nonhtml form this is what i was trying to avoid from the beginning so i am reading all the makefiles now trying to figure out why platform is not being resolved and source build is failingwhat i finally settled withscraping html docs yep realized that would get my job doneimport urllib2import pymongomongo pymongoconnectionlocalhostmongo db mongoapi dbmongo collection mongo dbapi collectionurlurl range 271def getpageelementsurl contenturllib2urlopenurlread from beautifulsoup import beautifulsoup soup beautifulsoupcontent elements soupdl return elementsdef savepageelementselements for i in elements0 try entrytype descriptionstrifindnextdtsplit1split0 ifindnextafindnextarendercontents signatureifindnextafindnextarendercontentsifindnextbrendercontents description ifindnextddrendercontents print entry insert id mongo collectionsaveentry except passdef retrievestr mongo documents mongo collectionfind signature str type descriptionmethod of javaioprintstream for this document in mongo documents print this documentif name main for i in range1url range urlurlstrihtml print processing url elementsgetpageelementsurl print elements0 savepageelementselements retrieveprintlnstringbut take a look at dexy if i could have managed to build openjdk on ubuntu without issue it would have generated nice json to play with,['java'] +360350,game programming and quantity of timers i have made a simple 2d game engine using c and directx and it is fully functional for the demo i made to test it i have a timer object that uses queryperformancecounter and i do not know whats the better choice use only one timer in the game loop to update everything in the game or an independent timer in every object that needs onemy worry is that when i try to implement threads what will happen with timers what happens with the sync,['c#'] +360352,can we use regex in symfony2 access control can we use regex in access control in symfony2 security1 fooid role admin2 fooidprofile is authenticated anonymouslyanother issueif i removed the access control from my security still it goes to the security module and try to authenticate from securityauthenticationproviderauthprovidewhat should be the ideal behavior i think it should not authenticate the resource if no access control is in securityymlmy firewall configuration is firewalls main pattern anonymous true myapp true,['php'] +360392,how to change itemspaneltemplate wrapgrid from xaml code i am trying to modify the maximumrowsorcolumns property of my wrapgrid like thisgridviewitemspanel itemspaneltemplate wrapgrid xnamewrapgriditems orientationvertical maximumrowsorcolumns1 itemspaneltemplategridviewitemspaneland then i am using this code to change the wrapgridvisualstate xnamesnapped storyboard objectanimationusingkeyframes storyboardtargetnamewrapgriditems storyboardtargetpropertymaximumrowsorcolumns thiscreteobjectkeyframe keytime0 value1 objectanimationusingkeyframes objectanimationusingkeyframes storyboardtargetnameheadertext storyboardtargetpropertytext thiscreteobjectkeyframe keytime0 valuepins objectanimationusingkeyframes storyboardvisualstatebut i am getting the errorwinrt information cannot resolve targetname wrapgriditemshow should i refer to the wrapgrid in the objectanimationusingkeyframes storyboardtargetname property,['c#'] +360437,how to add a button on the right side of the toolbar i created a toolbar programmaticallyuitoolbar boolbar uitoolbar new boolbarbarstyle uibarstyledefault boolbartintcolor uicolor orangecolor boolbar sizetofitand then added a button to ituibarbuttonitem cancelleftbarbutton uibarbuttonitem allocinitwithtitleok styleuibarbuttonitemstylebordered targetself actionselectortapbackgroundcancelleftbarbuttontintcolor uicolor orangecolornsarray array nsarray arraywithobjectscancelleftbarbutton nilboolbar setitemsarray animatedyeshowever this button appears only at the left side of the toolbar is it possible to put it on the right side of the toolbar,"['iphone', 'objective-c', 'ios']" +360439,run php file in windows cmd i wanna run a php file in windows cmdi have follow this suggestion php is not recognized as an intern command using windowsbut not working i am trying to do in command program cwindowssystem32cd myfolderthen it enter in my folder like cphpbut when i enter my my php file address like cmyfolderphp filephp it just showing error php is not recognized as internal or externalbut when i try without php command like cmyfolderfilephp it just open in notepad but i wanna run it in cmd how can be it possible,['php'] +360444,operator differet behaviour on wrapper class object can any body explain me what is happeing in the output if is use to compare two ref variable it simply check its reference if they are same then it enter in if body then why the hell aabb is equal if creting static method valueof and eeff is not equal which is ok if creating its object using new keyword static void mainstring args integer aa integervalueof12 integer bb integervalueof12 ifaabbsystemoutprintlnaabb ifaabbsystemoutprintlnaabb integer ee new integer12 integer ff new integer12 ifeeffsystemoutprintlneeff ifeeffsystemoutprintlneeffoutput aabbeeff,['java'] +360460,what does the css rule clear both do what does the following css rule doclear clear both and why do we need to use it,['css'] +360495,changing uiimage color i am trying to change color of uiimage my codeuiimage coloredimageuiimage firstimage withcoloruicolor color uigraphicsbeginimagecontextfirstimagesize cgcontextref context uigraphicsgetcurrentcontext color setfill cgcontexttranslatectmcontext 0 firstimagesizeheight cgcontextscalectmcontext 10 10 cgcontextsetblendmodecontext kcgblendmodecopy cgrect rect cgrectmake0 0 firstimagesizewidth firstimagesizeheight cgcontextdrawimagecontext rect firstimagecgimage cgcontextcliptomaskcontext rect firstimagecgimage cgcontextaddrectcontext rect cgcontextdrawpathcontextkcgpathelementmovetopoint uiimage coloredimg uigraphicsgetimagefromcurrentimagecontext uigraphicsendimagecontext return coloredimgthis code works but obtained image is not so well as shoud be bounds pixels of returned image are intermittent and not so smooth as in my first image how can i resolve this problem,"['iphone', 'objective-c', 'ios']" +360498,doubleclick on a row in listview is there any possibility to get a value of doubleclicked row in listviewi registered an event private void lvlista doubleclickobject sender eventargs e messageboxshowlvlistaselecteditemstostring but on message when i doubleclick some row in listview i get systemwindowsformslistviewselectedlistviewitemcollectionwhat is more i have got 2 columns in listview lvlistacolumnsaddid lvlistacolumnsaddtilteand i want to show in messagebox the id of doubleclicked row how to do it how to get a values from this event,"['c#', '.net']" +360517,difference between spring txadvice and spring aop pointcut i am new to spring with working knowledge of hibernatemy job was to implement transaction by using spring declarative approachand successfully i did with the help of google thanks to google but not able to understand clearly about the terms i used in applicationcontextxml1 txadvicetxadviceaopconfig here is point cut were declaredaopconfigcan somebody explain me about above point meanwhile i am trying to understand it from the google also,['java'] +360552,eclipse open declaration that is defined in a library in eclipse if i press f3 or open declaration on a reference that is in one of my libraries it opens a read only copy of the codei thought this quite useful at first as reminds me that it is library code and changes could affect more projects but i find it a pain to have to go and manually find the java file if i do want to editcan i either a make it always open the related java file or b once readonly copy is open quickly get to the editable java file,['java'] +360573,c web browser select list item click i am trying to select item from select list box using this method var elements webbrowser1documentgetelementsbytagnameselect foreach htmlelement element in elements if elementgetattributeidpagesize elementgetelementsbytagnameoption2setattributeselected selected webbrowser1documentinvokememberclick from this html codeselect namepagesize idpagesize onchangechangefilelistrequestsize option value1010 files per pageoption option value25 selectedselected25 files per pageoption option value5050 files per pageoption option value100100 files per pageoption option value200200 files per pageoption selectitem is actually changes but that is does not execute onchangechangefilelistrequestsize javascript eventhow to simulate select list item click or change,['c#'] +360579,how can i get the right relative paths in my compiled less css files i am having a problem with less breaking relative urls in my compiled files for example i havea stylelessa stylecssa assetsa a imga a a bgpnga a lessa a a includedlestyleless imports includedless which has the following linebody background urlimgwalltexturepngbut the output in stylecss becomesbody background urlassetslessassetslessimgwalltexturepngwhats going on here and how can i fix this so that my paths remain correct after compiling i realize that perhaps my relative path in includedless needs to be adjusted and that is fine but currently with how less is doubling assetsless it makes it extremely convoluted to get the right path while maintaining a reasonable folder structure besides that i am using git submodules to include different less projects so i do not really want to change either the code in the less files or the folder structure i just want to coerce less into compiling correctly i have tried all of the windows compilers i can find and they all behave the sameany help greatly appreciated,['css'] +360589,effective development and maintenance of largescale css for multilanguage websites consider this scenario you are developing a multilingual web application if all of languages you are targeting are either ltr or rtl you have no need for languagespecific css rules however if your target languages are a mix of ltr and rtl languages you need to specify the pages readingdirection for each languageif you add dirltr or dirrtl to the body element you logically should expect it should do the necessary magicshowever you actually need to switch all right and left settings in rules such as textdirection and margin you also need to change rules like margin 0 10px 0 20px to margin 0 20px 0 10pxthe w3c standard could avoid this issue by permitting two more values for directionrelated rules in other words instead of right and left as in marginright and marginleft they could allow something like the followingdivfoo marginnear 100px this would be equivalent to marginleft in ltr and marginright in rtl divbar marginfar 100px this would be equivalent to marginright in ltr and marginleft in rtl in essence in all rulesvalues where you can currently enter a left or right directionbased word you could instead write a near or fargiven the current weaknesses in the current version of css i am looking for some suggestions to streamline the creation and maintenance bidirection large webapps,['css'] +360593,is there an arbitrary precision floating point library for cc which allows arbitrary precision exponents i am looking for an arbitrary precision floating point library for cc plain c is preferred i need arbitrary precision exponents gmp and mpfr use fixed size exponents so they are ineligible i have some ideas for workarounds but i prefer an outofthebox solution it would be an nice feature if the exponent precision can be adjusted automatically to prevent infinityvaluesif you know for sure that such an library does not exist please say so,"['c++', 'c']" +360595,how to build pdf file from binary string returned from a webservice using javascript i am trying to build a pdf file out of a binary stream which i receive as a response from an ajax requestvia xmlhttprequest i receive following datapdf14hole data representing the file eofwhat i tried so far was to embed my data via dataurinow there is nothing wrong with itit works fine unfortunately it does not work in ie9 and ffpossible reason may be that ff and ie9 have there problems with this usage of the dataurinow i am looking for any solution that works for all browsersheres my code responsetext encoding pdftextbase64decodetrimpdftext now pdftext contains pdf14 data eofvar winlogicalname detailpdfvar winparams dependentyeslocationbarnoscrollbarsyesmenubaryes resizablescreenx50screeny50width850height1050var htmltext embed width100 height100 typeapplicationpdf srcdataapplicationpdf escapepdftext embed open pdf in new browser window var detailwindow windowopen winlogicalname winparams detailwindowdocumentwrite htmltext detailwindowdocumentclose as i said it works fine for opera and chrome safari not testedusing ie or ff will bring up a blank new windowis there any solution like building a pdf file on file systemin order to let the user download iti need a solution that works in all browsersat least in ie ff opera chrome and safarii have no permission to edit the webservice implementation so it had to be a solutionat clientsideany ideas,"['javascript', 'jquery']" +360638,sql native client 10 performance miserable due to serverside cursors we have an application that uses odbc via cdatabasecrecordset in mfc vs2010we have two backends implemented mssql and mysqlnow when we use mssql with the native client 100 retrieving records with select is dramatically slow via slow links vpn for example the mysql odbc driver does not exhibit this nasty behaviorfor examplecrecordset rm dbropencrecordsetsnapshot lselect asomething bsthelse from tablea as a left join tableb as b on aidbrefrmovefirstwhileriseof retrieve cstring strdata crsgetfieldvaluelasomething strdata crsmovenextnow with the mysql driver everything runs as it should the query is returned and everything is lightning fasthowever with the mssql native client things slow down because on every movenext the driver communicates with the serveri think it is due to serverside cursors but i did not find a way to thisable them i have tried usingsqlsetconnectattrm dbm hdbc sql attr odbc cursors sql cur use odbc sql is integerbut this did not help either there are still longrunning execs to sp cursorfetch et al in sql profileri have also tried a small reference project with sqlapi and bulk fetch but that hangs in fetchnext for a long time too even if there is only one record in the resultsetthis however only happens on queries with left joins tablevalued functions etcnote that the query does not take that long executing the same sql via sql studio over the same connection returns in a reasonable timequestion1 is is possible to somehow get the native client to cache all results locally use local cursors in a similar fashion as the mysql driver seems to do itmaybe this is the wrong approach altogether but i am not sure how else to do thisall we want is to retrieve all data at once from a select then never talk the server again until the next querywe do not care about recordset updates deletes etc or any of that nonsense we only want to retrieve datawe take that recordset get all the data and delete itquestion2 is there a more efficient way to just retrieve data in mfc with odbc,['sql'] +360680,speed performance of a qt program windows vs linux i have already posted this question here but since it is maybe not that qtspecific i thought i might try my chance here as well i hope it is not inappropriate to do that just tell me if it isiave developed a small scientific program that performs some mathematical computations iave tried to optimize it so that itas as fast as possible now iam almost done deploying it for windows mac and linux users but i have not been able to test it on many different computers yethereas what troubles me to deploy for windows iave used a laptop which has both windows 7 and ubuntu 1204 installed on it dual boot i compared the speed of the app running on these two systems and i was shocked to observe that itas at least twice as slow on windows i wouldnat have been surprised if there were a small difference but how can one account for such a differencehere are a few precisionsthe computation that i make the program do are just some brutal and stupid mathematical calculations basically it computes products and cosines in a loop that is called a billion times on the other hand the computation is multithreaded i launch something like 6 qthreadsthe laptop has two cores 173ghz at first i thought that windows was probably not using one of the cores but then i looked at the processor activity according to the small graphic both cores are running 100then i thought the c compiler for windows didnat the use the optimization options things like o1 o2 that the c compiler for linux automatically did in release build but apparently it doesiam bothered that the app is so mush slower 2 to 4 times on windows and itas really weird on the other hand i havenat tried on other computers with windows yet still do you have any idea why the differenceadditional info some dataaeven though windows seems to be using the two cores iam thinking this might have something to do with threads management hereas whysample computation na1 this one launches 2 qthreadspc1windows 733spc1linux 372spc2linux 136ssample computation na2 this one launches 3 qthreadspc1windows 684spc1linux 324spc2linux 106ssample computation na3 this one launches 6 qthreadspc1windows 835spc1linux 262spc2linux 047swherepc1windows my 2 cores laptop 173ghz with windows 7pc1linux my 2 cores laptop 173ghz with ubuntu 1204pc2linux my 8 cores laptop 220ghz with ubuntu 1204of course it is not shocking that pc2 is faster whats incredible to me is the difference between pc1windows and pc1linuxnote i have also tried running the program on a recent pc 4 or 8 cores 3ghz do not remember exactly under mac os speed was comparable to pc2linux or slightly fasteredit i will answer here a few questions i was asked in the commentsi just installed qt sdk on windows so i guess i have the latest version of everything including mingw the compiler is mingw qt version is 481i use no optimization flags because i noticed that they are automatically used when i build in release mode with qt creator it seems to me that if i write something like qmake cxxflags o1 this only has an effect in debug buildlifetime of threads etc this is pretty simple when the user clicks the compute button 2 to 6 threads are launched simultaneously depending on what he is computing they are terminated when the computation ends nothing too fancy every thread just does brutal computations except one actually which makes a not so smallcomputation every 30ms basically checking whether the error is small enoughedit latest developments and partial answershere are some new developments that provide answers about all thisi wanted to determine whether the difference in speed really had something to do with threads or not so i modified the program so that the computation only uses 1 thread that way we are pretty much comparing the performance on pure c code it turned out that now windows was only slightly slower than linux something like 15 so i guess that a small but not unsignificant part of the difference is intrinsic to the system but the largest part is due to threads managementas someone luca carlon thanks for that suggested in the comments i tried building the application with the compiler for microsoft visual studio msvc instead of mingw and suprise the computation with all the threads and everything was now only 20 to 50 slower than linux i think i am going to go ahead and be content with that i noticed that weirdly though the pure c computation with only one thread was now even slower than with mingw which must account for the overall difference so as far as i can tell mingw is slightly better than msvc except that it handles threads like a moronso iam thinking either thereas something i can do to make mingw ideally iad rather use it than msvc handle threads better or it just canat i would be amazed how could it not be well known and documented although i guess i should be careful about drawing conclusions too quickly iave only compared things on one computer for the moment,['c++'] +360688,how can i draw sound data from my wav file first off this is for homework or projecti am having trouble understanding the idea behind how to draw the sound data waves on to a graph in java for a projecti have to make this assignment entirely from scratch with a ui and everything so basically making a wav file editor the main issue i am having is getting the sound data into the graph to be drawn currently i have a randomly generated array of values just being drawn right nowso far i have a miniprogram running and validating the wav file for it to actually be a wav filei am reading it in with a fileinputstream and validating the riff bytes03 filelength47 wave bytes811 then the format chunk formatstarting from the end of the riff chunk and positioning the index to the end of it and giving format 03 length of format chunk 47 then the next 16 bytes for all the specifications of the wave file and storing those in their appropriate named variablesonce i get to the data chunk and its length past that is all my sound data and that is what i am unsure of how to store each byte for byte of sound data or even translate it to be value that is related to the amplitude of the sound i thought validating was similar so it would be the same but it does not seem to be that way either that or i have been complicating something super simple since i have been staring at this for a few days nowany help is appreciated thanks,['java'] +360699,image resizing in java to reduce image size i have an image of say dimensions 800x800 which has a size of 170 kb i want to resize this image to say 600x600 after resizing i want the image size to be reduced how can i do this,['java'] +360705,varargs in method overloading in java the following code does not compilepackage varargspkgpublic class main public static void testint i for int t 0 t ilength t systemoutprintlnit systemoutprintlnint public static void testfloat f for int t 0 t flength t systemoutprintlnft systemoutprintlnfloat public static void mainstring args test1 2 compilation error here quoted as follows a compiletime error is issuedreference to test is ambiguous both method testint in varargspkgmain and method testfloat in varargspkgmain matchit seems to be obvious because the parameter values in the method call test1 2 can be promoted to int as well as floatif anyone or both of the parameters are suffixed by f or f it compilesif we however represent the receiving parameters in the method signature with respective wrapper types as followspublic static void testinteger i systemoutprintlninteger arraysaslistipublic static void testfloat f systemoutprintlnfloat arraysaslistfthen the call to the method test1 2 does not issue any compilation error the method to be invoked in this case is the one that accepts one integer varargs parameter the first one in the preceding snippetwhy is in this case the error as in the first case not reported it appears that autoboxing and automatic type promotion are both applied here is autoboxing applied first so that the error is resolvedthe oracle docs saysgenerally speaking you should not overload a varargs method or it will be difficult for programmers to figure out which overloading gets calledthe last sentence in this link it is however for the sake of better understanding varargsalso to add below code compiles just finepublic class overloading public static void mainstring args load1 public static void loadint i systemoutprintlnint public static void loadfloat i systemoutprintlnfloat editthe following is the snap shot that indicates the compilation error i have created a new application therefore the package name is differenti am using jdk 6,['java'] +360730,get the first key and value pair from a hash table in ruby wierd results im just starting to learn rubyi am trying to get the first key and value key from a hash table in ruby i do not know the key values of the hash because it is passed to the method i cant find anywhere online how to find the first keyvalue as a separate hash table i think hash0 will just try to find an element with a name 0 it just returns nil when i run the code i know i can find the key name and the value and then create a new hash from them but i wonder if there is an easier way to do this so i get a hash right away here is my code ignore the ugly if else statements i will get rid of them soon def rps game winnergamerock in hash gameinvertrpaper in hash gameinvertpscissors in hash gameinvertsifrock in hash ifpaper in hash return paper in hash elsifscissors in hash return rock in hash end elsifpaper in hash ifrock in hash return paper in hash elsifscissors in hash return scissors in hash end end key gamekeys1 value gamevalues1 winner key value return winner endgame one bob p jim p puts rps game winnergame onethis gets me the correct result the problem is i dont understand why its 1 instead of zeroand i was hoping there was a better way to get the first keyvalue pair of a hash table instead of creating new hash table with the key and value you retrieved from the previous table,['ruby'] +360748,why a userwritten constructor affects the generated assembly test environment vs 2008 debug modetest code is a demo for return valueclass cpublic int value int value2 int value3 cint v0 valuev c getcint v c c1 return c1int main c c1 getc10 return 0and the asm output is 39 c c1 getc10push 10 0ahlea eax dword ptr t2595ebppush eaxcall getcyaavchz getcadd esp 8mov ecx dword ptr eaxmov dword ptr t2594ebp ecxmov edx dword ptr eax4mov dword ptr t2594ebp4 edxmov eax dword ptr eax8mov dword ptr t2594ebp8 eaxmov ecx dword ptr t2594ebpmov dword ptr c1ebp ecxmov edx dword ptr t2594ebp4mov dword ptr c1ebp4 edxmov eax dword ptr t2594ebp8mov dword ptr c1ebp8 eaxfrom the asm output we can see the compile create 2 temporary objecthowever when i define the constructor as followcint v0 valuev and recompiled the program the asm output is become 39 c c1 getc10push 10 0ahlea eax dword ptr c1ebppush eaxcall getcyaavchz getcadd esp 8obviously the compiler optimize the code and my question iswhy does adding the userwritten constructor affect the generated assembly so much,['c++'] +360777,unable to resolve ruby error missing psych whenever i run something with ruby on my server i get the following errorusrlocalrvmrubiesruby193p194libruby191yamlrb56in top requiredit seems your ruby installation is missing psych for yaml outputto eliminate this warning please install libyaml and reinstall your rubyi installed ruby using rvm onto my vpsiave tried installing the package libyaml as per instructed in other issues on stack overflow to no availiam not sure what type of system my vps is running but it doesnat have the aptget command it does have yuma,['ruby'] +360808,request to google texttospeech api i have this url ttsieutf8tlenqhelloworldwhen i put it to the address bar in a browser and hit enter i get mp3 file with synthesized speech saying hello world everything is correctbut now i have a link in html that redirects to this url like thisa href ttsieutf8tlenqhelloworldlinkawhen i click this link i do not get a file but an error simple quicktime logo could anyone explain me why is it so and how can i solve my problem,['html'] +360815,https requests in ruby is there a gem or library for https requests in ruby what is it called and can you provide some example usagewhat i am trying to do is open a page parse some text from it and then output it,['ruby'] +360817,runtime string concatenation evaluation according to jls1528 constant expressions an expression containing onlyiliterals of primitive type and literals of type string a3101 a3102 a3103a3104 a3105oriisimple names a6561 that refer to constant variables a4124oris a constant expressionnow string s1ab is a constant expression and will be evaluated to ab at compile timeso s1ab1 am i right in saying that now there are three objects in string pool as according to above statementababnow final string safinal string s1bstring s2ss1 is also constant expression and get evaluated at compile timethe above code will be transaled to s2ab after compilationso s2ab will be stored in string pool automaticallybut note there is no final nowstring sastring s1bstring s2ab constant expressionstring s3ss1 is not a constant expression and get evaluated at run timefor string s3ss1 the code will be translated to s3new stringbuilderstringvalueofsappends1tostringand will create a new string objecttherefore s2s3 will comes out to be falsedoes that mean result of string concatenation evaluated at runtime using stringbuilder not get stored in string pool but instead goes into heapoutside pool,['java'] +360839,get word from tap in uitextview i am trying to get a word from a tap the following functions sender is from the uigesture on the uitextview sentence ibactionprintwordselectedidsender nslogclicked cgpoint pos sender locationinviewselfview uitextview tv sentence nslogtap gesture coordinates 2f 2f posx posy eliminate scroll offset posy tvcontentoffsety get location in text from textposition at point uitextposition tappos tv closestpositiontopointpos fetch the word at this position or nil if not available uitextrange wr tvtokenizer rangeenclosingpositiontappos withgranularityuitextgranularityword indirectionuitextlayoutdirectionright nslogword tv textinrangewrthis is what i already have but it prints the word out as null,"['objective-c', 'ios']" +360841,how to calculate simple moving average faster in c what is the fastest libraryalgorithm for calculating simple moving average i wrote my own but it takes too long on 330 0 items decimal dataset period timems 20 300 60 1500 120 3500here is the code of my methodpublic decimal ma simpleint period int ii if period 0 ii period stpstart decimal summ 0 for int i ii i ii period i summ summ dataclosei summ summ period stpstop if ii 1500 systemwindowsformsmessageboxshowstpelapsedticks 10 stopwatchfrequency ms return summ else return 1the dataclose is a fixed size1 0 0 decimal array,['c#'] +360842,how to check if a string contains any letter from a to z possible duplicatec regex checking for aaza and aaza i could just use the code belowstring hello hello1char convertedstring stringtochararrayint errorcounter 0for int i 0 i createaccountpage passwordbox passwordpasswordlength i if convertedstringiequalsa convertedstringiequalsa convertedstringiequalsz convertedstringiequalsz errorcounter iferrorcounter 0 do somethingbut i suppose it takes too much line for just a simple purpose i believe there is a way which is much more simple the way which i have not yet mastered,['c#'] +360856,javascript mathrandom if num parameter is 52 how many possible return values are there is it 52 or 53 if i understand this correctly mathrandom uses random values from 0 to 1 inclusive if so then 0 is a possible return value and so is 52 this results in 53 possible return values is this correct reason i ask is that a book that i am learning from uses this code for a deck of cards i wonder if num should equal 51 thanks function getrandomnum var my num mathfloormathrandom num return my num,['javascript'] +360867,dude wheres my object or why does linq not return my object once i have the results of my linq query i am not always happy there could be a result that i was expecting to be there but was not for example my client was expecting that a customer was in a customer list but it was not it is my client saying dude wheres my customer not me i am the dude and to remain a dude i have to give my client the reasonis there a simple way to take a given object instance and a linq query and determine which expressions within the query excluded that instanceedit ok here is a better exampleoutput should be something along the linesyour customer was excluded for 2 reasonscustomer firstname is carl but it should be danielcustomer age is 18 but it should be 20 public class customer public string firstname get set public int age get set test public void dude wheres my object test1 var daniel new customer firstname daniel age 41 var carl new customer firstname carl age 18 var customers new listcustomer daniel carl asqueryable to convert ienumerablet to iqueryablet in the case of linqtoobjects only needed for this test not production code where queies written for linqtosql etc normally return iqueryablet var query from c in customersasqueryable where cage 20 where cfirstname daniel select c query would return daniel as youd expect but not executed here however i want to explain why carl was not in the results string r dudewheresmyobjectquery carl assertareequalage is 18 but it should be 20 r0 assertareequalfirstname is carl but it should be daniel r1 should even work for a customer who is not in the original customers collection var ficticiouscustomer new customer firstname other age 19 string r2 dudewheresmyobjectquery ficticiouscustomer assertareequalage is 19 but it should be 20 r20 assertareequalfirstname is other but it should be daniel r21 public string dudewheresmyobjecttiqueryablet query t instance do something here with the queryexpression and the instance first of all before i attempt to write some fancy fluent framework has anyone done this alreadyso far i have considered navigating the expression tree and executing each branch against an iqueryable that only contains my object now i do not have a great deal of experience using raw expression trees so i would like those who have to suggest any pitfalls or even explain whether this is a dead end and whyi am anxious that anything that results from this shouldbe reusable should be applicable to any object compared against a linq query returning objects of the same classnot affect the performance of the original query this should just be standard linqshould be linqimplementation agnosticif there are multiple property values set on the missing instance that excluded it from the results then all of those reasons should be reportedediti am not suggesting that i keep executing linqtosql against the database multiple times with different permutations of the query and comparing the results rather i am looking for a way to take a single instance and compare it to the expression tree without executing the query directly againalso i would like an indication of whether others might find this useful if so i would consider starting an open source project to solve it,"['c#', '.net']" +360869,how to make a jquery click event fire only on first click i have two divs basic1 and basic2 i want basic1 to fadeout on click and basic2 to fade in which i have working wonderfully the only problem is that once basic2 fades in if the user continues to click the link navbar1 it will fade in this div over and over i know that i need to use the bind function but i cannot seem to figure out where in my code to put it thanksdocumentreadyfunction navbar1clickfunctione epreventdefault basic2hideloadbasic2 function thisdelay600fadein10 basic1fadeout10,['jquery'] +360916,apc serialization slow examplearr arrayfori 5 i 30 i arri fooapc storedata arrit takes like 15 seconds to get the data it takes around 07sbut if i serialize the data with php and store it like that with apc storedata serializearr it takes only 1 secondto get the serialized data and then unserialize it it takes a little more than 06swhy is apc so slow,['php'] +360933,can code that is valid in both c and c produce different behavior when compiled in each language c and c have many differences and not all valid c code is valid c codeby valid i mean standard code with defined behavior ie not implementationspecificundefinedetcis there any scenario in which a piece of code valid in both c and c would produce different behavior when compiled with a standard compiler in each languageto make it a reasonableuseful comparison i am trying to learn something practically useful not to try to find obvious loopholes in the question let us assumenothing preprocessorrelated which means no hacks with ifdef cplusplus pragmas etc anything implementationdefined is the same in both languages eg numeric limits etcwere comparing reasonably recent versions of each standard eg say c98 and c90 or laterif the versions matter then please mention which versions of each produce different behavior,"['c++', 'c']" +360967,objectivec block parameters say we have this blockint ablockbool bool param my current understanding of this is the first int is the return type ablockbool gives the name of the method and the type of its parameter and bool param is the parameters name inside the block plus the parameters type againwhy is the syntax such that we have to list the parameter type twice could the two types ever be different,['objective-c'] +360975,error while deploying sample code by android projectandroid api demos i am getting following error on deploying one of the sample projects given by android android api demos for api level 8 error error retrieving parent for item no resource found that matches the given name androidstylethemewallpaperat valuesstylesxml line 43style namethemewallpaper parentandroidstylethemewallpaper item nameandroidcolorforegroundfitemstylei have been looking for solutions for over a month now i have tried rebuilding project dowloading entire source code again and rebuilding and cleaninghelp,['android'] +360987,sort list of strings with localization i want to sort below list of strings as per user localeliststring words arraysaslist abc abc abc a bc abc abc abc for different user locale sort output should be different as per there localehow to sort above list as per user locale i tried collectionssortwords stringcase insensitive orderbut this is not working for localization so how to pass locale parameter to collectionssort or is there any other efficient way,['java'] +361004,how can i manage separate session states for two different websites on the same hosting using php i am currently developing two web sites and debugging them by connecting to localhost the first site is referenced with httplocalhostweb1 and the second is referenced with httplocalhostweb2 i have created a login script for each in which three domainspecific session variables are set eg sessionweb1 user sessionweb1 login sessionweb1 sessionidhowever when i log in to both sites on the same browser then log out of one site which fires session destroy i am automatically logged out of the second site as wellany ideas as to how i might resolve this problem would be very much appreciated,['php'] +361036,how to programmatically change contrast of a bitmap in android i want to programmatically change the contrast of bitmap till now i have tried thisprivate bitmap adjustedcontrastbitmap src double value image size int width srcgetwidth int height srcgetheight create output bitmap bitmap bmout bitmapcreatebitmapwidth height srcgetconfig color information int a r g b int pixel get contrast value double contrast mathpow100 value 100 2 scan through all pixels forint x 0 x width x forint y 0 y height y get pixel color pixel srcgetpixelx y a coloralphapixel apply filter contrast for every channel r g b r colorredpixel r intr 2550 05 contrast 05 2550 ifr 0 r 0 else ifr 255 r 255 g colorgreenpixel g intg 2550 05 contrast 05 2550 ifg 0 g 0 else ifg 255 g 255 b colorbluepixel b intb 2550 05 contrast 05 2550 ifb 0 b 0 else ifb 255 b 255 set new pixel color to output bitmap bmoutsetpixelx y colorargba r g b return bmout but this does not work as expected please help me in this or provide any other solution to achieve this thanks in advance,['android'] +361047,interactive selection of series in a matplotlib plot i have been looking for a way to be able to select which series are visible on a plot after a plot is createdi need this as i often have plots with many series they are too many to plot at the same time and i need to quickly and interactively select which series are visible ideally there will be a window with a list of series in the plot and checkboxes where the series with the checked checkbox is visibledoes anyone know if this has been already implemented somewhere if not then can someone guide me of how can i do it myselfthanksomar,['python'] +361133,twitter bootstrap modal scrolling the page up on show clicking on a link which triggers a twitter bootstrap modal to pop up is causing the browser to scroll up the page this behavior is only occurring in chromehere is a demonstration pagethe page has 600 rows of links causing the page body to exceed window height if any of these links is clicked it thisplays the modal dialog when in chrome clicking any of the links below the initial view will cause the background page to scroll up not always entirely to the topi am use the following function to trigger the thisplay of the modalfunction testid imp modallabelhtmlheader modalbodyhtmlbody mymodalmodalshowand the links are of the forma href onclicktestreturn falsetest link ai am seeing this behavior in chrome 220122994 many suggestionsideas as to why this is happening and how to prevent itadditional examplethis can be recreated on the twitter bootstrap documentation page for the modal pluginonce on the page simply override the existing dataapi to use the javascript api insteadmodals adatatogglemodalonclick functione mymodalmodaltoggle return false now if the launch demo modal button is clicked the page will scroll up when the modal is shownagain this is using chrome,"['javascript', 'html', 'css']" +361159,sending an arraylist from the server side to the client side over tcp using socket i am trying to send one object from the server side socket to the client side socket over tcp i cannot find out where is the problem here is the error i am getting on the client sidejavaioeofexception at javaioobjectinputstreampeekinputstreamreadfullyobjectinputstreamjava2280 at javaioobjectinputstreamblockdatainputstreamreadshortobjectinputstreamjava2749 at javaioobjectinputstreamreadstreamheaderobjectinputstreamjava779 at javaioobjectinputstreaminitobjectinputstreamjava279 at clientsidemainclientsidejava16code for server sideimport javaioimport javanetimport javautilarraylistpublic class serverside public static void mainstring args try serversocket myserversocket new serversocket9 socket skt myserversocketaccept arrayliststring my new arrayliststring myset0bernard myset1 grey try objectoutputstream objectoutput new objectoutputstreamsktgetoutputstream objectoutputwriteobjectmy catch ioexception e eprintstacktrace catch ioexception e eprintstacktrace code for the client sideimport javaioimport javanetinetaddressimport javanetsocketimport javanetunknownhostexceptionimport javautilarraylistpublic class clientside public static void mainstring args try socket socket new socket101129 arrayliststring titlelist new arrayliststring try objectinputstream objectinput new objectinputstreamsocketgetinputstream error line try object object objectinputreadobject titlelist arrayliststring object systemoutprintlntitlelistget1 catch classnotfoundexception e systemoutprintlnthe title list has not come from the server eprintstacktrace catch ioexception e systemoutprintlnthe socket for reading the object has problem eprintstacktrace catch unknownhostexception e eprintstacktrace catch ioexception e eprintstacktrace,['java'] +361162,magento redirect to order view i want to redirect user from my backend module to adminorder saleview but i cant when i use mageappgetresponsesetredirectmagehelperadminhtmlgeturladminsales orderview arrayid1 magento is cutting of admin from url so it looks like orderviewid1keyfdb6089cf1e5cd77f85f085def1a013aand i get 404 pageany idea how to redirect to admin module in magento way,['php'] +361187,what is systemreactivelinqobservible note the alpha whatever is systemreactivelinqobserviblenote the greek letter alpha in place of the a observible not observablefound about a hundred classes all internal in this namespace in the assembly cprogram files x86microsoft sdksreactive extensionsv20binariesnetframeworkv40systemreactivelinqdll systemreactivelinq version20208230 cultureneutral publickeytoken31bf3856ad364e35,"['c#', '.net']" +361209,how can i run php code within a java application possible duplicatecalling php from java i was wondering how i could run php code within java using the scriptengine i am able to run javascriptstring codeprint55 sample bit of codescriptenginemanager manager new scriptenginemanagerscriptengine engine managergetenginebyextensionjstry engineevalcode catch scriptexception ex catch statementto run this i imported the library javaxscript i believe to run php i would have to import a similar library and change the third line of the code above to the extension php unfortunately i do not know which library this is i have googled to try and find the answer and came across the phpjava bridge library but i do not think this is exactly what i am looking for as it is focussed on running java through php as far as i knowi hope i have not missed anything out and any help would be greatly appreciated,"['java', 'php']" +361234,endpoint not found wcf web service i have created 2 endpoints for my wcf serviceit is working fine with basichttpbinding but causes error for webhttpbindingerror endpoint not foundoperation contract definitionoperationcontractwebinvokemethod post bodystyle webmessagebodystylewrappedrequest responseformat webmessageformatjsonvindescription calladswebmethodstring vin string styleidwebconfigsystemservicemodel bindings basichttpbinding binding namedescription7abinding closetimeout0100 opentimeout0100 receivetimeout0010 sendtimeout0100 allowcookiesfalse bypassproxyonlocalfalse hostnamecomparisonmodestrongwildcard maxbuffersize65536 maxbufferpoolsize524288 maxreceivedmessagesize65536 messageencodingtext textencodingutf8 transfermodebuffered usedefaultwebproxytrue readerquotas maxdepth32 maxstringcontentlength8192 maxarraylength16384 maxbytesperread4096 maxnametablecharcount16384 security modenone transport clientcredentialtypenone proxycredentialtypenone realm message clientcredentialtypeusername algorithmsuitedefault security binding basichttpbinding bindings client endpoint address bindingbasichttpbinding bindingconfigurationdescription7abinding contractdescription7adescription7aporttype namedescription7aport client services service behaviorconfigurationasmx nameadschromevindecoderservice endpoint namehttpendpoint address bindingbasichttpbinding contractadschromevindecoderiservice endpoint namewebendpoint addressjson behaviorconfigurationweb bindingwebhttpbinding contractadschromevindecoderiservice service services behaviors endpointbehaviors behavior nameweb webhttp enablewebscript behavior endpointbehaviors servicebehaviors behavior nameasmx servicemetadata httpgetenabledtrue servicedebug includeexceptiondetailinfaultstrue behavior servicebehaviors behaviors servicehostingenvironment multiplesitebindingsenabledtrue systemservicemodelplease suggest me how i can fix this,"['c#', 'asp.net', '.net']" +361251,ifstatement inside jquery append inside my jquery append i want to run an ifstatement to include an image on all my objects except on the first onelikevar i 0divdetailsforselectedinfoappend div classroundedandboxshade leftresultobject id valuequeryid div classleftresultobject inner if i 0 img srcimgjpgdivasdfdivthe code is generated by jsonjquery and then it is all appended on a div in my indexfileas far as i have been able to tell through immence googleing this cannot be done but i might be wrongif it is indeed impossible could the first selector in jquery be used in some cool way,"['jquery', 'html']" +361257,how to thisable altf4 for the application how can i thisable the use of altf4 applicationwide for c applications in my application i have many winforms and i want to thisable the ability of closing the forms using altf4 users should be able to close the form using x of the form thoughagain this is not for just one form i am looking for a way so altf4 is thisabled for the entire application and will not work for any of the form is it possible,"['c#', '.net']" +361259,codefirst loading 1 parent linked to 25 0 children is slow i searched a lot on my performance problem and tried all sorts of different things but i just cannot seem to get it to work fast enough heres my problem to it is simplest formi am using entity framework 5 and i want to be able to lazy load child instances of a parent when the user selects that parent so i do not have to pull the entire database however i have been having performance problems with lazy loading the children i think the problem is the wire up of the navigation properties between the parent and the children i am also thinking it must be something i did wrong because i believe this is a simple caseso i put up a program to test a single lazy load to isolate the problemheres the testi created a poco parent class and a child poco class parent has and children and child has 1 parent there is only 1 parent in the sql server database and 25 0 children for that single parent i tried different methods to load this data whenever i load either the children and the parent in the same dbcontext it takes a really long time but if i load them in different dbcontexts it loads really fast however i want those instances to be in the same dbcontexthere is my test setup and everything you need to replicate itpocospublic class parent public int parentid get set public string name get set public virtual listchild childs get set public class child public int childid get set public int parentid get set public string name get set public virtual parent parent get set dbcontextpublic class entities dbcontext public dbsetparent parents get set public dbsetchild childs get set tsql script to create the database and datause mastergoif existsselect name from sysdatabases where name performanceparentchild alter database performanceparentchild set single user with rollback immediate drop database performanceparentchildgocreate database performanceparentchildgouse performanceparentchildgobegin tran t1set nocount oncreate table dboparents parentid int constraint pk parents primary key name nvarchar200 nullgocreate table dbochildren childid int constraint pk children primary key parentid int not null name nvarchar200 nullgoinsert into parents parentid namevalues 1 parentdeclare nbchildren intdeclare childid intset nbchildren 250set childid 0while childid nbchildrenbegin set childid childid 1 insert into dbochildren childid parentid name values childid 1 child convertnvarchar5 childidendcreate nonclustered index ix parentid on dbochildren parentid ascgoalter table dbochildren add constraint fk childrenparents parentid foreign keyparentidreferences dboparents parentidgocommit tran t1appconfig containing the connection stringxml version10 encodingutf8configuration connectionstrings add nameentities providernamesystemdatasqlclient connectionstringserverlocalhostdatabaseperformanceparentchildtrusted connectiontrue connectionstringsconfigurationtest console classclass program static void mainstring args listparent parents listchild children entities entities datetime before timespan childrenloadelapsed timespan parentloadelapsed using entities new entities before datetimenow parents entitiesparentstolist parentloadelapsed datetimenow before systemdiagnosticsdebugwritelineload only the parent from dbset parentloadelapsedtotalseconds seconds using entities new entities before datetimenow children entitieschildstolist childrenloadelapsed datetimenow before systemdiagnosticsdebugwritelineload only the children from dbset childrenloadelapsedtotalseconds seconds using entities new entities before datetimenow parents entitiesparentstolist parentloadelapsed datetimenow before before datetimenow children entitieschildstolist childrenloadelapsed datetimenow before systemdiagnosticsdebugwritelineload the parent from dbset parentloadelapsedtotalseconds seconds then load the children from dbset childrenloadelapsedtotalseconds seconds using entities new entities before datetimenow children entitieschildstolist childrenloadelapsed datetimenow before before datetimenow parents entitiesparentstolist parentloadelapsed datetimenow before systemdiagnosticsdebugwritelineload the children from dbset childrenloadelapsedtotalseconds seconds then load the parent from dbset parentloadelapsedtotalseconds seconds using entities new entities before datetimenow parents entitiesparentstolist parentloadelapsed datetimenow before before datetimenow children parents0childs childrenloadelapsed datetimenow before systemdiagnosticsdebugwritelineload the parent from dbset parentloadelapsedtotalseconds seconds then load the children from parents lazy loaded navigation property childrenloadelapsedtotalseconds seconds using entities new entities before datetimenow parents entitiesparentsincludep pchildstolist parentloadelapsed datetimenow before systemdiagnosticsdebugwritelineload the parent from dbset and children from include parentloadelapsedtotalseconds seconds using entities new entities entitiesconfigurationproxycreationenabled false entitiesconfigurationautodetectchangesenabled false entitiesconfigurationlazyloadingenabled false entitiesconfigurationvalidateonsaveenabled false before datetimenow parents entitiesparentsincludep pchildstolist parentloadelapsed datetimenow before systemdiagnosticsdebugwritelineload the parent from dbset and children from include parentloadelapsedtotalseconds seconds with everything turned off here are the results of those testload only the parent from dbset0972 secondsload only the children from dbset0714 secondsload the parent from dbset01 seconds then load the children from dbset86026 secondsload the children from dbset06864 seconds then load the parent from dbset75816159 secondsload the parent from dbset0 seconds then load the children from parents lazy loaded navigation property85644549 secondsload the parent from dbset and children from include86428788 secondsload the parent from dbset and children from include91416586 seconds with everything turned offanalysiswhenever the parent and the children are in the same dbcontext it takes a long time 9 seconds to wire everything up i even tried turning off everything from proxy creation to lazy loading but to no avail can someone please help me,['c#'] +361289,does c11 allow not require releaseacquire semantics for volatile keyword since visual c 2005 microsoft has made additional ordering guarantees for accesses to volatile types which are not required by the c standarddoes anything in the c standard actually forbid these guarantees the microsoft documentation seems to think soplease let me know whether the standard allows the ordering implemented by microsoft and also vote on this bug reportvolatilems documentation mangles what iso compliant means,['c++'] +361313,is it preferable to use activityonattachfragment or fragmentonattach to communicate between an activity and a nested fragment the android documentation suggests that to communicate from an activity to a hosted fragment the fragment can define a callback interface and require that the host activity implement it the basic pattern involves implementing onattach in your fragment and casting the activity to a callback inteface see heres an example of providing a fragment some initialization data as well as listening for a navigation callbackpublic class hostactivity extends activity implements fragmenthost override uimodel getuimodel return muimodel override fragmentnavlistener getnavlistener return mnavlistener public class hostedfragment extends fragment override public void onattachactivity activity superonattachactivity if activity instanceof fragmenthost fragmenthost host fragmenthost activity setuimodelhostgetuimodel setnavlistenerhostgetfragmentnavlistener compare this to using onattachfragment in the host activity to explicitly initialize the fragmentpublic class hostactivity extends activity override public void onattachfragmentfragment fragment superonattachfragmentfragment if fragment instanceof hostedfragment hostedfragment hostedfragment hostfragment fragment hostedfragmentsetuimodelmuimodel hostedfragmentsetnavlistenermnavlistener to me it seems like the first pattern has some drawbacksit makes the fragment harder to use from different activities sincesince all of those activities must implement the required interface i can imagine cases where a given fragment instance does not require being fully configured by the host activity yet all potential host activities would need to implement the host interfaceit makes the code slightly harder to follow for someone unfamiliar with the pattern being used initializing the fragment in onfragmentattached seems easier to follow since the initialization code lives in the same class that creates the fragmentunit testing using a library like robolectric becomes harder since when calling onattach you must now implement fragmenthost rather than just calling onattachnew activityfor those of you whove done activity to fragment communication what pattern do you find preferable and why are there drawbacks to using onattachfragment from the host activity,['android'] +361322,data grouping in sql i am working on a small project using c and ef50 and i need to group some data let say i have table of columns in a building like shown belowcolumns table columnid columnnamewidthlengthheightnumber 1 c101 50 70 250 1 2 c102 70 70 250 1 3 c103 70 60 250 1 4 c104 90 70 250 1 5 c105 40 50 250 1 6 c106 50 70 250 1 7 c107 50 60 250 1 8 c108 70 70 250 1 i need a c code to see the above data groupped like thisgroupped columns tableg columnidcolumnnamewidthlengthheightnumber 1 c101106 50 70 250 2 2 c102108 70 70 250 2 3 c103 70 60 250 1 4 c104 90 70 250 1 5 c105 40 50 250 1 6 c107 50 60 250 1 i prefer clues than the exact solutionedit below code shows my current state i think i can find the columns with the same height width and length using this code but i am not sure how to generate a new name for the groupusing pehlivanentities context new pehlivanentities foreach var item in contexttable1 int id itemcolumnid foreach var item2 in contexttable1 int id2 item2columnid if id id2 if itemwidth item2width if itemlength item2length if itemheight item2height alter itemcolumnname increase itemnumber by one remove item2,"['c#', 'sql']" +361333,standard guarantees for aliases of integer types in cc eg is unsigned always equal to unsigned int first questionis unsigned always the same as unsigned intis signed always the same as intis short always the same as signed shortis second questionif a cc standard specifies answers to above questions what paragraphs are related to them,"['c++', 'c']" +361335,adb push multiple files with the same extension with a single command i want to push some files of the same type img to the sdcard partition of the phone with a single command but the wildcard does not workadb push img sdcardis there any way i can achieve that,['android'] +361339,is there a standard way of determining the number of va args i am experimenting with variable arguments in c using va args the idea is useful and is indeed something i have used a lot in c via the params functionality one thing that frustrates me is the following excerpt regarding va args abovenotice also that va arg does not determine either whether the retrieved argument is the last argument passed to the function or even if it is an element past the end of that listi find it hard to believe that there is no way to programmatically determine the number of variable arguments passed to the function from within that function itself i would like to perform something like the followingvoid fcnint arg1 va list arglist va startarglist arg1 int numremainingparams function that returns number of remaining parameters for int i0 inumremainingparams i do stuff with params va endarglistto reiterate the documentation above suggests that va arg does not determine whether the retrieved arg is the last in the list but i feel this information must be accessible in some manneris there a standard way of achieving this,['c++'] +361346,how can i optimize the code to always use the same reference to a string without increasing the memory usage i am working on an application that has a lot of duplicate strings and my task is to eliminate them to decrease memory usage my first thought was to use stringintern to guarantee that only one reference of a string would exist it worked to decrease the heap memory but it increased the permgen way too much in fact because there are many strings that are declared only once the total amount of memory used by the application increased actuallyafter searching for another ideas i found this approach it happened the same thing as stringintern the string usage decreased but the memory that i saved is being used in the weakhashmap and weakhashmapentry classesis there an effective way to maintain only one reference for each string that does not spend the same amount of memory that i am recovering doing it,['java'] +361359,is there a way to get all files from a blob of azure i need to compare from a list that i have to the files in a blob storage of azure the only part i need is a way to get a list of the files in that blobfor example blob azureimagesfilesnamesomethingjpgasdjpgiwdajpgmy listnamesomethingjpgasdjpgwhen i compare the files from the blob with my list i would like to delete the files that have no match in my list,['c#'] +361371,trying to understand cmtime i have seen some examples of cmtime three separate links but i still do not get it i am using an avcapturesession with avcapturevideodataoutput and i want to set the max and min frame rate of the the output my problem is i just do not understand the cmtime structapparently cmtimemakevalue timescale should give me value frames every 1timescale seconds for a total of valuetimescale seconds or am i getting that wrongwhy is not this documented anywhere in order to explain what this doesif it does truly work like that how would i get it to have an indefinite number of framesif its really simple i am sorry but nothing has clicked just yet,['ios'] +361377,read from a gzip file in python i have just make excises of gzip on python import gzipfgzipopenonlyfinnalyloggzrbfile contentfreadprint file contentand i get no output on the screen as a beginner of python i am wondering what should i do if i want to read the content of the file in the gzip file thank you,['python'] +361389,allow python list append method to return the new list i want to do something like thismylist 102030yourlist mylistappend 40unfortunately list append does not return the modified listso how can i allow append to return the new list,['python'] +361409,cannot use kiwi to test with frameworks added by cocoapods i am having an issue getting the testing framework kiwi to work with frameworks added through cocoapods i have both afnetworking and lumberjack being loaded in and both are causing a failure in the test the test only fails if any source files in my project being built into the test target are including files from cocoapods this is the message i am receiving20121015 131044386 otest472947e03 the test bundle at usersusernamelibrarydeveloperxcodederiveddatabuildproductsdebugiphonesimulatorkiwiunittestoctest could not be loaded because a link error occurred it is likely that dyld cannot locate a framework framework or library that the the test bundle was linked against possibly because the framework or library had an incorrect install path at link timei have followed all the instructions on both cocoapods and kiwi for example i have a apiclient class it includes afhttpclienth if i run a test without the apiclientm being built into the test target the test builds and runs fine if i do include the source into it it says everything succeeded but not tests are ran and the above error message is in my logthanksjames,['ios'] +361412,python userdefined classes have cmp and hash methods by default or in the python docs yeah i have this thing with the docs it says thatuserdefined classes have cmp and hash methods by default with them all objects compare unequal except with themselves and x hash returns idxbut the following code shows another thing class testobject pass t test t hash methodwrapper hash of test object at 0x01f2b5d0 t cmp traceback most recent call last file stdin line 1 in moduleattributeerror test object has no attribute cmp so where is cmp or what am i missing,['python'] +361431,completion block for popviewcontroller when thismissing a modal view controller using thismissviewcontroller there is the option to provide a completion block is there a similar equivalent for popviewcontrollerthe completion argument is quite handy for instance i can use it to hold off removing a row from a tableview until the modal is off screen letting the user see the row animation when returning from a pushed view controller i would like the same opportunityi have tried placing popviewcontroller in an uiview animation block where i do have access to a completion block however this produces some unwanted side effects on the view being popped toif there is no such method available what are some workarounds,['ios'] +361435,static const class members i have a variety of constants that i need to reference throughout my program rather than using global variables i have been using static const class membersclass humanpublic static const int hands 2 static const int fingers 10the problem is that i need to read the value in from an xml data file i know that i can initialize a static member with a functionconst int humanhands readdatafromfilesince the order of initialization can only be predicted in the same compilation unit i have to define all of them in the same cpp file that is not really a problem but it gets a bit clutteredthe real problem is that everything in my readdatafromfile function needs to be ready for use before my code even has a chance to run for instance i have an xml class that normally handles reading xml data from files i cannot use it in this case though because the static members are initialized before my xml class object is even constructedaside from random global variables everywhere is there a better solution to organize constants,['c++'] +361437,safely storing encrypted credentials in django i am working on a pythondjango app which among other things syncs data to a variety of other services including samba shares sshscp servers google apps and others as such it needs to store the credentials to access these services storing them as unencrypted fields would be i presume a bad idea as an sql injection attack could retrieve the credentials so i would need to encrypt the creds before storage are there any reliable libraries to achieve thisonce the creds are encrypted they would need to be decrypted before being usable there are two use cases for my appone is interactive in this case the user would provide the password to unlock the credentials the other is an automated sync this is started by a cron job or similar where would i keep the password in order to minimise risk of exploits hereor is there a different approach to this problem i should be taking,['python'] +361441,javaioioexception error2 no such file or directory i am trying to run a java program from another java program using runtimegetruntimeexeccode string java home systemgetenvjava home string command java homebinjava cp cp scsugplib tdesigner cd pr in ingrsp out scratchsugngpla ad stopo try proc runtimegetruntimeexeccommand procwaitfor int exitcode procexitvalue catch ioexception e eprintstacktrace catch interruptedexception e eprintstacktrace it gives me following error javaioioexception cannot run program netslscjdk6binjava cp scsugplib tdesigner cd pr in ingrsp out scratchsugngpla ad stoponerror javaioioexception error2 no such file or directory at javalangprocessbuilderstartprocessbuilderjava460 at javalangruntimeexecruntimejava593 at javalangruntimeexecruntimejava466can anyone help me to solve the issue is it that i need to add individual jar files with cp rather than setting the directory,['java'] +361483,signed vs unsigned values for counting in a loop so i have within a program an ordinary for loop through a vector of objects objects that are of a type i defined if that is relevantforint k 0 k objectssize k and when i compile i get this warningwarning comparison between signed and unsigned integer expressions this makes sense since i think size for a vector returns a size t but why would it matter is not a certain number of elements or even memory chunks an integer that you can count more importantly since my program has multiple such loops and happens to segfault a lot could this be part of it,['c++'] +361493,country name from iso short code in dictionary how to deal with nonascii chars i am making a webapp that takes country short code google app engine get from request header and i want to get the country name full name not just the 2 letter initialsi tried making a python dictionary but it breaks bkz the names have nonascii chars accent marks etc i used the python library pycountry but i am not sure how to include that in my google app engine project unfortunately pycountries output also has accent marks so i cannot just copy their txt values and make a dictionarybesides i just want the country code to name lookup table no other detailsheres a copy of the dictionarys i have been trying to make but they have these annoying accent marksthanks for the help in advanceshort2long afafghanistanaxaland islandsalalbaniadzalgeriaasamerican samoaadandorraaoangolaaianguillaaqantarcticaagantigua and barbudaarargentinaamarmeniaawarubaauaustraliaataustriaazazerbaijanbsbahamasbhbahrainbdbangladeshbarbadosbybelarusbebelgiumbzbelizebjbeninbmbermudabtbhutanbobolivia plurinational state ofbqbonaire sint eustatius and sabababosnia and herzegovinabwbotswanabvbouvet islandbrbraziliobritish indian ocean territorybnbrunei darussalambgbulgariabfburkina fasobiburundikhcambodiacmcamerooncacanadacvcape verdekycayman islandscfcentral african republictdchadclchilecnchinacxchristmas islandcocos keeling islandscocolombiakmcomoroscgcongocdcongo the democratic republic of theckcook islandscrcosta ricacica te divoirehrcroatiacucubacwcuraocycyprusczczech republicdkdenmarkdjdjiboutidmdominicadodominican republicececuadoregegyptsvel salvadorgqequatorial guineaereritreaestoniaetethiopiafkfalkland islands malvinasfofaroe islandsfjfijififinlandfrfrancegffrench guianapffrench polynesiatffrench southern territoriesgagabongmgambiagegeorgiadegermanyghghanagigibraltargrgreeceglgreenlandgdgrenadagpguadeloupeguguamgtguatemalaguernseygnguineagwguineabissaugyguyanahthaitihmheard island and mcdonald islandsvaholy see vatican city statehnhondurashkhong konghuhungaryisicelandinindiaidindonesiairiran islamic republic ofiqiraqieirelandimisle of manilisraelititalyjmjamaicajpjapanjejerseyjojordankzkazakhstankekenyakikiribatikpkorea democratic peoples republic ofkrkorea republic ofkwkuwaitkgkyrgyzstanlalao peoples democratic republiclvlatvialblebanonlslesotholrliberialylibyaliliechtensteinltlithuanialuluxembourgmomacaomkmacedonia republic ofmgmadagascarmwmalawimymalaysiamvmaldivesmlmalimtmaltamhmarshall islandsmqmartiniquemrmauritaniamumauritiusytmayottemxmexicofmmicronesia federated states ofmdmoldova republic ofmcmonacomnmongoliamemontenegromsmontserratmamoroccomzmozambiquemyanmarnanamibianrnaurunpnepalnlnetherlandsncnew caledonianznew zealandninicaraguanenigerngnigerianuniuenfnorfolk islandmpnorthern mariana islandsnonorwayomomanpkpakistanpwpalaupspalestinian territory occupiedpapanamapgpapua new guineapyparaguaypeperuphphilippinespnpitcairnplpolandptportugalprpuerto ricoqaqatarreraunionroromaniarurussian federationrwrwandablsaint barthalemyshsaint helena ascension and tristan da cunhaknsaint kitts and nevislcsaint luciamfsaint martin french partpmsaint pierre and miquelonvcsaint vincent and the grenadineswssamoasmsan marinostsao tome and principesasaudi arabiasnsenegalrsserbiascseychellesslsierra leonesgsingaporesxsint maarten dutch partskslovakiasisloveniasbsolomon islandssosomaliazasouth africagssouth georgia and the south sandwich islandsesspainlksri lankasdsudansrsurinamesouth sudansjsvalbard and jan mayenszswazilandseswedenchswitzerlandsysyrian arab republictwtaiwan province of chinatjtajikistantztanzania united republic ofththailandtltimorlestetgtogotktokelautotongatrinidad and tobagotntunisiatrturkeytmturkmenistantcturks and caicos islandstvtuvaluugugandauaukraineaeunited arab emiratesgbunited kingdomusunited statesumunited states minor outlying islandsuyuruguayuzuzbekistanvuvanuatuvevenezuela bolivarian republic ofvnviet namvgvirgin islands britishvivirgin islands uswfwallis and futunaehwestern saharayeyemenzmzambiazwzimbabwei tried to use this code to build the dictionaryimport pycountryt listpycountrycountriesfor country in t print countryalpha2 countryname,['python'] +361507,how to use facebook access token in android app webview in my application the user opens a webview to the mobile versions of facebook profile page page my problem is that when opening the webview the user is required to enter username and password for facebook since i already have a facebook access token through fb sdk and the user might have installed the facebook application i assume there is some way to skip this annoying phase of signing into facebook when opening the webviewin other words how do i use the access token that i already have in my applications webview,['android'] +361527,beginning automated testing i am ashamed to admit it but i have never done any automated testing of my code usually i will write a function or method then do some manual testing and continue on i realize this is very bad practice so i am trying to change my ways problem is i am a bit lost on how to actually start i am writing a small python web application using flask that is connected to a database and i would like to use this as a chance to force myself into better development practices i am guessing i need to populate my database with some test data probably just writing scripts to generate it then proceed to write tests for each function in my program for example i have a function that pulls all of a users comments from the system would i have to write a test for a specific user and then check to make sure the list of returned comment ids matched an array i created from a manual database query is this unit testing just having a hard time understanding it all even pointing me towards some newb friendly docs would be very appreciated,['python'] +361529,trying to push a button to bottom of linear layout in android i know this can be very easily done by using a relative layout but i feel what i am doing is correct and should give me the desired result with the linear layout itself but for some reason when i run on this on google nexus 7 running android jb 412 i see the button and the text view immediately after the list view items if the list view is empty i see them at the top of the screen am i doing something wrong here is my xml filexml version10 encodingutf8linearlayout xmlnsandroidandroidididattachments listandroidlayout widthfill parentandroidlayout heightfill parentandroidweightsum1androidorientationverticallistview androidididmtg attachments androidlayout widthfill parent androidlayout height0dp androidlayout weight1 button androidididattach delete androidlayout widthwrap content androidlayout heightwrap content androidlayout gravitycenter androidtextstringdelete androidtextsize22sp textview androidtextstringattach warning androidlayout widthwrap content androidlayout heightwrap content androidtextsize18sp linearlayout,['android'] +361569,offline map with routing ios i am working with a project its related to offline map applicationbecause of that i searched for offline map which shows the defined area i used mapbox for offline mapping i can add annotation on this map and draw lines but my requirement is offline map with routing i was fed up to find a offline routing library or offline routing engine to embedded to xcodeappreciate if any of you have any clue or sample projectcode to implement this note this question is related to my one no one replied to this as wellthanks,['ios'] +361574,systemdatasqlite slow connect for nonadmin users i have a net 4 application in mixed mode with systemdatasqlite 1082 for database access to an encrypted database when i install the application to cprogram filesmyfolder the connect to the sqlite database file is slow log files show that it is the sqlite connect statement that is delayed by a few seconds the problem does not occur when i do the followingrun the application with admin privilegesinstall any other place than cprogram filesinstall the application to cprogram files but move the database to another folderi have no clue what can be the cause of this,['.net'] +361622,zend framework 2 active menu items build navigation from confignavigation array default array admin array label administration controller index action index route admindefault album array label album controller index action index route albumdefault routing is configured like it is true navigation in the menu works links menu lead to the desired controlleraction of the desired module but while introducing menu and a transition to one or another menuitem active marked both points simultaneously and administration and album as i understand it for the reason that match the names of controllers and actions with them but there is still the route and it is different not for nothing that the generated different url for each item but somehow despite this they both are marked as active routing config router array routes array admin array type literal options array route admin defaults array namespace admincontroller controller index action index may terminate true child routes array default array type segment options array route controlleractionidid constraints array controller azazazaz09 action azazazaz09 id 09 defaults array album routing config similarwhy this is happening thanks,['php'] +361645,matlab hangs when i try to use the java package jdde but only for the first time after a system reboot i am using the external java package jdde in matlab please note that for the following example the dll file that comes with the package needs to be on the matlab librarypath the method to do this is different depending on your matlab versionusing jdde in matlab works fine except for the first time after i reboot the computer or i logofflogon in windows when i run the following code for the first time after a computer reboot matlab will stay in busy mode forever with 0 cpu when this happens i kill the matlab process in the task manager and restart matlab when i run the same code again it will execute instantly not staying busy forever javaaddpathcprettytoolsjdde102jara compretty toolsddeclientddeclientconversationaconnectto sum it up the above code will cause matlab to stay busy forever the first time i run it after a system reboot or user logofflogon when i run it again after killing the matlab process it will work perfectly fine not hanging up matlabi have seen this behavior on different computers and in different versions of matlab 2010 and 2012 i am using windows 7 x64in the code example the aconnect command is the one that causes matlab to stay busy forever putting this command in a trycatch block would not help because the aconnect does not cause an error it just never does continuei am not sure if this problem is caused by matlab or by the java packageany ideas how to get rid of this behavior would be much appreciatednote the input argument of aconnect does not matter it will always hang so i just gave as input in this example,['java'] +361725,what name should i use for exception name of nsexception in objectivec i want to use nsexception exceptionwithnamereasonuserinfobut what string should i use for argument nameshould exception name be unique in the projector i can use myexception for all of my exceptionand i do not know what exception name is used forwhere are exception names used,"['iphone', 'objective-c']" +361759,still dyld library not loaded i am integrating facebook in my application as required frameworks i added to the projectbut the app crashes without loading even first screendyld library not loaded systemlibraryframeworksadsupportframeworkadsupport referenced from varmobileapplications8e09c9aaca814c26aeedb2c632b60a54gridlockedappgridlocked reason image not foundi use xcode 45 my ipad runs ios 51 the app runs fine on simulator both 60 51but when i connect ipad change the deployment target to 51as without this device is not shown to run app crashescan anyone pls help to get out of it i really spent good time still looking struggling to achieve success,"['iphone', 'objective-c']" +361771,facebook ios 31 sdk login with publish permission callbacks i am having trouble logging in with publish permissions in the facebook 31 ios sdkmy app has a button to share a video and when the user clicks it i want to add the basic publish permission as i understand i have to do two calls openactivesessionwithreadpermissions and thenreauthorizewithpublishpermissionsheres the code i am using nowopens a facebook session and optionally shows the login ux voidopensessionforreadpermissions fbsession openactivesessionwithreadpermissionsnil allowloginuiyes completionhandler fbsession session fbsessionstate state nserror error this is called even from the reauthorizewithpublishpermissions if state fbsessionstateopen error self opensessionforpublishpermissions else if state fbsessionstateclosedloginfailed fbsessionactivesession closeandcleartokeninformation nsnotificationcenter defaultcenter postnotificationnamefbloginerrornotification objectsession voidopensessionforpublishpermissions nsarray permissions nsarray arraywithobjectpublish stream fbsession activesession reauthorizewithpublishpermissionspermissions defaultaudiencefbsessiondefaultaudiencefriends completionhandler fbsession session nserror error if error nsnotificationcenter defaultcenter postnotificationnamefbloginsuccessnotification objectsession else nsnotificationcenter defaultcenter postnotificationnamefbloginerrornotification objectsession i see that the block in the opensessionforreadpermissions is called twice once with fbsessionstateopen and once with fbsessionstateopentokenextended from the opensessionforpublishpermissions call and i get a errorreauthorizefailedreasonusercancelled when first trying to login to the app if o deleted all app permissions beforewhat is the proper way to implement this login the app does not require facebook login except for this one feature so the login process should be on the same button pushthanks,['ios'] +361772,in sql server do composite primary keys increase the chance of a deadlock i was wondering if either because of increased row locking andor because of increased time spent holding locks having a composite primary key defined on a table would increase the chance of having a deadlock when a it is being updated my multiple threads at oncethank you for any help,['sql'] +361793,the entity or complex type cannot be constructed in a linq to entities query possible duplicatethe entity cannot be constructed in a linq to entities query var tasks from i in dataincidents join a in dataaccounts on icustomerid equals aacct cid select new tasks creator id aid start date idateopened end date idateclosed product code iproductcode install type iinstalltype os iostype details idescription solution isolution creator name itechid category ititle text ticket for iname status id 7 foreach var task in tasks datatasksaddtask datasavechanges public class incidents key public int incidentid get set public string customerid get set public string productcode get set public string techid get set public datetime dateopened get set public datetime dateclosed get set public string title get set public string description get set public string solution get set public string name get set public string ostype get set public string installtype get set public string addonsoftware get set public string screenshare get set gives me an error when i try to iterate i would love some help with this,['c#'] +361804,complex type is getting null in a apicontroller parameter i dona t know why my parameter parametrofiltro filtro is getting null the other parameters page and pagesize is getting okpublic class parametrofiltro public string codigo get set public string descricao get set my apicontroller get methodpublic pageddatamodelparametrodto getparametrofiltro filtro int page int pagesizemy ajax callvar fullurl api selfapiajax url fullurl type get datatype json data filtro codigo 1 descricao teste page 1 pagesize 10 success function result alertresultdatalength selfparametrosresultdata,['c#'] +361808,why does stllist copy elements added to the list the standard template library documentation for list saysvoid push back const t x add element at the end adds a new element at the end of the list right after its current last element the content of this new element is initialized to a copy of xthese semantics differ greatly from the java semantics and confuse me is there a design principle in the stl that i am missing copy data all the time that scares me if i add a reference to an object why is the object copied why is not just the object passed across there must be a language design decision here but most of the commentary i have found on stack overflow and other sites focuses on the exception throwing issues associated with the fact that all this object copying can throw exceptions if you do not copy and just handle references all those exception problems go away very confusedplease note in this legacy code base i work with boost is not an option,['c++'] +361813,when does exactly jquery load event fire i have been looking here and in google when does exactly the jquery load event fire of course i mean load event for images i do not mean typical situtation when document with images is loading what i know load event fires when we1 appending new img to documentimg srcpicturejpg appendtobody2 changing the src attribute of existing imageimgattrsrc new pathjpg3 creating new img objectvar object img srcpicturejpg but what about these situations becasue i am not sure4 appending image to object not added to document domvar o divdivoappendimg srcpicturejpg i mean o does not exist in dom tree it is not appended5 loading content with imgs to object not added to the documentvar o divdivoloadurlhtml pictures i mean o does not exist in dom tree it is not appendedi would be very grateful for help,['jquery'] +361871,aspnet web site debugging extremely slow with several thousand temporary aspnet files my team is responsible for maintaining a legacy aspnet webforms web application projectwe are currently using visual studio 2010 and the project is targeting net framework 40the project has over 200 ascx controls and nearly 900 resx resource files it generates a temporary aspnet files folder which contains over 20 filesof these temporary files there are 121 cmdline files 151 compiled files 64 delete files 121 err files all of which are 0 bytes 121 out files 59 pdb files 121 tmp files and 246 cs fileswhen we start debugging the project it seem to take forever for it to load roughly 5 minutes or sothe debug output window shows many many lines similar tow3wpexe managed v4030319 loaded cwindowsmicrosoftnetframeworkv4030319temporary aspnet filesprojectc863323788f5a808app web snat3rsudllthese lines appear slowly roughly one every second until eventually the first page loadsonce the first page loads in the browser the project performance seems reasonable but getting there seems to take an inordinately long timei am looking for suggestions on how i can improve the load time for this projecti am concerned that there is something fundamentally wrong with the project that needs to be addressed because it seems unreasonable that it should take 5 minutes for it to load in the debugger,"['c#', 'asp.net', '.net']" +361892,how to share secondary yaxis between subplots in matplotlib if you have multiple subplots containing a secondary yaxis created using twinx how can you share these secondary yaxis between the subplots i want them to scale equally in an automatic way so not setting the ylimits afterwards by handfor the primary yaxis this is possible by using the keyword sharey in the call of subplotbelow example shows my attempt but it fails to share the secondary yaxis of both subplots i am using matplotlibpylabax create upper subplotaxappendsubplot211plotrand1 rand10rcreate plot on secondary yaxis of upper subplotaxappendax0twinxplot10rand1 rand10bcreate lower subplot and share yaxis with primary yaxis of upper subplotaxappendsubplot212 sharey ax0plot3rand1 rand10gcreate plot on secondary yaxis of lower subplotaxappendax2twinxset twinxed axes as the current axes againbut now attempt to share the secondary yaxisaxesax3 sharey ax1plot10rand1 rand10ythis gets me something likethe reason i used the axes function to set the shared yaxis is that twinx does not accept the sharey keywordiam using python 32 on win7 x64 matplotlib version is 120rc2,['python'] +361897,c detect templated class templatetypename tstruct check static const bool value falsewhat i want to do is to have checktvalue be true if and only if t is a stdmapab or stdunordered mapab and both a and b be stdstring so basically check enables compiletime checking of the type thow do i do this,['c++'] +361899,jquery auto detect if i need to use html or val i am writting a jquery plugin to create ajax calls designed for my app inside this plugin my ajax call looks like this reduced to what the question need ajax url route type post data inputdata success functionresponse textstatus jqxhr if outputselector undefined outputselectorhtmlresponse or outputselectorvalresponse outputselector is a selector defined outside the plugin i do not know if this selector is a div or an input or even a select is there a smart way to know if i need to use val or html,['jquery'] +361915,nohup is not writing log to output file i am using the following command to run a python script in the backgroundnohup cmdpy cmdlog but it appears that nohup is not writing anything to the log file cmdlog is created but is always empty in the python script i am using sysstdoutwrite instead of print to print to standard output am i doing anything wrong,['python'] +361936,mark ticks in latex in matplotlib in a plot in matplotlib i specially want to mark points on the xaxis as pi2 pi 3pi2 and so on in latex how can i do it,['python'] +361962,cocoalumberjack filelogger logging to multiple files i am using this cocoalumberjack framework to log all my messages in objectivec design now i want to log all errors to one file and all other messages to another file i know i could use formatter to filter this information i created two ddfilelogger instances in appdelegate but these two loggers keep writing into the same file i wonder if there is a way that i could specify the logging destination so that two loggers write to two different files,['objective-c'] +361994,how do you set the duration for uicollectionview animations i have a custom flow layout which is adjusting the attributes for cells when they are being inserted and deleted from the collectionview with the following two functions but i am unable to figure out how you would adjust the default animation duration uicollectionviewlayoutattributes initiallayoutattributesforappearingitematindexpathnsindexpath itemindexpath uicollectionviewlayoutattributes attributes self layoutattributesforitematindexpathitemindexpath assign the new layout attributesattributestransform3d catransform3dmakescale05 05 05attributesalpha 0return attributesuicollectionviewlayoutattributes finallayoutattributesforthisappearingitematindexpathnsindexpath itemindexpathuicollectionviewlayoutattributes attributes self layoutattributesforitematindexpathitemindexpath assign the new layout attributesattributestransform3d catransform3dmakescale05 05 05attributesalpha 0return attributes,['ios'] +362011,how to setup a group in supervisord so i am setting up supervisord and trying to control several processes and that all works fine now i want to setup a group so i can startstop different sets of processes rather than all or nothing heres a snippet of my config filegrouptapjoyprogramstapjoygame1tapjoygame2programtapjoygame1commandpython tapjoy pingerpy g game1directorygoherefirstredirect stderrtrueautostarttrueautorestarttruestopasgrouptruekillasgrouptrueprogramtapjoygame2commandpython tapjoy pingerpy g game2directorygoherefirstredirect stderrtrueautostarttrueautorestarttruestopasgrouptruekillasgrouptruenow from reading the docs this looks to me like it should work but callingsupervisorctl restart tapjoydoes not do anythingam i missing somethingadding a star does not give an error but does not do anything eithersupervisorctl restart tapjoysupervisorctl statustapjoy game1 running pid 4697 uptime 1 day 215623tapjoy game2 running pid 4698 uptime 1 day 215623tapjoy game3 running pid 4699 uptime 1 day 215623tapjoy game4 running pid 4700 uptime 1 day 215623tapjoy game5 running pid 4701 uptime 1 day 215623,['python'] +362016,from within java how can i create a list of all possible numbers from a specific regular expression i have a strange problem at least one i have never come across i have a precondition where customers have simple regular expressions associated with labels the labels are all they care about what i would like to do is create a list of all possible numbers that would match each of these regular expressions i would have logic that would warn me when the list is beyond a certain threshold here is an example of the regular expression 342514227228229230243244245246lets say that these ips are associated with acme behind the scenes when the user selects acme in our ui i am filling out a filter object that contains all of those possible numbers and submitting them as an or query to a highly specialized vertica databasei just cannot determine an elegant way of creating a list of numbers from said regular expressionsthe others aspect of this is that the java code within another portion of the product is using those regular expressions to show acme by using a java patterncompile which means the customer could create a complex regular expression i have only seen them so far use something simple as shown aboveis there a method that will generate a list based on regular expressionthanks for your time,['java'] +362032,difference between instance variable and attr accessor i just started learning ruby and i do not see the difference between an instace variable and an attribute declared using attr accessorwhat is the difference between the following two classesclass myclass variable1 endandclass myclass attr accessor variable1endi searched lot of tutorials online and everybody uses different notation does it have to do anything with the ruby version i also searched few old threads in stackoverflow what is attr accessor in ruby whats the difference between these two ruby class initialization definitionsbut still i am not able to figure out what is the best way to use,['ruby'] +362053,single camera calibration with opencv problems generating a complete unthistorted image i have been attempting to unthistort imagery from a fisheye camera if it is relevant i am using a gopro using opencvs camera calibration suite i have got most of the process working and can generate unthistorted images however when using remap the unthistorted image is the valid rectangle in other words the image returned is a cropped version of the original to avoid the curved black borders that are inherent in unthistorted framesi have attempted to use getoptimalnewcameramatrix to correct the situation with very strange results i am hoping one of you can shed some light on my problemsi currently calibrate the camera as followsdouble error calibratecameraworldpoints sensorpoints process size cameramatrix thistcoeffs rvecs tvecs calibration flagswhich generates the cameramatrix i need this part works i think because if i run this through initunthistortrectifymap followed by remap i get a valid image back however i am looking for the full image so the next thing i do is try to correct my cameramatrix as followsint alpha 1cameramatrix corr getoptimalnewcameramatrixcameramatrix thistcoeffs imagesize alphathen i generate the x and y maps for remap as follows this is borrowed directly from the opencv 20 cookbook so i am fairly confident it works tooinitunthistortrectifymap cameramatrix corr computed camera matrix thistcoeffs computed thistortion matrix mat optional rectification none mat camera matrix to generate unthistorted imagesize size of unthistorted cv 32fc1 type of output map map1 map2 the x and y mapping functionsfinally i remap my image apply mapping functionsremapimage unthistorted map1 map2 inter linearhere are my results so far if i use alpha 0 no change to the matrix i get reasonable though cropped resultsif i use alpha 1 which i think should give me an image with every original pixel mapped to the new image i get the followingso my question is this what am i doing wrong and why can i not just get an uncropped unthistorted image out of the calibrationthanks all for putting up with me this is my first question here but i tried to be as complete as possible let me know if i screwed up somehow,['c++'] +362066,how to estimate sql query timing i am trying to get an rough orderofmagnitude estimate of how long time the following query could takemysql explain select t1col1 t1 col4 from t1 left join t2 on t1col1t2col1 where col20 and col3 is null id select type table type possible keys key key len ref rows extra 1 simple t1 ref foobar foobar 4 const 9715129 1 simple t2 ref col1 col1 4 db2t1col1 42318 using where using index 2 rows in set 0 secmysql,['mysql'] +362070,how to set uicollectionviewdelegateflowlayout a uiviewcontroller maintains a reference to a uicollectionview the controller should modify the builtin flow layout using the uicollectionviewdelegateflowlayoutit is pretty easy to set the views data source to selfmyviewcontrollerm voidviewdidload selfcollectionviewdatasource selfbut how do i set the controller to be the delegate flow layout of the view voidviewdidload selfcollectionviewdatasource self selfcollectionview self i have tried voidviewdidload selfcollectionviewdatasource self selfcollectionviewcollectionviewlayout self but i get the error incompatible pointer types assigning the collection header file looks like thismyviewcontrollerhinterface myviewcontroller uiviewcontroller uicollectionviewdatasource uicollectionviewdelegateflowlayout,['ios'] +362071,how to hover over and click on an invisible element using selenium webdriver there is an invisible element on my html page which becomes visible when a mouse hover is done on the element what i have to do is hover over the element click on the element it will thisplay 4 options click on one of the optionsi am using java api for selenium web driver and following is what i have been tryingactions builder new actionsdriverbuildermovetoelementmainmenubtnclickbuildperformsubmenubtnclickmainmenubtn element that becomes visible when you hover the mouseover it submenubtn element that is being chosen out of the menu optionsthat are thisplayedwhat is happening is the click on mainmenubtn is generating elementnotvisible exceptioni tried following to avoid this but did not workactions builder new actionsdriverbuildermovetoelementmainmenubtnbuildperformbuilderclicksubmenubtnclicka note mainmenubtn and submenubtn are webelements generated bydriverfindelementbyxpathxpath stringam i missing anything help appreciated,['java'] +362162,why does ruby seem to hoist variable declarations from inside a case statement even if that code path is not executed we define a function foodef foos case s whenfoo x 3 puts xinspect when bar y 4 puts yinspect end puts xinspect puts yinspectendwe then call it as follows193p194 017 foofooin foo scope3in outer scope3nil nil 193p194 018 foobarin bar scope3in outer scopenil3 nil why does the function not throw an error about an unregistered local variable in either case in the first case the variable y seems like it should not exist so you cannot call inspect on it in the outer scope the same for x in the second caseheres another similar exampledef test1 x 5 if false puts xinspectenddef test2 puts xinspectendand then193p194 028 test1nil nil 193p194 029 test2nameerror undefined local variable or method x for mainobjectwhats going on here it seems like ruby is hoisting the variable declaration into the outer scope but i was not aware that this is something ruby does searching for ruby hoisting only turns up results about javascript hoisting,['ruby'] +362172,how can i thisable mod security in htaccess file how can we thisable mod security by using htaccess file on apache serveri am using wordpress on my personal domain and posting a post which content has some code block and as per my hosting provider said mod security gives an error and my ip has gone into firewall because of mod securityso i want to thisable mod security by using htaccess file,['php'] +362186,angularjs service broadcast and watch not triggering on receiving controller angularjs noob here on my path to the angular enlightenment heres the situationi have implemented a service audioplayer inside my module app and registered like so appserviceaudioplayer functionrootscope thisnext function loads the next track in the playlist thisloadtrackplaylistplayindex thisloadtrack functiontrack loads the track and plays it broadcast trackloaded event when done rootscopebroadcasttrackloaded track and heres the receiver controller mostly for ui presentation logicappcontrollerplayerctrl function playerctrlscope audioplayer audioplayer broadcasts the event when the track is loaded scopeontrackloaded functionevent track assign the loaded track as the current scopecurrent track scopenext function audioplayernext in my views i show the current track info like sodiv ngcontrollerplayerctrl button ngclicknextbutton p idinfocurrenttitle by currentauthorpdivthe next method is defined in the playerctrl and it simply invokes the same method on the audioplayer servicethe problemthis works fine when there is a manual interaction ie when i click on the next button the flow is the followingplayerctrl intercepts the click and fires its own next methodwhich in turn fires the audioplayernext methodwhich seeks the next track in the playlist and calls the loadtrack methodloadtrack broadcasts the trackloaded event sending out the track itself with itthe playerctrl listens the broadcast event and assigns the track to the current objectthe view updates correctly showing the currenttitle and currentauthor infohowever when the next method is called from within the audioservice in the background ie when the track is over all the steps from 1 to 5 do happen but the view does not get notified of the change in the playerctrls current objecti can see clearly the new track object being assigned in the playerctrl but it is as if the view does not get notified of the change i am a noob and i am not sure if this is of any help but what i have tried is adding a watch expression in the playerctrlscopewatchcurrent functionnewval oldval consolelogcurrent changedwhich gets printed out only during the manual interactionsagain like i said if i add a consolelogcurrent in the on listener like soscopeontrackloaded functionevent track scopecurrent track consolelogscopecurrentthis gets printed correctly at all timeswhat am i doing wrongps i am using audiojs for the html5 audio player but i do not think this is the one to blame here,['javascript'] +362213,search widget call onnewintent twice i have an activity in which i want to search when i click to search event onnewintent it is called twice what i am doing wrong i am creating searchview like thispublic override bool oncreateoptionsmenuimenu menu searchview new searchviewthis var searchmanager searchmanagergetsystemservicecontextsearchservice var searchableinfo searchmanagergetsearchableinfocomponentname searchviewsetsearchableinfosearchableinfo var search item menuaddnew javalangstringsearch search itemsetactionviewsearchview search itemsetshowasactionshowasactionifroom var edit menuadd0 insertitemid 0 insert editsetshowasactionshowasactionifroom editseticonandroidresourcedrawableicmenuadd return baseoncreateoptionsmenumenu log1017 074545491 iactivitymanager 900 start actandroidintentactionsearch flg0x10 cmpintranetintranetintranetscreenscontactlistactivity has extras from pid 29711017 074547562 wegl emulation 2971 eglsurfaceattrib not implemented1017 074547562 iactivitymanager 900 start actandroidintentactionsearch flg0x10 cmpintranetintranetintranetscreenscontactlistactivity has extras from pid 29711017 074548472 dopenglrenderer 2971 flushing caches mode 01017 074548481 ddalvikvm 900 gc concurrent freed 559k 13 free 7991k9159k paused 1ms1ms1017 074548500 winputmanagerservice 900 window already focused ignoring focus gain of comandroidinternalviewiinputmethodclientstubproxyb48b34701017 074548561 ddalvikvm 963 gc concurrent freed 389k 41 free 6027k10183k paused 0ms0ms,['android'] +362220,regex in javascript match a string like abc12 how to match the following string using regular expression in javascripthas a total of 5 characters first 3 charaters are capital letters last 2 characters are only numbersi have got this pattern az3092 but seems that it is still missing something thanks for help,['javascript'] +362253,how to see console log output in samsung galaxy s2 i am using samsung galaxy s2 version 233 i open a web page in android default web browserin the page i put consolelogsome info to debug the page but i am unable to see the consolelog output in my deviceplease help me in thisthanks in advance,"['javascript', 'android']" +362303,ios6 uilabel not center text aligned i am working on a ios app minimum ios 5 and i have just hit a weird issue with uilabels or maybe im missing something obvious anyway the problem im having is that i have a uilabel which is to be centered text aligned all works fine on ios 5 but on ios 6 it is always is left aligned i seen that the old way of doing uilabel text align has deprecated and that setting it as so should workselftopcommenttextalignment nstextalignmentcenterbut no even this way it still only is center aligned on ios 5 and left aligned on ios 6i do have some code that resizes the font of the text in the label to try make it fit with a min and max sizeuifont font selftopcommentfontforint i maxfont i minfont i set the new font size font font fontwithsizei cgsize constraintsize cgsizemakeselftopcommentframesizewidth 10 cgsize labelsize topstring sizewithfontfont constrainedtosizeconstraintsize linebreakmodeuilinebreakmodewordwrap iflabelsizeheight selftopcommentframesizeheight fits yes break selftopcommenttext topstringselftopcommentfont fontselftopcommenttext topstringso that is the only thing i am doing to the label but it always is left aligned in ios 6 important to note that if i drop in a uilabel with text and center align it and dont use the above code then it is centered on both ios 5 and 6,"['objective-c', 'ios']" +362325,asyncawait with configureawait is continueoncapturedcontext parameter and synchronizationcontext for asynchronous continuations i would like put the code first and then explain the situation and ask my question based on thatpublic partial class mainwindow window public mainwindow initializecomponent private async void button click 2object sender routedeventargs e var result await getvaluesasync footext result public async taskstring getvaluesasync using var httpclient new httpclient var response await httpclient getasync configureawaitcontinueoncapturedcontext false this is the continuation for the httpclientgetasync method we should not get back to sync context here cuz the continueoncapturedcontext is set to false for the task which is returned from httpclientgetasync method var html await getstringasync this is the continuation for the getstringasync method should i get back to sync context here cuz the continueoncapturedcontext is set to true for the task which is returned from getstringasync however getstringasync may be executed in another thread which has no knowledge for the sync context because the continueoncapturedcontext is set to false for the task which is returned from httpclientgetasync method but on the other hand getstringasync method also has a chance to be executed in the ui thread but we should not be relying on that html hey footext html return html public async taskstring getstringasync await taskdelay10 return done this is a fairly simple wpf sample which runs on net 45 and probably does not make a lot of sense but this should help me explain my situation i have a button on the screen which has an asynchronous click event when you look at the getvaluesasync code you will see the usage of await keyword twice with the first usage i set continueoncapturedcontext parameter of the taskconfigureawait method to false so this indicates that i do not necessarily want my continuation to be executed inside the synchronizationcontextcurrent so far so goodat the second await usage with the getstringasync method i did not call the configureawait method so i basically indicated that i want to get back to current synchronization context for the continuation of the getstringasync method so as you can see i try to set the textblocktext which belongs to ui thread property inside the continuationwhen i run the application and click the button i get an exception giving me the following message the calling thread cannot access this object because a different thread owns itat first this made no sense to me and i thought that i thiscovered a bug but then i realized that getstringasync may be executed in another thread highly likely which is different than the ui thread and has no knowledge for the sync context because the continueoncapturedcontext is set to false for the task which is returned from httpclientgetasync methodis this the case here also in this case is there a chance for getstringasync method to be posted back to ui thread bacuse the httpclientgetasync method continuation may be executed inside the ui threadi have also a few comments inside the code in view of my questions and the comments inside the code am i missing anything here,['c#'] +362329,convert varchar timestamp to timestamp i have a time stamp of the form 171628 sep 13 2011 pdt in a mysql database the type of the field in the database is varchar i would like to convert this varchar to a field of type timestamp in mysqli tried a few solutions suggested elsewhere on this site such as using a string to time function but these solutions all start from a different type of timestamphow do i convert the varchar timestamp mentioned above to a timestamp recognised by mysql in such a way that i can sort my data by date,['mysql'] +362350,datatype for systemversion in sql server what is the best way to store systemversion in sql serverwhen i use varchar type result of rrder by asc is1011012020,"['c#', '.net']" +362360,is sphinx already suitable for c documentation i want to try out documentation generators for a new project in c i think my options are either doxygen or sphinx since i have projects in python for which i would like to use sphinx i wonder whether sphinx is the right choice for c as well the sphinx website states that c is supported but i could not find a document to get me started with c documentation a similar question has already been thiscussed on stackoverflow and the main answer concludesnot yet fully usable but keep watchingsince the thiscussion is well over a year old i wonder whether this conclusion is still valid should i choose doxygen over sphinx for my c documentation,['c++'] +362371,is there a short contains function for lists i see people are using any to gather another list to see if an item exists in a list but is there a quick way to just doif listcontainsmyitem do something,['python'] +362423,integration test elastic search timing issue document not found i have an integration test in java of a facade that does a few things among which is an index operation into an elastic search database this elastic search database has been very naively set up out of the box stuff actually i am in the learning fase the insertion is done inside that facade with the java api also very naively with the example nearly completely copy pasted from elastic search as described here htmlafterwards i test a whether my facade did its stuff correctly part of it is checking whether that document has really been inserted in the database this i do again in the way elastic describes on their site i insert a document with a certain payload and look it up the same waythis test works if i run in debug and set a breakpoint after facade did it is stuff but it fails with no results found if i do not put this breakpoint or do not run in debug this makes me think i am really doing something wrong also the application itself works inserts and so on so there is likely something wrong with my integration test and not with my copy pasted codei guess that after the indexing operation returns the indexing is not really finished yet or there is some replication going on that does not complete before the search or something like that but it eludes me what exactly and i cannot seem to get it solved either i did not try to put elastic on one node and one shard yet maybe there is something wrong there but i do not really see what exactly so i did not walk that path yet like i said just started using elastic so i might be missing something crucial and beginnerstyle i can paste my exact code if needs be but like i said it boils down to using two code snippets from the elastic search site in a testkasper,['java'] +362435,my promises no longer working in jquery 18 this code snippet worked in 172 with both successerror callbacks as well as promises style callbacks with 182 the successerror callbacks still work but the promises do not my hunch is that the return dfdpromisejqxhr line is the problem but im not certainajaxprefilterfunction options originaloptions jqxhr do not infinitely recurse originaloptions retry isnanoriginaloptions retry commonauthmaxexpiredauthorizationretries originaloptions retry 1 set up to date authorization header with every request jqxhrsetrequestheaderauthorization commonauthgetauthorizationheader save the original error callback for later if originaloptionserror originaloptions error originaloptionserror overwrite current request error callback optionserror noop setup our own deferred object to also support promises that are only invoked once all of the retry attempts have been exhausted var dfd deferred jqxhrdonedfdresolve if the request fails do something else yet still resolve jqxhrfailfunction var args arrayprototypeslicecallarguments if jqxhrstatus 401 originaloptions retry 0 refresh the oauth credentials for the next attempts will be stored and returned by commonauthgetauthorizationheader commonauthhandleunauthorized retry with our modified ajaxoriginaloptionsthendfdresolve dfdreject else add our error callback to our promise object if originaloptions error dfdfailoriginaloptions error dfdrejectwithjqxhr args now override the jqxhrs promise functions with our deferred return dfdpromisejqxhrupdate here is my ajax request that failsajax url somefunctiontogeturl works success callback error ajaxerrorhandler then callback errorback ajaxerrorhandler,"['javascript', 'jquery']" +362441,find all numeric literals in java code i am supporting external code and i want to extract all constants and magic numbers from the code is there any fast way of doing it in eclipse,['java'] +362459,how to make height auto on colorbox i am using a jquery plugin called colorbox and basically it creates a jquery modal however the modal has a fixed size height of 500 and i want it to have a minimum height but also i have expending menus within the modal so i would like to to automatically expand how do i do thisthe code i currently have iscolorboxlink1colorbox opacity02 width450 height500 titleto close this dialog click x icon at the right iframetrueiv tried deleting the height from this and using css but that didnt work iv tried putting what i know of jquery in this line but nothing seems to work however i am pretty new to jquery anyone got any ideas,['jquery'] +362463,loaders and onloaderreset android i implemented a loader in my application for querying data from the database i listen the changes that happen by implementing loadercallbackscursor listener the problem that i have is when using the onloaderresetloadercursor loader method when my data change and i want to invalidate and free any data associated with the loader in all the examples in this method there is the following call madapterswapcursornullbut the thing is i do not use the data from the cursor in adapter i use it in some other way in my application directly from the returned cursor in onloadfinishedloadercursor loader cursor data for example override public void onloadfinishedloadercursor loader cursor data if datamovetofirst total cards datagetcount mviewcreatecardstotal cards else total cards 0 mviewcreatecardstotal cards what would be the corresponding thing to do here that is similar with madapterswapcursori do not have much experience with loaders in fact i just started working with them so if someone has a solution to this i would appreciate it thxeditfor now i am passing null to the loader and it works like thisoverridepublic void onloaderresetloadercursor loader loader nullbut is this the right solution,['android'] +362474,conditional operators in java throw an unexpected nullpointerexception possible duplicatenullpointerexception through autoboxingbehavior of java ternary operator the following code uses simple conditional operatorspublic class main public static void mainstring args integer exp1 true null 5 integer exp2 true null true null 50 systemoutprintlnexp1 exp1 exp2 exp2 integer exp3 false 5 true null 50 causes the nullpointerexception to be thrown systemoutprintlnexp3 exp3 this code compiles fine all the expressions ultimately attempt to assign null to integer type variables exp1 exp2 and exp3 respectivelythe first two cases do not throw any exception and produce exp1 null exp2 null which is obvious the last case however if you go through it carefully you will see it also attempts to assign null to integer type variable exp3 and looks something similar to the preceding two cases but it causes the nulpointerexception to be thrown why does it happenbefore i posted my question i have referred to this nice question but in this case i could not find what rules as specified by jls are applied here,['java'] +362478,twitter bootstrap center text on progress bar i have been using twitters bootstrap and i would like the text on the progress bar to be centered on the on bar regardless of valuethe below link is what i have now i would like all text to be aligned with the bottom most barscreenshoti have tried my best with pure css and i am trying to avoid using js if possible but i am willing to accept it if it is the cleanest way to do itdiv classprogress div classbar stylewidth 86517600divdiv,['css'] +362496,is there a way to intelligently fix documentation in eclipse back in my c days i loved using a visual studio extension called ghostdoc now that i am a being used as a java developer i am using eclipse i can live without being able to have inferred documentation but something that i would like to do is to intelligently fix my documentation for example let us assume i have the following method gets a collection of link foo objects param bar the bar level param baz the bazziness public collectionfoo getfoosint bar int baz do something coollater on in development i realize that it would be useful to allow the consumers of my method to pass in a qux value not only that but it makes the most sense to have it as the first parameter also i am going to have the method throw my super useful foobarexception so now my method looks like this gets a collection of link foo objects param bar the bar level param baz the bazziness public collectionfoo getfoosstring qux int bar int baz throws foobarexception do something coolbeing a good developer i want my changes reflected in my javadoc in ghostdoc i could hit my document shortcut key and it would add in the new stuff without thisturbing the old stuff in eclipse it renders a whole new set of javadoc and i have to do a bunch of copy pastaing is there a super cool shortcut or extension that i can execute that would automatically put in the new parameter exception and the missing return parameter into my javadoc without losing the javadoc that i currently have,['java'] +362516,is there a recommended amount of spacing between css sprites usually if i create css sprites i line them all up next to each other with no spacing at all for example if all the images are 10x10 pixels i would put them at the coordinates 010 020 1010 1020but this seems to cause problems in certain circumstances for example during page zooming and on mobile you can see the edge of the next sprite alongwhy does this problem occur is it to do with rounding errors is simply adding spacing around the sprites the best way to avoid the problem if so is there a minimum or recommended amount of spacing we should have between the icons in the sprite image,['css'] +362552,how can i make a view fill a relativelayout i have a relativelayout with some stuff in it and i want a background view to fill the whole thing this is what i would expect to work relativelayout androidlayout widthmatch parent androidlayout heightwrap content androidbackground0 view androidlayout widthmatch parent androidlayout heightmatch parent androidlayout alignparentlefttrue androidlayout alignparentrighttrue androidlayout alignparenttoptrue androidlayout alignparentbottomtrue androidlayout margin1px androidbackgroundfafafa imageview androidididim androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentlefttrue androidlayout centerverticaltrue androidsrcdrawableic blank profile and so onthat does not work it fills the width but the height gets set to zero however if i change layout alignparentbottom to layout alignbottomidim then it does work sort of that is not a satisfactory solution but at least it is not 0 height any morewhats going on is this a bug,['android'] +362588,scrolltop returns 0 in firefox but not in chrome not sure if there is another question regarding this if so i apologize and please do not release the houndsusing the html5 doctype and doing a quick consolelog off my scroll listener that tells me the value of scrolltop value i am basically doing this so when i scroll past a point i change the opacity of an element i am doing this using an mvs solution and i do not have the ability to push this to an external site so you can look heres a quick snippetvar opacity 1var scrolltop bodyscrolltopif scrolltop 200 opacity 01elementcssopacity opacityif i scroll in chrome i get a consolelogscrolltop thisplaying what i want ie 100 for each scroll i do and my opacity thisappears after i hit 200 scrolltop if i scroll in ff and ie7 the var returns 0 each scroll if i change bodyscrolltop to documentscrolltop then i get a null return on scrollany ideasthanks,"['jquery', 'html']" +362641,outofmemoryerror permgen space jasper report with spring running on tomcat our web application encounter a complicated situationit is a spring application developed by ststomcat 7 after the application been integrated with jasper report 460 it always throw outofmemoryerror permgen space then the only way to get it work is to restart the application but after a while it happen againhere is log before the exceptionoct 17 2012 34227 pm orgapachejaspercompilertldlocationscache tldscanjarinfo at least one jar was scanned for tlds yet contained no tlds enable debug logging for this logger for a complete list of jars that were scanned but no tlds were found in them skipping unneeded jars during scanning can improve startup time and jsp compilation timeoct 17 2012 34230 pm orgapachecatalinacoreapplicationthispatcher invokesevere servletservice for servlet jsp threw exceptionhere is a section within the exception where i found something about jasperat orgapachejaspercompilerjdtcompilergenerateclassjdtcompilerjava442at orgapachejaspercompilercompilercompilecompilerjava378at orgapachejaspercompilercompilercompilecompilerjava353at orgapachejaspercompilercompilercompilecompilerjava340at orgapachejasperjspcompilationcontextcompilejspcompilationcontextjava646at orgapachejasperservletjspservletwrapperloadtagfilejspservletwrapperjava240at orgapachejaspercompilertagfileprocessorloadtagfiletagfileprocessorjava578at orgapachejaspercompilertagfileprocessoraccess0tagfileprocessorjava49at orgapachejaspercompilertagfileprocessortagfileloadervisitorvisittagfileprocessorjava655here are a few findings when the situation occursthe issue can happen on page without any jasper report components it seems the jasper report bean is trying to find a tag lib all the time when a request is processed by the back end and responded to the front end normally from log file i can see above exception will not throw until all back end operationsjpa management are completewhen run log4j on debug mode i see tons of information showing something like parsingrendering the all components from jasper templatetextfields pen box there is a small cut from the huge log20121017 152912025 debug orgapachecommonsdigesterdigestersax startelement20121017 152912025 debug orgapachecommonsdigesterdigester pushing body text 20121017 152912025 debug orgapachecommonsdigesterdigester new matchjasperreportsummarybandtextfieldtextelement20121017 152912025 debug orgapachecommonsdigesterdigester fire begin for factorycreateruleclassnamenetsfjasperreportsenginexmljrtextelementfactory attributenamenull creationfactorynetsfjasperreportsenginexmljrtextelementfactory12dc600720121017 152912025 debug orgapachecommonsdigesterdigester factorycreaterulejasperreportsummarybandtextfieldtextelement new netsfjasperreportsenginedesignjrdesigntextfield20121017 152912025 debug orgapachecommonsdigesterdigestersax ignorablewhitespacestill this log is generated when a request to the page which does not contains any jasper componenti did some research but still cannot find the solution to this issue the first question is even there is a jasperreport bean in the application why it is always running when it is not even autowired with current servicemeaning current page does not have any jasper component is there a solutionanswer to this situationalso from the exception message at least one jar was scanned for tlds yet contained no tlds at orgapachejaspercompilerjdtcompilergenerateclassjdtcompilerjava442should comes from tomcat and tomcat never contains any jstl jar then i assume it cannot find a match tld to parse jasper report hence do a full scan of all jars if so then how come there is huge amount of debug logs from orgapachecommonsdigesterdigester actually seems busy on parsing the jasper templatein general make this thread is just try to figure out a solution to the probelm and also find an answer to why jasper is so active on a place does not require it and how we can let tomcat properly parsed the templatesapologize if too verbose and thanks for any hints,['java'] +362651,opencv python single rather than multiple blob tracking i have been trying to get single color blob tracking thru opencv on pythonthe below code is working but it finds the centroid of all the tracked pixels not just the centroid of the biggest blob this is because i am taking the moments of all the pixels but i am not sure how else to color tracki am kind of stuck on what exactly i need to do to make this a single blob tracker instead of a multiblob averageerheres the code usrbinenv python if using newer versions of opencv just import cvimport cv2cv as cvcolor tracker window color tracker class colortracker def init self cvnamedwindow color tracker window 1 selfcapture cvcapturefromcam0 def runself while true img cvqueryframe selfcapture blur the source image to reduce color noise cvsmoothimg img cvcv blur 3 convert the image to hsvhue saturation value so its easier to determine the color to trackhue hsv img cvcreateimagecvgetsizeimg 8 3 cvcvtcolorimg hsv img cvcv bgr2hsv limit all pixels that do not match our criteria in this case we are looking for purple but if you want you can adjust the first value in both turples which is the hue range120140 opencv uses 0180 as a hue range for the hsv color model thresholded img cvcreateimagecvgetsizehsv img 8 1 cvinrangeshsv img 120 80 80 140 255 255 thresholded img determine the objects moments and check that the area is large enough to be our object moments cvmomentsthresholded img 0 area cvgetcentralmomentmoments 0 0 there can be noise in the video so ignore objects with small areas ifarea 10 determine the x and y coordinates of the center of the object we are tracking by dividing the 1 0 and 0 1 moments by the area x cvgetspatialmomentmoments 1 0area y cvgetspatialmomentmoments 0 1area print x strx y stry area strarea create an overlay to mark the center of the tracked object overlay cvcreateimagecvgetsizeimg 8 3 cvcircleoverlay x y 2 255 255 255 20 cvaddimg overlay img add the thresholded image back to the img so we can see what was left after it was applied cvmergethresholded img none none none img thisplay the image cvshowimagecolor tracker window img if cvwaitkey10 27 break if name main color tracker colortracker color trackerrun,['python'] +362664,treating strings for insertion into xelement we gather lots of strings and send them to our clients in xml fragments these strings could contain literally any character weve been seeing an error caused by trying to serialize xelement instances that contain bad characters heres an examplevar message new xelementsongchar c char0x1a subvar somedata stringformatsome0stuff cvar attr new xattributesomeattr somedatamessageaddattrstring msgstr messagetostringsaveoptionsthisableformatting exception herethe code above generates an exception at the indicated line heres the stacktracesub hexadecimal value 0x1a is an invalid character systemargumentexception systemargumentexception hexadecimal value 0x1a is an invalid character at systemxmlxmlencodedrawtextwriterinvalidxmlcharint32 ch char pdst boolean entitize at systemxmlxmlencodedrawtextwriterwriteattributetextblockchar psrc char psrcend at systemxmlxmlencodedrawtextwriterwritestringstring text at systemxmlxmlwellformedwriterwritestringstring text at systemxmlxmlwriterwriteattributestringstring prefix string localname string ns string value at systemxmllinqelementwriterwritestartelementxelement e at systemxmllinqelementwriterwriteelementxelement e at systemxmllinqxelementwritetoxmlwriter writer at systemxmllinqxnodegetxmlstringsaveoptions omy suspicion is that this is not the correct behaviour and the bad char should be escaped into the xml whether this is desirable or not is a question i will answer laterso heres the questionis there some way of treating strings such that this error might not occur or should i simply strip all chars below char 0x20 and cross my fingers,['c#'] +362670,having clause vs subquery i could write a query using an aggregate function in two waysselect team countmin as min countfrom tablegroup by teamhaving countmin 500or select from select team countmin as min count from table group by team as awhere amin count 500are there any performance benefits to either approach or are they functionally the same thing,['sql'] +362684,implement for all classes bsonignoreextraelements i am using mongdb with mongodrive i wonder how i can implement to all my classes the bsonignoreextraelementsi know there is a way through the conventionprofile but i do not know how to implement it,['c#'] +362738,how to pass viewmodel to a layoutmaster page having googling for some time i am a little bit confused with how to do this in asp mvc 3so the task is to have a common layout or master page for several controllers views all the views are stronglytyped themselves this layout page in fact visualizes some stronglytyped object so i need this object to be passed to the layout page to pass it to htmlrenderpartial or to render it right in the pagethe article passing data to view master pages c though an old one for mvc2 gives an example to provide a base abstract controller class passing the model to viewdata this could be the cure butin some threads i found a way one could make a stronglytyped master page master inheritssystemwebmvcviewmasterpagemywebmodelsclient so is there the same approach in mvc3 or the only way to pass data to a layout page is to use viewbag or viewdatahaving read what is the best way to bind viewmodel data to master page in aspnetmvc i have considered darins answer but still think that this bunch of views will have the same layout and see no reason to go against dry principleso how to pass stronglytyped objects to layout pages or have i mixed something up,['c#'] +362781,add android support library v4 to intellij ide i am trying to use viewpager from android support library v4 in intelli j currently i am using the android sdk 41i copied androidsupportv4jar to my intellij android project under libsin the project settings of intelliji went to modules mymodulename dependencies tab and add the androidsupportv4jar by navigating the path to the libs folder under my own projecti checked the export besides this newly added jar filebut i still cannot use viewpager in my applicationi get a crash msg likejavalangruntimeexception unable to start activity componentinfocomxcomxmyactivity androidviewinflateexception binary xml file line 13 error inflating class androidsupportv4viewviewpager,['android'] +362790,email address validation in android on edittext how can we perform email validation on edittext in android i have gone through google so but i did not find out a simple way to validate it,['android'] +362794,ios unknown process unknown crash i have an intermittent crash which my users have been reporting i believe it to be a memory issue i have finally reproduced it on device i can not reproduce in the simulator however there is no exception no low memory warning and nothing from ios that calls any of the methods to exit the application it just exits and returns to the main screen does not even terminate but stays in the suspended app list there is an unknown crash log but i have no idea what it means is there any meaning that can be derived from this log my app is the one named srts the rpages value seems like it might be excessive but i am not sure any help in interpreting this crash log would be much appreciatedi am using xcode 451 and building to ios sdk 51incident identifier 4695578c43674be1860f94ff8562ecafcrashreporter key 9de810f246c07ab4704bd4f440fe9a3d0cab9401hardware model ipad21os version iphone os 60 10a403kernel version darwin kernel version 1300 sun aug 19 002805 pdt 2012 rootxnu21072334release arm s5l8940xdate 20121018 0140 0400time since snapshot 103 msfree pages 882active pages 3028inactive pages 1941throttled pages 104533purgeable pages 0wired pages 17730largest process srtsprocesses name uuid rpages recent max reason state mobilemail bff817c61ce33c85a43ea9a6c98c29f5 1010 1010 vm resume continuous mobilephone 3fca241f2a193d0fb8264218d296ea41 992 992 vm resume continuous kbd 3e7136ddcefc3d77a01499db593466cd 438 438 vm daemon tccd eb5ddcf533663f8d987d67cae6a4c4ea 179 179 vm daemon srts 66eed1e3358a33a4997bbf88dad284f2 90334 90334 vm audio frontmost resume ptpd 04a56fce67053c57a7979aeea8e5a7ea 677 677 daemon locationd 892cd1c9ffa43c99a82dba197be5f09e 535 535 daemon iaptransportd f784f30dc09d32078d87b450e8113ef6 287 287 daemon wifid 9472b090746237998cdbb9b34f090d0c 362 362 daemon mediaserverd 80657170daca32c9b8f3a6b1faac43a2 926 926 daemon syslogd cbef142fa0a839f0885afb693fb169c3 158 158 daemon springboard 27372aae101f3bbc87804edc10314af3 2031 2031 backboardd 5037235f295b33eda98eb5c72c098858 5629 5629 daemon networkd 0032f46009f53a6c80973fe153d1a588 206 206 daemon btserver c92fbd7488e63be99ec9dbd05824f5e5 347 347 daemon configd 4245d73a9e96360399452cf6b8671844 411 411 daemon fairplaydk93 47f0ea63619d351db2ef1b21790e89b9 178 178 daemon fseventsd 996cc4ca03793184aea8d781b55bce08 400 400 daemon imagent 1e68080947be352590ce96b7a1d07b2f 376 376 daemon mdnsresponder 3e557693f3073697a58da6d27a827d97 252 252 daemon lockdownd ba1358c7a8003f1b91af7d5f58dd5bbe 295 295 daemon powerd 2d2ffed5e69638aeba1b92ef124ed861 197 197 daemon usereventagent 6edfd8d8dba23187b05772dcdfc94f90 509 509 daemon debugserver 185719f06f1631d4922c652bdd4c8529 0 0 daemon gputoolsd 889065a15ba8372ca533e023c10bd776 0 0 daemon gputoolsd 889065a15ba8372ca533e023c10bd776 0 0 daemon gputoolsd 889065a15ba8372ca533e023c10bd776 0 0 daemonspringboardservi ff6f64b3a21a39c9a1793321eefa5304 0 0 daemon syslog relay 45e9844605d737a08368b5215bb54426 0 0 daemon syslog relay 45e9844605d737a08368b5215bb54426 0 0 daemonfilecoordination fbab576f37a63b56a1039153fc1aa7d8 169 169 daemonnotification pro 845b7beebc8538ca9ceef731031983b7 177 177 daemon thistnoted a89af76ec8633ac2bbe99bc2b7964bb0 177 177 daemon apsd 94d8051dd5f5362f82d775bc279ae608 370 370 daemon aggregated 8c3c991dc4153bc38aee1e841864d088 93 93 daemon notifyd 51c0e03da8a93ac8a595442fcaac531f 163 163 daemon reportcrash 8c32f231b2ed360bb151b2563bcaa363 234 234 daemonend,['ios'] +362798,force strings to utf8 from any encoding in my rails app i am working with rss feeds from all around the world and some feeds have links that are not in utf8 the original feed links are out of my control and in order to use them in other parts of the app they need to be in utf8how can i detect encoding and convert to utf8,"['ruby-on-rails', 'ruby']" +362808,creating c map from composite key i want to create a map that will contain composite key for example i have students roll no and semester in which heshe is studying now i want to create a map such that roll no and semester together act as the key for the map,['c++'] +362827,is there any way i can write copypaste nicelyformatted sql queries in java string literals using eclipse when i wish to use sql queries in java i usually hold them in final string variables now when the string is too large it goes out of page breadth and we either have to manually break it in eclipse go to a particular place in the string and place enter and do it for each of the resulting smaller part or we can set the formatter in eclipse to allow only say 100 characters per line but the string is not broken in a logical manner i can format a query nicely in sql developer say but if i paste that in java i will have to manually set all the end quotes and symbols to make it a proper java string i just want to know a way to have a properly formatted sql query copypasted directly into a java file i am using eclipseperhaps when a query is formatted like select from something where id4then when its pasted inside a java string we can have it like select from something where id4,['java'] +362853,java arrays how to add elements at the beginning i need to add elements to an arraylist queue whatever but when i call the function to add an element i want it to add the element at the beginning of the array so it has the lowest index and if the array has 10 elements adding a new results in deleting the oldest element the one with the highest indexdoes anyone have any suggestions,['java'] +362880,how to use for loop in mongodb i need to insert a new fieldcolumn to mongodb collection which has now 5246 documents the field should be auto incremented so that i use an for loop my query is as follows fori1i5246i dbcollupdatesetnew fieldifalsetrue but my bad the output is as new field5246new field5246new field5246is there any problem with query,['javascript'] +362926,accessing projects via dte in c t4 template i am currently trying to iterate over all of my projects sharepoint to get all feature guids into an file there i want to prefix them with the projects name my problem is dtesolutionitem and dtesolutionprojectsitem or the enumerators for foreach will not take an integer as parameter and foreach returns an object which is not castable to projecthere is my code snippet var hostserviceprovider iserviceprovider hostvar dte dte hostserviceprovidergetservicetypeofdtevar projectcount dtesolutionprojectscountvar projects new dictionarystring stringforeachproject dteproject in dtesolution var dteproject dtesolutionitemi projectsadteprojectname dteprojectfullnameokay the code is alright the debugger is notmy exceptions where thrown in a debug context but the template will run fine if the debugger is not attached,['c#'] +362944,visual studio 2012 winform designer is very slow weve recently migrated one of our winforms projects to visual studio 2012 from visual studio 2008 the transition has went remarkably smoothly and everything builds just fine however were now struggling with the winforms designer which is running incredibly slowto give an example if we open a small form the form contains two text boxes a numeric updown and two buttons all standard builtin controls nothing 3rd party it will take approximately 4045 seconds in 2012 however on 2008 it would open in 1 or 2 seconds for our larger forms this difference is much more pronounced in 2008 it would take about 7 seconds to open the form but in 2012 its taking over 6 minutes the worst part is that this is a blocking action vs2012 is almost completely unresponsive while opening the forms this also happens just by clicking on the h of a form so it is not like we can easily avoid it just by sticking to the code itselfhas anyone else experienced this does anyone know why it is happening and if there is anything that can be done about itadditional information our application is a ccli winforms app the behaviour is seen on all of our development machines which run windows 7 x64 my machine is a core i7 860 cpu with 12gb of ram over 60 free right now while i was benchmarking the above more than enough i would think in any case my system is by no means running slow it is just the vs2012 designeredit just for extra clarification we have not installed any addons or anything like that this is a virgin vs2012 installedit2 it does not seem to be a network thing either,['.net'] +363003,accidentally removed android dependencies folder i accidentally removed the library android dependencies is there a way to retrieve it or importdownload a person suggested me to go to source and say order import export for all libraries you need except the android defualt libs but i do not understand exactly what it means any advice would be greatly appreciated,['android'] +363035,substring in java length up to a value i am trying to make a substring which lets me have up to 6 letters of a surname however what i have here seems to throw an error when it finds a surname of less than 6 letters i have been looking for hours for a solution with no sucess id firstnamesubstring 01tolowercase secondnamesubstring 06tolowercasesystemoutprint here is your id number idit is the substring06 i need it to be up to 6 letters not exactly 6the errorexception in thread main javalangstringindexoutofboundsexception string index out of range 6 at javalangstringsubstringunknown source at testmaintestjava27,['java'] +363080,reduce the xcode simulator retina 4 inch i am using macbook air and using the iphone simulator i changed it to retina 4 inch and the screen of the simulator become so big is there a way to reduce the size,['ios'] +363090,nsnotification order of observer notifications if i have several classes observing a particular nsnotification in what order are the observers notified when the notification is posted,"['objective-c', 'ios']" +363096,how to reuse existing c class definitions in typescript projects i am just going to start use typescript in my html client project which belongs to a mvc project with a entity framework domain model already there i want my two projects client side and server side totally separated as two teams will work on this json and rest is used to communicate objects back and forthof course my domain objects on the client side should match the objects on the server side in the past i have normally done this manually is there a way to reuse my c class definitions specially of the pojo classes in my domain model to create the corresponding classes in typescript thanks,['javascript'] +363100,are there any samples of using cefglue or cefsharp in a windows forms application with minimum setup i am still using visual studio 2005 and wanting to embed a webkit browser within a c winforms application preferably as a winforms controli am looking for a simple example of either cefglue or cefsharp to get started with along with the minimum necessary dlls i cannot make any sense of the cefsharp sample on github,['c#'] +363166,subdomains actionviewtemplateerror missing host to link to i have worked through the numerous solutions to the error described in the title actionviewtemplateerror missing host to link to please provide the host parameter set default url optionshost or set only path to truehowever this project has also modified the url for function to make use of subdomains as seen in this railscastso the traditional answers to this error such as setting the variables in my environment settings do not seem to be the solutionhere are some other hintsthis is a brand new set up i have just cloned a project and installed ruby rails gems etci have tried rvm implode and starting over many timesthe rest of the team typically develops locally on macs while i am developing on a ubuntu machine remotelyi am working as root does this mattercompleted 500 internal server error in 1889msactionviewtemplateerror missing host to link to please provide the host parameter set default url optionshost or set only path to true 1 headermenurole banner 2 col980 3 h1 4 alogohref root urlsubdomain false 5 if current userpremium 6 imgalt contently src imageslogo beta premiumpng 7 else apphelpersurl helperrb16in url for appviewsshared logged in writer navhtmlhaml4in app views shared logged in writer nav html haml 656388632 107925510 appviewslayoutsapplicationhtmlhaml35in block in app views layouts application html haml 193634629 107212530 apphelpersapplication helperrb15inhtml5 haml tag appviewslayoutsapplicationhtmlhaml2in app views layouts application html haml 193634629 107212530 appcontrollersapplication controllerrb18inerror generic,"['ruby-on-rails', 'ruby']" +363167,is it normal for java library code to throw catch lots of exceptions during normal processing more as an experiment i decided to enable the following breakpoint in the eclipse debugger throwable include subclasses caught and uncaught i then let my code which is running fine as far as i know run under the debugger and was surprised to see dozens of exceptions being thrown and caught previously unknown to me by standard j2se library code when my code was running normally for all i know for example here are just some of the java framework functions i found throwing exceptions urlclassloaderfindclass filedircontextlookup and webappclassloaderfindclassinternalis this considered normal behavior for a java application is this something i should look into my code seems to be running fine as far as i know,['java'] +363198,sslpeerunverifiedexception peer not authenticated yet again the dreary problem of sslpeerunverified but i am not using self signed certificatesi try to connect to a host using https this host has a correct certificate neither firefox nor httpsurlconnection has any problems with ithowever trying to connect using httpclient i get the dreaded exceptionany clues or tip where to look closerthanksedit debug outputmain handling exception javaxnetsslsslhandshakeexception sunsecurityvalidatorvalidatorexception pkix path building failed sunsecurityprovidercertpathsuncertpathbuilderexception unable to find valid certification path to requested targetmain ioexception in getsession javaxnetsslsslhandshakeexception sunsecurityvalidatorvalidatorexception pkix path building failed sunsecurityprovidercertpathsuncertpathbuilderexception unable to find valid certification path to requested target,['java'] +363253,prompt javascript if else unexpected token else i am teaching myself javascript using code academy and i am trying to make some simple code so that when prompt asks a question the user reply gives a response exampleprompt says whats your favourite colouruser says blueresponse that is the same colour as the skybut when i try to add different options i get syntax error unexpected token elsei tried making it so that if i asked a question the reply gets a response but anything else gets a responseheres the codepromptwhat do you wantif cokeconsolelog no coke pepsielseconsolelog pepsi onlyif anyone has any ideas i would be very grateful,['javascript'] +363308,send and receive data in same ajax request with jquery what is the best way to send data and receive a response dependent on that dataconsider the php file used for the requesttest posttestecho json encodetesti have tried unsucessfully to achieve this withajax type post datatype json data test worked url ajaxgetdudephp success functionresponse alertresponse,"['php', 'jquery']" +363333,ios why do i have white rounded corners on my modal view i have a modal view popping up in my ipad app and for some reason it has white rounded cornersit might be worth noting i built this model view in my storyboard not programmatically however in my viewwillappear method i am setting the corner radius like so voidviewwillappearboolanimated super viewwillappearanimated selfviewlayercornerradius 60fwhen i set the value above 6 the white corners become visible how can i set the value higher without these white rounded corners showingthanks so much in advance for your wisdom,"['iphone', 'ios']" +363389,i want to allow invalid ssl certificates with afnetworking i want to allow invalid ssl certificatesmy main code is belowmyclient myclient alloc initmyclient gethtmlpathtothethistinationhtmlthe myclient class code is belowimport foundationfoundationhimport afnetworkinghinterface myclient nsobject voidgethtmlnsstring pathenddefine afnetworking allow invalid ssl certificates implementation myclient voidgethtmlnsstring path afhttpclient httpclient afhttpclient alloc initwithbaseurlnsurl urlwithstring httpclient getpathpath parametersnil successafhttprequestoperation operation id responseobject nslog responseobject failureafhttprequestoperation operation nserror error nslogerror error endi read below page and tried the macro but this does not workself signed certificate ssl a issue 189 a afnetworkingafnetworking please help me,['objective-c'] +363409,html5 content editable paragraph after list i use google chromei need to have a very tiny html editor and i found simple edit very small editor just for my needs however this and many other editors that are using content editable have one common problemproblemafter creating a list hit enter twice on last list item it creates a new div expected to me would be to create a new paragraph taglinkstry the editor here look at the tiny source code questionwhat is the correct way of prevent divs and instead add paragraph tags after a list,"['javascript', 'jquery']" +363418,jpa getuseclose of entitymanager and lazy loading ibm suggests that the best practice for using entitymanagers is getuseclose if entitymanager is not closed there is a chance that the same entitymanager may be used by more than one thread which will result in the following erroropenjpa212snapshotr42661179900 fatal general error orgapacheopenjpapersistencepersistenceexception multiple concurrent threads attempted to access a single broker by default brokers are not thread safe if you require andor intend a broker to be accessed by more than one thread set the openjpamultithreaded property to true to override the default behavior if you load an object which has onetomany collection mapped as fetchlazy like thispublic t findobject id t t null entitymanager em getem t emfindtype id emclose return tentitymanager getem ifthisem null thisemisopen thisem emfcreateentitymanager return thisemthe collection will always be null as by the time someone calls the getter entitymanager is closed the collection is only loaded if fetch is eager but that results in a sql join every single time which is slow so it is either multiple threads error or openjpamultithreadedtrue which is a bad practice or it is slow because of the sql join every single time even if the collection is not needed is there any way to do it properly so it is both fast with lazy fetch and done using best practices only,['java'] +363493,uipasteboard does not paste audio files i am developing an app in which one of the module is a simple listing tableview which shows the list of audio file when user selects any audio file an action sheet comes with one of the option sms i need to send the particular audio file through sms please let me know how to go with this and if this is not possible please provide me apple documentation so that it acts as a proof for me to showthis is what i have tried for pasting the audio filefirst wayuipasteboard pasteboard uipasteboard generalpasteboardnsstring path nsbundle mainbundle pathforresourceaudiofilename oftypecafnsdata mydata nsdata datawithcontentsoffilepathpasteboard setdatamydata forpasteboardtypeaudiofilensstring copypath nshomedirectory stringbyappendingpathcomponentdocumentsaudiofilecafnsurl sndurl nsurl fileurlwithpathcopypathpasteboard setstringnsstring stringwithformatsndurluiapplication sharedapplication openurlnsurl urlwithstringnsstring stringwithformatsms12345678second wayclass messageclass nsclassfromstringmfmessagecomposeviewcontrollerifmessageclass cansendtext messagepicker mfmessagecomposeviewcontroller alloc init messagepickermessagecomposedelegate self uipasteboard pasteboard uipasteboard generalpasteboard nsstring path nsbundle mainbundle pathforresource290912044119 oftypecaf nsdata mydata nsdata datawithcontentsoffilepath pasteboard setdatamydata forpasteboardtypeaudiofile nsstring copypath nshomedirectory stringbyappendingpathcomponentdocumentsaudiofilecaf nsurl sndurl nsurl fileurlwithpathcopypath messagepicker setbodynsstring stringwithformatsndurl self presentmodalviewcontrollermessagepicker animatedyes uiapplication sharedapplication setstatusbarhiddenyesi know that this is possible through posting onto server and retrieving from there but this is not the requirementany help would be appreciated and if it is not possible then please provide with apple documents,['iphone'] +363494,android sd card issues i currenlty have a few problems with developing an app and using the external sd cardthe first problem is that i check if there is a sd card mounted this function returns a true even if there is no sd card inserted i have usedtried the following code from developerandroidcomevery androidcompatible device supports a shared external storage that you can use to save files this can be a removable storage media such as an sd card or an internal nonremovable storage files saved to the external storage are worldreadable and can be modified by the user when they enable usb mass storage to transfer files on a computermaybe that is a problemi am using a lg l5 e610i have added the correct permission to the manifest filemy other issue could be related to this issueany help is very much appreciated thank you,"['java', 'android']" +363500,box sizing on inputs in firefox hides text i have an issue with firefox when applying mozboxsizing borderbox to inputs seems like the text i type in is somewhere hidden or overflown or somethingyou can see the issue in here test resize your window to a size smaller than 980px because it is a mobile version so what could be the issue there because i tried everything i could find and the only thing that worked is removing the mozboxsizing borderbox property,['css'] +363535,how to do an inner join on row number in sql server sql server 2008two tablestable a has following datarowarowbrowcrowdtable b has following datarow4row3row2row1i want to get the following outputrowa row1rowb row2rowc row3rowd row4the only common value between the two tables is the row numberi can get the data individually of courseselect valfrom aorder by valselect valfrom border by valbut how do i join on the row numberand what if i do not have an orderby but just want the rows in the order they come outrowa row4rowb row3rowc row2rowd row1as in the join ofselect valfrom aselect valfrom b,['sql'] +363543,uiswitch setthumbtintcolor causing crash ios 6 only update got a mail from apple saying that the bugissue has been fixed now and the next sdk release would not have this issue peacei have this in the code for my appdelegate void customizeappearance uiswitch appearance setontintcoloruicolor colorwithred0 green17502550 blue17602550 alpha10 uiswitch appearance settintcoloruicolor colorwithred2550f2550f green2550f2550f blue2550f2550f alpha10f uiswitch appearance setthumbtintcoloruicolor colorwithred09 green09 blue09 alpha10 which i then call from boolapplicationuiapplication application didfinishlaunchingwithoptionsnsdictionary launchoptionsi also use arc in ios 6 my app keeps crashing i enabled nszombie and it keeps saying uidevicergbcolor release message sent to deallocated instance 0x9658eb0and now i have realized one perfectly reproducible flow for the above when i comment out the setthumbtintcolor line alone inside customizeappearance then everything works fine as it should when i use the setthumbtintcolor line instead the app crashes the exact same way every time is this a known issue to anyone with uiswitchsetthumbtintcoloruicolor what else could be the cause if not the switch color,"['iphone', 'ios']" +363555,aptana building workspace extremely slow i am running a pretty big web application around 15gb on my local server and i just added the project into aptana it automatically started building the work space after being added and started slowing down drastically whenever it encounters a javascript file what exactly does building the workspace even do is there a way to shut it off if it is not much use it is been stuck at 24 scanning different js files for over 15 minutes now,['javascript'] +363593,nsattributedstring change style to bold without changing pointsize i am digging into nsattributedstrings on ios i have a model that is returning a persons first and last name as nsattributesstring i do not know if it is a good idea to deal with attributed strings in models i want the first name to be printed regular where as the last name should be printed in bold what i do not want is to set a text size all i found so far is this nsattributedstringattributedname nsmutableattributedstring name nsmutableattributedstring alloc initwithstringselfname name setattributesnsfontattributename uifont boldsystemfontofsizeuifont systemfontsize rangeselfname rangeofstringselflastname return namehowever this will of course override the font size of the last name which gives a very funny look in a uitableviewcell where the first name will be printed in the regular text size of the cells label and the last name will be printed very smallis there any way to achieve what i wantthanks for your help,"['iphone', 'ios']" +363612,android overriding onpause and onresume proper way when overriding the onpause and the onresume methods of the activity where is the proper location to call the superonpause and superonresume at the beginning of the method or at the end,"['java', 'android']" +363620,renewing provisioning profile and certificates i have 2 ios certificates one for development and one for thistribution app store both are expiring in 2 weeks i am on xcode 441 i have 2 development provisioning profiles and 4 thistribution provisioning profiles in xcode i see that all of the provisioning profiles tied to the thistribution certificate are set to expire in 2 weeks i went into the organizerprovisioning profiles and tried to renew but i received an error dialog indicating that no value was provided for the parameter deviceids when i look on the apple provisioning portal for that profile it shows that the certificate is expiring in 2 weeks and that there are no devices associated with it which is the way i have been doing it all alongso i am trying to renew these and have not done this before has anyone seen a similar error in xcode do i need to renew my certificate first and if so how i do not see any create new certifcate button on the provisioning portal or in xcode,['ios'] +363625,android tcp connection best practice i am working on an android application that requires a tcp connection to a tcp serverwritten in nodejsmy android tcp client is working an can send messages back and forthmy spesific questions is what is the best way to handle a tcp connection to a server in android how to maintain the connectionclose the connection properly on ondestroy etc is there any bether way then using an asynctaskexcept a normal thread class which is not allowed in android 40i have my socket connection in an asynctask like thisoverrideprotected void doinbackgroundvoid params try logdtcp message connecting socket new socketmy local ip 8080 dataoutput new dataoutputstreamsocketgetoutputstream inputstream new inputstreamreadersocketgetinputstream input new bufferedreaderinputstream while canceled string message inputreadline handlemessagemessage catch exception e eprintstacktrace return nullthe reason i have the connection in an asynctask is because i am using android 40 and are not allowed to have network code in a regular thread,['android'] +363637,listselectionlistener invoked twice class mylistlistener implements listselectionlistener public void valuechanged listselectionevent e jlist source jlist egetsource do something jlist mylist new jlist mymodel mylistaddlistselectionlistener new mylistlisteneri am doing something very simple i have a jlist if an item on the list is selected the handler is called the problem is the handler is invoked twice when i go from one item to another i can see the use if the first trigger passes on the original selected item and the second trigger passes on the new item but both times the same new item is passed what is the point of that is there a way to prevent the handler from being called twice,['java'] +363654,how to connect uiview outlets to a custom subview i am still new to xcode ios and have the following problemin order to thisplay some mobile debug information i have a uiview addedconnected as outletproperty to one of my viewcontroller this view is a custom subclass of uiview now i added some uilabels as sub views to this view and want to drag the outlet connections from these labels to my customuiviewh file in order to have these labels accessible as properties of my custom uiview class no need to access them directly from the view controllerproblem is that the interface builder i am using storyboards xcode43 does not make the trick i can connect the outlets to the viewcontrollerclassh but not to my sub views h filecan anyone point out where the problem is,['ios'] +363662,using datatoggle with htmlactionlink i want to use datatoggle wiht actionlink like this htmlactionlinkdelete users admin new itemuserid strrole strrole new id cmddelete hrefmyalert datatogglemodal unfortunately does not accept how can i use datatoggle like standart links,['c#'] +363672,how do i log the raw http request in aspnet web api whether or not it routes to a controller is it possible to log every http request made to an aspnet web api even if the request is malformed or for some other reason fails to route to one of the controllersfor example if a post method has an order model as it is parameter an incorrect request will prevent it from ever reaching the controllers post method i would like to alert someone so that actions can be taken to prevent future failuresis there a way to capture these requests further upstream from the controller,"['c#', 'asp.net']" +363695,which int type does var default to possible duplicatec shortlongint literal format reading up on the use of var in programming i am curious about what var defaults to when it is used for an int type for example if i usevar foo 65535will the type be ushort or just int thanks,['c#'] +363720,in opencv converting 2d image point to 3d world unit vector i have calibrated my camera with opencv findchessboard etc so i have camera thistortion coefficients intrinsics matrix camera pose information translation rotation computed separatedly via other means as euler angles a 4x4 2d points within the camera framehow can i convert these 2d points into 3d unit vectors pointing out into the world i tried using cvunthistortpoints but that does not seem to do it only returns 2d remapped points and i am not exactly sure what method of matrix math to use to model the camera via the camera intrinsics i have,['c++'] +363735,http live streaming duration less than 10 seconds allowed were trying to do low latency video on ios while complying with apples hls guidelines for video over cellular from a technical perspective we can set our extxtargetduration to and seconds where and is less than 10 think 2 or 3 seconds practically is this allowed does anyone have experiencing with an app getting approved when using hls segments of 5 seconds or fewer i have heard anecdotal evidence that this is not allowed regarding apples rules nothing i have seen has a restriction on segment minimums however there is a technical note that stateswe strongly recommend a 10 second target durationthe question is whether that recommendation is effectively an unstated rule source indexhtmlone further note apple provides a media stream validator tool which does not report errors on streams with target durations of 2 or 3 seconds that further suggests the stream duration is valid thank you for any experiencethoughts also if you know of any approved apps that you believe are using hls segments of 5 seconds or fewer that would also be helpful since i can check to see if they are indeed using shorter duration and use that as a comp for apples approval,['ios'] +363771,pdo error sqlstatehy0 general error when updating database i am getting an error when updating a database using pdoi am new to pdo so maybe the problem is a small one and i just do not understandfunny thing about the error the command works fine and the database does actually get updatedbut it still returns an error back at mecodetry stmt pdoprepareupdate page set section new content where section old content stmtexecutearray new content new content result stmtfetchall echo database updatedcatchpdoexception e echo error updating content egetmessageerrorerror updating content sqlstatehy0 general errori literally have no idea where the problem could be because its very vaque and i have not been able to find anyone with the same problem,['php'] +363775,programmatically connect and thisconnect android device i need to find a way to using an android application programmatically connect and thisconnect an android device from a hosti am using a galaxy nexus my goal is to keep everything as close to stock as possible though i have already enabled verbose debug messages in the kernel and in order to view them have enabled root access on the phone to access prockmsg and the shell command dmesgi am certain that there is a way to leverage root access to do what i need to do but all of my attempts have lead to nixmess with procbususbmess with devbususbchange between mtpptp unable to do programaticallymaking the android usb gadget driver into a module i am going to try to figure out how to do the last object on the list as then i would be able to rmmod and insmod the resulting ko in my application and that would connect and thisconnect the phone i am unsure of the feasibility of this option though,['android'] +363803,how to change the brightness of an image my question i want to be able to change the brightness of a resource image and have three instances of it as imageicons one at 50 brightness so darker another at 75 brightness a little brighter and finally another at 100 brightness the same as the original image i also want to preserve transparencywhat i have tried i have searched around and it looks like the best solution is using rescaleop but i just cannot figure it out i do not know what the scalefactor and the offset is all about heres my code for what i have triedpublic void initializestring imagelocation float regularbrightness float focusedbrightness float pressedbrightness string bordertitle throws ioexception bufferedimage bufferedimage imageioreadbuttoniconclassgetresourceimagelocation setregularicongetalteredimageiconbufferedimage regularbrightness setfocusedicongetalteredimageiconbufferedimage focusedbrightness setpressedicongetalteredimageiconbufferedimage pressedbrightness settitlebordertitle initprivate imageicon getalteredimageiconbufferedimage bufferedimage float brightness rescaleop rescaleop new rescaleopbrightness 0 null return new imageiconrescaleopfilterbufferedimage nullthe call would be something like thisseeatemplatebuttoninitializeresourcestemplateiconregularpng 100f 75f 50f see a templatei think my 100f 75f 50f variables need to change but whenever i change them it behaves unexpectedly changes colors and stuffwhat happens with that code the image appears invisible i know it is there because it is on a jlabel with a mouse clicked event on it and that works just fine if i just skip the brightness changing part and say setregulariconnew imageiconbuttonclassgetresourceimagelocation it works just fine but obviously it is not any darkerwhat i think i need some help understanding what offset scalefactor and the filter method meando and consequently what numbers to give for the brightness variableany help would be greatly appreciated thanks,['java'] +363813,ios app with django so we currently have a website that was created using django now we would like to create a native ios app that uses the same backend so we do not have to recode the whole thing from my understanding there are two alternative routes1 call directly django urls which then calls a function within that function create a httpresponse with encoded json data and send that back2 create a rest service from the django server with something like tastypie however aside from doing straightforward get calls to an object i do not see how we can call custom functions in our django models from tastypie can we even do thati find it surprising that there is not a lot of information about consuming a web service from ios with existing backends like django or ror for example i know that instagram uses django but how do they communicate from ios to their serversthanks a lot,['ios'] +363814,how to make a static variable threadsafe i have this static class which contains a static variable a simple int i have implemented a lock in the run method of the threads so no other threads can access to this class concurrently but the variable still goes crazy thisplaying duplicates insanely high values etcthis is the classpublic static class explorationmanager public static int counter 0 public static void explorermakerlistint validpaths liststring myparents string myexplorationmap listint mypositions foreach var thread in validpathsselect path new explorermyparents path myexplorationmap mypositions selectexplorer new threadexplorerexplore threadname thread of counter generation counter threadstart is there a way to make this variable more threadsafe,['c#'] +363824,taskwaitall hanging with multiple awaitable tasks in aspnet below is a simplified version of the code i am having trouble with when i run this in a console application it works as expected all queries are run in parallel and taskwaitall returns when they are all completehowever when this code runs in a web application the request just hangs when i attach a debugger and break all it shows that execution is wait on taskwaitall and the first task has completed but the others never finish i cannot figure out why it hangs when running in aspnet but works fine in a console applicationpublic foo doworkint values int count valueslength task tasks new taskcount for int i 0 i count i tasksi getfooasyncvaluesi try taskwaitalltasks catch aggregateexception handle exceptions return public async taskfoo getfooasyncint value foo foo null funcfoo task executecommand async command foo new foo using sqldatareader reader await commandexecutereaderasync readfooreader foo await queryasyncexecutecommand value return foopublic async task queryasyncfuncsqlcommand task executecommand int value using sqlconnection connection new sqlconnection connectionopen using sqlcommand command connectioncreatecommand set up query await executecommandcommand log results return,"['c#', 'asp.net']" +363837,how to debug failing tests in django how do i debug my tests for example i post to create an entry and expect it to validate and return a particular page it works in the browser and in the shell but the test is the only thing that fails ironically i would like to print the response to the console or something so i could read errors or what have you but i can only see things that i print in eg the viewnot sure it is necessary but heres the test code in question from testspy resp selfclientpostmealinvite summary test munch when now max diners 1 description munchies followtrue selfassertequalrespstatus code 200 selfassertcontainsresp test munch 1 selfassertcontainsresp you are hosting this meal 1the final assertion is incorrect if i change it to a value present in the original form page showing field required errors it passes i just cannot see what i am missingi have a few other tests working but i just do not know how to debug thishow is it done,['python'] +363924,msdeployexe can connect as administrator but not any other windows account i am integrating msdeploy into my build process and having problems authenticating the following command works finemsdeploy verbsync sourceapphostconfigkitchenpccomputername19216803usernameadministratorpasswordsecret destpackagecdeploytestkpcziphowever this does not workmsdeploy verbsync sourceapphostconfigkitchenpccomputername19216803usernamekpcpublishpasswordsecret destpackagecdeploytestkpczipand yields the errorerror code error user not adminmore information connected to 192168011 using the web deployment agent service but could not authorize make sure you are an administrator on 192168011 learn more at user not adminerror the remote server returned an error 401 unauthorizederror count 1i have followed the instructions in the link above and any other docs i could find which pretty much all say the same thingi created an account called kpcpublishi added this account to a group called msdepsvcusers heck i even added the account to administratorsi right clicked on the site and selected deployconfigure web deploy publishing and added kpcpublish to the list it says the followingpublish enabled for serverkpcpublish granted serverkpcpublishfull control on cwebsite successfully created settings filecusersadministratordesktopserver kpcpublish kitchenpcpublishsettingsthere must be some step i am missing but i just cannot figure out what could beupdateusing the full http path for the computername property i get the errorerror code error destination not reachable more information could not connect to the remote computer 19216803 on the remote computer make sure that web deploy is installed and that the required process web management service is started learn more at des tination not reachable error unable to connect to the remote server error a connection attempt failed because the connected party did not properly respond after a period of time or established connection fa iled because connected host has failed to respond 192168038192 error count 1i have checked and the web management service is indeed runninganother updatei have completely paved the system and set it up again from scratch i have done nothing out of the ordinary just installed the iis role and made sure to check management service under management tools which is required for wmsvc to run i then installed web pi and installed recommended configuration for hosting providers which will install web deploy 30 however i did notice there was an error while installing this i believe i got this error the last time as well it looks likei have also attached the log files herei then tried to install web deploy 30 manually however it says it is already installed next i downloaded the msi directly from and ran it in repair mode that seems to have worked i also noticed that the wmsvc service is up and running so this looks goodstill msdeploy will not connect i thought it might be some sort of firewall issue so i ran it locally i have tried using both https and http to connect https gives me an error http just times out after 23 minuteshttpsmsdeploy verbsync sourceapphostconfigdefault web sitecomputernamehttpsstaging8172msdeployaxdusernameadministratorpasswordkhorf123 destpackagecdeletemezipinfo using id f3a54096adc44f549e4fad8fde12edb6 for connections to the remote servererror code error certificate validation failedmore information connected to the remote computer staging using the specified process web management service but could not verify the servers certificate if you trust the server connect again and allow untrusted certificateslearn more at certificate validation failederror the underlying connection was closed could not establish trust relationship for the ssltls secure channelerror the remote certificate is invalid according to the validation procedureerror count 1httpmsdeploy verbsync sourceapphostconfigdefault web sitecomputernamehttpstaging8172msdeployaxdusernameadministratorpasswordkhorf123 destpackagecdeletemezipinfo using id ebee66f008e54d9d98ea0c2e59784895 for connections to the remote servererror could not complete the request to remote agent url httpstaging8172msdeployaxderror the operation has timed outerror count 1,['asp.net'] +363955,proper autoresizingmask i have a view that appears at the center of its parent view portrait mode what autoresizemask should i use so that it appears in the center in landscape mode too it is size should remain samei just want its origin should shift themselves automatically at the point so that it appears at the centerany help pleasei have givenparentview setautoresizessubviewyesparentviewautoresizingmask uiviewautoresizingflexibleheightuiviewautoresizingflexiblewidth,['ios'] +363995,install parse failed no certificates error in eclipse hi i have been looking at different post than we on the subject of error in error install parse failed no certificates eclipse but i have not yet found the cause and how to fix it i attached a screenshot of my eclipse to see an idea that visuali have no idea how to fix thissign the application for publication in google play since then i get this error it can be i can do because if they lose the project thank you very muchcapture my eclipse,['android'] +364003,scope in coffeescript classes i would like to nest a number of functions inside a class property as shown belowunfortunately they would not get access to the main scope of the classcan i solve this without passing each nested function a reference to thisclass myclass constructor errors dosomething errorspush i work as expected functions dostuff errorspush i cant access errors typeerror cannot call method push of undefined ugly context contexterrorspush it works but i am ugly works fine but requires scope injectionnonworking alternative using suggested fat arrowclass myclass constructor errors functions dostuff errorspush i wont work either typeerror cannot call method tostring of undefinedoptional alternative which does not write to the global thiserrors propertyclass myclass constructor functions errors dostuff errorspush i will write to functionserrors only,['javascript'] +364033,what is the difference between and 1 operators in a loop in c i usually encounter situations to use or 1 but i cannot tell their difference for instance if i have an integerint num 0and then in a loop i donum ornum 1they both increase the value of num but what is their difference i doubt num could work faster than num1 but how is this difference subtle enough to be ignored,['c++'] +364038,how do i test if a bitwise enum contains any values from another bitwise enum in c for instance i have the following enumflagspublic enum stuff stuff11 stuff22 stuff34 stuff48so i set mystuff to mystuff stuffstuff1stuffstuff2then i set hisstuff to hisstuff stuffstuff2stuffstuff3how do i now test if these overlap ie hisstuff and mystuff both contain at least one of the same enum valuesand also if there are multiple ways to do it which is the most efficient this is for a game,"['c#', '.net']" +364076,custom nstablecellview labels not changing text color when selected i have a custom nstablecellview with 3 textfields 1 that came along and 2 others that i created myself heres the problemthe textfields text color stays the same even when i click on the row i have tried to implement a code i found out by googling but it does not work my custom nstablecellview code is voiddrawrectnsrectdirtyrect nscolor color nscolor colorwithcalibratedred262550 green262550 blue262550 alpha10 selftextfield settextcolorcolor color nscolor colorwithcalibratedred1022550 green1022550 blue1022550 alpha10 lbl1 settextcolorcolor lbl2 settextcolorcolor voidsetbackgroundstylensbackgroundstylebackgroundstyle nscolor color backgroundstyle nsbackgroundstyledark nscolor windowbackgroundcolor nscolor controlshadowcolor selftextfieldtextcolor color selflbl1textcolor color selflbl2textcolor color super setbackgroundstylebackgroundstylewhat can i do to make the labels text color white when the user clicks on them,['objective-c'] +364149,java swing open source gantt chart library i am looking for a good open source gantt chart library for java swingi tried jfreechart but it is not able to draw subtaski tried with swiftgantt too it is able to draw subtask but it is a little unstable and the look and feel is not professional can you recomends othersthanks in advance,['java'] +364184,why does ios 5 fail to connect to a server running jdk 16 but not jdk 15 we have a java socket server listening on an sslsocket port 443 and an ios application that connects with it when running on ios 51 the application stopped working when we upgraded the java version of the server from jdk 15 to 16 or 17 the app connects just fine to jdk 5 and 6 when running on ios 6the ios app is reporting an error 9809 errsslcrypto on the java side we get javaxnetsslsslexception received fatal alert close notify on the java server side we have enabled all the available cipher suites on the client side we have tested enabling several different suites although we have yet to complete a test involving each one individually enabled right now it is failing when we use tls dh anon with aes 128 cbc sha although it has failed with others and we are starting to think it is not the suite here is the debug output it makes it all the way to serverhellodone and then fails shortly thereafteris secure renegotiation falseraw read length 50 16 03 03 00 41 araw read length 650 01 00 00 3d 03 03 50 83 1e 0b 56 19 25 65 c8 f2 pve0010 af 02 ad 48 fe e2 92 cf b8 d7 a6 a3 ea c5 ff 5d h0020 74 0f 1b c1 99 18 00 00 08 00 ff 00 34 00 1b 00 t40030 18 01 00 00 0c 00 0d 00 08 00 06 05 01 04 01 02 0040 01 urt read unknown33 handshake length 65 clienthello unknown33randomcookie gmt 13992971 bytes 86 25 37 101 200 242 175 2 173 72 254 226 146 207 184 215 166 163 234 197 255 93 116 15 27 193 153 24 session id cipher suites tls empty renegotiation info scsv tls dh anon with aes 128 cbc sha ssl dh anon with 3des ede cbc sha ssl dh anon with rc4 128 md5compression methods 0 unsupported extension signature algorithms data 06050104010201read md5 and sha1 hashes len 650 01 00 00 3d 03 03 50 83 1e 0b 56 19 25 65 c8 f2 pve0010 af 02 ad 48 fe e2 92 cf b8 d7 a6 a3 ea c5 ff 5d h0020 74 0f 1b c1 99 18 00 00 08 00 ff 00 34 00 1b 00 t40030 18 01 00 00 0c 00 0d 00 08 00 06 05 01 04 01 02 0040 01 created session1 tls dh anon with aes 128 cbc sha serverhello tlsv1randomcookie gmt 13992972 bytes 100 3 56 153 7 2 251 64 41 32 66 240 227 181 55 190 2 237 146 0 73 119 70 0 160 9 28 207 session id 80 131 30 12 241 73 52 38 46 41 237 226 199 246 156 45 3 247 182 43 223 8 49 169 188 63 160 41 102 199 50 190cipher suite tls dh anon with aes 128 cbc shacompression method 0extension renegotiation info renegotiated connection emptycipher suite tls dh anon with aes 128 cbc sha diffiehellman serverkeyexchangedh modulus 233 230 66 89 157 53 95 55 201 127 253 53 103 18 11 142 37 201 205 67 233 39 179 169 103 15 190 197 216 144 20 25 34 210 195 179 173 36 128 9 55 153 134 157 30 132 106 171 73 250 176 173 38 210 206 106 34 33 157 71 11 206 125 119 125 74 33 251 233 194 112 181 127 96 112 2 243 206 248 57 54 148 207 69 238 54 136 193 26 140 86 171 18 122 61 175 dh base 48 71 10 213 160 5 251 20 206 45 157 205 135 227 139 199 209 177 197 250 203 174 203 233 95 25 10 167 163 29 35 196 219 188 190 6 23 69 68 64 26 91 44 2 9 101 216 194 189 33 113 211 102 132 69 119 31 116 186 8 77 32 41 216 60 28 21 133 71 243 169 241 162 113 91 226 61 81 174 77 62 90 31 106 112 100 243 22 147 58 52 109 63 82 146 82 server dh public key 8 60 59 13 224 110 32 168 116 139 246 146 15 12 216 107 82 182 140 80 193 237 159 189 87 34 18 197 181 252 26 27 94 160 188 162 30 29 165 165 68 152 11 204 251 187 14 233 239 103 134 168 181 173 206 151 197 128 65 239 233 191 29 196 93 80 217 55 81 240 101 31 119 98 188 211 52 146 168 127 127 66 63 1 198 134 70 213 31 162 146 25 178 79 56 116 anonymous serverhellodonewrite md5 and sha1 hashes len 3830 02 00 00 4d 03 01 50 83 1e 0c 64 03 38 99 07 02 mpd80010 fb 40 29 20 42 f0 e3 b5 37 be 02 ed 92 00 49 77 b7iw0020 46 00 a0 09 1c cf 20 50 83 1e 0c f1 49 34 26 2e f pi40030 29 ed e2 c7 f6 9c 2d 03 f7 b6 2b df 08 31 a9 bc 10040 3f a0 29 66 c7 32 be 00 34 00 00 05 ff 01 00 01 f240050 00 0c 00 01 26 00 60 e9 e6 42 59 9d 35 5f 37 c9 by5 70060 7f fd 35 67 12 0b 8e 25 c9 cd 43 e9 27 b3 a9 67 5gcg0070 0f be c5 d8 90 14 19 22 d2 c3 b3 ad 24 80 09 37 70080 99 86 9d 1e 84 6a ab 49 fa b0 ad 26 d2 ce 6a 22 jij0090 21 9d 47 0b ce 7d 77 7d 4a 21 fb e9 c2 70 b5 7f gwjp00a0 60 70 02 f3 ce f8 39 36 94 cf 45 ee 36 88 c1 1a p96e600b0 8c 56 ab 12 7a 3d af 00 60 30 47 0a d5 a0 05 fb vz0g00c0 14 ce 2d 9d cd 87 e3 8b c7 d1 b1 c5 fa cb ae cb 00d0 e9 5f 19 0a a7 a3 1d 23 c4 db bc be 06 17 45 44 ed00e0 40 1a 5b 2c 02 09 65 d8 c2 bd 21 71 d3 66 84 45 eqfe00f0 77 1f 74 ba 08 4d 20 29 d8 3c 1c 15 85 47 f3 a9 wtm g0100 f1 a2 71 5b e2 3d 51 ae 4d 3e 5a 1f 6a 70 64 f3 qqmzjpd0110 16 93 3a 34 6d 3f 52 92 52 00 60 08 3c 3b 0d e0 4mrr0120 6e 20 a8 74 8b f6 92 0f 0c d8 6b 52 b6 8c 50 c1 and tkrp0130 ed 9f bd 57 22 12 c5 b5 fc 1a 1b 5e a0 bc a2 1e w0140 1d a5 a5 44 98 0b cc fb bb 0e e9 ef 67 86 a8 b5 dg0150 ad ce 97 c5 80 41 ef e9 bf 1d c4 5d 50 d9 37 51 ap7q0160 f0 65 1f 77 62 bc d3 34 92 a8 7f 7f 42 3f 6f c6 ewb4bo0170 86 46 d5 1f a2 92 19 b2 4f 38 74 0e 00 00 00 fo8turt write tlsv1 handshake length 383raw write length 3880 16 03 01 01 7f 02 00 00 4d 03 01 50 83 1e 0c 64 mpd0010 03 38 99 07 02 fb 40 29 20 42 f0 e3 b5 37 be 02 8 b70020 ed 92 00 49 77 46 00 a0 09 1c cf 20 50 83 1e 0c iwf p0030 f1 49 34 26 2e 29 ed e2 c7 f6 9c 2d 03 f7 b6 2b i40040 df 08 31 a9 bc 3f a0 29 66 c7 32 be 00 34 00 00 1f240050 05 ff 01 00 01 00 0c 00 01 26 00 60 e9 e6 42 59 by0060 9d 35 5f 37 c9 7f fd 35 67 12 0b 8e 25 c9 cd 43 5 75gc0070 e9 27 b3 a9 67 0f be c5 d8 90 14 19 22 d2 c3 b3 g0080 ad 24 80 09 37 99 86 9d 1e 84 6a ab 49 fa b0 ad 7ji0090 26 d2 ce 6a 22 21 9d 47 0b ce 7d 77 7d 4a 21 fb jgwj00a0 e9 c2 70 b5 7f 60 70 02 f3 ce f8 39 36 94 cf 45 pp96e00b0 ee 36 88 c1 1a 8c 56 ab 12 7a 3d af 00 60 30 47 6vz0g00c0 0a d5 a0 05 fb 14 ce 2d 9d cd 87 e3 8b c7 d1 b1 00d0 c5 fa cb ae cb e9 5f 19 0a a7 a3 1d 23 c4 db bc 00e0 be 06 17 45 44 40 1a 5b 2c 02 09 65 d8 c2 bd 21 ede00f0 71 d3 66 84 45 77 1f 74 ba 08 4d 20 29 d8 3c 1c qfewtm 0100 15 85 47 f3 a9 f1 a2 71 5b e2 3d 51 ae 4d 3e 5a gqqmz0110 1f 6a 70 64 f3 16 93 3a 34 6d 3f 52 92 52 00 60 jpd4mrr0120 08 3c 3b 0d e0 6e 20 a8 74 8b f6 92 0f 0c d8 6b n tk0130 52 b6 8c 50 c1 ed 9f bd 57 22 12 c5 b5 fc 1a 1b rpw0140 5e a0 bc a2 1e 1d a5 a5 44 98 0b cc fb bb 0e e9 d0150 ef 67 86 a8 b5 ad ce 97 c5 80 41 ef e9 bf 1d c4 ga0160 5d 50 d9 37 51 f0 65 1f 77 62 bc d3 34 92 a8 7f p7qewb40170 7f 42 3f 6f c6 86 46 d5 1f a2 92 19 b2 4f 38 74 bofo8t0180 0e 00 00 00 raw read length 50 15 03 01 00 02 raw read length 20 02 00 urt read tlsv1 alert length 2urt recv tlsv1 alert fatal close notifyurt called closesocketurt handling exception javaxnetsslsslexception received fatal alert close notifyfyi this works in ios 60,['java'] +364186,why am i getting undefined reference to dladdr even with ldl for this simple program i am working through an llvm tutorial but i am having trouble compiling i have written a minimal example that reproduces the issueinclude llvmmodulehinclude llvmllvmcontexthint mainint argc char argv llvmmodule module new llvmmoduletest llvmgetglobalcontext return 0when i try to compile i get a bunch of undefined reference errosclang llvmconfig cxxflags c o testo testcppclang testo llvmconfig ldflags libs core o testusrlibllvm29liblibllvmsupportasignalso in function printstacktracevoidtext0x6c undefined reference to dladdrusrlibllvm29liblibllvmsupportasignalso in function printstacktracevoidtext0x1f6 undefined reference to dladdrusrlibllvm29liblibllvmsupportamutexo in function llvmsysmuteximplmuteximplbooltext0x53 undefined reference to pthread mutexattr initusrlibllvm29liblibllvmsupportamutexo in function llvmsysmuteximplmuteximplbooltext0x64 undefined reference to pthread mutexattr settypeusrlibllvm29liblibllvmsupportamutexo in function llvmsysmuteximplmuteximplbooltext0x74 undefined reference to pthread mutexattr setpsharedusrlibllvm29liblibllvmsupportamutexo in function llvmsysmuteximplmuteximplbooltext0x88 undefined reference to pthread mutexattr destroyusrlibllvm29liblibllvmsupportamutexo in function llvmsysmuteximpltryacquiretext0x179 undefined reference to pthread mutex trylockusrlibllvm29liblibllvmsupportarwmutexo in function llvmsysrwmuteximplrwmuteximpltext0x3e undefined reference to pthread rwlock initusrlibllvm29liblibllvmsupportarwmutexo in function llvmsysrwmuteximplrwmuteximpltext0x80 undefined reference to pthread rwlock destroyusrlibllvm29liblibllvmsupportarwmutexo in function llvmsysrwmuteximplreader acquiretext0xb9 undefined reference to pthread rwlock rdlockusrlibllvm29liblibllvmsupportarwmutexo in function llvmsysrwmuteximplreader releasetext0xe9 undefined reference to pthread rwlock unlockusrlibllvm29liblibllvmsupportarwmutexo in function llvmsysrwmuteximplwriter acquiretext0x119 undefined reference to pthread rwlock wrlockusrlibllvm29liblibllvmsupportarwmutexo in function llvmsysrwmuteximplwriter releasetext0x149 undefined reference to pthread rwlock unlockusrlibllvm29liblibllvmsupportathreadingo in function llvmllvm execute on threadvoid void void unsigned inttext0x1cc undefined reference to pthread createusrlibllvm29liblibllvmsupportathreadingo in function llvmllvm execute on threadvoid void void unsigned inttext0x208 undefined reference to pthread attr setstacksizeusrlibllvm29liblibllvmsupportathreadingo in function llvmllvm execute on threadvoid void void unsigned inttext0x228 undefined reference to pthread joinclang error linker command failed with exit code 1 use v to see invocationmake test error 1if i view the manpage for dladdr it says that i need to link with ldl but i am already doing that with llvmconfig llvmconfig ldflags libs corelusrlibllvm29lib lpthread lffi ldl lm lvmcore lvmsupport lusrlibllvm29libadditionally ldl appears in the correct order ie after the o file that requires the symbolsi am at a loss for the next step in debugging this issue can anyone point me in the right direction i am running lvvm 297 on ubuntu 1204,['c++'] +364217,how to download inapp hosted content i followed to set up apple hosted inapp purchase it lists the products when i want to download the products from apple i do something like thisvoid paymentqueueskpaymentqueue queue updatedtransactionsnsarray transactions for skpaymenttransaction transaction in transactions switch transactiontransactionstate case skpaymenttransactionstatepurchased skpaymentqueue defaultqueue startdownloadstransactiondownloads void paymentqueueskpaymentqueue queue updateddownloadsnsarray downloads nslogpaymentques for skdownload download in downloads switch downloaddownloadstate case skdownloadstateactive nslogf downloadprogress break void paymentqueueskpaymentqueue queue removedtransactionsnsarray transactionsi started the download in updatedtransactions then updateddownloads is called by apple with downloadstate active then next apple calls removedtransaction without ever actually start the download the download progress is always 0 and updateddownloads is never called with downloadstate finishedi do not know why my download never started and why my transaction get removed before the download finishes anybody has a working sample,"['iphone', 'ios']" +364223,in angularjs how to access the element that triggered the event i use both bootstrap and angularjs in my web app i am having some difficulty getting the two to work togetheri have an element which has the attribute dataprovidetypeaheadinput idsearchtext ngmodelsearchtext typetext classinputmedium searchquery placeholdertitle dataprovidetypeahead ngchangeupdatetypeahead and i want to update the datasource attribute when the user inputs in the field the function updatetypeahead is triggered correctly but i do not have access to the element that triggered the event unless i use searchtext which is the jquery way not the angularjs waywhat is the best way to get angularjs to work with old style js module,['javascript'] +364232,how to delete an object of a polymorphic class type that has no virtual destructor i am getting the following error when i try to compile some code from a thirdparty sdkdescription resource path location typedeleting object of polymorphic class type avendor sysvendorcodea which has nonvirtual destructor might cause undefined behaviour werrordeletenonvirtualdtor pnservercpp pcounter line 467 cc problemi do not know if its possible to satisfy this condition with only partial knowledge of the vendors sdk where most of the heavy lifting is done in a dll or library objectmy build environment is eclipse juno with gppi searched in google for the error message and did not find any instances of this errorso if i cannot modify the black box part of the vendor code what are my optionshere is the code that is failing during the make processdelete pdataunit,['c++'] +364238,how to use adb pull command possible duplicatehow to copy selected files from android with adb pull i am using adb pull command like thisadb pull sdcardtrace cbut i show me remote object sdcardtrace does not exit i check trace files are in the sdcardnow how to pull these files from sdcardcan you help me how to fix,['android'] +364256,prims algorithm for mst adjacency list implementation in c i have this question for my programming class which i have been struggling to complete for the past day and i have no real idea what to do i understand the basic concept of prims algorithm1 start at an arbitrary node the first node will do and add all of its links onto a list 2 add the smallest link which does not duplicate an existing path in the mst to the minimum spanning tree remove this link from the list 3 add all of the links from the newly linked node onto the list4 repeat steps 2 3 until mst is achieved there are no nodes left unconnected i have been given this implementation of a graph using an adjacency list to implement prims algorithm on the problem is i do not really understand the implementation my understanding of the implementation so far is as followsbeing an adjacency list we have all the nodes in array form linked to this is a list of links containing details of the weight the destination and a pointer to the rest of the links of the specific nodesomething that looks a bit like this0 weight 1destination 3 weight 6destination 4null1 weight 4destination 3nulland so onwe also have an edge struct which i think is supposed to make things simpler for the implementation but i am not really seeing it here is the code givengraphh interfacetypedef struct int v int w int weight edgeedge edge int int inttypedef struct graph graphgraph graphinit int void graphinserte graph edge void graphremovee graph edge int graphedges edge graph ggraph graphcopy graph void graphdestroy graphint graphedgescan edge void graphedgeprint edgeint graphsearch graph intgraph graphmst graphgraph graphmstprim graphdefine maxv 8graphc implementation include stdlibhinclude stdiohinclude graphhdefine excha b edge t a a b b t define maxabababdefine minabababtypedef struct node linkstruct node int v int weight link next struct graph int v int e link adj static void sortedges edge edges int noofedgesstatic void updateconnectedcomponent graph g int from int to int newval int connectedcomponentedge edge int v int w int weight edge e v w weight return elink new int v int weight link next link x malloc sizeof x xv v xnext next xweight weight return x graph graphinit int v int v graph g malloc sizeof g set the size of the graph number of verticies gv v ge 0 gadj malloc v sizeoflink for v 0 v v v gadjv null return gvoid graphdestroy graph g not implemented yetvoid graphinsertegraph g edge e int v ev int w ew int weight eweight gadjv new w weight gadjv gadjw new v weight gadjw gevoid graphremoveegraph g edge e int v ev int w ew link curr curr gadjw while curr null if currv v curr currnext ge break curr currnext curr gadjv while curr null if currv w curr currnext break curr currnext int graphedges edge edges graph g int v e 0 link t for v 0 v gv v for t gadjv t null t tnext if v tv edgese edgev tv tweight return evoid graphedgeprint edge edge printf d d d edgev edgeweight edgewint graphedgescan edge edge if edge null printf graphedgescan called with null n abort if scanf d edgev 1 scanf d edgew 1 scanf d edgeweight 1 return 1 else return 0 update the cc label for all the nodes in the mst reachable through the edge fromto assumes graph is a tree will not terminate otherwisevoid updateconnectedcomponent graph g int from int to int newval int connectedcomponent link currlink gadjto connectedcomponentto newval while currlink null if currlinkv from updateconnectedcomponent g to currlinkv newval connectedcomponent currlink currlinknext insertion sort replace with on lon n alg to get optimal work complexity for kruskalvoid sortedges edge edges int noofedges int i int l 0 int r noofedges1 for i r1 i l i int j i while j r edgesjweight edgesj1weight exch edgesj edgesj1 j graph graphmst graph g edge edgessorted int i int connectedcomponent malloc sizeof int gv int sizeofcc malloc sizeof int gv graph mst graphinit gv edgessorted malloc sizeof edgessorted ge graphedges edgessorted g sortedges edgessorted ge keep track of the connected component each vertex belongs to in the current mst initially mst is empty so no vertex is in an mst cc therefore all are set to 1 we also keep track of the size of each cc so that were able to identify the cc with fewer vertices when merging two ccs for i 0 i gv i connectedcomponenti 1 sizeofcci 0 int currentedge 0 the shortest edge not yet in the mst int mstcnt 0 no of edges currently in the mst int v w the mst can have at most min ge gv1 edges while currentedge ge mstcnt gv v edgessortedcurrentedgev w edgessortedcurrentedgew printf looking at edge graphedgeprint edgessortedcurrentedge if connectedcomponentv 1 connectedcomponentw 1 graphinserte mst edgessortedcurrentedge mstcnt if connectedcomponentv connectedcomponentw connectedcomponentv mstcnt connectedcomponentw mstcnt sizeofccmstcnt 2 initialise a new cc else connectedcomponentv max connectedcomponentw connectedcomponentv connectedcomponentw max connectedcomponentw connectedcomponentv sizeofconnectedcomponentw printf is in mstn else if connectedcomponentv connectedcomponentw printf is not in mstn else printf is in mst connecting two mstsn graphinserte mst edgessortedcurrentedge mstcnt update the cc label of all the vertices in the smaller cc size is only important for performance not correctness if sizeofconnectedcomponentw sizeofconnectedcomponentv updateconnectedcomponent mst v v connectedcomponentw connectedcomponent sizeofconnectedcomponentw sizeofconnectedcomponentv else updateconnectedcomponent mst w w connectedcomponentv connectedcomponent sizeofconnectedcomponentv sizeofconnectedcomponentw currentedge free edgessorted free connectedcomponent free sizeofcc return mst my code so fargraph graphmstprim graph g initializations graph mst graphinit gv graph to hold the mst int i 0 int nodeisconnectedgv initially all nodes are not connected initialize as 0 fori 0 i gv i nodeisconnectedi 0 extract the first vertex from the graph nodeisconnected0 1 push all of the links from the first node onto a temporary list link templist newlist link vertex gadj0 whilevertex null templist prependtemplist vertex vertex vertexnext find the smallest link from the node mstadj0 some helper functions i have been writingstatic link newlistvoid return nullstatic link prependlink list link node link temp list list mallocsizeoflist listv nodev listweigth nodeweight listnext temp return liststatic link getsmallestlink list int nodeisconnected link smallest list whilelist null iflistweight smallestweightnodeisconnectedlistv 0 smallest list list listnext ifnodeisconnectedsmallestv 0 return null else return smallest for clarity file to obtain test data from fileinclude stdlibhinclude stdiohinclude graphh call with graph e1txt as input for exampleint main int argc char argv edge e edges graph g mst int graphsize i noofedges if argc 2 printf no size provided setting max no of vertices to dn maxv graphsize maxv else graphsize atoi argv1 g graphinit graphsize printf reading graph edges format v w weight from stdinn while graphedgescan e graphinserte g e edges malloc sizeof edges graphsize graphsize noofedges graphedges edges g printf edges of the graphn for i 0 i noofedges i graphedgeprint edgesi printf n mst graphmstprim g noofedges graphedges edges mst printf n mst n for i 0 i noofedges i graphedgeprint edgesi printf n graphdestroy g graphdestroy mst free edges return exit successthanks in advance lukefiles in full update i have had another attempt at this question here is the updated code one edit above to change the graph clientc to use graphmstprim function that i have writtengraph adjlistc include stdlibhinclude stdiohinclude graphhdefine excha b edge t a a b b t define maxabababdefine minabababtypedef struct node linkstruct node int v int weight link next nodestruct graph int v int e link adj typedef struct edgenode edgelinkstruct edgenode int v int w int weight edgelink nextedgenodestatic void sortedges edge edges int noofedgesstatic void updateconnectedcomponent graph g int from int to int newval int connectedcomponentedge edge int v int w int weight edge e v w weight return elink new int v int weight link next link x malloc sizeof x xv v xnext next xweight weight return x graph graphinit int v int v graph g malloc sizeof g gv v ge 0 gadj malloc v sizeoflink for v 0 v v v gadjv null return gvoid graphdestroy graph g not implemented yetvoid graphinsertegraph g edge e int v ev int w ew int weight eweight gadjv new w weight gadjv gadjw new v weight gadjw gevoid graphremoveegraph g edge e int v ev int w ew link curr curr gadjw while curr null if currv v curr currnext ge break curr currnext curr gadjv while curr null if currv w curr currnext break curr currnext int graphedges edge edges graph g int v e 0 link t for v 0 v gv v for t gadjv t null t tnext if v tv edgese edgev tv tweight return evoid graphedgeprint edge edge printf d d d edgev edgeweight edgewint graphedgescan edge edge if edge null printf graphedgescan called with null n abort if scanf d edgev 1 scanf d edgew 1 scanf d edgeweight 1 return 1 else return 0 update the cc label for all the nodes in the mst reachable through the edge fromto assumes graph is a tree will not terminate otherwisevoid updateconnectedcomponent graph g int from int to int newval int connectedcomponent link currlink gadjto connectedcomponentto newval while currlink null if currlinkv from updateconnectedcomponent g to currlinkv newval connectedcomponent currlink currlinknext insertion sort replace with on lon n alg to get optimal work complexity for kruskalvoid sortedges edge edges int noofedges int i int l 0 int r noofedges1 for i r1 i l i int j i while j r edgesjweight edgesj1weight exch edgesj edgesj1 j graph graphmst graph g edge edgessorted int i int connectedcomponent malloc sizeof int gv int sizeofcc malloc sizeof int gv graph mst graphinit gv edgessorted malloc sizeof edgessorted ge graphedges edgessorted g sortedges edgessorted ge keep track of the connected component each vertex belongs to in the current mst initially mst is empty so no vertex is in an mst cc therefore all are set to 1 we also keep track of the size of each cc so that were able to identify the cc with fewer vertices when merging two ccs for i 0 i gv i connectedcomponenti 1 sizeofcci 0 int currentedge 0 the shortest edge not yet in the mst int mstcnt 0 no of edges currently in the mst int v w the mst can have at most min ge gv1 edges while currentedge ge mstcnt gv v edgessortedcurrentedgev w edgessortedcurrentedgew printf looking at edge graphedgeprint edgessortedcurrentedge if connectedcomponentv 1 connectedcomponentw 1 graphinserte mst edgessortedcurrentedge mstcnt if connectedcomponentv connectedcomponentw connectedcomponentv mstcnt connectedcomponentw mstcnt sizeofccmstcnt 2 initialise a new cc else connectedcomponentv max connectedcomponentw connectedcomponentv connectedcomponentw max connectedcomponentw connectedcomponentv sizeofconnectedcomponentw printf is in mstn else if connectedcomponentv connectedcomponentw printf is not in mstn else printf is in mst connecting two mstsn graphinserte mst edgessortedcurrentedge mstcnt update the cc label of all the vertices in the smaller cc size is only important for performance not correctness if sizeofconnectedcomponentw sizeofconnectedcomponentv updateconnectedcomponent mst v v connectedcomponentw connectedcomponent sizeofconnectedcomponentw sizeofconnectedcomponentv else updateconnectedcomponent mst w w connectedcomponentv connectedcomponent sizeofconnectedcomponentv sizeofconnectedcomponentw currentedge free edgessorted free connectedcomponent free sizeofcc return mstedgelink newedgelistvoid return nulledgelink addedgelistedgelink list int node link edge printfedgeliststart edgelink temp list list mallocsizeofedgenode listw node listv edgev listweight edgeweight listnext temp printfedgelistend return list edgelink findsmallestedgelink waitlist int nodeisconnected printfsmalleststart edgelink smallest waitlist int small 9 whilewaitlist null ifwaitlistweight smallnodeisconnectedwaitlistv 0 smallest waitlist small smallestweight else printfnn smallest already used d waitlistv waitlist waitlistnext printfsmallestendifnodeisconnectedsmallestv 0 return smallest else printfreturning null return null link addlistedgelink smallest link list int v printfistsatt link temp list list mallocsizeofnode listv v listweight smallestweight listnext temp printflistend return list graph graphmstprim graph g graph mst graphinit gv graph to hold the mst int i 0 int v 0 int w 0 int nodeisconnectedgv array to hold whether a vertex has been added to mst int loopstarted 0 edgelink smallest null initially all nodes are not in the mst fori 0 i gv i nodeisconnectedi 0 whilesmallest nuloopstarted 0 printfv is d v add the very first node to the mst nodeisconnectedv 1 loopstarted 1 push all of its links onto the list link vertex gadjv edgelink waitlist newedgelist whilevertex null waitlist addedgelistwaitlist v vertex vertex vertexnext find the smallest edge from the list which does not duplicate a connection smallest findsmallestwaitlist nodeisconnected no nodes do not duplicate a connection return the current mst ifsmallest null return mst otherwise add the attributes to the mst graph w smallestw v smallestv mstadjv addlistsmallest mstadjv w mstadjw addlistsmallest mstadjw v return mstsummary of changes added edgelist to hold the edges that may be entered into the mst array nodeisconnected to track whether a node is in the mst function to select the smallest node if there is no node which does not duplicate a link this returns null,['c'] +364266,androidviewinflateexception binary xml file line 2 error inflating class i am developing a simple app just finished the home screen if the orientation changes more than two times it is throwing the error and application is force closingmy activity code public class passwordactivity extends activity implements onclicklistener button login button forgotbutton register private static final string preferences prefsprivate static final string preferences name pref name sharedpreferences settingsprivate cursor coverride public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain loginbuttonfindviewbyidridlogin login loginsetonclicklistenerthis registerbuttonfindviewbyidridlogin register registersetonclicklistenerthispublic void onclickview v my xml codexml version10 encodingutf8linearlayout xmlnsandroidandroidlayout widthfill parentandroidlayout heightwrap contentandroidorientationvertical androidbackgrounddrawablelistpiclinearlayout androidlayout widthfill parentandroidlayout heightwrap contentandroidorientationhorizontalandroidpaddingtop5dpandroidpaddingleft3dpandroidpaddingright3dp textview androidlayout widthfill parent androidlayout weight075 androidlayout heightwrap content androidtextstringlogin user name androidtextstylebold edittext androidlayout widthfill parent androidlayout heightwrap content androidlayout weight025 androidididlogin user name androidinputtypetext linearlayoutlinearlayout androidlayout widthfill parentandroidlayout heightwrap contentandroidorientationhorizontalandroidpaddingleft3dpandroidpaddingright3dp textview androidlayout widthfill parent androidlayout weight075 androidlayout heightwrap content androidtextstringlogin password androidtextstylebold edittext androidlayout widthfill parent androidlayout heightwrap content androidlayout weight025 androidinputtypetextpassword androidididlogin password linearlayoutlinearlayout androidlayout widthfill parentandroidlayout heightwrap contentandroidorientationhorizontalandroidpaddingleft3dpandroidpaddingright3dp button stylestyleleft button androidtextstringlogin submit androidididlogin login button stylestyleright button androidididlogin register androidtextstringregister linearlayoutlinearlayoutlog cat details1021 120559982 ddalvikvm622 gc external alloc freed 774 objects 56240 bytes in 61ms1021 120615031 ddalvikvm622 gc external alloc freed 737 objects 30992 bytes in 59ms1021 120618022 edalvikvmheap622 75960byte external allocation too large for this process1021 120618022 egraphicsjni622 vm would not let us allocate 75960 bytes1021 120618043 dandroidruntime622 shutting down vm1021 120618043 wdalvikvm622 threadid1 thread exiting with uncaught exception group0x4001d8001021 120618092 eandroidruntime622 fatal exception main1021 120618092 eandroidruntime622 javalangruntimeexception unable to start activity componentinfocomravipasswordcomravipasswordpasswordactivity androidviewinflateexception binary xml file line 2 error inflating class unknown1021 120618092 eandroidruntime622 at androidappactivitythreadperformlaunchactivityactivitythreadjava26631021 120618092 eandroidruntime622 at androidappactivitythreadmainactivitythreadjava46271021 120618092 eandroidruntime622 at javalangreflectmethodinvokenativenative method1021 120618092 eandroidruntime622 at javalangreflectmethodinvokemethodjava5211021 120618092 eandroidruntime622 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava8681021 120618092 eandroidruntime622 at comandroidinternaloszygoteinitmainzygoteinitjava6261021 120618092 eandroidruntime622 at dalviksystemnativestartmainnative method1021 120618092 eandroidruntime622 caused by androidviewinflateexception binary xml file line 2 error inflating class unknown1021 120618092 eandroidruntime622 at androidviewlayoutinflatercreateviewlayoutinflaterjava5131021 120618092 eandroidruntime622 at comandroidinternalpolicyimplphonelayoutinflateroncreateviewphonelayoutinflaterjava561021 120618092 eandroidruntime622 at androidviewlayoutinflatercreateviewfromtaglayoutinflaterjava5631021 120618092 eandroidruntime622 at androidviewlayoutinflaterinflatelayoutinflaterjava3851021 120618092 eandroidruntime622 at androidviewlayoutinflaterinflatelayoutinflaterjava3201021 120618092 eandroidruntime622 at androidviewlayoutinflaterinflatelayoutinflaterjava2761021 120618092 eandroidruntime622 at comandroidinternalpolicyimplphonewindowsetcontentviewphonewindowjava1981021 120618092 eandroidruntime622 at androidappactivitysetcontentviewactivityjava16471021 120618092 eandroidruntime622 at comravipasswordpasswordactivityoncreatepasswordactivityjava341021 120618092 eandroidruntime622 at androidappinstrumentationcallactivityoncreateinstrumentationjava10471021 120618092 eandroidruntime622 at androidappactivitythreadperformlaunchactivityactivitythreadjava26271021 120618092 eandroidruntime622 12 more1021 120618092 eandroidruntime622 caused by javalangreflectinvocationtargetexception1021 120618092 eandroidruntime622 at androidwidgetlinearlayoutinitlinearlayoutjava1151021 120618092 eandroidruntime622 at javalangreflectconstructorconstructnativenative method1021 120618092 eandroidruntime622 at javalangreflectconstructornewinstanceconstructorjava446 1021 120618092 eandroidruntime622 at androidviewlayoutinflatercreateviewlayoutinflaterjava500 1021 120618092 eandroidruntime622 22 more 1021 120618092 eandroidruntime622 caused by javalangoutofmemoryerror bitmap size exceeds vm budget 1021 120618092 eandroidruntime622 at androidgraphicsbitmapnativecreatenative method 1021 120618092 eandroidruntime622 at androidgraphicsbitmapcreatebitmapbitmapjava468 1021 120618092 eandroidruntime622 at androidgraphicsbitmapcreatebitmapbitmapjava435 1021 120618092 eandroidruntime622 at androidgraphicsbitmapcreatescaledbitmapbitmapjava340 1021 120618092 eandroidruntime622 at androidgraphicsbitmapfactoryfinishdecodebitmapfactoryjava488 1021 120618092 eandroidruntime622 at androidgraphicsbitmapfactorydecodestreambitmapfactoryjava4621021 120618092 eandroidruntime622 at androidgraphicsbitmapfactorydecoderesourcestreambitmapfactoryjava3231021 120618092 eandroidruntime622 at androidviewviewgroupinitviewgroupjava2851021 120618092 eandroidruntime622 26 more images are of very small size around 5kb,['android'] +364267,using readlines in python first time i have a text file with columns of data and i need to turn these columns into individual lists or arraysthis is what i have so farf opendatatxt rtemp for row in freadlines data rowsplit tempappendfloatdata0when i run this i get indexerror list index out of rangesnippet of the data below16 020 17 030 18 040 20 050 21 060 22 07024 080 25 09026 10 i need the first column if possible to look like thisdata 16 17 18 20 21 22 24 25 26,['python'] +364287,how to setup and launch a scrapy spider programmatically urls and settings i have written a working crawler using scrapynow i want to control it through a django webapp that is to say set 1 or several start urlsset 1 or several allowed domainsset settings valuesstart the spider stop pause resume a spiderretrieve some stats while runningretrive some stats after spider is completeat first i thought scrapyd was made for this but after reading the doc it seems that it is more a daemon able to manage packaged spiders aka scrapy eggs and that all the settings start urls allowed domains settings must still be hardcoded in the scrapy egg itself so it does not look like a solution to my question unless i missed something i also looked at this question how to give url to scrapy for crawling but the best answer to provide multiple urls is qualified by the author himeslf as an ugly hack involving some python subprocess and complex shell handling so i do not think the solution is to be found here also it may work for start urls but it does not seem to allow allowed domains or settingsthen i gave a look to scrapy webservices it seems to be the good solution for retrieving stats however it still requires a running spider and no clue to change settingsthere are a several questions on this subject none of them seems satisfactoryusingonescrapyspiderforseveralwebsitesthis one seems outdated as scrapy has evolved a lot since 07creatingagenericscrapyspiderno accepted answer still talking around tweaking shell parametersi know that scrapy is used in production environments and a tool like scrapyd shows that there are definitvely some ways to handle these requirements i cannot imagine that the scrapy eggs scrapyd is dealing with are generated by hand thanks a lot for your help,['python'] +364314,cancel notification on remove application from multitask panel i manage an ongoing notification from my application not from a servicewhen i kill application from task manager with end button notification thisappearwhen i remove application from multitask pannel application is killed but notification remainsmy questions arehow to catch this event to clear notificationwhat happens when application is removed from multitask pannel application is destroyed but process staying alive is it normalas an updateall my activities extends myactivity class which extends activity with methodsoverride protected void oncreatebundle state superoncreatestate myapplication getapplicationonactivitycreatethis stateoverride protected void ondestroy superondestroy myapplication getapplicationonactivitydestroythisand my application extends myapplication class which extends application with methodsprivate listactivity activities new arraylistactivityprotected final void onactivitycreateactivity activity bundle state ifactivitiesisempty state null onstart activitiesaddactivityprotected final void onactivitydestroyactivity activity activitiesremoveactivity ifactivitiesisempty activityisfinishing onexit protected void onstart some codeprotected void onexit some code notificationmanagercancelnotification idactivities is a list of all running activitiesit is not simplest mechanism but i need itshould i use a service insteadas a new updatein my onexit method if i log debug message to know what happens like thispublic void onexit forint i 0 i 100 i logdtag onexit a small amount of log appears once on two not all ex 13100so i understand that remove application from multitask pannel force to kill application without waiting close methods end to finish properly but why not process how can i force to terminate properly,['android'] +364317,trouble building the gcm demo server application whenever i try to build the gcm demo server from the documentation using ant i get 17 compilation errors it seems that some gcm libraries are missing how can i resolve these issues errors buildfile buildxmlinitcompile javac compiling 7 source files to rootgcmsamplesgcmdemoserverbuildclasses javac rootgcmsamplesgcmdemoserversrccomgoogleandroidgcmdemoserversendallmessagesservletjava18 package comgoogleandroidgcmserver does not exist javac import comgoogleandroidgcmserverconstants javac javac rootgcmsamplesgcmdemoserversrccomgoogleandroidgcmdemoserversendallmessagesservletjava19 package comgoogleandroidgcmserver does not exist javac import comgoogleandroidgcmservermessage javac javac rootgcmsamplesgcmdemoserversrccomgoogleandroidgcmdemoserversendallmessagesservletjava20 package comgoogleandroidgcmserver does not exist javac import comgoogleandroidgcmservermulticastresult javac javac rootgcmsamplesgcmdemoserversrccomgoogleandroidgcmdemoserversendallmessagesservletjava21 package comgoogleandroidgcmserver does not exist javac import comgoogleandroidgcmserverresult javac javac rootgcmsamplesgcmdemoserversrccomgoogleandroidgcmdemoserversendallmessagesservletjava22 package comgoogleandroidgcmserver does not exist javac import comgoogleandroidgcmserversender javac javac rootgcmsamplesgcmdemoserversrccomgoogleandroidgcmdemoserversendallmessagesservletjava46 cannot find symbol javac symbol class sender javac location class comgoogleandroidgcmdemoserversendallmessagesservlet javac private sender sender javac javac rootgcmsamplesgcmdemoserversrccomgoogleandroidgcmdemoserversendallmessagesservletjava59 cannot find symbol javac symbol class sender javac location class comgoogleandroidgcmdemoserversendallmessagesservlet javac protected sender newsenderservletconfig config javac javac rootgcmsamplesgcmdemoserversrccomgoogleandroidgcmdemoserversendallmessagesservletjava62 cannot find symbol javac symbol class sender javac location class comgoogleandroidgcmdemoserversendallmessagesservlet javac return new senderkey javac javac rootgcmsamplesgcmdemoserversrccomgoogleandroidgcmdemoserversendallmessagesservletjava81 cannot find symbol javac symbol class message javac location class comgoogleandroidgcmdemoserversendallmessagesservlet javac message message new messagebuilderbuild javac javac rootgcmsamplesgcmdemoserversrccomgoogleandroidgcmdemoserversendallmessagesservletjava81 package message does not exist javac message message new messagebuilderbuild javac javac rootgcmsamplesgcmdemoserversrccomgoogleandroidgcmdemoserversendallmessagesservletjava82 cannot find symbol javac symbol class result javac location class comgoogleandroidgcmdemoserversendallmessagesservlet javac result result sendersendmessage registrationid 5 javac javac rootgcmsamplesgcmdemoserversrccomgoogleandroidgcmdemoserversendallmessagesservletjava115 cannot find symbol javac symbol class message javac message message new messagebuilderbuild javac javac rootgcmsamplesgcmdemoserversrccomgoogleandroidgcmdemoserversendallmessagesservletjava115 package message does not exist javac message message new messagebuilderbuild javac javac rootgcmsamplesgcmdemoserversrccomgoogleandroidgcmdemoserversendallmessagesservletjava116 cannot find symbol javac symbol class multicastresult javac multicastresult multicastresult javac javac rootgcmsamplesgcmdemoserversrccomgoogleandroidgcmdemoserversendallmessagesservletjava123 cannot find symbol javac symbol class result javac listresult results multicastresultgetresults javac javac rootgcmsamplesgcmdemoserversrccomgoogleandroidgcmdemoserversendallmessagesservletjava127 cannot find symbol javac symbol class result javac result result resultsgeti javac javac rootgcmsamplesgcmdemoserversrccomgoogleandroidgcmdemoserversendallmessagesservletjava140 cannot find symbol javac symbol variable constants javac if errorequalsconstantserror not registered javac javac 17 errorsbuild failed,"['java', 'android']" +364333,what is the best way to implement an array of 3d vectors i decided to use eigen library in my projectbut it is not clear from documentation how the most efficiently one should specify an array of 3d vectorsas i suggest the first way is eigenmatrixeigenvector3d eigendynamic 1 array of v3dsize but in that case how should i get another array which elements are equal to scalar products of elements of array of v3d and some other instance of vector3din other words can i rewrite the following loop using eigens functionseigenvector3d v3d05 05 05 eigenvectorxd other arraysize for size t i 0 i size i other arrayi array of v3didotv3dthe second way is to use a matrix which size is 3 x size or size x 3for example i can declare it like thiseigenmatrixdouble 3 eigendynamic matrix but i did not get from the documentation how to set the number of columnsthe following seems to work but i have to repeat the number of rows 3 twiceeigenmatrixdouble 3 eigendynamic matrix3 size then the above loop is equivalent toother array v3dtranspose array of v3das my experiments shown that this is a little bit faster than eigenmatrixdouble eigendynamic 3 matrixsize 3 other array array of v3d v3din additionanyway my use of eigen seems to be not so optimal since the same program in plain c is almost 15 times faster it is not true indeed it depends on size for size t i 0 i size i4 si ai x bi y ci z si1 ai1 x bi1 y ci1 z si2 ai2 x bi2 y ci2 z si3 ai3 x bi3 y ci3 zhave i missed something is there some other way in the scope of eigen library to solve my problemupdatehere i present results of my testings there are 5 casescstyle for loop which is partially unrolledeigenmatrix rows x cols 3 x size in this case values of 3d vectors are stored together in memory because by default eigen stores data in columnmajor or i could set eigenrowmajor and everything else like in next case eigenmatrix rows x cols size x 3 here each component of 3d vector is stored on a separate vectorxd so there are three vectorxd objects which are put together on vector3dan stdvector container is used to store vector3d objectsthis is my test programinclude iostreaminclude iomanipinclude vectorinclude ctimeinclude eigendensedouble for loopsize t rep size t size stdvectordouble asize bsize csize double x 1 y 2 z 3 stdvectordouble ssize forsize t i 0 i size i ai i bi i ci i si 0 double dtime clock forsize t j 0 j rep j forsize t i 0 i size i 8 si ai x bi y ci z si ai1 x bi1 y ci1 z si ai2 x bi2 y ci2 z si ai3 x bi3 y ci3 z si ai4 x bi4 y ci4 z si ai5 x bi5 y ci5 z si ai6 x bi6 y ci6 z si ai7 x bi7 y ci7 z dtime clock dtime clocks per sec double res 0 forsize t i 0 i size i res stdabssi assertres 0 return dtimedouble eigen 3 sizesize t rep size t size eigenmatrixdouble 3 eigendynamic a3 size eigenmatrixdouble 1 eigendynamic ssize eigenvector3d x1 2 3 forsize t i 0 i size i a0 i i a1 i i a2 i i si 0 double dtime clock for size t j 0 j rep j snoalias xtranspose a dtime clock dtime clocks per sec double res sarrayabssum assertres 0 return dtimedouble eigen size 3size t rep size t size eigenmatrixdouble eigendynamic 3 asize 3 eigenmatrixdouble eigendynamic 1 ssize eigenvector3d x1 2 3 forsize t i 0 i size i ai 0 i ai 1 i ai 2 i si 0 double dtime clock for size t j 0 j rep j snoalias a x dtime clock dtime clocks per sec double res sarrayabssum assertres 0 return dtimedouble eigen vector3 vectorsize t rep size t size eigenmatrixeigenvectorxd 3 1 a a0resizesize a1resizesize a2resizesize eigenvectorxd ssize eigenvector3d x1 2 3 forsize t i 0 i size i a0i i a1i i a2i i si 0 double dtime clock for size t j 0 j rep j snoalias a0 x0 a1 x1 a2 x2 dtime clock dtime clocks per sec double res sarrayabssum assertres 0 return dtimedouble eigen stlvector vector3size t rep size t size stdvector eigenvector3d eigenaligned allocatoreigenvector3d asize stdvectordouble ssize eigenvector3d x1 2 3 forsize t i 0 i size i ai0 i ai1 i ai2 i si 0 double dtime clock for size t j 0 j rep j forsize t i 0 i size i si xdotai dtime clock dtime clocks per sec double res 0 forsize t i 0 i size i res stdabssi assertres 0 return dtimeint main stdcout size for loop matrix matrix vector3 of stl vector of n 3 x size size x 3 vector size tinyvectors n stdendl size t and 10 size t sizes 16 32 64 128 256 512 1024 2048 4096 8192 int rep all 1024 1024 1024 for int i 0 i n i size t size sizesi size t rep rep all size double t1 for loop rep size double t2 eigen 3 size rep size double t3 eigen size 3 rep size double t4 eigen vector3 vector rep size double t5 eigen stlvector vector3 rep size using namespace std cout setw8 size setw13 t1 setw13 t2 setw13 t3 setw14 t4 setw15 t5 endl the program was compiled by gcc 46 with options marchnative o2 msse2 mfpmathsse on my athlon 64 x2 4600 i got a nice table size for loop matrix matrix vector3 of stl vector of 3 x size size x 3 vector size tinyvectors 16 223 31 329 195 334 32 212 272 351 225 295 64 215 252 327 203 274 128 2 243 314 192 266 256 219 238 334 215 261 512 217 236 354 228 259 1024 216 235 352 228 258 2048 216 236 343 242 259 4096 1157 535 2029 1388 523 8192 1155 531 1617 1379 524the table shows that good representations of an array of 3d vectors are matrix components of 3d vectors should stored together and stdvector of fixed size vector3d objects this confirms jakobs answer for big vectors eigen indeed shows good results,['c++'] +364334,remove xticks in a matplot lib plot i have a semilogx plot and i would like to remove the xticks i tried pltgcaset xtickspltxticksaxset xticksthe grid thisappear ok but small ticks at the place of the main ticks remain how to remove them,['python'] +364356,how to create a dynamic width column in twitter bootstrap how do you use twitter bootstrap to create a tablelike list structure where some columns take as much space as required to accommodate the widest element of that column and a single column takes the remaining spacefor example id name email address 101joe 100 christine1001 john the id column takes just enough space to accommodate the 101 id which is the longest id the name column takes just enough space to accommodate the name christinethe email column takes the remaining space,"['javascript', 'html', 'css']" +364369,uicollectionview animation custom layout i am thisplaying lots of image cells in an uicollectionviewwith one button i would like to be able to group all my cell over the first onethis is working well but when i am trying to add an animation transition to my regroup action nothing happenshere the method i use in a custom layout nsarraylayoutattributesforelementsinrectcgrectrect nsarray allattributesinrect super layoutattributesforelementsinrectrect ifallattributesinrect count 0 isregroup uicollectionviewlayoutattributes firstattribute allattributesinrect objectatindex0 cgrect frame firstattributeframe foruicollectionviewlayoutattributes attribute in allattributesinrect uiview animatewithduration03f animationsattributeframe frame return allattributesinrect voidregroupcellsboolisregroup this method is called from my collection controller when my button is pressed isregroup isregroup self invalidatelayoutany idea thanks,['ios'] +364385,php socket listening loop with the following code i can receive 1 request and write itfunction listen set time limit to indefinite execution set time limit 0 set the ip and port we will listen on address x port x create a tcp stream socket sock socket createaf inet sock stream 0 bind the socket to an addressport bind socket bindsock address port start listening for connections socket listensock accept incoming requests and handle them as child processes client socket acceptsock read the input from the client 8211 1024 bytes input socket readclient 2024 strip all white spaces from input echo input close the master sockets close socket closesock var dumpcloselistenbut it close automatically listening once it received 1 packet i need to keep receiving packets until an exit or any close command is received how should i go about changing the code above to make this function into a loop,['php'] +364392,alias function in javascript possible duplicateif javascript has firstclass functions why doesnat this work when i try to make an alias function for documentgetelementbyid as belowf documentgetelementbyidbut when i try to callvar e fullname fafullnameait was rised an error could not convert javascript argumentand below is okvar e fullname fcalldocument afunnameacan you tell me why,['javascript'] +364490,serial code much slower than using only one thread in c so i was doing some benchmark tests with threads and i wrote these pieces of coderesp threadless and resp threaded are global int arrays and their size is nint and 10void function for long j 0 j n j int count 0 double x vetorj while x 10 x sqrtx count resp threadlessj count dword winapi function th lpvoid lpparam for long j 0 j n j int count 0 double x vetorj while x 10 x sqrtx count resp threadlessj count i benchmarked the first function by just calling herfunctionand the second one like thishandle hthreadarray1dword dwthreads1hthreadarray0 createthreadnull 0 function th null 0 dwthreads0waitformultipleobjects1 hthreadarray true infiniteclosehandlehthreadarray0keep in mind that i know that calling multiple threads using function th will not parallelize it this is just a test because i was having really strange results so i decided to see what would happen with one thread and one function using the same codei tested this in a intel atom n270 and windows xp with numproc 1resultsserial code 1485 msone thread 425 msi have had similar results using multiprocessor machines and even with code using semaphores to parallelize the work done by the threadsdoes anyone has any idea of what could be happeningeditinverting the order running multiple times each one etc no changehigher and thread one is proportionally even fasterusing queryperformancecounter no changethread creation overhead should make the threaded even one slower not fasteroriginal code,['c'] +364550,how do you debug an assembly loaded through assemblyloadbyte i am creating a plugin for a product that loads plugin dlls using assemblyloadbyte this is all very well and good but it means that i have no conventional means of loading the debugging symbols to step through my codethe crazy thing is several months ago i was having the exact same issue and solved it and boy was i proud of myself so i know it can be done i have just forgotten howi have a few vague memories of things i might have tried but i cannot tease the details out of my headnet reflectorprobably wrong though because i thistinctly remember stepping through the original cs fileusing iis express rather than cassinibut this strikes me as a weird solution the assembly is loaded from a bytearray so the framework knows nothing about where the dll came from or what an appropriate pdb might look like if it saw one this problem should exist in any environmentloading the symbols manually through the modules windowtried this i get the symbol file xpdb does not match the module because of course were loading from a bytearray not the dll itself,"['c#', '.net']" +364563,android app screen flashing at launch hi i have searched everywhere here and on google without getting a correct answer so i post a new questioni have several android apps that were working perfectly with 16 up to 23but now with android 40 ics i have users reporting that the screen is flashing on the homepage when the application is launched and nothing can be done but home and force stop the app then you can start the app again and it eventually works oi have tested the app on the emulator and on several devices including the galaxy s 3 with android 404 and i could never reproduce the issue it seems that the issue is mostly on the htc onehere is the simple code of the activitypublic class welcomepage extends activity called when the activity is first created overridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate eulashowthis on lui associe le layout setcontentviewrlayoutmain on racupa re tous les alaments button buttonguide buttonfindviewbyidridbuttonoui button buttonhotel buttonfindviewbyidridbuttonnon button buttonmap buttonfindviewbyidridbuttonmapg button buttonmaps buttonfindviewbyidridbuttonmaps button buttonmapb buttonfindviewbyidridbuttonmapb button buttontwitt buttonfindviewbyidridbuttontwitt button buttonfaceb buttonfindviewbyidridbuttonfaceb button buttongoogle buttonfindviewbyidridbuttongoogle button buttongeoloc buttonfindviewbyidridbuttongeoloc onclicklistener onclicklister new onclicklistener public void onclickview v intent intent switchvgetid si on a cliqua sur le button oui case ridbuttonoui bundle objetbunble new bundle objetbunbleputstringtitre phuket string lurl if getstringrstringlnguserlookequalsen lurl phuketen else lurl phuket objetbunbleputstringurl lurl intent new intentwelcomepagethis afficheguideclass toastmaketextwelcomepagethis getstringrstringtitguid phuket getstringrstringtitguid2 toastlength shortshow myapplicationgetapplicationcontextsetispagehelpfalse pas help en globale on affecte a lintent le bundle que lon a craa intentputextrasobjetbunble startactivityintent break case ridbuttonnon toastmaketextwelcomepagethis getstringrstringhotellist toastlength shortshow on craa lintent qui va nous permettre dafficher lautre activity intent new intentwelcomepagethis listedestinationallclass startactivityintent break case ridbuttongeoloc if extrasinternetisonline alertdialogbuilder builder new alertdialogbuilderwelcomepagethis buildersetmessagegetstringrstringtxtoffline setpositivebuttonok new dialoginterfaceonclicklistener public void onclickdialoginterface dialog int id dialogcancel createshow else toastmaketextwelcomepagethis geolocalisation toastlength shortshow intent new intentwelcomepagethis affichegeolocclass startactivityintent break case ridbuttonmapg toastmaketextgetapplicationcontext getstringrstringmap1 toastlength shortshow if extrasinternetisonline alertdialogbuilder builder new alertdialogbuilderwelcomepagethis buildersetmessagegetstringrstringtxtoffline setpositivebuttonok new dialoginterfaceonclicklistener public void onclickdialoginterface dialog int id dialogcancel createshow else toastmaketextwelcomepagethis phuket toastlength shortshow objetbunble new bundle cela fonctionne plus ou moins comme une hashmap on entre une clef et sa valeur en face objetbunbleputstringtitre phuket objetbunbleputstringurl phukettitrephuket intent new intentwelcomepagethis affichemapsclass on affecte a lintent le bundle que lon a craa intentputextrasobjetbunble startactivityintent break case ridbuttonmaps toastmaketextgetapplicationcontext getstringrstringmap2 toastlength shortshow bundle objetbunblemap new bundle objetbunblemapputstringtitre getstringrstringmap2 objetbunblemapputstringurl pic final intent intentm intentm new intentwelcomepagethis imageviewerjpclass intentmputextrasobjetbunblemap startactivityintentm break case ridbuttonmapb if extrasinternetisonline alertdialogbuilder builder new alertdialogbuilderwelcomepagethis buildersetmessagegetstringrstringtxtoffline setpositivebuttonok new dialoginterfaceonclicklistener public void onclickdialoginterface dialog int id dialogcancel createshow else on craa un objet bundle cest ce qui va nous permetre denvoyer des donnaes a lautre activity objetbunble new bundle objetbunbleputstringtitre getstringrstringtitevent3 phuket objetbunbleputstringurl getstringrstringurlevent2phuket intent new intentwelcomepagethis afficheeventsclass toastmaketextwelcomepagethis getstringrstringtitevent3 phuket toastlength shortshow on affecte a lintent le bundle que lon a craa intentputextrasobjetbunble startactivityintent break case ridbuttontwitt if extrasinternetisonline alertdialogbuilder builder new alertdialogbuilderwelcomepagethis buildersetmessagegetstringrstringtxtoffline setpositivebuttonok new dialoginterfaceonclicklistener public void onclickdialoginterface dialog int id dialogcancel createshow else toastmaketextwelcomepagethis twitter toastlength shortshow on craa lintent qui va nous permettre dafficher lautre activity intent new intentintentaction view intentsetdatauriparseresahotelthai startactivityintent break case ridbuttongoogle if extrasinternetisonline alertdialogbuilder builder new alertdialogbuilderwelcomepagethis buildersetmessagegetstringrstringtxtoffline setpositivebuttonok new dialoginterfaceonclicklistener public void onclickdialoginterface dialog int id dialogcancel createshow else toastmaketextwelcomepagethis google toastlength shortshow on craa lintent qui va nous permettre dafficher lautre activity intent new intentintentaction view intentsetdatauriparse startactivityintent break case ridbuttonfaceb if extrasinternetisonline alertdialogbuilder builder new alertdialogbuilderwelcomepagethis buildersetmessagegetstringrstringtxtoffline setpositivebuttonok new dialoginterfaceonclicklistener public void onclickdialoginterface dialog int id dialogcancel createshow else toastmaketextwelcomepagethis facebook toastlength shortshow on craa lintent qui va nous permettre dafficher lautre activity intent new intentintentaction view intentsetdatauriparse startactivityintent break on affecte aux button lacouteur dava nement buttonguidesetonclicklisteneronclicklister buttonhotelsetonclicklisteneronclicklister buttonmapsetonclicklisteneronclicklister buttonmapssetonclicklisteneronclicklister buttonmapbsetonclicklisteneronclicklister buttontwittsetonclicklisteneronclicklister buttonfacebsetonclicklisteneronclicklister buttongooglesetonclicklisteneronclicklister buttongeolocsetonclicklisteneronclicklistermathode qui se daclenchera lorsque vous appuierez sur le bouton menu du talaphonepublic boolean oncreateoptionsmenumenu menu craation dun menuinflater qui va permettre dinstancier un menu xml en un objet menu menuinflater inflater getmenuinflater instanciation du menu xml spacifier en un objet menu inflaterinflaterlayoutmenu menu il nest pas possible de modifier lica ne dentaate du sousmenu via le fichier xml on le fait donc en java menugetitem0getsubmenusetheadericonrdrawablelanguage return true mathode qui se daclenchera au clic sur un itempublic boolean onoptionsitemselectedmenuitem item intent intent on regarde quel item a ata cliqua grace a son id et on daclenche une action switch itemgetitemid case ridoption toastmaketextwelcomepagethis getstringrstringlanguage toastlength shortshow return true case ridfrench locale locale new localefr localesetdefaultlocale configuration config new configuration configlocale locale getbasecontextgetresourcesupdateconfigurationconfig getbasecontextgetresourcesgetthisplaymetrics myapplicationgetapplicationcontextsetstatefr passe langue en globale toastmaketextwelcomepagethis franaais toastlength shortshow intent new intentwelcomepagethis welcomepageclass on redamarre lactivity startactivityintent finish return true case ridenglish locale locale2 new localeen localesetdefaultlocale2 configuration config2 new configuration config2locale locale2 getbasecontextgetresourcesupdateconfigurationconfig2 getbasecontextgetresourcesgetthisplaymetrics myapplicationgetapplicationcontextsetstateen passe langue en globale toastmaketextwelcomepagethis english toastlength shortshow intent new intentwelcomepagethis welcomepageclass on redamarre lactivity startactivityintent finish return true case ridabout assigne un layout particulier a la dialogue box layoutinflater inflater layoutinflater welcomepagethisgetsystemservicelayout inflater service view layout inflaterinflaterlayoutafficheabout viewgroup findviewbyidridlayout root traitement du texte a afficher linkify pour que le lien soit cliquable textview text textview layoutfindviewbyidridtext final spannablestring s new spannablestringversion 110nwbloodicocomnncopyright a20112012nbloodico co ltd textsettexts linkifyaddlinkstext linkifyall traitement de limage a afficher a gauche imageview image imageview layoutfindviewbyidridimage imagesetimageresourcerdrawablesawadi construction de la dialogbox alertdialogbuilder adb new alertdialogbuilderwelcomepagethis adbsetviewlayout adbsettitleguidephuket adbseticonrdrawableic launcher on indique que lon veut le bouton ok a notre boite de dialogue adbsetpositivebuttonok null adbshow return true case ridhelp toastmaketextwelcomepagethis getstringrstringhelptitle toastlength shortshow on craa un objet bundle cest ce qui va nous permetre denvoyer des donnaes a lautre activity bundle objetbunble new bundle cela fonctionne plus ou moins comme une hashmap on entre une clef et sa valeur en face objetbunbleputstringtitre getstringrstringhelptitle objetbunbleputstringurl getstringrstringhelpurl intent new intentwelcomepagethis afficheguideclass on affecte a lintent le bundle que lon a craa intentputextrasobjetbunble startactivityintent return true case ridmorapp toastmaketextwelcomepagethis getstringrstringmorapp toastlength shortshow intent marketintent new intentintentaction viewsetdatauriparsemarketsearchqpubbloodicocoltd startactivitymarketintent return true return superonoptionsitemselecteditem and here is the layout usedxml version10 encodingutf8linearlayout xmlnsandroidandroidorientationverticalandroidlayout widthfill parentandroidlayout heightfill parentandroidgravitycenterandroidbackgrounddrawablefond imageview androidididimageintro androidlayout widthfill parent androidlayout heightwrap content androidsrcdrawablelogocompanyfr androidgravitycenter horizontal androidcontentdescriptionstringapp name linearlayout xmlnsandroid androidlayout widthwrap content androidlayout heightwrap content androidorientationhorizontal androidlayout margintop20dp button androidididbuttonoui androidlayout widthfill parent androidlayout heightfill parent androidlayout marginright20dp androidbackgrounddrawabletitreguidebutton button androidididbuttonnon androidlayout widthfill parent androidlayout heightfill parent androidlayout marginright20dp androidbackgrounddrawabletitrehotelbutton button androidididbuttongeoloc androidlayout widthfill parent androidlayout heightfill parent androidbackgrounddrawabletitregeolocbutton linearlayout linearlayout xmlnsandroid androidlayout widthwrap content androidlayout heightwrap content androidorientationhorizontal androidpaddingtop5dp button androidididbuttonmapg androidlayout widthfill parent androidlayout heightfill parent androidlayout marginright20dp androidbackgrounddrawabletitreinfobutton button androidididbuttonmaps androidlayout widthfill parent androidlayout heightfill parent androidlayout marginright20dp androidbackgrounddrawabletitremapsbutton button androidididbuttonmapb androidlayout widthfill parent androidlayout heightfill parent androidbackgrounddrawabletitremapbbutton linearlayout linearlayout xmlnsandroid androidlayout widthwrap content androidlayout heightwrap content androidlayout margintop100dp androidorientationhorizontal button androidididbuttonfaceb androidlayout widthfill parent androidlayout heightfill parent androidlayout marginright20dp androidbackgrounddrawabletitrefacebbutton button androidididbuttontwitt androidlayout widthfill parent androidlayout heightfill parent androidlayout marginright20dp androidbackgrounddrawabletitretwittbutton button androidididbuttongoogle androidlayout widthfill parent androidlayout heightfill parent androidbackgrounddrawabletitregooglebutton linearlayoutlinearlayoutand here is an excerpt of the manifest fileusessdk androidminsdkversion4 androidtargetsdkversion8 usespermission androidnameandroidpermissioninternetusespermission androidnameandroidpermissionaccess coarse location usespermission androidnameandroidpermissionaccess wifi state supportsscreens androidsmallscreenstrue androidnormalscreenstrue androidlargescreenstrue androidanydensitytrue application androidicondrawableic launcher androidlabelstringapp name androidnamemyapplication androidallowbackuptrue androidscreenorientationportrait activity androidnamewelcomepage androidscreenorientationportrait androidlabelstringapp name androidicondrawableic launcher androidthemeandroidstylethemenotitlebar intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activityany help would be grantly appreciated as i have more and more users concerned and can not find a way where to search,['android'] +364566,how can i get the list of dom elements that are located at a given position in the page possible duplicatelocating dom element by absolute coordinates i want to find out the list of all the dom elements that are located at the position where my mouse is clicked i require to do this using javascript or jquery could someone suggest me on how i could do this,"['javascript', 'jquery', 'html']" +364590,meteor set overall template context in meteor i can set various template helpers like thistemplatestorytitle function return titletemplate namestory h3titleh3 pdescriptionptemplatewhich is great but if i have a lot of variables i wouldnt want to set them individually i want to pass the context to the main templatehow do i do thattemplatestorydata function return titletitle descriptiondesctemplate namestory h3titleh3 pdescriptionptemplatethat does not work thanks,['javascript'] +364635,month and javautilformatter in the javadoc of javautilformatter i readm month formatted as two digits with leading zeros as necessary ie 01 13why 13,['java'] +364701,why are static imports of static methods with same names legal lets say we have these packages and classespackage p1public class a1 public static void a package p2public class a1 public static void a package p3import static p1a1aimport static p2a1apublic class a1 public static void test i am wondering why the static import of methods is legal would not result in compile time error in package p3 we would not be able to use them further in the test method as such usage will result in the compile time errorwhy it is not the same as with a normal import of classes lets say we would like to import classes a1 from packages p1 and p2 into p3package p3import p1a1import p2a1such import is illegal and will result in the compile time error,['java'] +364710,yii controller force https i would like to know how to force https ssl at yii controller action,['php'] +364749,checking for nan and using it in an if i am collecting some data from a database and adding them together to get some statistics but since i backdate some of my data then the calculated sum will sometime come up as nan not a number i want to create an if sentence that says ifnot a number then exclude this data from my tablehow do i test if the data in this case double is nan,['java'] +364750,is there a simple but useful jqueryjsplumb example for the last week i have been searching for some graphvisualization javascriptlibrary and i have stumbled upon jsplumb which is judging by the examples i have seen the best looking and most advanced library i have seen so far the documentation is while being quite big not very helpful as i cannot figure out how to actually perform the most essential tasksmy list of questions includeshow do i tell the graph to use predefined elements of the domtreewhat part of these elements will be thisplayedwhile making connections is easy how do i define the alignmentwhile these questions remain there are a few examples but either they are to simple to be of any use see example 1 or they are so complex that even retrievingwell the download is not a problem but i do not really want to analyse everything before playing around with some library the code is at least for me impossible see example 1 head script typetextjavascript src script script typetextjavascript src script script typetextjavascript srcpath tojqueryjsplumb1315allminjs script script typetextjavascript jsplumbbindready function var e0 jsplumbaddendpointcontainer0 e1 jsplumbaddendpointcontainer1 jsplumbconnect sourcee0 targete1 script head body div idcontainer0 div div idcontainer1 div bodywhich results incan anyone give me an example which answers my questionsthanks in advance,"['javascript', 'jquery']" +364753,cannot find module coffeescript trying to get a basic site set up with towerjs as a test but ran into this error when running the scaffold generatormacbookapp john tower generate scaffold post titlestring bodytext belongstouser error cannot find module coffeescript code module not found modulejs340 throw err error cannot find module usersjohnsitestowerappappconfigsharedapplication at functionmodule resolvefilename modulejs33815 at functionmodule load modulejs28025 at modulerequire modulejs36217 at require modulejs37817 at functiontowerapplicationapplicationreopenclassinstance usrlocallibnode modulestowerlibtowerapplicationserverapplicationjs4215 at extendnamespace usrlocallibnode modulestowerlibtowersupportsharedsharedjs21830 at generatorscaffoldgeneratortowergeneratorresourcesbuildapp usrlocallibnode modulestowerlibtowergeneratorserverresourcesjs27366 at generatorscaffoldgeneratorgenerator usrlocallibnode modulestowerlibtowergeneratorservergeneratorjs5723 at new generatorscaffoldgenerator usrlocallibnode modulestowerlibtowergeneratorservergeneratorstowerscaffoldscaffoldgeneratorjs2161 at functionrun usrlocallibnode modulestowerlibtowergeneratorservergeneratorjs2212,['javascript'] +364773,handling 2 3 4 5 fingers tapped doubletap holding gestures in winrt app i can easily handle 1 finger tapped doubletap and holding gestures like thispublic mainpage thisinitializecomponent thistapped mc tapped thisdoubletapped mc doubletapped thisholding mc holdingpublic void mc tappedobject sender tappedroutedeventargs e tappublic void mc doubletappedobject sender doubletappedroutedeventargs e doubletappublic void mc holdingobject sender holdingroutedeventargs e holdbut the events do not have a property to get the number of fingers and they do not even get fired when more than 1 touch contact is present on the screen i also want to handle 2 3 4 5 fingers tapped doubletap and holding gestures can anyone tell me how to do that,"['c#', '.net']" +364782,cannot add keyvaluepair directly to dictionary i wanted to add a keyvaluepairtu to a dictionaryt u and i could not i have to pass the key and the value separately which must mean the add method has to create a new keyvaluepair object to insert which cannot be very efficient i cannot believe there is not an addkeyvaluepairt u overload on the add method can anyone suggest a possible reason for this apparent oversight,['c#'] +364787,how to put json data in html javascript grid table i have the following jsonformatted data id 0050c263101a start 13497738382760 end 1349773838270 startarea areastart endarea areaend duration 10 id 0050c263101a start 13497738382760 end 13497738382780 startarea areastart endarea areaend duration 20 id 0050c263101a start 13497738382760 end 13497738382780 startarea areastart endarea areaend duration 20how can i thisplay this data nicely in a html data tableis there a plugin for jquery that can help memy basic approach is this,"['javascript', 'jquery', 'html']" +364821,how to suppress missing default launch image warning in xcode 45 xcode 45 gives a retina 4 support warning if you do not include a widescreen default launch image as part of your projectmy problem is that if i do not add the image my app works fine iphone 5s with the os adding some letterboxing to fill in the unused realestate but i have a warning i cannot get rid of if i do add an image the app uses the full screen which is a problem animations that play or start and stop partially offscreen now are onscreen etcso my question isis there a way to suppress the retina 4 support warningif not is there a way to add a default image while keeping the app in the nonwidescreen letterboxed mode,['ios'] +364865,return true if all column values are true is there a faster way in postgresql to essentially do an if on several rowssay i have a tableticket row archived1 1 true1 2 true1 3 true2 1 false2 2 trueis there any way i could do an if statement across down the column where ticket so that where ticket 1 would be true becausetrue true true trueand where ticket 2 would be false becausefalse true falseor should i just stick withselect select count from table where ticket 1 select count from table where ticket 1 and archived true,['sql'] +364881,c workaround for tuple with names i want immutable anonymous types with named members that can be passed around compared and recognized a merging of tuples and anonymous types this does not exist and i realize that so the question is what is a good idiomatic substitute for this using c4 or 5 the use case is fluid linq data processing from heterogeneous data sources in a word etl in c i do some pretty complex analysis and data comes from multiple platforms and sources it is not an option to just put it all on the same platform and use entity framework i want to able to fluidly pass around what are essentially arbitrary records immutable named sets of read only propertiesthe only thing i can come up with short of creating a custom immutable poco for every single otherwiseanonymous type is to use attributes to add compiled annotations to methods which return tuples certainly it wouldnt be hard to write a codegenerator for spitting out the immutable pocos but i hate how that clutters up the object model of a project using dynamic completely erases all the performance and designtime usefulness of static typing especially if composing further queries from the results of other methods so i do not consider it a viable solution my idea adding a attribute to methods to at least record the names of the columns of a tuple at a method levelpublic class namedtupleattribute attribute public string names get private set public namedtupleattributestring names thisnames names using namedtuple attribute to note meaning of members of tuplenamedtuplenew storenumber gross cost tax public ienumerabletupleint decimal decimal decimal getsales what i want imaginary msdn documentaion for c 6duck c referencethe duck keyword allows anonymous types to be used in all the staticallytyped features of c like normal anonymous types the compiler will treat anonymous types with the same number names and types of properties as having the same type however the duck keyword also allows these types to be used in member declarations and as type parameters for generic types 1 duck type instanceslike anonymous types instances of duck type objects can only be created using an object initializerwithout a type name the syntax is the same as for a normal anonymous type except that the keyword duck is added after the new operatorvar record new duck storenumber1204 transaction410 datenew datetime2012 12 13 gross13512m cost9780m tax1211m 2 duck type referencesduck types can be referenced using a duck type literal a duck type alias or implicitly when the return type of a property or method can be inferred21 duck type literalsa duck type can be expressed with a type literal which can be used in the place of any type reference duck type literals consist of the keyword duck followed by a list of name type identifier pairs just as in a parameter list of a method except enclosed in curly braces a duck type literalduck int storenumber int transaction datetime date decimal gross decimal cost decimal tax in a member declarationpublic duck int storenumber int transaction datetime date decimal gross decimal cost decimal tax gettransaction as a type parametervar transactions new listduck int storenumber int transaction datetime date decimal gross decimal cost decimal tax 22 duck type aliasesyou can assign an alias to a duck type with a using directive immediately after the namespace using directives in a c code file or namespace the alias may then be used in the place of any type reference namespace directivesusing systemusing odbc systemdataodbc duck type aliasesusing transtotal duck int storenumber int transaction datetime date decimal gross decimal cost decimal tax member declarationpublic transtotal gettransaction as a type parametervar transactions new listtranstotal23 inferred duck typesif the return type of a property or method can be inferred the body of a duck type literal may be omitted in a member declaration long formpublic duck int storenumber int transaction datetime date decimal gross decimal cost decimal tax getdummytransaction return new duck short formpublic duck getdummytransaction return new duck short form as a type parameterpublic ienumerabeduck gettransactions return from record in someprovidergetdetails where datetimerecorddatedate somedate group record by new storenumber intrecordnumber transaction intrecordtransnum date datetimerecorddate into transtotal select new duck transtotalkeystorenumber transtotalkeytransaction transtotalkeydate gross transtotalsumx decimalxgross cost transtotalsumx decimalxcost tax transtotalsumx decimalxtax,['c#'] +364887,java enums mutability usecases and possibilities i do not know if i am the only one to know that but the values of an enum are not implicitly final and can be modified enum enumtest totototo 1 tatatata 2 private string str private enumteststring str thisstr str override public string tostring return str public static void mainstring args systemoutprintlnenumtesttata enumtesttatastr newval systemoutprintlnenumtesttata tata 2newvalthese values are oftenly initialized at instance creation totototo 1 but except myself i have never seen anyone using the final keyword for enum variables that should be immutable that is not the point of the question just wondering if i am the only one aware of thiswhat i would like to know is if there was any usecase to create mutable enumsand i would also like to know the limits of what we can do with enums good practice or noti have not tested it but maybe an enum can be injected with spring beansat least it seems we can annotate each instance deprecated works fine for exemple and also the methods,['java'] +364898,gcm msg delivery times are wildly erratic i have setup an android app with gcm support and have a little test app to send a msg to the appwhen i run the app in the emulator i can see via logging msgs that it registers with gcm and gets a tokenthen when i put the token in my test app and have it send a msg the result shows that 1 msg was sent 0 failed and 0 had id changessometimes the msg shows up almost immediately sometimes it takes 20 minuteson friday my 2 test msgs took 15 and 20 minutesthe first 2 i sent this morning were immediately the next one has not shown up yet it is only been 10 minutesis there anything i can do to make the delivery times consistently fast a random 20 minute delay will be pretty much an unacceptable condition,['android'] +364942,using pyserial is it possble to wait for data i have got a python program which is reading data from a serial port via the pyserial module the two conditions i need to keep in mind are i do not know how much data will arive and i do not know when to expect databased on this i have came up with the follow code snipetscode from main loop spawning thread and waiting for datas serialserial5 timeout5 open com5 5 second timeoutsbaudrate 19200code from thread reading serial datawhile 1 tdata sread500 read 500 characters or 5 seconds iftdata len 0 if we got data ifselfflag got data is 0 if it is the first data we recieved store it selfdata tdata else if it is not the first append the data selfdata tdata selfflag got data 1so this code will loop forever getting data off the serial port well get up to 500 characters store the data then alert the main loop by setting a flag if no data is present well just go back to sleep and waitthe code is working but i do not like the 5s timeout i need it because i do not know how much data to expect but i do not like that it is waking up every 5 seconds even when no data is present is there any way to check when data becomes available before doing the read i am thinking something like the select command in linuxedit just thought i would note that i found the inwaiting method but really that seems it just change my sleep to a poll so that is not what i want here i just want to sleep until data comes in then go get it,['python'] +364953,execute jar file with multiple classpath libraries from command prompt i have a maven project which generates a jar file and copies all dependencies to targetlib folder i want to execute this project on clients machine windows so i copied myprojectjar to cxyz folder and all dependencies to cxyzlib folder how do i execute this project from clients command prompti tried to use java cp libjar jar myprojectjar from cxyz folder but it throws following errorexception in thread main javalangnoclassdeffounderror libcommonscodec13jarcaused by javalangclassnotfoundexception libcommonscodec13jar at javaneturlclassloader1rununknown source at javasecurityaccesscontrollerdoprivilegednative method at javaneturlclassloaderfindclassunknown source at javalangclassloaderloadclassunknown source at sunmisclauncherappclassloaderloadclassunknown source at javalangclassloaderloadclassunknown sourcecould not find the main class libcommonscodec13jar program will exiti think if i specify all dependencies in classpath like java cp libdep1jardep2jar it will get rid of the problem but i do not want to do this as i have 40 libraries already and it might grow in future releases is there a better way to do this,['java'] +364963,jspinclude param array i would like to pass an array as a parameter in a jspinclude code below does not workjspinclude pageheaderjsp jspparam namestylesheets valuelogincss jspparam namestylesheets valuelogin2css jspincludewhat is the right way to do this so that paramstylesheets logincss login2css,['java'] +364966,time sinceago library for androidjava any suggestions for a good library for androidjava to thisplay time sinceeg 10 minutes ago 5 days ago,['android'] +364967,convert character to html in r whats the prefered way in r to convert a character vector containing nonascii characters to html i would for example like to convert a14to uumli am aware that this is possible by a clever use of gsub but has anyone doen it once and for all and i thought that the package r2html would do that but it does notedit here is what i ended up using it can obviously be extended by modifying the dictionarychar2html functionx dictionary dataframe symbol ca14a a a a html caumlouml uumlauml ouml uumlszlig fori in 1dimdictionary1 x gsubdictionarysymbolidictionaryhtmlix xx cbuschwindraschen weiadornchar2htmlx,['html'] +365002,how to test if a parameter is provided to a function i was wondering can you create a function with a parameter that can be neglectedex this is not good code but it shows what i wantfunction parametertestbool if existsbool alertthe parameter exists else alertthe parameter does not exist so if you call parametertest then the result would be a message the parameter does not exist and if you call parametertesttrue then it would return the parameter exists can someone please help me is this possible,['javascript'] +365023,gcm why my application crash in gcmregistrarcheckdevicethis i have a simple application with a few lines because i am trying to figure out why my real application crashes in gcmregistrarcheckdevicethis if i delete it my application does not crash can anyone help public class demoactivity extends activity private string tag pushandroidactivity private textview mthisplay override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate gcmregistrarcheckdevicethis gcmregistrarcheckmanifestthis setcontentviewrlayoutmain mthisplay textview findviewbyidridthisplay mthisplaysettextciaomanifestmanifest xmlnsandroidpackagecomexampleregistrazionegcmandroidversioncode1androidversionname10 usessdk androidminsdkversion8 androidtargetsdkversion16 permission androidnamecomexampleregistrazionegcmpermissionc2d message androidprotectionlevelsignature usespermission androidnamecomexampleregistrazionegcmpermissionc2d message app receives gcm messages usespermission androidnamecomgoogleandroidc2dmpermissionreceive gcm connects to google services usespermission androidnameandroidpermissioninternet gcm requires a google account usespermission androidnameandroidpermissionget accounts keeps the processor from sleeping when a message is received usespermission androidnameandroidpermissionwake lock application androidicondrawableic launcher androidlabelstringapp name androidthemestyleapptheme activity androidnamedemoactivity androidlabelstringtitle activity demo intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity receiver androidnamecomgoogleandroidgcmgcmbroadcastreceiver androidpermissioncomgoogleandroidc2dmpermissionsend intentfilter action androidnamecomgoogleandroidc2dmintentreceive action androidnamecomgoogleandroidc2dmintentregistration category androidnamecomexampleregistrazionegcm intentfilter receiver service androidnamegcmintentservice applicationmy errors 1022 215421075 eandroidruntime955 fatal exception main1022 215421075 eandroidruntime955 javalangruntimeexception unable to start activity componentinfocomexampleregistrazionegcmcomexampleregistrazionegcmdemoactivity javalangunsupportedoperationexception device does not have package comgoogleandroidgsf1022 215421075 eandroidruntime955 at androidappactivitythreadperformlaunchactivityactivitythreadjava20591022 215421075 eandroidruntime955 at androidappactivitythreadhandlelaunchactivityactivitythreadjava20841022 215421075 eandroidruntime955 at androidappactivitythreadaccess600activitythreadjava1301022 215421075 eandroidruntime955 at androidappactivitythreadhhandlemessageactivitythreadjava11951022 215421075 eandroidruntime955 at androidoshandlerthispatchmessagehandlerjava991022 215421075 eandroidruntime955 at androidoslooperlooplooperjava1371022 215421075 eandroidruntime955 at androidappactivitythreadmainactivitythreadjava47451022 215421075 eandroidruntime955 at javalangreflectmethodinvokenativenative method1022 215421075 eandroidruntime955 at javalangreflectmethodinvokemethodjava51022 215421075 eandroidruntime955 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava7861022 215421075 eandroidruntime955 at comandroidinternaloszygoteinitmainzygoteinitjava5531022 215421075 eandroidruntime955 at dalviksystemnativestartmainnative method1022 215421075 eandroidruntime955 caused by javalangunsupportedoperationexception device does not have package comgoogleandroidgsf1022 215421075 eandroidruntime955 at comgoogleandroidgcmgcmregistrarcheckdevicegcmregistrarjava981022 215421075 eandroidruntime955 at comexampleregistrazionegcmdemoactivityoncreatedemoactivityjava161022 215421075 eandroidruntime955 at androidappactivityperformcreateactivityjava50081022 215421075 eandroidruntime955 at androidappinstrumentationcallactivityoncreateinstrumentationjava10791022 215421075 eandroidruntime955 at androidappactivitythreadperformlaunchactivityactivitythreadjava20231022 215421075 eandroidruntime955 11 more1022 215421085 wactivitymanager167 force finishing activity comexampleregistrazionegcmdemoactivity1022 215421095 wwindowmanager167 failure taking screenshot for 246x410 to layer 210101022 215421205 ijdwp265 ignoring second debugger accepting and dropping1022 215421395 ichoreographer167 skipped 40 frames the application may be doing too much work on its main thread1022 215421615 wactivitymanager167 activity pause timeout for activityrecord411d90d0 comexampleregistrazionegcmdemoactivity1022 215422177 ichoreographer265 skipped 120 frames the application may be doing too much work on its main thread1022 215432339 wactivitymanager167 activity destroy timeout for activityrecord411d90d0 comexampleregistrazionegcmdemoactivity,['android'] +365029,chrome blocking javascript on localhost i am working on developing a site on my local machine windows 7 ultimate x64 using wamp running apache v2 php 5313 and mysql v5524 i am developing using chrome v 220122994 i have got quite a bit of javascript in the site however and chrome is relentlessly blocking javascript from running on the pageclicking on the little blocked javascript on this page icon in the address bar includes the dropdown that has always allow javascript on localhost checked off and i also have a javascript exception in chromes settings explicitly saying to always allow javascript on httplocalhost cookies are being allowed allow all sites to run javascript is checked off and i have no idea as to why chrome is not allowing the javascript to runoverall it is not imperative to the project that i figure out a fix as both ie9 and firefox 161 are allowing javascript and i can utilize them i am simply curious if there is anything i can do to fix this in chrome as i would like to continue developing in chrome,['javascript'] +365035,get country code for timezone using pytz i am using pytz i have read through the entire documentation sheet but did not see how this could be done i have a timezone americachicago all i want is to get the respective country code for this timezone usit shows that i can do the opposite such as country timezonescheuropezurich country timezonescheuropezurichbut i need to do it the other way aroundcan this be done in python using pytz or any other way for that matter,['python'] +365040,why cannot i put hex value to byte array in java my code looks like thispublic byte s 0x63 0x7c 0x77 0x7b 0xf2 0x6b 0x6f 0xc5 0x30 0x01 0x67 0x2b 0xfe 0xd7 0xab 0x76 0xca 0x82 0xc9 0x7d 0xfa 0x59 0x47 0xf0 0xad 0xd4 0xa2 0xaf 0x9c 0xa4 0x72 0xc0 0xb7 0xfd 0x93 0x26 0x36 0x3f 0xf7 0xcc 0x34 0xa5 0xe5 0xf1 0x71 0xd8 0x31 0x15 0x04 0xc7 0x23 0xc3 0x18 0x96 0x05 0x9a 0x07 0x12 0x80 0xe2 0xeb 0x27 0xb2 0x75 0x09 0x83 0x2c 0x1a 0x1b 0x6e 0x5a 0xa0 0x52 0x3b 0xd6 0xb3 0x29 0xe3 0x2f 0x84 0x53 0xd1 0x00 0xed 0x20 0xfc 0xb1 0x5b 0x6a 0xcb 0xbe 0x39 0x4a 0x4c 0x58 0xcf 0xd0 0xef 0xaa 0xfb 0x43 0x4d 0x33 0x85 0x45 0xf9 0x02 0x7f 0x50 0x3c 0x9f 0xa8 0x51 0xa3 0x40 0x8f 0x92 0x9d 0x38 0xf5 0xbc 0xb6 0xda 0x21 0x10 0xff 0xf3 0xd2 0xcd 0x0c 0x13 0xec 0x5f 0x97 0x44 0x17 0xc4 0xa7 0x7e 0x3d 0x64 0x5d 0x19 0x73 0x60 0x81 0x4f 0xdc 0x22 0x2a 0x90 0x88 0x46 0xee 0xb8 0x14 0xde 0x5e 0x0b 0xdb 0xe0 0x32 0x3a 0x0a 0x49 0x06 0x24 0x5c 0xc2 0xd3 0xac 0x62 0x91 0x95 0xe4 0x79 0xe7 0xc8 0x37 0x6d 0x8d 0xd5 0x4e 0xa9 0x6c 0x56 0xf4 0xea 0x65 0x7a 0xae 0x08 0xba 0x78 0x25 0x2e 0x1c 0xa6 0xb4 0xc6 0xe8 0xdd 0x74 0x1f 0x4b 0xbd 0x8b 0x8a 0x70 0x3e 0xb5 0x66 0x48 0x03 0xf6 0x0e 0x61 0x35 0x57 0xb9 0x86 0xc1 0x1d 0x9e 0xe1 0xf8 0x98 0x11 0x69 0xd9 0x8e 0x94 0x9b 0x1e 0x87 0xe9 0xce 0x55 0x28 0xdf 0x8c 0xa1 0x89 0x0d 0xbf 0xe6 0x42 0x68 0x41 0x99 0x2d 0x0f 0xb0 0x54 0xbb 0x16 netbeans tells me possible loss of precision required byte found intwhat am i doing wrong if i use a short instead of the int it works correctly,['java'] +365057,fellow oak dicom changing image window level i am not an experienced programmer just need to add a dicom viewer to my vs2010 project i can thisplay the image in windows forms however cannot figure out how to change the window center and width here is my scriptdicomimage image new dicomimage filename int maxv imagenumberofframes sbslicemaximum maxv 1 imagewindowcenter 70 double wc imagewindowcenter double ww imagewindowwidth image result imagerenderimage0 thisplayimageresultit did not work i do not know if this is the right approach,"['c#', 'asp.net']" +365078,which is the preferred method to use jinja2 on app engine i originally implemented jinja2 on app engine using the examples shown on the app engine site here where jinja2 is imported directlyimport jinja2import osjinja environment jinja2environment loaderjinja2filesystemloaderospathdirname file class mainpagewebapp2requesthandler def getself greetings somestring template values greetings greetings template jinja environmentget templateindexhtml selfresponseoutwritetemplaterendertemplate valuesbut i am currently bolting on simpleauth which follows the implementation that nick johnson described here where jinja2 is imported from webapp2 extrasimport osimport webapp2from webapp2 extras import jinja2class basehandlerwebapp2requesthandler webapp2cached property def jinja2self return jinja2get jinja2appselfapp def render templateself filename template args selfresponsewriteselfjinja2render templatefilename template argsclass indexhandlerbasehandler def getself selfrender templateindexhtml nameselfrequestgetnamewhich of these is the preferred method for using jinja2 they do not seem to play together nicely and would prefer to standardize on the best option,['python'] +365104,why cannot i update data in an array with foreach loop i am trying to run a clean up job on data in an array specifically converting epoch time to ymmddi tried this function originallyforeach data as row roweventdate dateymd roweventdateecho preprint rdataecho prehowever the foreach loop did not update the data when i output itthe following for loop did workfor i0 icountdata i dataieventdate dateymd dataieventdatewhy did the first loop fail and the second work are not they the same,['php'] +365123,is wcfs datacontractserilaizer thread safe i have been converting a fairly large system from remoting to wcf and everything seems to be running well except we frequently get the following exception systeminvalidoperationexception collection was modified enumeration operation may not execute i have not had any luck tracking it down because it only happens when there are hundreds of calls getting passed through and i can only assume it is because an object is being modified as it is being serialized the classes all use datacontractisreferencetrue there were no similar exceptions when using remoting so i am wondering if anyone has had a similar problem in wcf or can let me know that it probably is the serializer in which case i assume i have to write my own serializers to perform locks where necessary which is a big undertaking i would prefer to avoidthe following is the stack tracewcf error at systemcollectionsgenericlist1enumeratormovenextrare at writearrayoflinetoxmlxmlwriterdelegator object xmlobjectserializerwritecontext collectiondatacontract at systemruntimeserializationcollectiondatacontractwritexmlvaluexmlwriterdelegator xmlwriter object obj xmlobjectserializerwritecontext context at systemruntimeserializationxmlobjectserializerwritecontextinternalserializexmlwriterdelegator xmlwriter object obj boolean isdeclaredtype boolean writexsitype int32 declaredtypeid runtimetypehandle declaredtypehandle at systemruntimeserializationxmlobjectserializerwritecontextinternalserializereferencexmlwriterdelegator xmlwriter object obj boolean isdeclaredtype boolean writexsitype int32 declaredtypeid runtimetypehandle declaredtypehandle at writelinegrouptoxmlxmlwriterdelegator object xmlobjectserializerwritecontext classdatacontract at systemruntimeserializationclassdatacontractwritexmlvaluexmlwriterdelegator xmlwriter object obj xmlobjectserializerwritecontext context at systemruntimeserializationxmlobjectserializerwritecontextserializewithoutxsitypedatacontract datacontract xmlwriterdelegator xmlwriter object obj runtimetypehandle declaredtypehandle at systemruntimeserializationxmlobjectserializerwritecontextinternalserializexmlwriterdelegator xmlwriter object obj boolean isdeclaredtype boolean writexsitype int32 declaredtypeid runtimetypehandle declaredtypehandle at systemruntimeserializationxmlobjectserializerwritecontextinternalserializereferencexmlwriterdelegator xmlwriter object obj boolean isdeclaredtype boolean writexsitype int32 declaredtypeid runtimetypehandle declaredtypehandle at writelinetoxmlxmlwriterdelegator object xmlobjectserializerwritecontext classdatacontract at systemruntimeserializationclassdatacontractwritexmlvaluexmlwriterdelegator xmlwriter object obj xmlobjectserializerwritecontext context at systemruntimeserializationxmlobjectserializerwritecontextserializeandverifytypedatacontract datacontract xmlwriterdelegator xmlwriter object obj boolean verifyknowntype runtimetypehandle declaredtypehandle type declaredtype at systemruntimeserializationxmlobjectserializerwritecontextserializewithxsitypeattopleveldatacontract datacontract xmlwriterdelegator xmlwriter object obj runtimetypehandle originaldeclaredtypehandle type graphtype at systemruntimeserializationdatacontractserializerinternalwriteobjectcontentxmlwriterdelegator writer object graph datacontractresolver datacontractresolver at systemruntimeserializationdatacontractserializerinternalwriteobjectxmlwriterdelegator writer object graph datacontractresolver datacontractresolver at systemruntimeserializationxmlobjectserializerwriteobjecthandleexceptionsxmlwriterdelegator writer object graph datacontractresolver datacontractresolver at systemruntimeserializationxmlobjectserializerwriteobjectxmldictionarywriter writer object graph at systemservicemodelthispatcherdatacontractserializeroperationformatterserializeparameterpartxmldictionarywriter writer partinfo part object graph at systemservicemodelthispatcherdatacontractserializeroperationformatterserializeparameterxmldictionarywriter writer partinfo part object graph at systemservicemodelthispatcherdatacontractserializeroperationformatterserializebodyxmldictionarywriter writer messageversion version string action messagedescription messagedescription object returnvalue object parameters boolean isrequest at systemservicemodelthispatcheroperationformatterserializebodycontentsxmldictionarywriter writer messageversion version object parameters object returnvalue boolean isrequest at systemservicemodelthispatcheroperationformatteroperationformattermessageoperationformatterbodywriteronwritebodycontentsxmldictionarywriter writer at systemservicemodelchannelsbodywriterwritebodycontentsxmldictionarywriter writer at systemservicemodelchannelsbodywritermessageonwritebodycontentsxmldictionarywriter writer at systemservicemodelchannelsmessageonwritemessagexmldictionarywriter writer at systemservicemodelchannelsmessagewritemessagexmldictionarywriter writer at systemservicemodelchannelsbufferedmessagewriterwritemessagemessage message buffermanager buffermanager int32 initialoffset int32 maxsizequota at systemservicemodelchannelsbinarymessageencoderfactorybinarymessageencoderwritemessagemessage message int32 maxmessagesize buffermanager buffermanager int32 messageoffset at systemservicemodelchannelsframingduplexsessionchannelencodemessagemessage message at systemservicemodelchannelsframingduplexsessionchannelonsendmessage message timespan timeout at systemservicemodelchannelsoutputchannelsendmessage message timespan timeout at systemservicemodelthispatcherduplexchannelbinderduplexrequestcontextonreplymessage message timespan timeout at systemservicemodelchannelsrequestcontextbasereplymessage message timespan timeout at systemservicemodelthispatcherimmutablethispatchruntimereplymessagerpc rpc,"['c#', '.net']" +365133,shareactionprovider for api level less than 14 is it possible to use shareactionprovider for apps using api less than 14,['android'] +365146,validation of htmltextbox in mvc4 i use an update action to update based on the input from the htmltextbox using htmlbeginformupdate shopping new userid requestquerystringuserid formmethodpost new id myform htmlvalidationsummary htmlhiddenid requestquerystringuserid as string htmlhiddenproductid itemproductid as string htmltextboxquantity itemquantity htmlvalidationmessagequantity htmlhiddenunitrate itemrate input typesubmit valueupdate and in my model class requirederrormessage quantity is required thisplayname quantity range2 100 errormessage there is not enough inventory for the product to fulfill your order public int quantity get set the problem is i m not getting the validation message when the textbox is emptybut when i use htmltextboxfor htmltextboxformodelitem itemquantity htmlvalidationmessageformodelitem itemquantity i am getting the validation message and my update action is not workinghere i have two options1 how to pass the textbox name qty in htmltextboxfor or2 how to get the validation message in htmltextbox using htmlvalidationmessageany suggestions edit my update actionhttppost public actionresult updatestring id string productid int quantity decimal unitrate if modelstateisvalid int records updatepriceid productid quantity unitrate if records 0 return redirecttoactionindex1 shopping new userid requestquerystringuserid else modelstateaddmodelerrorcan not update return viewindex1,"['c#', 'asp.net']" +365206,how to find the process id of a running java process on windows and how to kill the process alone i want to kill the particular java process in windows like in linux ps aux to get processid and then kill processid to kill the process,['java'] +365271,android alphabetindexer with numbers in android how do you use the alphabetindexer with numbers the code below does not seem to workalphabetindexer alphabetindexer new alphabetindexercursor column index0123456789,['android'] +365287,how to get all cells in a uitableview let us say i have a uitableview which has multiple rows i want to get all the uitableviewcells as an nsarray at a certain point of time i have tried tableview visiblecells but there is a problem with this approach i can not have all those cells which are not currently in the current screen so i turned to another approachnsarray cellsfortableviewuitableview tableview nsinteger sections tableviewnumberofsections nsmutablearray cells nsmutablearray alloc init for int section 0 section sections section nsinteger rows tableview numberofrowsinsectionsection for int row 0 row rows row nsindexpath indexpath nsindexpath indexpathforrowrow insectionsection uitableviewcell cell selftableview cellforrowatindexpathindexpath here for those cells not in current screen cell is nil cells addobjectcell return cellsbut seems that this approach still can not get those cells which are not thisplayed in the screen can anyone help me on this,['ios'] +365289,json schema to javascript typed object is there any library around to generate javascript typed object js functions from a json schema basically the equivalent js version of this thankseditstarting from description an entity typeobject properties geometries type array items ref geometry i would like some code like this to be generated for mefunction entity thisgeometriesobviously the schema could be more complex with refs etc i hope this gives the idea,['javascript'] +365312,jquery equal height responsive div rows i know this question has been asked a million times but i am looking for something more specificas my site is fully responsive i need the divs to be resized based on a per row basis rather than setting all to one heighti am using the following modified code to set the heights of all divs within a containerfneqheights function var el this if ellength 0 eldataeqheights windowbindresizeeqheights function eleqheights eldataeqheights true return eleachfunction var curtop 0 var curhighest 0 thischildreneachfunctionindx var el this elheight elheightautoouterheight var thistop elpositiontop if curtop 0 curtop thistop curhighest 0 if elheight curhighest curhighest elheight curtop thistop heightcurhighest i have var thistop elpositiontop to determine which elements are on the same row but am unsure how i can then set all elements in the same row to the highest valuecurrently heightcurhighest sets all the elements to the same height whether they are on the same row or notthanks for help with this,"['javascript', 'jquery']" +365319,uiactivityitemsource protocole set complex object i am using ios 6 new way to share information uiactivityviewcontroller to select the shared data depending on the media facebook twitter or mail my view controller implement the uiactivityitemsource protocol as follow ibactiononsharebuttonuibutton sender uiactivityviewcontroller activityviewcontroller uiactivityviewcontroller alloc initwithactivityitemsself applicationactivitiesnil activityviewcontrollerexcludedactivitytypes uiactivitytypemessage uiactivitytypeassigntocontact uiactivitytypecopytopasteboard uiactivitytypemessage uiactivitytypeposttoweibo uiactivitytypeprint uiactivitytypesavetocameraroll self presentviewcontrolleractivityviewcontroller animatedyes completionpragma mark uiactivityitemsource protocol idactivityviewcontrolleruiactivityviewcontroller activityviewcontroller itemforactivitytypensstring activitytype if activitytype isequaltostringuiactivitytypeposttofacebook nsarray items message facebook nsurl urlwithstring return items else if activitytype isequaltostringuiactivitytypeposttotwitter nsarray items message twitter nsurl urlwithstring return items else if activitytype isequaltostringuiactivitytypemail nsarray items message mail nsurl urlwithstring return items nsarray items not a proper activity nsurl urlwithstring return items idactivityviewcontrollerplaceholderitemuiactivityviewcontroller activityviewcontroller return placeholderwhen i am returning a simple nsstring for activityviewcontrolleritemforactivitytype the string is well used by my uiactivityviewcontroller but i cannot find a way to use an array according to apple documentation it should be possible this method returns the actual data object to be acted on by an activity object apple documentationdoes anyone ever use this uiactivityitemsource protocol with arrays or is there a use full tutorial to do that note i also got this error on the console it may help launch services registering unknown app identifier comapplemobilemail failedlaunch services unable to find app identifier comapplemobilemail,['objective-c'] +365325,how to make css file more important than another css file i want all the classestags and ids within csscss overwritten over bootstrapmincss without repeating the classestags and ids of bootstrapmincsslink hrefcssbootstrapmincss relstylesheetlink hrefcsscsscss relstylesheet,"['html', 'css']" +365334,use custom fonts in iphone app possible duplicatecan i embed a custom font in an iphone application how can i customize font in my iphone appis it possiblehow can i give this custom font for a label can anyone suggest a good methodiam trying to add myriadprosemiboldotf font in my appand the code is uifont customfont uifont fontwithnamemyriadprosemibold size35 titlelblfont customfont and the plist is,"['iphone', 'ios']" +365384,php function to delete all between certain characters in string i am interested in function delete all betweenchar1 char2 stringthat will search given string for char1 and char2 and if such has been found clear string from substring between these two characters including char1 and char2 itselfexamplestring some valid and scriptsome invalidscript textdelete all beteenscript script stringnow string should contain just some valid and text note two spaces between and textdoes someone have quick solution,['php'] +365415,unity3d for ios and android multiplayer bluetooth connection i am looking for a way to connect two devices using bluetooth in unity ios and android basic for multiplayergaming i foundalljoyn by qualcomm bluetooth works apparently only with rootandroid devices and currently not with ios ios gamekit local multiplayer by prime31 only for iosbonjour plugin by gregzo not bluetooth but a other localmultiplayer solution only for iostnet not bluetooth only for android and ios prohas anyone any other solution especially for android i would be grateful for any help also for other p2punitysolutions,"['android', 'ios']" +365417,ruby gems with gitlab no such file to load rbinotify i am using gitlab and i am trying to follow these instructions to upgrade my gitolite v2 to v3if this issue occurs in 29x you should reinstall gitolite1 backup all repositories just copy homegitrepositories elsewhere2 install new gitolite see 3 copy repositories back4 sudo u gitlab h bundle exec rake gitlabgitoliteupdate keys sudo u gitlab h bundle exec rake gitlabgitoliteupdate reposthat is allthat steps also related to users who wants to update gitolite v2 to v3my gemfile and gemfilelock have rbinotify in them as shown belowgitlabhqbuildgitlabhq grep notify gemfilegem rbinotify require linux onlyrbinotifygitlabhqbuildgitlabhq grep notify gemfilelockrbinotify 088rbinotifyi am trying to update my keys and repos using the following commands but i always get the error no such file to load rbinotifygitlabhqgeminibuildgitlabhq sudo u gitlabhq h bundle exec rake gitlabgitoliteupdate keysrake abortedno such file to load rbinotifysee full trace by running task with tracei have tried to do a bundle install and the list of using does not contain the rbnotify gemi have tried to install the rbinotify gem like sosudo u gitlabhq gem install rbinotifyi have wiped the gemfilelock file and then runsudo u gitlabhq bundle installstill no luckhow can i get gitlab to recognize and use rbinotify thank you,['ruby'] +365427,how to get current php page name possible duplicateget the current script file name i have a file called demophp where i do not have any get variables in the url so if i want to hide a button if am on this page i cannot use something like this if getname value hide else showso i want something likefilename get file nameiffilename file namephp hide else show i do not want to declare unnecessary get variables just for doing this,['php'] +365447,java placeholder on textfield i am trying to create a gui with swing my problem is i have a textfield but i want it to have a placeholder like in html i read here and there that it can be done by overriding the paint of the textfieldsince my code is generated i found out that i need to use the custom creation code to override the code that was generatedhere is what i have put in the custom creation code field new javaxswingjtextfield string test supergettext string hint username public void paintgraphics g if test null testlength 1 gsetcolor colorred gdrawstringhint 0 0 gsetcolorcolorblack superpaintg this generates the following outputjavaxswingjtextfield username new javaxswingjtextfield string test supergettext string hint username public void paintgraphics g if test null testlength 1 gsetcolor colorred gdrawstringhint 0 0 gsetcolorcolorblack superpaintg for now i see the textfield but there is nothing in it maybe i need to add some function onto some event but i am not surei would be grateful if anyone could lend a handedit here is a demo of what i want to do,['java'] +365453,facebook php api login window popup i am using using the most recent version of facebooks php api sdk i am trying to make the login button activate a popup instead of opening the full page i tried using this tutorial the popup worked but when i logged in instead of the popup window closing the website just opened inside the popupdoes anybody know what i need to do to make the popup window close once i have logged inhere is my php code for generating the login urlphp loginurl me on facebookgetloginurlarray thisplay popup next configbaseurl redirect uri configbaseurl scope email,['php'] +365489,interfacing with tuntap for mac osx lion using python i found the following tuntap example program and can not get it to work udpfilestunproxypyi have modified the following linesf osopendevtun0 oso rdwrifs ioctlf tunsetiff structpack16sh totod tunmodeifname ifs16stripx00the first line was modified to reflect the real location of the driver it was originallyf osopendevnettun oso rdwrupon running i get the following error sudo tuntappy s 90 password traceback most recent call last file tuntappy line 65 in module ifs ioctlf tunsetiff structpack16sh totod tunmode ioerror errno 25 inappropriate ioctl for devicei am using the latest tuntap drivers installed from,['python'] +365515,phps array map including keys is there a way of doing something like thistest array arrayfirst key first value second key second valuevar dumparray mapfunctiona b return a loves b array keystest array array valuestest arraybut instead of calling array keys and array values directly passing the test array variablethe desired output isarray2 0 string27 first key loves first value 1 string29 second key loves second value,['php'] +365530,rails invalid datetime on model results in nil i have a model with a datetime attribute i am trying to validate incoming json which would update the model but activerecord seems to be setting the value of the attribute to nil if it is an invalid datetime i cannot respond with the appropriate error because the attribute is allowed to be nil what am i doing wrongcodeclass datetimevalidator activemodeleachvalidator def validate eachrecord attribute value valueto datetime rescue recorderrorsattribute optionsmessage must be a date endendclass foo column my date datetime validates my date allow nil true datetime trueendconsole193p125 001 x foonew foo id nil my date nil193p125 001 xmy date bad value bad value193p125 001 xmy date nil193p125 001 xvalid trueas far as activerecord is concerned setting the datetime attribute to bad value is equivalent to setting it to nil so i cannot validate it since my date is not required this seems like a bug to me what is the best workaroundthanks,['ruby-on-rails'] +365537,how to override variable parameter loaded from another script i have a script that loads the code dynamically it is kind of a search engine when i press a search button the action gets triggered and a new page opens with many parametersi want to override one of the parameters generated with the script in the new url js code is quite big and hard to read but i have found the important part in the firebug dom editorthis is the pattern of the url generated when you perform the searchparametertwotwothisparametersthparameterfourfourwhat i want to edit is thisparameter and change its value this is the part edited in the dom that does what i wantfoobar options var options parameterone123parametertwotwothisparameterabcparameterfourfourand this is the output of thisparameter when you choose copy path in firebugs dom tab options0thisparameteri am wondering it this is possible at all what makes me think that it is is the fact that i can change this parameter in firebug and it works perfectly so if firebug can edit it there should be a way to influence it with another scriptlooking forward to any suggestions thank you in advance,"['javascript', 'jquery']" +365551,python calendar daymonth names in specific locale i am playing with pythons calendar module that is in the standard library basically i need a list of all days of a month like so import calendar calobject calendarmonthcalendar2012 10 print calobject1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 0 0 0 0now what i also need are the names of the month and days in a specific locale i did not find a way to get these from the calobject itself but i was able to get them like so import calendar calobject calendarlocaletextcalendarcalendarmonday de de calobjectformatmonth2012 10 oktober 2012nmo di mi do fr sa son 1 2 3 4 5 6 7n 8 9 10 11 12 13 14n15 16 17 18 19 20 21n22 23 24 25 26 27 28n29 30 31nso oktober is the de de name for october fine the information must be there i am wondering if i can access that month name somehow on a plain calendar object instead of a calendarlocaletextcalendar object the first example with the list is really what i need and i do not like the idea to create two calendar objects to get localized namesanyone got a smart idea,['python'] +365610,why are individual select queries running when an allencompassing select already ran railsactiverecord i have the following code note the includes and the eachsubscribers mailgroupmailgroup membersopted to receive emailincludesroster contact roster infoeach m subscribers emailaddress mroster contactmember email name mroster contactmember name customfields key gender value mroster infogenderpresent mroster infogender x if mroster contactmember emailpresentsubscriberscorrespondingly i see the following in my logs ie select from roster info in select roster info from roster info where roster infoid in 1450 10 1yet immediately after that there are select from roster info for each id already specified in the in list of the previous queryrosterinfo load 848ms select roster info from roster info where roster infoid 1450 limit 1rosterinfo load 592ms select roster info from roster info where roster infoid 10 limit 1rosterinfo load 568ms select roster info from roster info where roster infoid 1 limit 1if select had already been done on roster info on all ids of interest in why is another select being done again for each of the same ids does not activerecord already know all the roster info columns for each idmeanwhile there are no individual queries for roster contact yet if i remove roster contact from the includes method then roster info is not queried again but roster contact isrosterinfo model abridgedclass rosterinfo activerecordbase selfprimary key idendrostercontact model abridgedclass rostercontact activerecordbase selfprimary key id has many mailgroup members foreign key rosterid has many mailgroups through mailgroup members has one roster info foreign key id can use this line belongs to roster info foreign key id or this with no difference def member name i added this method to this roster infomember name question only after having end figured out the problemendrosterweb model abridgedclass rosterweb activerecordbase selfprimary key idendmailgroup model abridgedclass mailgroup activerecordbase selfprimary key id has many mailgroup members foreign key mailcatid has one mailing list foreign key legacy idendmailgroupmember model abridgedclass mailgroupmember activerecordbase selfprimary key id belongs to mailgroup foreign key mailcatid belongs to roster contact foreign key rosterid belongs to roster info foreign key rosterid belongs to roster web foreign key rosterid scope opted to receive email joinsroster webwhereroster webreceiveemail 1end,"['sql', 'ruby-on-rails']" +365623,unable to call firefox from selenium in python on aws machine i am trying to use selenium from python to scrape some dynamics pages with javascript however i cannot call firefox after i followed the instruction of selenium on the pypi page i installed firefox on aws ubuntu 1204 the error message i got isin 1 from selenium import webdriverin 2 br webdriverfirefoxwebdriverexception traceback most recent call lasthomeubuntuipythoninput2d6a5d754ea44 in module 1 br webdriverfirefoxusrlocallibpython27thistpackagesseleniumwebdriverfirefoxwebdriverpyc in init self firefox profile firefox binary timeout 49 remotewebdriver init self 50 command executorextensionconnection127001 selfprofile 51 selfbinary timeout 52 desired capabilitiesdesiredcapabilitiesfirefox 53usrlocallibpython27thistpackagesseleniumwebdriverfirefoxextension connectionpyc in init self host firefox profile firefox binary timeout 45 selfprofileadd extension 46 47 selfbinarylaunch browserselfprofile 48 url httpsdhub host port 49 remoteconnection init usrlocallibpython27thistpackagesseleniumwebdriverfirefoxfirefox binarypyc in launch browserself profile 42 43 self start from profile pathselfprofilepath 44 self wait until connectable 45 46 def killselfusrlocallibpython27thistpackagesseleniumwebdriverfirefoxfirefox binarypyc in wait until connectableself 79 raise webdriverexceptionthe browser appears to have exited 80 before we could connect the output was s 81 self get firefox output 82 if count 30 83 selfkillwebdriverexception message the browser appears to have exited before we could connect the output was error no thisplay specifiedni did search on the web and found that this problem happened with other people topicseleniumusers21sjrojulzy but i do not understand the solution if it is can anyone help me please thanks,['python'] +365664,trying to configure ldap as jndi resource in tomcat i have an ldap server that i am using to authenticate users within a tomcat web application i am using the jndirealm and it is configured within a context file and this works greati will also need to search the ldap for user information i have figured out how to do this with the jndi method and i have it working fine outside of tomcat by creating my own jndi context using a hashtable however instead of configuring the jndi properties in code i would like to create a jndi rsource in my context file right next to the realm configurationi am thinking i would do something like thisresource nameldap authcontainer typecomsunjndildapldapctxfactory javanamingfactoryinitialcomsunjndildapldapctxfactory javanamingproviderurlldaplocalhost389 javanamingsecurityauthenticationsimple javanamingsecurityprincipaluidrjcarrdcexample javanamingsecuritycredentialsabc123but either tomcat tells me the resource cannot be created or when i try to initialize it with something like thiscontext initctx new initialcontextdircontext ctx dircontext initctxlookupjavacompenvldaptomcat tells me the cannot create resource instance i have also added the correct resourceref in my webxml file so i do not think that is the problemsince ldap is being used with the jndi method i am assuming it should be able to be configured as a resource right what am i missing,['java'] +365682,google app engine warmuploading requests and always on my understanding of a warmup request is that it is a request to prime a new frontendbackend instance or do they only apply to frontends in preparation of being used at some point in the near futuremy understanding of a loading request is that it is a request to spinup a new instance because it is needed right now hence it would behoove oneself to try and warm up instances ahead of time to make loading latency that much leso my first question is is my understanding of these request types correct and if not or if i am missing anything noteworthy here then please begin by clarifyingcorrecting menext i am curious how do you get your gae serverside code to handle a warmup or loading request is there a specific interface i need to implement in java ee land you need too implement servicecontextlistener which the webapp container looks for and calls when an app is deployedstarted if so what is the api for doing so otherwise what is the entry point for a gae app basically i am wondering what classmethod should be handling warmuploading requestslast i ask what general activities should be different in the startup process between the handling of warmup requests and loading requests wouldnt they be the same i ask because i am interested in using gaes always on premium feature and not really sure where i should place my startup code for the instances that will always be on,['java'] +365685,teamcity v702 checkout directory file cannot be deleted when applying patch one of developer is applying patch to ci and has broken the ci build the error occurred as below in the build log i have done the below steps and still doesnot work i could not delete the folder 35b0f615bcea75bd manually eventhough i have full write and delete access to the build agent directoriesi have tried to run enforce clean checkout still doesnot workhave rerun the build still doesnot workquestionsis deleting this file manually the best solution to fix the below error if the answer is yes what should i try next to delete this filewhat is the best way to prevent this error to happen again when applying patchbuild log183228checking for changes183515publishing internal artifacts183515clearing temporary directory dteamcitybuildagenttempbuildtmp183515checkout directory dteamcitybuildagentwork35b0f615bcea75bd183515updating sources server side checkout 2m09s183516updating sources will perform clean checkout reason agent does not have any version of the project sources183516updating sources building clean patch for vcs root projectname trunk183724updating sources transferring cached clean patch for vcs root projectname trunk183725updating sources repository sources transferred 2761mb total183725updating sources removing dteamcitybuildagentwork35b0f615bcea75bd183725updating sources error while applying patch failed to delete dteamcitybuildagentwork35b0f615bcea75bdprojectnamebindebug183725publishing internal artifacts183725build failed to start artifacts will not be published for this build183726build finished,['c#'] +365709,run ios 6 device as a ble peripheral as we know ios 6 support running devices iphone 4s and above and new ipad as a ble peripheral there is a demo in wwdc 2012 session 705 called advanced core bluetooth i asked for the source code from apple they sent me a modified version of source code btle transfer draft then irun the app in iphone 5 ios 6 in peripheral mode and start advertisingrun the app in new ipad ios 511 in central modethe problem is that the peripheral is never been thiscovered at all so i use other testing applications including some downloaded from app store all failed to thiscover peripherals i think the problem should be in btle transfer draft because i am not sure whether i am allowed to present the whole source code so i just show the peripheral mode part here voidviewdidload super viewdidload start up the cbperipheralmanager peripheralmanager cbperipheralmanager alloc initwithdelegateself queuenil voidperipheralmanagerdidupdatestatecbperipheralmanager peripheral opt out from any other state if peripheralstate cbperipheralmanagerstatepoweredon return were in cbperipheralmanagerstatepoweredon state nslogselfperipheralmanager powered on so build our service start with the cbmutablecharacteristic selftransfercharacteristic cbmutablecharacteristic alloc initwithtypecbuuid uuidwithstringtransfer characteristic uuid propertiescbcharacteristicpropertynotify valuenil permissionscbattributepermissionsreadable then the service cbmutableservice transferservice cbmutableservice alloc initwithtypecbuuid uuidwithstringtransfer service uuid primaryyes add the characteristic to the service transferservicecharacteristics selftransfercharacteristic and add it to the peripheral manager selfperipheralmanager addservicetransferservice start advertising ibactionswitchchangedidsender if selfadvertisingswitchon all we advertise is our services uuid selfperipheralmanager startadvertising cbadvertisementdataserviceuuidskey cbuuid uuidwithstringtransfer service uuid else selfperipheralmanager stopadvertising the ble is in powered on status and the startadvertising is called but the ble central can never thiscover itpost updatedaccording to mttrbs suggestion i added cbadvertisementdatalocalnamekey when i startadvertising but my service is still cannot be thiscovered by most of the apps including some apps from app store the only one app can thiscover my service is an app from app store called ble scannermy question is does this mean my application is working as a peripheral but why my own code cannot thiscover the service how am i supposed to debug it my code in central mode is like this voidviewdidload super viewdidload start up the cbcentralmanager centralmanager cbcentralmanager alloc initwithdelegateself queuenil voidcentralmanagerdidupdatestatecbcentralmanager central if centralstate cbcentralmanagerstatepoweredon return selfcentralmanager scanforperipheralswithservicesnil optionsnil voidcentralmanagercbcentralmanager central didthiscoverperipheralcbperipheral peripheral advertisementdatansdictionary advertisementdata rssinsnumber rssi voidperipheralcbperipheral peripheral didthiscoverservicesnserror error if error nslogerror thiscovering services error localizeddescription return voidperipheralcbperipheral peripheral didthiscovercharacteristicsforservicecbservice service errornserror error deal with errors if any if error nslogerror thiscovering characteristics error localizeddescription return voidcentralmanagercbcentralmanager central didthisconnectperipheralcbperipheral peripheral errornserror error nslogperipheral thisconnected selfthiscoveredperipheral nilthe didthiscoverperipheral and didthiscoverservices are never called what could be wrong any idea thanks,['ios'] +365717,tag array sorting issue 10252012 still not solved please see belowmy client has a wordpress tag cloud tag array with tags which include character as well as the prefix for some tags ieroseautumnthe abbythe cloudthe elephantobviously all the tags enclosed in the quotations marks are sorted on the top of the list and all the words starting with the prefix are sorted somewhere around the letter t following the logical asc orderit was sprinkled on me that all tags in the wp tag cloud have to be ordered ascending but those which contain the or the characters have to be sorted with all other tags in the chronological order ignoring the and the prefixi looked into the wp core functionfunction wp generate tag cloudbut i have no idea where to start in the raw sql statement i could probably use the trim to filter out the and the characters form the tag cloud array but that is only a thought which i have no idea how to apply,['php'] +365739,in nsdatecomponents how do you know if it is am or pm when i use nsdatecomponents how do i know i am setting a time as am or pm or is it 24hour format heres the codensdate morningend nsdate datensdatecomponents components1 gregorian componentsnsuintegermax fromdatemorningendcomponents1 sethour11components1 setminute59how do i know if i am setting it as 1159 am or 1159 pm,"['iphone', 'objective-c']" +365756,want to upgrade php 53 to 54 i just started working with php so i do not have any idea what is involved with upgrades currently i am working with php 53 and would like to move to 54 how is this done is it just a simple installation of 54 will this break code written in 53,['php'] +365760,what is appconfig in cnet how to use it i have done a project in cnet where my database file is an excel workbook since the location of the connection string is hard coded in my coding there is no problem for installing it in my system but for other systems there isis there a way to prompt the user to set a path once after the setup of the application is completedthe answers i got was use appconfig can anyone tell what is this appconfig and how to use it in my context here,"['c#', '.net']" +365819,migrating data not just schema rails sometimes data migrations are required as time passes code changes and migrations using your domain model are no longer valid and migrations fail what are the best practices for migrating datai tried make an example to clarify the problemconsider this you have a migrationclass changefrompartnerappliedtoappliedat activerecordmigration def up useralleach do user userapplied at userpartner application at usersave end endthis runs perfectly fine of course later you need a schema changeclass addacceptanceconfirmedat activerecordmigration def change add column users acceptance confirmed at datetime endendclass user activerecordbase before save do something with acceptance confirmed atendfor you no problem it runs perfectly but if your coworker pulls both these today not having run the first migration yet he will get this error on running the first migrationrake abortedan error has occurred this and all later migrations canceledundefined method acceptance confirmed at for user0x007f85902346d8that is not being a team player he will be fixing the bug you introduced what should you have done,"['ruby-on-rails', 'ruby']" +365844,parseerror not wellformed invalid token using celementtree i receive xml strings from an external source that can contains unsanitized user contributed contentthe following xml string gave a parseerror in celementtree print reprscommentdx08x08x08x08x08x08 comment import xmletreecelementtree as et etxmlstraceback most recent call last file pyshell4 line 1 in module etxmls file string line 106 in xmlparseerror not wellformed invalid token line 1 column 17is there a way to make celementtree not complain,['python'] +365924,can you insert a line break in text when using d3js i am looking for a way to use a line break within a tooltip text element using d3jstexttest br testthe above and other similar efforts do not seem to workthere is a thread here that seems to answer ittopicd3jsggftf24ltjcbut the solution is not very clear how would html be used in the above situationtexthtmltest testdid not workthanks,['javascript'] +365932,initializing a stdmap when the size is known in advance i would like to initialize a stdmap for now i am using insert but i feel i am wasting some computational time since i already know the size i want to allocate is there a way to allocate a fixed size map and then fill the map,['c++'] +365935,javahow to override this generic method public s extends t lists saveiterables entities if i use following method to overrideoverridepublic listmytype saveiterablemytype structures listmytype result new arraylist return resulti get following errormethod does not override or implement a method from a supertypename clash saveiterablemytype in mytyperepositoryimpl and ssaveiterables in simplejparepository have the same erasure yet neither overrides the other where st are typevariables s extends t declared in method ssaveiterables t extends object declared in class simplejparepositoryhow can i solve this i do not need the method to be generic and in fact it should not be what i mean is thatoverridepublic s extends mytype lists saveiterables structures lists result new arraylist return resultwill not work as the method can create a new object of mytype which is not compatible to list how can i make this workeditfor clarification i am trying to override the different save methods of spring data simplejparepository which is extented by querydsljparepositoryclass defintionspublic class mytyperepositoryimpl extends querydsljparepositorymytype long implements mytyperepositorynorepositorybeanpublic interface mytyperepository extends jparepositorymytype long querydslpredicateexecutormytype and this from spring datapublic class querydsljparepositoryt id extends serializable extends simplejparepositoryt id implements querydslpredicateexecutortedit 2the method calls savemytype entity for each element and that method contains following logicentity has a field which is uniqueget that fields value and check if entity with that value already existsif yes use that entity call to entitymanagermerge does not work returns mytype not sif no create a new one here new object is created does not work with generic typefor 4 i can just set id null and use the passed in object that does not work for 3so i am very puzzled why this method has this signature it makes it unusable for me and i do not get why i would save a subclass of t using ts dao the save methods are the only ones with all others just use t i could just cast to s to make it compile but that seems ugly tooas any other type than t would lead to an exception,['java'] +366014,is there an example project in c that uses opencv and travis ci i am using github as the source control tool and i would like to use the travisci plugin for ci i did not find any project that does that since travisci provides ubuntu 1204 without the opencv libraries i am installing those but then i am having troubles using cmake to compile my code with the installed librariesi would very much like to see an example project and it is travisyml if you know of one preferably with a setup that would work on both the travis ubuntu and windows for dev machines,['c++'] +366016,possible compiler bug in visual c 2012 x86 i am currently experiencing random floating point errors when compiling for x86 targets using vc 11 ctp update 1 see the short example testcpp below and compile usingcl gl o2 ehsc testcpp link machinex86the output should be 10 10 but it produces 10 0 when gl whole program optimization is enabled the problem seems to be that get scaling factor pushes the result on the floating point stack but the calling function is expecting it in the sse register xmm0question am i missing something obvious or is this really a bug the test program of course does not make sense as it is a stripped down test casetestcppinclude iostreamtemplate typename tinline t get scaling factorint units switch units case 0 return 1 case 1 return 10 case 2 return 100 case 3 return 10 case 4 return 10 case 5 return 10 case 6 return 10 case 7 return 10 case 8 return 10 case 9 return 10 default return 1 template int targetunits typename tinline t scalet value int sourceunits return value get scaling factortsourceunits get scaling factorttargetunits declspecnoinlinedouble scaledouble value int units return scale9value unitsint main stdcout 10 scale1e9 1 stdendlupdateissue confirmed by microsoft it even affects straight forward code like thisinclude stdiohdouble testint a switch a case 0 return 10 case 1 return 100 case 2 return 10 case 3 return 10 case 4 return 10 case 5 return 10 case 6 return 10 case 7 return 10 case 8 return 10 case 9 return 10 default return 10 void main int nine 9 double x testnine x test7 int val intx if val 100 printfpass else printffail val is d val,['c++'] +366030,thisabled keyguard lock reenables itself after clicking on a notification in my application i thisable the keyguard lock ieremove lockscreen using the code below and it works fine until i click on any notification in the notification bar if i click on a notification the lock screen is automatically reenabled any help is appreciatedprivate void remove lockscreen final checkboxpreference lock checkboxpreference findpreferenceremove lockscreen keyguardmanager km keyguardmanagergetsystemservicekeyguard service keyguardlock kl kmnewkeyguardlockkeyguard lock if lockischecked prefeditremove lockscreen 1 toastmaketextgetbasecontext lockscreen will not be shown toastlength shortshow klthisablekeyguard else if lockischecked prefeditremove lockscreen 0 toastmaketextgetbasecontext lockscreen will be shown toastlength shortshow klreenablekeyguard androidosprocesskillprocessandroidosprocessmypid,['android'] +366047,highquality opensource texttospeech tts engines written in c i am looking for opensource texttospeech tts engines written in c ideally with highquality voices see quality definition below but also lower quality alternatives are okay as long as the source is freely availabledoes such an open source project existby highquality i mean human sounding nonrobotic and with end results roughly on par with these two english language examples example 1 example 2,['c++'] +366051,what are the differences between didfinishlaunchingwithoption and viewdidload what is the difference between the two methods didfinishlaunchingwithoption and viewdidloadthe former is a method of appdlegatemand the latter is a method of viewcontrollerm but both of them perform the same mission of loading the uis onto the view,['iphone'] +366062,emit mapper vs valueinjecter or automapper performance i have spent some time comparing this three mappers and it is interesting why so big performance diffrenece between emitmapper and any of valueinjecter or automapperlast two comparable by performance from benchmark test in emitmapper solution 10 iterations auto mapper simple 38483 milliseconds emit mapper simple 118 milliseconds handwritten mapper simple 37 milliseconds auto mapper nested 53800 milliseconds emit mapper nested 130 milliseconds handwritten mapper nested 128 milliseconds auto mapper custom 49587 milliseconds emit mapper custom 231 millisecondsalso some benchmarks from valueinjecter runned with added emitmapperfor 10 iterations convention 05016074 automapper 01992945 smart convention 02132185 emit mappereach time new mapper 01168676 emit mapperone mapper 012337there in first emit mapper test it was created each time in second one mapper for all conversions taking this into account have result as valueinjecteralso as automapper slower than in 100 times than emit mapper what is a reason of so huge performance difference as for me object to object mapper cannot took so much time comparing to handwritten mapper as it be a bottleneck of projectif we need to map collection of objects for exampleat this moment i am thinking about using emit mapper but only one reason why i am not ready to decide emit mapper not supported at all by first developers but i am not sure that this is very importantvery low possibility to requirement of some additional functionality,['.net'] +366109,how to print module documentation in python i know this question is very simple i know it must have been asked a lot of times and i did my search on both so and google but i could not find the answer probably due to my lack of ability of putting what i seek into a proper sentencei want to be able to read the docs of what i importfor example if i import x by import x i want to run this command and have its docs printed in python or ipythonwhat is this commandfunctionthank youps i do not mean dir i mean the function that will actually print the docs for me to see and read what functionalities etc this module x has,['python'] +366150,copy bits from ulong to long in c so it appears that the net performance counter type has an annoying problem it exposes long for the counter rawvalue while the actual perf counter value in windows is unsigned and cannot be negative for instance if you have a numberofitems64 counter the api will be perfectly happy to accept a negative value then silently convert it to a very large number in fact for half the value range of the counter the only way to set it there is to find the correct negative value to pass ini assume what is happening here is that they are taking the raw bits from the long and treating it as an unsigned 64bit number the negative values from twos complement are just read as a straight up number for the counterso i am trying to figure out how to coerce c into just dropping the bits from the ulong straight into the long since that is what the api wants but c is being too helpful here you cannot cast or use converttoint64ulong since it throws overflow exceptions because of the value being too large i stumbled upon this way of doing the conversionconverttoint64myulongtostringx 16when it converts from a string in nonbase 10 it assumes the number is in twos complement and does what i need it to but it is not ideal because it needs to allocate an object and parse a string for every conversion and this api is going to be performancecritical is there a better way in c to do this,"['c#', '.net']" +366153,passing in a subclass to a method but having the super class as the parameter sorry about the title i could not come up with a good onei have an abstract class vehicle with 2 implemented subclasses redvehicle and yellowvehicle in another class i have a list of type vehicle containing instances of both subclassesi want to be able to pass into a method a class type and then use that type to decide which set of objects i want to do something to in the listsince class is generic i should parameterise it with something however putting the parameter as the parent class vehicle stops the calling code working since examplemethod is now expecting a type of vehicle not a subclass of redvehicle or yellowvehiclei feel there should be a clean way to do this so what would be the correct way to implement the functionality nb i do not necessarily have to pass in the class type if there are better suggestions i would be happy to try thosecalling codeserviceexamplemethodredvehicleclaserviceexamplemethodyellowvehicleclassfieldsmethodlist of vehiclesvehicle has 2 subclasses redvehicle and yellowvehicleprivate listvehicle vehicleshaving vehicle as the class parameter stops the calling code workingpublic void examplemethodclassvehicle type forvehicle v vehicles ifvgetclassequalstype do something,['java'] +366166,how to implement a put call with json data using ajax and jquery i have looked around and tried many different methods but cannot seem to pass actual data to my controllers functionhere is some code var url timesheettimesheetupdateentry var dataobject newweekentry newentry oldweekentry oldentry alertjsonstringifydataobject ajax url url type put data jsonstringifydataobject datatype json success functionresult alertsuccess newentry and oldentry are both objectsthe alert line outputs this with some properties removed just for brevity newweekentrymondayhours2tuesdayhours2wednesdayhours5thursdayhours5fridayhours4saturdayhours0sundayhours0oldweekentrymondayhours2tuesdayhours2wednesdayhours5thursdayhours5fridayhours2saturdayhours0sundayhours0when i debug my controller action updateentry the two parameters are filled with the timesheetentry class default parameters 0am i passing this in properly,['jquery'] +366167,zf2 how to orwhere i am trying to figure out how to make a mysql select with an or in where clause by default all clauses in where statement are anded and after some hours of try and fail and looking the net cannot make it work in zf1 it would be an orwhere but there is not in zf2this is the code i have inside a abstracttablegatewayresultset thisselectfunction select select use searchstring selectjoinusersblog postsid user usersidarrayname joinblog categoriesblog postsid category blog categoriesid array cat name name cat alias alias cat image icon orderdate desc wheretitle like searchstring or content like searchstring selectwherelikecontentsearchstring selectwhereliketitlesearchstring return resultsetthe lines with the selectwherelike are the ones that are anded and i want them with or what should i change,['php'] +366173,holding a value in unit tests i have a question for you guysi have 2 unit tests which are calling webservices the value that one unittest returns should be used for another unit test methodexample namespace testproject1 public class unittest1 string tid stringempty public void test1 calling webservices and code assertarenotequalhoid hid tid hid public void test2 calling webservices and code string hid tid i need the tid value from the above testcase here assertarenotequalhid hid how can i store a value in one unittest and use that value in another unittest,['c#'] +366180,waitlong timeout in a while loop i have read that youre supposed to put objectwait calls in java in a while loop the reason is that this thread may be woken up and the condition that you were waiting to notify on is still falsespurious wakeupwhat about objectwaitlong timeout here you do not want to loop on the condition since you want it to time out after the specified amount of time but if you do not put it in a loop then how can you ensure that it would not be woken up early,['java'] +366183,set lodash underscore template settings globally using requirejs is there a way to set the templatesettings for lodash when using requirejsright now in my main startup i have requirelodash questionview function questionview var questionview templatesettings interpolate g evaluate g questionview new questionview return questionviewrender but it does not seem to want to set the templatesettings globally because when i use template in a module it wants to use the default templatesettings the problem is that i do not want to change this setting in every module that uses template,['javascript'] +366200,load more content when user scrolls near bottom of page i use this to detect scroll to the bottom of page but how do i detect a thistance from the bottom of the pageifwindowscrolltop windowheight documentheight my ajax herei mean i want the function to execute when he is 100px or 200px from the bottom and not in the very bottom of page how would i change thisalso is it possible to instead catch if the scroll is at the last of a specific element say my big container which shows the loaded contentthanks in advance,['jquery'] +366210,setting a whenever job at different hours every day i am trying to set a whenever job that should be executed 2 times a day exactly at 11am and 11pm is there any way to do it with only one block i mean something like thisevery day at 11am11pm do runner taskend,['ruby'] +366233,using flasksqlalchemy in blueprint models without reference to the app i am trying to create a modular application in flask using blueprintswhen creating models however i am running into the problem of having to reference the app in order to get the dbobject provided by flasksqlalchemy i would like to be able to use some blueprints with more than one app similar to how django apps can be used so this is not a good solutionit is possible to do a switcharoo and have the blueprint create the db instance which the app then imports together with the rest of the blueprint but then any other blueprint wishing to create models need to import from that blueprint instead of the appmy questions are thusis there a way to let blueprints define models without any awareness of the app they are being used in later and have several blueprints come together by this i mean having to import the app modulepackage from your blueprintam i wrong from the outset are blueprints not meant to be independent of the app and be rethistributable a la django appsif not then what pattern should you use to create something like that flask extensions should you simply not do it and maybe centralize all modelsschemas a la ruby on railsedit i have been thinking about this myself now and this might be more related to sqlalchemy than flask because you have to have the declarative base when declaring models and that is got to come from somewhere anywayperhaps the best solution is to have your projects schema defined in one place and spread it around like ruby on rails does declarative sqlalchemy class definitions are really more like schemarb than djangos modelspy i imagine this would also make it easier to use migrations from alembic or sqlalchemymigratei was asked to provide an example so let us do something simple say i have a blueprint describing flatpages simple static content stored in the database it uses a table with just shortname for urls a title and a body this is simple pages init pyfrom flask import blueprint render templatefrom models import pageflat pages blueprintflat pages name template foldertemplatesflat pagesroutepagedef showpage page object pagequeryfilter bynamepagefirst return render templatepageshtmlformatpage pagepage objectthen it would be nice to let this blueprint define its own model this in simple pagemodelspy todo somehow get ahold of a db instance without referencing the app i might get used inclass pagedbmodel name dbcolumndbstring255 primary keytrue title dbcolumndbstring255 content dbcolumndbstring255 def init self name title content selfname name selftitle title selfcontent contentthis question is related toflasksqlalchemy importcontext issuewhats your folder layout for a flask app divided in modulesand various others but all replies seem to rely on import the apps db instance or doing the reverse the large app how to wiki page also uses the import your app in your blueprint pattern since the official documentation shows how to create routes views templates and assets in a blueprint without caring about what app it is in i have assumed that blueprints should in general be reusable across apps however this modularity does not seem that useful without also having independent modelssince blueprints can be hooked into an app more than once it might simply be the wrong approach to have models in blueprints,['python'] +366238,tcp and pf ring i was taking a look at using pf ring for sending and receiving in my applicationif i plan to use pf ring for maintaining a tcp connection it looks like i will need to manually forge the ip and tcp messages myself as pfring send sends raw packets does this mean i will have to manually reimplement tcp on top of pf ringi understand there is a clear advantage for receiving using pf ring has anyone tried sending data with pf ring is there a clear advantage over normal send callsnote i am not using dna direct nic access i am just using the kernel partial bypass with nic aware drivers,"['c++', 'c']" +366245,html5 css3 circle with partial border is it possible to create a circle using only html5 css3 which has a border that only goes part way around the circle if not what techniques can i use to accomplish this effect i would prefer to use pure dom elements but if i have to i can draw on canvas or spin up an svg,['css'] +366278,impossible nullreferenceexception i am investigating an exception that a colleague just got while running an application through visual studio 2010systemnullreferenceexception was unhandled by user code messageobject reference not set to an instance of an object sourcemscorlib stacktrace at systemcollectionsgenericgenericequalitycomparer1equalst x t y at systemcollectionsconcurrentconcurrentdictionary2trygetvaluetkey key tvalue value at xrepositorybase2getfromcachetidentity id using net reflector i have looked at the code for genericequalitycomparertequalst x t y and i cannot see any possible cause for a nullreferenceexceptiongenericequalitycomparertequalst x t y from mscorlib 4030319269public override bool equalst x t y if x null return y null xequalsy if y null return false return truethe type of t tkey and tidentity are all the same type in this stack tracethe type is a custom type called identity that implements iequatableidentity it is immutable and cannot be constructed with null values for the fields that it uses in its implementation of equalsidentity other it also overrides equalsobject obj like thispublic override bool equalsobject obj if objectthis obj return true return equalsobj as identitypublic bool equalsidentity other if objectthis objectother return true if objectother null return false if fieldaequalsotherfielda return false return fieldbequalsotherfieldbi have a fairly exhaustive set of unit tests around the equals implementations so it will happily accept a value of null for otherobj and return false as expectedthe type does not either override the operators nor operatorseven so i would expect to see my class on top of the stack trace if the exception was being thrown from the implementation of equalsidentity other in my identity class but it says the nullreferenceexception is coming from mscorlibi am running on net framework version 4030319269i do not have a memory dump and i have not seen this before and have not reproduced it since still i am obliged to investigate and to be absolutely certain that it is not being caused by our code and that it would not happen in productionso the real question is what caused this exceptionbug in mscorlib seems highly unlikelytransient memory corruption on the machine possible hard to back up with evidenceother updates in response to jordao is it possible to call the method with an object that is not an identitythe concurrentdictionarytkey tvalue is typed such that tkey identity and nothing subclasses identity so i cannot see how it could be possibleis it possible to call the method with nullunit tests cover the scenario of calling all of the equals implementations with nullwhat version of the code is the stack trace from maybe some older version susceptible to the exceptioni am analyzing the same code that generated the exception i have checked that the version of the net framework running on my colleagues computer is also 4030319269any multithreaded scenario could cause the exception these are usually hard to reproduce but might be worth investigatingyes the code is multithreaded and intended to be so that is why i am using a concurrentdictionary followup related to response from jalal aldeen saad i would have thought that a race condition where some other thread sets x to null could only be the cause if the parameter x was passed by reference using the ref keyword i set out to validate that theory with the following codemanualresetevent testfornull new manualreseteventfalsemanualresetevent settonull new manualreseteventfalsetestmethodpublic void test var x new object var y new object var t taskfactorystartnew return equalsx y testfornullwaitone wait until x has been tested for null value x null settonullset signal that x has now been set to null var result tresult assertisfalseresultpublic bool equalstt x t y if x null testfornullset signal that we have determined that x was not null settonullwaitone wait for original x value to be set to null would fail here if setting the outer scope x to null affected the value of x in this scope return y null xequalsy if y null return false return trueand the test completes without errorsi can force that behavior if i change the signature to pass x and y by reference that is public bool equalstref t x ref t y then the test fails with anullreferenceexception but this does not match the method signature ofgenericequalitycomparerequalst x t y,['c#'] +366390,mysql default datetime through phpmyadmin in an existing database i have age column int now i need to set it as dob datetimei try doing so through phpmyadmin giving current timestamp as default value as defined by answer with 138 upvotes however phpmyadmin is complaining 1067 invalid default value for dob as in attached screenshotcan someone please suggest why i am getting that error and how to fix that,['mysql'] +366402,change form size at runtime c how can i change window form size at runtimei saw examples but every require formsize property this property can be set like here but i have created my application form in visual tool and form is created like thisstatic void main applicationrunnew formi do not know how to set that size property now and then change it by formheight and formwidth methods,['c#'] +366415,why nsarray does not have a firstobject method but it does have a lastobject anybody know why,"['objective-c', 'ios']" +366419,how to get current time from internet in android i am making an app in which i want to get the current time from interneti know how to get the time from the device and even after searching a loti did not get any clue about how to get it from internetthis is the code i am using for getting the time from the devicepublic static long timechecker long millis systemcurrenttimemillis return millis please help methanks a lot in advance,['android'] +366422,malloc vs custom allocator malloc has a lot of overhead why i have an image compression application that now has two different versions of memory allocation systems in the original one malloc is used everywhere and in the second one i implemented a simple poolallocator that just allocates chunk of memory and returns parts of that memory to myalloc calls weve been noticing a huge memory overhead when malloc is used at the height of its memory usage the malloc code requires about 170 megabytes of memory for a 1920x1080x16bpp image while the pool allocator allocates just 48 megabytes of which 47 are used by the program in terms of memory allocation patterns the program allocates a lot of 8bytemost 32bytemany and 1080byteblockssome with the test image apart from these there are no dynamic memory allocations in the codethe os of the testing system is windows 7 64 bithow did we test memory usage with the custom allocator we could see how much memory is used because all malloc calls are defered to the allocator with malloc in debug mode we just stepped through the code and watched the memory usage in the task manager in release mode we did the same but less fine grained because the compiler optimizes a lot of stuff away so we could not step through the code piece by piece the memory difference between release and debug was about 20mb which i would attribute to optimization and lack of debug information in release modecould malloc alone be the cause of such a huge overhead if so what exactly causes this overhead inside malloc,['c'] +366436,multiple transitions for twitter bootstrap transition i am wanting to animate two properties in bootstrap v210the opacity and the margini have triedtransitionopacity 05s margin 025s no outputtransitionopacity 05s margin 025s invalid css outputtransitionopacity 05s transitionmargin 025s margin overrides opacitynote that i am using lessphp so solutions that use the javascript regex will not worki know i could copy the mixin and modify it to accept two parameters as well but that just seems hacky surely there is a better way,['css'] +366438,mvc4 bundling cache headers i want to change the cache headers sent from a bundle request currently it is varying by useragent but i do not want it to is there a way to change the headers sent by a bundle requestafter a quick look in the systemweboptimization assembly i can see the headers get set in bundlesetheaders which is a private static function so i do not think its possible although i would love to be proven wrong,"['c#', 'asp.net']" +366475,xstream serialize null values suppose i have class studentstring nameint agestring teacherthen public class app1 public static void mainstring args student st new student stsetnametoto xstream xs new xstream xsaliasstudentstudentclass systemoutprintlnxstoxmlst gives me student nametotoname age0agestudentis there a way for dealing null values i mean student nametotoname age0age teacherteacherstudentit is possible if i do stsetteacherbut not if teacher is nulli tried with a custom converter but it seems the null values are not sent to the converter,['java'] +366537,what is the meaning of java is portable i am new in java i am confused about java portabilityif java language is portable why enum is unknown in j2mei am a c programmer in c it is not important which platform or library is used c language does not change in all platformsmy purpose is developing a java library that just uses primitive types like int string or array something like a library for genetic algorithms i want to use this library in mobile and desktop applications but it seems that enum or some other keywords do not exist in all platformsi think i misunderstood the meaning of java portabilitywhat is the meaning of java is portable,['java'] +366545,parallelise python loop with numpy arrays and sharedmemory i am aware of several questions and answers on this topic but have not found a satisfactory answer to this particular problemwhat is the easiest way to do a simple sharedmemory parallelisation of a python loop where numpy arrays are manipulated through numpyscipy functionsi am not looking for the most efficient way i just wanted something simple to implement that does not require a significant rewrite when the loop is not run in parallel just like openmp implements in lower level languages the best answer i have seen in this regard is this one but this is a rather clunky way that requires one to express the loop into a function that takes a single argument several lines of sharedarray converting crud seems to require that the parallel function is called from main and it does not seem to work well from the interactive prompt where i spend a lot of my timewith all of pythons simplicity is this really the best way to parellelise a loop really this is something trivial to parallelise in openmp fashioni have painstakingly read through the opaque documentation of the multiprocessing module only to find out that it is so general that it seems suited to everything but a simple loop parallelisation i am not interested in setting up managers proxies pipes etc i just have a simple loop fully parallel that does not have any communication between tasks using mpi to parallelise such a simple situation seems like overkill not to mention it would be memoryinefficient in this casei have not had time to learn about the multitude of different sharedmemory parallel packages for python but was wondering if someone has more experience in this and can show me a simpler way please do not suggest serial optimisation techniques such as cython i already use it or using parallel numpyscipy functions such as blas my case is more general and more parallel,['python'] +366587,is the html is view source different from the html in inspect element i am using firefox alongside firebug developer toolsis the html shown in view source ctrl u different from the html i see when inspecting elements using firebugwhat are the differences between the two,['html'] +366588,combining multiple suppresswarnings annotations eclipse indigo so the issue is being able to combine multple warning suppressions so that each item does not need it is own suppresswarnings annotationso for examplepublic class example public example go go new go unused liststring list liststring gogetlist unchecked getterssettersother methodsnow instead of having two suppresswarnings i want to have one at the class level for those two warnings so like thissuppresswarnings unused unchecked public class example public example go go new go unused suppressed liststring list liststring gogetlist unchecked suppressed getterssettersother methodsbut that is not a valid syntax is there a way to do this,['java'] +366593,lightweight restful java framework i have been looking into restful web services in java and most of the approaches i have found look to be rather bloated these include approaches from netbeans spring 3 and ejb using singletonsi may be wrong so please feel free to correct me but these all feel like very complicated solutions to a relatively simple problemcan anyone suggest a very simple and lightweight approach to doing restful webservices in javai am not convinced mvc is necessary on the back end for these instead i am looking at doing clean vertical slicesi will not need persistence unless it can be wired to mongodb so i do not need any orm mapping,['java'] +366608,leftpositioning a bootstrap popover i have a popover that appears to the left of a label labelhoverfunction thispopover offset 10 placement left popovershowthe popover is currently blocking a radio button and i want to move it left say 10px i cannot seem to figure out how to do this offset seems to do nothing at all if i add 10 or 10 it does not make a difference here is the html for one such label label formaincontent wizard1 rbleader idmaincontent wizard1 lblleader classradio dataoriginaltitlevisionary giving level datacontentdiamond fullpage ad 2 dinner ticketsvisionary 250span classradio namerbleaderinput idmaincontent wizard1 rbleader typeradio namectl00maincontentwizard1givinglevel valuerbleader onclickwizardstep1 click spanlabel i can try to set the popover position by overriding the class in css with something likepopover left 380px importantbut this is far from ideal as it appears in different spots using different browsers there must be a way of adding a small right margin yesthanks,['css'] +366620,how to check if two types are same at compiletimebonus points if it works with boost strong typedef i was wondering if it is possible to check if 2 types are same at compile timewhat i came up with isidk if it works because it feels hackish and idk standard that good so idk what to look for when testinginclude booststrong typedefhppboost strong typedefdouble cmboost strong typedefdouble inchtemplatetypename t typename ustatic constexpr void help templatetypename t typename uclass aresametype public constexpr operator bool return helptu helput usage int main static assertaresametypedoublefloat false oh noes1 static assertaresametypedoubledouble true oh noes2 static assertaresametypeintdouble false oh noes3 static assertaresametypedoubledouble false oh noes4 static assertaresametypeconst doubledouble false oh noes5 static assertaresametypeinchcm true oh expected firesso 1 is there a better way to it2 is this address of a function hack guaranteed to work by standardi would bet not,['c++'] +366654,mpmovieplayercontroller simulator crash my mpmovieplayercontroller crashes when i try and play any videothis happens only on the simulator works fine on a deviceerror is as follows20121025 164624033 thefasterchef852914303 mpavcontroller autoplay thisabling autoplay for pause20121025 164624035 thefasterchef852914303 mpavcontroller autoplay thisabling autoplay20121025 164624172 thefasterchef852914303 mpavcontroller autoplay skipping autoplay thisabled for current item 1 on player 020121025 164624190 thefasterchef852914303 mpavcontroller autoplay enabling autoplay20121025 164624227 thefasterchef852914303 mpavcontroller autoplay likely to keep up or full buffer 020121025 164624227 thefasterchef852914303 mpavcontroller autoplay skipping autoplay not enough buffered to keep up20121025 164624232 thefasterchef852914303 mpavcontroller autoplay enabling autoplay20121025 164624238 thefasterchef852914303 mpcloudassetdownloadcontroller prioritization requested for media item id 0my code is the bog standard method for calling mpmovieplayercontrollerin h fileproperty retain mpmovieplayercontroller videoplayerin m filensbundle appbundle nsbundle mainbundlensstring contenturlstring appbundle pathforresourcevideoidentifier oftypemp4nsstring contenturlstring appbundle pathforresourcetest oftypemp4nsurl contenturl nsurl fileurlwithpathcontenturlstringselfvideoplayer mpmovieplayercontroller alloc initwithcontenturlcontenturlselfvideoplayer preparetoplayselfvideoplayerview setframe selfviewboundsselfview addsubviewselfvideoplayerviewselfvideoplayer preparetoplayselfvideoplayer playi have tried this snippet of code in a different view controller with the same error resulti have tried this snippet code in a new project and it works finewhat else could be causing this errorthe answer here did not solve it for me,['ios'] +366675,is it possible to graceful degrade an android application i am wondering if it is possible to use graceful degradation approach in an android application ie use some functions of say api 15 but if it is not supported use api 10 insteadspecifically i have swiping tabs in android 4 vs missing support of this feature in android 2x and thus using normal tabs in mind but the question is rather generali would like to use an advanced functionality on devices that support it but when it is not supported i would like to use an alternative i do not seem to be able to use android 4 libraries in an android 2 project while an android 4 project will not understandably be launchable on an android 2 deviceany solution or at least and for this moment any solution for swiping tabs on android 2,['android'] +366680,how to break from mainouter loop in a doublenested loop if i have loop in a loop and once if statement is satisfied i want to break main loop how am i supposed to do that this is my code forint d 0 d amountofneighbors d forint c 0 c myarraysize c ifgraphisedgelistofneighborsgetd c ifkeyfromvaluecequalsgoalword once this is true i want to break main loop systemoutprintlnwe got to goal it is keyfromvaluec break this breaks second loop not main one,['java'] +366700,very basic actionbarsherlock tabs with fragments fragmenttransaction is null in the ontabselected method i am implementing some code from an example and trying to convert it to work with actionbarsherlockhere is tabactivityjavapackage compnetimport comactionbarsherlockappactionbarimport comactionbarsherlockappactionbartabimport comactionbarsherlockappsherlockactivityimport androidcontentcontextimport androidosbundleimport androidsupportv4appfragmentimport androidsupportv4appfragmenttransactionimport androidutillogimport androidwidgettoastpublic class tabactivity extends sherlockactivity private static string tag tabactivity public static context appcontext called when the activity is first created override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayouttab activity actionbar gets initiated actionbar actionbar getsupportactionbar tell the actionbar we want to use tabs actionbarsetnavigationmodeactionbarnavigation mode tabs initiating both tabs and set text to it actionbartab playertab actionbarnewtabsettextfragment a actionbartab stationstab actionbarnewtabsettextfragment b create the two fragments we want to use for thisplay content fragment playerfragment new afragment fragment stationsfragment new bfragment set the tab listener now we can listen for clicks playertabsettablistenernew mytabslistenerplayerfragment stationstabsettablistenernew mytabslistenerstationsfragment add the two tabs to the actionbar actionbaraddtabplayertab actionbaraddtabstationstab class mytabslistener implements actionbartablistener public fragment fragment public mytabslistenerfragment fragment thisfragment fragment override public void ontabselectedtab tab fragmenttransaction ft todo autogenerated method stub if fragment null logvtag fragment is null if ft null logvtag fragment transaction is null ftreplaceridfragment container fragment override public void ontabunselectedtab tab fragmenttransaction ft todo autogenerated method stub override public void ontabreselectedtab tab fragmenttransaction ft todo autogenerated method stub toastmaketexttabactivityappcontext reselected toastlength longshow here is afragmentjavapackage compnetimport comactionbarsherlockappsherlockfragmentimport androidosbundleimport androidviewlayoutinflaterimport androidviewviewimport androidviewviewgrouppublic class afragment extends sherlockfragment override public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate inflate the layout for this fragment return inflaterinflaterlayoutafragment container false here is bfragmentjavapackage compnetimport comactionbarsherlockappsherlockfragmentimport androidosbundleimport androidviewlayoutinflaterimport androidviewviewimport androidviewviewgrouppublic class bfragment extends sherlockfragment override public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate inflate the layout for this fragment return inflaterinflaterlayoutbfragment container false here is tab activityxmllinearlayout androidlayout gravitycenter androidlayout heightfill parent androidlayout widthfill parent androidorientationvertical xmlnsandroidlinearlayout androidididfragment container androidlayout heightmatch parent androidlayout widthmatch parent linearlayoutlinearlayouthere is afragmentxmlxml version10 encodingutf8linearlayout xmlnsandroid androidlayout widthmatch parent androidlayout heightmatch parent androidorientationvertical textview xmlnsandroid androidididtext androidlayout widthmatch parent androidlayout heightmatch parent androidgravitycenter verticalcenter horizontal androidtextappearanceandroidattrtextappearancemedium androidtextstringhello worldlinearlayouthere is bfragmentxmlxml version10 encodingutf8linearlayout xmlnsandroid androidlayout widthmatch parent androidlayout heightmatch parent androidorientationvertical textview xmlnsandroid androidididtext androidlayout widthmatch parent androidlayout heightmatch parent androidgravitycenter verticalcenter horizontal androidtextappearanceandroidattrtextappearancemedium androidtextstringtab navigation contentlinearlayoutwhen the activity loads it triggers the ontabselected method i put a couple if statements checking objects for null which write to the log and it shows that the fragmenttransaction object is null anyone see where i am going wrong thanks,['android'] +366703,good php framework for strong security i am trying to choose a framework that provides really good security of web applications protects against as much of owasp top10 as possible such assql injectionxss csrfauthenticationauthorizationetcthe thing is i have tried researching really heavilycakephp zend yii code igniter kohana and some have basic authentication maybe a little authorization but nothing for any application that needs solid codesecurityis most of the vulnerability types above currently secured by only writing custom code in these frameworks this is kinda my first experience with using frameworks everything up til this point has been custom php web apps my whole thought for phpframeworks was it was going to be easy to protect against these vulnerabilities given it is not natively why use one or is there a framework out there i am not looking at which is better than those listed above for strong web app security thanks,['php'] +366759,add css rule via jquery for future created elements i have a somewhat unusual issue i have done something like this many timesselectorcsscolor00fmy problem is that i create a div idselector and i call the command above and it works finenow on another event later i remove that element from the dom and add it again at a later time with the same id this element now does not have color00fis there a way that i can add a rule in css such that it will affect items that are created in the future with that same idclass i like jquery but anything with plain javascript would be fine as wellit has to be dynamic and i do not know the classes to put in a css file also i plan on changing a single attribute a few different times through the course of the application for example setting the color to black to blue to red and back to blacki went with the answer from lucassp and this is what i ended up withfunction toggleiconelem classname ifelemattrsrcimgcheckbox checkedgif elemattrsrc imgcheckbox uncheckedgif classnamehidethis was the old line that i removed html headappendstyleclassname thisplaynone style else elemattrsrc imgcheckbox checkedgif classnameshowthis was the old line that i removed html headappendstyleclassname thisplayblock style i also want to say that nelson is probably the most correct though it would require more work to go into application code that always works fine and that is not effort i want to spend at the momentif i had to rewrite this or write something similar in the future i would look into detach,"['javascript', 'jquery', 'css']" +366777,php get actual maximum upload size when usingini getupload max filesizeit actually gives you the string specified in the phpini fileit is not good to use this value as a reference for the maximum upload size becauseit is possible to use socalled shorthandbytes like 1m and so on which needs alot of additional parsingwhen upload max filesize is for example 025m it actually is zero making the parsing of the value much harder once againalso if the value contains any spaces like it is interpreted as zero by php while it shows the value without spaces when using ini getso is there any way to get the value actually being used by php besides the one reported by ini get or what is the best way to determinate it,['php'] +366792,update table with random record in update statment in sql server i have two tables table 1 has about 80 rows and table 2 has about 10 million i would like to update all the rows in table 2 with a random row from table 1 i do not want the same row for all the rows is it possible to update table 2 and have it randomly select a value for each row it is updatingthis is what i have tried but it puts the same value in each rowupdate member info testset hostessid select top 1 hostessid from hostess test order by newidedited,['sql'] +366829,notification autocancel does not call deleteintent i am implementing gcm in my app and keeping a hash of notifications to keep track of what is in the notification shade i have to change intents based on if the user is in or out of appi set the deleteintent pendingintent for all my notifications all this does is remove the notification from my local hash so it would not be updated anymore the intent is fired fine if i clear all or swipe to delete a notification however i also set my notifications to auto cancel clicking on a notification does not trigger the deleteintent for my notificationmy question is is there any way to be notified when my notifications are autocancelled,['android'] +366868,how can i find the header files of the c programming language in linux when i write c programs in linux and then compile them using gcc i am always curious about where those header files are for example where stdioh is more generally where is stdboolhwhat i want to know is not only where it is but also how to get those places for example using shell command or using the c programming language,['c'] +366872,first ever bundle install stack level too deep i have created a brand new rails project using the commandrails new qbc databasemysql it creates all the files perfectly fine butat the bundle install it errors out bundle installfetching gem metadata from fetching gem metadata from unfortunately a fatal error has occurred please see the bundlertroubleshooting documentation at thanksusrbinbundle23 stack level too deep systemstackerrorgistgithubcom3956513i have searched and searched for the solution to this issue but i cannot seem tofind anyone else who has experienced it i am developing on cygwin and iwouldnt be surprised if that has something to do with iti tried creating a gemfile with just the source and one gem in it in an emptydirectory and bundle install still gives the same error i have followed all ofthe troubleshooting steps reinstalled cygwin and all packages everything whatkeeps catching my eye is the fetching gem metadata twiceis it possible thatbundler is caught in some kind of loop,['ruby-on-rails'] +366898,what causes androids contentresolverquery to return null under what conditions does contentresolverquery return null instead of a cursor object i have gotten empty cursors before but just realized that the method can also return null i have not been able to trace the circumstances that this happens in though,['android'] +366968,how can i print a float with thousands separators how can i format a decimal number so that 3275712133 will thisplay as 3275712133,['python'] +366969,menu like skout and sliding from one view to another by touch in android i want to implement a sliding menu like fb or g app and i have found some sample code from fb menu demo and these are good to begin with but i need something extra from them like here it works only on the click of the menu button but i want to move it by gestures as well i want to have the behavior that there is a center view and on moving that center towards the right one view will appear and on moving that towards left the menu will appear say there are three views abc and when i swipe c towards left then a appear and when i swipe c towards right then b appear c is in the middle of a and b 1middle view moves towards right move towards right 2move the middle view towards left side move towards leftnow my question is what are the best practices to develop the views like that i have heard from someone that i should use fragments and view pager as well so how can i develop this is there any sample implementation done by anyone any help and suggestions are appreciated for reference see this app which uses this type of sliding bw views skout app,['android'] +366980,layouttransition animate view next to an expanding view i have recreated my problem to a very simple representation i have 3 textviews 2 of them are in a seperate linearlayout the third is on the same level as the linearlayouti am toggling the visibility of test1 and test2 and i would like to see them fade away which works furthermore i want test3 to slide into his new place taking place of test1 and test2 i cannot make this happen test3 just snaps to it is new pointhow can i achive thismy codexml version10 encodingutf8linearlayout xmlnsandroid androidididparent androidlayout widthmatch parent androidlayout heightwrap content androidanimatelayoutchangestrue androidorientationvertical button androidididbutton androidlayout widthwrap content androidlayout heightwrap content androidtextclick linearlayout androidanimatelayoutchangestrue androidididchild1 androidlayout widthmatch parent androidlayout heightwrap content androidorientationvertical textview androidididtest1 androidlayout widthmatch parent androidvisibilitygone androidlayout heightwrap content androidtexttest1 textview androidididtest2 androidlayout widthmatch parent androidvisibilitygone androidlayout heightwrap content androidtexttest2 linearlayout textview androidididtest3 androidlayout widthmatch parent androidlayout heightwrap content androidtexttest3 linearlayoutand in my activitypublic class layoutanimations extends activity private boolean toggle true called when the activity is first created override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutlayout animations button button button findviewbyidridbutton buttonsetonclicklistenernew onclicklistener override public void onclickview v if toggle findviewbyidridtest1setvisibilityviewvisible findviewbyidridtest2setvisibilityviewvisible else findviewbyidridtest1setvisibilityviewgone findviewbyidridtest2setvisibilityviewgone toggle toggle edit i actually have another textview next to test1 and test2 which should be visible at all times so i cannot just hide the linearlayout itself,['android'] +367055,in mvvm is every viewmodel coupled to just one model in an mvvm implementation is every viewmodel coupled to just one modeli am trying to implement the mvvm pattern in a project but i found that sometimes a view may need information from multiple models for example for a userprofileview its userprofileviewmodel may need information from useraccountmodel userprofilesettingsmodel userpostsdatamodel etchowever in most articles i read about mvvm the viewmodel only consists on one model via dependency injection so the constructor takes in only one modelhow would the viewmodel work when it has to get information from multiple models or would such a situation ever occur in mvvmps i am not using the prism or unity framework i am trying to implement similar patterns into a project that i am working on which does not use prism or unity that is why i need to understand exactly how some of these things work,['c#'] +367068,feature detection for ability to drop file over html file input can we detect whether a browser supports dropping a file over an input typefile for example this is possible in chrome but not in ie8modernizrdraganddrop is a possibility but is it the right choice i am not adding any custom dragdrop event handlersupdateto verify joes answer heres a jquery example that should stop the file drop verified in chrome and firefoxyourfileinputondrop function return false if joes explanation was right file will not be dropped,"['javascript', 'html']" +367080,understanding the output of xxprintcompilation i am running some micro benchmarks on java list iteration code i have used xxprintcompilation and verbosegc flags to ensure that nothing is happening in the background when the timing is being run however i see something in the output which i cannot understandheres the code i am running the benchmark onimport javautilarraylistimport javautillistpublic class performantiteration private static int thesum 0 public static void mainstring args systemoutprintlnstarting microbenchmark on iterating over collections with a call to size in each iteration listinteger nums new arraylistinteger forint i0 i50 i numsaddi systemoutprintlnwarming up warmup make sure all jit comliling is done before the actual benchmarking starts forint i0 i10 i iteratewithconstantsizenums iteratewithdynamicsizenums actual systemoutprintlnstarting the actual test long constantsizebenchmark iteratewithconstantsizenums long dynamicsizebenchmark iteratewithdynamicsizenums systemoutprintlntest completed printing results systemoutprintlnconstantsizebenchmark constantsizebenchmark systemoutprintlndynamicsizebenchmark dynamicsizebenchmark systemoutprintlndynamicsizebenchmarkconstantsizebenchmark doubledynamicsizebenchmarkdoubleconstantsizebenchmark private static long iteratewithdynamicsizelistinteger nums int sum0 long start systemnanotime forint i0 inumssize i appear to do something useful sum numsgeti long end systemnanotime setsumsum return endstart private static long iteratewithconstantsizelistinteger nums int count numssize int sum0 long start systemnanotime forint i0 icount i appear to do something useful sum numsgeti long end systemnanotime setsumsum return endstart invocations to this method simply exist to fool the vm into thinking that we are doing something useful in the loop private static void setsumint sum thesum sum heres the output 152 1 javalangstringcharat 33 bytes 160 2 javalangstringindexof 151 bytes 165 3starting microbenchmark on iterating over collections with a call to size in each iteration javalangstringhashcode 60 bytes 171 4 sunniocsutf 8encoderencodearrayloop 490 bytes 183 5 javalangstringlastindexof 156 bytes 197 6 javaiounixfilesystemnormalize 75 bytes 200 7 javalangobjectinit 1 bytes 205 8 javalangnumberinit 5 bytes 206 9 javalangintegerinit 10 bytes 211 10 javautilarraylistadd 29 bytes 211 11 javautilarraylistensurecapacity 58 bytes 217 12 javalangintegervalueof 35 bytes 221 1 performanceapiperformantiterationmain 21 173 byteswarming up 252 13 javautilarraylistget 11 bytes 252 14 javautilarraylistrangecheck 22 bytes 253 15 javautilarraylistelementdata 7 bytes 260 2 performanceapiperformantiterationiteratewithconstantsize 19 59 bytes 268 3 performanceapiperformantiterationiteratewithdynamicsize 12 57 bytes 272 16 performanceapiperformantiterationiteratewithconstantsize 59 bytes 278 17 performanceapiperformantiterationiteratewithdynamicsize 57 bytesstarting the actual testtest completed printing resultsconstantsizebenchmark 301688dynamicsizebenchmark 782602dynamicsizebenchmarkconstantsizebenchmark 25940773249184588i do not understand these four lines from the output260 2 performanceapiperformantiterationiteratewithconstantsize 19 59 bytes268 3 performanceapiperformantiterationiteratewithdynamicsize 12 57 bytes272 16 performanceapiperformantiterationiteratewithconstantsize 59 bytes278 17 performanceapiperformantiterationiteratewithdynamicsize 57 byteswhy are both these methods being compiled twice how do i read this output what do the various numbers mean,['java'] +367085,actionbar up navigation with fragments i have a tabbed actionbarviewpager layout with three tabs say a b and c in tab c tabfragmenti am adding another fragment say fragment d with dfragment f new dfragment ftaddandroidridcontent f ftremovecfragmentthis ftaddtobackstacknull ftcommiti modify actionbar in dfragments onresume to add up buttonactionbar ab getactivitygetactionbarabsetnavigationmodeactionbarnavigation mode standardabsetthisplayhomeasupenabledtrueabsetthisplayshowhomeenabledtruenow in dfragment when i press hardwarephone back button i return to the original tabbedabc layout with cfragment selected how can i achieve this functionality with actionbar up button,['android'] +367119,java how to parse a date strictly simpledateformat is a very kind parser that rolls the resulting date instead of throwing an error how can i parse a date strictly without regexps etcfmt new simpledateformatddmmyfmtparse10112012 it worksfmtparse1011502012 it works but it is unwanted,['java'] +367126,custom android download service providing progress notification row per file i would like to be able to show multiple downloads of files in the notification bar which can also be cancelledi have implemented a custom service the performs multiple downloads in parallel using asynctasks onpublishprogress i am trying to update the individual rows in the notification bar to show the download progress for each file for two solid days i have been trying to fix issues with the rows flickering swapping order and sometimes just being blank or only updating one row also tapping the row to cancel routine does not always workhere is my code protected void showprogressnotificationfinal file item int progress boolean isdownloading string message null int smallicon 0 bitmap largeicon null int flags 0 flags notificationflag ongoing event flags notificationflag foreground service flags notificationflag only alert once flags notificationflag auto cancel notificationcompatbuilder builder new notificationcompatbuildergetapplicationcontext buildersetautocanceltrue if progress 100 largeicon bitmapfactorydecoderesourcegetresources o2folderlistadaptergeticonforitemitem false smallicon rdrawableic cloud upto date if isdownloading message download completed tap to clear else message upload completed tap to clear else if progress 0 largeicon bitmapfactorydecoderesourcegetresources o2folderlistadaptergeticonforitemitem true if isdownloading smallicon rdrawableic cloud downloading message downloading progress tap to cancel else smallicon rdrawableic cloud uploading message uploading progress tap to cancel buildersetprogress100 progress false else largeicon bitmapfactorydecoderesourcegetresources o2folderlistadaptergeticonforitemitem true smallicon rdrawableic cloud conflict if isdownloading message cancelled download tap to clear else message cancelled upload tap to clear if mresultintent null mresultintent new intentgetapplicationcontext customdownloadserviceclass mresultintentaddflagsnotificationflag ongoing event mresultintentputextracancel itemgetpathhashcode logdo2abstractdownloadservice setup task id itemgetpathhashcode if mcontentintent null mcontentintent pendingintentgetservicegetapplicationcontext pi req code mresultintent pendingintentflag update current buildersetcontentintentmcontentintent buildersetlargeiconlargeicon buildersetsmalliconsmallicon buildersetcontenttitleitemgetname buildersetcontenttextmessage if progress 100 builderaddactionrdrawableic action dark cancel cancel contentintent final notification notification builderbuild notificationflags flags notificationdefaults notificationdefault lights notificationmanager mnotificationmanager notificationmanager getsystemservicecontextnotification service id allows you to update the notification later on mnotificationmanagernotifyitemgetpathhashcode notification startforegrounditemgetpathhashcode notification only update notification every 100ms unless cancel or complete long notificationdelay 100 long now systemcurrenttimemillis if mfuturecalltime 0 now mfuturecalltime progress 1 progress 100 startforegrounditemgetpathhashcode notification mnotificationmanagernotifyitemgetpathhashcode notification else logdcustomdownloadservice called too often to notification mfuturecalltime now notificationdelayso i am trying to setup the action to call the service when tapping on the notification passing the id of the file to cancel the download can anyone see what i am doing wrong is what i am after actually possible on a xoom tablet the notifications flicker a lot but no so often on the nexus 7 all devices end up swapping rows about constantly which means it is virtually impossible to cancel the download you wantany advice would be greatly appreciatedupdate 1 i think this may be causing one of my issuesandroid servicestartforeground does not respect notification id uniquenessupdate 2 the swapping out issue was fixed by calling buildersetwhenfixedtime obviously the new datetime was causing the rows to reorder each time it was refreshed just need to fix the flickering on xoom and the tap to cancel featureupdate 3 the flickering on xoom was fixed with limiting the calls to refresh the code at the end prevents the notification from being updated more than once ever 100ms the remaining issues are to do with cancelling the tap to cancel works the first time but does not work on subsequent files also i cannot clear the rowsupdate 4 the single cancel issue was cause by the resultintent field being at class level when i created a new one each time i refreshed the notification the ids tied up i also changed the flag to notificationflag only alert once only and only used notify and not startforeground,['android'] +367149,how to copy data from boostscoped array to stdvector vectorint vecboostscoped arrayint scpaintsscpaintsresetnew int10for int i0 i10 i scpaintsi i2vecassignscpaints0 scpaints91 method onevecassignscpaintsget scpaintsget10 method twoquestion 1i have figured out two methods but i am not sure whether they are correct or there is a better way to do this question 2 is it true that we cannot get the valid length from boostscoped arraythank you,['c++'] +367203,sqlite compare dates i have this sqlstatementselect geburtsdatum from kundewhere geburtsdatum between 19930101 and 20101but i get some weird results like 2021990geburtsdatum is a dateany suggestions or solutionsmy tablestructurecreate table kunde kunde id integer not null card integer vorname varchar255 not null nachname varchar255 not null ort varchar255 not null strasse varchar255 not null postleitzahl varchar10 not null mail varchar255 telefonnummer varchar255 geburtsdatum date not null beitrittsdatum date not null geschlecht integer not null land varchar255 not null default asterreich bankname varchar255 bankleitzahl varchar255 kontonummer varchar255 groupid integer not null besucher integer access boolean image blob null writedate date drinkabo boolean primary key kunde id,['sql'] +367217,android edittext hint does not appear it seems to be the most weird thing that i have ever come acrosshere is a layoutrelativelayout xmlnsandroid xmlnstools androidlayout widthmatch parent androidlayout heightmatch parent edittext androidididguessappedittext androidlines1 androidlayout widthmatch parent androidlayout heightwrap content androidlayout alignparentbottomtrue androidgravitycenter horizontal androidinputtypetextcapwords androidhintstringhint relativelayoutthe hint of edittext is not shownif i remove either androidgravitycenter horizontal or androidinputtypetextcapwords hint becomes visiblei have absolutely no idea what has gravity and textcapwords to do with hint is it another android bug or am i doing something wrong in the former case what would be a workaround i want my text to be centeraligned and capitalized and hint to be shown or i want too much from poor android,['android'] +367237,is move assignment via destructmove construct safe heres a very easy way to define move assignment for most any class with a move constructorclass foo public foofoo foo you still have to write this one foo operatorfoo foo if this foo avoid destructing the only copy thisfoo call your own destructor new this foostdmovefoo call move constructor via placement new return this is this sequence of calling your own destructor followed by placement new on the this pointer safe in standard c11,['c++'] +367314,how many spaces for tab charactert i want to implement a text drawing function but i am not sure how t works which means i do not know how many spaces i should print for ti have come up with the following algorithma each t represents at most number of spaces for tab spacesb if t appears in the last line at a corresponding position t for this line should be aligned to the t of last lineexampleprintfattbnprintfttcnshould printa12b34cwhere1number i represents the spaces of t at position i 2number of spaces for tab 4does anyone know the standard algorithm thanks in advance,"['c++', 'c']" +367323,ruby on rails database deployment with gerrit i am considering using ruby on rails for my next project understanding the deployment of a rails website is easy enough to understand sounds like i will be using phusion passengerbut now i am trying to figure out the database i see a lot about database migrations which allow me to update the database using ruby code i also see that i am allowed to create both an up and down variant of these migrations however i can only fathom how this works cleanly in a single direction imagine if i suddenly say the color column cannot be null so the up will make it required and give all null entries a default value but what will the down do if you care about it being identical to how it started you cannot just set the default values back to nullthis does not really matter much for releases to production that will likely just be done in a single direction in the up direction however i want to use gerrit for code reviews as well as setting up a bot to run a build before allowing checkinsso how could that work from one code review to the next the build server will check out the new set of code and run the migrations but when this happens it would not even retain the migration code from before so how could it run the down steps as an simpler example i do not see how i could check out an old version of the code and db migrate backwards,"['ruby-on-rails', 'ruby']" +367355,why does a web audio oscillator only play a note once when i successfully create a tone with a web audio oscillator with noteon then call its noteoff function subsequent calls to noteon does not play the tone again i seem to have to create a new oscillator to play a new note why is thisvar ctx new webkitaudiocontextvar osc ctxcreateoscillatoroscconnectctxdestinationoscstart0 tone is heard previously noteon0 some time lateroscstop0 tone falls silent previously noteoff0 some time lateroscstart0 no effect previously noteon0,['javascript'] +367378,why is the operation address incremented by two i am looking at a javascript emulator of a nes to try and understand how it workson this line addr thisloadopaddr2the opcode is incremented by two however the documentation see appendix e i am reading sayszero page addressing uses a single operand which serves as a pointer to an address in zero page 0ff where the data to be operated on can be found by using zero page addressing only one byte is needed for the operand so the instruction is shorter and therefore faster to execute than with addressing modes which take two operands an example of a zero page instruction is and 12so if the operands argument is only one byte should not it appear directly after it and be 1 instead of 2 why 2this is how i think it works which may be incorrect suppose our memory looks like 0 1 2 3 4 5 index a b c d e f memory pcand our pc is 0 pointing to a for this cycle we say that the opcodevar pc 0 for examples sakevar opcode memorypc aso should not the first operand be the next slot ie bvar first operand memorypc 1 b,['javascript'] +367409,thispatch async and calling a completion handler on the original queue i have seen some related questions but none seem to answer this case i want to write a method that will do some work in the background i need this method to call a completion callback on the same thread queue used for the original method call voidsomemethodvoid bool resultcompletionhandler thispatch queue t current queue some setup code here thispatch asyncthispatch get global queuethispatch queue priority default 0 bool ok some result do some long running processing here thispatch asynccurrent queue completionhandlerok what magic incantation is needed here so the completion handler is called on the same queue or thread as the call to samemethod i do not want to assume the main thread and of course thispatch get current queue is not to be used,"['objective-c', 'ios']" +367424,using stat to check if a file is executable in c for homework i have to write a c program and one of the things it has to do is check to see a file exists and if it is executable by the ownerusing statpathj sb 0 i am able to see if the file indicated by pathj existsi have looked through man pages a lot of questions and answers on stackoverflow and several websites but i am not able to wrap my head around exactly how to check if a file is executable using stati thought it would be as simple as statpathj sb 0 sbst mode 0 s iexec but as far as i can tell by testing it it seems to ignore the fact that these files are not executablei think that perhaps stat does not work the way i think it does assuming i use stat how can i go about fixing this,['c'] +367426,html openingcomment is valid javascript an old idiom for getting very old browsers to ignore javascript blocks in html pages is to wrap the contents of the script element in html commentsscript alertyour browser supports javascript scriptthe rationale is that old javascriptless browsers will render as text the contents of the script element so putting the javascript in an html comment makes the browser have nothing to rendera modern browser on the other hand will see the script element and parse its contents as javascript consequently the comments need to be valid javascript the closing html comment is ignored by the javascript parser because it is preceded by a javascript linecomment my question is how does the opening html comment not cause the javascript parser to fail i have heard from various people that the opening html comment is valid javascript if it is true that the opening comment is evaluated as javascript what does it do when it executes,"['javascript', 'html']" +367451,c11 why does stdcondition variable use stdunique lock i am a bit confused about the role of stdunique lock when working with stdcondition variable as far as i understood the documentation stdunique lock is basically a bloated lock guard with the possibility to swap the state between two locksi have so far used pthread cond waitpthread cond t cond pthread mutex t mutex for this purpose i guess that is what the stl uses on posix it takes a mutex not a lockwhats the difference here is the fact that stdcondition variable deals with stdunique lock an optimization if so how exactly is it faster,['c++'] +367564,angularjs client side data binding and server side templating angularjs uses twoway client side data binding from angularjs developers guidehas anyone consider using mix of server side templating engine with angularjs twoway client side data binding something like thisi am thinking about using angularjs just for partscomponents of the page would it be good ideai would like to hear if you already had experiences with similar approach and what were drawbacks and advantages,['javascript'] +367565,is the setthisplayorientation sample code correct the documentation page for camerasetthisplayorientation contains the following code sample stating that using it will make the camera image show in the same orientation as the thisplay public static void setcamerathisplayorientationactivity activity int cameraid androidhardwarecamera camera androidhardwarecameracamerainfo info new androidhardwarecameracamerainfo androidhardwarecameragetcamerainfocameraid info int rotation activitygetwindowmanagergetdefaultthisplay getrotation int degrees 0 switch rotation case surfacerotation 0 degrees 0 break case surfacerotation 90 degrees 90 break case surfacerotation 180 degrees 180 break case surfacerotation 270 degrees 270 break int result if infofacing cameracamerainfocamera facing front result infoorientation degrees 360 result 360 result 360 compensate the mirror else backfacing result infoorientation degrees 360 360 camerasetthisplayorientationresult however i had problems using it sometimes the image would appear upside down after some trialanderror i found that the correct code would be replacing the last 8 lines of the method int result 360 infoorientation degrees 360 camerasetthisplayorientationresultwhich means the calculation for backfacing cameras is correct for front cameras too the compensate the mirror comment is a bit weird since mirroring cannot be undone by rotating that operation only swaps 90a and 270a rotations which does not really make sense to meso the question is is the sample wrong indeed or am i missing something i tried it on multiple devices both back and front cameras and all supported orientations so i know that my code is working one little detail that might be worth mentioning all my devices returned 90a as infoorientationedit here is my camerarelated code i have tested it on a nexus one and a samsung galaxy s plus it is used in my headtracking 3d app the preview is shown in the lower left corner and should always have the correct orientationsolution sort of it looks like the code is correct but my testing phone samsung galaxy s plus returns an incorrect value for the front cameras camerainfoorientation there are many related thiscussions about the preview being shown upside down on this model examples here and here a way to fix is to include an option to manually rotate the image,['android'] +367575,how to write programs in c net to run them on linuxwinemono in this particular case i need to run complicated net application for linux by complicated i mean that project was developed for 3 years and i do not want to write it again in java or something else and develop and support both net and java version laterapplication is generating mouse and keyboard events by winapidll import and uses serial port i have also few timers for delays for serial port communication 1020ms i dont need big precision herethe rest is just a lot of simple code nothing special no weird controls no directx etcwhat should i expect will this workif some part of code will fail i can change it a little make network connection between net app and miniapplication on linux that i can write for sending mouse and keyboard events or rs232 communicationadditionally i want to ask about wine and net in generalhow to write net applications that should run on linuxwinemonowhich version of framework 1x 20 or can i use 35what should i avoid imports from windows dll timerseditmoved from commenti saw mono few years ago but it was terrible now i see it growed up supports linq threading and other complicated features in addition now help looks really serious im not accepting answer yet because i see that people still posting very useful links if this question gets many 1 i will rewrite it and maybe this will help othersi hope someone here have some practical experience with net on linux here,"['c#', '.net']" +367594,c structs pointless possible duplicatewhat are the differences between struct and class in c i am just trying to figure out if using c structs in c are essentially useless or not do you gain anything by using them opposed to simply creating another classin c the point of structs is obvious simply contiguous allocations of grouped data and a nice way to access said data in c i feel the role becomes a little more vagueseeing as that you can have functions which are members of structs instance variables and visibility labels the only real difference that i see between structs and classes in c is that struct members default to public while class members default to private the way i see them they can actually both be implemented with the same exact underlying systemso am i missing something here as to the purpose of structs in c or have they kind of lost their purpose as i feel they have in c,"['c++', 'c']" +367607,ios how can i destroy a singleton in arc should i i have a singleton class that accumulates data until that data is written to my database if you want to know why i am implementing things this way see here after saving the data i would like to destroy the singleton how can i do this in arc or am i being paranoid and do i need to destroy it at allyou might say that this is a duplicate of this question but the accepted answer here is not specific enough to be helpful it says you can declare a methodfunction you call explicitly what might the code for this look like if i cannot release the object outside a method how can i possibly pull it off inside a method it also says the simplest way is to have a static c class hold it then release it in its destructor i do not know c but can you really put a c class in your app code my singleton is implemented like sonhcfamilystatus familystatus static thispatch once t pred static nhcfamilystatus familystatussharedobjectnil thispatch oncepred familystatussharedobject nhcfamilystatus alloc init return familystatussharedobject,['ios'] +367623,printing mongodb shell output to file i want to pretty print the results of a mongodb find to a file the json object is too large so i am not able to view the entire object with the shell window sizeis there a way to pretty print the results to a file from the shell,['javascript'] +367689,set windowlocation with typescript i am getting an error with the following typescript code reference pathsharedtypescriptjquerydts reference pathsharedtypescriptjquerystaticdts function accesscontrolsaction action logoutlink clickfunction var link this windowlocation linkattrdatahref i am getting an underlined red error for the followinglinkattrdatahref the message says cannot convert string to location type string is missing property reload from type locationdoes anyone know what this means,"['javascript', 'jquery']" +367695,jqueryjavascript syntax highlighting as user types in contenteditable region i am developing a contenteditable region on my website where users will be able to type messages to each other div contenteditabletrue clasmarttextuser types heredivthe thing is we will have smart text inside meaning that if a user type usersame inside this div the username should be highlighted in blue if the username exist and green if he does not exist and of course all of this should happen as the user typesi have no idea where to start right now i have thisbodyonkeyupsmarttextfunction var this this value thishtml regex s gim value valuereplaceregexspan stylecolorredspan thishtmlvaluebut the text keeps jumping as well as the caret position and does not feel like the right direction i guess it is a little similar to jsfiddle which colors code as it finds it i basically want the same thing as twitter has here is a jsfiddle to play around with thanks in advance for your help,"['javascript', 'jquery']" +367713,html5 game how to protect against modification of variables i wrote html5 game based in canvas and i have a problemi use var like thatvar score 0 another code scorebut user can edit that var eg in firebug or chrome editor score hackedany ideas,"['javascript', 'jquery']" +367744,unexpected overload called when function is called from variadic template instantiation assume following codeinclude iostreamtemplatetypename tvoid fooconst t templateunsigned nvoid fooconst char n stdcout charn stdendlvoid fooconst char stdcout const char stdendltemplatetypename tvoid fooconst t stdcout single stdendltemplatetypename first typename tvoid fooconst first first const t rest stdcout generic sizeoft stdendl foofirst foorestint main const char c asdf char a a b c d foof c a 1 fooathe output isgeneric 3single fine f is char genericgeneric 2const char fine c is const char generic 1const char not finesinglecharn fine a is char4the last call fooa where a is char4 calls the version i am expecting templateunsigned n void fooconst char n but why does not instantiation of variadic template of foo call fooconst char n but calls fooconst char instead if there was not a char array overload that should be expected but why is it happening here should not const first capture array type properlyalso what would be the easiest way to make the generic variadic version work properly with arrays passed to itas matthieu m noticed in comments the problem probably is not caused by variadic templates but by indirectioninclude iostreamtemplate unsigned nvoid fooconst char n stdcout charn stdendlvoid fooconst char stdcout const char stdendltemplate typename tvoid goot const t footint main char a a b c d fooa gooa charn const char he also said that it might be compiler bug although the code yields exactly same results in both clang 32 dev g 46 and 47r martinho fernandes noted that changing as type in the last snippet to const char a makes code yield const char twice,['c++'] +367764,best way to redirect single php page for mobile devices with phpjavascript i have a php google map application that i want to make visible to users when they are using a desktop but redirect to another php page if the visitor is using a mobile device i know there are numerous ways to do this from os to browser type detection but was wondering if someone could provide some code they feel is the best way to handle this and it being the most consistent,"['php', 'javascript']" +367766,android alternate row colors in listview public class listview extends listactivity static string itempublic void oncreatebundle icicle superoncreateicicle arrayadapterstring adapter new arrayadapterstringthis androidrlayoutsimple list item 1 strs setlistadapteradapter this is my list view class which works nice and it takes the strings from a class called str and thisplay them in a listview the problem is the listview style is not nice it is black with the strings in whitei want them to be alternative each row has a colori tried many tutorials but none was clear enough how do i make alternative color for each row ex row1 blue row 2 white row 3 blue row 4 white etc,['android'] +367776,initialize a vector to zeros cc11 i know in c11 they added the feature to initialize a variable to zero as such double number number 0int data data 0is there a similar way to initialize a stdvector of a fixed length to all zeros,['c++'] +367847,resizing buttons in twitterbootstrap i am developing a mobilefriendly web app which i would like to feature a deadsimple ui including buttons so large even andre the giant could tap them with ease the problem is i see no simple way of explicitly resizing bootstrap buttons by setting their width or height to a percentage number of pixels or simply having them fill their containers is there a canonical way of greatly enlarging buttons outside of using btn btnsmall or btn btnlarge classes or is this considered a bad practice,['css'] +367957,defining sequel models before connecting in my nonrails app i am trying to define a sequel modelclass foo sequelmodelendwhen i run my app i am getting the error no database associated with sequelmodel have you called sequelconnect or sequelmodeldb sequelerrorin fact i have not called connect because the require foo is happening before my database code runsof course i could switch things around so that the require is done after the db connects but is there another option currently i have all my apps require statements in one file and it would be nice not to have to break that for these model class files,['ruby'] +367965,composite entity scaffolding in ruby on rails i am new to ruby on rails so far i have only created crud operations by using scaffolding now i need to integrate two entities into single form using scaffolding not by hard coding it how can we scaffold two entities together using scripti have two entities student address and student phnumber i want to scaffold these two entities into a single form where i can do crud operations and i want to achieve this by scaffoldingstudent address is an entity consisting of hse name street name etcstudent phnumber another entity consisting of ph number type etci want to scaffold these two entities together,['ruby-on-rails'] +367985,fastest way to find up to 6 consecutive 0 bits in a char array this is what i am currently doingint datalen 500char datadatalenint desired 1 between 1 and 6 inclusivechar bitsdatalen 8for int32 j 0 j datalen j for int i 0 i 8 i bitsj8i dataj 1 7i 1 0 int offset stdsearch nbits bits datalen8 desired 0 bitsreally nasty i know and it is killing performancewhats the fastest way to find the bit offset of the first set of x consecutive 0 bits in a char array where 0 x 7 i am on gcc with sse 42 so builtins like builtin ctz builtin popcountl are an option i just cannot figure out the best way to use them,"['c++', 'c']" +368004,python scoping in dict comprehension x foo 0 localsgetx0 foo 0 localsgetx spam for spam in 0 nonewhat is the reason for this thiscrepancy in behaviour,['python'] +368060,generating doxygen for c projects with generic collections i am using doxygen and graphviz dot to generate some collaboration diagrams for a c project the problem is generic collections like list are not recognised by doxygen does anyone have a solution to thisi found this comment that does not seem very hopeful but was wondering if there are any workarounds,['c#'] +368081,can css dropdown behave like windows7 dropdowns let us say that menu has the following structureli classparentofalla hrefparenta ul clasubmenu level0 lia hrefitem 1ali lia hrefitem 2ali lia hrefitem 3ali lia hrefitem 4a ul clasubmenu level1 lia hrefitem 11ali lia hrefitem 12ali lia hrefitem 13a ul clasubmenu level2 lia hrefitem 21ali lia hrefitem 22a ul clasubmenu level3 lia hrefitem 31ali lia hrefitem 32ali ul li ul li ul li ulliand this is how it looks like when styled please note that nested submenus are position absolute left 100now the questions is can i avoid it being pushed off the screen i am looking for a solution that windows7 menus use they never go off the screen is there some simple javascript check i think that doing just left 100 would work but under what conditions i just need some idea and i can code that in javascript,"['javascript', 'html', 'css']" +368158,rails form in bootstrap modal i am trying to put a rails form in a bootstrap modal dialog i would like to use the modalfooter to hold the cancelsubmit buttons but this does not seem to work inside the form tagdiv classmodalbody simple form for state search do f long form here div classmodalfooter button classbtn datathismissmodal ariahiddentruecancelbutton fbutton submit class btn btnprimary div end div,['ruby-on-rails'] +368187,how do i add a call to fortran code to a project in xcode 45 my company has a bunch of fortran code traditionally we compiled the code we needed into a dll and called that dll when we needed a calculation done we are now trying to create an ipad app which unfortunately means we cannot just call a dll anymore one of my coworkers have managed to make a simple command line tool project where we call a fortran file to write hello world in the debugger however when i try to get it to work on view based ipad app i get a bunch of linker errors saying the symbols i am using cannot be found i know that the command line tool uses a cpp file to actually run the fortran and i have seen many threads concerning calling cpp files in an app but all the ones i have seen are outdated directly contradict each other and their fixes do not work for memy question is is there a more direct way to call fortran straight from a m file if not what do i have to do to take the working command line tool and get it into an appupdate 1 following the tutorials posted in the comments i have been able to create a o file from my fortran code i can do a fileadd files to add it in easily enough but now how do i actually call itupdate 2 okay baby steps i found out you can make a a static library i will call it new library from o files source fileo using the terminal command ar crv new librarya source fileo you can do it for multiple o files by just adding source file2o source file3o for as many o files as you want note make sure you use cd to get to the folder where the o files are located i am pretty sure xcode will work with a files but it seems a h file is still needed to let the other files in the project like the view controllers make calls to whats in the a file i know i can make a new a file from xcode itself new project ios framework library cocoa touch static library but when i have done it that way in the past i just write normal m and h files and when i build the new library it just mashes all the m files into 1 a when i want to use the code in that a in another project i just import the a and all the h files into the new project and i can call the methods in the a file just as if i had imported all the separate m files so the next question is do i still need a h when my a is made with the terminal instead of xcode if so how would i make a fortran header file if not how do i call my fortran code in the a,['objective-c'] +368189,is there any major difference between innerhtml and using createtextnode to fill a span the title is pretty clearis there any major difference between innerhtml and createtextnode used with append to fill a span with text,['javascript'] +368205,jqueryeach this vs valueofelement in a jqueryeach loop i always thought that this was equivalent to valueofelement could someone explain the differenceexampleeachobject functioni val bodyappendbvalueofelementb typeof val bthis b typeof this brresult valueofelement string this objectvalueofelement boolean this objectvalueofelement object this objectfiddle,"['javascript', 'jquery']" +368237,cannot type into html input fields on ios after clicking twice i am experiencing an issue on ios and i have put up a fiddle for itif an event listener is added to the document for any touch event touchstarttouchmovetouchend like sofunction ontouch e documentaddeventlistener touchstart ontouch false that results in the input fields having the following behaviour on iosfirst touch the input gets focus and the user can type correctly into itsubsequent touches with focus on the field already in place typing does not work anymorei am experiencing and testing this issue on ios 5 51 and 6 on both ipad and iphone simulators and actual devicesthe only fix seems to be removing the event listener to restore the correct behaviour of the input fields or to actually never add the listener at alldocumentremoveeventlistener touchstart ontouchi also noticed that if there are multiple iframes on the page and one of them adds the listener to its document it breaks the other iframes input fields toothe fiddle behaves correctly on my android phoneany ideas why is this happening or how to have global custom event handlers for touch events in place that do not break the inputs on ios,"['javascript', 'ios']" +368264,will java have a way for nonlibrary developers to use extension methods cs extension methods are great for adding syntactic sugar java extension methods are great for allowing library developers to add methods to their interfacesi am a nonlibrary java developer and know i will reap a lot of benefits from getting new functionality from libraries but i would still like to have the syntactic sugar capabilities of c extension methods is this or will this be possible in future versions of javaeg i would like to add methods to the string clastring data stringutilscapitalizeabcd instead of thisstring data abcdcapitalize i would like to do thisplease do not focus on this particular example i am only showing the class of functionality i want to be able to achieve,['java'] +368279,remove objects from nsarray i have a project with arci have an nsarray whit some object inside at certain point i need to change the object in the arraywhit a nsmutablearray i will do array removeallobjectsand i am sure that this method release all object contained in the arraybut with an nsarray i cannot do that so my question is if i set array to nil and then reinitialize it the old object contained in the array are really released from memory array nilarray nsarray alloc initwitharraynewarrayor i need to use nsmutablearray,['ios'] +368288,is there a way to query if array field contains a certain value in doctrine2 starting out with symfony2 doctrinei have a table with user objects fos user for which my schema contains a roles column of an array typedoctrine saves fields of this type by serializing them from php array to longtext in mysqls caseso let us say i have the following users saved into dbuser1 arrayrole admin role custom1user2 arrayrole admin role custom2user3 arrayrole custom2now in my controller i want to select all users with role admin set is there a way to write a dql query which would directly return me user1 and user2or do i need to fetch all users to have doctrine to unserialize roles column and then for each of them do in arrayrole admin usergetrolesi have searched the dql part of the manual but so far did not find anything similar to my needsupd found a question about the same thing which contains a working query code,"['php', 'mysql']" +368319,onnewintentintent not working as it should i am building this twitter app where browser is called to authenticate from my main activityrunning the following code in a threadasynctaskintent intent new intentintentaction view uriparseurlsetflagsintentflag activity single top intentflag activity no history intentflag from backgroundcontextstartactivityintentherecontext is the context of main activitythe uri is returned through intentafter authentication what it to do is to come back to my main activityto its present statewhat happens now isit create another instance of main activityi am usingoverridepublic void onnewintentintent intent superonnewintentintent sharedpreferences prefs getsharedpreferencestwitter 0 final uri uri intentgetdata if uri null urigetschemeequalsconstantsoauth callback scheme setloggedintrue tlogout tstatustrue new retrieveaccesstokentaskthisconsumerproviderprefststringexecuteuri but stillthe problem persistanother thing iseverything works fine in emulator23not working in my deviceits android 236my manifest isactivity androidnamemainactivity androidlaunchmodesingletask androidlabelstringtitle activity main intentfilter action androidnameandroidintentactionview category androidnameandroidintentcategorydefault category androidnameandroidintentcategorybrowsable data androidschemexoauthflowtwitter androidhostcallback intentfilteractivity,['android'] +368320,operator call syntax in c whether there can be a situation where the syntaxif first second is different from thatif firstoperatorsecond i do not think so but just want to know it,['c++'] +368324,how do you change the done text in a cab androids documentation says a lot about cabs but nothing about how to change the text for done does anyone know how toother links,['android'] +368348,including a define in all c source files at compile time i need to include a define at the top of around 300 c files i would prefer not to change the code as it is open source code but if i have to i will just write a script to modify all the files is there a way using gcc to add a define or header file include to the top of every source file during compilation the define is thisdefine malloc mymalloc,['c'] +368362,ldap query does not return correct data from active directory i am working on a tool to get user details from ad and import them into another system we were planning on using the objectsid as the unique identifier but i have found that for some reason the objectsid in the ldap result does not match whats in active directory most of the bytes are the same but there are some there are different and sometimes ldap results have fewer bytes than there are in ad objectsid from user in addecimal 1 5 0 0 0 0 0 5 21 0 0 0 35 106 2 96 236 251 239 68 32 255 234 203 122 4 0 0hex 01 05 00 00 00 00 00 05 15 00 00 00 23 6a de 60 ec fb ef 44 20 ff ea cb 7a 04 00 00objectsid for same user via ldap resultdecimal 1 5 0 0 0 0 0 5 21 0 0 0 35 106 63 96 63 63 63 68 32 63 63 63 122 4 0 0hex 01 05 00 00 00 00 00 05 15 00 00 00 23 6a 3f 60 3f 3f 3f 44 20 3f 3f 3f 7a 04 00 00it almost seems as if any value over 128 comes back as 633f in the ldap result for another user the ldap result is missing 1 byte the question markshex from ad 01 05 00 00 00 00 00 05 15 00 00 00 23 6a de 60 ec fb ef 44 20 ff ea cb 88 04 00 00hex from ldap 01 05 00 00 00 00 00 05 15 00 00 00 23 6a 3f 60 3f 3f 3f 44 20 3f 3f 3f 04 00 00heres the main portion of the code i am using to do these tests final string ldapadserver ldap cmdlinegetoptionvalueldapfinal string binddn cmdlinegetoptionvalueufinal string bindcredential cmdlinegetoptionvaluepfinal string basectxdn cmdlinegetoptionvaluedfinal hashtablestring object env new hashtablestring objectenvputcontextsecurity authentication simpleenvputcontextsecurity principal binddnenvputcontextsecurity credentials bindcredentialenvputcontextinitial context factory comsunjndildapldapctxfactoryenvputcontextprovider url ldapadserverenvputcomsunjndildaptraceber systemerrfinal ldapcontext ctx new initialldapcontextenv nullfinal string searchfilter objectclassuser samaccountname accountname final searchcontrols searchcontrols new searchcontrolssearchcontrolssetsearchscopesearchcontrolssubtree scopefinal stringbuilder builder new stringbuilderfinal namingenumerationsearchresult results ctxsearchbasectxdn searchfilter searchcontrolswhile results null resultshasmoreelements final searchresult result resultsnextelement builderappendldaphelpergetsearchresultdetailsresult loggerinfosearch results stringutilsnew line buildertostringthe ldaphelper simply loops through all attributes and returns them in a nicely formatted string the objectguid and objectsid are printed in hex formati was running the test using jre 6 as well as jre 7 with the same result our ad server is window server 2008 rc2 and i have tried to use both ad ports 389 and 3268i am going to look into other java ldap libraries now but i wanted to see if anyone else had run into these issues or does anyone know why this is and how to get around it ie is there a way to get the proper values from adthanksupdatei have now done the same using the unboundid ldap sdk and this works properly and returns the full and correct objectsid as well as objectguid so this seems to be a bug in the standard j2se library code to do that in case anyone is interestedprivate static void unboundidldapsearchfinal string ldapadserver final string binddn final string bindcredential final string basectxdn final string username throws ldapexception exception final ldapconnection connection new ldapconnectionldapadserversubstring0 ldapadserverindexof integerparseintldapadserversubstringldapadserverindexof 1 binddn bindcredential findaccountbyaccountnameconnection basectxdn username connectioncloseprivate static void findaccountbyaccountnamefinal ldapconnection connection final string basectxdn final string accountname throws exception final string searchfilter objectclassusersamaccountname accountname loggerinfoldap search filter searchfilter final searchrequest request new searchrequestbasectxdn searchscopesub searchfilter final comunboundidldapsdksearchresult result connectionsearchrequest final int numofresults resultgetentrycount final stringbuilder builder new stringbuilder builderappendsearch returned with appendnumofresultsappend results appendstringutilsnew line for final searchresultentry entry resultgetsearchentries builderappendldaphelpergetsearchresultdetailsentry loggerinfosearch results stringutilsnew line buildertostring2nd updatehappened to stumble across why the jndi ldap method did not work properly for objectsid and objectguid and got it working in addition to my unboundid solutionfirst of all i realized that when i used the unboundid method of getvalue which returns a string it also returned the same values the j2se jndi version did which is when i figured out that this does a string conversion to utf8 of the imported value i then happened to come across another blog post jndi how to convert as well as this page so all that is needed in order to get the objectsid and objectguid properly is to add them to the list of binary attributes by adding a space separated list of attribute names to the map for the ldap contextenvputjavanamingldapattributesbinary objectsid objectguid,['java'] +368370,why is stdcopy 5x slower than memcpy in my test program this is a followup to this question where i posted this programinclude algorithminclude cstdlibinclude cstdioinclude cstringinclude ctimeinclude iomanipinclude iostreaminclude vectorinclude chronoclass stopwatchpublic typedef stdchronohigh resolution clock clock constructor starts the stopwatch stopwatch mstartclocknow returns elapsed number of seconds in decimal form double elapsed return 10 clocknow mstartcount clockperiodden clocktime point mstartstruct test cast int operatorconst char data const return intdata struct test memcpy int operatorconst char data const int result memcpyresult data sizeofresult return result struct test memmove int operatorconst char data const int result memmoveresult data sizeofresult return result struct test std copy int operatorconst char data const int result stdcopydata data sizeofint reinterpret castchar result return result enum iterations 20 container size 20 returns a list of integers in binary formstdvectorchar get binary data stdvectorchar bytessizeofint container size for stdvectorintsize type i 0 i bytessize i sizeofint memcpybytesi i sizeofi return bytestemplatetypename functionunsigned benchmarkconst function function unsigned counter stdvectorchar binary data get binary data stopwatch sw for unsigned iter 0 iter iterations iter for unsigned i 0 i binary datasize i 4 const char c reinterpret castconst charbinary datai counter functionc return unsigned05 10 swelapsedint main srandtime0 unsigned counter 0 stdcout cast benchmarktest cast counter ms stdendl stdcout memcpy benchmarktest memcpy counter ms stdendl stdcout memmove benchmarktest memmove counter ms stdendl stdcout stdcopy benchmarktest std copy counter ms stdendl stdcout counter counter stdendl stdendli noticed that for some reason stdcopy performs much worse than memcpy the output looks like this on my mac using gcc 47g o test stdc0x o0 wall werror wextra pedanticerrors maincppcast 41 msmemcpy 46 msmemmove 53 msstdcopy 211 mscounter 3838457856g o test stdc0x o1 wall werror wextra pedanticerrors maincppcast 8 msmemcpy 7 msmemmove 8 msstdcopy 19 mscounter 3838457856g o test stdc0x o2 wall werror wextra pedanticerrors maincppcast 3 msmemcpy 2 msmemmove 3 msstdcopy 27 mscounter 3838457856g o test stdc0x o3 wall werror wextra pedanticerrors maincppcast 2 msmemcpy 2 msmemmove 3 msstdcopy 16 mscounter 3838457856as you can see even with o3it is up to 5 times slower than memcpythe results are similar on linuxdoes anyone know why,['c++'] +368373,how do string literals in ruby bypass newinitialize and is there a way to instrument this i was playing with an idea this afternoon and stumbled into something i do not quite understand basically what i am trying to achieve in this experiment is to somehow know every time a string is created for later use such as in some kind of dsl the following works fine for any string that is created via stringnewclass string class self alias method new orig new def newargs o new origargs puts newing o o end end alias method initialize orig initialize def initializeargs initialize origargs puts initializing self endendegirb stringnewfooinitializing foonewing foo foowhat i cannot figure out is how a string object is created when you use a literal for example why does this not go through the same initialization and setupirb literal string literal stringi realize that the compiler is doing something or other differently when a string is literal but does not it need to be initialized simply to be a fully functional object are there any tricks that i could use to determine when a string is created using a literal or is that impossible to dothanks,['ruby'] +368388,is there an open source implementation of shortest path algorithm with thistance labeling a la gavoille et al if you are allowed to precompute linear in v amount of data on graph then there are a family of algorithms which have sublinear query times for shortest paths in a graphgavoille et al thistance labeling in graphscohen et al reachability and thistance queries via 2hop labelsabraham goldberg et al hierarchical hub labellings for shortest pathssome of them are used in bing maps for extremely fast shortest routes calculations the basic idea is to precompute for each vertex forward labels l fv and backward labels l bv which poses a cover property each label is a pair of a vertex and the thistance to it eg l fv u thistv u and l rv u thistu v and the cover property asserts that for any vertices s and t l fs union l rt contains at least one vertex on the shortest path from s to tis there an open source implementation of one of those algorithms c c f d go java,"['c#', 'c++']" +368394,what causes the g1 garbage collector in java 7 to abort its concurrentmark phase i have noticed occasional full gcs in my application using the g1 garbage collector and am trying to figure out why they happen the cycle from one regionscanstart to the next is excerpted below at 61807406 a full gc is logged followed by an entry for concurrentmarkabort what i want to know is why the gc felt the need to do a full stoptheworld garbage collection and how i can avoid it note that this question appears to have been asked before on the openjdk mailing list with no responsesi have trimmed the details of the young gcs for brevity but i can post the full chunk somewhere if needed61805878 gc concurrentrootregionscanstart61805882 gc concurrentrootregionscanend 03358661805882 gc concurrentmarkstart61806133 gc pause young 002836202 secs eden 498m498m0b478m survivors 14m34m heap 3025m4096m2548m4096m times user019 sys0 real003 secs 61806426 gc pause young 0027662 secs eden 478m478m0b480m survivors 34m32m heap 3050m4096m2576m4096m times user019 sys0 real003 secs 61806717 gc pause young 002214895 secs eden 480m480m0b502m survivors 32m10m heap 3056m4096m2571m4096m times user009 sys0 real002 secs 618070 gc pause young 001899188 secs eden 502m502m0b502m survivors 10m10m heap 3074m4096m2573m4096m times user009 sys0 real002 secs 61807201 gc pause young 002619259 secs eden 162m502m0b500m survivors 10m12m heap 3036m4096m2876m4096m times user011 sys0 real003 secs 61807283 gc pause young 002068515 secs eden 102m500m0b500m survivors 12m12m heap 3058m4096m2957m4096m times user009 sys0 real002 secs 61807350 gc pause young 001606520 secs eden 52m500m0b498m survivors 12m14m heap 3020m4096m2969m4096m times user011 sys0 real002 secs 61807389 gc pause young 001573865 secs eden 42m498m0b500m survivors 14m12m heap 3021m4096m2978m4096m times user009 sys0 real002 secs 61807406 full gc 2978m2498m4096m 48896638 secs times user637 sys008 real489 secs 61812296 gc concurrentmarkabort61812542 gc pause young 001526403 secs eden 512m500m0b510m survivors 0b2048k heap 3018m4096m2506m4096m times user009 sys0 real002 secs 61812793 gc pause young initialmark 001391544 secs eden 510m510m0b508m survivors 2048k4096k heap 3016m4096m2508m4096m times user009 sys0 real001 secs 61812807 gc concurrentrootregionscanstartthis is using the java hotspot 170 7 release with the following interesting settingsxxpermsize128mxxmaxpermsize128mxxnewsize512mxxmaxnewsize512mxms4096mxmx4096mxxunlockdiagnosticvmoptionsxxunsyncloadclassxxusetlabxxuseg1gcxxsurvivorratio10xloggcworkspacegclogverbosegcxxprintgcxxprintgctimestampsxxprintgcdetails,['java'] +368408,telling hashset how to sort the data i am trying to create a hashset or any collection type but i think hashset will suit me best that will remain in order no matter what is inserted it is for a contact manager project i am working oni have been experimenting with the example below import javautilpublic class testdriver public static void mainstring args fullname person1 new fullnamestephen harper fullname person2 new fullnamejason kenney fullname person3 new fullnamepeter mackay fullname person4 new fullnamerona ambrose fullname person5 new fullnamerona aabrose hashsetfullname names new hashsetfullname namesaddperson3 namesaddperson1 namesaddperson4 namesaddperson2 systemoutprintlnnames i expected the output to put the names in alphabetical order at least according to either their first or last name however i cannot even thiscern the method hashset used to come up with this orderingjason kenney rona ambrose stephen harper peter mackaymy question is how do i tell my program how to sort the names based on my specifications,['java'] +368433,catransform3dmakerotation hides half the uiview during animation using the following uiview animation with catransform3dmakerotation half the uiview will thisappear during the transform and reappear on completion this only happens when theres a uiimageview behind the uiview in the view hierarchy of interface builderuiview animatewithduration10 delay00 optionsnil animations myviewlayertransform catransform3dmakerotationm pi0010 completionnilthe following is the view layout in interface builderand the animation result belowthe 2nd image is before any animation has taken place the left half thisappears after it has shrunk then grown past the center point the right side previous left side reappears as shown in 4th imagewhen the background image is set usingselfviewbackgroundcolor uicolor colorwithpatternimageuiimage imagenamedjeanspngthe animation completes as expected,['ios'] +368435,nsmergebypropertyobjecttrumpmergepolicy vs nsmergebypropertystoretrumpmergepolicy in my multithreaded app the main thread and one or more background threads may simultaneously access fetch and change information in my core data store for each thread i am creating a new nsmanagedobjectcontext however each instance of nsmanagedobjectcontext uses the same nspersistentstorecoordinator instance stored elsewhere in a singleton my question is in regards to the merge policies of each instance of nsmanagedobjectcontext is there an intrinsic benefit if i set one merge policy for background threads nsmergebypropertystoretrumpmergepolicy and another policy nsmergebypropertyobjecttrumpmergepolicy for the main threadin my nsmangagedobjectcontext getter i have the following conditional if nsthread ismainthread context setmergepolicynsmergebypropertyobjecttrumpmergepolicy else context setmergepolicynsmergebypropertystoretrumpmergepolicy thank youedit is it necessary should i just default to one policy over the other for both types of threads,"['objective-c', 'ios']" +368454,building a small numpy array from individual values fast and readable method i found that a bottleneck in my program is the creation of numpy arrays from a list of given values most commonly putting four values into a 2x2 array there is an obvious easytoread way to do itmy array numpyarray1 3 24 1which takes 15 us very very slow since i am doing it millions of timesthen there is a far faster hardtoread waymy array numpyempty22my array00 1my array01 3my array10 24my array11 1this is 10 times faster at just 1 usis there any method that is both fast and easytoreadwhat i tried so far using asarray instead of array makes no difference passing dtypefloat into array also makes no difference finally i understand that i can do it myselfdef make array from listthe list num rows num cols the array npemptynum rows num cols for i in rangenum rows for j in rangenum cols the arrayij the listij return the arraythis will create the array in 4us which is medium readability at medium speed compared to the two approaches above but really i cannot believe that there is not a better approach using builtin methodsthank you in advance,['python'] +368460,logging variable data with new format string i use logging facility for python 273 documentation for this python version saythe logging package predates newer formatting options such as strformat and stringtemplate these newer formatting options are supportedi like new format with curly braces so i am trying to do something like log logginggetloggersomelogger logdebugformat this message 0 1and get errortypeerror not all arguments converted during string formattingwhat i miss hereps i do not want to use logdebugformat this message 0format1because in this case the message is always being formatted regardless of logger level,['python'] +368472,how to judge whether it is a new day in an ios project i have a uiview i want it to thisplay in a new dayfor exampletoday i launch my appand that uiview comes to my viewbut after thisi cannot see that uiview until tomorrowso i want to know how to judge whether it is a new day to thisplay the uiview,"['ios', 'objective-c']" +368482,how to set path for jre 6 when jre 7 installed i am programming through java 16 you 17 but i have jre version 6 and jre version 7 installed so how to run my compiled program from jdk 16 to run through the jre 6 onlyby default it runs my class files through jre 7 how to change this behavior any idea of setting class path in windows 7 as we does it for jdkthe following is shown in my command promptejavajavac versionjavac 160 17ejavajava versionjava version 170 09javatm se runtime environment build 170 09b05java hotspottm client vm build 235b02 mixed mode sharingthis is for my set command showing the windows 7 environment pathsallusersprofilecprogramdataappdatacusersadministratorappdataroamingclasspathcprogram filesjavajdk160 17binmysqlconnectorjava515binjarcommonprogramfilescprogram filescommon filescomputernamerandmatepccomspeccwindowssystem32cmdexefp no host checknohomedrivechomepathusersadministratorjava homecprogram filesjavajre6binlocalappdatacusersadministratorappdatalocallogonserverrandmatepcnumber of processors2oswindows nt pathcwindowssystem32cwindowscwindowssystem32wbemcwindowssystem32windowspowershellv10cprogram filesjavajdk160 17bincprogram filesjavajre6bincprogram filesmysqlmysql server 51bincprogram filesultraeditcprogram filesjar2exe wizardcprogram filesjavajre6binpathextcomexebatcmdvbsvbejsjsewsfwshmscprocessor architecturex86processor identifierx86 family 15 model 6 stepping 5 genuineintelprocessor level15processor revision0605programdatacprogramdataprogramfilescprogram filespromptpgpsmodulepathcwindowssystem32windowspowershellv10modulespubliccuserspublicsessionnameconsolesystemdrivecsystemrootcwindowstempcusersadmini1appdatalocaltemptmpcusersadmini1appdatalocaltempuserdomainrandmatepcusernameadministratoruserprofilecusersadministratorwindircwindows,['java'] +368497,how to select similar sets in sql i have the following tablesorderid pkorderitemorderid fk orderiditemid fk itemidquantityitemid pkhow can i write a query that can select all orders that are at least 85 similar to a specific orderi considered using the jaccard index statistic to calculate the similarity of two orders by taking the intersection of each set of orderitems divided by the union of each set of orderitems however i cannot think of a way to do so without storing the computed jaccard index for each possible combination of two orders is there another wayalso is there a way to include the difference in quantity of each matched orderitem into accountadditional infototal orders 79ktotal orderitems 176mavg orderitems per order 215total items 13knotethe 85 similarity number is just a best guess at what the customer actually needs it may change in the future a solution that works for any similarity would be preferable,['sql'] +368538,when do i need to override equals and hashcode methods possible duplicateoverriding equals and hashcode in java if i haveclass a int x 1a a1 new aa a2 new aa1equalsa2if i compare 2 instances of a without override the equals method will i get expected result,['java'] +368548,digitincreasing number test a number is called digitincreasing if it is equal and nn n for some digit and between 1 and 9 for example 24 is digitincreasing because it equals 2 22 here and 2actually a friend of mine asked me this question and i am stuck thinking about it but could not find the exact solution so far can anyone help i needed the function that returns true if it is digitincreasing else false,"['c++', 'c']" +368556,apachepoi sorting rows in excel i would like to sort rows in a sheet by one of string column i tried to achive that using sheetshiftrows method but i cannot manage with that it does not switch positions of rows in my method whats wrong in my code or maybe there is better way to sort rows by any string column in excel sorts az rows by string column param sheet sheet to sort param column string column to sort by param rowstart sorting from this row down private void sortsheetsheet sheet int column int rowstart boolean sorting true int lastrow sheetgetlastrownum while sorting true sorting false for row row sheet skip if this row is before first to sort if rowgetrownumrowstart continue end if this is last row if lastrowrowgetrownum break row row2 sheetgetrowrowgetrownum1 if row2 null continue string firstvalue rowgetcellcolumn null rowgetcellcolumngetstringcellvalue string secondvalue row2getcellcolumn null row2getcellcolumngetstringcellvalue compare cell from current row and next row and switch if secondvalue should be before first if secondvaluecomparetoignorecasefirstvalue0 sheetshiftrowsrow2getrownum row2getrownum 1 sheetshiftrowsrowgetrownum rowgetrownum 1 sorting true any idea how to manage row sorting in a sheetupdate the method above works since apachepoi 39 versionedit added missing bracket helvio,['java'] +368575,why does this state that webgl is a 2d api not a 3d api according to html5 rocks webgl is actually a 2d api not a 3d api why do they say that and what does it mean we can specify x y z coordinates in webgl vertex shaders and fragment shaders i cannot understand the difference between a 2d and 3d graphics api could you explain why they say this is a 2d api,['javascript'] +368576,difference between ssl and tls and their usage in java i am trying to establish an ssl or tls connection between a java client and server i am setting upi have been using sslcontextgetinstancessl to build the sslcontext and it workedi would like to know what the purpose of the protocol parameter is in sslcontextgetinstancestring protocolin particular what changes between using sslcontextgetinstancessl and sslcontextgetinstancetls or other possible values,['java'] +368612,why cannot pip uninstall pysqlite i am trying to remove pysqlite from my system using pipwhat i get doing so makes no sense pip uninstall pysqlitethe command worked but watch this pip freezepysqlite101let us try again pip uninstall pysqlitecannot uninstall pysqlite no files were found to uninstallnop seems removed but still show up in pip freezenow comes the fun pip install pysqliterequirement already satisfied use upgrade to upgrade pysqlite in usrlibpython26thistpackagescleaning upfair enough pip install u pysqliteerror command gcc failed with exit status 1cannot roll back pysqlite was not uninstalledi just do not get it why cannot pip uninstall pysqlite,['python'] +368638,greendao creating an automatic id property is there a way to make the db create the id property in an automatic way i want to generate something that looks like thisentity entity schemaaddentitymyentityentityaddidpropertyautoincrementprimarykeyis this possible,['android'] +368670,loading entries in expressionengine with ajax i am looking to load entries from expressionengine in a popup modal with an ajax call using jquery the idea is when the user clicks on the entry title it will open show a modal with the full entry in it i am then looking to have a next previous button on the modal which will allow me to move to the next and previous entries within the popup modali donat know if it is best to load the template or a feed ie json or if there is another way i am happy to hearhas anyone attempted this yet or know of a tut that maybe helpful i have come across this article which sheds some light on it,['jquery'] +368673,benchmarks does python have a faster way of walking a network folder i need to walk through a folder with approximately ten thousand files my old vbscript is very slow in handling this since i have started using ruby and python since then i made a benchmark between the three scripting languages to see which would be the best fit for this jobthe results of the tests below on a subset of 4500 files on a shared network arepython 106 secondsruby 5 secondsvbscript 124 secondsthat vbscript would be slowest was no surprise but i cannot explain the difference between ruby and python is my test for python not optimal is there a faster way to do this in pythonthe test for thumbsdb is just for the test in reality there are more tests to doi needed something that checks every file on the path and does not produce too much output to not thisturb the timing the results are a bit different each run but not by muchpython270import osdef recursepath for path dirs files in oswalkpath for file in files if filelower thumbsdb print pathfileif name main import timeit path serversharefolder printtimeittimeitrecursepath setupfrom main import recurse number1vbscript57set ofso createobjectscriptingfilesystemobjectconst path serversharefolderstart timermylcfilenamethumbsdbsub recursefolder for each file in folderfiles if lcasefilename mylcfilename then wscriptecho file end if next for each subfolder in foldersubfolders call recursesubfolder nextend subset folder ofsogetfolderpathrecursefolderwscriptecho timerstartruby193require benchmarkdef recursivepath bench benchreportpath do dirpatheachfile puts file if filebasenamefiledowncase thumbsdb endendpath serversharefolderbenchmarkbm bench recursivepath benchedit since i suspected the print caused a delay i tested the scripts with printing all 4500 files and also printing none the difference remains r5 p107 in the first case and r45 p107 in the latteredit2 based on the answers and comments here a python version that in some cases could run faster by skipping foldersimport osdef recursepath for path dirs files in oswalkpath for file in files if filelower thumbsdb print pathfiledef recurse2path for path dirs files in oswalkpath for dir in dirs if dir in comics dirsremovedir for file in files if filelower thumbsdb print pathfileif name main import timeit path f printtimeittimeitrecursepath setupfrom main import recurse number1 620102692 printtimeittimeitrecurse2path setupfrom main import recurse2 number1 273848228ruby 57,"['python', 'ruby']" +368682,read metadata from nupkg is there anyway to read the metadata of a nugetpackagefilei would really like to create a simple site for searching among my nupkgfilesthanks in advance,"['c#', '.net']" +368693,how to search in a list of java object i have a list of object and the list is very big the object is class sample string value1 string value2 string value3 string value4 string value5 now i have to search for a specific value of an object in the list say if value3three i have to return those objects my search is not always based on value3the list is listsample list new arraylistsamplewhat is the efficient way of doing itthanks,['java'] +368707,detect device type in my application written in objectivec how do i detect if the device is an iphone ipad or iphone5 ifuidevice currentdeviceuserinterfaceidiom uiuserinterfaceidiomphone iphone or itouch else ipad,"['iphone', 'objective-c']" +368709,primefaces datatable with rowspan i am quite new with jsf primefaces 31 i try to build a complex table and i cannot find a good solution using datatable i need a sorting componenti would like to build a table equivalent to the following html representation using a basic pojo like thatstring field1string field2liststring fields3 3 itemsstring field4table border1tr td rowspan3col1td td rowspan3col2td tdcol31td td rowspan3col4tdtrtr tdcol32tdtrtr tdcol33tdtr tablei give maybe too little information so if you need it please tell me i hope that my question is clearthank you,['html'] +368712,how can i change the font size of ticks of axes object in matplotlib i have a figure i added subfigure to inset i have usedfig pltfigureax figadd subplot1suba figadd axes040140202i now want to change the xtick font size of the subfigure i tried some naive approach such assubaget xaxisget xticksset fontsize10without any luck how can i do this then,['python'] +368734,figure out width of a string in a certain font is there any way to figure out how many pixels wide a certain string in a certain font is in my activity there are dynamic strings put on a button sometimes the string is too long and it is divided on two lines what makes the button look ugly however as i do not use a sort of a console font the single charwidths may vary so it is not a help writing something likestring test somestringifsomestringlengthsomevalue decrement font sizebecause an m is wider than i alternatively is there a way in android to fit a certain string on a single line so the system scales the font size automaticallyeditsince the answer from wsanville was really nice heres my code setting the font size dynamicallyprivate void setupbutton button button new button buttonsettextgetbuttontext getbuttontext is a custom method which returns me a certain string paint paint buttongetpaint float t 0 ifpaintmeasuretextbuttongettexttostring3230 3230 is the max width fitting in the button t getappropriatetextsizebutton buttonsettextsizet private float getappropriatetextsizebutton button float textsize 0 paint paint buttongetpaint textsize paintgettextsize whilepaintmeasuretextbuttongettexttostring3230 textsize 025 buttonsettextsizetextsize return textsize,"['java', 'android']" +368773,if sqldataadapter uses a data reader internally why do people say that using a sqldatareader is faster i keep reading that sqldatareaders are much faster than sqldataadapters because of their fastforward readonly onerowatatime connected nature and that they are specifically faster than sqldataadapters when to populate a datatable object sqldataadapterfilldatatablehowever here and there somebody will mention it probably would not make a difference what you use because sqldataadapter uses a data reader internally to fill its table if this is true how exactly can the adapter be so much slower if it is communicating with the database by using an internal data reader anyway i know i could set up some tests and profile the performance of each one but what i would really like is for someone to shed some light on the alleged performance thiscrepancies if were essentially dealing with the same process either wayi understand that youd typically use a reader to create a list of stronglytyped pocos unlike the data adapter that just fills a table however my question is strictly about the details of the performance difference between the two and not orm concerns,"['c#', '.net']" +368822,whats the difference between standalone and domain on jee6 i am starting an jboss to use on the development and i am using it as standalonei read that on the production environment the jboss should be as a domaini searched for that to understand whats the difference between than but i did not found any document well explained,['java'] +368826,eclipse actually rad throwing war validation error chkj30e on project i have a project that i have just imported from cvs it is working in several dozen other developers ide but in my case it is reporting a problemchkj30e war validation failed comibmetoolsj2eecommonarchivecoreexceptiondeploymentdescriptorloadexception webinfwebxmlgoogling for this suggests its an issue with the way eclipse loads the context for some users cleaning the project works it did not for meany ideas on what i could attempt next to resolve it,['java'] +368837,determine if characters in a string are all of a specific character set i need to be able to take a string in java and determine whether or not all of the characters contained within it are in a specified character set eg iso88591 i have looked around quite a bit for a simple way to do this including playing around with a charsetdecoder but have yet to be able to find somethingwhat is the best way to take a string and determine if all the characters are within a given character set,['java'] +368838,lazy transform in c i have the following python snippet that i would like to reproduce using cfrom itertools import count imapsource count1pipe1 imaplambda x 2 x sourcepipe2 imaplambda x x 1 pipe1sink imaplambda x 3 x pipe2for i in sink print ii have heard of boost phoenix but i could not find an example of a lazy transform behaving in the same way as pythons imap edit to clarify my question the idea is not only to apply functions in sequence using a for but rather to be able to use algorithms like stdtransform on infinite generators the way the functions are composed in a more functional language like dialect is also important as the next step is function compositionupdate thanks bradgonesurfing david brown and xeo for the amazing answers i chose xeos because it is the most concise and it gets me right where i wanted to be but davids was very important into getting the concepts through also bradgonesurfings tipped boostrange,"['c++', 'python']" +368883,downside of thisplay block for images is there any downside to converting img from inlineblock elements into block objects with the thisplay block css propertymost of the time i want them to be block elements any useful inline aspects that i am losing perhaps i am not seeing some as usefulshould all images be converted into block elements by default why are they inlineblock elements according to specps i am asking this with considerations for layout via positioning floats and surrounding elements,['css'] +368900,how to create a string from char array without copying it i have a very big char array that i need to convert to string in order to use regex on itbut it is so big that i get outofmemoryexception when i pass that to string constructori know that string is immutable and therefore it should not be possible to specify its underlying character collection but i need a way to use regular expressions on that without copying the whole thinghow do i get that arrayi get it from a file using streamreader i know the starting position and the length of the content to read read and readblock methods need me to supply a char bufferso here are the things i want to knowis there a way to specify a strings underlaying collection does it even keep its chars in an arrayor using regex directly on a char arrayor getting the part of the file directly as string,"['c#', '.net']" +368920,no loop condition in for and while loop whilecond fineforcond finebut when i remove the conditional part while syntax compilation error for infinite loophow these loops are internally implemented orhow does compiler parser know that empty condition in while is error and in for as infinitei did not find anything about this particularly i think guys like me who are beginner in c might have same confusion,['c'] +368939,html body says czshortcutlistentrue with chromes developer tools i was testing some html code i am making and while using the developer tools on google chrome version 220122994 m i saw the body tag has the attribute czshortcutlistentrue which of course is not on my code what does it mean and why is it showing up i tried looking it up in google but found nothing relevant,['html'] +368943,android is it possible to use stringenum in drawable selector questionsq1 has anyone managed to get custom stringenum attribute working in xml selectors i got a boolean attribute working by following 1 but not a string attributeedit thanks for answers currently android supports only boolean selectors see accepted answer for the reasoni am planning to implement a little complex custom button whose appearance depends on two variables other will be a boolean attribute true or false and another categorylike attribute has many different possible values my plan is to use boolean and string or maybe enum attributes i was hoping i could define the ui in xml selector using boolean and string attributeq2 why in 1 the oncreatedrawablestate boolean attributes are merged only if they are truethis is what i tested boolean attribute works string does notnote this is just a test app to figure out if stringenum attribute is possible in xml selector i know that i could set buttons textcolor without a custom attributein my demo application i use a boolean attribute to set button background to darkbright and string attribute to set text color one of red green blue attributes are defined in resvaluesattrsxmlxml version10 encodingutf8resources declarestyleable namemycustombutton attr namemake dark background formatboolean attr namestr attr formatstring declarestyleableresourceshere are the selectors i want to achievedrawablecustom button background which worksxml version10 encodingutf8selector xmlnsandroid xmlnsapp item appmake dark backgroundtrue androiddrawablecolordark item androiddrawablecolorbright selectorcolorcustom button text color which does not workselector xmlnsandroid xmlnsapp item appstr attrred androidcolorcolorred item appstr attrgreen androidcolorcolorgreen item appstr attrblue androidcolorcolorblue item androidcolorcolorgrey selectorhere is how custom button background is connected to boolean selector and text color is connected to string selectorcomexamplecustomstringattributemycustombutton androidbackgrounddrawablecustom button background androidtextcolorcolorcustom button text color here is how attributes are loaded in the init methodprivate void initattributeset attrs typedarray a getcontextobtainstyledattributesattrs rstyleablemycustombutton final int and agetindexcount for int i 0 i n i int attr agetindexi switch attr case rstyleablemycustombutton str attr mstrattr agetstringattr break case rstyleablemycustombutton make dark background mmakedarkbg agetbooleanattr false break arecyclei have the int arrays for the attributesprivate static final int make dark bg set rattrmake dark background private static final int str attr id rattrstr attr and those int arrays are merged to drawable stateoverrideprotected int oncreatedrawablestateint extraspace logitag oncreatedrawablestate final int drawablestate superoncreatedrawablestateextraspace 2 ifmmakedarkbg mergedrawablestatesdrawablestate make dark bg set mergedrawablestatesdrawablestate str attr id return drawablestatei also have refreshdrawablestate in my attribute setter methodspublic void setmakedarkbgboolean makedarkbg ifmmakedarkbg makedarkbg mmakedarkbg makedarkbg refreshdrawablestate public void setstrattrstring str ifmstrattr str mstrattr str refreshdrawablestate 1 android how to add a custom button state,['android'] +368985,how do i find which transaction is causing a waiting for table metadata lock state i am trying to perform some ddl on a table and show processlist results in a waiting for table metadata lock messagehow can i find out which transaction is not yet closedi am using mysql v5524,['mysql'] +369071,how to remove borders around broken images in webkit can anybody advise me on this webkit browsers keeps on putting a gray 1px border around thisabled images the reason i need this removed is for email optimization for when email clients have images thisabled works fine in firefox but webkit browsers keep showing the borderi have tried bordernone important everywhere including inline but chromesafari are being stubbornedit here is sample html with inline cssimg styleoutlinenonetextdecorationnonethisplayblockbordernonewebkitborder0 border0 srcimagesrm bnkgif width10 height10 alttest,"['html', 'css']" +369095,how to edit multiple models in one form i got a task from my trainer i want to edit two models in one form for example we have two entities student and address in the new student part i want to add both student details and address how can i achieve this through scaffolding in ruby on rails,"['ruby-on-rails', 'ruby']" +369127,what are the major differences between objectivec c and c i am just beginning to learn objectivec and am finding that a background in c which i do not have is a useful starting point i have dabbled in c so have some understanding of basic c paradigms and syntax fwiw i have extensive experience in java and higherlevel languages like javascript and actionscripti am interested in exploring ios development but a bit wary of focusing in on a language useful only on a single vendors platform i would like to know more about how concepts i will learn as i proceed with objectivec will transfer or not to knowledge of c and ci am interested mainly in core language concepts but information on portability frameworks targetable platforms etc is welcome as well,"['c++', 'objective-c', 'c']" +369182,ld framework not found homemade framework i am trying to deploy a project on an ipad containing a homemade framework called hellounityframeworkwhen i try to deploy my project i get the following error ld framework not found hellounity clang error linker command failedwith exit code 1 use v to see invocationmore specific ld userslabinnovationlibrarydeveloperxcodederiveddataunityiphoneakzhbmwtkcooizfaebdhmbyuhrbkbuildproductstestapptest normal armv7 cd userslabinnovationipadwipadwii setenv iphoneos deployment target 221 setenv path applicationsxcodeappcontentsdeveloperplatformsiphoneosplatformdeveloperusrbinapplicationsxcodeappcontentsdeveloperusrbinusrbinbinusrsbinsbin applicationsxcodeappcontentsdevelopertoolchainsxcodedefaultxctoolchainusrbinclang arch armv7 isysroot applicationsxcodeappcontentsdeveloperplatformsiphoneosplatformdevelopersdksiphoneos60sdk luserslabinnovationlibrarydeveloperxcodederiveddataunityiphoneakzhbmwtkcooizfaebdhmbyuhrbkbuildproducts luserslabinnovationipadwipadwii luserslabinnovationipadwipadwiilibraries fuserslabinnovationlibrarydeveloperxcodederiveddataunityiphoneakzhbmwtkcooizfaebdhmbyuhrbkbuildproducts fuserslabinnovationipadwipadwiidesktop fuserslabinnovationipadwipadwii filelist userslabinnovationlibrarydeveloperxcodederiveddataunityiphoneakzhbmwtkcooizfaebdhmbyuhrbkbuildintermediatesunityiphonebuilddebugiphoneosunityiphonebuildobjectsnormalarmv7testlinkfilelist dead strip all load weak framework coremotion weaklsystem fobjclinkruntime miphoneosversionmin221 framework foundation framework uikit framework opengles framework quartzcore framework openal liconv2 liphonelib framework audiotoolbox framework cfnetwork framework mediaplayer framework corelocation framework systemconfiguration weak framework iad framework coremedia framework corevideo framework hellounity weak framework avfoundation framework coregraphics weak framework coremotion weak framework gamekit o userslabinnovationlibrarydeveloperxcodederiveddataunityiphoneakzhbmwtkcooizfaebdhmbyuhrbkbuildproductstestapptestand i do not know why because my framework exist and the frameworks folder is not emptywhat is wrongthanks,['ios'] +369191,c stl vector for existing data can i create an stdvector using my preexisting data instead of it allocating new memory and copying the datato be clearer if i have a memory area either a carray or part of another vector or whatever and i want to provide vectorlike access to it can i create a vector and tell it to use this block of memory,['c++'] +369208,fastest way to read and write large files line by line in java i have been searching a lot for the fastest way to read and write again a large files 05 1 gb in java with limited memory about 64mb each line in the file represents a record so i need to get them line by line the file is a normal text filei tried bufferedreader and bufferedwriter but it does not seem to be the best option it takes about 35 seconds to read and write a file of size 05 gb only read write with no processing i think the bottleneck here is writing as reading alone takes about 10 secondsi tried to read array of bytes but then searching for lines in each array that was read takes more timeany suggestions pleasethanks,['java'] +369218,why does jdk sourcecode take a final copy of volatile instances i read the jdks source code about concurrenthashmapbut the following code confused mepublic boolean isempty final segmentkv segments thissegments my question isthissegments is declaredfinal segmentkv segmentsso here in the beginning of the method declared a same type reference point to the same memorywhy did the author write it like this why did not they use thissegments directly is there some reason,['java'] +369228,how do i make a new list of strings from another list based on certain criteria that is the best way i could think to ask the question the detail is below it is taken me an hour just to figure out how to ask the questionlet us say that i have 5 or more types of text files they are generated by a scientific instrument and each has certain results let us call these types a b c d e the actual names of the text files do not give this away so the user cannot easily see what they are just by the name if it makes it easier we could just consider a list of strings i have no idea what to do about replcate types but i will worry about that lateri wish to give the user the option to combine the text files into a conglomerate file but the challenge is it does not make sense to combine certain types for reasons that i do not feel it worthwhile to go intoi have constructed and example matrix of compatibility a b c d e a 1 1 1 1 0 b 1 1 1 0 0 c 1 1 1 1 0 d 1 0 1 1 1 e 0 0 0 1 1so this is saying that i could combine a with b c d but not e and so onnow if a user chooses files that have types a b and c from a list of files that are not obviously typed i would like to check the selections and say yes abc is a legal merge and perform the mergeif the user selects abcd i would like to say no you cannot do that as d is not compatible with b however you could do abc or acd as d should not be where b would bestill with mei created the above matrix in code and have got to a looping structure where i started to get a bit muddled and thought i might ask for some help before i find myself losing my home and family i have got a fairly large comment section on how i am trying to make choices remember that a could be dog and b could be cat etcinternal class compatibilitycheck private liststring filetypes public compatibilitycheck strings are unique types for text files filetypes new liststring a b c d e int compatibilitymatrix 1 1 1 1 0 1 1 1 0 0 1 1 1 1 0 1 0 1 1 1 0 0 0 1 1 scenario 1 list of file names from user all legal var userselection new liststring a b c go through each item in userselection and make arrays of legal file combinations start with a and find the compatible matches b and c check that b and c are okay answer should look like this as a b and c can be combined scenario 2 list of file names from user not all legal d and b are incompatible var userselection2 new liststring a b c d in my head i go through each item in userselction2 take a and build abcd as it is compatible check b with cyes and dno remove d end abc start with b and build bac check a with cyes end bac start with c and build cab check a with byes end cab start with d and build dac check a with cyes end dac take the nth string and compare to n1 n2 nlengthn the unique string sets woudld be a b c and a c d i hope this is clear so what is the best way to achieve such a task recursion linq magic matrix mathedit an idea i just had that may be easier to implement might be to show a list of files and as a user selects them i could deactivate the other choices that are not compatible imagine a listbox or similar where you select an a type and if the above matrix is in play type e files would be greyed out i wonder if this will cause me less stress,['c#'] +369244,calling thisint index via reflection i try to implement a reflectionbased latebound library to microsoft officethe properties and methods of the offce com objects are called the following waytype type typegettypefromprogidwordapplicationobject comobject activatorcreateinstancetypetypeinvokemembermethod name binding flags null comobject new object paramsinvokemember is the only possible way because typegetmethod getproperty works improperly with the com objectsmethods and properties can be called using invokemember but now i have to solve the following problemmethod in the officeinterop wrapperexcelworkbooks wb excelworkbooksexcelworkbook firstwb wb0respectivelyforeachexcelworkbook w in excelworkbooks dosmth how can i call the thisint index operator of excelworkbooks via reflection,['c#'] +369251,questions about c virtual inheritance the following code are from the book inside the c object modelinclude iostream using namespace stdclass xclass y public virtual xclass z public virtual xclass a public y public zint main coutsizeofx sizeofy sizeofz sizeofaendl return 0in my computerwindows vs2010 the output is1 4 4 8herere my questions1 sizeofx1the book says when x type generate two instance say xa and xb the compile insert a byte into a so that xa and xb can have different address i am not quite understand the reasons2 sizeofy4by using virtual inheritance will we have an additional virtual pointer i guess this might be different from virtual pointer in polymorphism can anyone give me the memory layout for y thank you,['c++'] +369253,javaioioexception setdatasource failed status0x80 i am tying to play url using media player in activity using mediaplayer mediaplayercreategetapplicationcontexturiparseholderit is working fine same code i use to set it as an live wallpaper in onsurfacecreated in wallpaperservice it is giving me following error log dmediaplayer 4128 create failed dmediaplayer 4128javaioioexception setdatasource failed status0x80dmediaplayer 4128 atandroidmediamediaplayer setdatasourcenative method dmediaplayer4128 atandroidmediamediaplayersetdatasourcemediaplayerjava844dmediaplayer 4128 atandroidmediamediaplayersetdatasourcemediaplayerjava806if i use local video uri to set live wallpaperit working fineany ideasuggestion over here,['android'] +369316,how does task become a int we have this methodasync taskint accessthewebasync httpclient client new httpclient taskstring getstringtask clientgetstringasync you can do work here that does not rely on the string from getstringasync doindependentwork string urlcontents await getstringtask the thing is that this returns an int to a method that has a return type of taskint return urlcontentslengthdoes an implicit conversion occur between task and int if not then what is happeninghow is it implemented to work,"['c#', '.net']" +369320,set attribute without value how do i set a data attribute without adding a value in jquery i want thisbody databodyi triedbodyattrdatabody this is a getter not workingbodyattrdatabody null not adding anythingeverything else seems to add the second arguments as a string is it possible to just set an attribute without value,"['javascript', 'jquery']" +369364,decompressing passwordprotected zip files with net 45 microsoft introduces improvements for zip file handling in net 45 in the systemiocompression namespace namely the classes ziparchive and zipfile however i have not yet seen a way to use native net zip file handling for password protected files is there a way to achieve this i am aware that there are pretty good 3rd party zip file libraries that is not the question,"['c#', '.net']" +369376,aggregate values over a range of hours every hour i have a postgresql 91 database with a table containing a timestamp and a measuring value20121025 0100 220121025 0200 520121025 0300 1220121025 0400 720121025 0500 1 i need to average the value over a range of 8 hours every hour in other words i need the average of 1h8h 2h9h 3h10h etci have no idea how to proceed for such a query i have looked everywhere but have also no clue what functionalities to look forthe closes i find are hourlydaily averages or blockaverages eg 1h8h 9h16h etc but in these cases the timestamp is simply converted using the date trunc function as in the example below which is not of use to mewhat i think i am looking for is a function similar to thisselect date truncday timestamp maxvalue from table namegroup by date truncday timestampbut then using some kind of 8hour range for every hour in the groupby clause is that even possible,['sql'] +369392,saving file in internal storage android i am new to android and i am having a problem when i am trying to save a file into internal storage the new example works on my sdk but does not work on my phone i am trying to run de example in a sony ericsson xperia with android 21 by the way the logi gives me the next line datadatacomexamplekeyfilestextmy title thanks override protected void oncreatebundle savedinstancestate todo autogenerated method stub superoncreatesavedinstancestate setcontentviewrlayoutnew text file edittext findviewbyidridtitle new entry edittext findviewbyidridentry new btn button findviewbyidridsave new btnsetonclicklistener new onclicklistener override public void onclickview v file mydir getfilesdir newfilename filegettexttostring if newfilenamecontentequals newfilename untitled newentry entrygettexttostring try file file new new filemydirtext newfilename file newcreatenewfile logifile file newtostring if file newmkdirs fileoutputstream fos new fileoutputstreamfile new foswritenewentrygetbytes fosflush fosclose catch filenotfoundexception e todo autogenerated catch block eprintstacktrace catch ioexception e todo autogenerated catch block eprintstacktrace intent textpass new intentcomexampletextmenu startactivitytextpass that is for creating then in other activity i am reading override protected void oncreatebundle savedinstancestate todo autogenerated method stub superoncreatesavedinstancestate setcontentviewrlayouttext menu btn button findviewbyidridnewnote listfinal listview findviewbyidridlistview btnsetonclicklistenernew onclicklistener override public void onclickview v todo autogenerated method stub intent textpass new intentcomexampletextnew startactivitytextpass listfinalsetonitemclicklistenerthis file filewithinmydir getapplicationcontextgetfilesdir loadbtn button findviewbyidridloadlist loadbtnsetonclicklistenernew onclicklistener override public void onclickview v file mydir getfilesdir file dir new filemydir text string files dirlist string files getapplicationcontextfilelist liststring list new arrayliststring for int i 0 i fileslength i listaddfilesi arrayadapterstring ad new arrayadapterstringtextmenuthis androidrlayoutsimple list item 1 androidridtext1 list listfinalsetadapterad in my android manifiest i have the permissions usessdk androidminsdkversion5 androidtargetsdkversion15 usespermission androidnameandroidhardwarecamera usespermission androidnameandroidpermissioninternet usespermission androidnameandroidpermissionwrite external storage usespermission androidnameandroidpermissionwrite internal storage,['android'] +369423,extjs 41 storeadd followed by sync vs modelsave first i realize this question has been asked here in extjs is it better to call modelsave or storesync however i wish to examine this further specifically regarding minimizing xhrs and unnecessary overhead on both the client and server i do not feel either of these points were addressed in the linked questioni have a somewhat large application designed for enterprise resource management consisting of many models views and controllers i handle all responses from my server by establishing a listener to extajax requestcomplete and requestexception events i took this approach rather than writing duplicate event handlers on every models proxy afterrequest event this enables me to have all of my backend using the zend framework controllers responding with three parameters success message and dataafter a successful request ie http 200 the method run for requestcomplete will inspect the json response for the aforementioned parameters if success is false it is expected that there will be an error message contained in message which is then thisplayed to the user eg there was a problem saving that product invalid product name if success is true action is taken depending on the type of request ie create read update or destroy after a successful create the new record is added to the appropriate data store after delete the record is destroyed and so forthi chose to take this approach rather than adding records to a store and calling the stores sync method in order to minimize xhrs and otherwise round trips my current means of savingupdating data is to send the request to the backend and react to the result on the ext front end i do this by populating a model with data and calling modelsave for createupdate requests or modeldestroy to remove the datai found that when addingupdatingremoving records from a store then calling storesync i would have to react to servers response in a way that felt awkward take for example deleting a recordfirst remove the record from the store via storeremoveinvoke storesync as i have stores autosync set to falsethis fires the ajax destroy request from the stores model proxyheres where it gets weird if there is an error on the server while dropping the row from the database the response will return success false however the record will have already been removed from the extjs data storeat this point i can either call storesync storeload both requiring a round trip or get the record from the request and add it back to the store followed by a commitchanges to avoid calling an additional syncload and thus avoiding an unnecessary round tripthe same goes for adding records if the server fails somewhere while adding data to the database the record is still in the extjs store and must be removed manually to avoid a round trip with storesync or storeloadin order to avoid this whole issue as i previously explained i instantiate one of my model objects eg a product model populate it with data and call mymodelsave this in turn invokes the proxys create or update depending on the id of the model and fires the appropriate ajax request in the event that the backend fails the frontend store is still unchanged on successful requests read success true not http 200 i manually add the record to the store and invoke storecommitchangestrue effectively syncing the store with the database without an additional round trip and avoiding unnecessary overhead for all requests the server will respond with the newmodified data as well as a success parameter and conditionally a message to thisplay on the clientam i missing something here or is this approach a good way to minimize xhrs and serverclient overhead i am happy to provide example code should that be requested however i feel that this is a rather general concept with fundamental code,['javascript'] +369428,forgivingfuzzy search with linq i am attempting to implement a search against a db that i inherited the requirement states that the user must be able to search for an object by name unfortunately an object could have multiple names associated with it for exampleid name1 john and jane doe2 foo mcfoo3 boo mcbooit is easy enough to implement a search when a single name exists in each recordvar objects from x in dbfoo where xnamecontainsfoo mcfoo select xhowever when multiple names exist that approach does not workquestion is it possible to write a search method that would return record one john and jane doe when someone uses the search terms john doe or jane doe,['c#'] +369437,sticky footer not working on safari i am working on a wordpress website and i have run into an issue the sticky footer i have implemented works great in every browser but safari i think it is some sort of padding issue because adding extra padding to the footer corrects the problem in safari but this causes the footer to be taller in other browsers which looks odd i have been struggling with getting the sticky footer right and i thought i would figured it out but obviously i have not i am sure this is a simple fix but i cannot sort it outany help would be greatly appreciated this is the website gandyprinterscomwordpressthanksrebeccaeditsomehow i have managed to correct this issue i do not know exactly at what point it corrected itself but it hasthanks to everyone who gave input i really appreciate the time you took to respond and offer help,['css'] +369452,nscache and background i have noticed that nscache evicts all of its object when the application goes in background is that the expected behaviour is there a way to avoid it i would expect it to evict objects when the device run out of memory not immediately when the app goes in backgrounddo you know any valid alternative,['ios'] +369467,why use tornado and flask together as far as i can tell tornado is a server and a framework in one it seems to me that using flask and tornado together is like adding another abstraction layer more overhead why do people use flask and tornado together what are the advantages,['python'] +369472,obd2 elm327 bluetooth simulator i am developing android application for connecting to elm327 for car unit through bluetooth is there any simulator to simulate elm327 on windows 7 through bluetooth so i can test my application without a car,['android'] +369489,unable to deobfuscate gwt stacktrace we are trying to send uncaught gwt exceptions we are using gwt 25 rc1 to our server for logging and debugging purposes we want to deobfuscate the exception stack traces otherwise it would be pretty much uselessafter some investigations i found 7 tips for exception handling in gwt and webmodeexceptions that contained valuable informationso we created a gwt uncaughtexceptionhandler that uses a custom rpc service to transfer the exceptions with their stack traces that works fineas described in webmodeexceptions deobfuscation section we enabled stacktrace emulation with this in our gwt module setproperty namecompilerstackmode valueemulated setconfigurationproperty namecompileremulatedstackrecordlinenumbers valuetrue now our stacktraces look like this comgooglegwtcoreclientjavascriptexception typeerror cannot call method pp of null unknownatunknown source174 unknownavaunknown source501 unknownyfunknown source29 unknownlqbunknown source138 it seems ok to me because it contains the obfuscated method name and the line number which seems to be what is needed as described in webmodeexceptions deobfuscation sectionthen we compile our gwt modules with the extra parameter to get the symbolmapsour custom log service uses the symbolmaps directory to invoke comgooglegwtloggingserverstacktracedeobfuscator we use xgwtpermutation http header to invoke the deobfuscator i stepped in the deobfuscate method to make sure it could load the symbol map it could i validated that the symbolmap file name used was matching the cachejs file name of the gwt module it does matchso basically the service does this create the deobfuscatorstring dir getsymbolmapsdirpathstacktracedeobfuscator deobfuscator new stacktracedeobfuscatordir request is the httpservletrequeststring strongname requestgetheaderrpcrequestbuilderstrong name header deobfuscate the stack traceexceptionsetstacktrace deobfuscatordeobfuscatestacktraceexceptiongetstacktrace strongname log the exceptionloggersevereuncaught gwt exception exceptionthe end result is that the stack traces do not get deobfuscated sometimes some lines would get deobufscated with the wrong class and method name but nothing more when looking at the symbolmap file the actual symbols in the stack trace do not match to any of the symbols in the symbolmap fileany idea what we are doing wrong hereedit i tried remoteloggingserviceimpl and i get the same results,['java'] +369494,determine if checkbox is checked using jquery possible duplicatecheck checkbox checked property using jquery what is the correct way of accessing a checkbox to check if it is checked is it necessary to first check if that element exists in the dom and then see if is checked or not,['jquery'] +369515,using fileutils in eclipse when trying to use fileutils i get cannot be resolved errorthen how do i install fileutils library to be able to use it in eclipse i see it is an ant utility but i am not sure how many jars i need to install,['java'] +369534,configure rspec to use the capybarajavascript driver for all request specs is it possible globally configure rspec to use capybaras default or custom javascript driver for all request specs we sometimes forget to manually add js true to every request spec and it is kind of annoying,['ruby'] +369540,python simple swap function i came across this problem when attempting to learn python consider the following functiondef swap0s1 s2 assert types1 list and types2 list tmp s1 s1 s2 s2 tmpreturns1 1s2 2swap0s1 s2print s1 s2what will s1 and s2 printafter running the problem i found that the print statement will print 1 2 it seems that the value of s1 and s2 did not change from the swap0 function the only explanation that i could think of was because of the linetmp s1since s1 is a copy this makes sense that the value of s1 will not change in the function call however because the parameter of swap0 is s1 s2 i am not sure if after doing tmp s1 anytime i dos1 somethingit will be a reference to the copy of s1 instead of s1 itself can someone offer a better explanation thanks,['python'] +369548,hide navigationbar for one viewcontroller in storyboard i have found many posts but still no solution i am trying to hide a navigationbar on the initial uiviewcontroller but i want to still show it on the second uiviewcontroller here is my storyboardwhen i turn off the inferred top bar for my main view controller it thisappears in storyboard but it still shows when i run the app when i do the same in to the navigationbar in navcontroller it thisappears for all three because they all inherit the no nav bari want to show the navbar in scrollviewv view controller but have it hidden in mainviewcontrollerall controllers have the corresponding h or m files but i am confused on how to do this programmatically let me know if you need to see anything else thank you much,"['iphone', 'ios']" +369559,what is a threadsafe bytearrayoutputstream i would like to read from a proces output and error streams and merge them into one stream of text my program is in groovy and reads like thisdef mergestream new bytearrayoutputstreamprocesswaitforprocessoutputmergestream mergestreamthe problem is that bytearrayoutputstream is not thread safe and waitforprocessoutput generates two threads which append to mergestream is there a threadsafe variant that i can use how else do you recommend that i control access to mergestream it looks like in practice characters are sometimes dropped with this implementation,['java'] +369565,restkit dynamically map relationship name based on value i am using restkit to parse json and map it into core data nsmanagedobjects here is a sample json events description subject type photo subject id 1 thumb url medium url large url description subject type user subject id 1 username followers using rkobjectmappingprovider and rkmanagedobjectmapping i am mapping the events array into separate core data event objects this works finenow event has two relationships on it user and photo now i need to map the subject array to the proper core data object based on the value of subject typeand set that to the correct relationship on eventi tried using rkdynamicobjectmapping but i do not know how to specify that for a dynamic relationship i need some way to set the name of the destination relationship based on the value of subject typeany thoughts,"['iphone', 'objective-c', 'ios']" +369576,rails creating migration to add columns to table causes error when running rake dbmigrate i have a model created called users and i created a new migration to add some columns to the users table now when i run rake dbmigrate i get the error below bc it is trying to create the users table again rake dbmigrate devisecreateusers migrating create tableusersrake abortedan error has occurred all later migrations canceledmysqlerror table users already exists create table userswhy is it trying to create the table againheres the command i used to create the new migration rails generate migration adetailstousers home phonedecimal cell phonedecimal work phonedecimal birthdaydate home addresstext work addresstext positionstring companystringthe new migration looks like thisclass adetailstousers activerecordmigration def change add column users home phone decimal add column users cell phone decimal add column users work phone decimal add column users birthday date add column users home address text add column users work address text add column users position string add column users company string endendedit20120511224920 devise create usersclass devisecreateusers activerecordmigration def change create tableusers do t database authenticatable tstring email null false default tstring username null false default tstring encrypted password null false default recoverable tstring reset password token tdatetime reset password sent at rememberable tdatetime remember created at trackable tinteger sign in count default 0 tdatetime current sign in at tdatetime last sign in at tstring current sign in ip tstring last sign in ip encryptable tstring password salt confirmable tstring confirmation token tdatetime confirmed at tdatetime confirmation sent at tstring unconfirmed email only if using reconfirmable lockable tinteger failed attempts default 0 only if lock strategy is failed attempts tstring unlock token only if unlock strategy is email or both tdatetime locked at token authenticatable tstring authentication token ttimestamps end add index users email unique true add index users reset password token unique true add index users confirmation token unique true add index users unlock token unique true add index users authentication token unique true endend20120619023856 add name to usersclass addnametousers activerecordmigration def change add column users first name string add column users last name string endend20121031174720 add details to usersrbclass adetailstousers activerecordmigration def change add column users home phone decimal add column users cell phone decimal add column users work phone decimal add column users birthday date add column users home address text add column users work address text add column users position string add column users company string endend,"['ruby-on-rails', 'ruby']" +369598,how do i make my aspnet website more cookie free i ran my website through yahoos yslow on my aspnet vb website that has 47 pages there were a few problems but one of them said i get a grade f on use cookiefree domainsspecifically it sayswhen the browser requests a static image and sends cookies with the request the server ignores the cookies these cookies are unnecessary network traffic to workaround this problem make sure that static components are requested with cookiefree requests by creating a subdomain and hosting them therei really do not know what they are trying to tell me they say 43 components on my homepage are not cookiefree including sitecss printcss homesliderjs and then 38 or 39 jpg or png images are not cookiefreedoes anybody know how i can improve this and improve my sites performance thank you for any suggestions you can offer,['asp.net'] +369627,hide vertical scroll bar in listbox control i am developing an application that requires a listbox control unfortunately when i add too many items in the listbox a vertical scroll bar is shown is there something i can do to hide the vertical scroll bar shown by the listbox i can see that there is a property to hide the horizontal scroll bar but there is no property for the vertical scroll bar,['c#'] +369632,php combine two associative arrays into one array array1 arrayname1 id1array2 arrayname2 id2 name3 id3i need a new array combining all together ie it would bearray3 arrayname1 id1 name2 id2 name3 id3what is the best way to do thissorry i forgot the ids will never match each other but technically the names could yet would not be likely and they all need to be listed in one array i looked at array merge but was not sure if that was best way to do this also how would you unit test this,['php'] +369644,can i set the window border color in wpf may i know how to set the window style or color the image below is my wpfi want to set my window become something like the app belowthanks,['c#'] +369666,how to connect datasource outlet of a page view controller using storyboard in interface builder according to apples documentation here we should be able to add a page view controller into the storyboard and then optionally set the data source by connecting the outletscreating a page view controller interface using a storyboardthe pagebased application xcode template creates a new project with a page view controller as the initial sceneto add a page view controller to an existing storyboard do the followingdrag a page view controller out of the library add a page view controller scene to your storyboardin the attributes inspector set up the appropriate optionsoptionally set a delegate a data source or both by connecting the corresponding outletsthisplay it as the first view controller by selecting the option is initial view controller in the attributes inspector or present the view controller in your user interface in another wayi then defined a uipageviewcontroller subclass like sointerface detailspageviewcontroller uipageviewcontroller uipageviewcontrollerdatasourcebut then when i tried to connect the data source outlet it does not highlight the controller or allow to connect it i have also tried implementing uipageviewcontrollerdatasource on other controllers but i have the same problem of not being able to connect the outletcan anyone help,['objective-c'] +369672,easiest and most efficient way to convert jsonarray to list what is the easiest and most efficient way to convert orgjsonjsonarray to list,['java'] +369689,eclipse surround block with if in eclipse we can surround a piece of code with trycatch i want to surround a piece of code with if statement is there any shortcut key pressing crtl 1 after selecting the block of code did not give me hint to surround with if,['java'] +369694,lineargradients artifacts in mozilla firefox i have problem with lineargradient in mozilla firefox 16on screenshow bad thing is visible bad light line at the bottom of blockcodea hrefbutton textaand css parta background mozlineargradientcenter top 88eb52 3ca82d border 1px solid 399a29 borderradius 4px 4px 4px 4px color f thisplay block float left fontsize 16px fontweight bold lineheight 54px marginbottom 20px margintop 20px textalign center textdecoration none width 376pxi have changed lineheight property on screenshot can anyone describe what is it line and how to hide itthank you sorry for my english,['html'] +369706,syntax error insert enumbody to complete enumdeclaration i was in middle of coding and accidentally put the following line of code at the part of class where we declare instance variables but i checked and it gives the same error anywhere by anywhere i mean inside a static block inside constructor inside any class method except when private is put as the first line of the class it gives syntax error insert enumbody to complete classbodydeclarations as written by chaitanya10 in comments below and also verified by me on my workspace error in eclipse tooltip when we hover cursor over it i understand there is errorbut i dont understand the error message when i hover cursor over the error what is the meaning of this message why does it expecting enumbody below is the screenshot,['java'] +369713,strange memory leak with python paramiko i have an apparent memory leak in a python script that i cannot quite explain the resident memory just keeps growing it started off with about 6mb resident i left it running overnight and it had gotten to over 200mb i did that to rule out a sawtooth memory usage pattern due to gc i have condensed it down to this scriptimport sysimport timeimport paramikodef update ssh paramikosshclient sshset missing host key policyparamikoautoaddpolicy try sshconnecthostnamelocalhost finally sshclosedef main whiletrue update timesleep01if name main sysexitmaini thought the problem might be that i keep instantiating a new sshclient and they somehow werent getting thrown out but this version leaks memory even fasterimport sysimport timeimport paramikossh paramikosshclientsshset missing host key policyparamikoautoaddpolicydef update global ssh try sshconnecthostnamelocalhost finally sshclosedef main whiletrue update timesleep01if name main sysexitmainif anyone could shed some light on this or if i am just being dumb and someone can point out why i would be most appreciative thanks,['python'] +369749,namedpipeclientstream can not access to namedpipeserverstream under session 0 i have namedpipeclientstream which connects to namedpipeserverstream they exchange a couple of messages and then namedpipeclientstream closing while namedpipeserverstream recreated and continue listening for the client pipes i could not make a working async server pipe so this is some kind of dognailthe clientserver interaction works fine during my clients streams launched from normal user sessionsbut there are a situation when client pipe is launched from session 0 on win7 and win2008 server when this happens i had an error in client streamaccess to the path is deniedwhat is the problem how to avoid itsorry i cannot tell you more info about exception only i have is this message in log and i cannot debug my program from zero session can ithe server stream codepipesecurity ps new pipesecuritysystemsecurityprincipalsecurityidentifier sid new systemsecurityprincipalsecurityidentifiersystemsecurityprincipalwellknownsidtypebuiltinuserssid nullpipeaccessrule par new pipeaccessrulesid pipeaccessrightsreadwrite systemsecurityaccesscontrolaccesscontroltypeallowpsaddaccessruleparpipeclientconnection new namedpipeserverstreamgeneralpipename pipedirectioninout 1 pipetransmissionmodebyte pipeoptionsasynchronous generalbuffersize generalbuffersize psconsolewritewaiting for client connectioniasyncresult result pipeclientconnectionbeginwaitforconnectiononpipeconnected pipeclientconnectionmaybe something is wrong with security settingsand the client codeusing namedpipeclientstream pipestream new namedpipeclientstream generalpipename pipedirectioninout try consolewritelineconnecting with pipe pipestreamconnectgeneralconnectiontimeout consolewritelinepipe connection established do something the server is launched as windows service under localsystem the client is a simple console application it is launched by another application launched from localsystem service,['c#'] +369761,two fragments in one viewpager page currently i use one fragment per viewpagers page through fragmentpageradapter very wellbut now i want to use a two panel view inside one viewpagers page for tabletfro example the left hand side is a list view and the right hand side is a gridviewdoes anybody know how can i achieve thatthanks a lot,['android'] +369767,add classes dynamically to the children by looping through div i need a jquery script to add class dynamically to the divs in the class row the class is for setting margins if there is two divs in class row add class to first one only and if there is three divs add class to two avoid third so the actual need is calculate the divs on the row and add classes to div other than the last one here is my html div classrow div classtwocol h3header 23 columnh3 pkidney cancer canada is a charitable patientled support organization established to improve the quality of life for patients and their families living with kidney cancer a hrefkidney cancer canadaa advocates for access to netreatments provides support and information to patients funds muchneeded research and works to increase awareness of kidney cancer as a significant health issue our goal is to help patients navigate through information about their thisease and ensure they have access to new treatment options available to themp div div classonecol h3header 13 columnh3 pkcc hosts patient and caregiver education meetings and webcasts from locations all across canada atending meetings inperson provides an excellent oppurtunity to meet other kidney cancer patients caregivers and healthcare professionalsp div div classcleardiv div div classrow div classonecol h3header 13 columnh3 pkcc hosts patient and caregiver education meetings and webcasts from locations all across canada atending meetings inperson provides an excellent oppurtunity to meet other kidney cancer patients caregivers and healthcare professionalsp div div classonecol h3header 13 columnh3 pkcc hosts patient and caregiver education meetings and webcasts from locations all across canada atending meetings inperson provides an excellent oppurtunity to meet other kidney cancer patients caregivers and healthcare professionalsp div div classonecol h3header 13 columnh3 pkcc hosts patient and caregiver education meetings and webcasts from locations all across canada atending meetings inperson provides an excellent oppurtunity to meet other kidney cancer patients caregivers and healthcare professionalsp div div classcleardiv div,"['jquery', 'css']" +369771,jackson deserializing with custom deserializer causes a lot of gc calls and takes a lot longer to solve my type mismatch problem thiscussed in this thread i created custom deserializers and added them to objectmapper however the performance deteriorates significantly with thiswith default deserializer i get 12 garbage collection calls in logcat while with custom deserializer there are at least 78 gc calls and hence the processing time is also increase significantlymy deserializer public class deserializert public jsondeserializert getdeserializerfinal classt cls return new jsondeserializert override public t deserializejsonparser jp deserializationcontext arg1 throws ioexception jsonprocessingexception jsonnode node jpreadvalueastree if nodeisobject return new objectmapperconvertvaluenode cls return null and i am using this to add to mapperpublic class deserializerattachedmappert public objectmapper getmapperattachedwithfinal classt cls jsondeserializert deserializer objectmapper mapper new objectmapper simplemodule module new simplemoduledeserializertostring new version1 0 0 null null null moduleadeserializercls deserializer mapperregistermodulemodule return mapper edit added extra datamy json is of considerable size but not hugei have pasted it herenow for parsing the same json if i use this code string response connectionmanagerdogetmauthtype url authtoken flogdlocation object response response simplemodule module new simplemoduleusermodule new version1 0 0 null null null jsondeserializeruser userdeserializer new deserializerusergetdeserializeruserclass moduleadeserializeruserclass userdeserializer objectmapper mapper new objectmapper mapperregistermodulemodule jsonnode tree mapperreadtreeresponse integer code integerparseinttreegetcodeastexttrim ifconstantsapi response success code code explorelocationobject locationobject mapperconvertvaluetreepathresponsegetlocationobject explorelocationobjectclass flogdlocationobject locationobject flogdlocationobject events locationobjectgeteventssize return locationobject return null then my logcat is like thisbut if i use this code for same json string response connectionmanagerdogetmauthtype url authtoken flogdlocation object response response simplemodule module new simplemoduleusermodule new version1 0 0 null null null jsondeserializeruser userdeserializer new deserializerusergetdeserializeruserclass moduleadeserializeruserclass userdeserializer objectmapper mapper new objectmapper mapperregistermodulemodule jsonnode tree mapperreadtreeresponse integer code integerparseinttreegetcodeastexttrim ifconstantsapi response success code code explorelocationobject locationobject mapperconvertvaluetreepathresponsegetlocationobject explorelocationobjectclass flogdlocationobject locationobject flogdlocationobject events locationobjectgeteventssize return locationobject return null then my logcat is like this,"['java', 'android']" +369776,call python function from javascript code i would like to call a python function from javascript code because there is not an alternative in javascript for doing what i want is this possible could you adjust the below snippet to workjavascript partvar tag documentgetelementsbytagnamep0text taginnerhtml here i would like to call the python interpreter with python functionarrofstrings opensomehowpythoninterpreterpythoncodepy processparagraphtextpythoncodepycontains functions using advanced libraries that do not have an easy to write equivalent in javascriptimport nltk is not in javascriptdef processparagraphtext nltk calls return lst returns a list of strings will be converted to javascript array,"['javascript', 'python']" +369860,elasticsearch return the tokens of a field how can i have the tokens of a particular field returned in the resultfor example a get requestcurl xget httplocalhost9200twittertweet1returns index twitter type tweet id 1 source user kimchy postdate 200915t141212 message trying out elastic search i would like to have the tokens of sourcemessage field included in the result,['java'] +369863,javascript for iphone to open in safari from nondefault ios browser googlechromewlegocom opened in mobile safari will switch to google chrome ios app to open the url this allows for scriptlets like the one below which allows you to open the current page in google chrome ios app switching from mobile safarifunction7bifdocumentlocationhrefindexofhttp0documentlocationhrefdocumentlocationhrefreplace5ehttpgooglechrome7dmy question is can the reverse be done i tried safariwlegocom and it is simply an invalid url can you make a scriptlet which switches from google chrome to mobile safari to open the current page,"['javascript', 'ios']" +369870,show a custom picture before a youtube video starts i am trying to thisplay an image in the player div and then after the visitor clicks the button replace it with a video replace the div with an iframe heres my codedoctype html headstyle typetextcsshtml textalign centerplayer thisplay inlineblockwidth 640pxheight 360pxbackground url norepeatstyleheadhtml body 1 the iframe and video player will replace this div tag div idplayerdiv pbutton onclickplaymeplaybuttonp script function playme 2 this code loads the iframe player api code asynchronously var tag documentcreateelementscript tagsrc api var firstscripttag documentgetelementsbytagnamescript0 firstscripttagparentnodeinsertbeforetag firstscripttag 3 this function creates an iframe and youtube player after the api code downloads var player function onyoutubeiframeapiready player new ytplayerplayer height 360 width 640 videoid jw5mekfy3fy playervars autoplay 0 controls 0 rel 0 showinfo 0 events onready onplayerready 4 the api will call this function when the video player is ready function onplayerreadyevent eventtargetplayvideo script bodyhtmlbut it does not work it works when the playme function is removed but i would need the video start after a buttondivlink is clicked i have tried to put the picture and the video into separate divs picture on top of the video and than after the click hide the top div and start the video but that did not work either,"['javascript', 'html']" +369872,android https connection to a net wcf service gives sslexception no peer certificate solved see belowi have been getting an exception when trying to get some json data from my rest enabled wcf service in android 22 over a https connection i then noticed something very strange happeningwhen running the application on my phone it worked great and it would get beautiful json data back however when running the application on my the emulator it crashed as soon as the httpclientexecuterequest was executed giving an sllexception no peer certificate this being especially strange because my wcf service had a valid rapidssl signed certificate ca plus i made sure client certificates werent needed inside my iis also this function was not running on the uithread it was running on a separate threadmy code public object getjsonstring url hashmapstring string parameters string method string tag try thistag tag send get request to servicemethodparams target api8 for androidhttpclient and target api5 for defaulthttpclient androidhttpclient client androidhttpclientnewinstanceandroid string params ifparameters null for entrystring string para parametersentryset params params stringparagetkey stringparagetvalue params paramssubstring0 paramslength 1 logius and ps paramsusername and password check httpget request new httpgeturl method params logitag requestgetrequestlinetostring requestsetheaderaccept applicationjson requestsetheadercontenttype applicationjson httpresponse response clientexecuterequestcrashes here httpentity responseentity responsegetentity read response data into buffer char buffer new charintresponseentitygetcontentlength inputstream stream responseentitygetcontent inputstreamreader reader new inputstreamreaderstream readerreadbuffer streamclosenow i have tried searching for a solution however basically no solution fitted this situation solutionmy emulator was running through a snapshot since i edited the hosts file so i did not need to set my service up in a dns now here comes the catch since i ran it through a snapshot every time the date was set to oct 24 2012 with time 1848 in the emulator i then realized the date i validated the certificate was oct 27 2012 with time 1445 apparently the get time from the internet option does not work on the emulator this made my httpclient throw the no peer certificate exception since it technically did not have a validated certificate in the emulator the sad part is that when you search for a solution to this exception with keywords as android or https android wcf you only get results of people with problems relating to self signed certificates tldr apparently in the future validated certificates do not get accepted,['android'] +369876,prepend models to collection i am looking for an elegant way to prepend models to a collection when adding them in the backbone source code there is an unshift method to do just that but the add method for adding models to a collection is too complex to simply extend i am building a slide show that depends on photos and tweets and should always show the newest on top oldest last simplification of my probleminitialize app api call returnsapple banana lemonso apple is the newest slide the collection is builtapple banana lemonafter interval api call checks if there are newer fruits resultorangecollection appends modelapple banana lemon orangethat is not what i want orange is the newest fruit and apple after that but in this case i could reverse my initial collection before appending and rereverse when drawing slides now things get more complex i added parentheses to clarifyapi call checks for even more fruitspineapple kiwicollection appends new models one by oneapple banana lemon orange pineapple kiwiso now from new to old my collection looks like thisnot so old older oldest pretty new brand new newwhich makes absolutely no sense ofcourse changing the api response could make my life easier but that is currently not an option also it should not really matter as the order of items in the response is new old which is fine by mei could not find an out of the box solution for this and i do not want to overcomplicate things by cloning part of the backbone source just to unshift new models suggestions thanks,['javascript'] +369879,comparing speed of nonmatching regexp the following python code is incredibly slowimport rerematch ac a 30 b and it gets worse if you replace 30 with a larger constanti suspect that the parsing ambiguity due to the consecutive is the culprit but i am not very expert in regexp parsing and matching is this a bug of the python regexp engine or any reasonable implementation will do the samei am not a perl expert but the following returns quite fastperl e sab print okn if s macand increasing the number of a does not alter substantially the execution speed,['python'] +369902,force overflow menu in actionbarsherlock i want the 40 overflow menu to be used on pre ics devices 23 21 i am using holoeverywhere with actionbarsherlocki tried the following solutionactionbarsherlock holoeverywhere forcing overflowbut it does not work because absforceoverflow does not exist was it removed in the newest version or something i have checked the r files of both abs and he library projects and the field is simply not theremy apps theme is set to styleholothemesherlocklight and that is the theme that i was trying to inherit from and add the absforceoverflow parameter set to true,['android'] +369926,how to dynamically change youtube player videoid i want to use the ytplayer code so that i can detect events i have a csv file with youtube video ids and a function that puts the ids in an array and want to be able to dynamically change the id when a user click an image essentially like thishtml 1 the iframe and video player will replace this div tag div idplayerdivjavascript 2 this code loads the iframe player api code asynchronouslyvar tag documentcreateelementscripttagsrc wyoutubecomiframe apivar firstscripttag documentgetelementsbytagnamescript0firstscripttagparentnodeinsertbeforetag firstscripttag 3 this function creates an iframe and youtube player after the api code downloads note videoid is taken out and instead is placed as the generated iframe src from the postselection functionvar playerfunction onyoutubeiframeapiready player new ytplayerplayer height 100 width 100 videoid call to function or variable here events onready onplayerready onstatechange onplayerstatechange if you are familiar with this code then what happens is the player div is replaced by an iframe i can change the iframe source with this functionfunction postselection playerattrsrc selectedattributesurl selectedattributesurl comes from the cvs filebut this is very buggy and not cross browser friendly if i use a standard iframe and not the yt player api then everything works just fine but i want to detect the end and pause and so on so i have to use the api my guess is that it is an issue with state and that persistence is lost some where in the creation of the iframeregards,"['javascript', 'jquery']" +369928,why are java primitive types modifiers public abstract final in the process of doing some reflection on java types i came across an oddity that i do not understandinspecting int for its modifiers returns public abstract and final i understand public and final but the presence of abstract on a primitive type is nonobvious to me why is this the caseedit i am not reflecting on integer but on intimport javalangreflectmodifierpublic class integerreflection public static void mainfinal string args systemoutprintlnstringformatintclass integerclass b intclass integerclass systemoutprintlnstringformatintclass modifiers s modifiertostringintclassgetmodifiers systemoutprintlnstringformatintegerclass modifiers s modifiertostringintegerclassgetmodifiers the output when runintclass integerclass falseintclass modifiers public abstract finalintegerclass modifiers public final,['java'] +369931,maintaining logging andor stdoutstderr in python daemon every recipe that i have found for creating a daemon process in python involves forking twice for unix and then closing all open file descriptors see simple unix linux daemon in python for an examplethis is all simple enough but i seem to have an issue on the production machine that i am setting up my daemon is aborting silently since all open file descriptors were closed i am having a tricky time debugging the issue currently and am wondering what the proper way to catch and log these errors arewhat is the right way to setup logging such that it continues to work after daemonizing do i just call loggingbasicconfig a second time after daemonizing whats the right way to capture stdout and stderr i am fuzzy on the details of why all the files are closed ideally my main code could just call daemon startpid file and logging would continue to work,['python'] +369970,c thread safe fastest counter what is the way to obtain a thread safe counter in c with best possible performancethis is as simple as it getspublic static long getnextvalue long result lock lock result counter return resultbut are there faster alternatives,['c#'] +370027,how to open a bootstrap modal window using jquery i am using twitters bootstrap modal window functionality when someone clicks submit on my form i want to show the modal window upon clicking the submit button in the formform idmyform classformwizard h2 classformwizardheadingbootstap wizzard formh2 input typetext value input typesubmitform modal div idmymodal classmodal hide fade tabindex1 roledialog arialabelledbymymodallabel ariahiddentrue div classmodalheader button typebutton classclose datathismissmodal ariahiddentrueabutton h3 idmymodallabelmodal headerh3 div div classmodalbody pone fine bodyap div div classmodalfooter button classbtn datathismissmodal ariahiddentrueclosebutton button classbtn btnprimarysave changesbutton divdivjquerymyformonsubmit functionev mymodalmodal show false var data thisserializeobject json data jsonstringifydata resultstextjson data modalbodytextjson data resultstextdata evpreventdefault,"['javascript', 'jquery']" +370056,is there a concise emacs lisp equivalent of pythons nm list slices one thing i find myself missing in emacs lisp is surprisingly a particular bit of list manipulation i miss pythons concise list slicing mylist foo bar baz qux frobnitz mylist14bar baz quxi see the functions butlast and nthcdr in the emacs documentation which would give the same results from code like thissetq mylist foo bar baz qux frobnitzbutlast nthcdr 1 mylist 1 bar baz quxis there a more concise way of getting a list slice than combining butlast and nthcdr,['python'] +370058,c function not overridden when using templates sorry if this is a stupid question but i have been tearing my hair out over this problem and cannot figure out how to solve iti am in the final stages of writing a small calendar library for a school assignment and i have run into an unexpected and very confusing problem my assignment operator is not overridden when i introduce templatesso the structure is the following i have an abstract class date with mostly pure virtual functions including the assignment operator and then i have two subclasses gregorian and julian that implement all its functions finally i have written a template for a class calendar which contains todays date in the form of a gregorian or julian object and some other stuff that are not really relevant for this particular problemthe problem is that when trying to set this member today i get a long linker errorerror 4 error lnk2019 unresolved external symbol public virtual class lab2date thiscall lab2dateoperatorclass lab2date const 4datelab2uaeaav01abv01z referenced in function public class lab2gregorian thiscall lab2gregorianoperatorclass lab2gregorian const 4gregorianlab2qaeaav01abv01z cuserstestobj calendartelling me that it cannot find the function operator in the date class obviously because it is purely virtual why is not it using any of the overridden onesit is telling me that gregorianoperator is trying to call dateoperatorheres the simplified code where things go wrongnamespace cal lib template typename t class calendar public calendar today t this yields the error private t today and heres a snippet from gregoriancppnamespace cal lib class gregorian public date public gregorian virtual gregorian operatorconst date date virtual date add yearint and 1 virtual date add monthint and 1 here i am using dates constructor to get the current date gregoriangregorian gregorian gregorianoperatorconst date date if this date these member variables are specified as protected in date m year 1858 m month 11 m day 17 add yeardatemod julian day365 add monthdatemod julian day mod julian day31 operatordatemod julian day mod julian day the default constructor of date simply sets the values of m year m month and m day to todays datedatedate time t t timet struct tm now gmtimet m year nowtm year 1900 m month nowtm mon 1 m day nowtm mdayit is worth noting though that this works perfectly finegregorian gjulian jg j no problems heredate gp new gregoriandate jp new juliangp jp no problems here eitherthis is how the calendar class is instantiatedusing namespace cal libcalendargregorian calis there some very obvious mistake here that i am doingedit thank you so much everyone for helping me this is the first time i am asking a question at stack overflow and did not expect to receive that much good help that quick many thanks,['c++'] +370069,must be nonnullable in order to use as parameter t i am trying to create a code first class with my own object types and get this errormtobject must be a nonnullable value type in order to use it as parameter t in the generic type or method systemdataentitymodelconfigurationconfigurationstructuraltypeconfigurationtstructuraltypepropertytsystemlinqexpressionsexpressionsystemfunctstructuraltypetis there a way to declare my class property to get past this errorcode is below simple examplepublic class mtobject public string object get set public mtobject public class person public decimal id get set public string name get set public mtobject name get set public int32 age get set public class personconfiguration entitytypeconfigurationperson public personconfiguration base haskeyp pid propertyp pidhascolumnnameidhasdatabasegeneratedoptiondatabasegeneratedoptionidentity propertyp pnamehascolumnnamenameisoptional propertyp pagehascolumnnameageisoptional totableperson public class persondatabase dbcontext public dbsetperson persons get set public persondatabasestring connectionstring baseconnectionstring databasecreateifnotexists protected override void onmodelcreatingdbmodelbuilder modelbuilder modelbuilderconfigurationsaddnew personconfiguration baseonmodelcreatingmodelbuilder end simple example,"['c#', '.net']" +370083,using less and version control should generated css be included in a repo i am considering using less for css development with server or development side processing but i cannot decide if i should keep the generated css files in version control there are plenty of solutions with hooks but this adds software dependencies to the server a hook could just be added locally so staging and production areas on the web would get the same files so the question isshould generated css files be included in version control or not please keep in mind that some frameworks require a css file to exist for a particular reason ie wordpress themes require a stylecss file in order to be recognizedcheersedit when i say considering using less i mean it becomes a requirement new developers would not have the option use vanilla css after the choice is in favor of less,['css'] +370114,which python web frameworkdjango or djangonorel or pyramid to use when mongodb is used as a database i am using mongodb as my primaryand only till now database and because of google and the links it provided me i am confused between django or pyramid i am comfortable with python but never done web development in pythoni have done in php now because i will be using mongo so i wont use django orm will that take away the ease of development people associate with django i am new to djangojust a few hours so i am not sure what parts of the framework the orm affects or should i go with the django fork djangonorel with django mongodb engine they are not actively maintained though or should i use pyramid because i plan to use jinja2 as my template layer so that makes 2 parts of django useless to meafter removing these batteries from django does it still remain true that it a framework for people with deadlinesadvice,['python'] +370116,nsusernotification how open the app when clicked i am using nsusernotification to thisplay notifications this is working fine the problem is that when you click on a notificationthe apps notifications are not removed from the notification centerthe app when minimized does not openanyone familiar with the nsusernotification who can offer some pointersnoticemimport noticehimplementation notice void notifynsdictionary message nslognotification show it nsusernotification notification nsusernotification alloc init notification settitlemessage valueforkeytitle notification setinformativetextmessage valueforkeycontent notification setdeliverydatensdate datewithtimeinterval0 sincedatensdate date notification setsoundnamensusernotificationdefaultsoundname nsusernotificationcenter center nsusernotificationcenter defaultusernotificationcenter center schedulenotificationnotification void usernotificationcenternsusernotificationcenter center didactivatenotificationnsusernotification notification nslognotification clicked notificationnil center removedeliverednotification notificationpragma mark webscripting protocol bool isselectorexcludedfromwebscriptselselector if selector selectornotify return no return yes nsstring webscriptnameforselectorselselector id result nil if selector selectornotify result notify return result right now exclude all properties eg keys bool iskeyexcludedfromwebscriptconst charname return yesendthank you,['objective-c'] +370153,how to implement a custom 404 error page on app engine java hi i am trying to set up a static error page for 404 not found errors on app engineaccording to handlers it says 404 cannot be customized and according to error responses it do not seem to support 404 toohowever topicgoogleappenginejava3cpy5ta2hq seems to suggest that 404 error page can be customised i am confused right now,['java'] +370158,how to change inner lineheight of css text i am trying to work with an icon font called entypo the font is great but the padding that the developer chose is horrendous and makes this font infuriating to work with the icons are really good though and i am just trying to make it workwhat it boils down to to make the font look normal the font size needs to be huge like 40px if youre trying to fit the icon into a space of 15px height the fontsize will be 40px and then there is all that extra space you need to deal withi have tried setting explicit height explicit lineheight verticalalign in every conceivable combination and the result is differenct between pc and macthe only thing i can think of is that leftover space is handled differently by different operating systemsis there some css property that i am not aware of that will fix thispcmacthis is the very hackish css i used to try and zero it out as best i could keep in mind i have already tried playing with height and lineheight it always is the same problem pc always puts it way below where mac puts iticon fontfamily entypo thisplay inlineblock color 0 fontsize 40px lineheight 0 height 0 verticalalign middle for the sake of those images above to demo to you guys these are the properties i addedheight 20px width 20px background red only to demonstrate how it renders so differently,"['html', 'css']" +370168,why is ie 10 refusing to send post data via jquery ajax both in my development and production environment ie 10 is refusing to send any post data via a simple ajax callmy script looks like thisd testvarsomethingajax data d success functionh consolelogh the actual ajax request is going through but no post datathe request headers look normalrequest post stepsdo http11accept contenttype applicationxwformurlencoded charsetutf8xrequestedwith xmlhttprequestreferer httplocalhost8080stepsacceptlanguage engbenauq07enq03acceptencoding gzip deflateuseragent mozilla50 compatible msie 100 windows nt 62 wow64 trident60host localhost8080contentlength 0dnt 1connection keepalivecachecontrol nocachebut the request body is empty i am using ies network tab in their f12 dev bar to capture requests in the php script print r post returns an empty arraythis works fine in ie 7 9 chrome ff and safari but breaks in ie10i am not sure if i have missed something or if ie 10 is just buggyediti have set the global ajax settings as followsajaxsetup url rootdo root is either httplocalhostdo or httpswstepsorgaudo depending on production or development environment type postfurther editusing ie version 100920016384 on windows 8 pro 64 bitdirect copypaste of request headers arekey valueaccept acceptencoding gzip deflateacceptlanguage engbenauq07enq03cachecontrol nocacheconnection keepalivecontentlength 0contenttype applicationxwformurlencoded charsetutf8cookie utma9194952819477027691348201656135321251013532379556 utmz91949528134820165611utmcsrlocalhostutmccnreferralutmcmdreferralutmcctcoconutoilorgau utmb919495282101353237955 utmc91949528 cartid8b3b2b9187cfb1aeabd071d6ec86b phpsessidbl57l7fp0h37au7g0em7i3uv13dnt 1host wstepsorgaureferer request post do http11useragent mozilla50 compatible msie 100 windows nt 62 wow64 trident60xrequestedwith xmlhttprequestthe request body is emtpyreponse headerskey valueresponse http11 200 okserver nginx0765date sun 18 nov 2012 112335 gmtcontenttype texthtmltransferencoding chunkedconnection closexpoweredby php5351ubuntu72ppa1lucidexpires thu 19 nov 1981 085200 gmtcachecontrol nostore nocache mustrevalidate postcheck0 precheck0pragma nocacheinitiatorproperty valuestage document processingelement xmlhttprequestaction processingdocument id 0frame id 0frame url page which replicates the problem the entire site actuallysteps to life shop health products,['jquery'] +370198,how to make a page with header and leftsidebar i would like to make a webpage like this header l e f t s content area i d e b a r the header has a fixed height but it is width should be dynamic the leftsidebar should have a fixed width but a dynamic height for the content area both height and width are dynamic when user scale their browser the scrolling bar should not appearnot set overflowhidden to hide iti tried to write code like thisdiv classtop topdivdiv classleft leftdivdiv classmain maindivwith csstop width 100 height 92pxleft width 178px height 100 floatleftmain float left height 100 width 100 but it failedis there any solution for thisthanks in advancededit content area and leftsidebar must fill the whole browser windowi do not need header l e f t s content area i d e b a r,"['html', 'css']" +370211,async wcf client calls with custom headers this operationcontextscope is being thisposed out of order i am calling a wcf service from a winrt app the service requires that some headers are set for the authentication the problem is that if i do multiple calls to the service simultaneously i get the following exception this operationcontextscope is being thisposed out of orderthe current code looks like the followingpublic async taskresult callserverasync var address new endpointaddressurl var client new adminserviceclientendpointconfig address using new operationcontextscopeclientinnerchannel operationcontextcurrentoutgoingmessagepropertieshttprequestmessagepropertyname getheader var request new myrequest context context var result await clientgetdatafromserverasyncrequest i found the following comment from the docsdo not use the asynchronous aawaita pattern within a operationcontextscope block when the continuation occurs it may run on a different thread and operationcontextscope is thread specific if you need to call aawaita for an async call use it outside of the operationcontextscope blockso it seems i am clearly calling the service incorrectly but what is the correct way,['c#'] +370220,using cmd to perform method on main thread in objective c i came across this cmd trickvoidmethodtoberunonmainthreadwithobjidobject if nsthread ismainthread self performselectoronmainthread cmd withobjectobject else method body is this a reliable way to ensure a method is performed on the main thread,"['objective-c', 'ios']" +370258,android jellybean network media issue i have an application that is playing mp3 files that are available at a public url unfortunately the server does not support streaming but the android makes the user experience quite acceptable it all works fine for all platforms except for jellybean when requesting the mp3 jb requests for a rangeheader for 10 times only after the 10th attempt it seems to revert to the old behavior looks like this already reported issue i found another so thread where a solution recommended is to use tranferencoding chunked header but just below there is a comment that this does not workfor the moment i have no control whatsoever to deliver above response headers but until i will be able to do that i thought to search for an alternative at client side even so i can only return a contentrange that contains indexes from 0 to contentlength 1 ex contentrange bytes 031234563123457what i tried to do is to implement a pseudostreaming at client side byopen an input stream to the mp3decode the incoming bytes using jlayer i found the decoding at this linksend the decoded array bytes to an already playeable stream mode audiotrackthe piece of code that does the decoding can be found there i have only modified it so it will receive an inputstreampublic byte decodeinputstream inputstream int startms int maxms throws ioexception bytearrayoutputstream outstream new bytearrayoutputstream1024 float totalms 0 boolean seeking true try bitstream bitstream new bitstreaminputstream decoder decoder new decoder boolean done false while done header frameheader bitstreamreadframe if frameheader null done true else totalms frameheaderms per frame if totalms startms seeking false if seeking loggerdebughandling header frameheaderlayer string samplebuffer output samplebuffer decoderdecodeframeframeheader bitstream if outputgetsamplefrequency 44100 outputgetchannelcount 2 throw new illegalargumentexceptionmono or non44100 mp3 not supported short pcm outputgetbuffer for short s pcm outstreamwrites 0xff outstreamwrites 8 0xff if totalms startms maxms done true bitstreamcloseframe return outstreamtobytearray catch bitstreamexception e throw new ioexceptionbitstream error e catch decoderexception e throw new ioexceptiondecoder error e i am requesting the decoded bytes in time chunks starting with 0 50 so i will have a bigger array to play at first then i am requesting the next byte arrays that span over a second 50 10 60 10 70 10 etcthe decoding is fast enough and is done in another thread and once a decoded byte array is available i am using a blocking queue to write it to the audiotrack that is playing in another threadthe problem is that the playback is not smooth as the chunks are not continuous in a track each chunk is continuous but added in the audiotrack results in a sloppy playbackto wrap upif you have bumped into this jellybean issue how did you solve itif any of you tried my approach what am i doing wrong in above code if this is the solution you used i can publish the rest of the codethanks,['android'] +370261,collectionviewviewforsupplementaryelementofkindatindexpath called only with uicollectionelementkindsectionheader i have a collection view and i would like each section to have both a header and a footer i am using the default flow layouti have my own subclasses of uicollectionreusableview and i register each for both the header and the footer in the viewdidload method of my view controlleri have implemented the method collectionviewviewforsupplementaryelementofkindatindexpath but for each section it is only called with kind being uicollectionelementkindsectionheader therefore my footer is not even createdany ideas why this happens,['ios'] +370266,gpuimage equivalent of cvfindcontours my app uses opencvs cvfindcontours on a binary image i now need to make it realtime gpuimage has a cannyedge filter but i could not find anything related to findcontours does gpuimage have anything that closely resembles findcontours if not can someone suggest an alternativethanks,['objective-c'] +370279,mysql date show results todayyesterdayweek i am retrieving data from a table and show the total sum of entries what i want to do is to show the total sum of entries made on todays date yesterday and this month the table is using the unix timestamp format eg 1351771856 for examplecurrently i am using this line to show todays resultsand comment date unix timestamp 24 3600but that gives me just the entries for the last 24 hours example so let us say its friday 1700 pm it gives me the count from thursday 1700 pm to friday 1700 pm what i want is to get the results forthursday 0 235959 yesterday in this case the results for today 0 235959and last week results that start on monday 0 until today in this case fridayi could not find a way in the mysql documentation to achieve this,"['php', 'mysql']" +370336,android howto send requests to the google api when a user pauses typing i am working on this app where users can enter a location in an autocompletetextview and it will suggest locations based on the google places api as is described herehowever i would like to restrict the amount of request send by the app by only sending requests if the user stops typing for a certain amount of time does anyone know how to do this,['android'] +370393,get number of rows with pdo i have a simple pdo prepared query result dbprepareselect id course from coursescompleted where personp result bindparamp q pdoparam int resultexecute rows resultfetchpdofetch num echo rows0the echo seems to be returning the id value of the record not the number of records returned by the queryany idea or explanation for this has me confusedthanks as always,['mysql'] +370400,phonegap deviceready not firing using cordova 220 in ios i am building a phonegap app unfortunately when deploying to ios devices and simulators the deviceready event never fires i am using phonegap 220when i deploy the same code to android using the androidspecific cordovajs file of course the app will work perfectlywhen i replace the deviceready with a jqueryready the app will load on ios as well yet it will then lack access to the device specific apisthe cordovajs is loaded as i will see a simple alert message that i put inside of it yet deviceready never fires and the apis are never exposedmy htmls headscript typetextjavascript charsetutf8 srcjscordovajsscript yes it is the ios version script srcjsjquery182minjsscriptscript srcjsappjsscriptmy jsfunction dostuffapp functionalitydocumentaddeventlistenerdeviceready dostuff falsebut somehow stuff will only get done on android,"['javascript', 'jquery', 'ios']" +370402,mysql subtracting value from previous row group by i need to have the consumption value base on previous one by sn numberthis is my datatable energylogsn date value2380 20121030 001551 21012380 20121031 003103 22042380 20121101 001602 22652380 20121102 001532 231120100 20121030 001538 352120100 20121031 001548 370720100 20121101 001549 381720100 20121102 001519 389720103 20121030 102734 579820103 20121031 122442 6083this is the result i needsn date value consumption2380 20121030 001551 2101 02380 20121031 003103 2204 1032380 20121101 001602 2265 0612380 20121102 001532 2311 04620100 20121030 001538 3521 020100 20121031 001548 3707 18620100 20121101 001549 3817 1120100 20121102 001519 3897 0820103 20121030 102734 5798 020103 20121031 122442 6083 285,"['mysql', 'sql']" +370454,adding httpclient headers generates a formatexception with some values this occurred within the context of coding against google cloud messaging but applies elsewhereconsider the followingvar http new httpclienthttpdefaultrequestheadersauthorization new authenticationheadervaluekeyxandvar http new httpclienthttpdefaultrequestheadersaddauthorization keyxboth of which generate a formatexceptionsystemformatexception the format of value keyx is invalidthe solution is to remove the equals signdigging into reflector shows there is oodles of validation and parsing code that runs when adding a a new header value why is all this necessary should not this client just be getting out of our wayhow do you escape the equals sign so that adding this value succeeds,['c#'] +370505,how can i link with or work around two thirdparty static libraries that define the same symbols i cannot be the only one to run into thisi have a c application that needs to link with one thirdparty and another static library set in an sdk the sdk has for some hideously frustrating reason recompiled a subset of that same thirdparty library into their own renamed lib although the symbols themselves are named the same and they are not encapsulated within a namespace my application itself depends upon the same thirdparty libraryi have considered a few options but maybe i am missing something and hopefully a fresh look will help me out perhaps i am close and someone will know the next step for one of these i will enumerate what i have tried and the shortcomings of each solution so farlink with bothi get about 2500 lines of symbol redefinition size change warnings and errors this is when i first found that they defined the same symbols i am trying to recompile openssl with g and drop it into a namespace at the momentsee edit belowlink with the sdk onlyi get undefined symbols that my own code depends upon this is when i found that their recompile of the third party lib is a subset or at least was configured with one module thisabledlink with the third party lib onlyi have a couple of undefined symbols reported by the sdk one of them is actually a define in a header file within the third party lib so all references in the third party lib resolve to the definition but references outside there do not i moved that into the c file which resolves that however i still have two unresolved functions i cannot find anywhere this is the closest i have gotten so farstrip conflicting symbols from one lib and link in bothso far this has not worked it could be a version issue between the lib statically linked in the sdk and the versions i have tried using of the thirdparty lib but it looks like some functions were moved between symbols so by removing a symbol i inadvertently remove a function that i need elsewhere there does not seem to be a perfect mapping between functions in symbols in the sdk vs functions in symbols in the thirdparty lib is it plausible to strip functions without having to manually adjust addressesi have been examining symbols in libs withnm c definedonly libnameaand extracting entire objects withar x libnamea objnameohopefully this will also help others who have had to link with thirdparty libs that conflict with one another for the sake of specifics the thirdparty lib is openssl and the sdk is opsec libcpopenssla is the offending lib in opsecedit a late entry possible workaround may be to recompile openssl with g and put the whole thing in a namespace and then link both libs i am trying that nowmore to come,"['c++', 'c']" +370539,getting herokus config vars to work in nodejs i have a node app that has a line like thisvar ip processenvip httplocalhosti am using it with passportfacebook node package to define the callback from facebook authenticationpassportusenew facebookstrategyclientid facebook app idclientsecret facebook app secretcallbackurl ip port authfacebookcallback functionaccesstoken refreshtoken profile done asynchronous verification for effect processnexttickfunction return donenull profile it seems that heroku does not know processenvip so i went ahead and defined a config var in herokuheroku configadd processenvipdebugging the server i see that ip is not what i want but it is httplocalhost same as i defined as the fallback in the first line of codehow do i get node to read the config var correctly from heroku,['javascript'] +370552,how to get custom annotation attributes for a controller action in aspnet mvc 4 i am working with a permission based authorization system for my app in aspnet mvc for this i have created a custom authorization attributepublic class myauthorizationattribute authorizeattribute string roles get set string permission get setso that i can authorize a user by both role or a specific permission key with annotation for actions likepublic class usercontroller controller myauthorizationrolesadmin permissionsuser add public actionresult add myauthorizationrolesadmin permissionsuser edit public actionresult edit myauthorizationrolesadmin permissionsuser delete public actionresult deletethen i override authorizecore method in myauthorizationattribute class with similar logicpseudo codeprotected override bool authorizecorehttpcontextbase httpcontext ifuser not authenticated return false ifuser has any role of roles return true ifuser has any permission of permissions return true return falseup to this is working fine now i need some sort of extension methods so that i can dynamically generate action url in view pages that will return action url based on myauthorization attribute authorization logic for the given action likeurlmyauthorizedactionadd userwill return url to useradd if user has admin role or has permission of user add as defined in attributes for the action or return empty string otherwisebut after searching in internet for few days i could not figure it out so far i have found only this security aware action link which works by executing all action filters for the action until it failsit is nice but i think it would be an overhead to execute all the action filters for each time i call the myauthorizedaction method besides it also did not work with my version mvc 4 and net 45what all i need is to check authenticated users role permissions will be stored in session against authorized role and permission for the given action like something as following pseudo codemyauthorizedactionstring actionname string controllername actionobject action someunknownclassgetactionactionname controllername myauthorizationattribute attr actionreturnsannationattributes ifuser roles contains any in attrroles or user permissions contains any attrpermissions return url to action return empty stringi am searching the solution of getting action attributes value for quite a long time could not find enough good resources at all am i missing out right keywords if anyone can provide me the solution that would be truly a great helpthanks in advance for the solutions,['c#'] +370565,can jtableheader span over multiple columns i have spent quite some time searching for this and i have only found the groupableheader code i need one header over 2 columns in a 2 column jtable how can this be done without the use of the infamous groupableheader while keeping the default look and feel of the jtableheaderthis is a graphical representations of what i have in mind table header,['java'] +370567,how do you move the legal sign in mapview i wonder if anyone know how you move the legal sign on a mapview right now my toolbar is covering it does anyone know how there is lots of help with the google logo but nothing on the apple maps,['objective-c'] +370586,moq interop types works in vs2012 fails in vs2010 i have a net library project with about 500 unit tests all these tests run fine in visual studio 2012 however some of my tests fail in visual studio 2010 in these failing tests i use moq to mock several interop types from microsoftofficeinteropexcel the test fails immediately when attempting to access these mocked interop typeserror missing method instance class microsoftofficeinteropexcelrange exceladdincore microsoftofficeinteropexcellistrowget range from class castleproxieslistrowproxythis exception implies that i forgot to setup the appropriate property getter on my mock which is not the case listrowmocksetupm mrangereturns rangemockobjectnow i can imagine that moq might not work too well with interop types but what i find most puzzling is that these tests run fine in visual studio 2012 but fail in visual studio 2010 why is my visual studio influencing the behavior of my codeupdate 3112012ok so i got it down to thisi have two projects core and coreunittest core is the actual library while coreunittest is a unit test project of the core libraryboth projects reference microsoftofficeinteropexcel with embed interop types enabledbecause eit is enabled both projects include their own view of the microsoftofficeinteropexcel library the view includes all classes methods and properties that are used in their respective projectbecause both projects use different classes methods and properties of the microsoftofficeinteropexcel the embedded types of both libraries differ eg listrow in core has an index and range property whereas listrow in coreunittest only has the range propertyalthough both types are different and do not share a common interface or super class they are equivalent this means that the clr will treat them as if they are the same and will allow you to use these types across assembly boundaries eg an instance of listrow from coreunittest will work fine when passed to a method in the core library the shared range property will function whereas the missing index property will throw a missingmethodexception on accessthe aforementioned behavior even works with mocked types an mocked object of mockexcellistrow will work fine when crossing the assembly boundaryunfortunately the behavior described in the previous point only works when i build my assemblies in visual studio 2012 when i build my assemblies in visual studio 2010 and debug my code i can see the mocked listrow instance being passed into a method of my core project the moment the instance crosses the assembly boundary all methods and properties of listrow lose their implementation and throw missingmethodexceptionsnow for the fun part i actually managed to mitigate this issue by ensuring that both embedded types of listrow are aligned eg in order for the compiler to create the same view of listrow in both projects i made sure that i used the exact same methods and properties in my unittest project this means adding dummy lines like var dummy listrowindex once i had the compiler creating identical views of my embedded listrow type the instance was allowed to cross assembly boundaries without losing its implementationthe question still remains though what causes this difference in behavior between visual studio 2010 and visual studio 2012update 9112012demo solution i have created a small solution to demonstrate the effect the solution consists of a library and a unittest project both reference microsoftofficeinteropexcelrange with eit enabled the test works fine in vs2012 but throws missingmethodexception in vs2010 uncommenting the dummy line in the test will make it work in vs2010final update 29122012my apologies for the late update a colleague of mine found a solution however i was unable to reproduce it on my machine in the meantime our company has made the switch to tfs2012 so this is no longer a blocking issue for me the two most important conclusions my colleague made werethe semantics of the any cpu platform have changed from visualstudio 2010 to visual studio 2012 this will result in differentdlls being generated depending on whether you are using vs2010 orvs2012 both projects referenced different versions of microsoftofficeinteropexceli checked my projects and straightened out the references but it made no difference after that i tried different variations of platforms in both vs2010 and vs2012 but was unable to produce a satisfactory result i will accept jeremys answer as it was the most helpful thank you all for your assistance,['c#'] +370602,android and sqlite when to use semicolons to end statements if you are using the rawquery or execsql methods of sqlite on android when should you use a semicolon to end your statementon this tutorial for instance the author uses the semicolon on the create table statement via execsql but not on select statement via rawquery for instancecreate table statementprivate static final string database create create table table comments column id integer primary key autoincrement column comment text not nulldatabaseexecsqldatabase createselect statementcursor cursor getreadabledatabase rawqueryselect from todo where id new string id is it the case that statements using the execsql method need a semicolon at the end but statements using the rawquery method do not,['android'] +370647,why does jslint recommend x undefined vs typeof x undefined i am confused with jslintmy code originally checked if divjqmdatame was undefined like soif typeof eljqmdatame undefined elnotjqmdatapanelmainlength 0 elnotjqmdatamefirstlength 0 jslint complains that i should replace checking with typeof with so i did like thisif eljqmdatame undefined elnotjqmdatapanelmainlength 0 elnotjqmdatamefirstlength 0 jslint does not complain anymore but my nested if statement is broken because i am now always ending up with the 2nd if elnotjqmdatamefirstlength even when i should notquestionwhy does jslint recommend over typeof undefined how comes this breaks my logicthanks for some enlightment,"['javascript', 'jquery']" +370674,how to obtain native logger in selenium webdriver is it possible to obtain the logger somehow that selenium webdriver uses i want to capture a transcript of all the commands that were issued eg open wait click etc in particular i am looking for a java solution as i am exporting the tests into juniti found this code on their website however it thisplays nothing on standard out desiredcapabilities caps desiredcapabilitiesfirefox loggingpreferences logs new loggingpreferences logsenablelogtypedriver levelfinest capssetcapabilitycapabilitytypelogging prefs logs driver new firefoxdrivercaps,['java'] +370683,how do i retrieve keystrokes from a custom keyboard on an ios app i need to build a custom keyboard for my iphone app previous questions and answers on the topic have focused on the visual elements of a custom keyboard but i am trying to understand how to retrieve the keystrokes from this keyboardapple provides the inputview mechanism which makes it easy to associate a custom keyboard with an uitextfield or uitextview but they do not provide the functions to send generated keystrokes back to the associated object based on the typical delegation for these objects wed expect three functions one of normal characters one for backspace and one for enter yet no one seems to clearly define these functions or how to use themhow do i build a custom keyboard for my ios app and retrieve keystrokes from it,['ios'] +370684,pipeasy install pil in virtualenv vcvarsallbat error windows 7 so i know there is a fair amount of documentation on this already but i just cannot seem to get it to work i am deploying a django app to heroku and am trying to install pil into my virtualenv a main part of the app requires user uploaded imagesi have tried botheasy install pilandpip install piland everyone the installation ends inerror unable to find vcvarsallbathow can i get pil into my virtualenv can anyone walk me through itthanks,['python'] +370685,rubinus or mri 193 yarv so i have a few questions that i have to ask i did browse the internet but there werent too many reliable answers mostly blog posts that would cancel eachother out because they both praised different things and had benchmarks to prove their viewpoint i have never seen so many contradicting benchmarks in my lifeanyway my questions areis rubinius really faster i was pretty impressed by this apparently honest prorubinius presentation another thing that confuses me a little is that a lot of rubinius is written in ruby itself yet somehow it is faster than cruby it must be a pretty damn good implementation of the language thendoes eventmachine work with ruinius as far as i know eventmachine partially relies on fibers correct me if i am wrong which werent implemented until 19 i know rubinius will eventually support 19 too i do not mind waiting a littledo c extensions work in rubinius i have written a c extension which serializes binary messages received from a tcp stream into ruby objects and viceversa i suppose the details are not important but if it helps answer this question i will update the post this can be a lot of messages i managed to write the same code in ruby although it made little sense after a month but it proved to be a real bottleneck in the application so i had to use c as a solution to my problemedit i just remembered i use c for another task it is a hittest method for arrays basically it just checks if a point is inside an a polygon it was impossibly slow in crubyif the previous answer was a no is there then an alternative for c extensions in rubinus i gather the vm is written in c so that thena few bonus questionswill cruby 20 yarv ever get rid of gil or at least modify it so cruby supports true parallelismwhat is exactly mruby i see matz is working on it and as far as the description goes it seems pretty awesome how different is it from cruby performancewisei apologize for this textstorm i unleashed upon you a,['ruby'] +370727,search filtering with phpmysql im trying to create a search filtering option in my blood donar application where donar can be searched by sexnameblood group or with selecting all here are my codefunction search donar post by name postby name by sex postby sex by group postby group by level postby level search query select from donar where ifby name search query nameby name ifby sex search query sexby sex ifby group search query blood groupby group ifby level search query e levelby level search query result mysql querysearch query return result and here is the htmlifisset postsubmit retrived result donarsearch donar post form action methodpost table width100 border0 stylebordernone tr tdlabelnamenbsplabelinput typetext nameby name td tdlabelsexnbsplabelinput typetext nameby sex td tdlabelblood groupnbsplabelinput typetext nameby group td tdlabellevelnbsplabelinput typetext nameby level td tdinput classbutton typesubmit namesubmit valuesearch td tr table formsingle filtering works very fine but to filter with all i used and but it gives me error can anyone help thanks in advance,"['php', 'mysql']" +370737,what does rests principle of statelessness actually means after reading the introductory articles on rest fieldings thesis and other my perception of statelessness is that there should be no session objects on the server side yet i see flask and maybe other rest frameworks in different technologies that i do not know about gives us a session object to store information on the server in this exampleapproutelogin methodsget postdef login if requestmethod post sessionusername requestformusername return redirecturl forindexsurely i am misunderstanding rests statelessness so what is it really,['python'] +370741,virtualenv env not creating bin directory in windows 7 i am a newbie to python and i have spent hours on this i cannot seem to figure out why when i run a simple command to setup my python environment virtualenv thistribute envthis does not create a bin file in the env directoryit only creates env include lib scriptsmy impressions was that a bin directory would be created per a lot of the examples i have found on the web eg i am not able to run this command envbinactivatei am using windows 7 and python 27,['python'] +370748,permissionerror errno 13 in python just starting to learn some python and i am having an issue as stated belowa file openepython win764amd 33test encodingutf8traceback most recent call last file pyshell9 line 1 in module a file openepython win764amd 33test encodingutf8permissionerror errno 13 permission denied epython win764amd 33testseems to be a file permission error if any one can shine some light it would be greatly appreciatednote not sure how python and windows files work but i am logged in to windows as admin and the folder has admin permissionsi have tried changing exe properties to run as admin,['python'] +370763,custom dropin icons for dmg background for application packaging on macosx i am having trouble adding custom icons for a dmg background in a selfcontained package built on macosx i have added a package in the root directory of my project the custom icon is getting loaded from it but the dmg background icon is not i am using java fx 223 and jdk170 09 here is the verbose output generated for the samedetected javafx ant api version 12 launching fxjar task fromlibraryjavajavavirtualmachinesjdk170 09jdkcontentshomelibantjavafxjarlaunching fxdeploy task fromlibraryjavajavavirtualmachinesjdk170 09jdkcontentshomelibantjavafxjarcopying 102 files tousersapplenetbeansprojectsjavafxapplication2thist using base jdkat libraryjavajavavirtualmachinesjdk170 09jdk using defaultpackage resource bundle config file add packagemacosxinfoplistto the class path to customize using custom package resource iconloaded from fileusersapplenetbeansprojectsjavafxapplication2packagemacosxjavafxapplication2icnscreating app bundleusersapplenetbeansprojectsjavafxapplication2thistbundlesjavafxapplication2appconfig files are saved tovarfoldersvdnyxf14z53tx56g2 lbqcnfrr0gntbuild1722966263281326253fxbundlermacosxuse them to customize package building dmg package forjavafxapplication2 using default package resource bundle configfile add packagemacosxinfoplist to the class path to customizeusing custom package resource icon loaded from fileusersapplenetbeansprojectsjavafxapplication2packagemacosxjavafxapplication2icnsconfig files are saved tovarfoldersvdnyxf14z53tx56g2 lbqcnfrr0gntbuild1722966263281326253fxbundlermacosxuse them to customize package using default package resource dmgbackground add packagemacosxjavafxapplication2backgroundpng tothe class path to customize using custom package resource volumeicon loaded from fileusersapplenetbeansprojectsjavafxapplication2packagemacosxjavafxapplication2icnsusing default package resource script to run after applicationimage is populated addpackagemacosxjavafxapplication2postimagesh to the class path tocustomize using default package resource dmg setup script addpackagemacosxjavafxapplication2dmgsetupscpt to the class pathto customize result dmg installer for javafxapplication2usersapplenetbeansprojectsjavafxapplication2thistbundlesjavafxapplication2dmgconfig files are saved tovarfoldersvdnyxf14z53tx56g2 lbqcnfrr0gntbuild1722966263281326253fxbundlermacosxuse them to customize packagehere is the directory where all my icon files are listedapplesmacbookpro2 apple ls l usersapplenetbeansprojectsjavafxapplication2packagemacosxtotal 136rwrr 1 apple staff 1251 nov 1 1902 infoplistrwrr 1 apple staff 18017 nov 1 1822 javafxapplication2backgroundpngrwrr 1 apple staff 902 nov 2 1355 javafxapplication2dmgsetupscptrwrr 1 apple staff 38115 jan 19 2006 javafxapplication2icnsas you can see the icon gets loaded from the package but the dmg background file is not even though i have added that file in the same directory as well,['java'] +370772,symfony 2 forms embedding collection in embedded collection i have a data structure where a topic has many questions one to many and a question has many answers one to manyi have set up questions as an embedded collection in the topic form and i have it all working 100 thanks to the cookbook entrywhen i try to develop this to embed a collection of answer forms in the question form then i run in to a problemthe dataprototype attribute that contains the prototype form at the top level has the full depth of form in it so includes the prototype for both question and answer but it uses the same placeholder name for each leveldiv idtopic questions name div classcontrolgroup label fortopic questions name questiontext classcontrollabelquestionlabel div classformrowerrorsdiv div classcontrols textarea idtopic questions name questiontext nametopicquestions name questiontext requiredrequired classinputblockleveltextarea divdivdiv classcontrolgroup label classcontrollabelanswerslabel div classcontrols div idtopic questions name answers dataprototypeltdiv classquotcontrolgroupquotgtltlabel classquotcontrollabelquotgt name label ltlabelgtltdiv classquotcontrolsquotgtltdiv idquottopic questions name answers name quotgtltdiv classquotcontrolgroupquotgtltlabel forquottopic questions name answers name answertextquot classquotcontrollabelquotgtoptionltlabelgtltdiv classquotformrowerrorsquotgtltdivgtltdiv classquotcontrolsquotgtltinput typequottextquot idquottopic questions name answers name answertextquot namequottopicquestions name answers name answertextquot requiredquotrequiredquot maxlengthquot255quot gtltdivgtltdivgtltinput typequothiddenquot idquottopic questions name answers name sortorderquot namequottopicquestions name answers name sortorderquot gtltdivgtltdivgtltdivgtdiv divdivyou can see the really long line at the bottom which i guess is the prototypeprototype for the answer form there is no way that i can see to only replace the question related name placeholders and not the answer related ones doing the normalvar newform prototypereplace name g collectionholderchildrenlengthwhen creating a real instance of a question form of course replaces all instances of name with the same value so when the dataprototype is created for the answer form it has already had all the placeholders replacedthis is what the dataprototype looks like for the answer form when i have clicked to add a real question formdiv classcontrolgrouplabel classcontrollabel1label labeldiv classcontrols div idtopic questions 1 answers 1 div classcontrolgroup label fortopic questions 1 answers 1 answertext classcontrollabeloptionlabel div classformrowerrorsdiv div classcontrols input typetext idtopic questions 1 answers 1 answertext nametopicquestions1answers1answertext requiredrequired maxlength255 div div divdivas you can see the name placeholder doesnt feature at all it was already replaced with the count for the question form when the question form was createdis it possible to achieve this kind of multiple depth embedded collection with the mechanism symfony providesas long as it tries to use the same placeholder for each level then i can not see how,['php'] +370789,how to prevent a system call from being executed with ptrace i am working on a ideonelike system where untrusted user code must run in sandboxed mode for this i have been looking the possibilities of ptrace for a first layer of protection however after a few experiments it seems thati can intercept a system call before it is called and modify the input argumentsi can intercept a system call after it has been called and change the return valuehowever there seems to be no way to prevent the call from happing at all except for killing the entire applicationi want to intercept certain system calls and return a fake result code without the call actually happening is there a way to implement this,"['c++', 'c']" +370829,what is the alternative for deprecated canvasgetmatrix i have the following code snippet that transforms a set of bounds using the canvas current transformation matrix final rectf bounds renderercomputebounds activecanvasgetmatrixmaprectresult bounds return boundshowever with the latest api level 16 i get a warning statingthe method getmatrix from the type canvas is deprecatedas confirmed by the api 16 diff specification which is fine and all but the current documentation on canvasgetmatrix does not mention the deprecation nor does it offer an alternative as a workaround i now simply suppress this warning but i would really like to know what the new and improved tm way of doing this looks like,['android'] +370830,how to get sms list as convesations in every android device 22 i need to get list of text messages and thisplay them like in stock aplication or go sms pro i am using following codeurisms uriparsecontentmmssmsconversations cursor cursor getcontentresolverqueryurisms new string null null date desc cursormovetofirst do try string address cursorgetstring32 ifaddress null address phone number else address getcontactnameaddress string body cursorgetstring2 systemoutprintln mobile number address systemoutprintln sms text body catch exception e eprintstacktrace whilecursormovetonextit works on my galaxy tab android 22 but on my s3 ics application crashes at start i do not want to parse mms so i tried using urisms uriparsecontentsmsconversationsbut it did not work on both devices i googled a lot to find a solution and i found nothing i have only thiscovered that access to sms conversations depends on android os and device my purpose is to make application which support every android device 22 in stock application they using threadcontent uri to get sms list as conversations egthreadscontent uribuilduponappendqueryparametersimple truebuildbut class thread is not provided with source code and i cannot find it in internetwhat can i do to make my application run on every android device 22 just like handcent sms or go sms pro,['android'] +370945,is locationprotocol ever invalid i want to construct urls with the same scheme presumably http or https as the page that loaded the currentlyrunning javascript modern browsers support simply omitting the scheme for example srcexamplecomtestjs but this is not fully crossbrowser compatible i have read that ie 6 is the only browser that does not support it but i still need compatibility with that versionthe crossbrowser way to do this seems to be to check locationprotocol for example google analytics useshttps documentlocationprotocol httpsl httpw in googles case they wanted to use different domains depending on whether the request uses ssl so that pattern makes sense but i have seen others use the same pattern even when only the protocol is differenthttps locationprotocol https http examplecomone example is in the final wufoo snippet at i would prefer to use this simpler expression insteadlocationprotocol examplecomshould i really be concerned about the possibility of locationprotocol taking on some value other than https or http when my code is used on sites i do not control,['javascript'] +370946,difference between variable reference and name i am studying reference of c and now i am quite confused by the difference between variable name and reference the test code is belowclass testclassprivate int numpublic testclassint nnumn coutthis init of thisnumendl testclassconst testclass tnumtnum coutthis copyinit of thisnumendl int mainint argc const char argv testclass t new testclass55 just to test copy initialization const testclass t2 testclass100 option1 const testclass t2 testclass100 option2so now i have two options in making object which are exclusive with each other in my understanding if i use options2 the compiler makes a temporary object in the stack memory and returns the reference value to t2 if this is right how can i verbalize or explain the option1 it seems that the same object is created in the stack memory and computer gives a name t2 to that object but i do not clearly understand how this option1 is different with the option2 because a name of variables and reference are somewhat confusing in addition switching options alternatively i could see that the objects are created in different memory locations in each case eg the object of option1 was created in 0x7f5fbff828 and that or option2 was in 0x7f5fbff820could you please explain 1 whats the difference between a variable nameoption1 and referenceoption22 how things work differently in option 1 and 23 why objects are created in different memory location in either casesin advance thanks for your help,['c++'] +370953,msoffice mime type verification i have the followingmimetypes arrayapplicationmsword used to be an arrayfinfo new finfofileinfo mime usrsharemiscmagic type finfofile filesuserfiletmp namemime substrtype 0 strpostype if in arraymime mimetypes let it inthe problem is that i am getting applicationvndmsoffice as the filetype for any msoffice file that i attempt to upload i do not wish to allow all msoffice files only docs is there a workaround for this please note that these msoffice type files were created in openoffice would this make a difference,['php'] +370956,lesscss multiple class selectors with keyword say have a less sheet with a large number of multiple css rules to manage iconographysomething like soicon thisplayinlineblock positionrelative textindent9emiconllegend width24px height24pxiconwhitelegend backgroundurlicon legend white norepeaticonlarrow leftbackgroundposition 128px 32pxand apply rules like this as suchi classicon iconl iconcolor legend arrow leftithis works fine when i have access to markup as one would expect but i am having a hard time applying these rules via less to a given elementheres what i would expect to worksomething icon iconllegend iconwhitelegend iconlarrow leftwhich just throws an errori am led to believe that the operator can apply rules like sosomething icon iconllegend iconwhitelegend iconlarrow leftthis throws no error but only the rules for icon are getting applied anyone have a solutionupdatefyi i am compiling several less files together for many different unique sheets works really wellsublimetext2 plugin works reasonably well and integrates really well into the workflow need to build the file but could not render multiple classes like thissimpless is a nice standalone that i like alot except that i kept getting errors compiling my less stack without clear reference to the error locationwinless manages to complete all my compiling needs as well as successfully compiling multiple classes like this also its error reporting is very specific making it the winner,"['html', 'css']" +371010,mac osx attributeerror figurecanvasmac object has no attribute restore region walking through matplotlibs animation example on my mac osx machine animhtml i am getting this errorfile libraryframeworkspythonframeworkversions27libpython27sitepackagesmatplotlibanimationpy line 248 in blit clear afigurecanvasrestore regionbg cacheaattributeerror figurecanvasmac object has no attribute restore regiondoes anyone who has encountered this before know how to resolve this issuelooks like it is a known and unresolved at this time of writing issue,['python'] +371037,logging flask errors with mod wsgi i have been trying to get this working since a long time but i am really at my wits end now i have tried to do everything that i could find on so and flask documentation and still i cant a simple error log working so that i can debug my applcation below is the pasted code mainpyfrom flask import flaskimport loggingapp flask name file handler loggingfilehandlerfilenametmpelection errorlogfile handlersetlevelloggingwarningapploggeraddhandlerfile handlerapproutedef hello return hello missing quotes to generate errorif name main apprunwsgi fileimport sysimport loggingsyspathinsert0 varwvoting apploggingbasicconfigstreamsysstderrfrom main import app as application apache2 conf filewsgidaemonprocess voting app threads5wsgiscriptalias election varwvoting appvoting appwsgiloglevel infodirectory varwvoting app wsgiprocessgroup voting app wsgiapplicationgroup global order denyallow allow from alldirectoryplease tell me where i am going wrong thank you so much,['python'] +371041,if exists condition not working with plsql i am trying to print the text when condition is true the select code is perfectly working fine it is showing 403 value when i only run select code but i have to print some text when condition exists whats the problem with following codebeginif existsselect ces regno fromcourseoffering cojoin co enrolment ce on ceco id coco idwhere ces regno403 and cecoe completionstatus c and coc id 803then dbms outputput lineyes you canendhere is the error reporterror reportora06550 line 5 column 1pls00103 encountered the symbol join when expecting one of the following with group having intersect minus start union where connect06550 0 line s column snscause usually a plsql compilation erroraction,['sql'] +371058,angular js textarea validation i have this angularjs code trying to show two stars next to label when there is no text in the textarea same code works for input tags but not with textareadiv classinputleft label foremail span ngshowcontactformemailerrorrequired classrequiredspanemail label input ngmodelemail typetext nameemail idemail requiredbrbr label forbudgetbudzetlabel input ngmodelbudget typetext namebudget idbudgetdivdiv classclearboth label formsg classleft span ngshowcontactformmsgerrorrequired classrequiredspanpitanja ili komentari label textarea ngmodelmsg rows8 cols50 classinputnowidth rounded shaded left clearboth idmsg requiredtextareadivaccording to angularjs documentation textarea should behave same as input,['javascript'] +371069,d with ef code first how to put them together i am learning d development for few days and i start to like iti think i understand the principle of d where your main focus is on business objects where you have aggregates aggregates roots repositories just for aggregates roots and so oni am trying to create a simple project where i combine d development with code first approachmy questions are i am using aspnet mvcd business objects will be different than code first objectseven if they will probably be the same for example i can have a product business object which has all the rules and methods and i can have a product code first poco object which will just contain the properties i need to save in databaseif answer to question 1 is true then how do i notify the product poco object that a property from business object product has been changed and i have to update it i am using an automapper or something like thisif the answer is no i am completely lostcan you show me the most simple crud example of how can i put those two togetherthank you,['c#'] +371115,argparse get undefined number of arguments i am building a script which uses arguments to configure the behavior and shall read an undefined number of files using the following code allows me to read one single file is there any way to accomplish that without having to set another argument telling how many files the script should readparser argparseargumentparserparseradd argumentfile helpfile to store as gistparseradd argumentp private actionstore true helpmake gist private,['python'] +371133,latest adt and sdk tools installed but still asking for latest sdk tools i have just installed eclipse juno and installed the adt plugin 2003 but i am still getting this message on every eclipse launch saying this version of adt requires android sdk tools in revision 20 or abovecurrent revision is 1800please upgrade your sdk to latest versionthe sdk tools i pointed to in preferences are up to date because tomorrow i was working on eclipse indigowhich also had adt 2003 installed and had all the sdk tools updatedi just pointed the same sdk folder in junoplease help thank you,['android'] +371146,strange semantic error i have reinstalled emacs 24250 on a new linux host and started a new dotemacs config based on magnars emacs configuration since i have used cedet to some success in my previous workflow i started configuring it however there is some strange behaviour whenever i load a c source file this part is solvedas expected semantic parses all included files and during the initial setup parses all files specified by the semanticaddsysteminclude variables but it prints this an error message that goes like this warning semanticfindfilenoselect called for usrincludec47vector while in setautomode for usrincludec47vector you should call the responsible function into modelocalinithookin the above example the error is printed for the stl vector but a corresponding error message is printed for every file included by the one i am visiting and any subsequent includes as a result it takes quite a long time to finish and unfortunately the process is repeated any type i open a new buffer this problem is solved toofurthermore it looks like the parsing does not really work as when i place the point above a nonc primitive type ie not intdoublefloat etc instead of printing the types definition in the modeline an error message like idle service error semanticidlelocalsymbolhighlightidlefunction buffer depfetresolutionanalysiscc wrong type argument stringp 0 indexmapidle service error semanticidlesummaryidlefunction buffer depfetresolutionanalysiscc wrong type argument stringp fxbetween 0 nil nilwhere depfetresolutionanalysiscc is the file buffer i am currently editing and indexmap and fxbetween are types defined in files included by the file i am editingsome file included by the file i am editing i have not tested any further features of cedetsemantic as the problem is pretty annoying my cedet config can be found hereedit with the help of alex ott i kinda solved the first problem it was due to my horrible cedet initialisation see his first answer for the proper way to configure cedetthere still remains the problem with the idle service error which when enabling globalsemanticidlelocalsymbolhighlightmode occurs permanently not only when checking the definition of the type at pointand there is the new problem of how to thisable the sitewise init files edit2 i have executed semanticdebugidlefunction in a buffer where the problem occurs and it produces a 700kb sic output it looks like it is performing some operations on a data container which by the looks of it contains information on all the symbols defined in the files parsed as i have parsed a rather large package 20mb source files this table is rather large can semantic handle a database that large or is this impossible and the reason of my problem edit3 deleting the content of semanticdb and reparsing all includes did the trick i still need to thisable the sitewise init files but as this is not related to cedet i will close this question the question related to the sitewise init files can be found here,['c++'] +371158,jquery detect css backgroundimage finish download i am trying to download an image then apply a fade using css backgroundimagei can accomplish this when it is a regular img src like so mainimg thisplaynonevar c mainimgnew imageloadfunction cfadein300attrsrc cattrsrcbut how can i detect it when it is a css backgroundheres css using jquery but i cant seem to get it like the code above and detect when the download is finishedimgattrsrc imagepngloadfunction mainimgcssbackgroundimage urlimagepngedit this helped outhow can i check if a background image is loadedthank you colin,"['jquery', 'css']" +371198,how to revoke the permission that my app get from users google gmail accountmanagergetauthtoken created a test app using eclipse to get the authtoken from one of my google email accounts on my deviceexecuting this prompted me with the allow access dialog where i press allow access accountmanagergetauthtokenaccountoauth2 false new getauthtokencallback nulli wanted to create a chooser dialog that works from api8 and up where the user can choosewhat google account he allow me to access to do this i have to revoke the permission to see the screen again should i see my test app on this page or notauthorized access to your google accounti have search for a way to revoke the permission and non is workingonly thing working is to create a new app project update 2013using the google play service gcm and this is working ok,['android'] +371208,how can i send an excel file by email i have an excel file excel 2003 xls format and i want to send it by email with cmy code send it successfully but when i try to open the response file it seems to encoded wronglyfor example here is the response filename utf8 b rwxzesohbw9sw6fzxziwmtjfmtbfmtzfdatand here is the response file itselfutf8bvedwdmjiwmhjmkz1wk1pelh6uxlyekzmpz0ncia9p3v0zi04p0ivgtw utf8btlgwzfrxatu0ykhnpt89 contenttransferencoding base64 contentthisposition attachment0m8r4kgxgueapgadap7cqagaba aqaeaiwaeadad here is my code fragmentvar attachment new attachmentwritefiletomemoryfilefullpath filenamexlsattachmentcontenttype new contenttypeapplicationvndmsexcelattachmentcollectionaddattachmentprivate stream writefiletomemorystring filepath var memorystream new memorystream openedstreamsaddmemorystream using var file new filestreamfilepath filemodeopen fileaccessread var bytes new bytefilelength filereadbytes 0 int filelength memorystreamwritebytes 0 int filelength fileclose memorystreamposition 0 return memorystreamhow can i set the attachment encoding type and which encoding should i use with excel filesplease help me solve this problemthanks in advance,['c#'] +371229,dart javascript interop callbacks with jquery how can i translate the following jquery code to dart i am having difficulty getting the alert callback to work using jsinteropscript srcscriptscript function phideslow function alertthe paragraph is now hidden scriptany help is appreciated,['javascript'] +371237,uicollectionview registercell blank cells i have just starting playing around with uicollectionview for the first time seems to work nicely but having an issue and a question about iti have my uicollectionview setup as below and with a custom cell nsintegercollectionviewuicollectionview view numberofitemsinsectionnsintegersection return 10 nsintegernumberofsectionsincollectionview uicollectionview collectionview return 1 uicollectionviewcell collectionviewuicollectionview cv cellforitematindexpathnsindexpath indexpath contactcell cell cv dequeuereusablecellwithreuseidentifiercell forindexpathindexpath cellnamelbltext text return cell cgsizecollectionviewuicollectionview collectionview layoutuicollectionviewlayoutcollectionviewlayout sizeforitematindexpathnsindexpath indexpath return cgsizemake145 95 uiedgeinsetscollectionviewuicollectionview collectionview layoutuicollectionviewlayoutcollectionviewlayout insetforsectionatindexnsintegersection return uiedgeinsetsmake10 10 10 10so this is all dandy however i have added this line to viewdidloadcollectionview registerclasscontactcell class forcellwithreuseidentifiercellthis is causing trouble and i do not understand why when i enable this line all of my cells go blank how come what am i missingalso as i understand it if that line enables reusable cells why do i have to with a collection view vs not having to in a table viewany technical or explanatory help appreciatedthanks,"['iphone', 'objective-c']" +371252,the this keyword returns the window object within an objects prototype in javascript i have the following function in a classmyclassprototypemyfunction functionitem args consolelogthisthis function is called from an external library that i do not have access to change when it is called the console is logging this as the window object instead of the actual instanced object upon searching stackoverflow i found this quotethis is set according to how the method is called and not according to how the method is written so for objmethod this will be set to obj inside of method for objmethodcallx this inside of method will be set to x it is determined by how it is called what that also means is that if you pass it as a callback to eg onclick this will be set to the global window object rather than what you expecti am assuming this is what is going on and i cannot change the way it is called my question is is there anyway then to get the instance of the object its in regardless of how it is called,['javascript'] +371255,suggested protocol for androidarduino communication using the android open accessory standard i have an android powered device talking back and forth with an arduino mega adk microcontroller hooked up via usb i would like to know what the best communication protocol is at the data link layer levelfrom the android arduino sides it is simple file based io eg writebuffer buffer length readbuffer buffer length doing some research i came across this link entitled simple serial pointtopoint communication protocol that recommends using the hdlc protocol would that be a good protocol to run with or is there something betterthank you,['android'] +371301,django defaulttimezonenow saves records using old time this issue has been occurring on and off for a few weeks now and it is unlike any that has come up with my project two of the models that are used have a timestamp field which is by default set to timezonenow this is the sequence that raises error flagsmodel one is created at time 730 pmmodel two is created at time 10 pm but in the mysql database it is stored as 730 pm every model that is created has its time stamp saved under 730 pm not the actual time until a certain duration passes then a new time is set and all the following models have that new time bizzaresome extra details which may help in thiscovering the issuei have a bunch of methods that i use to strip my timezones of their tzinfos and replace them with utc this is because i am doing a timezonenow creationtime calculation to create a model was posted this long ago featurein the project however this really should not be the cause of the problemi do not think using datetimedatetimenow will make any difference eitheranyway thanks for the help,['python'] +371315,rails presence validation fails on value 0 i have a model similar to the followingclass activity activerecordbase attr accessible name admin validates name presence true validates admin presence trueend the name property is a string and the admin property is defined as a boolean in the migrationif i try to create an instance of the model in the console using a activitycreatename test admin 0then the validation fails saying i need to provide a value for admin why i have supplied a value i could understand if i had failed to supply a value at all or if i had supplied nil but why does a value like 0 or even false for that matter cause validation to fail,['ruby-on-rails'] +371324,how to create a java class with static method called cage that place x in a prison bar shape this is for my homework how to create a public method called cagechar arr that returns a char the method should place xs along the borders of the grid represented by the 2d array in addition it should place bars along the columns of the array skipping one column for every bar for example if arr has 8 columns the returning array looks like this x x x x x x x x x x x x x x x x x x x x x xmy other shape was this create a java class arrayart with static methods as specified belowa public method called framechar arr that returns a char the method should put xs along the borders of the grid represented by the 2d array and then it should return that array for example if arr has 4 columns and 4 rows the resulting array should be jgrasp exec java arrayart x x x x x x x x x x x x jgrasp operation completethe source code for the frame printing is next public class arrayart public static void mainstring args printarrayframe44 frame printingpublic static char frameint n int m char xnew charnm forint row0rowxlengthrow forint col0colxrowlengthcol if row 0 row n1 row colrow row rowcolm1 xrowcol x else xrowcol return x printarray public static void printarraychar arr forint row0rowarrlengthrow for int col0colarowlengthcol systemoutprint arowcol systemoutprintln,['java'] +371344,template inheritance for handlebars i am trying for template inheritance from basehtml to other templates using handlebarsbut am not getting soul for this please can anyone help me out with simple demo with basehtml extendhtmlfor example basehtmlhtmlheadheadbody block content endblock bodyhtmlextendhtml extends basehtml block content h1foobarh1 endblock which files i need to include in basehtml,['javascript'] +371405,uicollectionview align logic missing in horizontal paging scrollview i have got a uicollectionview which works ok until i start scrollinghere some pics firstas you can see it is great as i start scrolling paging enabled the first one goes a bit offscreenthis is the problem originaly my view have 3 views and i want to scroll and show 3 views only but as it scrolls paging enabled it hides a little bit of the first view and show little bit of the next first view from the next page and here is a video because it is kinda hard to explainvideo of the problem dropboxhere is a picture of my uicollectionview settings it is going to be great if someone can help,"['iphone', 'ios']" +371411,facebook ios sdk 31 crashes on subsequent call to fbsession openwithbehavior if we call openwithbehavior after a call to closeandcleartokeninformation it causes exc bad access regardless of whether it is using the native ios builtin dialog or one of the fastswitching ones our code to login to fb first time through worksif fbsession activesession ifdef free app nsstring suffix free else nsstring suffix paid endif fbsession session fbsession alloc initwithappid1 permissionspermissions urlschemesuffixsuffix tokencachestrategynil autorelease fbsession setactivesessionsession else if fbsession activesessionisopen fbsession activesession closefbsession activesession openwithbehaviorfbsessionloginbehaviorusesystemaccountifpresent completionhandlerfbsession session fbsessionstate state nserror error self sessionstatechangedsession statestate errorerror our code to logout after which the code above fails after openwithbehaviorfbsession activesession closeandcleartokeninformationi was initially using openactivesessionwithreadpermissions instead of openwithbehavior as prescribed in the 31 docs which does not crash but the app switching back from fb appsafari did not work perhaps because of the need to have a suffix if it would be easiest to fix the app switching and go back to that please advise thanks,['ios'] +371461,what does auto tell us if you read code likeauto var foowhere foo is any function retuning by value of type t then var is an lvalue of type rvalue reference to t but what does this imply for var does it mean we are allowed to steal the resources of var are there any reasonable situations when you should use auto to tell the reader of your code something like you do when you return a unique ptr to tell that you have exclusive ownership and what about for example t when t is of class typei just want to understand if there are any other use cases of auto than those in template programming like thiscussed in the examples in this article universal references by scott meyers,['c++'] +371512,where do i store general config parameters in silex i have some general parameters i would like to share all along my application like path information baseurl where would you ideally store this information in silex,['php'] +371544,resharper wont function properly in visual studio 2012 running on windows 8 i installed visual studio 8 on windows 8 with resharper 701 and i have some problems getting resharper to function properly it seems most of resharper does not work but here is some of the strange behaviour i have noticedclicking ctrlshiftt opens up the select file or folder dialog but when i select a file from here and click enter the dialog closes but the file is not opened upctrlrr rename gives the message that the key is bound to resharper rename but that it is not currently available even when the cursor is inside a variable in a standard cs file and the program is not debuggingaltenter does nothing so the context menu does not pop up at all anywheredoes anyone know if resharper is not supposed to work under win 8 or is it something that is messed up on my machine in that case whateditnotices that code analysis is not working either so that bar on the right hand side of the code windows that thisplays the green yellow and red lines to indicate problems is not there,['.net'] +371588,lots of query end states in mysql all connections used in a matter of minutes this morning i noticed that our mysql server load was going sky high max should be 8 but it hit over 100 at one point when i checked the process list i found loads of update queries simple ones incrementing a hitcounter that were in query end state we could not kill them well we could but they remained in the killed state indefinitely and our site ground to a haltwe had loads of problems restarting the service and had to forcibly kill some processes when we did we were able to get mysqld to come back up but the processes started to build up again immediately as far as were aware no configuration had been changed at this pointso we changed innodb flush log at trx commit from 2 to 1 note that we need acid compliance in the hope that this would resolve the problem and set the connections in phppdo to be persistent this seemed to work for an hour or so and then the connections started to run out againfortunately i set a slave server up a couple of months ago and was able to promote it and it is taking up the slack for now but i need to understand why this has happened and how to stop it since the slave server is significantly underpowered compared to the master so i need to switch back soonhas anyone any ideas could it be that something needs clearing out i do not know what maybe the binary logs or something any ideas at all it is extremely important that we can get this server back as the master asap but frankly i have no idea where to look and everything i have tried so far has only resulted in a temporary fixhelp,['mysql'] +371589,custom scaffold for controller i am using repository pattern in my asp mvc4 app and i thought it would be nice to create custom scaffold templates to avoid tweaking code every time i generate somethingi followed some tutorials from the web i copied the codetemplates directory form programfiles to my project only some of the files and i cleared the custom tool property for eachi managed to achieve 2 goalsoverride the default template for controller when i go to controlleraddcontrollers and select controller with readwrite actions and views it uses my templateadd a new view template when i go to someviewfolderaddview i can choose my new template therethe thing i was unable to achieve was to create a new template controllerwithrepott and be able to select it in controlleraddcontrollers even though i have controllerwithrepott created it does not show up on the template drop down listi know it is possible to do what i want by hardcoding things in controllerwithcontext but it seems to be a lame solution i would like to do it the right way to pass a repository class instead of dbcontext class and generate the controller the way i wantright now if i try to put my repository class as dbcontext it fails to perform the scaffoldto sum up how can i create my own controller scaffold template for repository pattern,"['c#', 'asp.net']" +371620,openerp context in act window in openerp 61 this act windowact window domainid student idact schedule student namestudent res modelschoolstudent src modelschoolschedulecreates a student button in the schedule form which opens the student tree view showing only the appropriate studentmy goal is to directly open the corresponding form view of the student instead of a tree view with the right filtered student i tried adding a view modeformtree but it opens a new form instead of the one i want i am guessing this can possibly be achieved by adding context to the act window maybe a record id but i tried that with active id and it did not work,['python'] +371627,generic in app purchase products implementation consider following example let us say we have an app in which professional writers write stories from a web based ui and then these stories become available for user of the ios app as in app purchase itemsas you may know we need to create in app purchase products in advance but in our situations it means that for each of the story created by the writers we will have to create a new iap product and wait for apple to approve itto circumvent this i am planning to create generic consumable products in iap like story worth 199 story worth 299 so on so forth then in the application ui i will show the list of stories of created by the writers and show corresponding prices for the stories as specified by the authors when they created the story once the user taps on the buy button i will show the purchase for the generic consumable product of the same price and complete the in app purchase process now the question is will apple approve of such implementation does it fit with their iap policy i am asking as i could not find a guideline for a workflow such as this another approach to implement this is by implementing an in app creditcurrency system like games use where people buy creditscoins and then they purchase items with coins this is a tried and tested approach but it does not fit in my analogy of the app hence the question,['ios'] +371697,convert stdbind to function pointer i have a thirdparty library which has a method that takes a function pointer as the first parameterint third party methodvoid funcdouble double int int double i want to pass a pointer to a class method that is declared as followsclass testclass public void myfunction double double int int voidi tried to pass this function as followstestclass tc new testclassusing namespace stdplaceholdersthird party methodstdbindtestclassmyfunction tc 1 2 3 4 5 however this does not compileconversion of parameter 1 from stdtr1 bind result type ret bindn to void cdecl double double intintvoid is not possiblewith result typevoid retvoid bindnstdtr1 bind6stdtr1 callable pmfvoid thiscall testclass const double double intintvoid testclassfalsetestclass stdtr1 ph1stdtr1 ph2stdtr1 ph3stdtr1 ph4stdtr1 ph5is there any way i can pass the member to the function,['c++'] +371727,architecture solution for python web application were setting up a python rest web application right now were using wsgi but we might do some changes to that in the future using twisted for example to improve on scalability or some other feature i would really like some help regarding what is considered a good architecture for a web application in pythonin general our app serves dynamic content processes a moderate to high level of data from clients performs pretty highdemand database network and filesystem calls and should be easily scalable quotes here because if a solution is great but somewhat tough to configure for scalability it would definitely be thought of as good we would probably like to evolve this into a highly parallel application in the midtolong term google app engine is not an accepted suggestion mainly because of its costmy question is thisis using wsgi a good idea should we be looking into something like twisted insteadshould we use apache as a reverse proxy for our static filesis there some different pattern or architecture that we should considerthat i have not mentioned even if completely obviousany help at all with this would be very appreciated thanks a lot,['python'] +371731,orgspringframeworkdaodataintegrityviolationexception misreporting cause i am using hibernate to insert to a mysql table on which all columns are defined as not null it has a unique primary key and another unique index on several columnsi am getting the following errororgspringframeworkdaodataintegrityviolationexception could not execute jdbc batch update sql insert into my tablecol1 col2 col3 col4 id values constraint nullthis error is in customer logs and i cannot reproduce the problem myself so i cannot put in debugging to see what the values are in the insert statementmy understanding is that constraint null means a not null constraint is being violated however looking at my code i cannot see any possible way that any of the data could be null at the time of the insert unless hibernate is trying to insert a null id which would be a very bad bug in hibernate and so seems unlikelyhowever i can see how it could happen that a unique constraint is being violated is it possible that the message is misleading and i am actually getting a unique key violation does constraintnull always mean a not null constraint was violated,['java'] +371746,referencing a custom shape class in xml i have been extending the standard range of shape classes rectshape ovalshape and so on by extending the shape class to create my own custom set of shapes for example i have created a simple triangleshape class like soimport androidgraphicscanvasimport androidgraphicspaintimport androidgraphicspathimport androidgraphicsdrawableshapesshapepublic class triangleleftshape extends shape overridepublic void drawcanvas canvas paint paint path path new path pathsetlastpoint0 getheight2 pathlinetogetwidth getheight pathlinetogetwidth 0 pathclose canvasdrawpathpath paint what i would like to do is create a drawable resource entirely in xml using this class is this possiblei am aware that using one of the standard shapes is simply achieved by the following example where the shape element represents a shapedrawablexml version10 encodingutf8shape xmlnsandroid androidshapeoval gradient androidstartcolorf0 androidendcolor80ff00ff androidangle270shapewhat i cannot see is how one would pass in xml a custom shape class to this shapedrawable that is being defined in xml i understand that the androidshape attribute is simply passing an enum value which can only be rectangle oval line or ring it seems that there is no xml attribute to specify a custom shape class however the shapedrawable has a setshape method which seems to suggest i could programmatically set my custom shape class but not do it via xmlhow if possible can i make use of a custom shape class in xml i realise that i could create a custom view very easily to draw my basic shapes but use of drawables seems to have the advantage of being able to specify colours etc and other attributes in xml or styles themes,['android'] +371754,ios appstore installs old version and then offer to update to the new one i submitted a new version of my app to appstore and it was approved a week agohowever i delete the app from the ipad install it from appstore and i get the old version installed the install button on appstore turns to update instead of launch and then i get the new version installeddoes anyone know what could be happen here why the new version is not installed in first placei tried with ios 5 and ios 6,['ios'] +371775,jfreechart change seriesstroke of chart lines from solid to dashed in one line the answer accepted here jfreechartjava how to draw lines that is partially dashed lines and partially solid lines helped me start down the path of changing my seriesstroke lines on my chart after stepping through my code and watching the changes i see that my seriesstroke does in fact change to dashedstroke when it is supposed to after a certain date dashedafter but when the chart is rendered the entire series line is dashed how can i get a series line to be drawn solid at first and dashed after a set date series line modifications final number dashedafter timenowdategettimexylineandshaperenderer render new xylineandshaperenderer stroke regularstroke new basicstroke stroke dashedstroke new basicstroke 10f basicstrokecap round basicstrokejoin round 10f new float 100f 60f 00f override public stroke getitemstrokeint row int column number xval cdgetxvaluerow column if xvaldoublevalue dashedafterdoublevalue return dashedstroke else return regularstroke rendersetbaseshapesvisiblefalserendersetbaseshapesfilledtruerendersetdrawserieslineaspathtrueplotsetrendererrender,['java'] +371821,composing adaptors in boostrange i started playing with boostrange in order to have a pipeline of lazy transforms in c my problem now is how to split a pipeline in smaller parts suppose i haveint main auto map boostadaptorstransformed shorten the name auto sink generate1 mapint x return 2x mapint x return x1 mapint x return 3x forauto i sink stdcout i nand i want to replace the first two maps with a magic transform ieint main auto map boostadaptorstransformed shorten the name auto sink generate1 magic transform mapint x return 3x forauto i sink stdcout i nhow would one write magic transform i looked up boostranges documentation but i cannot get a good grasp of itaddendum i am looking to write a class like thisclass magic transform run pipeline input return input mapint x return 2x mapint x return x1,['c++'] +371831,java recursion triangle with deviation hello i am fairly new to programming and i am trying in java to create a function that creates recursive triangles from a larger triangles midpoints between corners where the new triangles points are deviated from the normal position in yvalue see the pictures below for a visualizationthe first picture shows the progression of the recursive algorithm without any deviation order 012 and the second picture shows it withorder 01i have managed to produce a working piece of code that creates just what i want for the first couple of orders but when we reach order 2 and above i run into the problem where the smaller triangles do not use the same midpoints and therefore looks like the picture below so i need help with a way to store and call the correct midpoints for each of the triangles i have been thinking of implementing a new class that controls the calculation of the midpoints and stores them and etc but as i have said i need help with thisbelow is my current codethe point class stores a x and y value for a pointlinebetween creates a line between the the selected pointsvoid fractallineturtlegraphics turtle int order point ett point tva point tre int dev iforder 0 linebetweenetvaturtle linebetweentvatreturtle linebetweentreeturtle else double deltax tvagetx ettgetx double deltay tvagety ettgety double deltaxtre tregetx ettgetx double deltaytre tregety ettgety double deltaxtva tvagetx tregetx double deltaytva tvagety tregety point one point two point three double xt deltax2ettgetx double yt deltay2ettgety randomutilitiesrandfuncdev one new pointxtyt xt deltaxtre2ettgetx yt deltaytre2ettgety randomutilitiesrandfuncdev two new pointxtyt xt deltaxtva2tregetx yt deltaytva2tregety randomutilitiesrandfuncdev three new pointxtyt fractallineturtleorder1onetvathreedev2 fractallineturtleorder1ettonetwodev2 fractallineturtleorder1twothreetredev2 fractallineturtleorder1onetwothreedev2 thanks in advancevictor,['java'] +371890,how to thisable scrollviewer automatic moving of scrollviewer in xaml phone application how can i make my scrollviewer not to move automatically when i moveand release it with mousei know it is the normal behavior i need to make it keep its current horizontal offset when i release mouse,['c#'] +371899,how to apply a fragment shader to only one object in opengl i am just beginning to learn opengl with all of the tutorials i have seen they demonstrate using a fragment shader to set the color of all the objects in view what i have not found yet is how you would use a fragment shader on just one of the objects giving different objects different colors how do you do thatto provide background to the question i am drawing a simple scene with a house and a road in 2d i have thiscovered how to set the colors of each of my objects the main body of the house the window etc using the fixed graphics pipeline i just do not understand how to set the colors using fragment shadersany clarification would be greatly appreciated including correction if i am misunderstanding something,['c++'] +371965,html and attribute encoding i came across a post on meta so and i am curious about what the subtle differences between html and attribute encoding are,['html'] +371970,is azure cloudtable threadsafe i am writing to azure table storage using storage sdk 20 from different threads aspnet applicationis cloudtable object threadsafe can i initialize cloudstorageaccount cloudtableclient and cloudtable only once for example in static constuctor and then use them in different threadsor is it better to create all cloudstorageaccount cloudtableclient and cloudtable objects each time from a blank like it is shown in this article does it affect the performance in any waywhat is a prefered way of getting instance of cloudtable each time executing an operation against the table,['.net'] +371973,error correction in names i am trying to device an algorithm that performs error correction in names my approach is having a database with the correct names compute edit thistance between each of them and the name entered and then suggest the 5 or 10 closestthis task is significantly different from standard error correction in words as some of the names might be replaced by initials for instance jonathan smith and j smith are actually quite close and could easily be considered the same name so the edit thistance should be really small if not 0 another challenge is that some names might be written differently while sounding the same for instance shnaider and schneider are versions of the same name written by people with different localesthere are better examples for that i guess and another case just imagine all the possible errors in writing jawaharlal nehru most of which have nothing to do with the real name again probably most of them will be similar phoneticallyobviously lucenes error correction algorithm will not help me here as it does not handle the above casesso my question is do you know any library capable of doing error correction in names can you propose some algorithm for handling the cases mentioned abovei am interested in libraries in c or java as for algorithm proposals any language or pseudo code will do,"['java', 'c++']" +371993,is socketgetinputstreamreadbyte guaranteed to not block after at least some data is read the javadoc for the class inputstream says the followingreads up to len bytes of data from the input stream into an array of bytes an attempt is made to read as many as len bytes but a smaller number may be read the number of bytes actually read is returned as an integer this method blocks until input data is available end of file is detected or an exception is thrownthis corresponds to my experience as well see for instance the example code belowclientsocket socket new socketlocalhost portoutputstream out socketgetoutputstreambyte b 0 0 threadsleep50outwritebthreadsleep50outwritebserverserversocket server new serversocketportsocket socket serveracceptinputstream in socketgetinputstreambyte buffer new byte4systemoutprintlninreadbuffersystemoutprintlninreadbufferoutput2 two bytes read five seconds after client is started2 two bytes read ten seconds after client is startedthe first call to readbuffer blocks until input data is available however the method returns after two bytes are read even though there is still room in the byte buffer which corresponds with the javadoc stating that an attempt is made to read as many as len bytes but a smaller number may be read however is it guaranteed that the method will not block once at least one byte of data is read when the input stream comes from a socketthe reason i ask is that i saw the following code in the small java web server nanohttpd and i wondered if a http request smaller than 8k bytes which most requests are potientially could make the thread block indefinately unless there is a guarantee that it would not block once some data is readinputstream is mysocketgetinputstream read the first 8192 bytes the full header should fit in herebyte buf new byte8192int rlen isreadbuf 0 bufsizeeditlet me try to illustrate once more with a relatively similar code example ejp says that the method blocks until either eos is signalled or at least one byte of data has arrived in which case it reads however many bytes of data have arrived without blocking again and returns that number which corresponds to the javadoc for method readbyte int int in the class inputstream however if one actually looks at the source code it is clear that the method indeed blocks until the buffer is full i have tested it by using the same client as above and copying the inputstreamcode to a static method in my server examplepublic static void mainstring args throws exception serversocket server new serversocketport socket socket serveraccept inputstream in socketgetinputstream byte buffer new byte4 systemoutprintlnreadin buffer 0 bufferlengthpublic static int readinputstream in byte b int off int len throws ioexception if b null throw new nullpointerexception else if off 0 len 0 len blength off throw new indexoutofboundsexception else if len 0 return 0 int c inread if c 1 return 1 boff bytec int i 1 try for i len i c inread if c 1 break boff i bytec catch ioexception ee return ithis code will have as its output4 four bytes read ten seconds after client is startednow clearly there is data available after 5 seconds however the method still blocks trying to fill the entire buffer this does not seem to be the case with the input stream that socketgetinputstream returns but is it guaranteed that it will never block once data is available like the javadoc says but not like the source code shows,['java'] +372007,slcomposeviewcontroller thismisses differently for facebook and twitter i have some social sharing code that looks like thisslcomposeviewcontroller composer slcomposeviewcontroller composeviewcontrollerforservicetypeacomposer setinitialtextacomposer addurlacomposer setcompletionhandlerslcomposeviewcontrollerresult result somecontroller thismissviewcontrolleranimatedyes completion a 1 somecontroller presentmodalviewcontrollercomposer animatedyesthe problem is that the code behaves differently for facebook and twitter when the user confirms the facebook compose screen the composer apparently thismisses itself because the completion handler marked as 1 is never called and even when i remove the thismissviewcontrolleranimated call everything works fineon the other hand when user confirms the twitter compose screen and i donat thismiss it by hand the compose screen slides out but the app stays stuck like some controller is still in foreground when i add the thismissviewcontrolleranimated call the problem thisappears and the completion handler 1 is called correctlydid you also notice this behaviour am i doing something wrong this is current ios 6 sample code on github i have reported the problem to apple radar 12642889 no reaction yet,['ios'] +372010,whats the difference between r and a when open file in python possible duplicatepython open builtin function difference between modes a a w w and r i have try r and a to open file and read and write but r and a are all append the str to the end of the fileso whats the difference between r and a addi have found the reason i have read the file object and forgot to seek0 to set the location to the begin,['python'] +372021,private vs static constructors in net i searched for this a lot but none of the answers are clear atleast for me now i am putting this question in so as i believe i cannot get a more clarified answer anywhere elsewhen should i use a privatestatic constructor in my class i am fed up of usual answers so please help me with some realtime examples and advantagesthisadvantages of using these constructors,"['c#', '.net']" +372047,using text sql with linq i am currently having issues with using linq to sql for my project this is because most of the lengthy sql queries or views rather are hardcoded into c and what weve been doing all along is to use contextdatabasesqlqueryclassnamesql sqlparamsit is been generally very effective but right now we need something more dynamic we need to plug in stuff like wherex xnamecontainsanonymoustake20 or something else along the lines however plugging in directly to the previously mentioned line of code would result in the followingcontextdatabasesqlqueryclassnamesql sqlparamswherex xnamecontainsanonymoustake20while it actually works and pulls the top 20 records where the name contains anonymous the performance is pretty bad what it does behind the scenes is to take all the records from that table and then finally filtering them after having loaded them to memoryi would then like to ask is there any way to translate the text sql to linq or translate the linq to sql such that i can execute both my text sql and linq in one single statement if you do not actually have a solution i would gladly appreciate suggestions tooedit i have considered using expression trees but i am not sure how they can actually fit into the picture also i have considered using database views but there are so many views quite a number per table it would definitely be a hassle to port everything over to ms sql and then rewriting all the querying logic,"['c#', 'sql']" +372073,change view onclick coverflow android i am using this coverflow i want to be able to change view when i click on a button the button being a backforward icon which will take you to the previousnext item in the coverflowi have modded the coverflow slightly so that i use an xml layout insteadhere is my oncreate method setcontentviewrlayoutmain coverflow coverflow coverflowfindviewbyidridcoverflow coverflowsetadapternew imageadapterthis imageadapter coverimageadapter new imageadapterthis coverflowsetadaptercoverimageadapter coverflowsetspacing20 coverflowsetselection0 true coverflowsetanimationduration10 tv textviewfindviewbyidridtextview1 coverflowsetonitemclicklistenernew onitemclicklistener override public void onitemclickadapterview arg0 view arg1 int arg2 long arg3 toastmaketextgetbasecontext stringvalueofarg2 toastlength shortshow coverflowsetonitemselectedlistenernew onitemselectedlistener override public void onitemselectedadapterview arg0 view arg1 int arg2 long arg3 tvsettextstringvalueofarg2 override public void onnothingselectedadapterview arg0 do something my xmlxml version10 encodingutf8relativelayout xmlnsandroid androidlayout widthfill parent androidlayout heightfill parent androidbackgrounddrawablehome background androidorientationvertical comdemoappcoverflowcoverflow androidididcoverflow androidlayout widthfill parent androidlayout heightfill parent button androidididbutton1 androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentbottomtrue androidlayout alignparentlefttrue androidlayout marginbottom39dp androidlayout marginleft35dp androidbackgrounddrawablebutton left button androidididbutton2 androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentbottomtrue androidlayout alignparentrighttrue androidlayout marginbottom39dp androidlayout marginright35dp androidbackgrounddrawablebutton right textview androidididtextview1 androidlayout widthwrap content androidlayout heightwrap content androidlayout marginbottom55dp androidlayout alignparentbottomtrue androidlayout centerhorizontaltrue androidtexthello androidtextcolorcolorwhite androidtextsize16dp imageview androidididimageview1 androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparenttoptrue androidlayout alignparentrighttrue androidlayout marginright170dp androidlayout margintop15dp androidsrcdrawableunsa logo imageview androidididimageview2 androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentrighttrue androidlayout marginright14dp androidlayout margintop23dp androidsrcdrawablepnc logo relativelayout,['android'] +372085,linq to entity join and group by i am new to linq to entity and here is my test scenariothere are usersusers have photo albums an album belongs to only one useralbums have photos a photo belongs to only one albumphotos have tags a tag may belong to many photosi want to write a method which thisplays count and name of tags used in albums of a particular user using linqhere is the method that i wrote and it works fine public static void teststatisticsint userid select albumtitle tagname tagcount where userid userid var results from photo in dbsetphotoset join album in dbsetalbumset on photoalbumid equals albumid into albumset from alb in albumset where albuserid userid join phototag in dbsetphototagset on photoid equals phototagphotoid into phototagset from pt in phototagset join tag in dbsettagset on pttagid equals tagid group new alb tag by new albtitle tagname into resultset orderby resultsetkeyname select new albumtitle resultsetkeytitle tagname resultsetkeyname tagcount resultsetcount foreach var item in results consolewritelineitemalbumtitle t itemtagname t itemtagcount and this is the standart tsql query which does the sameselect atitle as albumtitle tname as tagname counttname as tagcountfrom tblphoto p tblalbum a tbltag t tblphototag ptwhere pid ptphotoid and tid pttagid and palbumid aid and auserid 1group by atitle tname order by tnameit is pretty obvious that standard tsql query is much simpler than the linq queryi know linq does not supposed to be simpler than tsql but this complexity difference makes me think that i am doing something terribly wrong besides the sql query generated by linq is extremly complexis there any way to make the linq query simplerupdate 1i made it a little simpler without using joins but using a approach like used in tsql actually it is now as simple as tsql still no navigation properties and no relations on dbvar results from photo in dbsetphotoset from album in dbsetalbumset from phototag in dbsetphototagset from tag in dbsettagset where photoalbumid albumid photoid phototagphotoid tagid phototagtagid albumuserid userid group new album tag by new albumtitle tagname into resultset orderby resultsetkeyname select new albumtitle resultsetkeytitle tagname resultsetkeyname tagcount resultsetcount,['c#'] +372125,allow rotationlandscape in one fragment my app has a single activity with a fragmentpageradapter with four fragments using the viewpagerindicator library one of these fragments has designs for both a separate portrait and landscape layout the other three do not and need to be fixed to portrait orientationmy thought was to set androidconfigchangesorientation in the manifest and call getactivitysetrequestedscreenorientation in the onresume of all the fragments locking to screen orientation portrait in three of them but to screen orientation unspecified in the one that needs to allow rotation but this does not work the app remains in portrait mode is there a way to achieve thisit is not actually necessary for the actual activity to rotate if there is anyway to allow a fragment to change orientation without its activity doing so but i have not found anything mentioning this being possible it would also be equally ok if the activity rotates since the tab bar will be hidden when in landscape orientation,['android'] +372127,change font for edittext hint is it possible to change the font for the hint thisplayed in the edittext field i want to set the font in the xml itself,['android'] +372129,get child in list without id and with epreventdefault on first level of i have some menu with structure like thisul idmenu lia hrefspanfirst level link 1spana ul lia hrefspanchild link 1spanali lia hrefspanchild link 2spanali ul li lia hrefspanfirst level link 2spana ul lia hrefspanchild link 2spanali lia hrefspanchild link 2spanali ul liulit need to show only first level ul li its ok but then it needs to show by on click second level links and i cant usw id or rel attr in ul or li this is my problem to catch child my code is likevar menuraw ulmenu lilt5 menurawclickfunctione epreventdefault var menuitem this menurawremoveclaselected menuitemaddclaselected menu ulhide menuitemfindulshow and it works but epreventdefault is blocking all links in menu but on second level links needs to be working links as normally they dosorry for my english and this is first question on stackoverflow,"['javascript', 'jquery']" +372197,how do i get the viewport position relative to the screen my questionwhat javascript code will tell me where the viewport of the browser is located relative to the screencontextmy web application includes an applet that allows taking a snapshot via javaawtrobot the applet us jar is of course signed and is privileged to perform thisthe problem is that robots createscreencapture works with rectangles relative to the entire screen whereas i want to capture a rectangle relative to the viewporta browser can obviously be anywhere on the screen but even if it is maximized and therefore begins at the top left of the screen ie 00 i still do not know how much the content is pushed down because of the window header or some toolbarsmy research so farit seems only ie gives the viewport position through windowscreentopleftchrome supports these but they hold the browser positionff does not support these instead it has screenxy but like chrome they hold the browser positionmaking sure we all use the same terminologyscreen aka the desktop for example i have a wsxga 1680x1050 thisplay i use windows and my taskbar is always shown at the bottom so it consumes about 50 pixels verticallybrowser a window that may or may not have various toolbars address andor bookmarks bar at the top statusaddon bars at the bottom etcviewport where a url is actually being rendered,['javascript'] +372209,metainfservices in jar with gradle i wanted to build a plugin module that can be loaded with a serviceloader this requires adding a file to the metainfservices directory that is named after the service interface and that contains the qualifying path to the class that implements it then you can load these services by calling serviceloaderloadhere is an examplesay we want to provide a plugin interface called orgexamplepluginspluginservice we then provide an implementation of this service in the class orgexamplepluginsimplexamplepluginif we want to have some sort of plugin mechanism we could create a jar file that contains the implementation this jar file must also contain the file metainfservicesorgexamplepluginspluginservice this file must contain one lineorgexamplepluginsimplexamplepluginto enable the serviceloader to find the implementation if that jar file is in the build path you can load the plugin by callingiteratorpluginservice it serviceloaderloadpluginserviceclassiteratorthat iterator will give you access too all plugins that are found by the serviceloaderfor some reason gradle does not include files into the metainf directory by default is there a way to let the resulting jar contain such a filei already found the method metainf in class jar but i do not know groovy good enough to find the solution on my own,['java'] +372210,cannot find resolve in context menu of visual studio 2010 ultimate as in subject i cannot find resolve in context menu of visual studio 2010 ultimatei have seen it in my teacher computer in the internet but i cannot find it in the context menu look at screen how to get it,['c#'] +372228,creating a fake user in symfony2 for testing purposes i am somewhat new to testing in php i have done quite a bit of testing on rails using cucumber rspec capybara and factory girl but i have barely done any testing with phpi will ask a question about my current challenge in the most general way possible since i have gone down a few specific paths and been met only with frustrationi want to write a functional test for signing a user in whats a good way to create the test user object that i would need in order to try to sign ineven more generally whats the de facto standard for creating test objects in symfony2 fixtures some kind of factoryin ruby i would use factory girl since it lets you handle any objects dependencies in a clean dry way there seems to be a factory girl equivalent in php in phactory but unfortunately it seems that that tool is not widely used and no longer maintained,['php'] +372281,c proscons of enumindexed arrays in my experience the real world rarely provides for indexes of nonnegative integers many things are not even represented numerically and many things with a numericallyrepresented index do not begin their indexes at 0 why then are we still limited to integerindexed arraysmaybe i am wrong but it seems like enum indexed arrays are often more appropriate than numericallyindexed arrays as enums are often more accurate realworld representations while enums can often be translated into cstyle array indices with relative easeenum weekday sunday monday tuesday wednesday thursday friday saturday hopefully c does not allow nonsequential enum values else pray to god no one does something like setting sunday 4 and saturday 4096int numberofdays saturdaysunday1int hoursworkedperdaynumberofdayshoursworkedperdayintsunday 0hoursworkedperdayintmonday 8hoursworkedperdayinttuesday 10hoursworkedperdayintwednesday 6hoursworkedperdayintthursday 8hoursworkedperdayintfriday 8hoursworkedperdayintsaturday 0we are still required to maintain consistency between the number of enums and the size of the array however this is not an awful solution because there is not a more valid integer mapping for sunday than 0 and more importantly anything that can be cast to an int could still be dropped into the index to manipulate the array continued from abovevoid resethours void int i 0 int hours 0 for i 0 inumberofdays i hoursworkedperdayhours i oops should have been i hours an enumindexed implementation would have caught this during compilation furthermore the entire conversion from enum to int is an entire layer of complexity that seems unnecessarycan someone please explain whether there is validity to enumindices and list some pros and cons to each approach and perhaps why a feature so seemingly useful is missing from the c standard if such information exists,"['c++', 'c']" +372285,twitter bootstrap modal leaves screen unclickable after it thisappears i tried to use the modal feature of the twitter bootstrap framework with ios5 after the user clicks on the close button the modal thisappears correctly but no other item of the screen seems to be clickable this behaviour just occurs under ios5 it is working correctly with ios 6 and in any desktop browserhere the close buttona typebutton classclose datathismissmodal ariahiddentrueaamay this occur because of the missing html5css3 support in ios5,['ios'] +372296,why does the entity framework generate nested sql queries why does the entity framework generate nested sql queriesi have this code var db new context var result dbnetworkwherex xserverid serverid orderbyx xstarttime takelimitwhich generates this note the double select statementselectproject1id project1serverid project1eventid project1starttimefrom selectextent1id extent1serverid extent1eventid extent1starttimefrom networkes as extent1 where extent1serverid p linq 0 as project1 order by project1starttime desc limit 5what should i change so that it results in one select statement i am using mysql and entity framework with code firstupdatei have the same result regardless of the type of the parameter passed to the orderby methodupdate 2 timedtotal time hhmmssms 0534130average time hhmmssms 25420max time hhmmssms 51540count 13first seen nov 6 12 194819last seen nov 6 12 204022raw queryselect projectid projectserverid projecteventid projectstarttime from select extentid extentserverid extenteventid extentstarttime from network as extent where extentserverid as project order by projectstarttime desc limit i used a program to take snapshots from the current process in mysqlother queries were executed at the same time but when i change it to just one select statement it never goes over one second maybe i have something else that is going on i am asking because i am not so into dbsupdate 3 the explain statementthe entity framework generated1 primary derived2 all null null null null 46 using filesort2 derived extent ref serveridneventidserverid serveridneventid 109 45 using whereone liner1 simple network ref serveridneventidserverid serveridneventid 109 const 45 using where using filesortthis is from my qa environment so the timing i pasted above is not related to the rowcount explain statements i think that there are about 50 records that match one server idsolutioni switched from mysql to sql server i do not want to end up completely rewriting the application layer,"['c#', 'mysql']" +372303,android webview inside scrollview scrolls only scrollview in my app i have a scrollview that contains some linearviews some textviews and one webview then other linear layouts etc the problem is that the webview does not scroll the scroll listens only on scrollviewany suggestionsscrollview textview webview this does not scroll textview scrollview,['android'] +372312,how to use android support library correctly i am working my way through professional android 4 application development chapter 4 modifies the to do list app to use fragments but i am trying to test on a gingerbread device there is mention in the book of using support libraries to allow using android v3 or v4 features on a lower version device but it is not covered very welli am running into a problem specifically with get references to the fragments androidappfragmentmanager fm getfragmentmanager todolistfragment todolistfragment todolistfragment fmfindfragmentbyid ridtodolistfragment i have got these imports at the top import androidsupportv4appfragmentmanager import androidsupportv4applistfragmentbut lint warns on the todolistfragment todolistfragment todolistfragment line cannot cast from fragment to todolistfragmentin my todolistfragment class i have import androidsupportv4applistfragment public class todolistfragment extends listfragment this is almost verbatim from the book except for the change to use support libraryi am not clear on how to get this code to work correctly using the v4 support library i apologize in advance if this is not enough info i am still learning this and i am more familiar with cc than java if i do not use the support library the code builds just fine and will run on an ice cream sandwich device but i would like to get it working on lower level devices too,['android'] +372372,using closure library on phonegapandroid application hi has any one used googles closure library in building phonegap applications on android i have read that closure has good support for internationalization of applications so if anyone could provide material they referred or sample snippets to get an idea of how to implement it,"['javascript', 'android']" +372400,first person simulation with threejs using keyboard arrows for my source visit backgroundi have a simple 3d simulation using threejs where the camera is surrounded in 3 dimensions by cubes these cubes are to help visualise where the camera is looking until the view controls are coded and tested i want to create a simple 3d application where the camera is controlled via up down left and right keys just like moving your headissuesin my current application when facing forward and starting to look up we are successful however when we turn left 90 degrees and we press the up arrow the wrong thing happens the camera increments the x axis but because were facing another direction modifying the x axis alone is wrongnow i am assuming this is because some trigonometry is required to calculate the correct values for the z axis however my trig is not brilliantcurrentto get a better understanding of what i mean please visit my jsfiddle up key only increments xdown key only decrements xleft key only increments yright key only decrements yq key only increments zw key only decrements z q and w were only coded to try and help me understand from my current understanding when i press the up key x must increment and the z axis must be modified based on what the current y axis is however i do not know the algorithm so x and z must be modified in the keyup code i think please correct me if i am wrong setrotatex getrotatex setrotatey and getrotatey are extended camera functions i wrote so i could work with degrees solution is not required to use them they just helped meswitch key case keyup if cameragetrotatex 90 restrict so they cannot look overhead camerasetrotatex cameragetrotatex view increment break case keydown if cameragetrotatex 90 restrict so they cannot look under feet camerasetrotatex cameragetrotatex view increment break case keyleft camerasetrotatey cameragetrotatey view increment break case keyright camerasetrotatey cameragetrotatey view increment break,['javascript'] +372402,is it okay to double check before and inside a lock before running the code inside on working with threadsafety i find myself always double checking before executing code in a lock block and i wondered if i was doing the right thing consider the following three ways of doing the same thingexample 1private static somecollection mycollectionprivate static object lockerprivate void dosomethingstring key ifmycollectionkey null locklocker mycollectionkey dosomethingexpensive dosomethingwithresultmycollectionkeyexample 2private static somecollection mycollectionprivate static object lockerprivate void dosomethingstring key locklocker ifmycollectionkey null mycollectionkey dosomethingexpensive dosomethingwithresultmycollectionkeyexample 3private static somecollection mycollectionprivate static object lockerprivate void dosomethingstring key ifmycollectionkey null locklocker ifmycollectionkey null mycollectionkey dosomethingexpensive dosomethingwithresultmycollectionkeyi always lean towards example 3 and heres why i think i am doing the right thingthread 1 enters dosomethingstringmycollectionkey null so thread 1 obtains a lock just as thread 2 entersmycollectionkey null is still true so thread 2 waits to obtain the lockthread 1 calculates the value for mycollectionkey and adds it to the collectionthread 1 releases the lock and calls dosomethingwithresultmycollectionkeythread 2 obtains the lock by which time mycollectionkey nullthread 2 does nothing releases the lock and continues on its merry wayexample 1 would work but there is a big risk that thread 2 could redundantly calculate mycollectionkeyexample 2 would work but every thread would obtain a lock even if it did not need to which could be a admittedly very small bottleneck why hold up threads if you do not need toam i overthinking this and if so what is the preferred way of handling these situations,['c#'] +372415,need help in using predicatebuilder i need to know about using predicatebuilder on almost every example of how to use it they show the code as followsvar predicate predicatebuildertrueemployeeif stringisnulloremptytxtaddresstext predicate predicateande1 e1addresscontainstxtaddresstextif stringisnulloremptytxtempidtext predicate predicateande1 e1id converttoint32txtempidtextif stringisnulloremptytxtdesctext predicate predicateande1 e1desccontainstxtdesctextif stringisnulloremptytxtnametext predicate predicateande1 e1namecontainstxtnametextemployeedatacontext edb new employeedatacontextvar emp edbemployeeswherepredicategrdemployeedatasource emptolistgrdemployeedatabindwhat is that employee object the one between the greater than and less than brackets i have racked my brains on that one i am using linq to sql entities and i get compile errors when i try this myself i think the errors are something likecannot cast from a linq table toi am a beginner please forgive me for asking what may be an obvious thing thank you,['sql'] +372423,how to get the absolute path of the current javascript file name i have a javascript file named mainjsinside mainjs i want to get the absolute path of this current file something likehttpserverappmainjshttpserverappscriptmainjswhat is the fastest way to get the absolute path,['javascript'] +372464,findclass from any thread in android jni androids jni tips page mentions this faq why did not findclass find my classthey mention multiple solutions and the last option there is this onecache a reference to the classloader object somewhere handy and issue loadclass calls directly this requires some effortso i tried to get it working and it seems that no matter what this method simply does not work for me eventually i figured how to use classloader but it would not work if from a native thread i try to loadclass that has not been touchedloaded yet essentially it is the identical to envfindclass in behavior when called from a native thread with the exception that it would not return 0 for classes that were already use in the app any idea if i did not get it right or it is impossible to access classes from a native thread that werent usedloaded yetedit i will give more info to explain what exactly i mean there is regular jni envfindclassclassname and another one that i wrote myfindclassenv classname that uses cached classloaderloadclassthe class that i am trying to access from native cc is comnonametestclient inside myfindclass i also use envfindclass and log value that it returnsjclass myfindclassjnienv env const char name jclass c0 envfindclassname jclass c1 jclassenvcallobjectmethodclassloader mid loadclass envnewstringutfname dlogmyfindclas c0p c1p c0 and c1 are same d name c0 c1 envissameobjectc0 c1 then i have these 3 combinations to explain the issue1inside jni onload threadmyfindclassenv comnonametestclientinside native thread created by pthread createmyfindclassenv comnonametestclienti get this logcatmyfindclasscomnonametestclent c00x41b64558 c10x41b64558 c0 and c1 are same 1 myfindclasscomnonametestclent c00 c10x41b64558 c0 and c1 are same 02inside jni onload threadenvfindclasscomnonametestclientinside native thread created by pthread createmyfindclasscomnonametestclienti get this logcatmyfindclasscomnonametestclent c00 c10x41b64558 c0 and c1 are same 03inside jni onload threadcomnonametestclient is not touched from jni onloadinside native thread created by pthread createmyfindclassenv comnonametestclienti get this logcatmyfindclasscomnonametestclent c00 c10 c0 and c1 are same 1basically my issue is that classloader does not find my class in the 3rd case is it a bug what can be done to fix the problemedit2on top of that it seems that classloaderloadclass is plainly buggy if i ask myfindclassnonametestclent then it returns some garbage and when i use that returned jclass in any way the app crashes,"['android', 'c++']" +372549,uicollectionview how to define a uicollectionviewlayout that supports horizontally and vertically scrolling at the moment i am trying to create an uicollectionview that should thisplay a simple excellikespreadsheet with rows and columns this should be an easy task with uicollectionviews i believed and i really would like to do the implementation in uicollectionview not in any grid frameworkbut at the moment i am hanging a little bit what i have figured out is that i unfortunately cannot use a uicollectionviewdelegateflowlayout because this only supports scrolling in either horizontally or vertically direction but i need scrolling in both directionstherefore i have to use a uicollectionviewlayout but for this i did not find good examples how to use it has anyone of you an example how to subclass an uicollectionviewlayout to support rows and columnsthanks in advance,['objective-c'] +372577,oncreateoptionsmenu is never called i am having some trouble getting an options menu working in android i build apps before and they all worked fine but now the menu just does not pop upthe code overridepublic boolean oncreateoptionsmenumenu menu superoncreateoptionsmenumenu getmenuinflaterinflatermenuactivity video menu return truethe whole method is never even called checked by setting a breakpoint the activity is supersimple it just has a videoview in it with an ontouchlistener set i am using android 404 on a samsung galaxy 101 api level 15 minsdk 15 am i missing something,['android'] +372655,is it possible to access a local printer using tcpip sockets in php i know that php has it is own pecl to do this but i am currently using php 54 and the php printerdll is not compiled for this version,['php'] +372660,cartesian product in pandas i have two pandas dataframesfrom pandas import dataframedf1 dataframecol112col234df2 dataframecol356 what is the best practice to get their cartesian product of course without writing it explicitly like medf1 df2 cartesian productdf cartesian dataframecol11212col23434col35566,['python'] +372675,how to execute code before windowload and after dom has been loaded ok so here is the circumstancei have 2 pages 1 x html page 1 x external javascriptnow in the html page there will be internal javascript coding to allow the placement of the windowonload and other page specific methodsfunctionsbut in the external javascript i want certain things to be done before the windowonload event is triggered this is to allow customized components to be initialized firstis there a way to ensure initialization to occur in the external javascript before the windowonload event is triggeredthe reason i have asked this is to attempt to make reusable code build once use all over to which the external script must check that it is in ordercheck before the javascript in the main htmljspaspphp page takes over and also i am not looking for a solution in jquery here are some of the links on stackoverflowcom i have browsed through for a solution javascript how to detect if document has loaded ie 7firefox 3 how to check if page has fully loadedscripts and all execute javascript when page has fully loadedcan someone help or direct me to a solution your help will be muchness of greatness appreciated please thanks dregards craigupdated response 19 november 2012hi all thanks for you advice and suggested solutions they have all been useful in the search and testing for a viable solutionthough i feel that i am not 100 satisfied with my own results i know your advice and help has moved me closer to a solution and may indeed aid others in a similar situationhere is what i have come up withtest pagehtmlhtmlheadtitletitlescript typetextjavascript srcloaderjsscriptscript typetextjavascript srctest script 1jsscriptscript typetextjavascript srctest script 2jsscriptscript typetextjavascriptwindowonload function documentgetelementbyiddiv 1innerhtml windowonload completescriptstyle typetextcssdiv borderthin solid 0 width500pxheadbody div iddiv 1div brbr div iddiv 2div brbr div iddiv 3divbodyhtmlloaderjsvar loader methods arr init loader new function documentonreadystatechange functione if documentreadystate complete for var i 0 i loadermethods arrlength i loadermethod arri load functionmethod loadermethods arrpushmethod test script 1jsloaderloadfunctioninittestscript1function inittestscript1 documentgetelementbyiddiv 1innerhtml test script 1 initializedtest script 2jsloaderloadfunctioninittestscript2function inittestscript2 documentgetelementbyiddiv 2innerhtml test script 2 initializedthis will ensure that scripts are invoked before invocation of the windowonload event handler but also ensuring that the document is rendered firstwhat do you guys think of this possible solutionthanking you all again for the aid and help d,['javascript'] +372698,how to use different background images for different resolutions in android i am doing an android app for android tablets that has a full image background but i cannot use a 9patch so i need the background to be as close as posible as the window sizewhat i have testedi have tested using the drawableldpi drawablemdpi etc folders but as i want the images to fit the window it does not work that well now i am trying with the drawablewxdp folders to have images with sizes that are close to the real window size so i have this folder structure each folder with a different image ie images of same size are different on different foldersdrawablew800dpmdpi 800x600px imagedrawablew800dphdpi 800x600px imagedrawablew1024dpmdpi 1024x600px imagedrawablew1024dphdpi 1024x600px imagedrawablew1280dpmdpi 1280x800 imagedrawablew1280dphdpi 1280x800 imagedrawablew1280dpxhdpi 1280x800 imagethe problem is that when i test the app on different tablets it does not always take the image from the expected folderfor instance in a 1280x800px and 160 dpis tablet that reports using thisplaymetrics a window size of 1280x752 it uses the 1280x800px image from the drawablew1280dpmdpi folder and cuts a bit of the image from the top and the bottom but on a 1280x800px and 213dpis tabletthat reports a window size of 1280x736 it takes the image from the drawablew800dphdpi i would expect to take it from other folder like one of the drawablew1024dp folders but not from that oneon the other hand if i try on the emulator with a configuration like 1024x600px and 160dpis that reports a window size of 1024x552 it gets the image from the drawablew1024dphdpi folder but it scales it down and centres it on the screen so i end with very big border all around the imagefilesthe testing layout i am using isrelativelayout xmlnsandroid xmlnstools androidlayout widthmatch parent androidlayout heightmatch parent imageview androidididappbackground androidlayout widthmatch parent androidlayout heightmatch parent androidscaletypecenter androidsrcdrawablebackground image toolsignorecontentdescription relativelayout and on my manifest file i haveusessdk androidminsdkversion13 androidtargetsdkversion15 supportsscreens androidanydensitytrue androidlargescreenstrueandroidnormalscreenstrue androidsmallscreenstrueandroidresizeabletrueupdatemy activity codepublic class screentest extends activity private int width private int height private int dpis private string sdpis override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate ask for a full screen window requestwindowfeaturewindowfeature no title getwindowsetflagswindowmanagerlayoutparamsflag fullscreen windowmanagerlayoutparamsflag fullscreen setcontentviewrlayoutactivity screen test nonjavadoc see androidappactivityoncreateviewjavalangstring androidcontentcontext androidutilattributeset override public view oncreateviewstring name context context attributeset attrs return superoncreateviewname context attrs nonjavadoc see androidappactivityonstart override protected void onstart todo autogenerated method stub superonstart get the info about the screen thisplay thisplay getwindowmanagergetdefaultthisplay width thisplaygetwidth sizex height thisplaygetheight thisplaymetrics outmetrics new thisplaymetrics thisplaygetmetricsoutmetrics dpis outmetricsdensitydpi sdpis switch dpis case thisplaymetricsdensity default sdpis 160 break case thisplaymetricsdensity high sdpis 240 break case thisplaymetricsdensity low sdpis 120 break case thisplaymetricsdensity xhigh sdpis 320 break default sdpis dpis break logddpis dpis dpis sdpis sdpis width width height height override public boolean oncreateoptionsmenumenu menu getmenuinflaterinflatermenuactivity screen test menu return true summaryso i do not know how to predict from wich folder is the app going to take the image and what it will do with it scale cropextra backgroundi have checked all the questions on the androidresoruces tag i have read several times the official documentationsuporting multiple screensproviding resources best matchand some related questions how to findout the best matchandroid resources abest matcha fallback logicdynamic bitmap drawable in android why android uses resources from the higher resource instead of a lowerupdate fixed typos in the folder names,['android'] +372719,partial ungrouping list of duplicate values i know how to group data using linq and i know how to split it into separate items but i have no idea how to only partially ungroup it i have a set of data which looks something like this var data new dictionaryheader detail new header new detail parts new liststring part1 part1 part2 in order to process this correctly i need every instance of a duplicate part to be a separate entry in the dictionary although it does not matter if it remains a dictionary ienumerablekeyvaluepairheader detail is perfectly acceptable however i do not want to split up the parts list entirely having different parts in the list is finespecifically i want the end data to look like this new header new detail parts new liststring part1 part2 new header new detail parts new liststring part1 for a more complex examplevar data new dictionaryheader detail new header1 new detail parts new liststring part1 part1 part2 new header2 new detail parts new liststring part1 part2 new header3 new detail parts new liststring part1 part2 part2 part2 part3 part3 var desiredoutput new listkeyvaluepairheader detail new header1 new detail parts new liststring part1 part2 new header1 new detail parts new liststring part1 new header2 new detail parts new liststring part1 part2 new header3 new detail parts new liststring part1 part2 part 3 new header3 new detail parts new liststring part2 part3 new header3 new detail parts new liststring part2 any advice,['c#'] +372752,horizontal uiscrollview having vertical uiscrollviews inside how to prevent scrolling of inner scroll views when scrolling outer horizontal view could not find a solution for thati am building an app with big scroll view who has paging horizontalinside this scroll view there is a grid of uiviews and an uiscrollview inside each one of them with vertical scroll viewnow the point is when i am paging my big scrollview sometimes the touch get stuck in one of small scrollviews inside the uiviews of the grid i do not know how to avoid it tried trick with hittest but still could not find the answerhope i am clearthanks for your helpeditthis is the bigger scrollviewimplementation uigridscrollview idinitwithframecgrectframe self super initwithframeframe selfpagingenabled return selfendnow to this uigridscroll view i added as a subview this viewimplementation uinoteviewiboutlet uiscrollview innerscrollview this scrollview frame is in the size of the all uinoteview voidawakefromnib innerscrollviewcontentsize cgsizemake innerscrollviewframesizewidth innerscrollviewframesizeheight500fendthe paging works well the inner scroll view works well but too many times when i paging the bigger note view my finger get stuck in the innerscrollviewthanks,"['objective-c', 'ios']" +372814,phpmongodb uncaught exception mongocursorexception with message no such file or directory i am working on a web application which is trying to connect to a mongodb database from phpin the 90 of page loads everything works fine but in the other 10 it throws the following exception when i try to update a collectionfatal error uncaught exception mongocursorexception with message no such file or directory in dwebdevwebsitesstrdev3 global classesuserphp40stack trace0 dwebdevwebsitesstrdev3 global classesuserphp40 mongocollectionupdatearray array array1 dwebdevwebsitesstrdev3 init initphp8 user constructnull2 dwebdevwebsitesstrdev3indexphp3 includedwebdevwebsi3 main thrown in dwebdevwebsitesstrdev3 global classesuserphp on line 40php codepublic function constructsessionid null user users collection main mongoselectcollectionusers query arraysession id session id expiry time main lifetime data array session id session id expiry stringexpiry ip serverremote addr options array upsert true safe true try user users collectionupdatequery arrayset data options catch exception e throw e mongo versionwed oct 17 105348 usrbinmongos db version v207 pdfile version 45 starting help for usagewed oct 17 105348 git version 875033920e8869d284f32119413543fa475227bfwed oct 17 105348 build info linux ip1022940 262172ec2v12fc8xen 1 smp fri nov 20 174828 est 2009 x86 64 boost lib version1 41my mongo cluster has only one shard my php version is 544 and my mongo driver version is 1212,['php'] +372859,can i use ordinary javascript in coffeescript file i am trying to add some javascript code in my ruby on rails application i have already created for me some jscoffee files for each view in my assets since i am not familiar with the coffeescript i just passe some ordinary javascriptjquery line in the file such asif cartlength 1 carthideblind direction vertical 10 cart trnottotal lineremovebut the following error was thrownerror parse error on line 1 unexpected post if in homegotqnaptana projectsdepotappassetsjavascriptscartsjscoffeethe source is pointed on showing homegotqnaptana projectsdepotappviewslayoutsapplicationhtmlerb where line 6 raisedand in this file on line 6 i got javascript include tag application i am new in ruby on rails but what i suppose is happening is that i am not able to write simple javascript in the coffeescript if this is true can i only remove the coffe extension and be sure that the rails magic will work and load the file,"['javascript', 'ruby-on-rails']" +372919,increase pages after each swipe objectivec i have one uiviewcontroller and inside i have 3 uiwebview i added swipe left to my webviews programatically right now i can swipe but just 3 pages and then repeat again i want to increase my currentpage and add this to my webview3 but i do not know how should i do thatwould you please give me some hints i really have problem in this parthere is my code voidviewdidloadsuper viewdidloadnslogtest viewnsurl url nsurl fileurlwithpath nsbundle mainbundle pathforresource namename1 oftypehtml nsurlrequest request nsurlrequest requestwithurlurl webview2 loadrequestrequest webview2 bringtofront nsurl url nsurl fileurlwithpath nsbundle mainbundle pathforresource namename2 oftypehtml nsurlrequest request nsurlrequest requestwithurlurl webview3 loadrequestrequest uiswipegesturerecognizer swipeleft uiswipegesturerecognizer alloc initwithtargetself actionselectorswipeleftactionswipeleftdirection uiswipegesturerecognizerdirectionleftswipeleftdelegate selfselfview addgesturerecognizerswipeleft boolgesturerecognizeruigesturerecognizer gesturerecognizer shouldrecognizesimultaneouslywithgesturerecognizeruigesturerecognizer othergesturerecognizerreturn yescurrentpage is an integer and at the beginning it is 0 my question is how should i add my currentpage to webview3 so that when i swipe it increase my pages voidswipeleftactionidignored nslogswipe leftuiwebview temp webview2 webview2 webview3webview3 webviewwebview tempwebview2 bringtofrontcurrentpage thanks in advanceedit this current page is not connected to any webview how can i get this increase in my webview,['objective-c'] +372962,automatically inserting a header in vim is there a way to auto add a header when i open a new file in vimmy objective is to automatically add the shebang usrbinpython when i open a new file using the command vim testpy if the file is already present no header should be inserted,['python'] +372972,ruby infinite loop i am currently learning ruby and i have gotten stuck on this problem write a deaf grandma program whatever you say to grandma whatever you type in she should respond with huh speak up sonny unless you shout it type in all capitals if you shout she can hear you and yells back no not since 1938 to make your program really believable have grandma shout a different year each time maybe any year at random between 1930 and 1950 you cannot stop talking to grandma until you shout byethis is the code i tried puts say something to grandmasomething getschompwhile something bye if something somethingupcase puts no not since 19 rand3050to s else puts huh speak up sonny endendwhenever i execute this the if and else strings just go on an infinite loop what am i doing wrong here,['ruby'] +372998,redirect traffic of google talk for android i know google talk for android tries to connect to mtalkgooglecom5228 or port 5223 or port 52 but when i am connected to university wifi i cannot use gtalk because all outgoing connection to port 5228 etc are blocked i know also that the google talk services are accessible trought port mtalkgooglecom443 correct me if i am wrongcan i redirect all my outgoing traffic to mtalkgooglecom5228 to mtalkgooglecom443 maybe using an app or using iptables and how can i do,['android'] +373001,how dangerous is setting self class to something else say i have a class which has a number subclassesi can instantiate the class i can then set its class attribute to one of the subclasses i have effectively changed the class type to the type of its subclass on a live object i can call methods on it which invoke the subclas version of those methodsso how dangerous is doing this it seems weird but is it wrong to do such a thing despite the ability to change type at runtime is this a feature of the language that should completely be avoided why or why notdepending on responses i will post a morespecific question about what i would like to do and if there are better alternatives,['python'] +373045,adding items to a collection using entity framework i am trying to follow the d repository pattern with entity framework 4 but i am having problems saving changes to collection properties of my aggregate roots consider my classes below item is my aggregate root which contains a collection of subitem entitiespublic class item public int itemid get set public string name get set public icollectionsubitem subitems get private set public item thissubitems new hashsetsubitem public class subitem public int itemid get set public int subitemid get set public string name get set next i defined a repository interface for my aggregate root classpublic interface iitemrespository item getint id void additem i void saveitem inow here is my dbcontext class that sets up the ef mappingpublic class itemcontext systemdataentitydbcontext protected override void onmodelcreatingsystemdataentitydbmodelbuilder modelbuilder modelbuilderentityitemhaskeyi iitemid modelbuilderentityitempropertyi iname modelbuilderentityitemhasmanyi isubitems withrequired hasforeignkeysi siitemid modelbuilderentitysubitemhaskeyi isubitemid modelbuilderentitysubitempropertyi iname finally heres my implementation of irepository using the dbcontextpublic class repository iitemrespository public void saveitem i using var context new itemcontext contextsetitemattachi contextsavechanges public item getint id using var context new itemcontext var result from x in contextsetitem where xitemid id select xfirstordefault return result public void additem i using var context new itemcontext contextsetitemaddi contextsavechanges the following code creates a new item adds it to the repository adds some new subitems and then saves the changesiitemrespository repo new repositorycreate a new itemitem parent new item name parent repoaddparenta long period of time may pass later add sub itemsparentsubitemsaddnew subitem name child 1 parentsubitemsaddnew subitem name child 2 parentsubitemsaddnew subitem name child 3 save the added sub itemsreposaveparenti get the following exception when the save method tries to attach the item to the contexta referential integrity constraint violation occurred the property values that define the referential constraints are not consistent between principal and dependent objects in the relationshipi realized i am creating a new context for each method in the repository this is intentional a long period of time may pass between when an item is added and then later edited and i do not want to keep the context or database connection open for the entire timenow if i attach the newitem to the second context before adding the sub items as in the code below it works create a new itemitem newitem new item name parent using itemcontext context1 new itemcontext create a new aggrgate context1setitemaddnewitem context1savechangeslong period of time may passusing itemcontext context2 new itemcontext context2setitemattachnewitem newitemname edited name newitemsubitemsaddnew subitem name child 1 newitemsubitemsaddnew subitem name child 2 newitemsubitemsaddnew subitem name child 3 context2savechangeshowever if i want to be true to the repository pattern the code that edits item should not know anything about how the repository works or the itemcontext class it should simply be able to make changes to an aggregate root entity and then save those changes through a repository save methodso how do i modify my save method so that changes to itemsubitems are saved correctly,"['c#', '.net']" +373062,python cannot access nonlocal variable before local variable is defined with same name possible duplicatepython nested functions variable scoping i have used decorators before and so i was surprised to find a bug in my code def make handlername panels def getself admin true keys ndbkeypanel panel for panel in panels panels zipndbget multikeys panels panels panelpanel html if panel else get default contentpanel id panel id for panel panel id in panels templates panels panels admin admin selfrender templatepanel pagehtml templates return typename basehandler get gettraceback most recent call last file cprogram filesgooglegoogle appenginelibwebapp2webapp2py line 1536 in call rv selfhandle exceptionrequest response e file cprogram filesgooglegoogle appenginelibwebapp2webapp2py line 1530 in call rv selfrouterthispatchrequest response file cprogram filesgooglegoogle appenginelibwebapp2webapp2py line 1278 in default thispatcher return routehandler adapterrequest response file cprogram filesgooglegoogle appenginelibwebapp2webapp2py line 1102 in call return handlerthispatch file cprogram filesgooglegoogle appenginelibwebapp2webapp2py line 572 in thispatch return selfhandle exceptione selfappdebug file cprogram filesgooglegoogle appenginelibwebapp2webapp2py line 570 in thispatch return methodargs kwargs file cusersrobertpycharmprojectsbalmoral doctorsmainpy line 35 in get keys ndbkeypanel panel for panel in panelsunboundlocalerror local variable panels referenced before assignmentmy fix is to change panel to panel2 beyond the first usagedef make handlername panels def getself admin true keys ndbkeypanel panel for panel in panels panels2 zipndbget multikeys panels panels2 panelpanel html if panel else get default contentpanel id panel id for panel panel id in panels2 templates panels panels2 admin admin selfrender templatepanel pagehtml templates return typename basehandler get getnow everything works fine and i am wondering whythis is what i guess happens but i do not knowpanels zipmeans that panels is a local variable that means the function does not look in the outerscope for panelsthis is done before the get function is run and not midway throughi thought it would firstly grab panels from the outer function and then when panels gets defined in the inner function after that it would from then on use the new local panels variableam i on the right track,['python'] +373085,regex for allowing alphanumeric and space hi all i am searching for regular expression for allowing alphanumeric or space in javascriptjquery i tired googling but did not able to find thatcan any one help me out with thisthanks in advance,"['javascript', 'jquery']" +373088,arithmetic operators using bitwise operators is there a way to perform additionor arithmetic operations by using only bitwise operators,"['c++', 'c']" +373166,how to style actionbar tab background on selected tab i am struggling with styling the actionbar my app has an actionbar with three tabs i am trying to get the selected tab to have a background color and the unselected tabs to show a different color i am following this reference customizing action bar but all the tabs are showing the selected colormy stylesxml file is as followsstyle namemyactionbartabstyle parentandroidstylewidgethololightactionbartabbar item nameandroidbackgrounddrawabletab backgrounditem item nameandroidpaddingleft32dpitem item nameandroidpaddingright32dpitemstyle style namemyactionbartabbarstyle parentandroidstylewidgethololightactionbartabbar item nameandroidbackgrounddrawablereditemstyle style nameappthemelight parentandroidstylethemehololight item nameandroidactionbarstylestyleactionbarlightitem item nameandroidactionbartabstylestylemyactionbartabstyleitem item nameandroidactionbartabbarstylestylemyactionbartabbarstyleitemstyletab background is just a 9 patch i am also not sure if i am inheriting the action bar tab from the correct parent parentandroidstylewidgethololightactionbartabbar i have looked through the references find it very difficult to understand the style hierarchywhy wont my tabs show selected or no thanks in advance for your assistance,['android'] +373172,how to add android tools dir to windows 7 path i like to quickly start hierarchyviewer at the moment i use the prompt to go navigate to appdatalocalandroidandroidsdktools and then hierarchyvieweri think i need to add something to windows 7 path but i do not know what to do exactlyany suggestionsregards,['android'] +373176,clone a and also increment the name attribute of elements inside by 1 i have to implement a add new row feature in a form the structure of the form is something liketabletr tdinput typetext namev1label td tdinput typetext namev1observation td tdinput typetext namev1remarks tdtrtr tdinput typetext namev2label td tdinput typetext namev2observation td tdinput typetext namev2remarks tdtrtr td colspan3 input typebutton idaddrow valueadd one more rownbsp input typesubmit nameproceed valuesubmit td trtableas seen with each row there is an increase in v number v1 v2and so onwhat i am looking forwhen add one more row button is clicked the following things should happena new row gets inserted just above the last row the row withbuttonsthe name attribute value increases by 1 ie v2label becomesv3label v2observation becomes v3observation and so on in thatrowwhat i triedthe closest i came to was using jquerys clone this does add the row perfectly but i am finding it difficult to find a way to increase the value of the name attribute by 1 each time the button is clickedjquery being used currentlyinputbuttonidaddrowclickfunction var secondlast table trlastprevtr secondlastcloneinsertbeforesecondlastif i click the button two times i am getting the following html addedtr tdinput typetext namev2label td tdinput typetext namev2observation td tdinput typetext namev2remarks tdtrtr tdinput typetext namev2label td tdinput typetext namev2observation td tdinput typetext namev2remarks tdtrso a row is being added but the name attribute remains at v2 whereas it should be v3 and v4 for the third and fourth row i understand clone cannot do that and that is why i am looking for an alternative,"['javascript', 'jquery']" +373230,is there a way to use phantomjs in python i want to use phantomjs in python i googled this problem but could not find proper solutionsi find ospopen may be a good choice but i could not pass some arguments to itusing subprocesspopen may be a proper solution for now i want to know whether there is a better solution or notis there a way to use phantomjs in python,['python'] +373237,magento get price including tax in a nonetemplate file at the moment i am trying to get the product price including tax in a php file for my product feed i have this code at the moment product magegetmodelcatalogproductloadproductid priceincludingtax thishelpertax getprice product productgetfinalpriceproblem is that since that of course the this part does not work so well from the fileanyone know how i can still get the price including tax in this file,['php'] +373254,do web audio api events run in a separate thread i am particularly interested in the onaudioprocess of the scriptprocessornode until recently called javascriptnode it is an event listener which is called periodically for audio processing does it run in a separate thread i would want to feed the data to a circular buffer and process it outside of this callback so i do not hog the cpu i can use web workers for the async processing but afaik i would need a different implementation of the ring buffer in the case of different threadsis there a way to test this,['javascript'] +373283,ajax post not working jquery phonegap android hello everyone and thanx in advancei am using phonegap 210in whitelist everything is acceptedaccess uri subdomainstrue access origin subdomainstruei am using this function to call a remote php file from my university web servervar postdata thisserialize ajax type post url httpsmartphoneloginphp datatype json data postdata success functiondata alertgood error function alertproblem the php file is just for debug reasons like this phpheadercontenttype applicationjsonsample array namemy name emailmy echo json encodesamplebut ajax request is not happening in eclipse i keep getting this error when i click submitjscallback error request failed with status 0 at fileandroid assetwjscordova210js3743what is more i forgot to add is that i can open the url as a link from the emulatorit works fine html codedoctype html html langen head meta charsetutf8 link relstylesheet typetextcss hrefcssindexcss script typetextjavascript charsetutf8 srcjscordova210jsscript script srcscript script typetextjavascript srcjsindexjsscript titlesmart greenhousetitle head body div idcontainer img srccssimagessmart green housepng classlogo altl1ogo form idlogin form classfirst thisplay label classtitle emaillabel input id1 typeemail classinput size45 nameemail label classtitle passwordlabel input id2 typepassword classinput size45 namepassword input id3 clasubmit type typesubmit valuelogin form div body htmli have searched i think pretty much the whole web2 days searchingeverything has been testedthanx a lot,"['android', 'jquery']" +373318,ec2 jgroups thiscovery for my current project weve decided to deploy our application to amazons elastic computing cloud on some linux boxes we use jgroups for group communication and needed a reliable thiscovery mechanism that did not require preconfiguring each application with the addresses of the other cluster members which is necessary with tcpping and sort of necessary with tcpgossip since we cannot use udp multicast that excludes multicast thiscovery from our optionswe looked into using the s3 ping protocol but after reading that there were some reliability issues with it we decided to roll our own protocol do accomplish this thiscoveryi would love to get some feedback on the simple protocol that we wrote and how it might compare to the s3 ping the one limitation it currently has is that it depends on the aws sdk for javapublic class ec2ping extends thiscovery private static final logger log loggerfactorygetloggerec2pingclass public static final short ec2 ping protocol id 1001 private static final int default jgroups port 7800 static classconfiguratoraddprotocolec2 ping protocol id ec2pingclass the jgroups port number private int port default jgroups port the ec2 client private amazonec2client client the ec2 instance filters private listfilter filters public ec2pingec2ping src thisclient srcclient thisport srcport public ec2ping default constructor required public void setclientamazonec2client client thisclient client public void setfilterslistfilter filters thisfilters filters public void setportint port thisport port public int getport return port override public collectionphysicaladdress fetchclustermembersstring cluster name listphysicaladdress addresses new arraylistphysicaladdress describeinstancesrequest request new describeinstancesrequest if filters null requestsetfiltersfilters describeinstancesresult result clientdescribeinstancesrequest for reservation res resultgetreservations for instance instance resgetinstances string ipaddr instancegetprivateipaddress ipaddress addr try addr new ipaddressipaddr port addressesaddaddr catch unknownhostexception uhe logerrorunable to resolve cluster member address ipaddr return addresses override public boolean isdynamic return true override public boolean sendthiscoveryrequestsinparallel return true i can include my protocol stack configuration if necessary but it is very similar to udp except that instead of multicast thiscovery it uses our ec2ping protocolmy main questions are as followsdoes this present a more reliable solution than the s3 pingdoes the dependency on the aws java sdk negate the usefulness of this solution in terms of contributing back to jgroupsany comments would be greatly appreciated thanks,['java'] +373353,moq when using setup how is equality of method parameters determined i am using the setup method to set up the behaviour of a mocked instance of an interfacethe method i am setting up let us call it dosomething accepts an instance of a class let us call the class foofoo foo existing foo instancemockimyinterface mock new mockimyinterfacemocksetupx xdosomethingfooreturns1the problem i am having is that when i use the mock it never matches the setup so never returns 1 i have overridden equals and gethashcode for foocan anyone help how does moq determine whether the parameters provided to a set up method are equal or not,['c#'] +373360,why is the foreign key part of the primary key in an identifying relationship ok i hope this is an appropriate question for stackoverflow as i am trying to understand a concept rather than fixing a piece of code that would not worki will take a general example of a form parent table and a form field child table logically this would be an identifying relationship since a form field cannot exist without a formthis would make me think that in order to translate the logical relationship into the technical relationship a simple not null for the form id field in the form field table would suffice see the left part of above screenshothowever when i add an identifying relationship using mysql workbench form id is not only not null but also part of the primary key see the right part of above screenshotand when i add a nonidentifying relationship not null is still applied so logically it would actually be an identifying relationship as welli guess this confuses me a little as well as the fact that until now i always simply used the id field as primary keyso i understand the logical concept of identifying vs nonidentifying relationships but i do not understand the technical part why is it as this answer states the right way to make the foreign key part of the childs primary key what is the benefit of these composite primary keys,['sql'] +373388,warning fileattributesatpathtraverselink is deprecated first deprecated in ios 20 i made this function that returns the size of file in documents direcetory it works but i get warning that i wish to fix the functionunsigned long long intgetfilesizensstringpathnsarray paths nssearchpathfordirectoriesindomainsnsdocumentdirectory nsuserdomainmask yesnsstring documentsdirectory paths objectatindex0nsstring getfilepath documentsdirectory stringbyappendingpathcomponentpathnsdictionary filedictionary nsfilemanager defaultmanager fileattributesatpathgetfilepath traverselinkyes warningunsigned long long int filesize 0filesize filedictionary filesizereturn filesizethe warning is fileattributesatpathtraverselink is deprecated first deprecated in ios 20 what is it mean and how i can fix it,['ios'] +373398,working with hmacsha256 in windows store app i am migratingconvertingrebuilding a windows phone 71 app to a windows 8 store appone method i am using in de wp7 app is giving me troubleprivate byte getsha256keystring data string secretkey byte value encodingutf8getbytesdata byte secretkeybytes encodingutf8getbytessecretkey hmacsha256 hmacsha256 new hmacsha256secretkeybytes byte resultbytes hmacsha256computehashvalue return resultbyteslooking at the documentation for windows store apps i came up with this new code which i hoped would give the same result but no i am doing something wrong but whatprivate byte getsha256keystring value string secretkey create a macalgorithmprovider object for the specified algorithm macalgorithmprovider objmacprov macalgorithmprovideropenalgorithmmacalgorithmnameshmacsha256 create a buffer that contains the message to be signed ibuffer valuebuffer cryptographicbufferconvertstringtobinaryvalue binarystringencodingutf8 create a key to be signed with the message ibuffer buffkeymaterial cryptographicbufferconvertstringtobinarysecretkey binarystringencodingutf8 cryptographickey cryptographickey objmacprovcreatekeybuffkeymaterial sign the key and message together ibuffer bufferprotected cryptographicenginesigncryptographickey valuebuffer datareader datareader datareaderfrombufferbufferprotected byte bytes new bytebufferprotectedlength datareaderreadbytesbytes return bytesi am not an expert on cryptography i am not sure what i am doing maybe there is somebody out there who can help methanxjp,['c#'] +373418,dialogfragment with a custom layout causes a crash in my application i have problem with dialog fragment simple dialog with my custom layout is working ok but i want to initiate controls when dialog is showing i am trying to do this in method onactivitycreated but getview return null so i thought that i must set my custom view in oncreateview instead of oncreatedialog and here the error occurs when i use oncreateview then my application crashes here is my codeclass statisticdialog extends dialogfragment override public dialog oncreatedialogbundle savedinstancestate use the builder class for convenient dialog construction alertdialogbuilder builder new alertdialogbuildergetactivity builder setpositivebuttongetstringandroidrstringok new dialoginterfaceonclicklistener public void onclickdialoginterface dialog int id fire ze missiles create the alertdialog object and return it return buildercreate override public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate return inflaterinflaterlayoutstatistics container true override public void onactivitycreatedbundle savedinstancestate superonactivitycreatedsavedinstancestate i open this dialog on button click on activitystatisticdialog dlg new statisticdialog dlgshowgetsupportfragmentmanager missiles and errors1108 180514470 eandroidruntime1075 fatal exception main1108 180514470 eandroidruntime1075 androidutilandroidruntimeexception requestfeature must be called before adding content1108 180514470 eandroidruntime1075 at comandroidinternalpolicyimplphonewindowrequestfeaturephonewindowjava2151108 180514470 eandroidruntime1075 at comandroidinternalappalertcontrollerinstallcontentalertcontrollerjava2341108 180514470 eandroidruntime1075 at androidappalertdialogoncreatealertdialogjava3361108 180514470 eandroidruntime1075 at androidappdialogthispatchoncreatedialogjava35108 180514470 eandroidruntime1075 at androidappdialogshowdialogjava2561108 180514470 eandroidruntime1075 at androidsupportv4appdialogfragmentonstartdialogfragmentjava3851108 180514470 eandroidruntime1075 at androidsupportv4appfragmentperformstartfragmentjava13361108 180514470 eandroidruntime1075 at androidsupportv4appfragmentmanagerimplmovetostatefragmentmanagerjava9071108 180514470 eandroidruntime1075 at androidsupportv4appfragmentmanagerimplmovetostatefragmentmanagerjava10831108 180514470 eandroidruntime1075 at androidsupportv4appbackstackrecordrunbackstackrecordjava6351108 180514470 eandroidruntime1075 at androidsupportv4appfragmentmanagerimplexecpendingactionsfragmentmanagerjava143108 180514470 eandroidruntime1075 at androidsupportv4appfragmentmanagerimpl1runfragmentmanagerjava4201108 180514470 eandroidruntime1075 at androidoshandlerhandlecallbackhandlerjava6151108 180514470 eandroidruntime1075 at androidoshandlerthispatchmessagehandlerjava921108 180514470 eandroidruntime1075 at androidoslooperlooplooperjava1371108 180514470 eandroidruntime1075 at androidappactivitythreadmainactivitythreadjava47451108 180514470 eandroidruntime1075 at javalangreflectmethodinvokenativenative method1108 180514470 eandroidruntime1075 at javalangreflectmethodinvokemethodjava5108 180514470 eandroidruntime1075 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava7861108 180514470 eandroidruntime1075 at comandroidinternaloszygoteinitmainzygoteinitjava5531108 180514470 eandroidruntime1075 at dalviksystemnativestartmainnative method,['android'] +373458,get full path to file while debugging using iis express i have a net application that i am trying to debug and part of my application loads a file from my project this file is located atcusersuser folderdocumentsvisual studio 2012projectsmy project templatesmyfilehtmlin my code i specify a relative path to the file and use the directoryinfo class to get the full directory path to my filestring myfile new directoryinfo templatesmyfilehtmlfullnamehowever this returns the following path extra s as escape characterscprogram filesiis express templatesmyfilehtmli was expecting the path that is returned when debugging in iis express would match the first path i listed not the third why is this is there something else that i need to set up in my project to have it derive the paths properly i am assuming that this would not happen if i deployed my code to a iis7 site but i have not gotten to that testing level yet,"['c#', '.net']" +373500,how to define method in javascript on arrayprototype and objectprototype so that it does not appear in for in loop i want to define helper methods on the arrayprototype and objectprototype my current plan is to do something likearrayprototypefind functiontestfun code to find element in arrayso that i can do thisvar arr 1 2 3var found arrfindfunctionel return el 2 it works find but if i loop over the array in a for in loop the methods appear as valuesfor var prop in arr consolelogprop prints out 1 2 3 findthis will screw up anybody else relying on the for in to just show values especially on objects the later versions of javascript have map and filter functions built into arrays but those do not show up on for in loops how can i create more methods like that which would not show up in a for in loop,['javascript'] +373521,adjust richtextbox font size under high dpi setting my c application includes grids with both simple text boxes and richtext boxes often the richtext boxes contain rich text copied and pasted from elsewhere and often the rtf markup includes hardcoded font size fsxx xx in half points in most cases the rich text font size is the same or close to the simple text font size when the dpi scaling is set to anything other than the default 96 the rich text is thistorted as followsa when the application is not set to be dpi aware the richtext is shown smaller than the simple text and is blurryb when the application is set to be dpi aware the rich text is larger than the simple textis there a means to allow or force the richtext to scale with the simple text short of editing the markup directly,['c#'] +373548,sequence contains no elements linq mvc average i am running into this error i see that the reason is because the average returned at times is 0 which from a data stand point is accurate this sql query works fine but that is because it puts in 0 automatically linq complains and so i tried using defaultifempty but it says it is expecting my viewmodeldim ticketcounts from t in queue where tstatusid 2 and tclosedateyear converttodatetimedatetimenowyear and tresolutiondays 0 group t by column1 ctypetclosedatemonth integer column2 ctypetclosedatetostringm string into g group order by column1 select id column1 month column2 critical gwherefunctiont tpriorityid 1defaultifemptyaveragefunctiont tresolutiondays high gwherefunctiont tpriorityid 2defaultifemptyaveragefunctiont tresolutiondays normal gwherefunctiont tpriorityid 3defaultifemptyaveragefunctiont tresolutiondays low gwherefunctiont tpriorityid 4defaultifemptyaveragefunctiont tresolutiondays total gwherefunctiont tid nothingdefaultifemptyaveragefunctiont tresolutiondaysupdatedthis is the sql query doing the same thing i need vb to doselect datenamemonthtclosedate as month avgcase when tpriorityid 1 then casttresolutiondays as decimal18 2 else 0 end as critical avgcase when tpriorityid 2 then casttresolutiondays as decimal18 2 else 0 end as high avgcase when tpriorityid 3 then casttresolutiondays as decimal18 2 else 0 end as normal avgcase when tpriorityid 4 then casttresolutiondays as decimal18 2 else 0 end as low avgcasttresolutiondays as decimal18 2 as monthly averagefrom tblmaintenanceticket twhere tstatusid 2 and yeartclosedate yeargetdategroup by monthtclosedate datenamemonthtclosedateorder by monthtclosedate,['sql'] +373555,searching two arrays for matches no extra memory i had an interview the other day with amazon and a question they asked me was pertaining to the following problemgiven 2 integer arrays containing any number of elements both positive and negative find numbers that appear in both arraysi was able to solve this problem very easily with hashmaps so it would have on computational complexity but unfortunately this will also have on space complexity this could be done with no extra memory by iterating through all elements in each array but this would be on2the interviewer after i finished explaining the hashmap method asked if i could think of a method that would be on computationally but would not use any extra memory i could not think of any on the fly and have not been able to find a solution for this is there a way of finding these values without using extra memory in linear timenote i have posted this question on careercup but everyone on there does not seem to get the concept that i need it to not use extra space and that it has to be on computationallyhere is the code i used during the interview it works but just is not o1 for spaceimport javautilpublic class arrayfun public static void mainstring args int a 1234 int b 25673212 arraylistinteger matches arrayfunfindmatchesab for int i 0imatchessizei systemoutprintlnmatchesgeti public static arraylistinteger findmatchesint a int b hashmapintegerinteger map new hashmapintegerinteger arraylistinteger matches new arraylistinteger for int i 0ialengthi mapputai0 for int i 0iblengthi if mapgetbi null mapgetbi 0 mapputbi1 matchesaddbi return matches this code will return123edit also when i say no additional space and o1 i am kind of using them interchangeably by no additional space i mean small placeholder variables are fine but allocating new arrays is not,['java'] +373575,eclipse c including header file from my source folder i am pretty new to c and eclipse in general so i apologise if i am missing something fairly obviousthe problem i am having is that i am trying to include a header file in one of my source files but they are in different folders in my project directory i have no idea how i should be including them i have uploaded an image showing my problem with the header file i want to include highlightedif someone could tell me what include statement i should be using them that would be brilliantthanks,['c++'] +373577,how do i import a preexisting python project into eclipse i am using eclipse for python how do i import an existing project into eclipse in the current workspacethanks,['python'] +373605,mac os x equivalent of securezeromemory rtlsecurezeromemory is there a mac os x equivalent of rtlsecurezeromemory securezeromemory a function which zeroes a block of memory but the call will not be optimized away by the compiler,"['objective-c', 'c']" +373631,noninteger class labels scikitlearn quick svm question for scikitlearn when you train an svm it is something likefrom sklearn import svms svmsvcsfittraining data labelsis there any way for labels to be a list of a nonnumeric type for instance if i want to classify vectors as cat or dog without having to have some kind of external lookup table that encodes cat and dog into 1s and 2s when i try to just pass a list of strings i get valueerror invalid literal for float catso it does not look like just shoving strings in labels will work any ideas,['python'] +373657,c11 equivalent of pythons x y z array is there a c11 equivalent to this python statementx y z three value arrayin c you could do this asdouble x y zstdarraydouble 3 three value array assign values to three value arrayx three value array0y three value array1z three value array2is there a more compact way of accomplishing this in c11,['c++'] +373678,rendering css in a go web application i wrote a very basic web application following this tutorial i want to add css rules in an external stylesheet but it is not working when the html templates are rendered something goes wrong and the css is completely ignored if i put the rules in tags it works but i do not want to have to deal with thatin a go web application how do i render an external css stylesheet,"['html', 'css']" +373685,how to add extra object to tasty pie return json in python django in django project i get two objects when i receive the json responsedatameta and dataobjectsthis is my resourceclass myresourcemodelresource def dehydrateself bundle bundledataabsolute url bundleobjget absolute url bundledatamyfields mydatafields return bundle class meta queryset mydataobjectsall resource name weather serializer serializerformatsjson ordering mydatafieldsnow i want to other field in json likedatamyfieldsbut if i do the above way then that field is added to every object likedataobjectsmyfieldshow can i do datamyfields,['python'] +373710,how to access the class variable by string in python the codes are like thisclass test a 1 def init self selfb2when i make an instance of test i can access its instance variable b like thisusing the string btest testa string bprint test dict a stringbut it does not work for a as self dict does not contain a key named a then how can i accessa if i only have a string athanks,['python'] +373721,objectivec continue in collection enumeration block if i have an nsarray and i use enumerateusingblock to loop through elements in the array but in some cases i need to skip the loop body and go to next element is there any continue equivalent in block or can i use continue directlythanksupdatejust want to clarify what i want to do isfor int i 0 i 10 i if i 5 continue do something with iwhat i need is the continue equivalent in block,"['objective-c', 'ios']" +373751,3d visualization realtime in c do you known any 3d visualization library in c that can update plots realtimei am not searching for something spectacular just a replacement for matlab plot3 functionmy main problem is that i need to make plots at a high fps at least 8,['c++'] +373765,interpret xmpmetadata in alassetrepresentation when a user makes some changes cropping redeye removal to photos in the builtin photosapp on ios the changes are not applied to the fullresolutionimage returned by the corresponding alassetrepresentation however the changes are applied to the thumbnail and the fullscreenimage returned by the alassetrepresentationfurthermore information about the applied changes can be found in the alassetrepresentations metadata dictionary via the key adjustmentxmpi would like to apply these changes to the fullresolutionimage myself to preserve consistency i have found out that on ios6 cifilters filterarrayfromserializedxmp inputimageextenterror can convert this xmpmetadata to an array of cifiltersalassetrepresentation rep nsstring xmpstring repmetadataadjustmentxmpnsdata xmpdata xmpstring datausingencodingnsutf8stringencodingciimage image ciimage imagewithcgimagerepfullresolutionimagenserror error nilnsarray filterarray cifilter filterarrayfromserializedxmpxmpdata inputimageextentimageextent errorerrorif error nslogerror during cifilter creation error localizeddescriptioncicontext context cicontext contextwithoptionsnilfor cifilter filter in filterarray filter setvalueimage forkeykciinputimagekey image filter outputimagehowever this works only for some filters cropping autoenhance but not for others like redeye removal in these cases the cifilters have no visible effect therefore my questionsis anyone aware of a way to create redeye removal cifilter in a way consistent with the photosapp the filter with the key kciimageautoadjustredeye is not enough eg it does not take parameters for the position of the eyesis there a possibility to generate and apply these filters under ios 5,['ios'] +373777,is there a pure python implementation of murmurhash i need and cannot find a pure python no c implementation of murmurhash and i am too novice to write myself speed or memory usage does not matter on my projecti find a attempt here but it is limited to 31bits hash and i really need a 64bits hashnote for those who need a fast implementation there is a murmurhash2 library here and a murmurhash3 library here,['python'] +373798,ruby openuri library aborted in 404 http error code i use openuri library object openif server code response is equals to 200 my program acts as i expectedbut if server response code is equals to 400 or other then script aborts with openurihttperror 404 not foundi can avoid this if i use beginrescue construction and handle httperror exceptionis this a correct wayshould i use nethttp library instead of openuri to handle all cases,['ruby'] +373825,do stdfunction and stdbind do dynamic memory allocation if i do this class thing void function const stdstring messagestdliststdfunctionvoid workand in some member of thing workpush backstdbindthingfunction this hellodoes either the call to stdbind or the use of stdfunction cause any dynamic memory allocation using new or otherwise or is all the storage allocated at compile time if the standard does not say anything what about in visual studio 2012 as my program will only need to build on there and for efficiency i probably need to avoid dynamic memory allocations in the place where i am thinking of using this mechanism,['c++'] +373826,can you recover from reassigning builtins in python if i open up interactive mode and type builtins 0 breaks everythinghave i completely broken the session if so what is going on behind the scenes to assign builtins to the builtin module that cannot be handled by the interpreter if not how can i recover from thisjust a few of my own attempts to fix itany attempt to import anything results in an error importerror import not foundall functions i might use to do anything other than evaluate numerical expressions are brokenthere is another variable package still accessible but i do not know ifhow it can be used,['python'] +373830,restrict keyword and pointers inside structs by using the restrict keyword like thisint fint restrict a int restrict bi can instruct the compiler that arrays a and b do not overlap say i have a structurestruct sint ipand write a function that takes two struct s objectsint f2struct s a struct s bhow can i similarly instruct the compiler in this case that aip and bip do not overlap,['c'] +373852,backtrace symbols with both static and rdynamic looking at this question and this question i can see that for backtrace symbols to work one must compile with the rdynamic flagi have tried it into a test program and it works but i am writing a program that is also compiled with static and this page says that backtrace symbols does not work when static is passed to the compilerlinkeris there any quick workaround to this or i will never have a humanreadable backtrace function in my statically linked program,"['c++', 'c']" +373920,storing passwords in mysql use a hash right but how do you send the user a forgotten password i have been looking into storing user passwords in mysql and the ubiquitous reply is to store it using an encryption algorithm like md5 or sha1 but what if user x forgets her password and wants it to be sent to her what then i cannot send her the md5 hash how is this issue dealt with in the real world are there two databases one to compare hashes and another for forgotten passwords but whats the difference both would be readonly by the sql user connecting to it at that time so how do you do it thanks,"['mysql', 'sql']" +373930,change the default value of boolean i am writing an application where i have quite a lot properties of type boolean defined private bool kajmak true public bool kajmak get return kajmak set kajmak value firepropertychanged kajmak as you see i set kajmak to true at the beginningthe reason is nonrelevant you might know that the default value of a bool variable is falsenow is there a way to change the default value of a bool to true so i would writeprivate bool kajmak kajmak trueinstead ofprivate bool kajmak truewhat could i do to achieve this,['c#'] +373944,replace element contents with document fragment javascript i am trying to replace all contents of an element with a document fragmentvar frag documentcreatedocumentfragmentthe document fragment is being created just fine no problems there i add elements to it just fine no problems there either i can append it using elementappendchildfrag that works just fine tooi am trying to create a replace method similar to jquerys html i am not worried about oldbrowser compatibility is there a magical function to replace all content of an element i have tried elementinnerhtml fragclonenodetrue as per every replace element content wiki i could find that does not work it gives me divobject documentfragmentdivno libraries pleasethat means if you put a jquery solution as an answer you will get downvoted not trying to be a jerk but it happens every timethanksedit for clarity i am looking for a magic solution i know how to remove all the existing elements one at a time and then append my fragment,['javascript'] +373985,how can i find a memory leak on heroku i have a rails 328 app running on heroku cedar with ruby 193 the app runs fine when it launches but after a day or so of continuous use i start to see r14 errors on my logs once the memory errors start they never go away even if the app is idle for several hoursshouldnt the garbage collector clean up unused objects after a while and reduce the memory load it seems this is not happening on heroku generally memory usage starts to creep up after running some reports with several thousand rows of data although results are paginatedhow can i find the memory leak plugins like bleak house are way out of date or dont run nicely in the heroku environment can i adjust the gc settings to make it more aggressive,"['ruby-on-rails', 'ruby']" +373995,is a string formatter that pulls variables from its calling scope bad practice i have some code that does an awful lot of string formatting often i end up with code along the lines offormatxx yy zz foofoo where i am trying to interpolate a large number of variables into a large stringis there a good reason not to write a function like this that uses the inspect module to find variables to interpolateimport inspectdef interpolates return sformatinspectcurrentframef backf localsdef generatethestringx y foox z x y more calculations go here return interpolatex y z,['python'] +374014,how do i plot just the positive error bar with pyplotbar i am trying to plot 4 average values with positive error bars and the max value within the plotmeans 268226461176155 mean data stds 459439437438 standard deviation datapeakval 268226461176155 string array of meansind nparangelenmeanswidth 035colours redbluegreenyellowpyplotfigurepyplottitleaverage agefor i in rangelenmeans pyplotbarindimeansiwidthcolorcoloursialigncenteryerrstdsiecolorkpyplotylabelage yearspyplotxticksindyoung maleyoung femaleelderly maleelderly femaledef autolabelbarspeakval for iibar in enumeratebars height barsii pyplottextindii height5 s peakvalii hacenter vabottomautolabelmeanspeakval however i can cannot find out how to plot only the positive error bars so i end up with a graph like thisany suggestions would be greatly appreciated,['python'] +374045,populate an array using constexpr at compiletime i would like to populate an array of enum using constexprthe content of the array follows a certain patterni have an enum separating ascii character set into four categoriesenum type alphabet number symbol otherconstexpr type table128 blah blah i would like to have an array of 128 type they can be in a structurethe index of the array will be corresponding to the ascii characters and the value will be the type of each characterso i can query this array to find out which category an ascii character belongs to something likechar c randomfunctionif tablec alphabet dosomethingi would like to know if this is possible without some lengthy macro hackscurrently i initialize the table by doing the followingconstexpr bool isalphabet char c return c 0x41 c 0x5a c 0x61 c 0x7aconstexpr bool isnumber char c blah blah constexpr bool issymbol char c blah blah constexpr type whichcategory char c blah blah constexpr type table128 initialize where initialize is the entry point of some very lengthy macro hackssomething likedefine initialize init0define initn init ndefine init 0 whichcategory0 init 1define init 1 whichcategory1 init 2define init 127 whichcategory127i would like a way to populate this array or a structure containing the array without the need for this macro hackmaybe something likestruct table type 128constexpr table table magicfunctionso the question is how to write this magicfunctionnote i am aware of cctype and likes this question is more of a is this possible rather than is this the best way to do itany help would be appreciatedthanks,['c++'] +374222,how to create a phraselist that includes every word wildcard i am trying to create a windows phone 8 application that includes a voice command the voice command goes something along the lines of what are the top songs by artist and so i need to use some kind of wildcard for artist that will allow the user to say any artist how might i do this without listing out every artist in the world in a phraselist,['c#'] +374229,suggestions for digit recognition i am writing an android app to extract a sudoku puzzle from a picture for each cell in the 9x9 sudoku grid i need to determine whether it contains one of the digits 1 through 9 or is blank i start off with a sudoku like thisi preprocess the sudoku using opencv to extract blackandwhite images of the individual digits and then put them through tesseract there are a couple of limitations to tesseract thoughtesseract is large contains lots of functionality i do not need ie full text recognition and requires englishlanguage training data in order to function which i think has to go onto the devices sd card at least i can tell it to only look for digits using tesseractsetvariabletessedit char whitelist 123456789tesseract often misinterprets a single digits as a string of digits often containing newlines it also sometimes just plain gets it wrong here are a few examples from the above sudokui have three questionsis there any way i can overcome the limitations of tesseractif not what is a useful accurate method to detect individual digits not knearest neighbours that would be feasible to implement on android this could be a free library or a diy solutionhow can i improve the preprocessing to target that method one possibility i have considered is using a thinning algorithm as suggested by this post but i am not going to bother implementing it unless it will make a difference,['android'] +374246,image to video conversion with transition effect i am successfully able to convert a sequence of images into a video referring the link but now my requirement is to put some transition effects like fade in fade out to be shown in video with the change of every imageis it possible to do using ffmpeg or should i use something else for thatreferffmpeg convert a series of images to video with crossfade or any other transition between every two framesfor more detailsplease direct me,['android'] +374250,jquery usage in background page of chrome extension goali am trying to use this boilerplate code to look up using a dictionary api online to find the selected word and return the definitionproblemi have tested the actual jqeury ajax call seperatley and it works well also i can get the selected word on the page however for some reason i am having issues actually calling the ajax function within my boilerplate code in samplejsadvisement is neededbackgroundhtml script srcjqueryjs script srcsamplejs body p image here p img idtarget srcwhitepng width640 height480 bodyhtmlmanifestjson name context menus sample description shows some of the features of the context menus api version 06 permissions contextmenus background scripts samplejs pages backgroundhtml manifest version 2samplejs a generic onclick callback function function genericonclickinfo tab consolelogitem infomenuitemid was clicked consoleloginfo jsonstringifyinfo consolelogtab jsonstringifytab alertinfoselectiontext thisplaytextinfoselectiontext consolelogasfasdf testid documenthtmltesting jquery ajax url keymykeyincluderelatedfalseincludetagsfalselimit1 datatype json success functiondata called when successful alertdata0word error functione called when there is an error consolelogemessage create one test item for each context typevar contexts pageselectionlinkeditableimagevideo audiofor var i 0 i contextslength i var context contextsi var title test context menu item var id chromecontextmenuscreatetitle title contextscontext onclick genericonclick consolelog context item id create a parent item and two childrenvar parent chromecontextmenuscreatetitle test parent itemvar child1 chromecontextmenuscreate title child 1 parentid parent onclick genericonclickvar child2 chromecontextmenuscreate title child 2 parentid parent onclick genericonclickconsolelogparent parent child1 child1 child2 child2 create some radio itemsfunction radioonclickinfo tab consolelogradio item infomenuitemid was clicked previous checked state was infowaschecked var radio1 chromecontextmenuscreatetitle radio 1 type radio onclickradioonclickvar radio2 chromecontextmenuscreatetitle radio 2 type radio onclickradioonclickconsolelogradio1 radio1 radio2 radio2 create some checkbox itemsfunction checkboxonclickinfo tab consolelogjsonstringifyinfo consolelogcheckbox item infomenuitemid was clicked state is now infochecked previous state was infowaschecked var checkbox1 chromecontextmenuscreate title checkbox1 type checkbox onclickcheckboxonclickvar checkbox2 chromecontextmenuscreate title checkbox2 type checkbox onclickcheckboxonclickconsolelogcheckbox1 checkbox1 checkbox2 checkbox2 intentionally create an invalid item to show off error checking in the create callbackconsolelogabout to try creating an invalid item an error about item 9 should show upchromecontextmenuscreatetitle oops parentid9 function if chromeextensionlasterror consoleloggot expected error chromeextensionlasterrormessage,['jquery'] +374282,how does boostspirithold any work evidently hold any has better performance than boostany how does it manage to do this edit thanks to mats comment i found an answer by hkaiser about hold any at another question but it lacks details a more detailed answer would be welcome,['c++'] +374307,yet another mingw gcc error createprocess no such file or directory i have installed mingw c compiler in windows 8 64 bit through the gui installerbut when i try to compile a c program gcc says gcc createprocess no such file or directoryit is a common bug and i have tried all the solutions i found without successin particular following createprocess no such file or directory i have tried toedited add cmingwlibexecgccmingw32472 to my system path uninstall and reinstall gcc through mingwget climingwget remove mingw32gccmingwget install mingw32gccother suggestionsedit verbose gcc output gcc v helloworldcusing builtin specscollect gccgcollect lto wrappercmingwbinlibexecgccmingw32472ltowrapperexetarget mingw32configured with gcc472configure enablelanguagesccadafortranobjcobjc thisablesjljexceptions withdwarf2 enableshared enablelibgomp thisablewin32registry enablelibstdcxxdebug thisablebuildpoststage1withcxx enableversionspecificruntimelibs buildmingw32 prefixmingwthread model win32gcc version 472 gcollect gcc optionsv mtunei386 marchi386cc1plus quiet v iprefix cmingwbinlibgccmingw32472optionsc quiet dumpbase optionsc mtunei386 marchi386 auxbase options version o cuserselvisappdatalocaltempcc4fwsvgsgcc error createprocess no such file or directory,['c'] +374313,how to achieve the floatright effect while preserving the inlineblock thisplay consider the following jsfiddle fndyqdjg1htmldiv idcontainer div classchar a div div classchar sticktoright b divdivacsscontainer bordersolid 2px greenchar thisplay inlineblock border solid 2px redsticktoright float rightais there another way to make sticktoright be aligned right without floating iti need to keep it as thisplayinlineblock so that i can make its vertical alignment consistent with other char elementshow can i achieve the floatright rightalignment effect whilst keeping the element thisplayinlineblock note that i do not know the width of the container elementi would like purely css solutions if there are any,"['html', 'css']" +374321,what is the eclipse shortcut for autogenerating a default and field constructor i had a look at eclipseshortcuts but i found nothing for generating a constructor whats the shortcut for generating a standard constructor,['java'] +374338,memory consumption of a dictionary set a value none vs delete the item i understand that del dkey will delete the keyvalue pair whereas dkeynone only dereferences the valuehowever in terms of memory management is there any difference does setting a value none trigger garbage collection immediately assuming that there is no other variable referencing this valuei ran a little experimentin 74 import sysin 75 a a blahin 76 sysgetsizeofaout76 280in 77 aa nonein 79 sysgetsizeofaout79 280in 80 del aain 81 sysgetsizeofaout81 280not sure if the approach is valid but it seems no difference in terms of the size of the dictionary at all i must miss something here,['python'] +374348,eot not working in ie i am importing a font with css however it does not seem to work in ie i do not know whyheres my css code fontface fontfamily bello src urlfontsbelloeot src urlfontsbelloeotiefix formatembeddedopentype urlfontsbellowoff formatwoff urlfontsbellottf formattruetype urlfontsbellosvgbello formatsvg fontweight normal fontstyle normal bello fontfamily bello verdana tahomai have added eot svg woff ttf and otf to the folder fonts it thisplays correctly in all browsers except ie to create the eot file i used this site i have no idea why it is not working any help would be great thanks,['css'] +374352,when to host using a cdn and when not to this question tries to find whether its worth to tradeoff the benefits of a cdn in favor of a more structured and organized vendor code managementi know that using a cdn to deliver vendor libs like jquery is recommended yet i was reading about bower today and it made me wonder with bower i can easily manage all of the dependencies of my application in a very structured way i can eventually pack them up in a single vendorjs file using yeoman brunch or simple grunt that will be server in the html in a script taghowever while this approach can make my life easier what are its cons i can think of the followingthere is high chance that many of the libs i am using are already cached in the users browser by putting it all in a single vendorjs file the browser will eventually cache this file but i will start facing problems whenever i add new thirdparty depencies ie when my vendor file is changed the browser will have to reload that file thus loosing the caching of the original vendorsj fileputting it this way paying the time to manage dependencies in the html as script tags seams to offer a better performanceload timedo you think there is something wrong in my way of thinking is the benefit of organizing code with say bower convincing enough after all its like for backbone yes a backbone app is heavier for small applications it contains more code but from a dev point of view its worth itcheers and thanks for the comments that made me reedit the question,['jquery'] +374396,queries with colon in the search variable using pdo i have an annoying problem i am trying to do something simple as getting a cell value from a dbthis is the most basic thing you can do with a db give me a value where there is a cell with this valuethe problem is that the search query contains a colon i am using pdo function in a class with prepared statements but no lucki have tried everything even dividing up the query so it wont contain a colon but still no luck i have tried to revert to mysqli but still the same resultthe data table contain values like title morlanda c2 and sourceid s11btw if i try to search for an title in phpmyadmin i will get what i want when i look for morlanda c2 but when i am calling my function thislysourceid sourcessourceavalibemorlanda c2i am accessing my functionpublic function sourceavalibesourcetitle try sql select sourceid from sources where titlesourcetitle core coregetinstance stmt coredbhpreparesql stmtbindparamsourcetitle sourcetitle pdoparam str 32 stmtexecute row stmtfetchpdofetch assoc return row then the result will be emptybut if i call the function like this sourceid sourcessourceavalibe1910 massachusetts censusthe result will return what i am looking forthe result will be an empty if the query contains a colon but will return the correct sourceid if i it contains something without an colon i have tried to escape the colon in different ways but it wont find a result then eithercan you please help me before i go bananasupdate 1hithanks for your answers the data i am searching for is exactly the same as in the db using copypaste i have looked for evil white spaces but nothing extra was found i have now switched to bindvalue insteadregarding the comment about thisable emulating of prepared statements my answer is que i have now found what you where talking about regarding emulating in this article best way to prevent sql injection and have updated my constructor class i am still getting the same result tho nothing i am using this constructor class for my db connectionsclass core public dbh private static instance function construct thisdbh new pdomysqlhostdb hostdbnamedb name db user db pass arraypdomysql attr init command set names utf8 pdoattr emulate prepares false public static function getinstance if issetselfinstance object class selfinstance new object return selfinstance update 2hiwhen i hard code the search value morlanda c2 into my sql line everything works as intended so i did a comparison of my php generated title sourcetitle sourcepretitle pretitlenumber0 pretitlenumber1with orginalstring morlanda c2and they did not matchdid a type check but both came out as stingsi am starting to think that it is the old utf8 encoding problem that is messing with me heremy database table and cell is set to utf8 unicode cithe pdo connection is utf8 and have encoded the php files with ansi with utf8 without bom using notepad the whole project here is to turn a genealogy note to a source so i am collection a long string from a table in the same database and exploding it and then assemble some pieces into tho a sourcetitle like above i then searching the database to see if the source already exists if not then i just create a new one the collection of the data and searching for the sourcetilte is done by the same pdo class update 3hiit was a stupid white space or something similari did use trim at the sourcetitle variable but not on each piece in the array from the explode function when i did that it worked i guess it was a endline or something after the last number that messed with methanks for your help i can now finally convert my 30 notes to sources next project is how to prevent my scripts custom to choke my vps,"['php', 'mysql']" +374446,equivalent of settimeout and setinterval function in script how to use settimeout and setinterval method in c with scriptfor example how to write setintervalfunctionalerthello30,"['c#', 'javascript']" +374453,how to understand this crash log i got in itc below presented crash report for my first mac app store appusing knowledge founded on stackoverflow i tried to symbolicate this log but using atos and otool i was only able to read last 20 line which means start in my app 52 i really do not know how to interpret lines above and how to find cause of crash process my app 270identifier commycompanymyappversion 100 100app item id 568750app external id 11410code type x8664 nativeparent process launchd 143user id 501datetime 20121107 1921365 0200os version mac os x 1082 12c60report version 10perapp interval since last report 1232 secperapp crashes since last report 1crashed thread 0 thispatch queue comapplemainthreadexception type exc bad access sigsegvexception codes exc i386 gpfltthread 0 crashed thispatch queue comapplemainthread0 libobjcadylib 0x07f877a5256 objc msgsend 221 comappleappkit 0x07f8dac6e27 nsoutlineview delegate isgrouprow 662 comappleappkit 0x07f8da46878 nstableview isgrouprow 813 comappleappkit 0x07f8da41fad nstableview issourcelistgrouprow 564 comappleappkit 0x07f8da418e8 nstableview rectofrow 2885 comappleappkit 0x07f8da5b3cb nstvvisiblerowsforupdate 2966 comappleappkit 0x07f8da5aa85 nstablerowdata unsafeupdatevisiblerowentries 967 comappleappkit 0x07f8da5a8a1 nstablerowdata updatevisiblerowviews 1198 comappleappkit 0x07f8da6e463 nstablerowdata idleupdatevisiblerows 669 comapplecorefoundation 0x07f87547da4 cfrunloop is calling out to a timer callback function 2010 comapplecorefoundation 0x07f875478bd cfrunloopdotimer 55711 comapplecorefoundation 0x07f8752d099 cfrunlooprun 151312 comapplecorefoundation 0x07f8752c6b2 cfrunlooprunspecific 29013 comapplehitoolbox 0x07f830a30a4 runcurrenteventloopinmode 20914 comapplehitoolbox 0x07f830a2e42 receivenexteventcommon 35615 comapplehitoolbox 0x07f830a2cd3 blockuntilnexteventmatchinglistinmode 6216 comappleappkit 0x07f8d8d8613 dpsnextevent 68517 comappleappkit 0x07f8d8d7ed2 nsapplication nexteventmatchingmaskuntildateinmodedequeue 12818 comappleappkit 0x07f8d8cf283 nsapplication run 51719 comappleappkit 0x07f8d873cb6 nsapplicationmain 86920 commycompanymyapp 0x010f29ce1c 0x10f29b0 7708,['objective-c'] +374461,mock networkstreamread i have been trying to mock a network stream for some unit testsso far using moq the best i have come up with is to use a wrapper for the stream and then mock my interface public interface inetworkstreamwrapper int readbyte buffer int offsetint size void flush bool dataavailable get bool canread get void closequestion is whilst that gives me a start i actually want to test some byte array values as read into my read buffer how can i return some test data into the buffer when calling read on the mock object,"['c#', '.net']" +374498,debugging an aspnet mvc application on an android phone objectivei am looking for the simplestpossible stepbystep setup process for debugging my aspnet mvc 4 application using my ip address as the url i want to be able to access the application from my android phone which is connected to my local network via wifi using my computers local ip address eg i am running visual studio 2012 rc on windows 7this question has been addressed by two other questions this one and this one but the answers are extremely brief and are not helping me at all i have had to resolve this issue before by banging on my computer and mindlessly changing every setting until something worked i do not want to have to go through that again i want to understand what i am doing this timesetup informationthe project is just a default aspnet mvc 4 internet application i am pretty sure i have not changed anything yetthe web tab in my applications properties is set to use local iis web server and i have use iis express checked the project url is httplocalhost25968 i see that the locahost there might be a problem but vs would not let me put in an ip address or wild cardsmy iis express applicationhostconfig file for my application are as followssite nameapplication name id13 application path applicationpoolclr4integratedapool virtualdirectory path physicalpathcusersusernamedocumentsvisual studio 11projectsapplication name application bindings binding protocolhttp bindinginformation25968localhost bindingssitewhats happeningwhen i connect to the site from the host computer with httplocalhost25968 it works great if i try to use from the host computer i get bad request invalid hostname http error 400 the request hostname is invalid using this same url from another computer on the network it just times out,['android'] +374586,invalid packaging for parent pomxml must be pom but is ear could anybody suggest me an solution with the following exception i am going to create a multimodule project parent project name is logicbackendchild project name is dbaccessi need to have ear file of logicbackend which should contain dbaccess prjoects jar file i am getting following exception when i run mav clean install p developer errorthe project comproject1databasedbaccess10snapshot cproject1dbaccesspomxml has 1 errorerrorinvalid packaging for parent pom comproject1logiclogic10snapshot cproject1pomxml must be pom but is ear comproject1logiclogic10snapshot cproject1pomxml line 6 column 13this is how part of my parent pomxml looks modelversion400modelversiongroupidcomproject1logicgroupidartifactidlogicbackendartifactidpackagingearpackagingversion10snapshotversion this is how child pomxml looksgroupidcomproject1logicgroupidartifactiddbaccessartifactidpackagingejbpackagingnamedbaccessnameversion10snapshotversionparent groupidcomproject1logicgroupid artifactiddbaccessartifactid version10snapshotversion relativepathpomxmlrelativepathparentcould anybody help me here to understand what is going wrong here thanks in advance for any help,['java'] +374602,warning window hierarchy when loading delegate today i update my xcode and started updating my app for the new iphone 5 screen i suddenly notice that every time i go from screen a to screen b i get this warningwarning attempt to present on whose view is not in the window hierarchy this delegate method prepares the segue from screen a dilemmaviewcontroller to screen b optionsviewcontroller voidprepareforsegueuistoryboardsegue segue senderidsender executes the following if statement if the user wants to add new options if segueidentifier isequaltostringaddoptions uinavigationcontroller navigationcontroller seguedestinationviewcontroller optionsviewcontroller controller optionsviewcontroller navigationcontrollertopviewcontroller controllerdelegate self if the user has already put some inputs on the form we send them through the segue if edit count 0 controlleredit edit i have not touched this since the first version of my app so i am not sure of what can be happening here i have looked around the web and some people talk about moving code from viewdidload to viewappear but i do not think that applies to this scenarioany idea of what could be happeningthanks in advanced,['ios'] +374603,why does the void wrapper class exists in the jdk possible duplicateuses for the java void reference type what is the real usage of void class in real world problems in which scenario can we use this class,['java'] +374620,how to write exif data using custom camera class in android i have a custom camera application that is used to take pictures and crop them to square now i want to know how to write exif data for the final output image specially the orientationhere are the important parts of my codecapturebutton button findviewbyidridbutton capture capturebuttonsetonclicklistenernew viewonclicklistener override public void onclickview v take a picture mcameratakepicturenull null mpicture and this is the call back functionpicturecallback mpicture new picturecallback override public void onpicturetakenbyte data camera camera file picturefile getoutputmediafile if picturefile null return try fileoutputstream fos new fileoutputstreampicturefile foswritedata fosclose catch filenotfoundexception e catch ioexception e updatei added the following to the onpicturetaken method but nothing changedexifinterface exif exif new exifinterfacepicturefilegetabsolutepath notice getorientation method gets an integer with the angle 0 90 180 270 etc exifsetattributeexifinterfacetag orientation stringvalueofgetorientation exifsaveattributes,['android'] +374678,sorting in c swapping pointers leads to unexpected results at the start of the programm i allocate memory for an array of charpointerschar buffer calloc 20 sizeofchar then the user can input up to 20 wordsbufferi calloc 40 sizeofchar fgets bufferi 40 stdin afterwards i want to sort this array it works as expected if i use my swap function as followsvoid swapchar args1 char args2 char tmp40 strcpy tmp args1 strcpy args1 args2 strcpy args2 tmp void sort char args int count swap argsi argsj after thinking through this i noticed that this was a waste of cpu since all i had to do was actually redirecting the pointers to the corresponding stringsso i rewrote my swap functionvoid swapchar args1 char args2 char tmp args1 args1 args2 args2 tmpvoid sort char args int count swap argsi argsj however this will not work at all the results are extremely unexpected i cannot figure out why i tried several printf calls and whatnot my understanding was that the pointers are just redirected and thus swapped let us say the memory looks like thisbegin of char100 160108 200116 240124 280begin of char160 hello0200 world0my idea was to alter the pointers instead of the arrays for minimum cpu effort here swap pointer in 100 with pointer in 108begin of char100 200108 160116 240124 280begin of char160 hello0200 world0i tried to explain this as thorough as i could and i am sorry if it is too much explanationi would be most glad if someone could give me insight into this and helpthe full code with the working strcpy can be found here,['c'] +374740,how to make first launch iphone app tour guide with xcode i would like to know how to make a first launch tour guide for my ios app with xcode i describe myself as a beginner in objectivec language but what i know logically is that i have to make the app to detect the first launch of the application and then thisplay a scrollable tour guide with a skip button on the top to thismissi have searched though the website but did not find the best solution for my questionit is basically two questionhow to detect the first launch of the apphow to detect first time app launchiphonehow to thisplay the the tour guide which probably will be located in the storyboardwhat i want is similar to the tour guide in paper ipad app in appstore,"['iphone', 'objective-c', 'ios']" +374763,is there a twig shorthand syntax for outputting conditional text is there a shorter syntax in twig to output a conditional string of texth1 if not infoid create else edit endif h1traditional php is even easier than thish1php infoid create edit h1,['php'] +374769,how to update statusstrip in windows forms i am trying to update the status strip in my windows forms application but nothing is being thisplayed here is my codeprivate void textbox1 textchangedobject sender eventargs e lines regexsplittextbox1texttrim rn linecount linescount statusstrip1text lines linecount statusstrip1refreshwhat am i doing wrong any examples would be appriciated,['c#'] +374836,c vs java endless loop creating objects only crashes c this was a question in one of my books with no answer attached to it that i have been thinking about for a few days now is the answer simply that the c code will eventually crash because it is creating a garbage memory cell after each iterationconsider the following java and c code fragments parts of two versions of a gui based application which collects user preferences and use them to assemble a command and its parameters the methodfunction getusercommandspecification returns a string representing the command code and its parameters the returned string is used to build the required command which is then executed assume the following i after the creation in the while loop of the command object referred by cmd in java case or pointed by cmd in c case the reference pointer cmd to the generated object is no more referenced or used ii the application also defines a class command along with its methodfunction executea which of the two code versions detailed below will eventually crash b explain why a program version crashes while the other one is not crashingjava codewhile true string commandspecification getusercommandspecification command cmd new commandcommandspecification cmdexecutec codewhile true string commandspecification getusercommandspecification command cmd new commandcommandspecification cmd execute,"['java', 'c++']" +374847,typing greek letters etc in python plots i need to type greek letters and the angstrom symbol in labels of axes in a plot so for examplefiggcaset xlabelwavelength angstromfiggcaset ylabellambdaexcept that i actually want angstrom and lambda replaced by actual symbols how should i do this thanks,['python'] +374855,how to make twitter bootstrap tooltips have multiple lines i am currently using the below function to create text that will be thisplayed using bootstraps tooltip plugin how come multiline tooltips only works with br and not n i prefer that there is not any html in my links title attributes what worksdef tooltipobject tooltip objecteach do user tooltip useridentifier br end return tooltipendwhat i wantdef tooltipobject tooltip objecteach do user tooltip useridentifier n end return tooltip end,"['javascript', 'css']" +374929,how can i find out where the httpdconf file is located how can i find out the path of the httpdconf file on apache php i do not know whether my script will be runned in windows apache or linux i need to know where i can find this file in order to find a parameter from there thanks,['php'] +374937,how to create a custom dialog box in android i want to create a custom dialog box like below i have tried the following thingsi created a subclass of alertdialogbuilder and used a custom title and custom content view and used that but the result was not as expectedanother attempt was to subclass dialogfragment and customize the dialog inside oncreatedialog that but result was not as expectedthen i tried using a plain dialog class the result was not as expectedin all three cases the problem is when i overlook the title view the size of the dialog is not as expected and when i use title view the result is there is a thick border around the content view which really looks bad now i have two questions in my mindhow can i achieve that as i have already tried so many things a direct answer will be more appreciatedwhat is the best way to show an error or alert dialog in an android appeditandroid developer documentation recommends that we should use either dialogfragments or dialogs for showing error alert messages to the user however at one point they say tip if you want a custom dialog you can instead thisplay an activity as a dialog instead of using the dialog apis simply create an activity and set its theme to themeholodialog in the manifest elementwhat is the meaning of that is not it too much to use an activity just for showing an error message,['android'] +374946,howto cleanly fetch 401 in a backbonejs based app in my backbonejs based app i am talking to my api that responds with a 401 in case the underlying request was made without or with an invalid authentication token i would like to instrument that by navigating to a login page every time a 401 is receivedto fetch the 401 i successfully wrapped backbonesync but at that point i get kind of stuck i tried several strategies herethrow unauthorized down in backbonesync and try to fetch up in my router failed with uncaught unauthorizedtrying to navigate login down in backbonesync which not only looks odd but comes with the problem that my app is based on amdrequirejs and i cannot simply access my backbonerouter instance down in my wrapped sync functionthe only solution i see so far would be to create a globally available caching object that gets a reference to my router instance and in turn is put into define as a dependency where it is needed that cache object had to be a singleton and broke my whole pleasenoglobalsandnonamespaces strategy i am kind of stuck here can anyone point me to a more clean solution to that common problem,['javascript'] +374987,a function like glreadpixels in directx sharpdx i am searching for a way to read a pixels color at the mousepoint in opengl it was done by calling the function glreadpixels after drawing the scene or parts of it i want to make a simple color picking routine in the background for identifing a shapes lines in 3d spaceso is there any equivalent methodfunctionsuggestion for doing the same in sharpdx directx10 directx11,['c#'] +374995,calling an asynchronous function within a for loop in javascript i have the following codeforvar i 0 i listlength i mc cligetlisti functionerr response do somethingi mc cli is a connection to a memcached database as you can imagine the callback function is asynchronous thus it may be executed when the for loop already ended also when calling in this way do somethingi it always uses the last value of the for loopi tried with a closure in this way do somethingfunctionxreturn xi but apparently this is again using always the last value of the index of the for loop i also tried declaring a function before the for loop like sovar create closure functioni return function return i and then calling do somethingcreate closureibut again without success with the return value always being the last value of the for loopcan anybody tell me what am i doing wrong with closures i thought i understood them but i cannot figure why this is not working,['javascript'] +375001,can i override the used phpcs ruleset per file if so how recently we migrated to git and implemented for now post receive hooks on our central server to send reports to developers as well as making several tools enabling us to have our codestandard checked automagically with phpcs on our development environmentsthis is all nice and dandy works well but we want to be able to always depend on our code standard not ignoring every file which does not conform for a logical reason now we have our own ruleset which overrides some stuff in the default pear standard but we want to go a little further if possibleour problem is that while the pear standard is perfect for all classes business logic but in the view files we want to loosen the rules for say closing brackets needing to be on their own line the problem is that we mostly define html in these files and the only control structures we have are simple ifelse or foreach statements and opening php then adding a newline closing bracket newline and closing php is a bit silly imorequired syntax to be validphp end of some if statement what wed instead like to use for viewsphp end of some if statement this would make our code more readable we thislike the alternate syntax as wel if endif afaik mainly because there were some problems in validity here as well it is all about the whitespaceignoring the whole file with codingstandardsignorefile is not an option for ustldrso what we would like to do is define a seperate ruleset for our view files so we still have a standard to adhere to but with the relaxed rules on these fronts so our code can still be made readablei am not too knowledgable about phpcs yet and could not find any solutions myself using keywords i though were logical any suggestions to make tidy view files that also conform to pear are also welcome,['php'] +375009,bytes to human readable and back without data loss i need to convert strings which contain the memory usage in bytes like 1048576 which is 1m into exactly that a humanreadable version and visaversa note i looked here alreadyreusable library to get human readable version of file sizeand here even though it is not pythonhow to convert human readable memory size into bytesnothing so far helped me so i looked elsewherei have found something that does this for me here r984137 or for shorter url the codedef bytes2humann formatvalueisymbols bytes2human10 9k bytes2human101221 95m symbols b k m g t p e z y prefix for i s in enumeratesymbols1 prefixs 1 i110 for symbol in reversedsymbols1 if and prefixsymbol value floatn prefixsymbol return format locals return format dictsymbolsymbols0 valuenand also a function for conversion the other way same sitedef human2bytess human2bytes1m 1048576 human2bytes1g 1073741824 symbols b k m g t p e z y letter s1stripupper num s1 assert numisdigit and letter in symbols num floatnum prefix symbols01 for i s in enumeratesymbols1 prefixs 1 i110 return intnum prefixletterthis is great and all but it has some information loss example bytes2human109k human2bytes9k9216to try to solve this i change the formatting on the function bytes2humaninto formatvalue3fsymbolswhich is much nicer giving me these results bytes2human109766kbut when i try to convert them back with the human2bytes function human2bytes9766ktraceback most recent call last file pyshell366 line 1 in module human2bytes9766k file pyshell359 line 12 in human2bytes assert numisdigit and letter in symbolsassertionerrorthis is because of the so my question is how can i convert a humanreadable version back into byteversion without datalossnote i know that 3 decimal places is also a little bit of data loss but for the purposes of this question lets ignore that for now i can always change that to something greater,['python'] +375012,freeing memory in circular doubly linked list valgrind tells me that i have xx bytes in xx blocks that are definitely lost record blah blahand the source is in malloc however i think it is because i am not freeing up enough memory for malloc anyway i have provided the code that i believe is causing the heap errori am aware that i am not freeing up the memory in list remove which i am pretty sure is the only source of the problem it probably requires some shifting around of temps but i do not know if that is the only problem list t list removelist t list list t node list t oldnode node nodeprevnext nodenext nodenextprev nodeprev if list oldnode freeoldnode return list else list t value listnext list null listnext freeoldnode return value void list freelist t list if list while list removelist list lastlist null list last simply gives the last node of the listedit i am sorry about not providing enough information kerrek sb alk here is the rest of the code as you can see the malloc occurs in newnode where i can start creating new lists the struct is pretty simple with a value and a prev nextinclude stdlibhinclude stringhinclude stdiohinclude llhstruct list char value struct list next struct list prevconst char list node valuelist t node return nodevaluelist t list firstlist t list return listlist t list lastlist t list return listprevlist t list nextlist t node return nodenextlist t list previouslist t node return nodeprevstatic void failed allocationvoid fprintfstderr out of memoryn abortstatic list t new nodeconst char value list t node mallocsizeoflist t if node failed allocation nodevalue mallocstrlenvalue1 if nodevalue failed allocation strcpynodevalue value return nodelist t list insert beforelist t list list t node const char value list t insert node new nodevalue insert nodeprev nodeprev insert nodenext node insert nodenextprev insert node insert nodeprevnext insert node if list node return insert node else return list list t list appendlist t list const char value if list void list insert beforelist list value return list else list t node new nodevalue nodeprev nodenext node return node list t list prependlist t list const char value if list return list insert beforelist list value else list t node new nodevalue nodeprev nodenext node return node list t list removelist t list list t node list t oldnode node nodeprevnext nodenext nodenextprev nodeprev if list oldnode freeoldnode return list else list t value listnext list null listnext freeoldnode return value void list freelist t list if list while list removelist list lastlist null void list foreachlist t list void functionconst char if list list t cur list firstlist do functioncurvalue cur curnext while cur list firstlist please help it still gives me a memory leak error in the heap,['c'] +375025,cancelling a task within a task i am trying to cancel a task by calling the cancellationtokensourcecancel method within the task but i cannot get it to workhere is the code i am usingtaskscheduler ts taskschedulercurrentcancellationtokensource cts new cancellationtokensourcetask t new task consolewriteline in task ctscancel ctstoken task c1 tcontinuewith antecedent consolewriteline in continuewith 1 cancellationtokennone taskcontinuationoptionsonlyonrantocompletion ts task c2 c1continuewith antecedent consolewriteline in continuewith 2 taskcontinuationoptionsnotoncanceled tstartconsolereadkeyenvironmentexit 1 this print outsin taskin continuewith 1in continuewith 2what i expected was thisin taskam i missing something here can tasks only be cancelled outside of the task,['c#'] +375041,overriding javadoc comment on javalangenumvalues i have a very specific problem about the method javalangenumvaluesi would like to override its javadoc very precisely the current javadoc for this is after i created my own enumpublic static myclassmyenum values this method may be used to iterate over the constants as follows for myclassmyenum c myclassmyenumvalues systemoutprintlnc returns but here systemout calls are considered bad practice so i would like it not to be shown my first try was to override values but apparently it is not possible is there another way i can do this or is the only possibility to do something on maven sidei am also curious about why values is not overridable i read on other questions that it is generated by the compiler but can someone be more precise it seems that it is generated from the enums name but it does not explain why,['java'] +375042,can a move constructor be implicit consider the following classclass apublic stdstring field a stdstring field bnow consider the following copy constructiona a1a2the copy construction will adequately copy a despite the lack of of an explicit copy constructor because the copy constructors for stdstring will be called by the compiler generated implicit copy constructorwhat i wish to know is is the same true for move constructionedit testing here shows thata a2stdmovea1will actually result in a copy construction unless the specific move constructora a other astdmoveothera is definededit editi pinged stephan t lavavej and asked him why vc 2012 does not seem to follow what draft 128 states regarding implicit move constructor generation he was kind enough to explainit is more of a feature not yet implemented than a bug vc currently implements what i refer to as rvalue references v20 where move ctorsassigns are never implicitly generated and never affect the implicit generation of copy ctorsassigns c11 specifies rvalue references v30 which are the rules youre looking at,['c++'] +375076,how to prevent new line in styledtext after enter pressed i need to prevent textviewer making new lines after i press enter key in case of preventnewlines flag is enabled i have this piece of codetextviewer mytextviewer new textviewer mygroup swtv scroll swtfull selection swtborder swtwrapmytextviewersetdocumentnew documentmytextstyledtext mystyledtext mytextviewergettextwidgetmystyledtextaddtraverselistenernew traverselistener override public void keytraversedtraverseevent e if edetail swttraverse return if preventnewlines edoit false but it makes new lines anyway what am i doing wrongcould anybody please post me the correct code how to prevent iteditok i have found the answer by luck i hope it helps to someone else maybemystyledtextaddverifykeylistenernew verifykeylistener override public void verifykeyverifyevent e if preventnewlines ekeycode swtcr ekeycode swtkeypad cr edoit false,['java'] +375086,how to check if binaries are built from particular sources the legacy project i am working on includes some external library in a form of set of binary jar files we decided that for analysis and potential patching we want to receive sources of this library use them to build new binaries and after detailed and long enough regression testing switch to these binariesassume that we have already retrieved and built the sources i am actually in planning phase before real testing i would like to perform some compatibility checks to exclude possibility that the sources represent something dramatically different from what is in the old binariesusing the javap tool i was able to extract the version of jdk used for compilation at least i believe it is the version of jdk it says the binaries were built using major version 46 and minor 0 according to this article it maps to jdk 12assume that the same jdk would be used for sources compilationthe question isis there a reliable and possibly effective method of verification if both of these binaries are built from the same sources i would like to know if all method signatures and class definitions are identical and if most or maybe all of method implementations are identicalsimilarthe library is pretty big so i think that detailed analysis of decompiled binaries may be not an option,['java'] +375100,argparse optional argument before positional argument i was wondering if it is possible to have a positional argument follow an argument with an optional parameter ideally the last argument entered into the command line would always apply toward testnameimport argparseparser argparseargumentparserdescriptiontafparseradd argumentrreleasenargsdestreleasedefaulttrunkparseradd argumenttestnamenargsargs parserparse argsi would like both of these calls to have smoketest apply to testname but the second one results in an error python tafpy r 10 smoketest python tafpy r smoketesttafpy error too few argumentsi realize that moving the positional argument to the front would result in the correct behavior of the optional parameter however this is not quite the format i am looking for the choices flag looks like an attractive alternative however it throws an error instead of ignoring the unmatched itemediti have found a hacky way around this if anyone has a nicer solution i would appreciate itimport argparseparser argparseargumentparserdescriptiontafparseradd argumentrreleasenargsdestreleasedefaulttrunkparseradd argumenttestnamenargsargparseremainderargs parserparse argsif not argstestname argstestname argsrelease argsrelease,['python'] +375129,glkview drawinrect not called i am learning opengles and i am trying to put a glkviewer inside an uiviewcontroller i know i can come around the main issues by using glviewcontroller but i am trying to learn how to do it this wayi found this question nesting glkview into uiviewcontroller and nested glkview and glkviewcontroller but i must be missing something even though i think i am doing all the right steps because when i run my project i am not getting to the drawinrect print line in the storyboard i am pointing the viewcontroller as the delegate of the glkview componenti tried to keep the code as simple as possible and any help will be apreciatedmycontrollerhimport foundationfoundationhimport glkitglkithinterface myglcontroller uiviewcontroller glkviewdelegate gluint vertexbufferidproperty weak nonatomic iboutlet glkview glviewproperty strong nonatomic glkbaseeffect baseeffectendmyglcontrollermimport myglcontrollerhimplementation myglcontrollersynthesize baseeffectvoid viewdidload super viewdidload selfglviewcontext eaglcontext alloc initwithapi keaglrenderingapiopengles2 eaglcontext setcurrentcontextselfglviewcontext printfview loaded voidglkviewglkview view drawinrectcgrectrect printfdrawinrectend update as far as i can tell the glkview is hooked up properly as suggested per and added the joshknapp and called setneedsthisplay in case there is something i am missing i have uploaded a copy of the project here i am a total noob in this so i apologize for any silly oversight,"['iphone', 'objective-c', 'ios']" +375132,error cannot bind astdbasic ostreama lvalue to astdbasic ostreama i have already looked at a couple questions on this specifically overloading operator cannot bind lvalue to astdbasic ostreamcharawas very helpful it let me know that my problem is i am doing something that c11 cannot deduce the type fromi think a big part of my problem is that the instantiated class i am working with is templated but originally obtained from a pointer to a nontemplate base class this is something i did advised from another stackoverflowcom question about how to put template class objects into an stl containermy classesclass dbvaluebase protected virtual void null return null needed to make class polymorphictemplate typename tclass dbvalue public dbvaluebase public dbvalueconst tval data new tval dbvalue if data delete data t data const t dataref const return data friend stdostream operatorstdostream out const dbvaluet val out valdataref return out and the code snippet where the compile error databasecc53090 error cannot bind astdbasic ostreamchara lvalue to astdbasic ostreamchara occursnb typedef stdmapstdstringdbvaluebase dbvaluemap const commpointdbvaluemap db values cpvalue map for auto i db valuescbegin i db valuescend i todo need to implement an ostream operator and conversion operators for dbvaluebase and dbvalue todo figure out how to get a templated output operator to work dbvaluestdstring k dynamic castdbvaluestdstringisecond stdcerr database field ifirst should have value isecond endl if my output tries to print isecond it compiles and runs and i see the pointer if i try to output isecond i get the compile error when singlestepping in gdb it seems to still know that isecond is of the correct typegdb p isecond2 dbvaluebase 0x680900gdb p isecondwarning rtti symbol not found for class dbvaluestdstring3 warning rtti symbol not found for class dbvaluestdstring vptrdbvaluebase 0x4377e0 vtable for dbvaluestdstring16gdb quiti am hoping that i am doing something subtly wrong but it is more complicated than i seem to be able to figure it out on my own anyone else see what things i have done wrong or incompletelyeditpiotrnycz did give a good solution for my proposed problem below however despite currently printing values while doing development the real need for these dbvalue objects is to have them return a value of the correct type which i can then feed to database operation methods i should have mentioned that in my original question that printing is of value but not the end of my goal,['c++'] +375194,android testing dialog check it isshowing here is my method it works fine and shows the dialogpublic void showdialog final dialog dialog new dialogthis dialogsetcontentviewrlayoutmylayout dialogshowi have a test project and i would like to test that the dialog is showing up i would like to apply the isshowing method something like thisasserttruedialogisshowingbut i do not know how to get to the dialog variable within my test i am not using robotium this is not an option for mei am currently using the activityunittestcase to test with if any more information is required please do not hesitate to askediti have attempted to use the answer below by making the dialog publicpublic dialog getdiag return dialogusing this answer i have a new problem when i run showdialog in the test it breaks when it hits dialogshowandroidviewwindowmanagerbadtokenexception unable to add window token null,"['java', 'android']" +375270,in a regular expression match one thing or another or both in a regular expression i need to know how to match one thing or another or both in order but at least one of the things needs to be therefor example the following regular expression0909will match234and 56but not 23456while the following regular expression0909will match all three of the strings above but it will also match the empty string which we do not wanti need something that will match all three of the strings above but not the empty string is there an easy way to do thatupdateboth andrews and justins below work for the simplified example i provided but they do not unless i am mistaken work for the actual use case that i was hoping to solve so i should probably put that in now heres the actual regexp i am usings009091309309sazaz this will match4545988456893456909823356790090934 banana fries056 pointsbut it would not match56and i need it to do this,['javascript'] +375274,match all class selectors that begin with is it possible to use a wildcard for selectors in css3egdiv classmyclassonedivdiv classmyclasstwodivdiv classmyclassthreedivand then magically set all above divs to red in one gomyclass color f00 possible,['css'] +375281,slicing sparse matrices in scipy which types work best the scipy sparse matrix tutorial is very good but it actually leaves the section on slicing underdeveloped still in outline form see section handling sparse matricesi will try and update the tutorial once this question is answeredi have a large sparse matrix currently in dok matrix format import numpy as npfrom scipy import sparsem sparsedok matrix106 106for various methods i want to be able to slice columns and for others i want to slice rows ideally i would use advancedindexing ie a boolean vector bool vect with which to slice a sparse matrix m as inbool vect nparange1062 every even indexout mbool vect want to select every even rowor out mbool vect want to select every even columnfirst off dok matrices do not support this but i think it works slowly if i first cast to lil matrices via sparselil matrixmas far as i can gather from the tutorial to slice columns i want to use csc and to slice rows i want to slice csr so does that mean i should cast the matrix m viamtocscbool vectormtocsrbool vecti am kinda guessing here and my code is slow because of it any help from someone who understands how this works would be appreciated thanks in advanceif it turns out i should not be indexing my matrix with a boolean array but rather a list of integers indices that is also something i would be happy to find out whichever is more efficientfinally this is a big matrix so bonus points if this can happen in place with broadcasting,['python'] +375283,rspec load missing constant expected x to define y and it does when we run bundle exec rake specit errors while trying to load the environment with the errorgemsactivesupport328libactive supportdependenciesrb503in load missing constant expected appmodelslinkscategoryrb to define linkscategory loaderrorthe file appmodelslinkscategoryrb does indeed define linkscategory even stranger is that error does not occur when running under guard and spork the standard way we run testsbundle exec guard iruns the test suite as expected without issuespork is configured to run rspec so i am a bit confused about why running rake spec manually would cause thisi have seen similar issues which seemed to be solved by looking at the autoload paths and checking if it was including lib and lib however ours is not doing anything funky with autoload paths that i can see our autoload paths looks like this defined in applicationrbconfigautoload paths wrailsrootappsrc configrootappapi railsrootaproductswere using bundle exec rake spec in our ci server to run the tests rather than guard which we use on our development machinesdoes categoryrb get loadedadded puts hey at the top of categoryrb and puts yo at the bottom and when running the specs the output incldues itdeprecation warning activeadmindashboard is deprecated and will be removed in the next versionheyyousersshimmsrvmgemsruby193p125leximgemsactivesupport328libactive supportdependenciesrb503in load missing constant expected usersshimmsdevelopmentleximappmodelslinkscategoryrb to define linkscategory loaderrorappmodelslinkslinkrbclass linkslink activerecordbase selftable name links category links attr accessible description name url category id acts as paranoid belongs to category class name linkscategory validates presence of url validates presence of nameendappmodelslinkscategoryrbclass linkscategory activerecordbase selftable name links categories attr accessible description name space id acts as paranoid extend friendlyid friendly id name use scoped scope space belongs to space belongs to spacespace has many links class name linkslink validates presence of nameendspec helperrbrequire fileexpand pathconfigenvironment file require rubygemsrequire railsallrequire rspecrailsrequire factory girlsystem railsrootto sdbtestdbenvrails env testload schema lambda load railsrootto sdbschemarb use db agnostic schema by default activerecordmigratorupdbmigrate use migrationssilence streamstdout load schemadirrailsrootjoinspecsupportrbeach f require f rspecconfigure do config configinclude factorygirlsyntaxmethods configmock with rspec configfixture path railsrootspecfixtures configuse transactional fixtures true activesupportdependenciesclearendsimplest category specrb that causes errorrequire spec helperdescribe linkscategory do pending add some examples to or delete file endrake executiona lexim gitdeveop a rails envtest be rake spec trace invoke spec first time invoke dbtestprepare first time invoke dbabort if pending migrations first time invoke environment first time execute environmentagent is configured to send raw sql to the serviceagent is configured to send raw sql to the servicedeprecation warning passing tag class and others to use is deprecated please invoke buse input wrap with claspan4 instead called from block 2 levels in top required at usersshimmsdevelopmentleximconfiginitializerssimple formrb47 invoke dbload config first time execute dbload config execute dbabort if pending migrations execute dbtestprepare invoke dbtestload first time invoke dbtestpurge first time invoke environment invoke dbload config execute dbtestpurge execute dbtestload invoke dbtestload schema first time invoke dbtestpurge execute dbtestload schema invoke dbschemaload first time invoke environment invoke dbload config execute dbschemaload execute specusersshimmsrvmrubiesruby193p125binruby s rspec specproduct features specrb speccontrollersleximlogo controller specrb specmailersenterprise enquiry mailer specrb specmailersnew account mailer specrb specmailersuser mailer specrb specmodelsaccount boltons specrb specmodelsaccount specrb specmodelsaccount status specrb specmodelsaddress specrb specmodelsadminimport specrb specmodelsadmin user specrb specmodelsassignment materials specrb specmodelsassignment submission rubric selection specrb specmodelsassignmentssubmission files specrb specmodelsassignmentssubmission specrb specmodelsbolton screenshot specrb specmodelsbolton specrb specmodelsbolton status specrb specmodelscalendarentry specrb specmodelscalendarevent sharing specrb specmodelscalendar specrb specmodelscancellation reason specrb specmodelscharge specrb specmodelsclient application specrb specmodelscommon cartridgeexport specrb specmodelscredit card specrb specmodelsthiscussionsreply specrb specmodelsthiscussionstag specrb specmodelseducation domain name specrb specmodelsemail address validation specrb specmodelsgradebookcolumn specrb specmodelsgradebookvalue specrb specmodelsgradebook column type specrb specmodelsimporteruser specrb specmodelsinvitation specrb specmodelsinvoice specrb specmodelslinkscategory specrb specmodelslinkslink specrb specmodelsmailing list specrb specmodelsmaterial item specrb specmodelsmaterialsfolder specrb specmodelsmaterialspage details specrb specmodelsmaterialspage specrb specmodelsmaterialsyoutube details specrb specmodelsmobile phone country carrier specrb specmodelsmobile phone country specrb specmodelsnet promoter score specrb specmodelsnetwork specrb specmodelsnotification channel specrb specmodelsnotification event specrb specmodelsnotification specrb specmodelsopen graph object authorization specrb specmodelsplan pool specrb specmodelsplan specrb specmodelsprivacy setting specrb specmodelsproduct bolton specrb specmodelsproduct specrb specmodelsquiz specrb specmodelsquizzesquestion option specrb specmodelsquizzesquestion specrb specmodelsquizzesquestion type specrb specmodelsquizzessubmission answer option specrb specmodelsquizzessubmission answer specrb specmodelsquizzessubmission specrb specmodelsreferrer campaign specrb specmodelsregistration specrb specmodelsrubric specrb specmodelsrubricscriterion specrb specmodelsrubricsdescriptor specrb specmodelsrubricslevel specrb specmodelssanitized text specrb specmodelsscheduled mail specrb specmodelsspace specrb specmodelssubscription specrb specmodelssubscription status specrb specmodelssystem announcement specrb specmodelssystem announcement views specrb specmodelstip specrb specmodelstour activity specrb specmodelsunauthorized access specrb specmodelsunavailable feature request specrb specmodelsuser activity specrb specmodelsuser authentication tokens specrb specmodelsuser creation type specrb specmodelsuser notification specrb specmodelsuser specrb specmodelswall post likes specrb specmodelswallpost specrbagent is configured to send raw sql to the serviceagent is configured to send raw sql to the servicedeprecation warning passing tag class and others to use is deprecated please invoke buse input wrap with claspan4 instead called from block 2 levels in top required at usersshimmsdevelopmentleximconfiginitializerssimple formrb47deprecation warning activeadmindashboard is deprecated and will be removed in the next versionusersshimmsrvmgemsruby193p125leximgemsactivesupport328libactive supportdependenciesrb503in load missing constant expected usersshimmsdevelopmentleximappmodelslinkscategoryrb to define linkscategory loaderror from usersshimmsrvmgemsruby193p125leximgemsactivesupport328libactive supportdependenciesrb192in block in const missing from usersshimmsrvmgemsruby193p125leximgemsactivesupport328libactive supportdependenciesrb190in eachfrom usersshimmsrvmgemsruby193p125leximgemsactivesupport328libactive supportdependenciesrb190in const missing from usersshimmsdevelopmentleximspecmodelslinkscategory specrb4in top required from usersshimmsrvmgemsruby193p125leximgemsactivesupport328libactive supportdependenciesrb245in loadfrom usersshimmsrvmgemsruby193p125leximgemsactivesupport328libactive supportdependenciesrb245in block in load from usersshimmsrvmgemsruby193p125leximgemsactivesupport328libactive supportdependenciesrb236in load dependency from usersshimmsrvmgemsruby193p125leximgemsactivesupport328libactive supportdependenciesrb245in loadfrom usersshimmsrvmgemsruby193p125leximgemsrspeccore2101librspeccoreconfigurationrb746in block in load spec files from usersshimmsrvmgemsruby193p125leximgemsrspeccore2101librspeccoreconfigurationrb746in map from usersshimmsrvmgemsruby193p125leximgemsrspeccore2101librspeccoreconfigurationrb746in load spec filesfrom usersshimmsrvmgemsruby193p125leximgemsrspeccore2101librspeccorecommand linerb22in run from usersshimmsrvmgemsruby193p125leximgemsrspeccore2101librspeccorerunnerrb69in run from usersshimmsrvmgemsruby193p125leximgemsrspeccore2101librspeccorerunnerrb10in block in autorunrake abortedusersshimmsrvmrubiesruby193p125binruby s rspec specproduct features specrb speccontrollersleximlogo controller specrb specmailersenterprise enquiry mailer specrb specmailersnew account mailer specrb specmailersuser mailer specrb specmodelsaccount boltons specrb specmodelsaccount specrb specmodelsaccount status specrb specmodelsaddress specrb specmodelsadminimport specrb specmodelsadmin user specrb specmodelsassignment materials specrb specmodelsassignment submission rubric selection specrb specmodelsassignmentssubmission files specrb specmodelsassignmentssubmission specrb specmodelsbolton screenshot specrb specmodelsbolton specrb specmodelsbolton status specrb specmodelscalendarentry specrb specmodelscalendarevent sharing specrb specmodelscalendar specrb specmodelscancellation reason specrb specmodelscharge specrb specmodelsclient application specrb specmodelscommon cartridgeexport specrb specmodelscredit card specrb specmodelsthiscussionsreply specrb specmodelsthiscussionstag specrb specmodelseducation domain name specrb specmodelsemail address validation specrb specmodelsgradebookcolumn specrb specmodelsgradebookvalue specrb specmodelsgradebook column type specrb specmodelsimporteruser specrb specmodelsinvitation specrb specmodelsinvoice specrb specmodelslinkscategory specrb specmodelslinkslink specrb specmodelsmailing list specrb specmodelsmaterial item specrb specmodelsmaterialsfolder specrb specmodelsmaterialspage details specrb specmodelsmaterialspage specrb specmodelsmaterialsyoutube details specrb specmodelsmobile phone country carrier specrb specmodelsmobile phone country specrb specmodelsnet promoter score specrb specmodelsnetwork specrb specmodelsnotification channel specrb specmodelsnotification event specrb specmodelsnotification specrb specmodelsopen graph object authorization specrb specmodelsplan pool specrb specmodelsplan specrb specmodelsprivacy setting specrb specmodelsproduct bolton specrb specmodelsproduct specrb specmodelsquiz specrb specmodelsquizzesquestion option specrb specmodelsquizzesquestion specrb specmodelsquizzesquestion type specrb specmodelsquizzessubmission answer option specrb specmodelsquizzessubmission answer specrb specmodelsquizzessubmission specrb specmodelsreferrer campaign specrb specmodelsregistration specrb specmodelsrubric specrb specmodelsrubricscriterion specrb specmodelsrubricsdescriptor specrb specmodelsrubricslevel specrb specmodelssanitized text specrb specmodelsscheduled mail specrb specmodelsspace specrb specmodelssubscription specrb specmodelssubscription status specrb specmodelssystem announcement specrb specmodelssystem announcement views specrb specmodelstip specrb specmodelstour activity specrb specmodelsunauthorized access specrb specmodelsunavailable feature request specrb specmodelsuser activity specrb specmodelsuser authentication tokens specrb specmodelsuser creation type specrb specmodelsuser notification specrb specmodelsuser specrb specmodelswall post likes specrb specmodelswallpost specrb failedusersshimmsrvmgemsruby193p125leximgemsrspeccore2101librspeccorerake taskrb137in block 2 levels in initializeusersshimmsrvmgemsruby193p125leximgemsrake0922librakefile utils extrb60in verboseusersshimmsrvmgemsruby193p125leximgemsrspeccore2101librspeccorerake taskrb127in block in initializeusersshimmsrvmgemsruby193p125leximgemsrake0922libraketaskrb205in callusersshimmsrvmgemsruby193p125leximgemsrake0922libraketaskrb205in block in executeusersshimmsrvmgemsruby193p125leximgemsrake0922libraketaskrb200in eachusersshimmsrvmgemsruby193p125leximgemsrake0922libraketaskrb200in executeusersshimmsrvmgemsruby193p125leximgemsrake0922libraketaskrb158in block in invoke with call chainusersshimmsrvmrubiesruby193p125libruby191monitorrb211in mon synchronizeusersshimmsrvmgemsruby193p125leximgemsrake0922libraketaskrb151in invoke with call chainusersshimmsrvmgemsruby193p125leximgemsrake0922libraketaskrb144in invokeusersshimmsrvmgemsruby193p125leximgemsrake0922librakeapplicationrb116in invoke taskusersshimmsrvmgemsruby193p125leximgemsrake0922librakeapplicationrb94in block 2 levels in top levelusersshimmsrvmgemsruby193p125leximgemsrake0922librakeapplicationrb94in eachusersshimmsrvmgemsruby193p125leximgemsrake0922librakeapplicationrb94in block in top levelusersshimmsrvmgemsruby193p125leximgemsrake0922librakeapplicationrb133in standard exception handlingusersshimmsrvmgemsruby193p125leximgemsrake0922librakeapplicationrb88in top levelusersshimmsrvmgemsruby193p125leximgemsrake0922librakeapplicationrb66in block in runusersshimmsrvmgemsruby193p125leximgemsrake0922librakeapplicationrb133in standard exception handlingusersshimmsrvmgemsruby193p125leximgemsrake0922librakeapplicationrb63in runusersshimmsrvmgemsruby193p125leximgemsrake0922binrake33in top requiredusersshimmsrvmgemsruby193p125leximbinrake23in loadusersshimmsrvmgemsruby193p125leximbinrake23in maintasks top spec,"['ruby-on-rails', 'ruby']" +375287,mono for android code obfuscation as everybody knows piracy becomes a very serious issue on androiddoes mono for android provide code obfuscation when compiling to native code,['android'] +375297,tinymce removethisable resizing toggles tinymce is adding those move and resize handles to some of my elements not just the imagesi would love to get rid of them all together but i have had no successthese did not work for metinymceinit object resizing falseseems like it should be real easyok so it looks like it is adding the resize js to any element that is absolutely positioned if that helps anyone with an answer i just tried to remove it but i need to position it to do what i need,['javascript'] +375311,sorting an array with strings that contains numbers possible duplicatesorting nsstring values as if nsinteger using nssortdescriptor i have an array that i fill with my nsmutabledictionary and i use thismyarray mydict allkeyssortedarrayusingselectorselectoridontknowallkeys of mydicts are nsstrings like 123423 or 423343 i need to sort the new myarray by incremental numbers 12234 453343 522533 543266 etc etcwhat must insert in selector to do this properly thanks,['objective-c'] +375338,find all paths through a tree nested dicts from top to bottom edit see below for a suggested answer and how it is not quite right yetthere are many similar questions to this one on stack overflow but none exactly like it in python i am a programming novice so please go easyi have a tree of nested dictionaries like thisword the next word end next none word quick next word brown next word fox next none word best next word of next word times next none i want to flatten all paths from top to bottom and end up with thisword the word end word the word quick word brown word fox word the word best word of word timesi made a lovely little recursive function that created the original structure in the first place but i am having a hard time unrecursivizing it this is as far as i gotdef flatten combinationsresult tree current combo none all combos none if current combo is none current combo if all combos is none all combos if result tree is none all combosappendcurrent combo return for word in result tree current comboappendword wordword flatten combinationswordnext current combo all combos return current comboawhich returns thisword the word end word quick word brown word fox word best word of word timesawhich is clearly somewhat close but not quite righti know that function is probably horribly unpythonic but i am teaching myself programming so i am not even trying to take advantage of possiblyexistent language features that would let me elide over thinking through this stuff from scratch a he said posting to a qa site in the hope its members would help him elide a bit of thoughtso what am i doing wrongedit moshe below corrected a couple of problemsdef flatten combinationsresult tree current combo none all combos none if current combo is none current combo if all combos is none all combos if result tree is none all combosappendcurrent combo return for word in result tree current combo current combo current comboappendword wordword flatten combinationswordnext current combo all combos return all combos this is closer yet but not quite rightword the word endword the word end word quick word brown word foxword the word end word quick word best word of word times,['python'] +375347,what kind of content does apple host for inapp purchases and under which conditions i have heard that apple offers hosting content for inapp purchases we are working on an app where users can purchase small video clips of about 5 mb eachi could not find detailed information about the conditions what apple hosts how they host it and how much they charge for it some developers say it is only available in ios 6 this is confusingis it also possible to host content at apple which users can simply download without inapp purchasescan inapp purchases be freecan someone clarify and provide links to official information from apple,"['iphone', 'ios']" +375360,python how to refactor circular imports i have got a thing that you can do enginesetstatestate class and it will instantiate the class type you give it and start running on the new statein selectfilestate there is a button to go to newfilestate and on newfilestate there is a button to go back to selectfilestatenow at the beginning of selectfilestate i am importing newfilestate so i can later in the class do enginesetstatenewfilestate at the beginning of newfilestate i am also importing selectfilestate so i can later go back to selectfilestate however this creates a circular import as described in some other posts some say that circular imports are indicators bad design and should be refactored i know that i can just fix this problem by importing selectfilestate right before i need to use it but i would rather do things the right way and refactor it now i am wondering though how would you refactor that outthankseditpydsigner suggests that i merge the two files into one as they are both very related to each other however i cannot put every state that has a circular dependency into one file so there is got to be a better method for that any ideas2editi am circumventing this problem for now by not using the from x import y syntax and instead just doing import x this is not a preferable solution and i would like to know the pythonic way to fix this kind of thing just merging files together cannot be the fix foreverthe codeselectfilestatefrom statesstate import statefrom statesnewfilestate import newfilestatefrom elementsposter import posterfrom elementslabel import labelfrom elementsbutton import buttonfrom elementstrifader import trifaderimport globimport osclass selectfilestatestate def init self engine super init engine def createself selfenginecreateelement0 0 posterselfenginegetimagegui loadsave 1 selfenginecreateelement168 30 labelload a game 40 2 selfenginecreateelement400 470 buttonnew save codeselfenginecreateelement args0 0 trifadernewfilestate false 240 3 ycounter 150 globs globglobsavemcw for file in globs selfenginecreateelement200 ycounter buttonospathbasenamefile4 2 ycounter 50newfilestatefrom statesstate import statefrom statesselectfilestate import selectfilestatefrom elementsposter import posterfrom elementslabel import labelfrom elementsbutton import buttonfrom elementsinputbox import inputboxfrom elementstrifader import trifaderclass newfilestatestate def init self engine super init engine def createself selfenginecreateelement0 0 posterselfenginegetimagegui loadsave 1 selfenginecreateelement135 30 labelmake a new save 40 2 selflvlname selfenginecreateelement180 212 inputboxlength25 textworld name 2 selfenginecreateelement200 240 buttontextok codeselfcreatesave args 2 def createsaveself opensave selflvlnamegettext mcw w selfenginecreateelement0 0 trifaderselectfilestate 240,['python'] +375367,android black screenshot in ddms issue or security reason i am taking screenshots in android jelly bean using galaxy nexususing ddms i can take screenshot like thisin home screenbut heres the problemwhen i opened the camera app and take a screenshot from ddmsresult is a black imageeven in device it cannot take also screenshotwhy is this happeningany help will be appreciated,['android'] +375442,mysql create user if not exists i have a query to check mysql users list for create new userif select existsselect 1 from mysqluser where user title 0 then create user title localhost identified by password end ifbut i get this errorerror 1064 420 at line 3 you have an error in your sql syntax check the manual that corresponds to your mysql server version for the right syntax to use near if select existsselect 1 from mysqluser where user cms localhost 0 at line 1,['mysql'] +375452,how to toggle torch functionality in iphone 4 ios 6 at app start with preferences plist i am using an app called stickam which is live audiovideo recording and upload over 3g the app is perfect for my purpose except for lacking led torch flashlight mode i have a tweak installed which allows me to toggle on torch via settings and leave it on while i use other apps ie safari appstore but when i start a stickam broadcast the torch turns offi am using a file browser on the iphone with basic text editing and file manipulation ability to examine the ios file structure and the apps i do not want to edit stickam just override it is setting by pasting in stickams varmobileapplicationsfa037a73c48343d68ae87e69cd57ebddlibrarypreferencesglobalpreferencesplist a reference to torchs location and triggersimilar todictkeycellkeystringpsswitchcellstringkeydefaultkeyfalsekeyalternatecolorskeytruekeydefaultskeystringcomravirajmtorchstringkeykeykeystringtorchenabledstringkeylabelkeystringenable torchstringkeypostnotificationkeystringcomravirajmtorchprefsstringdictdoes not seem like it would work what ideas do you have on how to do this,['ios'] +375454,fast way to set byte array to unity texture2d in unity3d i get image from camera color camera device as byte array from a plugin and i want show image in realtime in screen if i use texture2dsetpixels32 for making a texture it decrease fps dramatically from 80 to 10first convert byte to color colorr getcolorimagebuffer imagecolorsetpixels32colorr imagecolorapply fps reduced herei guess i need to do this with a shader on gpu so what is solution to do this faster if answer is using shader can give a sample thx,['c#'] +375459,how get all videos from a playlist using youtube api now i am using this linkto retrieve video from youtube playlist but the problem is only getting 25 video but the playlist contains 100 videos how get all video from playlist,['php'] +375469,how to config gruntjs to minify files separately there are some js files in staticjs 1 ajs 2 bjs 3 cjs how to config gruntjs to get below files 1 aminjs 2 bminjs 3 cminjsas far i have to type specific file name min thist src jsjs dest jsminxminjs,['javascript'] +375483,jquery intellisense in vs2012 how can i add a plugin into visual studio 2012 to work with jquery syntax in intellisense on visual studioplease do not give me link of other site just give a solution that you did and worked fine,['jquery'] +375506,mysql how to get x number of results per grouping possible duplicatemysql using limit within group by to get and results per group i have a two tablesitemscategorieseach item belongs to a category what i want to do is select 5 items per category but say 20 items in totalselect item id item name itemscatid from items categorieswhere itemscatid categoriescatidgroup by itemscatid limit 05 5 per category groupthanksedit if there are more than 5 items per category they should be ordered by the item id numeric value,"['mysql', 'sql']" +375524,jframethispose vs systemexit what is the difference between these two methods systemexit and jframethisposeif we want to close a java swing application when a button is clicked which method should i use,['java'] +375534,print into xpsfile and then print it to printer i have tried to print content of richtextbox and there are too many bugs if i print to printerbut when i am printing to xpsfile through xpsprinter in windows and then printing this file to printer all is okso can i do all these things programmaticallyhere is my printing method public int printrotatebool rotate printpageeventargs e int charfrom int charto calculate the area to render and print rect recttoprint recttoprinttop intemarginboundstop aninch recttoprintbottom intemarginboundsbottom aninch recttoprintleft intemarginboundsleft aninch recttoprintright intemarginboundsright aninch calculate the size of the page rect rectpage rectpagetop intepageboundstop aninch rectpagebottom intepageboundsbottom aninch rectpageleft intepageboundsleft aninch rectpageright intepageboundsright aninch intptr hdc egraphicsgethdc formatrange fmtrange fmtrangechrgcpmax charto indicate character from to character to fmtrangechrgcpmin charfrom fmtrangehdc hdc use the same dc for measuring and rendering fmtrangehdctarget hdc point at printer hdc fmtrangerc recttoprint indicate the area on page to print fmtrangercpage rectpage indicate size of page setgraphicsmodefmtrangehdc gm advanced xform par new xform par new xform parem11 1 parem12 0 parem21 0 parem22 1 paredx epagesettingsmarginsleft 100 epagesettingsprinterresolutionx paredy epagesettingsmarginstop 100 epagesettingsprinterresolutiony modifyworldtransformfmtrangehdc ref par mwt leftmultiply intptr res intptrzero intptr wparam intptrzero wparam new intptr1 get the pointer to the formatrange structure in memory intptr lparam intptrzero lparam marshalalloccotaskmemmarshalsizeoffmtrange marshalstructuretoptrfmtrange lparam false send the rendered data for printing res sendmessagehandle em formatrange wparam lparam free the block of memory allocated marshalfreecotaskmemlparam release the device context handle obtained by a previous call egraphicsreleasehdchdc return last 1 character printer return restoint32,['c#'] +375549,basic mysql versioning we have a shopping cart as pictured below the setup works well except for one fatal flaw if you place an order the order is linked to a product so if i update the product after you have purchased the product there is no way for me to show you want the product looked like when you bought it including price this means we need versioningmy plan at present is to when a new product or variant is created or an existing one is edited create a duplicate of the product or variant in the database when a purchase is made link the order to the version not the productthis seems rather simple except from what i can see the only things we do not need to version are the categories as no one cares what categories it was in so we need to version productsvariantsthe key value pairs of attributes for each versionthe imagesmy current thinking is note when a product is created a default variant is created as well this cannot be removed when a product is createdinsert the product into the products tablecreate the default variantduplicate the product into the products versions table replace current id column with a product id columnadd id columnduplicate the variant into the variants versions tablereplace current id column with variant id columnadd id columnreplace product id column with product version id column when a product is editedupdate the product into the products tableduplicate the product into the products versions table replace current id column with a product id columnadd id columnduplicate all product variants into the variants versions tablereplace current id column with variant id columnadd id columnreplace product id column with product version id column duplicate all variant image links into the variant image link version tablereplace current variant id column with variant version id columnwhen a variant is addedadd the variant into the variants tableduplicate the product into the products versions table replace current id column with a product id columnadd id columnduplicate all product variants into the variants versions tablereplace current id column with variant id columnadd id columnreplace product id column with product version id column when a variant is editedupdate the variant in the variants tableduplicate the product into the products versions table replace current id column with a product id columnadd id columnduplicate all product variants into the variants versions tablereplace current id column with variant id columnadd id columnreplace product id column with product version id column duplicate all variant image links into the variant image link version tablereplace current variant id column with variant version id columnso the final structure looks like full sizenow this all seems great except it seems like a heck of a lot of duplicated data eg if we update a product we duplicate the variants even though they would not have been updated since they were inserted also this seems like a lot of workis there a better way of doing this,['mysql'] +375561,array must contain 1 element i have the following classpublic class createjob required public int jobtypeid get set public string requestedby get set public jobtask taskdescriptions get set i would like to have a data annotation above taskdescriptions so that the array must contain at least one element much like required is this possible,"['c#', '.net']" +375572,sqlite encryption in java using hibernate i am currently using hibernatesqliteto access dynamically created sqlite databases this works perfectly now i want to secure the sqlite files after some research i found out the way to go is aes encryption can anyone explain to me if this is possible using hibernate and if so how if this does not work is there any other solution for securing the data in the files,['java'] +375595,difference between lookup and dictionaryof list i am trying to wrap my head around which data structures are the most efficient and when where to use which onesnow it could be that i simply just do not understand the structures well enough but how is an ilookupof key different from a dictionaryof key listof also where would i want to use an ilookup and where would it be more efficient in terms of program speed memory data accessing etc,"['c#', '.net']" +375617,pass data from java to cups filter i am working on the printing system and need to add arbitrary text to each printed document like author document hash some sysvars and else we use java printing service javaxprint as printing client and cups as servercups has some procedures of document postprocessing called filtersfilter is a program that will be launched by cups cups passes filter some params job attributes among themso i decided to pass custom attributes from java to cups and add attributes as text to document in filter everything works without exception document is printed but i do not get my attributes in filter they are not even passed to cups saw that in packet snifferi already used getsupportedattributecategories to see the list of supported by printer attributes maybe i should somehow add mine to that list but i do not understand howi am not limited to attributes i just need to pass arbitary data from java to cups filter how can i do itmy java code is likemyattrset attrs new myattrsetattrsaddnew myattr42attrsaddnew copies18 printservice service printservicelookuplookupdefaultprintservicedocflavor flavor docflavorinput streamautosensedoc doc new simpledocis flavor nulldocprintjob job servicecreateprintjobjobprintdoc attrsfilter is a simple bash script that prints everything passed to itbinbashecho all args tmpf1logfor var in do echo var tmpf1logdonetmpf1log looks likeall args87 oroboros java printing 18 number of pages is passed but not myattrsome useless crap like job uuid and elsemyattrclass myattr extends integersyntax implements printrequestattribute protected myattrint value supervalue public class extends attribute getcategory todo autogenerated method stub return myattrclass public string getname todo autogenerated method stub return somemycustop5,['java'] +375701,how do i get puma to start automatically when i run rails server like thin does normally when you run rails server it starts webrick if you install the thin gem then thin starts instead i would like to do the same thing with the puma server i see that the start command within railties librailscommands calls super but i cannot find what the various options for super are i have also reviewed many references to rails within thini found a changelog entry entitled added thin support to scriptserver 488 bob klosinski from oct of 2008 but that code area has changed significantly since that commit a93ea88c0623b4f65af98c0eb55924c335bb3ac1if someone could direct me to the right section of code that would be very helpful,['ruby-on-rails'] +375741,filterable multiselect combobox shuttletransfer widget backgroundi am looking for a jquery or javascriptbased combobox shuttle widget that allows the user to filter the source list the source list is a combobox on the left and the destination list is a second combobox on the rightmockupthe widget should resemblean existing jquery widgetusagethe user cantype a regex to filter the source list eg toythe widget hides all items that do not match the filter expressionselect one or more items in the source list using click controlclick and shiftclick selectionsclick the to transfer the items from the source list to the destination listclear the filter to reveal the full source listtechnicalideally the comboboxes would use a multiselect html combobox and the markup would be trivialselect namesourcelist idsourcelist size20 multiplemultiple option value1toyotaoption option value2mitsubishioption option value3nintendooption option value4samsungoption option value5bank of kyotooptionselectselect namedestinationlist iddestinationlist size20 multiplemultiple option value6mazdaoption option value7fujioption option value8hondaoptionselectscript sourcelistshuttlescriptfindingsthese are close no filter does not allow multiple selections no filter uses mootools no filter no filter select no filter mootoolsthese are nearly perfect uses div tags instead of select no regex search no regex searchi am looking to batch up the assignment of categories for 30 50 items and thought this would be a quick way to accomplish such a feat the japanese company names are purely fictional in reality the names will typically have a word or phrase in commonquestionwhat is a free and open source widget jquery or pure javascript that meets these requirementsrelatedrelated linksmultiselect twocolumn transfer widget with twitter bootstrap theme,"['javascript', 'jquery']" +375762,java abstract methods i am slightly confused with the keyword abstract here my compiler is telling me that i am not allowed to have a body for a method that is abstract however my assignment saysthe abstract method orderdescription returns a string giving details about a particular orderabstract string orderdescription return nullhowever my code returns an error as i mentioned above so my question is what should i do for this problem up to now i have just removed the keyword abstract and it works fine,['java'] +375783,are python exceptions as class attributes a bad thing i find myself often wanting to structure my exception classes like this legendspyclass errorexception passclass rickobject class errorerror pass class gaveyouuperror pass class letyoudownerror passclass michaelobject class errorerror pass class blameditonthesunshineerror pass class blameditonthemoonlighterror passi have only seen this pattern used in django doesnotexist and it makes so much sense is there anything i am missing why most people seem to favor toplevel exceptionsediti would use these classes for versatile granularity egimport legendstry do stuffexcept legendsmichaelerror blame it on the boogieexcept legendsrickgaveyouup let you downexcept legendserror passexcept exception as e raise hell,['python'] +375787,how does the c11 rangebased for loop know the array size when i do something like thisint my array5 1 2 3 4 5for int x my array x 2c11 obviously knows that my array only has 5 elements is this information stored somewhere in the my array objectif so is there any good reason why it is not made available to me as a developer or is it it seems that a lot of the worlds problems would be solved if c devs always knew the bounds of the arrays they are dealing with,['c++'] +375857,enums in processing 20 this question refers to version 121 and it does not compile at a different part so it is not a duplicatei want to use enums in processing i have read they work better in a separate file so i have done that this code compiles correctlyenum status stoppedmovingbut when i have this codestatus statusin a different file it gives me the following errorunrecognized type46 enum defi know enums are not supported in earlier versions of processing but are they supported in version 20 if so whats cause the error,['java'] +375870,writing to console char by char fastest way in a current project of mine i have to parse a string and write parts of it to the console while testing how to do this without too much overhead i thiscovered that one way i was testing is actually faster than consolewriteline which is slightly confusing to mei am aware this is not the proper way to benchmark stuff but i am usually fine with a rough this is faster than this which i can tell after running it a few timesstatic void mainstring args var timer new stopwatch timerrestart test1just a little test string timerstop consolewritelinetimerelapsed timerrestart test2just a little test string timerstop consolewritelinetimerelapsed timerrestart test3just a little test string timerstop consolewritelinetimerelapsedstatic void test1string str consolewritelinestrstatic void test2string str foreach var c in str consolewritec consolewritenstatic void test3string str using var stream new streamwriterconsoleopenstandardoutput foreach var c in str streamwritec streamwriten as you can see test1 is using consolewriteline my first thought was to simply call write for every char see test2 but this resulted in taking roughly twice as long my guess would be that it flushes after every write which makes it slower so i tried test3 using a streamwriter autoflush off which resulted in being about 25 faster than test1 and i am really curious why that is or is it that writing to the console cannot be benchmarked properly noticed some strange data when adding more test casescan someone enlighten mealso if there is a better way to do this going though a string and only writing parts of it to the console feel free to comment on that,['c#'] +375874,elegant grid search in pythonnumpy i have a function that has a bunch of parameters rather than setting all of the parameters manually i want to perform a grid search i have a list of possible values for each parameter for every possible combination of parameters i want to run my function which reports the performance of my algorithm on those parameters i want to store the results of this in a manydimensional matrix so that afterwords i can just find the index of the maximum performance which would in turn give me the best parameters here is how the code is written nowparam1 list p11 p12 p13param2 list p21 p22 p23 not necessarily the same number of valuesresults size lenparam1 list lenparam2 listresults npzerosresults size dtype npfloatfor param1 idx in rangelenparam1 list for param2 idx in rangelenparam2 list param1 param1 listparam1 idx param2 param2 listparam2 idx resultsparam1 idx param2 idx my funcparam1 param2 max index npargmaxresults indices of best parametersi want to keep the first part where i define the lists asis since i want to easily be able to manipulate the values over which i searchi also want to end up with the results matrix as is since i will be visualizing how changing different parameters affects the performance of the algorithmthe bit in the middle though is quite repetitive and bulky especially because i have lots of parameters and i might want to add or remove parameters and i feel like there should be a more succinctelegant way to initialize the results matrix iterate over all of the indices and set the appropriate parametersso is there,['python'] +375881,inline svg best alternative to alt tag normally used for img seo say i were to swap out an img within my main site header to use svg instead normally i would depend on the imgs alt tag is the svg title the best replacement method for alt with this type of changeover svg roleimg arialabeltitle description here titletitle heretitle desclong description heredesc svg,['html'] +375889,using stdmutex stdcondition variable and stdunique lock i am having some trouble understanding condition variables and their use with mutexes i hope the community can help me with please note i come from a win32 background so i am used with critical section handle setevent waitformultipleobject etcheres my first attempt at concurrency using the c11 standard library it is a modified version of a program example found hereinclude condition variableinclude mutexinclude algorithminclude threadinclude queueinclude chronoinclude iostreamint tmainint argc tchar argv stdqueueunsigned int nnumbers stdmutex mtxqueue stdcondition variable cvqueue bool m bqueuelocked false stdmutex mtxquit stdcondition variable cvquit bool m bquit false stdthread thrquit using namespace std this threadsleep forchronoseconds7 set event by setting the bool variable to true then notifying via the condition variable m bquit true cvquitnotify all stdthread thrproducer using namespace std int nnum 0 unique lockmutex lock mtxquit while m bquit cvquitwait for lock chronomilliseconds10 cv statustimeout nnum unique lockmutex qlockmtxqueue cout produced nnum n nnumberspush nnum stdthread thrconsumer using namespace std unique lockmutex lock mtxquit while m bquit cvquitwait for lock chronomilliseconds10 cv statustimeout unique lockmutex qlockmtxqueue if nnumberssize 0 cout consumed nnumbersfront n nnumberspop thrquitjoin thrproducerjoin thrconsumerjoin return 0a few questions about thisi have read that any thread that intends to wait on stdcondition variable must acquire an stdunique lock firstso i have got a quit mutex condition variable bool to indicate when quit has been signalled the producer and consumer threads must each acquire an stdunique lock as sostdunique lockstdmutex lockm mtxquitthis is confusing the hell out of me would not this lock the quit mutex in the first thread thereby blocking the second and if that is true then how does the first thread release the lock so that the other thread can beginanother question if i change the wait for call to wait for zero seconds that thread is starved can someone explain i would expect it not to block before executing the while loop am i correct to assume that a no timeout is recvd instead of a timeouthow can i call a wait for and specify a zero time so that the wait for call does not block instead it just checks the condition and continuesi would also be interested to hear about good references on this subject,['c++'] +375936,android path of assets folder for file i have some files in the assets folder of my project and i want to list them so i put this in my codefile dir new filecompackagenameassetsfontsfile filelist dirlistfileswhich path should i put to make it worki want it so users could install new fonts i dont know how to do this yet so i need to list all the fonts in the folder including postinstalled fonts if there is any other solutions please share,"['java', 'android']" +375951,show a balloon notification i am trying to use the below code to show a balloon notification i have verified that it is being executed by using breakpoints it is also showing no errorswhat should i do to debug this since it is not throwing errors and not showing the balloonprivate void showballoonstring title string body notifyicon notifyicon new notifyicon notifyiconvisible true if title null notifyiconballoontiptitle title if body null notifyiconballoontiptext body notifyiconshowballoontip30,"['c#', '.net']" +375954,greendao schema update and data migration i am evaluating greendao for consideration in a commercial android app i will be working on and wanted to determine the migration path for schema updatesam i correct in asserting that i would have to write a custom openhelper which provides the onupdate and extracts transforms and stores data according to the new schema this assumption raises some interesting questions around ordering of calls and partitioning of responsibilityi have not been able to find any documentation around schema update and data migration for greendaohere are a bunch of blog articles i have written on this topicreview of greendaopart 1 a schema generationpart 2 a schema migrationpart 3 a testing schema migration,['android'] +375958,deleting file created from mysql i executed the query in mysql asselect into outfile tmpresultsout from table xwhich inturn wrote all the records in that table to the file in tmp directory the file was created with the following permissionsrwrwrw 1 mysql mysql 66k nov 14 1014 tmpresultsouti know that it is not possible to delete this file from my login but i tried removing this from mysql but i get the following error messagemysql system rm tmpresultsoutrm cannot remove tmpresultsout operation not permittedps i do not have root permissions,"['mysql', 'sql']" +375965,preg match all into simple array i have preg match all functionpreg match allh2h2is source output preg set orderit is working as intended but the problem is it preg matches all items twice and into a huge multi dimensional array like this for example where it as intended preg matched all 11 items needed but twice and into a multidimensional arrayarray 0 array 0 h210 emcruelem by st vincenth2 1 10 emcruelem by st vincent 1 array 0 h29 emrobot rockem by daft punkh2 1 9 emrobot rockem by daft punk 2 array 0 h28 emseven nation armyem by the white stripesh2 1 8 emseven nation armyem by the white stripes 3 array 0 h27 emdo you want toem by franz ferdinandh2 1 7 emdo you want toem by franz ferdinand 4 array 0 h26 emteenage dreamem by katie perryh2 1 6 emteenage dreamem by katie perry 5 array 0 h25 emcrazyem by gnarls barkleyh2 1 5 emcrazyem by gnarls barkley 6 array 0 h24 emkidsem by mgmth2 1 4 emkidsem by mgmt 7 array 0 h23 embad romanceem by lady gagah2 1 3 embad romanceem by lady gaga 8 array 0 h22 empumped up kicksem by foster the peopleh2 1 2 empumped up kicksem by foster the people 9 array 0 h21 emparathiseem by coldplayh2 1 1 emparathiseem by coldplay 10 array 0 h2song that get stuck in your head youtube playlisth2 1 song that get stuck in your head youtube playlist how to convert this array into simple one and without those duplicated items thank you very much,['php'] +375995,how can i addsubview to uibutton in interface builder like i said i add a uibutton in interface builder i want add a uilabelauiimageview as the buttons subviews but i cannot add any object on it in ib is anybody know how to do this thank you very muchi can use code to achieve that but i want achieve it in ib so i can use it in any class i want,['ios'] +376054,mulitprocessing terminate and corrupt queues whilst looking at the python doc for multiprocessingterminate i came across the followingterminate if this method is used when the associated process is using a pipe or queue then the pipe or queue is liable to become corrupted and may become unusable by other process similarly if the process has acquired a lock or semaphore etc then terminating it is liable to cause other processes to deadlockwhich basically says if you terminate a process which is using a queue pipe or similar you run the risk of the structure becoming corrupt i have a couple of questions about thiswhat will happen to another process trying to retrieve the data from the pipe queue or similar if a corruption occurshow can a process check to see if there is corruptioncan the deadlock be resolved in any way if you know another process has been terminatedi understand you should always try to not use terminate but this is for that situation where you cannot do anything else but this,['python'] +376128,lcov can not collect branch coverage statistics i used the lcov to create coverage information in my project but i only can get line coverage and function coverage statistics information lcov version110 gcov version445the commands i used is lcov d ospl homesrc d ospl outer homesrc c o workliloglcovrawinfolcov r workliloglcovrawinfo ll yy yyc yaccpar tao161 usrinclude testsuite o workliloglcovinfoafter these two commands i got the results is deleted 23 fileswriting data to workliloglcovinfosummary coverage rate lines 454 65087 of 143496 lines functions 461 5575 of 12102 functions branches no data foundso there were no branches coverage results why so what happened and how can this happen i am confused hereafter the first command i got lots of warnings like thesegeninfo warning cannot find an entry for codeaccumcgcov in gcno file skipping file geninfo warning cannot find an entry for codeatcgcov in gcno file skipping file geninfo warning cannot find an entry for codeautodefcgcov in gcno file skipping file geninfo warning cannot find an entry for codecopyofcgcov in gcno file skipping file geninfo warning cannot find an entry for codedebugcgcov in gcno file skipping file geninfo warning cannot find an entry for codedefinecgcov in gcno file skipping file geninfo warning cannot find an entry for codedumpcgcov in gcno fileskipping file geninfo warning cannot find an entry for codeerrorcgcov in gcno file skipping file geninfo warning cannot find an entry for codeexpandcgcov in gcno file skipping file geninfo warning cannot find an entry for codeexprcgcov in gcno fileskipping file geninfo warning cannot find an entry for codeifcgcov in gcno file skipping file geninfo warning cannot find an entry for codeincludecgcov in gcno file skipping file geninfo warning cannot find an entry for codeiocgcov in gcno file s kipping file geninfo warning cannot find an entry for codeiscgcov in gcno file s kipping file geninfo warning cannot find an entry for codelinecgcov in gcno fileskipping file geninfo warning cannot find an entry for codepragmacgcov in gcno file skipping file geninfo warning cannot find an entry for codepreprocesscgcov in gcnofile skipping file geninfo warning cannot find an entry for codesetcgcov in gcno fileskipping file geninfo warning cannot find an entry for codesharpcgcov in gcno file skipping file geninfo warning cannot find an entry for codesymtblcgcov in gcno file skipping file geninfo warning cannot find an entry for codeundefcgcov in gcno file skipping file geninfo warning cannot find an entry for codewhilecgcov in gcno file skipping file,['c'] +376190,is it possible to start activity through adb shell i want to start activity through adb shell so that i can launch a specific activity that is needed,['android'] +376214,why is jenkins android emulator plugin recreating my emulator snapshots in every build i use jenkins to build one of my projects the android emulator plugin automatically starts an emulator with the following configuration configuration of the emulator plugin every time the job is running i get the following output erasing existing emulator data cihometoolsandroidsdktoolsemulator nobootanim ports6447064471 prop persistsyslanguagede prop persistsyscountrydeavd hudson dede 240 480x720 google inc google apis 8 nosnapshotload nosnapshotsave wipedatashell input keyevent 4 android giving the system some time to settlebefore creating initial snapshot localhost64471 shell log p v t jenkins creating snapshotandroid creating snapshot full log below it seems that the plugin is creating a new emulator every time and is not using snapshots this takes something between 2 and 4 minutes depending on the emulator configuration the plugin creates avd and ini files in the androidavd directory inside the job folder the avds are not deleted after the run processif i thisable the use snapshots config the emulator needs less then a minute to start is this an issue with the emulator plugin or are snapshots not possible because of my configuration i hope that using snapshots will speed up my building process a lotfull log cihometoolsandroidsdktoolsandroid list target androidusing android sdk cihometoolsandroidsdk android adding 200msd card to avd hudson dede 240 480x720 google inc google apis 8android setting hardware properties hwramsize 512 cihometoolsandroidsdkplatformtoolsadb startserver cihometoolsandroidsdktoolsemulator snapshotlist nowindow avd hudson dede 240 480x720 google inc google apis 8android starting android emulator and creating initial snapshotandroid erasing existing emulator data cihometoolsandroidsdktoolsemulator nobootanim ports 6447064471 prop persistsyslanguagede prop persistsyscountryde avd hudson dede 240 480x720 google inc google apis 8 nosnapshotload nosnapshotsave wipedata daemon not running starting it now on port 64472 daemon started successfully cihometoolsandroidsdkplatformtoolsadb connect localhost64471android waiting for emulator to finish booting cihometoolsandroidsdkplatformtoolsadb s localhost64471 shell getprop devbootcomplete error device offline cihometoolsandroidsdkplatformtoolsadb connect localhost64471 cihometoolsandroidsdkplatformtoolsadb s localhost64471 shell getprop devbootcomplete cihometoolsandroidsdkplatformtoolsadb connect localhost64471 cihometoolsandroidsdkplatformtoolsadb s localhost64471 shell getprop devbootcomplete cihometoolsandroidsdkplatformtoolsadb thisconnect localhost64471 cihometoolsandroidsdkplatformtoolsadb connect localhost64471 cihometoolsandroidsdkplatformtoolsadb s localhost64471 shell getprop devbootcomplete cihometoolsandroidsdkplatformtoolsadb connect localhost64471 cihometoolsandroidsdkplatformtoolsadb s localhost64471 shell getprop devbootcomplete cihometoolsandroidsdkplatformtoolsadb connect localhost64471 cihometoolsandroidsdkplatformtoolsadb s localhost64471 shell getprop devbootcomplete cihometoolsandroidsdkplatformtoolsadb s localhost64471 logcat v time cihometoolsandroidsdkplatformtoolsadb connect localhost64471android attempting to unlock emulator screen cihometoolsandroidsdkplatformtoolsadb s localhost64471 shell input keyevent 82 cihometoolsandroidsdkplatformtoolsadb s localhost64471 shell input keyevent 4android giving the system some time to settle before creating initial snapshot cihometoolsandroidsdkplatformtoolsadb connect localhost64471 cihometoolsandroidsdkplatformtoolsadb s localhost64471 logcat c cihometoolsandroidsdkplatformtoolsadb s localhost64471 shell log p v t jenkins creating snapshotandroid creating snapshot cihometoolsandroidsdkplatformtoolsadb connect localhost64471android emulator is ready for use took 158 secondsbuildfile for an example job xml version10 encodingutf8project actions descriptiondescription keepdependenciesfalsekeepdependencies properties scm classhudsonpluginsgitgitscm configversion2configversion userremoteconfigs hudsonpluginsgituserremoteconfig namename refspecrefspec urlgitprojecturl hudsonpluginsgituserremoteconfig userremoteconfigs branches hudsonpluginsgitbranchspec namemastername hudsonpluginsgitbranchspec branches thisablesubmodulesfalsethisablesubmodules recursivesubmodulesfalserecursivesubmodules dogeneratesubmoduleconfigurationsfalsedogeneratesubmoduleconfigurations authororcommitterfalseauthororcommitter cleanfalseclean wipeoutworkspacefalsewipeoutworkspace prunebranchesfalseprunebranches remotepollfalseremotepoll ignorenotifycommitfalseignorenotifycommit useshallowclonefalseuseshallowclone buildchooser classhudsonpluginsgitutildefaultbuildchooser gittooldefaultgittool submodulecfg classlist relativetargetdirrelativetargetdir referencereference excludedregionsexcludedregions excludedusersexcludedusers gitconfignamegitconfigname gitconfigemailgitconfigemail skiptagfalseskiptag includedregionsincludedregions scmnamescmname scm canroamtruecanroam thisabledfalsethisabled blockbuildwhendownstreambuildingtrueblockbuildwhendownstreambuilding blockbuildwhenupstreambuildingtrueblockbuildwhenupstreambuilding triggers classvector hudsontriggersscmtrigger spec5 spec hudsontriggersscmtrigger triggers concurrentbuildfalseconcurrentbuild builders hudsontasksant targetsclean debug installtargets antnamedefaultantname hudsontasksant hudsontasksant targetstargets antnamedefaultantname buildfilecheckstyleantxmlbuildfile hudsontasksant hudsontasksshell commandos optsquotdjavaawtheadlesstruequot lint xml lintresultsxml command hudsontasksshell hudsonpluginsandroid emulatormonkeymonkeybuilder packageiddepackageid eventcount10eventcount throttlems10throttlems seedtimestampseed hudsonpluginsandroid emulatormonkeymonkeybuilder hudsontasksshell thistribution script hudsontasksshell builders publishers orgjenkinscipluginsandroid lintlintpublisher healthyhealthy thresholdlimitlowthresholdlimit pluginnameandroidlint pluginname defaultencodingdefaultencoding canrunonfailedfalsecanrunonfailed usestablebuildasreferencefalseusestablebuildasreference usedeltavaluesfalseusedeltavalues thresholds unstabletotalallunstabletotalall unstabletotalhighunstabletotalhigh unstabletotalnormalunstabletotalnormal unstabletotallowunstabletotallow unstablenewallunstablenewall unstablenewhighunstablenewhigh unstablenewnormalunstablenewnormal unstablenewlowunstablenewlow failedtotalallfailedtotalall failedtotalhighfailedtotalhigh failedtotalnormalfailedtotalnormal failedtotallowfailedtotallow failednewallfailednewall failednewhighfailednewhigh failednewnormalfailednewnormal failednewlowfailednewlow thresholds shoulddetectmodulesfalseshoulddetectmodules dontcomputenewfalsedontcomputenew donotresolverelativepathsfalsedonotresolverelativepaths patternpattern orgjenkinscipluginsandroid lintlintpublisher hudsonpluginscheckstylecheckstylepublisher healthyhealthy unhealthyunhealthy thresholdlimitlowthresholdlimit pluginnamecheckstyle pluginname defaultencodingdefaultencoding canrunonfailedfalsecanrunonfailed usestablebuildasreferencefalseusestablebuildasreference usedeltavaluesfalseusedeltavalues thresholds unstabletotalallunstabletotalall unstabletotalhighunstabletotalhigh unstabletotalnormalunstabletotalnormal unstabletotallowunstabletotallow failedtotalallfailedtotalall failedtotalhighfailedtotalhigh failedtotalnormalfailedtotalnormal failedtotallowfailedtotallow thresholds shoulddetectmodulesfalseshoulddetectmodules dontcomputenewtruedontcomputenew donotresolverelativepathsfalsedonotresolverelativepaths patternpattern hudsonpluginscheckstylecheckstylepublisher hudsonpluginswarningswarningspublisher healthyhealthy unhealthyunhealthy thresholdlimitlowthresholdlimit pluginnamewarnings pluginname defaultencodingdefaultencoding canrunonfailedfalsecanrunonfailed usestablebuildasreferencefalseusestablebuildasreference usedeltavaluesfalseusedeltavalues thresholds unstabletotalallunstabletotalall unstabletotalhighunstabletotalhigh unstabletotalnormalunstabletotalnormal unstabletotallowunstabletotallow failedtotalallfailedtotalall failedtotalhighfailedtotalhigh failedtotalnormalfailedtotalnormal failedtotallowfailedtotallow thresholds shoulddetectmodulesfalseshoulddetectmodules dontcomputenewtruedontcomputenew donotresolverelativepathstruedonotresolverelativepaths parserconfigurations consoleparsers hudsonpluginswarningsconsoleparser parsernamejava compiler eclipseparsername hudsonpluginswarningsconsoleparser consoleparsers hudsonpluginswarningswarningspublisher hudsonpluginsanalysiscollectoranalysispublisher healthyhealthy unhealthyunhealthy thresholdlimitlowthresholdlimit pluginnameanalysiscollector pluginname defaultencodingdefaultencoding canrunonfailedfalsecanrunonfailed usestablebuildasreferencefalseusestablebuildasreference usedeltavaluesfalseusedeltavalues thresholds unstabletotalallunstabletotalall unstabletotalhighunstabletotalhigh unstabletotalnormalunstabletotalnormal unstabletotallowunstabletotallow failedtotalallfailedtotalall failedtotalhighfailedtotalhigh failedtotalnormalfailedtotalnormal failedtotallowfailedtotallow thresholds shoulddetectmodulesfalseshoulddetectmodules dontcomputenewtruedontcomputenew donotresolverelativepathstruedonotresolverelativepaths ischeckstyledeactivatedfalseischeckstyledeactivated isdrydeactivatedtrueisdrydeactivated isfindbugsdeactivatedtrueisfindbugsdeactivated ispmddeactivatedtrueispmddeactivated isopentasksdeactivatedtrueisopentasksdeactivated iswarningsdeactivatedfalseiswarningsdeactivated hudsonpluginsanalysiscollectoranalysispublisher hudsonpluginsandroid emulatormonkeymonkeyrecorder failureoutcomefailurefailureoutcome hudsonpluginsandroid emulatormonkeymonkeyrecorder hudsonpluginscigamegamepublisher hudsontasksmailer recipientsrecipients dontnotifyeveryunstablebuildfalsedontnotifyeveryunstablebuild sendtoindividualstruesendtoindividuals hudsontasksmailer publishers buildwrappers hudsonpluginslocksandlatcheslockwrapper locks hudsonpluginslocksandlatcheslockwrapper lockwaitconfig nameandroidemulatorname hudsonpluginslocksandlatcheslockwrapper lockwaitconfig locks hudsonpluginslocksandlatcheslockwrapper hudsonpluginsandroid emulatorandroidemulator osversiongoogle incgoogle apis8osversion screendensity240screendensity screenresolution480x720screenresolution devicelocalede dedevicelocale sdcardsize200msdcardsize hardwareproperties hudsonpluginsandroid emulatorandroidemulator hardwareproperty keyhwramsizekey value512value hudsonpluginsandroid emulatorandroidemulator hardwareproperty hardwareproperties wipedatafalsewipedata showwindowtrueshowwindow usesnapshotstrueusesnapshots deleteafterbuildfalsedeleteafterbuild startupdelay0startupdelay commandlineoptionscommandlineoptions hudsonpluginsandroid emulatorandroidemulator buildwrappersproject,['android'] +376232,wpf mvvm combobox tag selection i have a combobox that has a declared comboboxitems list in other words not dynamically bound via itemssource i use the comboboxitemcontent for the thisplay name and comboboxitemtag for the corresponding id as shown belowhow do i get the tag of the selected item return and not the content i tried selecteditemvaluepathtag but that does not work combobox visibilitybinding pathshowoutpatientfields converter staticresource booltovisconverter gridrow5 gridcolumn2 margin0202 textbinding pathnewcaseservicetype validatesondataerrorstrue notifyonvalidationerrortrue selectedvaluepathtag comboboxitems comboboxitem contenthospice tag33 comboboxitem contenthospital outpatient tag36 comboboxitem contenthospital inpatient extension tag128 comboboxitem contentmaternity tag52 comboboxitems combobox,['c#'] +376246,php undefined variable in a closure the following snippet returns a bunch of input fields but i am unable to set their values because data is undefined it being inside a closurerow array mapfunctionn name sprintfpoint0d n1 value datameasurementsn return form inputname value classinputmini rangei6 i65i know global variables are not cool whats the best way to get around this,['php'] +376287,square bracket syntax vs functions for localstorage what is the difference between the following two snippets of code is the square bracket syntax an old deprecated syntax when i first used localstorage all the documentation i found definitely said to use the square bracket syntax but now i cannot find any documentation on it at allthe documented syntaxlocalstoragesetitemhello worldlocalstoragegetitemhello worldthe square bracket syntaxlocalstoragehello worldlocalstoragehello world,['javascript'] +376290,common encryptdecrypt code example for c and nodejscrypto i am attempting to use application request routing arr in iis for passing a set of paths to a nodejs website my issue is being able to getset the authentication ticket on either sidei just really need a simple example of an encryptdecrypt pair that will work for c and nodejs close to out of the box with the same results for both i will be working on this problem myself as time permits over the next few days and intend to answer if nobody comes up with an answer before memy intention is to write the node side as a connectexpress module on the nodejs side i am already doing a custom authentication in the aspnet solution and can easily replace my current method with something that can be secure from both platforms so long as they share the same keycurrent code to create the authentication cookie in accountcontrollercsprivate void processuserloginmyentitymodel db siteuser user bool rememberfalse var roles stringjoin valueusersiterolesselectsr srnametolowerinvarianttrimthistincttoarray update the laston records useruseragent requestuseragent userlaston datetimeoffsetutcnow dbsavechanges create and tuck away the cookie var authticket new formsauthenticationticket 1 userusername datetimenow datetimenowadays31 max 31 days remember stringisnullorwhitespaceroles guest roles var ticket formsauthenticationencryptauthticket var cookie new httpcookieformsauthenticationformscookiename ticket if remember cookieexpires datetimenowadays8 responsecookiesaddcookiecurrent code to read the authentication cookie in globalasaxcsvoid application authenticaterequestobject sender eventargs args httpcookie authcookie contextrequestcookiesformsauthenticationformscookiename if authcookie null return formsauthenticationticket authticket formsauthenticationdecryptauthcookievalue string roles authticketuserdatasplitnew char create new generic identity and corresponding principal var g new genericidentityauthticketname var up new genericprincipalg roles set principal for current request thread app will handle transitions from here threadcurrentprincipal contextuser uprelevant portion of the webconfigxml version10 encodingutf8configuration systemweb membership providers remove default providers so custom override works clear providers membership systemwebconfiguration,['c#'] +376306,jquery offset broken by body positionrelative combined with element margin this is not a bug because the behaviour is consistent across ff chrome ie9 and safari on win7 the app i am working on is 3rd party to the host page so the css is immutablethe script attempts to align a new div with an existing elementthe body is positionrelativethere is an h1 at the top of the pagethe margin from the h1 seems to change where the body 00 is calculated from even though the background on the body extends all the way to the edge and it is offsettop property reports 0setting a border on the body solves the problem seems strange behaviour but is consistent across browsers not a viable solutionremoving the h1 margins solves the problem not a viable solutionexample here the js is commented for replicating each casei do not think this is a bug with jquery it seems to be down to a legitimate relationship between the h1 margin and the body elementfunction setting body to positionrelative breaks offset because h1 margin moves body down documentbodycssposition relative strange putting a border on body fixes things documentbodycssborder 1px solid 0 removing h1 margin removes problem h1cssmargin 0 overlaycss left existingoffsetleft top existingoffsettop,"['javascript', 'jquery', 'css']" +376321,is there any embedable keyvalue store for ruby i need fast and reliable keyvalue store for ruby is there anything like it already the requirement is for it to run wholly inside the ruby process not needing any outside processesit might be inmemory with explicit thisk flushesit needs to have minimal valueforkey retrieval times write times may be not so goodthe amount of data stored would not be terrible about few hundred thousand keys each with 1kb text value,['ruby'] +376329,multiple select and join with linq and lambda how can i do this query using linq and lambda queryselect san negocioimovel id san negocionegocio id san imovelcredenciada id san propostaproposta id san propostacredenciada id from san negocio join san proposta on san negocioimovel id san propostaimovel id join san imovel on san negocioimovel id san imovelimovel id where san negociocredenciadacaptadora id is null and san negociocredenciadavendedora id is null and san propostastatusproposta id 2i have triedvar objetos dbsan negociojoindbsan proposta a aimovel id b bimovel id a b new san negocio a san proposta b joindbsan imovel a asan negocioimovel id c cimovel id a c new san negocio a san imovel c wherea asan negociosan negociocredenciadacaptadora id null asan negociosan negociocredenciadavendedora id null selecta new asan negociosan negocionegocio id asan negociosan negocioimovel id asan imovelcredenciada id my doubt is in my select how can i call my san proposta table,['c#'] +376342,how to sleep in c possible duplicatewhy does printf not flush after the call unless a newline is in the format string when i run something like for i 1 i 10 i sleep1 printfthen what i would expect is one dot per second ten times what i get is ten dots once after ten seconds why is that so and how do i get the program to actually print one point or do other things each second or different time interval,['c'] +376343,how can i remove extra whitespace from strings when parsing a csv file in pandas i have the following file named datacsv 1997forde350 1997 ford e350 1997forde350super luxurious truck 1997forde350super luxurious truck 1997forde350 super luxurious truck 1997forde350 1997forde350 20mercurycougarand i would like to parse it into a pandas dataframe so that the dataframe looks as follows year make model description 0 1997 ford e350 none 1 1997 ford e350 none 2 1997 ford e350 super luxurious truck 3 1997 ford e350 super luxurious truck 4 1997 ford e350 super luxurious truck 5 1997 ford e350 none 6 1997 ford e350 none 7 20 mercury cougar nonethe best i could do was pdread tabledatacsv sepr namesyear make model descriptionwhich gets me year make model description 0 1997 ford e350 none 1 1997 ford e350 none 2 1997 ford e350 super luxurious truck 3 1997 ford e350 super luxurious truck 4 1997 ford e350 super luxurious truck 5 1997 ford e350 none 6 1997 ford e350 none 7 20 mercury cougar nonehow can i get the dataframe without those whitespaces,['python'] +376397,determining if two time ranges overlap at any point possible duplicatedetermine whether two date ranges overlap i am trying to work out if two time ranges in php overlap i have been referring to determine whether two date ranges overlap for my initial try however it is not matching all cases if a time range is nested in between the start and end times of another time range it is not being matched if it overlaps the beginning or the end of the shift or if the shifts are exact matches it works as expectedcheck out this image of what i am talking aboutbasically i am trying to hide any orange shifts if they overlap any red shifts anywhere heres the relevant portion of code i am trying to use to make this happenifredstart orangeend redend orangestart conflict handlingthe values of the variables are unix timestamps working through the numbers logically i understand why the statement above fails there are obviously ways i could do more logic to determine if the one shift falls in the other shift which is what i may need to do but i was hoping for a more universal catchedit adding the values of each blocks start and end time i agree what i have should work the fact that it is not is where my issue lies i am probably overlooking something dumborangestart 1352899800orangeend 13529070redstart 1352923200redend 1352926200therefore my logic would stateif1352923200 13529070 1352926200 1352899800so following that the first comparison failsedit 2 it looks like my logic is sound which i thought was the case and my issue is something related to the unix timestamp not matching the actual time being thisplayed i thank those who worked though this with me and help me thiscover that as being the issue i wish i could accept both andreys and jasons answers,['php'] +376415,using composer with local dependencies i know composer because of symfony2 but now i would like to use it as a standalone part i followed the instructions that its documentation said but do not know how to set a local library as a dependency how to load itin other words how to load a local repository using composer instead of referencing a remote one,['php'] +376421,xcode 45 warns about method name conflicts between categories for parentchild classes i am working on a project that was originally built in xcode 40 and then migrated to using xcode 42 now i have tested out migrating to xcode 45 and i am getting a ton of warnings like belowinstance method values in category from pathtothefilehistoryobjectextraso conflicts with same method from another categorythese warnings never appeared in previous versions of xcode and the code has not changedthe project is set at ios 43 for the deployment targetso we have from a previous developer a bunch of dao type classes that i believe were autogenerated from coredata and then each of these classes has a category that extends it to implement certain methods i will give an examplewe have a base class named lisaobject that inherits from nsmanagedobject and it has a category named lisaobjectextras in lisaobjectextras there is a method named values that returns an nsmutabledictionarywe then have a class named historyobject that inherits from lisaobject there is also a category for historyobject that is named histroyobjectextras this category also has a method named values in the historyobjectextras values method it calls super values and then checks for some conditions and sets some additional values in the dictionary that are not set in the base class methodwe then have a class named lessonstatusobject that inherits from historyobject and it too has a category named lessonstatusobjectextras which has a method named values this values method also calls super values and then does some additional work on the returned dictionaryfor each of these values methods we get a warning at compile time like the one shown above where it says the category has a method with a conflicting namei have a few questions about this first could this implementation cause any legitimate problems or are these warnings generally benign i have tried to think of how this implementation could cause an ambiguity at runtime but i do not see how that could happensecond is there something that i should do to fix these warnings and i do not mean just make them stop appearing i mean fix the cause is there some other way we should be going about thisalso why would xcode 42 not warn about this but xcode 45 does warnam i misunderstanding something about categories i mean if the values method was actually part of the each class implementation it wouldnt be a problem to override them the way we do but the compiler seems to be complaining simply because these are categories is there anything unsafe about thisany advice is much appreciatededit just to provide more information when we were using xcode 42 the project had the compiler set to apple llvm compiler 30 now when i open the project in xcode 45 it has the compiler set to apple llvm compiler 41,"['objective-c', 'ios']" +376429,locating segmentation fault for mutithread program running on cluster it is quite straightforward to use gdb in order to locate a segmentation fault while running a simple program in interactive mode but consider we have a multithread program written by pthread submitted to a cluster node by qsub command so we do not have an interactive operationhow we can locate the segmentation fault i am looking for a general approach a program or test tool i can not provide a reproducible example as the program is really big and crashes on the cluster in some unknown situationsi need to find a problem in such hard situation because the program runs correctly on the local machine with any number of threads,['c++'] +376454,balancing groups in variablelength lookbehind tldr using capturing and in particular balancing groups inside nets lookbehinds changes the obtained captures although it should not make a difference what is it with nets lookbehinds that breaks the expected behaviori was trying to come up with an answer to this other question as an excuse to play around with nets balancing groups however i cannot get them to work inside a variablelength lookbehindfirst of all note that i do not intend to use this particular solution productively it is more for academic reasons because i feel that there is something going on with the variablelength lookbehind which i am not aware of and knowing that could come in handy in the future when i actually need to use something like this to solve a problemconsider this inputa b c d e f g h i j k l m n p qthe goal is to match all letters that are inside parentheses that are preceded by not matter how deep down so everything from a to i my attempt was to check for the correct position in a lookbehind so that i can get all letters in a single call to matches here is my patterndepthdepthazin the lookbehind i try to find a and then i use the named group stack depth to count extraneous opening parentheses as long as the parenthesis opened in is never closed the lookbehind should match if the closing parenthesis to that is reached depth cannot pop anything from the stack and the lookbehind should fail that is for all letters from j unfortunately this does not work instead i match a b c e f g and m so only thesea b c e f g m that seems to mean that the lookbehind cannot match anything once i have closed a single parenthesis unless i go back down to the highest nesting level i have been to beforeokay this could just mean there is something odd with my regular expression or i did not understand the balancing groups properly but then i tried this without the lookbehind i created a string for every letter like thisz b c d e f x y g h i j k l m na z c d e f x y g h i j k l m na b z d e f x y g h i j k l m na b c d e f x y g h i j k l z na b c d e f x y g h i j k l m zand used this pattern on each of thosedepthdepthzand as desired all cases match where z replaces a letter between a and i and all the cases after that failso what does the variablelength lookbehind do that breaks this use of balancing groups i tried to research this all evening and found pages like this one but i could not find a single use of this in a lookbehindi would also be glad if someone could link me to some indepth information about how the net regex engine handles netspecific features internally i found this amazing article but it does not seem to go into variablelength lookbehinds for instance,['.net'] +376458,unable to run android virtual device manager android avd getting nullpointerexception getting nullpointerexception when trying to start avd i just downloaded the adt bundle for mac and ran android avd anyone know why it would fail android avdjavalangnullpointerexception at comandroidsdklibinternalavdavdinfogetdevicenameavdinfojava158 at comandroidsdkuilibinternalrepositoryuidevicemanagerpagefilldevicesdevicemanagerpagejava497 at comandroidsdkuilibinternalrepositoryuidevicemanagerpagefilltabledevicemanagerpagejava357 at comandroidsdkuilibinternalrepositoryuidevicemanagerpagecreatecontentsdevicemanagerpagejava259 at comandroidsdkuilibinternalrepositoryuidevicemanagerpageinitdevicemanagerpagejava130 at comandroidsdkuilibinternalrepositoryuiavdmanagerwindowimpl1createdevicetabavdmanagerwindowimpl1java210 at comandroidsdkuilibinternalrepositoryuiavdmanagerwindowimpl1createcontentsavdmanagerwindowimpl1java193 at comandroidsdkuilibinternalrepositoryuiavdmanagerwindowimpl1openavdmanagerwindowimpl1java133 at comandroidsdkuilibrepositoryavdmanagerwindowopenavdmanagerwindowjava94 at comandroidsdkmanagermainshowavdmanagerwindowmainjava369 at comandroidsdkmanagermaindoactionmainjava311 at comandroidsdkmanagermainrunmainjava119 at comandroidsdkmanagermainmainmainjava102,['android'] +376466,android 42 broke my aes encryptdecrypt code it is my first time asking for help in here my department a government have published some app on the market google play and the encryption and description was working really well up to yesterday when i got the jelly bean 42 on my nexus the encrypt works fine it is in fact encrypt the information to be stored though when decrypt it i am getting an exception exactly like this pad block corruptedi have checked the string and it is consistent with it on others devices using the same key for test purposes meaning it is exactly the samethe problem is that we need keep the back compatibility with previous versions meaning that if i change something in the code it is should be able to read the old encrypted information the encrypted information it is stored on sqlite due that i need encode it to base64 the exception happen on this line byte decrypted cipherdofinalencryptedhere is my classimport javasecuritysecurerandomimport javaxcryptocipherimport javaxcryptokeygeneratorimport javaxcryptosecretkeyimport javaxcryptospecsecretkeyspecimport androidutilbase64public class encodedecodeaes private final static string hex 0123456789abcdef public static string encryptstring seed string cleartext throws exception byte rawkey getrawkeyseedgetbytes byte result encryptrawkey cleartextgetbytes string fromhex tohexresult string base64 new stringbase64encodetostringfromhexgetbytes 0 return base64 public static string decryptstring seed string encrypted throws exception string base64 new stringbase64decodeencrypted 0 byte rawkey getrawkeyseedgetbytes byte enc tobytebase64 byte result decryptrawkey enc return new stringresult public static byte encryptbytesstring seed byte cleartext throws exception byte rawkey getrawkeyseedgetbytes byte result encryptrawkey cleartext return result public static byte decryptbytesstring seed byte encrypted throws exception byte rawkey getrawkeyseedgetbytes byte result decryptrawkey encrypted return result private static byte getrawkeybyte seed throws exception keygenerator kgen keygeneratorgetinstanceaes securerandom sr securerandomgetinstancesha1prng srsetseedseed try kgeninit256 sr catch exception e logwlog this device does not suppor 256bits trying 192bits try kgeninit192 sr catch exception e1 logwlog this device does not suppor 192bits trying 128bits kgeninit128 sr secretkey skey kgengeneratekey byte raw skeygetencoded return raw private static byte encryptbyte raw byte clear throws exception secretkeyspec skeyspec new secretkeyspecraw aes cipher cipher ciphergetinstanceaes cipherinitcipherencrypt mode skeyspec byte encrypted cipherdofinalclear return encrypted private static byte decryptbyte raw byte encrypted throws exception secretkeyspec skeyspec new secretkeyspecraw aes cipher cipher ciphergetinstanceaes cipherinitcipherdecrypt mode skeyspec byte decrypted cipherdofinalencrypted return decrypted public static string tohexstring txt return tohextxtgetbytes public static string fromhexstring hex return new stringtobytehex public static byte tobytestring hexstring int len hexstringlength 2 byte result new bytelen for int i 0 i len i resulti integervalueofhexstringsubstring2 i 2 i 2 16bytevalue return result public static string tohexbyte buf if buf null return stringbuffer result new stringbuffer2 buflength for int i 0 i buflength i appendhexresult bufi return resulttostring private static void appendhexstringbuffer sb byte b sbappendhexcharatb 4 0x0fappendhexcharatb 0x0f i would like to know if somebody help me what m i doing wrong with this code or if it is a issue with android 42 and if it is a issue with 42 if has any workaroundthank you,['android'] +376470,how to use xmlwritersettings when using override void writeendelement i am working with a legacy application that does not import abbreviated empty xml elements for examplebad emptyfoo good emptyfoofooi know the solution to achieve this which i will present nowpublic class xmltextwriterfull xmltextwriter public xmltextwriterfullstream stream encoding enc basestream enc public xmltextwriterfullstring str encoding enc basestr enc public override void writeendelement basewritefullendelement and the client code var x settings new xmlwritersettings x settingsnewlinechars environmentnewline x settingsnewlineonattributes true x settingsnewlinehandling newlinehandlingreplace x settingscloseoutput true x settingsindent true x settingsnewlineonattributes true var memout new memorystream var writer new xmltextwriterfulloutputfilename encodingutf8 or the encoding of your choice var x serial new xmlserializertypeofyour object type x serialserializewriter your object instance writerclosehowever if you observed carefully the xmlwritersettings are never used in the client code therefore the xml output is terribly formatted my questions is this how do i adapt the above code to accept xmlwritersettings the use of factory creation methods and sealedinternalabstract classes makes this difficult to implement an overridei will accept an alternative solution i am not married to my above solutionworkaround solutionstep 1 create the following class in your solutionpublic class xmltextwriterfull xmltextwriter public xmltextwriterfulltextwriter sink basesink formatting formattingindented public override void writeendelement basewritefullendelement step 2 add the following client code make sure to replace your object type and your object instance with the class and instance your are working withtextwriter streamwriter new streamwriteroutputfilenamevar writer new xmltextwriterfullstreamwritervar x serial new xmlserializertypeof your object typex serialserializewriter your object instancewriterclosethe workaround above will produce the following empty xml element formattingfoofoothe issue with this workaround is that it adds a line feed notice the elements are on separate lines this may be acceptable for you but causes issues with my legacy application,['c#'] +376503,dynamically adding fragments with xml layout to gridlayout is not workng in our app we are trying to dynamically add fragments to a gridlayout the empty grid layout is defined in xml as is the layout for the fragment at run time we examine some data and from that determine the number of fragments to add to the layout as well as which layout to use for each fragment when we have the fragment assign a size to its generated view it all works however if we specify the size in the layout file for the fragment nothing shows up in the grid layout obviously we could simply specify the size when we create the view but we would prefer to do it in the xml layouts for the fragments because that would allow us to take advantage of androids built in system for selecting the correct layouts for each device i am using support library fragments i am not using support library gridlayout if that makes a differencethe relevant code and xml followsthe gridlayout xmlxml version10 encodingutf8merge xmlnsandroid scrollview androidididgrid scroll androidlayout widthmatch parent androidlayout heightmatch parent androidlayout aboveidbottom fragment androidlayout alignparentlefttrue androidlayout alignparenttoptrue androidlayout marginright8dp androidlayout margintopandroidattractionbarsize androidoverscrollmodeifcontentscrolls gridlayout androidididgrid androidlayout widthmatch parent androidlayout heightwrap content androidalignmentmodealignmargins androidanimatelayoutchangestrue androidcolumncount3 androidcolumnorderpreservedtrue androidorientationhorizontal androidoverscrollmodeifcontentscrolls androidroworderpreservedtrue gridlayout scrollviewmergean example of the fragment xmlxml version10 encodingutf8relativelayout xmlnsandroid androidlayout width200dp androidlayout height100dp androidalpha1 button androidididbutton1 androidlayout widthmatch parent androidlayout heightmatch parent androidalpha10 relativelayoutthe fragment oncreateview methodoverridepublic view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate superoncreateviewinflater container savedinstancestate view view gridlayoutspec rowspec gridlayoutspecmrowstart mrowspan gridlayoutspec columnspec gridlayoutlayoutparams childparams if large view inflaterinflaterlayoutmy place large container false columnspec gridlayoutspecmcolumnstart 2 childparams new gridlayoutlayoutparamsrowspec columnspec childparamswidth 200 if i do this everything works regardless of the layout size else view inflaterinflaterlayoutmy place small container false columnspec gridlayoutspecmcolumnstart 1 childparams new gridlayoutlayoutparamsrowspec columnspec childparamswidth 100 if i do this everything works regardless of the layout size childparamssetmargins0 0 0 0 childparamsheight 100 if i do this everything works regardless of the layout size viewsetlayoutparamschildparams viewsetidid return viewto add fragments to the layoutprivate void populategrid relativelayout gridparent relativelayout mparentactivityfindviewbyidridlocations mlocationsgrid gridlayout gridparentfindviewbyidridgrid ncolumns mlocationsgridgetcolumncount madapter new myadaptermcontext this mresolver this is how i keep track of the various fragments depending on my apps state int ncards madaptergetnumberofcards fragmentmanager fragmentmanager mparentactivitygetsupportfragmentmanager fragmenttransaction fragmenttransaction fragmentmanagerbegintransaction for int i 0 i ncards i fragmenttransactionaddmlocationsgridgetid madaptergetfragmentatindexi stringvalueofi fragmenttransactioncommit mpopulated truei think that should cover it just to reiterate if i uncomment the lines which explicitly set the dimension in oncreateview they show up properly in gridlayout so i know everything that keeps track of the fragments and such works as does the fragment transaction the issue comes when i try and specify the size in the fragments xml in which case i get a blank screen you thoughts suggestions and musings are appreciated thanksjared,['android'] +376543,about java get stringclass from stringclass what if stringclass is a runtime type here is a variable class cls now i want to get another array class object which component type is cls for example if clsstringclass i want to get stringclass if clsintclass i want to get intclass what should i do you see it is quite easy to get stringclass from stringclass class arrayclsstringclassifarrayclsisarray class clsarrayclsgetcomponenttypebut i cannot find easy way to do the reverse here is one possible solution class clazzstringclassclass arrayclassarraynewinstanceclazz0getclassis there any batter way to do this please,['java'] +376581,return multiple values in java i wrote a function in java and i want this function to return multiple values except use of array and structure is there a way to return multiple valuesmy code string query40 select good namequantityprice from tbl1 where good idxcursor c dbrawqueryquery nullif c null cmovetofirst goodnameshow cgetstring0 quantityshow cgetlong1 goodunitpriceshow cgetlong2 return goodnameshowquantityshow goodunitpriceshow,['java'] +376595,c find if lambda what is wrong with the code below it is supposed to find an element in the list of structs if the first of the structs memebers 0 the compiler complains about the lambda argument not being of type predicateinclude iostreaminclude stdinthinclude fstreaminclude listinclude algorithmstruct s int s1 int s2using namespace stdint main lists l s s1 s1s1 0 s1s2 0 s s2 s2s1 1 s2s2 1 lpush backs2 lpush backs1 listsiterator it find iflbegin lend s s return ss1 0,['c++'] +376639,wrapping python doctest results that are longer than 80 characters i am trying to keep my source code under the 80 character guideline width that pep8 recommends but cannot figure out how to wrap my doctest which has results longer than 80 charactersa noddy exampledef long string returns a string which is wider than the recommended pep8 linewidth print long string 0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789 return 0123456789 10i have tried a couple of combinations including using doctest normalize whitespace and trying to simply wrap the line with a newline,['python'] +376650,rjava not getting generated with intellij idea 12 i am brand new to android development and i am working with intellij idea 12everything is set up correctly but one problem i am facing is that my rjava file inside gen folder does not have the code that should have been therei think this code should have been auto generated but it is not present there here are the links on on what my project structure looks likei could not post more than two links so here is the link to galleryit contains my stringxml mainxml rjava haikuthisplayjavaso i wanted to know wheres the problem,['android'] +376680,xcode why launchoptions in didfinishlaunchingwithoptions always nil i want my app to do specific things when the app is launched by a click on a notification i want to do these specific things when the app is already running into background but also when the app is started from scratch not running into background by a click on the notificationwhen the app is started from background by a click on the notification i get the notification via voidapplicationuiapplication application didreceivelocalnotificationuilocalnotification notification no problem when the app is started from scratch by a click on the notification i would like to get the notification via boolapplicationuiapplication application didfinishlaunchingwithoptionsnsdictionary launchoptions uilocalnotification localnotif launchoptions objectforkeyuiapplicationlaunchoptionslocalnotificationkeybut launchoptions is always nil it is nil when the app is started from scratch via a click on the app icon normal but also when the app is started from scratch via a click on a notification not normalanybody knows how to solve this issue thanks edit 1here is how my notifications are created joe question nsdictionary userinfo nsdictionary dictionarywithobjectsnsarray arraywithobjectsnotiftextlatitudestringlongitudestringnilforkeysnsarray arraywithobjectsnotiftextlatitudelongitude nil uilocalnotification localnotif uilocalnotification alloc init localnotiffiredate itemdate localnotiftimezone nstimezone defaulttimezone localnotifalertbody msg localnotifalertaction ok localnotifsoundname uilocalnotificationdefaultsoundname localnotifapplicationiconbadgenumber 1 localnotifuserinfo userinfo uiapplication sharedapplication schedulelocalnotificationlocalnotif localnotif releaseedit 2 answer to my question here is the procedure i used to debug my app butthis procedure is wrongi set up my debugger with the wait for myappapp to launch option in the edit scheme menui launched my app with xcode a first time launch from scratch xcode thisplays the waiting for my myapp to launch i clicked on my app icon to launch the appthe app is launched i clicked on the home button the notification is thisplayedi clicked on the stop button in xcode to close the app i relaunched it with xcode xcode thisplays again the waiting for my myapp to launch message i clicked on thenotification in the status bar to launch the app launchoptions is nil launchoptions equal to nil is due to the fact that relaunching the app with xcode in this case with the waiting for my myapp to launch option deletes the notifications even if it is still thisplayed in the status bar to be able to debug check what is the content of launchoptions after a relaunch of the app from scratch by a click on a notification it seems that the only way is to thisplay this content in a uialert as mentioned in answer by tammo freese so use the following to debug in this specific case boolapplicationuiapplication application didfinishlaunchingwithoptionsnsdictionary launchoptions uialertview alertview uialertview alloc initwithtitleoptions messagelaunchoptionsuiapplicationlaunchoptionslocalnotificationkey description delegatenil cancelbuttontitleok otherbuttontitlesnil alertview show return yesthanks all for your help,['ios'] +376723,uidocumentinteractioncontroller openinmenu crashes ios app i am trying to send an image generated in my app to other apps using the uidocumentinteractioncontroller openin menu i am saving the uiimage to thisk with this code filejpeg nstemporarydirectory stringbyappendingpathcomponentactiveimagejpg jpegfileurl nsurl fileurlwithpathfilejpeg uiimage imagetowrite image uiimagejpegrepresentationimagetowrite 10 writetofilefilejpeg atomicallyyesi am accessing the jpegfileurl in another method to send the image by email using the mfmailcomposeviewcontroller and it works perfectly so the nsurl is valid but when i try to send the image to another app just sending i am not implementing any preview functionality the app crashes here is the method ibactionopeninotherappidsenderuidocumentinteractioncontroller controller uidocumentinteractioncontroller interactioncontrollerwithurl jpegfileurlcontrollerdelegate selfcgrect rect selfviewframecontroller presentopeninmenufromrectrect inviewselfview animatedyesthe open in menu is presented when i tap the button of any available app it crashes when testing in ios6 601 and ios5 511 devices i get no error output in the console just the usual exc bad access code1 address crash but on a ios 43 device the app is 43 upwards compatible i get this error in the console terminating app due to uncaught exception nsinvalidargumentexception reason nscftype actionsheetclickedbuttonatindex unrecognized selector sent to instance 0x16b7f0i have been reading apples documentation on uidocumentinteractioncontroller and uidocumentinteractioncontrollerdelegate that i implement in my class interface but none of the optional delegate methods seem to be required for my needs or helpful in this crash cannot figure what is wrong or missing any help would be appreciated,['ios'] +376730,how to understand the full gc log i currently see in prod the following5429779 full gc psyounggen 13809k0k505216k psoldgen 253802k245481k319488k 267612k245481k824704k pspermgen 70059k70059k118784k 05869143 secs times user059 sys0 real059 secsi understand that abc means a before gc b after gc c heap without tenured and permwhat i do not understand is piece outside all s which is 267612k245481k824704k what does it refer to,['java'] +376752,why are c int and long types both 4 bytes many sources including microsoft reference both the int and long type as being 4 bytes and having a range of signed 2147483648 to 2147483647 what is the point of having a long primitive type if it does not actually provide a larger range of values,['c++'] +376808,how exactly does android determine whether it is online how exactly does android determine the difference between the following stateshas a network interface active eg wifi or 3g but unable to access the internethas a network interface active and needs to ask the user to sign in to a network on a web pagehas a network interface active and able to access the internetdoes it perhaps send a simple http request to a fixed url perhaps on googlecom and check that the document returned is what it expects if so do we know the url used,['android'] +376816,making your php website into saml identity provider story is that i need to make my website act as identity provider read idp website itself is on zend platform idea is making a idp controller by which service providers read sp contacts idp as it must be part of the website i would need to include some extension which could be easily used for responding saml requests from spi have found list of php extensions fromall of these extensions have little documentation or are too complex for example i have not found a way to use simplesamlphp in my application and also extracting useful code out of it looks very time consuming which i really do not have anymore also i find all of them hard to implement into website i have been googling and checking github for days now trying to find easy way to use some library right now i am trying to implement lasso which seems reasonable but unfortunately lacks good examples information how to use it as idpany kind of criticism ideas help or tutorialcode examples would be useful,['php'] +376904,passing shared ptr as shared ptr what is the best method to go about passing a shared ptr of a derived type to a function that takes a shared ptr of a base typei generally pass shared ptrs by reference to avoid a needless copyint fooconst shared ptrbar ptrbut this does not work if i try to do something likeint fooconst shared ptrbase ptrshared ptrderived bar make sharedderivedfoobari could usefoodynamic pointer castbase derivedbarbut this seems suboptimal for two reasonsa dynamic cast seems a bit excessive for a simple derivedtobase castas i understand it dynamic pointer cast creates a copy albeit a temporary one of the pointer to pass to the functionis there a better solutionupdate for posterityit turned out to be an issue of a missing header file also what i was trying to do here is considered an antipattern generallyfunctions that do not impact an objects lifetime ie the object remains valid for the duration of the function should take a plain reference or pointer eg int foobar bfunctions that consume an object ie are the final users of a given object should take a unique ptr by value eg int foounique ptrbar b callers should stdmove the value into the functionfunctions that extend the lifetime of an object should take a shared ptr by value eg int fooshared ptrbar b the usual advice to avoid circular references appliessee herb sutters back to basics talk for details,['c++'] +376906,what are extended integer types quoting from the book i am readingsigned char signed short int signed int signed long int signed long long int are called standard signed integer typesunsigned char unsinged short int unsigned int unsigned long int unsinged long long int bool are called standard unsigned integer typesin addition to the standard integer types the c99 standard allows implementationdefined extended integer types both signed and unsigned for example a compiler might be provide signed and unsigned 128bit integer typesi have problem with 3rd point what are these extended integer types any examples,['c'] +376911,memory leak using tornados genengine i have code which in a simplified form looks like thisfrom tornado import gen httpclient ioloopio loop ioloopioloopinstanceclient httpclientasynchttpclientio loopio loopgenenginedef go for it while true r yield gentaskfetchgenenginedef fetchcallback response yield gentaskclientfetch httplocalhost8 callbackresponseio loopadd callbackgo for itio loopstartwhen i run it the memory footprint keeps increasing over time more or less linearly if however i remove the genengine nestinggenenginedef go for it while true r yield gentaskclientfetch httplocalhost8memory usage remains constanti have managed to reproduce the issue with different versions of tornado 2 on both mac os x and linux any ideas what might be the cause of this problem,['python'] +376939,compile boost c11 clang mac cannot find cstddef i cannot compile boost with clang 31 on mac os x 1082this is what i didbootstrapsh withtoolsetclangb2 toolsetclang cxxflagsstdc11 stdliblibc linkflagsstdliblibci also tried without chrono test wave and signalsi tried a userconfigjam withusing clangdarwinthis is the error i have for almost every fileboostconfigselect stdlib confighpp1812 fatal error cstddef file not foundit is kind of similar to how to compilelink boost with clanglibc thank you updatei do have the latest xcode 452 with the command line tools installedhere is part of the console outputkikohstrunk kikohs b2 toolsetclang cxxflagsstdc11 stdliblibc linkflagsstdliblibcperforming configuration checks 32bit no 64bit yes x86 yes has icu builds nowarning graph library does not contain mpibased parallel componentsnote to enable them add using mpi to your userconfigjam gcc visibility yes long double support nowarning skipping optional message passing interface mpi librarynote to enable mpi support add using mpi to userconfigjamnote to suppress this message pass withoutmpi to bjamnote otherwise you can safely ignore this messagebuilding the boost c libraries iconv libc no iconv separate yes icu no icu lib64 nocomponent configuration atomic building chrono building context building date time building exception building filesystem building graph building graph parallel building iostreams building locale building math building mpi building program options building python building random building regex building serialization building signals building system building test building thread building timer building wave buildingpatiencepatiencepatiencepatiencefound 8672 targetsupdating 1127 targetscommonmkdir binv2libsatomiccommonmkdir binv2libsatomicbuildcommonmkdir binv2libsatomicbuildclangdarwin421commonmkdir binv2libsatomicbuildclangdarwin421debugclangdarwincompilec binv2libsatomicbuildclangdarwin421debuglockpooloin file included from libsatomicsrclockpoolcpp1boostatomichpp1010 fatal error cstddef file not foundinclude cstddef 1 error generatedclang x c o0 g stdc11 stdliblibc o0 fnoinline wall g dboost all no lib1 dboost atomic dyn link1 dboost atomic source i c o binv2libsatomicbuildclangdarwin421debuglockpoolo libsatomicsrclockpoolcpp,['c++'] +376969,merge macho executable with a static lib suppose you have a prebuilt ios executable app for simulator or device a prebuilt static archive library static library which among other things contains c static initializersnow it should be possible to merge the two built products to produce the a new ios executable which is like the old one except that it is now also linked with the additional static library and on execution will run the static librarys static initializerswhich tool if any could help solve this merge problem edit an acceptable solution is also to dynamically load the library using dlopen the whole purpose of this is for application testing so the relinked app will never see app store,"['c++', 'ios']" +376993,android how to blurglassfrost current activity basicallyin an activity i have a listviewwhen i select an item an transparent activity opens as a small boxwhen this box appears you can still view the previous activities screenwhat i am trying to figure out is how to blur the previous screen like theimage linked here ignore the ui just look at the blurred grass areahow is this possiblethank you for any advice,"['java', 'android']" +376999,fluentvalidation unique name validation using database i have category model that has name field and every category name must be unique i have made validation and it works when i try to create new category but i have problem when trying to edit it for now it is just checking if the name exists and of course it does when i try to edit same categorymodelvalidatortypeofcategoryvalidatorpublic class category public int id get set public string name get set virtual public icollectionimage images get set public class categoryvalidator abstractvalidatorcategory public categoryvalidator ruleforx xnamenotemptywithmessagecategory name is requiredmustuniquenamewithmessagethis category name already exists private bool uniquenamestring name projectedatacontext db new projectedatacontext var category dbcategorieswherex xnametolower nametolowersingleordefault if category null return true return false as you can see i have uniquenamestring name function but how can i pass id or whole model in it so i can check if it is same id as model i am trying to edit then it pass how could i pass something like uniquenamestring name int id i thiscovered fluentvalidation only today and i cannot figure out,"['c#', 'asp.net']" +377007,sqlalchemy why cannot i update to funcnow but can use now when i try to do a query that looks like thissessionquerymymappedclassupdatemymappedclasstimefuncnowi getinvalidrequesterror could not evaluate current criteria in python specify fetch or false for the synchronize session parameterbut if i dosessionquerymymappedclassupdatemymappedclasstimenowit works anyone know why,"['python', 'sql']" +377017,proper way to update ui on different thread so i have this simple class that updates my labels and it gets accessed by different threads and reports progress of my application it works fine however when closing this app this code always throws an error about trying to access something that is thisposed private delegate void setlabeltextdelegatestring str1 string str2public void setlabeltextstring str1 string str2 if thislabel1invokerequired thislabel2invokerequired thisinvokenew setlabeltextdelegatesetlabeltext new object str1 str2 return thislabel1text str1 stringempty thislabel1text str1 thislabel2text str2 stringempty thislabel2text str2is this not the proper way to go about this is there something i need to add to make sure it does not try to perform updates on the ui while the app is closing,['c#'] +377018,filling a vector of pairs i want to fill a vector with 8 pairs each pair represents the moves in x and y coordinates a knight in a game of chess can make at the moment i am doing it like thisvectorpairintint moves8pairintint apairapairfirst 2apairsecond 1moves0push backapairapairfirst 2apairsecond 1moves1push backapairapairfirst 1apairsecond 2moves2push backapairapairfirst 1apairsecond 2moves3push backapairapairfirst 1apairsecond 2moves4push backapairapairfirst 1apairsecond 2moves5push backapairapairfirst 2apairsecond 1moves6push backapairapairfirst 2apairsecond 1moves7push backapair i am doing this to learn about the std library this seems like a hopelessly inefficient way of solving this problemanyone have a more elegant solutionthanks,['c++'] +377022,nvarchar is not a recognized cursor option i am running some sql that take the info from a temporary table and puts it into the permanent table i got it from a step by step guide written 3 years ago and the person who wrote it is long goneit states to use this sql heredeclare password nvarchar100 set password rewardsif not existsselect 1 from sysopenkeys where key name sym userpassdata and database name db name open symmetric key sym userpassdata decryption bycertificate userpasstables with passwordasbpass71509newinsert into user username password allowchange forcechange fullnamesalesrep openlink userprofileid lastupdatedbyuseremail select usernameencryptbykeykey guidsym userpassdatapassword allowchange forcechange fullname salesrep openlink userprofileid lastupdateby useremail from tempusersand then after that it says the followingif the password is unique for each row take the set password apassworda off and replace the password with passwordso at first i just changed the 2nd line so it saiddeclare password nvarchar100set passwordbut that gave me an error with the password column so then i changed it todeclare password nvarchar100 set passwordif not existsselect 1 from sysopenkeys where key name sym userpassdata and database name db name open symmetric key sym userpassdata decryption bycertificate userpasstables with passwordasbpass71509newinsert into user username password allowchange forcechange fullnamesalesrep openlink userprofileid lastupdatedbyuseremail select usernameencryptbykeykey guidsym userpassdatapassword allowchange forcechange fullname salesrep openlink userprofileid lastupdateby useremail from tempusersand that is what gave me the error nvarchar is not a recognized cursor option does anyone know what i am missing if i can provide any other info i will do my best to do sothank you to anyone who is able to help with this,['sql'] +377058,how can jquerys click function be so much faster than addeventlistener i am sure weve all seen the site for vanillajs the fastest framework for javascript d and i was just curious exactly how much faster plain javascript was than jquery at adding an event handler for a click so i headed on over to jsperf to test it out and i was quite surprised by the resultsjquery outperformed plain javascript by over 2500 my test codejquerytestclickfunction consoleloghiplain javascriptdocumentgetelementbyidtestaddeventlistenerclick function consoleloghii just cannot understand how this would happen because it seems that eventually jquery would end up having to use the exact same function that plain javascript uses can someone please explain why this happens to me,"['javascript', 'jquery']" +377085,how to generate random float number in c possible duplicatec random floathow to generate a random number in c i cannot find solution to find the random float number from the 0a where a is some float defined by the useri have tried the following but it does not seem to work correctlyfloat xfloatrandfloatrand maxa,['c'] +377131,do i have to memset after malloc new memory include stdlibhinclude stdiohinclude stringhint main int argc char argv int test malloc15 sizeofint forint i 0i 15 i printftest is intesti memsettest0sizeofint 15 forint i 0 i 15 i printftest after memset is intestithe out put is very wierd which is test is 1142126264 test is 32526 test is 1701409394 test is 1869348978 test is 1694498930 test after memset is 0 test after memset is 0 test after memset is 0 test after memset is 0 test after memset is 0 test after memset is 0 test after memset is 0 test after memset is 0 test after memset is 0 test after memset is 0why would that happeni thought i just mallocated some new fresh memory that ready to useso how about thisint test15do i have to callmemsettest0sizeofint 15,['c'] +377143,how to read an entire text stream in nodejs in ringojs there is a function called read which allows you to read an entire stream until the end is reached this is useful when youre making a command line application for example you may write a tac program as followsusrbinenv ringovar string systemstdinread read the entire input streamvar lines stringsplitn split the lineslinesreverse reverse the linesvar reversed linesjoinn join the reversed linessystemstdoutwritereversed write the reversed linesthis allows you to fire up a shell and run the tac command then you type in as many lines as you wish to and after youre done you can press ctrld or ctrlz on windows to signal the end of transmissioni want to do the same thing in nodejs but i cannot find any function which would do so i thought of using the readsync function from the fs library to simulate as follows but to no availfsreadsync0 buffer 0 bufferlength nullthe file descriptor for stdin the first argument is 0 so it should read the data from the keyboard instead it gives me the following errorerror espipe invalid seek at objectfsreadsync fsjs38119 at repl14 at replserverselfeval repljs10921 at rlionselfbufferedcmd repljs25820 at replserverselfeval repljs1165 at interfaceanonymous repljs24812 at interfaceeventemitteremit eventsjs9617 at interface online readlinejs20010 at interface line readlinejs5188 at interface ttywrite readlinejs73614how would you synchronously collect all the data in an input text stream and return it as a string in nodejs a code example would be very helpful,['javascript'] +377156,how do i read an xcode crash report i have an app that i just submitted it to the app sore the app was developed for me as i do not know ios development i do however know know other coding languages apple rejected the app saying that is crashed the strange thing is is never crashed in all tests i did probably about 50 i got their crash log symbolicated it in xcode and get this as a result the only problem is that i do not understand this either i was wondering if someone can explain what this means where abouts in my code that this error is and how i can fix it incident identifier 0e0825d2fbe94bf18c7fb83709c2991acrashreporter key 5b0d1e3117951cb6f669414656a30ad10c807e15hardware model iphone41process chapter3 framework 63path varmobileapplications4a4c7a701b6c403e8a986563bdf3af83chapter3 frameworkappchapter3 frameworkidentifier chapter3 frameworkversion code type arm nativeparent process launchd 1datetime 20120107 174613980 1100os version iphone os 501 9a405report version 104exception type exc bad access sigsegvexception codes kern invalid address at 0xb08crashed thread 0thread 0 name thispatch queue comapplemainthreadthread 0 crashed0 libobjcadylib 0x31be9fbc objc msgsend 161 chapter3 framework 0x04d78 0x10 157362 chapter3 framework 0x028b2 0x10 63223 uikit 0x35531e5e uiapplication handleapplicationsuspendeventinfo 7544 uikit 0x354c1d10 uiapplication handleeventwithnewevent 20245 uikit 0x354c13b8 uiapplication sendevent 486 uikit 0x354c0d26 uiapplicationhandleevent 58027 graphicsservices 0x37bdedec purpleeventcallback 8768 corefoundation 0x380dd54c cfrunloop is calling out to a source1 perform function 329 corefoundation 0x380dd4ee cfrunloopdosource1 13410 corefoundation 0x380dc33c cfrunlooprun 136411 corefoundation 0x3805f4d6 cfrunlooprunspecific 29412 corefoundation 0x3805f39e cfrunloopruninmode 9813 graphicsservices 0x37bddfc6 gseventrunmodal 15014 uikit 0x354ef73c uiapplicationmain 108415 chapter3 framework 0x024d6 0x10 533416 chapter3 framework 0x0246c 0x10 5228thread 1 name thispatch queue comapplelibthispatchmanagerthread 10 libsystem kerneldylib 0x339933b4 kevent 241 libthispatchdylib 0x37dc7f74 thispatch mgr invoke 7082 libthispatchdylib 0x37dc7c92 thispatch mgr thread 30thread 2 name webthreadthread 20 libsystem kerneldylib 0x33993010 mach msg trap 201 libsystem kerneldylib 0x33993206 mach msg 502 corefoundation 0x380dd41c cfrunloopservicemachport 1203 corefoundation 0x380dc154 cfrunlooprun 8764 corefoundation 0x3805f4d6 cfrunlooprunspecific 2945 corefoundation 0x3805f39e cfrunloopruninmode 986 webcore 0x32930128 zl12runwebthreadpv 3967 libsystem cdylib 0x36531c16 pthread start 3148 libsystem cdylib 0x36531ad0 thread start 0thread 30 libsystem kerneldylib 0x339a3cd4 workq kernreturn 81 libsystem cdylib 0x3652c30a pthread wqthread 6102 libsystem cdylib 0x3652c09c start wqthread 0thread 0 crashed with arm thread state r0 0x001562b0 r1 0x30b6f09c r2 0x01 r3 0x014 r4 0xb0 r5 0x00352ea0 r6 0x3f398608 r7 0x2fdfe760 r8 0x0034fa00 r9 0x0c2dbc27 r10 0x00113560 r11 0x3f38d010 ip 0x01924c sp 0x2fdfe750 lr 0x04d7f pc 0x31be9fbc cpsr 0x200f0030binary images 0x10 0x18f chapter3 framework armv7 deb18410d0314fac23e4c6b05a8265 varmobileapplications4a4c7a701b6c403e8a986563bdf3af83chapter3 frameworkappchapter3 framework0x2fecf0 0x2fef0f dyld armv7 be7c0b491a943054ad12eb5060f1da06 usrlibdyld0x30c2d0 0x30c30f libsystem networkdylib armv7 b18e0a845b1e317c8abcf6b5d06b29a0 usrlibsystemlibsystem networkdylib0x30c9e0 0x30ca4f mobileicons armv7 2f4c13053206306996726629b0b7eb01 systemlibraryprivateframeworksmobileiconsframeworkmobileicons0x30cb80 0x30cc4f corevideo armv7 474c89eb09fe3464851a20d76052341b systemlibraryframeworkscorevideoframeworkcorevideo0x30f5e0 0x30fa7f addressbook armv7 0a858565acd03f28a1bc69a650b64a7b systemlibraryframeworksaddressbookframeworkaddressbook0x30faf0 0x30ff4f geoservices armv7 6c9eb6372f723a57852cfc9ed7b78e31 systemlibraryprivateframeworksgeoservicesframeworkgeoservices0x311940 0x3119ef libvmiscdylib armv7 b93ee3136d1c3d44b1e513a56bb0f86c systemlibraryframeworksaccelerateframeworkframeworksveclibframeworklibvmiscdylib0x315430 0x31543f libcvmspluginsupportdylib armv7 85582e1094633fccb52b50ca13c5a5d0 systemlibraryframeworksopenglesframeworklibcvmspluginsupportdylib0x316e30 0x316e4f datamigration armv7 d067b65a904a3f438b5d9e13b208b117 systemlibraryprivateframeworksdatamigrationframeworkdatamigration0x317e10 0x317e2f coresurface armv7 fcb6a869daef3a3abc4300c28b218e9f systemlibraryprivateframeworkscoresurfaceframeworkcoresurface0x317e30 0x317e4f libremovefiledylib armv7 9c8cee9652453241ac1fc99eab05c40a usrlibsystemlibremovefiledylib0x319b20 0x319baf mobilewifi armv7 f07cb8d6dadf36919bae8ef6e5ce1749 systemlibraryprivateframeworksmobilewififrameworkmobilewifi0x31be60 0x31cacf libobjcadylib armv7 eb32df194b331e9b3dc14e40f46833 usrliblibobjcadylib0x31d240 0x31d5bf security armv7 b89c9f6373f037f2a4801558f97b9a95 systemlibraryframeworkssecurityframeworksecurity0x31d750 0x31d79f libgfxshareddylib armv7 0a36fb9d60a43479943bafb2f81313b1 systemlibraryframeworksopenglesframeworklibgfxshareddylib0x31d9b0 0x31d9df mobileinstallation armv7 4ccf76f0e6cb3cd7b4e0087c2f284a1d systemlibraryprivateframeworksmobileinstallationframeworkmobileinstallation0x31db0 0x31ef5f coregraphics armv7 641fb6e558f239588a8bd05dbef99a systemlibraryframeworkscoregraphicsframeworkcoregraphics0x31f460 0x31f49f libcompiler rtdylib armv7 414332f9a55238bab2cbec323e0fc8da usrlibsystemlibcompiler rtdylib0x31f9f0 0x3211df foundation armv7 ce466f428d953cac6641d1865809 systemlibraryframeworksfoundationframeworkfoundation0x3214e0 0x32198f libvdspdylib armv7 d8489a4ce77933abac52394c43ff5513 systemlibraryframeworksaccelerateframeworkframeworksveclibframeworklibvdspdylib0x321990 0x32199f libunwinddylib armv7 d212aad8c93d6c9580f9bf47071946 usrlibsystemlibunwinddylib0x321ad0 0x321f7f coretelephony armv7 1f4cacb552533c948122cb180f4192b3 systemlibraryframeworkscoretelephonyframeworkcoretelephony0x322030 0x322d3f webkit armv7 74661b1bf4613aafb827bfe0134ed92b systemlibraryprivateframeworkswebkitframeworkwebkit0x323a90 0x323ccf printkit armv7 279fb51deec3377ab9f820af2da4d915 systemlibraryprivateframeworksprintkitframeworkprintkit0x323f70 0x323fdf liblaunchdylib armv7 09f21c3e774c30b1aab1b56c2d6efbc3 usrlibsystemliblaunchdylib0x323fe0 0x32400f libcorevmclientdylib armv7 6ddb7cf8a93830628787a5b83eea0f1d systemlibraryframeworksopenglesframeworklibcorevmclientdylib0x324080 0x324cef glengine armv7 0231a8c1fa3f3cfe82e83fc53c0cf5d8 systemlibraryframeworksopenglesframeworkglenginebundleglengine0x325950 0x32596f libdnsinfodylib armv7 dbd1e77a4beb309d8f160d927d442467 usrlibsystemlibdnsinfodylib0x326270 0x3262cf libcopyfiledylib armv7 9072462f28af3665875b3ecaba002c00 usrlibsystemlibcopyfiledylib0x3280 0x3303f webcore armv7 7137e0ea008f3a3e8ae9e57f96d34d1d systemlibraryprivateframeworkswebcoreframeworkwebcore0x330450 0x3304f libbz210dylib armv7 28583efb9f1b38e7ae83c667b07dbd08 usrliblibbz210dylib0x330cb0 0x330d8f libbsm0dylib armv7 a6414b0a5fd53df58c4f0b2f8878f81f usrliblibbsm0dylib0x3710 0x3341bf libblasdylib armv7 9aabff01422f3cb8960f93d11d2b6de1 systemlibraryframeworksaccelerateframeworkframeworksveclibframeworklibblasdylib0x334c50 0x334def openal armv7 87e810d1a1e93b5b8523a4f97fdaaec5 systemlibraryframeworksopenalframeworkopenal0x334df0 0x334e6f assetslibraryservices armv7 c0093954f6ee329aa6b4848215bcb8c0 systemlibraryprivateframeworksassetslibraryservicesframeworkassetslibraryservices0x334e70 0x334eaf libmachodylib armv7 3237bc9c109e3354bc4b38b957243f31 usrlibsystemlibmachodylib0x334eb0 0x33501f eap8021x armv7 16801802d86e3c479f3034034192faed systemlibraryprivateframeworkseap8021xframeworkeap8021x0x335190 0x3352df persistentconnection armv7 81eb1b3e08cf3d7196313307ad60649d systemlibraryprivateframeworkspersistentconnectionframeworkpersistentconnection0x3352e0 0x33534f mobilekeybag armv7 f5633749a1c83058a28cd7d0b488e19f systemlibraryprivateframeworksmobilekeybagframeworkmobilekeybag0x335a90 0x335a9f liblangiddylib armv7 342170169bf232a08912f5ef97112d usrlibliblangiddylib0x335c80 0x336ecf javascriptcore armv7 24ff2747b3973aecb9c37960eba5ff4d systemlibraryprivateframeworksjavascriptcoreframeworkjavascriptcore0x3375d0 0x33768f accountsettings armv7 090bb6a4f97433089b5cabc6a40c619a systemlibraryprivateframeworksaccountsettingsframeworkaccountsettings0x337690 0x337a5f appsupport armv7 de0c2fbb95f8383db43acfb44e9c66fe systemlibraryprivateframeworksappsupportframeworkappsupport0x337ec0 0x3382f libcommoncryptodylib armv7 be9a231cfe6e3ae387abb4a098bce9 usrlibsystemlibcommoncryptodylib0x338590 0x33949f quartzcore armv7 ff595b1a042933249466e92433e1af6f systemlibraryframeworksquartzcoreframeworkquartzcore0x339920 0x339a8f libsystem kerneldylib armv7 afd3cb06e20336dca2e5a6e11d080504 usrlibsystemlibsystem kerneldylib0x339a90 0x33aaf imgsgx543gldriver armv7 f92d0f00c6eb3fbdae116fb1febe4fb1 systemlibraryextensionsimgsgx543gldriverbundleimgsgx543gldriver0x33ab10 0x33b08f coreaudio armv7 2e4975a2156e328585f2a478e80704fc systemlibraryframeworkscoreaudioframeworkcoreaudio0x342030 0x34228f opencl armv7 e1d5bfcdb59934b0923b9307c75e7457 systemlibraryprivateframeworksopenclframeworkopencl0x342290 0x3476df facecorelight armv7 cc2edb3645d2390dbca5471d35f1bf6e systemlibraryprivateframeworksfacecorelightframeworkfacecorelight0x349630 0x34986f bom armv7 0e6087f75a81345ea81751197ccb712c systemlibraryprivateframeworksbomframeworkbom0x349880 0x3499df libresolv9dylib armv7 97d6eb53ae3e0480f51771c9665613 usrliblibresolv9dylib0x34aa10 0x34ab0f generationalstorage armv7 c581bffc87013530b3c2d017142395e6 systemlibraryprivateframeworksgenerationalstorageframeworkgenerationalstorage0x34ab10 0x34c6df imageio armv7 df300f66a317352e92354a8a48af3453 systemlibraryframeworksimageioframeworkimageio0x34ce90 0x34d32f libc1dylib armv7 ad15503487243836b7c296f3439ba0c1 usrliblibc1dylib0x34d930 0x34d94f libsystem blocksdylib armv7 4bb97971d037879bec814fe750d86d usrlibsystemlibsystem blocksdylib0x351310 0x35135f libaccessibilitydylib armv7 ee734c0e964934a887a66d170270b114 usrliblibaccessibilitydylib0x351ac0 0x351c5f libripadylib armv7 ad22ea5ee99a358691f9820e62c85058 systemlibraryframeworkscoregraphicsframeworkresourceslibripadylib0x351c60 0x351c6f libkeymgrdylib armv7 791bb8b832943b2392c0c35228f52e09 usrlibsystemlibkeymgrdylib0x351f50 0x35214f libsystembdylib armv7 31a0ffbb18bf3a28b46fd286733e7d9f usrliblibsystembdylib0x352630 0x3526f libcrfsuitedylib armv7 ea460e3f1ac338a9885d5752864dbffb usrliblibcrfsuitedylib0x35270 0x3535ef libiconv2dylib armv7 6e858938edb93162ba8cf25702f08b16 usrliblibiconv2dylib0x3548a0 0x3548ef libcachedylib armv7 4511f0ec5b713636ade7245a12553c usrlibsystemlibcachedylib0x354be0 0x35957f uikit armv7 97b527cd6fba35c6bb39263e0f3623 systemlibraryframeworksuikitframeworkuikit0x359950 0x3599ef libmobilegestaltdylib armv7 bf8d7c30f11a393a8adf4c8277e65aa3 usrliblibmobilegestaltdylib0x35af50 0x35b40f corelocation armv7 e959d4dd596b31eeaa49c8c0156b1e12 systemlibraryframeworkscorelocationframeworkcorelocation0x35c20 0x35c20f veclib armv7 106ef8294b0d3c2d89e9230527846227 systemlibraryframeworksaccelerateframeworkframeworksveclibframeworkveclib0x35c210 0x35ee2f liblapackdylib armv7 5490a87fe5153771b9c67940292842ba systemlibraryframeworksaccelerateframeworkframeworksveclibframeworkliblapackdylib0x35ee30 0x35ee4f libdylddylib armv7 f1963e7ef64e39a58ec1e39ed7c74849 usrlibsystemlibdylddylib0x35f2b0 0x35f2cf libsystem sandboxdylib armv7 b8612b4ce18535a94f4b75c730e090 usrlibsystemlibsystem sandboxdylib0x35f440 0x35f49f libsystem dnssddylib armv7 4d8b38f1cb603f0d8af78c56c485f05a usrlibsystemlibsystem dnssddylib0x35f4a0 0x35f7f systemconfiguration armv7 753be0ebdcb13b24b1a4adcdc94d6bd9 systemlibraryframeworkssystemconfigurationframeworksystemconfiguration0x363260 0x36329f coretime armv7 e2f02260f2a63359b9a0a47c69f59c9e systemlibraryprivateframeworkscoretimeframeworkcoretime0x365220 0x365af libsystem cdylib armv7 1707c3cf3c5b3045af4bed38ff8420a6 usrlibsystemlibsystem cdylib0x365df0 0x367bcf audiotoolbox armv7 da4f78fd20fb3b42b1a8be4f383d9c12 systemlibraryframeworksaudiotoolboxframeworkaudiotoolbox0x367c20 0x36841f libsqlite3dylib armv7 af4718fee01734748c42f2214ab6883d usrliblibsqlite3dylib0x36a3d0 0x36a5df libxslt1dylib armv7 f37418b7e89137bba433677d61cd779d usrliblibxslt1dylib0x36a5e0 0x36b0bf libxml22dylib armv7 78462273eb5b38d1a0873b02f0e35e23 usrliblibxml22dylib0x36b0c0 0x36b1bf opengles armv7 6d1afb451f50310895ec59864739e781 systemlibraryframeworksopenglesframeworkopengles0x36b680 0x36b6df libgpusupportmercurydylib armv7 2066fe9b4ee73d1d83f5801b6d0bb432 systemlibraryprivateframeworksgpusupportframeworklibgpusupportmercurydylib0x36b720 0x36c41f libglprogrammabilitydylib armv7 cb91cd9952e7371a9659da26034c8324 systemlibraryframeworksopenglesframeworklibglprogrammabilitydylib0x36c860 0x36dcf libicucoreadylib armv7 1bc960f75d633190a09b093209a9f0c5 usrliblibicucoreadylib0x36e6b0 0x36e7af springboardservices armv7 79f1564c1b23303eb3b7db67f9375228 systemlibraryprivateframeworksspringboardservicesframeworkspringboardservices0x36edf0 0x36ee2f captivenetwork armv7 c3a5b1659eb0302eb205498ffacb09f1 systemlibraryprivateframeworkscaptivenetworkframeworkcaptivenetwork0x36ee30 0x36f23f libglimagedylib armv7 9440420d838a382caa175399d74a5044 systemlibraryframeworksopenglesframeworklibglimagedylib0x36f240 0x36f3af libmisdylib armv7 fd046316dedc34dd81a6601ea3b1e8a6 usrliblibmisdylib0x36f3b0 0x36f84f managedconfiguration armv7 05711081dd883c58a844c5f9c251e8c9 systemlibraryprivateframeworksmanagedconfigurationframeworkmanagedconfiguration0x36fa90 0x36fa9f libgcc s1dylib armv7 69d8dab7388b33d38b30708fd6b6a340 usrliblibgcc s1dylib0x370230 0x37034f libxpcdylib armv7 7d49e385ee5d3e7eb08d06525abd6435 usrlibsystemlibxpcdylib0x3703a0 0x37073f videotoolbox armv7 49f9f09f23f7396b94a29bb1280759fe systemlibraryprivateframeworksvideotoolboxframeworkvideotoolbox0x370a30 0x370b4f dataaccessexpress armv7 6bc443b0f87e338698cac9e5a96e8f8f systemlibraryprivateframeworksdataaccessexpressframeworkdataaccessexpress0x372cf0 0x372d6f protocolbuffer armv7 6ca7dca9370132a2a592356bf9f2170b systemlibraryprivateframeworksprotocolbufferframeworkprotocolbuffer0x373170 0x37368f libstdc6dylib armv7 dc2061145c1a3307829d4f3bfc547c1a usrliblibstdc6dylib0x373690 0x37375f libz1dylib armv7 eef915ed9b2c3433b03fd9030957b945 usrliblibz1dylib0x374560 0x3745cf liblockdowndylib armv7 bfaf7fb16e5a3b2ea07c47b8b2f2b64e usrlibliblockdowndylib0x3755a0 0x375d3f proofreader armv7 09d057676f6837cd9e7a7354b67e77 systemlibraryprivateframeworksproofreaderframeworkproofreader0x375db0 0x376b2f cfnetwork armv7 6fbc9f187eaa309780e70288c9f289 systemlibraryframeworkscfnetworkframeworkcfnetwork0x3770d0 0x3770df accelerate armv7 a62771c826753815a5cae96eaa60ffd7 systemlibraryframeworksaccelerateframeworkaccelerate0x378760 0x3787af iomobileframebuffer armv7 c2e6bd6dafde3097b47bc255a8c871ef systemlibraryprivateframeworksiomobileframebufferframeworkiomobileframebuffer0x3787b0 0x378b6f libcgfreetypeadylib armv7 753daf497ca736739a301261a522f1 systemlibraryframeworkscoregraphicsframeworkresourceslibcgfreetypeadylib0x378b70 0x378fbf mobilecoreservices armv7 9a79a2d389ba35389a30782ed01c46dd systemlibraryframeworksmobilecoreservicesframeworkmobilecoreservices0x378fc0 0x37900f iosurface armv7 0f003f50b18e3dbf87607d819e0ac6b9 systemlibraryprivateframeworksiosurfaceframeworkiosurface0x37aa60 0x37ae3f iokit armv7 e5f727892ee034a4be04e6da608f413f systemlibraryframeworksiokitframeworkversionsaiokit0x37b5a0 0x37b70f dictionaryservices armv7 5bbab664f97932a79a1566fda3a4383e systemlibraryprivateframeworksdictionaryservicesframeworkdictionaryservices0x37bda0 0x37be5f graphicsservices armv7 4ec745ffb2e039faab4b39a30268f707 systemlibraryprivateframeworksgraphicsservicesframeworkgraphicsservices0x37bf40 0x37c11f libsystem infodylib armv7 1e36ab94661c372bab5a801d68c79353 usrlibsystemlibsystem infodylib0x37dc40 0x37ddaf libthispatchdylib armv7 defe319d1f4d3c1c8c4f18ebd96b396a usrlibsystemlibthispatchdylib0x37dfa0 0x37e43f coremedia armv7 d585cf4e0cfa34fa8beaa43b06a4bcd7 systemlibraryframeworkscoremediaframeworkcoremedia0x37e460 0x37e48f libcorefscachedylib armv7 1ece4be587ca397b8f0494c56ed46976 systemlibraryframeworksopenglesframeworklibcorefscachedylib0x37e510 0x37e57f libnotifydylib armv7 1e374857ac68370095ddbafe94f021a1 usrlibsystemlibnotifydylib0x37ec20 0x37f9cf vimage armv7 42a5e58ff1b9350cad90de36bd3ceb09 systemlibraryframeworksaccelerateframeworkframeworksvimageframeworkvimage0x37f9f0 0x37fa3f aggregatedictionary armv7 cfd957904957310381369729bfd9b2b0 systemlibraryprivateframeworksaggregatedictionaryframeworkaggregatedictionary0x37fa90 0x38019f coreimage armv7 b1d0678497f43769840f173c0f9dce20 systemlibraryframeworkscoreimageframeworkcoreimage0x380480 0x3804f libcabidylib armv7 f769ce305c3033ee90e8c2ecc4846619 usrliblibcabidylib0x38050 0x38167f corefoundation armv7 de9eefc6109735369cfd8f3de9895da0 systemlibraryframeworkscorefoundationframeworkcorefoundation0x3835d0 0x383aef coretext armv7 23150093d39b393e9bc5f8230176df47 systemlibraryframeworkscoretextframeworkcoretext,"['ios', 'iphone']" +377169,windowopen only if the window is not open i have a link on my site that opens a new window to a page that plays a very long audio file my current script works fine to open the page and not refresh if the link is clicked multiple times however when i have moved to a seperate page on my site and click this link again it reloads i am aware that when the parent element changes i will lose my variable and thus i will need to open the window overiding the existing content i am trying to find a solution around that i would prefer not to use a cookie to achieve this but i will if requiredmy script is as followsfunction openwindow iftypeofwinref undefined winrefclosed create new winref windowopenhttpsamplesitepagewinpopsamplelistofoptions else give it focus in case it got burried winreffocus,['javascript'] +377170,install sd card vs phone memory and why the size of the app differs i am bit confused about memory sizes in android apps is there any difference between installing the application in phone memory and sd card i guess there might be difference of responding and running speed but i am wondering is there any other differences in thatand also i installed my application in phone memory and again installed in sd card alsothe immediate difference i can see is the size of the appwhile installed in phone memory total size 515 mbapp size 496 mbdata 192 kb while installed in sd card total size 315 mbapp size 296 mbdata 196 kbmy actual size of the apk file is 2 mbwhy the above difference with phone and sd card installationi am really confused about these size variations where is app 2 mb and data 4 kb goes as the differencei googled a lot and failed to find the answers i tried in developerandroidcom and stackoverflow also but i am unluckyso my doubts arewhat are the differences between installing an app in phone and sd cardwhy the size difference shows when i install my app in sd card and phone where is the difference 2 mb goes and what is that differencehow the size is more when installed from the actual apk my guess is the apk will be extracted and installed in the device so the sizes might be increased while installing please correct me if my guessing is wrong in the 3rd onethank you in advance,['android'] +377187,whats the difference between invokeasync and begininvoke for wpf thispatcher i noticed in net 45 that the wpf thispatcher had gotten a new set of methods to execute stuff on the thispatchers thread called invokeasync before net 45 we had invoke and begininvoke which handled this syncronously and asynchronously respectivelybesides the naming and the slightly different overloads available are there any major differences between the begininvoke and the invokeasync methods oh and i already checked both can be awaitedprivate async task runstuffonuithreadaction action both of these works fine await thispatcherbegininvokeaction await thispatcherinvokeasyncaction,['c#'] +377208,how to drop rows of pandas dataframe whose value of certain column is nan i have a df df stk id eps cashstk id rpt date 601166 201231 601166 nan nan6036 201231 6036 nan 126016 201231 6016 43 nan601009 201231 601009 nan nan601939 201231 601939 25 nan01 201231 01 nan nanthen i just want the records whose eps is not nan that is dfdrop will return the dataframe as below stk id eps cashstk id rpt date 6016 201231 6016 43 nan601939 201231 601939 25 nanhow to do that,['python'] +377231,checking if the google analytics gaq object is loaded and available i have some google analytics tracking code gatc on my site which triggers calls to the gaqpush method in googles codein the scenario that ga is not available or gaq has not loaded i want to ensure that i do not have any javascript errors on the page by checking that gaq is not identical to undefined will this suffice to check if it is available and is this xbrowser i have had a look at googles documentation but it does not mention anything about thisi am aware of checking if the object is null but i am not sure if this is necessaryif typeof gaq undefined gaqpush trackevent downloaded video yes gaqpushrollup trackevent downloaded video yes,"['javascript', 'jquery']" +377235,edittext set number of characters programmatically i have a edittext and i would like to restrict the number of characters which could be inputted in this edittext and make this restriction programmatically how to do it for example say i would like to restrict it to only allow 10 characters,['android'] +377255,why is boostcall traitsparam type a reference for enumerated types a basic c 03 enumerated type is just an integral value with a fancy name therefore i would expect to pass it by valuefor this reason i would also expect boostcall traitstparam type with tsomeenum to determine that the most efficient way of pass t is by valuefrom boost documentation see call traitsdefines a type that represents the best way to pass a parameter of type t to a functionwhen i use boostcall traitstparam type with tsomeenum it determines that someenum should be passed by referencei would also expect c11 class enums to also be passed by valuetest codeinclude stringinclude typeinfoinclude boostcall traitshppinclude boosttype traitsis referencehppenum someenum en1 zero 0 en1 one en1 two en1 threestruct somestructtemplatetypename tvoid thisplaycalltraits const stdstring desc typedef typename boostcall traitstparam type param type stdcout n stdcout call traits for desc n stdcout ttypeof t typeidtname n stdcout ttypeof param type typeidparam typename n stdcout tis referenceparam type stdboolalpha boostis referenceparam typevalue nint main int char thisplaycalltraits unsigned unsigned pass by value as expected thisplaycalltraits somestruct struct pass by reference as expected thisplaycalltraits someenum enumeration pass by reference why return 0,['c++'] +377300,why object id persists on windows while not on linux this program class objectgarden class selfclone puts selfobject id endendputs objectgardencloneobject idwhen run on linux have tested on rhel generates thistinct object ids across multiple runs as i had expected however when i run it on windows i get same output across multiple runs and no matter what i do hibernateshutdowninfamous blue screen and restart object ids would not change i also notice that object id on windows changes iff i change the content even an insignificant change like add a new line or comment of the program why is this difference between windows and linux implementations and since i do not have access to os x can someone please run it on a mac and document the resulti am using ruby 192p136 on windows and ruby 192p180 on linux,['ruby'] +377315,how to generate an image from imagedata in javascript i would like to know if there is any way to create a new image from imagedata which was previously obtained from a canvas elementi have searched for a solution but they all seem to be drawing the result to a canvasso basically i need a way to convert an imagedata object to image directly if its possible,['javascript'] +377322,synchronous request with websockets i can send and receive messages from server on websockets i need to write a function that will send data to the server and is awaiting a response from the server and then return it as a result of a functionsendwssendmy message to serverreceive it is a event wsbindmessage functionmessage consolelogmessagemy function function requestmessagewssendmessage how wait for receive return response,"['javascript', 'jquery']" +377363,time complexity of c math library pow function i wanted to know what is the worst case timecomplexity of the pow function that is built in c,['c++'] +377369,thisable horizontal scrolling by clicking the mouse wheel in the element with overflowxhidden how can i determine the possibility of horizontal scrolling by clicking the mouse wheel and thisable it in the element with overflowxhidden using javascript or jquery scrolling is impossible in firefox but possible in ie chrome and safari code examplediv styleoverflowxhidden overflowyautodivscreenshots,"['javascript', 'jquery', 'html', 'css']" +377387,boost program options exception not replacing canonical option tag have been integrating this version 1520 into my app but have stumbled upon the problem as described abovein the example attached the exception what method always still has the canonical option tag intact and is not replaced with my option namei am using vs2008 have thisabled unicode option none and removed all other files from my project it is only this code in a maincpp fileor have i got this all wrong and there is something else i should be calling to format the exception message with the correct parameter nameinclude boostprogram optionshppnamespace po boostprogram optionsusing namespace stdint mainint argc char argv try pooptions description optionalparamsoptional optionalparamsadd options log severityl povalueintrequired minimum severity logging level log fileg povaluestring full path to log file povariables map optmap poparsed options parsed pocommand line parserargc argv optionsoptionalparams allow unregistered run postoreparsed optmap ponotifyoptmap catchpoerror e cout ewhat return 0 return 0,['c++'] +377461,xcodebuild archive location i am currently trying to build an xcarchive using this command linexcodebuild project onethingxcodeproj target onething archivethis places the xcarchive within a hard to find file location so i was wondering if there is a configuration to be able to set the file location for the archive,['ios'] +377468,twitter bootstrap jquery how to temporarily prevent the modal from being closed i am using twitter bootstrap modals with the default options where you can click the backdrop or press esc to close the modalhowever when i initiate an ajax operation in the modal i want to thisable the modal from being closed in any way so i thisable buttons and hide the modals close button but i cannot figure out how to thisable the backdrop and the esc keyi triedmymodalmodal backdrop static keyboard falsebut this does not seem to work on the flyi will also need to reenable the backdrop and keyboard once the ajax operation is finished,"['javascript', 'jquery']" +377535,argparse subparser hide metavar in command listing i am using the python argparse module for command line subcommands in my program my code basically looks like thisimport argparseparser argparseargumentparsersubparsers parseradd subparserstitlesubcommands metavarcommandsubparser subparsersadd parserthis helpdo thissubparser subparsersadd parserthat helpdo thatparserparse argswhen running python testpy help i would like to list the available subcommands currently i get this outputusage testpy h command optional arguments h help show this help message and exitsubcommands command this do this that do thatcan i somehow remove the command line in the subcommands listing and still keep it in the usage line i have tried to give helpargparsesuppress as argument to add subparsers but that just hides all the subcommands in the help output,['python'] +377570,java7 propertyeditors registered via threadgroupcontext i found out that propertyeditormanager registersfinds editors per threadgroupcontext basis not per global registry as prior to java7 and java7 every time creates a new threadgroupcontext for a new threadgroup thus propertyeditorfinder which actually registersfinds editors is again newjava uses predefined editors for some classes byte long etc and registers them in propertyeditorfinder at ctor let us say i want to register my own propertyeditor for some predefined class ie long it is easy to do in java6 but in java7 each time threads are created within new threadgroup i lost my editorso could you please tell me is there any solution to handle in a nice manner which editors are created for a new threadgroup in java7 if face some issue and how do you overcome itps i guess i should apologize for my english pps threadgroupcontext is a replacement for appcontext and i was hoping that implementation of creating contexts would be similar both use mapping between threadgroup to context appcontext in java 6 threadgroupcontext in java 7 and java 6 uses the same appcontext for new threadgroup as for its parent in other words appcontext is used for the whole threadgroup tree in a jvm but unfortunately creating of threadgroupcontext is different it is simply a new context for a new group so the question is automatically resolved if one day threadgroupcontext will use the same creating technique,['java'] +377592,what parameters does the stringlength attribute errormessage take in the mvc4 template one of the data annotation attributes used is stringlengthfor examplestringlength100 errormessage the 0 must be at least 2 characters long minimumlength 6what parameters 0 1 2 more are legaledit to be more specific i can see from the example and trial and error what the possibilities are but i would like to see some hard documentationi cannot find anything about this in the stringlengthattribute documentation,['c#'] +377597,check if a browser tab is already open so i do not make extra tabs when a user adds an item to our shopping cart it opens our store in a new tab different websites oddly enoughi would like to check if the tab is already open and then repopulate it it with the second item instead of opening another tab with the updated cartis there a way to check this with js i imagine i can track that we opened the tab but i do not see how i can confirm that it was not closed in the time between adding items to the cart without doing some ajax requests pinging both pages etc which seems like overkillso simply how do you check if a browser tab is already openedited with a solutionfirstvar tab windowopenmytabtheniftab var tab windowopenmytab,['javascript'] +377610,how do i assign a dictionary value to a variable in python i am an amateur when it comes to programming but i am trying my hand at python basically what i want to be able to do is use math on a dictionary value the only way i could think to do it would be to assign a dictionary value to a variable then assign the new value to the dictionary something like thismy dictionary foo 10 bar 20 variable my dictionaryfoonew variable variablemy dictionaryfoo new variablehowever when i try to assign a variable this way i get a syntax error is there a better and straightforward way to do this edit also i am only using this as an example let us say this is a block of code not the entire program the fact that new variable has not been declared is completely irrelevant i just want to know how to perform math to a dictionary value also i am attempting to access a dictionary outside of the function i have my code in,['python'] +377625,visual studio 2012 alongside 2010 kernel32lib windowsh i just installed visual studio 2012 alongside visual studio 2010 the problem is that i cannot manage to convert simple projects from 2010 to 2012 they fail to link to files such as kernel32lib or include files such as windowsh my system also has windows sdk 71 installedi have tried messing with property manager for my x86 and x64 user platforms since i had appropriate dxsdk dir references added there only to get mixed results sometimes it just works sometimes it compiles but does not link other times it simply stops at windowshfor example currently i am getting1link fatal error lnk1104 cannot open file kernel32libor1sourcecpp2 fatal error c1083 cannot open include file windowsh no such file or directorydepending on the inclusion or not of windowsh with a simple hello world type program only in x64in the project properties for activedebug activex64 vc directories include directories i can now see vcinstalldirincludevcinstalldiratlmfcincludewindowssdk includepathdxsdk dirinclude if i expand that input box and i click edit i seevcinstalldir cprogram files x86microsoft visual studio 110vcwindowssdk includepath cprogram files x86windows kits80includeumcprogram files x86windows kits80includesharedcprogram files x86windows kits80includewinrtwhile my platform toolset v110 windowsh resides at cprogram files x86windows kits80includeumwindowsh so there should be no problem stuff works if i select windows sdk 71 as platform toolsetany solution besides formatting and reinstalling windowsle if i replace the variable directories with absolute paths within the system everything works i do not see why i would do this since i am sharing the project with others as well,['c++'] +377704,how to avoid applied lazily liststransform in guava mapstringobject map mapsnewhashmapmapputtest123mapputfuyou001456mapputid145listmapstringobject list listsnewarraylistlistaddmapliststransformlist new functionmapstring object object override public object applynullable mapstring object input systemoutprintlntest input return input systemoutprintlnlistconsole is not thisplay testhow to avoid applied lazilyi also try listmapstringobject newlist new arraylistmapstring objectlistsizecollectionscopynewlistlistbut not effect,['java'] +377730,insert bytes into middle of a file in windows filesystem without reading entire file using file allocation table i need a way to insert some file clusters into the middle of a file to insert some datanormally i would just read the entire file and write it back out again with the changes but the files are multiple gigabytes in size and it takes 30 minutes just to read the file and write it back out againthe cluster size does not bother me i can essentially write out zeroes to the end of my inserted clusters and it will still work in this file formathow would i use the windows file api or some other mechanism to modify the file allocation table of a file inserting one or more unused clusters at a specified point in the middle of the file,['c#'] +377827,does performance differs between python or c coding of opencv i aim to start opencv little by little but first i need to decide which api of opencv is more useful i predict that python implementation is shorter but running time will be more dense and slow compared to the native c implementations is there any know can comment about performance and coding differences between these two perspectives,"['c++', 'python']" +377837,best way to include use php classes in magento i want to use this mobile detection php file on a magento website and i want to know wich is the best way to insert a php file and use it across other subtemplates since magento structure is still a bit tricky for me basically i have something like this maintemplatephtml and headerphtmlmaintemplatephtml content isphp include once mobile detectphp detect new mobile detect echo thisgetchildhtmlheadphp if detectismobile condition nr2 meta namemobilemain contentthis is for mobilephp else meta namenotmobilemain contentthis is not for mobilephp headerphtml content is php if detectismobile condition nr1 meta namemobile contentthis is for mobilephp else meta namenotmobile contentthis is not for mobilephp when i load maintemplatephtml in browser the second condition is working but the first one throws out an error call to a member function ismobile on a nonobjectwhat would be the best way to include mobile detectphp just once in my maintemplatephtml and then be able to run that condition in all my subfiles like headerphtml which are gonna be inserted also inside maintemplatephtmlthank you,['php'] +377854,how to check if allow url fopen is enabled or not i am using the following codeecho file get contents ini getallow url fopen enabled thisabledthis can get it enabled or thisabledbut i would like to make as function say function name is isgetcontentsthen i can call it as following any where in my website codeif isgetcontentsecho this is enabled will do an actionelseecho this is thisabled will do another action thanks,['php'] +377855,java lucene ngramtokenizer i am trying tokenize strings into ngrams strangely in the documentation for the ngramtokenizer i do not see a method that will return the individual ngrams that were tokenized in fact i only see two methods in the ngramtokenizer class that return string objectshere is the code that i havereader reader new stringreaderthis is a test stringngramtokenizer gramtokenizer new ngramtokenizerreader 1 3where are the ngrams that were tokenizedhow can i get the output in stringswordsi want my output to be like this is a test string this is is a a test test string this is a is a test a test string,['java'] +377860,remove alpha characters and white space from string i have a string which contains many characters i want to remove azaz and white space and be left with the rest whats the best way to do thisheres what i have triedpresaleestimatehigh regexreplacepresaleestimatehigh azaz stringemptybut i also need to remove white space,"['c#', '.net']" +377891,maps api v3 getcenter and getzoom not working in the google maps api v3 i have created a map objectmap new googlemapsmapdocumentgetelementbyidmap canvas myoptionsi will zoom in and pan on that map and to go back to the original view later i would like to save the zoom level and the center of the map i try the followingoldcenter mapgetcenteroldzoom mapgetzoombut the variables stay undefined when i do the same thing in the console i get the correct responseswhat am i doing wrong please let me know if more code is needed to find the answer or if it is an obvious problemthanksfull codefunction initialize custom places var latlng new googlemapslatlng51 10 var germany new googlemapslatlng51 10 var mylatlng new googlemapslatlng4912 define style var styles stylers invert lightness true marker styles var coin image coinpng var merch image merchpng define options for map var myoptions pancontrol false zoomcontrol true zoomcontroloptions style googlemapszoomcontrolstylesmall position googlemapscontrolpositionleft top maptypecontrol false scalecontrol false streetviewcontrol false overviewmapcontrol false maptypeid googlemapsmaptypeidroadmap create map object map new googlemapsmapdocumentgetelementbyidmap canvas myoptions mapsetoptionsstyles styles select zoom etc by defining 2 points var southwest new googlemapslatlng4510 var northeast new googlemapslatlng5515 var bounds new googlemapslatlngboundssouthwestnortheast mapfitboundsbounds placemarkersouthwest placemarkernortheast place random markers var lngspan northeastlng southwestlng var latspan northeastlat southwestlat for var i 0 i 50 i var location new googlemapslatlngsouthwestlat latspan mathrandom southwestlng lngspan mathrandom var marker new googlemapsmarker position location map map icon merch image var j i 1 markersettitlejtostring transaction markers one full cycle set marker var trans marker new googlemapslatlng523179913241904 var marker new googlemapsmarker position trans marker map map animation googlemapsanimationdrop titlehello world icon coin image heres the problem var oldcenter mapgetcenter var oldzoom mapgetzoom consolelogmap oldmap map consolelogoldmap consolelogoldzoom consolelogoldcentertostring pan to marker settimeoutfunction mappantotrans marker startdelayed30 zoom in on marker settimeoutfunction zoominendzoom startdelayed10 show info window var contentstring h3daner coco banhh3 contentstring psumup was used to pay for a daner at coco banh in berlin germanyp var infowindow new googlemapsinfowindow content contentstring settimeoutfunction infowindowopenmapmarker startdelayed80 settimeoutfunction infowindowclose startdelayed50 zoom out again settimeoutfunction zoomoutoldzoom startdelayed20 center again settimeoutfunction mappantooldcenter startdelayed80 infowindow new googlemapsinfowindow content contentstring,['javascript'] +377918,how do i create message chat bubbles on the iphone programmatically like in iphone messages i was wondering if there is a way to build those chat bubbles programmatically from ios if not ios own then are there any decent open source libraries that will let me do that,['iphone'] +377939,how can i add an eclipse quick fix for a custom java marker i would like to report custom problems for java files to the problems view of eclipse and provide quick fixes for themthe standard way to do is to use the extension point orgeclipsecoreresourcesmarkers to declare a custom marker and add markers by calling orgeclipsecoreresourcesiresourcecreatemarkerstring then one can use the extension point orgeclipseuiidemarkerresolution to provide a quick fix for the custom markersthe above approach is a languageindependent method of creating and resolving resource markers the downside is that i have to write some boilerplate code to resolve my custom java problems instead i would like to be reuse iquickfixprocessor that is i would like to resolve my custom java markers using the extension point orgeclipsejdtuiquickfixprocessors using this extension point i no longer have to parse the java file in which the marker is found i do not have to build the bindings and find the ast node covering the marker if i do not reuse orgeclipsejdtinternaluitextcorrectioncorrectionmarkerresolutiongenerator and its dependencies i will end up duplicating most of ithow can i provide quick fixes for my custom java markers using the jdt infrastructureattempt 1i defined my custom marker as followsextension idcustommarker namecustom java problem pointorgeclipsecoreresourcesmarkers super typeorgeclipsejdtcoreproblem super typeorgeclipsecoreresourcesproblemmarker super typeorgeclipsecoreresourcestextmarker persistent valuetrueextensionthen i added instances of the above marker by invoking method iresourcecreatemarkercustommarkernext i defined a custom quick fix processorextension pointorgeclipsejdtuiquickfixprocessors quickfixprocessor classquickfixescustomquickfixprocessor idquickfixesquickfixprocessor quickfixprocessorextensionmy custom markers show up in the problems view of eclipse but when i rightclick on a custom problem the quick fix menu item is thisabledattempt 2i repalced imarker marker resourcecreatemarkercustommarker by imarker marker resourcecreatemarkerijavamodelmarkerjava model problem marker as a result of this change when i rightclick on a custom problem in the problems view the quick fix menu item becomes available but when i select it a dialog pops up that says there is no fix available for the selected problem however i verified that customquickfixprocessorhascorrectionsicompilationunit int gets called and returns true but customquickfixprocessorgetcorrectionsiinvocationcontext iproblemlocation does not get invokedattempt 3attempt 3 is a continuation of attempt 2 i set the ijavamodelmarkerid of the custom marker as followsmarkersetattributeijavamodelmarkerid iproblemexternalproblemfixableconsequently customquickfixprocessorgetcorrections gets called when i hover over my custom marker in the editor or click on the lightbuild on the left margin of the java editor however when i select the marker in the problems view rightclick on the marker and select the quick fix menu item customquickfixprocessorgetcorrections does not get called and a dialog appears saying that no quick fixes are availablei ran jdt in debug mode to see why it does not call customquickfixprocessorgetcorrections when i invoke the quick fix from the problems view it turned out correctionmarkerresolutiongeneratorinternalgetresolutionsimarker finds no resolutions because correctionmarkerresolutiongeneratorhasproblem contextgetastrootgetproblems location does not find the custom problem in the ast of the compilation unit i am not sure how to associate my custom markers with the ast of the compilation unit,['java'] +377943,how to redirect jvm output without tear up output from the application recently i am writing some microbenchmark code so i have to print out the jvm behaviors along with my benchmark information i usexxprintcompilationxxprintgcdetailsand other options to get the jvm status for benchmark information i simply use systemoutprint method because i need to know the order of the message i printed and the jvm outputi can get good result when i just print them out in the console although the jvm output sometimes tear my messages up but since they are in different threads it is understandable and acceptablewhen i need to do some batch benchmarks i would like to redirect the output into a file with pipe in linux system and use python to get the result from the file and analyse ithere is the problemthe jvm output always overlapped with the messages i printed in the java application it ruined the completion of the messagesany idea how to deal with this situation i need both the jvm output and application output in the same place in order to preserve the sequence because it is important and they do not overlap on each other so i do not lose anything,"['java', 'python']" +377984,how to store list of object into viewstate i have a list of type listjobseeker i want to store it in viewstate how this can be doneprivate listjobseeker jobseekerslist get set,"['c#', 'asp.net', '.net']" +378040,bigo for various fibonacci implementations i just tried implementing code in java for various means by which the nth term of the fibonacci sequence can be computed and i am hoping to verify what i have learntthe iterative implementation is as followspublic int iterativefibonacciint n if and 1 return 0 else if and 2 return 1 int i 0 j 1 sum 0 for n2 0 n sum i j i j j sum return sumthe recursive implementation is as follows public int recursivefibonacciint n if and 1 return 0 else if and 2 return 1 return recursivefibonaccin1 recursivefibonaccin2 the memoized implementation is as follows public int memoizedfibonacciint n if and 0 return 1 else if and 1 return 0 else if and 2 return 1 if memoryn1 0 memoryn1 memoizedfibonaccin1 if memoryn2 0 memoryn2 memoizedfibonaccin2 return memoryn1memoryn2 i am having a bit of a doubt when trying to figure out the bigo of these implementations i believe the iterative implementation to be on as it loops through n2 timesin the recursive function there are values recomputed hence i think it is on2in the memoized function more than half of the values are accessed based on memoization i have read that an algorithm is olog n if it takes constant time to reduce the problem space by a fraction and that an algorithm is on if it takes constant time to reduce the problem space by a constant amount am i right in believing that the memoized implementation is on in complexity if so wouldnt the iterative implementation be the best among all three as it does not use the additional memory that memoization requires,['java'] +378065,android pass gesture event to another view good morning alli am continuing work on my sticky listview in which a specified view in a listview will stick to the top andor bottom as it passes by i have accomplished this by setting up a view that is identical to the list item and showing or hiding it as the list item passes on and off the screenmy problem is that when these sticky items are present i want them to react to touch as if they are part of the listview itself for example a fling down on the top sticky should send the listview scrolling downmy question is if it is possible to assign an touch listener to this view and then pass these events directly to the listi was hoping it would be as easy aslistview liststickyviewsetontouchlistenernew ontouchlistener override public boolean ontouchview arg0 motionevent motionevent listontoucheventmotionevent return false any help is greatly appreciatedjosh,['android'] +378067,embedding vlcj in jpanel i have read this so thread and when i have tried to use the code with some changes i am getting just a black window can some one tell me what i am doing wrong here i have just one class with main function import javaawtcolorimport javaxswingjframeimport javaxswingjpanelimport comsunjnanativelibraryimport ukcocapricavlcjplayermediaplayerfactoryimport ukcocapricavlcjplayerembeddedembeddedmediaplayerimport ukcocapricavlcjplayerembeddedvideosurfacecanvasvideosurfaceimport ukcocapricavlcjruntimewindowswindowscanvaspublic class canvas demo create a media player factory private mediaplayerfactory mediaplayerfactory create a new media player instance for the runtime platform private embeddedmediaplayer mediaplayer private jpanel panel private windowscanvas canvas private jframe frame constructor public canvas demostring url creating a panel that while contains the canvas panel new jpanel panelsetbackgroundcolorblack creating the canvas and adding it to the panel canvas new windowscanvas paneladdcanvas panelrevalidate panelrepaint creation a media player mediaplayerfactory new mediaplayerfactory mediaplayer mediaplayerfactorynewembeddedmediaplayer canvasvideosurface videosurface mediaplayerfactorynewvideosurfacecanvas mediaplayersetvideosurfacevideosurface construction of the jframe frame new jframedemo with canvas awt framesetdefaultcloseoperationjframeexit on close framesetlocation100 100 framesetsize700 500 adding the panel to the frameaddpanel framesetvisibletrue playing the video mediaplayerplaymediaurl main function public static void mainstring args nativelibraryaddsearchpathlibvlc cprogram filesvideolanvlc final string url cmyvideomp4 new canvas demourl thanks in advance,['java'] +378090,htmlagilitypack remove script and style im using the following method to extract text form html public string getalltextstring html string alltext try htmlagilitypackhtmldocument document new htmlagilitypackhtmldocument documentloadhtml html var root documentdocumentnode var sb new stringbuilder foreach var node in rootdescendantnodesandself if nodehaschildnodes string text nodeinnertext if stringisnulloremptytext sbappendlinetexttrim alltext sbtostring catch exception alltext systemwebhttputilityhtmldecode alltext return alltext problem is that i also get script and style tagshow could i exclude them,['c#'] +378099,download binary file from github using java i am trying to download this file with the following method and it does not seem to work i am getting an emptycorrupt filestring link string filename championhelper4jarurl url new urllinkurlconnection c urlopenconnectioncsetrequestpropertyuseragent mozilla40 compatible msie 60 windows nt 51 net clr 103705 net clr 114322 net clr 1230703inputstream inputinput cgetinputstreambyte buffer new byte4096int and 1outputstream output new fileoutputstreamnew filefilenamewhile n inputreadbuffer 1 if n 0 outputwritebuffer 0 n outputclosebut i can successfully download the following file from my dropbox with the same method so somehow github knows that i am not a regular user trying to download a file i already tried to change the user agent but that did not help eitherso how should i download a file that is hosted on my github account using javaedit i tried to use the apache commonsio for this but i get the same effect an emptycorrupt file,['java'] +378101,when i try to run vim in command line i get python errors when i try running vim in the terminal so as to follow romainls suggestion in my other question i get lots of python errors which all boil down toioerror invalid python installation unable to open usrincludepython27pyconfigh no such file or directorywhy is this i can use python or sublime text even without any problemsthe full list of errors is the followingtraceback most recent call last file systemlibraryframeworkspythonframeworkversions27libpython27sitepy line 565 in module file systemlibraryframeworkspythonframeworkversions27libpython27sitepy line 547 in main file systemlibraryframeworkspythonframeworkversions27libpython27sitepy line 278 in addusersitepackages file systemlibraryframeworkspythonframeworkversions27libpython27sitepy line 253 in getusersitepackages file systemlibraryframeworkspythonframeworkversions27libpython27sitepy line 243 in getuserbase file systemlibraryframeworkspythonframeworkversions27libpython27sysconfigpy line 523 in get config var file systemlibraryframeworkspythonframeworkversions27libpython27sysconfigpy line 419 in get config vars file systemlibraryframeworkspythonframeworkversions27libpython27sysconfigpy line 298 in init posixioerror invalid python installation unable to open usrincludepython27pyconfigh no such file or directoryextra infoi am on mac os x mountain lion os 108editi tried bobdunakey idea with no success the idea was to use sudo i still get the same errorsedit 2i was able to solve the problem thanks to ziraks solution which is the following,['python'] +378115,is there an email template file like oft which can be opened in all email programs currently i am writing a web interface which is full of data i would like to export this data as an email template so you can edit the email afterwards is there a format such as oft which can be read by all email programsi know that there is such a function in html a hrefmailto since the email text is very long and i want to attach files this does not seems to be a good solutioncan someone help me,['php'] +378116,ini setupload max filesize200m not working in php possible duplicateoverriding upload max filesize i use these code for change upload file size echo ini getupload max filesizebrini setupload max filesize300mecho ini getupload max filesizebut i got2m2mwhich is set in phpinii want to change file upload size limit,['php'] +378134,lazy loading of images in listview i know this is a widely thiscussed issue but i would like to ask a question anyway i have lists with baseadapters in my app all of which obtain images from the web now i have tried1 asynctasks in which the image is downloaded first stored into a cache and then thisplayed on the onpostexecute method the image is obtained from the cache subsequently 2 nostras universal image loader3 fedors lazylist and4 novodas imageloaderall of these methods claim to make the loading of images lazy but the problem is that the scrolling of my list still is not smooth it gets stuck and continues when the image completes loading i have been at this for days now does anyone know of a good solution for this problem,['android'] +378144,performance of ccli function pointers versus net delegates for my ccli project i just tried to measure the cost of ccli function pointers versus net delegatesmy expectation was that ccli function pointers are faster than net delegatesso my test separately counts the number of invocations of the net delegate and native function pointer throughout 5 secondsresultsnow the results were and still are shocking to menet delegate 910m executions with result 152080413030 in 5003msfunction pointer 347m executions with result 57893422166551 in 5013msthat means the native ccli function pointer usage is almost 3x slower than using a managed delegate from within ccli code how can that be i should use managed constructs when it comes to using interfaces delegates or abstract classes in performancecritical sectionsthe test codethe function which gets called continuously int64 doitint n int64 sum if n 3 0 return sum n else return sum 1the code which invokes the method tries to make use of all the parameters as well as the return value so nothing gets optimized away hopefully heres the code for net delegates int64 executions int64 resultsystemdiagnosticsstopwatch w gcnew systemdiagnosticsstopwatchsystemfuncint int64 int64 managedptr gcnew systemfuncint int64 int64doitwrestartexecutions 0result 0while welapsedmilliseconds 50 for int i0 i 10 i result managedptri executions executionssystemconsolewritelinenet delegate 0m executions with result 2 in 1ms executions welapsedmilliseconds resultsimilar to the net delegate invocation the c function pointer is usedtypedef int64 doitmethodint n int64 sumdoitmethod nativeptr doitwrestartexecutions 0result 0while welapsedmilliseconds 50 for int i0 i 10 i result nativeptri executions executionssystemconsolewritelinefunction pointer 0m executions with result 2 in 1ms executions welapsedmilliseconds resultadditional infoscompiled with visual studio 2012net framework 45 was targetedrelease build execution counts stay proportional for debug buildscalling convention is stdcall fastcall not allowed when the project gets compiled with clr supportall tests donenet virtual method 1025m executions with result 171358304166325 in 5004msnet delegate 910m executions with result 152080413030 in 5003msvirtual method 336m executions with result 5605633598 in 5006msfunction pointer 347m executions with result 57893422166551 in 5013msfunction call 1459m executions with result 244230520832847 in 5001msinlined function 1385m executions with result 231791984166205 in 50msthe direct call to doit is represented here by function call which seems to get inlined by the compiler as there is no significant difference in execution counts compared to a call to the inlined functioncalls to c virtual methods are as slow as the function pointer a virtual method of a managed class ref class is as fast as the net delegateupdatei digged a little deeper and it seems that for the tests with unmanaged functions the transition to native code happens each time the doit function gets calledtherefore i wrapped the inner loop into another function which i forced to compile unmanagedpragma managedpush off int64 testcall int64 executions int64 result 0 for int i0 i 10 i result doitnativei executions executions return resultpragma managedpopadditionally i tested stdfunction like thatpragma managedpush off int64 teststdfunc int64 executions int64 result 0 stdfunction int64int int64 funcdoitnative for int i0 i 10 i result funci executions executions return resultpragma managedpopnow the new results arefunction call 2946m executions with result 4953404397054 in 50msstdfunction 160m executions with result 26679519840 in 5018msstdfunction is a bit thisappointing,['.net'] +378154,how to unit test an application using google drive api java client what is the best way to unit test an application using the google drive api java clientit seems like applications written rely heavily on the drive class but short of eithercreating a really extensive mock which itself would likely need tobe tested orwriting an integration test dependent on the actual drive servicehow could such an application be testedusing mock frameworks like mockito are a bit tedious with the drive api java client since usage of the drive java client rely on making so many chained calls eg from the documentationdrive service getdriveservicereq respservicefilesgetfileidexecute,['java'] +378175,detect if textview spans over 2 lines i wonder if there are any ways to detect either if string to be fitted into a text view reaches the end of screen and therefore change line or if a textview spans over 2 linesi want to know this so i can increase margins between some textviews if a textview spans over 2 lines of course i want to do this dynamically,['android'] +378200,undefined reference to virtual base class destructor possible duplicatewhat is an undefined referenceunresolved external symbol error and how do i fix it i have some experience with java and am now doing a c course i wanted to try writing an interface but i have run into some trouble with destructors which i have not been able to resolve even with the help on the internet heres my code class force public virtual force virtual vector evalvector x double tclass invsquare public force public invsquaredouble a c a invsquare vector evalvector x double t omitted stuff private double ci have tried to declare a virtual destructor for the base class and a nonvirtual one for the derived class but i get an error saying undefined reference to forceforce what does it mean and how can i fix itforgive me if this is a silly questionthank you very much for your helpnoctilux,['c++'] +378205,is the u8 string literal necessary in c11 from wikipediafor the purpose of enhancing support for unicode in c compilers the definition of the type char has been modified to be at least the size necessary to store an eightbit coding of utf8i am wondering what exactly this means for writing portable applications is there any difference between writing thisconst char str test stringor thisconst char str u8test stringis there be any reason not to use the latter for every string literal in your codewhat happens when there are nonasciicharacters inside the teststring,['c++'] +378220,paypal datetime payment date parsing issue paypal sends payment datetime like093a373a22nov182c2012psti try to convert it by this code but getting an exceptionany clue about how to parse itthank youdatetime paymentdatedatetimetryparsewebutilityhtmldecoderpayment date out paymentdatenpaymentdate paymentdate payment date093a373a22nov182c2012pst,"['c#', '.net']" +378233,renderincontext flips the origin of colorwithpatternimage i have uiview with backgroundcolor set with colorwithpatternimage as expected the background image is drawn starting at the top left cornerproblem appears when i am doing renderincontext on that view the background image is drawn starting at the bottom left corner everything else seems to render fineheres the source and destination imageshere is the code here is the layer to be rendered into an imageuiview src uiview alloc initwithframecgrect0 0 100 100srcbackgroundcolor uicolor colorwithpatternimageuiimage imagenamedbackgroundpngselfview addsubviewsrc here well thisplay the imageuiimageview dest uiimageview alloc initwithframecgrect110 0 srcboundssizeselfview addsubviewdest render src to an image in destuigraphicsbeginimagecontextsrcboundssizecgcontextref context uigraphicsgetcurrentcontextsrclayer renderincontextcontextdestimage uigraphicsgetimagefromcurrentimagecontextuigraphicsendimagecontextis there a way to keep the image to tile in right direction as in the src view,['ios'] +378234,standalone java implementation for extracting values in uri template rfc 6570 is there a java standalone implementation to extract values aaof parameters in an uri as defined by an uritemplate rfc 6570the best implementation i have found is a ruby implementation via i found a java implementation handyuritemplatesit supports the resolution of an uritemplate with parameter values to a final uri unfortunately it can not do the reverse extraction of parameter values aain the uri according uritemplateimplentations of the jaxrs or restlet have this feature internallybut none seems to have isolated this feature module which could used independentlydoes anyone have another ideahere a example to use springweb import orgspringframeworkwebutiluritemplatepublic class uriparserspringimpl implements uriparser private final uritemplate uritemplate private final string uritemplatestr public uriparserspringimplfinal string template thisuritemplatestr template thisuritemplate new uritemplatetemplate override public mapstring string parsefinal string uri final boolean match thisuritemplatematchesuri if match return null return uriutilsdecodeparamsthisuritemplatematchuri override public setstring getvariables return collectionsunmodifiablesetnew linkedhashsetstringthisuritemplategetvariablenames another for jersey jaxrs implementation import comsunjerseyapiuriuritemplatepublic class uriparserjerseyimpl implements uriparser private final uritemplate uritemplate private final mapstring string valuesmaps public uriparserjerseyimplfinal string template thisuritemplate new uritemplatetemplate final mapstring string valuesmaps new hashmapstring string for final string prop thisuritemplategettemplatevariables valuesmapsputprop null thisvaluesmaps collectionsunmodifiablemapvaluesmaps override public mapstring string parsefinal string uri final mapstring string values new hashmapstring stringthisvaluesmaps final boolean match thisuritemplatematchuri values if match return null return values override public setstring getvariables return thisvaluesmapskeyset with interface public interface uriparser public setstring getvariables public mapstring string parsefinal string uri,['java'] +378261,python pandas remove entries based on the number of occurrences i am trying to remove entries from a data frame which occur less than 100 times the data frame data looks like thispid tag1 23 1 451 622 242 453 343 253 62now i count the number of tag occurrences like thisbytag datagroupbytagaggregatenpcount nonzerobut then i cannot figure out how to remove those entries which have low count,['python'] +378280,how can i get a views current width and height when using autolayout constraints i am not talking about the frame property because from that you can only get the views size in the xib i am talking about when the view is resized because of its constraints maybe after a rotation or in response to an event is there a way to get its current width and heighti tried iterating through its constraints looking for width and height constraints but that is not very clean and fails when there are intrinsic constraints since i cannot differentiate between the two also that only works if they actually have width and height constraints which they do not if they rely on other constraints to resizewhy is this so difficult for me arg,['ios'] +378324,how to use greater than operator with date no idea what is going on here here is the query right from phpmyadminselect from la schedule where start date 201218but i consistently get all records in the table returned including those with start date 20121101 what gives,['mysql'] +378329,exported content providers can provide access to potentially sensitive data i am using contentprovider in my android application to share the database between the application for sharing the database i need to add the provider access in androidmanifestxml like as followsproviderandroidnamecontentproviderandroidauthoritiesumbconappsvid i added and implemented successfully but the warning message showing in the provider tag like this exported content providers can provide access to potentially sensitive data will it cause any security problem in future,['android'] +378348,how to view all the metadata of columns of a table in oracle database i want to know the query that allows us to view all the columns that are defined for a table in oracle databaseelaborationtable name some table have 10 columnsi want to know how i can retrieve the all column names their data type and any constraints that are defined for any column,['sql'] +378362,exposing application scripts to certain scripts only uhh it is hard to come with a right title for this problem excuse mein a backbonejs application i am building models views templates are all in separate javascript html files i want to export the models views and templates to the application bootstapper file appjs without polluting the global variable ie doing windowappmodel mymodel that by export i mean make the code inside the files available to appjs for initialization and runninghow do i go about doing thisare there any patterns that will solve the problem could you provide me a exampledescriptionin cases where modelsviews and templates are split to many thisparate files the application bootstrapper file appjs should have some means to access these mvc components hence common approach is to do below inside the modeljs filewindowappmodelpersonmodel backbonemodelextendappjsvar instance new windowappmodelpersonmodelvar personview new windowappviewspersonviewmodelinstancefinally you see that everything derives from the global object app which i think is not safe improper and weak way to build application dependenciessuggestionsjust to the above question could someone suggest a template loading libraryjavascript templates regardless of engine used that can be used to load the templates,['javascript'] +378391,using photoshop files from web application i want to interact with a photoshop file and create images using its actions and smart objectsis there any php or c api to can do it,"['c#', 'php']" +378409,how to get the value of autoincrement of last row at the insert i have googled this problem one week and no thing useful i think am not using the correct wordi am using sql server 2008 with tsql and my need is to optimise my function when i insert a new rowi have a table with first column is the key of integer autoincrement type and other columns are just for informationwhen we do an insert sql server increments the key automatically and i have to do a select max to get the value so is there a way like a global variable like identity or a function to avoid the begin end transaction and select max,['sql'] +378412,android videoview cannot play video mp4 i used the android videoview to play a video file via http my problem is my phone prompts cannot play video sorry this video cannot be played when playing a mp4 file from http but it is ok when playing another mp4 video file when used in a newer phone like samsung galaxy s my program can play both mp4 video file from http successfullymy phone samsung gts5830 android version 234 thisplay 320x480video file 1 ok video codec h264 resolution 640x360 others 169 340kbps 2992fps audio codec aac 44khz 96kbps stereovideo file 2 fail video codec h264 resolution 640x360 others 169 993kbps 25fps audio codec aac 44khz 125kbps stereobelow is my code that hardcoded to play the video file 1 successfullypublic class videoplayactivity extends activity videoview vvoverridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate requestwindowfeaturewindowfeature no title getwindowsetflagswindowmanagerlayoutparamsflag fullscreen windowmanagerlayoutparamsflag fullscreen vv new videoviewthis relativelayoutlayoutparams param1 new relativelayoutlayoutparamsrelativelayoutlayoutparamsmatch parent relativelayoutlayoutparamsmatch parent param1addrulerelativelayoutcenter in parent vvsetonerrorlistenernew onerrorlistener public boolean onerrormediaplayer mp int what int extra logddbg onerrorlistener onerror what extra return false relativelayout layout new relativelayoutthis layoutaddviewvv param1 setcontentviewlayout playcontent private void playcontent string path 1330378998288mp4 vvsetvideopathpath vvrequestfocus vvstart the error log when playing video file 2 is as below 19 174930119 ivideoview16860 start 19 174930139 emediaplayer16860 error 1 2147483648 19 174930149 emediaplayer16860 error 12147483648 19 174930149 dvideoview16860 error 12147483648 19 174930149 ddbg16860 onerrorlistener onerror 1 2147483648 it is noted that i tried to install the mx player and downloaded the both video file into my phones sd card the mx player can play both video files successfullyso can anyone help me to answer the questions below why my program cannot play the video file 2 on my phone how can i play the video file 2 on my phonethank you for your advice,['android'] +378423,force external download url i want to host on my webpage an external url containing a mp3 file the problem is that clicking on that link will open the player i have to right click and save link as in order to download the file is there any solution to force the file downloadi do not want to download the file and then use headers to force the download,['html'] +378449,how to read systemnetmailsettingssmtp from webconfig this is my webconfig mail settingssystemnet mailsettings smtp deliverymethodnetwork from network defaultcredentialstrue hostlocalhost port587 username password123456 smtp mailsettings systemnetand heres how i try to read the values from webconfig var smtp new systemnetmailsmtpclient var credential new systemnetconfigurationsmtpsectionnetwork string strhost smtphost int port smtpport string strusername credentialusername string strfrompass credentialpasswordbut credentials are always null how can i access these values,['c#'] +378469,unexplained behavioural difference between objectwithid versus existingobjectwithid i understand the documented differences between these two calls however does anyone know the reasons for the following observed behaviour i have noticedif i have a parentcontext and a temporary childcontext where i use the childcontext to edit insert and deleted objects if use childcontext objectwithidobjectid to retrieve a known existing managed object present in the parent context it will sometimes give me an object with a fault that on being fired fails and generates an exception i understand objectwithid will by design always return an object in a faulted state regardless of if an actual managedobject exists for the given objectid however if the object actually exists in the parent context i would expect that when any of the properties are accessed the object will always be successfully retrieved from the parent context eg the fault will be fired without any problem if i use childcontext existingobjectwithidobjectid i find it does indeed always succeed for the record i have turned off caching on the child context and this same behaviour occurs after childcontext resetcontext has been called so it is not an artefact of old cached data hanging around that is inconsistent with the parent context the documentation alone seems to me to be insufficient to explain this behaviour i can of course chalk it up to experience and just say i now know to always use existingobjectwithid when passing object ids to my child edit context perform block but i feel uneasy and would like to understand exactly what is going on here not least so i can understand if there is any performance impact of using the one as over the other but also to understand what the constraint is so i can ensure there is not some bad practice i am unnecessarily implementing in my code and then using a wrong or inefficient call to fix it,['ios'] +378477,replace bgl iterate over vertexes with pure c11 alternative i want to replace the bgl iteration over vertexes or edges with pure c11 equivalent the bgl code from 52 0libsgraphdocquick tourhtml istypename boostgraph traitsgraphout edge iterator out i out endtypename boostgraph traitsgraphedge descriptor efor stdtieout i out end out edgesv g out i out end out i e out i vertex src sourcee g targ targete g stdcout namegetvertex id src namegetvertex id targ i tried several suggestions from here replace boost foreach with pure c11 alternative but without lucki want to be able to write something likefor auto e out edgesv g or something likefor stdtieauto out i auto out end out edgesv g out i out end out iis it possible,['c++'] +378488,php check if file exists and not directory i read the file exists can also return turn if it points to a directory what is the fastest way to check if only a file exitsat the moment i have check if the file exists return bool public function exists ifis nullthis file return false return is dirthis file file existsthis file true falsei found lots of posts relating to checking if file exits in php but nothing that talks about the directory and how best to check this this method can get called 10s of time so i could really do with making it as fast as possible,['php'] +378489,read apns in android 42 i have a problem reading apns in android v42 yes reading not writing apns it is throwing a security exceptionno permission to write apn settings neither user 10068 nor current process has androidpermissionwrite apn settingssame code used to work on all previous platforms does anyone know of any work around to thisthanks,['android'] +378540,why is my hidden input writing valuevalue instead of truefalse i have an mvc4 site with as part of a hidden forminput namesomefield typehidden valueviewbagtestthe value of viewbagtest is true the form field is posting to an input parameter of the formpublic actionresult someactionbool somefield false but somefield is always false upon investigating i see that the source code hasinput namesomefield typehidden valuevaluehowever i know this used to work what has happened and what can i do,['asp.net'] +378548,curved line on d3 force directed tree new to d3 and trying to develop a force directed tree into which we can plug varioss dataset i have managed to get the basic idea up and running but would like to make the links curved so i can deal with multiple links i have looked at and i am just not getting it the nearest i get is it all working with no path visible this is my code for straight lines i would appreciate some help if youve got the timethankssets up the svg that holds the data structure and puts it in the div called mapboxvar svg d3selectdivmapboxthemapappendsvgattrwidth mapwidthattrheight mapheightsets up the data structure and binds the data to it var force d3layoutforcenodesdatanodeslinksdatalinkssizemapwidth mapheightcharge600linkthistance60startdraws the links and set up their stylesvar link svgselectalinkdatadatalinksenterappendlineattrclass linkstylestroke creates nodes and attached g element to append other things tovar node svgselectallnodedatadatanodesenterappendgcallforcedragappends the cirdle to the g element and defines stylesnodeappendcircleattrr functiond if dweight11 return 5 else return dweight135 stylefill white stylestrokewidth 3stylestroke functiond if dtype1 return eda45e ifdtype2 return 819e9aelse return c36256 node stroke colorsonmouseover nodemouseoveronmouseout nodemouseoutonmousedown nodemousedowncallforcedragappends text to the g element and defines stylesnodeappendtextattrclass nodetextattrdx 16attrdy 35emattrtextanchor functiond if dtype1 return middle else return start textfunctiond return dname forceontick function linkattrx1 functiond return dsourcex attry1 functiond return dsourcey attrx2 functiond return dtargetx attry2 functiond return dtargety nodeattrtransform functiond return translate dx dy,['javascript'] +378553,autocomplete with mvc 4 razor i think i am missing something obvious while attempting to add autocomplete functionality in mvc 4 from what i have found in other posts i have been able to put together an example however the method in my controller is not being calledwhat i have tried so far layoutstylesrendercontentthemesbasecscriptsrenderbundlesjqueryscriptsrenderbundlesjqueryuiscriptsrenderbundlesjqueryvalcontrollerpublic function numbersterm as string as actionresult return jsonnew string one two three four five six jsonrequestbehaviorallowgetend functionview i have hard coded the homenumbers for nowdiv classeditorlabel htmllabelforfunctionmodel modelnumberdivdiv classeditorfield htmleditorforfunctionmodel modelnumber htmlvalidationmessageforfunctionmodel modelnumberdivscript typetextjavascript function numberautocomplete source homenumbers minlength 1 scriptwhen i run my app and type in the textbox nothing happens i have put a breakpoint in the numbers function and it seems that it is never calledmy project can be found here,['jquery'] +378585,setting up vim as c ide i wish to setup vim as c ide so i can do all work from iti am using these plugins for vimclang complete accurate completionnerdtree browse filessnipmate insert snippetsautocomplpop omnicompletionbuffergator buffer managementvimpowerline nice statusbarvundle to manage pluginsbut i lack things like jump to definition and compiling multiple files in one executable project viewi am usingnmap f8 w bar g w wall wextra pedantic stdc11 o trcr bar trcrto compile current file but it would not work if there are multiple file that create one executablei know i could just use eclipse netbeans codeblocks and such but i really like vim if such thing as vim ide is not possible do i have to learn gnu build system or some other methodany advice is welcome,['c++'] +378624,adding image inside table cell in html i am sorry but i am not able to do this simple thing i am not able to add an image in the table cellbelow is my code which i have written html headcar applicationhead body table border 5 bordercolor red align center th colspan 14abcdth tr th colspan 4nameth th colspan 4originth th colspan 4phototh tr tr td colspan 4bugatti veyron super sportth td colspan 4molsheim alsace franceth td colspan 4img srccpicshgif alt border3 height100 width100imgtd tr tr td colspan 4ssc ultimate aero tt topspeedtd td colspan 4united statestd td colspan 4 border3 height100 width100photo1td tr tr td colspan 4koenigsegg ccxtd td colspan 4angelholm swedentd td colspan 4 border4 height100 width300photo1td tr tr td colspan 4saleen s7td td colspan 4irvine california united statestd td colspan 4 border3 height100 width100photo1td tr tr td colspan 4 mclaren f1td td colspan 4surrey englandtd td colspan 4 border3 height100 width100photo1td tr tr td colspan 4ferrari enzotd td colspan 4maranello italytd td colspan 4 border3 height100 width100photo1td tr tr td colspan 4 pagani zonda f clubsporttd td colspan 4modena italytd td colspan 4 border3 height100 width100photo1td trtable bodyhtmlwhat i am doing wrong this is my output screen,['html'] +378664,pass complex parameter from ksoap android to wcf webservice i am calling net wcf web service from ksoap my webmethod take one complex parameter updatablecustomerinfopublic class updatablecustomerinfo implements kvmserializable public string customeridpublic string facebookoverridepublic object getpropertyint arg0 string retval switcharg0 case 0 retval customerid break case 1 retval facebook break return retvaloverridepublic int getpropertycount return 2overridepublic void getpropertyinfoint arg0 hashtable arg1 propertyinfo arg2 switcharg0 case 0 arg2type propertyinfostring class arg2name customerid break case 1 arg2type propertyinfostring class arg2name facebook break defaultbreak overridepublic void setpropertyint arg0 object arg1 switcharg0 case 0 customerid arg1tostring break case 1 facebook arg1tostring break default break and this is my web service calling to the webservice updatablecustomerinfo ucinfo new updatablecustomerinfo ucinfocustomerid 1f089071c126e2119b2edca971c098f5 ucinfofacebook asdfqwer1234 propertyinfo pinfo new propertyinfo pinfosetnameupdatableinfo pinfosetvalueucinfo pinfosettypeupdatablecustomerinfoclass soapobject request new soapobjectnamespace method name requestaddpropertypinfo soapserializationenvelope envelop new soapserializationenvelopesoapenvelopever11 envelopsetoutputsoapobjectrequest envelopdotnet true httptransportse hts new httptransportseurl htsdebug true try htscallsoap action envelop catch exception ex exprintstacktrace but in fact i logged the web service method and the log tell me that the method is called but the parameter is came nulli tried to change soapenvelope version to soapenvelopever10 but that make the parameter on the method of web service came as not null but have no value of what i specified in the ucinfo,"['java', 'android']" +378721,on the stdabs function is the stdabs function well defined for all arithmetic types in c11 and will return x with no problem of approximationa weird thing is that with g47 stdabschar stdabsshort int stdabsint stdabslong int and stdabslong long int seem to return a double on the contrary of and if the number is casted to a double we could have some approximation error for very large number like 9223372036854775806ll 2633so do i have the guarantee that stdabsx will always return x for all arithmetic types edit here is an example program to make some tests include iostreaminclude iomanipinclude cmathinclude typeinfotemplatetypename tvoid abstestt x static const unsigned int width 16 const t val x if sizeofval 1 stdcoutstdsetwwidthstatic castintval stdcoutstdsetwwidthstatic castintstdabsval else stdcoutstdsetwwidthval stdcoutstdsetwwidthstatic casttstdabsval stdcoutstdsetwwidthsizeofval stdcoutstdsetwwidthsizeofstdabsval stdcoutstdsetwwidthtypeidvalname stdcoutstdsetwwidthtypeidstdabsvalnamestdendlint main double ref 10 abstestcharref abstestshort intref abstestintref abstestlong intref abstestlong long intref abstestsigned charref abstestsigned short intref abstestsigned intref abstestsigned long intref abstestsigned long long intref abstestunsigned charref abstestunsigned short intref abstestunsigned intref abstestunsigned long intref abstestunsigned long long intref abstestfloatref abstestdoubleref abstestlong doubleref return 0,['c++'] +378723,any way to use some scala for ios coding i want to be able to use scala to code ios programs any tools available for this,['ios'] +378733,linqpad and mongodb is it possible to use linqpad with mongodb or any other tool for that matter that allows you to use linq to run adhoc queries on mongoi have tried using the shell to write the queries in json but the brackets quotes colons are driving me absolutely insane if there is not a tool i am going to resort to writing my queries in c and compilingrunning,['.net'] +378742,java filter failing to set response headers i am trying to create a java filter which detects a custom http request header and inserts response headers so that the file will download automatically the response header that is most important for this is the contenttype attachment response header i have created an http request object that inserts the custom headerfunction myhttpobjectfilepathfunction makehttpobject return new xmlhttprequestvar request makehttpobjectrequestopenget filepath falserequestsetrequestheaderxwriadownload pdfdownloadrequestsendnullwindowopenfilepathconsolelogrequestgetallresponseheadersthis will insert the xwriadownload header into the requestthen i have a java filter which looks for that request header and should set the response header to contenttypeattachmentimport javaxservletimport javaxservlethttphttpservletrequestimport javaxservlethttphttpservletresponseimport javaxservlethttphttpsessionimport javaioioexceptionimport javautilhashmapimport javautilmappublic class contenttypefilter implements filter protected filterconfig filterconfigpublic void initfilterconfig filterconfig throws servletexception thisfilterconfig filterconfigpublic void destroy nooppublic void dofilterservletrequest request servletresponse response filterchain chain throws ioexception servletexception httpservletrequest req httpservletrequest request httpservletresponse res httpservletresponse response get the headers we placed in the request based on those request headers set some response headers ifreqgetheaderxwriadownload null ressetheadercontenttype applicationpdf ressetheadercontentthisposition attachment filenamesuccesspdf chaindofilterreqresand then of course the webxml has the code to include the filter on all jsp files the thing that is baffling me is that the header is being set on the response file but it is not downloading as it should if i put the ressetheadercontentthisposition attachment filenamesuccesspdf line outside the if statement then it will work but it will apply the download behavior to all jsps which i do not want why is it applying the contentthisposition but not working when i have the ressetheader in the if statement and then working when it is outside the if statement any ideas for how i can get the desired behavior only applying content thisposition to jsps that i have applied a custom request header to,['java'] +378763,can i use reactive extensions in a monotouch project there is a port of rx called monoreactive that contains a monotouch project but the author announced ten days ago he is abandoning the project in favor of microsoft open source implementationi happily announce that i am not going to work on this code base anymore now that microsoft has opensourced reactive extensions in apache license monodevelop hangs trying to open rxsln in rx master and there is not a monotouch target there anyway pcl support is not there yet for monotouch tooi am wondering if anyone already put up a monotouchcompatible project for rx and whether it is actually usable in production,"['c#', '.net']" +378774,how to get the return type of a method call in intellij normally you would expect just hovering over a method it would show a popup of the return typehow do you get this information in intellij ultimate,['java'] +378788,cannot install rjava on ubuntu system i have seen a few posts related to thisbut all the suggested solutions ive seen dont seem to worki am running r in an ec2 instance and ran the following commands to try and install rjava but to no availany help would be greatly appreciated installpackagesrjava installing packages into ahomeubunturlibrarya as aliba is unspecified trying url 093targz content type applicationxgzip length 537153 bytes 524 kb opened url downloaded 524 kb installing source package arjavaa package arjavaa successfully unpacked and md5 sums checkedchecking for gcc gcc stdgnu99checking for c compiler default output file name aoutchecking whether the c compiler works yeschecking whether we are cross compiling nochecking for suffix of executables checking for suffix of object files ochecking whether we are using the gnu c compiler yeschecking whether gcc stdgnu99 accepts g yeschecking for gcc stdgnu99 option to accept iso c89 none neededchecking how to run the c preprocessor gcc stdgnu99 echecking for grep that handles long lines and e bingrepchecking for egrep bingrep echecking for ansi c header files yeschecking for syswaith that is posix1 compatible yeschecking for systypesh yeschecking for sysstath yeschecking for stdlibh yeschecking for stringh yeschecking for memoryh yeschecking for stringsh yeschecking for inttypesh yeschecking for stdinth yeschecking for unistdh yeschecking for stringh cached yeschecking systimeh usability yeschecking systimeh presence yeschecking for systimeh yeschecking for unistdh cached yeschecking for an ansi cconforming const yeschecking whether timeh and systimeh may both be included yesconfigure checking whether gcc stdgnu99 supports static inlineyeschecking whether setjmph is posix1 compatible yeschecking whether sigsetjmp is declared yeschecking whether siglongjmp is declared yeschecking java support in r presentinterpreter usrbinjavaarchiver compiler header prep cpp flags java libs lusrlibjvmjava6openjdkamd64jrelibamd64server lusrlibjvmjava6openjdkamd64jrelibamd64 lusrlibjvmjava6openjdkamd64jrelibamd64 lusrjavapackageslibamd64 lusrlibx86 64linuxgnujni llibx86 64linuxgnu lusrlibx86 64linuxgnu lusrlibjni llib lusrlib ljvmconfigure error java development kit jdk is missing or not registered in rmake sure r is configured with full java support including jdk runr cmd javareconfas root to add java support to rif you do not have root privileges runr cmd javareconf eto set all javarelated variables and then install rjavaerror configuration failed for package arjavaa removing ahomeubunturlibraryrjavaawarning in installpackages installation of package arjavaa had nonzero exit statusthe downloaded source packages are in atmprtmpaeiskudownloaded packagesa systemsudo r cmd javareconfjava interpreter usrbinjavajava version 160 24java home path usrlibjvmjava6openjdkamd64jrejava compiler not presentjava headers gen java archive tool java library path java homelibamd64serverjava homelibamd64java homelibamd64usrjavapackageslibamd64usrlibx86 64linuxgnujnilibx86 64linuxgnuusrlibx86 64linuxgnuusrlibjnilibusrlibjni linker flags ljava homelibamd64server ljava homelibamd64 ljava homelibamd64 lusrjavapackageslibamd64 lusrlibx86 64linuxgnujni llibx86 64linuxgnu lusrlibx86 64linuxgnu lusrlibjni llib lusrlib ljvmjni cpp flags updating java configuration in etcrdone installpackagesrjavasame as before just skipping to the error parts java libs lusrlibjvmjava6openjdkamd64jrelibamd64server lusrlibjvmjava6openjdkamd64jrelibamd64 lusrlibjvmjava6openjdkamd64jrelibamd64 lusrjavapackageslibamd64 lusrlibx86 64linuxgnujni llibx86 64linuxgnu lusrlibx86 64linuxgnu lusrlibjni llib lusrlib ljvmconfigure error java development kit jdk is missing or not registered in rmake sure r is configured with full java support including jdk runr cmd javareconfas root to add java support to rif you do not have root privileges runr cmd javareconf eto set all javarelated variables and then install rjavaerror configuration failed for package arjavaa removing ahomeubunturlibraryrjavaawarning in installpackages installation of package arjavaa had nonzero exit statusthe downloaded source packages are in atmprtmpaeiskudownloaded packagesa sessioninfor version 2151 20120622platform x86 64pclinuxgnu 64bitlocale 1 lc ctypeen usutf8 lc numericc lc timec lc collatec 5 lc monetaryc lc messagesc lc paperc lc namec 9 lc addressc lc telephonec lc measurementc lc identificationc attached base packages1 stats graphics grdevices utils datasets methods base loaded via a namespace and not attached1 tools 2151,['java'] +378796,what is the easiest way in javascript to get just the sign of a number possible duplicatenumbersign in javascript given some number variable what is the easiest way to determine it is signi keep ending up with code like thisvar direction vector0 0 1 vector0 0 1 0it seems less than elegant when all i want is a 1 if the number is negative 1 if positive and a 0 if it is 0 by easiest i really mean elegant or less typingalternatively maybe there is a way to increase a value absolutely like if the number is negative then subtract 1 from it and if it is positive to add one to it mathabs provides the absolute value but there is no way to convert it back to a signed number once you run mathabs,['javascript'] +378829,running out of band garbage collection with unicorn rack i am attempting to run garbage collection out of band once a request has finished serving its response in my ruby on rails application i added the following to my configru this file is used by rackbased servers to start the applicationrequire fileexpand pathconfigenvironment file begin require unicornoob gcrescue loaderror nameerrorend outofband gc runs gc after every 10th request and after the response has been deliveredbegin use unicornoobgc interval10rescue nameerrorendrun myappapplicationgcstarti am looking at my newrelic portal however and most web transactions do indicate that at least 110150ms is spent on average doing garbage collection is unicornobgc supposed to do it out of the scope of the actual request if it is why is this showing up in the web transaction how do i get time spent on garbage collection to happen outside the context of a web request so that perceived client response times are faster cpu time spent will still be the same since it needs to happen in the background however better in the background than holding up a request pipeline,"['ruby-on-rails', 'ruby']" +378870,eigenmatrixxd to flannmatrix conversion assume that mat below is of type eigenmatrixxd and already contains some data in an attempt to avoid duplicating memory i tried to instantiate a flannmatrixdouble object from the pointer to the raw memory chunk allocated by eigen3flannmatrixdouble inputconst castdouble matdata matrows matcolshowever my algorithm outputs garbage but is just fine with the uglyflannmatrixdouble inputnew doublematrowsmatcols matrows matcolsfor int i 0 i matrows i for int j 0 j matcols j inputij mati ji investigated the option to subclass the base matrix type from flann to create an adaptor to eigen3 matrices the problem though is that matrix relies on the implementation of the operator in its interace it makes me feel that i might encounter the same memory issue than in the simple but broken solution shown above what do you think could explain such behaviour rowcolumnmajor issueinner outer stride issuememory alignment incompatibilities eigenmap is sweet but not what i am looking for it would suck to rewrite my code to use stlvectorstdvectordouble as base types and eigenmap them to eigenmatrixxd 1 1kdtreigenmatrixadaptorhtml unfortunately too far from the base libflann library to be usable,['c++'] +378878,sql select multiple columns into one i have this query in sql server 2008select id year manufacturer model from tableand i need something like thisselect id year space manufacturer space model as mycolumn from tablehow can i get this result,['sql'] +378891,converting equations into bitshifting operations is there any standard way for converting an any equation into bitshift operationsby this i mean converting any thing that is not a or into bitshifts so the end equation contains only the operands and this is in the interest of making formulas less processor intensive obviously these resultant equations will only be approximations giving better accuracy with the more orders considered firstorder secondorder etci have scoured the web for any information on this but cannot find any except for stuff on specific formulas sin cos inv etci was envisioning something like a polynomial or taylors expansion procedure and then converting that to bitshift operations,['c'] +378908,how to set time to midnight for current day every time that i create a nonnullable datetime in my mvc3 application it defaults to now where now is current date with current time i would like to default it to todays date with 12am as the timei am trying to default the time in my mvcbutthe following is not setting to todays date 12am instead it defaults to now with current date and timeprivate datetime begin new datetimedatetimenowyear datetimenowmonth datetimenowday 12 0 0public datetime begin get return begin set begin value how can i set to 12am for the current date for nonnullable datetime,"['c#', '.net']" +378931,high resolution screen shot in android is there any way to get a high resolution screen shot of a certain view in an activity i want to convert html content of my webview to pdf for that i tried to take screen shot of the webview content and then converted it to pdf using itext the resulted pdf is not in much more clarity my code protected void takeimg picture picture mwebviewcapturepicture bitmap b bitmapcreatebitmappicturegetwidth picturegetheight bitmapconfigargb 8 canvas c new canvasb picturedrawc byte bt bgetninepatchchunk bitmap b view v1 mwebviewgetrootview v1setdrawingcacheenabledtrue b bitmapcreatebitmapv1getdrawingcache v1setdrawingcacheenabledfalse fileoutputstream fos null try file root new fileenvironmentgetexternalstoragedirectory sample if rootexists rootmkdir string sdcardhtmlpath rootgetpathtostring temp 1png fos new fileoutputstreamsdcardhtmlpath fos openfileoutputsamsp 1jpg mode world writeable if fos null bcompressbitmapcompressformatpng 100 fos foswritebt fosclose catch exception e logetakeimg etostring eprintstacktrace protected void pdfimg document mydoc new documentpagesizea3 try file root new fileenvironmentgetexternalstoragedirectory sample if rootexists rootmkdir string sdcardhtmlpath rootgetpathtostring mydocsetmargins0 0 0 0 pdfwritergetinstancemydoc new fileoutputstreamsdcardhtmlpath pdffilename mydocopen image image1 imagegetinstancesdcardhtmlpath temp 1jpg image1scalepercent95f mydocaddimage1 mydocnewpage mydocclose catch exception e logepdi name etostring,['android'] +378936,how to convert g729 encoded byte array to wav in c i have been working on a voip application in c sharp language the purpose of the project is voip call recording it uses g729 codec i can extract the voice part from rtp payload how to convert this byte array to wav format please help me,['c#'] +379000,how to rename a column and change its type by migration same time in my general exams table i have a column named semester type is string now i want to change its name to semester id type is integer i have read about migration and it has available transformationsrename columntable name column name new column name renames a column but keeps the type and contentchange columntable name column name type options changes the column to a different type using the same parameters as add columnso i create my migration file like thisclass renamesemesterfromgeneralexams activerecordmigration def change rename column general exams semester semester id change column general exams semester id integer endendbut when i run rake dbmigrate it has error renamesemesterfromgeneralexams migrating rename columngeneral exams semester semester id 00572s change columngeneral exams semester id integerrake abortedan error has occurred this and all later migrations canceledpgerror error column semester id cannot be cast to type integer alter table general exams alter column semester id type integerin my table generalexam i destroyed all dataso anyone can tell me how can i do that or i must create two migration files,['ruby-on-rails'] +379005,how to change timezone for a javautilcalendardate i would like to change the timezone value in a java calendar instance at runtimei tried below but the output is the same in both instances calendar cschedstartcal calendargetinstancetimezonegettimezonegmt systemoutprintlncschedstartcalgettimegettime cschedstartcalsettimezonetimezonegettimezoneasiacalcutta systemoutprintlncschedstartcalgettimegettimeoutput 1353402486773 1353402486773i have tried this also but the output is still the same calendar cschedstartcal calendargetinstancetimezonegettimezonegmt systemoutprintlncschedstartcalgettime calendar cschedstartcal1 calendargetinstancetimezonegettimezoneasiacalcutta cschedstartcal1settimecschedstartcalgettime systemoutprintlncschedstartcalgettimein the api i am seeing the below comment but i am not able to understand much of it calls calsettimezoneest calsethour 1 calsettimezonepst is cal set to 1 of the clock est or 1 of the clock pst answer pst more generally a call to settimezone affects calls to set before and after it up to the next call to completecould you please help meone possible solution calendar cschedstartcal calendargetinstancetimezonegettimezonegmt long gmttime cschedstartcalgettimegettime long timezonealteredtime gmttime timezonegettimezoneasiacalcuttagetrawoffset calendar cschedstartcal1 calendargetinstancetimezonegettimezoneasiacalcutta cschedstartcal1settimeinmillistimezonealteredtimeis this solution ok,['java'] +379042,css applying padding to box with scroll bottompadding does not work i cannot get bottompadding to work when i use overflowy auto on a boxhtmldiv idcontainer div idsome infodivdivcsscontainer padding 3em overflowx hidden overflowy auto width 300px height 300px background redsome info height 900px background 0fiddle edit i use firefox,"['html', 'css']" +379068,annotating resource to produce json but return textplain in response header i am currently implementing a web apispringjerseycomthetransactioncompanycors the output if any will be json so all my classes are annotated with the expected media typeproducesmediatypeapplication jsonpublic class customerresource that way my classes are automatically transformed to jsonbutdue to microsoft their ie only support cors if the requestresponse type is textplain 4 only textplain is supported for the requests contenttype headerso i need to force my application to respond with textplain in the header but still projecting my classes to json output i know that the cors classes i added is setting that header but somehow that is overwritten again by my annotation even if i add another filter by my own,['java'] +379102,how to use a string variable as key in a json object possible duplicateis a way that use var to create json object in key i would like to construct a json object in javascript by using the value of a string variable as the key but what i got is the name of the variable as the keyexamplejsfunction constructjsonjsonkey jsonvalue var jsonobj key1jsonvalue jsonkey2 return jsonobjthe call constructjsonkey28returns a json key18jsonkey2 but i would like to have key18key22does anyone know how to achieve this seems like a simple problem but i cannot find the solutionthx in advanceronny,['javascript'] +379122,utilinherits alternative or workaround i am a n00b in node and find utilinherits very useful except for the fact that it seems to replace the entire prototype of the original object for instancevar myclass functionname this name name myclassprototype utilinheritsmyclass requireeventseventemitterseems to erase my original prototypethat brings me two inconveniences1 i have to declare add properties to my prototype after calling inheritsvar myclass functionname this name name utilinheritsmyclass requireeventseventemittermyclassprototypeprop1 functionmyclassprototypeprop2 functionand most important i think i cannot inherit from two or more different classescan anyone explain to me why this makes sense and what would be a good way to work around thisthanks,['javascript'] +379140,uibutton does not work in uiscrollview i have a scrollview that has a uiview as subview this has as uiview subview a uibutton only the scrollview is connected to the outlet the rest is all in code the button does not respond to touches not turns blue when touched what can i do to make it workthis is the code voidviewdidload super viewdidload selfbuttonhome uibutton buttonwithtypeuibuttontypecustom selfbuttonhome addtargetself actionselectorpressedhome forcontroleventsuicontroleventtouchupinside selfcontainerview uiview allocinitwithframeselfscrollviewframe selfcontainerviewuserinteractionenabledyes selfscrollview addsubviewselfcontainerview selfcontainerview addsubviewselfbuttonhome void pressedhomeidsender,['ios'] +379156,mysql wrongly updates integer column when it is updated second time i have extremely strange problem which drives me crazy all day i have a simple mysql table with few columns one column is int11 null when i update its value it works as expected however when i update its value second time it gets assigned 0 value i have tested this same behaviour on my mysql 51581ubuntu1 and on other mysql 5096community and both behave exactly the same so it apparently is not problem of one version mysqlit is difficult for me to explain but i have attached 2 screenshots which will tell you much better where is the betterfirst screenshot is structure of my table i am updatingand here is shown sql queries beeing executed where you can see that first update is correct and the second produces 0 value in column invoice number with no reasonam i overlooking something obvious it really drives me crazy because it does not make any sense to me thank you for any help in advanceedit i have tried using only numbers in my queries and this is result very strange for me as well,"['mysql', 'sql']" +379169,validating youtube url using regex i am trying to validate youtube urls for my applicationso far i have the following set the youtube urlyoutube url wyoutubecomwatchvvpfzjcczdtckif preg matchhttp0w0youtubecom1 youtube1watchvs1 youtube url 1 echo validelse echo invalidi wish to validate the following variations of youtube urlswith and without httpwith and without with the urls youtubecom and youtubemust have watchvmust have the unique video string in the example above vpfzjcczdtckhowever i do not think i have got my logic right because for some reason it returns true for wyoutubecowatchvvpfzjcczdtck notice i have written it incorrectly with co and not com,['php'] +379178,structure reference and dereference operators suppose i define this structurestruct point double x ynow suppose i create a dynamic array of this typepoint p new point10why do i use pkx and pky instead of pkx and pky to access the kth points elementsi thought you had to use the latter for pointers,['c++'] +379216,why can assignment from one type to the same need checking i am running intellijs code analyzer intellij 14 on a class and am getting this warningunchecked assignment javautillist to javautillist the code it complains about isliststring targetdocumentids pepperworkflowinstancegettargetdocumentidsfor referencepublic class pepperworkflowinstancet extends pepperworkflowinstancedata implements serializable private liststring targetdocumentids new arrayliststring public liststring gettargetdocumentids return targetdocumentids so the types match so why would i need to check the assignment,['java'] +379221,android vertical viewpager is there a way to make a viewpager that does not scroll horizontally but vertically,['android'] +379230,how to give already purchased android app to customer as a gift yes so i know it is not a programmers question but customers sometimes help us devs with our code so we devs shold be grateful i think answer to my question will be useful for all fellow android devsuser has purchased my app refund period 15min is over of course now i would like to return money to him as a gift because he helped me in testing a little if i refund the entire order in checkoutorders will user keep my app purchased i mean will he be able to uninstall and install it again from googleplaymyapps and will app be marked purchased will google lvl accept him to run the appi have done such refunds before but then they called it android market and refund was 12h and there were no lvl maybe somebody know another way to make a small gift using google play,['android'] +379295,how to upload binary file using urlconnection in order to upload a binary file to an url i have been advised to use this guide however the file is not in a directory but is stored in a blob field in mysql db the blob field is mapped as a byte property in jpabyte binaryfilei have slightly modified the code taken from the guide in this wayhttpurlconnection connection httpurlconnection new urlurlopenconnection set some connection propertiesoutputstream output connectiongetoutputstreamprintwriter writer new printwriternew outputstreamwriteroutput charset true set some headers with writerinputstream file new bytearrayinputstreammyentitygetbinaryfilesystemoutprintlnsize fileavailabletry byte buffer new byte4096 int length while length filereadbuffer 0 outputwritebuffer 0 length outputflush writerappendcrlfflush writerappend boundary appendcrlfflush catch and close streamsi am not using chunked streaming the headers used areusername and passwordcontentthisposition formdata namefile filenamemyfilenamerncontenttype applicationoctetstreamcontenttransferencoding binaryall the headers are received correctly by the host it also receives the uploaded file but unfortunately complains that the file is not readable and asserts that the size of the received file is 37 bytes larger than the size outputed by my codemy knowledge of streams connections and byte is too limited for grasping the way to fix this any hints appreciatededitas suggested by the commenter i have tried also to write the byte directly without using the bytearrayinputstreamoutputwritemyentitygetbinaryfileunfortunately the host gives exactly the same answer as the other way,['java'] +379296,access denied for mysql error 1045 i just got a new macbook pro os x 1082 and am attempting to get mysql set up on it so far i have been able to get it installed but i cannot get my root user access or any user for that matter i plan on using this for python on my other computer i only use mysql no mamp and i prefer to keep it that wayfor reference i did the following alias mysqlusrlocalmysqlbinmysql sudo librarystartupitemsmysqlcommysqlcom start alias mysqladminusrlocalmysqlbinmysqladminwhen i enter mysql or mysql u root p it gives me thiserror 1045 280 access denied for user rootlocalhost using password yesor error 1045 280 access denied for user jmitchlocalhost using password no depending on which phrasing i usemysql is running in my system preferences thank you for your help,['mysql'] +379314,contains cycles and cannot be serialized if reference tracking is thisabled jsonnet and webapi i am getting the error object graph for type systemcollectionsgenericlist1projmodelprom projmodel version10 cultureneutral publickeytokennull contains cycles and cannot be serialized if reference tracking is thisabledreading about that seems to be the serializer but jsonnet claims to be the solution and i have read webapi and framework 45 has it by default so is it coming by default if so why i am still getting that error thanks guillermoedit adding codeusing systemusing systemcollectionsgenericusing systemdataspatialnamespace projmodel public class prom public prom thisstores new liststore thisbranches new listbranch thisproducts new listproduct public int id get set public string name get set public dbgeography location get set public string latitude get set public string longitude get set public int stateid get set public int categoryid get set public virtual icollectionstore stores get set public virtual icollectionbranch branches get set public virtual icollectionproduct products get set public virtual category category get set public virtual state state get set using systemusing systemcollectionsgenericnamespace projmodel public class category public category thisproms new listprom public int id get set public string name get set public string description get set public virtual icollectionprom proms get set then running something like this returns the errorpublic ienumerablecategory getlistint estadoid string idtipostarjetaslist var ids 1234split var intids idsselectintparse var categories uowcategoriasgetallincludingc cpromstolist foreach var category in categories var proms categorypromswherep intidscontainspid pstateid stateidtolist categoryproms proms return categories,['c#'] +379353,any way to reliably compress a short string i have a string exactly 53 characters long that contains a limited set of possible characters azaz09 53i need to reduce this to length 50 without loss of information and using the same set of characters i think it should be possible to compress most strings down to 50 length but is it possible for all possible length 53 strings we know that in the worst case 14 characters from the possible set will be unused can we use this information at all thanks for reading,['javascript'] +379364,how to share internal storage file with gmail client i am trying to share my internal storage file via gmail client on my moto razr but every time i sent to my test gmail account i got everything except attachmentthis is how i invoke and start gmail while add file as attachmentprivate void savedaily intent intent new intentandroidcontentintentaction send multipleintentsettypetextplainintentputextraintentextra email new string loademailaddress intentputextraintentextra subject dailyintentputextraintentextra text daily logintentaddflagsintentflag grant read uri permissionarraylisturi uris new arraylisturiurisaddsavedaily2filedailyrecordtxtlogdtag d size urissizeintentputparcelablearraylistextraintentextra stream urisstartactivityintentcreatechooserintent send emailthis is how i implement my customized content providerpublic class savedfileprovider extends contentprovider private static final string tag d contentproviderprivate static final hashmapstring string mime types new hashmapstring stringstatic mime typesputtxt textplainoverridepublic string gettypeuri uri string path uritostringfor string extension mime typeskeyset if pathendswithextension return mime typesgetextension return nulloverridepublic parcelfiledescriptor openfileuri uri string mode throws filenotfoundexception logdtag d openfilefile f new filegetcontextgetfilesdir urigetpathlogdtag d fgetabsolutepathif fexists return parcelfiledescriptoropenf parcelfiledescriptormode read onlythrow new filenotfoundexceptionurigetpathoverridepublic cursor queryuri url string projection string selection string selectionargs string sort throw new runtimeexceptionoperation not supportedoverridepublic uri inserturi uri contentvalues initialvalues throw new runtimeexceptionoperation not supportedoverridepublic int updateuri uri contentvalues values string where string whereargs throw new runtimeexceptionoperation not supportedoverridepublic int deleteuri uri string where string whereargs throw new runtimeexceptionoperation not supportedprivate void copyinputstream in file dst throws ioexception fileoutputstream out new fileoutputstreamdstbyte buf new byte1024int lenwhile len inreadbuf 0 outwritebuf 0 lenincloseoutcloseoverridepublic boolean oncreate logdtag d oncreatefile f new filegetcontextgetfilesdir dailyrecordtxtif fexists assetmanager assets getcontextgetresourcesgetassets try copyassetsopendailyrecordtxt f catch ioexception e logefileprovider exception copying from assets e return false return truethen i add the following lines in my androidmanifestxml fileprovider androidnamesavedfileprovider androidauthoritiespackage path here androidexportedtrue androidgranturipermissionstrue androidmultiprocesstrue provideri wonder what i am missing herei have check the linklink1 link2,['android'] +379365,dependency injection in windows phone 8 does anyone know of decent dependency injection framework for windows phone 8 i am creating a project following mvvm which shares code with a windows store project i was using unity for the windows store app but i cannot get it to work with windows phone has anyone had similar problems,['c#'] +379412,find a list of all jersey resource methods in my app does jersey provide any way to list all of the resources it exposes that is given the resource classpackage comzooresourcepathanimalspublic class animalresource get producesmediatypeapplication json pathdog public dog getdog get producesmediatypeapplication json pathcat public cat getcat does jersey provide any way for me to get the informationget at the path animalsdog returns type dog get at the path animalscat returns type catand furthermore does it provide a way for me to know that animalresource is a resourcei would like to have this information available to me in a unit test so that i can check that every resource i expose conforms to what an external system expectsi know that there is automagic that exposes the applicationwadl but i do not see that showing me return types and i do not know how to access it from within my tests,['java'] +379435,android stream camera data and write it to server i stream webcam data to my clienti can see the data is arriving by listening ondata however when i create it i am not able to view it and it is probably garbage data or missing some headers vlc cannot play it my next step is to make it realtime streamable to browser what am i doing wrongnet requirenetfs requirefs start a tcp servernetcreateserverfunction socket consolelogclient connected var file fscreatewritestreamtempmp4 socketpipefile end false socketonend function consolelogended listen50i tested to see if did it really capture video output mediainfo tempmp4 generalcomplete name tempmp4format h263format version h263file size 126 kibvideoformat h263width pixel0height pixel0color space yuvchroma subsampling 420bit depth 8 bitscompression mode lossyand this is the following android code for setting mediarecorder assume socket is connected no problem mediarecordersetaudiosourcemediarecorderaudiosourcecamcorder mediarecordersetvideosourcemediarecordervideosourcecamera mediarecordersetoutputformatmediarecorderoutputformatdefault mediarecordersetvideosize320 240 mediarecordersetvideoencodermediarecordervideoencoderdefault mediarecordersetaudioencodermediarecorderaudioencoderdefault parcelfiledescriptor pfd parcelfiledescriptorfromsocketsocket mediarecordersetoutputfilepfdgetfiledescriptor mediarecordersetmaxduration50 mediarecordersetmaxfilesize50,['android'] +379437,strange postgresql value too long for type character varying500 i have a postgres schema which looks likethe problem is that whenever i save text longer than 500 characters in the description column i get the errorvalue too long for type character varying500in the documentation for postgres it says type text can have unlimited charactersi am using postgresql91this table has been generated using django 14 and the field type in the model is textfield if that helps explain the problem furtherany ideas as why this is happening and what i can do to fix it,['sql'] +379463,how to use customs fonts in emails or email templates how to use customs fonts in emails or email templates why we cant use custom fonts in emails why fontface style is not supported by most of the mail providers,"['html', 'css']" +379509,how to update same table on deletion in mysql in my database i have a table employee that has recursive association an employee can be boss of other employeecreate table if not exists employee ssn varchar64 not null name varchar64 default null designation varchar128 not null mssn varchar64 default null primary key ssn constraint fk manager employee foreign key mssn references employeessn engineinnodb default charsetlatin1amysql describe employee field type null key default extra ssn varchar64 no pri null name varchar64 yes null designation varchar128 no null mssn varchar64 yes mul null 4 rows in set 0 secthen insertsmysql insert into employee values 1 a owner null 2 b boss 1 3 c worker 2 4 d boss 2 5 e worker 4 6 f worker 1 7 g worker 4 query ok 7 rows affected 002 secrecords 7 duplicates 0 warnings 0 now i have following hierarchical relation owner boss worker among the rows in table a b f c d g efollowing is select statement for table mysql select from employee ssn name designation mssn 1 a owner null 2 b boss 1 3 c worker 2 4 d boss 2 5 e worker 4 6 f worker 1 7 g worker 4 7 rows in set 0 secnow i want to impose a constraint like if any employee boss deleted then new boss of workers under him become immediate boss of deleted employee old boss eg if i delete d then b become boss of g and e for that i also written a trigger as follows mysql delimiter mysql create trigger employee before delete before delete on employee for each row begin update employee set mssnoldmssn where mssnoldmssn endquery ok 0 rows affected 007 secmysql delimiter but when i perform some deletion mysql delete from employee where ssn4error 1442 hy0 cannot update table employee in stored functiontriggerbecause it is already used by statement which invoked this stored functiontriggeri learn here that this trigger is not possible because in mysql triggers cannot manipulate the table they are assigned to is there some other possible way to do this is it possible using nested query can some one suggest me other method a suggestion would be enough but should be efficient edit i got answers instead of trigger a stored procedure or two consecutive queries is possible first and second the solution i wrote for this problem as below working well a a helper signal function as i am writing for mysql version older then 55delimiter create procedure my signalin errortext varchar255begin set sqlconcatupdate in errortext set x1 prepare my signal stmt from sql execute my signal stmt deallocate prepare my signal stmtenda stored procedure to delete employee from employee tablecreate procedure delete employeein dssn varchar64begin declare empdesignation varchar128 declare empssn varchar64 declare empmssn varchar64 select ssn designation mssn into empssn empdesignation empmssn from employee where ssn dssn if empssn is not null then case when empdesignation owner then call my signalerror owner can not deleted when empdesignation worker then delete from employee where ssn empssn when empdesignation boss then begin update employee set mssn empmssn where mssn empssn delete from employee where ssn empssn end end case else call my signalerror not a valid row end ifenddelimiter,"['mysql', 'sql']" +379510,how to change speed of translate and scale when zooming in and out in d3 using zoomon d3eventtranslate d3eventzoom can you adjust the speed of the zoom when the user scrolls in and out using the mousewheelmy understanding is that the zoomon listener produces the two events d3eventtranslate d3eventzoom which contain matrices or coordinates that when passed to the translate or scale functions allow panning and rescaling of the graphic but how do i speed this up so that if the user moves his mousewheel by a little she rapidly zooms in or out i have a large visualization that i want to allow users to zoom in and out of rapidly with the mousewheel can i simply modifyadd arguments to the above existing events and functions or do i have to create my own i have a feeling some of the above is inaccuratepatchy in terms of understanding so please explain if so very simple jsfiddle example here with identical code below var svg d3selectbodyappendsvgsvg attrwidth 10 attrheight 20 appendsvgg calld3behaviorzoomonzoom redraw appendsvggsvgappendsvgrectattrwidth 200attrheight 300attrfill greenfunction redraw svgattrtransform translate d3eventtranslate scale d3eventscale,['javascript'] +379533,error er bad field error unknown column asd123 in field list in node js i receive this error when i am trying to update table in phpmyadmincan anyone tell me whats wrong pleasethis is the tablecreate table ms registereduseruserid varchar10socketid varchar255this is my serverjsvar http requirehttpvar mysql requiremysqlvar connection mysqlcreateconnection host localhost user root password database pushnotificationdbvar userid 1234567890 socketid asd123httpcreateserverfunctionrequest response responsewritehead200 contenttype textplain responsewritehello world responseendlisten1connectionconnect connectionquerycallpushnotificationdbspupdatesocketiduseridsocketidonendfunction consoleloguser userid has updated his socketid to socketid connectionendand this is my spupdatesocketid with as a delimiterdrop procedure if exists spupdatesocketidcreate procedure spupdatesocketidin userid varchar10 in socketid varchar255beginset userid useridset socketid socketidset s concatupdate ms registereduser set socketid socketid where userid useridprepare stmt from sexecute stmtdeallocate prepare stmtendif i try to call the procedure in phpmyadmin like this call pushnotificationdbspupdatesocketid1234567890asd123it works but if i try to call it from nodejs it gave me error like this error er bad field error unknown column asd123 in field list please help,"['mysql', 'sql']" +379572,videoview is not thisplayed on a fragment i have a problem in running a video in samsung s3android 411 the issue seems to be because the videoview is on a fragment because if i put it on and activity it worksalso i found out that if i turn on the gpu hardware acceleration on the video worksi have also a game made by drawing on a surfaceview and that view does not work as wellonly with gpu on the rest of the app content is thisplayed as it supposed to buttons and other layoutsi tested the app on nexus s and on the emulator and it works fine also on other devicesdoes anyone know what the problem could bethank youand here is the codepublic class videofragment extends fragment implements mediaplayeroncompletionlistener mediaplayeronpreparedlistener mediaplayeronerrorlistener private video mvideo private videoview mvideoview the video position private int mposition override public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate view fragmentview inflaterinflaterlayoutscreen video container false mvideoview videoview fragmentviewfindviewbyidridvideoview return fragmentview override public void onpause superonpause pause the video if it is playing if mvideoviewisplaying mvideoviewpause save the current video position mposition mvideoviewgetcurrentposition override public void onresume superonresume mvideoviewsetoncompletionlistenerthis mvideoviewsetonpreparedlistenerthis mvideoviewsetonerrorlistenerthis mvideoviewsetkeepscreenontrue initialize the media controller mediacontroller mediacontroller new mediacontrollergetactivity mediacontrollersetmediaplayermvideoview setup the video view mvideoviewsetmediacontrollermediacontroller mvideoviewrequestfocus mvideoviewsetvideopathmvideogeturl if mvideoview null restore the video position mvideoviewseektomposition mvideoviewrequestfocus override public void ondestroy superondestroy cleanup if mvideoview null mvideoviewstopplayback mvideoview null override public void oncompletionmediaplayer mediaplayer logevideo play end video play override public void onpreparedmediaplayer mediaplayer start the video view mediaplayerstart logevideo play video ready for playback override public boolean onerrormediaplayer mediaplayer int i int i1 logevideo play error i return true i do not think it is something related to contextapplication or activity because on all other devices the video and the games are thisplayed thanks for the help,['android'] +379670,what is the difference between setthisplayhomeasupenabled and sethomebuttonenabled i want to enable the home button in the action bar i am using this codeif buildversionsdk int buildversion codesice cream sandwich actionbarsethomebuttonenabledtrue actionbarsetthisplayhomeasupenabledtruein this i am using sethomebuttonenabled and setthisplayhomeasupenabled to put a back mark at icon in actionbar if i use only setthisplayhomeasupenabled then also will it work is there a need to set sethomebuttonenabled to truewhat is the difference between the two,['android'] +379671,rest services how to specify annotatedmethod without using annotations we are trying to take out all the annotations from our classes and configure it in a springconfigxmlspringconfigxml looks likejaxrsserver idrestserver addressrest jaxrsmodel idrestmodel jaxrsresource namecomcscfsrestcontactretrievecontacthistorybp pathretrievecontacthistorybp jaxrsoperation nameretrieve pathpartyid consumesapplicationjson producesapplicationjson verbget jaxrsparam namereq typecontext jaxrsparam namepartyid typepath jaxrsoperation jaxrsresource jaxrsresource namecomcscfsrestcontactstartcontactbp pathstartcontactbp jaxrsoperation namestartcontact path consumesapplicationjson producesapplicationjson verbput jaxrsparam namereq typecontext jaxrsparam namestartcontact typerequest body jaxrsoperation jaxrsresource jaxrsmodel jaxrsservicebeansnow when i click on the exposed service i get the following trace http status 500 type exception reportmessage description the server encountered an internal error that prevented it from fulfilling this requestexception javalangruntimeexception orgapachecxfinterceptorfault orgapachecxfinterceptorabstractfaultchaininitiatorobserveronmessageabstractfaultchaininitiatorobserverjava102 orgapachecxfphasephaseinterceptorchaindointerceptphaseinterceptorchainjava315 orgapachecxftransportchaininitiationobserveronmessagechaininitiationobserverjava113 orgapachecxftransportservletservletdestinationinvokeservletdestinationjava105 orgapachecxftransportservletservletcontrollerinvokedestinationservletcontrollerjava461 orgapachecxftransportservletservletcontrollerinvokeservletcontrollerjava188 orgapachecxftransportservletabstractcxfservletinvokeabstractcxfservletjava148 orgapachecxftransportservletabstracthttpservlethandlerequestabstracthttpservletjava179 orgapachecxftransportservletabstracthttpservletdogetabstracthttpservletjava108 javaxservlethttphttpservletservicehttpservletjava621 orgapachecxftransportservletabstracthttpservletserviceabstracthttpservletjava159root cause orgapachecxfinterceptorfault orgapachecxfinterceptorabstractfaultchaininitiatorobserveronmessageabstractfaultchaininitiatorobserverjava67 orgapachecxfphasephaseinterceptorchaindointerceptphaseinterceptorchainjava315 orgapachecxftransportchaininitiationobserveronmessagechaininitiationobserverjava113 orgapachecxftransportservletservletdestinationinvokeservletdestinationjava105 orgapachecxftransportservletservletcontrollerinvokedestinationservletcontrollerjava461 orgapachecxftransportservletservletcontrollerinvokeservletcontrollerjava188 orgapachecxftransportservletabstractcxfservletinvokeabstractcxfservletjava148 orgapachecxftransportservletabstracthttpservlethandlerequestabstracthttpservletjava179 orgapachecxftransportservletabstracthttpservletdogetabstracthttpservletjava108 javaxservlethttphttpservletservicehttpservletjava621 orgapachecxftransportservletabstracthttpservletserviceabstracthttpservletjava159root cause javalangnullpointerexception orgapachecxfjaxrsmodelwadlwadlgeneratorhandleoperationwadlgeneratorjava310 orgapachecxfjaxrsmodelwadlwadlgeneratorhandleresourcewadlgeneratorjava253 orgapachecxfjaxrsmodelwadlwadlgeneratorhandlerequestwadlgeneratorjava185 orgapachecxfjaxrsimplrequestpreprocessorcheckmetadatarequestrequestpreprocessorjava189ai did debug into the cxfjaxrs source and at line javalangnullpointerexception orgapachecxfjaxrsmodelwadlwadlgeneratorhandleoperationwadlgeneratorjava310the method searches for the annotatedmethod but the object has annotatedmethod field as null which thus throws the error i could get it to work using annotations in the class above the method but i want it to work through the xml configi have specified jaxrsoperation nameretrieve pathpartyid consumesapplicationjson producesapplicationjson verbgetthe retrieve is the operation to be called what other attribute needs to be set up specified or is it just a limitation of xml configurationps if you feel some more info needs to be added or clarified do leave comments new to restful services and not sure what all information is expected in this contextupdate service classpathstartcontactbppublic class startcontactbp put consumesmediatypeapplication json producesmediatypeapplication json path public comcscfswscontactstartcontactresult startcontactcontext httpservletrequest req comcscfswscontactstartcontact startcontact public comcscfswscontactstartcontactresult startcontacthttpservletrequest req comcscfswscontactstartcontact startcontact call login call actual service call logoff,['java'] +379675,hibernate could not initialize proxy no session my code only retrieves all information related to the usersessionfactory sessionfactory hibernateutilitiesconfiguresessionfactorysession session sessionfactoryopensessionuserdetails ud nullsetaddress useraddress nulltry sessionbegintransaction ud userdetails sessiongetuserdetailsclass 1 useraddress udgetaddresses sessiongettransactioncommit catch hibernateexception e eprintstacktrace sessiongettransactionrollback finally sessionclosesystemoutprintlnudgetnameforaddress addr useraddress systemoutprintlnstate addrgetstatethe udgetaddresses simply returns a set of addresses of the usermy question is that how come the ud object still have its valueeg name even though the session is already close getaddresses is an instance variable of the userdetails class but how come i cannot retrieve its value but i can retrieve regular instance variables of the userdetails classudgetaddresses is an embeddedcollection,['java'] +379682,when do we use saveaccountacaccount account of acaccountstore class please clarify me when do we use this method voidsaveaccountacaccount account withcompletionhandleracaccountstoresavecompletionhandlercompletionhandleras i know we get access to the account through oauth and we do not get users credentials so how do we create an account i have found that acaccount has the only one creation method idinitwithaccounttypeacaccounttype typewhat actually happens when we create account this way and can we save it now,"['iphone', 'objective-c']" +379697,how to set custom listview in android fragement i have been doing application for android tablet in this i need to thisplay two listviews one for simple listview and one for custom listview once i click on simple listview row then that details have to be thispalyed in another custom listview for this i was taken fragment for thisplaying both listviews in single screen for custom listview i was taken custom adapter to bind custom data but when i hit on simple list view row the application shows not responding error my code would be like thisfor my fragment contains the code like thispublic class listdetails extends fragmentprivate int nandroidspublic static arraylisthashmapstring string menuitems new arraylisthashmapstring stringlistdetailsadapter adapterstatic final string key title titleitempublic listdetails constructor for being created explicitly public listdetailsint nandroids thisnandroids nandroids if we are being created with saved state restore our state override public void oncreatebundle saved superoncreatesaved if null saved nandroids savedgetintnandroids save the number of androids to be thisplayed override public void onsaveinstancestatebundle tosave tosaveputintnandroids nandroids make a grid and fill it with and androids override public view oncreateviewlayoutinflater inflater viewgroup container bundle saved int n context c getactivitygetapplicationcontext linearlayout l new linearlayoutc string listitemsnew stringnandroids hashmapstring string map new hashmapstring string mapputkey title question1 map new hashmapstring string mapputkey title question2 map new hashmapstring string mapputkey title question3 map new hashmapstring string mapputkey title question4 menuitemsaddmap for n 0 and nandroids n listitemsn onen listview list new listviewc adapter new listdetailsadapterthis menuitems listsetadapteradapter return l and my custom adapter code like thispublic class listdetailsadapter extends baseadapterprivate listdetails listactivityprivate activity activityprivate arraylisthashmapstring string dataprivate static layoutinflater inflaternullpublic listdetailsadapteractivity a arraylisthashmapstring string d activity a datad inflater layoutinflateractivitygetsystemservicecontextlayout inflater servicepublic int getcount todo autogenerated method stub return datasizepublic object getitemint position todo autogenerated method stub return positionpublic long getitemidint position todo autogenerated method stub return positionpublic view getviewint position view convertview viewgroup parent todo autogenerated method stub view viconvertview ifconvertviewnull vi inflaterinflaterlayoutcustomlist null textview title textviewvifindviewbyidridtxttitle button btnone buttonvifindviewbyidridbtnfirst button btntwo buttonvifindviewbyidridbtnsecond button btnthree buttonvifindviewbyidridbtnthird button btnfour buttonvifindviewbyidridbtnfourth button btnfive buttonvifindviewbyidridbtnfifth btnonesetonclicklisteneroneclick btntwosetonclicklistenertwoclick btnthreesetonclicklistenerthrirdclick hashmapstring string mymap new hashmapstring string mymap datagetposition titlesettextmymapgetlistdetailskey title return viprivate viewonclicklistener oneclick new viewonclicklistener public void onclickview v todo autogenerated method stub logebutton clicked button one clicked please guide me whats going wrong in above code,['android'] +379711,how to allow multiple product selection in magento widget configuration i am trying to implement embedded widget administrators will be able to configure this widget and embed it inside wysiwyg editor two of the many configuration options are list of products that should show up on frontend and list of categoriesi want to allow this selection with adminhtmlcatalog product widget chooser and adminhtmlcatalog category widget chooser i tried to implement these widgets with sparse documentation available on the web but all i managed to accomplish is implementation for selecting one product or selecting one category i need multiselect behavioras far as i can see no multiselection possibility is allowed by the current implementation i checked code for both classes and gridphtml template and it seams it is badly written and not extensible beyond current intention of use for example this is how you would suppose to initialize helper block for a widget parameter to allow multiple selecthelper block typeadminhtmlcatalog product widget choosertype data button translateopen openselect productsopen button use massaction1use massaction datahelper blockbut product chooser is hard coded for use without mass actions with this part of the codepublic function prepareelementhtmlvarien data form element abstract element uniqid magehelpercoreuniqhashelementgetid sourceurl thisgeturlcatalog product widgetchooser array uniq id uniqid use massaction false and gridphtml template that is supposed to have some kind of button to confirm multiple selection is just showing search and reset filter buttons and there is no handling of adding another button for example here is the default code responsible for printing button htmlpublic function getmainbuttonshtml html ifthisgetfiltervisibility html thisgetresetfilterbuttonhtml html thisgetsearchbuttonhtml return htmlonly these two buttons are going to be printed by defaultso i started my own implementation based on two implementations mentioned above and it is getting ugly and could end up as an unmaintainable mess of copypasta and i work by principle that if things start to look ugly then i am doing something wrongso is there a straightforward way to implement multiple product and multiple category selection on widget configuration screen by using grid widget,['php'] +379752,a way to scroll an underlying div when mouse is on top of a fixed div the question is so long that coming up with a title that summarises it proved trickyso anyway i have a div that has overflow auto and that frequently does flow over so the scrollbar appears then i have a div that has position fixed and is positioned on top of the content divnow when i have a fixedpositioned div over the html body itself i can scroll the document with the wheel when i have my mouse over the div not so lucky with the aforementioned divis there a way to scroll the div through the fixedpositioned onei noticed that even catching the scroll event when over the fixed div is not easy the event is not fired unless the fixed div itself is scrollablei made a simple jsfiddle here and for your convenience stripped it of all the javascript i triededit i need to retain other mouse functions with the fixed div so turning pointerevents off is not the solution in my case,"['javascript', 'jquery', 'html', 'css']" +379785,how to i thisplay why some tests where skipped while using pytest i am using skipif from unittest for skipping tests in certain conditions unittestskipifcondition this is why i skipped themhow do i tell pytest to thisplay skipping conditionsi know that for unittest i need to enable the verbose mode v but the same parameter added to pytest increase the verbosity by still does not thisplay the skip reasons,['python'] +379824,updating a date in oracle sql table i am trying to update a date in a sql table i am using peoplesoft oracle when i run this queryselect asofdate from pasofdatei get 4162012i tried running this queryupdate pasofdate set asofdate 11212012but it is not working does anyone know how i would change the date to the one desired,['sql'] +379837,retrieve file creation or modification date i am using this piece of code to try to retrieve the last modified date of a filenserror error nilnsdictionary attributes nsfilemanager defaultmanager attributesofitematpath myfilepath errorerror if attributes nil nsdate date nsdateattributes objectforkey nsfilemodificationdate nslogdate modiifed date description else nslognot found this works well for files in the main bundle but not if the file is located in a subdirectory of the apps document folder with myfilepath like thisusersuserlibraryapplication supportiphone simulator60applicationsthe app id numberdocumentsmysubdirectorymy saved fileit keeps returning not foundi know the file is there as i can view it with finder i also tried removing the spaces in the file name but this had no effectthe error log says no such file or directory so it looks like something must have gone wrong when i tried to copy the file to the document directory weird thing is iterating through the document sub directory with contentsofdirectoryatpath shows the file as being presenti have tried hardcoding the path and retrieving it programmatically withmyfolder documentsdirectory stringbyappendingpathcomponentmyfoldermyfilepath myfolder stringbyappendingpathcomponentthefilenamecan anyone see where i am going wrong,"['ios', 'objective-c']" +379883,nodejs express launching my app expresscreateserver is deprecated i downloaded a node app to test and play around with i have googled around and found that express is found to be a little outdated can someone help me to fix the implemented codehere is the code module dependencies base dependencies for appvar express requireexpress routes requireroutes db requireaccessdbaccessdb passport requirepassport mongoose requiremongoose mongostore requireconnectmongodbvar app moduleexports expresscreateserverglobalapp appvar db requireaccessdbvar conn mongodblocalhostcrowdnotesvar db socketio configurationvar io requiresocketiolistenappiosocketsonconnection functionsocket socketonuser note function note consolelognote configurationappconfigurefunction appsetviews dirname views appsetview engine jade appuseexpresscookieparser appuseexpressbodyparser appuseexpressmethodoverride appuserequirestylusmiddleware src dirname public appuseexpresession store mongostoreconn secret applecake function appuseapprouter appusepassportinitialize appusepassportsession appuseexprestatic dirname publicdb new dbstartupconnappconfiguredevelopment function appuseexpresserrorhandler dumpexceptions true showstack true appconfigureproduction function appuseexpresserrorhandler routesrequireroutesappapplisten30consolelogexpress server listening on port d in s mode appaddressport appsettingsenvand here is the error i receive once running the app via node appccrowdnotesnode appwarning expresscreateserver is deprecated expressapplications no longer inherit from httpserverplease use var express requireexpress var app expressccrowdnotesappjs63consolelogexpress server listening on port d in s mode appaddresspo typeerror object function appreq res apphandlereq res has no methodaddress at objectanonymous ccrowdnotesappjs6367 at module compile modulejs44926 at objectmodule extensionsjs modulejs46710 at moduleload modulejs35632 at functionmodule load modulejs31212 at modulerunmain modulejs49210 at procestartupprocessnexttickprocess tickcallback nodejs2449ccrowdnotesfixedi am now at the point where i register and go to login using my new user data and receive this errorreferenceerror ccrowdnotesviewsaccountjade6 4 divheader 5 h2 crowdnotes 6 p hi currentusernamefirst 7 8 if myevent 9 pcenter my event myeventname currentuser is not defined at eval eval at anonymous ccrowdnotesnode modulesjadelibjadejs1768 at exportscompile ccrowdnotesnode modulesjadelibjadejs18112 at objectexportsrender ccrowdnotesnode modulesjadelibjadejs21614 at viewexportsrenderfile as engine ccrowdnotesnode modulesjadelibjadejs24313 at viewrender ccrowdnotesnode modulesexpresslibviewjs758 at functionapprender ccrowdnotesnode modulesexpresslibapplicationjs50010 at serverresponseresrender ccrowdnotesnode modulesexpresslibresponsejs7167 at moduleexportsgetaccount ccrowdnotesroutesindexjs4711 at promisemoduleexportsgetmyevent ccrowdnotesaccessdbjs547 at promiseaddback ccrowdnotesnode modulesmongooselibpromisejs1288i am wondering if this is some form of syntax error too not sure whats gone wrong here as i thought the code all lined up tbhi am using the code from here,['javascript'] +379918,jaxws error on wsdl file error resolving component sschema the errori am using wsimport in a java project to generate sources for three soap web services the first two work fine i use the jaxws maven plugin to grab the wsdl file and generate corresponding java source filesthis fails for one web service i get the following errorjaxwswsimportprocessing homemenetbeansprojectsadminadminwebsrcwsdlerpappdevelsrvmycompanycaegtestreportengineserviceasmxwsdljaxwswsimport args s homemenetbeansprojectsadminadminwebtargetgeneratedsourcesjaxwswsimport d homemenetbeansprojectsadminadminwebtargetclasses verbose catalog homemenetbeansprojectsadminadminwebsrcjaxwscatalogxml wsdllocation target 20 extension xnocompile homemenetbeansprojectsadminadminwebsrcwsdlerpappdevelsrvmycompanycaegtestreportengineserviceasmxwsdlparsing wsdlsrcresolve42 error resolving component sschema it was detected that sschema is in namespace but components from this namespace are not referenceable from schema document filehomemenetbeansprojectsadminadminwebsrcwsdlerpappdevelsrvmycompanycaegtestreportengineserviceasmxwsdltypesschema1 if this is the incorrect namespace perhaps the prefix of sschema needs to be changed if this is the correct namespace then an appropriate import tag should be added to filehomemenetbeansprojectsadminadminwebsrcwsdlerpappdevelsrvmycompanycaegtestreportengineserviceasmxwsdltypesschema1 line 80 of filehomemenetbeansprojectsadminadminwebsrcwsdlerpappdevelsrvmycompanycaegtestreportengineserviceasmxwsdltypesschema1undefined element declaration sschema line 80 of filehomemenetbeansprojectsadminadminwebsrcwsdlerpappdevelsrvmycompanycaegtestreportengineserviceasmxwsdlundefined element declaration sschema line 127 of filehomemenetbeansprojectsadminadminwebsrcwsdlerpappdevelsrvmycompanycaegtestreportengineserviceasmxwsdlundefined element declaration sschema line 142 of filehomemenetbeansprojectsadminadminwebsrcwsdlerpappdevelsrvmycompanycaegtestreportengineserviceasmxwsdlthe culpritthe difference between this wsdl file and the ones that work is whats at the lines noted in the error message lines 80 127 and 142selement refsschema note the root element of the wsdl file defines the s namespace thusxmlnss what i have triedi have done my research it looks like other people have had similar problems with solutions from just do not use selement refsschema to use an import tag to some unknowable solution that was apparently on the old javanet forum before it was taken down an arson of the modernday alexandrian library of java knowledgei have tried putting the following import statement just inside the element that contains the problem tags simport namespace schemalocation wsimport gives me a new errorjaxwswsimportprocessing homemenetbeansprojectsadminadminwebsrcwsdlerpappdevelsrvmycompanycaegtestreportengineserviceasmxwsdljaxwswsimport args s homemenetbeansprojectsadminadminwebtargetgeneratedsourcesjaxwswsimport d homemenetbeansprojectsadminadminwebtargetclasses verbose catalog homemenetbeansprojectsadminadminwebsrcjaxwscatalogxml wsdllocation target 20 extension xnocompile homemenetbeansprojectsadminadminwebsrcwsdlerpappdevelsrvmycompanycaegtestreportengineserviceasmxwsdlparsing wsdlelement annotation shows up in more than one properties line 248 of the following location is relevant to the above error line 242 of property any is already defined use ltjaxbproperty to resolve this conflict line 108 of filehomemenetbeansprojectsadminadminwebsrcwsdlerpappdevelsrvmycompanycaegtestreportengineserviceasmxwsdlthe following location is relevant to the above error line 109 of filehomemenetbeansprojectsadminadminwebsrcwsdlerpappdevelsrvmycompanycaegtestreportengineserviceasmxwsdlproperty any is already defined use ltjaxbproperty to resolve this conflict line 184 of filehomemenetbeansprojectsadminadminwebsrcwsdlerpappdevelsrvmycompanycaegtestreportengineserviceasmxwsdlthe following location is relevant to the above error line 185 of filehomemenetbeansprojectsadminadminwebsrcwsdlerpappdevelsrvmycompanycaegtestreportengineserviceasmxwsdlproperty any is already defined use ltjaxbproperty to resolve this conflict line 199 of filehomemenetbeansprojectsadminadminwebsrcwsdlerpappdevelsrvmycompanycaegtestreportengineserviceasmxwsdlthe following location is relevant to the above error line 200 of filehomemenetbeansprojectsadminadminwebsrcwsdlerpappdevelsrvmycompanycaegtestreportengineserviceasmxwsdllines 108 and 109 referenced in this error are lines 1845 199200 are similarsany minoccurs0 maxoccursunbounded namespace processcontentslax sany minoccurs1 namespaceurnschemasmicrosoftcomxmldiffgramv1 processcontentslax i have tried upgrading jaxwsmavenplugin from 110 to 22 same problemheres a possible solution i am trying to figure out how to implement this using the jaxws maven plugin any hintsconclusionany ideas any further information you need i have omitted the pomxml and serviceasmxwsdl files for brevity but could include them if there is more important information in themthank youaddendaheres another person having the same problem if this is helpful to any potential answerersheres yet another similar problemi do not really understand this article but it seems to imply that i have to parse the soap xml manually horror,['java'] +379922,comparing synchronizationcontext how do i compare synchronizationcontext it seems that the same thispatcher can create different synchronizationcontext when using begininvoke when i drill down into the two unequal contexts i see that the thispatcher thread id is the same yet they are not equal to each otherpublic partial class mainwindow window private synchronizationcontext contexta private synchronizationcontext contextb private synchronizationcontext contextc private synchronizationcontext contextd public mainwindow initializecomponent contexta synchronizationcontextcurrent loaded mainwindow loaded private void mainwindow loadedobject sender routedeventargs e contextb synchronizationcontextcurrent thispatcherinvoke contextc synchronizationcontextcurrent thispatcherbegininvokenew action contextd synchronizationcontextcurrent debugassertcontexta contextb debugassertcontexta contextc fails why debugassertcontexta contextd fails why debugassertcontextc contextd fails why maybe the two of them cannot be used together i noticed that this actually works contextasendnew sendorpostcallbacks contexte synchronizationcontextcurrent nullupdate but strangely it does not always work public override void addrangeienumerablet items if synchronizationcontextcurrent context baseaddrangeitems else contextsendnew sendorpostcallbackstate addrangestate as ienumerablet items never gets a matched context and goes on forever for example even though it should not this latter example the threads actually end up being the same and there is a context but it is differentupdate2 ok i got it to work but i really feel uncomfortable about it apparently when you post or send your task is run from the right thread but if you are not coming from the ui it seems that a new synchronizationcontext is generated public override void addrangeienumerablet items if synchronizationcontextcurrent context baseaddrangeitems else contextpostnew sendorpostcallbackstate if synchronizationcontextcurrent context synchronizationcontextsetsynchronizationcontext context called every time strange addrangeitems null and look at thisrequires full trust for the immediate caller this member cannot be used by partially trusted or transparent code,['c#'] +379939,what size of clyther overhead i am thinking about using clyther for a high performance task it is exciting to write opencl kernels using only python but i am wondering about the performance gap what are tasks that clyther is good at bad at are clythergenerated kernels good or notis it possible to find some benchmarks,['python'] +379940,angular ui sortable callback is there a way to set a callback function with angular uis sortable i would like to add ngupdatefoo to the tbody tag below and have foo run whenever the list changestbody idexistingstockresults uisortable ngmodelprocesses tr ngrepeatprocess in processes ngclassodd index2 0 even index2 0 tdprocessprocesstd tdprocessvendortd tdprocessdesctd tdprocesscosttd tda href ngclickeditprocessindexeditatd tda href ngclickremoveprocessindexremoveatd trtbodythanks,['javascript'] +379961,ajax call destroys session wiht no apparent reason i know it looks like a banal question but please read the whole thing i am stumped by thisi have an ajax call on one of my pages it is a dynamic messaging systemfunction validatemessage var recipient documentgetelementbyidsend tovalue var subject documentgetelementbyidpopup subjectvalue var message documentgetelementbyidpopup messagevalue var parametersmessagemessagerecipientrecipientsubjectsubject if windowxmlhttprequest code for ie7 firefox chrome opera safari xmlhttpnew xmlhttprequest else code for ie6 ie5 xmlhttpnew activexobjectmicrosoftxmlhttp xmlhttponreadystatechangefunction if xmlhttpreadystate4 xmlhttpstatus200 documentgetelementbyiderror messinnerhtml xmlhttpresponsetext xmlhttpopenpostincludesend messagephpfalse xmlhttpsetrequestheadercontenttype applicationxwformurlencoded xmlhttpsendparameters it is implemented as synchronous for a reason that is not the issue here i tried switching to asynchronous and the problem remainsthis is the send messagephp file it just grabs the post variables and saves them into the databasephpsession startincludedbphpdbconnectmessage postmessagesubject postsubjectrecipient postrecipientresultmysql queryselect from korisnici where usernamerecipient or diemysql errorrowmysql fetch arrayresultnummysql num rowsresultifrecipientporuka za subjectnaslov messageporuka recipient subject message echo p stylecolorredmorate popuniti sva poljapelseifnum0 echo p stylecolorredkorisnik ne postojipelse primarowid user salje sessionid user mysql queryinsert into poruke salje prima naslov poruka values salje prima subject message or diemysql error echo p stylecolorgreenporuka uspjeano poslataphowever when i tried to save the sessionid user variable as the sender i found a problem it turns out the session is being destroyed every time this ajax call runs so doing print r session right after session start prints an empty arraythe session is alive on the original page itself and refreshing that page keeps the session alive only when i click the button to make the ajax call the session thisappears can someone spot the issue,"['php', 'javascript']" +380076,how to convert between linq expressions with different return types i am having a headache trying to convert the following linq expression expressionfunct objectto the following linq expression expressionfunct uin the example above the object is always of type u i know how easy it could to convertcast between parameter types but i am not too sure how to cast between return types,"['c#', '.net']" +380103,how to extract the host from a url in javascript capture the domain till the ending characters i need a regex that captures domiancom in all of thesedomaincom30domaincompassgasdomaincomdomaincom,['javascript'] +380109,datacontractjsonserializer to skip nodes with null values i am using datacontractjsonserializer to serialize my custom object to json but i want to skip the data members whose values are null if datamember is null that node should not come in json stringhow can i achieve this give me a simple code snippet to work with,['c#'] +380111,how to determine if rails is running from cli console or as server i have a middleware for announcing my application on the local network app using bonjour but it is also announcing the service when rails is invoked from rake or through the console i would like to exclude these cases and only use the bonjour middleware when rails is running as a server the middleware configuration accepts a proc to exclude middlewares under certain conditions using a procconfigmiddlewareinsert before actionthispatchstatic rackssl exclude proc env envhttps on but how do i determine if rails was invoked from the cli console or as a server,['ruby-on-rails'] +380120,java asynchronous exceptions can i catch them i have been reading the jls and i encountered the section 13 asynchronous exceptions from which i quotemost exceptions occur synchronously as a result of an action by the thread in which they occur and at a point in the program that is specified to possibly result in such an exception an asynchronous exception is by contrast an exception that can potentially occur at any point in the execution of a programandasynchronous exceptions occur only as a result ofan internal error or resource limitation in the java virtual machine that prevents it from implementing the semantics of the java programming language in this case the asynchronous exception that is thrown is an instance of a subclass of virtualmachineerroris it possible to catch such exceptions for logging purposes or notification because i believe such thing is unrecoverable how can i achieve such thing,['java'] +380135,doctrine2 export entity to array i have product entity with manytoone to category entity i need store product in session first of all i try to implement serializable interface on product how should i serialize my related category entity should i also implement serializable interfacei read that serialization in doctrine is very pain operation and i think about thiscan we get raw values from entity exactly that data which stored in database if we can get this values we can store it anywhere and recreate objecti read doctrine2 code and find method doctrineorminternalhydrationobjecthydratorhydraterowdata but it is protected is there any public api for doing thisupdatei just copypaste and integrate some code from basicentitypersister and it seems to work product productsrepositoryfindid if product throw thiscreatenotfoundexceptionno product found for id id uow emgetunitofwork entitypersister uowgetentitypersisterget classproduct classmetadata entitypersistergetclassmetadata originaldata uowgetoriginalentitydataproduct result array foreach originaldata as field value if issetclassmetadataassociationmappingsfield assoc classmetadataassociationmappingsfield only owning side of x1 associations can have a fk column if associsowningside assoctype doctrineormmappingclassmetadatato one continue if value null newvalid uowgetentityidentifiervalue targetclass emgetclassmetadataassoctargetentity owningtable entitypersistergetowningtablefield foreach assocjoincolumns as joincolumn sourcecolumn joincolumnname targetcolumn joincolumnreferencedcolumnname if value null resultowningtablesourcecolumn null else if targetclasscontainsforeignidentifier resultowningtablesourcecolumn newvalidtargetclassgetfieldforcolumntargetcolumn else resultowningtablesourcecolumn newvalidtargetclassfieldnamestargetcolumn elseif issetclassmetadatacolumnnamesfield columnname classmetadatacolumnnamesfield resultentitypersistergetowningtablefieldcolumnname value print rresultin result we have raw values now we need way how to create object by this array,['php'] +380168,android seterrorerror not working in textview we can set error in edittext successfully but failed to set in textview is there any problemi triedtextview findviewbyidriddfrequestfocustextview findviewbyidriddfsetselectedtruetextview findviewbyidriddfseterrorakjshbdbut i am not getting popup for error,['android'] +380169,delete topn rows from a table with some sortingorder by column i am having some confusion regarding deleting the top and rows order by some columni created have an example here example at fiddlewhat is wrong with these queries delete top3 from table1 order by id desc delete top3 from table1 where id in select id from table1 order by id descsince in mysql the limit keyword does the job very well,['sql'] +380178,creating multi purpose button in html when on a phone i am unable to view these two buttons as they are too far apart i want to make it so after you choose the file the choose file button would be replaced by the upload button is this possible what would i have to domy html form methodpost action enctypemultipartformdata nameform1 input namefile typefileclassbox input typesubmit idmybut valueupload namesubmitformnote i do not care to put them on separate lines or make font smaller etc,"['javascript', 'html', 'css']" +380184,java reflection getconstructor method lets say i have classes a and b where b extends a i also have a constructor in b with one argument which is of type a i also have an object of type b called bobjis there a way to call bclassgetconstructornew class bobjgetclass and get the constructor since b extends a at the moment i am getting a nosuchmethodexceptionregardsstan,['java'] +380210,converting camera yuvdata to argb with renderscript this is my first question here in stackoverflowmy problem is i have set up a camera in android and receive the preview data by using an onpreviewframelistener which passes me an byte array containing the image data in the default android yuvformat device does not support r5g6b5format each pixel consists of 12bits which makes the thing a little tricky now what i want to do is converting the yuvdata into argbdata in order to do image processing with it this has to be done with renderscript in order to maintain a high performance my idea was to pass two pixels in one element which would be 24bits 3 bytes and then return two argb pixels the problem is that in renderscript a u8 3 a 3dimensional 8bit vector is stored in 32bit which means that the last 8 bits are unused but when copying the image data into the allocation all of the 32bits are used so the last 8bit get lost even if i used a 32bit input data the last 8bit are useless because they are only 23 of a pixel when defining an element consisting a 3bytearray it actually has a real size of 3 bytes but then the allocationcopyfrommethod does not fill the inallocation with data argueing it does not has the right data type to be filled with a bytethe renderscript documentation states that there is a scriptintrinsicyuvtorgb which should do exactly that in api level 17 but in fact the class does not exist i have downloaded api level 17 even though it seems not to be downloadable any more does anyone have any information about it does anyone have ever tried out a scriptintrinsicso in conclusion my question is how to convert the camera data into argb data fast hardwareacceleratedthat is how to do it in dalvik vm found the code somewhere online it works suppresswarningsunusedprivate void decodeyuv420spint rgb byte yuv420sp int width int height final int framesize width height for int j 0 yp 0 j height j int uvp framesize j 1 width you 0 v 0 for int i 0 i width i yp int y 0xff int yuv420spyp 16 if y 0 y 0 if i 1 0 v 0xff yuv420spuvp 128 you 0xff yuv420spuvp 128 int y1192 1192 y int r y1192 1634 v int g y1192 833 v 400 u int b y1192 2066 u if r 0 r 0 else if r 262143 r 262143 if g 0 g 0 else if g 262143 g 262143 if b 0 b 0 else if b 262143 b 262143 rgbyp 0xff0 r 6 0xff0 g 2 0xff00 b 10 0xff,['android'] +380274,uibackgroundmodes location and significant location changes with region monitoring i have an app that uses a combination of startmonitoringforregion and startmonitoringsignificantlocationchanges to keep aware of where the user is when the app is in the background does this mean that i need to include the location value for the uibackgroundmodes key in the infoplistthis is a quote from the docsthe significantchange location service is highly recommended for apps that do not need highprecision location data with this service location updates are generated only when the useras location changes significantly thus it is ideal for social apps or apps that provide the user with noncritical locationrelevant information if the app is suspended when an update occurs the system wakes it up in the background to handle the update if the app starts this service and is then terminated the system relaunches the app automatically when a new location becomes available this service is available in ios 4 and later and it is available only on devices that contain a cellular radioan app that provides continuous location updates to the user even when in the background can enable background location services by including the uibackgroundmodes key with the location value in its infoplist file the inclusion of this value in the uibackgroundmodes key does not preclude the system from suspending the app but it does tell the system that it should wake up the app whenever there is new location data to deliver thus this key effectively lets the app run in the background to process location updates whenever they occurmy interpretation of this is that the location value for the uibackgroundmodes key is only required if the app needs continuous location updates like a sat nav appi have also tried running the app on a device without the location value for the uibackgroundmodes key and it continues to report significant location changes and when the a region is entered of exitedalso the only place that uibackgroundmodes is mentioned in the cllocationmanager class reference is in the startupdatinglocation thiscussion which i am not using,"['iphone', 'objective-c', 'ios']" +380284,the enable externalimages property has not been set for this report i am trying to add an external photo as the logo along with the report on the reportrdlc file i have this errorthe enable externalimages property has not been set for this reporthere is my code try thispedidostableadapterconnectionconnectionstring conmysqlconnect thispedidostableadapterfillthisfabricacaodataset8pedidos pagesrelatoriosnum thisreportviewer1refreshreportcatch for external imagethisreportviewer1localreportenableexternalimages truereportparameter parm new reportparameterparmnew reportparameterpath clogojpgtruethisreportviewer1localreportsetparametersparmthisreportviewer1refresh,['c#'] +380340,how to set timeout for a line of c code possible duplicateset timeout to an operation how can i set timeout for a line of code in cfor examplerunthislinesomemethodsome input timespanfromseconds10run somemethod with 10 second time outthanks in advance,['c#'] +380354,javascript automatically converts some special characters i need to extract a htmlsubstring with js which is position dependent i store special characters htmlencodedfor examplehtmldiv idtestploumlsen amp gruumlszligenpdivatextlasen gra14aenmy problem lies in the jspart for example when i try to extract the fragmentla which has the htmldependent starting position of 3 and the end position of 9 inside the div block js seems to convert some special characters internally so that the count from 3 to 9 is wrongly interpreted as lasen and not louml other special characters like the amp are not affected by thisso my question is if someone knows why js is behaving in that way characters like auml or ouml are being converted while characters like amp or nbsp are plain is there any possibility to avoid this conversioni have set up a fiddle to demonstrate this jsfiddlethanks for any helpeditmaybe i have explained it a bit confusing sorry for that what i want is the htmlploumlsen amp gruumlszligenp every special character should be unconverted except the htmltags like in the html abovebut js converts the ouml or uuml into a or a14 automatically what i need to avoid,"['javascript', 'jquery']" +380364,jackson best way writes a java list to a json array i want to use jackson to convert a arraylist to a jsonarray eventjava this is the java bean class with two fields field1 field2 mapped as jsonpropertymy goal isconvertarraylistevent list new arraylistevent listaddnew eventa1a2 listaddnew eventb1b2to field1a1 fielda2field1b1 fieldb2the way i can think of iswritelisttojsonarraypublic void writelisttojsonarray throws ioexception arraylistevent list new arraylistevent listaddnew eventa1a2 listaddnew eventb1b2 outputstream out new bytearrayoutputstream jsonfactory jfactory new jsonfactory jsongenerator jgenerator jfactorycreatejsongeneratorout jsonencodingutf8 objectmapper mapper new objectmapper jgeneratorwritestartarray for event event list string e mapperwritevalueasstringevent jgeneratorwriterawusage here big hassles to write a comma to separate json objects when the last object in the list is reached no comma jgeneratorwriteendarray jgeneratorclose systemoutprintlnouttostringi am looking for something likegeneratorwriteout list this directly convert the list to json array format and then write it to outputstream outeven greediergeneratorwriteout list1generatorwriteout list2this will just convertadd in the list1 list2 into a single json array then write it to out,['java'] +380369,nesting a text inside a tag in slim how do i nest the featured text inside the a tag given the span the text and the other span are siblingsli a href claselected span classiconbefore featured span classiconafter,"['ruby-on-rails', 'ruby']" +380386,how to get file from directory with patternfilter i have to get a file from a pdf files directory i have problem that i have not a field to concant all data to find the fileheres an examplefile namecomp 20120619 170310 2 632128 fc a 8 23903pdffile name generatecomp 20120619 2 632128 fc a 8 23903pdfi dont have the field to make file complete namei am trying with filelist but i cannot find the correct file,['java'] +380387,entity framework 5 why is entity state modified after propertyvalue is set back to original i use the ef5 and do not know why a entity has the state modified after i set the only changed propertyvalue of this entity back to the original value using testdbcontext context new testdbcontext string name contextpersonfirstname count is 0 int count contextchangetrackerentriescounte estate entitystatemodified change value contextpersonfirstname test count is 1 count contextchangetrackerentriescounte estate entitystatemodified revert value contextpersonfirstname name contextchangetrackerdetectchanges count is 1 count contextchangetrackerentriescounte estate entitystatemodified why,['c#'] +380389,what is the difference between lowagie and itext what is the difference between lowagie and itext is this just version difference or an upgrade to the library which one is recommended to be used,['java'] +380453,whats the difference between palphai and pli in ruby i am trying to build a regexp in ruby to match alpha characters in utf8 like a3aoa14 etc i know palphai works and pli works too but whats the difference,['ruby'] +380476,jfilechooser filters i am putting a jfilechooser in my program but that only takes images so i decided to add filterscodeimport javaxswingpublic class filechooser public static void mainstring args jpanel panel new jpanel final jfilechooser fc new jfilechooser int file fcshowopendialogpanel fcaddchoosablefilefilternew imagefilter fcsetacceptallfilefilterusedfalse i got that straight from the java tutorials but eclipse underlines the following as an errorfcaddchoosablefilefilternew imagefilterfcsetacceptallfilefilterusedfalseany suggestions,['java'] +380477,using deployjavarunapplet to target specific element after many years of successfully maintaining an applet that uses the good old script srcfoojsscript method of embedding a java applet were unable to cover our ears and sing la la la anymore it is time to be usingdeployjavarunappletwhen i fire this method using a click handler here using an event listener on a button via jquery but it does not matterbuttonclickfunction deployjavarunappletattributes parameters versionit wipes out the entire existing document and replaces it with the applet all i need to know is how to target a specific dom element to be the container for the applet so that my page does not get wiped it seems like it would be an attribute i could pass in the form of target someelement where someelement is either a dom object or the elements id as a string but alas i cannot find documentation for such an attributefor the sake of being complete heres whats being passedhere is where i imagine there might be an applicable attribute var attributes name somename code someclass archive somejar width 640 height 400var parameters someparameter somevaluevar version 15i can documentwrite everything i need to rebuild a document but i am sure you can all well imagine how hideous that prospect seems to meany pointers would be greatly appreciated,"['java', 'javascript', 'css']" +380510,mysql 5524 duplicate entry on update when there is no real duplicate i have to update a table with the following structurecreate table eav entity attribute entity attribute id int10 unsigned not null auto increment comment entity attribute id entity type id smallint5 unsigned not null default 0 comment entity type id attribute set id smallint5 unsigned not null default 0 comment attribute set id attribute group id smallint5 unsigned not null default 0 comment attribute group id attribute id smallint5 unsigned not null default 0 comment attribute id sort order smallint6 not null default 0 comment sort order primary key entity attribute id unique key unq eav entity attribute attribute set id attribute id attribute set idattribute id unique key unq eav entity attribute attribute group id attribute id attribute group idattribute id key idx eav entity attribute attribute set id sort order attribute set idsort order key idx eav entity attribute attribute id attribute id engineinnodb default charsetutf8 commenteav entity attributesabove table contains a single rowinsert into eav entity attributeentity attribute id entity type id attribute set id attribute group id attribute id sort ordervalues32758 4 224 3423 5171 12i am running an automatic import procedure which will read an external source of data and write into this table this import runs multiple times and therefore sometimes the same data is imported several times in such case the procedure simply overwrites the old data with the new one even when the new one is identical to the old the condition where the same data exists is handled with an on duplicate key update clause this works almost perfectly except on this specific table on this table when the procedure attempts an update i receive a duplicate key message which i cannot explain i debugged the code and this is the query that fails extracted from the inserton duplicate keyupdate eav entity attributeset attribute group id 3423 attribute id 5171 attribute set id 223 entity type id 4 sort order 320where attribute group id 3423 and attribute id 5171the error is the followingerror code 1062 duplicate entry 34235171 for key unq eav entity attribute attribute group id attribute idi know that the pair 34235171 already exists but the update would replace these values with themselves not create a new entry i am quite confused about the cause of this issue any suggestion would be very welcome thanksupdate new findingi got some sort of inspiration and i made an experiment i removed the unique constraint involving on attribute set idattribute id note this is not the one in the error and i ran the inserton duplicate query it worked perfectlymine is a conjecture but this is what i think the data i am trying to write to the table clashes with two constraints uniqueattribute set idattribute iduniqueattribute group idattribute idthe insert fails presumably because of the duplication error raised by the first constraint this triggers the update which uses the first constraint as the implicit where clause my speculation is that in such case the first constraint is somehow ignored but the update trips over the second which did not get involved earlierthis still does not seem to me a valid reason for an update which replaces something with itself to raise a duplicate entry error but it may shed some light on the logic behind itsecond update i found out that the table i was testing against actually contains a lot of rows i forgot to thisable the filtered view resulting from the successful import of other data however the duplicate candidate is still unique in the seti confirm what posted in the comments when the table contains only that rows the inserton duplicate works as well as the update alone now i am wondering why does the table get messed up when there is more data in it since we are still talking about a single unique row being updated with the same datathird update found the root causei finally found out the reason why the update fails now i have to find out how do i get in such condition the clue was my conjecture in the first update simply i have two very similar rows please note i am using different values as i started from a clean databaserowentity attribute identity type idattribute set idattribute group idattribute idsort order116919 4 120 1746 80 1216649 4 119 1744 80 210heres what happensthe insert attempts to insert a row with the following values 120 4 1744 80 54this triggers the duplicate key since the values 120 80 are a duplicate for the fields attribute set id attribute id row 1mysql then tries the update which becomes as followsupdate tableentity type id 4attribute group id 1744sort order 54where attribute set id 120 and attribute id 80this time the update fails because the values 174480 are violate the constraint on the pair attribute group id attribute id found in row 2in summary the insert fails because row 1 has the same values for the key attribute set id attribute idthe update fails because row 2 has the same values for the key attribute group id attribute idsolutioni will have to review the whole import procedure as in theory none of such duplicates should arise mysql is doing its job fine it is the database that is complicatedthanks for all the suggestions,['mysql'] +380514,python dijkstra k shortest paths i am trying to make a small public transport routing applicationmy data is represented in a following structuregraph a b3 c5 b c2 d2 c d1 d c3 e f8 f c2wheregraph dict key is a nodesubdict key is an edge between 2 nodessubdict value is an edge weighti was using find shortest path algorithm described here but it is rather slow because of recursion and has no support of weightsso i moved to the algorithm described by davide epstein here and even better implementation could be find there in comments with the usage of heapqit works great it is really fast but i get only the best route instead of the list of all possible routes and that is where i stuckcould somebody help me with that please or at least give a direction i am not very good in graph shortest paths algorithms thanks in advance,['python'] +380520,android singleton which is used between activity and service im wondering if it would be a bad idea to create a singleton that is used between some android activities and a android service as far as i know the static fields in my case the singleton is available as long as the whole process is alive my plan is to use a singleton instead of parcelable to share data between my activities and a background service so my activity1 will add some data by calling mysingletongetinstanceadatafoo then i would sent an intent to inform my service that new data has been added to the singleton next my backgroundservice would handle the intent and call mysingletongetinstancegetlatestdata then it would process the data takes some time the result of the service would next be post back by using the singleton and fire a broadcast intent which are handled by the activity1 if alive and the activity1 will retrieve the result from the singletondo you guys think thats a bad ideaeditwhat i want to implement is an peace of software that downloads data from a web server parse it and return the result so my activity would create downloadjob object the downloadjobobject would be put into the downloadscheduler singleton which queues and manage all downloadjobs the downloadscheduler would allow to run 5 downloadjobs at the same time and use a queue to store the waiting the effective download would be done by the downloadservice intentservice which gets informed over an intent that the a new downloadjob should now be executed downloaded right now the dowanlodservice would retrieve the next job from the downloadschedulers queue priorityblockingqueue and return the result by setting downloadjobsetresult and fires up an broadcast intent that the result is ready which will be received by the downloadscheduler which would remve the job from the queue and inform the activity that the download is complete etcso in my scenario i would use the singleton to access the downloadjobs from the downloadservice instead of making a downloadjob parcelable and pass it with the intent so i would avoid the problem that i have two downloadjobs in memory one on the activity site and one on service siteany suggestions how to solve this betteris it true that static instances like downloadschedulersingleton would be used by freed by the android system on low memory so would subclassing the application and hold there the reference non static avoid this problem,['android'] +380533,purgeidlecellconnections about the duplicate state of this questionthis question here was asked in nov 2012 it contains a detailed description of the problem and has 3 answersthe question referred to as original was asked in feb 2013 3 month after this duplicate has no detailed description and only 2 answers the best of its two answers is just a linkonlyanswerwhy do i get this message in my consolepurgeidlecellconnections found one to purge conn some objectidwhen my app starts i send a message to my server i do this with this lines of codeimplementation appstatus nsmutabledata activedownload nsurlconnection connection id init self super init if self activedownload nil connection nil return self voidsendstatusnsstringurl nsstring escaped url stringbyaddingpercentescapesusingencodingnsutf8stringencoding nsurlconnection conn nsurlconnection alloc initwithrequestnsurlrequest requestwithurlnsurl urlwithstringescaped delegateself connection conn nslogs connection pretty function connectionin the same file i have this delegatemethods voidconnectionnsurlconnectionconnection didreceivedatansdatadata nslogs connection pretty function connection activedownload appenddatadata voidconnectionnsurlconnectionconnection didfailwitherrornserrorerror nslogs connection pretty function connection activedownload nil connection nil do nothing else just ignore the error voidconnectiondidfinishloadingnsurlconnectionconnection nslogs connection pretty function connection nsstring answer nsstring alloc initwithdataactivedownload encodingnsutf8stringencoding do something usefull with the servers answer activedownload nil connection nilwhen i run this app on a real device not on the simulator i get this messages in the console20121122 204151309 bookman376907 appstatus sendstatus connectionnsurlconnection 0x1dd7ff4020121122 204151929 bookman376907 appstatus connectiondidreceivedata connectionnsurlconnection 0x1dd7ff4020121122 204151935 bookman376907 appstatus connectiondidfinishloading connectionnsurlconnection 0x1dd7ff40purgeidlecellconnections found one to purge conn 0x1dd8ff60the purgeidlecellconnectionsmessage apears about 4 or 5 seconds after the connectiondidfinishloadingmessage as you can see the objectnumber of the purgeidlecellconnectionsmessage is not the same as the number of the connection i did create and use in my appmaybe important i do get this message only when i run the app on a real device iphone 4 with ios 601 this device uses a 3gconnection not a wificonnection at the moment i have no wifinetwork to test if this happens on a wificonnection tooi do not get this message when i run the app on the simulator when i change the method sendstatus to this voidsendstatusnsstringurl nsstring escaped url stringbyaddingpercentescapesusingencodingnsutf8stringencoding nsurlconnection conn nsurlconnection alloc initwithrequestnsurlrequest requestwithurlnsurl urlwithstringescaped delegateself connection conn nslogs connection pretty function connectioni get this output in the console20121122 204511927 bookman391907 appstatus sendstatus connectionnulli do not get the purgeidlecellconnectionsmessage when i do not create a connectionso what does this message mean and why do i get itpurgeidlecellconnections found one to purge conn some objectid,['ios'] +380538,action bar icon size in android 42 has the action bar icon size changed in android 42 i have had a 120x48px hdpi icon that was rendered perfectly in android 41 and below it still ishowever on any 42 device it is squelched to fit as 48x48px from what i can see or something like that it is definitely a squareany ideas thanks,['android'] +380576,what are the rules for function pointers and member function pointers to standard functions what are the existing rules for taking function pointers or member function pointers to standard functions for example something likeauto p stdstringsizeis this legal would it be more or less legal if i explicitly requested the correct type so it would function even if there was an additional implementationadded overload of stdstringsize,['c++'] +380629,how to add additional xmlns namespace attributes to xml in javascript i am a little bit stuck trying to attach multiple namespaces to an xml element via javascript across browsers i have tried about a dozen different ways to no avail i am usually using plain old javascript but for the sake of keeping this example short this is how what i am doing would be done via jqueryvar soapenvelope soapenvenvelope xmlnssoapenvsoapenvenvelopevar jxml jqueryparsexmlsoapenvelopejxmldocumentelementattrxmlnsxsd in both chrome and ff this works as expected giving a result like thissoapenvenvelope xmlnssoapenv xmlnsxsd but in ie9 i get a result like thissoapenvenvelope xmlnssoapenv xmlnsns1 ns1xmlnsxsdand i cannot find a way to add this namespace attribute without ie9 adding this ns1 prefix to my namespaces also if i try passing this result back into parsexmlresult i get a malformed xml exceptionam i misunderstanding something to do with the way namespaces are declared in ie or can anyone suggest a way i can get a consistent result across browsersthanks in advance,"['javascript', 'jquery']" +380637,html5 time inputs shows 12 hours i am using html 5 input element with typetime the problem is it shows time with 12 hours but i want it to show it in 24 hours a day how can i make it to 24 hours here is my input fieldinput typetime nametime placeholderhrsmins pattern010920405090509 classinputs time requireddemohere is jsfiddle,['html'] +380638,python complex dictionary keys my question pertains to dictionary keys i want to set up a dictionary that has 3 keys for any single object the keys must be in order and can have a wide range of values for instancedictionary key1key2key3 objectkey1 can be any value between 1 and 10key2 can be any value between 11 and 20key3 can be any value between 21 and 30the order in which the keys are placed does mattermore specifically my keys correspond to a range of xyz cartesian coordinates in which many objects are floating around in i want to be able to sort the relative position of the objects based off their xyz positionsis there any way to set this up or will i have to take a different approachthanks for any help,['python'] +380659,how can i throw an exception from xslt i want to throw an exception if one tag does not contain an attribute,['java'] +380693,log in with facebook in ios6 unrecognized selector sent to instance i am getting the following error when i am working with facebook loginyes it is a basic mistake unrecognized selector sent to instance but i did not get where the mistake is uistatusbar orientation unrecognized selector sent to instance 0xa9a9c0020121123 1546854 tattoo later12651cd03 terminating app due to uncaught exception nsinvalidargumentexception reason uistatusbar orientation unrecognized selector sent to instance 0xa9a9c00in this method voidlogintofacebookid logindelegatefbservicerequestingobj logindelegate nsarray permissions nsarray alloc initwithobjects publish streamuser birthdayread streamuser about meoffline accessemailread mailboxuser about menil facebook authorizepermissions delegateselfapp crashes in this line facebook authorizepermissions delegateselfin my project i intergrated gpuimage i am working on ios6thanks in advance,"['iphone', 'objective-c', 'ios']" +380696,dojostoreobservable json rest and queryengine does anybody know how to use the jsonrest store in dojo witn an observable weapper like the one in dojostoreobservablewhat do i need server side to implement the store and make it work as an observable one what about the client side the documentation says if you are using a server side store like the jsonrest store you will need to provide a queryengine in order for the update objects to be properly included or excluded from queries if a queryengine is not available observe listener will be called with an undefined indexbut i have no idea what they mean i have never created a store myself and am not 100 familiar with queryengine to be honest i find it a little confusing why is queryengine needed what does the doc mean by undefined index and how do you write a queryengine for a jsonrest store should not i use some kind of web socket for an observable rest store since other users might change the data as wellconfused,['javascript'] +380703,how to solve the typeerror arraysplice is not a function when var array possible duplicatehow to remove a property from a javascript objectjavascript hashmap equivalent i am using jquery and i am handling a variable this wayvar array arrayan object somethingarrayanother object something elsearray when i try to run the splice method on the array i get a typeerror arraysplice is not a function my intent is to remove the an object key and all its content from the array variablehow can i make that note when i run the consolelogarrayan object the same is valid for another object and all other objects i getobject labelstr1 value1 object labelstr2 value2 labelstrn valuen,"['javascript', 'jquery']" +380796,ie 9 highcharts do not render series hello i have a problem with highcharts under ie 9internet explorer highcharts screenshothighcharts works fine in other browsers screenshotas you can see the chart is rendered in ie and in chrome butthe lines are rendered just in the chrome the data has to be there also for ie because legend box is there best bid qualification value the codeby the way it is erb template so i load data from railsscript typetextjavascript use strict var chart assign data for current and qualification values var qualificationtranslation tqualification value nobr var currenttranslation tevent current value var qualificationvalue lotqualification value var currentvalue lotcurrent value jquerydocumentreadyfunction var parsechartdata functiondata var chartdata jqueryeachdata functionindex value chartdatapush x dateparsevaluex y parsefloatvaluey formated value valueformated value return chartdata var dataforchart parsechartdata raw datachart datato json chart new highchartschart chart renderto chart type line zoomtype x marginright 25 credits enabled false title text ttotal difference progression chart x 20 center xaxis type datetime labels formatter function return highchartsdateformatim p thisvalue yaxis title text tbid value price per uom x quantity symbol loteventcurrencysymbol tooltip formatter function var seriename thispointseriesname do not show tooltip when you hover over qualification or current price ifseriename qualificationtranslation seriename currenttranslation return false else return b thisseriesname bbr highchartsdateformatd b ims p thisx brb thispointformated value b legend backgroundcolor f verticalalign top y 20 shadow true plotoptions series step true series name tbest bid data dataforchart this function will add the current price and qualification price lines var addorupdateserie functionname value serie var data datapushchartxaxis0min value datapushchartxaxis0max value var options name name type spline dashstyle shortdot marker enabled false data data ifserie chartaddseriesoptions else seriesetdatadata addorupdateseriequalificationtranslation qualificationvalue addorupdateseriecurrenttranslation currentvalue socket ioconnect ioserveraddr charts query lot id lotid secure isproduction socketonconnect function socketemitjoin host difference progression event chart socketon lotid host difference progression event chart functiondata add data to series chartseries0setdataparsechartdatadatachart data update hirizontal values addorupdateseriequalificationtranslation qualificationvalue chartseries1 addorupdateseriecurrenttranslation currentvalue chartseries2 chartredraw scriptedit it raises no errorsolvedthe problem was with dateparse because ie uses other format solved the problem,['javascript'] +380806,is nullablegethashcode a poor hash code function the implementation of nullabletgethashcode is as followspublic override int gethashcode if thishasvalue return 0 return thisvaluegethashcodeif however the underlying value also generates a hash code of 0 eg a bool set to false or an int32 set to 0 then we have two commonly occurring different object states with the same hash code it seems to me that a better implementation would have been something likepublic override int gethashcode if thishasvalue return 0xd523648a eg some arbitrary 32 bit int with a good mix of set and unset bits also probably a prime number return thisvaluegethashcode,"['c#', '.net']" +380811,inject array of strings to a bean in spring xml version10 encodingutf8beans xmlns xmlnsxsi xsischemalocation http wspringframeworkorgschemabeansspringbeansxsd bean idtest classcomtest constructorarg list valueaavalue valuebbvalue valueccvalue list constructorarg beanbeansthis is my current xmlif only test took a list everything would be finethe problem is that test takes an array of stringshow to do it in spring,['java'] +380816,alternative for collectionsnewsetfrommap to be used in jdk 15 i want to use such collectionsnewsetfrommap method in jdk 15 which doesnt support italso concurrenthashset class is not supported in java 5have to compile following line in jdk 15how do i do it protected setstring knownlcwords collectionsnewsetfrommapnew concurrenthashmapstring booleanplease guide me,['java'] +380818,punch a hole in a rectangle overlay with hw acceleration enabled on view i have a view which does some basic drawing after this i want to draw a rectangle with a hole punched in so that only a region of the previous drawing is visible and i would like to do this with hardware acceleration enabled for my view for best performancecurrently i have two methods that work but only works when thisabled hardware acceleration and the other is too slowmethod 1 sw acceleration slowfinal int savecount canvassave clip out a circlecircleresetcircleaddcirclecx cy radius pathdirectioncwcircleclosecanvasclippathcircle regionopdifference draw the rectangle colorcanvasdrawcolorbackcolorcanvasrestoretocountsavecountthis does not work with hardware acceleration enabled for the view because canvasclippath is not supported in this mode i know i can force sw rendering but i would like to avoid thatmethod 2 hw acceleration v slow create a new canvasfinal bitmap b bitmapcreatebitmapgetwidth getheight bitmapconfigargb 8final canvas c new canvasb draw the rectangle colourcdrawcolorbackcolor erase a circlecdrawcirclecx cy radius eraser draw the bitmap on our views canvascanvasdrawbitmapb 0 0 nullwhere eraser is created aseraser new painterasersetcolor0xferasersetxfermodenew porterduffxfermodeporterduffmodeclearthis is obviously slow a new bitmap the size of the view is created every drawing callmethod 3 hw acceleration fast does not work on some devicescanvasdrawcolorbackcolorcanvasdrawcirclecx cy radius erasersame as the hw acceleration compatible method but no extra canvas required there is a major problem with this though it works with sw rendering forced but on the htc one x android 404 and probably some other devices at least with hw rendering enabled it leaves the circle completely black this is probably related to 22361method 4 hw acceleration acceptable works on all devicesas per jans suggestion for improving method 2 i avoided creating the bitmap in each call to ondraw instead doing so in onsizechangedif w oldw h oldh b bitmapcreatebitmapw h bitmapconfigargb 8 c new canvasband then just used these in ondrawif overlaybitmap null b bitmapcreatebitmapgetwidth getheight bitmapconfigargb 8 c new canvasbberasecolorcolortransparentcdrawcolorbackcolorcdrawcirclecx cy radius erasercanvasdrawbitmapb 0 0 nullthe performance is not as good as method 3 but much better than 2 and slightly better than 1the questionhow can i achieve the same effect but do so in a manner compatible with hw acceleration and that works consistently on devices a method which increases the sw rendering performance would also be acceptablenb when moving the circle around i am just invalidating a region not the entire canvas so there is no room for a performance improvement there,['android'] +380904,how to convert a column of type text to varchar is there a way to convert a column with data in it as text to varcharx easily there are no existing records in the column is longer than x,['mysql'] +380945,join 2 children tables with a parent tables without duplicated problemi have 3 tables people phones and emails each person has an unique id and each person can have multiple numbers or multiple emailssimplified it looks like this id name 503 amy 504 george 505 john 508 steven 809 ashley id number 505 51234 505 5154324 508 2487312 809 7134584 508 8451384 id email 505 505 508 508 508 809 504 i am trying to joining them together without duplicates it works great when i try to join only emails with people or only phones with peopleselect peoplename peopleid phonesnumber from people left outer join phones on peopleidphonesid order by name id number name id number steven 508 8451384 steven 508 24887312 john 505 51234 john 505 5154324 george 504 null ashley 809 7134584 amy 503 null select peoplename peopleid emailsemail from people left outer join emails on peopleidemailsid order by name id email name id email steven 508 steven 508 steven 508 john 505 john 505 george 504 ashley 809 amy 503 null however when i try to join emails and phones on people i get thisselect peoplename peopleid phonesnumber emailsemail from people left outer join phones on peopleid phonesid left outer join emails on peopleid emailsid order by name id number email name id number email steven 508 8451384 steven 508 8451384 steven 508 8451384 steven 508 24887312 steven 508 24887312 steven 508 24887312 john 505 51234 john 505 51234 john 505 5154324 john 505 5154324 george 504 null ashley 809 7134584 amy 503 null null what happens is if a person has 2 numbers all his emails are shown twice they can not be sorted which means they can not be removed by lastwhat i wantbottom line playing with the last i want to end up with somethig like this but last would not work if i do not arrange order columns in the righ way and this seems like a big problemorderin the email column because seen from the example abovesteven has 2 phone number and 3 emails the join emails with numbers happens with each email thus duplicated values that can not be sorted sort by does not work on themthis is what i want name id number email steven 508 8451384 24887312 john 505 51234 5154324 george 504 null ashley 809 7134584 amy 503 null null now i am told that it is best to keep emails and number in separated tables because one can have many emails so if it is such a common thing to do what is not there a simple solutioni would be happy with a php solution aswellwhat i know how to do by now that satisfies it but is not as prettyif i do it with group contact i geat a satisfactory result but it does not look as pretty i cannot put a email type work next to it select peopleime group concatthistinct phonesnumber group concatthistinct emailsemail from people left outer join phones on peopleidphonesid left outer join emails on peopleidemailsid group by name name group concatthistinct phonesnumber group concatthistinct emailsemail steven 845138424887312 john 512345154324 george null ashley 7134584 amy null null,"['php', 'mysql']" +380962,unable to calculate position within ownerdraw text i am trying to use visual studio 2012 to create a windows forms application that can place the caret at the current position within a ownerdrawn string however i have been unable to find a way to accurately calculate that positioni have done this successfully before in c i have tried numerous methods in c but have not yet been able to position the caret accurately originally i tried using net classes to determine the correct position but then i tried accessing the windows api directly in some cases i came close but after some time i still cannot place the caret accuratelyi have created a small test program and posted key parts below i have also posted the entire project herethe exact font used is not important to me however my application assumes a monospaced font any help is appreciatedform1csthis is my main formpublic partial class form1 form private string teststring private int avecharwidth private int position public form1 initializecomponent teststring 123456789012345678901234567890123456789012345678901234567890 avecharwidth getfontwidth position 0 private void form1 loadobject sender eventargs e font new fontfontfamilygenericmonospace 12 fontstyleregular graphicsunitpixel protected override void ongotfocuseventargs e windowscreatecarethandle intptr0 2 intfontheight windowsshowcarethandle updatecaretposition baseongotfocuse protected void updatecaretposition windowssetcaretpospaddingleft position avecharwidth paddingtop protected override void onlostfocuseventargs e windowshidecarethandle windowsdestroycaret baseonlostfocuse protected override void onpaintpainteventargs e egraphicsdrawstringteststring font systembrusheswindowtext new pointfpaddingleft paddingtop protected override bool isinputkeykeys keydata switch keydata case keysright case keysleft return true return baseisinputkeykeydata protected override void onkeydownkeyeventargs e switch ekeycode case keysleft position mathmaxposition 1 0 updatecaretposition break case keysright position mathminposition 1 teststringlength updatecaretposition break baseonkeydowne protected int getfontwidth int averagecharwidth 0 using var graphics thiscreategraphics try windowstextmetric tm var hdc graphicsgethdc intptr hfont thisfonttohfont intptr holdfont windowsselectobjecthdc hfont var a windowsgettextmetricshdc out tm var b windowsselectobjecthdc holdfont var c windowsdeleteobjecthfont averagecharwidth tmtmavecharwidth catch finally graphicsreleasehdc return averagecharwidth windowscshere are my windows api declarationspublic static class windows serializable structlayoutlayoutkindsequential charset charsetauto public struct textmetric public int tmheight public int tmascent public int tmdescent public int tminternalleading public int tmexternalleading public int tmavecharwidth public int tmmaxcharwidth public int tmweight public int tmoverhang public int tmdigitizedaspectx public int tmdigitizedaspecty public short tmfirstchar public short tmlastchar public short tmdefaultchar public short tmbreakchar public byte tmitalic public byte tmunderlined public byte tmstruckout public byte tmpitchandfamily public byte tmcharset dllimportuser32dll public static extern bool createcaretintptr hwnd intptr hbitmap int nwidth int nheight dllimportuser32dll public static extern bool setcaretposint x int y dllimportuser32dll public static extern bool destroycaret dllimportuser32dll public static extern bool showcaretintptr hwnd dllimportuser32dll public static extern bool hidecaretintptr hwnd dllimportgdi32dll charset charsetauto public static extern bool gettextmetricsintptr hdc out textmetric lptm dllimportgdi32dll public static extern intptr selectobjectintptr hdc intptr hgdiobj dllimportgdi32dll public static extern bool deleteobjectintptr hobjecteditthe code i have posted has an issue that makes it even more inaccurate this is a result of trying many different approaches some more accurate than this what i am looking for is a fix that makes it fully accurate as it is in my mfc hex editor control in c,['c#'] +380985,java generics compile in eclipse but not in javac i had to thiscover i have java code in my project which compiles and runs fine in eclipse but throws a compilation error in javaca selfcontained snippetimport javautilhashsetimport javautilsetpublic class main public static void mainstring args setinteger setofints new hashsetinteger setobject setofobjects covariantsetsetofints public static s t extends s sets covariantsetsett set return new hashsetsset compilation in javac returnsmainjava10 incompatible typesfound javautilsetjavalangintegerrequired javautilsetjavalangobject setobject setofobjects covariantsetsetofints this error now prevents building the project in maven as the eclipse compiler is built to be more tolerant i now have to assume the definition and usage of snippets as above static method is no valid java,['java'] +380988,can a scheduled future cause a memory leak i think i have a memory leak in my android live wallpaper whenever i rotate the screen the amount of memory garbage collected increases by 50kb and does not go back down i think it may be caused by a scheduled future so i am going to present a scenario to see if that is the caselet us say you have a class let us call it foo that has the following membersprivate scheduledfuture futureprivate final scheduledexecutorservice scheduler executors newsinglethreadscheduledexecutorprivate final runnable runnable new runnable public void run do stuff and now you set a scheduled futurefuture schedulerscheduleatfixedraterunnable delay speed timeunitmillisecondsthe future holds a reference to the runnable and the runnable holds a reference to the parent foo object i am not sure if this is the case but could this fact mean that if nothing in the program holds a reference to foo the garbage collector still cannot collect it because there is a scheduled future i am not too good at multithreading so i do not know if the code i have shown means the scheduled task will live longer than the object meaning it would not end up being garbage collectedif this scenario will not result in preventing foo from being garbage collection i just need to be told that with a simple explanation if it does prevent foo from being garbage collected then how do i fix it do have to do futurecanceltrue future null is the future null part unnecessary,"['java', 'android']" +381034,c vs f for programmatic wpf guis i am trying to decide where to draw the line on the use of f and c in enterprise software development f for mathematical code is a nobrainer i like f for gui work even though it lacks gui designer support but of course there is more resource availability of c gui people in industry however i am not too familiar with cxaml gui development so i am concerned about introducing biasin the case of one client they have dozens of similar guis that are quite static changed yearly and a few other guis that are very dynamic eg business rules engines they already have f code live and are already investing in f training so skills availability is not an issue my impression is that cxaml let you build static guis a few sliders a few text boxes etc easily but i cannot see how the gui designer would help with programmatic guis like a business rules engine am i right in thinking that maintaining a battery of mostlystatic guis eg adding a new field to 100 separate guis will require manual labor also am i right in thinking that the gui designer is of little use in the context of heavily programmatic guis so something like a business rules engine would be written primarily in cxaml with little use of the gui designer,['c#'] +381037,capture ratingbar click i seem to have a problem with catching my ratingbar click the ratings bar is showing up just fine and has the default value the only problem is that i cannot change any values or it is not enabled i have tried numerous different things eg enabling in the layout building it entirely in java none of them seem to have an impact here is my latest incarnation of the ratings bar i must be doing something stopid to not be able capture the clickjava code ratingbar showratingbar ratingbar findviewbyidridshowratingbar showratingbarsetenabledtrue showratingbarsetclickabletrue showratingbarsetrating0 showratingbarsetonratingbarchangelistenernew ratingbaronratingbarchangelistener override public void onratingchangedratingbar ratingbar float rating boolean fromuser systemoutprintlnshowratingbuildratingbar rating ratingbarsetratingrating showratingbarrefreshdrawablestatelayout linearlayout androidlayout widthmatch parent androidlayout heightwrap content textview androidididshowqualitylabel androidlayout width100dp androidlayout heightwrap content androidtextstringshow rating label androidtextappearanceandroidattrtextappearancemedium androidtextcolore6e6e6 androidtextsize12sp ratingbar androidididshowratingbar styleandroidattrratingbarstylesmall androidlayout widthwrap content androidlayout heightwrap content androidmax5 androidnumstars5 androidrating0 androidstepsize1 linearlayoutthank you in advancecraig,['android'] +381039,python debug tools for multiprocessing i have a python script that works with threads processes and connections to a databasewhen i run my script python crashesi cannot explicitly detect the case in which this happensnow i am looking for tools to get more information when python crashesor a viewer to see all my created processesconnections,['python'] +381052,adding line breaks in ipython if introduce a for loop in ipython or any multiline command how do i go back and add lines to it i ran thisfor row in tablefind alltr cells rowfind alltd for ccell in enumeratecells print ccellget textstrip try this cells0 that cells1 the docket cells2 other thign cells3 jumble resubs strcells5strip except nopeand realized i need to add a line to it but i cannot just hit enter in ipython bc that runs the command so can i edit that multiline command win ipython,['python'] +381102,keeping sqlite data after update i have an app that has an sqlite with 3 tables my concern is that if i introduce an update that adds another table so that is 4 tables then the updated version will wipe out the databasehow can i backuprestore db given that the backup happens before the update and the restore after the update if i do it using the io copy to sd card and copy back then it will faili am thinking probably of exporting data to xml and loading manually is there another way any example on how to do it,['android'] +381106,ruby split by whitespace how can i write a ruby function that splits the input by any kind of whitespace and remove all the whitespace from the result for example if the input is aa bcc dd eethen return an array aa b cc dd ee,['ruby'] +381110,error on using proguard with android facebook sdk 30 warning i removed a lot of old text to keep the question more clean just check the history if neededi am using proguard to both shrink and obfuscate an app that uses the facebook sdk 30 i am using the sdkversion302b tag i am not using a jar file instead i imported the sdk inside my workspace as taught by the documentationat a certain point in the execution the app loads a placepickerfragment to let the user choose the place where he is to code this i follow exactly the scrumptious tutorial when i generate the debug apk without using proguard everything works as expected but when i generate the signed apk using proguard it crashes when the placepickerfragment loads nearby places with the following traceeandroidruntime27472 fatal exception maineandroidruntime27472 comfacebookfacebookgraphobjectexception cannot infer generic type of interface comfacebookmodelgraphobjectlisteandroidruntime27472 at comfacebookmodelgraphobjectfactorycoercevaluetoexpectedtypeunknown sourceeandroidruntime27472 at comfacebookmodelgraphobjectfactorygraphobjectproxyproxygraphobjectgettersandsettersunknown sourceeandroidruntime27472 at comfacebookmodelgraphobjectfactorygraphobjectproxyinvokeunknown sourceeandroidruntime27472 at comfacebookwidgetproxy2getdatanative methodeandroidruntime27472 at comfacebookwidgetgraphobjectpagingloaderaddresultsunknown sourceeandroidruntime27472 at comfacebookwidgetgraphobjectpagingloaderrequestcompletedunknown sourceeandroidruntime27472 at comfacebookwidgetgraphobjectpagingloaderaccess1unknown sourceeandroidruntime27472 at comfacebookwidgetgraphobjectpagingloader2oncompletedunknown sourceeandroidruntime27472 at comfacebookrequest4rununknown sourceeandroidruntime27472 at androidoshandlerhandlecallbackhandlerjava587eandroidruntime27472 at androidoshandlerthispatchmessagehandlerjava92eandroidruntime27472 at androidoslooperlooplooperjava130eandroidruntime27472 at androidappactivitythreadmainactivitythreadjava3687eandroidruntime27472 at javalangreflectmethodinvokenativenative methodeandroidruntime27472 at javalangreflectmethodinvokemethodjava507eandroidruntime27472 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava867eandroidruntime27472 at comandroidinternaloszygoteinitmainzygoteinitjava625eandroidruntime27472 at dalviksystemnativestartmainnative methodtrying to avoid this error i kept all facebook classes untouched but did not work my current proguardprojecttxt filekeep class comfacebook my current projetproperties file excerptproguardconfigsdkdirtoolsproguardproguardandroidtxtproguardprojecttxtas you can see my proguard configuration is a specialization of this fileif i put dontobfuscate in proguardprojecttxt file it will work but what i do not understand is that the keep class comfacebook should already prevent classes related to facebook to be obfuscated which suggests that the problem is not directly related to the facebook classesthe excerpt of code that throws comfacebookfacebookgraphobjectexception isstatic u you coercevaluetoexpectedtypeobject value classu expectedtype parameterizedtype expectedtypeasparameterizedtype else if iterableclassequalsexpectedtype collectionclassequalsexpectedtype listclassequalsexpectedtype graphobjectlistclassequalsexpectedtype if expectedtypeasparameterizedtype null throw new facebookgraphobjectexceptioncannot infer generic type of expectedtypetostring clearly expectedtypeasparameterizedtype is null in release build but in both builds debug and release expectedtype is a comfacebookmodelgraphobjectlist interface unfortunately i do not understand almost nothing about java reflection conceptshow can i fix this problem,['android'] +381114,hardcode string vs string in java code android i am just wondering what the benefitsoverheads are for using string rather than hard coding strings within the actual java code for example to get the string resourcegetactivitysettitlegetstringrstringmy stringis this the best practice for things like actionbar titles dynamically created button text ect or should i just do this hardcoded stringgetactivitysettitlemy stringi know there will be a bit more overhead doing it the first way just not sure what best practice is,['android'] +381165,android pick activity text color i have a problem with pick activity i have this popup text color is white and background toothis is code i use bundle bundle new bundle arrayliststring shortcutnames new arrayliststring shortcutnamesaddgetstringrstringgroup applications bundleputstringarraylistintentextra shortcut name shortcutnames arraylistshortcuticonresource shortcuticons new arraylistshortcuticonresource shortcuticonsaddshortcuticonresourcefromcontextthis rdrawableic launcher bundleputparcelablearraylistintentextra shortcut icon resource shortcuticons intent pickintent new intentintentaction pick activity pickintentputextraintentextra intent new intentintentaction create shortcut pickintentputextraintentextra title gettextrstringapp name pickintentputextrasbundle startactivityforresultpickintent 1,['android'] +381174,zf2 autoloader classmap fatal error map file provided does not exist i just started learning zend framework but i am having problem with my modulesplease see the below error i do not know what else to show you yet for further infomationplease let me know what i need to show you to solve the problem fatal error uncaught exception zendloaderexceptioninvalidargumentexceptionfatal error uncaught exceptionzendloaderexceptioninvalidargumentexception with message mapfile provided does not exist map file cprogramfilesxampphtdocszend intromodulealbumautoload classmapphp incprogramfilesxampphtdocszend introvendorzendframeworkzendframeworklibraryzendloaderclassmapautoloaderphp175stack trace 0 cprogramfilesxampphtdocszend introvendorzendframeworkzendframeworklibraryzendloaderclassmapautoloaderphp85zendloaderclassmapautoloaderloadmapfromfilecprogram file 1 cprogram filesxampphtdocszend introvendorzendframeworkzendframeworklibraryzendloaderclassmapautoloaderphp121zendloaderclassmapautoloaderregisterautoloadmapcprogramfile 2 cprogramfilesxampphtdocszend introvendorzendframeworkzendframeworklibraryzendloaderclassmapautoloaderphp64zendloaderclassmapautoloaderregisterautoloadmapsarray 3cprogramfilesxampphtdocszend introvendorzendframeworkzendframeworklibraryzendloin cprogramfilesxampphtdocszend introvendorzendframeworkzendframeworklibraryzendloaderclassmapautoloaderphpon line 175,['php'] +381189,why does it seem like operations are not being performed in the order of the code heres some background i am working on game similar to collapse blocks fill up at the bottom and when all twelve blocks have been filled they push up on to the playfield i have a counter called intnextspawn that not only tells when to push up the next row as well as calculating vectors for the graphics it resets to 0 when the blocks have been pushed upi have added some debug text on the screen to try and see what is happening but i cannot seem to hunt down the issue it almost seems like it is still incrementing the counter while trying to randomize the the block that is supposed to appear things acting out of order i end up getting blank blocks and it causes some really screwy effects while testing it gets worse when jack up the speedi am willing to post any additional code that might help below are the two main blocks where this is could happening is there something i might be doing wrong or may there be a way i can prevent this from happening if that is what it is doingany help would be greatly appreciatededit the first code block is in the update method calculate time between spawning bricksfloat spawntick fltspawnspeed fltspawnspeedmodifierfltspawn elapsedif fltspawn spawntick fetch a new random block ponextlayerintnextspawn randomspawn increment counter intnextspawn max index reached if intnextspawn 12 push the line up returns true if lines go over the top if pushline gmstatenew gamestategameover gmstateold gamestateplaying game still in play else reset spawn row to empty bricks for int i 0 i 12 i ponextlayeri new playobjectobjecttypebrick playcolorneutral vector2zero intnextspawn 0 reset spawn counter intlines one less line to go fltspawn spawntickprivate bool pushline go through the playfield top down for int y 14 y 0 y and left to right for int x 0 x 12 x top row contains an active block gameover if y 14 poplayfieldx yactive stop here return true else not bottom row if y 0 copy from block below poplayfieldx y poplayfieldx y 1 move drawing position up 32px poplayfieldx ymoveup bottom row else copy from spawning row poplayfieldx y ponextlayerx move drawing position up 32px plus 4 more poplayfieldx ymoveup4 make the block active clickable poplayfieldx yactive true game still in play return false,['c#'] +381196,jquery ajax and the when function i have some lets say 5 ajax requests that i run at the same time by using jqueryajax functionnow i would like to synchronize and aggregate their results and i used jquerywhen function to achieve thismy problem is that when returns as soon as one of the requests failed and prevent the others to return even if they succeedhow can i sycnhronize and get all the results from all my ajax requests those that failed and those that succeed,['jquery'] +381233,why for i 01 i 10 i 01 does not break at i 10 i had an exam today in c and i was asked a question similar towhat is wrong with this programfor x 1 x 10 x 1 printffn xi could not solve it and since i had to write something i marked 1 as an error but when i went back home i run this program it turned out that it does not break when x equals to 10 and stuck in an infinite loop cat examcinclude stdiohint mainint argc char argv float x forx 1 x 10 x 1 printffn x return 0 gcc examc o exam exam010203040506070809010 110120130140150could someone please explain why this is happening,['c'] +381301,dependency reference issues in vs2012 on windows 8 i have got a solution with several projects many of which reference apache is log4net i am currently trying to build just one of these projects a class library to resolve a reference issue i am having but no luck yet the warnings and errors only occur when building in vs2012 on windows 8 and not in vs2010 on windows 7anyone have any ideas how i might resolve this heres the warning messagesthe primary reference log4net could not be resolved because it was built against the netframeworkversionv401profileclient framework this is a higher version than the currently targeted framework netframeworkversionv40profileclientand heres the error messagesthe type or namespace name log4net could not be found are you missing a using directive or an assembly reference cusersrunedocumentsteam foundation servernoodinyggdrasilodinlibcommoncsthe type or namespace name ilog could not be found are you missing a using directive or an assembly reference cusersrunedocumentsteam foundation servernoodinyggdrasilodinlibcommoncsi am ignoring the errors right now as they are a result of the log4net reference not loadingthe reference is included in my csproj file like thisreference includelog4nethintpathdependencieslog4netdllhintpathreferenceas such the problems is really the warning i am getting since it seems to find my log4netdll file in my dependencies folder any one know how i might solve that please do ask if you need more information,"['c#', '.net']" +381320,c how does the try catch finally block work in c how does a try catch finally block workso if there is an exception i know that it will jump to the catch block and then jump to the finally block but what if there is no error the catch block wont get run but does the finally block get run then,['c#'] +381361,valgrind invalid read of size 4 sigsegv works fine without valgrind and in visual studio i have implemented a compression algorithm using huffman coding which uses a priority queue of nodes a struct i defined now when i just run the code in linux or in visual studio everything works fine when i check for memory leaks in visual studio none are given the problem now is when i use valgrind to analyse my program it terminates with signal 11 sigsegv the first error encountered is an invalid read of size 4 in the method delete min other errors after that are adress is 0 bytes inside a block of size 453 freed invalid write of size 4 invalid freedelete or realloccan anyone give me advice about what kind of error i possibly could have made i have been searching the internet for hours but cannot find what i am doing wrong especially since it just works when not using valgrind or tips how to debug and find out whats causing the read errormany thankshere is the code in case somebody would want to review it but i guess that is not that easy to just dive in this specific codei am guessing it has something to do with the priority queue of the codethe part where i do the huffman part every time delete the 2 minimal nodes and add the sum of both back as one nodewhilequeuesize 1 node n1 delete minqueue node n2 delete minqueue all the errors are encountered in this call node temp node callocsizeofnode1 tempamount n1amount n2amount insert nodequeuetemp n1parent temp n2parent temp templeft n1 tempright n2here is are the delete min and insert node methods for the priority queuevoid insert nodepriority queue p queue node x int i p queuesize ifi 0 p queuequeue node mallocsizeofnode else p queuequeue node reallocp queuequeuesizeofnodep queuesize1 p queuequeuep queuesize x whilei0 p queuequeueiamount p queuequeuei12amount node temp p queuequeuei p queuequeuei p queuequeuei12 p queuequeuei12 temp i i12 p queuesizenode delete minpriority queue p queue node queue p queuequeue node min queue0 ifp queuesize1 int r 0 int current 1 left child of root queue0 queuep queuesize1 queue node reallocqueuesizeofnodep queuesize whilecurrent p queuesize in case of 2 children check if current needs to be right or left child ifcurrent p queuesize1 queuecurrent queuecurrent1 current ifqueuecurrent queuer node temp queuer queuer queuecurrent queuecurrent temp r current current 2 current else break current else freequeue p queuesize return minedit added the valgrind outputinvalid read of size 41893 at 0x80498e0 delete min huffmanc3311893 by 0x80492da huffman encode huffmanc1961893 by 0x8049dde encode file mainc941893 by 0x8049bbe main mainc321893 address 0x441d9a8 is 0 bytes inside a block of size 452 freed1893 at 0x402bc70 realloc in usrlibvalgrindvgpreload memcheckx86linuxso1893 by 0x8049922 delete min huffmanc3351893 by 0x80492cc huffman encode huffmanc1951893 by 0x8049dde encode file mainc941893 by 0x8049bbe main mainc321893 1893 invalid read of size 41893 at 0x8049901 delete min huffmanc31893 by 0x80492da huffman encode huffmanc1961893 by 0x8049dde encode file mainc941893 by 0x8049bbe main mainc321893 address 0x441db64 is 4 bytes inside a block of size 452 freed1893 at 0x402bc70 realloc in usrlibvalgrindvgpreload memcheckx86linuxso1893 by 0x8049922 delete min huffmanc3351893 by 0x80492cc huffman encode huffmanc1951893 by 0x8049dde encode file mainc941893 by 0x8049bbe main mainc321893 1893 invalid write of size 41893 at 0x8049906 delete min huffmanc31893 by 0x80492da huffman encode huffmanc1961893 by 0x8049dde encode file mainc941893 by 0x8049bbe main mainc321893 address 0x441d9a8 is 0 bytes inside a block of size 452 freed1893 at 0x402bc70 realloc in usrlibvalgrindvgpreload memcheckx86linuxso1893 by 0x8049922 delete min huffmanc3351893 by 0x80492cc huffman encode huffmanc1951893 by 0x8049dde encode file mainc941893 by 0x8049bbe main mainc321893 1893 invalid free delete delete realloc1893 at 0x402bc70 realloc in usrlibvalgrindvgpreload memcheckx86linuxso1893 by 0x8049922 delete min huffmanc3351893 by 0x80492da huffman encode huffmanc1961893 by 0x8049dde encode file mainc941893 by 0x8049bbe main mainc321893 address 0x441d9a8 is 0 bytes inside a block of size 452 freed1893 at 0x402bc70 realloc in usrlibvalgrindvgpreload memcheckx86linuxso1893 by 0x8049922 delete min huffmanc3351893 by 0x80492cc huffman encode huffmanc1951893 by 0x8049dde encode file mainc941893 by 0x8049bbe main mainc321893 1893 invalid read of size 41893 at 0x8049a0e delete min huffmanc3371893 by 0x80492da huffman encode huffmanc1961893 by 0x8049dde encode file mainc941893 by 0x8049bbe main mainc321893 address 0x0 is not stackd mallocd or recently freed1893 1893 1893 process terminating with default action of signal 11 sigsegv1893 access not within mapped region at address 0x01893 at 0x8049a0e delete min huffmanc3371893 by 0x80492da huffman encode huffmanc1961893 by 0x8049dde encode file mainc941893 by 0x8049bbe main mainc32line 331 is the line in delete min of node min queue0editthe problem is solved now in the accepted answer the reason why is explained just assigning the realloced value correct in delete min solved all issuesrealloc queue and assign new value to local queue varp queuequeue node reallocqueuesizeofnodep queuegroottequeue p queuequeue,['c'] +381405,how does matrixsetlookatm work how does matrixsetlookatm work i have been searching all over and cannot find an explanation i understand that the first three coordinates are to define the location of the camera in the world space and i take it that center of view means the xyz coordinate i am looking at in the world space that being the case what does the up vector meandoif there is a previous question or tutorial that i have overlooked i would be happy to accept that,['android'] +381406,errors of pushing rails app to heroku error occurred while installing sqlite3 and bundler cannot continue i was trying to push my rails app to heroku and received errors as below counting objects 177 done delta compression using up to 2 threads compressing objects 100 161161 done writing objects 100 177177 4473 kib done total 177 delta 39 reused 0 delta 0 heroku receiving push rubyrails app detected installing dependencies using bundler version 121 running bundle install without developmenttest path vendorbundle binstubs bin fetching gem metadata from fetching gem metadata from installing rake 1002 installing i18n 061 installing multi json 137 installing activesupport 328 installing builder 304 installing activemodel 328 installing erubis 270 installing journey 104 installing rack 141 installing rackcache 12 installing racktest 062 installing hike 121 installing tilt 133 installing sprockets 213 installing actionpack 328 installing mimetypes 119 installing polyglot 033 installing treetop 1412 installing mail 244 installing actionmailer 328 installing arel 302 installing tzinfo 0335 installing activerecord 328 installing activeresource 328 using bundler 121 installing coffeescriptsource 140 installing execjs 140 installing coffeescript 220 installing rackssl 132 installing json 175 with native extensions installing rdoc 312 installing thor 0160 installing railties 328 installing coffeerails 322 installing jqueryrails 213 installing rails 328 installing sass 323 installing sassrails 325 installing sqlite3 136 with native extensions geminstallerextensionbuilderror error failed to build gem native ex tension usrlocalbinruby extconfrb checking for sqlite3h no sqlite3h is missing try port install sqlite3 universal or yum install sqlitedevel and check your shared library search path the location where your sqlite3 shared library is located extconfrb failed could not create makefile due to some reason probably lack of necessary libraries andor headers check the mkmflog file for more details you may need configuration options provided configuration options withoptdir withoutoptdir withoptinclude withoutoptincludeoptdirinclude withoptlib withoutoptliboptdirlib withmakeprog withoutmakeprog srcdir curdir rubyusrlocalbinruby withsqlite3dir withoutsqlite3dir withsqlite3include withoutsqlite3includesqlite3dirinclude withsqlite3lib withoutsqlite3libsqlite3dirlib enablelocal thisablelocal gem files will remain installed in tmpbuild 2pense1pvyqutvendorbundle ruby191gemssqlite3136 for inspection results logged to tmpbuild 2pense1pvyqutvendorbundleruby191gems sqlite3136extsqlite3gem makeout an error occurred while installing sqlite3 136 and bundler cannot co ntinue make sure that gem install sqlite3 v 136 succeeds before bundling failed to install gems via bundler heroku push rejected failed to compile rubyrails appmy gemfile as belowgem rails 328 bundle edge rails instead gem rails git gitgithubcomrailsrailsgit group production do gem pg end group development test do gem taps gem rvm gem rspecrails201 gem annotate gem faker031 gem rspec201 gem webrat071 gem spork084 gem factory girl rails10 end gem rake 1001 gem yaml db gems used only for assets and not required in production environments by default group assets do gem sassrails 323 gem coffeerails 321 see for more supported runtimes gem therubyracer platforms ruby gem uglifier 103 end gem jqueryrails to use activemodel has secure password gem bcryptruby 300 to use jbuilder templates for json gem jbuilder use unicorn as the app server gem unicorn deploy with capistrano gem capistrano to use debugger gem debuggeri tried almost all the solutions provided online but still no luck any help will be greatly appreciated,['ruby-on-rails'] +381410,phpserial not working i am trying to use php to make my arduino send out a signal whenever i run the code below it says invalid serial port though it is validphpinclude serial connectphpserial new phpserialserialdevicesetcom2serialdeviceopenserialsendmessage10serialdeviceclosethe serial connectphp class is phpserial link here here is my arduino sketchint ledpin 13void setup pinmodeledpin output serialbegin9600void loop ifserialavailable 0 int time serialparseint digitalwriteledpin high delaytime digitalwriteledpin low please help thanks,['php'] +381482,how to add row index as a column to sql select query assume i have sql query like thisselect id name indexnot a real column from users order by rating desci want to add column to selected columns that will represent the index of the recordexample id name rating 1 a 4 2 b 2 3 c 8 4 d 5for this table i want to get id name rating index 3 c 8 1 4 d 5 2 1 a 4 3 2 b 2 4,"['mysql', 'sql']" +381492,how to handle unknown number of parameters with spring mvc i want to use jquerys sortable so my left list will end with something like thisul li some txt1 input typehidden nameli1 value1 li li some txt2 input typehidden nameli2 value2 liulthe number of li will be different every time my idea is to get all hidden inputs values and names put them in array and post the array as json data but how should my controller look likeis there a way to wait for list of something in the controller for examplerequestmappingvalue listitems public responsebody gridmodel getusersforgridrequestparamvalue items listnameidpair items,"['java', 'javascript', 'jquery']" +381495,when should i create a new dbcontext i am currently using a dbcontext similar to thisnamespace models public class contextdb dbcontext public dbsetuser users get set public dbsetuserrole userroles get set public contextdb i am then using the following line at the top of all my controllers that need access to the database im also using it in my userrepository class which contains all methods relating to the user such as getting the active user checking what roles he has etccontextdb db new contextdbthinking about this there are occations when one visitor can have multiple dbcontexts active ie if hes visiting a controller that uses the userrepository this might not be the best of ideas and i have got a few questions about itwhen should i make a new dbcontext should i have one global context that i pass aroundcan i have one global context that i reuse in all placesdoes this cause a performance hithow is everyone else doing this,['c#'] +381592,arraylists 2 times slower than array i was testing a molecular dynamic algorithm which have among others an class particle compose by 9 array of doubles to store particles components velocity force and position in a 3d environmenti test the algorithm using 5 inputs sizessize mb time s006 036 fits in cache l2014 179 fits in cache l2060 3686 fits in cache l3135 18224 fits in cache l31738 56655 it only fits in ramthan i change the particles layout from array to arraylist in order to have a continuous memory block i had created the arraylist with the size that will occupyarraylist double px new arraylist doubleinput sizei run the version in the same conditions of the testes described above and the results weresize mb time s006 0608014 278060 5715135 299241738 143642the test environment as amd opteron processor 6174 800 mhz 12 mb cache l3 with 24 coresi am getting a speeddown of about 2x is this normal should not be expecting almost the same times in both version since arraylist is allocated continuous in memory like the arrayeditrunning with the option xxprintcompilation with array 1 javautiljarmanifestfastinputstreamreadline 167 bytes 2 sunniocsutf 8decoderdecodearrayloop 553 bytes 3 javalangstringhashcode 60 bytes 4 javalangstringcharat 33 bytes 5 sunsecurityutilmanifestdigesterfindsection 180 bytes 6 javalangobjectinit 1 bytes 7 moldynrandomupdate 104 bytes 8 moldynrandomseed 80 bytes and javalangstrictmathlog static 9 javalangmathlog 5 bytes 10 moldynmdscalingvelocity 82 bytes 11 moldynparticlesthistance 192 bytes 1 moldynparticlesforce 42 211 bytes 12 moldynparticlesforce 211 bytes 13 moldynparticlesdomove 163 bytes 14 moldynparticlesdomove out 160 bytes 2 moldynparticlescicle domove 5 23 bytes 15 moldynparticlesupdate force 49 bytes 3 moldynparticlescicle forces 6 27 bytes 16 moldynparticlesmkekin 141 bytes 4 moldynparticlescicle mkekin 9 33 bytes 17 moldynparticlesvelavg 70 bytes 5 moldynparticlescicle velavg 9 37 bytes 18 moldynparticlescicle domove 23 bytes 19 moldynparticlescicle forces 27 bytes 20 moldynparticlescicle mkekin 33 bytes 21 moldynparticlescicle velavg 37 bytes36763with arraylist double 1 javautiljarmanifestfastinputstreamreadline 167 bytes 2 sunniocsutf 8decoderdecodearrayloop 553 bytes 3 javalangstringhashcode 60 bytes 4 javalangstringcharat 33 bytes 5 sunsecurityutilmanifestdigesterfindsection 180 bytes 6 javalangobjectinit 1 bytes and javalangsystemarraycopy static 7 javalangnumberinit 5 bytes 8 javautilarraylistensurecapacity 58 bytes 9 javalangdoublevalueof 9 bytes 10 javalangdoubleinit 10 bytes 11 javautilarraylistadd 100 bytes 12 javautilarraylistrangecheck 48 bytes 13 javautilarraylistset 21 bytes 14 moldynrandomupdate 104 bytes 15 moldynrandomseed 80 bytes and javalangstrictmathlog static 16 javalangmathlog 5 bytes 17 javautilarraylistget 12 bytes 18 javalangdoubledoublevalue 5 bytes 19 moldynmdscalingvelocity 120 bytes 20 moldynparticlesthistance 240 bytes 1 moldynparticlesforce 42 211 bytes 21 moldynparticlesforce 211 bytes 22 moldynparticlesdomove 337 bytes 23 moldynparticlesdomove out 292 bytes 2 moldynparticlescicle domove 5 23 bytes 24 moldynparticlesupdate force 91 bytes 3 moldynparticlescicle forces 6 27 bytes 25 moldynparticlesmkekin 297 bytes 4 moldynparticlescicle mkekin 9 33 bytes 26 moldynparticlesvelavg 118 bytes 5 moldynparticlescicle velavg 9 37 bytes 27 moldynparticlescicle domove 23 bytes 28 moldynparticlescicle forces 27 bytes 29 moldynparticlescicle mkekin 33 bytes 30 moldynparticlescicle velavg 37 bytes5598,['java'] +381597,implementing the ls al command in c as a part of an assignment from one of my classes i have to write a program in c to duplicate the results of the ls al command i have read up on the necessary materials but i am still not getting the right output here is my code so far its only supposed to print out the file size and the file name but the file sizes its printing are not correct codeinclude systypeshinclude sysstathinclude unistdhinclude stdiohinclude stdlibhinclude direnthint mainint argc char argv dir mydir struct dirent myfile struct stat mystat mydir opendirargv1 whilemyfile readdirmydir null statmyfiled name mystat printfdmystatst size printf sn myfiled name closedirmydirthese are my results after executing the coderootlocalhost aout downloads4096 4096 hw22c4096 ankurtxt4096 4096 destinationtxthere are the correct sizesrootlocalhost ls al downloadstotal 20drwxrxrx 2 root root 4096 nov 26 0135 drxrx 24 root root 4096 nov 26 0129 rwrr 1 root root 27 nov 21 0632 ankurtxtrwrr 1 root root 38 nov 21 0650 destinationtxtrwrr 1 root root 1139 nov 25 2338 hw22ccan anyone please point out my mistakethanksankur,['c'] +381603,overloaded operator must be a unary or binary operator error following the advice given in this answer i have overloaded the operator in my simple point class as follows the overload works finepoint operator point p1 const point p2 return stdmovep1 p2but i get an error saying overloaded operator must be a unary or binary operator has 3 parameterswhat is wrong,['c++'] +381653,referenceerror is not defined i am using a jquery based wordpress twitter widget and receive the error referenceerror is not definedam not sure how to declare the variable here is the widgetscript typetextjavascript cdata function twittercallback2twitters var statushtml for var i0 itwitterslength i var username twittersiuserscreen name var status twittersitextreplacehttpssftpsshssg functionurl return a hrefurlurla replaceb az09ig functionreply return replycharat0a hrefreplysubstring1replysubstring1a statushtmlpush li classtweet span classcontentstatus a stylefontsize85 classtime hrefusernamestatusestwittersiid strrelative timetwittersicreated ataspan div classclearfixdivli documentgetelementbyidtwitter update list php echo unique id innerhtml statushtmljoin var template span classauthor img src userprofile image url nbsp a classusername href userscreen name strong userscreen name strong a span jquery template template user twitters0user insertafterbizsteam twitter ul function relative timetime value var values time valuesplit time value values1 values2 values5 values3 var parsed date dateparsetime value var relative to argumentslength 1 arguments1 new date var delta parseintrelative togettime parsed date 10 delta delta relative togettimezoneoffset 60 if delta 60 return less than a minute ago else ifdelta 120 return about a minute ago else ifdelta 6060 return parseintdelta 60tostring minutes ago else ifdelta 12060 return about an hour ago else ifdelta 246060 return about parseintdelta 3600tostring hours ago else ifdelta 486060 return 1 day ago else return parseintdelta 86400tostring days ago script php ifexclude replies exclude replies str ampexclude repliesexclude replies else exclude replies str script typetextjavascript src timelinephp echo twitter username jsoncallbacktwittercallback2ampcountphp echo twitter count ampinclude rtstphp echo exclude replies str scriptfirebug states that the line of code with the error isjquery template template user twitters0user insertafterbizsteam twitter ulany help would be greatly appreciated,"['javascript', 'jquery']" +381663,dexopt failed on a very big apk outoforder method idx when dexforcejumbotrue i have a very big android project with a multiple big 3rd party jars as android librariesi believe i have hit a dexs max number of method limitation compiling via eclipse 201218 022845 find in files dx processing classesdex 201218 022848 dex loader unable to execute dex cannot merge new index 66774 into a nonjumbo instruction 201218 022848 find in files conversion to dalvik format failed unable to execute dex cannot merge new index 66774 into a nonjumbo instruction taking advantage of sdk tools 21 platform tools 16 i therefore edited my main project projectproperties to set dexforcejumbotruethe flag allowed to me generate the apk but i could not install it properly on physical and emulator alike there seems to be a dex optimizer failure18 201105338 ipackagemanager103 running dexopt on commypackagemyapp 18 201108577 edalvikvm868 outoforder method idx 0x2ae0 then 0x1 18 201108577 edalvikvm868 trouble with item 1544 offset 0xf7ae24 18 201108577 edalvikvm868 swap of section type 2006 failed 18 201108577 edalvikvm868 error byte swap verify failed 18 201108597 edalvikvm868 optimization failed 18 201108597 winstalld39 dexinv end dataappcommypackagemyapp1apk status0xff00 process failed 18 201108597 einstalld39 dexopt failed on datadalvikcachedataclassesdex res 65280 18 201108697 wpackagemanager103 package could not be installed in dataappcommypackagemyapp1apk 18 201109018 ddalvikvm103 gc explicit freed 1698k 13 free 17034k19463k paused 7ms135ms 18 201109068 dandroidruntime780 shutting down vmam i trying to use the dexforcejumbo flag for a purpose it was not intended for or is this error unpredictableif so is there a better strategy to generate a project that includes a very big number of classesmethods,['android'] +381683,get sender ip from multicast packet how do you get the ip of the sender of a multicast udp packet the current code is setup in a synchronousblocking manner see note below here is the code private void receive string mcastgroup setmcastgroup s new socketaddressfamilyinternetwork sockettypedgram protocoltypeudp senablebroadcast true ipendpoint ipep new ipendpointipaddressany 50 sbindipep ipaddress ip ipaddressparsemcastgroup ssetsocketoptionsocketoptionlevelip socketoptionnameaddmembership new multicastoptionip ipaddressany while true try byte b new byte4096 sreceiveb string str encodingasciigetstringb 0 blength thissettextipepaddress strtrim thissettextsenderip strtrim catch note this question comes from chat as such is not my code i am only asking because i understand the problem,['c#'] +381730,imagevideo processing options i have a small 12 volt board camera that is placed inside a bee hive it is lit with infrared leds bees cannot see infrared it sends a simple ntsc signal along a wire to a little tv monitor i have this allows me to see the inside of the hive without thisturbing the bees the queen has a dot on her back such that it is very obvious when she is in the frame i would like to have something processing the signal such that it registers when the queen is in the frame this does not have to be a very accurate count instead of processing the video it would be just as fine to take an image every 10 seconds and see if there is a certain amount of brightness indicating that the queen is in frame this is useful since it helps bee keepers know if the queen is alive if she did not appear for a number of days it could mean something is wrongi would love to hear suggestions for inexpensive ways of processing this video especially with low power consumption raspberry pi arduino camera example heresample video no queen in frame here,['python'] +381732,jquery datatable footer with total rows from the ajax output i am trying to use the fnfootercallback to sum the amounts in a colum as a total the part that i can not figure out yet is that i need the total for that page wich im getting fine from the aadataany idea on how to thisplay the footer with the output we got in aadata using ajax output,['jquery'] +381733,can i get data from shared preferences inside a service i am developing an android application i am using android 22in my application i am capturing gps data and sending it to service with the 1 hour time interval if user exits from application it is also working it is requiredi am using 2 services user defined one for capturing gps data and other for sending to the serverhere my doubt in service can we use shared prefrencesif we store any data in shared preferences in any activity of the application will we be able to use that data in service with the help of shared preferencesall are welcome to give their ideas,['android'] +381735,importing a javascript project in eclipse i was wondering if it was possible to separate my javascript libraries in different eclipse project and then import them in another dynamic web project like i would normally do for regular java subprojects this answer link javascript project with java project in eclipseis what i want to do however i dont really like the answer i would rather link to workspace projects rather than directly rely on the filesystem it seems the jsdt adds a javascript project type and perspective to the eclipse workbench but how do you use import link these js projects in your java project thanks for your help,['javascript'] +381766,jsoup selectorparseexception when colon in xml tag exception is thrown when xml tag has colonexceptionorgjsoupselectselectorselectorparseexception could not parse query wr unexpected token at rxmlwr wrpr wrstyle wvaljid wrpr wtanwtwrjava code orgjsoupnodesdocument doc jsoupparsedocumentxmlstringhere documentxmlstring has the xml specified above,['java'] +381782,how to append text to qplaintextedit without adding newline and keep scroll at the bottom i need to append text to qplaintextedit without adding a newline to the text but both methods appendplaintext and appendhtml adds actually new paragraphi can do that manually with qtextcursorqtextcursor text cursor qtextcursormy plain text editdocumenttext cursormovepositionqtextcursorendtext cursorinserttextstring to append that works but i also need to keep scroll at bottom if it was at bottom before appendi tried to copy logic from qts sources but i stuck on it because there actually qplaintexteditprivate class is used and i cannot find the way to do the same without it say i do not see method verticaloffset in qplaintexteditactually these sources contain many weird at the first look at least things and i have no idea how to implement thisheres the source code of append,['c++'] +381785,selenium web driver handle confirm box using java hi i am using the following code for handling the alert box after clicking an action but it is not workingcan somebody please helpthis is where i call the handler clickonalert after clickonaddquote is called alert box appearssystemoutprintlnbefore add to quotethisclickonaddquotesystemoutprintlnbefore alertthisclickonalertsystemoutprintlnafter alertfunction clickonalertpublic void clickonalert systemoutprintlnin click alert alert webdriversessionswitchtoalert systemoutprintlnafter constructor alertaccept please helpthanks,['java'] +381795,android limit fragments loading with a viewpager i have 3 fragments that are managed by an fragmentpageradapter set to a viewpageri want to load fragments one by one but when the oncreate method of fragmentactivity is executed the 2 first fragments are executed oncreateview methodi have tried to limit fragments loading with the setoffscreenpagelimit method but nothing changempageradapter new mypageradaptersupergetsupportfragmentmanager fragmentspager viewpager superfindviewbyidridtabviewpagerpagersetoffscreenpagelimit0pagersetadapterthismpageradapterthank you for your help,['android'] +381821,how to translate a wordpress template name i know how to create translations for themes and templates generally by generating po and mo files with poedit for example but since template names are written in php comments at top of each template file there is no way to translate this as i see it wordpress template header template name three columns package wordpress template name is somehow parsed by wordpress and used to populate the template select dropdown when creating a pageso my question is is there a way to translate a wordpress template name does wordpress also look for any specific variable i can set in my template file or is it just impossible,['php'] +381848,php mysql for permutations on mysql table i have a mysql table with 7 columns on which with each row contains integer values i have a simple site which receives values from the user and i have to try to see if the values sent by the user match or are similiar to any of the rows in the tableso the user writes eg 1 2 3 4 5 6 7 as input i have to find out if any of the rows in my table are similar to it without order so 1 2 3 4 5 6 7 7 6 5 4 3 2 1 and so on the table my contain more than 40 rows of datai also have to see if they share at least 5 6 or 7 digits in commonthis means using permutations to find all possible combinations however what is the best approach for such a problemtake the input from the user and get all permutations and match against first row second row etc and report if found alternatively do the reverse get a row from the table and get all permutations and do the match against the user inputwhat about memory and cpuusage when going through such a big table with so many permutationsthanks for any tips on thissouciance,"['php', 'mysql']" +381851,how to get the exact number of times that a function is executed in c includeiostreamusing namespace stdvoid callme int count0 couti am called count timesnint main callme callme callme callme return 0in this case the output will bei am called 1 timesi am called 1 timesi am called 1 timesi am called 1 timesinstead i want the output printed asi am called 1 timesi am called 2 timesi am called 3 timesi am called 4 times,['c++'] +381865,debugging in codeigniter and mvc often times i feel the need to dump a variable for debugging purpose in codeigniter i am struggling to do that since i cannot simply echo a variable without passing it to the view first which i think is painstaking i have read the official documentation though i had found a good solution with the log message function but cannot make it work even though i successfully made the logs folder writable and changed the threshold as advised any suggestions,['php'] +381867,editing djangorestframework serializer object before save i want to edit a djangorestframwork serializer object before it is saved this is how i currently do it def uploadrequest if requestmethod post form imageformrequestpost requestfiles if formis valid all validation rules pass obj formsavecommitfalse objuser id 15 objsavehow can i do it with a djangorestframework serializer objectapi viewpostgetdef upload serializersrequest if requestmethod post serializer filesserializerdatarequestdata filesrequestfiles if serializeris valid serializersave,['python'] +381896,create a java annotation with ide contextual behaviour i have created an annotation highlights this method is declared in xml public interface fromxml i am using this on methods that look like thisfromxmlpublic void onsomethingclickview vthe v variable is needed by the android reflection system to call this methodhowever the input var v is unused so my ide warns me of this i like this warning and want it on for the rest of my codeto hide the warning i could do suppresswarningsunusedfromxmlpublic void onsomethingclickview vor i could add a param tagbut i would rather that the ide eclipse reads my fromxml annotation and does not give me the warningi know you cannot extend an annotation but thats basically what i want to dois there a way i can add my annotation to be recognised as a suppress warnings annotationoris there a way to code my annotation to act like suppress warnings,"['java', 'android']" +381899,how to detect and count a spirals turns i need to detect a spiral shaped spring and count its coil turnsi have tried as followsimagebgr byte processimageimagebgr byte img imagebgr byte imgclone new imagebgrbyte imgwidth imgheight imgclone imgclone bgr bgrred new bgrsystemdrawingcolorred region algorithm 1 imgclonepyrup imgclonepyrdown imgclonepyrup imgclonepyrdown imgclonepyrup imgclonepyrdown imgclone equalizehist imgclone dilate20 imgclone equalizehist imgclone erode10 imgclonepyrup imgclonepyrdown imgclonepyrup imgclonepyrdown imgclonepyrup imgclonepyrdown imgclone equalizehist imgclone dilate20 imgclone equalizehist imgclone erode10 imagegray byte imgclonegray new imagegray byteimgclonewidth imgcloneheight cvinvokecvcvtcolorimgclone imgclonegray emgucvcvenumcolor conversioncv bgr2gray imgclonegray imgclonegraycannyc thresh c threshlink intc threshsize contoursystemdrawingpoint pts imgclonegrayfindcontoursemgucvcvenumchain approx methodcv chain approx simple emgucvcvenumretr typecv retr external cvinvokecvcvtcolorimgclonegray imgcloneycc emgucvcvenumcolor conversioncv gray2bgr if null pts imgclonedrawpts bgrred 2 imgclonedrawptsboundingrectangle bgrred 2 endregion return imgclone i am some how able to get the spring but how to get the counts i am looking for algorithmsi am currently not looking for speed optimizationthis is similar like counting fingers spring spiral is very thin to get using contour what else can be done,['c#'] +381909,deploying maven artifact to multiple repositories with different settings we have numerous java projects which are ci built with jenkins these are deployed to our own nexus server just finethe problem is we need to provide these libraries to a third party but without the source codeso for each project in nexus we havereleases repository for our devs includes deployed source codesnapshots repositories for our devs includes deployed source codethird party release repository only jar pomand would be good to have third party snapshot repository only jar pom for third party nightly buildsthe question is how is this usually handled in jenkinsnexus world i would prefer to have one single job in jenkins which handles the ci build and the release artefact deployment process automaticallycurrently i am using multiple thistributionmanagement profiles in our main root pomxml included by all projectsprofiles profile iddefaultid thistributionmanagement repository idreleasesid namereleasename urlhttppathtonexuscontentrepositoriesreleasesurl repository snapshotrepository idsnapshotsid namesnapshotname urlhttppathtonexuscontentrepositoriessnapshotsurl uniqueversionfalseuniqueversion snapshotrepository thistributionmanagement profile profile idthirdpartyid thistributionmanagement repository idreleasesid namereleasename urlhttppathtonexuscontentrepositoriesthirdpartyurl repository snapshotrepository idsnapshotsid namesnapshotname urlhttppathtonexuscontentrepositoriesthirdpartysnapshotsurl uniqueversionfalseuniqueversion snapshotrepository thistributionmanagement profileprofilesfrom the maven docs it seems to be no way of using multiple repositories during the same build lifecycle not to mention the fact that we needdo not need the source based on the target repoi can do a trick with creating a job in jenkins with the maven goals and options clean deploy p thirdparty and then adding the postbuild action deploy artifacts to maven repository with the default data but in this case only snapshots are going to both repo and artefacts released via jenkins maven release plugin are going into one repository onlyany practical ideas how can i do this without overcomplicating our ci job hierarchythanks in advance,['java'] +381913,how to force racksession sinatra to read racksession from params instead of cookies i am dealing with oauth 10 twitter and flickr website works at port 80 and oauth server works at port 8080algorithmsend ajax request to oauth server to check if user have valid access tokenopen authorization window if user have no access token or access token is expiredsave access token in users session at the oauth serversend sharing data to the oauth serverit uses sinatra racksession racksessionsequel sqlite to store sessions it sends setcookie racksessionid in each responsei am using 2 types of request crossdomain ajax with jquery and usual request with windowopen i have a big security problem passing cookies to crossdomain ajax request no matter that servers response headers containsaccesscontrolallowheaders chromium will throw security errorrefused to set unsafe header cookiei want to avoid this problem by passing racksessionid to post data and load itbefore twitterconnectjson do session racksessionsomethingparamsracksessionendbut i cant find in documentation how to do this,['ruby'] +381961,how can i install from a git subdirectory with pip i have a git repository with many folders one of them being a python module installable with pip like thisrepogitrepogitfolder1repogitfolder2repogitmymodulerepogitmymodule init pyrepogitmymodulesetuppyrepogitmymoduleright now i have to do the following to installgit clone httpserverrepogitcd repopip install mymodulecd rm rf repois it possible to install the module directly with pip without explicitly cloning i triedpip install githttpserverrepogitmymodulepip install githttpserverrepogitmymodulebut i getioerror errno 2 no such file or directory tmppip88tllmbuildsetuppy,['python'] +381962,declaring variable in javafx css file i have been inspecting the caspiancss thistributed by oracle in the javafx runtime library and i see they have declared some color values as variables egfxbase d0d0d0 caspiancss line 47and then they used it as value of some other property likefxcolor fxbase caspiancss line 96now what i want to do is to declare a measurement unit fxradiusdefault 10px and then use it everytime i need to set radius of a control for instancefxborderradius fxradiusdefaultfxbackgroundradius fxradiusdefaulti have been unsuccessful so far my question is is this possible at alledit adding experiment detailsdetailshere is my experimentfxml file that i created on javafx scene builder 11xml version10 encodingutf8import javalangimport javanetimport javautilimport javafxscenecontrolimport javafxscenelayoutimport javafxscenepaintanchorpane idanchorpane maxheightinfinity maxwidthinfinity minheightinfinity minwidthinfinity prefheight40 prefwidth60 xmlnsfx children textarea layoutx20 layouty1190 prefwidth20 styleclasstrack wraptexttrue children stylesheets url valuecssexperimentcss stylesheetsanchorpaneand below is the cssexperimentcss that i have used fxradiusdefault 10pxtrack fxborderradius fxradiusdefault fxbordercolor blackunfortunately this does not work giving an error message like thiscould not resolve fxradiusdefault while resolving lookups for fxborderradius from rule track in stylesheet file homeabdullahcodebasesrcpackagecssexperimentcssif i use plain syntax fxborderradius 10px there is no problem with thatwhat am i doing wrong hereedit conclusionconclusion not possibleit seems what i am looking for is not possible with the current version of javafx since javafx css reference guide only mentions lookedup colors and not a generic concept of variables it would be a good feature though just saying,['css'] +381975,how to correct syntax highlighting for setting rails link or form field class in sublimetextmate 2 background in sublime text and textmate the word class is incorrectly highlighted when using the new ruby hash format in a rails link to or form fieldobjective is there any way to correctly highlight the class keyword as it does when using the old format,"['ruby-on-rails', 'ruby']" +381987,compiling python to a static lib and using pythoncorelib i am trying to build python 27 as a static single lib filei have already made the following changes to the python source codechange to release modechange all dll projects to static library lib and set runtime library to mtadd preprocessor definition py no enable shared to python and pythoncorei have managed to compile the pythoncore project to pythoncorelib about 11mb sizebut when trying to compile the python project i get the following linking errorserror lnk2019 unresolved external symbol py activateactctx referenced in function pyimport getdynloadfunc cpython273 sourcepcbuildpythoncorelibdynload winobj error lnk2019 unresolved external symbol py deactivateactctx referenced in function pyimport getdynloadfunc cpython273 sourcepcbuildpythoncorelibdynload winobj error lnk2019 unresolved external symbol py hgidentifier referenced in function pysys init cpython273 sourcepcbuildpythoncorelibsysmoduleobj error lnk2019 unresolved external symbol py hgversion referenced in function pysys init cpython273 sourcepcbuildpythoncorelibsysmoduleobj error lnk2019 unresolved external symbol py getbuildinfo referenced in function py getversion cpython273 sourcepcbuildpythoncorelibgetversionobjcan anyone help methanksidan update i just managed to make it work if it helps anyone these are the changes i made1 add modulesgetbuildinfoc to the pythoncore project2 in pcdl ntc move this line ifdef py enable shared from line 14 to line 79 just above dllmainand that is ityou may now link to pythoncorelib idan,['python'] +381989,optionally supporting initializer list construction for templates maybe wrapping containers if i have a template that wraps a standard container it seems i can reasonably easily delegate the initializer list constructortemplatetypename tstruct holder t t holder t holderstdinitializer listtypename tvalue type values t values so this works nicely with stdvector for instanceint mainint argc char argv holderstdvectorint y123 return exit successbut it pretty obviously does not work for t as int or any other type that does not have a nested value type typedef so i would like to use some sort of enable if or similar trick to make the initializer list constructor not be emitted unless t both defines a nested value type typedef and is constructible from stdinitializer listi tried the following but it still does not work because the compiler clang 31 in my case still trips over the invalid tvalue type when t is intholdertypename stdenable ifstdis constructiblet stdinitializer listtypename tvalue typevalue stdinitializer listtypename tvalue typetype values t values any thoughts on how to express the concept give this template on t an initializer list constructor over ts value type if and only if t has a value type typedef and is constructible from an initializer list of tvalue type,['c++'] +382007,how to solve xaml parse errors i have a xaml windows 8 winrt xaml c application that has a xaml usercontrol in the designer i do not see any issue no red underlines or similar the project also compiles without any errors when i run the application the application breaks in initializecomponent with xaml parse error i have no idea how to debug this kind of issue what would be the steps to identify the problem yes the there is something wrong with the xaml user control or the ressource dictionary but how would one deal with this kind of error in a structured wayeditok it seems that trailerror seems to be the right approach for winrtbtw i found the issue with my code my project was called pegasuscore and in the generated calendercontrolgics file from visual studio the path was this msappxpegasus coreviewcalendarcontrolxaml replaced with the fix url,['c#'] +382008,advanced debugging advice in wpf garbagecollection situationwe are running a large wpf application which does not release memory for quite some time it is not a real memory leak as the memory will be released eventually i know that normally this would not be considered to be a problem unfortunately it becomes a performance issue in conjunction with the wpf commanding infrastructure see below for a more detailed descriptionfindingswe have automated tests that perform typical use cases some cases are working fine and are releasing the memory in time others are hogging the memory until the client is minimized a new window is opened or some other conditions occur that triggers a gen2 collectiona with ants we see that the objects do not have a gc root but a lot of references to other objects that require finalization a windbg does not show any objects to be ready for finalizationa running several gccollect gcwaitforpendingfinalizers completely frees the memorya we know which ui action causes the high memory condition but we could not identify any suspicious codequestionwe would appreciate any advice on debugging such a problem wpf commandmanager background the wpf commandmanager holds private collection of weakreferences requerysuggestedhandlers for raising the canexecutechanged event handling canexecutechanged is quite costly especially finding the eventroute for canexecute which apparently is a routedevent anytime the commandmanager feels like requerying if commands can be executed it iterates through this collection and calls the canexecutechanged event on the respective command sourcesthe weakreferences are not removed from that collection as long as there is a gc handle for the referenced object while the object has not been collected the commandhelper keeps processing canexecute events for these elements buttonbase or menuitems in case there is a lot of garbage as in our case this can result in an extremely large number of calls the canexecute event handlers which causes the application to be really laggy,['c#'] +382015,retrieve image orientation in php how can i get the image orientation landscape or portrait of an image jpeg or png in php i created a php site where users can upload pictures before i scale them down to a smaller size i want to know how the image is orientated in order to scale it properlythanks for your answer,['php'] +382023,is there a way to view cpickle or pickle file contents without loading python in windows i use cpickle to save data sets from each run of a program since i sometimes need to see the outline of the data without running the code i would like an easy way to quickly view the contents by just doubleclicking on the file i am trying to avoid having to load a terminal and pointing python to a file each time just to run some print scripti looked for notepad plugins but could not find anythingis there some easy way to do this does anyone have any suggestionsnote i run windows 7,['python'] +382050,css vertical scrollbar leads to horizontal scrollbar my css looks like thisdivsomeclass position absolute maxheight 300px height auto width auto overflow auto the div height and width scale automatically the height has fixed a maximum though as soon as this value is reached vertical scrollbars appear this works all pretty swellnow the issueif the vertical scrollbars appear they use up around 10px of horizontal space as the scrollbars will be placed inside the divhowever the width is not autoscaled to allow for these additional 10something pixels used up by the vertical scrollbars as the horizontal width before the adding the vertical scrollbars was just exactly right for the content as expected from the widthauto setting the div now also thisplays horizontal scrollbars to allow for the missing 10 pixels this is sillyhow can i avoid having these horizontal scrollbars and just autoscale the width of the div to make the vertical scrollbars fitif possible i am looking for a solution which does not rely on just completely thisabling horizontal scrolling as this will probably be needed at some point ie for certain inputs,['css'] +382058,least common multiple i have the current coding which used to be a goto but i was told to not use goto anymore as it is frowned upon i am having troubles changing it into for say a while loop i am fairly new to c and programming in general so some of this is completely new stuff to me any help would be appreciated the actual question is input two numbers and find the lowest common multiplehere is the original with gotobob if b d a myint myint a b myint myint myint a if b myint2 0 consolewrite0 h consolereadline if d b c myint2 myint2 c d myint2 myint2 myint2 c if d myint 0 consolewrite0 t consolereadline else goto bob else goto bob,['c#'] +382060,rails s return bug segmentation fault if i run rails s i getusersadamrvmgemsruby193p327gemspg0132libpg extbundle bug segmentation faultruby 187 20120208 patchlevel 358 universaldarwin120abort trap 6versionsrails vrails 321ruby vruby 193p327 201210 revision 37606 x86 64darwin1220why is in the error message mentioned the ruby version 187 if i use 193,"['ruby-on-rails', 'ruby']" +382085,knockout visible binding not working i have got a very simple view modelvar viewmodel function thisshowrow koobservablefalse thistogglevisibility function ifthisshowrow true thisshowrow false else thisshowrow true alertshowrow is now thisshowrow only here for testing with equally simple markupa href databindclick togglevisibilitytoggleabr table tr databindvisible showrowsome texttrtablemy problem is that when the link is clicked the alert box shows thisplaying the correct value truefalsehowever the visible binding on the tr element does not seem to work either initially the row should be invisible on load nor when the value of showrow togglesjsfiddle of above,['javascript'] +382091,how to pass some parameters to function called in addeventlistener possible duplicatehow to pass arguments to addeventlistener listener function how can i pass some argument in this case an integer to a function through addeventlistener on a click eventi have two buttons if i press the right one i want to do some stuff if i press the left one then i would like it to do something elseheres the codedocumentgetelementbyiddate rightaddeventlistener click switch date1 false documentgetelementbyiddate leftaddeventlistener click switch date1 false function switch date k ifk1 do stuff else another stuff,['javascript'] +382119,get first and last date of current month with javascript or jquery possible duplicatecalculate last day of month in javascriptwhat is the best way to determine the number of days in a month with javascript as title says i am stuck on finding a way to get the first and last date of the current month with javascript or jquery and format it asfor example for november it should be var firstdate 11012012var lastdate 11302012,"['javascript', 'jquery']" +382124,java spring how to use classpath to specify a file location how can i use the classpath to specify the location of a file that is within my spring projectthis is what i have currentlyfilereader fr new filereadercuserscoreydesktopstoredproceduressqlthis is hardcoded to my desktop what i would like is to be able to use the path to the file that is in my projectfilereader fr new filereadersrcmainresourcesstoredproceduressqlany suggestions,['java'] +382136,ask permission to access camera roll i have a settings view where the user can choose switch on or off the feature export to camera rollwhen the user switches it on for the first time and not when he takes the first picture i would like the app to ask him the permission to access the camera roll i have seen behavior in many app but cannot find the way to do it,"['objective-c', 'ios']" +382172,inserting values into a sql server database using adonet via c i have created a simple program to insert values into the table regist but i keep getting the error incorrect syntax near on cmdexecutenonquery private void button1 clickobject sender eventargs e sqlconnection cn new sqlconnectiondata sourcedellpcinitial catalogadventureworks2008r2 user idsapasswordsqlpassintegrated securitysspi sqlcommand cmd new sqlcommandinsert into dboregist firstname lastname username password age gendercontact values textbox1text textbox2text textbox3text textbox4text combobox1textcombobox2texttextbox7text cn cnopen cmdexecutenonquery cnclosei am new to this and i am really confused,"['c#', 'sql']" +382184,full video background using videojs i am trying to make a full screen video background that always shows the full size even on window resizehere it is the sitethis is the problem i haveon wide screen it shows like thisand on vertical screen it shows like thisas you can see it always put some black bars to the video instead of resizing the video to the full of the screen this is my markup div idfullbackground video classvideojs vjsfullscreen autoplay preloadauto poster datasetup source srcvideo1mp4 typevideomp4 video div with this cssfullbackground zindex 9 minheight 100 minwidth 1024px width 100 height 100 position fixed top 0 left 0videojsvjsfullscreen position fixed overflow hidden zindex 10 left 0 top 0 bottom 0 right 0 width 100 important height 100 important position absolute ie6 fullwindow underscore hack i am using the videojs pluginany ideas and how to make the video full size without showing black bars on the side or topbottom,"['javascript', 'jquery', 'html', 'css']" +382188,svg in html resize paths according to page width i have an svg element in my document which has 100 width via css this only resizes the svg element it does not resize the paths here is my path codepath idquadcurveabc dm 0 300 q 300 0 500 100 l 0 100 z strokeblack strokewidth2 fillblack i need the xcomponent of m to be lined up against the left side of the screen which it is but also i need the 500 of q 300 0 500 100 to be against the right side of the screen how would i accomplish this,['html'] +382219,android widget previewimage size i have a widget in android for which i am setting a previewimage unfortunately i am having issues figuring the good size for the widget if it is too big it gets cropped at the bottom of the framei have been trying to find the recommended size or even better the pixel dimensions of this frame where the preview image gets thisplayed but i cannot find it in the documentationdoes anyone please know where to look for that information pleasethank you,['android'] +382226,jquery replace all instances of a character in a string this does not work and i need it badlysomemultiwordstringreplace always getssome multiwordstringit is always replacing for the first instance only but i need it to work for all symbols,['jquery'] +382232,construct pandas dataframe from items in nested dictionary suppose i have a nested dictionary user dict with structurelevel 1 userid long integerlevel 2 category stringlevel 3 assorted attributes floats ints etcfor example an entry of this dictionary would beuser dict12 category 1 att 1 1 att 2 whatever category 2 att 1 23 att 2 anothereach item in user dict has the same structure and user dict contains a large number of items which i want to feed to a pandas dataframe constructing the series from the attributes in this case a hierarchical index would be useful for the purposespecifically my question is whether there exists a way to to help the dataframe constructor understand that the series should be built from the values of the level 3 in the dictionaryif i try something likedf pandasdataframeusers summarythe items in level 1 the user ids are taken as columns which is the opposite of what i want to achieve have user ids as index i know i could construct the series after iterating over the dictionary entries but if there is a more direct way this would be very useful a similar question would be asking whether it is possible to construct a pandas dataframe from json objects listed in a file,['python'] +382237,trying to solve telephone word more elegantly with recursion i have looked through stack overflow but have not been able to get anything to work i apologize if i missed a blatantly obvious posti had a school problem that involved taking a phone number getting all the possible word combinations and then writing it to a text file i did that and got full credit for my assignment i was able to do this with seven nested loops but that is not very elegant and is very rigid i was blown away and totally thisappointed to find the textbook solution was seven nested loops my instructor did not have any answers eitheri have tried many different approaches but i have not been able to get it dialed in i identified a recursion and the kill point but never was able to get it to work i can produce the letter sequences but nowhere close to how many there should be i commented out my attempts so you can see my failed thought processes please take a look and let me know if you have any ideaspublic partial class telephoneworderizer form protected dictionaryint ienumerablestring keymappings new dictionaryint ienumerablestring protected string activelettersgroups null protected liststring words new liststring protected liststring recursivewords new liststring protected int iteration 0 public telephoneworderizer initializecomponent thiskeymappings thisgetkeymappings private void btngetwords clickobject sender eventargs e string textboxcontent textboxnumbertext int digits thisgetphonenumberstextboxcontent liststring words thisgetwordsdigits using streamwriter writer new streamwriterewordstxt foreach var word in words writerwritelineword textboxnumberclear private liststring getwordsint digits liststring lettergroupings new liststring digits array of numbers for int i 0 j digitslength i j i int digit digitsi if the number has a letter group mapped to it if thiskeymappingscontainskeydigit letters mapped to a given number lettergroupingsaddthiskeymappingsdigittoarray thiswordmakerlooplettergroupings thiswordmakerlettergroupings return thiswords return thisrecursivewords private void recursionteststring word liststring groups int letterctr int groupctr string group groupsgroupctr word groupletterctr letterctr 1 if letterctr grouplength 1 letterctr 0 groupctr 1 hit bottom if groupctr groupscount 1 groupctr 1 recursiontestword groups letterctr groupctr private void wordmakerliststring lettercollections string newword int numberlength lettercollectionscount thisactivelettersgroups lettercollectionstoarray string lettergroup thisactivelettersgroups0 thisrecursivegetwordsnewword 0 0 summary summary param namewordparam param namegroupindexparam param nameletterindexparam private void recursivegetwordsstring word int groupindex int letterindex var numactivelettergroups thisactivelettersgroupslength if thisactivelettersgroupslength 0 thisiteration numactivelettergroups if groupindex numactivelettergroups var letters thisactivelettersgroupsgroupindex picks the a letter group ex a b c if letterindex letterslength var letter1 lettersselectx string letter lettersletterindex picks a letter from the group ex a word letter thisrecursivegetwordsword groupindex 1 thisiteration else thisrecursivewordsaddword word thisrecursivegetwordsword 0 1 else thisrecursivewordsaddword word thisiteration thisrecursivegetwordsword 0 thisiteration region private void wordmakerloopliststring lettergroups string word array of string var newgroup lettergroupstoarray grabs a letter group for int i 0 i newgrouplength i var lettergroup1 newgroupi grabs a letter from group 1 for int j 0 j lettergroup1length j string letter1 lettergroup1j if i 1 newgrouplength var lettergroup2 newgroupi 1 grabs a letter from group 2 for int k 0 k lettergroup2length k string letter2 lettergroup2k if i 2 newgrouplength var lettergroup3 newgroupi 2 grabs a letter from group 3 for int l 0 l lettergroup3length l string letter3 lettergroup3l if i 3 newgrouplength var lettergroup4 newgroupi 3 grabs a letter from group 4 for int m 0 m lettergroup4length m string letter4 lettergroup4m if i 4 newgrouplength var lettergroup5 newgroupi 4 grabs a letter from group 5 for int and 0 and lettergroup5length n string letter5 lettergroup5n if i 5 newgrouplength var lettergroup6 newgroupi 5 grabs a letter from group 6 for int o 0 o lettergroup6length o string letter6 lettergroup6o if i 6 newgrouplength var lettergroup7 newgroupi 6 grabs a letter from group 6 for int p 0 p lettergroup7length p string letter7 lettergroup7p word letter1 letter2 letter3 letter4 letter5 letter6 letter7 thiswordsaddword word sanitizes input text and converts the string into and arra of int private int getphonenumbersstring content int phonenumbers null string cleanstring thissanitizestringcontent int numbers if int32tryparsecleanstring out numbers phonenumbers thisgetintarraynumbersoftypeinttolist phonenumbers thisgetintarraynumbers return phonenumbers removes potential unwanted characters from the phone number private string sanitizestringstring content content contentreplace content contentreplace content contentreplace return content breaks a number into an array of its individual digits private int getintarrayint num listint listofints new listint while num 0 listofintsaddnum 10 num num 10 listofintsreverse return listofintstoarray gets the mappings for the numerical values private dictionaryint ienumerablestring getkeymappings liststring alphabet new liststring a b c d e f g h i j k l m n o p q r s t u v w x y z dictionaryint ienumerablestring mappings new dictionaryint ienumerablestring for int i 0 i 10 i string letters null switch i case 0 case 1 break case 2 case 3 case 4 case 5 case 6 case 8 letters alphabettake3toarray mappingsaddi letters alphabetremoverange0 3 break case 7 case 9 letters alphabettake4toarray mappingsaddi letters alphabetremoverange0 4 break default break return mappings endregionlet me emphasize that the school assignment is over for those people in doubt i want to do this better and more efficient i can post my project on github if that would help,['c#'] +382238,jersey json array with 1 element is serialized as object i am creating a rest server with jerseyjava and i found a strange behaviori have a method on the server that returns an array of objects as jsongetpathfilesproducesmediatypeapplication jsonpublic object getfiles throws exception databasemanager db new databasemanager fileinfo result dbgetfiles return resultthe code is executed correctly and data is returned to the client a jquery ajax callthe problem is that the format of the returned data changes if the result array has one element or more than oneresponse with one elementfileinfofilenameweatherarffid10response with two elementsfileinfofilenameweatherarffid10filenamesupermarketarffid11as you can see in the first scenario the value of the fileinfo property of the returned object is an object and in the second case the value is an arraywhat am i doing wrong should not the first case return something like thisfileinfofilenameweatherarffid10ie an array with a single object insidei know that i can detect this on the client side but it seems like a very ugly hackthanks for your time,['java'] +382300,jquery tools validator not working correctly and issue with element hanging below parent element i have 2 problems at the moment i bought a template and am trying to integrate it into a rails appfirst problemi am having trouble with the jquery tools form validations the validation is not working when you click the submit button it just shows the inputs value where the validation message should be also even though the required fields are filled in it still would not let me submit the form if you go to this link you can try and edit the data to see the valiation errorssecond problemif you go to this link you can see that the avatar and edit info button are hanging through the gray background how can i get that gray background to fully encapsulate the avatar icon,"['jquery', 'css', 'ruby-on-rails']" +382354,why filestreamlength is long type but filestreamread argument offset has a shorter length why filestreamlength is long type but filestreamread argument offset has a shorter length int instead bryan,['c#'] +382372,skip first line using open csv reader here is the line i am using currentlyfile booleantopicfile booleantopicfile is csv file uploaded from formcsvreader csvreader new csvreadernew inputstreamreadernew fileinputstreambooleantopicfile utf8want to skip the first line of the csv which contains headingsi dont want to use any separator as except the default one comma which is already available in default constructorin parameterized constructor there is a option to skip no of lines but how to deal with the 2nd and 3rd param of the constructorcsvreader csvreader new csvreadernew inputstreamreaderreader reader char c char c1 int indexthanks,['java'] +382374,can i animate multiple css transform properties separately using keyframe animation i want to animate two or more css transform properties separately using keyframe animation like thiskeyframes translatex 100 transform translatex100px keyframes rotatez 100 transform rotatez80deg htmldiv classrectdivtranslatex animation should start with 0s delay and last for 5 seconds rotatez animation should start with 1s delay and last for 3 seconds so rect element starts moving then after 1 second it starts rotating then after 3 seconds it stops rotating and after 1 more second it finishes its movementapply animationrect animationname translatex rotatez animationduration 5s 3s animationtimingfunction ease easeinout animationdelay 0s 1s animationdirection forward forwardthe problem here is that only rotatez animation is applied my question is are there any ways to implement such animation using just css keyframe animation transitions or i need js and requestanimationframeedit my fiddle,['css'] +382378,how to import data from text file to mysql database i have a 350mb file named text filetxt containing this tab delimited data345868230 1646198120 1531283146 keyword 1531283146 155 252910745345566 1646198120 1539847239 another 1531276364 275 9878310mysql database name xml datedatabase table performancereporti have already created the table with all the destination fieldsi want to import this text file data into a mysql i googled and found some commands like load data infile and quite confused on how to use ithow can i import this text file data,['mysql'] +382416,local and static variables in c when compiling this external definitionsint value1 0static int value2 0the gcc compiler generates the following assemblyglobl value1 bss align 4 type value1 object size value1 4value1 zero 4 local value2 comm value244however when i initialize the variables to a value other than zero such as external definitionsint value1 1static int value2 1the gcc compiler generated the followingglobl value1 data align 4 type value1 object size value1 4value1 long 1 align 4 type value2 object size value2 4value2 long 1my questions arewhy in the first case the values are allocated in the bss segment while in the second case in the data segmentwhy value2 variable is defined as local and comm in the first case while not in the second,['c'] +382437,bootstrap theme variablesless bootswatch how do you generate bootstrapcss file from the variablesless and bootstrapless files from compiling using lessc i get a css file but that is way smaller than bootstrapcss how am i supposed to change the colour in one of the themes thanks a ton,['css'] +382458,unable to inject jsf viewscoped bean into validator as managedproperty i am trying to inject jsf viewscoped bean as managedproperty into a requestscoped bean which implements javaxfacesvalidatorvalidator but always a fresh copy of viewscoped bean is injectedviewscoped beanviewscopedmanagedbeanpublic class bean private integer count 1 private string field2 public string action count return null public string anotheraction return null getter and settervalidatorrequestscopedmanagedbeanpublic class somevalidator implements validator public void validatefacescontext context uicomponent comp object value throws validatorexception logging beangetcount is always one here even after calling ajax action a few times managedpropertyvalue bean private bean beanxhtml pagedoctype html html langen xmlns xmlnsfxmlnsheadhheadhbody hform hpanelgroup layoutblock idpanel1 hcommandbutton typesubmit valueaction actionbeanaction fajax renderpanel1fajax hcommandbutton houtputtext valuebeancounthoutputtext hpanelgroup hpanelgroup layoutblock idpanel2 hinputtext typetext valuebeanfield1 fvalidator bindingsomevalidator hinputtext hpanelgroup hcommandbutton typesubmit valueanother action actionbeananotheraction fajax executepanel2 renderpanel2fajax hcommandbutton hformhbodyhtmlas mentioned in code even after calling ajax action a few times when logging beangetcount always thisplay onebut the same scenario works if i change viewscoped to sessionscoped also if i remove validator implementation of requestscoped bean and use a logger in postconstruct the count does increment for every ajax request as expectedam i doing something wrong or is this how it should work thanks in advance,['java'] +382468,php session not sent through loginphp file i have created my site on windows xp32 and a few days ago then re installed the same type of windows professional xp 32bitnow my website does not work properly sessions are not sent and i wonder if the windows have something to do with this cuz i turned off some startup services in msconfigservicesother thing i suspect is the xampp after i found out the problem i edited phpini in apache 10times and it did not fix the problem in google a lot of people complain about common problem they say that they changed server and now sessions are not sent i am new to php and do not have idea what exactly is going oncan someone help me with some hints about where might the problem be and also i would like to know if it is a good practice to use alternatives of sessions for example if user is logged insend data to mysql set logged in 1 and if logout set logged in 0or anything elseevery info on this matter would be helpful thank youhere is the exact code situationproject link i have this login form form actionloginphp methodpost ul li input typetext nameusername li li input typepassword namepassword li li input typesubmit valuelogin li li a hrefregisterphpregistera li ul formin loginphp i have this else sessionuser id login sessionuser id works here and outputs the correct data user id headerlocation indexphp exitand in intphpit is incl in indexphp i have this session startprint rsession get cookie params echo br outputs array lifetime 0 path domain secure httponly print rsession status echo br output 2var dump session output array0 print r sessionprint r sessionuser id outputs notice undefined index user id in cxampphtdocsorderfoodcoreintphp on line 10require databaseconnectphprequire functionsgeneralphprequire functionsusersphprequire functionsoptionsphpiflogged in truethis is oksession user id sessionuser id not working script continues fixed i cannot explain exactly what was wrong but i removed session start from coreintphp by the way the path was written without core and i added session start in my indexphp and in the files that require logged in usersthis fixed the issue for me actualy this is appears to be a noobish mistake i had the website running in the previous windows but i accidentally deleted it and the files i provided in the ink are from an old backup which i believed has been working but that was not true sorry for noob post and thank you for your attention,['php'] +382487,jquery scroll to bottom of page im using the following to scroll to the top of a page when you click a certain link mylinktotopclickfunction html bodyanimatescrolltop0 slow return falsei want to make another link that scrolls to the bottom of the page the following is working ok i think it tries to scroll 10px down the page so if the page is shorter then it scrolls faster than it should and if the page is taller then it wont go all the way to the bottom how can i replace 10 with the window height thanks mymenulinkclickfunction html bodyanimatescrolltop10 slow return falsei know that this code jumps to the bottom of the page but it doenst scroll smoothly like i need documentscrolltopdocumentheight,['jquery'] +382524,php with mysql is slow important edit 3 running the testajax2php by itself and not ajax the duration is about the same 102103s so i guess that means the problem is in phpmysql or xampp when ran through phpmyadmin query heres the result showing rows 0 29 50 total query took 015 sec it appears the problem lies not in ajax after all but perhaps in php help please i have also just edited the question titleanswer add the following line in the hosts file located in acwindowssystem32driversetca 127001 localhostthe question beforeis it normal for jquery ajax with sql queries on the other side have the minimum duration of 1 sec i have tried get postgetjsonajaxtypepost ajaxtypeget as i have said it is the minimum it could get worse to about 3 sec even i doubt it is the sql queries though as when i try them in phpmyadmin the results come up extremely fastit does not matter also if the queries are very simple and the table only has 2 elements it would still follow the 1 sec minimum i am using the latest xampp and i do not know if it matters but i am accessing the files through localhost and 127001 thanksedit thanks for the reply guys i am running it on a local environment on the same laptop i made these files on jquery is updated the returned valuearray is json encoded i am using mysqli the database is in innodb and within are only about 5 tables and there are hardly anything on them heres a very simple sample queryindexphp var test id 2 testcall function testcall ajax url testajax2php type post data test id test id success functiondata testajax2php mysqli new mysqlilocalhost root testdb mysqliset charsetutf8 ifmysqli connect errno echo connection failed mysqli connect errno exit testreceive posttest id query select first name from tblperson result mysqliqueryquery row resultfetch allmysqli assoc echo json encoderowthe tblperson contains 50 records and there are only 4 columns according to firebug it took 103s to do that extremely simple task i am not sure what it really means but viewing through net tab in firebug the bar is entirely violet 0 and 103s waiting 103s and 0 receivingedit 2 it also does not matter if i send them as json encoderow or foreachrow as value echo valuefirst name it would still be about at least 1 sec i have tried on chrome and safari and though i cannot have the exact duration i can tell that it is about the same but for simple ajax call with no sql queries if i remember correctly it is very fast i would be back with a sample and duration output,"['php', 'mysql', 'sql']" +382550,why is the row property of nsindexpath a signed integer why is the row property of nsindexpath a signed integercould it ever take on a valid negative valueediti have not thought about this until today when i set llvm to check sign comparison this made the compiler spew out warnings whenever there was indexpathrow somearray count or similar,['objective-c'] +382554,sql server 2005 str46551 47 str36551 36 in sql server 2005 str behaves strange on some float values while rounding while searching in net i found the below code and explanations thereselect str46551 it will give 47select str36551 it will give 36i got some explanations here and here but did not get anything from there that above tsql taken from one of the explanations linkcould anyone please explain why it behaves like this,['sql'] +382572,csv export in stream from django admin on heroku we have the need to export a csvfile comprising data from the model from django admin which runs on heroku therefore we created an action where we created the csv and returned it in the response this worked fine until our client started exporting huge sets of data and we run into the 30 second timeout of the web workerto circumvent this problem we thought about streaming the csv to the client instead of building it first in memory and sending it in one piece trigger was this piece of informationcedar supports longpolling and streaming responses your app has an initial 30 second window to respond with a single byte back to the client after each byte sent either recieved from the client or sent by your application you reset a rolling 55 second window if no data is sent during the 55 second window your connection will be terminatedwe therefore implemented something that looks like this to test itimport cstringio as stringioimport csv timedef csvrequest csvfile stringiostringio csvwriter csvwritercsvfiledef read and flush csvfileseek0 data csvfileread csvfileseek0 csvfiletruncate return datadef data for i in xrange10 csvwriterwriterowiabc timesleep1 data read and flush yield dataresponse httpresponsedata mimetypetextcsvresponsecontentthisposition attachment filenametestcsvreturn responsethe http header of the download looks like this from firebughttp11 200 okcachecontrol maxage0contentthisposition attachment filenamejobentityjob2csvcontenttype textcsvdate tue 27 nov 2012 135642 gmtexpires tue 27 nov 2012 135641 gmtlastmodified tue 27 nov 2012 135641 gmtserver gunicorn0146vary cookietransferencoding chunkedconnection keepalivetransferencoding chunked would indicate that cedar is actually streaming the content chunkwise we guessproblem is that the download of the csv is still interrupted after 30 seconds with these lines in the heroku log20121127t1300240 appweb1 debug exporting tasks in csvstream for job id 56 20121127t1300540 appweb1 20121127 130054 2 critical worker timeout pid520121127t1300540 herokurouter atinfo methodpost pathadminjobentity hostmyappherokuappcom fwd dynoweb1 queue0 wait0ms connect2ms service29480ms status200 bytes5109220121127t1300540 appweb1 20121127 130054 2 critical worker timeout pid520121127t1300540 appweb1 20121127 130054 12 info booting worker with pid 12this should work conceptually right is there anything we missedwe really appreciate your helptom,['python'] +382575,installing mariadb on mac i am using mac ports to install the mariadb with the following commandsudo port install mariadbserver after the file is installed i have no idea whats going on nexti try to find any configuration guidance but i failed does anybody have some guidance for the next steps after installing from mac ports like how to start and stop configure etc,['php'] +382580,php unicode accentuated char and diacritics in our website some mac users have troubles when they copypaste text from pdf files into a textarea handled by tinymce all accentuated char are corrupted and became for example e for a a i for a a etc i cannot reproduce this problem with a windows computerwhen i wrote the content of the textarea on a file before inserting it in the database i just thiscovered that the initial ei is visually different that a traditionnal a on vim see belowindeed the corrupted a first line of the screenshotecho bin2hexchar thisplay 65cc81 traditionnal aecho bin2hexei thisplay c3a9after searching a lot here i am it seems that mac os copies unicode accentuated chars as a combination of two chars in our example e i so far i did not find any solution to replace corrupted a with the real one to avoid e in the databaseand i am a little desperate,['php'] +382583,how to get requestcode from pending intent at the time of alarm in android is it possible to get requestcode at the time of intent either in receiver class or activity classand this was my pending intent alarmmgr alarmmanagergetsystemservicecontextalarm service intent intent new intentthis broadcastreceiver classclass intentputextraalarm time minutes minutes pendingintent pendingintentgetbroadcastthis requestcode intentrequestcode alarmmgrsetalarmmanagerrtc wakeup calgettimeinmillis pendingintentthanks in advance,['android'] +382621,keypress event equivalent in wpf i have the following code in wpa and i am trying to convert it to wpf i tried keydown instead of keypress and changed for example ekeychar to ekey esubtractits not working the samei cant find the equal sign within ekeyfirst codepublic partial class form1 form public form1 initializecomponent foreach textbox tb in thiscontrolsoftypetextbox tbenter textbox enter void textbox enterobject sender eventargs e focusedtextbox textboxsender private void form1 keypressobject sender keypresseventargs e if ekeychar operand1real getoperandreal operand1imag getoperandimag flag1 1 ehandled true else if ekeychar if focusedtextbox null if focusedtextboxtext ehandled false else ehandled true operand1real getoperandreal operand1imag getoperandimag flag1 2 else if ekeychar operand1real getoperandreal operand1imag getoperandimag flag1 3 ehandled true else if ekeychar operand1real getoperandreal operand1imag getoperandimag flag1 4 ehandled true else if ekeychar ehandled true operand2real getoperandreal operand2imag getoperandimag switch flag1 case 1 operand1 operand1 operand2 break case 2 operand1 operand1 operand2 break case 3 operand1 operand1 operand2 break case 4 if operand2magnitude 0 textbox1clear textbox2clear messageboxshowcannot divide by a number whose magnitude is zero operand1 new complex operand2 new complex listbox1clearselected else operand1 operand1 operand2 break string s operand1tostring if flag 1 string s1 ssplit if s11 textbox1text s10 textbox2text s13 else textbox1text s10 textbox2text s13 else if flag 2 string s1 ssplit textbox1text s10trim textbox2text s11trim listbox1itemsaddoperand1 second codeprivate void win keydownobject sender keyeventargs e if ekey keyadd operand1real getoperandreal operand1imag getoperandimag flag1 1 ehandled true else if ekey keysubtract if textbox2text ehandled false else ehandled true operand1real getoperandreal operand1imag getoperandimag flag1 2 else if ekey keymultiply operand1real getoperandreal operand1imag getoperandimag flag1 3 ehandled true else if ekey keydivide operand1real getoperandreal operand1imag getoperandimag flag1 4 ehandled true else if ekey keyenter ehandled true operand2real getoperandreal operand2imag getoperandimag switch flag1 case 1 operand1 operand1 operand2 break case 2 operand1 operand1 operand2 break case 3 operand1 operand1 operand2 break case 4 if operand2magnitude 0 textbox1clear textbox2clear messageboxshowcannot divide by a number whose magnitude is zero operand1 new complex operand2 new complex listbox1unselectall else operand1 operand1 operand2 break string s operand1tostring if flag 1 string s1 ssplit if s11 textbox1text s10 textbox2text s13 else textbox1text s10 textbox2text s13 else if flag 2 string s1 ssplit textbox1text s10trim textbox2text s11trim listbox1itemsaddoperand1,['c#'] +382659,java static members in a subclass accessed via a generic parent this seems like a newbish question but the last time i worked with java the language did not have generics i have a class hierarchy names changed to be as generalized as possiblepublic abstract class abstractbase public class concreatesuba extends abstractbase public class concreatesubb extends abstractbase public class concreatesubzz9pluralzalpha extends abstractbase i am trying to clean up some legacy code and there is one place where a ton of repetitive duplication can all be factored out into a single routine via generics i am thinking generics because when this routine is called it needs to operate on only one of the concrete classesthe routine looks likepublic thing extends abstractbase void somefunc another function call thingconcretespecialtoken could also be another function call thingconcretespecialtoken if methods are more feasible than fields cannot use another function call thingconcretespecialtoken because creating instances of these types is a major operationtmi am leaving out about a zillion lines but that is the important part somefunc is type parametric it actually takes arguments but none of them are things so no inference eventually i need to fetch a special token and this is where i am getting fuzzythe tokens are hugeass unique strings for each concrete class they are classbased not instancebased the actual token value is declared as a private static final field in each subclaso i need to use the public methodsfields of a base class to eventually get to the private static field of a subclass obviously i cannot declare an abstract static method in the base because that makes no sense if the data were instancebased then this would be trivial with a polymorphic getter in the base class but the subclass stuff is statici feel like i am missing a feature of java generics here but i cannot use thingwhatever unless the whatever is something that is possible to declare in the abstract base class i am running up against either limitations of java or my lack of expertise trying to bridge the gap the one attempt i made that seemed promising also had a ton of code duplication all the way down the class hierarchy defining abstract methods with the exact same code over and over which is what generics are supposed to help prevent,['java'] +382670,regular expression to match a quoted string embedded in another quoted string i have a data source that is commadelimited and quotequalified a csv however the data source provider sometimes does some wonky things i have compensated for all but one of them we read in the file linebyline then write it back out after cleansing and i am looking to solve the last remaining problem when my regexfu is pretty weakmatching a quoted string inside of another quoted stringso here is our example stringfoobar 356 lieudit chez matral chilly fr 109 467 barfoo 1345456235231 93518i am looking to match the substring chez matral in order to replace it with the substring chez matral ideally in as few lines of code as possible the final goal is to write the line back out or return it as a method return value with the replacement already doneso our example string would end up asfoobar 356 lieudit chez matral chilly fr 109 467 barfoo 1345456235231 93518i know i could define a pattern such as quotedstringw to match quoted strings but my regexfu is weak database developer almost never use c so i am not sure how to match another quoted string within the named group quotedstringfyi for those noticing the large integer that is formatted with commas but not quotequalified that is already handled as is the random use of rowdelimiters sometimes cr sometimes lf as other problems,['c#'] +382681,how to use numpywhere with logical operators i am trying to find the indices of all elements in an array that are greater than a but less than b it is probably just a problem with my syntax but this does not worknumpywheremy array a and my array bhow should i fix this or is there a better way to do itthanks,['python'] +382683,how to raise a custom error code in sinatra i did the following in my sinatra appthisable show exceptionsthisable raise errorserror do haml error locals error message requestenvsinatraerrorto sendget error do raise errorendif i visit error i get a 500 internal server error response code which is god and wanted but how do i change the code to eg 404 or 501the answerthisable show exceptionsthisable raise errorsget error do halt404hamlerror locals error message requestenvsinatraerrorto send,['ruby'] +382685,the matching wildcard is strict but no declaration can be found for element contextcomponentscan i am getting the following errors while trying my first spring projectcaused by orgxmlsaxsaxparseexception cvccomplextype24c the matching wildcard is strict but no declaration can be found for element contextcomponentscanhere is the applicationcontextxmlxml version10 encodingutf8beans xmlns xmlnsxsi xmlnsp xmlnsaop xmlnstx xmlnscontext xsischemalocation contextcomponentscan basepackagecomxyz beanswhat is causing the error,['java'] +382686,facebook php sdk getuser suddenly returns 0 first of all to get this out of the way i have spent hours looking through answers to this question here on stackoverflow and tried to solve it on my own but it just is not working anymore so anywayyesterday everything worked fine went to bed woke up login with facebook did not work anymore on 2 of my websites the login link sends me to the facebook page which requires me to approve the app but after it redirects me back to the site it does not log me in i quickly tracked the problem to getuser always returning 0 so i set up a new test app with a very very basic code just to see if that works it does not heres the codephp session start require oncefacebookphp config array configappid 1971880127910 test app so i do not mind showing these configsecret e065588cb1edd96f821de8b3d362c488 configtrustforwarded true facebook new facebookconfig try user facebookgetuser var dumpuser catch exception e egetmessage loginurl facebookgetloginurlarrayredirect uri echo a hrefloginurlloginathe second answer in here caught my eye i tried that solution and it did not work so i opened up base facebookphp and scrolled to the line where that code is passed to some variable line 458code thisgetcodei echod this and it thisplayed correctly the code parameter that was passed from the url the problematic line turns out to be the one couple rows below that one access token thisgetaccesstokenfromcodecodethis function returns a value of false to access token when passed the code variable in that function this part of the code throws an exceptiontry need to circumvent json decode by calling oauthrequest directly since response is not json format access token response this oauthrequest thisgeturlgraph oauthaccess token params arrayclient id thisgetappid client secret thisgetappsecret redirect uri redirect uri code code catch facebookapiexception e most likely that user very recently revoked authorization in any event we do not have an access token so say so print re return false print re thisplays a huge blob of gibberish i am somewhat of a noob so i cannot read almost anything from it that makes sense the only thing that i see repeating in there isl certificate problem verify that the ca cert is ok details error14090086ssl and this is how far i have come with debugging this any help is appreciated once again yesterday everything was working fine today without a single line of code changed it does not work anymore mind boggling oh yeah i am running wamp with php 543edit heres the error message edit2 solvedin base facebookphp add the following 2 lines under curl optscurlopt ssl verifypeer falsecurlopt ssl verifyhost 2which makes itpublic static curl opts array curlopt connecttimeout 10 curlopt returntransfer true curlopt timeout 60 curlopt useragent facebookphp32 curlopt ssl verifypeer false curlopt ssl verifyhost 2 i am not sure how much of a security issue this is but it makes the login with facebook work so there you have it and there i have it entire day lost on this fmledit3 new sdk released which fixes this problem,['php'] +382721,delegating constructors an initializer for a delegating constructor must appear alone i have a pair of constructors that work just fine in c03 style one of the constructors calls a superclass or base class constructor class window public rectanglepublic window winnew rawwindowthis refresh windowrectangle rect rectangle rect winnew rawwindowthis refresh i am trying to figure out how to use the new c11 delegating ctor functionality to neaten this up a little however the following code gives the following compiler error class window public rectanglepublic window winnew rawwindowthis refresh windowrectangle rect rectangle rect windowan initializer for a delegating constructor must appear alone is there any way around this,['c++'] +382752,does python optimize tail recursion i have the following piece of code which fails with the following errorruntimeerror maximum recursion depth exceededi attempted to rewrite this to allow for tail recursion optimization tco i believe that this code should have been successful if a tco had taken placedef trisumn csum if and 0 return csum else return trisumn 1 csum nprinttrisum10 0should i conclude that python does not do any type of tco or do i just need to define it differently,['python'] +382755,load image from resources i want to load the image like thisvoid infostring channel something like that channelpicimage propertiesresourceschannelbecause i do not want to dovoid infostring channel switchchannel case chan1 channelpicimage propertiesresourceschan1 break case chan2 channelpicimage propertiesresourceschan2 break is something like this possible,['c#'] +382813,how to get around lack of covariance with ireadonlydictionary i am trying to expose a readonly dictionary that holds objects with a readonly interface internally the dictionary is writeable and so are the objects within see below example code my problem is that ireadonlydictionary does not support covariant conversions because of the reason outlined in the question here this means i cannot just expose my internal dictionary as a read only oneso my question is is there an efficient way to convert my internal dictionary to an ireadonlydictionary or some other way to handle this the options i can think of arehold two internal dictionaries and keep them in synccreate a new dictionary when the property is accessed and cast all the objects withincast the ireadonlys back to notreadonly when using it internally1 seems like a pain 2 seems highly inefficient 3 sounds like the most promising at the moment but is still ugly do i have any other optionspublic class exposesreadonly private dictionaryint notreadonly internaldict get set public ireadonlydictionaryint ireadonly publiclist get this does not work return thisinternaldict this class can be modified internally but i do not want to expose this functionality private class notreadonly ireadonly public string name get set public interface ireadonly string name get,"['c#', '.net']" +382817,what is the difference between uriescape and uriencode in ruby i am trying to figure out a difference between a uriescape and uriencode in ruby neither is doing what i want them to which is to completely encode an urlfor example i want to be http3a2f2fmy2eweb2ecom,['ruby'] +382818,does not work setting default value of property in hibernate i have a boolean property in my entity heres my annotations for itcolumnname is active nullable false columndefinitionbit default 1 length 1public boolean getactive return isactivebut columndefinitionbit default 1 doent work perfectly heres sql code i get as result for generated tableis active bit1 not nullwhat am i doing wrongand so when i try to save an instance of this class to the database i get the exceptioncommysqljdbcexceptionsjdbc4mysqlintegrityconstraintviolationexception column is active cannot be nullif i remove nullable false propertycolumnname is active columndefinitionbit default 1 length 1public boolean getactive return isactiveso i can save a created object in this case but it is still the default value is not set and i get null in the value of this field in databaseany ideas please i use mysql server 51 if it is important i would be very grateful for any help thanks in advance,['java'] +382823,mapsetview on windows phone 8 is there a specific time in the pages lifecycle that the mapsetview function should be called in our app we use this on various map objects and it seems to work randomly sometimes perfectly and sometimes with no effect but also no exception example coderoutemapsetviewlocationrectanglecreateboundingrectangledirectioncoordinateswhere routemap is the mapping component and directioncoordinates contains the startend coordinates for the mapi can see that the bounding box is being created properly but the maps positioning is not always being affected even loading the same data if i add a break point it does seem to work so i was assuming it had something to do with the map loading but adding the setview functionality to the loaded event has the same issue we currently process the map information in the page loaded eventupdatei have been testing more and added events to what i could i know for a fact that the maploaded event is being called before setview after setview is called it is working sometimes and not others neither viewchanging or viewchanged events are called,['c#'] +382869,getting dynamic attribute in python i have and object with an pseudo or special attribute that can be named in three different ways note i do not control the code which generates the objectthe value in the attributes depending which one is set is exactly the same and i need to get that for further processing so depending of the source of data i can have something like objavalue objbtraceback most recent call last file stdin line 1 in moduleattributeerror obj instance has no attribute b objctraceback most recent call last file stdin line 1 in moduleattributeerror obj instance has no attribute cor objatraceback most recent call last file stdin line 1 in moduleattributeerror obj instance has no attribute a objbvalue objctraceback most recent call last file stdin line 1 in moduleattributeerror obj instance has no attribute cor objatraceback most recent call last file stdin line 1 in moduleattributeerror obj instance has no attribute a objbtraceback most recent call last file stdin line 1 in moduleattributeerror obj instance has no attribute b objcvaluei am interested in getting value and unfortunately dict property does not exist in that object so what i ended doing for getting that value was just do a bunch of getattr calls assuming that possibilities are only three the code looked like this g lambda o l getattro l0 getattro l1 getattro l2 none gobj a b cvaluenow i would like to know whether there is a better way to this as i am 100 convinced what i have done thanks in advance,['python'] +382884,how to listen for preference changes within a preferencefragment as described here i am subclassing preferencefragment and thisplaying it inside an activity that document explains how to listen for preference changes here but only if you subclass preferenceactivity since i am not doing that how do i listen for preference changesi have tried implementing onsharedpreferencechangelistener in my preferencefragment but it does not seem to work onsharedpreferencechanged never seems to get calledthis is my code so farsettingsactivityjavapublic class settingsactivity extends activity override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate thisplay the fragment as the main content getfragmentmanagerbegintransactionreplaceandroidridcontent new settingsfragmentcommit settingsfragmentjavapublic class settingsfragment extends preferencefragment implements onsharedpreferencechangelistener public static final string key pref exercises pref number of exercises override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate load the preferences from an xml resource addpreferencesfromresourcerxmlpreferences override public void onsharedpreferencechangedsharedpreferences sharedpreferences string key it never gets in here if keyequalskey pref exercises set summary to be the userdescription for the selected value preference exercisespref findpreferencekey exercisesprefsetsummarysharedpreferencesgetstringkey preferencesxmlxml version10 encodingutf8preferencescreen xmlnsandroid edittextpreference androiddefaultvalue15 androidenabledtrue androidkeypref number of exercises androidnumericinteger androidtitlenumber of exercises preferencescreenalso is the preferencefragment even the right place to listen for preference changes or should i do it within the activity,['android'] +382885,how to throw a custom fault on a jaxws web service how do you throw a custom soap fault on a jaxws web service how can i specify the faultcode faultstring and detail of the soap fault is it possible to set the value of the detail as bean instead of a stringplease note that i am developing using codefirst approach,['java'] +382895,android image resizing and preserving exif data orientation rotation etc if your android app uses the device camera to take a picture and then resizes it this is very very common to reduce the size for upload you might not realize that this resize operation strips the exif metadatathis can cause problems especially if the device in question relies on the orientation tag to properly show the image uprightdifferent android devices handle cameraimage rotation in different ways my trusty ol nexus one seems to always rotate the image immediately post capture so the files native contents are always upright when viewed however other devices especially samsung phones in my testing do not rotate the contents of the image file rather they set the exif orientation tag whenever the image is thisplayed later the relevant image code should detect the presence of the orientation tag and rotate the image appropriately but if you have done any bitmap processing on the image and saved it to a new file all of that exif data is lostin addition to orientation data you might also lose other valuable metadata such as makemodel etcthis confused me for a few weeks image appears upright when thisplayed in phone gallery but then arrives on my server with bad orientation and no apparent metadata i am adding this selfquestion here to help others this blog post was very helpful,['android'] +382902,from xmlgregoriancalendar to datecalendar adds extra timeunwanted iam developing a client to a web service which exposes wsdl contract which requires ymmdd format for 1 on the request parameters however auto generated pojos based on the wsdl create the date attribute as type xmlgregoriancalendarmy issue is not converting to or from xmlgregoriancalendar see my utility belowpublic static xmlgregoriancalendar toxmlgregoriancalendarcalendar c gregoriancalendar gc new gregoriancalendar gcsettimeinmilliscgettimeinmillis xmlgregoriancalendar xc nulltry xc datatypefactorynewinstancenewxmlgregoriancalendargc catch datatypeconfigurationexception e todo autogenerated catch block eprintstacktrace return xcmy issue is going from xmlgregoriancalendar to datecalendar adds extra timeunwanted data to my ymmdd when calling calendargettime in a particular code segment i need to go from xmlgregoriancalendar to dateif repairordertypegetclosedate null logdebugservicehistorymapper processrepairorders repairordertypegetclosedate before repairordertypegetclosedate string date repairordertypegetclosedategetyear repairordertypegetclosedategetmonth repairordertypegetclosedategetday approach 1 trying to remove hourminutesec values by calendarclear method not successful calendar calendar calendargetinstance calendarsetrepairordertypegetclosedategetyear repairordertypegetclosedategetmonth repairordertypegetclosedategetday calendarclearcalendarhour calendarclearcalendarminute calendarclearcalendarsecond calendarclearcalendarmillisecond approach2 trying to remove hourminutesec values using simpledateformat also not successful simpledateformat or dateformat are use to format string output not remove internal data dateformat formatter new simpledateformatymmdd calendar calendar formattergetcalendar calendarsetrepairordertypegetclosedategetyear repairordertypegetclosedategetmonth repairordertypegetclosedategetday logdebugservicehistorymapper processrepairorders repairordertypegetclosedate after calendargettime repairordersetclosedatecalendargettime output27nov2012 181039743 debug comtmsownersintegrationnshmappingservicehistorymapper servicehistorymapper processrepairorders repairordertypegetclosedate before2012043027nov2012 181051413 debug comtmsownersintegrationnshmappingservicehistorymapper servicehistorymapper processrepairorders repairordertypegetclosedate afterwed may 30 180 pdt 2012as you can see above before date is before20120430 and after date is may 30 180 pdt 2012 with unwanted hours 180 pdtbelow is my actual request xml sent to the servicesenvelope xmlnss sbody ns4vehicleservicehistorydetails xmlnsurntmstoyotacomcomponents xmlnsns2urnesbarixcom20081210schemascommoncustomer xmlnsns3urnincentivesarixcomstandardheader xmlnsns4urnesbarixcom20081210schemashistory xmlnsns5 xmlnsns6urnarixcomrtmheader ns5applicationarea ns5creationdatetime20121127t1811230710800 ns5creationdatetime ns5sender ns5userarea ns5applicationarea ns4vehicleservicehistorydataarea ns4vehicleservicehistoryheader ns3timestamp20121127t1811230710800ns3timestamp ns3sourcesystemtoons3sourcesystem ns4sourcekeytoy1twxens4sourcekey ns4vehicleservicehistoryheader ns4vehicleservicehistory ns4vinxns4vin ns4repairorder ns2repairorderdealer dealernumber29059dealernumber ns2repairorderdealer ns2repairordernumber0088745ns2repairordernumber ns2closedate201205300700ns2closedate ns4repairorder ns4vehicleservicehistory ns4vehicleservicehistorydataarea ns4vehicleservicehistorydetails sbodysenvelopeyou can see in the request xml in the 201205300700 that extra 0700 data is added i just want 20120530thanks,['java'] +382930,call class method in background using objective c in the below excerpta classname with instancemethod and classmethod voidinstancemethodvoidclassmethodto call a instance method in background classname class1obj classname alloc initclass1obj performselectorinbackgroundselectorinstancemethod withobjectnilsimilarly how to call a classmethod in background using performselectorinbackgroundif possible please explainplease guys join hands,"['iphone', 'objective-c', 'ios']" +382964,tpl dataflow how to forward items to only one specific target block among many linked target blocks i am looking for a tpl data flow block solution which can hold more than a single item which can link to multiple target blocks but which has the ability to forward an item to only a specific target block that passes a filterpredicate at no time should an item be delivered to multiple target blocks at the same time always only to the one which matches the filter or the item can be thiscarded i am not fond of broadcastblock because if i understand correctly it does not guarantee delivery or does it and the filtering is done on the target block side meaning broadcastblock essentially sends copies of each item to all linkedto target blocks it also does not hold more than one item at any time if i understand correctly i do not want to use postasync but maintain a linkto chain is there a way around a complete custom data flow block or am i misunderstanding how broadcastblock works unfortunately there really is not much documentation out there that goes into detail and covers use cases any ideas are highly appreciated,['c#'] +382972,jquery ui what files do i need i am implementing tabs in a websitei want to use this jquery ui widget there are other uses of jquery on the website but not jqueryui only in this particular placeso i am trying to include only the needed parts of jqueryuihow can i determine what minimum parts of js code have to be included,['jquery'] +383006,extract data from xml clob using sql from oracle database i want to extract the value of decision using sql from table traptabclob having column testclob with xml stored as clob sample xml as below xml version10 encodingutf8dcresponse statussuccestatus authentication statussuccestatus authentication responseinfo applicationid5701200applicationid solutionsetinstanceid 63a5c214b5b54c459f1eb839a0409c24 solutionsetinstanceid currentqueue responseinfo contextdata decision details start field keysoftdecisionafield field keydecision1field field keynodeno402field field keynodedescription decision details end error details start field keyerrorresponse response statusstatusstatus errorcodeerrorcodeerrorcode errordescriptionerrordescriptionerrordescription segmentsegmentsegment response field field keyerrorcode0field field keyerrordescription contextdatadcresponse,['sql'] +383015,what do the parentheses around a function name mean in one of my project source files i found this c function definitionint foo int bar return foo barnote there is no asterisk next to foo so it is not a function pointer or is itwhat is going on here with the recursive call,['c'] +383055,how do i find the difference between two values without knowing which is larger i was wondering if there was a function built into python that can determine the thistance o between to rational numbers but without me telling it which number is largeriethistance633thistance363obviously i could write a simple definition to calculate which is larger and then just do a simple subtraction def thistancex y if x y result x y else result y x return resultbut i would rather not have to call an in house function like this from my limited experience i have often found python has a built in function or a module that does exactly what you want and quicker than your code does it hopefully someone can tell me there is a built in function that can do this,['python'] +383056,javalangsecurityexception requires vibrate permission on jelly bean 42 since yesterday i have an issue on android 42 when i receive push notifications it requires the permission even if i do not set it to vibratenotification notification new notificationicon notificationitemmessage whennotificationsetlatesteventinfocontext app notificationitemmessage pendingintentgetactivitycontext 0 intent 0notificationflags notificationflag auto cancelnotificationdefaults notificationdefault soundnotificationmanager nm notificationmanagercontextgetsystemservicecontextnotification servicenmnotifynotificationitemnotificationid notificationthe exception is raised by nmnotifyi have this issue in two different apps and i never modify the code,['android'] +383063,is it possible to get reference to listview from adapter in android is it possible to get reference to listview from adapter in android without passing it as an argument to constructor,['android'] +383129,which boost libraries are headeronly which boost libraries are header only and which require building libsdoes such a list exist,['c++'] +383142,c linq orderby filtering null or empty values to be last i try to make my custom orderby extension method i successfully worked my code but in addition i want to list null or empty or zero values last in result anyone can help me about that issue here is my extension method to orderby public static iqueryablet orderbytthis iqueryablet q string sortfield bool isasc var nullexpr expressionconstantnull typeoft var param expressionparametertypeoft p var prop expressionpropertyparam sortfield var exp expressionlambdaprop param string method isasc orderby orderbydescending type types new type qelementtype expbodytype var mce expressioncalltypeofqueryable method types qexpression exp return qprovidercreatequerytmce thanks in advance,['c#'] +383179,requirejs difference between requirejs and require functions i am using requirejs 2x i found out that some tutorials and the official docs sometimes use requirejsconfig requirejsmodule and sometimesrequireconfig requiremodule is there any difference between those two functions require and requirejs i could not find any word about that in the docs,['javascript'] +383202,embedded object not instantiated automatically if it has no basic datatype fields fundamental question why are not embedded objects always instantiatedthe interesting observation is that ebean does not instantiate embedded objects if those do not contain basic datatypes int boolean or werent touched before exampleentitypublic class embedder getnotautoinstantiated will return null if this field was not touched before embedded private notautoinstantiated notautoinstantiated new notautoinstantiated getautoinstantiated will always return an instance embedded private autoinstantiated autoinstantiated new autoinstantiatedembeddablepublic class autoinstantiated thekey is why this embedded object is always instantiated private int thekey private string field1 embeddablepublic class notautoinstantiated private string field2,['java'] +383203,html change language using elementlang first question on stack so hurray to mei am trying to develop a new way apparently since i have seen no solution to this online perhaps cos it is not possible to change the language of html written elements using js and the lang propertybasically i have created multiple tags with the lang property in each of them so that giving the certain lang a thisplay value of none hides it and a value of inherit to show itin that way using the linealangenplangen thisplay none alangitplangit thisplay inherit i can see one language at a time and that worksnow i have created an a href langen iden word atag around the english text and the same with any other language with their own lang propertyi have tried to useenclickfunction alangencssthisplay inherit alangitcssthisplay none which does not seem to workany ideasthanks a bunchshay,"['javascript', 'html']" +383246,right aligning text in pdfpcell i have a c application that generates a pdf invoice in this invoice is a table of items and prices this is generated using a pdfptable and pdfpcellsi want to be able to rightalign the price column but i cannot seem to be able to the text always comes out leftaligned in the cellhere is my code for creating the tablepdfptable table new pdfptable2tabletotalwidth invoicepagesizewidthfloat widths invoicepagesizewidth 70f 70f tablesetwidthswidthstableaddcellnew phraseitem name tableheadfonttableaddcellnew phraseprice tableheadfontsqlcommand cmditems new sqlcommandselect conusing sqldatareader rdritems cmditemsexecutereader while rdritemsread tableaddcellnew phraserdritemsitemnametostring tablefont double price converttodoublerdritemsprice pdfpcell pcell new pdfpcell pcellhorizontalalignment pdfpcellalign right pcelladdelementnew phrasepricetostring0 tablefont tableaddcellpcell can anyone help,['c#'] +383278,how to scroll a web page using watir i am trying to scroll a web page to find and click on a content that is lazily loaded when the page is scrolled i am using following commandrequire watirwebdriverbrowser watirnew firefoxbrowsersend keys spacei am using webdriver with firefox and i am on ubuntu but it is not working in the following ruby code i am trying to scroll the page down until i do not find the element with id the element is loading lazilyi am getting timeout after few seconds any idea what is wrong with the following code when deal d is loaded do id 05each do click browsersend keys space endendwhat is the best way to scroll a page using watirdriver,['ruby'] +383358,best practice or workaround for rspec specs faking class constants let us say i have classes car and mechanic car has run method mechanic requires car for some reason then i write rspec specs in mechanic i define a fake clas like thisclass car endand later stub the method that mechanic uses on it all works fine if i run tests seperately but when i run both tests together rspec specdirectory my mechanic specs use real car claso i guess this is because ruby classes are open and i already loaded the class once for car specs but is there a better way to do this what are best practices for this kind of situations does this mean my code needs some improvements cause it is probably tightly coupledi made a quick demo in github,['ruby'] +383369,classnotfoundexception netsourceforgejtdsjdbcdriver i am running into javalangclassnotfoundexception netsourceforgejtdsjdbcdriveri can get around the error by putting jtdsjar file in the catalina homelib directory but this is not an ideal solution as the application should be modular enough to be deployable on any server i have the jtdsjar file in tomcat dirwebappsmyappwebinflib which is where i want it to be found from i know there are tons of similar questions so i apologize if this is a duplicate but i have yet to be able to find a post that helps why cannot my app find the correct jtdsjar file which i have included in the app package what do i need to do in order to get the app to recognize that jar file,['java'] +383384,represent an int as 2 bytes in java i need to represent a value of 0xff00 as two bytes in java i am trying to do it like thisint val 0xff00bytearray0 byteval 8 0xffbytearray1 byteval 0 0xffi know that byte in java can hold values 0255 so i expect the first array element to have a value of 255 and the second element to be zero but what i am getting instead is 1 and 0 what i am doing wrong what this 1 value mean,['java'] +383432,testing multiple android devices on one machine i have two different android devices plugged into the same machine what i would like to do is to target each device and execute a test on it separatelyunfortunately it seems as if i need to unplug one of the devices to run the test each time because if i do not i receive the following errorerror more than one device and emulatordoes anyone know of a workaround for this issue so that i can simply keep both devices plugged in and run my tests,['android'] +383444,internal property setters in c i am trying to figure out a good way to approach this i have a customer class which implements the icustomer interface this interface has a number of properties in itpublic interface icustomer string firstname get set string lastname get seti only want certain classes to have the ability to set those properties however namely those classes in the project so i thought about making the setter internalpublic class customer icustomer string firstname get internal set string lastname get internal seti would like to mark that setter as internal in the interface however so there is no chance someone implements icustomer and someone outside the assembly modifies those properties is there a good way to do this,['c#'] +383512,is there a way to add reminders to a new calendar event using intents i need to support android 21 and up i know that calendarcontract is not available in android 21 so i have done the following workaroundintent intent new intentintentaction edit settypevndandroidcursoritemevent putextrabegintime begintimegettimeinmillis putextratitle title putextradescription description putextraeventlocation location putextraallday allday putextraintentextra email email ifallday intentputextraendtime endtimegettimeinmillis startactivityintentthis works very well so far i have tested on 21 through 41i would like to add reminders too but i cannot find any documentation on how to do it using intents does anyone have an example i want to avoid adding more permissions to my manifest for writing to the calendar so if you have a suggestion that requires that i would not be able to use it,['android'] +383527,how do i catch a websocket connection interruption in firefox at least if you hit esc then it will close all open websockets connectionsi need to capture that thisconnection and try to reconnect once it is available againheres an example of the code i have tried to implement but nothing i can figure out will catch the error and allow me to handle it gracefullyhave a look at the code var url wsechowebsocketorg try socket windowmozwebsocket new mozwebsocketurl new websocketurl socketonopen function consolelogsocket is now open socketonerror function error consoleerrorthere was an unidentified web socket error socketonmessage function message consoleinfomessage o messagedata catch e consoleerrorsorry the web socket at s is unavailable url settimeoutfunction socketsendhello world 10turn on your console and watch the outputam i doing something wrong here or is it just not possible because the connection is running outside of the scope of the js scriptany input would be helpfulthanks,['javascript'] +383541,installation failed due to invalid uri installs only in debug mode what are the possible causes of android failed to install invalid uri what uri is this referring to and in what way is it invalid it works fine in debug mode but i cannot get it to install outside of debug modethanks,['android'] +383542,what makes editors paste data on textarea as html like in rich wysiwyg editors i want to copypaste html from websites and store them in mysql database to do this i have checked out ckeditor which allows me to paste html even word documents and it generates html code for it since all i want is to generate the pasted data as html instead of using a full wysiwyg editor like ckeditor i want to write some code perhaps with jquery to convert the pasted data to have html tags and formattingto achieve this functionality what do these online editors do how do they convert the clipboard data to html code why do i get only text when i paste html formatted text or divs or buttons to this textarea here and images and properly sized divs on wysiwyg editors do the editors access the clipboard data and manipulate it does clipboard save formatting data in an organized manner allowing the ckeditor or others to manipulate itcan this be done with jquery or do we need serverside code as wellif you can shed some light on this subjects i would appreciate it i only want to know the method so that i can write appropriate code for itfor reference,"['javascript', 'html']" +383617,how to generate temporary file in django and then destroy i am doing some file processing and for generating the file i need to generate some temporary file from existing data and then use that file as input to my functionbut i am confused where should i save that file and then delete itis there any temp location where files automatically gets deleted after user session,['python'] +383649,prevent clickable div from being highlighted in android webview i am using a fullscreen webview in an android app using api level 15 there are some onoff switches that i am making clickable with jquerys click function the approach works fine but the click handler causes the button to be highlighted in a transparent shade of blue when the element is tapped and it is unsightlynone of these approaches worked to prevent the element from being highlighted css approach divpill outline noneclick approachdivpillclickfunctionevent other code here eventstoppropagation eventpreventdefault return falsemousedown approachdivpillmousedownfunctionevent other code here eventstoppropagation eventpreventdefault return falsehere is an example of the div with a blue highlightdoes anyone know how to prevent a clickable div from being highlighted when it is clicked,['android'] +383686,jpahibernate cycles in entity relationships cascade strategy i have a set of entities that connect to each other forming a cycle ie parent entity p has two onetomany relationships with two child entities c1 and c2 and each one of these has a onetomany relationship with another entity a entity a realises the association of these entities c1c2 and defines the relationships attributes it is not just a join table all the relationships are navigable in both directions the following question arises from this design what should be the cascade strategy so that entity a can be persistedmerged given that you always invoke entity manager operations on the root entity p should a be cascade reachable from both pathsconsiderations it seems that if the application chooses to provide only one cascade path there can be scenarios that throw a transientobjectexception if it provides both paths then these paths have to make the full cycle as for example c1 could be attempted to be saved through a versions jpa 20 hibernate core 417 hibernatejpa20api 101,['java'] +383698,what is a good usage of the isoperator what is a good usage of the isoperatorthe construct below for casting is not the recommended way to go virtually all documentation prefers the asoperator with a nullcheckifobj is someclass someclass some someclassobj and sure this is a very small performance increase and some even mention the tread safetyand yes this is trueso why do we have the isoperatorwhere does the asoperator with a nullcheck not work or is not the way to godoes is have an advantage to restrict the scope of you declaration you get by using the isoperator,['c#'] +383735,jave ee application does not recognize google visualization api i would like to include the charts of google visualization api in my java ee application however whatever i do the application does not recognize the api i have used it like this before so i do not understand what i am doing wrong could someone look at my code and tell me what i am doing wrong thanks taglib prefixc uri page contenttypetexthtmlcharsetutf8 languagejava link typetextcss hreflocationstylenamecss relstylesheetscript srctisjavascriptcommonjqueryinlinemenujs typetextjavascriptscriptscript typetextjavascript srcscript script typetextjavascript load the visualization api and the piechart package googleloadvisualization 10 packagescorechart set a callback to run when the google visualization api is loaded googlesetonloadcallbackdrawchart callback that creates and populates a data table instantiates the pie chart passes in the data and draws it function drawchart create the data table var data new googlevisualizationdatatable dataaddcolumnstring topping dataaddcolumnnumber slices dataaddrows mushrooms 3 onions 1 olives 1 zucchini 1 pepperoni 2 set chart options var options titlehow much pizza i ate last night width400 height300 instantiate and draw our chart passing in some options var chart new googlevisualizationpiechartdocumentgetelementbyidchart div chartdrawdata options scriptdiv that will hold the pie chart div idchart divdivthe errors are the followingreferenceerror google is not definedthe method setonloadcallback is underlined and says unresolved function or method setonladcallback,['java'] +383744,log4net adonet appender connection issue i have developed a windows service in which i am using a timer control to perform some scheduled tasks the timer elapse event occurs every 5 minutes in which a log entry is made using log4net appender to oracle databaseall works fine until the db server closes all connections for nightly cold backup since that time all logs in db are missed and nothing is logged unless service is restarted even though the backup process takes less than 30 minsfrom other posts i found that log4net uses only one connection which if lost then all subsequent logs are thiscarded to remedy this i started using reconnectonerror attribute set as true in its configuration but unfortunately the issue is still there the logs are still missing after the backup i enabled tracing and found following errors but i do not know how to resolve this issuelog4neterror customadonetappender exception while writing to database oracledataaccessclientoracleexception ora03113 endoffile on communication channel at oracledataaccessclientoracleexceptionhandleerrorhelperint32 errcode oracleconnection conn intptr opserrctx oposqlvalctx poposqlvalctx object src string procedure at oracledataaccessclientoracleexceptionhandleerrorint32 errcode oracleconnection conn string procedure intptr opserrctx oposqlvalctx poposqlvalctx object src at oracledataaccessclientoraclecommandexecutenonquery at log4netappenderadonetappendersendbufferidbtransaction dbtran loggingevent events at log4netappenderadonetappendersendbufferloggingevent eventsandlog4neterror customadonetappender exception while writing to database systeminvalidoperationexception connection is already part of a local or a thistributed transaction at oracledataaccessclientoracleconnectionbegintransactionisolationlevel isolationlevel at oracledataaccessclientoracleconnectionbegindbtransactionisolationlevel isolationlevel at systemdatacommondbconnectionsystemdataidbconnectionbegintransaction at log4netappenderadonetappendersendbufferloggingevent eventsany help on this highly appreciated,['c#'] +383745,resharper split string literal i was not lucky in my 15 minutes googling maybe bad luck with good keywordwhy does the resharper suggest spliting a string in function parameterexamplefrom this return partialviewcategorias listato this return partialviewcat egorias listai checked documentation here linkand it says split string literal splits string literal into two literalsi want to thiscover why is this a good practice what are the fundamental idealogic behind the scenes that achieved this practicei do not want to do it without knowing why,['c#'] +383746,concatenating activerecordrelations queried through polymorphic association my application has a job model every job in the system has a contact this is like a person you would call up if you need to ask a question about the job a contact can either be a client or an employee of a client clientemployeeclass job activerecordbase belongs to contact polymorphic trueendclass client activerecordbase has many jobs as contact has many employees class name clientemployendclass clientemployee activerecordbase belongs to client has many jobs as contactendclients have the idea of commissioned jobs the clients commissioned jobs are those jobs for which the client is the contact or one of the clients employees is the contactclass client activerecordbase has many jobs as contact has many employee jobs through employees source jobs def commissioned jobs jobs employee jobs endendaside that method is a bit of a hack because it returns an array rather than an activerecordrelation it is also interesting that it blows up if i try to concat jobs into employee jobs it may or may not do for my purposesi would like to add a scope to client called with commissioned jobs this should return all the clients in the system who have jobs or who have employees who have jobsclass client activerecordbase def selfwith commissioned jobs i can get clients with jobs using joinsjobs how do i also include clients with employees who have jobs endendhow do i implement this methodi am using rails 329updatei have made some progress and i now have two methods each of which does half of what i needclass client activerecordbase return all clients who have an employee with at least one job def selfwith employee jobs joinsemployees jobs sql select clients from clients inner join client employees on client employeesemployer id clientsid inner join jobs on jobscontact id client employeesid and jobscontact type clientemployee end return all clients who have at least one job def selfwith jobs joinsjobs sql select clients from clients inner join jobs on jobscontact id clientsid and jobscontact type client endendnow all i need to do is combine these two method calls into one activerecordrelation i can obviously do this def selfwith commissioned jobs with jobs with employee jobs endthe problem is that that returns an array rather than an instance of relation and i cannot chain more scopes on itupdate 2using merge does not appear to work either here is the ar query and the resulting sqljoinsjobsmergejoinsemployees jobsselect clients from clients inner join jobs on jobscontact id clientsid and jobscontact type client inner join client employees on client employeesemployer id clientsid inner join jobs jobs client employees on jobs client employeescontact id client employeesid and jobs client employeescontact type clientemployeeby the way here are the tests i am trying to pass the first test fails because there are zero results when i use mergedescribe with commissioned jobs do a client with a job letclient with create client letjob create job contact client with a client who does not himself have a job but who has an employee with a job letclient with emp create client letemployee create client employee employer client with emp letemp job create job contact employee a client with nothing should not show up letclient without create client it should return clients with jobs and clients with employee jobs do clientwith commissioned jobsshould client with client with emp end it should return a relation do clientwith commissioned jobsshould be instance ofactiverecordrelation endend,['ruby-on-rails'] +383760,how to use c union nested in struct with no name i am working on the so called hotspot open source project and looking at the implementation i found a nasty nested union in struct looking like thattypedef struct rc model t st union struct block model t st block struct grid model t st grid block model or grid model int type thermal config t configrc model tas far as i am aware in cc that union is unaccesible so how someone can make use of union declared in such manner and for what purposethanks,"['c++', 'c']" +383832,custom list items not responding to state checked in selector i am going to begin by saying that i have read in detail almost every question on so that i can find related to custom checkable list items and selectors many of them have similar issues but none of the answers solve my problemat a point in my app i present a custom list activity when created it retrieves a set of static data from the intent that called it and passes that data to it is custom array adapter each list item is a simple relativelayout that implements the checkable interface by default if you click on one of the items a new activity is shown which thisplays detailed information about the selected contact however if an item in the list is longclicked an actionmode is started clicking on an item in the list at this point does not thisplay the detail activity it just sets the item to checked then if the user chooses one of the action mode items it performs the action on the checked itemsan important thing to understand is that in both selection modes clicking on a list item sets it to checkedall of what i described above works perfectly my only problem has to do with the backgrounds of the list items not being highlighted when they are set to checked even using the default selectorwhat i want to do is have two selectors one for each selection mode in the first the background does not change when an item is checked and in the second it does i have tried implementing custom selectors but even in those state checked is ignored other parts of the selector work fine but not state checked my implementation of checkablelistitem incorporates ideas from a lot of different examples so if i am doing something wrong or if there is a better way let me knownote an interesting point is that if i set the background of the list items in results list itemxml to my selector instead of the listselector property of the listview the backgrounds do change when an item is checked however doing this causes the longpress transition in my selector not to workresultsactivityjavapublic class resultsactivity extends listactivity implements onitemlongclicklistener private listview listview reference to the list belonging to this activity private actionmode mactionmode reference to the action mode that can be started private boolean selectionmode detail mode or check mode public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity results when the home icon is pressed go back actionbar actionbar getactionbar actionbarsetthisplayhomeasupenabledtrue get a reference to the list listview getlistview initially in detail mode selectionmode true get the contacts from the intent data and pass them to the contact adapter suppresswarningsunchecked arraylistcontact results arraylistcontactgetintentgetserializableextraresults contact contacts new contactresultssize contactarrayadapter adapter new contactarrayadapterthis resultstoarraycontacts setlistadapteradapter we will decide what happens when an item is longclicked listviewsetonitemlongclicklistenerthis if we are in detail mode when an item in the list is clicked create an instance of the detail activity and pass it the chosen contact public void onlistitemclicklistview l view v int position long id if selectionmode intent thisplaycontact new intentthis contactactivityclass thisplaycontactputextracontact contactlgetadaptergetitemposition startactivitythisplaycontact public boolean oncreateoptionsmenumenu menu return superoncreateoptionsmenumenu if the home button is pressed go back to the search activity public boolean onoptionsitemselectedmenuitem item switch itemgetitemid case androidridhome intent intent new intentthis searchactivityclass intentaddflagsintentflag activity clear top startactivityintent return true default return superonoptionsitemselecteditem when an item is longpressed switch selection modes and start the action mode public boolean onitemlongclickadapterview adapter view view int position long i if mactionmode null return false if selectionmode toggleselectionmode listviewstartactionmodenew listactionmodethis getlistview return true return false clear the lists checked items and switch selection modes public void toggleselectionmode listviewclearchoices contactarrayadapterlistviewgetadapternotifydatasetchanged if selectionmode selectionmode false else selectionmode true activity resultsxmllistview xmlnsandroid androididandroididlist androidlayout widthmatch parent androidlayout heightwrap content androidchoicemodemultiplechoice androidlistselectordrawablelist selector list selectorxmlselector xmlnsandroid item androidstate pressedtrue androiddrawabledrawableblue transition item androidstate checkedtrue androiddrawabledrawableblue selectortwolinearrayadapterpublic abstract class twolinearrayadapter extends arrayadaptercontact private int mlistitemlayoutresid public twolinearrayadaptercontext context contact results thiscontext rlayoutresults list item results public twolinearrayadaptercontext context int listitemlayoutresourceid contact results supercontext listitemlayoutresourceid results mlistitemlayoutresid listitemlayoutresourceid public view getviewint position view convertview viewgroup parent layoutinflater inflater layoutinflatergetcontextgetsystemservicecontextlayout inflater service view listitemview convertview if convertview null listitemview inflaterinflatemlistitemlayoutresid parent false get the text views within the layout textview lineoneview textviewlistitemviewfindviewbyidridresults list item textview1 textview linetwoview textviewlistitemviewfindviewbyidridresults list item textview2 contact c contactgetitemposition lineoneviewsettextlineonetextc linetwoviewsettextlinetwotextc return listitemview public abstract string lineonetextcontact c public abstract string linetwotextcontact ccontactarrayadapterpublic class contactarrayadapter extends twolinearrayadapter public contactarrayadaptercontext context contact contacts supercontext contacts public string lineonetextcontact c return cgetlastname cgetfirstname public string linetwotextcontact c return cgetdepartment checkablelistitemjavapublic class checkablelistitem extends relativelayout implements checkable private boolean ischecked private listcheckable checkableviews public checkablelistitemcontext context attributeset attrs int defstyle supercontext attrs defstyle initialiseattrs public checkablelistitemcontext context attributeset attrs supercontext attrs initialiseattrs public checkablelistitemcontext context int checkableid supercontext initialisenull private void initialiseattributeset attrs thisischecked false thischeckableviews new arraylistcheckable5 public boolean ischecked return ischecked public void setcheckedboolean check ischecked check for checkable c checkableviews csetcheckedcheck refreshdrawablestate public void toggle ischecked ischecked for checkable c checkableviews ctoggle private static final int checkedstateset androidrattrstate checked protected int oncreatedrawablestateint extraspace final int drawablestate superoncreatedrawablestateextraspace 1 if ischecked mergedrawablestatesdrawablestate checkedstateset return drawablestate protected void onfinishinflate superonfinishinflate final int childcount thisgetchildcount for int i 0 i childcount i findcheckablechildrenthisgetchildati private void findcheckablechildrenview v if v instanceof checkable thischeckableviewsaddcheckable v if v instanceof viewgroup final viewgroup vg viewgroup v final int childcount vggetchildcount for int i 0 i childcount i findcheckablechildrenvggetchildati results list itemxmlcomtestmycompanywidgetscheckablelistitem androidididresults list item xmlnsandroid androidlayout widthmatch parent androidlayout heightwrap content androidpaddingleft10dp androidpaddingright10dp androidpaddingtop5dp androidpaddingbottom5dp textview androidididresults list item textview1 androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentlefttrue androidtextsize20sp androidtextcolor0 androidfocusablefalse textview androidididresults list item textview2 androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentlefttrue androidlayout belowidresults list item textview1 androidtextsize16sp androidtextcolorandroidcolordarker gray androidfocusablefalse comtestmycompanywidgetscheckablelistitem,['android'] +383876,as3 flash render html via externalinterface this is my first question on stack overflow it is not the first time i wanted to write one but usually i find a solution using the search bar this time i did not the problem i am tackling is a little bit complex so i will try and be as thorough as possibilebasically were adding chinese payments to an already existing ecommerce in flash the whole website is in as3 embedded using swfobject already using externalinterface for other thingsthis new chinese payment method is a bit oldfashioned so they have a strange way of handling payments once weve sent a post to their servers with all the order details they respond with an html page my problem is rendering this page considering that i receive it inside flashthe solution i am trying at the moment works partially meaning that i am able to see the page but the chinese characters that are supposed to be in the page are rendering out badly instead of the chinese characters i am seeing weird characters so i am guessing there must be an encoding problem when i pass the html from flash to javascript this is how i am doing itas3extract html page from responsevar newhtmlstring ecurrenttargetdatatrim whitespace to avoid javascript errornewhtml newhtmlreplaceng newhtml newhtmlsplitrjoinifexternalinterfaceavailable externalinterfacecallchinesepaymentnewhtmlelse traceexternal interface errorjavascriptfunction chinesepaymentparam var newwindow windowopen var unescaped unescapeparam newwindowdocumentwriteparami have tried messing about with unescape escape uriencoding but without any success so i am really hoping you can help me out herethanksdomenicoediti would just like to mention that i am receiving a correct html page from their servers i have tried saving the page locally copying the html code directly from the server response and the page views correctly that means that there has to be something wrong in the process of passing the page from as3 to javascriptedit2 importanti have realised that the problem lays in the popup encoding when i copy the html from the popup paste it in an editor and save it i can correctly view the html seems like the popup does not consider gbk encoding i am now looking for a solution to this problem,['javascript'] +383928,jquery draggable enable and thisable ive tried anything to do this but always get the same errortooltipdraggablethisableerror cannot call methods on draggable prior to initialization attempted to call method thisableprior to initialization so i cannot remove the option before its actually being dragged around ive tried with droppable as well cant seem to get them thisabled enabled without getting this errorediti found out that i have an element with the class that is without draggable which makes sense when you look at the error now i just have to find a way so it thisables all the draggables without throwing the error,['jquery'] +383977,use decltype and stdfunction with lambda this works auto x 4typedef decltypex x tx t y 5 so why does not thisint j 4 auto func int i cout hello i i j j endltypedef decltypefunc lambda tlambda t func2 int i cout bye i i j j endl and how would i declare lambda t manually using stdfunction,['c++'] +383980,data structure with o1 lookup time which will allow duplicates my goal is to create a data structure implementing ilistt interface which will achieve o1 element lookup time by compromising memorybackgroundas you know all array based ilistt implementations like listt have on element lookup time it means that the operations like int indexoft element or bool containst element iterate through the underlaying array until they find a matchwell known idea achive that is to use a combination of a list and hashtable as underlaying data structures values are kept in a list the hashtable will keep indexes as values and values of list as keys so lookup can be performed using hashtablethat is exactly how the keyedcollectiontkey titem see msdn is implementedwhat i have tried so farinternal class mylistt keyedcollectiont t protected override t getkeyforitemt item return item this worked so far except one problem this data structure does not mimic the behavior expected behind listt exactly the point is that the listt allows duplicates mylist does notquestionis there any ready to use data structure or can you recommend an elegant way of implementing the ilistt so thatlookup operations have o1 timeall other operations have same o performance as listtmemory can be compromised by hashtable overhead constanta constantb n bytesduplicates must be allowedallowing nulls is optional they can be boxed into null objects,"['c#', '.net']" +383981,when should i use longrunning task creation option i have an azure worker role that has three types of processesc thread that reads from the database and writes to workerinputqueue task1java thread that reads from workerinputqueue does work and writes to workeroutputqueuec thread that reads from workeroutputqueue and writes to database task2 task1 and task2 run indefinitely and sleep if their respective queues are emptymy code looks like this spawnjavaprocesses taskfactorystartnewtask1 taskfactorystartnewtask2 whiletrue do some trivial sporadic work threadsleep6010 my questionsshould i use the longrunning task creation option when starting task1 and task2is there a better way to implement what i am trying to do here,"['c#', '.net']" +383985,aptana studio 3 code assist for sass scss files i am using aptana studio 3 and i would like to get the code assist feature to work for sass scss files it is ok if code assist does not work for sass syntaxdeclarations but i would like to get syntax highlighting and code completion help for standard css declarations so for example if i type in background i would like the editor to thisplay the syntax like it does for htmli have added a new file association preference for scss files from here and assigned the css editor as the default editor for scss files this gets me syntax highlighting but no code completion help for css rulesam i doing something wrong or am i just out of luck for getting code completioncode assist help,['css'] +383994,android build a notification taskstackbuilderaddparentstack not working i am trying to launch an activity from a notification like the android docs explain but when i open the notification and then press the back button the homeactivity parent does not open instead the application closes what am i doing wrong intent resultintent new intentcontext matchactivityclass resultintentsetflagsintentflag activity multiple task taskstackbuilder stackbuilder taskstackbuildercreatecontext adds the back stack for the intent but not the intent itself stackbuilderaddparentstackmainactivityclass stackbuilderaddnextintentresultintent,['android'] +384000,signedxmlchecksignature fails in net 4 but it works in net 35 3 or 2 i have a response from a 3rd party web service i load an xmldocument with that response string txt readstreamreadtoend response new xmldocument responsepreservewhitespace true responseloadxmltxt return responsenow i would like to verify that the respones is signed using the certificate i have a verifyxmldocxmldocument xmldoc method which i have found on msdni know that the message is correct public bool verifyxmldocxmldocument xmldoc signedxml signed new signedxmlxmldoc xmlnodelist signaturenodelist xmldocgetelementsbytagnamesignature signedloadxmlxmlelementsignaturenodelist0 x509certificate2 servicecertificate null foreach keyinfoclause clause in signedkeyinfo if clause is keyinfox509data if keyinfox509dataclausecertificatescount 0 servicecertificate x509certificate2keyinfox509dataclausecertificates0 bool result signedchecksignatureservicecertificate true return result if i set target framework of my project to net 35 or net 3 or net 2 it works great result is true but if i change target framework to net 4 result is false and i have to use net 4any ideas on how to solve this problem,['c#'] +384055,webkit haslayout bug i have an accordion type thing that has header text when it is open it has one padding and when it is closed it has another all of the panels start with their open styles and then through js they are closed in chrome and safari the header text does not have the closed padding applied if i view it in the inspector the correct open padding shows as being applied and when clicking on the actual element in the inspector i can see where the padding is supposed to be the only way i can get it to apply it or draw it if that is the correct term is to toggle or add any style on that header text or within that panel i have also thiscovered that when i add padding as an inline style via the inspector that is also not applied and toggling that does not change itit seems like this is very similar to the ie haslayout issues but i cannot find anything referencing a similar error does any one have any ideas for further testing or how to fix iti cannot seem to replicate this issue in a simpler jsfiddle and the project i am working on is massive so here are the chunks of code giving me issuecssmedia only screen and minwidth 600px and maxwidth 767px checkoutplans collapsible title paddingright 130px checkoutplans collapsibleclosed title paddingright 323px htmldiv classmodule checkoutplans div classcollapsible active header div classtitle h3this text has the correct padding appliedh3 div header div div classcollapsible closed header div classtitle h3this text does not have the correct padding after having the closed class applied via jsh3 div header divdiv,['css'] +384086,best way to handle many incoming packets i am currently developing a simple p2p network as an exercise each node in the network sends heartbeats to a subset of the other nodes to be able to detect nodes that have left the network beside the heartbeat packets i send packets when new nodes joinleave the network when they want to locate a resource small text files etc all packets are udp packetswhenever i receive a packet i start a new thread that handles that specific packet i am however concerned with the amount of threads i start during one applications lifetime which adds up to quite a lot especially because of the heartbeats there is also the risk of deadlocks and the like i would like to avoid i thought about having a queue or something where i put all incoming packets and have a single thread handling all packets one at a time from that queue something like the producerconsumer pattern i would like the packets to be handled rapidly so the sender does not think the packet is lostwhat is the best way to handle a lot of different incoming packets without having to start a new thread for each of them should i go with what i have the producerconsuming or something different,['java'] +384103,variadic template of a specific type i want a variadic template that simply accepts unsigned integershowever i could not get the following to workstruct array template typename sizes this works template unsigned sizes this does not work gcc 472 arraysizes sizes this causes narrowing conversion warning if signed int is supplied unsigned args sizes snipped int main array arr1 1any help appreciatededit in case youre wondering i am trying to use variadic template to replicate the followingstruct array arrayunsigned size1 arrayunsigned size1 unsigned size2 arrayunsigned size1 unsigned size2 unsigned size3 arrayunsigned size1 unsigned size2 unsigned sizen,['c++'] +384111,how to check for the type of a template parameter suppose i have a template function and two classesclass animal class person templateclass tvoid foo if t is animal kill how do i do the check for t is animal i do not want to havesomething that checks during the run time thanks,['c++'] +384113,python checking oddeven numbers and changing outputs on number size i have a couple of problems to solve for an assignment and am a bit stuckthe question is to write a program that gets the user to input an odd number check it is odd then print an upside down pyramid of stars based on the size of the inputfor example if you enter 5 it comes up with my problem is therefore twofold1 how do i check if it is even or odd i tried if number2 int in the hope that it might do something and the internet tells me to do if number20 but that does not work2 how do i change the asterisks in the middle of each lineany help with either problem is greatly appreciated,['python'] +384116,can you submit a new app for review while having a version in pending developer release state have an app that is currently available a recent version was submitted and approved and in the the pending developer release until we meet our launch date however there are a few bugs wed like to fix we do not want to removeor reject the current binary that was approved because we may not have enough time before our launch to go through the review process again the question is can we submit a new version of the app for review while keeping the approved version in the pending developer release state,['iphone'] +384117,does hhvm hiphop support postgresqlarbitary pecl extensions facebook made a big announcement today hhvm is replacing the original hiphop compilerthe old hiphop had limited support for extensions including iirc no postgres supportdoes hhvm support all pecl extensions how much of the standard php library does it supportwhat does not hhvm support,['php'] +384129,why are filesystemwatcher attribute changes detected on windows 7 but not windows 8 i have some code that uses filesystemwatcher to monitor file changes outside of my application on windows 7 using net 4 the below code would detect when a file had been edited and saved in an application like notepad while my app was running however this logic is not working using net 4 on windows 8 specifically the filesystemwatchers changed event never firespublic static void mainstring args const string filepath cuserscraigdesktopnotestxt if fileexistsfilepath consolewritelinetest file exists var fsw new filesystemwatcher fswnotifyfilter notifyfiltersattributes fswpath pathgetdirectorynamefilepath fswfilter pathgetfilenamefilepath fswchanged onfilechanged fswenableraisingevents true block exiting consolereadlineprivate static void onfilechangedobject sender filesystemeventargs e if fileexistsefullpath consolewritelinefile change reported i understand that i can alter the notifyfilter to also include notifyfilterslastwrite which can solve my problem however i want to understand why this code worked on windows 7 but now fails to fire the changed event on windows 8 i am also curious to know if there is a way to restore my windows 7 filesystemwatcher behavior when running in windows 8 without changing the notifyfilter,"['c#', '.net']" +384230,signalr broadcasting from outside a hub does not work based on the wiki article here i am able to get my mvc application to broadcast messages via my hub with thisfunction proxy created on the fly var chat connectionchatterbox declare a function on the chat hub so the server can invoke it chatclientaddmessage function message messagesappendli message li start the connection connectionhubstartdonefunction broadcastclickfunction call the chat method on the server chatserversendmsgval my hub which is in a separate dll named serverhubdll looks like thisnamespace serverhub public class chatterbox hub public void sendstring message clientsalladdmessagemessage so with the above set up i can browse to the same url on several different browsers and sending a message from one browser will be reflected across all the other browsershowever what i am trying to do now is to send a message from within a controllerso in my outofthebox mvc internet application in the homecontroller about action i added thisusing serverhub public actionresult about viewbagmessage your app description page var context globalhostconnectionmanagergethubcontextchatterbox contextclientsallsayhello from about return view but the above does not seem to be working there is no error messages or run time error the code executes just that i cannot see the message on my other browserswhere did i go wrong,['c#'] +384257,sqlite delete cascade not working in android 42 using sqlite 3711 when i delete a row from the quizzes table whos schema is below the corresponding rows in the quizquestions table are not deletedi cannot figure out whats wrong i have tried putting dbexecsqlpragma foreign keys on before and after the create table statementscreate table statementscreate table quizzesquiz name text primary key collate nocasecreate table quizquestionsquiz name text question id integer primary keyquiz name question id foreign keyquiz name references quizzesquiz name on delete cascade foreign keyquestion id references questionsquestion id on delete cascade,['android'] +384288,no color in vi when called from pythons script when i edit a file with vi like vi bashrc i have colorswhen in pythons script i have ossystemvi bashrc i do notwhy i am guessing that i open a different shell but i cannot figure why the settings are different and how to solve this i am running fedora and my shell is bashvi versiongives vim vi improved 73,['python'] +384344,visual studio 2012 debugging of remote process not working as expected i am struggling with a rather difficult debugging challenge and hoping that someone might have some clues how to make this workheres the scenarioi have a c windows service that runs under a user account with admin privileges and launches a separate executable process under a user account that has standard user privileges the two processes are designed to communicate using wcfunfortunately when the child process is launched it crashes immediately with nothing in the event log that suggests what happened the parent process continues running without exceptionsfor information these two applications work reliably together in a configuration whereby the parent process is a desktop application i have also had success with the parent as a windows service but only when both processes run under the same user account with admin privilegesi now need to reconfigure their relationship to restrict the privileges of the child process but this is when the crash occursin order to prove that what i am trying to do is feasible i have created two stub applications and launched them successfully in the desired configuration so i can deduce that my real child app contains something that is incompatible with this configuration and which causes a crash even before the code starts executing unfortunately since the child process is a based on some rather complex legacy code it is not easy to isolate its elements until i eliminate the problem so i really need a reliable means of stepping through itif i modify the code of the child process to launch debugging immediately on startup it invites me to attach a debugger but fails to complete the attachment with a message that indicates that the justintime debugger does not have permission to debug the processi have also seen this question and attempted to implement this proposed solution which looks really promising but it fails to work in my scenario instead of launching debugging prior to launching the application it appears to do nothing niether the debugger nor the application are launched and the debugging invite dialog is not thisplayed however i have verified that this technique works in my environment by using it to launch notepadexe so there is clearly something about my application or the way that i am launching it that is causing the problemi am happy to experiment and to share more details about my test results if anyone has any suggestionsmany thanks for your ideastim,['c#'] +384348,how to do custom filtering with datatables and serverside processing i am using datatables to thisplay tabular data in my web application and have configured it to make use of serverside processing ie query the server via ajax for filtered data i want to filter according to additional parameters that are specific to my application ie corresponding to some user options fex via a checkbox in the ui how do i make datatables pass these additional filter parameters to the server,['jquery'] +384353,make edittext lose focus on clicking a button i have two edittext fields in my activity and a done button i want both the edittext fields to loose focus that is the cursor should not not be thisplayed on either of them when the user presses the button i am using the following codefinal button savebutton button findviewbyidridsavebutton savebuttonsetonclicklistenersavebuttonlistenerprivate onclicklistener savebuttonlistener new onclicklistener override public void onclickview v text1clearfocus text2clearfocus however when i press the done button the cursor comes up on text1 even if i have not clicked on any edittext yet how can i make the edittext fields loose focus on the click of the button,['android'] +384395,javascript forin vs for loop performance i was clustering around 40 points using kmean algorithm in the first version of the program i wrote the euclidean thistance function like thisvar euclideanthistance function p1 p2 p1length p2length 3 var sum 0 for var i in p1 sum mathpow p1i p2i 2 return mathsqrt sum the overall program was quite slow taking on average 7sec to execute after some profiling i rewrote the above function like thisvar euclideanthistance function p1 p2 p1length p2length 3 var sum 0 for var i 0 i p1length i sum mathpow p1i p2i 2 return mathsqrt sum now the programs on average take around 400ms that is a huge time difference just because of the way i wrote the for loop i normally do not use forin loop for arrays but for some reason i used it while writing this functioncan someone explain why there is this huge difference in performance between these 2 styles,['javascript'] +384397,determine size of object best way to use instrumentation in scalasbt according to this question the standard way to determine the memory size of an object in java is by using javalanginstrumentation after to some research it looks like there is no scala specific way to achieve this so the java approach should also applies hereunfortunately for a scala programmer without java background it is not fully straightforward to adapt this technique in scala my questions arequestion 1what exactly is happening here i guess the reason why we have to put a class like objectsizefetcher in a separate jar is to ensure that it is somehow loaded before the actual program where we want to use it i assume it is not possible to use instrumentation without the premainclass entry and the parameter javaagentthejarcontainingobjectfetcherjarquestion 2is there a simple way to implement the complete work flow in sbt currently i only see a somewhat cumbersome solution i first have to set up a secondary sbt project where i define objectsizefetcher and package it into a jar so far i did not figure out how to automatically add the premainclass entry to the jar during packaging so i would have to solve that manually than i can add the resulting jar to the local libraries of the project where i want to use getobjectsize for this project i now have to enable fork in run and use javaoptions in run javaagentthejarcontainingobjectfetcherjar is there a more simple and less intrusive work flow to quickly use instrumentation within an existing sbt project maybe i can tell sbt directly about a premainclass to make this secondary jar unnecessaryquestion 3would you recommend a completely different way to evaluate the memory usage of an object in scala,['java'] +384415,how to get real ip from visitor i am using this php code to get visitor ip addressphpecho serverremote addrbut i cont get real ip address from visitors when they are using proxyplease help me is there any way to get visitors ip address,['php'] +384423,is there a cross browser way to prevent cut copy and paste on a website in plain javascript i found an answer but it was for jquery here is the link i want something in plain javascript which work on chrome latest firefox safari and ie 8 and 9updatedue to all the negative comments saying that this is a bad idea for an internet site i can only say i agree please note that this is for an intranet application where cut copy and paste need to be overidden as the default browser behaviour for cut copy and paste needs to be customized to handle embedded tags in a rich text area,['javascript'] +384435,remove last line from string how do i remove the last line n from a string if i dont know how big the string will bevar temphtml contentdocumentbodyinnerhtmlvar htmlwithoutlastline removelastlinetemphtmlfunction removelastlinetemphtml code,"['javascript', 'jquery']" +384491,convert bufferedimage to imageicon how can i convert a bufferedimage to an imageiconi can not find any documentation on this,['java'] +384522,multiline raw string literals as preprocessor macros arguments can a multiline raw string literal be an argument of a preprocessor macrodefine identityx xint main identityr this code does not compile in both g472 and vc11 novctpis it a compiler lexer bug,['c++'] +384592,wrap text within element i need to wrap text inside a div with a spandiv classitem span classcountspan text that needs to be wrappeddivdiv classitem span classcountspan text that needs to be wrappeddivdiv classitem span classcountspan text that needs to be wrappeddivtried this but it did not really workitemtextwrapspan classnew,['jquery'] +384597,read iphone settings programmatically precisely settingsgeneraldate timeset automatically we are developing an iphone application for which i need to read iphone settings value precisely the status of settingsgeneraldate timeset automatically is there any way easydifficult way to find out that value any tips and tricks will be highly appreciated,"['iphone', 'ios']" +384611,objectivec a waiting for two async methods to complete i am calling four methods that i want to execute in synchronous order the first two methods are synchronous the last two methods are asynchronous data fetching from urlspseudocode voidsyncdata show activity indicator object sync synchronous method object2 sync synchronous method bool object3synced object3 sync async method bool object4synced object4 sync async method wait for object3 and object4 has finished and then hide activity indicatorhow can i achieve this,"['objective-c', 'ios']" +384704,access denied error in ie when submitting form through javascript using htmlbeginformupload myprofile formmethodpost new enctype multipartformdata id imgform name imgform target uploadtarget input typefile namefileupload classfilestylenotext fileupload iframe iduploadtarget nameuploadtarget styleposition absolute left 9em top 9emiframeand through javascriptjquery i am doing form submit on change of file inputmyprofile fileuploadchangefunction imgformsubmitit throws an error access is denied and it happens only in ie i am using ie8 and works fine in firefox chromeafter reading in forums i see there is an issue with form submit through javasript in ie due to security reasons but is there any workaround and i do not understand why the hell only ie does that when all browsers are supporting it is ie more secure than all browsers pool in your suggestions please,"['javascript', 'jquery']" +384725,android google maps sign up not works and it says entered md5 certificate not valid i generated md5 fingerprint correctly cprogram filesjavajdk160 19binkeytoolexe list alias androiddebugkey keystore candroiddebugkeystore storepass android keypass androidandroiddebugkey nov 11 2012 privatekeyentrycertificate fingerprint md5 cprogram filesjavajdk160 19binbut when i put it on then it shows the fingerprint that you entered is not valid please press the back button on your browser and enter a valid certificate fingerprint plz plz help me urgent im badly facing this problem,['android'] +384738,how to install xcode in windows 7 platform possible duplicatehow can i develop for iphone using a windows development machine can you tell me how to install xcode in windows 7 or there is any other way to develop iphone app on windows 7,"['iphone', 'ios']" +384746,handlebars breaks when passing thisitem in spinejs i am attempting to implement the todoexample given in the spinejs docs given here tasksonly i would like to use handlebars instead of jquerytmpl i am using handlebars 10rc1however when i attempt to calltemplate handlebarscompilehistorytemplatehtmlrender function var t thistemplatethisitem thisreplacet return thishandlebars throws an exception at thistemplatethisitemuncaught typeerror cannot call method match of undefinedin the handlebars lexer this input is coming back as undefinedmy template is as follows script idhistorytemplate typetextxhandlebarstemplate div classcontentinner if viewedmsg unseenif divdatadiv divscriptdata datahelloidc0any ideas,['javascript'] +384747,wordpress tinymce issue in article posting found 1 strange issue in wordpress article posting for one specific useruser adds article in tinymce html modeagain trying to add new post in tinymce visual mode not actually posted just switched the tinymce slected tab from html to visualuser tried to open post saved in html mode in setp 1 it shows tinymce visual mode active in tabs but icons loaded are from html mode the tinymce content is not viewable now content is there but not viewable if i press ctrla i can view the content and it also blocking other features as editing draft logout etcnow if user again trying to add new post and selects html from tinymce tabs and exit from pagehe tries to edit post added in setp 1 now it is showing correctlyno issue in content as i tried to copy and paste this content in new post and it working fineit is not happening for all users and 1 more point the icons loading in visual mode are very less than found in admin account,['php'] +384750,multiple font not working at time in application friends running out in a strange issuei want to use two font gujarat hindi in same applicaion here is process of install fonts in deviceneeded root device install font installer appdownload lohitdevanagarittf lohitgujaratittf from thissitecopy ttf files file at systemfontsgiven readwrite permission installed both fontsreboot deviceissueafter reboot device i can read only that font which i installed last either gujarati or devangari note i am creating only softkeyboard apps which will work in all app so i cannot use typeface classi am just doing settext for read fontstextview1settexttextview1 a34atextview2settexttextview2 a1aa a i want like thistextview1 a34atextview2 a1aa abut i getting output like thistextview1 a34atextview2 aortextview1 atextview2 a1aa anote i am creating only softkeyboard apps which will work in all app so i cannot use typeface class,['android'] +384765,what goes behind printf in c possible duplicateunderstanding the hardware of printf i am not looking for the implementation of printf function but i want to know what all happens when the call to printf is made in c what all activities take place at the software and hardware level this is what i thinkprintfcall kernelmodeon systemcallmade data put on output buffer of some sort output to be dumped on some controllers buffer controller dumps it on the monitor interrupts cpu saying that work is donehow correct am ithanksedit unix can be taken as a platform say ubuntuand can someone tell me where the data flows out from and is there any controller for the monitor too and to what extent is the timeline presented above is correct,['c'] +384794,why am i getting thistributionnotfound error when i try to run pyramid project i installed in my new windows 8 x64python27 pywin32218win32py27 setuptools06c11win32py27 and pyramid via easy installi tried to run my pyramid projectpserve iprojectspyramidprojectdevelopmentiniand pkg resourcesthistributionnotfoundreq was raised iprojectsmyprojectpserve developmentini traceback most recent call last file cpython27scriptspservescriptpy line 9 in module load entry pointpyramid14b1 console scripts pserve file cpython27libsitepackagespyramid14b1py27eggpyramidscriptsps ervepy line 50 in main return commandrun file cpython27libsitepackagespyramid14b1py27eggpyramidscriptsps ervepy line 301 in run relative tobase global confvars file cpython27libsitepackagespyramid14b1py27eggpyramidscriptsps ervepy line 332 in loadserver server spec namename relative torelative to kw file cpython27libsitepackagespastedeploy150py27eggpastedeployl oadwsgipy line 255 in loadserver return loadobjserver uri namename kw file cpython27libsitepackagespastedeploy150py27eggpastedeployl oadwsgipy line 271 in loadobj global confglobal conf file cpython27libsitepackagespastedeploy150py27eggpastedeployl oadwsgipy line 296 in loadcontext global confglobal conf file cpython27libsitepackagespastedeploy150py27eggpastedeployl oadwsgipy line 320 in loadconfig return loaderget contextobject type name global conf file cpython27libsitepackagespastedeploy150py27eggpastedeployl oadwsgipy line 454 in get context section file cpython27libsitepackagespastedeploy150py27eggpastedeployl oadwsgipy line 476 in context from use object type nameuse global confglobal conf file cpython27libsitepackagespastedeploy150py27eggpastedeployl oadwsgipy line 406 in get context global confglobal conf file cpython27libsitepackagespastedeploy150py27eggpastedeployl oadwsgipy line 296 in loadcontext global confglobal conf file cpython27libsitepackagespastedeploy150py27eggpastedeployl oadwsgipy line 328 in loadegg return loaderget contextobject type name global conf file cpython27libsitepackagespastedeploy150py27eggpastedeployl oadwsgipy line 620 in get context object type namename file cpython27libsitepackagespastedeploy150py27eggpastedeployl oadwsgipy line 640 in find egg entry point pkg resourcesrequireselfspec file cpython27libsitepackagesthistribute0632py27eggpkg resources py line 690 in require needed selfresolveparse requirementsrequirements file cpython27libsitepackagesthistribute0632py27eggpkg resources py line 588 in resolve raise thistributionnotfoundreq pkg resourcesthistributionnotfound pastemy developmentiniappmyprojectuse eggmyprojectpyramidreload all truepyramidreload templates truepyramidreload assets truepyramiddebug all falsepyramiddebug authorization falsepyramiddebug notfound falsepyramiddebug routematch falsepyramiddebug templates truemakodirectories appviewmakomodule directory herescachetemplatesmakocache type filemakocache enabled falsemakocache dir herescacheviewmakocache impl beakermakocache timeout 60makoinput encoding utf8makoimports from markupsafe import escape silentmakodefault filters escape silentmakoerror handler sqlalchemyurl mysqlusermyproject devcharsetutf8sqlalchemypool recycle 3600beakersessiontype filebeakersessioncookie expires truebeakersessioncookie domain myprojectplbeakersessiondata dir heresdatasessionsdatabeakersessionlock dir heresdatasessionslockbeakersessionkey myprojectplbeakersessionsecret 57b0d7ff4c665d87e3c3745c2abf519ca7d4082abeakersessionvalidate key 57b0d7ffbeakercacheenabled truebeakercachetype memorybeakercachedata dir herescachedatabeakercachelock dir herescachelock beakercacheregions default term second term minute term hour term day term month term short term middle term long term beakercachesecond termexpire 1beakercacheminute termexpire 60beakercachehour termexpire 3600beakercacheday termexpire 86400beakercachemonth termexpire 2678400beakercachedefault termexpire 60beakercacheshort termexpire 30beakercachemiddle termexpire 300beakercachelong termexpire 86400sitefrontdefault skin myprojectsitefrontavailable skins default mobile myprojectdefault skin myprojectavailable skins default mobile myprojectfiltertmuse eggrepozetm2tmcommit veto repozetmdefault commit vetopipelinemainpipeline eggweberrorevalerror tm myprojectservermainuse eggpastehttphost 127001port 50 begin logging configurationloggerskeys root myproject sqlalchemyhandlerskeys consoleformatterskeys genericlogger rootlevel infohandlers consolelogger myprojectlevel debughandlers qualname myprojectlogger sqlalchemylevel infohandlers qualname sqlalchemyengine level info logs sql queries level debug logs sql queries and results level warn logs neither recommended for production systemshandler consoleclass streamhandlerargs sysstderrlevel notsetformatter genericformatter genericformat asctimes levelname55s namesthreadnames messages end logging configurationhave you any idea what did i wrong,['python'] +384798,how to store and check synonym of string in java i am making a program which can response to what user said something like chatter bot but i wonder if i can make it understand if two or more words have the same meaning for example i make it to answer yes when user say are you scared of the dark but scared afraid and frightened have the same meaning if the user use afraid instead of scared how the program recognize those two words have equal meaning hence make the reference to are you scared of the dark question and answer yesi wonder if i could make array of string like hello hi hey or afraid scared frightened etc thank you for helpingps the program i wrote does not use english language i am afraid i cannot use library or api because of that but i have no problem defining the synonym list myself,['java'] +384828,change notification without inotifypropertychanged excerpt from pro wpf in c 2010 while reading pro wpf in c 2010 the author writesyou can raise an event for each property in this case the event must have the name propertynamechanged for example unitcostchanged itas up to you to fire the event when the property is changedcould someone confirm this feature works i was experimenting and not able to reproduce this behavior i want to see if this works so then i can do some experimenting with systemreflectionemit to create dynamic typesedit i should clarify the emphasis here is to implement change notification without implementing inotifypropertychanged as this is what the book is claimingheres the poco i am testing withpublic class employee private string firstname public string firstname get return firstname set if firstname value firstname value if firstnamechanged null firstnamechangedthis new propertychangedeventargsfirstname i bound it to a datagrid and have a timer in the background update the firstname property randomly every few seconds but the datagrid never firesdatagrid xnamedgemployees itemssourcebinding elementnamemainwindow pathmyemployees datagridcolumns datagridtextcolumn headerfirstname bindingbinding pathfirstname datagridcolumns datagridthe firstnamechanged event is always null i thought the binding engine might automatically subscribe to it if it detected it according to the naming convention myemployees is just an observablecollectioncan someone confirm if this feature the author mentions does indeed work and if i am making a mistakeedit for the benefit of anyone who thinks i am misinterpreting the textyou can use three approaches to solve this problemyou can make each property in the product class a dependency property using thesyntax you learned about in chapter 4 in this case your class must derive fromdependencyobject although this approach gets wpf to do the work for youwhich is nice it makes the most sense in elementsaclasses that have a visualappearance in a window itas not the most natural approach for data classes likeproductyou can raise an event for each property in this case the event must have thename propertynamechanged for example unitcostchanged itas up to you tofire the event when the property is changedyou can implement the systemcomponentmodelinotifypropertychangedinterface which requires a single event named propertychanged you must thenraise the propertychanged event whenever a property changes and indicate whichproperty has changed by supplying the property name as a string itas still up toyou to raise this event when a property changes but you donat need to define aseparate event for each property,"['c#', '.net']" +384836,portable class libraries webrequestcontentlength i have a portable class library that targets net for windows store apps and windows phone 75 or higher i make http post requests and as of last week the admins in charge of the backend decided that i need to send a contentlength of 0 as opposed to 1 that is defaulted by net i use the webrequest class but i am flexible enough to use httpwebrequest if needednormally i would just use webrequestcreate and set the contentlength property in the pcl library the contentlength property is not available if i try to add a header with a key of contentlength the framework complains that i should just use the contentlength propertyany ideas on how i can set the contentlength in a pcl,"['c#', '.net']" +384992,use of ellipsis in java i was looking through some code and saw the following notation i am somewhat unsure what the three dots mean and what you call them void doactionobjectothanks,['java'] +384996,efficiently scanning memory of a process recently i have put together a c class that can read and write bytes in another processes memory using api calls etc as i am sure youve all seen beforemy question however relates to how i can efficiently scan the memory of another process i know the basic method of testing each group of 4 bytes until you reach int32maxvalue but i have found it is as you may imagine incredibly time and resource consumingfrom what i have read there is a way to determine the allocated addresses of a process by doing a heapwalk can anyone provide me with some code examples andor information about this and what would be the best way of going about it,['c#'] +385002,several questions about header in c 11 i have several questions about new chrono header in c 11 using windows 7 visual studio 2012looking at the example include iostreaminclude chronoinclude ctimeint fibonacciint n if n 3 return 1 return fibonaccin1 fibonaccin2int main stdchronotime pointstdchronosystem clock start end start stdchronosystem clocknow int result fibonacci42 end stdchronosystem clocknow int elapsed seconds stdchronoduration caststdchronoseconds endstartcount stdtime t end time stdchronosystem clockto time tend stdcout finished computation at stdctimeend time elapsed time elapsed seconds snpossible outputfinished computation at sat jun 16 204257 2012elapsed time 3si have noticed that example uses stdchronosystem clocknow does it mean it can be used to measure only elapsed time and not the cpu time and if i want to measure cpu time what clocks should i use notice that elapsed time 3s is output is rounded to whole integer is there way to make it more granulated,['c++'] +385022,googlebot unexplained 32character hexadecimal appended string causing more than 20 404 errors per day i have a very interesting problem that i am failing to explainevery 2 to 6 seconds googlebot i have looked up googlebots ip its the real thing using host ip is requesting a page on our site running php apache mongodb that does not exist 404s no other robot or human has ever requested a page like this just googlebotthe requests each look something like this2de4f853c2853807b2e72387aa8928a4ea5700c343d1a9798bc554af7c1a330ee5aafa102d54ba75177036846cc019our code does not use any 32 char strings and there are no links anything like that internal or external of our site we use codeigniter so at first i thought it was the default session id i have checked it is nothas anyone ever seen anything like this our website uses historypush on some pages could this cause it just an idearaw data of an example requestarray date 20121201 time 100133 pm additional data array server vars array redirect status 200 http host wxcom http accept http accept encoding gzipdeflate http from googlebotatgooglebotcom http user agent mozilla50 compatible googlebot21 http x forwarded for x http x forwarded port 80 http x forwarded proto http http connection keepalive path sbinusrsbinbinusrbinhomeec2userec2bin server signature addressapache2 amazon server at wxcom port 80address server software apache2 amazon server name wxcom server addr x server port 80 remote addr 10171147114 remote port 40759 redirect url e5aafa102d54ba75177036846cc019 gateway interface cgi11 server protocol http11 request method get query string request uri e5aafa102d54ba75177036846cc019 script name indexphp path info e5aafa102d54ba75177036846cc019 path translated redirectindexphpe5aafa102d54ba75177036846cc019 php self indexphpe5aafa102d54ba75177036846cc019 request time 1354428093 codeigiter session array session id c795e40a279f58d9fbbf7f5501a26787 ip address 10171147114 user agent mozilla50 compatible googlebot21 last activity 1354428093 user data what else can i collect to figure this out its very strangeupdate the traffic is coming from 2 primary ip addresses 10171147114 1016146102i have looked these up and they are not googleboti have gotten this info from one ip lookup site remember that ip address ranges 10 a 10255255255 1721600 a 17231255255 19216800 a 192168255255 and 2240 239255255255 are reserved ip addresses for private internet use and ip lookup for these will not return any resultswhat should can i do about these requests what is the point of these requests if this is a type of dos attack they are doing a very bad job at it,['php'] +385041,massive cpu load using stdlock c11 my recent efforts to implement a thread mutex manager ended up in an 75 cpu load 4 core while all four running threads were either in sleep or waiting for a mutex beeing unlockedthe specific class is far too large for being posted here entirely but i could narrow down the cause to the deadlocksafe acquiring of two mutexesstdunique lockstdmutex lock1 mutex1 stddefer lock stdunique lockstdmutex lock2 mutex2 stddefer lock stdlock lock1 lock2 another part of the class uses a stdcondition variable with wait and notify one on mutex1 for some code to be executed selectively at the same time the simple change tostdunique lockstdmutex lock1 mutex1 stdunique lockstdmutex lock2 mutex2 brought the cpu usage down to normal 12i cant believe the stdlock function is that inefficient could this be a bug in g 463edit example include iostreaminclude threadinclude mutexinclude chronoinclude condition variablestdmutex mutex1 mutex2stdcondition variable cond varbool cond false done falsevoid take locks while done stdthis threadsleep for stdchronoseconds 1 stdunique lockstdmutex lock1 mutex1 stddefer lock stdunique lockstdmutex lock2 mutex2 stddefer lock stdlock lock1 lock2 stdthis threadsleep for stdchronoseconds 1 lock1unlock lock2unlock void conditional code stdunique lockstdmutex lock1 mutex1 stddefer lock stdunique lockstdmutex lock2 mutex2 stddefer lock stdlock lock1 lock2 stdcout t4 waiting n while cond cond varwait lock1 stdcout t4 condition met n int main stdthread t1 take locks t2 take locks t3 take locks stdthread t4 conditional code stdcout threads started n stdthis threadsleep for stdchronoseconds 10 stdunique lockstdmutex lock1 mutex1 stdcout mutex1 locked n stdthis threadsleep for stdchronoseconds 5 stdcout setting conditionnotify n cond true cond varnotify one stdthis threadsleep for stdchronoseconds 5 lock1unlock stdcout mutex1 unlocked n stdthis threadsleep for stdchronoseconds 6 done true t4join t3join t2join t1join,['c++'] +385043,what is the difference between forwarda and ta templatetypename t void outert t innerforwardtt templatetypename t void outert t innertt what is the difference,['c++'] +385045,javascript does not work in android webview i want to load a url by webviewthe url is this page can work correctly on system default browser but in my webview some javascript not workingjavascript is enabled and i dont know whats wrong with iti would appreciate any helpprivate void initui webview webview findviewbyidridweb view webviewgetsettingssetjavascriptenabledtrue final navigationbar navigationbar navigationbar findviewbyidridnavigationbar navigationbarrefreshui navigationbarrightbuttonsetimageresourcerdrawablerefresh navigationbarrightbuttonsetvisibilityviewvisible navigationbarrightbuttonsetonclicklistenernew onclicklistener public void onclickview v refresh navigationbarleftbuttonsetimageresourcerdrawableback navigationbarleftbuttonsetonclicklistenernew onclicklistener public void onclickview arg0 webviewgoback webviewsetwebviewclientnew webviewclient public boolean shouldoverrideurlloadingwebview view string url viewloadurlurl return true public void onpagefinishedwebview view string url navigationbarleftbuttonsetvisibilitywebviewcangoback viewvisible viewinvisible superonpagefinishedview url refreshupdate the problem is solvedjust add following codewebviewgetsettingssetdomstorageenabledtrue,"['javascript', 'android']" +385098,get files size from bytes array without saving to thisc i have a bytes array and i want to calculate what would be the file size if i will write these bytes to file is it possible without writing the file to thisc,"['c#', '.net']" +385104,find the smallest number that is greater than a given number in a sorted list given a sorted list of numbers i need to find the smallest number that is greater than a given number consider this listarr12357101131151181191313353373383say the specified number is 320 then my method should return 353 as 353 is the smallest number greater than 320i am trying to use a slightly modified form of binary search however on execution the program goes into infinite loopdef modbinarysearcharrx llenarr midl2 if arrmidx and arrmid1x return arrmid elif arrmidx and arrmid1x modbinarysearcharrmidlx else modbinarysearcharr0midxnintraw inputarr12357101131151181191313353373383print modbinarysearcharrncan someone point out what i am doing wrong,['python'] +385109,customize the delete button in uitableview i have the functionality for swipe to delete the tableviewcell i want to customize the delete button is this possible and how to access the delete button,['iphone'] +385133,getting pid of spawned exec in phing i am using phing and running selenium server via exectask sometimes i need to stop running server by killing its processis there a possibility in phing of getting pid of process spawned in exectask,['php'] +385165,jquery form validation on button click i have a simple page with a form and a button outside the form i am trying to validate the form on the button clicki have added the rules for validation of the form on the documentonready function however the form is not getting validated htmlhtmlhead script srclibjquery152jsscript script srclibjqueryvalidatejsscript script srclibmyjsjsscriptheadbodyform idform1 nameform1 field 1 input idfield1 typetext classrequiredformdiv input idbtn typebutton valuevalidatedivbodyhtmljsdocumentreadyfunctionform1validate rules field1 required messages field1 please specify your name btnclickfunction form1validate this is not working and is not validating the formany idea whats wrong,['jquery'] +385197,how to refresh custom listview using baseadapter in android sir how can i refresh my custom listview using baseadapter i do not know what to place or where to place it in my code please help me thanks in advancepublic class editdetails extends activitypublic string namechangedpublic string numchangedpublic string namepublic string numpublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayouteditdetails final edittext sqlname edittextfindviewbyidrideditname final edittext sqlnumber edittextfindviewbyidrideditnumber name customlistviewname num customlistviewnumber button bupdate buttonfindviewbyidrideditupdate button bview buttonfindviewbyidrideditview sqlnamesettextname sqlnumbersettextnum bupdatesetonclicklistenernew onclicklistener public void onclickview arg0 namechanged sqlnamegettexttostring numchanged sqlnumbergettexttostring groupdb info new groupdbeditdetailsthis infoopen long rowid infogetrowidname num infoupdatenamenumberrowid namechanged numchanged arraylistcontact searchresults infogetview mycustombaseadapter mcba new mycustombaseadaptereditdetailsthis searchresults toastmaketextgetapplicationcontext update successful toastlength longshow infoclose bviewsetonclicklistenernew onclicklistener public void onclickview arg0 intent intent new intent intentsetclasseditdetailsthis customlistviewclass startactivityforresultintent 0 here is where i thisplayed my listviewpublic class customlistview extends activity final context context thispublic static string namepublic static string numberoverridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain groupdb info new groupdbthis infoopen arraylistcontact searchresults infogetview final listview lv listview findviewbyidridsrlistview lvsetadapternew mycustombaseadapterthis searchresults infoclose lvsetonitemclicklistenernew onitemclicklistener public void onitemclickadapterview a view v int position long id todo autogenerated method stub object o lvgetitematpositionposition final contact fullobject contacto alertdialogbuilder alertdialogbuilder new alertdialogbuildercontext alertdialogbuilder setmessageselect action setcancelablefalse setpositivebuttonedit new dialoginterfaceonclicklistener public void onclickdialoginterface dialogint id toastmaketextgetapplicationcontext edit toastlength longshow name fullobjectgetname number fullobjectgetphonenumber intent contactintent new intentmyfolderprojeditdetails startactivitycontactintent and here is my baseadapter classpublic class mycustombaseadapter extends baseadapter private static arraylistcontact searcharraylistprivate layoutinflater minflaterpublic mycustombaseadaptercontext context arraylistcontact results searcharraylist results minflater layoutinflaterfromcontextpublic int getcount return searcharraylistsizepublic object getitemint position return searcharraylistgetpositionpublic long getitemidint position return positionpublic view getviewint position view convertview viewgroup parent viewholder holder if convertview null convertview minflaterinflaterlayoutcustom row view null holder new viewholder holdertxtname textview convertviewfindviewbyidridname holdertxtphone textview convertviewfindviewbyidridphone holderstatus textview convertviewfindviewbyidridstatus convertviewsettagholder else holder viewholder convertviewgettag holdertxtnamesettextsearcharraylistgetpositiongetname holdertxtphonesettextsearcharraylistgetpositiongetphonenumber holderstatussettextsearcharraylistgetpositiongetstatus return convertviewstatic class viewholder textview txtname textview txtphone textview status,['android'] +385201,maxwidth adjusts to fit text not the best title but anywayi have an element with a maxwidth and some textif the text is longer than will fit on one line i get thismy text here hello everyone in other words it takes up the full maxwidth but there is an empty space on the right due to the word moving downis there any way to make it so that this happens insteadmy text here helloeveryone,['css'] +385213,split string into strings by length is there a way to take a string that is 4x characters long and cut it into 4 strings each x characters long without knowing the length of the stringfor examplex qwertyuisplitx one two three fourtwoer,['python'] +385232,how to write a simple java program that finds the greatest common divisor between two numbers here is the questionwrite a method named gcd that accepts two integers as parameters and returns the greatest common divisor of the two numbers the greatest common divisor gcd of two integers a and b is the largest integer that is a factor of both a and b the gcd of any number and 1 is 1 and the gcd of any number and 0 is that numberone efficient way to compute the gcd of two numbers is to use euclids algorithm which states the followinggcda b gcdb a b gcda 0 absolute value of ai am really confused as to how to solve this problem i just want some hints and tips as to what i did wrong in the program i have so far i have to put in a scanner that is my teachers requirementdo not give me a full code as i kinda want to solve this out myself maybe just give me a hint on how i incorporate this formula that you see above and if youre wondering why i put in the 0 it is because i thought that if you have two numbers say 0 and 90 their gcd would be 0 rightalso my code has to include while loopsi wouldve preferred if loopsthanks in advance my current programpublic static void mainstring args scanner console new scannersystemin int a consolenextint int b consolenextint gcd a b public static void gcdint a int b systemoutprinttype in two numbers and i will print outs its greatest common divisor int gcdnum1 consolenextint int gcdnum2 consolenextint while gcdnum1 0 gcdnum1 0 while gcdnum2 gcdnum1 int gcd gcdnum1 gcdnum2 systemoutprintgcdnum1 gcdnum2,['java'] +385243,mysql case to update multiple columns i would like to update multiple columns in my table using a case statement but i cannot find how to do this is this even possible i came up with a query likeupdate tablename set case name when name1 then col15col2 when name2 then col13col2whatever else col10col2 endthis is however not a valid query is there anyway of achieving the same thing in valid sqlgrviller,"['mysql', 'sql']" +385248,can i use odata client code inside a portable class library i am trying to build a portable class library targeting net silverlight windows rt and windows phone that acts as an odata client i am using visual studio 2012 when i created the service reference to my odata server side i got the following error message unable to add a service reference to the specified odata feed because wcf data services is not installed for this target framework to install a supported version of wcf data services see when i go to the url listed in the error message i can choose between a library for windows rt and one for windows phone so this does not seem to work for a portable class library is there any secret workaround to this or do i have to code my own odata client with bare http requests also if i do have to use bare http requests is there at least some kind of api i can build on for json or xml serialization deserialization that works inside a portable class libararythanksadrian,['.net'] +385432,not a png filcommand copypng emitted errors but did not return a nonzero exit code to indicate failure i am getting following error while adding images the running the project on ipadit worked fine on simulator with all images but on ipad its running but showing no imagescopypngfile usersuserlibrarydeveloperxcodederiveddatarimagegallerycmwaittvclhwgxfpcoarddipylivbuildproductsdebugiphoneosrimagegalleryappdefaultpng photobrowserdemodefaultpng cd usersuserdesktopdemo setenv path applicationsxcodeappcontentsdeveloperplatformsiphoneosplatformdeveloperusrbinapplicationsxcodeappcontentsdeveloperusrbinusrbinbinusrsbinsbin applicationsxcodeappcontentsdeveloperplatformsiphoneosplatformdeveloperusrbincopypng compress usersuserdesktopdemophotobrowserdemodefaultpng usersuserlibrarydeveloperxcodederiveddatarimagegallerycmwaittvclhwgxfpcoarddipylivbuildproductsdebugiphoneosrimagegalleryappdefaultpng not a png filcommand applicationsxcodeappcontentsdeveloperplatformsiphoneosplatformdeveloperusrbincopypng emitted errors but did not return a nonzero exit code to indicate failurenull while reading usersuserdesktopdemophotobrowserdemodefaultpng pngcrush caught libpng errornull could not find file usersuserlibrarydeveloperxcodederiveddatarimagegallerycmwaittvclhwgxfpcoarddipylivbuildproductsdebugiphoneosrimagegalleryappdefaultpngcommand applicationsxcodeappcontentsdeveloperplatformsiphoneosplatformdeveloperusrbincopypng emitted errors but did not return a nonzero exit code to indicate failure,"['iphone', 'ios']" +385434,issue in adding m2 repo variable in eclipse i am adding m2 repo variable in eclipse using window preferences java build path classpath variables new and then providing name as m2 repo and selecting maven repository folder then i see this variable getting added in the classpath variables list then i click ok buttonafter that if again i see the above classpath variables then i do not find the m2 repo variable there due to which i am getting unbound classpath variable m2 repojar error in my projectcan someone please help,['java'] +385439,communications link failure last packet sent to the server was 1 ms ago i tried to connect to mysql database but i failed and this error is shown communications link failure last packet sent to the server was 1 ms agoand this is my code anyone can help me please package android programmers guidetestconnectionimport javasqlconnectionimport javasqldrivermanagerimport androidosbundleimport androidappactivityimport androidgraphicscolorimport androidviewmenuimport androidwidgetedittextpublic class testconnection extends activity override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity test connection connection conn null string url jdbcmysql1270013306test string driver commysqljdbcdriver string username root string password root try classfornamedrivernewinstance conn drivermanagergetconnectionurlusernamepassword edittext edittextedittext findviewbyidridedittext1 edittextsetbackgroundcolorcolorgreen edittextsettextconnected to the database connclose edittextsetbackgroundcolorcolorblue edittextsettextthisconnected from database catch exception e eprintstacktrace override public boolean oncreateoptionsmenumenu menu inflate the menu this adds items to the action bar if it is present getmenuinflaterinflatermenuactivity test connection menu return true,"['java', 'android', 'mysql']" +385473,implementing oauth in sugarcrm using net i have a web application developed in net framework i am trying to implement oauth in sugarcrm in order to integrate it with my applicationsthe oauth mechanism given by sugarcrm is using php click herewhere as my application is designed in aspi am trying to figure out solution like converting php code to asp or implementing the same mechanism in my application for same but got no solutionany help would be appreciated,"['php', 'asp.net']" +385502,javascript extension to use c based apisclutter in a webapp my goal is to use the c libraries to form web appsi have choosen the way to do that via using swig tool the swig tool requires three things1 c file which defines all the functions2 i file also called interface file which is creating theinterface to load the apis wherin i used the extern keyword3 app written in javascript extension js filei used swig tool to compile and run this app to verify the js file has made correctlythe application is running fine on xming x11 windowon compilation it creates wrapo o file and libfilenamesonow i want to run this app on browser pagefor this i have used the webkit clutter port which gives us the mxlauncher codei am using webkit iweb view load uriwebkit iweb viewview filenamehtml api to load my html file to run that javascript on my webpage viewi am linking the so created at the compilation time error message js console filefilenamejs referenceerror cannot find variable examplefilenamec int gcdint x int y enter code here int g g y while x 0 g x x y x y g return gfilenamei module exampleextern int gcdint x int yfilenamejsx 42y 105g examplegcdxyhow to get my goal to be achieved,['javascript'] +385579,d3 line acting as a closed path update heres an example of the issue i am trying to use d3 to code a line graph and my line is being closed at the end by which i mean it acts as a closed path where the first and last points are the same my data comes in the following json format entitya time 1230 time since epoch attribute1 123 numeric value attribute2 123 numeric value time 1230010 time since epoch attribute1 123 numeric value attribute2 123 numeric value entityb same format as above i am using a standard declaration of a line d3svgline with a function for x and yvar line d3svgline xfunctiond return x scaledc date yfunctiond return y scaledtotal then inside a for loop that iterates over the entities i am appending a svgpathcanvasappendsvgpath attrd linedataentityeverything else about the graph works the points are correctly placed i have multiple independent lines per entity the axes are drawn etc however each independent line acts as a closed paththanks for in advance for any help,['javascript'] +385604,how do you manage the user documentation for an android application coming from the linux desktop world i would be used to write the user documentation of my app as a set of markdowndocbookwhatever files generate the corresponding html files at build time and thistribute them together with my app in order to be viewed with some kind of help viewer like yelp kchmviewer okular or similar we are talking of guibased apps like gnome and kde so manpages and info pages are not involved hereandroid does not provide anything like that no officiallysupported suggestedmandatory way to create manage and thistribute the end users documentation afaik at least no tools for this task put aside the web browser andor the webviewcurrently we are maintaing a set of html files totally indipendent from the source tree and we just supply the user with a link to read them on the web from his own device if the screen size allows such a kind of reading or from a different devicethe alternative seems to beput all of your stuff in a asset or res directoryshow the user the indexhtml page into the default web browser or inside a webview inside a dialog box and leave him navigate the rest of the docudoes anybody knows of any better more organized better engineered way to create manage and thistribute the user documentation for an android applicationand yes i am aware that mobile applications usually are expected to be almost completely selfdocumenting that is the ui shoul lead the user in the right way without any other help unfortuately we are developing something that requires some amount of previous knwoledge in order to be used,['android'] +385664,map collection of objects i am trying to introduce automapper into an application for the first time but i keep getting an error saying i have some invalid argumentsmy modelnamespace storegradeslibmodels public class store key public int storeid get set required maxlength120 public string storename get set required maxlength20 public string storenumber get set required maxlength120 public string managername get set required public long phonenumber get set required public string addressline1 get set public string addressline2 get set required public string postcode get set required public int wallarea get set required public int floorarea get set required public int numwindows get set required public int numdesks get set required public int numdoors get set required public int storegradeid get set required public bool active get set public virtual storegrade storegrade get set timestamp public byte timestamp get set my view modelnamespace storegradeslibviewmodels public class storevm public int storeid get set public bool active get set public byte timestamp get set requirederrormessage store name is required thisplayname store name public string storename get set requirederrormessage store number is required public string storenumber get set requirederrormessage store manager is required thisplayname manager name public string managername get set requirederrormessage contact number is required thisplayname phone number public int phonenumber get set requirederrormessage address line 1 is required thisplayname address line 1 public string addressline1 get set thisplayname address line 2 public string addressline2 get set requirederrormessage postcode is required public string postcode get set requirederrormessage must input wall area thisplayname wall area public int wallarea get set requirederrormessage must input floor area thisplayname floor area public int floorarea get set requirederrormessage must input number of windows thisplayname windows public int numwindows get set requirederrormessage must input number of desks thisplayname desks public int numdesks get set requirederrormessage must input number of doors thisplayname doors public int numdoors get set requirederrormessage store must have a grade public storegrade storegradeid get set public string address get return storename addressline1 addressline2 postcode created mappingscreatemapstore storevmcreatemapstorevm storewithin my controller i am trying to map a selection of stores to storevm i am currently getting my stores as sovar stores dbstoreincludes sstoregradestores from s in dbstorewheres sactiveequalstrue select si am wanting to map the selection of stores to storevm i have tried the following but i get an invalid parameters warningvar vmstores mappermapstore storevmstoresi am receiving the error that the best overloaded method match has some invalid argumentscan anyone point me in the right direction,['c#'] +385737,full integration testing for nodejs and the client side with yeoman and mocha i got awesome client side tests that i run with yeoman yeoman compiles my coffeescript opens up the test page in a server visit it with phantomjs and pass all the tests results to the command line the process is pretty hacky the test results are passed via alert messages to the phantom process which creates a temporary file and fills it with the messages as json yeoman well grunt loops over the temporary file parses the tests and thisplays them in the command linethe reason i explained the process is that i want to add a few things to it i got server side tests as well they use mocha and supertest to check the api endpoints and a rethis client to make sure the database state is as expected but i want to merge those two test suitesi do not want to write client side mock response for the server calls i do not want to send the server mock data somewhere along the way i will change the server or the client and the test will not fail i want to do a real integration testing so whenever a test finishes in the client side i want a hook to run a relevant test on the server side checking db state session state moving to a different test pageare there any solutions to this or altenatively where do i start hacking on yeoman grunt gruntmocha to make this worki think the phantom handlers in gruntmocha is a good place to start handle methods passed from phantomjs including mocha hooks var phantomhandlers mocha hooks suitestart functionname unfinishedname true currentmodule name suitedone functionname failed passed total delete unfinishedname teststart functionname currenttest currentmodule currentmodule name verbosewritecurrenttest testfail functionname result resulttestname currenttest failedassertionspushresult testdone functiontitle state log errors if necessary otherwise success if state failed list assertions if optionverbose logerror logfailedassertions else logwritefred else verboseokorwrite done functionfailed passed total duration var nduration parsefloatduration 0 statusfailed failed statuspassed passed statustotal total statusduration mathroundnduration100100 print assertion errors here if verbose mode is thisabled if optionverbose if failed 0 logwriteln logfailedassertions else logok error handlers done fail functionurl verbosewriterunning phantomjsorwrite logerror gruntwarnphantomjs unable to load url uri 90 done timeout function logwriteln gruntwarnphantomjs timed out possibly due to a missing mocha run call 90 consolelog passthrough console consolelogbindconsole debugging messages debug logdebugbindlog phantomjs thanks there will be a bounty on this,['javascript'] +385760,how to make bold text in php exported xls file i am working in core phpi need to make header text in bold format and remains normal text formatthe xls file will be export from phpi am not using any plugin in my project i need to complete this without using any pluginbut i unable to solve thismy code as followsheader part crationwhilermysql fetch arrayexe need to set bold but it is not working it giving error header brquestionbt header rquestiont body part crationwhilermysql fetch arrayexe data ranswert code continuousand exporting code as followsheadercontenttype applicationoctetstreamheadercontentthisposition attachment filenamereportsxlsheaderpragma nocacheheaderexpires 0print headernndataexporting file working fine but i unable to make headers are boldplease any help much be appreciated,['php'] +385791,finding all the concrete classes that implements abstract class in eclipse clicking f3 on the change class in eclipse change change refactoringcreatechangemonitori could open the classjava public abstract class change implements iadaptable however i need the concrete java classes that implements the change class how can i find them in eclipse,['java'] +385821,how to copy a file in cc with libssh and sftp i am posting here because i need help with some code relating with libsshi read all the official documentation here but still i do not understand the things i need to do if someone can en light me i would be pleasedactually i want to copy a file from a client to a remote server but i do not understand how to do it with the library libssh and the function sftp in libsshthe situation is that the ssh session is open and the sftp session is open too i can create a file and write in it from the client to the server with the integrated function of lib sshi did not find an easy way to copy a file from the client to the server with a simple function like sftp transfersourcefilelike cmy documenthello worldtxtremotefilehomeuserhello worldtxtrightread and write with what i have understood from the tutorial it is first creating a file in the remote location server then it is opening this file with this line of code file sftp opensftp homehelloworldtxtaccess type1after that the file is created on the server and then it is writing into this created file with a bufferconst char helloworld hello worldnint length strlenhelloworldnwritten sftp writefile helloworld lengthmy question is now if i have a file for example a doc file and i want to transferupload that file from cmydocumentdocumentdoc to remote the remote server homeuserdocumentdoc how can i do it with this method how can i put this file into the sftp write function to send it like the helloworld in the sample function i may be not good enough in programming to understand but i really tried to understand it and i am stuck with itthanks in advance for your helpsee below a sample of the code i used to test set variable for the communication char buffer256 unsigned int nbytes create a file to send by sftp int access type o wronly o creat o trunc const char helloworld hello worldn int length strlenhelloworld open a sftp session sftp sftp newmy ssh session if sftp null fprintfstderr error allocating sftp session sn ssh get errormy ssh session return ssh error initialize the sftp session rc sftp initsftp if rc ssh ok fprintfstderr error initializing sftp session sn sftp get errorsftp sftp freesftp return rc open the file into the remote side file sftp opensftp homehelloworldtxtaccess type1 if file null fprintfstderr cannot open file for writing snssh get errormy ssh session return ssh error write the file created with whats into the buffer nwritten sftp writefile helloworld length if nwritten length fprintfstderr cannot write data to file sn ssh get errormy ssh session sftp closefile return ssh error,"['c++', 'c']" +385843,c string literal too big for character with msvc 2010 i try to compile this in c or c mode needs to be compilable in both and it does not work why i thought and found in the documentation that x takes the next two characters as hex characters and not more 4 characters when using x i also learned that there is no portable way to use character codes outside ascii in c source code anyway so how can i specify some german iso88591 charactersint main char x xbcd why is this not char188 d returns testc2 error c2022 3021 too big for character and a warning with gcc,['c'] +385855,good way to get any value from a java set given a simple sett what is a good way fast few lines of code to get any value from the setwith a list it is easylistt things return thingsget0but with a set there is no get method because sets are not ordered,['java'] +385861,error when new is called from a metaclass the following code produces an errorclass foometatype def new mcl classname bases classdict return type new mcl classname bases dict def init cls name bases classdict superfoometa cls init name bases classdict d dict for key item in classdictitems if keystartswith setattrcls key item else dkey item setattrcls items dclass fobject metaclass foometaclass passingfoo def init self args kw passclass failingfoo def new cls args kw return superfailing cls new cls def init self args kw passfail failingthe error istraceback most recent call last file foometapy line 30 in module fail failingtypeerror unbound method new must be called with failing instance as first argument got foometa instance insteadthere appears to be some difference in the way new is called when called from a metaclass1 anyone know why this is happening2 is there some way to fix it,['python'] +385929,what are open source ffmpeg players for iosandroid i have been searching for open source ffmpeg player and i found somes but i think there is a lot more out there if you know one please drop a line in the comment or answer i am working on ios but really want to look further to see what has been made for androidhere are what i foundmooncatventures groupkxmovieplayer use opengles core audioffmpeg for ios with opengles audioqueueiframeextractor,"['android', 'ios']" +385947,how to make a c11 stdunordered set of stdweak ptr i have a set like this setweak ptrnode owner lessweak ptrnode setnameit works fine but i would like to change it to an unordered set however i get about six pages of errors when i do that any ideas how to do thatafter looking through all the pages of error messages i found to lines that might helpusrincludec47bitsfunctional hashh607 error static assertion failed stdhash is not specialized for this typeusrincludec47bitsstl functionh in instantiation of abool stdequal to tpoperatorconst tp const tp const with tp stdweak ptrnodea,['c++'] +385974,google maps android api v2 authorization failure my steps got sha1 code from debugkeystore create app in google apis console enabled google map api v2 input sha1mypackagename get api key created androidmanifest file permission androidnamemypackagenamepermissionmaps receive androidprotectionlevelsignature usespermission androidnamemypackagenamepermissionmaps receive usessdk androidminsdkversion8 androidtargetsdkversion15 usespermission androidnameandroidpermissioninternet usespermission androidnameandroidpermissionwrite external storage usespermission androidnameandroidpermissionaccess coarse location usespermission androidnameandroidpermissionaccess fine location usespermission androidnamecomgoogleandroidprovidersgsfpermissionread gservices usesfeature androidglesversion0x020 androidrequiredtrue application androidlabelstringapp name androidicondrawableic launcher androidhardwareacceleratedtrue metadata androidnamecomgoogleandroidmapsv2api key androidvaluemy api key here activity androidnamemyactivity androidlabelstringapp name intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity applicationmanifestcreated layout put googleplayservicesjar to libs after compilation i have got crash errorandroidruntime10182 fatal exception main javalangnoclassdeffounderror comgoogleandroidgmsrstyleable at comgoogleandroidgmsmapsgooglemapoptionscreatefromattributesunknown source at comgoogleandroidgmsmapsmapfragmentoninflateunknown source at androidappactivityoncreateviewactivityjava4716 at androidviewlayoutinflatercreateviewfromtaglayoutinflaterjava680 at androidviewlayoutinflaterinflatelayoutinflaterjava466 at androidviewlayoutinflaterinflatelayoutinflaterjava396 at androidviewlayoutinflaterinflatelayoutinflaterjava352 at comandroidinternalpolicyimplphonewindowsetcontentviewphonewindowjava270 at androidappactivitysetcontentviewactivityjava1881 at comexamplegm2myactivityoncreatemyactivityjava16 at androidappactivityperformcreateactivityjava5104 at androidappinstrumentationcallactivityoncreateinstrumentationjava1080 at androidappactivitythreadperformlaunchactivityactivitythreadjava2144 at androidappactivitythreadhandlelaunchactivityactivitythreadjava2230 at androidappactivitythreadaccess600activitythreadjava141 at androidappactivitythreadhhandlemessageactivitythreadjava1234 at androidoshandlerthispatchmessagehandlerjava99 at androidoslooperlooplooperjava137 at androidappactivitythreadmainactivitythreadjava5039 at javalangreflectmethodinvokenativenative method at javalangreflectmethodinvokemethodjava511 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava793 at comandroidinternaloszygoteinitmainzygoteinitjava560 at dalviksystemnativestartmainnative methodafter that i have changed layout toxml version10 encodingutf8framelayout xmlnsandroid androidididmap androidlayout widthmatch parent androidlayout heightmatch parent and changed myactivity to superoncreatesavedinstancestate setcontentviewrlayoutmain fragmentmanager manager getfragmentmanager fragmenttransaction transaction managerbegintransaction transactionaddridmap mapfragmentnewinstance transactioncommitas result the application was started but i did not see the map console logerrorgoogle maps android api10369 authorization failure,['android'] +386003,restricting the use of an assembly from assemblies that are not signed i have a requirement to have a restriction in an assembly such that only assemblies that are signed with a given key can use it i am inexperienced but what i understand is signing is done to help identify who created the assembly hence just signing this assembly should not be enough to ensure that all calling assemblies are signed probably the reverse is true ie if an assembly is signed all the assemblies it depends on should be signedby the same key perhaps what would be the way to meet the requirement,"['c#', '.net']" +386009,character limit of a javascript string variable can javascript string store 100k characters i have written a script where a string from php is passed to a variable in javascript it works fine when it is cut short to almost ten thousand characters but breaks the script when attempting to pass the entire string whose length is a bit greater than 100k no errors could be found though is there any solution for this as to any way of increasing character limit of javascript variable i am just a beginner would appreciate is some one could find a solution for this,"['php', 'javascript']" +386017,phpmyadmin logs out after 1440 secs in my local development ubuntu box i use mysql and phpmyadmin to work with the database whenever phpmyadmin is idle for 1440 secs 24min the session expires i lose my place and have to login and start over i tried changing the cfglogincookievalidity 3600 9 inside configincphp but it still times out in 1440 seconds i have restarted everything and cleared the browser cache firefox history clear recent history cache everythingi am not sure why the increased timeout does not take effect what am i doing wrong,['mysql'] +386054,what is 0 1 in ruby i am a java developer and i have been given ruby code to understand and later to work oni went through the ruby tutorials on tutorialspointcom but i cannot figure out what 0 isit is being assigned to a variable in the code and it is definitely not a commandline argument because i wrote code to test that and it failedso can anyone say what the significance of it is,['ruby'] +386062,custom android acceleratedecelerateinterpolator i am trying to use acceleratedecelerateinterpolator and custom iti can see that interpolators like decelerateinterpolator have a factor field so you can change its behaviors but acceleratedecelerateinterpolator has nonwhen i am using acceleratedecelerateinterpolator i almost cannot even notice that the interpolator is doing any thing the animation looks very linear so is there any way to factor the acceleratedecelerateinterpolator or change it in any waythanks,['android'] +386112,php a slow string manipulation i have some very large data files and for business reasons i have to do extensive string manipulation replacing characters and strings this is unavoidable the number of replacements runs into hundreds of thousandsit is taking longer than i would like php is generally very quick but i am doing so many of these string manipulations that it is slowing down and script execution is running into minutes this is a pain because the script is run frequentlyi have done some testing and found that str replace is fastest followed by strstr followed by preg replace i have also tried individual str replace statements as well as constructing arrays of patterns and replacementsi am toying with the idea of isolating string manipulation operation and writing in a different language but i do not want to invest time in that option only to find that improvements are negligible plus i only know perl php and cobol so for any other language i would have to learn it firsti am wondering how other people have approached similar problemsi have searched and i do not believe that this duplicates any existing questions,['php'] +386113,maven webapp metainf contextxml i am using maven 3 and i am trying to add metainf folder under webapp folder so i am trying to do the followingsrc main webapp metainf contextxml webinfbelow is my pom filexml version10project xsischemalocation xmlnsxmlnsxsimodelversion400modelversiongroupidcomdatagroupidartifactidjavawebappartifactidversion001snapshotversionpackagingwarpackagingnamejavaweb applicationname shared version number propertiespropertiesorgspringframeworkversion306releaseorgspringframeworkversionpropertiesdependenciesdependency groupidjunitgroupid artifactidjunitartifactid version381version scopetestscope dependency dependenciesbuildfinalnamedatafinalnamebuildparentgroupidcomdatagroupidartifactidjavaparentartifactidversion001snapshotversionparentprojectunder srcmainresources i have added a metainfcontextxml when the war file is packaged using mvn package the structure looks like thisdata webapp metainf webinf indexjspthe relevant files under webinf can be seen however the metainf folder is blank my default maven will add resources under the webinfclassesi want specifically would like to havedata webapp metainf contextxml webinfhow is this possible i have tried other things but still it does not work the contextxml contains the followingxml version10 encodingutf8context pathdata1i have tried removing the metainf folder from srcmainresources and directly put it under webappmetainf the contextxml thisplays but when deployed into tomcat the context root that i have defined does not work,['java'] +386140,localstorage array of objects handling array of json objects are stored in html5 localstoragefor now delimiter is for accessing and modifying array of objects from localstorage split and join operations usedhowever delimiter approach looks unstablefor instance could be met inside objects attribute and split operation will be uncorrectit could be used for delimiterbut i am not certain it will be stable alsois there any robust way to handle localstorage presented as array of objectsas far localstorage saved as stringeditone of stoppers is that array of object could not be saved to localstorage as classical localstorage converts it automatially to string like my current data within localstoragenamevolvoid033namesaabid034assumptionperhapsi can add at the start and at the endbut it looks not gracefull,['javascript'] +386149,expected or before if i made a stupid mistake forgot semicolon too much python lately but got an interesting error message from gcc expected or before ifi know those error messages provide just an upper bound for possible source code but i would like to know if there is any construct in c such that if token really comes after and not after,['c'] +386177,properties containing references goodbad i am sort of new in androidjava normally work with php and javascript i have read a few articles about memory leaking problems with apps when references are used the wrong way so i have a question about something i have often seen in other peoples work a lot of people when they need to access things like views and such in multiple methods keeps a reference of this in a property which are assigned during the creation of the activity from what i have read or at least understood of what i have read this is one of the courses for memory leaks is it better to assign an id to the objects and then search for them in each method if so what about dynamic created objects,['android'] +386185,converting between datetime timestamp and datetime64 how do i convert a numpydatetime64 object to a datetimedatetime or timestampin the following code i create a datetime timestamp and datetime64 objectsimport datetimeimport numpy as npimport pandas as pddt datetimedatetime2012 5 1 a strange way to extract a timestamp object there is surely a better wayts pddatetimeindexdt0dt64 npdatetime64dtin 7 dtout7 datetimedatetime2012 5 1 0 0in 8 tsout8 timestamp 20120501 0in 9 dt64out9 numpydatetime6420120501t010100note it is easy to get the datetime from the timestampin 10 tsto datetimeout10 datetimedatetime2012 5 1 0 0but how do we extract the datetime or timestamp from a numpydatetime64 dt64update a somewhat nasty example in my dataset perhaps the motivating example seems to bedt64 numpydatetime6420020628t010100which should be datetimedatetime2002 6 28 1 0 and not a long 1025240l,['python'] +386187,how do i fill a va list if i have a va list i know how to extract all its elements void printintsint n va list va va startva n forunsigned int i0 in i int argva argva int printfdarg va endva so when i call printints3123 the va list get filled of all the parametersbut how do i manually fill a va list without using va start i mean that i want something like va list vapush argva int 5 and so on until i fill all parametersi need this because there is a function that accept a va list as argument and i do not know how to fill that va list of all its parameters,['c'] +386196,systemruntimecachingmemorycache vs httpruntimecache are there any differences i am wondering if there are any differences between memorycache and httpruntimecache which one is preferred in aspnet mvc projectsas far as i understand both are thread safe api is from first sight more or less the same so is there any difference when to use which,['c#'] +386220,the http request is unauthorized with client authentication scheme ntlm the authentication header received from the server was negotiatentlm i have looked through a ton of so articles and even other sites but cannot seem to get this service working i have a soap service i am trying to hit and it is configured like thissystemservicemodel bindings basichttpbinding binding nameproviderssoapbinding security modetransportcredentialonly transport clientcredentialtypentlm proxycredentialtypenone realm security binding basichttpbinding bindings client endpoint address bindingbasichttpbinding bindingconfigurationproviderssoapbinding contractservicereference1providerremote nameproviders clientsystemservicemodelhowever i am getting the following error when hitting it from my console applicationthe http request is unauthorized with client authentication scheme ntlm the authentication header received from the server was negotiatentlmcan somebody help me out,"['c#', '.net']" +386225,zip lists in python i am a python newbie and i am trying to learn how to zip lists to this end i have a program where at a particular point i do the followingx1 x2 x3 stuffcalculationswithdataathis gives me three lists x1 x2 and x3 each of say size 20now i dozipall zipx1 x2 x3however when i doprint len of zipall s lenzipalli get 20 which is not what i expected i expected three i think i am doing something fundamentally wrong,['python'] +386262,c datagridview doubleclick on row with fullrowselect i have a datagridview in my c application and the user should only be able to click on full rows so i set the selectionmode to fullrowselectbut now i want to have an event which is fired when the user double clicks on a row i want to have the row number in a messageboxi tried the following thisroomdatagridviewcellcontentdoubleclick new systemwindowsformsdatagridviewcelleventhandlerthisroomdatagridview cellconta aentdoubleclick private void roomdatagridview cellcontentdoubleclickobject sender datagridviewcelleventargs e messageboxshowerowindextostring unforunately nothing happens what am i doing wrong,['c#'] +386280,kerberos doublehop in aspnet 40 sql2008r2 i have an aspnet 40 application within which i need to forward the authentication to the databasefor the purposes of this request for assistance lets call the web server app1 and the database server sql1the sql2008r2 database service is running as a named instance sql2008r2 under a custom domain account sqlserver the server is running windows server 2008 r2 enterprise editioni have created an spn for thissetspn a mssqlsvcsql1mydomainlocalsql2008r2 sqlserverthe aspnet application is running under an application pool using a custom domain account webapplicationuser in integrated pipeline mode it is currently running on my laptop running windows 7 enterprise but will eventually be hosted on windows server 2008 r2 standard editioni have created 2 spns for the application on the windows 7 machine that i am currently running fromsetspn a httpapp1 webapplicationusersetspn a httpapp1mydomainlocal webapplicationuserwithin active directory users and computers i have selected the webapplicationuser account and i have enabled constrained delegation to mssqlsvcsql1mydomainlocalsql2008r2 using any protocol i have also tried using kerbero onlythe application is setup in iis 75 and the authentication is set to thisable anonymouse basic digest and forms whilst enabling aspnet impersonation and windows the windows authentication has extended protection turned off and kernelmode authentication enabled the providers are negotiate and ntlm in that orderthe aspnet application uses ef and the connection string is configured to use integrated securityconnectionstrings add namemycontext connectionstringmetadataresdatamymodelcsdlresdatamymodelssdlresdatamymodelmslprovidersystemdatasqlclientprovider connection stringquotdata sourcesql1mydomainlocalsql2008r2initial catalogmydatabasepersist security infofalseintegrated securitytruemultipleactiveresultsetstruequot providernamesystemdataentityclient connectionstringsmy web config specifies both windows authentication and impersonation since i a using async pages i have also enabled inpersonation policy flowingruntime alwaysflowimpersonationpolicy enabledtrue runtimesystemweb authentication modewindows identity impersonatetrue systemwebif i log on locally on web1 and browse to the application using ie this all works but this does not involve the double hop that i am trying to resolveif i log on to another machine and then browse to the application using ie or i browse from the local machine using firefox this does not work note firefox does prompt me for the login details the connection to the database fails with login failed for user nt authorityanonymous logonunlike a lot of the articles and here might be part of the problem i am not using any custom code to impersonate the user it is my understanding that the impersonation will be applied across the board to the application by the webconfig settings above all i do is to open the connection and then close it again when i am finished with iti have obviously missed a step or two but having looked at all of the documentation that i can find and there has been a lot i still cannot find what that step is it does not help that 99 of the documentation that i can find is actually related to iis6 and windows 2003 but the principles should remain the samehas anybody suceeded in getting such a configuration to work on windows 7 andor windows server 2008,['asp.net'] +386325,pythondev installation error importerror no module named apt pkg i got stuck in a problem i am debian user and i want to install pythondev but when i run the code in the shell as a root aptitude install pythondevi get the following errortraceback most recent call last file usrbinaptlistchanges line 28 in module import apt pkgimporterror no module named apt pkgwhat seems to be the problem and how can i resolve itthanks in advance,['python'] +386338,css gradient colour stops from end in pixels i am working on a htmlcssjs project where the app is a fixed size and elements must be positioned precisely based on the designs because the window size is fixed i can easily work with pixel dimensions in css and not worry about resizing the browser i also have the luxury of not worrying about ie or opera the app must work in webkit and firefox onlyin a few places i need to have a gradient background going over specific number of pixels this would be easily accomplished with something likebackgroundimage lineargradientto top 6 0 60pxand its webkit and moz counterparts this does the trick for most elements however there are a couple where i need to have the top and bottom pixel positions for colour stops if these were percentage points then it could be done with something likebackgroundimage lineargradientto top 6 black 60px transparent 60px transparent 90 black 90 6from grey to black over 60px then transparent and then black to grey over the last 10 however i need to accomplish the same with pixels as the element in question is sized differently at different times i would like to avoid having to use js to reapply the gradient at different dynamically calculated percentage points if neededso my question is there a way to specify a colour stop x pixels not percentage from the end,['css'] +386340,programmatically get a storyboard id trying to see if a uiviewcontroller or uiview can identify it is storyboard id so was hoping for uiviewcontroller aviewcontroller nsstring storyboardid aviewcontrollerstoryboardid not an actual propertyor nsstring storyboardid aviewcontrollerstoryboard valueforkeystoryboardid also not a working callbut no joy and could not find a similar solution online does anyone know if this is even possible,['objective-c'] +386384,numeric field simple form for in my numeric fields when using simple form for scroll bars are showed on the side of the fields when using google chromehow can i stop them from showing,['ruby-on-rails'] +386392,upload and process csv file in aspnet mvc 4 architectural considerations i am working on an aspnet mvc 4 application that imports and processes a csv file i am using a standard form and controller for the upload here is an overview of what i am doing currentlycontroller logicpublic actionresult importrecordshttppostedfilebase importfile var fp pathcombinehttpcontextservermappathimportuploads pathgetfilenameuploadfilefilename uploadfilesaveasfp var filein new fileinfofp var reader fileinopentext var tfp new textfieldparserreader textfieldtype fieldtypedelimited delimiters new whiletfpendofdata parse records into domain object and save to database htmlusing htmlbeginformimportrecords import formmethodpost new id upldfrm enctype multipartformdata input iduploadfile nameuploadfile typefile input idsubbutton typesubmit valueuploadfile titleupload file the import file can contain a large number of records average 40k and can take quite some time to complete i would rather not have a user sitting at the import screen for 5 minutes for each file processed i have considered adding a console application to watch the uploads folder for new files and process when something new is added but would like to see what input i receive from the community before starting my journey down this path is there a more efficient way to handle this operation is there a way to perform this action allowing the user to continue about hisher merry way and then notify the user when processing is done,['c#'] +386400,whats a workaround for chrome for androids incorrect clientx and clienty behavior in chrome for android versions 16 and 18 at least there is a bug that reports clientx and clienty incorrectly if the page is scrolled the values of clientxy will be incorrect for at least the touchstart event though not the click event there is a bug for it herewhich contains this example that you can try yourself i have made a similar example with canvas here these examples work on other mobile browsers including the plain old android browser but chrome for android seems to have broken clientxy on at least some touch events when scrolledinterestingly clientx and clienty are not broken on the click event like they are on touchstartmy question is whats the best workaround to get clientx and clienty working consistently across browsers it appears that offsetting with windowscrollx and windowscrolly will solve the issue but a good workaround needs todetermine that the browser is afflicted or not preferably without making the user do anything and without resorting to checking the useragent so not making any assumptions of specific browser versions in other words how do we tell which browsers have bad values for clientx and clientysolve the issue reliably and only on those browsers where it needs solving presumably only chrome for android and only specific versions of it as future versions may be fine seemingly offsetting by windowscrollxy is the only thing that needs to be done here,"['javascript', 'android']" +386408,how to update values using pymongo i have a mongodb collection in this formidobjectidkeydictionary of valueswhere dictionary of values is a1b2let dictionary of values be di need to update the values of the key in the die i want to change a1 to a2how can do i this in pymongocode goes something like thisproductdata is a collection in mongodbfor p in productdatafind for kv in piteritems valueva valuevalue1 vavaluenow reflect the new value in the productdata this is what i have tried and it introduces a new keyvalue pair instead of updating the for p in productdatafind for kv in piteritems valueva valuevalue1 vavalue productdataupdate idmongoidsetda100upsertfalse,['python'] +386412,what is the difference in the following js syntax following are two ways to define bwtimer can someone tell me what the difference is i am not certain the first is even valid but if it is valid what is different about using the myfuncfunction syntaxbwtimer function return add function o alerto remove function o alerto andbwtimer function return add function o alerto remove function o alerto,['javascript'] +386484,render to string partial format error in controller i get the below error when running the below code on a controller please note the formatsjson in the error even though formatshtml is passed into render to stringwhat am i doing wrong any ideas actually the code below worked fine before not sure what changes influenced this errorrails version 328 btw the template is definitely in place loc search detailshtmlerbbonus question where can i find the api documentation showing what parameters can be passed to render to string and how it workserroractionviewmissingtemplate missing partial locsearch details with localeen formatsjson handlerserb builder coffee respond to do format formatjson detail str render to stringpartial locsearch details layout false formatshtml locals beer results beer results list str render to stringpartial locsearch list layout falseformatshtml locals beer results beer results render json results results hash result details detail str result list list str end,['ruby-on-rails'] +386495,yii how to count records in a model i have following code to fetch data from a model notifymodel notificationmodelfindbyattributesarray user id yiiappuseruid now i want to count the number of rows fetched neither notifymodelcount work nor countnotifymodelit is very simple but googling did not help,['php'] +386505,in c should my commonlogging logger be an instance member or static looking a project that uses commonlogging for net i noticed that some classes declare the logger instance as a class static member for instancepublic class hellojob ijob private static ilog log logmanagergetloggertypeofhellojob public hellojob public virtual void executeijobexecutioncontext context loginfostringformathello world 0 systemdatetimenowtostringr and in other classes the logger is declared as an instance memberpublic class simpleexample iexample public virtual void run ilog log logmanagergetloggertypeof simpleexample loginfo initializing etc is there a reason to prefer one approach or the other in which cases is each approach recommended is it related to thread safetywould it be a problem if i just declared a logger class with a static logger member and the whole project used that apart from the issue that i would in practice have a global variable,['c#'] +386508,pass two arguments with navigatornotificationconfirm i am trying to use the phonegap notification to thisplay an error message in my phonegap app and then allow the user to email the error the only problem is i cannot pass the error message to the callback function rendering the email uselessthe code i have now looks like thisfunction thisplayerrorerrormsg navigatornotificationconfirm errormsg onconfirm error submit cancel function onconfirmbuttonindex if buttonindex 1 alerterrormsg which is called by thisplayerrortest which would make the error content test i want to then pass errormsg on to onconfirm but i do not know how to do this or if it is possiblea possible solution i was considering was this function thisplayerrorerrormsg test errormsg navigatornotificationconfirm errormsg onconfirm error submit cancel function onconfirmbuttonindex if buttonindex 1 alerttest but that does not change the errormsg if a new error is thisplayed i confirmed this because in the simulator setting my app throws two errors the first one works fine when using that method passing on test but then the second error which directly follows uses the original variable instead of the most recent one,['javascript'] +386554,d3js plotting multiple data sets from separate files i am trying to make a scatter plot with two sets of data from two tsv files however each one shares the xaxis with single scale there are two yaxis each with their own scale the graph i have right now will help visuallyproblem is the 2nd data set in orange only plots partially as seen as a smudge at about 150 on the aaxis it should really be a much larger line also when i run this sometimes the 2nd data set renders and the first does now not sure why this is happeninghere are the two likely relevant blocks of code 1st data set d3tsvdatatest4tsv functionerror tsv1 tsv1foreachfunctiond daltit daltit dtmp dtmp xdomaind3extenttsv1 functiond return daltit nice ydomaind3extenttsv1 functiond return dtmp nice svgappendg attrclass x axis attrtransform translate0 height callxaxis appendtext attrclass label attrx width attry 6 styletextanchor end textaltitude m svgappendg attrclass y axis axis1 callyaxis appendtext attrclass label attrtransform rotate90 attry 6 attrdy 71em styletextanchor end svgselectalldot datatsv1 enterappendcircle attrclass dot attrr 1 attrcx functiond return xdaltit attrcy functiond return ydtmp stylefillsteelblue and 2nd data set d3tsvdatatest2tsv functionerror tsv2 tsv2foreachfunctiondd ddalti ddalti ddpressure ddpressure x2domaind3extenttsv2 functiondd return ddalti nice y2domaind3extenttsv2 functiondd return ddpressure nice svgappendg attrclass x axis attrtransform translate0 height callxaxis2 attrx width attry 6 textaltitude m svgappendg attrclass y axis axis2 callyaxis2 appendtext attrclass label attrtransform rotate90 attry 6 attrdy 71em styletextanchor end svgselectalldot datatsv2 enterappendcircle attrclass dot attrr 1 attrcx functiondd return x2ddalti attrcy functiondd return y2ddpressure stylefillorange,['javascript'] +386631,using xpath with php to parse html i am currently trying to parse some data from a forum here is the codexml simplexml load filenames xmlxpathhtmlbodydivdivformdivdivdivdivdivdivdivtabletrtdclasstopicviewsforeachnames as name echo name branyway the problem is that i am using google xpath extension to help me get the path and i am guessing that google is changing the html enough to make it not come up when i use my website to do this search is there some type of way i can make the host look at the site through google chrome so that it gets the right code what would you suggestthanks,['php'] +386643,why is not the function declared in the prototype called var p function thisshow function alerthello world pprototypeshow function alerthahavar o new poshowit alerts hello world why can i modify prototype method if yes how,['javascript'] +386675,clgeocodecompletionhandler only has one placemark entry the documentation for voidgeocodeaddrestringnsstring addrestring completionhandlerclgeocodecompletionhandlercompletionhandlerthe documentation clearly statesin the case of forwardgeocoding requests multiple placemark objects may be returned if the provided information yielded multiple possible locationsstates that it returns an array of placemarks however even if i search for objects i know for certain have multiple entries hollywood washington denmark main street ect i always only get one entrysome people just shrug and say use the google api instead but i fear for the request limitis there some setting or hack to fix this or is the clgeocoder simply broken,"['iphone', 'objective-c']" +386676,enable paging in uiscrollview after zooming i have a uiscrollview that loads three different pageswhen i zoom in on a page and zoom back out to the original size the application stops letting me scroll between the pages as if paging is thisabled what can i do to reenable paging when zoomed out to the original size scale 1this is my code voidviewdidload scview setmaximumzoomscale 20f scview setminimumzoomscale 10f scviewcontentsize cgsizemake10243 10 scviewpagingenabled yes scviewclipstobounds yes scviewdelegate self scviewshowshorizontalscrollindicator no scviewshowsverticalscrollindicator no super viewdidload self returnimagesvoidreturnimages for pagenumber 1 pagenumber 3 pagenumber imagen uiimageview alloc initwithimageuiimage imagenamednsstring stringwithformatdpngpagenumber imagenframe cgrectmakepagenumber11024 0 1024 768 scview addsubviewimagen uiview viewforzoominginscrollviewuiscrollview scrollview return scview return imagen initwithimageuiimage imagenamednsstring stringwithformatdpngpagenumber voidscrollviewwillbeginzoominguiscrollview myscrollview withviewuiview view nslogscroll will begin scviewscrollenabled yes voidscrollviewdidendzoominguiscrollview myscrollview withviewuiview view atscalefloatscale ifscale 1 scviewscrollenabled yes scviewpagingenabled yes self returnimages nslogscrolol will end scviewmaximumzoomscale 20f super viewdidload self returnimages any ideas will be highly appreciated,['ios'] +386680,flotgraph series onoff hover zoompan and tracking i am trying to combine the flot examplesinto one graph thanks to many answers from this forum i am able to combine turningseries and navigate preview however i cannot seems to add trackingit seems like if i edit the labels the flot graph does not show anything because the labels do not match is there a trickhack so i will be able to have an x axis showing the value of those plots in the legendi actually managed to add in the tracking but now i cannot add multiple axis anyone can give me an idea how,['jquery'] +386701,implement expand and collapse notification android i need to implement expand and collapse notification in status bar for android 40 and above version i have search on google for this but did not getting any code solution for implementation does anybody have i idea how to implement thisthank you in advance,['android'] +386713,build warnings for obsolete c events does anyone know of a trick or workaround to get the visual studio c compiler to issue build warnings when an obsolete event is being usedif i create a simple assembly with a public event and apply the obsolete attribute to the event when i reference that assembly and subscribe to the event in another project the compiler does not issue a warning when i build even with the highest warning level or warnings set to errorsdeclaration of event in project 1 public class apiclass obsoleteobsolete in v20 public event eventhandler obsoleteevent use of obsolete event in project 2 does not cause a build warning private void subscribetoeventapiclass apiclass apiclassobsoleteevent delegate when i open the source file visual studio recognizes the event as obsolete and adds the warning or error to the error listhowever as soon as i build the warning thisappears and does not appear in the build outputthe missing compiler warning seems to have been filed as a bug but until it is fixed is there any possible way to force a warning when someone uses the event otherwise there is no way to alert external consumers that they need to change their calling code,['c#'] +386719,set child layout width programmatically in android in my code i have a xml file having multiple child layouts aand i just want to set one of these child layouts width programmatically according to devices screen widthtill now i had tried layout params setparam and other methods but it shows null pointer exception on getting layout idmy parent layout is a relative layoutand 1st child layout is a linear layoutfor this layout i need to change widthlinearlayout xmlnsandroid androidididparentlayout androidlayout widthfill parent androidlayout heightfill parent linearlayout androidididchildlayout androidlayout width250dip androidlayout heightfill parent androidorientationvertical androidbackground153746 linearlayout androidlayout widthfill parent androidlayout heightwrap content androidorientationvertical androidbackgrounddrawablesub title androidgravitycenter vertical textview androidididmenu header label androidlayout widthwrap content androidlayout heightwrap content androidtextstylebold androidtextasd androidtextcolorf androidlayout marginleft10dip imageview androidididmenu header androidlayout widthwrap content androidlayout heightwrap content androidlayout gravitycenter horizontal linearlayout listview androidididmenu listview androidlayout widthfill parent androidlayout heightwrap content androiddividerandroidcolordarker gray androiddividerheight1dip androidscrollingcachefalse linearlayout framelayout androidididoverlay androidlayout widthfill parent androidlayout heightfill parent framelayoutlinearlayoutjava code public class slidemenu extends linearlayout keys for savingrestoring instance state public final static string key menushown menuwasshown private final static string key statusbarheight statusbarheight private final static string key superstate superstate thisplay thisplay windowmanager getwindowtokengetdefaultthisplay int width thisplaygetwidth deprecated int height thisplaygetheight deprecated float laywidth width70100 linearlayout view linearlayoutfindviewbyidridchildlayout linearlayoutlayoutparams params linearlayoutlayoutparams viewgetlayoutparams paramswidth 130 viewsetlayoutparamsparams viewsetlayoutparamsnew linearlayoutlayoutparamslayoutparamsfill parent thesizeiwant public static class slidemenuitem public int id public drawable icon public string label here is my code snippet and i comment the part what i tried so far and get any fine result,['android'] +386805,how to check exists culture in net i have this code when i try to get not existed culture i get exception is there exists method like trygetcultureinfo which return bool value i do not want to use trycatch statementcultureinfo culture cultureinfogetcultureinfoculturecodeif culture null culture cultureinfogetcultureinfodefaultculturecode,"['c#', '.net']" +386821,singleton and public static variable java i have 2 optionssingleton patternclass singleton private static singleton singleton null public static synchronized singleton getinstance ifsingleton null singleton new singleton return singleton using a static final fieldprivate static final singleton singleton new singletonpublic static singleton getsingleton return singletonwhats the difference singlethreaded or multithreadedupdates i am aware of bill pugh or enum methodi am not looking for the correct way but i have only used 1 is there really any difference bw 1 or 2,['java'] +386831,how to get the scrapy failure urls i am a newbie of scrapy and it is amazing crawler framework i have known in my project i sent more than 90 0 requests but there are some of them failed i set the log level to be info and i just can see some statistics but no details 20121205 2103040800 pd spider info dumping spider statsdownloaderexception count 1 downloaderexception type counttwistedinterneterrorconnectiondone 1 downloaderrequest bytes 46282582 downloaderrequest count 92383 downloaderrequest method countget 92383 downloaderresponse bytes 123766459 downloaderresponse count 92382 downloaderresponse status count200 92382 finish reason finished finish time datetimedatetime2012 12 5 13 3 4 8360 item scraped count 46191 request depth max 1 schedulermemory enqueued 92383 start time datetimedatetime2012 12 5 12 23 25 4270is there any way to get more detail report for example show those failed urls thanks,['python'] +386884,get rid of dynamic javascript views in visual studio since i installed visual studio 2010 from scratch about 2 months ago it behaves slightly different when debugging javascript code being run in iewhen i set a breakpoint it opens a duplicate of the view with the term dynamic in the header and marks the breakpoint in therewhen a javascript error happens during execution it does the same before it marks the line of code that threw the errorthis dynamic view is editable but edits have no effect they are not saved to the filei find this behavior pretty uncomfortable everytime i notice an error in the code during debugging i happen to fix it in the dynamic view i hit save vs does not complain next i refresh the page in ie and bang the changes are lost it loads the untouched old version againi have not been able to find out how i can turn these views off before i reinstalled visual studio it did not do that it would only create dynamic views for script found in inline script tags in html files,['javascript'] +386909,mergesort in java i am new to java and have tried to implement mergesort in java however even after running the program several times instead of the desired sorted output i am getting the same user given input as the output i would be thankful if someone could help me understand this unexpected behaviourimport javaioimport javautilarrayspublic class mergesort public static void mainstring args throws ioexception bufferedreader r new bufferedreadernew inputstreamreadersystemin int arraysize integerparseintrreadline int inputarray new intarraysize for int i 0 i arraysize i inputarrayi integerparseintrreadline mergesortinputarray for int j 0 j inputarraylength j systemoutprintlninputarrayj static void mergesortint a if alength 1 int q alength2 int leftarray arrayscopyofrangea 0 q int rightarray arrayscopyofrangeaq1alength mergesortleftarray mergesortrightarray a mergeleftarrayrightarray static int mergeint l int r int totelem llength rlength int a new inttotelem int iliri i li ri 0 while i totelem if li llength rirlength if lli rri ai lli i li else ai rri i ri else if li llength while ri rlength ai rri i ri if ri rlength while li llength ai lli li i return a,['java'] +386952,how do you integrate robolectric maven actionbarsherlock and preferably intellij into an android project i have been banging my head against a wall for some time trying to get maven robolectric actionbar sherlock and intellij to all play nicely i have given up on building with intellij for now and am focusing on maveni have an app with an action bar when i skip the tests in the maven build which tells me i am good to go on the actionbar integration front the intellij build fails on manifestparsingtestjava complaining that it does not know where junit is among other issuesrobolectric integrationi already had robolectric running successfully in the project i copied the files from jake whartons gist into srctestjavacomblahblahsupport except shadowsherlockfragmentactivityjava which lives in srctestjavacomblahblahsupportshadows and put this line in the constructor for my custom test runner lives in support folderactionbarsherlockregisterimplementationactionbarsherlockrobolectricclassmvn errorsi am running into these build errors intellij also has red squigglies for the same stufferror failed to execute goal orgapachemavenpluginsmavencompilerplugin30testcompile defaulttestcompile on project blah compilation failure compilation failureerror usersclatislawdocumentscodeandroidprojectnamesrctestjavacomblahblahsupportsherlockresourceloaderjava299 cannot find symbolerror symbol constructor resourceloaderintjavalangclassjavautillistjavaiofilejavaiofileerror location class comxtremelabsrobolectricresresourceloadererror usersclatislawdocumentscodeandroidprojectnamesrctestjavacomblahblahsupportsherlockresourceloaderjava455 method does not override or implement a method from a supertypeerror usersclatislawdocumentscodeandroidprojectnamesrctestjavacomblahblahsupportactionbarsherlocktestrunnerjava3937 resourceloaderforrootanddirectory has private access in comxtremelabsrobolectricrobolectrictestrunnererror usersclatislawdocumentscodeandroidprojectnamesrctestjavacomblahblahsupportactionbarsherlocktestrunnerjava4730 cannot find symbolerror symbol method getresourcepatherror location class comxtremelabsrobolectricrobolectricconfigerror usersclatislawdocumentscodeandroidprojectnamesrctestjavacomblahblahsupportactionbarsherlocktestrunnerjava489 resourceloaderforrootanddirectory has private access in comxtremelabsrobolectricrobolectrictestrunnererror usersclatislawdocumentscodeandroidprojectnamesrctestjavacomblahblahsupportactionbarsherlocktestrunnerjava383 method does not override or implement a method from a supertypepomxmlxml version10 encodingutf8project xmlns xmlnsxsi xsischemalocation 0 0xsd modelversion400modelversion groupidcomblahblahgroupid artifactidprojectnameartifactid version100snapshotversion packagingapkpackaging nameproject name appname dependencies dependency groupidcomgoogleandroidgroupid artifactidandroidartifactid version4012version scopeprovidedscope dependency dependency groupidcompivotallabsgroupid artifactidrobolectricartifactid version11version scopetestscope dependency dependency groupidjunitgroupid artifactidjunitartifactid version482version scopetestscope dependency dependency groupidcomgoogleandroidgroupid artifactidsupportv4artifactid versionr6version dependency dependency groupidcomactionbarsherlockgroupid artifactidlibraryartifactid version410version typeapklibtype dependency build finalnameprojectartifactidfinalname plugins plugin see groupidcomjaywaymavenpluginsandroidgeneration2groupid artifactidandroidmavenpluginartifactid version320version configuration sdk platform15platform sdk configuration extensionstrueextensions plugin plugins buildprojectis there some project config i am missing,['android'] +386957,elementwise multiplication of two vectors in c i am trying to do the following mathematical operation with two vectorsv1 a1a2a3a4a5v2 b1b2b3b4b5want to computev a2b2a3b3a4b4a5b5note that i did not want the first element in the new vectori was wondering if there is a more efficient oneliner way to multiply elementwise two vectors in c than a forloop using push back my current approach is as followsforlong i1i v1sizeivpush backv1iv2ii also tried the following for long i 1 i v1size i vi1 v1iv2i any suggestions,['c++'] +386963,vm image with readytouse rails development environment so i have been trying to start developing rails and i am having a horrible time setting up my environmentinstalled ubuntu 1210 in a vm installed rvm installed ruby 193 installed rails then rails console did not work because i did not have readline and i had to start futzing with rvm commands from here and from a stack overflow thread only to get numerous incomprehensible errorsand that is just me trying to get off the ground and start running please oh please is not there a ready virtualbox vm file with a machine preconfigured for development work,['ruby-on-rails'] +386983,convert simple html to a richtextblock i am starting with windows 8 and i am trying to convert html to a richtextblocki have read that i could use this function htmlutilitiesconverttotext in a textblock but i cannot find a way to use this function in a richtextblockfrom what i understand and tried i cannot extend the richtextblock so i cannot apply this function everytime a richtextblock is called also i cannot find any way to bind text to a richtextblock and building a parser just for simple html i only want paragraphs and italicsbolds seems an overkill also i have no idea where i should do this parsing since i the richtextblock seems unextendablei cannot use the webview because i need transparency and from what i have read the webview does not have it editmydogisbox made me see i was getting too far on my researchi can use htmlutilitiesconverttotext in the getter of a property that i can bind in the richtextblock i could not bind it because i was trying to do run textbinding texthtml without a paragraph tag however htmlutilitiesconverttotext does not preserve italics or bolds only paragraphs,['html'] +386990,deserializing json with indexed array in c i am very new to working with json and am dealing wtih a return from an api which i cannot change the formatting of the return example is actual urls have been removedbody link linkurl wgooglecom error nullmessage data retrieved successfullystatus truei am using the newtonsoftjson library with mvc 3 in vs2010my class is jsonobjectmemberserializationoptin public class linksjson jsonproperty public string link get set jsonproperty public string message get set jsonproperty public string error get set jsonproperty public bool status get set i am deserializing it with private static t download serialized json datatstring url where t new using var w new webclient var json data stringempty attempt to download json data as a string try json data wdownloadstringurl catch exception if string with json data is not empty deserialize it to class and return its instance return stringisnulloremptyjson data jsonconvertdeserializeobjecttjson data new t public string checkjsonlink var url api urlremoved for security var outobj download serialized json datalinksjsonurl return outobjlink however i am trying to get the value of linkurl which is an indexed array within linkhow would i access this information,['c#'] +387009,how do i prevent rehashing of an stdunordered map while removing elements i have an stdunordered map that i will be removing elements from via iterationauto itr mymapbeginwhile itr mymapend if removal condition itr mymaperaseitr else itr i would like to prevent the map for performing any expensive operations until i am done removing all of the elements that i need to remove do i have a valid concern am i misunderstanding how the internal storage works,['c++'] +387019,how to iterate through an inmemory zip file in ruby i am writing a unit test and one of them is returning a zip file and i want to check the content of this zip file grab some values from it and pass the values to the next testsi am using rack test so i know the content of my zip file is inside last responsebody i have looked through the documentation of rubyzip but it seems that it is always expecting a file since i am running a unit test i prefer to have everything done in the memory as not to pollute any folder with test zip files if possible,['ruby'] +387046,allowing the enter key to press the submit button as opposed to only using mouseclick i am learning swing class now and everything about it i have got this toy program i have been putting together that prompts for a name and then presents a joptionpane with the message youve entered your namethe submit button i use can only be clicked on but i would like to get it to work with the enter button too i have tried adding a keylistener as is recommended in the java book i am using eventful java bruce danyluk and murtaghthis is my codeimport javaawtborderlayoutimport javaawteventactioneventimport javaawteventactionlistenerimport javaxswingjbuttonimport javaxswingjframeimport javaxswingjlabelimport javaxswingjpanelimport javaxswingjtextfieldpublic class nameprompt extends jframe private static final long serialversionuid 1l string name public nameprompt setlayoutnew borderlayout jlabel enteryourname new jlabelenter your name here jtextfield textboxtoentername new jtextfield21 jpanel paneltop new jpanel paneltopaddenteryourname paneltopaddtextboxtoentername jbutton submit new jbuttonsubmit submitaddactionlistenernew submitbuttontextboxtoentername submitaddkeylistenernew submitbuttontextboxtoentername jpanel panelbottom new jpanel panelbottomaddsubmit add paneltop to jframe addpaneltop borderlayoutnorth addpanelbottom borderlayoutsouth jframe setup settitlename prompt program setdefaultcloseoperationexit on close pack setlocationrelativetonull public static void mainstring args nameprompt promptforname new nameprompt promptfornamesetvisibletrue and this is the actionlistener keylistener classimport javaawtcomponentimport javaawteventactioneventimport javaawteventactionlistenerimport javaawteventkeyeventimport javaawteventkeylistenerimport javaxswingjframeimport javaxswingjoptionpaneimport javaxswingjtextfieldpublic class submitbutton implements actionlistener keylistener jtextfield nameinput public submitbuttonjtextfield textfield nameinput textfield override public void actionperformedactionevent submitclicked component frame new jframe joptionpaneshowmessagedialogframe youve submitted the name nameinputgettext override public void keypressedkeyevent e if egetkeycodekeyeventvk enter systemoutprintlnhello component frame new jframe joptionpaneshowmessagedialogframe youve submitted the name nameinputgettext override public void keyreleasedkeyevent arg0 todo autogenerated method stub override public void keytypedkeyevent arg0,['java'] +387050,send php variable to javascript function i have a php file that generates a variable and i would like the variable to be put into a javascript function which is called by onclick on the main page is this possible to send from php to javascript,"['php', 'javascript']" +387058,how can i capture mouse events that occur outside of a wpf window i have a window element that has windowstylenone and allowstransparencytrue therefore it has no title bar and supports transparencyi want the user to be able to move the window to any position on the screen by leftclicking anywhere within the window and dragging the window should drag along with the mouse as long as the left mouse button is pressed downi was able to get this functionality to work with one exception when the mouse moves outside of the window such as when the left mouse button was pressed down near the edge of the window and the mouse is moved quicly the window no longer captures the mouse position and does not drag along with the mousehere is the code from the codebehind that i use to get the job donepublic point mousedownposition get set public point mouseposition get set public bool mouseisdown get set private void window mywindowname mouseleftbuttondownobject sender mousebuttoneventargs e mousedownposition egetpositionnull mouseisdown trueprivate void window mywindowname mousemoveobject sender mouseeventargs e if mouseisdown mouseposition egetpositionnull left mousepositionx mousedownpositionx top mousepositiony mousedownpositiony private void window mywindowname mouseleftbuttonupobject sender mousebuttoneventargs e mouseisdown false,['c#'] +387090,add value attribute to aspnet checkbox i am programmatically adding checkboxes to a aspnet webform i want to iterate through the requestformkeys and get the value of the checkboxes aspnet checkboxes do not have a value attributehow do i set the value attribute so that when i iterate through the requestformkeys i get a more meaningful value than the default oncode for adding the checkboxes to the pageliststring userapps getuserapplicationscontextpanel pnl new panelint index 0foreach btapplication application in userapps panel newpanel new panel checkbox newcheckbox new checkbox newpanelcssclass filtercheckbox newcheckboxid appsetting indextostring newcheckboxtext applicationname if userappscontainsapplicationname newcheckboxchecked true newpanelcontrolsaddnewcheckbox pnlcontrolsaddnewpanel indexpanel apanel findcontrolrecursivethisformviewaddrecordpanel applicationsettingspanel as panelapanelcontrolsaddpnlcode for retrieving checkbox values from requestformstringbuilder settingsvalue new stringbuilderforeach string key in requestformkeys if keycontainsappsetting settingsvalueappend settingsvalueappendrequestformkey,"['c#', 'asp.net']" +387098,what are managed modules i have recently been pushing some aspnet mvc 3 and 4 sites to iis 7 and have had major issues usually the fix is to include the following to the webconfigsystemwebserver httperrors errormodedetailed asp scripterrorsenttobrowsertrue modules runallmanagedmodulesforallrequeststrue systemwebservermy question is why what is a managed module and how do they work with aspnet mvcceditafter further testing i have thiscovered that this issue does not exist on server 2008 r2 and iis 75 but the question still stands what is a managed module and how would i know if i am using one in my code,['.net'] +387101,android providing recent search suggestions without searchable activity i have an actionbar searchview and i am successfully able to make searches with it the android documentation does not explain how to implement search suggestions i do not want to have a searchable activitythis is my search codepublic boolean oncreateoptionsmenumenu menu getmenuinflaterinflatermenuactivity add song menu final searchview searchview searchview menufinditemridsong searchgetactionview searchviewsetfocusabletrue searchviewseticonifiedfalse final addsongactivity activity this searchviewsetonquerytextlistenernew searchviewonquerytextlistener override public boolean onquerytextchangestring newtext do nothing return true override public boolean onquerytextsubmitstring query clear searchview searchviewclearfocus begin spotify search textview notice textviewfindviewbyidridsearch notice url url try url new url urlencoderencodequeryutf8 catch malformedurlexception e noticesettextmalformed search noticesetheightnoticeheight return true catch unsupportedencodingexception e noticesettextunsupported encoding maybe a problem with your device noticesetheightnoticeheight return true new searchdownloadurl activityexecute noticesettextloading tracks noticesetheightnoticeheight logiinfodb noticeheight return true this works for searching but i have no idea to implement recent search query suggestions how do i go about doing thisthank you,"['java', 'android']" +387145,transactional handling of text files on windows i have multiple windows programs running on windows 20 xp and 7 which handle text files of different formats csv tsv ini and xml it is very important not to corrupt the content of these files during file io every file should be safely accessible by multiple programs concurrently and should be resistant to system crashes this so answer suggests using an inprocess database so i am considering to use the microsoft jet database engine which is able to handle delimited text files csv tsv and supports transactions i used jet before but i do not know whether jet transactions really tolerate unexpected crashes or shutdowns in the commit phase and i do not know what to do with nondelimited text files ini xml i do not think it is a good idea to try to implement fully acidic file io by hand what is the best way to implement transactional handling of text files on windows i have to be able to do this in both delphi and cthank you for your help in advanceeditlet us see an example based on sirrufos idea forget about concurrency for a second and let us concentrate on crash tolerance i read the contents of a file into a data structure in order to modify some fields when i am in the process of writing the modified data back into the file the system can crash file corruption can be avoided if i never write the data back into the original file this can be easily achieved by creating a new file with a timestamp in the filename every time a modification is saved but this is not enough the original file will stay intact but the newly written one may be corrupt i can solve this by putting a 0 character after the timestamp which would mean that the file has not been validated i would end the writing process by a validation step i would read the new file compare its contents to the inmemory structure i am trying to save and if they are the same then change the flag to 1 each time the program has to read the file it chooses the newest version by comparing the timestamps in the filename only the latest version must be kept older versions can be deletedconcurrency could be handled by waiting on a named mutex before reading or writing the file when a program gains access to the file it must start with checking the list of filenames if it wants to read the file it will read the newest version on the other hand writing can be started only if there is no version newer than the one read last timethis is a rough oversimplified and inefficient approach but it shows what i am thinking about writing files is unsafe but maybe there are simple tricks like the one above which can help to avoid file corruptionupdateopensource solutions written in javaatomic file transactions article1 article2 source codejava atomic file transaction jaft project homexathisk tutorial source codeatomicfile description source code,['c#'] +387154,is there a way to detect which cellular network is used on android my app will feature live video streams i would like to know if there is a way to detect if the user has 2g 3g or 4g on their devices and if the which category the current connection belongs to my question is specifically about android devices,['android'] +387191,how do i convert a single char to a string i would like to enumerate a string and instead of it returning chars i would like to have the iterative variable be of type string this probably is not possible to have the iterative type be a string so what is the most efficient way to iterate through this stringdo i need to create a new string object with each iteration of the loop or can i perform a cast somehowstring mystring hello worldforeach char c in mystring what i want to do in here is get a string representation of c but i cannot cast expression of type char to type string string cstring stringc this will not compile,['c#'] +387246,table layout with equal rows height i have created a tablelayout where i want each row to have the same height regardless of it is contenthow can i do thishere is my code each row element get the same width but the heights are not equal what am i doing wrong tablelayout androidlayout widthfill parent androidlayout heightwrap content androidbackgroundcolorgrey androidpadding1dip tablerow androidlayout widthfill parent androidlayout heightfill parent androidlayout weight1 androidbackgroundcolorgrey linearlayout androidlayout width0dip androidlayout heightfill parent androidlayout weight1 androidbackgroundcolorwhite androidorientationvertical textview androidlayout widthfill parent androidlayout heightfill parent androidlayout gravitycenter vertical androidlayout marginbottom5dip androidlayout margintop2dip androidlayout weight1 androidbackgroundcolorwhite androidgravitycenter horizontal androidtextstringcar make androidtextstylebold textview androidididcarmake androidlayout widthfill parent androidlayout heightfill parent androidlayout gravitycenter vertical androidlayout marginleft1dip androidlayout weight1 androidbackgroundcolorwhite androidgravitycenter horizontal androidtextstringcar detail linearlayout linearlayout androidlayout width0dip androidlayout heightfill parent androidlayout weight1 androidbackgroundcolorwhite androidorientationvertical textview androidlayout widthfill parent androidlayout heightfill parent androidlayout gravitycenter vertical androidlayout marginbottom5dip androidlayout margintop2dip androidlayout weight1 androidbackgroundcolorwhite androidgravitycenter horizontal androidtextstringcar model androidtextstylebold textview androidididcarmodel androidlayout widthfill parent androidlayout heightfill parent androidlayout gravitycenter vertical androidlayout weight1 androidbackgroundcolorwhite androidgravitycenter horizontal androidtextstringcar detail linearlayout linearlayout androidlayout width0dip androidlayout heightfill parent androidlayout weight1 androidbackgroundcolorwhite androidorientationvertical textview androidlayout widthfill parent androidlayout heightfill parent androidlayout gravitycenter vertical androidlayout marginbottom5dip androidlayout margintop2dip androidlayout weight1 androidbackgroundcolorwhite androidgravitycenter horizontal androidtextstringcar version androidtextstylebold textview androidididcaryear androidlayout widthfill parent androidlayout heightfill parent androidlayout gravitycenter vertical androidlayout weight1 androidbackgroundcolorwhite androidgravitycenter horizontal androidtextstringcar year linearlayout tablerow tablerow androidlayout widthfill parent androidlayout heightfill parent androidlayout margintop1dip androidlayout weight1 androidbackgroundcolorgrey linearlayout androidlayout width0dip androidlayout heightfill parent androidlayout weight1 androidbackgroundcolorwhite androidorientationvertical textview androidlayout widthfill parent androidlayout heightwrap content androidlayout gravitycenter vertical androidlayout marginbottom5dip androidlayout margintop2dip androidbackgroundcolorwhite androidgravitycenter horizontal androidtextstringcar year androidtextstylebold textview androidididcaryear androidlayout widthfill parent androidlayout heightwrap content androidlayout gravitycenter vertical androidbackgroundcolorwhite androidgravitycenter horizontal androidtextstringcar year linearlayout linearlayout androidlayout width0dip androidlayout heightfill parent androidlayout weight1 androidbackgroundcolorwhite androidorientationvertical textview androidlayout widthfill parent androidlayout heightwrap content androidlayout gravitycenter vertical androidlayout marginbottom5dip androidlayout margintop2dip androidbackgroundcolorwhite androidgravitycenter horizontal androidtextstringcar mileage androidtextstylebold textview androidididcaryear androidlayout widthfill parent androidlayout heightwrap content androidlayout gravitycenter vertical androidbackgroundcolorwhite androidgravitycenter horizontal androidtextstringcar year linearlayout linearlayout androidlayout width0dip androidlayout heightfill parent androidlayout weight1 androidbackgroundcolorwhite androidorientationvertical textview androidlayout widthfill parent androidlayout heightwrap content androidlayout gravitycenter vertical androidlayout marginbottom5dip androidlayout margintop2dip androidbackgroundcolorwhite androidgravitycenter horizontal androidtextstringcar engine capacity androidtextstylebold textview androidididcaryear androidlayout widthfill parent androidlayout heightfill parent androidlayout gravitycenter vertical androidbackgroundcolorwhite androidgravitycenter horizontal androidtextstringcar year linearlayout tablerow tablerow androidlayout widthfill parent androidlayout heightfill parent androidlayout margintop1dip androidlayout weight1 androidbackgroundcolorgrey linearlayout androidlayout width0dip androidlayout heightfill parent androidlayout weight1 androidbackgroundcolorwhite androidorientationvertical textview androidlayout widthfill parent androidlayout heightwrap content androidlayout gravitycenter vertical androidlayout marginbottom5dip androidbackgroundcolorwhite androidgravitycenter horizontal androidtextstringcar engine type androidtextstylebold textview androidididcaryear androidlayout widthfill parent androidlayout heightwrap content androidlayout gravitycenter vertical androidbackgroundcolorwhite androidgravitycenter horizontal androidtextstringcar year linearlayout linearlayout androidlayout width0dip androidlayout heightfill parent androidlayout weight1 androidbackgroundcolorwhite androidorientationvertical textview androidlayout widthfill parent androidlayout heightwrap content androidlayout gravitycenter vertical androidlayout marginbottom5dip androidbackgroundcolorwhite androidgravitycenter horizontal androidtextstringcar exterior color androidtextstylebold textview androidididcaryear androidlayout widthfill parent androidlayout heightwrap content androidlayout gravitycenter vertical androidbackgroundcolorwhite androidgravitycenter horizontal androidtextstringcar year linearlayout linearlayout androidlayout width0dip androidlayout heightfill parent androidlayout weight1 androidbackgroundcolorwhite androidorientationvertical textview androidlayout widthfill parent androidlayout heightwrap content androidlayout gravitycenter vertical androidlayout marginbottom5dip androidbackgroundcolorwhite androidgravitycenter horizontal androidtextstringcar city androidtextstylebold textview androidididcaryear androidlayout widthfill parent androidlayout heightwrap content androidlayout gravitycenter vertical androidbackgroundcolorwhite androidgravitycenter horizontal androidtextstringcar year linearlayout tablerow tablerow androidlayout widthfill parent androidlayout heightfill parent androidlayout margintop1dip androidlayout weight1 androidbackgroundcolorgrey linearlayout androidlayout width0dip androidlayout heightfill parent androidlayout weight1 androidbackgroundcolorwhite androidorientationvertical textview androidlayout widthfill parent androidlayout heightwrap content androidlayout gravitycenter vertical androidlayout marginbottom5dip androidbackgroundcolorwhite androidgravitycenter horizontal androidtextstringcar transmittion androidtextstylebold textview androidididcaryear androidlayout widthfill parent androidlayout heightwrap content androidlayout gravitycenter vertical androidbackgroundcolorwhite androidgravitycenter horizontal androidtextstringcar year linearlayout linearlayout androidlayout width0dip androidlayout heightfill parent androidlayout weight1 androidbackgroundcolorwhite androidorientationvertical textview androidlayout widthfill parent androidlayout heightwrap content androidlayout gravitycenter vertical androidlayout marginbottom5dip androidbackgroundcolorwhite androidgravitycenter horizontal androidtextstringcar area androidtextstylebold textview androidididcaryear androidlayout widthfill parent androidlayout heightwrap content androidlayout gravitycenter vertical androidbackgroundcolorwhite androidgravitycenter horizontal androidtextstringcar year linearlayout linearlayout androidlayout width0dip androidlayout heightfill parent androidlayout weight1 androidbackgroundcolorwhite androidorientationvertical textview androidlayout widthfill parent androidlayout heightwrap content androidlayout gravitycenter vertical androidlayout marginbottom5dip androidbackgroundcolorwhite androidgravitycenter horizontal androidtextstringcar registered city androidtextstylebold textview androidididcaryear androidlayout widthfill parent androidlayout heightwrap content androidlayout gravitycenter vertical androidbackgroundcolorwhite androidgravitycenter horizontal androidtextstringcar year linearlayout tablerow tablelayout,['android'] +387274,cannot make android inapp billing sample app to work i have tried to get the inapp billing sample app to work according to the steps in integratehtmlbillingdownloadi will specify everything i have done added logs at the endi hope someone will be able to tell me what i am doing wronghere is everything i did i know it is long but i wanted to make sure i did not forget anythingi imported the dungeons project into my workspace and my google public key to securityjavas base64encodedpublickey variablei got that public key from a new app i added to my google developer accounti changed the name of the application package as requested so it does not have the comexample prefixi build the app and signed in via android tools export signed application packagei uploaded that apk to the new app i created in my developer account the one from which i took the public keyi added in app product to the new app with the same ids as in the dungeons project sword 001 postion 001 and activated themi added a test account to my developer account in settings gmail accounts with testing accessthat account is not the my developer account but a new one i createdi installed the signed app on a device which i factory reseted and logged in with the test account i added to my developer accountmy devicei installed the app on an android 234 device with no sim card this is my testing device google play version 3109resultswhen i try to buy one of the products i get an item not available error i get it twice actuallyi tried setting debug to true and now i get error retrieving information from server rpcs5aec0 twicelogs1206 075842255 dfinsky1955 7 marketbillingservicegetpreferredaccount comsakalbillingtestmerchant account from first account1206 075842275 dfinsky1955 7 marketbillingservicegetpreferredaccount comsakalbillingtestmerchant account from first account1206 075842325 dfinsky1955 27 marketbillingservicegetpreferredaccount comsakalbillingtestmerchant account from first account1206 075842335 dfinsky1955 27 marketbillingservicegetpreferredaccount comsakalbillingtestmerchant account from first account1206 075842991 evolley1955 15 basicnetworkperformrequest unexpected response code 500 for 0011206 075844785 dfinsky1955 1 marketbillingservicesendresponsecode sending response result error for request 8273178932293834331 to comsakalbillingtestmerchant1206 075844785 ibillingservice3173 handlecommand action comandroidvendingbillingresponse code1206 0758451 evolley1955 14 basicnetworkperformrequest unexpected response code 500 for 0011206 075846225 dfinsky1955 1 marketbillingservicesendresponsecode sending response result error for request 2493329704825383 to comsakalbillingtestmerchant1206 075846245 ibillingservice3173 handlecommand action comandroidvendingbillingresponse code,['android'] +387287,why does not class have a nice generic type in this case in this code why can type not be declared as class extends bpublic class foob public void dosomethingb argument class extends object type argumentgetclass,['java'] +387291,map view following user mylocationoverlay type functionality for android maps api v2 i switched to v2 of maps for android and i am trying to port over the following functionalitywith mylocationoverlay i can show the devices current location blue dot when the users location changes and the dot reaches the edge of the visible area the map animates out so the dot becomes the center of the view in real timein v2 i am using supportmapfragment with getmapsetmylocationenabledtrue the current location appears as a blue dotarrow but when the device changes location the map view does not shift and the dot eventually leaves the viewany ideas,['android'] +387308,cgcontextclear warning i am having an issue with ios while using cgimagedestinationfinalize i will call cgimagedestinationfinalize on a cgimagedestinationref and i will get the following warningerror the function cgcontextclear is obsolete and will be removed in an upcoming update unfortunately this application or a library it uses is using this obsolete function and is thereby contributing to an overall degradation of system performancelooking at instruments my memory usage shoots up sometimes it gets so high that it crashes when i call cgimagedestinationfinalize i am not sure if this issue is to blame or not but i have isolated it to being an issue with cgimagedestinationfinalizeany advice on what to use to avoid calling a cgcontextclear or how to reduce memory usage with cgimagedestinationfinalize,['ios'] +387362,java system properties httpproxyhost two questions i am developing a java application that makes http requests and half of my development time is behind a proxy so i have the following block in my codeif behind proxy javautilproperties systemproperties systemgetproperties systempropertiessetpropertyhttpproxyhost proxy host systempropertiessetpropertyhttpproxyport proxy portthe idea is that i change the value of behind proxy based on where i am i was working today not behind a proxy and forgot to set behind proxy to false however the connection was still made successfully and my application received the data it requested how is this possible is there something built into this that if the proxy server cannot be reached it simply tries again but bypasses the proxy on this retryand a second question i have been trying to find a complete list of system properties i have found many posts like this one but not one of them lists httpproxyhost or httpproxyport which makes me think they are clearly not very complete am i searching wrong somehow do these httpx properties belong in these other lists is there a more complete list somewhere,['java'] +387386,ios universal development a use of tilde sign in xib file and image name for differentiation while developing universal apps we have to write a conditional code for each device a the ipad as well as the iphone in this scenario the proper use of tilde can be extremely beneficialfor example if you want to push new view controller then youad have to write lot of lines almost 10 of codeif uidevice currentdevice userinterfaceidiom uiuserinterfaceidiomphone masterviewcontroller masterviewcontroller masterviewcontroller alloc initwithnibnameamasterviewcontroller iphonea bundlenil selfnavigationcontroller pushviewcontrollermasterviewcontroller animatedyes masterviewcontroller releaseelse masterviewcontroller masterviewcontroller masterviewcontroller alloc initwithnibnameamasterviewcontroller ipada bundlenil selfnavigationcontroller pushviewcontrollermasterviewcontroller animatedyes masterviewcontroller releasehow can we differentiate images for iphone and ipad,"['iphone', 'objective-c', 'ios']" +387427,is there a way to uninstall dev dependencies with composer i want to uninstall and not remove from my composerjson dev dependencies on a projectis there a simple way to do this,['php'] +387429,when should we use observer and observable an interviewer asked mewhat is observer and observable and when should we use themi was not aware of these terms so when i came back to home i started to google about observer and observable and found some points from different resources1 observable is a class and observer is an interface2 observable class maintain a list of observers3 when an observable object is updated it invokes the update method of each of its observers to notify that it is changedi found this exampleimport javautilobservableimport javautilobserverclass messageboard extends observable private string message public string getmessage return message public void changemessagestring message thismessage message setchanged notifyobserversmessage public static void mainstring args messageboard board new messageboard student bob new student student joe new student boardaddobserverbob boardaddobserverjoe boardchangemessagemore homework class student implements observer public void updateobservable o object arg systemoutprintlnmessage board changed arg but i do not understand why we need observer and observable what are the setchanged and notifyobserversmessage methods for,['java'] +387441,does c standard description of indirection operator guarantee memory writes are not optimized away this is basically a continuation of this question so far it looks like that if i have a function like thisvoid securezeromemory void ptr size t cnt volatile char vptr volatile char ptr while cnt vptr 0 vptr cnt and call it like this char buffersize securezeromemory buffer size then since buffer is not declared volatile it does not matter that a pointer to volatile is used the data itself is not volatile so write to the variable do not constitute observable behavior 196 and the compiler is allowed to optimize them awayhowever recently i have come across a statement that it is only the pointer declaration that matters specifically c03 5311 describes indirection like thisthe unary operator performs indirection if the type of the expression is apointer to ta the type of the result is ataso the claim is that because of using indirection on a volatile char we get volatile char and writes to those do constitute observable behavior and it no longer matters how the actual data is declareddoes the c03 5311 description of indirection really guarantee that overwriting memory using a volatile t pointer as in the sample above constitute observable behavior and is thisallowed to be optimized away,['c++'] +387447,nsnotificationcenter and safe multithreading given that objects may be deallocated even while a method invocation is in progress link is it safe for an object to register for and receive notifications that will be delivered on a thread that is different from the one on which it expects to be deallocatedfor reference the documentation states thatin a multithreaded application notifications are always delivered in the thread in which the notification was posted which may not be the same thread in which an observer registered itselfalso important is the fact that nsnotificationcenter does not keep a strong reference to objects that are registered to receive notificationsheres an example that might make the situation more concrete idinit self super init if self nsnotificationcenter defaultcenter addobserverself selectorselectorhandlenotification namesomenotification objectnil voiddealloc nsnotificationcenter defaultcenter removeobserverself voidhandlenotificationnsnotification notification do somethingan object with this implementation receives somenotification on thread x before handlenotification returns the last strong reference to the object in the code i can see is brokenam i correct in thinking thata if nsnotificationcenter takes a strong reference to the object before calling handlenotification on it then the object will not be deallocated until after handlenotification returns andb if nsnotificationcenter does not take a strong reference to the object before calling handlenotification on it then the object may be deallocated before handlenotification returnswhich way a or b does it work i have not found this topic covered in the documentation yet but it seems somewhat important to using nsnotificationcenter safely in a multithreaded environmentupdate the answer in the aforementioned link was updated indicating that arc retains and releases around an invocation on a weak reference this means that an object should not be deallocated while a method invocation is in progress,['objective-c'] +387506,android calling ui thread from worker thread hi i want to make toast available to me nomatterwhat and available from any thread whenever i like within my application so to do this i extended the activity classimport androidappactivityimport androidosbundleimport androidoshandlerimport androidwidgettoastpublic class myactivity extends activity private handler mhandler override public void oncreatebundle savedinstancestate mhandler new handler superoncreatesavedinstancestate private class toastrunnable implements runnable string mtext public toastrunnablestring text mtext text public void run toastmaketextgetapplicationcontext mtext toastlength shortshow public void dotoaststring msg mhandlerpostnew toastrunnablemsg so that all activity classes in my app are now simplypublic class appmain extends myactivity blahwhat i expected to be able to do in a worker thread was thistry myactivity me myactivity loopergetmainloopergetthread medotoasthello worldcatch exception ex logeoh dear exgetmessageand so long as the activity was a myactivity it should work but the problem is the loopergetmainloopergetthread is not returning the myactivity to me and it is making me cry what am i doing wrong edit some background to explain why i am stuck with this type of implmentationi need to be able to confirm to the user that a http post event has been a success now if the user clicks ok on the ui form it may or may not have internet at that time if it has internet all well and good it posts the form via http post all well and good but if there is no internet most 9 of android apps lame pathetic mewling at this and basically offer the user no plan b assuming that at all times the internet is there when it is not my app will not go lame as i call it it does have a plan b instead it queues the post event and retries every x minutes now this is a silent thread in the background i have plenty of user interaction all over the app i do not know where the user will be but eventually when the http post that queueretriesqueueretries returns success i want to toast that as a message to the user eg your form was sent,['android'] +387514,how do you implement nspagecontroller to navigate through a webviews history i have a webviewbased app but i want the user to be able to navigate it with swiping on the trackpad and magic mouse therefore i am going to implement nspagecontrolleri have looked at the documentation and the pictureswiper app however those are not really meant for a webview so i would like to know how i can use an nspagecontroller on a webview i have a webview defined as webview and two actions goback and goforward that load the previous and next page respectively however i am unaware of how i get nspagecontroller to work with a simple webview there has a to be a way to do it but i see no way if someone could please explain what i am suppose to do that would be great or if you are feeling especially generous you can download my free browser source example that source shows how my own app is pretty much set up if you would like to implement the nspagecontroller on that app and send me the source i would really appreciate it it is not much but if you do that i will add the swiping example to infinite open syntax and put your name on it you can choose the license this is cocoa not cocoa toucheditokay now i just need to make sure the app still works on snow leopard supposedly i can test this by thisconnecting the outlets it works fine minus the back and forward button to do this i believe i check for the class nspagecontroller if it does not exist then i just skip using the pagecontroller ibactiongobackidsender if nsclassfromstringnspagecontroller nil selfpagecontroller navigatebacksender not 108 webview goback,['objective-c'] +387560,gradient problems in java in my program i wanted to have a translucent white to transparent gradient on my jframe to overlay a yellow background this works fine and it needs to be a white to transparent because of how my settings for the program work for the user however when i take the program into college jre7 to my jre6 the gradient goes white to blackish then transparent it is not so bad until you start to increase the opacity of the white colour is there anyway i can fix thishere is the relevant code from the top of my jframe codepublic class dictionarygui extends jframe protected jpanel pgradientpane interface gradient specification private color pinterfacecolour new color255 245 62 protected int idegreewhite 180 protected int idegreeblack 0 dictionaryguiint iwidth int iheight general definitions superstringformatfrench verb conjugator version s mainlauncherversion setsizeiwidth iheight new menuthis thisiwidth iwidth thisiheight iheight getcontentpanesetbackgroundpinterfacecolour pgradientpane new jpanelnew gridbaglayout private static final long serialversionuid 1l protected void paintcomponentgraphics pgraphics graphics2d pgraphicsgradientrender graphics2d pgraphics pgraphicsgradientrendersetrenderinghintrenderinghintskey antialiasing renderinghintsvalue antialias on gradientpaint pgradient new gradientpaint0 0 new color255 255 255 idegreewhite 0 getheight new color0 0 0 idegreeblack pgraphicsgradientrendersetpaintpgradient pgraphicsgradientrenderfillrect0 0 getwidth getheight superpaintcomponentpgraphics pgradientpanesetopaquefalse pgradientpanesetpreferredsizenew dimensioniwidth 16 iheight 62 components added to pgradientpane here addpgradientpane and the mainclass aswellpublic class mainlauncher static int iheight 400 static int iwidth 730 static string version 0a3b6 public static void mainstring args try for lookandfeelinfo info uimanagergetinstalledlookandfeels if nimbusequalsinfogetname uimanagersetlookandfeelinfogetclassname break catch exception e eprintstacktrace dictionarygui window new dictionaryguiiwidth iheight windowsetdefaultcloseoperationjframeexit on close windowsetlocationbyplatformtrue windowsetvisibletrueis it just some difference between jre6 and jre7 should i make the bottom colour to white aswell was black incase people want to darken the colour at the bottomi can post some screenshots tommorrow if anybody needs themthanksjamieediti changed the second transparent colour in the gradient to white and it fixes the problem however i am still troubled to why the transparent black colour shows through in the middle it must be something to do with jre7 because thats where it occurs maybe they changed something with how transparency in gradients work does anybody know how to eliminate this problem while keeping the colour black,['java'] +387595,jersey client how to add a list as query parameter i am creating a jersey client for a get service that has a list as query parameter according to the documentation it is possible to have a list as a query parameter this information is also at queryparam javadoc check it out in general the java type of the method parameter maybe a primitive typehave a constructor that accepts a single string argumenthave a static method named valueof or fromstring that accepts a single string argument see for example integervalueofstring and javautiluuidfromstringstring orbe list set or sortedset where t satisfies 2 or 3 above the resulting collection is readonlysometimes parameters may contain more than one value for the same name if this is the case then types in 4 may be used to obtain all valueshowever i cannot figure out how to add a list query parameter using jersey client i understand alternative solutions are use post instead of get transform the list into a json string and pass it to the service the first one is not good because the proper http verb for the service is get it is a data retrieval operation the second will be my option if you cannot help me out i am also developing the service so i may change it as needed thanksupdateclient code using jsonclient client clientcreatewebresource webresource clientresourceuritostringsearchwrapper sw new searchwrappertermo pagina ordenacao hits search view navegadoresmultivaluedmapstring string params new multivaluedmapimplparamsadduser usertouppercase paramsaddsearchwrapperasjson new gsontojsonswclientresponse clientresponse webresource pathlistar queryparamsparams headerhttpheadersauthorization authenticationhelpergetbasicauthheader getclientresponseclasearchresultwrapper busca clientresponsegetentitynew generictypesearchresultwrapper,['java'] +387626,locations in core data sorted by thistance via nsfetchedresultscontroller i have a set of entity objects in my ios core data database that describe something at a location let us call the entity location i have implemented this by having two attributes on location that refer to the location latitude and longitude both doubles there are other elements like namei am using a nsfetchedresultscontroller to bind the entities to a uitableviewcontroller what i would like to do is have the results sorted by thistance to a given cllocationcoordinate2d in an really ideal scenario i am able to refresh that list to recalculate the sort based on a new location therefore this sort would depend on two keys and a third static variable one that does not vary across the items in the collectioni think i could figure out how to do this if i was sorting an arbitrary list with nssortdescriptors however i do not control how the sort descriptors are used in an nsfetchedresultscontrolleris there a way that i could configure my entities my nsfetchedresultscontroller my nssortdescriptors etc to accomplish this i suspect that the answer lies not in creating a fancy nssortdescriptor but instead in creating a transient attribute in the entity that represents the thistancetome and recalculating that attribute periodically however i am new enough to core data that i am not sure how to best do this iterate over all entities and recalculate a field i am also not sure if nssortdescriptors will work on transient attributes,['ios'] +387663,trying to download file from ftp results in an 500 illegal port command error if i execute this locally everything works finerequire netftpftpnetftpnewmyftpservercom username passwordftpgetbinaryfilemyfileziplocalfilezipftpcloseif i attempt to execute it on the linux server i am using the result isusrlocallibruby191netftprb273in getresp 500 illegalport command netftppermerror fromusrlocallibruby191netftprb281in voidresp fromusrlocallibruby191netftprb304in block in voidcmd fromusrlocallibruby191monitorrb201in mon synchronize fromusrlocallibruby191netftprb302in voidcmd fromusrlocallibruby191netftprb317in sendport fromusrlocallibruby191netftprb325in makeport fromusrlocallibruby191netftprb358in transfercmd fromusrlocallibruby191netftprb420in block 2 levels inretrbinary from usrlocallibruby191netftprb166inwith binary from usrlocallibruby191netftprb419in blockin retrbinary from usrlocallibruby191monitorrb201inmon synchronize from usrlocallibruby191netftprb418inretrbinary from usrlocallibruby191netftprb539ingetbinaryfilewhat could be the problem,['ruby'] +387773,send html email with gmail 421 it seems that gmail 421 may have broken htmlformatted emails the following code worked perfectly prior to 421 the email that was sent from gmail had the desired embedded links bolded and underlined words unfortunately after updating to 421 the email that gets sent appears as if all the html formatting has been stripped out i am hoping there may be a workaround for this that maybe someone has foundfinal intent intent new intentintentaction sendintentsettypemessagerfc822string toarr new string intentputextraintentextra email toarrintentputextraintentextra subject this is a subjectintentputextraintentextra text htmlfromhtmlhello here is some bbold textb some uunderline textu and a hrefa linkathe interesting thing or maybe not is that the compose preview of this email message shows all of the bolded underlined and linked text as one would expect it to appear but when it gets sent the recipient gets the email with all of that stuff stripped outand yes i am aware of this other question about this that was closed i think that maybe it was closed prematurely and am hoping that the additional detail here may warrant another lookmore information upon further research this problem is way bigger than just sending html email via intents if one creates a draft email using the gmail web app that has some formatting bold underline hyperlinks etc then open that draft email on your gmail android app v421 it will appear that all of your formatting has been kept however if you then send that draft email using your gmail android app all of your formatting will be stripped out before the email is sent,['android'] +387785,jackson required property i am using jacksons readvalue method on an object mapper to read from a json file and convert it into my java object egmapperobjectreadvalue node mytargetclassclass are there any annotations that i can set on mytargetclass to enforce required attributes for example if i have a json object with properties abcdef and ghi and my json is the following abc somevalue def someothervalue i want it to fail somehow and only succeed on the readvalue if it contained abc def and ghi,['java'] +387796,what does android getintrinsicheight and getintrinsicwidth mean hi i am confused by the two methods from android drawable classgetintrinsicheightgetintrinsicwidthapi definition says what does the word intrinsic heightwidth meani mean is it a width of the actual image,['android'] +387806,numbers localization in web applications how can i set the variant of arabic numeral without changing character codes eastern arabic u u u2 u3 u u u u u u1persian variant u u u2 u3 u u u u u u1western arabic 0 1 2 3 4 5 6 7 8 9 and perhaps any other in use numeral system if anyhere is a sample codedoctype htmlhtmlhead meta charsetutf8headbodydiv langfa0123456789divdiv langar0123456789divdiv langen0123456789divbodyhtmlhow can i do this using only clientside technologies htmlcssjsthe solution should have no negative impact on pages seo scorenote that in windows text boxes eg run numbers are thisplayed correctly according to language of surrounding textsee also numbers localization in desktop applications,"['javascript', 'html', 'css']" +387823,start fragmentactivity from activity how can i start a fragmentactivity from an activitymy mainactivity is a splash screen and i want to star a fragmentactivity nexti need something instead of for example startactivitynew intentcomexamplemanagermyfragmentactivitytia,['android'] +387848,android bitmap to byte array and back skimagedecoderfactory returned null the goal is to convert a bitmap to a byte pass it between activities in a bundle of data then reconvert it back to a bitmap at a later stage for thisplay in an imageviewthe issue is that whenever i try this i just get a null bitmap and the nondescriptive unhelpful log output1207 170133282 dskia2971 skimagedecoderfactory returned nulli have looked at the following solutionssolution supplies the bitmap to byte code usedhighlighted that copypixelstobuffer is essential over compress especially seeing as it is not necessary in this casei have run up the following test case which definitely narrows down the problem to the converting and restoring code based on my debugging there is correct decoding the byte array is the correct size and full bitmap configs are forced to be the same decodebytearray is just failingpackage comexampledebugimport javaniobytebufferimport androidosbundleimport androidappactivityimport androidgraphicsbitmapimport androidgraphicsbitmapconfigimport androidgraphicsbitmapfactoryimport androidutillogimport androidviewmenuimport androidwidgetimageviewimport androidwidgetrelativelayoutpublic class mainactivity extends activity relativelayout rl null relativelayoutlayoutparams rlp null imageview ivbef null imageview ivaft null bitmap bmbef null bitmap bmaft null override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate test bitmapfactoryoptions bmo new bitmapfactoryoptions bmoinpreferredconfig configargb 8 bmbef bitmapfactorydecodefilemntsdcarddebug001png bmo byte b bitmaptobytearraybmbef bmaft bitmapfactorydecodebytearrayb 0 blength bmo linearlayout ll new linearlayoutthis ivbef new imageviewthis ivbefsetimagebitmapbmbef ivaft new imageviewthis ivaftsetimagebitmapbmaft lladdviewivbef lladdviewivaft setcontentviewll override public boolean oncreateoptionsmenumenu menu inflate the menu this adds items to the action bar if it is present getmenuinflaterinflatermenuactivity main menu return true public static byte bitmaptobytearraybitmap bm create the buffer with the correct size int ibytes bmgetwidth bmgetheight 4 bytebuffer buffer bytebufferallocateibytes logedbg bufferremaining returns a correct number based on dimensions copy to buffer and then into byte array bmcopypixelstobufferbuffer logedbg bufferremaining returns 0 return bufferarray the before imageview correctly thisplays the image the after imageview shows nothing as you would expect with a null bitmap,"['java', 'android']" +387853,how should i iterate a priority queue properly i have a java assignment involving iterating a priority queue the queue consists of objects with a string and an int in them and i need to have a way to check a seperate objects string against all the objects in the queue would it be best way to do this be an iterator object that seems too messy i could dequeue and enqueue but that seems inefficient maybe a foreach loop,['java'] +387858,java pattern class does not have a public constructor why i have been reviewing java regex library surprised by the fact the pattern class does not have a public constructor which i have taken for granted for yearsone reason i suspect the static compile method is being used in favor of constructor could be that constructor would always return a new object while a static method might return a previously created and cached object provided that the pattern string is the samehowever it is not the case as demonstrated by the followingpublic class patterncompiler public static void mainstring args pattern first patterncompile pattern second patterncompile if first second systemoutprintlnthe same object has been reused else systemoutprintlnwhy not just use constructor any other strong rationales behind using static method over constructoredit i found a related question here none of the answers there convinced me either reading through all answers i get a feeling that a static method has quite a few advantages over a public constructor regarding creating an object but not the other way around is that true if so i am gonna create such static methods for each one of my classes and safely assume that it is both more readable and flexible,['java'] +387891,range instead of get range rangeaspx it says to use the range property instead of get rangeobject cell1 object cell2they are both doing the same thing gets a microsoftofficeinteropexcelrange object that represents a cell or a range of cells so whats the difference except that this is a method and another is a property why are they pointing on use of range whats the reason for it,['c#'] +387980,nsurlconnectiondownloaddelegate destinationurl i am currently developing an ipad ios 6 application which uses async downloadsto receive progress information i used the delegate nsurlconnectiondownloaddelegatethe download and the progress received by a connectiondidwritedatatotalbyteswrittenexpectedtotalbytesworks just finehowever once the download is finished i do not know how to extract the data out of the nsurl destinationurl provided by the delegatemethoda connectiondidfinishdownloadingdestinationurlthe destinationurl received in string looks like privatevarmobileapplications7cb3b1949e794f0bacfd7b87aa8c7baftmpfilenamemp4then i try to extract the data from the given nsurlnsdata data nsdata alloc initwithcontentsofurldestinationurlthe data however is emptynslogdata size datalength prints out 0has someone the same issue by using nsurlconnectiondownloaddelegate any ideas how to solveedit i tried to copy the file first and then use nsdata initwithcontentsoffile as suggested but the data size is still 0 void connectiondidfinishdownloadingnsurlconnection connection destinationurlnsurl destinationurlnsfilemanager defaultmanager copyitematpathdestinationurlpath topathdest path errornilnsdata data nsdata alloc initwithcontentsoffiledest pathnslogdata size i datalength still returns 0edit2i can extract the nsdata when using sendasynchronousrequest method of nsurlconnection however like this i am not able to determine the progress of the downloadnsurlconnection sendasynchronousrequesttherequest queuensoperationqueue alloc init completionhandlernsurlresponse response nsdata data nserror errorif datanslogsize of the data i bytess datalength works finedata writetofiledest path atomicallyyesfrom this point i can use the file at dest pathnslogsucceededelse if errornslogerror,['ios'] +387981,calling superclass method from subclass javascript possible duplicateset attribute with javascript super method i am trying to create a simple game in html5 for fun i have an entity class that is supposed to be the superclass of the player classfunction entityx y thisx x thisy y thistick function do generic stuff function playerx y thisparentconstructorcallthis x y thistick function do playerspecific stuff thisparenttickcallthis playerprototype new entityplayerprototypeconstructor playerplayerprototypeparent entityprototypethe problem is at this linethisparenttickcallthisi get an error thisplayed in the javascript console of chrome uncaught typeerror cannot call method call of undefinedi do not get it and i have spent a long time trying to find posts of a similar issue my call to the superclass constructor works fine but the call to the superclass tick method does not worki am very new to making games so i have no idea if this a good setup calling superclass tick from subclass tick if there is a better more typical way that people use please tellthanks,['javascript'] +388005,android how to put an image file from sd card to hashmap with simpleadapter i am reading files from the selected folder on my phone like you can see in the following code and how could i get this work with an imagefileat the end i like to have an imagelist with a preview of every image like thatimg imgview filename string forint i0 i fileslength i file file filesi map new hashmapstring string iffileishidden filecanread pathaddfilegetpath iffileisdirectory mapputimg list rdrawablefolder mapputstring cell filegetname your array listaddmap else imagefilefilter filefilter new imagefilefilterfile iffilefilteracceptfile its an imagefile i like to replace the rdrawableimage with the file that i have read mapputimg list rdrawableimage else its not an image file mapputstring cell filegetname your array listaddmap simpleadapter mschedule new simpleadapterthis your array list rlayoutconnected upload row new string img list string cell new int ridimg list ridstring celistsetadaptermschedulein the following picture i like to replace the white image picture with the original picture called 41786486733jpg as previewso that the user can see what picture this is edit florian pilziffilefilteracceptfile logvpath1 filegetpath imageview myimageview imageview findviewbyidridimg list bitmap bmp bitmapfactorydecodefilefilegetabsolutepath myimageviewsetimagebitmapbmp,['android'] +388022,how can i save messagedigest internal state into database is it possible and if than how to save the internal state of messagedigest object i want to save it in a database so have to use only primitive data like string int bytewhat i am trying to achieve is to be able to receive a fragmented file during a long period of time save all the fragments in database and after receiving last fragment verify the sha512 digest of the file without getting back all the data previously saved in databaseso basically i want something like thismessagedigest md messagedigestgetinstancesha512 restore previous internal state of mdmdupdatedatasegment save internal md state,['java'] +388041,selection is not possible when uicollectionview is nested in uitableview i have a uitableview where each cell contains a uicollectionviewi can scroll the uitableview vertically and scroll the nested uicollectionview horizontally however i cannot select a uicollectionviewcell in the uicollectionviewselection is thisabled in the uitableview and enabled the default state in the uiccollectionviewthe uicollectionviews collectionviewdidselectitematindexpath is simply never called,"['ios', 'objective-c']" +388096,what is the naming convention for python class references what is the naming convention for a variable referencing a class in pythonclass myclassobject pass which one is correctreference to class myclass orreferencetoclass myclasshere is another example that resembles my situation carspyclass carobject passclass sedancar passclass coupecar passclass statonwagoncar passclass vancar passdef get car claslug config return configgetslug configpyconfig fordmustang coupe buickriviera coupe chevroletcaprice sedan chevywan van fordeconoline van mainpyfrom configpy import configfrom cars import get car classmycarclass get car classbuickrivieramy car mycarclassi would prefer referencetoclass that everybody new to the code knows it is a class and not an instance but as poplitea wrote literature reference would be great,['python'] +388103,ios event handling in complex applications i have been developing for android for quite a while and now started learning ios and heres the thingon android when you have a massive amount of events going through the application it becomes very tedious creating and implementing all these interfaces protocols subscribing and unsubscribing and stuff and there is a couple of very good eventbusses for example an otto by square so i was wondering is there any standart solution for ios to handle various events across various application elements or it is done by implementing and subscribing protocols too or maybe there is some cool eventbus library for it like on android,['ios'] +388128,using jquery to find a class by id name div idcalcwrapper img clasugarcube srcimagessugarcubepng width13 height17 div iddrinks a iddrink1 hrefimg srcimagesdrinkicon1png width84 height81adiv classdrink1div divdivin the example above there is only the single drink button but my code contains eight buttons each with a corresponding samenamed classed div what i am trying to do is dynamically grab the id of the anchor tag iddrink1 to append a clone sugarcube image img clasugarcube into the equivalent class name div classdrink1 i hope that does not sound confusing perhaps the unsuccessful attempts below will give you some idea of what i am trying to achieveattempt 1sugarcubecloneattrclass sugarcube iappendtothisparentdrink1attrclassattempt 2 trying to find a working solution via the consolevar classname thisattridconsolelogclassnameconsolelogthisparentchildrendivhasclassclassnamei have searched google and stackoverflow and have not found any code samples thank you for your helpheres the complete html code contextdoctype htmlhtmlhead script srcscript script srcjsjqueryanimatecssrotatescalejsscript script function sugarcubehide var max 8 function animatesugarcubes for var i1 imax i sugarcube icssposition absolute sugarcube icsstop mathceilmathrandom 50 20 20 sugarcube icssleft mathceilmathrandom 85 40 40 sugarcube ihide drinks aclickfunction for var i1 imax i attempt 1 sugarcubecloneattrclass sugarcube iappendtothisparentchildrenthisattrid attempt 2 test code var classname thisattrid consolelogthisparentchildrendivhasclassclassname return false animatesugarcubes scripthead body div idcalcwrapper img clasugarcube srcimagessugarcubepng width13 height17 div iddrinks a iddrink1 hrefimg srcimagesdrinkicon1png width84 height81adiv classdrink1div a iddrink2 hrefimg srcimagesdrinkicon2png width84 height81adiv classdrink2div a iddrink3 hrefimg srcimagesdrinkicon3png width84 height81adiv classdrink3div a iddrink4 hrefimg srcimagesdrinkicon4png width80 height81adiv classdrink4div a iddrink5 hrefimg srcimagesdrinkicon5png width84 height81adiv classdrink5div a iddrink6 hrefimg srcimagesdrinkicon6png width84 height81adiv classdrink6div a iddrink7 hrefimg srcimagesdrinkicon7png width84 height81adiv classdrink7div a iddrink8 hrefimg srcimagesdrinkicon8png width84 height81adiv classdrink8div divdivbody html please note that the anchor tag uses an id iddrink1 while the div uses a class classdrink1,['jquery'] +388133,where can i find a reference for what every bit of the corflags value means i am messing around with some rather low level things and trying to determine why i get different outputs with the corflagsexe utility for reference the outputs are as so corflags test2exemicrosoft r net framework corflags conversion tool version 403031917929copyright c microsoft corporation all rights reservedversion v4030319clr header 25pe pe32corflags 0x1ilonly 132bitreq 032bitpref 0signed 0 corflags testexemicrosoft r net framework corflags conversion tool version 403031917929copyright c microsoft corporation all rights reservedversion v4030319clr header 25pe pe32corflags 0x203ilonly 132bitreq 032bitpref 1signed 0i am trying to figure out what the other bits in the corflags value mean that are not exposed in the corflags utility where is a reference for this,['.net'] +388143,ruby how to make a public static method in java i might dopublic static void dosomethingand then i can access the method statically without making an instanceclassnamedosomething how can i do that in ruby this is my class and from my understanding self makes the method staticclass ask def selfmake permalinkphrase phrasestripdowncasegsub endendbut when i try to callaskmake permalinkmake a slug out of this linei getundefined method make permalink for askclasswhy is that if i have not declared the method to be private,"['ruby-on-rails', 'ruby']" +388153,is there a phpcs standard targeting php docblocks is there a phpcs coding standard that would check that proper annotations param return throws etc are present in a docblock including the proper spacing between them,['php'] +388224,how to set a single value of transform while leaving the other values if you have an element with many values for transform how do you change just one of those values without changing the other valuesyou could rewrite them every time but in some situations that means you will have to parse apart the css for the transform into its different parts for examplewebkittransformrotatey45deg rotate45degyou would have to get the property and value for rotate and rotatey is not there a way to get and set just rotate without changing the value for rotateythe problem is illustrated here,"['javascript', 'css']" +388252,java inheritance puzzle i have created the following puzzle for inheritance in javaanimaljavapublic class animal private string sound public void roar systemoutprintlnsound public void setsoundstring sound thissound sound tigerjavapublic class tiger extends animal public string sound public tiger sound roar junglejavapublic class jungle public static void mainstring args tiger diego new tiger diegoroar diegosound hust hust diegoroar diegosetsoundbla diegoroar systemoutprintlndiegosound outputnullnullblahust husti guess this weird behaviour is taking place because sound in animal is private while sound in tiger is public but can you explain and tell me the relevant parts of the jls why this happens,['java'] +388271,center proportional font text in an html5 canvas i would like to be able to center single lines of text within rectangular areas i can calculate the one thing i have expected to do in 2d geometry on a canvas is to center something whose width is unknown to youi have heard as a workaround that you can create the text in an html container and then call jquerys width function but i did not correctly handle the momentary addition to the documents body and got a width of 0if i have a single line of text significantly shorter than would fill most of the width in a screen how can i tell how wide it will be on a canvas at a font size i knowtia,"['javascript', 'jquery']" +388278,could f type providers be incorporated in c the cool new f 30 feature type providers can be used to bridge the mismatch between f data types or classes and data source structures like xml or wsdl however this mismatch is also a challenge in other net languages like c i would like to use the f 30 providers in c code how can i do this if at all further if we cannot what would a c implementation need to be able to use them,"['c#', '.net']" +388326,rmagick gem fails to install on debian stable editfixedthe problem was that i had it installed already but did not know and tried to install from source this created two versions and the gem did not know which to use i fixed it by going to the downloaded source and runningsudo make uninstallthen i ran gem install rmagick again and it workedoriginal problemi am trying to install the rmagick gem like in this railscast heres a snippet of what i put in my gemfile gem rmagick gem carrierwaveand when i run bundle install i get the following outputinstalling rmagick 2131 with native extensions geminstallerextensionbuilderror error failed to build gem native extension hometechusbrbenvversions193p125binruby extconfrb checking for ruby version 185 yesextconfrb128 use rbconfig instead of obsolete and deprecated configchecking for cc yeschecking for magickconfig yeswarning found more than one imagemagick installation this could cause problems at runtime usrlocalbinmagickconfig reports version 680 q16 is installed in usrlocal usrbinmagickconfig reports version 1312 is installed in usrusing 680 q16 from usrlocalchecking for imagemagick version 649 yeschecking for hdri thisabled version of imagemagick yeschecking for stdinth extconfrb failed could not create makefile due to some reason probably lack ofnecessary libraries andor headers check the mkmflog file for moredetails you may need configuration optionsprovided configuration options withoptdir withoutoptdir withoptinclude withoutoptincludeoptdirinclude withoptlib withoutoptliboptdirlib withmakeprog withoutmakeprog srcdir curdir rubyhometechusbrbenvversions193p125binrubyhometechusbrbenvversions193p125libruby191mkmfrb381in try do the compiler failed to generate an executable file runtimeerroryou have to install development tools first from hometechusbrbenvversions193p125libruby191mkmfrb506in try cpp from hometechusbrbenvversions193p125libruby191mkmfrb931in block in have header from hometechusbrbenvversions193p125libruby191mkmfrb790in block in checking for from hometechusbrbenvversions193p125libruby191mkmfrb284in block 2 levels in postpone from hometechusbrbenvversions193p125libruby191mkmfrb254in open from hometechusbrbenvversions193p125libruby191mkmfrb284in block in postpone from hometechusbrbenvversions193p125libruby191mkmfrb254in open from hometechusbrbenvversions193p125libruby191mkmfrb280in postpone from hometechusbrbenvversions193p125libruby191mkmfrb789in checking for from hometechusbrbenvversions193p125libruby191mkmfrb930in have header from extconfrb193in maingem files will remain installed in hometechusbrbenvversions193p125librubygems191gemsrmagick2131 for inspectionresults logged to hometechusbrbenvversions193p125librubygems191gemsrmagick2131extrmagickgem makeoutan error occurred while installing rmagick 2131 and bundler cannot continuemake sure that gem install rmagick v 2131 succeeds before bundlingregarding this linethe compiler failed to generate an executable file runtimeerroryou have to install development tools firsti think i have exhausted all the information on how to fix this error via googlestackoverflow i already tried installing the development packages and such not sure where to go from here any help greatly appreciated,"['ruby-on-rails', 'ruby']" +388332,what does it mean when the main method throws an exception i am reviewing a midterm i did in preparation for my final exam tomorrow morning i got this question wrong but there is no correct answer pointed out and i neglected to ask the prof about itconsider the following code snippetpublic static void mainstring args throws filenotfoundexceptionwhich of the following statements about this code is correctthe main method is designed to catch and handle all types of exceptionsthe main method is designed to catch and handle the filenotfoundexceptionthe main method should simply terminate if the filenotfoundexception occursthe main method should simply terminate if any exception occursi had chosen the second option,['java'] +388342,can a class have no constructor this is a piece of code as an example after this rest are just methods look at bottom for maze class so when this is instantiated usingmaze labyrinth new mazeandsystemoutprintln labyrinththis will print out the grid arrayis this legit i thought all classes needed constructors how does it print out the 2d grid arraymaze classpublic class maze private final int tried 3 private final int path 7 private int grid 101101 10101001 0101010100 1010101 10101001 10101 10 1 public string tostring string result n for int row 0 row gridlength row for int column0 column gridrowlength column result gridrowcolumn result n return result,['java'] +388347,systemnetmailsmtpexception the smtp server requires a secure connection or the client was not authenticated i am trying to send email with my websites address from a c applicationthis worked fine for several months until recently maybe my provider changes some things or someone else changed settings heres the code private void sendemailemail invite mailmessage mail new mailmessage smtpclient smtpserver new smtpclientsmtpservername mailfrom new mailaddressemailusername mailtoaddinviterecipientemail mailsubject invitemessagesubject mailbody invitemessagebody smtpserverusedefaultcredentials false smtpserverport 587 smtpservercredentials new systemnetnetworkcredentialemailusername emailpassword smtpserverenablessl true smtpserversendmail heres the error the smtp server requires a secure connection or the client was not authenticated the server response was smtp authentication is requiredlooking at other questions i tried what they suggested to make smtpserverenablessl true this did not work at all it gave the followingsystemnetmailsmtpexception server does not support secure connectionsi am guessing i should thisable ssl and have it the way it was beforeany suggestions how to make email sending work againediti have tried without smtpserverusedefaultcredentials falsei have tried with it set to true smtpserverusedefaultcredentials truei have tried commenting that line along with the following smtpservercredentials new systemnetnetworkcredentialemailusername emailpassword,['c#'] +388386,database sync or migration tool it is really a pain keeping production and development databases in sync manuallyis there any tool that allows one to keep the two databases in sync something like the amazing laravel frameworks migrations thingi am using mysql and php i searched here and there but was not able to spot the right tool for the job,['php'] +388391,javascript interface not working with android 42 i am facing a serious bug of android os jelly bean 42 here in my program i am using javascript to get the height of webpage and it is perfectly working from android 22 to 41 but when i tried to use the same code in android 42 so the javascript interface not workinghow can i fix this issue,"['javascript', 'android', 'css']" +388400,tan 45 gives me 09 why does tan 4507853981633974483 in radian give me 09 whats wrong with the following code systemoutprintlnmathtanmathtoradians450 i do not think there is any typo in hereso whats the solution here,['java'] +388437,using ios dropbox sdk to do a chunked upload of core data i have an ios app that uses core data for persistent data storage i integrated dropbox as a way for users to perform a a backup of the persistent store file appnamesqlitea uibutton calls a method to see if a file already exists on dropbox ifdbsession sharedsessionislinked nsstring foldername selfdateformatter stringfromdatensdate date stringbyreplacingoccurrencesofstring withstring nsstring destinationpath nsstring stringwithformatgradebook probackupfoldername selfmetadataindex metadata request backup selfrestclient loadmetadatadestinationpath the loadedmetadata delegate method initiates the upload with the rev number of the existing file if one exists void restclientdbrestclient client loadedmetadatadbmetadata metadata save core data nsstring foldername selfdateformatter stringfromdatensdate date stringbyreplacingoccurrencesofstring withstring nsstring documentsdirectory documents directory nsstring sourcepath nsstring stringwithformatgradebookprosqlite documentsdirectory nsstring destinationpath nsstring stringwithformatgradebook probackupfoldername selfrestclient uploadfilegradebookprosqlite topathdestinationpath withparentrevmetadatacontents lastobjectrev frompathsourcepath this works well for reasonably small files or large files over a perfect network connection but any small error during the upload cancels the whole process i would like to switch to using the chunked upload methods but i am at a loss as to how to actually do the chunking of the sqlite filei cannot seem to find any sample apps that are using the chunked upload that i can learn from and the documentation simply says to provide the file in chunksso my questions areis the chunked upload the right approach to addressing the user issues with uploading large files over a possibly spotty network connectioncan you point me to sample code app documentation for chunking a file i am pretty comfortable with the dropbox sdkthanks,"['objective-c', 'ios']" +388444,objective c underscore property vs self i am was playing around with the standard sample split view that gets created when you select a split view application in xcode and after adding a few fields i needed to add a few fields to thisplay them in the detail viewand something interesting happendin the original sample the master view sets a detailitem property in the detail view and the detail view thisplays it voidsetdetailitemid newdetailitemif detailitem newdetailitem detailitem newdetailitem update the view self configureviewi understand what that does and all so while i was playing around with it i thought it would be the same if instead of detailitem i used selfdetailitem since it is a property of the classhowever when i used selfdetailitem newdetailitemi actually got stuck in a loop where this method is constantly called and i cant do anything else in the simulatormy question is whats the actual difference between the underscore variablesivar and the properties i read some posts here it seems to be just some objective c convention but it actually made some difference,['objective-c'] +388476,how to use visual studio generated async wcf calls my operationcontractpublic listmessagedto getmessages listmessagedto messages new listmessagedto foreach message m in contextmessagestolist messagesaddnew messagedto messageid mmessageid content mcontent date mdate hasattachments mhasattachments mailinglistid intmmailinglistid senderid intmsenderid subject msubject return messages in service reference configuration i checked the option generate asynchronous operations how do i use the generated getmessagesasync in the net i found examples that use asynccallback however i am not familiar with that is there a way to use it in some friendly way like async and await keywords in net 45 if not what should i do to invoke the method asynchronously,"['c#', '.net']" +388487,php memcachedll for 64 bit wampserver with either php 5313 or 543 okay so far ive been googeling and trying to find a solution for over 6 hours normally i dont post questions because i feel the answer should be findable but here goes nothingi need to work with php code that has implemented the memcache class i use wampserver 22 as 64 bit install with apache 2 php 543 installed 5313 too to see if i could fix it in that version and mysql 5524i have run the memcache service with both the memcachedwin6414414zip link and the memcached126win32binzip link i am now at a point where the feedback from wampserver i get is the following when restarting the apache module mem cache module using the answers from a similar thread on stackoverflowcomquestions3894065phpmemcachedllvc6x64 in combination with php 5313 64 bit php startup memcache unable to initialize module module compiled with module api20090626 php compiled with module api20100525 these options need to matchthis is a lot further than i got with the other options most or all results i can come up with seem to redirect to either a 32 bit dll which i cant use since my wampserver is 64 bit or with the wrong php version or api version compilation date i do not think i am able to compile my own library to solve thisi have added extensionphp memcachedll to both phpini files for both php versions and the dll files have been placed into the correct phpphp5xxext folders of the wamp servermy assumption so far is that i need the php memcachedll compilated for 64 bit x64 for php 5313 on the 25th of may 2010 that or i need to install a php version matching the binairy compiled on the 26th of june 2009do any of you have a soltion to my specific dillemma any help will be greatly appriciated,['php'] +388488,is there any way to get another element value in less i am new to lessin my script i would like to use the width of box1 in box2please review my scriptbox1 width 10px height 500pxbox2 width box1width 100pxis it possible or not if yes please give me correct less code,['css'] +388501,why is not a qualified static final variable allowed in a static initialization block case 1class program static final int var static programvar 8 compilation error public static void mainstring args int i i programvar systemoutprintlnprogramvar case 2class program static final int var static var 8 ok public static void mainstring args systemoutprintlnprogramvar why does case 1 cause a compilation error,['java'] +388513,a better way to avoid hibernate lazy init exception when serializing in to a json response this is in reference to a question i asked a month backin this question the answer to avoid the lazy init exception when json serializing was to set null to the variables that cause lazy init exception but consider when the class has many dependencies now with the code base is grown and every time i have to set null to the troublesome variables everywhere in the code to avoid json serializing problem the method does not look neat when the code base is largean example code is shown below that does not look goodsetting some variables to avoid lazy init exception in jackson mapper serializationbatchsetenrollmentlistnulistbatchschedule schedulelist arraylistbatchschedule batchgetbatchschedulelist for batchschedule batchschedule schedulelist batchschedulesetbatchnull batchgetlecturersetbatchlistnull batchgetlecturersetsubjectlistnull batchgetsubjectsetbatchlistnull batchgetsubjectsetlecturerlistnullcan you please suggest me a better way to handle this problemthanks,['java'] +388554,is there any way to create a primitive array without initialization as we know java always initialises arrays upon creation ie new int10 always returns an array with all elements 0 i understand that it is a must for object arrays but for primitive arrays except may be boolean in most cases we do not care about the initial values does anybody know a way to avoid this intialization,['java'] +388561,inapp purchase tracking with google analytics ios sdk i would like to track inapp purchases with the google analytics sdk for ios v2 as indicated in their ecommerce tracking guidei am currently doing the following after receiving a skpaymenttransactionstatepurchased transaction update void tracktransactionskpaymenttransactiontransaction nsstring transactionidentifier transactiontransactionidentifier gaitransaction gaitransaction gaitransaction transactionwithidtransactionidentifier withaffiliationapp store skpayment payment transactionpayment nsstring productidentifier paymentproductidentifier skproduct product self productforidentifierproductidentifier nsstring producttitle productlocalizedtitle int64 t priceinmicros productpricefloatvalue 10 fixme does not consider different currencies gaitransaction additemwithcodeproductidentifier nameproducttitle categorynil pricemicrospriceinmicros quantitypaymentquantity gaitransactionrevenuemicros priceinmicros paymentquantity fixme does not consider apples cut idgaitracker tracker gai sharedinstancedefaulttracker tracker tracktransactiongaitransactionis the above the right way of tracking inapp purchases i detect two problems at the very leastskproduct returns a localized price and if i track it asis revenue aggregation will be incorrect is there a way to normalize the pricethe revenue returned does not take apples cut into account which is not always 30 is it possible to obtain the net revenue within the app,"['iphone', 'ios']" +388617,why do gcc and nvcc g see two different structure sizes i am trying to add cuda to an existing single threaded c program that was written sometime in the late 90s to do this i need to mix two languages c and c nvcc is a c compilerthe problem is that the c compiler sees a structure as a certain size while the c compile sees the same structure as a slightly different size thats bad i am really puzzled by this because i cannot find a cause for a 4 byte thiscrepancy usrlibgcci586suselinux43i586suselinuxbinld warning size of symbol tree changed from 324 in tmpccvx8fpjo to 328 in gpuomy c looks likeinclude stdiohinclude stdlibhinclude asserthextern cinclude structinfoh contains the structure declarationand my c files look likeinclude structinfohwith structinfoh looking likestruct tb int nbranch nnode root branchesnbranch2 double lnl treemy make file looks like prgs progcc cflagsstdgnu99 m32cucc nvcuflags archsm 20libs lm lusrlocalcuda50lib lcuda lcudartall prgsprog cc cflags progc gpuo libs o proggpuo cucc cuflags c gpucusome people asked me why i did not use a different host compilation option i think the host compilation option has been deprecated since 2 release ago also it never appeared to do what it said it would do nvcc warning option hostcompilation has been deprecated and is ignored,"['c++', 'c']" +388654,context menus in chrome extensions i have searched and searched and searched for a solution to this but every source i come across seems to assume i already have profound knowledge of chrome extensions even googles help pagesi know the very basics of chrome extensions and i made one with some basic content scripts however now i am looking to make one that involves context menuslet us say when you highlight words and rightclick them you see the option search highlighted words on google and when clicked it opens highlighted words in a new tab i know this exists in chrome and i am sure there have been a billion extensions replicating it but this is only an example for me to build off ofhow can i do this,['javascript'] +388664,how do i access services of upnp device the device belkin wemo switchdev environment ms vc 2010 on windows7i am trying to enumerate the services of a upnp device using c from windowsi have got the iupnpdevice pointer and can access several propertiesi have got the iupnpservices pointer and can count the correct number of services 7i use queryinterface to get the ienumvariant pointer which appears to succeedhowever the next method always fails with hresult of 0x80040500 which translates as windows error 1280 0x500 error already fiberthis error does not make any sense to mei have tried using both ienumvariant and ienumunknown as the docs indicate it could be either but both produce the same resulti have included below the complete source file plus the output it producesnote it is hardcoded to use the udn of my own devicei would be very grateful if anyone can help as i am currently stuckbest regardsdavecode upnptest1cpp defines the entry point for the console applicationinclude stdafxhinclude windowshinclude upnphstatic void dumpcomerrorconst tchar api hresult hrint tmainint argc tchar argv int retcode1 assume failure hresult hr coinitialize0 if hrs ok iupnpdevicefinder devicefinder0 hr cocreateinstanceclsid upnpdevicefinder 0 clsctx inproc server iid iupnpdevicefinder voiddevicefinder if hrs ok iupnpdevice device0 hr devicefinderfindbyudnluuidsocket1 0221239k11002f6 device if hrs ok if device tchar manufacturer0 manufacturerurl0 tchar description0 name0 modelurl0 tchar serialnumber0 udn0 upc0 devicetype0 tchar presentationurl0 deviceget manufacturernamemanufacturer deviceget manufacturerurlmanufacturerurl deviceget descriptiondescription deviceget friendlynamename deviceget modelurlmodelurl deviceget serialnumberserialnumber deviceget uniquedevicenameudn deviceget upcupc deviceget typedevicetype deviceget presentationurlpresentationurl tprintf tmanufacturer s sn manufacturer manufacturerurl tprintf tmodel s sn sn description name modelurl tprintf tdevice serialsn udnsn upcsn typesn serialnumber udn upc devicetype tprintf turl sn presentationurl iupnpservices services0 hr deviceget servicesservices if hrs ok if services long numberofservices0 servicesget countnumberofservices if numberofservices0 iunknown unknown0 hr servicesget newenumunknown if hrs ok if unknown ienumvariant enuminterface0 hr unknownqueryinterfaceiid ienumvariantvoidenuminterface if enuminterface variant var unsigned long fetched0 hr enuminterfacenext1 var fetched if hrs ok else dumpcomerror tienumvariantnext hr else dumpcomerror tiunknownqueryinterface hr else fprintfstderr failed to get enumeration interfacen else dumpcomerror tiupnpservicesget newenum hr else fprintfstderr no services availablen else fprintfstderr failed to get services collectionn else dumpcomerror tiupnpdeviceget services hr else fprintfstderr device not foundn else dumpcomerror tiupnpdevicefinderfindbyudn hr else dumpcomerror tcocreateindex hr else dumpcomerror tcoinitialize hr return retcodestatic void addbooltostringconst tchar name bool value tchar buf int i int max if name name value buf i0 i snwprintf sbufi maxi maxi1sizeoftchar tssyes i0 t t namestatic void addinttostringconst tchar name int value tchar buf int i int max if name name value buf i0 i snwprintf sbufi maxi maxi1sizeoftchar tssd i0 t t name valuestatic void dumpcomerrorconst tchar api hresult hr bool failure hr0x80 true false bool severe hr0x40 true false bool microsoft hr0x20 false true bool ntstatus hr0x10 true false bool xbit hr0x080 true false int facility hr0x07ff016 int code hr0x0f tchar buf10240 int bufsize sizeofbufsizeoftchar int i0 addbooltostring tfailure failure buf i bufsize addbooltostring tsevere severe buf i bufsize addbooltostring tmicrosoft microsoft buf i bufsize addbooltostring tntstatus ntstatus buf i bufsize addbooltostring txbit xbit buf i bufsize addinttostring tfacility facility buf i bufsize addinttostring tcode code buf i bufsize ftprintfstderr tns failed hr0x08xnsn api hr bufoutputit produces following outputmanufacturer belkin international inc model belkin plugin socket 10 wemo switch device serial221239k11002f6 udnuuidsocket1 0221239k11002f6 upc123456789 typeurnbelkindevicecontrollee1url ienumvariantnext failed hr0x80040500failureyes microsoftyes facility4 code1280editafter a lot of deadends i have managed to get this working by manually building the soap requests and sending the requests via tcp using windows sockets tricky bit was getting the syntax just right as i had no experience of soap before upnp was useful to identify the ip address port number as these can change once up and running it is actually a lot simpler than the upnp interface let me know if youre interested and i can post the code it does not directly answer the question i posed here so it wouldnt make sense to answer my question with this detailhowever if youre interested let me know and i can post the codecheersdave,['c++'] +388669,how to force ie8 to repaint after adding a class to a dom element in ie8 if elements do not repaint with the associated css when you change the classname how can you force the browser to refresh and not kill ie8 performancethis post how can i force webkit to redrawrepaint to propagate style changes suggested calling offsetheight which forces a repaint this post had a comment that suggested adding and removing a class from body elementboth of these approaches killed ie8 performance and the first had sideeffects on my layoutwhats the best approach,"['javascript', 'jquery']" +388674,capybara tests fail with timeouterror in the first test when using google maps i am testing with rspec capybara selenium firefox no matter what subset of my acceptance tests i run the first one fails next tests do work correctly with reason like this failureerror visit timeouterror timeouterrormy application relies on googlemaps and backbonejs heavily when i run tests page does not finish to load and transferring data from mapsgoogleapiscom message stays in bottomleft of firefox window however page looks like it loaded properly maps and other content are present i have already set timeout to 60 secs to exclude any slow network problems and all the subsequent tests do work very fast like proper google scripts were fetched and are already cached also when i start server in development environment and access it localhost30 everything works finefirefox 1701 some of my gemscapybara 201database cleaner 091mongoid 3013rspec 2120rspeccore 2121rspecexpectations 2120rspecmocks 2120rspecrails 2120seleniumwebdriver 2260do you have any idea why this happens and how to prevent iteditspecspec helperrb this file is copied to spec when you run rails generate rspecinstallenvrails env testrequire fileexpand pathconfigenvironment file require rspecrailsrequire rspecautorun requires supporting ruby files with custom matchers and macros etc in specsupport and its subdirectoriesdirrailsrootjoinspecsupportrbeach f require frspecconfigure do config configinclude factorygirlsyntaxmethods configtreat symbols as metadata keys with true values true configinfer base class for anonymous controllers false configorder randomendspecfeaturesfeatures spec helperrbrequire relative spec helperrequire capybararspeccapybaradefault driver seleniumcapybaradefault wait time 60edit2it used to work properly before few weeks ago this project was halted for that time could be introduced by rspec upgrade from 211 to 212 which i did those few weeks ago but i have just tried to downgrade it and same things do happen i have reverted whole codebase to the point month ago to exclude possible gem regression problem still happensedit3i have just thiscovered that if i comment out the line responsible for attaching map from googlenew googlemapsmapmap0 mapoptionsthen everything works like a charmedit4source code of example application running all specs will result with timeouterror in the first one at least for me however all specs will pass whenyou remove line which initializes geocoder it is not used in example app but i use it in mineyou remove line which initializes mapwhat surprised me most when you provide trivial style sheet like nothing more than thatmap width 600px height 600px gems are exactly the same gems as i use in my app there are some 3rd party scripts in vendorassets,['ruby-on-rails'] +388708,how can i provide sphinx documentation for a namedtuple with autodoc i am trying to document a python project with sphinx but i am having trouble combining the autodoc extension with a namedtuple generated classin one document gammatonerst i havemodgammatone gammatone filterbank toolkit automodule gammatone members automodule gammatonecoeffs membersin my gammatonecoeffspy i havefrom collections import namedtupleerbfiltercoeffs namedtuple erbfiltercoeffs most parameters omitted a0 gain the code generated by namedtuple includes very generic docstrings that sphinxs autodoc module picks up and includes i would rather document the class properly myself without forgoing autodoc for the rest of the modulei have tried putting something like this just before the class class erbfiltercoeffsa0 gainparam a0 a0 coefficientparam gain gain coefficientmagic coefficientsbut it does not show up in the generated docs putting it after the class results in it being nested underneath the generic class documentation rather than replacing ithow do i simply tell sphinx and the autodoc extension to use my documentation for the erbfiltercoeffs class instead of that generated by namedtuple,['python'] +388710,why in java high low 2 is wrong but high low 1 is not i understand the fixes the overflow when adding two big positive longs you may endup with a negative number can someone explain how this bitwise shift magically fixes the overflow problem and how it is different than my suspicious i think it has to do with the fact that java uses twocompliments so the overflow is the right number if we had the extra space but because we do not it becomes negative so when you shift and paddle with zero it magically gets fixed due to the twocompliments but i can be wrong and someone with a bitwise brain has to confirm,['java'] +388713,definition of global variables using a non constant initializer include stdiohint i10int jiint main printfdji get an error stating that initialization element is not a constant what is the reason behind this,['c'] +388731,android onclose event i want to show a thanks for using message when the application closewhat is the event that handles application closing,['android'] +388741,how do i override constructor parameters in sphinx with autodoc let us say i have a class like thisclass myclassobject summary docs for my class extended documentation for my class def init self args selfvalues npasarrayargsif i use sphinx with the autodoc extension to document this class like so automodule mymodule membersthe constructor signature appears as myclassargs i would rather override this and document it as say myclassfirst second thirdif this were a function i could override the signature in the first line of the docstring but that trick does not seem to work on a class docstring so how can i override the constructor signature,['python'] +388745,copy folder recursively in nodejs is there an easier way to copy a folder and all its content without manually doing a sequence of fsreadir fsreadfile fswritefile recursively just wondering if i am missing a function which would ideally work like thisfscopypathtosourcefolderpathtodestinationfolder,['javascript'] +388755,check if two hashes have the same set of keys what is the most efficient way to check if two hashes h1 and h2 have the same set of keys thisregarding the order could it be made faster or more concise with close efficiency than the answer that i post,['ruby'] +388756,determine managed vs unmanaged resources there are lots of questions about managed vs unmanaged resources i understand the basic definition of the two however i have a hard time knowing when a resource or object is managed or unmanagedwhen i think of unmanaged resources i tend to think of native code that is not directly part of net such as pinvoke or marshaling resources i would normally think of resources meant to interface to something that will use hw such as a file handle or network connection also being unmanagedwhat about net objects that wrap native unmanaged resources such as a filestreama filestream must use unmanaged resources but when i implement the ithisposable pattern should i consider this a managed or unmanaged resourcesi have been assuming thus far that if the object implements ithisposable then it is managed how would i know that intptr should be handled as an unmanaged resoruce,"['c#', '.net']" +388786,when is smart to use bindservice and when startservice this may be a stupid question but i would like to know when it is smart to use bindservice and when to use startservicefor exampleif i use bindservice with bind auto create the service will be started and created automatically as is written here auto createwhen is it smart then to use bindservice and when startservice i really do not understand these two correctly,['android'] +388789,copying text to clipboard in chrome extension i am writing a google chrome extension and i want to copy some text in clipboard in a content script i tried selecting it and then documentexeccommandcopy it does not work i do not want flash because it is not easy and elegant way to achieve that i tried background page and input it does not workis there any working elegant and simple way to copy text to clipboard in chrome extension it may also use jqueryregards,"['javascript', 'jquery']" +388821,c address of lambda objects as parameters to functions from my experience it seems that eithera lambda expression created inside a function call is destroyed just after the invocationcalling a function that expects a stdfunction creates a temporary object stdfunction out of the lambda and that object is destroyed after invocationthis behavior can be observed with the following snippet of codeconst functionvoid pointervoid aconst functionvoid f pointer fvoid b pointerint main int value 1 stdcout value stdendl 1 this works functionvoid f stdcout value stdendl af 2 this does not a stdcout value stdendl modify the stack char data1024 for int i 0 i 1024 i datai i 4 b return 0what exactly s actually happening in the second caseis there a correct way to call a without creating an explicit stdfunction objecteditthis both versions 1 and 2 compile just right but result in different outputsversion 10x7fa70148c80x7fa70148c8version 20x7fa70148c80,['c++'] +388830,how to design rest uri for multiple keyvalue params of http get i am designing a restful api one service should offer a query functionality for multiple keyvalue pairs for example the client can query with one http get request for different products and the belonging quantityexamplethe client wants to query product 1 with the amount 44 and product 2 with the amount 55 so how can i design my uri for this casei actually do not want my uri to look like cause i do not know how many products are queriedproduktproductid11productquantity144productid22productquantity255or like because how can the client know that before the comma there is the productid and after the comma the quantityproduktproduct144product255does anyone have got other solutions or isntt it restful to offer the possibility to query multiple products with one request is it maybe better to offer the possibility to query just one product with the belonging quantity and if the client whants to query more products he actually should send more requests,['java'] +388848,variable declaration between function name and first curly brace i am reading an article about code obfuscation in c and one of the examples declares the main function asint maincv char v int ci have never saw something like this v and c are global variablesthe full example is thisinclude stdiohdefine this printfdefine is sndefine obfuscation vint mainc v char v int c int a 0 char f32 switch c case 0 this is obfuscation break case 34123 for a 0 a 13 a fa va21 main0f break default main34123h3eglhl1o wortlwdls0m break thank in advancethe article obfphp,['c'] +388905,using cmd with in responsive mode in c or java i am using openssl in my c app the problem is if i use execopen ssl commandthen it will execute that particular command but actually this command is repsonsivei mean it further asks you are you sure you want to do this yni do not know how to cater this scenariohow can i use java or c to run a command line which is responsiveany help would be appreciatedthanks,"['java', 'c++']" +388912,jquery lazyload with ajax i use lazyload on my ecommerce website lazyload works great i use this code to do thatfunction imglazylazyload effect fadein also there are some filter like color price etc which is run an ajax and show new result when new result come lazyload does not work i know that i have to use lazyload with live delegate or on but i am a newbie on jquery and i could not do that can anyone help me please my jquery version is 172 and we can use on,['jquery'] +388923,java enum return int i am having trouble declaring an enum i have read up on the documentation but cannot figure it outwhat i am trying to create is an enum for a downloadtype where there are 3 download types audio video audio and videoi have implemented the code as followsprivate enum downloadtype audio0 video1 audio and video2 private final int value private downloadtypeint value thisvalue value this works fine if i then use it like thisdownloadtypeaudio and videovaluehowever i would like it so that i do not have to ask for the value i may be mistaken but this is the way several classes work in java such as font for example to set a font style you usefontplainwhich returns an int value we do not usefontplainvaluei must have misunderstood something because i cannot figure this outthanks in advance everyone,['java'] +388924,fitting height of homescreenwebapp for iphone 5 i have a problem with fitting the height of a webapp homescreenim using following metatagmeta nameviewport contentwidthdevicewidthminimumscale10maximumscale10userscalableno my problem is that the screen has black bars on top and bottom first i thoght that this is a bug of iphone 5 because of the heigher screen but today i saw a webapp appsftcom which fits perfect into the iphone5 screenany ideas what im making wronghere my full relevant metatagsmeta nameapplemobilewebappcapable contentyesmeta nameapplemobilewebappstatusbarstyle contentblacklink relappletouchiconprecomposed hrefimgiconsios icon 52pnglink relappletouchicon hrefimgiconsios icon 52pnglink relappletouchicon sizes72x72 hrefimgiconsios icon 72pnglink relappletouchicon sizes114x114 hrefimgiconsios icon 114pngedit after an hour of searching i found the solution how to force the browser to fit on full heightmy iphone only fits the height when i define a startup image appletouchstartupimagehere my code iphone 4 retina link hrefimgiconsappletouchstartupimage640x920png mediadevicewidth 320px and deviceheight 480px and webkitdevicepixelratio 2 relappletouchstartupimage iphone 5 link hrefimgiconsappletouchstartupimage640x1096png mediadevicewidth 320px and deviceheight 568px and webkitdevicepixelratio 2 relappletouchstartupimage,['html'] +388952,respond to vs respond to missing what is the point of defining respond to missing as opposed to defining respond to what goes wrong if you redefine respond to for some class,['ruby'] +388955,running a meteor app on nodejitsu deployed a meteor app to a nodejitsu trial environment but failed to get it to run upon executing jitsu deploy from my meteor app directory i get the following error referenceerror meteor is not defined if you have gotten a meteor app up and running on nodejitsu please highlight the steps you took and dependencies i might be missing i will use your suggestions and try to get my app to run thanks packagejson contents name test123meteor subdomain user123test123meteor really not sure about this line here scripts start node clientcontrollersgeneralcontrollerjs version 0012 engines node 08x,['javascript'] +388968,find closest match to input string in a list of strings i have problems finding an implementation of closest match strings for neti would like to match a list of strings exampleinput string publiczna szkoaa podstawowa im bolesaawa chrobrego w wasoszulist of stringspubliczna szkoaa podstawowa im b chrobrego w wasoszuszkoaa podstawowa specjalnaszkoaa podstawowa imhenryka sienkiewicza w wasoszuszkoaa podstawowa im romualda traugutta w wasoszu ga3rnymthis would clearly need to be matched with publiczna szkoaa podstawowa im b chrobrego w wasoszuwhat algorithms are there available for net,"['c#', '.net']" +389024,listagg function result of string concatenation is too long i am using oracle sql developer version 3004 i attempted to use the function listagg to group the data together create table final log as select session dt c ip cs user agent listaggweb link within grouporder by c ip cs user agent web links from webviews group by c ip cs user agent session dt order by session dthowever i keep getting the errorsql error ora01489 result of string concatenation is too longi am pretty sure that the output may be more than 40 since the web link mentioned here is a concatenated value of url stem and url query is there any way to go around it or is there any other alternative,['sql'] +389045,extjs grid click event listener i did successfully add a row double click event listener to my grid bylisteners itemdblclick functiondv record item index e alertworking now i need to get the exact value in third column at the selected row how can i do that editokay found itlisteners itemclick functiondv record item index e alertrecordgetname but seems like the result of recordgetname is not a text its an object but i cannot handle it as if it a text any body has any idea editfor example if i pass the name to search function searchrecordgetname this would not work but if i pass it this way searchmike it works,['javascript'] +389073,authentication between mvc and webapi separate domainsapplications im looking for good ideasresourcesimplementations for the following scenarioa mvc website at a webapi rest service at important please notice the separate domainsapplications a user logs in at the website and data is fetched from the api via jsonpcorsobviously i dont want the user to authenticate on the webapi using basic authentication but the api is also exposed to androidios apps so i need the basic authi have thought about returning a token from the mvc site and then writing a delegatinghandler at the webapi site to authenticate using that token but i would like some inputs or perhaps even better solutionsi made a pretty diagram just for the occation,['c#'] +389076,identifying a property name with a low footprint i wish to send packets to sync properties of constantly changing game objects in a game i have sent notifications of when a property changes on the server side to a entitysync object that is in charge of sending out updates for the client to consumeright now i am prefixing the property string name this is a lot of overhead for when youre sending a lot of updates position hp angle i would like for a semiunique way to idneity these packetsi thought about attributes reflection slow using a suffix on the end and sending that as an id position a hp a but i am at a loss of a clean way to identify these properties quickly with a low foot print it should consume as few bytes as possibleideas,['c#'] +389133,unable to execute dex multiple dex files define lcomgoogleandroidgcmgcmbaseintentservice i am busy for a school assignment to create a timetable app which fetches data from my database by json i use the gcm service for push notifications and johan nilssons android actionbarhowever when i try to export my application to an apk file the following errors occur 20121210 102803 dex loader unable to execute dex multiple dex files define lcomgoogleandroidgcmgcmbaseintentservice20121210 102803 timetable conversion to dalvik format failed unable to execute dex multiple dex files define lcomgoogleandroidgcmgcmbaseintentservicewhile exporting an android dependencies map is created and creating a duplicate inside there is a reference to gcm and the android actionbar while the gcm is already in the referenced libraries map after adding the gcm to the build path from the libs folderso after deleting the dependencies i cannot run and export the application because of the errorsi already tried cleaning and rebuilding the app please help me,['android'] +389150,what happens to a background worker that is still running when you close the form or another facet to the questions is should i be handling the possibility the form is closed when coding a background workeri have for example code that does an sql query which is not cancellable in a background worker then when complete boldifies dates in a calendar control to match the dates returned from the query i am curious what the background worker is designed to do in such a situation not fire the runworkercomplete event ignore calls to the dialog in the runworkercomplete function call because it is not a window any more,['c#'] +389166,why there is no static if in c11 i wonder why such a natural thing like static if did not manage to get into c11 some people object that using inheritance or template specialization we could achieve demanded results butwhy do not we have a simple static if for simple situations when one does not want to bloat up the source code with all that,['c++'] +389206,back to main activity from notificationcreated activity i am trying to implement the behaviour described here where a notification or whatever starts an internal activity in your app and then when the user pressed back it goes to my home activity the android docs sayin the case of the back button you should make navigation more predictable by inserting into the tasks back stack the complete upward navigation path to the apps topmost screen this allows users whove forgotten how they entered your app to navigate to the apps topmost screen before exitingis there a good way to actually do that other questions on stackoverflow suggest starting the main activity with an intent that tells it to start the internal activity but that seems like a huge hack that i somewhat doubt google would have used in gmail and i assume there is a decent method given that they are advocating the behaviourso is there a nonhacky way to do this,['android'] +389234,sending html email through amazon ses i am sending bulk emails using amazon ses my code is given belowpublic void sendmailstring sender linkedliststring recipients string subject string body destination destination new destinationrecipients try access key emailsenderpropgetpropertyaccesskey secret key emailsenderpropgetpropertysecretkey content subjectcontent new contentsubject content bodycontent new contentbody body msgbody new bodybodycontent message msg new messagesubjectcontent msgbody sendemailrequest request new sendemailrequestsender destination msg awscredentials credentials new basicawscredentialsaccess key secret key amazonsimpleemailserviceclient sesclient new amazonsimpleemailserviceclientcredentials sendemailresult result sesclientsendemailrequest systemoutprintlnresult email sent catchexception e systemoutprintlnexception from emailsenderjava email not send here i have given my html content as string to the variable bodythe mail sent successfully but i got the html content as email how to send html content in mail what changes in the code will solve this issue,['java'] +389279,for google api access can i create multiple client ids for the same android package name i am following the quickstart guide here to get google drive integration with my android app so i created two client ids using the debug and release sha1 fingerprints for the same package name the api console allowed this but i was wondering since i created the client id with the debug key sha1 fingerprint will the google oauth2 server accept authentication request coming from my release apps by the way i am using google play services api to request auth token so there is no way to specify the client id string shown in the api console,['android'] +389295,jsonnet struct serialization thiscrepancy when using jsonnet to serializedeserialize structs a buildin struct type like systemdrawingsize serializes to a string whereas a custom struct type serializes to a json object for exampleusing systemusing systemdrawingusing newtonsoftjsonnamespace testjsonnet class program static void mainstring args consolewritelinejsonconvertserializeobjectnew size50 50 consolewritelinejsonconvertserializeobjectnew size250 50 struct size2 public int width get set public int height get set public size2int w int h this width w height h outputs the following50 50width50height50i can understand the thinking behind serializing a struct to a string since the memory layout is always the same however why the thiscrepancy when serializing a custom structalso i would for internal legacy reasons like to have jsonnet serialize structs like the latter case ie as json not string if it is possible how can that be achieved,['c#'] +389335,akka actors and futures understanding by example i am trying to learn akka actors and futures but after reading the docs at and doing i am still having some issues with understanding i guess calculate the value of piis a thing a lot of people can relate too but not me i have search around a bitbut have not found any examples that suits me therefore i thought that i would take some reallife code of mine and throw it in here and exchange it for an example of how to do this with akkaok so here we goi have an java play2 application where i need to take some data from my db and index it in my elasticsearch instance i call the db and get the ids for the venues i then split the list and create a couple of callable indextasks after that i invoke all tasks where each task collects the venues for the assigned ids from the dbfor each venue index it to the elasticsearch instance and make it searchabledoneapplicationjavapublic class application extends controller private static final int venue batch 10 private static int size public static result index listlong venueids dbservicegetallvenueids size venueidssize loggerinfowill index size items in total executorservice service executorsnewfixedthreadpoolgetruntimeavailableprocessors int startix 0 collectioncallableobject indextasks new arraylistcallableobject do int endix mathminstartix venue batch size listlong sublist venueidssubliststartix endix venueindextask indextask new venueindextasksublist indextasksaddindextask while startix venue batch size loggerinfoinvoking all tasks try serviceinvokeallindextasks catch interruptedexception e eprintstacktrace return okindexrenderdone indexing venuetaskpublic class venueindextask implements callableobject private listlong idsublist public venueindextasklistlong idsublist thisidsublist idsublist loggerdebugcreating task which will index idsublistsize items range rangeasstring override public object call throws exception listvenue venues dbservicegetvenuesforidsidsublist loggerdebugdoing some indexing venuessize forvenue venue venues venueindex return null private string rangeasstring return idsublistget0 idsublistgetidsublistsize 1 venueindextypename venuepublic class venue extends index private string name find method static for request public static findervenue find new findervenuevenueclass public venue public venuestring id string name superid id thisname name override public map toindex hashmap map new hashmap mapputid superid mapputname name return map override public indexable fromindexmap map if map null return this thisname string mapgetname return this so all you akka people out there go nuts and please do as much as you can propose cool futures functionality that could be used or any other knowledgecode that i could use to learn this stuff,['java'] +389356,how to set a breakpoint on objectatindex method of a specific property in a specific class in xcode 4 i would like to set a symbolic breakpoint on objectatindex method of a specific property in a specific clasee the following code interface fooproperty strongnonatomic nsmutablearray fooarrayendi ve tried the following things foo fooarray objectatindexfoofooarray objectatindexfoofooarray objectatindexfoofooarrayobjectatindexfoofooarrayobjectatindexfoofooarrayobjectatindexnone of theses solutions workany ideas to do the trick,['objective-c'] +389375,calculate the percentage of the root owned by its parents in simplified terms i am trying to calculate the percentage of the root of a tree owned by its parents further up the tree how can i do this in sql aloneheres my sample schema please note that though the hierarchy itself is quite simple there is an additional holding id which means that a single parent can own different parts of their childcreate table hierarchy test id number root id parent id number parent of id holding id number the id can be split into multiple parts percent owned number 3 2 primary key id parent id holding id and some sample datainsert all into hierarchy test values 1 2 1 1 into hierarchy test values 2 3 1 025 into hierarchy test values 2 4 1 025 into hierarchy test values 2 5 1 01 into hierarchy test values 2 4 2 04 into hierarchy test values 4 5 1 1 into hierarchy test values 5 6 1 03 into hierarchy test values 5 7 1 02 into hierarchy test values 5 8 1 05select from dualsql fiddlethe following query returns the calculation i would like to make due to the nature of sys connect by path it cannot to my knowledge perform the calculation itself select a level as lvl 1 sys connect by pathpercent owned as calc from hierarchy test a start with id 1connect by nocycle prior parent id idthere are cyclical relationships in the data just not in this exampleat the moment i am going to use a pretty simple function to turn the string in the calc column into a numbercreate or replace function some sum p sum in varchar2 return number is l result numberbegin execute immediate select p sum from dual into l result return l result endthis seems to be a ridiculous way of going about it and i would rather avoid the additional time that will be taken parsing the dynamic sql1theoretically i think i should be able to use the model clause to calculate this my problem is caused by the nonuniqueness of the tree one of my attempts at using the model clause to do this isselect from select a level as lvl 1 sys connect by pathpercent owned as calc from hierarchy test a start with id 1 connect by nocycle prior parent id id model dimension by lvl ll id ii measures percent owned parent id rules upsert all percent ownedany any order by ll ii percent ownedcvll cvii nvl percent ownedcvll 1 parent idcvll cvii 1 this understandably fails with the followingora32638 non unique addressing in model dimensionsusing unique single reference fails for a similar reason namely that the order by clause is not uniquetldris there a simple way to calculate the percentage of the root of a tree owned by its parents using only sql if i am on the right track with model where am i going wrong1 i would also like to avoid the plsql sql contextswitch i realise that this is a tiny amount of time but this is going to be difficult enough to do quickly without adding an additional few minutes a day,['sql'] +389388,jquery mobile page resizing during page transition i am developing an app using jquery mobile and phonegap the issue that i have is that when i do a page transition the incoming page first appears incorrectly dom elements not in the right position nor the right size then once the transition is complete the elements resize and move to the correct position also the page transitioning out also appears incorrectly before it moves out i have tested this using both fade and slide transitions i would like to have slide transitions ultimatelyhere is a jsfiddle illustrating the problemi am also using a div as a page container so that the entire page is not transitioning at once but just the page container divi am using css percentages for pretty much everything heights widths margins etc so that the app will scale to different device sizes additionally i am using javascript to center some elements fired on pageshow event i think these percentages are part of the problem i constructed a simple test on a desktop browser taking out phonegap and set a fixed height to the page container this seemed to fix the problem but when i tried it on my phone the issue was still there each page in the app is preloaded into the dom using mobileloadpage i figured if i preload them the percentage height would be relative to the parent the page container div and the transitions should look correctlooking into jquery mobile further i found that during a transition the height of the page was set to an empty string i tried to comment out this line just to test to see if it would work with percentage heights again it worked on my desktop test but not on the phonei am using android phonegap api level 8 android 22 on a samsung galaxy nexus to testis there any way to have the css and javascript positioning applied before the page transitions while keeping percentage based valuesindexhtmlbody header on every page div idmainheaderthis is a headerdiv page content div idpagecontainer div datarolepagediv divbodypage1htmlbody div datarolepage idpage1 div clasubheader div classbackbuttondiv div clasubheadertextsettingsdiv div classhelpbuttondiv div divbodyrelevant csspagecontainer overflow hidden width 100 height 86772486772486772486772486772487uimobile datarolepage minheight 0px important color white position relative width 100 height 100 background 868a73subheader width 100 height 1016260162601626016260162601626 backgroundcolor 0 thisplay inlineblock textalign center position relativebackbutton background urlimagesback buttonpng backgroundsize contain backgroundrepeat norepeat thisplay inlineblock float left width 89 height 52 marginleft 56subheadertext color f fontsize 245em fontweight bold thisplay inlineblockhelpbutton float right background urlimageshelp buttonpng backgroundsize contain backgroundrepeat norepeat thisplay inlineblock width 89 height 64 right 56,"['android', 'jquery']" +389402,ios chrome detection i use javascript codeif androidwebosiphoneipadipodblackberrytestnavigatoruseragent for mobile device detection but chrome at ios is not detected is there a way to detect itthanks,"['javascript', 'ios']" +389418,binary image loaded from server to image with javascript i am loading a jpeg image from my server in binary format via xmlhttprequest i need it that way it is not base64 encodedis it possible to turn it to an img object with javascriptthanks,"['javascript', 'html']" +389500,rails 3 smtp settings for hotmaillive hosted email i am having an issue properly setting up my web application to use windows live hosted email instead of the normal google apps email this is due to the fact that google is down charging for such servicesi have entered in the proper configaction mailersmtp settings but for some reason i cannot get email notifications to properly send my config below if i swap the config with another google apps config settings email it is functional am i missing somethingconfigaction mailersmtp settings enable starttls auto trueaddress smtplivecomport 587domain maillivecomuser name netpassword authentication plainthis is the error i am receivinggetaddrinfo nodename nor servname provided or not known,['ruby-on-rails'] +389509,do any clientside javascript frameworks integrate well with nodejsexpressjssocketiojs i am building an webapp using nodejsexpressjssocketiojs on the backenddo any of the popular frontend frameworks agility angular backbone closure dojo ember gwt jquery knockback knockout spine yui etc integrate well with this backend for realtime applicationsi want my application to have a very realtime feel specifically when a user submits a form i want the information to be sent using web sockets to the backend for validation and if validation passes to be updated in the database then the serverside will use web sockets to send a confirmation that the data was saved or some list of errors i will use the servers response to update the page using javascripti know all this can be done with any of the listed frameworks i am interested in features of particular frameworks that will help the framework integrate better with the nodebased backend than the other frameworks,['javascript'] +389520,java class is public should be declared in a file named i am writing a program to process a file with weather data i scan the file take the data and place it into arrays and then print the array the problem i am having is that i am getting this compiler errori have checked my file names and my public class is the same as my java file besides checking that i have no idea where to gohere is my codeimport javaiofileimport javaiofilenotfoundexceptionimport javautilscannerpublic class weatherarray public static void mainstring args throws filenotfoundexception scanner input new scannernew fileportlandweather2011txt string head inputnextline string head2 inputnextline systemoutprintlnhead systemoutprintlnhead2 int count 0 whileinputhasnextline processinput count double prcp new doublecount double snow new doublecount double snwd new doublecount double tmin new doublecount double tmax new doublecount input new scannernew fileportlandweather2011txt head inputnextline head2 inputnextline systemoutprintlnhead systemoutprintlnhead2 count 0 whileinputhasnextline inputnext inputnext prcpcount inputnextdouble snowcount inputnextdouble snwdcount inputnextdouble tmincount inputnextdouble tmaxcount inputnextdouble count systemoutprintlnarrayavgprcp systemoutprintlnarrayavgsnow systemoutprintlnarrayavgsnwd systemoutprintlnarrayavgtmin systemoutprintlnarrayavgtmaxpublic static void procescanner input whileinputhasnext string station inputnext whileinputhasnextint string date inputnext whileinputhasnextint int prcp inputnextint whileinputhasnextint int snow inputnextint whileinputhasnextint int snwd inputnextint whileinputhasnextint int tmin inputnextint whileinputhasnextint int tmax inputnextint public static double arrayavgdouble array int count 0 double sum 0 forint i 0 i arraylength i count ifarrayi 3937 sum arrayi return sumcount,['java'] +389521,android 40 edittext without soft keyboard and with cursor positioning i am attempting to define an edittext box without having the soft keyboard thisplay automatically when the box is touched i also need to have the blinking cursor thisplayed and moved based on touch this is simple to do prior to android 40 by just using mtextsetinputtypeinputtypetype null this is the only way to suppress automatic soft keyboard thisplay but in android 40 it also suppresses the blinking cursor the cursor does however position properly and mtextgetselectionstart does return the last touch location for example if i touch between the 2 and 3 in an edittext box containing 123 mtextgetselectionstart correctly returns a 2 even though no cursor is thisplayed is there a way to programmatically thisplay a cursor at that locationhere is the code i am using to test edittext cursor locationspublic class testcodeactivity extends activity implements onclicklistener private edittext mtext override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate getapplicationcontext setcontentviewrlayouttest findviewbyidridbutton01setonclicklistenerthis findviewbyidridbutton02setonclicklistenerthis findviewbyidridbutton03setonclicklistenerthis findviewbyidridbutton04setonclicklistenerthis mtext edittext findviewbyidridedittext1 mtextsetinputtypeinputtypetype null override public void onclickview v if vgettagequalsclear mtextsettext else string buttontag vgettagtostring string str mtextgettexttostring int cursor mtextgetselectionstart ifcursorstrlength str str buttontag else str strsubstring0 cursor buttontag strsubstringcursor strlength mtextsettextstr mtextsetselectioncursor1 need code to thisplay blinking cursor at cursor1 location here is the layout xml xml version10 encodingutf8 linearlayout xmlnsandroid androidlayout widthfill parent androidlayout heightfill parent androidorientationvertical linearlayout androidlayout widthmatch parent androidlayout height85dp edittext androidididedittext1 androidlayout width0dp androidlayout heightwrap content androidlayout weight013 androidems10 androidtextsize25sp requestfocus edittext linearlayout linearlayout androidlayout widthmatch parent androidlayout heightwrap content button androidididbutton01 androidlayout width60dp androidlayout height60dp androidtext1 androidtag1 androidlayout gravitycenter androidtextsize30sp button androidididbutton02 androidlayout width60dp androidlayout height60dp androidtext2 androidtag2 androidlayout gravitycenter androidtextsize30sp button androidididbutton03 androidlayout width60dp androidlayout height60dp androidtext3 androidtag3 androidlayout gravitycenter androidtextsize30sp button androidididbutton04 androidlayout width60dp androidlayout height60dp androidtextclear androidtagclear androidlayout gravitycenter androidtextsize30sp linearlayoutlinearlayout,['android'] +389528,how to overload on stdfunction signature in c i know this question has been asked before but despite being a fairly experienced coder i do not understand the answers and see no way to respond to these previous questions to ask for clarification there is no reply link or anything besides those questions were quite old so i am asking the question afreshi have a class in which i am overloading the operator i want one overload to take a bare function pointer and the other to take a stdfunctionvoid operatorvoid handlervoid operatorfunctionvoid void t handlerusagemyclass aa dosomething a void x t y dosomething unfortunately the code does not compile because the compiler cannot determine that the second overload is unsuitable for the first callhow do i define my operator member functions to correct this problem i do not want to change how the operators are used eg by using an explicit cast i want them to work as demonstrated abovein addition it would be handy to have the following overload as wellvoid operatorfunctionvoid handlerbut again i cannot overload based on the signature of the function templatesee this thread for further examples isnt the template argument the signature of stdfunction part of its typei tried implementing the various solutions mentioned in that thread and none of them would compilei have been programming for many years in a number of languages but my c skills are a little rusty,['c++'] +389568,adt bundle for windows 7 64bit missing jre folder and wont run i have tried so i downloaded the 64bit version of the adt bundle from developerandroidcom and what not but when i run eclipse from this bundle this is not trying to add the plug in to an existing ide this is just the bundle it tells me im missing javawexe in a path for adteclipsejrebinjavawexei found my personal java installation on my computer and copied the files over but now it is saying it is failing at running a dll filedoes anyone have any advice perhaps even which jre version does this bundle use,['android'] +389664,a proper wrapper for consolelog with correct line number i am now developing an application and place a global isdebug switch i would like to wrap consolelog for more convenient usageisdebug controls the entire sitevar isdebug truedebugjsfunction debugmsg level var global this ifglobalisdebug globalconsole globalconsolelog return level levelinfo globalconsoleloglevel msgmainjsdebughere is a msgthen i get this result in firefox consoleinfo here is a msg debugjs line 8what if i want to log with line number where debug gets called like info here is a msg mainjs line 2,['javascript'] +389691,get cell value from a datatable in c here is a datatable dt which has lots of data i want to get the specific cell value from the datatable say cellij where i rows and j columns i will iterate ijs value with two forloopsbut i cannot figure out how i can call a cell by its indexheres the code for i 0 i dtrowscount 1 i for j 0 j dtcolumnscount 1 j var cell dtrowsij xlworksheetcellsi 1 j 1 cell,"['c#', '.net']" +389704,is it possible to develop static for loop in c is it possible for something like this to exist templateint channelvoid deduce maskmatrix const src int mask i hope i could become a constant and the compiler would unroll the loop at compile time forint i channel i 1 i mapper is a helper class which translate two and three dimension into one dimension index constexpr makes it possible to find out the index at compile time maskmapper0 1 i srcrow 1 coli maskmapper1 1 i srcrow coli maskmapper2 1 i srcrow 1 coli instead oftemplateint channelclass deducemaskpublic static void deduce maskmatrix const src int masktemplateint channelvoid deduce maskmatrix const src int mask maskmapper0 1 channel srcrow 1 colchannel maskmapper1 1 channel srcrow colchannel maskmapper2 1 channel srcrow 1 colchannel deducemaskchannel 1deduce masksrc masktemplateclass deducemask1public static void deduce maskmatrix const src int mask the second solution is the only solution i could come up of when i want the compiler to figure out the result at compile timedo i have an easy way to make the i become constant value likethe metaprogramming solutionfor me a simple for loop is much more easier to work with rather thanthe metaprogramming versionsorry for my poor english i hope i explain my problem properly,['c++'] +389724,how to change inside background color of uisearchbar component on ios i know how to removechange uisearchbar background color around search fieldselfsearchbarsubviews objectatindex0 removefromsuperviewselfsearchbarbackgroundcolor uicolor graycolorbut do not know how to do this inside it like thatthis needs to be compatible with ios 43thanks,"['ios', 'objective-c']" +389737,historypushstate not updating title i am using ajax to load main content of the page using historypushstateobjectstate stringtitle stringurl i am able to update the url in the address bar and navigate back in the historyhowever the title parameter appears to have no effect neither does the window title change nor the title of the entries in the history list perhaps both of them are same anywaywhat am i doing wrongupdate title param is simply ignored in chrome,['javascript'] +389747,matplotlib and libpng issues with ipython notebook i was trying to use ipython notebook i installed all the dependency libraries however i cannot use either the pylabinline option when launching ipython or savefig function in the ipython console when i tried to do either of them an error message was returned runtimeerror could not create write struct resulting from execution of matplotlib also a warning from the notebookapp prompt said libpng warning application built with libpng1241 but running with 1513however i installed the newest libpng1513 uninstalled matplotlib with pip uninstall and reinstalled matplotlib with pip install and during the build process i can see that libpng1513 is used for the building of matplotlibthe configuration for my system is mac os x106 python27 anybody has similar experience or some suggestiongshere are the traceback errorsmatplotliblinesline2d at 0x106066d50runtimeerror traceback most recent call lastoptlocallibraryframeworkspythonframeworkversions27libpython27sitepackagesipythonzmqpylabbackend inlinepyc in showclose 100 try 101 for figure manager in gcfget all fig managers 102 send figurefigure managercanvasfigure 103 finally 104 show to draw optlocallibraryframeworkspythonframeworkversions27libpython27sitepackagesipythonzmqpylabbackend inlinepyc in send figurefig 209 210 fmt inlinebackendinstancefigure format 211 data print figurefig fmt 212 print figure will return none if there is nothing to draw 213 if data is noneoptlocallibraryframeworkspythonframeworkversions27libpython27sitepackagesipythoncorepylabtoolspyc in print figurefig fmt 102 try 103 bytes io bytesio 104 figcanvasprint figurebytes io formatfmt bbox inchestight 105 data bytes iogetvalue 106 finallyoptlocallibraryframeworkspythonframeworkversions27libpython27sitepackagesmatplotlibbackend basespyc in print figureself filename dpi facecolor edgecolor orientation format kwargs 2050 orientationorientation 2051 dryruntrue 2052 kwargs 2053 renderer selffigure cachedrenderer 2054 bbox inches selffigureget tightbboxrendereroptlocallibraryframeworkspythonframeworkversions27libpython27sitepackagesmatplotlibbackendsbackend aggpyc in print pngself filename or obj args kwargs 501 pngwrite pngrenderer rendererbuffer rgba 502 rendererwidth rendererheight 503 filename or obj selffiguredpi 504 finally 505 if closeruntimeerror could not create write structthanks a lotjie,['python'] +389759,devise gem skip confirmation and skip confirmation via email both at once i am using devise gem and while creating user i want to skip confimation and skip confimation email for exampleusercreatefirst name vidur last name punjconfirmskip confirmationbut it skips only confirmation and does not skip sending confirmation email can any one give me an idea to skip both,['ruby-on-rails'] +389786,css wordwrap not working as expected why doesnt word wrap property work properly in the example belowwhat can i do to ensure that part of the word consectetur fits in the first line itself i want maximum number of characters to fit in each linethe css is fos fontfamily helvetica neue helvetica arial sansserif fontsize14px fontweight normal lineheight 18px width 238px height38px cursor pointer wordwrapbreakword border2px solid,"['html', 'css']" +389797,how to calculate moving sum with reset based on condition in teradata sql i have this data and i want to sum the field usage flag but reset when it drops to 0 or moves to a new id keeping the dataset ordered by su id and weeksu id week usage flag100 1 0100 2 7100 3 7100 4 0101 1 0101 2 7101 3 0101 4 7102 1 7102 2 7102 3 7102 4 0so i want to create this tablesu id week usage flag sum100 1 0 0100 2 7 7100 3 7 14100 4 0 0101 1 0 0101 2 7 7101 3 0 0101 4 7 7102 1 7 7102 2 7 14102 3 7 21102 4 0 0i have tried the msum function using group by but it would not keep the order i want above it groups the 7s and the week numbers together which i do not wantanyone know if this is possible to do i am using teradata,['sql'] +389800,char vs unsigned char for byte arrays when storing byte arrays blobs is it better to use char or unsigned char for the items unsigned char aka uint8 t standard says that sizeof of both is precisely 1 bytedoes it matter at all or one is more convenient or prevalent than the other maybe what libraries like boost do use,['c++'] +389810,how can i see the sql statements executed against my localdb database i am running localdb to develop my application and would like to see the sql statements which are being executed by my application from its various components is there a tool i can use to capture these statements,['sql'] +389824,whats the most secure way to embed a password inside java code i have to preface this question by saying that i am aware that hardcoding a password in the client application is bad practice for many reasons there are other questions dealing with that issue the scope of this question is narrower and assumes that authenticating credentials have to reside on the client applications code for some set of reasons that are out of your controlif some ways are better than others for instance jpasswordfield stores the password in a char array instead of a string and if you had to hard code it in the java application what measures could you take to make it harder to be fetchedupdateone instance of the application runs on a remote pc where the end user has admin rights the credentials are used to access a database in the same network so the actual password is already predetermined and must be entered manually in the actual code,['java'] +389825,this certificate was signed by an unknown authority i need to create ipa file for testing purposesi go to keychian access certificate assistant request a certificate from a certificate authority and create somecertsigningrequest filethen i upload that file to customer ios provisioning portal and create development and thistribution certificate which i download and install on my vmware macwhen i select certificate i got message this certificate was signed by an unknown authority here is the imagei am confused and do not know what can be wrongany help is greatly appreciatethanks people,['ios'] +389846,applicationwide configuration of lambdaj finalclassargumentcreators where and how to do it we have a problem with configuring lambdaj to work with joda time since localdate is a final class lambdaj needs to be initialized like following see bug 70public class localdateargumentcreator implements finalclassargumentcreatorlocaldate private final long msecs in day 10l 60l 60l 24l public localdate createargumentplaceholderint seed return new localdatelongseed msecs in day argumentsfactoryregisterfinalclassargumentcreatorlocaldateclass new localdateargumentcreatorsince we need this configuration to be applied virtually everywhere we are short of options on how to implement this our application is a web application based on spring and wicketi have come up with three different options1 static initialization block in the core maven modulesince the core module is included in every other module all modules would include the class the remaining question is that do static blocks always get initialized even if there are no references to the target classexamplepublic final class lambdajinitializer static initialize like above 2 an initializing bean in applicationcontextxmldownside never gets initialized for nonspring testsexample in applicationcontextcorexml included in every modulebean classlambdajinitializer public class lambdajinitializer postconstruct public void init lambdaj initialization 3 a call to a initializing method in the wicket application classdownside never gets initialized outside the web modulepublic class myapplication extends webapplication override public void init lambdaj initialization my question is which is the preferable way to achieve this,['java'] +389861,add option to a select and select it i have this codevar opt select optionfirstoptremovebuttononclick function selectprependoptval1that works fine in some browser but of course ie is not one of them in ie the combo ends with the two options but the text is in blank there is no selected option i assume this is because the option is still not loaded into the dom i assume that because i can easily fix this problem using this code insteadvar opt select optionfirstoptremovebuttononclick function selectprependopt settimeoutfunction selectval1 1however i would prefer something nicer any ideasnote i am not looking for performance in the selector or things like that the posted code is just a reduced example not my real script,"['javascript', 'jquery']" +389887,how to use linq on a multidimensional array to unwind the array consider the following arrayint numbers new int3 2 2 1 3 4 6 5 i would like to use linq to construct an ienumerable with numbers 2 1 3 4 6 5what would be the best way to do so,"['c#', '.net']" +389901,are there any benefits to using sql variant over varchar in sql server i currently have a database table setup as follows eav business reasons are validid int pkkey unique varchar15value varchar10this allows me to add in mixed values into my databse as keyvalue pairs for example1 some text hello world2 some number 123456etcin my c code i use adonet using readergetstring2 to retrieve the value as a string then have my code elsewhere convert it as needed for example int32parseintmyobjvalue i am looking at enhancing my table by possibly changing the value column to a sql variant datatype but i do not know what the benefit of this would be basically is there any advantage to having my value column be of sql variant vs varchar10to be more clear i read somewhere that sql variant gets returned as nvarchar40 back to the client making the call ouch but could not i cast it to it is type before returning it obviously my code would have to be adjusted to store the value as an object instead of a string value i guess what are the advantagesthisadvantages of using sql variant versus some other type in my current situation oh and it is worth mentioning that all i plan to store are datetimes strings and numerical types int decimal etc in the value column i do not plan on storing and blob or images or etc,['c#'] +389921,html5 video unable to playback in ipad after appendto or detach i am running into an interesting issue where my video is unable to play back in ipad after appendto or detach it presents a play button but when the play button is pressed nothing happensjsfiddlehtmlvideo idvideo1 source idmp4 src trailer480mp4 typevideomp4videodiv idnewdivjavascriptadocumentreadyfunction video1appendtonewaeditok folks there is been some confusion as to whats working and what is not let me make it really easy works does not workdoes not have anything to do with html tags or autoplay it is just a dead simple thing that makes ipad not play i am just wondering why or how to do an appendto or detach and have it work,"['javascript', 'jquery']" +389944,what do c generic methods on a nongeneric class boil down to if i have a class like this static class foo public static void bartt item consolewritelineitemtostring i know that in this example it is unnecessary to use t since all types have tostring on them etc it is simply a contrived example what i am more interested in is what happens under the bonnet in terms of the following foobarhellofoobar123foobarnew employeeisaaci broadly think i understand reification ie if you make different types of a generic class eglistint32liststringlistemployetc then at compiletime or runtime we end up with three actual concrete types one for each generic argument specified does the same apply to method calls in my first example ie would we still have a single class foo but three reified bar methods one for string int32 and employee,['c#'] +389945,android different drawable screen resolutions i am a bit confused as to what resolutions i should be saving my images in for the different drawable folders is there a general formula for it for exampleif i want an image to take up 10 of the height and the full width of the screen roughly how would i calculate what different resolutions i should save the image in,['android'] +390002,sdl2 opengl3 how to initialize sdl inside a function i am experimenting with the new sdl2 beta and an opengl3 context and i am having a weird problemif i run the sdl initialization code in my main function it works fine but i want to have this code in a separete init sdl functionif i put the initialization code in a separate init sdl function and call this function from main the background color is never drawn and the program starts to madly consume all my systems resourcescould someone point me to a working example where sdl is initialized in a separate function i cannot seem to find one maybe this is not possible i think i vaguely remember having a similar problem with sdl 12 but it is been a few years since i have used that and i do not think i ever found a solution in fact this may be the reason i chose to switch to using sfml insteadi really want to use sdl2 instead of sfml because it runs on more platforms but not being able to separate things out into small functions is a deal breaker for me this should be easy am i missing something obviouseditthis worksinclude iostreaminclude glglewhinclude sdlhdefine program name sdl2 opengl3 exampleint mainint argc char argv sdl window sdl2 window 0 sdl glcontext opengl3 context sdl initsdl init video set the opengl context version sdl gl setattributesdl gl context major version 3 sdl gl setattributesdl gl context minor version 2 turn on double buffering set the depth buffer to 24 bits you may need to change this to 16 or 32 for your system sdl gl setattributesdl gl doublebuffer 1 sdl gl setattributesdl gl depth size 24 create the sdl2 window sdl2 window sdl createwindowprogram name sdl windowpos centered sdl windowpos centered 512 512 sdl window opengl sdl window shown create the opengl3 context opengl3 context sdl gl createcontextsdl2 window glenum status glewinit if status glew ok stdcerr glew error glewgeterrorstringstatus n exit1 sync buffer swap with monitors vertical refresh rate sdl gl setswapinterval1 set background color glclearcolor 10 00 00 10 while true int status 0 glclear gl color buffer bit sdl gl swapwindowsdl2 window sdl event event while sdl polleventevent switch eventtype case sdl keydown break case sdl keyup if escape is pressed quit if eventkeykeysymsym sdlk escape status 1 set status to 1 to exit main loop break case sdl quit status 1 break if status 1 if received instruction to quit break delete opengl3 context destroy sdl2 window and shut down sdl subsystems sdl gl deletecontextopengl3 context sdl destroywindowsdl2 window sdl quit return 0this does not workinclude iostreaminclude glglewhinclude sdlhdefine program name sdl2 opengl3 examplevoid init sdlsdl window sdl2 window sdl glcontext opengl3 context sdl initsdl init video set the opengl context version sdl gl setattributesdl gl context major version 3 sdl gl setattributesdl gl context minor version 2 turn on double buffering set the depth buffer to 24 bits you may need to change this to 16 or 32 for your system sdl gl setattributesdl gl doublebuffer 1 sdl gl setattributesdl gl depth size 24 create the sdl2 window sdl2 window sdl createwindowprogram name sdl windowpos centered sdl windowpos centered 512 512 sdl window opengl sdl window shown create the opengl3 context opengl3 context sdl gl createcontextsdl2 windowint mainint argc char argv sdl window sdl2 window 0 sdl glcontext opengl3 context init sdlsdl2 window opengl3 context glenum status glewinit if status glew ok stdcerr glew error glewgeterrorstringstatus n exit1 sync buffer swap with monitors vertical refresh rate sdl gl setswapinterval1 set background color glclearcolor 10 00 00 10 while true int status 0 glclear gl color buffer bit sdl gl swapwindowsdl2 window sdl event event while sdl polleventevent switch eventtype case sdl keydown break case sdl keyup if escape is pressed quit if eventkeykeysymsym sdlk escape status 1 set status to 1 to exit main loop break case sdl quit status 1 break if status 1 if received instruction to quit break delete opengl3 context destroy sdl2 window and shut down sdl subsystems sdl gl deletecontextopengl3 context sdl destroywindowsdl2 window sdl quit return 0,['c++'] +390007,estimating small time shift between two time series i have two time series and i suspect that there is a time shift between them and i want to estimate this time shiftthis question has been asked before infind phase difference between two inharmonic waves and find time shift between two similar waveforms but in my case the time shift is smaller than the resolution of the data for example the data is available at hourly resolution and the time shift is only few minutessee imagethe cause of this is that the datalogger used to measure one of the series has few minutes shift in its timeany algorithms out there that can estimate this shift preferably without using interpolation,['python'] +390022,java hashmap implementation has next member in entry class whats the use of it java hashmap implementation has next member in entry private class since a new value for a key will override the old value whats the use of next member in the entry class static class entrykv implements mapentrykv final k key v value entrykv next final int hash creates new entry entryint h k k v v entrykv n value v next n key k hash h,['java'] +390066,html catch event when user is typing into a text input im just wondering how i go about catching the event when the user is typing into a text input field on my web applicationscenario is i have a contacts listing grid at the top of the form the user can type the name of the contact they are trying to find once there is more than 1 character in the text input i want to start searching for contacts in the system which contain those characters entered by the user as they keep typing the data changesall it is really is a simple type ahead type functionality or autocomplete but i want to fire off data in a different controli can get the text out of the input once the input has lost focus fine but this doesnt fit the situationany ideasthanks,"['javascript', 'jquery', 'html']" +390150,consuming a http stream without reading one byte at a time i have been trying to read data from the twitter stream api using c and since sometimes the api will return no data and i am looking for a nearrealtime response i have been hesitant to use a buffer length of more than 1 byte on the reader in case the stream does not return any more data for the next day or twoi have been using the following lineinputbeginreadbuffer 0 bufferlength inputreadcomplete null buffer new byte1now that i plan to scale the application up i think a size of 1 will result in a lot of cpu usage and want to increase that number but i still do not want the stream to just block is it possible to get the stream to return if no more bytes are read in the next 5 seconds or something similar,"['c#', 'asp.net', '.net']" +390154,unknown background style at phpstorm html code i am new to phpstorm this is awesome software for php developers i have a small problem on phpstorm html intelligent coding when i type html code the html code shows with background gray color i do not like the background gray colorso i want to remove this background color is it possible or not please help me,['html'] +390166,logarithm algorithm i need to evaluate a logarithm of any base it does not matter to some precision is there an algorithm for this i program in java so i am fine with java codehow to find a binary logarithm very fast o1 at best might be able to answer my question but i do not understand it can it be clarified,['java'] +390212,get base in html after it has been set but not using page url the base is dynamically set in php when an html page is builtbase line base href some path echo base linenow that i am in the html page i need to access this information some path and after searching for a few hours i do not seem to find an answer please note that the loaded html page has a url that is not related to the base and i do not have access to the php code to modify it the loaded page could have a url like but all other links in the page will be based on the value set by the base so i cannot get the base using the page urli suppose i could grab one of the elements like an image and thissect it using dom to find the base but there should be an easier way to do this any ideasusing windowlocation does not work in this situation as it will return what is related to the loaded page url and not what has been set as base within it,"['javascript', 'html']" +390214,how to attach a scrollbar to a text widget i am probably overthinking this but for some reason i cannot seem to figure this out i am trying to attach a scrollbar to my text field and have been unable to do so here is the segment of codeselfscroller scrollbarselfrootselfscrollerplacex706 y121selfoutputarea textselfroot height26 width100 selfoutputareaplacex0 y120selfscrollerconfigcommandselfoutputareayviewselfoutputareaconfigstatethisabled yscrollcommand selfscrollersetthis code is placing a very small scrollbar right next to my text field and by very small i mean that you can see the up and down arrows but nothing in between i can scroll with it when my text field fills up but is there a way to at the very least set the height of the scrollbar so that it appears to be the same height as the text field,['python'] +390221,initialize 2d array i am trying to initialize a 2d array in which the type of each element is charso far i can only initialize this array in the follow way public class tictactoe private char tablepublic tictactoe table00 1 table01 2 table02 3 table10 4 table11 5 table12 6 table20 7 table21 8 table22 9i think if the array is 1010 it is the trivial wayis there any efficient way to do that,['java'] +390226,no google fonts working in google chrome here is the linkif you click the squares within the black section they will change the font of the word to the left all of the fonts are google fonts but non of them are working in google chrome i have searched the internet with no solution all other browsers it is working fine,['css'] +390243,return json but it includes backward slashes which i do not want i use mvc4 webapi c and want to return json uning jsonnetthe problem is it comes with backward slashesi also added this code to globalasaxglobalconfigurationconfigurationformattersxmlformattersupportedmediatypesclearhere is what it returnscid1modelwt50jbdetailsdfunit2time in20121211t190time out20121212t130627746910700time used dd00time used hh00so what i want to see iscid1modelwt50jbdetailsdfunit2time in20121211t190time out20121212t1308505450700time used dd00time used hh00here is jsonconvetorstring json jsonconvertserializeobjectmyobj,['c#'] +390268,how to add string objects to nsmutablearray i have an nsmutablearray named randomselectionnsmutablearray randomselectioni am then trying to add strings to this array if certain criteria are metrandomselection addobjectstring1i am then trying to output the string to determine if it has added itnsstring test randomselection objectatindex0nslogtesthowever nothing is being output to the error log and i cannot figure out why any helphints appreciated,['objective-c'] +390376,seekg cannot handle file of 4294967295 bytes properly i found that in vs2010 seekg function does not work properly when file of exactly 4294967295 bytes is openedi am using simple codeinclude iostreaminclude fstreamusing namespace stdint tmainint argc tchar argv stdifstream file cmd fsutil file createnew tmptxt 4294967295 fileopenlctmptxt ifstreamin ifstreambinary iffileis open return 1 fileseekg0 stdiosend auto state filerdstate this condition shoots only when size of the file is equal to 4294967295 ifstate ifstreamfailbitifstreamfailbit stdcout seekg failed after seekg failed tellg returns 0 stdstreampos endpos filetellg return 0same code with files of 4294967294 and 4294967296 is working without any problemsdoes someone know a solution to this problemupdateit looks like that problem lies heretemplateclass statetypeclass fpos clr or this call operator streamoff const return offset return streamoff myoff fposoff fpos exactly at fposoff fposwheredefine fposofp longfpso it takes 4294967295 and converts it to 1 in other words speaking such code will failreturns 1 even if sizeoffpos t8fpos t pos fposoff4294967295 myoff fpos streamoffset are 64bitwhy they do this conversion if all types are 64 bit i have no idea,['c++'] +390437,xuggler encoding and muxing i am trying to use xuggler which i believe uses ffmpeg under the hood to do the followingaccept a raw mpjpeg video bitstream from a small ttl serial camera and encodetranscode it to h264 andaccept a raw audio bitsream from a microphone and encode it to aac thenmux the two audio and video bitsreams together into a mpegts containeri have watchedread some of their excellent tutorials and so far heres what i have got i will worry about implementing this functionality later but involves querying native device driversbyte nextmjpeg getnextmjpegfromserialport i will also worry about implementing this functionality as well i am simply providing these for thoroughnessbufferedimage mjpeg mjpegfactorynewmjpegnextmjpeg specify a h264 video stream howstring h264stream imediawriter writer toolfactorymakewriterh264streamwriteraddvideostream0 0 icodecidcodec id h264writerencodevideo0 mjpegfor one i think i am close here but it is still not correct and i have only gotten this far by reading the video code examples not the audio i cannot find any good audio examplesliterally i will be getting bytelevel access to the raw video and audio feeds coming into my xuggler implementation but for the life of me i cannot figure out how to get them into an h264aacmpegts format thanks in advance for any help here,['java'] +390438,open source libraryframework for building dashboard barlinepieetc i am looking for an open source libraryframework using which i can develop my dashboard showing different graphsi searched for few like eg highcahrts but these are licensedthe ui framework must handle the real time data like ajax calls or restany helpful suggestion appreciated,['javascript'] +390439,ruby gets that works over multiple lines using the irb i want to enter a multiple line string in order to strip certain characters from it gets only allows a single line is there a similar function for multiple linesascii projectrbmain0020 puts whats the text you want to strip whats the text you want to stripascii projectrbmain0030 str getsi now want to paste in a section of text because of the new lines it does not function this is why i want to collect over multiple lineshere is the code encoding cp850puts whats the text you want to stripstr getsstrgsubpascii puts str,['ruby'] +390472,setting up with ruby cannot load such file jsonpure hi i was working on an api while doingbinsbapp new app slug i got the error homeniteshgemruby191gemsbundler123libbundlerspec setrb90in block in materialize could not find multi json136 in any of the sources bundlergemnotfoundafter which i again tried gem install multi jsonand then again got the error successfully installed multi json150usrlocalsharerubysite rubyrubygemscore extkernel requirerb45in require cannot load such file jsonpure loaderror,['ruby'] +390490,convert string array to enum on the fly i am binding an enum to a property grid like thispublic enum myenum ethernet wireless bluetoothpublic class myclass public myclass myproperty myenumwireless defaultvaluemyenumwireless public myenum myproperty get set public form1 initializecomponent propertygrid pg new propertygrid pgselectedobject new myclass pgdock dockstylefill thiscontrolsaddpgmy problem i get data on the fly when the program is running i read the network adapter then store adapter names to myarray like thisstring myarray new string myarray0 ethernetmyarray1 wirelessmyarray2 bluetoothis possible convert myarray to myenum on the fly using c thank you,['c#'] +390498,html5 capture the screen possible duplicateusing html5canvasjavascript to take screenshots is there a way for a browser to take a global screenshot i mean the entire screen including what is not in the browseri kown that i may sound a little bit silly by asking this,['javascript'] +390499,does role provider cache per request my mvc application makes use of a users role in multiple places during individual page requests my question is whether the default sqlroleprovider caches the current users roles for the lifetime of a pagerequestfor example i make use of roles in attributes on controller methodsauthorizeroles adminand custom code if userisinrolemembershiproleadmin do somethingelse if userisinrolemembershiproleprinter do something elseif the role provider does not cache roles is the best solution to write a custom role provider that inherits from the default one and override the methods to get the roles once and cache them for the request duration can this be done in a way that both the authorize attribute and my own code will make use of the cached rolesin case you were wondering i do not want to use the cacherolesincookie webconfig option to cache the roles in cookiesthanks in advance for any suggestionsedit to include details triggered from joes answeri decompiled systemwebmvcauthorizeattribute and the authorizecore method calls the following method for each role to be checkedhttpcontextuserisinrolethen peering into systemwebsecurityroleprincipal which is what user is above both the methods below do indeed use a cached copy of the users roles or populates the cache if emptypublic string getrolespublic bool isinrolestring rolethe cache is stored as a field on user so its lifetime is for the duration of the requestthe methods find the roles usingrolesprovidersthis providernamegetrolesforuserthisidentitynameso will use whatever role provider you have chosen for the application default or custom,['asp.net'] +390532,android 412 default browser rendering issue with thisabled input fields it seems like some versions of the default android browser have a rendering issue if i create a page where i have some sort of input field and a button when i thisable the other input field the button appears grayed out unless this is done on page load you have to click around zoom for a bit to get the browser to rerenderthe interesting thing is it does not apply the thisabled style to the button but simply grays it out here is a samplelink to editor jsfiddlelink to embedded jsfiddle cssul liststyletypenone x background blue color whitexthisabled backgroundcolor red htmldiv idroot ul li input namex idenable classx typeradioenableinput li li input namex idthisable classx typeradiothisableinput li ul input typebutton classx valuebuttoninputdivjsfunction xeq0propthisabled truethings to notethe button is not thisabled click on it and it temporarily gets ungrayedoutthere is a style for the buttons thisabled state that sets its background color to red if you thisable the button you will see this work but the button does not appear red in the example so it is not even just rendering the thisabled style it seems to mainly just set the opacity to a lower valuea button before the radio buttons will not be affected any ideas how to work around this,"['android', 'html', 'css']" +390555,afnetworking why does it spawn a network request thread i am trying to understand operations and threads better and looked to afnetworkings afurlconnectionoperation subclass for example realworld source codemy current understanding is when instances of nsoperation are added to an operation queue the queue among other things manages the thread responsible for executing the operation in apples documentation of nsoperation it points out that even if subclasses return yes for isconcurrent the operation will always be started on a separate thread as of 106based on apples strong language throughout the thread programming guide and concurrency programming guide it seems like managing a thread is best left up to the internal implementation of nsoperationqueuehowever afnetworkings afurlconnectionoperation subclass spawns a new nsthread and the execution of the operations main method is pushed off onto this network request thread why why is this network request thread necessary is this a defensive programming technique because the library is designed to be used by a wide audience is it just less hassle for consumers of the library to debug is there a subtle performance benefit to having all networking activity on a dedicated threadadded jan 26thin a blog post by dave dribin he illustrates how to move an operation back onto the main thread using the specific example of nsurlconnectionmy curiosity comes from the following section in apples thread programming guide keep your threads reasonably busy if you decide to create and manage threads manually remember that threads consume precious system resources you should do your best to make sure that any tasks you assign to threads are reasonably longlived and productive at the same time you should not be afraid to terminate threads that are spending most of their time idle threads use a nontrivial amount of memory some of it wired so releasing an idle thread not only helps reduce your applicationas memory footprint it also frees up more physical memory for other system processes to useit seems to me that afnetworkings network request thread is not being kept reasonably busy it is running an infinite whileloop for handling networking io but see that is the point of this questions i do not know and i am only guessingany insight or deconstruction of afurlconnectionoperation with specific regards to operations threads run loops and or gcd would be highly beneficial to filling in the gaps of my understanding,['objective-c'] +390584,no mapped field when using partial query and composite keys in doctrine2 i have two models called person and tag one person has many tags and the tag primary key is a composite key of person id and tag person person and tag in doctrine2there is a data field blob in the tag model with a lot of data i am setting up a query that does not require the data from that field so i want to set up a query that does not retrieve that fieldi tried with the following queryselect c partial ttag from contact c left join ctagshere i get the somewhat expected error the partial field selection of class tag must contain the identifier no problem i add the contact fieldselect c partial tcontacttag from contact c left join ctagsbut now i get there is no mapped field named contact on class tagdoes doctrine2 not support partial queries on composite keyshere is the tag class entity tablenametag class tag id manytoonetargetentitycontactinversedbytags var contact protected contact id columntypestringlength10nullablefalse var string protected tag columntypeblob protected data,['php'] +390602,angularjs remove bindings to avoid memory leaks what is the proper way in angularjs to thisconnect bindingsi have a noneangular application which is loading a component that uses angularjs to do databinding at some point i want to destroy the component and want to be sure that there are no memory leaks how do i tell angular to remove all event listeners from that part of the domwould noderemove do the trick or does angular do other things in memory that need to be cleaned up any other tips on avoiding memleaks in angular would be appreciated,['javascript'] +390616,file separators of path name of zipentry zip entries store the full path name of the entry because i am sure of the next part the zip archive is not organized as directories the metadata contains the info about how files are supposed to be stored inside directoriesif i create a zip file in windows when i unzip the data in another os eg mac os x the file structure remains as it used to be in windows is this because the unzipper is designed to handle this or isit because the file separators inside the zip are standardi am asking this because i am trying to find an entry inside a zip file using the name of the zipped file but which file separator should i use to make it work in systems other than windowsi am using java and the method getname of the zipentry gives me the path using the windows file separator would it be enough if i use the java fileseparator separator to make it work on another os or will i have to try to find my file with each possible separator,['java'] +390617,python 33 mysql connector possible duplicatemysqldb lib for python 30 i use python33 and cannot connect to mysql because i do not find module for mysql connectorhow do i connect to mysql with python33,['python'] +390699,convert json to csv using python idle i have a json file of latitudelongitude that i want to covert to a csv file i want to do this using python i have readtried all other stackoverflow and google search results suggestions i have managed to get as far as creating the csv and including headers but beyond that goofy stuff starts to happen here is the working part of my code so farimport json csvx longitude73689070latitude407180 longitude73688400latitude40715990 longitude73688340latitude40715790 longitude73688370latitude40715500 longitude73688490latitude40715030 longitude736810latitude40714370 longitude73688980latitude40714080 longitude73689350latitude40713390 longitude73689530latitude40712800 longitude73689740latitude40712050 longitude73689820latitude40711810 longitude73689930latitude40711380 longitude73690110latitude40710710x jsonloadsxf csvwriteropentestcsv wbfwriterowlongitude latitudeand heres where it falls apart s mean i am not sure what to put there i have tried all sorts of combinations of things that i have found in my search for answersfor in fwriterowi got the above from answers to this question by little fish i can see that our json examples are slightly different and i am assuming that has something to do with why i cannot get it to work any help would be greatly appreciated and i am happy to provide clarification if need be fyi i am new to python so if youre going to use jargon please explain it as clearly as possible thanks ps not sure if it matters but i am using idle,['python'] +390700,replace layout on orientation change my app has a webview and some buttons inside a linerlayoutthe problem is i want the buttons to be on bottom in portrait mode and on left in landscape mode while the webview maintains it is state two different layout does not work as it force recreation of the activity that refresh the webview for now i use androidconfigchangesorientation in activity tag so webview does not get refreshed on orientation changeis there anyway to replace the layout of buttons on the change of screen modeportrait modelandscape mode,['android'] +390711,ruby if elsif else on a single line with the ruby ternary operator we can write the following logic for a simple if else constructa true a b abut what if i wanted to write this as if foo a elsif bar b else ci could write it as the following but it is a little difficult to followfoo truea foo a bar b c afoo falsebar truea foo a bar b c bare there any better options for handling such a scenario or is this our best bet if we wish to condense ifelsifelse logic into a single line,['ruby'] +390798,c faster way to do string addition i am finding standard string addition to be very slow so i am looking for some tipshacks that can speed up some code i havemy code is basically structured as followsinline void add to stringstring data string added data ifadded datalength1 added data added data added data added datadataint main int some int 100 float some float 10 string some string test string added data added datareserve1064 forint ii0ii10ii variables manipulated here some int ii some float ii some stringassignii20a then we concatenate the strings stringstream fragment fragmentsome int some floatsome string add to stringfragmentstradded data returndoing some basic profiling i am finding that a ton of time is being used in the for loop are there some things i can do that will significantly speed this up will it help to use c strings instead of c strings,['c++'] +390815,cmake does not honour d cmake cxx compilerg i am trying to force cmake to build my cpp code with g as by default it uses clang instead so i use cmake d cmake cxx compilerg srccmakeliststxt after which cmake checks for gcc and g with success but nonetheless make verbose1 yieldsusrbinc o cmakefilestrial cppdirtrialcppo c userskubacodesketchpadtrial projectsrctrialcpplinking cxx executable trial cppoptetlocalbincmake e cmake link script cmakefilestrial cppdirlinktxt verbose1usrbinc wlsearch paths first wlheaderpad max install names cmakefilestrial cppdirtrialcppo o trial cpp as it calls usrbinc not usrbing i concur it still uses clang any idea whats the problem i know i have g and it is in usrbini am running mac os x 1082,['c++'] +390819,pure css solution square elements if i have a div with a relative width such as width 50 is there a simple way to make it have the same width as it does height without resorting to javascript,['css'] +390835,caching an image and uicollectionview i am pretty new to objectivec so hopefully this all makes sense i have downloaded images from a server and have thisplayed them in an image view in the collectionview cellforitematindexpath method the issue i am facing is that the images do not appear to be caching it looks like each time a cell is being reused the associated image from the server is being redownloaded in my viewdidload method i am creating a nsmutabledictionaryimagedictionary nsmutabledictionary allocinitwithcapacity500from reading the documentation and looking at answers to similar questions i thought that this plus the following code would be enough i have been at this for a couple of days and i know there is something i am missing or a concept i am not grasping pragma mark uicollectionview data source nsintegercollectionviewuicollectionview view numberofitemsinsectionnsintegersection nslogbegin retrieving photos return selfphotos countnsintegernumberofsectionsincollectionviewuicollectionview collectionview return 1 uicollectionviewcell collectionviewuicollectionview collectionview cellforitematindexpathnsindexpath indexpath collectionviewcell cell collectionview dequeuereusablecellwithreuseidentifiermy cell forindexpathindexpath cellimageviewimage nil if cellimageviewimage nil thispatch queue t downloadqueue thispatch queue createimage downloader null thispatch asyncdownloadqueue nsdata data nsdata datawithcontentsofurlnsurl urlwithstringselfphotos objectatindexindexpathrow objectforkeyfullimage uiimage image uiimage imagewithdatadata imagedictionary setobjectimage forkeyimage thispatch asyncthispatch get main queue cellimageviewimage imagedictionary objectforkeyimage cell setneedsthisplay return cellany help would be greatly appreciated thanks in advance,['ios'] +390883,pivot table with group by select outaoutb from outpivot countevent for date in montues as event countgroup by outaoutbwhile executing this query i am getting the following errorthe multipart identifier outaoutb could not be bound,['sql'] +390934,suppress javac warning is internal proprietary api and may be removed in a future release when i compile the spring jdbc source on os x with jdk 170 i get this warningwarning cachedrowsetimpl is internal proprietary api and may be removed in a future releasehow do i suppress the warning message during a compilei already know and use javas suppresswarning annotations i am looking for the specific use of this to suppress the warning i have describedmy question specifically is in this line of codesuppresswarningsvaluegoesherewhat should valuegoeshere be replaced withedit people i know that it is best to avoid the code that leads to the warning and usually that would be my approach however i am compiling thirdparty code here which i do not want to rewrite i just want to add the correct annotation to suppress the warning so that warnings i can actually do something about do not get buried,['java'] +390945,what is the difference between difftime and i have 2 variables of type time t varend and varstartnow in order to see the difference between themeither i can do varend varstart or difftimevarend varstartand both returns number of secondsplease let me know if they have any difference or which is the recommended one,['c'] +390950,usage of forcelayout requestlayout and invalidate i am a bit confused about the roles of forcelayout requestlayout and invalidate methods of the view classwhen shall they be called,['android'] +390974,can i link a plain file into my executable some frameworks qt windows gtk offer functionality to add resources to your binaries i wonder if it would be possible to achieve this without the framework since all that is really needed isa symbol to contain the resources address within the binary data segmenta symbol to represent the length of the resourcethe resource itselfhow can this be achieved with the gcc toolchain,"['c++', 'c']" +390983,how should i set up my integration tests to use a test database with entity framework i am writing integration tests for an application and have not been able to find any best practices on how to set up a test database for my integration suite i am working on an aspnet mvc4 application using entity framework codefirsti can confirm that the tests in my test project talk to the local development database on my machine by default this is not ideal as i want to have a fresh database every time i run the testshow can i set up my test project so that my tests talk to a separate instance i am assuming that it is possible to set up an sql server compact edition instance but i am not sure how to configure this,['c#'] +390999,inner shadow on circle android canvas i need to make inner shadow and gradient on circle which i draw in ondraw method of my view see this sorry because of i am new to stackoverflow i cannot post images yeti figure out how to get gradient working but i cannot get inner shadow doneall i have found so far is this post but it seems a bit complicated and not exactly what i needi have tried using setshadowlayer but it i probably cannot get it working right because besides inner shadow i get outer shadow too and this is not what i needany help would be appreciatedthanks,['android'] +391008,how to navigate to pasted stack trace visualstudio i remember i used to navigate to pasted stack trace by clickingctrl e tis it a resharper utility whats the build in equivalent for visual studio 2012,"['c#', '.net']" +391091,show data in aspnet html table i am writing an aspnet page which reads data from a database and needs to show it in a table for some reason i do not want to use the gridview how do i show the data in a table on the html pagethis is my c code sqlconnection thisconnection new sqlconnectiondbconnection sqlcommand thiscommand thisconnectioncreatecommand thiscommandcommandtext select from test thisconnectionopen sqldatareader reader thiscommandexecutereader while readerread int id readergetint320 string name readergetstring1 string pass readergetstring2 thisconnectionclosethis is my aspx page page languagec autoeventwireuptrue masterpagefiletestmaster codefiletestaspxcs inheritstest aspcontent idbodycontent runatserver contentplaceholderidcontentplaceholder table width100 aligncenter cellpadding2 cellspacing2 border0 bgcoloreaeaea tr alignleft stylebackgroundcolor004080colorwhite td id td td name td tdpasstd tr need the while output into here tableaspcontent,"['c#', 'asp.net', 'html']" +391103,animate imageview width without scaling i am trying to animate an imageview so it is slowly shown from left to right when i asked this before i was having trouble to explain what i wanted so this time i created the desired effect using html jswhat would be the best way to get this effect in androidi tried changing the scaletype and then applying a scaleanimation directly to that imageviewlayoutimageview androidididgraphimage androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentlefttrue androidlayout alignparenttoptrue androidscaletypecentercrop androidbackgroundandroidcolortransparent androidcontentdescriptionstringstroom grafiek javascale new scaleanimationfloat0 float1 float1 float1 animationrelative to self float0 animationrelative to self float1scalesetduration10graphimagestartanimationscalebut this stil scales the imagei also tried wrapping the imageview in a framelayout hoping i could just animate the framelayoutframelayout androidlayout width70dp androidlayout heightfill parent androidclipchildrentrue imageview androidlayout widthwrap content androidlayout heightwrap content androidlayout gravitybottomleftclip horizontal framelayoutthis will still try to scale my imageview to fit inside the framelayout,['android'] +391117,how to upload file with phonegap and jquerymobile i am building a mobile app for android with jqm and phonegapi need to upload a file image to remote server from galery or take a picture with camerabasically it can be done using phonegap file api the problem is that the server was written to support simple post submissionwhat i need is to simulate in my app request exact as it would sent from the following html formin addition i need to get the server responseform namemywebform enctypemultipartformdata action methodpost input typefile nameimage input typesubmit valuesubmit formi tried to use phonegap file api but the structure of the retrieved data on the server side is different than it should bei tried to implement that form in my app but the choose file button was thisabledhow it can be achieved without making any changes on the server side,['jquery'] +391180,how write several using instructions possible duplicateusing statement with multiple variables i have several thisposable object to manage the ca20 rule ask me to thispose all my object before exiting the scope i do not like to use the thispose method if i can use the using clause in my specific method i should write many using in usingusing person person new person using adress address new address my code is it possible to write this on another way likeusing person person new person adress address new address,"['c#', '.net']" +391217,android how to circular zoommagnify part of image i am trying to allow the user to touch the image and then basically a cirular magnifier will show that will allow the user to better select a certain area on the image when the user releases the touch the magnified portion will thissapear this is used on several photo editing apps and i am trying to implement my own version of it the code i have below does magnify a circular portion of the imageview but does not delete or clear the zoom once i release my finger i currently set a bitmap to a canvas using canvas new canvasbitmap and then set the imageview using takenphotosetimagebitmapbitmap i am not sure if i am going about it the right way the ontouch code is belowzoompos new pointf00 takenphotosetontouchlistenernew ontouchlistener override public boolean ontouchview v motionevent event int action eventgetaction switch action case motioneventaction down zoomposx eventgetx zoomposy eventgety matrixreset matrixpostscale2f 2f zoomposx zoomposy shadersetlocalmatrixmatrix canvasdrawcirclezoomposx zoomposy 20 shaderpaint takenphotoinvalidate break case motioneventaction move zoomposx eventgetx zoomposy eventgety matrixreset matrixpostscale2f 2f zoomposx zoomposy canvasdrawcirclezoomposx zoomposy 20 shaderpaint takenphotoinvalidate break case motioneventaction up clear zoom here break case motioneventaction cancel break default break return true,['android'] +391219,exporting stl class from dll why is there no warning from the return type my question is related to exporting a c class with stl inside for exampleclass declspecdllexport hello stdstring namepublic stdstring getname void setnameconst stdstring namevarious articles seems to indicate that this is very bad which is quite understandable everything must be compiled with the same compiler settings and crt version otherwise everything will crash and burnquestionwhat i do not understand is why only data members seem to have an issue with the below code i get c4251 needsto have dllinterface to be used by clients of class which is apparently fixed by exporting the instantiated stdstringstruct declspecdllexport someclass removes the warning template class declspecdllexport stdstring stdstring name compiler balks at thisand the fixed version is export the instantiations of allocator and basic stringtemplate class declspecdllexport stdallocatorchartemplate class declspecdllexport stdbasic stringchar stdchar traitschar stdallocatorchar struct declspecdllexport someclass stdstring name no more balkingthis will give lnk2005 basic string already defined when you try to use the dll meaning you have to not link in the crt on the client so it ends up using the instantiation in the dllreturn types and arguments seem to have no problem with the stl and do not receive the same treatment data members get from the compiler no exporting requiredstruct declspecdllexport someotherclass stdstring dosomething1 no problemo void dosomething2const stdstring s no problemoadditional info question is abovein bothclass a stdstring foo return stdstring stdstring foo gives the same result stdstring foo also gives the same resultclass b stdstring aneither seem to export stdbasic string or stdallocator rather they only export the membersfunctions of the classhowever the fixed version mentioned in the question exports both basic string and allocator,['c++'] +391228,ruby cucumber how to execute cucumber in code i would like to execute cucumber features from within ruby codetypically the cucumber binary installed with the gem is executed on the command line with one or more features specifiedhowever i would like to define logic that creates a dynamic feature execution flow in other words the program can work out which features should be executedis it possible to instantiate cucumber with specified feature files from ruby code as opposed to the command line,['ruby'] +391231,ambiguous function calls to c base classes i am trying to create a variadic templated class which provides a method for each class in the typelist an example is shown below which creates a print method for every class in the typelistinclude iostreaminclude string helper class providing a function calltemplate typename tclass printhelperpublic void printconst t t stdcout t stdendl provides a print method for each type listedtemplate typename tsclass printer public printhelpertsint main printerint stdstring p pprintstdstringhello world ambiguous callthe commented line results in an error from gcc 463 on the commented line what is the correct way to resolve the ambiguity or should i be looking at a different design,['c++'] +391240,java compiler string optimization it seems reasonable to me that the compiler is going to take something like thisloginfoa really long logger message that is kind of a pain in the tucous and violates formatting standards by making the line to longand compile the two strings into one i am pretty sure this is true but i would liketo have my ducks in a row if anyone brings it up,['java'] +391249,to fragment or not to fragment as i have started to adopt fragments more and better but also as fragments functionality is increased fragments in fragments mapfragments i am starting to reach a point where i need to define when i should make a new viewaction as a fragment or as an activity an activity is defined as an activity is a single focused thing that the user can dobut a fragments have kinda taken that definition instead as described in the docs for example a news application can use one fragment to show a list of articles on the left and another fragment to thisplay an article on the rightaboth fragments appear in one activitythis is two things the user can do in one activity with two fragmentsso i would like some inputhelp to figure out what is the best approach to decide if i should make a new actionview as a fragment or as an activity,['android'] +391280,mfmailcomposeviewcontrollers cancel button action sheet possibly freezes the view i have seen several questions before such as this but for the lack of an accepted answer as well as having implemented everything as needed i still continue to face the issue as followsi thisplay the mail composer but on clicking cancel the composer view freezes i think this is due to the savedelete draft action sheet showing up out of the visible frame yes i have set the mailcomposedelegate to the presenting view controller and have read up on several similar questions where users have not handled the voidmailcomposecontrollermfmailcomposeviewcontrollercontroller didfinishwithresultmfmailcomposeresultresult errornserrorerror delegate to thismiss the composer on cancel i have handled that as well but i cant seem to figure out for the life of me why the action sheet wont show up in the visible area of the screen in the iphone version of my universal app the view frame of the viewcontroller modally presenting the mail composer as nslogged is 00320480 my app is universal the mail composer works perfectly on the ipad below is a screenshot of how the composer view looks running on iphone simulator 51 heres the code to thisplay the composeribactionmailbuttonpressedidsender mfmailcomposeviewcontroller controller mfmailcomposeviewcontroller alloc init controllermailcomposedelegate self controller setsubjectsubject controller setmessagebodytest ishtmlyes controller settorecipientsnil ifcontroller self presentmodalviewcontrollercontroller animatedyes controller release voidmailcomposecontrollermfmailcomposeviewcontrollercontroller didfinishwithresultmfmailcomposeresultresult errornserrorerror self thismissmodalviewcontrolleranimatedyes,"['iphone', 'ios']" +391287,can i shorten this regular expression using intersection i have this language l that contains only one stringwritten more concisely this string has 22na1 characters and i want to reduce iti was thinking of using intersection if i can find some regular languages in which the intersection of their regular expressions will yield this stringi have here the recursive function in case that would helpfunction recursiveregexcharset ifcharsetlength 0 return else var char charsetsplicecharsetlength 1 1 var returnval recursiveregexcharset return returnvalconcatreturnval char consolelogrecursiveregexa1 a2 a3 a4,['javascript'] +391352,rules for lookup of operators in c11 n37 working draft standard for programming language c gives the following example in clause 13312 p 10struct a void operator a astruct b void operator b void f a avoid bf operator aa error global operator hidden by member a a ok calls global operatorhowever this is just a notenote the lookup rules for operators in expressions are different than the lookup rules for operator function names in a function call as shown in the following examplemy question is where in the standard does it say that this is what has to happen as opposed to just having the note with an exampleas far as i can tell according to clause 13312 p 2 operator expressions are converted to operator function calls so why and how should there be a difference in the example aboveeditafter looking into the problem i think that i may have overlooked p 3 and p6 in the same clause that together state that global candidates and member candidates are considered equally when looking up operators thus lookup rules are different as the note says however my inquiry into this subject was stemmed by this example that compiles in the same way with gcc 48 and clangstruct x struct y void operatorx x void operatorx y void test void operatorx x x x y y x x ok x y ok operatorx y error operatorx x okwhy is there shadowing by the block scope declaration when the operator function is called directly but not when it is called by operator expressionhere are the errors from gccoperatorsmainsscpp in function avoid testaoperatorsmainsscpp1317 error could not convert aya from aya to axa operatorx y error and here from clangoperatorsmainsscpp1316 error no viable conversion from y to x operatorx y error operatorsmainsscpp18 note candidate constructor the implicit copy constructor not viable no known conversion from y to const x for 1st argumentstruct x struct y operatorsmainsscpp722 note passing argument to parameter here void operatorx x are the compilers correct to have the block declaration shadow the global name in one case but not the other,['c++'] +391397,why css transform rotate make text ugly some browser for me firefox chrome on xp do not seem to apply antialiasing on text with css rotationexemple why they apply on images but not text,['css'] +391439,setting environment variables in c that persist after execution is complete i need to setup an environment variable from a c program so batch files that run later can use this newly created variable i have tried usingenvironmentsetenvironmentvariableusrnam my name environmentvariabletargetprocessafter this statement i have a breakpoint setup and when it gets to this breakpoint i go to a command prompt issue the following commandcuserslenovoset usrnami getenvironment variable usrnam not definedhow can i set an environment variable that persists after the c program execution has completedsuggestions are very much appreciated,['c#'] +391512,mysql foreign key constraints that exceed max depth i have mysql server 5162 installed on production server i am monitoring mysql servers error log file every day and suddenly i found below error in my error log file innodb cannot deleteupdate rows with cascading foreign key constraints that exceed max depth of 250 please drop excessive foreign constraints and try againi have a database structure with primary key foreign key relationships with proper updatedelete actions and i need to delete data of child tables if the data in parent table deleted by application or manually backend i had googled this issue but i cannot find proper solution how can i resolve this issue,['mysql'] +391533,access parents overriden method from parents context in php i have a drawing php class called classa that is extended by many other drawing classes classb for instancei need the inherited classes to fire its parent classes draw method however in my particular situation i do not want to call such method directly eg parentdraw i would like a third function eg parentinvokedraw to call my drawing method from within the parents contextheres some code to illustrateclass classa function draw drawing code function invokedraw thisdraw class classb extends classa function draw parentinvokedraw drawing code the problem i am facing is that invokedraw will not call the parents draw method but rather the extended class own draw method thus causing an infinite loopalthough the issue is fairly logical i am having a hard time figuring out a workaround on that how to accomplish this taskdesired effectinfinite loop problem,['php'] +391548,why is the gcc math library so inefficient when i was porting some fortran code to c it surprised me that the most of the execution time thiscrepancy between the fortran program compiled with ifort intel fortran compiler and the c program compiled with gcc comes from the evaluations of trigonometric functions sin cos it surprised me because i used to believe what this answer explains that functions like sine and cosine are implemented in microcode inside microprocessorsin order to spot the problem more explicitly i made a small test program in fortranprogram ftest implicit none real8 x integer i x 0d0 do i 1 10 x cos 2d0 x end do write xend program fteston intel q6600 processor and 3691arch x86 64 linuxi get with ifort version 1210 ifort o ftest ftestf90 time ftest 0211417093282753 real 0m0280suser 0m0273ssys 0m03swhile with gcc version 472 i get gfortran o ftest ftestf90 time ftest 016184945593939115 real 0m2148suser 0m2090ssys 0m03sthis is almost a factor of 10 difference can i still believe that the gcc implementation of cos is a wrapper around the microprocessor implementation in a similar way as this is probably done in the intel implementation if this is true where is the bottle neckeditaccording to comments enabled optimizations should improve the performance my opinion was that optimizations do not affect the library functions which does not mean that i do not use them in nontrivial programs however here are two additional benchmarks now on my home computer intel core2 gfortran o ftest ftestf90 time ftest 016184945593939115 real 0m2993suser 0m2986ssys 0m0sand gfortran ofast marchnative o ftest ftestf90 time ftest 016184945593939115 real 0m2967suser 0m2960ssys 0m03swhich particular optimizations did you commentators have in mind and how can compiler exploit a multicore processor in this particular example where each iteration depends on the result of the previous oneedit 2the benchmark tests of daniel fisher and ilmari karonen made me think that the problem might be related to the particular version of gcc 472 and maybe to a particular build of it arch x86 64 linux that i am using on my computers so i repeated the test on the intel core i7 box with debian x86 64 linux gcc version 445 and ifort version 1210 gfortran o3 o ftest ftestf90 time ftest 016184945593939115 real 0m0272suser 0m0268ssys 0m04sand ifort o3 o ftest ftestf90 time ftest 0211417093282753 real 0m0178suser 0m0176ssys 0m04sfor me this is a very much acceptable performance difference which would never make me ask this question it seems that i will have to ask on arch linux forums about this issuehowever the explanation of the whole story is still very welcome,['c'] +391615,simulate ipad using cordovaphonegap emulator command i would like to use the included emulator command with cordovaphonegap to run my app in the ipad simulator from the command linethe basic instructions are here commandline indexmdhtmli have installed the ios simulator from herethe documentation says it supports simulating an ipad from the command line however it opens by default to iphone and changing the device to ipad closes the app and it is not installed on the home screen i have searched but cannot find documentation to launch to simulate an ipadhow do i run the cordova emulator command to open to ipad,['ios'] +391666,rails modelvalid flusing custom errors and falsely returning true i am trying to add a custom error to an instance of my user model but when i call valid it is wiping the custom errors and returning true99 prymain uemail 100 prymain ustatus 101 prymain uvalidtrue102 prymain uerrorsaddstatus must be yes or no 0 must be yes or no103 prymain uerrorsactivemodelerrorsmessagesstatusmust be yes or no104 prymain uvalidtrue105 prymain uerrorsactivemodelerrorsmessagesif i use the validate method from within the model then it works but this specific validation is being added from within a different method which requires params to be passeduserdef do something witharg1 arg2 errorsaddfield etc if arg1 arg2endbecause of the above uservalid is returning true even when that error is added to the instance,['ruby-on-rails'] +391674,event handlers closures and garbage collection in javascript i am not running into a memory leak in my application yet but i am worried about possible problems in the future i would like to know if doing something like thissomeclassprototypesomemethod function var that this thisdiv2clickfunction thatsomemethod2 and lets say that thisdiv2 is appended to another div thisdiv1 if i callthisdiv1removeand later loses the reference of my someclass instance does the someclass instance gets garbage collected and what about the html element thisdiv2 thisdiv2 would not be inside the dom because it is appended to thisdiv1i ask this because the event handler in thisdiv2 might keep a reference to the html element thisdiv2 and also keeps a reference to the instance of someclass through the closure because of the variable thatso should i care about properly removing all events and html elements like this or simply removing the root element thisdiv1 solves the problem,"['javascript', 'jquery']" +391775,retrieve an arbitrary number of random rows from each group by category in mysql i have a table in mysql that contains a column name categoryi am trying to write a query that will return 2 random records from each categoryhere is code that i use to get 2 records from each category with the highest values in my rating columnselect e1 from entries as e1 where select count from entries as e2 where e2category e1category and e1rating e2rating 2 order by category rating desc check this link out to see a table with some sample data and the above query9bab8e1,['mysql'] +391786,does greasemonkey allow loading local javascript via require i have tried to include some local javascript in the same folder as the gm script and in both cases the script fails to load and the scripts seems to stop working until i restart the browser even if the line with the require is removedi tried both require filescriptjsthen require filefullpathtoscriptjsand both options do not workis loading local javascript banned in greasemonkey or does it require some extra settings to enable it,['javascript'] +391810,how use height 100 with ie8 i am trying to use css property height 100 in order for a div taking all available space in the browser i can make it work with chrome and firefox but not with ie8 actually i understand that in ie8 height 100 means 100 of the size of the immediate parent unlike in firefox or chrome where it means 100 of the available space i came up with this sample html body margin 0 padding 0 bottom0px height100grid thisplay table width100tablerow thisplay tablerowtablecell thisplay tablecellgrow bottom0px height100 div classgrid grow div classtablerow div classtablecell abr abr abr abr abr abr abr abr abr abr abr abr abr abr abr abr abr abr div div div classtablerow grow div classtablecell grow styleborder solid 3px abr abr abr abr abr abr abr abr abr div div div you can see that running it with ie8 the second row is much bigger is there any workaround without using fixed height i would like to keep the same behavior of the div taking all the available space if there is no solution to make it works with ie8 what would be the best degraded solution maybe with conditional css for ie8 thank you very much for your help,"['html', 'css']" +391839,every ndk build is a full rebuild possible duplicateprevent ndkbuild from automatically cleaning module android project with an ndk library ndk r8c compiling under cygwin it is an old projecta bunch of c and c files and some a libraries linked via local ldlibssince some time ago i am noticing that every ndk build goes over all source files even if i call the ndkbuild twice in a row there is a full rebuild on second try there is nothing to the effect in the mk files that i can see and the command i invoke to build is a vanilla ndkpathndkbuild there is no b option anywherethe only wrinkle is this on every build ndk says the followingcygdrivecandroidndkr8cbuildcoreaddapplicationmk128 android ndk warningapp platform android9 is larger than androidminsdkversion 3 incygdrivedapathandroidmanifestxmlwhats going on please can i somehow see based on what file dates is make making a decision to rebuild it all,['android'] +391872,passing options to chrome driver selenium i am trying to thisable the output to the console for chrome if i pass the startmaximized option it works fine i may have the wrong commanddesiredcapabilities capabilities desiredcapabilitieschromecapabilitiessetcapabilitychromeswitches arraysaslistsilentchrome new chromedriver chromeservicecapabilitiesi also tried chromeoptions options new chromeoptions optionsaddargumentssilent chrome new chromedriveroptionsoutputstarted chromedriver port26703 version23012400 logbrettworkspacetestngchromedriverlog 1214161331erroripc sync channelcc378 canceling pending sends 1214161331erroripc sync channelcc378 canceling pending sends 1214161331erroripc sync channelcc378 canceling pending sendsblockquote,['java'] +391908,select all text in a readonly when it gains focus i have got a textbox set to readonly and i need its contents to be selected for easy copypaste when it gains focus using the code below it only seems to quickly select the text and then unselect it for some reasonhtmlinput idthing typetext valuesome text readonlyreadonly ajavascriptdocumentgetelementbyidthingonfocus function thisselectafiddle,"['javascript', 'html']" +391912,urlaction with a string array i have an array of strings that i need to pass in a query string of urlaction urlactionindex resource new formatids modelformatidsright now the link is showing up in my browser as systemstring instead of a query string is it possible to have mvc do this automatically with model binding i need it to bind with my controller action likepublic actionresult indexstring formatids,['c#'] +391919,simple form fhidden field works why not finput simple form for foo do f this works fhidden field asdf value something this works finput asdf as hidden input html value something why does not this work exactly finput title as hidden value somethingwhen i look at my log i see that value is coming through as an empty string in the latter input but it is not clear to me why this is happening,['ruby-on-rails'] +392028,how to get all the possible 3 letter permutations possible duplicatelisting all permutations of a stringinteger for examplea aaz aba abz aca acz azz baa baz bba bbz zbasically imagine counting binary but instead of going from 0 to 1 it goes from a to zi have been trying to get this working for a few hours now to no avail and the formula is getting quite complex and i am not sure if there is a simpler way to do itthanks for readingedit i have something like this at the moment but it is not quite there and i am not sure if there is a better wayprivate ienumerablestring getwordsoflengthint length char lettera a letterz z stringbuilder currentletters new stringbuildernew stringlettera length stringbuilder endingletters new stringbuildernew stringletterz length int currentindex length 1 while currentletterstostring endingletterstostring yield return currentletterstostring for int i length 1 i 0 i if currentlettersi letterz for int j i j length j currentlettersj lettera if currentlettersi 1 letterz currentlettersi 1 else currentlettersi break,['c#'] +392083,i want to kill a stdthread using its thread object possible duplicatec0x thread interruption i am trying to killstop a c stdthread by using its thread objecthow can we do this,['c++'] +392143,what does the ic launcherwebpng in my project root do unbelievably enough i could not find an answer when googling for this very basic questioni noticed that since i upgraded from eclipse helios to eclipse juno and updated the android sdk eclipse places a file called ic launcherwebpng in the project root whenever i create a new android project the file is the same as the application icon selected in the project creation dialog but what does it do as mentioned it is in the project root not in any of the res folders so is it included in the finished apk file and what is it is purpose,['android'] +392174,how to center a div without width hello i would like to know if it is possible to center a div without having a width because of two different versions of a container depending from language settings with different widths i would like to center it dynamicallymargin 0 autois not working without any settings of widthso the structure is simplediv idcontainer div idlist span classuptext largespan ul classnavigation lioneli lili litwoli lili lithreeli lili lifourli ul divdivand the csswrapper container width 960px clear both margin 0 autowrapper container list width 420pxshould be dynamically margin 0 auto only works when setting widthwrapper container list up fontsize 11px float left thisplay inlineblock textalign right thisplay inlinewrapper navigation fontsize 10px margintop 15px float left paddingleft 5pxwrapper nav li float left thisplay inlineblock marginleft 15px liststyle noneso if there is someone who knows how to deal with that i really would appreciatethanks alotupdate thanks for answering this question for so far usingthisplay inlineblockon that container that should be centered works great,"['css', 'html']" +392176,rand returns the same number each time the program is run in this rather basic c code snippet involving random number generationinclude iostreamusing namespace stdint main cout rand 100 return 0why am i always getting an output of 41 i am trying to get it to output some random number between 0 and 100 maybe i am not understanding something about how the rand function works,['c++'] +392180,htmlagilitypack get all links inside a div i want to be able to get 2 links from inside a divcurrently i can select one but whene there is more it does not seem to workhtmlweb web new htmlweb htmldocument doc webloadurlhtmlnode node docdocumentnodeselectsinglenodedivclassmyclass if node null foreach htmlnode type in nodeselectnodesahref recipetype typeinnertext else recipetype error fetching typetrying to get it from this piece of htmldiv classmyclassh3not relevant headerh3 a hrefthis texta a hrefand this textadivany help is appreciated thanks in advance,"['c#', '.net']" +392184,how to make a python decorator function in flask with arguments for authorization i used a flask snippet for my flasklogin that checks that a user is logged infrom functools import wrapsdef logged inf wrapsf def decorated functionargs kwargs if sessiongetlogged in is not none return fargs kwargs else flashplease log in first error return redirecturl forlogin return decorated functionand i decorate views like soapproutesecrets methodsget postlogged indef secrets error nonei would like to do something similar for authorization too right now i have many views to check that a user owns a resource let us say the hotdogs resourceif the logged in user is the owner of that particular hotdog he can edit and manage his hotdogs if he is not i kick him out to the unauthorized screenapproutehotdogaddmustardmethodsgetlogged indef addmustardhotdog if not authorizeownerhotdog return redirecturl forunauthorized do stuffauthorizeowner takes a hotdog as input and checks that the recorded hotdog owner matches the owner name listed in the session variablei tried making a owns hotdog wrapperdecorator function similar to my logged in one but it complained that it did not accept arguments how can i achieve something similar something likedef owns hotdogf wrapsf def decorated functionargs kwargs if not authorizeownerhotdog return fargs kwargs else flashplease log in first error return redirecturl forlogin return decorated functionfrom the error message decorator seems not to be receiving the hotdog argument that flask views have access to from the variable in the route my hope is for something likeapproutehotdogaddmustardmethodsgetlogged inowns hotdoghotdogdef addmustardhotdog do stuffeverything works with my current authorizeownerhotdog function but it just seems cleaner to have this in place as a wrapper on top of my route rather than as the first line inside the routesome other notesi know that flasksecurity and flaskprincipal can manageauthorization for me unfortunately i am using an unsupporteddatabase backend and am unable to use these extensions so i amforced to do authentication without them if you see any glaring holes in doing authorization this way please let me know,['python'] +392186,cannot use await in portable class library for win 8 and win phone 8 i am attempting to create a portable class library in visual studio 2012 to be used for a windows 8 store app and a windows phone 8 appi am getting the following errorawait requires that the type windowsfoundationiasyncoperation have a suitable getawaiter method are you missing a using directive for systemat this line of codestoragefolder guidesinstallfolder await packagecurrentinstalledlocationgetfolderasyncguidesfoldermy portable class library is targeted at net framework 45 windows phone 8 and net for windows store appsi do not get this error for this line of code in a pure windows phone 8 project and i do not get it in a windows store app either so i do not understand why it would not work in my pclthe getawaiter is an extension method in the class windowsruntimesystemextensions which is in systemruntimewindowsruntimedll using the object browser i can see this dll is available in the net for windows store apps component set and in the windows phone 8 component set but not in the net portable subset i just do not understand why it wouldnt be in the portable subset if it is available in both my targeted platforms,['c#'] +392193,android analogclock setting drawables programmatically i am making an analog clock app which has around 15 designs in one app one way of setting the designs would be to create different widgetconfigsxml for each design but thatll clutter up devices running 40i also thought of setting up an activity which allows changing of the design usingremoteviewssetintridanalogclock1 setdialresource rdrawableclock1but this would not allow the hand drawables to be set what else can i do,"['java', 'android']" +392256,does binding temporary to a reference require a copy constructor in c consider the following codeclass a aconst a public a int main const a a athis code compiles fine with gcc 472 but fails to compile with visual c 2010 with the following errortestcc8 error c2248 aa cannot access private member declared in class a testcc2 see declaration of aa testcc1 see declaration of aso is it necessary to have a copy constructor accessible when binding a temporary to a referencethis is somewhat related to my previous questionis there a way to thisable binding a temporary to a const reference,['c++'] +392259,is java runtime preinstalled on mac osx i need to port a java desktop app for mac osx the app will be launched via jnlp is the java runtime environment preinstalled on macosx,['java'] +392279,gae sdk 174 and invalidcertificateexception recently i upgraded my gae sdk to ver 174 and it started to throw invalidcertificateexception when i try to run development server i searched about this error and some people said it goes away with time but mine did not what should i look into to fix this problem i am using python framework django for my app if that has to matter somehow dev appserverpy info 20121216 074431412 appcfgpy586 checking for updates to the sdktraceback most recent call last file usrlocalbindev appserverpy line 171 in module run file file globals file usrlocalbindev appserverpy line 167 in run file execfilescript path globals file applicationsgoogleappenginelauncherappcontentsresourcesgoogleappenginedefaultbundlecontentsresourcesgoogle appenginegoogleappenginetoolsdev appserver mainpy line 747 in module sysexitmainsysargv file applicationsgoogleappenginelauncherappcontentsresourcesgoogleappenginedefaultbundlecontentsresourcesgoogle appenginegoogleappenginetoolsdev appserver mainpy line 680 in main update checkcheckforupdates file applicationsgoogleappenginelauncherappcontentsresourcesgoogleappenginedefaultbundlecontentsresourcesgoogle appenginegoogleappenginetoolsappcfgpy line 597 in checkforupdates runtimeselfconfigruntime file applicationsgoogleappenginelauncherappcontentsresourcesgoogleappenginedefaultbundlecontentsresourcesgoogle appenginegoogleappenginetoolsappengine rpcpy line 391 in send f selfopeneropenreq file libraryframeworkspythonframeworkversions27libpython27urllib2py line 394 in open response self openreq data file libraryframeworkspythonframeworkversions27libpython27urllib2py line 412 in open open req file libraryframeworkspythonframeworkversions27libpython27urllib2py line 372 in call chain result funcargs file libraryframeworkspythonframeworkversions27libpython27urllib2py line 1207 in https open return selfdo openhttplibhttpsconnection req file applicationsgoogleappenginelauncherappcontentsresourcesgoogleappenginedefaultbundlecontentsresourcesgoogle appenginelibfancy urllibfancy urllib init py line 379 in do open url errorreasonargs1fancy urllibinvalidcertificateexception host appenginegooglecom returned an invalid certificate sslc503 error14090086ssl routinesl3 get server certificatecertificate verify failed to learn more see,['python'] +392300,getting an url which led to error 404 from errorpage controller in spring mvc say i have a spring mvc application with the following webxml entryerrorpage errorcode404errorcode locationerror404locationerrorpageand following errorpage controllerrequestmappingcontrollerpublic class rootcontroller requestmappingerrorerrorid public string errorpagepathvariable integer errorid model model modeladdattributeerroriderrorid return rooterrortile now user requested nonexistent url usershowiamnotauser which triggered error page controller how do i get this nonexistent usershowiamnotauser url from errorpage method of rootcontroller to put it into model and thisplay on error page,['java'] +392316,youtube api orderbyduration not handling the entire playlist just the newest videos i am trying to build a little javascript program to query the youtube api for a given playlist ordered by duration everything works otherwise perfectly but the ordering does not account for the whole playlist just the 25 newest videos on it heres a minimum complete working example as a jsfiddle and heres the javascript part of itvar playlistid uuaunt6odekwe6v1ngqxug jquerygetjson playlistidv2orderbydurationaltjson functiondata eachdatafeedentry functionkey val var title valtitlet var url valcontentsrc var duration valmediagroupytdurationseconds var minutes mathfloorduration 60 var seconds duration 60 if seconds 10 seconds 0seconds var newrow trtr newrowappendtda hrefurltitleatd newrowappendtd classdurminutessecondstd videosappendnewrow i have tried this in both xml and json and i have also tried other kinds of searches besides the playlist search having the api sort just the newest videos of the result seems quite pointless how exactly do i retrieve the longest or shortest videos of a playlist or those uploaded by a given user for that matter,['javascript'] +392325,debugging in android device over wifi without rooting is there any possible way to debug or run android apps from eclipse to my sony tablet s over wifi rather than usb without rooting the device there are ways to do it if the device is rooted however i am seeking the solution in a device that is not rooted,['android'] +392350,is an implementation of stdtuple allowed to fail with triggering a derivedtobase conversion for empty class elements this code does not compile with gcc47struct a void fastruct b bstdtuplea void fbint main fstdmake tupleabecause gcc derives from a to make use of the empty base class optimization however that causes gcc to pick fa and complain error a is an inaccessible base of tupleais this error granted by the c standard or is this simply a bug of libstdc,['c++'] +392373,how can jekyll judge whether it is a page or a post i want to add a class to the body tag using if sentence if the page is a post then add page to the class if the page is a post then add post to it i do not know in specific how to do this can anyone help me figure it out,['html'] +392375,using httpclient class with winrt i have a piece of code which works perfect in net 40code string uri bininet pnrstat cgicgi string parameters uriescapeuristringlccp pnrno18561180607ampsubmitpnrget status systemnethttpwebrequest req httpwebrequestsystemnetwebrequestcreateuri http post headers reqcontenttype applicationxwformurlencoded reqhost windianrailgovin you can use your own useragent requseragent mozilla50 compatible msie 70 windows phone os 75 trident50 iemobile90 dellvenue pro reqheadersaddhttprequestheaderacceptlanguage enusenq05 reqheadersaddhttprequestheaderacceptcharset iso88591utf8q07q07 reqkeepalive true reqreferer stathtml reqaccept textplain reqmethod post byte size calculation before sending request byte bytes systemtextencodingasciigetbytesparameters reqcontentlength byteslength systemiostream os reqgetrequeststream oswritebytes 0 byteslength osclose systemnetwebresponse resp reqgetresponse var request status httpwebresponserespstatusdescription if resp null return systemiostreamreader sr new systemiostreamreaderrespgetresponsestream consolewritelinesrreadtoend consolereadline i just cant seem to figure out what to write in win store apps so far i have got to which class i have to use or may be not httpclient httpclient new httpclienthttpclientdefaultrequestheadersaddhost windianrailgovin but what about the other values there are some header in which we can add some data some are there which need to be added to the collection defaultheaders directlyis there any documentation for usage and description for the sameany help in this direction will be great,['c#'] +392389,ob flush takes long time to be executed in my websiterunning with drupal the ob flush function takes a long timebetween 10 100 secs to be executed how do i find out why what can cause this so long time,['php'] +392391,a big bug of vc why does initializerlist not valueinitialize a struct the c11 standard 8543 says if the initializer list has no elements and t is a class type with a default constructor the object is valueinitializedstruct a int get return i private int iint main a a int and aget cout and endl and is a random number rather than 0 return 0is this a bug of vc my vc is the latest nov 2012 ctp,['c++'] +392428,is it wise to ignore gclangs wmissingbraces warning consider the following programinclude arrayint main stdarrayint 1 x 0 warning x 0 no warning return 0the first initialization leads to warnings on gcc 472maincpp522 warning unused variable axa wunusedvariable and clang 31maincpp528 warning suggest braces around initialization of subobject wmissingbraces stdarrayint 1 x 0 as far as the standard goes there should be no difference between double or single curly braces at least in this examplethere are two ways to deal with the warningjust turn it ofix the code so the compiler is happywhat do you propose imho the double curly expression looks somewhat ugly on the other hand the warning might detect real problems in more complicated examples do you know an example where the warning would have helped you,['c++'] +392460,creating and using a csv file with uiactivityviewcontroller so i am creating a csv file and then allowing the user to share it using the uiactivityviewcontrollermy code to create the csv file will return the nsurl of the file nsurl exporttocsv nsstring docpath nssearchpathfordirectoriesindomainsnsdocumentdirectory nsuserdomainmask yesobjectatindex0 nsstring filepath docpath stringbyappendingpathcomponentresultscsv if nsfilemanager defaultmanager fileexistsatpathdocpath nsfilemanager defaultmanager createfileatpathfilepath contentsnil attributesnil nsmutablestring contents nsmutablestring stringwithcapacity0 fill contents with data in csv format nsfilehandle filehandle nsfilehandle filehandleforupdatingatpathfilepath filehandle writedatacontents datausingencodingnsutf8stringencoding filehandle closefile return nsurl fileurlwithpathfilepathand then my activity uses that nsurl to initiate the uiactivityviewcontroller ibactionsharebuttonpressedidsender nsarray activityitems resultscsv selfobject exporttocsv uiactivityviewcontroller sharescreen uiactivityviewcontroller alloc initwithactivityitemsactivityitems applicationactivitiesnil self presentviewcontrollersharescreen animatedyes completionnilwhen i select mail an option the csv file is not attached it just has the text resultscsvwhat am i doing wrong,['ios'] +392471,problems with androidlocationgeocoder i know there has been a lot of questions on the site about the ioexeption service not availablei have checked all the answers i could find on the subject i am running it as async task which seems to be working fine but still getting the same exception i have used ispresent on previous attempts although it is not in the following code and i am using the same phone i have the internet permission i have tried to change target to google api to see if that was the problem but it made no differencethis is a vital part of a forth year project so any help would be serious ps never worked with java or android before very recently so forgive any rookie looking coding tyoverrideprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain view1 textview findviewbyidridtextview1 view2 textviewfindviewbyidridtextview2 view3 textviewfindviewbyidridtextview4 b1 button findviewbyidridbutton1 locationmanager locationmanager thisgetsystemservicecontextlocation service provider locationmanagergetproviderlocationmanagergps provider final locationlistener listener new locationlistener override public void onlocationchangedlocation location view2settextdoubletostringlocationgetlatitude view3settextdoubletostringlocationgetlongitude double lat doublevalueoflocationgetlatitude double longtemp doublevalueoflocationgetlatitude new geoexecutelatlongtemp override public void onproviderthisabledstring provider todo autogenerated method stub override public void onproviderenabledstring provider todo autogenerated method stub override public void onstatuschangedstring provider int status bundle extras todo autogenerated method stub b1setonclicklistenernew viewonclicklistener override public void onclickview v todo autogenerated method stub locreqest private void locreqest locationmanagerrequestlocationupdateslocationmanagergps provider 10 0 listener class geo extends asynctaskdouble void string geocoder geocoder new geocodergetapplicationcontext localegetdefault override protected string doinbackgrounddouble params address address null listaddress addresses null try call the synchronous getfromlocation method by passing in the latlong values addresses geocodergetfromlocationparams0doublevalueparams1doublevalue 1 address addressesget0 if address null return got your address addressgetcountrynametostring catch ioexception e eprintstacktrace return failed returnfail override protected void onpostexecutestring result todo autogenerated method stub superonpostexecuteresult view1settextresult toastmaketextgetapplicationcontext the address is result toastlength longshow heres the logcat1216 230653855 wsystemerr23578 javaioioexception service not available1216 230653865 wsystemerr23578 at androidlocationgeocodergetfromlocationgeocoderjava1361216 230653865 wsystemerr23578 at comboggertechlocalmaingeodoinbackgroundmainjava1021216 230653880 wsystemerr23578 at comboggertechlocalmaingeodoinbackgroundmainjava11216 230653900 wsystemerr23578 at androidosasynctask2callasynctaskjava2641216 230653900 wsystemerr23578 at javautilconcurrentfuturetasksyncinnerrunfuturetaskjava3051216 230653905 wsystemerr23578 at javautilconcurrentfuturetaskrunfuturetaskjava1371216 230653915 wsystemerr23578 at androidosasynctaskserialexecutor1runasynctaskjava2081216 230653915 wsystemerr23578 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava10761216 230653915 wsystemerr23578 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava5691216 230653920 wsystemerr23578 at javalangthreadrunthreadjava8561216 230710440 wsystemerr23578 javaioioexception service not available,['android'] +392527,xdebug for remote server not connecting netbeans i am trying to use xdebug in the following scenariomy computer windows 7 netbeans 69physical host at computer on the same network windows 7 with virtual boxvirtual centos 62 with apache server 2215 and php 533the php code of my website is on a shared folder on centos in varwhtmlmysite and have separate and can access it by server ip 1921681240edited cwindowssystem32driversetchosts 1921681240 mysitethe php code is accessible from my windows host on hostiphtmlmysite with rw permissionsi created a netbeans project on my computer pointing to hostiphtmlmysite in the project run configuration i have the followingrun as remote web siteproject url httpmysiteindex file indexphp does exist in the projectin the advanced run configurationi checked default i have not touched the proxy settingsi have the following in the phpini on my centos vmextensionxdebugsozend extensionusrlib64phpmodulesxdebugsoxdebugremote enableonxdebugremote logvarlogxdebuglogxdebugremote host192168131xdebugremote connect back1xdebugremote handlerdbgpxdebugremote port90note i tried the configurations with extensionxdebugso and tried commenting xdebugremote connect back1 with uncomment xdebugremote host192168131 which is my computer ip addreso basically i have all the configurations like this imagebut still not working after run the debugger will open this urlhttpmysiteindexphpxdebug session startnetbeansxdebugand nothing will happened just netbeans listing waiting for xdebug connection,['php'] +392562,set android alarm clock programmatically i am trying to build a personal app that will set alarms in the deskclock app i can get it to set alarms for anytime in the current day but how would i go about setting an alarm for the next day or later in the week looking through the alarmclock api in android i do not see a normal way to do this is this even possiblebtw this is my code for setting the alarm it might not be pretty but i am learning as i go package comnetwokzsetit import javautilcalendar import javautilgregoriancalendar import androidappactivity import androidcontentintent import androidosbundle import androidprovideralarmclock import androidviewmenu import androidviewview import androidviewviewonclicklistener import androidwidgetbutton import androidwidgetedittext public class mainactivity extends activity implements onclicklistener button btnsetalarm edittext ethour etminute int minute hour day calendar cal override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain activity btnsetalarm button findviewbyidridbtn set alarm ethour edittext findviewbyidridethour etminute edittext findviewbyidridetminute btnsetalarmsetonclicklistenerthis override public boolean oncreateoptionsmenumenu menu getmenuinflaterinflatermenumain activity menu return true override public void onclickview v switch vgetid case ridbtn set alarm setalarm break private void setalarm cal new gregoriancalendar calsettimeinmillissystemcurrenttimemillis day calgetcalendarday of week hour calgetcalendarhour of day minute calgetcalendarminute intent i new intentalarmclockaction set alarm iputextraalarmclockextra hour hour integerparseintethourgettexttostring iputextraalarmclockextra minutes minute integerparseintetminutegettexttostring iputextraalarmclockextra skip ui true startactivityi,"['java', 'android']" +392574,deconstructing rails joins where methods i have two models banner and bannertypetheir schema looks like thisbanner table name banners id integer not null primary key name string255 image string255 created at datetime not null updated at datetime not null url string255 banner type id integerbannertype table name banner types id integer not null primary key name string255 created at datetime not null updated at datetime not nullbanner belongs to banner type and bannertype has many bannersi have two records in bannertype that are thesebannertypeall bannertype load 03ms select banner types from banner types bannertype id 1 name featured created at 20121217 043524 updated at 20121217 043524 bannertype id 2 name side created at 20121217 043540 updated at 20121217 043540 if i want to do a query to find all the banners of the type featured i can do something like thisbannerjoinsbanner typewherebanner typesname featuredi know that i could also query by the banner type id 1 but that is germane to this particular questionif we break down that statement there are a few things that are a bit confusing to mebannerjoinbanner type would generate nomethoderror undefined method join for class0x007fb6882909f0 why is there no rails method called join when that is the sql method namewhy do i do bannerjoinsbanner type ie the singular banner type when the table name is banner types am i not joining the banner bannertype tables which rails conventions denote as plural if i try bannerjoinsbanner types this is the error that i getbannerjoinsbanner typesactiverecordconfigurationerror association named banner types was not found perhaps you misspelled itwhy does the where clause need banner types and not banner type ie the pluralized version ie the table name and not the symbol used in the joins method it seems it would be more intuitive if you use the table names in both places or use the symbol names in both places if at the very least for consistency purposeswhy cannot i do dynamic finding via associations ie it would be nice if i could do bannerfind by banner type namefeaturedwould love to hear your thoughtsthanks,['ruby-on-rails'] +392589,progress of python requests post i am uploading a large file using the python requests package and i cannot find any way to give data back about the progress of the upload i have seen a number of progress meters for downloading a file but these will not work for a file upload the ideal solution would be some sort of callback method such asdef progresspercent print percentr requestsposturl filesfhugefilehandle callbackprogressthanks in advance for your help,['python'] +392601,can objectivec or objective c handle c exceptions i have a c library for network communication that i need to port for mac previously this library was used on windows c appthe flow of the c network lib is based on exceptions in case of errors instead of returning error code or last errornow since on mac we use objectivecc for apps i need to have ui in objectivecc but the lib used for the core network functionality is the same c lib so my question is will the objective c be able to handle exceptions thrown by c calls if so how if not how do i resolve it or do we write a wrapper around c lib calls and consume exceptions and return error codes please advise how to solve it,"['c++', 'objective-c']" +392622,why is it good save to save sessions in the database i have seen that codeigniter have facility to save session values in databaseit says saving session in database is good security practice but i think saving session in database helps to improve performancethey save only few elements of the session such ascreate table if not exists ci sessions session id varchar40 default 0 not null ip address varchar16 default 0 not null user agent varchar50 not null last activity int10 unsigned default 0 not null user data text not null primary key session idbut if a site use more session variable such as username last logging time etc can i save them in database and use them in the program if yes do i have to add these coloum to same tablei think saving session in database helps only to reduce web serverss memory usage ramand can anybody explain in what sense it does improve security,['php'] +392627,can backbone and express routers work together in an express application i have built several backbone apps and appreciate the clientside code structure and organization i am moving into node development using express and i am uncertain as to how express and backbone can work together in the handling of routes,['javascript'] +392653,a fatal error has been detected by the java runtime environment sigsegv 0xb at pc0x02b2f7e9b2744 pid28778 tid1138739520 i am getting the following error while executing the program and this is not always happening the code contains some complex calculations with a large volume of datacould somebody help to identify the error a fatal error has been detected by the java runtime environment sigsegv 0xb at pc0x02b2f7e9b2744 pid28778 tid1138739520 jre version 70b147 java vm java hotspottm 64bit server vm 210b17 mixed mode linuxamd64 compressed oops problematic frame v libjvmso0x64e744 phaseidealloopclone loopideallooptree node list int node0xe34 failed to write core dump core dumps have been thisabled to enable core dumping try ulimit c unlimited before starting java again if you would like to submit a bug report please visit t h r e a d current thread 0x02ab41980 javathread c2 compilerthread0 daemon thread in native id28799 stack0x043cfc0x043dfd0siginfosi signosigsegv si errno0 si code1 segv maperr si addr0x08registersrax0x0 rbx0x0f2793a0 rcx0x040 rdx0x0rsp0x043df8050 rbp0x043df8170 rsi0x02ab727e610 rdi0x02ab6020d70r8 0x02ab5ff7519 r9 0x040 r100x02ab72266c0 r110x02ab5fe9140r120x02ab4d3f7c0 r130x02 r140x0c5f76d0 r150x043df9bc0rip0x02b2f7e9b2744 eflags0x010202 csgsfs0x033 err0x04 trapno0x0etop of stack sp0x043df80500x043df8050 02ab4d41ea0 043df81200x043df8060 043df8120 0x043df8070 020043df80a0 043df86e00x043df8080 02ab6020d70 02ab419c0200x043df8090 038d443df9bc0 0x043df80a0 0 0x043df80b0 02ab4d40d78 02ab6020d700x043df80c0 02ab4d41638 020ab4801e800x043df80d0 02ab5ff6d18 02ab5ff4aa80x043df80e0 02ab4d40df8 043df9be00x043df80f0 02ab5ff6d20 0100x043df8100 043df9be0 02ab4d416780x043df8110 02d02d 020102c0x043df8120 02ab419c020 02a080x043df8130 02ab5fe9140 02b2f030x043df8140 02ab4ff9448 043df9bc00x043df8150 02ab4d3ffa8 02ab4d3ff400x043df8160 02ab4d3fe70 02ab4ff95800x043df8170 043df8250 02b2f7e996ea50x043df8180 043df9be0 0101c018ba100x043df8190 043df86e0 02ab6020d700x043df81a0 043df9bc0 02ab4ff94f80x043df81b0 02ab4d3f6d8 02ab5ff70b80x043df81c0 0c5fc740 02ab4d3f5200x043df81d0 7f0200 02ab4ff94480x043df81e0 02ab4d3f4e0 03b6020d700x043df81f0 02ab4d3fe30 043df9be00x043df8200 0b77a070 02ab4d3fd480x043df8210 02ab4d3fa38 01b5ff750x043df8220 043df86e0 02ab6020d700x043df8230 02ab4ff9580 043df9bc00x043df8240 043df86e0 01 instructions pc0x02b2f7e9b27440x02b2f7e9b2724 ff ff 66 2e 0f 1f 84 00 00 00 00 00 89 c0 48 8d0x02b2f7e9b2734 34 c5 00 00 00 00 49 03 b7 e0 09 00 00 48 8b 160x02b2f7e9b2744 48 8b 42 08 48 83 38 00 75 2b 41 8b 4f 28 66 0f0x02b2f7e9b2754 1f 44 00 00 8b 42 28 31 d2 39 c8 73 0e 89 c2 49 register to memory mappingrax0x0 is an unknown valuerbx0x0f2793a0 is an unknown valuercx0x040 is an unknown valuerdx0x0 is an unknown valuersp0x043df8050 is pointing into the stack for thread 0x02ab41980rbp0x043df8170 is pointing into the stack for thread 0x02ab41980rsi0x02ab727e610 is an unknown valuerdi0x02ab6020d70 is an unknown valuer8 0x02ab5ff7519 is an unknown valuer9 0x040 is an unknown valuer100x02ab72266c0 is an unknown valuer110x02ab5fe9140 is an unknown valuer120x02ab4d3f7c0 is an unknown valuer130x02 is an unknown valuer140x0c5f76d0 is an unknown valuer150x043df9bc0 is pointing into the stack for thread 0x02ab41980stack 0x043cfc0x043dfd0 sp0x043df8050 free space1008knative frames jcompiled java code jinterpreted vm code cnative codev libjvmso0x64e744 phaseidealloopclone loopideallooptree node list int node0xe34v libjvmso0x632ea5 phaseidealloopdo unrollideallooptree node list bool0x645v libjvmso0x6382c9 ideallooptreeiteration split implphaseidealloop node list0x4b9v libjvmso0x638468 ideallooptreeiteration splitphaseidealloop node list0x148v libjvmso0x638418 ideallooptreeiteration splitphaseidealloop node list0xf8v libjvmso0x638418 ideallooptreeiteration splitphaseidealloop node list0xf8v libjvmso0x638418 ideallooptreeiteration splitphaseidealloop node list0xf8v libjvmso0x638418 ideallooptreeiteration splitphaseidealloop node list0xf8v libjvmso0x638418 ideallooptreeiteration splitphaseidealloop node list0xf8v libjvmso0x638418 ideallooptreeiteration splitphaseidealloop node list0xf8v libjvmso0x645e3c phaseidealloopbuild and optimizebool0x90cv libjvmso0x39c36e compileoptimize0x43ev libjvmso0x39d96c compilecompilecienv c2compiler cimethod int bool bool0xdacv libjvmso0x312042 c2compilercompile methodcienv cimethod int0x142v libjvmso0x3a2cad compilebrokerinvoke compiler on methodcompiletask0x2edv libjvmso0x3a35dd compilebrokercompiler thread loop0x43dv libjvmso0x80d79a javathreadrun0x17av libjvmso0x6f84b0 java startthread0x100current compiletaskc2 768101 3793 fmicommonutilsportfolioevaluatorcalculatemaxdrawdown 6 bytes p r o c e s s java threads current thread 0x0d858800 javathread keepalivetimer daemon thread blocked id3547 stack0x0553360x0558370 0x0c858800 javathread logrotationtimer thread blocked id29237 stack0x049a110x049f120 0x02ab9c97800 javathread thread54 daemon thread in native id29089 stack0x04bd180x04c2190 0x02ab8d6b0 javathread thread51 daemon thread blocked id29052 stack0x04c71a0x04cc1b0 0x0e630 javathread httpthreadpool4435 daemon thread blocked id28901 stack0x04900f0x049510 0x0e62f0 javathread httpthreadpool4434 daemon thread in native id28900 stack0x04ea210x04ef220 0x0e62e800 javathread httpthreadpool4433 daemon thread in java id28899 stack0x049510x049a110 0x0f4610 javathread httpthreadpool4432 daemon thread blocked id28898 stack0x0512290x05172a0 0x0e21b800 javathread httpthreadpool4431 daemon thread in native id28897 stack0x053f320x0544330 0x02ac1de5800 javathread pool7thread1 thread blocked id28892 stack0x054e350x0553360 0x02ab98f20 javathread scr component actor daemon thread blocked id28890 stack0x04f9240x04fe250 0x02ab9d72800 javathread fileinstallvarglassfishdomainsdomain1autodeploybundles daemon thread blocked id289 stack0x0544330x0549340 0x02ab5d66800 javathread rmi renewclean1270018686 daemon thread blocked id287 stack0x053a310x053f320 0x02ab9220 javathread configuration updater daemon thread blocked id286 stack0x053530x053a310 0x02ab9ed3800 javathread rmi scheduler0 daemon thread blocked id285 stack0x05302f0x053530 0x02ab8d740 javathread httpthreadpool805 daemon thread blocked id284 stack0x052b2e0x05302f0 0x02aba5d9800 javathread httpthreadpool804 daemon thread blocked id283 stack0x05262d0x052b2e0 0x02aba5d8800 javathread httpthreadpool803 daemon thread blocked id282 stack0x05212c0x05262d0 0x02ab94970 javathread httpthreadpool802 daemon thread blocked id281 stack0x051c2b0x05212c0 0x02ab94960 javathread httpthreadpool801 daemon thread blocked id280 stack0x05172a0x051c2b0 0x02ab8976800 javathread gc daemon daemon thread blocked id28878 stack0x050d280x0512290 0x02ab8e750 javathread rmi reaper thread blocked id28877 stack0x0508270x050d280 0x0ec1b0 javathread rmi tcp accept8686 daemon thread in native id28876 stack0x0503260x0508270 0x0b4e8800 javathread destroyjavavm thread blocked id28782 stack0x0402e50x0407e60 0x0ee68800 javathread glassfish kernel main thread thread blocked id28875 stack0x04fe250x0503260 0x02ac1dc80 javathread autodeployer daemon thread blocked id28873 stack0x04f4230x04f9240 0x02ac1104800 javathread dynamicreloader daemon thread blocked id28872 stack0x04ef220x04f4230 0x02ab62880 javathread containerbackgroundprocessorstandardengineglassfishwebstandardhostserverstandardcontextappuipages daemon thread blocked id28869 stack0x04e520x04ea210 0x02ab8f1d800 javathread mysql statement cancellation timer daemon thread blocked id28868 stack0x04e01f0x04e520 0x02abb0020 javathread thread33 daemon thread blocked id28867 stack0x04db1e0x04e01f0 0x02ab6295800 javathread thread32 daemon thread blocked id28866 stack0x04d61d0x04db1e0 0x0e6ea0 javathread listener12172012 01263856 daemon thread blocked id28865 stack0x04d11c0x04d61d0 0x0ee220 javathread thread31 daemon thread blocked id28864 stack0x04cc1b0x04d11c0 0x02ab623b0 javathread java2d thisposer daemon thread blocked id28862 stack0x04c2190x04c71a0 0x02ab5064800 javathread deploymentjarscanner daemon thread blocked id28848 stack0x04b8170x04bd180 0x02ab7545800 javathread deploymentjarscanner daemon thread blocked id28847 stack0x04b3160x04b8170 0x0d00a800 javathread deploymentjarscanner daemon thread blocked id28846 stack0x04ae150x04b3160 0x02ab7476800 javathread containerbackgroundprocessorstandardengineglassfishwebstandardhostserverstandardcontexthello daemon thread blocked id28845 stack0x04a9140x04ae150 0x02ab8c7a800 javathread containerbackgroundprocessorstandardengineglassfishweb daemon thread blocked id28824 stack0x04a4130x04a9140 0x02ab899d800 javathread deploymentjarscanner daemon thread blocked id28823 stack0x049f120x04a4130 0x0c57f800 javathread transactionmanager daemon thread blocked id28819 stack0x048b0e0x04900f0 0x0cfe0800 javathread grizzlykernelthread1 daemon thread in native id28818 stack0x04860d0x048b0e0 0x02ab43430 javathread thread21 thread blocked id28817 stack0x04810c0x04860d0 0x0cfdf0 javathread grizzlykernelthread1 daemon thread in native id28816 stack0x047c0b0x04810c0 0x02ab4715800 javathread thread18 thread blocked id28815 stack0x04770a0x047c0b0 0x0cfe1800 javathread grizzlykernelthread1 daemon thread in native id28814 stack0x0472090x04770a0 0x0c88b0 javathread grizzlykernelthread1 daemon thread in native id28813 stack0x046d080x0472090 0x02ab897e0 javathread thread14 thread blocked id28812 stack0x0468070x046d080 0x0ce690 javathread grizzlykernelthread1 daemon thread in native id28811 stack0x0463060x0468070 0x02ab897d0 javathread thread9 thread blocked id28810 stack0x045e050x0463060 0x0cb96800 javathread thread7 thread blocked id28809 stack0x0459040x045e050 0x02ab895f800 javathread thread5 thread blocked id28808 stack0x0454030x0459040 0x02ab89690 javathread pool1thread1 daemon thread blocked id28807 stack0x044f020x0454030 0x02ab86410 javathread felixstartlevel daemon thread blocked id28806 stack0x04450x044a010 0x0beff0 javathread felixthispatchqueue daemon thread blocked id28805 stack0x044a010x044f020 0x02ab419f800 javathread service thread daemon thread blocked id28801 stack0x043efe0x0443ff0 0x02ab419d800 javathread c2 compilerthread1 daemon thread blocked id28800 stack0x043dfd0x043efe0x02ab41980 javathread c2 compilerthread0 daemon thread in native id28799 stack0x043cfc0x043dfd0 0x02ab40ee0 javathread multithreadedhttpconnectionmanager cleanup daemon thread blocked id28796 stack0x0437fb0x043cfc0 0x02ab4003800 javathread ad thread poolglobal1 daemon thread blocked id28795 stack0x0432fa0x0437fb0 0x02ab400d800 javathread ad thread poolglobal0 daemon thread blocked id28794 stack0x042df90x0432fa0 0x0b88e0 javathread ad threadmetric reporter0 daemon thread blocked id28793 stack0x0428f80x042df90 0x0b8570 javathread ad threadconfig poller daemon thread blocked id28792 stack0x0415ec0x041aed0 0x0b7b3800 javathread thread0 daemon thread blocked id28791 stack0x0410eb0x0415ec0 0x0b5ef0 javathread signal thispatcher daemon thread blocked id28790 stack0x040bea0x0410eb0 0x0b5a0 javathread finalizer daemon thread blocked id28789 stack0x0423f70x0428f80 0x0b59e0 javathread reference handler daemon thread blocked id28788 stack0x041ef60x0423f70other threads 0x0b5960 vmthread stack 0x040070x0401710 id28787 0x02ab41a40 watcherthread stack 0x0443ff0x04450 id28803vm statenot at safepoint normal executionvm mutexmonitor currently owned by a thread noneheap psyounggen total 937216k used 6414k 0x07a240 0x07e0c0 0x080 eden space 8458k 0 used 0x07a240x07a2a43ad80x07d5e10 from space 91328k 0 used 0x07db2d0x07db2d0x07e0c0 to space 86784k 0 used 0x07d5e10x07d5e10x07db2d0 psoldgen total 912576k used 467925k 0x0718c0 0x0750730 0x07a240 object space 912576k 51 used 0x0718c0x07354f55a00x0750730 pspermgen total 94720k used 94326k 0x06e6c0 0x06ec880 0x0718c0 object space 94720k 99 used 0x06e6c0x06ec81d9b00x06ec880code cache 0x02aeb210 0x02af8c10 0x02ab1b210 total blobs4170 nmethods3358 adapters762 free code cache35382kb largest free block36057856memory 4k page physical 4043424k265500k free swap 4095992k2992388k freevm info java hotspottm 64bit server vm 210b17 for linuxamd64 jre 170b147 built on jun 27 2011 013059 by java re with gcc 430 20080428 red hat 4308time mon dec 17 013909 2012elapsed time 768 seconds,['java'] +392659,how to approach copying objects with smart pointers as class attributes from the boost library documentation i read thisconceptually smart pointers are seen as owning the object pointed to and thus responsible for deletion of the object when it is no longer neededi have a very simple problem i want to use raii for pointer attributes of a class that is copyable and assignable the copy and assignment operations should be deep every object should have its own copy of the actual data also rtti needs to be available for the attributes their type may also be determined at runtime should i be searching for an implementation of a copyable smart pointer the data are small so i do not need copy on write pointers or do i delegate the copy operation to the copy constructors of my objects as shown in this answer which smart pointer do i choose for simple raii of a class that is copyable and assignable i am thinking that the unique ptr with delegated copyassignment operations to the class copy constructor and assignment operator would make a proper choice but i am not sure heres a pseudocode for the problem using raw pointers it is just a problem description not a running c code operation interfaceclass modeloperation public virtual void operate implementation of an operation called special class specialmodeloperation public modeloperation private private attributes are present here in a real implementation public implement operation void operate all operations conform to modeloperation interface these are possible operation names class morespecialoperation class differentoperation concrete model with different operationsclass mymodel private modeloperation firstoperation modeloperation secondoperation public mymodel firstoperation 0 secondoperation 0 forgetting about runtime type definition from input files here firstoperation new morespecialoperation secondoperation new differentoperation void operate firstoperation operate secondoperation operate mymodel delete firstoperation firstoperation 0 delete secondoperation secondoperation 0 int main mymodel modelone some internal scope i want modeltwo to have its own set of copied not referenced operations and at the same time i need raii to for the operations deleting them automatically as soon as it goes out of scope this saves me from writing destructors for different concrete models mymodel modeltwo modelone return 0,['c++'] +392674,why does not jaxb generate setters for lists when i generate jaxb classes from an xsd the elements with maxoccursunbounded gets a getter method generated for them but no setter method as follows gets the value of the element3 property p this accessor method returns a reference to the live list not a snapshot therefore any modification you make to the returned list will be present inside the jaxb object this is why there is not a codesetcode method for the element3 property p for example to add a new item do as follows pre getelement3addnewitem pre p objects of the following types are allowed in the list link type public listtype getelement3 if element3 null element3 new arraylisttype return thiselement3the method comment makes it crystal clear on how can i use it but my question is as follows why does not jaxb just generate a setter following the java beans rules i know i can write the setter method myself but is there any advantage to the approach suggested in the generated getter methodthis is my xsdxml version10 encodingutf8schema xmlns xmlnstns targetnamespace element namecollectiontest typetnscollectiontestelement complextype namecollectiontest sequence element nameelement1 typestring maxoccurs1 minoccurs1element element nameelement2 typeboolean maxoccurs1 minoccurs1element element nameelement3 typetnstype maxoccursunbounded minoccurs1 nillabletrueelement sequence complextype complextype nametype sequence element namesubelement1 typestring maxoccurs1 minoccurs1element element namesubelement2 typestring maxoccurs1 minoccurs0element sequence complextypeschema,['java'] +392705,do c template classes duplicate code for each pointer type used from what i understand if you have for example an stdvectorint and an stdvectorfloat the compiler creates two classes one for each type thus although you reduce the amount of code written you do not reduce executable size correct me if i am wrongis the same true even if the type is a pointer for example would instantiating an stdvectorsomeclass and an stdvectorsomeotherclass necessarily cause the compiler to generate separate code for each of the two instantiations,['c++'] +392706,what is c11 cor 12012 i just noticed that there has been a correction to the c11 standard called isoiec 98992011cor 12012 what was changed in this update,['c'] +392733,networkx extract the connected component containing a given node directed graph i am trying to extract from a big graph the subgraph of all connected nodes containing a specific nodeis there a solution in the networkx libraryeditmy graph is a digrapheditrephrased simplyi want the part of my graph that contain my specific node and i and and all the nodes that are connected directly or indirectly passing by other nodes using any incoming or outcoming edgesexample g nxdigraph gadd pathabc gadd pathxyz gedgesa b b c y z x ymy desired result would be g2 getsubgraphg b g2nodesa b c g2edgesa b b c,['python'] +392735,why edittext in a custom compound view is reusing the text entered in another compound view instance i am trying to write a custom compound view composed by a textview and an edittext compound viewxml linearlayout xmlnsandroidandroidididcompoundtextandroidlayout widthmatch parentandroidlayout heightwrap content textview androidididtextlabel androidlayout widthwrap content androidlayout heightwrap content androidtextlabel edittext androidididtextedit androidlayout widthmatch parent androidlayout heightwrap content androidhintenter text here edittextand this is the class extending linearlayoutpublic class compoundview extends linearlayout public compoundviewcontext context attributeset attrs supercontext attrs readattributescontext attrs initcontextpublic compoundviewcontext context supercontext initcontextprivate void initcontext c final layoutinflater inflater layoutinflater c getsystemservicecontextlayout inflater service inflaterinflaterlayoutcompound view this now if i use 2 of these view in my activity mainxml relativelayout xmlnsandroidxmlnstoolsandroidlayout widthmatch parentandroidlayout heightmatch parenttoolscontextmainactivity itmoondroidcompoundviewexamplecompoundview androidididcompoundview1 androidlayout widthmatch parent androidlayout heightwrap content androidlayout alignparenttoptrue itmoondroidcompoundviewexamplecompoundview androidididcompoundview2 androidlayout widthmatch parent androidlayout heightwrap content androidlayout belowidcompoundview1 relativelayoutand in the activity code i only inflate the relativelayout without managing onsaveinstancestateoverrideprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity mainthen when i write something in the 2nd edittext and i rotate my device the same text appears in the edittext of the first custom viewwhy is happening this behaviourediti solved the issue by removing androidid and using androidtag for the edittext in compound viewxml then managing the saving of the edittext state in compoundview classoverrideprotected parcelable onsaveinstancestate bundle bundle new bundle bundleputparcelableinstancestate superonsaveinstancestate bundleputstringcurrentedit medittextgettexttostring bundleputbooleanisfocused medittexthasfocus return bundleoverrideprotected void onrestoreinstancestateparcelable state if state instanceof bundle bundle bundle bundle state medittextsettextbundlegetstringcurrentedit if bundlegetbooleanisfocused medittextrequestfocus superonrestoreinstancestatebundlegetparcelableinstancestate return superonrestoreinstancestatestate,['android'] +392769,checking multiple columns for one value i have a table that has columns like this for exampleidcol1col2col3col4now i want to check if any of col1 col2 col3 col4 have the passed in valuethe long way to do nit would beselect from table where col1 123 or col2 123 or col3 123 or col4 123i guess it is the opposite version of inis there an easier way to do what i want,"['mysql', 'sql']" +392782,how to install a specific version of a package with pip possible duplicateinstalling specific package versions with pip i am a bit new to pip install and virtualenv in generali have setup an virtualenv on my server as well as on my local dev environmenton the server the package django modeltranslation040 beta2 works perfectly finehowever on my local machine django modeltranslation050alpha does not seem to work well at alli usually simply install it in virtualenv like this source binactiveenv pip install django modeltranslationthis gets the latest version though which now for the first time causes issues working with latest versionso i have uninstalled the version 5 alpha like thisenv pip uninstall django modeltranslationbut now i do not know how i could get the working version 040 beta againi tried this but it could not find itenv pip install django modeltranslation040 beta2downloadingunpacking djangomodeltranslation040beta2 could not find any downloads that satisfy the requirement djangomodeltranslation040beta2no thistributions at all found for djangomodeltranslation040beta2i think there must be a way since that is the whole point of using virtual env,['python'] +392798,how do i delete or replace a file in a zip archive i am creating a program in python which downloads a set of files and puts them into an archive with the zipfile modulei already found out how to append to the archive but there are cases where the files in the archive already exist and should be overwrittencurrently if i append an already existing file to the archive i get a duplicatedoes anyone know how to delete a file in an archive,['python'] +392836,use the apple search api to search by genre is it possible to use the apple search api to search by genre i am thinking specifically games in the app store using objcas has been pointed out in the comments of this questionsearch apple app store by genre with iosobjcthere seems to be a problem with trying to search by genre so i am looking for answers which of examples of that actually working not just links to the docs,"['objective-c', 'ios']" +392852,rails 3 routes stack level too deep devise i get this error about my routes filesystemstackerror stack level too deep actionpack 328 libaction thispatchmiddlewarereloaderrb70 rendered usersduyrvmgemsruby193p194gemsactionpack328libaction thispatchmiddlewaretemplatesrescues traceerb 15ms rendered usersduyrvmgemsruby193p194gemsactionpack328libaction thispatchmiddlewaretemplatesrescues request and responseerb 13ms rendered usersduyrvmgemsruby193p194gemsactionpack328libaction thispatchmiddlewaretemplatesrescuesdiagnosticserb within rescueslayout 199msi could isolate the problematic code but do not understand whats creating the infinite loop devise for users controllers registrations registrations sessions sessions omniauth callbacks usersomniauth callbacks devise scope user do match sessionssimulate userid sessionssimulate user as simulate user sessions match sessionsleave simulation mode sessionsleave simulation mode as leave simulation mode sessions get user confirmation to deviseconfirmationscreate get after confirmation to challengesindex endany help would be greatly appreciatededitclass sessionscontroller devisesessionscontroller def new after sign in page paramsafter sign in page if paramsafter sign in page super end def create paramsuseremaildowncase super end def simulate user if can simulate user user admin current userid sign out user userfindparamsid if sign in user sessionsimulation for admin redirect to requestreferer else flashnotice something went wrong redirect to action leave simulation mode end end end def leave simulation mode user userfindsessionsimulation for sign out if sign in user sessionsimulation for nil else flashnotice something went wrong end redirect to requestreferer endendclass challengescontroller applicationcontroller def index paramsformat html unless paramssubactionnil video true unless user signed in if current user current page paramspage paramspageto i 1 columns paramscols paramscols 2 keyword paramskeyword search true if paramssearch 1 challenges challengeis openwhereid current userchallengesfilteredparamskeywordparamsuserparamsexpertizecollectroot iduniq loggerdebug challenges found challengescount users userscoped expertizes expertizeall end respond to do format formathtml if current user if current userchallengeswaiting for approvalcount 1 and challengescount 1 redirect to challenge pathcurrent userchallengeswaiting for approvalfirst subaction description return loggerdebug redirect called else challenges challengespage1percurrent pageto i 10orderchildren counttasks count desc end end render formatjson render json challenges formatjs challenges challengespagecurrent pageper10orderchildren counttasks count desc render end endendalso i forgot to mention that when i restart the local server it works fine every time i change my routesrb file i get this error then i have to restart the thin server then i can work further onedit 2rake route output,['ruby-on-rails'] +392863,is there a performance gain from caching this i often use this inside jquery event handlers and never cache it if i will dovar this thisand will use variable instead of the constructor will my code get any significant extra performancejs perf test to measure the performance gain from this optimization,['jquery'] +392866,zf2 module loading performance as far as i understand every enabled module in a zf2 application is loaded for every request unless one uses optimization methods such as that offered by the zf2lazyloadingmodule module i have been keeping an eye on modules that get published on moduleszendframeworkorg and i have come across modules which offer extremely limited functionality such as the akrabatformatuktelephone module which purpose is to format phone numbers to uk format whilst i understand development should focus on creating single purpose modules that are good at doing one thing instead of modules which do many things but not in a very good way i am thinking if we start using modules which offer such limited functionality as the one mentioned we will need to combine hundreds of modules in order to build a rich application which could be thisastrous for performance instead i would expect this sort of functionality to be put in a class eg zendi18n and loaded on demand which would be more optimized but knowing akrabats reputation i am thinking i must be missing something hence my questionis the loading of modules such as the one i mentioned significantly worse for performance than loading the same functionality via php classes or is it similar due to the way zf2 has been designed does anybody have any figures ie is it 5 10 15 slower about module vs class loading performance,['php'] +392877,update a pypi package is there a way to update a pypi package without changing the version numberimagine for a second that i have found a small bug in a package i recently uploaded to pypi is there a way to editreupload the code without incrementing the version numberupdatei guess i should clarify that by bug i mean the version number in the actual source code is wrong it is not a functional thing it just means if you do packageversion you get the previous version not the current one and yes i know this could cause a bug in someone elses code but given were in alpha i would hope version dependencies have not set in just yet for the record clearly silent bug fixes are badupdate 2as of jan 2015 the solution provided is no longer valid see this post for more information,['python'] +392915,how to rotate an image actor in libgdx by the middle point if i understand correctly libgdx is rotating an image with the use of the addactions methodthisaddaction parallelrotateby360 05f moveto320 100 05fthe thing is it is being rotated by the point00 of the imageheres my questionis there a way to rotate an image by the center point of the object something like pinning it in the middle and then turning it like a wheel in a carboth rotateby and rotateto methods turn it by the 00 point of the image itself,"['java', 'android']" +392943,python urllib2 receive json response from url i am trying to get a url using python and the response is json however when i runimport urllib2response urllib2urlopenhtmlresponsereadprint htmlthe html is of type str and i am expecting a json is there any way i can capture the response as json or a python dictionary instead of a str,['python'] +392960,adding column with primary key in existing table i am trying to add primary key to newly added column in existing table name product detailsnew column added product detail id int and not nulli am trying add primary key to product detail id please note there are no other primary or foreign key assigned to this tablei am trying with this query but getting error alter table product detailsadd constraint pk product detils product detail id primary keyproduct detail idgoerrorthe create unique index statement terminated because a duplicate key was found for the object name dboproduct details and the index name pk product detils the duplicate key value is 0am i missing something here i am using sql server 2008 r2 i would appreciate any help,['sql'] +392963,upload an image with phonegap invalidcastexception i am trying to upload a file to my server with phonegap i am currently stuck when an error that saysinvalidcastexceptionfailed to deserialize wp7cordovaclasslibcordovacommandsfiletransferuploadoptions with json value filepathcapturedimagescachephotochooser51766419c65746dba53df09bee300a89jpgserverfilekeyfilefilenamephotochooser51766419c65746dba53df09bee300a89jpgmimetypeimagejpgparamsvalue1testvalue2paramchunkedmodefalsethe html javascriptdoctype htmlhtml head meta httpequivcontenttype contenttexthtml charsetutf8 meta nameformatdetection contenttelephoneno titlefile transfer exampletitleheadbody button iduploadphotobuttonupload a photobutton script typetextjavascript srccordova220jsscript script typetextjavascript srcjsjquery182minjsscript script typetextjavascript srcjsjquerymobile120minjsscript script typetextjavascript srcjscamerajsscript script typetextjavascript documentonepause function consolelogpaused documentoneresume function consolelogresumed documentonedeviceready function consolelogdevice is ready documentonebackbutton function consolelogback button pressed documentreadyfunction consolelogdom is ready documentonclick uploadphotobutton function e consolelogclicked button getimage function getimage retrieve image file location from specified source navigatorcameragetpictureuploadphoto function message alertget picture failed quality 50 destinationtype navigatorcameradestinationtypefile uri sourcetype navigatorcamerapicturesourcetypephotolibrary function uploadphotoimageuri var options new fileuploadoptions optionsfilekey file optionsfilename imageurisubstrimageurilastindexof 1 optionsmimetype imagejpeg var params new object paramsvalue1 test paramsvalue2 param optionsparams params optionschunkedmode false var ft new filetransfer ftuploadimageuri win fail options function winr consolelogcode rresponsecode consolelogresponse rresponse consolelogsent rbytessent alertrresponse function failerror alertan error has occurred code errorcode script bodyhtmlthe complete error loggapbrowser navigated appwindexhtmlappwuploadtesthtmllogclicked buttonthe thread no name 0xf55026a has exited with code 0 0x0the thread no name 0xe3f0326 has exited with code 0 0x0info appdeactivatedinfo appactivatedlogpausedthe thread no name 0xf1a02e6 has exited with code 0 0x0logresumedthe thread no name 0xf2a01d2 has exited with code 0 0x0options filepathcapturedimagescachephotochooser51766419c65746dba53df09bee300a89jpgserverfilekeyfilefilenamephotochooser51766419c65746dba53df09bee300a89jpgmimetypeimagejpgparamsvalue1testvalue2paramchunkedmodefalsea first chance exception of type systeminvalidcastexception occurred in systemservicemodelwebdlla first chance exception of type systeminvalidcastexception occurred in systemservicemodelwebdllinvalidcastexceptionfailed to deserialize wp7cordovaclasslibcordovacommandsfiletransferuploadoptions with json value filepathcapturedimagescachephotochooser51766419c65746dba53df09bee300a89jpgserverfilekeyfilefilenamephotochooser51766419c65746dba53df09bee300a89jpgmimetypeimagejpgparamsvalue1testvalue2paramchunkedmodefalsea first chance exception of type systemnullreferenceexception occurred in lionmyappdllthe thread no name 0xfdc025e has exited with code 0 0x0logerror in error callback filetransfer1325332352 referenceerror invalid lefthand side in assignmentthe thread no name 0xfa60286 has exited with code 0 0x0does anyone have an idea on how to make this workthanksw,['javascript'] +393029,render error messages with js form rails i changed my form to remote and while the form now works the error messages are no longer thisplaying if there is an error render sharederror messages is there a good wear to get the messages to show again below is my controllerthank yourespond to do format if postsave formatjs render js windowlocation edit post path post formathtml redirect to edit post else formatjs render js posterrors formathtml redirect to error could not save comment endend,['ruby-on-rails'] +393058,imageview fit without stretching the image is it possible that my imageview will fit to all screen sizes without the image look stretchedi tried all scale types changing it to background and src with fill parent wrap contentbut still if the image is not smaller it just looks stretched exampleimageview androidlayout widthfill parent androidlayout heightwrap content androidscaletypecenterinside androidadjustviewboundstrue androidbackgrounddrawablebackground imageview androidlayout widthfill parent androidlayout heightwrap content androidscaletypefitxy androidadjustviewboundstrue androidbackgrounddrawablebackground these 2 fits the width but the image is stretched but when i change it to src the image is just centered and small,['android'] +393059,specifying default format in routing spec i have the following rspec routing spec but i need to specify defaults format json in the post how would i do thisspecit should route to alocationsnav do post locations nav path should route tocontroller api action locations navendedit 1so playing around it looks like this fixes itit should route to alocationsnav do post locations nav path should route tocontroller api action locations nav format jsonendbut was curious if this is documented anywhere,['ruby-on-rails'] +393065,conditional explicit template instantiation other than the preprocessor how can i conditionally enablethisable explicit template instantiationsconsidertemplate typename t struct thetemplate blah template struct thetemplatetype1template struct thetemplatetype2template struct thetemplatetype3template struct thetemplatetype4under some compilation conditions type3 is the same as type1 and type4 is the same as type2 when this happens i get an error i would like to detect that the types are the same and not instantiate on type3 and type4 as in this does not worktemplate struct thetemplatetype1template struct thetemplatetype2template struct thetemplateenable ifis sametype1 type3value type3typetemplate struct thetemplateenable ifis sametype2 type4value type4typei have diverted myself trying enable if and sfinae and i believe i know why they fail but only the preprocessor has worked ugh i am thinking about putting the types in a tuple or variadic removing duplicates and then use the remainder for instantiationis there a way to conditionally enablethisable explicit template instantiation based on template argument types,['c++'] +393068,how to play two sound file at the same time with wpf i use soundplayer to play sound effects in the wpf program however i find that when two sounds effects are played at the same time the new one will replace the old one ie the new will terminate the old and play itself but what i want is to keep playing the old one even when the new one is playedsoundplayer wowsound new soundplayersoundeffectwowwavsoundplayer countingsound new soundplayersoundeffectfunnywavwowsoundplay play like background musiccountingsoundplay from click to generate the sound effect,['c#'] +393115,restkit 02 multiple ways to make a getpostput request i am getting slightly confused as to the way to use restkit it seems like there is multiple ways to do the same thing before i was content just messing about with it till it worked but now he has changed the framework and usage in 020x and i have spent a great deal of time converting my code over and now spending even more time trying to get it to work like before and i have scoured for some examples and such and the ones that people claim to work for them do not do so much for me so there must be a difference somewhere so perhaps someone can tell me the difference in the following when attempting to get this data at least for example 1 2 which fails but that is for a question on the restkit githubresponsebodyplayer id 50585c86ded998e77a02 1rkobjectmanager sharedmanagerrouterrouteset addrouterkroute routewithclassplayer class pathpatternplayerfbidfid methodrkrequestmethodgetand to get your player something like thisplayer player player newplayerplayerid 2rkobjectmanager sharedmanager getobjectplayer pathnil parametersnil successrkobjectrequestoperation operation rkmappingresult result request failurenil2using a response descriptor like sorkresponsedescriptor responsedescriptor rkresponsedescriptor responsedescriptorwithmappingplayerwtfmappingin pathpatternnil keypathplayer statuscodesrkstatuscodeindexsetforclassrkstatuscodeclasuccessfulrkobjectmanager sharedmanager addresponsedescriptorresponsedescriptortempplayer setfbidresult objectforkeyidobjectmanager getobjecttempplayer pathnil parametersnil successrkobjectrequestoperation operation rkmappingresult mappingresultfailurenil3or in fact blakes own exmaple on the restkit wikirkresponsedescriptor responsedescriptor rkresponsedescriptor responsedescriptorwithmappingarticlemapping pathpatternnil keypatharticles statuscodesrkstatuscodeindexsetforclassrkstatuscodeclasuccessfulnsurl url nsurl urlwithstringnsurlrequest request nsurlrequest requestwithurlurlrkobjectrequestoperation objectrequestoperation rkobjectrequestoperation alloc initwithrequestrequest responsedescriptors responsedescriptor objectrequestoperation setcompletionblockwithsuccessrkobjectrequestoperation operation rkmappingresult mappingresult rkloginfoload collection of articles objects failurerkobjectrequestoperation operation nserror error rklogerroroperation failed with error errorobjectrequestoperation startand i am sure there are many other ways my suspicion if anyone can confirm it is that the way you should setup your paths and whether you use one method over another is decided quite strongly by the data set you are trying to map and it is format then again some of it also looks like a different way of doing the exact same thing thanks,['ios'] +393151,cannot access the controller functions in code igniter hi my folder sturcture is like thiscontrollersuserregistrationregisterphpinside the registerphp controller there is let say for test index function saying hello worldbut i cant access the folder index through browsermy base url isconfigbase url httplocalhostnewbut while i write localhostnewindexphpuserregistrationregisterindexi got an error the page you requested was not found what is weird is i can access the controller fxn of user folder but cant access the controller fxn inside registration folder and for default controller i have homephproutedefault controller homeroute404 override i just want to access the controlleruserregistrationregisterindex fxn which says hello world but it says an errorthe page you requested was not foundthanks,['php'] +393159,texture not thisplaying properly probably coordinates are wrong opengl c i will try to explain my problem with images so this is a test texture i am using for my opengl applicationas you can see there is a 2pixels wide border around the image with different colors for me to be able to see if coordinates are properly set in my applicationi am using a 9cell pattern so i am drawing 9 quads with specific texture coordinates at first sight everything works fine but there is a small problem with thisplaying a texturein the picture i marked where is first quad and where is the second one as you can see first one is thisplayed correctly but second one smoothly goes from first quads colors to it is own but it should start with pure green and pink so i am guessing it is a problem with texture coordinatesthis is how they are set bottom left quad 1st quadglbegingl quads bottom left gltexcoord2f00f 10 glvertex2iposx posy height top left gltexcoord2f00f glfloat10 maxtexcoordbordery glvertex2iposx posy height m borderwidth top right gltexcoord2fmaxtexcoordborderx glfloat10 maxtexcoordbordery glvertex2iposx m borderwidth posy height m borderwidth bottom right gltexcoord2fmaxtexcoordborderx 10 glvertex2iposx m borderwidth posy heightglend bottom middle quad 2nd quadglbegingl quads bottom left gltexcoord2fmaxtexcoordborderx 10 glvertex2iposx m borderwidth posy height top left gltexcoord2fmaxtexcoordborderx glfloat10 maxtexcoordbordery glvertex2iposx m borderwidth posy height m borderwidth top right gltexcoord2fglfloat10 maxtexcoordborderx glfloat10 maxtexcoordbordery glvertex2iposx width m borderwidth posy height m borderwidth bottom right gltexcoord2fglfloat10 maxtexcoordborderx 10 glvertex2iposx width m borderwidth posy heightglendyou can see that i am using maxtexcoordborderx variable which is calculated based on border and image size image width is 32 and border width is 2maxtexcoordborderx 2 32 00625could anyone please help with with finding out where the problem is,['c++'] +393220,how to determine the version of android sdk installed in computer how to determine the version of android sdk installed in my computer,['android'] +393255,matplotlib wrong overlapping when plotting two 3d surfaces on the same axes i am trying to plot two 3d surfaces on the same axes in matplotlib with the plot surface commandfig pltfigurefigfigsize fig sizeax figgcaprojection3dsurf axplot surfacex y exp fric map alpha 1 rstride1 cstride1 cmapcmwinter linewidth05 antialiasedtruesurf axplot surfacex y fric map alpha 1 rstride1 cstride1 cmapcmautumnlinewidth05 antialiasedtruethe problem i have is that when viewing the plot not always the correct surface is on top for instance in the plotin the back corner 200n 25hz on the axes the bluegreen surface is on top when actually the yellowred is closer to the viewer if i rotate the plotthen things look ok now the bluegreen surface is underneath the yellowred one at 200n and 25hz now on the left side i have tried searching stackoverflow and google but cannot find any similar problems with a solutioni am using python 273 numpy 161 and matplotlib 1rc on linux,['python'] +393261,inheritance in net entityframework 40 for similar database tables i am looking for a solution in the following problemi have many tables that differentiate from one another in fewnone columns why this happens is not the case as i have not designed said database nor can i change itexample table user columnsnamesurnameagetable olduser columnsnamesurnameagelastdateseenetcis there any way to indicate to the entityframework 40 in visual studio to extend a base class consisting of name surname age fields and their corresponding properties so that i can use that class for batch jobs in the codemy current solution is to make this class and use converters to pass the values from the persistent objects its objects it works but it is not elegant and i do not like iti come from a javahibernate environment where this is basic functionalityfor future refernce can the same thing be done if i want the classes to implement an interfacethanks in advance,"['c#', '.net']" +393268,configure jetty cluster to share web sessions i am new with jetty i am trying to setup a cluster including 2 jetty servers with haproxy as the load balancer however the two jetty servers worked separately without sharing sessionsi found this document that instructs to use wabi but it seems the document is deprecated because it used jetty 6 i am using jettythistribution818 how can i configure thisthanks for your concern,['java'] +393269,tinytext text mediumtext and longtext maximum storage sizes per the docs there are four text typestinytexttextmediumtextlongtextwhat is the maximum length that i can store in a column of each data type assuming the character encoding is utf8,['mysql'] +393276,how to check if twitter bootstrap is loaded how can i check whether there is a bootstrapjs loaded on page a file bootstrapjs may be compiled into another big js file,['javascript'] +393296,injecting a java method before another method is called i am using asm and want to rewrite something likesomemethodtargetmethodargstosomemethodinjectedmethodargtargetmethodargsthe trouble is that i do not know what the method before is i only know the target method so finding somemethod and injecting after that is not an optioni also have many versions of the target method with different sets of parameters i want this to work withusing asm i can easily find the target method invocation but unfortunately the operand stack at that point is argn arg1 instance and while i can work out how far down the instance will be there is no bytecode i can inject that will read it i know you can do it for up to 4 parameters using tricks with dup commands but i need a general solutioni could add a bunch of local variables and copy everything off the stack dup the instance pointed and put everything back on but that is a runtime inefficiency i really do not wantwhat i think would work is if i could track which instructions were responsible for putting the instance pointer on the stack and then i could inject my method invocation there rather than at the target method invocation however i have had no luck in finding anything to help me do thisi know that things like aspectj allow for this but have to do this for a lot of classes as they load and aspectj is just too slowcan anyone point me at analysis tools built on top of asm that might let me do this or can anyone think of a better approach for injecting one method call before another,['java'] +393299,progressbar under action bar question summary how can i make a progressbar integrated inside the actionbar like on the chrome appdetails look at this screenshot from chromei want to create an action bar just like this just under the action bar there is a progressbar that fills according to page load i have seen this example from many apps like feedly but i have not been able to create my own implementation i tried using androids own apis to create itoverrideprotected void oncreatebundle savedinstancestate request permission to thisplay the progress bar thisrequestwindowfeaturewindowfeature progress thissetwindowcontentviewrlayoutactivity main superoncreatesavedinstancestate thissetprogressbarindeterminatetruebut this code only causes the progressbar to show over the action bar like soso how can i make my progressbar appear under the action bar like on the chrome app,['android'] +393317,write a c wrapper around c classes with c callbacks i need to wrap a c library with c this c library defines callback functions for example from c library typedef x callbackfny y x and y are classes class z public void addcallback callbackfn fn callbackfn fn private callbackfn callbackfn in the c wrapper i could define new c callbacks which call the c callbacks something like this in c wrapper extern c typedef int callbackfncint n callbackfnc callbackfnc int addcallbackvoid handle callbackfnc fn handle is pointer to z instance callbackfnc fn zhandleaddcallbackcallbackfncpp x callbackfncppy y int rtn callbackfncyn return xrtn where i assume i can map the relevant members of y to the arguments of the c callback function and that i can sufficiently construct the return type x from the c returnis this going to work there is no way around defining the new c callbacksthe new c callback should be inside the extern c and the defined instance of the c callback should be outside,"['c++', 'c']" +393319,how can i detach the object reference on memorycache i am currently trying out the new memorycache in net 4 to cache a few bits of data in one of our apps the trouble i have is the objects are updated and the cache appears to be persisting the changes egpublic ienumerablesomeobject getfromdatabase const string cachekeygetthisplaytree somekey objectcache cache memorycachedefault var objectincache cacheget cachekeygetthisplaytree as ienumerablesomeobject if objectincache null return objectincachetolist do something to get the items cacheadd cachekeygetthisplaytree categories new datetimeoffsetdatetimeutcnowaddhours1 return categoriestolistpublic ienumerablesomeobject getwithindentation var categories getfromdatabase foreach var c in categories cname cname return categoriesif i were calling getwithindentation first and then later calling getfromdatabase i would expect it to return the original list of someobject but instead it returns the modified items with prefixed on the namei thought tolist destroyed the reference but it still seems to persist the changes i am sure it is obvious but can anyone spot where i am going wrong,['c#'] +393380,a token was not found in the securitycontext on silex symfony i built a silex project with an login mechanismnot being a symfony expert i strictly followed the guidelines here for the authentication process and it works fine on my development environmenthowever when i pushed my project on my production server i get the following error each time i try to log into my web app20121218 163533 critical symfonycomponentsecuritycoreexceptionauthenticationcredentialsnotfoundexceptiona token was not found in the securitycontext uncaught exception atmyapathvendorsymfonysecuritysymfonycomponentsecurityhttpfirewallaccesslistenerphp line 53 which means that the following code in accesslistenerphpthiscontextgettokenthrows an expectiongiven the fact that the same code works perfectly fine on my development environment i assume it has something to do with my production server configurationi found this thread msgsymfonydevsjkphny 0q2yvyfkauyjshej that suggests to add the following line to my projects htaccessrewriterule ehttp authorizationhttpauthorizationlwith no result i still get the a token was not found in the securitycontext exceptiondoes anybody have an idea editthe content of appsecurityfirewalls is the followingappregisternew silexprovidersecurityserviceprovider arraysecurityfirewalls arraylogin array pattern loginadmin array pattern form arraylogin path login check path adminlogin check logout arraylogout path adminlogout url to call for logging out users array admin arrayrole admin somepassword,['php'] +393401,inherit a parent class docstring as doc attribute there is a question about inherit docstrings in python class inheritance but the answers there deal with method docstringsmy question is how to inherit a docstring of a parent class as the doc attribute the usecase is that django rest framework generates nice documentation in the html version of your api based on your view classes docstrings but when inheriting a base class with a docstring in a class without a docstring the api does not show the docstringit might very well be that sphinx and other tools do the right thing and handle the docstring inheritance for me but django rest framework looks at the empty doc attributeclass parentwithdocstringobject parent docstring passclass subclasswithoutdoctringparentwithdocstring passparent parentwithdocstringprint parent doc prints parent docstringsubclass subclasswithoutdoctringprint subclass doc prints nonei have tried something like supersubclasswithoutdocstring self doc but that also only got me a none,['python'] +393403,pythons range analog in common lisp how to create a list of consecutive numbers in common lispin other words what is the equivalent of pythons range function in common lispin python range2 10 2 returns 2 4 6 8 with first and last arguments being optional i could not find the idiomatic way to create a sequence of numbers though emacs lisp has numbersequencerange could be emulated using loop macro but i want to know the accepted way to generate a sequence of numbers with start and end points and steprelated analog of pythons range in scheme,['python'] +393408,rails route to only index this might be a simple routing question in rails but i have searched around and received answers for rails 2 rather than rails 3i generated a scaffold and the resources users which includes new edit show are routed together with the indexi only want to route to the index and remove the new edit show etci have already removed the htmlerb files but they are still being routedany advice on what i should do to remove the other routes would be appreciated,"['ruby-on-rails', 'ruby']" +393431,why there is no way to check if current thread holds the read lock of reentrantreadwritelock i found that the write lock of the reentrantreadwritelock provides an isheldbycurrentthread method to check whether the invoking thread holds that lockbut there is no corresponding isheldbycurrentthread method for the read lock why not,['java'] +393440,css transition auto height not working i have a website and i decided to replace the jquery based toggle boxes with pure css snippets when i use fixed height value for the transition last lines of the css it works well but with the auto value the animation is missing only the height change has an effectis there a way to use this with auto value i would like to use variable texts and no scriptsaccontainer width 400px margin 10px auto 30px auto textalign leftaccontainer label fontfamily bebasneueregular arial narrow arial sansserif padding 5px 20px position relative zindex 20 thisplay block height 30px cursor pointer color 7 textshadow 1px 1px 1px rgba25525525508 lineheight 33px fontsize 19px background f background mozlineargradienttop f 1 eaeaea 100 background webkitgradientlinear left top left bottom colorstop1f colorstop100eaeaea background webkitlineargradienttop f 1eaeaea 100 background olineargradienttop f 1eaeaea 100 background mslineargradienttop f 1eaeaea 100 background lineargradienttop f 1eaeaea 100 filter progiddximagetransformmicrosoftgradient startcolorstrf endcolorstreaeaeagradienttype0 boxshadow 0px 0px 0px 1px rgba15515515503 1px 0px 0px 0px rgba25525525509 inset 0px 2px 2px rgba01accontainer labelhover background faccontainer inputchecked labelaccontainer inputchecked labelhover background c6e1ec color 3d7489 textshadow 0px 1px 1px rgba255255255 06 boxshadow 0px 0px 0px 1px rgba15515515503 0px 2px 2px rgba01accontainer input thisplay noneaccontainer section background rgba255 255 255 05 margintop 1px overflow hidden height 0px position relative zindex 10 webkittransition height 03s easeinout boxshadow 06s linear moztransition height 03s easeinout boxshadow 06s linear otransition height 03s easeinout boxshadow 06s linear mstransition height 03s easeinout boxshadow 06s linear transition height 03s easeinout boxshadow 06s linearaccontainer section p fontstyle italic color 7 lineheight 23px fontsize 14px padding 20px textshadow 1px 1px 1px rgba25525525508accontainer inputchecked section webkittransition height 05s easeinout boxshadow 01s linear moztransition height 05s easeinout boxshadow 01s linear otransition height 05s easeinout boxshadow 01s linear mstransition height 05s easeinout boxshadow 01s linear transition height 05s easeinout boxshadow 01s linear boxshadow 0px 0px 0px 1px rgba15515515503accontainer inputchecked sectionacsmall height 120px autodiv classaccontainer div input idac1 nameaccordion1 typecheckbox section classacsmall psome content p section label forac1about uslabel div div input idac2 nameaccordion2 typecheckbox section classacsmall psome content p section label forac2about uslabel divdiv,['css'] +393448,guava cache vs ehcache benchmark i am trying to decide which of these two to use in my project guava cache or ehcache looking for a lightweight service level caching solutioni have searched for some benchmarks but could not find anyif youve have a benchmark handy please post it herecheers,['java'] +393515,setting contenttype header for rspec and railsapi i am using the railsapi gem to build a web service and want to test my api with rspec every request i make regardless of the http method has the content type header set as applicationxwformurlencoded this is not really a problem until i try to use wrap parameters in my controller and it is not have any affect on the params hashclass applicationcontroller actioncontrollerapi include actioncontrollerparamswrapperendclass projectscontroller applicationcontroller wrap parameters project include name endthis hack no longer works request is nil and none of the other stack overflow posts i found work eitherif i make the following request in my rspec testput projects1json name updated project 1and put a debugger in my controller i getrdb1 p params nameupdated project 1 actionupdate controllerprojects id5539bbd9010c4cfb88d382dadbc99507 formatjsonrdb1 p requestcontent typeapplicationxwformurlencodedi am expecting to see something like this for the params hash note the addition of the project key nameupdated project 1 actionupdate controllerprojects id5539bbd9010c4cfb88d382dadbc99507 formatjson project name updated project 1is it possible to set the content type header using just rspec or do i have have to use racktest for this functionality,['ruby-on-rails'] +393518,when is it bad form to return a deferred ienumerable i am curious if anyone has any rulesofthumb or best practices on when it makes sense to return a deferred ienumerablet or to call toarray on it before returning it from a functionfor example as the consumer of an api i think that i would prefer for a method like ienumerablewidget getwidgets to throw an httpexception when i call it and not have it throw when i am enumerating the resultspublic ienumerablewidget getwidgetsienumarableint widgetids return widgetidsselectid getwidgetfromwidgetwebserviceid,"['c#', '.net']" +393523,does linq optimizes execution based on real collection type linq to objects works on any ienumerable object the variablesstring foo new string andvar bar new liststringare both ienumerablestring but if i want to know how many items each one of them has i can use length property on the array and count property on the list or i can use the count method from linq which will work for boththe question is does linq provides some kind of optimization such as implement different algorithms for every method calling one or another depending on the actual type of the object being queriedi imagine something like thisif obj is arrayt dosomethingforarrayobj as arraytelse if obj is listt dosomethingforlistobj as listtelse if obj is collectiont dosomethingforcollectionobj as collectiontelse dosomethingthatworksforanyienumerableobj,"['c#', '.net']" +393527,android 42 on nexus 7 canvasdrawtext not working correctly i am facing a serious issue with my application published on google play and apparently working fine on all versions of android except for 40this is a screenshoot from my android 40 htc phoneand this is what i get on nexus 7 android 421 same behaviour in the emulatori see the same behaviour for each text drawn using canvasdrawtextthe paint used to draw text ispaint new paintpaintsetantialiastruepaintsetcolorcolor some colorpaintsettextsizesize some sizepaintsettypefacetypefacedefaultfromstyletypefaceboldpaintsettextalignaligncenterin the logcat 421 emulator i see a lot of1218 204221096 wtrace276 unexpected value from nativegetenabledtags 0i use these settings in the manifest usessdk androidminsdkversion8 androidtargetsdkversion8,['android'] +393570,any real word example about how setup and teardown should be used in phpunit methods setup and teardown are invoked before and after each test but really is there any real word example about why should i need thisinspecting other people tests i always see something likepublic function setup thistestsub new testsubjectpublic function teardown unsetthistestsubpublic function testsomething thisassertsamefoo thistestsubgetfof course there is virtually no difference between this way and the old local variable way,['php'] +393595,how to convert from string to a primitive type or standard java wrapper types i have a javalangreflectinvocationhandler and i need to implement the method invokei have a value of type javalangstring from my elaboration and i need to convert this value to the appropriate returntype expected by the method it can be a primitive like int boolean double or wrapper classes like boolean integer double float etc examplepublic object invokeobject proxy method method object args throws throwable string computedvalue compute return convertmethodgetreturntype computedvalueprivate object convertclass returntype string stringvalue return whats the simplest wayi am not expecting to simply implement an automatic conversion between complex objects but i expect a simple way to convert from string to the standard java typesi have seen too many times stuff like this but it does not seem appropriate to mepublic static object toobject class clazz string value if booleanclassisassignablefrom clazz return booleanparseboolean value if byteclassisassignablefrom clazz return byteparsebyte value if shortclassisassignablefrom clazz return shortparseshort value if integerclassisassignablefrom clazz return integerparseinteger value if longclassisassignablefrom clazz return longparselong value if floatclassisassignablefrom clazz return floatparsefloat value if doubleclassisassignablefrom clazz return doubleparsedouble value return valueand the above is not even the worse one i saw so far does anybody have a secret trick here,['java'] +393610,inapp billing does not work iab helper is not set up i tried to include inapp billing in my app and for the purpose of testing based the whole procedure on the trivialdrive example for version 3 of inapp billing and implementing the unmodified versions of the iab files as supplied in the util subdirectory of the demo but it does not work for me on logcat just before the app terminates with an error it gives the message inapp billing error illegal state for operation launchpurchaseflow iab helper is not set up right after the startregistered function has been fired and given me the log message register button clicked launching purchase flow for upgradeany idea what goes wrong here here are the relevant parts of my codepackage commytestimport commytestiabiabhelper the originals from the demo example unmodifiedimport commytestiabiabresultimport commytestiabinventoryimport commytestiabpurchasepublic class result3 extends activity implements onclicklistener private static final string tag billingserviceprivate context mcontextboolean misregistered false this has already been set up for my app at the publishers consolestatic final string is registered myregisteredstatic final int rc request 101 the helper objectiabhelper mhelper call when the activity is first created overridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutresult3 mcontext this string base64encodedpublickey my public key from publishers console for my app create the helper passing it our context and the public key to verify signatures with logdtag creating iab helper mhelper new iabhelperthis base64encodedpublickey enable debug logging for a production application you should set this to false mhelperenabledebugloggingtrue start setup this is asynchronous and the specified listener will be called once setup completes logdtag starting setup mhelperstartsetupnew iabhelperoniabsetupfinishedlistener public void oniabsetupfinishediabresult result logdtag setup finished if resultissuccess complainproblem setting up inapp billing result return hooray iab is fully set up now let us get an inventory of stuff we own logdtag setup successful querying inventory mhelperqueryinventoryasyncmgotinventorylistener set the onclick listeners findviewbyidridbtnpurchasesetonclicklistenerthis listener that is called when we finish querying the items we owniabhelperqueryinventoryfinishedlistener mgotinventorylistener new iabhelperqueryinventoryfinishedlistener public void onqueryinventoryfinishediabresult result inventory inventory logdtag query inventory finished if resultisfailure complainfailed to query inventory result return logdtag query inventory was successful do we have the premium upgrade misregistered inventoryhaspurchaseis registered logdtag user is misregistered registered not registered setwaitscreenfalse logdtag initial inventory query finished enabling main ui user clicked the register buttonprivate void startregistered logdtag register button clicked launching purchase flow for upgrade setwaitscreentrue mhelperlaunchpurchaseflowthis is registered rc request mpurchasefinishedlisteneroverrideprotected void onactivityresultint requestcode int resultcode intent data logdtag onactivityresult requestcode resultcode data pass on the activity result to the helper for handling if mhelperhandleactivityresultrequestcode resultcode data not handled so handle it ourselves heres where youd perform any handling of activity results not related to inapp billing superonactivityresultrequestcode resultcode data else logdtag onactivityresult handled by iabutil callback for when a purchase is finishediabhelperoniabpurchasefinishedlistener mpurchasefinishedlistener new iabhelperoniabpurchasefinishedlistener public void oniabpurchasefinishediabresult result purchase purchase logdtag purchase finished result purchase purchase if resultisfailure oh noes complainerror purchasing result setwaitscreenfalse return logdtag purchase successful if purchasegetskuequalsis registered logdtag user has registered alertthank you misregistered true setwaitscreenfalse were being destroyed it is important to thispose of the helper hereoverridepublic void ondestroy very important logdtag destroying helper if mhelper null mhelperthispose mhelper nullvoid complainstring message logetag register error message alerterror messagevoid setwaitscreenboolean set just a dummy for nowvoid alertstring message alertdialogbuilder bld new alertdialogbuilderthis bldsetmessagemessage bldsetneutralbuttonok null logdtag showing alert dialog message bldcreateshowoverridepublic void onclickview v switch vgetid case ridbtnpurchase startregistered break default break here more lines from logcat1220 010636701 ddalvikvm299 gc for malloc freed 4262 objects 308592 bytes in 84ms1220 010636701 dwebviewglue299 nativedestroy view 0x2ea7181220 010636771 wwebcore299 cannot get the viewwidth after the first layout1220 0107071 wwebcore299 cannot get the viewwidth after the first layout1220 010718510 dwebviewglue299 nativedestroy view 0x2dd4581220 010718510 ddalvikvm299 gc for malloc freed 6042 objects 544504 bytes in 50ms1220 010718530 dwebviewglue299 nativedestroy view 0x2ea8d01220 010718660 dbillingservice299 creating iab helper1220 010718660 dbillingservice299 starting setup1220 010718660 diabhelper299 starting inapp billing setup1220 010719621 wwebcore299 cannot get the viewwidth after the first layout1220 010720160 wwebcore299 cannot get the viewwidth after the first layout1220 010732481 dwebviewglue299 nativedestroy view 0x3f88e81220 010732491 ddalvikvm299 gc for malloc freed 5798 objects 513640 bytes in 50ms1220 010732511 dbillingservice299 register button clicked launching purchase flow for upgrade 1220 010732511 eiabhelper299 inapp billing error illegal state for operation launchpurchaseflow iab helper is not set up1220 010732521 dandroidruntime299 shutting down vm1220 010732521 wdalvikvm299 threadid1 thread exiting with uncaught exception group0x4001d8001220 010732541 eandroidruntime299 fatal exception main1220 010732541 eandroidruntime299 javalangillegalstateexception iab helper is not set up cannot perform operation launchpurchaseflow1220 010732541 eandroidruntime299 at comtest ediabiabhelperchecksetupdoneiabhelperjava6731220 010732541 eandroidruntime299 at comtest ediabiabhelperlaunchpurchaseflowiabhelperjava3151220 010732541 eandroidruntime299 at comtest ediabiabhelperlaunchpurchaseflowiabhelperjava2941220 010732541 eandroidruntime299 at comtest edresult3startregisteredresult3java1571220 010732541 eandroidruntime299 at comtest edresult3onclickresult3java2481220 010732541 eandroidruntime299 at androidviewviewperformclickviewjava24081220 010732541 eandroidruntime299 at androidviewviewperformclickrunviewjava88161220 010732541 eandroidruntime299 at androidoshandlerhandlecallbackhandlerjava5871220 010732541 eandroidruntime299 at androidoshandlerthispatchmessagehandlerjava921220 010732541 eandroidruntime299 at androidoslooperlooplooperjava1231220 010732541 eandroidruntime299 at androidappactivitythreadmainactivitythreadjava46271220 010732541 eandroidruntime299 at javalangreflectmethodinvokenativenative method1220 010732541 eandroidruntime299 at javalangreflectmethodinvokemethodjava5211220 010732541 eandroidruntime299 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava8681220 010732541 eandroidruntime299 at comandroidinternaloszygoteinitmainzygoteinitjava6261220 010732541 eandroidruntime299 at dalviksystemnativestartmainnative method,['android'] +393615,meaning of red color in androids ninepatch drawables according to the android documentation we know that the left and top black line define the stretchable area and the bottom and right line define the content areait is easy to understand but i found the below image named textfield activated holo dark9png from android17 framework what is the purpose of the red colors in the lowerleft lowerright and topright corners,['android'] +393616,jqueryjavascript check if var exists possible duplicatehow can i check whether a variable is defined in javascriptis there a standard function to check for null undefined or blank variables in javascript i have a script that occurs in two partsthe first part sets up a varvar pagetype textpagethe 2nd part is a simple if statementifpagetype textpage do somethingnow the 2nd part the if statement appears on all pages of my site but the first part where the var is declared only appears on some of my pageson the pages without the var i naturally get this erroruncaught referenceerror pagetype is not definedso my question is is there a way with javascript or jq to detect if a var exists at all not just if it has data assigned to iti am imagining i would just use another if statment egif a var called pagetypes exists,"['javascript', 'jquery']" +393625,llvm clang cannot compile for a supported arch under ubuntu 64 bit i gotllc versionllvm llvm version 31 optimized build with assertions built oct 15 2012 181559 default target x86 64pclinuxgnu host cpu btver1 registered targets arm arm mips mips mips64 mips64 experimental mips64el mips64el experimental mipsel mipsel thumb thumb x86 32bit x86 pentiumpro and above x8664 64bit x86 em64t and amd64i cannot do thisclang marcharm x c tmpcppcpp error unknown target cpu armi am missing something here why i cannot compile for arm,['c++'] +393633,fastest way to removehide a lot of elements from a list i have a dropdown that contains around 10 rows which make up a listinput idsearch typetext ul liitem 1li liitem 2li liitem 10liuli have a text box which acts as a search so as you type it matches the input to items in the list removing what does not match this is the class i wrote to perform the removing of list elementssee the fiddle list has about 20 items requires jqueryvar search function var cls function name var self this selfelem name selflist namenextulchildren selfelembindkeyup function selfchange clsprototype change function var self this gets the closest ul list var typed selfelemval only do something if there is something typed if typed remove irrelevent items from the list selflisteachfunction var item thishtml if itemindexoftyped 1 thisaddclasszero tried using a class with visibility hidden else thisremoveclasszero else check what list items are hidden and unhide them selflisteachfunction if thishasclasszero thisremoveclasszero return clsi am just adding a class which adds a height of 0 and no marginpadding etc but i have also tried using visibilityhidden i have also tried using the detach method in jquery but this is about the same in terms of speed are their any javascript experts who can see any problems with the code or offer some optimization techniques,['javascript'] +393644,facebook javascript sdk uncaught typeerror cannot read property userid of undefined i am trying to implement an authorization feature using the facebook javascript sdk when i run it it and check the console i see the error uncaught typeerror cannot read property userid of undefined code snippetdiv idfbrootdiv load the facebook javascript sdk script srcconnectfacebookneten usalljsscriptscriptvar appid app idvar uid initialize the js sdkfbinit appid 413026618765431 cookie true get the users uidfbgetloginstatusfunctionresponse uid responseauthresponseuserid responseauthresponseuserid nullfunction authuser fbloginfunctionresponse uid responseauthresponseuserid responseauthresponseuserid null scopeemailpublish actionsscript,['javascript'] +393654,how to have value sent once clicking on a post queried from database in wordpress i am trying to create an overview function using colorbox in wordpress let me explain a little in wordpress pages have posts that are queried through this code lastposts get posts args foreachlastposts as post setup postdatapost get template part content get post format endforeachso this will grab all the posts that are in the wordpress database now each post is a product so i want to know if there is a way i can add some code to this to have a value set to each post that once someone clicks on the post image it will send the title of that post so it can grab an overview template something i will make of that specific productupdatehere is the jquery that opens once any image is clickedlink mediascreen relstylesheet hrefphp echo get template directory uri jscolorboxcss script srcphp echo get template directory uri jsjquerycolorboxminjs typetextjavascriptscriptscript typetextjavascript function itempost acolorboxopacity03 hrefoverviewa512454dzdtfa scripti want the title of the post the image is associated with sent to the file that is opened in colorbox,['php'] +393660,no property found for type error when try to create custom repository with spring data jpa i have a media entity that has some basic fields for files uploaded by the user for saving the bytes of the files uploaded i want to create a custom repository that holds that functionality following the steps in the spring documentation i have created an interface that looks like thispublic interface mediabytesrepository public byte getbytesmedia media throws ioexception public void savebytesmedia media byte bytes throws ioexception public void appendbytesmedia media byte bytes throws ioexception public void deletebytesmedia media throws ioexception public boolean bytesexistmedia media throws ioexceptionthen i provided an implementation for this interface called mediabytesrepositoryimplwith this i then created the following interfacepublic interface mediarepository extends jparepositorymedia long mediabytesrepositorynow when i start up the server i get the following stack tracesevere exception sending context initialized event to listener instance of class orgspringframeworkwebcontextcontextloaderlistenerorgspringframeworkbeansfactorybeancreationexception error creating bean with name mediarepository factorybean threw exception on object creation nested exception is javalangillegalargumentexception could not create query metamodel for method public abstract void comfoobarcoremediamediabytesrepositorysavebytescomfoobarcoremediamediabyte throws javaioioexception at orgspringframeworkbeansfactorysupportfactorybeanregistrysupportdogetobjectfromfactorybeanfactorybeanregistrysupportjava149caused by javalangillegalargumentexception could not create query metamodel for method public abstract void comfoobarcoremediamediabytesrepositorysavebytescomfoobarcoremediamediabyte throws javaioioexception at orgspringframeworkdatajparepositoryqueryjpaquerylookupstrategycreatequerylookupstrategyresolvequeryjpaquerylookupstrategyjava92 at orgspringframeworkdatajparepositoryqueryjpaquerylookupstrategycreateifnotfoundquerylookupstrategyresolvequeryjpaquerylookupstrategyjava162 at orgspringframeworkdatajparepositoryqueryjpaquerylookupstrategyabstractquerylookupstrategyresolvequeryjpaquerylookupstrategyjava68 at orgspringframeworkdatarepositorycoresupportrepositoryfactorysupportqueryexecutormethodinterceptorinitrepositoryfactorysupportjava280 at orgspringframeworkdatarepositorycoresupportrepositoryfactorysupportgetrepositoryrepositoryfactorysupportjava148 at orgspringframeworkdatarepositorycoresupportrepositoryfactorybeansupportgetobjectrepositoryfactorybeansupportjava125 at orgspringframeworkdatarepositorycoresupportrepositoryfactorybeansupportgetobjectrepositoryfactorybeansupportjava41 at orgspringframeworkbeansfactorysupportfactorybeanregistrysupportdogetobjectfromfactorybeanfactorybeanregistrysupportjava142 20 more caused by javalangillegalargumentexception no property save found for type class comfoobarcoremediamedia at orgspringframeworkdatamappingpropertypathinitpropertypathjava73 at orgspringframeworkdatamappingpropertypathinitpropertypathjava92 at orgspringframeworkdatamappingpropertypathcreatepropertypathjava319 at orgspringframeworkdatamappingpropertypathcreatepropertypathjava3 at orgspringframeworkdatamappingpropertypathcreatepropertypathjava301 at orgspringframeworkdatamappingpropertypathfrompropertypathjava265 at orgspringframeworkdatamappingpropertypathfrompropertypathjava239 at orgspringframeworkdatarepositoryqueryparserpartinitpartjava70 at orgspringframeworkdatarepositoryqueryparserparttreeorpartinitparttreejava180 at orgspringframeworkdatarepositoryqueryparserparttreepredicatebuildtreeparttreejava260 at orgspringframeworkdatarepositoryqueryparserparttreepredicateinitparttreejava240 at orgspringframeworkdatarepositoryqueryparserparttreeinitparttreejava68 at orgspringframeworkdatajparepositoryqueryparttreejpaqueryinitparttreejpaqueryjava57 at orgspringframeworkdatajparepositoryqueryjpaquerylookupstrategycreatequerylookupstrategyresolvequeryjpaquerylookupstrategyjava90 27 morei found this similar post but the suggestions there all in same package naming convention are things i am already doing all my media classes and interfaces are in the same package and i am using the impl suffixcan someone please shed some light on why i am getting this error and how i can fix it thanks,['java'] +393682,embedding boo in c does not recognise executing assembly scriptsaidreambooimport cultlibimport lonelyheroclass dreamenemy passcvar bc new boocompilerbcparametersinputaddnew fileinputrscscriptai dream boobcparameterspipeline new compiletomemorybcparametersreferencesaddassemblygetexecutingassemblybcparametersreferencesaddassemblyloadfilenew directoryinfocultlibdllfullnamebcparametersreferencesaddassemblyloadfilenew directoryinfosfmlnetaudio2dllfullnamebcparametersreferencesaddassemblyloadfilenew directoryinfosfmlnetgraphics2dllfullnamebcparametersreferencesaddassemblyloadfilenew directoryinfosfmlnetwindow2dllfullnamevar cc bcrunifccgeneratedassemblynull ccgeneratedassemblycreateinstancedream true bindingflagsnonpublic null new object parent pos null nullelse foreach var error in ccerrors consolewritelineerrorin the line bcparametersreferencesaddassemblygetexecutingassembly i add the executing assembly which contains the namespace lonelyhero however the errorrscscriptaidreamboo2 8 bce0021 namespace lonelyhero not found maybe you forgot to add an assembly referenceappearslonelyhero should exist why does this error occur and what can i do to resolve itnoteupon replacing assemblygetexecutingassmebly with assemblygetassemblytypeofenemy thus assuring it adds the assembly with a class under the lonelyhero namespace the same error occurs also with assemblyloadfilenew directoryinfolonelyheroexefullnameoccurs in boo 0949 and booxw1203,['c#'] +393699,pyinstaller 20 bundle file as onefile i am trying to bundle my py script as an exe using pyinstaller 20 i am able to bundle the script but in my script i need to open a file that should be bundled in the exe so it is portable i am having trouble doing thisin my py i have filename cpathtomyfiledocdocxdata openfilenamerbi use pyinstaller 20 and this works fine on my computer but if i transfer the exe to another computer it is not going to work pyinstaller 20 is pretty new so there are very few documents on it and the publishers documentation is quite lackinghere is the publishers info on the matter i do not think their documentation is up to date because in the beginning it says use configurepy then in other docs it says configurepy is no longer needed in 20in a onefile thistribution data files are bundled within the executable and then extracted at runtime into the work directory by the c code which is also able to reconstruct directory trees the work directory is best found by osenviron meipass2 so you can access those files throughospathjoinosenviron meipass2 relativenamethat does not really make sense to me a beginning programmera different document from the publisher saysin a onefile thistribution data files are bundled within the executable and then extracted at runtime into the work directory by the c code which is also able to reconstruct directory trees the work directory is best found by sys meipass so you can access those files throughospathjoinsys meipass relativenamei have experimented around quite a bit with osenviron meipass2 and python does not seem to understand osenvironment meipass2 i get this back print osenviron meipass2traceback most recent call last file pyshell0 line 1 in module print osenviron meipass2 file cpython27libospy line 423 in getitem return selfdatakeyupperkeyerror meipass2i also experimented with sys meipass yeah python responds module has no attribute meipassat this point i feel like my head is about to explode i appreciate pyinstallers authors for their work but their documentation is the worst i have ever seen i just need someone to help me bundle my file into the exe i would really like to use pyinstaller 20 since all the spec stuff confuses me with previous versions of pyinstallerbtw i am using win8 64bit with python 273please help,['python'] +393703,is there any method like foreach for ilist possible duplicatelinq equivalent of foreach for ienumerablet all i know listt has a method called foreach can easily performs the specified action on each element of it liststring names new liststring namesaddbruce namesaddalfred namesaddtim namesaddrichardnamesforeachp consolewritelinep but what if names is not a listt but an ilistt ilistt does not has a method like foreach how to make it thanks,['c#'] +393739,rules for using references in c possible duplicatehow to pass objects to functions in cwhy pass by const reference instead of by value in c is there a kind of rule or guidance of when exactly one must or at least should opt for using pass by references than by value and if is about the size of the object with some object as far as know little honestly it can become difficult to judge,['c++'] +393745,error in masterpage namespace already exists i want to add some code into my masterpage so i removed the namespace but when i want to test it it gives this error no idea how to fix thiserror 2 the namespace project in cuserstestappdatalocaltemptemporary aspnet filesprojectfe95a5506aff5a12assemblydl39f54421ae011b011 23bccd01projectdll conflicts with the type project in cuserstestappdatalocaltemptemporary aspnet filesprojectfe95a5506aff5a12app web exfemb4udll cuserstestappdatalocaltemptemporary aspnet filesprojectfe95a5506aff5a12app web hrdlxq5l4cs 154 masterpagecspublic partial class project systemwebuimasterpage protected void page loadobject sender eventargs e masterpage master languagec autoeventwireuptrue codefileprojectmastercs inheritsproject,"['c#', 'asp.net']" +393747,meaning of port in eclipse debug view in the eclipse debug viewwhat is the meaning of the localhost51883 is it the connection port for remote debugging or is something else,['java'] +393753,static initializer runs after the constructor why i have 2 classesclass apublic class a static b b new b static systemoutprintlna static block public a systemoutprintlna constructor class bpublic class b static systemoutprintlnb static block new a public b systemoutprintlnb constructor i create a main class which just creates new apublic class main public static void mainstring args new a the output i get isb static blocka constructorb constructora static blocka constructoras you can see the constructor of a is invoked before its static initializer i understand it got something to do with the cyclic dependency i created but i was under the impression the static initializer should always run before the constructorwhat is the reason for this to happen technically in the java implementation is it recommended to avoid static initializers all together,['java'] +393761,how to move canvas speedometer needle slowly i use following codes in order to move a picture in canvas for my speedometervar meter new image needle new imagewindowonload function var c documentgetelementsbytagnamecanvas0 var ctx cgetcontext2d setintervalfunction ctxsave ctxclearrect0 0 cwidth cheight ctxtranslatecwidth 2 cheight 2 ctxdrawimagemeter 165 160 ctxrotatex mathpi 180 x degree ctxdrawimage needle 13 1215 ctxrestore 50 metersrc meterpng needlesrc needlepng however i want to move the needle slowly to the degree which i entered such as speedtest webpages any ideathanks,['html'] +393767,localbroadcastmanager vs using callbacks androids compatibility pack supports localbroadcastmanager which enables sending broadcasts within my processuntil now i was using callbacks interfaces similar to onclicklistener to transfer data asynchronous and synchronous between different parts of my appsi was wondering if one is better then the otherany opinions,['android'] +393796,what is wrong with this database connection string i am trying to connect to my remote mysql server using the following code can you tell me what i am doing wrong as the replacement of database connection info with variables does not seem to be working using mysqldatamysqlclient string db server 10 string db name mydatabase string db user myuser string db pass mypassword connection string mysqlconnection myconnection new mysqlconnectionserver 0 database 1 uid 2 pwd 3 db server db name db user db passas a php developer i prefer to use the code above instead of the deliberate casting below mysqlconnection myconnection new mysqlconnectionserver10 databasemydatabase uidmyuser pwdmypasswordbut as you can see in this image i am getting a lot of red squiggles,"['c#', 'mysql']" +393810,why does the java increment operator allow narrowing operations without explicit cast possible duplicatejava operator in java this is not valid does not compile as expectedlong lng 0xflint ii 5 lng error possible loss of magnitudebut this is perfectly fine long lng 0xflint i 5i lng compiles just finethis is obviously a narrowing operation that can possibly exceed the int range so why does not the compiler complain,['java'] +393820,how to pass qlist from qml to cqt i am trying to pass qlist of integer from qml to c code but somehow my approach is not working with below approach am getting following errorleft of setparentitem must point to clastructuniongeneric typetype is int any inputs to trouble shoot the issue is highly appreciatedbelow is my code snippetheader fileq propertyqdeclarativelistpropertyint enablekey read enablekey qdeclarativelistpropertyint enablekey function declarationqlistint m enablekeyscpp fileqdeclarativelistpropertyint keyboardcontainerenablekey return qdeclarativelistpropertyintthis 0 keyboardcontainerappend listvoid keyboardcontainerappend listqdeclarativelistpropertyint list int key int ptrkey qobject castint listobject if ptrkey keysetparentitemptrkey ptrkeym enablekeysappendkey,['c++'] +393831,thisplay sound waves for audio recording in android how can we thisplay sound waves as thisplayed in below imagewhen user speaks the yellow bars will animate based on users volumeplease guide me is there any reference link available is there any sample tutorial availablesame question in iphone but i wants to it in android,['android'] +393842,opencv or boost smart pointers i have an expanding image processing project which relies heavily on the opencv library for much of its functionality although i do also use a few boost functions as welli would like to start using smart pointers to replace some raw pointers which are beginning to cause problems my question is on which type of smart pointer to use with my main choices i think being the opencv cvptr or one of the boost variantsi realise there are a number of questions explaining the different between each of the boost pointers but i hoped somebody could offer an explanation of how cvptr compares with them and make any recommendations of one or the otheredit i have noticed from the opencv docs that ptr is similar to boost shared ptr is the essential difference just which libraryinclude files are required,['c++'] +393862,java springquartz basic tutorial code not working i am trying to get a basic example of spring and quartz to work here is the tutorial i am following i have copied everything as exactly as far as i can tell but i do not see anything in the output windowspringquartzxmlbeans xmlns xmlnsxsi xsischemalocation bean idrunmetask classcomkscjobsrunmetask spring quartz bean namerunmejob classorgspringframeworkschedulingquartzjobdetailbean property namejobclass valuecomkscjobsrunmejob property namejobdataasmap map entry keyrunmetask valuerefrunmetask map property bean bean idsimpletrigger classorgspringframeworkschedulingquartzsimpletriggerbean property namejobdetail refrunmejob property namerepeatinterval value50 property namestartdelay value10 bean bean classorgspringframeworkschedulingquartzschedulerfactorybean property namejobdetails list ref beanrunmejob list property property nametriggers list ref beansimpletrigger list property beanbeansapplicationcontextxmlxml version10 encodingutf8beans xmlns xmlnsxsi xsischemalocation import resourcespringquartzxmlbeansproject structureeditdo i need to manually start the job somehow i see in that tutorial and in others they usually start a quartz job inside a main method coming from a net background that seems a little odd to me as i only know main methods to be in desktop apps not web apps in aspnet we have globalasax where we can call code to run when the web app starts is there some equivalent in java or maybe this is not even the problem at all i am just guessing here if anyone has any idea about how to solve this or even just gives me a working sample can be different to the one above even i am not fussy then i would most appreciate it i just need a basic working sample that i can then later modify to my requirementsedit 2heres the glassfish server output if it helpsnote removed due to body length of this post being too long else i wouldnt be able to post edit 3 belowedit 3some progress but still not working i have added the log4j file as suggested by shuttsy and here is the new output from glassfishlaunching glassfish on felix platforminfo running glassfish version glassfish server open source edition 3122 build 5info registered orgglassfishhastoreadaptercacheshoalbackingstoreproxy for persistencetype replicated in backingstorefactoryregistryinfo grizzly framework 1950 started in 0ms bound to 03700info grizzly framework 1950 started in 31ms bound to 08080info grizzly framework 1950 started in 15ms bound to 08181info grizzly framework 1950 started in 15ms bound to 04848info grizzly framework 1950 started in 0ms bound to 07676info the admin console is already installed but not yet loadedinfo glassfish server open source edition 3122 5 startup time felix 1750ms startup services771ms total2521msinfo hv01 hibernate validator 430finalinfo jmx005 jmxstartupservice had started jmxconnector on jmxservice url servicejmxrmimattlaptop8686jndirmimattlaptop8686jmxrmiinfo grizzly framework 1950 started in 0ms bound to 08080info grizzly framework 1950 started in 0ms bound to 08181info created ejbthreadpoolexecutor with threadcorepoolsize 16 threadmaxpoolsize 32 threadkeepaliveseconds 60 threadqueuecapacity 2147483647 allowcorethreadtimeout false info sec1002 security manager is offinfo sec1010 entering security startup serviceinfo sec1143 loading policy provider comsunenterprisesecurityproviderpolicywrapperinfo sec15 realm adminrealm of classtype comsunenterprisesecurityauthrealmfilefilerealm successfully createdinfo sec15 realm file of classtype comsunenterprisesecurityauthrealmfilefilerealm successfully createdinfo sec15 realm certificate of classtype comsunenterprisesecurityauthrealmcertificatecertificaterealm successfully createdinfo sec1011 security services started successfullyinfo web0169 created http listener httplistener1 on hostport 08080info web0169 created http listener httplistener2 on hostport 08181info web0169 created http listener adminlistener on hostport 04848info web0171 created virtual server serverinfo web0171 created virtual server asadmininfo web0172 virtual server server loaded default web module severe exception while visiting comsungjcspijdbcobjectsfactoryclass of size 3615javalangnullpointerexception at orgglassfishhk2classmodelreflectimpltypesimplgettypetypesimpljava78 at orgglassfishhk2classmodelreflectimplmodelclassvisitorvisitmodelclassvisitorjava119 at orgobjectwebasmclassreaderacceptunknown source at orgobjectwebasmclassreaderacceptunknown source at orgglassfishhk2classmodelreflectparser5onparserjava363 at orgglassfishhk2classmodelreflectutiljararchiveonselectedentriesjararchivejava125 at orgglassfishhk2classmodelreflectparserdojobparserjava348 at orgglassfishhk2classmodelreflectparseraccess300parserjava70 at orgglassfishhk2classmodelreflectparser3callparserjava307 at orgglassfishhk2classmodelreflectparser3callparserjava296 at javautilconcurrentfuturetasksyncinnerrunfuturetaskjava334 at javautilconcurrentfuturetaskrunfuturetaskjava166 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava10 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava603 at javalangthreadrunthreadjava722info eclipselink version eclipse persistence services 232v20125r10461info filecusersmattdocumentsnetbeansprojectskscbuildwebwebinfclasses kscpu login successfulwarning multiple 2 jmx mbeanserver instances exist we will use the server at index 0 comsunenterprisev3admindynamicinterceptor282458warning jmx mbeanserver in use comsunenterprisev3admindynamicinterceptor282458 from index 0 warning jmx mbeanserver in use comsunjmxmbeanserverjmxmbeanserver3a683b33 from index 1 severe log4jerror log4j called after unloading see severe javalangillegalstateexception class invariant violation at orgapachelog4jlogmanagergetloggerrepositorylogmanagerjava199 at orgapachelog4jlogmanagergetloggerlogmanagerjava228 at orgslf4jimpllog4jloggerfactorygetloggerlog4jloggerfactoryjava64 at orgslf4jloggerfactorygetloggerloggerfactoryjava253 at orgapachecommonsloggingimplslf4jlogfactorygetinstanceslf4jlogfactoryjava156 at orgapachecommonsloggingimplslf4jlogfactorygetinstanceslf4jlogfactoryjava132 at orgapachecommonslogginglogfactorygetloglogfactoryjava272 at orgspringframeworkbeanstypeconverterdelegateclinittypeconverterdelegatejava53 at sunmiscunsafeensureclassinitializednative method at sunreflectunsafefieldaccessorfactorynewfieldaccessorunsafefieldaccessorfactoryjava43 at sunreflectreflectionfactorynewfieldaccessorreflectionfactoryjava140 at javalangreflectfieldacquirefieldaccessorfieldjava949 at javalangreflectfieldgetfieldaccessorfieldjava930 at javalangreflectfieldgetfieldjava372 at orgglassfishwebloaderwebappclassloaderclearreferenceswebappclassloaderjava1833 at orgglassfishwebloaderwebappclassloaderstopwebappclassloaderjava1662 at orgglassfishwebloaderwebappclassloaderpredestroywebappclassloaderjava1631 at orgglassfishdeploymentcommondeploymentcontextimplgetclassloaderdeploymentcontextimpljava236 at orgglassfishdeploymentcommondeploymentcontextimplgetclassloaderdeploymentcontextimpljava186 at comsunenterprisev3serverapplicationlifecycledeployapplicationlifecyclejava450 at comsunenterprisev3serverapplicationlifecycledeployapplicationlifecyclejava240 at orgglassfishdeploymentadmindeploycommandexecutedeploycommandjava389 at comsunenterprisev3admincommandrunnerimpl1executecommandrunnerimpljava348 at comsunenterprisev3admincommandrunnerimpldocommandcommandrunnerimpljava363 at comsunenterprisev3admincommandrunnerimpldocommandcommandrunnerimpljava1085 at comsunenterprisev3admincommandrunnerimplaccess1200commandrunnerimpljava95 at comsunenterprisev3admincommandrunnerimplexecutioncontextexecutecommandrunnerimpljava1291 at comsunenterprisev3admincommandrunnerimplexecutioncontextexecutecommandrunnerimpljava1259 at comsunenterprisev3adminadminadapterdocommandadminadapterjava461 at comsunenterprisev3adminadminadapterserviceadminadapterjava212 at comsungrizzlytcphttp11grizzlyadapterservicegrizzlyadapterjava179 at comsunenterprisev3serverhk2thispatcherthispathhk2thispatcherjava117 at comsunenterprisev3servicesimplcontainermapperhk2thispatchercallablecallcontainermapperjava354 at comsunenterprisev3servicesimplcontainermapperservicecontainermapperjava195 at comsungrizzlyhttpprocessortaskinvokeadapterprocessortaskjava860 at comsungrizzlyhttpprocessortaskdoprocessprocessortaskjava757 at comsungrizzlyhttpprocessortaskprocessprocessortaskjava1056 at comsungrizzlyhttpdefaultprotocolfilterexecutedefaultprotocolfilterjava229 at comsungrizzlydefaultprotocolchainexecuteprotocolfilterdefaultprotocolchainjava137 at comsungrizzlydefaultprotocolchainexecutedefaultprotocolchainjava104 at comsungrizzlydefaultprotocolchainexecutedefaultprotocolchainjava90 at comsungrizzlyhttphttpprotocolchainexecutehttpprotocolchainjava79 at comsungrizzlyprotocolchaincontexttaskdocallprotocolchaincontexttaskjava54 at comsungrizzlyselectionkeycontexttaskcallselectionkeycontexttaskjava59 at comsungrizzlycontexttaskruncontexttaskjava71 at comsungrizzlyutilabstractthreadpoolworkerdoworkabstractthreadpooljava532 at comsungrizzlyutilabstractthreadpoolworkerrunabstractthreadpooljava513 at javalangthreadrunthreadjava722severe at orgapachelog4jlogmanagergetloggerrepositorylogmanagerjava199severe at orgapachelog4jlogmanagergetloggerlogmanagerjava228severe at orgslf4jimpllog4jloggerfactorygetloggerlog4jloggerfactoryjava64severe at orgslf4jloggerfactorygetloggerloggerfactoryjava253severe at orgapachecommonsloggingimplslf4jlogfactorygetinstanceslf4jlogfactoryjava156severe at orgapachecommonsloggingimplslf4jlogfactorygetinstanceslf4jlogfactoryjava132severe at orgapachecommonslogginglogfactorygetloglogfactoryjava272severe at orgspringframeworkbeanstypeconverterdelegateclinittypeconverterdelegatejava53severe at sunmiscunsafeensureclassinitializednative methodsevere at sunreflectunsafefieldaccessorfactorynewfieldaccessorunsafefieldaccessorfactoryjava43severe at sunreflectreflectionfactorynewfieldaccessorreflectionfactoryjava140severe at javalangreflectfieldacquirefieldaccessorfieldjava949severe at javalangreflectfieldgetfieldaccessorfieldjava930severe at javalangreflectfieldgetfieldjava372severe at orgglassfishwebloaderwebappclassloaderclearreferenceswebappclassloaderjava1833severe at orgglassfishwebloaderwebappclassloaderstopwebappclassloaderjava1662severe at orgglassfishwebloaderwebappclassloaderpredestroywebappclassloaderjava1631severe at orgglassfishdeploymentcommondeploymentcontextimplgetclassloaderdeploymentcontextimpljava236severe at orgglassfishdeploymentcommondeploymentcontextimplgetclassloaderdeploymentcontextimpljava186severe at comsunenterprisev3serverapplicationlifecycledeployapplicationlifecyclejava450severe at comsunenterprisev3serverapplicationlifecycledeployapplicationlifecyclejava240severe at orgglassfishdeploymentadmindeploycommandexecutedeploycommandjava389severe at comsunenterprisev3admincommandrunnerimpl1executecommandrunnerimpljava348severe at comsunenterprisev3admincommandrunnerimpldocommandcommandrunnerimpljava363severe at comsunenterprisev3admincommandrunnerimpldocommandcommandrunnerimpljava1085severe at comsunenterprisev3admincommandrunnerimplaccess1200commandrunnerimpljava95severe at comsunenterprisev3admincommandrunnerimplexecutioncontextexecutecommandrunnerimpljava1291severe at comsunenterprisev3admincommandrunnerimplexecutioncontextexecutecommandrunnerimpljava1259severe at comsunenterprisev3adminadminadapterdocommandadminadapterjava461severe at comsunenterprisev3adminadminadapterserviceadminadapterjava212severe at comsungrizzlytcphttp11grizzlyadapterservicegrizzlyadapterjava179severe at comsunenterprisev3serverhk2thispatcherthispathhk2thispatcherjava117severe at comsunenterprisev3servicesimplcontainermapperhk2thispatchercallablecallcontainermapperjava354severe at comsunenterprisev3servicesimplcontainermapperservicecontainermapperjava195severe at comsungrizzlyhttpprocessortaskinvokeadapterprocessortaskjava860severe at comsungrizzlyhttpprocessortaskdoprocessprocessortaskjava757severe at comsungrizzlyhttpprocessortaskprocessprocessortaskjava1056severe at comsungrizzlyhttpdefaultprotocolfilterexecutedefaultprotocolfilterjava229severe at comsungrizzlydefaultprotocolchainexecuteprotocolfilterdefaultprotocolchainjava137severe at comsungrizzlydefaultprotocolchainexecutedefaultprotocolchainjava104severe at comsungrizzlydefaultprotocolchainexecutedefaultprotocolchainjava90severe at comsungrizzlyhttphttpprotocolchainexecutehttpprotocolchainjava79severe at comsungrizzlyprotocolchaincontexttaskdocallprotocolchaincontexttaskjava54severe at comsungrizzlyselectionkeycontexttaskcallselectionkeycontexttaskjava59severe at comsungrizzlycontexttaskruncontexttaskjava71severe at comsungrizzlyutilabstractthreadpoolworkerdoworkabstractthreadpooljava532severe at comsungrizzlyutilabstractthreadpoolworkerrunabstractthreadpooljava513severe at javalangthreadrunthreadjava722info ejb5181portable jndi names for ejb eventapplicationservice javaglobalksceventapplicationservicecomkscserviceseventapplicationservice javaglobalksceventapplicationserviceinfo ejb5181portable jndi names for ejb sitesettingservice javaglobalkscsitesettingservicecomkscservicessitesettingservice javaglobalkscsitesettingserviceinfo ejb5181portable jndi names for ejb eventsservice javaglobalksceventsservice javaglobalksceventsservicecomkscserviceseventsserviceinfo ejb5181portable jndi names for ejb userservice javaglobalkscuserservice javaglobalkscuserservicecomkscservicesuserserviceinfo ejb5181portable jndi names for ejb roleservice javaglobalkscroleservicecomkscservicesroleservice javaglobalkscroleserviceinfo ejb5181portable jndi names for ejb announcementservice javaglobalkscannouncementservicecomkscservicesannouncementservice javaglobalkscannouncementserviceinfo ejb5181portable jndi names for ejb userinroleservice javaglobalkscuserinroleservice javaglobalkscuserinroleservicecomkscservicesuserinroleserviceinfo weld0900 118 finalinfo pwc1412 webmodulenull servletcontextlogno spring webapplicationinitializer types detected on classpathinfo pwc1412 webmodulenull servletcontextloginitializing spring root webapplicationcontextsevere log4jwarn no appenders could be found for logger orgspringframeworkwebcontextcontextloadersevere log4jwarn please initialize the log4j system properlysevere log4jwarn see for more infoinfo pwc1412 webmodulenull servletcontextloginitializing spring frameworkservlet thispatcherinfo web0671 loading application ksc at kscinfo ksc was successfully deployed in 10070 millisecondsso we have a new error here which may or may not be related to my original question about quartz it seems the error is jdbc related i am using sqljdbc4 driver id11774,['java'] +393864,join a specific boost thread i m creating about 300 boost threads in a processis there any way to join a specific thread based on the thread id,['c++'] +393875,aligning div right next to the list items i am trying to create div elements and print items on to them dynamically i have created a demo to show where i have reached the issue with my code is that it does not show up right next to the list where i want it instead it is thisplayed at the bottom is it possible to show the new div right next to the element that i am hovering overbubblelive mouseenter function bubbleshow bubblehtmlthisattrid mouseleave function bubbleempty bubble width100px height20px backgroundcolor6 positionabsolute thisplayhiddenul lispan classbubble idtest1test1spanli lispan classbubble idtest2test2spanli lispan classbubble idtest3test3spanli lispan classbubble idtest4test4spanli lispan classbubble idtest5test5spanliuldiv idbubblediv,"['javascript', 'jquery', 'html', 'css']" +393876,need to have date mask depending on the culture in jquery mvc pages with culture depending on the user in search option search can be done by duedate i need to have a mask on that duedate text box mask must be dependant on the users culture in both js and cshtml have an error saying masksplit is not a function changed my jquerymaskedinput123js from makesplit to maketostringsplit and the error is gone but must looks like this object object or has some 01 numbers any idea code in cshtml looks like this script typetextjavascript function var maskformat htmlcurrentdatemask dateboxmaskmaskformat script,['jquery'] +393880,do not want to refresh retain last inserted values in my htm page i want to use a button which submit my form by using function i use validations on my fields and when i press submit button it thisplays error message but doesnot retain last values it refresh my form i just want that the values that i entered will be exist there and just the field that has only error message will be thisappear all other fields remain therehere is my code doctype html public w3cdtd xhtml 10 transitionalen html head meta httpequivrefresh contenttexthtml charsetiso88591 meta httpequivcontenttype contenttexthtml charsetutf8 titlephone registrationtitle link relstylesheet typetextcss hreffilecxampphtdocstrackcssviewcss mediaall script typetextjavascript srcfilecxampphtdocstrackjavascriptviewjsscript script typetextjavascript srcfilecxampphtdocstrackjavascriptexternaljsscript link relstylesheet href script srcscript script srcscript script function datepicker datepicker script head body idmain body img idtop srcfilecxampphtdocstrackimagestoppng alt div idform container h3 a hreffilecxampphtdocstrackphoneregphpphone registrationa a hreffilecxampphtdocstrackofficerregphpofficer registrationa a hreffilecxampphtdocstrackcustomerregphpcustomer registrationa a hreffilecxampphtdocstracktaskentryphptask entrya h3 form nameorder idform 532698 classappnitro methodpost action div classform description h2phone registrationh2 div ul li span label classdescriptionimei label input nameimei idimeinum classelement text medium typetext maxlength15 value span li li span label classdescription phone number label input namephone idphnum classelement text medium typetext maxlength11 value onblurvalidatethis span li li span label classdescription from date label input iddatepicker namefdate classelement text medium maxlength10 value typetext span li li span label classdescription forelement 4active label input namer1 idrad classelement radio typeradio valueyes checkedchecked label classchoiceyeslabel input namer1 idrad classelement radio typeradio valueno label classchoicenolabel span li li input typebutton namesave valuesave li li classbuttons input typehidden nameform id value532698 input classbutton text typesubmit namesave valuesave id nbspinput classbutton text typereset namecancel valuecancel nbspinput classbutton text typesubmit namesearch valuesearch id nbspinput classbutton text typesubmit nameup valueupdate id nbspinput classbutton text typesubmit namedel valuedelete id li ul form div img idbottom srcfilecxampphtdocstrackimagesbottompng alt script typetextjavascript languagejavascriptsubmit formdocumentordersubmitscript bodyhtmlkindly guide me how can i do this i will be thankful to you,"['php', 'javascript', 'html', 'mysql']" +393892,get row index in datatable from a certain column 1 2 3 a b c d e f g h i systemdatadatatable dt new datatabledtcolumnsadd1dtcolumnsadd2dtcolumnsadd3dtrowsaddnew object a b c dtrowsaddnew object d e f dtrowsaddnew object g h i int index nullvar rows new systemdatadataviewdttotablefalse new 1rowsfor var i 0 i rowscount i if rowsiitemarrayfirstordefault as string a index iis there any way to simplify this code for fetching the index of a certain row with a column provided in this case index will be 0 since i am iterating through the first column until i find a feels like there should be a linq solution to this but i cannot figure it out,"['c#', 'asp.net', 'sql']" +393901,regular expression to get parameter list from function definition possible duplicatehow to get function parameter namesvalues dynamically from javascript i am currently working on a project in javascript nodejs that has me trying to get an array of parameter names not values i do not need arguments from a function i am currently using functiontostring to get the function string and then running a regex against that to get my parameter list let us take the following simple examplevar myfunction function paramone paramtwo running my regex against this and then doing some string magic split etc i would expect an array back like thisparamlist paramone paramtwoi have something that works but i am feeling like it is probably not the best solution given some of the funky characters javascript lets you use for variable names and that javascript will let you define functions on multiple lines here is what i currently havefunctionwswsthis gives me my match in group 1 and then my param list without parens in group 2 which is cool is this really the best way to do what i want is there a better regular expression i could use for this i am not really looking for something simpler but really just something that could catch all possible situationsany help would be appreciated and many thanks in advance,['javascript'] +393906,how to access router globally in backbone js this is my appjs file i need to access the routers navigate method from within the navigatetologin method of the landingview class but since the approuter is defined after the view it cannot recognize the router from within the view so i need to find a way to globally access the router from any class or method how can i get around this problemvar landingview backboneviewextend tagname div id landing classname landingpad events click buttonlogin navigatetologin render function thiselappendbutton classbutton idloginloginbuttonbrbrbr thiselappendbutton classbutton idnewnew userbutton consolelogthisel return this navigatetologin functione appnavigatelogin true return false var approuter backbonerouterextendinitialize function contenthtmlnew landingviewrenderel app new approuter,['javascript'] +393912,unexpected behaviour formatting very large decimal numbers in objc i am running into unexpected behaviour formatting very large numbers in objc using the nsnumberformatterit seems that the number formatter rounds decimals nsdecimalnumber after the fifteenth digit regardless of fraction digitsthe below test fails on values 13 and 5 two requestsany suggestions on alternative code would be greatly appreciatedi assume the issue is happening due to the usage of a hardcoded digit limit in nsnumberformatterthe post here lists a workaround without sufficient description if the problem also our application banking sector runs across multiple countries and we link the formatting to the users locale as configured in the backend this workaround would imply that we write our own number formatter to handle the requirement something i do not want to do voidtestformatterusingonlysdk nsdecimalnumber value1 nsdecimalnumber decimalnumberwithmantissa 9423372036854775808u exponent3 isnegativeyes nsdecimalnumber value2 nsdecimalnumber decimalnumberwithmantissa 90u exponent3 isnegativeyes nsdecimalnumber value3 nsdecimalnumber decimalnumberwithmantissa 91u exponent3 isnegativeyes nsdecimalnumber value4 nsdecimalnumber decimalnumberwithmantissa 900u exponent4 isnegativeyes nsdecimalnumber value5 nsdecimalnumber decimalnumberwithmantissa 10u exponent4 isnegativeyes nsnumberformatter formatter nsnumberformatter alloc init autorelease formatterallowsfloats yes formattermaximumfractiondigits 3 self assertstringareequalwithactualformatter stringfromnumbervalue1 andexpeted 9423372036854775808 self assertstringareequalwithactualformatter stringfromnumbervalue2 andexpeted 9 self assertstringareequalwithactualformatter stringfromnumbervalue3 andexpeted 91 self assertstringareequalwithactualformatter stringfromnumbervalue4 andexpeted 9 self assertstringareequalwithactualformatter stringfromnumbervalue5 andexpeted 1 voidassertstringareequalwithactualnsstring actual andexpetednsstring expected stasserttrueexpected isequaltostringactual expected but got expected actual,['objective-c'] +393931,not able to resolve jsobject in a java applet project i am trying to call jsobjectgetwindowthis in the init method of japplet but it is not able to resolve the symbol getwindowthis problem is specifically happening with a javafx application project created through netbeans getwindow is getting resolved if used in a java application projecti have also included the pluginjar from path javajdk170 07jrelibthis is a javafx application project that i created in netbeans,"['java', 'javascript']" +393939,cross domain jquery ajax call with credentials i have followed the following steps get the server to allow cross domain calls with all the headers and stuff this works test the server with some cross domain calls this works get the server to force a certificate this works go to a file on the server with a browser choose the right certificate and see the file still worksnow we get to the nice part combine the cross domain calls with the certificate this does not work problem i am getting the certificate request from the browser but when i select the same certificate as i do when using the browser the call is made but i get a 403 forbidden code ajax type post xhrfields withcredentials true datatype xml contenttype textxml charsetutf8 url any ideasedit the accesscontrolallowcredentials true and the accesscontrolalloworigin are properly configured additional information i am starting to think that it has something to do with the content type when i change it to texthtml i get a 415 error but i do really need to send xml because it is a soap serverresponse headers accesscontrolallowcred trueaccesscontrolallowhead contenttype origin man messagetype soapaction xtestheaderaccesscontrolallowmeth getpostheaddeleteputoptionsaccesscontrolalloworig accesscontrolmaxage 1800cachecontrol privatecontentlength 5561contenttype texthtml charsetutf8date wed 19 dec 2012 150646 gmtserver microsoftiis75xpoweredby aspnetrequest headersaccept texthtmlapplicationxhtmlxmlapplicationxmlq09q08acceptencoding gzip deflateacceptlanguage nlenusq07enq03accesscontrolrequesthe contenttypeaccesscontrolrequestme postcachecontrol nocacheconnection keepalivehost myhoastcomorigin pragma nocacheuseragent mozilla50 windows nt 61 wow64 rv170 gecko20100101 firefox170,"['javascript', 'jquery']" +393962,how to handle unauthorizedaccessexception when attempting to add files from location without permissions i am trying to get all files from folder this waytry string files directorygetfilesfolderbrowserdialog1selectedpath searchoptionalldirectoriescatch unauthorizedaccessexception throwif my root folder contains a folder for which the user does not have permission to access the unauthorizedaccessexception is caught and my array is empty and all the recursion failedhow can i handle this case and insure that my code ignore locations without permission but add the files from location with permissions,['c#'] +393981,keyboardfocus does not work on text box in wpf i am banging my head on what looks like such a simple problem to fix in wpf but i have yet to thiscover why i cannot get my app to behave according to my plan i have a small search box that popsup in my wpf application when user presses ctrlf all i want is for the caret to be flashing inside the search box text box ready to take whatever user input without the user having to click on it here is the xaml code for the text box which is visible enabled hit testable tabstopable and focusable textbox xnamesearchcriteriatextbox textbinding searchcriteria focusabletrue isenabledtrue istabstoptrue ishittestvisibletrue styledynamicresource searchtextboxstyle gridcolumn1 margin51005 in the code behind i have this method called when the visibility of the search box is affected the search box is loaded at the start of the app summary handles events triggered from focusing on this view summary param namesenderthe senderparam param namedependencypropertychangedeventargsthe key event argsparam private void onisvisiblechangedobject sender dependencypropertychangedeventargs dependencypropertychangedeventargs if bool dependencypropertychangedeventargsnewvalue return searchcriteriatextboxfocus keyboardfocussearchcriteriatextbox searchcriteriatextboxselect0 0 if searchcriteriatextboxtextlength 0 searchcriteriatextboxselectall the problem is code gets called component becomes isfocusedtrue but does not gain keyboard focus am i missing something unless another control keeps hold ferociously to the keyboard focus which i am pretty sure i didntt code why would this piece of rather simple code not work properly,['c#'] +393989,in c how do you oneway serialize the unserializable oftentimes i need to serialize an object either for logging or debugging this is a oneway serialization i do not need to get it back out later i just need to turn an object into a string to write it somewhereyes yes this is why you should always override the tostring method i know this but i am often dealing with objects i did not write and cannot change additionally i do not want to have to write and update a tostring method for every class i writexml serialization offers a seemingly perfect solution just flatten that object out into xml but there are so many limitations specifically that you cannot serialize idictionary and you have to have a parameterless constructor i can get around these in my classes but again i am often working with other peoples classesso whats the solution to getting an comprehensive string representation of an object is there something simple that i am missing,['c#'] +393992,pattern to get objects structured difference and statistics or how to create diff tool let us say i have such structurepublic class form region public properties public listfield fields get set public string id get set public string name get set public string version get set public int revision get set endregionso the form class contains the list of fields let us say that the field itself is represented with such structurepublic class field region public properties public string thisplayname get set public listfield fields get set public string id get set public fieldkind type get set public fieldtype fieldtype get set endregionthe field is basically composite structure each field contains the list of child fields so the structure is hierarchical also field has reference to the fieldtype classpublic class fieldtype region public properties public datatype datatype get set public string thisplayname get set public string id get set endregionand at the end we have reference to the datatypepublic class datatype region public properties public string basetype get set public string id get set public string name get set public listrestriction restrictions get set endregionwhat i want to achieve is to get the difference of such complex structure let us say if i have some sort of comparer it will give me structured difference for the whole form as one class let us say differenceresult when i said structured difference i mean that it should be something like thatdifference for the form fields output form has difference in version field different colordifferences for the fields collection including the hierarchy of the fields to the edited fieldsame behavior for the fieldtype and datatypedetect removing and adding the field into the form so probably each difference will have a typewhat i have right now i started with generic approach and tried to use reflectioncomparer implementing iequalitycomparer interfacepublic bool equalst x t y var type typeoft if typeofiequatabletisassignablefromtype return equalitycomparertdefaultequalsx y var enumerabletype typegetinterfacetypeofienumerablefullname if enumerabletype null var elementtype enumerabletypegetgenericarguments0 var elementcomparertype typeofdifferencecomparermakegenerictypeelementtype var elementcomparer activatorcreateinstanceelementcomparertype new object founddifferencecallback existeddifference return booltypeofenumerablegetgenericmethodsequenceequal new typeofienumerable typeofienumerable typeofiequalitycomparer makegenericmethodelementtypeinvokenull new x y elementcomparer foreach var propertyinfo in typegetproperties var leftvalue propertyinfogetvaluex var rightvalue propertyinfogetvaluey if leftvalue null var propertycomparertype typeofdifferencecomparermakegenerictypepropertyinfopropertytype var propertycomparer activatorcreateinstancepropertycomparertype new object founddifferencecallback existeddifference if booltypeofiequalitycomparermakegenerictypepropertyinfopropertytype getmethodequals invokepropertycomparer new object leftvalue rightvalue create and publish the difference with its type else if equalsleftvalue rightvalue create and publish the difference with its type return true if no differences are foundand difference classpublic struct difference public readonly string property public readonly differencetype type public readonly iextractionable expected public readonly iextractionable actualbut probably it is not the way i want to go because i should compare field more precisely taking in consideration that each field has id which can be different for different forms as well and i want to take more control of the comparing process for me it sounds more like a diff toolso i am looking for good pattern and pretty good structure to publish the difference to the client code which can easily visualize it,['c#'] +394007,unzipped data being padded with 0 when using dotnetzip and memorystream i am trying to zip and unzip data in memory so i cannot use filesystem and in my sample below when the data is unzipped it has a kind of padding 0 chars at the end of my original data what am i doing wrong test public void zip and unzip from memory buffer byte originaldata encodingutf8getbytesmy string byte zipped using memorystream stream new memorystream using zipfile zip new zipfile zipcompressionmethod compressionmethodbzip2 zipcompressionlevel ioniczlibcompressionlevelbestspeed zipaddentrydata originaldata zipsavestream zipped streamgetbuffer assertareequal256 zippedlength just to show that the zip has 256 bytes which match with the length unzipped below byte unzippeddata using memorystream mem new memorystreamzipped using zipfile unzip zipfilereadmem zipentry zipentry unzipentriesfirstordefault zipentry zipentry unzipdata using memorystream readstream new memorystream zipentryextractreadstream unzippeddata readstreamgetbuffer assertareequal256 unzippeddatalength why my data has trailing 0 chars like a padding to 256 module assertareequaloriginaldatalength unzippeddatalength fail the unzipped data has 256 bytes assertareequaloriginaldata unzippeddata fail at index 9,['c#'] +394012,galaxianlike enemy movement i am making a galaxianlike shooter and my enemy objects have a destination vector which they travel towards using this bit of codepositionx motionx magnitude speedpositiony motiony magnitude speedmotion is worked out bythismotion initialposition destinationthis makes them travel in a straight line towards the destinationhowever i want to make them a bit more interesting and travel on a sin or cos wave a bit like galaxian did how can i do this,['c#'] +394061,javascript should run only if tabbrowser window is focused possible duplicatedetect if browser tab has focus i have a simple java applet that captures clients screen with the help of a piece of javascript code i am able to call the applet and capture the active screen picturebut even though it only captures active screen with a click on a button users are likely to manipulate the process by switching to some other tab with alt tab while capture process i want to make sure that capturing must be done only if page is loaded and page is focusedso far i found this piece of javascript code which does not seem to be working correctly sometimes it gets stuck at the focus even though the page is minimizedscript languagejavascript windowonpageshow functione consolelogpageshow windowonfocus functione consolelogfocus scriptso are there any suggestions to what i am trying to achieve or any other solutions,"['javascript', 'jquery']" +394063,how to change size of raphael icons how i can change the width and the height of icons from free raphael icons i tried to use attr tried to use like this var paper raphaelcanvas 100 100i need to do this if i change the size of the parent block the size of my icon changes tooupd i tried use scale and transform but icon resize from centre and not fit into the parent correctly,"['javascript', 'jquery', 'css']" +394070,can i get an android device id through a mobile website is it possible to get a devices telephony id mac address serial number andor android id through a mobile website that is not through a downloadable app but through a link that the user goes to in the browser on their mobile device if so how,['android'] +394097,loading a properties file from a path that is not in my class path hmm simple task but how do i load properties file from path that is not in my class pathfor example i have simple java file that i execute like this foojar dsampledirdirapp1propertiesand in the code i do public boolean initconfigstring propepath prop new properties try inputstream in thisgetclassgetclassloadergetresourceasstreampropepath proploadin return true catch ioexception e todo autogenerated catch block eprintstacktrace return false where propepath is dsampledirdirapp1propertiesand inputstream in is always null why does this happen,['java'] +394124,python urllib2 cookiejar with selenium i am using python urllib2 and a cookiejar to access a website the last page of the site is too complex to handle with urllib2 it uses javascript and frames so i would like to open it using selenium but i need to transfer my cookies over to selenium before i can proceedi have my cookiejar setup as followscj cookielibcookiejaris there some way to iterate over this and output each cookie it looks like i can set the cookies in selenium usingcookie cookie new cookiekey valuedrivermanageaddcookiecookie,['python'] +394126,pymongo mongoclient or connection i am trying to connect mongodb using pymongo i see two classes to connect to mongodbmongoclient and connection what is the difference of these two classes,['python'] +394131,in c why do interface implementations have to implement a another version of a method explicitly take this examplepublic interface ifoo ifoo barpublic class foo ifoo public foo bar ifoo ifoobar return bar why is this necessarywhy is the implicit implementation of ifoo bar necessary even though foo converts to ifoo without a cast,"['c#', '.net']" +394139,defaultmodelbinder and collection of inherited objects i have an action method like this belowacceptverbshttpverbspostpublic actionresult createform newform i have a model with the following classes which i would like to load the data from the ajax json data public class form public string title get set public listformelement controls get set public class formelement public string controltype get set public string fieldsize get set public class textbox formelement public string defaultvalue get set public class combo formelement public string selectedvalue get set here is the json data title form1 controls controltype textbox fieldsize small defaultvaluetest controltype combo fieldsize large selectedvalueoption1 ajax url urlactioncreate form type post datatype json data newform contenttype applicationjson charsetutf8 success function data var msg datamessage defaultmodelbinder is handling the nested object structure but it cannot resolve the different sub classes what would be the best way to load list with the respective subclasses,['c#'] +394171,syntax error when using command line in python i am a beginner to python and am at the moment having trouble using the command line i have a script testpy which only contains print hello and it is located in the map cpython27 in my system variables i have specified python to be cpython27 i have other versions of python installed on my computer as welli thought this should be enough to run python testpy in the command line but when i do so i get thisfile stdin line 1python testpy syntaxerror invalid syntaxwhat is wrong thanks in advance,['python'] +394193,php exec change encoding i need to address utf8 filenames with the php exec command the problem is that the php exec command does not seem to understand utf8 i use something like thisecho execlocale charmapreturns ansi x341968looking at this so question the solution lookes like thatecho execlangde deutf8 locale charmap but i still get the same output ansi x341968on the other hand if i execute this php command on the bash command linephp r echo execlangde deutf8 locale charmapthe output is utf8so the questions arewhy is there an different result be executing the php command at bash and at apache moduleweb pagehow to set utf8 for exec if it runs inside a website as apache module,['php'] +394230,sql rank over partition on joined tables i have two tables rslts and contactsrslts qry id res id score a 1 15 a 2 32 a 3 29 c 7 61 c 9 30contacts c id qry id res id 1 a 2 2 a 1 3 c 9i am trying to create a report that would show for each contact record c id the rank of res id by score in the rslts table within its group qry id using the data above it would look like this c id qry id res id score rank 1 a 2 32 1 2 a 1 15 3 3 c 9 30 2so far i tried this but it returns rank 1 for the last row and rank 2 for the second which is also wrongselect c rscore rank over partition by rqry id order by rscore descfrom contacts c left join rslts ron cres id rres idand cqry id rqry idupdate sqlfiddlethanks in advance for your help,['sql'] +394237,when adding circles to a gmaps4rails i get an error that reads typeerror undefined is not an object evaluating circleserviceobjectgetbounds my objective is to add circles in place of markers to show the general area of the location of the each tool in the tool model i was able to add circles based on other answers on so however using the following code i get the error in the title of this questionin my controllerdef index tools toolall jsontoolallto gmaps4rails circles toolallt longitude tlongitude latitude tlatitude radius 10 to json respond to do format formathtml indexhtmlerb formatjson render json tools endendin my view file gmaps markers data circles circles data circles the javascript error directs me to the line 401 in the gmaps4railsgooglemapsjs file thisboundsobjectextendcircleserviceobjectgetboundsgetnortheastany ideas why,"['javascript', 'ruby-on-rails']" +394248,jquery ajax post not passing anything to php i am having a problem passing variable using post method with ajaxjqueryhere is my codeajaxtestphpphp dir postdir scaned globdirglob onlydir echo json encodescanedajaxtesthtmlhtmlheadscript typetextjavascript srcjsjqueryjsscriptheadscriptdocumentreadyfunctionbuttontypebuttonclickfunction var dir gals ajax url ajaxtestphp type post data dir success functionresults data jqueryparsejsonresults for var i 0 i datalength i buttonaafterbr dataibr scriptbodybr button idbuttona typebuttontest buttonbuttonbodyhtmlthis code not workingbut this one do but not with jsonpostajaxtestphp dirdir functionresults var data parsejsonresults for var i 0 i datalength i buttonaafterbr dataibr why sowhat is wrong in my code please advicethanks a lot,"['php', 'jquery']" +394251,is it a good idea to store a lot of text that is acquired periodically to a cache before saving to a file so i am trying to write messages from users on a messaging network to a file i am trying to build this program with good java practices and appropriate file io techniquecurrently my program recognizes someone has posted a message takes the message and immediately writes it to a file creating the file object creating the writer object appends the message then closes the filethis seems like good practice if there are not many messages coming in but if there is a rapid stream of conversation this seems slow and requires a lot of unnecessary actions because the file is going to opened again immediately then i thought what if i just left the file open and just wrote the messages as they came to the file then closed it periodically is that good practice leaving a file open for extended periods of time for instance after an hour or after some amount of data has been writtennow i am thinking i should take the messages store them in a cachelike a string array then save the string array to a file when the cache is full is this better practiceso i have two questions1 is it good practice to leave a file open for an extended period of time a few minutes to a few hours if you are not using the file 2 what is good practice for a cache like i am talking about is a string array good is there something better i should use how would you go about storing this information,['java'] +394258,how to effectively destroy session in java servlet the servlet i am working has a variable sessioni have tried sessioninvalidate this seem to have destroyed session but when i do a redirect like so responsesendredirectrestanesjsp it gives me http status 500 error with this linejavalangillegalstateexception getattribute session already invalidatedthis is expected since i was trying to destroy the session but why is the page unable to redirect on the same page elsewhere i have redirected successfullyhow can i destroy session and redirect successfully code snippetifrequestgetparameterlogout null sessioninvalidate responsesendredirectrestanesjspupdateall i needed to do was return after responsesendredirectrestanesjsp sincere thanks to balusc,['java'] +394262,how does visual studio evaluate properties while debugging in c in the past i have been burned by the sideeffectsinanaccessor issue when debugging meaning that i have had caches being initialised without my breakpoints being triggered since it was already paused in visual studio and so i have been wondering about the mechanism that visual studio uses to execute code outoforder so as to evaluate properties in a debugger it would seem to me that this would circumvent the clrso the question how is this done from a technical standpoint articles explaining it would be helpful,['c#'] +394286,android custom horizontal progress bar animation i am trying to create a progress bar where the bar itself animates in a vertical spin as it progresses horizontally i am successfully using my progress drawable as the drawable viaprogressbar androidididprogressbar androidlayout widthfill parent androidlayout heightwrap content styleandroidstylewidgetprogressbarhorizontal androidprogressdrawabledrawablecustom progress androidlayout marginright5dp here is my drawablebut i want it to have a subtle roll effect as its progressing so it would look like the vertical lines are moving backwards sorta you follow any help is much appreciated thanksediti tried created an animationlist as my progress drawable but i am still not able to see the animation can an animationlist be inside of a clip for the progress itemxml version10 encodingutf8layerlist xmlnsandroiditem androididandroididbackground androiddrawabledrawablegutteritemitem androididandroididprogressclip animationlist androidoneshotfalse item androiddrawabledrawableprogress bar animate androidduration100 item androiddrawabledrawableprogress bar animate2 androidduration100 item androiddrawabledrawableprogress bar animate3 androidduration100 item androiddrawabledrawableprogress bar animate4 androidduration100 item androiddrawabledrawableprogress bar animate5 androidduration100 item androiddrawabledrawableprogress bar animate6 androidduration100 item androiddrawabledrawableprogress bar animate7 androidduration100 animationlistclipitemlayerlist,['android'] +394325,converting matlabs datenum format to python i just started moving from matlab to python 27 and i have some trouble reading my matfiles time information is stored in matlabs datenum format for those who are not familiar with ita serial date number represents a calendar date as the number of days that has passed since a fixed base date in matlab serial date number 1 is january 1 0matlab also uses serial time to represent fractions of days beginning at midnight for example 6 pm equals 075 serial days so the string 31oct2003 600 pm in matlab is date number 73188575taken from the matlab documentationi would like to convert this to pythons time format and i found this tutorial in short the author states thatif you parse this using pythons datetimefromordinal73196504835648148 then the result might look reasonable before any further conversions which does not work for me since datetimefromordinal expects an integer datetimefromordinal73196504835648148 traceback most recent call last file stdin line 1 in moduletypeerror integer argument expected got floatwhile i could just round them down for daily data i actually need to import minutely time series does anyone have a solution for this problem i would like to avoid reformatting my mat files since there is a lot of them and my colleagues need to work with them as wellif it helps someone else asked for the other way round sadly i am too new to python to really understand what is happening thereedit 20121101 this has been fixed in the tutorial posted above,['python'] +394329,sigpipe exception in ios project with bump api integrated i am experiencing a sigpipe error in my xcode project this error has been started showing since one week before if i commented this method call self configurebump everything works fine i had integrated bump api in my project this api is working till one week before without any problems i am not sure about the cause of this error could anyone please help me to resolve this error some of my friends are also reported this errorxcode version 45ios version ios 60ios 50please see the below stack trace thread 1 tid 0x1c03 0x95a887d2 libsystem kerneldylibmach msg trap 10 stop reason signal sigpipe frame 0 0x95a887d2 libsystem kerneldylibmach msg trap 10 frame 1 0x95a87cb0 libsystem kerneldylibmach msg 68 frame 2 0x029ef13a corefoundation cfrunloopservicemachport 186 frame 3 0x02952580 corefoundation cfrunlooprun 1312 frame 4 0x02951db4 corefoundationcfrunlooprunspecific 212 frame 5 0x02951ccb corefoundationcfrunloopruninmode 123 frame 6 0x03093879 graphicsservicesgseventrunmodal 207 frame 7 0x0309393e graphicsservicesgseventrun 114 frame 8 0x017a0a9b uikituiapplicationmain 1175 frame 9 0x02dd7 icardmain 199 at mainm17 frame 10 0x02185 icardstart 53,['objective-c'] +394403,why is used for both binary and and addressof in c this question is in response to what is operation in c which got me thinking about being used both as binary and and addressofwhy is the same symbol used for both these very thissimilar tasks when thinking about it would seem to be a better symbol for addressofi do not expect it to cause much problem in practice since the compiler will probably catch most faulty use but it would probably be possible to create code involving macros that looks like it is doing a binary and while it is actually doing addressof,['c'] +394421,pause form from submitting with javascript i am trying to do a submit form with photos after the user loads the photos he presses the submit button i want the form to pause for 10 seconds animate a progress bar for those 10 seconds and then submit the form can you guys say what i did wrong it does not seem to submit the form after 10 seconds here is the codehtmlform actionuploadpicphp methodpost idupload forminput typetext nametitle idtitlep idtitle ptitlephr input typetext nametheme idpicture theme size40p idthemepicture themeimg srcsimagesinfogif idinfo width12 height12 stylemarginleft10pxphr div classcustomupload input typefile namepicture idtrue pic div classfakefile input thisabledthisabled divdivp idupload picupload picturepainput typesubmit namesubmit idsubmit valueupload formjavascriptform documentgetelementbyidupload form size1 formonsubmit function if size 10 settimeoutdelayedsubmit10 return false function delayedsubmit size if size5 settimeoutdelayedsubmit10 alertcounting size else alertform submitted formsubmit php phpif postsubmit title posttitle theme postpicture theme echo title theme i can tell that the form would not submit anything by the fact that the php variables would not show anything and then page does not load,"['php', 'javascript', 'html']" +394422,java comparator for multicolumn sorting is there any java opensource comparator for comparing beans by multiple fields for multicolumn sorting each column can be sorted asceding or descendingfor singlecolumn sorting it can be achieved by using orgapachecommonsbeanutilsbeancomparator together with orgspringframeworkutilcomparatorinvertiblecomparator i am aware that this functionality is quite trivial to write but whats the benefit from reinventing the wheel if it was already written and tested,['java'] +394450,android share image in imageview without saving in sd card i want to share the image in image viewbut i do not want save to sdcard but when i use intent to share i used code intent share new intentintentaction send sharesettypeimagejpeg shareputextraintentextra streamuriparsepath startactivityintentcreatechoosershare share image here path specified location of image in sdcard but i do not want save image is there possible,['android'] +394455,t4 template vs2010 get host assembly i want to get a reference to assembly of a project in which t4 template is i know i can get path to the project with for example hostresolveassemblyreferenceprojectdir and i could maybe add bindebugprojectnamedll because my assembly names are named by project name but that is not always the case and i am creating reusable template so i need path to dll or most preferably assembly instance i have also found how to get reference to the project as explained here in method getprojectcontainingt4file but then whatis there a way to get itbtw i need that reference to access specific types and generate some code from them,['c#'] +394467,use of clone in php i have a class a and instantiated it using newobja new ai know the difference between the below two linesobja2 ojbaobja2 clone objabut even if you declare or not declare clone in the class a the first line obja2 refer to obja memory space and second line creates a copy of the obja till here it is clear to methen why php is having a magic method cloneis it only for executing a set of codes which is written inside clone while we use obja2 clone objasomebody please help to get a better idea of it,['php'] +394468,is lambda comparison deterministic as we know comparing two matching string literals can result in equalityhello hello could be true or falsedoes the same hold for lambdas false guaranteedis the compiler free to evaluate this as it pleases or is it guaranteed that it will evaluate to false is it legal what does the above actually compare,['c++'] +394472,uicollectionview spacing margins i have a uicollectionview which shows photos i have created the collectionview using uicollectionviewflowlayout it works good but i would like to have spacing on margins is it possible to do that using uicollectionviewflowlayout or must i implement my own uicollectionviewlayout,['ios'] +394525,optimization techniques for c in his talk a few days ago at facebook slides video andrei alexandrescu talks about common intuitions that might prove us wrong for me one very interesting point came up on slide 7 where he states that the assumption fewer instructions faster code is not true and more instructions will not necessarily mean slower codehere comes my problem the audio quality of his talk around 620min is not that well and i do not understand the explanation very well but from what i get is that he is comparing retired instructions with optimality of an algorithm on a performance levelhowever from my understanding this cannot be done because these are two independent structural levels instructions especially actually retired instructions are one very important measure and basically gives you an idea about performance to achieve a goal if we leave out the latency of an instruction we can generalize that fewer retired instructions faster code now of course there are cases where an algorithm that performs complex calculations inside a loop will yield better performance even though it is performed inside the loop because it will break the loop earlier think graph traversal but wouldnt it be more useful to compare to algorithms on a complexity level rather than saying this loop has more instructions and is better than the other from my point of view the better algorithm will have less retired instructions in the endcan someone please help me to understand where he was going with his example and how can there be a case where significantly more retired instructions lead to better performance,['c++'] +394544,redundant implementation of list interface in arraylistjava possible duplicatewhy does arraylist have aimplements lista i am new to java i was trying to see the hierarchy of collection interface i found that the signature of abstractlistjava is likepublic abstract class abstractliste extends abstractcollectione implements listeit implements list interface but if you look at signature of child class arraylistjava it looks likepublic class arrayliste extends abstractliste implements liste randomaccess cloneable javaioserializableif you look parent class is already implemented list interface then why child class is again implementing same interface listis there specific reason or requirement behind this,['java'] +394565,error cannot find all types required by the async modifier are you targeting the wrong framework version or missing a reference to an assembly i have following configuration of my pcwindows 8visual studio 2012net framework 45my project configuration iswp 71silverlight 40net framework 40ctp async installed using async and await keywordsthe project was written using vs2010 on windows 7 machine for wp71 now i have upgraded the pc to windows 8 and have installed vs2012 the project however complaining about async modifiercannot find all types required by the async modifier are you targeting the wrong framework version or missing a reference to an assemblyany idea how to solve this problemthank you,['c#'] +394569,how do i consolelog a jquery dom element in chrome i used to be able to do consolelogsomejqueryobj and it logged in an array all of the dom elements that are in the object that i could click and go to the inspectornow it does something like thisprevobject pfnpinit1 context selector next which can confuse many peoplehow do i make it so that chrome logs how it used to log jquery elementshere is a fiddle examplei am ingoogle chrome 230127197 official build 171054 m,['jquery'] +394579,howto generate querystring from model with aspnet mvc framework i have a model with some nested properties lists and i want to get a querystring parameters from that modelis there any classhelper in aspnet mvc framework to do this i know that with model binder we can bind a model from a querystring but i want to do the inversethanks,['c#'] +394588,what does an functions code block in a razor file do and when if ever should i use it whilst looking at a theme i downloaded from the orchard cms gallery i noticed that a layoutcshtml file had this block of code at the top of the filefunctions to support the layout classifaction below implementing as a razor function because we can could otherwise be a funcstring string string in the code block followingstring calcuclassifystring zonenames string classnameprefix var zonecounter 0 var zonenumsfilled stringjoin zonenamesselectzonename zonecounter return modelzonename null zonecountertostring toarray return hastextzonenumsfilled classnameprefix zonenumsfilled i know what the declared function does calculates which zones are populated in order to return the width of each column my question is what is the correct use of the function block and when should i ever use it,['c#'] +394614,why is the onnewintentintent intent method getting called twice i start a new activity with two parametersintent intent new intentwebtestactivitythis mainactivityclassintentaddflagsintentflag activity single top intentflag activity clear top uri uri uriparseurlintentsetdatauristartactivityintentand catch uri in onnewintent methodoverridepublic void onnewintentintent intent calls twice superonnewintentintent uri uri intentgetdata new asynktaskexecuteuri but the onnewintent method is called twice for some unknown reason which does not seem to be right,"['java', 'android']" +394644,convert a statically linked elf binary to dynamically linked i have a elf binary which has been statically linked to libci do not have access to its c codei would like to use openonload library which has implementation of sockets in userspace and therefore provides lower latency compared to standard libc versionsopenonload implements standard socket api and overrides libc version using ld preloadbut since this elf binary is statically linked it cannot use the openonload version of the socket apii believe that converting this binary to dynamically link with openonload is possible with the following stepsadd new program headers pt interp pt dynamic and pt loadadd entries in pt dynamic to list dependency with libcadd plt stubs for required libc functions in the new pt load sectionmodify existing binary code for libc functions to jump to corresponding plt stubsas a first cut i tried just adding 3 pt load segments new segment headers were added after existing pt load segment headers also vm addr of existing segments was not modified file offsets of existing segments were shifted below to next aligned address based on p alignnew pt load segments were added in the file at end of the fileafter rewriting the file when i ran it it was loaded properly by the kernel but then it immediately segfaultedmy questions areif i just shift the fileoffsets in the elf binary without modifying the vm addresses can it cause any error while running the binaryis it possible to do what i am attempting has anybody attempted it,['c'] +394658,admob vs adsense i am looking for way to monetize my free android application i saw two choices ad mob and adsense looks like admob is getting closed and replaced by adsense i read later google shut down adsense so how to put ads in mobile now sorry for my limited understanding any pointers are welcome one general question does people really click ads and can you make decent money in andriod apps,['android'] +394676,logmanager and garbage collector in the description of the getlogger method of the logmanager it is written the followinglogger associated with the string name may be garbage collected at any time if there is no strong reference to the logger the caller of this method must check the return value for null in order to properly handle the case where the logger has been garbage collectedhow is it possible that the gc can erase the logger since logmanager has to keep all the references to all loggers to be able to resolve the names of the loggersis not that a bit strange that java api allows a situation that at the start of my app i create and setup my loggers but forget to keep refrences and then later if i use loggergetlogger somename i will get new default one instad of my loggers which i set up,['java'] +394685,hibernate 419 which jar files do i need i started to learn hibernate framework from hibernate 32 in simple steps book but i downloaded latest version of hibernate which is 419 according to the book there are many essential jars we need to add to the class path likeanttr276jarasmjarasmattrsjarcglib213jarcommonscollections211jarcommonslogging104jar etcbut i cannot find all those required jars in new version so what can i do without going for an old version do i just only need to add jars in required folder can any one please tell me what jars i should need to add class path 419 versionthis question may be silly but i am a beginner and i am stuck here please help methank you,['java'] +394695,drive quickstart nullpointerexception i am trying to get the google drive quickstart example to run but i will always get a runtimeexception this seems to come from the depths of the the api i usedoes anyone had the same problems then i and could help me to fix ithere is my errorcode1220 191954920 eandroidruntime15682 fatal exception thread20161220 191954920 eandroidruntime15682 javalangnullpointerexception1220 191954920 eandroidruntime15682 at javaneturiparseuriurijava3531220 191954920 eandroidruntime15682 at javaneturiiniturijava2041220 191954920 eandroidruntime15682 at comgoogleapiclienthttpgenericurlinitgenericurljava1001220 191954920 eandroidruntime15682 at comgoogleapiclientgoogleapismediamediahttpuploaderuploadmediahttpuploaderjava2691220 191954920 eandroidruntime15682 at comgoogleapiclientgoogleapisservicesabstractgoogleclientrequestexecuteunparsedabstractgoogleclientrequestjava4081220 191954920 eandroidruntime15682 at comgoogleapiclientgoogleapisservicesabstractgoogleclientrequestexecuteunparsedabstractgoogleclientrequestjava3281220 191954920 eandroidruntime15682 at comgoogleapiclientgoogleapisservicesabstractgoogleclientrequestexecuteabstractgoogleclientrequestjava4491220 191954920 eandroidruntime15682 at comexampledrivequickstartmainactivity1runmainactivityjava971220 191954920 eandroidruntime15682 at javalangthreadrunthreadjava8561220 191955100 dopenglrenderer15682 flushing caches mode 01220 191955130 dopenglrenderer15682 flushing caches mode 11220 192019750 iprocess15682 sending signal pid 15682 sig 9i copied the code from the drive quickstarttutorial here is a link,"['java', 'android']" +394701,using freopen to print to file and screen i am trying to use freopen to print to a text file and the screen but i am only achieving the printing to a filei was wondering if there was an easy to save the programs output to a file and print it to the screen because i had this working another way but i ended up having to print out every statement twice one being for the file the other just for the outputnote i am new to c and i am trying to learn it for a class next semester so direct answer are needed as i have already look online and could not find any simple answers to this solution besides here is what i have so farincludeiostreamincludetimehincludestdlibhincludefstreamusing namespace std void menu cout tn t welcome to slot machine n t would you like to play 1 to play 2 not to play n tnn returnvoid updateint arr int token if arr0arr1 arr1arr2 token4 cout you win else if arr0arr1 arr1arr2 arr0arr2 token1 cout you got two out of threenn else token1 cout you losenn int main freopenfiletxt w stdout int x arr3 token4 srandtime0 menu cin x whiletoken0 cout you have token tokensnn pull 1 to pull 2 not to pullnn cinx ifx1 forint i0 i3 i arri1rand10 cout tt forint j0 j3 j cout arrj cout nn updatearrtoken else cout okn cinget return 0,['c++'] +394720,why is sin addr inside the structure in addr my doubt is related to the following structure of sockets in unix struct sockaddr in short sin family eg af inet af inet6 unsigned short sin port eg htons3490 struct in addr sin addr see struct in addr below char sin zero8 zero this if you want tohere the member sin addr is of type struct in addrbut i do not get why someone would like to do that as all struct inaddr has is struct in addr unsigned long s addr load with inet ptonall in addr has is just one member s addr why cannot we have something like this struct sockaddr in short sin family eg af inet af inet6 unsigned short sin port eg htons3490 unsigned long s addr char sin zero8 zero this if you want to,['c'] +394721,how does the visitor pattern not violate the open close priniciple from wikipedia the idea was that once completed the implementation of a class could only be modified to correct errors new or changed features would require that a different class be created that class could reuse coding from the original class through inheritancefrom what i understand the visitor pattern is a powerful technique to traverse similar but different objects that implement the same interface by the use of double thispatch in one of my java examples i created a composite set of objects that form a tree structure and each specific implementation of those objects implement the visitable interface the visitor interface has a method for each of the visitable objects and the concrete visitor implements what to do for each of those casesthe thing i am trying to get my head around is the fact that if i were to add a new implementation to the composite structure that also implements visitable then i need to reopen the visitor interface and add that case to it also forcing me to modify each implementation of visitor while this is fine since i would need to do this anyway what good is adding to your visitables if the visitor cannot understand them but on an academic level wouldnt this be violating the open closed principle is not that one of the core reasons for design patterns anyway trying to show a decent reason for switching to this pattern instead of maintaining a switch statement to end all switch statements but everyone argues that the code will be the same anyways with a method for each case instead of a switch block just broken up and harder to read,['java'] +394733,pthreads how to assert code is run in a single threaded context i am writing a c library which needs to fork during initialization therefore i want to assert that the application code which is outside of my control calls my library initialization code from a single threaded context to avoid the well known threads and fork do not mix problem once my library has been initialized it is thread safe and expected that the application level code may create threads i am only concerned with supporting pthreadsit seems impossible to count the number of threads in the current process space using pthreads indeed even googletest only implements getthreadcount on mac os and qnxgiven that i cannot count the threads is it somehow possible that i can instead assert a single threaded contextclarification if possible i would like to avoid using proc nonportable an additional library dependency like libproc and ld preloadstyle pthread create wrappersclarification 2 in my case using multiple processes is necessary as the workers in my library are relatively heavy weight using webkit and might crash however i want the original process to survive worker crashes,['c'] +394736,cannot run any rake command error rakerdoctask is obsolete and no longer supported i am trying to run the rake migratedb command and i get the following error messageerror rakerdoctask is obsolete and no longer supported use rdoctask available in rdoc 242 insteadi tried doing other rake commands and i got the same error how can i fix this,"['ruby-on-rails', 'ruby']" +394738,getting a windows credentials username in c windows form application how do i get the currently signed in username in a windows forms applicationthe app runs on windows embedded standard 7 os,['c#'] +394748,find dead rails code what is a good way to find methods in a that are not being called anymore i am in the process of refactoring a large rails application and the worst thing you can find is code that is not being used anymore,['ruby-on-rails'] +394776,jquery ajax calls executing synchronously instead of concurrently on calls to wcf service i have a web application that contains a page with a form that has hundreds of fields on it changing any of the fields fires a jquery ajax call back to the server to determine if any other fields need to be added to the form based on it is new value in other words it checks to see if any dependent fields need to be added to the form when one field changesthere is a bit of complexity around this process and as a result sometimes these checks can take a few seconds the problem is if one field is in the middle of its ajax call and i attempt to change another field while waiting for the first one to complete the ui gets blocked and i cannot do anything on the page until the first call completes it is like the ui can only handle one ajax call at a time heres a copy of the ajax callajax type post async true url serviceurl data jsonstringifydata contenttype applicationjson charsetutf8 datatype json processdata true success servicesuccess error servicefailed the servicesuccess callback has a lot of complex code to update the ui but i deleted all of the code within it and the problem still occurs i figured it was not anything to do with the callback since it seems to happen before the call completes but just to be sure i gave it a shothas anyone heard of anything like this before with jquery ajaxedit i noticed the size of the response coming back from the ajax call is about 130kedit 2 the ajax calls are making calls to a wcf service the class definition now looks like thisaspnetcompatibilityrequirementsrequirementsmode aspnetcompatibilityrequirementsmodeallowedpublic class reviewdataservice ireviewdataservice ireadonlysessionstate solution so jason definitely pointed me in the right direction my problem was in fact due to aspnet session locking in order to get around this i had to eliminate the use of session from anywhere in the call stack on calls that originated from my wcf service additionally i set aspnetcompatibilityrequirementsmode to aspnetcompatibilityrequirementsmodenotallowed and i set aspnetcompatibilityenabledfalse in the servicehostingenvironment element in webconfig this caused wcf to throw errors when an attempt was made to access session and i juts refactored each of those instances so that they did not rely on session after that my wcf calls started running concurrently instead of synchronously,"['jquery', 'asp.net']" +394785,rails devise how do i place the login form and the recover password on the same page my template looks like thisdropdownlight login form foruser url user session path do f fhidden field redirect to value requestfullpath femail field email placeholder email size fpassword field password placeholder password size divremember fcheck box remember me checked checked flabel remember me clearfix aforgotpuleft hrefforgot forgot your password inputpullright typesubmit valuesign in forgotten form foruseras user forgot url password pathuser html method post do f p strong reset your password psmall give us your email and youall be back in a jiffy div femail field email clearfix aforgotnevermindpuleft hrefforgot nevermind inputpullright typesubmit valuereset password sent p strong email sent p in a couple of minutes you should receive an email with a link to reset your passwordit actually works but it generates two forms with duplicate ids such asinput iduser email nameuseremail size30 typeemailhow do i change this so the ids do not duplicate,['ruby-on-rails'] +394820,how to animate fragment removal i want to animate the removal of fragmenti tried getsupportfragmentmanagerbegintransaction setcustomanimationsranimpush down in ranimpush up out removemyfragment commitbut the fragment just thisappearsi noticed the out animation only plays with replace so i tried to replace the fragment with an empty fragment like thisgetsupportfragmentmanager begintransaction setcustomanimationsranimpush down in ranimpush up out replaceviewid new fragmentcommitbut it still just thisappears thisappearsso how can i animate the removal of fragment,['android'] +394827,is it safe to reinterpret cast an integer to float note i mistakenly asked about static cast originally this is why the top answer mentions static cast at firsti have some binary files with little endian float values i want to read them in a machineindependent manner my byteswapping routines from sdl operate on unsigned integers typesis it safe to simply cast between ints and floatsfloat read float read in 4 bytes uint32 val fread val 4 1 fp swap the bytes to littleendian if necessary val sdl swaple32val return as a float return reinterpret castfloat val x is this safei want this software to be as portable as possible,['c++'] +394829,using dependencies on multiple threads with parallelforeach i use simple injector as my ioc container simpleinjector uses this simple technique to handle mixed life style for per thread and per web requestcontainerregisterperwebrequestiwebrepository repositorycontainerregisterlifetimescopeithreadrepository repositorycontainerregisterirepositorycontainergetinstancerepository register as hybrid perwebrequest perlifetimescopecontainerregisterrepository repository repository if httpcontextcurrent null repository repositorycontainergetinstanceiwebrepository else repository repositorycontainergetinstanceithreadrepository return repositoryunfortunately and obviously elsewhere in my unitofwork class this is giving me an issue when i use parallelforeach and try to call into multiple instances of the repository class in parallel as only the first of the threads finds a value in httpcontextcurrentusing transactionscope scope new transactionscope parallelforeachnew listirepository repository1 repository2 repository repositorycommit scopecompletenow that i have finished writing out the question i can see i am probably asking for the impossible or something stupid but what the hell can this be done can a single requestthread registration be made available to multiple internal threads,['c#'] +394845,actionresult returning a stream my actionresult returns a file but i also need it to conditionally return a streami have not been able to find documentation on how an actionresult can return a streamhere is my code for return of a file return filememorystream as mentioned i need to return just a stream,['c#'] +394860,nodejs socketio rooms issue considering a multichat applicationusers can join multiple rooms socketjoinroom users can leave a room socketleaveroom when socket is leaving a room i notify the other room participants if the socket is currently in 3 rooms and he suddenly thisconnects from the website without leaving the rooms the proper way how can i notify those rooms that the user has left if i work with the on socket thisconnect event the user will no longer be in any room at that point is the only way keeping a separate array of users or is there some clever way i have not thought about,['javascript'] +394875,how to get right path files in android my code is followingscanner sc nulltry sc new scannernew fileassetsmainmenureadsourcefiletxt catch filenotfoundexception e1 todo autogenerated catch block systemoutprintlne1tostring e1printstacktracethen logcat show exception javaiofilenotfoundexceptionhow can i find my file i tried sc new scannernew filemainmenureadsourcefiletxthowever it is still throw filenotfoundexceptionmy file is in folder assetsmainmenureadsourcefiletxtand i have try thisprivate inputstream istry is thisgetresourcesgetassetsopenmainmenureadsourcefiletxt catch ioexception e etostring i use getassets to access assets file in android however how can i suppose to read text file if i use inputstream,"['java', 'android']" +394876,is an executable built differently if linked against a library that is not used apart from a longer compile time is there any downside to linking against an unused libraryfor example is there any difference in the executable of a program that is compiled one of two waysg o main maincppg o main maincpp llib1 llib2 llib3 lmoreno library files were actually needed to build maini believe it makes no difference because the file sizes are the same but i am asking for confirmation,['c++'] +394920,xmlhttprequest in rhino lately i have been playing around with javas scriptengine api namely the javascript engine which uses rhino for everything i sumbled upon the fact that rhino has no xmlhttprequest i was wondering if anyone knew of a possible way around this,"['java', 'javascript']" +394924,how to read a csv file one line at a time and replaceedit certain lines as you go i have a 60gb csv file i need to make some modifications to the customer wants some changes to the files data but i do not want to regenerate the data in that file because it took 4 days to dohow can i read the file line by line not loading it all into memory and make edits to those lines as i go replacing certain values etc,"['c#', '.net']" +394958,performance impact of floating point values for css proprties are there any know issues where the use of floating point values for css properties has any performance impact on the rendering performance especially on mobile devicesin my case we set the width of the border with javascript and it seems to take longer on iphone4 when we use floating point values,['css'] +394963,google plus client an internal error occured last day i started to receive an internal error occured while trying to sign user with google plus in my application that i used well and have not changed the code has not changed for a long timegmsclient returns connect bindservice returned true for intent actcomgoogleandroidgmsplusservicestart service broker connected binder androidosbinderproxy40fdbd20and right after that shows toast message an internal error occuredi tried to compile google sdk samples and run on the same device but it shows the same errormaybe something changed in google apis,['android'] +394969,where to get mythical microsoft msgtool for c serialization while reading about actors oni noticed the part on serializationsince serialization is critical to the correct function of a program and it is so easy to get wrong the c actors library includes a simple message definition generation tool amsgtoola which given an xml document will create the necessary type and serialization definitioni cant find msgtool in vs command prompt or using google search,['c++'] +394970,how to trigger enter key press of textbox in my html page i had a textbox for user to input keyword for searching when they click the search button the javascript function will generate a url and run in new window the javascript function work properly when the user clicks the search button by mouse but there is no response when the user presses the enter keyfunction searching var keywordsstr documentgetelementbyidkeywordsvalue var cmd httpxadvancedsearch resultasplanguageeng encodeurikeywordsstr x11y4 windowlocation cmd form nameform1 methodget input namekeywords typetext idkeywords size50 input typesubmit namebtn search idbtn search valuesearch onclickjavascriptsearching return false onkeypressjavascriptsearching return false input typereset namebtn reset idbtn reset valuereset form,['javascript'] +394972,how to to initialize keyboard event with given charkeycode in a chrome extension i am developing a google chrome extension which simulates keyboard events on a webpagei found that eventinitkeyboardevent does not work properly because of this webkit bug and i also found some workarounds eg so question however defining properties on event object is not working because extensions content script has its own parallel world so properties defined in content script are not visible to webpage scriptmy only and last hope that dom 4 event constructors work in google chrome and it would be possible to properly initialize keyboard event through constructorvar event new keyboardeventkeypress key u0041 char a unfortunately it fails with typeerror illegal constructor i was not able to find any documentation on supported event constructors in chrome could anyone point me to some docssource codeany other way to simulate keyboard events in a google chrome extension note textevent would not help because many realworld controls listen to keydownkeyup specifically,['javascript'] +394975,drawing a rectangle using a move gesture i am trying to create a rectangle but this is what happens when i move from starting coordinates towards the end coordinates actually i want to show the progress when the user moves from one point to other as wellthis is what i would like to have codepublic boolean ontouchview v motionevent event int action eventgetaction switch action case motioneventaction down downx eventgetx downy eventgety vinvalidate break case motioneventaction move upx eventgetx upy eventgety canvasdrawrectdownx downy upx upy paint choosenimageviewinvalidate break case motioneventaction up upx eventgetx upy eventgety canvasdrawrectdownx downy upx upy paint vinvalidate break return trueedit what i would like to do is to show the progress ie as the user moves his finger shape should be drawnsuggestionssampleslinks anything will be appreciated,['android'] +394981,php filter text for banned words we have a c2c website and we thiscourage selling branded products on our website we have built a database of brand words such as nike and dg and made an algorithm that filters product information for these words and thisables products if it contains these words our current algorithm removes all white space and special characters from provided text and matches text with word from database these cases are required to be caught by algorithm and are caught efficientlyi am nike worldi have and ikee shoesi have nikeeshoesi sell iphone casingsi sell iphonecasingsyou can have iphonenow the problem is that it also catches followingrapid garment factory for dgrosnik electronics for nikewhat can be done to prevent such false matches while preserving efficiency with catching true caseseditheres the code for those of you who understand code betterorignal txt preg replace0 strip tagsorignal txtorignal txt nospace preg replacew orignal txt qry kws arraynike iphone dg foreachqry kws as rs kw no space db kw preg replacew rs kw ifstristrorignal txt nospace rs kw ipr banned keywords strtolowerrs kw else ifstristrorignal txt nospace no space db kw ipr banned keywords strtolowerrs kw,['php'] +394988,cannot start service from the command line or debugger i have created a windows service and installed it on a server it appears to work fine ie doing what its meant to do but when i log on to the server through remote desktop i get this messagecannot start service from the command line or debugger a windows service must first be installedusing installutilexe and then started with the serverexplorer windows services administrative tool or the net start commandi click on and then go to the services explorer to check the service its started ok no errors reportedi have installed this so it uses local system as log on asthanks,['c#'] +395013,what is the lifecycle of spring bean i am confused about the lifecycle of spring xmlbeanfactory beanfactory new xmlbeanfactorynew classpathresourcespringhelloworldxmlwhether the above snippet of codes creates the object or notif the above answer is true a then for the bean where scope is singleton get the object which was created during the above snippet of code am i right or wrongb for the case where scope is prototype whether the created object was unused because the container always return new objectxmlbeanfactory beanfactory new xmlbeanfactorynew classpathresourcespringhelloworldxmlwhether the above snippet of codes creates the object or notif the answer is false how the spring framework validates whether the bean definition is correct or notfrom the answer of henryusually singleton beans are created when the context starts this can be changed with the lazyinit or defaultlazyinit attributesprototype beans are only created when neededonly syntactically there might still be errors when the bean is instantiated for example if a required property is not provided,['java'] +395024,is there any way to programatically send my iphone app to the background i have an iphone app that i need to send to the background automatically the app is defined with the voip key in its background modes so it should continue running when in background i specifically need the app to keep running so calling exit0 is no goodthe app will not be thistributed via app store so using a private api is oki have read about uiapplication terminate and uiapplication terminatewithsuccess but they do not seem to be available anymore,['ios'] +395041,regular expression to match a dot was wondering what the best way is to match testthis from blah blah blah blah blah is using pythoni have tried resplitrbwwthanks,['python'] +395047,how to set value in htmltextboxfor in razor syntax i have created an textbox using razor and trying to set value as followshtmltextboxformodel modeldestination new id txtplace value 3 i have tried appending value with htmltextboxformodel modeldestination new id txtplace value 3 even though it renders html input tag with empty value input idtxtplace namedestination typetext value classuiinputtext uibodyc uicornerall uishadowinset uimini what am doing wrong,['.net'] +395077,where do you store your secret key in a java web application cryptography is a widely adopted techonlogy to ensure confidentiality not considering implementation flaws it has a single critical point the secret key storage if the secret key is stolen the whole system will be compromisededit let me specify the context to make the question less broadhere a java web application is addressedmore specifically it is used the spring framework version 3spring security 31 is used to secure the applicationa mysql5 database is availablethe application server is tomcat6 or tomcat7the server machine is not under my controlmaybe the questions can be focused on this scenario but as pointed out the problem of the secret key storage is transversal to the adopted technologies however some libraries might offer peculiar features that can somehow facilitate the worka clear point is that a tradeoff has to be found between security and the need to do practical things to complete the analysis it is obvious that the required security level depends on the value of information to secure it is senseless to flip our minds to enforce supersecure strategies demanding a very lot of efforts to keep secret the shoe size of a customerhere i have to secure an email password that will be stored in a db i consider this information average criticalwhat i am looking for here is the best solution with reasonable effortso the question is very clear where would you store this informationdo you store it in a database so it should be encrypted and this requires another key and where do you store this second keydo you store it inside the war package how do you prevent unauthorized accesses to the sourcesdo you adopt a different strategymotivations for your strategy will be appreciatedthank you,['java'] +395095,why guava does not provide a way to transform map keys this question is kind of already posted herehow to convert mapstring string to maplong string using guavai think the answer of collind is appropriateall of guavas methods for transforming and filtering produce lazy results the functionpredicate is only applied when needed as the object is used they do not create copies because of that though a transformation can easily break the requirements of a setlet us say for example you have a mapstring string that contains both 1 and 01 as keys they are both thistinct strings and so the map can legally contain both as keys if you transform them using longvalueofstring though they both map to the value 1 they are no longer thistinct keys this is not going to break anything if you create a copy of the map and add the entries because any duplicate keys will overwrite the previous entry for that key a lazily transformed map though would have no way of enforcing unique keys and would therefore break the contract of a mapthis is true but actually i do not understand why it is not done becausewhen the key transformation happen if 2 keys are merged a runtime exception could be raised or we could pass a flag to indicate to guava to take any value of the multiple possible values for the newly computed key failfastfailsafe possibilitieswe could have a mapstransformkeys which produces a multimapis there a drawback i do not see in doing such things,['java'] +395136,better search for a string in all files using c after referring many blogs and articles i have reached at the following code for searching for a string in all files inside a folder it is working fine in my tests questionsis there a faster approach for this using cis there any scenario that will fail with this codenote i tested with very small files also very few number of filescodestatic void main string sourcefolder ctest string searchword class1 liststring allfiles new liststring addfilenamestolistsourcefolder allfiles foreach string filename in allfiles string contents filereadalltextfilename if contentscontainssearchword consolewritelinefilename consolewriteline systemconsolereadkey public static void addfilenamestoliststring sourcedir liststring allfiles string fileentries directorygetfilessourcedir foreach string filename in fileentries allfilesaddfilename recursion string subdirectoryentries directorygetdirectoriessourcedir foreach string item in subdirectoryentries avoid reparse points if filegetattributesitem fileattributesreparsepoint fileattributesreparsepoint addfilenamestolistitem allfiles referenceusing streamreader to check if there there contains a stringsplitting a string with two criteriac detect folder junctions in a pathdetect symbolic links junction points mount points and hard linksfolderbrowserdialog selectedpath with reparse pointsc high quality byte array conversion of images,"['c#', '.net']" +395140,left outer join in tsql i have the following two tables i am using sql server 2008 r2create table tmp1 a char1create table tmp2 id inta char1val intinsert tmp1 values ainsert tmp1 values binsert tmp1 values cinsert tmp2 values 1 a 10insert tmp2 values 1 b 20insert tmp2 values 2 a 30insert tmp2 values 2 c 40select from tmp1 t1 left outer join tmp2 t2 on t1a t2aorder by t2idthis returns the result seta 1 a 10b 1 b 20c 2 c 40a 2 a 30i would like to have the following result set a 1 a 10 b 1 b 20 c 1 null null a 2 a 30 b 2 null null c 2 c 40right now i am acheiving this by creating a new table with a cross join like this and then doing a outer joinselect into tmp3 from tmp1 cross join select thistinct id from tmp2 tselect from tmp3 t1 left outer join tmp2 t2 on t1a t2a and t1id t2idis there a better way to do this thanks,['sql'] +395142,the async and await keywords do not cause additional threads to be created i am confused how can one or many task run in parallel on a single thread my understanding of parallelism is obviously wrongbits of msdn i cannot wrap my head aroundthe async and await keywords do not cause additional threads to be created async methods do not require multithreading because an async method does not run on its own thread the method runs on the current synchronization context and uses time on the thread only when the method is active andbetween starting a task and awaiting it you can start other tasks the additional tasks implicitly run in parallel but no additional threads are created,['c#'] +395152,why is call super considered an antipattern according to wikipedia wikipedia classifies call super as an antipattern and i do not really understand why the pattern is used pretty frequently in objectiveccocoa for example initdealloc drawrect awakefromnib all require you to call super am i misunderstanding the concept herelink to the article super,['objective-c'] +395168,what is the difference between classpath and classpath in spring xml i am working on some spring xml configuration files and sometimes they use classpathdatasourcexml and sometimes classpathdatasourcexml is there a difference between the two or is the leading optional implied redundant,['java'] +395170,necessity of static block in java i found that in java there is a feature called static block which includes code that is executed when a class is first loaded i do not understand what loaded means does it mean initialized is there any reason to do the initialization bit inside a static block and not in the constructor i mean even the constructor does the same thing do all the necessary stuff when a class is first initialized is there anything that the static block accomplishes which a constructor cannot,['java'] +395196,why case always requires constant expression while if does not may be possible duplicate but could not have found the samesuppose i have following c code int aprintfenter number scanfda suppose entered only an integer ignoring return value of scanfi got a case to check whether a is zero or nonzeroifa printfd is nonzeroaelse printfd is zeroaeverything is fine using ifelse and i also know the other variations of ifelse to achieve this but problem comes with the switchcase as it says that we can implement everything in switchcase which we can do in ifelse but the following code failsswitcha case a printfd is nonzeroa break default printfd is zeroa breakalso i know to reverse the case in the above code like this below will work and i will have my answerswitchacase 0 printfd is zeroa breakdefault printfd is nonzeroa breakbut the question is why why ifa is valid while case a is not is switchcase a compile time operation and if runtime,['c'] +395222,jquery widget has no method extend i am working on a wordpress site which contains a number of jquery and jquery uidependent plugins everything seemed to be working fine but when we moved over the entire site to the new domain name i started seeing the following error in the chrome consoleuncaught typeerror object function bcdvar ebsplit0fbbsplit1febddccawidgetaexprffunctioncreturnadatacbaeaeaebfunctionabargumentslengththis createwidgetabvar gnew cgoptionsaextend0goptionsaebprototypeaextend0gnamespaceewidgetnamebwidgeteventprefixaebprototypewidgeteventprefixbwidgetbaseclassfdawidgetbridgebaeb has no method extendhere is the line in jquery ui 193 that seems to be causing thisthisoptions widgetextend thisoptionsthis getcreateoptionsoptions i cannot seem to get past this at all no matter what i tried to do i am using the proper method or so i have read to add scripts by using wp enqueue script and setting jquery as a dependency of jqueryui and looking at the html jquery is indeed loading before jquery uiif anyone has any idea of what might be happening i would really appreciate it this is driving me nuts,"['javascript', 'jquery']" +395223,is vec0 defined behavior for a stdvector vec i see this a lotstdvectorsomething vecdo something with vecvecsomething arrvec0do something that needs carrayarri mean a vector will probably use an array internally so i see why this works i am just wondering whether or not this is defined behavior like is an implementor allowed to run an implementation of stdvector with which this would breakif there are conflicts between the standards i am interested in what the c11 standard says,['c++'] +395247,are comparisons on outofrange pointers welldefined given the following codechar buffer1024char const begin bufferchar const end buffer 1024char p begin 20if p begin p end stdcout pointer is out of rangenare the comparisons performed p begin and p end welldefined or does this code have undefined behaviour because the pointer has been advanced past the end of the arrayif the comparisons are well defined what is that definitionextra credit is the evaluation of begin 20 itself undefined behaviour,['c++'] +395257,unmarshalling errors in android app with custom parcelable classes for my android application i get several unmarshalling errors although i think i have done everything that is needed to properly save and load objects via parcelables can you tell me whats wrong with my codeerror 1javalangruntimeexception unable to start activity componentinfocaused by javalangruntimeexception parcel androidosparcel41279860 unmarshalling unknown type code 6619241 at offset 1372at androidosparcelreadvalueparceljava1922at androidosparcelreadmapinternalparceljava2094at androidosbundleunparcelbundlejava223at androidosbundlegetparcelablebundlejava1158at androidappactivityoncreateactivityjava860at myapackageplaycomputeroncreateplaycomputerjava1012at androidappactivityperformcreateactivityjava4465line 1012 in myactivity is the call to superoncreatesavedinstancestate in the activitys oncreateprotected void onsaveinstancestatebundle savedinstancestate if myobject null savedinstancestateputparcelablemyobject null else savedinstancestateputparcelablemyobject myobject savedinstancestateputint savedinstancestateputstring savedinstancestateputboolean superonsaveinstancestatesavedinstancestatemyobject is of class myobject which has the following methodspublic void writetoparcelparcel out int flags outwriteintarray outwriteint outwritestringarray outwritestring outwriteparcelablearray flagspublic static final parcelablecreatormyobject creator new parcelablecreatormyobject public myobject createfromparcelparcel in try if in null return null else return new myobjectin catch exception e return null public myobject newarrayint size return new myobjectsize private myobjectparcel in inreadintarray inreadint inreadstringarray inreadstring otherobject inreadparcelablearrayotherobjectclassgetclassloadererror 2javalangruntimeexception unable to start activity componentinfocaused by androidosbadparcelableexception classnotfoundexception when unmarshallingat androidosparcelreadparcelableparceljava1971at androidosparcelreadvalueparceljava1859at androidosparcelreadmapinternalparceljava2099at androidosbundleunparcelbundlejava223at androidosbundlegetparcelablebundlejava1158at androidappactivityoncreateactivityjava905at myapackageplaycomputeroncreatesourcefile1012same files and classeserror 3javalangruntimeexception unable to start activity componentinfocaused by javalangruntimeexception parcel androidosparcel4051aff8 unmarshalling unknown type code 7340149 at offset 1276at androidosparcelreadvalueparceljava1913at androidosparcelreadmapinternalparceljava2083at androidosbundleunparcelbundlejava208at androidosbundlegetparcelablebundlejava1100at myapackageplaycomputeroncreatesourcefile1this time the causing line 1 is the following onemyobject myobject savedinstancestategetparcelablemyobject,['android'] +395292,simple neural network cannot learn xor i am trying to learn about neural networks and coded a simple backpropagation neural network that uses sigmoid activation functions random weight initialization and learninggradient momentumwhen configured with 2 inputs 2 hidden nodes and 1 it fails to learn xor and and however it will correctly learn ori fail to see what i have done wrong and so any help would be greatly appreciatedthanksedit as stated i tested with 2 hidden nodes but the code below shows a configuration of 3 i simply forgot to change this back to 2 after running tests using 3 hidden nodesnetworkrbmodule neuralclass network attr accessor num inputs num hidden nodes num output nodes input weights hidden weights hidden nodes output nodes inputs output error gradients hidden error gradients previous input weight deltas previous hidden weight deltas def initializeconfig initialize inputconfig initialize nodesconfig initialize weights end def initialize inputconfig selfnum inputs configinputs selfinputs arraynewnum inputs1 selfinputs1 1 end def initialize nodesconfig selfnum hidden nodes confighidden nodes selfnum output nodes configoutput nodes treat threshold as an additional inputhidden node with no incoming inputs and a value of 1 selfoutput nodes arraynewnum output nodes selfhidden nodes arraynewnum hidden nodes1 selfhidden nodes1 1 end def initialize weights treat threshold as an additional inputhidden node with no incoming inputs and a value of 1 selfinput weights arraynewhidden nodessizearraynewnum inputs1 selfhidden weights arraynewoutput nodessizearraynewnum hidden nodes1 set random weightsinput weights set random weightshidden weights selfprevious input weight deltas arraynewhidden nodessizearraynewnum inputs10 selfprevious hidden weight deltas arraynewoutput nodessizearraynewnum hidden nodes10 end def set random weightsweights 0weightssizeeach do i 0weightsisizeeach do j weightsij rand100 49to f 100 end end end def calculate node valuesinputs inputseach index do i selfinputsi inputsi end set node valuesselfinputs input weights hidden nodes set node valueshidden nodes hidden weights output nodes end def set node valuesvalues weights nodes 0weightssizeeach do i nodesi networksigmoidvalueszipweightsimapvw vwinject end end def predictinputs calculate node valuesinputs output nodessize 1 output nodes0 output nodes end def traininputs desired results learning rate momentum rate calculate node valuesinputs backpropogate weightsdesired results learning rate momentum rate end def backpropogate weightsdesired results learning rate momentum rate output error gradients calculate output error gradientsdesired results hidden error gradients calculate hidden error gradientsoutput error gradients update all weightsinputs desired results hidden error gradients output error gradients learning rate momentum rate end def selfsigmoidx 10 1 mathex end def selfdsigmoidx sigmoidx 1 sigmoidx end def calculate output error gradientsdesired results desired resultszipoutput nodesmapdesired result desired result networkdsigmoidresult end def reversed hidden weights arrayhidden nodeweights to output nodes reversed arraynewhidden nodessizearraynewoutput nodessize hidden weightseach index do i hidden weightsieach index do j reversedji hidden weightsij end end reversed end def calculate hidden error gradientsoutput error gradients reversed reversed hidden weights hidden nodeseach with indexmap do node i networkdsigmoidhidden nodesi output error gradientszipreversedimaperror weight errorweightinject end end def update all weightsinputs desired results hidden error gradients output error gradients learning rate momentum rate update weightshidden nodes inputs input weights hidden error gradients learning rate previous input weight deltas momentum rate update weightsoutput nodes hidden nodes hidden weights output error gradients learning rate previous hidden weight deltas momentum rate end def update weightsnodes values weights gradients learning rate previous deltas momentum rate weightseach index do i weightsieach index do j delta learning rate gradientsi valuesj weightsij delta momentum rate previous deltasij previous deltasij delta end end endendendtestrbusrbinrubyload networkrblearning rate 03momentum rate 02nn neuralnetworknewinputs 2 hidden nodes 3 output nodes 110times do i xor does not work nntrain0 0 0 learning rate momentum rate nntrain1 0 1 learning rate momentum rate nntrain0 1 1 learning rate momentum rate nntrain1 1 0 learning rate momentum rate and very rarely works nntrain0 0 0 learning rate momentum rate nntrain1 0 0 learning rate momentum rate nntrain0 1 0 learning rate momentum rate nntrain1 1 1 learning rate momentum rate or works nntrain0 0 0 learning rate momentum rate nntrain1 0 1 learning rate momentum rate nntrain0 1 1 learning rate momentum rate nntrain1 1 1 learning rate momentum rateendputs testing puts 0 0puts result nnpredict0 0to sputsputs 1 0puts result nnpredict1 0to sputsputs 0 1puts result nnpredict0 1to sputsputs 1 1puts result nnpredict1 1to sputs,['ruby'] +395295,ios subclass uicollectionviewcell custom init method i am implementing a custom uicollectionviewcell and i want to know how to send model data to it so the data can be used to initialize the subviews of the celli register my mycollectionviewcell by doingselfcollectionview registerclassmycollectionviewcell class forcellwithreuseidentifiermycelland in the following method i do uicollectionviewcell collectionviewuicollectionview collectionview cellforitematindexpathnsindexpath indexpath mycollectionviewcell cell selfcollectionview dequeuereusablecellwithreuseidentifiermycell forindexpathindexpaththe problem i am facing is when a cell is not in the reuse queue it initializes a new cell by calling the initwithframe method which the documentation confirms should happen however i have a custom init method in my mycollectionviewcell class which is id initwithframecgrectframe withdata nsdictionary datai want my custom initialize method to be called instead how would i do that i am not using any nibs and i am doing everything programmatically if there is no way and i must use the initwithframe method instead how else can i pass model data to my mycollectionviewcell so that i can initialize the subviews with that datathanks,"['iphone', 'ios']" +395320,pointers on modern opengl shadow cubemapping backgroundi am working on a 3d game using c and modern opengl 33 i am now working on the lighting and shadow rendering and i have successfully implemented directional shadow mapping after reading over the requirements for the game i have decided that i would be needing point light shadow mapping after doing some research i thiscovered that to do omnidirectional shadow mapping i will do something similar to directional shadow mapping but with a cubemap insteadi have no previous knowledge of cubemaps but my understanding of them is that a cubemap is six textures seamlessly attached i did some looking around but unfortunately i struggled to find a definitive tutorial on the subject for modern opengl i look for tutorials first that explain it from start to finish because i seriously struggled to learn from snippets of source code or just concepts but i triedcurrent understandingshere is my general understanding of the idea minus the technicalities please correct mefor each point light a framebuffer is set up like directional shadowmappinga single cubemap texture is then generated and bound with glbindtexturegl texture cube map shadowmapthe cubemap is set up with the following attributesgltexparameterigl texture cube map arb gl texture wrap s gl clamp to edgegltexparameterigl texture cube map arb gl texture wrap t gl clamp to edgegltexparameterigl texture cube map arb gl texture wrap r gl clamp to edgegltexparameterigl texture cube map gl texture min filter gl lineargltexparameterigl texture cube map gl texture mag filter gl linearthis is also similar to directional shadowmappingnow glteximage2d is iterated through six times once for each face i do that like this for int face 0 face 6 face fill each face of the shadow cubemap glteximage2dgl texture cube map positive x face 0 gl depth component32f 1024 1024 0 gl depth component gl float nullthe texture is attached to the framebuffer with a call toglframebuffertexturegl framebuffer gl depth attachment shadowmap 0when the scene is to be rendered it is rendered in two passes like directional shadow mapping first of all the shadow framebuffer is bound the viewport is adjusted to the size of the shadowmap 1024 by 1024 in this caseculling is set to the front faces with glcullfacegl frontthe active shader program is switched to the vertex and fragment shadow shaders that i will provide the sources of further downthe light view matrices for all six views are calculated i do it by creating a vector of glmmat4s and push back the matrices like this create the six view matrices for all six sidesfor int i 0 i renderedobjectssize i iterate through all rendered objects renderedobjectsibindbuffers bind buffers for rendering with it glmmat4 depthmodelmatrix renderedobjectsigetmodelmatrix set up model matrix for int i 0 i 6 i draw for each side of the light glframebuffertexture2dgl framebuffer gl depth attachment gl texture cube map positive x i shadowmap 0 glcleargl depth buffer bit clear depth buffer send mvp for shadow map glmmat4 depthmvp depthprojectionmatrix depthviewmatricesi depthmodelmatrix gluniformmatrix4fvglgetuniformlocationshadowmappingprogram depthmvp 1 gl false glmvalue ptrdepthmvp gluniformmatrix4fvglgetuniformlocationshadowmappingprogram lightviewmatrix 1 gl false glmvalue ptrdepthviewmatricesi gluniformmatrix4fvglgetuniformlocationshadowmappingprogram lightprojectionmatrix 1 gl false glmvalue ptrdepthprojectionmatrix gldrawelementsrenderedobjectsigetdrawtype renderedobjectsigetelementsize gl unsigned int 0 the default framebuffer is bound and the scene is drawn normallyissuenow to the shaders this is where my understanding runs dry i am completely unsure on what i should do my research seems to conflict with eachother because it is for different versions i ended up blandly copying and pasting code from random sources and hoping it would achieve something other than a black screen i know this is terrible but there does not seem to be any clear definitions on what to do what spaces do i work in do i even need a separate shadow shader like i used in directional point lighting what the hell do i use as the type for a shadow cubemap samplercube samplercubeshadow how do i sample said cubemap properly i hope that someone can clear it up for me and provide a nice explanationmy current understanding of the shader part is when the scene is being rendered into the cubemap the vertex shader simply takes the depthmvp uniform i calculated in my c code and transforms the input vertices by them the fragment shader of the cubemap pass simply assigns the single out value to the gl fragcoordz this part is unchanged from when i implemented directional shadow mapping i assumed it would be the same for cubemapping because the shaders do not even interact with the cubemap opengl simply renders the output from them to the cubemap right because it is a framebufferthe vertex shader for the normal rendering is unchangedin the fragment shader for normal rendering the vertex position is transformed into the lights space with the lights projection and view matrixthat is somehow used in the cubemap texture lookup once the depth has been retrieved using magical means it is compared to the thistance of the light to the vertex much like directional shadowmapping if it is less that point must be shadowed and viceversait is not much of an understanding i go blank as to how the vertices are transformed and used to lookup the cubemap so i am going to paste the source for my shaders in hope that people can clarify this please note that a lot of this code is blind copying and pasting i have not altered anything as to not jeoparthise any understandingshadow vertex shaderversion 150in vec3 positionuniform mat4 depthmvpvoid main gl position depthmvp vec4position 1shadow fragment shaderversion 150out float fragmentdepthvoid main fragmentdepth gl fragcoordzstandard vertex shaderversion 150in vec3 positionin vec3 normalin vec2 texcoorduniform mat3 modelinversetransposeuniform mat4 modelmatrixuniform mat4 viewmatrixuniform mat4 projectionmatrixout vec3 fragnormalout vec3 fragnormaldirectionout vec2 fragtexcoordout vec4 fragpositionout vec4 fragshadowcoordvoid main fragposition modelmatrix vec4position 10 fragtexcoord texcoord fragnormaldirection normalizemodelinversetranspose normal fragnormal normalizenormal fragshadowcoord projectionmatrix viewmatrix modelmatrix vec4position 10 gl position projectionmatrix viewmatrix modelmatrix vec4position 10standard fragment shaderversion 150out vec4 outcolourin vec3 fragnormaldirectionin vec2 fragtexcoordin vec3 fragnormalin vec4 fragpositionin vec4 fragshadowcoorduniform mat4 modelmatrixuniform mat4 viewmatrixuniform mat4 projectionmatrixuniform mat4 viewmatrixinverseduniform mat4 lightviewmatrixuniform mat4 lightprojectionmatrixuniform sampler2d texuniform samplercubeshadow shadowmapfloat vectortodepthvaluevec3 vec vec3 absvec absvec float localzcomp maxabsvecx maxabsvecy absvecz const float f 20480 const float and 10 float normzcomp fn fn 2fnfnlocalzcomp return normzcomp 10 05float computeshadowfactorsamplercubeshadow shadowcubemap vec3 verttolightws float shadowvec textureshadowcubemap vec4verttolightws 10 if shadowvec 01 vectortodepthvalueverttolightws to avoid self shadowing i guess return 10 return 07void main vec3 light position vec300 00 00 vec3 verttolightws light position fragpositionxyz outcolour texturetex fragtexcoord computeshadowfactorshadowmap verttolightwsi cannot remember where the computershadowfactor and vectortodepthvalue function code came from because i was researching it on my laptop which i cannot get to right now but this is the result of those shadersit is a small square of unshadowed space surrounded by shadowed spacei am obviously doing a lot wrong here probably centered on my shaders due to a lack of knowledge on the subject because i find it difficult to learn from anything but tutorials and i am very sorry for that i am at a loss it it would be wonderful if someone can shed light on this with a clear explanation on what i am doing wrong why it is wrong how i can fix it and maybe even some code i think the issue may be because i am working in the wrong spaces,['c++'] +395321,how to specify date format when using pandasto csv the default output format of to csv is12142012 120 ami cannot figure out how to output only the date part with specific format20121214or date and time in two separate columns in the csv file20121214 084530the documentation is too brief to give me any clue as to how to do these can anyone help,['python'] +395327,using php to write large amount of data to excel without memory limit error i have a oracle database where large amount of biometric data like hrv and ecg is stored i need to show this data for each users in excel sheet but this data is so large even for a single user we are getting more than 10 records there are currently 100 users what i am doing is i execute a cron job using command line for the same which i developed in zend frameworki make sure that the this cron does not overlapi get all the data from oracle database for each user one by one then i store this in an arraywhen i get data for all users then i am using phpexcel library to generate excel sheetstructure of excel sheetuid 1 uid2 uid3 nthdata data data data data data nthproblem php takes 15 gb of ram and stores the data in array and send it to the functions for interacting with phpexcel but this library takes 34 hours and then i get fatal memory limit error my system has only 2 gb ramwhat steps i should take to optimize my code to handle data of this size and thisplaying the same information in excel format or i need to increase the ram,['php'] +395333,unable to create android avd because of target and cpuabi settings i am running juno and just beginning to learn android programming on mac on the latest sdk 42 api 17 and when i try to create an avd and as you can see from the screenshot actually never mind as a new user i am not allowed to post a screen shot i can input my title i can also choose my device but when i try to change the dropdown menus of the target and cpuabi options they do not drop at all also the typical hardware box in which you add and delete chosen hardware is not present maybe just because of the newer eclipse version anyhow why are not these options given to me also this ends up in me having an ok button still being grayed out thanks,['android'] +395370,how to select after element using jquery bellow is my codeswhat i have triedwhen this popup appear i want to use this close button to close entire popboxcss codebigdiv thisplaynone backgroundcolorefefef boxshadow 10px 10px 10px 10px rgba0 0 0 04 border2px solid efefef width400px height300px positionfixed zindex500 top25 left25 margin0 auto padding20px bigdivafter cursorpointer contenturl position relative right 195px top 310px zindex 9 jqueryleft divclickfunction bigdivshowslow bigdivclickfunction bigdivhide htmldiv classleftdivintro text heredivdivdivdivdivdivdiv classbigdivsome contentdivi want to select after elements how to do that using jquery,"['javascript', 'jquery', 'html', 'css']" +395387,what is this denormal data about c i would like to have a broad view about denormal data and what it is about because the only thing that i think i got right is the fact that is something especially related to floating point values from a programmer viewpoint and it is related to a generalcomputing approach from the cpu standpoint someone can decrypt this 2 words for me thankseditplease remember that i am oriented to c applications and only the c language,['c++'] +395397,how to add key and a value to a json using javascript or jquery i have a json variable like thisvar jsondataalltruei want to push another key and value to the jsondata after that my jsondata have to be like thisalltruefdamountfalseddamounttruehow to do that i tried jsondatapushfdamountfalse and jsondatapushfdamountfalse both of these method is not working thank you,['javascript'] +395402,how to cancel a playing sound started with audioservicesplaysystemsound is there a way to cancel pause or stop a sound that started playing through a call to audioservicesplaysystemsound,"['iphone', 'ios']" +395415,optimal io buffering programmers or kernels task my task is very simple read and parse a large file in c on linux there are two waysparse byte by bytewhile fgetc do something with the char parse buffer by bufferwhile char buffersome large number freadbuffer some large number 1 parse the buffer now parsing byte by byte is easier for me no check for how full the buffer is etc however i heard that reading large pieces is more efficientwhat is the philosophy is optimal buffering a task of the kernel so it is already buffered when i call fgetc or is it suggested that i handle it to gain best efficiencyalso apart from all philosophy whats the reality on linux here,['c++'] +395440,is there a workaround to c not being able to infer generic type arguments using type constraints eric lippert has explained in his blog post at why constraints are not considered for type inference which makes sense given that methods cannot be overloaded by simply changing type constraints however i would like to find a way to instantiate an object using two generic types one which can be inferred and another which could be inferred if constraints were considered without having to specify any of the typesgiven the typespublic interface it othert createotherpublic class c istring public otherstring createother return new otherstring public class othertand the factorypublic static class factory1 public static tuplet othert1 createt t1t o where t it1 return new tuplet othert1o ocreateother the following desired code will not compile public void wontcompile c c new c var v factory1createc would not compile the error message is error cs0411 the type arguments for method yofactory1createt cannot be inferred from the usage try specifying the type arguments explicitly which is in line with what eric said in his blog postthus we can simply specify the generic type arguments explicitly as the error message suggests public void specifyalltypes c c new c var v factory1createc stringc type is tuplec otherstring if we do not wish to specify type arguments and we do not need to retain type c we can use the following factorypublic static class factory2 public static tupleit1 othert1 createuntypedt1it1 o return new tupleit1 othert1o ocreateother and now specify public void untyped c c new c var v factory2createuntypedc type is tupleistring otherstring however i wish to retain type c in the returned object and not specify the types,['c#'] +395468,fft in python not showing peaks in right place i am trying to understand the numpy fft function because my data reduction is acting weirdly but now that i have transformed a simple sum of two sines i get weird results the peaks i have is extremely high and several points wide around zero flattening the rest does anybody have a clue of what i might be doing wrong import numpy as npfrom numpy import exp sqrt pi linspacefrom matplotlib import cmimport matplotlibpyplot as pltimport scipy as spimport pylabfouriertdata nparange59300datay 3npsintdata6npsin2tdatafouriery npfftfftdatayfreqs npfftfftfreqdataysize d01pylabplotfreqsfourierypylabshowwhat i get is thiswhile it should have two sidepeaks on both sides one of em 2x higher than the other,['python'] +395469,variadic templates ambiguous call the following code compiles in both gcc 472 and msvc110template typename tvoid foot bar template typename t typename argsvoid foot bar args args int main foo0 okwhy i think that it is must be ambiguous callisoiec 148822014562 partial ordering of function templates tempfuncorder5 exampletemplateclass t class u void ft u 1templateclass t void ft 2templateclass t class u void gt u 3templateclass t void gt 4void hint i fi error ambiguousgi ok calls 3aend example,['c++'] +395485,always getting 401 unauthorized with new install of rails devise i have a new install of rails and am trying to set up authentication with devise as far as i can tell i have a very basic set up that should work but whenever i try to log in with the default devise sign in form i get an unauthorized error i am sure my credentials are correct as i created a user to test with in the console like sousernewemail priv level admin passwordmypassword password confirmationmypasswordsavemy user modelclass user activerecordbase include default devise modules others available are token authenticatable confirmable lockable timeoutable and omniauthable devise database authenticatable recoverable rememberable trackable validatable confirmable setup accessible or protected attributes for your model attr accessible email password password confirmation remember me priv level unconfirmed email attr accessible title body has one supplierendmy logstarted post adminusersign in for 127001 at 201212 131056 0500processing by adminsessionscontrollercreate as htmlparameters utf8a authenticity tokenwylsalxn9rtv8p8bvyut0wzcvlfbu6b1svocykttcii admin useremail passwordfiltered remember me0 commitsign inuser load 02ms select users from users where usersemail limit 101ms begin transaction00ms commit transactioncompleted 401 unauthorized in 69msis there any way i can get more information about what is failing from devise when i create the user in the console is the encryption used different than through the forms,"['ruby-on-rails', 'ruby']" +395510,android searchview icon i want to thisable the mag icon thisplayed inside the search view component any idea how to reference it and remove it or replace it with another drawable,['android'] +395542,implementing abstract generic method in java with multiple generics types i will ask a very short question and hope to someone can help me towards a solution it abouts generics methods in java with two generics types one for return type and another for a formal paremeter and how to implement iti guess i am missing something in the picture to get it work the matter is thisthis is working public enum getter billitemssize override public integer get object entity desiredclass ref desiredclass entity old time cast do things public abstract tk t get k entity this is not working public enum getter billitemssize override public integer get desiredclass entity no cast at all do things public abstract tk t get k entity the java compiler yells me this anonymous datasourcedbgetter1 is not abstract and does not override abstract method tkgetk in getterwell that is the situationthanks in advance to allhope it helps others in the futurepd it is not a problem of enums types it happens across classes hierarchies so do not bother blaming the emuns i tried this and does not works neitherpublic abstract class superclass public abstract te t pepe e epublic class subclass extends superclass override public integer pepedesiredclass e fails return null updatedfor generics parameterswe can make a general rule statement that for generics parameter those whose types is generic the type implicitly taken in the method signature is equals to upper limits of that generic that can be object if nothing is specified or a more specific subclass if upper bounds are used in example t extends stringfor generics returns typesthere is no problem overwriting a generic method with a specific return type as long the return type is a subtype of the overwritten return type and what is the return type at first place well it happens to be object by default the compiler assumes in the method signature the generic type as an object type so we have to thing that the trick is to know that any method that have a generic return type are actually having an object return type then if in any subclasses the method is overwritten and we alter he return type stating that return another type there will be no problem because besides that method will return an object of another class that object returned will inevitable be subclass of the object class and there will be no problem overwrite a method with a different return type that the original as long it be a subtype of the original the technique called covariant return type allow us to do such thingpublic abstract class superclass public abstract t t operation public class subclass extends superclass override public chair operation bla bla meanwhile in another part of the codevoid main subclass sb new subclass chair chair sboperation the chair type can be easely replaced by super type like object object object sboperationthanks to all the folks who help clear this out,['java'] +395549,how do you force mysql like to be case sensitive possible duplicatemysql like case sensitive mysql ignores case for its like comparisonshow can you force it to perform casesensitive like comparisons,"['mysql', 'sql']" +395551,get userinfo from google oauth 20 php api i am trying to use google oauth api to get userinfoit works perfectly for google plus api but i am trying to create a backup in case the user does not have google plus accountthe authentication process is correct and i even get the userinfo object but how exactly do i access the properties i tried userinfoget but it only return the id of the useram i doing something wrong here is the code that i am usingrequire once srcgoogle clientphprequire once srccontribgoogle oauth2servicephpsession startclient new google clientclientsetapplicationnamegoogle php starter application visit to generate your oauth2 client id oauth2 client secret and to register your oauth2 redirect uri clientsetclientid clientsetclientsecret clientsetredirecturi clientsetdeveloperkeyplus new google oauth2serviceclientif isset requestlogout unset sessionaccess tokenif isset getcode clientauthenticate getcode sessionaccess token clientgetaccesstoken headerlocation http serverhttp host serverphp selfif isset sessionaccess token clientsetaccesstoken sessionaccess tokenif clientgetaccesstoken userinfo plususerinfo print ruserinfoget else authurl clientcreateauthurldoctype htmlhtmlhead meta charsetutf8 link relstylesheet hrefstylecss headbodyheaderh1google sample apph1headerdiv classboxphp ifissetpersonmarkup div classmephp print personmarkup divphp endif php ifissetauthurl print a classlogin hrefauthurlconnect mea else print a classlogout hreflogoutlogouta divbodyhtmlthankseditwas missing scopesadded clientsetscopesarrayworks now,['php'] +395573,a private variable can be accessed from another object of the same type possible duplicatewith a private modifier why can the member in other objects be accessed directly private members of a c class are designed to be invisible to other class instances i am confused since private members can be accessed as shown below can anyone explain it to meheres my codeinclude iostream using namespace std class personprivate char name int agepublic personchar nametemp int agetemp name new charstrlennametemp 1 strcpyname nametemp age agetemp person ifname null delete name name null bool compareperson p p can access the private param p this is where confused me ifthisage page return false return true int main person phello world 23 return 0,['c++'] +395575,usage of the copy property attribute to maintain an immutable nsstring i am very new to ios development and programming in objectivec i have been doing the exercises on the app dev library this is the current exercise that i am trying to understand3 test what happens if you set a mutable string as the personas first name then mutate that string before calling your modified sayhello method change the nsstring property declarations by adding the copy attribute and test againi attempt to do this however the nsstring that i modify does in fact change despite the use of the copy property attributehere are my declarations and implementations as well as my test codexyzpersonhimport foundationfoundationhinterface xyzperson nsobjectproperty copy nsstring firstnameproperty nsstring lastnameproperty nsdate dob voidsayhello voidsaysomethingnsstring greeting idinit idpersonwithfirstnamensstring firstname lastnamensstring lastname dobnsdate dateofbirthendxyzpersonmimport xyzpersonhimplementation xyzpersonsynthesize firstname firstnamesynthesize lastname lastnamesynthesize dob dob voidsayhello self saysomethinghello world nslogthis is selffirstname selflastname voidsaysomethingnsstring greeting nslog greeting idinit return self personwithfirstnameyorick lastnamerobinson dob8231990 idpersonwithfirstnamensstring firstname lastnamensstring lastname dobnsdate dateofbirth xyzperson person self alloc init personfirstname firstname personlastname lastname persondob dateofbirth return personendtest codeimport uikituikithimport appdelegatehimport xyzpersonhimport xyzshoutingpersonhint mainint argc char argv autoreleasepool xyzperson guy xyzperson init guy sayhello i thought that this change would never be made but it is everytime i run the code guyfirstname darryl guy sayhello xyzshoutingperson girl xyzshoutingperson init girl sayhello return uiapplicationmainargc argv nil nsstringfromclassappdelegate class,['ios'] +395583,android invalidateoptionsmenu for api 11 i used activitycompatinvalidateoptionsmenumainactivitythis so that my menu item refresh can automatically be enabledthisabled without the using have to touch the menu option imagine the user leaves the menu open i need the refresh menu item to automatically thisabled and enable itself the activitycompatinvalidateoptionsmenumainactivitythis works fine in android 11 but what can i use for android api 11 s i have searched so much but i cannot find an answer can anyone please help me on this this works fine in android api 11 using the onprepareoptionsmenu and activitycompatinvalidateoptionsmenumainactivitythis the issue is trying to get it done in android api 11here is my onprepareoptionsmenu method overridepublic boolean onprepareoptionsmenumenu menu ifmenurefreshenable menugetitem0setenabledtrue ifmenurefreshenable menugetitem0setenabledfalse return true,['android'] +395586,localstorage returning null in a different tab in chrome this is my issuei update the localstorage in popupjs in a new tab i access the same localstoragesame key in the backgroundjs now this is returning null in every tab apart from the chromeextensions tabwhen i load the extensions i thought localstorage was persistant across all tabs codepopupjsdocumentreadyfunction alertlocalstoragegetitemfilters var oldfilters localstoragegetitemfilters all the filters show up on the popuphtml page documentgetelementbyidtd1innerhtml oldfilters var dat oldfilters newarrayj localstoragesetitemfiltersstringdatbackgroundjswindowreadyfunction handler for ready called var filters localstoragegetitemfilters alertbackground filters this shows all the filters in the chromeextensions page but always pops up background null in every new tab load changeimagefilters,['javascript'] +395605,what does assignable really mean c11 removed the requirement that the value type of all containers be copyconstructible and assignable although specific operations on containers may impose these requirements in theory that should make it possible to define for example stddequeconst foo which was not possible in c03unexpectedly gcc 472 produced its usual vomit of incomprehensible errors 1 when i tried this but clang at least made the error readable and clang with libc compiled it with no errorsnow when two different compilers produce different results it always makes me wonder what the correct answer is and so i searched out all the references i could find to constassignablevalue typescontainers etc etc i found almost a decades worth of very similar questions and answers some of them here on so and others in the various c mailing lists amongst other places including the gnu buganizer all of which basically can be summarized as following dialogueq why cannot i declare stdvectorconst int as a simplified examplea why on earth would you want to do that it is nonsensicalq well it makes sense to me why cannot i do ita because the standard requires value types to be assignableq but i am not planning on assigning them i want them to be const after i have created thema that is not the way it works next questionwith a mild dashing ofa2 c11 has decided to allow that youll just have to wait in the meantime rethink your ridiculous designthese do not seem like very compelling answers although possibly i am biased because i fall into the category of but it makes sense to me in my case i would like to have a stacklike container in which things pushed onto the stack are immutable until they are popped which does not strike me as a particularly odd thing to want to be able to express with a type systemanyway i started thinking about the answer the standard requires all containers value types to be assignable and as far as i can see now that i found an old copy of a draft of the c03 standard that is true it didon the other hand the value type of stdmap is stdpairconst key t which does not look to me like it is assignable still i tried again with stddequestdtupleconst foo and gcc proceeded to compile it without batting an eye so at least i have some kind of workaroundthen i tried printing out the value of stdis assignableconst foo const foo and stdis assignablestdtupleconst foo const stdtupleconst foo and it turns out that the former is reported as not assignable as youd expect but the latter is reported as assignable by both clang and gcc of course it is not really assignable attempting to compile a b is rejected by gcc with the complaint error assignment of readonly location this was just about the only error message i encountered in this quest which was actually easy to understand however without the attempt to do an assignment both clang and gcc are equally happy to instantiate the dequeconst and the code seems to run finenow if stdtupleconst int really is assignable then i cannot complain about the inconsistency in the c03 standard and really who cares but i find it thisturbing that two different standard library implementations report that a type is assignable when in fact attempting to assign to a reference of it will lead to a very sensible compiler error i might at some point want to use the test in a template sfinae and based on what i saw today it does not look very reliableso is there anyone who can shed some light on the question in the title what does assignable really mean and two bonus questions1 did the committee really mean to allow instantiating containers with const value types or did they have some other nonassignable case in mind and2 is there really a significant difference between the constnesses of const foo and stdtupleconst foo1 for the truly curious heres the error message produced by gcc when trying to compile the declaration of stddequeconst stdstring with a few lineendings added and an explanation if you scroll down far enoughin file included from usrincludex86 64linuxgnuc47bitscallocatorh340 from usrincludec47bitsallocatorh48 from usrincludec47string43 from usrincludec47random41 from usrincludec47bitsstl algoh67 from usrincludec47algorithm63 from const stackcc1usrincludec47extnew allocatorh in instantiation of aclass gnu cxxnew allocatorconst stdbasic stringchar ausrincludec47bitsallocatorh8911 required from aclass stdallocatorconst stdbasic stringchar ausrincludec47bitsstl dequeh48961 required from aclass std deque baseconst stdbasic stringchar stdallocatorconst stdbasic stringchar ausrincludec47bitsstl dequeh72811 required from aclass stddequeconst stdbasic stringchar aconst stackcc11227 required from hereusrincludec47extnew allocatorh837 error aconst tp gnu cxxnew allocator templateparameter11 address gnu cxxnew allocator templateparameter11 const reference const with tp const stdbasic stringchar gnu cxxnew allocator templateparameter11 const pointer const stdbasic stringchar gnu cxxnew allocator templateparameter11 const reference const stdbasic stringchara cannot be overloadedusrincludec47extnew allocatorh797 error with a tp gnu cxxnew allocator templateparameter11 address gnu cxxnew allocator templateparameter11 reference const with tp const stdbasic stringchar gnu cxxnew allocator templateparameter11 pointer const stdbasic stringchar gnu cxxnew allocator templateparameter11 reference const stdbasic stringcharaso whats going on here is that the standard 20691 insists that the default allocator have member functionspointer addressreference x const noexceptconst pointer addressconst reference x const noexceptbut if you instantiate it with a const template argument which is apparently ub then reference and const reference are the same type and so the declarations are duplicated the body of the definition is identical for what it is worth consequently no allocatoraware container can deal with an explicitly const value type hiding the const inside a tuple allows the allocator to instantiate this allocator requirement from the standard was used to justify closing at least a couple of old libstdc bugs about problems with stdvectorconst int although it does not strike me as a solid point of principle also libc works around the problem in the obvious simple way which is to provide a specialization of allocatorconst t with the duplicate function declarations removed,['c++'] +395606,c immutable int in java strings are immutable if we have a string and make changes to it we get new string referenced by the same variablestring str abcstr def now str refers to another piece in the heap containing abcdef while abc is still somewhere in the heap until taken by gcit is been said that int and double are immutable in c does it mean that when we have int and later change it we would get new int pointed by the same variable same thing but with stackint i 1i 1 same thing in the stack there is value 2 to which variable i is attached and somewhere in the stack there is value 1is that correct if not in what way is int immutable,['c#'] +395608,relativelayout weight i do have 3 relativelayout which is inside the main relativelayout the view will be vertically so i have 3 relativelayout which setted next to each other and i want them to fill the whole screen doesnt matter what will be the screen size my layout viewrelativelayout xmlnsandroidxmlnstoolsandroidlayout widthmatch parentandroidlayout heightmatch parentandroidbackgrounddrawablebackg imageview androidididimageview1 androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentlefttrue androidlayout alignparenttoptrue androidlayout margintopdimentop mr image androidsrcdrawabletemp relativelayout androidididr1 androidlayout width0dp androidlayout heightwrap content androidlayout alignparentbottomtrue androidlayout alignparentlefttrue androidlayout belowidimageview1 androidlayout marginleft10dp androidbackgrounddrawabler1bg androidlayout weight1 textview androidididtextview1 androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentlefttrue androidlayout marginleftdimentxt mr right androidlayout marginrightdimentxt mr right androidlayout margintop39dp androidtexts androidtextappearanceandroidattrtextappearancelarge textview androidididtextview2 androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentlefttrue androidlayout belowidtextview1 androidlayout marginleftdimentxt mr right androidlayout marginrightdimentxt mr right androidtextt androidtextappearanceandroidattrtextappearancelarge relativelayout relativelayout androidididr2 androidlayout width0dp androidlayout heightwrap content androidlayout alignparentbottomtrue androidlayout aligntopidr1 androidlayout torightofidr1 androidlayout weight1 relativelayout relativelayout androidididr3 androidlayout width0dp androidlayout heightwrap content androidlayout alignparentbottomtrue androidlayout aligntopidr2 androidlayout torightofidr2 androidlayout weight1 relativelayouti set weight1 and layout width0dp for each releativelayout and this technique works with buttons i thought the same will be with relativelayout seems my thoughts were wrong any ideaupd1 i have added an image of what i would like to have,['android'] +395612,how to use malt parser in python nltk as a part of my academic project i need to parse a bunch of arbitrary sentences into a dependency graph after a searching a lot i got the solution that i can use malt parser for parsing text with its pre trained grammeri have downloaded pretrained model engmaltlinear17mco from but i do not know how to parse my sentences using this grammer file and malt parser by the python interface for malt i have downloaded latest version of malt parser 172 and moved it to usrlib import nltk parser nltkparsemaltmaltparsertxtthis is a test sentenceparsertrain from filehomerohithmalt172engmaltlinear17mcoparserraw parsetxtafter executing the last line the following eror message is thispalyedtraceback most recent call lastfile pyshell7 line 1 in moduleparserraw parsetxtfile usrlocallibpython27thistpackagesnltk20b5py27eggnltkparsemaltpy line 88 in raw parsereturn selfparsewords verbosefile usrlocallibpython27thistpackagesnltk20b5py27eggnltkparsemaltpy line 75 in parsereturn selftagged parsetaggedwords verbosefile usrlocallibpython27thistpackagesnltk20b5py27eggnltkparsemaltpy line 122 in tagged parsereturn dependencygraphloadoutput filefile usrlocallibpython27thistpackagesnltk20b5py27eggnltkparsedependencygraphpy line 121 in loadreturn dependencygraphopenfilereadioerror errno 2 no such file or directory tmpmalt outputconllplease help me to parse that sentence using this malt parser,['python'] +395622,solid principles and compilation for example regarding single responsibility principle let us talk about a radio class one could argue that the radio class has two responsibilities being volume and station management these operations will be called from completely different areas of the client using ithence we have this all finebut i always see sentences like these so now when we need a change all the code depending on the broken component donat even need to be recompiledwait a minute if i need to change the volumemanager class i will not have to recompile radio and stationmanagerbut i will have to stop in web the iis in order for the application to use the new dll and it will cause the application downalso in console i will have to terminate the whole program in order to change the dll since it is locked by the process you cant change dll when the app is running the file is lockedeven when i will use the gac i will have to stop the proram in order to chagne the dllso what does it save me compile is just right click and build thats alli am not seeing the benefit of mentioning you will need to compile only the broken classwhat am i missing look for the word build principleshtml look for the word recompiled look for the word recompile,"['c#', '.net']" +395642,jquery mobile what is the order of page events triggering i have to build fast a prototype for an application and i would like to know exactly where to insert various application logiccould you iterate the events and the order in which they trigger when using phonegap and jquerymobileit would be great to have a clear understanding of eventsorder fora when you open the application for the first time b when you change page i guess there would not be some of the eventsanymorec when you minimize the app ex when you click a link in the app which takes you to smscall or you just press devices home buttond when you restore the app ex hitting the back button or justmaximize it somehow,"['javascript', 'jquery']" +395645,abaddressbookcreate abaddressbookgetgroupcount return 0x0 i am trying to get groups name but after many time call this method by the user to reload contacts it give the nil value and the following errorvoid getgroupsname groupsname removeallobjects address book object to interact with iphone contacts abaddressbookref addressbook abaddressbookcreate get groups count cfindex groupscount abaddressbookgetgroupcountaddressbook get all available groups as array cfarrayref allgroups abaddressbookcopyarrayofallgroupsaddressbook for int i 0 igroupscount i get group of indexi from groups array abrecordref group cfarraygetvalueatindexallgroups i get group name i use bridge transfer to transfer from c to objectivec groupsname addobject bridge transfer nsstringabrecordcopycompositenamegroup cfreleaseallgroups cfreleaseaddressbook warning could not compile statement pragma journal mode wal unable to open database file error 14 creating properties table unable to open database file warning could not compile statement select value from sqlitedatabaseproperties where key unable to open database file warning could not compile statement select value from sqlitedatabaseproperties where key unable to open database file warning could not compile statement select value from sqlitedatabaseproperties where key unable to open database file warning could not compile statement select rowid first last middle null null null organization null null kind null null nickname prefix suffix firstsort lastsort creationdate modificationdate compositenamefallback null storeid null firstsortsection lastsortsection firstsortlanguageindex lastsortlanguageindex null null null personlink null ispreferredname from abperson unable to open database file warning could not compile statement select rowid first last middle null null null organization null null kind null null nickname prefix suffix firstsort lastsort creationdate modificationdate compositenamefallback null storeid null firstsortsection lastsortsection firstsortlanguageindex lastsortlanguageindex null null null personlink null ispreferredname from abperson unable to open database file warning could not compile statement insert or replace into sqlitedatabaseproperties values unable to open database file warning could not compile statement select value from sqlitedatabaseproperties where key unable to open database file warning could not compile statement insert or replace into sqlitedatabaseproperties values unable to open database file warning could not compile statement select value from sqlitedatabaseproperties where key unable to open database file warning could not compile statement select value from sqlitedatabaseproperties where key unable to open database file warning could not compile statement select rowid from abgroup unable to open database file warning could not compile statement select rowid name externalidentifier storeid null null null from abgroup unable to open database fileso i use the native notification to let me know when addressbook get modified to decrease number of time i access the addressbook but still not good by the time if user make many update and everytime addrssbook get modified must call this meathod or any other one related to addressbookso still need your help,"['iphone', 'objective-c', 'ios']" +395660,generating fractal swirl i need to draw a fractal swirl using the algorithm iterated function systemthere are coefficients for this fractal0745455 0459091 0406061 0887121 1460279 0691072 09126750424242 0065152 0175758 0218182 3809567 6741476 0087325and here is my codeimport javaawtgraphicsimport javaxswingjpanelpublic class surface extends jpanel double a1 0745455double b1 0459091double d1 0406061double e1 0887121double c1 1460279double f1 0691072double p1 0912675double a2 0424242double b2 0065152double d2 0175758double e2 0218182double c2 3809567double f2 6741476double p2 0087325double x1double x double y return a1 x b1 y c1double y1double x double y return d1 x e1 y f1double x2double x double y return a2 x b2 y c2double y2double x double y return d2 x e2 y f2public void paintgraphics g drawfractalgvoid drawfractalgraphics g double x1 300 double y1 300 double x2 0 double y2 0 gfilloval300 int x1 300 int y1 3 3 for int i 0 i 10 i double p mathrandom if p 091675 x2 x1x1 y1 y2 y1x1 y1 gfilloval300 int x2 300 int y2 3 3 x1 x2 y1 y2 else x2 x2x1 y1 y2 y2x1 y1 gfilloval300 int x2 300 int y2 3 3 x1 x2 y1 y2 unfortunately with this code i get a wrong pictureit would be great if someone could point out my mistake,['java'] +395666,explicitly initializing jquery mobile i am using jquery mobile i just wanted to stop jquery mobile to do anything unless i explicitly call triggercreate method is there a way to stop jquery mobile auto initialization for some time,"['javascript', 'jquery']" +395672,how to use python mysqldb to insert many rows at once i have a list of lists eg abcdi have a table called t and two fields f1 f2 the first item in the field list maps to f1 second to f2how can i insert rows for each inner list in a single command or call rather than using a for loop like thisfor i in abcd cexecuteinsert into t f1f2 values s s i0 i1,"['python', 'mysql']" +395676,ios generate image from nonimage data godus like landscape so upon seeing images from godus i was wondering how to generate a simple noninteractive 2d image with different colors for different heights or layers of heights like on the picture belowi was just thinking in terms of generating the basic layers of colors for the topography without the houses trees objects and units i was not thinking in terms of creating a graphics engine that would solve this but a simple way to generate a flat image on the screenthe question is twofold1 what kind of data could be used for this sort of generation i was thinking maybe ascii art which is kind of easy to create and modify to quickly change the topography but would be difficult to provide height information 2 what existing frameworks classes methods or methodologies could be used for solving the generation after having the data readygodusascii art northern europe with for norway for sweden for finland and for russiataken from the mapbox docs data as ascii art,"['objective-c', 'ios']" +395702,smooth removal of items within a custom listview i wish to be able to remove items from a listview in a way that will animate both the removed item and the items beneath it in a similar way shown for the layoutanimations demo in the api demosfor examplehere i wish to remove item 1 the first animation will smoothly move item 1 to the right and upon completion will smoothly animate all of the items below this item including more items if exist to the empty space that item 1 usedthe first animation was quite easyfinal translateanimation animation new translateanimationtranslateanimationrelative to self 00f translateanimationrelative to self 10f translateanimationrelative to self 00f translateanimationrelative to self 00fanimationsetduration500viewstartanimationanimationbut how would i achieve the nice effect of the other items where i actually use a listview which recycles its itemsin the demo i have mentioned they do not even use a listview in my case it is quite problematic since i have a lot of itemsi have also noticed a similar post about this matter but all i found about it is that you need to modify the listview code but no real solutionincidentally the minimal sdk is 9,['android'] +395705,how to pass a 2d array through pointer in c possible duplicatepassing a pointer representing a 2d array to a function in c i am trying to pass my 2dimensional array to a function through pointer and want to modify the valuesinclude stdiohvoid funcint ptrint main int array22 2 5 3 6 funcarray printfd array00 getchvoid funcint ptr int i j for i 0 i 2 i for j 0 j 2 j ptrij 8 but the program crashes with this what did i do wrong,"['c++', 'c']" +395838,how to unban a project on maven i am trying to install a file to my local maven repositor following the steps from although i am always getting the following error message ps candroidandroidsdkextrasgooglegoogle play serviceslibprojectgoogleplayservices lib mvn installinstallfile dgroupidcomgoogleandroidgms dartifactidgoogleplayservicesjar dversion4 dpackagingjar dfilelibsgoogleplayservicesjar info scanning for projects info info info building googleplayservices 4 info info info maveninstallplugin24installfile defaultcli googleplayservices info installing candroidandroidsdkextrasgooglegoogle play serviceslibprojectgoogleplayservices lib to cusersjulianom2repositorycomgoogleplayservicesjar4googleplayservicesjar4jar info info info skipping googleplayservices info this project has been banned from the build due to previous failures info info info build failure info info total time 1534s info finished at mon dec 24 0504 brst 2012 info final memory 6m89m info error failed to execute goal orgapachemavenpluginsmaveninstallplugin24installfile defaultcli on project googleplayservices error installing artifact comgoogleplayservicesjarjar failed to install artifact comgoogleplayservicesjarjar4 candroidandroidsdkextrasgooglegoogle play serviceslibprojectgoogleplayservices lib access is denied help 1 error error to see the full stack trace of the errors rerun maven with the e switch error rerun maven using the x switch to enable full debug logging error error for more information about the errors and possible solutions please read the following articles error help 1 i am not sure if the error is because googleplayservices is being skipped if you think so please help to unban it,['android'] +395876,how to change the return value by spring aop i have a method with a return value in dao layer i want to change the return value by spring aop according different requirements and then send to corresponding method in service layer but i do not know how to do so,['java'] +395894,cakephp cachehelper appcontroller not found error i added cachehelper to my appin my appconfigcorephp i haveconfigurewritecachecheck truein appconfigbootstrapphp i have configurewritethispatcherfilters array assetthispatcher cachethispatcherin my controller i havepublic helpers arraytext cachepublic cacheaction 1 houri do not have any callbacks directly in this controller nor in the appcontrollerthe problem is that each page loads only one time for example a after cache is cleared on second request i am getting backfatal errorerror class appcontroller not found if cache is turned off everything works wellcakephp version is 223debug log 20121224 122100 error fatal error 1 class appcontroller not found in volumesappcontrollernewscontrollerphp line 2 20121224 122100 error fatalerrorexception class appcontroller not found 0 volumeslibcakeerrorerrorhandlerphp161 errorhandlerhandlefatalerror1 class appcontr volumesdatad 2 1 internal function errorhandlerhandleerror1 class appcontr volumesd 2 array 2 volumeslibcakecoreaphp926 call user funcerrorhandlerh 1 class appcontr volumesd 2 array 3 volumeslibcakecoreaphp899 app checkfatalerror 4 internal function appshutdown 5 mainnewscontrollerphpclass newscontroller extends appcontroller public components arraysecurity imagetool uploaderpublic paginate array fields arraynewsid newscreated limit 5 contain array order arraynewsid descpublic helpers arraytext cachepublic cacheaction 1 hour,['php'] +395901,android searchviews suggestion from the network i have a searchview in the actionbar and i want the suggestion to be fetched from a servicei have seen a sample in the android samples searchable dictionary but it is loading the results from a local databasei got that it is necessary to use the content providerbut i am wondering when to fetch the result from the web service i mean when to made a network callplease can anyone help,['android'] +395910,method order in generated class file by javac with jdk7 the reflection api has changed and now the methods returned by getdeclaredmethods are not returned in the order in which they are declared in the source file now my question is does the class file generated by javac contains methods in the same order in which they were defined in the source file or it can write methods in random order too,['java'] +395915,calculate the execution time of a method possible duplicate how do i measure how long a function is runningi have an io timetaking method which copies data from a location to another whats the best and most real way of calculating the execution time thread timer stopwatch any other solution i want the most exact one and briefest as much as possible,"['c#', '.net']" +395926,single event handler for all events javascriptjquery i know i can have one handler handle multiple events using jquery likemyidbindblur mousedown mouseup focus function e also i can register an event from all elements using jquery likedocumentonclick functionevent consolelogclicki have two questionshow do i register a single listener for multiple events in pure javascriptis there any way to have a single handler for all events in a document using js or jquery like a master handler which will delegate the events to my other handlers i am looking at something like thisdocumenton functionevent consolelogi am the master handler call delegates,"['javascript', 'jquery', 'html']" +395937,extracting only date from datetime field mysql and assigning it to php variable i am unable to assign only date to a php variable from datetime field of a mysql table i am using php 4 i know how to do it in php 5can someone help as to what is missing from the below php codedc mysql queryselect from invhdr where invdate between 20110401 and 20120331while dc2 mysql fetch assocdc invno dc2invno here invno is a datetime field type invdat3 dc2invdate date array explode invdat3 invdat sprintf02d02d4d date array2 date array1 date array0,"['php', 'mysql']" +395947,strcpy vs strdup i read that strcpy is for copying a string and strdup returns a pointer to a new string to duplicate the stringcould you please explain what cases do you prefer to use strcpy and what cases do you prefer to use strdup,['c'] +395950,using a gradientdrawable with more than three colors set according to what i have read you can use a gradientdrawable and have three colors set for it for examplegradient startcolor00ff00 centercolorf00 endcolorfbut what if i want more than three colors and not only that i want to be able to set where to put each in weightpercentageis it possible using the api or should i make my own customized drawable if i need to make my own customized drawable how should i do it,['android'] +395958,is using javascript eval safe for simple calculations in inputs i would like to allow user to perform simple calculations in the text inputs so that typing 25 will result in 10 i am replacing everything but digits with an empty string and then make calculation using eval this seems easier and probably faster then parsing it manuallyit is often being said that eval is unsafe so i would like to hear is there any danger or drawback of using it in this situationfunction input value inputvaluereplacedg inputvalueevalvalue,['javascript'] +395986,fragment viewstate restored in onstart when orientation changes fragment viewstate restored only in onstart after onattach oncreateview onviewcreated and onactivitycreated and even after oncreatewhy this is too late i need to populate db query results to listview based on some textview value currently i try to do this in onviewcreated but view state is not restored at this stepcan i force restore earlyor how to overcome this problem any ideas pleaseps i use actionbarsherlock and dependent android supportv4 r7 libraryps2 if i will load data in onstart then it will do additional queries when fragment is resumed after onstop i can solve this by adding some boolean isloaded but this is not best solution,['android'] +396024,can foreign key be null in our database project we have a table sale that has an primary key and two exclusive foreign keys vehicle id and piece id for example if we sell a vehicle we need vehicle id as a foreign key but not piece id can we put null to piece id could a foreign key be null or is there a way to do this jobthanks,['sql'] +396038,nsdate return 1604 for year value i am try to get birth data for contacts but if user does not choose year or the contact come from facebook and the year or the data it self is hidden so it give me the 1604 value for the year you can see what i mean in the image,"['iphone', 'objective-c', 'ios']" +396047,what is the best method in xna to have the player paint smoothly on the screen i am developing a wp7 game where the player draws lines in the program and a ball bounces off of them i am using xna and farseer physics what is the best method for a user to draw a line and then for the program to take it and turn it in to a physics object or at least a list of vector2s i have tried creating a list of touchlocations but it ends up spotty if the user does not draw very slow like the picture i have attached any suggestionsthanksheres some codei am using the gamestatemanagement sample and this is in the handleinput methodforeach touchlocation t in inputtouchstate pathmanagerupdategametime tpositionthe pathmanager class manages a collection of path classes which are drawable physics objects here is pathmanagerupdatepublic void updategametime gametime vector2 touchposition pathsaddnew pathworldtexture new vector255 01f pathspathscount1position touchpositionthis is just what i am doing now and i am willing to throw it out for anything youd think that having a 5x5 rectangle for each touch location would kill the performance but using farseer i did not see any drops even with a mostly full screen however this system does not create a smooth line at all if the line is drawn fasti doubt this helps any but here is the path constructorpublic pathworld world texture2d texture vector2 size float mass thissize size thistexture texture body bodyfactorycreaterectangleworld sizex pixeltounit sizey pixeltounit 1 bodybodytype bodytypestatic bodyrestitution 1f bodyfriction 0 bodyfriction 10,['c#'] +396054,how do i give template arguments to an object created inline with its class i know that in c we can do thisclass a athis makes an object of type a named a it is equivalent toa ai was wondering how i would do this with templates for exampletemplate typename t struct and int nthis does not compile but you get the idea how would i specify the template arguments to an object created inline with its class definition is this even possible,['c++'] +396056,c11 random numbers and stdbind interact in unexpected way i am using gcc 463 and was trying to generate random numbers with the following codeinclude randominclude functionalint main stdmt19937 rng engine printfwith bindn forint i 0 i 5 i stduniform real thistributiondouble thist00 10 auto rng stdbindthist rng engine printfgn rng printfwithout bindn forint i 0 i 5 i stduniform real thistributiondouble thist00 10 printfgn thistrng engine return 0i expected both methods to generate a sequence of 5 random numbers instead this is what i actually getwith bind01354770135477013547701354770135477without bind01354770835009096886802210340308167is this a gcc bug or is it some subtle issue having to do with stdbind if so can you make any sense of the resultthanks,['c++'] +396077,how to open connection with microsoft access database in c i am using microsoft access to create my database heres my codestatic string constr providermicrosoftjetoledb40 data source mydataaccdboledbconnection conn new oledbconnectionconstrdataset dataset1 new datasetstring sqlstr select from tabeloledbdataadapter dataadapter1connopeni am getting this exceptionan unhandled exception of type systemdataoledboledbexception occurred in systemdatadlladditional information unrecognized database format,['c#'] +396102,jit loop optimization using system namespace consoleapplication1 class testmath static void main double res 00 forint i 0i10i res systemmathsqrt20 consolewritelineres consolereadkey by benchmarking this code against the c version i thiscover than performance are 10 times slower than c version i have no problem with that but that lead me to the following question it seems after a few search that jit compiler cannot optimize this code as c compiler can do namely just call sqrt once and apply 10 on itis there a way to force jit to do it,['c#'] +396103,how can i ensure a numeric decimal keyboard in android i have an edittext that requires unsigned decimal inputif i usesetinputtypeinputtypetype class number inputtypetype number flag decimalsetkeylistenernumericdigitskeylistenergetinstancefalse truethen it works fine in the us but my european customers cannot use it because it does not seem to allow a comma as the decimal pointif on the other hand i usesetinputtypeinputtypetype class number inputtypetype number flag decimalsetkeylistenerdigitskeylistenergetinstance01234567890then it works fine in the us and in europe but on some devices like the galaxy s3 the soft keyboard that comes up is strictly numeric no comma or periodhow can i enforce a numeric keyboard with access to a decimal separator that is appropriate for the localethanks,['android'] +396113,how to bind mousedouble click command in mvvm i have listview and i want to have show new window when someone double click in any position but i have mvvm application and i do not want to have any function in code behind of xaml file like this how to bind a command to doubleclick on a row in datagrid and many other samples like this i want to have method in viewmodel file and bind it like this listview mousedoubleclickbinding myfunction thanks,['c#'] +396116,uicollectionviewcell shake i have created a uicollectionview and would like to have all the cells shake like the edit mode of the springboard on the iphone i have created my shake code but do not know how to implement it i have custom cells so i assume it goes in there but do not know how it gets implemented thank youdefine degreestoradiansx m pi x 1800define kanimationrotatedeg 05define kanimationtranslatex 10define kanimationtranslatey 10startjigglingint count 1cgaffinetransform leftwobble cgaffinetransformmakerotationdegreestoradians kanimationrotatedeg count2 1 1 cgaffinetransform rightwobble cgaffinetransformmakerotationdegreestoradians kanimationrotatedeg count2 1 1 cgaffinetransform movetransform cgaffinetransformtranslaterightwobble kanimationtranslatex kanimationtranslateycgaffinetransform concattransform cgaffinetransformconcatrightwobble movetransform selftransform leftwobble starting point uiview animatewithduration01 delaycount 008 optionsuiviewanimationoptionallowuserinteraction uiviewanimationoptionrepeat uiviewanimationoptionautoreverse animations selftransform concattransform completionnil,"['iphone', 'ios']" +396140,what type of html table is this and what type of webscraping techniques can you use i am trying to extract data within in this link lnfnspgrploclnggen with r but it is rather difficulti notice that the url link does not change whenever i click on a page number is this table created with javascript is the table created by some external source and how can i get access to it also is there a technical name for this type of table also for anyone who knows web scraping with r or any other program how would you extract all the data from this table i tried using the following code in r to extract the data but i get null how would you address this issuemps pastespecialtysearchgendersearchsortcurrentpage1 mpsdoc htmlparsempsmpstabs readhtmltablempsdocalso if you can not anwer the second half of my question that is okay i mainly want to know the answer of the first half of my question,"['javascript', 'jquery', 'html']" +396144,how would you go about executing a database query based on the value from a form select element i am using coldfusion as my application server and sql server for the database i have a select form element which lists a number of vehicles volvo s60 bmw m6 vw jettabased on what vehicle the user selects i need my webpage to perform a database query to find out what type of vehicle they selected eg suv coupe convertible depending on what type is returned from the database the database will return a list of options suitable for that vehicle type my database tables can do this based on the vehicle dropdowns value so that is all goodnow then i want to now list the available options for that vehicle type as a group of checkboxes doing this should be a simple case of looping through the database resultset and generating a checkbox for each row i want to do this without refreshing the page how do i dynamically get the value from the dropdown pass this value to the database get the result back and then show the appropriate checkboxes,"['javascript', 'jquery']" +396149,how to implement accessibility in java i am visually impaired and am developing some java guis and i would find it extremely ironic if my guis were not accessible to myself so anyone out there who can help it would be great if someone could give some adviceexamples of how to implement accessibility in javai am looking for how to makecombo boxes accessibletabbedpanesbuttonstables adding descriptionsand anything else you feel is importantalso could someone explain what is the getaccessiblecontext method and how to use itsome of these such as buttons appear to be already quite accessible but my test combo boxes i have made are not interpreted so well with my speech readerany information on any of the above would be greatly appreciatedthank you so muchps using eclipse to right the code if that is useful,['java'] +396151,how to check if empty flash card reader is present in usb slot i use getlogicaldrives to get all drives on my computer but that function shows not only present ready to use volumes but also empty flashreaders with no card in them next the getdrivetype shows code 2 for such volume and that is no matter if the flash card is present or not in the slot some multireaders produce many such nonexisting drives the question is how can i determine the correct status of such volumetrying to call findfirstfile on such nonpresent drive produces visual error even in console app exception processing message c013 parameters 75b3bf7c 4 75b3bf7c 75b3bf7c after such error the code continues to run but this annoying error shows up to the user in a window as the app would made a major crashso one method of dealing with that would be using findfirstfile but i do not know any way to get that error out of the way of the user,['c++'] +396178,differences between output of c compiler and ccli compiler i have a wpf application that does a lot of matching across large datasets and currently it uses c and linq to match pocos and thisplay in a grid as the number of datasets included has increased and the volume of data has increased i have been asked to look at performance issues one of the assumptions that i was testing this evening was whether there is a substantive difference if we were to convert some of the code to c cli to that end i wrote a simple test that creates a list with 50 items and then does some simple matching the basic object structure ispublic class csclasswithprops public csclasswithprops createdate datetimenow public long id get set public string name get set public datetime createdate get set one thing that i noticed was that on average for the simple test of creating the list and then building a sublist of all objects with an even id the ccli code was about 8 slower on my development machine 64bit win8 8gb of ram for example the case of a c object being created and filtered took 7 seconds while the ccli code took 8 seconds on average curious as to why this would be i used ildasm to see what was happening under the covers and was surprised to see that the ccli code has extra steps in the constructor first the test codestatic void createcppobjectwithmembers listcppclasswithmembers results new listcppclasswithmembers stopwatch sw new stopwatch swstart for int i 0 i iterations i resultsaddnew cppclasswithmembers id i name stringformatname 0 i var halfresults resultswherex xid 2 0tolist swstop consolewritelinetook 0 total seconds to execute swelapsedtotalsecondsthe c class is above the c class is defined aspublic ref class cppclasswithmemberspublic long long id systemdatetime createdatetime systemstring name cppclasswithmembers thiscreatedatetime systemdatetimenow when i extract the il for both classes constructors this is what i get first the cmethod public hidebysig specialname rtspecialname instance void ctor cil managed code size 21 0x15 maxstack 8 il 0 ldarg0 il 01 call instance void mscorlibsystemobjectctor il 06 nop il 07 nop il 08 ldarg0 il 09 call valuetype mscorlibsystemdatetime mscorlibsystemdatetimeget now il 0e stfld valuetype mscorlibsystemdatetime cslibwithmemberscsclasswithmemberscreatedate il 0013 nop il 0014 ret end of method csclasswithmembersctorand then the cmethod public hidebysig specialname rtspecialname instance void ctor cil managed code size 25 0x19 maxstack 2 locals 0 valuetype mscorlibsystemdatetime v 0 il 0 ldarg0 il 01 call instance void mscorlibsystemobjectctor il 06 call valuetype mscorlibsystemdatetime mscorlibsystemdatetimeget now il 0b stloc0 il 0c ldarg0 il 0d ldloc0 il 0e box mscorlibsystemdatetime il 0013 stfld class mscorlibsystemvaluetype modoptmscorlibsystemdatetime modoptmscorlibsystemruntimecompilerservicesisboxed cpplibwithmemberscppclasswithmemberscreatedatetime il 0018 ret end of method cppclasswithmembersctormy question is why is the c code using the local to store the value of the call from datetimenow is there a cspecific reason for this to happen or is it just how they chose to implement the compileri know already that there are many other ways to improve performance and i know that i am pretty far down the rabbit hole as it is but i was curious to know if anyone could shed some light on this it is been a long time since i have done c and with the advent of windows 8 and microsofts renewed focus on c i thought it would be good to refresh and that was also part of my motivation for this exercise but the difference between the two compiler outputs caught my eye,['c#'] +396182,bundling module for nodejs aspnet mvc 4 has brought amazing tool for bundling multiple stylesheets or javascripts into one like thisbundlesaddnew stylebundlecontentthemesbasecssinclude contentthemesbasejqueryuicorecss contentthemesbasejqueryuidatepickercss contentthemesbasejqueryuithemecssdoes nodejs have any modules to fulfil the same task to bundle client javascript libraries into one i have seen tools like browserify uglifier etc but these require manual invocation of console commands or may i have missed something meanwhile it would be nice to eliminate that excessive step and have middleware that could be easily integrated into expressjs application for instance,['javascript'] +396198,after publishing my umbraco admin panel did not show in ie9 but it appear in ff and chrome browsers after publishing my umbraco admin panel did not show in ie9 but it appear in ff and chrome browsersnote before publishing website i run it from visual studio 2012 and i observed that everything was okaycan anyone help me,['asp.net'] +396224,how to add option group in html select how can i add option group in html select tagi want to categories my option list with option grouphow can i use ithere is an exampleselect first category option option valuevolvovolvooption option valuesaabsaaboption second catgory option option valuemercedesmercedesoption option valueaudiaudioptionselect,['html'] +396229,how to render django template variable as html what i want is like stack overflow user can html format their text input and the page should be rendered exactly in the same wayi use the wmdjs to store the formatted input consider i have a context variable variable with string value psomethingp when i render the templatevariable outputs psomethingpand variablesafe also output psomethingpit shows the html tag as text in the page how to render the html tag in the variable but not showing them as plain textthe template div idthread answer content for answer in questionanswer setall answeranswerbodysafe endfor divthe view def detailrequestquestion idq get object or 404questionpkquestion idreturn render to responsecodedetailhtmlquestionq context instance requestcontextrequest here is the django admin page of the question am using sqlite3 by the way,['html'] +396248,stdis default constructible error if constructor is private i have following snippetinclude type traitsinclude boosttype traitshppclass c c int main static assertboosthas trivial default constructorcvalue constructible static assertstdis default constructiblecvalue constructibleconditions are not equal but first condition works fine and second construction give error that constructor is private compiler gcc 47 so is this gcc bug or it is defined by standard5ok since this conditions are really unequal we can use something like thisinclude type traitsinclude boosttype traitshppclass c private c noexceptfalse int main static assertboosthas nothrow constructorcvalue constructible static assertstdis nothrow constructiblecvalue constructible24anyway i know that static assert should not fails since types are really not default constructiblenot nothrow constructible question is why there is compilation error not by my static assert,['c++'] +396273,why does this css not work for chrome on android but works everywhere else this really puzzles me i want to have picjpg be static in the background not move when scrolling and that it would not stretchit works on every browser ie chrome safari firefox except chrome on android it even works on android original browserbody backgroundcolor transparent important backgroundimage url asset path picjpg backgroundposition center center backgroundrepeat norepeat backgroundattachment fixed webkitbackgroundsize cover mozbackgroundsize cover obackgroundsize cover backgroundsize cover chrome for android renders it as picjpg being halfway up in the screen not on the entire page and does not stay static on scrolli cannot reproduce it on jsfiddle i also try to debug it with my android phone and nothing seems to helpis not this the way to create the background image,"['android', 'css']" +396280,android instantiationexception with fragment it is public i have a fragment it is not an inner class and it does not have any constructor whatsoeverpublic class preferencelistfragment extends listfragment implements onclicklisteneri am getting this crash report on the android developer consolejavalangruntimeexception unable to start activity componentinfocomredactedredactedcomredactedredactedpreferenceactivity androidsupportv4appfragmentinstantiationexception unable to instantiate fragment comredactedredactedpreferencelistfragment3make sure class name exists is public and has an empty constructor that ispublicat androidappactivitythreadperformlaunchactivityactivitythreadjava1750at androidappactivitythreadhandlelaunchactivityactivitythreadjava1766at androidappactivitythreadhandlerelaunchactivityactivitythreadjava2960at androidappactivitythreadaccess1600activitythreadjava127at androidappactivitythreadhhandlemessageactivitythreadjava945at androidoshandlerthispatchmessagehandlerjava99at androidoslooperlooplooperjava130at androidappactivitythreadmainactivitythreadjava3818at javalangreflectmethodinvokenativenative methodat javalangreflectmethodinvokemethodjava507at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava875at comandroidinternaloszygoteinitmainzygoteinitjava633at dalviksystemnativestartmainnative methodcaused by androidsupportv4appfragmentinstantiationexception unable to instantiate fragment comredactedredactedpreferencelistfragment3 make sure class name exists is public and has an empty constructor thatis publicat androidsupportv4appfragmentinstantiatefragmentjava399at androidsupportv4appfragmentstateinstantiatefragmentjava97at androidsupportv4appfragmentmanagerimplrestoreallstatefragmentmanagerjava1760at androidsupportv4appfragmentactivityoncreatefragmentactivityjava200at comredactedredactedpreferenceactivityoncreatepreferenceactivityjava37at androidappinstrumentationcallactivityoncreateinstrumentationjava1047at androidappactivitythreadperformlaunchactivityactivitythreadjava1710 12 morecaused by javalanginstantiationexception comredactedredactedpreferencelistfragment3at javalangclassnewinstanceimplnative methodat javalangclassnewinstanceclassjava1409at androidsupportv4appfragmentinstantiatefragmentjava388 18 morei am unable to replicate this on any of my test devicesheres the preferenceactivityoncreate where the exception is occurringpublic class preferenceactivity extends fragmentactivity preferencelistfragment frag override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutpreference frag preferencelistfragment getsupportfragmentmanager findfragmentbyidridpreference list frag fragsetstatealarmpreferencestateselected fragsetistwopanefalse and here is rlayoutpreferenceframelayout xmlnsandroid androidlayout widthmatch parent androidlayout heightmatch parent fragment classcomredactedredactedpreferencelistfragment androidididpreference list frag androidlayout widthmatch parent androidlayout heightmatch parentframelayoutanyone know why i might be getting this exception andor how to reproduce it,['android'] +396345,jquery hide text content in a tag not the tag itself i have a slider using this html syntaxdiv idtheatre a clasliderimg href01jpg sometexta a clasliderimg href02jpg anotherdescriptiona a clasliderimg href03jpg whatevera a clasliderimg href04jpg whateveradivwhat i need to do is to hide the text of the a tags not the a tags themselvesi got this but does not workvar imgcaptions theatre asliderimghtmlimgcaptionshidei cannot add a span because i use the content for some ajax the structure has to remainmany thanks for your help merry xmas,"['jquery', 'html']" +396378,why is extending native objects a bad practice every js opinion leader says that extending the native objects is a bad practice but why do we get a perfomance hit do they fear that somebody does it the wrong way and adds enumerable types to object practically destroying all loops on any objecttake tj holowaychuks shouldjs for example he adds a simple getter to object and everything works fine sourceobjectdefinepropertyobjectprototype should set function get function return new assertionobjectthisvalueof configurable truethis really makes sense for instance one could extend arrayarraydefinepropertyarrayprototype remove set function get function return removearrayelementbindthis var arr 0 1 2 3 4aremove3are there any arguments against extending native types,['javascript'] +396399,aspnet how to make linkbutton function as hyperlink how do i use an aspbutton or asplinkbutton as asphyperlinkthe existing hyperlink just goes to another section on the same page navigateurlsection2i want to do this in the aspx file without additional coding thanksthe purpose is to have a button look instead of the underlined text but i do not want to use an image with hyperlink to achieve this purpose,['asp.net'] +396403,how to get existing fragments when using fragmentpageradapter i have problem making my fragments communicating with each other through the activity which is using the fragmentpageradapter as a helper class that implements the management of tabs and all details of connecting a viewpager with associated tabhost i have implemented fragmentpageradapter just as same as it is provided by the android sample project support4demosthe main question is how can i get particular fragment from fragmentmanager when i do not have neither id or tag fragmentpageradapter is creating the fragments and auto generating the id and tags,['android'] +396406,jquery load more data on scroll im just wondering how can i implement more data on scroll only if the divloading is visibleusually we look for page height and scroll height to see if we need to load more data but the following example is little complicated then thatfollowing image is perfect example there are two loading divs on the drop down box when user scroll the content whichever is visible it should start loading more data for itso how can i find out if loading div is visible to user yet or not so i can start loading data for that div only,"['javascript', 'jquery']" +396410,nginx reverse proxying to nodejs with rewrite i have several apps running behind an nginx reverse proxy one of which is a node server with expressjs i am proxying domaincomdemoapath to localhost7003path using this nginx confighttp server listen 80 server name domaincom location demoapp proxy set header host host proxy set header xrealip remote addr proxy set header xforwardedfor proxy add x forwarded for proxy set header xscheme scheme rewrite demoapp 1 break proxy pass httplocalhost7003 this works great and app receives requests as if it was rooted at the problem is app handles its own static files and might make requests for routes such as cssappcss or imagesimagejpg but because of the reverse proxy these actually exist at demoappcssappcss and demoappimagesimagejpg respectivelyi have solved this by getting nginx to pass to node a custom header indicating the root path which the node server prepends to the urls of all subsequent requests but now my code is littered with these root path strings for example part of my backend templateslinkrelstylesheet hrefbasepathcssbasecsslinkrelstylesheet hrefbasepathcskeletoncsslinkrelstylesheet hrefbasepathcsslayoutcsswhats a more elegant way to handle this is not there a way to get nginx to recognize requests coming from an upstream server and automatically forward them to that server,['javascript'] +396413,choose which constructor in c i am practicing c by building my own version of vector named vector i have two constructors among others fill constructor and range constructor their declarations look like followingtemplate typename type class vector public fill constructor vectorsize t num const type cont range constructor templatetypename inputiterator vectorinputiterator first inputiterator last other members the fill constructor fills the container with num of val and the range constructor copies every value in the range first last into the container they are supposed to be the same with the two constructors of the stl vectortheir definitions goes followingfill constructor template typename type vectortypevectorsize t num const type cont content new typenum for int i 0 i num i contenti cont contentsize contentcapacity num range constructortemplate typename type templatetypename inputiteratorvectortypevectorinputiterator first inputiterator last thiscontent new typelast first int i 0 for inputiterator iitr first iitr last iitr i content i iitr thiscontentsize thiscontentcapacity ihowever when i try to use them i have problem thistinguishing themfor examplevectorint v13 5with the this line of code i intended to create a vector that contains three elements each of which is 5 but the compiler goes for the range constructor treating both 3 and 5 as instances of the inputiterator which with no surprises causes error of course if i change the code tovectorint v1size t3 5everything is fine the fill constructor is called but that is obviously not intuitive and user friendly so is there a way that i can use the fill constructor intuitively,['c++'] +396446,scrolling in listview with different cell height i have a listview and its rows have different heights when i scroll up rows appear to move up or down erraticallyi do not find the behavior when i scroll downi suspect its due to the fact listview picks one of used rowsthe row is placed on top of visible rowslistview changes the rows heighthere erratic movementbut it is a guessi tried googling since this should be a common problem but could not find any,['android'] +396453,statuscallback not called after requestnewreadpermissions then requestnewpublishpermissions i am developing an android app that integrates with facebook i would like tolet the user login with facebookget the users email address on facebook could be a proxied email address which is finepost to the users walltimeline on hisher behalftechnically that would be toauthenticate the userrequest the email permissionrequest the publish stream permission1 authenticate the useri called sessionopenactivesession with a sessionstatuscallback i already checked that there is no active opened session beforehandfinal sessionstatuscallback sessionstatuscallback new sessionstatuscallback public void callfinal session session sessionstate state exception exception if there is an exception ifexception null handle fail case here return if session is just opened ifstate sessionstateopened handle success case here return start facebook loginsessionopenactivesessionactivity true sessionstatuscallbackmy callback is called after successful login so far so good2 request the email permissionthis is my status callbacknew sessionstatuscallback public void callfinal session session sessionstate state exception exception if there is an exception ifexception null handle fail case here return if token is just updated ifstate sessionstateopened token updated handle success case here return i request the permission with sessionrequestnewreadpermissionsfinal session session sessiongetactivesessionfinal static string permission array read emailfinal liststring permissionlist arraysaslistpermission array read if all required permissions are availableifsessiongetpermissionscontainsallpermissionlist handle success case here return request permissionssessionrequestnewreadpermissionsnew sessionnewpermissionsrequestactivity permissionlistmy callback is called after permission is granted so far so good3 request the publish stream permissionthis is my status callbacknew sessionstatuscallback public void callfinal session session sessionstate state exception exception if there is an exception ifexception null handle fail case here return if token is just updated ifstate sessionstateopened token updated handle success case here return i request the permission with sessionrequestnewpublishpermissionsfinal session session sessiongetactivesessionfinal static string permission array publish publish streamfinal liststring permissionlist arraysaslistpermission array publish if all required permissions are availableifsessiongetpermissionscontainsallpermissionlist handle success case here return request permissionssessionrequestnewpublishpermissionsnew sessionnewpermissionsrequestactivity permissionlistthis time my callback is not called after permission is grantedinvestigationupon further investigation i found that my callback is triggered by comfacebooksessionpoststatechangesessionstate sessionstate exceptionvoid poststatechangefinal sessionstate oldstate final sessionstate newstate final exception exception if oldstate newstate exception null return since oldstate and newstate are equal both being sessionstateopened token updated my callback is not calledquestionhow can i receive any notification after permission is granted for the 2nd time am i supposed to close the session and reopen it from cacheadditional infomy facebook android sdk 30 is download from here which is stated in facebooks getting started with the facebook sdk for android,['android'] +396461,what does this mean in php or possible duplicatewhere we use object operator aa in phpreference what does this symbol mean in php i see these in php all the time but i do not have a clue as to what they actually mean what does do and what does do and i am not talking about the operators they are something else but nobody seems to know,['php'] +396468,writing a python list of lists to a csv file i have a long list of lists of the following form a 12abc312werew414qew2ie the values in the list are of different types floatint stringshow do i write it into a csv file so that my output csv file looks like12abc312werew414qew2,['python'] +396478,hyperlink to go back to previous page in asp net i have a page in asp net httplocalhosterrorpagenotfoundthere is a link in page on clicking on which has to go back to previous page from where i came froma hrefgo back to previous pagea how can i go back to previous page by taking from history,"['c#', 'asp.net', '.net']" +396498,creating xml node with null value in php i am creating a xml file using phpthe resulting xml isxml data firstnamepeterfirstname insertionvinsertion lastnamejohnlastname gendermalegender dataxmlbut in case where a value is null the resulting xml is look at node insertionxml data firstnamepeterfirstname insertion lastnamejohnlastname gendermalegender dataxmlif a value is null i want the xml to be created such that it results inxml data firstnamepeterfirstname insertioninsertion lastnamejohnlastname gendermalegender dataxmlthis is my code doc new domdocument10 docformatoutput true root doccreateelementdata docappendchildroot data doccreateelementdata fname doccreateelementfirstname fnameappendchild doccreatetextnoderowfirstname dataappendchildfname ins doccreateelementinsertion insappendchild doccreatetextnoderowinsertion dataappendchildins lname doccreateelementlastname lnameappendchild doccreatetextnoderowlastname dataappendchildlname gender doccreateelementgender genderappendchild doccreatetextnoderowgender dataappendchildgender rootappendchilddata docsavepath testxmli am sending this xml as response after creating it so in client side the lastname node is becoming a subnode of insertion when it is insertion,['php'] +396499,how to clear push notification badge count in ios i want to clear the push notification badge count once app is launchedim not clear where to set the below codeplease give brief description about clearing the badge countuiapplication sharedapplicationapplicationiconbadgenumber 0,['ios'] +396514,how can i get context parameter value in jsp contextparam paramnameproductsearchrparamname paramvalue8paramvalue contextparami want to get value of productsearchrpp in productsjsp page,['java'] +396515,java swing minimal or range for font size for other application for swing applications default font settings for components are in current theme and can be retrieved using uimanagerpublic class javatesting public static void mainstring args systemoutprintlnuimanagergetlabelfont this can be adjusted in java homelibswingproperties for range of applications with for exampleswingdefaultlafjavaxswingplafnimbusnimbuslookandfeelor set at command line withjava dswingdefaultlafjavaxswingplafnimbusnimbuslookandfeel myappor the application itself remembers it is look and feel and has this value stored somewhere in configuration file it works because application can set look and feel for itself eguimanagersetlookandfeeljavaxswingplafnimbusnimbuslookandfeel this all looks nice but applications need often smaller fonts eg unimportant status bar message for label or larger fonts label with some heading is there any recommended way for thisas a user of high density monitor i had to thiscard lot of java applications that use code like this source code copied from squirrel sqlfont tmp fontuimanagergetlabelfontif tmp null font font tmpderivefont100f statusbarfontinfo new fontinfofontthis example code makes status bar completely unreadable but most components are adjusted to new bigger fontfor creating my own application i might use some ratio eg 50 to 150 of theme font but hardcoding 050 150 range looks as a bad coding habbit as well and it does not fix problem with applications that i do not have source code for this belongs to the theme lf look feel look and feel examplefontuiresource label font resource fontuiresourcejavaxswinguimanagergetlabelfontfont label font label font resourcefont label font bigger label fontderivefontlabel fontgetsize2d 15fit is worth asking before i try some ugly hacks like custom components replacing swing default ones or graphics2dsetfont adjustments or any other scary stuff edit the only thing that exists is size variant which is supported only by nimbus theme allowed values are mini small regular large examplejcomponent mini new jbuttonminiminiputclientpropertyjcomponentsizevariant minihowever looking into source code for nimbus theme it is not possible to simply adjust these values eg scale to 150 for large it is actually hardcodedpackage javaxswingplafnimbuspublic final class nimbusstyle extends synthstyle public static final string large key large public static final string small key small public static final string mini key mini public static final double large scale 115d public static final double small scale 0857d public static final double mini scale 0714dthis value can be edited only by very advanced user for example edit constant pool in java homelibrtjar with program called rej i tried it and it works but it does not work always because they actually hardcoded the constants at several places is this really best quality standard library for exampleif largeequalsstr thisscrollbarwidth intthisscrollbarwidth 115d thisincrgap intthisincrgap 115d thisdecrgap intthisdecrgap 115dbottom line no java look and feel does not support that for now i suggest using ratios eg 07 13 of default font sizejlabel smalabel new jlabelsome textsmalabelsetfontsmalabelgetfontderivefont08f smalabelgetfontgetsize2d,['java'] +396524,what is the best way for a rails noob to learn rspec i have been reading as many tutorials and watching all kinds of videos on learning rspec i have perused the rails guides on testing and the rspec docs too do not feel like its clicked yet and i am just roaming in the darkdoes anyone have some recommendations for a good overview of rspec and testing rails apps,['ruby-on-rails'] +396556,the proper way to handle up navigation according to guidelines i do totally agree with the navigation belowimagine that the book detail is made in different instances of a bookdetailactivitythe stack before pressing up in book2 detail isbookdetailactivity book 2 you are herebookdetailactivity book 1allbooksactivityif i follow the guidelines i will use intent parentactivityintent new intentthis allbooksactivityclass parentactivityintentaddflags intentflag activity clear top intentflag activity new task startactivityparentactivityintent finishbut the big problem with this code is that bookdetailactivity book 1 is still alivepressing back button after up would bring the detail of book 1how can i kill all the bookdetailactivity that are between the original allbooksactivity and the activity where i pressed up,['android'] +396563,c templates and derived classes i am trying to understand the following code derived is a derived structure from t and what does means and then fallback template class tstruct has flowtraitst true struct fallback bool flow struct derived t fallback what does it means templatetypename c static char fsametypebool fallback cflow1 templatetypename c static char f2public static bool const value sizeoffderived0 2,['c++'] +396569,releasing io resource properly i was wondering that what is the bestappropriate way to release file resourceshandlestraditional codebufferredinputstream stream nulltry stream new bufferredinputstreamnew fileinputstream finally ifstream null streamclose will the file handle be released by closing bufferredinputstreamclose alone or it needs the underlying streamie fileinputstreamclose also to be called explicitlyps javadoc for filteroutputstreamclose method specifies that it will explicitly close the underlying stream too but other streams does not seem to have this in the docfilteroutputstreamclose please advice thanks in advance,['java'] +396580,using cx freeze on flask app i am using flask to develop a python app at the moment i want this app to be run locally it runs locally fine through python but when i use cx freeze to turn it into an exe for windows i can no longer use the flaskrender template method the moment i try to execute a render template i get an http 500 error exactly as if the html template i am trying to render does not existthe main python file is called indexpy at first i tried to run cxfreeze indexpy this did not include the templates directory from the flask project in the cxfreeze thist directory so then i tried using this setuppy script and running python setuppy build this now includes the templates folder and the indexhtml template but i still get the http 500 error when it tries to render the templatefrom cx freeze import setupexecutableincludefiles templatesindexhtmlincludes excludes tkintersetupname indexversion 01description membership appauthor meauthor email options build exe excludesexcludesinclude filesincludefiles executables executableindexpyhere is an example method from the scriptapprouteindex methodsgetdef index print rendering index return render templateindexhtmlif i run indexpy then in the console i get running on rendering index 127001 26dec2012 152641 get http11 200 127001 26dec2012 152642 get faviconico http11 404 and the page is thisplayed correctly in my browser but if i run indexexe i get running on rendering index127001 26dec2012 153057 get http11 500 127001 26dec2012 153057 get faviconico http11 404 and internal server errorthe server encountered an internal error and was unable to complete your request either the server is overloaded or there is an error in the applicationin my browserif i return raw html egapprouteindex methodsgetdef index print rendering index return this worksthen it works fine so a possible work around is to stop using flasks templates and hardcode all the html logic into the main python file this gets very messy though so i would like to avoid it if possiblei am using python 27 32bit cx freeze for python 27 32bit and flask 09thanks for any help and ideas,['python'] +396621,proper way to load assemblies with maf i have a program with a plugin based architecture using the managed addin framework maf i am trying to load my addin assemblies in a way where they run in their own process and i can specify where they should look for other assemblies to load below are two different methods i have tried and why they do not work 100appdomain domain create application domain setup informationappdomainsetup domaininfo new appdomainsetup configuredomaininfoapplicationname pluginnamedomaininfoapplicationbase mypathdomaininfoprivatebinpath mypathdomaininfoloaderoptimization loaderoptimizationmultidomaindomaininfothisallowapplicationbaseprobing falsedomaininfothisallowbindingredirects falsedomaininfothisallowcodedownload falsedomaininfothisallowpublisherpolicy falsesystemsecuritypolicyevidence adevidence appdomaincurrentdomainevidence create the new application domain using setup information domain appdomaincreatedomainpluginname domain adevidence domaininfo addin tokenactivateiopensourceautomationaddinv2 domainthis method allows me to tell each addin to run in a new app domain and i can specify where to look for additional assemblies this is important because each addin is in its own subdirectory and needs to look in the same directory as the host to load other assemblies the problem with this method is if an addin has an unhandled exception it will cause the host to crash since it is running in the same processaddinprocess process process new addinprocessplatformanycpu addin tokenactivateiopensourceautomationaddinv2 processaddinsecuritylevelfulltrustthis method loads each addin into its own process so it an individual addin crashes it does not affect the host the problem with this is i have not been able to figure out if it is possible to tell the addins where to look for additional assemblies they will only look in their directory instead of the hosts directorywhat is the best way to use maf in order to accomplish what i am looking for i need to be able to load my addins is such a way to separate them from the host because i am not writing the addins i do not have control over their code so i need to be sure they would not crash the host i also need to be to able to specify where the addins should load assemblies from since they will be in their own subdirectory and need to load an assembly from the host directory i would also prefer to not use the gac if possible,"['c#', '.net']" +396625,how to extend clang with an additional parser how can i extend clang with an additional parser for files with a special file ending ie can i develop a frontendaction that says hey i will take care of all files with the file ending lorem and return an abstract syntax tree clangastcontext i have read about clangfrontendaction clangparser and clangdriverdriver but i have not been able to figure out where and how i should extend clang to be able to extend the compiler with an additional parser not extending the current parser,['c++'] +396709,regex checking repeat i am trying to check a text line using regex 134581012141914here numbers are delimited with and should be nonnegetive and less than or equals to 20and also any number should not be repeatedhere is my pattern01919109200191910920but it cant check the repeat how can i check it,"['c#', 'java']" +396747,datagridview use datapropertyname to show child element property lets image that i have the following classespublic class master public string mastername something public listdetail details new listdetailpublic class detail public string foo testand then i want to show the collection of details objects in a datagridview using the code belowdatagridviewtextboxcolumn column new datagridviewtextboxcolumncolumndatapropertyname detailsfoocolumnheadertext foo headerdgvcolumnsaddcolumnthe column is shown in the grid but without value,['c#'] +396766,printing an invoice on preformatted paper using css i have an invoice in html that thisplays well on the screen i want to print it to preformatted paper the paper has three sectionsheader fixed height from the top of the pagebody table made up of 1 and rowsfooter fixed height from the bottom of the pagei have tried using css and creating a div using invfooter and csslink relstylesheet hrefprintcss typetextcss mediaprint page size85in 11in margin 2cm invfooter positionabsoluteleft50pxbottom0px i have two problems i cannot figure outhow to anchor the footer to the bottom of the printed pagehow to limit the body to a fixed section of the page and overflow into another page if the table has too many rows,"['html', 'css']" +396836,what are the nuances of scope prototypal prototypical inheritance in angularjs the api reference scope page saysa scope can inherit from a parent scopethe developer guide scope page saysa scope prototypically inherits properties from its parent scopeso does a child scope always prototypically inherit from its parent scope are there exceptions when it does inherit is it always normal javascript prototypal inheritance,['javascript'] +396847,sse uncaught error security err dom exception 18 with a server that provides server sent events sse i am trying to connect browsers with a server that provides server sent events sse this server has a different domain than the original one for example if you call this page will try to connect to an sse channel on trying to do that will prompt the following erroruncaught error security err dom exception 18on the linevar source new eventsourcehow can i fix thatupdate solutions that i have tried out1 corsi tried cors by adding accesscontrolalloworigin to the headers of my web service d2examplecom it did not solve eventsource problem even though get calls from d1examplecom pages are working fine now i thought sse works on normal http requests so why is it not working on chrome2 redirecti am using httpd server so i created a redirect rule in d1examplecom virtual host that passes sse requests to d2examplecom it worked perfectly with firefox chrome on the other hand did not prompt any error and did not connect to the sse server either it looks like it dumped the whole eventsource command it looks like this solution will never work so lets move on3 reverse proxyboth browsers connected on d1examplecomsubscribe which is basically connecting to d2examplecom through reverse proxy but on close event is never caught even if the browser is closed which makes sense since the d2 server is now making the channel with the proxy server how can i forward the on close event from proxy server to d2is there any different ways that could make this work,['javascript'] +396855,issue when calling ffmpegc twice that makes the app crashes i am trying to call ffmpegc to trim a video based on this code videotrimmer so when i try to run the activity that loads and uses the native lib the first time i click trin it works and i could trim the video but when i try to run it again it crashes and it only work with the application restartsso i spend three days looking for a solution for this issue most of the answers says the issue with the static variables in ffmpegc and creating a lib that loads and unload the class fixes the issue answer1 answer2 so i tried to apply the solution that is based on the answers and this github repo on the videotrimmer project but all my attempts failed is there any one knows about a fork of the videotrimmer project that fixes the issue or can anybody provide step by step answer of how to implement the solution in the videotrimmer project because i tried to follow all the solution on the web and apply them in that project but with no luck,"['android', 'c']" +396943,php ignores ssl certificates when connecting to mysql using the code from the php manual found here and herephpmysqli mysqli initif mysqli diemysqli init failedmysqlissl setpathtoclientkeypem pathtoclientcertpem pathtocacertpem nullnull does not matter if the paths are right or wrongif mysqlioptionsmysqli init command set autocommit 0 diesetting mysqli init command failedif mysqlioptionsmysqli opt connect timeout 5 diesetting mysqli opt connect timeout failedif mysqlireal connectx my user my password my db dieconnect error mysqli connect errno mysqli connect errorecho success mysqlihost info nmysqliclosei am unable to connect to mysql it gives the following errormessage sqlstate280 1045 access denied for user my userx using password yes the client ipi have narrowed down the problem to the line mysqlissl setwhen i pass wrong paths to the certificates it should throw a ssl certificate error according to this post where the user suffered from the same problem instead it throws the same previous access denied errori managed to make a connection using navicat to the server with the help of the database admin by configuring the ssl connection as followsnotesmy php version is 5315mysql version used on the remote database server is 551355both navicat and the php code are run from the same pcthe database admin created a ssl user specially for testing this user is denied normal access and must connect using sslno proxies are usedi tried pdo and it suffers from the same problemi tried mysqlconnect but it throws a bad handshake error and according to some comments in the manual it does not workopen ssl is enabled from phpinfoso the question is why php is not complaining about the wrong paths to the certificates it seems php is ignoring the line where i set the certificate pathsupdatei tried changing the line where i make the connection to explicitly set the port and use mysqli client sslmysqlireal connectx my user my password my db3306nullmysqli client sslhowever i got this errorwarning mysqlireal connect 08s011043 bad handshake in update 2this is the result of tcpdumping from the database server0x0040 3142 6164 2068 616e 6473 6861 6b65 1badhandshake131618133282 ip tos 0x8 ttl 64 id 40823 offset 0 flags df proto tcp 6 length 52 x202mysql x13042766 f cksum 0xf15f correct 1121120 ack 79 win 46 nopnoptimestamp 19516376 3465907 0x0 4508 0034 9f77 40 4006 c8a7 c0a8 28ca e4w 0x0010 c0a8 2882 0cea a70e b36c 7e8b 7b4d a169 lmi 0x0020 8011 002e f15f 0 0101 080a 0129 cbd8 0x0030 0034 e2b3 4131618133433 ip tos 0x8 ttl 64 id 17337 offset 0 flags df proto tcp 6 length 52 x13042766 x202mysql f cksum 0xb695 correct 79790 ack 113 win 92 nopnoptimestamp 3480910 19516376 0x0 4508 0034 43b9 40 4006 2466 c0a8 2882 e4cf 0x0010 c0a8 28ca a70e 0cea 7b4d a169 b36c 7e8c mil 0x0020 8011 005c b695 0 0101 080a 0035 1d4e 5n 0x0030 0129 cbd8 131618133452 ip tos 0x8 ttl 64 id 40824 offset 0 flags df proto tcp 6 length 52 x202mysql x13042766 cksum 0xb6c3 correct 1131130 ack 80 win 46 nopnoptimestamp 19516376 3480910 0x0 4508 0034 9f78 40 4006 c8a6 c0a8 28ca e4x 0x0010 c0a8 2882 0cea a70e b36c 7e8c 7b4d a16a lmj 0x0020 8010 002e b6c3 0 0101 080a 0129 cbd8 0x0030 0035 1d4e 5nx202 is the database server ipx130 is my pc ipupdate 3i checked for the password length using the following codemysql select lengthpassword from mysqluser where useryouruserand the password length was 41update 4there might be a hint in the error message returned when i connect using the command line via ssh on the remote server i uploaded the whole project to the remote servermysql u test ssl password sslkeyusrlocalapache2htdocscertsclientkeypem sslcertusrlocalapache2htdocscertswrongcertificatepemi get the following errorssl error unable to get certificate from usrlocalapache2htdocscertswrongcertificatepemerror 2026 hy0 ssl connection error notice the error hereif i do not supply any certificates at all i get the following messagebash32 mysql u test ssl passworderror 1045 280 access denied for user test ssllocalhost using password yeswhich is the same error i get when i connect using php using correct or invalid paths to the certificatesmaybe this means something,"['php', 'mysql']" +396960,how to write an android multipane app with very deep navigation tldrhow should multipane apps with deep navigation similar to the spotify ipad app look and work on android and how to implement thislong versioni am working on an app where the user sees lists of items and can then delve deeper into these items these item detail pages can again open lists of related items that in turn have detail pages and so on as a phone app these would be separate activities that might look and link to each other like thisin the mockups the user sees an initial overview and then selects item 2 from the first list a new activity opens up showing him details for item 2 here he selects to see a list of things relating to item 2 the newly openend activity in the third picture shows this list and clicking on one opens the details for this thing he can navigate as deep into the content as he likesthis works quite well with the usual android activities i am working on bringing the app to tablets and am thinking on how to best implement this the plan is to create a multipane layout with the same concept it is very similar to how the ipad spotify app works it will be interesting to see how they bring this to android once they create tabletspecific layoutsin the tablet layout each click on an item or list name opens the corresponding child item as a new pane that animates in from the right the same workflow as in the example above would look like thisi am unsure how to best implement this navigation pattern multipane apps with a limited navigational depth like gmail can be built with a static viewgroup linearlayout would be ok containing all fragments and going deeper into the navigation replaces the content of the next container to the right and animates to this see commonwares implementation of this on sothis suggests that a custom viewgroup would be the way to go if it has to thisplay a subpage ie list of things then it creates a new child in the viewgroup that is half as wide the screen with the fragment and then scrolls the visible area so that the pane that was just interacted with and the new child are visible to link this correctly to a fragmenttransaction so that the back stack works correctly i would guess it would be something like thisview newpane containeraddchildfragmenttransaction ft getsupportfragmentmanagerbegintransactionftaddnewpane new listofthingsfragment2ftremovepaneonright fragmentonrightftcommitcontaineranimatetorighti do not see a way to do the animation within the fragmenttransactionfeedback welcome my employer is generally favorable with respect to open sourcing frameworks we develop so if this is something that is of broader interest and if i can come up with a reusable solution i would be glad to share it,['android'] +396979,how can i determine the max scroll position in different browsers with different lineheight andor padding is there a way to determine the max scroll position for every browser without actually scrolling to the end and reading this positiontaken a container div with a fixed height and overflow several div elements in the container whose sum of heights is bigger then the height of the containerthere is a max scroll position y which i thought is simply the containerheight minus the total itemsheight this seems to be true until the lineheight of the container is larger then the height of the items if this is the case it seems that every browser determines the max scroll position differentlywith padding it got even worse some browsers add the top padding some browsers add both top and bottom paddingsee this fiddle for example play around with the container lineheight and the divitem height,"['javascript', 'css']" +397007,sql server datatypes nvarchar and varchar are incompatible error i have inherited a c app which i have converted to vb i get one error which as far as i can see has nothing to do with the conversioni have a sql statement which isselect resolverid as ddlvalue resolverteam resolverperson as ddltext from dbotblresolvers order by resolverteam resolverpersonwhen this runs i get the error the data types nvarchar and varchar are incompatible in the boolean and operatorin the table both resolverteam and resolverperson are specified as nvarchar255 nullwhy am i getting this error,['sql'] +397029,how to avoid undefined execution order for the constructors when using stdmake tuple how can i use stdmake tuple if the execution order of the constructors is importantfor example i guess the execution order of the constructor of class a and the constructor of class b is undefined forstdtuplea b tstdmake tupleastdcin bstdcini came to that conclusion after reading a comment to the questiontranslating a stdtuple into a template parameter packthat says that this templatetypename argsstdtupleargs parsestdistream stream return stdmake tupleargsstreamimplementation has an undefined execution order of the constructorsupdate providing some contextto give some more background to what i am trying to do here is a sketchi want to read in some serialized objects from stdin with the help of codesynthesis xsd binary parsingserializing here is an example of how such parsing and serialization is done examplecxxtreebinaryxdrdrivercxml schemaistreamxdr ixdr xdr stdauto ptrcatalog copy new catalog ixdri want to be able to specify a list of the classes that the serialized objects have eg catalog catalog someotherserializableclass for 3 serialized objects and store that information as a typedeftemplate typename argsstruct variadic typedef typedef variadic typedefcatalog catalog someotherserializableclass mytypesas suggested in is it possible to astorea a template parameter pack without expanding itand find a way to get a stdtuple to work with after the parsing has finished a sketchauto serializedobjectsbinaryparsemytypesstdcinwhere serializedobjects would have the type stdtuplecatalog catalog someotherserializableclass,['c++'] +397040,select menu option border none i am trying to change select option border but unable to do that i have tried it many times but not find the proper solution i have attached the screen shot head style select option backgroundtransparent border0 styleheadbody select optionhellooption optionhellooption optionhellooption optionhellooption optionhellooption selectbody,['css'] +397049,weird position taken by a div i have a strange situation where my middle div is slightly downwardheres a screenshothtml div idfooter div classcontent div idinfo1 img srcimgtemppng altabout me h4about meh4 pthis is about me sectionbrand this is the other linebrand this is a third linep div div idinfo2 h4random photosh4 div idrandomphotosdiv div div idinfo3 h3follow meh3 div img srcimgtemppng altfacebook a hreffacebooka div div img srcimgtemppng alttwitter a hreftwittera div div img srcimgtemppng altemail a hrefemaila div div divdivcssinfo1 info2 info3 padding 10px thisplayinlineblockinfo1 width20info1 img marginright3px width20px height20px backgroundimageurlimgglyphiconshalflingspng backgroundrepeatnorepeat backgroundposition162px 1pxinfo1 img info1 h4 thisplayinlineblockinfo2 width55 borderleft1px solid gray borderright 1px solid grayinfo3 width15info3 img width20px height20px marginright5pxinfo3 imgaltfacebook background urlimgresultpng norepeat 0px 30px info3 imgalttwitter background urlimgresultpng norepeat 0px 60pxinfo3 imgaltemail background urlimgresultpng norepeat 0px 0pxinfo2 div padding3pxrandomphotos height 100pxi am really not that good at css so it maybe a small problem i just cannot find it out,['css'] +397080,robust skipping of data in a javaioinputstream and its subtypes i am processing a binary stream and need to skip efficiently past a range of data that i am not interested in to some data that will be processedinputstreamskiplong does not make much in the way of guaranteesskips over and thiscards and bytes of data from this input stream the skip method may for a variety of reasons end up skipping over some smaller number of bytes possibly 0 this may result from any of a number of conditions reaching end of file before and bytes have been skipped is only one possibility the actual number of bytes skipped is returnedi need to know that one of two things has happenedthe stream endedthe bytes were skippedsimple enough however the leniency afforded in this description means that for example bufferedinputstream can just skip a few bytes and return sure it tells me that it is skipped just those few but it is not clear whyso my question is can you make use of inputstreamskiplong in such a way as that you know when either the stream ends or the skip completes successfully,['java'] +397084,prevent an element to rotate itself in a circular css3 animation ok so this is really getting frustrated for me here first of all if my question framing is wrong please do edit itif you think soand ok as my screens will explain you but still i would like that my element should stay in a specific shape and not to rotate along with the animation am missing something really stupid thingwhat i want whats happening jquery solutions are welcomed but i would love css3 solutionsnote do not go on the elements opacity 1 is made using paint and other with photoshop what matters is square should rotate as square shapehtmldivspanspandivcsskeyframes round round from transform rotate0deg to transform rotate360deg div width 50px height 50px animation round round 3s linear infinite margin 50px auto 0 transformorigin 50 150px backgroundcolor 8fc1e0span thisplay inlineblock margin 5px height 5px width 5px background c0demo,"['jquery', 'html']" +397102,is my websockets server origin checking safe i am using i can allow some domains and i have allowed localhost and a domain which points to my local server but i wonder if someone else which has a server on his computer can connect to my websocket through my domain using an script in his localhost serverhere is the relevant code serverserverphpserversetallowedoriginlocalhostserversetallowedoriginmydomaincom serverlibwebsocketconnectionphp check originifthisservergetcheckorigin true origin issetheaderssecwebsocketorigin headerssecwebsocketorigin false origin issetheadersorigin headersorigin origin iforigin false thislogno origin provided thissendhttpresponse401 stream socket shutdownthissocket stream shut rdwr thisserverremoveclientonerrorthis return false ifemptyorigin thislogempty origin provided thissendhttpresponse401 stream socket shutdownthissocket stream shut rdwr thisserverremoveclientonerrorthis return false ifthisservercheckoriginorigin false thisloginvalid origin provided thissendhttpresponse401 stream socket shutdownthissocket stream shut rdwr thisserverremoveclientonerrorthis return false serverlibwebsocketserverphppublic function checkorigindomain domain str replacehttp domain domain str replacehttps domain domain str replacew domain domain str replace domain return issetthis allowedoriginsdomainpublic function setallowedorigindomain domain str replacehttp domain domain str replacew domain domain strposdomain false substrdomain 0 strposdomain domain ifemptydomain return false this allowedoriginsdomain true return trueeditmaybe i was not clear enough i want that everybody can connect to the websocket but only if they are at my domain or my localhost something like same origin policy in ajaxmy worry is that if i allow localhost maybe all other localhost in other computers will be allowed too,['php'] +397103,adding noise to a signal in python i want to add some random noise to some 100 bin signal that i am simulating in python to make it more realisticon a basic level my first thought was to go bin by bin and just generate a random number between a certain range and add or subtract this from the signali was hoping as this is python that there might a more intelligent way to do this via numpy or something i suppose that ideally a number drawn from a gaussian thistribution and added to each bin would be better alsothank you in advance of any repliesi am just at the stage of planning my code so i do not have anything to show i was just thinking that there might be a more sophisticated way of generating the noisein terms out output if i had 10 bins with the following valuesbin 1 1bin 2 4bin 3 9bin 4 16bin 5 25bin 6 25bin 7 16bin 8 9bin 9 4bin 10 1i just wondered if there was a predefined function that could add noise to give me something likebin 1 113bin 2 421bin 3 879bin 4 1608bin 5 2497bin 6 2514bin 7 1622bin 8 890bin 9 402bin 10 091if not i will just go binbybin and add a number selected from a gaussian thistribution to each onethank youit is actually a signal from a radio telescope that i am simulating i want to be able to eventually choose the signal to noise ratio of my simulation,['python'] +397105,qt qrc resource file cannot load icon i have a qt5 desktop project and i added a resourceqrc file with the qt creator editor which created the following line into the projects pro fileresources resourceqrci put a blank prefix and a png file 14x14 and i tried to use it like thisqpixmap pixmap qpixmap my imagepnguicomboboxadditemqiconpixmap itemnamethe problem is the icon would not show upthe following worksqpixmap pixmap1414pixmapfillqcolorreduicomboboxadditemqiconpixmap itemnameso the problem must be in the resource embedding process i noticed that the generated exe has not a resource section inside it i do not have static linked external libraries so i do not think i need the q init resourceresource macro it gives me undefined externalupdatei am posting here my qrc filercc qresource prefix filemy imagepngfile qresourcerccit is pretty simple and i do not understand why at runtime icons are not showing up,['c++'] +397129,onclickreturn confirm working with classclickfunction i have this function that thisables the input after user clicksclickoffclickfunction var btn this settimeoutfunction btnattrthisabled thisabled 1 return trueand i have this input with a javascript confirmationinput typesubmit classclickoff onclickreturn confirmare you sure valuedeleteeven if i click cancel in the confirmation box the clickoffclick event is called and the button becomes thisabledthe clickoffclick is used by a lot of inputs so the confirmation cannot be inside of ithow can i check the confirm return in the clickoffclick event or even prevent the clickoffclick event to be called,['jquery'] +397146,qsort comparison function i am a beginner to c and i am trying to understand the comparison function needed for the qsort functionpart one syntaxa simple suggested use is this i have included some main code to print the results as wellinclude stdiohinclude stdlibhint values 40 10 100 90 20 25 12 13 10 40 int compare const void a const void b const int ia const int a casting pointer types const int ib const int b return ia ib int main int n for n0 n10 n printfd valuesn printfn qsort values 10 sizeofint compare for n0 n10 n printf d valuesn printfn systempause return 0i do not understand why you need all the extra things in the compare function so i simplifed it to thisint compare int a int b return ab this still works and produces the same results can anyone explain to me what i removed and why it still workspart 2 why pointersadditionally do i really need to use pointers why cannot i just compare a and b directly like so this does not workint compare int a int b return ab for some reason with a multidimensional array i was able to get away with not using pointers and for some reason it worked what is going on example code of sorting a multidimensional array by the 2nd item in each sub arrayinclude stdiohinclude stdlibhint values73 4055 1052 1008 9090 2091 2524 int compare int a2 int b2 return a1 b1int main int n for n0 n6 n printf dvaluesn0 printf d valuesn1 printfn qsort values 6 sizeofint3 compare for n0 n6 n printf dvaluesn0 printf d valuesn1 printfn systempause return 0i am really glad the multidimensional array sorting is working as that is my end goal anyway but i have no idea how i managed to get it to work other than dumb luck and chopping up the code so i would really love some explanation as to why some of the examples i provided work and why some do not thank you,['c'] +397218,dynamic thispatch without visitor pattern problemi am working with an already existing library to the source code of which i do not have access this library represents an asti want to copy parts of this ast but rename references to variables in the process since there can be a assigncommandobject which holds an expressionobject i want to be able to copy each object with its own function so i can call them recursively however since i do not have access to the code of the library i cannot add a method such as copyandrenamestring prefixthus my approach was to create a single function rename with several overloads thus i would have a family functions as followspublic static command renamecommand cmd string prefixpublic static assigncommand renameassigncommand cmd string prefixpublic static additionexpressionrenameadditionexpression expr string prefixa function now consists of a listcommand where assigncommand is a subclass of command i assumed that i could just pass a command to the renamefunction and the runtime would find the most specific one however this is not the case and all commands are passed to command renamecommand cmd string prefix why is this the case is there a way to delegate the call to the correct function without using ugly isoperationsminimal examplei have broken this problem down to the following nunittestcodeusing nunitframeworkpublic class topclass public int retvalpublic class subclassa topclass testfixturepublic class throwawaytest private topclass foo topclass x xretval 1 return x private subclassa foo subclassa x xretval 2 return x test public void overloadtest topclass t new topclass topclass t1 new subclassa subclassa s1 new subclassa t foo t t1 foo t1 s1 foo s1 assertareequal1 tretval assertareequal2 s1retval assertareequal2 t1retval so my question boils down to how can the test above be fixed in an elegant polymorphic objectoriented way without resorting to ischecksextension methodsi have also tried using extension methods as follows this did not solve the problem since they are merely syntactical sugar for the approach aboveusing nunitframeworkusing extensionmethodspublic class topclass public int retvalpublic class subclassa topclass testfixturepublic class throwawaytest private topclass foo topclass x xretval 1 return x private subclassa foo subclassa x xretval 2 return x test public void overloadtest topclass t new topclass topclass t1 new subclassa subclassa s1 new subclassa tfoo s1foo t1foo assertareequal1 tretval assertareequal2 s1retval assertareequal2 t1retval namespace extensionmethods public static class extensions public static void foo this topclass x xretval 1 public static void foo this subclassa x xretval 2,['c#'] +397225,get all products in cart instead of most recent i am adapting the modern theme to create a new theme to use i am relatively new to magento but i am finding it to be a great platform for ecommerce here is my problemi need to thisplay all the products in the customers basket i have this code and currently it only thisplays up to three items is there a different command i can use instead of getrecentitems to thisplay all the items in their basket i tried using getallitems but this does not seem to do anything php items thisgetrecentitems php ifcountitems ol idcartheader classminiproductslist php foreachitems as item php echo thisgetitemhtmlitem php endforeach ol php else php echo this there are no items in your shopping basket php endif any ideas,['php'] +397228,google charts how to line break axis label into two rows multiple x axes i have my google line chart which looks something like this10 09 08 07 20121227 1201 20121226 12 20121225 1133and i want it to look like this notice the xaxis label10 09 08 07 20121227 20121226 20121225 1201 12 1133i tried adding br n and r but no lucki looked through the documentation and the closest thing i found was haxismaxtextlines but there is no mintextlines options so i could not figure out how to force it how can i do thisupdateit seems that this is possible when creating charts by linking to google you just have to set the chxt variable with extra x values however many more x axes you need chxtyxx and then for each x axis you set what the labels will be with the chxl variable chxl120121227201212262012122521201121133 for example20121227201212262012122521201121133chxr0710chxtyxxchs360x240chtbvgchco0chdt19107chtlcchds710but the way i am creating my charts is through javascript this waygooglesetonloadcallbackfunction var data new googlevisualizationdatatable dataaddcolumnstring date dataaddcolumnnumber count populate data new googlevisualizationlinechartdocumentgetelementbyidchart drawdata curvetype function chartarea left 70 top 50 width 100 height 85 width 950 height 800 interpolatenulls true pointsize 5 legend position none vaxis title count viewwindow min 7 max 10 haxis title date viewwindow min 0 max 3 so i need to figure out a way how to do this using this formatapi how can i do it this way,['javascript'] +397240,clearest way to read and print txt file lines in c there are a bunch of ways describing how to use various methods to print out lines of a text file on this siteposixstylereading ip addressesfixed line lengththey all seem to be tailored to a specific exampleit would be great to have the clearest and most concise and easiest way to simply print each line of any text file to the screen preferably with detailed explanations of what each line does points for brevity and clarity,['c'] +397243,overlay a smaller image on a larger image python opencv hi i am creating a program that replaces a face in a image with someone elses face however i am stuck on trying to insert the new face into the original larger image i have researched roi and addweightneeds the images to be the same size but i have not found a way to do this in python any advise is great i am new to opencvi am using the following test images smaller imagelarger imagehere is my code so far a mixer of other samplesimport cv2import cv2cv as cvimport sysimport numpydef detectimg cascade rects cascadedetectmultiscaleimg scalefactor11 minneighbors3 minsize10 10 flags cvcv haar scale image if lenrects 0 return rects2 rects2 return rectsdef draw rectsimg rects color for x1 y1 x2 y2 in rects cv2rectangleimg x1 y1 x2 y2 color 2if name main if lensysargv 2 check for error in usage syntax print usage python facespy image fileelse img cv2imreadsysargv1cv2cv load image color read image file if img none print could not open or find the image else cascade cv2cascadeclassifierhaarcascade frontalface altxml gray cv2cvtcolorimg cvcv bgr2gray gray cv2equalizehistgray rects detectgray cascade extract face coordinates x1 rects03 y1 rects00 x2 rects04 y2 rects05 yy2y1 xx2x1 extract face roi faceroi grayx1x2 y1y2 show face roi cv2imshowthisplay face roi faceroi small cv2imreadaverage facepngcv2cv load image color print here smallcv2resizesmall x y cv2namedwindowthisplay image create window for thisplay cv2imshowthisplay image small show image in the window print size of image imgshape print size of image cv2waitkey10,['python'] +397283,jsp ajax call using jquery i have this code snippet where i am passing data to another jsp filejavascriptdocumentreadyfunction clickclickfunction name nameval age ageval ajax type post url pagetwojsp data name name age age success functiondata responsehtmldata htmlbody nameinput typetext idname namename br br age input typetext idage nameage br br button idclickclick mebutton div idresponsedivbodyand in pagetwojsp my code is string name requestgetparametername string age requestgetparameterage outprintlnname age but this is not workingis any mistake in my jquery can any one please help me,['jquery'] +397289,php unset local reference affecting global scope i have come across some very strange php behaviour 532 on ubuntu 1004 an unset which should occur within local scope is affecting the scope of the caller function the following snippet is a simplification of my code which thisplays what i can only assume is a bugphpfunction should not alterin in ref inlevel1 should only unset locallyin return infunction should only unset locallyin unsetinlevel1level2 0data arraylevel1 arraylevel2 0 first value level2 1 second valuedata should not alterdata test 1should only unset locallydata test 2print rdataif you run the above you will see that the value first value has been unset from the data array in the global scope however if you comment out test 1 and run test 2 this does not happeni can only assume that php does not like referencing an element of an array in my code i need to alter in ref hence the reason for the in ref inlevel1 line in the above code i realize that removing this line would fix the problem of first value being unset in the global scope but this is not an optioncan anyone confirm if this is intended behaviour of phpi suspect it is a bug rather than a feature because this behaviour is inconsistent with the way that php handles scopes and references with normal nonarray variables for example using a string rather than an array function should only unset locally has no effect on the global scopephpfunction should not alterin in ref in should only unset locallyin return infunction should only unset locallyin unsetindata originaldata should not alterdata test 1should only unset locallydata test 2print rdataboth test1 or test2 output original as expected actually even if data is an array but in ref is referenced to the entire array ie in ref in then the buggy behaviour goes awayupdatei have submitted a bug report,['php'] +397303,the awaitable and awaiter in c 50 asynchronous task or tasktresult object is awaitable so we can use await key on those whose return value is task or tasktresulttask or tasktresult are the most frequentlyused awaitable objectwe also can define our own awaitable objectthe object should has below qualificationit has a getawaiter method instance method or extension methodits getawaiter method returns an awaiter an object is an awaiterifit implements inotifycompletion or icriticalnotifycompletion interfaceit has an iscompleted which has a getter and returns a booleanit has a getresult method which returns void or a resultmy question is that why microsoft did not provide a interface to constrain these awaitable object the current method to implement awaitable object is a little complicated,['c#'] +397307,android toggle text color of togglebutton to create a custom togglebutton i have defined a new style in resvaluesstylesxmlstyle namemytogglebutton item nameandroidlayout widthwrap contentitem item nameandroidlayout heightwrap contentitem item nameandroidtextcolor0item item nameandroidbackgrounddrawablemy toggle buttonitemstyleand i then use a selector to specify how the buttons states look in resdrawablemy toggle buttonxmlxml version10 encodingutf8selector xmlnsandroid item androidstate checkedtrue shape shape item item androidstate checkedfalse shape shape itemselectorhow can i modify this setup to toggle the text color of the button when the state changes,['android'] +397308,how to get the exact text from edit text and set into text view in android my problem is this i want to get exact text from edit text with font that set in edit text as well as text sizetext color and text style like bold italic and underlinetill now i used spannable like this spannable messagetext and get the text from edittext like this messagetext edittextgettextand set into textview textviewsettextmessagetextbut in this case it return only the simple string not colorfontsize and styleedittext edittext androidididmessage androidlayout widthfill parent androidlayout height180dp androidinputtypetextmultiline androidsinglelinefalse androidtagno androidtextcolor0 androidtextsize15sp androidtextstylenormal androidtypefacenormal textviewtextview androidididpreview androidlayout widthwrap content androidlayout heightwrap content androidlayout weight1 androidtext androidtextcolor0 androidtextsize15sp androidtextstylenormal androidtypefacenormal help me thanks,['android'] +397313,how to detect css inheritance source so far i can only tell if a property is inherited or not but i need to know the source of inheritance for ex which css file caused the final value is this possible is there a handy tool for this edithere is what i get in chrome computed style show inheritancesee the direction property there is no info about its inheritance source,['css'] +397321,copy tables with data to another database in sql server 2008 i have to copy the tables with data from one database to another using query i know how to copy tables with data within a database but i was not sure about how to do the same for copying between two databasesi have to copy huge number of tables so i need any fast method using queryanybody please help outthanks in advance,['sql'] +397324,struggling between native and phonegap simple app requirements i am going to make a native meaning not in the browser mobile app since i am a webdeveloper i am struggling to decide whether or not i should try phonegap or just build an native app in java or objectivecthe app requirements are simple gpswifi location facebook integration and i guess i will need a database to handle some of the application specific facebookfriend relations like the highscores in a game for example stuff like thati am a webdeveloper and do not know neither java or objectivec yet i have never used phonegap before so i do not know if it is capable of fulfilling my requirementsso my question is as followscan i use phonegap for my app or do i need to dive into a new language,"['android', 'jquery', 'ios']" +397359,body not rotating to face downward with gravity i have a rectangle body that is being fired from a canon at a 45degree angle the body is also rotated up at a 45 degree angle and i have set the mass to be at the front of the body the body goes up in the air fine however as the body comes back down to earth it does not rotate is there a way so that the mass side comes down firstmy real world example is throwing a tennis ball with a string attached into the air currently the string does not fall behind the ball when gravity comes into affecthere is my ballbody bodyfactorycreaterectangleworld convertunitstosimunitstexturewidth convertunitstosimunitstextureheight100f postition thisbodymass 1bodylocalcenter new vector2convertunitstosimunitstexturewidth convertunitstosimunitstextureheight 2bodyuserdata thisbodybodytype bodytypedynamicbodycollisioncategories categoryallbodycollideswith categoryallbodyignoregravity falsefloat ang barreljointjointanglebodyrotation angthen i do this to fire itbodyapplylinearimpulsenew vector2floatmathcosang 100 floatmathsinang 100i am guessing there is some setting or calculation i am forgetting,['c#'] +397416,multiple should statements in one rspec it clause bad idea heres my rspec testit can release an idea do jamesclaimsi title jamesreleasesi title jamesideassizeshould eq 0 si titlestatusshould eq availableendare the two should lines at the end a really bad idea i read somewhere that you should only test for one thing per it block but it seems silly to make a whole test just to make sure that the title status changes the same function does both things in my code,['ruby-on-rails'] +397436,creating a list containing a single string and times is there any way to construct a list of type liststring which contains a single string n times without using a loop something similar to stringchar c int count but instead for list of stringsliststring list new liststring str str str and times,"['c#', '.net']" +397455,evaluating mongodblike json queries in php consider the following rather complicated query expressed in this json object name kindle fire sale true price gt 199 lt 264 pricevat bogus just to show apricevat apricevat lte 12 or qty gt 30 eta or lt 3 gt 30 countriesavailable in us ca objectivei want to parse that json so that it evaluates to the php equivalent of where a is my target dataaname kindle fire asale true aprice 199 aprice 264 apricevat 12 aqty 30 aeta 3 aeta 30 in arrayacountriesavailable arrayus cai have little experience building expression evaluators my idea is to traverse the query from the innermost level to the outermost level calling the corresponding mongodb operator methods as neededassuming a matches the query this would be the evaluation planquery arrayqueryname truequerysale truequeryprice arrayquerypricegt truequerypricelt truequerypricevat arrayquerypricevatlte truequeryor arrayqueryorqty arrayqueryorqtygt falsequeryoreta arrayqueryoretaor arrayqueryoretaorlt truequeryoretaorgt falsequerycountriesavailable arrayquerycountriesavailablein truethe second stepquery arrayqueryname truequerysale truequeryprice arrayquerypricegt truequerypricelt truequerypricevat truequeryor arrayqueryorqty falsequeryoreta arrayqueryoretaor truequerycountriesavailable truethe third stepquery arrayqueryname truequerysale truequeryprice truequeryor arrayqueryorqty falsequeryoreta truequerycountriesavailable truethe fourth stepquery arrayqueryname truequerysale truequeryprice truequeryor truequerycountriesavailable truesince all the values are booleans the evaluation ends returning in arrayfalse query trueif a better approach exists let me knowproblem accessing parent array keysi am stuck trying to get the innermost the elements and the relevant ignoring operators array index path for instance if i use a recursiveiteratoriterator i get the correct values for the first iterationnodes new arrayiteratorqueryiterator new recursivearrayiteratornodesiteratoriterator new recursiveiteratoriteratoriterator recursiveiteratoriteratorleaves onlyprint riterator to arrayiteratoriteratorarray name kindle fire hd sale 1 gt 30 lt 3 lte 12 0 us 1 cahowever it is of little use since i cannot be sure what a index the keys are referring to not to mention that the key values are being overwritten by latter entries and the fact that i cannot change their valuesi have also tried playing with recursivearrayiterator but without the hasparent getparent methods it does not seem to give me much advantage over simply foreaching the arrayany suggestions,['php'] +397462,is stdvectordata preserved by moving possible duplicatedoes moving a vector invalidate iterators consider the following codesstdvectort preparet data stdvectort buffer fill in buffer data bufferdata return buffert dataauto vec preparedata line 12is it possible that vecdata data in line 12 similarlystdvectort buffer fill in buffer t data bufferdataauto vec stdmovebuffer line 5is it possible that vecdata data in line 5practically both are not possible in the implementation of libstdc and libc because the move constructors are implemented as simple pointer assignments but it seems the standard does not specify anything on it similar to is the capacity required to be preserved when moving a stdvector can the constant complexity guarantee that vecdata data,['c++'] +397465,c printing out map values so i have a map like thismapstring pairstringstring mymapand i have inserted some data in my map usingmymapinsertmake pairfirst name make pairmiddle name last namemy question is how do i print out all the data in my mapplease provide an example for my reference,['c++'] +397475,initializing page loading browser indicatoranimated icon with javascript is there an easy way to start and stop the browser throbber page loading indicator without changing the page you are on preferably with no external libraries or ajax calls,['javascript'] +397477,android maps library v2 zoom controls custom position how can i customize the position of the builtin zoom controls in a googlemap v2 there are a lot of questions related to this topic for the version 1 of google maps libraryplacing zoom controls in a mapviewhow to reposition builtin zoom controls in mapviewhow to layout zoom control with setbuiltinzoomcontrolstruehowever i was not able to find any questions in relation to the v2 of the libraryin the v2 there is no methodlinearlayout mapviewgetzoomcontrolsall the previously mentioned questions becomes obsoletethanks in advance,['android'] +397491,postgresql date difference i have a postgresql function which calculates date differencecreate or replace function testdatediff returns int as bodydeclare startdate timestampdeclare enddate timestampdeclare diffdatepart int beginselect evt start date from events where evt id 5 into startdate select evt start date from events where evt id 6 into enddate select extractday from timestamp startdate enddate into diffdatepartreturn diffdatepartendbodylanguage plpgsql cost 100if dates are subtracted directly then difference is calculated but in my case dates are present in variables as startdate and enddate which causes the problemhow can i subtract dates contained in variables,['sql'] +397509,using if else statement based on count to execute different insert statements while i am searching through my database i run an insert statement if i find that a particular item does not exist and i run a different insert statement if i find one or more of this itemi am not entirely sure how to use the if else expressionswhat i have so far is a statement that will count the number of times the target data appears it will print true if it is greater than 0 if not it will print false i cannot find any examples to help me understand how i can use this to run two different insert statementshere is what i have so farselect case when count0 then true else false end select some column count totalcount from incidents where some column target data group by some column,['sql'] +397514,cacheable key on multiple method arguments from the spring documentation cacheablevaluebookcache keyisbnpublic book findbookisbn isbn boolean checkwarehouse boolean includeusedhow can i specify cachable to use isbn and checkwarehouse as key,['java'] +397525,slicing strings in strformat i want to achieve the following with strformatxy 12345678print strx2 stry2the only way i was able to do it wasprint 01formatstrx2stry2now this an example and what i really have is a long and messy string and so i want to put slicing inside the i have studied the docs but i cannot figure out the correct syntax my question is is it possible to slice strings inside a replacement field,['python'] +397527,whats the use of gemfile in rails my question may seem a bit complicated but let me clarify use of gemfile in rails i am new to rails its getting difficult for me to do the same if anyone can provide me a link for its demo or can explain me how to use gemfile then it would be of great help to me thanks in advance,['ruby-on-rails'] +397556,warning passing argument afrom incompatible pointer type enabled by default i have been looking around on the other threads somehow related to this but somehow i just do not get iti want to do some fft on a set of values i have evaluated and wrote this program to first read the values and save them to an array of size nint main some variables and also a bit of code to read the messwertetxtprintfgeben sie an wieviele messwerte ausgelesen werden sollen scanfd ndouble werten array der fertigen messwertein fopen messwertetxtrdouble nuln array von nullenint logn 14lfftlognwertenulin the same file i also do the fft with the help of this programdouble fft int logn double real double im logn is base 2 logn blabla fft calculationhowever when i compile i always get this errorgcc fftc lmfftc in function amainafftc942 warning passing argument 2 of affta from incompatible pointer type enabled by defaultfftc48 note expected adouble a but argument is of type adouble unsigned intnafftc942 warning passing argument 3 of affta from incompatible pointer type enabled by defaultfftc48 note expected adouble a but argument is of type adouble unsigned intnasince this is my first time programming i really do not know what is wrong with my code will i have to set more flags for the compiler or stuff like that because i had to do this lm stuff or it wouldnt compile and said something like pow not found or soalso i was made aware that there might be a difference when writing on a windows or a linux machine and i am using linux lubuntu 1210 32bit if it is a problem of the os,['c'] +397577,how do i allow multiline content in a rails text area field how would i go about allowing users to input multiline text in a text area form fieldcurrently anytime content is entered in the text areathe line breaks are removed they are retained when i edit the content so maybe it is in the show view that the breaks are being removedi have found a few things that indicate that i would need to implement a wysiwyg editor but i would prefer to avoid that if possibleany suggestionsupdate so it looks like rails saves the content with line breaks and i can add html safe to the field in the show view ie postposthtml safe now it will present content with basic html eg br b etc but still does not present the line breaks in the content ie when i press enter for a new line that are saved by rails and i can view when i am editing the content,['ruby-on-rails'] +397642,java initializing superclass variables in subclasses okay so for example let us say i have an abstract class called vehicle the vehicle class has among other things a static variable called wheels which is not initialized what i want to do is have other subclasses extending from the vehicle class like motorcycle and truck and in these subclasses have the wheels initialized code public abstract class vehicle static int wheels number of wheels on the vehiclebut the below does not work public class motorcycle extends vehicle wheels 2is there a way to do this effectivelyedit thank you to all the people who replied so far i get that making instances is probably a better way to go than to put them all in separate classes but i do not get the static part of java perfectly so i need a little help here what i am trying to do for my program is have separate sprites for the motorcycle and truck classes and i want them to be static so that i would not have to reload the image every time i create an instance of a motorcycle or truck other than that though they will have almost identical properties to each other which is why they will both be extending from the vehicle superclass the only other way i can see this being done is by just not declaring the sprite variable at the vehicle class but at the motorcycletruck class like below public abstract class vehicle other codingpublic class motorcycle extends vehicle static bufferedimage sprite initialize imageother codingpublic class truck extends vehicle static bufferedimage sprite initialize imageother coding,['java'] +397655,ruby how to add zeros to front of a number string using sprintf i want to normalize zipcodes to be 5 digits long with zeros replacing any missing characters like so95616 95616854 00854062 0620016 016i have tried using sprintf like so sprintf05s zipcode and like so sprintf05d zipcode both give incorrect answers using the s95616 95616854 854062 0620016 0016this is the correct number of characters but using spaces not zeros using the d95616 95616854 00854062 05016 014what is the proper use of sprintf in this case,['ruby'] +397735,why doesnat stopping an application in ios simulator trigger applicationwillterminate i have some code in my appdelegateas applicationwillterminate method but i donat know how to test if it works using xcode to stop the simulator does not trigger ithow do i test the code in applicationwillterminateplease note that this is specific to the simulator and not the device,['objective-c'] +397763,objectivec enumeration ns enum ns options whats the correct way to create an enumeration with a specific type in objectivec how does ns enum and ns options work ns options are used for masks like nsautoresizing thankscode from nsobjcruntimeh define ns enum type name enum name type name enum name type define ns options type name type name enum type,['objective-c'] +397783,extended uibutton border is not initially drawn i am trying to create a custom uibutton which extends from uibuttontyperoundedrectmy added functionality is working but there is an issue with the initial rounded border state of my button the border of my extended button is not drawn until after it has been tappedupdate january 24th 2013 added the result of red background test as requested by richard marskell which concludes only the label of the button is drawn backgroundcolor uicolorredbelow is my source code for creating my custom buttonpublic class testview uiview public testviewintptr p basep public testviewrectanglef bounds frame bounds backgroundcolor uicolorwhite uibutton button1 new uibuttonuibuttontyperoundedrect button1frame new rectanglef202010050 button1settitlebutton 1 uicontrolstatenormal addsubviewbutton1 drawn correctly mybutton button2 new mybutton button2frame new rectanglef209010050 button2settitlebutton 2 uicontrolstatenormal addsubviewbutton2 only drawn correctly after tap edit added to test miguels theory uibutton button3 uibuttonfromtypeuibuttontyperoundedrect button3frame new rectanglef2016010050 button3settitlebutton 3 uicontrolstatenormal addsubviewbutton3 drawn correctly public class mybutton uibutton public mybutton baseuibuttontyperoundedrect i am just not sure how to force the border to be drawn correctly on loading of the viewi do not need a button of type uibuttontypecustom as i do not want to style the button myselfwhen i debug i the type of mybutton is correctly set to uibuttontyperoundedrectthe uibutton base properties of mybutton button2 match the properties of the uibutton instance button1 how can i resolve this issueupdate january 31st 2013 herman schoenfeld provided a suitable solution for this bug,['c#'] +397811,pthread vs intel tbb and their relation to openmp for multithread programming with the considerations of combinations with hpc application mpi which one is better can we say in terms of functionality intel tbb thread building block is comparable to pthread or not i only get experience in open mp but i heard both tbb and pthread offers finer thread control comparing to open mp but can tbb or tbbopenmp offer similiar functionality compared to pthread,['c++'] +397840,why bother using apache or nginx etc i have been assigned a project which requires me to add some html page serving this embedded system running linux centos 63 has some extra juice available but also already has numerous responsibilitiesi considered apache but tossed it due to bloat i looked into nginx but am now shying from that too it just seems that i am getting way more functionality and as a result more cpu usage than i needcan someone enlighten me as to why i wouldnt just implement the http protocol myself using async socketsmy specific needs are receive and decode gets and posts send css js and jpg files as requested output header cookie head and body data based upon the decode of the getspostsgiven that i do not need the myriad things these webservers offer am i being naive in assuming this course of doing it myself what would you suggest or warn against,"['c++', 'c']" +397863,duplicate id tag null or parent id with another fragment for comgoogleandroidgmsmapsmapfragment i have an application with three tabseach tab has its own layout xml file the mainxml has its own map fragment it is the one that shows up when the application first launcheseverything works fine except for when i change between tabs if i try to switch back to the map fragment tab i get this error switching to and between other tabs works just finewhat could be wrong herethis is my main class and my mainxml as well as a relevant class that i use you will also find the error log at the bottom main classpackage comnfcdemoimport androidappactionbarimport androidappactionbartabimport androidappactivityimport androidappfragmentimport androidappfragmenttransactionimport androidosbundleimport androidwidgettoastpublic class nfcdemoactivity extends activity public void oncreatebundle savedinstancestate superoncreatesavedinstancestate actionbar bar getactionbar barsetnavigationmodeactionbarnavigation mode tabs barsetthisplayoptions0 actionbarthisplay show title baraddtabbar newtab settextmap settablistener new tablistenermapfragmentthis map mapfragmentclass baraddtabbar newtab settextsettings settablistener new tablistenersettingsfragmentthis settings settingsfragmentclass baraddtabbar newtab settextabout settablistener new tablisteneraboutfragmentthis about aboutfragmentclass if savedinstancestate null barsetselectednavigationitemsavedinstancestategetinttab 0 setcontentviewrlayoutmain override protected void onsaveinstancestatebundle outstate superonsaveinstancestateoutstate outstateputinttab getactionbargetselectednavigationindex public static class tablistenert extends fragment implements actionbartablistener private final activity mactivity private final string mtag private final classt mclass private final bundle margs private fragment mfragment public tablisteneractivity activity string tag classt clz thisactivity tag clz null public tablisteneractivity activity string tag classt clz bundle args mactivity activity mtag tag mclass clz margs args check to see if we already have a fragment for this tab probably from a previously saved state if so deactivate it because our initial state is that a tab is not shown mfragment mactivitygetfragmentmanagerfindfragmentbytagmtag if mfragment null mfragmentisdetached fragmenttransaction ft mactivitygetfragmentmanager begintransaction ftdetachmfragment ftcommit public void ontabselectedtab tab fragmenttransaction ft if mfragment null mfragment fragmentinstantiatemactivity mclassgetname margs ftaddandroidridcontent mfragment mtag else ftattachmfragment public void ontabunselectedtab tab fragmenttransaction ft if mfragment null ftdetachmfragment public void ontabreselectedtab tab fragmenttransaction ft toastmaketextmactivity reselected toastlength short show mainxmlxml version10 encodingutf8linearlayout xmlnsandroid androidlayout widthmatch parent androidlayout heightmatch parent androidorientationvertical fragment xmlnsandroid androidididmapfragment androidnamecomgoogleandroidgmsmapsmapfragment androidlayout widthmatch parent androidlayout heightmatch parent linearlayoutrelevant class mapfragmentjava package comnfcdemoimport androidappfragmentimport androidosbundleimport androidviewlayoutinflaterimport androidviewviewimport androidviewviewgrouppublic class mapfragment extends fragment override public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate superoncreateviewinflater container savedinstancestate return inflaterinflaterlayoutmain container false public void ondestroy superondestroy error androidviewinflateexception binary xml file line 7 error inflating class fragment at androidviewlayoutinflatercreateviewfromtaglayoutinflaterjava704 at androidviewlayoutinflaterrinflatelayoutinflaterjava746 at androidviewlayoutinflaterinflatelayoutinflaterjava489 at androidviewlayoutinflaterinflatelayoutinflaterjava396 at comnfcdemomapfragmentoncreateviewmapfragmentjava15 at androidappfragmentperformcreateviewfragmentjava1695 at androidappfragmentmanagerimplmovetostatefragmentmanagerjava885 at androidappfragmentmanagerimplattachfragmentfragmentmanagerjava1255 at androidappbackstackrecordrunbackstackrecordjava672 at androidappfragmentmanagerimplexecpendingactionsfragmentmanagerjava1435 at androidappfragmentmanagerimpl1runfragmentmanagerjava441 at androidoshandlerhandlecallbackhandlerjava725 at androidoshandlerthispatchmessagehandlerjava92 at androidoslooperlooplooperjava137 at androidappactivitythreadmainactivitythreadjava5039 at javalangreflectmethodinvokenativenative method at javalangreflectmethodinvokemethodjava511 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava793 at comandroidinternaloszygoteinitmainzygoteinitjava560 at dalviksystemnativestartmainnative methodcaused by javalangillegalargumentexception binary xml file line 7 duplicate id 0x7f0405 tag null or parent id 0xf with another fragment for comgoogleandroidgmsmapsmapfragment at androidappactivityoncreateviewactivityjava4722 at androidviewlayoutinflatercreateviewfromtaglayoutinflaterjava680 19 more,['android'] +397881,parallelforeach misbehaviour possible duplicatec value storage during parallel processing i was running some performance tests in my console application today and i stumbled across something really unexpected my codeint iterations 10var mainlist new liststringfor int i 0 i iterations i mainlistadditostringvar lista new liststringparallelforeachmainlist listitem if int32parselistitem2 0 listaaddlistitem consolewritelineparallel count 0 listacountvar listb new liststringforeach var listitem in mainlist if int32parselistitem 2 0 listbaddlistitem consolewritelinesequential count 0 listbcountwhich resulted in an outputparallel count 495939sequential count 50i ran it several times and the parallel loop never seems to get executed at a proper amount of times can anyone explain this misbehaviour are the parallel loops trustworthyps i know there is a lot of nonsense going on in the provided example of code like tostring calls on an integer and than parsing them back but that was just a random code i came up with while testing thanks in advance,['c#'] +397899,configuring logback in eclipse i am in the process of switching from log4j to logback but i am not having success at making logback work yet i have placed logbackxml in the root directory of my eclipse java project and below is its contentconfiguration appender namefile classchqoslogbackcorefileappender filemyapplogfile encoder patterndate level thread logger10 fileline msgnpattern encoder appender appender namestdout classchqoslogbackcoreconsoleappender encoder patternmsgnpattern encoder appender root leveldebug appenderref reffile appenderref refstdout rootconfigurationand below is the relevant content of my mainjavaimport orgslf4jloggerimport orgslf4jloggerfactorypublic class main static final logger logger loggerfactorygetloggermainclass public static void mainstring args loggerinfomain started this does not seem to be working as no file named myapplog is created in the root of my eclipse java application any idea what i am doing wrong,['java'] +397909,why do c11deleted functions participate in overload resolution why does c11 make deleted functions participate in overload resolutionwhy is this useful or in other words why are they hidden instead of being deleted entirely,['c++'] +397939,why does f inline cause 11x performance improvement i am working on some heavy cpu bound problem i see a big performance improvement when i use the inline keywordi create a dictionary from the standard net library passing in a custom key comparer see code and timing results belowwithout inline keyword on eq cmp perf run 10 real 011039 cpu 011029 gc gen0 771 gen1 3 gen2 1val it unit using inline keyword on eq cmpperf run 10 real 01319 cpu 01388 gc gen0 1 gen1 1 gen2 1val it unit i also noticed the huge difference in the amount of gen 0 gc with the inlined code and non inlined codecould someone explain why there is such a huge difference,['.net'] +397956,count logical lines of code in ubuntu i am working on a web application and i need to be able to keep track of php css html and javascript lines of code within the varw directorybut using the terminal lines of code counter i naturally feel like writing more lines and spacing out code likeifvar otherechohiwould be done asifvar other echohiin this way i can come up with a very high number of lines without actually doing any real work is there any way i can count the logical lines of code in the directory is there any program that can do sothanks,"['php', 'javascript', 'html', 'css']" +397971,cannot copy a stdvector using uniform initialization is this correct the following code does not compile in gcc 472 or clang 32include vectorinclude functionalint main stdvectorstdfunctionvoid a stdvectorstdfunctionvoid bathe issue is that the compiler will try to create b using an initializer list when clearly it should just be calling the copy constructor however this seems to be desired behavior because the standard says that initializer list constructors should take precedencethis code would work fine for other stdvector but for a stdfunction the compiler cannot know whether you want the initializer list constructor or another oneit does not seem like there is a way around it and if that is the case then you can never use uniform initialization in templated code which would be a giant shamevisual studio 2012 november ctp on the other hand does not complain about this but the initializer list support is not very good in there at the moment so it might be a bug,['c++'] +397980,edittext androidhint not thisappearing onfocus i am on android 4 and i am trying to add hints to my edit text widgets i tried adding the hint to the layout as follows edittext androidididbar name androidlayout widthfill parent androidlayout heightwrap content androidinputtypetext androidhintstringbar name hint but when i focus on the text box it writes over the hint instead of the hint thisappearingi found documentation on adding a onfocus listener to the edittext but i would like to avoid doing this programatically the post below also mentioned using selectors but i cannot find documentation on how to do thatandroid edittext hintso what is the best way to handle thisi wrote this as recomended here by ac and flexo because they say comments that say nothing beyond me too are just noise and it is better to ask the same question againcomments like that are very useful as a way to contact the 1st person with the problem maybe he has already fixed it and can post an answer that will be useful for everybody but did not posted yet because he thought nobody would carei am not going to post answers to questions only to get points so i can comment i have more stuff to do it should be available to everybody anywayi wouldnt be posting this if i had not tried everything to fix my problem,['android'] +398009,how to move an element in the dom i have an element superwidget in the dom that is very interactive it uses jquery ui sortable draggable and a bunch of other pluginsdiv idwrapperadivdiv idwrapperb div idsuperwidgetdivdivi want to change the position of superwidget in the dom i want to remove it from wrapperb and place it in wrapperadiv idwrappera div idsuperwidgetdivdivdiv idwrapperbdivi have tried the followingvar copy superwidgetclonetrue truesuperwidgetremovewrapperaappendcopyhowever this breaks a lot of the plugins i do not want to have to rebind everything is there a better way to do this i notice that jquery ui sortable is somehow able to move elements around in the dom without breaking any interactivity there must be a waythanks in advance for your help,"['javascript', 'jquery']" +398030,iboutlet is nil inside custom uiview using storyboard i have custom uiview class inside it i have declared iboutlet property for uiimageviewimport uikituikithinterface settingitem uiviewproperty strong nonatomic iboutlet uiimageview myimageendnow i am using storyboard there is a viewcontroller i dragged uiview to viewcontroller i dragged one uiimageview as a subview of above uiview i set the settingitem class to uiview from storyboard i connected the outlet to myimage by normal dragging from outlets of settingitem from utilities windowsettingitem implementationimport settingitemhimplementation settingitem idinitwithframecgrectframe self super initwithframeframe if self initialization code self baseinit return selfid initwithcodernscoder adecoder self super initwithcoderadecoder if self initialization code self baseinit return self void baseinit nslogmyimage selfmyimage only override drawrect if you perform custom drawing an empty implementation adversely affects performance during animation voiddrawrectcgrectrect drawing codeendnow my problem is myimage is always nil above nslog just print null for the outlet i checked the view in storyboard and checked its outlet reference and its pointing to myimage i am missing something i googled for the help but could not find any solution can you please point out what am i doing wrong,['objective-c'] +398099,how to make a new line or tab in xml eclipseandroid so in my stringsxml i have a very long text which i want to format somehowhow can i put a tab before the first sentence of the text also what is the code for new line thanks,['android'] +398110,bottom up set generation and ordering any method about any numerical methods you know which may be relevant please post it herebackgroundi have an array of values for each set and the index to each value corresponds to the set the value is bound to therefore i represent a set as an integer where elements represent the bit position eg a set with element one in it is represented as 001 where 1 is the lsbso the set is only an index and never stored it is generated on the fly it is the key that leads to the index in the array that represent values of setswhat i do is given a set is the summed value for any of the pairwise thisjoint subset greater than the value for that set eg if set 01 have a value of 3 where two subsets have the value of 0100 2 and 0011 2 then this splitting is more beneficial to do i do this for all subsets of the set given three agents and the ordering is the sets number representationval8 01243242 the values is not important only how they are ordered 0 0 0 0 1 1 1 1 msb bit representation of the index 0 0 1 1 0 0 1 1 0 1 0 1 0 1 0 1 lsbbest splitting of 1 is 011 and 100 with a sum of 7so to get the value of the set which contain only the first element ergo 001 you put val1 for set with element 1 and 3101 you put val5 how the val array is ordered when grouped by cardinalityval8 01234242 0 0 0 1 0 1 1 1 msb bit representation of the index 0 0 1 0 1 0 1 1 0 1 0 0 1 1 0 1 lsbhere you have to translate the index to the right bin in the array so it would look like this for a set with only the third element in it100 valtranslate4 think arrays of size 225 elementslook at improving random memory access when random access is needed for further clarificationhowever this results in a high order of random access in the memory even if i group them after cardinality currently grouping them by cardinality and generating an index is slower than ordering them after the number the set representsthe way i generate an index with the sets grouped by cardinality is by using pascals triangle in constant memory as described by the answer in determin the lexicographic thistance between two integers where the sets value is located when it is ordered and grouped by cardinality with four agentsn index 1 2 4 8 3 5 6 9 10 12 7 11 13 14 15 msb 0 0 0 1 0 0 0 1 1 1 0 1 1 1 1 0 0 1 0 0 1 1 0 0 1 1 0 1 1 1 0 1 0 0 1 0 1 0 1 0 1 1 0 1 1lsb 1 0 0 0 1 1 0 1 0 0 1 1 1 0 1n index represent the index it would have if not ordered in cardinality this is just to show where the value for each set is locatedthe integer set represent an index in the value array either through direct indexwhat i am currently doing gives random access or through a translation from the set to an indexthe ideainstead of splitting a set into subsets i though of generating the sets bottom up eg instead of splitting 01 to all of its pairwise thisjoint subsets i would at some point generate if from the sets 0101100100101010110how and why it should worksay we want to evaluate all the splittings of the sets with a cardinality of 3 ergo sets 71314 as the only way to split a set of cardinality 3 is by splitting into sets of cardinality 1 and 2 we need to evaluate if the sum of any of all the thisjoint subsets of cardinality 1 and 2 is greater than the union of those sets notation of what is requiredmay be a little flawedcna ab a aa b c a a b a ab nso by reading in the values using coalesced memory access to each thread for each subsets that form a set of cardinality n check if it its value is greater than the formed set if so update the valuesimple example if n 2 then you should read in all values with cardinality 1 and do all combinations of those sets and update accordingly this example is easy as all sets are thisjoint pseudo code for 4 threads input card1 is pointer to array of sets s 1 shared int value4tid threadidxxvaluetid card1tid coalesced memory accessint thvalue valuetid holds the value for the thread to avoid bank conflictint rvalueblockdimx2 0 holds the sumint i blockdimxint x 0reduction loop that dont generate duplicate setsfori0i1 iftid i x rvaluex1 valuetidxblockdimx thvalue fori 0 i x i int index getindextidi1 gets the index for the set it generated 1 represent the cardinality ifoutputindex rvaluei outputindex rvalueiiteration of the reduction loopthread set specific for thread first iteration second iteration 0 01 01 0010 01 01001 0010 0010 0100 0010 102 0100 0100 10 none3 10 10 01 noneas you see it have fetched all the values for all the subset that form sets of cardinality 2the problem is however that generating sets of cardinality greater than 2 is more trickier due to not all sets are thisjoint eg 01 and 0011 are not thisjointkeep in mind that i do not store the sets anywhere only the value for the setsfinallyhow would you go about having this in mind creating an algorithm that reads in the memory coalesced and generating all sets from thisjoint subsets without checking whether the subsets are thisjoint it should be completely deterministicfor bountythe algorithm should be either be described text with thistinct steps marked out or pseudo code it should be proven with examples that it works not that this algorithm goes up to n32 sets so it need to scale wellthe algorithm is allowed to be spitted to two or more instances eg one for even number and one for odd i would gladly be referred to sources about the technique you usethe algorithm should use as few assignments and instructions as possible and should avoid any divergence but if you think you got one eventhough you have a lot of this try and post i will be happy with any information if it is ordered in another way but it still works as i have described i urge you to please post it here any help is really helpful please ask if there is anything uncleartldr simple explanationi have an array z with values the index i as in zi represent an integer set depending on the ordering of z the values is grouped by cardinality and ordered by binary lexicographical permutation the position the sets value is located 1243567 so i use an functioni have this function implemented to translate the index to the correct index eg set 3 index 4by having the values for the set grouped by cardinality what i want is want to see if any of the pairwise thisjoint sets value is greater than the set they form eg a 3 bc 3 b a c a b 1 so reading in x amount of values of type b and x amount of values from type c find all the thisjoint subsets of b and c that from type asets of cardinality 3 and get their sum continue until all the sets have been generatedfor referencehamming weight based indexingdetermin the lexicographic thistance between two integersimproving random memory access when random access is needed,['c'] +398114,generating function callgraph doxygengraphviz how can i generate a function call graph using doxywizard with graphviz installed i am aware of how to get doxygen to produce call caller graphs for c functions but it did not helpcurrently i have tried the following config but i cannot find the graphs anywhere i have never used the tool for this matter so it may not be a technical issue but more of a user problem,['c'] +398132,javascript how to hide unhide i am trying to avoid using innerhtml because it causes my browser to crash probably due to the 250 milliseconds refresh rateanyway i would rather have some content in an hidden div and make the div visible only if a certain condition is met whats the best approach to go around thisbasically what i am doing now issetintervalfunction if serverreachable lines of code lines of code var changeit documentgetelementbyidchange changeitinnerhtml timeout setintervalfunctionwindowlocationhref trackerhtml50 else cleartimeouttimeout timeout null var changeit documentgetelementbyidchange changeitinnerhtml offline 250this will crash my browser because i am not using innerhtml to print offline but a whole div i want to have this div hidden and instead of using innethtml to simply unhide if a condition is met in this case no internet connection,"['javascript', 'html']" +398138,word separators for postgres full text search with rails i am using pg search for some text searching within my model among other attributes i have an url fieldunfortuantelly postgres does not seem to identify and as word separators therefore i cannot search within the urlexample searching for test in yields no resultsis there a way to fix this problem perhaps using another gem or some inline sql,['ruby-on-rails'] +398153,adding a package with composer through svn i created a svn repository for my personal php library and added a composerjson file at the root level name mypersonallibrarylib type library description light mvc framework for php 54 keywords databasemvc homepage license mit require php 530 mustachemustache devmaster autoload psr0 bbn src then i created a project with the following composerjson require monologmonolog 10 zerkalicaphpcodesniffer devmaster mustachemustache devmaster mypersonallibrarylib repositories type svn url branchespath false tagspath false trunkpath src and when i try to update my project i get no valid composerjson was found in any branch or tag of httpsi think the problem is coming from my files structure but i could not manage to find any documentation about thismy repo src lib api db file html mvcphp objphp composerjsoni tried to post my url on packagistorg and got no validsupported repository was found at the given url,['php'] +398155,android easiest way to change the colour of a png file i am writing a game which has a basic sprite a balloon currently i have 2 different color balloon png files which i have created i need to create more probably another 5 or so and do not want to have like 7 different png files that would be 20 extra files as i have 4 different sizes for scaling purposes i would rather stick to 1 the ones i have at the moment are yellow and red almost solid but not quite they have details on themquestion is there a simple way to alter the colour of my existing png files i have seen people mention setcolor and setcolorfilter but i cannot work out how to use these also will these even work on png files that already have a colour or do they only work on white png files i do not think my pngs can realistically be just whitethank you all any help would be appreciated,['android'] +398188,android override 9patch padding in xml of one side when using a 9patch image as a background the padding seems to be always derived from the 9patch image even if you do not use a padding bar in the 9 patch image it uses the drawableif the padding lines are not included android uses the left and top lines to define this drawable area however you can override it in the xml by using androidpadding0dp or xdpunfortunately using androidpaddingleftxdp does not work so you are stuck with uniform padding i tried doing this androidpadding2dp androidpaddingleft20dpit had no effect on the padding on the left placing them in a stylesxml produced similar results the only hack i have seen to get around this was to set the padding in code,['android'] +398218,enable pcntl in ubuntu php test fails i need help on how to enable pcntl in ubuntu php mkdir tmpphpsource cd tmpphpsource wget tar xvf php532targz cd php532extpcntl phpize bash phpize command not foundeverything went fine until i tried to run phpize and then i get the error bash phpize command not found any ideasupdate ran sudo aptget updateand then ran sudo aptget install php5devwith the help of nick i managed to finish the procedure but make test fails phpize configure make cp modulespcntlso usrlibphp520090626 echo extensionpcntlso etcphp5confdpcntlini make test failedhelp i typed echo extensionpcntlso etcphp5confdpcntlini instead of echo extensionpcntlso etcphp5confdpcntlini the first time i ran this is that bad make test error messages php deprecated comments starting with are deprecated in tmpphpsourcephp532extpcntltmpphpini on line 1850 in unknown on line 0php deprecated comments starting with are deprecated in tmpphpsourcephp532extpcntltmpphpini on line 1852 in unknown on line 0php deprecated comments starting with are deprecated in tmpphpsourcephp532extpcntltmpphpini on line 1850 in unknown on line 0php deprecated comments starting with are deprecated in tmpphpsourcephp532extpcntltmpphpini on line 1852 in unknown on line 0php warning module pcntl already loaded in unknown on line 0warning module pcntl already loaded in unknown on line 0php deprecated comments starting with are deprecated in tmpphpsourcephp532extpcntltmpphpini on line 1850 in unknown on line 0php deprecated comments starting with are deprecated in tmpphpsourcephp532extpcntltmpphpini on line 1852 in unknown on line 0php warning module pcntl already loaded in unknown on line 0warning module pcntl already loaded in unknown on line 0php usrbinphpphp sapi cliphp version 5321ubuntu418zend version 230php os linux linux lvps217825363vpswebfusioncouk 2632042stab0688 1 smp fri dec 7 170614 msk 2012 x86 64ini actual tmpphpsourcephp532extpcntltmpphpinimore inis cwd tmpphpsourcephp532extpcntlextra dirs valgrind not usedtime start 20130102 230556fail test pcntl wait functionality tests001phptfail pcntl pcntl sigprocmask pcntl sigwaitinfo pcntl sigtimedwait tests002phptfail pcntl sig block sig unblock sig setmask tests003phptfail bug 47566 return value of pcntl wexitstatus testsbug47566phptfail pcntl alarm testspcntl alarmphptfail pcntl exec testspcntl execphptfail pcntl exec 2 testspcntl exec 2phptfail pcntl exec 3 testspcntl exec 3phptfail test function pcntl fork by calling it with its expected arguments testspcntl fork basicphptfail test function pcntl fork by testing the process isolation in the forking hierarchy father son grandson where father can not knows his grandson testspcntl fork variationphptfail pcntl signal testspcntl signalphptfail pcnt signal thispatch testspcntl signal thispatchphptfail pcntl wait testspcntl waitphptfail closures as a signal handler testssignal closure handlerphpttime end 20130102 230559test result summaryexts skipped 0exts tested 44number of tests 14 14tests skipped 0 00 tests warned 0 00 00tests failed 14 10 10expected fail 0 00 00tests passed 0 00 00time taken 3 secondsfailed test summarytest pcntl wait functionality tests001phptpcntl pcntl sigprocmask pcntl sigwaitinfo pcntl sigtimedwait tests002phptpcntl sig block sig unblock sig setmask tests003phptbug 47566 return value of pcntl wexitstatus testsbug47566phptpcntl alarm testspcntl alarmphptpcntl exec testspcntl execphptpcntl exec 2 testspcntl exec 2phptpcntl exec 3 testspcntl exec 3phpttest function pcntl fork by calling it with its expected arguments testspcntl fork basicphpttest function pcntl fork by testing the process isolation in the forking hierarchy father son grandson where father can not knows his grandson testspcntl fork variationphptpcntl signal testspcntl signalphptpcnt signal thispatch testspcntl signal thispatchphptpcntl wait testspcntl waitphptclosures as a signal handler testssignal closure handlerphptany ideascarl,['php'] +398225,nswindow is not receiving any notification when it loses focus i have a custom nswindow class that has the following methods voidsetupwindowforevents nsnotificationcenter defaultcenter addobserverself selectorselectorwindowdidresignkey namenswindowdidresignmainnotification objectself nsnotificationcenter defaultcenter addobserverself selectorselectorwindowdidresignkey namenswindowdidresignkeynotification objectselfvoidwindowdidresignkeynsnotification note nslognotification self closei call window setupwindowforevents but the windowdidresignkey never gets calledthis is how i call my nswindow when the status bar item is clicked i makekeyandorderfront and the window is thisplayed right beneath the status bar item like thisany ideas why the i do not get any notification when the window loses focus i have used both nswindowdidresignmainnotification and nswindowdidresignkeynotification to see if any of these worked but none is working,['objective-c'] +398245,how can i cut down the number of queries this code is currently executing about 50 sql queriesc categoryobjectsallcategories w rand books for category in c r bookobjectsfilterauthor categorycategoryorder by5 categories w rand booksappendcategory ri need to cut down the number of used queries to the minimum to speed up things and do not cause server loadbasically i have three models category author book the author belong to the category not books and i need to get a list of all categories with 5 random books under each one,['python'] +398248,optimising java objects for cpu cache line efficiency i am writing a library whereit will need to run on a wide range of different platforms java implementations the common case is likely to be openjdk or oracle java on intel 64 bit machines with windows or linuxachieving high performance is a priority to the extent that i care about cpu cache line efficiency in object accessin some areas quite large graphs of small objects will be traversed processed let us say around 1gb scalethe main workload is almost exclusively readsreads will be scattered across the object graph but not totally randomly ie there will be significant hotspots with occasional reads to less frequently accessed areasthe object graph will be accessed concurrently but not modified by multiple threads there is no locking on the assumption that concurrent modification will not occurare there some rules of thumb guidelines for designing small objects so that they utilise cpu cache lines effectively in this kind of environmenti am particularly interested in sizing and structuring the objects correctly so that eg the most commonly accessed fields fit in the first cache line etcnote i am fully aware that this is implementation dependent that i will need to benchmark and of the general risks of premature optimization no need to waste any further bandwidth pointing this out,['java'] +398260,horizontal scroll on textview on android i am working on a calculator i noticed that in the default android calc you can scroll the textview horizontally i looked up the documentation and found out about the attribute androidscrollhorizontally but after adding it to the textview i still cannot do horizontal scroll there is no further info about it on the documentation leading me to think that only adding the attr should suffice this is the calculators textview textview androidididedit text androidlayout width0dip androidlayout heightmatch parent androidlayout weight8 androidsinglelinetrue androidscrollhorizontallytrue androidgravitycenterright androidtext0 when characters exceed the textview width the string is trimmed and appear at it is end what am i doing wrong,"['java', 'android']" +398299,i need custom tab for specific product type only not for all product type i want to add new custom tab like in image price size for my custom product type onlyi have try code from this link1 and link2 but it show tab on all product type addeditmy question is same as this but want to do this using codingmysql4install010phpinstaller thisinstallerstartsetupinstalleraddattributecatalog product limits array group price size type varchar frontend backend custproductentity attribute backend limit label limit input text class source global mage catalog model resource eav attributescope global visible true required false user defined true default 1 searchable false filterable false comparable false visible on front true unique false apply to my custproduct model product typetype customproduct product also try custproduct is configurable falseinstalleraddattributegroupcatalog product defaultprice size 40installeraddattributetosetcatalog productdefault price size limitsfieldlist arraypricespecial pricespecial from datespecial to date minimal pricecosttier priceweighttax class id foreach fieldlist as field applyto explode installergetattributecatalog product field apply to if in arraycustproduct applyto applyto custproduct installerupdateattributecatalog product field apply to join applyto installerendsetupattribute limits is added but it show on all product type i need it only with my custom product typecustproduct onlythank for reply my issue solved nowjust added limits to fieldlist arrayfieldlist arraypricespecial pricespecial from datespecial to date minimal pricecosttier priceweighttax class id limitsthanks,['php'] +398349,all my java projects are giving errors after installing new jre in eclipse i installed an older version of jre all my projects start to give compiler errors there is a cross and unbound message onbuild path for project when i checked they still see the uninstalled jre in path i did some of them and changed one by one but is not there a quick way to add new jre to all my current projects at one timei have almost 80 projects and to make them one by one is time consumingthanks,['java'] +398370,session timeout on ajax call i know this is duplicate but i could not get reliable solutionfor aspnet webi just want to redirect to the login page if session expires i have tried following1 using jquery status code ajax type post url streamasmxsomemethod contenttype applicationjson charsetutf8 datatype json success function msg success msg error function request status error if status 403 locationhref loginaspx problem this returns same status code403 for other errors too which i only expect for session timeout2 sending json message whether session expiredcode behind if objectequalshttpcontextcurrentsessionuser null id intparsehttpcontextcurrentsessionusertostring else result from row in dtscrabasenumerable select new redirecturl loginaspx isredirect true on ajax success success function msg if msgd0isredirect windowlocationhref msgd0redirecturl else load containt problem it is somehow desnt invoke ajax success line if session expiresit does return correct json and even this is not a proper way if i have many number of ajax request in the pageshould be handled globally however i saw this post which is really good soltion but it is for mvc using authorizeattribute handlingsessiontimeoutinajaxcallsso is there i can use same concept used in mvc using authorizeattribute in aspnet web api if not how i can troubleshoot those issue which i am facing any of above two mentioned,"['c#', 'asp.net']" +398375,how to determine location of device in android using ip address i am developing an android appi want to determine the location of the device using its ip addresswhere do i startthe links on google apis are not conclusive enoughthanks,['android'] +398402,list comprehension in function arguments in python 271 i am trying to provide a list of messages as the first argument and a list of colors as the second argument i want the second argument to default to a list of whites if it is not provided this is the way i tried to do itdef multicolor messagemsgs colorslibtcodwhite for x in lenmsgsfunction bodylibtcodwhite is a part of the library i am using and is in no way causing any problemsthe compiler says the variable msgs is not defined obviously the msgs variable does not exist in this scope but i need to create a list of appropriate length and assign it to colors what is the cleanest way to do this,['python'] +398408,is it possible to have multiline datagridview cells without wrapping text i know i can set wrapmode to true on the defaultcellstyle of the rowtemplate however this does not give me the behaviour i want i am thisplaying a list of strings within each cell and i therefore want the carriage returns to be recognised but i do not want text from long items wrappingdoes anyone know if it is possible to achieve this,['c#'] +398421,why does a recursed return call break out of stack without an explicit return statement i was shown a sample program to demonstrate recursion which looks like it should not work but does the logic is pretty clear but why does it work even when the recursed function call is not returned it seems like the return command breaks out of the stack even if it is not requested to is this a language standard or a gcc thing i saw it with c and c compiled with gcc on windows and linuxinclude iostreaminclude cstdlibusing namespace stdint isprimeint num int i if i 1 return 1 else if num i 0 return 0 else isprimenum i1 should be returned int mainint argc char argv int input atoiargv1 cout input t isprimeinput input2 n,['c++'] +398467,styling of submit buttons i am wondering if anyone knows why the default style of a submit button looks pretty good corners slightly rounded some gradient from top to bottom etc but the moment i add a background color it changes to a 1990s era square button with 2px borderjust looks awfulcan i somehow keep most of the default styling but change the background color thank you,"['html', 'css']" +398491,sql like operator with parameters and wildcards i have a query where i want to return all clients that have a certain string in the name with wildcards on either side so the input could be smith and i want to return all things like the john smith company or smith and bros i want client to be prompted so i set up the sql like thisparameters client text 255 select where tbl incomingchecksclient like client order by tbl incomingchecksclientthe query is not returning any results please help,['sql'] +398497,compressing x if x else y statement in python i am quite acquainted with pythons ternary operator approachvalue foo if something else barmy question is very simple without prior assignments is there anyway to reference the term being evaluated in if from one of the return operands if or else the motivation here is that sometimes i use expressions in if that are exactly what i would like to have as result in the ternary operation happens though that for small expressions there is no problem repeating it but for a bit longer expressions it goes somewhat nasty take this as an examplevalue infofindnextb if infofindnextb else oompa loompa,['python'] +398504,how does stdflush work can someone please explain preferably using plain english how stdflush workswhat is itwhen would you flush a streamwhy is it importantthank you,['c++'] +398517,why are multiple assignments in one line considered bad style in c you can do multiple assignment by doing thisx y z 10yet multiple people have told me that is a bad style and i should not be using it without giving me a reason why can someone please explain to me why this is considered a bad style,['c++'] +398522,linux memory usage in top when using stdvector versus stdlist i have noticed some interesting behavior in linux with regard to the memory usage res reported by top i have attached the following program which allocates a couple million objects on the heap each of which has a buffer that is around 1 kilobyte the pointers to those objects are tracked by either a stdlist or a stdvector the interesting behavior i have noticed is that if i use a stdlist the memory usage reported by top never changes during the sleep periods however if i use stdvector the memory usage will drop to near 0 during those sleepsmy test configuration isfedora core 16kernel 3674g version 463what i already know1 stdvector will reallocate doubling its size as needed2 stdlist i beleive is allocating its elements 1 at a time3 both stdvector and stdlist are using stdallocator by default to get their actual memory4 the program is not leaking valgrind has declared that no leaks are possiblewhat i am confused by1 both stdvector and stdlist are using stdallocator even if stdvector is doing batch reallocations wouldnt stdallocator be handing out memory in almost the same arrangement to stdlist and stdvector this program is single threaded after all2 where can i learn about the behavior of linuxs memory allocation i have heard statements about linux keeping ram assigned to a process even after it frees it but i do not know if that behavior is guaranteed why does using stdvector impact that behavior so muchmany thanks for reading this i know this is a pretty fuzzy problem the answer i am looking for here is if this behavior is defined and where i can find its documentationinclude stringhinclude unistdhinclude iostreaminclude vectorinclude listinclude iostreaminclude memoryclass foopublic foo data new char9 memsetdata x 9 foo delete data private char dataint mainint argc char argv forint x0 x10 x sleep1 stdauto ptrstdlistfoo foosnew stdlistfoo stdauto ptrstdvectorfoo foosnew stdvectorfoo forint i0 i20 i foospush backnew foo stdcout sleeping before deallocn sleep5 whilefalse foosempty delete foosback foospop back stdcout sleeping after final deallocn sleep5,['c++'] +398534,python subprocess call check call and returncode to find if a command exists i have figured out how to use call to get my python script to run a commandimport subprocessmycommandline lumberjack sleep all night work all daysubprocesscallmycommandlinethis works but there is a problem what if users do not have lumberjack in their command path it would work if lumberjack was put in the same directory as the python script but how does the script know it should look for lumberjack i figured if there was a commandnotfound error then lumberjack wouldnt be in the command path the script could try to figure out what its directory is and look for lumberjack there and finally warn the user to copy lumberjack into one of those two places if it was not found in either one how do i find out what the error message is i read that check call can return an error message and something about a returncode attribute i could not find examples on how to use check call and returncode what the message would be or how i could tell if the message is commandnotfoundam i even going about this the right way,['python'] +398539,how can i avoid a full table scan on this mysql query explainselect from zipcode thistances z inner join venues v on zzipcode tovzipcodeinner join events e on videvenue idwhere zzipcode from92108 and zthistance 5i am trying to find all events at venues within 5 miles of zipcode 92108 however i am having a hard time optimizing this queryhere is what the explain looks likeid select type table type possible keys key key len ref rows extra1 simple e all idx venue id 60024 1 simple v eq ref primaryidx zipcode primary 4 comedyworldevenue id 1 1 simple z ref idx zip from thistanceidx zip to thistanceidx zip from to idx zip from to 30 constcomedyworldvzipcode 1 using where using indexi am getting a full table scan on the e table and i cannot figure out what index i need to create to get it to be fastany advice would be appreciatedthank you,['mysql'] +398556,how to verify and require selfsigned certificate in ios i would like to create an ssl connection to my server using selfsigned certificates that are shipped with the code in ios that way i do not have to worry about more sophisticated maninthemiddle attacks where someone has access to a high level trusted cert authority i am having issues doing so using what i believe to be apples standard waygenerating the certificate via the procedure found here create root ca private keyopenssl req newkey rsa4096 sha512 days 9 x509 nodes out rootpemcer create a certificate signing requestopenssl req newkey rsa4096 sha512 nodes out sslcsr keyout sslkey create an openssl configuration file from enhtmlvim opensslconf create the indexestouch certindexecho 0a certserialecho 0a crlnumber generate ssl certificate openssl ca batch config opensslconf notext in sslcsr out sslpemcer create certificate revocation listopenssl ca config opensslconf gencrl keyfile privkeypem cert rootpemcer out rootcrlpemopenssl crl inform pem in rootcrlpem outform der out rootcrl rm rootcrlpemand the ios code voidconnectionnsurlconnection connection willsendrequestforauthenticationchallengensurlauthenticationchallenge challenge nsurlprotectionspace protectionspace challenge protectionspace if protectionspace authenticationmethod nsurlauthenticationmethodservertrust load anchor cert also tried this with both certs and it does not seem to matter nsstring path nsbundle mainbundle pathforresourcerootder oftypecrt nsdata data nsdata alloc initwithcontentsoffilepath seccertificateref anchorcert seccertificatecreatewithdatakcfallocatordefault bridge cfdatarefdata cfmutablearrayref anchorcerts cfarraycreatemutablekcfallocatordefault 0 kcftypearraycallbacks cfarrayappendvalueanchorcerts anchorcert set anchor cert sectrustref trust protectionspace servertrust sectrustsetanchorcertificatestrust anchorcerts sectrustsetanchorcertificatesonlytrust yes only use that certificate cfreleaseanchorcert cfreleaseanchorcerts validate cert sectrustresulttype secresult ksectrustresultinvalid if sectrustevaluatetrust secresult errsecsuccess challengesender cancelauthenticationchallengechallenge return switch secresult case ksectrustresultinvalid case ksectrustresultdeny case ksectrustresultfataltrustfailure case ksectrustresultothererror case ksectrustresultrecoverabletrustfailure it is always ksectrustresultrecoverabletrustfailure aka 5 nslogfailing due to result lu secresult challengesender cancelauthenticationchallengechallenge return case ksectrustresultunspecified the os trusts this certificate implicitly case ksectrustresultproceed the user explicitly told the os to trust it nsurlcredential credential nsurlcredential credentialfortrusttrust challengesender usecredentialcredential forauthenticationchallengechallenge return default it is somebody elses key fall through the server sent a key other than the trusted key connection cancel perform other cleanup here as needed else nslogin weird space not handling authentication method protectionspace authenticationmethod connection cancel i am always getting ksectrustresultrecoverabletrustfailure as the result i do not think this is localhost issue as i have tried using apples code to change that too what to dothanks,['ios'] +398581,javascript function scoped for loops heres an example of a situation where a simple js loop does not behave as expected because of the loop variable not being in a separate scope the solution often presented is to construct an unpleasantlooking bit of loop code that looks like this for var i in obj function obji this new shadowed i here is now no longer getting changed by for loop imy question is could this be improved upon could i use this objectprototypeeach function f for var i in this fithisi leading to this somewhat more straightforward invocationobjeach functioniv v alternatively v is identical to obji when i ascertain that i need a scoped loop it is somewhat cleaner looking and should have similar performance to the regular forloop since it uses it the same way update it seems that doing things with objectprototype is a huge nono because it breaks pretty much everything here is a less intrusive implementation function each objf for var i in obj fiobji the invocation changes very slightly to eachobj functioniv v so i guess i have answered my own question if jquery does it this way cannot really go wrong any issues i have overlooked though would warrant an answer,['javascript'] +398588,how to align text vertically center in android i have arabic text therefore i set gravity to right in order to start text from right side text starts from right now but another issue is text starts to render from the top of the page but i need to vertically center the textalthough i tried several variations i couldnt make it vertically centerhere is the sample of my xml filelinearlayout androidididlinearlayout5 androidlayout widthfill parent androidlayout heightwrap content androidgravityright androidorientationvertical textview androidididtextview2 androidlayout widthwrap content androidlayout heightwrap content androidlayout gravitycenter vertical androidlayout marginbottom23dp androidgravityright androidpaddingdimenpadding maintextview androidtextstringtext androidtextappearanceandroidattrtextappearancemedium androidtextsize20sp linearlayoutproblem is with above textviewhere i have put whole xml filexml version10 encodingutf8relativelayout xmlnsandroid androidlayout widthfill parent androidlayout heightwrap content androidbackgrounddrawablepage1background androidpaddingrightdimenpadding large textview androidididtextview1 androidlayout width196dp androidlayout heightwrap content androidlayout centerhorizontaltrue androidgravitycenter horizontal androidpaddingtopdimenpadding title top androidtextstringtext androidtextappearanceandroidattrtextappearancemedium androidtextsize20sp linearlayout androidididlinearlayout1 androidlayout widthwrap content androidlayout heightwrap content androidlayout belowidtextview1 androidgravitycenter horizontal androidorientationvertical view androidididview1 androidlayout widthfill parent androidlayout height5dp linearlayout scrollview androidlayout widthfill parent androidlayout heightwrap content androidlayout aboveidlinearlayout2 androidlayout belowidlinearlayout1 androidlayout gravitycenter androidpaddingdimenpadding maintextview linearlayout androidididlinearlayout5 androidlayout widthfill parent androidlayout heightwrap content androidgravityright androidorientationvertical textview androidididtextview2 androidlayout widthwrap content androidlayout heightwrap content androidlayout gravitycenter vertical androidlayout marginbottom23dp androidgravityright androidpaddingdimenpadding maintextview androidtextstringtext androidtextappearanceandroidattrtextappearancemedium androidtextsize20sp linearlayout scrollview linearlayout androidididlinearlayout2 androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentbottomtrue androidlayout centerhorizontaltrue view androidididview2 androidlayout widthfill parent androidlayout height100dp linearlayout linearlayout androidididlinearlayout3 androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentbottomtrue androidlayout centerhorizontaltrue imagebutton androidididback arrow androidlayout width0dip androidlayout heightwrap content androidlayout marginbottom30dp androidlayout marginright45dp androidlayout weight5 androidbackgrounddrawablebackbut androidcontentdescriptionstringdescription androidonclickonclickbtn androidsrcdrawablebackarrowpress imagebutton androidididcopybutton androidlayout width0dip androidlayout heightwrap content androidlayout marginleft45dp androidlayout weight5 androidbackgrounddrawablecopy androidcontentdescriptionstringdescription androidonclickonclickbtn linearlayoutrelativelayoutcan anybody show me where i have done the mistake i think problem is clear if not tell me in commentsherewith i have appended updated code after review your answersxml version10 encodingutf8relativelayout xmlnsandroid androidlayout widthfill parent androidlayout heightwrap content androidbackgrounddrawablepage1background androidpaddingrightdimenpadding large textview androidididtextview1 androidlayout width196dp androidlayout heightwrap content androidlayout centerhorizontaltrue androidgravitycenter horizontal androidpaddingtopdimenpadding title top androidtextstringtext androidtextappearanceandroidattrtextappearancemedium androidtextsize20sp linearlayout androidididlinearlayout1 androidlayout widthwrap content androidlayout heightwrap content androidlayout belowidtextview1 androidgravitycenter horizontal androidorientationvertical view androidididview1 androidlayout widthfill parent androidlayout height5dp linearlayout scrollview androidlayout widthfill parent androidlayout heightfill parent androidlayout aboveidlinearlayout2 androidlayout belowidlinearlayout1 androidlayout gravitycenter androidlayout centerinparenttrue androidpaddingdimenpadding maintextview linearlayout androidididlinearlayout5 androidlayout widthfill parent androidlayout heightwrap content androidgravityright androidorientationvertical textview androidididtextview2 androidlayout widthfill parent androidlayout heightfill parent androidlayout gravitycenter vertical androidlayout marginbottom23dp androidgravitycenter verticalright androidpaddingdimenpadding maintextview androidtextstringtext androidtextappearanceandroidattrtextappearancemedium androidtextsize20sp linearlayout scrollview linearlayout androidididlinearlayout2 androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentbottomtrue androidlayout centerhorizontaltrue view androidididview2 androidlayout widthfill parent androidlayout height100dp linearlayout linearlayout androidididlinearlayout3 androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentbottomtrue androidlayout centerhorizontaltrue imagebutton androidididback arrow androidlayout width0dip androidlayout heightwrap content androidlayout marginbottom30dp androidlayout marginright45dp androidlayout weight5 androidbackgrounddrawablebackbut androidcontentdescriptionstringdescription androidonclickonclickbtn androidsrcdrawablebackarrowpress imagebutton androidididcopybutton androidlayout width0dip androidlayout heightwrap content androidlayout marginleft45dp androidlayout weight5 androidbackgrounddrawablecopy androidcontentdescriptionstringdescription androidonclickonclickbtn linearlayoutrelativelayoutbut i am in same situation no text is vertically centered,['android'] +398589,cookies not sent on windows phone app but cookies are sent with same code in windows 8 app i have a basic class that makes get and post requests using httpwebrequesthttpwebresponsei use my class to login to an api and then request data in a windows 8 metro application it works exactly as expected on a windows phone 8 application the login appears to succeed but in the subsequent request for data no cookies are sent and the server responds as if the client is not logged inhere is the class this exact same code is used in the windows 8 app and the windows phone appclass class1 cookiecontainer cookiejar new cookiecontainer cookiecollection responsecookies new cookiecollection public async taskstring httprequesthttpwebrequest request string received using var response httpwebresponseawait taskwebresponsefactoryfromasyncrequestbegingetresponse requestendgetresponse null using var responsestream responsegetresponsestream using var sr new streamreaderresponsestream cookiejar requestcookiecontainer responsecookies responsecookies received await srreadtoendasync return received public async taskstring getstring path var request webrequestcreatenew uripath as httpwebrequest requestcookiecontainer cookiejar return await httprequestrequest public async taskstring poststring path string postdata var request webrequestcreatenew uripath as httpwebrequest requestmethod post requestcookiecontainer cookiejar byte data encodingutf8getbytespostdata using var requeststream await taskstreamfactoryfromasyncrequestbegingetrequeststream requestendgetrequeststream null await requeststreamwriteasyncdata 0 datalength return await httprequestrequest and the code to initiate the requests var and new class1 await npost usernamemyusernamepasswordmypassword await ngetthe curious thing is that if i prefix the domain name with w it works in both the windows phone 8 app and the windows 8 metro appi think it has something to do with how the domain is handled the cookies domain is mydomaincom and without the prefix it must think the cookies do not belong to that domain after some searching i found a report of someone noticing a similar problemwhat i do not understand is why this is treated differently in the windows 8 app than the windows phone app so that lineforline identical code works on one platform but fails on anotheri have done some more digging into thisthe server code i used for this is in phpphpif requestwhat set setcookietestcookie requestusername requestpassword time360024 subdmydomaincomif getwhat get var dump cookieclient code in c var and new classlibrary1class1 await ngetusernamefoopasswordbar await ngethere is an example of a cookie response from the serversetcookie arraffinity295612ca pathdomainsubdmydomaincomsetcookie testcookiefoobar expiresfri 04jan2013 171925 gmt path domainsubdmydomaincomin the windows 8 storemetro app this is the resultarray2 arraffinity string8 295612ca testcookie string7 foo barin the windows phone app this is the resultarray0the windows phone does not see any cookies when they are set this wayi change how testcookie is set the result from the server now looks like thissetcookie arraffinity295612capathdomainsubdmydomaincomsetcookie testcookiefoobar expiresfri 04jan2013 172959 gmt pathtestcookie now does not explicitly set a domain arraffinity is unchangedthe windows 8 storemetro app now returns thisarray2 testcookie string7 foo bar arraffinity string8 295612cathe windows phone 8 app returns thisarray1 testcookie string7 foo barthe arraffinity cookie is not sent because it explicitly declares a domainif i assign some breakpoints and check the cookiecontainer of the request i have two entries in the m domaintable 0 subdmydomaincom systemnetpathlist systemcollectionsgenerickeyvaluepairstringsystemnetpathlist 1 subdmydomaincom systemnetpathlist systemcollectionsgenerickeyvaluepairstringsystemnetpathlistthe cookie that is not sent is in the subdmydomaincom container this is the same on both windows 8 and windows phone 8however if the cookie declares itself like thissetcookie testcookiefoobar expiresfri 04jan2013 171925 gmt path domainmydomaincomit is correctly sent on windows phone 8in my original case the server declares the cookie the same way regardless of if it is accessed via mydomaincom or wmydomaincom as mydomaincom but windows phone 8 does not seem to think a cookie for mydomaincom should be sent to mydomaincom this is problematic as even if the server puts subdmydomaincom as the domain it is treated as having a preceding dot and then does not work through no fault of its own it seems it has to not send domain info with the cookie to have it treated correctly,"['c#', '.net']" +398612,thisable slidingmenu in activity i have one parent class which uses slidingmenu and the childs extending parent class shows the sliding menu on home icon clickhow to thisable the sliding menu in the child classescodes parent class public class bcfragmentactivity extends slidingfragmentactivity override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate getsupportactionbarsetthisplayhomeasupenabledtrue setslidingactionbarenabledtrue setbehindcontentviewrlayoutslide menu getslidingmenusetshadowwidthresrdimenshadow width getslidingmenusetshadowdrawablerdrawableshadow getslidingmenusetbehindoffsetresrdimenactionbar home width getslidingmenusetbehindscrollscale025f override public boolean onoptionsitemselectedmenuitem item switch itemgetitemid case androidridhome toggle return true return superonoptionsitemselecteditem codes for child class public class settingspageractivity extends bcfragmentactivity private actionbar actionbar private viewpager settingspager private tab profilestab private tab accountstab override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity settings pager actionbar getsupportactionbar actionbarsetnavigationmodeactionbarnavigation mode tabs settingspager viewpager findviewbyidridsettingspage settingspagersetonpagechangelistenerpagechangelistener fragmentmanager fm getsupportfragmentmanager profilestab actionbarnewtab settextprofile settablistenertablistener accountstab actionbarnewtab settextaccount settablistenertablistener actionbaraddtabprofilestab actionbaraddtabaccountstab actionbartablistener tablistener new actionbartablistener override public void ontabselectedtab tab fragmenttransaction ft settingspagersetcurrentitemtabgetposition override public void ontabunselectedtab tab fragmenttransaction ft todo autogenerated method stub override public void ontabreselectedtab tab fragmenttransaction ft todo autogenerated method stub viewpagersimpleonpagechangelistener pagechangelistener new viewpagersimpleonpagechangelistener override public void onpageselectedint position superonpageselectedposition actionbarsetselectednavigationitemposition,['android'] +398613,facebook ios seems lost session when return to app after clicking okay to you have already authorized app i have upgraded my app from facebook sdk 2 to 31i have a post button on the recordsscreen if the user is not login to facebook the login page will appear and if the user is login already another nib will be loaded to prompt the user to enter a message for posting to hisher own walli have already login and after that every time when i click the post button the page about the app is already authorized and ask you whether to continue by clicking okay appears after clicking okay the app terminates and starts again launching from the beginning every time when i click the post button this same page appears again it look like it cannot find a valid session or the token is losti have tested this on the simulator and the device same thing occurs deployment target is ios51the only parameter i have not entered is the iphone app store id will this affect the above behavior i have tried a lot of times already and could not find a solutionany help is appreciatedthanksaobsedited on jan 4i found out that every time opensessionwithallowloginui is called the state fbsessionstateclosedloginfailed is returned there is a problem with login but the user has login already since the already authorized page appearsthe reason is applicationwillterminate executes right after opensessonwithallowloginui can anyone shed light on thisin the appdelegateh i import the facebooksdkfacebooksdkh and in appdelegatem the following is implementedboolapplicationuiapplication application openurlnsurl url sourceapplicationnsstring sourceapplication annotationidannotation return fbsessionactivesession handleopenurlurlvoidapplicationdidbecomeactiveuiapplication application fbsessionactivesession handledidbecomeactivevoidapplicationwillterminateuiapplication application fbsessionactivesession closethe mainviewcontroller is a multiview controller that will switch nibsi have implemented a class fbhandler to handle facebook loginlogout fbhandlerh contains import facebookh and fbhandler is a class that containsvoidsessionstatechangedfbsession session statefbsessionstatestate errornserror error switchstate case fbsessionstateopen break case fbsessionstateclosed case fbsessionstateclosedloginfailed fbsessionactivesession closeandcleartokeninformation default break nsnotificationcenter defaultcenterpostnotificationnamefbsessionstatechangednotification objectsession if there is an error thisplay the alert view i have skipped this codeboolopensessionwithallowloginuiboolallowloginui return fbsession openactivesessionwithreadpermissionsnil allowloginuiallowloginui completionhandlerfbsession session fbsessionstate state nserror error self sessionstatechangedsession statestate errorerror one of the nibs recordsscreenxib contains the facebook loginlogout buttons in the recordsscreenm a place where the user can see hisher score and login or logout from facebook the following is added to viewdidloadfbhandler fbhandler alloc initfbhandler opensessionwithallowloginuino also we will listen to fbsessionstatechangednotification in viewdidload code is skipped here the implementation of sessionstatechanged in recordsscreenvoidsessionstatechangednsnotification notification if fbsessionactivesessionisopen if selffacebook nil selffacebook facebook allocinitwithappidfbsessionactivesessionappid anddelegatenil selffacebookaccesstoken fbsessionactivesessionaccesstoken selffacebookexpirationdate fbsessionactivesessionexpirationdate else selffacebook nil in recordsscreenm if the user clicks the login in button if fbsessionactivesessionisopen login to facebook fbhandler opensessionwithallowloginuiyes else if user is login post to wall self postscoretowall,"['iphone', 'ios']" +398632,alternative of datatypeconverterprinthexbinarybyte array and datatypeconverterparsehexbinarystring str in android what are the alternative of datatypeconverterprinthexbinarybyte array and datatypeconverterparsehexbinarystring str in android android do not have classdef of javaxmlbinddatatypeconverter,['android'] +398638,what is passbooks urlscheme for ios6 possible duplicateios 6 passbook open passbook app from my app hi what is the urlscheme for the new passbook app in ios6 as i cannot find it anywhere on the web thanks in advance,"['iphone', 'ios']" +398679,application stopped working after enabling proguard it was a working app both on emulator and the device i am testing onbut now i enabled proguard and exported the signed app using androidtools export signed applicationthen i copied this apk on to the sd card and tried to install on the device but the application stopped working asking for force close if i try to open itit works on the device if i run from eclipsesince its saidproguard has effect only when you export a release apk file i checked it and the apk file size in the bin folder is 18mb where as the 1 i got after exporting is 14mb seems like proguard has done its job but the application is not working and sadly i cannot see any logs etceditif i thisabled proguard and then exported the release apk file works fine now so some problem with proguardmy folder structureproguardprojecttxt this is a configuration file for proguard dontusemixedcaseclassnamesdontskipnonpubliclibraryclassesverbose optimization is turned off by default dex does not like code run through the proguard optimize and preverify steps and performs some of these optimizations on its owndontoptimizedontpreverify note that if you want to enable optimization you cannot just include optimization flags in your own project configuration file instead you will need to point to the proguardandroidoptimizetxt file instead of this one from your projectproperties filekeepattributes annotationkeep public class comgooglevendinglicensingilicensingservicekeep public class comandroidvendinglicensingilicensingservicekeep public class extends androidappapplicationkeep public class extends androidappactivitykeep public class extends androidapreferenceactivitykeep public class extends androidviewviewkeep public class extends androidwidgetbaseadapterkeep public class extends androidappservicekeep public class extends androidcontentbroadcastreceiverkeep public class implements androidviewviewontouchlistenerkeep public class implements androidviewviewonclicklistenerkeep public class extends comactionbarsherlockappsherlockactivitykeep public class extends comactionbarsherlockappsherlockfragmentactivitykeep public class extends comactionbarsherlockappsherlockmapactivitykeep public class extends comreadystatesoftwaremapviewballoonsballoonitemizedoverlayoverlayitemkeep public class extends comactionbarsherlockappsherlockfragmentlibraryjars libsandroidsupportv4jarlibraryjars libsapachemime4j06jarlibraryjars libshttpmime401jarlibraryjars libslibgoogleanalyticsv2jar assumenosideeffects class androidutillog public static v public static i public static d public static w public static e for native methods see keepclasseswithmembernames class native methods keep setters in views so that animations can still work see keepclassmembers public class extends androidviewview void set get we want to keep methods in activity that could be used in the xml attribute onclickkeepclassmembers class extends androidappactivity public void androidviewview for enumeration classes see keepclassmembers enum public static values public static valueofjavalangstringkeep class implements androidosparcelable public static final androidosparcelablecreator keepclassmembers class r public static fields the support library contains references to newer platform versions do not warn about those in case this app is linking against an older platform version we know about them and they are safedontwarn androidsupportdontwarn orgapachei just started using it today and i am not sure if i am using it the right way so please correct me if i am wrong anywherethis is the logcat error0102 131854711 eandroidruntime585 javalangruntimeexception unable to start activity componentinfocomxappappcomxappapplandingactivity javalangruntimeexception javalangnosuchmethodexception aactivityint0102 131854711 eandroidruntime585 at androidappactivitythreadperformlaunchactivityactivitythreadjava16470102 131854711 eandroidruntime585 at androidappactivitythreadhandlelaunchactivityactivitythreadjava16630102 131854711 eandroidruntime585 at androidappactivitythreadaccess1500activitythreadjava1170102 131854711 eandroidruntime585 at androidappactivitythreadhhandlemessageactivitythreadjava9310102 131854711 eandroidruntime585 at androidoshandlerthispatchmessagehandlerjava990102 131854711 eandroidruntime585 at androidoslooperlooplooperjava1300102 131854711 eandroidruntime585 at androidappactivitythreadmainactivitythreadjava36830102 131854711 eandroidruntime585 at javalangreflectmethodinvokenativenative method0102 131854711 eandroidruntime585 at javalangreflectmethodinvokemethodjava5070102 131854711 eandroidruntime585 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava8390102 131854711 eandroidruntime585 at comandroidinternaloszygoteinitmainzygoteinitjava5970102 131854711 eandroidruntime585 at dalviksystemnativestartmainnative method0102 131854711 eandroidruntime585 caused by javalangruntimeexception javalangnosuchmethodexception aactivityint0102 131854711 eandroidruntime585 at comactionbarsherlockaaunknown source0102 131854711 eandroidruntime585 at comactionbarsherlockappsherlockactivityaunknown source0102 131854711 eandroidruntime585 at comactionbarsherlockappsherlockactivitysetcontentviewunknown source0102 131854711 eandroidruntime585 at comxappapplandingactivityoncreateunknown source0102 131854711 eandroidruntime585 at androidappinstrumentationcallactivityoncreateinstrumentationjava10470102 131854711 eandroidruntime585 at androidappactivitythreadperformlaunchactivityactivitythreadjava16110102 131854711 eandroidruntime585 11 more0102 131854711 eandroidruntime585 caused by javalangnosuchmethodexception aactivityint0102 131854711 eandroidruntime585 at javalangclassgetmatchingconstructorclassjava6430102 131854711 eandroidruntime585 at javalangclassgetconstructorclassjava4720102 131854711 eandroidruntime585 17 morethank you,['android'] +398704,using new on void pointer int main void foo new delete foohow do you do something like the above you cannot put new voidsize and i do not want to know how to do it with malloc and free i already know that works i am curious and want to know how it is done with new and deletei googled this and saw something about operator newsize and operator deletesizewhat is the difference between those and newdelete why does c not just allow new voidsize,['c++'] +398714,groupby with elementselector and resultselector the enumerablegroupby and queryablegroupby extensions have 8 overloads two of them for enumerablegroupby are aienumerabletresult groupbytsource tkey tresult this ienumerabletsource source functsource tkey keyselector functkey ienumerabletsource tresult resultselector bienumerabletresult groupbytsource tkey telement tresult this ienumerabletsource source functsource tkey keyselector functsource telement elementselector functkey ienumerabletelement tresult resultselectorfor queryablegroupby the same just with expressionfunc instead of funcb has an additional elementselector as parameteron msdn is an example for overload a and an example for overload b they both work with the same example source collectionlistpet petslist new listpet new pet namebarley age83 new pet nameboots age49 new pet namewhiskers age15 new pet namedaisy age43 example a uses this queryvar query petslistgroupby pet mathfloorpetage keyselector age pets new resultselector key age count petscount min petsminpet petage max petsmaxpet petage and example b uses this queryvar query petslistgroupby pet mathfloorpetage keyselector pet petage elementselector baseage ages new resultselector key baseage count agescount min agesmin max agesmax the result of both queries is exactly the samequestion 1 is there any kind of query that i cannot express by using the resultselector alone and where i really would need the elementselector or are the capabilities of the two overloads always equivalent and it is just a matter of taste to use one or the other wayquestion 2 is there a counterpart for the two different overloads when using linq query syntaxas a side question when using queryablegroupby with entity framework will both overloads be translated into the exact same sql,"['c#', '.net']" +398724,how to desaturate background image of a div using css i saw so many plugins to desaturate an image with in the tagbut i did not find any thing to desaturate the background imagean image which is used as a background for an element divis there a way to desaturate the background image on hover with out using 2 backgroundsie image sprites one is bw and the other is colori can do something like this using image sprites initially color image elementmouseoverfunctione jquerythischildrenfirststopanimate backgroundposition some coordinates coordinates of bw image 100 estoppropagation mouseoutfunctione jquerythischildrenfirststopanimate backgroundposition some coordinates coordinates of color image 100 settingseasingtype estoppropagation but i dont want this i want desaturate background image on flyplease help,"['javascript', 'html']" +398773,use php codesniffer for modified lines only i am trying to build a precommit script in svn and i want to run php codesniffer on the modified lines only as opposed to the whole file so far i have this scriptbinshrepos1txn2 make sure that the log message contains some textsvnlookusrbinsvnlooksvnlook log t txn repos grep azaz09 devnull exit 1 check for code validation before commiting the script using php codesniffertmppeardownloadphp codesniffer143scriptsphpcssvnprecommit repos t txn 2 exit 1 all checks passed so allow the commitexit 0,['php'] +398776,making an https connection using urlopenconnection i am trying to make an https connection to a server that has a certificate set to expire in april 2013 and uses globalsign as the root certificatehttpsurlconnection urlconnection httpsurlconnection urlopenconnection urlconnectionsetsslsocketfactorysslsocketfactoryurlconnectionsetdooutputtrueurlconnectionsetchunkedstreamingmode0 send the post dataoutputstream out new bufferedoutputstreamurlconnectiongetoutputstreamoutwritepostparamstringtostringgetbytesutf8 read the replyinputstream in urlconnectiongetinputstreamas it stands this throws javaxnetsslsslhandshakeexception orgbouncycastlejceexceptionextcertpathvalidatorexception could not validate certificate signature when getoutputstream is calledthis same site and certificate are valid in the stock htc web browser and desktop browsers when i use the same code to access google it works but then complains about a 404 error various posts on stackoverflow imply that it should just work and others say to set up your own key store or thisable all https validation i assume the difference in behaviour is down to different root key stores in use can anyone clarify thisi have now tried creating a key store using bouncy castle but i cannot get this to load on my deviceafter exporting the certificate from firefox i create a key store usingkeytoolexe import alias onlinescoutmanager file wonlinescoutmanagercoukcrt storetype bks keystore resrawkeystorethis is then loaded and used in the application usinginputstream stream contextgetresourcesopenrawresourcerrawkeystore bks seems to be the default but we want to be explicitkeystore ks keystoregetinstancebksksloadstream wonlinescoutmanagercouktochararraystreamclosetrustmanagerfactory tmf trustmanagerfactorygetinstancetrustmanagerfactorygetdefaultalgorithmtmfinitksx509trustmanager defaulttrustmanager x509trustmanager tmfgettrustmanagers0sslcontext context2 sslcontextgetinstancetlscontext2initnull new trustmanager defaulttrustmanager nullsslsocketfactory context2getsocketfactorythis is failing with javaioioexception wrong version of key store when keystoreload is calledi have ensured i am passing storetype bks used a 7 character keystore password added the ca certs to the key store and using both bouncy castle version 145 and 147 to create the key store with no change in the reported error messagemy environment is eclipse juno 421 with jre 17u9b5 running on windows 8 the device i am testing on is an htc sensation running stock android 23 the application has a minimum sdk version of 7 and a target of 15if anyone can explain how to create a valid bks key store on windows 8 or how i can get java to use the same key store as the browseror system that would be appreciatedyou can download the entire project as it was at the time of writing and the generated keystore if required,"['java', 'android']" +398780,how to thisable caching of html when testing in chrome i think this is because of cacheing but i am not totally sure the issue i am having is that when i change a file and save it it is not updating in my browser for a while i think this is because the file was cached in my browser and it is loading the previous version since i am testing i need to figure out how to thisable this because i will be changing the files oftentried searching for this on the web but could not really find what i was looking fori am running this on localhost currently but the changing file is just htmlediti know it is not a problem with my files because if i open it in a new browser it loads the new version of the page i am trying to use chrome to do my testing edit2also the file being changed is loaded through requirejs so it is not the direct file entered in the url,['html'] +398799,detect support for backgroundattachment fixed is there a way to detect browser support for backgroundattachment fixededit although this feature is widely supported on desktop browsers it is poorly supported on portable devices which i why i would like to be able to detect the feature,"['javascript', 'jquery', 'css']" +398810,pygame installation for python 33 i am trying to import pygame to use for my version of python 33 the downloads on the pygame website only have python 31 and 32 i cannot seem to be able to import pygame though i thought i had it installed in the correct path i have tried both the 31 and 32 pygame downloadsis pygame just not installed in the correct file path or is pygame not compatible with my version of python 33i am running windows 7 and here is the errortraceback most recent call lastfile pyshell3 line 1 in moduleimport pygamefile pygame init py line 95 in modulefrom pygamebase import importerror dll load failed the specified module could not be found,['python'] +398816,which aspnet lifecycle events can be async i have written a custom aspnet control and i just updated it to have an async load event handler now i am getting this erroran asynchronous operation cannot be started at this time asynchronous operations may only be started within an asynchronous handler or module or during certain events in the page lifecycle if this exception occurred while executing a page ensure that the page is marked page asynctrue the page does have the page asynctrue tag already so i take it that controls cannot have async load event handlers where can i find a comprehensive list of events in the aspnet webforms lifecycle that are allowed to be async,['asp.net'] +398817,using apache httpclient how to set cookie for http request i am trying to set abc123 cookie before sending http request in the response i am expecting the same cookie to be sent back but in the response i get abc890 where the value is set by the target server defaulthttpclient httpclient new defaulthttpclient cookiestore cookiestore httpclientgetcookiestore basicclientcookie cookie new basicclientcookieabc 123 prepare a request object httpget httpget new httpget cookiestoreaddcookiecookie httpclientsetcookiestorecookiestore execute the request httpresponse response httpclientexecutehttpget examine the response status loginfohttp request response is responsegetstatusline listcookie cookies cookiestoregetcookies for int i0 icookiessizei if cookiesgetigetnametostringequalsabc loginfocookie is cookiesget0getvaluetostring thanks,['java'] +398826,quality of image after resize very low java in the script it is going from around the 300x300 mark down to 60x60 need to improve the overall image quality as it is coming out very poorly at the momentpublic static boolean resizeimagestring sourceimg string destimg integer width integer height integer whitespaceamount bufferedimage origimage try origimage imageioreadnew filesourceimg int type origimagegettype 0 bufferedimagetype int argb origimagegettype int fheight height int fwidth width int whitespace height whitespaceamount formatting all to squares so do not need two whitespace calcs double aspectratio work out the resized dimensions if origimagegetheight origimagegetwidth if the pictures height is greater than the width then scale appropriately fheight height set the height to 60 as it is the biggest side aspectratio doubleorigimagegetwidth doubleorigimagegetheight get the aspect ratio of the picture fwidth intmathroundwidth aspectratio sets the width as created via the aspect ratio else if origimagegetheight origimagegetwidth if the pictures width is greater than the height scale appropriately fwidth width set the height to 60 as it is the biggest side aspectratio doubleorigimagegetheight doubleorigimagegetwidth get the aspect ratio of the picture fheight intmathroundheight aspectratio sets the height as created via the aspect ratio int extraheight whitespace fheight int extrawidth whitespace fwidth bufferedimage resizedimage new bufferedimagewhitespace whitespace type graphics2d g resizedimagecreategraphics gsetcolorcolorwhite gfillrect0 0 whitespace whitespace gsetcompositealphacompositesrc gsetrenderinghintrenderinghintskey interpolation renderinghintsvalue interpolation bilinear gsetrenderinghintrenderinghintskey rendering renderinghintsvalue render quality gsetrenderinghintrenderinghintskey antialiasing renderinghintsvalue antialias on gdrawimageorigimage extrawidth2 extraheight2 fwidth fheight null gthispose imageiowriteresizedimage jpg new filedestimg catch ioexception ex return false return truereally just need to know if their is something i can plug in that will bump up the quality or if i need to look at something else entirelyedit picture comparisonsource just picked a random washing machine from googlethe same picture converted in photoshop to what i need it to bewhat it looks like being converted like this,['java'] +398828,clojure performance really bad on simple loop versus java spoiler alert this is problem 5 of project euleri am attempting to learn clojure and solved problem 5 but it is a couple orders of magnitude slower 1515 ms in java versus 169932 ms in clojure i even tried using type hinting unchecked math operations and inlining functions all for naughtwhy is my clojure code so much slowerclojure codeset uncheckedmath truedefn divides long number long divisor zero mod number divisordefn hasalldivisors divisors long num if every fn i divides num i divisors num falsetime prn some fn long i hasalldivisors range 2 20 i iterate inc 1java codepublic class problem5 public static void mainstring args long start systemcurrenttimemillis int i 1 whilehasalldivisorsi 2 20 i long end systemcurrenttimemillis systemoutprintlni systemoutprintlnelapsed time end start public static boolean hasalldivisorsint num int startdivisor int stopdivisor forint divisorstartdivisor divisorstopdivisor divisor ifdividesnum divisor return false return true public static boolean dividesint num int divisor return num divisor 0,['java'] +398841,how to force gcc to link an unused static library i have a program and a static library maincppint main mylibcppinclude iostreamstruct s s stdcout hello worldns si want to link the static library libmyliba to the program object maino although the latter does not use any symbol of the former directlythe following commands do not seem to the job with g 47 they will run without any errors or warnings but apparently libmyliba will not be linkedg o program maino wlnoasneeded pathtolibmylibaorg o program maino lpathto wlnoasneeded lmylibdo you have any better ideas,"['c++', 'c']" +398848,how to use jnlp to pass command line arguments to the application i have a jnlp package for my applicationnow i have the need to pass command line arguments to my applicationhow do i extend my jnlp file to list the command line argumentsfor instance i need to say java mainclass arg1 arg2 and the arg1 and arg2 need to be mentioned as part of jnlp file,['java'] +398912,how to create a menu instance programmatically ie inflate a menu outside oncreateoptionsmenu i want to inflate a menu object outside oncreateoptionsmenu method which means to createshow the menu when the user does not press the button so i need to create a menu instance to pass it to the inflate methodhere is an example of what i am trying to achievemenu menu how to create an instance new menuinflatercontextinflatermenumy menu menumenu is an interface so i need to know which class is implementing it i did browse android code to get any hint on how a menu object is created but still could not find what i am looking foredit 1my goal is to fire an onoptionsitemselectedmenuitem item event from a custom view which will be handled by the activity so i need to have a menuitem object with specific itemid and title to pass it with the eventif i can successfully create a menu object it will be easy to get its children menuitemsedit 2i am not trying to thisplay a menu at all what i want is to populate a listview with elements defined in a menu xml that have title icon and itemid and whenever a listviewitem is clicked i want to fire a onoptionsitemselectedmenuitem item event that is handled in my activityi know that i can parse the menu xml to extract items information however i will not be able to fire onoptionsitemselectedmenuitem item without creating a standard menuitem object to pass it as argument any help will be appreciated thanks,['android'] +398932,changing images depending on device orientation i am building a basic web app using phonegap for a local company i have created two images for the headerbanner at the top of the app one is optimised for portrait orientation and one is optimised for landscapei want to be able to show either one depending which way the device is held i have been reading about media queries and frankly its a little bit over complicated for my needs as jquery mobile will take care of rest of the functionality for me and i am only using one css for the whole appdoes anyone have a few simple lines of code i can add to help solve this issue,['css'] +398979,what open source c library can readwrite micro qr codes i am looking for a c library to generate and read micro qr codes example below it would be great if the llibrary could recognise a micro qr code in an image with other things in it ie isolate and read the qr code,"['c#', '.net']" +399052,updated android facebook api 30 error cannot call loginactivity with a null calling package i am trying to integrate an android app with the the new facebook 30 api but i get this exceptionjavalangruntimeexception unable to resume activity dkimukonnektcomfacebookloginactivity comfacebookfacebookexception cannot call loginactivity with a null calling package this can occur if the launchmode of the caller is singleinstancei have search for this error but no one else seems to have had any troble with it i guess it is because i am using a tabhost and tabsgroupactivities for each tab but i have no clue on how to solve it i have added the relevant code herepublic class maintabactivity extends tabactivity public void oncreatebundle savedinstantestate superoncreatesavedinstantestate setcontentviewrlayouttab layout tabhost tabhost gettabhost view sharetab getlayoutinflaterinflaterlayoutshare tab null tabhostaddtabtabhostnewtabspecsharesetindicatorsharetab setcontentnew intentmaintabactivitythis sharegroupactivityclass public class sharegroupactivity extends tabsgroupactivity override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate startchildactivityshareactivity new intentthis shareactivityclass public class shareactivity extends baseactivity override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutshare testfacebookconnection public void testfacebookconnection session session new sessionthis sessionsetactivesessionsession sessionstate state sessiongetstate settingsaddloggingbehaviorloggingbehaviorinclude access tokens sessionstatuscallback statuscallback new sessionstatuscallback override public void callsession session sessionstate state exception exception toastmaketextshareactivitythis facebook session status changed toastlength shortshow if sessionisopened sessionisclosed sessiongetstate sessionstateopening openrequest open new openrequestthissetcallbackstatuscallback liststring permission new arrayliststring permissionaddpublish actions opensetpermissionspermission sessionopenforpublishopen else sessionopenactivesessionthis true statuscallback override public void onactivityresultint requestcode int resultcode intent data superonactivityresultrequestcode resultcode data sessiongetactivesessiononactivityresultthis requestcode resultcode data any clue on how to solve itupdate 1 stack tracefatal exception main javalangruntimeexception unable to resume activity dkimukonnektcomfacebookloginactivity comfacebookfacebookexception cannot call loginactivity with a null calling package this can occur if the launchmode of the caller is singleinstance at androidappactivitythreadperformresumeactivityactivitythreadjava2812 at androidappactivitythreadhandleresumeactivityactivitythreadjava2851 at androidappactivitythreadhandlelaunchactivityactivitythreadjava2234 at androidappactivitythreadaccess600activitythreadjava139 at androidappactivitythreadhhandlemessageactivitythreadjava1261 at androidoshandlerthispatchmessagehandlerjava99 androidoslooperlooplooperjava154 at androidappactivitythreadmainactivitythreadjava4945 at javalangreflectmethodinvokenativenative method at javalangreflectmethodinvokemethodjava511 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava784 at comandroidinternaloszygoteinitmainzygoteinitjava551 at dalviksystemnativestartmainnative method caused by comfacebookfacebookexception cannot call loginactivity with a null calling package this can occur if the launchmode of the caller is singleinstance at comfacebookloginactivityonresumeloginactivityjava110 at androidappinstrumentationcallactivityonresumeinstrumentationjava1236 at androidappactivityperformresumeactivityjava4613 at androidappactivitythreadperformresumeactivityactivitythreadjava2796 12 moreupdate 2i looked through the code and found the implementation of startchildactivitypublic void startchildactivitystring id intent intent window window getlocalactivitymanagerstartactivityidintentaddflagsintentflag activity clear top if window null midlistaddid setcontentviewwindowgetdecorview it uses the flag flag activity clear top i tried to remove it but no change in the outcomeupdate 3the facebook code uses callingpackage getcallingpackageand if callingpackage null throw new facebookexceptionnull calling pkg error msgthis method has a note if the calling activity is not expecting a result that is it did not use the startactivityforresultintent int form that includes a request code then the calling package will be nullin the method startchildactivity i use the getlocalactivitymanagerstartactivity in tabsgroupactivity that extends activitygroup to handle tab activitiesjavalangstring androidcontentintentthis method does not what the notes says it does not expect a result and does not use the startactivityforresult method the method also ensures something similar to singleinstance launchmodehow should i change this method implementation so it can work with facebook,['android'] +399095,how to see what is returned when a remote script is blocked i am using google hosted jquery in my webapp ajaxgoogleapiscomajaxlibsjquery183jqueryminjs as part of bug diagnostics i have a windowonerror handler which catches any errors i am not catching locally and lets the server know about them so far so good but sometimes i get errors like these script errorerror loading scriptunexpected token my assumption is that the google cdn is blocked in these cases for whatever reason i do have a local fallback for jquery that i am fairly sure is working well but i would like to find out whats being returned so that i can test my assumptions and maybe get some of these users on a white list for google cdn if it is company firewall blocking itbut so far i have not been able to figure out how to retrieve the returned content cannot retrieve innertext of a script tag if it is a file cannot do an ajax request because of crossdomain policy etc does anyone have any ideas about how this would be possible,"['javascript', 'jquery']" +399108,dynatree ignores select property when using ajax i am using the dynatree plugin to thisplay a checkbox tree using multiselect mode mode 3 when the tree is initialized using ajax no lazy loading it seems to forget that some nodes are loaded initially selected when i select one of these nodes the value of the flag passed into the onselect handler is true ie it thinks i want to select the node when i click the checkbox again it deselects it seems that in the background the selection is not registered until i physically click the checkbox i want to load the tree with this node already selectedthe json that i am using to load the tree looks fine to me the select property is true for the node in question the root node here is a snippet of the jsonexpandtruetitleallisfolderfalsekey0islazyfalseaddclassnullselecttrueunselectablefalsechildren omitted for clarityupdatei am loading the tree this waylocationstreedynatree checkbox true selectmode 3 initajax type post url dynatreeiniturl classnames nodeicon where dynatreeiniturl is the url that returns the jsonif i hardcode the json like solocationstreedynatree checkbox true selectmode 3 children expandtrue titleall isfolderfalse key0 islazyfalse addclassnull selecttrue unselectablefalse children expand true title child isfolder false key 1 islazy false addclass null select true unselectable true children classnames nodeicon it works updatei thiscovered why this is happening it is a bug in dynatree or maybe intended behaviour where it is trying to be too cleverif the child node has unselectable true the parent will be unselected when the child is loaded even if the parent has select true this makes it impossible create a tree where the selection is hierarchical ie to have it so that if parent is selected all children are automatically selected and cannot be unselected i suppose this could be added to dynatree as another mode,"['javascript', 'jquery']" +399124,get visible height of an element instead of its actual height with jquery this post is related to this oneplease consider reading it as well in the post i linked to i figured the solution to my problem would be to change the target of a link if the visible height of a div is greater than that of another div in my layout all the divs i am referring to have a height of 1100px but that is not what i want to get i would like the script to get height of the div that is currently visible to the visitor not its real height is there a way to do it using jquerythanks in advance,"['jquery', 'html']" +399134,print help for both normal and positional args with boostprogram options when you use boost library program options it is very easy to print help for your programboostprogram optionsvariables map optionsboostprogram optionsoptions description optionsdescboostprogram optionspositional options description positionaloptionsdescifoptionscounthelp cerr optionsdesc endlbut how do you add the options from positional options description to the help message in the tutorial i can see the output of such setup at the end of the section 52 0dochtmlprogram optionstutorialhtmlid2607297the option inputfile is printed in help and it is positional but i cannot see the codeis there an buildin way to print it like with options description or you have to do it manually apparently the does not work for positional options description the compilation error iserror cannot bind astdostream aka stdbasic ostreamchara lvalue to astdbasic ostreamchara,['c++'] +399159,why bootstrap uses floats on span instead of thisplay inlineblock i was tinkering with custom grid and wanted to see how other people have created their gridsystems since twitters bootstrap seemed to be so popular i have looked at its code now i wonder why are they using floats i would use thisplay inlineblock html elements have either thisplay inline or thisplay block i would try to avoid floats but for some reason bootstrap creators decided to use floats first i was thinking they used them to have backward compatibility since ie6 does not support thisplay inlineblock and ie7 supports it only on elements with thisplay inline by default but ie6 more or less out of the game and since they use micro clearfix hack which uses zoom 1 to target ie6 imo they could replicate the same thisplay inlineblock with thisplay inline zoom 1 so the final question why floats over thisplay inline block are there any issues they tried to solve i did not mentioned above,['css'] +399179,change background of edittexts error message what i want to do is change the background color set custom drawable of a popup error message thisplayed after using seterror methodcurrently it looks like thisi have found that android has two filespopup inline error9pngpopup inline above error9pngand youre supposed to be able to set them using two attributeserrormessagebackgrounderrormessageabovebackgroundbut when i try to set them in my theme all i get isitem nameerrormessagebackgrounddrawablepopup inline error holo lightitemitem nameerrormessageabovebackgrounddrawablepopup inline error above holo lightitemerror error no resource found that matches the given name attr errormessagebackgroundit is the same with androiderrormessagebackgroundi am putting this question here cause i have run out of ideas maybe someone already managed to do thateditheader of the theme i am usingresources xmlnsandroid style namethememythemename parentstylethemesherlocklightanother edituh i have found that my question is a duplicate ofandroiderrormessagebackground getting no resource found error in stylesxmlyet another editthis is a known problem take a look at this link,['android'] +399192,sharedpreferences reads old values i use sharedpreferences to write and later read values within different activities in my applicationit used to work ok but lately it seems like it if was not sincronized i mean i write a value but then the other activity still reads the old valuesometimes it works correclyany ideaeditthis is a sample codefirst from a threadsharedpreferences prefs getsharedpreferencesmyprefs contextmode privatesharedpreferenceseditor editor prefsediteditorputintcomandtodo valueeditorcommit some code lateralarmmanagersetalarmmanagerrtc wakeup miliseconds senderin the alarm receiversharedpreferences prefs contextogetsharedpreferencesmyprefs contextmode privateint value prefsgetintcomandtodo 1 and here comes the problem because value is not the value written in the thread,['android'] +399198,killing child process when parent crashes in python i am trying to write a python program to test a server written in c the python program launches the compiled server using the subprocess modulepid subprocesspopenargsserver file pathpidthis works fine however if the python program terminates unexpectedly due to an error the spawned process is left running i need a way to ensure that if the python program exits unexpectedly the server process is killed as well some more detailslinux or osx operating systems onlyserver code can not be modified in any way,['python'] +399261,how do you change the reset password url in meteor i am using meteor along with the accountspassword package i am rolling my own login and password changingresetting ui and want to knowhow can i customize the password reset link in the reset password email sent as a result of accountsresetpasswordcurrently it in the form like so resetpasswordid since i am using meteor router i would like to send in the form resetpasswordidso i can catch it with the route resetpasswordid,['javascript'] +399275,php undefined index http user agent the following code validates the user agent accessing the site however i am getting the error what do i need to update to accommodate scenarios where there is no user agent being seterrorphp notice undefined index http user agent in utilsphp on line 7codepublic static function detectbrowser useragent strtolower serverhttp user agent if preg matchopera useragent name opera elseif preg matchwebkit useragent name safari elseif preg matchmsie useragent name msie elseif preg matchmozilla useragent preg matchcompatible useragent name mozilla else name unrecognized if preg matchrvitraie d useragent matches version matches1 else version unknown if preg matchlinux useragent platform linux elseif preg matchmacintoshmac os x useragent platform mac elseif preg matchwindowswin32 useragent platform windows else platform unrecognized return array name name version version platform platform useragent useragent,['php'] +399339,finding coordinate of sketch image eg scanned as photo format in r or other software i want to redraw any sketch within r with polygon but i need a painstaking work to find coordinates x or y values for each pointsis there any r package or other software that can find coordinates from an image thus output will be data with considerably high number of points xy so that the figure can be recreated edits here are examples1 map outline for examplesecond example2 object shape example,['java'] +399355,how to read uwsgi parameters in pythonflask passed from nginx i set up pythonflaskuwsginginx web app and it works fine i want to use geoip i set it up on nginx side location include uwsgi params uwsgi pass unixtmpqbackavisitsock uwsgi param geoip country code geoip country code but now i do not know how to read this property in python prior to uwsgi i used simple flask builtin webserver nginx proxy pass in which case i used proxy set header xgeocountry geoip country code and read this argument using requestheaders but for uwsgi params i could not figure out how to read them,['python'] +399366,explode a string to associative array i have a string like 1350939099 and i need to turn it into an associative array like this array 1 350 9 39099 is it possible to do this using only array functions with no loops,['php'] +399375,implementing first fit like algorithm problemi have 3 machines each machine have a limit of 30 ms time each machine have 3 zones that a task cannot be executed there the tasks have a p priority and w weight which is the time to complete the task in this setup tasks must be first ordered by a priority from lower to higher like thistask 01 6 2 pw 3 this task executed last 3task 02 7 7 pw 1 this task executed first 1task 03 4 2 pw 2 this task executed second 2now in order to execute a tasksi have 6 i must check all 3 machines to find the first fit to the task to chose a fit for task it must be the optimal in the 3 machines examplemachine 01 5916171920machine 02 45781718machine 03 58101315181task 02 executed in machine 02 we look for p ms to execute task and the minimum time to start a task since both machine 01 starting from 9 ms and 02 starting from 8 ms have a 7 ms free time machine 02 can start a task first then the machine 012task 03 executed in machine 02 we look for p ms to execute task3task 01 executed in machine 01 we look for p ms to execute taskcertain periods of time are defined as critical and cannot be used to schedule a job these periods for instance 59 78 are stored in the dedicated struct z inthispothe bfeet struct is used to store in witch the task start and in witch machinei implemented mostly the entire algorithm in c but my results are different than expectedinclude stdiohtypedef struct z inthispo int t1 int t2 z inthispo typedef struct machines int t20 array represent time z inthispo zone2 machinestypedef struct tache int p int w int c pw int i task number tachetypedef struct bfeet int t store the time to of ending execution by a task int m the machine responsible for executing a task bfeetint mainint argc char argv machines m4 tache j6 tache j tmp bfeet b4 int i 0 int and 0 int you 0 int k 0 int count 0 int trouver 0 int f totale 0 int f3 0 m0zone0t1 7 m0zone0t2 9 m0zone1t1 14 m0zone1t2 15 m1zone0t1 8 m1zone0t2 9 m1zone1t1 16 m1zone1t2 17 m2zone0t1 7 m2zone0t2 8 m2zone1t1 18 m2zone1t2 19 initialise all machines 0 represent free time 1 represent critical zone range 2 represent a task already executed fori 0 i 3 i forcount 0 count 20 count ifcount mizone0t1 1 count mizone0t2 1 count mizone1t1 1 count mizone1t2 1 mitcount 1 else mitcount 0 fori 0 i 3 i ifi 0 printf d11 t1 s1 d12 t2 s2 d13n else ifi 1 printf d21 t1 s1 d22 t2 s2 d23n else ifi 2 printf d31 t1 s1 d32 t2 s2 d33n printf forcount 0 count 20 count printf3d mitcount printf nn j0p 5 j0w 2 j0i 1 j1p 9 j1w 3 j1i 2 j2p 6 j2w 3 j2i 3 j3p 6 j3w 4 j3i 4 j4p 7 j4w 7 j4i 5 calc c pw forcount 0 count 5 count jcountc jcountp jcountw sort tasks from low to hight forcount 0 count 5 count fork 0 k 5 count k ifjkc jk 1c j tmp jk 1 jk 1 jk jk j tmp printf2j 2 p 2 w c n printf n forcount 0 count 5 count printf4d4d4d4dn jcounti jcountp jcountw jcountc printfn execute tasks whilen 5 forcount 0 count 3 count i 0 trouver 0 whilei 20 trouver 1 ifmcountti 0 we have a free time to start with it you 0 num of available indexs whilemcountti 1 mcountti 2 ifu jnp break u i ifu jnp whilemcountti 1 mcountti 2 bypass unfree unites i else ifu jnp bcountt i u bcountm count trouver 1 we find the necessary unites to start a task else i ifu jnp printfthere is no free time to execute task d jni else find the minimum time in all machines to start a task b3t b0t b3m b0m forcount 0 count 3 count ifb3t bcount 1t b3t bcount 1t b3m bcount 1m put 2 to indicate that index is unfree you b3t jnp forcount b3t count u count mb3mtcount 2 ifb3m 0 f0 b3t jnp else ifb3m 1 f1 b3t jnp else ifb3m 2 f2 b3t jnp printftask d end at 2d machine dn jni b3t jnp b3m 1 n printfn f totale f0 f1 f2 printff of machine 01 dn f0 printff of machine 02 dn f1 printff of machine 03 dn f2 printftotal f dn f totale printfn printfn fori 0 i 3 i ifi 0 printf d11 t1 s1 d12 t2 s2 d13n else ifi 1 printf d21 t1 s1 d22 t2 s2 d23n else ifi 2 printf d31 t1 s1 d32 t2 s2 d33n printf forcount 0 count 20 count printf3d mitcount printf nn return 0updatei have now only two unavailability zones in each machine i also updated the code to fix some errors but i still get a different output then this examplei have this unavailability zonesm0zone0t1 7m0zone0t2 9m0zone1t1 14m0zone1t2 15m1zone0t1 8m1zone0t2 9m1zone1t1 16m1zone1t2 17m2zone0t1 7m2zone0t2 8m2zone1t1 18m2zone1t2 19 5 tasksp 6 9 5 7 6w 3 3 2 7 4 c 2 3 2 1 1after ordering by cp 7 6 5 6 9w 7 4 2 3 3 c 1 1 2 2 3the execution of tasks should be like this j4 7 9 14 15 mstask 04 should end at 7 p represent the time necessary to execute a task j5 8 9 16 17 mstask 05 should end at 7 j1 j3 7 8 18 19 mstask 01 should end at 6 task 03 should end at 14update 02 this problem fixedi noticed a strange behavior in my program after i initializing mitcount array i found that variables responsible for storing unavailability zones changed note this problem fixedupdate03 this problem fixed but with new issuei have situation when a task cannot find the necessary unites to start i never get this message there is no free time to execute task witch i should receive it for task 2 since it has 9 unites and all machines have no such of free time like that the code responsible for this test forcount 0 count 3 count search on all machines i 0 trouver 0 whilei 20 trouver 1 ifmcountti 0 we have a free time to start with it you 0 num of available indexs whilemcountti 1 mcountti 2 ifu jnp break u i ifu jnp whilemcountti 1 mcountti 2 bypass unfree unites i else ifu jnp bcountt i u bcountm count trouver 1 we find the necessary unites to start a task else i you represent the number of continuous free time jnp represent the necessary time to execute the current task and is the current task ifu jnp printfthere is no free time to execute task d jni else find the minimum time in all machines to start a task b3t b0t b3m b0mupdate04now i can see excluded task when there is no free time to execute a task however the output is not right because i see a task override the period time on another taskwhilen 5 k 0 forcount 0 count 3 count i 0 you 0 trouver 0 whilei 20 trouver 1 ifmcountti 0 we have a free time to start with it u 0 num of available indexs ifu jnp break else u i ifu jnp ifmcountti 1 mcountti 2 bypass unfree unites you 0 i ifu jnp k bcountt i u bcountm count trouver 1 we find the necessary unites to start a task ifu jnp printfthere is no free time to execute task dn jnielse find the minimum time in all machines to start a task b3 b0 forcount 0 count 3 count ifbcountt 0 ifb3t bcount 1t b3 bcount 1 put 2 to indicate that index is unfree you b3t jnp forcount b3t count u count mb3mtcount 2 ifb3m 0 f0 b3t jnp else ifb3m 1 f1 b3t jnp else ifb3m 2 f2 b3t jnp printftask d end at 2d machine dn jni b3t jnp b3m 1n output d11 t1 s1 d12 t2 s2 d13 0 0 0 0 0 0 1 1 1 0 0 0 0 1 1 0 0 0 0 0 d21 t1 s1 d22 t2 s2 d23 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 1 1 0 0 0 d31 t1 s1 d32 t2 s2 d33 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 1 1 0 j p w c 1 5 2 2 2 7 3 2 3 8 3 2 5 17 7 2 4 16 4 4 task 1 end at 5 machine 1task 2 end at 7 machine 1task 3 end at 8 machine 1there is no free time to execute task 5there is no free time to execute task 4f of machine 01 8f of machine 02 0f of machine 03 0total f 8 d11 t1 s1 d12 t2 s2 d13 2 2 2 2 2 2 2 2 1 0 0 0 0 1 1 0 0 0 0 0 d21 t1 s1 d22 t2 s2 d23 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 1 1 0 0 0 d31 t1 s1 d32 t2 s2 d33 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 1 1 0,['c'] +399376,how to create data channel in webrtc peer connection i am trying to learn how to create an rtcpeerconnection so that i can use the datachannel api heres what i have tried from what i understoodvar client new mozrtcpeerconnectionvar server new mozrtcpeerconnectionclientcreateofferfunction description clientsetlocaldescriptiondescription serversetremotedescriptiondescription servercreateanswerfunction description serversetlocaldescriptiondescription clientsetremotedescriptiondescription var clientchannel clientcreatedatachannelchat var serverchannel servercreatedatachannelchat clientchannelonmessage serverchannelonmessage onmessage clientchannelsendhello server serverchannelsendhello client function onmessageevent alerteventdata i am not sure whats going wrong but i am assuming that the connection is never established because no messages are being thisplayedwhere do i learn more about this i have already read the getting started with webrtc html5 rocks tutorial,['javascript'] +399415,is there any referenceresource about how to design the structure of a data file possible duplicatewhat are important points when designing a binary file format i am going to develop a program which will store data in filethe file can be big the data in the file is basically made up with variable length records and i need random access to the recordsi just want to read some resoucesbooks about how to design the structure of a data file but i cannot find any yetany suggestion is much appreciated,"['c++', 'c']" +399426,how do i best represent a onetomany relationship where one child is a special case i have a schema with a parentchild relationship between two entities it is a onetomany so would naturally be implemented astable parents idtable children id parent idhowever i also need to treat one of the children as a special case let us call it the promoted child i can think of several ways to do this includingjust put an attribute on childrentable parents idtable children id parent id is promotedwhich is obviously flawed in that the database cannot guarantee consistency at least not through regular foreign key constraintscreate a foreignkey on the parents tabletable parents id promoted child idtable children id parent idwhich was my first inclination but it does have the obvious downside of a cyclic dependency so probably not optimalanother option i can think of is to put a second foreignkey on the children tabletable parents idtable children id parent id promoted parent idwhich allows me to place a unique index thereby enforcing database consistency one problem with this is that it would be possible to have a meaningless relationship where a child of parent a lists as promoted of parent bthe last option i can think of is to create an intermediary table egtable parents idtable children idtable parentchildrelationship parent id child id is promotedagain i can declare a unique constraint on parent idis promoted enforcing consistency i am a bit ambivalent on this one since it seems like overkill to promote the relationship to a full entity although the moment i put attributes on it which essentially is promoted is i guess it is warrantedi would like to know what you would consider the canonical way to handle this problem in particular i am using rails so that may influence on what is the most practical solution,['ruby-on-rails'] +399461,azure service bus peeklock is timing out after just five seconds i am building a message queue on azure using service bus working through the php sdk and am having some problems with peeklock messages timing out too quickly i can connect to the queue and retrieve a message using peeklock however if i take longer than five seconds to delete the message azure throws a 404 error indicating that the lock has expired and the message is put back into the queue as though it had never been processed heres an example of some test code i have used assume in this example that the azure sdk is loaded and the appropriate namespaces have been referencedphp load the sdk and namespaces etc service bus servicesbuildergetinstancecreateservicebusserviceconnection string goes here options new receivemessageoptions optionssetpeeklock message service busreceivequeuemessagequeue name here options print message body is messagegetbody service busdeletemessagemessagethis code executes perfectly the message is retrieved the body is thisplayed and the message is deleted however if i insert a sleep5 just before the deletemessage call the service bus api returns the following errorerror the lock supplied is invalid either the lock expired or the message has already been removed from the queuewhen creating the queue via the azure portal i explicitly set the lock timeout period to five minutes and i have experimented with setting different timeout periods on other queues and all of them still revert to a five second expiry what am i doing wrong hereissue resolvedi got a reply from the azure support team who quickly figured out that the azure portal is not persisting the lock duration that is selected when creating a queue the default expiry is apparently five seconds although i could not find any references to this default value in any of the docs which is annoying which is why it was timing outso anyway the dev team are apparently working on a fix and everything should be working soon,['php'] +399463,actionbar menu items thisappear in nestedfragments since android 42 now support nestedfragment and added it to support v13i use this nestedfragment on a classic situation create fragmenta that can swipe left and right and consume a majority of the screen space and insert fragmentb and fragmentc into each fragment pagemy problem is the menuitem i create in fragmentb and fragmentc cant show on activitys actionbarwhich before i use nestedfragment it works well,['android'] +399483,notifydatasetchanged fails to update listview i have a dialogfragment which has a list view with checkedtextview and a checkbox at the top to check and uncheck all the items in the list view i am trying to set the state of the checkedtextview to checkedunchecked depending on the state of the checkall check box but i am not able to update the view accordingly using notifydatasetchangedcategoriesdialogfragmentjavapublic class categoriesdialogfragment extends sherlockdialogfragment checkbox checkall listview categorieslistview categorieslistadapter adapter static category category string categories new string hill station beach historic wild life waterfall river archeology hill station beach historic wild life waterfall river archeology boolean categories state new boolean true false true true true true false true false true true true true false public static categoriesdialogfragment newinstance categoriesdialogfragment frag new categoriesdialogfragment bundle args new bundle fragsetargumentsargs return frag override public dialog oncreatedialogbundle savedinstancestate final dialog dialog new dialogmainactivitycontext dialogrequestwindowfeaturewindowfeature no title dialogsetcontentviewrlayoutdialog categories categorieslistview listview dialog findviewbyidridlistviewdialog listcategory thecategories new arraylistcategory for int i 0 i categorieslength i boolean flag category pl new categorycategoriesi categories statei thecategoriesaddpl categorieslistviewsetchoicemodelistviewchoice mode multiple adapter new categorieslistadaptermainactivitycontext rlayoutdialog list item category thecategories categorieslistviewsetadapteradapter list view item click listener categorieslistview setonitemclicklistenernew adapterviewonitemclicklistener override public void onitemclickadapterview parent view view int position long id todo autogenerated method stub categorieslistadapter adapter categorieslistadapter parent getadapter category c category adaptergetitemposition csetcheckedcgetchecked adapternotifydatasetchanged checkall checkbox checkall checkbox dialogfindviewbyidridcheckboxall checkallsetoncheckedchangelistenernew compoundbuttononcheckedchangelistener override public void oncheckedchangedcompoundbutton buttonview boolean ischecked toastmaketextmainactivitycontext check toastlength shortshow for int i 0 i adaptergetcount i categorieslistviewsetitemcheckedi ischecked loginomad ischecked ischecked i adapternotifydatasetchanged if ischecked loginomad ischecked for int i 0 i adaptergetcount i category adaptergetitemi categorysetcheckedtrue loginomad ischecked i adapternotifydatasetchanged else loginomad isunchecked for int i 0 i adaptergetcount i category adaptergetitemi categorysetcheckedfalse loginomad isunchecked i adapternotifydatasetchanged return dialog private static class categorieslistadapter extends arrayadaptercategory public context mcontext listcategory mcategories public categorieslistadaptercontext context int resource listcategory categories supercontext resource categories todo autogenerated constructor stub thismcategories categories thismcontext context public int getcount return mcategoriessize override public category getitemint position todo autogenerated method stub return mcategoriesgetposition override public long getitemidint position return position override public view getviewint position view convertview viewgroup parent viewholder holder if convertview null layoutinflater viewinflater viewinflater layoutinflaterfromgetcontext convertview viewinflaterinflate rlayoutdialog list item category null holder new viewholder holdercategoryname checkedtextview convertview findviewbyidridcategories checkbox convertviewsettagholder else holder viewholder convertviewgettag holdercategorynamesettextmcategoriesgetposition getcategoryname holdercategorynamesetcheckedmcategoriesgetposition getchecked return convertview static class viewholder checkedtextview categoryname categoryjavapublic class category string categoryname private boolean checked false public categorystring categoryname boolean checked thiscategoryname categoryname thischecked checked public string getcategoryname return categoryname public void setcategorynamestring categoryname thiscategoryname categoryname public boolean getchecked return checked public void setcheckedboolean checked thischecked checked dialog categoriesxmlxml version10 encodingutf8linearlayout xmlnsandroid androidididparentpanel androidlayout widthmatch parent androidlayout heightwrap content androidlayout marginend8dip androidlayout marginstart8dip androidbackgroundcolorprimary white androidorientationvertical linearlayout androidididtitle template androidlayout widthmatch parent androidlayout heightwrap content androidlayout marginend16dip androidlayout marginstart16dip androidgravitycenter verticalstart androidorientationhorizontal androidpaddingtop5dp textview androidididtextview1 styleandroidattrtextappearancelarge androidlayout width0dp androidlayout heightwrap content androidlayout weight1 androidpaddingleft10dp androidtextstringdialog category title androidtextcolorcolorprimary color androidtextsize22sp textview androidididall androidlayout widthwrap content androidlayout heightwrap content androidtextstringdialog category checkbox androidtextcolorcolorprimary color checkbox androidididcheckboxall androidlayout widthwrap content androidlayout heightwrap content androidpaddingright6dp linearlayout view androidididtitledivider androidlayout widthmatch parent androidlayout height2dip androidbackgroundcolorblack linearlayout androidididcontentpanel androidlayout widthmatch parent androidlayout height0dp androidlayout weight1 androidminheight64dp androidorientationvertical listview androidididlistviewdialog androidlayout widthmatch parent androidlayout heightwrap content listview linearlayout linearlayout androidididbuttonpanel androidlayout widthmatch parent androidlayout heightwrap content androidorientationvertical button androidididbutton category ok androidlayout widthfill parent androidlayout heightwrap content androidtextstringdialog category btn ok androidtextsize14sp linearlayoutlinearlayoutdialog list item categoryxmlxml version10 encodingutf8checkedtextview xmlnsandroid androidididcategories checkbox androidlayout widthfill parent androidlayout heightandroidattrlistpreferreditemheight androidcheckmarkandroidattrlistchoiceindicatormultiple androidgravitycenter vertical androidonclicktoggle androidpaddingbottom10dp androidpaddingleft10dp androidpaddingright12dp androidpaddingtop10dp androidtexts,['android'] +399507,secure way to unlock full version via inapp purchase i am planning to use inapp purchases to unlock some features in my appwhat is the most secure way to do thisoriginally i planned to set a bool in the nsuserdefaultsnsuserdefaults standarduserdefaults setboolyes forkeyisprobut i am not really sure whether there is a possibility to set this value via a hack as nsuserdefaults are managed by ios and not directly by the app so that the user does not have to perform the inapp purchase in order to get the full versionwhats the best practice to handle this,['ios'] +399532,css selector for element within element with inline style is there a css selector to target elements with inline styles so can i target the first span but not the 2nd with css only if not can this be done with jquery p styletextalign center spantargetspanpp spannot targetspanpa,"['html', 'css']" +399539,understanding oauth2 client credentials flow i am trying to understand and implement a client credentials flow between our new rest server and our existing client app i have setup springsecurity oauth2 like this from my understanding so far my server should now support the following request curl x v d client idthe clientclient secretsecretgrant typeclient credentials x post httplocalhost9090oauthtokenbut i get insufficientauthenticationexception there is no client authenticationcaused by the principal being null here springsecurity code frameworkendpointrequestmappingvalue oauthtokenpublic class tokenendpoint extends abstractendpoint requestmapping public responseentityoauth2accesstoken getaccesstokenprincipal principal requestparamgrant type string granttype requestparam mapstring string parameters if principal instanceof authentication throw new insufficientauthenticationexceptionso it seems i need to authenticate against the server first but that is not what i want to do i want two of my servers to talk to each other using a shared secret the oauth provider server should provide an access token to the trusted client server on request so that the client server can then use that token to access all rest resources on the server this should protect the rest resources from external access later i want to provide selected resources to a third party and eventually implement some finer grained security for the servertoserver communication as well but for now i need to protect the rest server from external accesslooks like i might have some misunderstandings about the whole client credentials flow or the application of springsecurity right there so any clarification would be greatly appreciated,['java'] +399570,how to generate narcissistic numbers faster the anarcissistic numbersa are and digit numbers where the sum of all the nth power of their digits is equal to the numberso 153 is a narcissistic number because 13 53 33 153now given n find all narcissistic numbers that are and digit length my approach was to iterate over all numbers doing sum of powers of digitsand check if its the same number or not and i per calculated the powersbut that is not good enough so is there any faster way updatein nature there is just 88 narcissistic numbers and the largest is 39 digits longbut i just need the numbers with length 12 or lessmy code long long int powers12 powersxy is xy and its already calculatedbool isnarcissisticlong long int xint n long long int r x long long int sum 0 forint i0 in i sum powersx10n ifsum r return false x 10 return sum rvoid findint nvectorlong long int vv long long int start powers10n1 long long int end powers10n forlong long int istart iend i ifisnarcissisticin vvpush backi,['c++'] +399581,why load staticfiles for every template even if it is extendend i have a basehtml file which has some random html code and i have the following code load staticfiles doctype htmlhtml head block extra js top endblock head htmlin my indexhtml file i extend basehtml and i load some extra javascript files extends basehtml block extra js top script typetextjavascript src static jssomejsjs script endblock the problem is that extra javascript does not load because of the static var it does not load even if i extend basehtml which have the load staticfiles inside the template finally i solved the problem adding one more load staticfiles at indexhtmlmy question is why we should add load staticfiles for every template we use even if we extend a file that has it already,['python'] +399598,celery programmatically list workers how can i programmatically using python code list current workers and their corresponding celeryworkerconsumerconsumer instances,['python'] +399624,compare list of datetimes with datetime in python i have a list of datetime objects and would like to find the ones which are within a certain time frameimport datetimedates datetimedatetime2007 1 2 0 1 datetimedatetime2007 1 3 0 2 datetimedatetime2007 1 4 0 3 datetimedatetime2007 1 5 0 4 datetimedatetime2007 1 6 0 5 datetimedatetime2007 1 7 0 6 in reality this is a list of over 250 datesmask datesdatetimedatetime200713 datesdatetimedatetime200716however this results in the following errortypeerror cannot compare datetimedatetime to listhow can i fix my code,['python'] +399640,java junit test generators i would like to know about good tools to automatically generate junit4 tests by automatic generation i mean that if i write a java file then a test file for the same should be created with method placeholders and setupteardown in place like the autogenerate constructors feature of eclipsei found some but i have not tried them all and frankly i am overwhelmed by the plethora of choices i was wondering if someone has tried someall of them and has any recommendations from these or any other case generationhlhuhu,['java'] +399690,cron job does not output to nohupout i have startsh bash script that is running though cron job on ubuntu server startsh contains bellow mentioned lines of codepath of startsh is homeubuntufolder1folder2startshbinbashcrawlers nohup scrapy crawl first nohup scrapy crawl 2nd wait nohup scrapy crawl 3rd nohup scrapy crawl 4th waitcd homeubuntufolder1folder2pathpathusrlocalbinexport pathpython initpy wait crawlerspython finalpymy issue is if i run startsh my myself on command line it outputs in nohupout file but when it executes this bash file through cronjob although scripts are running fine its not producing nohupout how can i get output of this cronjob in nohupout,['python'] +399734,calling a getter in java though reflection whats the fastest way to repeatedly call it performance and scalability wise given a class foo and a property bar neither of which i know at compile time i need to repeatedly call the getter foogetbar many many timessuppose i havemethod bargettermethod do not worry how i got thisand i need to do something like thisfor object foo foolist 10 elements in foolist object bar bargettermethodinvokefoo the implementation above is still very slow compared to calling it without reflection is there a faster way whats the fastest way of calling a getter with reflection in java,['java'] +399738,how to change the default rails server in rails 3 i am new to rails and i am wondering if there is an option to change the default rails server ie webrick for another one such as puma or thin i know it is possible to specify which server to run with rails server command however i would like to use this command without specify the name of the server so it can run the default rails server is there a way to change the default rails server into a configuration file or something like this thanks in advance for your help,['ruby-on-rails'] +399742,arduino printffprintf prints question mark instead of float i have the following code for an arduino sketchinclude liquidcrystalhliquidcrystal lcd12 11 5 4 3 2static file lcdout 0 static int lcd putcharchar ch file stream lcdwritech return 0 void setup lcdbegin16 2 fdev setup stream lcdout lcd putchar null fdev setup writevoid loop stdout lcdout printf2f volts 20the problem comes at the last line of the code this should print out 200 volts but instead it prints volts a question mark instead of the actual float value if i try to format an integer this works great so basically if i replace the printf line with the following it will work properlyprintfd volts 2 prints correctly 2 voltsany idea whats the problem,['c'] +399756,immutable class vs struct the following are the only ways classes are different from structs in c please correct me if i am wrongclass variables are references while struct variables are values therefore the entire value of struct is copied in assignments and parameter passesclass variables are pointers stored on stack that point to the memory on heap while struct variables are on stored heap as valuessuppose i have an immutable struct that is struct with fields that cannot be modified once initialized each time i pass this struct as a parameter or use in assignments the value would be copied and stored on stackthen suppose i make this immutable struct to be an immutable class the single instance of this class would be created once and only the reference to the class would be copied in assignments and parameter passesif the object was mutable the behavior in these two cases would be different when one would change the object in the first case the copy of the struct would be modified while in the second case the original object would be changed however in both cases the object is immutable therefore there is no difference whether this is actually a class or a struct for the user of this objectsince copying reference is cheaper than copying struct why would one use an immutable structalso since mutable structs are evil it looks like there is no reason to use structs at allwhere am i wrong,['c#'] +399783,line chart using ordinal xaxis with d3js and nvd3js i am trying to make a line chart from a dataset while keeping xaxis categoricalfor the observer it will look like a line chart with equithistant spacing between observations x coordinates 1 5 30 600for now i am getting something like this1530600 this is my datasetvar ds1 key var1 color ff7f0e values x 600 y 007706 x 30 y 0553 x 5 y 0919 x 1 y 0969 i tried to create the ordinal axis and set it in the line chart objectvar chart nvmodelslinechart margintop 10 bottom 40 left 60 right 30 var x d3scaleordinaldomain15 30 600chartxaxisscalexchartyaxis tickformatd3format3fchartforcey0d3selectexampleone datumds1 transitionduration500 callchartnothing seems to be changing on the plot however i was wondering could the ordinal axis be enabled at all in the nvd3 line chart implementation or this line chart was written for numerical data only ps i am new to d3js so i might be doing something wrong here,['javascript'] +399800,incompleteread using httplib i have been having a persistent problem getting an rss feed from a particular website i wound up writing a rather ugly procedure to perform this function but i am curious why this happens and whether any higher level interfaces handle this problem properly this problem is not really a show stopper since i do not need to retrieve the feed very ofteni have read a solution that traps the exception and returns the partial content yet since the incomplete reads differ in the amount of bytes that are actually retrieved i have no certainty that such solution will actually workusrbinenv pythonimport osimport sysimport feedparserfrom mechanize import browserimport requestsimport urllib2from httplib import incompletereadurl id543375guid83d4a09c6b404300a04bf84048d49mode2013titlecityofhattiesburg2cmscalendar2013content feedparserparseurlif bozo exception in content print contentbozo exceptionelse print success sysexit0print if you see this please tell me what happened try using mechanizeb browserr bopenurltry rreadexcept incompleteread e print incompleteread using mechanize e try using urllib2r urllib2urlopenurltry rreadexcept incompleteread e print incompleteread using urllib2 e try using requeststry r requestsrequestget urlexcept incompleteread e print incompleteread using requests e this function is old and i categorized it as at least it works darnnit but i would really like to learn whats happening please help me put this function into eternal restdef get rss feedurl response urllib2urlopenurl read it true content while read it try content responseread1 except incompleteread read it false return content responseinfocontent info get rss feedurlfeed feedparserparsecontentas already stated this is not a mission critical problem yet a curiosity as even though i can expect urllib2 to have this problem i am surprised that this error is encountered in mechanize and requests as well the feedparser module does not even throw an error so checking for errors depends on the presence of a bozo exception keyedit i just wanted to mention that both wget and curl perform the function flawlessly retrieving the full payload correctly every time i have yet to find a pure python method to work excepting my ugly hack and i am very curious to know what is happening on the backend of httplib on a lark i decided to also try this with twill the other day and got the same httplib errorps there is one thing that also strikes me as very odd the incompleteread happens consistently at one of two breakpoints in the payload it seems that feedparser and requests fail after reading 926 bytes yet mechanize and urllib2 fail after reading 1854 bytes this behavior is consistend and i am left without explanation or understanding,['python'] +399801,how to represent bridge table in entity framework code first i am trying to find out how i can represent a bridge table between two entities many to many relationi am using entity framework code firststudent studentid int pk studentname varchar50class classid int pk classname varchar50studentclass studentid int pk classid int pkwhat is the best class structure should i use to represent it in entity framework code first and how can i select from the bridge table and insert in itshould i represent the classes it like this public class student public int studentid get set public string studentname get set public listclass class get set public class class public int classid get set public string classname get set public liststudent students get set,['c#'] +399814,text on image mouseover i am trying to get a small box to appear on the bottomleft side of an image when a mouse moves over it inside the box there will be a link to a different pagehere is somewhat similar to what i want but the box to be smaller and not connected to the border of the imagei have tried everything and cannot find an answer and i do not want to use tooltip let alone the fact that i have no javascript knowledge whatsoever i really want this to be cssalso the images i am trying to work with can be found right here,['css'] +399823,how do i force a signcharacter on the output of an nsnumberformatter i want to use a number formatter to generate my output so the number is automatically formatted for the users locale but i want it to work like 1f does in printf that is always have a sign specified nsnumberformatter nf nsnumberformatter alloc initnfnumberstyle nsnumberformatterdecimalstylenfmaximumfractiondigits 1double val 31234labeltext nsstring stringwithformat x x nf stringfromnumber nsnumber numberwithdouble vali want the label to come out x 31 x in the us and the appropriate but equivalent string for any other location the only things i can find are setpositiveformat and setpositiveprefixbut i do not want to set the format since i do not know how to format numbers in other countries i do not know if a plussign is used to designate a positive number in arabic or russian or some culture i have not thought of i do know for example that decimal points commas spaces etc all have different meanings in european countries compared to the us could the same be true for signswhat i do currently islabeltext nsstring stringwithformat x s x val 0 nf stringfromnumber nsnumber numberwithdouble valbut this presumes that and are correct for all formatsi am sure it must be there since it is a standard formatting thing that has been in printf since the dark ages,"['objective-c', 'ios']" +399837,android beginner place image at dragevent i realize that similar questions have been posted and i have viewed them and lots of other topics etc to find a solution i am clearly missing the obvious as i am still learning the basicsgoal simple drag and dropuser moves image across screen and either drops on top of another image or anywhere on the screenapi 11completedcan drag the image and place on top of another image and get response using toast to confirmcan drag the image anywhere on screen and get response using toast to confirmnot workingcannot drag image anywhere on screen and deposit image where finger liftedi have tried lots of different methods but always compiling errors looking at my code could anyone recommend a clean and simple method to place a image at action drag ended keep in mind i am a beginner here is my java codepublic class mainactivity extends activity overridepublic boolean oncreateoptionsmenumenu menu inflate the menu this adds items to the action bar if it is present getmenuinflaterinflatermenuactivity main menu return trueboolean oktodrop called when the activity is first created overrideprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main findviewbyidridovalsetontouchlistenernew thetouchlistener findviewbyidridsquaresetontouchlistenernew thetouchlistener findviewbyidridrobotsetontouchlistenernew thetouchlistener findviewbyidridovalsetondraglistenernew thedraglistener findviewbyidridsquaresetondraglistenernew thedraglistener findviewbyidridrobotsetondraglistenernew thedraglistenerprivate final class thetouchlistener implements ontouchlistener public boolean ontouchview view motionevent motionevent if motioneventgetaction motioneventaction down clipdata data clipdatanewplaintext dragshadowbuilder shadowbuilder new viewdragshadowbuilder view viewstartdragdata shadowbuilder view 0 viewsetvisibilityviewvisible return true else return false class thedraglistener implements ondraglistener override public boolean ondragview view dragevent dragevent int dragaction drageventgetaction view dragview view drageventgetlocalstate if dragaction drageventaction drag exited oktodrop false else if dragaction drageventaction drag entered oktodrop true else if dragaction drageventaction drag ended if dropeventnothandleddragevent true code to generate image goes here context context getapplicationcontext charsequence text action dropped not in box int duration toastlength short toast toast toastmaketextcontext text duration toastshow dragviewsetvisibilityviewvisible else if dragaction drageventaction drop oktodrop imageview i imageview findviewbyidridsquare isetimageresourcerdrawableoval dragviewsetvisibilityviewinvisible context context getapplicationcontext charsequence text action resulted in it being dropped in the box int duration toastlength short toast toast toastmaketextcontext text duration toastshow return true private boolean dropeventnothandleddragevent dragevent return drageventgetresult and my xmlrelativelayout xmlnsandroid xmlnstools androidlayout widthmatch parent androidlayout heightmatch parent toolscontextmainactivity imageview androidididsquare androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentrighttrue androidlayout centerverticaltrue androidsrcdrawablesquare box imageview androidididoval androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentlefttrue androidlayout alignparenttoptrue androidlayout marginleft58dp androidlayout margintop58dp androidsrcdrawableoval imageview androidididrobot androidlayout widthwrap content androidlayout heightwrap content androidlayout alignleftidoval androidlayout belowidsquare androidlayout margintop70dp androidsrcdrawableic launcher relativelayout,"['java', 'android']" +399853,java charat used with characters that have two code units from core java vol 1 9th ed p 69the character a requires two code units in the utf16 encoding callingstring sentence a is the set of integers for clarity not in bookchar ch sentencecharat1does not return a space but the second code unit of abut it seems that sentencecharat1 does return a space for example the if statement in the following code evaluates to truestring sentence a is the set of integersif sentencecharat1 systemoutprintlnsentencecharat1 returns a spacewhyi am using jdk se 170 09 on ubuntu 1210 if it is relevant,['java'] +399886,sqrt perfect squares and floating point errors in the sqrt function of most languages though here i am mostly interested in c and haskell are there any guarantees that the square root of a perfect square will be returned exactly for example if i do sqrt810 90 is that safe or is there a chance that sqrt will return 898 or 903if numerical precision is not guaranteed what would be the preferred way to check that a number is a perfect square take the square root get the floor and the ceiling and make sure they square back to the original numberthank you,['c'] +399963,why is not the copy constructor called possible duplicatewhat are copy elision and return value optimization i am having difficulty understanding why in the following piece of code the copy constructor is not calledinclude iostreamclass testpublic testintstdcout test stdendl testconst teststdcout testconst test stdendlint main test test test test2test3 return 0can someone explain why only the constructor is called and no copy constructor thanks,['c++'] +399975,how ajax calls work with twig i am trying to understand how twig can load a template through ajaxfrom their website it is clear how to load a template echo twigrenderindexhtml arraythe variables go herebut how would this work for an ajax call how would you tell twig that you want to render something that is only a part of indexhtml and not reload the entire page i looked at twigs sole ajax example but this does not explain how twig knows what part of the page you want to change assuming your ajax call results in page content updates i just need a simple example of this something more than what is on twigs recipe page,"['php', 'jquery']" +400007,dynamically change image src using jquery not working in ie and firefox i am implementing a captcha for a email when click on linkemail button email modal will openthere i have to set captcha image generated by a handler captchageneratorashx on click of linkemail button click here is the code for thatlinkemailclickfunction load captcha image imgcaptchaattrsrc customappcodeutilitiescaptchageneratorashx emailmodalmodalabove code is working fine in crome but not working in ie and firefoxalthough i have tried followings there is no luckhtmlp idcaptchacontainerp classcaptchacontainerpcaptchacontainerpprependimg idimcaptcha classimgcaptcha srccustomappcodeutilitiescaptchageneratorashximgvar img img idimcaptcha classimgcaptchaimgattrsrc customappcodeutilitiescaptchageneratorashxcaptchacontainerpemptyimgappendtocaptchacontainerpcaptchacontainerpemptycaptchacontainerpappendimg idimcaptcha classimgcaptcha srccustomappcodeutilitiescaptchageneratorashximg,"['javascript', 'jquery']" +400045,why does not followed by parse during andrei alexandrescus talk on error handlingsee c and beyond 2012 andrei alexandrescu systematic error handling in c about 30 minutes inandrei presents the following piece of codeexpected using stdexception ptr if gotham hamt else spamexception ptrthis destructor is cleaning up a union which contains either some type t or a stdexception ptr the union is populated using placement newandrei then explains that the using stdexception ptr is necessary because the following code does not parse else spamstdexception ptrthis means that it is always necessary to have a using directive if you need to explicitly call the destructor of a class in a different namespacewhy does not the second example parsewould the followng code be a valid alternative else delete spamdoes this have the same affect as explicitly calling the destructor of stdexception ptr,['c++'] +400072,count occurrences of character in a string using mysql example words a aka akokaa kokoko kakao oaooa kkako kakaoai need the regexp witch gives words with 2 or less a but not the words without aresult a akka kakao oaooa kkakook actually i am usingselect word from dictionary gr where word regexp i23 limit 0 30this returns 0 lines there are words with 2 is and 3 is,"['mysql', 'sql']" +400101,wpf animate background color i need help in taking right decision i need to animate a background color of my user control when some event happens when it is i want to change the background just for 1 second and then turn it back which way should i go use color animation or timer or may by some other waysolved thanks to all this works good for me coloranimation animation animation new coloranimation animationfrom colorsorange animationto colorsgray animationduration new durationtimespanfromseconds1 thiselgridbackgroundbeginanimationsolidcolorbrushcolorproperty animation,['c#'] +400118,change child view controller i have a view controller that when i press a button a child view controller appear this works perfectly but i want to change this child view controller for other one if i press the button next that is inside of this to do like two step loginany idea because from the main view controller i know how show a child but from the child i do not know how to do it,['ios'] +400177,java stringsubstring method potential memory leak i was going through the string class api and looks like there is a potential memory leak caused by substring method as it shares same character array as original string if original string is huge then small string returned by substring can prevent original stringbacked up by large array from garbage collection in javaany thoughts or did i read the api wrong,['java'] +400199,how to implement growth function in javascript i am trying to implement microsoft excels growth function in javascript this function calculates predicted exponential growth by using existing data what makes it tricky is that it must work with multiple sets of known xs values i could not find any reference equation any suggestionsthanks in advance for your help,['javascript'] +400201,convert a classpath filename to a real filename how would i convert the name of a file on the classpath to a real filenamefor example let us say the directory cworkspaceprojecttargetclasses is on your classpath within that directory is a file such as infopropertieshow would you determine at runtime the absolute file path to the infoproperties file given only the string infopropertiesthe result would be something like cworkspaceprojecttargetclassesinfopropertieswhy is this useful when writing unit tests you may want to access files bundled in your test resources srcmainresources but are working with a thirdparty library or other system that requires a true filename not a relative classpath referencenote i have answered this question myself as i feel it is a useful trick but it looks like no one has ever asked this question before,['java'] +400217,how do i get logcat for multiple devices running at the same time in eclipse i have two android devices connected to the same station i would like to view the logcat for both while running them in debug mode in eclipsei have had some luck with the following stepsrun the app on device 1run the app on device 2open a new window windownewin the new window open view logcatabout 40 of the time this results in in each eclipse window showing data from a different phone but not always it seems to be almost a luckofthedraw kind of thing more often than not both windows show the same device if i open device viewer and select a device in either window both change how can i do this all the time,['android'] +400237,mvc web api complex object query via get is there a way to query a web api through get but with complex object in its parameterall the examples i have seen so far seems to indicate i would have to use post but i do not want to use post because this is a query at the same time i do not want a function with 16 arguments because that just screams brittle public product getint id string name datetime createdby string stocknumber i want the above to be turned intopublic product getproductquery query is there a way to do this and how do you make the httpclient work with the above service,['asp.net'] +400246,some part of your sql statement is nested too deeply rewrite the query or break it up into smaller queries i have action in my controller which calls the following method public iqueryableausercontactinfo getcontactinfolong id var organizationsiteids from accountsitemapping in entitiesaccountsitemappings where idanyaccountid accountsitemappingaccountid accountid select accountsitemappingsiteid var usersdepts from userdept in entitiesuserdepartments join deptdefinition in entitiesdepartmentdefinitions on userdeptdeptid equals deptdefinitiondeptid where organizationsiteidsanyaccountid deptdefinitionsiteid accountid select userdept var contactsinfos from userdept in usersdepts join contactinfo in entitiesausercontactinfoes on userdeptuserid equals contactinfouser id select contactinfo return contactsinfosbut when i run the application and i navigate to the action method the folowing error will be raised on the view levelsystemdataentitycommandexecutionexception was unhandled by user code hresult2146232004 messagean error occurred while executing the command definition see the inner exception for details sourcesystemdataentity stacktrace at systemdataentitycliententitycommanddefinitionexecutestorecommandsentitycommand entitycommand commandbehavior behavior at systemdataobjectsinternalobjectqueryexecutionplanexecutetresulttypeobjectcontext context objectparametercollection parametervalues at systemdataobjectsobjectquery1getresultsnullable1 formergeoption at systemdataobjectsobjectquery1systemcollectionsgenericienumerabletgetenumerator at systemdataentityinternallinqinternalquery1getenumerator at systemdataentityinfrastructuredbquery1systemcollectionsgenericienumerabletresultgetenumerator at systemlinqenumerablecounttsourceienumerable1 source at asp page views home customersdetails cshtmlexecute in cusersadministratordesktopnew app demo2mvcapplication4 latest mvcapplication4viewshomecustomersdetailscshtmlline 6 at systemwebwebpageswebpagebaseexecutepagehierarchy at systemwebmvcwebviewpageexecutepagehierarchy at systemwebwebpagesstartpagerunpage at systemwebwebpagesstartpageexecutepagehierarchy at systemwebwebpageswebpagebaseexecutepagehierarchywebpagecontext pagecontext textwriter writer webpagerenderingbase startpage at systemwebmvcrazorviewrenderviewviewcontext viewcontext textwriter writer object instance at systemwebmvcbuildmanagercompiledviewrenderviewcontext viewcontext textwriter writer at systemwebmvcviewresultbaseexecuteresultcontrollercontext context at systemwebmvccontrolleractioninvokerinvokeactionresultcontrollercontext controllercontext actionresult actionresult at systemwebmvccontrolleractioninvokerc thisplayclass1cinvokeactionresultwithfiltersb 19 at systemwebmvccontrolleractioninvokerinvokeactionresultfilteriresultfilter filter resultexecutingcontext precontext func1 continuation innerexception systemdatasqlclientsqlexception hresult2146232060 messagesome part of your sql statement is nested too deeply rewrite the query or break it up into smaller queries sourcenet sqlclient data provider errorcode2146232060 class15 linenumber105 number191 procedure stacktrace at systemdatasqlclientsqlconnectiononerrorsqlexception exception boolean breakconnection action1 wrapcloseinaction at systemdatasqlclientsqlinternalconnectiononerrorsqlexception exception boolean breakconnection action1 wrapcloseinaction at systemdatasqlclienttdsparserthrowexceptionandwarningtdsparserstateobject stateobj boolean callerhasconnectionlock boolean asyncclose at systemdatasqlclienttdsparsertryrunrunbehavior runbehavior sqlcommand cmdhandler sqldatareader datastream bulkcopysimpleresultset bulkcopyhandler tdsparserstateobject stateobj boolean dataready at systemdatasqlclientsqldatareadertryconsumemetadata at systemdatasqlclientsqldatareaderget metadata at systemdatasqlclientsqlcommandfinishexecutereadersqldatareader ds runbehavior runbehavior string resetoptionsstring at systemdatasqlclientsqlcommandrunexecutereadertdscommandbehavior cmdbehavior runbehavior runbehavior boolean returnstream boolean async int32 timeout task task boolean asyncwrite at systemdatasqlclientsqlcommandrunexecutereadercommandbehavior cmdbehavior runbehavior runbehavior boolean returnstream string method taskcompletionsource1 completion int32 timeout task task boolean asyncwrite at systemdatasqlclientsqlcommandrunexecutereadercommandbehavior cmdbehavior runbehavior runbehavior boolean returnstream string method at systemdatasqlclientsqlcommandexecutereadercommandbehavior behavior string method at systemdatasqlclientsqlcommandexecutedbdatareadercommandbehavior behavior at systemdatacommondbcommandexecutereadercommandbehavior behavior at systemdataentitycliententitycommanddefinitionexecutestorecommandsentitycommand entitycommand commandbehavior behavior innerexceptionso what is causing this errorupdated,['c#'] +400273,identifying large bodies of text via beautifulsoup or other python based extractors given some random news article i want to write a web crawler to find the largest body of text present and extract it the intention is to extract the physical news article on the pagethe original plan was to use a beautifulsoup findalltrue and to sort each tag by its gettext value edit do not use this for html work use the lxml library it is python based and much faster than beautifulsoup command which means extract all html tagsbut this would not work for most pages like the one i listed as an example because the large body of text is split into many smaller tags like paragraph dividers for exampledoes anyone have any experience with this any help with something like this would be amazingat the moment i am using beautifulsoup along with python but willing to explore other possibilitiesedit came back to this question after a few months later wow i sounded like an idiot and solved this with a combination of libraries own codehere are some deadly helpful python libraries for the task in sorted order of how much it helped me1 goose library fast powerful consistent2 readability library content is passable slower on average than goose but faster than boilerpipe3 pythonboilerpipe slower hard to install no fault to the boilerpipe library originally in java but to the fact that this library is build on top of another library in java which attributes to io time errors etci will release benchmarks perhaps if there is interestindirectly related libraries you should probably install them and read their docsnltk text processing library thisis too good not to install they provide text analysis tools alongwith html tools like cleanup etclxml htmlxml parser mentionedabove this beats beautifulsoup in every aspect but usability it is abit harder to learn but the results are worth it html parsing takesmuch less time it is very noticeable pythonwebscrapper library i think the value of this code is not thelib itself but using the lib as a reference manual to build your owncrawlersextractors it is very nicely coded documenteda lot of the value and power in using python a rather slow language comes from it is open source libraries they are especially awesome when combined and used together and everyone should take advantage of them to solve whatever problems they may havegoose library gets lots of solid maintenance they just added arabic support it is great,['python'] +400279,requirejs optional dependency i am adding amd support to a javascript library i developthis library may use jquery but it will still work if jquery is not loadedwhen defining the module dependency there is a way to set a dependency as optional so that if that library is missing the module will still work,['javascript'] +400335,jqueryui dialogdatepicker autoopens i currently have a dialog box with two inputs as its content with the two inputs using datepicker when i open dialog box the first input becomes the focus and the first datepicker automatically appears i have tried hiding the div and blurring the input but that causes the datepicker to no longer appear on focus ideally i want to be able to the followingopen the dialog box with no datepickers showingclick in the first input and have the datepicker showhere is my current codejavascripttodatepicker onclose function selecteddate fromdatepickeroption mindate selecteddate fromdatepicker onclose function selecteddate todatepickeroption maxdate selecteddate settingsdialogdialog autoopen false open function event ui if uidatepickerisvisible uidatepickerhide toblur thisfocusclick close function thisdialogclose i have also made a jsfiddle demo i have searched online for a solution and found similar questions but none that seem to help could anyone assist meeditthe browser i am using is chrome,['jquery'] +400375,scaling canvas to resize svg in android i am not having much luck wrapping my head around this so i am hoping someone can help me outi am getting a drawable from an svg using svgandroid but the drawable is not scaling to the view everything that i have been able to find says i should draw directly to canvas and rescale the canvas but when i try that it only seems to change the bounds but not scale the imagethis is what i have tried so farimageview testview imageviewfindviewbyidridtestviewget svg and convert to drawablesvg vector svgparsergetsvgfromresourcegetresourcesrdrawabletestvectordrawable test vectorcreatepicturedrawabletestviewsetbackgroundtest thisplays fine but would not scale to the dimensions of the viewfunction that clips the image but does not scaledrawable testtwo new custompicturedrawablevectorgetpicture float05 float05testviewsetbackgroundtesttwoclass custompicturedrawable extends picturedrawable private float scalex scaleypublic custompicturedrawablepicture picture float scalex float scaley superpicture thisscalex scalex thisscaley scaleyoverridepublic void drawcanvas canvas matrix original canvasgetmatrix canvasscalescalex scaley superdrawcanvas canvassetmatrixoriginaldoes not thisplay anythingpicture testthree vectorgetpicturebitmap b bitmapcreatebitmap10 10 bitmapconfigargb 4canvas c new canvasbcdrawpicturetestthree new rect001010testviewdrawci have also found a function that will create a scaled bitmap but the image quality is significantly reduced so i may as well just use scaled pngsobviously i am missing something and my lack of experience is making it really frustrating what i would like to be able to do is have svgandroid completely rescale the svg before pulling a picture or picturedrawable out of it but i cannot figure out how to step through the svgparser and running multipliers on every coordinate pair would probably be super resource intensive anywayedit is the only way to scale and redraw the picture and assign that to a view to create custom views and override ondraw iepicture testthree vectorgetpicturebitmap b bitmapcreatebitmap10 10 bitmapconfigargb 4canvas c new canvasbcdrawpicturetestthree new rect001010customview extends imageview or button or whatever with ondraw overridden and noother changes customview testview customviewfindviewbyidridtestview testviewondrawcam i on the right track canvas c would overwrite the default canvas which is what i want wouldnt it,['android'] +400389,get the vtable address in c i am willing to use unsafe how can i get a class virtual table address and convert it to an int,['c#'] +400415,argumentdependent lookup when is it done what is searched and how can you force or prevent it i am having trouble understanding the rules behind argumentdependent koenig lookup consider the code belowinclude iostreamusing namespace stdnamespace adl struct test void foo1test const cout adl used foo1 endl void foo2test const cout adl used foo2 endl void foo3test const cout adl used foo3 endl struct foo1 foo1 templateclass t foo1t const cout adl not used foo1 endl templateclass t void operatort const const cout adl not used foo3 endl templateclass t void foo2t const cout adl not used foo2 endl int main adltest t foo1 foo3 foo1t foo2t foo3tits output isadl not used foo1 adl used foo2 adl not used foo3i expected all of them to use adl but i was surprised that only some of them didwhat are the potentially gory i know details behind the rules of adli understand the concept well enough but the details are what i am having trouble withwhich scopes are searched when are they searched and when are they not searchedis it at all possible to tell whether adl is used without having to look through all the included files before the given line of code i expected functors and functions to behave the same way in terms of not masking adl but apparently they do notis there any way to force adl in cases where it is not done automatically such as the above and you do not know the clas namespace eg in a template,['c++'] +400421,enablethisable actionbar menu item i have actionbar menuitems cancel and savemenuxmlxml version10 encodingutf8menu xmlnsandroid item androidididsavebutton androidshowasactionalways androidtitlestringsave androidvisibletrue item item androidididcancelbutton androidshowasactionalways androidtitlestringcancel androidvisibletrue itemmenui want to thisable save menuitem when activity is startedmy activity code override protected void oncreatebundle savedinstancestate todo autogenerated method stub superoncreatesavedinstancestate setcontentviewrlayoutadd project edittext projectname edittext findviewbyidridedittextprojectname projectnameaddtextchangedlistenernew textwatcher override public void ontextchangedcharsequence s int start int before int count configuresavebuttons override public void beforetextchangedcharsequence s int start int countint after override public void aftertextchangededitable s override public boolean oncreateoptionsmenumenu menu menuinflater inflater getmenuinflater inflaterinflatermenuaddprojectmenu menu return superoncreateoptionsmenumenu override public boolean onprepareoptionsmenumenu menu menuitem item menuitem findviewbyidridsavebutton itemsetenabledfalse return superonprepareoptionsmenumenu private void configuresavebuttoncharsequence s string text null ifs null text stostring iftext null texttrimlength 0 else so what i am trying to do here is initially when activity is started save menu item should be thisabled and when editext contains some text then it should be enabled i am not sure what should be the code in if else in configuresavebutton methodalso how can i thisable save menu item initiallyi get null pointer exception in onprepareoptionsmenui am using android 41,['android'] +400438,using transactionscope when integration testing web apis at the moment i am doing something similar to this to integration test a library that communicates with our api controllers and so far so good but i have run into a snag in all of our other integration tests we run the test inside an msdtc transaction at isolation level readcommitted so that each one gets its own little private session with the databases and such and at the end of each test the transactions are rolled back but that does not work for these tests because the transactions are perthread and all of the httpclienthttpserver methods are asynchronous so the work is done on a different thread than the main one for that test does not have an ambient transaction to subscribe to and goes right along and commitsi have come across a few posts about how to open a transactionscope on one thread and then create a dependent transaction to be passed to a new task via a closure but i have no idea how to apply that to an httpclient that is connected to an inmemory httpserver i suspect i am just not thinking about it the right way but that is about all i have to go onwhat would make senseworketc i have full control over the creation of the httpserver and the httpclient that will connect to it but i am at a loss as to what to do with themupdatesome progress has been made i wrote a message handler that can create a dependent transaction on the worker thread if transactioncurrent is populated when it gets there and for some of my calls it is but for others it is not and i am wondering if i may be chasing shadows like there is a lot of continuewith around and i think it is executed on the calling thread which would naturally have a transaction if the antecedent task is already completewould it be possible just to run the whole thing synchronously and carry the tests thread all the way through i have experimented some with continuewithing synchronously without much success,['c#'] +400443,how to use multiprocessing with class instances in python i am trying to create a class than can run a separate process to go do some work that takes a long time launch a bunch of these from a main module and then wait for them all to finish i want to launch the processes once and then keep feeding them things to do rather than creating and destroying processes for example maybe i have 10 servers running the dd command then i want them all to scp a file etc my ultimate goal is to create a class for each system that keeps track of the information for the system in which it is tied to like ip address logs runtime etc but that class must be able to launch a system command and then return execution back to the caller while that system command runs to followup with the result of the system command latermy attempt is failing because i cannot send an instance method of a class over the pipe to the subprocess via pickle those are not pickleable i therefore tried to fix it various ways but i cannot figure it out how can my code be patched to do this what good is multiprocessing if you cannot send over anything usefulis there any good documentation of multiprocessing being used with class instances the only way i can get the multiprocessing module to work is on simple functions every attempt to use it within a class instance has failed maybe i should pass events instead i do not understand how to do that yetimport multiprocessingimport sysimport reclass processworkermultiprocessingprocess this class runs as a separate process to execute workers commands in parallel once launched it remains running monitoring the task queue until none is sent def init self task q result q multiprocessingprocess init self selftask q task q selfresult q result q return def runself overloaded function provided by multiprocessingprocess called upon start signal proc name selfname print s launched proc name while true next task list selftask qget if next task is none poison pill means shutdown print s exiting proc name selftask qtask done break next task next task list0 print s s proc name next task args next task list1 kwargs next task list2 answer next taskargs kwargs selftask qtask done selfresult qputanswer return end of processworker classclass workerobject launches a child process to run commands from derived classes in separate processes which sit and listen for something to do this base class is called by each derived worker def init self config indexnone selfconfig config selfindex index launce the processworker for anything that has an index value if selfindex is not none selftask q multiprocessingjoinablequeue selfresult q multiprocessingqueue selfprocess worker processworkerselftask q selfresult q selfprocess workerstart print got here process should be running and listening for functions to execute return def enqueue processtarget no self since it is a decorator used to place an command target from this class object into the task q note any function decorated with this must use fetch results to get the target tasks result value def wrapperself args kwargs selftask qputtarget args kwargs fail target is a class instance method and cannot be pickled return wrapper def fetch resultsself after all processes have been spawned by multiple modules this command is called on each one to retreive the results of the call this blocks until the execution of the item in the queue is complete selftask qjoin wait for it to to finish return selfresult qget return the result enqueue process def run long commandself command print i am running number as process number selfname in here i will launch a subprocess to run a longrunning system command p popencommand etc pwait etc return def closeself selftask qputnone selftask qjoinif name main config some value something else index 7 workers for i in range5 worker workerconfig index workerrun long commandls workersappendworker for worker in workers workerfetch results do more work this would actually be done in a thistributor in another class for worker in workers workerclose edit i tried to move the processworker class and the creation of the multiprocessing queues outside of the worker class and then tried to manually pickle the worker instance even that does not work and i get an error runtimeerror queue objects should only be shared between processes through inheritance but i am only passing references of those queues into the worker instance i am missing something fundamental here is the modified code from the main sectionif name main config some value something else index 7 workers for i in range1 task q multiprocessingjoinablequeue result q multiprocessingqueue process worker processworkertask q result q worker workerconfig index process worker task q result q something to look at pickledumpsworker fail does not like queues process workerstart workerrun long commandls,['python'] +400454,ios draw radial gradient that fills recrangle the code below draws a perfect elliptical radial gradient but does not fill in the corners of it is view how do i get it to draw beyond the edge of the ellipse the documented option is kcggradientdrawsafterendlocation but i think it is not available in ios voiddrawrectcgrectrect cgfloat colors 02 02 02 10 00 00 00 10 cgcolorspaceref basespace cgcolorspacecreatedevicergb cggradientref gradient cggradientcreatewithcolorcomponentsbasespace colors null 2 cgcolorspacereleasebasespace basespace null cgcontextref context uigraphicsgetcurrentcontext cgcontextsavegstatecontext cgcontextaddellipseinrectcontext rect cgcontextclipcontext cgcontextdrawradialgradientcontext gradient selfcenter 0 selfcenter selfframesizewidth kcggradientdrawsafterendlocation cggradientreleasegradient gradient null cgcontextrestoregstatecontext,['ios'] +400457,strict aliasing and memory alignment i have performance critical code and there is a huge function that allocates like 40 arrays of different size on the stack at the beginning of the function most of these arrays have to have certain alignment because these arrays are accessed somewhere else down the chain using cpu instructions that require memory alignment for intel and arm cpussince some versions of gcc simply fail to align stack variables properly notably for arm code or even sometimes it says that maximum alignment for the target architecture is less than what my code actually requests i simply have no choice but to allocate these arrays on the stack and align them manuallyso for each array i need to do something like that to get it aligned properlyshort history hist size 32short history shortuintptr thistory 31 31this way history is now aligned on 32byte boundary doing the same is tedious for all 40 arrays plus this part of code is really cpu intensive and i simply cannot do the same alignment technique for each of the arrays this alignment mess confuses the optimizer and different register allocation slows down the function big time for better explanation see explanation at the end of the questionso obviously i want to do that manual alignment only once and assume that these arrays are located one right after the other i also added extra padding to these arrays so that they are always multiple of 32 bytes so then i simply create a jumbo char array on the stack and cast it to a struct that has all these aligned arraysstruct tmp short historyhist size short history22hist size int energy320 char bufsizeoftmp 32tmp x tmpuintptr tbuf 31 31something like that maybe not the most elegant but it produced really good result and manual inspection of generated assembly proves that generated code is more or less adequate and acceptable build system was updated to use newer gcc and suddenly we started to have some artifacts in generated data eg output from validation test suite is not bit exact anymore even in pure c build with thisabled asm code it took long time to debug the issue and it appeared to be related to aliasing rules and newer versions of gccso how can i get it done please do not waste time trying to explain that it is not standard not portable undefined etc i have read many articles about that also there is no way i can change the code i would perhaps consider modifying gcc as well to fix the issue but not refactoring the code basically all i want is to apply some black magic spell so that newer gcc produces the functionally same code for this type of code without thisabling optimizationsedit i used this code on multiple osescompilers but started to have issues when i switched to newer ndk which is based on gcc 46 i get the same bad result with gcc 47 from ndk r8d i mention 32 byte alignment if it hurts your eyes substitute it with any other number that you like for example 6 if it helps there is absolutely no point to even mention that most architectures do not need that alignment if i align 8kb of local arrays on stack i loose 15 bytes for 16 byte alignment and i loose 31 for 32 byte alignment i hope it is clear what i mean i say that there are like 40 arrays on the stack in performance critical code i probably also need to say that it is a third party old code that has been working well and i do not want to mess with it no need to say if it is good or bad no point for that this codefunction has well tested and defined behavior we have exact numbers of the requirements of that code eg it allocates xkb or ram uses y kb of static tables and consumes up to z kb of stack space and it cannot change since the code would not be changed by saying that alignment mess confuses the optimizer i mean that if i try to align each array separately code optimizer allocates extra registers for the alignment code and performance critical parts of code suddenly do not have enough registers and start trashing to stack instead which results in a slowdown of the code this behavior was observed on arm cpus i am not worried about intel at all by the way by artifacts i meant that the output becomes nonbitexact there is some noise added either because of this type aliasing issue or there is some bug in the compiler that results eventually in wrong output from the functionin short the point of the question how can i allocate random amount of stack space using char arrays or alloca and then align pointer to that stack space and reinterpret this chunk of memory as some structure that has some well defined layout that guarantees alignment of certain variables as long as the structure itself is aligned properly i am trying to cast the memory using all kinds of approaches i move the big stack allocation to a separate function still i get bad output and stack corruption i am really starting to think more and more that this huge function hits some kind of bug in gcc it is quite strange that by doing this cast i cannot get this thing done no matter what i try by the way i thisabled all optimizations that require any alignment it is pure cstyle code now still i get bad results nonbitexact output and occasional stack corruptions crashes the simple fix that fixes it all i write instead ofchar bufsizeoftmp 32tmp x tmpuintptr tbuf 31 31this codetmp buftmp x bufthen all bugs thisappear the only problem is that this code does not do proper alignment for the arrays and will crash with optimizations enabledinteresting observationi mentioned that this approach works well and produces expected outputtmp buftmp x bufin some other file i added a standalone noinline function that simply casts a void pointer to that struct tmpstruct tmp to struct tmpvoid buffer32 return struct tmp buffer32initially i thought that if i cast alloced memory using to struct tmp it will trick gcc to produce results that i expected to get yet it still produces invalid output if i try to modify working code this waytmp buftmp x to struct tmpbufthen i get the same bad result wow what else can i say perhaps based on strictaliasing rule gcc assumes that tmp x is not related to tmp buf and removed tmp buf as unused variable right after return from to struct tmp or does something strange that produces unexpected result i also tried to inspect generated assembly however changing tmp x buf to tmp x to struct tmpbuf produces extremely different code for the function so somehow that aliasing rule affects code generation big timeconclusionafter all kinds of testing i have an idea why possibly i cannot get it to work no matter what i try based on strict type aliasing gcc thinks that the static array is unused and therefore does not allocate stack for it then local variables that also use stack are written to the same location where my tmp struct is stored in other words my jumbo struct shares the same stack memory as other variables of the function only this could explain why it always results in the same bad result fnostrictaliasing fixes the issue as expected in this case,"['c++', 'c']" +400484,unresolved external symbol public virtual struct qmetaobject const thiscall parent i inherited a class from qobject class parent public qobject q object qobject clpublic parentqobject parent0qobjectparent cl null qobject getcl const return cl void setclqobject obj cl obj but when i write parent evi get the following errormainobj1 error lnk2001 unresolved external symbol public virtual struct qmetaobject const thiscall parentmetaobjectvoidconst metaobjectparentubepbuqmetaobjectxzmainobj1 error lnk2001 unresolved external symbol public virtual void thiscall parentqt metacastchar const qt metacastparentuaepaxpbdzmainobj1 error lnk2001 unresolved external symbol public virtual int thiscall parentqt metacallenum qmetaobjectcallintvoid qt metacallparentuaehw4callqmetaobjecthpapaxz,['c++'] +400495,preloading the webview in activity a and passing it to activity b for faster loading in one of my app i am using webview to load the pages the scenario is i have activity a and activity b activity a thisplays the menu list on selection of any of the item in the list it will open activity b in activity b i am doing all the webview related activities like loading webview using the url but its taking lot of time to thisplay that page my question here is there anyway i can preload the webview in activity a and pass it to b for immediate loadingif it is possible to preload the webview in activity a and pass it to activity b for immediate rendering please let me know how it is doablenote i can use progress dialog in activity a until the webview loadswait till onpagefinished get called and start the activity b but how can i make the webview load immediately here,"['java', 'android']" +400560,how do i create a line break in a javascript string to feed to nodejs to write to a text file i have created a simple html page that takes some input from the user to store on a server to be retrieved later this is how the text is treated when the user clicks a submit button i have placed numbered comments under the key lines but provide the surrounding code for contextvar origtext inputfieldval 1 gets whatever user typed into input field jsontext text origtext 2 wraps it an object string ajaxtext encodeuricomponentjsontext 3 encodes the string for use with ajaxajax url httplocalhost8124 data save ajaxtext fnsave 4 the encoded string is added to the query section of the ajax request datatype jsonp cache false timeout 50 success functiondata inputreadyhtmldatasavetext error functionjqxhr textstatus errorthrown alerterror textstatus errorthrown the request is sent to a nodejs server i am running locally which within the httpcreateserver callback does the followingvar queryobj urlparserequrl truequery 1 get the query part of the requesturl as an objectreswritehead200 contenttype applicationjavascript 2 prepare servers response as javascriptqueryobjfn queryobjfn queryobjsave queryobjsave queryobjcallback queryobjcallback 3 ensure the properties needed are defined even if falseyif queryobjfn save 4 if the request is to save then write the user input as object to a text file fswritefilejsonpstorage2txt queryobjsave function err if err throw err else consolelogsaved message successfully ready to be read now resendqueryobjcallback fn queryobjfn save queryobjsave assuming the user types and submits this is a line of text the output on the server is a text file called jsonpstorage2txt containing this text this is a line of text after all that my question is quite simple how do i prettify the output in the text filethe code needs work but i am thinking of using this to try storing larger objects for reading later however at the server end i would like the files for now to be easy for me to read when opening them with notepad for examplei have tried using n and t like sojsontext nttext origtext ni have also tried r but the lines remain unbrokensome answers suggest that i can only do this at the level of the encoded string or after the file has been written perhaps i missed something simple is there a way to do it by manipulating my jsontext variableupdatejust to be clearer about the output desired currently the content of the text file produced looks like this text this is a line of text but i would like to know if it can be produced like this text this is a line of text,"['javascript', 'jquery']" +400562,creating shared libraries in c for osx i just started programming in c and i have realized that i have been having to write the same code over and over againmostly utility functionsso i am trying to create a shared library and install it in path so that i could use the utility functions whenever i needed toheres what i have done so far create a file utilsh with the following contents includeiostreamincludestringstdstring to binaryint xcreate a file utilscpp with the following contents include utilshstdstring to binaryint x stdstring binary while x 0 if x 1 binary 1 else binary 0 x 1 return binaryfollow the steps mentioned here create the library object code g wall fpic c utilscppbut as the link above is meant for linux it does not really work on osx could someone suggest reading resources or suggest hints in how i could go about compiling and setting those objects in the path on an osx machinealso i am guessing that there should be a way i can make this crossplatformie write a set of instructionsbash script or a makefile so that i could use to compile this easily across platforms any hints on that,['c++'] +400573,http delete verb in nodejs do i need to set up any configuration before i can make delete requests to a nodejs applicationi can make get post or put requests but delete requests would not workdelete httplocalhost8081api10entry yields undefined from the routing logger i am using express to register the routes but it looks like i cannot even resolve the url verbthis is how i am invoking itrowsfindaremoveonclick function ajax url api10entry type delete donefunctionres var row thisparentsuntiltbody rowslideup sample logget 200 18ms get authorentry 200 10ms get api10entry 200 2ms get api10entry 200 1ms get api10entry 200 1ms undefined,['javascript'] +400581,automatically deleting related rows in laravel eloquent orm when i delete a row using this syntaxuserdeleteis there a way to attach a callback of sorts so that it would eg do this automaticallythisphotodeletepreferably inside the modelclass,['php'] +400663,is there a more basic tutorial for the c unit testing framework check i am trying to follow along with the official tutorial here but it requires a working knowledge of autotools which i do not have i was hoping just to write a couple quick tests and i am finding this tutorial overwhelming it relies on a lot of magic in autoconf automake and some check macros i guess and it does not explain how check actually works so that i could build tests by handcan anybody recommend a simpler tutorial that does not require autotools,['c'] +400670,why are member function pointers behaving so weirdly in visual c i have had a really bizarre problem that i have reduced to the following test caseinclude iostreaminclude mapinclude stringstruct test stdmapstdstring void test m test thismtest1 testtest1 thismtest2 testtest2 void test1 void test2 void thispatchstdstring s if thismats testtest1 stdcout test1 will be called stdendl else if thismats testtest2 stdcout test2 will be called stdendl thisthismats int main test t tthispatchtest1 tthispatchtest2it outputstest1 will be called test1 will be calledwhen optimizations are enabled which is really bizarre whats going on,['c++'] +400673,canvas element with and image loaded from aws s3 using cors does not work first couple loads so i have cors setup on my aws s3 bucketcorsconfiguration xmlns corsrule allowedoriginallowedorigin allowedmethodgetallowedmethod corsrulecorsconfigurationin my htmldiv idexplain canvasdivin my javascript i am loading an image and placing it into a canvas imagevar outlineimage new imageoutlineimagecrossorigin outlineimagesrc drawing imageoutlineimageonload function var canvasdiv documentgetelementbyidexplain canvas var canvas documentcreateelementcanvas canvassetattributewidth 722 canvassetattributeheight 170 canvassetattributeid canvas canvas element canvassetattributename canvas canvas element canvasdivappendchildcanvas iftypeof g vmlcanvasmanager undefined canvas g vmlcanvasmanagerinitelementcanvas var context canvasgetcontext2d contextdrawimageoutlineimage 10 10 600 150i am loading the context like that to be compatible with internet explorerhere is my problem when the page loads the first two times it comes up with this errorcrossorigin image load denied by crossorigin resource sharing policyhowever when i reload the page a couple times it will eventually work and load the image once it is done i am able to successfully call todataurl on the canvas elementdoes anyone know why this happens have i made a mistake is it an issue with aws and i will just have to wait for amazon to fix the corsit is happening in all browsers i have tested in chrome firefox safari ie on my mac pc and iphone so i do not think it is browser related also it happens locally and in productionthanks,['javascript'] +400732,draw nstableview alternating rows like itunes 11 i am aware that there are other questions on so about changing alternating row colors that is easy and it is not what i want to doi want to draw custom alternatingcolored rows in a viewbased nstableview that look like those from itunes 11 slight bezel at the top and bottom of the row as shown in this screenshotnotei know i can subclass nstablerowview and do my custom drawing there however this is not an acceptable answer because the custom row will only be used for rows that have data in the table in other words if the table has only 5 rows those 5 rows will use my custom nstablerowview class but the remaining rows in the rest of the table which are empty will use the standard alternating colors in that case the first 5 rows will show the bezel and the remaining ones would not not goodso how can i hack nstableview to draw these styled alternating rows for both filled and empty rows,['objective-c'] +400734,javascript dynamic function names how to create a function with a dynamic name something likefunction create functionname new functionname consoleloghello worldcreate functionexampleexample hello worldalso the function should be a function object so i can modify the prototype of the object,['javascript'] +400798,allow only anonymous users via webconfig authorization i want to use authorization in the webconfig to block access to signupaspx to authenticated users it cannot be accessed by user such as their roles is administrator and guestlocation pathsignupaspx systemweb authorization allow users authorization systemweblocation authentication modeforms forms nameauthcookie loginurlloginaspx timeout60 defaulturlindexaspx authentication authorization deny users authorization,['asp.net'] +400821,why do sql databases use a writeahead log over a command log i read about voltdbs command log the command log records the transaction invocations instead of each row change as in a writeahead log by recording only the invocation the command logs are kept to a bare minimum limiting the impact the thisk io will have on performancecan anyone explain the database theory behind why voltdb uses a command log and why the standard sql databases such as postgres mysql sqlserver oracle use a writeahead log,['sql'] +400930,rationale for why javascript converts primitive values to numbers in operator comparisons when one is boolean i know the rule if the two operands are not of the same type javascript converts the operands then applies strict comparison if either operand is a number or a boolean the operands are converted to numbers if possible else if either operand is a string the other operand is converted to a string if possibleso iftrue passes but iftrue true fails because it is handle like ifnan 1 i was wondering what the rational is behind this when one value is boolean in other weak typed languages like php this is handle this differentlyif one value is a boolean the other is converted to a boolean for comparisons and not covert both to numbers as in javascripti am assuming this choice was made for the operator on careful consideration can anyone provide rational as to why this was the chosen functionality is there a common use case that this was chosen to address i am betting is was not just a mistake,['javascript'] +400936,how to rotate image x degrees in c i have done some searching and i can not find any function thats doing what i whant it todoi have a image file of a scanned document with text but the document is some degrees rotated so i whant to rotate it so the text being inline with each otherin a perfect world its should be a function doing this automaticly but i can not find anything and what i understand to get it to work automaticly its needed to be some analyze of the image and i think its to big thing todobut then i have done a tool to rotate the image on a website manually but now i need a function to save the rotation to the image filethis seems to be some differents methods for but no one i tested doing what i whantthe function i have finded that works almost like i whant ispublic static bitmap rotateimgbitmap bmp float angle color bkcolor int w bmpwidthint h bmpheightpixelformat pf defaultpixelformatif bkcolor colortransparent pf pixelformatformat32bppargbelse pf bmppixelformatbitmap tempimg new bitmapw h pfgraphics g graphicsfromimagetempimggclearbkcolorgdrawimageunscaledbmp 1 1gthisposegraphicspath path new graphicspathpathaddrectanglenew rectanglef0f 0f w hmatrix mtrx new matrixusing systemdrawingdrawing2dmatrix class mtrxrotateanglerectanglef rct pathgetboundsmtrxbitmap newimg new bitmapconverttoint32rctwidth converttoint32rctheight pfg graphicsfromimagenewimggclearbkcolorgtranslatetransformrctx rctygrotatetransformangleginterpolationmode interpolationmodehighqualitybilineargdrawimageunscaledtempimg 0 0gthisposetempimgthisposereturn newimg but this do not change the height and width of the image file so the image file is in the same size but the image object has been scaled and rotatedany idea how i can do this goodansweri find the solution that worked with my image that has a resolution on 300 at a old answer here,['c#'] +400944,missing some colors from png texture in directx during loading and saving i use standard directx functions like createtexture2d d3dx11savetexturetofile and d3dx11createshaderresourceviewfromfile to load the png image render it on new created texture and than save to file all the textures are the power of two sizes but during it i have noticed that some colors from png are a little corrupted similar but not the same as the colors from the source texture the same with transparency it works for 0 and 100 transparency parts but not for eg 34are there some big colorapproximations or i do something wrong if so how can i solve ithere are these two images left is source a little different colors and some gradient transparency on the bottom right is image after loading first image and render it on the new texture that was than saved to file i do not know what cause that behaviour maybe the new textures descriptiontexturedescformat dxgi format r8g8b8a8 unormi have tried to change it to dxgi format r32g32b32a32 float but the effect was even strangerhere is the code for rendering source texture on the new texturecontextomsetrendertargets1 rendertargetview depthstencilview to render on new texture instead of the screenfloat clearcolor4 00f 00f 00f 00f red green blue alphacontextclearrendertargetviewrendertargetview clearcolorclear the depth buffer to 10 max depthcontextcleardepthstencilviewdepthstencilview d3d11 clear depth 10f 0renderingturnzbufferoffshadersetcontextobjectrendershader camera texturemanager context 0swapchainpresent0 0and in objectrenderuint stridestride sizeofvertexuint offset 0contextiasetvertexbuffers 0 1 buffersvertexbuffer stride offset set vertex buffercontextiasetindexbuffer buffersindexbuffer dxgi format r16 uint 0 set index buffercontextiasetprimitivetopology d3d11 primitive topology trianglelist set primitive topologyiftextureid contextpssetshaderresources 0 1 texturemanagergettextureidtextureconstantbuffer2dstructure cbperobjcbperobjpositionandscale xmfloat4centergetx centergety halfsizegetx halfsizegetycbperobjtexturecoordinates xmfloat4texturerecttouse0getx texturerecttouse0gety texturerecttouse1getx texturerecttouse1getycontextupdatesubresourceconstantbuffer 0 null cbperobj 0 0contextvssetconstantbuffers0 1 constantbuffercontextpssetconstantbuffers0 1 constantbuffercontextdrawindexed6 0 0the shader is very simplevs output vsfloat4 inpos position float2 intexcoord texcoord vs output output outputposzw float200f 10f inposxy 11 outputposxy inposxy positionandscalezw positionandscalexy outputtexcoordxy intexcoordxy texturecoordinateszw texturecoordinatesxy texturecoordinatesxy return outputfloat4 psvs output input sv targetreturn objtexturesampleobjsamplerstate inputtexcoordfor some optimalisation i parse the sprites size as the shaders param it works fine the size of texture borders etc are right,['c++'] +400979,dynamic operator resolution i have a generic method that calls operators by casting one of the operands to dynamicthere are two different callsarray is tt is myclassarrayrowcolumn defaultt as dynamicthis works and calls static bool operator myclass a myclass b even if both sides are nullwhat surprised me is the behaviour of the following linearray a and b are tt is myclassarrayrowcolumn alinei bicolumn as dynamicthis callspublic static myclass operator myclass a object b andpublic static myclass operator myclass a object band notpublic static myclass operator myclass a myclass b andpublic static myclass operator myclass a myclass bremoving the myclass object operators causesmicrosoftcsharpruntimebinderruntimebinderexception wurde nicht behandelt hresult2146233088 messageder operator kann nicht auf operanden vom typ myclass und object angewendet werden sourceanonymously hosted dynamicmethods assembly stacktrace bei callsitetargetclosure callsite myclass object bei systemdynamicupdatedelegatesupdateandexecute2t0t1tretcallsite site t0 arg0 t1 arg1 bei matrixmultiplytt a t b in innerexception ellipses minewhycan i call the right operator without explicitly calling a t operatorsaddtt a t b method instead of the operatorupdatepublic static t testmethodtthis t a t b return ta b as dynamic this method in a separate assembly calls or tries to call operator t object if the same method is in the main assembly it correctly calls operator t tthe class i use as type parameter is internal and the problem thisappears when i change it to public so it seems to depend on the class visibility towards the methodoperator t object is called successfully even if the class is not visible,['c#'] +400980,jsonnet fails when trying to deserialize a class that inherits from exception i have a class searcherror that inherits from exception and when ever i try to deserialize it from a valid json i get the following exceptioniserializable type searcherror does not have a valid constructor to correctly implement iserializable a constructor that takes serializationinfo and streamingcontext parameters should be present path line 1 position 81i tried implementing the suggested missing constructor and it did not helpthis is the class after implementing the suggested constructorpublic class apierror exception jsonpropertyerror public string error get set jsonpropertyhttp status code public int httpstatuscode get set jsonpropertywarnings public liststring warnings get set public apierrorstring error int httpstatuscode liststring warnings baseerror thiserror error thishttpstatuscode httpstatuscode thiswarnings warnings public apierrorsystemruntimeserializationserializationinfo info systemruntimeserializationstreamingcontext context baseinfo context error stringinfogetvalueerror typeofstring httpstatuscode intinfogetvaluehttp status code typeofint warnings liststringinfogetvaluewarnings typeofliststring now i am getting the following exception also in jsonnet codemember classname was not foundi also tried implementing the same solution as in this related question also got the same error above,['c#'] +400992,nsmutablearray arraywitharray compares same as nsarray mutablecopy given the following code example is the newmutablearay variable different depending on the two different initializations or the samensarray originalarray obj1 obj2 oj3nsmutablearray newmutablearray nilif thereissomedifference newmutablearray nsmutablearray arraywitharrayoriginalarray else newmutablearray originalarray mutablecopy,['objective-c'] +401057,how to make visual studio 2012 call the native 64bit visual c compiler instead of the 32bit x64 crosscompiler visual studio 2012 seems to always call the 32bit version of clexe located at programfilesx86microsoft visual studio 110vcbinx86 amd64 instead of the 64bit one located at programfilesx86microsoft visual studio 110vcbinamd64i tried prepending vcinstalldirbinamd64 to the beginning of the executable directories list in the vc directories section of the microsoftcppx64user property sheet but that does not work at all when i rebuild i get this errortracker error trk02 failed to execute command cprogram files x86microsoft visual studio 110vcbinamd64clexecusersmy profileappdatalocaltemptmpf3d817cafe064ad28e7dd62b2cb591c3rsp the operation identifier is not validhow can i make visual studio 2012 use the native 64bit c compiler,['c++'] +401064,android pre compiler error on 2101 android sdk i check out the old android project on a different pc and i get aandroid pre compiler null pointer exception error on every save so rjava cannot be generated the project is a library project using other library tothe new where the project is not working is system is 64 bit ubuntu adt eclipse android sdk tools 2101 android sdk platformtools 16the error isentry orgeclipsecoreresources 4 2 20130107 020715177 message problems occurred when invoking code from plugin orgeclipsecoreresources stack 0 javalangnullpointerexception at comandroidideeclipseadtinternalbuildbuildersprecompilerbuilderbuildprecompilerbuilderjava673 at orgeclipsecoreinternaleventsbuildmanager2runbuildmanagerjava728 at orgeclipsecoreruntimesaferunnerrunsaferunnerjava42 at orgeclipsecoreinternaleventsbuildmanagerbasicbuildbuildmanagerjava199 at orgeclipsecoreinternaleventsbuildmanagerbasicbuildbuildmanagerjava239 at orgeclipsecoreinternaleventsbuildmanager1runbuildmanagerjava292 at orgeclipsecoreruntimesaferunnerrunsaferunnerjava42 at orgeclipsecoreinternaleventsbuildmanagerbasicbuildbuildmanagerjava295 at orgeclipsecoreinternaleventsbuildmanagerbasicbuildloopbuildmanagerjava351 at orgeclipsecoreinternaleventsbuildmanagerbuildbuildmanagerjava374 at orgeclipsecoreinternaleventsautobuildjobdobuildautobuildjobjava143 at orgeclipsecoreinternaleventsautobuildjobrunautobuildjobjava241 at orgeclipsecoreinternaljobsworkerrunworkerjava53entry orgeclipsecoreresources 4 75 20130107 020715717 message errors occurred during the build subentry 1 comandroidideeclipseadt 4 75 20130107 020715717 message errors running builder android pre compiler on project myproject stack 0 javalangnullpointerexception at comandroidideeclipseadtinternalbuildbuildersprecompilerbuilderbuildprecompilerbuilderjava673 at orgeclipsecoreinternaleventsbuildmanager2runbuildmanagerjava728 at orgeclipsecoreruntimesaferunnerrunsaferunnerjava42 at orgeclipsecoreinternaleventsbuildmanagerbasicbuildbuildmanagerjava199 at orgeclipsecoreinternaleventsbuildmanagerbasicbuildbuildmanagerjava239 at orgeclipsecoreinternaleventsbuildmanager1runbuildmanagerjava292 at orgeclipsecoreruntimesaferunnerrunsaferunnerjava42 at orgeclipsecoreinternaleventsbuildmanagerbasicbuildbuildmanagerjava295 at orgeclipsecoreinternaleventsbuildmanagerbasicbuildloopbuildmanagerjava351 at orgeclipsecoreinternaleventsbuildmanagerbuildbuildmanagerjava374 at orgeclipsecoreinternaleventsautobuildjobdobuildautobuildjobjava143 at orgeclipsecoreinternaleventsautobuildjobrunautobuildjobjava241 at orgeclipsecoreinternaljobsworkerrunworkerjava53the project works on a old systemthe old system is 32 bit ubuntu 421 eclipse juno android sdk tools 21 git is used as a version control systemit is a very strange problem i have checkt all of the xml run them with lint to find a xml build problem but no luck on every save the i have the same error and the rjava is not generated thanks,['android'] +401075,writing a simple windows 7 gui app in ruby has anyone used ruby to develop a simple gui app for windows 7 which gui framework did you use i am considering tk or wxruby for the gui and using ocra to package will i need an installer too to install ruby and libs on the users machinethis is new territory for me and thoughts would be helpful,['ruby'] +401093,c class member callback simple examples i know this has been asked so many times and because of that it is difficult to dig through the cruft and find a simple example of what worksi have got this it is simple and it works for myclassinclude iostreamusing stdcoutusing stdendlclass myclass public myclass static void callbackmyclass instance int x private int private xclass eventhandler public void addhandlermyclass owner cout handler added endl let us pretend an event just occured ownercallbackowner1 eventhandler handlermyclassmyclass private x 5 handleraddhandlerthisvoid myclasscallbackmyclass instance int x cout x instanceprivate x endlint mainint argc char argv handler new eventhandler myclass myclass new myclassclass yourclass public yourclass static void callbackyourclass instance int xhow can that be rewritten so eventhandleraddhandler will work with both myclass and yourclass i am sorry but it is just the way my brain works i need to see a simple example of what works before i can comprehend whyhow it works if youve got a favorite way to make this work nows the time to show it off please markup that code and post it backeditit was answered but the answer was deleted before i could give the checkmarkthe answer in my case was a templated function changed addhandler to thisclass eventhandler public templatetypename t void addhandlert owner cout handler added endl let us pretend an event just occured ownercallbackowner1,['c++'] +401113,html5 audio element with dynamic source i have a basic audio playeraudio controlscontrols autoplaytrue looploopsource srcsongphp typeaudiompeg audioand instead of the source pointing directly to the mp3 file i have it pointed at a php file which then points to the mp3 file which works but when the current track is over the php file is pointing to a new mp3 file so the problem that i have is that when the player goes to loop with the new mp3 file it completely stops working is there any way around this is there a way to do this with a playlist or any other players,"['php', 'html']" +401119,implementing one to one and group chat in android i am developing an android app in which i have to implement chat messaging i would like one to one chat or a group chat but i have no idea how to start please help me with this stuff any help will be appreciated,['android'] +401120,firefox wordbreak breaks short words at random points i am breakwording a container so that extremely long words would not overflow while chrome and safari deal with this really well it seems that firefox and ie like to break words randomly even short words at the most ridiculous points see the screenshots belowhere is the code i am using to prevent break the wordsbreakword mswordbreak breakallwordbreak breakallwordbreak breakwordwebkithyphens automozhyphens autohyphens autothis is the the css i am using for the container and the textwrap position relativetextalign centermargin 40px auto 20pxpadding 50pxborder 4px double f7f7f7thisplay blockquotetext fontsize 40pxlineheight 50pxfontweight 400html div classwrap breakword div classrowfluid quotationmarksldquordquodiv span classquotetext having a partner definitely allows you to take more risks span span classauthorarianna huffingtonspan divwhy is this happening any clues on how i could get the words to break normally across all browsers firefox is definitely a priority thanks in advance,"['html', 'css']" +401156,detect screen onoff from ios service i am developing a network monitor app that runs in background as a service is it possible to get a notificationcall when the screen is turned on or offit exists in android by using the following codeprivate void registerscreenonoffreceiver intentfilter filter new intentfilterintentaction screen on filteraddactionintentaction screen off registerreceiverscreenonoffreceiver filterscreenonoffreceiver is then called when screen is turned onoff is there a similar solution for ioseditthe best i have found so far is uiapplicationprotecteddatawillbecomeunavailable detect if iphone screen is onoff but it require the user to enable data protection password protection on the device,"['objective-c', 'ios']" +401172,span exclusive exclusive spans cannot have a zero length can someone explain this error span exclusive exclusive spans cannot have a zero length i think it concerns with edittext is there a solution for itthis is my log107 142947654 dopenglrenderer24479 enabling debug mode 00107 143036954 esensormanager24479 thread start0107 143036959 dsensormanager24479 registerlistener handle 0 name lsm330dlc 3axis accelerometer delay 20 listener androidvieworientationeventlistenersensoreventlistenerimpl430e980107 143037139 espannablestringbuilder24479 span exclusive exclusive spans cannot have a zero length0107 143037139 espannablestringbuilder24479 span exclusive exclusive spans cannot have a zero length0107 143037419 iprocess24479 sending signal pid 24479 sig 90107 143037654 etrace25014 error opening trace file no such file or directory 20107 143037754 ddalvikvm25014 gc for alloc freed 108k 6 free 12258k12931k paused 15ms total 16ms0107 143037754 idalvikvmheap25014 grow heap frag case to 14860mb for 2457616byte allocation0107 1430379 ddalvikvm25014 gc concurrent freed 6k 5 free 14651k15367k paused 12ms2ms total 23ms0107 143037809 ddalvikvm25014 gc for alloc freed 0k 5 free 14651k15367k paused 11ms total 11ms0107 143037819 idalvikvmheap25014 grow heap frag case to 19018mb for 4367376byte allocation0107 143037834 ddalvikvm25014 gc concurrent freed 0k 4 free 18917k19655k paused 2ms2ms total 16ms0107 143037834 ddalvikvm25014 wait for concurrent gc blocked 3ms0107 143037894 ddalvikvm25014 gc for alloc freed 2660k 17 free 17674k21063k paused 13ms total 13ms0107 143037909 ddalvikvm25014 gc for alloc freed 688k 14 free 18212k21063k paused 10ms total 10ms0107 143037944 ddalvikvm25014 gc for alloc freed 1k 11 free 18890k21063k paused 12ms total 12ms0107 143037949 idalvikvmheap25014 grow heap frag case to 20170mb for 12356byte allocation0107 143037964 ddalvikvm25014 gc for alloc freed 0k 10 free 20097k279k paused 11ms total 11ms0107 143038019 dlibegl25014 loaded systemlibegllibegl maliso0107 143038024 dlibegl25014 loaded systemlibegllibglesv1 cm maliso0107 143038024 dlibegl25014 loaded systemlibegllibglesv2 maliso0107 143038029 d25014 device driver api match0107 143038029 d25014 device driver api version 100107 143038029 d25014 user space api version 100107 143038029 d25014 mali revisionlinuxr2p402rel0 build datefri sep 28 104256 kst 2012 0107 143038064 dopenglrenderer25014 enabling debug mode 0,['android'] +401181,getting class html not found error in laravel 4 working on a new project in laravel 4 aka illuminate i am trying to create the link to the style sheet in my masterbladephp template like so htmlstylecstylecss but this throws an error saying the class html was not found has it been removed or renamed in laravel 4 or am i forgetting anything else,['php'] +401194,what ruby based mobile crossplatform solution to use i am looking at ways to use ruby for mobile crossplatform development we need support for at least android en ios with windows phone and blackberry support as nice to have it will be an app that will end up in the app stores for the general public so it is not an enterprisey inhouse only thing so far i have foundrhodes covers all the platforms mentioned and open source we do not need the extra paid functionality from rhomobile right nowrubymotion ios only and costs 199 dolla unfortunately there is no trial version availableruboto android only and open sourcemobiruby ios only with android support planned open source but looks like it is not mature enough at the time of writing for our needswe also have a musthave use case in which we need access both the camera and the accelerometer simultaneously and draw data from the accelerometer on screen because this is so specific it is not supported in any crossplatform framework i have looked at including others like phonegap titanium etc and it looks like i will need to write native code for each platform to get this workingso far i am inclined to choose rhodes it is a proven framework and seems to be able to do everything i need including going native for the aforementioned use case another option would be to use both rubymotion and ruboto which are both solutions to write ruby instead of objectivec or java in theory i should be able to share common code like connectivity and storage across platforms although i could not find any examples of anybody successfully using these two for writing an app that works on both android and iosi am wondering if somebody can confirm my thinking or that i have overlooked something any additional insights are welcome of course,"['android', 'ios', 'ruby']" +401203,is there a recursivedescription method for the view controller hierarchy recursivedescription is very useful when debugging a hierarchy of views view controller hierarchies are also very important is there an equivalent for this,"['objective-c', 'ios']" +401209,when are class templates instantiated suppose you have the following illformed programstruct a aint int template typename tclass b b if sizeof t 1 throw a0 wrong a needs two arguments int main return 0gcc compiles this program without any errors clang refuses it with an erroris it justified to say thats it is not a bug in gcc because the template isnt instantiated what magic does clang do to find this errorwhat does the c standard say about those situations,['c++'] +401236,how to place textview using xy position i am new to androidcan anyone help mei need to show the textview values and button and imageview using xy positionhow its possiblemy coding xml version10 encodingutf8 relativelayout xmlnsandroid androidlayout widthmatch parent androidlayout heightmatch parent androidorientationvertical androidbackgrounddrawablelevelbg button androidididlevel1 androidlayout width560dp androidlayout heightwrap content androidlayout alignparenttoptrue androidlayout centerhorizontaltrue androidlayout margintop71dp androidbackgrounddrawablelevelbox textview androidididlevelno1 androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentlefttrue androidlayout alignparenttoptrue androidlayout margintop43dp androidbackgrounddrawablelevelno textview androidididlastshoot1 androidlayout widthwrap content androidlayout heightwrap content androidlayout alignbottomidlevel1 androidlayout alignparentlefttrue androidlayout marginbottom18dp androidlayout marginleft85dp androidtext134 androidtextsize20sp textview androidididbestshoot1 androidlayout widthwrap content androidlayout heightwrap content androidlayout alignbaselineidlastshoot1 androidlayout alignbottomidlastshoot1 androidlayout marginleft50dp androidlayout torightofidlastshoot1 androidtext123 androidtextsize20sp imageview androidididlevelonestar1 androidlayout widthwrap content androidlayout heightwrap content androidlayout alignbottomidbestshoot1 androidlayout marginleft17dp androidlayout marginbottom10dp androidlayout torightofidbestshoot1 androidsrcdrawablestar1 imageview androidididlevelonestar2 androidlayout widthwrap content androidlayout heightwrap content androidlayout aligntopidlevelonestar1 androidlayout torightofidlevelonestar1 androidsrcdrawablestar1 imageview androidididlevelonestar3 androidlayout widthwrap content androidlayout heightwrap content androidlayout aligntopidlevelonestar2 androidlayout torightofidlevelonestar2 androidlayout marginright2dp androidsrcdrawablestar1 i need this via programmatically up to 50 times it should be shown50 buttonscan any one suggest me the alternative waythanks for advance,['android'] +401237,java jdbc how to connect to oracle using tnsnamesora tnsnamesora file contains the databases and the their description host portis it possible to establish a connection relying on the file mentioned above say by providing only the db namein order to find this file i have to know the default oracle home i need to check in the windows registry for hkey local machinesoftwareoracle and then to have all the key x files and then check which one appears first on the path is there a way to automatically find this file on the client computer,['java'] +401239,nsdate finding nearest date to today i have a sorted array of nsdates can someone help with how i can find the date in the array that is closest to the current datei need to get the index of the date closest so that i can scroll to that date in my tableviewfor example if i have jan 1 2013 jan 6 2013 jan 9 2013 and jan 10 2013 i want the index of jan 6 2013hope that makes sense thanks for the helpupdatei am trying this nstimeinterval interval 0 nsuinteger indexofdate for nsdate date in m areventssorted ifabsdate timeintervalsincedatensdate date interval interval absdate timeintervalsincedatensdate date indexofdate m areventssorted indexofobjectdate,"['iphone', 'objective-c', 'ios']" +401240,playing local video in webview on android i am building an app with a webview thats supposed to play a video that is saved locally strangely the video player is not working with local video files it does play videos saved on a server thoughthe local files html and video are saved in a folder assetshtml testhere are the fileshtmldiv classvideocontainer pserverp video postervideostarpng controls source src videodivdiv classvideocontainer plocalp video postervideostarpng controls source srcbigbuckm4v videodivoncreate in activitywebview browser webview findviewbyidridbrowserwebsettings websettings browsergetsettingswebsettingssetjavascriptenabledtruewebsettingssetpluginstatewebsettingspluginstateon demandwebsettingssetallowfileaccessfromfileurlstruebrowsersetwebchromeclientnew webchromeclientbrowserloadurlfileandroid assethtml testvideohtmlthe first video works the second one does not i tried different values for the source neither of them worked for mesource srcbigbuckm4v source srcfileandroid assethtml testbigbuckm4v not sure if this is related but as soon as i press play logcat puts out this0107 121918073 emediaplayer32542 error 1 21474836480107 121918073 emediaplayer32542 error 12147483648i have no clue what the problem is here any help would be much appreciated,['android'] +401261,how to thisplay raw json data on a html page possible duplicatejson pretty print using javascript i would like to thisplay my raw json data on a html page just as jsonview does for example my raw json data is heyguy anumber243 anobject whoanuts anarray 1 2 thrh1ee morestuff awesometrue bogusfalse meaningnull japanesea link notlink is greatit comes from and what i want to achieve is like if you use chrome and have installed the jsonview plugini have tried but failed to understand how it works i would like to use a js script css to highlight to custom format my raw json data which is retrieved by ajax and finally put it on a html page in any position like into a div element are there any existing js libraries that can achieve this or how to do it,"['javascript', 'jquery', 'html', 'css']" +401285,how to use a qt quick 2 extension plugin on qml with qmlscene or qmlviewer5 i was create a test plugin as the qt5qml shared library using project templete librariesqt quick 2 extension plugin in qtcreator my developing environment is linux with qt500 and qtcreator26detail is append in the bottomthe source files on gist the source files are default generated without any changes the project name is untitled the uri is commycompanymycomponents and the object classname is myitem the source files in tmpuntitled as a srcdirand build it to output library file as libuntitledso qmldir and some object files in tmpuntitledbuild as a destdir ls tmpuntitledbuildmakefile libuntitledso moc myitemcpp moc myitemo moc untitled plugincpp moc untitled plugino myitemoqmldir untitled pluginobut i cannot use the library at tmptesttestqml as the test qml source with qmlscene command mkdir tmptest cd tmptest vim testqmltestqml on gist qmlscene testqmlit is fail and qml import trace log isqqmlimportdatabaseaddimportpath usrlib64qt5qmlqqmlimportdatabaseaddimportpath usrbinqqmlimportsfiletmptesttestqmladdimplicitimportqqmlimportsfiletmptesttestqmladdlibraryimport qtquick 20 as qqmlimportsfiletmptesttestqmlimportextension loaded usrlib64qt5qmlqtquick2qmldirqqmlimportdatabaseimportplugin qtquick from usrlib64qt5qmlqtquick2libqtquick2pluginsofiletmptesttestqml2 module commycompanymycomponents is not installedand try i option qmlscene testqml i tmpuntitledbuildthat is fail too log isqqmlimportdatabaseaddimportpath usrlib64qt5qmlqqmlimportdatabaseaddimportpath usrbinqqmlimportdatabaseaddimportpath tmpuntitledbuildqqmlimportsfiletmptesttestqmladdimplicitimportqqmlimportsfiletmptesttestqmladdlibraryimport qtquick 20 as qqmlimportsfiletmptesttestqmlimportextension loaded usrlib64qt5qmlqtquick2qmldirqqmlimportdatabaseimportplugin qtquick from usrlib64qt5qmlqtquick2libqtquick2pluginsofiletmptesttestqml2 module commycompanymycomponents is not installedand try with tmptestqmldir vim tmptestqmldirtmptestqmldir on gist that is fail logqqmlimportdatabaseaddimportpath usrlib64qt5qmlqqmlimportdatabaseaddimportpath usrbinqqmlimportsfiletmptesttestqmladdimplicitimportqqmlimportsfiletmptesttestqmlimportextension loaded tmptestqmldirqqmlimportdatabaseimportplugin tmptest from tmpuntitledbuildlibuntitledsomodule tmptest does not contain a module identifier directive it cannot be protected from external registrationsqqmlimportsfiletmptesttestqmladdlibraryimport qtquick 20 as qqmlimportsfiletmptesttestqmlimportextension loaded usrlib64qt5qmlqtquick2qmldirqqmlimportdatabaseimportplugin qtquick from usrlib64qt5qmlqtquick2libqtquick2pluginsofiletmptesttestqml2 module commycompanymycomponents is not installedhow to use the librarytmpuntitledbuildlibuntitledso in the test qmltmptestqml with qmlscene or qmlviewer5environment detail based on opensuse122 uname alinux lhmain 3411216desktop 1 smp preempt wed sep 26 170500 utc 2012 259fc87 x86 64 x86 64 x86 64 gnulinux g version head n1g suse linux 471 20120723 gcc4 7branch revision 189773 qmake v qmake version 30using qt version 500 in usrlib64 qtcreator version 21 devnull grep head n1qt creator 261 based on qt 500 qmlviewer5 v qml debugging is enabled only use this in a safe environmentqt qml viewer version 500references,['c++'] +401325,when to use and not to use the android application class i am considering using the android application class as a place to store temporary state and common code shared by other fragment activities in the app i would like to get more feedback as to whether it is a good place forshared constants like ids pref key names etcglobal variables ie settersgetters reflecting current ui state navigation selected fragment and in general temporary data that does not need to be persistedhooks for persisting data when certain conditions are triggeredupdating the ui after preference changesproviding an easy way to access the context from anywhere in the app including code where getapplication is not available eg via a static getter such as myappgetapp common methods that need the visibility of the global state variables and which would become too cumbersome to move away to dedicated classeswhat else would be appropriateusefulhandy to have in the activity class what would not be a good idea to keep in it and what would be the best alternatives and finally what you have found application to be best used for in your apps,['android'] +401410,expand environment variables in qt getenv equivalent i am looking for an equivalent of the getenv function,['c++'] +401411,how to create dynamic diagonal line from leftbottom to righttop corner i have created a simple layout where i have three divs which interact one is the logo in the middle of the screen and the other are two blocks which with jquery are moved out of the screen i used the skew option from css to apply a degree transformation i would like to apply the certain degree depending on the screen so this degree will apply to all screens correctly visual example for now i have this codehtmlhtml header link relstylesheet typetextcss hrefcssresetcss link relstylesheet typetextcss hrefcstylecss script typetextjavascript srcscript script typetextjavascript srcjsjqanimationjsscript header body div idpreloader div idblocktopdiv div idlogodiv div idloadlinediv div idblockbottomdiv div bodyhtmlcsshtml overflow hiddenpreloader width 100 height 100logo backgroundimage urlimglogotestpng width 300px height 300px thisplay block position fixed top 50 left 50 marginleft 150px margintop 150px zindex 10blocktop backgroundcolor f4ed width 100 height 100 position absolute top 0px left 50 zindex 10 transform skew45deg otransform skew45deg moztransform skew45deg webkittransform skew45degblockbottom backgroundcolor ff7f33 width 100 height 100 position absolute bottom 0px right 50 transform skew45deg otransform skew45deg moztransform skew45deg webkittransform skew45degjquerydocumentreadyfunction buttonclickfunction settimeoutfunction blocktopanimate left 120 opacity 0 800 blockbottomanimate right 120 opacity 0 800 logofadeout700 20,"['javascript', 'jquery']" +401439,impossible to initialize elixir i am starting with elixir and sql alchemy i have created a python file connecting with a mysql database to but as soon as i execute with python i get the error bellowrootraspberrypipythonmainflaskyonkipops python yonkipytraceback most recent call last file yonkipy line 1 in module from elixir import metadata entity field file usrlocallibpython27thistpackageselixir071py27eggelixir init py line 29 in module from elixirentity import entity entitybase entitymeta entitydescriptor file usrlocallibpython27thistpackageselixir071py27eggelixirentitypy line 17 in module from sqlalchemyorm import mapperextension mapper object session importerror cannot import name scopedsessioni have been looking for it but i do not find the reason this is the yonkipy file from elixir import metadata entity fieldfrom elixir import unicode unicodetext from elixir import class userentity username fieldstring64metadatabind mysqlrootnomasandroid42localhostyonkipopssessionbindecho truesetup allcreate alli think that it is maybe due to a required module not installed but i do not know which one,"['python', 'mysql']" +401455,authenticating a game center player on an online games servers clash of clans uses game center to authenticate and link a player with an existing remotely stored game statefrom what i can see a game is only provided a player identifier on client side is there a supported technique to securely authenticate a user instead of sending just the identifier which is an equivalent of authenticating with just a username,['ios'] +401523,how do i shrink a div using its center as reference point in jquery i have the following div div id shrinktest style positionabsolutetop100pxleft50marginleft50pxheight100pxwidth100pxbackgroundcolor red and i want to use jquerys animate to shrink the div to half of its size but keep the animation and position of my div centered i am trying shrinktestanimate height 50 width 50but it shrinks the div using its top left corner as reference how can i make it use its center as the reference pointthanks for any help,"['javascript', 'jquery', 'css', 'html']" +401544,android hidden application i am writing a legal spy program i want to make this program hidden on the launcher so that no icon is shown i tried to remove category androidnameandroidintentcategorylauncher line from androidmanifestxml but then the user cannot launch the application in first start mode configuration who have any ideas how can i do it,['android'] +401552,unable to call app code class from a codebehind i have a class in a file that is in the app code folder i am able to use this in an aspx file but not from a codebehind file how do i make it visible to a codebehindnote this is aspnet on mono and i am writing the classes directly not using an ide to compile themmy filesaspx file testappcodeaspx page languagec srctestappcodeaspxcs inheritstestappcodetestappcode autoeventwireuptrue html head titletest app code foldertitle head body form idcontactform runatserver asptextbox idname runatserver asptextbox asptextbox idage runatserver asptextbox aspbutton idsubmit runatserver textsubmit onclicksubmitform form bodyhtmlcode behind testappcodeaspxcsusing systemusing systemwebuiwebcontrolsnamespace testappcode public class testappcode systemwebuipage protected void submitformobject sender eventargs e it fails here with the error cs0246 the type or namespace name myappcodeclass could not be found are you missing a using directive or an assembly reference myappcodeclass m new myappcodeclass app code class app codemyappcodeclasscspublic class myappcodeclass public myappcodeclass i tried giving it a namespace but that does not fix the issue,['asp.net'] +401566,await a async void method call for unit testing i have a method that looks like thisprivate async void dostufflong idtolookup iorder order await orderservicelookupidasyncidtolookup close the search issearchshowing false other stuff in case you want to see itpublic delegatecommandlong dolookupcommand get set viewmodel dolookupcommand new delegatecommandlongdostuff i am trying to unit test it like thistestmethodpublic void testdostuff arrange myviewmodelissearchshowing true container is my unity container and it setup in the init method containerresolveiorderservicereturnsorderservice orderservice substituteforiorderservice orderservicelookupidasyncarganylong returnsnew taskiorder null act myviewmodeldolookupcommandexecute0 assert myviewmodelissearchshowingshouldbefalsemy assert is called before i get done with the mocked up lookupidasync in my normal code that is just what i want but for my unit test i do not want thati am converting to asyncawait from using backgroundworker with background worker this was functioning correctly because i could wait for the backgroundworker to finishbut there does not seem to be a way to wait for a async void methodhow can i unit test this method,"['c#', '.net']" +401575,drawbitmap with different rendering outputs nexus 7 versus other devices in my application i use drawbitmap to thisplay a low res bitmap while i am zooming it out i tested it on several devices galaxy tab kindle fire moto xoom and nexus 7 in all of them i get the same rendering quality except in nexus 7 you can see on the attached screen shots the difference the outer region is the one i am using drawbitmap something like thismsrcrectfsetsrc x1 src y1 src x2 src y2mdesrectfsetview x1 view y1 view x2 view y2mmatrixsetrecttorectmsrcrectf mdesrectf matrixscaletofitcentercanvasdrawbitmapbmp mmatrix mpagepaintif i try using the other variant drawbitmapbitmap bitmap rect src rectf dst paint paint without the matrix i get the same resultsi believe this issuedifference may be related to the hardware acceleration if i turn it off in manifest file i get the same results for all devices if i turn it on the rendering improves for all of them except nexus which still shows a more pixelated bitmap i have read that some routines are not supported in ha but even so i cannot understand what is happening in this case in a recent post of romain guy in his blog he comments note that alpha bitmaps only work with shaders when invoking the asimplea version of drawbitmap the variants that take a matrix or a source and destination rectangle are not supported with hardware acceleration at the momentcan someone shed some light on thisnexus 7 nexus 7 screen shotxoom or galaxy tab kindle fire xoom screen shot,['android'] +401602,how to set an environment variable in amazon elastic beanstalk python i have been working on a django application lately trying to get it to work with amazon elastic beanstalkin my ebextensionspythonconfig file i have set the followingoption settings namespace awselasticbeanstalkapplicationenvironment option name productionbucket value s3bucketname namespace awselasticbeanstalkapplicationenvironment option name productioncache value memcachedserversitecom11211however whenever i look on the server no such environment variables are set and as such are not accessible when i try osgetenvproductionbucketi came across this this page which appears to attempt to document all the namespaces i have also tried using param1 as the option name but have had similar resultshow can i set environment variables in amazon elastic beanstalkediti have also tried adding a command prior to all other commands which would just export an environment variablecommands 01 env vars command source scriptsenv vars this was also unsuccessful,['python'] +401634,arc bridge modifiers demystified i was asked recently by one of my friends about the new bridge modifiers that became active under arc he asked me if i knew which ones to use in specific times and what the difference between the different bridge modifiers were he asked meso how do they work when do i use them how do i use them and how do they work under the hood note this was supposed to be a share your knowledge type of question where i answered the question myself but i am not sure i set it up properly,['objective-c'] +401660,when to use indexphp instead of indexhtml i am relatively new to php there is a very basic thing that has been troubling me i understand that php is used to make web sites dynamic i also understand that php is one of the many server side scripting languages that can be used to make dynamic web sites however what i do not understand is that when do i need to use an indexphp page say for example if i have just a simple login page on my index page it could very well just be a simple html page as well right then why would i want to make it indexphp instead of indexhtml an example of a sample situation would be great,['php'] +401665,collections of zeroing weak references under arc how can i get an array of zeroing weak references under arc i do not want the array to retain the objects and i would like the array elements either to remove themselves when they are deallocated or set those entries to nilsimilarly how can i do that with a dictionary i do not want the dictionary to retain the values and again i would like the dictionary elements either to remove themselves when the values are deallocated or set the values to nil i need to retain the keys which are the unique identifiers at least until the corresponding values are deallocatedthese two questions cover similar groundnsarray of weak references to objects under archaving a list of unretained id objectsbut neither is asking for zeroing referencesper the documentation neither nspointerarray nor nshashmap support weak references under arc nsvalues nonretainedobjectvalue will not work either as it is nonzeroingthe only solution i see is to create my own nsvaluelike wrapper class with a weak property as this answer mentions near the end is there a better way i am not seeingi am developing for os x 107 and ios 60,['objective-c'] +401677,loding a weka model to a java code i have saved the result of weka classification by right clicking on the model and selecting save model now i want to load it and work with in my java application how can i do that models could be naive bias decision tree and regression i need to use these three modelsany suggestion or solution would be appreciatedthanks,['java'] +401740,automatically cropping an image with pythonpil can anyone help me figure out whats happening in my image autocropping script i have a png image with a large transparent areaspace i would like to be able to automatically crop that space out and leave the essentials original image has a squared canvas optimally it would be rectangular encapsulating just the moleculeheres the original imagedoing some googling i came across pilpython code that was reported to work however in my hands running the code below overcrops the imageimport imageimport sysimageimageopenl 2dpngimageloadimagesize imagesizeimagebox imagegetbboximagecomponents imagesplitrgbimage imagenewrgb imagesize 0rgbimagepasteimage maskimagecomponents3croppedbox rgbimagegetbboxprint imageboxprint croppedboxif imagebox croppedbox croppedimagecropcroppedbox print l 2dpng size imagesize new sizecroppedbox croppedsavel 2d croppedpngthe output is thiscan anyone more familiar with imageprocessingpli can help me figure out the issue,['python'] +401760,fileiofilesystemcopyfile vs systemiofilecopy i have a couple of questions about the difference between this 2 classes and these specific methods fileiofilesystemcopyfile and systemiofilecopyat the simplest level they both do the same thing when overloaded with sourcefile destinationfile and bool set to true to overwrite egfileiofilesystemcopyfilesource destination true systemiofilecopysource destination truemy two questions arewhat are the differences between the 2 with the overload shown because i cannot find or may be i missed the point anything on the msdn sitehow do you the kind person answering know the differences when it is not in the msdn documentation,['.net'] +401764,c issue with function overloading in an inherited class this is possibly a noob question sorry about that i faced with a weird issue recently when trying to mess around with some high level stuff in c function overloading and inheritancei will show a simple example just to demonstrate the problemthere are two classes classa and classb as belowclass classa public void funcchar class classbpublic classa public void funcintaccording to what i know classb should now posses two func functions overloaded due to different argumentsbut when trying this in the main methodint main int a char b20 classb objb objbfunca this one is fine objbfuncb heres the problem return 0it gives errors as the method void funcchar which is in the super class classa is not visible int the derived class classbhow can i overcome this is not this how overloading works in c i am new to c but in java i know i can make use of something like thisthough i have already found this thread which asks about a similar issues i think the two cases are different,['c++'] +401777,how to emulate a mobile android browser on desktop i am trying to debug a problem that only occurs when i access a mobile website from a mobile browser i strongly suspect that the root cause of the problem is due to caching that occurs when you access the same page several timesi can reproduce the problem consistently when i access the page from my android phone but if i use a desktop browser the problem never occursbecause i cannot use any developer tools on my android phone i really need to reproduce the problem from a desktop browser so that i have some way of debugging into it i have already tried using both firefox and chrome with an appropriate setting of the useragent header so that the mobile version of the site is thisplayed but that does not workis there a better way to emulate the behaviour of a mobile browser from the desktop in a manner that allows the clientside code can be debugged fwiw i am fairly confident that i could also reproduce the problem on an iphone but do not have one available,"['javascript', 'android']" +401791,getting windows serial number was getting machineguid from registry i am trying to fetch machineguid from the registry to create some level of binding with the os for my license system from the documentation i can usestring key hkey local machinesoftwaremicrosoftcryptographystring r stringregistrygetvaluekey machineguid objectdefaultto get it also the docs tell me that i get default when the name is not found or null if the key does not exist i should get a security exception if i have no accessthe above code gives me default which means the name is not found however if i look in the registry with regedit it is there how do i get the machineguid value from an application without administrator privilegesupdate when using regexe i have no problems getting the valueupdate i updated the title so people looking for a unique way of determining the windows install get here as well,['c#'] +401796,compare two sound in android is possible to compare a voice with already recorded voice in the phonebased on the comparison we can rate like good very good excellent etc most closed sound get high ratinganybody know is it possible in androidhelp is highly appreciable,['android'] +401832,why does jshint complain about linebreak within expression when passing the following code to jshint it considers the linebreak in the ifcondition to be bad saying bad line breaking before if 1 1 true consoleloghello worldhowever having the linebreak after is fine if 1 1 true consoleloghello worldwhy does jshint consider the first to be wrong and the latter to be right,['javascript'] +401852,drop cap with nsattributedstring i would like to do a drop cap first character in a uilabel using the attributedtext nsattributedstring property only like thisi have experimented with adjusting the base line for the range of the first character to a negative value and it works for aligning the top of the first char with the top of the rest of the first line but i have not found any way to make the other lines flow to the right of the drop capped charactercan this be solved using nsattributedstring only or do i have to split the string and render it myself using core text,['ios'] +401893,force importing module from current directory i have package p that has modules a and b a relies on bbpy contentsimport ahowever i want to ensure that b imports my a module from the same p package directory and not just any a module from pythonpathso i am trying to change bpy like the followingfrom import athis works as long as i import b when i am outside of p package directory given the following filestmp p apy bpy init pythe following works cd tmp echo import pb pythonthe following does not work cd tmpp echo import b pythontraceback most recent call last file stdin line 1 in module file bpy line 1 in module from import avalueerror attempted relative import in nonpackagewhyps i am using python 273,['python'] +401921,file upload in aspnet mvc 4 razor i am using asp net mvc 40 and vs10 i am a newbie in web application i have designed a page with html razor view here is some code of indexcshtmlviewbagtitle bap automationsection featured section classfeatured div classcontentwrapper hgroup classtitle h1viewbagtitleh1 h2viewbagmessageh2 hgroup form actionindex table edited bellow trform action methodpost tdupload excel file td tdinput typetext namenametxtfilenametd tdinput typebutton valueupload ididbtnupload namenamebtnuploadtd form tr tr tdcompany name td tdinput typetext td tdtd tr tr tdtd td alignrightinput typesubmit valueprocess td tdtd tr table form div sectioni am trying to upload an excel file in namebtnuploads click event clicking on this button we will be in this page just a file upload dialog will open and selecting the file the file location will be shown in the nametxtfilename textboxedit 1i have written some code from the suggested code httppost public actionresult indexhttppostedfilebase namebtnupload if namebtnuploadcontentlength 0 var filename pathgetfilenamenamebtnuploadfilename var path pathcombineservermappathapp datagiven excels filename namebtnuploadsaveaspath return redirecttoactionindex but this shows following error server error in applicationthe resource cannot be founddescription http 404 the resource you are looking for or one of its dependencies could have been removed had its name changed or is temporarily unavailable please review the following url and make sure that it is spelled correctly requested url,['c#'] +401923,how to extend a base member field i have a class base and a field of type infobase holding some information aspecialization ext of base needs to hold additional information infoexttherefore ext assigns an infoext to baseinfo however i ran into problems whenbase replaces info since it would assign info new infobase hence theadditional info of infoext is losttherefore i created an abstract void assign in base variant a in thiscase info needs to be casted to infoext everytime it is used in extin variant b i have thus additionally created abstract infobase info variant a variant b infobase base base name string info infobase abstract infobase info abstract void assign abstract void assign infoext ext ext id int void assign infoext info info new infoext infobase info return info void assign info new infoext class infobase public string name abstract class base abstract public void assign abstract infobase info class infoext extends infobase public int id class ext extends base public infoext info override infobase info return info override public void assign info new infoext is this a common situation with a generic way how to deal with it are thereany drawbacks to variant abhow can i provide an info field in base that subclasses can use to store extended informationthank you for your consideration,['java'] +401928,split by a character in javascript but not contiguous ones here is the casevar stringexample hellogoodbyehellovar parts stringexamplesplitoutputhellogoodbyehelloi need this outputhellogoodbyehellocontiguous repeated characters must be ignored just take the single to splitmaybe some regex,['javascript'] +401937,accessing objects in json array javascript possible duplicatei have a nested data structure json how can i access a specific value i have a service that returns nested objects in a json array how can i loop through the objects and print the desired datathis is my result item1 sourceuuid 5599ffac4b9947c79370a25e7e465429 targetuuid 5599ffac4b9947c79370a25e7ef item2 sourceuuid bf63fe508b2b488db565009fcaebdb45 targetuuid 1 item3 sourceuuid 05fd96f6544781860209fedc0cdd35 targetuuid 05fd96f6544781860209fedc0cdd35 this is what i want to print for each item item1 item2 item3 item name item1source 5599ffac4b9947c79370a25e7e465429target 5599ffac4b9947c79370a25e7efso far i triedfor var i 0 length datalength i length i for obj in datai consolelogobjthis only returns item1 item2 etc but i do not know how access sourceuuid etc from there,['javascript'] +401959,why are null and undefined of the type domwindow when you run the following code in the browser or in nodejs you get the expected outcomes listed in the commentsobjectprototypetostringcallundefined object undefinedobjectprototypetostringcallnull object nullwhen you run that code in phantomjs however the output is object domwindow in both casesthis seems strange since undefined and null are both native types the typeof operator appears to work as it does in other environments including the typeof null object quirk so it would appear that phantomjs does at least have the concept of the undefined typetypeof undefined undefinedit also claims that objectprototypetostring contains native code which may indicate that phantom itself is not doing anything to modify the implementation i do not know if that is the case or not though i have not been able to find anything useful in the sourceobjectprototypetostringtostring function tostring native code so why does phantomjs not use or at least expose the correct class property values for null and undefined and is there a way i change that i know i could use a different method to determine type but i would rather not have to,['javascript'] +401988,setting generic types of swingworker as void possible duplicatewhat is the difference between javalangvoid and void i wanted to create a concrete class for swingworker with both final and intermediate result types as void i wrote the following codeclass answerworker extends swingworkervoid void protected void doinbackground systemoutprintlnwhat is your problem this gave me the following errormultiple markers at this line syntax error on token void dimensions expected after this token syntax error on token void dimensions expected after this tokenhowever when i changed the code from void to void ie small v to capital v it worked fine although i was still forced to return null at the end of doinbackground methodwhy is this i know void is a class in javalang package but the documentation does not says much about it atleast not which i could follow pthanx in advance,['java'] +402071,thisplaying data when using bootstrap framework i have an edit form which formhorizontal and controllabel however now i want to thisplay one record to the user for example details of a users profile so i envision something like thisfirst name foolast name barjob somethingwhat is the best way to do this using bootstrap framework i wanted to use the same structure as my edit form but since i will be showing data i cannot used the formhorizontal class if i use the table tag then what class could i use,['html'] +402101,mapping a specific servlet to be the default servlet in tomcat i am trying to implement a servlet that gets raw requests and decide either to process them or forward them to another backend server it is similar to a loadbalancer where a received request is forwarded to one of the in my case 2 destinations one of the destination is remote on another host furthermore the requests could come to the root since i want to get raw requests i implemented my own servlet subclassing httpservlet and that works great my servlet looks likepublic class myproxyservlet extends httpservlet override protected void doposthttpservletrequest req httpservletresponse resp throws servletexception ioexception processorforwardreq resp also doget dohead since the service i want to process may send requests to the root i would like to map my servlet to be the default servlet thereby receiving any request that does not have an explicit servlet mapping assume my servlet us name is myservlet and is running along side of another servlet foo i expect all requests in the form of to be delivered to foo and everything else eg bar myservlet to myservlet looking at earlier posts eg root mapping here and here or url rewriting here i thought i figured it out but it does not work here is my webxmlwebapp servlet servletnameproxyservletservletname servletclasscommycompanymyproxyservletservletclass loadonstartup1loadonstartup servlet servletmapping servletnameproxyservletservletname urlpatternurlpattern servletmappingwebappin the above webxml for urlpattern i tried and and empty ie urlpatternurlpattern all behave the same requests to root goes to tomcats default servlet requests to myservlet are handled by myservlet requests to fubar are always 404is there a way of turning my servlet to be the default ie any request that does not map specifically to a servlet comes to mine it is even acceptable to receive all requests since i can deploy this servlet in its own container in case it matters i am using tomcat 7030 on ubuntu 1210,['java'] +402132,ruby copy a paperclip attachment from one model to another i have two models like this model 1 card contains a representation of data of interest for front page attachment name cardimagemodel 2 user contains the user attachment name avatar when i create a new card i want the avatar from the user model to be copied to the card model as a new cardimage is there a simple one liner for thisrubyrailspaperclip,"['ruby-on-rails', 'ruby']" +402136,lambda assigning local variables consider the following sourcestatic void mainstring args bool test action lambda test true lambda if test consolewritelineokit should compile right well it does not my question is according to c standard should this code compile or is this a compiler bugthe error messageuse of unassigned local variable testnote i know how to fix the error and i partially know why does it happen however the local variable is assigned unconditionally and i guess that compiler should notice that but it does not i wonder whycomment for answers c allows declaring unassigned variables and that is actually quite useful iebool cond1 cond2if someconditions cond1 someotherconditions1 cond2 someotherconditions2else cond1 someotherconditions3 cond2 someotherconditions4compiler compiles this code properly and i think that leaving variables unassigned actually makes the code a little bit better becauseit tells the reader that values are assigned later mostly probably in the following conditional statementforces the programmer to assign the variables in all branches of internal conditions if it was the purpose of this code from the beginning because compiler will refuse to compile the code if one of the branches does not assign one of themon the marginthat is even more interesting consider the same example in cint mainint argc char argv bool test comment or uncomment this block auto lambda test true lambda if test printfok return 0if you comment the block out compilation ends with warningmaincpp12 warning c4700 uninitialized local variable test usedhowever if you remove the comment compiler emits no warnings whatsoever it seems to me that it is able to determine if the variable is set after all,"['c#', 'c++']" +402155,replace any string between quotes problemcannot find a consistent way to replace a random string between quotes with a specific string i want any help would be greatly appreciated examplestring str1 test1should becomestring str2 test31but also work forstring str3 testfoobarbasically i want to turn thisstring str4 testantyhingcangohereinto thisstring str4 test31have triedcase insensitive regex without using regexoptions enumerationhow do you do caseinsensitive string replacement using regular expressions replace any character in between anytext and with an empty string using regex replace string in between occurrencesreplace a string between two stringscurrent code regex removename new regexvariable regexoptionsignorecase string convertseccons removenamereplacerulefixed 31returns errorsystemargumentexception was caught messageparsing variable unrecognized grouping construct sourcesystem stacktrace at systemtextregularexpressionsregexparserscangroupopen at systemtextregularexpressionsregexparserscanregex at systemtextregularexpressionsregexparserparsestring re regexoptions op at systemtextregularexpressionsregexctorstring pattern regexoptions options boolean usecache at systemtextregularexpressionsregexctorstring pattern regexoptions options at applicationapplicationinsertgroupidstring rule in cuserswinserv8documentsvisual studio 2010projectsapplicationapplicationmainformlaunchercsline 298 at applicationapplicationxmlquerydbstring xmlsavelocation textwriter tw string rulename in cuserswinserv8documentsvisual studio 2010projectsapplicationapplicationmainformlaunchercsline 250 innerexception found answerstring s regexreplacerulefixed variable variable31rulefixed si found this code sample at replace any character in between anytext and with an empty string using regex which is one of the links i previously posted and just had skipped over this syntax because i thought it wouldnt handle what i needed,['c#'] +402163,fastest technique to pass messages between processes on linux what is the fastest technology to send messages between c application processes on linux i am vaguely aware that the following techniques are on the tabletcpudpsocketspipesnamed pipesmemorymapped filesare there any more ways and what is the fastest,['c++'] +402200,i am getting an implicit conversion from enumeration type warning in xcode for ios and i do not know why with this codensdatadetector detector nsdatadetector datadetectorwithtypesnstextcheckingtypelink errorerrori am getting this warningimplicit conversion from enumeration type enum nstextcheckingtype to different enumeration type nstextcheckingtypes aka enum nstextcheckingtypescan someone explain to me why i am getting this warning and how to fix it,"['iphone', 'ios']" +402203,css stretched background image i have a large image to be use as a backgroundimage of a page what i want is that the height of the image will be stretched to fill the height of the page it should be centered alsobackground black urlimagebackgroundjpg norepeat fixed center,['css'] +402276,why is method overloading and overriding needed in java possible duplicatepolymorphism vs overriding vs overloading i am struggling to know why method overloading and overriding needed in java i have read some articles regarding this but not able to catch why it is needed practicallyi also visited the below url in stackoverflow but i am not clear in this topic yetjava overloading and overridingany practical example will be appreciated thanks in advance,['java'] +402391,what is difference between memorycache vs objectcache in net 40 what is difference between net 40 memorycache vs objectcachewhere to use which object,"['c#', '.net']" +402397,how to increase android virtual device max heap size i would like to increase the android virtual device map heap size with eclipse i tried to set the max vm application heap size to 128 in the eclipse avd manager but it does not work the line runtimegetruntimemaxmemory10241024 always returns 48 no matter the set heap size device ram size is set to 512 selected target is android 412 api level 16 moreover i have set androidlargeheaptrue in the manifest fileis there a limit to max heap size is 128mib to much or is there another file to edit or parameter to set,['android'] +402421,comparing two strings in c this code is not working the comparison is not being done why all names get past the if printfenter product nscanfs nameit2printfenter description nscanfs descriptioniprintfenter quantity nscanfd qtyiprintfenter order quantity nscanfs ordqtyiwhilefscanffp4 s s d sn namet2description2qty2ordqty2 eof ifnamet2 nameit2 fprintffpt2 s s d sn namet2 description2 qty2 ordqty2,['c'] +402432,replace google now gesture if you want to start google now on nexus devices you swipeup with a simple gesture from the navbar i want go replace this feature with my own app if you swipe the apicker comes and asks you which app do you want to start my app or google now how can i implement this i have found an example which runs without root,['android'] +402445,how to prevent file hotlink from internet download manager idm am having some issue fixing media file hotlink or download using idm am working on serving a video file using php and it works fine but i notice that idm installed on my computer was able to add download box to the video i am playing using jwplayeri change the structure of code and added htaccess to rewrite the link so that the direct access to the file is not thisplaymysitecomfilephpmyvideoflv mysitecomapifileju78vhx5uhi was able to implement this in jwplayer and it works when serving with php yet the same idm fetch my video file i search for other means which is htaccess and it is belowrewriteengine onrewritecond http referer httpmysitecom ncrewritecond http referer rewriterule mp4flvmp4mp3 videothieveflv lthis only work for web browsers and does not stop idm software i found another php referer validator which check the refere linkif strpos serverhttp referermysitecom0 headerlocation whateverphp else headerlocation indexphp nb i found out that idm sent this information to my scriptuser agentmozilla4020compatible20msie208020windows20nt206020trident40http referermysitecomapifileju78vhx5uh the same with the page where my video is been playedplease how else am i to prevent hotlinking from this software because this website is serving free video streaming and i do not want my video downloaded,['php'] +402464,javascript how to get parent element by selector examplediv someattrparentdiv we need to get it from child table td div idmydivdiv td tabledivi want to get parent by some selector from inner div element in example with mydiv class how to get it without jquery only jssomething like var div documentgetelementbyidmydivdivsomeparentfindmethodsome selector,['javascript'] +402492,how to assert that an expression does not compile i have written a piece of framework that adds the possibility for typesafe invocations of its interface now when writing the junit tests i want to show that specific expressions that earlier led to runtime errors are checked by the compiler now this does not compile because nameprop is of type propertystringinteger name interfacegetpropertynamepropprobably it would be best to simply comment that code out and leave it like that i was just wondering whether it would be possible with some testing framework to write something likeassertcompilationerror integer name interfacegetpropertynamepropi explicitly do not want to fiddle around with invocations of javac with a custom classpath myself if there is the possibility for a general solution that could be extracted to framework code and donated to junit or testng such a solution would be welcome as well,['java'] +402500,wcf why make it more complicated today i have a question regarding style of wcf communicationi sometimes refuse a bit so use things programmatically want to have control myself and i do not like huge sometimes communication between 2 program parts are needed sometimes on the same machine sometimes on networkso i tried to use wcf programmatically instead of using configuration files svcutil and so onif i use the followinga define a contractservicecontract public interface imycontract operationcontract bool dosomethingstring something in b programm some codepublic class mysomething imycontract public bool dosomethingstring something in ifstringisnulloremptysomething in return false return true and then programmaticly host ituri baseaddress new urinettcplocalhost48080mysimpleservice using servicehost host new servicehosttypeofmycontract baseaddress hostaddserviceendpointtypeofimycontract new nettcpbinding hostopen consolewritelineenter to stop the service consolereadline hostcloseand later just consume it from another programvar binding new nettcpbinding var endpoint new endpointaddressnettcplocalhost48080mysimpleservice var channelfactory new channelfactoryimycontractbinding endpoint imycontract client null try client channelfactorycreatechannel bool test clientdosomething icommunicationobjectclientclose catch exception ex if client null icommunicationobjectclientabort what would be the drawbackwouldnt it be easier to understandcould such a thing cause other problemsi am mostly interested in this because i think it is quite annoying to use svcutil and so one just because of a class change which can simple handled manually if the wcf service is only used for cumminication of own programsso what am i missingis it just a bad style to do things manually instead with large unread xml files,['c#'] +402534,passing data from a c process to a c process this is my first time posting a question here i usually find answers in the archive but i am stumped this time i am grabbing data off of a joystick using some code from the vendor that uses windows driver kit the data is in the form of an array with 6 elements it is a 6 degree of freedom mouse i had already written the code that needs to grab the data and it is in cit uses the standard library a lot with vectors and what not it seems that using the standard library with wdk is a big head ache that i spent a couple days trying to get to work but failed my next idea was to use boostinterprocess but this to is difficult to use with wdk for the same reasons i am wondering if there is a way to share memory between a c process and c process i would like to write the array to memory using a c program and read it in from a c program it needs to happen very fast and there should be a way to make sure i do not read it in the middle of a write mutex any ideas or suggestions are welcome editi made a dll instead now i just have a dll that has a getvalues function that i can call from my c project i had to use the pimpl idiom to hide the c stuff though thanks for the help guys,"['c++', 'c']" +402535,using setinterval in angularjs factory i was trying the code given in angularjs docs given here it just implements a time factory and uses timeout to update the time object after each secondangularmoduletimeapp factorytime functiontimeout var time function tick timenow new datetostring timeouttick 10 how to do it using setinterval return timehow would i do it using setinterval function instead of timeout i know that one need to use scopeapply to enter the angular execution context but how would that work in a factory function i mean in a controller we have a scope but we do not have scope in a factory function,['javascript'] +402545,android listview with cursoradapter has incorrect scroll position after requery is called when new items are added heres the scenario i have got a simple listview thisplaying a twitter feed i have a cursoradapter which is fetching tweets from sqlite when i call requery on my cursor i expect that new tweets will be fetched that have since been added to the database this all works fine and the new items are even visible in the listview after this happensthe problem is the scroll position seems to be saved based on the item position offset so let us say the first visible position in my listview is 4 when i requery and 2 new items are added to the top of the list the listview keeps the first visible item scroll position as 4 however since there is two new items in the list i now see a different item at position 4 than before i refreshed this image illustrates the before and afternotice how before tweet d is the first visible item and afterwards tweet b now becomes the first visible itemmy question is how do i keep the same scroll position based on cursor positon when calling requery so that in this example tweet d would still be the first visible item after a requery,['android'] +402589,injecting dependent services when unit testing angularjs services i am testing service a but service a depends on service b ie service b is injected into service ai have seen this question but my case is a bit different because in my opinion it makes more sense to mock service b instead of injecting an actual instance of service b i would mock it with a jasmine spyheres a sample testdescribesample test suite function beforeeachfunction modulemodulethatcontainsservicea inject servicea functionservice thisservice service itcan create an instance of the service function expectthisservicetobedefined the error i get iserror unknown provider servicebproviderhow could i do something like this,['javascript'] +402598,how does servicestack handle concurrent calls how does servicestack handle concurrent calls i am looking for equivalent of concurrencymodemultiple in wcfmy wcf services have this attribute set servicebehaviorinstancecontextmode instancecontextmodepercall concurrencymode concurrencymodemultiple usesynchronizationcontext falsedo i need to enable anything in servicestack to get it to use multiple threads for each call,['c#'] +402601,how to show only integer values on yaxis of highchart we have a set of a data that contains counts of instances of events these can only be integers when we thisplay data that has a high enough yvalue the yaxis labels are integers however when we zoom in to ranges of data that have under y 5 we see the tick markers show things like 05 075 15 etc how can we force the yaxis labels to only show integer valueshere is an example bit of code with some data as you zoom in to the lower value region of the chart you can see what i meanthis is the current yaxis setupyaxis labels style fontsize 9px width 175px title text,['javascript'] +402610,interleave different length lists elimating duplicates and preserve order in python i have two lists lets saykeys1 a b c d e h ikeys2 a b e f g h j khow do i create a merged list without duplicates that preserve the order of both lists inserting the missing elements where they belong like somerged a b c d e f g h i j knote that the elements can be compared against equality but not ordered they are complex stringsupdate the elements cannot be ordered by comparing them but they have a order based on their occurrence in the original listsupdate in case of contradiction different order in both input lists any output containing all elements is valid of course with bonus points if the solution shows common sense in preserving most of the orderupdate again as some comments still argue about it the lists normally do not contradict each other in terms of the order of the common elements in case they do the algorithm needs to handle that error gracefullyi started with a version that iterates over the lists with next to advance just the list containing the unmatched elements but next just does not know when to stopmerged l iterkeys1h iterkeys2l lnexth hnextfor i in rangemaxlenkeys1 keys2 if l h if l not in merged mergedappendl l lnext h hnext elif l not in keys2 if l not in merged mergedappendl l lnext elif h not in keys1 if h not in merged mergedappendh h hnext else just in case the input is badly ordered if l not in merged mergedappendl l lnext if h not in merged mergedappendh h hnext print mergedthis obviously does not work as next will cause an exception for the shortest list now i could update my code to catch that exception every time i call next but the code already is quite unpythonic and this would clearly burst the bubbledoes anyone have a better idea of how to iterate over those lists to combine the elementsbonus points if i can do it for three lists in one go,['python'] +402612,what is the difference between function and function possible duplicatea vs a in javascript closures is there any difference between function and function in this example both works the same waywindowonloadfunction var a functioni return a i 1 var b functioni return b i 2 consoleloga a consolelogb b,['javascript'] +402649,java spring scheduled tasks executing twice quick questioni have a simple test method here that is set to run every 5 seconds and it does but looking at the systemout you can see it appears to be doing something oddscheduledcron5 public void testscheduledmethod systemoutprintlnnew date running testscheduledmethodoutputwed jan 09 164915 gmt 2013 running testscheduledmethodwed jan 09 164915 gmt 2013 running testscheduledmethodwed jan 09 164920 gmt 2013 running testscheduledmethodwed jan 09 164920 gmt 2013 running testscheduledmethodwed jan 09 164925 gmt 2013 running testscheduledmethodwed jan 09 164925 gmt 2013 running testscheduledmethodwed jan 09 164930 gmt 2013 running testscheduledmethodwed jan 09 164930 gmt 2013 running testscheduledmethodwhy is it running twice appear each timethanks in advance for your time,['java'] +402673,devmaster in composerjson is this madness i am using composer in symfony2 projects and often get errors updating librariesmany libraries most to my experience use devmaster as version for their dependencies or worse they use whenever something is committed to the master branch you get to update the library and the chances of an api change are higher as time goes by what today in master is version 121 tomorrow could be 127 with no harm and become later 17 or 2x with sure incompatibilitiesmy questions arehow did we get to this point is it a practice suggested from high profile sourceswhat can iwe do to sensibilize the authors to this subjector am i mad,['php'] +402692,java synchronized method how does it work i think i know this but would like it confirmingobviously the synchronized blocks other threads from accessing it but i see and awful lot of examples such as public synchronized void setvalueint value balancevalue am i right in thinking that if the method only does one line like the above then there is no point in it being synchronizedthanks,['java'] +402755,locate an ascii art image inside a body of text with a certain toleration for error are there any algorithms that would find the following asciiart image inside the following body of textcomplete file here i must highlight the ascii art image in yellow which corresponds to the complete shape see the picture attachedi have to search a file which contains the rough shape but not completely a number of can be missing the tolerance for a missing in the shape should be set by handnow i have two 2d arrays data array 100100 and the slimetorpedo array 1311code for how to make the detection as stated by kjartan 34 bullet int match 0 for int i 0 i 100 i for int j 0 j 100 j compare dataarrij with slimetorpedoarrij look for checked position in the picture which corresponds to a checked position in the slime torpedo array match what would be general guidance for how to approach this problem,['java'] +402812,requestsecuritytoken using windows credentials and net 45 wif can anyone point to sample code for actively issuing a requestsecuritytoken using the nt credentials of the threadcurrentprincipal as claimsprincipalthe scenario is an aspnet web app with windows authentication enabled so there is an authenticated windowsidentity my desire is to call the sts actively rather than enabling passiveredirect and to do this using the net 45 identity librariesmost code samples such as claims helper for windows phone or using an active sts set the credentials with a usernamepwd input and usernamewstrustbindingi thought the solution might involve impersonation or a call to channelfactorycreatechannelwithactastoken with the a token created from the windows identity the following net45 code does get a genericxmlsecuritytoken when hitting an adfsservicestrust13windowsmixed endpointhowever the claims are for the domain account under which the site is running and not the domain account of the authenticated user when i switch the endpoint to adfsservicestrust13kerberossmixed i get cannot negotiate errors as documented in several questions and forums but i cannot apply any offered solutions with net 45 one of the classes not ported over from microsoftidentitymodel is the kerberoswstrustbindingpublic static void callsts try var wsmod federatedauthenticationwsfederationauthenticationmodule var appliestoep new endpointreferencewsmodrealm var stsep new endpointaddressnew uriwsmodissuer endpointidentitycreatespnidentitystsspn var msgbinding new ws2007httpbindingsecuritymodetransportwithmessagecredential false msgbindingsecuritymessageestablishsecuritycontext false msgbindingsecuritymessageclientcredentialtype messagecredentialtypewindows usingvar factory new wstrustchannelfactorymsgbinding stsep factorycredentialssupportinteractive false factorytrustversion trustversionwstrust13 var myrst new requestsecuritytoken requesttype requesttypesissue appliesto appliestoep keytype keytypesbearer var channel factorycreatechannel var ststoken channelissuemyrst as genericxmlsecuritytoken ifststoken null logdebugformatreply token is 0 ststokengettypename var handlers federatedauthenticationfederationconfigurationidentityconfigurationsecuritytokenhandlers var token handlersreadtokennew xmltextreadernew stringreaderststokentokenxmlouterxml var identity handlersvalidatetokentokenfirst todo write to session else logdebugreply token is null catchexception ex logerrorrstcall has failed ex for leastprivilege suggestion i add this code var user threadcurrentprincipal as claimsprincipalvar winid useridentity as windowsidentityifwinid null shows my domain account after i was prompted for credentials my domain account does not exist on the client machine so it is a true domain credential logdebugformatwindowsidentity name is 0 winidnameusingwinidimpersonate again shows my domain account logdebugformatimpersonation context 0 windowsidentitygetcurrenttruename var channel factorycreatechannel var ststoken channelissuemyrst as genericxmlsecuritytoken request is issued but results in securitynegotiationexception the caller was not authenticated by the servicewhich fails with the caller was not authenticated by the service the same sts will authenticate my domain account in a passive redirect scenarioso although i know i am doing something wrong the account itself should be recognizedupdatei received a notification that this question received a notable number of views so i will offer the following as one workaroundalthough we configured our servers for delegation as dominick suggested below we still did not surmount the doublehop issue if i remember we hit a roadblock from simple network management policies above our local it that any enterprise might hit as wellso while impersonating over a doublehop against a server with windows authentication is not allowed credentials can be impersonated over a double hop using basic authentication this may or may not be an acceptable situation intranet for our case if you do you would add msgbindingsecuritymessagenegotiateservicecredential trueto the above channelbinding configuration,['asp.net'] +402819,how to attach mdf with no log file i am trying to attach yafnetmdf in sql server management studio which does not have a log file i get the error below any ideas how this can be donean exception occurred while executing a transactsql statement or batch microsoftsqlserverconnectioninfounable to open the physical file csql logsyafnet logldf operating system error 2 2the system cannot find the file specified microsoft sql server error 5120,['sql'] +402864,getting url to a webapp context the base url sometimes you need to construct a full url to your web app context inside a servletjspwhatever based on httpservletrequestsomething like servlet api does not have a single method to achieve thisthe straightforward approach is to append all url components to a stringbuffer like ctxurl sbappendreqgetschemeappendappendreqgetgetservernameappendappendreqgetserverport etci wonder if there is anything wrong with this alternative which is 10 times fasterctxurl reqgetrequesturlctxurl ctxurlsubstring0 ctxurllastindexofwill two above methods always produce the same result,['java'] +402869,how to close modal by clicking on background twitter bootstrap hi i set the default for twitter bootstrap modals to not close when the user clicks on the backgroundfnmodaldefaults backdrop static keyboard false show falsehowever there is one particular scenario whereby i need to overwrite this default to allow the user to click the background to close the modali tried to overwrite it when thisplaying the particular modalmodal to be thisplayed and allow user to close it by clicking on backgroundview new onethingadayviewsmusesmusemodalview model optionsmusemodalhtml viewrenderelmodalbind shown modalmodal backdrop true modalunbind showmodalmodalshowhowever my code above does not work anyone has any idea how can modify the code to make it work also the code above seem to be changing the default behavior of all my modals in the app which is not what i want how do i change the backdrop just for this particular modal ie musemodalview thanks,['jquery'] +402872,updating session after revoking individual permissions i am trying to give users an option to setrevoke publishing permission via checkbox facebook sdk for android code is provided below everything works fine except that after revoking the code responsible for checking publishing permissions fails miserably i understand that session has no way of knowing if user has revoked any permissions after loggin in what is the correct way to handle this kind of situation do i have to query available permissions manually or is there a way to seamlessly recreate session with basic permissions public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate publishcheckbox checkbox viewfindviewbyidridpublishcheckbox publishcheckboxsetonclicklistenernew viewonclicklistener override public void onclickview v checkbox chb checkbox v if chbischecked checkforpublishpermission false requestpublishpermissions else removepublishpermissions private void requestpublishpermissions session session sessiongetactivesession if session null sessionisopened sessionnewpermissionsrequest newpermissionsrequest new sessionnewpermissionsrequestthis permissionssetrequestcodereauth activity code newpermissionsrequestsetcallbackcallback sessionrequestnewpublishpermissionsnewpermissionsrequest private void removepublishpermissions request r new requestsessiongetactivesession publish actions permission path null httpmethoddelete rsetcallbacknew requestcallback override public void oncompletedresponse response publishcheckboxsetenabledtrue rexecuteasync publishcheckboxsetenabledfalseprivate boolean checkforpublishpermission boolean result false session session sessiongetactivesession if session null sessionisopened result false else liststring permissions sessiongetpermissions if permissionscontainsallpermissions result true returnresult private void onsessionstatechangesession session sessionstate state exception exception if stateisopened publishcheckboxsetcheckedcheckforpublishpermission else if stateisclosed,['android'] +402893,proxy settings in a java program i am trying to connect to a web service with a client generated from wsdl through a java program in eclipse i am passing my request through a proxy server but it seems that request is not getting through same proxy settings are working fine on soapui please find below the system properties set by me properties props new propertiessystemgetproperties propsputhttpproxyset true propsputhttpproxyhost 10x propsputhttpproxyport 80propsputhttpproxyuserdomainnamexpropsputhttpproxypasswordxproperties newprops new propertiespropsjava program throws an exception as javanetunknownhostexceptionwhat is it i am missing,['java'] +402913,how to delete a specific file from folder using aspnet heres the deal i got a datagridviewer which is called gridview1 and a fileupload1 when i upload a file it updates the gridview1 and table in database with the file name and path and stores the said file in folder mag but now what i want to do is the reverse i got how to use the gridview to delete the table entry but deleting the file from folder mag is not working have used the following code in c or codebehindprotected void gridview1 delobject sender eventargs e string deletethis gridview1selectedrowcells0text string files directorygetfilesiwebsitewebsite3mag foreach string file in files if filetouppercontainsdeletethistoupper filedeletefile it gives me error object reference not set to an instance of an object pls tell me what im doing wrong am new and do not have to in depth understanding of the platform so any and all help will be appreciatedthanks in advancemark here is the answer i found thanks tammy and everyone else for all the answersok here the deal target function delete file details from gridview and database table and file from project folder where the file is stored in script section of gridview you would want to includeonrowdeletingfuntionnamenotonselectedindexchanged funtionnameoronrowdeletedfuntionnamethen in c codecodebehindprotected void funtionnameobject sender gridviewdeleteeventargs e storing value from cell tablecell cell gridview1rowserowindexcells0 full path required string filename iwebsitewebsite3mag celltext iffilename null filename stringempty ifsystemiofileexistsfilename systemiofiledeletefilename and just for added reference for those who want to learnonrowdeletingfuntionname is for just before deleting a row you can cancel deleting or run functions on the data like i didonrowdeletedfuntionname it directly deletes,"['c#', 'asp.net']" +402945,how do i correctly bind a popup to a togglebutton i am trying to do something that seems relatively simple and logic from a user interface level but i have one bug that is very annoying i have a togglebutton and i am trying to show a popup when the button is toggled in and hide the popup when the button is toggled out the popup also hides when the user clicks away from iteverything is working as expected with the following xaml except when i click the toggle button after the popup is shown the popup thisappears for a split second then reappearsi suspect whats going on here is that clicking away from the popup is causing it to toggle the button off then immediately after the button is toggled back on as the mouse clicks it i just do not know how to go about fixing itany help is appreciated thanks togglebutton xnametogglepopupbutton contentmy popup toggle button width100 popup staysopenfalse isopenbinding ischecked elementnametogglepopupbutton modetwoway border width100 height200 backgroundwhite borderthickness1 borderbrushblack textblockthis is a testtextblock border popup,['c#'] +402956,is there any available api to represent various units of item like kg litre metre km etc in my project somewhere i have to work with a unitofissue of items now various items of course can have different units of representation so i was searching for some api or some way to elegantly handle this situationis there any available api that provides some way to represent these units i have heard of jscience which seems impressive but again i am facing another problem with mapping it in jpa after some google work i found out that some work is going on in this context as jsciencejpa but it seems like it is not yet stable to be used in production i also found something about jsr275 but from this jcp page it seems like it has been rejected then i came across unitsofmeasure which i have not yet dig into details but again the same issue comes can this be mapped with jpaedit from this so question i came across java numbers with unit but i do not know whether it is production ready or noti am really confused specially after seeing those options above and jpa is an added concern as to whether i can use any of them or not have anyone ever faced such kind of situation and found a way out of it i really need some help here what should i useand if there is no other way out then what would be appropriate way to represent these units one way i see is by using enums but of course that would be the last choice,['java'] +403008,aspnet mvc jquery ajax post form serialize ajax functionfunction formsubmitfunction if thisvalid ajax url thisaction type thismethod data model thisserialize locations getcheckedlocation reports getcheckedreports beforesend function complete function success function result user operations containerhtmlresult settimeoutfunction loadactionurlactiongetallusers user 10 widgets ul li aremoveclasslink active widgets ul lifirstchild aaddclasslink active return false functions that are using in ajax data attributefunction getcheckedlocation var nodes tt locationtreegetchecked var s for var i 0 i nodeslength i if s s s nodesitext return sfunction getcheckedreports var nodes tt reportstreegetchecked var s for var i 0 i nodeslength i if s s s nodesitext return s htmldiv there are html helpers for model dropdownlistfor textboxfordivdiv checkbox tree tt locationdivdiv checkbox tree tt reportsdivcontrollerhttppostpublic actionresult edituseruserviewmodel modelstring locationsstring reports model null locations and reports are expected not nullquestionwhy model is null when i use ajax data attribute like this data thisserialize it works model is not nullhow can i post model with additional data locationsreportsi hope i can explain thanks,['jquery'] +403011,drawing android ui on top of glsurfaceview for my game i am thinking of drawing ui elements textview for thisplaying time elapsed buttons for pausingrestarting game on top of my glsurfaceview using relativelayouttill now i was drawing all the ui elements myself directly to surfaceview but considering the wide options available from android ui like changing typeface of font and color i have decided to use itquestionsis it good practice to draw ui elements on top of glsurfaceview or is it better to draw all the ui stuff myself directly to glsurfaceviewi will be updating the content of the ui elements say textview regularly for each 16 ms by using runonuithread method is this badwill my game be susceptible for force closes here is the test java code which i am using to set up the relativelayout glview is the glsurfaceview instance rl new relativelayoutthis rladdviewglview tv new textviewthis relativelayoutlayoutparams lp new relativelayoutlayoutparamslayoutparamswrap content layoutparamswrap content lpaddrulerelativelayoutalign top tvsetlayoutparamslp tvsettextfps 0 tvsetbackgroundcolor0x4060ff70 rladdviewtv setcontentviewrl,['android'] +403028,how to get row data by clicking a button in a row in an aspnet gridview i have a gridview in a aspnet web application in which i have added two buttons in each row itemtemplate aspbutton idbtnedit textedit runatserver aspbutton idbtndelete textdelete runatserver itemtemplatenow how i can get the row data from gridview simply by clicking an edit button in a row,"['c#', 'asp.net']" +403058,fetching date from sqlite database in android in my sqlite database i saved date in a data type date how can i fetch this date from cursor,['android'] +403079,jquery isotope checkbox filter if all uncheck show no item this is regarding input checkbox for filtering jquery isotope itemselectorrefer to demo here checkboxes are checked when the page is load however i stumble upon the problem when all is unchecked by user it will just show all items instead of an empty containercheckboxeschangefunction var filters get checked checkboxes values checkboxesfiltercheckedeachfunction filterspush thisvalue red blue red blue filters filtersjoin containerisotope filter filters many thanks in advance cheers,['jquery'] +403093,expand multiple selection to all suggestions boxeshints in sublime text 2 i am wondering if there already exists a way to expand selection to all areas suggested by sublime text 2 boxes so one does not have to keep pressing ctrld and sometimes ctrlkd as shown in skip ctrld selection in sublime text 290 of time the boxes on the screen are exactly what i want to multiple select and it would be very handy if there was a one key option to do sofor example if you have foo2422322and you click on the first 2 the boxes will be shown around only the three single 2s these i would like to select with a single commandmacroif you go with ctrld you have to skip the 2s in 42 and 23 with ctrlkdif nothing like this exists any pointers on writing a plugin for such functionality would be much appreciatedupdate i have gotten a great suggestion to use altf3 which is awesome for making changes in the whole file however it would be also beneficial to limit the scope of multiple select to current visible page or tag or brackets or something else,['python'] +403098,how to merge row in one cell in table layout in android dynamically how to get below functionality in android with table layoutas it is seen in the image i need to merge the two cells in row 5 column 1 and row6 column1 dynamically and i have to replace one image over there how can i achieve this your answers are appreciated,['android'] +403107,linq select objects in list where exists in abc i have a list of ordersi want to select orders based on a set of order statusesso essentially select orders where orderstatuscode in a b c filter the orders based on the order statusvar filteredorders from order in ordersorder where orderstatuscodea b c select ordermany thanks,['c#'] +403209,css selector for first image only if first child does anyone know if it is possible to define a css selector that selects the first image within a div but only if it is the first child within the divin jquery i would use a comparison something like thisif div imgfirstchild divfirstchild,['css'] +403215,php regex remove empty paragraph tags i am trying to remove all empty p tags ckeditor is inserting in to a description box but they all seem to vary the possibilities seem to bepwhitespaceppnbspbr ppnewlinenbspnewlinebr br newlinenbsppwith these possibilities there could be any amount of whitespace nbsp and br tags in between the paragraphs and there could be some of each kind in one paragraphi am also not sure about the br tag from what i have seen it could be br br or bri have searched so for a similar answer but of all the answers i have seen they all seem to cater for just one of these cases not all at once i guess in simple terms what i am asking is is there a regular expression i can use to remove all p tags from some html that do not have any alphanumeric text or symbolspunctuation in them,['php'] +403219,is it safe to use fork with boostasioiptcpiostream i am attempting to daemonize a simple tcp client and although the client works just fine in the foreground daemonizing it causes strange behavioras a test case i have a server that once you connect and send a single message connected will send you the number of seconds connected once per secondif i daemonize by calling testconnecttrue the connection drops after an arbitrary amount of time even after successfully receiving a few numbersif i do not daemonize by calling testconnectfalse the connection stays active and i continue to receive numbers as expectedinclude stringinclude iostreaminclude boostasiohppinclude unistdhclass test public test io nullptr void connectbool daemonize io new boostasioiptcpiostreamlocalhost 6500 if io io io connected stdendl if daemonize pid t child fork if child 0 exitexit failure else if child 0 exitexit success umask0 if setsid 0 exitexit failure if chdirtmp 0 exitexit failure child fork if child 0 exitexit failure else if child 0 exitexit success stdstring line while io stdgetlineio line stdcout line linelength line stdendl delete io io nullptr private boostasioiptcpiostream ioi am absolutely stumped as to what could be cutting off the input stream early it appears that the loop exits because ioeof true and thus boolio false since this only happens when trying to daemonize should i avoid forking altogether is there a better way to send the process into the background programmatically using cc code only,['c++'] +403224,multiple left joins on multiple tables in one query i have got one master table which has items stored in multiple levels parents and childs and there is a second table which may or may not have additional data i need to query two levels from my master table and have a left join on my second table but because of the ordering within my query this will not workselect something from master as parent master as child left join second as parentdata on parentsecondary id parentdataid left join second as childdata on childsecondary id childdataidwhere parentid childparent id and parentparent id rootidthe left join only works with the last table in the from clause so i am only able to make it work for one of the left joins in the example above none of the left joins will work because the first left join points towards the first table in the from clause the second one will never work like thishow can i make this work,['sql'] +403240,need better and simpler understanding of catransform3d please go through the imagesso this is the code which i got from some online source and it does transform my object besides that i understood nothing at all i am new to catransform3d and want to know exactly how it works catransform3d transform catransform3didentitytransformm34 10 500transform catransform3drotatetransform 450f m pi 1800f 0 1 00f bgviewlayertransform transformi want to know how did this code runwhy did we set some value in m34 i found that its some kind of matrix which even confuses me more also what do the arguments in the catransform3drotate meani am trying to understand but not getting any furtheri want a deep understanding of catransform3d please help with any articles documentation or by explaining yourselves thanks a lot,['ios'] +403297,javascript replace dash hyphen with a space i have been looking for this for a while and while i have found many responses for changing a space into a dash hyphen i have not found any that go the other directioninitially i havevar str thisisanewsitemi try to replace it withstrreplace and simply thisplay the resultalertstrright now it does not do anything so i am not sure where to turn i tried reversing some of the existing ones that replace the space with the dash and that does not work eitherthanks for the help,['javascript'] +403316,how to compile a basic dbusglib example i am trying to learn how to use dbus with c bindings i have never used dbus before i am following this tutorial which i assume is the official one freedesktoporg i have read it until this paragraph that gives a first sample program but unfortunately i do not see any indication on this page about how to compile it or which libraries to include did i miss something my os is ubuntu 1004 32bit i installed the libdbusglib1dev package i tried to add include dbusdbush at the beginning of the source file and to compile with gcc ldbus1 iusrincludedbus10 iusrlibi386linuxgnudbus10include o my dbusbin my dbuscbut i just keep failingmy dbusc in function amainamy dbusc73 error unknown type name adbusgconnectionamy dbusc83 error unknown type name agerroradid i miss a point in the tutorial it not could you please help me compile this piece of code thanks in advance,['c'] +403362,how to call stored procedures with entityframework i have genereated a ef4 model from a mysql database and i have included both storedprocedures and tablesi know how to make regular instertupdatefetchdelete operations against the ef but i dont find my storedprocedures this was what i was hoping fore using entities context new entities contextmystoreadprocedureparameters edit 1 this is how it looked without the ef sqlstr call updategamecommandobj new odbccommandsqlstr mainconnectioncommandobjparametersaddid odbctypeintvalue ingameidcommandobjparametersaddname odbctypevarchar 255value ingamenamecommandobjparametersadescription odbctypetextvalue ingamedescriptioncommandobjparametersaddyearpublished odbctypedatetimevalue ingameyearpublishedcommandobjparametersaddminplayers odbctypeintvalue ingameminplayerscommandobjparametersaddmaxplayers odbctypeintvalue ingamemaxplayerscommandobjparametersaddplayingtime odbctypevarchar 127value ingameplayingtime return converttoint32executescalercommandobjps i can change ef version if needededit 1 create definer106228 procedure updategameinid intinname varchar255indescription textinyearpublished datetimeinminplayers intinmaxplayers intinplayingtime varchar127,"['c#', 'mysql']" +403373,static final methods in enum so i have looked around google and so i cannot find a example or explanation of what is the purpose of static final methods in enumwhat i understand methods declare static can be accessed like functionprocedural languagesfinal means you cannot override it cannot change the reference as assylias pointed out in comments static cannot be overridden eitherenums cannot be subclassed explained hereso whats the point of static final methods in enums if it will never be overridden since there would not be a subclass,['java'] +403381,net max concurrent timer threads i am trying to load a queue of interval processes in other words i have a queue and i want each item in the queue to run on an individual interval my problem is that i cannot seem to get more than 25 threads to run at one time i am using net 45 on a 64bit machine which has a default max thread count of 32768how do i make my app run as many concurrent threads as my machine can handlehere is an example app that replicates the actual problem in my production codeclass program static void mainstring args systemthreadingthreadpoolsetmaxthreads200 200 test t new test tloadurls while 1 1 systemthreadingthreadsleep10refresh every 5 seconds consolewritelinesystemdiagnosticsprocessgetcurrentprocessthreadscount public class test public void loadurlsstring url for int i 0 i 100 i systemthreadingtimer t new systemthreadingtimernew systemthreadingtimercallbackruninterval url 0 10 consolewritelineloaded 0 feeds i private static void runintervalobject state string url state as string string data using systemnetwebclient cl new systemnetwebclient consolewritelinegetting data for url data cldownloadstringurl do something with the data this code should theoretically run 198 threads after 2 seconds or soby the way this worked beautifully in my prototype app it was written in node but now i cannot get it to work correctly in canswerthe problem was actually with garbage collection and was not a threadpool issue at all the pool is more than capable of spooling all the threads i am throwing at it the trick is to use the single parameter constructor of the systemthreadingtimer this will make the timer use itself as a semaphore thus avoiding gcclass program static void mainstring args for int i 0 i 100 i test t new test turl i systemthreadingtimer ti new systemthreadingtimernew systemthreadingtimercallbacktruninterval tichange0 10 while 1 1 systemthreadingthreadsleepintmaxvalue public class test public string url get set public void runintervalobject state consolewritelinegetting data for thisurl string data using systemnetwebclient cl new systemnetwebclient data cldownloadstringthisurl i am not for sure why you would ever want a timer to be collected by the gc but hey what do i know,"['c#', '.net']" +403383,encoding an url correctly while using a rewrite engine i am using a mod rewrite and a routing system extracted from akelos frameworki have a very big problem while using some symbols in a search key parametera routing map is followingmapconnectlangsearchstring arraycontroller searchaction indexin controller now i get thisregistrymapparamsgetstring as a search keywordi cannot find a way to properly encode a url for example let us take a string t urlencode gives t5c2f2325263d and page thisplays the requested url siteensearcht was not found on this serverrawurlencode gives t5c202f2325263d and page thisplays the sameyou can download or view a router class source here on this pagei really do not want to use base64 for url and such encodings by which you cannot read anythingin case if you need here is a htaccess file contents as wellifmodule mod rewritec rewriteengine on rewritecond request filename d rewritecond request filename f rewriterule indexphpurl1 qsalifmoduleupdatehere are actually working files for making testsplease download these files and test on your server if you have timeguidecontrollerclassphp simple controller framework enables searchcontrollerphp to work by defining a class controller in itrouterclassphp a router class extracted from akelos framework bug is probably thereroutesphp a place where you define your routs in our case we have only searchstringsearchcontrollerphp a basic application to test strings searchstringhere points to this fileindexphp where all the initiation and routing happens to beginhtaccess i do not think an error is herei think you would not need to make changes in indexphp controllerclassphp routesphp searchcontrollerphpa bug is probably in routerclassphp or maybe there is some fix needed in htaccess which i do not believe,['php'] +403425,js how to cache a variable what i want to do is to be able to create a variable give it a value close and reopen the window and be able to retrieve the value i set in the last session what is the simplest way to do that jquery answers are welcome,"['javascript', 'jquery', 'html']" +403455,python drag and drop explorer files to tkinter entry widget i am fairly new to python i am trying to input a file name complete with full path to a tkinter entry widget since the path to the file name can be very long i would like to be able to drag and drop the file directly from windows explorer in perl i have seen the followinguse tkdropsitemy mw new mainwindowtop mwtoplevellabel entry topentrywidth 45 background ivory2packlabel entrydropsitedropcommand dropdroptypes win32is there something similar i can do using tkinter in python,['python'] +403460,cancelling a thread that has a mutex locked does not unlock the mutex helping a client out with an issue that they are having i am more of a sysadmindba guy so i am struggling with helping them out they are saying it is a bug in the kernelenvironment i am trying to either prove or thisprove that before i insist that it is in their code or seek vendor support for the oshappens on red hat and oracle enterprise linux 57 and 58 application is written in cthe problem they are experiencing is that the main thread starts a separate thread to do a potentially longrunning tcp connect client connecting to serverif the longrunning aspect takes too long they cancel the thread and start another onethis is done because we do not know the state of the server programserver program up and running connection immediately acceptedserver program not running machine and network ok connectionimmediately failed with error connection refused machine or network crashed or down connection takes a long timeto fail with error no route to hostthe problem is that cancelling the thread that has the mutex lockedwith cleanup handlers set up to unlock the mutex sometimes does not unlock the mutexthat leaves the main thread hung on trying to lock the mutexdetailed environment infoglibc2565glibc2565libcap11026kerneldebug2618274el5glibcheaders2565glibccommon2565libcap11026kerneldoc2618274el5kernel2618274el5kernelheaders2618274el5glibcdevel2565code was built withc g3 tst2c lpthread o tst2any advice and guidance is greatly appreciated,"['c++', 'c']" +403466,has anybody found a way to load https pages with an invalid server certificate using uiwebview if a user attempts to load a https web page in mobile safari and the servers certificate validation check fails its expired revoked selfsigned etc then the user is presented is presented with a warning message and asked if they want to continue or notsimilarly nsurlconnection offers the ability for the implementator to decide firstly how to check the certificate and then decide how to proceed if it fails so in this situation too it would be possible to thisplay a warning to the user and offer them the opportunity to continue loading the page or nothowever it seems when loading a https page in uiwebview that fails a certificate check the behaviour is just to fail to load the page didfailloadwitherror gets called with kcfurlerrorservercertificateuntrusted however nothing gets thisplayed to the userthis is inconsistent surely the uiwebview behaviour should behave in a similar way to safari to be consistent within iphone itself its also a daft that nsurlconnection allows total flexibility with this yet nsurlrequestsetallowsanyhttpscertificate is privateis there anyway to implement behaviour which is consistent with safari can this default behavior be customized in a similar way to nsurlconnection allowscheerspsplease refrain from getting into patronizing side thiscussions about why would anybody want to do this thank you very much,['ios'] +403476,actioncontrollerlive is it possible to check if connection is still alive i am trying to implement texteventstream using rails 4s live streaming it works great and the only trouble i met is that i cannot check if the connection is alive without sending any messagesthe only solution i figured out is to make supportive channel with cyclic tick generator so that some background task will send messages there periodically but it seems to be messy and nonreliable any better solutions here is my controllerrequire persistencysserequire persistencytrackclass persistencycontroller applicationcontroller include actioncontrollerlive def stream responseheaderscontenttype texteventstream sse persistencyssenewresponsestream track persistencytracknewcurrent user rethis rethisnew begin rethissubscribeinfo chat do on onmessage do channel message ssewrite message message event channel end end rescue ioerror ensure trackclose sseclose end endend,['ruby-on-rails'] +403561,how to add text with format into edit text the image is from an app called kakao story suppose there is a post with a list of comments like any sns appswhen you click a comment it inserts the user name of the commenter in the edittext to indicate my new comment is a reply to the useryou cannot add the same name more than oncewhen you hit backspace to delete the name the entire characters that make up the nameeg chabeau in the example will be deleted by 1backspace i am trying to mimic the behavior and want some pointers how to implement it or what to search for,['android'] +403568,libgdx is there an easy way to center text on each axis on a button i have been trying to figure out a way to center text on a button but cannot find an easy multipurpose way to i can do it but it will only work for a certain string not for any string i would like to know if there is a way to center any string on a button my button in this case is 185x50i have been able to center this button on the screen like sobuttonx width 2 screengetregionwidth 2buttony height 2 screengetregionheight 2any help would be much appreciated,['java'] +403570,programmatically determine current target run or test in ios project is there any way to programmatically determine if you are running code in the test target vs the regular run target while developing ios applicationsi have the hack of checking if this variable is nil or not as it is only in my test target but this seems pretty hackynsprocessinfo processinfo environment objectforkeyxcinjectbundle,['ios'] +403592,webpage starts zoomed in on mobile devices i am using this code on my webpagemeta nameviewport contentwidth10 initialscale10 maximumscale10i would think the initial scale would make sure the webpage was zoomed out but it does not any ideasi have tried thismeta nameviewport contentwidthdevicewidth initialscale10but i need the width to be set to 10px or it does not look correctanswermeta nameviewport contentwidth10 userscalable0,['html'] +403604,whats the difference between user thread and daemon thread in java possible duplicatewhat is daemon thread in javawhen are daemon threads useful i am confuse wtth the difference between user thread and daemon thread in javacan you tell mewhats the difference between user thread and daemon thread in javain which situation daemon thread will be used can you give me some examplesanybody can answer question 2,['java'] +403626,get the contents from the webview using javafx i am working on a swing application using java fx controls in my application i have to take print out the html page thisplayed in the webview what i am trying is to load the html content of webview in a string with the help of htmldocuementto load the content of html file from web viewi am using the following code but its not workingtry string strwebview1getenginegetdocmentbodyouterhtmlcatchexception ex,['java'] +403656,android turn off screen without going in standby mode i know that this question has been asked a lot of times but it has never been answered satisfactorilymy problem is the followingi have an activity which prevents the screen from turning off for a predefined amount of timegetwindowaddflagswindowmanagerlayoutparamsflag keep screen onwhen the predefined time is over i show a dialog with a countdown to inform the user that the thisplay will turn off in 10 seconds if he doesnt press canceli managed to turn off the thisplay but the phone always switches into standbymodefor switching off i usedwindow mywindow getwindowwindowmanagerlayoutparams lp mywindowgetattributeslpscreenbrightness 00fmywindowsetattributeslpis there any possibility to completely darken the thisplay without going to standbymode which pauses the activitymy goal is that the user should be able to just tap the thisplay to brighten up the screen again so the activity has to remain in an active statea similar question has been asked here since this question is almost a year old i am hoping that maybe somebody managed to this in the mean timelots of greetingssiggy,['android'] +403660,static final long serialversionuid 1l possible duplicatewhat is a serialversionuid and why should i use itwhat is meant by that in a servlet private static final long serialversionuid 1l i have 1 simple question about this guided program given by our professor i have seen serialversionuid several times but i dont whats that forpackage moduleimport javaioioexceptionimport javaioprintwriterimport javautilscannerimport javaxservletservletexceptionimport javaxservletservletoutputstreamimport javaxservletservletresponseimport javaxservlethttphttpservletrequestimport javaxservlethttphttpservletresponse author ja public class servlet 1 extends javaxservlethttphttpservlet implements javaxservletservlet static final long serialversionuid 1l public void doget httpservletrequest request httpservletresponse response throws servletexception ioexception responsesetcontenttypetxthtml servletoutputstream out responsegetoutputstream outprintlnhtml outprintlnheadtitlehello pangettitlehead outprintlnbody outprintlnh1hello pangeth1 outprintlnbodyhtml protected void dopost httpservletrequest request httpservletresponse response throws servletexception ioexception write your program here panget what is the use of static final long serialversionuid 1lin the program,['java'] +403715,using jsf houtputlink to produce a page anchor simple questionhow do you create an html anchor likea idorganization with jsf eghoutputlink or another jsf link component is it possible at all,['html'] +403742,how to delete a draft from google play developer console i have a test draft on google play developer console it is empty no apk files on it and no description i just created it for check somethingnow the draft is here and i cannot find a button for delete ithow can i delete that draft i cannot find any documentation about itthanks,['android'] +403744,php exec performance the following php code does return me a runtime of about 35 seconds measured multiple times and averagedstarttime microtimetrueexecusrlocalbinconvert 1pdf density 200 quality 85 1jpgendtime microtimetruetime taken endtimestarttimewhen i run the same command over a ssh terminal the runtime is reduced to about 06 seconds measured with the command line tool timethe version of the imagemagick library isversion imagemagick 67010 20121218 q16 copyright copyright c 192011 imagemagick studio llcfeatures openmpwhat could be the reason for this time differenceone answer to a similar question here on stackoverflow was that the overhead comes from the webserver having to start a threadshell could this be really the reason i thought threads are leightweight and do not take long at all to startterminateprior to calling exec i set the number of threads used by imagemagick because this wasis a bug in openmp reference to 1 with execenv magick thread limit1 the runtime from php does not change much no matter what value i set for magick thread limit anyway there does not seem to be a bug in openmp on in this version because the runtime of the command line execution is okany suggestions of how i could improve the runtime of the above command would be greatly appreciatedthank you very much for your help,['php'] +403749,how to check whether a string contains at least one alphabet in java i want such a validation that my string must be contains at least one alphabeti am using the followingstring s 1a11boolean flag smatchesazazflag gives me false even though a is in my string s,['java'] +403766,how i do add text to specific div element using jquery i am having a problem with jquerymy html is div idfirst span classtestspandivdiv idsecond span classtestspandiv now i am trying to add text in span using jqueryjspantesttextwelcomeafter that it becomesdiv idfirst span classtestwelcomespandivdiv idsecond span classtestwelcomespandiv but i am tryting to achieve isdiv idfirst span classtestwelcomespandivdiv idsecond span classtestspandivhow can i do that in jquerythanks,"['javascript', 'jquery', 'html']" +403775,how to solve findbugs dp do inside do privileged when reading and scanning an old codes i saw these lines of code public static void replacenullobject obj if obj null return field fields objgetclassgetdeclaredfields if fields null for field field fields fieldsetaccessibletrue class fieldtype fieldgettype try if fieldgetobj null setdefaultvalueobj field fieldtype catch illegalargumentexception e logger errorfailed replacing null egetmessagee catch illegalaccessexception e logger errorfailed replacing null egetmessagee private static void setdefaultvalueobject obj field field class fieldtype throws illegalaccessexception if fieldtype stringclass fieldsetobj commonconstantsblank else if fieldtype dateclass fieldsetobj new date else if fieldtype longclass fieldsetlongobj 0l else if fieldtype integerclass fieldsetintobj 0 else if fieldtype bigdecimalclass fieldsetobj new bigdecimal00 from the flow of the program it seems that the writer want to create a default values for all of the data member of the object if the value is nullupon scanning using findbugs the findbugs reported dp do inside do privileged with this description on setaccessibletruebad practice method invoked that should be only be invoked inside a doprivileged block plugin findbugs key dp do inside do privileged this code invokes a method that requires a security permission check if this code will be granted security permissions but might be invoked by code that does not have security permissions then the invocation needs to occur inside a doprivileged blockmy question why is this bad and how should i solve it,['java'] +403860,is it possible to adjust the baseline in nsattributedstring i would like to slightly modify the y position of a character in an nsattributedstring i know i can subscript or superscript using the attribute dictionaryidkctsuperscriptattributename 1unfortunately the shift caused by this is too large in my case i am looking for an option to adjust the baseline in 1point stepsthe attributed string will be thisplayed in a uibutton using setattributedtitleforstate,['ios'] +403991,google oauth2 javascript client not working in ie 9 although the following code works correctly using chrome shows a popup that requests permission from the user to allow access to map and places data ie 9 opens the popup form but it is empty when calling handleauthclick method i have tried adding settimeouts but without effect i ensured popups are allowed and checked the popup page urls which are identical in chrome and ie has anyone encountered this problem or can someone offer a workaroundvar clientid appsgoogleusercontentcomvar apikey avar scopes function handleclientload gapiclientsetapikeyapikey windowsettimeoutcheckauth 1function checkauth gapiauthauthorize client id clientid scope scopes immediate true handleauthresultfunction handleauthresultauthresult if authresult authresulterror makeapicall else function handleauthclickevent try windowsettimeoutfunction gapiauthauthorize client id clientid scope scopes immediate false handleauthresult 10 catch e alertemessage function makeapicall gapiclientloadplus v1 function var request gapiclientpluspeopleget userid me requestexecutefunction resp googlesigninfindimgattrsrc respimageurlcssheight 32csswidth 32 loginmsgtextwelcome respthisplayname imgvotecssvisibility visible,['javascript'] +403992,android maps api v2 marker with custom defined anchor jumps when dragged i have an google maps android v2 api marker that i have set an anchor at 0510 just placing the marker works fine the problem is when i drag the marker on first move it jumps up and to the left up by approximately the height of the image 10 and half the width 05 it seems like the dragging code of google does not consider the custom defined anchormmapaddmarkernew markeroptionsdraggabletrue iconbitmapdescriptorfactory fromresourcerdrawableblue flag anchor05f 10f positionendpositionanyone seen this seems like a bug in the dragging algorithm,['android'] +404006,why cannot my java application find my properties file i have a simple application that reads from and writes to a properties file it was developed in netbeans and when run from within netbeans works just fine however now i have built and deployed it the properties file cannot be foundproject structurecomcompanyprojectnamecontrollercontrollerclassjava this is where the code using the properties file existsconfruncontrollerproperties the properties file this exists herein the code i have the following to access the properties fileprivate final string propertiesfilelocation confruncontrollerpropertiespublic void runcontrollerthisruncontroller new propertiesthispropertieslocation thisgetclassgetclassloadergetresourcethispropertiesfilelocationfileinputstream propsinput new fileinputstreamthispropertieslocationgetfilethisruncontrollerloadpropsinputsummarized for brevitywhen i call the jar file from the command line i issuejava classpath usrjavaprojectdirectoryprojectjar comcompanyprojectnamecontrollercontrollerclass arg1so i have managed to achieve this before on other projects in just this way but for some reason this is not workingi have checked the structure inside the jar file and all is as expected in therecan anyone point out my mistake and help me get this up and running pleaseedit changed the names to match across they were always consistent in my code,['java'] +404044,find all items within a bounding box with postgis and rails i have a rails model that uses a postgis point type to store the coordinates of a location how can i query all locations that are contained within a bounding box the bounding box comes from google maps like thislocationswithin407661592c739897862c407727812c73979905per page500then in my model i have a scope to handle this but cannot figure out how to get the query rightscope within box string sw box stringsplit01reversemap c cto f ne box stringsplit23reversemap c cto f box box3dsw0 sw1 ne0 ne1 where what do i do here,['ruby-on-rails'] +404069,how to achieve dynamic polymorphism runtime call thispatch on unrelated types goali would like to achieve typesafe dynamic polymorphism ie runtime thispatch of a function call on unrelated types ie on types which do not have a common base class it seems to me that this is achievable or at least theoretically sound i will try to define my problem more formallyproblem definitiongiven the followingtwo or more unrelated types a1 an each of which has a method called f possibly with different signatures but with the same return type r anda boostvarianta1 an object v or whatever other type of variant which can and must assume at any time one value of any of those typesmy goal is to write instructions conceptually equivalent to vfarg 1 arg m that would get thispatched at runtime to function aif if the actual type of the value contained in v is ai if the call arguments are not compatible with the formal parameters of each function ai the compiler should raise an error of course i do not need to stick to the syntax vfarg 1 arg m for instance something like callv f is also acceptablei tried to achieve this in c but so far i have failed to come up with a good solution i do have a bunch of bad ones below i clarify what i mean by good solutionconstraintsa good solution is anything that lets me mimic the vf idiom eg call on variantv f and satisfies the following constraintsdoes not require any sort of separate declaration for each function f that must be called this way eg enable call on variantf or for any list of unrelated types a1 an that can be treated polymorphically eg enable variant calla1 an somewhere else in the code especially on global scopedoes not require to explicitly name the types of the input arguments when doing the call eg call on variantint double stringv f naming the return type is ok so for instance call on variantvoidv f is acceptablefollows a demonstrative example that hopefully clarifies my wish and requirementsexamplestruct a1 void fint double string cout a struct a2 void fint double string cout b struct a3 void fint double string cout c using v boostvarianta1 a2 a3 do not want anything like the following here enable variant callfoo whateverint main a a b b c c v v a call on variantv f 42 314 hello do not want anything like the following here call on variantint double stringv f 42 314 hello v v b call on variantv f 42 314 hello v v c call on variantv f 42 314 hellothe output of this program should be abcbest failed attemptthe closest i got to the desired solution is this macrodefine call on variantr v f r struct caller public booststatic visitorvoid templatetypename t r operator t pobj pobjf va args caller c return vapply visitorc which would work perfectly if only template members were allowed in local classes see this question does anybody have an idea how to fix this or suggest an alternative approach,['c++'] +404117,windows phone log to console thisclaimer i am quite new to the msft tech world and only started windows phone development a month or so agoi am unable to figure out how to log information to the visual studio output window from within a c and c direct3d windows phone 8 app is this possiblei am building in debug mode targeting windows phone 8 running in the xde emulator and my development machine is a windows 8 box with vs2012 ultimate installed my app runs fine my direct3d scene renders normally but i cannot log anything this makes tracing code execution difficult and forces me to use breakpoints which can be overkill in many situationsi have been searching far and wide and have tried many methods outputdebugstring being one of them i cannot see anything on msdn about this why is this not documented anywhere,['c++'] +404229,iterate through listview and get edittextfield values i have created a listview mylist with one edittextfield in each row ridmannschaften under the listview i have created a button and set an onclicklistener for it in the oncreatemethodnow when the button is clicked i want to iterate through the listview and get the value of the edittextfield in every row and save them in a stringlist but how do i do thathere is my codeprivate void buttonclick get all values of the edittextfields view v arrayliststring mannschaftsnamen new arrayliststring edittext et for int i 0 i mylistgetcount i v mylistgetchildati et edittext vfindviewbyidridmannschaften mannschaftsnamenaddetgettexttostring i already know that getchildat is only for the visible rows but i do not know how to do it differently,['android'] +404231,build an expression with multiple sorting i am trying to build an expression for sorting and i wrote code that sorts my list using one property but i need to sort it firstly by one property secondly by another property and so on i mean i want to build an expression that will implement something like that studentsorderbyfistexpressioncompilethenbysecondimpressioncompliethenbythirdexpressioncompileso how to dynamically put that thenby methods here is my codetype studenttype typeofstudentparameterexpression studentparam expressionparameterstudenttype xmemberinfo ageproperty studenttypegetpropertyagememberexpression valueinnameproperty expressionmakememberaccestudentparam agepropertyexpressionfuncstudent int orderbyexpression expressionfuncstudent intlambdafuncstudent intvalueinnameproperty studentparamvar sortedstudents studentsorderbyorderbyexpressioncompile,['c#'] +404241,impacts and benefits of creating empty object using objectcreatenull first of all i made a quick jsperf test case to show the obvious objectcreatenull is way slower than creating a object with the syntaxbut given this fact can the former case be a good alternative sometimes concerning optimization and performance in other words does manipulating the most lightweight js object can increase performance enough so that it became a reasonable choice to use it in some casesi am refering to cases where you are going to access the object properties a lot or making an heavy use of the for in loop for exampleis this method too much risky to be used in a library where people could be lead to heandle these object that does not own the standard properties bring by the standard object prototypealso do you know another quicker way to create the most lightweight js objectps i made a brief test case to show a case where using a objectcreatenull and accessing properties is a little more quickier than with,['javascript'] +404297,cannot import a python module that is definitely installed mechanize ongoing woes with the python 273 installation on my ubuntu 1204 machine and importing moduleshere i am having an issue where i have definitely installed mechanize both on my machine and in various virtual environmentsi have tried installing from pip easy install and via python setuppy install from this repo to no avail each time i enter my python interactive and i get python 273 default aug 1 2012 051439 gcc 463 on linux2type help copyright credits or license for more information import mechanizetraceback most recent call last file stdin line 1 in moduleimporterror no module named mechanize other computers i install this on do not have a problem a mac or a windows machine at work for instance it is all good installs and imports like normalit is pretty much driving me crazy at this point just want to get some work doneupdate info in response to commentsout put of easy install mechanize and pathsmehost sudo easy install mechanizesudo password for me processing mechanizewriting homememechanizesetupcfgrunning setuppy q bthist egg thistdir homememechanizeeggthisttmpzxwj dwarning no files found matching html under directory docswarning no files found matching css under directory docswarning no files found matching js under directory docsmechanize 026dev20130112 is already the active version in easyinstallpthinstalled usrlocallibpython27thistpackagesmechanize026dev 20130112py27eggprocessing dependencies for mechanize026dev20130112finished processing dependencies for mechanize026dev20130112mehost cmehost which piphomemebinpipmehost which pythonhomemebinpythonmehost which easy installhomemebineasy installmehost second updateseems to be something with mechanize if i add any other random package via pip there is not problem in this instance html5libthird update dsm1 syspath homemelocallibpython27sitepackagessetuptools06c11py27egg homemelocallibpython27sitepackagesvirtualenvwrapper211py27egg homemesrcgeopy homemelocallibpython27sitepackagesbeautifulsoup320py27egg homemelocallibpython27sitepackagesdjango sorting01py27egg so on and so forth but mechanize is not here2 pretty long output of which most looks likemehost ls lar usrlocallibpython27thistpackagesmechusrlocallibpython27thistpackagesmechanizetotal 1144lots of other files pretty much same permissionsrwrr 1 root staff 24916 jan 11 0119 mechanizepylots of other files3 import imp impfind modulemechanizetraceback most recent call last file stdin line 1 in moduleimporterror no module named mechanizefourth edit this is getting ridiculous this is similar to a problem i have had before complete removal and fresh install of python on ubuntu 1204 if i run everything with sudo it is fine but i do not know if i should have to do thatwhats up with the permissions,['python'] +404308,broadcast to everyone on lan i am attempting to contact everyone on a lan to thiscover which devices are currently using the ip and running my service every device running the service will know which other devices are connected when they come online i have basic networking experiencetcpudp but i have not done much with more complicated communication packages i wanted to post what i have researchedtried so far and get some expert responses to limit my trial and error time on future potential solutionsrequirementscurrently using java but require crosslanguage communicationmust be done in an acceptable time framecouple seconds max and preferably reliablyi would like to use similar techniques for both broadcast and later communications to avoid introducing added complexity of multiple packagestechnologiescurrently i am planning on a heartbeat to known ips to alert that still connected but i may want to continuously broadcast to lan lateri am interested in using crosslanguage rpc communication for this service but this technique does not necessarily have to use thatlater communicationnonbroadcast must be reliableresearch and things attemptedudp worried about crosslanguage communication lack of reliable delivery and would add another way of communicating rather than using one solution like the ones below i would prefer to avoid it if another more complete solution can be foundapache thrift currently i have tried to iterate through all potential ips and try to connect to each one this is far too slow since the timeout is long for each attempted connectionwhen i call open i have yet to find any broadcast optionzeromq done very little testing with basic zeromq but i have only used a wrapper of it in the past the pubsub features seem to be useful for this scenario but i am worried about subscribing to every ip in the lan also worried what will happen when attempt to subscribe to an ip that does not yet have a service running on itdo any of these recommendations seem like they will work better than the others given my requirements do you have any other suggestions of technologies which might work betterthanks,['java'] +404393,c pointers and arrays sizeof operator possible duplicatestack pointer difference for char pointer and arrayto illustrate my questionint mainvoid int myary20 int myaryptr myaryptr myary sizeofmyary will it return 80 correct sizeofmyaryptr will it return 4 correct return 0first off is my assumption correctand then assuming my assumption is correct what is the detailed explanation i understand that my 20 element array is 80 bytes but is not the name myary merely a pointer to the first element of the array so should not it also be 4,['c'] +404412,where is filestream at the net for windows store i am creating a windows store appi need to create a filestream in order to write some complex data for a proprietary file format i add systemio to my uses but there is no filestream availablei have investigating some more and the net for windows store apps overview guide talks about isolatedstorage which this library do not even use currentlyafter some reading i think the real replacement could be filerandomaccestream from the nacemspace windowsstoragestreamswhat is the real equivalent to filestream to use in a windows store app,['.net'] +404434,property userdetailsservice no matching editors or conversion strategy found i always getjavalangexception javalangillegalstateexception containerbaseaddchild start orgapachecatalinalifecycleexception orgspringframeworkbeansfactorybeancreationexception error creating bean with name orgspringframeworksecurityfilterchains cannot resolve reference to bean orgspringframeworksecuritywebdefaultsecurityfilterchain0 while setting bean property sourcelist with key 0 nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name orgspringframeworksecuritywebdefaultsecurityfilterchain0 cannot resolve reference to bean orgspringframeworksecuritywebauthenticationusernamepasswordauthenticationfilter0 while setting constructor argument with key 2 nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name orgspringframeworksecuritywebauthenticationusernamepasswordauthenticationfilter0 cannot resolve reference to bean orgspringframeworksecurityauthenticationprovidermanager0 while setting bean property authenticationmanager nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name orgspringframeworksecurityauthenticationprovidermanager0 cannot resolve reference to bean orgspringframeworksecurityconfigauthenticationauthenticationmanagerfactorybean0 while setting constructor argument nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name orgspringframeworksecurityconfigauthenticationauthenticationmanagerfactorybean0 factorybean threw exception on object creation nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name orgspringframeworksecurityauthenticationmanager cannot resolve reference to bean orgspringframeworksecurityauthenticationdaodaoauthenticationprovider0 while setting constructor argument with key 0 nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name orgspringframeworksecurityauthenticationdaodaoauthenticationprovider0 initialization of bean failed nested exception is orgspringframeworkbeansconversionnotsupportedexception failed to convert property value of type orgspringframeworksecurityauthenticationprovidermanager to required type orgspringframeworksecuritycoreuserdetailsuserdetailsservice for property userdetailsservice nested exception is javalangillegalstateexception cannot convert value of type orgspringframeworksecurityauthenticationprovidermanager to required type orgspringframeworksecuritycoreuserdetailsuserdetailsservice for property userdetailsservice no matching editors or conversion strategy foundat comsunenterprisewebwebapplicationstartwebapplicationjava138at orgglassfishinternaldataenginerefstartenginerefjava130at orgglassfishinternaldatamoduleinfostartmoduleinfojava269at orgglassfishinternaldataapplicationinfostartapplicationinfojava301at comsunenterprisev3serverapplicationlifecycledeployapplicationlifecyclejava461at comsunenterprisev3serverapplicationlifecycledeployapplicationlifecyclejava240at orgglassfishdeploymentadmindeploycommandexecutedeploycommandjava389at comsunenterprisev3admincommandrunnerimpl1executecommandrunnerimpljava348at comsunenterprisev3admincommandrunnerimpldocommandcommandrunnerimpljava363at comsunenterprisev3admincommandrunnerimpldocommandcommandrunnerimpljava1085at comsunenterprisev3admincommandrunnerimplaccess1200commandrunnerimpljava95at comsunenterprisev3admincommandrunnerimplexecutioncontextexecutecommandrunnerimpljava1291at comsunenterprisev3admincommandrunnerimplexecutioncontextexecutecommandrunnerimpljava1259at comsunenterprisev3adminadminadapterdocommandadminadapterjava461at comsunenterprisev3adminadminadapterserviceadminadapterjava212at comsungrizzlytcphttp11grizzlyadapterservicegrizzlyadapterjava179at comsunenterprisev3serverhk2thispatcherthispathhk2thispatcherjava117at comsunenterprisev3servicesimplcontainermapperhk2thispatchercallablecallcontainermapperjava354at comsunenterprisev3servicesimplcontainermapperservicecontainermapperjava195at comsungrizzlyhttpprocessortaskinvokeadapterprocessortaskjava849at comsungrizzlyhttpprocessortaskdoprocessprocessortaskjava746at comsungrizzlyhttpprocessortaskprocessprocessortaskjava1045at comsungrizzlyhttpdefaultprotocolfilterexecutedefaultprotocolfilterjava228at comsungrizzlydefaultprotocolchainexecuteprotocolfilterdefaultprotocolchainjava137at comsungrizzlydefaultprotocolchainexecutedefaultprotocolchainjava104at comsungrizzlydefaultprotocolchainexecutedefaultprotocolchainjava90at comsungrizzlyhttphttpprotocolchainexecutehttpprotocolchainjava79at comsungrizzlyprotocolchaincontexttaskdocallprotocolchaincontexttaskjava54at comsungrizzlyselectionkeycontexttaskcallselectionkeycontexttaskjava59at comsungrizzlycontexttaskruncontexttaskjava71at comsungrizzlyutilabstractthreadpoolworkerdoworkabstractthreadpooljava532at comsungrizzlyutilabstractthreadpoolworkerrunabstractthreadpooljava513at javalangthreadrunthreadjava722springsecurityxmlbeans xmlnsxmlnssecurity xmlnsxsixsischemalocation securityhttp autoconfigtrue accessdeniedpagewebinfviewerroraccessdeniedjsp securityintercepturl pattern accessadministrator securityintercepturl patternresources accessis authenticated anonymously securityintercepturl patternindex accessis authenticated anonymously securityformlogin loginpageindex defaulttargeturlhome authenticationfailureurlerror securityhttpbean iduserdetailsservice classcomsyncbroclinicserviceimpluserdetailsserviceimpl bean iddaoauthenticationprovider classorgspringframeworksecurityauthenticationdaodaoauthenticationprovider property nameuserdetailsservice refuserdetailsservice beanbean idprovidermanager classorgspringframeworksecurityauthenticationprovidermanager property nameproviders list ref localdaoauthenticationprovider list propertybeansecurityauthenticationmanager securityauthenticationprovider userservicerefprovidermanager securitypasswordencoder hashsha256 securityauthenticationprovidersecurityauthenticationmanageruserdetailsserviceimpljavaimport orgspringframeworkbeansfactoryannotationautowiredimport orgspringframeworksecuritycoreuserdetailsuserdetailsimport orgspringframeworksecuritycoreuserdetailsuserdetailsserviceimport orgspringframeworksecuritycoreuserdetailsusernamenotfoundexceptionimport orgspringframeworkstereotypeserviceimport orgspringframeworktransactionannotationtransactionalserviceuserdetailsservicepublic class userdetailsserviceimpl implements userdetailsservice autowired private userdao userdao autowired private assembler assembler override transactionalreadonly true public userdetails loaduserbyusernamestring username throws usernamenotfoundexception user user userdaofindbyusernameusername ifuser null throw new usernamenotfoundexceptionlogin user username not found return assemblerassembleuseruser,['java'] +404438,where do i use endthreadex windows api i am a novice in the windows api and recently i learned i should not use createthread and terminatethread i switched to beginthreadex however i am not sure how i am supposed to use endthreadex for example here is a basic function i was testing with mythreadfunction outputs i work and endsunsigned int stdcall mythreadfunction void lpparam int i intlpparam cout i i work endl endthreadex0 return 0is my placement of endthreadex correct i have it before the return 0 which just seems odd to me i read in the msdn pages about endthreadex that it is called automatically when a function ends but you should call it for better memory cleanup and that is why i tried putting it in it just does not seem right sorry if this is a bad question i just want to make sure i am doing everything right to the best of my abilities,"['c++', 'c']" +404451,how to refresh the multiline output dynamically i want to refresh some info dynamicallyjust like progress bar i can do it with following code usrbinenv pythonimport sysimport timeprint start the outputdef loop i 0 while 1 i 1 output rfirst lines stri sysstdoutwriteoutput sysstdoutflush timesleep1loopit could only output single line info dynamically when add n into output it could not work as expectoutput rfirst linesn striany way could help it to refresh multi line content,['python'] +404465,why is the performance of bufferedreader so much worse than bufferedinputstream i understand that using a bufferedreader wrapping a filereader is going to be significantly slower than using a bufferedinputstream wrapping a fileinputstream because the raw bytes have to be converted to characters but i do not understand why it is so much slower here are the two code samples that i am usingbufferedinputstream inputstream new bufferedinputstreamnew fileinputstreamfilenametry byte bytebuffer new bytebuffersize int numberofbytes do numberofbytes inputstreamreadbytebuffer 0 buffersize while numberofbytes 0finally inputstreamcloseandbufferedreader reader new bufferedreadernew filereaderfilename buffersizetry char charbuffer new charbuffersize int numberofchars do numberofchars readerreadcharbuffer 0 buffersize while numberofchars 0finally readerclosei have tried tests using various buffer sizes all with a 150 megabyte file here are the results buffer size is in bytes times are in millisecondsbuffer input size stream reader 4096 145 497 8192 125 46516384 95 51532768 74 50665536 64 531as can be seen the fastest time for the bufferedinputstream 64 ms is seven times faster than the fastest time for the bufferedreader 465 ms as i stated above i do not have an issue with a significant difference but this much difference just seems unreasonablemy question is does anyone have a suggestion for how to improve the performance of the bufferedreader or an alternative mechanism,['java'] +404476,create div with data attributes i am creating div the following waydiv class draggable player player unit unit unitand i cannot find what other properties i can assign to it the same way i assign class especially if i can assign data or attr,"['javascript', 'jquery']" +404536,how to customize twitter widget style i just implemented the lists widget on my site i just want to override the backgroundcolor from white to transparent since it is a embedded widget i cannot edit it directly can anyone help me with it,['css'] +404545,android inapp billing purchase state stays purchased after order cancelation i am currently testing my inapp billing mechanism using the inapp billing version 3 api therefore taking the trivialdrive example as referencei have one managed item which is upgrade to premium versionnow purchasing the item with my test account works but when i do a cancellation of the entire order in google checkout afterwards my code still tells me that the item is purchased an therefore grants the premium featureshere is how i check for the purchase in my mainactivity i do not save the purchase state locally somewhere as i understood that the with the billing api v3 you can query for purchases ad hoc as neededoverride protected void onstart todo autogenerated method stub superonstart iabhelper new iabhelperthis helpergetpkey iabhelperenabledebugloggingtrue iabhelperstartsetupnew iabhelperoniabsetupfinishedlistener override public void oniabsetupfinishediabresult result logdiab setup finished ifresultissuccess logdiab setup not ok return else logdiab setup ok iabhelperqueryinventoryasync new queryinventoryfinishedlistener override public void onqueryinventoryfinishediabresult result inventory inv logdiab query inventory finished if resultisfailure logdiabfailed to query inventory result return logdiab query inventory was successful do we have the premium upgrade boolean mispremium invhaspurchasehelperpremiumsku purchase p invgetpurchasehelperpremiumsku ifp null logdiab purchase state iabhelpergetresponsedescpgetpurchasestate else logdiab purchase state purchase is null logdiab user is mispremium premium not premium i keep getting getpurchasestate 0 which means is purchased even one hour after i cancelled the order why,['android'] +404576,is it possible to erase elements of a stdlist in a c11 for each loop i want to use the new c11 for each loop to iterate over all elements of a list and erase certains elements for examplestdlistint mylistmylistpush back1 mylistpush back13mylistpush back9mylistpush back4forint element mylist ifelement 5 do something with the element erase the element else do something else with the element is it possible to do this using the for each loop or do i have to go back to iterators to achive this,['c++'] +404614,hardware section is missing under android virtual device manager i was trying to fix my problem hardware buttons not enabled in avd after an hour researchall i found was people who lead people to go to hardware section and fix blabla but interestingly my avd does not have this sectioni actually found some of options under device definitions but still couldnt fix my problem nor found this menuall screenshots i saw had hardware sectionmy specs are macos android 422 api17 eclipse pseverything else works perfectly i am just missing this section,['android'] +404621,how to access the raw unaltered http post data in rails how can i access the original post message in a controller and send it back unaltered to its original sender,['ruby-on-rails'] +404640,making a slide up view similar to the new google maps ios app troubles with multiple uipangesturerecognizer i am trying to reproduce the behaviour of the slide up menu of the new ios google maps applicationso basically it is a view that you can slide up with panning up to a certain point or slide down to a certain point this view can also with sliding to the right and to the left like a paginated scroll viewit should either scroll up and down or slide to the side but not both at the same timeafter a lot of research and testing i have something that is close but not quite working like need it tomy implementation is a uiscrollview with a frame of 320x400 and content view of 960x400 with paginated scrolling then i add a uipangesturerecognizer that handles the slide up of the whole viewhere is the handletouch ibaction of the panrecognizer ibactionhandlepanuipangesturerecognizer sender nslogpanning cgpoint translatedpoint uipangesturerecognizersender translationinviewselfview ifuipangesturerecognizersender state uigesturerecognizerstatebegan firstx sender view centerx firsty sender view centery if is iphone 5 if firsty 216 translatedpoint cgpointmake firstx 216 else translatedpoint cgpointmake firstx firstytranslatedpointy else if firsty 307 translatedpoint cgpointmake firstx 307 else translatedpoint cgpointmake firstx firstytranslatedpointy sender view setcentertranslatedpoint ifuipangesturerecognizersender state uigesturerecognizerstateended cgfloat velocityy 02uipangesturerecognizersender velocityinviewselfviewy cgfloat finalx firstx cgfloat finaly translatedpointy velocityy iffinaly firsty if is iphone 5 finaly 307 else finaly 216 else iffinaly firsty if is iphone 5 finaly 605 else finaly 515 cgfloat animationduration absvelocityy022 uiview beginanimationsnil contextnull uiview setanimationdurationanimationduration uiview setanimationcurveuiviewanimationcurveeaseout uiview setanimationdelegateself uiview setanimationdidstopselectorselectoranimationdidfinish sender view setcentercgpointmakefinalx finaly uiview commitanimations so basically if the pan slide the view up and not to the sides the problem i have with this handlepan method is that i cannot make it work so that it does not allow scrolling higher than a point which it what i am trying to do with if firsty 216 translatedpoint cgpointmake firstx 216 else translatedpoint cgpointmake firstx firstytranslatedpointythe biggest problem thought is that the uiscrollview pan gesture recognizer is handling the pan at the same time than the one i added which means the uiscrollview is slided up and to the sides at the same time if i slide up the view with my finger by moving it to the sides as wellsame is happening if i try to slide to the sides only and move the view up 1 pixel while doing my pan recognizer ends and slides the view up completelythe workaround i found is to set my pan recognizer to require the uiscrollview pan recognizer to fail to work pangesturerecognizer requiregesturerecognizertofail slideupscrollviewpangesturerecognizerso now when i slide to the sides it works and does not move the view up the problem thought is that it sets itself as failed only when you remove your finger and the view did not scroll to the sides what happens is that you cannot pan the view up anymore but if you flick up inside it does the goes the uigesturerecognizerstateended if and slides the view upi looked at uipangesturerecognizer topics and looked at few options including subclassing my pan recognizer to make it recognise only slide up pans and not those of the sidedo you guys i think i am using the right strategy or should i look at it another waythe ideal solution would be that when a slide to the side is recorded it only moves content horizontally and is handle by the uiscrollview and that when an horizontal pan is recorded it only pans vertically and is handled by my panreconizer the same behaviour that safari has with horizontal and vertical scrolling though i did not figure out how to implement thatthanks for reading let me know what you think it would be great if many apps had a great slide up menu like google mapsedit i am targeting ios 6,['ios'] +404680,how to add javascript in the head of a html knitr document i use the rmd version of knitr because it is less verbose than rhtml i am currently doing script srcscriptin the body of the rmd document but this should be in the head of the downstream html document that gets generated by markdowntohtml is it possible,['html'] +404683,jquery draggable and droppable between two containers and sortable im trying to develop a small page that has the following functionalitypage will have two divs one being origin containing a lot of thumbnail images and the second one will be drop where the images can be dropped on up to 3 onlyit needs to be possible to dragdrop the images from drop back to origindrop needs to be sortable since the order of the 3 selected images matterwhen dropped on drop the images should align as if they had original been thisplayed like that from the starti had never used jquery before and i even had a working page prototype before where i already had the drag and drop between two containers through native html5 drag and drop events but when i added the sortable jquery functionality to drop the images could no longer be dragged back to origin which breaks my functionalityso i started over and wanted to implement both the drag drop functionality as well as the sortable with jquery i have read pretty much the whole api for all draggable droppable and sortable functionality but i am having trouble getting this to work not sure if it is the settings i am using for each functionality on the fiddle you can see that the images become draggable and i can see the settings i specify in effect opacity cursor but the images cant be dropped on drop from what i understand the combination of making images draggable the images having a draggable class and making drop droppable with an accepts of draggable it should allow the most basic functionality but even that does not seem to take also i read that if both draggable and droppable have the same scope setting it should also work but it is notheres a simple version of the pages code plus a jsfiddle codecssorigin backgroundcolor greendrop backgroundcolor red minheight 120pxjsimgdraggable helper clone opacity 05 cursor crosshair scope drop dropdroppable accept draggable scope dropdropsortablehtmldiv idwrapper div idorigin classfbox img src idone titleone classdraggable img src idtwo titletwo classdraggable img src idthree titlethree classdraggable div ptestp div iddrop classfbox divdivany help is greatly appreciated,['jquery'] +404693,how hard is it really to decompile assembly code i am trying to find hard facts that will help my management understand how hardeasy it is to reverseengineer compiled c codesimilar questions have been asked before on this site see eg is it possible to adecompilea a windows exe or at least view the assembly or possible to decompile dll written in c but the gist of these questions is that decompiling compiled c code is hard but not entirely impossiblein order to facilitate answers that are based in fact i am including compiled code for a mystery function and i propose that answers to this question measure the success or failure of the proposed techniques by whether they can determine what this function does this may be unusual for so but i think it is the best way to get good subjective or factual answers to this engineering question therefore what is your best guess at what this function is doing and howthis is the compiled code compiled on mac osx with gcc mysteryleh func begin1 pushq rbpltmp0 movq rsp rbpltmp1 movsd lcpi1 0rip xmm1 subsd xmm0 xmm1 pxor xmm2 xmm2 ucomisd xmm1 xmm2 jbe lbb1 2 xorpd lcpi1 1rip xmm1lbb1 2 ucomisd lcpi1 2rip xmm1 jb lbb1 8 movsd lcpi1 0rip xmm1 movsd lcpi1 3rip xmm2 pxor xmm3 xmm3 movsd lcpi1 1rip xmm4 jmp lbb1 4 align 4 0x90lbb1 5 ucomisd lcpi1 2rip xmm1 jb lbb1 9 movapd xmm5 xmm1lbb1 4 movapd xmm0 xmm5 divsd xmm1 xmm5 addsd xmm1 xmm5 mulsd xmm2 xmm5 movapd xmm5 xmm1 mulsd xmm1 xmm1 subsd xmm0 xmm1 ucomisd xmm1 xmm3 jbe lbb1 5 xorpd xmm4 xmm1 jmp lbb1 5lbb1 8 movsd lcpi1 0rip xmm5lbb1 9 movapd xmm5 xmm0 popq rbp ret leh func end1updateigor skochinsky is the first to find the right answer it is indeed a naive implementation of herons algorithm for calculating square roots the original source code is hereinclude stdiohdefine eps 1e7double mysterydouble x double y1 double diff diffyyx diffdiff0diffdiff whilediffeps yyxy2 diffyyx diffdiff0diffdiff return yint main printfthe square root of 2 is gn mystery2,['c'] +404706,c aspnet single signon implementation i am tasked with implementing single signon for our customers as part of our next release the flow exists as follows user logs into their schools main portal system using a student idpassword provided to himher by the school user clicks the link to my companys productuser is automatically taken to the dashboard page as if they had just logged in through the login form on our sitethus there are two mechanisms by which a user can be authenticated into our sitecoming to our products home page and logging in using the emailpassword that we store in our local systemusing the single signon where the student has already logged into the schools main system with a student id and passwordif our products implementation is in aspnet as opposed to javaruby should we be using cas josso or some other third party single signon product or is there something available to a net environment which would be simpler for us as a net company,"['c#', 'asp.net']" +404745,sql find position in table i have a table in mysql which has the users id and scoreswhat i would like to do is organise the table by scores simple but then find where a certain user id sits in the tableso far i would have select from table scoreorder by score deschow would i find where userid 1234 is ie entry 10 of 12,"['mysql', 'sql']" +404748,python ctypes how to modify an existing char array i am working on a python application that makes use of libupnp which is a c library i am using ctypes to use the library which is easy enough the problem i am having is when i am registering a callback function for read requests the function has a prototype of the following formint read callbackvoid pfilehandle char pbuf long nbuflengthpfilehandle is just some file handle type pbuf is a writable memory buffer this is where the data is output nbuflength is the number of bytes to read from the file a status code is returnedi have a python function pointer for this that was easy enough to make but when i define a python function to handle this callback i have found that pbuf does not get written to because python strings are immutable and when you assign or modify them they create new instances this poses a big problem because the c library expects the char pointer back when the function finishes with the requested file data the buffer ends up being empty every time though because of the way python strings are is there some way around this without modifying the c librarythe handler should modify the buffer parameter that is given which is my problemso what i want to have happen is that the python function gets called to perform a read of some file could be in memory a file system handle or anything in between the pbuf parameter is populated by a read of the stream again in python the callback then returns to the c code with pbuf written to,['python'] +404749,hashtable why is get method synchronized i known a hashtable is synchronized but why its get method is synchronizedis it only a read method,['java'] +404755,monitor javascript events is it possible to monitor all javascript events in the browserfor example which functions has been called which parameters have been passed in which jsfilein my case i have some obfuscated code and need to find out which functions are being called when i perform an actionanybody an idea,['javascript'] +404761,how to plot data by c program i am a mechanical engineer who has only limited knowledge in c programming i wrote some code in order to make simulations and i want to visualize the simulation results at the moment i am using devc for writing my codes with fopen and fprintf commands i generate a dat file which includes the results then i open gnuplot program and import my dat file to plot the results this takes time and i have to wait till the end of the simulation is there an easy way to connect my plotter with devc so my plotter starts plotting data during the simulation any library or etc sorry i am not a programmer therefore the things i have read so far was too complicated for me,['c'] +404772,arrays passed by reference by default i am reading a c book which says thisc passes arrays to functions by referenceathe called functions can modify the element values in the callersa original arraysit is referring to situations like thisint hourlytemperatures 24 modifyarray hourlytemperatures 24 however this is vanilla c array pointers at work here right there is no use of a c reference technique what is being passed is a pointer by value in this case a pointer to the first element of the array the end result is that the function does have access to the full original array like a reference but this is not actually pass by reference rightfrom this prentice hall book,"['c++', 'c']" +404782,jquery ui tabs no longer supporting cookie now what i apologize for this being an open ended question but i am at a losince version 19 of the jquery ui they depreciated using the cookie option in order to save the active state of tabs across multiple pages i have not seen any other documentation out there on how to accomplish this now so i am left scratching my headmy best guess would be to use some sort of event to create a cookie then load the cookie or is there some other way to save the active state of the tabs across multiple pages and by user preference,['jquery'] +404788,how to calculate moving average using numpy there seems to be no function that simply calculates the moving average on numpyscipy leading to convoluted solutionswhy is this the case and whats the easiest way around this,['python'] +404811,why should all iterators iterator adaptors notmovable in c11 in this question thiscussed when to make a type nonmovable in c11 and i thiscovered scott meyers had similar question on compstdc where sg listed below class types are not movable in c11 libearyall mutex typesrecursive mutex timed mutex recursive timed mutex condition variabletype info error category localefacet random deviceseed seqreference wrapperdurationtime point all iterators iterator adaptorsios basebasic istreamsentrybasic ostreamsentryall atomic typesonce flagthe question is why is all iterators iterator adaptors notmovable,['c++'] +404818,set date format using apache poi i want to set date in date format in excel file with apache poi the value will set in such a manner so that in address bar it will show in mmddy and in cell it will show in ddm date in numeric and month in string like 01jan will you please help me in this situation,['java'] +404819,both asterisk and ampersand in a parameter c i am reading a book about binary search tree and something weird came upclass bstpublic void insertconst comparable itemprivate binarynode root struct binarynode comparable element binarynode left binarynode right binarynodeconst comparable theelement binarynode lt binarynode rt elementtheelement leftlt rightrt void insertconst comparable item binarynode t constthe private insert function is helper function for public insert function and private insert function looks for the right place to insert using recursionpart that i do not understand is binarynode t in the parameter what does it meanpointer of the address of t,['c++'] +404861,get all pages in yii i am trying to create my own xml sitemap everything is done except for the part that i thought was going to be the easiest how do you get a list of all the pages on the site i have a bunch of views in a site folder and a few others is there a way to explicitly request their urls or perhaps via the controllersi do not want to make use of an extension,['php'] +404870,is the formdata object available in internet explorer 10 i am writing a little javascript application that allows me to upload images asynchronouslythis script works awesome in every browser except for guess who internet explorerso the first thing that i made is to create a fallback for ie9 versions with ajaxform plugin for jquery which works greatheres the js scriptuploaderchangefunctione var form uploaderform formtriggersubmit thisattrthisabledthisabled epreventdefaultuploaderformsubmitfunctione epreventdefault estoppropagation var typepostvar loadingphotoisloading ifwindowapi true var formdata new formdatathis0 ajax url url type type xhr function myxhr ajaxsettingsxhr ifmyxhrupload myxhruploadaddeventlistenerprogressprogresshandlingfunction false return myxhr beforesend functionloadingremoveclassishidden important success functionresponse jres jsonparseresponse alerttest ok file uploaded error functionresponseconsolewarnresponse data formdata cache false contenttype false processdata false epreventdefault else thisajaxsubmit url url datatype json type type beforesubmit functionloadingremoveclassishidden importantthisformserialize successfunctionresponse jres jsonparseresponse alertfallbacktest complete error functionresponseconsolewarnresponse epreventdefault return false windowapi and every other variable are defined in a global script but do not worry they work to be precise windowapi is thisvar windowapitrueifwindowfilewindowfilereaderwindowfilelistwindowblobconsolelogwindowapi readywindowapitrueelseconsolelogwindowapi not readywindowapifalseso with this bunch of lines of code i handle every browser and ie9 browsersthe problem now is with ie10 because it has got all the window methods and it can use the formdata object but when i try to upload something with ie10 and formdata i receive an access is denied error for the formdata objectthe html that is involve in this process isform nameuploaderform iduploaderform methodpost enctypemultipartformdata input typefile nameuploader iduploader acceptimage tabindex1 formso at the end my question ishow can i avoid getting an access denied exception in ie10 when trying to access the formdata object,['javascript'] +404892,sql combination from and to a single table i have a single table looking like thistable extract owner attribute value 10 color blue 10 color red 10 color green 10 size big 20 color green 20 size medium 20 memory 16g 20 memory 32g 30 color red 30 color blue 30 memory 64gis there a sql which will calculate a combination of all attribute with a single index last column in the resultowner attribute value rule no10 color blue 110 size big 110 color red 210 size big 210 color green 310 size big 320 color green 120 size medium 120 memory 16g 120 color green 220 size medium 220 memory 32g 230 color blue 130 memory 64g 130 color red 230 memory 64g 2i tried to use the sql cross join but the number of attributes is not fixed then i cannot use it one cross join per attribute is needed and i want the combination to be new rows instead new columnsi am trying to use talend open studio to do it but a simple sql would be sufficient,"['mysql', 'sql']" +404943,multiple conditions for a filterexpression i am using condition expression but i am unable to add more than one condition to a filterexpressioncan any one help i have posted my source code hereconditionexpression with filters filter1filterexpression filter1 new filterexpressionfilter1filteroperator logicaloperatorandfilter1conditionsaddnew conditionexpressiona logicalname conditionoperatorequal id1filter1conditionsaddnew conditionexpressionb logicalname conditionoperatorequal id2querycriteriafiltersaddfilter1 filter2filterexpression filter2 new filterexpressionfilter2filteroperator logicaloperatorandfilter2conditionsaddnew conditionexpressionb logicalname conditionoperatorequal id3filter2conditionsaddnew conditionexpressionc logicalname conditionoperatorequal id4q shoppingcartitemquantitycheckcriteriafiltersaddfilter2,['c#'] +404996,does stdvectorresize ever reallocate when new size is smaller than current size possible duplicatestdvector resize downward if i resize an stdvector to some size smaller than its current size is it possible that the vector will ever allocate new memorythis is important to me for performance reasons,['c++'] +405002,testing python c libraries get build path when using setuptoolsthistutils to build c libraries in python python setuppy buildthe sopyd files are placed in buildlibwin3227 or equivalent i would like to test these files in my test suite but i would rather not hard code the buildlib path does anyone know how to pull this path from thistutils so i can syspathappendbuild path or is there an even better way to get hold of these files without having installed them first,['python'] +405011,why does not this code compile in vs2010 with net 40 somehow following code does not compile in vs2010 but compiles in vs2012 without changes the problematic line in vs2010 is namesselectfoogetnameerror cs1928 string does not contain a definition for select and the best extension method overload systemlinqenumerableselecttsourcetresultsystemcollectionsgenericienumerabletsource systemfunctsourcetresult has some invalid argumentsusing systemusing systemlinqnamespace consoleapplication1 class program static void main var foo new foo var names new hello consolewritelinestringjoin namesselectfoogetname public class foo static class extensions public static string getnamethis foo foo string name return name,"['c#', '.net']" +405015,how to make an api call using meteor ok here is the twitter apican any one give me any hint about how to go about calling this api or link using meteorupdatehere is the code that i tried but its not showing any responseif meteorisclient templatehellogreeting function return welcome to helloworld templatehelloevents click input function checktwitter meteormethodschecktwitter function thisunblock var result meteorhttpcallget alertresultstatuscode if meteorisserver meteorstartupfunction,['javascript'] +405037,sum between pairs of indices in 2d array sorry i do not know the protocol for reasking a question if it does not get an answer this question was asked a few months ago here numpy sum between pairs of indices in 2d array i have a 2d numpy array mxn and two more 1d arrays mx1 that represent starting and ending indices for each row of the 2d array that i would like to sum over i am looking for the most efficient way to do this in a large array preferably without having to use a loop which is what i am currently doing an example of what i would like to do is the following randomseed1234 a randomrand44 print a 019151945 062210877 043772774 078535858 077997581 027259261 027646426 080187218 095813935 087593263 035781727 050099513 068346294 071270203 037025075 056119619 b array1021 c array3244 d empty4 for i in xrange4 di sumai bici print d 105983651 105256841 08588124 164414897my problem is similar to the following question however i do not think the solution presented there would be very efficient numpy sum of values in subarrays between pairs of indices in that question they want to find the sum of multiple subsets for the same row so cumsum can be used however i will only be finding one sum per row so i do not think this would be the most efficient means of computing the sum,['python'] +405062,using of vector in c i am having trouble with the following code and cannot seem to figure out what is wronginclude iostreaminclude cmathinclude vectorusing namespace stddouble thistanceint a int b return fabsabint main vectorint age agepush back10 agepush back15 coutthistanceage0age1 return 0the error lies at calling of function thistanceusrincludec46bitsstl iterator base typesh in instantiation of astditerator traitsintatestcpp1830 instantiated from hereusrincludec46bitsstl iterator base typesh16653 error ainta is not a class struct or union typeusrincludec46bitsstl iterator base typesh16753 error ainta is not a class struct or union typeusrincludec46bitsstl iterator base typesh16853 error ainta is not a class struct or union typeusrincludec46bitsstl iterator base typesh16953 error ainta is not a class struct or union typeusrincludec46bitsstl iterator base typesh17053 error ainta is not a class struct or union type,['c++'] +405070,programmatically find how many fingers in multitouch android device supports on android it is possible to check programmatically if the device supports multitouch or not wth touchscreen multitouch is it also possible to check exactly how many fingers the device can recognize in multitouch eg from what i know a 2finger multitouch is supported starting with 2x but 3finger multitouch from 40 but our customer reports having some new devices with 4x which still do not support 3 fingers which makes a simple check against the version of android os uselessa possible solution would be to store in some dictionary for each device which number of fingers it supports max but with 1k devices out there and new ones constantly appearing it is not viableany solutionedit in fact i just found that the issue reported by the customer was a device issue on htc one series see the user has to turn the devicespecific gestures recognition in settings to get 5 fingers working so the device would probably even show 5 fingers support i guess we will just check for the devices model and show special popup for it telling the user to turn that htcspecific setting off,['android'] +405073,using reflection to determine which fields are backing fields of a property i am using reflection to map out objects these objects are in managed code but i have no visibility into their source code underlying structure etc other than through reflection the overarching goal of all this is a rudimentary memory map of an object similar in functionality to sosdll dumpobject and objsize commands as such i am trying to determine which members are being double counted as both a field and a property for examplepublic class calendarentry private property private datetime date get set public field public string day daywhen mapped showsfieldsdayk backingfieldpropertiesdatewhere as a class like thispublic class calendarentry private field private datetime date public field public string day day public property exposes date field safely public datetime date get return date set date value when mapped showsfieldsdaydatepropertiesdateat first glance there is nothing to tell you that the date propertys backing field is the field named date i am trying to avoid counting date twice in this scenario since that will give me a bad memory size approximation whats more confusingcomplicated is i have come across scenarios where properties do not always have a corresponding field that will be listed through the typegetfields method so i cannot just ignore all properties completelyany ideas on how to determine if a field in the collection returned from typegetfields is essentially the backing field of some corresponding property returned from typegetpropertiesedit i have had trouble determining what conditions a property will not have a corresponding field in listed in the collection returned from typegetfields is anyone familiar with such conditionsedit 2 i found a good example of when a propertys backing field would not be included in the collection returned from typegetfields when looking under the hood of a string you have the followingobject contains property named firstcharobject contains property named charsobject contains property named lengthobject contains field named m stringlengthobject contains field named m firstcharobject contains field named emptyobject contains field named trimheadobject contains field named trimtailobject contains field named trimbothobject contains field named charptralignconstobject contains field named alignconstthe m firstchar and m stringlength are the backing fields of the properties firstchar and length but the actual contents of the string are held in the chars property this is an indexed property that can be indexed to return all the chars in the string but i cannot find a corresponding field that holds the characters of a string any thoughts on why that is or how to get the backing field of the indexed property,['c#'] +405088,parsing dictionarylike url parameters in python i am working on implementing serverside filtering to serve kendouis grid component using pythonthe problem i am facing is that the ajax call that it generates by default seems to be incompatible with both flasks builtin url parser and pythons urlparse moduleheres a contrived sample of the type of query string i am having trouble with abcdfoobarbazfoobazqisfooqisbarheres the result i am going for a b c d foo bar baz baz qis qis bar unfortunately heres the requestargs you get from this if passed to a flask endpoint a b c d foobar baz foobaz qis fooqis barworse yet in practice the structure can be several layers deep a basic call where youre filtering the column foo to only rows where the value is equal to bar will produce the following filterlogic and filterfilters0value bar filterfilters0field foo filterfilters0operator eqi checked the rfc and it requires that the query string contain only nonhierarchical data while i believe it is referring to the object the uri represents there is no provision for this type of data structure in the specification that i can findi begin to write a function that would take a dictionary of params and return the nested construct they represented but i soon realized that it was nuanced problem and that surely someone out there has had this trouble beforeis anyone aware of either a module that will parse these parameters in the way i am wanting or an elegant way to parse them that i have perhaps overlooked,['python'] +405097,can you combine stdrecursive mutex with stdcondition variable can you combine stdrecursive mutex with stdcondition variable meaning do something like thisstdunique lockstdrecursive mutex locksome recursive mutexsome condition varwaitlockif it is not allowed then why noti am using vc11,['c++'] +405114,javaiowriteabortedexception writing aborted javaionotserializableexception orgapachelog4jlogger i am getting this error in tomcat when i am trying to log in a user into my system orgspringframeworkwebcontextcontextloader root webapplicationcontext initialization completed in 1967 mssau 14 2013 73917 pm orgapachecatalinasessionstandardmanager doloadsevere ioexception while loading persisted sessions javaiowriteabortedexception writing aborted javaionotserializableexception orgapachelog4jloggerjavaiowriteabortedexception writing aborted javaionotserializableexception orgapachelog4jlogger at javaioobjectinputstreamreadobject0unknown source at javaioobjectinputstreamdefaultreadfieldsunknown source at javaioobjectinputstreamreadserialdataunknown source at javaioobjectinputstreamreadordinaryobjectunknown source at javaioobjectinputstreamreadobject0unknown source at javaioobjectinputstreamreadobjectunknown source at javautillinkedlistreadobjectunknown source at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokeunknown source at sunreflectdelegatingmethodaccessorimplinvokeunknown source at javalangreflectmethodinvokeunknown source at javaioobjectstreamclassinvokereadobjectunknown source at javaioobjectinputstreamreadserialdataunknown source at javaioobjectinputstreamreadordinaryobjectunknown source at javaioobjectinputstreamreadobject0unknown source at javaioobjectinputstreamdefaultreadfieldsunknown source at javaioobjectinputstreamreadserialdataunknown source at javaioobjectinputstreamreadordinaryobjectunknown source at javaioobjectinputstreamreadobject0unknown source at javaioobjectinputstreamdefaultreadfieldsunknown source at javaioobjectinputstreamreadserialdataunknown source at javaioobjectinputstreamreadordinaryobjectunknown source at javaioobjectinputstreamreadobject0unknown source at javaioobjectinputstreamreadobjectunknown source at javautillinkedlistreadobjectunknown source at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokeunknown source at sunreflectdelegatingmethodaccessorimplinvokeunknown source at javalangreflectmethodinvokeunknown source at javaioobjectstreamclassinvokereadobjectunknown source at javaioobjectinputstreamreadserialdataunknown source at javaioobjectinputstreamreadordinaryobjectunknown source at javaioobjectinputstreamreadobject0unknown source at javaioobjectinputstreamdefaultreadfieldsunknown source at javaioobjectinputstreamreadserialdataunknown source at javaioobjectinputstreamreadordinaryobjectunknown source at javaioobjectinputstreamreadobject0unknown source at javaioobjectinputstreamreadobjectunknown source at javautilhashmapreadobjectunknown source at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokeunknown source at sunreflectdelegatingmethodaccessorimplinvokeunknown source at javalangreflectmethodinvokeunknown source at javaioobjectstreamclassinvokereadobjectunknown source at javaioobjectinputstreamreadserialdataunknown source at javaioobjectinputstreamreadordinaryobjectunknown source at javaioobjectinputstreamreadobject0unknown source at javaioobjectinputstreamdefaultreadfieldsunknown source at javaioobjectinputstreamreadserialdataunknown source at javaioobjectinputstreamreadordinaryobjectunknown source at javaioobjectinputstreamreadobject0unknown source at javaioobjectinputstreamreadobjectunknown source at javautillinkedlistreadobjectunknown source at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokeunknown source at sunreflectdelegatingmethodaccessorimplinvokeunknown source at javalangreflectmethodinvokeunknown source at javaioobjectstreamclassinvokereadobjectunknown source at javaioobjectinputstreamreadserialdataunknown source at javaioobjectinputstreamreadordinaryobjectunknown source at javaioobjectinputstreamreadobject0unknown source at javaioobjectinputstreamdefaultreadfieldsunknown source at javaioobjectinputstreamreadserialdataunknown source at javaioobjectinputstreamreadordinaryobjectunknown source at javaioobjectinputstreamreadobject0unknown source at javaioobjectinputstreamdefaultreadfieldsunknown source at javaioobjectinputstreamreadserialdataunknown source at javaioobjectinputstreamreadordinaryobjectunknown source at javaioobjectinputstreamreadobject0unknown source at javaioobjectinputstreamreadobjectunknown source at javautilhashmapreadobjectunknown source at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokeunknown source at sunreflectdelegatingmethodaccessorimplinvokeunknown source at javalangreflectmethodinvokeunknown source at javaioobjectstreamclassinvokereadobjectunknown source at javaioobjectinputstreamreadserialdataunknown source at javaioobjectinputstreamreadordinaryobjectunknown source at javaioobjectinputstreamreadobject0unknown source at javaioobjectinputstreamdefaultreadfieldsunknown source at javaioobjectinputstreamreadserialdataunknown source at javaioobjectinputstreamreadordinaryobjectunknown source at javaioobjectinputstreamreadobject0unknown source at javaioobjectinputstreamreadobjectunknown source at orgapachecatalinasessionstandardsessionreadobjectstandardsessionjava1595 at orgapachecatalinasessionstandardsessionreadobjectdatastandardsessionjava1060 at orgapachecatalinasessionstandardmanagerdoloadstandardmanagerjava284 at orgapachecatalinasessionstandardmanagerloadstandardmanagerjava204 at orgapachecatalinasessionstandardmanagerstartinternalstandardmanagerjava491 at orgapachecatalinautillifecyclebasestartlifecyclebasejava150 at orgapachecatalinacorestandardcontextstartinternalstandardcontextjava5294 at orgapachecatalinautillifecyclebasestartlifecyclebasejava150 at orgapachecatalinacorestandardcontextreloadstandardcontextjava3920 at orgapachecatalinaloaderwebapploaderbackgroundprocesswebapploaderjava426 at orgapachecatalinacorecontainerbasebackgroundprocesscontainerbasejava1345 at orgapachecatalinacorecontainerbasecontainerbackgroundprocessorprocesschildrencontainerbasejava1530 at orgapachecatalinacorecontainerbasecontainerbackgroundprocessorprocesschildrencontainerbasejava1540 at orgapachecatalinacorecontainerbasecontainerbackgroundprocessorprocesschildrencontainerbasejava1540 at orgapachecatalinacorecontainerbasecontainerbackgroundprocessorruncontainerbasejava1519 at javalangthreadrununknown sourcecaused by javaionotserializableexception orgapachelog4jlogger at javaioobjectoutputstreamwriteobject0unknown source at javaioobjectoutputstreamdefaultwritefieldsunknown source at javaioobjectoutputstreamwriteserialdataunknown source at javaioobjectoutputstreamwriteordinaryobjectunknown source at javaioobjectoutputstreamwriteobject0unknown source at javaioobjectoutputstreamwriteobjectunknown source at javautillinkedlistwriteobjectunknown source at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokeunknown source at sunreflectdelegatingmethodaccessorimplinvokeunknown source at javalangreflectmethodinvokeunknown source at javaioobjectstreamclassinvokewriteobjectunknown source at javaioobjectoutputstreamwriteserialdataunknown source at javaioobjectoutputstreamwriteordinaryobjectunknown source at javaioobjectoutputstreamwriteobject0unknown source at javaioobjectoutputstreamdefaultwritefieldsunknown source at javaioobjectoutputstreamwriteserialdataunknown source at javaioobjectoutputstreamwriteordinaryobjectunknown source at javaioobjectoutputstreamwriteobject0unknown source at javaioobjectoutputstreamdefaultwritefieldsunknown source at javaioobjectoutputstreamwriteserialdataunknown source at javaioobjectoutputstreamwriteordinaryobjectunknown source at javaioobjectoutputstreamwriteobject0unknown source at javaioobjectoutputstreamwriteobjectunknown source at javautillinkedlistwriteobjectunknown source at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokeunknown source at sunreflectdelegatingmethodaccessorimplinvokeunknown source at javalangreflectmethodinvokeunknown source at javaioobjectstreamclassinvokewriteobjectunknown source at javaioobjectoutputstreamwriteserialdataunknown source at javaioobjectoutputstreamwriteordinaryobjectunknown source at javaioobjectoutputstreamwriteobject0unknown source at javaioobjectoutputstreamdefaultwritefieldsunknown source at javaioobjectoutputstreamwriteserialdataunknown source at javaioobjectoutputstreamwriteordinaryobjectunknown source at javaioobjectoutputstreamwriteobject0unknown source at javaioobjectoutputstreamwriteobjectunknown source at javautilhashmapwriteobjectunknown source at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokeunknown source at sunreflectdelegatingmethodaccessorimplinvokeunknown source at javalangreflectmethodinvokeunknown source at javaioobjectstreamclassinvokewriteobjectunknown source at javaioobjectoutputstreamwriteserialdataunknown source at javaioobjectoutputstreamwriteordinaryobjectunknown source at javaioobjectoutputstreamwriteobject0unknown source at javaioobjectoutputstreamdefaultwritefieldsunknown source at javaioobjectoutputstreamwriteserialdataunknown source at javaioobjectoutputstreamwriteordinaryobjectunknown source at javaioobjectoutputstreamwriteobject0unknown source at javaioobjectoutputstreamwriteobjectunknown source at javautillinkedlistwriteobjectunknown source at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokeunknown source at sunreflectdelegatingmethodaccessorimplinvokeunknown source at javalangreflectmethodinvokeunknown source at javaioobjectstreamclassinvokewriteobjectunknown source at javaioobjectoutputstreamwriteserialdataunknown source at javaioobjectoutputstreamwriteordinaryobjectunknown source at javaioobjectoutputstreamwriteobject0unknown source at javaioobjectoutputstreamdefaultwritefieldsunknown source at javaioobjectoutputstreamwriteserialdataunknown source at javaioobjectoutputstreamwriteordinaryobjectunknown source at javaioobjectoutputstreamwriteobject0unknown source at javaioobjectoutputstreamdefaultwritefieldsunknown source at javaioobjectoutputstreamwriteserialdataunknown source at javaioobjectoutputstreamwriteordinaryobjectunknown source at javaioobjectoutputstreamwriteobject0unknown source at javaioobjectoutputstreamwriteobjectunknown source at javautilhashmapwriteobjectunknown source at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokeunknown source at sunreflectdelegatingmethodaccessorimplinvokeunknown source at javalangreflectmethodinvokeunknown source at javaioobjectstreamclassinvokewriteobjectunknown source at javaioobjectoutputstreamwriteserialdataunknown source at javaioobjectoutputstreamwriteordinaryobjectunknown source at javaioobjectoutputstreamwriteobject0unknown source at javaioobjectoutputstreamdefaultwritefieldsunknown source at javaioobjectoutputstreamwriteserialdataunknown source at javaioobjectoutputstreamwriteordinaryobjectunknown source at javaioobjectoutputstreamwriteobject0unknown source at javaioobjectoutputstreamwriteobjectunknown source at orgapachecatalinasessionstandardsessionwriteobjectstandardsessionjava1671 at orgapachecatalinasessionstandardsessionwriteobjectdatastandardsessionjava1077 at orgapachecatalinasessionstandardmanagerdounloadstandardmanagerjava432 at orgapachecatalinasessionstandardmanagerunloadstandardmanagerjava353 at orgapachecatalinasessionstandardmanagerstopinternalstandardmanagerjava518 at orgapachecatalinautillifecyclebasestoplifecyclebasejava232 at orgapachecatalinacorestandardcontextstopinternalstandardcontextjava5474 at orgapachecatalinautillifecyclebasestoplifecyclebasejava232 at orgapachecatalinacorestandardcontextreloadstandardcontextjava3913 7 moresau 14 2013 73917 pm orgapachecatalinasessionstandardmanager startinternalsevere exception loading sessions from persistent storagejavaiowriteabortedexception writing aborted javaionotserializableexception orgapachelog4jlogger at javaioobjectinputstreamreadobject0unknown source at javaioobjectinputstreamdefaultreadfieldsunknown source at javaioobjectinputstreamreadserialdataunknown source at javaioobjectinputstreamreadordinaryobjectunknown source at javaioobjectinputstreamreadobject0unknown source at javaioobjectinputstreamreadobjectunknown source at javautillinkedlistreadobjectunknown source at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokeunknown source at sunreflectdelegatingmethodaccessorimplinvokeunknown source at javalangreflectmethodinvokeunknown source at javaioobjectstreamclassinvokereadobjectunknown source at javaioobjectinputstreamreadserialdataunknown source at javaioobjectinputstreamreadordinaryobjectunknown source at javaioobjectinputstreamreadobject0unknown source at javaioobjectinputstreamdefaultreadfieldsunknown source at javaioobjectinputstreamreadserialdataunknown source at javaioobjectinputstreamreadordinaryobjectunknown source at javaioobjectinputstreamreadobject0unknown source at javaioobjectinputstreamdefaultreadfieldsunknown source at javaioobjectinputstreamreadserialdataunknown source at javaioobjectinputstreamreadordinaryobjectunknown source at javaioobjectinputstreamreadobject0unknown source at javaioobjectinputstreamreadobjectunknown source at javautillinkedlistreadobjectunknown source at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokeunknown source at sunreflectdelegatingmethodaccessorimplinvokeunknown source at javalangreflectmethodinvokeunknown source at javaioobjectstreamclassinvokereadobjectunknown source at javaioobjectinputstreamreadserialdataunknown source at javaioobjectinputstreamreadordinaryobjectunknown source at javaioobjectinputstreamreadobject0unknown source at javaioobjectinputstreamdefaultreadfieldsunknown source at javaioobjectinputstreamreadserialdataunknown source at javaioobjectinputstreamreadordinaryobjectunknown source at javaioobjectinputstreamreadobject0unknown source at javaioobjectinputstreamreadobjectunknown source at javautilhashmapreadobjectunknown source at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokeunknown source at sunreflectdelegatingmethodaccessorimplinvokeunknown source at javalangreflectmethodinvokeunknown source at javaioobjectstreamclassinvokereadobjectunknown source at javaioobjectinputstreamreadserialdataunknown source at javaioobjectinputstreamreadordinaryobjectunknown source at javaioobjectinputstreamreadobject0unknown source at javaioobjectinputstreamdefaultreadfieldsunknown source at javaioobjectinputstreamreadserialdataunknown source at javaioobjectinputstreamreadordinaryobjectunknown source at javaioobjectinputstreamreadobject0unknown source at javaioobjectinputstreamreadobjectunknown source at javautillinkedlistreadobjectunknown source at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokeunknown source at sunreflectdelegatingmethodaccessorimplinvokeunknown source at javalangreflectmethodinvokeunknown source at javaioobjectstreamclassinvokereadobjectunknown source at javaioobjectinputstreamreadserialdataunknown source at javaioobjectinputstreamreadordinaryobjectunknown source at javaioobjectinputstreamreadobject0unknown source at javaioobjectinputstreamdefaultreadfieldsunknown source at javaioobjectinputstreamreadserialdataunknown source at javaioobjectinputstreamreadordinaryobjectunknown source at javaioobjectinputstreamreadobject0unknown source at javaioobjectinputstreamdefaultreadfieldsunknown source at javaioobjectinputstreamreadserialdataunknown source at javaioobjectinputstreamreadordinaryobjectunknown source at javaioobjectinputstreamreadobject0unknown source at javaioobjectinputstreamreadobjectunknown source at javautilhashmapreadobjectunknown source at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokeunknown source at sunreflectdelegatingmethodaccessorimplinvokeunknown source at javalangreflectmethodinvokeunknown source at javaioobjectstreamclassinvokereadobjectunknown source at javaioobjectinputstreamreadserialdataunknown source at javaioobjectinputstreamreadordinaryobjectunknown source at javaioobjectinputstreamreadobject0unknown source at javaioobjectinputstreamdefaultreadfieldsunknown source at javaioobjectinputstreamreadserialdataunknown source at javaioobjectinputstreamreadordinaryobjectunknown source at javaioobjectinputstreamreadobject0unknown source at javaioobjectinputstreamreadobjectunknown source at orgapachecatalinasessionstandardsessionreadobjectstandardsessionjava1595 at orgapachecatalinasessionstandardsessionreadobjectdatastandardsessionjava1060 at orgapachecatalinasessionstandardmanagerdoloadstandardmanagerjava284 at orgapachecatalinasessionstandardmanagerloadstandardmanagerjava204 at orgapachecatalinasessionstandardmanagerstartinternalstandardmanagerjava491 at orgapachecatalinautillifecyclebasestartlifecyclebasejava150 at orgapachecatalinacorestandardcontextstartinternalstandardcontextjava5294 at orgapachecatalinautillifecyclebasestartlifecyclebasejava150 at orgapachecatalinacorestandardcontextreloadstandardcontextjava3920 at orgapachecatalinaloaderwebapploaderbackgroundprocesswebapploaderjava426 at orgapachecatalinacorecontainerbasebackgroundprocesscontainerbasejava1345 at orgapachecatalinacorecontainerbasecontainerbackgroundprocessorprocesschildrencontainerbasejava1530 at orgapachecatalinacorecontainerbasecontainerbackgroundprocessorprocesschildrencontainerbasejava1540 at orgapachecatalinacorecontainerbasecontainerbackgroundprocessorprocesschildrencontainerbasejava1540 at orgapachecatalinacorecontainerbasecontainerbackgroundprocessorruncontainerbasejava1519 at javalangthreadrununknown sourcecaused by javaionotserializableexception orgapachelog4jlogger at javaioobjectoutputstreamwriteobject0unknown source at javaioobjectoutputstreamdefaultwritefieldsunknown source at javaioobjectoutputstreamwriteserialdataunknown source at javaioobjectoutputstreamwriteordinaryobjectunknown source at javaioobjectoutputstreamwriteobject0unknown source at javaioobjectoutputstreamwriteobjectunknown source at javautillinkedlistwriteobjectunknown source at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokeunknown source at sunreflectdelegatingmethodaccessorimplinvokeunknown source at javalangreflectmethodinvokeunknown source at javaioobjectstreamclassinvokewriteobjectunknown source at javaioobjectoutputstreamwriteserialdataunknown source at javaioobjectoutputstreamwriteordinaryobjectunknown source at javaioobjectoutputstreamwriteobject0unknown source at javaioobjectoutputstreamdefaultwritefieldsunknown source at javaioobjectoutputstreamwriteserialdataunknown source at javaioobjectoutputstreamwriteordinaryobjectunknown source at javaioobjectoutputstreamwriteobject0unknown source at javaioobjectoutputstreamdefaultwritefieldsunknown source at javaioobjectoutputstreamwriteserialdataunknown source at javaioobjectoutputstreamwriteordinaryobjectunknown source at javaioobjectoutputstreamwriteobject0unknown source at javaioobjectoutputstreamwriteobjectunknown source at javautillinkedlistwriteobjectunknown source at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokeunknown source at sunreflectdelegatingmethodaccessorimplinvokeunknown source at javalangreflectmethodinvokeunknown source at javaioobjectstreamclassinvokewriteobjectunknown source at javaioobjectoutputstreamwriteserialdataunknown source at javaioobjectoutputstreamwriteordinaryobjectunknown source at javaioobjectoutputstreamwriteobject0unknown source at javaioobjectoutputstreamdefaultwritefieldsunknown source at javaioobjectoutputstreamwriteserialdataunknown source at javaioobjectoutputstreamwriteordinaryobjectunknown source at javaioobjectoutputstreamwriteobject0unknown source at javaioobjectoutputstreamwriteobjectunknown source at javautilhashmapwriteobjectunknown source at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokeunknown source at sunreflectdelegatingmethodaccessorimplinvokeunknown source at javalangreflectmethodinvokeunknown source at javaioobjectstreamclassinvokewriteobjectunknown source at javaioobjectoutputstreamwriteserialdataunknown source at javaioobjectoutputstreamwriteordinaryobjectunknown source at javaioobjectoutputstreamwriteobject0unknown source at javaioobjectoutputstreamdefaultwritefieldsunknown source at javaioobjectoutputstreamwriteserialdataunknown source at javaioobjectoutputstreamwriteordinaryobjectunknown source at javaioobjectoutputstreamwriteobject0unknown source at javaioobjectoutputstreamwriteobjectunknown source at javautillinkedlistwriteobjectunknown source at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokeunknown source at sunreflectdelegatingmethodaccessorimplinvokeunknown source at javalangreflectmethodinvokeunknown source at javaioobjectstreamclassinvokewriteobjectunknown source at javaioobjectoutputstreamwriteserialdataunknown source at javaioobjectoutputstreamwriteordinaryobjectunknown source at javaioobjectoutputstreamwriteobject0unknown source at javaioobjectoutputstreamdefaultwritefieldsunknown source at javaioobjectoutputstreamwriteserialdataunknown source at javaioobjectoutputstreamwriteordinaryobjectunknown source at javaioobjectoutputstreamwriteobject0unknown source at javaioobjectoutputstreamdefaultwritefieldsunknown source at javaioobjectoutputstreamwriteserialdataunknown source at javaioobjectoutputstreamwriteordinaryobjectunknown source at javaioobjectoutputstreamwriteobject0unknown source at javaioobjectoutputstreamwriteobjectunknown source at javautilhashmapwriteobjectunknown source at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokeunknown source at sunreflectdelegatingmethodaccessorimplinvokeunknown source at javalangreflectmethodinvokeunknown source at javaioobjectstreamclassinvokewriteobjectunknown source at javaioobjectoutputstreamwriteserialdataunknown source at javaioobjectoutputstreamwriteordinaryobjectunknown source at javaioobjectoutputstreamwriteobject0unknown source at javaioobjectoutputstreamdefaultwritefieldsunknown source at javaioobjectoutputstreamwriteserialdataunknown source at javaioobjectoutputstreamwriteordinaryobjectunknown source at javaioobjectoutputstreamwriteobject0unknown source at javaioobjectoutputstreamwriteobjectunknown source at orgapachecatalinasessionstandardsessionwriteobjectstandardsessionjava1671 at orgapachecatalinasessionstandardsessionwriteobjectdatastandardsessionjava1077 at orgapachecatalinasessionstandardmanagerdounloadstandardmanagerjava432 at orgapachecatalinasessionstandardmanagerunloadstandardmanagerjava353 at orgapachecatalinasessionstandardmanagerstopinternalstandardmanagerjava518 at orgapachecatalinautillifecyclebasestoplifecyclebasejava232 at orgapachecatalinacorestandardcontextstopinternalstandardcontextjava5474 at orgapachecatalinautillifecyclebasestoplifecyclebasejava232 at orgapachecatalinacorestandardcontextreloadstandardcontextjava3913 7 moresau 14 2013 73917 pm orgapachecatalinacorestandardcontext reloadinfo reloading context with name pirs web is completedthe thing is that most answers to this question say make that class implement javaioserializable but here i do not see any of my own classes involved these are just libraries i use and i cannot modify them or it is tomcat trying to use log4j,['java'] +405131,matplotlib custom markersymbol so there is this guide examplesscatter symbolhtml examplesscatter symbolhtmlfrom matplotlib import pyplot as pltimport numpy as npimport matplotlibx nparange00 500 20y x 13 nprandomrandxshape 300s nprandomrandxshape 800 500pltscatterx y s cg alpha05 markerrclubsuit labelluckpltxlabelleprechaunspltylabelgoldpltlegendloc2pltshowbut what if you are like me and do not want to use a clubsuit markerhow do you make your own marker updatewhat i like about this special marker type is that it is easy to adjust with simple matplotlib syntaxfrom matplotlib import pyplot as pltimport numpy as npimport matplotlibx nparange00 500 20y x 13 nprandomrandxshape 300s nprandomrandxshape 800 500pltplotx y ro alpha05 markerrclubsuit markersize22pltxlabelleprechaunspltylabelgoldpltshow,['python'] +405135,linq thistinct record containing keywords i need to return a thistinct list of records based on a car keywords search like alfa 147the problem is that as i have 3 alfa cars it returns 1 3 records it seems 1 for the alfa and 147 result and 3 for the alfa resulteditthe sqlserver query look something like thisselect thistinct cid cname countnumber of ads in the keywordadcategories table with those 2 keywords from categories as cinner join keywordadcategories as kac on kaccategory id cidinner join keywordadcategories as kac1 on kacad id kac1ad id and kac1keyword id select id from keywords where name alfainner join keywordadcategories as kac2 on kac1ad id kac2ad id and kac2keyword id select id from keywords where name 147my linq query is var query from k in keywordquery where splitkeywordscontainskname join kac in keywordadcategoryquery on kid equals kackeyword id join c in categoryquery on kaccategory id equals cid join a in adquery on kacad id equals aid select new categorylistbykeywordsdetaildto id cid name cname searchcount keywordadcategoryquerywheres scategory id cidwheres skeyword id kidthistinctcount listcontroller clistcontroller listaction clistaction var searchresults new categorylistbybeywordslistdto searchresultscategorylistbykeywordsdetails querythistincttolistthe entities arepublic class keyword primary properties public int id get set public string name get set keyword sample data 1356 alfa 1357 romeo 1358 145 1373 147public class category primary properties public int id get set public string name get set category sample data 1 null 1 carros 2 null 1 motos 3 null 2 oficinas 4 null 2 stands 5 null 1 comerciais 8 null 1 barcos 9 null 1 maquinas 10 null 1 caravanas e autocaravanas 11 null 1 peaas e acessa3rios 12 1 1 citadino 13 1 1 utilitario 14 1 1 monovolumepublic class keywordadcategory key columnkeyword id order 0 public int keyword id get set key columnad id order 1 public int ad id get set key columncategory id order 2 public int category id get set keywordadcategory sample data 1356 1017 1 1356 1018 1 1356 1019 1 1357 1017 1 1357 1018 1 1357 1019 1 1358 1017 1 1373 1019 1 public class ad primary properties public int id get set public string title get set public string titlestandard get set public string version get set public int year get set public decimal price get set navigation properties public member member get set public category category get set public ilistfeature features get set public ilistpicture pictures get set public ilistoperation operations get set public class adcar ad public int kms get set public make make get set public model model get set public fuel fuel get set public color color get set adcar sample data 1017 alfa romeo 145 16tdi 2013 alfa romeo 145 16tdi 2013 12 2 16tdi 10 1 2013 1 20 2052 adcar 1018 alfa romeo 146 16tdi 2013 alfa romeo 146 16tdi 2013 12 2 5 16tdi 10 2 2013 1 20 2052 adcar 1019 alfa romeo 147 16tdi 2013 alfa romeo 147 16tdi 2013 12 2 6 16tdi 10 3 2013 1 20 2052 adcarthe result i expect for the search of alfa is cars 3 and for the search of alfa 147 is cars 1 and actually the result i get is cars 1 and cars 3,['c#'] +405209,is it possible to use core location gps without any internet connection thisabled cellular network i need to capture the gps coordinates no reverse geocoding names etc in regions where there is no internet such as on a sailing boat or in the sahara desert so that you just get the latitude and longitude of where you aredoes core location support that and falls back to gpsonly no cell triangulation or wifi location mappingi think it does but just want to be sure,['ios'] +405216,jquery href click how can i fire up an event i have this anchor and on click i would like to popup somethingthis href is within a page that has other hrefsa clasign new hrefsign upsign upajquerydocumentreadyfunction ahref sign upclickfunction alertsign new href executed the above code does not fire up,"['javascript', 'jquery', 'html']" +405227,revising the syntax of duffs device is this legal cc only last night i encountered the curious duffs device for the first time i have been doing some reading on it and i do not think it is that daunting to understand what i am curious about is the strange syntax from wikipediaregister short to fromregister int count register int and count 7 8 switchcount 8 case 0 do to from case 7 to from case 6 to from case 5 to from case 4 to from case 3 to from case 2 to from case 1 to from whilen 0 i was reading the c standard definition of a switch statement please let me know if that is outdated i am not familiar with openstdorg so far as i can understand case statements are just simplified jump statements for use by the switch statementthe switch itself completely ignores the nested dowhile and the loop ignores the case statements since the switch jumps inside of the loop the loop is executed the switch is there to cover the remainder from the division by 8 and the loop handles the portion that is evenly divisible this all makes sensemy question then is why the awkward syntax it occurs to me that the loop could be written such that all of the case statements are contained within yes i see nothing in the standard that prohibits this behavior and it compiles correctly under gcc 47 so is the following considered legalregister short to fromregister int count register int and count 7 8 switch count 0 8 count 8 do case 0 to from case 7 to from case 6 to from case 5 to from case 4 to from case 3 to from case 2 to from case 1 to from default invalid count suppress warning etc whilen 0 to me this makes the intent of the code much clearer thanks for any feedback edit as noted below the original code was written for c and had implicit int for the count and n variables since i tagged it c i have modified thatedit 2 modified the revised example code to account for invalid count values,['c++'] +405239,with c wcf soap consumer that uses wsse plain text authentication i have a wcf soap consumer that is implemented by visual studio 2012 from a wsdl the wsdl was generated by peopletools the base object is of type systemservicemodelclientbasei need the soap request to resemblesoapenvenvelope xmlnssoapenv xmlnssch soapenvheader wssesecurity soapmustunderstand1 xmlnssoap xmlnswsse wsseusernametoken wsseusernameplain text username goes herewsseusername wssepasswordplain text password goes herewssepassword wsseusernametoken wssesecurity soapenvheader soapenvbody schinputparameters last namearenlast name first namecambrefirst name schinputparameters soapenvbodysoapenvenvelopeheres the closest we can getsenvelope xmlnss xmlnsa sheader aaction smustunderstand1aaction amessageidurnuuid3cc3f2cac647466cb38bf2423462c837amessageid areplyto aaddressaaddress areplyto ato smustunderstand1httpinternal url to soap listenerato sheader sbody trequestsecuritytoken contextuuid7db829752b22423694a1b3344a0bf04d1 xmlnst ttokentypettokentype trequesttypetrequesttype tkeysize256tkeysize tbinaryexchange valuetype encodingtypefgmbafobaabwawfq9ihufguo6tch0baq0n3usmmxzqa78udm4xfj5gaagaavaduabqakwbpafmajwaoamga4abmabaeaabxaqabakaayabaaxabgacwacaqatbinaryexchange trequestsecuritytoken sbodysenvelopeyoull notice two problemsno plaintext wsse credentials passes a binary form of the credentials that the service would not useauthentication is in body not headerthe request omits inputparametersheres the essential c codevar service new servicewithbizarrenamefrompeoplesoftif serviceclientcredentials null throw new nullreferenceexceptionserviceclientcredentialsusernameusername testserviceclientcredentialsusernamepassword passwordvar binding new wshttpbindingsecuritymodetransportwithmessagecredential security new wshttpsecurityserviceendpointbinding bindingbindingsecuritytransportclientcredentialtype httpclientcredentialtypenonebindingsecuritymessageclientcredentialtype messagecredentialtypeusernamebindingsecuritymode securitymodemessagevar input new inputparameters last name cambre first name aren var returndata servicebizarrepeoplesoftnameformethodinputthere is no http layer security and transport is sslencrypted authentication is only based on the soap message,['c#'] +405255,merging dictionaries incompatible type error i have been trying to merge two nsdictionaries for a couple hours now searched and found that i can use nsmutabledictionary addentriesfromdictionary nsdictionary areaattributes area entity attributesbyname nsdictionary gpsattributes gps entity attributesbyname nsmutabledictionary areaattributesm areaattributes mutablecopy nsmutabledictionary gpsattributesm gpsattributes mutablecopy nsmutabledictionary combinedattributes areaattributesm addentriesfromdictionarygpsattributesmbut i get the errorinitializing nsmutabledictionary strong with an expression of incompatible type voidso this is saying that areaattributesm addentriesfromdictionarygpsattributesm returns void is my understanding correct and why is it returning void,"['ios', 'objective-c']" +405309,is cc one language or two languages is cc one language or two languages i heard c was just c with classes is that right,"['c++', 'c']" +405337,how to use this singleton class in c i am struggling with using singleton design pattern i am trying to use it in this simple console application i have a problem with it in the main method in program class i want to define object from the singleton class such as var data singletoninstance but i do not know why i cannot do thatalso i do not know why i am getting the following error message when i run the programunhandled exception systemnullrefernceexception object reference not set to an instance of an objectso how to fix thatsingleton classnamespace singleton class singleton variable private static singleton instance private liststring messages constructor private singleton property public static singleton instance get if instance null instance new singleton return instance methods public void messagestring message messagesaddmessage public bool hasmessagestring message return messagescontainsmessage program classnamespace singleton class program static void mainstring args var data singletoninstance singletoninstancemessagehello world ifsingletoninstancehasmessage12 consolewritelineno string else consolewritelinethere is a match updateguys i really appreciate your help so far the program is working now but the logic is not working if you look at the main program you will see that the list only has hello world however when i used the hasmessage method does not work because the program keeps showing there is a match but it should show me no string as there is no match so how to fix that,['c#'] +405368,c msmq the max size of a single message using msmq i want to send a message near 1 gb i want to send array of bytes but i can send only 4 mb how can i get around this limitation,['c#'] +405384,a custom string class creation i tried to create a custom class string in javalang package in my eclipse workspaceinitially i suspected that a same class in same package can not be created but to my utter surprise i was able to create a class string in same package ie javalang now i am confused1 why is it possible and2 what can be the reason if that is allowed3 what will be the use if this type of creation of java classes is allowed in java,['java'] +405407,awscli getting started error i would already asked this on the aws official forum on jan2 but not any reply so i m posting it here again so that i can get the error fixedi installed awscli as stated in this page and the following is the installation detailsmillisami at millisami in codeface tester on design a1a which python usrlocalbinpythonmillisami at millisami in codeface tester on design a1a python version python 273millisami at millisami in codeface tester on design a1a pip install awscli upgrade requirement already uptodate awscli in usrlocallibpython27sitepackagesrequirement already uptodate botocore040 in usrlocallibpython27sitepackagesbotocore041py27egg from awsclirequirement already uptodate six110 in usrlocallibpython27sitepackagessix120py27egg from awsclirequirement already uptodate argparse11 in usrlocallibpython27sitepackagesargparse121py27egg from awsclirequirement already uptodate requests0121100 in usrlocallibpython27sitepackagesrequests0142py27egg from botocore040awsclirequirement already uptodate pythondateutil21 in usrlocallibpython27sitepackagespython dateutil21py27egg from botocore040awsclicleaning upmillisami at millisami in codeface tester on design a1a aws help traceback most recent call last file usrlocalsharepythonaws line 15 in module import awscliclidriver file usrlocallibpython27sitepackagesawscli init py line 18 in module import botocorebaseimporterror no module named botocorebasemillisami at millisami in codeface tester on design1 a a1since installing the pip its successful but why that botocore is being reported no such file,['python'] +405447,getfiledescriptor returns null while reading mp3 files from the expansion files i have downloaded and stored the expansion files successfullybut it crashes when i try to play the mp3 inside zipresourcefile expansionfile apkexpansionsupportgetapkexpansionzipfilegetapplicationcontext 1 0 inputstream filestream expansionfilegetinputstreammysongmp3 assetfiledescriptor asd expansionfilegetassetfiledescriptormysongmp3 mediaplayer mediaplayer new mediaplayer mediaplayersetaudiostreamtypeaudiomanagerstream music mediaplayersetdatasourceasdgetfiledescriptor asdgetstartoffset asdgetlength asdclose mediaplayerprepare mediaplayerstarthere the logcat says both the inputstream and the file descriptor are nullcan anyone help me,['android'] +405506,javascript spaframeworks single page application my goal is to migrate an existing web application to a restful spa single page applicationcurrently i am evaluating several javascript web application frameworks my requirements are as followrestful data layer like emberdatamvstructuredynamic routestestingsupportcoding by conventionseosupportbrowserhistorysupportgood api documentationproductionreadyliving communitybackbone the current application is using backbonejs all in all backbonejs is a nice project but i am missing well defined structures that determine where what has to happen and how things must get implemented working in a bigger team with changing developers this leads to some kind of unstructured code difficult to maintenance and difficult to understandthis is why i am searching now for a framework that already defines all this stuffember i looked into emberjs the last days the approach seems very promising to me but unfortunately the code changes almost daily so i would not call it productionready and we cannot wait for it to be version 10 unfortunately but i really like the idea behind this frameworkangularangularjs is a widely spreaded framework as well maintained by google but i could not get familiar with angular for me the structure seems kind of unclear explanations are missing of the overall responsibilites of each part of the framework and the implementations feel circuitousjust to get this straight this is just my personal impression and might be based on missing knowledgebatman meteoras i understood both frameworks need a server part as well and since we just want a restful backend no matter what language technic or software this is not what we want further the backend api does already exist rorknockout canjs spinei did not go any deeper in these three candidates maybe this will be my next stepso my questions nowam i missing any good spaframeworkswhat framework would you suggestrecommendwould you avoid any of the mentioned frameworkswhat is your experience in bigger sp applicationskind regardschristopherps i would would like to recommend a great blogpost from steven anderson core developer from knockoutjs about the throne of jsconference from 2012 and javascript frameworks in generalps yes i know there are already some question on so but since the development is so rapidly and fast for spas most of them are already outofdate,['javascript'] +405507,thisable spring method caching through external property i configured spring method caching with ehcache and annotation driven configurationi would like however to be able to thisable it from a configuration file we use in the applicationmy first idea was to call netsfehcachecachemanagercachemanager with no arguments if method caching is thisabled this throws exceptionjavalangillegalargumentexception loadcaches must not return an empty collectionat orgspringframeworkutilassertnotemptyassertjava268at orgspringframeworkcachesupportabstractcachemanagerafterpropertiessetabstractcachemanagerjava49my second idea was to configure the netsfehcachecachemanagercachemanager with default data so that the cache is not used maxelementsinmemory 0 etc but then the cache is still used which is not what i wantthere is a property netsfehcachethisabled but i do not want do thisable hibernate caching that also uses ehcacheq how can i configure everything to have spring method caching but thisable it from my external configuration file i do not want to modify the applicationcontext nor the code to enablethisable method caching only the configuration file we use in the application can be modified,['java'] +405515,upgrading to net 45 an itemscontrol is inconsistent with its items source i am building an application which uses many itemcontrolsdatagrids and listviews in order to easily update these lists from background threads i used this extension to observablecollections which has worked finetoday i installed vs12which in turn installed net 45 as i want to use a component which is written for net 45 before even upgrading my project to net 45 from 40 my datagrid started throwing invalidoperationexception when updated from a workerthread exception messagethis exception was thrown because the generator for control systemwindowscontrolsdatagrid itemscount5 with name unnamed has received sequence of collectionchanged events that do not agree with the current state of the items collection the following differences were detected accumulated count 4 is different from actual count 5 accumulated count is count at last reset adds removes since last resetrepro codexamlwindow xclasstest1mainwindow xmlns xmlnsx titlemainwindow height350 width525 grid datagrid itemssourcebinding items modeonetime presentationtracesourcestracelevelhigh gridwindowcodepublic partial class mainwindow window public extendedobservablecollectionint items get private set public mainwindow initializecomponent items new extendedobservablecollectionint datacontext this loaded mainwindow loaded void mainwindow loadedobject sender routedeventargs e taskfactorystartnew foreach var item in enumerablerange1 500 itemsadditem,['c#'] +405538,is it possible to build protobuf without pthread there is a need to use protocol buffers on the realtime os where there is no pthread i am able to link protobuf statically this wayg g wall examplepbcc examplecc o example static lprotobuf lpthreadhowever without pthread i get link errors is it possible to configure protobuf to work without pthread,['c++'] +405571,java remote debugging tomcat app why does the jvm not listen i want to remote debug an application running in tomcat 7 tomcat is running as a service on a win2008 serveri added the following to the java options in the java configuration panel of tomcatxdebug xrunjdwptransportdt socketaddress4711serverysuspendn and opened the firewall on my workstation and the server for this portbut when i try debugging from intellij 9 on my workstation i get an error message unable to open debugger port javanetconnectexception connection timed out connect the jvm is the standatd sunoracle 64 bit jvm version 160 27i verified that the command line parameters are in use by accessing managementfactorygetruntimemxbeangetinputarguments within the application deployed to tomcat and logging the result to the log filei verified via wireshark on my workstation and on the server that the tcp request on port 4711 is sent from my pc and arriving on the server but there is is no answer running netstat a on the server does not show a process listening on this port so i assume somehow tomcatjvm does not start the remote debugging,['java'] +405577,foreach in c int array i am new to c and i am writing the following codei needed to iterate over all the addons in my calling function testfunction i know this works in c but this code is not working can anyone please point out the right way to do it in c include stdafxhinclude iostreaminclude resourcehint testfunctionchar testerint tmain int mainprod2 int addons78910 testfunctionmainprodaddonsvoid testfunctionint mainprodint addons forint x 0 addonslengthx not working stdcout addonsx i tried to implment vector as below suggestions by you guysthanks guys and i really appreciate include stdafxhinclude iostreaminclude resourcehinclude vectorvoid testfunctionstdvectorint addonsint tmainint argc tchar argv stdvectorint addons forint i 0 i10i addonspush backi testfunctionaddonsvoid testfunctionstdvectorint addons forint i 0 iaddonssizei stdcoutaddonsati,['c++'] +405578,whats the point of enumerableelementat ienumerablet exposes an enumerator so the object can be enumerated there is nothing about indexes exposed by this interface ilistt is about indexes as it exposes the indexof methodso whats the point of enumerableelementat i just read the doc of this linq extension methodreturns the element at a specified index in a sequencewell yes it is about a sequence not just an ienumerable reading the remarksif the type of source implements ilist that implementation is used to obtain the element at the specified index otherwise this method obtains the specified elementokay so if the concrete type implements something that inherits from ilistt which is an actual sequence then it is the same as indexof if not it iterates until the index is reachedheres a sample scenario some extension method exposed by a lib i know it is not a good piece of code but let us say it is coded this waypublic static class enumerableextensions returns true if all elements are ordered public static bool isenumerableorderedthis ienumerableint value iterates over elements using an index for int i 0 i valuecount 1 i if valueelementati valueelementati 1 return false return true heres a collection that is enumerable but does not always returns its objects in the same orderpublic class randomaccessenumerablet ienumerablet private listt innerlist private static random rnd new random public randomaccessenumerableienumerablet list innerlist listtolist public ienumeratort getenumerator var listcount thisinnerlistcount listint enumeratedindexes new listint for int i 0 i listcount i int randomindex 1 while randomindex 0 enumeratedindexescontainsrandomindex randomindex rndnextlistcount enumeratedindexesaddrandomindex yield return thisinnerlistrandomindex ienumerator ienumerablegetenumerator return thisgetenumerator heres some test programinternal class program private static void main var test0 new listint 0 1 2 3 var test1 new randomaccessenumerableinttest0 consolewritelinewith list consolewritelinetest0isenumerableordered true consolewritelinetest0isenumerableordered true consolewritelinetest0isenumerableordered true consolewritelinetest0isenumerableordered true consolewritelinetest0isenumerableordered true consolewritelinewith randomaccessenumerable consolewritelinetest1isenumerableordered might be true or false consolewritelinetest1isenumerableordered might be true or false consolewritelinetest1isenumerableordered might be true or false consolewritelinetest1isenumerableordered might be true or false consolewritelinetest1isenumerableordered might be true or false consoleread so as randomaccessenumerable might return enumerated objects in a random order you just cannot rely on the simple ienumerablet interface to assume your elements are indexed so you do not want to use elementat for an ienumerablein the above example i think isenumerableordered should require a ilistt parameter as it implies elements are a sequence i actually cannot find a scenario where the elementat method is useful and not bugprone,"['c#', '.net']" +405608,implementing three actions inside a single menu item in android i want to have similar menu item functionality as in the chrome browser for mobile as it is in the picture i want to have back forward refresh menu items in a single row how can i implement a similar menu item is there any reference or is there is any hack to bring this functionalitymy app is aimed only for tablets here is my current action bar menu item menu xmlnsandroid item androidididfavorite androidshowasactionalways androidtitlehappyitem androidididshare button androidicondrawableshare androidshowasactionalways androidtitleshareitem androidididhola button androidshowasactionalways androidtitleholaitem androidicondrawablemore actions androidshowasactionalways menu item androidididback button androidicondrawableback androidtitleback item androidididforward button androidicondrawableforward androidtitleforward item androidididrefresh button androidicondrawablerefresh androidtitlerefresh menu item menu,['android'] +405630,invalid grant when trying to authorize a server to server type application in ruby for accessing google calendar i am trying to create an app for myself that just directly connects to my calendar but i never want to be involved with reauthenticating i just want to code the authentication once and be done with itthe auth code is as followskey googleapiclientpkcs12load keyservice account pkcs12 file path passwordasserter googleapiclientjwtasserternew service account email keyclient googleapiclientnewclientauthorization asserterauthorizeservice account emailclientmy service account pkcs file is in the root of the directory along with my sinatra appi have enabled the google calendar api on my gmail accounti have been looking at a method of authentication here under authorization where it talks about server to server communication ruby serverrb faraday you may want to install system timer for reliable timeoutshomemervmgemsruby187p371gemsfaraday084libfaradayutilsrb16 warning already initialized constant keymaphomemervmgemsruby187p371gemsfaraday084libfaradayutilsrb177 warning already initialized constant default sepw 20130115t095211371122 28607 warn googleapiclient please provide application name and application version when initializing the clienthomemervmgemsruby187p371gemssignet044libsignetoauth 2clientrb869in fetch access token authorization failed server message signetauthorizationerror error invalid grant from homemervmgemsruby187p371gemssignet044libsignetoauth 2clientrb882in fetch access token from homemervmgemsruby187p371gemsgoogleapiclient061libgoogleapi clientauthjwt asserterrb116in authorize from serverrb32in build client from serverrb38what could the issue be why am i getting this error especially since i have pretty much copied the code from the google gems site updatefound thisinvalid grant trying to get oauth token from googlesays i should do thismake sure you specify access typeoffline in your requesthow do i do this with the ruby gem without completely redoing the http requests,['ruby'] +405665,programmatic xml diff merge in c at this moment i am managing a piece of software that has multiple xml configuration files when a new version of software is released sometimes the base config files change we currently have the software call kdiff on startup if it detects a change it prompts the user to choose the changesthe problem with this approach is that kdiff is a line comparing program and not aware of the ways of xml like nodes etc ideally i would like to programmatically work with a library in c since were a ms shop that can diff two xml files a source xml and a current working xmland then merge the two together using a few simple rulesif the current working xml has a node that the source xml does not remove itif the source xml has a node that the current working xml does not add itif both have the same node and the values differ favor the source xmls value unless it the source xmls value is set to useexistingvaluefor example heres the source xmlconfiguration items item id1 positiontrue location xuseexistingvalue yuseexistingvalue zuseexistingvalue something somethingelse item items configurationand heres the current working xmlconfiguration items item id1 positionfalse location x123 y234 z345 another something item itemsconfigurationand the merged version would look likeconfiguration items item id1 positiontrue location x123 y234 z345 something somethingelse item itemsconfigurationi have looked at the ms xml diff and patch tool and it definitely merges the files together but does not allow for the programmatic rules that i want to definexmlunit for java devs seems promising but the net version of it seems underdeveloped which is unfortunateanyone have any suggestions for either scriptable xml diffmerge tools andor net libraries paid or freethanks,['c#'] +405703,are there any mq servers that can run embedded in a java process i am researching queuing solutions for one of my teams apps ideally we would like something that can be configured both as a lightweight inprocess broker for lowthroughput messaging between threads and as an external broker is there an mq server out there that can do this most seem to require setup as an external entity zeromq appears to come the closest to an inprocess solution but it seems to be more of a udp socket on steroids and we need reliable delivery,['java'] +405745,flasksqlalchemy or sqlalchemy i am new in both flask and sqlalchemy i just start working on a flask app and i am using sqlalchemy for now i was wondering if there is any significant benefit i can get from using flasksqlalchemy vs sqlalchemy i could not find enough motivations in or maybe i did not understand the value i would appreciate your clarifications,['python'] +405752,convert char array to string use c i need to convert a char array to stringsomething like thischar array20char string100array01array17array28array3array49i would like to get something like thatchar string0 array where it was stored 1789 in position 0,['c'] +405769,mysql query with count and group by i have got table a table with different records for publishers each record have a date in a column of type timestampid id publisher date1 1 112012 030940 pm2 1 122012 030940 pm3 2 012013 030940 pm4 3 012013 030940 pm5 4 112012 030940 pm6 4 022013 030940 pm7 4 022012 030940 pmi need a count for number of records published by each publisher for each month for examplemonth id publisher num112012 1 12012 2 0112012 3 0112012 4 1022013 4 2i tried with select countid from raw occurrence record group by monthdate id publisherbut dont work,['mysql'] +405793,how to warn the user when edited data in ui so i can warn them of overwriting or prompt them to save java how to warn the user when edited data in ui so i can warn them of overwriting if they load from another source or prompt them to save javafx22i will have over 50 text fields across a number of tabs and 2 or 3 tables with buttons to add and delete rowsi was wondering whether to have a global isdirty boolean flag and can set onaction handlers on the buttons but must i set onkeytyped handlers on every one of the text fields and text areas will it slow things does java keep track of whether any field was edited and if so can i capture that information from it,['java'] +405815,importerror no module named backend gdk i am starting to get some insight into interactive plotting with python and matplotlib using pygtk therefore i took a look at the example given at the matplotlib website interfacesgtk spreadsheethtmlthis is a short exerpt of the codeusrbinenv pythonexample of embedding matplotlib in an application and interacting witha treeview to store data double click on an entry to update plotdataimport pygtkpygtkrequire20import gtkfrom gtk import gdkimport matplotlibmatplotlibusegtkagg or gtkfrom matplotlibbackendsbackend gtk import figurecanvasgtk as figurecanvasfrom numpyrandom import randomfrom matplotlibfigure import figureones i try to run this script in the terminal i get the following errortraceback most recent call last file gtk spreadsheetpy line 15 in module from matplotlibbackendsbackend gtk import figurecanvasgtk as figurecanvas file libraryframeworkspythonframeworkversions27libpython27sitepackagesmatplotlibbackendsbackend gtkpy line 33 in module from matplotlibbackendsbackend gdk import renderergdk figurecanvasgdk file libraryframeworkspythonframeworkversions27libpython27sitepackagesmatplotlibbackendsbackend gdkpy line 29 in module from matplotlibbackends backend gdk import pixbuf get pixels arrayimporterror no module named backend gdki have python 27 matplotlib 120 and pygtk 224 installedcan anyone figure out where the error is located i think it might be connected to some linkin issuesthanks a lot,['python'] +405851,left align both list numbers and text i would like to left align both the numbers and the text in my ol this is what i am trying to accomplishfor now each li contains an a but that can change so far i tried putting left padding and then a textindent on the a here is my code as of nowhtmlol classdinosaurs liadinosaurali liatyrannosaurusali liacamptosaurusaliolcssdinosaurs liststyleposition insidenote i am viewing the webpage in chrome 23 on windows 7,"['html', 'css']" +405854,no opengl context found in the current thread how do i fix this error i am working on a card game and currently have a good foundation but i am running into an error when i run it in eclipse i am also using slick 2dhere is the error from the consoleexception in thread main javalangruntimeexception no opengl context found in the current thread at orglwjglopenglglcontextgetcapabilitiesglcontextjava124 at orglwjglopenglgl11glgeterrorgl11java1277 at orgnewdawnslickopenglrendererimmediatemodeoglrendererglgeterrorimmediatemodeoglrendererjava387 at orgnewdawnslickopenglinternaltextureloadergettextureinternaltextureloaderjava337 at orgnewdawnslickopenglinternaltextureloadergettextureinternaltextureloaderjava275 at orgnewdawnslickimageimagejava270 at orgnewdawnslickimageimagejava244 at orgnewdawnslickimageimagejava232 at orgnewdawnslickimageimagejava198 at cardscardcardjava18code where i believe the source of the error to be occuringcard classpackage cardsimport orgnewdawnslickimageimport orgnewdawnslickslickexceptionpublic class card final int numcards 52 image card new image numcards card int c string filelocation new string for int i 1 i 52 i filelocation rescards i png try card i new image filelocation line catch slickexception e eprintstacktrace public image getimage int cardlocation return card cardlocation has anybody seen this kind of problem before how can i solve it,['java'] +405887,is ajax in wordpress is there anyway to detect if the current server operation is currently an ajax request in wordpressfor exampleis ajax,['php'] +405918,is x newfoo the same as x new foo for an arbitrary foo i am looking at some legacy code and came across xnewfoo note the parenthesis around the type supplied i tested out variations and it appears to be the same as xnew foofoo is a nonpod data structure some external memory leak program is flagging the line it is allocating memory for a corba out parameter so the caller should be taking care of the delete but that is a separate issue with many layers of indirectionis my analysis correct and is it acceptable style,['c++'] +405937,how to combine multiple jars into one i have read so many articlesexplanations on this and spent too many hours but everything is either too broad or specificthis question really only applies to an applet i have made it contains one class and requires 2 other jar libraries i have included these in the projects multiple projects because i have tried this in netbeans and eclipseit is easy to recreate a one class project the point of all this is that my htmlweb project should not have to deal with more than one jar or reference them it is not a complicated appletproject at all eitheroriginally i made it in netbeans it has the main package and after adding the 2 jars they are put in a libraries area the resources folder after building it netbeans creates a jar for my one packageclass and then puts the 2 other libraries in a lib directory next to it i would like them to be in one thistributable jar from the many things i have looked through i have tried putting the following in buildxmltarget nameyourbigjar dependspostjar jar destfilethistbigjarjar zipfileset srcthistcxappletjar zipfileset srcresourcesdpotapijar zipfileset srcresourcesdpotjnijar jartargetbut it produces nothing i got this from netbeans deploying all in one jar i do not knowunderstand how to use buildxml so i wouldnt be surprised if somethings going wrong obviously but i get no errorwarning messageswhen i made it in eclipse it effectively combines them but when i use the jar in my actual web project it says it cannot find the classes from the other 2 jars i wouldnt understand how to fix it but is it a classpath problem in eclipse i make a new directory called lib and put the jars in it then i rightclick the project go to java build path and add the jars also checking them under the order and export tab from things i have read i rightclick the project choose export choose jar uncheck the classpath and project files only check export generated class files and resources and then allow it to generate the manifest file like i said this generates one jar but its contents are my package and then a lib directory that has the 2 other jars the manifest is there but it is pretty empty and does not reference any files not sure if that is important when i put it in my web app it says the applet cannot find the other classesit just seems so simple one packageclass two external jarscombine into one jar when built for thistribution as an applet any ideasupdatesince we started using maven someone looked into using a maven plugin so we ended up creating a new project to house the applet since it is used across multiple projects and used this in our pomxml in the endbuild resources resource directorybasedirappletdirectory excludes excludecodesignstoreexclude excludes resource resource directorybasedirsrcmainresourcesdirectory filteringtruefiltering resource resources plugins plugin artifactidmavenassemblypluginartifactid version22beta5version configuration descriptorrefs descriptorrefjarwithdependenciesdescriptorref descriptorrefs finalnamecxappletfinalname archive indextrueindex manifest adefaultimplementationentriestrueadefaultimplementationentries manifest archive appendassemblyidfalseappendassemblyid configuration executions execution idmakemyappletjarid phasepackagephase goals goalsinglegoal goals execution executions plugin plugin groupidorgapachemavenpluginsgroupid artifactidmavenjarsignerpluginartifactid version12version executions execution idsignid goals goalsigngoal goals execution executions configuration keystorebasedirappletcodesignstorekeystore aliascodesigncertalias storepasshiddenstorepass keypasshiddenkeypass configuration plugin pluginsbuildand it was nice because it allowed us to use our code signing certificate to automatically sign it too,['java'] +405971,html5 chrome checkvalidity onblur i am trying to do a simple checkvalidity of a numeric input field on blur but cannot get it to work properly does this work in chrome yet for instance input onblurcheckvalidity typenumber namex idx min64 max2048 value64orinput onblurthischeckvalidity typenumber namex idx min64 max2048 value64do not seem to do anything however in the console x0checkvalidity does return true or false based on the current value in the input box and the limits above of 642048 is this broken or am i doing it wrong,['javascript'] +406000,is there a java equivalent to the new modifier in c possible duplicateis there a anewa modifier for methods in java in c a subclas method can be modified as newone usage of the new modifier to explicitly hide a member inherited from a base classis there a same keyword in java,"['c#', 'java']" +406007,high memory issues in net framework 4 but not in framework 45 i have a following piece of code net 4 that is consuming a lot of memorystruct data private readonly listdictionarystringstring list public datalistdictionarystringstring list list list public void dowork int num 0 foreach dictionarystring string d in list foreach keyvaluepairstring string kvp in d num converttoint32kvpvalue consolewritenum list null class test1 blockingcollectiondata collection new blockingcollectiondata10 thread th public test1 th new threadwork thstart public void read listdictionarystring string l new listdictionarystring string random r new random for int i0 i10 i dictionarystring string d new dictionarystringstring d1 rnexttostring d2 rnexttostring d3 rnexttostring d4 rnexttostring lad collectionaddnew datal private void work while true collectiontakedowork class program test1 t new test1 static void mainstring args program p new program for int i 0 i 10 i ptread the size of blocking collection is 10 in my knowledge gc should collect references in data struct as soon its dowork method is complete however the memory keeps on increasing at a rapid rate until the program crashes or it come down on its own and this is happening more often on low end machines on some machines memory does not increasefurther when i add the following line list null at the end of dowork method and convert data into class from struct memory does not increase what could be happening here i need some suggestions hereupdate the issue is occuring on machines with net framework 4 installed 45 not installed,['c#'] +406053,jquery 19 live is not a function i recently updated jquery from 18 to 21 i suddenly thiscovered that the live stops workingi get the error typeerror live is not a functionis there any method i can use in place of live,"['javascript', 'jquery']" +406092,combining callermembername with params right now c 40 our logging method looks likepublic void logstring methodname string messageformat params object messageparameterswhere the logger does the string formatting so that the caller does not have put stringformats to create a nice log message and allows for the logger to skip the string formatting if no logviewer is attached with c 50 i would like to get rid of the methodname parameter by using the new callermembername attribute but i do not see how this can be combined with the params keyword is there a way to do this,['c#'] +406152,stream videos from amazon to ios devices i store my videos in amazon s3 bucket and stream them to my website using cloudfronteverything works fine but now i also have an ipad app for my website and i want to stream the same videos to my ipad appthe only documentation i could found is it is great explanation how to do live streams on different devices i also know that cloudfront uses fms 35 and i have set up cloudformation stack for fms 45 but i do not know how to connect it to my bucket create secured urls and stream videos to ios devicesplease help and provide me with any documentation that explains how to stream vod from amazon to ios devices with secured urls,['ios'] +406164,java library for url encoding if necessary like a browser if i put the httplocalhost90space test url to the address bar of a web browser it calls the server with httplocalhost90space20testhttplocalhost90specatest will be also encoded to httplocalhost90specc381c389c38dtestif put the encoded urls to the address bar ie httplocalhost90space20test and httplocalhost90specc381c389c38dtest they remain the same they would not be doubleencodedis there any java api or library which does this encoding the urls comes from the user so i do not know if they are encoded or not if there is not would it be enough to search for in the input string and encode if it is not found or is there any special case where this would not workediturlencoderencodespace20test utf8 returns with space2520test which is not what i would like since it is doubleencodededit 2furthermore browsers handle partially encoded urls like httplocalhost90specaac38dtest well without doubleencoding them in this case the server receives the following url httplocalhost90specc381c389c38dtest it is same as the encoded form of specatest,['java'] +406176,google gson nested hashmaps deserialization in my current project i use gson library in android and i have faced a problem of nested maps deserializtion this is how initial json looks like 5 id5 nameinitial name image urluploads71d44b5247cc1a7c56e62fa51ca91d9bpng status1 flowers 7 id7 category id5 nametest descriptionsome description price10 image urluploadstestpng status1 colorred and my pojosclass category long idstring namestring image urlhashmapstringflower flowersand flower classclass flower long idstring category idstring namestring descriptionstring pricestring image urlstring statusbut when i try to deserialize this objects i can access nested hashmaps the example code is public class testjson public static void mainstring args gson gson new gson try bufferedreader br new bufferedreader new filereader2txt hashmapstringcategory map gsonfromjsonbr hashmapclass collectioncategory asd mapvalues systemoutprintlnmapvalues catch ioexception e eprintstacktrace any suggestions,['java'] +406180,html5 checkbox how to thisplay text i want to thisplay the related text of the check box along with itinput idcheckbox1 typecheckbox valueadminspanadmin userspanthis is the most used markup to do that but it does not feel good to use a separate span for the check box and it does not even look good in the form is there way to relate these two with each other or what is the best way to do this,"['html', 'css']" +406187,elastic search using nest field boosting i am using elastic search in c using the nest strongly typed clienti have an index containing entrieselastictypename entry idproperty idpublic class entry public string id get set public string title get set public string description get set public string award get set public int year get set where year is the year of the entry eg 2012 and award is the type of award the entry won which can be nulli then want to search these entries using boosting for different properties in the following code i want results to be ranked higher that match on the title than those that match on the descriptionprivate iqueryresponseentry getmatchedentriesstring searchtext return elasticclientsearchentry body bodyqueryq qquerystringqs qsonfieldswithboostd daddentry entrytitle 50 addentry entrydescription 20 querysearchtexti have now been asked to boost the results by those which have won awards and also boost newer entries ie by the yearhow do i do this is it something that needs to be done as part of the indexing service or as part of the search,['c#'] +406188,on the static final keywords in java according to the tutorialthe static modifier in combination with the final modifier is also used to define constants the final modifier indicates that the value of this field cannot changei would agree with this only if the types involved were primitive with reference types eg an instance of a class point2d where its position attributes were not final ie we could change its position the attributes of this kind of variables such as public static final point2d a new point2dxy could still be changed is this true,['java'] +406198,how do i know if my tomcat supports servlet 30 or not i am using tomcat 633 and i am wondering how can i check if it supports servlet 30 or el 22 or not,['java'] +406326,how can it be that java is not type safe in a particular situation today i found a very very weird behavior of the jvm a normally typesafe listdate did actually hold a listmyobject at runtimei wonder how that ever could happen but could not find anything in the webthat is the situationi am working with spring data jpa 120 on a jboss eap 60 server with jre 160 18b07by mistake in a spring data jpa repository class there was written a wrong result type in the query expression it should have been queryselect thistinct truncrecordorderdatetime from mytype record public listdate getorderdatesbut was queryselect record from mytype record public listdate getorderdatesso the aim was to load a list of dates javautildate which works fine if the query is properly defined as in the first code snippetbut that coding mistake led to the following resultat runtime there actually was a listmytype returned even though the methods signature defines a listdate also in my model an attribute of listdate wascontained a listmytype i debugged it and could not believe my eyesi could even write the content of this list to a jsp i only recognized this weird behavior because a jsp could not be thisplayed any more due to a spring expression language error occuring with the attempt to type match from mytype to date which of course had to crashhell shall i now loose my believe in the typesafety of javahas anybody ever had such a problemdoes an explanation for this existand can i do anything to fix that or is it a general issue maybe another version of the jre jboss,['java'] +406338,python pandas deleting multiple series from a data frame in one command in short i have a python pandas data frame that is read in from an excel file using read table i would like to keep a handful of the series from the data and purge the rest i know that i can just delete what i do not want onebyone using del dataseriesname but what i would rather do is specify what to keep instead of specifying what to deleteif the simplest answer is to copy the existing data frame into a new data frame that only contains the series i want and then delete the existing frame in its entirety i would satisfied with that solution but if that is indeed the best way can someone walk me through ittia i am a newb to pandas,['python'] +406341,should javascript libraries use the deprecated annotation obviously it is up to the developers as to when to deprecate and when to remove but i am wondering how to warn developers that a javascript function has been deprecatedmost languages java c python support language level deprecation in some formfor javascript though i cannot find any standard way that developers can indicate a function has been deprecated in code the best i can do is follow a large number of release notesas an example grepping the full source of jquery 18 shows minimal inline comments curl grep i depre jquerysupportboxmodel deprecated in 18 since we do not support quirks mode attrchange attrname relatednode srcelement are not normalized nonw3c deprecated will be removed in 18 some plugins are using but it is undocumenteddeprecated and will be removed deprecated limit scope pollution from any deprecated api deprecated use jquerybrowserwebkit insteadw3c and mdn do not seem to have a standard way or provide suggestions on how to handle thisthe best i have found is jsdocs deprecated tagdoes anyone know if javascript does have a deprecation annotation that i have overlooked are there better or more common ways to do this,['javascript'] +406399,mysql select into outfile does not write the file to the directory that i choose the following commandselect into outfile homeuser1netbeansprojectsproject1dumpsthedatacsv fields terminated by lines terminated by n from database1does not write a file called thedatacsv to the specified directory how do i get this file to be written to the specified directory,['mysql'] +406408,optionselected not working jquery 19 the following select optioncontainsfishattrselected trueworks wonderfully in anything below jquery 19 but does not work at all in jquery 19 i have been searching for any documentation on any change but have not found anythingany idea how to get this code to work with the new jqueryexample here defaults to jquery 14,['jquery'] +406413,how to get the inmemory size of an object in android or performance benchmarks long story short i want to test my clone implementation of the androidosbundle class against that class to see which is better i already know my version is likely going to be worse but i want to know how much worse are there any benchmarking tools out there for android that i can use to see which object is bigger in memory andor takes more processing time to storeretrieve valuestldri looked at the source code for the androidosbundle class and i do not like how it stores and returns objects it just stores them in a hashmapstring object and then casts to the requested objects class like getstring or getint using a classloader i feel that this or any class casting for that matter violates typesafety and introduces ambiguity at the programming level which is what static typing aims to prevent is it noti want to create a similar data container class that does not violate typesafety and does not introduce ambiguity the logically simple yet obviously inefficient way would be to have a map for each class i want to storewhat i decided on was a single hashmapstring integer that contains keyindex mappings for an assortment of lists for each class i want to store for example a call to getstringstring key will get the integer index associated with that key from the map if it exists and then try to get the object at that index in the associated arrayliststringthe only ambiguity here would be returning either null where the index does not exist in the list for that class or the wrong object of the right class where the mapped index exists but the original object stored with that key is in another list which is really the programmers responsibility to check for objects of this class are only temporary containers used to ship data from one place to another in a standardized fashion they are not meant to stick around they are also not used in the same manner as bundles although part of the reason i want a unified data container like this is to be able to easily convert to a bundle jsonobject contentvalues or cursor and backor maybe the real question is is casting really all that bad or am i just going to extreme efforts to avoid it i guess good programming is really the only way to avoid ambiguity in either caseupdateit looks like bundle only uses the classloader when it is unpacking itself from a parcel but it makes a call to unparcel with every put call when retrieving it simply casts to the type that the method returns inside a trycatch block for classcastexception that is probably the simplest way to do it,"['java', 'android']" +406465,django datetimefield and timezonenow ok weird time zone issues when i am running function tests django 14 python 27 are milliseconds truncated in datetimefield on mysql that is the only theory i have got model filefrom djangodb import modelsfrom djangoutils import timezoneclass searchmodelsmodel query modelscharfieldmax length200 nulltrue query date modelsdatetimefieldnulltruetestpyfrom djangotest import testcasefrom djangoutils import timezonefrom searchmodels import searchclass searchmodeltesttestcasedef test creating a new search and saving it to the databaseself start by creating a new poll object with its question set search search searchquery test searchquery date timezonenow check we can save it to the database searchsave now check we can find it in the database again all search in database searchobjectsall selfassertequalslenall search in database 1 only search in database all search in database0 selfassertequalsonly search in database search and check that it is saved its two attributes question and pub date selfassertequalsonly search in databasequery test selfassertequalsonly search in databasequery date searchquery datethe test fails with thisselfassertequalsonly search in databasequery date searchquery dateassertionerror datetimedatetime2013 1 16 21 12 35 tzinfoutc datetimedatetime2013 1 16 21 12 35 234108 tzinfoutci think whats happening is that the milliseconds are being truncated after saving to the database can that be right i am running mysql v 55 is mysql truncating the date,['python'] +406467,moq to set up a function return based on called times i need to mock an interface to call to msmq is there a way i can use moq to simulate real msmq scenario that there are 10 messages in the queue i call mocked function 10 times and i can get a predefined object on 11th time i should get a different return value eg null,['c#'] +406520,how to set model for strongly typed view in razor i am trying to pass my model to my view in razor with the old method i could define it at the top of the file the modeli did some googling and thought i figured it out does not seem to be working i am not getting any intellisense on the modeltop of the view filemodel codysolutionmodelsphotomodel viewbagtitle photography layout viewsshared mastercshtmlwhere i am using the modelul classnav navpills navstacked margintop foreach var cat in modelcategories li classactivea hrefcatali ulis this the correct way to define it,['asp.net'] +406521,which characters are actually capable of causing sql injection in mysql we all know that we should use prepared statements or the appropriate replacementformatting rules in order to prevent sql injection in our applicationshowever when taking a look at mysqls list of character literals i noticed that it includes the following characters 0 an ascii nul 0x00 character a single quote aa character a double quote aa characterb a backspace charactern a newline linefeed characterr a carriage return charactert a tab characterz ascii 26 controlz see note following the table a backslash aa character a aa character a a a characternow while the and characters need to be escaped in order to prevent injection of unwanted wildcards into like statements and while the single quote backslash and double quote all need to be escaped in order to prevent injection of arbitrary sql could having any of these other characters unescaped lead directly to a sql injection vulnerability that would not otherwise be present does anyone have any real world examples of such an exploitlet us assume we are building our query likeselect from users where usernameuseris there any value for user where the only unescaped character literals are b backspace 0 nul and newline r linefeed t tab or z ctrlz that allows the injection of arbitrary sql into this query,['mysql'] +406522,is stdarray movable is stdarray movablein bjarne native 2012 presentation slides slide 41 it lists stdarray as one of the only containers that is not movablea quick look on gcc 48 libraries source code seems to confirm that stdarray is not movablestdvector brief vector move constructor vectorvector x noexcept basestdmove x while in stdarray the only method that receives a rvalue reference parameter is the random element access which avoids a return by copygetarray tp nm arr noexcept return stdmoveget int arr is the moveconstructor moveassignement for stdarray defaulted created or is stdarray unmovable if it is unmovable why stdarray cannot be moved while stdvector can,['c++'] +406534,how to understand this python functional style code by peter norvig while reading peter norvigs python iaq i came across this code snippetdef iftest return lambda alternative lambda result delayresult delayalternativenot not testdef delayf if callablef return f else return lambda ffact lambda n if n 1 1 lambda and factn1fact100i searched this in the internet and this code appeared in several forums but it seems that those who commented on it all understand how it worksi am quite new to functional programming concepts i know that if test is evaluated to true delayalternative will be selected but in fact if test is true result is returned this seems counterintuitive to me,['python'] +406548,angularjs defining angularmodule multiple times what is the behaviour of calling angularmodulemymodule multiple timesfor example i wish to define my routes and my directives in separate js filesis this safe egroutesjsangularmoduleappstrap configfunctionrouteprovider locationprovider directivesjsangularmoduleapp directiveforminput function also what is the impact of defining the dependencies multiple times is this additive or lastinwinseg,['javascript'] +406568,google app engine instances keep quickly shutting down so i have been using app engine for quite some time now with no issues i am aware that if the app has not been hit by a visitor for a while then the instance will shut down and the first visitor to hit the site will have a few second delay while a new instance fires uphowever recently it seems that the instances only stay alive for a very short period of time sometimes less than a minute and if i have 1 instance already up and running and i refresh an app webpage it still fires up another instance and the page it starts is minimal homepage html should not require much cpumemory looking at my logs its constantly starting up new instances which was never the case previouslyany tips on what i should be looking at or any ideas of why this is happeningalso i am using python 27 threadsafe python precompiled warmup inbound services ndbupdateso i changed my app to have at least 1 idle instance hoping that this would solve the problem but it is still firing up new instances even though one resident instance is already running so when there is just the 1 resident instance and i am not getting any traffic except me and i go to another page on my app it is still starting up a new instance additionally i changed the pending latency to 15s as koma pointed out but that does not seem to be helping the memory usage of the instances is always around 53mb which is surprising when the pages being called are not doing much i am using the f1 frontend instance class and that has a limit of 128 but either way 53mb seems high for what it should be doing is that an acceptable size when it first starts upupdate 2 i just noticed in the dashboard that in the last 14 hours the request ahwarmup responded with 24 404 errors could this be related why would they be responding with a 404 response statusmain question why would it constantly be starting up new instances even with no traffic especially where there are already existing instances and why do they shut down so quickly,['python'] +406592,how to turn off mysql query cache while using sqlalchemy i am working with a fairly large mysql database via the sqlalchemy library and i would love to turn off mysqls query caching to debug performance issues on a persession basis it is difficult to debug slow queries when repeating them results in much faster execution with the cli mysql client i can execute set session query cache type off to achieve the result i am looking for and i would like to run this on every sqlalchemy session when i am debuggingbut i cannot figure out how to configure sqlalchemy such that it runs set session query cache type off when it instantiates a new database sessioni have looked at the engine and connection docs but cannot seem to find anythingis there something obvious that i am missing or a better way of doing this,"['python', 'mysql']" +406606,rspec mocks on any instance with exactlyn times i want to use mocks in rspec tests likeklassany instanceshould receivesaveexactly2timesand returntruebut i get an error message likethe message save was received by object but has already been received by objecttemporary i use stub but for accuracy want to use mocks,['ruby-on-rails'] +406635,ios mkmapview user touch based drawing i have searched a lot for this question but none of them seem to do exactly what i wanta lot of tutorials show me how to add lines and polygons in code but not with freehand drawingthe question is the following onei am building a real estate application if the user is on the mkmapview it has the ability to draw a rectanglecircle around a certain area where heshe wants to buyrent a house then i need to thisplay the results that correspond within the area the user has selectedcurrently i have a uiview on top of my mkmapview where i do some custom drawing is there a way to translate points to coordinates from that or or is this completely not the way this is done i have also heard about mkmapoverlayview etc but am not exactly sure how to use thiscan anybody point me in the right direction or does he have some sample code or a tutorial that can help me accomplish what i am in need forthanks,['ios'] +406641,the view is not updated when the model updates in angularjs i have read threads on this issue such as the view is not updated in angularjs but i still cannot understand how to apply it on my simple examplei have this functionfunction mypageviewscope var mymodel new mymodel scopemymodel mymodelwhen mymodel is updated elsewhere in the code when user clicks interacts send xhr requests it does not update my view i understand i need to do something with apply but i did not understand where and how can someone explain to me how do i solve this issue for this simple usecasemy model looks something like this if that is necessary for the question it has no angularjs code inside of itvar mymodel function var this this thisload function thisupdatemodel function return thisadding a jsfiddle example,"['javascript', 'html']" +406648,doing a http basic authentication in rails hi i am from grails background and new to rails i wish to do http basic authentication in railsi have a code in grails which does basic authentication like thisdef authstring keygetbytesencodebase64tostringdef conn tourlopenconnectionconnsetrequestpropertyauthorization basic authstringis it the same can be done with railsthanks in advance,"['ruby-on-rails', 'ruby']" +406675,my programs are blocked by avast antivirus i am an amateur programmer and i am getting desperate and mad because of a big issue most of my programs are blocked by avast antivirus while some are not and i do not understand whythe more i try to investigate the less i understand what the problem could be i am requesting your help to find a solution so that my programs are no longer blocked or as a default at least some strong clues that would explain why it might be the casethere are already many topics about that on the web however most of them give only superficial answers they just explain how antivirus works with signatures and detection heuristics or state that you just have to add the offending application in the white list without asking any other question while it is certainly correct it is not acceptable answers in my sens because i am still left with my own programs that refuse to work without any concrete idea to start investigatingfirst of all the only antivirus that blocks my programs is avast 7x no other antivirus see any inconvenient to run my software secondly i have not avast myself it is installed on a friends machinei have windows 7 he has windows xp i am completely sure that the problem is avast only when it is temporarily thisabled or if the program is added to its white list everything works nicely as expectedthree different programs are in trouble a text editor with the goal to replace windows notepad while keeping simple efficient and customizablea small amateur audio player very simple to usethe client program of an online game platform currently having more than 10 usersthe first one is open source i can give a link to the executable and the source code if needed the two others are closed source but free to use i can give a link to the executable of the current version onlythe only obvious common things between these three programs are me as a developer my windows 7 machine that compiled them the compiler family which is mingwgcc and they are all win32 gui applications without any framework no mfc no wpf no qt wxwidgets or whatever just pure win32c gui applicationshere are my observations and though so far versions 11 121 and 13 of my text editor are blocked they are in c not c have been compiled with gcc 345 in unicode mode and are thistributed in portable zip files by portable i simply mean no installer and no installation neededversion 141 of the same text editor is not blocked it has been compiled with gcc 472 still in c and not c still in unicode mode and still as a portable zip fileall versions of my audio player are blocked they are in c with 0x features enabled have been compiled by gcc 472 in ansi mode thistributed in portable zip filethe current version of my game 172 is not blocked it is in c has been compiled with gcc 345 in ansi mode and is thistributed as an innosetup 5 installerthe new version of my game 200 which is currently a private beta is blocked it is in c with 0x features enabled has been compiled with gcc 472 in unicode mode i share it with my private betatesting team as zip files within a private dropbox folderthe problem is caused by avast 7x autosandbox the following happens when one try to start a program thisliked by avast the user doubleclick or hit enter on the executablethe program starts but is almost instantaneously and forcibly crashed by avasta popup appears and says something like avast has put this program into his sandbox because his reputation is lowif one click on the continue button of the popup the execution of the program is restarted and works normallyif one do not click on the continue button windows explorer freezes the executable remain in the task manager and invariably use 76 kb of ram while being impossible to kill finally after about 5 minutes windows explorer unfreezes the program is restarted and works normallythis is unacceptable newbie users of my program especially the game do not know how antivirus works do not know how to put it into the white list and why it will unblock it do not know how to change settings of their antivirus if they see the popup wont understand it and will end up being afraid or thisappointed because they cannot play without knowing why and if they do not see the popup i cannot expect them to wait 5 minutes with a halffreezing computer each time they want to playfrom there i made the following deductions my machine is not itself infected and no virus is injected into the executables i thistribute otherwise all recent programs would be blocked i have two which are my player and the new version of my game while one is not the latest version of my text editor the 172 of the game has been compiled in march 2012 while the 141 of the text editor is from october 2012the newest version of gcc 472 is not in cause by the same reasoning same for ansi vs unicode compilingthe mingw c runtime thistributed as a autolinked dll mandatory in all c applications compiled with gcc 472 is probably not the cause because many well known programs use it and my text editor is blocked and is in c and thus do not use itmy audio player and my game have the audio library in common this later is not the cause because the version 172 of my game works and the newest private beta not and of course that audio library is also used in many other known or less known applications that are not blockedboth the player and the game access the network using winsock so by the same reasoning it is not the cause eitherif it really were the reputation thing of avast why the version 141 of my text editor which is not blocked has only been downloaded around 70 times while the version 13 which is blocked has been downloaded more than 300 times it looks completely illogical is 70 users sufficient to claim something about reputation is it more with 300 users i really do not think so probably a critical mass of a dozens thousands users is necessaryadditionally to that i also though that the fact i am thistributing my programs as portable zip files may be a reason for avast to block and conversely the fact that a program is well installed in program files may be a reason to trust it more so i made a simple experience i compiled a new innosetup 5 installer for the beta 200 of my game as well as one for the version 13 of my text editor and thiscover that the installers themselves were blocked i made another experience with my friend where i tried to find exactly the place where the programs crash based on using messagebeep messagebox is also blocked i did not noticed anything problematic the game is blocked when setdlgitemtext is called for the first time in the login dialog box but if i remove all setdlgitemtext it is blocked further down in the text editor it is blocked while populating the menu barmy conclusion is there is something that avast do not like in the new version of my game in the old versions of my text editor and in my audio player something that is absent in the newest version of my text editor what could it be do you have any clue do you have only an idea on how i could proceed to find what it is so that i can hope to fix it is there only a way to analyse such a problem or is the hole world screwed by avastnote that i am a single person and not a company all those programs are free to use i have not pay any ide to develop them and i am not paid by the users when they use them so i assume that a certificate is probably not affordable at all moreover i do not know if it is a true solution how to sign an application compiled with gcc and i really do not want to switch to an usine a gaz like msvc i would prefer strongly forget that option if there is any other solution even a very dirty onethank you for reading,"['c++', 'c']" +406688,android destroying activities killing processes hi i am wondering how android is managing memory and i cannot find precise answer anywherelet us assume i have an application with 5 activities on current activity stack 4 are stopped and 1 is resumed there is no service connected i press home button so that all of my activities are stoppedi start some other memory consuming application and overall device memory is starting to be low and the question is what will happen to my applicationcan system destroy only one or some of my activities to recover memorywill system kill the whole process of my application will all activities be nicely destroyedwhat will happen when i get back to my application when it was totally killed will it start from beggining like the first start or will it try to recover activities to previeous state if yes is it only the one on the top of the stack or all of themupdatebefore asking this question i have seen activity lifecycle a few times but it does not have answers to my questionsi made some tests and i have some answers stop process in ddms was a clue for testingi have not tested answer for question 1 but as guide saysif an activity is paused or stopped the system can drop the activity from memory by either asking it to finish or simply killing its processit seems that one or more of the activities can be destroyed gentlywith ondestroy method without killing the process you will simply get oncreate bundle when getting back to themquestion 2 answeryes generally system kills the whole process this means all data including activities and static fields are destroyed this is not done nicely you would not get ondestroy or finialize for any of your pausedstopped activities this is why saveinstancestate is called just before onpause method onpause is basically the last method where you should save something because after this method you could never see onstop or ondestroy system can just kill the process destroying all of your objects whatever they hold and whatever they are doingquestion 3 answerwhat will happen when you get back to a killed applicationprior to android 22 application will start from the beggining with launcher activitystarting from 22 system will restore the previous application state what does it mean it means that last visible activity will be recreated oncreate bundle what will happen with activity stack stack is fine but all activities on it are dead each of them will be recreated oncreate bundle when you get back to it with back buttonthere is one more thing about thatnormally the system clears a task removes all activities from the stack above the root activity in certain situations when the user reselects that task from the home screen typically this is done if the user has not visited the task for a certain amount of time such as 30 minutesconclusiondo not think that handling activity rotation problems can be solvedby androidconfigchangesorientation when you do that you willget many other problems that you are not even aware oftest your application with ddms stop process button see thisbe careful when using static variables do not think that when you initialized them in activity 1 you will have them initialized in activity 2 the only safe place to initialize global statics would be application classremember that you may never see onstop or ondestroy close filesdatabases stop downloaders in onpause when you want app to do something in bg use foreground servicethat would be it hope i helped with my essey,['android'] +406714,scheduling recurring task in android i am designing an app that has a recurring task of sending presence to a dedicated server as long as the app is in foregroundin my searches across the web i saw a few different approaches and wanted to know what is the best way of doing thiswhat is the best way to schedule a server callthe options i saw weretimer scheduledthreadpoolexecutorservicebroadcastreciever with alarmmanagerwhats your opinionedit the reason i need this is for a chat based app that sends all the user actions to a remote server ie user is typing a message user is reading a message user is online user is offline etcthis means that once every interval i need to send the server what i am doing since i open a chat room with other people they need to know what i am doingsimilar to the whatsapp message feedback mechanism,['android'] +406726,changing behavior of ctrlshiftleftright in intellij idea like in eclipse hi i am new to intellij idea and got here and there usability issues because i am coming from eclipsewhen i rename a variable and want to mark the second part of it by hitting ctrlshiftright the cursor moves to the next word which is outside of the border for renaming and when i type the new name and click enter the rename is not executed for the other usages of the variable is there a setting where it is possible to change the behavior of ctrlshiftleftright so that the caret moves right after the last character of the variable namesecond questionwhen i am moving the cursor through a variable name with ctrlleftright the next stop in eclipse was always before the next upper case letter is in idea also a setting to activate this this would be very helpful when renaming variables,['java'] +406727,is there a recommended format for multiline imports i have read there are three ways for coding multiline imports in pythonwith slashesfrom tkinter import tk frame button entry canvas text left thisabled normal ridge endduplicating sentecesfrom tkinter import tk frame button entry canvas textfrom tkinter import left thisabled normal ridge endwith parenthesisfrom tkinter import tk frame button entry canvas text left thisabled normal ridge endis there a recomended format or a more elegant way for this statements,['python'] +406751,queryselector and queryselectorall vs getelementsbyclassname and getelementbyid in javascript i would like to know what exactly is the difference between queryselector and queryselectorall against getelementsbyclassname and getelementbyidfrom this link i could gather that with queryselector i can write documentqueryselectormyclass to get elements with class myclass and documentqueryselectormyid to get element with id myid but i can already do that getelementsbyclassname and getelementbyid which one should be preferredalso i work in xpages where the id is dynamically generated with colon and looks like this view id1inputtext1 so when i write documentqueryselectorview id1inputtext1 it does not work but writing documentgetelementbyidview id1inputtext1 works any ideas why,['javascript'] +406790,aspnet mvc 4 script bundling causes errors upon deployment my website is working fine on localhost when scriptsrender is not bundling the scripts however when i deploy to my server the bundled javascript must contain an error as all javascript on my page stops workinghere is my bundle code public static void registerbundlesbundlecollection bundles bundlesaddnew scriptbundlebundlesjqueryinclude scriptsjqueryversionjs scriptsjquerymigrateversionjs bundlesaddnew scriptbundlebundlesjqueryvalinclude scriptsjqueryunobtrusive scriptsjqueryvalidate bundlesaddnew scriptbundlebundlesjqueryuiinclude scriptsjqueryuiversionjs scriptsjqueryuiunobtrusiveversionjs bundlesaddnew scriptbundlebundlesmodernizrinclude scriptsmodernizr bundlesaddnew stylebundlecontentcssincludecontentsitecss bundlesaddnew stylebundlecontentthemesbasecssinclude contentthemesbasejqueryuicorecss contentthemesbasejqueryuiresizablecss contentthemesbasejqueryuiselectablecss contentthemesbasejqueryuiaccordioncss contentthemesbasejqueryuiautocompletecss contentthemesbasejqueryuibuttoncss contentthemesbasejqueryuidialogcss contentthemesbasejqueryuislidercss contentthemesbasejqueryuitabscss contentthemesbasejqueryuidatepickercss contentthemesbasejqueryuiprogressbarcss contentthemesbasejqueryuithemecss here is my rendering codestylesrendercontentcstylesrendercontentthemesbasecscriptsrenderbundlesjqueryscriptsrenderbundlesjqueryvalscriptsrenderbundlesjqueryuiscriptsrenderbundlesmodernizrcan someone explain what might be happening to my javascript upon deploymentthanksalex,"['c#', 'javascript']" +406865,compiling android app using boost undefined reference to mbtowc i am trying to compile an android app using boost 149s serialization library specifically this project had some convenient scripts to get the job done boost built without issue against the official ndkr8 using gnulibstdc 46 for armeabiv7a at least it was able to create libboost serializationgccmt1 49a without encountering any errors several warnings were thrown up during build forbids zerosize array pad pedantic does not support long long does not permit named variadic macros nothing that seemed serious but i do not claim to be an expert on the gnu compilerbuilding boost also created libboost wserializationgccmt1 49a which seemed odd but is probably irrelevant i did not include it in my makefilesin any case when i now try to compile my code using this library i get the following errorsuserswespaughdevelopmentandroidndkr8dtoolchainsarmlinuxandroideabi46prebuiltdarwinx86binlibgccarmlinuxandroideabi46armlinuxandroideabibinld objlocalarmeabilibboost serializationgccmt1 49axml iarchiveo in function boostarchivexml iarchive implboostarchivexml iarchiveloadstdbasic stringwchar t stdchar traitswchar t stdallocatorwchar t boostarchiveimplxml iarchive implipp71 error undefined reference to mbtowcuserswespaughdevelopmentandroidndkr8dtoolchainsarmlinuxandroideabi46prebuiltdarwinx86binlibgccarmlinuxandroideabi46armlinuxandroideabibinld objlocalarmeabilibboost serializationgccmt1 49axml iarchiveo in function boostarchivexml iarchive implboostarchivexml iarchiveloadwchar tboostarchiveimplxml iarchive implipp101 error undefined reference to mbtowcuserswespaughdevelopmentandroidndkr8dtoolchainsarmlinuxandroideabi46prebuiltdarwinx86binlibgccarmlinuxandroideabi46armlinuxandroideabibinld objlocalarmeabilibboost serializationgccmt1 49axml iarchiveo in function boostarchivexml iarchive implboostarchivenaked xml iarchiveloadstdbasic stringwchar t stdchar traitswchar t stdallocatorwchar t boostarchiveimplxml iarchive implipp71 error undefined reference to mbtowcuserswespaughdevelopmentandroidndkr8dtoolchainsarmlinuxandroideabi46prebuiltdarwinx86binlibgccarmlinuxandroideabi46armlinuxandroideabibinld objlocalarmeabilibboost serializationgccmt1 49axml iarchiveo in function boostarchivexml iarchive implboostarchivenaked xml iarchiveloadwchar tboostarchiveimplxml iarchive implipp101 error undefined reference to mbtowcuserswespaughdevelopmentandroidndkr8dtoolchainsarmlinuxandroideabi46prebuiltdarwinx86binlibgccarmlinuxandroideabi46armlinuxandroideabibinld objlocalarmeabilibboost serializationgccmt1 49axml oarchiveo in function boostarchiveiteratorsostream iteratorchar std copy movefalse false stdinput iterator tag copy mboostarchiveiteratorsmb from wcharboostarchiveiteratorsxml escapewchar t const boostarchiveiteratorsostream iteratorchar boostarchiveiteratorsmb from wcharboostarchiveiteratorsxml escapewchar t const boostarchiveiteratorsmb from wcharboostarchiveiteratorsxml escapewchar t const boostarchiveiteratorsostream iteratorcharboostarchiveiteratorsmb from wcharhpp91 error undefined reference to wctombcollect2 ld returned 1 exit statuseditok i have made some progress on this over lunch by actually digging into those src files in boost i found that mbtowc and its reciprocal are part of gnulibstdc so somehow when i build boost it must not be getting the right references cannot give it any more time over lunch but i have looked at how boost was compiled and the flags used should have linked everything appropriatelyfrom the build log building with toolsetgccandroidr8 cxxpathuserswespaughdevelopmentandroidndkr8dtoolchainsarmlinuxandroideabi46prebuiltdarwinx86binarmlinuxandroideabig cxxflagsiuserswespaughdevelopmentandroidndkr8dplatformsandroid14archarmusrinclude iuserswespaughdevelopmentandroidndkr8dsourcescxxstlgnulibstdc46include iuserswespaughdevelopmentandroidndkr8dsourcescxxstlgnulibstdc46libsarmeabiv7aincludeend editgiven that i am getting errors with the library and that it is the only library that i use in code i wouldnt think there could be a problem with makefiles for the sake of thoroughness though here are there contentsandroidmk included where i keep the compiled boost library define module to include serialization static librarylocal path call mydir serializationinclude clear varslocal cflags ilocal pathincludeboost1 49 llocal pathlib local ldlibs lboost serialization lndk rootsourcescxxstl gnulibstdc46libsarmeabiv7a lgnustl staticlocal cppflags fexceptionslocal cppflags frttilocal cpp extension cpp hpplocal c includes local pathincludeboost1 49 local pathincludeboost1 49boostarchive local pathincludeboost1 49boostserializationlocal module boost serializationlocal src files liblibboost serializationgccmt1 49alocal export c includes local pathclassesinclude prebuilt static libraryandroidmk in projandroidjni compile the applocal path call mydirinclude clear varsldflags lndk rootsourcescrystaxlibsarmeabiv7a463 lcrystax local cppflags fexceptions local cppflags frttilocal module game sharedlocal module filename libgamelocal src files hellocppmaincpp classesappdelegatecpp classeshelloworldscenecpp local c includes local pathclasses local pathcocos2dxplatformthird partyandroidprebuiltlibboostincludeboost1 49 local pathcocos2dxplatformthird partyandroidprebuiltlibboostincludeboost1 49boostarchive local pathcocos2dxplatformthird partyandroidprebuiltlibboostincludeboost1 49boostserializationlocal whole static libraries boost serialization cocos2dx static cocosdenshion static cocos extension staticinclude build shared librarycall importmodulecocosdenshionandroid call importmodulecocos2dxcall importmodulelibboostmy best guess is that i am not building boost correctly but cannot say for sure what could be causing those errors i cannot even seem to google the files that are allegedly referenced in the serialization library mbtowc and permutations is it trying to reference the system or filesystem boost libraries which i did not include via makefile,['android'] +406911,basic authentication with resttemplate 31 i am trying to reproduce the following curl command using javacurl v u userpass this command returns some json datamy buggy java implementation is as followstestpublic void calltest resttemplate resttemplate createresttemplateuser pass uri uri new uri string res resttemplategetforobjecturi stringclassprivate static resttemplate createresttemplatestring username string password usernamepasswordcredentials cred new usernamepasswordcredentialsusername password basiccredentialsprovider cp new basiccredentialsprovider cpsetcredentialsauthscopeany cred defaulthttpclient client new defaulthttpclient clientsetcredentialsprovidercp clienthttprequestfactory factory new httpcomponentsclienthttprequestfactoryclient resttemplate resttemplate new resttemplatefactory set the media types properly return resttemplateyet when i execute the test it returns a orgspringframeworkwebclienthttpclienterrorexception 401 unauthorized exceptionwhen logging in debug i see no information about the authenticationwhat am i doing wrong while setting the authentication credentials,['java'] +406955,nslocalizedstring use of undeclared identifier issue i am using nslocalizedstring in a particular message that works fine if the second parameter is passed as a variable but fails with use of undeclared identifier nslocalizedstring and too many arguments provided to functionlike macro invocation if the second parameter is written exactly the same as the variable was set i have working code using the variable which is fine i just want to understand the reasons for the failure to know how to avoid it in other situationswith the following declarationsnsstring branchtitle branchdictionary objectforkeytitlensstring localstring nsmutablestring stringwithformat node title branchtitlethis works fine with no errorsnavitem settitlenslocalizedstringbranchtitle localstring but this which seems identical to me fails with the errors noted abovenavitem settitlenslocalizedstringbranchtitle nsmutablestring stringwithformat node title branchtitlesearching here and elsewhere i have not found an explanation i read through a number of hits on each error message and various nslocalizedstring issues but nothing that tied them together what i found about the second error message implied maybe an issue with clang and the number of commas in the statement indicating that even though the extra comma is within the nsmutablestring message it was still being seen as an extra parameter by nslocalizedstring does that make any sensenot important for the question but the statement is intended to set the localized version of a navigation bar title based on the english version pulled from a dictionary which varies for different views the nsmutablestring portion defines the comment for the localization based on the english titleedit after resolving this issue per the accepted answer below i noticed another related issue the declaration of localstring was producing an unused variable compiler warning though it was clearly being used this is also due to it being within a cmacro and for completeness i am adding a link to a relevant post here about suppressing that warning how can i get rid of an aunused variablea warning in xcode,['objective-c'] +406959,how to prevent specialization of stdvector i have a templated class that has a data member of type stdvectort where t is also a parameter of my templated classin my template class i have quite some logic that does thist value m vectorindexthis does not seem to compile when t is a boolean because the operator of stdvector does not return a boolreference but a different typesome alternatives although i do not like any of themtell my users that they must not use bool as template parameterhave a specialization of my class for bool but this requires some code duplicationis not there a way to tell stdvector not to specialize for bool,['c++'] +406988,what can i do in my code today to prevent the unix time stamp running out in 2038 for example i mostly program in php what can i do today to prevent my program from exploding in 2038 due to unix time stamp running out i would love to see some specific algorithms functions or logics that can work to prevent this problem thanks,['php'] +407006,destructor called after throwing from a constructor i used to think that in c if a constructor throws an exception the destructor of this partially constructed class is not calledbut it seems that it is not true anymore in c11 i compiled the following code with g and it prints x destructor to the console why is thisinclude exceptioninclude iostreaminclude stdexceptusing namespace stdclass xpublic x x10 throw runtime errorexception thrown in xx xint a cout xx a endl x cout x destructor endl int main try x x catchconst exception e cerr error ewhat endl outputstandard outxx10 x destructorstandard error error exception thrown in xx,['c++'] +407037,css show only corner border i am wondering if it is possible in css or jquery to make a border but only for corner something like this content,"['jquery', 'css']" +407064,how do i make my custom config section behave like a collection how would i need to write my custom configurationsection so that it is both a section handler and a configuration element collectionnormally you have one class that inherits from configurationsection which then has a property that is of a type that inherits from configurationelementcollection which then returns elements of a collection of a type that inherits from configurationelement to configure that you would then need xml that looks something like thiscustomsection collection element namea element nameb element namec collectioncustomsectioni want to cut out the collection node and just havecustomsection element namea element nameb element namec customsection,['c#'] +407103,using i have seen people output different strings together by using both and cout firstname lastname endlversuscout firstname lastname endlis it better to use or does it not make much of a difference,['c++'] +407112,github api list all repositories and repos content if i was to go about thisplaying just my github repositories and their contents on an external website how would i go about doing this are there any source codes you can provide me with if not point me in the right direction i am quite a beginner to programming so any help is appreciated thank you everyonetaking a glance at their website i glanced over relevant links but still have no clue how i would accomplish thisgithub list all reposgithub list all repo content,"['php', 'javascript']" +407144,most lightweight way to plot streaming data in python to give you a sense of what i am looking for it looks like thisup until now i have used matplotlib for all my plotting and timing has not been critical it is been done in postprocessingi am wondering if there is a lighter weight way to plot other than shifting my data to the left and redrawing the entire plot,['python'] +407167,is there any difference between push back and resizesize1 a standard vector can be expanded to hold one more member by doing eitherstdvectorint vvpush back1orint os vsizevresizeos1vos 1apart from the terseness of the code using push back are there any other differences for example is one more efficient than the other or is the extra memory assigned differently in each case,['c++'] +407251,preventing instantiation of a class if argument to constructor is illegal i have a public constructor which takes a parameter int age to create an object i want to check if the passed parameter is legal or not for example age cannot be negative if its illegal then do not create an objectinstance if legal no problemi can only think of one way to do this make constructor private create a static method with parameter int age to do all the checking and return a null if you pass it an illegal value if you pass it a legal value then create an object and return its referenceis there any other way of doing it maybe from inside the constructor itself edit i thought of one problem with the above method the factory methodobject creator method can only be a static method for obvious reasons what happens if the factory method has to access a member variable to do some checking to create an object then we will be forced to make that member variable static this may not be okay in all cases does it make sense,['java'] +407263,slice array from and to last element how to make this transformationabcde c d ei was thinking that slice can do this butabcdeslice21 c d abcdeslice20,['javascript'] +407265,locationsearch in javascript hi i want to know what locationsearchsubstring1 actually does i see this code on some website i alert but this did not give any result does it suppose to alert location hrefalertlocationsearchsubstring1,['javascript'] +407301,qt 50 exposing c methods to java script i tried to expose an object as a global property to java script which has method belowq invokable myobject createmyobjectmyobject is derived from qobjectwhen i call this method in java script it returns an object of typeqvariantmyobjecti am wondering if it is possible to automatically convert it to qjsvalue so i can use it further in the script,['javascript'] +407318,unable to get public profile url from linkedin in android bufferedinputstream is closed i am unable to get the public profile url and get or post from the linkedin api in android i am using linkedinjandroid source i am able to get successful accesstoken but when calling this line from onnewintentedited i have internet permission in my app so this will not be a problemperson profile clientgetprofileforcurrentuserenumsetofprofilefieldpublic profile url override protected void onnewintentintent intent string verifier intentgetdatagetqueryparameteroauth verifier linkedinaccesstoken accesstoken oauthservicegetoauthaccesstokenlitoken verifier client factorycreatelinkedinapiclientaccesstoken person profile clientgetprofileforcurrentuserenumsetofprofilefieldpublic profile url logvpublic profile url profilegetpublicprofileurl the app crashes below is the log tracefatal exception maincomgooglecodelinkedinapiclientlinkedinapiclientexception javaioioexception bufferedinputstream is closedat comgooglecodelinkedinapiclientimpllinkedinapixppclientunmarshallobjectlinkedinapixppclientjava167at comgooglecodelinkedinapiclientimplbaselinkedinapiclientreadresponsebaselinkedinapiclientjava3710at comgooglecodelinkedinapiclientimplbaselinkedinapiclientcallapimethodbaselinkedinapiclientjava37at comgooglecodelinkedinapiclientimplbaselinkedinapiclientcallapimethodbaselinkedinapiclientjava3725at comgooglecodelinkedinapiclientimplbaselinkedinapiclientgetprofileforcurrentuserbaselinkedinapiclientjava1122please help me thanks in advance,['android'] +407378,rotating a bitmap using jni ndk backgroundi have decided that since bitmaps take a lot of memory which can cause outofmemory errors easily i will put the hard memory consuming work on cc code the steps i use for rotating a bitmap areread bitmap info widthheightstore bitmap pixels into an arrayrecycle the bitmapcreate a new bitmap of opposite sizeput the pixels into the new bitmap free the pixels and return the bitmapthe problemeven though everything seems to run without any errors the output image is not a rotation of the original in fact it ruins it completely the rotation should be counter clock wise 90 degrees example screenshot is zoomed in of what i getso as you can see not only the colors became weirder but the size does not match what i have set to it something is really weird here maybe i do not readput the data correctly of course this is just an example the code should work fine on any bitmap as long as the device has enough memory to hold it also i might want to do other operations on the bitmap other than rotating it code i have created androidmk filelocal path call mydirinclude clear varslocal module jnitestlocal src files jnitestcpplocal ldlibs lloglocal ldflags ljnigraphicsinclude build shared libraryapp optim debuglocal cflags gcpp fileinclude jnihinclude jnihinclude androidloghinclude stdiohinclude androidbitmaphinclude cstringinclude unistdhdefine log tag debugdefine logd android log printandroid log debuglog tag va args define loge android log printandroid log errorlog tag va args extern c jniexport jobject jnicall java com example jnitest mainactivity rotatebitmapccw90jnienv env jobject obj jobject bitmap jniexport jobject jnicall java com example jnitest mainactivity rotatebitmapccw90jnienv env jobject obj jobject bitmap getting bitmap info logdreading bitmap info androidbitmapinfo info int ret if ret androidbitmap getinfoenv bitmap info 0 logeandroidbitmap getinfo failed errord ret return null logdwidthd heightd strided infowidth infoheight infostride if infoformat android bitmap format rgba 8 logebitmap format is not rgba 8 return null read pixels of bitmap into native memory logdreading bitmap pixels void bitmappixels if ret androidbitmap lockpixelsenv bitmap bitmappixels 0 logeandroidbitmap lockpixels failed errord ret return null uint32 t src uint32 t bitmappixels uint32 t temppixels new uint32 tinfoheight infowidth int stride infostride int pixelscount infoheight infowidth memcpytemppixels src sizeofuint32 t pixelscount androidbitmap unlockpixelsenv bitmap recycle bitmap using bitmaprecycle logdrecycling bitmap jclass bitmapcls envgetobjectclassbitmap jmethodid recyclefunction envgetmethodidbitmapcls recycle v if recyclefunction 0 logeerror recycling return null envcallvoidmethodbitmap recyclefunction creating a new bitmap to put the pixels into it using bitmap bitmapcreatebitmap int width int height bitmapconfig config logdcreating new bitmap jmethodid createbitmapfunction envgetstaticmethodidbitmapcls createbitmap iilandroidgraphicsbitmapconfiglandroidgraphicsbitmap jstring configname envnewstringutfargb 8 jclass bitmapconfigclass envfindclassandroidgraphicsbitmapconfig jmethodid valueofbitmapconfigfunction envgetstaticmethodidbitmapconfigclass valueof ljavalangstringlandroidgraphicsbitmapconfig jobject bitmapconfig envcallstaticobjectmethodbitmapconfigclass valueofbitmapconfigfunction configname jobject newbitmap envcallstaticobjectmethodbitmapcls createbitmapfunction infoheight infowidth bitmapconfig putting the pixels into the new bitmap if ret androidbitmap lockpixelsenv newbitmap bitmappixels 0 logeandroidbitmap lockpixels failed errord ret return null uint32 t newbitmappixels uint32 t bitmappixels int wheretoput 0 for int x infowidth 1 x 0 x for int y 0 y infoheight y uint32 t pixel temppixelsinfowidth y x newbitmappixelswheretoput pixel androidbitmap unlockpixelsenv newbitmap freeing the native memory used to store the pixels delete temppixels return newbitmap java file static systemloadlibraryjnitest rotates a bitmap by 90 degrees counterclockwise br notesbr the input bitmap will be recycled and should not be used anymore br returns the rotated bitmap br could take some time so do the operation in a new thread public native bitmap rotatebitmapccw90bitmap bitmap bitmap rotatedimagerotatebitmapccw90bitmaptorotateedit after i got my answer i wish to share this code and notes about it to everyonein order for it to work i have replaced in the code every instance of uint16 t with uint32 t that is the bug on my code i have asked aboutinput and output bitmap must be with 8 config which is argb input bitmap will be recycled during the process the code rotates the image 90 degrees counter clock wise of course you can change it depending on your needsbetter solutioni have made a nice post having this functionality and others here,['android'] +407415,is there an operation to move and overwrite files i am looking for an operation to move and overwrite a file i know that there is a new method in java7 but i was hoping to get around java7 also i know about the methods in fileutils and guava but the fileutils would not overwrite and the guava one does not document italso i am aware i could write my own method well i started but saw some problems here and there so i was hoping for something already donedo you have any suggestions,['java'] +407457,efficient way to read big endian data in c i use the following code to read bigendian information using binaryreader but i am not sure if it is the efficient way of doing it is there any better solutionhere is my code some code to initialize the stream value set the length value to the int32 sizebinaryreader reader new binaryreaderstreambyte bytes readerreadbyteslengtharrayreversebytesint result systembitconvertertoint32temp 0,['c#'] +407458,livestream video from one android phone to another over wifi i have searched the internet for days now on how to implement a video streaming feature from an android phone to another android phone over a wifi connection but i cannot seem to find anything useful i looked on android developers for sample code stackoverflow google android blogs but nothing all i can find are some sort of phonetodesktop or desktoptophone solutions for streaming but nothing that i can borrow in my implementation i need to control a robot using an arduino adk so i am using 2 phones one which will be mounted on the robot and another which will receive the video stream from the robot i am mentioning this because i am trying to achieve the smallest delay between the broadcast time and the viewing timei am writing 2 apps one master app to control the robotfrom the handheld phone which will control the slave app and receive the stream and the second slave app which will run on the robotstrapped phone controlling the motorsactuatorsstreaming to master app i can not use third party apps unfortunately i need to integrate the video stream code into my 2 appswhat options are there for achieving this also is it very hard to do because i never worked with videostreaming tough i am doing pretty good in both java and android development how should i encodedecode the stream how do i initiate the connection will i need to work with udp instead of tcpip i really do not know where to start with no sample code anywhere i am pretty sure this can be achieved i just cannot find anything useful to get me started in the right directioni stumbled across spydroid but it is using vlc on a desktop so its no good for me,['android'] +407463,adding style to file upload button in css i have a text field and button with following cssjs fiddle link submit mozboxshadowinset 0px 1px 0px 0px cae3fc webkitboxshadowinset 0px 1px 0px 0px cae3fc boxshadowinset 0px 1px 0px 0px cae3fc backgroundwebkitgradient linear left top left bottom colorstop005 79bbff colorstop1 4197ee backgroundmozlineargradient center top 79bbff 5 4197ee 100 filterprogiddximagetransformmicrosoftgradientstartcolorstr79bbff endcolorstr4197ee backgroundcolor79bbff mozborderradius6px webkitborderradius6px borderradius6px border1px solid 469df5 thisplayinlineblock colorf fontfamilyarial fontsize14px fontweightbold padding5px 14px textdecorationnone textshadow1px 1px 0px 287ace cursorpointersubmithover backgroundwebkitgradient linear left top left bottom colorstop005 4197ee colorstop1 79bbff backgroundmozlineargradient center top 4197ee 5 79bbff 100 filterprogiddximagetransformmicrosoftgradientstartcolorstr4197ee endcolorstr79bbff backgroundcolor4197ee submitactive positionrelative top1px textinput padding 6px fontsize 13px border 1px solid d5d5d5 color 3 borderradius 4px 4px 4px 4px important form input typetext classtextinput size40 input typebutton valueupload idupload clasubmitformi want to add the same style to the file upload input type i am a css beginner how can i use this style to file upload button,"['html', 'css']" +407490,getting total result count from rails query using will paginate i get a list of objects from my rails app and use will paginate to page as usual and then i have a little method used to save details of the search to the databaseper page10sessionsearch params paramssearch peopledocuments personsearch peopleparamssearch people paramspage per pagesearchcreateuser id current user 0 current userid search type person firstname paramssearch peoplefirst name lastname paramssearch peoplelast name results documentscount the problem is the number of search results doumentscount is always per page used for will paginate i understand why this is but is there a way around it without running the query twice once with will paginate and once without,['ruby-on-rails'] +407503,should you overload swap in the std namespace i read something interesting today that said the standard way to call swap on a user provided type provided as a template argument isusing stdswapswapsomething soemthingelsethe reason for this is to use argument dependent lookup to either use a swap function in a user namespace or swap in the std namespace this raised an interested question for me when i overload stdswap for one of my classes i had actually been defining it in the std namespace namespace std void swap is this practice wrong should i define my own swaps in std or my own namespace and why,['c++'] +407614,python urlparse extract domain name without subdomain need a way to extract a domain name without the subdomain from a url using python urlparsefor example i would like to extract googlecom from a full url like the closest i can seem to come with urlparse is the netloc attribute but that includes the subdomain which in this example would be wgooglecomi know that it is possible to write some custom string manipulation to turn wgooglecom into googlecom but i want to avoid byhand string transforms or regex in this task the reason for this is that i am not familiar enough with url formation rules to feel confident that i could consider every edge case required in writing a custom parsing functionor if urlparse cannot do what i need does anyone know any other python urlparsing libraries that would,['python'] +407617,how ro run code after uiview transitionwithview i want to run a block of code after animations completed but the compiler shows the following error incompatible block pointer types sending void void to parameter of type void boolhere is my code i am not sure what i am doing wrong please help thanksuiview transitionwithviewselfview duration15 optionsuiviewanimationoptiontransitionflipfrombottom change to whatever animation you like animations selfview addsubviewmyimageview1 selfview addsubviewmyimageview2 completion nsloganimations completed do something,"['ios', 'objective-c']" +407640,directx application hiccups every 3 seconds i have been investigating an issue in my directx 11 c application for over a week now and so i am turning to the good people on stackoverflow for any insight that may help me track this one downmy application will run mostly at 6090 frames per second but every few seconds i will get a frame that takes around a third of a second to finish after much investigation debugging and using various code profilers i have narrowed it down to calls to the directx api however from one slow frame to the next it is not always the same api call that causes the slowdown in my latest run the calls that stall always for about a fifth of a second are id3d11devicecontextupdatesubresourceid3d11devicecontextdrawindexedidxgiswapchainpresentnot only is it not the same function that stalls but each of these functions mainly the first two the slow call may be from various places in my code from one to the next according to multiple profiling tools and my own high resolution timers i placed in my code to help measure things i found that this hiccup would occur at consistent intervals of just under 3 seconds 295this application collects data from external hardware and uses directx to visualize that data in real time while the application is running the hardware may be idle or running at various speeds the faster the hardware goes the more data is collected and must be visualized i point this out because it may be useful when considering some of the characteristics of this bugthe long frames do not occur while the hardware is idle this makes sense to me because the software just has to redraw data it already has and does not have to transfer new data over to the gpuhowever the long frames occur at these consistent 3 second intervals regardless of the speed the hardware is running so even if my application is collecting twice the amount of data per second the frequency of the long frames does not changethe duration of these long frames is very consistent always between 025 and 03 seconds i believe it is the slow call to the directx api that is consistent so any variation on the overall frame duration is external to that callwhile field testing last week when i first thiscovered the issue i noticed that on a couple runs of the application after a long time probably 20 minutes or more of continuous testing without interacting much with the program aside from watching it the hiccup would go away the hiccup would come back if we interacted with some features of the application or restarted the program does not make sense to me but almost like the gpu figured out and fixed the issue but then reverted back when we changed up the pattern of work it had been doing previously unfortunately the nature of our hardware makes it difficult for me to replicate this in a lab environmentthis bug is occurring consistently on two different machines with very similar hardware dual gtx580 cards however in recent versions of the application this issue did not occur unfortunately the code has undergone many changes since then so it would be difficult to pinpoint what specific change is causing the issuei considered the graphics driver and so updated to the latest version but that did not make a difference i also considered the possibility that some other change was made to both computers or possibly an update to software running on both of them could be causing issues with the gpu but i cannot think of anything other than microsoft security essentials that is running on both machines while the application runs and i have already tried thisabling it is realtime protection feature to no availwhile i would love for the cause to be an external program that i can just turn off ultimately i worry that i must be doing something incorrectlyimproperly with the directx api that is causing the gpu to have to make adjustments every few seconds maybe i am doing something wrong in the way i update data on the gpu since the lag only happens when i am collecting data to thisplay then the gpu stalls every few seconds and whatever api function that happens to get called during a stall cannot return as fast as it normally wouldany suggestions would be greatly appreciatedthankstimupdate 20130121i finally gave in and went searching back through previous revisions of my application until i found a point where this bug was not occurring then i went revision by revision until i found exactly when the bug started happening and managed to pinpoint the source of my issue the problem started occurring after i added an unsigned integer field to a vertex type of which i allocate a large vertex buffer because of the size of the vertex buffer this change increased the size 18465 mb 110787 mb to 129252 because i do in fact need this extra field in my vertex structure i found other ways to cut back on overall vertex buffer size and got it down to 70426 mbmy best guess is that the addition of that field and the extra memory it required caused me to exceed some thresholdlimit on the gpu i am not sure if it was an excess of total memory allocation or an excess of some limit to a single vertex buffer either way it seems that this excess caused the gpu to have to do some extra work every few seconds maybe communicating with the cpu every few seconds and so my calls to the api had to wait on this if anyone has any information that would clarify the implications of large vertex buffers i would love to hear itthanks to everyone who gave me their time and suggestions,['c++'] +407700,using ilmerge with log4net is causing inaccessible due to protection level error i created a wrapper class for the initialization of my log4net logging objects in order to make it easier to establish custom properties in the threadcontext this occurs within a class library that i have established along with many other useful functions to join all of the various libraries i have also added an afterbuild target to ilmerge using the internalize switchall references to this initializer method within the library targeted by ilmerge seem to work just fine however when i reference this merged library in other places my implementation throws protection level errors i have tried adding various things to the optional exclude internalizeexcludestxt file but this does not seem to workexample excludestxtlog4netconfiglog4netthreadcontextlog4netlogmanagerhas anyone else had this issueedithere is the code assembly log4netconfigxmlconfiguratorwatch truenamespace logging public static class log4netthreadcontext public static ilog initializetype declaringtype read from configuration xmlconfiguratorconfigure set properties threadcontextpropertiesid ifsystemdiagnosticsdebuggerisattached special debugging logger return logmanagergetloggerdebug mode else root logger return logmanagergetloggerdeclaringtype i am utilizing this code like soprivate static readonly type declaringtype methodbasegetcurrentmethoddeclaringtypeprivate static readonly ilog log log4netthreadcontextinitializedeclaringtypeloginfosomething usefuleditthis is my afterbuild targettarget nameafterbuildcreateitem includereferencecopylocalpaths conditionextensiondll output itemnameassembliestomerge taskparameterinclude createitemmessage textmerging assembliestomergefilename importancehigh exec commandquotprogramfilesmicrosoftilmergeilmergeexequot targetplatformv2 log internalizequotilmergeexcludestxtquot keyfileassemblyoriginatorkeyfile outmainassembly quotintermediateassemblyquot assembliestomergequotfullpathquot delete filesreferencecopylocalpathsoutdirdestinationsubdirectoryfilenameextension is there just a better way in general to debug protection level issues log4netthreadcontextinitializesystemtype is inaccessible due to its protection level,['c#'] +407738,is there a good framework for java desktop applications i have developed many desktop applications in swing even those a bit more complex with hibernate and spring integration i found out that many things repeats and should be done quickly and in convenient way like application lifecycle logging alerts authorisation forms and their validation i started looking for frameworks i met swing application framework which is dead since several years as it turned out spring rcp really met with my expectations especially creating forms basing on java bean model is what i liked but i realised it is dead too netbeans rcp is not for me i am using eclipse and i do not want to use another ide for desktop development i am not really excited about eclipse rcp i got feeling that it is too eclipse oriented i would prefer something low coupled to any tool besides it is not so straightforward to learn i am surprised that there is so weak support for developing desktopbased business applications in java it is like java was only used in web environment what is the preferred language for making such apps then and if i want to stay with java is there a chance to find something similar to spring rcp so far i could not,['java'] +407745,assign one value to multiple objects in one statement if i want to declare three new arrays a1 a2 a3 i can do this a1a2a3but now i want to do it all on one line likea1 a2 a3 but this fails how can i assign them all to an empty array on one line,['ruby'] +407753,google drive api does not play well with proguard npe currently i am having experience that a piece of code which makes use of google drive api is running fine without introducing proguardhowever after introducing proguard i am getting the following runtime error at javalangthreadrunthreadjava856caused by javalangnullpointerexception at comgoogleapiclientutiltypesgetactualparameteratpositiontypesjava329 at comgoogleapiclientutiltypesgetiterableparametertypesjava309 at comgoogleapiclientjsonjsonparserparsevaluejsonparserjava546 at comgoogleapiclientjsonjsonparserparsejsonparserjava350 at comgoogleapiclientjsonjsonparserparsevaluejsonparserjava586 at comgoogleapiclientjsonjsonparserparsejsonparserjava289 at comgoogleapiclientjsonjsonobjectparserparseandclosejsonobjectparserjava76 at comgoogleapiclientjsonjsonobjectparserparseandclosejsonobjectparserjava71 at comgoogleapiclienthttphttpresponseparseashttpresponsejava491 at comgoogleapiclientgoogleapisservicesabstractgoogleclientrequestexecuteabstractgoogleclientrequestjava456 at comjstockcbacloudfilejava136note the crash happens at my code which is comjstockcba if i retrace using mappingtxt request is fileslistfilelist files requestexecutein my proguard i thought having the following 2 key instructions able to prevent the crash from happen i tell proguard never touch on jackson and google librarieskeep class orgcodehaus keep class comgoogle keep interface orgcodehaus keep interface comgoogle but that does not work npe still happen at typesjavanote that i had another try is that i thought obfuscate process causes npe happens hence i try to thisable it using dontobfuscate but this time i will not able to generate apk file and getting a popular error message conversion to dalvik format failed with error 1here is the proguard configuration which causes npe at google drive apioptimizationpasses 1dontusemixedcaseclassnamesdontskipnonpubliclibraryclassesdontpreverifyverboseoptimizations codesimplificationarithmeticfieldclassmerging comment out the following line will cause popular conversion to dalvik format failed with error 1dontobfuscatedontwarn sunmiscunsafedontwarn comgooglecommoncollectminmaxpriorityqueuedontwarn javaxswingdontwarn javaawtdontwarn orgjasyptencryptionpbedontwarn javabeansdontwarn orgjodatimedontwarn comgoogleandroidgmsdontwarn orgw3cdombootstrapdontwarn comibmicutextdontwarn demo hold onto the mappingtext file it can be used to unobfuscate stack traces in the developer console using the retrace toolprintmapping mappingtxt keep line numbers so they appear in the stack trace of the develeper console keepattributes annotationenclosingmethodsourcefilelinenumbertablekeep public class extends androidappactivitykeep public class extends androidappapplicationkeep public class extends androidappservicekeep public class extends androidcontentbroadcastreceiverkeep public class extends androidcontentcontentproviderkeep public class extends androidappbackupbackupagenthelperkeep public class extends androidpreferencepreferencekeep public class comandroidvendinglicensingilicensingservicekeep class androidsupportv4app keep interface androidsupportv4app keep class comactionbarsherlock keep interface comactionbarsherlock keep class orgcodehaus keep class comgoogle keep interface orgcodehaus keep interface comgoogle assumenosideeffects class androidutillog public static int d public static int i public static int e public static int v keepclasseswithmembernames class native methodskeepclasseswithmembers class public initandroidcontentcontext androidutilattributesetkeepclasseswithmembers class public initandroidcontentcontext androidutilattributeset intkeepclassmembers class extends androidappactivity public void androidviewviewkeepclassmembers enum public static values public static valueofjavalangstringkeep class implements androidosparcelable public static final androidosparcelablecreator assumenosideeffects class androidutillog public static d public static v public static ikeepclasseswithmembers class comgooglecommonbaseinternalfinalizer methodsis there anything else i can tryi am not sure it might be caused by the combination of the libraries although things run pretty well without introducing proguardif i look at the npe crash location typesgetactualparameteratpositiontypesjava329private static type getactualparameteratpositiontype type class superclass int position parameterizedtype parameterizedtype typesgetsuperparameterizedtypetype superclass type valuetype parameterizedtypegetactualtypeargumentsposition this is normally a type variable except in the case where the class of iterabletype is superclass eg iterablestring if valuetype instanceof typevariable type resolve typesresolvetypevariablearraysaslisttype typevariable valuetype if resolve null return resolve return valuetypei suspect typesgetsuperparameterizedtype returning null so i further look into typesgetsuperparameterizedtypepublic static parameterizedtype getsuperparameterizedtypetype type class superclass if type instanceof class type instanceof parameterizedtype outer while type null type objectclass class rawtype if type instanceof class type is a class rawtype class type else current is a parameterized type parameterizedtype parameterizedtype parameterizedtype type rawtype getrawclassparameterizedtype check if found collection if rawtype superclass return the actual collection parameter return parameterizedtype if superclassisinterface for type interfacetype rawtypegetgenericinterfaces interface type is class or parameterized type class interfaceclass interfacetype instanceof class class interfacetype getrawclass parameterizedtype interfacetype if superclassisassignablefrominterfaceclass type interfacetype continue outer move on to the super class type rawtypegetgenericsuperclass return nullwhat is the possible root cause that may cause getsuperparameterizedtype returning null after processed by proguard,['android'] +407759,determine if a python class is an abstract base class or concrete my python application contains many abstract classes and implementations for exampleimport abcimport datetimeclass messagethisplayobject metaclass abcabcmeta abcabstractproperty def thisplayself message passclass friendlymessagethisplaymessagethisplay def greetself hour datetimedatetimenowtimetupletm hour if hour 7 raise exceptioncannot greet while asleep elif hour 12 selfthisplaygood morning elif hour 18 selfthisplaygood afternoon elif hour 20 selfthisplaygood evening else selfthisplaygood nightclass friendlymessageprinterfriendlymessagethisplay def thisplayself message printmessagefriendlymessageprinter is a concrete class that we can usefriendlymessageprintergreetgood nightbut messagethisplay and friendlymessagethisplay are abstract classes and attempting to instantiate one would result in an errortypeerror cannot instantiate abstract class messagethisplay with abstract methods sayhow can i check if a given class object is an uninstantiatable abstract class,['python'] +407765,cannot start site in iis use by another process when i try to start a site in iis it says the process cannot access the file because it used by another processi searched in google and found that another site may have been using port 80 but in myiis i see that only this site is using port 80 what else could be using port 80 or is there another issue involved,['asp.net'] +407815,what does nsmakerangei 1 mean i just start to learn ioswhat does nsmakerangei 1 mean for int i 0 i name length i nsrange range nsmakerangei 1 nsstring substring name substringwithrangerange const char cstring substring utf8string if strlencstring 3 return no,"['ios', 'objective-c']" +407817,unbalanced calls to beginend appearance transitions for while compiling the code i got unbalanced calls to beginend appearance transitions for uinavigationcontroller 0xa98e050 warning here is my codekvpasscodeviewcontroller passcodecontroller kvpasscodeviewcontroller alloc initpasscodecontrollerdelegate selfuinavigationcontroller passcodenavigationcontroller uinavigationcontroller alloc initwithrootviewcontrollerpasscodecontrolleruiviewcontroller selfdelegate presentmodalviewcontrollerpasscodenavigationcontroller animatedyes,"['iphone', 'ios', 'objective-c']" +407837,twig access object i want to access the value of a object inside a twig templatenormally i would get the return like thatecho langgettestbut how can i do the same in the template with twigi tried so many methods but no one workedfor example i tried attributelang get test with the resultcatchable fatal error argument 3 passed to twig node expression getattr construct must be an instance of twig node expression array instance of twig node expression constant giventhanks,['php'] +407861,why 0 0 equals 1 in python why does 0 0 equal 1 in python should not it throw an exception like 0 0 does,['python'] +407865,how to pass enum as an argument in a method in java public class enumvalues enum courselist java c python perl enum generalinformation name age phone enum sex male female public static void mainstring args printenumvaluegeneralinformation how to pass enum in this blockstatic void printenumvalueenum generalinformation how to receive enum in this block systemoutprintlnjavautilarraysaslistgeneralinformationvalues,['java'] +407870,sqlalchemy complains that foreign key does not exist but actually it exists i have the following modelsclass lookbase tablename looks id columninteger primary keytrue url columnstring nullablefalse uniquetrueclass similaritybase tablename similarities table args uniqueconstraintlook id small look id big id columninteger primary keytrue look id small columninteger foreignkeylooksid nullablefalse look id big columninteger foreignkeylooksid nullablefalsewhen i am running this codetry with sessionbegin nested similarity similarity similaritylook id small similaritylook id big look id1 look id2 sessionaddsimilarity sessioncommitexcept exception e loggingerrore print look id1 s look id2 s look id1 look id2this is the error i am getting20130119 045542974 error foreign key associated with column similaritieslook id small could not find table looks with which to generate a foreign key to target column idlook id1 217137 look id2 283579so i tried looking for these values in pgsql and they do existgiordano select from looks where id 217137 or id 283579 id url title image url 217137 283579 2 rowsi have spent the whole night trying to figure this out some cluesi am only getting these errors on certain values i do not think having double foreignkeys on the same table will result in an issueanyone editgiordano d looks table publiclooks column type modifiers storage description id integer not null default nextvallooks id seqregclass plain url character varying not null extended indexes looks pkey primary key btree id looks url key unique constraint btree urlreferenced by table similarities constraint similarities look id big fkey foreign key look id big references looksid table similarities constraint similarities look id small fkey foreign key look id small references looksidhas oids nogiordano d similarities table publicsimilarities column type modifiers storage description id integer not null default nextvalsimilarities id seqregclass plain look id small integer not null plain look id big integer not null plain indexes similarities pkey primary key btree id similarities look id small look id big key unique constraint btree look id small look id bigforeignkey constraints similarities look id big fkey foreign key look id big references looksid similarities look id small fkey foreign key look id small references looksidhas oids noeditafter turning on my postgresql statements this is what i am seeinglog statement beginlog statement select versionlog statement select current schemalog statement show transaction isolation levellog statement select casttest plain returns as varchar60 as anon 1log statement select casttest unicode returns as varchar60 as anon 1log statement rollbacklog statement beginlog statement declare c 10dfc08d0 1l cursor without hold for select feedbacksid as feedbacks id feedbacksuser id as feedbacks user id feedbackslook id as feedbacks look id from feedbacks limit 500log statement fetch forward 1 from c 10dfc08d0 1llog statement fetch forward 5 from c 10dfc08d0 1llog statement fetch forward 10 from c 10dfc08d0 1llog statement fetch forward 20 from c 10dfc08d0 1llog statement fetch forward 50 from c 10dfc08d0 1llog statement fetch forward 100 from c 10dfc08d0 1llog statement fetch forward 250 from c 10dfc08d0 1llog statement fetch forward 500 from c 10dfc08d0 1llog statement fetch forward 10 from c 10dfc08d0 1llog statement close c 10dfc08d0 1llog statement rollbacklog unexpected eof on client connectioni am not seeing any inserts why,['python'] +407874,do marker animations exist on googlemaps sdk for ios is it possible to moverotate gmsmarker on gmsmapview with animation,['ios'] +407897,common folderfile structure in flask app i have just created a flask application and so far i have a router for my hello world templatei would like to add a little a lot more functionality but i wonder how i should structure the app directorywhats the most common way of structuring a flask appfor instance should i create a routespy for all my routeswhere does the sqlalchemy stuff goshould models be in modelspy,['python'] +407911,javalangunsupportedoperationexception posixpermissions not supported as initial attribute on windows i am using java7 file api i write a class that is working fine on ubuntu creating directories perfectly but when i run same code in windows then it is throwing errorexception in thread main javalangunsupportedoperationexception posixpermissions not supported as initial attribute at sunniofswindowssecuritydescriptorfromattributeunknown source at sunniofswindowsfilesystemprovidercreatedirectoryunknown source at javaniofilefilescreatedirectoryunknown source at javaniofilefilescreateandcheckisdirectoryunknown source at javaniofilefilescreatedirectoriesunknown source at comcloudspokefolder permissionfoldercreatefolderfolderjava27 at comcloudspokefolder permissionmainmainmainjava139my folder class code ispackage comcloudspokefolder permissionimport javaioioexceptionimport javaniofilefilesimport javaniofilepathimport javaniofileattributefileattributeimport javaniofileattributeposixfilepermissionimport javaniofileattributeuserprincipalimport javautilsetpublic class folder attributes required for creating a folder private userprincipal owner private path folder name private fileattributesetposixfilepermission attr public folderuserprincipal ownerpath folder namefileattributesetposixfilepermission attr thisownerowner thisfolder namefolder name thisattrattr invoking this method will create folders public void createfolder try createdirectories function is used for overwriting existing folder instead of createdirectory method filescreatedirectoriesfolder name attr filessetownerfolder name owner catch ioexception e todo autogenerated catch block eprintstacktrace systemoutprintlncreated folder thisfolder name error is coming from createfolder method of folderhow to remove this error,['java'] +407931,core data deadlock while removing persistent store is there a safe way to remove the persistent store and create a new one in an application where other threads are using nsmanagedobjectcontexts associated with the store being removed i have tried locking the nspersistentstorecoordinator and unlocking it after the operation is over but it did not help all my attempts have resulted in a deadlock it always happens on this line executed on the main threadselfpersistentstorecoordinator removepersistentstore store error error,['ios'] +407972,findreplace mysql to mysqli makes code nonfunctional so as i am sure anyone whos been a regular on so has noticed the mysql functions are going to be deprecated and it is suggested that one use mysqli or pdo instead thus i decided to transition over to mysqli by doing a simple findreplace in my code replacing every mysql with mysqli this seemed to work okay in dreamweaver and i got no syntax errors or anything all the new mysqli functions were colored blue meaning that they were recognized as valid functions however when i saved everything and ran the code i noticed that any code having to do with mysql had become nonfunctional undoing the replace solved the problem is my server perhaps not supporting the mysqli functions i know that it is running php 5 and mysql 5 is there perhaps something else that you have to add to the code what am i missing,"['php', 'mysql']" +407981,how to start the vuforia ar sample app android i am following the vuforia and i have run the samples it is working fine but if i want to start the our own app so could you help me how to start the appthanks,['android'] +408008,set very low values to zero in numpy in numpy i have an array like 0 05j 025 123524e24j 025 0j 246519033e32 0j what is the fastest and easiest way to set the super low value to zero to get 0 05j 025 0j 025 0j 0 0j efficiency is not the paramount,['python'] +408010,how to make adsense ads work with responsive website i looked around the current solutions and this question has been partially covered in these two postsmaking adsense responsiveandin javascript if mobile phonei have a site that is responsive and the only thing that breaks it on mobile phones is the horizontal google ad on my page which makes it stick out at first with extra space since it is bigger than everything elsei am looking to see if anyone has a workable solution so i can basically switch between this big banner and a smaller format for mobile browsers where the screen size is smaller and does not break my responsive site my current solution would be to pull in the screen size and show a smaller ad if it is below a certain threshold is there a better way,"['javascript', 'jquery']" +408019,mmap prot read only difference between map shared and map private if i create an mmap2 of a file with a prot parameter of prot read only and the file backing it is also readonly and does not change is there any performance difference or any difference at all between map shared and map private will the kernel do something differently between the twothe documentation only refers to difference of behaviour in terms of updates but as it is prot read there can be no updates i wonder if there is some other difference,['c'] +408032,facebook php sdk dealing with access tokens i have crawled around lots of various answers but am still a bit confused with how i should be dealing with facebook access tokensone of the main problems i am having is due to what information is being stored in my browser for example i log onto the app the token expires i cannot logon again unless i clear cookiesapp settings in browser i stumbled across this thread how to extend access token validity since offline access deprecationwhich has shown me how to create an extended access token through phpmy questions are1 do i need to store the access token anywhere2 what happens when the access token expires or becomes invalid at the moment my app simply stops working when the short term access ones expire 3 is there a way i should be handling them to check if they have expiredi am using the php sdk and have basically used the standard if user like thisrequire sdksrcfacebookphp facebook new facebookarray appid x secret x user facebookgetuser if user try user profile facebookapime catch facebookapiexception e error loge user null if user params array scope email loginurl facebookgetloginurl params echo script typetextjavascript windowopen loginurl self script exit if user access token facebookgetextendedaccesstoken get user json token access token rest of my code hereis there anything else i should be doing to handle tokens should i be passing the access token between pages or is it ok to just call it again at the top of each page like thisfacebook new facebookarray appid x secret x redirect uri httplocalhost80 token facebookgetextendedaccesstoken,['php'] +408076,is there an opposite of linqs all method i am currently usinga listallitem itemfield is true truewhich works well but i would like to know if there was a proper linq method to do the opposite of all,['c#'] +408080,manifestin package data and data files clarification i am trying to create a python package and i have a directory structure like this mypkg init py module1 xpy ypy ztxt module2 apy bpythen i added all the files in manifestin and when i check the created archive it had all the files the when i do python setuppy install in the thistpackagesmypkgmodule1 i see only the python files and not the ztxti have the ztxt in manifest and the setuppy as well setup packages mypkgmypkgmodule1mypkgmodule2 package data mypkgmodule1ztxt include package data true i tried adding the file as data files as well but that created a directory in usrlocal i want to keep it inside the source code directory as the code uses that datai have read these posts but i keep getting confused about what is the right way to keep ztxt in the right location after the setuppy installposts manifestin ignored on python setuppy install no data files installedinstalling data files into sitepackages with setuppy dataplease help me resolve this issue i am still a beginner and this is my first time trying to create something like this,['python'] +408115,how to close a spring applicationcontext after my application finishes i want to close the spring contextthe relevant code has an applicationcontext reference but i could not find a close method,['java'] +408216,immutable objects in php is it a good idea to create objects that cannot be changed in phpfor example a date object which has setter methods but they will always return a new instance of the object with the modified datewould these objects be confusing to other people that use the class because in php you usually expect the object to changeexampleobj new object2x objadd5 7y objadd2 4,['php'] +408230,nodejs build system in sublime text 2 i justed started learning javascript while doing that i got tired of embedding my javascript code into an html document in order to run it in the browser i thought it would be nice to just run my scripts right in sublimes console so i wouldnt have to leave the editor therefore i was trying to create a javascript build system since sublime does not come with onemy idea was to use nodejs as the javascript interpreter i installed it with the package manager of linux mint as far as i can say it works just fine let us say i have a file testjs containing the following line of javascript code consoleloghello worldwhen i run nodejs pathtotestjs in my console i get hello worldhowever i do not get this to work with sublime i created a new build system by clicking tools build system new build system i then typed in the following lines cmd nodejs file as far as i know this one line is the json representation of the following command nodejs pathtocurrentfileext like i said if i run this manually in the console it works just fine if i press f7 in sublime which is the shortcut for build sublimes console shows up it is empty thoughthere is another weird thing even though the nonexisting output of sublimes console indicates that the build system is not configured to correctly work with nodejs i got some nodejs errors thisplayed when i accidentally tried to run nonjs files such as the nodesublimebuild file this is the output thisplayed in sublimes console homebaerenfaengerconfigsublimetext2packagesusernodesublimebuild2 cmd nodejs file modulejs434 var compiledwrapper runinthiscontextwrapper filename true syntaxerror unexpected token at module compile modulejs43425 at objectjs modulejs46410 at moduleload modulejs35332 at function load modulejs312 at array0 modulejs48410 at eventemitter tickcallback nodejs19039finished in 01s with exit code 1so why do i not get any output when executing actual javascript code thank you in advance,['javascript'] +408232,how to implement excels accrint as part of the formulajs project i am trying to reimplement excels accrint function in javascript but the language should not matter i have been trying to find a proper description for how it is supposed to work especially with respect to the first interest parameter but could not find anythinginterestingly enough excel google spreadsheets apple numbers gnumeric and openoffice all thisagree on the way to implement it even though all three major versions of excel win mac web seem to agree with each other some more context can be found on this blog postdozens of tests cases and my current flawed implementation can be found hereany help would be greatly appreciatedupdate to be clear the issue is not related to the day count convention which we implemented using david wheelers pseudocode for yearfrac which itself was validated by over 32 million tests covering all five basis options the issue comes from the first interest parameter which nobody seems to really understand as far as we can tell this parameter is simply ignored by many alternative spreadsheets including openoffice it is commented out in the source code and this parameter really behaves in strange ways if you use excel and you change its value you will see that it will change the results given by the accrint function but in ways that seem chaotic try changing the first interest date by a full century and youll see the accrued interest changing but not by much i really cannot make sense of that if anyone can i am all ears,['javascript'] +408344,get the bits of a float in python i am looking for the python equivalent of javas floatfloattobits i found this python obtain manipulate as integers bit patterns of floats but does anyone know of a less complicated way,['python'] +408363,django serialize queryset to json to construct restful response with only field information and id i currently have a post model with title and summary fields i am retrieving all the posts and returning them as json as part of a restful api interface heres the basic approachfrom djangocore import serializersdef list postsrequest posts postobjectsfilterownerauthenticated user serialized serializersserializejson posts fieldstitle summary return httpresponseserialized mimetypeapplicationjsonand i am getting the following response back when i visit the corresponding routecurrent responsepk 4 model apipost fields summary testing title my test pk 5 model apipost fields summary testing again title another testthis technically contains all the information my clientside needs to construct models i am using backbone and could use collectionparse to construct what i need but the server side should be responsible for structuring the response nicely what troubles me about this is that it does not look like the standard api responses i am used to seeing in reputable apis i think a json response like the following would be more standarddesired responsesummary testing id 4 title my test summary my test id5 title another testthe output from serialize does not seem quite right for returning a collection of model instances in json as a response from an api call and this seems like a fairly common need i would like to return the fields information along with the id or pk if it must be called pk,['python'] +408379,high performance library for bitwise operations dealing with very large bool data set try to use bitwise operation to handle it looking for some library that dealing with bitset that candynamic set and can be passed by pointers or references read and write bitwisely count set bits and fastobviously stdbitsets functionalities are too limited for that any recommendations,"['c++', 'c']" +408390,why outcome object in futuretask is nonvolatile i read futuretask class in jsr166 found that outcome object is nonvolatile the comments in code is nonvolatile protected by state readswrites line 75 the state is volatile int i have read java memory model from java language spec but not found the accurate answer does anybody know the reason,['java'] +408411,default session timeout for apache tomcat applications what is the default session timeout for web applications deployed on tomcat55 is it browser specific in my web applications default timeout is mentioned neither in webxml nor in code,['java'] +408464,what is the complexity of this python sort method i have a list of lists and i am sorting them using the following datasorteddata keyitemgetter0was wondering what is the runtime complexity of this python method,['python'] +408500,why use httpclient for synchronous connection i am building a class library to interact with an api i need to call the api and process the xml response i can see the benefits of using httpclient for asynchronous connectivity but what i am doing is purely synchronous so cannot see any significant benefit over httwebrequestsif anyone can shed any light i would greatly appreciate it i am not one for using new technology for the sake of it,"['c#', 'asp.net']" +408535,two divs next to each other that then stack with responsive change i am trying to achieve something that i am sure should be easier than i am making iti am using the skeleton responsive framework and have been fine up until nowhere is a diagram of what i want to achievethis will be placed within a column once that columns reduces in size i would like it to stack the divs as per the second example in the diagram i have tried a few different ways but keep getting it wrongi am pretty new to htmlcss so any help is appreciated many thanks,"['css', 'html']" +408587,fastest way to replace string patterns by mask i have string like string string keyfoobar and array of paramsparams arrayfoo 1 bar 2how can i replace this params in string pattern expected result is string key12,['php'] +408588,unable to access validation errors in view i have set up a controller with some validationpublic function attemptlogin rules array emailrequiredemail passwordrequired validator validatormakeinputall rules ifvalidatorfails return redirecttologinwitherrorsvalidator if i output the messages directly in the controller messages validatormessagesprint rmessagesalli get the validation errors however if i redirectreturn redirecttologinwitherrorsvalidatorthe errors array available in the view is always coming up empty,['php'] +408600,include nuget packages in teamcity i recently started using nuget to manage external packages for now i have only needed it for nlog everything works fine when i build the project in vs 2012 however i am trying out teamcity as a ci server i am fairly new to ci and it is giving me the following errorcsc somenamespacesomeclasscs10 7 error cs0246 the type or namespace name nlog could not be found are you missing a using directive or an assembly referencethis error is repeated throughout where ever i use nlognow i did not include the packages folder in svn since i thought it was good practice not to include binaries and let msbuild in teamcity download these on its own however it is clearly not doing that i do include the packagesxml file in svnwhat can i check to see what is going wrongupdatethanks to davidbrabant i was nudged in the right direction however i now get the following error in teamcitypackage restore is thisabled by default to give consent open the visual studio options dialog click on package manager node and check allow nuget to download missing packages during buildhowever i am not in visual studio but teamcity so i do not know how to set consent to true i tried to set restorepackages to true in the nugettargets filerestorepackages condition restorepackages truerestorepackagesbut this did not workupdate 2to make it work i also set the following property nugettargetsrequirerestoreconsent condition requirerestoreconsent true falserequirerestoreconsentthis made the build run succesfully,['c#'] +408667,find all classes with a specific attribut possible duplicatefinding all classes with a particular attribute in an assembly i would like to get all instances of a particular class attribute in other words i would like to have the list of classes that have a specific attributenormally you would have a class for which you can fetch the attribute using the getcustomattributes method is it possible to have a list of who has a particular attribute,['c#'] +408695,function signature as template parameter is it possible to achieve something like thistemplatetypename signatureclass test public here i want operator to respect the signaturetestvoidint t1 void operatorinttestvoidint float t2 void operatorint floatreturn type is always voidi want to send as template parameter the function signature is this possible i cannot use variadic templates as my compiler does not support this feature yet,['c++'] +408708,is it modern c to use srand to set random seed for code that uses stdrandom shuffle i need to set a random seed so that the pseudorandom sequences produced vary in each program runthe code example here makes a call tosrand unsigned time null which needs toinclude ctimeinclude cstdlibi wonder since c11 includes major updates to pseudorandom number generation is this still up to date what should i use to set the random seed for stdrandom shuffle,['c++'] +408794,two forward slashes in python i came across this sample of code from a radix sortdef getdigitnum base digit num pulls the selected digit return num base digit num basewhat does the do in python,['python'] +408806,difference between initloader and restartloader in loadermanager i am completely lost regarding the differences between the initloader and the restartloader functions of the loadermanagerthey both have the same signature restartloader also creates a loader if it does not exist starts a new or restarts an existing loader in this manager is there some relation between the two methods does calling restartloader always call initloader can i call restartloader without having to call initloader is it save to call initloader twice to refresh the data when should i use one of the two and important why,"['java', 'android']" +408825,datediff in hhmmss format i need to calculate the total length in terms of hours minutes seconds and the average length given some data with start time and end timefor example the result must be something like 451510 which means 45 hours 15 min 10 sec or 3007 for 30 min 07 secwere using sql server 2008 r2 and the conversion failed when time is more than 245959 any idea of how i could do thisfor information the columns in the table are id startdatetime enddatetime etc i need to make a monthly report which contains the recordings count of the month the total length of these records and the average length i would like to know if there is an easy way to perform all of this,['sql'] +408859,select back microphone on iphone 5 is there a way for remoteio unit to pick up back microphone on iphone 5 i can configure avaudiosession to choose between front microphone or bottom microphone but i cannot find a way to select the back microphonethe avfoundation framework for sure uses the back microphone for video recording when using the back camera but i want a way to choose the same using coreaudio is that possible,['iphone'] +408879,contextual menu on only certain items in a source list i have a window with a source list nsoutlineview my source list has just two levels level one is header and level two is data i want to have a contextual menu on some of the data cells not allfirst i try to attach a menu on the table cell view who represents the data cell nothing happenssecond i attach a menu on the outline view in ib the contextual menu opens on each cells header and data i search for stopping the opening of the menu but i do not find anythingdo you have some ideas thank youos x 1082 lion xcode 452 sdk 108,['objective-c'] +408882,paypal sandbox recurring payment with initial amount pending i am using the php library here to create a new subscription profile if i set an initial amount the profile appears as pendingexamplependingcustomer mark wally verifiedprofile start date feb 18 2013 profile id ibe824p6f9peron the other hand if i set no initial payment amount the profile will be active i am setting the initial payment and the start date 1 month in the future since i want to bill monthly and get a payment right awayi have already verifiedaccount is set to accept money in any currencythe seller account has digital goods enabled created via automated processboth accounts are verifiedthe buyer account has a credit card as well as a paypal balanceboth accounts are us basedi have tried with multiple accountsany help would be greatly appreciatedcode snippet to create the subscription that use the library listed abovesubscription details array description premium membership 495 every 30 days initial amount 495 amount 495 period day start date gmdate ymdthis strtotime 30 day frequency 30,['php'] +408883,zxing library errors in ios private field cached y is not used i am currently trying to use the zxing library for an ios project however i cannot even get the sample projects to workthe scantest project as well as the ones that i created myself throw the following error in the binarybitmapcpp filein file included from volumesmacintosh hduserstimdownloadszxing21iphonezxingwidgetcppcoresrczxingbinarybitmapcpp20cppcoresrczxingbinarybitmaph337 error private field cached y is not used werrorwunusedprivatefield int cached y 1 error generatedi searched on google and stackoverflow but have not found a solution for the problemi have tried it with both the current stable release of xcode and the betai do not know if anybody else has got this problem too but any help would be greatly appreciated,"['c++', 'ios', 'objective-c']" +408887,how to use a trim function in sql server i cannot get this trim code to workselect dbocol v cost gems detailtng sys nr as ehp code dbocol tbl vcoursetng na as course title ltrimrtrimfct typ cd and ltrimrtrimdep typ id as course owner,['sql'] +408892,php dependency injection when the arguments for the constructor are not available we are just starting to make a concerted effort to use dependency injection uniformly in our project and i have run into an issuei am writing a class to handle our mongodb queries i pass in a mongoclient as a dependency on the constructor with no problem but how do i handle a dependency when the variable necessary to instantiate the object is not available at the time of instantiationin particular we have a wrapper for the mongocollection method findone that if you pass a string in currently in the old code turns that string into a mongoid with new mongoid id and uses that for the find functionfrom what i have learned about dependency injection having new mongoid is a bad idea and i know already that it will make it harder to write test cases for the function that converts a string to a mongoidbut how do i handle the injection when the mongoid class takes the id string on the constructorthe only thing i have thought of that would work is to pass in a closure on the class constructor that does something likegetmongoid function id return new mongoid id withclass mymongo function construct mongoclient client closure mongoidgetteredited to fix this last partbut is this the right way to handle it of course if we are using a dic it we can do it but requiring a closure for the constructor seems a bit much am i just being too dogmatic about injecting my dependencies i could fix this easily by using new mongoid id in the new class i suppose,['php'] +408905,android how to do image screen slide i am building a very basic gallery on android it shows the last image on the camera folder and the user can slide left to see the previous onei finished an implementation using a viewpager and a pageradapter using samplesize to scale images my problem is that the implementation is nowhere as efficient as the default gallery app every time you slide an image you have to wait around 200ms for the next one to load so basically my idea on how to implement it is not working outhow can i do this efficiently and if possible with an implementation that allows zooming in and out later onthis looks promising but i do not know how to implement it with files instead of drawablesediti have managed to improve speed a bit using photoview a hacked viewpager however it takes too much to convert the filepaths to bitmaps or drawablesi have tried these two methods suggested by dilix and idroid explorer method adrawable d drawablecreatefrompathimagepathimageviewsetimagedrawabled method bbitmap mybitmap bitmapfactorydecodefileimagepathimageviewsetimagebitmapmybitmapbut both produce error bitmap too large to be uploaded into a texture i need to get the image to the imageview as fast as possible and somehow bypass this error and maybe i will get a decent speed right now i am scaling the images and converting them to a drawable but it is not very efficient,"['java', 'android']" +408917,how to consolelog print r debugtrace in c php has a function called print r and var dump that will thisplay all the contents of an item it makes it very easy to figure out what things areis there something like that in c i know there is a consolewritelinehello in c but does this work in the mvc can i do some type of debugtrace like flash does into a debug console while i run the application,['c#'] +408979,change marker icon during runtime is there a way to change google maps android api v2 markers icon during runtime without removingreadding the marker i want to change its icon can i apply transformations to it like rotationthanks,['android'] +409029,coverage on a frozen executable is there any way to run coverage against an executable built with pyinstaller i tried just running it like a it was a python script and it didnt like the executable file as input i didnt really expect it to work and i suspect that the answer is no there is no easy way to run coverage against a built executable this is on windows exethe coverage package i am using is just the normal coverage package that you get with easy install coverage from nedbatcheldercom,['python'] +409040,why do i get unknown validator messagevalidator i get this errorunknown validator messagevalidatori have no idea why i am getting thatwhats wrong with my codevalidates title presence true uniqueness true length maximum 100 message must be input and has to be less than 100 characters and unique,['ruby-on-rails'] +409075,tinymce custom theme bullist numlist link unlink not working so i have created a custom theme for tinymce using the button method on their website most of the buttons seem to be working but the bullist numlist link and unlink buttons do nothing even when switching to html view the html is not even added ie ulliliul i have tried adding plugins for advlist advlink etc but no change cannot seem to find any answers online for this onehere is my tinymce codetextareahtmlifytinymce mode textareas script url host jsadmintinymcetiny mcejs content css host cssadmintiny mcecss language false setup functioneditor showpreview editorid previewclickfunctionevent eventpreventdefault tinymceexeccommandmceaddcontrol false editorid editorid previewcssthisplay none editoraddcommandshowhtml functionui v tinymceexeccommandmceremovecontrol false editorid editorid previewcssthisplay block theme functioneditor target var editorcontainer targetafter div div classmcetoolbar clearfix button classbtnmcebold datamcecommandboldboldbutton button classbtnmceitalic datamcecommanditalicitalicbutton button classbtnmceunderline datamcecommandunderlineunderlinebutton button classbtnmcestrikethrough datamcecommandstrikethroughstrike throughbutton button classbtnmcejustifyleft datamcecommandjustifyleftjustify leftbutton button classbtnmcejustifycenter datamcecommandjustifycenterjustify centerbutton button classbtnmcejustifyright datamcecommandjustifyrightjustify rightbutton button classbtnmcejustifyfull datamcecommandjustifyfulljustify fullbutton button classbtnmcebullist datamcecommandbullistbullet listbutton button classbtnmcenumlist datamcecommandnumlistnumber listbutton button classbtnmceundo datamcecommandundoundobutton button classbtnmceredo datamcecommandredoredobutton button classbtnmcelink datamcecommandlinklinkbutton button classbtnmceunlink datamcecommandunlinkunlinkbutton button classbtnmcecode datamcecommandshowhtmlhtmlbutton div div classhtmlifydiv div next mcetoolbarcsswidth targetcssoffsetwidth bind events for each button button editorcontainerclickfunctionevent eventpreventdefault editorexeccommand thisattrdatamcecommand false thisattrdatamcevalue setup tabbing tabindex parseint editoridattrtabindex if tabindex 1 tabindex tabindex1 keydownfunctionevent var keycode eventkeycode eventwhich if keycode 9 eventpreventdefault editorexeccommandmcefocus false editorid else editorexeccommandmcefocus false editorid editoronkeydownaddfunctioned event var tabindex parseint edidattrtabindex var keycode eventkeycode eventwhich if keycode 9 tabindex whiletabindex tabindex length 0 tabindex tabindex notreadonlylength 0 tabindex 150 tabindex if tabindex 150 tabindextabindexfocus register state change listeners editoroninitaddfunctioned event button editorcontainereachfunctioni button editorformatterformatchangedbuttondatamcecommand functionstate buttontoggleclassbtnmceon state edid ifrcssheight 100 return editor and iframe containers return editorcontainer editorcontainer0 iframecontainer editorcontainerchildreneq1 calculate iframe height target height toolbar height iframeheight targetheight editorcontainerfirstouterheight,"['javascript', 'jquery']" +409082,does invoking a constructor mean creating object when we create a subclass object which extends an abstract class the abstract class constructor also runs but we know we cannot create objects of an abstract class hence does it mean that even if a constructor completes running without any exception there is no guarantee whether an object is created,['java'] +409094,remove an empty string from array of strings jquery i have an array lorem ipsum i would like to remove the empty string from this array and get lorem ipsumis there any way to do this without using the loop and traversing through each element and removing it,['jquery'] +409103,how to get locale currency price for inapp purchases in ios i want to find out users app store location it means they are in us australiaaud store following code used voidproductsrequestskproductsrequest request didreceiveresponseskproductsresponse response books responseproducts if skpaymentqueue canmakepayments responseproducts count0 for skproduct book in books nslocale locatnslocale currentlocale nsstring strlocatelocat objectforkeynslocalecountrycode nslogn device country nstrlocate nslocale storelocale bookpricelocale nsstring storecountry nsstringcflocalegetvaluecflocalerefstorelocale kcflocalecountrycode nslogn store country nstorecountry i want like wise if book tier is one means us 099 aud 099 jpy 85 based on the app store price matrix tablei tested in the simulator i changed country name in itunes appstore and safari application in the system but i get only us country codeedit settings general internationalregion format countryi tested in the device device country only changed store country show us country code and price i want to store country code before start inapp purchase timehow many days once change the price for based on currency fluctuationis it provide any api query for fluctuated price to knownupdatemy inapp operation made one class before inapp operation made i want to thisplay the local price to user same price effect reflect in the inapp operationi thisplay the list of book free and paid books thats is list get from my server in that i thisplay the price for each item those item price while processing the appstore it will show the dollar price if appstore shown the price as also i want to shown so that i want to send country code to my server from that my server respond that country related price list and currency symbol,"['iphone', 'ios', 'objective-c']" +409135,how do i make the text in a textarea monospace when using twitter bootstrap i have the following textarea elementform actioncheckit methodget textarea classfield span8 idtextarea nameuser input rows20default datatextarea input typesubmit valuecheckerformi have just started using bootstrap but cannot work out the best way to make the text in the textarea monospace,['css'] +409230,what to use instead of orgjbossresteasyclientclientrequest i just found that orgjbossresteasyclientclientrequest is deprecated invalidating everything i could find on google about how to use the resteasy client the javadoc gives no indication as to what to use instead google is likewise silenti have reverted to 235 for now but would be interested in the answer anyways as well as how one was supposed to find out the answer without asking someone else who knew is there a resource with that information where i could have looked,['java'] +409240,how object files with templates are linked together imagine we have three h files fh template typename t class class public class t idt x return x gh template typename t class class public class t idt x return x 100 hh template typename t class class public class t idt x now we also have three cpp filesfcpp include fhint fint x classint t return tidx gcpp include ghint gint x classint t return tidx hcpp include hhint hint x classint t return tidx compiling them gives us fo go and ho now let us throw in this maincppinclude stdioextern int fintextern int gintextern int hintint main stdcout f1 stdendl stdcout g2 stdendl stdcout h3 stdendland let us do g maincpp fo go ho now comes my actual surprise since those three o files contain three different definitions for int classintidint i expect to get a linking error however what i get is a working aout which prints 1 2 3 and if i reorder o files in the command it will print 101 102 103and now for the actual questions how exactly does the linker perform linking in this case how does it figures out what instantiation of classint to keep and what to throw away and why it does not complain about multiple definitionsnm utility gives following output for nm fo go hofo0 b bss0 d data0 t text0 t text zn5classiie2idei0 t text zn5classiiec1ev0 t z1fi0 t zn5classiie2idei0 t zn5classiiec1evgo0 b bss0 d data0 t text0 t text zn5classiie2idei0 t text zn5classiiec1ev0 t z1gi0 t zn5classiie2idei0 t zn5classiiec1evho0 b bss0 d data0 d eh frame0 t text0 t z1hi you zn5classiie2idei you zn5classiiec1evclearly fo and go both export symbol zn5classiie2idei and ho imports this symbol capital letters mean external linkage and it leads to no errors why,['c++'] +409243,comparing doublenan with itself i am stuck trying to find out why these two operations return different valuesdoublenan doublenan returns false doublenanequalsdoublenan returns truei have the answer to the first part but not the second and not to why are these two comparisons returning different values,"['c#', '.net']" +409247,performseguewithidentifier tricks to avoid initial delay hi there i have a viewcontroller performing a segue on a button ibactionmovetocoolviewbuttontapped self performseguewithidentifiertocoolview sendernilthis works fine apart from an annoying delay the first time it is performed i guess due to the view not being initialized yet i obviously do not want to have to prematurely create a lot of views there are several others segues planned from the same viewcontroller so a long shot perhaps but i wondered if anyone had any brilliantly inspired tricks to avoid the initial lag,['objective-c'] +409249,getservletconfiggetservletcontext equivalent in spring i referred to a lot of posts but still i am unable to find a correct working answeri want to get it from my java class itself and not using el in jsp how to get the servlet context path in spring,['java'] +409252,using matplotlib in gae my tags and title quite clearly state my problem i want to use matplotlib to create realtime plots in google app engine i have read the documentation and searched on so and google i found a post pointing to this working demo but when i try it on my own it does not work for mei created a simple application consisting only of a handlerscript hello worldpyimport numpy as npimport osimport sysimport cstringioprint contenttype imagepngnosenvironmatplotlibdata osgetcwdu own matplotlib dataosenvironmplconfigdir osgetcwdu own matplotlibrcimport matplotlibpyplot as pltpltplotnprandomrandom20 imshownprandomrandint1010sio cstringiostringiopltsavefigsio formatpngsysstdoutwritesiogetvalueand a a configuration file appyamlapplication helloworldtakversion 1runtime python27api version 1threadsafe nohandlers url script hello worldpylibraries name numpy version latest name matplotlib version latesti want to plot something and then return the content as pngimage this procedure works fine for a normal webserver like apache or iis i did this a million times the problem is rather when i run my script locally within the development server i get an error that is probably due to my mpl version 1 which is only experimental in gae but when i deploy my app to gae i get a completely different uncorrelated errorlooking at the looks the traceback istraceback most recent call last file basedatahomeappsshelloworldtak1364765672279579252hello worldpy line 16 in module import matplotlibpyplot as plt file python27 runtimepython27 libversionsthird partymatplotlib1matplotlibpyplotpy line 23 in module from matplotlibfigure import figure figaspect file python27 runtimepython27 libversionsthird partymatplotlib1matplotlibfigurepy line 18 in module from axes import axes subplotbase subplot class factory file python27 runtimepython27 libversionsthird partymatplotlib1matplotlibaxespy line 14 in module import matplotlibaxis as maxis file python27 runtimepython27 libversionsthird partymatplotlib1matplotlibaxispy line 10 in module import matplotlibfont manager as font manager file python27 runtimepython27 libversionsthird partymatplotlib1matplotlibfont managerpy line 1324 in module rebuild file python27 runtimepython27 libversionsthird partymatplotlib1matplotlibfont managerpy line 1278 in rebuild fontmanager fontmanager file python27 runtimepython27 libversionsthird partymatplotlib1matplotlibfont managerpy line 995 in init selfdefaultfontf selfttffiles0indexerror list index out of rangeit seems to have to do something with the fontscache of mpl i read in the docs that caching and fileaccess is one of the problems with mpl in gae but obviously the import works for others what am i doing wrongeditbased on the answer below i changed my code to be import numpy as npimport cstringioimport matplotlibpyplot as pltimport webapp2class mainpagewebapp2requesthandler def getself pltplotnprandomrandom20r sio cstringiostringio pltsavefigsio formatpng selfresponseheaderscontenttype imagepng selfresponseoutwritesiogetvalueapp webapp2wsgiapplication mainpage debugtrueand like this it is working,['python'] +409271,localizing attributed uitextview from storyboard i am using the storyboard and have a view where i have subclassed some uitextviewsmy problem is that i am using ibtool generatestringsfile to extract strings from the storyboard for localization and afterwards use ibtool write on another storyboard file to apply the translated stringswhen i use ibtool any uitextviews that have attributed text is ignored by the ibtool generatestringsfile command and omitted from the resulting strings fileis it possible to extract attributed text from a storyboard for localization,['ios'] +409283,copy to clipboard not working in ffchrome i am using below mentioned javascript to copy the text to clipboard its working in ie but not working in firefox and chromeplease advice mewhat is wrong function setdatatoclipboard var strdocumentgetelementbyidpopulatedstringvalue if windowclipboarddata clipboarddatasetdata clipboarddatasetdatatext str alertcopied,"['javascript', 'html']" +409317,finding out if an enum has the flags attribute set using reflection how do i determine whether an enum has the flags attribute or notso for mycolor return trueflagspublic enum mycolor yellow 1 green 2 red 4 blue 8and for mytrade return falsepublic enum mytrade stock 1 floor 2 net 4,['c#'] +409350,how to declare the type for local variables using phpdoc notation i use zend studio to develop in php with cakephp and one of the problems with cakephp is that the views all reference undeclared local variablesso for example in the controller you wouldthissetjobnew myjobobjectthen in the view you couldecho jobgetnamemy problem is that zend studio cannot perform autocomplete on job because it is type is unknown now there are phpdoc tags that allow you to declare the type so that ides can perform autocomplete the var tag for example can be used in a class to define a propertys typeclass myjobobject var mystatusobject public statusis there a way to do something like this for local variables,['php'] +409362,error in final launch sequence failed to execute mi command gdbset targetasync off i have two projects on eclipse one produces an so and the other is android application which uses it i am trying to debug the native code in the so using this guidei set my application debuggable i started my application in the debug mode i run ndkgdb when i run the native debugger i am gettingerror in final launch sequencefailed to execute mi commandgdbset targetasync offerror message from debugger back endcannot change this setting while the inferior is runningcannot change this setting while the inferior is running,['android'] +409365,can i override important what i am trying is setting this css on element background red important so when i try to do this background yellow i am not using external cssit still only shows the red and not the yellow for that one field as i would like it to bewhat i am asking is how to override it is it possible,"['html', 'css']" +409374,what is the meaning of quick in swings timers from the java tutorialnote that the swing timers task is performed in the event thispatch thread this means that the task can safely manipulate components but it also means that the task should execute quickly if the task might take a while to execute then consider using a swingworker instead of or in addition to the timerwhat does it mean by quickly i mean that is not exact less than a minute is quickly or whatfor example if i want to make an animation1 minute with some panels via moving them change their transparency andand the user is just going to see the panels and is not going to work with them no io now is timer a good idea for such situation,['java'] +409383,func delegate does not chain methods lets imagine simple delegate callsvoid main funcint int string tfunc null tfunc add bind first method tfunc sub bind second method consolewritelinetfunc2 2private string addint a int b return add a btostringprivate string subint a int b return sub a btostringthe result of this program is sub 0so why add method was not called i am expecting to call method add and then method sub,['c#'] +409387,having trouble understanding objectivec block documentation i am currently having trouble understanding the fundamentals of objc blocks and the block storage type from the following documentation refdocuidtp407502ch6sw6i am trying to understand the following paragraph and exampleswhen a block is copied it creates strong references to object variables used within the block if you use a block within the implementation of a methodif you access an instance variable by reference a strong reference is made to selfif you access an instance variable by value a strong reference is made to the variablethe following examples illustrate the two different situationsthispatch asyncqueue instancevariable is used by reference a strong reference is made to self dosomethingwithobjectinstancevariableid localvariable instancevariablethispatch asyncqueue localvariable is used by value a strong reference is made to localvariable and not to self dosomethingwithobjectlocalvariableto override this behavior for a particular object variable you can mark it with the block storage type modifiermy questionshow exactly is one example accessed by reference while the other one is accessed by variable why is localvariable used by valuewhat does the doc mean by a strong reference is made to self which self is it referring toif i add the block storage type to localvariable in the second example am i wrong to assume that the block closes over the variable so it keeps it around in heap until block is released what other things are happeningthank you,"['ios', 'objective-c']" +409393,objectivec arc forbids explicit message send of retain i am new to objectivec i try to port an old objectivec project written in an older version of objectivec to the new one but i am getting the following compiler errorarc forbids explicit message send of retainin color acolor retainor color nscolor blackcolor retaini was reading about the new automatic reference counting that clang is using nowi have also tried to use xcodes refactor function but with no luckwhat is the proper objectivec code that need to replace this old code,['objective-c'] +409424,how to check heap usage of a running jvm from the command line can i check heap usage of a running jvm from the commandline i mean the actual usage rather than the max amount allocated with xmxi need it to be commandline because i do not have access to a windowing environment and i want script based on the value the application is running in jetty application server,['java'] +409477,c template specialization calling methods on types that could be pointers or references unambiguously summaryis there a way to call a class method on a templated type that could be a pointer or a reference without knowing which and not get compilerlinker errorsdetailsi have a templated quadtree implementation that can take any of the following nontrivial userdefined typesabstract base classa2deshapederived classesa2depointa2delinea2derectanglea2decirclea2deellipsea2detrianglea2dearca2desplinea2desectora2depolygonbut they could be a pointer or a reference as they are all derived from a2deshape so the specializations are declared astemplate class quadtreea2deshapesimilar for all derived types as referencestemplate class quadtreea2deshapesimilar for all derived types as pointersthe problem i am having is the ability to call a class method when the indirection or lack thereof is unknown and due to the templates both sets of code are generatedtemplatetypename tbool quadtreetaddt elem when elem of type t is expecting a pointer here notation fails to compile where t is a reference ie template class quadtreea2deshape with pointer to reference is illegal ifelemintersects bounds false return false if i change the above line to use the dot notationtemplatetypename tbool quadtreetaddt elem when elem of type t is expecting a reference here dot notation fails to compile where t is a pointer ie template class quadtreea2deshape with pointer to reference is illegal ifelemintersects bounds false return false if i remove the referencebased types in favor of the pointerbased types including in the declaration and usage of the quadtree class i get the error left of functionname must have clastructunionif i remove the pointerbased type in favor of the referencebased types including in the declaration and usage of the quadtree class i get the aforementioned reference to pointer is illegal againcompiler vs2010sp1,['c++'] +409492,why is my pythonnumpy example faster than pure c implementation i have pretty much the same code in python and c python exampleimport numpynbr values 8192n iter 10a numpyonesnbr valuesastypenumpyfloat32for i in rangen iter a numpysinac exampleinclude stdiohinclude mathhint mainvoid int i j int nbr values 8192 int and iter 10 double x for j 0 j nbr values j x 1 for i0 in iter i x sinx return 0something strange happen when i ran both examples time python numpy testpy real 0m5967suser 0m5932ssys 0m0012s g sinc time aout real 0m13371suser 0m13301ssys 0m08sit looks like pythonnumpy is twice faster than c is there any mistake in the experiment above how you can explain itps i have ubuntu 1204 8g ram core i5 btw,"['python', 'c']" +409516,only content controls are allowed c webcontrols so i am not sure whats going on my boss was not pleased with me using mvc and razor so i am being forced to code with this nasty webcontrolcodebehind style the error isonly content controls are allowed directly in a content page that contains content controlshere is the masterpage master languagecdoctype htmlhtmlhead titleapplication formtitlehead body div idcontainer aspcontentplaceholder idcontentplaceholder runatserver divbodyhtmland here is the defaultaspx page that is throwing the error page languagec inheritsdumbdefault masterpagefilemasterpagemaster h2application formh2aspcontent idcontent contentplaceholderidcontentplaceholder runatserver pplease complete this applicationp form actiondefaultaspx methodpost runatserver div span claspacednamespanasptextbox idname runatserver div form p asplabel idfinalmessage runatserver paspcontentand the silly defaultaspxcs codebehindusing systemusing systemwebusing systemwebuinamespace dumb public partial class default systemwebuipage protected void page load object sender eventargs e if ispostback finalmessagetext submission processed successfully,"['c#', 'asp.net']" +409779,responsive sprite background image how to hi i have two columns of content within a container the first column has text and the second is a span with a background sprite image the problem is when i get to smaller screen resolutions i want the background sprite image to have a width in percentage to be able to scale it along with the h5 with a percentage width is there a way to do this h5 floatleft thisplayblock width800pxsprite backgroundimage urlassetsimgwebsite sprite apng backgroundposition 60px 60px floatleft thisplayblock width64pxdiv classcontainer h5title h5 span clasprite spandiv,['css'] +409821,android javascript touchstart event not fired until zoom or scroll the page in my android application the user can browse some html pages using viewpager and the user can touch an element to highlight the problem is when trying to get the touch event using javascript using the following code elementfrompoint returns null when navigate to new page but after the user zoom the page or scroll on it it works right i found that register of the touchstart event happens after zoom or scroll the page so it works right after that although it is registered on documentready documentreadyfunction documentaddeventlistenertouchstart touchstart false function touchstarte var x etargettouches0clientx var y etargettouches0clienty el documentelementfrompointx y thank you,"['javascript', 'android']" +409831,what is a proper way to return not null pointer i use an external c library in my c program and the library uses a callback function that must return void the library checks if return value is not null which means succeso what is the best way to tell it that all is finei usereturn reinterpret castvoid1but it looks uglyedit thanks for reply i will stay with thisstatic int successreturn success,['c++'] +409837,can i detect if chrome is in windows 8 metro mode is there a way to detect if google chrome is running in windows 8 metro mode or in desktop modei am writing a chrome extension and i do not want it to run in metro mode,['javascript'] +409859,dynamically load the jdbc driver i am trying to load the jdbc driver dynamically with this kind of code try url urlnew urlfilelibsmysqlconnectorjava5121jar urlclassloader loader new urlclassloaderurl systemclassgetclassloader loaderloadclassdrivername enumerationdriver drivers drivermanagergetdrivers whiledrivershasmoreelements driver driver driversnextelement systemoutprintlndriverdriver classfornamedrivername true loader drivers drivermanagergetdrivers whiledrivershasmoreelements driver driver driversnextelement systemoutprintlndriverdriver connection connect drivermanagergetconnectionjdbcurl user password return connect catch malformedurlexception e eprintstacktrace return null the first whileloop shows the drivers of the classpathdriversunjdbcodbcjdbcodbcdriver35712651driveroraclejdbcoracledriver58df0438drivercomibmdb2jccdb2driver525c7734driversqlserverdriver1and the second loop shows the same drivers but without the mysql driver my question is why did i miss somethingi read in the javadoc of drivermanager that every driver tries to register himself by the drivermanager if the driver is loaded in my code this should be loaderloadclassdrivername i thought this code should invoke the static part for example static try javasqldrivermanagerregisterdrivernew driver catch sqlexception e throw new runtimeexceptioncannot register driver of the driver class,['java'] +409886,extract data from existing html with angularjs angularjs is great for complex client side javascript based web applications but i also thinking about to use it for smaller simple javascript tasksfor example i have a list with some itemsul li dataid1fooli li dataid2barliulnow i want to add some buttons to the html which should filter andor sort the list after some user input which should be an easy taskis there any way to extract the data from existing html elements to use them with angularjs the data need to be in the html so search engine could also get a hold of whats edit for claritythe end result would be that the data from the ul list will be pushed into a model of the controller that handling the list id1 textfoo id2 textbarif i push more objects into the model the list should thisplay themif i apply a filter to the model it should filter the li elementsbest case scenario would be something similar to thisdiv ngmodeldata ul ngrepeatobject in data filterfiltercriteria li dataid1fooli li dataid2barli li dataidobjectidobjecttextli uldiv,['javascript'] +409947,two way binding not working in directive with transcluded scope i have a textbox in a controller which is bound to model name there is a directive inside the controller and there is another textbox inside the directive which is bound to the same model namediv classborder ngcontrollereditctrl controller editctrl br input typetext ngmodelname br tabs directive tabs br input typetext ngmodelname tabsdivmoddirectivetabs function return restrict e transclude true template div classborder ngtranscludediv when you type something in the outer textbox it is reflected in the inner textbox but if you type something in the inner textbox it stops working ie both textbox no more reflects the same valuesee example at i have also tried using two way binding attr scope name but it gives syntax errorand using scope name has same effectany help would be greatly appreciatedin addition to the accepted answer this article really helped me in understanding the prototypical inheritance in child scpoes i would highly recommend anyone having problem with scopes to read it thoroughly,['javascript'] +409955,how to avoid progressdialog in android dialogs android developer says to avoid progressdialog to indicate loading and instead to put an activity indicator right in the layoutprogress activity android developer thiscusses activity indicators but does not name the classes used i have had no luck searching for android classes with names like activitybar activitycircle or activityindicatorwhere can i find documentation tutorials examples or api documentation on androids support for including activity indicators right in my layout avoiding a progressdialogupdate fullstackex pointed me the right answerfirst include the following code in the activitys oncreate method before invoking setcontentviewrequestwindowfeaturewindowfeature indeterminate progressnext just before loading eg firing up an asynctaskloader use this call to make the spinner appearsetprogressbarindeterminatevisibilitytruefinally after the load is completed hide the spinner againmainactivitythissetprogressbarindeterminatevisibilityfalsebingo no progressdialog required making the spinner visible seems to slow down loading considerably in the emulator it takes minutes instead of seconds but not on my actual phone i am not sure if there is any way to make the spinner use fewer cpu cycles,['android'] +409961,actionbarsherlock google maps api v2 duplicate id i am trying to integrate the actionbarsherlock with google maps api v2 fragmentsi have a layout with 2 fragments one for a list layout and another with a supportmapfragmentwhen i click on a list item first go well but when i click on a list item second time it throws an error duplicate id 0x7f040038 tag null or parent id 0x0 with another fragment for comgoogleandroidgmsmapssupportmapfragmenti tried several solutions and none of them have been able to fix it is there something i am doing wrong please help mei modified actionbarsherlock to include sherlockmapfragment implemented to support the new supportmap as shown here this is my code,['android'] +409980,multiplying an object with a constant from left side i have a matrix class and it has overloaded operators for scalar and matrix multiplicationstemplate class t class matrix public matrix operatort scalar const template class tmatrixt matrixtoperatort rightscalar const matrixt resultmatrixm unrowsize m uncolsize for uint64 t i0 im unrowsize i for uint64 t j0 jm uncolsize j resultmatrixi j thematrixm uncolsize i j rightscalar return resultmatrix i can multiply a matrix object with a scalar from right side without any problemmatrixdouble x3 3 define a 3x3 matrix and initialize its contentsmatrixdouble y define an output matrixy x 100 do the linear operationbut how do i multiply it from left side same waymatrixdouble x3 3 matrixdouble yy 100 xin arithmetic it is a common notation to write constants on the left side when doing multiplication i would like to obey this rule to make my code more readableis it possible to implement this in cif it is possible how do i modify the class method in my code,['c++'] +409984,forward a port via upnp in python i am making a python application that requires the user to have a port forwarded to his computer in order to communicate with a server or another user the current implementation works quite great yet the only thing is that the person whos running the file must forward the port to the local ip manually i want to automate this he picks a port script checks if it can be forwarded then it forwards it if it cannot it handles the error respectivelyi have looked into some libraries that claim they can do this in pure python since i will need to compile to exes after finishing but did not manage to find something useful if you could provide me with a code sample on how to attempt to forward a port and handle successfail respectively that would be greatthanks in advance for your timepsit is python 27x that i am targeting,['python'] +409994,stdshared ptr thread safety i have read that multiple threads can simultaneously read and write different shared ptr objects even when the objects are copies that share ownership msdn thread safety in the standard c librarydoes that mean that changing shared ptr object is safe for an instance is the next code considered safeshared ptrmyclass global make sharedmyclassin thread 1shared ptrmyclass private globalin thread 2global make sharedmyclasscan i be sure in that case that thread 1 private will have the original value of global or the new value which thread 2 assigned but either way it will have a valid shared ptr to myclasseditjust to explain my motivation i want to have a shared pointer to hold my configuration and i have a thread pool to handle requestsso global is the global configurationthread 1 is taking the current configuration as it start to handle a requestthread 2 is updating the configuration only apply to future requests if it is work i can update the configuration that way without breaking it in the middle of a request handling,['c++'] +410013,annoying errors running builder android pre compiler on project dialog possible duplicateeclipse android aerrors running builder aandroid pre compilera on projectaa i keep getting the following error popup every now and then on my android project on eclipse 421titlebuilding workspace has encountered a problem errors occurred during the buildmessageerrors running builder android pre compiler on project x javalangnullpointerexceptionfyi my project has svn repositories and uses 4 external libraries that seem to be fine no errors i am using android 42what could be the issue here,['android'] +410050,closing tags in contenteditable without inserting superfluous tags working with an unordered or ordered list in a contenteditable gives me a headachewhenever i want to end editing the list by pressing enter twice the browser will close the ul but inserts a p firefox or a div chrome tag that contains a br example heremy goal is to avoid that superfluous p or div and instead just close the ul i have tried to modify tim downs solution which will prevent the browser to insert p or div when pressing enter and instead inserts a clean br tagexample hereunfortunately though when using that solution the ul is never closed by the browser since only br tags are inserted inside the li itemso my question is how can i actively close the ul by inserting a node or pasting html when pressing enter on the last empty li update in case the question is stll unclear i am looking for a way to close the ul without inserting p or div tags but just by inserting a good old plain br instead,"['javascript', 'jquery']" +410093,how to check if a class inherits another without instanciating an object function afunction bbprototype new ahow can i check if the class b inherits class a in javascript i would like to avoid instanciating b to use instanceof new b instanceof a,['javascript'] +410099,flask confusion with app i am starting a flask project and in my code i havefrom flask import flask render template abortapp flask name now what exactly is appi am following this guide and i am particularly confused about the structure because he has chosen to have directory named app and is his app init py he hasfrom flask import flaskapp flask name from app import viewsand in his appviewspy he hasfrom app import appwhat the hell is it with all these apps,['python'] +410122,typescript event handler function for event type field incorrect context this is a jquery interface from jquerydtsexport interface idialogevent extends dialogevent event event ui dialoguiparams voidthis is my custom interface mimicking partial functionality of the dialogoptions interface of jquerydtsexport interface idialogoptions open idialogeventexport class dialogclass implements idialogoptions dialog options public open idialogevent class related fields public somefield any public dialogel jquery constructor thisopen thisopenhandler thisdialogel divdivdialogthis passing this initializes the dialog by mapping relevant class fields to the dialogs option object in this case the only relevant field is open public openhandlerevent event ui dialoguiparams var value thissomefield bad this is not type baseclass public noneventhandlermethod var value thissomefield good this is type baseclass var dialog new dialogclassdialogdialogeldialogopen the last line fires openhandler but inside it this is not type basedialog unlike in noneventhandlermethodthe reason i need an event handler function for the dialog options field and the reason why i cannot simply do this export class dialogclass implements idialogoptions constructor thisopen event handling logic is because i need to add additional openevent handling logic in classes that extend dialogclass and there is no differentiation between thismember and supermember there is only differentiation between thisfunction and superfunction export class logindialog extends dialogclass constructor thisopen thisopenhandler public openhandlerevent event ui dialoguiparams superopenhandler base handling logic additional handling logic i think this may be a bug because export class dialogclass implements idialogoptions constructor thisopen var test thissomefield correct context and calling the method directly var dialog new dialogclass dialogopenhandler correct context when called directly note i have not actually tested this persay but this function is no different than any other functionso a direct call should certainly not be problem,['javascript'] +410130,include jekyll liquid template data in a yaml variable i am using the yaml heading of a markdown file to add an excerpt variable to blog posts that i can use elsewhere in one of these excerpts i refer to an earlier blog post via markdown link markup and i use the liquid template data variable siteurl in place of the base url of the siteso i have something like trimmed it somewhat title decluttering ordination plots in vegan part 2 orditorpstatus publishlayout postpublished truetags tag1 tag2excerpt in the earlier post in this series siteurl 20130112declutteringordinationplotsinveganpart1ordilabel decluttering ordinationplots in vegan part 1a ordilabel i looked at the ordilabel functionhowever jekyll and the maruku md parser do not like this which makes me suspect that you cannot use liquid markup in the yaml headeris it possible to use liquid markup in the yaml header of pages handled by jekyllif it is what i am i doing wrong in the example shownif it is not allowed who else can i achieve what i intended i am currently developing my site on my laptop and do not want to hard code the base url as it will have to change when i am ready to deploythe errors i am getting from maruku are maruku tells you must quote title the earlier post in this series siteurl 20130112declutteringo byte 40and maruku tells you unclosed link the earlier post in this series siteurl 20130112declutteringor byte 41and maruku tells you no closing i will not create the link for earlier post in this series the earlier post in this series siteurl 20130112declutteringor byte 41,['ruby'] +410139,how to force inlineblock elements to wrap i have an inlineblock divelement thisplay inlineblocki use jquery to repeatedly append it to the dom var element div classelement bodyappendelementappendelementappendelementappendelementhowever the appended divs do not wrap it is as if i had the following markup no newlinesdiv classelementdivdiv classelementdivdiv classelementdivdiv classelementdivappending whitespace inbetween the elements does not fix problem bodyappendelementappend how can i force these elements to wrap i do not want to use floats,['css'] +410142,get class name for empty queryset in django i have empty queryset of model studentstudents studentsobjectsallif the above queryset is empty then how can i get the modelclass namehow can i get the model name for empty querysetedithow can i get the app name from the queryset,['python'] +410215,javascript object pushed into an array possible duplicate how do i correctly clone a javascript objecti have this codevar temp var obj name1temppushobjobjname 2temppushobjwhat i am expecting to be truetemp0name 1 temp1name 2what actually happenstemp0name 2 temp1name 2why does this happen and how i can get what i am expecting,['javascript'] +410216,change position of google maps apis my location button i am using the google maps android api v2 and i need a way to chance the position of the my location button i get the my location button like this googleplayservicesutilisgoogleplayservicesavailablegetapplicationcontextfinal googlemap map supportmapfragment getsupportfragmentmanager findfragmentbyidridmapgetmap this gets the buttonmapsetmylocationenabledtrue,"['java', 'android']" +410261,detect allusions eg very fuzzy matches in language of inaugural addresses i am trying to develop a python script to examine every sentence in barack obamas second inaugural address and find similar sentences in past inaugurals i have developed a very crude fuzzy match and i am hoping to improve iti start by reducing all inaugurals to lists of stopwordfree sentences i then build a frequency indexnext i compare each sentence in obamas 2013 address to each sentence of every other address and evaluate the similarity like socompare two lemmatized sentences assumes stop words already removed frequencies is dict of frequencies across all inaugural def comparesenta sentb frequencies intersect x for x in senta if x in sentb and frequenciesx for x in intersect calculate sum that weights uncommon words based on frequency inaugurals and sum100 x 1 for x in n ratio of matches to total words in both sentences john adams and william harrison both favored long sentences that tend to produce matches by sheer probability c floatlenintersect lensenta lensentb return intersect n n clast i filter out results based on arbitrary cutoffs for and and c it works better than one might think identifying sentences that share uncommon words in a nonnegligible proportion to total words for example it picked up these matchesobama 2013for history tells us that while these truths may be selfevident they have never been selfexecuting that while freedom is a gift from god it must be secured by his people here on earthkennedy 1961with a good conscience our only sure reward with history the final judge of our deeds let us go forth to lead the land we love asking his blessing and his help but knowing that here on earth gods work must truly be our own obama 2013through blood drawn by lash and blood drawn by sword we learned that no union founded on the principles of liberty and equality could survive halfslave and halffreelincoln 1861yet if god wills that it continue until all the wealth piled by the bondsmans two hundred and fifty years of unrequited toil shall be sunk and until every drop of blood drawn with the lash shall be paid by another drawn with the sword as was said three thousand years ago so still it must be said the judgments of the lord are true and righteous altogetherobama 2013this generation of americans has been tested by crises that steeled our resolve and proved our resiliencekennedy 1961since this country was founded each generation of americans has been summoned to give testimony to its national loyaltybut it is very crudei do not have the chops for a major machinelearning project but i do want to apply more theory if possible i understand bigram searching but i am not sure that will work here it is not so much exact bigrams were interested in as general proximity of two words that are shared between quotes is there a fuzzy sentence comparison that looks at probability and thistribution of words without being too rigid the nature of allusion is that it is very approximatecurrent effort available on cloud9ideupdate 12413per the accepted answer heres a simple python function for bigram windowsdef bigramstokens blur1 grams for c in rangelentokens 1 for i in rangec 1 minc blur 1 lentokens gramsappendtokensc tokensi return grams,['python'] +410265,c cast parent class to child class i am fairly new to c and this is the problem i have i have two classes client and host and when everything is loaded you have the option to press two buttons if you press button 1 client is loaded and if you press button 2 host is loadednow both client and host are fairly big classes and i do not want to put them both into the memory so my idea was creating a base class and then both client and host should extend the base class and then the only thing i had to do was thisbase connectionif button 1 is pressedconnection clientif button 2 is pressedconnection hostwell this sounded almost too good to be true and when i tried it i got no errors now comes the problem base has a function called a and client has a function called b so the function b is unique to the class clientwhen i try to call function b i get this error class base has no member named b how can i let c know that i am talking to class client or host instead of base i am also open for a whole new approach to this problem maybe it is just an error in my thinking processthanks in advance,['c++'] +410266,using numpytake for faster fancy indexing edit i have kept the more complicated problem i am facing below but my problems with nptake can be summarized better as follows say you have an array img of shape planes rows and another array lut of shape planes 256 and you want to use them to create a new array out of shape planes rows where outpj lutp imgp j this can be achieved with fancy indexing as followsin 4 timeit lutnparangeplanesreshape1 1 img10 loops best of 3 471 us per loopbut if instead of fancy indexing you use take and a python loop over the planes things can be sped up tremendouslyin 6 timeit for in lutjtakeimgj for j in xrangeplanes pass10 loops best of 3 59 us per loopcan lut and img be in someway rearranged so as to have the whole operation happen without python loops but using numpytake or an alternative method instead of conventional fancy indexing to keep the speed advantageoriginal questioni have a set of lookup tables luts that i want to use on an image the array holding the luts is of shape planes 256 n and the image has shape planes rows cols both are of dtype uint8 matching the 256 axis of the lut the idea is to run the pth plane of the image through each of the n luts from the pth plane of the lutif my lut and img are the followingplanes rows cols and 3 40 40 4lut nprandomrandint231 231 1 sizeplanes 256 and 4viewuint8lut lutreshapeplanes 256 nimg nprandomrandint231 231 1 sizeplanes rows cols 4viewuint8img imgreshapeplanes rows colsi can achieve what i am after using fancy indexing like thisout lutnparangeplanesreshape1 1 1 imgwhich gives me an array of shape planes rows cols n where outi j holds the ith plane of img run through the jth lut of the ith plane of the lutall is good except for thisin 2 timeit lutnparangeplanesreshape1 1 1 img1 loops best of 3 565 s per loopwhich is completely unacceptable especially since i have all of the following not so nice looking alternatives using nptake than run much fastera single lut on a single plane runs about x70 fasterin 2 timeit nptakelut0 0 img010 loops best of 3 785 ms per loopa python loop running through all the desired combinations finishes almost x6 fasterin 2 timeit for in nptakelutj k imgj for j in xrangeplanes for k in xrangen pass1 loops best of 3 947 ms per loopeven running all combinations of planes in the lut and image and then thiscarding the planes2 planes unwanted ones is faster than fancy indexingin 2 timeit nptakelut img axis1nparangeplanes nparangeplanes1 loops best of 3 379 s per loopand the fastest combination i have been able to come up with has a python loop iterating over the planes and finishes x13 faster in 2 timeit for in nptakelutj imgj axis0 for j in xrangeplanes pass1 loops best of 3 434 ms per loopthe question of course is if there is no way of doing this with nptake without any python loop ideally whatever reshaping or resizing is needed should happen on the lut not the image but i am open to whatever you people can come up with,['python'] +410284,run code from a python module modify module then run again without exiting interpeter i would like to be able to open a python shell execute some code defined in a module then modify the module then rerun it in the same shell without closingreopeningi have tried reimporting the functionsobjects after modifying the script and that does not workpython 272 default jun 20 2012 1623 gcc 421 compatible apple clang 40 tagsappleclang418060 on darwintype help copyright credits or license for more information from my module import buggy function test input buggy functiontest inputwrong value returns incorrect result go to the editor make some changes to the code and save them thought reimporting might get the new version from my module import buggy function test input buggy functiontest inputwrong value returns the same incorrect resultclearly reimporting did not get me the new version of the function in this case it is not that big a deal to close the interpreter and reopen it but if the code i am testing is complicated enough sometimes i have to do a fair amount of importing objects and defining dummy variables to make a context that can adequately test the code it does get annoying to have to do this every time i make a changeanyone know how to refresh the module code within the python interpeter,['python'] +410295,cancelling a getusermedia request i have a modal dialog box in my application which uses getusermedia to thisplay a video from the users camera this causes a denyallow bar to appear let us say that the user closes the dialog before clicking deny or allow the bar remains even though the elements that would be using it have thisappearedis there a way to notify the browser that it can hide the permission request even though the user never interacted with it,['javascript'] +410323,ajax jquery autocomplete with json data i am trying to setup my jquery ui autocomplete field to have data from an ajax connection here is my code so far mainingredientautocompleteautocomplete source function request response ajax url apiingredientchoices datatype json success function data responsefunction item return label itemmainname value itemmainitemid this is my jsonsubitemid1mainitemid1subname2mainnamemilksubitemid2mainitemid1subnameskimfat freemainnamemilksubitemid3mainitemid2subnamecheddermainnamecheesehtmltable idtbl ingredients stylepadding0px tr idingheader tdingredienttd tdmeasurementtd tdamounttd tdinput idmainingredientautocomplete td tdtd trtablewhen i start to type mil for milk my code gives me this errorediti made your change which worked for a few attempts but now i am getting a new error unhandled exception at line 55 column 25 in url0x800a1391 microsoft jscript runtime error data is undefined mainingredientautocompleteautocomplete source function request response ajax url apiingredientchoices datatype json response mapdata functionvi return label vmainname value vmainitemid,['jquery'] +410335,how to set selfmaxdiff in nose to get full diff output when using nose 121 with python 330 i sometimes get an error message similar to the following onefail maxdiff2test equaltraceback most recent call last file usrlocallibpython33sitepackagesnosecasepy line 198 in runtest selftestselfarg file usersloiccmrsjcalculus iiscrapmaxdiff2py line 32 in test equal assert equalstr1 str2assertionerror lorem ipsum dolor sit amet consectetur adipiscing elit donec adiam lectusn truncated suspenthisse lectus leo consectetur in tempor sitamet placerat quis nequene truncateddiff is 1780 characters long set selfmaxdiff to none to see itran 1 test in 0064sfailed failures1in many situations to figure out what the error really is i need to see the full diff output however i have no idea of how to set that selfmaxdiff googling for nose and maxdiff does not help with the same version of nose on python 271 the full diff is printed to screenhere is a simple script that generates the error above when run with nosetests33from nosetools import assert equaldef test equal str1 lorem ipsum dolor sit amet consectetur adipiscing elit donec a diam lectussed sit amet ipsum mauris maecenas congue ligula ac quam viverra necconsectetur ante hendrerit donec et mollis dolor praesent et diam eget liberoegestas mattis sit amet vitae augue nam tincidunt congue enim ut porta loremlacinia consectetur donec ut libero sed arcu vehicula ultricies a non tortorlorem ipsum dolor sit amet consectetur adipiscing elit aenean ut gravidalorem ut turpis felis pulvinar a semper sed adipiscing id dolorpellentesque auctor nisi id magna consequat sagittis curabitur dapibus enimsit amet elit pharetra tincidunt feugiat nisl imperdiet ut convallis libero inurna ultrices accumsan donec sed odio eros donec viverra mi quis quampulvinar at malesuada arcu rhoncus cum sociis natoque penatibus et magnis thisparturient montes nascetur ridiculus mus in rutrum accumsan ultricies maurisvitae nisi at sem facilisis semper ac in est str2 suspenthisse lectus leo consectetur in tempor sit amet placerat quis nequeetiam luctus porttitor lorem sed suscipit est rutrum non curabitur lobortisnisl a enim congue semper aenean commodo ultrices imperdiet vestibulum utjusto vel sapien venenatis tincidunt phasellus eget dolor sit amet ipsumdapibus condimentum vitae quis lectus aliquam ut massa in turpis dapibusconvallis praesent elit lacus vestibulum at malesuada et ornare et est utaugue nunc sodales ut euismod non adipiscing vitae orci mauris ut placeratjusto mauris in ultricies enim quisque nec est eleifend nulla ultricesegestas quis ut quam donec sollicitudin lectus a mauris pulvinar id aliquamurna cursus cras quis ligula sem vel elementum mi phasellus non ullamcorperurna assert equalstr1 str2,['python'] +410337,how to access ui elements in parent activity from fragment parent activity layoutrelativelayout xmlnsandroid xmlnstools androidlayout widthmatch parent androidlayout heightmatch parent toolscontextlockercodeactivity linearlayout androidididfragment container androidlayout widthmatch parent androidlayout heightmatch parent linearlayout progressbar androidlayout widthwrap content androidlayout heightwrap content androidlayout centerhorizontaltrue androidlayout centerverticaltrue androidididctrlactivityindicator androidindeterminateonlytrue androidkeepscreenonfalse textview androidididtv results androidlayout widthwrap content androidlayout heightwrap content androidlayout centerhorizontaltrue androidlayout centerverticaltrue androidtext relativelayoutinflate the fragment in the parent activity oncreate functionfragmentmanager fragmentmanager getfragmentmanager fragmenttransaction fragmenttransaction fragmentmanagerbegintransaction fragment scannerfragment new scanfragment fragmenttransactionaddridfragment container scannerfragment fragmenttransactioncommitworking great so far now how do i hide the progressbarthis is what i have triedpublic view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate view view inflaterinflaterlayoutfragment scan container false progressbar progressbar progressbar viewfindviewbyidridctrlactivityindicator progressbarsetvisibilityviewinvisible return view i get a null pointer exception,['android'] +410347,c gccollect not destroy an object if it is constructed using instance constructor initializer possible duplicateresurrection difference in using object initializer i am having a hard time trying to understand how garbage collector works in c i am using 2012 so c 45 here is my example code public class a public int c public a public aint pc c pc public static void main test 1 var a new a c199 var aref new weakreferencea a null consolewritelinearefisalive gccollect consolewritelinearefisalive consolewritelinegcgetgenerationareftarget output 1 test 2 a new a 200 aref new weakreferencea a null consolewritelinearefisalive gccollect consolewritelinearefisalive output is true true true falseit seems to me in both tests the object on the heap has no root before calling gccollect but it happens that in test 1 the object get through the force gc run while in test 2 it does not so is there something mysterious going on about using initializer my guess is that there might be some extra code when use initializer that would become a strong root for the same objectthanks,"['c#', '.net']" +410348,impacts of cpu cache on speed i just wrote a program to test the impact of cpu cache on speed performancevoid foovoid ptr int r int ptr for int i r s i n i num threads r numi return nullvoid barvoid ptr int r int ptr int idx r s int block nnum threads int start idx block end start block for int i start i end i r numi return nullbasically foo did an interlace scanning on the other hand bar scan the array blockbyblocktest result indicates that bar is much fastergcc pingpongc stdgnu99 lpthread o2 aout1077037s0395525sso how to interpretate this resultthe full source code is at update all ifstatements removed,['c'] +410376,get driving directions using google maps api v2 i am trying to get the driving direction between the two positionslatlng12917745607762378830latlng128420568076630964940the code which i have triedpolyline line mmapaddpolylinenew polylineoptions addnew latlng12917745607762378830 new latlng128420568076630964940 width5colorcolorredbut this draws a straight line between the two points is there any other methodway to get the driving directions between these two points,"['java', 'android']" +410377,tomcat server fails to start the server and application in sts when i run the spring mvc application i get this exception and sever fails to startplease help me to fix this issueexception stacktracejan 24 2013 113359 am orgapachecatalinastartupcontextconfig processannotationsjarsevere unable to process jar entry orgspringframeworkinstrumentclassloadingoc4jpackageinfoclass from jar jarfiledworksmetadatapluginsorgeclipsewstservercoretmp0wtpwebappsdailyshipwebinflibspringcontext310releasejar for annotationsjavautilzipzipexception invalid loc header bad signature at javautilzipzipfilereadnative method at javautilzipzipfileaccess1400zipfilejava56 at javautilzipzipfilezipfileinputstreamreadzipfilejava677 at javautilzipzipfilezipfileinflaterinputstreamfillzipfilejava413 at javautilzipinflaterinputstreamreadinflaterinputstreamjava158 at javaiobufferedinputstreamfillbufferedinputstreamjava235 at javaiobufferedinputstreamreadbufferedinputstreamjava254 at javaiodatainputstreamreadintdatainputstreamjava387 at orgapachetomcatutilbcelclassfileclassparserreadidclassparserjava237 at orgapachetomcatutilbcelclassfileclassparserparseclassparserjava114 at orgapachecatalinastartupcontextconfigprocessannotationsstreamcontextconfigjava2104 at orgapachecatalinastartupcontextconfigprocessannotationsjarcontextconfigjava1980 at orgapachecatalinastartupcontextconfigprocessannotationsurlcontextconfigjava1946 at orgapachecatalinastartupcontextconfigprocessannotationscontextconfigjava1931 at orgapachecatalinastartupcontextconfigwebconfigcontextconfigjava1325 at orgapachecatalinastartupcontextconfigconfigurestartcontextconfigjava878 at orgapachecatalinastartupcontextconfiglifecycleeventcontextconfigjava369 at orgapachecatalinautillifecyclesupportfirelifecycleeventlifecyclesupportjava119 at orgapachecatalinautillifecyclebasefirelifecycleeventlifecyclebasejava90 at orgapachecatalinacorestandardcontextstartinternalstandardcontextjava5173 at orgapachecatalinautillifecyclebasestartlifecyclebasejava150 at orgapachecatalinacorecontainerbasestartchildcallcontainerbasejava1559 at orgapachecatalinacorecontainerbasestartchildcallcontainerbasejava1549 at javautilconcurrentfuturetasksyncinnerrunfuturetaskjava334 at javautilconcurrentfuturetaskrunfuturetaskjava166 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava10 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava603 at javalangthreadrunthreadjava722,['java'] +410402,how to convert varchar to double in sql i have problem with my query when i was trying to convert the varchar field to double numeric i have this sql statementselect fullname casttotalbal as numeric92 from client info order by totalbal descactually i want to thisplay the values of totalbal in descending order but since that field is in varchar the resultset is sometimes wrong this is the resultset when i tried to query using this statementselect fullname totalbal from client info order by totalbal desc resultset isthe sorting of totalbal is not correct so i decided to convert the varchar to numeric so that it might be sorted perfectly any idea,['sql'] +410409,how can i stick the div after scrolling down a little i wanted to stick the 2nd div when we scroll down the page and when the 2nd div meets the top boundary when it is fixed it should scroll along with the other pages how can i achieve thissettings width100 background383838 height60pxmenu width100 positionrelative height100px backgroundabodycontent height900px positionrelativeand the html bodydiv idtop div idsettings div div idmenu divdivdiv idbodycontentdivbodyhere in this example the 2nd div should be fixed when we scroll the page when we scroll up should turn into the previous state itself please help me,"['javascript', 'html', 'css']" +410435,javascript charting nvd3 line chart with two yaxis can anyone please suggest me a way to assign two yaxis to a nvd3 line chart,['javascript'] +410477,repository deployment and composer what workflow as a php developer i find myself working with composer a lot in the past it was on personal projects and such so i did not have much problems with it but now with laravel 4 it is on project that require deploying and i am in kind of a struggle to adapt my workflowall my projects are git repositories thus per convention and because it is still quite buggy like most developers i put the vendor directory in my gitignorenow the problem is i also use git to deploy to the server and by all logic the vendor directory is not uploaded as it is not tracked by the repositoryso my question is towards people that have worked with composer and git for longer than me what is the best workflow to keep the server in sync how to track the vendor folder without really tracking it i tried uploading it every time i update with composer but some of my vendor folders are quite big and i cannot manually upload 30mb of files every time something updates i do not really know how do you guys work it out i tried not ignoring the vendor folder but git just messes it up half are recognized as cloned repos and are just ignored anyway etcupdate note that i am on a shared host so i do not have access to the servers terminal,['php'] +410498,mongodb conversation private message schema using mongoid i am building a forum system in rails in order to become more acquainted with rails and mongoid a feature i would like to add is a private message system forum users can use to message each otherin terms of schema design i can think of two solutionssolution 1users and messages are separate documents linked to each other using has many and belongs touser documenthas many messages sent class name message inverse of message senderhas many messages received class name message inverse of message recipientandmessage documentfield created type datetime default timenow field content type stringbelongs to message sender class name user inverse of messages sentbelongs to message recipient class name user inverse of messages receivedin order to show a user his inbox i would look at some usermessages received ordered by created and filtered so i have a list of unique sender ids ordered by the time their last message was sent to some userthen to show a specific conversation i would just get all messages between the two participants and interleave them according to timestamps messages in some usermessages receivedwheremessage sender selected correspondentmessages out some usermessages sentwheremessage recipient selected correspondenti do not like this solution because it involves hitting the messages collection with where queries multiple times and a lot of manual filtering and interleaving of messages sent and received effortsolution 2 which i am using nowembed messages in a conversation document i will provide the code for user message and conversation below a conversation is linked to two or more users via has and belongs to many nn since a user may also have many conversations this could also potentially allow multiuser conversations i like this solution because in order to show a user his inbox i can just use some userconversations ordered by last message received stored and updated in the conversation document no filtering required to show a specific conversation i do not need to interleave messages sent and received as messages are already embedded in the conversation document in the correct orderthe only problem with this solution is finding the correct conversation document shared by two or more users when you want to add a message one solution is suggested here mongodb conversation system but i do not like it because the query seems relatively expensive and scaling for multiuser conversations looks like it will get tricky instead i have a field in the conversation document named lookup hash which is a sha1 hash calculated from the object ids of each user participating in the conversation this way given two or more users it is trivial to find their corresponding conversation document or create it if it does not exist yetto add a message to a conversation i just use conversationadd message class method not instance method because the conversation may not exist yet giving it a sender recipient and new message objectquestionmy question is am i doing anything obviously wrong considering mongoid or just nosql in general schema design best practices is there anything i can do to improve my solution is my idea of using a hash to lookup conversations a bad ideacodeuserrbclass user include mongoiddocument field username type string field joined type datetime default timenow field last activity type datetime default timenow has and belongs to many conversations endconversationrbrequire digestsha1class conversation include mongoiddocument field lookup hash type string field created type datetime default timenow field last message time type datetime default timenow array of user ids of users that have read all messages in this conversation field last message seen by type array default embeds many messages has and belongs to many participants class name user validates presence of lookup hash index lookup hash 1 unique true name lookup hash index used to show a user a list of conversations ordered by last message time index id 1 last message time 1 unique true name id last message time index def selfadd messagerecipient sender message find or create a conversation conversation conversationfind or create by lookup hash get lookup hashrecipientid senderid do c cparticipantsconcat recipient sender end conversationmessages message conversationlast message time timenow conversationlast message seen bydeleterecipient conversationsave end private def selfget lookup hashparticipant ids lookup key participant idssortjoin digestsha1hexdigest lookup key endendmessagerbclass message include mongoiddocument field created type datetime default timenow field text type string embedded in conversation belongs to author class name user validates length of text minimum 2 maximum 256 validates presence of authorend,"['ruby-on-rails', 'ruby']" +410506,how to properly setup nginx accesscontrolalloworigin into response header based on the origin header from the request i am looking for a nginx config setup that does setup the accesscontrolalloworigin to the value received in the originit seems that the method does not work with chrome and the multiple urls does not work with firefox as it is not allowed by cors specification so far the only solution is to setup the accesscontrolalloworigin to the value received in the origin yes some validation could be implementedthe question is how to do this in nginx preferably without installing additional extensionsset allow origin instead i want to get the value from origin request headeradd header accesscontrolalloworigin allow origin,['javascript'] +410511,facebook xmpp chat api device priority i have created a facebook app that uses the chat api using the following structurestrophejs punjab facebook xmppall works fine my question is can i prevent other clients receiving messages once my app is connectedto elaborate if a user starts using my app to communicate he should not receive replies at the normal facebook chat uican this be done,['javascript'] +410528,autofocus on a jbutton on a jpanel i have a jpanel loaded on a jframe the jpanel contains 4 jbuttons the thing i am trying to do is to get the focus automatically on the 1st jbutton so that i can traverse between the jbuttons with the keyboard i tried the jbutton1requestfocusinwindow code inside the constructor of the jpanel but still it did not work is there something that i am missing what more can i doeditthe project contains 3 java files and their code is as followsnewjframejava to change this template choose tools templates and open the template in the editor package sampleuiimport javaawtcontainerimport javaawttoolkitimport javaxswingjrootpaneimport javaxswinguimanager author administrator public class newjframe extends javaxswingjframe static container container creates new form newjframe public newjframe initcomponents rootpane getrootpane containergetcontentpane setsizetoolkitgetdefaulttoolkitgetscreensize setvisibletrue this method is called from within the constructor to initialize the form warning do not modify this code the content of this method is always regenerated by the form editor suppresswarningsunchecked editorfold defaultstatecollapsed descgenerated code private void initcomponents jmenuitem1 new javaxswingjmenuitem jpanel1 new javaxswingjpanel jlabel2 new javaxswingjlabel jlabel5 new javaxswingjlabel jlabel6 new javaxswingjlabel jlabel1 new javaxswingjlabel jlabel3 new javaxswingjlabel jpanel2 new javaxswingjpanel jlabel7 new javaxswingjlabel jlabel8 new javaxswingjlabel jlabel9 new javaxswingjlabel jdesktoppane1 new javaxswingjdesktoppane jmenuitem1settextjmenuitem1 setdefaultcloseoperationjavaxswingwindowconstantsexit on close settitlethis is the title jpanel1setbackgroundnew javaawtcolor204 204 204 jpanel1setlayoutnew javaawtborderlayout jlabel2setforegroundnew javaawtcolor255 255 255 jpanel1addjlabel2 javaawtborderlayoutpage start jlabel5setfontnew javaawtfonttahoma 1 14 noi18n jlabel5setforegroundnew javaawtcolor51 51 51 jlabel5settextdfgdfgdfg jpanel1addjlabel5 javaawtborderlayoutline start jlabel6setfontnew javaawtfonttahoma 1 14 noi18n jlabel6settextdfgdfgdfg jpanel1addjlabel6 javaawtborderlayoutline end jlabel1setfontnew javaawtfonttahoma 1 14 noi18n jlabel1sethorizontalalignmentjavaxswingswingconstantscenter jlabel1settextdfgdfgfdgfdgfdg jpanel1addjlabel1 javaawtborderlayoutcenter jlabel3sethorizontalalignmentjavaxswingswingconstantscenter jlabel3settextjlabel3 jpanel1addjlabel3 javaawtborderlayoutpage end getcontentpaneaddjpanel1 javaawtborderlayoutpage start jpanel2setbackgroundnew javaawtcolor204 204 204 jpanel2setlayoutnew javaawtborderlayout jlabel7settextjlabel7 jpanel2addjlabel7 javaawtborderlayoutline start jlabel8sethorizontalalignmentjavaxswingswingconstantstrailing jlabel8settextjlabel8 jpanel2addjlabel8 javaawtborderlayoutline end jlabel9sethorizontalalignmentjavaxswingswingconstantscenter jlabel9settextjlabel9 jpanel2addjlabel9 javaawtborderlayoutcenter getcontentpaneaddjpanel2 javaawtborderlayoutpage end jdesktoppane1addmouselistenernew javaawteventmouseadapter public void mouseclickedjavaawteventmouseevent evt jdesktoppane1mouseclickedevt getcontentpaneaddjdesktoppane1 javaawtborderlayoutcenter pack editorfold private void jdesktoppane1mouseclickedjavaawteventmouseevent evt todo add your handling code here containergetcontentpane setsizetoolkitgetdefaulttoolkitgetscreensize setvisibletrue callcompanyoption containersetvisiblefalse jdesktoppane1setvisiblefalse newjpanel pnew newjpanel psetbounds40 30 1200 786 containeraddp containersetvisibletrue param args the command line arguments public static void mainstring args set the nimbus look and feel editorfold defaultstatecollapsed desc look and feel setting code optional if nimbus introduced in java se 6 is not available stay with the default look and feel for details see try for javaxswinguimanagerlookandfeelinfo info javaxswinguimanagergetinstalledlookandfeels if nimbusequalsinfogetname javaxswinguimanagersetlookandfeelinfogetclassname break catch classnotfoundexception ex javautilloggingloggergetloggernewjframeclassgetnamelogjavautillogginglevelsevere null ex catch instantiationexception ex javautilloggingloggergetloggernewjframeclassgetnamelogjavautillogginglevelsevere null ex catch illegalaccessexception ex javautilloggingloggergetloggernewjframeclassgetnamelogjavautillogginglevelsevere null ex catch javaxswingunsupportedlookandfeelexception ex javautilloggingloggergetloggernewjframeclassgetnamelogjavautillogginglevelsevere null ex editorfold create and thisplay the form javaawteventqueueinvokelaternew runnable public void run new newjframesetvisibletrue variables declaration do not modify private javaxswingjdesktoppane jdesktoppane1private javaxswingjlabel jlabel1private javaxswingjlabel jlabel2private javaxswingjlabel jlabel3private javaxswingjlabel jlabel5private javaxswingjlabel jlabel6private javaxswingjlabel jlabel7private javaxswingjlabel jlabel8private javaxswingjlabel jlabel9private javaxswingjmenuitem jmenuitem1private javaxswingjpanel jpanel1private javaxswingjpanel jpanel2 end of variables declaration newjpaneljava to change this template choose tools templates and open the template in the editor package sampleuiimport javaawtcomponentimport javaawtcontainerimport javaawteventkeyevent author administrator public class newjpanel extends javaxswingjpanel creates new form newjpanel public newjpanel initcomponents this method is called from within the constructor to initialize the form warning do not modify this code the content of this method is always regenerated by the form editor suppresswarningsunchecked editorfold defaultstatecollapsed descgenerated codeprivate void initcomponents jpanel2 new javaxswingjpanel jpanel1 new javaxswingjpanel jbutton2 new javaxswingjbutton jxmonthview1 new orgjdesktopswingxcalendarjxmonthview setlayoutnew javaawtgridbaglayout javaxswinggrouplayout jpanel2layout new javaxswinggrouplayoutjpanel2 jpanel2setlayoutjpanel2layout jpanel2layoutsethorizontalgroup jpanel2layoutcreateparallelgroupjavaxswinggrouplayoutalignmentleading addgap0 0 shortmax value jpanel2layoutsetverticalgroup jpanel2layoutcreateparallelgroupjavaxswinggrouplayoutalignmentleading addgap0 0 shortmax value addjpanel2 new javaawtgridbagconstraints jbutton2settextok jbutton2setnextfocusablecomponentjbutton2 jbutton2addmouselistenernew javaawteventmouseadapter public void mouseclickedjavaawteventmouseevent evt jbutton2mouseclickedevt jbutton2addactionlistenernew javaawteventactionlistener public void actionperformedjavaawteventactionevent evt jbutton2actionperformedevt jbutton2addkeylistenernew javaawteventkeyadapter public void keypressedjavaawteventkeyevent evt jbutton2keypressedevt jxmonthview1addkeylistenernew javaawteventkeyadapter public void keypressedjavaawteventkeyevent evt jxmonthview1keypressedevt javaxswinggrouplayout jxmonthview1layout new javaxswinggrouplayoutjxmonthview1 jxmonthview1setlayoutjxmonthview1layout jxmonthview1layoutsethorizontalgroup jxmonthview1layoutcreateparallelgroupjavaxswinggrouplayoutalignmentleading addgap0 0 shortmax value jxmonthview1layoutsetverticalgroup jxmonthview1layoutcreateparallelgroupjavaxswinggrouplayoutalignmentleading addgap0 160 shortmax value javaxswinggrouplayout jpanel1layout new javaxswinggrouplayoutjpanel1 jpanel1setlayoutjpanel1layout jpanel1layoutsethorizontalgroup jpanel1layoutcreateparallelgroupjavaxswinggrouplayoutalignmentleading addgroupjpanel1layoutcreatesequentialgroup addgap64 64 64 addgroupjpanel1layoutcreateparallelgroupjavaxswinggrouplayoutalignmentleading false addcomponentjbutton2 javaxswinggrouplayoutdefault size 217 shortmax value addcomponentjxmonthview1 javaxswinggrouplayoutdefault size javaxswinggrouplayoutdefault size shortmax value addcontainergap56 shortmax value jpanel1layoutsetverticalgroup jpanel1layoutcreateparallelgroupjavaxswinggrouplayoutalignmentleading addgroupjpanel1layoutcreatesequentialgroup addgap19 19 19 addcomponentjxmonthview1 javaxswinggrouplayoutpreferred size javaxswinggrouplayoutdefault size javaxswinggrouplayoutpreferred size addpreferredgapjavaxswinglayoutstylecomponentplacementunrelated addcomponentjbutton2 javaxswinggrouplayoutpreferred size 31 javaxswinggrouplayoutpreferred size addcontainergap addjpanel1 new javaawtgridbagconstraints editorfoldprivate void jbutton2mouseclickedjavaawteventmouseevent evt jpanel1setvisiblefalse newjframecontainerremovenewjpanelthis newjpanel1 pnew newjpanel1 newjframecontaineraddp private void jbutton2keypressedjavaawteventkeyevent evt todo add your handling code here int keyevtgetkeycode ifkeykeyeventvk enter systemoutprintlnenter pressed jpanel1setvisiblefalse newjframecontainerremovenewjpanelthis newjpanel1 pnew newjpanel1 newjframecontaineraddp private void jxmonthview1keypressedjavaawteventkeyevent evt todo add your handling code here jbutton2requestfocus private void jbutton2actionperformedjavaawteventactionevent evt todo add your handling code here jpanel1setvisiblefalse newjframecontainerremovenewjpanelthis newjpanel1 pnew newjpanel1 newjframecontaineraddp variables declaration do not modifyprivate javaxswingjbutton jbutton2private javaxswingjpanel jpanel1private javaxswingjpanel jpanel2private orgjdesktopswingxcalendarjxmonthview jxmonthview1 end of variables declarationnewjpanel1java to change this template choose tools templates and open the template in the editor package sampleui import javaawtwindow import javaawteventkeyevent import javaxswingjrootpane author administrator public class newjpanel1 extends javaxswingjpanel new newjframe creates new form newjpanel1 public newjpanel1 initcomponents this method is called from within the constructor to initialize the form warning do not modify this code the content of this method is always regenerated by the form editor suppresswarningsunchecked editorfold defaultstatecollapsed descgenerated codeprivate void initcomponents jpanel1 new javaxswingjpanel jbutton1 new javaxswingjbutton jbutton2 new javaxswingjbutton jbutton3 new javaxswingjbutton jbutton4 new javaxswingjbutton jbutton5 new javaxswingjbutton setrequestfocusenabledfalse addkeylistenernew javaawteventkeyadapter public void keypressedjavaawteventkeyevent evt formkeypressedevt setlayoutnew javaawtgridbaglayout jpanel1setnextfocusablecomponentjbutton5 jpanel1addkeylistenernew javaawteventkeyadapter public void keypressedjavaawteventkeyevent evt jpanel1keypressedevt public void keyreleasedjavaawteventkeyevent evt jpanel1keyreleasedevt jbutton1settextback jbutton1addmouselistenernew javaawteventmouseadapter public void mouseclickedjavaawteventmouseevent evt jbutton1mouseclickedevt public void mouseenteredjavaawteventmouseevent evt jbutton1mouseenteredevt jbutton1addkeylistenernew javaawteventkeyadapter public void keypressedjavaawteventkeyevent evt jbutton1keypressedevt jbutton2settextjbutton2 jbutton2addkeylistenernew javaawteventkeyadapter public void keypressedjavaawteventkeyevent evt jbutton2keypressedevt jbutton3settextjbutton3 jbutton3addkeylistenernew javaawteventkeyadapter public void keypressedjavaawteventkeyevent evt jbutton3keypressedevt jbutton4settextjbutton4 jbutton4addkeylistenernew javaawteventkeyadapter public void keypressedjavaawteventkeyevent evt jbutton4keypressedevt jbutton5settextjbutton5 jbutton5setcursornew javaawtcursorjavaawtcursordefault cursor jbutton5setfocuscycleroottrue jbutton5setfocustraversalpolicyprovidertrue jbutton5setinheritspopupmenutrue jbutton5setnextfocusablecomponentjbutton4 jbutton5setverifyinputwhenfocustargetfalse jbutton5requestfocusinwindow jbutton5addactionlistenernew javaawteventactionlistener public void actionperformedjavaawteventactionevent evt jbutton5actionperformedevt jbutton5addkeylistenernew javaawteventkeyadapter public void keypressedjavaawteventkeyevent evt jbutton5keypressedevt javaxswinggrouplayout jpanel1layout new javaxswinggrouplayoutjpanel1 jpanel1setlayoutjpanel1layout jpanel1layoutsethorizontalgroup jpanel1layoutcreateparallelgroupjavaxswinggrouplayoutalignmentleading addgroupjavaxswinggrouplayoutalignmenttrailing jpanel1layoutcreatesequentialgroup addcontainergap41 shortmax value addgroupjpanel1layoutcreateparallelgroupjavaxswinggrouplayoutalignmentleading false addcomponentjbutton1 javaxswinggrouplayoutdefault size javaxswinggrouplayoutdefault size shortmax value addcomponentjbutton2 javaxswinggrouplayoutdefault size javaxswinggrouplayoutdefault size shortmax value addcomponentjbutton3 javaxswinggrouplayoutdefault size javaxswinggrouplayoutdefault size shortmax value addcomponentjbutton4 javaxswinggrouplayoutdefault size javaxswinggrouplayoutdefault size shortmax value addcomponentjbutton5 javaxswinggrouplayoutpreferred size 126 javaxswinggrouplayoutpreferred size addgap38 38 38 jpanel1layoutsetverticalgroup jpanel1layoutcreateparallelgroupjavaxswinggrouplayoutalignmentleading addgroupjpanel1layoutcreatesequentialgroup addcontainergap addcomponentjbutton5 addpreferredgapjavaxswinglayoutstylecomponentplacementunrelated addcomponentjbutton4 addpreferredgapjavaxswinglayoutstylecomponentplacementunrelated addcomponentjbutton3 addpreferredgapjavaxswinglayoutstylecomponentplacementunrelated addcomponentjbutton2 addpreferredgapjavaxswinglayoutstylecomponentplacementunrelated addcomponentjbutton1 addcontainergapjavaxswinggrouplayoutdefault size shortmax value jbutton5getaccessiblecontextsetaccessibleparentthis addjpanel1 new javaawtgridbagconstraints jbutton1requestfocusinwindow newjframegetrootpanesetdefaultbuttonjbutton1 jbutton1requestfocus editorfoldprivate void jbutton1mouseclickedjavaawteventmouseevent evt todo add your handling code here jpanel1setvisiblefalse newjframecontainerremovenewjpanel1this newjpanel pnew newjpanel newjframecontaineraddp private void jpanel1keypressedjavaawteventkeyevent evt todo add your handling code here systemoutprintlnkey pressed private void jbutton5keypressedjavaawteventkeyevent evt todo add your handling code here int keyevtgetkeycode ifkeykeyeventvk escape systemoutprintlnescape pressed jpanel1setvisiblefalse newjframecontainerremovenewjpanel1this newjpanel pnew newjpanel newjframecontaineraddp private void jbutton4keypressedjavaawteventkeyevent evt todo add your handling code here int keyevtgetkeycode ifkeykeyeventvk escape systemoutprintlnescape pressed jpanel1setvisiblefalse newjframecontainerremovenewjpanel1this newjpanel pnew newjpanel newjframecontaineraddp private void jbutton3keypressedjavaawteventkeyevent evt todo add your handling code here int keyevtgetkeycode ifkeykeyeventvk escape systemoutprintlnescape pressed jpanel1setvisiblefalse newjframecontainerremovenewjpanel1this newjpanel pnew newjpanel newjframecontaineraddp private void jbutton2keypressedjavaawteventkeyevent evt todo add your handling code here int keyevtgetkeycode ifkeykeyeventvk escape systemoutprintlnescape pressed jpanel1setvisiblefalse newjframecontainerremovenewjpanel1this newjpanel pnew newjpanel newjframecontaineraddp private void jbutton1keypressedjavaawteventkeyevent evt todo add your handling code here int keyevtgetkeycode ifkeykeyeventvk escapekeykeyeventvk enter jpanel1setvisiblefalse newjframecontainerremovenewjpanel1this newjpanel pnew newjpanel newjframecontaineraddp private void jbutton1mouseenteredjavaawteventmouseevent evt todo add your handling code here private void formkeypressedjavaawteventkeyevent evt todo add your handling code here systemoutprintlnkey pressed private void jpanel1keyreleasedjavaawteventkeyevent evt todo add your handling code here private void jbutton5actionperformedjavaawteventactionevent evt todo add your handling code here variables declaration do not modifyprivate javaxswingjbutton jbutton1private javaxswingjbutton jbutton2private javaxswingjbutton jbutton3private javaxswingjbutton jbutton4private javaxswingjbutton jbutton5public static javaxswingjpanel jpanel1 end of variables declarationthe reason to make the button focus able is to traverse between the buttons with arrow keys or the keyboard,['java'] +410558,strange issue with in java regex in order to reproduce the problem as stated in a recent question why does makes two matches and selects nothing in group 1 i tried various combination of and inside and outside the brackets and the result i got was not expectedi would have expected the output same as one explained in the accepted answer in that question and also in another duplicate question tagged under perl why doesnt the consume the entire string in this perl regex but it is not behaving the same wayto make it simple heres the code i tried string str inputstring patterns for string pattern patterns matcher matcher patterncompilepatternmatcherstr while matcherfind systemoutprint matchergroup1 matcherstart t systemoutprintlnand this is the output i got for all the 4 combination 0 5 for 0 5 for input 0 null 5 for input 0 for now what i cannot understand why in 1st and 2nd output i am not getting the entire string as first result for matcherfind i mean ideally in 1st case should first capture the entire string and then also capture the empty string at the end now although it is giving expected result for 2nd match it is not behaving well for 1st match and also in 2nd case i should not even get the 2nd match because i am having a quantifier outside the bracketmy expected output is input 0 5 for 1stinput 0 for 2ndalso in the 3rd output why i got null as 2nd match instead of empty string should not the 2nd match for first 3 combination be same4th output is as per expectation so no doubt in that,['java'] +410576,how to delete leading empty space in a sql database table using ms sql server managment studio i imported an excel sheet with countries into a database tableunfortunately all rows have some leading empty spaceso how can i delete these empty spaces,['sql'] +410588,using different cipher than default i need to connect to a server using only one cipher adhrc4md5i am looking for a generic solution which will enable me to check what cipher the server is using i am a provisioning server that acts as a client to many other application servers and need to connect and get data each time it can be a different serverthe flow i had so far wastcpclient tcpclient new tcpclientservername portsslstream sslstream new sslstreamtcpclientgetstream false null null encryptionpolicyrequireencryptionsslstreamauthenticateasclienthostnamei keep on crash in the authenticateasclient the reason is that one as is working only with the mentioned cipheri have verified this is the case with the sslscan tooli have tried to enter this cipher through the policy editor gpeditmsc in the command linebut again with no luckbasically i am looking for a way to use this cipher from code dynamicallyi have a working java codesslsocketsetneedclientauthtruestring list new string1list0 adhrc4md5sslsocketsetenabledciphersuiteslistany idea of c equivalent,['c#'] +410590,several string inputs for one variable is there any other way to shorten this conditionif operequalsadd operequalsadd operequalsaddition operequalsaddition operequalsi was just wondering if there is something i can do to shortcut this the user will type a string when prompted what kind of operation is to be performed in my simple calculator program our professor said our program should accept whether the user enters add or add you know in lowercase letters or not or is the only way i should do it,['java'] +410630,completely removing a django app that has dot notation i want to remove the djangocontribcomments app from a project i am working on i tried python managepy sqlclear djangocontribcommentson the shell but goterror app with label djangocontribcomments could not be found are you sure your installed apps setting is correcti have double checked my installed apps setting and indeed djangocontribcomments is presentany suggestions on how to get around this,['python'] +410640,what are webgls draw primitives i have been doing some graphics programming using webgl to draw objmeshs but it has not gone too well as it is not drawing it correctly i think thats because of the drawing primitives that i am using eg gldrawarraysgltriangle strip 0 vertexbuffernumitemsso can i ask what primitives do webgl allow is it the same as opengl i have been trying to use glquads as i thought it would allow it as opengl does so i am not too sure anymore,['javascript'] +410657,elasticsearch sorting by nested documents values i am facing a trouble in the use of elasticsearch for my java applicationi explain myself i have a mapping which is something like products properties id type long ignore malformed false locations properties category type long ignore malformed false subcategory type long ignore malformed false order type long ignore malformed false so as you can see i receive a list of products which are composed of locations in my model this locations are all the categories product it means that a product can be in 1 or more categories in each of this category the product has an order which is the order the client wants to show themfor instance a diamond product can have a first place in jewelry but the third place in woman my examples are not so logic so when i click on jewelry i want to show this products ordered by the field locationsorder in this specific categoryfor the moment when i search all the products on a specific category the response for elasticsearch that i receive is something like id5331880locationscategory5322606order1category5883712subcategorynullorder3category5322605subcategory6032961order2is it possible to sort this products by the element locationsorder for the specific category i am searching for for instance if i am querying the category 5322606 i want the order 1 for this product to be takenthank you very much beforehand regardsolivier,['java'] +410669,pythons xmlrpc extremely slow one second per call i built an xmlrpc server in python using simplexmlrpcserver according to the example in the python documentation i am calling it from a python client on the same machine the body of the server function executes very fast on its ownbut i find that xmlrpc client performance is excruciatingly slow taking one second per call using xmlrpcliba speedup technique i found on the web skipping the getfqdn resolution did not helpmy connect uri ishttplocalhost50080i am running python 27 x64 on windows 7 but it works the same for 32bit python 27,['python'] +410682,convert stdchronotime point to unix timestamp how can i get an stdchronoduration since a fixed date i need this to convert a stdchronotime point to an unix timestamp insert code into xauto unix epoch start xauto time stdchronosystem clocknowauto delta time unix epoc startauto timestamp stdchronoduration caststdchronomillisecondsdeltacounti know time point has a method time since epoch but it is not guaranteed that this is the same as the unix epoch 0 utc on 1 january 1970,['c++'] +410757,what is the default layout background i got a webview that load an html file with a text the problem is that the color inside the html and outside is not the same here is a screenshotthe html file ishtml dirrtlhead titleabouttitle meta contenttexthtml charsetutf8 httpequivcontenttype body bgcolorf pthis is a testp psee the problemp plast testp bodyhtmlif i remove the bgcolorf it is stay the same colorthanks,"['android', 'html']" +410768,instruct sencha sdk tools to bundle other js files specified in appjson my appjson file of a sencha touch 2 application containjs path sdksenchatouchjs path jsmootools125corejs i want these files to be bundled too path jsmootools1251morejs path jssoundmanager2nodebugjsminjs and there are more path appjs bundle true indicates that all class dependencies are concatenated into this file when build update delta now i see when i invoke sencha app build production it compiles all the sencha classes into a giant appjs file but all my other classes are just compressed to build directory they are not concatenated how can i include them in appjs faqyour json file is properly written right a yes appjson is written without any syntax error the project builds successfully on invoking sencha app build production,['javascript'] +410769,embedding mono on ios i want to embed mono into my ios application i do not want to use monotouch i want to embed mono manually like this monoi have have done this successfully on windows using the above guide and various online examples heres a good windows onehowever i am having trouble getting started on ios i know it can be done companies like unity3d use it to power their game engine tech i cannot work out how to compile and link mono for ios nor can i find any good instructions to do so i have not found any help using search engines they exclusively seem to turn up articles about monotouch xamarins own commercial wrapper around embedding mono into iosheres a few more noteworthy linksis there somewhere i can get precompiled libraries and headers for mono for ios so in my c code i can simply link and include could someone provide and example of how to compile mono for ios arm cpusmonotouch provides a great wrapper around all of the ios objective c apis however you do not necessarily need all of that as i understand it should be possible to compile and then embed mono yourself and then use pinvoke to call the few native functions you will needany help would be greatly appreciated ty,['ios'] +410841,create file in a threadsafe manner i have an array of filenames and each process need to create and write only to a single filethis is what i came toforeach filenames as vmidfile if file existsvmidfile a continue fp fopenvmidfile c b if flockfp lock ex lock nb c continue if filesizevmidfile d write to the file flockfp lock un fclosefp break flockfp lock un fclosefp ebut i do not like that i am relying on the filesizeany proposals to do it in another better wayupd added the labels to thiscuss easilyupd 2 i am using filesize because i do not see any other reliable way to check if the current thread created the file thus it is empty yetupd 3 the solution should be condition race free,['php'] +410868,wtforms creating a custom widget the wtforms documentation is woefully inadequate they do not even show you one single example of a custom widget that is not derived from another widget alreadyi am trying to make a button type that is not input in htmlsubmit inlinebuttonnamesubmit typesubmit titlesave this page textwithinspansavefrom flaskextwtf import required length equalto field textinput html paramsfrom flask import markupclass inlinebuttonwidgetobject text html params staticmethodhtml params def init self input typesubmit kwargs selfinput type input type def call self field kwargs kwargssetdefaultid fieldid kwargssetdefaulttype selfinput type if value not in kwargs kwargsvalue field value return markupbutton typesubmit sspansspanbutton selfhtml paramsnamefieldname kwargs kwargstextwithinspanclass inlinebuttonfield widget inlinebuttonwidget def init self label kwargs selfwidget inlinebuttonwidgetsubmit label def call self kwargs return selfwidgetself kwargs def valueself if selfdata return u joinselfdata else return uclass signupformform name textfieldname lengthmin1 max200 submit inlinebuttonnamesubmit typesubmit titlesave this page textwithinspansavei should not even need a field derived object but it does not thisplay when you only use widget by itselfand when you use the field object then it gives you all sorts of invalid parameter errorseven delving into the wtforms source code makes it difficult to understand why it would not pass kwargs from form to widget update ok after i submit the question i basically figured out a workable solutionclass inlinebuttonwidgetobject html params staticmethodhtml params def init self input typesubmit text selfinput type input type selftext text def call self field kwargs kwargssetdefaultid fieldid kwargssetdefaulttype selfinput type if value not in kwargs kwargsvalue field value return markupbutton typesubmit sspansspanbutton selfhtml paramsnamefieldname kwargs fieldtextclass inlinebuttonfield widget inlinebuttonwidget def init self labelnone validatorsnone textsave kwargs superinlinebutton self init label validators kwargs selftext text def valueself if selfdata return ujoinselfdata else return uclass signupformform name textfieldname lengthmin1 max200 submit inlinebuttonsubmit textsave descriptionsave this,['python'] +410903,erasing elements in a multimap while iterating i am writing a nodal path finding algorithm i need to run through a multimap and delete elements out of it under certain conditions but keep iterating through the multimap below is my code so far it seems to work most of the time but occasionally i get an error when doing nct it is it safe to erase the iterator pointer from the table before incrementing the iteratorstdlistsinksourcenodeconniterator itstdmultimapsysnode sysnodeiterator nct itsysnode found node nullnct it node conn tablebeginwhilenct it node conn tableend find the node in the ever shrinking node connection table ifnct itfirst parent node found node nct itsecond remove the table entry if we have found a node iffound node search for the node in the expanded list if it is not found add it bool found the node false forit m sink source nodes begin it m sink source nodes end it ifitsink source sink source itnode found node found the node true iffound the node recursion listpush backfound node recursion listunique sinksourcenodeconn ssnc ssncnode found node ssncsink source sink source m sink source nodes push backssnc iffound nodegetpotential sink sourcegetpotential found nodesetpotentialsink sourcegetpotential found node null unset the found node node conn tableerasenct it nct it else nct it,['c++'] +410931,undefined local variable or method json in jbuilder when i try get all categories index action there is an errorundefined local variable or method jsonbut in show action everything fine all files has jbuilder extensionhere is controller codedef index categories categoryallend get categories1 get categories1jsondef show category categoryfindparamsidendstack traceappviewscategoriesindexjsonbuilder1in app views categories index json builder 502133872307116590 70140532925300 actionpack 3211 libaction viewtemplaterb145inblock in render activesupport 3211 libactive supportnotificationsrb125in instrument actionpack 3211 libaction viewtemplaterb143inrender,['ruby-on-rails'] +410932,dumping registers in stack for conservative stack scanning i am writing a noninvasive conservative gc in c and i am having some concerns about the correctness of its stack scanning phasespecifically with no compiler optimizations enabled it works fine because every local variable which points to an object is predictably allocated on the stack in o3 the gc misses some valid references which i believe is due to the fact that the compiler opts to use registers instead of the stack which the gc scans for some variables and function argument passing and the gc is not yet programmed to handle that if you suspect that this still should not be happening and that i am misreading the source of the problem please let me knowapart from some rudimentary requirements having to use a gc malloc instead of malloc for gc objects not pointing to the gc heap from the nongc heap and of course not explicitly calling free the gc should not have any more requirements from the client code or the compiler therefore requiring any additional special patterns from the client code is not an option similarly forcing programs that use this gc to be compiled with special compiler flags that suppress stack optimizations should be a last resort option at best with these two out of the way heres the buildup to my questioni am trying to find a way to make the gc handle the o3 case with the stack optimizations seamlessly heres my train of thoughts assumptions more preciselyno matter how far gcc or any valid compiler goes with the optimizations it wouldnt go so far that it would compromise the correctness of the program if 1 holds i believe that at least in practical implementations of c if a reachable allocated as local at any call level variable is going to remain accessible at all it has to be either on the stack or in the current register set but not really anywhere else if 2 holds it should mean that simply dumping all the registers to the stack when the gc cycle starts would guarantee that a subsequent stack scanning would now find the previously missed references as welladditionally if 1 and 2 hold then if the compiler lets any variables be overwritten in the case of registerbased ones mostly it means that it has performed some level of code analysis and it has proved that that variable is not used anywhere else in that function so in that sense if we do not see a variable in the stack or in the register dump even though it is still in scope theoretically this should not be a cause for alarm for me because the compiler has simply sort of helped out the gc by getting rid of a dead referencequestion 1 are all 4 of my assumptions correctquestion 2 what is the most portable way to force a register dump i have found some sources claiming that a simple setjmp call will have this effect is this correct,['c'] +411007,python opencv solvepnp yields wrong translation vector i am attempting to calibrate and find the location and rotation of a single virtual camera in blender 3d using homography i am using blender so that i can double check my results before i move on to the real world where that is more difficult i rendered ten pictures of a chess board in various locations and rotations in the view of my stationary camera with opencvs python i used cv2calibratecamera to find the intrinsic matrix from the detected corners of the chess board in the ten images and then used that in cv2solvepnp to find the extrinsic parameterstranslation and rotation however though the estimated parameters were close to the actual ones there is something fishy going on my initial estimation of the translation was 01120548100490256813892491 the actual location was 00807105 pretty close right but when i moved and rotated the camera slightly and rerendered the images the estimated translation became farther off estimated 015933154013367286934058867 actual 17918151073976597 the z value is close but the x and the y are not i am utterly confused if anybody can help me sort through this i would be highly grateful here is the code it is based off of the python2 calibrate example supplied with opencvimports left outusage usage calibpy save filename debug output path square size image mask args img mask getoptgetoptsysargv1 save debug square sizeargs dictargstry img mask img mask0except img mask cpp0pngimg names globimg maskdebug dir argsgetdebugsquare size floatargsgetsquare size 10pattern size 5 8pattern points npzeros npprodpattern size 3 npfloat32 pattern points2 npindicespattern sizetreshape1 2pattern points square sizeobj points img points h w 0 0count 0for fn in img names print processing s fn img cv2imreadfn 0 h w imgshape2 found corners cv2findchessboardcornersimg pattern size if found if count 0 corners first is a list of the image points for just the first image this is the image i know the object points for and use in solvepnp corners first for val in corners corners firstappendval0 np corners first npasarraycorners firstnpfloat64 count1 term cv2term criteria eps cv2term criteria count 30 01 cv2cornersubpiximg corners 5 5 1 1 term if debug dir vis cv2cvtcolorimg cv2color gray2bgr cv2drawchessboardcornersvis pattern size corners found path name ext splitfnfn cv2imwritess chessbmp debug dir name vis if not found print chessboard not found continue img pointsappendcornersreshape1 2 obj pointsappendpattern points print okrms camera matrix thist coefs rvecs tvecs cv2calibratecameraobj points img points w hprint rms rmsprint camera matrixn camera matrixprint thistortion coefficients thist coefsravel cv2destroyallwindows np xyz nparrayxyznpfloat64t xyz list is from file not shown here for brevitycamera matrix2 npasarraycamera matrixnpfloat64np thist coefs npasarraythist coefsnpfloat64 foundrvecs newtvecs new cv2solvepnpnp xyz np corners firstcamera matrix2np thist coefsnp rodrigues npasarrayrvecs newnpfloat64print np rodriguesshaperot matrix cv2rodriguesnp rodrigues0def rot matrix to eulerr y rot asinr20 x rot acosr22cosy rot z rot acosr00cosy rot y rot angle y rot 180pi x rot angle x rot 180pi z rot angle z rot 180pi return x rot angley rot anglez rot angleprint euler rotation rot matrix to eulerrot matrixprint translation matrix tvecs newthank you so much,['python'] +411018,how to thisplay a number with always 2 decimal points using bigdecimal i am using bigdecimal to get some price values requirement is something like this what ever the value we fetch from database the thisplayed valued should have 2 decimal pointsegfetched value is 1 should be thisplayed as 100 fetched value is 17823 should be thisplayed as 178i am using setscale2 bigdecimalround half up but still some places if the data from db is a whole number then the same is being thisplayed i mean if the value is 0 from db its thisplayed as 0 only i want that to be thisplayed as 0thanks,['java'] +411041,best approach to wrap an existing java library in ruby jruby i am looking to putting a ruby jruby wrapper over a medium sized java library and am looking for advice and articles on best practices for everything from packaging to strategyi found a relatively dated 2009 thiscussion on this topic here i am looking to use the newest version of jruby,['java'] +411046,how to save complete webpage not just basic html using python i am using following code to save webpage using pythonimport urllibimport sysfrom bs4 import beautifulsoupurl f urlliburlretrieveurltesthtmlproblem this code saves html as basic html without javascripts images etc i want to save webpage as complete like we have option in browserupdatei am using following code now to save all the jsimagescss files of webapge so that it can be saved as complete webpage but still my output html is getting saved like basic htmlimport pycurlimport stringioc pycurlcurlcsetoptpycurlurl b stringiostringiocsetoptpycurlwritefunction bwritecsetoptpycurlfollowlocation 1csetoptpycurlmaxredirs 5cperformhtml bgetvalueprint htmlfh openfilehtml wfhwritehtmlfhclose,"['python', 'html']" +411084,is stringreplace implementation really efficient i used to think that stringreplace is faster than stringreplaceall because the latter uses pattern regex and the former does not but in fact there is no significant difference either in performance or implementation this is itpublic string replacecharsequence target charsequence replacement return patterncompiletargettostring patternliteralmatcher thisreplaceallmatcherquotereplacementreplacementtostringwhats the need to use pattern here i wrote a nonregex replace versionstatic string replacestring s string target string replacement stringbuilder sb new stringbuilders for int i 0 i sbindexoftarget i 1 i replacementlength sbreplacei i targetlength replacement return sbtostringand compared performance public static void mainstring args throws exception string s1 12233211 for long t0 systemcurrenttimemillis for int i 0 i 10 i string s2 s1replace11 x string s2 replaces1 11 22 systemoutprintlnsystemcurrenttimemillis t0 benchmarks my version 400ms jdk version 1700ms is my test wrong or is stringreplace really inefficient,['java'] +411086,recursive query in sql server i have a table with following structuretable name matchesthat basically stores which product is matching which product i need to process this tableand store in a groups table like belowtable name groupsgroup id stores the min product id of the product ids that form a group to give an example let us sayif a is matching b and b is matching c then three rows should go to group table in format a a a b a ci have tried looking into corelated subqueries and cte but not getting this to implement i need to do this all in sql thanks for the help,['sql'] +411092,ajax form submit not loading newly submitted data i updated jquery so i could play with the new jquery mobile ui 13 and for some reason my form no longer update page any more it worked previously but it was not through ajax it simply submitted the form without ajax i would however like ajax to just fetch the new data and append it to the div instead of reloading the whole page again when the popup closesi use a popup module for the form and on submission it should append the new information to content ulthe js load json data and events script typetextjavascript jquerynew ravelivesubmitfunction event ajax url httpwhoopsgoodtimes type post datatype json data new raveserialize success function data for var id in data jqueryhtmldataid return false documentreadyfunction getjsonhttpwhoopsgoodtimes function goodtimes eachgoodtimes function goodtime var output lia hrefthisgoodtimeid h3 thisgoodtimetitle h3 p thisgoodtimepost p p classuiliasidestrong thisgoodtimecreated at strongp ali content ulappendoutputlistviewrefresh scriptthe form new item popup div datarolepopup classuicontentdataoverlaythemea datapositiontowindow idadd form idnew rave label forgoodtime titletitlelabel input typetext namegoodtimetitle idgoodtime title label forgoodtime postravelabel div datarolefieldcontain textarea namegoodtimepost idgoodtime posttextarea div input typesubmit valuesubmit formdivand the content divdiv idcontent datarolecontent ul datarolelistview datathemed datadividerthemeduldiv content,"['javascript', 'jquery']" +411121,correct way to use scipysignalspectrallombscargle i am refering to the following post using scipysignalspectrallombscargle for period thiscoveryi realize the answer given correct for certain casefrequency for sinx which is 12 pi imports the numerical array and scientific computing packagesimport numpy as npimport scipy as spfrom scipysignal import spectral generates 100 evenly spaced points between 1 and 10time nplinspace1 10 100 computes the sine value of each of those pointsmags npsintime scales the sine values so that the mean is 0 and the variance is 1 the documentation specifies that this must be donescaled mags magsmagsmeanmagsstd generates 10 frequencies between 001 and 1freqs nplinspace001 1 10 computes the lomb scargle periodogram of the time and scaled magnitudes using each frequency as a guessperiodogram spectrallombscargletime scaled mags freqs returns the inverse of the frequence ie the period of the largest periodogram valueprint 12pi str12nppiprint frequency strfreqsnpargmaxperiodogram 20 nppithe following is printed is fine i guess the reason we divide the lombscargle result with 2pi is that we need to convert radian to frequency f radian 2pi12pi 0159154943092frequency 0159154943092however thing seems goes wrong for the following casefrequency for sin2x which is 1pi imports the numerical array and scientific computing packagesimport numpy as npimport scipy as spfrom scipysignal import spectral generates 100 evenly spaced points between 1 and 10time nplinspace1 10 100 computes the sine value of each of those pointsmags npsin2 time scales the sine values so that the mean is 0 and the variance is 1 the documentation specifies that this must be donescaled mags magsmagsmeanmagsstd generates 10 frequencies between 001 and 1freqs nplinspace001 1 10 computes the lomb scargle periodogram of the time and scaled magnitudes using each frequency as a guessperiodogram spectrallombscargletime scaled mags freqs returns the inverse of the frequence ie the period of the largest periodogram valueprint 1pi str1nppiprint frequency strfreqsnpargmaxperiodogram 20 nppithe following is being printed1pi 0318309886184frequency 00780862900972seem incorrect any step that i had missed out,['python'] +411123,is it possible to save the python interpreters state to a file what if when a user is using my python application and the application crashes the state of the application can be saved to a file and sent to me the developer i open the python interpreter and start debugging from the point where the user crashedto clarify when i am debugging an application and it raises an unhandled exception i can debug the application postmortem getting access to all the local variables and their values which is crucial to quickly fixing bugs when an users application crashes though i only receive the stack trace for when the error occurred which is helpful but not nearly as much as debugging interactively would beso is it possible to save the state of a python application to a file close the interpreter then resume the execution from that file at a later stage,['python'] +411162,numbers of an ordered list turn into 0 while clicking trough jquery tabs i have a page with jquery tabs on it in those tabs is an ordered list this is my html codediv idtabs ul lia hreftabs1nunc tinciduntali lia hreftabs2proin dolorali lia hreftabs3aenean laciniaali ul div idtabs1 ol start50 libibendum elitli livehiculali liamet bibendum ultriciesli ol div div idtabs2 ol lisollicitudin cras vehiculali livulputate euismodli liridiculus vehicula pharetra nullamli ol div div idtabs3 ol liullamcorper parturientli litristique mollis venenatis vehiculali livulputate bibendumli ol divdivand this is my javascriptfunction tabs tabssee when i view this in ie9 and i click from the first tab to the second tab and then back to the first tab again the numbers are all changed to 0 does anyone know what i am doing wrong or how to solve this problem,['jquery'] +411175,x 1 vs x 0 is there a performance difference i have heard a teacher drop this once and it has been bugging me ever since let us say we want to check if the integer x is bigger than or equal to 0 there are two ways to check thisif x 1 do stuffandif x 0 do stuff according to this teacher would be slightly faster then in this case it was java but according to him this also applied for c c and other languages is there any truth to this statement,"['java', 'c++']" +411201,sql server datetime accept null i have tried to make my code as compact as possibleusing microsoft sql server net 20i have a date field in my database which accepts null valuesleaseexpirydatetime nulli grab the value of the the textbox and convert it to datetime datetime leaseexpiry converttodatetimetbleaseexpirytextinsert recordleaseexpirythe problem i am having is if the form is submitted and the textbox is empty i get this error backstring was not recognized as a valid datetimehow do i set my code up so that if the textbox is empty the row is created in the database with nulli have tried initializing my variable to null but get an error in visual studiodatetime leaseexpiry nullcannot convert null to systemdatetime because it is a nonnullable value typeheres the data access layer if that helpspublic string insert recorddatetime leaseexpiry connect to the database and insert a new record string cnn configurationmanagerconnectionstringsconameconnectionstring using sqlconnection connection new sqlconnectioncnn string sql stringempty sql insert into dbname dbo tblallproperties leaseexpiry values leaseexpiry using sqlcommand command new sqlcommandsql connection commandparametersaddleaseexpiry sqldbtypedatetime commandparametersleaseexpiryvalue leaseexpiry try connectionopen commandexecutenonquery return success catch exception ex return exmessage thank you,['c#'] +411227,close a messagebox after several seconds i have a windows forms application vs2010 c where i thisplay a messagebox for show a message i have an okay button but if they walk away i want to timeout and close the message box after lets say 5 seconds automatically close the message boxthere are custom messagebox that inherited from form or another reporter forms but it would be interesting not necessary a formany suggestions or samples about itupdated for wpfautomatically close messagebox in ccustom messagebox using form inheritscrollable messageboxa scrollable messagebox in cexception reportergood crash reporting library in csolutionmaybe i think the following answers are good solution without use a form,['c#'] +411251,why does the linq cast helper not work with the implicit cast operator please read to the end before deciding of voting as duplicatei have a type that implements an implicit cast operator to another typeclass a private b b public static implicit operator ba a return ab class bnow implicit and explicit casting work just fine b b ab b2 baso how come linqs cast does not a aa new avar bb aacastb throws invalidcastexceptionlooking at the source code for cast there is not much magic going on a few special cases if the parameter really is a ienumerableb and thenforeach object obj in source yield return tobj this looks quite similar to the above b b2 baso why does my explicit cast work but not the one inside cast does the compiler sugarup my explicit cast ps i saw this question but i do not think its answers really explain whats going on,['c#'] +411261,angular js does not allow preventdefault or return false to work on form submission i have a form i would like to deliver via ajax form classforminline ngpristine ngsubmitsendform methodpost actionsign up acceptcharsetutf8scopesendform e epreventdefault consolelog sendform return false the consolelog appears and immediately it delivers the formit ignores both the epreventdefault and the return falseangularjs reminds me of the honey badger it just does not care,['jquery'] +411321,how do i get the file name from a string containing the absolute file path string variable contains a file name chelloanotherfolderthe file namepdf how do i only get the file name the file namepdf as a stringi planned to split the string but that is not the optimal solution,['java'] +411354,can i set a global header for all ajax requests this does not seem to be working ajaxsetup headers accept applicationvwebsitejsonversion1 authorization token tokenfuhclyy46 i would have thought it would if i add these filters specifically to my ajax call then they do work i would like to do this globally for all ajax calls,"['javascript', 'jquery']" +411365,does html 5s blobbuilder still work in google chrome based in this article i created a form to upload files initially works fine in chrome but now is not workin more in ff work finei made some debugs and this line var bb new windowmozblobbuilder windowwebkitblobbuilder windowblobbuilderseems stop working in chromebrowsering around i find some info about blobbuilder function that is not supported more in chromecan help me,['javascript'] +411386,convert an array to hash where keys are the indices i am transforming an array into a hash where the keys are the indices and values are the elements at that indexhere is how i have done it initial stuffarr one two three four fivex iterate and build hash as neededarreach with index v i xi v result 0one 1two 2three 3four 4fiveis there a better in any sense of the word better way to do it,['ruby'] +411403,how can i program a rotating circular animation such as this one picture attached android i am developing an app just built its logical part now i want to design this app like in famous timer appsfor examplesthe thing i want is the outer circle that fills with every trigger of some event or with increment of number i actually do not know that is it animation part like to be built in flash or what or just possible by coding in android itself using its inbuilt properties and featuresso anybody if tell explain me what tools are used or any reference tutorial that can explain things from bottom i really do not know any thing of designing any code for this,['android'] +411405,whats the pythonpath when there is no pythonpath i need to add a new directory location to my pythonpath but the problem is i am on a clean newlyinstalled system linux where no pythonpath has yet been defined i have read about and used pythonpath and i thought i understood it quite well but i do not know whats happening when no pythonpath yet exists i cannot append to something that does not exist but i want all important libraries currently found to still work so being cautious from within python i did print strsyspath to get all the standard values then i defined an envvariable for pythonpath including all the nodes i had just found plus my new directory but wow did a lot of stuff stop working python is so messed up with the new envvariable that i had to remove it at which point everything worked again with the bad pythonpath the system was so confused it could not even find an error message to thisplay when an incorrect command was typed in at the promptmy problem is not something simple like a missing colon or using semicolons when i should use colons i checked also my new directory does not cause the problem because even without the new node the problems still occur so can anyone explain why this approach does not work below i provide extra details as requested but one need not read any futher i think the problem is fixed the explanation that the nodes listed in pythonpath do not override all standard nodes but rather become new additional entries prepended i believe so one can control what comes first was the key starting from scratch defining no pythonhome or pythonpath results in this from within pythonprint joinsyspath usrlibpython27usrlibpython27platlinux2usrlibpython27libtkusrlibpython27liboldusrlibpython27libdynloadusrlocallibpython27thistpackagesusrlibpython27thistpackagesusrlibpython27thistpackagespilusrlibpython27thistpackagesgst010usrlibpython27thistpackagesgtk20usrlibpython27thistpackagesubuntussoclient using this as a pythonpath ie defining an envvariable before invoking python results in a very poorly functioning command prompt even without explicitly using python for example export pythonpathusrlibpython27usrlibpython27platlinux2usrlibpython27libtkusrlibpython27liboldusrlibpython27libdynloadusrlocallibpython27thistpackagesusrlibpython27thistpackagesusrlibpython27thistpackagespilusrlibpython27thistpackagesgst010usrlibpython27thistpackagesgtk20usrlibpython27thistpackagesubuntussoclient echo pythonpath usrlibpython27usrlibpython27platlinux2usrlibpython27libtkusrlibpython27liboldusrlibpython27libdynloadusrlocallibpython27thistpackagesusrlibpython27thistpackagesusrlibpython27thistpackagespilusrlibpython27thistpackagesgst010usrlibpython27thistpackagesgtk20usrlibpython27thistpackagesubuntussoclient intentionalbadcommand fatal python error py initialize unable to get the locale encoding file usrlibpython27encodings init py line 123 raise codecregistryerror syntaxerror invalid syntax abortedthe mistake was thinking that pythonpath needs to contain the whole universe of everything needed yes i did rtfm before posting but i guess i missed the significance of the beginning word augment so taking the advice that not everything needs to be explicitly specified that one can just specify the extra additions one wants i tried export pythonpathusrlibpython27thistpackagespostgresqlpkg echo pythonpath usrlibpython27thistpackagespostgresqlpkg intentionalbadcommand intentionalbadcommand command not foundso it seems to be working though i have not yet tried to use the postgresql package mentioned above still it is a little mysterious why prepending an abundance of unnecessary nodes to the pythonpath would make things break as badly as it did especially since i got the entries from what should be a reliable source syspath but anyway it is probably solved so thanks,['python'] +411425,how to make jnih be found in ubuntu 1204 i have jdk7 from sunoracle installed when locate jnih it prints multiple locations usrlibjvmjava6openjdkamd64includejnihusrlibjvmjdk170 07includejnihin the header file generated by jdk there is include jnih and currently it complains fatal error jnih no such file or directoryin my makefile there is no specification of locations where jnih is and i am asking if possible to configure certain system parameter to make path of jnih say usrlibjvmjdk170 07includejnih to be known when being compiled,['java'] +411537,can you suggest a good minhash implementation i am trying to look for a minhash open source implementation which i can leverage for my workthe functionality i need is very simple given a set as input the implementation should return its minhash a python or c implementation would be preferred just in case i need to hack it to work for meany pointers would be of great helpregards,['python'] +411541,flute hole calculation algorithm i am looking to write blow hole flute calculation program i can program javascript and want to make program public and freebut i look for algorithm to do that given pipe diameter and length i want to calculate where the holes should be drilled for desired notesi did my best on wikipedia and google for flute programs and math and physics behind it but this all seems so complicated those guys cannot speak simple words over two years i spent about 10 evenings trying to find this algorithm please allow this questioni believe all i need is one to ten lines of code not a 10 lines frameworkone solution that i found was thisif diameterlength30 printcdefgh171051087 from the open end of the pipebut this one is too fixed,['javascript'] +411560,legend not showing up in matplotlib stacked area plot i am creating a stacked linearea plot using pltfill between method of the pyplot and after trying so many things i am still not able to figure why it is not thisplaying any legend or labels even when i provide them in the code here is the codeimport matplotlibpyplot as pltimport numpya1 label record a1a2 label record a2a1 numpylinspace010040a2 numpylinspace3010040x numpyarange0 lena1 1pltfill betweenx 0 a1 facecolorgreenpltfill betweenx a1 a2 facecolorredplttitlesome titlepltgridonpltlegenda1 label a2 labelpltshowhere is the image generated note that the legend shows empty box instead of labels help,['python'] +411596,ie floating point vs custom float performance i am working on a processor without a floating point unit so i have to use fixed or a custom floating point type for a user interfacewhat does the performance on say a multiply look like for these three types1 ie float 322 custom 32 bit float class with a 16 bit signed value and a signed 16 bit exponent3 32bit fixed decimal i want something that will scale to a processor with a floating point unit as well will the custom float be competitive performancewise with an ie float i have heard the performance of ie floats are terrible on processors without fpus is that because it has to do crazy andoring due to the 24bit value not being native that is will the custom float class mitigate that performance problemany help would be greatly appreciated,['c++'] +411610,what do you mean by hashable in python i tried searching internet but could not find the meaning of hashablewhen they say objects are hashable or hashable objects what does it mean,['python'] +411612,executors how to synchronously wait until all tasks have finished if tasks are created recursively my question is strongly related to this one hereas was posted there i would like the main thread to wait until the work queue is empty and all tasks have finished the problem in my situation is however that each task may recursively cause new tasks to be submitted for processing this makes it a little awkward to collect all of those taskss futuresour current solution uses a busywait loop to await termination do wait until we are done the processing try threadsleep200 catch interruptedexception e throw new runtimeexceptione while executorgetqueueisempty numtaskslongvalue executorgetcompletedtaskcountnumtasks is a value that is increased as every new task is createdthis works but i think it is not very nice due to the busy waiting i was wondering whether there is a good way to make the main thread wait synchronously until being explicitly woken up,['java'] +411640,installing cordova plugins with phonegap no cordovaplist i am trying to install a plugin for my application which is working fine compiled in xcode using cordova and the phonegap frameworkon the instructions of the plugin i am supposed to add a key to the cordovaplist file but i cannot find it in my hierarchy here is a screenshot of the directories in my xcode projectwhat is the fix for this issue,['ios'] +411646,applying kiss fft on audio samples and getting nan output the title explains my problemwhat i am trying to do is quite simpleload mp3 track via libmpg123read samplesapply kiss fft on the samples what i have tried so farinline float scalekiss fft scalar val int g 0 return val 0 val1327680f val1327670fvoid main mpg123 handle m null int channels 0 encoding 0 long rate 0 int err mpg123 ok err mpg123 init m mpg123 newnull err mpg123 openm laudioioaudioanalysissampleszeromp3 mpg123 getformatm rate channels encoding err mpg123 format nonem err mpg123 formatm rate channels encoding get 2048 samples const int time 2048 16bit integer encoded in bytes hence x2 size unsigned char buffer new unsigned chartime2 size t done 0 err mpg123 readm buffer time2 done short samples new shortdone2 int index 0 iterate 2 bytes at a time for int i 0 i done i 2 unsigned char first bufferi unsigned char second bufferi 1 samplesindex first second 8 array to store the calculated data int speclen time 2 1 float output new floatspeclen kiss fftr cfg config kiss fft cpx spectrum config kiss fftr alloctime 0 null null spectrum kiss fft cpx mallocsizeofkiss fft cpx time right here kiss fftrconfig kiss fft scalar samples spectrum for int i 0 i speclen i float re scalespectrumir time float im scalespectrumii time outputi sqrtfrere imim returnthe problem occurs at this line kiss fftrconfig kiss fft scalar samples spectrumwhere samples contains the audio samples 16 bit and spectrum is suppose to hold the output dataafter the function completes here is whats happening in the debugger windowcan someone give me a simple example of how to apply kiss fft functions on audio 16 bit encoded samples,['c++'] +411679,sherlock actionbar rtl android 42 introduced the support for right to left action bar is there a way to configure the sherlock action bar to be in rtl modenote that the current sherlock actionbar version is 42 but i could not find anything related to the rtl support,['android'] +411727,angularjs error when thisplaying images i am filling in img src tags using angularjs so urls in my html areimg srcprofileimagewhen i load the page the image shows but the get errors in the javascript console tooget profileimage 404 not found so the browser is trying to fetch the image before angular has interpolated the value right then when angular sets the value the browser fetches again and this time shows the imagehow can i either get angular to do this earlier or get the browser to wait i do not like having the error exposed,['javascript'] +411729,increasing the android sdk emulator speed how do i increase the speed of the virtual device emulator in the eclipse sdk for android app developmenti have been searching all over the internet to find out how to speed this thing up but i cannot seem to find a fix that actually works for meanother problem i am having is that i cannot get the ram above 1024mbthanks for all the help i have now fixed the speed for anyone with the same problem make sure this box is checkedhowever i still cannot get my ram above 1024 mb whats the fix for that,['android'] +411770,pythons function readlinesn behavior i have read the documentation but what does readlinesn do by readlinesn i mean readlines3 or any other numberwhen i run readlines3 it returns same thing as readlines,['python'] +411796,hibernate orghibernatelazyinitializationexception could not initialize proxy no session have following query to the database session session employeesdaogetsessionfactorygetcurrentsession listemployee employees new arraylistemployee try sessionbegintransaction string hqlquery from employee emp left join fetch empemployeesoffices employeesoffice left join fetch employeesofficeoffice employeesofficeoffice left join fetch employeesofficeofficecompany left join fetch empaddress empaddress left join fetch empaddresscity empaddresscity left join fetch empaddresscitycountry query empquery sessioncreatequeryhqlquery empquerysetmaxresultsmaxresult employees listemployee empquerylist sessiongettransactioncommit catch hibernateexception e sessiongettransactionrollback eprintstacktrace while fetching employeeaddrestreet employeeaddresshousenumber or employeeaddresscity it fails with the exceptionorghibernatelazyinitializationexception could not initialize proxy no session at orghibernateproxyabstractlazyinitializerinitializeabstractlazyinitializerjava164 at orghibernateproxyabstractlazyinitializergetimplementationabstractlazyinitializerjava285 at orghibernateproxypojojavassistjavassistlazyinitializerinvokejavassistlazyinitializerjava185 at comemployeesmodeladdress javassist 6getcityaddress javassist 6java at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokeunknown source at sunreflectdelegatingmethodaccessorimplinvokeunknown source at javalangreflectmethodinvokeunknown source at javaxelbeanelresolvergetvaluebeanelresolverjava87 at javaxelcompositeelresolvergetvaluecompositeelresolverjava67 at orgapacheelparserastvaluegetvalueastvaluejava169 at orgapacheelvalueexpressionimplgetvaluevalueexpressionimpljava189 at orgapachejasperruntimepagecontextimplproprietaryevaluatepagecontextimpljava985 at orgapachejspweb 002dinflistemployees jsp jspx meth c 005fout 005f3listemployees jspjava306 at orgapachejspweb 002dinflistemployees jsp jspx meth c 005fforeach 005f1listemployees jspjava248 at orgapachejspweb 002dinflistemployees jsp jspx meth c 005fforeach 005f0listemployees jspjava155 at orgapachejspweb 002dinflistemployees jsp jspservicelistemployees jspjava89 at orgapachejasperruntimehttpjspbaseservicehttpjspbasejava70 at javaxservlethttphttpservletservicehttpservletjava722 at orgapachejasperservletjspservletwrapperservicejspservletwrapperjava432 at orgapachejasperservletjspservletservicejspfilejspservletjava390 at orgapachejasperservletjspservletservicejspservletjava334 at javaxservlethttphttpservletservicehttpservletjava722 at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava305 at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava210 at orgapachecatalinacoreapplicationthispatcherinvokeapplicationthispatcherjava690 at orgapachecatalinacoreapplicationthispatcherprocessrequestapplicationthispatcherjava477 at orgapachecatalinacoreapplicationthispatcherdoforwardapplicationthispatcherjava402 at orgapachecatalinacoreapplicationthispatcherforwardapplicationthispatcherjava329 at comemployeescontrolleremployeecontrollerprocessrequestemployeecontrollerjava69 at comemployeescontrolleremployeecontrollerdogetemployeecontrollerjava30 at javaxservlethttphttpservletservicehttpservletjava621 at javaxservlethttphttpservletservicehttpservletjava722 at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava305 at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava210 at orgapachecatalinacorestandardwrappervalveinvokestandardwrappervalvejava225 at orgapachecatalinacorestandardcontextvalveinvokestandardcontextvalvejava123 at orgapachecatalinaauthenticatorauthenticatorbaseinvokeauthenticatorbasejava472 at orgapachecatalinacorestandardhostvalveinvokestandardhostvalvejava168 at orgapachecatalinavalveserrorreportvalveinvokeerrorreportvalvejava98 at orgapachecatalinavalvesaccesslogvalveinvokeaccesslogvalvejava927 at orgapachecatalinacorestandardenginevalveinvokestandardenginevalvejava118 at orgapachecatalinaconnectorcoyoteadapterservicecoyoteadapterjava407 at orgapachecoyotehttp11abstracthttp11processorprocessabstracthttp11processorjava1001 at orgapachecoyoteabstractprotocolabstractconnectionhandlerprocessabstractprotocoljava585 at orgapachetomcatutilnetjioendpointsocketprocessorrunjioendpointjava310 at javautilconcurrentthreadpoolexecutorrunworkerunknown source at javautilconcurrentthreadpoolexecutorworkerrununknown source at javalangthreadrununknown sourcemapping for employeexml version10 encodingutf8doctype hibernatemapping publichibernatehibernate mapping dtd 30enhibernatemapping class namecomemployeesmodelemployee tableemployees id columnemployee id nameemployeeid typeint generator clasequence param namesequenceemp seqparam generator id property columnfirst name namefirstname typejavalangstring property columnlast name namelastname typejavalangstring manytoone nameaddress columnaddress id classcomemployeesmodeladdress set nameemployeesoffices key columnemployee id onetomany classcomemployeesmodelemployeeoffice set classhibernatemappingmapping for addressxml version10 encodingutf8doctype hibernatemapping publichibernatehibernate mapping dtd 30enhibernatemapping class namecomemployeesmodeladdress tableaddresses id columnaddress id nameaddressid typeint generator clasequence param namesequenceaddress seqparam generator id property columnstreet namestreet typejavalangstring property columnhouse number namehousenumber typeint manytoone namecity columncity id classcomemployeesmodelcity classhibernatemappingit is absolutely normal with other classes office company etc if comment the lines which load address fields in jsp application works without any exceptions whats wrong by the way it shows all information on jsp despite the exception,['java'] +411827,sdl error undefined symbols for architecture x86 64 sdl main i am using c with the sdl cocoa and foundation framework on my mac os x i get the following error undefined symbols for architecture x86 64 sdl main referenced from sdlmain applicationdidfinishlaunching in sdlmainold symbols not found for architecture x86 64when i run the following codeimport foundationfoundationhimport sdlsdlhinclude sdlmainhint mainint argc const char argv sdl initsdl init everything sdl setvideomode64048032sdl doublebuf sdl event event bool isrunning true whilesdl polleventevent ifeventtype sdl quit isrunningfalse sdl quit return 0i have no idea what is wrong although it seems that when i go into the sdlmainm file and comment out this line of codestatus sdl main gargc gargvthe program compiles with no problems however it does not work no window opens like its supposed to any ideas,['c++'] +411832,calling shell32dll from net windows service i have a net 40 library that uses shell32 and foldergetdetailsof to get metadata from wtv files i have used it successfully with console and windows forms apps without issue but for some reason when calling the component from a net 40 windows service the call to initiate the shell class causes a com errorthe code that fails inside the libraryshell32shell shell new shellthe errorunable to cast com object of type system comobject to interface type shell32shell this operation failed because the queryinterface call on the com component for the interface with iid 286e6f1b71134355956296b7e9d64c54 failed due to the following error no such interface supported exception from hresult 0x804002 e nointerfacei read my fill of apartment threading com interops dynamic pias etc etc etc but no combination of solutions i have found has solved the problem it must be a calling from another thread that cannot see the interop help please,"['c#', '.net']" +411841,how to print a variable with requests and json i have been programming an application that pulls information from an online api and i need some help with iti am using requests and my current code is as followsmydata requestsgettheapiwebsiteherecomthispartisworkingmyrealdata mydatajsonx myrealdatadataplayerstatsummariesplayerstatsummarysetmaxratingprint xi then get this errormyrealdata mydatajson typeerror nonetype object is not callablei want to be able to get to the variable maxrating and print it out but i cannot seem to do that thanks for your help,['python'] +411864,image resizing causing slow scrolling i am loading large images and having the browser resize them i am explicitly setting the sizeimg src width240 height360there are many such images on the page scrolling is very slow and choppy the events timeline in chrome looks something like this when scrollingpaint image decode jpeg image resize noncached image decode jpeg image resize noncached paint image resize cached image resize cached image resize cached image resize cachedpaint image decode jpeg image resize noncached image decode jpeg image resize noncached paint image resize noncached image resize noncached image resize noncached image resize noncachedpaint image decode jpeg image resize cached image decode jpeg image resize cached etci am not sure why some of the paint events include image decoding and others do not nor why sometimes the resizing is cached and sometimes it is not i guess it must have to do with new images coming into the viewportis there anything i can do to ensure that i only pay the image resize cost once per image when the page loads and avoid image resizing during scrollof course i understand that the best solution is to avoid browser resizing by loading in an image that is already of the appropriate size in this case this is not practical,"['html', 'css']" +411875,spring 32 hibernate 4 opensessioninviewfilter i am a spring newbie trying my first app my hibernate gets closed before the view is rendered and having problems with lazy loaded properties expected behavior i have added the opensessioninviewfilter to my webxml and caused the following javalangillegalstateexception no webapplicationcontext found no contextloaderlistener registeredbeforehand it was working fine with the default servlet context config i have had can someone tell me why so i have added the following contextparam paramnamecontextconfiglocationparamname paramvalue webinfspringappservletxml paramvalue contextparam listener listenerclassorgspringframeworkwebcontextcontextloaderlistenerlistenerclass listenerthe new error went awaybut still getting a no session exception from hibernateorghibernatelazyinitializationexception failed to lazily initialize a collection of role comtestmodelstorecategories could not initialize proxy no sessioni have put a debug message in one of my controllers and it seems that its being initialized 3 times maybe i have more than one instance of hibernate session factory bean my controller methods are marked transactional and everything worked until i have attempted to leave the session open to make the lazy fields available for the viewmy full webxml with the new context addition worked fine without it before i have added the hibernate filterxml version10 encodingiso88591webapp version24 xmlns xmlnsxsi xsischemalocation 2 4xsd thisplayname spring thisplayname description spring test description contextparam paramnamecontextconfiglocationparamname paramvalue webinfspringappservletxml paramvalue contextparam listener listenerclassorgspringframeworkwebcontextcontextloaderlistenerlistenerclass listener filter filternamehibernatefilterfiltername filterclassorgspringframeworkormhibernate4supportopensessioninviewfilterfilterclass initparam paramnamesessionfactorybeannameparamname paramvaluesessionfactoryparamvalue initparam filter filtermapping filternamehibernatefilterfiltername urlpatternurlpattern thispatcherrequestthispatcher thispatcherforwardthispatcher filtermapping servlet servletnamespringappservletname servletclassorgspringframeworkwebservletthispatcherservletservletclass loadonstartup1loadonstartup servlet servletmapping servletnamespringappservletname urlpatternurlpattern servletmapping errorpage errorcode500errorcode locationerror500location errorpage errorpage errorcode404errorcode locationresourcespageserrorhtmllocation errorpagewebappspringappservletxmlxml version10 encodingutf8beans xmlns xmlnsxsi xmlnscontext xmlnsmvc xmlnsaop xmlnstx xsischemalocation contextcomponentscan basepackagecomtestwebcontrollerscomtestserviceimpl mvcannotationdriven mvcresources mappingresources locationresources bean idmydatasource classorgapachecommonsdbcpbasicdatasource destroymethodclose property namedriverclassname valuecommysqljdbcdriver property nameurl valuejdbcmysqllocalhost3306testzerodatetimebehaviorconverttonull property nameusername valuespring property namepassword valuetest bean bean idsessionfactory classorgspringframeworkormhibernate4localsessionfactorybean property namedatasource refmydatasource property namemappinglocations valueclasspathcomtestmodelhbmhbmxml property namehibernateproperties value hibernatedialectorghibernatedialectmysql5dialect hibernateshow sqltrue value property bean txannotationdriven bean idtransactionmanager classorgspringframeworkormhibernate4hibernatetransactionmanager property namesessionfactory refsessionfactory bean bean idvelocityconfig classorgspringframeworkwebservletviewvelocityvelocityconfigurer property nameresourceloaderpath valuewebinftemplates bean bean idviewresolver classorgspringframeworkwebservletviewvelocityvelocitylayoutviewresolver property namecache valuetrue property nameprefix value property namesuffix valuevm property namelayouturl valueindexvm if you want to use the spring velocity macros set this property to true property nameexposespringmacrohelpers valuetrue bean bean idmultipartresolver classorgspringframeworkwebmultipartcommonscommonsmultipartresolver one of the properties available the maximum file size in bytes property namemaxuploadsize value10 bean bean idvalidator classorgspringframeworkvalidationbeanvalidationlocalvalidatorfactorybean bean idcategorydao classcomtestdaohibernatehibernatecategorydao property namesessionfactory refsessionfactoryproperty bean bean idcategoryservice classcomtestservicecategories scopesingleton property namedao refcategorydaoproperty bean bean idstoredao classcomtestdaohibernatehibernatestoredao property namesessionfactory refsessionfactoryproperty bean bean idstoreservice classcomtestservicestores scopesingleton property namedao refstoredaoproperty property namecategorydao refcategorydaoproperty beanbeans,['java'] +411886,why prototype is undefined i known this has been asked hundreds of times however i cannot seem to grasp the concept of prototypeheres my sample scriptvar config writable true enumerable true configurable truevar defineproperty functionobj name value configvalue value objectdefinepropertyobj name configvar man objectcreatenulldefinepropertyman sex malevar person objectcreatemanpersongreet function person return thisname why hello there person var pobjectgetprototypeofpersonalertpsexshows malepersonprototypeage13why there is a error said the prototype is undefined i thought it supposed be man objectvar childfunctionchildprototypecolorredwhy this line does not show error both child and person are an object alertchildprototypecolorshows redvar chobjectgetprototypeofchildalertchcolorwhy it is undefined it is supposed redhope you can give me some helps thanksupdatedthanks your guys kindly help based on elclanrss answer below is what i learnedfunction is the one of the buildin objects in javascript the 3 format creation function object are equalvar function name new functionarg1 arg2 argn function bodyfunction function namearg1 arg2 argnvar function namefunctionarg1 arg2 argnso that is why create a prototype chain we have to create a function and then call it with the new keyword functionprototype is the reference to all the function object prototypecheers,['javascript'] +411949,confusion about inclass initialization of static data members i am reading lippmans c primer where on p 303 they give thisclass account private static constexpr int period 30 double daily tblperiodif the member is used only in contexts where the compiler can substitute the members value then an initialized const or constexpr static need not be separately defined however if we use the member in a context in which the value cannot be substituted then there must be a definition for that memberalsofor example if we pass accountperiod to a function that takes a const int then period must be definedso i tried adding such a functionclass account private static constexpr int period 30 double daily tblperiod void fooconst int i void bar fooperiod no errorthere i have added a function that takes a const int i also did not add any definition for the period variable but still i get no error as they said i should get why not,['c++'] +411975,angularjs ngrepeat and ngswitch on tr tags i am trying to use angularjs to create a table of a list of events but each event has a type and events of different types have drastically different contents and some types also generate more than one rowin a perfect world i would do thistbody ngrepeatevent in events ngswitch oneventtype ngswitchwhentype1 tr tr tr tr ngswitchwhen ngswitchwhentype2 tr tr ngswitchwhen ngswitch ngrepeattbodybut this would not work because most browsers will thiscard or relocate the ng tags to enforce that the tbody only contains trsthe only solution i have seen to related problem how to use ngrepeat without an html element is to have multiple tbody elements i would prefer not to do that but even if i do this giving the tbody the ngrepeat and ngswitch attributes i still have the problem that i cannot wrap multiple trs in a single ngswitchwhenis there a way to do this in angularjs or is this impossiblethanks,['javascript'] +411979,putting sql data into html table i am trying to get the data from my mysql database and put them into a html tableafter searching a lot on the internet but i coudnt find code that worked for mecurrently i have this code doctype htmlhtml xmlnshead titletitleheadbody table thead tr tdnaamtd tdgemeentetd tddatumtd tr thead tbody php db select mysql select dbdbnamedb if db select diedatabase selection also failed miserably mysql error mysql select dbdatabaseiheko results mysql queryselect naamfuif gemeentefuif datumfuif from tblfuiven whilerow mysql fetch arrayresults tr tdphp echo rownaamfuiftd tdphp echo rowgemeentefuiftd tdphp echo rowdatumfuiftd tr php tbody tablebodyhtmlthe only thing that i get is the first row of my table naamgemeentedatumam i doing something wrong or did i forgot something,"['php', 'html', 'sql']" +411991,inner div to have height 100 inside a container of height auto i am struggling to get a div to expand fully to it is containers heightmarkupdiv classcontainer div classinnerone innerdiv div classinnertwo innerdivdivat different viewports innertwos content is taller than that of innerones but i would like it is background to be the same size as innertwosstylescontainer width 100 height auto backgroundcolor yellow clearfix zoom 1 before after thisplay table content lineheight 0 after clear both inner float left width 50 height 100 backgroundcolor redbut the heights wont match up i know it can be done by giving the container a set height but i do not want to do that since it is a responsive site is this possible i would rather not use js,['css'] +412007,how to implement swipe to delete with quickdialog i am using quickdialog for a form andi am trying to implement swipe to delete and have no idea how i would do thatcan anybody help me,"['objective-c', 'iphone']" +412014,failed to delete buffer no buffer to delete i am trying to generate an excel file with the extension xlsx from the code below i am able to download the file very well but when i open it with excel sheet i receive the following warning error excel cannot open the file dindixlsx because the file format or file extension is not valid ensure that the file is not corrupted and that the file extension matches the format of the filewhen i opened it with notepad the file had the following errornotice ob end clean refoutcontrol failed to delete buffer no buffer to deletebelow is the codeof what i am trying to dopublic function exportresults this load database query this db query select from farm limit 10 results query result array objphpexcel new excel objreader phpexcel iofactorycreatereaderexcel2007 objphpexcel objreaderloadfilesfarmdetailsxlsx objphpexcel getactivesheetsettitlefarmreport objphpexcel setactivesheetindex0 i 1 foreach results as result objphpexcel getactivesheet setcellvaluea i resultname objphpexcel getactivesheet setcellvalueb i resultdateofcontract objphpexcel getactivesheet setcellvaluec i resultleasorname objphpexcel getactivesheet setcellvalued i resultacre objphpexcel getactivesheet setcellvaluee i resultzone i echo resultname ob end clean filename dindixlsx headerlastmodified gmdated d m y his gmt headercachecontrol nostore nocache mustrevalidate headercachecontrol postcheck0 precheck0 false headerpragma nocache headercontenttype applicationvndopenxmlformatsofficedocumentspreadsheetmlsheet headercontentthisposition attachmentfilename filename objwriter phpexcel iofactorycreatewriterobjphpexcel excel2007 ob end clean objwriter savephpoutput objphpexcel thisconnectworksheets unsetobjphpexcel,['php'] +412027,android using only viewpager from support library the new edition of my app has a minimum sdk of 14 so i thought that i could get rid of the supportv4 library that i have been using for the older version however it now looks like i might have to use viewpager and thus am back to including the libraryso can i just use the viewpagerrelated classes from the library and not have to use the other classes that are now native in v14 such as fragment and also not have to change activity to fragmentactivityi would assume that i can do this only use viewpager from the library but wanted to check to make sure,['android'] +412058,compare list in python to detect an equality first i am a novice at python programming and attempted much research within other questions but none that i could find that relate to something like this all others were a bit more advanced that said moving on the solution neededgo through two two integer lists and compare for equality ideally i want it to continue going through the lists over and over till there is an equality more on this after showing code the number will be generated in list2 over and over till there is an equality explanation to code i have two lists that are generated via a random number generation the lists are not equal in size so list1 has 500 entries and list2 will have different amounts varying from 1 to 100 current attempt to figure out the comparison if list1 list2 printequalnumbermaybe i do not know much about looping but i want it to loop through the list i really do not know where to start from maybe i am not using a loop like a for loop or whilethis is my number generators for i in range0500 randoms randomrandint010 fivehundredloopappendrandomsthe second one would do some but would only have varying entries between 1 and 100 i can take care of this myself,['python'] +412068,possible to create a fixedwidth drawable in xml i am trying to simplify some graphics from requiring a 9patch for each density to just using an xml drawable it is a fairly simple graphic2 segments8dp wide for both segmentstop segment is 2dp tallbottom segment fills the viewright side is filled with transparencygiving this result when set as a background imageit seems like this should be fairly simple to recreate as an xml drawable and would avoid creating 5 different 9patch graphics however i have looked into layerlist drawables inset drawables clip drawables they all seem to require that you know the size of the view beforehand eg to keep it 2dp for an inset youd need to set insetright to the width of the view 2dp i also tried using the shape tags size tag but that does not keep a fixed size just a fixed proportion so for taller views it will scale proportionally am i overlooking something simple or is this something i would have to resort to checking programatically after layout,['android'] +412132,thismissing popover uipopovercontroller dealloc reached while popover is still visible i have a uipopovercontroller stored in a strong property in my view controller when the user rotates the ipad while the popover is visible i thismiss the popover and set my property to nil if selfpopover nil selfpopover thismisspopoveranimatedno selfpopoverdelegate nil selfpopover nilwhen the code gets to selfpopover nil arc attempts to dealloc the uipopovercontroller but it crashes because it is supposedly still visiblehow am i supposed to thismiss and nil out the popover without it crashing,['ios'] +412139,warn if accessing moved object in c11 possible duplicatewhat can i do with a movedfrom object after you called stdmove and passed the result to a function you generally have to assume that accessing the moved object later will result in undefined behavior are there tools that can detect those accesses and warn you for example widget w foostdmovew w may be undefined at this point wdosomething warnat least gcc 472 and clang 32 with wall do not complain,['c++'] +412155,cannot add new monogame content project to solution in vs2012 i am trying to add a new monogame content project via templates installed in the monogame 30 installer to an existing solution in visual studio 2012 professional but it always comes up with the following dialog boxit does create a few empty folders where the project should be though they do not have anything in them after this popup it also comes up with thisi do not have xna installed as vs2012 does not support italso i am using windows 7thank you,['c#'] +412174,set environment variables for a process what is the environment variable conceptin a c program i need to call an executable the executable will call some other executables that reside in the same folder the executables rely on the two environment variables path and raypath to be set correctly i tried the following two thingsi created a process and set the two varables in startinfo thevariables exist already but are missing the needed informationi tried to set the variables with systemenvironmentsetenvironmentvariablewhen i run the process the system cannot find the executable executeable1 i tried to set startinfofilename to the full path of executeable1 however then the exe files called form within executeable1 are not foundhow do i deal with thisstring pathvar systemenvironmentgetenvironmentvariablepathsystemenvironmentsetenvironmentvariablepath pathvar cud bindaysimbin windowscud binradiancebincud bindaysimsystemenvironmentsetenvironmentvariableraypath cud bindaysimlibcud binradiancelibsystemdiagnosticsprocess p new systemdiagnosticsprocesspstartinfoworkingdirectory cud bindaysimbin windowsstring pathvar pstartinfoenvironmentvariablespathpstartinfoenvironmentvariablespath pathvar cud bindaysimbin windowscud binradiancebincud bindaysimpstartinfoenvironmentvariablesraypath cud bindaysimlibcud binradiancelibpstartinfouseshellexecute falsepstartinforedirectstandardoutput truepstartinfocreatenowindow truepstartinfofilename executeable1pstartinfoarguments arg1 arg2pstartpwaitforexit,['c#'] +412199,using systemuihider to keep the navigation bar hidden in older versions of android it was necessary to use androidthemeandroidstylethemenotitlebarfullscreen in the manifest to make the title bar thisappearin the newer adt versions i have noticed a systemuihider class which lets you make calls to it is hide method to remove not only the title bar but also the action bar and navigation bari am trying to write a fullscreen app that i would like to stay full screen for a kiosk implementation unless a small hidden button is pressedi have tried taking the standard fullscreenactivity generated from the new android project wizard and prevent the ui from reappearing in a number of waysmaking calls to msystemuihiderhide in the setonvisibilitychangelistener to try and immediately hide the ui when it detects a change in visibilitysetting auto hide delay millis 0 to try and immediately hide it if it is visiblepreventing the call to msystemuihidershow within the onclick method of the contentviewsetonclicklistener to prevent it from being showni have also seen the setsystemuivisibility example in the docs for androidview again to try and hide it immediately if shown or visibility is changednone of them seem to work android defaults to the low profile mode for the navigation bar when any of these are triedi understand that they probably do not want developers doing what i am trying to do but i was hoping that i could extend systemuihider andor systemuihiderbase and override the show methods to essentially not show unless passed a true flag i cannot seem to find any documentation on either of these classes perhaps because they are utility classes,['android'] +412226,how to interfacing swi prolog to the visual studio 2012 i have a program that interfacing swiprolog in visual studio previously i used vs2010 xp and everything works fine then i upgrade my vs to become vs2012 win7 and now i have a problem in my codewhen it comes to the following codeplengineinitializeparamit always gives me the following exception messagethe specified module could not be found exception from hresult 0x8007007ecan anybody spot what mistake that i made or if possible some modification that i have to do due to the upgrading processadditional information regarding my codei used the most updated swiplcs library version 11603010my param in my code above is string param q f cprogram files x86pli have set the path environment variable to cprogram files x86pl and cprogram files x86plbini have this setting in my code environmentsetenvironmentvariableswi home dir globalg prologlocationi had the reference to swiplcsdlli already tried to use the swiprolog 64 bit but i still have the same problemany help is really appreciatedmany thanks,['c#'] +412272,layout folders for google nexus 7 and 10 i am developing an application for google nexus 7 and 10 but there is a problem i do not know which layout folder should be used for 7 and 10,['android'] +412309,how to know which phpini is used i search the path where the phpini file is located in our linux ubuntu server and i found many phpini when executing the command find name phpini so how to know exactly from a php script web page where the phpini is located,['php'] +412313,onactivityresult returned from a camera intent null i follow the instruction on camera on android dev sitei just start the camera intent not build my own camera the sample code to handle result return after taking a photo is as follows protected void onactivityresultint requestcode int resultcode intent data if requestcode capture image activity request code if resultcode result ok image captured and saved to fileuri specified in the intent toastmaketextthis image saved ton datagetdata toastlength longshow else if resultcode result canceled user cancelled the image capture else image capture failed advise user if requestcode capture video activity request code if resultcode result ok video captured and saved to fileuri specified in the intent toastmaketextthis video saved ton datagetdata toastlength longshow else if resultcode result canceled user cancelled the video capture else video capture failed advise user resultcode is ok but data is always null which causes a npe i looked into the sdcard the photo was really saved there any tip tks muchupdate logcat info as requested 0128 193900547 errorandroidruntime24315 fatal exception main javalangruntimeexception unable to resume activity comexamplecameratestcomexamplecameratestmycamera javalangruntimeexception failure delivering result resultinfowhonull request100 result1 datanull to activity comexamplecameratestcomexamplecameratestmycamera javalangnullpointerexception at androidappactivitythreadperformresumeactivityactivitythreadjava2455 at androidappactivitythreadhandleresumeactivityactivitythreadjava2483 at androidappactivitythreadhandlelaunchactivityactivitythreadjava1997 at androidappactivitythreadhandlerelaunchactivityactivitythreadjava3362 at androidappactivitythreadaccess700activitythreadjava127 at androidappactivitythreadhhandlemessageactivitythreadjava1162 at androidoshandlerthispatchmessagehandlerjava99 at androidoslooperlooplooperjava137 at androidappactivitythreadmainactivitythreadjava4511 at javalangreflectmethodinvokenativenative method at javalangreflectmethodinvokemethodjava511 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava980 at comandroidinternaloszygoteinitmainzygoteinitjava747 at dalviksystemnativestartmainnative method caused by javalangruntimeexception failure delivering result resultinfowhonull request100 result1 datanull to activity comexamplecameratestcomexamplecameratestmycamera javalangnullpointerexception at androidappactivitythreaddeliverresultsactivitythreadjava2991 at androidappactivitythreadperformresumeactivityactivitythreadjava2442 13 more caused by javalangnullpointerexception at comexamplecameratestmycameraonactivityresultmycamerajava71 at androidappactivitythispatchactivityresultactivityjava4654 at androidappactivitythreaddeliverresultsactivitythreadjava2987 14 more,['android'] +412337,thisplay pdf using an ajax call i am trying to thisplay a pdfwhich is created in the server side and pass to the client side as a web stream through an ajax call my code is given belowjqueryajax type post processdata false url apnamepdf data inputxml contenttype applicationxml charsetutf8 success functiondata here the data is the pdf stream i am getting from the server side the inputxml is containing input parameters for the server to create the pdf and the data in the success function containing pdf stream is there any way to open the pdf file on the browser inside the success function of the ajax call without doing any page submit in the server side the pdf is not physically generated also highly appreciate your help,['jquery'] +412338,why generic ilist does not inherit nongeneric ilist ilistt does not inherit ilist where ienumerableout t inherits ienumerableif out modifier are the only reason then why most of the implementation of ilistt eg collectiont listt implements ilist interfaceso any one can say ok if that statements is true for all implementation of ilistt then directly cast it to ilist when necessary but problem is that though ilistt does not inherit ilist so it is not guaranteed that every ilistt object are ilistmoreover using ilistobject is obviously not the solution because without out modifier generics can not be assigned to a less inherit class and creating new instance of list is not a solution here because someone may want actual reference of the ilistt as an ilist pointer and use listt insteed of ilistt is actually a bad programming practice and does not serve all purposeif net wants to give flexibility that every implementation of ilistt should not have a contract of nongeneric implementation ie ilist then why they did not keep another interface which implement both generic and nongeneric version and did not suggest that all concrete class which want to contract for generic and nongenetic item should contract via that interfacesame problem occurs for casting icollectiont to icollection and idictionarytkey tvalue to idictionary,"['c#', '.net']" +412342,how to exclude one particular field from a collection in mongoose i have a nodejs application with mongoose odmmongoose 331 i want to retrieve all fields except 1 from my collectionfor example i have a collection product which have 6 fieldsi want to select all except a field image i used exclude methodbut got errorthis was my code var query modelsproductfind queryexcludetitle image if reqparamsid querywhere id reqparamsid queryexecfunction err product if err return ressend statuscode 200 statustext ok data product else return ressend500 but this returns errorexpress500 typeerror object query has no method excludealso i tried var query modelsproductfindexcludetitleimage and var query modelsproductfindexcludetitleimage but getting the same error how to exclude onetwo particular fields from a collection in mongooseplease suggest a solution asap,['javascript'] +412381,jprogressbar low values will not be thisplayed i tried out the function of the jprogressbar in java but there is a problem i could not solvewhen i set the minimum to zero the maximum value to 100 and the current value to 6 then nothing will be thisplayed the progress bar is empty if i put 7 as current value then it works it seems to be a problem with any empty border or other space the problem occurs with windows 7 and only if the uimanager is set to systemlookandfeeldoes anyone knows this problem and has a solution for this below is my codepackage labimport javaawtflowlayoutimport javaxswingjdialogimport javaxswingjprogressbarimport javaxswinguimanagerimport coreconfigpublic class progresample extends jdialog public progresample setdefaultcloseoperationthispose on close getcontentpanesetlayoutnew flowlayout nothing is thisplayed jprogressbar progresix new jprogressbar0 100 progresixsetvalue6 getcontentpaneaddprogresix this works jprogressbar progreseven new jprogressbar0 100 progresevensetvalue7 getcontentpaneaddprogreseven packpublic static void mainstring args try uimanagersetlookandfeeluimanager getsystemlookandfeelclassname catch exception e eprintstacktrace progresample dialogtest new progresample dialogtestsetvisibletrue,['java'] +412386,coredata delete multiple objects i know how to delete a single object in coredata i am just wondering if theres a simpler way of deleting multiple objectsfor single delete you can usemoc deleteobjectsomemanagedobjectbut there is no equivalent for multiple objectsat the moment i am thinking of doingnsarray arrayofmanagedobjectstodelete for somemanagedobjectclass managedobject in arrayofmanagedobjectstodelete moc deleteobjectmanagedobjectbut i was not sure if there was another way of doing thisideally a method like voiddeleteobjectsnssetobjectson nsmanagedobjectcontext or some similar method,"['ios', 'objective-c']" +412426,scalaconcurrentforkjoinforkjoinpool vs javautilconcurrentforkjoinpool why forkjoinpool was forked for scalawhich implementation and for which case is preferred,['java'] +412442,how do i thisplay epub format book in pure html5cssjquery is it possible to thisplay epub format books in web browser using pure html5 css and jquery could anybody please suggest how do i do this i have to also make this responsive to be able to make it work on ipad i know that but i do not know how do i read the epub using html and javascriptthe epub may contain some mathematical functions and i need to thisplay them properly too,"['javascript', 'jquery', 'html', 'css']" +412461,amazon ses stops working i set up amazon ses and it initially worked for a few hours then all of a sudden stopped all of the emails i am sending as and our domain have been verified we are no sending bulk emails only a few hundred per day whenever i make changes to the webconfig it seems to allow it work again for another 23 hours for example it stopped working so i switched port 587 to 25 and it began working for 23 hours then stopped then i switched back to 587 and the same thing happened once it stops working it does not ever seem to start again on its own it is running on two load balanced servers aspnet framework v20 iis 75 here is the code i am usingwebconfigsystemnet mailsettings smtp deliverymethodnetwork from network defaultcredentialsfalse hostemailsmtpuseast1amazonawscom username password port587 smtp mailsettingssystemnetc codevar smtpclient new smtpclient enablessl true var mailmessage new mailmessagefromaddress toaddress subject body isbodyhtml true smtpclientsendmailmessagehere are the two errors i have been receivingthe following exception was thrown by the web event provider null in the application in an application lifetime a maximum of one exception will be logged per provider instancesystemwebhttpexception unable to send out an email to the smtp server please ensure that the server specified in the smtpmail section is valid systemnetmailsmtpexception failure sending mail systemioioexception received an unexpected eof or 0 bytes from the transport stream at systemnetfixedsizereaderreadpacketbyte buffer int32 offset int32 count at systemnetsecuritysslstatestartreadframebyte buffer int32 readbytes asyncprotocolrequest asyncrequest at systemnetsecuritysslstatestartreceiveblobbyte buffer asyncprotocolrequest asyncrequest at systemnetsecuritysslstateforceauthenticationboolean receivefirst byte buffer asyncprotocolrequest asyncrequest at systemnetsecuritysslstateprocessauthenticationlazyasyncresult lazyresult at systemthreadingexecutioncontextruntrycodeobject userdata at systemruntimecompilerservicesruntimehelpersexecutecodewithguaranteedcleanuptrycode code cleanupcode backoutcode object userdata at systemthreadingexecutioncontextrunexecutioncontext executioncontext contextcallback callback object state at systemnettlsstreamprocessauthenticationlazyasyncresult result at systemnettlsstreamwritebyte buffer int32 offset int32 size at systemnetpooledstreamwritebyte buffer int32 offset int32 size at systemnetmailsmtpconnectionflush at systemnetmailreadlinescommandsendsmtpconnection conn at systemnetmailsmtpconnectiongetconnectionstring host int32 port at systemnetmailsmtpclientsendmailmessage message end of inner exception stack trace at systemnetmailsmtpclientsendmailmessage message at systemwebmanagementmailwebeventprovidersendmailmailmessage msg end of inner exception stack trace at systemwebmanagementmailwebeventprovidersendmailmailmessage msg at systemwebmanagementsimplemailwebeventprovidersendmessageinternalwebbaseeventcollection events int32 notificationsequence int32 begin datetime lastflush int32 thiscardedsincelastflush int32 eventsinbuffer int32 messagesequence int32 messagesinnotification int32 eventsinnotification int32 eventslostduetomessagelimit at systemwebmanagementsimplemailwebeventprovidersendmessagewebbaseevent eventraised at globalsimplemailwithsslwebeventproviderprocesseventwebbaseevent raisedevent at systemwebmanagementwebbaseeventraiseinternalwebbaseevent eventraised arraylist firingruleinfos int32 index0 int32 index1the following exception was thrown by the web event provider null in the application in an application lifetime a maximum of one exception will be logged per provider instancesystemwebhttpexception unable to send out an email to the smtp server please ensure that the server specified in the smtpmail section is valid systemnetmailsmtpexception service not available closing transmission channel the server response was timeout waiting for data from client at systemnetmailmailcommandcheckresponsesmtpstatuscode statuscode string response at systemnetmailsmtptransportsendmailmailaddress sender mailaddresscollection recipients string deliverynotify smtpfailedrecipientexception exception at systemnetmailsmtpclientsendmailmessage message at systemwebmanagementmailwebeventprovidersendmailmailmessage msg end of inner exception stack trace at systemwebmanagementmailwebeventprovidersendmailmailmessage msg at systemwebmanagementsimplemailwebeventprovidersendmessageinternalwebbaseeventcollection events int32 notificationsequence int32 begin datetime lastflush int32 thiscardedsincelastflush int32 eventsinbuffer int32 messagesequence int32 messagesinnotification int32 eventsinnotification int32 eventslostduetomessagelimit at systemwebmanagementsimplemailwebeventprovidersendmessagewebbaseevent eventraised at globalsimplemailwithsslwebeventproviderprocesseventwebbaseevent raisedevent at systemwebmanagementwebbaseeventraiseinternalwebbaseevent eventraised arraylist firingruleinfos int32 index0 int32 index1i tried to get help on the amazon forums but have not had any luck it seems like something is interfering with the connection but i do not know what any ideas thanks,['asp.net'] +412471,why is not my innerexception making it to the client i have the following code on the serverif actualrowcount maxrows throw new domainexceptionovermaxrowlimitexception new overmaxrowlimitexceptionstringformatmaxrowsmessage actualrowcount maxrowsthis creates a new domainexception with the innerexception property set i have verified that this is set in the debuggerthe custom exception is defined thuspublic class overmaxrowlimitexception exception public overmaxrowlimitexceptionstring message thismessage message public new string message get set this is supposed to return a sensible error message to the client so the user can be told there are too many rows so in the load complete handler wed like to haveif resulthaserror showerrorresulterrorinnerexceptionmessageunfortunately the innerexception property is null so all we have to check is the text of the outer exception message which is not being transferred to the client properly eitherit has been suggested that i needcustomerrors modeoff in the web config file i have tried this and it does not workit is also been suggested that i needknowntypetypeofovermaxrowlimitexceptionon the data contract now unless i have put this in the wrong place this also does not worki have also tried adding serializable to the custom exception and replacing it with the general exception neither of these worked eitherso why is the innerexception property null what am i missing,['c#'] +412527,java http process for streaming video file i am creating a java application which streams a video file over http to a browser currently chrome v24x this video is sent to ffmpeg and the output of this is sent over http now once the file is completely encoded the file is served using chunked transfer and responding to range requests example headersrequestget file9fe6b502c12747c2b6d283ea58676a8d http11 host localhost1234 connection keepalive acceptencoding identityq1 q0 useragent mozilla50 macintosh intel mac os x 10 8 2 applewebkit53717 khtml like gecko chrome240131256 safari53717 accept referer httplocalhost1234media9fe6b502c12747c2b6d283ea58676a8d acceptlanguage enusenq08 acceptcharset iso88591utf8q07q03 cookie plushcontainerwidth10025 plushnotopmenu0 range bytes0 responsehttp11 206 partial content connection close date mon 28 jan 2013 145152 gmt contenttype videomp4 etag 9fe6b502c12747c2b6d283ea58676a8d acceptranges bytes contentrange bytes 0625825625826 contentlength 625826 transferencoding chunked data sent is 625826 bytes excluding header data and chunked overhead now this works just finethe trouble is when the get request happens before the file encoding has completed i have tried to start sending the file straight away over http using just chunked transfer with no content length attributes or ranges because they are not currently known this causes the browser to wait for the full file and not start playing until the transfer has completed in addition when the file transfer is completed the browser reports a video error that the file could not be played example headersrequestrequest get file9fe6b502c12747c2b6d283ea58676a8d http11 host localhost1234 connection keepalive acceptencoding identityq1 q0 useragent mozilla50 macintosh intel mac os x 10 8 2 applewebkit53717 khtml like gecko chrome240131256 safari53717 accept referer httplocalhost1234media9fe6b502c12747c2b6d283ea58676a8d acceptlanguage enusenq08 acceptcharset iso88591utf8q07q03 cookie plushcontainerwidth10025 plushnotopmenu0 range bytes0 responsehttp11 200 ok connection close date mon 28 jan 2013 145129 gmt contenttype videomp4 transferencoding chunkeddata sent is 625826 bytes excluding header data and chunked overhead does anyone have any ideas whats going wrong or how to start playing a video without knowing the full length of the file thanks for your time james editas the request for the incomplete file states range bytes0 can i reply with a partial content of n bytes say 10 bytes with contentrange bytes 09 edit 2as requested here is my code for outputting the file this is condensed as the code actually spans several classesfile f new file filenamerandomaccessfile raf new randomaccessfilef rchunkedoutputstream cos new chunkedoutputstream out 1024 100byte byteswhile true lbuffersizemax mathminlbuffersize fclength lcompleted bytes new byteintlbuffersizemax lcurrentread fcreadbytes if lcurrentread 0 break coswritebytes,['java'] +412539,error opening supportmapfragment for second time when opening my supportmapfragment android maps v2 for a second time calling setcontentview i get the following error0128 162721374 eandroidruntime32743 fatal exception main0128 162721374 eandroidruntime32743 androidviewinflateexception binary xml file line 6 error inflating class fragment0128 162721374 eandroidruntime32743 at androidviewlayoutinflatercreateviewfromtaglayoutinflaterjava7040128 162721374 eandroidruntime32743 at androidviewlayoutinflaterrinflatelayoutinflaterjava7460128 162721374 eandroidruntime32743 at androidviewlayoutinflaterinflatelayoutinflaterjava4890128 162721374 eandroidruntime32743 at androidviewlayoutinflaterinflatelayoutinflaterjava3960128 162721374 eandroidruntime32743 at androidviewlayoutinflaterinflatelayoutinflaterjava3520128 162721374 eandroidruntime32743 at androidviewviewinflateviewjava161190128 162721374 eandroidruntime32743 at mypackagemyviewinithitsviewjava260128 162721374 eandroidruntime32743 at mypackagemenulistfragmentonitemclickmenulistfragmentjava1330128 162721374 eandroidruntime32743 at androidwidgetadapterviewperformitemclickadapterviewjava2980128 162721374 eandroidruntime32743 at androidwidgetabslistviewperformitemclickabslistviewjava10860128 162721374 eandroidruntime32743 at androidwidgetabslistviewperformclickrunabslistviewjava28550128 162721374 eandroidruntime32743 at androidwidgetabslistview1runabslistviewjava35290128 162721374 eandroidruntime32743 at androidoshandlerhandlecallbackhandlerjava6150128 162721374 eandroidruntime32743 at androidoshandlerthispatchmessagehandlerjava920128 162721374 eandroidruntime32743 at androidoslooperlooplooperjava1370128 162721374 eandroidruntime32743 at androidappactivitythreadmainactivitythreadjava47450128 162721374 eandroidruntime32743 at javalangreflectmethodinvokenativenative method0128 162721374 eandroidruntime32743 at javalangreflectmethodinvokemethodjava5110128 162721374 eandroidruntime32743 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava7860128 162721374 eandroidruntime32743 at comandroidinternaloszygoteinitmainzygoteinitjava5530128 162721374 eandroidruntime32743 at dalviksystemnativestartmainnative method0128 162721374 eandroidruntime32743 caused by javalangillegalargumentexception binary xml file line 6 duplicate id 0x7f04003b tag null or parent id 0x0 with another fragment for comgoogleandroidgmsmapssupportmapfragment0128 162721374 eandroidruntime32743 at androidsupportv4appfragmentactivityoncreateviewfragmentactivityjava2850128 162721374 eandroidruntime32743 at androidviewlayoutinflatercreateviewfromtaglayoutinflaterjava6760128 162721374 eandroidruntime32743 20 morethe xml filexml version10 encodingutf8relativelayout xmlnsandroid xmlnsmap androidlayout widthmatch parent androidlayout heightmatch parent fragment androidididhits map androidlayout widthmatch parent androidlayout heightwrap content classcomgoogleandroidgmsmapssupportmapfragment mapmaptypenormal mapuizoomcontrolsfalse mapuizoomgesturestrue mapcamerazoom13 mapuirotategesturestrue mapuitiltgesturestruerelativelayoutmyviewclasspublic class myview extends relativelayout private googlemap map public myviewcontext context fragmentactivity activity supercontext inflateactivity rlayoutactivity hits this thismap supportmapfragment activitygetsupportfragmentmanager findfragmentbyidridhits mapgetmap i have no idea what this error means can someone explain this,['android'] +412543,background blur with css i want an vista7aeroglastyle effect on a popup on my site and it needs to be dynamic i am fine with this not being a crossbrowser effect as long as the site still works on all modern browsersmy first attempt was to use something likedialog base backgroundwhite backgroundrgba25525525508 filterblur4px ofilterblur4px msfilterblur4px mozfilterblur4px webkitfilterblur4pxhowever as i should have expected this resulted in the content of the dialog being blurred and the background staying clear is there any way to use css to blur the background of a semitransparent element instead of its contents,['css'] +412571,create video programmatically with qt 50 we have a qt application that renders programmatically generated qpixmaps one by one to the thisplay and we would like to save this output to a video file i know that in the past people have recommended using ffmpeg or opencv with qt to do this in qt 5 however the new qtmultimedia module seems to expose some of this type of functionality it is now possible for example to save video from a camera source in qt 5 by using the qmediarecorder as described in with this new functionality is there any way to use qt 5 to save our programmatically generated video or am i still better off using a third party library,['c++'] +412575,how to use flaskscript and gunicorn i am working on on a flask app using flasks built in dev server i start it using flaskscript i want to switch to using gunicorn as the web server to do so do i need to write some sort of integration code between flaskscript and gunicorn or is flaskscript irrelevant to running the app using gunicornthanks in advanceprops to seanlynch the following is working tested code based on his answerthe changes i made wereoptions that are not recognized by gunicorn are removed from sysargv in remove non gunicorn command line args before trying to start the server otherwise gunicorn throws an error with a message like this error unrecognized arguments port 5010 i remove p because even though it does not cause the error that is only because gunicorn thinks its the short form of its pidfile option which is obviously not whats intendedgunicornserverhandle signature modified to match the method it overrides ie commandhandlefrom flask script import commandfrom gunicornappbase import applicationclass gunicornservercommand description run the app within gunicorn def init self host127001 port80 workers6 selfport port selfhost host selfworkers workers def get optionsself return optiont host desthost defaultselfhost optionp port destport typeint defaultselfport optionw workers destworkers typeint defaultselfworkers def handleself app args kwargs host kwargshost port kwargsport workers kwargsworkers def remove non gunicorn command line args import sys args to remove portp def args filtername or value keep not args to removecountname or value if keep previous sysargvsysargvindexname or value 1 keep not args to removecountprevious return keep sysargv filterargs filter sysargv remove non gunicorn command line args from gunicorn import version info if version info 0 9 0 from gunicornarbiter import arbiter from gunicornconfig import config arbiter arbiterconfigbind sd host intportworkers workers app arbiterrun else class flaskapplicationapplication def initself parser opts args return bind 01formathost port workers workers def loadself return app flaskapplicationrunmanageradd commandgunicorn gunicornserver,['python'] +412586,identify if at least one row with given condition exists employee table has id and name columns names can be repeated i want to find out if there is at least one row with name like kaushikso query should return truefalse or 10 is it possible to find it using single queryif we try something like select count1 from employee where name like kaushikin this case it does not return truefalse also we are iterating over all the records in table is there way in simple sql such that whenever first record which satisfies condition is fetched it should stop checking further recordsor such thing can only be handled in plsql block edit first approach provided by justin looks correct answer select count from employee where name like kaushik and rownum 1,['sql'] +412625,how to add a callback function to the addclass method of jquery i am using prettify from google and markdown and i want each time i find a pre code added in the markdown textarea to call again the prettyprint functionthis is my actual codeifwmdpreviewlength 0 wmdpreviewondomnodeinserted domnoderemovedfunction thisfindprenotprettyprintaddclassprettyprint but i want something likethisfindprenotprettyprintaddclassprettyprintfunction prettyprintis there any possible way to achieve this,['jquery'] +412626,pandas installation on mac os x importerror cannot import name hashtable i would like to build pandas from source rather than use a package manager because i am interested in contributing the first time i tried to build pandas these were the steps i took1 created the virtualenvmkvirtualenv nositepackages pandas2 activated the virtualenv3 installed anaconda ce however this was installed in anaconda4 cloned pandas5 built c extensions in placepandasems virtualenvspandaslocalrepopandas anacondabinpython setuppy build ext inplace6 built pandaspandasems virtualenvspandaslocalrepopandas anacondabinpython setuppy build7 ran nosetests on master branchtests failedpandasems virtualenvspandaslocalrepopandas nosetests pandas e error failure valueerror numpydtype has the wrong size try recompiling traceback most recent call last file usersemilychenvirtualenvspandaslibpython27sitepackagesnoseloaderpy line 390 in loadtestsfromname addrfilename addrmodule file usersemilychenvirtualenvspandaslibpython27sitepackagesnoseimporterpy line 39 in importfrompath return selfimportfromdirdir path fqname file usersemilychenvirtualenvspandaslibpython27sitepackagesnoseimporterpy line 86 in importfromdir mod load modulepart fqname fh filename desc file usersemilychenvirtualenvspandaslocalrepopandaspandasinitpy line 6 in from import hashtable tslib lib file numpypxd line 156 in init pandashashtable pandashashtablec20354 valueerror numpydtype has the wrong size try recompilingran 1 test in 01sfailed errors1someone on the pydata mailing list saidit looks like you have numpy installed someplace else on your machine and anacondace is not playing nicely in the virtualenv the error you are getting is a cython error message which occurs when the numpy version it built against does not match the installed version on your system i had thought that 17x was supposed to be abi compatible with 16x so this would not happen but i guess not sighthe numpy version in anaconda ce library is 170b2 and my system numpy installation is version 151 setuppy linked to the numpy in the anaconda thistributions libraries when it built pandas but my guess is it is linking to my system version when nosetests runs pandasinitpynext i repeated the steps outside a virtualenv but got the same error finally i decided to install all the dependencies in a new virtualenv instead of using the anaconda thistribution to build pandas this way i can see that dependencies like numpy reside in the lib directory of the virtualenv python installation which takes precedent when pandasinit runs import statements this is what i did1 installed numpy dateutil pytz cython scipy matplotlib and openpyxl using pip2 built c extensions in place3 pandas install output here 4 pandas did not install correctlypandasems virtualenvspandaslocalrepopandas pythonpython 271 r27186832 jul 31 2011 193053 gcc 421 based on apple inc build 5658 llvm build 23351500 on darwintype help copyright credits or license for more information import pandas cannot import name hashtabletraceback most recent call lastfile stdin line 1 in modulefile pandas init py line 6 in modulefrom import hashtable tslib libimporterror cannot import name hashtablei took a look at this question but cython installed in my case and i am trying to build successfully from source rather than using pip like the answer recommendedpandasems virtualenvspandaslocalrepopandas which cythonusersemilychenvirtualenvspandasbincython,['python'] +412644,how to remove white screen while loading android application i am new to android i have a web view which loads a url the problem is that after i open the application there is a white screen for 23 seconds after that the web viewas url is loaded i think this is the time the application initiates how can i remove the white screen and thisplay my logo for that time i heard of splash screen but in that the logo appears for 1 second then white screen appears for another 23 seconds and then finally the web view is loaded what am i doing wrong is it splash screen or some other way to thisplay the logo while web view loads package comexampedatingimport androidosbundleimport androidappactivityimport androidaprogressdialogimport androidviewkeyeventimport androidviewmenuimport androidwebkitwebsettingsimport androidwebkitwebviewimport androidwebkitwebviewclientpublic class mainactivity extends activity override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main webview mywebview webview findviewbyidridwebview mywebviewloadurl websettings websettings mywebviewgetsettings websettingssetjavascriptenabledtrue mywebviewsetwebviewclientnew webviewclient override public boolean oncreateoptionsmenumenu menu inflate the menu this adds items to the action bar if it is present getmenuinflaterinflatermenuactivity main menu return true override public boolean onkeydownint keycode keyevent event webview mywebview webview findviewbyidridwebview if keycode keyeventkeycode back mywebviewcangoback mywebviewgoback return true return superonkeydownkeycode event splashactivityjavapackage comexampedatingimport androidappactivityimport androidcontentintentimport androidosbundleimport androidutillogimport androidviewwindowimport androidviewwindowmanagerpublic class splashactivity extends activity private static string tag splashactivityclassgetname private static long sleep time 10 sleep for some time override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate thisrequestwindowfeaturewindowfeature no title removes title bar thisgetwindowsetflagswindowmanagerlayoutparamsflag fullscreen windowmanagerlayoutparamsflag fullscreen removes notification bar setcontentviewrlayoutsplash start timer and launch main activity intentlauncher launcher new intentlauncher launcherstart private class intentlauncher extends thread override sleep for some time and than start new activity public void run try sleeping threadsleepsleep time10 catch exception e logetag egetmessage start main activity intent intent new intentsplashactivitythis mainactivityclass splashactivitythisstartactivityintent splashactivitythisfinish androidmanifestxml version10 encodingutf8manifest xmlnsandroid packagecomexampedating androidversioncode1 androidversionname10 usessdk androidminsdkversion8 androidtargetsdkversion8 usespermission androidnameandroidpermissioninternet application androidallowbackuptrue androidicondrawableic launcher androidlabelstringapp name androidthemestyleapptheme activity androidnamesplashactivity intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity activity androidnamecomexampedatingmainactivity androidlabelstringapp name androidthemeandroidstylethemenotitlebarfullscreen intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity applicationmanifest,['android'] +412664,simulating button click in javascript so what i want to do is when i click on a button it will pass this click event to another element in webpage or you can say it will create a new click event in another element below is my code it does not work please let me know what is wrong with it it looks make sensedoctype htmlhtml langenheadmeta charsetutf8 link relstylesheet href script srcscriptscript srcscriptlink relstylesheet hrefresourcesdemosstylecss scriptfunction datepicker datepickerscriptheadbodypdate input typetext iddatepicker onclickalerterror pbutton typebutton valuesubmit onclickdocumentgetelementbyiddatepickerclicksubmit buttonbodyhtml,['javascript'] +412683,mysql list tables and sizes order by size what would be the query to list all tables in a database order by their size in mysql,['mysql'] +412688,is there any point to temporarily making a pointer null i have seen lots of code like thissometype ptr nullptr somemethodsome paramswhats the point i have also seen it where ptr is declared somewhere else for example in a class definition and then in the class constructor there would be thisptr nullptr somemethodsome paramsi do not understand why this is done surely the ptr null line is useless,"['c++', 'c']" +412717,ipython redirecting output of a python script to a file like bash i have a python script that i want to run in ipython i want to redirect write the output to a file similar topython my scriptpy my outputtxthow do i do this when i run the script in ipython ie like execfilemy scriptpythere is an older page describing a function that could be written to do this but i believe that there is now a builtin way to do this that i just cannot find,['python'] +412736,convert image color from grayscale to rgb opencv c basically i am trying to convert the below output image to colorrgb the image that this code currently outputs is grayscale however for my application i would like it to be output as color please let me know where i should convert the image also the code below is c and it using a function from opencv please keep in mind that i am using a wrapper to use this code in my iphone applicationcvmat cvcirclesdetectedcirclesinimagecvmat img double dp double minthist double param1 double param2 int min radius int max radius cvmat img double minthist int min radius int max radiusifimgempty cout can not open image endl return img mat cimgmedianblurimg img 5cvtcolorimg cimg cv gray2rgbvectorvec3f circleshoughcircles img inputarray circles outputarray cv hough gradient int method 1dp double dp1 1 20 minthist double minthist10 log 110 100param1 double param1100 30param2 double param230 10 50 min radius int minradius1 1 500 max radius int maxradius30 1 500 for size t i 0 i circlessize i vec3i c circlesi circle cimg pointc0 c1 c2 scalar25500 3 cv aa circle cimg pointc0 c1 2 scalar02550 3 cv aa return cimg,['c++'] +412750,how do i style all anchor tags inside a certain div i cannot figure out how to properly do this i have the following csscontainer main content a color 3b7315i am using that to supposedly style all a tags in the content div the problem is however it does not seem to style a tags inside divs or nested lists etc it only styles the topmost tags such as the followingdiv idcontent a hreflorem ipsumadivwhen i put the link inside another element the styling is goneso how do i include the whole sub elements and make the style recursively apply itself from content onwards i think i am looking for a wildcard value of sort,"['html', 'css']" +412756,how can i perfectly simulate keyevents how can i construct my own keyevent objects which perfectly or very closely match the ones i would receive from a keylistener when the enduser types somethingfor example i have a united kingdom iso keyboard layout and to type the character i press shift2 if i record this on a jframe with a keylistener i receive the following eventsjavaawteventkeyeventkey pressedkeycode16keytextshiftkeycharundefined keycharmodifiersshiftextmodifiersshiftkeylocationkey location leftrawcode16primarylevelunicode0scancode42extendedkeycode0x10 on frame0javaawteventkeyeventkey pressedkeycode50keytext2keycharmodifiersshiftextmodifiersshiftkeylocationkey location standardrawcode50primarylevelunicode50scancode3extendedkeycode0x32 on frame0javaawteventkeyeventkey typedkeycode0keytextunknown keycode 0x0keycharmodifiersshiftextmodifiersshiftkeylocationkey location unknownrawcode0primarylevelunicode0scancode0extendedkeycode0x0 on frame0javaawteventkeyeventkey releasedkeycode16keytextshiftkeycharundefined keycharkeylocationkey location leftrawcode16primarylevelunicode0scancode42extendedkeycode0x10 on frame0javaawteventkeyeventkey releasedkeycode50keytext2keycharkeylocationkey location standardrawcode50primarylevelunicode50scancode3extendedkeycode0x32 on frame0i want to create a method which i would give the as a char parameter and it would return an array of the keyevents as listed abovemy problems arein the key pressed and key released events keychar represents the character that was pressed however the keycode50 refers to the nonshifted ascii value aka 2 i need to know how to get this nonshifted value from just the characterthis nonshifted value will also be different for different keyboard layouts for example the us ansi layout requires shift to type the key which means the keycode would be 39 rather than 50on some keyboard layouts the shift key is required to type a key but not on others the character for example requires shift3 on us ansi keyboards but requires no shift press on uk iso keyboards i need to know whether i should simulate the shift pressrelease events and provide a shift modifierany insight on how to solve these problems would be appreciated i should also note that using the robot class cannot be used in my situation,['java'] +412776,print int from signal handler using write or asyncsafe functions i want to print a number into log or to a terminal using write or any asyncsafe function inside a signal handler i would prefer not to use buffered iois there an easy and recommended way to do that for example in place of printf below i would prefer write or any asyn safe functionvoid signal handlerint sig pid t pid int stat int old errno errno whilepid waitpid1 stat wnohang 0 printfchild d terminatedn pid errno old errno returnprinting strings is easy in place of the printf above i can use without printing pidwritestdout fileno child terminated 16,['c'] +412800,stringformat input string was not in a correct format the following code keep giving me error saying input string was not in a correct format but i am pretty sure it is right is not it int id 112string newdata 1 2 21 reidb reidb reidb reidb aa some description 11 20120228 20120129 true 1 1 true note note note true 1 201203 45string data cmd save magellan deal data id 0 aid 1 cid 2 ccid3 la 4 ba 5 lsa 6 bsa 7 path 8 dscp 9 si 10 cd 11 period 12 isstatic 13 lsd 14 lc 15 rb 16 notes 17 isee 18 rby 19 dpdd 20 lid 21 string cmd stringformatdata idtostring newdataanyone any ideas edit after fixing the braces a new error of index zero based must be greater than or equal to zero and less than the size of the argument list is given the newdata has 21 and plus the idtostring should be exact 22,"['c#', '.net']" +412828,java reflection performance drops when packaged as jar i have a real headscratcher here i tried everything searched everywhere it comes from an application i inherited that test jars it consists of a gui front and a commandline application that does the actual checking the gui runs the commandline app by launching a new jvm on itself java cp itselfjar comdifferentmainclass it is a bad design i know but may be relevantanyway this program contains some reflection calls nested inside two forloops the problem is that when the application is jared up the first reflection call takes exactly one second every iteration but when it runs from classes it takes a few milliseconds practically this means this commandjava jar myjarjartakes hoursthis commandjava cp bunch of jarsmyjarjar commyclassesmaintakes minutesthe jar being tested is always a jar the difference is only in the test applicationany ideas or avenues to pursue are greatly appreciated thank you,['java'] +412853,rest api with nio i have worked in the construction of a public api that will have a lot of concurrent accesses and one of the aspects that i thought is to use asynchronous io to consider the scalability aspectinitially i thought in use nginx as a http server eventdriven because he work in async way differently of tomcat the api will be constructed in java and for that i thought in use the following components tomcat 7 httpweb server java containernettyio or httpcoreresteasy rest layer w httpservlet30thispatcher servletmongodb w async java driveri have seen many thiscussions about servlet 30 because the new version has support to asynchronous requests using niobased in my problem and in the model above i have some questionsis necessary to use nettyio once that i have plans to use servlet 30 that supports asynchronous requests toouse an eventdriven webserver ex jetty is different to use a process based webserver like tomcat 7 that supports to servlet 30 that is not an eventdriven webserveri saw in many sites that nettyio works in a way where a thread can accept many requests instead of the classic way of one thread peer request in the practice how it worksasynchronous request handing servlet 30 and nonblocking io nio are different concepts in which wayi never see a rest api using nio is it a good approach which potential problems can i will have,['java'] +412875,ruby converting text file to array i am very new to ruby on rails and am using it to augment some c code my c code currently outputs data from a multidimensional array to a text file like such2 2 2 2 2 3 1 1 1 1 5 2 2 2 2 2 2 2 2 3 1 1 1 1 1 1 1 1 5 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 3 1 1 1 1 1 1 1 1 1 1 1 1 5 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 5 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 6 1 1 1 1 1 1 1 1 1 1 1 1 1 1 4 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 6 1 1 1 1 1 1 1 1 1 1 1 1 4 2 2 2 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 6 1 1 1 1 1 1 1 1 4 2 2 2 2 2 2 2 2 6 1 1 1 1 4 2 2 2 2 2 i am looking for help in converting this text output into a twodimensional array for ruby input with dynamic heightwidthso far i have been inputting them by hand into my ruby code but will soon be doing a lot more tests and i have not been able to find a way to convert this into a twodimensional ruby array so far any help would be great,"['ruby-on-rails', 'ruby']" +412892,onwindowfocuschanged and oncreate android i am trying to setup the ui elements programatically i am able to setup the ui elements in onwindowfocuschanged method the question i want to ask is shall i setup the ui elements in the oncreate method or on onwindowfocuschanged the code overrideprotected void oncreatebundle savedinstancestate todo autogenerated method stub superoncreatesavedinstancestate setcontentviewrlayoutbaselayoutandoverridepublic void onwindowfocuschangedboolean hasfocus todo autogenerated method stub superonwindowfocuschangedhasfocus if hasfocus res getresources inflater layoutinflater getsystemservicelayout inflater service setupbackgroundimage setting up the background image setuptopmenu setting up the menu on top setuplogo setting up the logo is the above approach correct,['android'] +412909,ping application in android i am making an application which will implement some features of the ping commandthe problem is i have no idea of which librarylibraries to use in android anyone have any idea for iti have visited these stackoverflow links but they werent very helpfulis there a way to make an android device answer to icmp pings addressed to the broadcast addressproblem to do ping with androidandroid debugging inetaddressisreachablehow to icmp ping on androidhow to ping external ip from java android,['android'] +412914,source for learning templating in tridion using xslt and c i am working on a project which requires tridion component templates to be written in xslt and page templates to be written in c i know xslt basics and i am totally new to ccan anyone guide me to any sources of learning xslt and c templating for tridion 2011 it would be of great help if you could thanks in advanceif there is any better way to do the templating suggestions are welcome we can see if our client is accomodative for thatregardskeirthana,['c#'] +412941,how to sort a list of generic types in java i have a set of classes that all share some common attributes so i made them all extend a common base class baseentity so i have for example foo extends baseentity and bar extends baseentityi also want lists of these foo and bar objects to be sortable so i have implemented comparable i have the classes defined as foo extends baseentity implements comparablefoo and bar extends baseentity implements comparablebar and sorting of lists of foos or bars works as expected and of course the details of the sorting are different in the different subclasses but i cannot work out how to make my sorting work when i do not know in advance whether i will have foos or bars this code for example fails to compilepublic class utilityclasst extends baseentity bunch of stuff listt values public listt sort collectionssortvalues return values more methodswith the error message bound mismatch the generic method sortlistt of type collections is not applicable for the arguments listt the inferred type t is not a valid substitute for the bounded parameter t extends comparable super ti think the problem is that i am attempting to sort a list of baseentity objects and baseentity itself does not implement comparable but now i face a problem the only sensible thing to make baseentity objects comparable to is other baseentity objects but when i add implements comparablebaseentity to baseentity the compiler tells me that i have got problems now because my foo class is trying to implement both comparablebaseentity and comparablefoo which evidently is not allowedi know i could sidestep this issue by dropping the implements comparablefoo and just implementing comparablebaseentity but then my compareto methods will have to do ugly casting and i thought that was exactly the sort of problem using generics was supposed to avoidwhat i really want to do is specify in the signature of baseentity that all its subclasses will be comparable but only to instances of the same subclass any assistance gratefully received thanks,['java'] +412955,how to openthisplay documentspdf doc without external app i want to create a program that open documents without external app i need this because i want to scroll the document with the phones orientationpitch and roll i create a button on the bottom of the screen and when i hold down the button i can scroll the document too if i release the button i cannot scroll it so if i open the document with external app my button thisappears and the sensormanager works neitherhave someone any idea to solve this problem or have someone any idea how to scroll the document opened in an external app with my phones orientationsorry for my englishthis is my manifestxml version10 encodingutf8manifest xmlnsandroidpackagecomexampleorientationscrollingandroidversioncode1androidversionname10 usessdk androidminsdkversion8 androidtargetsdkversion17 usespermission androidnameandroidpermissioninternet application androidallowbackuptrue androidicondrawableic launcher androidlabelstringapp name androidthemestyleapptheme activity androidnamecomexampleorientationscrollingmainactivity androidlabelstringapp name intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activityapplicationmanifestthis is my layoutrelativelayout xmlnsandroidxmlnstoolsandroidlayout widthmatch parentandroidlayout heightmatch parentandroidorientationvertical webview xmlnsandroid androidididwebview1 androidlayout widthmatch parent androidlayout heightmatch parent linearlayout xmlnsandroid xmlnstools androidlayout widthmatch parent androidlayout heightmatch parent androidgravitybottom androidorientationvertical button androidididmybutt androidlayout widthwrap content androidlayout heightwrap content androidtextsize25sp androidtextscroll androidlayout gravityrightlinearlayoutthis is my codeprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main setrequestedorientationactivityinfoscreen orientation portrait button button findviewbyid ridmybutt string pdf string dociframe srcurl width100 height100 styleborder noneiframe webview webview findviewbyidridwebview1 webviewgetsettingssetjavascriptenabledtrue webviewgetsettingssetpluginsenabledtrue webviewgetsettingssetallowfileaccesstrue webviewloaddata doc texthtml utf8,['android'] +413001,whats the difference between including files with jsp include directive jsp include action and using jsp tag files it seems that there are two methods for templating with jsp including files with one of these statements include filefoohtml jspinclude pagefoohtml or using jsp tag files save this as mytagtag tag descriptiondescription pageencodingutf8htmlheadheadbody jspdobodybodyhtmland in another jsp page call it with taglib prefixt tagdirwebinftags tmytag h1hello worldh1tmytagso which method should i use is one now considered deprecated or are they both valid and cover different use caseseditis not using this tag file the same as using an include save this as producttag tag descriptionproduct templage pageencodingutf8 tag importcommyaproduct attribute nameproduct requiredtrue typecommyaproductproduct name productname brquantity productquantity brand call it on another jsp with taglib prefixt tagdirwebinftags tproduct cforeach itemscartproducts varproduct tproduct productproduct cforeachtproductthat seems to me to be the very same as using an include and passing parameters to it so are tag files the same as includes,['java'] +413033,fast multiplication of k x k boolean matrices where 8 k 16 i want to find an as fast as possible way of multiplying two small boolean matrices where small means 8x8 9x9 16x16 this routine will be used a lot so it needs to be very efficient so please do not suggest that the straightforward solution should be fast enough for the special cases 8x8 and 16x16 i already have fairly efficient implementations based on the solution found here where we treat the entire matrix as an uint64 t or uint64 t4 respectively on my machine this is roughly 7080 times faster than the straightforward implementationhowever in the case of 8 k 16 i do not really know how i can leverage any reasonable representation in order to enable such clever tricks as aboveso basically i am open for any suggestions using any kind of representation of the matrices and function signature you may assume that this targets either a 32bit or 64bit architecture pick what best suits your suggestion,['c'] +413051,why mamp does not thisplay errors ok this is getting very frustrating mamp used to thisplay errors but then stopped i decided to do a fresh install of it as i could not figure it out i check my php version running 544 and go to that folder and change the phpini to thiserror reporting e allthisplay errors onstill no errors showing i go through all the folders and change all phpini files just in case nothing i fix the forced error and dump out phpinfo check the error section and thisplay errors is off what the hell i place error reportinge all ini setthisplay errors on at the start of the php file and phpinfo again local value is now on master is still off force a php error and still get server error not php error anybody have any insight i have a bug somewhere in some code and cannot find it would love for php to just tell me,['php'] +413058,check date greater than 30 days from todays date i am using jquery datepicker and tried to find out difference between todays date and selected date but getting issues rather than issues i was not able to find it perfectly i tried to do this on onselect event of datepicker questionhow to check whether selected date using jquery datepicjer is greater than 30 days from todays date any help will be appreciatednote dont want to use any libraries i need to solve this by using only jquery,"['javascript', 'jquery']" +413072,when and why would i need a jbossdeploymentstructurexml for a spring application i am trying to understand how to use jboss eap6 with spring applications i have a sample openshift application and it contains a jbossdeploymentstructurexml filei found some documentation about this file but i am not clear why and when one should use those files with spring applications the content is the followingjbossdeploymentstructure xmlnsurnjbossdeploymentstructure10 deployment dependencies module namecomh2databaseh2 module nameorgcodehausjacksonjacksoncoreasl module nameorgcodehausjacksonjacksonmapperasl module nameorgslf4j dependencies deploymentjbossdeploymentstructurewhy does one need to declare dependencies to modules and what are modules in the jboss paradigm is it possible to live without this xml file,['java'] +413078,mapview android maps api v2 inside fragment layout doesnt show i am using viewpager to swipe between 2 action bar tabs used eclipse wizard for this kind of navigation i am using android maps v2 apii want to have mapview button and textview inside one of my tabs i guess having mapfragment is not possiblei inflate layout for my fragment from xml like thispublic view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate inflate the layout for this fragment return inflaterinflaterlayoutfirst tab fragment container false my first tab fragmentxmlxml version10 encodingutf8 relativelayout xmlnsandroid androidlayout widthmatch parent androidlayout heightmatch parent comgoogleandroidgmsmapsmapview androidididmapview androidlayout width100dip androidlayout height100dip androidlayout alignparenttoptrue androidlayout alignrightidtextview1 androidlayout marginright15dp comgoogleandroidgmsmapsmapviewbutton androidididbutton1 androidlayout widthwrap content androidlayout heightwrap content androidlayout aboveidtextview1 androidlayout centerhorizontaltrue androidtextbutton textview androidididtextview1 androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentbottomtrue androidlayout alignrightidbutton1 androidlayout marginbottom133dp androidtexttextview mapview is not thisplayed just textview and button i also get no errors do i have to write some code to initialize mapview,"['java', 'android']" +413090,how to exclude field from class serialization in runtime how to exclude class field from serialization process in runtime there is transient modifier for compilation time but what about runtime i mean common java serialization with objectoutputstream not gson or somethingsorry i think i did not explain right this is not exactly about serialization but about deserialization i have batch of legacy files and handle them like thispublic class deserialize param args throws ioexception throws classnotfoundexception public static void mainstring args throws classnotfoundexception ioexception file file new filehomedeveloperworkspaceddfssomeddf hackedobjectinputstream in new hackedobjectinputstreamnew gzipinputstreamnew fileinputstreamfile systemoutprintlnattempt to open filegetabsolutepath object obj inreadobject inclose static class hackedobjectinputstream extends objectinputstream migration table holds old to new classes representation private static final mapstring class migration map new hashmapstring class static migration mapputdbobexit exitclass constructor param stream input stream throws ioexception if io error public hackedobjectinputstreamfinal inputstream stream throws ioexception superstream override protected objectstreamclass readclassdescriptor throws ioexception classnotfoundexception objectstreamclass resultclassdescriptor superreadclassdescriptor for final string oldname migration mapkeyset if resultclassdescriptorgetnameequalsoldname resultclassdescriptor objectstreamclasslookupmigration mapgetoldname return resultclassdescriptor this code works fine for most of files but some files throws exception in thread main javalangclasscastexception cannot assign instance of javaawtpolygon to field exitmsgbackpt of type javaawtpoint in instance of exitat javaioobjectstreamclassfieldreflectorsetobjfieldvaluesobjectstreamclassjava2053because of different versions of exit class new version has new fieldserror thisappearing when i add transient to new fields but another files starts to throwing an exception latest files so can i add transient to these new fileds in runtime if i detect legacy serilized file maybe reflection or something,['java'] +413131,css vertically centering a fixed positioning div i have the following html for a sortof lightbox projectdiv idlightbox img idimage src divthat is using the following csslightboxthisplaynonepositionfixedwidth100textaligncenterzindex600cursorpointerleft0top100pximagepositionrelativeheight600pxborder1px solid greyto have the image always in the horizontal center i am simply using textaligncenter on the wrapper div so i am 100 sure it will be correcti am facing problems with the vertical centering and i am using a workaround of simply setting the top value in the lightbox propertiesas you can see the height of the image is known so it is easily doable in jquery but i am looking for a pure css solutionany ideas thanks,['css'] +413175,css after pseudo element not showing up on i have an image that kind of slides up from the menu when you hover it because it is hidden under the menu i want to give the bottom of the image a little bit of deph by adding a dark fade to the bottom i figured the best way to achieve this is to use pseudo elements i do not really care much about ie support as it is such a small detailso heres what i have gotheadersection tryggehandelicon position absolute top 45px right 280px zindex 0 thisplay block stripped out some transition style here heres where the cool stuff begins headersection tryggehandeliconafter position absolute top 0px left 0px height 20px width 20px thisplay block content zindex 9px background red first off i am unsure whether to use double or single colons before after i have always used one but recently i noticed people using two so whats the way to go either seems to workyou can see it in action here it is the yellow logo popping up above the header menu why am i not seeing a 20x20 red box above the image the parent tryggehandelicon is absolute positioned so the pseudo element should show up relative to it righti have been trying to fix this for over an hour now any suggestions,['css'] +413193,jquery mobile backbone cannot call methods on listview prior to initialization im just trying to combine the advantages of backbonejs and jquery mobile im developing for mobile devices and im currently trying to develop a dynamic list for debug logging messages imagine you have got a console window and want to put entries inside the thing is that always after inserting a new the list has to be refreshed ala mylistlistviewrefresh this doesnt work for me and i get the errorerror cannot call methods on listview prior to initialization attempted to call method refreshtagname ul id console consoletemplate templateconsoletemplatehtml initialize function consolelogconsoleviewinit thiselattrdatainset true thiselattrdatarole listview thiselcsswidth 50 thiselappendthisconsoletemplate fa14r alle funktionen die mit this arbeiten bindallthis render addconsoleitem appendconsoleitem thisconsoleitemcollection new consoleitemcollection thisconsoleitemcollectionbindadd thisappendconsoleitem thiscounter 0 thisrender render function consolelogconsoleviewrender var self this thisconsoleitemcollectionmodelseachfunctionitem selfaddconsoleitemitem this return this this is an extract of my console viewvar view backboneviewextend el div id content consoleview null initialize function consolelogapplicationviewinit bindallthis render thiselattrdatarole content bindallthis render thisconsoleview new consoleview thisconsoleviewaddconsoleitemnew consoleitemmodel render function consolelogapplicationviewrender thiselappendthisconsoleviewrenderel return this this is my application viewso when call the refresh methodthank you,['jquery'] +413219,pagertabstrip position within viewpager i have the following code androidsupportv4viewviewpager androidididmain pager androidlayout widthmatch parent androidlayout heightmatch parent androidsupportv4viewpagertabstrip androidididpager tab strip androidlayout widthmatch parent androidlayout heightwrap content androidsupportv4viewviewpagerand everything gets layouted like it shouldwhat i want now is that the pagertabstrip overlays the viewpager it should be rendered on top without taking up any layouting spacebasically the fragments in the viewpager should start at 00 like the pagertabstrip is doingany help appreciated thanks,['android'] +413237,can i rely on php phpini precision workaround for floating point issue i have found some workaround for floating point problem in phpphpini setting precision 1434234923 34176507 5841592 floating point problemphpini setting let us say precision 8 34234923 34176507 58416 voilademo how bad is that1 can i rely on this solution if i need just precise 2 digits calculations money2 if not can you provide me a clear example when this solutions fails edit 3 which phpiniprecision value suits best two digits money calculations please mind i cannot use integer calculations float100 cents it is far too late for thati am not going to work on numbers higher than 106i do not need to compare numbersupdatebaba answer is good but he used precision20 precision6 in his tests so still i am not sure is it gonna work or not please consider followinglet us say precision 8 and only thing i do is addition and subtraction a b ca b cquestion 1 is precision workaround gonna fail for numbers between 09 where a and b is a number with decimal places if so please provide me an example simple test would do the job if it fails what if i use 91011 how to find when it fails ini setprecision 8 fora0a9a001 forb0b9b001 mind i do not need to test comparision roundab2 ab echo a ba b vs echo rounda b 2rounda b 2n but obviously 9 2 is too big job so i cannot run this testquestion 2 how to estimatecalculate when precision workaround fails without such crazy tests is there any mathematicial straight answer for it how to calculate is gonna to fail or noti do not need to know floating point calculations works but when workaround fails if you know precision and range of a and bplease mind i really know cents and bcmath are best solution but still i am not sure is workaround gonna fails or not for substraction and addition,['php'] +413241,how some apps can open setting app programmatically within their app i know there are many questions how to open setting app programatically and the answer is big no i know that apple does not support opening settings from any other app after ios 50but there are some apps like mapmyfitness which can open settings and they are available in the app store and have been approved by apple mapmyfitness opens the bluetooth settings if bluetooth is turned off i have checked this in ios 6 and ios 51i want to know how can these apps are able to open settings legally and bypassed apple security because as per my information there is no legal way to do it,"['iphone', 'ios', 'objective-c']" +413251,using requirejs alongside nonamd javascript files i am trying to convert a javascriptheavy page to use typescript with requirejs to manage the module dependenciesthe problem i have got is that as well as the interdependencies between the typescript files the page also depends on some common javascript files that are shared with other parts of the system not yet converted to amdis it very dangerous to put nonamd scripts in normal script tags above the tag for require and just assume that they are loadedif that is a bad idea whats a better way to handle this do i need to have amd and nonamd version of each script or do i need to convert all scripts so that they optionally call define,['javascript'] +413255,why can you access static field before it is defined through a method in java i ran into an interesting thingstatic systemoutprintlntest error cannot reference a field before it is defined systemoutprintlncheat ok private static boolean cheat return testprivate static boolean test truepublic static void mainstring args the first way is wrong and both your compiler and ide will tell you it is wrong in the second case cheating is ok but it actually defaults the field test to false using sun jdk 6,['java'] +413274,is it better to use hbase columns or serialize data using avro i working on a project that stores keyvalue information on a user using hbase we are in the process of redesiging the hbase schema we are using the two options being thiscussed areuse hbase column qualifiers as names for the keys this would make rows wide but very sparse dump all the data into a single column and serialize it using avro or thrift what are the design tradeoffs of the two approaches is one preferable to the other are they are any reasons not to store the data using avro or thrift,['java'] +413328,android replace character from string i have a string variable that contains in it but before using it i have to replace all this characteri have tried replaceall function but without successtext textreplacealltext textreplaceallnullcould someone help me thanks,"['java', 'android']" +413355,setting the default json serializer in aspnet mvc i am having a hard time finding the answer to thisi am working on an existing application that has been partially converted over to mvc whenever a controller responds with a json actionresult the enums are sent as numbers opposed to the string name it sounds like the default serializer should be jsonnet which should be sending the enums over as their names opposed to the integer representation but that is not the case heream i missing a webconfig setting that sets this as the default serializer or is there another setting that needs to be changed,['c#'] +413360,how to make a function accept arbitrary number of arguments not using f a piece of code is worth a thousand wordsint main all of the following calls return true areequal1 1 areequal1 1 1 areequal1 1 1 1 areequal1 1 1 1 1 all of the following calls return false areequal1 2 areequal1 2 1 areequal1 7 3 1 areequal1 4 1 1 1 how to implement the function areequal that accepts arbitrary number of argumentsthe trivial but tedious soultion is through overloadingbool areequalint v1 int v2bool areequalint v1 int v2 int v3bool areequalint v1 int v2 int v3 int v4another trivial but not workable solution isbool areequalthis solution is not workable because the caller must add another argument argument count or ending marker to specify the number of the argumentsyet another way is through variadic template argumentstemplateclass argsbool areequalargs args what should be placed here,['c++'] +413391,getwidth returns 0 if set by androidlayout widthmatch parent i have a class called fractalview that extends imageview my goal is to draw a fractal with this class that has the size of the whole screen it is the only view in my activitys layout file other than the toplevel linearlayoutxml version10 encodingutf8linearlayout xmlnsandroid androidorientationvertical androidlayout widthmatch parent androidlayout heightmatch parent androidbackgroundf comantoncfractal wallpaperfractalview androidididfractal androidlayout widthmatch parent androidlayout heightmatch parent androidvisibilitygonelinearlayoutas you can see i am using match parent for both layout width and layout height of both the fractalview and the linearlayout at this point i assumed that the size of the fractalview is set to a certain value since it is matching it is parent which is matching it is parentwhich is the whole screen then i try to detect the size that is available to fractalview by using getwidth and getheightpublic class fractalview extends imageview private context mcontextprivate handler mhandlerprivate int mscrwidthprivate int mscrheightpublic fractalviewcontext context supercontext mcontext context initprivate void init mscrwidth getwidth mscrheight getheight breakpointoverrideprotected void ondrawcanvas canvas but when my code reaches the breakpoint the debugger shows that mscrwidth and mscrheight are zero i have tried using getmeasuredwidth and getmaxwidth but they also return incorrect values i have read several answers to similar questions ie this one and they all explain that getwidth returns the size of an image after it has been drawn while what i actually need is the width of the area which is available to this view before i start drawingis there a way to retrieve such values for width and height,['android'] +413393,android remote service callbacks i have a remote service with an aidl interface that is used by several client apps i would like to add an asynchronous method to the interface for calls that take some time but i need the solution to be secure meaning that only my applications can communicate with the service the client applications are signed with the same signature as the service app currently the apps just bind to the service and call a single interface method to perform various operationsone option is broadcasting an intent from the service when the operation is complete and using a broadcastreceiver in the client application but question 1 can this be done in a way that ensures only my apps can receive the intent setpackage seems to do this but i need to support gingerbread devices which seems to rule out that approach according to the answer here setpackage for intent in gingerbreadso it seems i need to add a second aidl interface with the callback interface for the service to use implemented by the client i have seen examples that use listeners here but i am not sure what the difference is versus the client just passing in the second interface object as an argument as used in the iscript iscriptresult example from this answer service call backs to activity in androidquestion 2 what is the benefit of using a listener here vs a callback method,['android'] +413430,python readonly property i do not know when attribute should be private and if i should use propertyi read recently that setters and getters are not pythonic and i should use property decoratorit is ok but what if i have attribute that must not be set from outside of class but can be read readonly attribute should this attribute be private and by private i mean with underscore like that self xif yes then how can i read it without using getteronly method i know right now is to writepropertydef xself return self xthat way i can read attribute by objx but i cannot set it objx 1 so it is finebut should i really care about setting object that must not be set maybe i should just leave it but then again i cannot use underscore because reading obj x is odd for user so i should use objx and then again user does not know that he must not set this attributewhats your opinion and practics,['python'] +413451,how to integrate flurry analytics into ios app i have flurryh and libflurrya added to my project from the flurry 41 sdk in my app delegate i have the following in didfinishlaunchingwithoptionsflurry startsessionapikeyi have also added flurry logeventcallapipath in the codebase such that it will get called 5 or 6 times in a typical session however i do not see any data on my flurry dashboard i am testing in the ios simulator and click the home button to quit the app since that was suggested in i have given it over 24 hours to process but still no datai do not see any obvious problems in the debug output20130129 160404579 tumtiki7578c07 flurry startsession called for the first time20130129 160404580 tumtiki7578c07 flurry start session called with apikeyapikey20130129 160404580 tumtiki7578c07 flurry trim white space and use apikeyapikey20130129 160404581 tumtiki7578c07 initial network status 1 20130129 160404583 tumtiki7578c07 flurrysession add session with starttime20130129 230437 0 to saved sessions20130129 160404587 tumtiki7578c07 flurrysession add crashed former session20130129 160404589 tumtiki7578c07 flurrysession initialized session from scratch with starttime20130130 0404 020130129 160404590 tumtiki7578c07 flurrysession created active session with apiapikey20130129 160404590 tumtiki7578c07 flurrysession session reports on close enabled120130129 160404590 tumtiki7578c07 flurrysession session reports on pause enabled120130129 160404591 tumtiki7578c07 flurrysession event logging enabled120130129 160404591 tumtiki7578c07 flurrysession sending sessions to server withtimeout020130129 160404593 tumtiki7578c07 flurrysession initial timestamp20130129 181218 0 from saved source20130129 160404594 tumtiki7578c07 flurry finish starting session with apikeyapikey20130129 160404603 tumtiki7578c07 flurrysession recording event eventnamecallapipath with parametersnull20130129 160404603 tumtiki7578c07 flurrysession event count for eventnamecallapipath updated to count120130129 160404603 tumtiki7578c07 flurrysession event log for eventnamecallapipath updated20130129 160404604 tumtiki7578c07 flurrysession recording event eventnamecallapipath with parametersnull complete20130129 160404660 tumtiki7578c07 flurrysession dealloc session20130129 160404687 tumtiki7578c07 updated network status 1 20130129 160404786 tumtiki7578c07 flurry http connection delegate received responsenshttpurlresponse 0xa4b82e020130129 160404787 tumtiki7578c07 flurrysession async http response code 20020130129 160404788 tumtiki7578c07 flurrysession application sent session120130129 160404788 tumtiki7578c07 flurrysession sent 1 sessionspressed home button20130129 160708166 tumtiki7578c07 flurrysession pause session with pausetime20130130 0708 020130129 160708166 tumtiki7578c07 flurrysession ending session with endtime20130130 0708 020130129 160708167 tumtiki7578c07 flurrysession ending all unterminated timed events with endtime20130130 0708 020130129 160708167 tumtiki7578c07 flurrysession finished ending unended timed events20130129 160708168 tumtiki7578c07 flurrysession ending session with endtime20130130 0708 0 complete20130129 160708168 tumtiki7578c07 flurry start background task20130129 160708169 tumtiki7578c07 flurrysession sending sessions to server withtimeout120130129 160708171 tumtiki7578c07 flurrysession initial timestamp20130129 181218 0 from saved source20130129 160708387 tumtiki7578c07 flurry http connection delegate received responsenshttpurlresponse 0x1127cf3020130129 160708389 tumtiki7578c07 flurrysession async http response code 20020130129 160708390 tumtiki7578c07 flurry stop background taski am using the api key provided by flurry which is a 20 character string is there a different application key i should be using instead i am doing something wrong here but have not been able to figure it out yet,['ios'] +413495,how to center icon in android action bar i am trying to center the icon in the android action bar i am using a custom layout that has a button on the left side an icon in the center and the menu options on the right xml version10 encodingutf8relativelayout xmlnsandroid androidididactionbarwrapper androidlayout widthmatch parent androidlayout heightmatch parent androidorientationvertical imagebutton androidididslidemenubutton androidlayout widthwrap content androidlayout heightwrap content androidsrcdrawableic menu bookmark relativelayout xmlnsandroid androidididrelativelayout1 androidlayout widthwrap content androidlayout heightwrap content androidorientationvertical androidlayout centerinparenttrue imageview androidididicon androidlayout widthwrap content androidlayout heightwrap content androidsrcdrawableic launcher androidlayout centerinparenttrue relativelayoutrelativelayouti have tried this with and without the relativelayout wrapping the imageview the left button shows up fine and i can set the icon with layout torightof but i cannot get it to center anyone have any ideaseditheres the android code in the on create methodactionbar actionbar getsupportactionbar actionbarsetthisplayshowtitleenabledfalse actionbarsetthisplayuselogoenabledfalse actionbarsetthisplayhomeasupenabledfalse actionbarsetthisplayshowcustomenabledtrue actionbarsetthisplayshowhomeenabledfalse actionbarsetthisplayoptionsactionbarthisplay show custom view cview getlayoutinflaterinflaterlayoutactionbar null actionbarsetcustomviewcview,['android'] +413503,jquery datatable add id to tr element after row is dynamically added i am using this code to init datatable tablegroupsdatatable bjqueryui true spaginationtype full numbers bfilter false binfo false alengthmenu 10 25 50 1 10 25 50 all aocolumns sclass name sclass tools bsortable false now i am adding rows via serverside script like thistablegroupsdatatablefnadata strong returnvaluenamestrongdiv classcell edit group id is returnvalueentryid div and my question is there a way to insert value of returnvalueentryid to be id of the tr,['jquery'] +413517,why log4js loggergetlogger need pass a class type i read some articles about how to use log4jmost of them give below code as a beginning logger logger loggergetloggercomfoobaror logger logger loggergetloggerxclassthis will initialize the logger objectbut my question is why need send the class type as pramameter it seems when i use the logger i do not care in which class i use itso the class type seems no effect to loggerif i declare a logger as static and public i can call this logger at another class so whats the intention of the author to desgin it like this will the class type bind someting when i use the logger or i can send any class types to the getlogger function,['java'] +413524,passes not enabled in provisioning profile here were my stepsi created a passtype id using passcomdomainappname stylei created an app id for comdomainappnamei enabled passes in the app idi created a new provisioning profile with the app id created earlieri opened my project in xcode set the code signing identity to the profile i had just made i enabled entitlements and under passes told it to use the ones in my provisioning profile it said that passes were not enabled what am i doing wrong,['ios'] +413544,how to combine date and time from two uidatepickers i have two uidatepickers in my app one mode is for selecting date and other to time mode i have fired a notification when the exact date and time is reached i am able to fire the reminder at correct time but the problem is that the date is not checked is there any way to check the date and time at the same timethanx in advanceeditnsdate date1 datepicker datensdate date2 timepicker datenscalendar gregorian nscalendar alloc initwithcalendaridentifiernsgregoriancalendarunsigned unitflagsdate nsyearcalendarunit nsmonthcalendarunit nsdaycalendarunitnsdatecomponents datecomponents gregorian componentsunitflagsdate fromdatedate1unsigned unitflagstime nshourcalendarunit nsminutecalendarunit nsdatecomponents timecomponents gregorian componentsunitflagstime fromdatedate2datecomponents sethourtimecomponents hourdatecomponents setminutetimecomponents minutensdate combdate gregorian datefromcomponentsdatecomponents uilocalnotification localnotif uilocalnotification alloc initif localnotif nil returnnsdate firetime combdatelocalnotiffiredate firetimelocalnotifalertbody alertlocalnotifsoundname uilocalnotificationdefaultsoundname uiapplication sharedapplication schedulelocalnotificationlocalnotif,"['iphone', 'ios']" +413580,trying to delay cabasicanimation position and opacity of layer by 3 seconds but i am trying to delay the animation of layers opacity and position by 3 seconds using setbegintime i have called the layer boxlayer the animation is going well however during the first 3 seconds the layer is not supposed to show yet the layer is thisplayed at its final position and opacity it should not group animation does not resolve the issue could anyone help see code below create an animation that will change the opacity of a layercabasicanimation fader cabasicanimation animationwithkeypathopacity it will last 1 second and will be delayed by 3 secondsfader setduration10fader setbegintimecacurrentmediatime30 the layers opacity will start at 00 completely transparentfader setfromvaluensnumber numberwithfloatstartopacity and the layer will end at 10 completely opaquefader settovaluensnumber numberwithfloatendopacity add it to the layerboxlayer addanimationfader forkeybigfade maintain opacity to 10 just to make sure it does not go back to original opacityboxlayer setopacityendopacity create an animation that will change the position of a layercabasicanimation mover cabasicanimation animationwithkeypathposition it will last 1 second and will be delayed by 3 secondsmover setduration10mover setbegintimecacurrentmediatime30 setting starting positionmover setfromvaluensvalue valuewithcgpointcgpointmakestartx starty setting ending positionmover settovaluensvalue valuewithcgpointcgpointmakeendx endy add it to the layerboxlayer addanimationmover forkeybigmove maintain the end position at 40 4500 otherwise it is going back to original positionboxlayer setpositioncgpointmakeendx endy,['ios'] +413582,reducing size of jre in javafx bundle i created a javafx application for it i bundled it as a selfcontained standalone application using a private copy of java runtimebut this became my applications size of 166mb in which 146 mb size is for jrehow can i reduce the size of my application or can say size of bundle runtime jrei read somewhere that some files are optional in jre so i tried to run my application after removing those files but unable to run the applicationso how can i remove the unused filesfoldersmodules from the runtime jre for my application it is said that only a subset of java runtime is included by default some optional and rarely used files are excluded to reduce the package size such as all executables if you need something that is not included by default then you need to copy it in as a postprocessing stepso by default it is not adding all the files in jre in that case my application is not running applicationjar is working fine as it is using system jarso i add all the reamaining files in postprocessing stepthanks,['java'] +413629,how to send and receive json data from a restful webservice using jersey api pathhellopublic class hello post pathid producesmediatypeapplication json consumesmediatypeapplication json public jsonobject sayplaintexthellopathparamidjsonobject inputjsonobj string input string inputjsonobjgetinput string outputthe input you sent is input jsonobject outputjsonobj new jsonobject outputjsonobjputoutput output return outputjsonobj this is my webservice i am using jersey api but i could not figure out a way to call this method from a java rest client to send and receive the json data i tried the following way to write the clientclientconfig config new defaultclientconfigclient client clientcreateconfigwebresource service clientresourcegetbaseurijsonobject inputjsonobj new jsonobjectinputjsonobjputinput valuesystemoutprintlnservicepathrestpathhelloacceptmediatypeapplication jsonentityinputjsonobjpostjsonobjectclassjsonobjectclassbut this shows the following error exception in thread main comsunjerseyapiclientclienthandlerexception comsunjerseyapiclientclienthandlerexception a message body writer for java type class javalangclass and mime media type applicationoctetstream was not found,['java'] +413635,best practice to insert null to mysql using php function savegmt name address phone remark query insert into user gmt name address phone remark values gmt name address phone remark mysql queryqueryhere address phone and remark can be null value i need it so that when i pass a null parameter into my function it stores an empty value in the database null i need to know what the best solution for doing this isthanks,"['php', 'mysql']" +413672,how handler classes work in android i am new to android and was reading the demo applications on official android website and i came across a method of handler class named as postdelayedrunnable r long millisecondscan anybody please explain what this method does,['android'] +413692,why does not java allow hiding static methods by instance methods as shown in java does allowoverriding an instance method by an instance method andhiding a static method by a static methodmy question is why java does not allow hiding a static superclass method by an instance method this could be done like thisclass base static void foo class derived extends base void foo void access foo basefoo i do not see any particular issue with the above approach it is only as messycomplex as the allowed hiding of statics already is,['java'] +413706,using joda time to get utc offset for a given date and timezone i have dates in the format 20jan2013 08aug2012 etc with their own specific timezones so for example 20jan2013 might have a timezone id of australiamelbourne and 08aug2012 might have an id of europelondon what i want to do is based on these timezones and the dates calculate the utc offset for that timezone on the given date i have come up with this so fardatetimeformatter dtf datetimeformatforpatternzzdatetimeformatter dtf1 datetimeformatforpatternddmydatetimezone zone datetimezoneforidaustraliamelbourne datetime thisdate dtf1parsedatetime30jul2013 systemoutprintlnnzone thisdatewithzonezonethis gives me the output zone 20130730t010this is correct but i would like to extract just the utc offset from this which in this case is 10 i have looked for ways to do this but cannot find anything is there any way i can do this the only option i see is to convert the output to a string and use the substring method to get the utc offsetthe above code does take dst daylight saving time into account so for example if i had datetime thisdate dtf1parsedatetime30jan2013 the output would be 20130130t01100 1100 at the end instead of 10 so basically all i need to do is find a way to extract 1100 from 20130730t01100 please help,['java'] +413732,hide jquery ui bootstrap tab is there any way to hide the jquery ui bootstrap tabi have written code below to show the particular tab mytab alasttabshowso i tried using below code to hide tab but it gives error that it has no method hide mytab alasttabhidei have declared tabs in following way in my html ul classnav navtabs idmytab lia hrefproduct datatoggletabcompanyali lia hrefversion datatoggletabemployeeali ul,['jquery'] +413736,how to merge fonts i have a number of fontsopensansboldttfopensansbolditalicttfopensansextraboldttfopensansitalicttfopensanslightfhow would i go on about to just create one file as oppose to this many different filesand perhaps use them on css like i would normally or like you would on photoshopegsmallfontfamilyopensans fontweight normalstrongfontfamilyopensans fontweight boldh2 fontfamilyopensans fontweight bolderany help would be appriciated,['css'] +413773,visualize bipartite graph can someone recommend a library or code to visualize bipartite graphs in cgraph seems not to support this kind of graph directly but hassome support to thisentangle verticesi want to create some graphic like this bipartite graph with some text in the nodes nodes being same width and height would be ideala wpf control would be perfect as it exists for graphperhaps even a xaml definition existsas an alternativ a report window can also be very goodprobably someone with more experience in graph can provide hints on how to do thisutilizing graphtried around a bit with nodexl but that seems not to be the perfect solutionas the nodes seems not be that much modifiable perhaps someone can provide a better solution have played with the networkview provided by soroush at the moment this comes closest to what i want updatetried out networkview shared by soroush falahati this seems to be a good basebut is not yet that flexible as i need it i have problems to believe that thereis no library out there that can do those things out of the box networkview has the excellent feature to set connections edges in the controlwhich gives it an extra boost over the nodexl perhaps graph can do even morebut at the moment i just have tried those two,['c#'] +413850,good practice for working with multiple solutions in visual c express background my team is made up of 3 fairly inexperienced developers we are developing inhouse software for our company currently we have a number of smaller and separate solutions many of these are interdependent currently these depencies are made by referencing the output dlls in the respective releasefolder updates are pushed around by manually rebuilding dependent solutions examplesolution a uses features of solution b the connection is made having solution a referencing releasebdll changes to b propagates by building solution b then building solution a and so forth this has worked okay before but now we are moving from a manual mind numbing version control system folder1 folder2 folder2new to using a proper one git it seems that versioning the dlls is not recommended this means that every time someone wants to build a new version of a he also needs to build b and maybe 5 other solutions in order to have the latest version of bi am thinking that there must be a better way to do thisi have been looking at combining the relevant solutions into one master solution but i cannot figure out how to do this in visual c express which we are usingso at long last the questionsis having a master solution that builds everything the way to go it seems so from msdn but i cannot figure out how to do this in visual c express 2008 which leeds me to is this even possible in visual c express if not what is agood way of managing the problemedit thanks to all for the great suggestions below heres a summary of what i ended up doingin short the answers to the questions are yes and sort of but mostly yes i implemented as follows in order to get an idea of the dependencies i did as suggested below and drew a map of the binary products with an arrow pointing from the dlls or exes name to all of its dependencies for each project i opened its corresponding solution since at first there was one solution pr project i then added the projectfile of each dependency in the tree structure revealed in the graph by rightclicking the solution in solution explorer so that also dependeciess dependencies and so forth were included then i removed the old references pointing directly to the dlls and added references to the projects insteadthe important result iswhen a solution of a project is built all it is dependencies are built with it so that when deploying you know that all the build products are automatically of the latest version,['c#'] +413854,mysql create a simple function i want to create a simple mysql function i have this mysql procedurecreate procedure getusergu int select from company where id number gucall getuser2i need some help making this into a mysql function what are the pros and cons of using a function over a procedure,['mysql'] +413865,type constraints in interface apply to base class i have a base class that defines a generic method like thispublic class baseclass public t dosomethingt as this class is by a thirdparty and does not come with an interface i am defining an interface that defines the actually needed methods from that class that way i get loose coupling and can actually exchange that thirdparty class with something else for this example consider the following interfacepublic interface isomething t dosomethingt where t fooas you can see it defines the same method but also applies a type constraint on the type parameter which comes from some other requirements that are not relevant to thisnext i define a subtype of baseclass which also implements isomething this class will be used as the usual implementation behind the interfaceawhile the interface will be what the rest of the application will be accessingpublic class something baseclass isomething as the dosomething in baseclass already supports any type parameter t it should especially support a type parameter which is a subtype of foo so one would expect that a subtype of baseclass already implements the interface however i get the following errorthe constraints for type parameter t of method baseclassdosomething must match the constraints for type parameter t of interface method isomethingdosomething consider using an explicit interface implementation insteadnow i have two possibilities the first one is to do what the error suggests and implement the interface explicitely the second is to hide the base implementation using new explicit implementationt isomethingdosomethingt return basedosomethingt method hidingpublic new t dosomethingt where t foo return basedosomethingtboth work although iad probably prefer the second solution to keep the method accessible from the class itself however it still leaves the following questionwhy do i have to reimplement the method when the base type already implements it with a lestrict read none type constraint why does the method need to be implemented exactly as it isedit to give the method a bit more meaning i changed the return type from void to t in my actual application i have both generic arguments and return values,['c#'] +413887,the character breaks passwords that are stored in the webconfig i have an aspnet mvc3 c net application running on iis 75 we have a windows nt service account we impersonate in our code in order to readwrite documents to a file share the user id is compiled in the code and the service account password is stored in the webconfig file the password contains an ampersand character ie pssword this broke the site when accessing the site we received this error sorry an error occurred while processing your request here is the code that uses the password var password configurationmanagerappsettingsgetcommonsvc pwd bool issuccess logonuser my svc acct mydomainnet password logon32 logon new credentials logon32 provider default ref token why would this cause the site to break,"['c#', 'asp.net', '.net']" +413895,overloading generics in java i want to run certain tests in lists the lists can contain entirely different classesi have one method to check the consistency of the list not null not empty no more than x elements this is common to all the lists then i want to test each of the objects using overloadingthe idea would be something likepublic static t void checklistt list do general checks for t element list checkelement and thenpublic static void checksometype element public static void checksomeothertype element but i also had to add a method like thispublic static void checkt element and this was called at runtime not my other methods with the specific classes although the class was exactly the same i am evidently missing some generics understandingnow if i do not use the general method at all and try to solve it this way public static void checklistsometype list public static void checklistsomeothertype list compiler error method checklist has the same erasure checklist as another methodso is there any elegant solution for this i could just use different method names but would like to know how it is possible without thatthanks,['java'] +413924,jquery mobile how to detect refresh some backgroundby default when you click a link to a separate html page jqm loads the first datarolepage on that page and attaches it to the dom of the first page the thing is jqm only loads that page div and not any scripts etc that are outside that container i have a jquery mobile app with 5 pages loginhtml menuhtml accounthtml settingshtml etci change pages with like mobilechangepageaccounthtmlalso i put all my page load logic to my first page loginhtml like thisscript documentonpageinit loginpage function do some stuff run some ajax scripts and add some html to its body documentonpageinit accountpage function do some stuff run some ajax scripts and add some html to its body documentonpageinit settingspage function do some stuff run some ajax scripts and add some html to its body scriptwhile this app works well problem is i find it very fragile and hard to survive from unexpected errors for examplesince how every pages body html will load is defined in loginhtml this means if any moment user manually refreshs any of these pages the page will load without running those scripts and load an empty page a without a body in that moment since the correct dom is deleted from memory user is stuck in an app with full of empty pages only way is he is smart enough to go and type loginhtml to address bar and only then all process can start smoothlyi think we cant 100 hide address bar it is visible again after scroll downso this is one problem i come up with some other weird things can happen and if somehow the dom gets corrupted only way to use app again is typing loginhtml address bar which users probably will not thing about ithow can i make this app more robust like detecting any dom corruption or refresh and forward the user to loginhtml so he does not stuck in an app with empty pages,"['javascript', 'jquery', 'html']" +413945,python first and last element from array i am trying to dynamically get the first and last element from an array so let us suppose the array has 6 elements test 1234678if i am trying to get the first and last 18 237 and 46 is there a way to get elements in this order i looked at a couple of questions link link2 i took help of these links and i came up with this prototypeusrbinenv pythonimport numpytest 1234678test1 numpyarray1234678len test lentestfirst list 012len first lenfirst listsecond list 123len second lensecond listfor a in rangelen first print numpyarraytestfirst lista second lista print test1first lista second listabut this prototype would not scale for if you have more than 6 elements so i was wondering if there is way to dynamically get the pair of elementsthanks,['python'] +413956,unreliable results with cv2houghcircles i have a video with 5 oil droplets and i am trying to use cv2houghcircles to find themthis is my codeimport cv cv2import numpy as npforeground1 cv2imreadforeground1jpgvid cv2videocapturenb14avicv2namedwindowvideocv2namedwindowcannycv2namedwindowblurwhile true ret frame vidread subtract1 cv2subtract foreground1 frame framegrey1 cv2cvtcolorsubtract1 cvcv rgb2gray blur cv2gaussianblurframegrey1 00 2 circles cv2houghcirclesblur cv2cvcv hough gradient 2 10 nparray 40 80 5 100 if circles is not none for c in circles0 cv2circleframe c0c1 c2 025502 edges cv2canny blur 40 80 cv2imshowvideo frame cv2imshowcanny edges cv2imshowblur blur key cv2waitkey30i would say that the canny edge detector looks very good while the results from the hough transform are very unstable every frame will provide different resultsexamplei have been playing with the parameters and honestly i dont know how to get more stable results,['python'] +413969,android memory leak in apache harmonys jarurlconnectionimpl i am working on an android app and were investigating memory uselooking at a heap dump from hprof were seeing nearly 2m 22 of our heap being used in a static cache in jarurlconnectionimpllooking at the source code for jarurlconnectionimpl it appears that entries are added to the static jarcache variable but never removed if it is true that they are never removed that strikes me as a potential memory leakis this a leak is there a fix or workaround,['android'] +413993,how to connect to facebook graph api from python using requests if i do not need user access token i am trying to find the easiest way how to use facebook graph api using my favorite requests library the problem is all examples i found are about getting user access token about redirects and user interactionall i need is only application access token i do not handle any nonpublic data so i need no user interaction and as my final app is supposed to be commandline script no redirects are desiredi found something similar here but it seems to be everything but elegant moreover i would prefer something using requests or requestsoauth2 or maybe there is library for that i found requestsfacebook and facepy both requests based but again all examples are with redirection etc facepy does not handle authorization at all it just accepts your token and it is up to you to get it somehowcould someone please provide a short sane working example how to get just the application access token,['python'] +413995,why everyone states that spinlock is faster i have read a lot of docs and articles and posts all over the internetalmost everyone and everywhere commits that spinlock is faster for a short running pieces of code but i made a test and it appears to me that simple monitorenter works faster than spinlockenter test is compiled against net 45using systemusing systemcollectionsconcurrentusing systemcollectionsgenericusing systemdiagnosticsusing systemthreadingtasksusing systemlinqusing systemglobalizationusing systemcomponentmodelusing systemthreadingusing systemnetsocketsusing systemnetclass program static int loopscount 10 static int threadscount 1 static processpriorityclass processpriority processpriorityclassrealtime static threadpriority threadpriority threadpriorityhighest static long testingvar 0 static void mainstring args threadscount environmentprocessorcount consolewritelinecoresprocessors count 0 environmentprocessorcount processgetcurrentprocesspriorityclass processpriority timespan tsinterlocked executeinterlocked timespan tsspinlock executespinlock timespan tsmonitor executemonitor consolewritelinetest with interlocked 0 msrntest with spinlock 1 msrntest with monitor 2 ms tsinterlockedtotalmilliseconds tsspinlocktotalmilliseconds tsmonitortotalmilliseconds consolereadline static timespan executeinterlocked testingvar 0 manualresetevent startevent new manualreseteventfalse countdownevent endcountdown new countdownevent threadscount thread threads new thread threadscount for int i 0 i threadslength i threadsi new thread starteventwaitone for int j 0 j loopscount j interlockedincrementref testingvar endcountdownsignal threadsipriority threadpriority threadsistart stopwatch sw stopwatchstartnew starteventset endcountdownwait return swelapsed static spinlock spinlock new spinlock static timespan executespinlock testingvar 0 manualresetevent startevent new manualreseteventfalse countdownevent endcountdown new countdownevent threadscount thread threads new thread threadscount for int i 0 i threadslength i threadsi new thread starteventwaitone bool locktaken for int j 0 j loopscount j locktaken false try spinlockenterref locktaken testingvar finally if locktaken spinlockexit endcountdownsignal threadsipriority threadpriority threadsistart stopwatch sw stopwatchstartnew starteventset endcountdownwait return swelapsed static object locker new object static timespan executemonitor testingvar 0 manualresetevent startevent new manualreseteventfalse countdownevent endcountdown new countdownevent threadscount thread threads new thread threadscount for int i 0 i threadslength i threadsi new thread starteventwaitone bool locktaken for int j 0 j loopscount j locktaken false try monitorenter locker ref locktaken testingvar finally if locktaken monitorexit locker endcountdownsignal threadsipriority threadpriority threadsistart stopwatch sw stopwatchstartnew starteventset endcountdownwait return swelapsed on a server with 24 cores of 25 ghz this application compiled with x64 produced the following resultscoresprocessors count 24test with interlocked 13730829 mstest with spinlock 108946283 mstest with monitor 11711591 ms,['c#'] +414008,pdo on duplicate key update rowcount in mysql table returns double amount of updated records i am working on a project where i upload a csv and update a mysql tableat the end of my sql insert statement i have an on duplicate key update statementmy problem is pdo rowcount seems to be returning 2x for updated rowsfor example when i upload the csv the first time i get a total of 100 rows count of csv rows and rowcount returns 100 which makes sense because i inserted 100 rowshowever if i upload the same file again all 100 rows are updated i update a unix timestamp and rowcount returns 200 i assume this is because rowcount returns 2 for each update and 1 for an insertare my assumptions correct has anyone run into this before and is there a solution that does not involve 100 separate insert statements i would like to be able to thisplay the total number of rows in the csv the total new rows inserted and the total rows updatedsql insert into projects implodefields values rowcount countcsvdata tmp array for i 0 i rowcount i placeholders array foreach fields as keyval do some post processing for special characters switchval case description value emptycsvdatai postval csvdatai postval null array pushtmpvalue break case country value empty csvdatai postval implode array uniqueexplode csvdatai postval null value str replacearrayvalue array pushtmpvalue break case add unixtime array pushtmptime break case project type array pushtmpstrtolowerformdataproject type break default value emptycsvdatai postval str replacearraycsvdatai postval null array pushtmpvalue break array pushplaceholders sql implodeplaceholders detect duplicate projects based on project number project type mysql unique index created with project number project type if duplicate found update row sql rtrimsql sql on duplicate key update foreachfields as keyval sql val values val sql rtrimsql update database query thisdbcpreparesql if queryexecutetmp result arraytotal rowsrowcountmodified rowsqueryrowcount return result return resulthere is the query generated for a 3 row insertinsert into projects project number project value project name address1 address2 city state zip country description project type add unixtime values on duplicate key update project number valuesproject number project value valuesproject value project name valuesproject name address1 valuesaddress1 address2 valuesaddress2 city valuescity state valuesstate zip valueszip country valuescountry description valuesdescription project type valuesproject type add unixtime valuesadd unixtime,"['php', 'mysql']" +414048,set checked radio button using a javascript variable is there a way to set the checked radio button using a javascript variable i was hoping i could get the radio button by id and update the checked radiodoctype html public w3cdtd xhtml 10 transitionalen html xmlnsheadmeta httpequivcontenttype contenttexthtml charsetutf8 titleuntitled documenttitlescriptvar shirtcolor greendocumentgetelementbyidshirtcolor scriptheadbodypshirt colorinput typeradio nameshirtcolor idred valuered redinput typeradio nameshirtcolor idgreen valuegreen greeninput typeradio nameshirtcolor idblue valueblue bluepbodyhtml,"['javascript', 'html']" +414051,using haml with the inlineblock spacing gaps so i read the solutions regarding making the spacing go away when using inlineblock as opposed to floats thisplay inlineblock extra margin and so if youre using haml and want to put the closing tag on the same line as the next opening tag is there is a solution besides switching to erband no i do not want to mess with a css property of the parent container and have to override that in all the child elementsthis breaks has spacing between the anchorsso is it true that in spite of the recommendations to do such layouts using inlineblock as opposed to floats it seems that floats are still the way to go especially when using hamlcssnav a thisplay inlineblock padding 5px background redhtmlnav a hrefonea a hreftwoa a hrefthreeanavworkaround csstricks oneul li onelili twolili threeliulorul lioneli litwoli lithreeliulanother oneul lioneli litwoli lithreeliul,['css'] +414052,do i need a doctype declaration in a php file with html i have a php file with my website content in it the file needs to be php because i get some variables first and then use it later in the website content like this examplephpuser name requestusernamedoctype htmlhtmlhead meta charsetutf8 titlepage titletitle link relstylesheet hrefcstylecss headbodywelcome php echo usernamebodyhtmldo i need the doctype html since the file extension is php also is it placed corretly should it come before the tag or in the very first line of my filei also noticed that if i remove the doctype html some of my css code stops workingthank you very much,"['php', 'html']" +414077,inotifypropertychanged and static properties i am tying myself in knots over a simple problem i have a class that implements inotifypropertychanged some of the instance properties getters use static properties and thus their values may change if the static property changes heres a simplified example class exampleclass inotifypropertychanged private static int minimumlength 5 public static int minimumlength get return minimumlength set if minimumlength value minimumlength value what goes here private int length 1 public int length get return length minimumlength length minimumlength set var oldvalue length minimumlength length minimumlength if length value length value var newvalue length minimumlength length minimumlength if newvalue oldvalue onpropertychangedlength public event propertychangedeventhandler propertychanged notifypropertychangedinvocator protected virtual void onpropertychangedstring propertyname if propertychanged null propertychangedthis new propertychangedeventargspropertyname clearly if the static property minimumlength changes then every instances property length may also change but how should the static property signal the possible change to the instances it cannot call onpropertychanged since that is not statici could keep a list at the class level of all the instances and call a method on each one but somehow that feels like overkill or i could pull the static properties out into a singleton class but logically they live at the class level is there an established pattern for this or should i be thinking about this differently,"['c#', '.net']" +414094,kway triangle set intersection and triangulation if we have k sets of potentially overlapping triangles what is a computationally efficient way of computing a new nonoverlapping set of trianglesfor example consider this problemhere we have 3 triangle sets a b c with some mutual overlap and wish to obtain the nonoverlapping sets a b c ab ac bc abc where for example the triangles in ac would contain the surfaces where there is exclusive overlap among a and c and a would contain the surfaces of a which do not overlap any other set,['c++'] +414110,looking for a good spacepartitioning data structure to generate millions of atomic bonds quickly from i am performing some md simulations involving systems of millions of atomsi have written some code to generate a file which is just a listing of xyz atom coordinates now i need to generate bonds between the atoms if two atoms are within a certain thistance of each other that is considered a bondexample xyz file1 0 02 0 07 0 010 0 09 0 0so i have got five atoms if my thistance threshold is 2 units then my bond listing will be1 23 54 5where the numbers correspond to the index of the coordinate in the xyz filethe naive approach to generate this list is justfor i 1numatoms for j i1numatoms if thistanceatomi atomj 2 bondspush i jhowever this quickly hits an algorithmic limit and is slow even in highly optimized c for millions of atoms at least for as frequently as i will be doing this processthe only experience i have with spacepartitioning data structures is with kdtrees when i wrote a photon mapper once so i do not really know what the best solution to this problem is i am sure there is probably something out there that is optimal for this thoughi should also mention that my simulation box is periodic meaning that an atom at 05 0 0 will bond to an atom at boxwidth 05 0 0 with a thistance threshold such as 2,['c++'] +414194,ambiguous call to overloaded function stdto string in attempting to insert integer values into a string i thought that my prayers were answered when i found stdto string but for some reason whenever i actually try to use it visual studio complains about ambiguity here is the current incarnation of my functionstring get time remaining int elapsed string remaining string temp string int time remaining timelimit elapsed int temp int temp int inttime remaining 3600 iftemp int 0 remaining 00 else temp string stdto stringtemp int here remaining temp string temp int time remaining 60 1 iftemp int 10 remaining remaining 0 temp string stdto stringtemp int remaining remaining temp string return remainingi have tried casting temp int inside the call to to string and as you can see i even tried casting the result of what should be integer division but no matter what i do vs spits this out at medmy programspowerplaypowerplaypowerplaycpp1285 error c2668 stdto string ambiguous call to overloaded function1 dmicrosoft visual studio 100vcincludestring688 could be stdstring stdto stringlong double1 dmicrosoft visual studio 100vcincludestring680 or stdstring stdto string ulonglong1 dmicrosoft visual studio 100vcincludestring672 or stdstring stdto string longlongany help would be appreciated,['c++'] +414200,regular expression with javascript i have following code in java script var regexp az09g for var i 0 i 6 i if regexptesta1 consolelogmatched else consolelogunmatched please run it on your browser console it will print alternative matched and unmatched can anyone tell the reason for it,['javascript'] +414231,how osgi bundles are used by sling i am just starting on apache sling and cq5 development there is this concept of using osgi bundles in sling i cannot find out how the sling framework actually interacts with these bundles and where does the response from bundles go,['java'] +414263,how to redirect towards gps setting window in android or ios using phonegap for on or off a gps i want to implement a functionality like native android in phonegap in which when user want to enable gps at that time via button click it will be redirected to setting section of android or ios so that user can on the button of gps because programatically we can not directly on or off the gps on the device we can only redirect the user to setting so how to redirect it to setting in phonegap for both android and iosi want to implement below functionality in phonegap can anyone help me function to check if best network provider return boolean public boolean cangetlocation return thiscangetlocation function to show settings alert dialog public void showsettingsalert alertdialogbuilder alertdialog new alertdialogbuildermcontext setting dialog title alertdialogsettitlegps is settings setting dialog message alertdialogsetmessagegps is not enabled do you want to go to settings menu setting icon to dialog alertdialogseticonrdrawabledelete on pressing settings button alertdialogsetpositivebuttonsettings new dialoginterfaceonclicklistener public void onclickdialoginterface dialogint which intent intent new intentsettingsaction location source settings mcontextstartactivityintent on pressing cancel button alertdialogsetnegativebuttoncancel new dialoginterfaceonclicklistener public void onclickdialoginterface dialog int which dialogcancel showing alert message alertdialogshow,"['android', 'ios']" +414267,infinite loop how to know in eclipse what code is running now i am using eclipse to run some androidjava code in my device sometimes the code seems to be stuck in a loop and sometimes it works i was wondering is there a way in eclipse where i can tell it to show my what is the current running or even last method called i want to know where this code stuck is so i can fix it stepping in would not help as i need the code to run without stoppage for this to reproduceplease help,"['java', 'android']" +414301,dynamic where clause or in linq to entities in the post here i learned how to build a dynamic query using the deferred execution of linq but the query is actually using an and concatenation of the where condition how can i achieve the same query but with an or logicdue to the flags enum the query should search for username windowsusername or bothpublic user getuseridentifiertype type string identifier using var context contextfactoryinvoke var query from you in contextusers select u if typehasflagidentifiertypeusername query querywhereu uusername identifier if typehasflagidentifiertypewindows query querywhereu uwindowsusername identifier return queryfirstordefault,['c#'] +414315,could not parse api file frameworksbaseapicurrenttxt i tried adding some files in android framework everything goes well except in the end of compilation i am getting below errori tried make updateapi too but no luck every time in compilation it is giving below errors if anybody know how to overcome this please let me knowdocs droiddoc outtargetcommondocsdoccommentcheckchecking api checkapilastchecking api checkapicurrenthost layoutlib create outhostcommonobjjava librariestemp layoutlib intermediatesjavalibjarcould not parse api file frameworksbaseapicurrenttxt as text comgoogledoclavaapicheckapiparseexception missing class or interface got private line 6342 as xml comgoogledoclavaapicheckapiparseexception error parsing apicould not parse api file outtargetcommonobjpackagingpublic apitxt as text comgoogledoclavaapicheckapiparseexception missing class or interface got private line 6342 as xml comgoogledoclavaapicheckapiparseexception error parsing apiexception in thread main javalangnullpointerexception at comgoogledoclavaapicheckapicheckcheckapiapicheckjava118 at comgoogledoclavaapicheckapicheckmainapicheckjava67you have tried to change the api from what has been previously approvedto make these errors go away you have two choices 1 you can add hide javadoc comments to the methods etc listed in the errors above 2 you can update currenttxt by executing the following command make updateapi to submit the revised currenttxt to the main android repository you will need approvalcould not parse api file outtargetcommonobjpackagingpublic apitxt as text comgoogledoclavaapicheckapiparseexception missing class or interface got private line 6342 as xml comgoogledoclavaapicheckapiparseexception error parsing apiexception in thread main javalangnullpointerexception at comgoogledoclavaapicheckapiinfoisconsistentapiinfojava60 at comgoogledoclavaapicheckapicheckcheckapiapicheckjava118 at comgoogledoclavaapicheckapicheckmainapicheckjava67you have tried to change the api from what has been previously released inan sdk please fix the errors listed abovemake outtargetcommonobjpackagingcheckapilasttimestamp error 38make waiting for unfinished jobsmake outtargetcommonobjpackagingcheckapicurrenttimestamp error 38rwrr 1 aankit admin 9763299 jan 31 1421 outtargetcommonobjjava librariesframework intermediatesclassesjaroutput outhostcommonobjjava librariestemp layoutlib intermediatesjavalibjarinput outtargetcommonobjjava librariescore intermediatesclassesjarinput outtargetcommonobjjava librariesframework intermediatesclassesjarfound 7983 classes in input jarsfound 2260 classes to keep 2143 class dependencies deps classes 2143 keep classes 2260 renamed 19created jar file outhostcommonobjjava librariestemp layoutlib intermediatesjavalibjar,['android'] +414451,why does not c have a power operator many languages have a power operator why does not c for example fortran and python use and is commonly written in latex for example using,['c++'] +414462,select multiple jquery objects with add does the add method allow selecting multiple objects in one go instead of adding one at a timeoneaddtwoaddthreeaddfouronclick function the following variables are set in the way they do because each carries a different function var one 1var two 2var three 3var four 4but what if i want to add an extra function that applies to all of these elements do i have to add them one by onei know you can select them all using 1234 but i just want to make use of the above variables,"['javascript', 'jquery']" +414464,pandas html output with conditional formatting i am trying to format a table such that data in each column are formatted in a style depending on their values similar to conditional formatting in spreadsheet programs how can i achieve that in pandas using the html formattera typical use case is highlighting significant values in a table for example correlation pvalue0 05 011 01 082 09 001pandas allows to define custom formatters for html output to obtain above output one could useimport pandas as pdfrom pandascore import formatfrom stringio import stringiobuf stringiodf pddataframecorrelation05 0109 p value0108001fmt formatdataframeformatterdf formattersp valuelambda x f x if x005 else strxformathtmlformatterfmtwrite resultbufhowever i would like to change the style for significant values for example by using bold fonta possible solution would be to attach a css class to td tags in the html output which could be then formatted using css stylesheet the above would then becometable border1 classdataframe thead tr styletextalign right thth thcorrelationth thp valueth tr thead tbody tr td0td td 05td td 010td tr tr td1td td 01td td 080td tr tr td2td td 09td td clasignificant 001td tr tbodytableedit as suggested by andyhayden i can add formatting by simply replacing stars with span clasignifcantspan in my exampleimport pandas as pdfrom stringio import stringiobuf stringiosignificant lambda x span clasignificantfspan x if x005 else strxdf pddataframecorrelation05 0109 p value0108001dfto htmlbuf formattersp value significantnewer versions of pandas escape the tags to avoid it replace last line withdfto htmlbuf formattersp value significant escapefalse,"['python', 'html', 'css']" +414480,jquery dragging with collision detection i have the following htmldiv classlist idlist div classitem idi1item 1div div classitem idi2item 2div div classitem idi3item 3divdivdiv classtimeline idtimelinedivwhat i want to be able to do with jquery isbe able to drag items from the list into the timelineitems can be dropped into the timeline as many times as required eg there could be 4 of item i1 in the timelineitems in the timeline must not overlap each otheritems can be positioned at any place along the timeline so long as they do not overlap any other items on the timelineso ive gone for jqueryuis draggable and droppable and also gone for the jqueryui draggable collision pluginhere is the jquery i have started withlist itemdraggable helper clone revert invalid the following are for the jqueryuidragablecollision plugin obstacle timeline item preventcollision truetimelinedroppable accept itemmy problem is that the jqueryui draggable collision plugin only works when you are dragging the original div itself and not dragging a helper i need helpers so that i can achieve 2 adding multiple copies of one item but i need something like the collision plugin so i can achieve 3 items not overlappingdoes anybody know of a solution to this problem is there another plugin that does collision detection on the helper of a draggable object is there another approach i can try to get what i want to achieve,"['javascript', 'jquery']" +414483,camera intent data null in onactivityresultint requestcode int resultcode intent data in samsung s3 problem i am getting camera intents data null in onactivityresultint requestcode int resultcode intent data in samsung s3 but working well on some other devices i customized my code for getting data and searched this issue in web but nothing found useful code protected void onactivityresultint requestcode int resultcode intent data if requestcode take camera data null datagetdata null else if requestcode take camera if resultcode result ok return intent intent new intentcomandroidcameraactioncrop intentsetdataandtypetempfileuri image intentputextraoutputx 90 intentputextraoutputy 90 intentputextraaspectx 1 intentputextraaspecty 1 intentputextrascale true intentputextrareturndata true startactivityforresultintent crop camera else if requestcode crop camera data null bitmap photo datagetextrasgetparcelabledata try fileoutputstream out new fileoutputstreamtempfileurigetpath photocompressbitmapcompressformatjpeg 90 out catch filenotfoundexception e todo autogenerated catch block eprintstacktrace if photo null imagephotosetimagebitmapphoto my code,['android'] +414488,safe markup for html email email clients are limited in their html thisplay capabilitieswhat html markup and css styles is it safe to use in htmlformatted email,"['html', 'css']" +414504,jquery detect which button submitted form i have a form with the followingform idmyform button typesubmit namebttnsubmit value1the first buttonbutton button typesubmit namebttnsubmit value2the last buttonbuttonformi would like to detect which triggered the form submit event using justmyformsubmitfunction psuedo code ifnamebttnsubmitval 1 obviously that selector will always return the value of the first bttnsubmit element it comes across so i need some other magic selector or filter or somethingi have seen namebttnsubmitclickedtrue touted about but that has not yet worked in my attemptsi could of course resort to namebttnsubmitclick but would prefer to be able to achieve my goals in the forms submit eventany helptips much appreciated,['jquery'] +414512,how do i make fixedsize byte array user type in c i am converting an old visual basic program to c it sends messages to some industrial machinery over ethernet to do this it assembles a stream of bytes from fixedsize user defined chunksmost of these chunks are small and in c it is easy to create structs of a few bytes or ints and control their size and layout using structlayouts for examplestructlayoutlayoutkindsequential pack 1so when we go into unmanaged space to do a bytewise copy we do not have byte order or padding problemsbut some of the vb6 structures are big arrays for example private type send msg buffer 320 bytes bytes0 to 319 as byte 320 bytesend typeand i am struggling with how to do this in c i can make a fixed size array in a class eg structlayoutlayoutkindsequential pack 1 public class some bytes public byte b new byte320 but to do the bytewise copy i need to be able to thiscover the size of this at runtime and systemruntimeinteropservicesmarshalsizeof returns a 4 for thisany suggestions for how do do this will be much appreciated,['c#'] +414533,android push message without gcm possible is there any possibility to implement pushmessages to android without google cloud messagingi already took a view on openmobster but it does not satisfy my needs i need tocreate pushmessages to an android deviceselfhosteda complete syncframework with rest for android would even be better thank you,['android'] +414571,sequential processing of asynchronous tasks assume the following synchronous codetry foo bar fubar consolewritelineall donecatchexception e for illustration purposes only catch specific exceptions consolewritelineenow assume all these methods have an async counterpart and i have to use those for some reason so simply wrapping the whole thing in a new task is not an optionhow would i achieve the same behaviorwhat i mean with same isexecute a handler for the exception if one is thrownstop execution of the following methods if an exception is thrownthe only thing i was able to come up with is horriblevar footask fooasyncfootaskcontinuewitht handleerrortexception taskcontinuationoptionsonlyonfaultedfootaskcontinuewith t var bartask barasync bartaskcontinuewitht handleerrortexception taskcontinuationoptionsonlyonfaulted bartaskcontinuewith t var fubartask fubarasync fubartaskcontinuewitht handleerrortexception taskcontinuationoptionsonlyonfaulted fubartaskcontinuewith t consolewritelineall done taskcontinuationoptionsonlyonrantocompletion taskcontinuationoptionsonlyonrantocompletion taskcontinuationoptionsonlyonrantocompletionplease notei need a solution that works with net 4 so asyncawait is out of the question however if it would work with asyncawait feel free to show howi do not need to use the tpl if it is impossible with the tpl another approach would be ok maybe with reactive extensions,"['c#', '.net']" +414600,get text content of an html element using xpath see this htmldiv p span classabcmonitorspan b300b p a hrefaddadd to cartadivdiv p span classabckeyboardspan 20 p a hrefaddadd to cartadivusing xpath i want to parse monitor 300 and keyboard 20 i use this xpath divacontains add to cartptextbut it selects span classabcmonitorspan b300b i do not want the tags how do i get only the text,['html'] +414604,logging in delayed job i cannot get any log output from delayed job and i am not sure my jobs are startingheres my procfileweb bundle exec rails serverworker bundle exec rake jobsworkworker bundle exec clockwork appclockrband heres the jobclass scanningjob def perform loggerinfo logging from delayed job end def afterjob railsloggerinfo logging from after delayed job endendi see that clockwork outputs to system out and i can see worker executor starting but i never see my log statements hit i tried puts as well to no avail my clock file is pretty simpleevery3seconds refreshlistings delayedjobenqueue scanningjobnew i just want to see this working and lack of logging means i cannot whats going on here,"['ruby-on-rails', 'ruby']" +414611,sqlclr database name adds 1 everytime i make a change to the project this is a new phenomenon i am seeing my database name is mysqlclr there is a script that always give this name in itsetvar databasename mysqlclrall of a sudden now everytime i make any change to my sqlclr project code and recompile the new output script has the name with an added 1 in it like the followingsetvar databasename mysqlclr 1another change to the code and subsequent build will generate thissetvar databasename mysqlclr 1 1and so forthany idea why this is happening vs2012 mssql2008 r2 on windows 2008 r2,"['c#', 'sql']" +414654,calculate profit based on firstin firstout pricing say i have purchase and sales data for some skuspo id sku purchase date price qty 1 123 20130101 1225 2015 5 2 123 20130501 1545 1750 3 3 123 20130502 1200 1500 1 4 456 20130610 1600 60 7sale id sku sale date price qty 1 123 20130115 1100 30 1 2 123 20130120 1400 2800 3 3 123 20130510 1500 2500 2 4 456 20130611 1200 80 1how can i find the sales margin via sql assuming they are sold in the order they were purchased eg the margin for sku 123 is301 283 252 20155 17501with 2 purchased at 1750 and 1 purchased at 1500 left unsold,"['mysql', 'sql']" +414715,php using thisvariable as class method parameter default value ok so this seems like a pretty dumb question but php is telling me i cannot do this or rather my ide in the below example its telling me i cannot use thissomevar as the default value for the methodie class something public somevar somevalprivate function somefuncdefault thissomevar,['php'] +414718,check if directory exists on ftp server i am running a check to see if a directory exists on my ftp server public bool directoryexistsstring directory bool directoryexists var request ftpwebrequestwebrequestcreatedirectory requestmethod webrequestmethodsftplistdirectory requestcredentials new networkcredentialuser pass try using requestgetresponse directoryexists true catch webexception directoryexists false return directoryexists in this casedirectory on my server i have a folder named rubicon1 this is causing my check to return true how can i ensure that it fails unless it matches the directory name exactly,['c#'] +414731,secure credential storage in python the attackone possible threat model in the context of credential storage is an attacker which has the ability to inspect any user process memoryread local user filesafaik the consensus on this type of attack is that it is impossible to prevent since the credentials must be stored in memory for the program to actually use them but there is a couple of techniques to mitigate itminimize the amount of time the sensitive data is stored in memoryoverwrite the memory as soon as the data is not needed anymoremangle the data in memory keep moving it and other security through obscurity measurespython in particularthe first technique is easy enough to implement possibly through a keyring hopefully kernel space storagethe second one is not achievable at all without writing a c module to the best of my knowledge but i would love to be proved wrong here or to have a list of existing modulesthe third one is tricky in particular python being a language with very powerful introspection and reflection capabilities it is difficult to prevent access to the credentials to anyone which can execute python code in the interpreter processthere seems to be a consensus that there is no way to enforce private attributes and that attempts at it will at best annoy other programmers who are using your codethe questiontaking all this into consideration how does one securely store authentication credentials using python what are the best practices can something be done about the language everything is public philosophy i know were all consenting adults here but should we be forced to choose between sharing our passwords with an attacker and using another language,['python'] +414735,can mvc 4 run on net 35 my server only supports asp net 35 max i am learning to develop mvc 4 is it possible to run mvc 4 on a net 35 machineof course i have no right to alter the server machines configurationthank you,['asp.net'] +414743,writing append only gzipped log files in python i am building a service where i log plain text format logs from several sources one file per source i do not intend to rotate these logs as they must be around foreverto make these forever around files smaller i hope i could gzip them in fly as they are log data the files compress very wellwhat is a good approach in python to write appendonly gzipped text files so that the writing can be later resumed when service goes on and off i am not that worried about losing few lines but if gzip container itself breaks down and the file becomes unreadable that is no noalso if it is no go i can simply write them in as plain text without gzipping if it is not worth of the hassle,['python'] +414757,view the file system of ipadiphone to verify saved files i would like to be able to view the file system of my actual ipadiphone to verify that files are being written correctly i can do this using the simulator by navigating to usersmelibraryapplication supportiphone simulator60applicationsspecific appdocuments here i can see all of the files and data i have written from within my appi would be really helpful if anyone knows of an app or some way of viewing the file system of my apps without jail breaking thanks in advance,['ios'] +414813,strange objective c bug properties not case sensitive i have two properties m and m not the best coding style i know but bear with me assignment to these properties in the init method does not function properly heres the code in it is entiretyimport appdelegatehinterface foo nsobjectproperty nonatomic assign int mproperty nonatomic assign int m idinitwithmintm mintmendimplementation foo idinitwithmintm mintm ifself super init selfm m printfm d dn m selfm selfm m printfm d dn m selfm printfm d dn m selfm return selfendimplementation appdelegate voidapplicationdidfinishlaunchingnsnotification anotification insert code here to initialize your application foo f foo alloc initwithm2 m1endand here is the output from the printfsm 2 2m 2 1m 1 0if i change m to bar and m to bar it works as i would expect is there an explanation for this other than being a compiler bugthanks,['objective-c'] +414886,android preference fragment text color i want to change the text color in android preferences fragment i am currently using a custom theme to change the checkbox image background onclick highlighting and it all works greatbesides the text color i do not want to use a default theme i want to have my own theme so it all looks how i want to but just change the text color can someone please helpstylesxmlxml version10 encodingutf8resources xmlnsandroid style nameselectedtextstyle item nameandroidtextsize18spitem style style namebuttontextstyle item nameandroidtextsize20spitem style style namepreferencestheme item nameandroidwindowbackgrounddrawablelists backgrounditem item nameandroidlistviewstylestylelistviewprefsitem item nameandroidcheckboxstylestylemycheckboxitem style style namemytextappearance parentandroidstyletextappearance item nameandroidtextcolorcolorblackitem style style namelistviewprefs parentandroidwidgetlistview item nameandroidlistselectorlayoutlist selector masteritem item nameandroidtextappearancestylemytextappearanceitem style style namemycheckbox parentandroidwidgetcompoundbuttoncheckbox item nameandroidbuttondrawablebtn checkitem styleresourcesmanifest activity androidnamecompackagesettingsactivity androidthemestylepreferencestheme androidconfigchangeskeyboardorientation activityactivityimport androidappactivityimport androidosbundleimport androidpreferencepreferencefragmentpublic class settingsactivity extends activity override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate thisplay the fragment as the main content getfragmentmanagerbegintransaction replaceandroidridcontent new settingsfragment commit public static class settingsfragment extends preferencefragment override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate load the preferences from an xml resource addpreferencesfromresourcerxmlpreferences,['android'] +414893,css only custom checkbox in ie8 i found custom checkbox and radio from the link but could not find this working in ie8 is there any way we can use below properties working for ie8afterbeforebigradiochecked labelafter please let me know,['css'] +414907,regular expression to match comma separated list of keyvalue where value can contain commas i have a naive parser that simply does something likexsplit for x in mystringsplit however mystring can be something likefoobarbreakfastspameggs obviouslythe naive splitter will just not do it i am limited to python 26 standard library for thisso for example pyparsing can not be usedexpected output isfoo bar breakfast spameggsi am trying to do this with regex but am facing the following problemsmy first attemptraz gave mefoo barbreakfastspameggsobviouslymaking nongreedy does not solve the problem soi am guessing i have to somehow make the last comma or mandatorydoing just that does not really workraz as with that the stuff behind the comma in an value containing one is omittedeg foo bar breakfast spami think i must use some sort of lookbehind operationthe questions1 which one do i use or2 how do i do thatthiseditbased on daramaraks answer belowi ended up doing pretty much the same thing as abarnert later suggested in a slightly more verbose formvals xrsplit 1 for x in datasplitret listwhile vals value valspop0 key vals1pop retappendkey value if lenvals1 0 breakedit 2just to satisfy my curiosity is this actually possible with pure regular expressions ie so that refindall would return a list of 2tuples,['python'] +414925,emberjs nested routes cheers i have got routestravelclientroutermapfunction thisresourcetours function thisresourcetour path tour id function thisrouteseats and a template script typetextxhandlebars datatemplatenametourseats scriptseats is an attribute of tour objecttravelclienttourfind1getseats12and i extend my tourseats route like thistravelclienttourseatsroute emberrouteextend model functionparams return travelclienttourfindparamstour idgetseats question how to render tours seats in templateupdatemy fixtures looks like thattravelclientstore dsstoreextend revision 11 adapter dsfixtureadaptertravelclienttour dsmodelextend title dsattrstring description dsattrstring seats dsattrnumbertravelclienttourfixtures id 1 title brighton england description lorem ipsum dolor seats 12and i have changed my route extend to thistravelclienttourseatsroute emberrouteextend model functionparams return travelclienttourfindparamstour id and in template script typetextxhandlebars datatemplatenametourseats tourseats scriptupdate 2 script typetextxhandlebars datatemplatenametourseats controllermodelseats scriptand it gives undefind backafter some debugging i founded out that there is no any id in params and params is empty thats why i cannot get the right model in tourseatsroute function,['javascript'] +414934,backbonejs where do i put my jquery setup i am getting to grips with backbonejs but one thing i do not understand is where to put all the oneoff jquery code i need to set up my page you know the sort of thing configuring a jquery carousel plugin adding a scroll to top arrow the oneoff configuration that happens when the user first loads the page at the moment i am doing it in my router var approuter backbonerouterextend routes some routes initialize function initializejquerystuff var stateapp new approuter backbonehistorystart pushstate true function initializejquerystuff oneoff jquery stuff goes here yeuch how should i be doing it should initializejquerystuff be another property of the router object should it all just live inside initialize or should i actually keep this code completely separate from the backbone app,['javascript'] +414978,why composer install git or hg directories with package files i am trying to publish composer package i saved composerjson in my package directory name vendor namemy bundle type symfonybundle autoload psr0 vendornamemybundle targetdir vendornamemybundlebut when i install it composer update with package files will added hg directorysimilar behaviour can be seen in this package with package files will added git directory,['php'] +415056,javascript timeout fires 3 times instead of once cleartimeout is not working i want to fire an ajax action when user make a pause in typing instead of after every keypressed so i made something like this when the user stops typing after 3 secs of being idle function done is to be executed it is but why 3 times for long phrases i would expect it to run only once since i clear timeout after every keydown what is the problem var timer var interval 30 inpkeyupfunction timer settimeoutdone interval inpkeydownfunction cleartimeouttimer function done consolelogajax working example on jsfiddle,"['javascript', 'jquery']" +415071,performance of jquerygrep vs arrayfilter in a question it was thiscussed on how jquery and native js would perform against each otherwhile of course the vanilla solution performs a lot faster because it does not process the whole array i proposed the usage of arrayfilter which i was pretty confident would be at least faster than grepsurprisingly after adding it to the test i was taught a lesson testsuiteedgecases of course have a different outcomeanyone having an idea why grep is supposed to be over 3 times faster than the native method arayfilteredit i modified the test to use the filter shim from mdn and the results are pretty interestingchrome even mdn shim is faster than the native method jquery way ahead firefox shim a bit slower than native method jquery way aheadand finally a result like i was hoping it to see in internet explorer native method is the fastest then jquery shim is slowest perhaps this is just the result of ies rather weak jsengine,"['javascript', 'jquery']" +415077,easier way to get views id string by its id int i am new with android and java so sorry if it is a too basic question but i have tried to find a solution in the forums and google and i could noti have 24 buttons in my layout all these buttons do something similar so i want to create a generic function but first i need to know the name xml id of he buttonthis the xml code of the button button androidididadd 04 androidlayout width42dp androidlayout heightwrap content androidlayout gravitycenter androidlayout marginleft15dp androidbackgroundxmlzbuttonshape androidonclickonclick androidtextstringmas i set androidonclickonclick for all the buttonsin my activity i have create a new function onclickthis the code i have triedpublic void onclickview v string name vgetcontextgetstringvgetid string name2 contextgetstringvgetid string name3 getstringvgetid string name4 getresourcesgetstringvgetid but when i try to get the name in this case add 04 i always get false finally i have found a solution with the following codeimport javalangreflectfieldstring name5 nullfield campos ridclassgetfieldsforfield fcampos try ifvgetidfgetintnull name5 fgetname break catchexception e eprintstacktrace my question is if is not there an easier way to get this idthanks in advance,['android'] +415131,opencv with android ndk undefined references i am trying to use opencv on android ndk only i compiled the latest source of the git repository for armeabibased on building opencv4android from trunkbut i am getting this errors with ndkbuilderror undefined reference to cvmatdeallocateerror undefined reference to cvfastfreevoiderror undefined reference to cv outputarray outputarraycvmaterror undefined reference to cvmatcopytocv outputarray consterror undefined reference to cvmatinvint constsimple test codecvmat testmat cvmatcvmatx44d 10 00 00 00 00 10 00 00 00 00 10 00 00 00 00 10cvmat testmatinv testmatinvmy androidmklocal c includes local pathlibsopencvincludelocal ldlibs llibsopencvlibandroidarmeabilocal ldlibs llog lglesv2 alzlocal static libraries libzip libpng libjpeg freetypelocal static libraries libopencv calib3d libopencv contrib libopencv core libopencv features2d libopencv flann libopencv highgui libopencv imgproc libopencv legacy libopencv ml libopencv nonfree libopencv objdetect libopencv photo libopencv stitching libopencv ts libopencv video libopencv videostabanyone has any clue thanks,"['android', 'c++']" +415172,pyaudio errno input overflowed 9981 i was getting the same error as the user inpython error audio recording in 160hz using pyaudiothe error was the same except for the line numbers as in the below graphicas i was writing this i found the solution to my problem in this link the solution was to up the bitrate to 480 but i had already been approved at 44100if pis format supported4410 sample rate input devicedevinfoindex input channelsdevinfomaxinputchannels input formatpyaudiopaint16print yaydoes anyone know why i was approved at 44100 and was overflowing but it works fine at 480 i was also approved for 480ordinarily i am the type of guy to get the solution and move on but this time i feel that i need to know thank you for your time,['python'] +415178,how does a uilabels minimumscalefactor work i have used minimumfontsize before but that function is now deprecated and i do not quite understand how minimumscalefactor worksi want the maximum font size to be 10 and the minimum to be 7how can i achieve the resize down to font size 7 with the scale factor uilabel creationuilabel label uilabel alloc initlabel settranslatesautoresizingmaskintoconstraintsnolabeltext labelname uppercasestringlabeltextalignment nstextalignmentcenterlabeltextcolor uicolor whitecolorlabelfont uifont fontwithnamehelvetica font style bold size95labelbackgroundcolor uicolor clearcolorlabelminimumscalefactor 1flabel addconstraintsnslayoutconstraint constraintswithvisualformathlabelwidth options0 metricswidth nsnumber numberwithfloatbuttonsizewidth viewsnsdictionaryofvariablebindingslabelcontentview addsubviewlabel,"['ios', 'objective-c']" +415190,mysql query issues using like and apostrophe so i have an interesting issue that i have never come across and cannot seem to find much information about correcting the issue i have massive database that has an enormous amount of data in it 10 years worth and attempting to search through itnow the search stuff works fine but recently someone brought it to my attention about a bug if you will i have tried to trouble shoot it to get the expected results but to no availthis is my issuewhen someone uses an apostrophe in the search it is not that the search faults out but it returns no results so for example when searching petes the query executes but returns nothing yes i make sure the query has the mysql real escape string so that petes becomes peteseven when i try to query it using phpmysqls search feature i get strange results the query is intended to be like thisselect from smd article where copy like petesbut when i use the search feature in phpmyadmin it gives meselect from smd article where copy like petesand when i actually type out the query in the sql tab it still returns no results but there are some 17k records that get returned when i just use pete and some 3k records when i do just petesso i am curious as to what i am doing wrong or missing to make it so that it can allow for the apostrophe in a query using the like statement thoughts,"['php', 'mysql']" +415203,print string representation of an enum nslog i am trying to nslog some enums i have for example this piece of code prints the integer representation of the enum but i want it to output the actual string name in this case mon how can i do thatimport foundationfoundationhint mainvoid typedef enum sun mon tues days days d mon nslog d return 0,['objective-c'] +415216,headless browser for multithreads application i am looking for a headless browser for net multithread application it must has next featuresworking without any server installation i need just simple libraryto thistribute with my application ajaxhtml 5 support ability to work with pages elements find and read attributes throughinternalexternal sgmlreader xml or using api to click buttonsfill forms etc correctly cookies container correctly working with multiple cookies response and storing cookies during all sessioncustomizable browser line even selecting chromefirefox is enoughmultithread so no static cookies container or smth else i need beable to login and working with same site under 210 differentusersfast workingworking with https by using insecure ssl i found this solutionsphantomjs i do not understand how to work with this library from net and if this solution suitable to my demands htmlunit with ikvm not work with yui library webkitnet html agility packawesomiumbut do not know what is a best will be pleasure if you suggest me best solution and give some net examples of using iti read this this and many others answers and i have not found answer still,['.net'] +415236,cakeyframeanimation delays before repeating i have an ball image that i am animating around a path the animation is set to repeat forever but why is there a delay between repeatsheres my code cgpathref apathapath cgpathcreatewithellipseinrectcgrectmake0 0 size size nullcatransaction beginarcanimation cakeyframeanimation animationwithkeypath positionarcanimation setbegintimecacurrentmediatimearcanimation setduration 15arcanimation settimingfunctioncamediatimingfunction functionwithnamekcamediatimingfunctionlineararcanimation setautoreverses noarcanimation setrepeatcounthuge valfarcanimationremovedoncompletion noarcanimationfillmode kcafillmoderemovedarcanimation setpath apathbalayer addanimation arcanimation forkey positioncatransaction commitcfreleaseapath,['ios'] +415270,how can i preserve the stack trace when exception is thrown on nonui thread doing this is bad form because it does not preserve a stack tracetry some code that can throw an exception catch exception e throw e use throw by itself insteadhowever if the exception is caught on a nonui thread i want to do raise it back up to the ui and handle it so the user gets the message like sotry some code that can throw an exception catch exception e thispatcherinvokeaction throw however i cannot use the throw keyword by itself here because the c lexer correctly does not think the throw statement is inside of a catch i have to instead dotry some code that can throw an exception catch exception e thispatcherinvokeaction throw e and rethrow the exception which loses its stack traceis there any easy way to get around this i could always package the stack trace at the time the exception is ready to switch threads but that seems hokeynote i saw this thread but it is similar in title only not content,['c#'] +415281,what does it mean by thread serialization in c i know about serializing objects and how they are saved to thisk but what does thread serialization actually mean could any one help me on this one and point me in the right direction please,"['c++', 'c']" +415287,get current page http status from javascript is there any way to get the http status of the current web page from javascriptspent some time searching on the web but no luck at all seems like it is not possible but wanted to check with stackoverflow for maybe some fancy workaroundproviding it from the server as part of the response body is not acceptable the status is supposed to be only available via the http header,['javascript'] +415299,better way to sum values in an array of hashes i need to sum values in an array hashes and i found a way to do it herebut it sure seems like there should be a more elegant way in ruby here is what workssales sale price210 deed typewarranty deed sale price268300 deed typewarranty deed jointtotal sales salesinject0 sum hash sum hashsale pricethe totals line is not very readable it would be nice if something like this workedtotal sales salessumsale priceis this just wishful thinking or am i overlooking a better solution,"['ruby-on-rails', 'ruby']" +415334,using opencv to detect parking spots i am trying to use opencv to automatically find and locate all parking spots in an empty parking lotcurrently i have a code that thresholds the image applies canny edge detection and then uses probabilistic hough lines to find the lines that mark each parking spotthe program then draws the lines and the points that make up the lineshere is the codeinclude opencv2highguihighguihppinclude opencv2imgprocimgprochppinclude iostreamusing namespace cvusing namespace stdint threshold value 150int threshold type 0int const max value 255int const max type 4int const max binary value 255int houghthresh 50char trackbar value valuechar window name find linesint mainint argc char argv const char filename argc 2 argv1 pic1jpg videocapture cap0 mat src dst cdst tdst bgrdst namedwindow window name cv window autosize createtrackbar trackbar value window name threshold value max valuewhile1 cap src cvtcolorsrc dst cv rgb2gray threshold dst tdst threshold value max binary valuethreshold type cannytdst cdst 50 200 3 cvtcolortdst bgrdst cv gray2bgr vectorvec4i lines houghlinespcdst lines 1 cv pi180 houghthresh 50 10 for size t i 0 i linessize i vec4i l linesi line bgrdst pointl0 l1 pointl2 l3 scalar02550 2 cv aa circle bgrdst pointl0 l1 5 scalar 0 0 255 1 8 circle bgrdst pointl2 l3 5 scalar 0 0 255 1 8 imshowsource src imshowwindow name bgrdst waitkey1 return 0currently my main problem is figuring out how to extrapolate the line data to find the locations of each parking space my goal is to have opencv find the parking spaces and draw out rectangles on each parking space with a number labeling the spots i think there are some major problems with the method i am currently using because as shown in the output images opencv is detecting multiple points on the line other than the 2 endpoints that might make it very hard to use opencv to connect 2 adjacent endpointsi read something about using convex hull but i am not exactly sure what it does and how it works any help will be appreciatedhere are the output images from my program,['c++'] +415374,how to properly retain a dialogfragment through rotation i have a fragmentactivity that hosts a dialogfragmentthe dialogfragment perform network requests and handles facebook authentication so i need to retain it during rotationi have read all the other questions relating to this issue but none of them have actually solved the problem i am using putfragment and getfragment to save the fragment instance and get it again during activity recreationhowever i am always getting a null pointer exception on the call to getfragment in onrestoreinstancestate i would also like to keep the dialog from being thismissed during rotation but so far i cannot even retain the instance of it any ideas whats going wrongheres what my code currently looks likepublic class okloginactivity extends fragmentactivity implements oklogindialoglistener private okloginfragment logindialog private static final string tag loginfragment okloginfragment override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate fragmentmanager fm getsupportfragmentmanager ifsavedinstancestate null logindialog new okloginfragment logindialogshowfm tag loginfragment override public void onsaveinstancestatebundle outstate getsupportfragmentmanagerputfragmentoutstatetag loginfragment logindialog override public void onrestoreinstancestatebundle instate fragmentmanager fm getsupportfragmentmanager logindialog okloginfragment fmgetfragmentinstate tag loginfragment this is the exception stack trace0201 163113684 eandroidruntime9739 fatal exception main0201 163113684 eandroidruntime9739 javalangruntimeexception unable to start activity componentinfoioopenkitexamplesampleokappioopenkitokloginactivity javalangnullpointerexception0201 163113684 eandroidruntime9739 at androidappactivitythreadperformlaunchactivityactivitythreadjava21800201 163113684 eandroidruntime9739 at androidappactivitythreadhandlelaunchactivityactivitythreadjava22300201 163113684 eandroidruntime9739 at androidappactivitythreadhandlerelaunchactivityactivitythreadjava36920201 163113684 eandroidruntime9739 at androidappactivitythreadaccess700activitythreadjava1410201 163113684 eandroidruntime9739 at androidappactivitythreadhhandlemessageactivitythreadjava12400201 163113684 eandroidruntime9739 at androidoshandlerthispatchmessagehandlerjava990201 163113684 eandroidruntime9739 at androidoslooperlooplooperjava1370201 163113684 eandroidruntime9739 at androidappactivitythreadmainactivitythreadjava50390201 163113684 eandroidruntime9739 at javalangreflectmethodinvokenativenative method0201 163113684 eandroidruntime9739 at javalangreflectmethodinvokemethodjava5110201 163113684 eandroidruntime9739 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava7930201 163113684 eandroidruntime9739 at comandroidinternaloszygoteinitmainzygoteinitjava5600201 163113684 eandroidruntime9739 at dalviksystemnativestartmainnative method0201 163113684 eandroidruntime9739 caused by javalangnullpointerexception0201 163113684 eandroidruntime9739 at androidsupportv4appfragmentmanagerimplgetfragmentfragmentmanagerjava5280201 163113684 eandroidruntime9739 at ioopenkitokloginactivityonrestoreinstancestateokloginactivityjava620201 163113684 eandroidruntime9739 at androidappactivityperformrestoreinstancestateactivityjava9100201 163113684 eandroidruntime9739 at androidappinstrumentationcallactivityonrestoreinstancestateinstrumentationjava11310201 163113684 eandroidruntime9739 at androidappactivitythreadperformlaunchactivityactivitythreadjava2158,['android'] +415419,angle bracket possible duplicateprinting ahtmla using html how can i put the symbol literally into html text without invoking html stuffs,['html'] +415453,change url when manually scrolled to an anchor by default if i have anchors in my website then the url on the address bar is changed when i click on a link ie wmysitecomanchoris it possible to change the url in the address bar instantly when i scroll to an anchor or have a long document with multiple anchors and the url changes on address bar when i hit a new anchor,"['javascript', 'jquery']" +415496,fallback for css3 multiple backgroundimages i have got 2 images as background of my bodybackground urlimgupper bgpng 0 495px repeatx urlimgbgpng repeati found out that in order to show upper bgpng above bgpng image i needed to place it first in the list however for browsers that do not support multiple backgrounds i would like to show just bgpng i am concerned that browser falls to upper bgpng as a fallback instead of bgpng how can i fix this issue,['css'] +415576,java why cannot i declare an array as a simple object in java i can compileobject obj new object1 new object2but i cannot compileobject obj new object new objectin the first example i declare a onedimensional array of objects and assign it a twodimensional array in the second i declare an object and assign it a one dimensional array if a java array extends object why does not the second code fragment compile why does the first,['java'] +415584,javascript scope of function declarations the var keyword in javascript causes a variable to be stored in the local scope without var variables belong to the global scope what about functions it is clear what happens when functions are declared like variablesvar foo function but what scope doesfunction foo belong toediti realized i did not ask quite the right question so as a follow up in the outer most nesting is there a difference between the above two declarations and the following declarationfoo function,['javascript'] +415611,create intermediate folders if one does not exist i am trying to create a folder for each username a user logs in as currently i haveprivate string destination cusersrichardprintingsubversionfileuploadwebwebinfuploaded main location for uploadsfile thefile new filedestination username will create a sub folder for each user but the file thefile bit does not create a new folder for the username how would i do this i have tried private string destinationpublic void file destination cusersrichardprintingsubversionfileuploadwebwebinfuploaded main location for uploads file thefile new filedestination username will create a sub folder for each user currently does not work below hopefully is a solution thefilemkdirsbut i need to use the destination later on in the program how would i do thatthis is my whole code to change this template choose tools templates and open the template in the editor package richardfileuploadimport javaiofileimport javaiofileoutputstreamimport javaioioexceptionimport javaioinputstreamimport javaiooutputstreamimport javaxannotationpostconstructimport javaxfacesapplicationfacesmessageimport javaxfacescontextfacescontextimport javaxfaceseventactioneventimport javaxfacesapplicationfacesmessageimport javaxfacesbeanmanagedbeanimport javaxfacesbeanviewscopedimport javaxfacescontextfacescontextimport javaiofileimport orgprimefaceseventfileuploadeventviewscopedmanagedbeanname fileuploadcontrollerpublic class fileuploadcontroller public void handlefileuploadfileuploadevent event systemoutprintlncalled facesmessage msg new facesmessagesuccesful eventgetfilegetfilename is uploaded facescontextgetcurrentinstanceaddmessagenull msg private string username private string destination postconstruct public void init systemoutprintlncalled get username username facescontextgetcurrentinstancegetexternalcontextgetremoteuser public void file destination cusersrichardprintingsubversionfileuploadwebwebinfuploaded main location for uploads file thefile new filedestination username will create a sub folder for each user currently does not work below hopefully is a solution thefilemkdirs public file getdirectorystring destination string username systemoutprintlncalled get directory currently not working is not calling the username or destination set the user directory from the destinarion and the logged user name file directory new filedestination username check if the location exists if directoryexists let us try to create it try directorymkdir catch securityexception secex handle the exception secexprintstacktracesystemout directory null return directory public void handlefileuploadfileuploadevent event systemoutprintlncalled handle file facesmessage msg new facesmessagesuccesful eventgetfilegetfilename is uploaded thisplays to user on the webpage facescontextgetcurrentinstanceaddmessagenull msg try copyfileeventgetfilegetfilename eventgetfilegetinputstream catch ioexception e handle the exception eprintstacktrace public void copyfilestring filename inputstream in try write the inputstream to a fileoutputstream outputstream out new fileoutputstreamnew filedestination filename cannot find path when adding username atm systemoutprintlncalled copyfile testing systemoutprintlndestination filename int read 0 byte bytes new byte1024 while read inreadbytes 1 outwritebytes 0 read inclose outflush outclosemake sure new file is created thisplays in glassfish server console not to end user systemoutprintlnnew file createdtesting catch ioexception e eprintstacktrace facesmessage error new facesmessagethe files were not uploaded facescontextgetcurrentinstanceaddmessagenull error final edit hopefully public void copyfilestring filename inputstream in try destination cusersrichardprintingsubversionfileuploadwebwebinfuploaded main location for uploads file thefile new filedestination username thefilemkdirs will create a sub folder for each user currently does not work below hopefully is a solution does now work systemoutprintlncompleted file write the inputstream to a fileoutputstream outputstream out new fileoutputstreamnew filedestination filename cannot find path when adding username atm systemoutprintlncalled copyfile testing systemoutprintlndestination filename int read 0 byte bytes new byte1024 while read inreadbytes 1 outwritebytes 0 read inclose outflush outclosemake sure new file is created thisplays in glassfish server console not to end user systemoutprintlnnew file createdtesting catch ioexception e eprintstacktrace facesmessage error new facesmessagethe files were not uploaded facescontextgetcurrentinstanceaddmessagenull error just how can i print out the new destination and use this later on as currently it creates the new folder but does not select it to useedit solved this too newdestination cusersrichardprintingsubversionfileuploadwebwebinfuploaded usernameadded the above code and now it all works,['java'] +415649,how to call a javascript function when iframe finished loading could any one tell me how i can detect if an iframe has finished loading so i can call a javascript function and alert the user that iframe finished loading and do some other process inside the javascript function note my iframe is my own site can i fire callback from within the iframe as i can have control over it if yes how iframe id myframe srciframe,"['javascript', 'html']" +415713,how to convert a string array to a byte array java i have a one dimensional string array that i want to convert into a one dimensional byte array how do i do this does this require bytebuffer how can i do this the strings can be any length just want to know how to go about doing such an act and after you convert it into a byte array how could i convert it back into a string arraydan,['java'] +415758,rails custom html into simple form label i am trying to customize the output of a simple form association basically i need to thisplay a checkbox label on two lines my idea was adding a br tag into the label but unfortunately it gets escaped so it thisplay actually br instead of going to a new linei use a lambda for customizing the label output fassociation item as check boxes collection current useritems label false label method lambda item itemcitycapitalizebr itemaddress this produces an escaped br into the label string how could i thisplay the label on two lines,['ruby-on-rails'] +415775,resolving name conflicts in references in sphinx with intersphinx i am writing docs for my python library using sphinx i also added another sphinx documentation with intersphinx and it works pretty nice but a few my functions are named the same as in referenced documentation which leads to shadowing their names for func referencingis there any way i can reference shadowed function do some in other documentation funcdo some creates a link to my function do some,['python'] +415806,sqlalchemy union parenthesis issue i need to generate a query similar to the followingselect from where and order by limit union allselect from where and order by limit order by using sqlalchemy i create two query objects as inq1 sessionqueryfilterfilterorder bylimitq2 sessionqueryfilterfilterorder bylimitq q1union allq2order byallhowever it would not work because sqlalchemy generates queries q1 and q2 are not within parenthesis and it creates an errorhow can i get these statements inside parenthesis for q1 q2 union to result in above expressed query,['python'] +415843,creating pdf reports with flot graph i am trying to implement an automatic report generation tool for my clients i need to create reports in pdf format and i am very much comfortable in creating graphs using jquery flot i just need a way to get the graphs inside the pdfi tried using flying saucer xhtmlrenderer to capture the image of the graph but it does not seem to help me as the graphs being created by javascriptcan xhtmlrenderer capture the elements created with javascript or is their any other tool which can capture the image of the graph,"['javascript', 'jquery']" +415899,iequalitycomparer for sequenceequal in c is there a iequalitycomparerienumerable that uses the sequenceequal method to determine equality,"['c#', '.net']" +415935,400x sorting speedup by switching alocalecompareb to ab10 by switching a javascript sort function frommyarraysortfunctiona b return anamelocalecomparebnametomyarraysortfunctiona b return anamebname1anamebname10i was able to cut the time to sort a 1700 element array in chrome from 1993 milliseconds to 5 milliseconds almost a 400x speedup unfortunately this is at the expense of correctly sorting nonenglish stringsobviously i cannot have my ui blocking for 2 seconds when i try to do a sort is there anything i can do to avoid the horribly slow localecompare but still maintain support for localized strings,['javascript'] +415936,extend visual studio 2012 test explorer with extra information as part of some research i am writing an extension for the microsoft visual studio unit testing framework with a custom testing type like described here i have created a custom attribute but i want to show some additional information in the test explorer about the executed test from my custom attributei was also wondering if there is any way to show information of all unit tests so from my custom attribute but also from the default visual studio unit testing framework attributes that were executed in the past so i can show the information from these tests in graphs etc does anybody know a good solution to achieve thisupdate 1what i mean is something like this,['c#'] +415977,how can i indent html or php code in notepad editor how can i indent html or php code in notepad editor to organize my code better,"['php', 'html']" +416031,how to debug large lists of strings and multidimensional arrays of numbers i often use c to work with large datasets which take the form of very large lists of strings or large 2 or 3 dimensional arrays of numbers the latter especially is very easy to visualize in matlab a functionality i often miss with cvs2012 has very nice debugging functions which allow you to stop execution and inspect different variables in various ways it will also highlight variables that change with redunfortunately for lists and matrices this is useless by default lists will not be expanded and if you do expand them the values of individual entries will not be visible unless you expand every single one individually the layout is uneconomical with space so you can see few entries at one time with larger 2d arrays the way the entries are arranged makes interpreting the array at a glance a nightmarefor datasets there is a great visualization tool that automatically shows up when you click the magnifying glass in debug mode unfortunately i cannot find anything similar to it for lists of strings string arrays or 2d arrays of numbersis there an extension or hidden feature for viewing such data structures when execution is paused if no how can i make my own,"['c#', '.net']" +416063,how to instantiate initialize and populate a array in typescript i have the following classes in typescriptclass bar length numberclass foo bars bar new arrayand then i havevar ham new foohambars new bar compiler says expected and expected length 1 is there a way to do that in typescriptupdatei came up with another solution by having a set method to return itselfclass bar length number private ht number heighth number bar thisht h return this constructorlen number thislength len class foo bars bar new array setbarsitems bar thisbars items return this so you can initialize it as belowvar ham new foohamsetbars new bar1height2 new bar3,['javascript'] +416083,jquery lightbox thumbnails ok background dims but no large image shows i have a weird issue where lightbox appears to be working but no larger image appearslinks to images are correct and thumbnails are showing but no full size imagethere are also no errors in the consolei have my gallery html set up as sucha hrefimagesherejpg rellightboxgalleryimg srcimagesherejpg altfast festival image galleryai have ensured that jquery jquery ui lightboxcss lighboxjs and jquerysmoothscrollminjs are all presentthe page is does anyone know whats happening at alleditchecking in the console i see there is not image appearing in the lightbox div when it is envokeddiv idlightboxoverlay stylewidth 1633px height 1234px thisplay blockdiv,"['javascript', 'jquery']" +416094,how to read maven settings in m2settingsxml file from plugin three questions in decreasing order of importance links will doi need to read certain maven settings such as proxies servers in my maven plugin how do i read them from my plugin i can read from m2settingsxml file but i think there must be an easier way some api that already does iti see from developers cookbook there is a class orgapachemavenprojectmavenproject what dependency i need for this to be available in my plugin i feel this would be good to haveis it possible to have my own properties in settingsxml say for exampleusers user usernameuser name1username passwordencrypted passwordpassword userusershow ps i am a beginnerupdate 1i was able to create and read custom properties following injecting pom properties via settingsxml however i would like to have configuration similar to what cargo provides eg servers server idtomcat7 localid configuration cargohostnamelocalhostcargohostname cargoremoteurihttplocalhost8080managertextcargoremoteuri cargoremoteusernamemy usernamecargoremoteusername cargoremotepasswordmy passwordcargoremotepassword cargoservletport8080cargoservletport configuration server server idtomcat6 localid configuration cargohostnamelocalhostcargohostname cargoremoteurihttplocalhost8080managercargoremoteuri cargoremoteusernamemy usernamecargoremoteusername cargoremotepasswordmy passwordcargoremotepassword cargoservletport8080cargoservletport configuration server servershow do i achieve this have a kind of workaround for my 3rd problem not sure if its the right wayeditthanks jordan002 i know i can have multiple profiles but i did not know to use them this way by having profiles i can set my variables value or rather inject the value in my plugin by saying something like parameteralias cargohostnameprivate string hostname but as i see for cargo plugin all it requires is defined like belowservers server idsomeidid configuration configurations are placed here configurationserverssimilarly or may be not so similar as there is no configuration hereproxies proxy activetrueactive protocolhttpprotocol hostmy proxy hosthost portmy proxy portport proxyproxiesis where i can put proxy information that maven uses now i do not want to redefine it inside some profiles and i do not want to parse this file to get informationsfurther i would like do something like cargo is doing it lets me write all the configuration inside servers and in projects pom i only have to do followingplugin groupidorgcodehauscargogroupid artifactidcargomaven2pluginartifactid configuration container containeridtomcat7xcontainerid typeremotetype container configuration typeruntimetype properties cargoserversettingstomcat7 localcargoserversettings properties configuration deployer typeremotetype deployer deployables deployable groupidprojectgroupidgroupid artifactidprojectartifactidartifactid typewartype properties contextprojectartifactidcontext properties deployable deployables configurationpluginand cargo picks up configurationss that i defined for tomcat7 local no need to write a profile for this,['java'] +416127,combining angularjs and codeigniter i am working on an existing site written in codeigniter and we are looking at using angularjs for some pages that require a lot of frontend functionality but we do not want to replace all all codeigniter views at once yetso i click a link that is controlled by angulars router and it is handled by javascript but next link could be a normal request that should handled by the codeigniter frameworkis there some elegant way to combine these two methods i do not really mind some extra client side overhead because the site is not running in production yet,"['php', 'javascript']" +416160,segoe ui font in non windows systems i am developing the frontend of a web application and the design requires the use of the segoe ui font i used this font for a few text areas but in non windows systems mac os borwsers android etc those texts do not render with the segoe ui fontafter googling this i found that this font is used by microsoft my question is can just use the font files in the frontend an use facefont to include the font in the frontend or do i need some licence or something like that,"['html', 'css']" +416238,is it possible to instruct c to not zeroinitialize global arrays i am writing an embedded application and almost all of my ram is used by global bytearrays when my firmware boots it starts by overwriting the whole bss section in ram with zeroes which is completely unnecessary in my caseis there some way i can instruct the compiler that it does not need to zeroinitialize certain arrays i know this can also be solved by declaring them as pointers and using malloc but there are several reasons i want to avoid that,['c'] +416280,on ios 61 uiswitch iboutlet is always nil i am having some trouble while working with uiswitch on a static uitableviewi have to restore the last state of a certain uiswitch when the app loads but whenever i check the state of the iboutlet it is nil i have tried to manually alloc the variable which was of no help eitherhere is what i am doingsettingscontrollerhiboutlet connected correctlyproperty strong nonatomic iboutlet uiswitch switch thisplaydetailsettingscontrollerm voidviewwillappearboolanimated super viewwillappearanimated if switch thisplaydetail nslog switch thisplaydetail is nil this is always thisplayed switch is default to yes i am trying to set it to no this line does nothing switch thisplaydetail setondatamanager shouldthisplaydetail animatedyeseverywhere else when i check the state of switch thisplaydetail it is nil i am calling all the super initialization methodsdid anything change on ios 61edit using the synthesized variable does not work eitheredit 2 found the problem to be a bug on xcode or on iphone simulator after testing on my ipod touch the initial algorithm worked perfectlyi am going nuts with this problem,"['ios', 'objective-c']" +416296,setting webview to view desktop site and not mobile site i have done quite a lot of research on stack overflow and a lot of google research but nothing i find is actually working out for me i want the site to view the desktop site instead of the mobile site how do i do this i want it to directly go to the desktop sitewebview mywebview webview findviewbyidridwebview mywebviewloadurl,['android'] +416305,inject dependencies in run method of the module in angularjs i trying to understand how do i work with angularjs it looks like nice framework but i stuck with a little problem with di how i can inject dependecies in run method of the module i mean i able to do it but it works only if i have servicefactoryvalue with as same name as run parameter namei build a simple application do illustrate what i meanvar configuration configuration i would like to have appconfigurationvar log service logservice i would like to have appserviceslogservicevar login controller logincontrollervar app appservices appcontrollers app angularextendapp angularmoduleapp runfunction rootscope location configuration logservice how to force logservice to be the logger in params not var logger logservice logservicelogapp run appinject configuration log service not works appserviceslogservice function config thislog function message confighasconsole consolelogmessage alertmessage appserviceslogserviceinject configurationappservicelog service appserviceslogserviceappcontrollerslogincontroller function config logger loggerlogcontroller constructedthe line below required only because of problem describedappcontrollerslogincontrollerinject configuration log serviceappfactoryconfiguration function return hasconsole console consolelog why i need it may you ask but in my mind first off all to have meaningful namespaces to organize the code it will also minimize name collision and in the last when minifing the js the things breaks down since it renamed to more shorten names,['javascript'] +416339,in numpy what does indexing an array with the empty tuple vs ellipsis do i just thiscovered a by chance a that an array in numpy may be indexed by an empty tuplein 62 a arange5in 63 aout63 array0 1 2 3 4i found some documentation on the numpy wiki zerorankarraysasha first whatever choice is made for x and x they should be the same because is just syntactic sugar for as many as necessary which in the case of zero rank leads to 0 second rank zero arrays and numpy scalar types are interchangeable within numpy but numpy scalars can be use in some python constructs where ndarrays cannotso for 0d arrays a and a are supposed to be equivalent are they for higherdimensional arrays too they strongly appear to bein 65 a arange25reshape5 5in 66 a is aout66 falsein 67 a aallout67 truein 68 a arange37reshape37in 69 a aallout69 truebut it is not syntactic sugar not for a highdimensional array and not even for a 0d arrayin 76 a is aout76 falsein 77 a is aout77 truein 79 b array0in 80 b is bout80 falsein 81 b is bout81 trueand then there is the case of indexing by an empty list which does something else altogether but appears equivalent to indexing with an empty ndarrayin 78 aout78 array shape0 3 3 3 3 3 3 dtypeint64in 86 aarange0out86 array shape0 3 3 3 3 3 3 dtypeint64in 82 bindexerror traceback most recent call lastindexerror 0d arrays cannot be indexedso it appears that and are similar but not quite identical and indexing with means something else altogether and a or b are syntaxerrors indexing with lists is documented at index arrays and there is a short notice about indexing with tuples at the end of the same documentthat leaves the questionis the difference between a and a by design what is the design then question somehow reminiscent of what does the empty do on a matlab matrixeditin fact even scalars may be indexed by an empty tuplein 36 numpyint6410out36 10,['python'] +416362,embed pdf in html5 i am trying to embed a pdf in a html document but only chrome seems to be taking it for the rest of the browser they either need plug ins or need a user to click the link which is not what i want here is my codehelp pleaseobject datapdffilesinterfacespdf typeapplicationpdf embed src pdffilesinterfacespdf typeapplicationpdfnbsp embed alt a hrefpdffilesinterfacespdf object,['html'] +416419,format string is not a string literal potentially insecure possible duplicatewhy is my string potentially unsecure in my ios application new compiler warning since upgrading xcode to 46smallest example demonstrating the warning on both of the final lines for nsuinteger i 0 i 10 i nsstring res testinstance generatei nsstring desc nsstring stringwithformattestdata d i stassertnotnilres desc stassertnotequals res desc i looked at other questions which concern this warning but they stem from programmers unnecessarily using stringwithformat here i want a dynamic assert description which changes per iteration but not per checki can pass the format string and data into the asserts but then i have to maintain the descriptions independently how can i avoid this warning if i require the formatting of a description is prior to using it in a log message or assert call,['objective-c'] +416440,requirejs finding the script responsible for an error i am looking for an elegant way to find out the full path to a script that caused a timeout error ie failed to load a dependencyrequirejsonerror function err this works var script that failed loading erroriginalerrortargetsrc now i want var the script responsible for this,['javascript'] +416450,read file from classpath with java 7 nio i have googled around for quite a while for this but all the results point to prejava 7 nio solutions i have used the nio stuff to read in files from the a specific place on the file system and it was so much easier than before filesreadallbytespath now i am wanting to read in a file that is packaged in my war and on the classpath we currently do that with code similar to the followinginput inputstream thisgetclassgetclassloadergetresourceasstreamfilenamebytearrayoutputstream bytestream new bytearrayoutputstream iterate through the input stream to get all the bytes no way to reliably find the size of the file behind the inputstream see int byteint 1try byteint inputstreamread while byteint 1 bytestreamwritebyteint byteint inputstreamread bytearray bytestreamtobytearray inputstreamclose return bytearraycatch ioexception e while this works i was hoping there was an easierbetter way to do this with the nio stuff in java 7 i am guessing i will need to get a path object that represents this path on the classpath but i am not sure how to do that i apologize if this is some super easy thing to do i just cannot figure it out thanks for the help,['java'] +416451,angularjs directive to replace text how would i create a directive in angularjs that for example takes this elementdivexample text divand convert it in to this divexample text a hrefadivi already have the functionality written to auto link the text in a function and return the html let us call the function autolink but i am not up to scratch on my directivesi would also like to add a attribute to the element to pass a object in to the directive egdiv linkpropslinkprops example text divwhere linkprops is object like a bla bla b waa waa which is to be passed to the autolink function as a second param the first been the text,['javascript'] +416453,access python nested dictionary items via a list of keys i have a complex dictionary structure which i would like to access via a list of keys to address the correct itemdatadict a r 1 s 2 t 3 b u 1 v x 1 y 2 z 3 w 3 maplist a ror maplist b v yi have made the following code which works but i am sure there is a better and more efficient way to do this if anyone has an idea get a given data from a dictionary with position provided as a listdef getfromdictdatadict maplist for k in maplist datadict datadictk return datadict set a given data in a dictionary with position provided as a listdef setindictdatadict maplist value for k in maplist1 datadict datadictk datadictmaplist1 value,['python'] +416520,mysql match against not return case insensitive results i have two tablescreate table if not exists test1 id int10 unsigned not null auto increment bucket id int10 unsigned not null comment folder this component belongs to test1 name varchar81 not null comment name of this component test1 desc varchar1024 not null comment component description primary key id fulltext key test1 search test1 nametest1 desc enginemyisam default charsetutf8 auto increment3 create table if not exists bucket id int10 unsigned not null auto increment bkt name varchar81 not null comment the name of this bucket bkt desc varchar1024 not null comment a description of this bucket bkt keywords varchar512 default null comment keywords for searches primary key id fulltext key fldr search bkt descbkt keywordsbkt name enginemyisam default charsetutf8 auto increment8 bucket is just a holder while test1 contains all the things that would go into a bucket for example insert into bucket id bkt name bkt desc bkt keywords values1 simpsons the simpsons cartoon family was first successful adult cartoon series homer marge lisa and bart2 griffins the family from the popular family guy series peter lois meg chris stewie brianinsert into test1 id bucket id bkt name bkt desc values1 1 homer simpson homer the figurative head of the simpsons family and is the husband of marge2 2 peter griffin peter the figurative head of the griffin family on the hit tv seriers the family guynow using the following query i want to look for all buckets whose name description or keywords contain the search term family or whose components contain the words familyso far what i have is this query and it is not returning mixed case results as in family is not found while family isselect from bucketright join test1 on test1bucket id bucketidwhere bucketisvisible 0 and matchbucketbkt keywords bucketbkt desc bucketbkt name againstfamily in boolean mode or matchtest1test1 name test1test1 desc againstfamily in boolean modei should also add that all text fields have the collation of utf8 general ci as does the entire table which is myisam,['mysql'] +416528,using opencv and svm with images i am having difficulty with reading an image extracting features for training and testing on new images in opencv using svms can someone please point me to a great link i have looked at the opencv introduction to support vector machines but it does not help with reading in images and i am not sure how to incorporate itthanks so much for the explanation my goals are to classify pixels in an image these pixel would belong to a curves i understand forming the training matrix for instance image a11 12 13 14 1521 22 23 24 2531 32 33 34 35i would form my training matrix as a 32 11 12 13 14 15 21 however i am a little confuse about the labels from my understanding i have to specify which row image in the training matrix corresponds which corresponds to a curve or noncurve but how can i label a training matrix row image if there are some pixels belonging to the curve and some not belonging to a curve for example my training matrix is 32 11 12 13 14 15 21 pixels 11 and 14 belong to the curve but the rest does notthanks a lot,['c++'] +416533,callback function after tooltip popover is created with twitter bootstrap i want to manipulate a tooltip or popover after it is created with twitter bootstrap as far as i know there is not a build in way to do thisselectorpopover placement bottomfor example lets say i want to move the created tooltip up 5px and left 5px from it is calculated location any ideas on the best way to do thisthis is what i would like to doselectorpopover placement bottom callback function alertawesome,"['javascript', 'jquery']" +416552,inconsistent behavior with http post requests in python trying to make a post request between a python wsgi and a nodejs express application they are on different servers the problem is that when using different ip addresses ie private network vs public network a urllib2 request on the public network succeeds but the same request for the private network fails with a 502 bad gateway or urlerror 32 broken pipethe urllib2 code i am using is thisreq urllib2requesturl somedata contenttype applicationjson charsetutf8res urllib2urlopenreqprint freadnow i have also coded the request like this using requestsr requestsposturl headers contenttype applicationjson charsetutf8 data somedataprint rtextand get a 200 ok response this alternate method works for both networksi am interested in finding out if there is some additional configuration needed for a urllib2 request that i do not know of or if i need to look into some network configuration which might be missing i do not believe this is the case since the alternate request method works but i could definitely be wrongany suggestions or pointers with this will be greatly appreciated thanks,['python'] +416607,google maps api for android limit 2500 requestsday is per client device or per application key sorry i found similar questions but not the answers only thiscussions i am developing android application which is intended to place points and draw routes on map in case google limits using of their maps 2500 rday per key there is no way to use it since even in case your application was once sold youll need to pay every month for every additional 10 reqday especially it is unclear for free application how much it will cost for 10 downloads per month after 1 year please share your experience not your assumptions thanks,['android'] +416636,unit testing web api using httpserver or httpselfhostserver i am trying to do some unit testing in for a web api project i am going simulate the web api hosting environment it seems like that i could use in memory host httpserver or self host httpselfhostserver just wondering what are the difference and which technology is good for what and is there any limitation for those options,['c#'] +416640,x86 64 asm maximum bytes for an instruction what is the maximum number of bytes a complete instruction would require in x64 asm codesomething like a jump to address might occupy up to 9 bytes i suppose ff 00 00 00 00 11 12 3f 1f but i do not know if that is the maximum number of bytes a x64 instruction can use,['c'] +416671,switching kivy widgets i am using the kivy python libraryi have two widgets definedwhen the program runs i run the first widgetwhen that widgets button is pressed i want it to thissapear and be replaced with the second widgethere is the kv for the two widgetsuitestkvtestform canvas rectangle pos selfcenter x 0 size 10 selfheight boxlayout size rootsize padding 40 button text hello on release roottestcallbacktestform2 canvas rectangle pos selfcenter x 0 size selfheight 10my main python file runs the app and returns the first widgetmainpyfrom testform import testformfrom kivyapp import appclass uitestappapp def buildself return testform main launching pointif name in main android uitestapprunmy first widget has a callback this is where the codeinquestion belongsfrom testform2 import testform2from kivyuixwidget import widgetclass testformwidget def testcallbackself testform2 code in question goes here todo replace this widget with testform2 widgetthe idea here is to have a user interface manager this manager does not run the ui like a tree but like a list and stack the list holds instances of all my ui forms the stack holds the traversal of said forms whenever we jump to a form we push it to the stack and render or whatever that oneediti chose my answer but in my searches i also found the screen object personally the clear and add commands are more powerful but the screen takes a lot of that out of your hands if youre interested transition effects too,['python'] +416738,how to get parent domain name in iframe with cross domain i want to get the parent domain or url or hostname inside iframe javascripti have used documentreferrer for that but it only works the first time by this i mean that my iframe contains the form so when the user submits the form the iframe loads again and the referrer will become the my iframes domainnow each time my iframe loads i want the parent domain name only as i am creating the links using thatexampleseturleachfunction var referrer documentreferrer thishrefreferrerabchtml but this only works the first time because of the reason i mentioned above so can somebody help me overcome thisask me in case if more clarity required,"['javascript', 'jquery']" +416742,how can i tell which android support library v4 revision i use i can see in the android sdk manager the version installed on my computer in android sdk manager but usually a project uses its own copy from the libs folderis there a way i can tell which version is the androidsupportv4jar being used in a specific project besides the file dateany method is considerable by code eclipse file manager,['android'] +416762,inverse of supplier in guava i am looking for the inverse of suppliert in guava i hoped it would be called consumer a nope a or sink a exists but is for primitive valuesis it hidden somewhere and i am missing iti would like to see it for the same kinds of reasons that supplier is useful admittedly uses are less common but many of the static methods of suppliers for example would apply in an analogous way and it would be useful to express in one line things like send this supplier every value in this iterablein the meantime predicate and functiontvoid are ugly workarounds,['java'] +416789,how can i get a python decorator to run after the decorated function has completed i want to use a decorator to handle auditing of various functions mainly django view functions but not exclusively in order to do this i would like to be able to audit the function postexecution ie the function runs as normal and if it returns without an exception then the decorator logs the factsomething likeaudit actionactiondid somethingdef do somethingargs kwargs if args0 foo return bar else return bazwhere audit action would only run after the function has completed,['python'] +416806,textsometext what does it mean i have recently come across a code sample i had to use and i was able to use it but i didnt quite understand exactly what was going on and i dont like thatheres part of the codesortelementsfunctiona b return texta textb inverse 1 1 inverse 1 1i know that this function is deciding which element should be sorted first out of a and b and i know that inverse is deciding the sort order but i dont know what texta is doing is it parsing a as text kind of like parseinta and dateparseai have asked google and it wont tell me anything possibly because it doesnt like to search for symbols and dots or possibly because i dont know how to use google to search for symbols and dots i have also looked on the jquery site and all i have found is the selectortextselectortextnewtext functionheres the jsfiddle i am basing my code from,"['javascript', 'jquery']" +416817,error could not materialize struct could not read eax for debugging on ios simulator i used to be able to read out eax register and get the error message however i do not know if it is the new xcode version 46 and ios 61 i cannot do that any morelldb po eaxerror could not materialize struct could not read eax materializeerrored out in execute could not preparetoexecutejitexpressionwhat nowalso eax is not in the real device what do i do,['objective-c'] +416832,angular js ngthisabled doesnt work this is my formform namemyforminput ngthisabledtrue typetext formhowever i am trying to understand why this input field is not thisabledi also tried with a scope so in the ctrlscopethisstrueand in html form namemyforminput ngthisabledthiss typetext formit still doesnt work any hint,['javascript'] +416870,saving serializable objects list into sharedpreferences can anyone tell me how i can save a list of custom serializable objects into sharedpreference i am new to android and i want to save an arraylistcontact list into shared preferencespublic class mainactivity extends sherlockfragmentactivity placeslidesfragmentadapter madapterviewpager mpagerpageindicator mindicatorpublic static final string tag detailsfragmentpublic view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate view view inflaterinflaterlayoutmain container false madapter new placeslidesfragmentadaptergetactivity getsupportfragmentmanager mpager viewpager viewfindviewbyidridpager mpagersetadaptermadapter mindicator circlepageindicator viewfindviewbyidridindicator mindicatorsetviewpagermpager circlepageindicator mindicatorsetsnaptrue mindicator setonpagechangelistenernew viewpageronpagechangelistener override public void onpageselectedint position toastmaketextmainactivitythisgetactivity changed to page position toastlength shortshow override public void onpagescrolledint position float positionoffset int positionoffsetpixels override public void onpagescrollstatechangedint state return view,['android'] +416887,how to schedule task daily onstart in play 204 i need to execute a piece of code 1 time everyday in playframework204 when i try to do with the class extends globalsettings it works but it works for every instance requesting i want it works when server starts and does its duty everyday 1 timepackage controllersimport javautilconcurrenttimeunitimport akkautildurationimport playapplicationimport playglobalsettingsimport playlibsakkapublic class parserjobapp extends globalsettingsoverridepublic void onstartapplication app akkasystemschedulerscheduledurationcreate0 timeunitmillisecondsdurationcreate6 timeunitseconds new runnable override public void run systemoutprintlna systemcurrenttimemillis and this is my controller where start the class abovepublic class application extends controller public static result index parserjobapp prnew parserjobapp pronstartnull systemoutprintlnsfsdfsdfreturn okindexrenderyour new,['java'] +416907,rails dynamically define class method based on parent class name within moduleconcern i want to dynamically generate a class method in a mixin based on the class name that include this mixin here is my current codemodule mymodule extend activesupportconcern def some methods end module classmethods here is where i am stuck define method selfnamedowncase status do do something end end end class myclass activerecordbase include mymodule end what i am trying to achievemyclassmyclass statusbut this give me the following method name myclassmymoduleclassmethods status getting the base class name inside the method definition works self selfname but i cannot make it works for the method nameso far i have tried define method selfdefine method selfnamedefine method selfclassdefine method selfclassnamedefine method selfmodel namedefine method selfparentnamebut none of this seems to do the trick is there any way i can retrieve the base class name not sure what to call the class that include my module i have been struggling with this problem for hours now and i cannot seem to figure out a clean solution thanks,"['ruby-on-rails', 'ruby']" +416926,remote attribute does not trigger when field is blank i am using remoteattribute for a particular field on my form the purpose of it is not important what is important is that it needs to fire the validation action whenever the field is changed this is working fine for me except when the field is changed to be blank i have googled this but found no results does anybody know if remoteattribute does actually trigger for blank fields and if not how it can be forcedalternatively can the remote validator be customisedmodified to trigger for blank values,"['jquery', 'asp.net']" +416940,boost coroutine assertion failure to try out the new coroutine feature in boost i created the following programinclude boostcoroutineallhppinclude stringinclude vectortypedef boostcoroutinescoroutineintchar coroutine tvoid fcoroutine tcaller type ca stdvectorint vec 1 2 3 for int i vec char c caget stdcout c c stdendl cai int main coroutine t crf stdstring strabc for char c str stdcout c stdflush crc int and crget stdcout and stdendl the code is based on the sample code from the docsmy build command goes as follows g stdc11 o test iusrlocalinclude lusrlocallib maincpp usrlocalliblibboost contextaoutput testtest usrlocalincludeboostcoroutinedetailcoroutine gethpp43 typename boostcoroutinesdetailparamresulttype boostcoroutinesdetailcoroutine getd result arityget const with d boostcoroutinescoroutinecharint 1 result char int arity 1 typename boostcoroutinesdetailparamresulttype char assertion static cast d const thisimpl result failedaborted core dumpedthe program is aborted due to failed assertion can you help me find the error in my code,['c++'] +416985,how to use servicestack funq in my own projects at work were doing several new web services projects in servicestack and taking advantage of funq in some of them i am currently working on a separate project that will consume said web services and was wondering if there was a way for me to use servicestacks funq in my project to resolve my dependencies as to use more or less the same patterns were using when developing our web servicesis this possible,['.net'] +417032,change name of process in task manager i have a windows form application running on a servernow i need to have multiple instances of the same application running at the same timeeach instance will connect to a different databaseduring the application startup i change the title so i can identify which db is connecting to but i would like to change the name in the task manager alsothis because i have another application that act as a supervisor killing and starting the process as neededi have to find a way to clearly identify the process to kill,['c#'] +417113,whats the less than dot symbol mean in chrome console output sometimes but not always when the result of an evaluation in the chrome javascript console results in undefined there is a symbol in the left margin that looks like a lessthan symbol with a dotexamples can be seen in this section of the chrome developers tools documentationbut what that symbol means does not appear to ever be explained does anybody know what it is trying to convey thanks,['javascript'] +417120,execute only one of many duplicate jobs with sidekiq i have a background job that does a mapreduce job on mongodb when the user sends in more data to the document it kicks of the background job that runs on the document if the user sends in multiple requests it will kick off multiple background jobs for the same document but only one really needs to run is there a way i can prevent multiple duplicate instances i was thinking of creating a queue for each document and making sure it is empty before i submit a new job or perhaps i can set a job id somehow that is the same as my document id and check that none exists before submitting italso i just found a sidekiquniquejobs gem but the documentation is nonexistent does this do what i want,['ruby-on-rails'] +417150,connecting 2 images in android i want to connect 2 images in android examplei want them to be like thisi have already done it by hard coding first i find the upper left of the green image and then find the the most lower left point of the green sidei do it with touch events eventgerrawx and eventgetrawy parameters now i know the thistance in x and y between those two points i do the similar thing for the red one too now when green piece is moved close to the red i just calculate if upper left point of red piece is near to the lower left of the green piece if so i translate the green one red one to the other one but this hard coded calculation should fail for same size tablet or phone with different resolution i just want to know how do i generalize the solution thanksedit my gameactivity and imageinfo class where i try to connect both images i have actually 6 images like this and i wanto connect them like image 1 will connect to image 2 and image 2 to 3 and so ongameactivity classpackage comexamplejigsawpuzzleimport comexampletestrimport androidannotationsuppresslintimport androidappactivityimport androidappalertdialogimport androidappdialogimport androidcontentcontext import androidcontentdialoginterfaceimport androidcontentintentimport androidcontentpmactivityinfoimport androidcontentresconfigurationimport androidgraphicspointimport androidmediaaudiomanagerimport androidmediasoundpoolimport androidosbundleimport androidutilthisplaymetricsimport androidutillogimport androidviewthisplayimport androidviewmotioneventimport androidviewsurfaceimport androidviewviewimport androidviewviewonclicklistenerimport androidviewviewontouchlistenerimport androidviewviewgrouplayoutparamsimport androidwidgetbuttonimport androidwidgetimageviewimport androidwidgetrelativelayoutimport androidwidgettoastsuppresslintnewapipublic class gameactivity extends activity implements ontouchlistenerstatic double screeninchesint touchstartx 0int touchstarty 0int diffx 0int diffy 0int attachedpieces0int imagex 0int imagey 0int heightwidthboolean flag new boolean7boolean isportaitrelativelayout relataivelayoutlayoutrelativelayoutlayoutparams paramsaparamsbparamscparamsdparamseparamsfimageview imageaimagebimagecimagedimageeimagefimageinfo imageinfoarray new imageinfo7 added for sound effectprivate soundpool soundpoolprivate int correctpieceattachsoundidgamefinishsoundidprivate boolean loaded falsefor 10inch landscape height 752 width 1280 portrait height 1232 width 800overrideprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate isportait getresourcesgetconfigurationorientation configurationorientation landscape false true thisplay thisplay getwindowmanagergetdefaultthisplay height thisplaygetheight width thisplaygetwidth imagea new imageviewthis imageb new imageviewthis imagec new imageviewthis imaged new imageviewthis imagee new imageviewthis imagef new imageviewthis thisplaymetrics dm new thisplaymetrics getwindowmanagergetdefaultthisplaygetmetricsdm double x mathpowdmwidthpixelsdmxdpi2 double y mathpowdmheightpixelsdmydpi2 screeninches mathsqrtxy ifscreeninches90 imageasetbackgroundresourcerdrawablea imagebsetbackgroundresourcerdrawableb imagecsetbackgroundresourcerdrawablec imagedsetbackgroundresourcerdrawabled imageesetbackgroundresourcerdrawablee imagefsetbackgroundresourcerdrawablef else imageasetbackgroundresourcerdrawableaa imagebsetbackgroundresourcerdrawablebb imagecsetbackgroundresourcerdrawablecc imagedsetbackgroundresourcerdrawabledd imageesetbackgroundresourcerdrawable imagefsetbackgroundresourcerdrawableff imageasetid1 imageasettaga paramsa new relativelayoutlayoutparamslayoutparamswrap contentlayoutparamswrap content the wrap content parameters can be replaced by an absolute width and height or the fill parent option imageasetlayoutparamsparamsa imageasetontouchlistenerthis logdgameactivity imagebsetid2 imagebsettagb paramsb new relativelayoutlayoutparamslayoutparamswrap contentlayoutparamswrap content the wrap content parameters can be replaced by an absolute width and height or the fill parent option imagebsetlayoutparamsparamsb imagebsetontouchlistenerthis imagecsetid3 imagecsettagc paramsc new relativelayoutlayoutparamslayoutparamswrap contentlayoutparamswrap content the wrap content parameters can be replaced by an absolute width and height or the fill parent option imagecsetlayoutparamsparamsc imagecsetontouchlistenerthis imagedsetid4 imagedsettagd paramsd new relativelayoutlayoutparamslayoutparamswrap contentlayoutparamswrap content the wrap content parameters can be replaced by an absolute width and height or the fill parent option imagedsetlayoutparamsparamsd imagedsetontouchlistenerthis imageesetid5 imageesettage paramse new relativelayoutlayoutparamslayoutparamswrap contentlayoutparamswrap content the wrap content parameters can be replaced by an absolute width and height or the fill parent option imageesetlayoutparamsparamse imageesetontouchlistenerthis imagefsetid6 imagefsettagf paramsf new relativelayoutlayoutparamslayoutparamswrap contentlayoutparamswrap content the wrap content parameters can be replaced by an absolute width and height or the fill parent option imagefsetlayoutparamsparamsf imagefsetontouchlistenerthis setuppieces set the hardware buttons to control the music thissetvolumecontrolstreamaudiomanagerstream music load the sound soundpool new soundpool10 audiomanagerstream music 0 soundpoolsetonloadcompletelistenernew soundpoolonloadcompletelistener override public void onloadcompletesoundpool soundpool int sampleid int status loaded true gamefinishsoundid soundpoolloadthis rrawbells 1 correctpieceattachsoundid soundpoolloadthis rrawbell 1public void playsoundint soundid audiomanager audiomanager audiomanager getsystemserviceaudio service float actualvolume float audiomanagergetstreamvolumeaudiomanagerstream music float maxvolume float audiomanagergetstreammaxvolumeaudiomanagerstream music float volume actualvolume maxvolume is the sound loaded already if loaded soundpoolplaysoundid volume volume 1 0 10f public void onconfigurationchangedconfiguration newconfig superonconfigurationchangednewconfig checks the orientation of the screen if newconfigorientation configurationorientation landscape toastmaketextthis landscape toastlength shortshow else if newconfigorientation configurationorientation portrait toastmaketextthis portrait toastlength shortshow toastmaketextthis in onconfiguaration changed toastlength shortshow isportait getresourcesgetconfigurationorientation configurationorientation landscape false true relativelayoutimageagetparentremoveallviews logdgameactivity in onconfigurationchanged setuppiecespublic void setuppieces relativelayout relataivelayoutlayout new relativelayoutthis thisplay thisplay getwindowmanagergetdefaultthisplay height thisplaygetheight width thisplaygetwidth ifisportait paramsaleftmargin 10 your x coordinate paramsatopmargin 30 your y coordinate else paramsaleftmargin 30 your x coordinate paramsatopmargin 10 your y coordinate imageasetlayoutparamsparamsa imageasetontouchlistenerthis logdgameactivity ifisportait paramsbleftmargin 650 your x coordinate paramsbtopmargin 300 your y coordinate else paramsbleftmargin 300 your x coordinate paramsbtopmargin 750 your y coordinate imagebsetlayoutparamsparamsb imagebsetontouchlistenerthis ifisportait paramscleftmargin 400 your x coordinate paramsctopmargin 380 your y coordinate else paramscleftmargin 400 your x coordinate paramsctopmargin 350 your y coordinate imagecsetlayoutparamsparamsc imagecsetontouchlistenerthis ifisportait paramsdleftmargin 750 your x coordinate paramsdtopmargin 20 your y coordinate else paramsdleftmargin 20 your x coordinate paramsdtopmargin 750 your y coordinate imagedsetlayoutparamsparamsd imagedsetontouchlistenerthis ifisportait paramseleftmargin 900 your x coordinate paramsetopmargin 400 your y coordinate else paramseleftmargin 475 your x coordinate paramsetopmargin 700 your y coordinate imageesetlayoutparamsparamse imageesetontouchlistenerthis ifisportait paramsfleftmargin 90 your x coordinate paramsftopmargin 300 your y coordinate else paramsfleftmargin 90 your x coordinate paramsftopmargin 300 your y coordinate imagefsetlayoutparamsparamsf imagefsetontouchlistenerthis imageinfo imageainfo new imageinfoimageagetidimagea12 imageinfoarray0 imageainfo imageinfo imagebinfo new imageinfoimagebgetidimageb13 imageinfoarray1 imagebinfo imageinfo imagecinfo new imageinfoimagecgetidimagec24 imageinfoarray2 imagecinfo imageinfo imagedinfo new imageinfoimagedgetidimaged35 imageinfoarray3 imagedinfo imageinfo imageeinfo new imageinfoimageegetidimagee46 imageinfoarray4 imageeinfo imageinfo imagefinfo new imageinfoimagefgetidimagef56 imageinfoarray5 imagefinfo relataivelayoutlayoutaddviewimagea relataivelayoutlayoutaddviewimageb relataivelayoutlayoutaddviewimagec relataivelayoutlayoutaddviewimaged relataivelayoutlayoutaddviewimagee relataivelayoutlayoutaddviewimagef setcontentviewrelataivelayoutlayoutprivate void updatepositionint id ifflagimageinfoarrayid1id return flagimageinfoarrayid1id true relativelayoutlayoutparams param relativelayoutlayoutparamsimageinfoarrayid1imageviewgetlayoutparams paramleftmargin imageinfoarrayid1imageviewgetleft diffx paramtopmargin imageinfoarrayid1imageviewgettop diffy imageinfoarrayid1imageviewsetlayoutparamsparam ifimageinfoarrayid1istopconnected updatepositionimageinfoarrayid1toppieceid ifimageinfoarrayid1isbottomconnected updatepositionimageinfoarrayid1bottompieceid returnoverridepublic boolean ontouchview v motionevent event ifv instanceof imageview imageview imageview imageview v imageinfo imageinfo imageinfoarrayimageviewgetid1 switch eventgetaction motioneventaction mask case motioneventaction down touchstartx int eventgetrawx touchstarty int eventgetrawy imagex imageviewgetleft imagey imageviewgettop toastmaketextthis x eventgetrawx y eventgetrawy toastlength shortshow break case motioneventaction up touchstartx int eventgetrawx touchstarty int eventgetrawy imagex imageviewgetleft imagey imageviewgettop int id imageinfoid whileimageinfoistopconnected ifimageinfoid imageinfotoppieceid break imageinfo imageinfoarrayimageinfotoppieceid1 ifimageinfoistopconnected imageview imageinfoimageview int topconnectingpieceid imageinfotoppieceid int topconnectingx0topconnectingy0 topconnectingx imageinfocalculatetopximageviewgetleft imageviewgetid topconnectingy imageinfocalculatetopyimageviewgettop imageviewgetid imageinfo topimageinfo imageinfoarraytopconnectingpieceid1 int bottomconnectingx topimageinfocalculatebottomxtopimageinfoimageviewgetlefttopconnectingpieceid int bottomconnectingy topimageinfocalculatebottomytopimageinfoimageviewgettoptopconnectingpieceid diffx bottomconnectingxtopconnectingx diffy bottomconnectingytopconnectingy ifmathabsdiffx20 mathabsdiffy20 forint i0i7i flagifalse updatepositionimageinfoid imageinfosetistopconnectedtrue topimageinfosetisbottomconnectedtrue attachedpieces ifattachedpieces5 setupfinishdialogue playsoundgamefinishsoundid else playsoundcorrectpieceattachsoundid break imageinfo imageinfoarrayid1 whileimageinfoisbottomconnected ifimageinfoid imageinfoarrayimageinfobottompieceid1id break imageinfo imageinfoarrayimageinfobottompieceid1 imageview imageinfoimageview ifimageinfoisbottomconnected int topconnectingx0topconnectingy0 int bottomconnectingx imageinfocalculatebottomximageviewgetleft imageviewgetid int bottomconnectingy imageinfocalculatebottomyimageviewgettop imageviewgetid int bottomconnectingpieceid imageinfobottompieceid imageinfo bottomimageinfo imageinfoarraybottomconnectingpieceid1 topconnectingx bottomimageinfocalculatetopxbottomimageinfoimageviewgetleftbottomconnectingpieceid topconnectingy bottomimageinfocalculatetopybottomimageinfoimageviewgettop bottomconnectingpieceid diffx topconnectingxbottomconnectingx diffy topconnectingybottomconnectingy ifmathabsdiffx20 mathabsdiffy20 forint i0i7i flagifalse updatepositionimageinfoid imageinfosetisbottomconnectedtrue bottomimageinfosetistopconnectedtrue attachedpieces ifattachedpieces5 setupfinishdialogue playsoundgamefinishsoundid else playsoundcorrectpieceattachsoundid break case motioneventaction move diffx int eventgetrawx touchstartx diffy int eventgetrawy touchstarty touchstartx inteventgetrawx touchstarty inteventgetrawy forint i0i7i flagifalse updatepositionimageinfoid break default break return truevoid lockorientation switch getresourcesgetconfigurationorientation case configurationorientation portrait ifandroidosbuildversionsdk int androidosbuildversion codesfroyo setrequestedorientationactivityinfoscreen orientation portrait else int rotation getwindowmanagergetdefaultthisplaygetrotation ifrotation androidviewsurfacerotation 90 rotation androidviewsurfacerotation 180 setrequestedorientationactivityinfoscreen orientation reverse portrait else setrequestedorientationactivityinfoscreen orientation portrait break case configurationorientation landscape ifandroidosbuildversionsdk int androidosbuildversion codesfroyo setrequestedorientationactivityinfoscreen orientation landscape else int rotation getwindowmanagergetdefaultthisplaygetrotation ifrotation androidviewsurfacerotation 0 rotation androidviewsurfacerotation 90 setrequestedorientationactivityinfoscreen orientation landscape else setrequestedorientationactivityinfoscreen orientation reverse landscape break void setupfinishdialogue ifgetwindowmanagergetdefaultthisplaygetrotation3 setrequestedorientationactivityinfoscreen orientation portrait else ifgetwindowmanagergetdefaultthisplaygetrotation1 setrequestedorientationactivityinfoscreen orientation reverse portrait else ifgetwindowmanagergetdefaultthisplaygetrotation2 setrequestedorientationactivityinfoscreen orientation reverse landscape else setrequestedorientationactivityinfoscreen orientation landscape setrequestedorientationactivityinfoscreen orientation nosensor lockorientation alertdialogbuilder builderforalertbox new alertdialogbuilderthis builderforalertboxsetcancelablefalsesetmessagegood jobsetpositivebuttonrestart dialogclicklistnersetnegativebuttonquit dialogclicklistner setcancelabletrueshow dialoginterfaceonclicklistener dialogclicklistner new dialoginterfaceonclicklistener public void onclickdialoginterface dialog int which setrequestedorientationactivityinfoscreen orientation sensor switch which case dialoginterfacebutton positive finish intent intent new intentgetapplicationcontextgameactivityclass startactivityintent break case dialoginterfacebutton negative finish default break imageinfo classpackage comexamplejigsawpuzzleimport androidwidgetimageviewimport androidwidgettoastpublic class imageinfo imageview imageviewint imageatopleftdifferencex 1int imageatopleftdifferencey 1int imageabottomrightdifferencex 113int imageabottomrightdifferencey 140int imagebtopleftdifferencex 0int imagebtopleftdifferencey 0int imagebbottomrightdifferencex 0int imagebbottomrightdifferencey 1int imagectopleftdifferencex 14int imagectopleftdifferencey 0int imagecbottomrightdifferencex 0int imagecbottomrightdifferencey 88int imagedtopleftdifferencex 92int imagedtopleftdifferencey 2int imagedbottomrightdifferencex 0int imagedbottomrightdifferencey 70int imageetopleftdifferencex 0int imageetopleftdifferencey 0int imageebottomrightdifferencex 55int imageebottomrightdifferencey 112int imageetopleftdifferencex 55int imageetopleftdifferencey 112int imageebottomrightdifferencex 0int imageebottomrightdifferencey 0int imageftopleftdifferencex 0int imageftopleftdifferencey 26int imagefbottomrightdifferencex 0int imagefbottomrightdifferencey 109int idtoppieceidbottompieceidint imageftopleftdifferencex 0int imageftopleftdifferencey 109int imagefbottomrightdifferencex 0int imagefbottomrightdifferencey 26int idtoppieceidbottompieceidboolean istopconnected falseboolean isbottomconnected falsepublic imageinfoint idimageview imageviewint toppieceidint bottompieceid thistoppieceid toppieceid thisbottompieceid bottompieceid thisimageview imageview thisid id ifid1 istopconnected true else ifid6 isbottomconnected true ifgameactivityscreeninches90 initializepiecesinfoprivate void initializepiecesinfo imageatopleftdifferencex 0 imageatopleftdifferencey 0 imageabottomrightdifferencex 150 imageabottomrightdifferencey 184 imagebtopleftdifferencex 0 imagebtopleftdifferencey 0 imagebbottomrightdifferencex 0 imagebbottomrightdifferencey 148 imagectopleftdifferencex 23 imagectopleftdifferencey 0 imagecbottomrightdifferencex 0 imagecbottomrightdifferencey 115 imagedtopleftdifferencex 121 imagedtopleftdifferencey 0 imagedbottomrightdifferencex 0 imagedbottomrightdifferencey 91 int imageetopleftdifferencex 0 int imageetopleftdifferencey 0 int imageebottomrightdifferencex 55 int imageebottomrightdifferencey 112 imageetopleftdifferencex 74 imageetopleftdifferencey 147 imageebottomrightdifferencex 0 imageebottomrightdifferencey 0 int imageftopleftdifferencex 0 int imageftopleftdifferencey 26 int imagefbottomrightdifferencex 0 int imagefbottomrightdifferencey 109 int idtoppieceidbottompieceid imageftopleftdifferencex 0 imageftopleftdifferencey 144 imagefbottomrightdifferencex 0 imagefbottomrightdifferencey 26int calculatetopxint realxint id ifid2 return realximagebtopleftdifferencex ifid3 return realximagectopleftdifferencex ifid4 return realximagedtopleftdifferencex ifid5 return realximageetopleftdifferencex ifid6 return realximageftopleftdifferencex return realxint calculatetopyint realyint id ifid2 return realyimagebtopleftdifferencey ifid3 return realyimagectopleftdifferencey ifid4 return realyimagedtopleftdifferencey ifid5 return realyimageetopleftdifferencey ifid6 return realyimageftopleftdifferencey return realyint calculatebottomxint realxint id ifid1 return realximageabottomrightdifferencex ifid2 return realximagebbottomrightdifferencex ifid3 return realximagecbottomrightdifferencex ifid4 return realximagedbottomrightdifferencex ifid5 return realximageebottomrightdifferencex return realximagefbottomrightdifferencex int calculatebottomyint realyint id ifid1 return realyimageabottomrightdifferencey ifid2 return realyimagebbottomrightdifferencey ifid3 return realyimagecbottomrightdifferencey ifid4 return realyimagedbottomrightdifferencey ifid5 return realyimageebottomrightdifferencey return realyimagefbottomrightdifferenceyvoid setistopconnectedboolean istopconnected thisistopconnected istopconnectedvoid setisbottomconnectedboolean isbottomconnected thisisbottomconnected isbottomconnected,['android'] +417157,how to get true size of mysql database i would like to know how much space does my mysql database use in order to select a web hosti found the command show table status like table name so when i do the query i get something like thisname rows avg row length data length index length table name 400 55 3620 66560numbers are roundedso do i have 3620 or 4003620 14480 bytes of data for this tableand what does index length meanthanks,['mysql'] +417169,why does prototyping function not affect consolelog i prototyped function so that it has a getbody functionfunctionprototypegetbody function get content between first and last var m thistostringmatchssm1 strip comments return mreplacesmgsee here for more infoi tried to test it this wayconsolelogconsoleloggetbodygetbodybut received an error typeerror consoleloggetbody is undefinedi figured out that maybe this happens because consolelog was defined before i actually prototyped function so i created an empty function x right before the prototyping and tried to call consolelogxgetbodygetbodywhich worked without a problem checking the type of consolelog with typeof consolelog results in function heres a codepen to try it out all of this was not really a surprise since it is what i expected except of consoleloggetbody to be undefinedso why does prototyping function not affect consolelog i am using firefox 1801 with firebug 1,['javascript'] +417183,spring mvc 32 content negotiation for error pages to globally handle errors such as http 404s which can occur outside of a controller i have entries similar to the following in my webxmlerrorpage errorcode404errorcode locationerrors404locationerrorpagein my errorcontroller i have corresponding methods similar to the followingcontrollerrequestmappingerrorspublic class errorcontroller requestmappingvalue 404 method requestmethodget responsebody public responseentityerrorresponse error404 errorresponse errorbody new errorresponse404 resource not found return new responseentityerrorresponseerrorbody httpstatusnot found the issue i am facing is that the contentnegotiationmanager and message converters i have configured are not being used in this case i suspect that since the request is being redirected to the error page the original requests attributes used in content negotiation are lost and this is treated as a completely separate request ie original request for mycontrollerbadresourcejson errors404 wno file extensionis there any way in an error handler like this determine andor respond with the appropriate content type as requested in the original request,['java'] +417211,adding extra axis ticks using matplotlib i have a simple plot code aspltplotxypltshowi want to add some extra ticks on the xaxis in addition to the current ones let us say atextraticks21 3 76as you see i do not have a pattern for ticks so i do not want to increase the tick frequency for the whole axis just keep the original ones and add those extrasis it possible at allregards,['python'] +417213,send a boolean value in jquery ajax data i am sending some data in an ajax call one of the values is a boolean set to false it is always evaluated as true in the php script called by the ajax any ideas ajax type post data photo id photo id vote 1 undo vote false this is the important boolean url buildajaxesvotephp success functiondata consolelogdata in votephp the script that is called in the above ajax i check the boolean valueif postundo vote true photoundo vote postphoto id else photovote postphoto id postvotebut the postundo vote true condition is always met,"['php', 'jquery']" +417253,chrome does not recalculate width when height changes i have a list of thumbnails with links and images so when the user hover an li element it is height becomes 100 but the problem it works wrong in chrome for some odd reason i do not understand why in chrome the hovered li width does not adjust to its new sizenote this is a simplified version of my problem also this problem occurs only on hover but not lets say with nthchild playground linkupdate problem continues see my solution in the answers but the problem continuesi have zoom in with the mouse and you will see it happeningnote that number of images can be hugeupdate 2force a redraw every mousehweel event firesthumbshideshow0,['css'] +417278,uirefreshcontrol beginrefreshing not working when uitableviewcontroller is inside uinavigationcontroller i have setup a uirefreshcontrol in my uitableviewcontroller which is inside a uinavigationcontroller and it works as expected ie pull down fires the correct event however if i programmatically invoke the beginrefreshing instance method on the refresh control likeselfrefreshcontrol beginrefreshingnothing happens it should animate down and show the spinner the endrefreshing method works properly when i call that after the refreshi whipped up a basic prototype project with this behavior and it works properly when my uitableviewcontroller is added directly to application delegates root view controller egselfviewcontroller tableviewcontrollerselfwindowrootviewcontroller selfviewcontrollerbut if i add the tableviewcontroller to a uinavigationcontroller first then add the navigation controller as the rootviewcontroller the beginrefreshing method no longer works eguinavigationcontroller navcontroller uinavigationcontroller alloc initwithrootviewcontrollertableviewcontrollerselfviewcontroller navcontrollerselfwindowrootviewcontroller selfviewcontrollermy feeling is this has something to do with the nested view hierarchies within the navigation controller not playing nice with the refresher control any suggestionsthanks,"['ios', 'objective-c']" +417307,sql server check to see if cast is possible i have the following code to cast nvarchar to integer castvalue as inthowever i have no control of the parameter value hence the code might fail is there anyway to check if a cast is possible before doing a cast,['sql'] +417338,uitextview and the mysterious missing space i have an app with a handful of uitextviews of various sizes it appears that if a uitextview small enough has a fontpointsize high enough there is no way to add a space after the text is big enough to fill the text viewfor examplei am trying to figure out what was going on here i starting typing my usual debug string i typed what hit the space key and no space appeared but this is usual i typed the and the looked like it was tacked right onto the end of the previous word sure enough there was no space i could go back and add the space just fine and once i do add the space i can add other spaces as word wrapping then becomes effectiveanother mysterious behavior is that when you double tap space it does not add a period to the end it replaces the last character with a period so what space space becomes whanow i am doing some interesting things with the font size like i am automatically resizing the font so that the text fills the space provided within reasonable bounds but when i thisable that i can still reproduce the behavior the only difference then is that instead of fitting on one line the word wraps to the next linefor example if i type what space the it comes out whatthe with what on the first line and the on the second though i can only see the tops of the the further heres some log information from the textviewdidchangecharacter textviewtextlength w 1h 2a 3t 4space 4t 5h 6space 7 heres a wierd one now spaces all 8 work fine unless it is resizing,"['ios', 'iphone', 'objective-c']" +417360,css floats overlapping boxes i have been messing with css trying to understand floats etc here is what the issue looks likeas you can see the yellow box floats behind the gray and past it how do i make it stop right before box two here is my codestyleresests beginhtml body div span object iframeh1 h2 h3 h4 h5 h6 p blockquote preabbr address cite code del dfn em img ins kbd q sampsmall strong sub sup var b i dl dt ddfieldset form label legendtable caption tbody tfoot thead tr th tdarticle aside canvas details figcaption figurefooter header hgroup menu nav section summarytime mark audio video margin 0 padding 0 border 0 fontsize 100 font inherit verticalalign baseline fontweightnormalarticle aside details figcaption figurefooter header hgroup menu nav section thisplay blockresests endbody fontsize16px margin5pxh1 fontsize2emnav backgroundcolorc padding5px width200px height200px margin10pxa backgroundcolorffc padding10pxrset paddingleft10px floatrightstyleheadbodyh1titleh1nav classrset pa hreftwoapnavdiv ida h3oneh3divbodyhtml,['css'] +417398,paypal recurring payment transaction error 11502 token is invalid i am new to paypal and i need to implement a subscription recurring payment for my clienti am using paypal sandbox for its implementation i followed the way that the paypal insists for creating a recurring payment profile on getting success acknowlegment from setexpresscheckout getexpresscheckout and doexpresscheckout i have tried to create the recurring payment profile with the token from the doexpresscheckoutpayment response but the response from the createrecurrinpayment profile returns failure stating that the toke in ivnalid i tried by setting billingagreementdescription and billingtyperecurringpayments on my set express checkout request but also the same error persistsplease find the code i used to implement the recurring deposit belowsetexpresscheckoutnamevaluecollection values new namevaluecollection valuesmethod setexpresscheckout valuesreturnurl paypalsettingsreturnurl valuescancelurl paypalsettingscancelurl valuespaymentaction sale valuescurrencycode usd valuesbuttonsource ppecwizard valuesuser paypalsettingsusername valuespwd paypalsettingspassword valuessignature paypalsettingssignature valuessubject valuesl name0 myname valuesl amt0 20 valuesversion 23 valuesamt paypalsettingsorderamount valuesl billingtype0 recurringpayments valuesl billingagreementdescription0 test subscription values submitvalues string ack valuesacktolower if ack success ack successwithwarning return new paypalredirect token valuestoken url stringformathttps0cgibinwebscrcmd expresscheckouttoken1 paypalsettingscgidomain valuestoken else throw new exceptionvaluesl longmessage0 submitprivate static namevaluecollection submitnamevaluecollection values string data stringjoin valuescaststring selectkey stringformat01 key httputilityurlencodevalueskey httpwebrequest request httpwebrequestwebrequestcreate stringformathttps0nvp paypalsettingsapidomain requestmethod post requestcontentlength datalength using streamwriter writer new streamwriterrequestgetrequeststream writerwritedata using streamreader reader new streamreaderrequestgetresponsegetresponsestream return httputilityparsequerystringreaderreadtoend getexpresscheckoutpublic actionresult succestring token getexpresscheckout getexpresscheckout new getexpresscheckout getexpresscheckoutdetailsresponsetype getexpresscheckoutresponse getexpresscheckoutecgetexpresscheckoutcodetoken if getexpresscheckoutresponseack ackcodetypesuccess expresscheckout expresscheckout new expresscheckout doexpresscheckoutpaymentresponsetype doexpresscheckoutresponse expresscheckoutdoexpresscheckoutpayment token getexpresscheckoutresponsegetexpresscheckoutdetailsresponsedetailspayerinfopayerid paypalsettingsorderamount paymentactioncodetypesale currencycodetypeusd if doexpresscheckoutresponseack ackcodetypesuccess createrecurringpaymentsprofile createrecurringpaymentsprofile new createrecurringpaymentsprofile createrecurringpaymentsprofileresponsetype recurringpaymentprofileresponse createrecurringpaymentsprofilecreaterecurringpaymentsprofilecode doexpresscheckoutresponsedoexpresscheckoutpaymentresponsedetailstoken doexpresscheckoutresponsetimestamp paypalsettingsorderamount 1 billingperiodtypemonth currencycodetypeusd if recurringpaymentprofileresponseack ackcodetypesuccess createreecurringpaymentsprofilepublic createrecurringpaymentsprofileresponsetype createrecurringpaymentsprofilecodestring token datetime date string amount int bf billingperiodtype bp currencycodetype currencycodetype callerservices caller new callerservices iapiprofile profile profilefactorycreatesignatureapiprofile set up your api credentials paypal end point and api version profileapiusername paypalsettingsusername profileapipassword paypalsettingspassword profileapisignature paypalsettingssignature profileenvironmentsandbox callerapiprofile profile create the request object createrecurringpaymentsprofilerequesttype pp requestnew createrecurringpaymentsprofilerequesttype pp requestversion510 add requestspecific fields to the request pp requestcreaterecurringpaymentsprofilerequestdetails new createrecurringpaymentsprofilerequestdetailstype pp requestcreaterecurringpaymentsprofilerequestdetailstokentoken pp requestcreaterecurringpaymentsprofilerequestdetailsrecurringpaymentsprofiledetailsnew recurringpaymentsprofiledetailstype pp requestcreaterecurringpaymentsprofilerequestdetailsrecurringpaymentsprofiledetailsbillingstartdatedate pp requestcreaterecurringpaymentsprofilerequestdetailsscheduledetailsnew scheduledetailstype pp requestcreaterecurringpaymentsprofilerequestdetailsscheduledetailspaymentperiodnew billingperioddetailstype pp requestcreaterecurringpaymentsprofilerequestdetailsscheduledetailspaymentperiodamountnew basicamounttype pp requestcreaterecurringpaymentsprofilerequestdetailsscheduledetailspaymentperiodamountvalue amount pp requestcreaterecurringpaymentsprofilerequestdetailsscheduledetailspaymentperiodamountcurrencyid currencycodetypeenum for currency code is currencycodetypeusd pp requestcreaterecurringpaymentsprofilerequestdetailsscheduledetailspaymentperiodbillingfrequencybf pp requestcreaterecurringpaymentsprofilerequestdetailsscheduledetailspaymentperiodbillingperiodbpenum for billingperiod is billingperiodtypeday pp requestversion 510 pp requestcreaterecurringpaymentsprofilerequestdetailsscheduledetailsdescription test subscription pp requestcreaterecurringpaymentsprofilerequestdetailsscheduledetailsdescription execute the api operation and obtain the response createrecurringpaymentsprofileresponsetype pp responsenew createrecurringpaymentsprofileresponsetype pp response createrecurringpaymentsprofileresponsetype callercallcreaterecurringpaymentsprofile pp request return pp response any help will be greatly appreciatedthanks in advance,"['c#', 'asp.net']" +417430,derivedclass constructor names being deprecated in php currently php supports two naming conventions for constructors php 4 supported javastyle constructorsclass a public function a echo i am a constructor for class a php 5 supports both the javastyle constructors and a magic method syntaxclass a public function construct echo i am a constructor for class a the javastyle syntax is slated for deprecation and some features of it do not work in the latest php however it has an interesting property that i know of no analogue for with the magic method syntax if derived class foobar has no explicit constructor then the foobar method of the base class becomes the foobar constructorclass a public function a echo i am a constructor for class a public function b echo i am a constructor for class b class b extends asince javastyle constructors are being deprecated what will become of the settheconstructorintheparent language feature,['php'] +417597,when liskov substitution refers to subtypes is it talking about derived classes in the context of c i am unfamiliar with the word subtype after looking at the wikipedia article i took liskov substitution to mean if you have a method that takes an animal you should be able to pass in a cat or an animal where cat animal without any unintended side effectsis this what liskov substitution refers to,['c#'] +417613,how to make uiview animation sequence repeat and autoreverse how to make this complex animation repeat and autoreverseis there any way to add options uiviewanimationoptionautoreverse uiviewanimationoptionrepeat to this animation sequence uiview animatewithduration10f animations someviewframe someframe1 completionbool finished uiview animatewithduration05f animations someviewframe someframe2 completionnil,"['ios', 'objective-c']" +417657,using httpclient how would i prevent automatic redirects and get original status code and forwading url in the case of 301 i have the following method that returns the http status code of a given url public static async void makerequestint row string url string result stopwatch sw new stopwatch swstart try using httpclient client new httpclient httpresponsemessage response new httpresponsemessage response await clientgetasyncurl dump contents of header consolewriteline responseheaderstostring if responseissuccestatuscode result intresponsestatuscodetostring else result intresponsestatuscodetostring catch httprequestexception hre result server unreachable swstop long time swelapsedticks stopwatchfrequency 10l 10l requestcompleterow url result time it works well for 200404 etc however in the case of 301 codes i believe the returned result is the alreadyredirected 200 result rather than the actual 301 that should be returned and which would have a header containing where the redirect would be pointed toi have seen something like this in other net web requests classes and the technique there was to set some sort of allowautoredirect property to false if this is along the right lines can anyone tell me the correct alternative for the httpclient classthis post has info on the above allowautoredirect concept i meanelse how might i get this method to return 301s rather than 200s for urls i know to be genuine 301s,['c#'] +417700,class cast exception in android stringxml i am developing an androidapp that uses the facebooksdkv3 so i created an entry in the stringsxmlresources string namefacebook app id12345678910stringresourcesand added the following to the manifestapplication metadata androidnamecomfacebooksdkapplicationid androidresourcestringfacebook app id applicationi always get this exception0206 163501231 wbundle8316 key comfacebooksdkapplicationid expected string but value was a javalanginteger the default value was returned 0206 163501231 wbundle8316 attempt to cast generated internal exception 0206 163501231 wbundle8316 javalangclasscastexception javalanginteger cannot be cast to javalangstring 0206 163501231 wbundle8316 at androidosbundlegetstringbundlejava1061 0206 163501231 wbundle8316 at comfacebookinternalutilitygetmetadataapplicationidutilityjava159i already tried to put the numbers in but this did not solve the problem hope somebody can help me,['android'] +417760,prevent garbage collection for managed reference which is used in unmanaged code my c application uses wrapped c code for calculationsc header declspecdllexport void setvolumebyte data unsigned int widthccli wrappervoid setvolumearraybyte data uint32 width clipin ptrbyte pdata data0 palsetvolumepdata width c public startcalc byte voxelarr filereadallbytesfilteredrec palwsetvolumevoxelarr 490 gckeepalivevoxelarr makes no sensethe c setvolume function starts asynchronous calculations voxelarr is not referenced from the managed side any longer and is garbage collected how can i prevent the garbage collection for this reference until the unmanaged code finished it is work without to declare voxelarr as global variable creating a copy of array is not an option as there is really a lot of data active wait inside of startcalc is not good too,['c#'] +417762,which standard wording tells us that reftoconst temporary lifetime extension only works once i was shown the following example in chatinclude iostreamstruct foo foo stdcout destroyingn const foo funcconst foo a const foo return a int main foo x const foo y funcfoo x stdcout mainnoutputdestroyingmaindestroyingit appears to demonstrate that the lifetime of the foo temporary is not extended to entirety of main even though it gets bound to a reftoconst in that scopepresumably then the lifetime extension only works once that is it is applied when funcs arguments are initialised but is not passed on through consecutive bindingsis my interpretation correct if so and if any individual paragraph is directly applicable whats the standard wording that defines this behaviour,['c++'] +417815,what does a constructor return in java after going on the post on this topic i found my self little confusedso again asking this does java constructor returns any value books say they cant return a value but the professor says they can and they are always doingas the control is need to be transferred to some one with some value either void,['java'] +417819,get pip to work with git and github repository i am writting a python app that depends on another one that is hosted on a github repository never in pypi for development reasonslets call themapp being written appaapp in github appbin app a the setuppy is like codingutf8import systry from setuptools import setup find packagesexcept importerror import thistribute setup thistribute setupuse setuptools from setuptools import setup find packagessetup install requires other requirements that install correctly app b011 dependency links git eggapp b011 now appa is being built by jenkins ci with every push and i get a failure because of the next error is thrownerror download error for git unknown url type githttpsfunny thing is that this only happens in jenkins it works perfectly on my computer i tried both of the other ssh urls that github gives and those are not even considered for downloadnow appa is included in the requirements file of a project also being built by jenkins so installing the dependencies manually via pip install appa pip install appb is not an option the dependencies are automatically installed by being included in the requirementstxtis there any way to make pip and git with github urls work togetherany help will be very appreciated thanks in advance,['python'] +417830,jlabel show longer text as multiple lines so say i have a really long line that i want to thisplay in a jlabel how can i do itcurrently longer lines come up as thisi have to resize the window to see the complete texthow can i make it so that there is linebreaks when the text almost reaches the width of my jframei am not sure if any code is required here for you to answer this but stillmy frame propertiesframe new jframeframesetdefaultcloseoperationjframeexit on closeframesetsizenew dimension450 400framesetlocationnew point400 300framesetlayoutnew borderlayoutthe label i want to modifyquestion new jlabelquestionquestionsetfontnew fontserif fontbold 15questionsethorizontalalignmentjlabelcentereditmore detailsi am reading lines from a file and then thisplaying them the size of lines is not fixed and so i do not know where to put br atedit 2i ended up using jtextareaprivate jtextarea textareapropertiesjtextarea textarea textareaseteditablefalse textareasetcursornull textareasetopaquefalse textareasetfocusablefalse textareasetlinewraptrue textareasetwrapstylewordtrue return textarea,['java'] +417868,an aggregate may not appear in the set list of an update statement update asgdb01dboinfo set fm sumapazartesi bkota from asgdb01dboinfo a asgdb01dbokota b where awork typein and anamealpwhen i run this i get the following erroran aggregate may not appear in the set list of an update statementany ideas,['sql'] +417885,difference between getclassgetclassloadergetresource and getclassgetresource when retrieving files from resources which one should i use in what circumstances,['java'] +417888,ruby classes within classes or modules within modules as i am reading different ruby books i have noticed that ruby classes can be defined within other ruby classes or modules heres an example of a class within a classclass outerclass def foobar puts foobar end class innerclass def barfoo puts barfoo end endendheres some code that i ran in irb to try to understand this conceptuallyoc outerclassnew outerclass0x0100a46478outerclassinstance methodsfalse foobaric outerclassinnerclassnew outerclassinnerclass0x0100a0b120ic outerclassinnerclassinstance methodsfalse barfoohere are my questionswhen the ruby interpreter first encounters my class definition code above does it go through the methods i have written and store it somewhere i know that the instance method foobar does not actually get run since there is no call being made to it within the outerclass definitionpiggybacking off the 1st question what about when ruby encounters the class innerclass what happens herein general what are some reasons why you would want to have classes within classes are there any advantages to doing thisdoes an instance of outerclass know anything about the class innerclassdoes an instance of innerclass know anything about the class outerclassappreciate any help you can provide,['ruby'] +417897,can i run a loop in mysql without using a procedurefunction for testing is it possible to run a loop from mysql workbench or similar tool i tried but got an errorif it is possible please supply a simple example i can run,['mysql'] +417947,work with two separate rethis instances with sidekiq good afternooni have two separate but related apps they should both have their own background queues read separate sidekiq rethis processes however i would like to occasionally be able to push jobs onto app2s queue from app1from a simple queuepush perspective it would be easy to do this if app1 did not have an existing sidekiqrethis stack in a process far far away configure client sidekiqconfigure client do config configrethis url rethisrethisexamplecom737212 namespace mynamespace end push jobs without class definition sidekiqclientpushclass exampleworkerstrace args hello push jobs overriding defaults sidekiqclientpushqueue example retry 3 class exampleworkerstrace args hellohowever given that i would already have called a sidekiqconfigure client and sidekiqconfigure server from app1 there is probably a step in between here where something needs to happenobviously i could just take the serialization and normalization code straight from inside sidekiq and manually push onto app2s rethis queue but that seems like a brittle solution i would like to be able to use the clientpush functionalityi suppose my ideal solution would be someting likesidekiqtwoconfigure client remote connection sidekiqtwoclientpushjobor evenrethis remote remote connectionsidekiqclientpushjob rethis remoteobviously a bit facetious but that is my ideal use casethanks,['ruby-on-rails'] +418086,android sideloading applications and keep them up to date via google play my company would like to give an android device to a group of our selected customersdoing that we would like to provide users with our mobile app the app is already on google play but we would like to avoid users downloading and installing by themselves we prefer to give the device ready with the app already installedwe found several ways to manually install an apk on the phone without having to login to the market but it seems that doing that the user will not be able to update the app via google play as the app would not be recognized as installedany idea,['android'] +418094,making span tag cover entire width of div i have the following structure for htmldiv span a hrefwhereverwherevera spandivif i want the span to cover the entire width of the div how can i do that in chromei tried in css usingspan backgroundf width100it works in firefox and ie but not in chrome,"['css', 'html']" +418097,post request using python to aspnet page i want scrap the pincodes from i am doing with following code writtenimport urllibimport urllib2headers accepttexthtmlapplicationxhtmlxmlapplicationxmlq09q08 origin useragent mozilla50 windows nt 61 applewebkit53717 khtml like gecko chrome240131257 safari53717 contenttype applicationxwformurlencoded referer acceptencoding gzipdeflatesdch acceptlanguage enusenq08 acceptcharset iso88591utf8q07q03viewstate julxdv576zuxovowthqqj4bdusexwdczmp0tthykdhovpbxg8ymisvtybsnqlnn76exeventvalidation 8xjw9gg8lmh6ab6jowr970cqchej956ezvxaqkqc1at06mdfiy7iyzh7813e13elxurl formdata eventvalidation eventvalidation eventtarget eventargument viewstate viewstate viewstateencrypted eventvalidation eventvalidation txt offname ddl thist0 txt thist on ddl state2 btn statesearch txt stateon hdn tabchoice3from urllib import fancyurlopenerclass myopenerfancyurlopener version mozilla50 windows nt 61 applewebkit53717 khtml like gecko chrome240131257 safari53717myopener myopenerencodedfields urlliburlencodeformdataf myopeneropenurl encodedfieldsprint finfotryfout opentmptxt wexceptprintcould not open output filenfoutwritelinesfreadlinesfoutclosei am getting response from server as sorry this site has encountered a serious problem please try reloading the page or contact webmasterpl suggest where i am going wrong,['python'] +418116,how bad is it to do ajax without jquery i have come to the point where i need ajax on my page but it is just for one small part to see if a username typed in is in the database as explained here ajax can be done with javascript alone what are the proscons of doing it this way i am leaning towards this because i do not want a large library and think it is unnecessarily complicated when everything else is already javascript alone,"['javascript', 'jquery']" +418133,android process produces logcat has died message very often i am working on an app that runs as a service and waits for a message after i check the log i find out that android kills and restarts many processes very often this not only happens to my app but is the same for many other services i cannot see any reason for this and my device has enough memory i test with a sony xperia s running android 404 is this normal or a bughere is a part of the log to show you what i mean0204 150238791 320 332 i activitymanager process comandroidemail pid 32763 has died0204 150238791 320 332 w activitymanager scheduling restart of crashed service comandroidemailservicemailservice in 50ms and 13 minutes later 0204 151532601 320 694 i activitymanager process comandroidemail pid 1453 has died,['android'] +418160,linq group by contiguous blocks let us say i have following datatime status 10 on 1100 off 1200 off 1300 off 1400 off 1500 on 1600 onhow could i group that using linq into something likeon 10 off 1100 1200 1300 1400 on 1500 1600,['c#'] +418168,placeholder backgroundimage while waiting for full image to load i have a few images on my page i am finding that the page starts to render before the images have been loading which is good but that the visual effect is not great initially the user sees this hr textthen a few milliseconds later the page jumps to show thishr image textis there a simple way that i can show a grey background image of exactly the width and height that the image will occupy until the image itself loadsthe complicating factor is that i do not know the height and width of the images in advance they are responsive and just set to width 100 of the containing div this is the htmlcssdiv classthumbnailimg srcmyimagejpeg div classcaptioncaptiondivdivimg width 100 heres a jsfiddle to illustrate the basic problem i have looked into things like lazyload but i cannot help feeling there must be a simpler nonjs answer or is the fact that i do not know the height of the image in advance an insurmountable problem i do know the aspect ratio of the images,['css'] +418182,what happens if compiler inlines a function which is called through a function pointer let us say i have a function in my program and somewhere in my code that function is called through a function pointer what happens if the compiler happened to inline that function or would the compiler realize that there is a function pointer assigned to that function and therefore avoid inlining it,"['c++', 'c']" +418243,how do i retrieve composer via ant i am trying to get make my ant script retrieve composer for me composer is a dependancy manager for php according to the doc one needs to run this command curl s php which will download composerphar into the directory i am in this works as intended when running from a terminalhow do i setup the ant build file for this so far i have got this segment for the composerget target but it is does not save the file only output it in my command shell target namecomposerget descriptioncomposer update dependencies exec executablecurl arg lines arg line arg line php exec targetany help is greatly appeciated,['php'] +418269,how to apply before filter to every action of every controller in rails 3211 i would like to verify if the user is logged in on every single request to the serversomething like before filter verify logged inwhere should i put that before filter so it applies to all controller actions and all requests,['ruby'] +418273,mongodb print json without whitespace ie unpretty json i am using mongodb 220 and am trying to print json in a single line as opposed to pretty printing using printjson or findpretty ie i need the documents listed in json format as done by just running the command dbcollectionfindlimit10 but i need it done using a cursor in a javascript file as followsvar cursor dbcollectionfindsort id1limit10whilecursorhasnext printnonprettyjsoncursornext howprint does not do the job it just prints some gibberish about the object identifier the reason i want this is because i am calling the javascript file from the console and then passing the output to a file as followsmongo mydatabase myjsfilejs tmpmyoutputtxtedit i want the output as follows dbzipsfindlimit2 city acmar loc 8651557 33584132 pop 6055 state al id 35004 city adamsville loc 86959727 33588437 pop 10616 state al id 35005 and not like dbzipsfindlimit2pretty city acmar loc 8651557 33584132 pop 6055 state al id 35004 city adamsville loc 86959727 33588437 pop 10616 state al id 35005as is given by all the other methods again i need this using a cursor object,['javascript'] +418274,creating a config file in php i want to create a config file for my php project but i am not sure what the best way to do this isi have 2 ideas so far1use variableconfighostname localhostconfigdbuser dbuserconfigdbpassword dbpasswordconfigdbname dbnameconfigsitetitle sitetitle2use constdefinedb name testdefinedb user rootdefinedb password definedb host localhostdefinetitle sitetitle3use databasei will be using the config in classes so i am not sure which way would be the best or if there is a better way,['php'] +418277,infinite redirect loop on android when redirecting from server with angularjs i am building a webphonegap application for an older version of android 23x everything works great up until i try to add any server redirection into the mix heres the scenariothe server nodejs has a route listening at when this route is hit it checks to see if the there is a session or not if there is no session it redirects to login fine this part works server wise anyways the problem arises when the client gets the redirect because android 23 does not support historypushstate it falls back to hashbangs this means angularjs rewrites the url to login which causes a server request to which causes the server to check session and redirect to login which causes angularjs to rewrite the url to login and so on and so forth indefinitely any ideas how i can redirect from the server with angularjs should i not be handling this logic in my route but instead try to implement it on the client there has to be a way to handle this i am sure but i just cannot seem to figure it outany help would be greatly appreciated thanks,['android'] +418281,geventhttphttpserver api suggests streaming but instead buffers entire requests and responses the apis offered by geventhttphttpserver would seem to support streaming in both directions the request object does not offer the request body as a simple string but instead provides an input buffer attribute that is a python iterable while in the other direction the data for a response can be delivered as chunks with the three callsrequestsend reply start200 okrequestsend reply chunk as many times as you wishrequestsend reply endbut i must have something misconfigured because despite this wonderfully unbuffered api my request handler is not getting called until the last chunk of request post data has finally arrived and in the other direction i am not seeing any headers arrive on my client socket until the server reaches send reply end is there some switch that i have to throw or some configuration setting that i have to manipulate in order to turn off buffering and see requests and send responses as they arrive like gevent supports with raw sockets through its streamservermy application needs to supports singlefile uploads and downloads that may be bigger than ram which will require this buffering to be turned offhere are a simple server and client written with gevent that should show you this behavior srvpyimport geventhttpm100 100 1024 1024def main print serving on 8088 geventhttphttpserver0 8088 handleserve foreverdef handlerequest print is request chunked requestchunked for item in requestinput buffer print received body segment of length lenitem bytes requestadd output headercontenttype applicationoctetstream requestsend reply start200 ok for i in range5 print sending chunk i requestsend reply chunkm100 x requestsend reply endif name main mainand clipyimport requestsimport timem100 100 1024 1024def gen for i in range5 print sending chunk i yield m100 x timesleep1if name main r requestsposthttplocalhost8088 datagen streamtrue for block in riter contentm100 print received lenblock bytes from downloadthanks for any guidance,['python'] +418369,stopping jetty from throwing stacktrace whenever it receives an invalid http request i am running my servlet application within jetty and it sometimes outputs the belowshown stack trace i think this means it is receiving an invalid url request but i cannot actually see the request can i handle this exception somwehere so that my logs are not clogged up with this nasty stack trace and if so can it handled in my code or does this error occur before getting to my code and therefore needs to be handled with jetty configurationeditso if i did move to jeety 9 how could i configure it so the stacktrace goes and could i configure a suitable http response codealternaively i have realized that jetty is receiving the request after it has been processed by is there something sensible i should configure in urlrewritefilter to do something else if the generated url is invalid201301 234810939warnoejuurlencodedorgeclipsejettyutilutf8appendablenotutf8exception not valid utf8 byte b0 in state 0201301 234810939warnoejsservlethandlerws2releaseorgeclipsejettyutilutf8appendablenotutf8exception not valid utf8 byte b0 in state 0at orgeclipsejettyutilutf8appendableappendbyteutf8appendablejava174at orgeclipsejettyutilutf8appendableappendutf8appendablejava99at orgeclipsejettyutilurlencodeddecodestringurlencodedjava709at orgeclipsejettyutilurlencodeddecodetourlencodedjava251at orgeclipsejettyutilurlencodeddecodetourlencodedjava187at orgeclipsejettyserverrequestmergequerystringrequestjava2045at orgeclipsejettyserverthispatcherforwardthispatcherjava244at orgeclipsejettyserverthispatcherforwardthispatcherjava103at orgtuckeywebfiltersurlrewritenormalrewrittenurldorewritenormalrewrittenurljava213at orgtuckeywebfiltersurlrewriterulechainhandlerewriterulechainjava171at orgtuckeywebfiltersurlrewriterulechaindorulesrulechainjava145at orgtuckeywebfiltersurlrewriteurlrewriterprocessrequesturlrewriterjava92at orgtuckeywebfiltersurlrewriteurlrewritefilterdofilterurlrewritefilterjava381at orgeclipsejettyservletservlethandlercachedchaindofilterservlethandlerjava1307at orgeclipsejettyservletservlethandlerdohandleservlethandlerjava453at orgeclipsejettyserverhandlerscopedhandlerhandlescopedhandlerjava137at orgeclipsejettysecuritysecurityhandlerhandlesecurityhandlerjava559at orgeclipsejettyserversessionsessionhandlerdohandlesessionhandlerjava231at orgeclipsejettyserverhandlercontexthandlerdohandlecontexthandlerjava1072at orgeclipsejettyservletservlethandlerdoscopeservlethandlerjava382at orgeclipsejettyserversessionsessionhandlerdoscopesessionhandlerjava193at orgeclipsejettyserverhandlercontexthandlerdoscopecontexthandlerjava1006at orgeclipsejettyserverhandlerscopedhandlerhandlescopedhandlerjava135at orgeclipsejettyserverhandlercontexthandlercollectionhandlecontexthandlercollectionjava255at orgeclipsejettyserverhandlerhandlercollectionhandlehandlercollectionjava154at orgeclipsejettyserverhandlerhandlerwrapperhandlehandlerwrapperjava116at orgeclipsejettyserverserverhandleserverjava365at orgeclipsejettyserverabstracthttpconnectionhandlerequestabstracthttpconnectionjava485at orgeclipsejettyserverabstracthttpconnectionheadercompleteabstracthttpconnectionjava926at orgeclipsejettyserverabstracthttpconnectionrequesthandlerheadercompleteabstracthttpconnectionjava988at orgeclipsejettyhttphttpparserparsenexthttpparserjava635at orgeclipsejettyhttphttpparserparseavailablehttpparserjava235at orgeclipsejettyserverasynchttpconnectionhandleasynchttpconnectionjava82at orgeclipsejettyionioselectchannelendpointhandleselectchannelendpointjava627at orgeclipsejettyionioselectchannelendpoint1runselectchannelendpointjava51at orgeclipsejettyutilthreadqueuedthreadpoolrunjobqueuedthreadpooljava608at orgeclipsejettyutilthreadqueuedthreadpool3runqueuedthreadpooljava543at javalangthreadrunthreadjava722editit has been suggested that maybe this could be handled in my tuckey configuration so thsi is what it currently looks likexml version10 encodingutf8doctype urlrewrite public tuckeyorgdtd urlrewrite 31en configuration file for urlrewritefilter urlrewrite usequerystringtrue rule note matches urls like httplocalhost8080ws1artistqueryblurampfmtxml and converts to httplocalhost8080typeartistampqueryblurampfmtxmlampversion1 note fromwsdfrom toversion1amptype2amp3to rule rule note the rule means that requests to teststatus will be redirected to rewritestatus the url will be rewritten note fromteststatusfrom to typeredirectcontextpathrewritestatusto rule outboundrule note the outboundrule specifies that when responseencodeurl is called if you are using jstl curl the url rewritestatus will be rewritten to teststatus the above rule and this outboundrule means that end users should never see the url rewritestatus only teststatus both in their location bar and in hyperlinks in your pages note fromrewritestatusfrom toteststatusto outboundruleurlrewrite,['java'] +418391,why are uncompiled repeatedly used regexes so much slower in python 3 when answering this question and having read this answer to a similar question i thought that i knew how python caches regexesbut then i thought i would test it comparing two scenariosa single compilation of a simple regex then 10 applications of that compiled regex10 applications of an uncompiled regex where i would have expected slightly worse performance because the regex would have to be compiled once then cached and then looked up in the cache 9 timeshowever the results were staggering in python 33 import timeit timeittimeitsetupimport re stmtrrecompilerwnfor i in range10n rsearch jkdhf 18547793477671938 timeittimeitsetupimport re stmtfor i in range10n researchrw jkdhf 10647892003890324that is over 57 times slower in python 27 there is still an increase by a factor of 25 which is also more than i would have expectedhas caching of regexes changed between python 2 and 3 the docs do not seem to suggest that,['python'] +418392,ios application missing from notification center problemthe app does not appear on notification center and it is unable to receive push notifications right after installation completes and the app registers for push notifications via registerforremotenotificationtypesdetailsthe app usually appears in notification center after the device is restarted and after that everything works just finesometimes the app shows up in notification center right after intallation and registration for apnsi still cannot confirm this but i think i stumbled upon such situationsthe app calls the method registerforremotenotificationtypes each time a user logins and each time a user logouts respectively with bit masks uiremotenotificationtypealert uiremotenotificationtypebadge uiremotenotificationtypesound and uiremotenotificationtypenoneenabledremotenotificationtypes returns correct valuesinitially i used the method unregisterforremotenotifications on logout but i changed it to registerforremotenotificationtypesuiremotenotificationtypenone due to suspicians that this could be causing the problem this problem occurs in both development and adhoc builds and irrespectively of whether the app is installed via xcode or itunesany thoughts and advices will be greatly appreciated thank you,"['iphone', 'ios']" +418404,setting finished tabbar images when using storyboards i am working on an application where the bulk of the ui is setup via a storyboard in xcode one thing that i want to do is specify finished images for the uitabbaritems on a tabbar rather than the default stencilled images that you can access via interface buildermy question is where is the best place to do this i am currently doing it in awakefromnib as it needs to be done when things are unarchived from the storyboard but i as unsure if i should be using initwithcoder instead which is best does it matter idinitwithcodernscoder adecoder self super initwithcoderadecoder ifself uiimage tabin uiimage imagenamedtab in uiimage tabout uiimage imagenamedtab out uitabbaritem tabbaritem self tabbaritem tabbaritem setfinishedselectedimagetabout withfinishedunselectedimagetabin tabbaritem settitletwo return selfor voidawakefromnib super awakefromnib uiimage tabin uiimage imagenamedtab in uiimage tabout uiimage imagenamedtab out uitabbaritem tabbaritem self tabbaritem tabbaritem setfinishedselectedimagetabout withfinishedunselectedimagetabin tabbaritem settitletwoi understand that initwithcoder is called at the start of unarchiving objects from nibs contained in the storyboard when outlets and actions are not yet hooked up i also understand that awakefromnib is called at the end of the unarchiving process and signals that the viewcontroller is now ready for use my feeling is that it really just depends on what you want to do although using awakefromnib might prove less problematic as your not going to hit issues where outlets and actions are not yet hooked upeditlet me rephrase this what situations would you use initwithcoder as apposed to awakefromnib and vice versa,"['iphone', 'objective-c']" +418454,writing xfce panel plugins in python i have googled around a bit but cannot find much this seems rather out of date and does not provide any examples is this possible should i just shut up and learn c already,['python'] +418471,when and when not to use block in objectivec when using blocks why do you need block for some variables and for other variables such as function parameters you do not,"['ios', 'objective-c']" +418488,at what point does scalability become an issue for a rails application deployed on heroku ruby on rails has largely been faulted for it is lack of scalability options and the alternative is generally to migrate to some form of a java webapp or something similar but all of the concerns seem to be very arbitrary at best in a wayare there any concrete numbers for when a certain application needs to be rewritten in a different language heroku provides various scaling options with the numbers of dynos available to the app but at what point will diminishing returns if any be evident or at what point will the cost of having so many dynos outweigh the costs of simply writing a new apphow many active concurrent users can i expect to be able to support without suffering performance issues on the basic free hosting plan at heroku,['ruby-on-rails'] +418507,reading a dynamic property map into spring managed bean i have a properties file like thismyproperties fileapponeid1apponeval60apptwoid5apptwoval75and i read these values into a map property in my bean in spring config file like thisspringconfigxmlbean idmybean classmyclass scopesingleton property namemymap map entry keyapponeid valueapponeval entry keyapptwoid valueapptwoval map propertybeanthis way if i add a new idval to the properties file i must add a row in config xml in order to have the new idval in mymapmy question is is there a way to specify the keyval pairs in spring config file so that the number of keyvals defined in xml can figure out the items in the properties file and create a map basically i want to use this xml file in different environments where we use different number of keyvalue items in properties file i just do not want to change the xml file in each environment to read in all these valueslet me know if you need any other details any thoughtscomments is appreciated thanks,['java'] +418516,baselayerandroid creating destroying log messages i am using a web view within an activity when i run my app on phone i am able to see lot of continous log messages with tag baselayerandroid0207 132906458 dbaselayerandroid27721 creating baselayerandroid 0x1a328b80207 132906505 dbaselayerandroid27721 destroying baselayerandroid 0x19771300207 132906560 dbaselayerandroid27721 creating baselayerandroid 0x197fa880207 132906599 dbaselayerandroid27721 destroying baselayerandroid 0x1a328b80207 132906653 dbaselayerandroid27721 creating baselayerandroid 0x199fbd00207 132906685 dbaselayerandroid27721 destroying baselayerandroid 0x197fa880207 132906755 dbaselayerandroid27721 creating baselayerandroid 0x1ba80180207 132906786 dbaselayerandroid27721 destroying baselayerandroid 0x199fbd00207 132906856 dbaselayerandroid27721 creating baselayerandroid 0x19c48d00207 132906903 dbaselayerandroid27721 destroying baselayerandroid 0x1ba80180207 132906966 dbaselayerandroid27721 creating baselayerandroid 0x1a20a900207 132907021 dbaselayerandroid27721 destroying baselayerandroid 0x19c48d00207 132907067 dbaselayerandroid27721 creating baselayerandroid 0x198e4800207 132907099 dbaselayerandroid27721 destroying baselayerandroid 0x1a20a900207 132907169 dbaselayerandroid27721 creating baselayerandroid 0x19771400207 132907216 dbaselayerandroid27721 destroying baselayerandroid 0x198e480my basic code isprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutthisplay progress progressbar findviewbyidridprogressbar1 webview webview findviewbyidridwebview1 websettings webviewgetsettings websettingssetbuiltinzoomcontrolstrue websettingssetjavascriptenabledtrue webviewsetwebviewclientnew webviewclient override public void onpagestartedwebview view string url bitmap favicon todo autogenerated method stub superonpagestartedview url favicon progresetactivatedtrue progresetvisibilityprogressbarvisible override public void onpagefinishedwebview view string url todo autogenerated method stub superonpagefinishedview url progresetactivatedfalse progresetvisibilityprogressbarinvisible new threadnew runnable public void run webviewloadurlsome url starteven when i come out of my activity showing webview i keep recieving this log messagescan anyone help me analyse what these log messages are all about and why are they appearing at such a fast rate,['android'] +418566,how does the stringsplit method determine separator precedence when passed multiple multicharacter separators if you have this codesplitnew string stringsplitoptionsnonethe resulting array elements are 1 2 3 now if you reverse the order of the separatorssplitnew string stringsplitoptionsnonethe resulting array elements are 1 2 3 4 from these 2 examples i feel inclined to conclude that the split method recursively tokenizes as it goes through each element of the array from left to righthowever once we throw in separators that contain alphanumeric characters into the equation it is clear that the above theory is wrong 5x7splitnew stringx x stringsplitoptionsnoneresults in 1 5 2 7 5x7splitnew stringx x stringsplitoptionsnoneresults in 1 5 2 7this time we obtain the same output which means that the rule theorized based on the first set of examples no longer applies ie if separator precedence was always determined based on the position of the separator within the array then in the last example we would have obtained 5 7 instead of 5 7as to why i am wasting my time trying to guess how net standard apis work it is because i want to implement similar functionality for my java apps but neither stringtokenizer nor orgapachecommonslangstringutils provide the ability to split a string using multiple multicharacter separators and even if i were to find an api that does provide this ability it would be hard to know if it always tokenizes using the same algorithm used by the stringsplit method,['c#'] +418569,how to alias the global namespace in c11 short form how can i define an alias for the root global namespace in c11 it might look likenamespace root namespace where the scope resolution operator in its naked form above is a place holder for some handle of the global namespace i read in the gcc internals manual thatthe root of the compilers entire intermediate representation is the variable global namespace this is the namespace specified with in c source code the name of the global namespace is even though in c the global namespace is unnamedps edit to respondents todate i appended a painfuly long form to address some concerns after the following long form since it may clarify some things and followers if you see us talking at rather than to each other dig inlong form an example of its potential use follows if unsatisfactory then yes this is an academic question see the painfully long form that follows this oneimagine that your boss barges in one day and says i just read a book about postpositivism get rid of namespace objectivereality in the code below all you have to do is omit the lines i have marked like this you can do that for intermediate levels of nesting currently however i am uncertain how to define the globalscope namespace current authority to allow simple elision of the first nonglobal namespaceinclude iostreaminclude iomanip using cat is alive stdtrue type because i like catsusing cat is alive cat is alive seems to work see g v below aside i originally had namespace higher authority compiler as a comment but changed it for simpler chaining closure the next two lines are the crux of my questionnamespace higher authority global namespace namespace current authority global namespace aka the naked if the above two lines defined aliases for the unnamed global namespace then the suggested elisionsreplacements work namespace objectivereality simplest fix replace with using objectivereality current authority otherwise a few other changes are necessary namespace higher authority current authority namespace current authority objectivereality using cat is alive higher authoritycat is alive namespace entangledobserver namespace higher authority current authority namespace current authority entangledobserver using cat is alive higher authoritycat is alive int main int argc char argv stdcout it is objectiverealityentangledobservercat is alivevalue that the cat is alive stdendl return 0 eofin case compiler info is needed g stdc11 vusing builtin specscollect gccgcollect lto wrapperusrlibgcci686linuxgnu47ltowrappertarget i686linuxgnuconfigured with srcconfigure v withpkgversionubuntulinaro 47211precise2 withbugurlfileusrsharedocgcc47readmebugs enablelanguagesccgofortranobjcobjc prefixusr programsuffix47 enableshared enablelinkerbuildid withsystemzlib libexecdirusrlib withoutincludedgettext enablethreadsposixwithgxxincludedirusrincludec47 libdirusrlibenablenls withsysroot enableclocalegnu enablelibstdcxxdebug enablelibstdcxxtimeyes enablegnuuniqueobject enablepluginenableobjcgc enabletargetsall thisablewerror witharch32i686withmultiliblistm32m64 withtunegeneric enablecheckingrelease buildi686linuxgnu hosti686linuxgnu targeti686linuxgnuthread model posixgcc version 472 ubuntulinaro 47211precise2 painfully long form as a response to some answers about start from a nested namespace note that home is inaccessible and that i may not have the luxury of handpicking namespaces in a team alicecppinclude iostreaminclude type traits the setup oneandahalf macros boo get rid of this casedefine enable subspace 1 namespace name namespace namespace name namespace last namespace namespace name namespace this namespace namespace name yeah instead define namespace this namespace and thendefine enable subspace namespace name namespace namespace name namespace last namespace this namespace namespace this namespace last namespacenamespace name some charactersstruct dorothy static constexpr auto obvious statement there is no place like struct rabbit template typename t static constexpr char const says t return tvalue i am late i am late but i ditched that addled girl struct alice using blue pill stdfalse type static constexpr auto where am i home the central structureenable subspace 1 oxford england using has strangers with candy stdtrue type struct alice using blue pill this namespacehas strangers with candy static constexpr auto where am i uncle charles picnic blanket enable subspace rabbit hole struct rabbit using is late typename aliceblue pill enable subspace rabbit hole struct rabbit using is late typename aliceblue pill enable subspace rabbit hole struct rabbit using is late typename aliceblue pill using has strangers with candy stdfalse type differentenable subspace rabbit hole struct rabbit using is late typename aliceblue pill enable subspace rabbit hole struct rabbit using is late typename aliceblue pill struct alice different using blue pill has strangers with candy static constexpr auto where am i needing a fix enable subspace rabbit hole struct rabbit using is late typename aliceblue pill struct alice last namespacealice different static constexpr auto where am i an empty rabbit hole end rabbit hole end rabbit hole end rabbit hole end rabbit hole end rabbit hole end rabbit hole end oxford england snarky outputint main int argc char argv stdcout stdendl dorothyobvious statement alicewhere am i stdendl there is no place like home stdcout dorothyobvious statement oxford englandrabbit holerabbit holerabbit holerabbit holerabbit holealicewhere am i stdendl there is no place like needing a fix stdcout dorothyobvious statement oxford englandrabbit holerabbit holerabbit holerabbit holerabbit holerabbit holealicewhere am i stdendl there is no place like an empty rabbit hole stdcout stdendl rabbitsays oxford england rabbit hole rabbit hole rabbit hole rabbit hole rabbit holerabbitis late stdendl i am late stdcout rabbitsays oxford england rabbit hole rabbit hole rabbit hole rabbit hole rabbit hole note aliceblue pill is false type rabbit holerabbitis late not this time alice is crashing stdendl i am late but i ditched that addled girl stdcout stdendl dorothyobvious statement oxford england rabbit hole 1 rabbit hole 2 rabbit hole 3 rabbit hole 4 rabbit hole 5 rabbit hole rabbit hole 6 last namespace rabbit hole 5 last namespace rabbit hole 4 last namespace rabbit hole 3 last namespace rabbit hole 2 last namespace rabbit hole 1 last namespacealicewhere am i oxford england stdendl there is no place like uncle charles picnic blanket stdcout dorothyobvious statement oxford england rabbit hole rabbit hole rabbit hole rabbit hole rabbit hole rabbit hole last namespace last namespace last namespace 3 last namespace 2 last namespace 1 last namespace oxford last namespacealicewhere am i not the global namespace but i would rather be alicewhere am i the global namespace stdendl there is no place like uncle charles picnic blanket but i would rather be home stdcout stdendl return 0 eof compiled with g stdc11 o alice alicecpp output of alice there is no place like homethere is no place like needing a fixthere is no place like an empty rabbit holei am latei am late but i ditched that addled girlthere is no place like uncle charles picnic blanketthere is no place like uncle charles picnic blanket but i would rather be home,['c++'] +418654,one form with two submit buttons and different actions for each button i have spent several hours trying to find a solution to my issue but just cannot seem to find the proper solution thanks in advance for your assistancei have one html form withform idcolumnarform actionformindb hoh 1php enctypemultipartformdata methodpost i would like to have two submit buttonsinput typeimage namecamper valuecamper srcimagesappscamperbtnpng clasubmit button input typeimage namemedical valuemedical srcimagesappsmedicalbtnpngclasubmit button i would like the first submit button to have the action of formindb hoh 1php when clicked and the second submit button to have the action of formindb hoh 2php but am unsure how to make one button have one action and have the other button has a different action,['php'] +418672,nsindexpathitem vs nsindexpathrow does anyone know the difference between nsindexpathrow and nsindexpathitem specifically which one do i use inuitableviewcell tableviewuitableview tableview cellforrowatindexpathnsindexpath indexpath,['ios'] +418681,could not find class x referenced from method x i am working on a libgdx project and i have a class called cheervarachnids that has another inline class which is an event listener when i run this project on the desktop it works fine but when i run on my android device it cannot find that inline class and i get the following errorcould not find class combbjcvacheervarachnidsplaceunitlistener referenced from method combbjcvacheervarachnidsinithere are the important parts of my classpackage combbjcvapublic class cheervarachnids implements applicationlistener class placeunitlistener implements eventsubscriberplaceunitevent override public void oneventplaceunitevent event public cheervarachnids eventbussubscribeplaceuniteventclass new placeunitlistener eventbussubscriberemovescreenobjecteventclass new removescreenobjectlistener any ideas why on android at runtime it cannot find that inline class,['android'] +418710,how to redirect page on button click event i am using a button on my form how do i link to another web pagefile when clicking on that link here is the code i tried but does not workbutton classbtn databindclick function documentlocationhrefthisattrriskassessmentmainaspx backbutton,['javascript'] +418712,pointerpressed not working on left click creating metro microsoft ui app for windows 8 on wpfc i met difficulty with pointerpressed event on a button event does not happen when i perform leftclick by mouse but it happens in case with rightclick or tap so whats wrong with that eventfor example button xnamesomebutton width100 height100pointerpressedsomebutton pointerpressed,['c#'] +418731,php using pdo with in clause array i am using pdo to execute a statement with an in clause that uses an array for it is valuesin array array1 2 3in values implode in arraymy result wbdbprepareselect from my table where my value in in valuesmy resultexecutemy results my resultfetchallthe above code works perfectly fine but my question is why this does not in array array1 2 3 in values implode in array my result wbdbprepareselect from my table where my value in in values my resultexecutearrayin values in values my results my resultfetchallthis code will return the item whos my value equals the first item in the in array 1 but not the remaining items in the array 2 and 3,['php'] +418747,simple bubble sort c int arr 8001150771649770240 9int temp 0for int write 0 write arrlength write for int sort 0 sort arrlength 1 sort if arrsort arrsort 1 temp arrsort 1 arrsort 1 arrsort arrsort temp consolewrite0 arrwrite all i am attempting to do is a simple bubble sort with this array i would like to figure out why the sorting is screwed upin example here is when the array is 8001150771649770240 9here is what gets thisplayed 11 50 649 9 649 770 771 800 i am thinking that i might be missing something in the comparison,['c#'] +418751,malloc for struct and pointer in c suppose i want to define a structure representing length of the vector and its values asstruct vector double x int nnow suppose i want to define a vector y and allocate memory for itstruct vector y struct vectormallocsizeofstruct vectormy search over the internet show that i should allocate the memory for x separatelyyx doublemalloc10sizeofdoublebut it seems that i am allocating the memory for yx twice one while allocating memory for y and the other while allocating memory for yx and it seems a waste of memoryit is very much appreciated if let me know what compiler really do and what would be the right way to initialize both y and yxthanks in advance,['c'] +418767,reasons to use backbonejs router for routing instead of using serverside code when and why would i use backbonejs router for routing instead of routing via serverside code could someone elaborate on that since it is my first time exposed to do routing on clientside,['javascript'] +418773,how to make a custom grid with images in android i want to make a custom grid with images that we usually see for gallery in android phonesi have been searching it for couple of hours but no luck favours and finally i am making an attempt to ask question here can someone please suggest me how to achieve this kind of gridview or do i need to follow any other approach,['android'] +418781,synchronise scrolling of two divs i have a 3 column layout with a header left sidebar content area and right sidebarthe left sidebar gets the position fixed when it reaches the top of the viewport so it is always in view and has an overflow so anything inside it can be seen by scrollingit always has a preventdefault function to stop the main content area and right sidebar scrolling when it is moused over so the 3 areas of the page appear thistinctly their own elementsthe page is fluid width for the most part so the center content area could be either longer or shorter than the right sidebar depending on the content contained withinhere is some code and a jsfiddle to help you visualisewhat i would like to do is have the right sidebar scroll faster or slower than the center div depending on their relative height so the right sidebar never thisappears up the top of the viewportthe effect can be seen here i am guessing some sort of jquery could handle thishtml head titlelayout testtitle script srcscript script srcscript script function var toolbox left height toolboxheight scrollheight toolboxget0scrollheight toolboxbindmousewheel functione d ifthisscrolltop scrollheight height d 0 thisscrolltop 0 d 0 epreventdefault function document ready if stickyoffset make sure sticky element exists var stickytop stickyoffsettop returns number windowscrollfunction scroll event var windowtop windowscrolltop returns number if stickytop windowtop stickycss position fixed top 0 else stickycsspositionstatic script style typetextcss html height 100 body margin 0 padding 0 height 100 header height 150px backgroundcolor aqua maincontent position relative marginleft 240px left width 220px height 100 paddingleft 10px paddingright 10px backgroundcolor red position absolute top150px webkittransitionduration 2s moztransitionduration 2s otransitionduration 2s transitionduration 2s overflow auto float left leftinner position relative height auto paddingbottom 200px backgroundcolor green webkittransitionduration 2s moztransitionduration 2s otransitionduration 2s transitionduration 2s center backgroundcolor blue height auto minheight 100 marginright 300px float left sidebar width 300px heightauto position absolute right0 backgroundcolor green float left overflow auto clearfix clear both media screen and maxwidth1150px style head body div classheaderdiv div classleft sticky div classleftinner lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum the end div div div classmaincontent div classcenter lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborumlorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborumlorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborumlorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborumlorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborumlorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum div div clasidebar lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborumthe end div div classclearfixdiv div end div maincontent div classfooterdiv bodyhtml,"['javascript', 'jquery']" +418791,what naming convention should i use in service stack service model we are thinking about using servicestack in our next project and while looking at examples i have noticed that there is no common naming conventionfor exampleentity movie request movie response movieresponse the same goes for all operationsnow this exampleentity answer request answers response answerresultyet anotherentity user request getusers response getusersresponseit is kind of weird to see class names staring with verbso may be you have come up with some clever naming convention and would like to sharealso are there any larger open source projects on service stack where i could look how they organize their service model,['c#'] +418814,android alertdialog styling i have an alert dialog in the app as shown below i want the title and the line which separates the title message body to be in orange colour how can i do thiswhat i tried is using custom style as shown below but this did not workstyle nameaboutdialog parentandroidstylethemedialog item nameandroidtextcolore5492aitemstylemy alert dialog codealertdialogbuilder alertdialog new alertdialogbuilder new contextthemewrappermainactivitycontext rstyleaboutdialogalertdialogsettitlesample alertdialogsetmessagerstringrate dialog text alertdialogsetpositivebuttonrstringrate now text new dialoginterfaceonclicklistener public void onclickdialoginterface dialog int which mainactivitycontextstartactivitynew intent intentaction view uri parsemarketdetailsid mainactivityapp pname if editor null editorputbooleandontshowagain true editorcommit dialogthismiss alertdialogsetneutralbuttonrstringremind later text new dialoginterfaceonclicklistener public void onclickdialoginterface dialog int which dialogthismiss alertdialogsetnegativebuttonrstringno thanks text new dialoginterfaceonclicklistener public void onclickdialoginterface dialog int which if editor null editorputbooleandontshowagain true editorcommit dialogthismiss return alertdialogcreate,['android'] +418828,how to thisplay a popover programmatically from a uibutton that is also created programmatically not using interface builder i have a button i have created programmatically within a view controller once the button is pressed i want it to to use a method to create the popover programmaticallythe button which is created in the viewdidload in my view controllerm uiview morefundinfoview uiview alloc initwithframecgrectmake0 0 540 620selfview addsubviewmorefundinfoviewmorefundinfoview setbackgroundcoloruicolor rmbcolorbbtncontact uibutton buttonwithtypeuibuttontyperoundedrectbtncontact setframecgrectmake390 575 contactbuttonwidth contactbuttonheight btncontacthidden nobtncontact settitlecontact forstateuicontrolstatenormalmorefundinfoview addsubviewbtncontactbtncontact addtargetself actionselectorshowcontactdetails forcontroleventsuicontroleventtouchupinsidethen i have the method i use when the button is pressedvoid showcontactdetails id senderuiviewcontroller popovercontent uiviewcontroller allocinituiview popoverview uiview allocinitwithframecgrectmake0 0 200 300popoverview setbackgroundcoloruicolor rmbcolorbpopovercontentview popoverviewpopovercontentcontentsizeforviewinpopover cgsizemake200 300uipopovercontroller contactpopover uipopovercontroller alloc initwithcontentviewcontrollerpopovercontentcontactpopover presentpopoverfromrectbtncontactframe inviewselfview permittedarrowdirectionsuipopoverarrowdirectionup animatedyes contactpopover setdelegateselfwhat am i missing here cause it runs fine but as soon as i click the button the app crashes i think it is a delegate issue but i am not sure any advice would be appreciated,['ios'] +418847,python jsonloads does not work i have been trying to figure out how to load json objects in python def do postself length intselfheaderscontentlength decdata strselfrfilereadlength print decdata typedecdata name journal2 type str postdata jsonloadsdecdata print postdata typepostdata name journal2 type unicode postdata jsonloadspostdata print postdata typepostdata error expecting property name enclosed in double quoteswhere am i going wrongerror code jscriptvar data namejournal2var http request new xmlhttprequesthttp requestopen post url true http requestsetrequestheadercontenttype applicationjsonhttp requestsenddatatrue code jscriptvar data namejournal2var http request new xmlhttprequesthttp requestopen post url true http requestsetrequestheadercontenttype applicationjsonhttp requestsendjsonstringifydatatrue code python def do postself length intselfheaderscontentlength decdata selfrfilereadlength postdata jsonloadsdecdata postdata jsonloadspostdata,['python'] +418940,mysql before update trigger change value so i have got a mysql table named employeesid name meta0 jack ok1 anne deli want to write a trigger which prevents a row where metadel to update the meta fieldso if i doupdate employees set meta busy where id 0the row should be updated and meta would be busybut when i doupdate employees set meta busy where id 1the meta field should still be deli trieddelimiter create trigger updateemployeesbefore update on employeesfor each row begin if oldmeta del then newmeta del end ifenddelimiter but mysql returns with an syntax error any ideas,"['mysql', 'sql']" +418951,implicitly casting a float constant please have a look at this code include stdiohint mainvoid short s int i 65696 float f 656960f printfsizeofshort lun sizeofshort s i printfs hdn s s f printfs hdn s s 65696 printfs hdn s s 656960f printfs hdn s return 0 it gave output as sizeofshort 2s 160s 160s 160s 32767in last line why it is 32767 and not 160 whats the difference between saying f 656960f s f and s 656960f,['c'] +418958,how to find the version numbers of built in modules in php from the cli basically i am new to php and i just installed php on my machineso we can know entire information of the php configuration by creating a php file andwriting the below code in it php phpinfoand i opened this through browser and can able to see all the configuration informationbut is there any way to know the version of php default modules from linux terminali am using fedora by the way so what all i mean to ask is whether is there any way to find the version number of all the modules or individual modules from terminal through some php commands for example there is a command php me which thisplays all the php modules that comes by default when php is installed like belowphp modulesmysqlmysqliopensslpcntlpcrepdopdo mysqlpdo sqlitepharreadlinereflectionsessionshmopbut in the same way i want to find the version number of the individual module too from the terminal how can we find it,['php'] +418974,matplotlib axis label format i am having an issue with the format of the tick labels of an axis i thisabled the offset from the y axisax1ticklabel formatstyle sci useoffsetfalseand tried to put it a scientific format but all i get is0355872but i expected something like355872e2or similarwhat i really want is something like355872 on the tick labelx 102 or something similar on the axis labeli could try to set the labels as static but in the end i will have a few tens or hundreds of plots with different values so it needs to be set dynamicallyan alternative would be to place the y axis offset as the label but i also have no clue on how to do this,['python'] +419065,gzip compression to a byte array i am trying to write a class that can compress data the below code fails no exception is thrown but the target gz file is emptybesides i do not want to generate the gz file directly like it is done in all examples i only want to get the compresseddata so that i can eg encrypt it before writting the data to a fileif i write directly to a file everything works fineimport javaioimport javautilzipimport javaniocharsetpublic class zipper public static void mainstring args byte datatocompress this is the test data getbytesstandardcharsetsiso 8859 1 gzipoutputstream zipstream null fileoutputstream filestream null try filestream new fileoutputstreamcusersusernamedesktopzip filegz zipstream new gzipoutputstreamfilestream zipstreamwritedatatocompress filestreamwritecompresseddata catchexception e eprintstacktrace finally try zipstreamclose catchexception e try filestreamclose catchexception e but if i want to bypass it to the byte array stream it does not produce a single byte compresseddata is always emptyimport javaioimport javautilzipimport javaniocharsetpublic class zipper public static void mainstring args byte datatocompress this is the test data getbytesstandardcharsetsiso 8859 1 byte compresseddata null gzipoutputstream zipstream null bytearrayoutputstream bytestream null fileoutputstream filestream null try bytestream new bytearrayoutputstreamdatatocompresslength zipstream new gzipoutputstreambytestream zipstreamwritedatatocompress compresseddata bytestreamtobytearray filestream new fileoutputstreamcusersusernamedesktopzip filegz filestreamwritecompresseddata catchexception e eprintstacktrace finally try zipstreamclose catchexception e try bytestreamclose catchexception e try filestreamclose catchexception e,"['java', 'android']" +419072,scrapy crawl from script always blocks script execution after scraping i am following this guide to run scrapy from my scripthere is part of my script crawler crawlersettingssettings crawlerconfigure spider crawlerspiderscreatespider name crawlercrawlspider crawlerstart logstart reactorrun print it cannot be printed outit works at it should visits pages scrape needed info and stores output json where i told itvia feed uri but when spider finishing his worki can see it by number in output json execution of my script wouldnt resume probably it is not scrapy problem and answer should somewhere in twisteds reactorhow could i release thread execution,['python'] +419094,antlr 4 channel hidden and options i need help with my antlr 4 grammar after deciding to switch to v4 from v3 i am not very experienced with antlr so i am really sorry if my question is dumb in v3 i used the following code to detect javastyle commentscomment nr r n channelhidden options greedyfalse channelhidden in v4 there are no rulespecific options the actions move to hidden channel are also invalidcould somebody please give me a hint how to do it in antlr v4,['java'] +419113,in a singlepage app what is the right way to deal with wrong urls 404 errors i am currently writing a web application using angularjs but i think this question applies to any clientside javascript framework that does routing on the client side as angular doesin a singlepage app what is the right way to deal with wrong urls looking at a few major sites i see that gmail will redirect to the inbox if you type any random url below this happens serverside with an http 300 code or clientside depending on whether the wrong path is before or after the character on the other hand twitter shows a real http 404 for any invalid url a third option would be to show a soft 404 a purely clientside error page these solutions seem appropriate for different situations twitter wants the links to twitter users and tweets to be real links so people can share them post them in news articles etc so it is important that invalid links be recognized as such if i have a broken link to a tweet in my website a simple crawl will tell me that in gmail on the other hand you are not expected to share links into your inbox and i am not even sure if the links are really permanentpersistent it seems the url updating mostly serves the purpose of browser history navigation within the singlepage app the third approach of giving soft errors might be appropriate for situations similar to gmail but where there is no reasonable default page after this long introduction here are some specific questionsis it ever acceptable to give a soft error page instead of a 404 error or should a singlepage app always redirect to a real 404 if a url is invalidgmails code may be perfectly bugfree but if it did have a bug leading to invalid links that end up redirecting back to the inbox that might be even more confusing for users than an error page for most web apps out there that are not as well tested as gmail would it be better to show an error pageto implement real 404s for singlepage apps it seems necessary to duplicate the routing logic on the serverside is there any way around thiswhen redirecting to a 404 i think the user should be able to see the url that caused the error possibly in the url bar with the html5 history api i think this can be accomplished by simply triggering a reload of the current page with the wrong url combined with the serverside routing mentioned above for browsers that do not support this or when using hashbang notation this does not seem possible whats the best way to support all browsers,['javascript'] +419154,convert relative path to absolute using javascript there is a function which gives me urls likesomecssextrasomecsslibsliderslidercssit is always a relative pathlet us think we know current path of the page like not sure how do i convert these relative paths to real oneswe should get something likesomecss extrasomecss libsliderslidercss no jquery only vanilla javascript,"['javascript', 'html']" +419176,post checkbox value i want to post values of check boxes on bookingphp pagethere are many checkboxes on the page but i dont know how to post on bookingphp page form namebookingphp methodpost label fortour classtourlabeladd to tour listlabel input typecheckbox namebookingcheck valuedesert safari form div classdetailsa hrefbookingphpbook selected toursadiv,['php'] +419185,restkit crashes because nsmanagedobjectcontext is nil in the rkresponsemapperoperation i am working on my diploma project which includes an ios client with a core data database and a ruby on rails server i am using restkit for the communication between them currently i am having a big issue getting the whole system to work as i try to map a response to objects from the server i get the following exception20130208 224043947 app667355903 assertion failure in rkmanagedobjectresponsemapperoperation performmappingwithobjecterror repositoriesapprestkitcodenetworkrkresponsemapperoperationm35820130208 230430562 app667355903 terminating app due to uncaught exception nsinternalinconsistencyexception reason unable to perform mapping no managedobjectcontext assigned mapping responseurl httplocalhost30contactsauth tokens78ufmq8mcqrr12gzcyx first throw call stack0x1de9012 0x1c0ee7e 0x1de8e78 0x16a4f35 0x8f56e 0x8d520 0x1647d23 0x1647a34 0x16d4301 0x23a253f 0x23b4014 0x23a52e8 0x23a5450 0x90ac6e12 0x90aaeccalibcabidylib terminate called throwing an exceptioni am trying to load a list an array of contacts from the server which should be saved as users in core data i have structured all my core data code in a data model class like i saw in this video here it isheader fileimport foundationfoundationhimport coredatacoredatahinterface appdatamodel nsobject idshareddatamodelproperty nonatomic readonly nsmanagedobjectcontext maincontextproperty nonatomic strong nsmanagedobjectmodel managedobjectmodelproperty nonatomic readonly nspersistentstorecoordinator persistentstorecoordinator nsstring modelname nsstring pathtomodel nsstring storefilename nsstring pathtolocalstoreendimplementation fileimport appdatamodelhinterface appdatamodel nsstring documentsdirectoryendimplementation appdatamodelsynthesize managedobjectmodel managedobjectmodelsynthesize persistentstorecoordinator persistentstorecoordinatorsynthesize maincontext maincontext idshareddatamodel static appdatamodel instance nil if instance nil instance appdatamodel alloc init return instance nsstring modelname return appmodels nsstring pathtomodel return nsbundle mainbundle pathforresourceself modelname oftypemomd nsstring storefilename return self modelname stringbyappendingpathextensionsqlite nsstring pathtolocalstore return self documentsdirectory stringbyappendingpathcomponentself storefilename nsstring documentsdirectory nsstring documentsdirectory nil nsarray paths nssearchpathfordirectoriesindomainsnsdocumentdirectory nsuserdomainmask yes documentsdirectory paths objectatindex0 return documentsdirectory nsmanagedobjectcontext maincontext if maincontext nil maincontext nsmanagedobjectcontext alloc initwithconcurrencytypensprivatequeueconcurrencytype maincontextpersistentstorecoordinator self persistentstorecoordinator return maincontext nsmanagedobjectmodel managedobjectmodel if managedobjectmodel nil nsurl storeurl nsurl fileurlwithpathself pathtomodel managedobjectmodel nsmanagedobjectmodel alloc initwithcontentsofurlstoreurl return managedobjectmodel nspersistentstorecoordinator persistentstorecoordinator if persistentstorecoordinator nil nslogsqlite store path self pathtolocalstore nsurl storeurl nsurl fileurlwithpathself pathtolocalstore nspersistentstorecoordinator psc nspersistentstorecoordinator alloc initwithmanagedobjectmodelself managedobjectmodel nsdictionary options nsdictionary dictionarywithobjectsandkeys nsnumber numberwithboolyes nsmigratepersistentstoresautomaticallyoption nsnumber numberwithboolyes nsinfermappingmodelautomaticallyoption nil nserror e nil if psc addpersistentstorewithtypenssqlitestoretype configurationnil urlstoreurl optionsoptions errore nsdictionary userinfo nsdictionary dictionarywithobjecte forkeynsunderlyingerrorkey nsstring reason could not create persistent store nsexception exc nsexception exceptionwithnamensinternalinconsistencyexception reasonreason userinfouserinfo throw exc persistentstorecoordinator psc return persistentstorecoordinatorendthe user class is pretty straightforward autogenerated with xcodeheader fileimport foundationfoundationhimport coredatacoredatahinterface user nsmanagedobjectproperty nonatomic retain nsstring emailproperty nonatomic retain nsstring firstnameproperty nonatomic retain nsstring lastnameproperty nonatomic retain nsnumber useridendimplementation fileimport userhimplementation userdynamic emaildynamic firstnamedynamic lastnamedynamic useridendjust like the data model class i have a server manager class which i use for communicationheader fileimport foundationfoundationhimport restkitrestkithimport appserverprotocolhimport appdatamodelhinterface appserver nsobject appserverdelegate idsharedinstanceproperty strong nonatomic rkobjectmanager objectmanagerproperty strong nonatomic rkentitymapping usermappingendand implementation fileimport appserverhimport userhimport devicehimport pinghimport appappdelegatehinterface appserver property bool initializedendimplementation appserver idsharedinstance static appserver instance nil if instance nil instance appserver alloc init instanceinitialized no if instance initialized instance initserver return instance voidinitserver initialize restkit nsurl baseurl nsurl urlwithstringhttplocalhost30 objectmanager rkobjectmanager managerwithbaseurlbaseurl enable activity indicator spinner afnetworkactivityindicatormanager sharedmanagerenabled yes initialize managed object store objectmanagermanagedobjectstore rkmanagedobjectstore alloc initwithmanagedobjectmodelappdatamodel shareddatamodel managedobjectmodel usermapping rkentitymapping mappingforentityfornameuser inmanagedobjectstore objectmanagermanagedobjectstore usermapping addattributemappingsfromdictionary email email firstname first name lastname last name usermapping setidentificationattributes userid rkresponsedescriptor contactsresponsedescriptor rkresponsedescriptor responsedescriptorwithmapping usermapping pathpatterncontacts keypathnil statuscodesnil objectmanager addresponsedescriptorcontactsresponsedescriptor initialized yes contacts voidgetcontactsforcurrentuser nsstring authtoken nsuserdefaults standarduserdefaults objectforkeyappauthenticationtoken objectmanager getobjectsatpathcontacts parametersauth token authtoken successrkobjectrequestoperation operation rkmappingresult mappingresult rkloginfoload collection of contacts mappingresultarray failurerkobjectrequestoperation operation nserror error rklogerroroperation failed with error error endso when i open the contacts table view which is set up correctly to use a fetched results controller successfully pulling entities out of the db i have a dangerous refresh button which calls the method youve just read above voiddownloadcontacts appserver sharedinstance getcontactsforcurrentuserhere is the format of the response created at201301t140357z email first namejohn id2 last namedoe updated at20130207t105716z created at201301t140357z email first namejane id3 last namedoe updated at20130207t105716zand before the exception the console states the following20130208 224036892 app66735c07 i restkitrklogm34 restkit logging initialized20130208 224036994 app66735c07 sqlite store path libraryapplication supportiphone simulator60applicationsd735548fdf424e13a7ef53df0c5d8f3bdocumentsappmodelssqlite20130208 224037001 app66735c07 context is ready20130208 224043920 app66735c07 i restkitnetworkrkhttprequestoperationm154 get httplocalhost30contactsauth tokens78ufmq8mcqrr12gzcyx20130208 224043945 app66735c07 i restkitnetworkrkhttprequestoperationm181the line of the restkit library that fails before the whole exception is thrown isnsassertselfmanagedobjectcontext unable to perform mapping no managedobjectcontext assigned mapping responseurl selfresponseurli have followed that back to the initserver method in the appserverm file in which before the method returns the properties of the rkobjectmanager class are like this as i have debugged i have traced that the problem is not with the server side or the communication of the app i can see the json received and deserialized into an array but the moment it is passed to the next method which is supposed to save it to core data the whole app goes kaboom because of the nsassert of the managed object contextany help is greatly appreciated,"['ios', 'ruby-on-rails']" +419231,dynamic libraries plugin frameworks and function pointer casting in c i am trying to create a very open plugin framework in c and it seems to me that i have come up with a way to do so but a nagging thought keeps telling me that there is something very very wrong with what i am doing and it either would not work or it will cause problemsthe design i have for my framework consists of a kernel that calls each plugins init function the init function then turns around and uses the kernels registerplugin and registerfunction to get a unique id and then register each function the plugin wants to be accessible using that id respectivelythe function registerplugin returns the unique id the function registerfunction takes that id the function name and a generic function pointer like sobool registerfunctionint plugin id string function name plugin function funcwhere plugin function istypedef void plugin functionthe kernel then takes the function pointer and puts it in a map with the function name and plugin id all plugins registering their function must caste the function to type plugin functionin order to retrieve the function a different plugin calls the kernelsplugin function getfunctionstring plugin name string function namethen that plugin must cast the plugin function to its original type so it can be used it knows in theory what the correct type is by having access to a h file outlining all the functions the plugin makes available plugins by the by are implemented as dynamic librariesis this a smart way to accomplish the task of allowing different plugins to connect with each other or is this a crazy and really terrible programming technique if it s please point me in the direction of the correct way to accomplish thisedit if any clarification is needed ask and it will be provided,['c++'] +419243,sql pivot and string concatenation aggregate i would like to use a pivot sql query to construct a result table where the concatenate text as a result within the data section of the pivot tableie i have the following result from using a simple select event name resource type resource name event 1 resource type 1 resource 1 event 1 resource type 1 resource 2 event 1 resource type 2 resource 3 event 1 resource type 2 resource 4 event 1 resource type 3 resource 5 event 1 resource type 3 resource 6 event 1 resource type 3 resource 7 event 1 resource type 4 resource 8 event 2 resource type 5 resource 1 event 2 resource type 2 resource 3 event 2 resource type 3 resource 11 event 2 resource type 3 resource 12 event 2 resource type 3 resource 13 event 2 resource type 4 resource 14 event 2 resource type 5 resource 9 event 2 resource type 5 resource 16 and i would like to construct a result query that would look like this eventresource type resource type 1 resource type 2 resource type 3 resource type 4 resource type 5 event 1 resource 1 resource 2 resource 3 resource 4 resource 5 resource 6 resource 7 resource 8 null event 2 null resource 3 resource 11 resource 12 resource 13 resource 14 resource 1 resource 9 resource 16 i know how to use a pivot statement in mssql but i do not know how to aggregate the resource name into a concatenation of comma separated items for each resource typepsi could also use a solution using the martix provided by ssrs 2008r2 using report builde 3 with the first table as my data set and create a matrix that will aggregate the resource names into a comma separated string,['sql'] +419245,observablecollection loses binding when i new it i have a listbox on my ui that is bound to a property of observablecollection i set a new instance of the observablecollection into the property in the view models constructor and i can add items to it with a button on the form these are visible in the listall is goodhowever if i reinitialize the property with new in the button callback it breaks the binding and the ui no longer shows what is in the collectioni assumed the binding would continue to look up the values of the property but its presumably linked to a reference which is destroyed by the newhave i got this right can anyone expand on how this is linked up is there a way to rebind it when my view model has no knowledge of the view,['c#'] +419267,monkeyrunner does not touch webview i need to test android app which includes webview with buttonsmonkeyrunner works fine for all parts of the app except webviewbutton in webview just ignores touches from monkeyrunneri see that button is clicked because it became grey but then button does nothingif i use mouse on emulator or finger on real device then button works greati see from logcat that touch event was sent to the app but there is no action from the appsome codefinal webview w webview findviewbyidridwebview1string summary htmlbodybgooglebform actioninput typesubmitinput typetextformbodyhtmlwloaddatasummary texthtml nulayout button androidididbutton1 androidtextclick me webview androidididwebview1 monkeyrunner pyfrom comandroidmonkeyrunner import monkeyrunner monkeydevicedevice monkeyrunnerwaitforconnection10 androidwidgetbutton coordinates this works finedevicetouch10100 down and up webview button coordinates button does not workdevicetouch200200 down and upi had tried separately down delay up the same resultmonkeyrunner from python or from inside java do not work tooflavors and wrappers for monkeyrunner like chimpchat do not worki think it should work because there are so many webhtml5 apps and it could not be true that all of them are not tested but it appears oppositeany ideas or suggestions how to enforce touch event for webview components,['android'] +419276,converting decimal to binary java i am trying to convert decimal to binary numbers from the users input using java i am getting errorspackage reversedbinaryimport javautilscannerpublic class reversedbinary public static void mainstring args int number scanner in new scannersystemin systemoutprintlnenter a positive integer numberinnextint if number 0 systemoutprintlnerror not a positive integer else systemoutprintconvert to binary is systemoutprintbinaryformnumberprivate static object binaryformint number int remainder if number 1 systemoutprintnumber remainder number 2 binaryformnumber 1 systemoutprintremainder return null how do i convert decimal to binary in java,['java'] +419341,bundle update fails marshal data too short bundle updatefetching gem metadata from a fatal error has occurred please see the bundler troubleshooting documentation at thanks usersmacbookrvmgemsruby193p374globalgemsbundler123libbundlerfetcherrb168in load marshal data too short argumenterrorfrom usersmacbookrvmgemsruby193p374globalgemsbundler123libbundlerfetcherrb168in fetch dependency remote specsfrom usersmacbookrvmgemsruby193p374globalgemsbundler123libbundlerfetcherrb125in fetch remote specsfrom usersmacbookrvmgemsruby193p374globalgemsbundler123libbundlerfetcherrb128in fetch remote specsfrom usersmacbookrvmgemsruby193p374globalgemsbundler123libbundlerfetcherrb73in specsfrom usersmacbookrvmgemsruby193p374globalgemsbundler123libbundlersourcerb234in block in remote specsfrom usersmacbookrvmgemsruby193p374globalgemsbundler123libbundlersourcerb232in eachfrom usersmacbookrvmgemsruby193p374globalgemsbundler123libbundlersourcerb232in remote specsfrom usersmacbookrvmgemsruby193p374globalgemsbundler123libbundlersourcerb165in fetch specsfrom usersmacbookrvmgemsruby193p374globalgemsbundler123libbundlersourcerb70in specsfrom usersmacbookrvmgemsruby193p374globalgemsbundler123libbundlerdefinitionrb191in block 2 levels in indexfrom usersmacbookrvmgemsruby193p374globalgemsbundler123libbundlerdefinitionrb188in eachfrom usersmacbookrvmgemsruby193p374globalgemsbundler123libbundlerdefinitionrb188in block in indexfrom usersmacbookrvmgemsruby193p374globalgemsbundler123libbundlerindexrb9in buildfrom usersmacbookrvmgemsruby193p374globalgemsbundler123libbundlerdefinitionrb184in indexfrom usersmacbookrvmgemsruby193p374globalgemsbundler123libbundlerdefinitionrb178in resolvefrom usersmacbookrvmgemsruby193p374globalgemsbundler123libbundlerdefinitionrb113in specsfrom usersmacbookrvmgemsruby193p374globalgemsbundler123libbundlerdefinitionrb108in resolve remotelyfrom usersmacbookrvmgemsruby193p374globalgemsbundler123libbundlerinstallerrb81in runfrom usersmacbookrvmgemsruby193p374globalgemsbundler123libbundlerinstallerrb14in installfrom usersmacbookrvmgemsruby193p374globalgemsbundler123libbundlerclirb291in updatefrom usersmacbookrvmgemsruby193p374globalgemsbundler123libbundlervendorthortaskrb27in runfrom usersmacbookrvmgemsruby193p374globalgemsbundler123libbundlervendorthorinvocationrb120in invoke taskfrom usersmacbookrvmgemsruby193p374globalgemsbundler123libbundlervendorthorrb275in thispatchfrom usersmacbookrvmgemsruby193p374globalgemsbundler123libbundlervendorthorbaserb408in startfrom usersmacbookrvmgemsruby193p374globalgemsbundler123binbundle14in block in top requiredfrom usersmacbookrvmgemsruby193p374globalgemsbundler123libbundlerfriendly errorsrb4in with friendly errorsfrom usersmacbookrvmgemsruby193p374globalgemsbundler123binbundle14in top requiredfrom usersmacbookrvmgemsruby193p374globalbinbundle19in loadfrom usersmacbookrvmgemsruby193p374globalbinbundle19in mainfrom usersmacbookrvmgemsruby193p374globalbinruby noexec wrapper14in evalfrom usersmacbookrvmgemsruby193p374globalbinruby noexec wrapper14in main,['ruby-on-rails'] +419351,convolution of two three dimensional arrays with padding on one side too slow in my current project i need to convolve two three dimensional arrays in a slightly unusual wayassume we have two three dimensional arrays a and b with the dimensions dima and dimb same for every axis now we want to create a third array c with the dimensions dimadimb for every axisthe entries of c are computed asc x1x2y1y2z1z2 a x1y1z1 b x2y2z2my current version is straightforwarddima ashape0dimb bshape0dimc dimadimbc npzerosdimcdimcdimcfor x1 in rangedima for x2 in rangedimb for y1 in rangedima for y2 in rangedimb for z1 in rangedima for z2 in rangedimb x x1x2 y y1y2 z z1z2 cxyz ax1y1z1 bx2y2z2 unfortunately this version is really slow and not usable my second version wasc scipysignalfftconvolveabmodefullbut this computes only the elements maxdimadimbhas anyone a better idea,['python'] +419375,object reference not set to an instance of an objectwhy does not net show which object is null regarding this net unhandled exception messageobject reference not set to an instance of an objectwhy does not net show which object is nulli know that i can check for null and resolve the error however why does not net help pointing out which object has a nullreference and which expression triggered the nullreferenceexception,"['c#', '.net']" +419391,do final fields really prevent mutability in java from the famous book java concurrency in practice chapter 341 final fieldsjust as it is a good practice to make all fields private unless they need greater visibilityej item 12 it is a good practice to make all fields final unless they need to be mutablemy understanding of final references in java a final reference field just prevents the the field from getting re initialized but if it references a mutable object we can still change its state rendering it mutable so i am having difficulty understanding the above quote what do you think,['java'] +419399,base64 image upload vs binary image upload i want my mobile application to be able to upload an image to my server in my case it is a rails 3211 with nginxi read alot about base64 encoding on client side and then decoding on the server sidewhy not just use binary upload with multipart headers on the http requestare the any pros cons for each technic,"['android', 'ruby-on-rails']" +419407,package name without mainjava in maven i develop my project in eclipse with standard maven directory layout sources are in srcmainjavacommycompany directory and it is required to put my source classes in package mainjavacommycompanywhen i build executable jarfile i have to define main class in manifestmf like mainclass mainjavacommycompanymymainclassbut i saw in lot of examples like configuring mainclass attribute in mavenassemblyplugin or maven jarplugin that class names are specified without mainjava part i just want to have mainclass commycompanymymainclassi cannot figure out how i can achive this because i am completely novice in maven,['java'] +419444,ios how to enable audio directions on google maps i am using the below code to open google maps from my ios application where i am passing starting and end point of placesit navigates correctly from start point to end point but does not guide through audio voicei want to enable voice guidance facility please helpclientstate clientstate clientstate sharedinstance cllocation currentlocation clientstatecurrentlocation nsstring googlemapsurlstring nsstring stringwithformatmapsmapsgooglecomxyzxyzsaddr18f18fdaddr currentlocationcoordinatelatitude currentlocationcoordinatelongitude trippickuplatitude trippickuplongitudeuiapplication sharedapplication openurlnsurl urlwithstringgooglemapsurlstring,"['iphone', 'ios', 'objective-c']" +419454,compile c to allow for buffer overflow i am learning about buffer overflows and am trying to make one i have this codeinclude stdiohchar secret passwordvoid go shell char shell binsh char cmd binsh 0 setreuid0 execveshellcmd0int authorize char password64 printfenter password getspassword if strcmppasswordsecret return 1 else return 0 int main if authorize printflogin successfuln go shell else printfincorrect passwordn return 0i compile this with gcc and then run it in gdbi enter about 100 as as the password and the program crashes the problem is no register is overwritten to 0x4141414141414141i googled this and added the fnostackprotector flag to gcc which allowed rbp to be overwritten to 0x4141414141414141 but nothing elsei was wondering if there was a way to compile the code so that rip can be overwritten,['c'] +419496,stop all instances of nodejs server this is my first time working with nodejs and i ran into this problemi have started a node server through the plugin of an ide unfortunately i cannot use the ides terminal so i tried to run the script from the command linethis is the problem i am using the express module and my app is listening some port 8080 when i start the app from the command line it throws this erroreventsjs71 throw arguments1 unhandled error event error listen eaddrinuse at errnoexception netjs77011 at httpserverserver listen2 netjs91014 at listen netjs93710 at httpserverserverlisten netjs9865 at objectanonymous cxampphtdocsnodechatappjs55 at module compile modulejs44926 at objectmodule extensionsjs modulejs46710 at moduleload modulejs35632 at functionmodule load modulejs31212 at modulerunmain modulejs49210even though i am not very sure what this error could be i assumed that it is because the app is listening on a port which is already in use so i didnetstat ani can see tcp 08080 0 listeningit is because the node server is already started when i tried to start it from the ideso i want to know how can i stop all server instances also if you can tell me how to detect whats running on a port and kill it,['javascript'] +419500,how can i check if key exists in list of dicts in python say i have a list of dicts that looks like this1 a 2 bwhat is the pythonic way to indicate if a certain key is in one of the dicts in the list,['python'] +419529,null byte injection in an upload form i am trying to reproduce the null byte injection attack on an upload form i have this codephpifsubstr filesfilename 3 php ifmove uploaded file filesfiletmp name filesfilename echo bfile uploadedb else echo bcan not uploadbelse echo bthis is not a valid filebi am trying to upload a file named like this filephp00jpg so it will bypass the substr and will be uploaded as filephp since move uploaded file should stop at the null byte 00the problem is that the uploaded file is not named filephp on the server but filephp00jpg which can be accessed by typing filephp2500jpg in the url barit seems that move uploaded file does not care about the null byte so how does this works is it possible to upload a file with php extension with my piece of codethanks,['php'] +419533,android bluetoothsocketisconnected always returns false i am trying to detect whether a bluetooth device is currently connected to an android device using api 14 or better it seems like i should be able to use the bluetoothsocketisconnected method but no matter what i have done so far i just get false back for anything connected or notandroidmanifest includes these linesusespermission androidnameandroidpermissionbluetooth usespermission androidnameandroidpermissionbluetooth admin locale 4x supports api 14 or greater usessdk androidminsdkversion14 androidtargetsdkversion17 usesfeature androidnameandroidhardwarebluetooth and the code in questionprotected void oncreatefinal bundle savedinstancestate superoncreatesavedinstancestate setbluetoothdevice paireddevices mbluetoothadaptergetbondeddevices for bluetoothdevice device paireddevices logiconstantslog tag stringformatlocaleus device s connected b devicegetname isconnecteddevice nonnls1z private boolean isconnectedbluetoothdevice device bluetoothsocket socket null get a bluetoothsocket for a connection with the given bluetoothdevice uuid spp uuid uuidfromstring0110101080805f9b34fb try socket devicecreaterfcommsockettoservicerecordspp uuid catch ioexception e logeconstantslog tag egetmessage nonnls1z return false logiconstantslog tag sockettostring nonnls1z return socketisconnectedno errors are thrown it simply returns false 100 of the time is there something that i am not doing right,['android'] +419598,detect if button click real user or triggered by a script is there any method that enables me to detect whether a button click was performed by a real user and not some automated method javascript that a user has loaded onto their browser developer console or other browser developer tooli tried the following methods suggested in various stackoverflow posts but none of them appear to work ref how to detect if a click is a mouse click or triggered by some codescript detection methods tried and failedmybuttonclickfunction e if ewhich triggered by code not actually clicked alert ewhich not a real button click else if istrusted in e eistrsuted triggered by code not actually clicked alert eistrusted not a real button click else if eoriginalevent undefined triggered by code not actually clicked alert eoriginalevent not a realbutton click else if efocus triggered does not detect efocus on a real btn click alert efocus not a realbutton click else button hopefully clicked by a real user and not a script if i run the following script to trigger the button click from the chrome browser console none of the methods above traps it as being triggered by a scriptvar button documentgetelementbyidbtnsubmitbuttonclickthank you for all your responses and thanks to stackoverflow for providing such a great site that facilitates so much knowledge sharing and for saving us techies an untold number of hoursit appears that i still do not have reliable method all 3 browsers ff ie chrome provide a developerconsole interfaces for a user to runinject a javascript on my webpage it appears that each browser flavor traps some event property values a little differently for example chrome traps the difference between a script activated cick and a real user with escreenx but in ie escreenx has the same value for both a script click synthetic and a user button clickthe following detection methods either did not work at all or are inconsistent across the different browsers ewhich eistrsuted eoriginalevent eventsource window ethistance nullthe mousedown event appears to be only triggered by a real user button click but i have to assume there is some script method to emulate a mousedown in addition to a button click eventmecontainer mybuttonmousedownfunction e alertmouseisdown real button click if anyone can figure out a reliable method that works across multiple browsers that detects the difference between a synthetic script button click and a button click by a user you will deserve superhero status,['javascript'] +419606,improve speed of splitting file i am using this code to extract a chunk from file info is fileinfo object pointing to filevar percentsplit infolength 50 100 extract 50 of filevar bytes new bytepercentsplitvar filestream fileopenreadfilenamefilestreamreadbytes 0 byteslengthfilestreamthisposefilewriteallbytessplitname bytesis there any way to speed up this process currently for a 530 mb file it takes around 4 5 seconds can this time be improved,['c#'] +419620,javah command for native methods gives exception i entered this into command prompt and i am not sure why it is saying that it is not a valid class name considering that it has the position on the thisk and the fully qualified class name java version works and i am running the latest version of the jvm with the jdk also the classpath is configured properlythe class is this package jnipublic class main public native void printtitlepublic static void mainstring args main main new main mainprintpublic void print systemoutprintlnthe print subroutine has finishedand the command line args arecusersuserdocumentsnetbeansprojectsjni test projectbuildclassesjnijavah jni classpath cusersuserdocumentsnetbeansprojectsjni test projectbuildclassesjni jnimainclassexception in thread main javalangillegalargumentexception not a valid class name jnimainclass at comsuntoolsjavacapijavactoolgettaskjavactooljava177 at comsuntoolsjavacapijavactoolgettaskjavactooljava68 at comsuntoolsjavahjavahtaskrunjavahtaskjava509 at comsuntoolsjavahjavahtaskrunjavahtaskjava335 at comsuntoolsjavahmainmainmainjava46,['java'] +419678,google spreadsheet query join equivalent function this question is concerning joining two databases in google spreadsheet using query functioni have a table like so in range a1c3a d gb e hc f ii have another tablec j ma k nb l oi want the final table to look like thisa d g k nb e h l o c f i j mi can do this by using a vlookup function pretty easily in cell d1 and paste it down and across but my dataset is huge i would need a whole page of vlookups and google spreadsheet tells i am at my limit in complexitiesi look at the googles query language reference there does not seem to be an type of join functions mentioned you would think it would be an easy join on a type operationcan anybody solves this without a vlookup,['sql'] +419701,fastest way to update a mysql table if row exists else insert more than 2 nonunique keys i have the following table structure create table if not exists reports id int11 not null auto increment day int11 not null uid int11 not null siteid int11 not null cid int3 not null visits int11 not null primary key id currently i check insertupdate with the following snippet checkq mysql queryselect count as rowexist from reports where dayday and uiduid and siteidsid and cidcid or diemysql error checkr mysql fetch arraycheckqif checkrrowexist 0 mysql queryupdate reports adv set visitsvisits1 where dayday and uiduid and siteidsid and cidcid else mysql queryinsert into reports adv set dayday uiduid siteidsid cidcid visits1is a fastest way to update this mysql table if row exists else insert with more than 2 nonunique keys,"['php', 'mysql', 'sql']" +419709,why are my structs members not properly initialised using i had the following codeinclude iostreamstruct t int a b cint main t t 0 stdcout ta tb tc noutput0after many years of this code running happily in a critical production environment serving a vital function the requirements of the project changed and i needed the output to be 1so i changed 0 to 1include iostreamstruct t int a b cint main t t 1 stdcout ta tb tc noutput100i expected 1 insteadwhy are my structs members not all being initialised properly,['c++'] +419712,python custom iterator close a file on stopiteration i have written an iterator class that opens a file in it is init def init self path selffile openpath rhow do i close that file automatically when the iteration is finishedcomplete classclass parseobject a generator that iterates through a cedict formatted file returning a tuple of parsed results traditional simplified pinyin english def init self path selffile openpath r def iter self return self def is commentself line return linestartswith def nextself this block ignores comments line selffilereadline while line and self is commentline line selffilereadline if line working linerstripsplit trad simp working0 working1 working joinworking2split pinyin working01 english working11 return trad simp pinyin english else raise stopiteration,['python'] +419721,how can i search subfolders using globglob module in python i want to open a series of subfolders in a folder and find some text files and print some lines of the text files i am using thisconfigfiles globglobcuserssamdesktopfile1txtbut this cannot access the subfolders as well does anyone know how i can use the same command to access subfolders as well,['python'] +419731,ios autoshrink uilabel with attributed text i have uilabel which contains two attributed strings separated by a new linefirst string has font size set to 17 and the second one to 14i want my first nsmutableattributedstring be resized to minimum font size if its content cannot fit in a single lineis that possibleit is pretty simple to configure such uilabel behaviour by setting auto shrink to minimum font size in ib for plain text but do not know how to do it for attributed texthere is my codensstring eventname long event namensstring placestring my placeeventname eventname stringbyappendingstringn nsmutableattributedstring attrname nsmutableattributedstring alloc initwithstringeventnameattrname addattributensfontattributename valueuifont boldsystemfontofsize17 rangensmakerange0 eventname length nsmutableattributedstring attrplace nsmutableattributedstring alloc initwithstringplacestring attrplace addattributensfontattributename valueuifont systemfontofsize14 rangensmakerange0 placestringlength attrplace addattributensforegroundcolorattributename valueuicolor graycolor rangensmakerange0 placestringlength nsmutableattributedstring finalstring nsmutableattributedstring alloc initwithattributedstringattrname finalstring appendattributedstringattrplace uilabel namelabel uilabel cell viewwithtag100 namelabelattributedtext finalstring,"['iphone', 'ios']" +419737,creating a random number using mysql i would like to know is there a way to select randomly generated number between 100 and 500 along with a select query eg select name address random number from usersi dont have to store this number in db and only to use it to thisplay purpose i tried it something like this but it cannot get to workselect name address floorrand 500 as random number from usershope someone help me outthank you,"['mysql', 'sql']" +419786,how to access parent class member from nested class in java simple question for java programmer i am not sure if it possible directly please present workaroundsi want to access parent variable to initialize nested class member but not know the java syntax to do it if it possible how to set child id with parent idpublic class parent final string id parent class child it is invalid since scope hide parent id final string id id the best solution with i found is very ugly see herepublic class parent final string id parent ugly clone string shadow id class child final string id shadow please help with syntax i do not know how to express it,['java'] +419789,parser error when deploy aspnet application i have finished simple aspnet web application project compiled it and try to test on local iis i have create virtual directory map it with physical directory then put all necessary files there including bin folder with all dllsin the project settings build section output path is binso when i try to browse my app i gotserver error in applicationparser error description an error occurred during the parsing of a resource required to service this request please review the following specific parse error details and modify your source file appropriately parser error message could not load type ameriatesttaskdefaultsource error line 1 page languagec autoeventwireuptrue codebehinddefaultaspxcs inheritsameriatesttaskdefault line 2 line 3 register assemblyajaxcontroltoolkit namespaceajaxcontroltoolkit tagprefixajaxtoolkit source file virtualdefaultaspx line 1 have read similar problem posts and solution was to set output path to bin but it is defalut for my project,['asp.net'] +419806,jquery checkbox toggle with button not working after few times can anyone explain why the code fragment does not work after pressing toggle 3 timesthe attribute checked is still set to checked but the browser does not check the checkbox anymoredocumentreadyfunction btnclickfunction ifchkischecked chkremoveattrchecked else chkattrcheckedchecked lbldebugtextchkclonewraparenthtml see i have tested it both on opera and chrome with the same problem in bothwhat am i missing here,"['javascript', 'jquery', 'html']" +419827,how do i make drawstring text bold i have a drawstring method in my paintcomponent method is there a way to make the text drawn by the drawstring bold also is there a way to make the text bigger i would like to avoid using jlabels unless it is absolutely necessary,['java'] +419858,array unique sort regular flag array array1 1a 1var exportarray uniquearray sort regularthe result array 0 1 2 1in the php manual sort regular compare items normally do not change typeswhat is the logic behind this why or how is 1a excluded,['php'] +419874,error when install pylibmc using pip hello when i attempt to install pylibmc on osx lion using pip i get the following error pylibmcmoduleh4210 fatal error libmemcachedmemcachedh file not foundinclude libmemcachedmemcachedh 1 error generatederror command clang failed with exit status 1any clues at how to solve this issue,['python'] +419964,thisable some characters from input field i have found some instructions similar but none helps all of them are either for special chars or for digitsi need to make user type only 1 2 3 4 5 n o a b c all other characters should be restrictedany way i can make my own selection of restrictedallowed chars for inputs not very familiar with javascript,"['javascript', 'jquery', 'html']" +419966,how to yield from parallel tasks in net 45 i would like to use net iterator with parallel tasksawait something like thisienumerabletdst footsrc tdestienumerabletsrc source parallelforeach source s ordering is not important items can be yielded as soon as they are done yield return executeordownloadsomethings unfortunately net cannot natively handle this best answer so far by svick use asparallelbonus any simple asyncawait code that implements multiple publishers and a single subscriber the subscriber would yield and the pubs would process core libraries only,['c#'] +419970,forcing http response to return status 200 in rails how do you force your requests to return status 200 except for serious cases where i return 500 currently i am running into the issue where my client keeps getting a status code of 411 length not specified and this is causing issues with my test frameworkis there a way to manually specify your return status in maybe a rails controlleredit more specifically i know that you can use statusbut where do i place that when using formatjson render jsonfinal objto return a http response after a post,['ruby-on-rails'] +420083,javaxannotationnonnull vs assert i am using findbugs and javaxannotationnonnull on method parameterson private methods i usually add an assert line to check for nullness likeprivate void mymethodnonnull string str assert str null latest netbeans version 73rc2 is reporting that the assert check is not necessary because of the nonnull annotation i am not fully sure this is a netbeans bug or notcan the assert line be removed because i specified the nonnull annotation as far as i understand the annotation is used only during static analysis while assert is when enabled active during execution so the twos are not alternative,['java'] +420135,symfony 2 doctrine 2 get changes to persistentcollection i am building an application where the user can edit some data and then gets presented with a screen where he can confirm and comment on his editsin the confirmation form i thisplay the changes that have been made to the entity this works for normal fields here is some code that works for checking a single field create form bind formif formisvalid data formgetdata example get changes of a normal field if datacolor entitygetcolor do something with changes but i cannot do the same for a relation example manytomany with users if datausers entitygetusersdoes not work because datausers and entitygetusers refer to the same persistent collection it is possible to call this function to see if there are changes if datausersisdirtybut it is not possible to see what changes were madethe second problem with the above is that if all items are removed from the persistent collection doctrine does not mark it as changed isdirty true so i cannot catch the specific change where the user removes all users from the entity in the formplease note that the code all works the only problem i have is that i am unable to viewprocess the changes made on the confirmation step,['php'] +420144,how to implement dialog architecture in mvvm i am developing a wpf 40 mvvm application based on prism framework unity containeri was wondering what is the best way to implement dialogs in the mvvm patterni am planning to use quite a few in my application so i want something reusable,['c#'] +420155,is it possible to compare two cursors i need to check if two cursors pointing at the same rows with the same values is it possiblemore detailsi am loading data from my own contentprovideri am sending request to server and then updating my data inside contentprovider with new valuesif values is changed i need to notify user that he can update data,['android'] +420190,how to customise ekeventeditviewcontroller i am using default ekeventeditviewcontroller in my app and i want to customize it currently it shows all fields that came in default ekeventeditviewcontroller but i do not want to show url field and also want to add timezone field can i do that and if yes then pleas let me know how can i do this,"['iphone', 'ios']" +420194,how to access the stored credentials passwordvault on win7 and win8 i just thiscovered that win8 has a section on the control panel called user accounts and family safely with credential manager i would like to access the credentials stored in there not to retrieve the passwords but to use them as tokens for a login so basically i would like to get a piggyback ride on already installed softwarethe closest to a solution has been suggested in this thiscussion and it is not that closewhere do i find the assembly for windowssecuritycredentialspasswordvault i have been googling for two hours but i only get information on app development while i will be targeting desktopis there a way to resolve access to the prestored credentials for both win7 and win8 i fear a little bit that the vault facility has been drastically remodeled in win8 making it impossible to target both platforms at once,['c#'] +420199,jvectormap custom zoom buttons with jvectormap is it possible to hide zoom buttons and call zoom inout using their api i have checked the api documentation and could not find any methods causing the map rezoom,['jquery'] +420214,multiple lock objects necessary given the following classclass x object lockone new object object locktwo new object listsomething listone new listsomething listsomething listtwo new listsomething void methodone locklockone some operation on listone void methodtwo locklocktwo some operation on listtwo is it correct to use two locking objects assuming that methodone and methodtwo can be called from different threads concurrently noting that listone and listtwo are not related in anyway the only operations involved in the locks are those specified in the comments above,['c#'] +420215,jquery tabs panel covers tabs at 100 height i am trying to use the tabs widgets of jqueryui having panels content to extend to the whole available spaceheres a simplified version of what i have got so faryoull see that the green panel content of tab1 just covers the whole page instead of just the panel space when i use the following css tab1 background green position absolute top 0 bottom 0 left 0 right 0i could use top 27px to fix that but this would collide with two thingsif i change the tabs theme the height 27px could possibly changeif i have a lot of tabs i will have a second row below the first row so my panel content would then cover this second rowa clean short solution would be finejavascript is acceptable while a clean cssonly solution would be preferable regardsstefan,"['jquery', 'css']" +420305,how to dynamically create textboxes using aspnet and then save their values in database i am creating a survey site i want to add the textboxes dynamically and then get their values in the databasenow let us say i select 4 textboxes from the dropdown to be there dynamicallycode on the selection on dropdown protected void numdropdown selectedindexchangedobject sender eventargs e if dropdownlist1selectedvalue textbox int j i intparsenumdropdownselectedvalue sessioni i switch i case 1 t new textboxi sessiontextbox t for j 0 j i j tj new textbox tjid txtcheckbox jtostring panel1controlsaddtj break case 2 t new textboxi sessiontextbox t for j 0 j i j tj new textbox tjid txtcheckbox jtostring panel1controlsaddtj break case 3 t new textboxi sessiontextbox t for j 0 j i j tj new textbox tjid txtcheckbox jtostring panel1controlsaddtj break case 4 t new textboxi listtextbox mytextboxes for j 0 j i j tj new textbox tjid txtcheckbox jtostring panel1controlsaddtj try mytextboxes listtextboxsessionaddedtextbox mytextboxesaddtj sessionaddedtextbox mytextboxes catch mytextboxes new listtextbox mytextboxesaddtj sessionaddedtextbox mytextboxes break 2 then here i entered the values in the textbox like a bcd and click addcode for the click on the add click 1 first i checked the session to be there on page init protected void page initobject sender eventargs e if sessionaddedtextbox null string a string b string c string d int listcount listtextboxsessionaddedtextboxcount foreach textbox t in listtextboxsessionaddedtextbox if listcount 1 if listcount 2 if listcount 3 if listcount 4 if tid txtcheckbox0 a ttext if tid txtcheckbox0 b ttext if tid txtcheckbox0 c ttext if tid txtcheckbox0 d ttext but the problem here is that i do not get the text values they appear to be emptyplease help me to solve this issue,"['c#', 'asp.net']" +420311,how to query mongodb directly from ruby instead of using mongoid i am writing a migration for a rails application that uses mongodb and mongoid my migration currently uses my models that use mongoid to query and update records but the performance is subpar i am essentially updating all records in a large collection and making n20 queries i killed the migration after taking an hour to run locally and did not finish i would like to be able to run raw queries to mongo without too much effort i am assuming there is some way to access a mongo driver from mongoid since mongoid has already loaded a connection to the database how can i access the database to run my update queries direcly,['ruby-on-rails'] +420318,crash of garbage collection work queue if dylib is loaded we are porting an app from 106 to 108 i am looking at dylib we load in app i am facing very unusual crash in garbage collection work queue with following messagemalloc threadsuspend unable to suspend a thread err 268435459 thread 0x10 pthread 0x1081290 thread 0x8b07 stack base 0x1081290 enlivening on 0 local blocksfor application gcc enable objc gc required is set if i have gcc enable objc gc required in dylib it will still crash i cannot turn off garbage collector in application i have to manage it crash from my dylibreason for crash turns out to be that garbage collector is not able to suspend the thread as it says in log this thread is created using thread create if i put a indefinite while loop with sleep in constructor of dylib i dont get crash i get crash when constructor has finished its executionis their a way to tell garbage collector not to try and suspend the thread or to increase reference count of thread or anything i can do to stop garbage collector not to interfere with my dylib code,['objective-c'] +420324,using buttons in tkinter to navigate to different pages of the application i have quite a simple question here in tkinter python i was wondering who to use a button to go to different pages of my application eg a register page and a login page i am aware that gui does not have pages like websites do ive seen a few different ways but what is the best way to make links to different pagesthank you all very much,['python'] +420360,how to implement a two finger drag gesture on android i am new to android development and am working on an accessibility research project for blind people jelly bean api level 17 project i have been experimenting with some gestures and the twofingerdrag gesture has been really tough to implement the following image captures what i actually require quite well i want the blind user to drag two fingers across horizontally anywhere on the screen and he would obtain an audio output of the text heshe typed in the edittext also according to the thistance the two fingers travel while dragging we output each word separatelyexample below example if the user types today is a good day and drags his finger x value by say 10 units to left we output good day but if he drags it say 20 units to left we output a good day for 30 units to left is a good day etc etci stumbled across which seems to detect twofinger touchtoucheventmotionevent eventalso this tutorial on detecting multiple touches seems promising but i need it to work for touch and drag which i am not sure can be implemented like thisany new suggestions to implement this or pointers to tutorials that can help would be greatthanks in advanceadit,['android'] +420368,python connectionerror max retries exceeded i occasionally get this error when my server call it server a makes requests to a resource on another one of my servers all it server bconnectionerror httpconnectionpoolhostsome ip portsome port max retries exceeded with url some url caused by errno 1 connection refusedthe message in the exception ismessage none max retries exceeded with url some url caused by redirectwhich i include because it has that extra piece of information caused by redirectas i said i control both servers involved in this request so i can make changes to either andor both also the error appears to be intermittent in that it does not happen every timepotentially relevant information server a is a python server running apache and server b is a nodejs server i am not exactly a web server wizard so beyond that i am not exactly sure what information would be relevant but any requests for additional info in the comments will be honored asap does anyone know exactly what this error means or how to go about investigating a fix or does anyone know which server is likely to be the problem the one making the request or the one receiving itedit the error has begun happening with our calls to external web resources also,['python'] +420371,box shadow not showing on the top or bottom i am developing a site and i am running into an issue towards the bottom with the boxshadows on the three different sections i want the border to show up around all three but it only shows on the left and righthere is the html for that sectiondiv classthreecolsrowdiv classthreecolscol threecolsp styletextalign centerimg src alt pp styletextalign centerlorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et a hrefread moreapdivdiv classthreecolscol threecolsp styletextalign centerimg src alt pp styletextalign centerlorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et a hrefread moreapdivdiv classthreecolscol threecolsp styletextalign centerimg src alt pp styletextalign centerlorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et a hrefread moreapdivdivdiv classclearbothdivhere is the css for that sectionthreecolscol margin0 16px 0 16px overflowhidden floatleft thisplayinline threecolsrow margin0 auto width960px overflowhidden threecolsrow threecolsrow margin0 16px 0 16px widthauto thisplayinlineblock threecols width248px padding 15px background f mozboxshadow 0 0 3px d4d4d4webkitboxshadow 0 0 3px d4d4d4 boxshadow 0 0 3px d4d4d4,['css'] +420375,realtime sql syntax highlighting in html5 i want to use a textarea tag or an alternative written in javascript that highlights my sql statements as i write them effectively the same as phpmyadmins sql section where you can manually write queriesplease tell me that this is possible without using huge libraries and can be easily customizable if so which library should i be using and how,"['html', 'css']" +420405,what doen f mean in jquery scripts i see the function f being used in a number of jquery related scripts but i cannot find a description of what this means anywhereexamplevar iframe documentgetelementbyidiframe idthisplayer globalfiframecan anyone point me to documentation,"['javascript', 'jquery']" +420416,android jni rootcausing deadd00d dvmabort comments on a number of stackoverflow questions have pointed out that a fault address of deadd00d indicates a deliberate vm aborti debug signal 11 sigsegv code 1 segv maperr fault addr deadd00dand indeed when running the logs through ndkstack i see that the top of the stack frame decodes tostack frame 00 pc 050b0e systemliblibdvmso dvmabortthen the comments say to look earlier in your logs for the problem what exactly am i looking for is there a particular tag or string to search for dalvikvm perhaps i have scrolled through many pages of logs without finding anything relevant is that normal or should it be immediately before the faultthe deadd00d most frequently happens inside a particular call to getobjectclass i have tried calling envexceptioncheck immediately before that line but it does not report any prior errorsi have also tried turning on checkjni withadb shell setprop debugcheckjni 1per the instructions here and here but when killing and relaunching the app i do not see the expected messaged lateenabling checkjnibut ratherd androidruntime checkjni is offusing adb shell getprop indicates that the property really is on so i am not sure whats going on there,['android'] +420453,can i get data from the clipboard with the new zeroclipboard i am using this fresh version of zeroclipboard in a projectcreating buttons to copy content from html really works like a breeze compared to zclip or the old zeroclipboardhowever i would now like to create a button which gets the current value in the clipboard and inserts it into a input field ie click to pasteunfortunately i cannot find anything on that topic getting the data from the clipboard that is setting the value of the input am not the issue i am not even sure if there is another solution other than using zeroclipboardany help is greatly appreciated,['javascript'] +420457,sprite becomes blurred i am starting learning c and xna and i want to thisplay an animated sprite moved by my keyboardi have got this sprite fileto thisplay only the part i need i use this coderectangle cuttedsprite new rectangle thisw intthismcurspritex thish intthismcurspritey thisw thishspritebatchdrawthismspritetexture thismposition cuttedsprite colorwhitebut my problem is that the rendered image is blurred after movingi tried to fix this by changing the samplerstates but nothing changed does anyone have an idea to help me,['c#'] +420477,s3gti9300 camera preview holder bug we created a custom camera based on androidhardwarecamera classwhen we press the button take a photo the expected behavior is to take the photo and see the still captured photo on a review screen but the camera still works the viewfinder is showing a live shot instead of the still review when we get to the review screenit looks like the holder does not workthis has been observed on some samsung galaxy s3 phones gti9300 but strangely on all other models everything works fine the still image appears in the review screen as it should,['android'] +420501,convert python dataframe to list i have a python dataframe with multiple columns logblk page bayfail 0 0 0 1 8 9 1 16 0 1 4 5 6 8 9 12 13 14 2 32 0 1 4 5 6 8 9 12 13 14 3 48 0 1 4 5 6 8 9 12 13 14 i want to find bayfails that is associated with logblk0 and page0 df2 df dfpage 16 dflogblk 0 bayfailthis will return 0189what i want to do is to convert this pandasseries into a list does anyone know how to do that,['python'] +420504,using runwithspringjunit4classrunnerclass can you access the applicationcontext object i have a spring test that usesrunwithspringjunit4classrunnerclassunlike the older way of testing extending from the spring test base classes there appears to be no obvious way to access to the applicationcontext that has been loaded by spring using contextconfigurationhow can i access the applicationcontext object from my test methodsthanks,['java'] +420521,how to handle deployment of whitelabeled platform mobile apps i am working on a product that will be deployed to many different organizations ideal scenario dozens each deployment of the system composed of native apps for ios and android will involve the followingbranding specific to the organization ie a new skinintegration with the organizations authentication system and user databasesome custom features depending on the organizations needsin other words the core functionality will remain the same across all deployments but each instance will look different hook into a different authentication systems and have certain features enabledthisabledmy question what would be the best strategy for managing our 2 mobile codebases ios android in order to minimize duplication and simplify the deployment processthe three solutions were debating arecreate a core library that is shared across all instances as a subprojectlibrary project or a git submodule and add a thin layer on top with the branding and any configuration detailsmaintain a git branch with the core functionality and create a new branch for each deployment that contains the additional codedo something totally different that some smarter person on stackoverflow suggestswhich sounds best to you thanks in advance for any feedback,"['android', 'ios']" +420536,is it bad practice to use a using statement on a class level variable i have code similar to the followingclass mycontroller threadstatic private dbinterface db public void importalldata using db new dbinterface var records pulldata pushdatarecords private dbrecord pulldata return dbgetfromtablea private void pushdatadbrecord records dbinsertintotablebrecords the alternative is a lot more cumbersome to maintainclass mycontroller public void importalldata using var db new dbinterface var records pulldatadb pushdatarecords db private dbrecord pulldatadbinterface db return dbgetfromtablea private void pushdatadbrecord records dbinterface db dbinsertintotablebrecords as far as i can see my first implementationis thread safe assuming dbinterface is thread safeprevents any other process from touching the db variable andensures db will always be thisposed even during an exceptionis it bad practice to use the using statement on a variable with class scope have i missed something,['c#'] +420587,store an integer for bitwise compare in a permission model using jpa 2 i am using a permission model where i have a table user permissions this table will hold one or more columns with a certain bigint i will use the bits of each decimal number to compare with certain permission rules the bit location will be a permission rule and the value will be the condition of the rule active or not activethe problem with this approach is that i have limited number of bits to work when using a number such as bigintwhat is the best column type i can use in this case that works in a crossdatabase environmentthe tags represent the technologies i am aiming for so any other solution related to those technologies are appreciatedi was thinking to use lob annotation to store large data is that the best practiceupdatethe user permission table extends the user with a 11 relationship and have bigint fields like bin create bin read bin update bin delete that will hold the binary data as decimal numbersto clarify the questioni am considering comparing the permissions using bitwise operators so let us assume i have a user with the permission value 101010 and an action requiring 13 1101 so 10 13 8 10 the user have one permission matching the required permissions for the action so i could allow or deny it is up to the application rules define whichbut with this approach i have a limited number of bits to work on lets say i increase the permissions to be considered so the numbers will increase too the max bigint value is 9223372036854775807 and that gives me the binary 1 with 60 blocks and permission possibilities per fieldso what is the best column type i can use in this case that works in a crossdatabase environment to store a huge quantity of binary blocks and with the possibility to work with bitwise operators in java,['sql'] +420640,faster way of searching a string in text files i need to search for a string roughly 13 characters in a group of text files using c the number of text files is changing and can range between 10010 the size of the files can range between 1kb and 10mbi tried the naive way of opening each file read it line by line and see if the string exists using indexof but this is too slow i also tried using the boyermoore algorithm which did improve the timing by 5 seconds but still this feels slowany idea on how to speed up the search,['c#'] +420682,facebook sharer popup window the fb sharer popup window thisplays the data of the page not the metadata i have inserted in the php linka hrefp5btitle5dgooglep5burl5dhttp3a2f2fwgooglecomp5bsummary5dgoogle search enginep5bimages5d5b05donclickreturn fbs click626 305 target blank titlesharefacebookait seems the to be caused by the javascript script typetextjavascriptfunction fbs clickwidth height var leftposition toppositionleftposition windowscreenwidth 2 width 2 10topposition windowscreenheight 2 height 2 50var windowfeatures statusnoheight height width width resizablenoleft leftposition top topposition screenx leftposition screeny topposition toolbarnomenubarnoscrollbarsnolocationnodirectoriesnoulocationhreftdocumenttitlewindowopenencodeuricomponentutencodeuricomponenttsharer windowfeaturesreturn falsescripthow can i thisplay the correct data in the popup window,"['php', 'javascript']" +420708,how to continue in nested loops in python how can you continue the parent loop of say two nested loops in pythonfor a in b for c in d for e in f if somecondition continue the for a in b loopi know you can avoid this in the majority of cases but can it be done in python,['python'] +420776,interfragment communication applied to nested fragments the android developers site has a great article on how to use interfaces to communicate betweena fragment and its hosting activitytwo fragments hosted by the same activityi am struggling to apply this concept to nested fragments in particular getactivity or fragmentonattachactivity tell you what activity is hosting a fragmentwhat is the equivalent in case of nested fragments how does a child fragment know what parent fragment it is included in and without knowing this how can a child fragment pass events up to its parent fragment an obvious way is to broadcast intents from the child fragment and have the parent fragment listen for the broadcast but i would rather use the interfacebased approach,['android'] +420780,convert a list of tuples to a list of lists i have written this function to convert a list of tuples to a list of lists is there a more elegant pythonic way of doing thisdef get list of listslist of tuples list of lists for tuple in list of tuples list of listsappendlisttuple return list of lists,['python'] +420781,download excel file from page via webapi call i am trying to send a 9mb xls file as a response from web api controller method the user will click a button on the page and this will trigger the download via the browserheres what i have got so far but it does not work however it does not throw any exceptions eitheracceptverbsgetpublic httpresponsemessage exportxls try byte exceldata m toolsserviceexporttoexcelfile httpresponsemessage result new httpresponsemessagehttpstatuscodeok var stream new memorystreamexceldata resultcontent new streamcontentstream resultcontentheaderscontenttype new mediatypeheadervalueapplicationoctetstream resultcontentheaderscontentthisposition new contentthispositionheadervalueattachment filename dataxls return result catch exception ex m loggererrorexceptionexception exporting as excel file ex return requestcreateresponsehttpstatuscodeinternalservererror here is the coffeescriptjavascript jquery ajax call from a button click in the interfaceajax url route datatype json type get success successcallback error errorcallback now that i think about it perhaps the datatype is wrong and should not be json,"['c#', 'asp.net']" +420812,nsgenericexception reason unable to install constraint on view terminating app due to uncaught exception nsgenericexception reason unable to install constraint on view does the constraint reference something from outside the subtree of the view that is illegal constraint view layer contentoffset 0 0,"['iphone', 'objective-c']" +420851,wpf key is digit or number i have previewkeydown method in my window and i would like to know that pressed key is only az letter or 10 number without anyf112 enter ctrl alt etc just letter or numberi have tried charisletter but i need to give the char so ekeytostring0 does not work because it is almost everytime a letter,['c#'] +420852,security of unzipping user submitted files not so much of a coding problem here but a general question relating to securityi am currently working on a project that allows user submitted contenta key part of this content is the user uploads a zip filethe zip file should contain only mp3 filesi then unzip those files to a directory on the server so that we can stream the audio on the website for users to listen tomy concern is that this opens us up for some potentially damaging zip filesi have read about zipbombs in the past and obviously do not want a malicious zip file causing damageso is there a safe way of doing this can i scan the zip file without unzipping it first and if it contains anything other than mp3s delete it or flag a warning to the adminif it makes a difference i am developing the site on wordpressi currently use the built in upload features of wordpress to let the user upload the zip file to our server i am not sure if there is any form of security within wordpress already to scan the zip file,['php'] +420853,mysql query to dynamically convert rows to columns can mysql convert columns into rows dynamically adding as many columns as are needed for the rows i think my question might be related to pivot tables but i am unsure and i do not know how to frame this question other than by giving the following examplegiven a two tables a and b which look liketable aidorderdata1 1 p 2 2 q 2 1 r 1 2 s i like to write a query that looks like the followingresult tableiddata1data21 p s 2 r q basically i want to turn each row in table b into a column in the result table if there was a new entry was added to table b for id1 then i want the result table to automatically extend by one column to accommodate this extra data point,"['mysql', 'sql']" +420854,angularjs checkbox ngrepeat and selected objects i am trying to do it in proper way with less pain but i cannot figure out how to deal with ngmodel and binding it to the selected list etc and moreover i need to populate that list in later time and keep selected objects in itcategories name sport id 50d5ad name general id 678ffr span ngrepeatcategory in categories label classcheckbox forcategoryid input typecheckbox valuecategoryid ngmodel ngclick namegroup idcategoryid categoryname label spani have to override the categories each time the list is populated since it will be pulled out from a server so i guess i need to have arrays and the second one will hold the selected objects if i am right how do i preselect checkboxes do i need ngclick in order call custom function to store the selected object in the other array do i need ngmodel in checkbox and what for what is the properway with less pain,['javascript'] +420910,thread safety of mpi send using threads created with stdasync according to this website the usage of mpicomm worldsend is thread safe however in my application i often not always run into deadlocks or get segmentation faults enclosing each call of mpicomm world methods with a mutexlock and mutexunlock consistently removes deadlocks as well as segfaultsthis is how i create threadsconst auto communicator stdmake sharedcommunicatorstdvectorstdfuturesize t handlesfor size t i 0 i n i handlespush backstdasyncstdlaunchasync foo communicatorfor size t i 0 i n i handlesigetcommunicator is a class which has a stdmutex member and exclusively calls methods such as mpicomm worldsend and mpicomm worldrecv i do not use any other methods of sendingreceiving with mpi foo takes a const stdshared ptrcomunicator as argumentmy question is the thread safety promised by mpi not compatible with threads created by stdasync,['c++'] +420990,jquery mousedown vs click today i thiscovered something that was quite confusing for mei just tried to hide sth via jquery first i tried to use this specificdiv linthchild3clickfunction anotherdivhidebut it does not workafter a time i tried it this wayspecificdiv linthchild3mousedownfunction anotherdivhidecan anyone explain me why mousedown works instead of clickwould be great to find outeditedited the anotherdiv,"['javascript', 'jquery']" +421037,how to add an event after close the modal window i have code modal button to trigger modal div idresultdiva hrefmymodal rolebutton classbtn datatogglemodallaunch demo modala modal div classmodal idmymodal tabindex1 roledialog arialabelledbymymodallabel ariahiddentrue div classmodalheader button typebutton classclose datathismissmodal ariahiddentrueabutton h3 idmymodallabelmodal headerh3 div div classmodalbody pone fine bodyap div div classmodalfooter button classbtn datathismissmodal ariahiddentrueclosebutton button classbtn btnprimarysave changesbutton divdivand i have code when should been after close moal windowresulthtmlyesresulttell me please how to make that when closing the modal windowclose or hide executed a second code,['jquery'] +421054,minify scriptscss in production mode with nodejs i have a web app that runs in node all the client javascriptcss files are not minified at the moment to make it easier to debugwhen i am going into production i would like to minify these scripts it would be nice to have something likenode appjs productionhow do i serve the minified version of my scripts without changing the script tags in my html files there should be something like if i am in production use these 2 minifiedcombined scripts else use all my unminified scriptsis this possible maybe i am thinking too complicated,"['javascript', 'css']" +421068,android notification action is not fired pendingintent i am trying to add an notification action item in my app which is a music player when a stream is started a notification should be triggered and an stop button for the stream should be thisplayed in the notfication the notification working fine so far i am having trouble with the stop action item here is how it is declared in the service starting the streamintent stopintent new intentthis musicplayernewclastopintentputextrastop stoppendingintent stoppendingintent pendingintentgetactivitythis 0 stopintent pendingintentflag update current nullmbuilderaddactionrdrawableic stat stop stop stoppendingintentnow in the onresumemethod of my activity i check with getintentgetstringextra for the stop extra but the intent i retrieved via getintent has no extras set i also tried to check to send an broadcast i have a broadcast receiver working to communicate from the service to the activityintent stopintent2 new intentmusicplayernewstop mediaplayerpendingintent stoppendingintent2 pendingintentgetbroadcastthis 0 stopintent2 pendingintentflag update currentmbuilderaddactionrdrawableic stat stop stop stoppendingintent2 now this works if the activity is currently in the foreground if the activity is in the background the stop button does nothing editi have the broadcastreceiver in my activity as a private classprivate class dataupdatereceiver extends broadcastreceiver override public void onreceivecontext context intent intent in the onresume register my app for this receiverintentfilter new intentfilterstop mediaplayerregisterreceiverdataupdatereceiver intentfilteronpauseunregisterreceiverdataupdatereceivernow if i remove the unregistering from the onpausemethod the broadcast is received even if the appactivity is not in the foreground anymore but is this the right way to do it i got this registerunregisterstuff from a tutorial on the web i think,['android'] +421120,whats the default hex color of the hololightdarkactionbar actionbar i have got a toolbar at the bottom of my layout which i would like to be the same color as the action bar i am using the holo light with dark action bar theme what is the hex code for this color thanks,['android'] +421154,why does google mocks find this function call ambiguous i have run into an issue while attempting to start using google mocks for some reason it cannot tell the call i am specifying in the expect call macro even though the types are consistent i want to know why it does not just match the first function and what i need to doadd to make it match the first functionthe mock classclass gmocktest public itestpublicmock method2setparameter intint nparameter double valuemock method2setparameter intint nparameter int valuemock method2setparameter intint nparameter int64 valuethe test code that throws the error int64 nfrom 0 nto 0expect callmock setparameter2 nfrom times1 willoncereturn0expect callmock setparameter3 nto times1 willoncereturn0the compilation errortestcpp1343 error c2668 gmocktestgmock setparameter ambiguous call to overloaded function testmocksh592 could be testinginternalmockspecf gmocktestgmock setparameterconst testingmatchert const testingmatchera2 with fint int int64 tint a2 int64 testmocksh590 or testinginternalmockspecf gmocktestgmock setparameterconst testingmatchert const testingmatchert with fint intint tint testmocksh580 or testinginternalmockspecf gmocktestgmock setparameterconst testingmatchert const testingmatcherfloattype with fint intdouble tint floattypedouble while trying to match the argument list int int64,['c++'] +421168,jquery each waiting for function to finish before continuing through loop i am essentially trying to loop through a collection of li tags and insert some text to simulate the look of someone writing a list of things to do it works but it writes each of the list items simultaneously instead of waiting is there an easy way to achieve this i have a js fiddle setup here but the code looks like this thanksfunction addlistitems var str listitem1personal background check listitem2look into my sketchy neighbor listitem3look up my driving record listitem4pick up milk listitem5wash the carlistcontainer lieachfunction var z thisattrid var str2 strz var delay 0 for var i 0 i str2length i functionstr2 delay 100 mathfloormathrandom116 settimeoutfunction appendstrstr2 delay str2i function appendstrstr2 zappendstr2,"['javascript', 'jquery']" +421179,mockito invaliduseofmatchersexception i have a command line tool that performs a dns check if the dns check succeeds the command proceeds with further tasks i am trying to write unit tests for this using mockito heres my codepublic class command void runcommand dnscheckhostname new inetaddressfactory do other stuff after dnscheck void dnscheckstring hostname inetaddressfactory factory calls to verify hostname i am using inetaddressfactory to mock a static implementation of the inetaddress class heres the code for the factorypublic class inetaddressfactory public inetaddress getbynamestring host throws unknownhostexception return inetaddressgetbynamehost heres my unit test caserunwithmockitojunitrunnerclasspublic class cmdtest many functional tests for dnscheck heres the piece of code that is failing in this test i want to test the rest of the code ie after dnscheck test void testpostdnscheck final cmd cmd spynew cmd this line does not work and it throws the exception below tried using inetaddressfactory anyobject donothingwhencmddnscheckhost anyinetaddressfactoryclass cmdruncommand exception on running testpostdnscheck testorgmockitoexceptionsmisusinginvaliduseofmatchersexception invalid use of argument matchers2 matchers expected 1 recordedthis exception may occur if matchers are combined with raw values incorrect somemethodanyobject raw stringwhen using matchers all arguments have to be provided by matchersfor example correct somemethodanyobject eqstring by matcherany input on how to solve this,['java'] +421180,javascript variable access in html say i have the following javascript in a html pagehtmlscript var simpletext hello world var finalsplittext simpletextsplit var splittext finalsplittext0scriptbody a href testhtmli need the value of splittext variable hereabodyhtmlhow do i get the value of the variable splittext outside the script tagsthanks,['javascript'] +421206,what does the operator mean in php i have a variable that is being defined as var valuehow does the use of the dot equal function,['php'] +421213,collectionsemptymap vs new hashmap what are some of the situations where i can use collectionsemptymap the documentation says i can use this method if i want my collection to be immutable why would i want an immutable empty collection what is the point,['java'] +421215,will php script be executed after header redirect yes this question has been asked before however the answers have been inconsistent take why i have to call exit after redirection through headerlocation in php for instance every answer including the accepted answer states yes except the last answer which received zero votes which says maybe i am starting to think the correct answer is maybe to make it a simple yes or no question will dothis be executed given the following script thanksheaderlocation diesleep10dothiseditthanks all with my phplinuxapache configuration the second syslog executes so the answer is yes all script down stream of the header will be executed i will assume and hope i am correct it is the same with all phplinuxapache configurationsphp headerlocation sysloglog infofirst sleep5 sysloglog infosecond,['php'] +421246,ruby idiom for substring from index until end of string just wondering if there is a ruby idiom for extracting a substring from an index until the end of the string i know of strindex1 which works by passing in a range object to the strings method but it is a little clunky in python for example you could write strindex which would implicitly get you the rest of the stringexamples hello worlds61 worldis there anything nicer than s61,['ruby'] +421267,return back to mainactivity from another activity the mainactivity contains some buttons each button opens a new activity via an intent these activities then have a button to return to the mainactivity via an intentbut when i press a button to return to the mainactivity i get some sort of menu on the screen someone who knows what could be wrong preciate some help thanksedit the return button in one of the other activitiesbutton btnreturn1 button findviewbyidridbtnreturn1btnreturn1setonclicklistenernew viewonclicklistener public void onclickview v todo autogenerated method stub intent returnbtn new intentandroidintentactionmain startactivityreturnbtn the manifestmanifest xmlnsandroidpackagecomkullabergtest02androidversioncode1androidversionname10 usessdk androidminsdkversion10 androidtargetsdkversion15 application androidicondrawableic launcher androidlabelstringapp name androidthemestyleapptheme activity androidnamemainactivity androidlabelstringtitle activity main intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity activity androidnameactivity1 androidlabelstringtitle activity main intentfilter action androidnameandroidintentactionactivity001 category androidnameandroidintentcategorydefault intentfilter activity activity androidnameactivity2 androidlabelstringtitle activity main intentfilter action androidnameandroidintentactionactivity002 category androidnameandroidintentcategorydefault intentfilter activity activity androidnameactivity3 androidlabelstringtitle activity main intentfilter action androidnameandroidintentactionactivity003 category androidnameandroidintentcategorydefault intentfilter activityapplication,['android'] +421282,unexpected behaviour of current in a foreach loop here is a simple loop list arraya b cdforeach list as var printcurrentlistoutput demo b output for 524 550alpha4 bcd output for 441 a output for 430 440 442 523question can someone please explain whats going on why am i not getting abcdeven if a copy of the array was made by foreach i should be getting a but not getting that in the current php stable versionnote i know i can simply use print var but the from php doc current a return the current element in an array the current function simply returns the value of the array element that is currently being pointed to by the internal pointer it does not move the pointer in any way if the internal pointer points beyond the end of the elements list or the array is empty current returns falseupdate 1 new observation thanks to daniel figueroa just by wrapping current in a function you get different result foreach list as var printitemlistfunction itemlist return currentlistoutput demo bcda what the hell question why not getting b how does wrapping current in a function affect foreach output where did the extra a come from update 2 list arrayabcditem2listfunction item2list foreach list as var printcurrentlist output see demo a no longer b when using a functionquestion what is the different running a loop in a function and running it outside a function because you get a outside and b in a function in most php version,['php'] +421285,fatal error call to undefined function pg connect i am using windows 7 php 535 and wamp server i have two php files triggerphp and backgroundphpi want to run backgroundphp as a background process i have to call this file from triggerphp to accomplish this i used below methodi included following code in triggerphp to make backgroundphp to process in backgroundhandle popenstart b cwampbinphpphp535phpexe cwampwemail3phprin backgroundphp i have the follwing code to connect to databaseconn string hostlocalhost port5432 dbnametagbase userpostgres passwordpostgres now on parsing this line am getting the follwing error fatal error call to undefined function pg connect in cwampwbackgroundphp on line 3 call stack 02 322792 1 main cwampwbackgroundphp0by searching in in the internet i found some solutions and made changes as recommended below in phpiniuncommented extensionphp pdo pgsqldlluncommented extensionphp pgsqldlluncommented extension dir cwampbinphpphp535extalso i do have php pdo pgsqldll and php pgsqldll files in cwampbinphpphp535ext folder any suggestions are appreciated,['php'] +421292,use sql cte table to include path and all children i have following hierarchical tree tablegodrop table tbl gocreate table tbl id int parentid intinsert into tbl id parentid values 0 nullinsert into tbl id parentid values 1 0insert into tbl id parentid values 2 1insert into tbl id parentid values 3 1insert into tbl id parentid values 4 2insert into tbl id parentid values 5 2insert into tbl id parentid values 6 3insert into tbl id parentid values 7 3gowhich maps to following tree0 1 2 4 5 3 6 7using cte recursive table how can i get the path and also all children of the selected node for example having 2 as input how can i get following data ordered if possibleid parentid 0 null 1 0 2 1 4 2 5 2i know i can traverse up in the tree get path with following statementwith recursivetree as anchor select from tbl where id 2 union all recursive member select parent from tbl as parent join recursivetree as child on childparentid parentidselect from recursivetreeand with following statement traverse down in the tree get all childrenwith recursivetree as anchor select from tbl where id 2 union all recursive member select child from tbl as child join recursivetree as parent on childparentid parentidselect from recursivetreequestion how to combine these two commands into one,['sql'] +421297,differences between nsarray arraywitharray and nsarray copy lately i work much with arrays and i am wonder whats diffrences between those two linesnsarray array nsarray arraywitharraysomearrayandnsarray array somearray copywhich of it is faster what in case we have nsmutablearray and mutablecopy,['objective-c'] +421307,why does not jsonencode encode data returned from jsondecode correctly when using the json class from systemwebhelpers and i run the following code i expected it to produce a json string containing the same information as the original string but strangely it only returns the string employees and omits the array entirely and replaces it with an empty objectstring jsondata employees firstnamejohn lastnamedoe firstnameanna lastnamesmith firstnamepeter lastnamejones var json jsondecodejsondatastring result jsonencodejson result is employees when i look at the object returned from jsondecode the array is decoded into a dynamicjsonarray if i create a net object with arrayslistsdictionaries it seems to encode them perfectly so the problem seems to be related to dynamicjsonarrayif i encodedecode a complex json string without arrays it seems to be working finestring jsondata firstname john lastname doe family mother firstname anna lastname smith father firstname peter lastname jones var json jsondecodejsondatastring result jsonencodejson result is formatted for readability firstname john lastname doe family mother firstname anna lastnamesmith father firstname peter lastname jones i have looked at the documentation on msdn but could not find any reasons why this should not work could it be a bug or is it by designupdateif i have a json string that is an array at the root node it encodesdecodes correctly so i really start to suspect that this is a bug or at least it is very inconsistentstring jsondata firstnamejohn lastnamedoe firstnameanna lastnamesmith firstnamepeter lastnamejones var json jsondecodejsondatastring result jsonencodejson result is formatted for readability firstname john lastname doe firstname anna lastname smith firstname peter lastname jones update 2i decided to open an issue with microsoft after all let us see what they have to say,"['c#', '.net']" +421329,change binary file in itunes connect i made one app for iphone and i upload my binary file in app store few days ago currently my app status shows in review now i want to change my ipa filecan i change my ipa file right now when my app is in review stateordo i have to wait for review completion and then reupload my binary and wait for more days any help will be appreciated,"['iphone', 'ios']" +421357,how to avoid line breaks after before in css on my website i am using font icons for certain link types these icons are added via before css syntaxasomelinkbefore fontfamily icons thisplay inlineblock paddingright 03em content xhowever when this link is at the beginning of a line it is sometimes separated from its iconi tried adding whitespace nowrap to the css rule above but that did not helphow do i keep the icon and the text together css 3 is okaynote i do not want to format the whole link with whitespace nowrap,['css'] +421369,jquery chosen empty string as option ia m using chosenjs for dropdowns in a form on a grailsenvironmenti want the users to be able to select an empty option but somehow it is ignoredthere must be a possibility to do this because the workaround to set an option like selectnone and later in databindig make a if condition if selectnone value would be unprettyto show my problem for example this select gselect idfoo dataplaceholderbar classfoo chznselect stylewidth 245px tabindex4 fromm f valuefoo nametitelwould return sure this is a nice feature of chosen but i guess my case is a common case and maybe someone of you already has a solution to override this behaviourthanks in advance,['jquery'] +421380,jquery check for file extension before uploading i am using uploadify for uploading files with codeigniter and before uploading the file i just have to check whether the file extension is correct is correct or not i have tried with and also bur did not got proper result can anyone please tell me how can i do the samethanks in advance,['jquery'] +421423,videoview on viewpager stopping video when switching page i have a viewpager with different fragments one of these has a videoview in it if i switch page when the video is playing then it remaings playing even when i am on a different page i tried implementing an onpagechangelistener for the viewpager like thisviewpagersetonpagechangelistenernew onpagechangelistener override public void onpageselectedint position ifpositionmadaptergetcount1 multimediafragment frag multimediafragmentmadaptergetitemposition1 fragonpageischanged ifposition 0 multimediafragment frag multimediafragmentmadaptergetitemposition1 fragonpageischanged with onpageischanged being a method of my own which tries to tell my videoview attribute to stop and hide controlspublic void onpageischanged ifmvideoviewnull ifmvideoviewisplaying mvideoviewstopplayback mmediahide the problem is that mvideoview is always null even when it is playing on the background this videoview is created on the oncreateview method of the fragment but should not it remain set to my mvideoview field until fragment is destroyed,['android'] +421461,not getting automatically webxml file while creating servlet in eclipse juno 42 i am using eclipse juno 42java 17 and tomcat 7but in my system when i create servlet the webxml file does not create automaticallybut anothor system it is create automatically webxml filei am totally confusedis there anything to configureplease help me outi also add webxml file when i am going to create a dynamic project,['java'] +421512,how to stop a java program if it is determined it should not run if i want to check if some preconditions are present in order to run a java program what is bestdosystemexit1 or throw a runtimeexception in main to end the main thread no other threads running yet,['java'] +421580,calculating median in ruby how do i calculate the median of an array of numbers using rubyi am a beginner and within the progress of my learning i am trying to stick to what has already been taught thus the other questions that i have found are beyond my scopehere are my notes and my attemptsort the array in ascending order figure out if it is odd or even in length if odd divide the sorted array length 1 in half thatis the index of the median return this value if even find the middle two numbers of the sorted array and divide them in 12return this value finding the middle two numbers divide the sorted array length in half this is index pt first middle numberdivide sorted array length 2 in half this is the index pt of thesecond middle number take average of these two middle numbersdef medianarray ascend arraysort if ascend 2 0 ascendlength 1 20 else ascendlength20 ascendlength 220 20 endend,['ruby'] +421623,append several variables to a list in python i want to append several variables to a list the number of variables varies all variables start with volume i was thinking maybe a wildcard or something would do it but i could not find anything like this any ideas how to solve this note in this example it is three variables but it could also be five or six or anythingvolumea 100volumeb 20volumec 10vol volappendvolume,['python'] +421670,annotation configuration replacement for mvcresources spring i am trying to upgrade my spring mvc project to utilize the new annotations and get rid of my xml previously i was loading my static resources in my webxml with the linemvcresources mappingresources locationresources now i am utilizing the webapplicationinitializer class and enablewebmvc annotation to startup my service without any xml files but cannot seem to figure out how to load my resources is there an annotation or new configuration to pull these resources back in without having to use xml,['java'] +421708,textview that is linkified and selectable i would like to have a textview that is both selectable and linkified when i do both i end up with selectable text but links cannot be clickedediti will show the code to explain with what i struggle textview textview viewfindviewbyidridmytext textviewsettextmy text 4412345678 go to website wgooglecom blah blah linkifyaddlinkstextview linkifyall if buildversionsdk int buildversion codeshoneycomb textviewsettextisselectabletrue,['android'] +421710,log4j2 assigning file appender filename at runtime i have a log4j2xml config file in the class path one of the appenders is a file appender and i would like to set the target file name at run time in the java applicationaccording to the docs i should be able to use a double and a context prefix in the log4j2xml fileappenders file namemyfile filenamesyslogfilename patternlayout pattern4r ddatestamp t 5level logger36 msgn fileappenderswhere the sys prefix indicates that the configurator will lookup the property logfilename in the system properties so in the application i call rather early onsystemsetpropertylogfilename filenamei have also turned on autoreconfiguration for log4j2 in the xml fileconfiguration statusdebug monitorinterval5unfortunately this has no effect whatsoever and the log file is never created some of the log4j2 status output is below20130213 153637574 debug calling createappender on class orgapachelogginglog4jcoreappenderfileappender for element file with paramsfilenamesyslogfilename appendnull lockingnull namemyfile immediateflushnull suppressexceptionsnull bufferedionull patternlayout4r dymmddhhmmsz t 5level logger36 msgn null20130213 153637576 debug starting filemanager syslogfilenamehow can i have the value of filename in the file appender be set at run time alternatively how can i simply add a new file appender to the root logger at run time in log4j 20 most of the api to change the configuration is hidden,['java'] +421719,launching a specific viewcontroller in response to a remote push notification i am creating an app whos storyboard flows like the image below when a user logs in from sysalert view controller they are brought into message list view controller where i do an nsurlconnection to load some json into the table when a user taps a row in the table they are brought into message details which shows more detailed information for that messagewhen a user launches the app from a push notification regardless of the state of the app prior to launching i want the app to load the message list data from my server and then show them the message that is just been pushed to the devicei know i need to use didfinishlaunchingwithoptions to tell the app to react to the push notification but how do i setup the view hierarchy so that the message list view controller loads its data and then pushes the message details view controller onto the stack for the appropriate messageessentially this kind of mimics the behaviour of the messages or mail apps where opening with a notification brings you to a view controller for that message but you are still able to move back in the hierarchy as if you had launched the app from the initial viewcontroller and traversed through the viewcontrollers in turn,['ios'] +421737,does javascript have undefined behaviour does javascript have undefined behaviour similar to c or is it completely welldefined by the spec and deterministicnote that i am thiscarding implementation bugs and spec divergences i am also thiscarding stuff like mathrandom and datenowis there a piece of javascript code for which the behaviour is not completely determined by the javascript specifications and as such has undefined behaviour,['javascript'] +421768,extract measures on each line from sheet music i would like to know a way to extract individual line of measures i am not sure if an algorithm for this already exists so i have thought of scanning a sheet music from left to right extract all the white spaces from above and below a line of measuresi am not looking for a way to convert the sheet music into musicxml or extract other useful information no essentially what i am dealing with is a regular document i need to separate the paragraphs i am not interested in the information conveyed by the paragraph but simply chunking them separately from the regions of the document in this case a paragraph would be one line of measures i do not need individual measures but all the measure on each line of sheet musicthis is one of the output i would like from the full sheet music but without the title composer and etc,"['java', 'python']" +421819,python module would not install this is my setuppy fileusrbinenv pythonfrom setuptools import setupfrom sys import pathsetupname conundrum version 010 author elssar author email py modules conundrum url license mit description a framework agnostic blog generator long description openpath0readmemd rread install requires pyyaml 309 markdown 220 requests 104 i have tried using both setuptools and thistutils but this would not install my module instead i getfile modulepy for module module not foundthis is my directory structuremoduletestreadmemdlicensetxtmodulepysetuppyjust to be clear module is the root directorycan anyone tell me what i am doing wrongthis is the output when i try to installelssarelssarlaptopusrlocalsrcconundrum sudo python homeelssarcodeconundrumsetuppy installusrlibpython26thistutilsthistpy250 userwarning licence thistribution option is deprecated use license warningswarnmsgrunning installrunning bthist eggrunning egg infowriting requirements to conundrumegginforequirestxtwriting conundrumegginfopkginfowriting toplevel names to conundrumegginfotop leveltxtwriting dependency links to conundrumegginfodependency linkstxtwarning manifest maker standard file setuppy not foundfile conundrumpy for module conundrum not foundreading manifest file conundrumegginfosourcestxtwriting manifest file conundrumegginfosourcestxtinstalling library code to buildbthistlinuxx86 64eggrunning install librunning build pyfile conundrumpy for module conundrum not foundfile conundrumpy for module conundrum not foundwarning install lib buildliblinuxx86 6426 does not exist no python modules to installcreating buildbthistlinuxx86 64eggcreating buildbthistlinuxx86 64eggegginfocopying conundrumegginfopkginfo buildbthistlinuxx86 64eggegginfocopying conundrumegginfosourcestxt buildbthistlinuxx86 64eggegginfocopying conundrumegginfodependency linkstxt buildbthistlinuxx86 64eggegginfocopying conundrumegginforequirestxt buildbthistlinuxx86 64eggegginfocopying conundrumegginfotop leveltxt buildbthistlinuxx86 64eggegginfozip safe flag not set analyzing archive contentscreating thistconundrum010py26egg and adding buildbthistlinuxx86 64egg to itremoving buildbthistlinuxx86 64egg and everything under itprocessing conundrum010py26eggremoving usrlocallibpython26thistpackagesconundrum010py26egg and everything under itcreating usrlocallibpython26thistpackagesconundrum010py26eggextracting conundrum010py26egg to usrlocallibpython26thistpackagesconundrum 010 is already the active version in easyinstallpthinstalled usrlocallibpython26thistpackagesconundrum010py26eggprocessing dependencies for conundrum010searching for requests104best match requests 104adding requests 104 to easyinstallpth fileusing usrlocallibpython26thistpackagessearching for markdown220best match markdown 220processing markdown220py26eggmarkdown 220 is already the active version in easyinstallpthinstalling markdown py script to usrlocalbinusing usrlocallibpython26thistpackagesmarkdown220py26eggsearching for pyyaml310best match pyyaml 310adding pyyaml 310 to easyinstallpth fileusing usrlocallibpython26thistpackagesfinished processing dependencies for conundrum010just to be sure there is not something wrong my my system i downloaded two packages from github with a similar setuppy and installed them installed without any problems,['python'] +421831,round some corners of uiview and round the viewas layeras border too i am trying to round the bottom two corners of a uiview and have the layeras border show up rounded as well i am currently doinguirectcorners corners uirectcornerbottomleft uirectcornerbottomrightcgsize radii cgsizemakekthisviewcornerradius kthisviewcornerradiusuibezierpath path uibezierpath bezierpathwithroundedrectmyviewbounds byroundingcornerscorners cornerradiiradiicashapelayer masklayer cashapelayer layermasklayer setpathpathcgpathmyviewlayermask masklayerthis works fine for normal views however myviewas layer has its bordercolor and borderwidth set and as you can see from the screenshot the layeras border is not getting roundedi also tried subclassing uiview and returning cashapelayer layer from class layerclass and setting up the viewas layer as a shape layer but the border ended up beneath the viewas subviewsis it possible to round some of a viewas corners round the viewas layeras border and clip the subviews underneath the layeras bordernote that this is not about how to round some corners and not others but rather how to get the stroke to behave correctly,"['ios', 'objective-c']" +421886,unittest for none type in python i was just wondering how i would go about testing for a function that does not return anything for example say i have this functiondef is inchar my list my listappendcharand then if i were to test itclass testisinunittesttestcase def test oneself test if one character was added to the list selfassertequalselfis ina and this is where i am losti do not know what to assert the function is equal to since there is no return value that icould compare it toedit would assertin work,['python'] +421963,check whether the delayed job is running in rails i am designing a status page where i need to show whether the delayed job is running please help me with a way to find it in the codeam using rails 3020 ruby 187 20110630 patchlevel 352 and delayed job 304,['ruby-on-rails'] +421999,install unistall from shell command in android i want to implement a silent installerfromapkfile and unistallerpackage in androidthe topic has largely been thiscussed on so and elsewhere but i cannot apply any for some reason that i am missingthe scope is obviously hard to achieve because if successful it would be a serious security breach in android but i need to implement it for a special project not for the consumer marketthere are two approachesto generate a custom rom from a source code aosp or cyanogen mod for example by tweaking the packagemanager installer in fact just to remove the user acceptance dialog boxesto do it programmatically by creating a process as super user and executing an adb shell pm install i previously installed su in systemxbin and i test during run time that roottoolsrootisavailablefor the first case i digged into the froyo source code but got into a dead end with a hide marked methodfor the second i have first tried the commands from the terminaladb shell pm install mntsdcardhelloandroidapkand adb shell pm uninstall comexamplehelloandroidboth work ok then i used the following code the development being tested on a rooted emulator 22 froyooverride public void onclickview v switch vgetid case ridbtninstall try install runtimegetruntimeexecsun dataoutputstream os new dataoutputstreaminstallgetoutputstream oswritebytespm install mntsdcardhelloandroidapkn oswritebytesexitn osflush installwaitfor if installexitvalue 0 toastmaketextmainactivitythis success toastlength longshow else toastmaketextmainactivitythis failure exit code stringvalueofinstallexitvalue toastlength longshow catch interruptedexception e logerrore catch ioexception e logerrore break case ridbtnuninstall try install runtimegetruntimeexecsun installruntimegetruntimeexecpm uninstall txtpackagenamegettexttostringn catch exception e logerrore break to avoid typos and other trims i hardcoded the apk file parameter of the command for the installation on case ridbtninstall the command is not executed and the exit is on failure with exit value 1 meaning that the class cannot be found no clue what that means i appreciate your help edited i have the clean solution i shall post the answer from az as soon as i have the time and the code in the right form,['android'] +422002,should i use shared ptr or unique ptr i have a question about stdunique ptr and stdshared ptr i know there are loads of questions about when to use which one but i am still not sure if i understand it correctly i read somewhere that the default choice for smart pointer should be stdunique ptr but as i understand it for my needs i should rather use stdshared ptr for example i haveclass bclass aprivate b bpublic b getbagetb return bso basically class a owns pointer to object of type b and there is a method which returns this pointer if i create getter i assume that some other class can access this pointer and therefore it should be shared ptr instead of unique ptr am i right or i do not get it yet,['c++'] +422007,cannot upload a file with sahi mink behat in a symfony2 application i am using mink and sahi for my user interface tests inside a symfony2 application but actually i cannot manage to upload a file with sahimy sahi server is up and running095133 coilubuntuwebdevsahibin sahish sahi home sahi userdata dir userdatasahi ext class pathsahi properties file homecoilwebdevsahiconfigsahipropertiessahi user properties file homecoilwebdevsahiuserdataconfiguserdatapropertiesadded shutdown hook sahi started listening on port 9 configure your browser to use this server and port as its proxy browse any page and ctrlaltdblclick on the page to bring up the sahi controllerreading browser types from homecoilwebdevsahiuserdataconfigbrowser typesxmlmy step implementation elementgetxpath htmldescendantorselfid attachment1elementattachfilefilenote here that if i use a file that is not homecoilwebdevsahiuserdata directory i get the following errorelementattachfiletotoerror setfile2 byxpathhtmldescendantorselfid attachment1 toto error file not found toto base directory is userdata directory homecoilwebdevsahiuserdata error file not found toto base directory is userdata directory homecoilwebdevsahiuserdata at sahi setfile s sprconcatjs139812 at sahi setfile2 s sprconcatjs13677 at eval eval at anonymous s sprconcatjs348014 anonymous17 at sahiex s sprconcatjs34809 at anonymous1 a href s dynlog getbrowserscripthrefnulln1bclick for browser scriptbaso sahi can find the file as it does not raise any error with a valid and existing file but when the form is submitted the file is never uploaded by the sahi proxyother checksi removed the client side html5 and javascript validation to be sure there is no side effectall my other sahi tests are ok only the 3 with an upload do not passthe proxy is set in my testing browseri can open the sahi controller in the browser without problemsame problem on maxosx and ubuntueach time i run an upload test i have got a new entry in userdatatempdownload named like sahi 11a83f8806be8046fc0a80eac076110b95 frfr20bdicwhat is really weird is that i am sure that those tests passed some times ago something must have changed in my application or configuration that breaks the sahi file upload but i cannot find whatand before in the sahi console i had logs about the files that it was uploading now there is no log at all,['php'] +422014,android the standalone version of traceview is deprecated i want to see my traces 1 in code i have added these lines of code start trace recordingandroidosdebugstartmethodtracinghc traceviewand stop trace recordingandroidosdebugstopmethodtracing2 i can see hc traceviewterac in file explorer of ddms3 based on viewing trace files in traceview i ran following command in terminalhesamk5vddesktopeclipsesdktools traceview mntsdcardhc traceviewbut out put isthe standalone version of traceview is deprecatedplease use android device monitor toolsmonitor insteadtrace file mntsdcardhc traceview not found4 based on suggestion i ran following command in terminalhesamk5vddesktopeclipsesdktools monitor mntsdcardhc traceviewddms opened but my traces are not here how can i see my tracesany suggestion would be appreciated,['android'] +422037,visual studio c multiline comments in vs c code if i have not selected anything or full line selected and press comment selection ctrlk ctrlc then it will comment the whole line with int x 5after pressing ctrlk ctrlc without anything selected or full line selected int x 5now if i select some part of the line and press comments button again only selected text will be commented bold means selectedint x 5after pressing ctrlk ctrlc with x 5 selectedint x 5incase of multiple linesint x 5int y 2int z x 5and after comments shortcutint x 5int y 2int z x 5what i wantint x 5int y 2int z x ynow this is what i do not like usually i select multiple lines and press comments button this will comment only the selected characters but i want all selected lines tobe commented is there anyway to do that any extension or from visual studio settings i can change that,['c++'] +422042,change spinner content on opening i have a spinner and its content depends on actual location gps position so the content should changes continually but it is only visible to the user when heshe selects an item instead of having a thread who continually updates the spinner content or a button to force an update from the user i would like to obtain another behaviourwhen the user touches the spinner before the spinner opens it should be updated i am already able to change programmatically the spinners content what i need is an event that triggers when the user touch the closed spinner but before the opened spinner is showni hope this question is clear enough thank you for you attention,['android'] +422103,nhibernate queryover with complex join over nonrelated entities so i have spent the last few hours looking for an answer and i cannot seem to find anything that makes sensepublic class game public virtual guid id get set public virtual resultstructure structure get set public virtual listresult results get set public class result public virtual player player get set public virtual int position get set public class resultstructure public virtual guid id get set public virtual listresultoutcomes outcomes get setpublic class resultoutcomes public virtual int position get set public virtual int points get set public class playersummary public virtual player player get set public virtual int points get set what i am trying to do is get a list of players and the points they have earned across a multitude of different games there are multiple entities above game that contain lists of games so the end result of the query would be listplayersummary the sql i am looking for would look something like thisselect p sumrspoints from result r join player p on rplayerid pid join game g on rgameid gid join resultstructure rs on gresultstructureid rsid join resultoutcomes ro on rsid roresultstructureid and roposition rpositionnote i will also need to do some queryingsumming against the structure entity which is why it is includedi am trying to do this with nhibernate using the typesafe stuff and my plan is for the application to be database agnostic so i cannot use direct sql currently it is using postgres but i may move to sql server at some pointi do not particularly want to use the hql stuff where you use those magic strings so i am trying to use linq or queryoverquerycan anyone point me in the right direction,['c#'] +422104,android view background changes unexpectedly i am building an app that has plenty of screensmost of the screens have a view at the top with a background colori often change that color using viewsetbackgroundcolorcolorhere comes the weird thing sometimes after setting the color of one view say to f14fb7 when navigating in the app other views backgrounds are set to that color without me wanting them toit sometimes even happens to views i had not set an id for so there is no way setbackgroundcolor was called on those viewsthis happens rarely and is not consistant to any flow i triedwhen i kill the app and restart it everything works as it shouldmy only guess is some king of memory leak but i hope there is a simpler explanationcan anyone think of some reason for this to happenit happens on my galaxy s3,['android'] +422237,including a interactive 3d figure with knitr using knitr it is possible to embed a rgl 3d graphics in a html document from a rmarkdown source filer setuplibraryrglknit hookssetrgl hook rglx sortrnorm10y rnorm10z rnorm10 atan2xyr rgltrueplot3dx y z colrainbow10but the 3d graphic is not interactive in the html document is it possible to get an interactive 3d graphic the writewebgl function of the rgl package creates a html file with an interactive 3d graphic is there a way to include directly this html code with rmarkdown otherwise how to include this html code manually update 24062013here is an example that does not work today the 3d graphic does not appear in chromethe rmd source file which is very basicr setuplibraryrglknit hookssetwebgl hook webglr webgltruem rbind c0 c140 c490 c630 points3dmcolredrsessioninfoi have knitted this file with the rstudio knit button in two situations using different versions of rgl and knitr packages but this is surely due to the rgl package because the problem occurs with the output of the writewebgl function old versions with r2152 source file and html rendering and the html file generated by writewebgl with rgl 093928 for me it works well there are just 4 red points in the 3d plot not easy to see on my dirty screen but i see them latest versions with r2153 source file and html rendering and the html file generated by writewebgl with rgl 093935 for me it does not work the 3d plot is not visible i use windows 7 and it does not work with chrome neither with firefoxedit 28062013the problem raised by the 2406 update has nothing to do with knitr i have rephrased it in this post webgl rendering with rgl 093935 r package,['html'] +422242,whats the difference between implementing filterattribute iactionfilter and inheriting from actionfilterattribute in aspnet mvc 3 i see that in one situation we can override onactionexecuting or onactionexecuted methods inheriting from actionfilterattribute class like this public class myfilterattribute actionfilterattribute public override void onactionexecutedactionexecutedcontext filtercontext bla bla and in other situation we also can implement iactionfilter and filterattribute like this public class mysecondfilterattribute filterattribute iactionfilter public void onactionexecutedactionexecutingcontext filtercontext so is there any differences between these two approaches maybe any particular situations where it would be preferable to use one of them over the otherthanks in advance,['asp.net'] +422246,can you advise me a resource with linqlambda code exercises can you advise me an a resource with simple c linqlambdaexpressions code exercises desirable but not obligatory online free with answers step by step the simplest and fast to study the syntax but not complicated puzzles or world problems i do not think it is duplicated withlearning c with exercises questions and puzzles since it was 2 years ago so propably outdated and it did not contain any good reference looked through all of them the best google search result i managed to find is c exercises and solutionsc variables and data types though i am not satisfied updatesomething similar to linq quiz which is for me the best reference i could find to this moment,['c#'] +422250,aliased arguments in strtol here is how strtol has to be declared according to a 72214 from c11 n1570include stdlibhlong int strtol const char restrict nptr char restrict endptr int baseas far as i know the restrict keyword means that the object referenced by the lvalue nptr will be accessed only with it or a value directly derived from it however a lot of programmers and even experienced ones use strtol in the following wayinclude stdlibhstrtol p p 10in that case endptr p p nptr and the behavior is undefined is it right,['c'] +422270,java hashset with a custom equality criteria i was looking for something akin to the java treesets ability to receive a custom comparator at instantiation time so i needed not to use the objects default equality and hash code criteriathe closest i could come up with was to wrap my objects in a private custom class but that seems hacky this ends up being a kind of recurring theme when programming so i was wondering if there is something already available for us to use maybe in the commons librariesthanks,['java'] +422311,run junit tests in maven without building and copying files i have a large maven project which has several modules in it when i want to run a junit test from one module i run mvn dtestnameoftest test in the directory that contains all the modules when i run this command maven goes through each module and tries to compile it though it is already compiled which involves copying a bunch of files and adds to the total time of the test it seems that the test command for the maven surefire plugin executes all the steps up to the test i was wondering if there is a way to execute only the test step and not bother with all the attempted compilation and copying of fileshere is some output from before the test startsinfo info buildhelpermavenplugin15addtestsource addtestsource module1 info test source directory directory in module1 with some generated sources addedinfo info mavenresourcesplugin25testresources defaulttestresources module1 debug execute contextualizeinfo copying 108 resourcesinfo copying 13 resourcesinfo copying 1 resourceinfoit repeats this for each of the other modules all told it takes a minute or two before it actually starts the test does anyone know a way to get the test to run without bothering with all the compilation beforehand please let me know if there is any more information i should provide,['java'] +422374,catching error when using taskfactory i am using the followingtaskfactorystartnew doprintconfigpageserialthen the function i am calling looks like thisprivate void doprintconfigpagestring serial do printing work my problem is an exception is being thrown inside the thread and not being handledi have tried wrapping it in a try catch try taskfactorystartnew doprintconfigpageserialcatch exception ex but it still is not catching the error and thus crashing the applicationhow can i catch exceptions in the main thread so i can handle themupdatei have made the changes recommended below and still it is saying the exception is unhandledvar task taskfactorystartnew doprintconfigpageserial continuewithtsk messageboxshowsomething broke taskcontinuationoptionsonlyonfaultedthen in my doconfigpage i added another try catch in this catch is now where it is crashing and saying the exception being thrown was unhandled what am i missingprivate void doprintconfigpagestring serial try call the print function catch exception ex throw ex it is crashing here and saying it is unhandled i also tried what eric j suggested with the same resultsvar task taskfactorystartnew doprintconfigpageserialtry taskwait catch aggregateexception ex messageboxshowsomething broke,"['c#', '.net']" +422377,order of execution in sql server variable assignment using select given the following exampledeclare i intselect i 1 i 2select iwill i always be 2this is about the most trivial example i can think of but i am considering using this for swapping values in variables i also believe this method of assignment select is not ansi compliant however useful but do not really care to have portable code in this caseupdatethanks to michaelfredrickson we have martinsmiths answer and reference to msdn on this i am now struggling with what the second sentence in this documentation means exactly emphasis addedif there are multiple assignment clauses in a single select statement sql server does not guarantee the order of evaluation of the expressions note that effects are only visible if there are references among the assignmentsthe first sentence is plenty enough to keep me away from relying upon the behavior however,['sql'] +422448,c static classes and the is operator after refactoring some code recently which involved some class renames some of my code broke in a surprising way the cause was a failing is operator test that i was very surprised was not a compiler error or warningthis complete program shows the situationstatic class extensionmethods class program static void main testtest public static bool testobject obj return obj is extensionmethods i would have expected obj is extensionmethods to raise a warning of some sort given that extensionmethods is a static class the compiler will issue a warning for the is operator when object under test can never be of the provided type stringobj is systemuri for example am i forgetting a scenario in which this would actually be a meaningful test,['c#'] +422474,convert jobject into dictionary is it possible i have a web api method that accepts an arbitrary json payload into a jobject property as such i do not know whats coming but i still need to translate it to net types i would like to have a dictionary so i can deal with it anyway i want toi searched a lot but could not find nothing and ended up starting a messy method to do this conversion key by key value by value is there a easy way to do itinput jobject person new jobject new jpropertyname john smith new jpropertybirthdate new datetime1983 3 20 new jpropertyhobbies new jarrayplay footbal programming new jpropertyextra new jobject new jpropertyfoo 1 new jpropertybar new jarray1 2 3 thanks,"['c#', '.net']" +422489,independent multithreaded processes block simultaneously the system is linux gentoo x64 the code is c i have a daemon application several instances of which are run on the same machine the application is multithreaded itself for some time i have been observing strange delays in its performanceafter putting some debugging code i came up with a strange thing when several instances of the daemon literally block simultaneously which is allegedly caused by some external reason or something to put it all simple i have a sequence like thislog time t1lock mutexcall c stdlistpush backpop back ie very simple mathunlock mutexlog time t2from time to time i clearly see that the sequence above running in several independent processes blocks at step 2 or probaby at step 4 for some really excessive time concerning the math at step 3 for instance 05 10 seconds as the proof i see that t2 in the logs for all the processes is literally the same different in some microseconds it looks like some threads of the processes enter the section at relatively different times i can clearly see 05 1 seconds difference for t1 lock in the mutex and unlock at the same time having allegedly spent unreasonable amount of time in the lock according to the log t2 t1 difference looks creepy to methe manifestation of the issue is relatively rare about once 510 minutes under moderate load no ntp time shifts are logged within the test that was my first idea actually if it were ntp there would not be actual delays in service only wrong times in the logwhere do i start do i start tuning the scheduler what can theoretically block an entire multithreaded process in linux,['c++'] +422512,java an entitymanager object in a multithread environment if i have multiple threads each use injector to get the entitymanager object each use the em object to select a list of other class objects ready to be used in a for loopif a thread finishes first and calls clear will that affect the other threads like the for loop will have exceptionhow about closeif the answer is it depends what class definition method call and where java code annotation xml should i look at to find out how is it dependedi did not write the source i am just using someone elses library without documentationthank you,['java'] +422531,setting up websockets without command line how can i follow a tutorial like this without using the command linei need to be able to use websockets but have a shared server and no access to the command linei cannot simply run the script from a browser if the script would stop running when i closed the browserthisconnected from the internet,['php'] +422539,assert in trycatch block is caught just came across some interesting behavior assert being caught by catch block listdecimal consarray new listdecimaltry decimal d assertistruedecimaltryparseitemvalue out d consarrayadcatch exception e consolewritelineitemvalue consolewritelineeassert throws assertfailedexception and its caught by catch always thought that if assert fails then test is failed and consecutive execution is aborted but in that case test moves along if nothing wrong happens later i get green test in theory is it right behavioredited i understand that maybe it is net restriction and how asserts are made in mstest assert throws exception since catch catches everything it catches assert exception but is it right in theory or mstest specific,['c#'] +422544,vertical viewpager implementation i really need a implementation of a vertical viewpager more exactly to be able to swipe through fragments vertically and not horizontally like is the default implementation of viewpager i am already aware of the library directionalviewpager by jake wharton but is deprecated and i need to use the latest support library v13i am running out of time that is why i am asking if someone implemented a vertical viewpager and can share the code here i would be very gratefulthanks a lot,['android'] +422596,c embed command prompt in form with locked position i have been looking at how you can embed a command prompt window into a winformi have it working from many examples that use pinvoke but i want to be able to lock the command prompt window in a strict position within the form that the end user is unable to moveis this possiblethe reason behind doing this is because we use remote tools over a large network and you can have many of these tools open in your session at once i want to try and bring them all into one space where possiblethanks,['c#'] +422603,internet explorer 8 ignores fontweight in css so i am having problems understand why ie is ignoring my css here i have this codeh2har du stadsnat eller kan du fa deth2ie nothing weird or anything and here is the resulting renderingbut here is the css code for this htmlrubrik h2 fontfamily lato fontsize 32px fontweight normal lineheight 38px fontvariant normal fontstyle normal color 969696 which clearly states that the h2 should have normal as font weight yet the rendered text is clearly bold here is a correct rendering from safariso using the included developer tools of internet explorer 8 i inspect the css interpretation and that looks like thisas i understand it what i am looking at here is ie8s interpretation of my css and suspiciously missing is the normal attribute ie has converted the css to the oneline version of font but did not include the normal part now the font lato is a fontface font and the fontface css is herefontface fontfamily lato src urlmediafontslatoeot src localnofont urlmediafontslatottf formattruetypefontface fontfamily lato src urlmediafontslatoboldeot src localnofont urlmediafontslatoboldttf formattruetype fontweight boldfontface fontfamily lato src urlmediafontslatobolditaliceot src localnofont urlmediafontslatobolditalicttf formattruetype fontweight bold fontstyle italicfontface fontfamily lato src urlmediafontslatoitaliceot src localnofont urlmediafontslatoitalicttf formattruetype fontstyle italiceven when specifying normal in the fontface declaration for fontweight it does not work so i am stuck here trying to figure out what i am doing wrong not to have ie include fontweight normal in the declaration for h2 any guesses thanks in advance,['css'] +422631,cannot heroku run rake db migrate through my app it is my first time to encounter such errorsrunning rake dbmigrate attached to terminal up run8524 heroku client internal error search for help at or report a bug at error operation timed out connect2 errnoetimedout backtrace usrlocalherokulibherokuclientrendezvousrb39in initialize usrlocalherokulibherokuclientrendezvousrb39in open usrlocalherokulibherokuclientrendezvousrb39in block in start usrlocalherokurubylibruby191timeoutrb68in timeout usrlocalherokulibherokuclientrendezvousrb31in start usrlocalherokulibherokucommandrunrb113in rendezvous session usrlocalherokulibherokucommandrunrb100in run attached usrlocalherokulibherokucommandrunrb21in index usrlocalherokulibherokucommandrb206in run usrlocalherokulibherokuclirb28in start usrlocalherokubinheroku24in main command heroku run rake dbmigrate app oppcis version herokutoolbelt2350 x86 64darwin1080 ruby193i have been out for awhile in using heroku and after the big comeback i encountered this errori am outdated already in terms of present heroku newsi hope somebody could give me a suggestion solution or issues involvedthankseditthe logs says20130215t08380 herokuapi starting process with command bundle exec rake dbmigrate by 20130215t0838030 herokurun6510 awaiting client20130215t0838030 herokurun6510 starting process with command bundle exec rake dbmigrate20130215t0838040 herokurun6510 state changed from starting to up20130215t0838330 herokurun6510 error r13 attach error failed to attach to process20130215t0838340 herokurun6510 process exited with status 12820130215t0838340 herokurun6510 state changed from up to complete,['ruby-on-rails'] +422719,refactoring a static class to use with dependency injection we need to use an unmanaged library in our code that has static methods i would like to introduce the library operation as a dependency in my code and apart from having static methods the library has an initialization method and a settings method both are global so i cannot just wrap this in an instance class because if one instance changes a setting all other instances will be affected and if one instance gets initialized all other instances will be reinitializedi thought about introducing it as a singleton class this way it will be in an instance class but there will only be one instance thus i would not have to worry about changing the settings or initialization what do you think about this approach i am pretty new to the dependency injection pattern and i am not sure if the singleton pattern is a good solution what would your solution be to a similar caseedit the initialization takes a parameter too so i cannot just lock the method calls and reinitialize and change settings every time it is callededit 2 here are the signatures of some methodspublic static void initializeint someparameter parameter can only be changed by reinitalization which will reset all the settings back to their default valuespublic static float method1int somenumber float somearraypublic static void changesettingstring settingname int settingvalue,['c#'] +422752,finishing an activity from another class i am working on an app that requires a permanent internet connection if no internet connection is present i want the user to be logged out of the app taken to the login screeni have a network receiver class that detects network connectivity i want this class to either terminate the activity on top of the stack or to start a new login activity and delete the entire history stackthe problem is that i cannot finish the foreground activity from inside the my receiver class and there is no way of knowing which activity the user is in when there is a network fail and if i am starting a new login activity from this class when the user presses back he is taken back to the appif he reconnects to a network but the app is not logged in and crashestried using myintentaddflagsintentflag activity new task flag activity clear top when starting a new login activity from my networkstatereceiver class but it does not work to my understanding this creates a new task in which the only activity is the one i started login but the old task with all the other activities remain intactso i need either a way to finish a foreground activity from a classor a way to start a new activity from a class and emptying the activity stack heres the receiver code for what it is worthpublic class networkstatereceiver extends broadcastreceiverpublic void onreceivecontext context intent intent superonreceivecontext intent logdappnetwork connectivity change ifintentgetextrasnull loginapikey null networkinfo ninetworkinfo intentgetextrasgetconnectivitymanagerextra network info ifninull nigetstatenetworkinfostateconnected logiappnetwork nigettypename connected ifintentgetextrasgetbooleanconnectivitymanagerextra no connectivitybooleanfalse loginloginactive logdappthere is no network connectivity toastmaketextcontext no internet connection logging out toastlength longshow logout receiverenginecontexthalt receivermsipdroidengine null receiverreregister0 new threadchatlistrunnableinterrupt chatlistbuddylistclear loginapikey null logilogout logged out loginloggedout true intent myintent new intentcontext loginclass myintentsetflagsintentflag activity clear top intentflag activity new task myintentaddflagsintentflag activity previous is top contextstartactivitymyintent solution passed reference from all activities to receiverrandom user activity overrideprotected void onpause superonpause networkstatereceivercuractivity nulloverrideprotected void onresume superonresume networkstatereceivercuractivity user activitythis edited getparent does not always workand in network receiver in onreceive ifcuractivity null curactivityfinish,"['java', 'android']" +422755,takepicture fails with heap related error first things first the following error occurs on 2 different htc desires one with 233 one with 404i get the following error messages when trying to call takepictureememoryheapbase104 error opening devpmem camera no such file or directoryequalcommcamerahardware104 failed to construct master heap for pmem pool devpmem cameraequalcommcamerahardware104 initsnapshot x failed with pmem camera trying with pmem adspthe corresponding picturecallback is never invoked after this errorthe only explanations i could find were a startpreview was not called b trying to take pictures too fast before the picture callback was invoked c not setting the correct usespermissionsi do a here in onresume of my fullscreenactivityopen the camera resourcecam cameraopencameraparameters params camgetparameterschange parametersparamssetjpegquality100best qualityparamssetflashmodeparametersflash mode torchparamssetzoom2listsize supportedpreviewsizes camgetparametersgetsupportedpreviewsizesparamssetpreviewsizesupportedpreviewsizesget0width supportedpreviewsizesget0heightcamsetparametersparamssurfaceview sv surfaceviewthisfindviewbyidridsurfaceview1surfaceholder mholder svgetholder mholdersettypesurfaceholdersurface type push buffers mholdersetsizefromlayoutmholderaddcallbackthistry camsetpreviewthisplaymholder catch ioexception e logdtag error setting camera preview egetmessagelogdtag starting previewcamstartpreviewb should not apply to me as i only attempt to take a single picturec usespart of my manifestusessdk androidminsdkversion8 androidtargetsdkversion8 usespermission androidnameandroidpermissioncamerausespermission androidnameandroidpermissionwrite external storageusespermission androidnameandroidpermissionflashlightusesfeature androidnameandroidhardwarecamera usesfeature androidnameandroidhardwarecameraautofocususesfeature androidnameandroidhardwarecameraflashsome additional codewhere i invoke takepicture note that recording here means that a asynctask is permitted to call takepicture again after it has completed irrelevant however as error persists without ever calling the asynctaskfindviewbyidridsnap buttonsetonclicklistenernew viewonclicklistener override public void onclickview v recording recording button btn buttonfindviewbyidridsnap button ifrecording update buttontext btnsettextstop start recording by taking a picture camtakepicturenullnull mpicture else update button text btnsettextstart editafter slightly altering my layout the picturecallback is finally invoked and i get valid data yay however the error persists heres my current layoutxml version10 encodingutf8linearlayout xmlnsandroid androidlayout widthfill parent androidlayout heightfill parent androidorientationhorizontal surfaceview androidididsurfaceview1 androidlayout width0dp androidlayout height369dp androidlayout weight155 linearlayout androidlayout widthwrap content androidlayout heightmatch parent androidorientationvertical button androidididsnap button androidlayout widthwrap content androidlayout heightwrap content androidtextcapture progressbar androidididprogressbar1 styleandroidattrprogressbarstylelarge androidlayout widthwrap content androidlayout heightwrap content linearlayoutlinearlayout,"['java', 'android']" +422763,matplotlib hooking in to homebackforward button events does anyone know how to get the home back and forward button events from a matplotlib figurei need the events to call some of my functions such that my plots behave correctly when those button are pressed ie the default behaviour is not doing what i need it to domatplotlib assumes the underlying dataset is constant and that all it need do is reset the xy axis limits and replot for those buttons unfortunately that assumption is untrue for my case i have a data stack that needs to be pushed and popped as those button events are triggered,['python'] +422779,create multiple columns in pandas aggregation function i would like to create multiple columns while resampling a pandas dataframe like the builtin ohlc methoddef mhldata return pandasseriesnpmeandatanpmaxdatanpmindataindex meanhighlowtsresample30minhowmhldies with exception must produce aggregated valueany suggestions thanks,['python'] +422827,sherlock actionbar invalidateoptionsmenu i am with a big error herei am trying to change the actionbar menus with the supportinvalidateoptionsmenu but when the function is executed the application closes without errorsthe strange thing is that everything works normally on my galaxy nexus 422 but does not work in my friends mobile android 403 nor in my emulator with android 21here is my codeprotected void oncreatebundle savedinstancestate actionbar getsupportactionbarmywebview webview findviewbyidridwebviewmywebviewgetsettingssetjavascriptenabledtruemywebviewaddjavascriptinterfacenew webappinterfacethis androidmywebviewloadurlgetstringrstringsite loadpublic class webappinterface sherlockactivity mactivitywebappinterfacesherlockactivity c mactivity c public void setrefreshon showrefresh true mactivitysupportinvalidateoptionsmenucan someone help me,['android'] +422843,file deletion with delete method in java i have a little doubt about following codetry file file new filewriting filecreatenewfile systemoutprintlnfiledelete systemoutprintlnfileexists printwriter pw new printwriterfile pwprint3242342 pwflush pwclose filereader fr new filereaderfile bufferedreader br new bufferedreaderfr systemoutprintlnbrreadline brclose catchioexception ioe systemoutprintlnindeedwhy in this circumstance the method filedelete apparently says that it works as it returns true when executed and it gets also confirmed by the fileexists method which returns false however at runtime i do not get any exception like ioexception the file writing does not exist or something likewisewhy does the file keep staying in the heap even though deleted physically should not it be automatically garbage collected as soon as the delete method gets called i know it does not because i saw the output,['java'] +422851,rails 32 asset pipeline and requirejs i am going to start a rich clientside web application with ruby on rails 32 i intended to use requirejs but it seems to collide with the asset pipeline as far as i know what the latter basically does is concatenating dependent assets minifiying and compressing them correct me if i am wrong which does not seem very compatible with loading javascript files asychronouslyat a first glance the asset pipeline seems to have much better performance however requirejs lets you organize the javascript code in modules easy to reuse and mange its dependenciesis there any way to combine both of them in case there is not which one would you choose,['ruby-on-rails'] +422871,javascript check if property defined what is the recommended way to check if an object property like objpropotherpropanother is definedifobj objprop objpropotherprop objpropotherpropanotherthis works well but enough ugly,['javascript'] +422872,how to cleanly verify if the user input is an integer in ruby i have a piece of code where i ask the user to input a number as an answer to my questioni can do to i but trickygarbage inputs would escape through to i for example if a user inputs 693iirum5 as an answer then to i would strip it to 693please suggest a function not a regular expressionthanks in advance for replying,['ruby'] +422873,changing the application and taskbar icon pythontkinter i have been working on a very simple pythontkinter script a pyw file and i would like to change it is application icon the file icon shown at the explorer window and the startall programs window for example not the file type icon nor the main window of the app icon and the taskbar icon the icon shown at the taskbar when the application is minimized is it possible to change them or is it something only doable when you effectively install an application through an exethis little app is supposed to run on windows xp 7 machines only and it is in python 273thanks in advance,['python'] +422876,stack foreach wrong order when using javas foreach syntax stack does not use lifo ordering on the outputted elements consider the following codeimport javautilqueueimport javautilstackimport javautillinkedlistpublic class queuestacktest private static int numbers 1 2 3 4 5 public static void mainstring args stackinteger s new stackinteger queueinteger l new linkedlistinteger for int i numbers spushi lofferi systemoutprintlnstack forinteger i s systemoutprintlni systemoutprintln systemoutprintlnqueue forinteger i l systemoutprintlni outputstack 12345queue12345questionsdoes this make sense is it a bugcan i guarantee that this will at least return queue elements in the correct orderwhen consuming processing a stack or a queue is this the best way to do it or should i make a more manual loop with something like whilesisempty handlespop or whilelisempty handlelpoll,['java'] +422919,404 on controllers in external assemblies i am having trouble resolving 404 responses in my aspnet mvc 4 project it is built in vs2012 targeting 45i have precompiled views and controllers built into standalone dlls i am able to dynamically load the dlls and inspect them from my core project even invoke methods on them however it seems that the mvc framework is not aware of the controllers i am close here but there is something missingbackground on the controllers and viewscontrollers are built in a standalone mvc project and inherit from controller nothing too interesting going on there the views use razorgenerator and become classes that live in the project the output of the project is a dll which correctly contains the controllers and viewsthe dlls implement a specific interface well call it iplugin in a separate class not part of a controller in the libraryloading the dllsrunning as admin in visual studio i compile my app which is hosted under iis with the project built i drop a plugin dll into my plugins directory without debugging this becomes important later i open ie and navigate to the site note that at this point the app has been built but never run so startup events will fire everything here is still consistent if i recycle the app pooli have a startup class with two methods prestart and poststart and invoke the methods using webactivatorpreapplicationstartmethod and webactivatorpostapplicationstartmethod respectivelyprestart is where i do the followingget a list of all the plugin dlls in my plugins directorycopy all plugins to appdomaincurrentdomaindynamicdirectoryload the typeif it contains an iplugin i thenadd the assembly to the buildmanagercall some of the methods on the class that implements ipluginin poststart i do this bit of code based on code from razorgeneratormvcforeach var assembly in modulesselectmmvalue var engine new precompiledmvcengineassembly usephysicalviewsifnewer httpcontextcurrentrequestislocal viewenginesenginesinsert0 engine virtualpathfactorymanagerregistervirtualpathfactoryenginemodules in this context is a keyvalue pair where the values are the loaded assemblies the purpose of this code is to make sure that mvc is aware of the views by adding a view engine for each assembly that knows how to resolve the views this is part of razorgeneratorhow i know i am close but clearly lacking the cigariplugin defines a method called registerroutes where you guessed it routes are to be registered for those who implement the interface i call this method in prestart and routes are added i have verified that these exist in my route table for instance on a route defined in my plugin created through dynamic invocation of the method during the prestart i see something like this as a datatoken when examining my routes namespaces pluginnamecontrollersso the route is registered the assembly is loaded i have verified that the dll is correctly copied to the dynamicdirectory of the appdomain i am able to invoke members of classes that are loaded dynamically at runtime but when i navigate to the url that is matched by the route i get a 404 this is not a could not locate view ysod it is more akin to not finding the controller at allhere is the part that confuses the heck out of me if at this point without doing anything i return to visual studio and hit f5everything worksit is like visual studio is becoming aware of the controller in some way that i cannot identify and the mvc framework is picking up on itfinally a questionwhat am i missing and how do i get the mvc framework to be aware of my controllerand hey at this point if youre still reading this thanks,['.net'] +422920,allegro 5 crashs on calling al clear to colorallegro color i am starting at allegro 5 but soon i got stucked in the second helloworldlike program i am coding after some debugging i concluded that the program crashs when it calls the function al clear to colorallegro color i have tried linking allegro statically and dynamically but the problem still remains i am completely losthere is the codeinclude cstdioinclude allegro5allegrohint main allegro thisplay thisplay allegro keyboard state kbstate ifal init return 0 ifal install keyboard return 0 thisplay al create thisplay800 600 ifthisplay return 0 do al get keyboard statekbstate al clear to coloral map rgb255 255 255 al flip thisplay al rest05 whileal key downkbstate allegro key escape al destroy thisplaythisplay return 0editsubstituting the lineal clear to coloral map rgb255 255 255for the lineal clear to colortempclearcolordeclaratingallegro color tempclearcolor al map rgb255 255 255before de loop starts it does work but crashs when the functional destroy thisplaythisplayis calledthe debugger returns the messages error while reading shared library symbols for cprogram files x86codeblocksmingwbinlibstdc6dll program received signal sigsegv segmentation fault,"['c++', 'c']" +422941,grouping sql results based on order i have table with data something like thisid rownumber data1 1 data2 2 data3 3 data4 1 data5 2 data6 1 data7 2 data8 3 data9 4 datai want to group each set of rownumbers so that my result is something like thisid rownumber group data1 1 a data2 2 a data3 3 a data4 1 b data5 2 b data6 1 c data7 2 c data8 3 c data9 4 c datathe only way i know where each group starts and stops is when the rownumber starts over how can i accomplish this it also needs to be fairly efficient since the table i need to do this on has 52 million rows additional infoid is truly sequential but rownumber may not be i think rownumber will always begin with 1 but for example the rownumbers for group1 could be 112234 and for group2 they could be 1246 etc,['sql'] +422985,is it possible to access resources from a different project using the designer in winforms i have got a rather large solution with many projects in it ideally i would like to create a resources project that contains all the embedded icons i need throughout my applicationi have read articles where people are referencing them through code but is it possible to get access to this projects resources in the designer in other words i would like to select the resources when clicking on the backgroundimage property of a form in the designerif not what sort of architecture should i consider when trying to decouple my resources from my main project it is probably not a smart idea to release a 100mb executable everytime i modify a line of code or two,['c#'] +422996,is vagrant useful for javajavaee developers when working with javajavaee usual development environment setup is to have everything locally jdk installation database appserver etc i know a lot of people in rubyjs world use virtual machines for development mainly with vagrant i wonder if there is an efficient way to set up similar env for javajavaeei suspect that i can easily install database server and application server together with jdk version on such virtual machine but what about regular development i still need to have jdk installed locally right i need my ide to work properly i need maven to build my project so that i need full maven local repo and then i need to deploy my app on virtual machines app serveri can see no real advantage here still having pieces of environment on both machinesdo you have any experience with that and can share with me,['java'] +423056,rails using websockets with nginx and unicorn i am considering implementing chess which needs websockets with rails and in production deployment using nginx as a reverse proxy to a bunch of unicorn processesin thinking about how to make that work led me to have the following questionsas far as i understand websockets are a persistent connection since everything goes through the reverse proxy nginx how exactly would a unicorn worker process maintain a websocket connection to a client browser would nginx maintain state about which unicorn process each browser websocket is connected to and act as a kind of intermediary does keeping a persistent websocket connection in a unicorn process block the entire worker processis there a recommended way to implementing chess with websockets using rails,['ruby-on-rails'] +423124,cannot start server bind on tcpip port cannot assign requested address i rebooted my server yesterday unfortunately mysql cannot be started nowthe error log is as followingrootsitediggervarlogmysql cat errorlog 130216 161132 note plugin federated is thisabled130216 161132 innodb initializing buffer pool size 80m130216 161132 innodb completed initialization of buffer pool130216 161133 innodb started log sequence number 0 1382359817130216 161133 error cannot start server bind on tcpip port cannot assign requested address130216 161133 error do you already have another mysqld server running on port 3306 130216 161133 error aborting130216 161133 innodb starting shutdown130216 161138 innodb shutdown completed log sequence number 0 1382359817130216 161138 note usrsbinmysqld shutdown completei checked and did not find any program is using 3306 please see followingrootsitediggervarlogmysql sudo netstatactive internet connections wo serversproto recvq sendq local address foreign address state tcp 0 0 sitediggercom59367 li56652memberslissh establishedtcp 0 0 sitediggercomssh 611505624865255 establishedtcp 0 216 sitediggercomssh 611505624861553 establishedtcp 0 0 sitediggercomw 182918526 time wait active unix domain sockets wo serversproto refcnt flags type state inode pathunix 2 dgram 600880492 unix 3 stream connected 600845962 unix 3 stream connected 600845961 unix 3 stream connected 600596531 unix 3 stream connected 600596530 i tried sudo mysql start but still not workingos ubuntu 10the results for netstat a t is as followingrootsitediggervarlogmysql netstat a tactive internet connections servers and establishedproto recvq sendq local address foreign address state tcp 0 0 w listen tcp 0 0 ssh listen tcp 0 0 https listen tcp 0 20824 sitediggercom59367 li56652memberslissh establishedtcp 0 0 sitediggercomssh 611505624865255 establishedtcp 0 52 sitediggercomssh 611505624861553 establishedtcp 0 0 sitediggercomw crawl6624973245760 time wait tcp 0 0 sitediggercomw 2183010314649094 time wait tcp6 0 0 ssh listen,['mysql'] +423125,how to show markers all the time by asynctask or handler in google map version 2 the final thing i am doing is i have the google map in my application with som buttons and extra stuffs but i also have to show the updated location of a marker all the timeinside my map i will get the data from external device not gps sensor of android phone so i thought using thread first but then changes to asynctask as you see in my code and tried to use addmarker method there but every time i run it map just stopps workingi want to just show one marker on map now but now successfulthe googlemap map cannot be reachable via ui thread and inside asynctaskwhy anybody encountered thiswhat should i do to solve thisplz help package comexamplemapsversion2 all imports public class mainactivity extends activity static final latlng exmpoint new latlng5933143818064957 public static googlemap map button button button waypointbutton button destinationbutton marker waypoint textview positiontext int countclick 3 public static datamodel autoboxdata new datamodel public static bitmap arrowbitmap marker currentplace mapfragment mapf override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main mapf mapfragment getfragmentmanagerfindfragmentbyidridmap map mapfgetmap mapsetmaptypegooglemapmap type hybrid positiontext textview findviewbyidridposition move the camera instantly to hamburg with a zoom of 15 mapmovecameracameraupdatefactorynewlatlngzoomexmpoint15 zoom in animating the camera mapanimatecameracameraupdatefactoryzoomto6 20 null addlisteneronbutton mapsetonmarkerdraglistenerthis new positionupdate1execute override public boolean oncreateoptionsmenumenu menu getmenuinflaterinflatermenuactivity main menu return true public void addlisteneronbutton destinationbutton button findviewbyidriddestinationb destinationbuttonsetonclicklistenernew onclicklistener override public void onclickview arg0 do something public class positionupdate1 extends asynctaskvoid void void override protected void doinbackgroundvoidarg0 todo autogenerated method stub mapaddmarkernew markeroptions positionhereiam systemoutprintlnhej return null here is the logcat0217 185717805 eandroidruntime9905 fatal exception main0217 185717805 eandroidruntime9905 javalangruntimeexception unable to start activity componentinfocomexamplemapsv2comexamplemapsv2mainactivity javalangnullpointerexception0217 185717805 eandroidruntime9905 at androidappactivitythreadperformlaunchactivityactivitythreadjava210217 185717805 eandroidruntime9905 at androidappactivitythreadhandlelaunchactivityactivitythreadjava21250217 185717805 eandroidruntime9905 at androidappactivitythreadaccess600activitythreadjava1400217 185717805 eandroidruntime9905 at androidappactivitythreadhhandlemessageactivitythreadjava12270217 185717805 eandroidruntime9905 at androidoshandlerthispatchmessagehandlerjava990217 185717805 eandroidruntime9905 at androidoslooperlooplooperjava1370217 185717805 eandroidruntime9905 at androidappactivitythreadmainactivitythreadjava48980217 185717805 eandroidruntime9905 at javalangreflectmethodinvokenativenative method0217 185717805 eandroidruntime9905 at javalangreflectmethodinvokemethodjava5110217 185717805 eandroidruntime9905 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava10060217 185717805 eandroidruntime9905 at comandroidinternaloszygoteinitmainzygoteinitjava7730217 185717805 eandroidruntime9905 at dalviksystemnativestartmainnative method0217 185717805 eandroidruntime9905 caused by javalangnullpointerexception0217 185717805 eandroidruntime9905 at comexamplemapsv2mainactivityoncreatemainactivityjava1400217 185717805 eandroidruntime9905 at androidappactivityperformcreateactivityjava52060217 185717805 eandroidruntime9905 at androidappinstrumentationcallactivityoncreateinstrumentationjava10830217 185717805 eandroidruntime9905 at androidappactivitythreadperformlaunchactivityactivitythreadjava20640217 185717805 eandroidruntime9905 11 more0217 185717935 eandroidosdebug2287 dumpstate dumpstate k t z d o datalogdumpstate app error,['android'] +423168,django rest framework django performance issue i am currently deploying django w djangorestframework on my ec2 small instance server to provide a set of apis for a couple of android appsthe problem is that i am facing a serious performance issue that i had to profile i found out that most of the time for a single request is spent inside drfs core sorry for making this a long post but i think i have to show everything so that i can get a proper answer for whats going on let me go aheadmy setup is nginx uwsgi heres how i am running uwsgi using upstartdescription pycmsstart on 2345stop on 06respawn start from virtualenv pathchdir wpythonappspycmsexec uwsgi b 250 chdirwpythonappspycms modulewsgiapplication env django settings modulesettings socket1270018081 processes5 harakiri20 maxrequests50 vacuum master pidfiletmppycmsmasterpid assuming i request the following apihttpip addressapinodesmostviewed9which matches the following ruleurlrnodesmostviewedpcategoryd mostviewednodeslistas view namemostviewednodeslistheres the classbased viewclass mostviewednodeslistgenericslistapiview api endpoint that lists featured nodes model objectstats serializer class nodeserializer permission classes permissionsallowany def get querysetself ifselfkwargshas keycategory category id selfkwargsgetcategory return objectstatsget most viewedcategory id else return the serializer classclass nodeserializerserializersmodelserializer images imageserializer favorite objectfieldsourceis favorite rating objectfieldsourceget rating meta objectfieldsourceget meta url objectfieldsourceget absolute url channel title objectfieldsourcechannel title class meta model node fields id title body images parent type rating meta favorite url channel titleand finally the classmethod get most viewed i know it is wrong to use classmethods rather than manager methodclassmethod def get most viewedcls category id return listnodeobjectsextra whereobjectsidcontent api objectviewsstatsnode id content api objectviewsstatsterm ids paramscategory id tablescontent api objectviewsstats order bycontent api objectviewsstatsnum views prefetch relatedimages objectmeta setselect relatedparent parentas you can see from all this it is a normal request the is redirected to the designated view fetching data from mysql and then returning the serialized result nothing out of the ordinary or any complex processingexecutingab c 500 n 50 httpip hereapinodesmostviewed9notice that this is without caching the following is frequently loggedharakiri uwsgi worker 5 pid 31015 was managing request apinodesmostviewed9 since sat feb 16 130721 2013 damn worker 2 pid 31006 died killed by signal 9 trying respawn respawned uwsgi worker 2 new pid 31040load average during testing goes up to 5 and heres the ab resultconcurrency level 500time taken for tests 251810 secondscomplete requests 1969failed requests 1771 connect 0 receive 0 length 1771 exceptions 0write errors 0non2xx responses 1967total transferred 702612 byteshtml transferred 396412 bytesrequests per second 782 sec meantime per request 63943511 ms meantime per request 127887 ms mean across all concurrent requeststransfer rate 272 kbytessec receivedfirst of all 7 requests per second is very thisappointing 1700 failed requests due to timeout errors is also because of the performance lag i am facing hereto be completely honest i am expecting 60 70 requests per second without caching i know that caching speeds up the process but it also hides the performance issues i have which is why i am pursuing to solve this before i cache stuffi decided then to profile this on a vmware centos machine using djangoprofiling which by adding prof to the request shows call stackinstance wide ram usagepartition of a set of 373497 objects total size 65340232 bytes index count size cumulative kind class dict of class 0 2270 1 7609040 12 7609040 12 dict of djangodbmodelssqlqueryquery 1 19503 5 6263400 10 13872440 21 dict no owner 2 63952 17 5739672 9 19612112 30 str 3 51413 14 5090344 8 24702456 38 list 4 58435 16 4991160 8 29693616 45 tuple 5 24518 7 4434112 7 34127728 52 unicode 6 8517 2 2384760 4 36512488 56 dict of djangodbmodelsbasemodelstate 7 2270 1 2378960 4 38891448 60 dict of djangodbmodelsqueryqueryset 8 2268 1 2376864 4 41268312 63 dict of 0x14d6920 9 6998 2 2088304 3 43356616 66 djangoutilsdatastructuressorteddict619 more rows type eg more to viewcpu time for this request 663425 function calls 618735 primitive calls in 2037 cpu seconds ordered by cumulative time ncalls tottime percall cumtime percall filenamelinenofunction 1 0 0 2037 2037 usrlibpython26sitepackagesdjangoviewsgenericbasepy44view 1 0 0 2037 2037 usrlibpython26sitepackagesdjangoviewsdecoratorscsrfpy76wrapped view 1 0 0 2037 2037 usrlibpython26sitepackagesrest frameworkviewspy359thispatch 1 0 0 2036 2036 usrlibpython26sitepackagesrest frameworkgenericspy144get 1 0 0 2036 2036 usrlibpython26sitepackagesrest frameworkmixinspy46list 1 0 0 2029 2029 appscontent apiviewspy504get queryset 1 0 0 2029 2029 appsobjects statsmodelspy11get most viewed 2321 0 0 2028 0097 usrlibpython26sitepackagesdjangodbmodelsquerypy92 iter 42 03 01 2028 1014 usrlibpython26sitepackagesdjangodbmodelsquerypy77 len 1 0 0 1645 1645 usrlibpython26sitepackagesdjangodbmodelsquerypy568 prefetch related objects 1 02 02 1645 1645 usrlibpython26sitepackagesdjangodbmodelsquerypy1596prefetch related objects 2 0024 0012 1643 0822 usrlibpython26sitepackagesdjangodbmodelsquerypy1748prefetch one level 2288 07 0 1156 01 usrlibpython26sitepackagesdjangodbmodelsmanagerpy115all 6252 0019 0 0762 0 usrlibpython26sitepackagesdjangodbmodelsquerypy231iterator 4544 0025 0 0727 0 usrlibpython26sitepackagesdjangodbmodelsquerypy870 clone 4544 0109 0 0694 0 usrlibpython26sitepackagesdjangodbmodelssqlquerypy235clone 2270 04 0 0619 0 usrlibpython26sitepackagesdjangodbmodelsquerypy619filter 2270 0013 0 0615 0 usrlibpython26sitepackagesdjangodbmodelsquerypy633 filter or exclude 1144 0019 0 0581 01 usrlibpython26sitepackagesdjangodbmodelsfieldsrelatedpy456get query set 1144 0019 0 0568 0 usrlibpython26sitepackagesdjangodbmodelsfieldsrelatedpy560get query set5591718180 0192 0 0500 0 usrlib64python26copypy144deepcopy 2270 03 0 0401 0 usrlibpython26sitepackagesdjangodbmodelsquerypy820usingand as you can see most of the time is spent on django views drf views can someone point out if i am doing anything wrong here why are requests so slow does python django scale i read that it does but how many requests second should i expect on a simple db read rendering operation such as the one i am doing,['python'] +423185,how to play or resume music of another music player from my code in my android app i want to play or resume the played music after a paused iti got my app to pause the music by sending a broadcast but i cannot get it to play or resume the musichere is the code to pause intent i new intentcomandroidmusicmusicservicecommand iputextracommand pause sendbroadcastihow can it be doneedit sorry i wrote resume instead of pause,['android'] +423186,alternate method for sethours of javautildate what is an alternate method for sethours of javautildate as it is deprecated to my date variable i want to set certain hours but i do not want to use the deprecated method sethours,['java'] +423295,python how to thistinguish between socket error and timeout i am having the following codetry while 1 ssocketsocketsocketaf inetsocketsock stream ssettimeout5 sconnecthostport printbefore send timesleep10 ssendallget http11rnconnection keepalivernhost wgoogleltrnrn datasrecv52 printafter send sclose if stringfinddatahttp11 200 ok 1 printlost connection printdata timesleep2except keyboardinterrupt printctrl c occuredexcept socketerror printsocket error occured except sockettimeout printtimeout errori have commented the sendall function to test how recv generates timeout exceptionbut the problem is that i get socketerror exceptionif i change the last lines of code toexcept sockettimeout printtimeout errorexcept socketerror printsocket error occured then i get sockettimeout exceptionso what exception is really generated,['python'] +423304,for constructors how do i choose between variadictemplates vs stdinitializer list in the current state of c11 say gcc 472 how should i choose between using a variadictemplate or a stdinitializer list when i need a constructor that can take variable arguments,['c++'] +423315,css3 flickering in safari 6 on osx but this is not the flickeringtowhite issue this issue does not present on ios or on chrome so it is not a webkit related issue it seems to be specific to the latest safari 602 on os x 1082 and not fixed by 1083 preview build 12d65 which comes with safari 603 i shall test on lion 1075 with safari 602 shortly and will also be testing on preview build 12d68 as wellhere is a fiddle that makes the problem quite apparent if youve got a mac running ml you should see a significant difference between chrome and safari where safari flickers a lot as you move the mouse around basically the problem is that safari will intermittently draw the target transform being set from js for a single frame then continue the transition animation this causes a flicker but only if the transition was in the middle of going somewhere to begin with so the bug would not rear its ugly head for most non intensive use of css3 transition but if functionality or visual effects depend on it to smoothly interpolate to a target as my current project does this flicker is not pleasant i have looked at similar topics related to flickering and applied pretty much all combinations of styles to counteract flickering such as the webkitbackfacevisibility hidden forcing various parent elements to gain hardware acceleration webkittransformstyle preserve3d webkitperspective 10 and none of them unfortunately do anything to address this safarispecific problem of flickering that is flickering not to white or blank but flickering to the target transform for a single framehere in this branch you can see me set a bunch of styles that help with regular flickering but have no effect for me as this is not a webkit specific issue i am unsure where to go about posting a bug report it would be especially nice to get this in before 1083 release since i see this as a rather big issue remember this is the sort of thing that were depending on html5 to do well in order for it to really kill flash updates safari version 603 85362810 on mountain lion 1083 12d68 retina macbook pro 154 still suffers from this issuesafari on windows 517 does not suffer from this bugsafari version 602 75362617 on lion 1075 macbook air mid 2011 does not suffer from this bug,"['javascript', 'css']" +423341,how to write setuppy for this application structure i have written an application with python 27 the structure looks likekent tree myappmyapp foopy gui g1py g2py g3py init py icons apng epng logic init py l1 init py lapy lcpy l2 init py ldpy lfpy logic1py logic2py logic3py myapy resources xdata zdatanow i am about to write a setuppy to thistribute my application i am new to this after reading the py doc and doing some testing a few questions come uphow can i or should i package my root package myapp under libpythonsitepackage since in my py file i reference resourcesicons by relative path for example in foopy there could be iconsapng and in guig1py there could be iconsepng and so onhow can i package icons and resources directoryit seems that package data and data files would not copy the two directories to right placeis this the right waypackages package dir package data icons resourcesafter install my files will beusrlibpython27sitepackagesiconspngusrlibpython27sitepackagesresourcesdatausrlibpython27sitepackagesguiusrlibpython27sitepackageslogicis there problem of my application structureshould those resourcesiconswhatever files go to certain python package not under the project root so that in setuppy i can use package data to copy them to right place,['python'] +423362,thisplay mkmapviewannotations within a map views visible rect i am thisplaying an mkmapview inside a pathstyle parallax table view header to create the effect the mapview bounds is larger than the area visible to the user i need to set the map view region such that all the maps annotations are contained within the visible rect of mkmapview whats the best way to do thisedit for clarity heres a usecase the mapview size is 320 x 380 the visible area however is defined by the rect 00 200 3200 10 i need to set the region such that all the annotations appear in this rect within the mapview,['ios'] +423367,negative variables in less new to less i am attempting to center a div using the followingform block thisplay block position absolute width 800px height 500px width width height height top 50 left 50 marginleft width2 px margintop 250pxit seems like margintop is set correctly since it the dimensions are explicitly there but i cannot seem to take the negative of a variable no matter how hard i try ie width 1 width etc any ideas it may just be a silly mistake,['css'] +423386,how to get json array from file with getjson how could i get an array json of a json file with javascript and jqueryi was triyng with the next code with it doesnt workvar questions function getarray getjsonquestionsjson function json for var key in json if jsonhasownpropertykey var item jsonkey questionspush category itemcategory return questions this is the json file called questionsjsonbiology category cell question1 que1what is the cell option1 op1the cell is the basic structural and functional unit op2is a fictional supervillain in dragon ball answer1opt1 astronomy category mars question1 que1how many moons does mars option1 op15 op22 answer1opt2 i want to get an array with this format biologycategorycellquestion1,"['javascript', 'jquery']" +423403,create an access point with the nexus 7 whats the aimcreate an access point with an android device nexus 7 in my case the final purpose is to connect a wifly card to this created network and exchange data between these devices hardwarenexus 7 with the android version 422 rooted with the rom cyanogenmod 101wifly card arduino shield with the same layout as zigbee cards that use wifi the productsoftwarei understood that the android version 422 does not allow to create an access point the service is thisabled programmatically this is why i rooted my device with the rom from cyanogenmod this rom enable this service google has hidden some methods from the class wifimanager specifically the method setwifiapenabled this is why i use reflection to call methods on the code belowthe source code is massive focus on the method createaccesspoint i chose to put the whole source code to help people that want to know how i did all of this public class testaccesspoint extends activity static final string tag ap teststatic final string ssid awesome access pointstatic final string psk helloworldstring numberofclientsconnectedstring wifiapenablestring wifiapstatewificonfiguration wifiapconfigwifimanager wifimanagerwificonfiguration wificonfigurationbroadcastreceiver receiverbroadcastreceiver receiverwifithisabledtextview textviewoverrideprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutaccesspoint test textview textview findviewbyidridtextview wifimanager wifimanager getsystemservicecontextwifi service wificonfiguration new wificonfiguration ifwifimanageriswifienabled createaccesspoint else logdtag set wifi enable wifimanagersetwifienabledtrue receiverwifithisabled new broadcastreceiver override public void onreceivecontext context intent intent int wifistate intentgetintextrawifimanagerextra wifi state wifimanagerwifi state unknown if wifistate wifimanagerwifi state enabled logdtag wifi enable createaccesspoint registerreceiverreceiverwifithisabled new intentfilterwifimanagerwifi state changed action final handler mhandler new handler public void handlemessagemessage msg switch msgwhat case 1 textviewsettext wifiapenable n wifiapstate n nb of clients connected numberofclientsconnected n wifi ap configuration n wifiapconfigtostring n wifimanager connection info n wifimanagergetconnectioninfotostring dhcp state wifimanagergetdhcpinfotostring break thread thread new threadnew runnable boolean alive true override public void run whilealive try threadsleep10 catch interruptedexception e eprintstacktrace numberofclientsconnected numberofclientsconnected wifiapenable iswifiapenabled wifiapstate getwifiapstate wifiapconfig getwifiapconfiguration mhandlersendmessagemhandlerobtainmessage1 threadstartoverride public void ondestroy superondestroy ifreceiver null unregisterreceiverreceiver ifreceiverwifithisabled null unregisterreceiverreceiverwifithisabled protected void createaccesspoint check if the wifi configuration already exists listwificonfiguration list wifimanagergetconfigurednetworks int networkid 1 iflist null forwificonfiguration conf list logdtag network id stringvalueofconfnetworkid network ssid confssid ifconfssidequalsid logdtag ssid found networkid confnetworkid wificonfiguration conf break else logdtag list of wificonfiguration is null if the configuration exists remove it to recreate it from scratch ifnetworkid 1 wifimanagerremovenetworknetworkid create a new wifi configuration wificonfigurationssid ssid wificonfigurationpresharedkey psk wificonfigurationhiddenssid false wificonfigurationstatus wificonfigurationstatusenabled wificonfigurationallowedauthalgorithmssetwificonfigurationauthalgorithmopen wificonfigurationallowedkeymanagementsetwificonfigurationkeymgmtwpa psk wificonfigurationallowedgroupcipherssetwificonfigurationgroupcipherccmp wificonfigurationallowedgroupcipherssetwificonfigurationgroupciphertkip wificonfigurationallowedpairwisecipherssetwificonfigurationpairwisecipherccmp wificonfigurationallowedpairwisecipherssetwificonfigurationpairwiseciphertkip wificonfigurationallowedprotocolssetwificonfigurationprotocolrsn catch enumeration ipassignment and proxysettings from wificonfiguration enum ipassignment catchenumipassignmentfromwificonfiguration enum proxysettings catchenumproxysettingsfromwificonfiguration set ip address gateway dns etc try logdtag try to set ip gateway and dns setipassignmentipassignment wificonfiguration logdtag ipassignment ok setproxysettingsproxysettings wificonfiguration logdtag proxysettings ok setipaddressinetaddressgetbyname1921682100 24 wificonfiguration logdtag ipaddress ok setgatewayinetaddressgetbyname19216821 wificonfiguration logdtag gateway ok setdnsinetaddressgetbyname19216821 wificonfiguration logdtag dns ok catchexception e eprintstacktrace add this new configuration to the wpa supplicant file networkid wifimanageraddnetworkwificonfiguration ifnetworkid 1 logdtag succeed to update the wifi configuration networkid else logdtag failed to update the wifi configuration save the new configuration on the wpa supplicant ifwifimanagersaveconfiguration logdtag succeed to save the wpa supplicant else logdtag failed to save the wpa supplicant set the wifi thisable to be able to start the access point logdtag set wifi thisable wifimanagersetwifienabledfalse receiver new broadcastreceiver override public void onreceivecontext context intent intent int wifistate intentgetintextrawifimanagerextra wifi state wifimanagerwifi state unknown if wifistate wifimanagerwifi state thisabled logdtag wifi thisabled when the wifi is thisable create the access point with the wifi configuration try method m wifimanagergetclassgetmethodsetwifiapenabled wificonfigurationclass booleanclass boolean succeed boolean minvokewifimanager wificonfiguration true ifsucceed logdtag succeed to set wifi ap else logdtag a problem occured while setting the wifi ap catch exception e logetag failed to set wifi ap e registerreceiverreceiver new intentfilterwifimanagerwifi state changed actionprotected string getwifiapstate try method m3 wifimanagergetclassgetmethodgetwifiapstate return wifi ap state stringvalueofm3invokewifimanager catch nosuchmethodexception e1 e1printstacktrace catch illegalargumentexception e eprintstacktrace catch illegalaccessexception e eprintstacktrace catch invocationtargetexception e eprintstacktrace return nullprotected wificonfiguration getwifiapconfiguration wificonfiguration wificonfiguration null try method m4 wifimanagergetclassgetmethodgetwifiapconfiguration wificonfiguration wificonfiguration m4invokewifimanager catch exception e eprintstacktrace return wificonfigurationprotected string iswifiapenabled try method m wifimanagergetclassgetmethodiswifiapenabled ifboolean minvokewifimanager return wifiap enabled else return wifiap not enabled catch exception e eprintstacktrace return nullprotected string numberofclientsconnected int maccount 0 bufferedreader br null try br new bufferedreadernew filereaderprocnetarp string line while line brreadline null string splitted linesplit if splitted null splittedlength 4 string mac splitted3 if macmatches maccount catch exception e eprintstacktrace finally try brclose catch ioexception e eprintstacktrace return stringvalueofmaccount suppresswarnings unchecked rawtypes protected enum catchenumipassignmentfromwificonfiguration enum dhcp null try classenum enumipassignment classenum classfornameandroidnetwifiwificonfigurationipassignment dhcp enumvalueofenumipassignment dhcp catch classnotfoundexception e eprintstacktrace return dhcpsuppresswarnings unchecked rawtypes protected enum catchenumproxysettingsfromwificonfiguration enum proxyset null try classenum enumproxysettings classenum classfornameandroidnetwifiwificonfigurationproxysettings proxyset enumvalueofenumproxysettings none catch classnotfoundexception e eprintstacktrace return proxysetpublic static void setipassignmentobject assign wificonfiguration wificonf throws securityexception illegalargumentexception nosuchfieldexception illegalaccessexception setenumfieldwificonf assign ipassignment public static void setproxysettingsobject assign wificonfiguration wificonf throws securityexception illegalargumentexception nosuchfieldexception illegalaccessexception setenumfieldwificonf assign proxysettings suppresswarnings rawtypes unchecked public static void setipaddressinetaddress addr int prefixlength wificonfiguration wificonf throws securityexception illegalargumentexception nosuchfieldexception illegalaccessexception nosuchmethodexception classnotfoundexception instantiationexception invocationtargetexception object linkproperties getfieldwificonf linkproperties iflinkproperties null return class laclass classfornameandroidnetlinkaddress constructor laconstructor laclassgetconstructornew classinetaddressclass intclass object linkaddress laconstructornewinstanceaddr prefixlength arraylist mlinkaddresses arraylistgetdeclaredfieldlinkproperties mlinkaddresses mlinkaddressesclear mlinkaddressesaddlinkaddress suppresswarnings rawtypes unchecked public static void setgatewayinetaddress gateway wificonfiguration wificonf throws securityexception illegalargumentexception nosuchfieldexception illegalaccessexception classnotfoundexception nosuchmethodexception instantiationexception invocationtargetexception object linkproperties getfieldwificonf linkproperties iflinkproperties nullreturn class routeinfoclass classfornameandroidnetrouteinfo constructor routeinfoconstructor routeinfoclassgetconstructornew classinetaddressclass object routeinfo routeinfoconstructornewinstancegateway arraylist mroutes arraylistgetdeclaredfieldlinkproperties mroutes mroutesclear mroutesaddrouteinfosuppresswarningsuncheckedpublic static void setdnsinetaddress dns wificonfiguration wificonf throws securityexception illegalargumentexception nosuchfieldexception illegalaccessexception object linkproperties getfieldwificonf linkproperties iflinkproperties nullreturn arraylistinetaddress mdnses arraylistinetaddressgetdeclaredfieldlinkproperties mdnses mdnsesclear mdnsesadns public static object getfieldobject obj string name throws securityexception nosuchfieldexception illegalargumentexception illegalaccessexception field f objgetclassgetfieldname object out fgetobj return outpublic static object getdeclaredfieldobject obj string name throws securityexception nosuchfieldexception illegalargumentexception illegalaccessexception field f objgetclassgetdeclaredfieldname fsetaccessibletrue object out fgetobj return out public static void setenumfieldobject obj object value string name throws securityexception nosuchfieldexception illegalargumentexception illegalaccessexception field f objgetclassgetfieldname fsetobj valuethis code works fine on my nexus 7 it creates an access point my laptop see the network link this it asks me to enter the wpa key i need to write it wrapped with quotes whether it does not work helloworldafter that my laptop is connected to the network but with the software xirrus i realized that the dhcp module does not give any ip address logsi get two interesting logs this one is when i start the application ehostapd configuration file datamiscwifihostapdconfehostapd ht ie 80211n in 11b mode is not allowed thisabling ht capabilitesihostapd rfkill cannot open rfkill control devicewhostapd wlan0 could not connect to kernel driverehostapd using interface wlan0 with hwaddr 021a11fd3258 and ssid awesome access pointehostapd random cannot read from devrandom try againihostapd random only 020 bytes of strong random data available from devrandomihostapd random allow operation to proceed based on internal entropyand this one is when i connect and thisconnect my laptop fromto the access point ihostapd wlan0 apstathisconnected 002710caf080ihostapd wlan0 apstaconnected 002710caf080questionsif you think that i am doing the wrong way could you tell me a better way do you know why i did not get ip address from the dhcp module do you know i could get more informationlogs from the dhcp modulethank you for your support,['android'] +423429,how to know when a backbone modelfetch completes i bind on the change event of my backbone models like thisthismodelon change thisrender this sometimes i want to fetch the latest version of the model and forcibly render the view so i do thisthismodelfetchunfortunately modelfetch only fires the change event if the new data is different from what was previously stored in the modelhow can i always trigger a thisrender callback when fetch completes whether it triggers a change event or notthanks in advance for your help,['javascript'] +423507,8 puzzle solvability and shortest solution i have built a 8 puzzle solver using breadth first search i would now want to modify the code to use heuristics i would be grateful if someone could answer the following two questionssolvabilityhow do we decide whether an 8 puzzle is solvable given a starting state and a goal state this is what wikipedia saysthe invariant is the parity of the permutation of all 16 squares plus the parity of the taxicab thistance number of rows plus number of columns of the empty square from the lower right cornerunfortunately i could not understand what that meant it was a bit complicated to understand can someone explain it in a simpler languageshortest solutiongiven a heuristic is it guaranteed to give the shortest solution using the a algorithm to be more specific will the first node in the open list always have a depth or the number of movements made so fat which is the minimum of the depths of all the nodes present in the open listshould the heuristic satisfy some condition for the above statement to be trueedit how is it that an admissible heuristic will always provide the optimal solution and how do we test whether a heuristic is admissiblei would be using the heuristics listed heremanhattan thistance linear conflict pattern database misplaced tilesnilssons sequence score nmaxswap xy tiles out of row and columnfor clarification from eyal schneider,['java'] +423582,whats the cost of calling a virtual function in a nonpolymorphic way i have a pure abstract base and two derived classesstruct b virtual void foo 0 struct d1 b void foo override cout d1foo endl struct d2 b void foo override cout d1foo endl does calling foo in point a cost the same as a call to a nonvirtual member function or is it more expensive than if d1 and d2 wouldnt have derived from bint main d1 d1 d2 d2 stdvectorb v d1 d2 d1foo d2foo point a polymorphism not necessary forauto i v ifoo polymorphism necessary return 0answer the answer of andy prowl is kind of the right answer i just wanted to add the assembly output of gcc tested in godbolt gcc47 o2 marchnative stdc11 the cost of the direct function calls ismov rdi rspcall d1foomov rdi rbpcall d2fooand for the polymorphic callsmov rdi qword ptr rbxmov rax qword ptr rdicall qword ptr raxmov rdi qword ptr rbx8mov rax qword ptr rdicall qword ptr raxhowever if the objects do not derive from b and you just perform the direct call gcc will inline the function callsmov esi offset flatlc0mov edi offset flatstdcoutcall stdbasic ostreamchar stdchar traitschar stdoperator stdchar traitschar stdbasic ostreamchar stdchar traitschar char constthis could enable further optimizations if d1 and d2 do not derive from b so i guess that no they are not equivalent at least for this version of gcc with these optimizations o3 produced a similar output without inlining is there something preventing the compiler from inlining in the case that d1 and d2 do derive from bfix use delegates aka reimplement virtual functions yourselfstruct dg delegate stdfunctionvoidvoid foo templateclass c dgc c foo voidcfoo and then create a vector of delegatesstdvectordg v d1 d2 this allows inlining if you access the methods in a nonpolymorphic way however i guess accessing the vector will be slower or at least as fast because stdfunction uses virtual functions for type erasure than just using virtual functions cannot test with godbolt yet,['c++'] +423589,exporting mysql database from xampp i need to send my website with the mysql database i have done the website and mysql database in xampp but donat know how to send the database,['mysql'] +423627,loading huge xml files and dealing with memoryerror i have a very large xml file 20gb to be exact and yes i need all of it when i attempt to load the file i receive this errorpython23358 malloc mmapsize140736680968192 failed error code12 error cannot allocate region set a breakpoint in malloc error break to debugtraceback most recent call last file filepy line 5 in module code xmlreadmemoryerrorthis is the current code i have to read the xml filefrom bs4 import beautifulsoupxml openpages fullxml rcode xmlreadxmlclosesoup beautifulsoupcodenow how would i go about to eliminating this error and be able to continue working on the script i would try splitting the file into separate files but as i do not know how that would affect beautifulsoup as well as the xml data i would rather not do thisthe xml data is a database dump from a wiki i volunteer on using it to import data from different timeperiods using the direct information from many pages,['python'] +423639,simple backup and restore for mysql database from java how to backup a mysql database from a java code such thatit is saving path is dynamically allocatedspaces in path do not create problemspath is generated using the executing jar filedbnamedbusername or dbpass are dynamically allottedcreating a specialized folder to save the backup file,"['java', 'mysql']" +423688,resuming interrupted radio stream using mpmovieplayercontroller i am developing an online radio app for ios6 devices ive looked for various wrappers to achieve this task avplayer mpmovieplayercontroller etc i tried using avplayer as it sounds more correct to use it for my purpose as it is audio only application but soon i came across this problem heretherefore i switched to mpmovieplayercontroller and this is what im trying to do pplayer mpmovieplayercontroller alloc initwithcontenturlnsurl urlwithstring pplayermoviesourcetype mpmoviesourcetypestreaming pplayerviewhidden yes avaudiosession sharedinstance setcategoryavaudiosessioncategoryplayback errornil avaudiosession sharedinstance setactiveyes errornil pplayer preparetoplay pplayer play pplayershouldautoplay yes nsnotificationcenter defaultcenter addobserverself selectorselectorstreamstatechanged namempmovieplayerloadstatedidchangenotification objectpplayerin my streamstatechanged method im doing nslogtrying to replaypplayer pausepplayer playpplayer is mpmovieplayer everything is fine except when there is an interrupt console spits out the following took background task assertion 1 for playback stall ending background task assertion 1 for playback stallthe number after assertion keeps increasing and then it recovers from it once the internet connection is stablemy question is is this approach correct am i doing something wrong along the way and is it ok to ignore that assert messageps please suggest if there is a better approach for developing radio streaming app using different api as opposed to mpmovieplayercontrollerthank you,"['ios', 'objective-c']" +423689,multiline java opts in setenvsh i am trying to setup my setenvsh on ubuntu 12tomcat 7tomcat has been installed with aptgeti have tried to create a multiline java opts variable but keep running into error messagesbinshexport java optsjava opts server xms512m xmx512m not foundtomcat7bincatalinash 4 usrsharetomcat7binsetenvsh using catalina base usrsharetomcat7using catalina home usrsharetomcat7using catalina tmpdir usrsharetomcat7tempusing jre home usrlibjvmjava7oracleusing classpath usrsharetomcat7binbootstrapjarusrsharetomcat7bintomcatjulijarerror could not find or load main classbinshexport java optsjava opts server xms512m xmx512m not foundtomcat7bincatalinash 3 usrsharetomcat7binsetenvsh using catalina base usrsharetomcat7using catalina home usrsharetomcat7using catalina tmpdir usrsharetomcat7tempusing jre home usrlibjvmjava7oracleusing classpath usrsharetomcat7binbootstrapjarusrsharetomcat7bintomcatjulijarinvalid maximum heap size xmx512merror could not create the java virtual machineerror a fatal exception has occurred program will exiti have updated it to this but at the echo location only the last line is thisplayedbinshjava optsjava opts server xms704m xmx704mjava optsjava opts xxonoutofmemoryerrorusrsharescriptson server crashshjava optsjava opts xxheapdumponoutofmemoryerror xxheapdumppathvarlogtomcat7java optsjava opts xxmaxpermsize128m xxmaxnewsize256m xxnewsize256mecho java optsjava optsjava opts xxsurvivorratio12 xxmaxtenuringthreshold0java optsjava opts xxuseconcmarksweepgc xxcmsincrementalmodejava optsjava opts xxcmsincrementalpacing xxcmsclassunloadingenabledjava optsjava opts xxcmspermgensweepingenabled xxthisableexplicitgcjava optsjava opts xxuseparnewgc xxusetlabjava optsjava opts djavaawtheadlesstruejava optsjava opts javaagentnr jar dnewrelicenvironmentproductionecho java optsexport java optswhen i try each command on its own line without the export option i get unrecognized option serverbinshjava optsjava opts serverjava optsjava opts xms704mjava optsjava opts xmx704mjava optsjava opts xxonoutofmemoryerrorusrsharescriptson server crashshjava optsjava opts xxheapdumponoutofmemoryerrorjava optsjava opts xxheapdumppathvarlogtomcat7java optsjava opts xxmaxpermsize128mjava optsjava opts xxmaxnewsize256mjava optsjava opts xxnewsize256mjava optsjava opts xxsurvivorratio12java optsjava opts xxmaxtenuringthreshold0java optsjava opts xxuseconcmarksweepgcjava optsjava opts xxcmsincrementalmodejava optsjava opts xxcmsincrementalpacingjava optsjava opts xxcmsclassunloadingenabledjava optsjava opts xxcmspermgensweepingenabledjava optsjava opts xxthisableexplicitgcjava optsjava opts xxuseparnewgcjava optsjava opts xxusetlabjava optsjava opts djavaawtheadlesstruejava optsjava opts javaagentnr jarjava optsjava opts dnewrelicenvironmentproductionecho java opts,['java'] +423712,java longparse binary string why does this code throw a numberformatexception string binstr 10systemoutprintlnbinstrlength 64systemoutprintlnlongparselongbinstr 2,['java'] +423729,java string concat vs stringbuilder optimised so what should i do in this answer it says implies that string concatenation is optimised into stringbuilder operations anyway so when i write my code is there any reason to write stringbuilder code in the source note that my use case is different from the ops question as i am concatenatingappending hundredsthousands of linesto make myself clearer i am wellaware about the differences of each it is just that i do not know if it is worth actually writing stringbuilder code because it is less readable and when its supposedly slower cousin the string class is converted automagically in the compilation process anyway,['java'] +423743,how to make a transparent jframe but keep everything else the same i want to make the jframe transparent but the image on top of it to be nontransparent this is what i have now does anyone know a way to make only the jframe transparentheres my codeimport javaxswingimport javaawtimport comsunawtawtutilitiesimport static javaawtgraphicsdevicewindowtranslucencypublic class splashdemo extends jframe public splashdemo setundecoratedtrue setsize200 200 addnew jlabelnew imageiconpuppy2png setdefaultcloseoperationwindowconstantsexit on close setvisibletrue setopacity085f public static void mainstring args new splashdemo,['java'] +423754,how can i fix the kerberos doublehop issue i am having some trouble calling a web service from within a web application and i was hoping someone here might be able to help from what i can tell this seems to have something to do with the kerberos doublehop issue however if it is i am not sure what to do to actually fix the problem to make things harder i do not have the proper permissions to make changes to active directory accounts so i need to know what to ask for when requesting changes in my situation i need to pass the credentials integrated windows authentication from a web application onto a backend web service so that the web service runs under the proper user context heres my exact issuethis worksthis does not workthe only difference between the working scenario and the nonworking scenario is that the working scenario is running the application on localhost whether a developers pc or on the server in question and the nonworking example is running on another machine the code between both scenarios is exactly the samewhat i have triedadding an spn to the domain account that runs the app pool for each server setspn a httpserver1 domainaccountdifferent methods of impersonationremoving the impersonation code using and executing the web service call as the app pool account this works as expecteddoes anyone have any idea on what i might be able to do in order to fix this problem,['asp.net'] +423756,so what does return 0 actually mean i am pretty proficient in php but i have started dabbling with c i have seen the codereturn 0at the end of functions that do not return a value this is not used in php because if a function is does not have a return a value null is automatically returned all i am asking is in simple english what does the return 0 actually do is it like php where it returns its argument as the value of the function call is it just good practicei know this question has been asked many times before but i am asking it from the point of view of a php developer the answers google throws up have not been that concise,['c'] +423763,how do get the full command line in ruby how do i get the full command line in ruby rails c 0 scriptrails argv ps eo pa grep sprocesspidstripsplit1 homesamrvmrubiesruby193p194perfbinruby scriptrails consoleis there anything cleaner than ninja ps i can do to get the same results to clarify in case there is confusion i want the exact same output as ps eo pa grep sprocesspidstripsplit1argv is coming back blank0 is missing the full path,['ruby'] +423771,passing double quote shell commands in python to subprocesspopen i have been trying to pass a command that works in shell that only works with literal double quotes in the commandline around the concatfile1file2 argument for ffmpeg i cant however make this work from python with subprocesspopen anyone have an idea how one passes quotes into subprocesspopen here is the codecommand ffmpeg i concat1ts2ts vcodec copy acodec copy tempmp4outputerror subprocesspopencommand universal newlinestruestdoutsubprocesspipestderrsubprocesspipecommunicatewhen i do this ffmpeg would not take it any other way other than quotes around the concat segement is there a way to successfully pass this line to subprocesspopen command,['python'] +423855,android gesture detection swipe updown on particular view i am trying to implement the ongesturelistener in android i have three textviews in my layout what i am trying to achieve is to set gesture listener for two of the textviews here is the layout relativelayout xmlnsandroidandroidididrlmainandroidlayout widthwrap contentandroidlayout heightwrap content textview androidididtvone androidlayout widthfill parent androidlayout heightwrap content androidlayout centerhorizontaltrue androidlayout marginbottom10dp androidlayout margintop5dp androidgravitycenter androidtextone textview androidididtvtwo androidlayout widthfill parent androidlayout heightwrap content androidlayout belowidtvone androidlayout centerhorizontaltrue androidlayout marginbottom10dp androidlayout margintop5dp androidgravitycenter androidtexttwo textview androidididtvthree androidlayout widthfill parent androidlayout heightwrap content androidlayout belowidtvtwo androidlayout centerhorizontaltrue androidlayout marginbottom10dp androidlayout margintop5dp androidgravitycenter androidtextthree and here is the activity import androidappactivityimport androidosbundleimport androidutillogimport androidviewgesturedetectorimport androidviewgesturedetectorongesturelistenerimport androidviewmotioneventpublic class timeactivity extends activity implements ongesturelistener gesturedetector gesturescannersuppresswarningsdeprecationoverridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutwheelview gesturescanner new gesturedetectorthisoverridepublic boolean ontoucheventmotionevent event todo autogenerated method stub return gesturescannerontoucheventeventoverridepublic boolean ondownmotionevent e todo autogenerated method stub return trueoverridepublic boolean onflingmotionevent e1 motionevent e2 float velocityx float velocityy todo autogenerated method stub logitest on fling return trueoverridepublic void onlongpressmotionevent e todo autogenerated method stuboverridepublic boolean onscrollmotionevent e1 motionevent e2 float thistancex float thistancey todo autogenerated method stub return falseoverridepublic void onshowpressmotionevent e todo autogenerated method stuboverridepublic boolean onsingletapupmotionevent e todo autogenerated method stub return falseat present fling for all the three textviews is getting called is there any way through which i can set the gesture listener for some particular views in the layoutany help will be highly appreciated,['android'] +423884,knockoutjs show hide block visibility pattern i have the code duplication problem in the next case on my page i have a lot of blocks that i need to show hide by clicking to linkdiv a databindclick showhiddenfirst visible isvisiblefirsthrefshow firsta div databindvisible isvisiblefirst stylethisplaynone hidden content first divdivdiv a databindclick showhiddensecond visible isvisiblesecondhrefshow seconda div databindvisible isvisiblesecond stylethisplaynone hidden content second divdivand my jsvar vm function thisisvisiblefirst koobservabletrue thisshowhiddenfirst function thisisvisiblefirstfalse thisisvisiblesecond koobservabletrue thisshowhiddensecond function thisisvisiblesecondfalse koapplybindingsnew vmhere is jsfiddle example question is how to avoid all this show visible duplication maybe i need some custom binding where i put id of my hidden block or smth else any patterns that you can suggest,['javascript'] +423894,how to combine two strings date and time to a single datetime i have two stringsstring one 130209string two 23510 pmi want to combine these two together and convert to a datetimei tried the following but it does not workdatetime dt converttodatetimeone twodatetime dt1 datetimeparseexactone two ddmmyy hhmmss tt cultureinfoinvariantculturewhat can i do to make this work,['c#'] +423905,datepicker how to popup datepicker when click on edittext i want to show datepicker popup window i have found some examples but i am not getting it properly i have one edittext and i want that when i click on edittext the datepicker dialog should popup and after setting the date the date should show in edittext in ddmmy format please provide me sample code or good links,['android'] +423914,convert mid file to any audio format as wav or mp3 file in android can anyone help me how to convert mid files into any audio format as wav or mp3 format by programmatically,['android'] +423950,androidsupportv4appgetfragmentmanager returns null this is my stacktracefatal exception mainjavalangnullpointerexceptionat comexampletestfragmentsloadingfragment1runloadingfragmentjava66at androidoshandlerhandlecallbackhandlerjava725at androidoshandlerthispatchmessagehandlerjava92at androidoslooperlooplooperjava137at androidappactivitythreadmainactivitythreadjava5041at javalangreflectmethodinvokenativenative methodat javalangreflectmethodinvokemethodjava511at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava793at comandroidinternaloszygoteinitmainzygoteinitjava560at dalviksystemnativestartmainnative methodline 66 of my fragmentfragmenttransaction ft fmbegintransactionfm is gotten like thisandroidsupportv4appfragmentmanager fm getfragmentmanagermy fragment extends androidsupportv4appfragment these are my importsimport androidosbundleimport androidsupportv4appfragmentimport androidsupportv4appfragmenttransactionimport androidviewlayoutinflaterimport androidviewviewimport androidviewviewgroupimport androidwidgettextviewi never had seen that i got null for a fragmentmanager anybody got an idea,['android'] +423964,cannot compile mongocdriver example i try to write simple mongo c client source file acinclude stdiohdefine mongo have stdintinclude mongohvoid mongo init cmongo con mongo initconint main return 0and i try to compile it withgcc iusrlocalinclude lusrlocallib lmongoc acbut get an erroractext0xd undefined reference to mongo initfiles usrlocalincludemongoh and usrlocalliblibmongocso existshow can i correctly compile acps mongo204 gcc46 mongocdriver pulled from githubupdate nm usrlocalliblibmongocso grep init034e0 t init0dd10 t bson init0c740 t bson init data0c7b0 t bson init finished data0dc10 t bson init size0d060 t bson iterator init0a5e0 t gridfile init09af0 t gridfile writer init095e0 t gridfs init010a18 r initialbuffersize05f40 t mongo cursor init08da0 t mongo env sock init05d90 t mongo init057b0 t mongo init sockets04800 t mongo md5 init05e40 t mongo replica set init05f00 t mongo replset init05b80 t mongo write concern init gcc iusrlocalinclude lusrlocallib wall werror lmongoc actmpcunep1o in function mongo init cactext0xd undefined reference to mongo init,['c'] +424032,how do i set params for wspost in play 21 java i am trying to perform a post with playapilibswsws but i cannot figure outhow to set the params my codepromiseresponse promise wsurlplayapplicationconfiguration getstringsmsserviceurlpostpost takes t body playapihttpwriteable wrt playapihttpcontenttypeof ctbut i do not understand how i should pass the params therethe documentation only statespromisewsresponse result wsurlhttplocalhost9001postcontenthow do i set the content eg param1foo and param2bar,['java'] +424053,how to avoid refreshing the page in a bootstrap modal here is the code for my modal in twitter bootstrapdiv classmodalbodyform classformhorizontal methodpost nameloginform idloginformdiv classcontrolgrouplabel classcontrollabel forinputemailemaillabeldiv classcontrols div classinputprepend span classaddoni classiconenvelopeispan input claspan2 idinputicon typetext nameemail divdivdivdiv classcontrolgrouplabel classcontrollabel forinputpasswordpasswordlabeldiv classcontrols div classinputprepend span classaddoni classiconlockispan input claspan2 idpassword typepassword namepassword divdivdivdiv classcontrolgroupdiv classcontrolslabel classcheckboxinput typecheckbox remember melabelformbutton typesubmit classbtn idsignin buttonsign inbuttondivdivwhenever i press the sign in button it reloads the page how can i possibly thisable refreshing the page upon clicking the button,['jquery'] +424069,get value from text area how to get value from the textarea field when it is not equal i tried this code but when i enter text into textarea the alert is not workshow to fix ittextarea nametextarea placeholderenter the texttextareadocumentreadyfunction if textareavalue alerttextareavalue,"['javascript', 'html']" +424074,boost shared from this and multiple inheritance i am currently having some troubles when using boost shared from this and multiple inheritancethe scenario can be described as followsclass a implements some functionality and should inherit from shared from thisclass b implements another functionality and should inherit from shared from thisclass d inherits functionalities from a and b class d public a public b when using some class b functionality from class d i got an exception weak ptrto inherit shared from this from class d is not an option for mei am not sure about how to solve thisoh i am using visual c 2010,['c++'] +424075,how to get the latest char written in textbox i want to know how to get the latest char written in textbox it does not mean the last of the stringfor instance i write this this i a testbut i forgot s so i move my finger to the i and i add the s this is a testso how can i get the s i want to get it in char or string but i do not know how to doi hope it is clear,['c#'] +424077,why subclass method is not called i have problem with subclassing and using methodsi create an instance of class b and store it as a pointer to a but when i use the pointer to call the overloaded method the output is a not b whythis works in other languages what am i doing wronginclude iostreamusing namespace stdclass a public void f cout a class b public a public void f cout b int main a a new b af return 0,['c++'] +424137,xml deserialization with servicestacktext i am learning servicestacktext library as it has some of the best featuresi am trying to deserialize xml into one of my dtos as belowc coderelevant code with console application hereclass program static void mainstring args string str webclient w new webclient string xml wdownloadstringstr response rss xmlfromxmlresponse foreach var item in rssrsschannelitem consolewritelineitemtitle consoleread you can go through the xml file at strgiven in the program i have prepared dtos for the deserialization they are as belowpublic class response public rss rss get set public class rss public string version get set public channelclass channel get set public class channelclass public string title get set public string ttl get set public string description get set public string link get set public string copyright get set public string language get set public string pubdate get set public listitemclass item get set public class itemclass public string title get set public string link get set public string description get set public string guid get set when i run the program i get an exception as shown belowso to change the element and the namespace i did following workaroundi put the datacontractattribute on my response class as belowdatacontractnamespace public class response public rss rss get set i changed the element name as below by adding following two lines just before deserializing to change rss element to response as in exception xml xmlreplacerss version20response for closing tag xml xmlreplacerssresponsebut it gave another exception on the foreach loop as the deserialized rss object was null so how should i deserialize it in a proper way using servicestacktextnote i know well how to deserialize with other libraries i want to do it with servicestack only,['c#'] +424176,static keyword inside array brackets i recently came across new use of static keywordwhat does static mean herevoid funint some arraystatic 7edit can someone give an example where this can be useful,['c'] +424224,overlapping pages with mmap map fixed due to some obscure reasons which are not relevant for this question i need to resort to use map fixed in order to obtain a page close to where the text section of libc lives in memorybefore reading mmap2 which i should had done in the first place i was expecting to get an error if i called mmap with map fixed and a base address overlapping an alreadymapped area however that is not the case for instance here is part of procmaps for certain process 7f729907f744c0 rxp 0 0805 654098 libx86 64linuxgnulibc215sowhich after making the following mmap call mmap0x7f731b0 getpagesize prot read prot write prot exec map anonymous map private map fixed 0 0 turns into7f729907f731b0 rxp 0 0805 654098 libx86 64linuxgnulibc215so7f731b07f731c0 rwxp 0 0 0 7f731c07f744c0 rxp 0830 0805 654098 libx86 64linuxgnulibc215sowhich means i have overwritten part of the virtual address space dedicated to libc with my own page clearly not what i want in the map fixed part of the mmap2 manual it clearly statesif the memory region specified by addr and len overlaps pages of any existing mappings then the overlapped part of the existing mappings will be thiscardedwhich explains what i am seeing but i have a couple of questionsis there a way to detect if something was already mapped to certain address without accesing procmapsis there a way to force mmap to fail in the case of finding overlapping pages,['c'] +424232,mediarecorderstop hangs on samsung galaxy camera calling stop on my mediarecorder hangs indefinitely on the samsung galaxy camera placing this call in a separate thread does not help the problem eitherlogcat does not show any error messages however running this same app does not incur any problems on the samsung galaxy nexus this is the code surrounding my call to stopviewonclicklistener capturelistener new viewonclicklistener override public void onclickview v if isrecording stop recording and release camera mmediarecorderstop releasemediarecorder release the mediarecorder object mcameralock take camera access back from mediarecorder inform the user that recording has stopped capturebuttonsettextcapture isrecording false else initialize video camera if preparevideorecorder camera is available and unlocked mediarecorder is prepared now you can start recording mmediarecorderstart inform the user that recording has started capturebuttonsettextstop isrecording true else prepare did not work release the camera releasemediarecorder inform user,['android'] +424277,sql server management studio show complete content of field varcharmax there is a way in sql server management studio to read all the contents of a varcharmax column when you run a selecti know that there is an option in options query execution set textsize but i was wondering if are something like when you have a xml file that you can click the cell and a new tab is open with the cell contents,['sql'] +424318,drawing outside a uiview i have a uiview where i would like to draw a circle that extends past the frame of the uiviewi have set the maskstobounds to no expecting that i can draw past outside the bounds of the uiview by 5 pixels on the right and bottomi expect the oval to not get clipped but it does get clipped and does not draw outside the bounds voiddrawrectcgrectrect int width selfboundssizewidth int height selfboundssizeheight selflayermaskstobounds no rounded rectangle drawing oval drawing uibezierpath ovalpath uibezierpath bezierpathwithovalinrect cgrectmake0 0 width5 height5 uicolor magentacolor setfill ovalpath fill uicolor blackcolor setstroke ovalpathlinewidth 1 ovalpath stroke,['ios'] +424340,c force stringformat to use decimals and never commas basically i am realizing that my application is using commas instead of decimals and i never want to allow this anyone know how i can correct i cannot find one thing via google that is to force decimals it is all about forcing commas return stringformat0f 1f 2f 3f 4f 5f 6f 7f 8f 9f 10f 11f 12f 13f 14f 15f mm11 mm12 mm13 mm14 mm21 mm22 mm23 mm24 mm31 mm32 mm33 mm34 moffsetx moffsety moffsetz mm44,['c#'] +424368,how can i specify an alternative directory for my handlebarsjs templates with the emberrails gem i have a rails application and i am using ember on the frontend i would like to move the emberrelated files down one level in the directory structure but when i do the templates no longer renderin the plain vanilla working version of the application my directory structure isapp assets javascripts applicationjs emberappjs routesjs storejs models controllers routes templates viewswith applicationjs require jquery require jquery ujs require handlebars require ember require emberdata require self require emberappapp emberapplicationcreateand emberappjs require store require tree models require tree controllers require tree views require tree helpers require tree templates require router require tree routeseverything works fine however i would like to move the emberapp file and all ember javascript code down one level and when i do so the templates do not render part of the application uses ember but not the entire application and i am trying to set up two separate paths through the asset pipelinethe desired structure isapp assets javascripts applicationjs embro emberappjs routesjs storejs models controllers routes templates viewswith applicationjs revised require emberapp becomes require embroemberapp require jquery require jquery ujs require handlebars require ember require emberdata require self require embroemberappapp emberapplicationcreateemberappjs is unrevisedas i said after the move none of the template content appears onscreen no errors onscreen or in the console just an empty emberapplicationwhen i examine embertemplates in the console all the expected templates are listed furthermore if i put the desired content in xhandlebars templates in the appropriate rails view the content successfully renders just as it did with the original directory structure for example in appsviewswelcomeindexhtmlscript typetextxhandlebars datatemplatenameapplication h1helloh1 outlet scriptscript typetextxhandlebars datatemplatenameindex h1this is the indexh1script and were good to go againbut if i leave the rails view empty as i did with the original structure it is a no gowondering if perhaps the emberrails gem requires the handlebars templates to be present in appassetsjavascriptstemplates and if there is a way to override this the documentation mentions adding a templates root option to the application configuration block and i am wondering if this is the key i have played around a bit no luck yetany ideasupdateafraid i am not having any luck with the templates root option as an experiment i tried building a new simple rails app and using the emberrails bootstrap generator to get it up and running alls well but if i then attempt to simply change the name of the templates folder ie appassetsjavascriptstemplates appassetsjavascriptstemple with appropriate changes to the sprockets includes and config files i am getting the same results any chance the templates root option is somehow brokeni am using ruby 193 rails 3211 emberrails 0100any pointers to where i should look in the ember emberrails handlebars source code have started poking aroundthanks,['ruby-on-rails'] +424385,strncmp in python i am parsing through a file with a list of paths i am trying to see if one path is under a specific directory or not so i have two strings s1 and s2 lets say they are s1 tmp and s2 tmpfiletxtif i want to check if is s2 has s1 and then some extra bytes in c i would do a strncmp of s1 and s2 upto strlens1 bytes is there a way to do that in python i am new to python and do not know all the modules available to me yet i could implement this trivially by just iterating over the characters in the strings and comparing but want to find out if there is anything that gives me these kind of helper functions by defaultthanks for any help p,['python'] +424400,how do i load my own library dynamically and invoke a method in it i would like to write some c code okay if it only works on linux to dynamically load a new shared library and then invoke a method from it to be determined at runtime it seems this is already possible because java can load native libraries dynamically and then invoke methods from themfor example i would like to do something likeint main libinfo t lib details load shared librarylibfooso run methodlib details bar 7this would invoke the method bar with argument 7 bar is a method compiled into libfoosouse case detailsi would like to compile a binary that loads all the shared libraries in a directory and runs some method from each in the memory context of the original program i would like to be able to quickly enable or thisable a shared library by addingremoving it from a directoryproof of conceptit seems this should be possible based on the way java manages to link with jni code dynamically you can use systemload and load the library of your choice coupled with compiling from memory it seems it would allow you to run an arbitrary function from an arbitrary library things i have triedi have looked at the manpage for uselib which seems useful but i am not sure what to do with the library once i have loaded ita bit of googling returned but this is not exactly what i need this project still requires a function pointer to make the function call i would be grateful for any pointer on where to look next even without a concrete answer thanks,['c'] +424402,android unit test case automation robolectric library vs android testing framework wondering which one is the better choice to write unit test cases for android apps and libraries using robolectric library or sticking with android testing framework i want to run test suite at commandline and want it be independent of need of configuring emulator or letting a device attached with build machine does anyone of you run a comparative analysis on both of these or something better your experiences will be great help me to decide on the better solution,['android'] +424413,gem install rails fails at binding of caller gem i am trying to get rails working and cannot get past a binding of caller gem that tries to install with the other gems after running sudo gem install rails i do not think the gem is required for rails to work but cannot figure out how to skip it or stop it from trying to install every time the list of gems gets to binding of callers i get the followinginstalling binding of callers 069 with native extensionsgeminstallerextensionbuilderror error failed to build gem native extensionsystemlibraryframeworksrubyframeworkversions18usrbinruby extconfrb creating makefilemakexcrun cc i isystemlibraryframeworksrubyframeworkversions18usrlibruby18universaldarwin120 isystemlibraryframeworksrubyframeworkversions18usrlibruby18universaldarwin120 i d xopen source d darwin c sourcea a a fnocommon arch i386 arch x86 64 g os pipe fnocommon denable dtracea a fnocommona a pipe fnocommona a o0 stdc99a a c binding of callercbinding of callerc410 fatal error vm coreh file not foundinclude vm coreha a a a a a a a a 1 error generatedmake binding of callero error 1gem files will remain installed in usersericavirtuebundlertmp54559gemsbinding of caller069 for inspectionresults logged to usersericavirtuebundlertmp54559gemsbinding of caller069extbinding of callergem makeoutan error occurred while installing binding of caller 069 and bundler cannot continuemake sure that gem install binding of caller v 069 succeeds before bundlingi am running osx 1082 and using pow web server with rbenv to manage ruby i am also running ruby 193p385,['ruby-on-rails'] +424427,convert unicode string dictionary into dictionary in python i have unicode ucode11code21 and i want it in dictionary formati want it in code11code21 formati tried unicodedatanormalizenfkd my dataencodeascignore but it returns string not dictionarycan anyone help me,['python'] +424432,how to get page title in magento any way to get the page title in magentoi have a script live personon this i need the current page title so can anybodey tell me how i get the current page title,['php'] +424441,why switch for enum accepts implicit conversion to 0 but no for any other integer there is anenum someenum a 0 b 1 c 2now compiler allows me to writesomeenum x someenumaswitchx case 0 considered someenuma break case someenumb break case someenumc break default break0 is considered someitemsa but i cannot writesomeenum x someenumaswitchx case 0 break case 1 here is a compilation error break case someenumc break default breakwhy only implicit conversion exists for 0,"['c#', '.net']" +424534,monitoring file changes c linux i am working with linux and i have a directory which has subdirectories and there are filesinside subdirectories i have to monitor the changes in the file in c i am using boost i go through all the directories every 30 seconds and check the last write time principally it works but every time this action is executed my cpu goes nuts and i see 1525 cpu usagejust for this program in top i have read about inotify if i use inotify would i have the more or less same cpu usage or would it be improved are there any good alternatives to what i am doing,['c++'] +424612,how to expire or reset geolocation when a user hits my website i check to see if i have a location session set in php if there is no session set with the users location in i redirect them to wdomainnetlocation on this page there are a number of options for the user to pick a location if the browser allows it one of the options is to use the browser to set this the below code works really well the issue i am having is that once a user has allowed the browser to share the location this seems to be set forever whilst the user is browsing they may decide to change their location so they then click a button to go to the wdomainnetlocation page again without anything popping up it automatically picks up the browsers location and redirects them there are other location options on the page including a clickable map i really need to be able to reset expire delete force something so that the browsers asks again if the user wants to use the browser to set the location or to allow the user to use one of the other optionsthe only thing i can think of is to move the actual javascript below onto another page and on the wdomainnetlocation page have another button that says something like use my precise location and that would then link to the js belowdoes anyone know of another way of resetting this or somethingscript typetextjavascript charsetutf8 function findlocation var options timeout 60 navigatorgeolocationgetcurrentpositionfoundlocation nolocation options function foundlocationposition var lat positioncoordslatitude var lng positioncoordslongitude alertfound location lat lng windowlocation lat lng lng function nolocation alertcould not find location windowlocation findlocation script,['javascript'] +424644,change the transactionscope isolationlevel after completing the transaction when i save data in the database i used transactionscope with isolationlevel set to serializabletransactionoptions options new transactionoptions isolationlevelisolationlevelserializable using var transaction new transactionscopetransactionscopeoptionrequiredoptions transationcompletenow after the execution is over i want to change the transactionscopeisolationlevel editwhat i understand is this if isolationlevel set to serializable then after completing the transaction the connection object is closed and return to connection pool and when some other request arrives it fetch that connection object from the pool and thus effected by the previous isolationlevel so i want to change isolation level to default after every transaction,['c#'] +424784,why do i have a lock here see the following concurrent performance analysis representing the work done by a parallel foreachinside the loop each thread reads data from the db and process it there are no locks between threads as each one process different data looks like there are periodic locks in all the thread of the foreach due to unknown reasons see the black vertical rectangles if you see the selected locked segment the dark red one you will see that the stack shows the thread locked at stockmodelquotation constructor the code there just constructs two empty listsi have read somewhere that this could be caused by the gc so i have changed the garbage collection to run in server mode withruntime gcserver enabledtrueruntimei got a small improvement about 10 15 faster but i still have the vertical locks everywhere i have also added to all the db queries the withnolock as i am only reading data without any differenceany hint on whats happening herethe computer where the analysis has been done has 8 coresedit after enabling microsoft symbol servers turns out that all threads are blocked on calls like wait gor gc done or waituntilgccomplete i thought that enabling gcserver i had one gc for each thread so i would avoid the vertical lock but seems that it is not the case am i wrongsecond question as the machine is not under memory pressure 5 of 8 gigs are used is there a way to delay the gc execution or to pause it until the parallel foreach ends or to configure it to fire less often,"['c#', '.net']" +424821,is there a python equivalent to highline highline is a ruby library for easing console input and output it provides methods that lets you request input and validate it is there something that provides functionality similar to it in pythonto show what highline does see the following examplerequire highlineimportinput askyes or no do q qresponsesnot valid answer y or and for yes or no qdefault y qvalidate aynziendit asks yes or no and lets the user input something as long as the user does not input y or and caseinsensitive it prints answer y or and for yes or no and lets the user type an answer again also if the user press enter it defaults to y finally when it is done the input is stored in input here is an example result where the user first input eh and then yyes or no y ehanswer y or and for yes or no yis there similarly simple way to do the same in python,"['python', 'ruby']" +424840,can visual studio 2010 prompt before rebuilding any way to have visual studio 2010 prompt before rebuilding or any other way to make it easier to avoid hitting rebuild instead of buildi have wasted countless hours when i right click on a project and select rebuild on accident when i meant to click buildthis is for a native c solution,['c++'] +424847,how to get all sections by name in the sectiongroup applicationsettings in net 20 heres the idea i had i want a small executable to have an appconfig file with multiple sections that are situated under the sectiongroup applicationsettings not appsettings i do not need to write to the file each section would have a name corresponding to a module that should be loaded if set heres an example configuration configsections sectiongroup nameapplicationsettings typesystemconfigurationapplicationsettingsgroup system version20 cultureneutral publickeytokenb77a5c561934e089 section nameexecutable typesystemconfigurationclientsettingssection system version20 cultureneutral publickeytokenb77a5c561934e089 requirepermissionfalse section namefirstmodule typesystemconfigurationclientsettingssection system version20 cultureneutral publickeytokenb77a5c561934e089 requirepermissionfalse sectiongroup configsections applicationsettings executable setting namemyfirstsetting serializeasstring valuemy awesome feature settingvalue setting executable firstmodule pathpath to the modules assembly setting nameimportantsettingtothemodule serializeasstring valuesome important stringvalue setting firstmodule applicationsettings configurationnow if i define the firstmodule section i want my application to load its assembly if the section is not defined the module should not be loaded this should be true for not only one module but a not yet defined number of themso i basically need to find out about the defined sections at runtime how would i do thatin addition i want this to become a portable executable it has to run on mono as well that is backwards compatible to net 20 it might be interesting to have a look at the project on github currently at this commit,['c#'] +424919,grape authorization i am attempting to create a restful json api in ruby so i am using grape inside of racki am not using rails for this project so cancan sorcery etc do not seem to be the best options plus i would hate to mix in a bunch of imperative logic into grapes declarative dslwhile grape has built in authentication support i do not see anything about authorization it seems like this would be a common enough use case that this road would have been traveled before but after some pretty thorough digging in google and the grape codebase itself i have turned up nothinghas anyone implemented something like this for their project in grape what did you use,['ruby'] +424944,how do i make a dll created with ikvm com visible i have seen a few posts on this but i have not seen any solutions so far i have a jar file that i am converting to a net dll via ikvm i am trying to figure out how to make the methods in the dll available inside the excel vba environment here are the details1 installed ikvm registered it is dlls to gac2 ran ikvm to create the a net dll mytestdllikvmc mytestjar3 registered the new dllregasm mytestdll4 from here i created a vbnet project and added mytestdll and ikvmopenjdkcoredll as references to the project i am then able to access the methods within the dll in net this is great5 what i really want to do is be able to use the dll in vba as well initially vba wouldnt accept the dll directly as it is a net library i attempted to create a type libraryregasm codebase tlb mytestdllthis created a tlb file which is nice but it did throw a warning about the library not being strongly named 6 then i loaded the tlb as a reference in my vba editor this works however when i try to access the methods nothing shows up similarly if i look in the object viewer for my library i can see my two classes but not the members of those classesadditionally i imagine that i probably also need to somehow reference the ikvmopenjdkcoredll inside vba as well however i cannot do that either since it is a net dllhas anyone had success converting a jar file into something that can be used with vba,"['java', '.net']" +424952,jquery change placeholder text color is it possible to use webkitinputplaceholder with jquery to set a color for the placeholder textsomething like thisinputwebkitinputplaceholdercsscolor b2cde0,['jquery'] +424974,transactions in mongodb i am using a nosql database mongodb with java and spring data i am aware that mongodb only supports transactions for a single documenti am using spring transactions to carry out mongodb transcations i am using transactiontemplate what should i set in transactionmanager when using transactiontemplateediti have something like thisbean idatxttemplatebeana classaorgspringframeworktransactionsupporttransactiontemplateaproperty nameatransactionmanagera refatxnmanagerbeanapropertyi need to define txnmanagerbean to point to something like datasourcetransactionmanager for a mongodb database,['java'] +425036,jquery click events firing multiple times i am attempting to write a video poker game in javascript as a way of getting the basics of it down and i have run into a problem where the jquery click event handlers are firing multiple timesthey are attached to buttons for placing a bet and it works fine for placing a bet on the first hand during a game firing only once but in betting for the second hand it fires the click event twice each time a bet or place bet button is pressed so twice the correct amount is bet for each press overall it follows this pattern for number of times the click event is fired when pressing a bet button oncewhere the ith term of the sequence is for the betting of the ith hand from the beginning of the game 1 2 4 7 11 16 22 29 37 46 which appears to be nn12 1 for whatever that is worthand i was not smart enough to figure that out i used oeis heres the function with the click event handlers that are acting up hopefully it is easy to understand let me know if not i want to get better at that as well the following function keeps track of bet buttons that are pressed until place button is pressed to place bet function pushingbetbuttons moneytextmoney left playermoney thisplays money player has left betclickfunction var amount 0 holds the amount of money the player bet on this click ifthisattrid bet1 the player just bet 1 amount 1 else ifthisattrid bet5 etc amount 5 else ifthisattrid bet25 amount 25 else ifthisattrid bet100 amount 100 else ifthisattrid bet500 amount 500 else ifthisattrid bet10 amount 10 ifplayermoney amount check whether the player has this much to bet playerbet amount add what was just bet by clicking that button to the total bet on this hand playermoney amount and of course subtract it from players current pot moneytextmoney left playermoney then rethisplay what the player has left else alertyou do not have amount to bet placeclickfunction ifplayerbet 0 player did not bet anything on this hand alertplease place a bet first else card paracssthisplay block now show the cards cardbindclick cardclicked and set up the event handler for the cards bet buttons paracssthisplay none hide the bet buttons and place bet button redrawcssthisplay block and reshow the button for redrawing the hand playerbet 0 reset the bet for betting on the next hand drawnewhand draw the cards please let me know if you have any ideas or suggestions or if the solution to my problem is similar to a solution to another problem on here i have looked at many similarly titled threads and had no luck in finding a solution that could work for me,"['javascript', 'jquery']" +425061,native code for java math class i was wondering if there is any way i could gain access to the native code for the math class more specifically i need to see the code for the sin method,['java'] +425063,fragment getarguments returns null i have a fragment which has a tabhost as the root layout as followsxml version10 encodingutf8tabhost xmlnsandroid androididandroididtabhost androidlayout widthfill parent androidlayout heightfill parent linearlayout androidorientationvertical androidlayout widthfill parent androidlayout heightfill parent tabwidget androididandroididtabs androidlayout widthfill parent androidlayout heightwrap content framelayout androididandroididtabcontent androidlayout widthfill parent androidlayout heightfill parent framelayout androidididtab 1 androidlayout widthfill parent androidlayout heightfill parent more framelayouts here each are placeholders for fragments framelayout linearlayouttabhostthe code to create update each fragment for the tab content is as followsprivate void updatetabstring tabid int placeholder fragmentmanager fm getfragmentmanager if fmfindfragmentbytagtabid null bundle arguments new bundle argumentsputintcurrent day mcurrenttab epgeventlistfragment fragment new epgeventlistfragment fragmentsetargumentsarguments fmbegintransaction replaceplaceholder new epgeventlistfragment tabid commit in the oncreate method of the epgeventlistfragment i then try to get the arguments bundle but i always get null doing the followingoverridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate bundle arguments getarguments if arguments null toastmaketextgetactivity arguments is null toastlength longshow else mcurrentday getargumentsgetintcurrent day 0 what am i missing here i also tried getarguments in onattach but i still got null i am new to using fragments so i am hoping there is a simple reason but i have not come up with anything when searching,['android'] +425086,how to pop fragment off backstack i have an activity a which calls fragment bf which calls fragment cf i want bf to be placed in the backstack when cf is called so that users can navigate back to it however if a specific button is pressed in cf i would like bf to be removed from the backstack is this possiblei see that there is a popbackstack function however i am a little confused on how this would work is it safe to use this function is there any possibility that an activity from a different application would be inserted after bf on the backstack also is there any way to alter the savedinstancestate of the fragment on the backstack sorry if this is a simple question i just cannot figure out how to do a robust test on the backstack using the emulatorthank you,['android'] +425135,what is binary compatibility i was reading effective java by joshua blochin item 17 use interfaces only to define types i came across the explanation where it is not advised to use interfaces for storing constants i am putting the explanation belowworse it represents a commitment if in a future release the class is modified so that itno longer needs to use the constants it still must implement the interface to ensure binarycompatibilitywhat does bianry compatibility mean herecan someone guide me with an example in java to show that code is binary compatible,['java'] +425248,is an executor meant to be reused is an executor object meant to be reused after a shutdown i mean if i call shutdown or shutdownnow after the executor is terminated should i do new to create a new thread pool or is it possible to somehow resetreuse the previously terminated executor and reuse it updateif i need to create new thread pool how can i understand that the previous has been stoppedeg the following public void startpool ifthreadpool null threadpoolisshutdown return threadpool executorsnewcachedthreadpool other stuff public void stoppool ifthreadpool null threadpoolshutdown will not work if i call stop and then start a new thread pool will not be created due to conditions what is the proper way to code this,['java'] +425250,apache php users requests hi my question is how the data flow works exactly in apache web server phpwhen user access to url localhostindexphp and in same time when another user access the same url i guess requests are executes one by one not multithreaded and the first user get response then other one the question is if somehow the first request stay in loop for long time like 1min the other users should wait the first request to finish then their requests to be finished in order to get response from apache web server phpif answer is yes other users should wait in queue can we make requests to be executed in parallel multithread in order to prevent waiting in queue,['php'] +425254,eclipse how to know on which workspace im working without clickingchanging main view currently working on 4 different branches in a projectfor each branch there is a different workspace in eclipseproblem is when i have multiple eclipses open on different workspace i have a hard time thistinguishing between them and understanding on which workspace currently viewing the paths are the same so the window name is the same on all branchesi can choose to do fileswitch workspaceother and it will shows the name of current workspace but im looking for a way for it to appear in my main thisplay windows so i do not need to do this action 100 times a day please advisethanks,['java'] +425300,why maven command mvn sonarsonar works without any plugin configuration in my pomxml i have a maven web project in my repo i am a maven noob but still i understand the fact that there are plugins which we need to configure only then we could run plugin specific commandsfactsi have a sonar server running on my local machine at port 90i have not added any sonar specific plugin in my pomxmlreferenceobservationbut still when i run mvn sonarsonar in my project from command line it works finematter of the fact is i have not configured sonar plugin in my pomxml even then from where the hell maven is picking up and understanding sonarsonar goalcommandquestion curiosityi do not want the working knowledge of sonar itself i want to know why mvn sonarsonar works without configuring a sonar plugin in my pomxmlwhy and how,['java'] +425324,converting special charactes such as aa14 and a back to their original latin alphbet counterparts in c i have been given an export from a mysql database that seems to have had it is encoding muddled somewhat over time and contains a mix of html char codes such as uuml and more problematic characters representing the same letters such as aa14 and a it is my task to to bring some consistency back to the file and get everything into the correct latin characters eg ao and a3an example of the sort of string i am dealing with is desinfektionslasungsta14cher fa14r flachenwhich should equate to50 tattoo desinfektionsl a sungst a14 cher f a14 r fl a chen 50 tattoo desinfektionsl a sungst a14 cher f a14 r fl a chenis there a method available in cnet 45 that would successfully reencode the likes of aa14 and a to utf8else what approach would be advisablealso is the paragraph character a in the above example string an actual paragraph character or part of some other character combinationi have created a lookup table in the case of needing to do find and replace which is below however i am unsure as to how complete it isaa a aa aa aa a aa ao aoa ae a a a a a a a a3 a3a a a ao aoa a,['c#'] +425331,reducing coupling between test cases i am trying to learn more about junit and tdd but i am running into some issues with coupling between test caseswhen i am writing a test case for a particular data types api say a dequet how can i limit the coupling between the test cases for instance if i were writing a test case for the method insertfirstt item it seems straightforward to assume that i should be able to assert two things after calling the method on a properly initialized objectthe size of the deque object should have increased by oneif i subsequently call the corresponding t removefirst method it should return a reference to the object i inserted with the initial call however this creates an undesirable coupling between at least two of my test cases where one test case passing depends on the correct implementation of another api method for instance in order for this test case to pass i would need a correct implementation for checking the number of items in the deque and also for removing items if my test for either of those methods was incorrect or incomplete for whatever reason then my test for the insertfirst method would automatically be suspect what are best practices for avoiding this scenario is my approach to writing test cases wrong in some way,['java'] +425373,which nosql implementation is most appropriate i am new to nosql and i am scratching my head trying to figure out the most appropriate nosql implementation for the application i am trying to buildmy java application needs to have an inmemory hashmap containing millions to billions of entries as it models a singlelayer neural network right now were using trove in order to be able to use primitives as keys and values to reduce the size of the map and increase the access speed the map is a map of maps where the outer maps keys are longs and the inner maps have longfloat keyvalues we need to be able to read the saved state from thisk to the map of maps when the application starts up the changes to the map of maps need also to be saved to thisk either continuously or according to some scheduled interval i was at first drawn towards orientdb because of their document and object dbs although i am still not sure at this point what would be better then i came across rethis which is a key value store and works with an inmemory dataset that can be dumped to thisk including masterslave replication however it does not look like the values of the map can be anything other than strings am i looking in the right places for a solution to my needs right now i like the inmemory and masterslave aspect of rethis but i like the objectdocument capabilities of orientdb as my data structures are more complicated than simple strings and being able to use trove with the primitive keyvalue types is very advantageous it would be better if reading was cheap and writing was expensive rather than the other way aroundthoughts,['java'] +425406,i need an immutable keyvalue structure that retains insertion order i want to find something like immutablelinkedhashmap in guava libraryi need to use an immutable keyvalue data structure with an insertion order so what should i use,['java'] +425475,connector style not being applied to jsplumb connector when created dynamically update 1here is my jsfiddlein this example i have connected first two div on dom loadin this line of codejsplumbjsplumbconnect source a target b anchors rightmiddle leftmiddle paintstyle strokestyle ff9696 linewidth 8 connector flowchart curviness 63 connectorstyle linewidth 3 strokestyle 5b9ada hoverpaintstyle strokestyle 2e2af8 linewidth 8 i am passing the connector style query i want to show the source and target endpoints as green and ping right now it is showing blueoriginali recently took over a development left incomplete by some other developer in the project we need to be able to draw connectors between 2 elements for that the original developer used jsplumb the library is working fine and producing results when i manually create a connector but now what i want to do is create a connector dynamically reading jsplumbs documentation i tried to do it but it is not producing the results that i wantthis is how it is when i create manually notice the color and the arrow at the target elementbut if i create it automatically i do not get this color and arrow this is the fiddle that i created for testing what i am doing is calling jsplumbconnect and passing the parametersjsplumbconnect source page1 target page2 anchors 106 05 0 1 006 05 0 0 endpoint dot radius 4 endpointstyle fillstyle 5b9ada setdragallowedwhenfull true paintstyle fillstyle 5b9ada linewidth 5 connector straight connectorstyle linewidth 3 strokestyle 5b9ada connectoroverlays arrow width 10 length 10 foldback 1 location 1 id arrow can anyone point out where is the mistakeregardsjehanzeb malik,['jquery'] +425492,using yeomanbrunch tools with a hybrid djangobackbone app i am building a hybrid web application with django on the back end and backbone on the front end the structure is as follows i generate all the html in django templates use requestis ajax to decide which templates to return and use backbone to pull in html as needed i do this because i want to support nonjavascript users anyway my question is this as my javascript code gets more complex i would like to be able to do the following things automatically asynchronous javascript loadingconcatenating and minifying css filesconcatenating and minifying javascript filesjslintingi am not too worried about image optimisation or package management is this possible with the setup i have currently it is a standard django appmedia js mainjs backbone code is in here plugins backbonejs underscorejs css maincss resultscss imgmyapp adminpy modelspy viewspytemplates myapp indexhtml references to all js and css files herei am not sure if i should be using yeoman or just grunt or brunch or if there is a simpler way whatever i use i am not sure if can just drop it into the js directory or if the location of the templates will complicate things currently i know how to use requirejs to load the js asynchronously but i do not know how to concatenate lint etc hence looking for a tool maybe i should just write a shell script,['javascript'] +425510,autofixture fails to createanonymous mvc controller the codeifixture fixture new fixturecustomizenew automoqcustomizationfixturecustomizeviewdatadictionaryc cwithoutx xmodelmetadatavar target fixturecreateanonymousmycontrollerthe exceptionsystemreflectiontargetinvocationexception systemreflectiontargetinvocationexception exception has been thrown by the target of an invocation systemnotimplementedexception the method or operation is not implementedmycontroller takes 3 parametersi have tried the fix described in the answer here but it wouldnt work,"['c#', '.net']" +425533,keep getting 404s for appletouchiconpng we keep getting 404s for the following two filesappletouchiconprecomposedpng 685 timesappletouchiconpng 523 timesi have been scouring my mobile website archive for the culprit to this 404 and there is no place in my code that is directing to appletouchiconpngperforming a find in folder in sublime text 2 provides zero results for appletouchiconsearching 100 files for appletouchicon0 matches across 0 fileswe are using the apple meta tags for webappsmeta nameapplemobilewebappcapable contentyesmeta nameapplemobilewebappstatusbarstyle contentblackwill usage of these meta tags cause an iphone to search for an appletouchicon by default we are not providing an icon but should we be we would really just like to remove this 404browsing apples developer documentation provided no hints that reinforce my theorythe plot thickens even further when we thiscovered this is happening on ios and android regardless of browser firefox safari chrome are all trying to find this appletouchiconi used html5 mobile boilerplate as a starter for my webapp which has a file called helperjs helperjs has this function inside of it which i removed from our code ios startup image helper mbpstartupimage function var portrait var landscape var pixelratio var head var link1 var link2 pixelratio windowdevicepixelratio head documentgetelementsbytagnamehead0 if navigatorplatform ipad portrait pixelratio 2 imgstartupstartuptabletportraitretinapng imgstartupstartuptabletportraitpng landscape pixelratio 2 imgstartupstartuptabletlandscaperetinapng imgstartupstartuptabletlandscapepng link1 documentcreateelementlink link1setattributerel appletouchstartupimage link1setattributemedia screen and orientation portrait link1setattributehref portrait headappendchildlink1 link2 documentcreateelementlink link2setattributerel appletouchstartupimage link2setattributemedia screen and orientation landscape link2setattributehref landscape headappendchildlink2 else portrait pixelratio 2 imgstartupstartupretinapng imgstartupstartuppng portrait screenheight 568 imgstartupstartupretina4inpng portrait link1 documentcreateelementlink link1setattributerel appletouchstartupimage link1setattributehref portrait headappendchildlink1 hack to fix letterboxed full screen web apps on 4 iphone ipod if navigatorplatform iphone ipod screenheight 568 if mbpviewportmeta mbpviewportmetacontent mbpviewportmetacontent replacebwidthss320b width3201 replacebwidthssdevicewidthb after removing this we still get 404s i am stumped any help is greatly appreciated,"['android', 'ios']" +425538,how do i select every other div class element using just css no js thank you kindly for your responses in advancei know how to do this using javascript and php but i am trying to learn howif it is possible to do this using just cssi have a container which holds many items each item has a picture and below it a div containing a description i want the background of the description to be different for every other itemis it possible to achieve this using just css if so how i have been fooling around with using the selectors itemnthchildoddbackgroundcolorreditem descriptionnthoftypeoddbackgroundcolororangei cannot seem to get it suggestions comments anything is appreciated thanks again friends below is some simplified sample code that demonstrates what i have going onstylecontainerwidth100 height100item floatleft width250px height700pxitem img width250px height250px floatleftdescription width250px height450px floatleft backgroundcolorbluedescriptionnthoftypeevenbackgroundcolorred heres the linestylehtml body div idcontainer div classitem item 1 img srcimagejpg div classdescription this and every odd number i want to be blue h1titleh1 h2sub titleh2 plorem ipsum dolor sit for adunp a hreflearn morea div div div classitem item 2 and so on img srcimagejpg div classdescription and this and every even number red h1titleh1 h2sub titleh2 plorem ipsum dolor sit for adunp a hreflearn morea div div div bodyhtml,"['html', 'css']" +425549,hibernate cache are objects returned by a cached query stored in l2 cache were using hibernate4 and ehcache in our project we mostly work on immutable objects so caching is a feature which fits nicely in our application while trying to enable query cache we ran into the following problemassuming we have the following entityentity tablename dogsimmutable cacheusage cacheconcurrencystrategyread onlyclass dog id column long id column string nameand the querycriteria criteria sessioncreatecriteriadogclasscriteriaaddrestrictionsinid idscriteriasetcacheabletruethe query cache timetolive is set to about 34 of the dog timetolive heres the scenario please correct me if i made a wrong assumptionthe first time the query is called assuming the cache is empty it is executed and the returned dog instances are stored in the second level cache also the dog ids are stored in the query cache the second time the query is called the dog ids are in the query cache and the dog objects are in the l2 cache everything works fine the query cache returns the ids and the dogs are fetched from l2when the query cache expires but the l2 cache is still valid the query reruns and caches the dog idsnow the l2 cache expires for the dog object and all objects are evicted from cache the query cache still has the ids cached so hibernate fetches the dog objects one by one which takes foreverthe 3rd point is bugging me the query cache got invalidated and reran on the database fetching the dog objects but the dog objects were not updated in the l2 cache it looks like the query only updated the dog ids in the query cache but not the l2 cacheis there a way to force the query to update also the l2 cache perhaps this scenario is to be handled differently,['java'] +425568,java clojure java i am trying to use clojure as a scripting language from a host java program the idea being that the end user will be able to write clojure scripting code that will call a domainspecific java api at runtime the host java program will evaluate the endusers clojure script which will in turn call the domain apis so i started with a deadsimple prototype to explore the terraindomainpackage aproblemdomainpublic class domain public domain public string defaultmsg return default public string passbackmsgstring s return s host java programend users clojure script hardcoded for simplicitystring script do import aproblemdomain domain defaultmsg domain systemoutprintlnrtvarclojurecore evalinvokertvarclojurecorereadstringinvokescriptcode snippet taken from hereso far so goodhowever i could not find a way to invoke the second method the one that requires an argument instead i resorted to dynamically generating the clojure script at runtime and replacing a placeholder with a literal that represents the result of calling the domain method passbackmsg obviously this is unsatisfactory and does not go very far what if i want to pass a javasqlconnection to my clojure script so how do i invoke the passbackmsg method from the host java programwhen i try the followingstring script ns foo import aproblemdomain domain defn numbertostring s passbackmsg domain s rtvarclojurecore evalinvokertvarclojurecorereadstringinvokescript lineasystemoutprintlnrtvarfoo numbertostringinvoke33 linebi getjavalangillegalstateexception cannot changeestablish root binding of ns with set on linea when i try without the ns and withrtvaruser numbertostringinvoke33user being a wild guess as i do not see a var method without a namespace argumenti get anjavalangillegalstateexception attempting to call unbound fn usernumbertostring on lineb,['java'] +425578,how to exclude certain properties from knockoutjs tojs i have the following modelvar model a one b two c threei bind various ui elements to these fields which works great however i convert the model back to a javascript object so i can save any changes to the servervar goingtoserver kotojsmodelgoingtoserver will include properties a b and c however let us say property c is a huge chunk of data that will never change i would like to avoid sending this back to the serveris there a way to make tojs only include a predefined set of fields when converting a model back to a javascript objectone thing i have been investigating is the knockout mapping plugin it has a setting called include which is documented as suchwhen converting your view model back to a js object by default the mapping plugin will only include properties that were part of your original view model except it will also include the knockoutgenerated destroy property even if it was not part of your original object however you can choose to customize this arrayhowever it appears this plugin does not work as documented as komappingtojs will still include a b and c even if i pass in an include array of a b i am guessing this feature is intended to include additional fields that were not in the original modelis there a way to exclude certain properties when converting a model back to a javascript object short of doing something hacky such as generating the object and manually removing the properties i do not want before sending to the server,['javascript'] +425583,pandas version of rbind in r you can combine two dataframes by sticking the columns of one onto the bottom of the columns of the other using rbind in pandas how do you accomplish the same thing it seems bizarrely difficult using append results in a horrible mess including nans and things for reasons i do not understand i am just trying to rbind two identical frames that look like thisedit i was creating the dataframes in a stupid way which was causing issues appendrbind to all intents and purposes 0 1 2 3 4 5 6 70 adnl 20130220 4374 44237 43650 44190 2775364 20130220 1847421 adml 20130220 12790 130 12720 12850 967730 20130220 1847422 agkl 20130220 17170 174900 17090 17390 834534 20130220 1847433 amecl 20130220 10300 1040 10240 10350 1972517 20130220 1847434 aall 20130220 19980 201450 194249 19510 36033 20130220 1847445 antol 20130220 10930 109700 10647899 10680 2183931 20130220 1847446 arml 20130220 9415 96510 9394250 9515001 2994652 20130220 184745but i am getting something horrible a la this 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 70 nan nan nan nan nan nan nan nan adnl 20130220 4374 44237 43650 44190 2775364 20130220 1847421 nan nan nan nan nan nan nan nan adml 20130220 12790 130 12720 12850 967730 20130220 1847422 nan nan nan nan nan nan nan nan agkl 20130220 17170 174900 17090 17390 834534 20130220 1847433 nan nan nan nan nan nan nan nan amecl 20130220 10300 1040 10240 10350 1972517 20130220 1847434 nan nan nan nan nan nan nan nan aall 20130220 19980 201450 194249 19510 36033 20130220 1847445 nan nan nan nan nan nan nan nan antol 20130220 10930 109700 10647899 10680 2183931 20130220 1847446 nan nan nan nan nan nan nan nan arml 20130220 9415 96510 9394250 9515001 2994652 20130220 1847450 nan nan nan nan nan nan nan nan adnl 20130220 4374 44237 43650 44190 2775364 20130220 1847421 nan nan nan nan nan nan nan nan adml 20130220 12790 130 12720 12850 967730 20130220 1847422 nan nan nan nan nan nan nan nan agkl 20130220 17170 174900 17090 17390 834534 20130220 1847433 nan nan nan nan nan nan nan nan and i do not understand why i am starting to miss r,['python'] +425588,how to interact between different controllers in angularjs simple example i have a player it is divided into 2 sections song section currently playing and playlist sectioni have 2 controllers actulally i am going to have 2 controllers that is why i am asking songctrl and plalistctrlbut how to interact between them for example when i start playing song i need also highlight it inside of playlist,['javascript'] +425598,android fast bitmap blur i have been searching the past three days for a builtin hardwareaccelerated way of bluring a bitmap with android i stumbled upon certain workarounds like shrinking the bitmap and scaling it up again but this method produced low quality results which were not suitable for my image recognition requirements i also read that implementing convolution with shaders or jni is a good way to go but i cannot believe that there is no builtin solution in the android framework for this very common purpose currently i have ended up with a selfwritten convolution implementation in java but it is awkwardly slow my question isis there really no builtin solution in the android frameworkin case there is none what is the most efficient way of accelerating the convolution with a still reasonable complexity of implementation and maintenance shall we use jni shaders or something completely different,['android'] +425599,howto use runnable in mono for android i am try to lern monodroid i try to rewrite java code to c and have some problem i do not understand howto use runnablethat is snipet of code in java that i coudnt translate to cpublic class runactivity extends activity implements onclicklistener private handler mhandler override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutrun mhandler new handler mhandlerpostdelayedmupdategeneration 10 private runnable mupdategeneration new runnable public void run madapternext mlifegridsetadaptermadapter mhandlerpostdelayedmupdategeneration 10 can you explain me how i must write this code and use runnable this runnable use for update gridview adapter and load data from adapter to gridview in background if i tried update adapter in main thread like thisc codemadapternextmlifegridadapter madapterthreadsleep10activity is stuckif i cannot use runnable how can i implement updating of adapter and gridview in new threadif i use c threading like thisthread th new threadnew threadstartmupdatgenerationthstartpublic void mupdategeneration madapternext mlifegridadapter madapter threadsleep10it generates an error systemnullreferenceexceptionthanks to all for any help ps sorry for my english,['c#'] +425602,javabean equivalent in python i am fairly new to using python as a oop i am coming from a java background how would you write a javabean equivalent in python basically i need a class that implements serializable has getters and setters private propertiesdummy constructorany inputs i am looking for a sample code,"['java', 'python']" +425607,why should i use rethis when i have postgresql as my database for django i have have a django app thats currently hosted up on amazons ec2 service i have two machines one with the django app and the other with my postgresql database so far it has been rock solid many sources claim i should implement rethis into my stack but what would be the purpose of implementing rethis with django and postgresql how can i implement rethis in my django code for example how can i use it with postgresql these are all the questions i have been trying to find answers to so i came here hoping to get answers from the biggest and the best i really appreciate any answers thank you,['python'] +425652,excess elements in struct initializer error with c11 uniform initialization i am surprised by the following compiler errortemplate typename tstruct a at t t t t t struct sint main as ssthe error is with clangtestcpp416 error excess elements in struct initializer at t t t testcpp1510 note in instantiation of member function asa requested here as ss gcc gives a similar errori would expect the expression t t to try to copy construct t from t since s has an implicitly generated copy constructor i wouldnt expect this to be a problemcould someone explain what is going on here,['c++'] +425658,get value in one column in spreadsheet using google apps script i want to get a string value to compare it later on with an if condition from only one column in spreadsheet using google apps scripti searched the internet and i found this link sorry if this sounds stupid i am new to google apps scripts spreadsheetvar values spreadsheetappgetactivesheetgetrange2 3 6 4getvalues i guess that must be helpful the only problem is that the column i want to get the values from is dynamic so how do i set the range of this column,['javascript'] +425666,tweetbot banner image pull down to zoom image tweetbot and kickstarter for ios uses a cool feature on user profiles that have a banner image if you pull down on the tableview the image zoomsi have it partially working using the following it changes the height of the image but strangely not the width voidscrollviewdidscrolluiscrollview scrollview uiimageview imageview uiimageview selftableviewtableheaderview cgfloat y scrollviewcontentoffsety imageviewframe cgrectmake0 scrollviewcontentoffsety selfcachedimageviewsizesizewidthy selfcachedimageviewsizesizeheighty nslog nsstringfromcgrectimageviewframedoes anyone know how to recreate this effect,"['ios', 'objective-c']" +425739,oracle create trigger error bad bind variable i at trying to create trigger with the following codecreate or replace trigger mytable trg before insert on mytable for each row begin select mytable seqnextval into newid from dual endi am getting errorerror252 pls049 bad bind variable newidany ideas thanks,['sql'] +425767,sql inner join more than two tables i can currently query the join of two tables on the equality of a foreignprimary key in the following way result mysql queryselect from table1 inner join table2 on table1primarykeytable2table1idi would like to extend this to multiple tables all with the same foreign keys i am trying the following code which is not returning anything can anyone point out what i am doing wrong result mysql queryselect from table1 inner join table2 inner join table3 on table1primarykeytable2table1idtable3table1id,['sql'] +425793,behavior of sizeof on variable length arrays c only my question is how exactly sizeof behaves when passed argument is a dynamic array variable length arraylet us consider an exampleint funint num of chars char name arrnum of chars 0 do something return sizeofname arrin this example it is obvious that return value is not a compile time constant because the size depends on run time value of num of chars a quote from c99 standard 6534the sizeof operator yields the size in bytes of its operand which may be an expression or the parenthesized name of a type the size is determined from the type of the operand the result is an integer if the type of the operand is a variable length array type the operand is evaluated otherwise the operand is not evaluated and the result is an integer constantwhat i can understand from the operand is evaluated is that when the argument passed for sizeof is a dynamic array variable length array sizeof behaves like a function and not as an operator is my understanding right,['c'] +425812,how to use runonuithread without getting cannot make a static reference to the non static method compiler error i have a main class clientplayer extends activity and a service lotteryserver extends service implements runnable when trying to use the runonuithread in the run method of this service i am getting compiler error of cannot make a static reference to the non static methodhow to fix this how i am using the code is shown here overridepublic void run i tried both clientplayerrunonuithread and lotteryserverrunonuithread both do not work clientplayerrunonuithreadnew runnable public void run toastmaketextgetapplicationcontext from inside thread toastlength shortshow end run method,['android'] +425894,how can i render html in validation message in aspnet mvc i am currently developing a registration page when user already exists i want to provide login and reset password links for user in error message for email field in controller i havehttppostpublic actionresult registerregistrationmodel registration ifuserexists const string errormessage user already exist you can a hrefaccountloginlogina modelstateaddmodelerroremail errormessage return viewregister registration but when i try to output this message in view i do not get what i expect i get html markup like plain text i have already triedusinghtmlbeginformdivhtmltextboxform memail htmlvalidationmessageform memail htmlrawhtmlvalidationmessageform memail string validationmessage htmlvalidationmessageform memailtostring htmlrawvalidationmessage string validationmessage htmlvalidationmessageform memailtohtmlstring htmlrawvalidationmessage string validationmessage htmlvalidationmessageform memailtostring new htmlstringvalidationmessage string validationmessage htmlvalidationmessageform memailtohtmlstring new htmlstringvalidationmessage string validationmessage htmlvalidationmessageform memailtostring new mvchtmlstringvalidationmessage string validationmessage htmlvalidationmessageform memailtohtmlstring new mvchtmlstringvalidationmessagediv,['c#'] +426081,how to generate a builder class i have developed in a library a custom javafxanimationtransition i want to provide the corresponding builder like the translatebuilder for the translate transformation as you can see in the translatebuilder javadoc the builder class is annotated by generatedvaluegenerated by javafxbuilderprocessorbuilderprocessor is it possible to use this processor if yes how,['java'] +426083,connecting to a protected wifi from python on linux i am creating a software for ubuntu linux that needs to connect to a wifi ap the wifi network is not predefined and can change several times during a single run of the software the user is the one who orders the change the idea is this given a set of ssids and their wpa or wep passphrases the software should be able to switch between the networks on the whim without the need to change any configuration files anywhere in the systemthe huge problem as it seems is to pass the passphrase to the connection heres what i have been operating with so farubuntu 1210 machine equipped with a wifi donglepython which runs the software and which will be used to request the connectionsconnman 079wpa supplicant v10dbusat first i thought it would be possible to pass the passphrase to connman through dbus but neither this version of connman nor 1 seem to expose any method for that then i found out that it is possible to dump a service ssidconf file to the varlibconnman directory contents of the file are very simple and look like thisservice ssidtypewifinamenetworkssidpassphraseheregoesthepassphraseonce this file is created connecting to the network requires a simple call to netconnmanserviceconnect method in appropriate service the problem is that connman would not parse the config file unless it is restarted this requires sudo privileges additional time and raises risk for all the what can go wrong now things to occur then i figured that passphrase could be somehow passed to the wpa supplicant dbus api but i failed to find anythinggoogle searches have failed me too it is as if no one ever tried to do this beforecommand sudo iwconfig wlan0 essid ssid key spassphrase results in a set failed on device wlan0 invalid argument error also it requires sudo which i would like to avoidi tried to figure out how the wpa gui program does its magic first of all i thiscovered that it also requires sudo and that it sends a bunch of commands directly to varrunwpa supplicantwlan0 replicating this behavior would be a last resort for me if i do not figure out anything simplierso the big question is this how to use python in order to connect to a wepwpa protected wifi networki am also wondering if using connman is a good approach here and if i should not revert to the network manager which is ubuntus default,['python'] +426090,loading cross domain html page with ajax i am trying to load a cross domain html page using ajax but unless the datatype is jsonp i cannot get a responsehowever using jsonp the browser is expecting a script mime type but is recieving texthtmlmy code for the request isajax type get url usernamedarties32012 passwordpssw0rd program2futilisateurs2fdarties320122fmondossier2fanalyse dcannee2012indv actionexecute datatype jsonpsuccess function data divajaxfield html data is there any way of avoiding using jsonp for the request i have already tried using the crossdomain parameter but it did not workif not is there any way of receiveing the html content in jsonp currently the console is saying unexpected in the jsonp replythanks in advance,"['javascript', 'jquery']" +426101,phantomjs using too many threads i wrote a phantomjs app to crawl over a site i built and check for a javascript file to be included the javascript is similar to google where some inline code loads in another js file the app looks for that other js file which is why i used phantomwhats the expected resultthe console output should read through a ton of urls and then tell if the script is loaded or notwhats really happeningthe console output will read as expected for about 50 requests and then just start spitting out this error20130221t100123 fatal qeventthispatcherunixprivate can not continue without a thread pipeqeventthispatcherunixprivate unable to create thread pipe too many open filesthis is the block of code that opens a page and searches for the script includepageopenurl function status consolelogyellow url status clear var found pageevaluatefunction if documentqueryselectorallscriptsrclength return true else return false if found consoleloggreen javascript found on url clear else consolelogred javascript not found on url clear selfcrawledurlsurl true selfcrawlurlsselfgetalinkspage depth1 the crawledurls object is just an object of urls that i have already crawled the crawlurls function just goes through the links from the getalinks function and calls the open function on all links that have the base domain of the domain that the crawler started onediti modified the last block of the code to be as follows but still have the same issue i have added pageclose to the fileif found consolelogred javascript not found on url clearselfcrawledurlsurl truevar links selfgetalinkspagepagecloseselfcrawlurlslinks depth1,['javascript'] +426126,char array subscript warning when i use char array subscript as in this exampleint main char pos0 int array100 forpos0pos100pos printfin arraypos return 0i am getting warning that i am using char array subscriptwarning array subscript has type achara wcharsubscriptswhich is ok because i have this warning enabledgcc manual sayswcharsubscripts warn if an array subscript has type char this is a common cause of error as programmers often forget that this type is signed on some machines this warning is enabled by wallso this warning should prevent of using negative array index my question is why is this warning active only on char and not also on other signed types thank you,['c'] +426157,automapper and convert a datetime to string i cannot get my head round the following issue i have a feeling it is a limitation of linq and expression trees but not sure how to accept the lambda body can i achieve this without creating a custom converter mappercreatemapi news newsmodel formemberx xdatecreated opt optmapfromsrc var dt datetimesrcdatecreated return dttoshortdatestring i am getting this errora lambda expression with a statement body cannot be converted to an expression tree,"['c#', '.net']" +426161,angularjs twoway binding inside ngrepeat i am working on an angular applicationi want to generate a form with an arbitrary number of text input fields with twoway bindings for every individual input field no buttons no watchers ngmodel is not working correctly because of the scoping if i am not mistaken the input fields are generated from an array with ngrepeat like this div ngrepeatitem in items labelitemnamelabel input typetext placeholderitemdefault ngmodelitemvalue this input should be bound divi just want a simple binding to update the items array in the controller on changes in the inputany help appreciated,['javascript'] +426165,multiple inhertance of interfaces in c i have an object interface and a open ended collection of interfaces that a derived object might want to support an objectclass iobject getattribute 0 a mutable objectclass imutable setattribute 0 a lockable object class ilockable lock 0 a certifiable object class icertifiable setcertification 0 getcertification 0some derived objects might look like thisclass object1 public iobject public imutable public ilockable class object2 public iobject public ilockable public icertifiable class object3 public iobject here is my question is there a way to write functions that will only take certain combinations of these interfaces for examplevoid dosomethingmagic interface combineriobject imutable ilockable objectdosomething object1 ok all interfaces are availabledosomething object2 compilation failure missing imutabledosomething object3 compilation failure missing imutable and ilockablethe closest thing i have found is boostmplinherit i have had some limited success but it does not do exactly what i needfor exampleclass object1 public boostmplinheritiobject imutable ilockabletypeclass object2 public boostmplinheritiobject ilockable icertifiabletypeclass object3 public iobjectvoid dosomethingboostmplinheritiobject ilockabletype objectdosomething object1 fails even though object1 derives from iobject and ilockabledosomething object2 fails even though object2 derives from iobject and ilockablei think something similar to boostmplinherit but that would generate an inheritance tree with all possible permutations of the supplied types might worki am also curious about other approaches to solving this problem ideally something that does compile time checks as opposed to runtime ie no dynamic cast,['c++'] +426173,how does androidattractivatedbackgroundindicator work i was looking for how to highlight a selected item in a list when thisplaying a contextual action bar for the selection and the solution i found was to set the androidbackground attribute of my row layout xml to androidattractivatedbackgroundindicatorhow does setting this work thoughwhat is the mechanism involvedwhat do the syntax elements like attr activatedbackgroundindicator meanwhere is the meaning of activatedbackgroundindicator defined,['android'] +426181,double equals vs is in python i run the following in the python interpreter foo 10 dirfoo dir10true dirfoo is dir10false why is this,['python'] +426195,simple and fast async binary tcp socket server i am looking for a simple and fast tcp socket server written in c it should be async run alongside a winforms app and support async receivingsending data to connected clients i found the following libraries that might work but i am looking for advice on specific librariesi am trying to send binary data using my custom serializer from c to an as3 frontend i have the client socket already written in as3 but i need a reliable socket server in cxynetsocket single file unreliable and misses packets does not support binarynetsocketssocketasynceventargssupersocket looks very bloated 100 classeswhich socket server library have you used with success does it support binary and is it reliable,['c#'] +426229,storm topology rebalance using java code i am trying to rebalance my storm topology which is using a kafkaspout my code is topologybuilder builder new topologybuilder properties kafkaprops new properties kafkapropsputzkconnect localhost2181 kafkapropsputzkconnectiontimeoutms 10 kafkapropsputgroupid storm buildersetspout kafkaspout new kafkaspoutkafkaprops test 3 buildersetbolt eventbolt new eventbolt 2 shufflegrouping kafkaspout eventstream buildersetbolt tablebolt new tablebolt 2 shufflegrouping kafkaspout tablestream mapstring object conf new hashmapstring object confputconfigtopology debug true localcluster cluster new localcluster clustersubmittopologytest conf buildercreatetopology utilssleep 105 listtopologysummary topologysummaries clustergetclusterinfoget topologies for topologysummary summary topologysummaries stormtopology topology clustergettopology summaryget id rebalanceoptions options new rebalanceoptions optionsset wait secs 0 optionsset num workers 4 for string name topologyget boltskeyset systemerrprintln name topologyget boltsgetnameget commonget json conf optionsput to num executors name 5 for string name topologyget spoutskeyset systemerrprintln name topologyget spoutsgetnameget commonget json conf optionsput to num executors name 5 clusterrebalance summaryget name options however during re balancing following error trace is shown 10341 storm rishabh136147365434595461d10 watcher executor info kafkaconsumerzookeeperconsumerconnector storm rishabh136147365434595461d10 begin rebalancing consumer storm rishabh136147365434595461d10 try 110341 storm rishabh13614736543453b26ed76 watcher executor info kafkaconsumerzookeeperconsumerconnector storm rishabh13614736543453b26ed76 begin rebalancing consumer storm rishabh13614736543453b26ed76 try 110342 storm rishabh136147365434595461d10 watcher executor error kafkaconsumerzookeeperconsumerconnector storm rishabh136147365434595461d10 error during syncedrebalancejavalangnullpointerexception nullat kafkautilszkutilsgetchildrenparentmaynotexistzkutilsscala181 kafka 292070jarnaat kafkautilszkutilsgetclusterzkutilsscala202 kafka 292070jarnaat kafkaconsumerzookeeperconsumerconnectorzkrebalancerlisteneranonfunsyncedrebalance1applymcvispzookeeperconsumerconnectorscala447 kafka 292070jarnaat scalacollectionimmutablerangeforeachmvcsprangescala78 scalalibrary292jarnaat kafkaconsumerzookeeperconsumerconnectorzkrebalancerlistenersyncedrebalancezookeeperconsumerconnectorscala4 kafka 292070jarnaat kafkaconsumerzookeeperconsumerconnectorzkrebalancerlisteneranon1runzookeeperconsumerconnectorscala401 kafka 292070jarna10342 storm rishabh13614736543453b26ed76 watcher executor error kafkaconsumerzookeeperconsumerconnector storm rishabh13614736543453b26ed76 error during syncedrebalancejavalangnullpointerexception nullat kafkautilszkutilsgetchildrenparentmaynotexistzkutilsscala181 kafka 292070jarnaat kafkautilszkutilsgetclusterzkutilsscala202 kafka 292070jarnaat kafkaconsumerzookeeperconsumerconnectorzkrebalancerlisteneranonfunsyncedrebalance1applymcvispzookeeperconsumerconnectorscala447 kafka 292070jarnaat scalacollectionimmutablerangeforeachmvcsprangescala78 scalalibrary292jarnaat kafkaconsumerzookeeperconsumerconnectorzkrebalancerlistenersyncedrebalancezookeeperconsumerconnectorscala4 kafka 292070jarnaat kafkaconsumerzookeeperconsumerconnectorzkrebalancerlisteneranon1runzookeeperconsumerconnectorscala401 kafka 292070jarna10342 storm rishabh136147365434595461d10 watcher executor info kafkaconsumerzookeeperconsumerconnector storm rishabh136147365434595461d10 stopping watcher executor thread for consumer storm rishabh136147365434595461d1010343 storm rishabh13614736543453b26ed76 watcher executor info kafkaconsumerzookeeperconsumerconnector storm rishabh13614736543453b26ed76 stopping watcher executor thread for consumer storm rishabh13614736543453b26ed76can someone please tell me what can be the problem do i need to define something more in kafkaspout so that at the time of rebalancing it properly shuts down and then starts again,['java'] +426252,how can i remove extra margin from inside an iframe i am currently developing a rotating montage of mixed media on a website there are about 5 imagesvideos that will appear in rotation on the site the site also uses the ektron cms so there is no way that i can determine which slots in the montage will be images and which will be videos the videos are hosted on youtubeso my problem is that the videos load perfectly aligned with the inside edge of the iframe but the images load with a slight margin of about 10px inside the iframe which is very bad because our site is laid out very precisely and a slight variation of even one pixel can mess it up this only appears in firefox and ie i have tested in chrome and safari and it works perfectly these 4 browsers are the only 4 that we officially supportheres my htmlhead body div idmainimage iframe scrollingno frameborder0 runatserver idmainimage1 src iframes do not work in your browseriframe iframe scrollingno frameborder0 runatserver idmainimage2 srcimagesdefaultmainimagemainimage 02jpg iframes do not work in your browseriframe div bodyheadthe css is as followsmainimage iframepositionabsolute top0 left 0 padding12px 0 0 12px thisplayblockmainimage iframe html body margin0px padding0px border0pxthis is the only code on the site that actively affects the way that the iframes thisplayso my question is how can i get rid of that margin inside the iframe and why does it only thisplay in firefox and ie,['html'] +426308,gnu make abort trap 6 after gcc call however call is valid when executed alone i am using gnu make to build a cc project that many people will use the makefile attempts to be general because there are many optional files in this project and each user selects those files through a matlab interface which are then provided to the makefile via command line arguments make target optsxyz etcwhen i use the makefile it correctly identifies the correct object dependencies then proceeds to find the source prerequisites for those objects and build them however every time it tries to execute an object rule i get an error saying abort trap 6 right after the gcc callthe makefile is as followsvpath c path obj dir pick compilerscc1gcc2gcclnkg assign variables for ccpp implicit rulescxxflags ccflags defines includescflags ccflags defines includes assign various userdefined valuesoutput o user libc objects patsubst cobj diroc sourcescpp objects patsubst cppobj dirocpp sourcesobjects c objects cpp objects sim objects user library dependencies and compilation rulesuser lib objects lnk linkerflags ccflags defines includes output objectsobj diro c cc2 cflags c o and an example of what i get isgcc g dthe defines iall the includes c o obj1xyzo commonxyzcmake obj1xyzo abort trap 6however if i take that exact same gcc call and run it on the command line just copy and paste the file is correctly compiled and the object file placed in the obj1 folderi tried to look at make d to see if i could find anything either since that output is crazy long the gist of it is the following output truncated for brevity gcc g dthe defines iall the includes c o obj1xyzo commonxyzcputting child 0x104f13cc0 obj1xyzo pid 24557 on the chainlive child 0x104f13cc0 obj1xyzo pid 24557 reaping losing child 0x104f13cc0 pid 24557 make obj1xyzo abort trap 6removing child 0x104f13cc0 pid 24557 from chainat which point the output ends i also tried running make k to see what happens after the first error every single source file produces the same result again each source file is compilable with the exact call that make uses when done independentlyi am completely lost on this one at this point and theres very little information about what abort trap 6 means in this contexti am running mac osx 107 with gcc42 installed through xcodei realize there is not a rule for cpp files currently i do not at present have any cpp source files to compile though in the future there likely will be which is why there is support structure for it so farthank you in advance for anyone who can help meedit added one proceeding line from the make d outputedit added solution moved to an answer,['c'] +426334,how do i convert utc to pst or pdt depending upon what the current time is in california i cannot use datetimenow because the server is not necessarily located in calfornia,"['c#', '.net']" +426353,why is there no xrange function in python3 recently i started using python3 and it is lack of xrange hurtssimple example1 python2from time import time as tdef count st t x for x in xrange10 if x4 0 et t print etstcount2 python3from time import time as tdef xrangex return iterrangexdef count st t x for x in xrange10 if x4 0 et t print etstcountthe results are respectively1 15383924482 3215819835662842why is that i mean why xranges been removed it is such a great tool to learn for the beginners just like myself like we all were at some point why remove it can somebody point me to the proper pep i cannot find itcheers,['python'] +426406,in java how do i extract a password from a httpservletrequest header without generating a string object a common java security guideline for handling sensitive data passwords recommends never using a string object to store the data and instead using an array of bytes or chars i am trying to apply this guideline in a httpservlet handler in particular i am using a basicauthenticationlike approach where the credentials are passed in in a header this is a get request so no bodythe issue i am running into is that it seems impossible to get to the header data without generating a string object which violates the guideline from the getgo i have searched for a solution pretty thoroughly and did not find any relevant thiscussion does anybody have any insight into this issuenote this takes place over https so there is no connection security problem here,['java'] +426412,how to add a custom mime type to tika and override a default extension pattern i am trying to add a custom mime type to apache tikai have the following custommimetypesxml document in orgapachetikamime xml version10 encodingutf8mimeinfo mimetype typetextstringtemplategroup glob patternstg mimetype mimetype typetextstringtemplate glob patternst mimetypemimeinfoi am getting an error about a conflicting extension pattern stcaused by orgapachetikamimemimetypeexception conflicting extension pattern st at orgapachetikamimemimetypesreaderstartelementmimetypesreaderjava166 at orgapachexercesparsersabstractsaxparserstartelementunknown sourcehow do i override the default entry for st extension and have it use my own,['java'] +426468,should i throw out an exception that happen in application error handler in globalasax the unhandled error codes in aspxcs will be caught by application error handler in globalasaxi have write some codes in application error handler to log such unhandled errors happened in aspxcsbut if the codes of log itself also fails and generated a exceptionmaybe due to io or files system problemsshould i throw such exception out if i throw it out which event should receive such exception or it makes no difference if i write throw syntax or not the code samples as followingprotected void application errorobject sender eventargs e try my codes to log exception to database system here catchexception throw should i write throw syntax here,"['c#', 'asp.net']" +426482,findchessboardcorners cannot detect chessboard on very large images by long focal length lens i can use findchessboardcorners functions for images that less than 15 mega pixel such like 2k x 15k however when i use it on the image from dslr the resolution at 3700x5300 it does not worki tried to use resize to reduce the image size directly then it worksobviously there is some hard coded or bug in the opencv source codecould you help me to figure it out or point me to a patch for this i found someone posted a similar issue in 2006 here so it looks like the problem still remainsthe code i used is like found findchessboardcorners viewgray boardsize ptvec cv calib cb adaptive thresh cv calib cb filter quads cv calib cb normalize image cv calib cb fast checkupdatejust here to clarify i think the algorithm works on large image resolution but it fails when the chessboard occupy larger proportion of the image for example when i use a 50mm fixed lens on the same camera position findchessboardcorners never fails after i change it to 100mm fixed lens the function starts to stop detecting the pattern i think it relates to the proportion or the focal lengththe image below is the 100mm lens resultupdate 2i added a sharpen filter to the large image and it starts to fix the problemfirstly i used do a sharpen filter for the large resolution imageif viewgraycols 1500 mat temp gaussianblurviewgraytemp size00 105 hardcoded filter size to be tested on 50 mm lens addweightedviewgray 18 temp 080viewgray hardcoded weight to be testedimwritetest imagelistki viewgray found findchessboardcorners viewgray boardsize ptveccv calib cb adaptive thresh cv calib cb filter quads cv calib cb normalize image cv calib cb fast checkuploaded the imagea jpg image at original resolution 3744 x 5616 if this site force convert then make sure you are using at the correct resolution,['c++'] +426504,setting overflowy hidden causes the page to jump to the top in firefox i have got some javascript which handles opening modal popups on my website and it also sets the overflowy property on the html element to hidden in chrome and ie this works as expected the scrollbar hides and the page behind the modal popup remains in the same scroll position when the popup is closed overflowy is set to scroll and the page is in the same state and position as before however in firefox as soon as overflowy is changed to hidden the page scroll position jumps to the very top and so when the popup is closed the view has changed for the user not idealthe problem can be seen on this jsfiddleis there any solution for this behaviour,"['javascript', 'css']" +426513,check if object is a number or boolean design a logical expression equivalent to the following statementx is a list of three or five elements the second element of which is the string hip and the first of which is not a number or booleanwhat i have x head hip 10print x1 is hipmy question how do you check for whether or not it is a boolean or a number,['python'] +426546,unlock mifare tag with android i am looking for a way to send the unlock sequence from an android phone to a mifare tag from the chinese manufacturer that makes the ones with a writable block 0i have been trying the connect transceive methods sending the 50 00 40 43 byte sequences but that would not work i have tried the private transceive function to get around error checking but that would not work either i get errors from the nfc servicehas anyone successfully been able to send the unlock sequence to unlock block0,['android'] +426594,how to calculate the angle from roational matrix i am using two image of the single object the object is roated certain degree from its first imageand i have calculated the pose of each image and converted the rotational vector to matrix using rodergues now how do i calculate and see how much it is rotated from its first positioni have tried many ways but answers was no were close edit my camera is fixed only the object is moving,['c++'] +426607,how are import statements in plpython handled i have a plypython function which does some json magic for this it obviously imports the json libraryis the import called on every call to the function are there any performance implication i have to be aware of,['python'] +426617,how to determine which script is being executed in phpfpm process i am running nginx phpfpm is there any way how can i know what is each of the php processes doing something like extended mod status in apache where i can see that apache process with pid x is processing url y i am not sure if the php process knows the url but getting the script path and name will be sufficient,['php'] +426631,minimal android api level to run google maps android api v2 i have developed a mobile application that uses google maps android api v1 and i plan to port it to the recent google maps android api v2 as recommended by googlehowever my application also targets android 21 devices and i cannot figure out whether the v2 maps will run on such devices i have found some reference suggesting that v2 should work with api level 8 and 10 here here and here provided that opengl es 20 is supported by the mobile device but nothing about api level 7my question is therefore what is the minimum android api level to run google maps android api v2tia,['android'] +426645,is it usefull using webview whole layout in native android app i am currently developing a native android app my app has a lot of activities i want to develop native android app but in some case i want to use a webview where the entire layout is just a webview not linear or relative or another layout just a webview all of the images and other things running in html all of screen will run in html5so i can partially transfer my app into iphone app or other platforms this is the benefit of this way to mebut i do not know is this way better what will the performance be what is the thisadvantages of converting to an html5 appcan you explainregards,"['android', 'html']" +426646,android google maps fragment in the xml i get unexpected namespace prefix i am trying to learn android and having followed the instructions on how to use the google maps api v2 i now got it working however the instructions on how to configure the initial state of the maps found at developersgooglecom suggests a namespace defined in the xmlfile in this case map the xmlcode below gives med the error unexpected namespace prefix map trying to define the xmlnsmap inside the fragment tag gave the same error but with xmlns i am obviously missing some fundamental xmlknowledge here can someone help me outrelativelayout xmlnsandroid xmlnstools xmlnsmap definition androidlayout widthmatch parent androidlayout heightmatch parent fragment androidididmap androidlayout widthmatch parent androidlayout heightmatch parent classcomgoogleandroidgmsmapssupportmapfragment mapcamerabearing1125 problem relativelayout,['android'] +426764,dompdf fails to load i am trying to get dompdf running on an inhouse server with the default configincphp settings i get the following when running the equivalent of the demo hello wolrd scriptwarning require oncevarwdompdfmasterlibphpfontlibclassesfontclsphp failed to open stream no such file or directory in varwdompdfmasterdompdf configincphp on line 335fatal error require once failed opening required varwdompdfmasterlibphpfontlibclassesfontclsphp include pathusrsharephpusrsharepear in varwdompdfmasterdompdf configincphp on line 335 when i turn off dompdf enable autoload i no longer get this warning but the code fails with the followingfatal error class dompdf not found in varwrfqtestphp on line 115the following is the coderequire oncevarwdompdfmasterdompdf configincphpdompdf new dompdf this is the line that failsdompdfload htmlquotehtmldompdfrenderdompdfstreamrfq requestquoteidpdfthis is ubuntu 1204 uptodate on patches with default apache settingsthanks so much,['php'] +426886,languageintegrated query linq for java i found several questions on so regarding linq for java eglinq for java toolis there something like linq for javahowever those questions were asked around year 2008 2010 at that time java language did not support necessary language feature like lambda expressions as per jon skeets answernow when java8 is about to emerge and will probably provide features such as lambda expressions do you think it is possible to have an linq for java implementation project soon did you hear about any project trying to fulfill that gap between java and c,['java'] +426889,c validate that string contains matching number of brackets if i have a string like this123153452632441944whats the best way to validate the following conditionsevery open bracket has a matching close bracketthere are no more than 3 sets of bracketsthere are no nested brackets ie 12349would a regex be able to validate all of these scenarios if not how about linq,['c#'] +426895,create a multiline edittext programatically i am trying to create a multiline edittext by codethis is what i useedittext txt new edittextthis lp new linearlayoutlayoutparamslayoutparamsmatch parent layoutparamswrap content 10ftxtsetlayoutparamslptxtsetsinglelinefalse txtsetinputtypeinputtypetype text flag multi linebut it is still in one single line any help,['android'] +426974,what does this keyword mean in a method parameter namespace systemwebmvchtml summary represents support for html in an application public static class formextensions public static mvcform beginformthis htmlhelper htmlhelper string actionname string controllername i have noticed that this object in front of the first parameter in beginform method does not seem to be accepted as a parameter looks like in real beginform methods functions as beginformstring actionname string controllernameomitting the first parameter but it actually receives that first parameter somehow in a hidden waycan you please explain me how this structure works i actually exploring mvc 4 internet sample thank you,['c#'] +426989,testing async tasks with robolectric do you know how to implement unit testing for asynctasks using robolectric any pointers will be appreciated,['android'] +427007,batch gradient descent with scikit learn sklearn i am playing with a onevsall logistic regression classifier using scikitlearn sklearn i have a large dataset that is too slow to run all at one go also i would like to study the learning curve as the training proceeds i would like to use batch gradient descent to train my classifier in batches of say 500 samples is there some way of using sklearn to do this or should i abandon sklearn and roll my ownthis is what i have so farfrom sklearnlinear model import logisticregressionfrom sklearnmulticlass import onevsrestclassifier xs are subsets of my training data ys are ground truth for same i have more data available for further training and crossvalidationxsshape ysshape 500 784 500lr onevsrestclassifierlogisticregressionlrfitxs yslrpredictxs0 1ys0 10ie it correctly identifies a training sample yes i realize it would be better to evaluate it with new data this is just a quick smoketest re batch gradient descent i have not gotten as far as creating learning curves but can one simply run fit repeatedly on subsequent subsets of the training data or is there some other function to train in batches the documentation and google are fairly silent on the matter thanks,['python'] +427033,strange error in rjava even after cleaning the project underscores can only be used with source level 17 or greater so everything was going quite nicely until just a while ago when rjava decided to have this error after adding an icon 5 content newpng to be exacti have tried cleaning the project and restarting eclipse to no availthe problem codepublic static final class drawable public static final int 5 content new0x7f020 public static final int ic launcher0x7f0201 the red line appears right under 5 and the error saysunderscores can only be used with source level 17 or greaterhas anyone encountered a problem like this before,"['java', 'android']" +427085,if ram is not a concern is reading line by line faster or reading everything into ram and access it python if ram is not a concern i have close to 200gb on the server is reading line by line faster or reading everything into ram and access it each line will be a string of around 200500 unicode characters there are close to 2 million lines for each filelinebylineimport codecsfor i in codecsopenunicodefilerutf8 print ireading into ramimport codecsfor i in codecsopenunicodefilerutf8readlines print i,['python'] +427148,how to continuously thisplay python output in a webpage i want to be able to visit a webpage and it will run a python function and thisplay the progress in the webpageso when you visit the webpage you can see the output of the script as if you ran it from the command line and see the output in the command linewhat do i need to do in the functionwhat do i need to do in the templateediti am trying to use markus unterwaditzers code with a template extends basehtml block content autoescape false word endautoescape endblock python codeimport flaskfrom flask import render templateimport subprocessimport timeapp flaskflask name approuteyielddef index def inner for x in range10 yield sbrn x timesleep1 return render templatesimplehtml wordinner return flaskresponseinner mimetypetexthtml texthtml is required for most browsers to show the partial page immediatelyapprundebugtrue port8080and it runs but i do not see anything in the browser,['python'] +427244,jquery set checkbox checked i already tried all the possible ways but i still did not get it workingi have a modal window with a checkbox i want that when the modal opens the checkbox check or uncheck should be based on a database value i have that already working with others form fields i started trying to get it checked but it did not workmy html divdiv idfmodal classmodal div classrowform div claspan12 span classtop titleestadospan input typecheckbox idestado cat classibtn div div divand the jqueryestado catprop checked true i also tried with attr and others seen here in the forums but none seem to workcan someone point me the right wayeditok i am really missing something here i can checkuncheck using code if the check box is in the page but is it is in the modal window i cannot i tried dozens of different waysi have a link that is supposed to open the modaland jquery to listen the click and execute some operations like filling some text boxes with data coming from database everything works like i want but the problem is that i cannot set checkbox checkedunchecked using code help pleasefunction editbuttonclickfunction var id thisdataid ajax type post url processphp datatypejson data id id op edit donefunction data the next two lines work fine ie it grabs the value from database and fills the textboxes nome categoriaval datanome categoria descricao categoriaval datadescricao categoria then i tried to set the checkbox checked because its unchecked by default and it does not work estado catpropchecked true fmodalmodalshow evtpreventdefault return false,['jquery'] +427256,detect and remove urls from textarea textarea nametest wgooglecom urlgooglecomurl texttextareamy current attempt at checking if there is a url in the textareaif textareanametestvalindexofurl 0 textareanametestvalmatchhttps textareanametestvalmatchw09azaz this does not seem to work completely for checking any of the urls above i am wondering how it can be optimized it seems very sloppy and hacked together at the moment and hopefully someone can shed some insightmy current attempt at removing urls from the textareavar value textareanametestval value valuereplaceurlg textareanametestvalvalueright now it will outputtextarea wgooglecom googlecom texttextareawhat i would like my output to betextarea texttextarea,['jquery'] +427265,javascript inheritance calling objectcreate when setting a prototype i am learning some aspects of objectoriented javascript i came across this snippet var person functionfirstname lastname thislastname lastname thisfirstname firstnameobjectdefinepropertiespersonprototype sayhi value function return hi my name is thisfirstname fullname get function return thisfirstname thislastname var employee functionfirstname lastname position personcallthis firstname lastname thisposition positionemployeeprototype objectcreatepersonprototypevar john new employeejohn doe devand my question is why do this snippet uses objectcreatepersonprototype should not we simply reset prototype withemployeeprototype personprotype,['javascript'] +427286,how to check if two words are anagrams i have a program that shows you whether two words are anagrams of one another there are a few examples that will not work properly and i would appreciate any help although if it were not advanced that would be great as i am a 1st year programmer schoolmaster and theclassroom are anagrams of one another however when i change theclassroom to theclafsroom it still says they are anagrams what am i doing wrongimport javautilarraylistpublic class anagramcheck public static void mainstring args string phrase1 tbeclassroom phrase1 phrase1tolowercasetrim char phrase1arr phrase1tochararray string phrase2 schoolmaster phrase2 phrase2tolowercasetrim arraylistcharacter phrase2arrlist convertstringtoarraylistphrase2 if phrase1length phrase2length systemoutprintthere is no anagram present else boolean isfound true for int i0 iphrase1arrlength i forint j 0 j phrase2arrlistsize j ifphrase1arri phrase2arrlistgetj systemoutprintthere is a common elementn isfound phrase2arrlistremovej ifisfound false systemoutprintthere are no anagrams present return systemoutprintfs is an anagram of s phrase1 phrase2 public static arraylistcharacter convertstringtoarrayliststring str arraylistcharacter charlist new arraylistcharacter forint i 0 istrlengthi charlistaddstrcharati return charlist,['java'] +427332,javascript local scoping var vs this i cannot seem to get my head around a specific case of scoping for javascript variables different from other examples and questions i have found i am interested in the scoping for nested functionsi have set up an example at this jsfiddle the relevant part is the followingfunction myobject var self this var a 1 thisb 2 var innermethod function 1 and 2 direct reference logmessagea a a 1 logmessageb b error b is not defined 3 and 4 using this logmessagethisa thisa thisa undefined logmessagethisb thisb thisb undefined 5 and 6 using self logmessageselfa selfa selfa undefined logmessageselfb selfb selfb 2 now i understand that a reference to a directly works i also understand that messages 3 and 4 thisa and thisb will fail because this refers to the internal function i also understand that line 6 works because i save the reference to the original objectwhat i do not understand iswhy are not messages 1 and 2 working alikewhy are not messages 5 and 6 working alike,['javascript'] +427481,slim line breaks and formatting i am using slim for templating and ruby on railsjust started using them the only problem i am facing is there is no formatting for the html rendered ie no line breaks no indentationi can understand it can be a little tricky for slim to render formatting intrinsicallyis there anyway to render properly formatted html,['ruby-on-rails'] +427515,python lower german umlauts i have a problem with converting uppercase letters with umlauts to lowercase onesprintaoulowerthe a o and the you gets converted properly but the aa and a stays uppercase any ideasfirst problem is fixed with the decodeutf8 but i still have a second one coding utf8 original messageaadecodeutf8original messageoriginal messageloweroriginal messageoriginal messagereplacea xprintoriginal messagetraceback most recent call last file untitledpy line 4 in original messageoriginal messagereplacea xunicodedecodeerror ascii codec cannot decode byte 0xc3 in position 0 ordinal not in range128,['python'] +427552,jinja2exceptionstemplatenotfound error i use flask and i got this error when i call this url login heres my login methodapproutelogindef login if authenticateforpanel return redirecturl forpanel else getparam requestargsgetlistredirect uri if getparam ref getparam0 else refpanel return render template themesdir gblogoptionsactive themeloginhtml blogoptions gblogoptions refref and the tracebacktraceback most recent call last file usersozcanlibrarypython27libpythonsitepackagesflaskapy line 1701 in call return selfwsgi appenviron start response file usersozcanlibrarypython27libpythonsitepackagesflaskapy line 1689 in wsgi app response selfmake responseselfhandle exceptione file usersozcanlibrarypython27libpythonsitepackagesflaskapy line 1687 in wsgi app response selffull thispatch request file usersozcanlibrarypython27libpythonsitepackagesflaskapy line 1360 in full thispatch request rv selfhandle user exceptione file usersozcanlibrarypython27libpythonsitepackagesflaskapy line 1358 in full thispatch request rv selfthispatch request file usersozcanlibrarypython27libpythonsitepackagesflaskapy line 1344 in thispatch request return selfview functionsruleendpointreqview args file usersozcandocumentspythonapy line 209 in login return render template themesdir gblogoptionsactive themeloginhtml blogoptions gblogoptions refref file usersozcanlibrarypython27libpythonsitepackagesflasktemplatingpy line 124 in render template return renderctxappjinja envget or select templatetemplate name or list file usersozcanlibrarypython27libpythonsitepackagesjinja2environmentpy line 758 in get or select template return selfget templatetemplate name or list parent globals file usersozcanlibrarypython27libpythonsitepackagesjinja2environmentpy line 719 in get template return self load templatename selfmake globalsglobals file usersozcanlibrarypython27libpythonsitepackagesjinja2environmentpy line 693 in load template template selfloaderloadself name globals file usersozcanlibrarypython27libpythonsitepackagesjinja2loaderspy line 115 in load source filename uptodate selfget sourceenvironment name file usersozcanlibrarypython27libpythonsitepackagesflasktemplatingpy line 61 in get source raise templatenotfoundtemplatetemplatenotfound staticthemesdefaultloginhtmli am absolutely sure the loginhtml is therestaticthemesdefault404htmlwhy can this occur,['python'] +427562,why does java force me to add f when i use float i am very new to programming i have the following codefloat f 1845fthis works fine if i change that tofloat f 1845java saying this as error error possible loss of precisionbut its optional in terms of double but in long again i am facing the same problemwhy does java forces me to do so but not in case with double,['java'] +427623,how do i convert a script using mysql functions to use mysqli functions edit whether or not to use mysqli is outside the scope of this question consider using pdowhat steps need to be taken to convert a script from using the deprecated mysql functions to mysqli is there anything that needs to be done differently when using mysqli instead of mysqlheres a basic script using mysql functionsphpdefine host username and passwordcon mysql connecthostusernamepasswordif con diecould not connect mysql errordb name db1mysql select dbdbname convalue1 mysql real escape stringinput stringquery select from table1 where table1col1 value1 result mysql queryquery conwhilerow mysql fetch assocresult col1 rowcol1 col2 rowcol2 echo col1 col2 br mysql closecon,"['php', 'mysql']" +427635,why is it not recommended to store constants in a separate class it is been told me and i have seen this statement in a few other places that it is not recommended to store your constants in a separate class in java in order to use them in the other classes but i have not seen anywhere why is it so what is the reason i should not store them in their own interfaceclass i came from c to java and in c i would just make a h file where i defined constants with define,['java'] +427648,jquery check if browser is ie how would i check if the users browser is ie i have this code here but it is not workingifbrowsermsie browserversion 9 alertyou are using an outdated browser switch to chrome or firefox,"['javascript', 'jquery', 'html', 'css']" +427657,getting raw http data headers cookies etc in google cloud endpoints i am wondering if it is possible to collect raw http data in a cloud endpoint i cannot seem to find anything in googles documentation but app engines twitter told me that it was enginestatus305747445017624576if so can i please have syntax for iti am aware that the api for gce is still in its early stages and any help would be greatly appreciated,['java'] +427794,whats a good global exception handling strategy for unity3d i am looking into doing some unity3d scripting stuff and i would like to set up global exception handling system this is not for running in the release version of the game the intention is to catch exceptions in user scripts and also in editor scripts and make sure they are forwarded to a database for analysis and also to send email to relevant devs so they can fix their shizzle in a vanilla c app i would have a trycatch around the main method in wpf i would hook one or more of the unhandled exception events in unityso far the best i have been able to come up with is something like thisusing unityengineusing systemcollectionspublic abstract class behaviourbase monobehaviour use this for initialization void start update is called once per frame void update try performupdate printhello catch systemexception e printetostring public abstract void performupdatein other scripts i derive behaviourbase instead of monobehavior and implement performupdate instead of update i have not implemented a parallel version for editor clases but i assume i would have to do the same thing there i do not like this strategy however because i will have to backport it to any scripts we grab from the community and i will have to enforce it on the team the editor scripts do not have a single point of entry comparable to monobehavior either so i assume i would have to implement exception safe versions of wizards editors and so on i have seen suggestions about catching log messages as opposed to exceptions using applicationregisterlogcallback but this makes me uncomfortable because i would need to parse the debug log string rather than having access to the actual exceptions and stacktracesso whats the right thing to do,['c#'] +427837,when to use keyword arguments aka named parameters in ruby ruby 200 supports keyword arguments ka and i wonder what the benefitsusecases are of this feature in context of pure ruby especially when seen in light of the performance penalty due to the keyword matching that needs to be done every time a method with keyword arguments is calledrequire benchmarkdef fooa1b2c3 abcenddef barabc abcendnumber 10benchmarkbm4 do bm bmreportfoo numbertimes fooa7b8c9 bmreportbar numbertimes bar789 end user system total real foo 27970 00320 28290 2906362 bar 02340 0 02340 0250010,['ruby'] +427855,having doxygen aware of namespace in cpp we have a c project that we document using doxygen putting only doxygen comments inside headers for classes we document static functions inside cppour doxygen configuration files harvest any header hpp implementation cpp file inside the project in addition we have quite a few independant components and externals that we isolate inside namespacesthe project is done in a way that we use polymorphism due to extensive use of proxy patternas it is a common practice we forbid the using directive inside the header and we use it in implementation filetypically we have in header brief test from a void fn1n2a brief test from a void fn1n2binside the implementation we haveusing namespace n1n2void fa void fb when running doxygen he seems confused and produces error messages warning no uniquely matching class member found for fapossible candidatesvoid fn1n2avoid fn1n2bany idea how to get rid of these errors and make doxygen aware of the using directive editbad news seems to be opened on bug tracker bugcgiid617285 bugcgiid154880 looks like i am looking for a workaround rather than a clean solution,['c++'] +427860,java memory questions about new keyword what happens if you run the following codewhile true string x new stringabcin terms of memoryis string x allocated on the stack or on the heap will the program eventually crash because of a memory overflow or will garbage collection prevent that does the new keyword always create the object on the heap when is an object created on the stack thanks,['java'] +427869,compare string with todays date in javascript i have got a string from an input field wich i use for date with a format like this 25022013 now i want to compare the string with todays date i want to know if the string is older or newer then todays dateany suggestions,['javascript'] +427872,how to thisplay rtsp from ip cameracctv in ios there is obviously a way to do this because so many applications are already doing it netcamviewer and icamviewer to name just onei have searched and searched but i am not finding anything of value that gives a hint as to how this is done i am reaching out hoping that someone will give me a cluei am trying to connect to an video security camera ycam which supports the rtsp protocol and thisplay the video from my iphoneipad application the camera has an ip address and i can view the video from a web browser and from quicktime running on my mac the problem is that rstp is not supported on ios so even trying to connect using safari on an ipad does not worki have read that some are trying to use live5 but i have not seen an article that describes if it has been done successfully and howan alternative is to capture the rtsp stream on a server convert it to an http live stream and then connect to the http live stream from ios unfortunately this has not proved as easy as it sounds i would prefer to go directly to the camera like other applications i have seen do the rtsp to live is a fall back if i have toany hints are greatly appreciated thanks,['ios'] +427886,should you set up database connection properties in serverxml or contextxml i am trying to set up the database connection properties using jndi for a spring web applicationi am considering two approaches as belowapproach 1in your spring configuration you may have something likejeejndilookup iddatasource jndinamejavacompenvjdbcfacsthen in your webapp metainfcontextxml file you should have something similar tooxml version10 encodingutf8 antiresourcelockingtrue context pathpoddapn reloadabletrue cachingallowedfalse antiresourcelockingtrue resource namejdbcfacs typejavaxsqldatasource usernamedatabaseusername passworddatabasepassword driverclassnameorgpostgresqldriver urldatabaseurl maxactive8 maxidle4 globaljdbcfacs contextand in your webxml you should something like jndi resourceref descriptionfacs datasourcedescription resrefnamejdbcfacsresrefname restypejavaxsqldatasourcerestype resauthcontainerresauth resourceref approach 2setup in the spring context like thisjeejndilookup iddbdatasource jndinamejdbcdatabasename expectedtypejavaxsqldatasource you can declare the jndi resource in tomcats serverxml using something like thisglobalnamingresources resource namejdbcdatabasename authcontainer typejavaxsqldatasource usernamedbusername passworddbpasswd urljdbcpostgresqllocalhostdbname driverclassnameorgpostgresqldriver initialsize5 maxwait50 maxactive120 maxidle5 validationqueryselect 1 poolpreparedstatementstrueglobalnamingresourcesand reference the jndi resource from tomcats web contextxml like thisresourcelink namejdbcdatabasename globaljdbcdatabasename typejavaxsqldatasourcemy question is where is the best place to keep database properties should they be placed in serverxml or contextxmlalso if i have 2 databases should i use two configs also is it best practice to directly place them in either serverxml or contextxml or do i need to configure through tomcat manager gui consolethanks,['java'] +427963,adding custom data attributes rails image tag i need to add datadescription and datatitle for galleria in my rails application but i cannot see how to do this with the image tag so far i have this div idgalleria entrieseach do entry image tag entryfilename title title class class datadescription entrycaption datatitle entrycaption end divbut this raises the undefined local variable or method description error so how would i do this in rails 3,['ruby-on-rails'] +427968,querying hibernate cache i have the following codeperson a new personasetnamejohnsession session openhibernatesessionsessionbegintransactionsessionsaveorupdateacriteria critera sessioncreatecriteriapersonclasscriteraaddrestrictionseqnamejohnperson personfromcache person criteriauniqueresultsessioncommitwhat i want is to have the ability to search objects from both the database and hibernates cache the following example returns null upon calling uniqueresult is there any way to retrieve saved objects that have not yet been committed to the database,['java'] +427969,stdmap threadsafety is reference to object in stdmap is thread safestdmap stdstring object objectsmap can be changed from many threads and this access is synchronized but reference to value object accessable just from 1 instance and thread is write operations with object is safe if another thread will add items to map will it reallocate,['c++'] +427980,how to create instances on the fly in cdi let us assume i have a car class in my code i want to create 10 cars car class has some inject annotated dependencies what would be the best approach to do thiscdi has a provider interface which i can use to create the carsinject providercar carproviderpublic void businessmethod car car carprovidergetunfortunately that does not work if i do not have a carfactory that has a method with produces annotation which creates the car as much as it reflects real world that i cannot create cars without a factory i would rather not write factories for everything i just want the cdi container to create my car just like any other bean how do you recommend i create those cars,['java'] +427996,how to add two background images left and right from center column i have this csswrapper1 minwidth1020pxminheight100wrapper2 height100 background urlimg1jpg 100px 300px norepeat urlimg2jpg 1165px 300px norepeatwrapper3 width1020pxmargin0 autoand this htmldiv idwrapper1 div idwrapper2 div idwrapper3 classclearfix content here pblah blah blahp div divdivi need to add 2 images left and right from center column without center column width changes and that the images did not affect the overall width of the pageexamplei can add images and made a some attemptswhen i try to change browser width background images go under the central column i tried to change minwidth1020px to minwidth1665px at first glance all is well but for the screen resolution less than 1665px all content is shifted to the righti tried a few options but unsuccessfullymy question nan i place an image so that when you change the width of the browser reduce thistance to the left and right of the center column this is the default behavior if no background imageshere is code with images examples if i make 1 big image with 1020px blank center part and put my leftright images into it will it work,"['html', 'css']" +428007,observableobserver android edit please see observer observables implementing issue it seems i was overriding methods that did not need to be and not calling setchanged before notifyi have been reading up on the observer pattern for keeping my ui up to date but i still cannot see the use for it even if in my particular object notifies my mainactivity then runs the update method i still wouldnt be able to use the pet object to pull the update values as the object is created in oncreateand i just cannot create a new object because then the variables will be differentthis is my implementation and it does not seem to workobservermainactivitypackage comgrimdroidchiimport javautilobservableimport javautilobserverimport androidappactivityimport androidappalarmmanagerimport androidapendingintentimport androidcontentintentimport androidcontentsharedpreferencesimport androidosbundleimport androidutillogimport androidviewmenuimport androidviewviewimport androidviewviewonclicklistenerimport androidwebkitwebsettingslayoutalgorithmimport androidwebkitwebviewimport androidwidgetbuttonimport androidwidgettextviewimport androidwidgettoastpublic class mainactivity extends activity implements observer onclicklistener private static final string tag vpet private static final string app prefs vpet private static final int request code 1 boolean isalive false textview happiness thisplay health thisplay hunger thisplay level thisplay button punchpet updatehunger public static pet pet new renamon override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main sharedpreferences settings getsharedpreferencesapp prefs mode private webview mywebview webview findviewbyidridpet thisplay mywebviewloadurlfileandroid assetrenamongif mywebviewsetinitialscale10 mywebviewgetsettingssetlayoutalgorithmlayoutalgorithmsingle column punchpet button findviewbyidridpunchpet updatehunger button findviewbyidridupdatehunger final textview hunger thisplay textview findviewbyidridhunger thisplay textview happiness thisplay textview findviewbyidridhappiness thisplay textview level thisplay textview findviewbyidridlevel thisplay textview health thisplay textview findviewbyidridhealth thisplay hunger thisplaysettextintegertostringpetgethunger health thisplaysettextintegertostringpetgethp level thisplaysettextintegertostringpetgetlvl happiness thisplaysettextintegertostringpetgethappy intent intent new intentthis gameloopclass pendingintent pendingintent pendingintentgetbroadcast getbasecontext request code intent 0 alarmmanager alarmmanager alarmmanager getsystemservicealarm service alarmmanagersetrepeatingalarmmanagerrtc wakeup systemcurrenttimemillis 5 10 180 pendingintent 180 ms 30 mins petfeed petaddobserverthis override public boolean oncreateoptionsmenumenu menu inflate the menu this adds items to the action bar if it is present getmenuinflaterinflatermenuactivity main menu return true override protected void onpause superonpause override public void updateobservable o object data hunger thisplaysettextintegertostringpetgethunger health thisplaysettextintegertostringpetgethp level thisplaysettextintegertostringpetgetlvl happiness thisplaysettextintegertostringpetgethappy logdtag updated from observer override public void onclickview v if v punchpet petsethp500 toastmaketextgetapplicationcontext punchpet toastlength shortshow health thisplaysettextintegertostringpetgethp else observablepetpackage comgrimdroidchiimport javautilobservableimport javautilobserverimport javautilsetimport androidutillogpublic class pet extends observable implements petinterface protected setobserver observers private static final string tag vpet private int health 100 override public void addobserverobserver o observersaddo superaddobservero override public void notifyobservers observersnotify supernotifyobservers override public synchronized void deleteobserverobserver o observersremoveo superdeleteobservero private int happiness 10 private int level 1 private int hunger 0 private int exp 0 private string name private boolean isalive true private boolean issick false public void sethpint hp thishealth hp notifyobservershp public void setlvlint lvl thislevel lvl notifyobserverslvl public void setxpint xp thisexp xp notifyobserversxp public void sethungerint hunger thishunger hunger notifyobservershunger public void sethappyint happy thishappiness happy notifyobservershappy public int gethp return health public int getlvl return level public int getxp return exp public int gethunger return hunger public int gethappy return happiness public boolean isalive return isalive public boolean issick return issick override public void sleep todo autogenerated method stub override public void clean todo autogenerated method stub override public void feed logdtag feeding from interface thing override public void passtime,"['java', 'android']" +428036,systemwindowsformsgroupbox hide frame on the systemwindowsformsgroupbox is there any way to hide frame around it i tried changing the flatstyle but that does not do what i want thanks,['c#'] +428079,parser error message could not load type sometype i am experiencing an error that i am unable to resolve for some time now i was wondering if someone can help identify the cause of this error i am completely new to asp asax after some research i think that the error i am getting is due to the web application trying to use outdated code i was thinking to rebuild the c file using visual studio andor the entire project however i am completely new to c and asp and was wondering can give me some suggestions if this may fix the problem andor if there is an possible alternate solution error messageparser error message could not load type inventory1globalsource error application codebehindglobalasaxcs inheritsinventory1global entire globalasax contents application codebehindglobalasaxcs inheritsinventory1global many thanks in advance,"['c#', 'asp.net']" +428164,what is the preferred pattern for rebinding jquerystyle ui interfaces after ajax load this always gets me after initializing all lovely ui elements on a web page i load some content in either into a modal or tabs for example and the newly loaded content does not have the ui elements initialized egabuttonbutton jquery ui button as an exampleselectchosen chosen ui as another examplecontentloaduri content is not styled my current approach is to create a registry of elements that need bindingvar uiregistry registry push function func thisregistrypushfunc apply function scope eachuiregistryregistry function i func funcscope uiregistrypushfunction scope abutton scopebutton select scopechosenuiregistryapplybody content gets styled as per usualcontentloaduri function uiregistryapplythis content gets styled i cannot be the only person with this problem so are there any better patterns for doing this,"['javascript', 'jquery']" +428212,avcapturevideopreviewlayer orientation need landscape my app is landscape only i am presenting the avcapturevideopreviewlayer like thisselfpreviewlayer avcapturevideopreviewlayer alloc initwithsessionsession selfpreviewlayer setbackgroundcoloruicolor blackcolor cgcolor selfpreviewlayer setvideogravityavlayervideogravityresizeaspect nslogpreviewview selfpreviewview calayer rootlayer selfpreviewview layer rootlayer setmaskstoboundsyes selfpreviewlayer setframerootlayer bounds nslogpreviewlayer f f f f selfpreviewlayerframeoriginx selfpreviewlayerframeoriginy selfpreviewlayerframesizewidth selfpreviewlayerframesizeheight rootlayer addsublayerselfpreviewlayer session startrunningselfpreviewview has a frame of 00568320 which is correct selfpreviewlayer logs a frame of 00568320 which is theoretically correct however the camera thisplay appears as a portrait rectangle in the middle of the landscape screen and the orientation of the camera preview image is wrong by 90 degrees what am i doing wrong i need the camera preview layer to appear in the full screen in landscape mode and the image should be orientated correctly,['ios'] +428227,replacing illegal character in filename in java i have a filenamestring there i want to replace all illegal characters with but not az 09 and i tried following code but this did not workedmystring mystringreplaceallw,['java'] +428244,format python decimal object to a specified precision i have spent countless hours researching reading testing and ultimately confused and thismayed at pythons decimal objects lack of the most fundamental concept formatting a decimals output to a stringlet us assume we have some strings or decimal objects with the following values 08 1 2312345678the goal is to simply set the decimals precision to the second decimal place eg 1 would be formatted as 1 and 12345678 as 123457i envision code similar to the followingimport decimaldecimals decimaldecimal08 decimaldecimal1 decimaldecimal2 decimaldecimal3 decimaldecimal12345678for dec in decimals print decas stringprecision2 roundinground half upthe resulting output would be0123123457obviously we cannot make use of the decimals contexts precision because this takes into consideration the total number of digits not just decimal precisioni am also not interested in converting the decimal to a float to output its value the entire reason behind decimal is to avoid storing and running calculations on floatswhat other solutions are there i understand there are many other similar questions on stack overflow but none of them have i found to resolve the underlying issue i am inquiring ofthanks much,['python'] +428246,logout in facebook using android fb sdk 30 my app using android facebook sdk 30after login getting some responseafter that i need to signout from facebook clicking on buttonhow to logout from the session in facebook pls help,['android'] +428259,java sslhandshakeexception no cipher suites in common i am using an sslserversocket to accept client connections on my opensuse server but none of them can connect i always get an sslhandshakeexception saying no cipher suites in common i have activated all of the possible suites enabled multiple protocols tried with the newest oracle jre and the openjdk also i followed several other posts on forums and stuff and unlocked all the cipher suites in the jre of oracle and i changed the settings of the openjdk jre like thisthisabled securityprovider10sunsecuritypkcs11sunpkcs11 javahomelibsecuritynsscfgand enabled securityprovider9sunsecurityecsunecthis is how i initialize my sslserversocket systemsetpropertyjavaxnetsslkeystore keystore systemsetpropertyjavaxnetsslkeystorepassword nopassword javalangsystemsetpropertysunsecuritysslallowunsaferenegotiation true create a trust manager that does not validate certificate chains trustmanager trustallcerts new trustmanager new x509trustmanager public void checkclienttrustedjavasecuritycertx509certificate certs string authtype public void checkservertrustedjavasecuritycertx509certificate certs string authtype public javasecuritycertx509certificate getacceptethissuers return null install the alltrusting trust manager sslcontext sc sslcontextgetinstancetlsv12 scinitnull trustallcerts new securerandom sslserversocket ssl sslserversocket scgetserversocketfactorycreateserversocket downloadfilelistport got rid of sslsetenabledciphersuitesscgetserversocketfactorygetsupportedciphersuites sslsetenabledprotocolsnew string tlsv1 tlsv11 tlsv12 sslv3 systemoutprintlnarraystostringsslgetenabledciphersuites s ssl s new serversocketdownloadfilelistport ssetsotimeouttimeoutthe problem is that i cannot find out what cipher suites the clients want neither can i influence it i started the program with djavaxnetdebugsslhandshake here is the result can someone of you figure out what the problem isedit the keystore was generated with keytool genkey keyalg rsa keystore keystoreheres the code on this page if that helps seems like the formatting is not messed uptrigger seeding of securerandomtrigger seeding of securerandomdone seeding securerandomdone seeding securerandomignoring unavailable cipher suite tls ecdhe rsa with aes 256 cbc shaignoring unavailable cipher suite tls ecdh ecdsa with aes 128 cbc shaignoring unavailable cipher suite tls ecdhe rsa with aes 256 cbc shaignoring unavailable cipher suite tls ecdh ecdsa with aes 128 cbc shaignoring unavailable cipher suite tls ecdh rsa with aes 256 cbc shaignoring unavailable cipher suite tls ecdh rsa with aes 256 cbc shaignoring unsupported cipher suite tls dhe dss with aes 128 cbc sha256ignoring unavailable cipher suite tls ecdh ecdsa with 3des ede cbc shaignoring unsupported cipher suite tls dhe dss with aes 256 cbc sha256ignoring unavailable cipher suite tls ecdh ecdsa with 3des ede cbc shaignoring unavailable cipher suite tls ecdh rsa with aes 128 cbc sha256ignoring unavailable cipher suite tls ecdhe rsa with rc4 128 shaignoring unavailable cipher suite tls ecdh ecdsa with rc4 128 shaignoring unavailable cipher suite tls ecdhe ecdsa with rc4 128 shaignoring unavailable cipher suite tls ecdhe rsa with aes 256 cbc sha384ignoring unavailable cipher suite tls ecdhe rsa with aes 128 cbc shaignoring unavailable cipher suite tls ecdhe ecdsa with 3des ede cbc shaignoring unavailable cipher suite tls ecdh rsa with rc4 128 shaignoring unavailable cipher suite tls ecdh ecdsa with aes 256 cbc sha384ignoring unavailable cipher suite tls ecdh rsa with 3des ede cbc shaignoring unavailable cipher suite tls ecdh rsa with aes 128 cbc shaignoring unavailable cipher suite tls ecdhe ecdsa with aes 256 cbc shaignoring unavailable cipher suite tls ecdhe ecdsa with aes 128 cbc shaignoring unavailable cipher suite tls ecdhe rsa with aes 128 cbc sha256ignoring unavailable cipher suite tls ecdhe ecdsa with aes 256 cbc sha384ignoring unavailable cipher suite tls ecdh rsa with aes 256 cbc sha384ignoring unavailable cipher suite tls ecdhe ecdsa with aes 128 cbc sha256ignoring unavailable cipher suite tls ecdh ecdsa with aes 128 cbc sha256ignoring unavailable cipher suite tls ecdh ecdsa with aes 256 cbc shaignoring unavailable cipher suite tls ecdhe rsa with 3des ede cbc shaignoring unavailable cipher suite tls ecdhe rsa with aes 256 cbc shaignoring unavailable cipher suite tls ecdh ecdsa with aes 128 cbc shaignoring unavailable cipher suite tls ecdh rsa with aes 256 cbc shaignoring unavailable cipher suite tls ecdh ecdsa with 3des ede cbc shaignoring unavailable cipher suite tls ecdh rsa with aes 128 cbc sha256ignoring unavailable cipher suite tls ecdhe rsa with rc4 128 shaignoring unavailable cipher suite tls ecdh ecdsa with rc4 128 shaignoring unavailable cipher suite tls ecdhe ecdsa with rc4 128 shaignoring unavailable cipher suite tls ecdhe rsa with aes 256 cbc sha384ignoring unavailable cipher suite tls ecdhe rsa with aes 128 cbc shaignoring unavailable cipher suite tls ecdhe ecdsa with 3des ede cbc shaignoring unavailable cipher suite tls ecdh rsa with rc4 128 shaignoring unavailable cipher suite tls ecdh ecdsa with aes 256 cbc sha384ignoring unavailable cipher suite tls ecdh rsa with 3des ede cbc shaignoring unavailable cipher suite tls ecdh rsa with aes 128 cbc shaignoring unavailable cipher suite tls ecdhe ecdsa with aes 256 cbc shaignoring unavailable cipher suite tls ecdhe ecdsa with aes 128 cbc shaignoring unavailable cipher suite tls ecdhe rsa with aes 128 cbc sha256ignoring unavailable cipher suite tls ecdhe ecdsa with aes 256 cbc sha384ignoring unavailable cipher suite tls ecdh rsa with aes 256 cbc sha384ignoring unavailable cipher suite tls ecdhe ecdsa with aes 128 cbc sha256ignoring unavailable cipher suite tls ecdh ecdsa with aes 128 cbc sha256ignoring unavailable cipher suite tls ecdh ecdsa with aes 256 cbc shaignoring unsupported cipher suite tls dhe rsa with aes 128 cbc sha256ignoring unavailable cipher suite tls ecdhe rsa with 3des ede cbc shaignoring unsupported cipher suite tls ecdh rsa with aes 128 cbc sha256ignoring unavailable cipher suite tls ecdhe rsa with rc4 128 shaignoring unavailable cipher suite tls ecdh ecdsa with rc4 128 shaignoring unsupported cipher suite tls dhe rsa with aes 256 cbc sha256ignoring unavailable cipher suite tls ecdhe ecdsa with rc4 128 shaignoring unsupported cipher suite tls ecdhe rsa with aes 256 cbc sha384ignoring unavailable cipher suite tls ecdhe rsa with aes 128 cbc shaignoring unavailable cipher suite tls ecdhe ecdsa with 3des ede cbc shaignoring unavailable cipher suite tls ecdh rsa with rc4 128 shaignoring unsupported cipher suite tls ecdh ecdsa with aes 256 cbc sha384ignoring unavailable cipher suite tls ecdh rsa with 3des ede cbc shaignoring unavailable cipher suite tls ecdh rsa with aes 128 cbc shaignoring unsupported cipher suite tls rsa with aes 256 cbc sha256ignoring unavailable cipher suite tls ecdhe ecdsa with aes 256 cbc shaignoring unavailable cipher suite tls ecdhe ecdsa with aes 128 cbc shaignoring unsupported cipher suite tls ecdhe rsa with aes 128 cbc sha256ignoring unsupported cipher suite tls ecdhe ecdsa with aes 256 cbc sha384ignoring unsupported cipher suite tls ecdh rsa with aes 256 cbc sha384ignoring unsupported cipher suite tls ecdhe ecdsa with aes 128 cbc sha256ignoring unsupported cipher suite tls ecdh ecdsa with aes 128 cbc sha256ignoring unavailable cipher suite tls ecdh ecdsa with aes 256 cbc shaignoring unsupported cipher suite tls rsa with aes 128 cbc sha256ignoring unavailable cipher suite tls ecdhe rsa with 3des ede cbc shamain setsotimeout20 calledallow unsafe renegotiation trueallow legacy hello messages trueis initial handshake trueis secure renegotiation false no cached client session clienthello tlsv1randomcookie gmt 1361763651 bytes 159 113 250 254 103 37 66 234 127 4 36 240 60 252 55 112 6 224 192 181 146 163 63 148 152 255 77 8 session id cipher suites tls rsa with aes 256 cbc sha tls dhe rsa with aes 256 cbc sha tls dhe dss with aes 256 cbc sha tls rsa with aes 128 cbc sha tls dhe rsa with aes 128 cbc sha tls dhe dss with aes 128 cbc sha ssl rsa with rc4 128 sha ssl rsa with 3des ede cbc sha ssl dhe rsa with 3des ede cbc sha ssl dhe dss with 3des ede cbc sha ssl rsa with rc4 128 md5 tls empty renegotiation info scsvcompression methods 0 main write tlsv1 handshake length 67main read tlsv1 handshake length 81 serverhello tlsv1randomcookie gmt 1361763767 bytes 249 20 120 68 76 110 168 235 47 91 119 64 151 242 169 191 1 105 146 90 173 223 55 127 133 12 1 247 session id 246 66 250 209 13 188 190 246 14 49 113 183 192 202 68 246 121 162 165 71 242 220 233 223 245 47 250 215 203 94 255 148cipher suite tls rsa with aes 256 cbc shacompression method 0extension renegotiation info renegotiated connection empty initialized session1 tls rsa with aes 256 cbc sha tls rsa with aes 256 cbc shamain read tlsv1 handshake length 933 certificate chainchain 0 version v3 subject cndchadikode ohadiko dc ltown stland of the free cde signature algorithm sha1withrsa oid 12840113549115 key sun rsa public key 2048 bits modulus 22613010171436639614880560956464961031525818836745124665845833909370970098210909007150132692078653881042731046316239498513359691936582885343174669796075601988313858262934995935649363223919652108615287224220030023261629874169833165458724674897658521210181069731052941643682915351437455424212894709269406495201972815275780671833019180604519706077034663995712451074569719657264314801319080071365646862915899199712754454017798317490609932521734486871031925633096008686226922893393848231102968523827453782367026700161857938280131947073692442355086505577514867501649615873175599114046362924859400297960451 public exponent 65537 validity from sat jul 07 125623 cest 2012 to tue jul 07 125623 cest 2015 issuer cndchadikode ohadiko dc ltown stland of the free cde serialnumber 8682354f f94fb5certificate extensions 31 objectid 252935 criticalityfalseauthoritykeyidentifier keyidentifier 0 43 1d d9 a7 cf 21 2e 17 f3 4e ee f6 6c 6c 88 16 cnll0010 08 3c 67 8e g2 objectid 252919 criticalityfalsebasicconstraints catrue pathlen21474836473 objectid 252914 criticalityfalsesubjectkeyidentifier keyidentifier 0 43 1d d9 a7 cf 21 2e 17 f3 4e ee f6 6c 6c 88 16 cnll0010 08 3c 67 8e g algorithm sha1withrsa signature0 14 83 48 d3 ec 39 49 e3 9c bc 20 f5 bf e4 32 33 h9i 230010 5f 09 8f 2d f2 c3 82 80 79 93 9a c1 97 93 92 d9 y0020 d0 da 4d b2 fc a1 43 60 1f b9 ea 4c 29 d7 79 d0 mcly0030 66 8c 25 14 eb 9d 60 94 d7 f4 15 33 8b 17 24 24 f30040 5c 65 26 3d c3 b0 8a 51 b6 27 01 d1 a6 a3 68 87 eqh0050 2d 6f 0b e6 00 96 b6 cf bc e9 d2 9c 7e 19 9e e1 o0060 3a 96 42 2e b7 e8 c0 70 01 99 20 39 89 6d 94 2b bp 9m0070 76 2f f1 0e 6d 2d 9b 52 77 d3 63 6a 11 dc a3 e6 vmrwcj0080 4e 0e 64 6d fa 77 bc 1e 4f c3 91 ad 21 f7 5d 31 ndmwo10090 f9 04 a5 fa 34 ef 43 61 f1 42 32 5a 9b d1 16 84 4cab2z00a0 07 2b ca 01 af 84 54 d2 a9 c4 3a 7a ea d1 2a 95 tz00b0 47 30 03 ba 48 c4 57 1f 78 58 6c 7a 56 60 40 2c g0hwxxlzv00c0 6a 17 15 3f 43 a5 fb 81 4d 9d 1b dc a7 ce 78 d1 jcmx00d0 5a 66 97 79 04 55 da 34 3c b2 cd 9a 62 ee 32 22 zfyu4b200e0 70 84 0e 3e 5d 7f 91 0d a5 d4 84 6b f3 e9 40 e9 pk00f0 e8 69 d7 e5 fc b6 0a 4c 35 66 cc ba e5 38 12 a0 il5f8main read tlsv1 handshake length 4 serverhellodone clientkeyexchange rsa premastersecret tlsv1main write tlsv1 handshake length 262session keygenpremaster secret0 03 01 59 d3 0f f9 95 e8 dc e2 c2 4a 2b 93 79 55 yjyu0010 0b 1a 43 5e f4 0a 73 f1 13 e1 00 df 78 55 f6 52 csxur0020 4e 6a d3 2c f8 08 a1 b3 03 df c9 5e 8c 14 8d 4e njnconnection keygenclient nonce0 51 2b dd 43 9f 71 fa fe 67 25 42 ea 7f 04 24 f0 qcqgb0010 3c fc 37 70 06 e0 c0 b5 92 a3 3f 94 98 ff 4d 08 7pmserver nonce0 51 2b de b7 f9 14 78 44 4c 6e a8 eb 2f 5b 77 40 qxdlnw0010 97 f2 a9 bf 6f 69 92 5a ad df 37 7f 85 0c 01 f7 oiz7master secret0 3e 9e 24 42 3d e4 82 af ad 97 76 ef 06 ef fb fd bv0010 c8 1a d5 7e 8e a2 74 4d e8 e7 b9 1e 60 e9 e0 6f tmo0020 09 e3 56 81 fc 2d 20 d9 69 6b 26 c3 0b c5 53 5f v iks client mac write secret0 04 30 70 7e a9 4a 1f 88 55 f8 31 31 75 36 40 35 0pju11u650010 25 65 24 5d eserver mac write secret0 8b c1 65 50 6d 11 21 32 cd 50 3a ab 0f 2e a5 fc epm2p0010 c7 30 e6 ec 0client write key0 25 d7 96 b0 9a 1f 49 95 06 4d 05 36 2e d0 38 04 im680010 0f 32 15 2e 8f 0a 6c 79 f8 ed e8 9b fe 5c 2c d8 2lyserver write key0 4a 91 5d df b2 fe 6f 35 3e 8a 21 df 17 e0 35 f0 jo550010 db 97 4c 7e 18 07 7e 27 dd ad bc c4 c4 28 c5 e1 lclient write iv0 b6 c1 98 05 9b 37 f9 0f 4e 0c 0f 6e 08 8a 26 c9 7nnserver write iv0 0e 83 27 3e 3b 40 e8 be 4c 58 c4 5f ef e4 d3 4c lx lmain write tlsv1 change cipher spec length 1 finishedverify data 23 181 134 191 68 30 119 81 239 135 238 80 main write tlsv1 handshake length 48main read tlsv1 change cipher spec length 1main read tlsv1 handshake length 48 finishedverify data 254 182 228 50 121 214 35 175 100 128 102 152 cached client session session1 tls rsa with aes 256 cbc shamain write tlsv1 application data length 48hsent hsup adbase adtigr adblommain read tlsv1 application data length 32main read tlsv1 application data length 48main read tlsv1 application data length 32main read tlsv1 application data length 32main write tlsv1 application data length 32main write tlsv1 application data length 288clientmanager read tlsv1 application data length 32clientmanager read tlsv1 application data length 96 cut out becausei exceeded body limitclientmanager read tlsv1 application data length 80clientmanager read tlsv1 application data length 32clientmanager read tlsv1 application data length 80main write tlsv1 application data length 32main write tlsv1 application data length 64allow unsafe renegotiation trueallow legacy hello messages trueis initial handshake trueis secure renegotiation falseignoring unavailable cipher suite tls ecdhe rsa with aes 256 cbc shaignoring unavailable cipher suite tls ecdh ecdsa with aes 128 cbc shaignoring unsupported cipher suite tls rsa with aes 256 cbc sha256 for sslv3ignoring unsupported cipher suite tls dhe rsa with aes 256 cbc sha256 for sslv3ignoring unsupported cipher suite tls dhe dss with aes 256 cbc sha256 for sslv3ignoring unsupported cipher suite tls rsa with aes 256 cbc sha256 for tlsv1ignoring unsupported cipher suite tls dhe rsa with aes 256 cbc sha256 for tlsv1ignoring unsupported cipher suite tls dhe dss with aes 256 cbc sha256 for tlsv1ignoring unsupported cipher suite tls rsa with aes 256 cbc sha256 for tlsv11ignoring unsupported cipher suite tls dhe rsa with aes 256 cbc sha256 for tlsv11ignoring unsupported cipher suite tls dhe dss with aes 256 cbc sha256 for tlsv11ignoring unavailable cipher suite tls ecdh rsa with aes 256 cbc shaignoring unavailable cipher suite tls ecdh ecdsa with 3des ede cbc shaignoring unavailable cipher suite tls ecdh rsa with aes 128 cbc sha256ignoring unavailable cipher suite tls ecdhe rsa with rc4 128 shaignoring unavailable cipher suite tls ecdh ecdsa with rc4 128 shaignoring unavailable cipher suite tls ecdhe ecdsa with rc4 128 shaignoring unavailable cipher suite tls ecdhe rsa with aes 256 cbc sha384ignoring unavailable cipher suite tls ecdhe rsa with aes 128 cbc shaignoring unavailable cipher suite tls ecdhe ecdsa with 3des ede cbc shaignoring unavailable cipher suite tls ecdh rsa with rc4 128 shaignoring unavailable cipher suite tls ecdh ecdsa with aes 256 cbc sha384ignoring unavailable cipher suite tls ecdh rsa with 3des ede cbc shaignoring unavailable cipher suite tls ecdh rsa with aes 128 cbc shaignoring unavailable cipher suite tls ecdhe ecdsa with aes 256 cbc shaignoring unavailable cipher suite tls ecdhe ecdsa with aes 128 cbc shaignoring unavailable cipher suite tls ecdhe rsa with aes 128 cbc sha256ignoring unavailable cipher suite tls ecdhe ecdsa with aes 256 cbc sha384ignoring unavailable cipher suite tls ecdh rsa with aes 256 cbc sha384a client read sslv3 handshake length 112ignoring unavailable cipher suite tls ecdhe ecdsa with aes 128 cbc sha256ignoring unavailable cipher suite tls ecdh ecdsa with aes 128 cbc sha256ignoring unavailable cipher suite tls ecdh ecdsa with aes 256 cbc shaignoring unavailable cipher suite tls ecdhe rsa with 3des ede cbc sha clienthello tlsv12randomcookie gmt 1361763651 bytes 47 7 95 146 25 28 95 191 146 159 184 47 149 220 67 169 121 123 252 98 0 253 108 88 108 188 52 76 session id cipher suites tls dhe rsa with aes 128 cbc sha tls dhe rsa with aes 128 cbc sha256 tls dhe rsa with camellia 128 cbc sha tls dhe rsa with aes 256 cbc sha tls dhe rsa with aes 256 cbc sha256 tls dhe rsa with camellia 256 cbc sha ssl dhe rsa with 3des ede cbc sha tls dhe dss with aes 128 cbc sha tls dhe dss with aes 128 cbc sha256 tls dhe dss with camellia 128 cbc sha tls dhe dss with aes 256 cbc sha tls dhe dss with aes 256 cbc sha256 tls dhe dss with camellia 256 cbc sha ssl dhe dss with 3des ede cbc sha ssl dhe dss with rc4 128 sha tls rsa with aes 128 cbc sha tls rsa with aes 128 cbc sha256 tls rsa with camellia 128 cbc sha tls rsa with aes 256 cbc sha tls rsa with aes 256 cbc sha256 tls rsa with camellia 256 cbc sha ssl rsa with 3des ede cbc sha ssl rsa with rc4 128 sha ssl rsa with rc4 128 md5compression methods 0 extension renegotiation info renegotiated connection emptyextension signature algorithms signature algorithms unknown hash0x4 signature0x2 sha256withrsa sha1withrsa sha1withdsa initialized session2 ssl null with null null invalidated session2 ssl null with null nulla client send tlsv12 alert fatal description handshake failurea client write tlsv12 alert length 2a client called closesocketa client handling exception javaxnetsslsslhandshakeexception no cipher suites in commonthe output contains one connect to another server that works and then the connection to my server i cannot remove the other connect because i am getting the information on how to connect over this connection i could enable debugging after the first connect if that is possible but i do not know howi removed all not related output output that i createdupdatei cannot even connect to myself when i create a sslserversocket and an sslsocket to connect to it in the same application i get the same error but when i compare the lists of enabled cipher suites there are a bunch of suites that are supported by both sockets i have tested that on windows 7 64bit with the newest jdkupdatei just started the server part of my program from scratch using a tutorial and magically it worked i have no idea why but it seems like i should have just used as much standard implementations as possible i give the reputation to bruno since he put the most effort in his post,['java'] +428299,singleton with volatile in java class myclass private static volatile resource resource public static resource getinstance ifresource null resource new resource return resource here my doubt is according to java concurrency in practice if you use volatile safe publication happens ie as soon the reference is visible to another thread the data is also available so can i use it here but if it is correct then suppose thread1 now checks resource and it is null so it starts creating the object while thread1 is creating the objet another thread ie thread2 comes and start checking the value of resource and thread2 finds it as null assume creating resource object takes some considerable amount of time and as thread1 has not yet completed the creation so the safe publication has not happened hence unavailable to thread2 then will it also start creating the object if yes then class invariant breaks am i correct please help me in understanding this specially use of volatile here please bear with me if i asking like a naive,['java'] +428328,how do i find out which gem has a specific dependency i commented out a gem but bundle install still would not run how do i find out which gem has a dependency on sysproctable bundle installfetching gem metadata from fetching gem metadata from resolving dependenciescould not find sysproctable092 in any of the sources grep proctable gemfile gem sysproctable 092 path vendorgems bundle listresolving dependenciescould not find gem rspecrails 2110 ruby in the gems available on this machine bundle vizresolving dependenciescould not find gem rspecrails 2110 ruby in the gems available on this machine bundle vbundler version 130 ruby vruby 193p385 20130206 revision 39114 i386cygwingemfile i have already tried these troubleshooting steps,"['ruby-on-rails', 'ruby']" +428365,how can i send a signal from a python program i have this code which listens to usr1 signalsimport signalimport osimport timedef receive signalsignum stack print received signumsignalsignalsignalsigusr1 receive signalsignalsignalsignalsigusr2 receive signalprint my pid is osgetpidwhile true print waiting timesleep3this works when i send signals with kill usr1 pidbut how can i send the same signal from within the above python script so that after 10 seconds it automatically sends usr1 and also receives it without me having to open two terminals to check it,['python'] +428381,getting get variable in laravel hello i am creating api using rest and laravel i was following this article everything went well but i want to map get request to recognise variable using for example domainapiv1todosstart1limit2my routesphp routeanyapiv1todosnum arrayas apitodos uses apitodosindexmy controllersapitodosphp class api todos controller extends base controller public restful true public function get indexid null ifis nullid return responseeloquenttodoall1 else todo todofindid if is nulltodo return responsejsontodo not found 404 else return responseeloquenttodo how to recognise get parameter using thank you and sorry for my bad english,['php'] +428414,c stdstring append vs push back this really is a question just for my own interest i have not been able to determine through the documentation i see on that append has complexityunspecified but generally up to linear in the new string lengthwhile push back has complexityunspecified generally amortized constant but up to linear in the new string lengthas a toy example suppose i wanted to append the characters foo to a string wouldmystringpush backfmystringpush backomystringpush backoand mystringappendfooamount to exactly the same thing or is there any difference you might figure that append would be more efficient because the compiler would know how much memory is required to extend the string the specified number of characters while push back may need to secure memory each call,['c++'] +428438,thisable div selection when clicking on it how can i avoid selecting a div and hide the highlight when i click in iti want to hide the dotted outlinecannot get the screenshot to appear here it is,"['html', 'css']" +428488,removing all rows from a table using jpa i want to remove all rows from a specific table using jpawhat i didpublic class emptybomtables extends httpservlet private static final long serialversionuid 1lpersistencecontextunitname xpublic entitymanager emresourceusertransaction utx see httpservletdogethttpservletrequest request httpservletresponse response protected void dogethttpservletrequest request httpservletresponse response throws servletexception ioexception query q1 emcreatequerydelete from bommodule query q2 emcreatequerydelete from bomitem query q3 emcreatequerydelete from itemmoduleconnection query q4 emcreatequerydelete from moduleconnection try utxbegin catch notsupportedexception systemexception e eprintstacktrace q1executeupdate q2executeupdate q3executeupdate q4executeupdate try utxcommit catch securityexception illegalstateexception rollbackexception heuristicmixedexception heuristicrollbackexception systemexception e eprintstacktrace error 093030197 error orgapachecatalinacorecontainerbasejbosswebdefaulthostssis2emptybomtables httplocalhost12700180801 servletservice for servlet emptybomtables threw exception javaxpersistencetransactionrequiredexception executing an updatedelete query at orghibernateejbabstractqueryimplexecuteupdateabstractqueryimpljava96 hibernateentitymanager401finaljar401final at orgjbossasjpacontainerquerynontxinvocationdetacherexecuteupdatequerynontxinvocationdetacherjava80 jbossasjpa711finaljar711final at comsicapssis2bomemptybomtablesdogetemptybomtablesjava50 classes at javaxservlethttphttpservletservicehttpservletjava734 jboservletapi 30 spec100finaljar100final at javaxservlethttphttpservletservicehttpservletjava847 jboservletapi 30 spec100finaljar100final at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava329 jbossweb7013finaljar at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava248 jbossweb7013finaljar at orgapachecatalinacorestandardwrappervalveinvokestandardwrappervalvejava275 jbossweb7013finaljar at orgapachecatalinacorestandardcontextvalveinvokestandardcontextvalvejava161 jbossweb7013finaljar at orgapachecatalinaauthenticatorauthenticatorbaseinvokeauthenticatorbasejava397 jbossweb7013finaljar at orgjbossasjpainterceptorwebnontxemcloservalveinvokewebnontxemcloservalvejava50 jbossasjpa711finaljar711final at orgjbossaswebsecuritysecuritycontextassociationvalveinvokesecuritycontextassociationvalvejava153 jbossasweb711finaljar711final at orgapachecatalinacorestandardhostvalveinvokestandardhostvalvejava155 jbossweb7013finaljar at orgapachecatalinavalveserrorreportvalveinvokeerrorreportvalvejava102 jbossweb7013finaljar at orgapachecatalinacorestandardenginevalveinvokestandardenginevalvejava109 jbossweb7013finaljar at orgapachecatalinaconnectorcoyoteadapterservicecoyoteadapterjava368 jbossweb7013finaljar at orgapachecoyotehttp11http11processorprocesshttp11processorjava877 jbossweb7013finaljar at orgapachecoyotehttp11http11protocolhttp11connectionhandlerprocesshttp11protocoljava671 jbossweb7013finaljar at orgapachetomcatutilnetjioendpointworkerrunjioendpointjava930 jbossweb7013finaljar at javalangthreadrunthreadjava722 rtjar170 09093030218 error orgjbossastxn httplocalhost12700180801 jbas010152 application error transaction still active in request with status 1what am i doing wrong,['java'] +428493,how to get the class of type variable in java generics i have seen similar questions but they didnt help very muchfor instance i have got this generic classpublic class containertestt public void dosomething i want here to determinate the class of the type argument in this case string and another class which uses this container classpublic class testcase private containerteststring containertest public void somemethod containertestdosomething is it possible to determinate the class of the type argument in method dosomething without having an explicit type variablefield or any constructor in containertest classupdate changed format of containertest class,['java'] +428499,testing php code that calls a static method i want to test this code block which has to call a static classclass somemodule public function processfoo foo foofactorygetfoo do something to foo return foo i cannot modify the static class i can however change the code inside the module how can i refactor this code to be unit testable,['php'] +428527,can you have ifthenelse logic in sql i need to do select data from a table based on some kind of priority like soselect product price from table1 where project 1 pseudo if no price found do thisselect product price from table1 where customer 2 pseudo if still no price found do thisselect product price from table1 where company 3that is if i found 3 products with prices based on project x i do not want to select on customer y i just want to return the resulting 3 rows and be donehow are you supposed to do stuff like this in sql use some kind of casestatement for the pseudoifs do a union or some other smart thingedit i am using ms sqlthanks,['sql'] +428530,behavior of exec function in python 2 and python 3 following code gives different output in python2 and in python3from sys import versionprintversiondef executea st b 42 execb nprintb bformatst printba 1executea 1e6apython2 prints272 default jun 12 2011 150859 msc v1500 32 bit intelb 1010python3 prints323 default apr 11 2012 071524 msc v1500 32 bit intelb 1042why does python2 bind the variable b inside the execute function to the values in the string of the exec function while python3 does not do this how can i achieve the behavior of python2 in python3 i already tried to pass dictionaries for globals and locals to exec function in python3 but nothing worked so far edit after reading martijns answer i further analyzed this with python3 in following example i give the locals dictionay as d to exec but db prints something else than just printing bfrom sys import versionprintversiondef executea st b 42 d locals execb nprintb bformatst globals d printb this prints 42 printdb this prints 10 printidd idlocals this prints truea 1executea 1e6a323 default apr 11 2012 071524 msc v1500 32 bit intelb 104210truethe comparison of the ids of d and locals shows that they are the same object but under these conditions b should be the same as db what is wrong in my example,['python'] +428537,running mstest from command line against visual studio 2012 native c tests i have a visual studio 2012 solution with a number of native c test projectsi can run all of these correctly and successfully from within visual studio 2012 using the test explorer tabhowever i cannot get the tests to run when running from the command linefollowing the documentation i have been running the following command linemstest testcontainerpathtotestprojectwin32releasetestprojectdlli also need to runmstest testcontainerpathtotestprojectx64releasetestprojectdllfor the testing of the 64bit version of the codewhen i run these command lines i get the following error messagemicrosoft r test execution command line tool version 110507271 copyright c microsoft corporation all rights reservedloading pathtotestprojectwin32releasetestprojectdll pathtotestprojectwin32releasetestprojectdll unable to load the test container pathtotestprojectwin32releasetestprojectdll or one of its dependencies if you build your test project assembly as a 64 bit assembly it cannot be loaded when you build your test project assembly select any cpu for the platform to run your tests in 64 bit mode on a 64 bit processor you must change your test settings in the hosts tab to run your tests in a 32 bit process error details could not load file or assembly filecpathtotestprojectwin32releasetestprojectdll or one of its dependencies the module was expected to contain an assembly manifestthe code is native c and has two build configurations one on win32 platform and the other on x64 platform i cannot have an anycpu platform configuration what am i missing here to be able to run the tests from the command line,['c++'] +428559,correct setting of database connection pool databaseyml for singlethreaded rails applications i was wondering about the following setting in the rails databaseymlby default the number of database connections for the connection pool of activerecord is set to 5development pool 5but by default rails 3 is single threaded why would you need 5 connections by defaultas far as i understand a single threaded rails app cannot trigger multiple database operations at once why would do you need to keep more connection openi would assume that 2 connections would make sense so you always have one active connection even if the other one times out but holding five connections seems a little odd to meam i missing somethingupdateif anyone else is curious i just found a commit that explains itin fact these default settings do not make any sense it was fixed but then temporarily reverted one year ago because of the test suite,['ruby-on-rails'] +428572,jobject camelcase conversion with jsonnet how can i convert a generic jobject to camelcase plain json stringi have tried with jsonserializersettings but does not work newtonsoftjson 4511testpublic void should convert to camel case var serializer jsonserializercreatenew jsonserializersettings contractresolver new camelcasepropertynamescontractresolver var jo new jobject jocamelcase 1 var stringwriter new stringwriter var writer new jsontextwriterstringwriter serializerserializewriterjo var serialized stringwritertostring assertareequalcamelcase1 serializedupdateaccording to that cannot be done tnx to nick w for the link,['c#'] +428580,cannot modify frozen hash in rails3 i am getting the following errorcannot modify frozen hashhomervmgemsruby193p327uigemsactiverecord326libactive recordattribute methodswriterb38in homervmgemsruby193p327uigemsactiverecord326libactive recordattribute methodswriterb38in write attributefrom this linewrite attributevalue new valuethis can be run properly for certain days but now it fail continously with an above error i tried out solution for that but nothing work for me,['ruby-on-rails'] +428585,jsonstringify an object with knockout js variables current scenariofunction employeedata var self this variablesthisforename koobservabledataforenamethissurname koobservabledatasurnamethissave function var obj jsonstringifyself without koobservables this works fine self does not work obviously consolelogobji think what i am trying to do is pretty straight forward get all the observable values without going through every single one of them and creating a json string using the stringify function this is easy to do without observables is there a simple way to do it with them,['jquery'] +428627,neatest way to loop over a range of integers since c11 introduced the rangebased for loop rangebased for in c11 what is the neatest way to express looping over a range of integersinstead of for int i0 in ii would like to write something likefor int i range0ndoes the new standard support anything of that kindupdate this article describes how to implement a range generator in c11 generator in c,['c++'] +428631,how can pass multiple parameters in nsurl string in ios i am developing one app in that app i need pass more than one parameters at a time in nsurlmy code is responsedata nsmutabledata data retainarrdata nsmutablearray arraynsurl url nsurl urlwithstringnsstring stringwithformattoqstrfromstrtostrgonsurlrequest request nsurlrequest requestwithurlnsurl urlwithstringurlnsurlrequest request1 nsurlrequest requestwithurlnsurl urlwithstringtoq1strfromstrtothe above code i need to pass more than one parameter dynamically is it possible if it is then howthanks regards,"['iphone', 'ios', 'objective-c']" +428705,posting json to url via webclient in c i have some javascript code that i need to convert to c my javascript code posts some json to a web service that is been created this javascript code works fine and looks like the followingvar vm k 1 a 2 c 3 v 4 ajax url type post data jsonstringifyvm contenttype applicationjsoncharsetutf8 success action succeeded error action failedfunction action succeededr consolelogrfunction log failedr1 r2 r3 alertfaili am trying to figure out how to convert this to c my app is using net 20 from what i can tell i need to do something like the followingusing webclient client new webclient string json clientuploadstring jsoni am a little stuck at this point i am not sure what json should look like i am not sure if i need to set the content type if i do i am not sure how to do that i also saw uploaddata so i am not sure if i am even using the right method in a sense the serialization of my data is my problem can someone tell me what i am missing herethank you,['c#'] +428706,sql server convert columns to rows i have a sql table with current value and previous valueid value1 pvalue1 value2 pvalue21 a a v v12 b b1 w w13 c c1 x xi want to compare them and thisplay in a the following table if the value has changesid column value pvalue1 value2 v v12 value1 b b12 value2 w w13 value1 c c1is it possible in sql 2008 without looping each column,['sql'] +428713,what does rc for function return values mean when reading c code i often come across statements such asint rc foobar baz assertrc nullwhere the variable rc is used for checking the return value of the function i assume it is a mnemonic of some sort but cannot deduce its meaningi would like to know its meaning to help with my understanding of the code,['c'] +428772,python mock process for unit testing backgroundi am currently writing a process monitoring tool windows and linux in python and implementing unit test coverage the process monitor hooks into the windows api function enumprocesses on windows and monitors the proc directory on linux to find current processes the process names and process ids are then written to a log which is accessible to the unit testsquestionwhen i unit test the monitoring behavior i need a process to start and terminate i would love if there would be a crossplatform way to start and terminate a fake system process that i could uniquely name and track its creation in a unit testinitial ideasi could use subprocesspopen to open any system process but this runs into some issues the unit tests could falsely pass if the process i am using to test is run by the system as well also the unit tests are run from the command line and any linux process i can think of suspends the terminal nano etci could start a process and track it by its process id but i am not exactly sure how to do this without suspending the terminalthese are just thoughts and observations from initial testing and i would love it if someone could prove me wrong on either of these pointsi am using python 266editget all linux process idstry processdirectories oslistdirselfprocess directoryexcept ioerror return return pid for pid in processdirectories if pidisdigitget all windows process idsimport ctypes ctypeswintypespsapi ctypeswindllpsapidllenumprocesses selfpsapienumprocessesenumprocessesrestype ctypeswintypesboolcount 50while true build arguments to enumprocesses processids ctypeswintypesdwordcount size ctypessizeofprocessids bytes returned ctypeswintypesdword call enum processes to find all processes if selfenumprocessesctypesbyrefprocessids size ctypesbyrefbytes returned if bytes returnedvalue lt size return processids else we werent able to get all the processes so double our size and try again count 2 else print enumprocesses failed sysexitwindows code is from here,['python'] +428775,change keystore password from no password to a non blank password i have a jks keystore with no password when i run the commandkeytool list keystore mykeystorejksand it prompts me for the keystore password i simply hit enterplease note that the keystore password is not the default java password of changeit it is blankwhen i try to runkeytool storepasswd keystore mykeystorejksto change the password to a non blank string it firsts prompts me for the current password simply hitting enter since it is blank sayskeytool storepasswd keystore mykeystorejksenter keystore passwordkeystore password is too short must be at least 6 characters just to confirm with everyone that the password is not changeitkeytool storepasswd keystore mykeystorejksenter keystore password changeitkeytool error javaioioexception keystore was tampered with or password was incorrectany idea how i can change the keystore password if the existing password is blank,['java'] +428777,whats c threading type between three types of threading kernellevel userlevel and hybrid which type does c or more generally net use,"['c#', '.net']" +428821,define something 1 0 i came accros this line of codedefine cparser flags debug 1 0what does it do its the same asdefine cparser flags debug 1right,['c'] +428835,mvc4 ajaxbeginform not replacing updatetargetid there are so many topics on so about issues with the ajaxbeginform not correctly updating the target element with the return partial viewmvc4 ajax updating same pageaspnet mvc 4 ajaxbeginform and html5mvc 4 razor controller is returning a partialview but entire page is being updatedmvc 4 ajax is not updating the partialview within the pagehowever all of these are answered by either manually writing out the jquery ajax or including a missing javascript file using ajaxbeginformpostcarddetails new ajaxoptions insertionmode insertionmodereplace updatetargetid details div idpostcardsearchresults htmlrenderactionpostcardsearchresults model div div iddetails divrelevant controller codeacceptverbshttpverbspost httpverbsgetpublic actionresult postcardsearchresultspostcardsearchfilter filter postcardsearchresults model new postcardsearchresultsfilter return partialview postcardsearchresults modelin my layout i am referencing these jquery files additionally i have verified that the page is outputting the proper path and that it finds the correct files i have tried switching the ordering of unobtrusiveajaxminjs and validateminjs to no succescript typetextjavascript srcurlcontentscriptsglobalizejsscriptscript typetextjavascript srcurlcontentscriptsjquery191jsscriptscript typetextjavascript srcurlcontentscriptsjqueryui1100customminjsscriptscript typetextjavascript srcurlcontentscriptsjqueryunobtrusiveajaxminjsscriptscript typetextjavascript srcurlcontentscriptsjqueryvalidateminjsscriptscript typetextjavascript srcurlcontentscriptsjqueryvalidateunobtrusiveminjsscriptadditionally in my websites root webconfig and the webconfig in my view folder i have includedadd keywebpagesversion value20add keypreserveloginurl valuetrueadd keyclientvalidationenabled valuetrueadd keyunobtrusivejavascriptenabled valuetruei am at a loss for where else to look there are no javascript errors being thrown and the controller is being properly hit returning a partialviewresult the form element in the html is populating all the correct data attributes,['c#'] +428837,python separate processes logging to same file does pythons logging library provide serialised logging for two or more separate python processes logging to the same file it does not seem clear from the docs which i have readif so what about on completely different machines where the shared log file would exist on an nfs export accessible by both,['python'] +428890,auto layout not working i have a search bar on top of a table view set up using auto layout like so searchbartranslatesautoresizingmaskintoconstraints no tableviewtranslatesautoresizingmaskintoconstraints noselfview addconstraintsnslayoutconstraint constraintswithvisualformat searchbar options0 metricsnil viewsnsdictionaryofvariablebindings searchbarselfview addconstraintsnslayoutconstraint constraintswithvisualformat tableview options0 metricsnil viewsnsdictionaryofvariablebindings tableviewselfview addconstraintsnslayoutconstraint constraintswithvisualformatv searchbar tableview options0 metricsnil viewsnsdictionaryofvariablebindings searchbar tablevieweverything looks nice when i run it but when i do searchbarshowsscopebar yes before i start editing the search bar the search bar and table view do not resize automatically even when i do searchbar sizetofit the table view does not resize and move down whynote i am not putting the search bar as the table views header it is just a parent view and two subviewsnote 2 i checked the intrinsiccontentsize of searchbar before and after i call searchbarshowsscopebar yes and the size does indeed change,"['ios', 'objective-c']" +428925,doctrine2 class is not a valid entity or mapped super class i get exception uncaught exception doctrineormmappingmappingexception with message class users is not a valid entity or mapped super class every time when i run the next codetestphpphprequire once vendorautoloadphpuse doctrineormtoolssetupuse doctrineormentitymanagerpaths arraydirname file entitiesisdevmode false the connection configurationdbparams array driver pdo mysql user root password pass dbname snabcentrconfig setupcreateannotationmetadataconfigurationpaths isdevmodeem entitymanagercreatedbparams configuser emfindusers 5entitiesusersphpphpuse doctrineormmapping as orm users ormtablenameusers ormentity class users var integer ormcolumnnameid typeinteger nullablefalse ormid ormgeneratedvaluestrategyidentity private id var string ormcolumnnameemail typestring length255 nullabletrue private email var string ormcolumnnamepassword typestring length255 nullabletrue private password var string ormcolumnnametype typestring nullabletrue private type var string ormcolumnnameclient inn typestring length255 nullabletrue private clientinn var string ormcolumnnameclient ogrn typestring length255 nullabletrue private clientogrn var string ormcolumnnameclient rs typestring length255 nullabletrue private clientrs var string ormcolumnnameclient ks typestring length255 nullabletrue private clientks var string ormcolumnnameclient bik typestring length255 nullabletrue private clientbik var string ormcolumnnameclient uaddress typestring length255 nullabletrue private clientuaddress var string ormcolumnnameclient faddress typestring length255 nullabletrue private clientfaddress var string ormcolumnnameclient daddress typestring length255 nullabletrue private clientdaddress var string ormcolumnnamename typestring length255 nullabletrue private name var string ormcolumnnamenotes typetext nullabletrue private notes var datetime ormcolumnnameadded date typedatetime nullabletrue private addeddate get id return integer public function getid return thisid set email param string email return users public function setemailemail thisemail email return this get email return string public function getemail return thisemail set password param string password return snabusers public function setpasswordpassword thispassword password return this get password return string public function getpassword return thispassword set type param string type return snabusers public function settypetype thistype type return this get type return string public function gettype return thistype set clientinn param string clientinn return snabusers public function setclientinnclientinn thisclientinn clientinn return this get clientinn return string public function getclientinn return thisclientinn set clientogrn param string clientogrn return snabusers public function setclientogrnclientogrn thisclientogrn clientogrn return this get clientogrn return string public function getclientogrn return thisclientogrn set clientrs param string clientrs return snabusers public function setclientrsclientrs thisclientrs clientrs return this get clientrs return string public function getclientrs return thisclientrs set clientks param string clientks return snabusers public function setclientksclientks thisclientks clientks return this get clientks return string public function getclientks return thisclientks set clientbik param string clientbik return snabusers public function setclientbikclientbik thisclientbik clientbik return this get clientbik return string public function getclientbik return thisclientbik set clientuaddress param string clientuaddress return snabusers public function setclientuaddressclientuaddress thisclientuaddress clientuaddress return this get clientuaddress return string public function getclientuaddress return thisclientuaddress set clientfaddress param string clientfaddress return snabusers public function setclientfaddressclientfaddress thisclientfaddress clientfaddress return this get clientfaddress return string public function getclientfaddress return thisclientfaddress set clientdaddress param string clientdaddress return snabusers public function setclientdaddressclientdaddress thisclientdaddress clientdaddress return this get clientdaddress return string public function getclientdaddress return thisclientdaddress set name param string name return snabusers public function setnamename thisname name return this get name return string public function getname return thisname set notes param string notes return snabusers public function setnotesnotes thisnotes notes return this get notes return string public function getnotes return thisnotes set addeddate param datetime addeddate return snabusers public function setaddeddateaddeddate thisaddeddate addeddate return this get addeddate return datetime public function getaddeddate return thisaddeddate do you have any ideas why eaccelerator is not set up doctrine v 22 php v 5322 zend engine 230,['php'] +428941,how to change default jre for all eclipse workspaces i have one jre in cprogram files x86javajre6 and that was the only one at the time i installed eclipse i have subsequently installed a complete jdk in chomesftwrjdk160 21 and changed my java home environment variable to that however every time i start a new eclipse workspace it only picks up the old jre and i have to manually remove it and add the new one how do i bind my eclipse install to the new jdk so that every new workspace points to that only i checked eclipseini but there was no reference there to which jre to go toupdatei went into prefsjavainstalled jres added the new location marked it as default removed the other and it was effective only for the current workspace however when i opened a new workspace only the old jre was available so this did not change the core eclipse config that is applicable across all at least new workspaces,['java'] +428945,can a class that references itself in a static field be garbage collected public class myclass private static myclass heldinstance public myclass heldinstance this assuming an instance of myclass is not rooted in any other way will the private static reference here prevent it from being garbage collected,['c#'] +428952,using angular service to share data between controllers i am trying to have two different controllers communicate with each other controller 1function welcomectlscope emailservice scopesavefunction emailservicesaveemailahia welcomectlinject scope emailservicethis controller is designed to take the text from a text field with ngmodel aemaila and put the text into a service emailservice so it can be used in the next ngview which is controlled by the next controllerfor testing purposes i am just putting ahia directly into the saveemail functioncontroller 2function signupctlscope emailservice windowalertemailservicegetemailsignupctlinject scope emailservicefor testing purposed i am using windowalert to thisplay the value of getemailemailserviceangularmodulemyappservices serviceemailservice function var text astart valuea return saveemailfunction data text data getemailfunction return text as a result of using controller1 and controller 2 as specified with this service windowalert prints out astart valuea instead of ahiawhen i put more windowalert functions in the code to see what is happening i see that when save is called controller 1 executes and saves a value into the service and expressjs loads the next page then controller2 activates when controller 2 activates it reinitializes the service setting text back to astart valuea then when getemail is called it return the value astart valueathis confuses me because i was under the impression that services were not initialized every time the were included in a controller consulted resourcesbetter design for passing data to other ngviews in angularjs persisting it across controllersi am also working off of the angularexpreseed,['javascript'] +428954,d3js force directed layout constrained by a shape i was wondering if there is a way to create a force directed layout with d3js and restrict it by an arbitrary shape in such a way that all the nodes are equivalently thistributed within the shape andthe thistance between the border and the nodes is equally to the thistance between the nodesi hope there is already such a solution out there otherwise my idea is to start with the force directed layout and check the thistances from the nodes to the borders in each iteration any suggestions from yourside,['javascript'] +428973,changing my query and causing sql exception i am lovin miniprofiler for our net project however i am running into an issue the profiler is actually causing queries to be slightly different which is causing errors for example when the profiler is not initialized a sql query is generated which contains nvarchar40 however with the profiler initialized that part of the query has been changed to nvarcharmax this causes the following sqlexception the fulltext query parameter for fulltext query string is not validi have not found anybody with a very similar issueone solution would be to be able to dynamically deinitialize miniprofiler somehow before this specific query is executed so that for just this one query the default dbproviderfactory would be used rather than miniprofilers dbproviderfactory however this does not seem to be supported,['.net'] +428974,create layer list with rounded corners programmatically i am currently trying to convert the following xml to be created programmatically so that i can set the top corners and bottom corners as needed throughout my project it is a simple layer list that has two rectangles one on top of another i would like to use this as a background for a few different views so it is important that the result scales layerlist xmlnsandroid item androidbottom20dp shape androidshaperectangle size androidheight20dp solid androidcolor969595 corners androidradius 0dp androidtopleftradius5dp androidtoprightradius5dp shape item item androidtop20dp shape androidshaperectangle size androidheight20dp solid androidcolor7b7979 corners androidradius 0dp androidbottomleftradius5dp androidbottomrightradius5dp shape itemlayerlistthis approach does work but i need a separate xml for each shape depending upon whether i want the top bottom both or none of the corners rounded my current attempts at creating the same drawable have yielded nothing more than two rectangles with one on top of the other i could not figure out how to set the positions of the rectangles i could see no visible change regardless of what the bounds of the shape were set to any suggestions would be greatly appreciated usage setbackgrounddrawablenew dualcolorstatedrawable0 10fprivate final int topcolorunselected colorredprivate final int bottomcolorunselected colorgreenprivate final int topcolorselected coloryellowprivate final int bottomcolorselected colorblueprivate final int m nzero radius 0class dualcolorstatedrawable extends statelistdrawable public nywtableviewcellstatedrawablefloat topradius float bottomradius addstatenew int androidrattrstate pressed createlistwithselectedstatefalse topradius bottomradius addstatenew int androidrattrstate pressed createlistwithselectedstatetrue topradius bottomradius public drawable createlistwithselectedstate boolean isselected float topradius float bottomradius int topcolor bottomcolor if isselected topcolor topcolorselected bottomcolor bottomcolorselected else topcolor topcolorunselected bottomcolor bottomcolorunselected int x 10 int y 10 int width 20 int height 20 roundrectshape rrstopshape new roundrectshapegetradiitopradius m nzero radius null null customshapedrawable csdtopshape new customshapedrawable rrstopshape topcolor roundrectshape rrsbottomshape new roundrectshapegetradiim nzero radius bottomradius null null customshapedrawable csdbottomshape new customshapedrawable rrsbottomshape bottomcolor csdbottomshapesetboundsx y x width y height return new layerdrawablenew drawable csdtopshape csdbottomshape private float getradiifloat top float bottom return new float top top top top bottom bottom bottom bottom class customshapedrawable extends shapedrawable private final paint fillpaint public customshapedrawableshape s int fill supers fillpaint new paintthisgetpaint fillpaintsetcolorfill override protected void ondrawshape shape canvas canvas paint paint shapedrawcanvas fillpaint,['android'] +429005,get load at a moment in time or getloadavg for a smaller time period in python in linux centos currently am using pythons osgetloadavg to get an idea of the current load on the server centos 63according to the python documentation osgetloadavg returns the number of processes in the system run queue averaged over the last 1 5 and 15 minutes osgetloadavgreturn the number of processes in the system run queue averaged over the last 1 5 and 15 minutes or raises oserror if the load average was unobtainablequestionis it possible to get the number of processes in the system run queueat the current instantif not is it possible to get the average over a shorter period oftime like the last 5 or 10 secondsthe reason i am asking is because i am getting the load average then if it is too high am killing some processes this can potentially happen many times per minute so am concerned too many processes will be killed before the 1 minute average catches upthanks,['python'] +429014,jquery select2 how to access ajax data at onchange function i am using select2 with ajax everything works fine when the user click on the item they want i use the onchange function as specified by the documentation for doing some stuff e6onchange functione inputdestinationvaleval the return value eval is the dataid value from the ajax call but my data object has name id and type i can add code to dataformatselection but this does not sound logic and is confusing function dataformatselectiondata consolelogdataname dataid datatype return dataname how can i access the whole data object instead of just dataid at the onchange event,['jquery'] +429027,how to make a parent div auto size to the width of its children divs i am trying to make the parent div only as wide as the child divs auto width is making the parent div fit the entire screen the children divs will be different widths depending on their content so i need the parent div to adjust accordingly thanks for your help div stylewidthauto div stylewidth 135px float left h4 stylepaddingright 5px paddingleft 15pxcolumn1h4 dl stylepaddingright 5px paddingleft 15px margintop 8px overflowx hidden dd stylewhitespace nowrap1dd dd stylewhitespace nowrap2dd dl h4 stylepaddingright 5px paddingleft 15pxcolumn1h4 dl stylepaddingright 5px paddingleft 15px margintop 8px overflowx hidden dd stylewhitespace nowrap1dd dd stylewhitespace nowrap2dd dl div div stylewidth 135px float right h4 stylepaddingright 5px paddingleft 10pxcolumn2h4 dl stylepaddingright 5px paddingleft 15px margintop 8px overflowx hidden dd stylewhitespace nowrap1dd dd stylewhitespace nowrap2dd dd stylewhitespace nowrap3dd dl divdiv,['css'] +429052,how to get coordinate center of gmsmapview in iphone i am use the new google maps sdk for ioscan i get true coordinate form gmsmapviewcenter now it return value of cgpoint but this not true coordinatethank and regards,"['iphone', 'ios']" +429054,jquery on a wellformed html string results in syntax error unrecognized expression i have got a complete html document i am pulling in with ajax and my done callback looks like thisfunction data text status jq xhr var what i want datafindwhatiwantwhere data is a string that contains the entirety of a wellformed html document this code never reaches find upon data i getuncaught error syntax error unrecognized expression doctype htmlthe factsi am using jquery 190 the document is wellformed html5 according to the w3c validator i have used jquery to objectify many an html string so i am surprised this is not working admittedly i do not recall ever trying a whole document given the error i am guessing perhaps i need to escape this string somehow but i am not sure howincidentally this worksvar what i want whatiwant parsehtmldatabut i cannot figure out why the first approach fails,"['javascript', 'jquery']" +429069,how do i get class name in php public class myclass in java we can get class name with string classname myclassclassgetsimplenamehow to do this in php i already know get class but it works only for objects currently i work in active record i need statement like myclassclassname,['php'] +429070,why cannot netftp connect to server i am trying to create a script to list and download data from a ftp server with ruby i am new to ruby so i looked for documentation how to use netftp i have trouble understanding why this does not workrequire netftpserver ftpservercomuser myuserpassword mypasswordnetftpopenserver user password do ftp files ftpchdirmydirectory files ftplist puts list out of directory puts filesendthat does not work returning this errorhomeadhownrvmrubiesruby193p194libruby191netftprb298in getresp 425 failed to establish connection netftptemperror from homeadhownrvmrubiesruby193p194libruby191netftprb325in block in sendcmd from homeadhownrvmrubiesruby193p194libruby191monitorrb211in mon synchronize from homeadhownrvmrubiesruby193p194libruby191netftprb323in sendcmd from homeadhownrvmrubiesruby193p194libruby191netftprb402in transfercmd from homeadhownrvmrubiesruby193p194libruby191netftprb478in block 2 levels in retrlines from homeadhownrvmrubiesruby193p194libruby191netftprb178in with binary from homeadhownrvmrubiesruby193p194libruby191netftprb477in block in retrlines from homeadhownrvmrubiesruby193p194libruby191monitorrb211in mon synchronize from homeadhownrvmrubiesruby193p194libruby191netftprb476in retrlines from homeadhownrvmrubiesruby193p194libruby191netftprb722in list from test ftprb10in block in from homeadhownrvmrubiesruby193p194libruby191netftprb116in open from test ftprb8in can anyone explain whats wrong with my script,['ruby'] +429101,overloading not specializing templates in std namespace this is very pedantic but in c03 it was apparently nonconforming for a program to overload not specialize a template function in the std namespace see mention of this here and long thiscussion on complangcmoderatedie this was oknamespace std template void swap foo f foo g but this was not if i understand correctlynamespace std template typename t void swap tempatefoot f tempatefoot g is this still true in c11 also does this apply to template classes like stdhash too or just template functionsedit also is there any example of a standard library implementation such that the latter would break things in practice and if not is there a specific reason for thisallowing overloads like in the second case above what could potentially break in theory,['c++'] +429122,laravel eloquent orm transactions the eloquent orm is quite nice though i am wondering if there is an easy way to setup mysql transactions using innodb in the same fashion as pdo or if i would have to extend the orm to make this possible,['php'] +429125,when i load adt why do i receive the error the android sdk requires android developer toolkit version x or above i just updated my android sdk tools to version 211 unfortunately this is causing an error when i load the android developer toolkitthe android sdk requires android developer toolkit version 2110 or abovecurrent version is 21012012126258please update adt to the latest versionwhen i upgraded the sdk i was warned that i might need to upgrade adt i tried to do so by going to help check for updates unfortunately this returns a message that no updates were foundin case i have missed something heres a screenshot of my android sdk manageram i missing an install package do i need to go about updating adt eclipse another way should i just download a new copy of adt,['android'] +429152,how does ampersand in the return type of a function declaration work in this piece of code why f is declared as double f what does it mean and how does it work i do not even know what to google to find the answer to my question please helpdouble a 1 b 2double f double d d 4 return bi know ampersand sign means the address of a variable or a function but i do not see why it would make sense to write it when you are declaring a function,['c++'] +429174,youwave for android in remote desktop environment using thin client i am using youwave for android in a remote desktop environment with atrust thin client t60 series when i run the youwave emulator a black screen appears and it stops there also the home menu and other buttons except rotate button does not work when i tried to run an app it says android os not readywhen i open youwave for a second time it saysanother youwave for android is already running or previous run is cleaning up this repeats even if i tried to open waiting for few minutes is there any remedy for this,['android'] +429182,how to read multiple qr codes from one image using zxing library i am currently developing a scanner that reads multiple qr codes found in one imagei manage to read the qr codes in the image but it is giving me inconsistent results assuming there are 4 qr codes in the image sometimes i can read 2 and sometimes 3 or just 1 unlike in the original scanner zxing scanner it decodes fast while in my case i have to make sure there is enough light and the image is not blurred to decode iti am using the qrcodemultireader to decode the image currently using zxing library to create the applicationbelow is the snippet of my codepublic void onpicturetakenbyte data camera camera bitmapfactoryoptions opt new bitmapfactoryoptions optinmutable true bitmap bitmap bitmapfactory decodebytearraydata 0 datalength opt hashtabledecodehinttype object hints new hashtabledecodehinttype object hintsputdecodehinttypetry harder booleantrue luminancesource source new rgbluminancesourcebitmap qrcodemultireader multireader new qrcodemultireader result results multireaderdecodemultiplenew binarybitmap new hybridbinarizersource hints,['android'] +429199,connecting to embedded bluetooth device from android device i just started working on connecting to embedded bt device through my android phoneit is connecting fine but i am facing problem when i am not thisconnecting it properly i mean first close socket and then any io steams opened but when i turn off my bluetooth suddenly in device how will i know the bluetooth is get thisconnecting is there is any way to receive bluetooth thisconnecting listener all the time in the app any ideas thanksmmsocket devicecreaterfcommsockettoservicerecorduuidtotrytry mmsocketconnectcatch ioexception e mmsocketclose,['android'] +429200,mapping two or more arrays into one with underscorejs i would need to add elementwise several arrays that is i have several arrays of equal lenght and i would need just one with the same number of elements that are the sum of the inputs underscore has methods to fold all elements into one and to map every element using a function but i cannot find any way to combine two arrays piece wiseif my original arrays were 123456 1 and 2 the result should be 456789i know i can do it by iterating over the arrays but wonder if it would be easierfaster using underscorejs functions can i do it how,['javascript'] +429223,open application without tapping on icon is there any way by which we can launch the app by the external volume button or by any other gestures made on the iphone instead of launching by the default wayorcan our app recognise the users interaction with the volume button when app is in the background,"['iphone', 'ios']" +429275,penalty of the msvs compiler flag bigobj the basic google search bigobj issue shows that a lot of people are experiencing the fatal error c1128 number of sections exceeded object file format limit compile with bigobj the error has more chance to occur if one heavily uses a library of c templates like boost libraries or cgal librariesthat error is strange because it gives the solution to itself set the compiler flag bigobjso here is my question why is not that flag set by default there must be a penalty of using that flag otherwise it would be set by default that penalty is not documented in msdn does anybody have a cluei ask the question because i wonder if the configuration system of cgal should not set bigobj by default,['c++'] +429300,how to show values from property file in jsp in a spring mvc app i am setting my properties in appservletxml with a bean like this bean classorgspringframeworkbeansfactoryconfigpropertyplaceholderconfigurer property namelocation valuewebinfmypropertiesproperty beanmost of the time i access the properties in my controllers or other classes like thisvaluedbtypepublic string dbtypebut what if i want to use a property in a jsp file and bypass the controller meaning i do not want the value type being passed from the controller to the jsp as a model attribute is there a way to access properties directly in a jsp,['java'] +429306,how to check if a string contains only digits in java in java for string class there is a method called matches how to use this method to check if my string is having only digits using regular expression i tried with below examples but both of them returned me false as resultstring regex 09string data 23343453systemoutprintlndatamatchesregexstring regex 09string data 23343453systemoutprintlndatamatchesregex,['java'] +429336,get the class instance variables and print their values using reflection i have a 2 pojo classes with getters and settersnow i am trying to get all the class instance variables of that classi got to know that we can use reflection how to do itthis is my pojo class which will extend my reflection classclass detailsprivate int ageprivate string namereflection class is like thisclass reflectionpublic string tostringreturn all the fields of that class,['java'] +429341,guidelines to design a c library well usable from f i just want to point out that this is question is not the reverse ofbest approach for designing f libraries for use from both f and chere i am not asking how to design a functional library written c to be used in both worldsi would like to know good practices on what design choices embrace or avoid to get a reasonable compromise for make this library usable from fpractices like for examplekeep object hierarchy as simple as possibleavoid mutating state of objects but return new onesetcanyone that already done it can share it is experienceside noteit is interesting note this oss project ironjs yes it is written in f but the author expose two specialized host ironjshostingfsharp and ironjshostingcsharp,['c#'] +429346,center align a div horizontally using default twitter bootstrap css i know how to center align a div horizontally in css you need to make the width to something less than 100 and have auto margin on both left and right sides i want to do this default styles of twitter bootstrap i do not want to write additional css wondering whether it is possible to achieve using default style used in twitter bootstrapto set width of the div i am using span but span is float left is there any class which can set the width of the div but will not add float left,['css'] +429354,reducing the number of database queries in a complex custom app i inherited an ecommerce software project written in php as i was inspecting the codebase i found a lot of sql statements all over the code there are a lot of classes like product category user customer etc and every class has a lot of database queriesi did not know how to treat this situation and decided to count the total queries of a single page visit i encapsulated the mysql query function and increased a counteri was a little shocked at the result to visit the indexpage alone there were 1633 mysql select queries executed listing the products of a category triggered almost 20 queriesi piped the queries into a text file to analyze them over 90 are single select statements of maybe one or two values now what should i do to clean up this mess what is your advice i enabled caching at the mysql server loading the page takes about 490msadditional detailfor example there is a class called product inside this class there are 8 single small sql select statementswhen you now open the category listing to thisplay the products the original programmer used one select statement to get get a list of the needed products and then created a product object for each of themlet us say this result gives us 20 productsselect id from products where price 10then he iterates through the results and creates a product object for every entryqresult queryselect id from products where price 10products arrayforeach qresult as prod products new productprodidthis alone generates 20 8 sql queries just for the products and the same method is used for other classes too user customer category and so onsome time agonow after some weeksmonths have passed i wanted to share my solutions i did so fari could cut down the queries to 50 per page visit and reduced the page loading time to under 400ms i did it very easily i tried to identified the hotspots and build a table cache class each visit this static class loads the whole table content to memory and each table request from now on will served out of the memory from the static class well very dirty and not that nice but it works is faster reduces the total queries and spares the server hardwarei guess we also will throw hardware to this problem als long as the user count increases in that ratio as it did by now if we come to the point to replace the application by another we will definitely head for a databasequerynice solutionthanks all for your advices,"['php', 'mysql']" +429358,select data from two tables in mysql what i have the next structuretable zero id primary with auto increment othertable 1 id foreign key to table zero id varchar80 example value aahellob one fieldtable 2 id foreign key to table zero id varchar160 example value aaececehellob other fieldwhat i want search and get an idvarchar array containing all matches with the like str on the varchar field for example if i search with the hello string i should get both example values with their respective ids these ids are allways going to be different since they are references to a primary keywhat i tried i tried with union all but it does not work with limits in my example,['mysql'] +429373,jquery parse html without loading images i load html from other pages to extract and thisplay data from that pageget functionhtml consolelog htmlfindc1034 that does work but because of the html my browser tries to load images that are linked in 205html those images do not exists on my domain so i get a lot of 404 errorsis there a way to parse the page like html but without loading the whole page into my browser,"['javascript', 'jquery']" +429381,time thisplayed in logcat i need to get the android device timestamp in the format hhmms i am able to view the time thisplayed in the logcat of eclipse is it the computers time or is it the android devices time,['android'] +429382,writing binary number system in c code as we use 0x prefix for hex numbers and o for octal ones is there anything that can be done for binary numbersi tried the b suffix but the gcc did not allow iterror invalid suffix b on integer constantis it possible,['c'] +429408,how to track event changes to a polygon with google maps api i am currently building a search an area feature for a site were working on a bit like the one on rightmovei have got everything up and running except the ability to track event changes to a polygon the setting of new points and altering existing ones i need to be able to post the coordinates to the form for submissioni have tried the google code docs for editing events and every time i try it out i either get a message about set at not being possible or my object not being definedi suppose the bit i know is wrong is thepolygon variable not being passed through to the new googlemapseventaddlistenerthepolygon set at function grab paths for infowindow grabpathsthepath but i do not know why it is a global variable or is notso the question is how can i track the changes to the polygon to pass the updated coordinates through to my formall help is greatly appreciatedhere is the code i currently havevar mapoptions optionsvar map new googlemapsmapdocumentgetelementbyidmap mapoptionsvar drawingmanager new googlemapsdrawingdrawingmanager drawingmode googlemapsdrawingoverlaytypepolygon drawingcontrol false polygonoptions drawing options drawingmanagersetmapmapgooglemapseventaddlistenerdrawingmanager polygoncomplete functionpolygon complete functionsgooglemapseventaddlistenerthepolygon set at function complete functionsgooglemapseventaddlistenerthepolygon insert at function complete functions,['javascript'] +429422,switching updown the stack with getcontextsetcontext i am trying to understand if getcontextsetcontext will work correctly in a specific scenarioi can see how setcontext can be used to unwind the stack back to a certain place in historyinclude stdiohinclude ucontexthint rollback 0ucontext t contextvoid funcvoid setcontextcpint mainvoid getcontextcontext if rollback 0 printfgetcontext has been calledn rollback func else printfsetcontext has been calledn but i was wondering if after an unwind you can rewind back to a place that was in the future i suppose this depends on the getcontext call captures a copy of the stack and i cannot find the exact details in the documentationinclude stdiohinclude ucontexthint rollback 0int backtofuture 0ucontext t contextucontext t futurecontextvoid funcvoid some complex calc if somecondition getcontextfuturecontext after returning i want to come back here to carry on with my work if backtofuture 0 setcontextcontext rewind to get stuffdone finishe workint mainvoid getcontextcontext if rollback 0 printfgetcontext has been calledn rollback func eventually always return here else printfsetcontext has been calledn do specialized work that needed to be done may involve function calls i worry that anything the adds new stack frames will thisrupt the saved state of futurecontext but without detailed information i can not be sure if this is an allowed senario backtofuture 1 setcontextfuturecontext,['c'] +429440,cannot inspect variables when debugging net asyncawait functions i have a net 45 proj that is using asyncawait functionalitywhen i try to inspectquickwatch a variable reference after an await statement i get the followingthe name id does not exist in the current contextknow how to fix this so i can debug itedit heres the code fact public async task works as expected var repo configiocgetinstanceiasyncrepositorycustomer var work configiocgetinstanceiunitofwork customer c new customer firstname micah lastname smith test datecreated datetimenow datemodified datetimenow email phone 72451212 var idawait repoinsertc i cannot inspect the value of id asserttrueid 0,['c#'] +429441,vbos slower than obsolete method of drawing primitives why i am working on a tilebased opengl c application i am adding sample screen from application so that it will be more cleari have tile class which contains an array of objects each tile can store up to 15 objects the example of that is tile with green and yellow square on it two objects so it is 10x10x15 1500 objects to draw in the worst case because i am not handling empty ones usually it is less in my testings i use around 600 of them object has it is own graphic that can be drawn each object belongs to one tile at a time but it can be moved as for example red squares in the picture objects backgrounds are going to have a border and they need to be nicely scalable so i am using 9patch pattern to draw them they are made of 9 quads without drawing tiles their objects to be precise my application has around 600 fps at first i have been using obsolete method to draw those tiles using glbegingl quadsglend and glthisplaylists i had a big drop of performance due to that drawing from 600 to 320 fps this is how i have been drawing thembool backgrounddrawconst tpoint pos int width int height ifwidth 0 height 0 return false glfrontfacegl cw glpushmatrix gltranslatefglfloatposx glfloatposy 00f move background to right direction ifwidth m savedwidth height m savedheight if size to draw is different than the one saved in thisplay list then recalculate everything and save in thisplay list that size will be now saved in thisplay list m savedwidth width m savedheight height if this background does not have unique thisplay list id specified yet then let opengl generate one ifm thisplaylistid no thisplay list id gluint thisplaylist thisplaylist glgenlists1 m thisplaylistid thisplaylist glnewlistm thisplaylistid gl compile glfloat texelcentersoffsetx glfloat12m width instead of coordinates range 01 we need to specify new ones glfloat maxtexcoordwidth m btiling glfloatwidthm width 10 glfloat maxtexcoordheight m btiling glfloatheightm height 10 glfloat maxtexcoordborderx glfloatm borderwidthm width glfloat maxtexcoordbordery glfloatm borderwidthm height 9cellpattern 1 2 3 4 9 5 6 7 8 glbindtexturegl texture 2d m texture select our texture top left quad 1 glbegingl quads bottom left gltexcoord2f00 maxtexcoordbordery glvertex2i0 0 m borderwidth top left gltexcoord2f00 00 glvertex2i0 0 top right gltexcoord2fmaxtexcoordborderx 00 glvertex2i0 m borderwidth 0 bottom right gltexcoord2fmaxtexcoordborderx maxtexcoordbordery glvertex2i0 m borderwidth 0 m borderwidth glend top middle quad 2 glbegingl quads bottom left gltexcoord2fmaxtexcoordborderx texelcentersoffsetx maxtexcoordbordery glvertex2i0 m borderwidth 0 m borderwidth top left gltexcoord2fmaxtexcoordborderx texelcentersoffsetx 00 glvertex2i0 m borderwidth 0 top right gltexcoord2fglfloat10 maxtexcoordborderx texelcentersoffsetx 00 glvertex2i0 width m borderwidth 0 bottom right gltexcoord2fglfloat10 maxtexcoordborderx texelcentersoffsetx maxtexcoordbordery glvertex2i0 width m borderwidth 0 m borderwidth glend top right quad 3 glbegingl quads bottom left gltexcoord2fglfloat10 maxtexcoordborderx maxtexcoordbordery glvertex2i0 width m borderwidth 0 m borderwidth top left gltexcoord2fglfloat10 maxtexcoordborderx 00 glvertex2i0 width m borderwidth 0 top right gltexcoord2f10 00 glvertex2i0 width 0 bottom right gltexcoord2f10 maxtexcoordbordery glvertex2i0 width 0 m borderwidth glend middle left quad 4 glbegingl quads bottom left gltexcoord2f00 glfloat10 maxtexcoordbordery glvertex2i0 0 height m borderwidth top left gltexcoord2f00 maxtexcoordbordery glvertex2i0 0 m borderwidth top right gltexcoord2fmaxtexcoordborderx maxtexcoordbordery glvertex2i0 m borderwidth 0 m borderwidth bottom right gltexcoord2fmaxtexcoordborderx glfloat10 maxtexcoordbordery glvertex2i0 m borderwidth 0 height m borderwidth glend middle right quad 5 glbegingl quads bottom left gltexcoord2fglfloat10 maxtexcoordborderx glfloat10 maxtexcoordbordery glvertex2i0 width m borderwidth 0 height m borderwidth top left gltexcoord2fglfloat10 maxtexcoordborderx maxtexcoordbordery glvertex2i0 width m borderwidth 0 m borderwidth top right gltexcoord2f10 maxtexcoordbordery glvertex2i0 width 0 m borderwidth bottom right gltexcoord2f10 glfloat10 maxtexcoordbordery glvertex2i0 width 0 height m borderwidth glend bottom left quad 6 glbegingl quads bottom left gltexcoord2f00f 10 glvertex2i0 0 height top left gltexcoord2f00f glfloat10 maxtexcoordbordery glvertex2i0 0 height m borderwidth top right gltexcoord2fmaxtexcoordborderx glfloat10 maxtexcoordbordery glvertex2i0 m borderwidth 0 height m borderwidth bottom right gltexcoord2fmaxtexcoordborderx 10 glvertex2i0 m borderwidth 0 height glend bottom middle quad 7 glbegingl quads bottom left gltexcoord2fmaxtexcoordborderx texelcentersoffsetx 10 glvertex2i0 m borderwidth 0 height top left gltexcoord2fmaxtexcoordborderx texelcentersoffsetx glfloat10 maxtexcoordbordery glvertex2i0 m borderwidth 0 height m borderwidth top right gltexcoord2fglfloat10 maxtexcoordborderx texelcentersoffsetx glfloat10 maxtexcoordbordery glvertex2i0 width m borderwidth 0 height m borderwidth bottom right gltexcoord2fglfloat10 maxtexcoordborderx texelcentersoffsetx 10 glvertex2i0 width m borderwidth 0 height glend bottom right quad 8 glbegingl quads bottom left gltexcoord2fglfloat10 maxtexcoordborderx 10 glvertex2i0 width m borderwidth 0 height top left gltexcoord2fglfloat10 maxtexcoordborderx glfloat10 maxtexcoordbordery glvertex2i0 width m borderwidth 0 height m borderwidth top right gltexcoord2f10 glfloat10 maxtexcoordbordery glvertex2i0 width 0 height m borderwidth bottom right gltexcoord2f10 10 glvertex2i0 width 0 height glend glfloat xtexoffset glfloat ytexoffset ifm borderwidth 0 glbindtexturegl texture 2d m centertexture if there is a border we have to use second texture now for middle quad xtexoffset 00 we are using another texture so middle middle quad ytexoffset 00 has to be texture with a whole texture else do not bind any texture here were still using the same one xtexoffset maxtexcoordborderx but it implies using offset which equals ytexoffset maxtexcoordbordery maximum texture coordinates middle middle quad 9 glbegingl quads bottom left gltexcoord2fxtexoffset maxtexcoordheight ytexoffset glvertex2i0 m borderwidth 0 height m borderwidth top left gltexcoord2fxtexoffset ytexoffset glvertex2i0 m borderwidth 0 m borderwidth top right gltexcoord2fmaxtexcoordwidth xtexoffset ytexoffset glvertex2i0 width m borderwidth 0 m borderwidth bottom right gltexcoord2fmaxtexcoordwidth xtexoffset maxtexcoordheight ytexoffset glvertex2i0 width m borderwidth 0 height m borderwidth glend glendlist glcalistm thisplaylistid now we can call earlier or now created thisplay list glpopmatrix return truethere is probably too much of code there but i wanted to show everything the main thing about this version is use of thisplay lists and glvertex2i which are deprecated i thought the problem of such slow down was use of this obsolete method which i read is quite slow so i decided to go for vbo i have used this tutorial and according to it i changed my method like thisbool backgrounddrawconst tpoint pos int width int height ifwidth 0 height 0 return false glpushmatrix gltranslatefglfloatposx glfloatposy 00f move background to right direction ifwidth m savedwidth height m savedheight if size to draw is different than the one saved in thisplay list then recalculate everything and save in thisplay list that size will be now saved in thisplay list m savedwidth width m savedheight height glfloat texelcentersoffsetx glfloat12m width instead of coordinates range 01 we need to specify new ones glfloat maxtexcoordwidth m btiling glfloatwidthm width 10 glfloat maxtexcoordheight m btiling glfloatheightm height 10 glfloat maxtexcoordborderx glfloatm borderwidthm width glfloat maxtexcoordbordery glfloatm borderwidthm height 9cellpattern each number represents one quad 1 2 3 4 9 5 6 7 8 how vertices are thistributed on one quad made of two triangles v1 v0 v2 v3 glfloat vertices top left quad 1 m borderwidth 0 0 v0 0 0 0 v1 0 m borderwidth 0 v2 0 m borderwidth 0 v2 m borderwidth m borderwidth 0 v3 m borderwidth 0 0 v0 top middle quad 2 widthm borderwidth 0 0 v0 m borderwidth 0 0 v1 m borderwidth m borderwidth 0 v2 m borderwidth m borderwidth 0 v2 widthm borderwidth m borderwidth 0 v3 widthm borderwidth 0 0 v0 top right quad 3 width 0 0 v0 widthm borderwidth 0 0 v1 widthm borderwidth m borderwidth 0 v2 widthm borderwidth m borderwidth 0 v2 width m borderwidth 0 v3 width 0 0 v0 middle left quad 4 m borderwidth m borderwidth 0 v0 0 m borderwidth 0 v1 0 heightm borderwidth 0 v2 0 heightm borderwidth 0 v2 m borderwidth heightm borderwidth 0 v3 m borderwidth m borderwidth 0 v0 middle right quad 5 width m borderwidth 0 v0 widthm borderwidth m borderwidth 0 v1 widthm borderwidth heightm borderwidth 0 v2 widthm borderwidth heightm borderwidth 0 v2 width heightm borderwidth 0 v3 width m borderwidth 0 v0 bottom left quad 6 m borderwidth heightm borderwidth 0 v0 0 heightm borderwidth 0 v1 0 height 0 v2 0 height 0 v2 m borderwidth height 0 v3 m borderwidth heightm borderwidth 0 v0 bottom middle quad 7 widthm borderwidth heightm borderwidth 0 v0 m borderwidth heightm borderwidth 0 v1 m borderwidth height 0 v2 m borderwidth height 0 v2 widthm borderwidth height 0 v3 widthm borderwidth heightm borderwidth 0 v0 bottom right quad 8 width heightm borderwidth 0 v0 widthm borderwidth heightm borderwidth 0 v1 widthm borderwidth height 0 v2 widthm borderwidth height 0 v2 width height 0 v3 width heightm borderwidth 0 v0 middle middle quad 9 widthm borderwidth m borderwidth 0 v0 m borderwidth m borderwidth 0 v1 m borderwidth heightm borderwidth 0 v2 m borderwidth heightm borderwidth 0 v2 widthm borderwidth heightm borderwidth 0 v3 widthm borderwidth m borderwidth 0 v0 copyvertices vertices 162 m vcoords 162 because we have 162 coordinates int datasize 162 sizeofglfloat m vboid createvbom vcoords datasize bind vbos for vertex array glbindbufferarbgl array buffer arb m vboid for vertex coordinates glenableclientstategl vertex array activate vertex coords array glvertexpointer3 gl float 0 0 gldrawarraysgl triangles 0 162 glthisableclientstategl vertex array deactivate vertex array bind with 0 so switch back to normal pointer operation glbindbufferarbgl array buffer arb no vbo id glpopmatrix return trueit is quite similar to previous version but instead of glthisplaylist and glvertex2i i used vbo which is being created from data stored in an array but results thisappointed me because i got performance drop instead of boost i got barely 260 fps and i must note that in this method version i have not yet implemented use of textures so there are only quads for now without any texture bound to it i have read a few articles to find what could be the reason of such slow down and found out that maybe it is due to big amount of small vbos and i should probably have one vbo containing all backgrounds data instead of separate vbo for each background but the problem is that objects can move around and they have different textures and texture atlas is not a good solution for me so it would be difficult for me to update those changes for those objects that changed their state for now when objects is being changed i just recreate it is vbo and the rest vbos stay untouched so my question is what am i doing wrong does using bigger 600 number of small vbos is really slower than obsolete method of drawing with glvertex2i and what could be maybe not the best but better solution in my case,['c++'] +429478,when to use nan or infinity what are the benefits of nan positiveinfinity or negativeinfinity for float and double when to use or avoid themif there are constants like these why floatparsea throw error rather than returning floatnanedithow nan is different than null why division by zero is even possible for floating types,['c#'] +429507,css text align justify big spaces to format paragraphs i use textalignjustify but i have one problem that there are big spaces between words for ie the solution is to use textjustify thistribute but chrome does not support this my question is what should i use for chrome and firefoxexample of big spaces,['css'] +429511,some doubts about rowmapper use in jdbc in a spring framework application i am studying how to execute query on a database using jdbc in spring frameworki am following this tutorial jdbc examplehtmin this tutorial i define a studentdao interface which only define the crud method that i wantthen is defined the student class that is the entity that i want to persist on the student database tablethen is defined the studentmapper class that is a specific implementation of rowmapper interface that in this case is used to map a specific record in the resultset returned by a query to a student objectthen i have the studentjdbctemplate that rappresent the implementation of my studentdao interface in this class i implement the crud method that was defined in the interfaceok and now i have a doubt about how the studentmapper class work in this studentjdbctemplate class there is defined the method that return the list of all record that are in the student database table this one public liststudent liststudents string sql select from student list student students jdbctemplateobjectquerysql new studentmapper return students how you can see this method return a list of student object and work in the following waythe first thing that it do is to define the query that return all record in the student database table in the sql stringthen this query is executed by the query method call on the jdbctemplateobject object that is an istance of jdbctemplate spring classthis method take two parameter the sql string that contains the sql query that must be executed and a new studentmapper object that take the resultset object returned by the query and map it is record on a new student objectreading here sayas that execute a query given static sql mapping each row to a java object via a rowmappermy doubt is related to the fact that my studentmapper map a resultset record on a student object using the maprow method this is the codepackage comtutorialspointimport javasqlresultsetimport javasqlsqlexceptionimport orgspringframeworkjdbccorerowmapperpublic class studentmapper implements rowmapperstudent public student maprowresultset rs int rownum throws sqlexception student student new student studentsetidrsgetintid studentsetnamersgetstringname studentsetagersgetintage return student so who call this maprow method is it called automatically by the spring framework because in this example is never called manuallytnxandreathen this query is executed by the query method call on the jdbctemplateobject object that is an istance of jdbctemplate spring class,['java'] +429554,compilation error cs0016 could not write to output file in briefwhen i attempt to browse my website i get the following error messagecs0016 could not write to output file cwindowsmicrosoftnetframework64v2050727temporary aspnet fileswxyzabdll the directory name is invalidin detaili have two websites on my development pc fictitious namesweb2 this is written in aspnet using net 35 and runs in an apool that addresses the v20 net framework and runs in an integrated mode this is developed using visual studio 2010web4 this is written in aspnet using net 45 and runs in an apool that addresses the v40 net framework and runs in an integrated mode this is developed using visual studio 2012recently i have been working in vs2012 on web4 almost constantly and it works fine however the other day i tried to run web2 and got the exception thisplayed abovebizarrely part of the path which i replaced above with letters z appear to point to a german language path since it is dede i am not operating in german so i have no idea where it got this idea fromone thing that is almost certainly unrelated but for some unknown reason i feel it is important to mention i was using the performance analysis tool in visual studio 2012 the day before this problem first appeared and i do not know if this might have made some changes to my computerattempted fixesthere are quite a few threads regarding this on the internet some threads end in success where file access permissions have been altered whilst others finish on a somewhat desperate sounding note i have gone through the process of comparing the ntfs permissions on all relevant sounding directories on my pc with that of a colleagues on whose machine this is still working unfortunately no joy to be had therei have also uninstalled aspnet 20 and reinstalled it usingcwindowsmicrosoftnetframework64v2050727aspnet regiisexe ucwindowsmicrosoftnetframework64v2050727aspnet regiisexe irand again no joy to be had there eithermy web4 continues to run unaffectedalso fyi using iis 75 on win7 x64i am now turning to the this wider audience in the hope of turning my current state of despair into one of successthanks everyonegriff,['asp.net'] +429612,d3 seems to assume i know the column names of a csv i have csv files that are generated and i am trying to load them into d3 to graph them the column names are based on the data so i essentially cannot know them in advance with testing i am able to load this data and graph it all well and nice if i know the names of the columnsbut i do not in my use case how can i handle this in d3 i cannot seem to find anything to helpreference this online or in the documentation i can see when i log to the console data0 from d3csv that there are two columns and the values read for them but i do not know how to refer arbitrarily to column 1 or 2 of the data without knowing the name of the column ahead of time i would like to avoid that in general knowing my timestamps are in column 1 and my data is in column 2 if that makes senseedit my answer uses d3entries to help learn the name of the unknown column and then continues to access all objects with that indexd3csvexportcsv functionerror data var mappedarray d3entriesdata0 var valuekey mappedarray1key dataforeachfunctiond dvalue dvaluekey,['javascript'] +429642,javalangverifyerror expecting a stackmap frame at branch target jdk 17 after upgrading to jdk 17 i am getting below exceptionjavalangverifyerror expecting a stackmap frame at branch target 71 in method comabcdomainmypackagemyclassjaxbaccessorm getdescription setdescription java lang stringgetljavalangobjectljavalangobject at offset 20 at javalangclassgetdeclaredconstructors0native method at javalangclassprivategetdeclaredconstructorsclassjava2413 at javalangclassgetconstructor0classjava2723 at javalangclassnewinstance0classjava345 at javalangclassnewinstanceclassjava327 at comsunxmlinternalbindv2runtimereflectoptoptimizedaccessorfactoryinstanciateoptimizedaccessorfactoryjava184 at comsunxmlinternalbindv2runtimereflectoptoptimizedaccessorfactorygetoptimizedaccessorfactoryjava129 at comsunxmlinternalbindv2runtimereflectaccessorgettersetterreflectionoptimizeaccessorjava384 at comsunxmlinternalbindv2runtimepropertysingleelementleafpropertyinitsingleelementleafpropertyjava72 at sunreflectnativeconstructoraccessorimplnewinstance0native method at sunreflectnativeconstructoraccessorimplnewinstancenativeconstructoraccessorimpljava57 at sunreflectdelegatingconstructoraccessorimplnewinstancedelegatingconstructoraccessorimpljava45 at javalangreflectconstructornewinstanceconstructorjava525 at comsunxmlinternalbindv2runtimepropertypropertyfactorycreatepropertyfactoryjava113 at comsunxmlinternalbindv2runtimeclassbeaninfoimplinitclassbeaninfoimpljava166 at comsunxmlinternalbindv2runtimejaxbcontextimplgetorcreatejaxbcontextimpljava494 at comsunxmlinternalbindv2runtimejaxbcontextimplinitjaxbcontextimpljava311 at comsunxmlinternalbindv2runtimejaxbcontextimplinitjaxbcontextimpljava126 at comsunxmlinternalbindv2runtimejaxbcontextimpljaxbcontextbuilderbuildjaxbcontextimpljava1148 at comsunxmlinternalbindv2contextfactorycreatecontextcontextfactoryjava130 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava57 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43 at javalangreflectmethodinvokemethodjava601 at javaxxmlbindcontextfindernewinstancecontextfinderjava248 at javaxxmlbindcontextfindernewinstancecontextfinderjava235 at javaxxmlbindcontextfinderfindcontextfinderjava445 at javaxxmlbindjaxbcontextnewinstancejaxbcontextjava637 at javaxxmlbindjaxbcontextnewinstancejaxbcontextjava584 at comabcdomainmypackagemyclassmarshalfacetstestmyclassjava73 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava57 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43 at javalangreflectmethodinvokemethodjava601 at orgtestnginternalmethodinvocationhelperinvokemethodmethodinvocationhelperjava80 at orgtestnginternalinvokerinvokemethodinvokerjava714 at orgtestnginternalinvokerinvoketestmethodinvokerjava901 at orgtestnginternalinvokerinvoketestmethodsinvokerjava1231 at orgtestnginternaltestmethodworkerinvoketestmethodstestmethodworkerjava128 at orgtestnginternaltestmethodworkerruntestmethodworkerjava1 at orgtestngtestrunnerprivateruntestrunnerjava767 at orgtestngtestrunnerruntestrunnerjava617 at orgtestngsuiterunnerruntestsuiterunnerjava334 at orgtestngsuiterunnerrunsequentiallysuiterunnerjava329 at orgtestngsuiterunnerprivaterunsuiterunnerjava291 at orgtestngsuiterunnerrunsuiterunnerjava240 at orgtestngsuiterunnerworkerrunsuitesuiterunnerworkerjava52 at orgtestngsuiterunnerworkerrunsuiterunnerworkerjava86 at orgtestngtestngrunsuitessequentiallytestngjava1203 at orgtestngtestngrunsuiteslocallytestngjava1128 at orgtestngtestngruntestngjava1036 at orgtestngremoteremotetestngrunremotetestngjava1 at orgtestngremoteremotetestnginitandrunremotetestngjava204 at orgtestngremoteremotetestngmainremotetestngjava175,['java'] +429676,audiotrack short array to byte array thistortion using jlayerjava mp3 decoder i am using jlayer to decode mp3 data with this callsamplebuffer output samplebuffer decoderdecodeframeframeheader bitstreamthis call which returns the decoded data returns an array of short outputgetbufferwhen i call audiotrack write with that method it plays fine as i loop through the fileatwriteoutputgetbuffer 0 outputgetbufferlengthhowever when i convert the short array to byte array using any of the methods in this answer the sound gets thistorted and jitteryatwriteoutputgetbuffer 0 outputgetbufferlengthbecomes byte array shorttobyte twiddle methodoutputgetbufferatwritearray 0 arraylengtham i doing anything wrong and what can i do to fix it unfortunately i need the pcm data to be in a byte array for another 3rd party library i am using the file is 22khz if that matters and this is how at is being instantiatedat new audiotrackaudiomanagerstream music 22050 audioformatchannel out stereo audioformatencoding pcm 16bit 10 10 second buffer audiotrackmode stream thank you so much in advanceedit this is how i am instantiating the audiotrack variable now so for 44khz files the value that is getting sent is 44100 while for 22khz files the value is 22050at new audiotrackaudiomanagerstream music decodergetoutputfrequency decodergetoutputchannels 1 audioformatchannel out stereo audioformatchannel out mono audioformatencoding pcm 16bit 10 10 second buffer audiotrackmode streamthis is decode methodpublic byte decodeinputstream inputstream int startms int maxms throws ioexception bytearrayoutputstream outstream new bytearrayoutputstream1024 float totalms 0 boolean seeking true try bitstream bitstream new bitstreaminputstream decoder decoder new decoder boolean done false while done header frameheader bitstreamreadframe if frameheader null done true else totalms frameheaderms per frame if totalms startms seeking false if seeking loggerdebughandling header frameheaderlayer string samplebuffer output samplebuffer decoderdecodeframeframeheader bitstream short pcm outputgetbuffer for short s pcm outstreamwrites 0xff outstreamwrites 8 0xff if totalms startms maxms done true bitstreamcloseframe return outstreamtobytearray catch bitstreamexception e throw new ioexceptionbitstream error e catch decoderexception e throw new ioexceptiondecoder error e this is how it sounds wait a few seconds and this is the actual file edit i would have loved to have split the bounty but instead i have given the bounty to bill and the accepted answer to neil both were a tremendous help for those wondering i ended up rewriting the sonic native code which helped me move along the process,"['java', 'android']" +429690,mysql unknown i just thiscovered you can write something likeselect null is unknownwhich returns 1 are there any other places you can use unknown it does not appear to be a keyword cannot do select unknown null is null is also true so what purpose does unknown have,['mysql'] +429701,measuring c async data access using stopwatch class i have the following code and it seems the elapsed milliseconds are inaccurate public async taskactionresult index try var connstring roleenvironmentisemulated configurationmanagerconnectionstringspocconnectionstring configurationmanagerconnectionstringspocvmconnectionstring var repository new accountrepositoryconnstring var stopwatch new stopwatch stopwatchstart var accounts await repositorygetall stopwatchstop viewbagaccounts accounts viewbagvmstatus stopwatchelapsedmilliseconds catch exception e blah blah blah return view does this look correct or am i missing something painfully obvious,['c#'] +429702,why are kdtrees so damn slow for nearest neighbor search in point sets i am using cgals the latest kdtree implementation for searching nearest neighbors in point sets and also wikipedia and other resources seem to suggest that kdtrees are the way to go but somehow they are too slow and wiki also suggests their worstcase time of on which is far from idealbeginedit i am now using nanoflann which is about 10010 times faster than the equivalent in cgal for kneighbor search and i am using intel embree for raycasting which is about 100200 times faster than cgals aabb treesendeditmy task looks like thisi have a huge point set say like up to a few 100 mio points and their thistribution is on surfaces of triangulated geometry yes a photon tracer so one could say that their thistribution is 2d in 3d space because it is sparse in 3d but dense when looking at the surfaces this could be the problem right because to me this seems to trigger the worstcase performance of a kdtree which probably could deal much better with 3d dense point setscgal is quite good at what it does so i have a bit doubt that their implementation just sucks their aabb tree i am using for raytracing burns a straight billion raytraces in a few mintues in the ground that is remarkable i guess but their kdtree on the other hand cannot even deal with a mio points and 250k samples point queries in any reasonable timei came up with two solutions which kick the crap out of kdtrees1 use texture maps to store the photons in a linked list on the geometry this is always an o1 operation since you have to do the raycast anyway2 use view dependent sliced hashsets that is the farther away you get the more coarse the hashsets get so basically you can think of a 1024x1024x1024 raster in ndc coordinates but with hashsets to save memory in sparse areas this basically has o1 complexity and can be parallelized efficiently both for inserts microsharding and queries lockfree the former solution has the thisadvantage that it is close to impossible to average over neighboring photon lists which is important in darker regions to avoid noisethe latter solution does not have this problem and should be on par feature wise with kdtrees just that it has o1 worst case performance lolso what do you think bad kdtree implementation if not is there something better than a kdtree for bounded nearest neighbor queries i mean i have nothing against my second solution above but a proven datastructure that delivers similar performance would be nicerthankshere is the code not compilable though that i usedinclude stdafxhinclude photonmaphpragma warning push pragma warning thisable 4512 4244 4061 pragma warning thisable 4706 4702 4512 4310 4267 4244 4917 4820 4710 4514 4365 4350 4640 4571 4127 4242 4350 4668 4626 pragma warning thisable 4625 4265 4371 include cgalsimple cartesianh include cgalorthogonal incremental neighbor searchh include cgalbasich include cgalsearch traitsh include cgalpoint generators 3hpragma warning popstruct photonicpoint float vec3 const photon photon photonicpointconst photon photon photonphoton vec0 photonhitpointgetx vec1 photonhitpointgety vec2 photonhitpointgetz photonicpointvector3 pos photonnullptr vec0 posgetx vec1 posgety vec2 posgetz photonicpoint photonnullptr vec0 vec1 vec2 0 float x const return vec0 float y const return vec1 float z const return vec2 float x return vec0 float y return vec1 float z return vec2 bool operatorconst photonicpoint p const return x px y py z pz bool operatorconst photonicpoint p const return this p namespace cgal template struct kernel traitsphotonicpoint struct kernel typedef float ft typedef float rt struct construct coord iterator typedef const float result type const float operatorconst photonicpoint p const return static castconst floatpvec const float operatorconst photonicpoint p int const return static castconst floatpvec3 typedef cgalsearch traitsfloat photonicpoint const float construct coord iterator traitstypedef cgalorthogonal incremental neighbor searchtraits nn incremental searchtypedef nn incremental searchiterator nn iteratortypedef nn incremental searchtree treestruct photonmap impl tree tree photonmap implconst photonallocator allocator tree int counter 0 maxcount allocatorgetallocationcounter forauto list allocatorgetphotonlists int listlength stdminintlistsize maxcount counter counter listlength treeinsertstdbeginlist stdbeginlist listlength treebuild photonmapphotonmapconst photonallocator allocator impl stdmake sharedphotonmap implallocatorvoid photonmapsamplevector3 where float radius int mincount stdvectorconst photon outphotons nn incremental search searchimpltree photonicpointwhere int count 0 forauto p search ifpsecond radius count mincount count 50 break count outphotonspush backpfirstphoton,['c++'] +429709,android holo dialog has 2 backgrounds layered on top of one another the dialog looks like this there is a layer behind the dialog itself about 1020 pixels or so on each side the theme i am using is themeholodialogi tried creating a custom dialog with a transparent background but that did not workstyle namecustomholodialog parentandroidstylethemeholodialog item nameandroidbackgroundandroidcolortransparentitemstyledoes anyone have any ideas on this,['android'] +429725,refreshing fragment view while using fragmentstatepageradapter seems the refresh issue is thiscussed before but none of the solutions worked for mewhat i am trying to doi am using fragmentstatepageradapter each position of the adapter holds a fragment that has a linear layout that has chess like appearance with each cell represented by a checkedtextviewand a listener that should listens for clicks and removes the previous selection on the cells and makes the new selectionwhats workingeach fragment is loaded correctly with all the datadefault states calculated while the fragment is loaded in a listwhen i click a cell all the states from the saved cells list are fetched correctly and i can change see the state change in the code while debugging at the same time i assign a new state for the checkedtextview which represent a cell this is set likecheckedtextview cellview checkedtextview gridrowgetchildatc cellviewsetselectedfalse cellviewsetcheckedfalse cellviewsettagcellschessgetigetcthe issueeven though the values are stored and assigned correctly the view cannot be refreshed the values of the cells in the view do not get updated tips i have tried that did not worked1 call adapternotifydatasetchangedcan be called while using fragmentstatepageradapter only when we have overriddenoverride public int getitempositionobject object return position none 2 adding overriden methods for destroyitem and also adding the fragments to a map on getitemthis is not appropriate as i am working with fragmentstatepageradapter so the whole purpose of using this pageradapter would be gone3 calling invalidatethis is inappropriate for this scenario i need realtime refresh4 settag method in instantiateitemi do not think this is appropriate in this situationreferenced threadsrefresh images on fragmentstatepageradapter on resuming activityviewpager pageradapter not updating the viewandroid viewpager cant update dynamicallynotifydatasetchanged fails to update listviewi have tried to state my issue as clear as possible if anyone needs more clarification do askurgent replies will be highly appreciatedcheersupdatei am using the viewpagerindicator instead of the default viewpager,['android'] +429735,how to get thistinct values from an array of objects in javascript assuming i have the followingvar array namejoe age17 namebob age17 namecarl age 35 what is the best way to be able to get an array of all of the thistinct ages such that i get an result array of17 35is there some way i could alternatively structure the data or better method such that i would not have to iterate through each array checking the value of age and check against another array for its existence and add it if notif there was some way i could just pull out the thistinct ages without iteratingcurrent inefficent way i would like to improve if it means that instead of array being an array of objects but a map of objects with some unique key ie 123 that would be okay too im just looking for the most performance efficient waythe following is how i currently do it but for me iteration appears to just be crummy for efficiency even though it does workvar thistinct for var i 0 i arraylength i if arrayiage not in thistinct thistinctpusharrayiage,['javascript'] +429740,running python on windows for nodejs dependencies i am getting into a nodejs codebase which requires that i download a few dependencies via npm namely jqueryin attempting to run npm install jquery i keep getting this erroryour environment has been set up for using nodejs 0821 x64 and npmcusersmatt cashattnpm install jquerynpm http get npm http 304 npm http get npm http get npm http get npm http get npm http get npm http get npm http 304 npm http 304 npm http 304 npm http 304 npm http 304 npm http 304 npm http get npm http get npm http get npm http get npm http 304 install cusersmatt cashattnode modulesjquerynode modulescontextify nodegyp rebuildcusersmatt cashattnode modulesjquerynode modulescontextifynode cprogram filesnodejsnode modulesnpmbinnodegypbinnode modulesnodegypbinnodegypjs rebuildnpm http 304 npm http 304 npm http 304 gyp err configure errorgyp err stack error cannot find python executable python you can set the python env variablegyp err stack at failnopython cprogram filesnodejsnode modulesnpmnode modulesnodegyplibconfigurejs11314gyp err stack at cprogram filesnodejsnode modulesnpmnode modulesnodegyplibconfigurejs8211gyp err stack at objectoncomplete fsjs29715gyp err system windows nt 617601gyp err command node cprogram filesnodejsnode modulesnpmnode modulesnodegypbinnodegypjs rebuildgyp err cwd cusersmatt cashattnode modulesjquerynode modulescontextifygyp err node v v0821gyp err nodegyp v v084gyp err not oknpm err error rolling back error enotempty rmdir cusersmatt cashattnode modulesjquerynode modulesjsdomnode modulesrequesttestsnpm err error rolling back error enotempty rmdir cusersmatt cashattnode modulesjquerynode modulesjsdomnode modulesrequesttestsnpm err error rolling back errno 53npm err error rolling back code enotemptynpm err error rolling back path cusersmatt cashattnode modulesjquerynode modulesjsdomnode modulesrequesttests npm err install nodegyp rebuildnpm err cmd c nodegyp rebuild failed with 1npm errnpm err failed at the install scriptnpm err this is most likely a problem with the contextify packagenpm err not with npm itselfnpm err tell the author that this fails on your systemnpm err nodegyp rebuildnpm err you can get their info vianpm err npm owner ls contextifynpm err there is likely additional logging output abovenpm err system windows nt 617601npm err command cprogram filesnodejsnodeexe cprogram filesnodejsnode modulesnpmbinnpmclijs install jquerynpm err cwd cusersmatt cashattnpm err node v v0821npm err npm v 1211npm err code elifecyclenpm err error enoent lstat cusersmatt cashattnode modulesjquerynode modulesjsdomnode modulesrequestteststestpipesjsnpm err if you need help you may report this log atnpm err npm err or email it tonpm err npm err system windows nt 617601npm err command cprogram filesnodejsnodeexe cprogram filesnodejsnode modulesnpmbinnpmclijs install jquerynpm err cwd cusersmatt cashattnpm err node v v0821npm err npm v 1211npm err path cusersmatt cashattnode modulesjquerynode modulesjsdomnode modulesrequestteststestpipesjsnpm err fstream path cusersmatt cashattnode modulesjquerynode modulesjsdomnode modulesrequestteststestpipesjsnpm err fstream type filenpm err fstream class filewriternpm err code enoentnpm err errno 34npm err fstream stack cprogram filesnodejsnode modulesnpmnode modulesfstreamlibwriterjs28426npm err fstream stack objectoncomplete fsjs29715npm errnpm err additional logging details can be found innpm err cusersmatt cashattnpmdebuglognpm err not ok code 0cusersmatt cashattit looks like the failure is due to a missing python installation well i have installed python set the variable and rebooted and still the errorany clue as to what i am missing,['python'] +429764,ajax get a return value from php i want to alert the return value from a php method but nothing happens here is the ajax and php methods can anyone see what i am doing wrong aajax script ajax type get url donationjunk4 data datastring success functiondata alertdata aphp methodfunction junkid return works11,"['php', 'javascript', 'jquery']" +429802,bluetoothheadset why is it necessary to use a timer for calling startvoicerecognition i wrote some codes for detecting the bluetooth headset connection and start audio through the headset for api 11 and later one can call startvoicerecognition when the headset is connected so a couple of use cases is as followheadset was turned on before the application launchesthe application should check for headset connected on start and establishes audio connectionuser turns on headset during lifetime of the applicationthe application should register for broadcast of headset connection state and start audio connection when receive connected state there is a problem with the second use case when received the connected state i call startvoicerecognition but it always return false so i have to implement a timer and after about a second the call will return true i guess the os and the headset need sometime to have everything ready to workdoes anybody know how to get headset audio connection without implement a timer if it is not possible should it be the os that should take care of this situation for example a ready for audio connection broadcast instead of the applicationbelow is the complete working code for api 11 or later manifest permissions usespermission androidnameandroidpermissionbluetooth usespermission androidnameandroidpermissionbroadcast sticky code public class mainactivity extends activity protected textview minfotextview protected bluetoothadapter mbluetoothadapter protected bluetoothheadset mbluetoothheadset protected bluetoothdevice mconnectedheadset protected audiomanager maudiomanager private static final string tag bluetooth headset nonnls1 override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main minfotextview textview findviewbyidridmain textview mbluetoothadapter bluetoothadaptergetdefaultadapter if mbluetoothadapter null maudiomanager audiomanager getsystemservicecontextaudio service if maudiomanagerisbluetoothscoavailableoffcall if buildversionsdk int buildversion codeshoneycomb mbluetoothadaptergetprofileproxythis mheadsetprofilelistener bluetoothprofileheadset override protected void ondestroy superondestroy if buildversionsdk int buildversion codeshoneycomb if mbluetoothheadset null need to call stopvoicerecognition here when the app change orientation or close with headset still turns on mbluetoothheadsetstopvoicerecognitionmconnectedheadset unregisterreceivermheadsetbroadcastreceiver mcountdowncancel mbluetoothadaptercloseprofileproxybluetoothprofileheadset mbluetoothheadset logdtag ondestroy nonnls1 protected bluetoothprofileservicelistener mheadsetprofilelistener new bluetoothprofileservicelistener this method is never called even when we closeprofileproxy on onpause when or will it ever be called override public void onservicethisconnectedint profile logdtag profile listener onservicethisconnected nonnls1 mbluetoothheadsetstopvoicerecognitionmconnectedheadset unregisterreceivermheadsetbroadcastreceiver mbluetoothheadset null override public void onserviceconnectedint profile bluetoothprofile proxy logdtag profile listener onserviceconnected nonnls1 mbluetoothheadset is just a head set profile it does not represent a head set device mbluetoothheadset bluetoothheadset proxy if a head set is connected before this application starts action connection state changed will not be broadcast so we need to check for already connected head set listbluetoothdevice devices mbluetoothheadsetgetconnecteddevices if devicessize 0 only one head set can be connected at a time so the connected head set is at index 0 mconnectedheadset devicesget0 string log the audio should not yet be connected at this stage but just to make sure we check if mbluetoothheadsetisaudioconnectedmconnectedheadset log profile listener audio already connected nonnls1 else the if statement is just for debug so far startvoicerecognition always returns true here what can we do if it returns false perhaps the only sensible thing is to inform the user well actually it only returns true if a call to stopvoicerecognition is call somewhere after a call to startvoicerecognition otherwise if stopvoicerecognition is never called then when the application is restarted startvoicerecognition always returns false whenever it is called if mbluetoothheadsetstartvoicerecognitionmconnectedheadset log profile listener startvoicerecognition returns true nonnls1 else log profile listener startvoicerecognition returns false nonnls1 minfotextviewsettextdevice name mconnectedheadsetgetname nonnls1 nn log nonnls1 logdtag log during the active life time of the app a user may turn on and off the head set so register for broadcast of connection states registerreceivermheadsetbroadcastreceiver new intentfilterbluetoothheadsetaction connection state changed calling startvoicerecognition does not result in immediate audio connection so register for broadcast of audio connection states this broadcast will only be sent if startvoicerecognition returns true registerreceivermheadsetbroadcastreceiver new intentfilterbluetoothheadsetaction audio state changed protected broadcastreceiver mheadsetbroadcastreceiver new broadcastreceiver override public void onreceivecontext context intent intent string action intentgetaction int state int previousstate intentgetintextrabluetoothheadsetextra previous state bluetoothheadsetstate thisconnected string log nonnls1 if actionequalsbluetoothheadsetaction connection state changed state intentgetintextrabluetoothheadsetextra state bluetoothheadsetstate thisconnected if state bluetoothheadsetstate connected mconnectedheadset intentgetparcelableextrabluetoothdeviceextra device minfotextviewappendnndevice name mconnectedheadsetgetname nonnls1 audio should not be connected yet but just to make sure if mbluetoothheadsetisaudioconnectedmconnectedheadset log headset connected audio already connected nonnls1 else calling startvoicerecognition always returns false here that why a count down timer is implemented to call startvoicerecognition in the ontick and onfinish if mbluetoothheadsetstartvoicerecognitionmconnectedheadset log headset connected startvoicerecognition returns true nonnls1 else log headset connected startvoicerecognition returns false nonnls1 mcountdownstart else if state bluetoothheadsetstate thisconnected calling stopvoicerecognition always returns false here as it should since the headset is no longer connected mconnectedheadset null else audio state intentgetintextrabluetoothheadsetextra state bluetoothheadsetstate audio thisconnected if state bluetoothheadsetstate audio connected log head set audio connected cancel countdown timer nonnls1 mcountdowncancel else if state bluetoothheadsetstate audio thisconnected the headset audio is thisconnected but calling stopvoicerecognition always returns true here boolean returnvalue mbluetoothheadsetstopvoicerecognitionmconnectedheadset log audio thisconnected stopvoicerecognition return returnvalue nonnls1 log naction action nstate state nonnls1 nonnls2 previous state previousstate nonnls1 minfotextviewappendnn log nonnls1 logdtag log protected countdowntimer mcountdown new countdowntimer10 10 override public void onticklong millisuntilfinished string log if mbluetoothheadsetisaudioconnectedmconnectedheadset log nontick audio already connected nonnls1 else first stick calls always returns false the second stick always returns true if the countdowninterval is set to 10 it is somewhere in between 500 to a 10 if mbluetoothheadsetstartvoicerecognitionmconnectedheadset log nontick startvoicerecognition returns true nonnls1 else log nontick startvoicerecognition returns false nonnls1 minfotextviewappendlog logdtag log override public void onfinish string log if mbluetoothheadsetisaudioconnectedmconnectedheadset log nonfinish audio already connected nonnls1 else if mbluetoothheadsetstartvoicerecognitionmconnectedheadset log nonfinish startvoicerecognition returns true nonnls1 else log nonfinish startvoicerecognition returns false nonnls1 minfotextviewappendlog logdtag log layout file scrollview xmlnsandroid xmlnstools androidlayout widthmatch parent androidlayout heightmatch parent textview androidididmain textview androidlayout widthmatch parent androidlayout heightwrap content androidtextisselectablefalse scrollview,['android'] +429828,should not xuacompatible ieedge header override thisplay intranet sites in compatibility view in ie10 i have a simple html5 aspnet website that i started testing in ie10 today since it released for win7this is an intranet site within my organization and i believe awhile back there was a group policy deployed to enable the thisplay intranet sites in compatibility view by defaultthe thing i noticed today in testing was that even though i am adding an xuacompatible ieedge http header via my webconfig the site is showing in ie asbrowser mode ie10 compat viewdocument mode standardsi believe my html is actually ok though because i can simply uncheck the thisplay intranet sites in compatibility view setting and when it reloads it immediately switches tobrowser mode ie10document mode standardsso my question is simply should not the ieedge header value override the thisplay intranet sites in compatibility view settingif not is there any way i can override it,"['asp.net', 'html']" +429839,error with expect eq for sum of double or float i am unable to understand why the test case failed in case of summing double numbers or floats it works very finely for the integer data typethe method in simple methodhdouble sum double a double b double res ab return res the test case for this methodtestsimplesum sumoffloat expect eq456 sum056 40 the output isrunning main from gtest maincc running 1 test from 1 test case global test environment setup 1 test from simplesum run simplesumsumoffloathomepcadmindesktopsoso3simple method testcpp7 failurevalue of sum056 40 actual 456expected 456 failed simplesumsumoffloat 0 ms 1 test from simplesum 0 ms total global test environment teardown 1 test from 1 test case ran 0 ms total passed 0 tests failed 1 test listed below failed simplesumsumoffloat 1 failed test,['c++'] +429906,pil and vectorbased graphics i run into several problems when i try to open eps or svgimages with pilopening epsfrom pil import imagetest imageopentestepsends intraceback most recent call last file stdin line 1 in module file cpython27libsitepackagespilimagepy line 1965 in open return factoryfp filename file cpython27libsitepackagespilimagefilepy line 91 in init self open file cpython27libsitepackagespilepsimagepluginpy line 206 in open raise ioerror bad eps header ioerror bad eps headeralso opening svg ends in ioerror cannot identify image filethe problem is i have to support both formats in my application converting to other formats is no alternative i am on windows 7 python 272 and pil 117i uploaded both images eps and svg,['python'] +429910,systemwebroutingroutecollection does not contain a definition for maphubs i follow sample from signalr wiki page and here is my globalasax application languagec import namespacesystem import namespacesystemwebrouting script runatserver void application startobject sender eventargs e code that runs on application startup routetableroutesmaphubs but i am gettingsystemwebroutingroutecollection does not contain a definition for maphubs and no extension method maphubs accepting a first argument of type systemwebroutingroutecollection could be found are you missing a using directive or an assembly reference globalasax 11what am i doing wrong,"['c#', 'asp.net']" +429919,java inner class inconsistency between descriptor and signature attribute class file i am trying to understand if there is a reason in the spec for the thiscrepany between java descriptors and signatures for inner classes i am looking directly at the content of the class files here but i use javap to illustrate nb i have tried this on jdk 160 33 and 170 05 both have the same issue when viewed with javap from java 7 java 6s javap does not seem to show any generic signature info as per seans answer below update thanks to those thiscussing my take isthe descriptor which does not contain generic information is correct the signature which is an attribute of the method and does contain generic information is incorrect the relevant constpool entry for signature of the init method is constantutf8ljavautillisttev javap in java 6 does not look at the signature just the descriptor my guessin case anyone wonders i hit this without using javap just looking at the class files myself i am only using javap to show it so it is unlikely to be a javap bugconsiderpublic class innerclasstest1 public int getx return new inner1new arrayliststringgetx4 public class inner1 private final list arg public inner1list arg thisarg arg vspublic class innerclasstest2 public int getx return new inner1new arrayliststringgetx4 public class inner1e private final liste arg public inner1liste arg thisarg arg if you look at the output of javap cs on the inner classes they are surprisingly differentpublic orgbenfcfrtestsinnerclasstest1inner1orgbenfcfrtestsinnerclasstest1 javautillist signature lorgbenfcfrtestsinnerclasstest1ljavautillistvvspublic orgbenfcfrtestsinnerclasstest2inner1javautilliste signature lorgbenfcfrtestsinnerclasstest2ljavautillistv the one which uses generics is missing the implicit parameter for the outer class it is correctly present in innerclasstest1i cannot find anything in the class file documentation to explain this does anyone know why this might bethanksleeupdate i have placed example files at given seans answer below i tried using javap on java 6 and i saw identical output for both with no generic information this leads me to believe that java 6s javap is not thisplaying full signature informationthe exact output i get using javap on 170 05b06 ispublic class orgbenfcfrtestsinnerclasstest2inner1e final orgbenfcfrtestsinnerclasstest2 this0 signature lorgbenfcfrtestsinnerclasstest2public orgbenfcfrtestsinnerclasstest2inner1javautilliste signature lorgbenfcfrtestsinnerclasstest2ljavautillistv code 0 aload 0 1 aload 1 2 putfield 1 field this0lorgbenfcfrtestsinnerclasstest2 5 aload 0 6 invokespecial 2 method javalangobjectinitv 9 aload 0 10 aload 2 11 putfield 3 field argljavautillist 14 return public int getxint signature ii code 0 iconst 2 1 ireturn,['java'] +429963,parsing large xml documents in java i have the following problem i have got an xml file approx 1gb and have to iterate up and down ie not sequential one after the other in order to get the required data and do some operations on it initially i used the dom java package but obviously while parsing through the xml file the jvm reaches its maximum heap space and halted in order to overcome this problem one of the solutions i came up with was to find another parser that iterates each element in the xml and then i store it is contents in a temporary sqlite database on my hard thisk hence in this way the jvms heap is not exceeded and once all data is filled i ignore the xml file and continue my operations on the temporary sqlite databaseis there another way how i can tackle my problem in hand,['java'] +429973,how to prevent document scrolling but allow scrolling inside div elements on websites for ios and android i created a website with jquerymobile for ios and androidi do not want the document itself to scroll instead just an area a div element should be scrollable via css property overflowyscrollso i thisabled document scrolling viadocumentbindtouchstart functione epreventdefaultdocumentbindtouchmove functione epreventdefaultbut that will also thisable scrolling for all other elements in the document no matter if overflowscroll is set or nothow can i solve this,['javascript'] +429987,how to debug a php script that never finishes loading i have been tasked with setting up a website on various environments for different stages of evaluation devteststagingetcon our staging environment however it seems there is some difference preventing the php script from finishing so the page is never delivered to the browseri am wondering if there is a way i can output to log some sort of stack trace or backtrace upon cutting the connection or is there some other method to find out what exactly php is doing at any given point in the scripts life cycleit is a drupal site so it involves a lot of code i am not familiar with and could take hours to sprinkle die commands throughout to see where the script is loading toi understand i should probably be looking at the differences in environments however all should have very similar configuration ubuntu 1104 and the staging environment seems entirely happy to serve other php sites whilst this particular site is refusing to finish if anything this staging site has more resources available that other environments which are not having problemsupdate sorry all found the problem in the end the staging environment was on a vlan that was not permitted to access itself via public ip and for whatever reason still confused about this it was trying to access itself as part of the page load and never completing the request setting a hosts file entry for 127001 fixed the issue,['php'] +429998,array setup in constructor means failure later on i had an issue where my code segfaulted on attempting to use the size function of a list on the advice of stackoverflow i constructed a minimum case in which the segfault occurs on the call inventorysize below it isinclude listclass thing class player private int xpcalcarray99 stdlistthing inventorypublic player int addtoinvthing t return 1 on success 0 on failureplayerplayer set up xp calculation array for int i1 i100 i if i10 xpcalcarrayi i100 if i10 i50 xpcalcarrayi i10 if i50 i99 xpcalcarrayi i50 int playeraddtoinvthing t if inventorysize 52 return 0 else inventorypush backt return 1int mainint argc char argv thing t player pc pcaddtoinvt return 1i notice that when i remove the setting up of the array in the player cosntructor it works fine so this looks to be the problem what am i doing wrong,['c++'] +430007,get duplicate file list by computing their md5 i have a array which contains a files path i want to make a list a those file which are duplicate on the basis of their md5 i calculate their md5 like thisprivate void calcmd5array files array contains a path of all files int i0 string md5 val new stringfileslength foreach string file name in files using var md5 md5create using var stream fileopenreadfile name md5 vali bitconvertertostringmd5computehashstreamreplace tolower i 1 from above i able to calculate their md5 but how to get only list of those files which are duplicate if there is any other way to do same please let me know and also i am new to linq,['c#'] +430032,sitecore dynamic placeholders with mvc i am looking for a working dynamic placeholder solution in mvcthere are at least two good descriptions of this pattern for use with webforms placeholder keys prototypeand i also found this blog explaining how to do it with mvcfirst i have tried to implement techphorias method with guids using techniques from the mvc blogpost extension of the sitecorehelper and i also tried implementing the last described method uses number suffixes that are incremented column 1 column 2 etcwith all the variations i tried i did not succeed in creating a working solution my placeholders do not get properly named i ended up with strange placeholder structures or placeholders repeating themselveswithout going into the specifics of my attempts i would like to know if anyone else has a working solution ready that i could useif i cannot find an already working solution i will describe my problem in more detail and see if i can get that to work,['asp.net'] +430043,aspnet mvc4 web api controller delete request 404 error i have a vs2012 mvc4 solution where i test web api controllersi successfully tested the get post put but the delete still got me an http 404 error when i set a breakpoint in my deletemovie action in my api controller the breakpoint is never reachedi read a lot of posts about this problem but no one helped mehere is my api controller for the delete httpdelete public httpresponsemessage deletemovieint id delete the movie from the database return status code return new httpresponsemessagehttpstatuscodenocontent here is my html pagescript typetextjavascript deletemovie1 function alertmovie deleted function deletemovieid callback ajax url apimovie data jsonstringify id id type delete contenttype applicationjsoncharsetutf8 statuscode 204 function callback scriptmy classic route is as follow public static void registerroutesroutecollection routes routesignorerouteresourceaxdpathinfo routesmaproute name default url controlleractionid defaults new controller home action index id urlparameteroptional my routing for api is as follow public static void registerhttpconfiguration config configroutesmaphttproute name actionapi routetemplate apicontrolleractionid defaults new id routeparameteroptional configroutesmaphttproute name defaultapi routetemplate apicontrollerid defaults new id routeparameteroptional in my solution properties i configure the use local iis web server with use iis express checkedi also tried with use visual studio development server but same problemany ideathanks,['asp.net'] +430070,google platform for android getcurrentperson i use the google platform for android withplusclient plusclient new plusclientbuilderthis this thissetscopesscopesplus loginbuildin the onconnectedlistener i want to read the data of the logged in useroverridepublic void onconnected superonconnected person person plusclientgetcurrentpersonthe method call getcurrentperson returns nullhas anyone managed to read the userdata,['android'] +430106,oauth 20 integrated with rest wcf service application i need help with integrating an authentication layer oauth20 with a rest service using vs 2012 wcf service application template in c this wcf needs to issue tokens for the authorization and authentication of the service before allowing the clientconsumer to access any of its resources three legged authentication is what i am looking at much like the twitter linkedin google oauth implementation have searched the internet extensively for an rest wcf api integrated with oauth and have not come across any suitable leads that is helping me i have looked at an old example i have used this example to integrate with an existing rest wcf when i run the service i am getting the 500 internal server error and other times the operation just times outhere is the implementation that is causing issuesi had to add the interceptor as below and referenced in the svc factorydemorestoauthserviceappservicehostfactoryclass appservicehostfactory systemservicemodelactivationservicehostfactory summary factory method called by wcf to create a see crefservicehost summary param nameservicetypethe type of the service to be createdparam param namebaseaddressescollection of base addresses where the see crefservicehost can listenparam returnsan instance of see crefservicehostreturns protected override servicehost createservicehosttype servicetype uri baseaddresses try microsoftservicemodelwebwebservicehost2 result new microsoftservicemodelwebwebservicehost2servicetype true baseaddresses resultinterceptorsaddnew oauthchanneloauthinterceptordemorestoauthserviceoauthoauthserviceslocatorprovider demorestoauthserviceoauthoauthserviceslocatoraccesstokenrepository return result catchexception e throw e when i debug using a log file i just am able to tell that an exception is thrown in the oauthinterceptorcs of oauthchannel assembly i have used tracelog and fiddler but i am not getting much help understanding the error other than 500 internal server errorpublic override void processrequestref requestcontext requestcontext if requestcontext null requestcontextrequestmessage null return message request requestcontextrequestmessage httprequestmessageproperty requestproperty httprequestmessagepropertyrequestpropertieshttprequestmessagepropertyname oauthcontext context new oauthcontextbuilderfromurirequestpropertymethod requestheadersto try provideraccessprotectedresourcerequestcontext oauthchannelmodelsaccesstoken accesstoken repositorygettokencontexttoken tokenprincipal principal new tokenprincipal new genericidentityaccesstokenusername oauth accesstokenroles accesstoken initializesecuritycontextrequest principal catch oauthexception authex xelement response xelementloadnew stringreaderxml version10 encodingutf8html xmlns versionw3cdtd xhtml 20en xmllangen xmlnsxsi xsischemalocation headtitlerequest errortitleheadbodydiv idcontentp classheading1b httputilityhtmlencodeauthexreporttostring bpdivbodyhtml message reply messagecreatemessagemessageversionnone null response httpresponsemessageproperty responseproperty new httpresponsemessageproperty statuscode httpstatuscodeforbidden statusdescription authexreporttostring responsepropertyheadershttpresponseheadercontenttype texthtml replypropertieshttpresponsemessagepropertyname responseproperty requestcontextreplyreply requestcontext null can anyone out there please help me with an insight as to what is going onor can you please help me with any other suitable examples pointers tips or documentations for three legged oauth provider implementation i am literally stuck with this issue for past one week any help is appreciatedthanks in advance,['c#'] +430146,aspectj pointcut for matching public method calls on annotated field i want to write a pointcut that matches execution of public methods on an annotated field this how ever does not seem to work the getimportant works as you expect on its own but it will of course match all access to the field i want to limit this to only public method executionis this possible at all i get no compile error but on the other hand it does not seem to workpublic class counter private int count 0 public void addint value count count value public class visitors important counter counter new counter public void increasecounter counteradd1 workspointcutvalue getimportant void testpointcut does not workpointcutvalue getimportant executionpublic void testpointcut,['java'] +430152,c rvalue reference and move semantics so i was watching c videos on youtube yesterday and came across one the was about c11 rvalue reference and move semantics i think i understand the concept in broad terms but today when i was going through my code with the ta he asked why i did not us a reference like stdpairhostname ipaddress p in the code below i had not thought about it at all in this case but when he asked i remembered the video saying in c11 you should generally use pass by valuemy question is thus in the code below would stdpairhostname ipaddress p be better off like stdpairhostname ipaddress p or not will move semantics be used and would it make a differenceipaddress nameserverlookup const hostname host const auto it stdfind if vecbegin vecend host stdpairhostname ipaddress p return pfirst host,['c++'] +430153,setting transformorigin on svg group not working in firefox i am having an issue with getting transformorigin to work in firefox v18 other versions not tested webkit browsers work as expectedi am trying to set the origin to the center of the group but nothing i have tried has worked so far heres the codedoctype htmlhtml head titletesttitle style test webkittransformorigin 50 50 transformorigin center center webkitanimation prop 2s infinite animation prop 2s infinite webkitkeyframes prop 0 webkittransform scale11 20 webkittransform scale18 40 webkittransform scale16 50 webkittransform scale14 60 webkittransform scale12 70 webkittransform scale14 80 webkittransform scale16 90 webkittransform scale18 100 webkittransform scale11 keyframes prop 0 transform matrix1 0 0 1 0 0 20 transform matrix1 0 0 8 0 0 40 transform matrix1 0 0 6 0 0 50 transform matrix1 0 0 4 0 0 60 transform matrix1 0 0 2 0 0 70 transform matrix1 0 0 4 0 0 80 transform matrix1 0 0 6 0 0 90 transform matrix1 0 0 8 0 0 100 transform matrix1 0 0 1 0 0 style head body svg xmlns xmlnsxlink width128px height128px viewbox0 0 16 16 g idtest rect fill404040 x7062 y3625 width1875 height875 g svg bodyhtmlthanks for your help,"['html', 'css']" +430207,explanation of jshints bad line breaking before error can someone explain to me why jshint complains about the followingwindowlocationhref string1 sting2 string3with the error bad line breaking before errori understand that this error can be configured with the laxbreak option which is described as this option suppresses most of the warnings about possibly unsafe line breakings in your code it does not suppress warnings about commafirst coding style to suppress those you have to use laxcomma see belowthis explanation is pretty terse and i am curious about why breaking lines this way is considered bad or lax in the first placekeep in mind i am not trying to start a holy war here i am just looking for an objective answer about why the jshint folks think this is bad whether it is just a style preference they are injecting into their linter i thought jslint was the opinionated linter or if there is something that can go wrong on certain interpreters when line breaking this way,['javascript'] +430236,get text of label that belongs to checked radio button i am trying to get the text of the labels that belong to checked radio buttons but do not seem quite to be able to documentreadyfunction bodyonclick btn function var radios inputtyperadio eachradios functionindex element if thispropchecked true var radioid elementid labeleachfunctionind elm if elmpropfor radioid consolelogelm jsbinfor whatever reason that just prints out 110713834 0 context length1 in the console what have i done wrong,['jquery'] +430250,why are ruby global strings like ignoring mutations without error i am learning ruby 20 and this just surprised mes 1234s d 1234 as expected contains the matched stringslice21 should mutate string 1234 whatsslice21 s 12 as expectedthe slice method is supposed to mutate the string other mutator methods behave in the same way my questions why is this not throwing an error which is what i expect when a function cannot do what it says it will do is this documented somewhere is there a rationaleupdateso i see that is not acting like a global variable each reference to it gives a new object as if it is really a noarg functionirb foo 1234 1234irb fobject id 70205012205980irb fobject id 70205012205980 the sameirb object id 70205003531300irb object id 70205011619040 different objectso my question becomes is this simply magic from the interpreter or is actually a noarg function just as i could define in ruby using def end and how could i tell the difference in python i could refer to a function foo by just using it is name foofunction foo at 0x10d3117d0is there way to do this in ruby i could then look at what really is if it is not magic,['ruby'] +430273,how do i remove extra space above and below imageview i have a really simple image within a relativelayout and for some reason i am getting extra spacing on the top and bottom which i cannot remove any ideas how to clear it out here is what it looks like here is the code xml version10 encodingutf8relativelayout xmlnsandroid androidlayout widthmatch parent androidlayout heightmatch parent imageview androidididimageview1 androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentlefttrue androidlayout alignparenttoptrue androidsrcdrawableslice11pp relativelayout,['android'] +430283,ruby koans not compatible with ruby 200 after successfully upgrading to ruby 200s stable release yay i decided to continue on my koans path to enlightenment however when running the rake command within the koans folder as i normally do i receive this errorrakecd koansusersjordanthornquestrvmrubiesruby200p0binruby path to enlightenmentrbusersjordanthornquestprogrammingrubykoanskoansedgecaserb399in rescue in meditate uninitialized constant edgecasesenseiassertionerror nameerror from usersjordanthornquestprogrammingrubykoanskoansedgecaserb407in meditate from usersjordanthornquestprogrammingrubykoanskoansedgecaserb470in block in walk from usersjordanthornquestprogrammingrubykoanskoansedgecaserb481in block 3 levels in each step from usersjordanthornquestprogrammingrubykoanskoansedgecaserb479in each from usersjordanthornquestprogrammingrubykoanskoansedgecaserb479in block 2 levels in each step from usersjordanthornquestprogrammingrubykoanskoansedgecaserb478in each from usersjordanthornquestprogrammingrubykoanskoansedgecaserb478in each with index from usersjordanthornquestprogrammingrubykoanskoansedgecaserb478in block in each step from usersjordanthornquestprogrammingrubykoanskoansedgecaserb476in catch from usersjordanthornquestprogrammingrubykoanskoansedgecaserb476in each step from usersjordanthornquestprogrammingrubykoanskoansedgecaserb469in walk from usersjordanthornquestprogrammingrubykoanskoansedgecaserb491in block in top requiredrake abortedcommand failed with status 1 usersjordanthornquestrvmrubiesruby2usersjordanthornquestprogrammingrubykoansrakefile90in block in top requiredusersjordanthornquestrvmgemsruby200p0binruby noexec wrapper14in evalusersjordanthornquestrvmgemsruby200p0binruby noexec wrapper14in maintasks top default walk the pathi also installed a fresh new koans batch from github today as well to assure that that was not my problem neither worked for me it still runs great with 193 it may be worth noting that i also installed ruby 20 via rvm i made sure to update to the latest rvm before doing sowhat seems to be the problem,['ruby'] +430334,sending chunked http 11 requests in objectivec i have the following issue i am creating a very big soap request the data is a video encoded as base64 string and because of that i cannot send it as a raw soap request but rather need to send it in http 11 chunks i cannot seem to figure out how to do it i used the code in herewhat are alternatives to nsurlconnection for chunked transfer encodingbut it does not seem to be doing what i think it should i can see that the request arrives on the server as a single request instead of many chunks i am using wireshark on the server to see the incoming traffic i know that a similar functionality on an android works using apache foundations http libraries for java with these any http request whose length is not specified in advance is transmitted as an http 11 chunked request and i can see indeed those requests arriving on the server as individual chunks i want to emulate thatupdate seems to me afnetworking might have the functionality but i fail to find any example as to how to use ithere is my code more or lessnsstring soapbody some correctly formed soap request xml here nsurl url nsurl urlwithstringnsmutableurlrequest request nsmutableurlrequest requestwithurlurlrequest addvalue forhttpheaderfieldsoapactionrequest sethttpmethodpostrequest addvaluetextxml forhttpheaderfieldcontenttyperequest sethttpbodysoapbody datausingencodingnsutf8stringencodingchunkedtransferconnection connection chunkedtransferconnection allocconnection establishconnectionwithrequestrequestwhere chunkedtransferconnection implementation is the followingimplementation chunkedtransferconnection synthesize p connection synthesize p responsedata voidestablishconnectionwithrequestnsmutableurlrequest request selfp responsedata nsmutabledata alloc initwithlength0 selfp connection nsurlconnection alloc initwithrequestrequest delegateself startimmediatelyyes end,"['ios', 'objective-c']" +430367,what is the difference between java 6 and 7 that would cause a performance issue my general experience with java 7 tells me that it is faster than java 6 however i have run into enough information that makes me believe that this is not always the casethe first bit of information comes from minecraft snooper data found here my intention was to look at that data to determine the effects of the different switches used to launch minecraft for example i wanted to know if using xmx4096m had a negative or positive effect on performance before i could get there i looked at the different version of java being used it covers everything from 15 to a developer using 18 in general as you increase the java version you see an increase in fps performance throughout the different versions of 16 you even see this gradual trend up i honestly was not expecting to see as many different versions of java still in the wild but i guess people do not run the updates like they shouldsome time around the later versions of 16 you get the highest peeks 17 performs about 10fps on average below the later versions of 16 but still higher than the early versions of 16 on a sample from my own system it is almost impossible to see the difference but when looking at the broader sample it is clearto control for the possibility that someone might have found a magic switch for java i control with by only looking at the data with no switches being passed that way i would have a reasonable control before i started looking at the different flagsi thismissed most of what i was seeing as this could be some magic java 6 that someones just not sharing with menow i have been working on another project that requires me to pass an array in an inputstream to be processed by another api initially i used a bytearrayinputstream because it would work out of the box when i looked at the code for it i noticed that every function was synchronized since this was unnecessary for this project i rewrote one with the synchronization stripped out i then decided that i wanted to know what the general cost of synchronization was for me in this situationi mocked up a simple test just to see i timed everything in with systemnanotime and used java 16 20 x86 and 170b147 amd64 and 17 15 amd64 and using the server i expected the amd64 version to outperform based on architecture alone and have any java 7 advantages i also looked at the 25th 50th and 75th percentile blueredgreen however 16 with no server beat the pants off of every other configurationso my question iswhat is in the 16 server option that is impacting performance that is also defaulted to on in 17i know most of the speed enhancement in 17 came from defaulting some of the more radical performance options in 16 to on but one of them is causing a performance difference i just do not know which ones to look atpublic class byteinputstream extends inputstream public static void mainstring args throws ioexception string song this is the song that never ends byte data songgetbytes byte read new bytedatalength bytearrayinputstream bais new bytearrayinputstreamdata byteinputstream bis new byteinputstreamdata long starttime endtime for int i 0 i 10 i code for byteinputstream starttime systemnanotime for int ctr 0 ctr 10 ctr bismark0 bisreadread bisreset endtime systemnanotime systemoutprintlnendtime starttime code for bytearrayinputstream starttime systemnanotime for int ctr 0 ctr 10 ctr baismark0 baisreadread baisreset endtime systemnanotime systemoutprintlnendtime starttime private final byte arrayprivate int posprivate int minprivate int maxprivate int markpublic byteinputstreambyte array thisarray 0 arraylengthpublic byteinputstreambyte array int offset int length min offset max offset length thisarray array pos offsetoverridepublic int available return max posoverridepublic boolean marksupported return trueoverridepublic void markint limit mark posoverridepublic void reset pos markoverridepublic long skiplong n pos n if pos max pos max return posoverridepublic int read throws ioexception if pos max return 1 return arraypos 0xffoverridepublic int readbyte b int off int len if pos max return 1 if pos len max len max pos if len 0 return 0 systemarraycopyarray pos b off len pos len return lenoverridepublic void close throws ioexception end class,['java'] +430411,phpexcel get column name relative to given column using phpexcel is it possible to get the name of a column located x number of columns to the left or rightexample given column bz i would like to return column name cb or bx 2 to the right or leftthanks,['php'] +430441,custom authorizations in webapi my understanding of aspnet mvc is that for authorizations i should use something like public class ipauthorize authorizeattribute protected override bool authorizecorehttpcontextbase httpcontext figure out if the ip is authorized and return true or falsebut in web api there is no authorizecorethere is onauthorization and the general advice for mvc is not to use onauthorizationwhat should i use for custom authorizations in web api,['c#'] +430444,group the numbers c heres the problemyou have and n represents the number of numbers that you have numbers divide them in 2 groups in such way that the difference between sums of the numbers in the groups is minimalexamples5 n1 9 5 3 8 the numbersthe difference is 0 if we put 1 9 and 3 in group a and 5 and 8 in group bi think first i should calculate the sum of all numbers and divide it by 2 then to check ever possible combination of numbers whose sum is not higher than half of the sum of all numbers after i do this i will choose the biggest number and print out the groupsi have problem with going through all combinations especialy when and is big numbers how can i run through all combinationsalso i think a little bit differently i will group the numbers in descending order and i will put the biggest number in group a and lowest in group b then i do the other way around this works with some of the numbers but sometimes it does not show the optimal grouping for exampleif i use the previous example arrange the number in descending order9 8 5 3 1put the biggest in group a and lowest in group bgroup a 9group b 1other way aroundgroup a 9 3group b 1 8and so on if in the end i have only one number i will put it in the group with lower sumso i finally will getgroup a 9 3group b 1 8 5this is not the optimal grouping because the difference is 2 but with grouping in different way the difference can be 0 as i showedhow can i get optimal groupingcodeinclude iostreaminclude cmathinclude stringusing namespace stdint converttobinaryint number int remainder int binnumber 0 int i 1 whilenumber0 remaindernumber2 binnumberbinnumber iremainder numbernumber2 ii10 return binnumberint main int number combinations sum 0 double average cin number int numbersnumber forint i 0 inumber i cin numbersi sum numbersi ifsum2 0 average sum2 else average sum2 05 combinations pow2number1 double closest average forint i 0 icombinationsi int rem int temp sum 0 int state converttobinaryi forint j 0 state0 j int rem state10 state state10 ifrem 1 temp sum temp sum numbersj ifabsaveragetemp sumclosest closest absaveragetemp sum ifclosest 0 break cout closest2 return 0,['c++'] +430512,android timepicker setis24hourview not working i am trying to use the timepicker in the 24 hour format and i am using setis24hourview true but i am still not getting 24 hour format on the timepicker here is my code in the oncreate of the activity timepicker timepicker findviewbyidridtimepicker1 timepickersetis24hourviewtruei even tried timepickersetcurrenthourcalhour of day after setis24hourview but i am not able to see the 24 hour format on the timepickertimepicker androidididtimepicker1 androidlayout widthwrap content androidlayout heightwrap content androidlayout margintop110dp am i missing anything here,['android'] +430519,line 60 in make tuple return tuplel typeerror iter returned noniterator of type vector i am new to vectors and making classes i am trying to construct my own vector class but when i pass it through my code which isposition headingthistance movedwhere position and heading are both vectors heading is normalized my goal is to repeat my code until position destinationwhat is wrong with this classimport mathclass vectorobject defaults are set at 00 for x and y def init self x00 y00 selfx x selfy y allows us to return a string for print def str self return s sselfx selfy from points generates a vector between 2 pairs of xy coordinates classmethod def from pointscls p1 p2 return clsp20 p10 p21 p11 calculate magnitudethistance of the line from points a to points b def get magnitudeself return mathsqrtselfx2selfy2 normalizes the vector divides it by a magnitude and finds the direction def normalizeself magnitude selfget magnitude selfx magnitude selfy magnitude adds two vectors and returns the resultsa new line from start of line ab to end of line bc def add self rhs return vectorselfx rhsx selfyrhsy subtracts two vectors def sub self rhs return vectorselfx rhsx selfyrhsy negates or returns a vector back in the opposite direction def neg self return vectorselfx selfy multiply the vector scales its size multiplying by negative reverses the direction def mul self scalar return vectorselfxscalar selfyscalar divides the vector scales its size down def div self scalar return vectorselfxscalar selfyscalar iterator def iter self return self next def nextself selfcurrent 1 return selfcurrent 1 turns a list into a tuple def make tuplel return tuplel,['python'] +430533,change regex to allow for both english japanese characters this is my regular expression codeonlylettersp regex azaz alerttext letters onlyhow can i change this to allow english characters as well as japanese,"['php', 'jquery']" +430542,simple dictionary in c moving some code from python to cbasepairs t a a t g c c g thinking maps might be overkill what would you use,['c++'] +430567,chrome rendering issue fixed position anchor with ul in body there is a rendering issue with google chrome and opera why with such codehtmlstyle content width 150px background gray sidebar position fixed left 200px background gray stylebody div idsidebar a hrefs1link 1abr a hrefs2link 2a div div idcontent div ids1 a hrefs1link 1 targeta plorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborump div div ids2 a hrefs2link 2 targeta ul liitem 1li liitem 2li ul div div a hreftopabodyhtmlas you can see i am trying to make sidebar static on the right sideeverything works fine until you add some ul tag on the pagethe fixed div sometimes starts to thisappear when i click anchor linkswhat can be done to avoid such behavior,"['html', 'css']" +430581,whats the difference between uicontrolstatehighlighted and uicontrolstateselected i am trying to set a state for uibuttonbut i do not know the difference between the uicontrolstatehighlighted and uicontrolstateselectedcould anyone help me outthanks and best regards,"['iphone', 'ios', 'objective-c']" +430586,what is adb device l listing adb devices ldevices l list all connected devices l will also list device qualifierswhen i execute it i am getting like padmakumarpadmakumardesktop adb devices llist of devices attached medfield14abx device usb215ztedfield14ax device usb216emulator54 device015d2994ec2x device usb215 productnakasi modelnexus 7 devicegroupermedfield14aba072 device usb1 changing to different portwhen i change to different port its thisplaying the bus number as 1 and 2 as thisplayed in lsusb commandwhat is this device usb215 16 11 so what this l will dowhats the exact meaning for the device qualifiersi tried with lsusb but the information is different that adb device lpadmakumarpadmakumardesktop lsusbbus 002 device 008 id 18d14e42 google inc bus 002 device 005 id 17ef7470 lenovo bus 002 device 002 id 80870024 intel corp integrated rate matching hubbus 002 device 001 id 1d6b02 linux foundation 20 root hubbus 001 device 003 id 046dc03d logitech inc mbt96a pilot optical mousebus 001 device 002 id 80870024 intel corp integrated rate matching hubbus 001 device 001 id 1d6b02 linux foundation 20 root hub,['android'] +430597,how to make settings provider inside a dynamically loaded assembly available for reflection following this question i successfully created my custom settings provider in the legacy c app we are developing it is referenced via the settingsprovider attributepublic sealed class mysettings settingsprovider settingsprovidertypeofmysettingsinternal sealed partial class settings however now i ran into another problemour client app includes an autoupdate facility and it is implemented so that the bulk of the client including the classes above is built into a dll let us call it clientdll here which is then used by an exe the exe first checks for updates and downloads the latest one from the update server if needed replacing all dlls etc with their newer version including clientdll in order to be able to replace dlls at runtime it cannot link to them statically so after the update it loads clientdll and runs it like thisassembly assy assemblyloadfile appdomaincurrentdomainbasedirectory clientdllobject frm assycreateinstanceclientformsmainformapplicationrunformfrmthe unfortunate consequence of this is that the framework cannot find my custom settings provider class inside the dynamically loaded assembly i tried to use loadfrom instead of loadfile above but it did not help the only working solution i found so far is to implement a proxy class in the loader exe with the same name as the real settings provider which is found by the framework all right the proxy then instantiates the real settings provider from the client assembly and delegates all calls to itthis seems to work but i am not happy with it is there a way to help the framework find my class inside a dynamically loaded assembly directlyupdatethe error message i getsystemconfigurationconfigurationerrorsexception failed to load provider type clientpropertiesmysettings client version4013410 cultureneutral publickeytokennull at systemconfigurationapplicationsettingsbaseget initializer at systemconfigurationapplicationsettingsbasecreatesettingpropertyinfo propinfo at systemconfigurationapplicationsettingsbaseensureinitialized at systemconfigurationapplicationsettingsbaseget properties at systemconfigurationsettingsbasegetpropertyvaluebynamestring propertyname at systemconfigurationsettingsbaseget itemstring propertyname at systemconfigurationapplicationsettingsbasegetpropertyvaluestring propertyname at systemconfigurationapplicationsettingsbaseget itemstring propertyname at clientpropertiessettingsget someconfigsetting at via debugging and log messages i determined that the initializer method of the class is never called so the class is never instantiated in other words there seems to be no hidden initialization error behind the above exceptionone more potentially important bit the client is currently running on net 20 and there are no plans to upgrade in the foreseeable futureupdate 2i started to investigate the appdomain as suggested by jwddixons answer first i wanted to check whether clientdll really ends up in a different app domain than that of the caller exe so i listed the assemblies in the current app domain and saw that client is in fact there but to my surprise i noticed that there are actually two assemblies named client in the list both the exe and the dll have the same assembly name but different version 40 for the exe 4013520 for the dll at present i was not fully aware of this so far and this may be important i will try changing the exe assembly name nextupdate 3and that actually fixed the problem argh towards my unknown predecessors who invented this contorted scheme for who knows why i have very unfond thoughts at this moment but kudos to all of you guys for contributing questions and ideas which eventually lead to the solution,['c#'] +430605,table inside table with different styles how to make two different styles for two tables table cells that one cells of them is inside another tablei have two css stylestablestyle1 any styles tablestyle1 td any styles and tablestyle2 any styles tablestyle2 td any styles in code i have somting like thistable clastyle1 tr td table clastyle2 trtdbla blatdtr table td trtableand the results is all of td table cells in second table with style2 are with style1 how to make two different css stile when i have table inside table,['css'] +430624,how to right align fixed position div inside a div my code is like thisdiv classouter div classinnersome text here divdivcssouter maxwidth1024px backgroundcolorred margin0 autoinner width50px border1px solid white positionfixedthe inner div which is positioned left by default need to be positioned right wrt the outer div and not to the pageif i am mentioning it to be right0px it make it to do the 0px from the browsers right not the outer divs right note my outer div is not fixed width it adjust as per screen resolution it is responsive website design,"['html', 'css']" +430692,singleton class with several different classloaders eg i have class singleton with static field instancepublic class singleton private static singleton instance other code construct getters no matter i can load this class twice with two different classloaders how could i avoid it it is unsafe and dangerous also if i set instance to null would it set to null for both classessingleton singleton singletongetinstancesingleton null,['java'] +430699,mysql calculate seconds between two datetimes for each day i have this table but i am helpless how to calculate seconds for each separate day from this tableid from to1 20130131 2350 20130202 0902 20130205 112112 20130208 0101013 20130208 173344 20130208 1822554 20130212 014012 20130212 0200595 20130228 014012 20130302 020059now i need to gain number of seconds for each day in february between from and toso for 1st feb x seconds 2nd feb y seconds 3rd feb 0 seconds etc any idea how should i do it many thanks,['mysql'] +430775,update elements in a jsonobject lets say i gave a jsonobject personnamesam surnamengonma carmaketoyota modelyaris how do i update some of the values in the jsonobject like below string name jsonarraygetjsonobject0getjsonobjectpersongetstringnamename sammie,"['java', 'android']" +430793,usage of javafx platformrunlater and access to ui from a different thread i have a few questions about platformrunlater i have a javafx application class in this class i run a thread the thread reads data from a network socketnow when i create a new stage inside the thread the system throws an execption javafx event thispatcher thread and my netorkread thread are not the same i understand this behaviourbut the other side is i append the text from the networkreader to an existing textarea or addremove some items in a listviewstring this does not throw an exception why i thought javafx is singlethreaded the ui library part is this the same thing as in swing sometimes it works and sometimes you have just garbage because edtmy questionswhen does the javafx event thispatcher thread throw an exception and when not are the any good documents about thisis there an easier shorter cleaner way to use platformrunlater with a run method in combination with a try catch or multiple catch it looks very strangei know the usage of platformrunlater in a thread is not that nice design solution,['java'] +430810,google cloud endpoints security oauth2 and custom user schema i am reading the google cloud endpoints docs related to oauth2 securityi assume this kind of security is against google accountsis there any support to have a custom user schema to authenticate againstwhat i would like is to have client js application which uses google cloud endpoints but authenticate against local storage app engine of usersis google clound endpoints suitable for this or do i need to write my own security mechanism,['java'] +430821,javautildate get milliseconds i have done the followingstring standardrange 0101simpledateformat rangeformatter new simpledateformathhmmssdate range rangeformatterparsestandardrangenowrangegettime i get the output of 35390 and not 610i am not sure what i am doing wrong when debugging cdate exists the attribute contains a fraction which contains the value 610 which is what i want,['java'] +430845,what is the difference between ldobj and ldind and why is ldobj faster when using a 64bit sized struct the following code snippetstructlayoutlayoutkindexplicit pack 1 size 8 unsafe struct buf bufdst bufsrc produces il 0046 nop il 0047 ldlocs dst il 0049 ldloc2 il 004a ldobj myclassbuf il 004f stobj myclassbufhowever when just using a long the following code produceslongdst longsrc producesil 0046 nopil 0047 ldlocs dstil 0049 ldloc2il 004a ldindi8 il 004b stindi8 does anyone know what difference ldobjstobj and ldindi8stindi8 makes if any for this exampleldobjstobj seems to give a 20 performance improvement but i cannot figure out why that is happening are not these two lines doing the exact same thingthanksedit 64bit release mode the bytecode looks the same when compiled in release mode the performance measurement was done a while ago in release mode,['c#'] +430860,rename packages with android maven plugin as usual you stuck with maven when you try to make something nonstandardi am currently trying to rename my main application package for android app to be able run different branded apps from same sourceswe are using android maven plugin and it is super hard to accomplish iti was trying first easy way use renamemanifestpackage configuration but this looks like not what i expected because resulted apk is not possible to install nowi tried second approach run ant on initialization phase to rename packages from sourcesresourcestestsandroidmanifestxml this almost works if i skip tests if not than robolectric fails because it is using original manifest if i wouldnt copy manifest and do replacement in original file everything works but i have now modified androidmanifest and this breaks my working environment idedoes anyone have clear steps how to have package renaming and still have working environmentupd the issue mentioned in point 1 was that i used wrong package name devapp it should contain at least one it is fixed by using mypackagedevapp and installation passed successfully but i cannot install new app right now becausecannot install because provider name mypackageapp in package mypackagedevapp is already used by mypackagelivei am not sure what to do next going to deep more into apktool,['android'] +430875,volatile fence demo im trying to see how the fence is appliedi have this code which blocks indefinitely static void main bool complete false var t new thread bool toggle false whilecomplete toggle toggle tstart threadsleep10 complete true tjoin blocks indefinitelywriting volatile bool complete solve the issue acquire fence an acquirefence prevents other readswrites from being moved before the fencebut if i illustrate it using an arrow a think of the arrowhead as pushing everything awayso now the code can look like var t new thread bool toggle false while complete a instructions cannot go up before this fence toggle toggle i do not understand how the illustrated drawing represent a solution for solving this issuei do know that whilecomplete now reads the real value but how is it related to complete true location to the fence,"['c#', '.net']" +430877,using helper methods like html escape in rails console i am trying to see what is going wrong with my encoding of variables in my view so i fire up rails console and try to do rails consoleloading development environment rails 3211irbmain0010 html escapea1 bmy strnomethoderror undefined method html escape for mainobjecthow do i use h or html escape in rails console,['ruby-on-rails'] +430883,how can i change all input values to uppercase using jquery i want to change all my form values to uppercase before the form is submittedso far i have this but it is not workingidsubmitclickfunction var allinputs input allinputsvaluetouppercase alertallinputs,"['javascript', 'jquery', 'html']" +430886,use d3 log scale instead of linear scale i am trying to do a chart based on the only difference being that i would like to use a log scale for the xaxisheres my fiddle as you can see the xaxis is defined at line 4x d3scalelinearrange0 wif i change it forx d3scalelogrange0 wthen it does not work nothing is rendered throwing these error messageserror invalid value for rect attribute widthnan changing the domain setting fromxdomain0 rootvaluenicetoxdomain1 rootvalueniceshows me the z axis names but still no bars or values,['javascript'] +430891,where to put helper functions for rake tasks and test files in ruby on rails in my rails application i have a file sample datarb inside libtasks as well as a bunch of test files inside my spec directoryall these files often share common functionality such asdef random address fakeraddrestreet address fakeraddresscityjoinnendwhere should i put those helper functions is there some sort of convention on thisthanks for any help,['ruby'] +430907,change font typeface of progressdialog within dialogfragment may i know is it possible to change the font typeface of progressdialogs message thisplay within dialogfragmentpublic class loadfromcloudtaskfragment extends dialogfragment override public dialog oncreatedialogbundle savedinstancestate thisprogressdialog new progressdialogthisgetactivity thisprogressdialogsetmessageprogressmessage thisprogressdialogsetcanceledontouchoutsidefalse return progressdialog create a custom class by inheriting from progressdialog might be one of the ways however i wish to know is there any better alternative sadly we do not have progressdialogbuilderone of the alternative i had tried isoverridepublic dialog oncreatedialogbundle savedinstancestate thisprogressdialog new progressdialogthisgetactivity thisprogressdialogsetmessageprogressmessage thisprogressdialogsetcanceledontouchoutsidefalse utilssetcustomfontthisprogressdialogfindviewbyidandroidridmessage utilsroboto light font return progressdialogbut this will give me errorandroidutilandroidruntimeexception requestfeature must be called before adding content,['android'] +430934,how do i maintain rowcolumn orientation of vectors in numpy coming from a background of matlaboctave i have been trying to learn numpy one thing that has been tripping me up over and over is the thistinction between vectors and multidimensional arrays for this question i will give a specific problem i am having but i would be much obliged if someone could also explain the more general picture behind singledimensional arrays in numpy why you would want them in the first place how to avoid trouble when mixing single and multidimensional arrays etc anyway the questioni have a 2d array called xx numpyarange10reshape25and i want to take the last column of x and store it as another 2d array ie a column vector called y the only way i have been able to come with for this isy numpyatleast 2dx4tbut i do not like that for a couple of reasonsi do not feel like i should have to tell it to transpose the vector when the orientation should be implied in x4using atleast 2d just seems so cumbersome to use over and over again in code where this situation would come up a lot it feels like i am doing something wrongso in short is there a better waythanks,['python'] +430937,rails observer alternatives for 40 with observers officially removed from rails 40 i am curious what other developers are using in their place other than using the extracted gem while observers were certainly abused and could easily become unwieldily at times there were many usecases outside of just cacheclearing where they were beneficialtake for example an application that needs to track changes to a model an observer could easily watch for changes on model a and record those changes with model b in the database if you wanted to watch for changes across several models then a single observer could handle that in rails 4 i am curious what strategies other developers are using in place of observers to recreate that functionality personally i am leaning towards a sort of fat controller implementation where these changes are tracked in each models controllers createupdatedelete method while it bloats the behavior of each controller slightly it does help in readability and understanding as all the code is in one place the downside is that there is now code that is very similar scattered throughout several controllers extracting that code into helper methods is an option but youre still left with calls to those methods littered everywhere not the end of the world but not quite in the spirit of skinny controllers either activerecord callbacks are another possible option though one i do not personally like as it tends to couple two different models too closely together in my opinion so in the rails 4 noobservers world if you had to create a new record after another record was createdupdateddestroyed what design pattern would you use fat controllers activerecord callbacks or something else entirely thank you,['ruby-on-rails'] +430972,php fetch over 20 imap emails i am trying to export several mailboxes to an database my current script will connect imap and just loop all messages though with larger mailboxes this would not work and it will slow down or even stopthe idea is to run the script daily to copy all messages who are not in the database yet to the database whats the best way to fetch big amounts of emails 20k mails spread over about 40 50 folderseventually this will need to work from a single server to scan hundreds or even thousands accounts daily so imagine the amounts of data it will store the mail uid and subject into the database and create a package which will be stored on the dataserver so it also needs to fetch the attachments,['php'] +430975,getserializablemembers formatterservices returns the same field twice why formatterservicesgetserializablemembers returns protected and internal fields twice for derived types once as an instance of serializationfieldinfo and once as rtfieldinfoi find this very confusing can anyone help me understand why microsoft decided to implement it this wayi have written a sample program that reproduce my problemclass program serializable public class basea private int privatefield serializable public class deriveda basea serializable public class baseb protected int protectedfield serializable public class derivedb baseb static void mainstring args programprintmemberinfotypeofderiveda programprintmemberinfotypeofderivedb consolereadkey static void printmemberinfotype t consolewritelinetname foreach var mbr in formatterservicesgetserializablememberst consolewriteline 0 1 mbrname mbrmetadatatoken consolewriteline i would expect that privatefield and protectedfield are reported once each however this is the actual output when running the programderiveda baseaprivatefield 67108865derivedb protectedfield 67108866 basebprotectedfield 67108866as you can see protectedfield appear twice with different names but with the same metadata token so it is indeed the very same fieldcan anyone explain why,['c#'] +430976,setting up proguard with android library projects i am trying to setup proguard for my android project my application project has very little code in it but references a library project which has the vast majority of the code and any other external jars that being said i am not sure how to setup proguard to take this into account right now my proguard config file is just the android example from the proguard site i have been searching around but have not found a lot or any documentation on using proguard with library projects just jars i am new to proguard so any push in the right direction would be great thanks,['android'] +431060,fixing position relative to parent div is it possible to fix an elements position relative to the parent div not the browser windowsay i havediv idpagecontainer div idlinkspage div clasidelinks a hrefpage1 classlinklink 1a p a hrefpage2 classlinklink 2a p a hrefpage3 classlinklink 3a p a hrefpage4 classlinklink 4a p div div classlinkscontent content of links page div div other pagesdivbasically a page with two sections the left section is a list of links while the right section is the pages content i want the content to be scrollable but the links to remain fixed to the parent pagecontainer so they do not scroll when pagecontainer scrolls but they will move when i scroll the entire browser windowi have already tried the jquery fixto plugin but i cannot use that one because my pages fade inout and the script bugs out when the parent element pagecontainer has an alpha of 0 it thinks the parent element is gone and has nowhere to fix tothanks,['css'] +431063,how do you do date math that ignores the year i am trying to select dates that have an anniversary in the next 14 days how can i select based on dates excluding the year i have tried something like the followingselect from eventswhere extractmonth from date 3and extractday from date extractday from date 14the problem with this is that months wrapi would prefer to do something like this but i do not know how to ignore the yearselect from eventswhere date 20130301 and date 20130401how can i accomplish this kind of date math in postgres,['sql'] +431105,change the color of divider in linearlayout may i know how i can change the color of divider in linearlayoutlinearlayout androidlayout widthmatch parent androidlayout height48dp androidorientationhorizontal androiddividerandroidattrdividervertical androiddividerpadding12dip androidshowdividersmiddle androidbackgroundff2d2d2d linearlayoutdo i need to manually copy 9 patch image from android sdk into my project and define my own attribute to refer it,['android'] +431106,rotating a background image with css3 i have a background image that has an arrow that points to the right when a user clicks on the button the selected state changes the arrow to point down using a different background position in my image spriteis there anyway to animate this using css3 so once the button is clicked and jquery assigns it a selected class it will rotate in an animation only 90 degrees from the right to down preferably using the single imageposition with the arrow that points to the righti am unsure as to whether transform or key animation frames need to be used,['css'] +431117,using c11 with gyp project i am trying to create a simple cross platform c project with gyp currently i am just trying this on a mac but would like to get it to build for windows linux ios and android eventually here is the simple gyp file that i am using i would like to be able to use ninja as well as xcodemsvc projects from this gypi know that i need to be able to addstdc11 and libstdc to the commandline for clang but right now i only see the generated build files using g instead of clang this is my gyp file targets target name libtest product name test type static library sources srclibcpp include dirs include target name testapp type executable sources testtestcpp include dirs src dependencies libtest,['c++'] +431133,is it possible to create this kind of custom view in android i was just wondering if i can create a similar kind of layout in androidthe custom view must be expandable depending upon image nature i tried with gridview to make this kind of viewif anyone has worked with a similar kind of thing let me know thanks in advance,['android'] +431137,how to create and use variable in views template in rails i am still new to ruby and rails and is looking to create a variable so i can use it over and over again in the views template for examplemy code right now is titlehome pagetitleh3welcome to my home pageh3now i want to make this home page as variable or symbol so i can just use that variablesymbol rather than typing the string over and over how to do it thanks,"['ruby-on-rails', 'ruby']" +431158,advantages of using thisplayinlineblock vs floatleft in css normally when we want to have multiple divs in a row we would use float left but now i thiscovered the trick of thisplayinlineblockexample link hereit seems to me that thisplayinlineblock is a better way to align divs in a row but are there any drawbacks why is this approach less popular then the float trick,"['css', 'html']" +431175,register clr function wcf based in sql server 2012 i have a clr based stored procedure which used msmqintegrationbinding to post messages to remote msmqs everything was working fine in sql server 2005 but now there is an upgrade from 2005 to 2012 suppose to happen i tried to register the clr sp in sql server 2012 but while registering systemservicemodelldll it came up with the following error msg 6544 level 16 state 1 line 1 create assembly for assembly systemservicemodel failed because assembly microsoftvisualbasicactivitiescompiler is malformed or not a pure net assembly unverifiable pe headernative stubi searched for the resolution and it appears that few other people are having the same problem and as of now there is no solution to it the primary reason for using msmqintegrationbinding is we wanted to make sure that each message is delivered only once as you can see that i was pretty much interested in the exactlyonce property which is not there in the normal systemmessaging class we process thousand of messages and ordering of messages is very important further more each message is stamped with an id and if any message is sent which has an id that is less than the message previously sent the client system halts big problem i also have rewritten the clr stored proc using systemmessaging i just need suggestions whether it can support the scenario i mentioned above,['sql'] +431203,cannot create a multi user chat muc room with asmack library for android packetdefaultpacketextension cannot be cast to packetmucuser for an application i need to be able to create a multi user chatroom and join it the chat server is a openfire serveri used to havemultiuserchat chat new multiuserchatconnection roomname conferencelocalhostchatjoinnicknamewhen the room does not exist it creates the room and joins however the next user cannot join he gets a 404 recipient unavailable404 which suggests the chatroom is locked or somethingthen i found code in the documentation and i tried the followingchatcreatenickname send an empty room configuration form which indicates that we want an instant roomchatsendconfigurationformnew formformtype submithowever when i try to execute this it says it crashes with the following error in the logcat0302 120412890 eandroidruntime20872 fatal exception asynctask 3 0302 120412890 eandroidruntime20872 javalangruntimeexception an error occured while executing doinbackground 0302 120412890 eandroidruntime20872 caused by javalangclasscastexception orgjivesoftwaresmackpacketdefaultpacketextension cannot be cast to orgjivesoftwaresmackxpacketmucuser 0302 120412890 eandroidruntime20872 at orgjivesoftwaresmackxmucmultiuserchatgetmucuserextensionmultiuserchatjava2002 0302 120412890 eandroidruntime20872 at orgjivesoftwaresmackxmucmultiuserchatcreatemultiuserchatjava364 0302 120412890 eandroidruntime20872 at bexioscrspivimanagersxmppmanagercreateorjoinchatgroupxmppmanagerjava116hope someone can help me with this and give some advise,['android'] +431250,how uiview animations with blocks work under the hood i am new to objectivecios programming and i am trying to understand how uiview animation works under the hoodsay i have a code like thisuiview animatewithduration20 animations selflabelalpha 10the thing that gets passed as an animations argument is an objectivec block something like lambdasanonymous functions in other languages that can be executed and then it changes the alpha property of label from current value to 10 however the block does not accept an animation progress argument say going from 00 to 10 or from 0 to 10 my question is how the animation framework uses this block to know about intermediate frames as the block only specifies the final stateeditmy questions is rather about under the hood operation of animatewithduration method rather than the ways to use it my hypothesis of how animatewithduration code works is as followsanimatewithduration activates some kind of special state for all view objects in which changes are not actually performed but only registeredit executes the block and the changes are registeredit queries the views objects for changed state and gets back the initial and target values and hence knows what properties to change and in what range to perform the changesit calculates the intermediate frames based on the duration and initialtarget values and fires the animationcan somebody shed some light on whether animatewithduration really works in such way,"['ios', 'objective-c']" +431251,android pinch zoom large image memory efficient without losing detail my app has to thisplay a number of high resolution images about 19002200 px support pinch zoom to avoid out of memory error i plan to decode image to show full screen by usingoptionsinsamplesize scale scale was calculated as power of 2 as documentmy view i used is touchimageview extends of imageviewso i can quickly load image and swipe smoothly between screensimages however when i pinch zoom my app loses detail because of scaled imageif i load full image i cannot load quickly or smoothly swipe drag after pinch zoomthen i try to only load full image when user begin pinchzooming but i still cannot drag smoothly image because of very large image android gallery can do it perfectly even 8mpx imagesanyone can help me thanks in advance,['android'] +431288,twitter bootstrap affixed navbar div below jumps up rather hard to describe the problem so just look at this jsfiddlewhen the navbar gets fixed to the top the content jumps below itcssaffix position fixed top 0pxabovetop height 100px background blackwhere is the problem,"['jquery', 'css']" +431293,two uitabbarcontrollers sharing one viewcontroller as tab content situation two uitabbarcontrollers each with their own tabs but last tab in both is identical so want one uiviewcontroller to show content issue at runtime shared item only appears in one of the tab sets when shownquestion anyone know a way to make this work link to external graphic of storyboard setup sorry do not have enough reputation to post images herestoryboard graphican xcode project with that storyboardxcode projecteach tab content item has it is own uiviewcontroller class they contain no code except the line to make the back buttons workyes i know this is odd real situation is an ipad app where tab controllers are shown in popovers popovers are property editors where different objects have different properties but all share a common set of properties thus one tab for unique props one shared tab content for the common props all objects havei have found a couple ways around this to get the effect i want but if this storyboard worked it would be a much easier solution other info somewhat unrelated to question alternate solution i am using tabbarcontrollers only link to one vc as tab content when that tab vc loads i use code to a instantiate shared vc from storyboard by identifier b add that new vc object to the tabbarcontroller via tabcontroller setviewcontrollerslist animatednoanother possible solution i like even less not using a tabbarcontroller and presenting content vcs with my own tab graphic drawn into them each showing myself as selected yukso i have a working solution i am just curious as to why this does not work just a known thing in ios api or some magical property setting that might render it functional,['ios'] +431300,what does sizeofarray return following the question how come an arrays address is equal to its value in cinclude stdiohdefine and 10 char str2nhelloint main printfsizeofstr2 d bytesn sizeofstr2 printfsizeofstr2 d bytesn sizeofstr2 return 0outputsizeofstr2 10 bytessizeofstr2 4 bytesi know that str2 alone is the adress of the first element in array str2 and that when str2 is an argument of sizeof it returns the size of the whole array str2in addition str2 is also the adress of the first element in arr str2 but from diffrent type char n pointer to array but how str2 behaves when it is an argument of sizeof,['c'] +431337,how to properly maintain a listening port for a long time i wrote this small server application in pure c that listens to incoming connections in a given port very simple stuffit goes with the usual socket initialization procedure create the socket then bind to the port says its a listen and ifinitely loops through a select waiting for incoming connections to acceptall goes just fine and works like a charm except that if i leave the thing running for a couple months the listening port closes while the application server keeps running unaware of it since i wrote it to trust the listening socket will not close if not told toso the question is why the hell is the port being closed without my applications concern and what can i do to prevent it from happeningis that expected behaviour should i check for some kind of exceptions or make health check on the listening socket to reopen it if necessarycode yes i realize i am using 0 as cue for errors and it is bad pratice and stuff but it is not relevant to the question as i explained in the comments when i set the socket file descriptor to 0 it is to stop the loop and shut down the application,['c'] +431345,javascript functions and default parameters not working in ie and chrome i created a function like thisfunction saveitemandclose false it works fine in firefoxin ie it gives this error on the consoleexpected in chrome it gives this error in the consoleuncaught syntaxerror unexpected token both browsers mark the source of the error as the function creation line,"['javascript', 'jquery']" +431353,how to get httpclient json serializer to ignore null values i am currently working with a console app which i am using the httpclient to interact with an apache couchdb database i am using this article i would like to ignore the null properties in my class when i am serializing and sending a document to my database via the postasjsonsync but i am not sure howpublic static httpresponsemessage insertdocumentobject doc string name string db httpresponsemessage result if stringisnullorwhitespacename result clientsetuppostasjsonasyncdb docresult else result clientsetupputasjsonasyncdb stringformat0 name docresult return result static httpclient clientsetup httpclienthandler handler new httpclienthandler handlercredentials new networkcredential httpclient client new httpclienthandler clientbaseaddress new uri needed as otherwise returns plain text clientdefaultrequestheadersacceptaddnew mediatypewithqualityheadervalueapplicationjson return client heres the class i am serializingclass testdocument public string schema get set public long timestamp get set public int count get set public string rev get set public string id get set would like this to be ignored if null any help much appreciated,"['c#', '.net']" +431480,how often should i reseed in c i just wonder if it is enough to seed the random number generator only once at the beginning of a program i write functions which uses random numbers i never seed the rand generator within the function but rather leave calling srand on main entry eg my program may look likevoid func1 stdcout this is func1 stdrand stdendlvoid func2 stdcout this is func2 stdrand stdendlint main stdsrandstdtimenull func1 func2 return 0by doing so i can easily switch off seeding from the main entry it comes useful when debugging a program the results are kept the same every time i run the program without seeding sometimes if a problem occurs due to some random number it may just thisappear if a different set of random numbers is to be generated so i would prefer such a simple mechanism to switch off seedinghowever i noticed in c11s new random utility set the random number generator has to be instantiated before using eg default random engine and every time a generator has to be seeded separately i wonder if it is actually encouraged to reseed the generator whenever a new generator is needed i know i could create a global random generator and seed it only once as before but i do not really like the idea of using global variables at all otherwise if i create a local random number generator i sort of lose the ability to globally switch off seeding for debugging or whatever purposei am excited to learn the new features in c11 but sometimes it is just very confusing can anyone let me know if i got anything wrong with the new random generators or what might be the best practice in c11,['c++'] +431534,jobject how to read values in the array this is the json string dnumberofrowsadded26723string json daogetuploaddatasummaryjobject uploaddata jobjectparsejsonstring array stringuploaddataselecttokendhow do i change the code to reader the values in numberofrowsadded,['c#'] +431547,how to generate unique long using uuid i have a requirement to generate unique long ids for my database primary key columni thought i can use uuidrandomuuidgetmostsignificantbits but sometimes its generating some negative long also which is problem for meis it possible to generate only positive long from uuid there will be like billions of entries so i want that each generated key must be unique,['java'] +431634,trying to verify sha1 message signature using python what am i doing wrong i am attempting to verify the sha1 signature of a message by downloading a certificate from a website and extracting its public key there is a few bits of sample code elsewhere on so here and here however i have not yet figured out what i am doing wrongimport requestsfrom m2crypto import bio rsa evp x509def verify messagecert url msg sig cert text requestsgetcert url verifytrue cert x509load cert stringcert textcontent pubkey certget pubkey sig sigdecodebase64 write a few files to thisk for debugging purposes f opensig wb fwritesig fclose f openmsg w fwritemsg fclose f openmypubkeypem w fwritepubkeyget rsaas pem fclose pubkeyreset contextmdsha1 pubkeyverify init pubkeyverify updatemsg assert pubkeyverify finalsig 1this gives me the following assertion error file tmptestpy line 71 in verify message assert pubkeyverify finalsig 1assertionerrorhowever if i use openssl from the command line along with the files generated from the above python script it works finejamietest5 tmp openssl dgst sha1 verify mypubkeypem signature sig msgverified oki have hit a brick wall here any suggestions would be greatly appreciated thanks,['python'] +431647,connections vs datasources i am reading about connections vs datasources in java and i have some questions is a datasource really just a manager and an abstraction of a connection or multiple connections,['java'] +431675,cmake link with libboost pythonpy32so instead of libboost pythonso i am trying to build python bindings for a library that i wrote and i am having some trouble getting cmake to understand that it should use the boostpython library for python 3here is my cmake filecmake minimum requiredversion 28find packageboost components system thread python requiredfind packagepythonlibs requiredinclude directoriespython librariesinclude directoriespython include dirsinclude directoriesboost include dirsadd library pschulze shared srccandidate relationcpp srcschulzecpp srccalculatecpp srccandidatecpp srcrankingcpp srcuserinputcpp pythoncpptarget link librariespschulze boost libraries python librariesadd executable schulze srccandidate relationcpp srcschulzecpp srccalculatecpp srccandidatecpp srcrankingcpp srcuserinputcpp srcjsonspiritjson spirit readercpp srcjsonspiritjson spirit valuecpp maincpptarget link librariesschulze boost libraries python librariesadd definitionsstdgnu0x osadd subdirectory testssetcmake build type debugand this is the linker error that i getlinking cxx executable schulzecmakefilesschulzedirsrcschulzecppo in function arg to pythonusrincludeboostpythonconverterbuiltin convertershpp122 undefined reference to pyint fromlongusrlibgccx86 64linuxgnu47liblibboost pythonso undefined reference to pystring size,"['c++', 'python']" +431680,how to use bootstrap modal with link to in rails i had asked this earlier but unfortunately i am still stuck i have a link to like this link to click here page path id login datatoggle modal in pagehtmlerb the page which i want to load in modal when the link gets clickedi havediv classmodal idloginmodal test contentdivin assetspagejscoffeeloginmodalmodaloptionsbut still the link is not opening in a modal any help,['ruby-on-rails'] +431687,netbeans 7 why is my edited manifest not being included i have the following target in my buildxmltarget nameprecompile property filebuildproperties buildnumber filebuildversion tstamp format propertytimestamp patternymmdd hhmmss tstamp manifest filemanifestmf attribute namemajor valueversionmajor attribute nameminor valueversionminor attribute namerelease valuerelease attribute namebuild valuebuildnumber attribute namebuilddate valuetimestamp attribute nameprotocol valueprotocol attribute nameappcode valueappcode manifest targetit works fine opening manifestmf after a clean and build within netbeans shows all my extra attributes that i have added however when i open my jar file i see that it just contains the default stuffmanifestversion 10antversion apache ant 182createdby 170b147 oracle corporationi had this working fine before when i had two packages in one project the one package was all library stuff that i am gonna be taking to other projects so i decided to split it out into another project so i could build the library jar by itself now i have this problem it occurs both when i compile the library on its own as well as my other project that depends on it,['java'] +431718,what does it mean for a method to be deprecated and how can i resolve resulting errors why do i get a deprecation error on the line containing setwallpaperbmp and how can i resolve iterror the method setwallpaperbitmap from the type context is deprecatedswitchvgetid case ridbsetwallpapertry getapplicationcontextsetwallpaperbmp catch ioexception e todo autogenerated catch block eprintstacktrace break,"['java', 'android']" +431736,why is file uppercase and dir lowercase in ruby 200p0 the dir variable was introduced for easy access to the directory of the file currently being executedwhy is dir lowercase when file is uppercase,['ruby'] +431762,android create a simple menu programmatically i am trying to create a simple menu with one button that will call a method to clear the array i do not want to use xml because all i need is one buttonsomething like this public boolean oncreateoptionsmenumenu menu button clear array onclick run method that wipes array return truethank you,['android'] +431838,python cannot import name i have been wrestling most of the night trying to solve an import errorthis is a common issue but no previous question quite answers my issuei am using pydev an eclipse plugin and the library kivy a python libraryi have a file structure set up like thiscode init py mainpy enginepy main menu widgetpycode is held within the eclipse folder myproject but it is not a package so i did not include itthe files look like thismainpy mainpyfrom codeengine import engineclass motionappapp ommitedenginepy enginepyfrom codemain menu widget import mainmenuwidgetclass engine ommitedmain menu widgetpy main menu widgetpyfrom codeengine import engineclass mainmenuwidgetscreen passthe error i recieve in full detail is traceback most recent call last file cmyprojectcodemainpy line 8 in module from codeengine import engine file cmyprojectcodeenginepy line 6 in module from codemain menu widget import mainmenuwidget file cmyprojectcodemain menu widgetpy line 3 in module from codeengine import engineany idea what i did wrong here i just renamed my entire folder structure because i screwed up this module structure so bad but i think i am close to how it should look,['python'] +431867,phonegap application text and layout too small i recently build an android app using html css javascript and running them through phonegap to create the actual app one of the problems i encountered in one phone is that the text looks too small also some images are a little small as well i added a viewport meta tag but it doesnt seem to work either here are the meta tags meta httpequivcontenttype contenttexthtml charsetutf8 meta nameformatdetection contenttelephoneno meta nameviewport contentwidthdevicewidth initialscale10 minimumscale10 userscalableno targetdensitydpidevicedpi this is how it looksthis is how its supposed to look,"['javascript', 'html', 'css']" +431877,how to clear a session container in zend framework2 i have recently started building an application using zendframework 2 i have good experience in zf1 the major problem i am facing here with zf2 is with sessions here is the way that i am creating a session container use zendsessioncontainer session container creation previously we were calling it as namespaces session user new containerusersession user errors new containerusererrorssession user shares new containerusersharesnow like this i have several containers i could clear a key of a particular container like this getting value from the session by key get value from namespace email session useroffsetgetemail setting value in session set value from namespace session useroffsetsetusername abcdnow my problem is to clear an entire container which are set in several levels of my application if i try the below code its clearing all of my session containers session user new containerusersession usergetmanagergetstoragecleari want to clear only the container called user which has many keys i dont know what all will be there at end is there a way to achieve this i know i can do offsetunset on each key but thats not an optimal solution i feel please kindly suggest if any alternative way is there to clear a particular session container note i am not using any of the third party modules like zfcuser and akrabat sessions thanks in advance for responding to this posting,['php'] +431898,minifycompress css with regex in php can you compressminify css with regex pcreas a theoretical in regex i am sure there are libraries out there that do this wellbackground note after spending hours writing an answer to a deleted half crap question i thought i would post a part of the underlying question and answer it my self hope it is ok,"['php', 'css']" +431927,hide text node in element but not children i am having a little trouble with css and cannot seem to find a solution i have this htmldiv idcloselink a hrefclosea click to closedivnow i want to hide the text aclick to closea only without hiding neither the div nor the link within itcan this be done,['css'] +432024,django pytest does not find settings module i do have the following project structurebase initpy settings init py settingspy tests pytestini test modulepymy pytestini looks like thispytestdjango settings module basesettingssettingsmy test modulepy looks like thisdef test django from basesettings import settings as base settings from djangoconf import settings as django settings assert 35when i now run pytestit will run the imports without issue and will raise an error at assert 35 as expected this tells me that base is on syspath and that basesettingssettings can be imported now i change test modulepy todef test django from basesettings import settings as base settings from djangoconf import settings as django settings print django settingsx assert 35when i now run pytest dsbasesettingssettingsi get the error error could not import settings basesettingssettings is it on syspath no module named basesettingssettings the same effect when i do not set the settings via command line but via the pytestini file by uncommenting the lineit looks like i miss something here,['python'] +432033,how to put an image in the center of navigationbar of a uiviewcontroller i have this snippet of code used in viewdidload of a uiviewcontroller iva no errors images exists i get the background but not the image image is a sort of logoif selfnavigationcontrollernavigationbar respondstoselectorselectorsetbackgroundimageforbarmetrics background of navigationbar uiimage navigationbarimage uiimage imagenamed01 navbar portraitpng selfnavigationcontrollernavigationbar setbackgroundimagenavigationbarimage forbarmetricsuibarmetricsdefault image in navigationbar uiimage logoinnavigationbar uiimage imagenamed01 logopng uiimageview logoview uiimageview alloc init logoview setimagelogoinnavigationbar selfnavigationcontrollernavigationitemtitleview logoview,['ios'] +432038,why can you throw anything in java in java theoretically you can throw only throwablesthis is allowed by the language and checked during classloading but if you thisable class checking java xverifynone cp badclassthatcompilesthen you can run a class that throws any class not derived from throwable examplewhywhy is it designed this way meaning a virtual machine that allows throwing objects and a verifier that has to filter out wrong code as if some code could be wrong it is not the code it is the designwhy,['java'] +432062,hibernate insert query during insertion in hibernate query i am passing some fields as table class objects which i have mapped to corresponding tables the query works fine but the query is becoming too large because each of these mapped objects are getting updated individually to their corresponding tablescan anyone please tell me whether this is the correct way of insertion and also why i am getting those update querieshibernate insert into ortmstool modified his tbl tool desc old tool desc connec1 old connec1 connec2 old connec2 landed cost old landed cost acqui date old acqui date manuf date old manuf date price ref old price ref op rate cost old op rate cost stb rate cost old stb rate cost day rate1 cost old day rate1 cost day rate2 cost old day rate2 cost packermilling cost old packermilling cost sale value old sale value status created date modified date tool id tool modi reas id tool modi usr id supplier id old supplier id tc status id old tc status id pricing type id old pricing type id old ownership id ownership id unit id old unit id branch id old branch id reta tool choice id old reta tool choice id non ser tol cho id old non ser tol cho id charge by id old charge by id size range id old size range id rack id old rack id values hibernate update ortmsmaster2 tool master set tool id tool desc connec1 connec2 landed cost acqui date manuf date price ref op rate cost stb rate cost day rate1 cost day rate2 cost packermilling cost sale value uploaded filename uploaded file status created date modified date supplier id tc status id pricing type id unit id reta tool choice id non ser tol cho id branch id charge by id size range id rack id ownership id where idhibernate update ortmstable users set user code username password first name last name status created date modified date dept id branch id where idhibernate update ortmstable choice select set choice name status created date modified date where idhibernate update ortmsmaster2 toolmast chargeby set chargeby status created date modified date where idhibernate update ortmsmaster2 sizerange set size code size range status created date modified date grp lev3 id where idhibernate update ortmsmaster2 group level3 set grp lev3 name grp lev3 desc created date modified date status grp lev2 id where idhibernate update ortmsmaster2 group level2 set grp lev2 name grp lev2 desc created date modified date status grp lev1 id where idafter calling action master2toolmastertoolmaster time taken 1234 msupdation 2toolmodifiedhistblhbmxmlxml version10doctype hibernatemapping public hibernatehibernate mapping dtd 30en generated mar 2 2013 92905 pm by hibernate tools 321ga hibernatemapping class namemappingfilestoolmodifiedhistbl tabletool modified his tbl catalogortms id nameid typejavalanginteger column nameid generator classidentity id property nametooldesc typestring column nametool desc length65535 property property nameoldtooldesc typestring column nameold tool desc length65535 property property nameconnec1 typestring column nameconnec1 length60 property property nameoldconnec1 typestring column nameold connec1 length60 property property nameconnec2 typestring column nameconnec2 length60 property property nameoldconnec2 typestring column nameold connec2 length60 property property namelandedcost typestring column namelanded cost length20 property property nameoldlandedcost typestring column nameold landed cost length20 property property nameacquidate typedate column nameacqui date length10 property property nameoldacquidate typedate column nameold acqui date length10 property property namemanufdate typedate column namemanuf date length10 property property nameoldmanufdate typedate column nameold manuf date length10 property property namepriceref typestring column nameprice ref length20 property property nameoldpriceref typestring column nameold price ref length20 property property nameopratecost typestring column nameop rate cost length20 property property nameoldopratecost typestring column nameold op rate cost length20 property property namestbratecost typestring column namestb rate cost length20 property property nameoldstbratecost typestring column nameold stb rate cost length20 property property namedayrate1cost typestring column nameday rate1 cost length20 property property nameolddayrate1cost typestring column nameold day rate1 cost length20 property property namedayrate2cost typestring column nameday rate2 cost length20 property property nameolddayrate2cost typestring column nameold day rate2 cost length20 property property namepackermillingcost typestring column namepackermilling cost length20 property property nameoldpackermillingcost typestring column nameold packermilling cost length20 property property namesalevalue typestring column namesale value length20 property property nameoldsalevalue typestring column nameold sale value length20 property property namestatus typestring column namestatus length20 property property namecreateddate typetimestamp column namecreated date length19 property property namemodifieddate typetimestamp column namemodified date length19 property manytoone classmappingfilesmaster2toolmaster uniquetrue nametoolid columntool id cascadeall manytoone classmappingfilestablemodifiedreason uniquetrue nametoolmodireasid columntool modi reas id cascadeall manytoone classmappingfilestableusers uniquetrue nametoolmodiusrid columntool modi usr id cascadeall manytoone classmappingfilestablesupplier uniquetrue namesupplierid columnsupplier id cascadeall manytoone classmappingfilestablesupplier uniquetrue nameoldsupplierid columnold supplier id cascadeall manytoone classmappingfilestabletoolcontractstatus uniquetrue nametcstatusid columntc status id cascadeall manytoone classmappingfilestabletoolcontractstatus uniquetrue nameoldtcstatusid columnold tc status id cascadeall manytoone classmappingfilesmaster2pricetype uniquetrue namepricingtypeid columnpricing type id cascadeall manytoone classmappingfilesmaster2pricetype uniquetrue nameoldpricingtypeid columnold pricing type id cascadeall manytoone classmappingfilestableownership uniquetrue nameoldownershipid columnold ownership id cascadeall manytoone classmappingfilestableownership uniquetrue nameownershipid columnownership id cascadeall manytoone classmappingfilesmaster2unitmaster uniquetrue nameunitid columnunit id cascadeall manytoone classmappingfilesmaster2unitmaster uniquetrue nameoldunitid columnold unit id cascadeall manytoone classmappingfilestablebranchescompany uniquetrue namebranchid columnbranch id cascadeall manytoone classmappingfilestablebranchescompany uniquetrue nameoldbranchid columnold branch id cascadeall manytoone classmappingfilestablechoiceselect uniquetrue nameretatoolchoiceid columnreta tool choice id cascadeall manytoone classmappingfilestablechoiceselect uniquetrue nameoldretatoolchoiceid columnold reta tool choice id cascadeall manytoone classmappingfilestablechoiceselect uniquetrue namenonsertolchoid columnnon ser tol cho id cascadeall manytoone classmappingfilestablechoiceselect uniquetrue nameoldnonsertolchoid columnold non ser tol cho id cascadeall manytoone classmappingfilesmaster2toolmastchargeby uniquetrue namechargebyid columncharge by id cascadeall manytoone classmappingfilesmaster2toolmastchargeby uniquetrue nameoldchargebyid columnold charge by id cascadeall manytoone classmappingfilesmaster2sizerange uniquetrue namesizerangeid columnsize range id cascadeall manytoone classmappingfilesmaster2sizerange uniquetrue nameoldsizerangeid columnold size range id cascadeall manytoone classmappingfilesmaster2racks uniquetrue namerackid columnrack id cascadeall manytoone classmappingfilesmaster2racks uniquetrue nameoldrackid columnold rack id cascadeall classhibernatemappingtableusershbmxmlxml version10doctype hibernatemapping public hibernatehibernate mapping dtd 30en generated jan 13 2013 42604 pm by hibernate tools 321ga hibernatemapping class namemappingfilestableusers tabletable users catalogortms id nameid typejavalanginteger column nameid generator classidentity id property nameusercode typestring column nameuser code length60 property property nameusername typestring column nameusername length50 property property namepassword typestring column namepassword length50 property property namefirstname typestring column namefirst name length60 property property namelastname typestring column namelast name length60 property property namestatus typestring column namestatus length20 property property namecreateddate typetimestamp column namecreated date length19 property property namemodifieddate typetimestamp column namemodified date length19 property manytoone classmappingfilestabledepartments uniquetrue namedeptid columndept id cascadeall manytoone classmappingfilestablebranchescompany uniquetrue namebranchid columnbranch id cascadeall classhibernatemappingupdation 3i have removed cascadeall attribute from all mappingsnow i am getting one update rest all clear hibernate insert into ortmstool modified his tbl tool desc old tool desc connec1 old connec1 connec2 old connec2 landed cost old landed cost acqui date old acqui date manuf date old manuf date price ref old price ref op rate cost old op rate cost stb rate cost old stb rate cost day rate1 cost old day rate1 cost day rate2 cost old day rate2 cost packermilling cost old packermilling cost sale value old sale value status created date modified date tool id tool modi reas id tool modi usr id supplier id old supplier id tc status id old tc status id pricing type id old pricing type id old ownership id ownership id unit id old unit id branch id old branch id reta tool choice id old reta tool choice id non ser tol cho id old non ser tol cho id charge by id old charge by id size range id old size range id rack id old rack id values hibernate update ortmsmaster2 tool master set tool id tool desc connec1 connec2 landed cost acqui date manuf date price ref op rate cost stb rate cost day rate1 cost day rate2 cost packermilling cost sale value uploaded filename uploaded file status created date modified date supplier id tc status id pricing type id unit id reta tool choice id non ser tol cho id branch id charge by id size range id rack id ownership id where id,['java'] +432114,how to use virtualenvwrapper in supervisor when i was developing and testing my project i used to use virtualenvwrapper to manage the environment and run itworkon myprojectpython myprojectpyof course once i was in the right virtualenv i was using the right version of python and other corresponding libraries for running my projectnow i want to use supervisord to manage the same project as it is ready for deployment the question is what is the proper way to tell supervisord to activate the right virtualenv before executing the script do i need to write a separate bash script that does this and call that script in the command field of supervisord config file,['python'] +432150,viewbag viewdata tempdata session how and when to use them viewdata and viewbag allows you to access any data in view that was passed from controllerthe main difference between those two is the way you are accessing the data in viewbag you are accessing data using string as keys viewbaganumbersain viewdata you are accessing data using properties viewdatanumbersviewdata examplecontroller var numbers new listint 1 2 3 viewdatanumbers numbersviewul foreach var number in listintviewdatanumbers linumberli ulviewbag examplecontroller var numbers new listint 1 2 3 viewbagnumbers numbersviewulforeach var number in viewbagnumberslinumberli ulsession is another very useful object that will hold any informationfor instance when user logged in to the system you want to hold his authorization level getuserauthorizationlevel some method that returns int value for user authorization levelsessionauthorizationlevel getuserauthorizationleveluseridthis information will be stored in session as long as user session is active this can be changed in webconfig filesystemweb sessionstate modeinproc timeout30so then in controller inside the action public actionresult levelaccess if sessionauthorizationlevelequals1 return viewlevel1 if sessionauthorizationlevelequals2 return viewlevel2 return viewaccessdenied tempdata is very similar to viewdata and viewbag however it will contain data only for one request controller you created a method to add new clienttempdataclientadded client has been addedviewif tempdataclientadded null h3tempdataclientadded h3tempdata is useful when you want to pass some information from view to controller for instance you want to hold time when view was requestedviewtempdatadateofviewwasaccessed datetimenowcontrollerif tempdatadateofviewwasaccessed null datetime time datetimeparsetempdatadateofviewwasaccessedtostring,['c#'] +432158,is there a python scipy function to determine parameters needed to obtain a target power in r there is a very useful function that helps with determining parameters for a two sided ttest in order to obtain a target statistical powerthe function is called powerproptestyou can call it usingpowerproptestp1 50 p2 75 power 90and it will tell you and the sample size needed to obtain this power this is extremely useful in deterring sample sizes for testsis there a similar function in the scipy package,['python'] +432190,c for vs foreach huge performance difference i was making some optimizations to an algorithm that finds the smallest number that is bigger than x in a given array but then a i stumbled on a strange difference on the code bellow the foreachupper ends in 625ms and the forupper ends in i believe a few hours insanely slower why so class teste public double valor get set public testedouble d valor d public override string tostring return teste valor private static ienumerableteste gettestedouble total for int i 1 i total i yield return new testei static void mainstring args int total 10 1030 double test total27 var ieteste gettestetotaltolist consolewriteline foreachupperietesteselectddvalor test consolewriteline forupperietesteselectd dvalor test consoleread private static void forupperienumerabledouble biglist double find var start1 datetimenow double uper 0 for int i 0 i biglistcount i var tomatch biglistelementati if tomatch find uper tomatch break var end1 datetimenow start1totalmilliseconds consolewritelineend1 uper private static void foreachupperienumerabledouble biglist double find var start1 datetimenow double upper 0 foreach var tomatch in biglist if tomatch find upper tomatch break var end1 datetimenow start1totalmilliseconds consolewritelineend1 upper thanks,['c#'] +432203,why does binding the mainwindow datacontext in xaml fail to act the same as binding in the codebehind with thisdatacontextthis i am trying to use data binding to bind an observablecollection to the itemssource of a datagrid as i learn about wpf and stuffin the codebehind i can set the datacontext with thisdatacontext this or bloopdatagriddatacontext this that is fine and dandyi thought i could try something likewindowdatacontext localmainwindowwindowdatacontextin my main window but this causes a stack overflow exception as explained in this question fine that makes some senseafter reading this and other questionsanswers that say to try datacontextbinding relativesourcerelativesource self in the windows xaml code i thought i could actually do this apparently i cannot or at least the ide lets me and it is syntactically correct but does not do what i want ie exactly what thisdatacontext this doesthen i read this about using binding elementname path and tried to use it like sodatagrid namebloopdatagrid gridrow1 itemssourcebinding elementnametestwin pathoutputcollectiondatagridwhich also does not work maybe not for the same reason but i cannot figure out the problem with it oddly i cannot replicate the rebinding example shown in rachel lims blog postxamlwindow xclassdatabindingmainwindow xmlns xmlnsx titlemainwindow height350 width525 xnametestwin grid gridrowdefinitions rowdefinition rowdefinition gridrowdefinitions label gridrow0 contentbinding text label datagrid namebloopdatagrid gridrow1 itemssourcebinding pathoutputcollection datagrid gridwindowcusing systemusing systemcollectionsobjectmodel for observablecollectiontusing systemwindowsnamespace databinding public partial class mainwindow window public string text get set public observablecollectionteststruct outputcollection get set public struct teststruct public teststructstring x string y this col1 x col2 y public string col1 get set public string col2 get set public mainwindow initializecomponent testa t1 new testa thisdatacontext this thisdatacontext t1 bloopdatagriddatacontext this text bound this t1text bound a class outputcollection new observablecollectionteststruct outputcollectionaddnew teststruct1 2 outputcollectionaddnew teststruct3 4 public class testa public string text get set the above code is what i am using to test this and is currently using the codebehind version which correctly gives mewhat am i doing wrong which is preventing me from getting the same results as the above picture but by using xaml for the datacontext handling am i not connecting the dots properly am i missing some dots,['c#'] +432209,unable to find the requested net framework data provider sqlclient i am trying to set up a simple aspnet mvc 4 webapp using db first migrations from a sql server 2005 i have created the tables in the database and used entity framework to create the objects in the code i can access the data using these objectsthe problems come when i try to initialize the websecurity using websecurityinitializedatabaseconnectionflmrentities userprofile userid username true in the globalasaxcs file i have tried using the initializesimplemembershipattribute filter that came with the template and got the same issue i get the error messageunable to find the requested net framework data provider it may not be installedhere is the relevant connection stringadd nameflmrentities connectionstringmetadataresmodelsflmrcsdlresmodelsflmrssdlresmodelsflmrmsl providersystemdatasqlclient provider connection stringquotdata sourcenotesmariettaedu initial catalogmuskwater user idmuskwaterpassword multipleactiveresultsetstrue appentityframeworkquot providernamesystemdataentityclient also i have created the membership tables in the database to match what the template creates if i change the final parameter in the initialize call to false so that it does not try to create the tables automatically it returns that it cannot find the userprofile table i have also tried variations on the names such as dbouserprofileall i need is to have a simple account model to allow users to log in and allow certain users to see more content,['c#'] +432221,breakpoint will not currently be hit no executable code associated with this line i have a class in a h fileclass blahpublic blah virtual blah void writemessage bool messagereceived ifmessagereceived cout message recievedn i was trying to figure out why my code is not working so i set a breakpoint on the conditional inside the writemessage funcition but as soon as i started running the project in debug mode the breakpoint faded out and the tooltip for it saidbreakpoint will not currently be hit no executable code associated with this linei have no idea why this is happening because all of my other member functions for other classes work just fine when implemented in the h file what is causing thisedit okay as requested heres a stripped down version of the real code i am working withvimbabridgeapih header file for dllpragma onceifdef vimbabridgeapi exportsdefine vimbabridgeapi api declspecdllexportelsedefine vimbabridgeapi api declspecdllimportendifinclude alcamincludeshinclude vimbasystemh global variables extern hbitmap hbitextern cedit global filenamehandle global flags extern bool imagereadyextern bool take pictureusing namespace avtvmbapivimbabridgeapi api void bridgedgetimageframeptr framepoint vmbuchar t imgdatvimbabridgeapi api hbitmap externalframerecieved const frameptr pframe myobserver class class vimbabridgeapi api myobserver public iframeobserverprivate myobserver myobserver myobserver operator const myobserver class member variables bitmapinfo pbmi cedit m filenameeditpublic myobservercameraptr pcamera iframeobserverpcamera virtual myobserver void framereceived const frameptr pframe note iframeobserver is not written by me but the framereceived function is a pure virtual declared in the iframeobserver class their documentation says that framerecieved gets called by their api whenever a frame comes in and i had to implement the function i have tested this functions and it works but only when defined outside the class inside i get the error i am getting nowvimbabridgeapicpp code hidden from uservoid framerecieved const frameptr pframe dbgmsglframe receivedn setup bitmap fileheader bitmapfileheader bf new bitmapfileheader bfbftype 0x4d42 bfbfsize 6054400 54 sizeofbitmapinfo bfbfoffbits 54 infoheader bitmapinfoheader bih new bitmapinfoheader bihbisize 40 bihbiwidth 2752 bihbiheight 2200 bihbiplanes 1 bihbibitcount 32 bihbicompression 0 bibisizeimage 6054400 not required bihbixpelspermeter 2835 bihbiypelspermeter 2835 bihbiclrused 0 bihbiclrimportant 0 info bitmapinfo pbmi bitmapinfoalloca sizeofbitmapinfoheader sizeofrgbquad256 pbmibmiheaderbisize sizeof pbmibmiheader pbmibmiheaderbiwidth 2752 pbmibmiheaderbiheight 2200 pbmibmiheaderbiplanes 1 pbmibmiheaderbibitcount 8 pbmibmiheaderbicompression bi rgb pbmibmiheaderbisizeimage 0 pbmibmiheaderbixpelspermeter 14173 pbmibmiheaderbiypelspermeter 14173 pbmibmiheaderbiclrused 0 pbmibmiheaderbiclrimportant 0 create grayscale color palette forint i0 i256 i pbmibmicolorsirgbred bytei pbmibmicolorsirgbgreen bytei pbmibmicolorsirgbblue bytei pbmibmicolorsirgbreserved byte0 image data vmbuchar t imagedata null bridgedgetimagepframe imagedata create image that is printed to dialog box hdc hdc getdcnull hbit createdibitmaphdc bih cbm init imagedata pbmi dib rgb colors clean up deleteobjectbf deleteobjectbih deleteobjecthdc,['c++'] +432224,how to pass on argparse argument to function as kwargs i have a class defined as followsclass mobject def init self kwargs do somethingand i have the result of argparseparse args for example args parse args print argsnamespacevalue5 messagetest message typeemail extrablah paramwhateveri want to pass on the values of this namespace except message type to create an instance of the class m i have triedmargsbut got an error typeerror init takes exactly 1 argument 2 givenwhich i do not understand how can i remove the value message type from the list in argspass on the values as if i would type mvalue5 messagetest extrablah paramwhatever directly,['python'] +432252,xcode command line uploaddownload files tofrom an ios device application sandbox does someone of you know how i can mange the file transfer of my app data like the organizer from the command line i tried to find a way with xcrun or instruments but currently without successmy goal is to run acceptance tests on the device by jenkins currently i am able to upload a new version of my app and start it by instruments but a way for reseting the client data or push modified data to test them is missingthanksthomas,['ios'] +432256,super in constructor i am reading through some code in the constructor it has super but the class implements interface which of course does not have a constructor so which super it is referring topublic class boundingbox implements iboundingvolume public boundingbox super mtransformedmin new number3d mtransformedmax new number3d mtmpmin new number3d mtmpmax new number3d mpoints new number3d8 mtmp new number3d8 mmin new number3d mmax new number3d forint i0 i8 i mpointsi new number3d mtmpi new number3d public interface iboundingvolume public void calculateboundsgeometry3d geometry public void drawboundingvolumecamera camera float projmatrix float vmatrix float mmatrix public void transformfloat matrix public boolean intersectswithiboundingvolume boundingvolume public baseobject3d getvisual,['java'] +432270,details on what happens when a struct implements an interface i recently came across this stackoverflow question when to use struct in cin it it had an answer that said something a bit profoundin addition realize that when a struct implements an interface as enumerator does and is cast to that implemented type the struct becomes a reference type and is moved to the heap internal to the dictionary class enumerator is still a value type however as soon as a method calls getenumerator a referencetype ienumerator is returnedexactly what does this mean if i had something likestruct foo ifoo public int foobarclass bar public ifoo bizget set assume this is foovar bnew barvar fbbizffoobar123 what would happen herebbizfoobar567 would this overwrite the above or would it have no effectbbiznew foo and herewhat exactly are the detailed semantics of a valuetype structure being treated like a referencetype,"['c#', '.net']" +432317,is there a good solution for a c html sanitizer a user can enter html that will later be thisplayed to other users the wysiwyg plugin i am using sanitizes the html from the front end it removes all potentially malicious tags script src anything starting with on etc i obviously need to do some validation in the back end as well does anyone know of a good solution for c i keep seeing this though i am a little hesitant to use some code from a random blog are there any well known plugins what do most people do in this situation,"['c#', 'html']" +432318,get the day of the last friday of each month i am new with ruby and i want to get the day of the last friday of each monthfor example the last friday of march is 29 the last friday of april 26so how can i get a solution i am using the rails frameworkthe method cweek returns the week of the year but does not return the week of the current month,"['ruby-on-rails', 'ruby']" +432336,how do i input variables using cin without creating a new line whenever i input a variable using cin after one hits enter it automatically goes to a new line i am curious if there is a way to use cin without having it go to a new line i am wanting to cin and cout multiple things on the same line in the command prompt is this possible,['c++'] +432381,how to scale transition uilabel without using a lot of memory i am trying to reproduce some of the 2d transitions in impressjss sample presentation in objective c specifically the rotate pan and scaling right now i am focusing on the scalingi have tried scaling a uilabel to the point where it passes the screen as the visualize your big thoughts and tiny ideas does in the sample presentationthis is what i have tried so faruilabel label uilabel alloc initlabeltext hello worldlabeltextcolor uicolor blackcolorlabelfont uifont fontwithnamearial size18flabel sizetofitlabelcenter cgpointmakeselfviewboundssizewidth 2 selfviewboundssizeheight 2selfview addsubviewlabellabelcontentscalefactor 80uiview animatewithduration5 animations labeltransform cgaffinetransformscalelabeltransform 80 80unfortunately this eats up about 3060 mb of ram depending on what the contentscalefactor and initial font size is if i do not increase the contentscalefactor the text looks blurry increasing the font size also seems to eat just as much memoryhere is what it looks in the profilerand this is just a single uilabelis there any way to do this without eating up so much memory without sacrificing quality of the text being rendered or the transitions,['ios'] +432427,javascript save data to file system with user prompt what is the best way to achieve the below in latest latest browsers with html5 support i mainly target google chromein my application data is manipulated through javascript and needs to write output to the file system with a browser prompt save as dialog i am not sure about the security restrictions to write to file system but i am not planning anonymous write but user is prompted and selects the location i see saveas not natively supported yet with my research i see few optionsadownload web filesystemobject urlsfileserver falls back to 234 if no native support and i may use it but i do not find a way to open a save as dialog it just save a file in default location downloads folder in macwhich option would you use to get a good support in latest browsers how can get open the save as dialog and let the user name the filethanks,['javascript'] +432434,calculating difference between different columns in different rows i have a table that records what happens to a vehicle during a visit for each visit there is are multiple rows to denote what has been done the table looks like thisvisitid actionid starttime endtime 0 0 112013 122013 1 0 122013 142013 1 1 142013 172013 2 0 142013 152013 2 1 152013 162013 2 2 162013 172013i wish to construct a linq query capable of getting the amount of time a visit took totaltime is calculated by first finding the first and last lowest and highest actionid then lastendtime firststarttime expected resultsvisitid totaltime 0 1 1 5 2 3i can generate my expected results by doingvar first dbvisitswherev vactionid 0var last dbvisitsgroupbyx xvisitidselectg gorderbydescendingx xactionidfirstfirstjoinlast f fvisitid l lvisitid f l new visitid key totaltime lendtime fstarttimei really do not like the hack i used to get the last actionid and i would really like to be able to do this within 1 linq statement what do i need to do to achieve this,['c#'] +432502,signal when a qlistview selection changes due to keyboard activity i have a qdialog created with qt designer that looks like so the list of servers on the left is a qlistview with a qstringlistmodel mouse clicking an item in the list view updates the form with the information for the selected item by connecting the viewas activatedqmodelindex signal to a slot function in the dialoghowever pressing up or down on the keyboard also changes the selected item but no signal is emitted so the form is not updated to match the selected item how can this be fixed,['c++'] +432541,jquery ui tooltips how to correctly position vertically centered to the mouse update still looking for a viable solution but check my answer below it may help you or give you an idea it works for a specific resolutioni am using the jquery ui tooltips plugin but im having trouble positioning the tooltip how i wanti would like it to be centered at the mouse vertically but just to the left of the element in question i believe i am wording that correctly but i will show you a picture of what i meanthis is what it should be doingas you can see in my example it is centering vertically to the element itself not the mouseif it could move with the mouse vertically tracking only that would be perfect not sure if this is possible with this plugin i do not really understand their positioning apiand heres a jsfiddle function document tooltip items entry position my center at left content function var element this if elementis entry return div classhithis is a very nice entry it is so pretty and i feel like i can touch it this is just random filler text to give you the ideadiv i really appreciate any insight you can give me on this thanks in advance,['jquery'] +432558,google plus for android invalid credentials i am using the followin code to get an access token after connecting to google to get profile info and emailstring saccesstoken googleauthutilgettokenthismplusclientgetaccountname oauth2 scopesplus profile this access token i am not storing and trying to reuse instead i ask for an access token everytime expecting a newdifferent token so that i do not need to check whether its expired etcbut i am getting the same access token every time i ask for i uninstalled the app cleared data of google app and still i get the same access tokenthe actual problem is using this access token gives a 401 error message invalid credentials error errors domain global reason autherror message invalid credentials locationtype header location authorization code 401 message invalid credentials this is a response on browseron a device i get this in logcat0225 020946919 wsystemerr3022 javaiofilenotfoundexception 0225 020946929 wsystemerr3022 at orgapacheharmonyluniinternalnetwprotocolhttphttpurlconnectionimplgetinputstreamhttpurlconnectionimpljava5210225 020946929 wsystemerr3022 at orgapacheharmonyluniinternalnetwprotocolhttpshttpsurlconnectionimplgetinputstreamhttpsurlconnectionimpljava2580225 020946929 wsystemerr3022 at comexamplegmailloginmainactivityconnectasynctaskdoinbackgroundmainactivityjava2690225 020946929 wsystemerr3022 at comexamplegmailloginmainactivityconnectasynctaskdoinbackgroundmainactivityjava10225 020946929 wsystemerr3022 at androidosasynctask2callasynctaskjava1850225 020946929 wsystemerr3022 at javautilconcurrentfuturetasksyncinnerrunfuturetaskjava3060225 020946929 wsystemerr3022 at javautilconcurrentfuturetaskrunfuturetaskjava1380225 020946929 wsystemerr3022 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava10880225 020946929 wsystemerr3022 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava5810225 020946929 wsystemerr3022 at javalangthreadrunthreadjava1019line 269urlconnection httpurlconnection urlopenconnectioncomplete codeurl url new urlstring saccesstoken googleauthutilgettoken mainactivitythis mplusclientgetaccountname oauth2 scopesplus profile logdsaccesstoken saccesstoken urlconnection httpurlconnection urlopenconnection urlconnectionsetrequestpropertyauthorization bearer saccesstoken bufferedreader r new bufferedreadernew inputstreamreader urlconnectiongetinputstream utf8 stringbuilder total new stringbuilder string line while line rreadline null totalappendline line totaltostringeditthis is definitely because the access token is expired which was expected but i thought i will get a new access token everytime i callbut as said hereif the android device already has an auth token for the particular gdata service youre trying to access it will be returned to youso i have to do thisif server indicates token is invalid invalidate the token that we found is bad so that googleauthutil would not return it next time it may have cached it googleauthutilinvalidatetokencontext stringcontext token consider retrying getandusetokenblocking once more return like the docs saybut how can i check if the access token is expired or invalidby catching the exception is the only solutionactually the exception is javaiofilenotfoundexception which does not make sense,['android'] +432567,get events from os i work on windows but i am stuck here on mac i have the canon sdk and have built a jna wrapper over it it works well on windows and need some help with macin the sdk there is a function where one can register a callback function basically when an event occurs in camera it calls the callback functionon windows after registering i need to use user32 to get the event and to thispatch the event byprivate static final user32 lib user32instanceboolean hasmessage libpeekmessage msg null 0 0 1 peek and removeif hasmessage libtranslatemessage msg libthispatchmessage msg message gets thispatched and hence the callback function is calledin the api i do not find a similar class in mac how do i go about this oneps the jna api for unix is extensive and i could not figure out what to look for the reference might help,['java'] +432607,how to get master view controller in detail view controller with uisplitviewcontroller i have a uisplitviewcontroller with master controller and detail controllermymastercontroller masterviewcontroller mymastercontroller alloc initwithdirectorydirectoryelement autoreleasemydetailcontroller detailviewcontroller mydetailcontroller alloc initmasterviewcontrollerdetailviewcontroller detailviewcontrolleruisplitviewcontroller splitviewcontroller uisplitviewcontroller alloc initsplitviewcontrollerviewcontrollers uinavigationcontroller alloc initwithrootviewcontrollermasterviewcontroller uinavigationcontroller alloc initwithrootviewcontrollerdetailviewcontrollersplitviewcontrollerdelegate self the mydetailcontroller is a table list view controller i want to master view controller run one method when user clicks on cell so how to get the master controller in detail controller void tableviewuitableview tableview didselectrowatindexpathnsindexpath indexpath master some method how to get,['ios'] +432674,jsf range slider with time values i have jsf webapp with primefaces 35 and i would like to have a range slider but with time values hourminute as in this picturethis is the code for a range slider with integer values hpanelgrid columns1 stylemarginbottom10px houtputtext idthisplayrange valuebetween sliderbeannumber6 and sliderbeannumber7 pslider fortxt6txt7 thisplaythisplayrange stylewidth400px rangetrue thisplaytemplatebetween min and maxhpanelgridhinputhidden idtxt6 valuesliderbeannumber6 hinputhidden idtxt7 valuesliderbeannumber7 where sliderbeannumber6 and sliderbeannumber7 are integeri think that to do what i want is to redefine the jquery slide function that thisplay the range values and work with minutes instead of hours function sliderrangeslider range true min 0 max 1440 step 15 slide functione ui var hours mathflooruivalue 60 var minutes uivalue hours 60 ifhourslength 1 hours 0 hours ifminuteslength 1 minutes 0 minutes thisplayrangehtmlhoursminutes but honestly i do not know how to do and if this is the correct waythanks,['jquery'] +432678,svg as css background problems with zoom level in opera i am having difficulties using svg background with operawhen i zoom out the page the background starts repeating on the x axis despite backgroundrepeat repeatyi created a codepen showing off the problem with the first online svg image i found body backgroundimage url gnu whitesvg backgroundrepeat repeatyand here is a screenshot of operas 1214 behavior on my computerthe behavior exhibits for any svg document with widthw heighth viewbox0 0 w h dimensioningi tried various values for width height viewbox and even preserveaspectratio on the root svg element without much success so farany hint please,['css'] +432707,theming actionbarsherlock gives api level error i updated my project from android 42 to android 422 and i suddenly get this error in my stylesxmlstyle namethemestyled parentthemesherlocklightdarkactionbar item nameactionbarstylestylewidgetstyledactionbaritem requires level 11 current 7 item nameandroidactionbarstylestylewidgetstyledactionbaritemstylehow do i fix this according to the abs docs this is how it should be done see,['android'] +432733,lazy singleton in a multithreaded c application i am working on a multithreaded c application which is consuming a wcf web service the connection to the webservice will have a specific timeout which we can define and after which it will close i am looking to store the connection to the web service using singleton class i am trying to get the instance as follows clazysingleton ins clazysingletoninstancestring connection clazysingletonabcbelow is the code for the singleton class using systemusing systemcollectionsgenericusing systemlinqusing systemtextnamespace lazysingleton public class clazysingleton private static readonly lazyclazysingleton instance new lazyclazysingleton new clazysingleton private static readonly object threadlock new object public static string abc i will use the service connection object in place of abc in the application assume that abc is storing the connection object private clazysingleton public static clazysingleton instance get if abc null lock threadlock make the connection abc connection stored in this variable consolewritelineconnection made successfully return instancevalue else return instancevalue my questions are 1 would this code be able to take care of multiple threads trying to get the instance at the same time this is currently my biggest concern2 can i have a better solution for this 3 do i need to use lock here or using lazy approach takes care of multithreads trying to get the instance any help would be appreciatedthanks,"['c#', '.net']" +432759,why is coffeescript of the opinion that shadowing is a bad idea i have wanted to switch to coffeescript for a while now and yesterday i thought i am finally sold but then i stumbled across armin ronachers article on shadowing in coffeescriptcoffeescript indeed now abandoned shadowing an example of that problem would be if you use the same iterator for nested loopsvar arr hab iarr 1 2 1 2 3 1 2 3forvar i 0 i arrlength i var subarr arri function forvar i 0 i subarrlength i consolelogsubarri because cs only declares variables once i wouldnt be able to do this within coffeescriptshadowing has been intentionally removed and i would like to understand why the csauthors would want to get rid of such a featureupdate here is a better example of why shadowing is important derived from an issue regarding this problem on githubps i am not looking for an answer that tells me that i can just insert plain javascript with backticks,['javascript'] +432771,do variables in static methods become static automatically because they are within static scopes in c public static void dosomethingint astring bdo somethingin the example above i have declared two variablesdo they become static because the method that contains them is static,['c#'] +432773,nsmutablearray removeobjectatindex strange issue strange behaviour in nsmutablearrayi have created object and filled itnsmutablearray array nsmutablearray alloc initwithobjects1234 nilarray removeobjectatindex0before removing it looks likearray nsmutablearray 0x1040b5e00 id 0x088a44 11 id 0x088a54 22 id 0x088a64 33 id 0x088a74 4after removing first elementarray nsmutablearray 0x1040b5e00 id 0x0 1 id 0x088a54 22 id 0x088a64 3what am i doing wrong here,['objective-c'] +432774,how to create a option menu in android i want to create a simple option menu in android application with c and xamarin studio how can i do iti have not found any c example of this can someone simply explain how to create a option menu please,"['c#', 'android']" +432826,jquery mobile panel width in the new jquery mobile there is a new panel option i have implemented this and it works but i would like to customize the width of the panel the standard width is 272px which is a bit much for my use i have tried using theuipanelwidth150pxcss selector but this simply resizes the contents of the panel the panel itself stays visible and remains the same width using the inspectors in firefox and chrome i have not been able to find the correct div responsible for this panel could anybody help me find a way to resize the panel in the correct manner,"['jquery', 'css']" +432878,full height content with the smallest possible width i would never think this is possible but there are a lot of clever people here so i thought i would ask i am looking for a way to have a fullheight container whose width depends on how much content there is i want the text to fill the area taking up the full height while using the smallest possible width the height is known and hardcoded the amount of content is noti am working with something like thisdiv plorem ipsum is simply dummy text of the printing and typesetting industry lorem ipsum has been the industrys standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambledpdivdiv backgroundred url floatleft width600px height400pxp backgroundf padding20px margin20pxnormally content fills the page from top to bottomwhat i am looking for is sort of the opposite filling in lefttorightwith less content it should look like thisusing full hardcoded height with widthauto produces this effectis there any way to have the text fill the height with the smallest possible width without hardcoding a width or having text overflow it seems impossible and i have no idea how to approach it javascriptjquery solutions welcome,"['javascript', 'jquery', 'html', 'css']" +432915,convert linq expression to sql text without db context either linq to sql or linq to entities already have the ability to convert linq into a sql text string but i want my application to make the conversion without using the db context which in turn means an active database connection that both those providers requirei would like to convert a linq expression into an equivalent sql strings for where and order by clauses without a db context dependency to make the following repository interface workpublic interface istoret where t class void addt item void removet item void updatet item t findbyidguid id sure could use a linq to sql converter ienumerablet findexpressionfunct bool predicate ienumerablet findallquestionit is primarily the expression tree traversal and transform i am interested in does anyone know of an existing library nuget that i can incorporate to be used in such a custom contextas it is i have already built my own working linq transformed to sql text tool similar to this expression tree to sql example which works in my above repository it allows me to write code like thisirepositoryperson repo new personrepositoryvar maxweight 170var results repofindx xage 40 xage 20 xweight maxweightbut my code and that sample are primitive and that sample itself relies on a linq to sql db context for example neither handle generation of like statements i do not expect or need a generatortool that handles every conceivable linq query for example i am not worried about handling and generating joins or includes in fact with another 20 hours my own custom code may cover all the cases that i care about mostly where and order by statementsbut at the same time i feel that i should not have to write my own custom code to do this if i am stuck writing my own then i would still be interested if someone could point me to specific classes i can reflect and imitate nhibernate ef etc i am asking about specific classes to peek at if you know them because i do not want to spend hours sifting through the code of a massive tool just to find the part i neednot that it matters but if anyone wants to know why i am not simply using linq to sql or linq to entitiesfor my specific application i simply prefer to use a tool such as dapperuse caseswhether i finish building the tool myself or find a 3rd party library here are reasons why a linq to sql text string would be usefulthe predicate i type into the irepositoryfind method has intellisense and basic compiletime checkingmy proposed istore interface can be implemented for db access or web service access to clarify if i can convert the linq whereorder by predicate to a sql whereorder by clause thenthe sql string could be used by dapper directlythe sql string unlike a linq expression can be sent to a wcf service to be used for direct db access which itself might not be using dapperthe sql string could be deserialized with custom code back into a linq statement by the wcf service eric lippert comments on thisthe ui can use iqueryable mechanics to dynamically generate a predicate to give to the repositoryin short such a tool helps fulfill the specification or query object notion of repositories according to d and does so without taking a dependency on ef or linq to sql,"['c#', '.net', 'sql']" +432933,adding parameter to a scope i have a activerecord query for example like thisresult stufflimit10where stuff is a active record query with where clauses order by etcnow i thought why to pass magic numbers like that to the controller so do you think is it a good practice to define a scope for limit10 and use that instead and how would the syntax look like,['ruby-on-rails'] +432940,attempt to add a rule to a css stylesheet gives the operation is insecure in firefox i am using greasemonkey and trying to add a rule in a specific domain but it results in an error saying the operation is insecurethe code works fine on chromethe script runs on and the css file is my functionfunction cselector property value for var i0 idocumentstylesheetslengthi try documentstylesheetsiinsertruleselector propertyvalue documentstylesheetsicssruleslength catcherr try ie documentstylesheetsiaddruleselector propertyvalue catcherr on google i found that it could be because i am trying to access crossdomains so i have tried adding the url to the css file to the accepted urls but no resulthow do i fix this,"['javascript', 'css']" +432974,how to combine results of two queries into a single dataset i have two queries queries simplified excluding joinsquery 1 select productnamenumberofproducts in inventory from table1query 2 select productname numberofproductssold from table2i would like to know how i can get an output as productname numberofproductsin inventory productname numberofproductssoldthe relationships used for getting the outputs for each query are differenti need the output this way for my ssrs report i tried the union statement but it doesnt work for the output i want to see,['sql'] +432978,java stack comparison i am wondering how to accomplish thiscompare two stack objects do this recursively after the method thatdoes this is complete the stacks remain as they were to begin withie same order same itemsonly the push pop and isempty methods for stack is availablei am looking more for theoretical help than coding help but any insight would be appreciated,['java'] +432985,searching music tracks from google play store via an api i am writing an app for a record label they would like to have a list of all their albums that are published in the google play storeis there a way to get a hold of the data from the play store like titles album art etcon ios you can even access the preview samples from itunes is that possible with androidor would amazon provide such a servicei found several inofficial apis that handle searching for apps is there one that can be used for music,['android'] +432990,vertical align checkbox label i have checkboxes like thislabel classcheckboxlabelinput typecheckbox value115administratorslabelbut i cannot fugure out how to style the label to be center valigned to the checkboxi tried adding verticalalignmiddlethanks,"['html', 'css']" +432993,c error expected before token this seems like the simplest code but i do not know why it would not compile switchchoice case 0 printfd loop limit this line gives the error break case 1when i comment out the line it compiles fine,['c'] +432999,specify datacontext type on listbox itemcontainer in style in a listbox i have a itemcontainers isselected property bound to my viewmodels isselected property using listboxitemcontainerstyle syntax it works fine but i get a resharper warningcannot resolve property isselected in data context of type foosolutionbarviewmodelhow do i specify specify datacontext type on listbox itemcontainer to get rid of this warninghere is the code i have a barviewmodel classpublic observablecollectionfooviewmodel fooitems getset barviewmodel is assigned to datacontext in the control which contains the listboxand fooviewmodel as followspublic bool isselected get return isselected set if isselected value return isselected value raisepropertychanged isselected and xaml like thislistbox itemssourcebinding fooitems selectionmodemultiple listboxitemcontainerstyle style targettypextype listboxitem setter propertyisselected valuebinding isselected style listboxitemcontainerstylelistboxupdatei have tried setting ddatacontext using a setter as suggested by highcore but unfortunatelly it does not help and even breaks the buildsetter propertyddatacontext valueddesigninstance yourxmlnsyouritemviewmodelclassthrows error 1 the tag designinstance does not exist in xml namespace schemasmicrosoftcomexpressionblend2008 line 31 position 50 update 2finaly the solution is to set ddatacontext on the style element itself see my answer bellowlistboxitemcontainerstyle style targettypextype listboxitem ddatacontextddesigninstance localfooviewmodel setter propertyisselected valuebinding isselected style,['c#'] +433049,laravel stylesheets and javascript do not load for nonbase routes okayi know this is a really elementary issue but i cannot figure it out this is a question regarding laravelbasically i have my stylesheets embedded in my default layout view i am currently just using regular css to link them such aslink relstylesheet hrefcssappcss it works great when i am at a single level route such as about but stops working when i go deeper such as aboutmeif i look at chromes developer console i see some of the following errors only for the deeper routesresource interpreted as stylesheet but transferred with mime type texthtml so clearly it is now looking for the css inside the about folderwhich of course is not a folder at alli just want it to look in the same place for the assets regardless of the route,['php'] +433068,uicollectionview with a sticky header i found a blog on how to make sticky headers and it works great only thing is i do not think it takes into account the sectioninsertsthis is how its intended to looki have my insertscollectionviewflowlayoutsectioninset uiedgeinsetsmake16 16 16 16with the sticky header it is moved down by 16 pixlesi tried tinking with the original code and i think the issue is with the last partlayoutattributesframe cgrect origin cgpointmakeoriginx originy size layoutattributesframesizeif i change it to originy 16 the header will start in the right location but when pushed up 16 pixels of the head go off screeni am not sure how to get it to take into account sectioninsects can anybody helphere is the code in full from the blog nsarray layoutattributesforelementsinrectcgrectrect nsmutablearray answer super layoutattributesforelementsinrectrect mutablecopy uicollectionview const cv selfcollectionview cgpoint const contentoffset cvcontentoffset nsmutableindexset missingsections nsmutableindexset indexset for uicollectionviewlayoutattributes layoutattributes in answer if layoutattributesrepresentedelementcategory uicollectionelementcategorycell missingsections addindexlayoutattributesindexpathsection for uicollectionviewlayoutattributes layoutattributes in answer if layoutattributesrepresentedelementkind isequaltostringuicollectionelementkindsectionheader missingsections removeindexlayoutattributesindexpathsection missingsections enumerateindexesusingblocknsuinteger idx bool stop nsindexpath indexpath nsindexpath indexpathforitem0 insectionidx uicollectionviewlayoutattributes layoutattributes self layoutattributesforsupplementaryviewofkinduicollectionelementkindsectionheader atindexpathindexpath answer addobjectlayoutattributes for uicollectionviewlayoutattributes layoutattributes in answer if layoutattributesrepresentedelementkind isequaltostringuicollectionelementkindsectionheader nsinteger section layoutattributesindexpathsection nsinteger numberofitemsinsection cv numberofitemsinsectionsection nsindexpath firstcellindexpath nsindexpath indexpathforitem0 insectionsection nsindexpath lastcellindexpath nsindexpath indexpathforitemmax0 numberofitemsinsection 1 insectionsection uicollectionviewlayoutattributes firstcellattrs self layoutattributesforitematindexpathfirstcellindexpath uicollectionviewlayoutattributes lastcellattrs self layoutattributesforitematindexpathlastcellindexpath cgfloat headerheight cgrectgetheightlayoutattributesframe cgpoint origin layoutattributesframeorigin originy min max contentoffsety cgrectgetminyfirstcellattrsframe headerheight cgrectgetmaxylastcellattrsframe headerheight layoutattributeszindex 1024 layoutattributesframe cgrect origin origin size layoutattributesframesize return answer,"['ios', 'objective-c']" +433072,tostringx produces single digit hex numbers we wrote a crude data scopethe freeware terminal programs we found were unable to keep up with bluetooth speedsthe results are okay and we are writing them to a comma separated file for use with a spreadsheet it would be better to see the hex values line up in nice columns in the richtextbox instead of the way it looks now screen cap appendedthis is the routine that adds the digits eg numbers from 0 to ff to the text in the richtextbox public void writebyte b if writting for int i 0 i blength i storagesplace bi pass bitostringx here is the problem if splace numericupdown1value 0 pass rn i would like a way for the instruction pass bitostringx to produce a leading zero on values from 00h to 0fhor some other way to turn the value in byte b into two alphabetic characters from 00 to ffdigits on left ff 40 0 5 line up nice and neatly because they are identical as soon as we encounter any difference in data the columns vanish and the data become extremely difficult to read with human observation,['c#'] +433074,getting rid of and when using readlines i have a txt file with values in itthe values are listed like sovalue1value2value3value4my goal is to put the values in a list when i do so the list looks like thisvalue1n value2nthe and is not neededhere is my codet openfilenametxt rwcontents treadlinealist for i in contents alistappendi,['python'] +433091,how to combine nthchild rules into one i currently have this long rulecontent wrapper table tdnthchild3 content wrapper table tdnthchild4 content wrapper table tdnthchild5 width 30pxis it possible to combine the nthchild to something shorter like nthchild345 instead of 3 separate lines,"['html', 'css']" +433099,add a space in this string between words tried setting up an enum that has spaces in attributes but was very hard so figured their might be an easy way to hack this with a string format or something since their is only one enum that i need that has spaces and i know exactly what it is any helping wiht adding a space to this stringpublic class addressblahmore class datatypes herepublic addresstype type get set addresstype is an enumblah if addresstypetostring unitedstates add space between united and states,['c#'] +433124,why do parentheses affect hashes when i used respond with and passed a literal hash it gave me the errorsyntax error unexpected tassoc expecting respond with status not foundhowever when i enclosed the literal hash in parentheses like sorespond withstatus not foundthe function runs without a hitch why do the parentheses make a difference is not a hash an enclosed call,['ruby'] +433196,correct way to removepurge all keychain data for an ios app i stored some information in the keychain and there is a case that i need to remove all of the items instead of doing keychain removeobjectforkeythekey for all the keys can i donsdictionary spec nsdictionary dictionarywithobjectsandkeysidksecclassgenericpassword ksecclass self servicename ksecattrservice nilreturn secitemdeletecfdictionaryrefspecinsteadi tried it and it worked just not sure if i am doing the correct thing,"['ios', 'objective-c']" +433215,select users have more than one thistinct records in mysql for a table that holds the records of users webpages visiting behavior how can i select users that visit more than one webpagesthe structure of this tables isuserid webpageid visittime 0 123 0 124 1 123 i can count usingselect userid countthistinct webpageid as count from visits group by useridit gives me the result likeuserid count 0 2 1 1 2 6 how can i excute query that gives me the final result likeuserid 0 2 each is user that visit more than one thistinct webpages,"['mysql', 'sql']" +433235,are androids debug logs really stripped at runtime android documentation saysverbose should never be compiled into an application except during development debug logs are compiled in but stripped at runtime error warning and info logs are always kepti just did a test in my activity i wroteprivate static string teststring what logetest i am called with argument what return whatoverridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main logvtest log level testv logdtest log level testd logitest log level testi logwtest log level testw logetest log level testei exported my project as an apk file then i installed this apk on my phone i run this application on my phone then i looked at logs there i saw that the function test was called all five times and all five calls to logsomething functions resulted in its text being written to logsso are logd calls really stripped at runtime,['android'] +433249,transfer data through audio jack cable over two android devices i am researching on transferring text data over maletomale audio jack cablei am testing this on htc one v and on pc which supports maletomale audio jack for data transfer as mentioned in this wikipedia article it saysthe first which places the return signal on the second ring and the microphone on the sleeve is used by apples iphone line htc devices latest samsung nokia and sony phones among othersyou can see my code hereproblems i face during transfer if i generate tone by entering any value from 031 at sender side receiver will get actual value in 23 try due to the wrong type of fsk modulationdemodulation would you suggest the best error correction code that will help me out for correcting the input received from another android deviceif anyone has done this type of data transfer before please suggest a code reference or some basic guidance regarding technical aspects so i can complete this and make it open source for everyone,['android'] +433325,how to know whether a string can be segmented into two strings i was asked in interview following question i could not figure out how to approach this question please guide mequestion how to know whether a string can be segmented into two strings like breadbanana is segmentable into bread and banana while breadbanan is not you will be given a dictionary which contains all the valid words,['java'] +433327,how to add custom view in maps annotations callouts here is my code i want to add my own custom callout view instead of ios default i know there is only leftcallout and right callout view but i need to add a view tool tip type with my own background and label mkannotationview mapviewmkmapview mapview viewforannotationid mkannotationannotation mkannotationview userannotationview nil if annotation iskindofclassmkuserlocationclass userannotationview mkannotationview mapview dequeuereusableannotationviewwithidentifieruserlocation if userannotationview nil userannotationview mkannotationview alloc initwithannotationannotation reuseidentifieruserlocation else userannotationviewannotation annotation userannotationviewenabled yes userannotationviewcanshowcallout yes userannotationviewimage uiimage imagenamedmap pinpng uiview view uiview allocinitwithframecgrectmake00141108 viewbackgroundcolor uicolor clearcolor uiimageview imgview uiimageview allocinitwithimageuiimage imagenamedtoltippng view addsubviewimgview userannotationviewleftcalloutaccessoryview view return userannotationview,['iphone'] +433353,slim dynamic conditional class just to help other developers because there is no similar question on sodiv classis active active inactivediv classactive if is active,['ruby-on-rails'] +433492,c changing the icon of the taskbar i want to change the icon on the taskbar of my software so i changed the project settings this path was suggested by visual studio itselfbut my taskbar still shows the same icon as before the standard one in my explorer the exe has the correct icon it just would not change in the taskbari also tried to end explorerexe and restart the task but this did not help at alli also tried to set the resolution on 16x16 and 32x32 but both did not work,['c#'] +433562,iframe prevents iscroll scrolling on mobile safari i am using iscroll on my mobile enable website using iphone here to scroll inside a divin this this div i have an iframe with a fixed height like thisbody div idiscroller iframe idtheiframeiframe other stuff divbodynow while scrolling within the div everything works as expected but i cannot scroll when the scrolling gesture begins on the iframethe problem is described here pretty well so i used the css workaround from that post by applying pointereventsnone to the iframenow scrolling works perfectly but i cannot click any links which are defined within the iframe because all clicktouch events on the iframe seems to be blocked due to pointerevents noneso i thoughtok while the user scrolls i need pointereventsnone if he is not scrolling and instead clicking i must set pointereventsauto in order to let the clicktouch events paso i did thiscsstheiframepointereventsnonejavascripttheiframebindtouchstart function enable click before click is triggered thiscsspointerevents autotheiframebindtouchmove function thisable clicktouch events while scrolling thiscsspointerevents noneeven adding this does not worktheiframebindtouchend function reenable clicktouch events after releasing thiscsspointerevents autono matter what i do either scrolling does not work or clicking the link inside the iframe does not workdoes not work any ideas,['ios'] +433592,failed to start up socket within 450 i am using ff version 19it was all working fine till yesterday and suddenly today morning i start getting this error and i have the same exact code that was running before no change nothingerror messagetest mtestcases12 failed failed to start up socket within 450 openqaseleniumwebdriverexception failed to start up socket within 450 at openqaseleniumfirefoxinternalextensionconnectionconnecttobrowserint64 timetowaitinmilliseconds at openqaseleniumfirefoxinternalextensionconnectionstart at openqaseleniumfirefoxfirefoxdriverstartclient at openqaseleniumremoteremotewebdriverctoricommandexecutor commandexecutor icapabilities desiredcapabilities at openqaseleniumfirefoxfirefoxdriverctorfirefoxbinary binary firefoxprofile profile timespan commandtimeout at openqaseleniumfirefoxfirefoxdriverctorfirefoxbinary binary firefoxprofile profile at openqaseleniumfirefoxfirefoxdriverctorfirefoxprofile profile0 passed 1 failed 0 skipped took 14580 seconds ad hochere is my source codepublic static iwebdriver getdriver switch commonbrowserselected case ff firefoxprofile profile new firefoxprofile profilesetpreferencenetworkhttpphishyuserpasslength 255 profilesetpreferencenetworkautomaticntlmauthtrusteduris url drv new firefoxdriverprofile break case ie var options new internetexploreroptions optionsintroduceinstabilitybyignoringprotectedmodesettings true desiredcapabilities capabilities new desiredcapabilities capabilitiessetcapabilitycapabilitytypeacceptsslcertificates true drv new internetexplorerdriveroptions break case chrome driver new chromedriver break return drv,['c#'] +433623,error using jackson and json i am trying to parse some json full example of the json can be seen in this gist i show the general structure of the json below title principles of compiler design authors aho ullman publisher adthison wesley year 1977 title compilers principles techniques and tools authors aho sethi ullman publisher adthison wesley year 1985 i am trying to parse the json with jackson libraries but i get the following error while testingexception in thread main comfasterxmljacksondatabindjsonmappingexception can not deserialize instance of javalangstring out of start array token at source libraryjson line 2 column 49 through reference chain comacmedatatypesuserauthors at comfasterxmljacksondatabindjsonmappingexceptionfromjsonmappingexceptionjava163 at comfasterxmljacksondatabinddeserializationcontextmappingexceptiondeserializationcontextjava588 at comfasterxmljacksondatabinddeserstdjdkdeserializersstringdeserializerdeserializejdkdeserializersjava90 at comfasterxmljacksondatabinddeserstdjdkdeserializersstringdeserializerdeserializejdkdeserializersjava59 at comfasterxmljacksondatabinddesersettablebeanpropertydeserializesettablebeanpropertyjava336 at comfasterxmljacksondatabinddeserimplmethodpropertydeserializeandsetmethodpropertyjava89 at comfasterxmljacksondatabinddeserbeandeserializerdeserializefromobjectbeandeserializerjava290 at comfasterxmljacksondatabinddeserbeandeserializerdeserializebeandeserializerjava112 at comfasterxmljacksondatabindobjectmapper readmapandcloseobjectmapperjava2563 at comfasterxmljacksondatabindobjectmapperreadvalueobjectmapperjava1759 at comacmedatatypesusertestmainusertestjava20here is my codeuser test classpublic class usertest public static void mainstring args throws jsonparseexception jsonmappingexception ioexception file jsonfile new filelibraryjson user user null objectmapper mapper new objectmapper user mapperreadvaluejsonfile userclass systemoutprintlnusergettitle user mapperreadvaluejsonfile userclass systemoutprintlnusergetauthors user mapperreadvaluejsonfile userclass systemoutprintlnusergetpublisher user mapperreadvaluejsonfile userclass systemoutprintlnusergetyear user classpublic class user private string authors private string publisher private string title private number year public string getauthors return thisauthors public void setauthorsstring authors thisauthors authors public string getpublisher return thispublisher public void setpublisherstring publisher thispublisher publisher public string gettitle return thistitle public void settitlestring title thistitle title public number getyear return thisyear public void setyearnumber year thisyear year does anyone know what the problem might be thanks,['java'] +433631,what do the different hotspot jvm thread types do i see there are six thread types implemented into the hotspot jvm vmthread cgcthread pgcthread javathread compilerthread and watcherthread however i do not know which thread type is doing what exactly here is what i understood so farvmthread run vm tasks like the garbage collectorcgcthread concurrent garbage collectorpgcthread parallel garbage collector differences with cgcjavathread programs threads i guesscompilerthread a thread for the compiler watcherthread additional question what about other jvms,['java'] +433656,how does python find a module file if the import statement only contains the filename everywhere i see python code importing modules using import sys or import mymodulehow does the interpreter find the correct file if no directory or path is provided,['python'] +433670,rails select tag selected value my tag select tagoption options for selectall 1 co 2 bought 3 view 4 top api 5 selected option how do i set the selected value to which option is selected for example if i select bought 3 and submit all 1 option is selected how can i thisplay the selected value after the form is submitted,['ruby-on-rails'] +433691,how to output oracle sql result into a file in windows i triedselect from users save dtestsql createbut sql plus gives me no proper endedhow to specify path in oracle sql in windows,['sql'] +433746,how to filter uicollectionview and keep keyboard up i have added a uisearchbar to a uicollectionview and in the delegate searchbartextdidchange filter my model and call collectionview reloaddata reloaddata as well as reloadsection etc wants to take away firstresponder from the searchbars textfield thus thismissing the keyboardi am trying to build a live updating filter and so it is annoying to have the keyboard go away after each character typed any ideas,['ios'] +433857,wordnet java api i am having to use a java api for wordnet it will be for a big implementation i am searching but coming across manyjwordnet mit java wordnet interface rita wordnetcan i get some advise about which one is better,['java'] +433885,how to get content of rendering programmatically i am attempting to write a method that will output the content ie html for any renderings that happen to exist within a specific placeholder the goal is to pass in a sitecoredataitemsitem and the placeholder key that i am interested in and the method should return the rendered contentthe issue with this seems to be that there is no page context established and therefore calling rendercontrol is throwing a null reference error in the getcachekey method of the sublayoutis anyone aware of a way to render a sublayout or xslt rendering programmaticallyheres what i have got so farprivate string getplaceholdercontentitem item string placeholder stringwriter sw new stringwriter using htmltextwriter writer new htmltextwritersw foreach renderingreference renderingreference in itemvisualizationgetrenderingssitecorecontextdevice false if renderingreferenceplaceholder placeholder this ensures were only dealing with sublayouts if renderingreferencerenderingiteminneritemisoftypesitecoretemplateidssublayout var control renderingreferencegetcontrol controlrendercontrolwriter throws null reference error in getcachekey return swtostring,['c#'] +433922,web audio start and stop oscillator then start it again i am trying to start and stop a sound and that works but i cannot start the sound up againdo i really have to make another oscillator again this just seems extremely unintuitive there must be a better waythis is all i have that worksoscillator1noteon0oscillator1noteoff0calling noteon again doesnt do anything why is beyond mei also tried setting the volume or in the context of the web audio people gain equal to zero but for some reason a gain of zero makes sound what value of gain would not make any soundman i cannot believe how difficult this is,['javascript'] +433963,twitter bootstrap tab selection not changing content although there are plenty of twitter bootstrap questions open that regard similar issues to that which i am having i have not been able to find any solutions to my particular issue i am using the twitter bootstraps tab feature in order to thisplay content and while the script succeeds in changing the changing the active tab the content remains the sameheres the codedoctype htmlhtml langen head titlehello tabstitle link relstylesheet hrefpubliccssbootstrapmincss script typetextjavascript srcscript script typetextjavascript srcpublicjsbootstrapminjsscript head body h3version informationh3 div classtabbable tabsleft ul classnav navtabs datatabstabs li classactive a hrefprojectsrcgraphgraphpm 0 datatoggletab9424a li li a hrefprojectsrcgraphgraphpm 1 datatoggletab9058a li li a hrefprojectsrcgraphgraphpm 2 datatoggletab8928a li li a hrefprojectsrcgraphgraphpm 3 datatoggletab8926a li li a hrefprojectsrcgraphgraphpm 4 datatoggletab8924a li li a hrefprojectsrcgraphgraphpm 5 datatoggletab8890a li li a hrefprojectsrcgraphgraphpm 6 datatoggletab89a li li a hrefprojectsrcgraphgraphpm 7 datatoggletab87a li ul div classtabcontent div classtabpane active idprojectsrcgraphgraphpm 0 p author joebr version v9424 131 pm february 28 2013br action modifiedbr message finalized a bit of the code should be better nowbr p div div classtabpane idprojectsrcgraphgraphpm 1 p author joebr version v9058 913 pm february 26 2013br action modifiedbr message hello worldbr p div div classtabpane idprojectsrcgraphgraphpm 2 p author joebr version v8928 208 am february 25 2013br action modifiedbr message hello worldbr p div div classtabpane idprojectsrcgraphgraphpm 3 p author joebr version v8926 114 am february 25 2013br action modifiedbr message hello worldbr p div div classtabpane idprojectsrcgraphgraphpm 4 p author joebr version v8924 1026 pm february 24 2013br action modifiedbr message hello worldbr p div div classtabpane idprojectsrcgraphgraphpm 5 p author joebr version v8890 959 pm february 23 2013br action modifiedbr message hello worldbr p div div classtabpane idprojectsrcgraphgraphpm 6 p author joebr version v89 953 pm february 23 2013br action addedbr message hello worldbr p div div classtabpane idprojectsrcgraphgraphpm 7 p author joebr version v87 940 pm february 23 2013br action addedbr message hello worldbr p div div div script typetextjavascript jquerydocumentreadyfunction navtabstab script bodyhtmlall the dependence files are loaded just fine when i run this for reference the version of bootstrap being used is 231 i have been headdesking about this problem for quite some time now so any help would be greatly appreciatededit heres a jsfiddle link containing the error code,"['javascript', 'html']" +433980,understanding cs fork through a simple example include stdiohint num 0int mainint argc charargv int pid pid fork printfd num ifpid 0 child num 1 else ifpid 0 parent num 2 printfd numi am having trouble understanding why the possible outputs would be 0102 or 0012 or 0201 or 0021 here is what i think it should be producing it hits the first printf statement and no matter what child or parent gets executed first num has not been modified so 0 first then next is either 1 or 2 then the next process executes so starts with 0 again copied from the parent and then either a 1 or 2 again so the possible outputs should be0101 or0102 or0201 or0202,['c'] +434164,upload file to ftp using c i try upload a file to an ftpserver with c the file is uploaded but with zero bytesprivate void button2 clickobject sender eventargs e var dirpath cdocuments and settingssandergdbureaubladtest ftp ftpclient new ftp username password string files directorygetfilesdirpath var uploadpath httpdocsalbum foreach string file in files ftpclientcreatedirectorytest ftpclientuploaduploadpath pathgetfilenamefile file if stringisnulloremptytxtnaamtext messageboxshowgelieve uw naam in te geven,"['c#', '.net']" +434168,why is my pbkdf2 implementation so slow vs sqlcipher i have written a simple android app on my xoom tablet which simply stores some string notes in a sqlcipher database the user is prompted to type in a passphrase which will be used for the database by the sqlcipher lib this works fine so far and very smoothnow i have also implemented a small pbkdf2 algorithm for authentication purposesin fact i want to encrypt some other files in the future wich cannot be stored in a databasebut as for now i only came to check if my pbkdf2 algorithm is correct i only used the javaxcrypto and javasecurity libscode snippet as followsint derivedkeylength 128int iterations 500keyspec spec new pbekeyspecpassphrasetochararray salt iterations derivedkeylengthsecretkeyfactory f secretkeyfactorygetinstancepbkdf2withhmacsha1byte derivedkey fgeneratesecretspecgetencoded the salt is a 16 byte random number generated with securerandomso i hardcoded the key and the salt and compare the the derivedkey for authentication only a test casemy problem now is that on my xoom it lasts about 5 seconds until the deriving function is done although the iteration is set to 500 onlyafaik sqlcipher is using an iteration number of 40 by default and it responds instant if the key is wrong or correctif i set the iteration to 40 it takes at least 15secondsthe question is did i implemented that inefficient or is it because sqlcipher is just that good in performance native ndk functions etc thank you in advanceps sorry my english isnt that great yetedit sorry i was not clear enough i know pbkdf2 is supposed to be slow in specific the iteration amount to slow down brute force attacks thats exactly the reason i am asking i wanted to set the iteration number to lets say 50 which is not acceptable with over 15secondsi am just wondering because like i said sqlcipher also uses pbkdf2 iteration 4k while i am using 500 for deriving a key from a given password i am not talking about the encryption with aes in the end its only about the difference in deriving the keyof course it seems legit that sqlcipher is way faster than an self made keyderiving function but i did not think that it would be this much difference since sclciphers pbkdf2 really works instantgreetings,"['java', 'android']" +434219,why xgrabkey generates extra focusout and focusin events does anyone know an xlib function to trap a keypress event without losing the original focus how to get rid of itor to use xgrabkey without generating grabstyle focusoutor how to get rid of notifygrab and notifyungrab focus events at system levelthe xgrabkey will lose focus on key pressed and restore focus on key releasedand i want to trap the keypress without leak it to the original window just as xgrabkey can do itreferencesxgrabkey will steal focusthe program receives control to do something in response to the key combination meanwhile the program has been temporarily focusedduring xgrabkeyboard thiscover which window had been focusedthe xgrabkeyboard function actively grabs control of the keyboard and generates focusin and focusout eventsi cannot see a way to provide metacitys current desktop changin behavior changing and showing the popup dialog at the same time without causing a grabtype focus out on the windowfullscreen mode should not exit on focusout events with notifygrab bugcgiid578265grabbing keyboard doesnt allow changing focus grabbing keyboard doesnt allow changing focusfocus events generated by grabs both the active grab of xgrabkeyboard and the passive grab of xgrabkey events generated by grabsthe xgrabkey source code maybe we could modify this to get rid of focusout eventsthere is dofocuseventskeybd oldwin grabwindow notifygrab in activatekeyboardgrab i am writting a onekeystroke to keyscombinationand mouse movement mapping softwarei have realized it in windows with registerhotkey and unregisterhotkey and i want to migrate it into linux with xgrabkey and xungrabkey i have created 10 bounty to resolve this problem we need more backers to place bounties,['python'] +434250,how to change alert dialog header divider color android i wanted to style or change divider color of header title in alert dialog i search about this question and i think lot of people searching for thisbut i am still not able to find out right solution i want to change this following,['android'] +434309,auto refresh without reload entire page i am trying to update the content of mydiv without refreshing the entire index pagemydata is given by mycontroller i need to recalculate it every n seconds and pass it to mydivwith link to it worksindexhtmlerb link torefresh mycontrollerindex remote truediv idmydiv mydata divindexjserbmydivhtml escape javascriptmydata now i need to refresh the content of mydiv automatically every n seconds so without click on the link i have tried solutions fromfirst linksecond linkbut no luckin my applicationjs i have writed thisfunction executequery ajax url index success functiondata mydivhtmldata settimeoutexecutequery 500documentreadyfunction settimeoutexecutequery 500for who is facing my same problem i solved it by replacingmydivhtmldatawithmydivloadmycontrollerindex mydiv,['ruby-on-rails'] +434310,continue processing php after sending http response my script is called by server from server i will receive id of message and text of message in my script i will handle incomming text and generate response with params answer to id and response messagethe problem is that i am sending response to incomming id of message but server which send me message to handle will set his message as delivered to me it means i can send him response to that id after receiving http response 200 one of solution is to save message to database and make some cron which will be running each minute but i need to generate response message immidiatelly is there some solution how to send to server http response 200 and than continue executing php scriptthank you a lot,['php'] +434311,addappend use case i am working on a template builder applicationa user can build html templates using different components like text boxpicture boxslideshow etcissue the issue we am facing is with the slideshow componentwe are using a nivoslider plugin for building itthe slider must have settings like the user can change transition timeselect transition etcthe user can add more than slideshowsnow the issue is when we add multiple slideshowseach one may have its own parameters for itso we cannot have a common functionalsothe user can come back to edit the templateso we need to have independent script for each slideshowreasearch we have the basic structure workingbut stuck at one placewe need to append a script tag to each slideshow added to the page by the user return div idslider classnivoslider div class img id classimage mover stylepositionabsoluteleft0pxtop0px srchttplocalhostgobiggi vs 2 2imagesslideshowslide01jpg datathumbimagesslideshowthumbslide01jpg alt div div class img id classimage mover stylepositionabsoluteleft0pxtop0px srchttplocalhostgobiggi vs 2 2imagesslideshowslide02jpg datathumbimagesslideshowthumbslide02jpg alt div div class img id classimage mover stylepositionabsoluteleft0pxtop0px srchttplocalhostgobiggi vs 2 2imagesslideshowslide03jpg datathumbimagesslideshowthumbslide03jpg alt div div class img id classimage mover stylepositionabsoluteleft0pxtop0px srchttplocalhostgobiggi vs 2 2imagesslideshowslide04jpg datathumbimagesslideshowthumbslide04jpg alt div divscriptslidernivoslidereffect slicedownanimspeed 500pausetime 30startslide 0controlnavthumbs truecontrolnavthumbsfromreltrue pauseonhover truemanualadvance falsescriptthe script tag at the end of the code is what we are trying to append to the html and save it to the databasewe tried having a blank div idtempdiv and appending the script tag in itbut i believe jquery executes the script and does not save it so we get a blank divhow can we store the script tag in the html structure and save it to the database,"['javascript', 'jquery', 'html']" +434312,is the maximum send speed of a tcp client limited exactly by the client computers upload speed backgroundi am attempting to stream a live feed of a remote computers desktop to my application to do this i am using connectionorientated tcp sockets capturing a frame of the clients computer and sending it to the server my researchi am sending a frame screenshot every 100 milliseconds that is 10 fps each frame is around 145kb that means i need to send 1450kb a second which equates to 14 megabytes 11 mega bits a secondmy internet has a maximum download speed of 032 mega bits per second because i need to send 11 mega bits of data a second this means i my internet is 106 megabits slower than what i need so by my calculations in order to stream the desktop efficiently i need each frame to be approximately 45kb 4608b 20b tcp header which is realistically impossible given the current system even when sending only updated parts of the desktop and compressing bitmaps questioni am not sure that the system is limited exactly by the upload speed i think this because 45kb is a ridiculously small size i can stream my desktop perfectly smoothly using similar software software such as teamviewer joinme and skype and even though these software packages use far more intelligent protocols than me good question here i highly doubt that they are sending just 45kb each frame desktop update so my question is ultimately are my calculations at all accurate and why my aim here is to decide what is an appropriate size for each frame so i can then work to reach that size and calculate the quality interval for different speed connections i am interested in any comments answers that are helpful to my situation of course but the answer i accept will be the one that answers my actual question,['c#'] +434371,access global variable from angularjs i want to initialize a angular model with a json object wich is embedded in a html page examplehtml body script typetextjavascript charsetutf8 var tags name some json script ul li ngrepeattag in tagstagnameli ul bodyhtmlthe tags field cannot be resolved because it is looked up in the scope i tried to access the tags field in my controller like thisfunction taglistscope rootscope scopetags rootscopetagsbut it does not workit works only if i include the taglist directly into the html page and render the json directly into this functionhow can i access the tags field in a separate js file in a angular controller,['javascript'] +434382,is it correct to call javalangstring immutable this java tutorialsays that an immutable object cannot change its state after creation javalangstring has a field cache the hash code for the string private int hash default to 0which is initialized on the first call of the hashcode method so it changes after creation string s new stringnew char field hash sgetclassgetdeclaredfieldhash hashsetaccessibletrue systemoutprintlnhashgets shashcode systemoutprintlnhashgetsoutput032is it correct to call string immutable,['java'] +434429,clojure repl not launching at windows command prompt i have placed the clojure140jar path cclojure140clojure140jar in my classpath environment variable now when i try to launch the repl from the command line with the following codejava cp clojure140jar clojuremaini get an errorerror could not find or load main class clojuremainit used to work before i set up emacs any ideas,['java'] +434433,how to create a dialogfragment without title i am creating a dialogfragment to show some help messages regarding my app everything works fine besides one thing there is a black stripe at the top of the window that shows the dialogfragment that i presume is reserved for the title something i do not want to usethis is specially painful since my custom dialogfragment uses a white background so the change is way too notorious to be left asidelet me show you this in a more graphical mannernow the xml code for my dialogfragment is as followsscrollview xmlnsandroid androidlayout widthfill parent androidlayout heightfill parent linearlayout androidididholding androidorientationvertical androidlayout widthfill parent androidlayout heightfill parent androidbackgrounddrawabledialog fragment bg usamos un linearlayout para que la imagen y el texto esten bien alineados linearlayout androidididconfirmationtoast androidorientationhorizontal androidlayout widthwrap content androidlayout heightwrap content textview androidididconfirmationtoasttext androidlayout widthwrap content androidlayout heightfill parent androidtextstringhelp dialog fragment androidtextcolorae0 androidgravitycenter vertical linearlayout linearlayout androidididconfirmationbuttonll androidorientationhorizontal androidlayout widthfill parent androidlayout heightfill parent androidgravitycenter horizontal button androidididconfirmationdialogbutton androidlayout widthwrap content androidlayout heightwrap content androidgravitycenter androidlayout marginbottom60dp androidbackgrounddrawableok button button linearlayout linearlayoutscrollviewand the code of the class that implements the dialogfragmentpublic class helpdialog extends dialogfragment public helpdialog empty constructor required for dialogfragment override public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate inflate the xml view for the help dialog fragment view view inflaterinflaterlayouthelp dialog fragment container textview text textviewviewfindviewbyidridconfirmationtoasttext textsettexthtmlfromhtmlgetstringrstringhelp dialog fragment get the ok button and add a listener button viewfindviewbyidridconfirmationdialogbuttonsetonclicklistenernew onclicklistener public void onclickview v when button is clicked call up to owning activity helpdialogthisthismiss return view and the creation process in the main activity shows the helpdialog fragment private void showhelpdialog androidsupportv4appfragmentmanager fm getsupportfragmentmanager helpdialog helpdialog new helpdialog helpdialogshowfm fragment helpi really do not know if this answer related with a dialog fits here also android how to create a dialog without a titlehow can i get rid of this title area,['android'] +434444,is thispatchevent a sync or an async function i am trying to write an event handler for a custom event in winjs i am not too sure how this works in ie i am creating a custom event and thispatching it var eventobject documentcreateeventcustomeventeventobjectinitcustomeventdropbomb true true nullthis elementthispatcheventeventobjectmy handler is this elementaddeventlistenerlogtelemetry function consolelogboomcan i be certain that the handler will be called in sync and not at a later time if so then what is the proof,['javascript'] +434471,ipad is not writing text in the i am having trouble with the input field when running my application on ipad on the desktop you click on the text box type the text in and click on a button to validate the input on ipad however it opens the keyboard panel when you click on it but the text does not show in the text box when you typeto make things even weirder i have a textarea in another section of the application and it works perfectly the difference is one is sitting on top of the application and the other is in an imported htmlthe structure of the application is like this on the top i have the main html5 page which imports a html page that contains 3 divs each div in turn imports other html pages and those pages have a different content each including the problematic input fieldsomething like thismainhtml containerhtml imported via iframe div1 imports page n1 via loadurl div2 imports page and via loadurl div3 imports page n1 via loadurlpagenhtml contains the input fieldthe code for the textarea sitting on the main html is like thisform idformnotes textarea idmaintextbox typetext onkeyuprefreshnote onchangerefreshnotetextareaformand the code for the input field inside the imported html page is like thisinput webkituserselect autoform idforminput input idtext1 typetext ontouchstartopenkeyboardthis onkeydownwritetextthis onkeyupwritetextthis onchangewritetextthisinputformone thing i have learned about using events on imported htmls though was you need to use ontouchstart and others to call the click functions but in this case i can get the ipad to open the keyboard so i do not know why it is not recognizing the click on the keyboard keys or why it is not sending the value into the text boxedit i found out the reason why i am not getting any text written is because the ipad thinks the input field does not exist it shows up blank in the alert instead of object object or object htmlinputelement i have no idea why thoughedit 2 i tried to use getelementsbytagname and getelementsbyclassname instead of getelementbyid with that it seems to recognize the input but i still cannot reach the value,['javascript'] +434475,is a naked char32 t signed or unsigned similarly is a naked char16 t signed or unsigned is it implementation defined,['c++'] +434488,jquery not working from google cnd i just started creating a html file and wanted to use jquery when i use the jquery from my local machine like this it works finescript srcjqueryminjsscriptbut when i try to use this it does not workscript srcajaxgoogleapiscomajaxlibsjquery191jqueryminjsscripti am not able to use any jquery functions when i load the script like thiswhat am i doing wrong hereedit btw my html file is on the local machine in drive c,['jquery'] +434491,signalr not always ready after startdone i have got a small project working with signalr however i am getting some very inconsistent behaviorscript typetextjavascript function var chat connectionbrewbattlehub connectionhubstartdonefunction broadcastclickfunction call the chat method on the server chatserverrollusernameval drinknameval chatserversendmessagesignalr loaded scriptwhen i load the page sometimes i am seeing the message signalr loaded other times i am notthere is is some other functionality on the page also and sometimes this does not work either if i click buttons and make things happen enough it will eventually all come through in one go from this point it is all golden and works perfectlydoes startdone not ensure it is all readyaddendum i am not referencing jquery mobile google mentioned there is a bug when doing so,['asp.net'] +434500,other open source alternatives to codahales metrics i came across the metrics project from codahale and i believe that it is used at yammer i like this solution but want to know if there are other open source alternatives with similar capabilities,['java'] +434535,whats compiler thinking about the switchstatement inspired from a 5 question againis empty case of switch in c combined with the next nonempty onei read this comment of quartermeister and been astonishedso why this compilesswitch1 case 2but this does not int iswitchi1 case 2 control cannot fall through from one case label case 2 to anotherneither thisswitch2 case 2 control cannot fall through from one case label case 2 to anotherupdate the 5 question became 3,['c#'] +434541,classifying a series to a new column in pandas i want to be able to take my current set of data which is filled with ints and classify them according to certain criteria the table looks something like thisin df pddataframea023200b 1020c 001010out a b c0 0 1 01 2 0 02 3 2 13 2 0 04 0 0 15 0 0 0i would like to classify these in a separate column by string being more familiar with r i tried to create a new column with the rules in that columns definition following that i attempted with ix and lambdas which both resulted in a type errors between ints series i am under the impression that this is a fairly simple question although the following is completely wrong here is the logic from attempt 1dfdif dfa 0 dfb 0 dfc0 return c1elif dfa 0 dfb 0 dfc 0 return c2else return c3for a final result of a b c d0 0 1 0 c21 2 0 0 c12 3 2 1 c33 2 0 0 c14 0 0 1 c25 0 0 0 c3if someone could help me figure this out it would be much appreciated,['python'] +434550,are java class files needed after an application is running i had a hard time writing the title to this question but here is my situation and what i am askingi have a java project that i run ant test on to run the teststhe tests take about 10 minutes to runcan i switch to a different git branch in the middle of running these tests without consequencesi want the tests to complete against the original code and allow me to simply work on a different branch while that happensi guess the root of my question is are class files needed after the application is loaded and running is the classes just stored in memory and i do not need the files on the file system anymore or does it still accessread things on the filesystemany insight or better understanding of what java needs for a running application is appreciated,['java'] +434589,file io inside casperjs is it possible do readwrite files inside a casperjs script var fs requirefsvar data fsreadfilesynctestdatadata utf8consolelogdatacalling casperjs fileiojsreturnsundefined is not a functioneven after running npm install fsbonus point if not explain why,['javascript'] +434679,how to reference microsoftofficeinteropexcel dll i had developed a system that deals with excel sheets in 2006 using ms vs 2005 now i can not use the same reference with ms vs 2012var app new microsoftofficeinteropexcelapplicationworkbooks wbs appworkbooks,['c#'] +434704,lifetime of a stdinitializer list return value gccs implementation destroys a stdinitializer list array returned from a function at the end of the return fullexpression is this correctboth test cases in this program show the destructors executing before the value can be usedinclude initializer listinclude iostreamstruct noisydt noisydt stdcout destroyedn void receive stdinitializer list noisydt il stdcout receivednstdinitializer list noisydt send return int main receive send stdinitializer list noisydt il send receive il i think the program should work but the underlying standardese is a bit convolutedthe return statement initializes a return value object as if it were declared stdinitializer list noisydt ret this initializes one temporary initializer list and its underlying array storage from the given series of initializers then initializes another initializer list from the first one what is the arrays lifetime the lifetime of the array is the same as that of the initializer list object but there are two of those which one is ambiguous the example in 8546 if it works as advertised should resolve the ambiguity that the array has the lifetime of the copiedto object then the return values array should also survive into the calling function and it should be possible to preserve it by binding it to a named referenceon lws gcc erroneously kills the array before returning but it preserves a named initializer list per the example clang also processes the example correctly but objects in the list are never destroyed this would cause a memory leak icc does not support initializer list at allis my analysis correctc11 a6632a return statement with a bracedinitlist initializes the object or reference to be returned from the function by copylistinitialization 854 from the specified initializer list8541a listinitialization in a copyinitialization context is called copylistinitialization8514the initialization that occurs in the form t x a a is called copyinitializationback to 8543listinitialization of an object or reference of type t is defined as follows aa otherwise if t is a specialization of stdinitializer liste an initializer list object is constructed as described below and used to initialize the object according to the rules for initialization of an object from a class of the same type 858545an object of type stdinitializer liste is constructed from an initializer list as if the implementation allocated an array of n elements of type e where n is the number of elements in the initializer list each element of that array is copyinitialized with the corresponding element of the initializer list and the stdinitializer liste object is constructed to refer to that array if a narrowing conversion is required to initialize any of the elements the program is illformed8546the lifetime of the array is the same as that of the initializer list object exampletypedef stdcomplexdouble cmplx stdvectorcmplx v1 1 2 3 void f stdvectorcmplx v2 1 2 3 stdinitializer listint i3 1 2 3 for v1 and v2 the initializer list object and array createdfor 1 2 3 have fullexpression lifetime for i3 the initializer list object and array have automatic lifetime a end examplea little clarification about returning a bracedinitlistwhen you return a bare list enclosed in braces a return statement with a bracedinitlist initializes the object or reference to be returned from the function by copylistinitialization 854 from the specified initializer listthis does not imply that the object returned to the calling scope is copied from something for example this is validstruct nocopy nocopy int nocopy nocopy const delete nocopy nocopy deletenocopy f return 3 this is notnocopy f return nocopy 3 copylistinitialization simply means the equivalent of the syntax nocopy x 3 is used to initialize the object representing the return value this does not invoke a copy and it happens to be identical to the 8546 example of an arrays lifetime being extendedand clang and gcc do agree on this pointother notesa review of n2640 does not turn up any mention of this corner case there has been extensive thiscussion about the individual features combined here but i do not see anything about their interactionimplementing this gets hairy as it comes down to returning an optional variablelength array by value because the stdinitializer list does not own its contents the function has to also return something else which does when passing to a function this is simply a local fixedsize array but in the other direction the vla needs to be returned on the stack along with the stdinitializer lists pointers then the caller needs to be told whether to thispose of the sequence whether they are on the stack or notthe issue is very easy to stumble upon by returning a bracedinitlist from a lambda function as a natural way to return a few temporary objects without caring how they are containedauto il stdinitializer list noisydt return noisydt noisydt indeed this is similar to how i arrived here but it would be an error to leave out the trailingreturntype because lambda return type deduction only occurs when an expression is returned and a bracedinitlist is not an expression,['c++'] +434714,uiautomation through command line on a real device i know starting from xcode 42 it is possible to run uiautomation scripts through command line i have tried this and is working perfectly fine for me in simulator i would like to know how to get this run in an actual devicei searched and got the command for running on device asinstruments w device id t developerplatformsiphoneosplatformdeveloperlibraryinstrumentspluginsautomationinstrumentbundlecontentsresourcesautomationtracetemplateapplication e uiascript script e uiaresultspath results pathwhat exactly should i give in the application is it the path to ipa or something elseadvance thanks,['ios'] +434727,hibernate onetomanymanytoone mapping giving null i have 2 classes called purchaselistjava and purchaselistitemsjavai have to map purchaselist in purchaselistitemspurchaselistjavaonetomanycascade cascadetypealljoincolumnnamepl idreferencedcolumnnameidprivate listpurchaselistitems purchaselistitemspurchaselistitemsjavamanytoonejoincolumnnamepl idprivate purchaselist purchaselistideverything is fine but i am getting null in pl id please tell where i am wrong,['java'] +434741,why should py increfpy none be required before returning py none in c why should py increfpy none be required before returning py none in c as followspy increfpy nonereturn py noneif py increfpy none is omitted what will happen,"['python', 'c']" +434767,c trying to avoid duplicates var multiples from i in enumerablerangemin max min from r in roots where i r 0 select ifor example if roots 210 it would select 20 twice is it possible to avoid duplicates here,['c#'] +434776,use of nested enums appropriate in this case i have a requirement to support a number of charttypes each of these chart types can support a number of chartsubtypes for example areachart type can have percentarea stackedarea etc i am thinking of using an enum both for charttypes and subtypes and then maintain a map somewhere which will be something like mapcharttypelistchartsubtypes maptypescan i somehow use a nested enum pattern here if yes then how,['java'] +434784,showhide script using javascript i have a showhide script that i am using for a menu when i click a main link it brings up a list below it i was wondering if there is a way to alter it a bit so that when i click the link it opens but when i click the next one it closes the other one instead of leaving them all open unless you click it again to closehere is my scriptscript typetextjavascript function toggle visibilityid var e documentgetelementbyidid ifestylethisplay block estylethisplay none else estylethisplay block scripta href onclicktoggle visibilitylist1 plist onep a div idlist1 stylethisplaynone ul liitem oneli liitem twoli liitem threeli ul div,"['javascript', 'html']" +434798,optional uritemplate parameter using webget i have tried these optional parameters in wcf service uri templateposted by kamal rawat in blogs net 45 on sep 04 2012this section shows how we can pass optional parameters in wcf servuce uriinshareand optional query string parameters in uritemplate in wcf but nothing works for me here is my code webgeturitemplate retrieveuserinformationhashapp public string retrieveuserinformationstring hash string app it works if the parameters are filled up but does not work if app has no value i want to make app optional how to achieve thishere is the error when app has no value endpoint not found please see the service help page for constructing valid requests to the service,['c#'] +434802,make j4 or j8 i have 4 processors and am compiling processor hungry application i read that using make with the j4 switch was recommended for opencv should i rather use j8 and what is the advantage of making for multiple processors,['c'] +434806,web response status code i have this simple function to get html pages and return it as a string though sometimes i get a 404 how can i only return the html string only if the request was successful and return something like badrequest when it is a 404 or any other error status codepublic static string getpagehtmlstring link using webclient client new webclient return clientdownloadstringlink,['c#'] +434842,allow only 1 value per key press i have a richtextbox on a windows form the user can enter text into but it needs to be setup so that if the user holds down a key they only get 1 charactereg if they hold down a then it will only input a and not a etcfrom the moment the key is down till the time the key is up i only want that to translate to 1 valueany ideas how i can achieve this i guess i need to use keydown and keyup but i am not sure past that,"['c#', '.net']" +434857,how to get all terms for a lucene field in lucene 4 i am trying to update my code from lucene 34 to 41 i figured out the changes except one i have code which needs to iterate over all term values for one field in lucene 31 there was an indexreaderterms method providing a termenum which i could iterate over this seems to have changed for lucene 41 and even after several hours of search in the documentation i am not able to figure out how can someone please point me in the right directionthanks,['java'] +434873,is this overloading methods with same name in different classes and different signature if i have the following code in javaclass a public int addint a int b return ab class b extends a public float addfloat a float b return abin this particular case the subclass is not exactly overriding the base clas add function as they have different signatures and the concept of overloading occurs only if they are in the same scope so is the function addfloat float in the subclass b treated as an entirely new function and the concept of overloading and overriding is not applicable to it and does it use static binding or dynamic binding,['java'] +434875,i have 2 versions of python installed but cmake is using older version how do i force cmake to use the newer version i have 2 versions of python installed but cmake is using older version how do i force cmake to use the newer version,['python'] +434898,facebook integration in android hi am trying to integrate facebook in my application so for that i was guided from integration guidebut i got error in step 3when am importingconsole showing some errors like20130308 101607 messagestask unable to resolve target android820130308 101700 messagestask unable to resolve target android820130308 155754 profilepicturesample unable to resolve target android820130308 155754 booleanogsample unable to resolve target android820130308 155754 hackbook unable to resolve target android820130308 155755 graphapisample unable to resolve target android820130308 155755 scrumptious unable to resolve target android820130308 155755 placepickersample unable to resolve target android820130308 155755 sessionloginsample unable to resolve target android820130308 155755 friendpickersample unable to resolve target android820130308 155755 hellofacebooksample unable to resolve target android820130308 155755 facebooksdk unable to resolve target android820130308 155756 switchusersample unable to resolve target android820130308 155805 profilepicturesample warning unable to write jarlist cache file cusersgtmfacebookandroidsdk30samplesprofilepicturesamplebinjarlistcache20130308 155807 facebooksdk unable to resolve target android820130308 155807 profilepicturesample unable to resolve target android820130308 155807 booleanogsample unable to resolve target android820130308 155807 hackbook unable to resolve target android820130308 155807 graphapisample unable to resolve target android820130308 155807 scrumptious unable to resolve target android820130308 155807 placepickersample unable to resolve target android820130308 155807 sessionloginsample unable to resolve target android820130308 155807 friendpickersample unable to resolve target android820130308 155807 hellofacebooksample unable to resolve target android820130308 155807 switchusersample unable to resolve target android820130308 155807 facebooksdk warning unable to write jarlist cache file cusersgtmfacebookandroidsdk30facebookbinjarlistcache20130308 155807 profilepicturesample warning unable to write jarlist cache file cusersgtmfacebookandroidsdk30samplesprofilepicturesamplebinjarlistcache20130308 155807 booleanogsample warning unable to write jarlist cache file cusersgtmfacebookandroidsdk30samplesbooleanogsamplebinjarlistcache20130308 155807 hackbook warning unable to write jarlist cache file cusersgtmfacebookandroidsdk30sampleshackbookbinjarlistcache20130308 155807 graphapisample warning unable to write jarlist cache file cusersgtmfacebookandroidsdk30samplesgraphapisamplebinjarlistcache20130308 155807 scrumptious warning unable to write jarlist cache file cusersgtmfacebookandroidsdk30samplesscrumptiousbinjarlistcache20130308 155807 placepickersample warning unable to write jarlist cache file cusersgtmfacebookandroidsdk30samplesplacepickersamplebinjarlistcache20130308 155807 sessionloginsample warning unable to write jarlist cache file cusersgtmfacebookandroidsdk30samplessessionloginsamplebinjarlistcache20130308 155807 friendpickersample warning unable to write jarlist cache file cusersgtmfacebookandroidsdk30samplesfriendpickersamplebinjarlistcache20130308 155807 hellofacebooksample warning unable to write jarlist cache file cusersgtmfacebookandroidsdk30sampleshellofacebooksamplebinjarlistcache20130308 155807 switchusersample warning unable to write jarlist cache file cusersgtmfacebookandroidsdk30samplesswitchusersamplebinjarlistcacheso could you please help me out from this problem,['android'] +434901,rails link to remote i have the following link to my path method delete confirm delete class linkdelete datamessage are you sure dataseverity danger remote true do i classicontrashi end which brings up a bootstrap modal for confirmation and i wanted to hook onto the ajax call that so that i can thisplay a spinner or some kind of texti know that i can use unobtrusive javascript to listen to the click event like so if i do not use remote true in my link tojquery linkdeletelive click event linkdeletehtmlloading the msg or animation i want to thisplay getthishref null null script falsebut not sure how to combine the two when using remote true any suggestionsthanks for the help,"['javascript', 'ruby-on-rails']" +434909,getting all keys in a dict that overlap with other keys in the same dict i have a list comprehension that looks like thiscart pq for pq in itertoolsproductcitems repeat2 if p1 q1 c is a dict with keys that are tuples of arbitrary integers all the tuples have the same length worst case is that all the combinations should be included in the new list this can happen quite frequentlyas an example i have a dictionary like thisc 01b 20c 00d and i want the the result to be cart 2 0 c 0 1 b 2 0 c 0 0 d 0 0 d 0 1 b 0 0 d 0 0 d so by overlap i am referring to for instance that the tuples 1234 and 2345 have the overlapping section 234 the overlapping sections must be on the edges of the tuples i only want overlaps that have length one shorter than the tuple length thus 1234 does not overlap with 3456 also note that when removing the first or last element of a tuple we might end up with nonthistinct tuples all of which must be compared to all the other elements this last point was not emphasized in my first examplethe better part of my codes execution time is spent in this list comprehension i always need all elements of cart so there appears to be no speedup when using a generator insteadmy question is is there a faster way of doing this a thought i had was that i could try to create two new dictionaries like thisaa defaultdictlistbb defaultdictlistaap1appendp for p in ckeysbbp1appendp for p in ckeysand somehow merge all combinations of elements of the list in aai with the list in bbi for all i but i can not seem to wrap my head around this idea eitherupdateboth the solution added by tobias k and shx2 have better complexity than my original code as far as i can tell my code is on2 whereas the two other solutions are on for my problem size and composition however all three solutions seem to run at more or less the same time i suppose this has to do with a combination of overhead associated with function calls as well as the nature of the data i am working with in particular the number of different keys as well as the actual composition of the keys seem to have a large impact the latter i know because the code runs much slower for completely random keys i have accepted tobias ks answer because his code is the easiest to follow however i would still greatly welcome other suggestions on how to perform this task,['python'] +434917,create sqlite database and table within c application code i would like to create and then interact with one or more sqlite databaseswhat is the preferred method to initialize a new sqlite database file and open it for reading and writingfollowing the databases creation how may i execute a ddl statement to create a table,['c#'] +434955,splitting text into lines with maximum length i have a long string and i want to fit that in a small field to achieve that i break the string into lines on whitespace the algorithm goes like this public static string breaklinestring text int maxcharsinline int charsinline 0 stringbuilder builder new stringbuilder for int i 0 i textlength i char c texti builderappendc charsinline if charsinline maxcharsinline chariswhitespacec builderappendline charsinline 0 return buildertostring but this breaks when there is a short word followed by a longer word foo howcomputerwork with a max length of 16 does not break but i want it to one thought i has was looking forward to see where the next whitespace occurs but i am not sure whether that would result in the fewest lines possible,['c#'] +434963,how can i inject a mock service into a unit test for a filter i have a simple angularjs filter it takes an id and converts it to a name string that depends on a custom service to do its workangularmoduleappfilteridtoname functionuser return functionid var result user result if id result no name found user usergetbyidid if user result userfirstname return result and i want to write a unit test for it i would like to be able to inject a mock of the user service into the testi can do this for a controller unit test as shown in the documentationvar mockuserservicemockuserservice getbyid functionid return firstname bob beforeeachinjectfunctionrootscope controller var ctrl scope userservice userservice mockuserservice scope rootscopenew return ctrl controllersomecontroller scope scope user userservice but replacing controller with filter in the beforeeach does not work as i presume filters are constructed differently by angular ie do not allow you to inject locals as a second parameter to the constructorhas anyone come across this solved this before,['javascript'] +434967,selenium firefox command click does not work with a found element i tried to find a solution to this thing and i spent a lot of time but it is almost imposible to me to do thatthe matter i am using selenium with java in firefox i need to find an element a listbox and click on it so the code finds the element but click action does not work it works fine in google chrome every time and just sometimes in firefox with the same java code sometimes works and sometimes does notthere is the part of code with the element when the program enters on the page div idsizebtn clasizebtn span claselectedsizeselecciona talla span div clasizeselect stylethisplay none table tbody tr idselecsize 2 classproductsize datagapropsactionseleccionar producto opt labelescoger talla datacatentryid1051607 tr idselecsize 3 classproductsize datagapropsactionseleccionar producto opt labelescoger talla datacatentryid1051608 tr idselecsize 4 classproductsize datagapropsactionseleccionar producto opt labelescoger talla datacatentryid1051609 tr idselecsize 5 classproductsize datagapropsactionseleccionar producto opt labelescoger talla datacatentryid1051610 tbody table button clasizeguide gaviewevent gatrack datagapropsactionseleccionar talla opt labelguia de tallas datahrefcategoryid358056langid5productid1047599storeid10701guaa de tallasbutton div divand there is the part of code that changes when the element is clicked div idsizebtn clasizebtn openedi tried many solutions and sometimes it works but the next time i run the program it does not work againsome solutionsit finds the element but does not run click action i checked with xpath and cselector and there are unique elements found with those expressionsdriverfindelementbyxpathdividsizebtn and notcontainsclassopenedspanclick also checked with bycselectorspanselectedsizei though it was because of the time so i tried to solve it that waywebelement we driverfindelementbyxpathdividsizebtn and notcontainsclassopenedspan bycselectorspanselectedsizethreadsleep30weclickfinally i was a little bit desperate and i created a new function to try to do this almost 60 times looking for the change on the element code and if there was any change just tried to do click action againclickandwaitwhileelementisnotpresentbyxpathdividsizebtn and notcontainsclassopenedspanbyxpathdivclasizebtn openedspan bycselectorspanselectedsizeprivate void clickandwaitwhileelementisnotpresentby by1 by by2 throws exception for int second 0 second if second 60 failtimeout try if iselementpresentby2 break else driverfindelementby1click catch exception e threadsleep10 there are the images of the elementdoes anybody know how to do that,['java'] +435011,jquery on delegated mouseenter and mouseleave whats the best way to delegate multiple events using onthis is the syntax for one delegated eventdocumentonmousenterfoo functionand here is the syntax for multiple events not delegatedfon mouseenter function stuff mouseleave function stuff i was wondering if there was a more succinct way to do this other thendocumentonmouseenter foo function onmouseleave foo functionit is not a big deal if i have to do it that way i am more curious about it than anything,['jquery'] +435028,transition when adding new data to d3 streamgraph i use d3 to draw a stream graph very similar to the official example the only difference is how i updated it with new data i do not only want a vertical yvalue transition but also want to add new data points on the right the whole graph should become compressed in the horizontal direction it was no problem to achieve the desired result the only problem is that the transition between the two states does not look as expectedyou can find a a minimal example of the strange transition effect on jsfiddle press the update button to see the effecttest data0 0 00 1 00 1 00 0 00 1 06 1 00 0 00 1 03 1 00 0 00 1 00 1 06 0 03 1 00 1 00 0 00 1 03 1 03 0 03 1 00 1 00 0 03 1 00 1 00 0 00 1 00 1 00test data1 0 00 1 00 1 00 0 00 1 06 1 00 0 00 1 03 1 00 0 00 1 00 1 06 0 03 1 00 1 00 0 00 1 03 1 03 0 03 1 00 1 00 0 03 1 00 1 00 0 00 1 00 1 00 0 00 1 00 1 00updateclickfunction streamed historytest data1var width 300 height 200 colors 0 6ff500 1 ffad0a 1 f90035 feedbacks 1 0 1 stack d3layoutstackvar svg d3selecttimelineappendsvg attrwidth width attrheight heightvar y d3scalelinear domain0 1 rangeheight 0streamed historytest data0function streamed historydata data array feedbacksmapfunction f return datamapfunctionelement i return x i y elementf layers stackdata array layers feedbacksmapfunction f i return layer layersi feedback f color colorsf var x d3scalelinear domain0 datalength 1 range0 width var area d3svgareainterpolatebasis xfunctiond return xdx y0functiond return ydy0 y1functiond return ydy0 dy enter svgselectallpath datalayers enterappendpath attrd function d return areadlayer stylefill functiond return dcolor update d3selectallpath datalayers transition duration20 attrd function d return areadlayer,['javascript'] +435049,problems with running exe file built with visual studio on another computer i created a client server application in c using visual studionow i want to run the client exe file on another computer which does not have visual studio installedbut when i try run the exe file it gives the following error messagethis application has failed to start because the application configuration is incorrect reinstalling the application may fix this problemhow can i run the exe file without installing anything on the computer,['c++'] +435060,create new pending intent every time in android how do i create pending intent evertime currently my existing pending intent is getting replaced with new one i trid using flag one shot as well as cancel current but it did not workcan someone please help methankschintan,['android'] +435068,populate listview from arraylist of objects i have a listactivity which will thisplay a list of persons name and address with data from arraylist of objects heres the method to fill the listview so farprivate void filldataarraylistperson messages populating list should go herethe person class is stores name and address of a personpublic class person string name string addresswhile my listitem for my listview consist of two textview like this twolinelistitem xmlnsandroidandroidlayout widthfill parentandroidlayout heightwrap contentandroidminheightandroidattrlistpreferreditemheightandroidmodetwolineandroidclickablefalseandroidpaddingbottom9dpandroidpaddingtop5dp textview androidididthisplay name androidlayout widthmatch parent androidlayout heightwrap content androidlayout marginleft10dp androidtextappearanceandroidattrtextappearancelarge textview androidididthisplay number androidlayout widthmatch parent androidlayout heightwrap content androidlayout alignleftidthisplay name androidlayout belowidthisplay name androidtextappearanceandroidattrtextappearancesmall i want each item in my listview to thisplaying both the name and address of each person can somebody please help thanks in advance and sorry for my bad english,['android'] +435072,core audio offline rendering genericoutput anybody successfully done offline rendering using coreaudioi had to mix two audio files and apply reverbused 2 audiofileplayermultichannelmixerreverb2 and remoteiogot it working and i could save it while its previewingon rendercallback of remoteioi need to save it without playing it offlinethanks in advance,['ios'] +435077,load 3d models with jpctae i am trying to load 3d models in my application with jpctae i read through several tutorials and i think i understand the basics but i have yet to succeed in integrating the 3d files i havei am making use of pieces of codes i found on tutorials package comexamplejpctimport javaioioexceptionimport javaioinputstreamimport javaiounsupportedencodingexceptionimport javalangreflectfieldimport javaxmicroeditionkhronoseglegl10import javaxmicroeditionkhronosegleglconfigimport javaxmicroeditionkhronosegleglthisplayimport javaxmicroeditionkhronosopenglesgl10import androidappactivityimport androidcontentresassetmanagerimport androidopenglglsurfaceviewimport androidosbundleimport androidviewmotioneventimport comthreedjpctcameraimport comthreedjpctframebufferimport comthreedjpctlightimport comthreedjpctloaderimport comthreedjpctloggerimport comthreedjpctobject3dimport comthreedjpctprimitivesimport comthreedjpctrgbcolorimport comthreedjpctsimplevectorimport comthreedjpcttextureimport comthreedjpcttexturemanagerimport comthreedjpctworldimport comthreedjpctutilbitmaphelperimport comthreedjpctutilmemoryhelperimport javaioimport comthreedjpctimport androidcontentresresourcesimport androidopenglglsurfacevieweglconfigchooserimport androidopenglglsurfaceviewrendererimport androidutillog a simple demo this shows more how to use jpctae than it shows how to write a proper application for android it includes basic activity management to handle pause and resume author egonolsen public class mainactivity extends activity used to handle pause and resumeprivate static mainactivity master nullprivate glsurfaceview mglviewprivate myrenderer renderer nullprivate framebuffer fb nullprivate world world nullprivate rgbcolor back new rgbcolor50 50 100private float touchturn 0private float touchturnup 0private float xpos 1private float ypos 1private object3d cube nullprivate int fps 0private light sun nullassetmanager assmaninputstream isprivate string thingname palmrealvizprivate int thingscale 1end protected void oncreatebundle savedinstancestate loggerlogoncreate if master null copymaster superoncreatesavedinstancestate mglview new glsurfaceviewgetapplication mglviewseteglconfigchoosernew glsurfacevieweglconfigchooser public eglconfig chooseconfigegl10 egl eglthisplay thisplay ensure that we get a 16bit framebuffer otherwise well fall back to pixelflinger on some device read samsung i7500 int attributes new int egl10egl depth size 16 egl10egl none eglconfig configs new eglconfig1 int result new int1 egleglchooseconfigthisplay attributes configs 1 result return configs0 renderer new myrenderer mglviewsetrendererrenderer setcontentviewmglviewoverrideprotected void onpause superonpause mglviewonpauseoverrideprotected void onresume superonresume mglviewonresumeoverrideprotected void onstop superonstopprivate void copyobject src try loggerlogcopying data from master activity field fs srcgetclassgetdeclaredfields for field f fs fsetaccessibletrue fsetthis fgetsrc catch exception e throw new runtimeexceptione public boolean ontoucheventmotionevent me if megetaction motioneventaction down xpos megetx ypos megety return true if megetaction motioneventaction up xpos 1 ypos 1 touchturn 0 touchturnup 0 return true if megetaction motioneventaction move float xd megetx xpos float yd megety ypos xpos megetx ypos megety touchturn xd 100f touchturnup yd 100f return true try threadsleep15 catch exception e no need for this return superontoucheventmeprotected boolean isfullscreenopaque return trueclass myrenderer implements glsurfaceviewrenderer private long time systemcurrenttimemillis public myrenderer public void onsurfacechangedgl10 gl int w int h if fb null fbthispose fb new framebuffergl w h if master null world new world worldsetambientlight20 20 20 sun new lightworld sunsetintensity250 250 250 create a texture out of the icon texture texture new texturebitmaphelperrescalebitmaphelperconvertgetresourcesgetdrawablerdrawableic launcher 64 64 texturemanagergetinstanceaddtexturetexture texture try cube loadmodelassets thingname 3ds thingscale catch unsupportedencodingexception e todo autogenerated catch block eprintstacktrace primitivesgetcube10 cubecalctexturewrapspherical cubesettexturetexture cubestrip cubebuild worldaddobjectcube camera cam worldgetcamera cammovecameracameracamera moveout 50 camlookatcubegettransformedcenter simplevector sv new simplevector svsetcubegettransformedcenter svy 100 svz 100 sunsetpositionsv memoryhelpercompact if master null loggerlogsaving master activity master mainactivitythis public void onsurfacecreatedgl10 gl eglconfig config public void ondrawframegl10 gl if touchturn 0 cuberotateytouchturn touchturn 0 if touchturnup 0 cuberotatextouchturnup touchturnup 0 fbclearback worldrenderscenefb worlddrawfb fbthisplay if systemcurrenttimemillis time 10 loggerlogfps fps fps 0 time systemcurrenttimemillis fps private object3d loadmodelstring filename float scale throws unsupportedencodingexception inputstream stream new bytearrayinputstreamfilenamegetbytesutf8 object3d model loaderload3dsstream scale object3d o3d new object3d0 object3d temp null for int i 0 i modellength i temp modeli tempsetcentersimplevectororigin temprotatexfloat 5mathpi temprotatemesh tempsetrotationmatrixnew matrix o3d object3dmergeobjectso3d temp o3dbuild return o3d so the applications fails here is my logcatfatal exception glthread 93javalangruntimeexception 1363008600568 error not a valid 3ds fileat comthreedjpctloggerlogloggerjava189at comthreedjpctloaderload3dsloaderjava1554at comthreedjpctloaderload3dsloaderjava154at comexamplejpctmainactivitymyrendererloadmodelmainactivityjava269at comexamplejpctmainactivitymyrendereronsurfacechangedmainactivityjava207at androidopenglglsurfaceviewglthreadguardedrunglsurfaceviewjava1505at androidopenglglsurfaceviewglthreadrunglsurfaceviewjava1240the 3d file is in the assets folder and is a 3ds valid file i tested it on other 3d enginecan you help me please,['android'] +435101,turn off predictive text for password field on websites i have an android application that thisplays a page in a webview to handle a usernamepassword login i have found that with certain keyboards like the stock keyboard on samsung jellybean devices the predictive text is changing what the user types in the password fieldfor example if the password is abd the predictive text tries to help by automatically entering a space after the punctuation making it ab d and causes an incorrect password to be entered the only reason i know that predictive text is behind this is that this problem does not occur when predictive text is turned off through the keyboard menu settingsis there a way to thisable the predictive text when typing in the web form i already have the input type set to password to mask the entry this is not an android textview it is an html input so i do not have the platform level controls on the input and as far as i know android does not understand the autocorrectoff setting that some sites use to tackle this problem on ios devices i have noticed that this problem does not seem to happen on other websites like mailgooglecom the same keyboard regardless of settings will politely leave the users input alone on the password field there looking through the html source on that page did not reveal anything special on the password field only the same input type that i already use have any of you run into this problem or can you think of possible solutions is there something that mailgooglecom or other sites do that i am missing any help will be greatly appreciatedsample of the html is belowdiv datarolefieldcontain classuihidelabel label foruseridlabelinput autocompleteoff autocorrectoff autocapitalizeoff spellcheckfalse typetext nameuser iduser value maxlength50 placeholderuserid text datathemecdivdiv datarolefieldcontain classuihidelabellabel forpasswordpasswordlabelinput autocompleteoff autocorrectoff autocapitalizeoff spellcheckfalse typepassword namepassword idpassword value maxlength50 placeholderpassword datathemecdiv,"['android', 'html']" +435153,python return return none and no return at all consider three functionsdef my func1 print hello world return nonedef my func2 print hello world returndef my func3 print hello worldthey all appear to return none are there any differences between how the returned value of these functions behave are there any reasons to prefer one versus the other,['python'] +435159,fputcsv in php will not write to file i have have searched and searched and done extensive debugging and for the life of me cannot figure out why fputcsv is not working for me i can sucessfully open the csv file and write to it my debugging proves that the array is properly loaded and that the foreach loop is working correctly however the fputcsv function fails to write anything at all i have removed all strings that i though may cause a problem such as urls etc but it still will not write i am the only person with access to this environment so i know it is not a file lock conflict i can create the file and write to it so i know it is not a permissions issue and i get debug output from the foreach loop so i know it is not an issue with the array or the loopi will provide my code and debug log belowposts meta array twitter title this title twitter brandtag this brandtag twitter hashtags this hashtags twitter iterations this iteration twitter timing this timing twitter time this time twitter id post id debugingfile put contentsblogdebugtxt about to write csv filen file appendfile put contentsblogdebugtxt print rposts meta truen file appendmyfile fopenblogpdm twitter ouptutcsv a more debuginfile put contentsblogdebugtxt myfile handle myfilen file appendfwritemyfile this file is open and workingrnforeach posts meta as fields fresponse fputcsvmyfile fields a little more debugging file put contentsblogdebugtxt fieldsn file appendfclosemyfile and more debuggingfile put contentsblogdebugtxt fputcsv response fresponsen file appendfile put contentsblogdebugtxt just closed csv file file appendand here is the resulting debug logabout to write csv filearray twitter title world stocks up as us jobs china exports improve twitter brandtag fp test 9 twitter hashtags economy markets business investing stocks twitter iterations 12 twitter timing 240 twitter time 20130308 075524 twitter id 11051myfile handle resource id 548 printout of fields hereworld stocks up as us jobs china exports improve fp test 9economy markets business investing stocks1224020130308 07552411051fputcsv response hm i wonder why no response codejust closed csv fileall that appears in the csv file is as you can see in the debug code above this file is open and workingany thoughts anyone may have would be greatly appreciatedthanks so muchtrip,['php'] +435182,how do you run meteor on windows 8 i have installed meteor js by following the instructions but still it would not work it will create an app but would not run it it always says youre not in a meteor project directory,['javascript'] +435199,how can i load the raw data of a 48bpp image into a bitmap i asked a similar question to do with a 24bpp image here but i am using the techniques described there and have a second issue this time to do with 48bppi have a byte containing a 16bit color depth image so there are two bytes for red two for green and two for blue in sequence from the top left of the image to the bottom right i am loading this into a bitmap like so taking into account the stride etcbyte data readrawdata swap from rgb to bgrfor int i 5 i datalength i6 var r1 datai 5 var r2 datai 4 var b1 datai 1 var b2 datai datai 5 b1 datai 4 b2 datai 1 r1 datai r2 load into a bitmap i know the width and height and the formatusing var b new bitmap157 196 pixelformatformat48bpprgb var bmpdata blockbitsnew rectangle0 0 bwidth bheight imagelockmodereadwrite bpixelformat here we loop through each line and make sure it is padded to the stride length var bytesperline bwidth 6 for int i 0 i bheight i intptr offset bmpdatascan0 i bmpdatastride marshalcopydata i bytesperline offset bytesperline int padding bmpdatastride bytesperline if padding 0 var pad new bytepadding marshalcopypad 0 offset bytesperline padding bunlockbitsbmpdata done so save bsavecouttiff imageformattiffand it produces this imagethe image is not correct though it should look like thisso my question is well what have i done wrongupdateif i switched the r1r2 and b1b2 and the green ones in case of an endianess issue but then it draws the image like thisso still not right but does that give us a clue as to what is going on perhapsi have put a file up on github here that is the raw data so you can save that down to your thisk and then this little method will open it upprivate static byte readrawdata byte data using var ms new memorystream using var f fileopenreadcdata16bin byte buffer new byte2048 int read while read freadbuffer 0 bufferlength 0 mswritebuffer 0 read data mstoarray return dataif i need to use wpf libraries instead that is fine with meupdate 2so as suggested in the comments i came up with a bit of code to generate a byte array that i could reason aboutwhat i did therefore was output a byte array that is 196 200 6 in length such that i will have an image that is 196 pixels wide by 200 high with 6 bytes per pixel the size is handy as it is big enough to see and one that does not mean i have to bother with the stride thing i then decided that i would split the picture up into 4 vertical stripes the bytes of which for each stripe are0x00 0x00 0x00 0x00 0xff 0xff 0x00 0x00 0x00 0x00 0x00 0xff0x00 0x00 0x00 0x00 0xff 0x0x00 0x00 0x00 0x00 0x00 0x00this should mean i can see the difference between the colours right well what i actually got was this so what am i doing wronghere is my code that produced the above imageusing systemusing systemdrawingusing systemdrawingimagingusing systemiousing systemruntimeinteropservicesnamespace imageplayingapplication class program static void mainstring args const int width 196 const int height 200 const int columnwidth width 4 const int bytesperpixel 6 var data new bytewidth height bytesperpixel for int y 0 y height y for int x 0 x width bytesperpixel x bytesperpixel int i y width bytesperpixel x blue and green components always 0x00 since we are just interested in red datai 0x00 datai 1 0x00 datai 2 0x00 datai 3 0x00 if x columnwidth bytesperpixel left most column full red datai 4 0xff datai 5 0xff else if x columnwidth bytesperpixel 2 next left half red datai 4 0x00 datai 5 0xff else if x columnwidth bytesperpixel 3 next left other half red datai 4 0xff datai 5 0x00 else final column no red datai 4 0x00 datai 5 0x00 using var b new bitmapwidth height pixelformatformat48bpprgb var bmpdata blockbits new rectangle0 0 bwidth bheight imagelockmodereadwrite bpixelformat marshalcopydata 0 bmpdatascan0 datalength bunlockbitsbmpdata bsavecuserspublicstripes2tiff imageformattiff so does any one know how i can get the byte array described here into a bitmap that is correct as i said if there is anything in wpf that would help that would be fine or maybe i need to transform it into i do not know 64bppargb format or something,"['c#', '.net']" +435201,function address in libc i am trying to obtain the address in hex of function exit provided in libc but i am not sure where and how to find itanyone knows the way to find it please share some idea thank you,['c'] +435242,uicollectionview cell subviews do not resize in a collectionview some cells should have an additional subview or layer the collectionview can be told to resize it is cells thus all content needs to resize appropriatelycurrently the cell is initialized from a nib containing a cell with imageview the cell nib is linked to a custom uicollectionviewcell subclass that only does the init autoresize subviews is checkedthe collectionview is told to resize the cell by a value derived and returned in sizeforitematindexpath i have subclassed a flowlayout but it only specifies scrolldirection and insetsall of that is working fine problem how do i add subviewlayer to the cell so it also resizes correctly i tried adding subviews and layers with translatesautoresizingmaskintoconstraints off but these do not automatically change size at all also tried to use code frameview instead of nib the best i got now is a cellcontentviewlayer sublayer which i add in cellforitematindexpath that is manually resized by storing the cells framesize from sizeforitematindexpath which is not only ugly but also ends up with the sublayer having various sizes for different cellsany help appreciated,['ios'] +435243,jackson json field mapping capitalization i am not clear how jackson deals with capitalization in mapping fields if anyone could help i would appreciate it userusernamepasswordpwdsendercompidcompidservicehostaddressport6services1serviceasstrings1mdreqidghost30022norelatedsym1symbolgoogmarketdepth0nomdentrytypes3mdentrytype012subscriptionrequesttype1aggregatedbooknabove is my json below is my exceptioncomfasterxmljacksondatabindexcunrecognizedpropertyexception unrecognized field mdreqid class commycoqafixrestmarketdatarequest not marked as ignorable 10 known properties mdreqid marketdepth user subscriptionrequesttype aggregatedbook mdentrytype symbol mdupdatetype norelatedsym nomdentrytypesabove is my exception below is my classpublic class marketdatarequest private user user private string mdreqid private char subscriptionrequesttype private int marketdepth private int mdupdatetype private char aggregatedbook private int nomdentrytypes private arraylistcharacter mdentrytype private int norelatedsym private arrayliststring symbol public user getuser return user public void setuseruser user thisuser user public string getmdreqid return mdreqid public void setmdreqidstring mdreqid thismdreqid mdreqid public char getsubscriptionrequesttype return subscriptionrequesttype public void setsubscriptionrequesttypechar subscriptionrequesttype subscriptionrequesttype subscriptionrequesttype et cetera,['java'] +435255,assigning a variable what actually happens java in the following example what actually happensint a 1a a 2the output is 3 however i wanted to know what actually happens under the covers for example i know that parentheses have higher priority to so happening first a 2 the expression should become a 2 2at runtime first the expression within parentheses should be executed and then a becomes 2 it seems that the first a on the left to gets loaded before of a 2 and this last expression does not seem to override the previous loadingin other words i am quite confused to what exactly happens behind the scenes if anybody knows thanks a lot in advance,['java'] +435270,how to handle floats and decimal separators with html5 input type number im building web app which is mainly for mobile browsers im using input fields with number type so most mobile browsers invokes only number keyboard for better user experience this web app is mainly used in regions where decimal separator is comma not dot so i need to handle both decimal separatorshow to cover this whole mess with dot and commamy findingsdesktop chromeinput typenumberuser enters 455 to input field my inputval returns 455i can not get the correct value from inputdesktop firefoxinput typenumberuser enters 455 to input field my inputval returns 455thats fine i can replace comma with dot and get correct floatandroid browserinput typenumberuser enters 455 to input field when input loses focus value is truncated to 4confusing to userwindows phone 8input typenumberuser enters 455 to input field my inputval returns 455thats fine i can replace comma with dot and get correct floatwhat are the best practices in this kind of situations when user might use comma or dot as decimal separator and i want to keep html input type as number to provide better user experiencecan i convert comma to dot on the fly binding key events is it working with number inputseditcurrenlty i do not have any solution how to get float value as string or number from input which type is set to number if enduser enters 455 chrome returns always 455 firefox returns 455 which is finealso it is quite annoying that in android tested 42 emulator when i enter 455 to input field and change focus to somewhere else the entered number get truncated to 4,"['javascript', 'jquery']" +435292,form validation allow only english alphabet characters i would like to restrict my form input from entering nonenglish characters for example all chinese japanese cyrllic but also single characters like a a a1 a a14 a a aa would this be possible do i have to set up a locale on my mvc application or rather just do a regex textbox validation just a side note i want to be able to enter numbers and other characters i only want this to exclude letters please advice thank you,"['c#', 'asp.net']" +435310,predefined macros for function name func i am attempting to build a debug log message function that records the file line and function of of where the log message was called from define debug panicp cloggingdebuglogf debug marker s s in file sd p func file line the above code works on some compilers but not all my code needs to be cross compatible with gcc as well as microsoft visual studios i have added the below defines to help with compatibility ifndef function name if defined func undeclared define function name func elif defined function undeclared define function name function elif defined pretty function undeclared define function name pretty function else declared define function name na endif func endif function name define debug panicp cloggingdebuglogf debug marker s s in file sd p function name file line the problem with the above code snippet is that it is the else macro is active on all compilers while the other macros are not in other words if defined func is false on compilers where func is a predefined macromy question ishow do i create a cross compiler macro to find the function name how can i tell if a func can be used,['c++'] +435312,gem install fails with openssl failure i tried to install cocoapods on my osx mountain lion moshembp moshem gem install cocoapods error could not find a valid gem cocoapods 0 here is why unable to download data from ssl connect returned1 errno0 statesslv3 read server key exchange b bad ecpoint specs48gzfirst i tried rvm reinstall all forcethen i tried brew upgrade openssl upgrading openssl downloading already downloaded librarycacheshomebrewopenssl101etargz perl configure prefixusrlocalcellaropenssl101e openssldirusrlocaletcopenssl zlibdynamic shared d make make test make install mandirusrlocalcellaropenssl101eshareman mansuffixssl caveats to install updated ca certs from mozillaorg brew install curlcabundle this formula is kegonly so it was not symlinked into usrlocal mac os x already provides this software and installing another version in parallel can cause all kinds of trouble the openssl provided by os x is too old for some software generally there are no consequences of this for you if you build your own software and it requires this formula youll need to add to your build variables ldflags lusrlocaloptopenssllib cppflags iusrlocaloptopensslinclude summary i 14i12o usrlocalcellaropenssl101e 429 files 15m built in 51 minutesi then triedopenssl versionand still gets the older versionmoshembp moshem openssl versionopenssl 098r 8 feb 2011moshembp moshem what am i doing wrong how can i install the cocoapods gemthanksedit trying sean suggestionmoshembp moshem brew updateupdated homebrew from 672af665 to 10b4d426 updated formulaebash wiresharkmoshembp moshem brew install opensslerror openssl101e already installedmoshembp moshem brew link openssl forcelinking usrlocalcellaropenssl101e 1139 symlinks createdmoshembp moshem brew install curlcabundleerror curlcabundle187 already installedmoshembp moshem moshembp moshem openssl versionopenssl 098r 8 feb 2011moshembp moshem gem install cocoapodserror could not find a valid gem cocoapods 0 here is why unable to download data from ssl connect returned1 errno0 statesslv3 read server key exchange b bad ecpoint specs48gzedit 2 after fixing issues with brew doctormoshembp moshem gem install cocoapodserror could not find a valid gem cocoapods 0 here is why unable to download data from ssl connect returned1 errno0 statesslv3 read server key exchange b bad ecpoint specs48gzmoshembp moshem openssl versionopenssl 098r 8 feb 2011moshembp moshem brew updateupdated homebrew from 10b4d426 to 6a00bc3c updated formulaeclozurecl python python3moshembp moshem brew install opensslerror openssl101e already installedmoshembp moshem moshembp moshem echo pathusersmoshemrvmgemsruby200p0binusersmoshemrvmgemsruby200p0globalbinusersmoshemrvmrubiesruby200p0binusersmoshemrvmbinbinusrlocalbinusrbinbinusrsbinsbinusrlocalgitbintoolsplatformsplatformtoolsmoshembp moshem edit after altering the etcpathsi edited the etcpath files tousrlocalbinusrbinbinusrsbinsbinclosed terminal completly and reopend and it still launches the old version of opensslwhymoshembp moshem env pathenv usersmoshemrvmgemsruby200p0binusersmoshemrvmgemsruby200p0globalbinusersmoshemrvmrubiesruby200p0binusersmoshemrvmbinbinusrlocalbinusrbinbinusrsbinsbinusrlocalgitbintoolsplatformsplatformtoolsedit my bash profilesource brew prefix grcetcgrcbashrcexport pathjava homebinpathexport pathpathandroid sdktoolsandroid sdkplatformsandroid sdkplatformtoolsandroid ndk s homervmscriptsrvm source homervmscriptsrvm load rvm into a shell session as a functionbtw the etcgrcbashrc does not seem to exist on my machine both this line and the rvm line at the end were added by installed scriptseditmoshembp moshem rvm pkg install openssl fetching openssl101ctargz to usersmoshemrvmarchivesextracting openssl to usersmoshemrvmsrcopenssl101cconfiguring openssl in usersmoshemrvmsrcopenssl101ccompiling openssl in usersmoshemrvmsrcopenssl101cinstalling openssl to usersmoshemrvmusrplease note that it is required to reinstall all rubies rvm reinstall all forceupdating openssl certificatesmoshembp moshem openssl versionopenssl 101e 11 feb 2013moshembp moshem gem source r removed from sourcesmoshembp moshem gem source a error fetching ssl connect returned1 errno0 statesslv3 read server key exchange b bad ecpoint moshembp moshem gem install cocoapodserror could not find a valid gem cocoapods 0 in any repository,['ruby'] +435313,boost intersection not working i have a big problem with boost intersection i would like to intersect a triangle with a quad but i get a clipcan somebody help me i tried to changed the orientation of the geometry nothing happened the intersection work with other triangles but not with thistypedef modelpolygonmodeld2point xydouble polygonstddequepolygon tmpbool ok intersectionquad triangle tmpthe triangle21357 213163e14 0 350 375 0 350 284217e14 0the boxboundingbox300 165 2 170 01 01updatehere my code i use gcc 472 with boost 1530 on ubuntu 1210include dequeinclude fstreaminclude boostgeometryhppinclude boostgeometrygeometriespolygonhppinclude boostgeometrygeometriespoint xyhppinclude boostgeometryiowktwkthppinclude boostgeometryextensionsiosvgsvg mapperhppusing namespace boostgeometryint main typedef modelpolygonmodeld2point xydouble polygon typedef typename modeld2point xydouble point type polygon quad triangle read wktpolygon21357 2131 3500 375 3500 2842 21357 2131 triangle read wktpolygon30 2 300 170 165 170 165 2 300 2 quad stddequepolygon output intersectionquad triangle output stdstring filename intersectiontestsvg stdofstream svgfilenamec str svg mapperpoint type mappersvg 600 600 mapperaddoutput0 mappermapoutput0 fillopacity05fillrgb1532040strokergb25500strokewidth5,['c++'] +435318,how to use powermock in android projects i created a new android test project i downloaded powermockmockitojunit115zip from i added all of the libraries to the test projects libs folder the test class is a very simple objectpackage comtesttestimport orgjunitrunnerrunwithimport orgpowermockmodulesjunit4powermockrunnerimport androidutillogrunwithpowermockrunnerclasspublic class testtestandroid public void testruns logetest test case is called then i try running the project from eclipse or making the project from the command line i get the same errorconversion to dalvik format failed unable to execute dex multiple dex files define lorghamcrestdescriptionas it turns out both junit482jar and mockitoall195jar define orghamcrestdescription i must include the mockito jar for obvious reasons i need mockito a different version of junit is provided by android but it is an old version that does not include the runwith annotationcan someone answer how to use powermock and mockito in an android project without the conflicting orghamcrestdescription problem,['android'] +435331,generate an adjacency matrix for a weighted graph i am trying to implement floydwarshall algorithm to do this it requires me to set up an adjacency matrix of a weighted graph how would i go about doing this i know the values and have attached a picture of the weighted graph i have tried to look for some online examples of this but i cannot seem to find anything i understand floydwarshall algorithm i just need help getting it set up so i am able to implement it here is one that i have built before but i did not have to use specific valuescodepublic static void buildadjmatrix for int i 0 i 100 i for int j 0 j 100 j if directionallowedi j true adjmatrixi j 1 else adjmatrixi j 50 here is the specific graph at handhere is a picture of the matrix i need to create sorry for the horrible quality,['c#'] +435334,cannot step into stringh function with gdb having trouble stepping into stringh in gdb 75 heres a simple example programsource codeinclude stdiohinclude stringhint main char str120 strcpystr1 step into men printfstr1compiled gcc g foocinvoked gdb q aoutgdbgdb break 5breakpoint 1 at 0x8048471 file fooc line 6gdb break strcpyfunction strcpy not definedmake breakpoint pending on future shared library load y or n ybreakpoint 2 strcpy pendinggdb run starting program homeuseraout breakpoint 1 main at fooc66 strcpystr a hello worldngdb step7 printfstr ashould not i be in the string library at this point instead it continues to the printfeditscotts suggestion worked but not in the expected mannerbreakpoint 1 main at fooc66 strcpystr a hello worldngdb i r eipeip 0x80484a1 0x80484a1 main21gdb stepbreakpoint 2 strcpy se3 at sysdepsi386i686multiarchstrcpyse3s7878 sysdepsi386i686multiarchstrcpyse3s no such file or directorygdb i r eipeip 0xb7e9c820 0xb7e9c820 strcpy se3 i am surprised at the directory in 78 expected something like libcmovlibcso6 and the claim that there is no such file or directory,['c'] +435350,pg peer authentication failed i have a user with password matching the one specified in databaseymlpostgres select from pg user usename usesysid usecreatedb usesuper usecatupd userepl passwd valuntil useconfig goodsounds 16386 t t t t postgres 10 t t t t 2 rowsthis is the errorfunkdifiedvizio rails projectsgoodsoundsorg rake dbcreatefatal peer authentication failed for user goodsoundshere is my pg hbaconf database administrative login by unix domain socketlocal all postgres peer type database user address method local is for unix domain socket connections onlylocal all all peer ipv4 local connectionshost all all 12700132 trust ipv6 local connectionshost all all 1128 trust allow replication connections from localhost by a user with the replication privilegelocal replication postgres peerhost replication postgres 12700132 trusthost replication postgres 1128 trustpreviously trust above was md5 but i changed to see if that would helphere is my databaseyml postgresql versions 82 and up are supported install the pg driver gem install pg on mac os x with macports gem install pg withpgconfigoptlocallibpostgresql84binpg config on windows gem install pg choose the win32 build install postgresql and put its bin directory on your path configure using gemfile gem pgdevelopment adapter postgresql encoding unicode database goodsounds development pool 5 username goodsounds password test connect on a tcp socket omitted by default since the client uses a domain socket that does not need configuration windows does not have domain sockets so uncomment these lines host localhost port 5432 schema search path the server defaults to userpublic schema search path myappsharedapublic minimum log levels in increasing order debug5 debug4 debug3 debug2 debug1 log notice warning error fatal and panic the server defaults to notice min messages warning warning the database defined as test will be erased and regenerated from your development database when you run rake do not set this db to the same as development or productiontest adapter postgresql encoding unicode database goodsounds test pool 5 username goodsounds password testproduction adapter postgresql encoding unicode database goodsounds production pool 5 username goodsounds password test,['ruby-on-rails'] +435355,box2d body velocity cap i have a body that has a mass of 10 and each cycle of the program i apply a force of 100 to it using the simple approachvector2 force new vector20 1 100bodapplyforceforce bodgetworldcenterit works great accelerates and all of that but once it gets to a velocity of 10 100 10 i assume it would not go any faster i am not a physicist by any means but i do recall that the body should continually accelerate like it would under gravity is this speed limit a result of the way box2d does things or am i royally screwing something up also what do i do to fix itnote i get the same limited velocity if i use applylinearimpulse instead of applyforceupdate i am well aware of the overall max speed limit imposed by box2d in b2settingsh in my example the item in question is moving well below this limit as changing the aplied force be it 10 or 10 will always come around to the max velocity of force mass,['c#'] +435421,what does a gem file contain how it is being used by rails framework i just created a test gem using bundle and it created a gem file with unreadable content so i was wondering what does that gem file contains is this binary data as i used to think that gem files contains packaged ruby functionshow is this gem file being used by rails framework since it does not look like a module thanks,"['ruby-on-rails', 'ruby']" +435445,jquery twoway data binding how do you implement a simple twoway data binding in jquerysomething like knockoutjs but in the simplest possible formscenario bind json object to table row every field is tdinputtdany suggestions,"['javascript', 'jquery']" +435459,emberjs how to filter by more than one property at once below i am filtering by a single property sure but how do i filter by another one in one go that is without providing the user with a drop down containing different search optionsexample my search term maybe name email or agevar search thiscontrollerforemployeessearch can be name email or ageemployees thisgetcurrentmodelfilterpropertyname searchthe above works fine for updating the master list but i am only able to filter by one property at a timesample modelappemployee dsmodelextend email dsattrstring name dsattrstring age dsattrnumberone thought is to refilter again if the filter results length 0 and some how merge the results however i am not big on that idea and believe ember may have a better more elegant way of achieving this,['javascript'] +435474,how does typedefing a block works in cobjc we do a typedef like this typedef int myint which is cleardoing typedef for a block typedef void myblock int anow we can use myblockshould not it be like typedef void myblock int a myblock similar to definehow the syntax works,['objective-c'] +435482,josephus sequence description there are people standing in a circle waiting to be executed the counting out begins at some point in the circle and proceeds around the circle in a fixed direction in each step a certain number of people are skipped and the next person is executed the elimination proceeds around the circle which is becoming smaller and smaller as the executed people are removed until only the last person remains who is given freedomi googled this josephus problem and the wikipedia hit gives me a dynamicprogramming solution fnkfn1kk1 mod n1 with f1k1 but this only yields the last survivor how can i get the sequence of the people executed say p5 3 31524also is there a onlogn solution instead of a onk one,"['java', 'c++', 'c']" +435527,resolve substitutions in restructuredtext i want to take the following restructured text snippet that contains a substitution definitiontext python python image pythonjpgand resolve the definitions so the substitution text is thisplayedresolved text image pythonjpgis there a function or utility in docutils or another module that can do this,['python'] +435534,what is the limit of sql variables one can specify in a single execsql query i am trying to improve the speed of my android database inserts what i am currently doing is generate a string likeselect as title as musician id as album id as genreunion select union select union select union select union select and then executing it withsqlitedatabase database initialized in some waystring insertquery the string of the query abovestring parameters the parameters to use in the insertiondatabaseexecsqlinsertquerytostring parametersi am getting the following error when i try to insert about 20 rowscaused by androiddatabasesqlitesqliteexception too many sql variables code 1 while compiling insert into songs title musician id album id genreselect as title as musician id as album id as genreunion select union select when i try to insert about 200 rows everything works finei suppose it is obvious i am trying to pass in too many variables in a single execsql does anyone know what is the limit so that i can split the rows i insert in appropriate batches,['android'] +435553,spring mvc how do i update a model objects attributes using a controller method using spring mvc 30 i am developing a member management system with basic crud operations and am having trouble with my controlleri cannot update a member record using a controller method i have methods to thisplay and process my add member form and another to thisplay my edit member form and they all work finehere is my controllercontrollerpublic class membercontroller private memberservice memberserviceinjectpublic membercontrollermemberservice memberservice thismemberservice memberservice show member listrequestmappingvalue memberslist method requestmethodgetpublic string showmemberlistmapstring object model modelputmembers memberservicegetallmembers return memberslist thisplay add member formrequestmappingvalue membersadd method requestmethodgetpublic string showaddmemberformmodel model modeladdattributenew member return membersadd process add member formrequestmappingvalue membersadd method requestmethodpostpublic string addmembermember member memberserviceaddmembermember return redirectlist thisplay edit member formrequestmappingvalue memberseditid method requestmethodgetpublic string showeditmemberformmodel model pathvariable int id string idasstring integertostringid modeladdattributemember memberservicegetmemberbyididasstring return memberseditid process edit member formrequestmappingvalue memberseditid method requestmethodpostpublic string updatememberpathvariable int id httpservletrequest request member member uncommenting the next line of code sets the member objects forename attribute to test forename membersetforenametest forename uncommenting the next line of code gives the following error http status 405 request method post not supported membersetsurnamerequestgetparametersurname memberserviceupdatemembermember return redirectmemberslisthere is my update methodpublic void updatemember member jdbctemplateupdate update members set forename surname address1 address1 city postcode where memberid membergetforename membergetsurname membergetaddress1 membergetaddress2 membergetcity membergetpostcode membergetidand here is my edit member jsp formsfform methodpost modelattributemember enctypemultipartformdata actionmemberseditmemberid fieldset table cellspacing0 tr thlabel formember ididlabelth tdsfinput pathid size15 idmember id td tr tr thlabel formember forenameforenamelabelth tdsfinput pathforename size15 idmember forename td tr tr thlabel formember surnamesurnamelabelth tdsfinput pathsurname size15 idmember surname td tr tr thlabel formember address1address 1labelth tdsfinput pathaddress1 size15 idmember address1 td tr tr thlabel formember address2address 2labelth tdsfinput pathaddress2 size15 idmember address2 td tr tr thlabel formember citycitylabelth tdsfinput pathcity size15 idmember city td tr tr thlabel formember postcodepostcodelabelth tdsfinput pathpostcode size15 idmember postcode td tr table input typesubmit valueupdate fieldsetsfformbecause the membersetforenametest forename code in my controller sets the test string i thought i could use the parameters that are posted from the form to set the atrributes as followsmembersetsurnamerequestgetparametersurnamebut this causes an http 405 error using firebug i have confirmed that the edit member form is posting the forename surname address1 etc parameters so i cannot figure out why i cannot pull them off the requestany help would be greatly appreciated as i have been at this for 2 days and am going round in circles,['java'] +435563,ios thisable page scrolling with overflowscrolling touch so let us say we want to make a webapp feel like a native app with add to home screen one of the first steps is to thisable the default scrolling easy right window or documentwindowaddeventlistenertouchmove functionevent no more scrolling eventpreventdefault falsethat is all fine and dandy until you add overflowscrolling to the mix to be precise on ios it would be webkitoverflowscrolling touch scrollable happens to be a ul scrollable overflowy auto webkitoverflowscrolling touchby adding event prevention hardwareaccelerated scrolling in a container does not function clearly not the intended effectthe obvious solution looks something like this you could do this for multiple elements of coursevar scrollable documentqueryselectorscrollablescrollableaddeventlistenertouchmove functionevent no more bubbling eventstoppropagation falsethis solution introduces a problem however if you try to scroll left or right in scrollable it reverts back to the default scroll listener clearly then you should monitor the events to see if the touchmove event is tracking left or right right unfortunately no as it will also under circumstances i do not entirely understand revert to the default scroll listener when scrolling vertically in the containernow what to make matters worse we would ideally be able to handle click or clicklike events on the individual lis read touchstartvar items scrollablequeryselectorallscrollable lifor var item 0 item itemslength item itemsitemaddeventlistenertouchstart function handle the touch start falseto fix this problem we could turn to simply using click events but that defaults the goal of making the webapp feel native due to the delay between tapping and response to solve this well add an event listener for touchstart and touchendvar items scrollablequeryselectorallscrollable livar activeitem null starttouch nullfor var item 0 item itemslength item itemsitemaddeventlistenertouchstart functionevent starttouch eventtouches0 activeitem this false itemsitemaddeventlistenertouchend functionevent var touch eventchangedtouches0 var deltax touchpagex starttouchpagex var deltay touchpagey starttouchpagey require the touchstart to be within 10 pixels of the touchend if deltax deltax deltay deltay 100 handle click event falsethat is all fine and good but we still have not solved the problem with default page scrolling taking control of some touchmove events any ideas,['ios'] +435584,how to determine whether c math uses sse2 i stepped into the assembly of the transcendental math functions of the c library with msvc in fpstrict mode they all seem to follow the same pattern heres what happens for sinfirst there is a thispatch routine from a file called thisp pentium4inc it checks if the variable use sse2 mathfcns has been set if so calls sin pentium4 otherwise calls sin default sin pentium4 in sin pentium4asm starts by transferring the argument from the x87 fpu to the xmm0 register performs the calculation using sse2 instructions and loads the result back in the fpu sin default in sinasm keeps the variable on the x87 stack and simply calls fsinso in both cases the operand is pushed on the x87 stack and returned on it as well making it transparent to the caller but if use sse2 mathfcns is defined the operation is actually performed in sse2 rather than x87this behavior is very interesting to me because the x87 transcendental functions are notorious for having slightly different behaviors depending on the implementation whereas a given piece of sse2 code should always give reproducible resultsis there a way to determine for certain either at compile or runtime that the sse2 code path will be used i am not proficient writing assembly so if this involves writing any assembly a code example would be appreciated,"['c++', 'c']" +435612,how to remove background image change flicker i have a div with an image as a background i have it so that whenever someone hovers over the div the background image changes to some other image the problem is the first time when your mouse hovers over the div the background image flickers as it loads and you see no image for few millisecondshow do i remove this flicker how do i load the image for the hover before the user actually hovers over the div so the effect is immediatemy code for changing the div background is very simplesomeid backgroundimage image sourcesomeidhover backgroundimage another image sourcei know that there is a solution with putting the two desired images in one image and then play with the background position but that is not an option here because i always set the background image to be like thisimagesize 100 100,"['javascript', 'jquery', 'html', 'css']" +435637,expressjs routes explanation i was looking at expressjs source code to find out how it maps named route parameters to reqparams properties for those who do not know in expressjs you can define routes with named parameters make them optional only allow the ones with specific format and moreappgetuseridnameaged function req res consolelogid is reqparamsid consolelogname is reqparamsname not specified consolelogage is reqparamsagei realized that the heart of this functionality is a method called pathregexp defined in libutilsjs the method definition is as followsfunction pathregexppath keys sensitive strict if path instanceof regexp return path if arrayisarraypath path pathjoin path path concatstrict replaceg replacewg function slash format key capture optional star keyspush name key optional optional slash slash return optional slash optional slash format capture format optional star replaceg 1 replaceg return new regexp path sensitive ithe important part is the regex on line 7 wg which groups the matched portions of pathname this wayslash the symbol format i do not know what is the purpose of this one explanation needed key the word ie w after the symbol capturea regex written in front of the key should be wrapped in parenthesis ex doptionalthe symbol after the key star the symbol and the callback handler builds a regex from the groups abovenow the question is what is the purpose of format heremy understanding according to the following lineformat capture format and the mentioned regex is if you put a symbol after the slash group and do not specify a match condition the regex wrapped in parenthesis after the key the generated regex matches the rest of path until it gets to a or symbolso whats the pointi am asking this becausei want to extract and use this method in my app and want to fully understand how it works before using it i did not find anything on expressjs documentation about it i am just curious,['javascript'] +435645,android hello world in intellij 12 cannot find androidappactivity class please see below i have a feeling i have got the sdks configured incorrectly but i am not sure how to solve it i tried googling for answers but no one had this exact problemdo i have the wrong java version maybe it seems like the two sdks might be conflicting with each otheri made this project viacreate new projectandroid application moduledefaults and finishedit see screenshot i got it working all i did was create a new project and reselect the android sdk i am still thinking it was because i added too many sdksjdks the first time i think all you need is the android sdk and do not need to add the normal java one too,['android'] +435665,css3 translate out of screen for a number of projects now i have had elements on the page which i want to translate out of the screen area have them fly out of the document in proper code this should be possible just by adding a class to the relevant element after which the css would handle the rest the problem lies in the fact that if for exampleblockhide webkittransformtranslatey10pxis used the element will first of all fly out of the screen unnecessarily far and with an unnecessarily high speed and purely from an aesthetic point of view there is a lot left to be desired theoretically speaking for example a screen with a height of 10px could be introduced one day in the futureupdate the problem why percentages cannot be used is that 100 is relative to the element itself rather than to the parent elementscreen size and containing the element in a fullsized parent would be possible but would create a mess with click events and after a few answers allow me to point out that i am talking about translations not about positionabsolute css3 transitions which are all fine but once you get enough of them they stop being funwhat aesthetically pleasing solutions to allow an element to translate out of a screen in a fixed amount of time can you guys think ofexample code can be found in this jsfiddle demonstrating the basic conceptsee my own answer below for a bit more information,"['javascript', 'html']" +435705,php unlink handling the exception well i have been wondering if i can handle the unlink function properly i dont want the unlink function to throw some nasty error if it is unable to unlink the file may be due to the file not foundi tried something liketry unlinksecretsecrettxt catchexception e print whoops or even leaving it empty so nothing is thisplayed but it is not working i am no expert in php i searched and found this exception handling code somewhere in the web but as i can remember my school days the same was used for java so it should have worked i dont know whats wrong with the codeor can i simply use a ifelse statement likeifunlinkfile leaving here empty must ensure that nothing is thisplayedelse leaving here empty must ensure that nothing is thisplayedbut this code isnt working either where am i doing the mistake what are the other ways to handle it properlycan the errors be hidden by manipulating with the error reporting php production and development environment,['php'] +435717,visual c 2008 express download link dead the programming class i am currently taking uses visual c 2008 and to work from home we have the option of getting the express edition i cannot find the download link anywhere on the website and the microsoft support was absolutely no help i also looked into just using visual c 2010 but i heard there is not much of a chance for compatability to work if anyone has information on where i can get the visual studio 2008 express iso or the c 2008 express download seperately then let me know,['c++'] +435722,matplotlib stops animating after first frame i am trying to animate two subplots each with multiple lines i am using matplotlib and i am using the funcanimation which is used by many of the animation examplesusing animationif i try to animate it i only get the result of the first framewithout using animationif i manually call my update lines function it works finecodebelow is the full code uncommenting the 3 indicated lines in main works but i would like to see it update in realtime hence trying to use the animationimport matplotlibpyplot as pltfrom matplotlibanimation import funcanimationdef make subplots def setup axesaxes for ax in axes axset xbound0 100 bound will change as needed axset ylim0 1 limit would not change automatically def make linesaxes labels a b c lines for ax in axes ax lines for label in labels x y 0 0 line axplotx y labellabel comma for unpacking ax linesappendline x y linesappendax lines return lines fig axes pltsubplots2 1 sharextrue shareytrue lines make linesaxes setup axesaxes return fig axes linesdef make data for i in xrange100 print make data i data dict for label in a b c from random import random datalabel random yield i 1 datadef update linesdata lines print update lines data lines updated lines for ax lines in lines for line x y in ax lines label lineget label xappenddata0 yappenddata1label lineset datax y updated linesappendlinedef main fig axes lines make subplots uncomment these 3 lines and it works new data make data for data in new data update linesdata lines funcanimationfigfig funcupdate lines framesmake data fargslines interval10 blitfalse pltshowif name main main,['python'] +435759,how to cut a part of div i try to give you a broad picture of my problem suppose i have a overlay div on my page with zindex 99 with backgroundcolor rgba05 then i want to remove a part of overlay div for example 100 x 100px in top 50px and left 200pxby removing i mean that exclude a part of overlay div to make that part visible and remove the backgroundcolor from thathow can i do that,['css'] +435772,how can i float elements with different size in a tile the question is simple i have a bunch of elements that are going to make a tile however some of them have a longer height let us say twice as much as the other ones i want all of them to match in a tile just by pure css stylinghere is what i haveand this is what i wanthere is my codedoctype htmlhtmlheadstyle typetextcssdiv boxshadow 0 0 1px black inset width 100px thisplay inlineblockd1d2d4d5d6d8d9 height 100px backgroundcolor yellowd7d3 height 200px backgroundcolor redstyleheadbodydiv idd11divdiv idd22divdiv idd33divdiv idd44divdiv idd55divdiv idd66divdiv idd77divdiv idd88divdiv idd99divbodyhtmland you can try it live on jsbin notesthe content is dynamicthe number of boxes can varyany box can be longer and possibly widerthe width or height of boxes are always a number of units the unit in this example is 50 and some boxes are 50 some others are 100px high but it would be perfect if the problem is solved for any number of units 123 which are 50px 100px 150px,"['html', 'css']" +435797,removing the highlight when touching infowindow adapter i have implemented a custom infowindow which i programmed to thisplay when touching a markerwhen i touch the infowindow it highlights in the default blue color on jelly bean as stated by the google maps v2 api the issue is that i cannot seem to thisable this highlighi have tried addingandroidclickablefalsebut it did not worki also tried implementing the oninfowindowclicklistener and overriding the oninfowindowclick method but this did not work eitherhelp me obiwan kenobi youre my only hope,['android'] +435905,python replace function replace once i need help with a program i am making in pythonassume i wanted to replace every instance of the word steak to ghost just go with it but i also wanted to replace every instance of the word ghost to steak at the same time the following code does not work sthe scary ghost ordered an expensive steak print s ssreplacesteakghost ssreplaceghoststeak print sit prints the scary steak ordered an expensive steakwhat i am trying to get is the scary steak ordered an expensive ghost,['python'] +435918,rvm install ruby 193 missing required packages i am trying to switch from ruby 18 to 193 through rvm rvm install 193but everytime i have a warning missing required packages autoconf automake libtool pkgconfig libyaml readline libxml2 libxslt libksba openssl curlcabundle sqlitei tried with rvm pkg install libyamlbut nothing better everytime i have this warning and it is preventing me from installing rails 3 missing libyaml and openssl anyone already solved that thanks for your helpi am running mac os x 1082,['ruby-on-rails'] +435938,how can i use the output in logcat after a fatal signal 11 to figure out where i am getting the error from in android native code i have one bug to fix that pops up alot its a fatal signal 11 the problem is the program doesnt crash in any of my native code but something else is causing it i have the following from logcat i do not know the proper term for this0310 125014419 flibc 3429 fatal signal 11 sigsegv at 0x0 code10310 125014819 idebug 11778 0310 125014819 idebug 11778 build fingerprint hphp tenderlointenderloin404imm76i330937userreleasekeys0310 125014819 idebug 11778 pid 3429 tid 3702 comrefinedcodehandocr 0310 125014819 idebug 11778 signal 11 sigsegv code 1 segv maperr fault addr 0310 125014819 idebug 11778 r0 004a1e30 r1 33401 r2 004a1e30 r3 0310 125014819 idebug 11778 r4 414b3da8 r5 004b6cb8 r6 07 r7 4e348f800310 125014819 idebug 11778 r8 4e766c10 r9 4e348f78 10 08 fp 4e766c240310 125014819 idebug 11778 ip 2ac56f9c sp 4e766c08 lr 2ac254dd pc 2b10ba64 cpsr 600100100310 125014819 idebug 11778 d0 0 d1 0310 125014819 idebug 11778 d2 0 d3 0310 125014819 idebug 11778 d4 4379044310 d5 437a0442d80310 125014819 idebug 11778 d6 bff921fb5440 d7 442a556b0310 125014819 idebug 11778 d8 4392103d3089705f d9 45a8203c7117060310 125014829 idebug 11778 d10 3f80 d11 3f80ff0310 125014829 idebug 11778 d12 4017ef9a0ff d13 03f80310 125014829 idebug 11778 d14 3fee940d6bb98cc4 d15 3ff0310 125014829 idebug 11778 d16 0 d17 042ff0310 125014829 idebug 11778 d18 3fc549 d19 bf9b6d5dd2eaade70310 125014829 idebug 11778 d20 3ef4e83ec07d9f84 d21 be5ae1fd202f348f0310 125014829 idebug 11778 d22 bc7a6263310 d23 3de5d93a5acfd57c0310 125014829 idebug 11778 d24 ff0 d25 0d8050a9d80310 125014829 idebug 11778 d26 03e14a0018a8a0 d27 02d80702a9da0310 125014829 idebug 11778 d28 0ff0 d29 090a0b0c0d0e0f100310 125014829 idebug 11778 d30 0101 d31 01010310 125014829 idebug 11778 scr 60100310 125014829 idebug 11778 0310 1250149 idebug 11778 00 pc 088a64 systemliblibskiaso znk6skpath7isemptyev0310 1250149 idebug 11778 01 pc 06e4da systemliblibandroid runtimeso0310 125015009 idebug 11778 02 pc 01edb0 systemliblibdvmso dvmplatforminvoke0310 125015009 idebug 11778 03 pc 059050 systemliblibdvmso z16dvmcalljnimethodpkjp6jvaluepk6methodp6thread0310 125015009 idebug 11778 0310 125015009 idebug 11778 code around pc0310 125015009 idebug 11778 2b10ba44 e5903014 e3530 03a01 012f1e 0s0310 125015009 idebug 11778 2b10ba54 e35301 13a0 112f1e e590300c s00310 125015009 idebug 11778 2b10ba64 e5d30 e2701 33a0 e12f1e p30310 125015009 idebug 11778 2b10ba74 e1a03002 e5912008 e92d4010 e15302 0 0310 125015009 idebug 11778 2b10ba84 e1a040 3a04 eddf7a09 edc07a01 zz0310 125015009 idebug 11778 0310 125015009 idebug 11778 code around lr0310 125015009 idebug 11778 2ac254bc ed78f7ca 463a4621 4605466e f7fc4668 xffnffhf0310 125015009 idebug 11778 2ac254cc 4628faa3 bdf0b005 4610b510 ed70f7ca ffp0310 125015009 idebug 11778 2ac254dc bf00bd10 4610b510 f7ca4619 bd10ed70 ffp0310 125015009 idebug 11778 2ac254ec 4610b510 ed70f7ca bf00bd10 4610b510 fpf0310 125015009 idebug 11778 2ac254fc ed70f7ca bf00bd10 2030b570 f7c74615 pp0 f0310 125015009 idebug 11778 0310 125015009 idebug 11778 stack0310 125015009 idebug 11778 4e766bc8 004b5270 heap0310 125015009 idebug 11778 4e766bcc 004a1ac0 heap0310 125015009 idebug 11778 4e766bd0 1d605 0310 125015009 idebug 11778 4e766bd4 2b2e62e3 systemliblibdvmso0310 125015009 idebug 11778 4e766bd8 004b2de0 heap0310 125015009 idebug 11778 4e766bdc 004b6cb8 heap0310 125015009 idebug 11778 4e766be0 004b2de0 heap0310 125015009 idebug 11778 4e766be4 2ac1c5c1 systemliblibandroid runtimeso0310 125015009 idebug 11778 4e766be8 41477d58 devashmemdalviklinearalloc deleted0310 125015009 idebug 11778 4e766bec 004b6cb8 heap0310 125015009 idebug 11778 4e766bf0 04 0310 125015009 idebug 11778 4e766bf4 4e348ee8 0310 125015019 idebug 11778 4e766bf8 2b524910 devashmemdalvikheap deleted0310 125015019 idebug 11778 4e766bfc 2b524910 devashmemdalvikheap deleted0310 125015019 idebug 11778 4e766c00 df0027ad 0310 125015019 idebug 11778 4e766c04 0 0310 125015019 idebug 11778 01 4e766c08 414b3da8 devashmemdalviklinearalloc deleted0310 125015019 idebug 11778 4e766c0c 2b2b0db4 systemliblibdvmsousually when i get this kind of error it is because of some of the native code i wrote messing up like accessing an invalid element of a vector or somethingthe problem usually happens sometimes after one of my native functions has run but not in it so its really hard for me to figure out how to fix it when i dont get a line number of where the problem is happening is there a way i can use this output to get more information on the problem i dont know what the proper term for this output is so i am having a hard time searching for answers if anyone here has experience with this i would really like to be able to use this thankszach,['android'] +435972,get android seekbar value and thisplay it on screen i am trying to get the value of the seek bar whenever it changes and thisplay it underneath i am using the onclick method on my seekbar to call this method public void getnumberview view seekbar seek seekbar findviewbyidridseekbar1 int seekvalue seekgetprogress string x value integertostringseekvalue textview findviewbyidridlevelsettextx,"['java', 'android']" +436027,generate random color with pure css no javascript is it possible to generate random color with pure css and without using javascript it is probably impossible but i am still curious,['css'] +436029,how can i dynamically add bundles after application start has occurred i have an aspnet mvc4 web application that uses style bundling for themes i have a physical themes folder structure like so themes base theme1 theme2 each themes folder has an arbitrary number of less files in it in my bundleconfigregisterbundles method i have some logic that loops through each themes folder and creates a bundle for each the bundling mechanism from systemweboptimization will watch for changes within the files and folders that are in existing bundles and flush the bundles cache which works finewhat i need however is a way for new theme folders ie theme3 to be copied into my themes root folder and the application to recognize those without having to first restart it i have tried creating a dummy bundle that references all files in every foldervar changetracking new stylebundlebundle rootchangetrackingtransformsclearchangetrackingincludedirectorytheme root less truechangetrackingtransformsaddnew lesstransformchangetrackingtransformsaddnew cssminifybundlesaddchangetrackingbut that does not seem to help when i make theme3 it does not trigger another call to bundleconfigregisterbundles i still have to do an iisreset recycle the application pool etc to get the new theme to be recognizedis there any way i can dynamically add bundles after application start has occurred,['asp.net'] +436080,postmessage source iframe i am working on a website with crossdomain iframes that are resized to the correct height using postmessage the only problem i am having is identifying which iframe has which height the way i have currently got it set up is that when one iframe sends its height to the parent all the iframes heights are changedparentvar eventmethod windowaddeventlistener addeventlistener attacheventvar eventer windoweventmethodvar messageevent eventmethod attachevent onmessage messageeventermessageevent functione iframeheightedata falseiframevar updateheight function ifwindowparent windowparentpostmessagewidgetouterheight is there some way to identify which iframe sent the message event,['javascript'] +436104,real time line graph with nvd3js i am trying to create a real time graph using nvd3js which would be updated periodically and with the impression that the data is processed in real time for now i have been able to create a function which would update the graph periodically but i cannot manage to have a smooth transition between states like the line doing a transition to the left here is what i did using nvd3js here the interesting code is d3selectchart svg datumdata transitiondurationduration callchartnow i have been able to produce what i want using d3js but i would prefer to be able to use all the tools provided by nvd3js here is what i would like to produce using nvd3the interesting code for the transition using d3js is function tick update the domains now new date xdomainnow n 2 duration now duration ydomain0 d3maxdata push the accumulated count onto the back and reset the count datapushmathrandom10 count 0 redraw the line svgselectline attrd line attrtransform null slide the xaxis left axistransition durationduration easelinear callxaxis slide the line left pathtransition durationduration easelinear attrtransform translate xnow n 1 duration eachend tick pop the old data point off the front datashift,['javascript'] +436136,how can i use nodejs with windows 7 i am about to became insane looking for it most of the examples shows only how to run it on linux terminal and just the communication with the servercan someone please explain to me how i can use nodejs make it run and load whatever is needed in windows 7and please how can i integrate it with my html5 codei really appreciate your answers,['javascript'] +436153,jsch invalid private key i am running jdk 17 windows 7 using netbeans 72i have generated a ssh private public key pair ssh22048 bits using puttykeygen i do not have any password for private keyi am now trying to connect to one of the host machine using sftp but when i pass private key ppk to set identity code is returning invalid private key error i used same private key in winscp to connect to same host it is working fine kindly help me to resolve the errorhere is my codejsch jsch new jschsession session nulltry jschaddidentitydtempkeyppk session jschgetsessiontiabscp ssiwsupportqvalentcom 22 sessionsetconfigstricthostkeychecking no sessionsetpassword sessionconnect channel channel sessionopenchannelsftp systemoutprintlngetting connected channelconnect systemoutprintlnconnected successfully channelsftp sftpchannel channelsftp channel sftpchannelgetremotefiletxt localfiletxt sftpchannelexit sessionthisconnectcatch jschexception e eprintstacktracecatch sftpexception e eprintstacktrace,['java'] +436195,how to convert jodatime to date of javautildate and vice versa is it possible to do that if yes then how do i do the conversion from jodatime to date and vice versa,['java'] +436207,listview items with rounded corners i am trying to make listview items rectangular shape with rounded corners but whats happening with me only first row comes with rounded corners on upper part rest of the child listview items comes in rectangular shapes with no rounded corners i do not know why this is happeninghere is my listview codeslistview androidididlistviewdoctorwithappointment androidlayout widthmatch parent androidlayout heightwrap content androidlayout marginleft7dp androidlayout marginright7dp androidlayout margintop10dp androidminheight80dp androidbackgrounddrawablecustomshapeduplicate androidcachecolorhintandroidcolortransparent androiddivider4f94cd androiddividerheight10dp androidsmoothscrollbartrue androidlistselectordrawableselector androidscrollbarsnone listviewand here is my customshapeduplicatefile is thisshape xmlnsandroid androidshaperectangle gradient androidstartcolorf androidendcolorf androidangle270 corners androidbottomrightradius10dp androidbottomleftradius10dp androidtopleftradius10dp androidtoprightradius10dp shape and this is the image,['android'] +436209,call grand parent function from child class in multilevel inheritance public class grandparent public void walk public class parent public void walk public class child public void walk here in some cases i want to use walk method of grandparent class now in childwalk i want to use grandparentwalk only in some cases how can i do that since superwalk will always use parentwalknote please note that this is simplified example of a complex scenarionote2 please only tell if there is a standard procedure of doing that i have used a flag in parent class which the child sets if it wants to use the method of grandparent but this sequence becomes very complex,['java'] +436211,how to flatten a referenced object into two jsonnet properties on the referer consider the following classpublic class user public virtual int id getset public virtual string name getset public virtual user superior getsetmy goal is to serialize this as json using newtonsofts jsonnet like so id 101 name mithon superiorid 100 superiorname themanwhy do i want to do this because i want to use the json as my dtos without generating an intermediate layer of dynamic objects generating the dtos should be done dynamically by convention rather than explicitly imho i know some might strongly thisagree with this but thiscussing my approach is besides the point i just want to know if and how it can be donethe challenge is that using jsonpropertyattribute for the superior property will yield only one property as output where i need two if i use a jsonobjectattribute i will get a nested attribute and i would have trouble with the top level user also being flattenedluckily it seems there are enough protected andor public properties and methods in the jsonnet library that i can extend something to get the desired result the question then is which classes and methods should i start with to get where i want to go would deriving from defaultcontractresolver and overriding the getproperties method be good places or should i look elsewhere,['.net'] +436224,kivy button text alignment issue i am trying to develop an email application in kivy basically just as an exercise to learn the ins and outs of the framework i am trying to create the initial window and have reached a bit of a stumbling block the idea is that it will simply thisplay a list of emails in the inbox much like any basic email app on a mobile devicethe problem i am having is that i cannot figure out how to get the text of each list item which is a just a button to align properly using halignleft in my button will make the text align left but only relative to each button it is still centered within each buttonmy actual app is a bit large to post so this is a quick and dirty example i made from a stock kivy example i realize this code is not perfect like i said quick and dirty for examples sake it does work though so as you can see the two rows of text on each button align with each other but they do not all align overall can anyone suggest what i would do to make all the text align at say 10px from the left of each button i did find one relative sounding item on stackoverflow but it did not really answer the question for example it seemed to deal more with using images on buttons i am new to kivy but i have read through the tutorials and documentation as well as searched google extensively so any help would be greatly appreciatedimport kivykivyrequire108from kivyapp import appfrom kivycorewindow import windowfrom kivyuixbutton import buttonfrom kivyuixscrollview import scrollviewfrom kivyuixgridlayout import gridlayoutimport randomclass scrollviewappapp def buildself create a default grid layout with custom widthheight layout gridlayoutcols1 spacing10 size hintnone none widthwindowwidth when we add children to the grid layout its size does not change at all we need to ensure that the height will be the minimum required to contain all the childs otherwise well child outside the bounding box of the childs layoutbindminimum heightlayoutsetterheight add button into that grid for i in range30 btn buttontextstri randomrandom n stri randomrandom size300 40 size hintnone none halignleft layoutadd widgetbtn create a scroll view with a size size of the grid root scrollviewsize hintnone none rootsize windowwidth windowheight rootcenter windowcenter rootadd widgetlayout return rootif name main scrollviewapprun,['python'] +436268,install c service on windows server access denied i created a c service now i want to install that service on windows server 2008 r2i am using the installutil command to install the service i opened the command prompt as an adminthe service should run as a certain user therefore i set the account to user on the service installer when i run the command i get an erroran exception occured during the install phasesystemcomponentmodelwin32exception access deniedhere is the log fileinstalling assembly cservicemyserviceexeaffected parameters are logtoconsole logfile cservicemyserviceinstalog assemblypath cservicemyserviceexerolling back assembly cservicemyserviceexeaffected parameters are logtoconsole logfile cservicemyserviceinstalog assemblypath cservicemyserviceexean exception occurred during the rollback phase of the systemserviceproceserviceprocessinstaller installersystemnullreferenceexception object reference not set to an instance of an objectan exception occurred during the rollback phase of the installation this exception will be ignored and the rollback will continue however the machine might not fully revert to its initial state after the rollback is completehere is what is thisplayed on the command promptbeginning the install phase of the installationsee the contents of the log file for the cservicemyserviceexe assemblys progressthe file is located at cservicemyserviceinstaloginstalling assembly cservicemyserviceexeaffected parameters are logtoconsole logfile cservicemyserviceinstalog assemblypath cservicemyserviceexean exception occurred during the install phasesystemcomponentmodelwin32exception access denied at systemserviceproceserviceprocessinstalleropensecuritypolicy at systemserviceproceserviceprocessinstallerinstallidictionary statesaver at systemconfigurationinstallinstallerinstallidictionary statesaver at systemconfigurationinstallinstallerinstallidictionary statesaver at systemconfigurationinstallassemblyinstallerinstallidictionary savedstate at systemconfigurationinstallinstallerinstallidictionary statesaver at systemconfigurationinstalltransactedinstallerinstallidictionary savedstatethe rollback phase of the installation is beginningsee the contents of the log file for the cservicemyserviceexe assemblys progressthe file is located at cservicemyserviceinstalogrolling back assembly cservicemyserviceexeaffected parameters are logtoconsole logfile cservicemyserviceinstalog assemblypath cservicemyserviceexean exception occurred during the rollback phase of the systemserviceproceserviceprocessinstaller installersystemnullreferenceexception object reference not set to an instance of an objectan exception occurred during the rollback phase of the installation this exception will be ignored and the rollback will continue however the machine might not fully revert to its initial state after the rollback is completethe rollback phase completed successfullythe transacted install has completedthe installation failed and the rollback has been performeddoes somebody know what i need to do to install the service,['c#'] +436274,how to change varchar type to datetime using alter in mysql how can i change varchar type to datetime using alter in mysql,['mysql'] +436285,why does simpledateformat parse incorrect date i have date in string format and i want to parse that into util datevar date 03112013i am parsing this as new simpledateformatmmddyparsedatebut the strange thing is that if i am passing 0308201309 hjhkjhk or 03882013 or 4388201378 it does not throw error it parses itfor this now i have to write regex pattern for checking whetehr input of date is correct or notbut why is it so code scala val date0388201309 hjhkjhkdate javalangstring 0388201309 hjhkjhkscala new simpledateformatmmddyparsedateres5 javautildate mon may 27 0 ist 201309,['java'] +436355,difference in sorting between net 35 and net 40 i have come across a very weird behaviour of the net frameworks when sorting a collectionthis behaviour is different between net 35 and 40 but i think i know why but more importantly and that is my real concern here the behaviour is different accross different machines on the same frameworkcontexti am working on a piece of software that is relying on some third party software springnet in this case but it does not matter and at some point it is sorting a collection that has all its item equal the comparer always return 0 this is not under my control and i would be very fine with it if the behaviour of sorting that list was always consistent it is nothow to reproducecreate a simple project in net 35 and run the code belowwhen compiled in 35 the behaviour seems to be consistent and the collection will be reversed it comes out as three two onenow please change the project target to net 4 not 45 and run it againon my machine it does not reverse the collection anymore one two three but on some other colleagues machine it does three two one we have exactly the same setupcan you please tell me on your machine under 40 which it is reversed or not reversedi am trying to assess whether my setup is correct or notproof of conceptclass program static void main var collection new arraylist one two three it should in any case write one two three consoleoutwritelinebefore sort foreach string item in collection consoleoutwritelinetitem collectionsortnew ordercomparator in net 35 it will write three two one in net 4 it will sometimes write three two one sometimes one two three what is it for you consoleoutwritelineafter sort foreach string item in collection consoleoutwritelinet item consoleoutwritelineend consoleread public class ordercomparator icomparer public virtual int compareobject o1 object o2 return 0 also if you have any idea why this is happening please let me know,"['c#', '.net']" +436363,dynamically loading a typescript class reflection for typescript i would like to be able to instantiate a typescript class where i get the class and constructor details at runtimethe function i would like to write will take in the class name and constructor parametersexport function createinstancemodulename string classname string instanceparameters string return new modulenameclassnameinstancepameters this is the bit i do not know how to do,['javascript'] +436378,androidactionbarstyle requires api level 11 while using the actionbarsherlock in xml atitem nameandroidactionbarstylestylewidgetstyledactionbaritemi got this errorandroidactionbarstyle requires api level 11 current min is 8 errori am using it for back porting my app with actionbar to 22 deviceshow to use them both together item nameactionbarstylestylewidgetstyledactionbaritem item nameandroidactionbarstylestylewidgetstyledactionbaritem,['android'] +436425,make my com assembly call asynchronous i have just earned the privilege to maintain a legacy library coded in c at my current workthis dllexposes methods for a big legacy system made with uniface that has no choice but calling com objectsserves as a link between this legacy system and another systems apiuses winform for its ui in some casesmore visually as i understand the components big legacy system in uniface com c library managed api big edm management systemthe question is one of the methods in this c library takes too long to run and i should make it asynchronousi am used to c but not to com at all i have already done concurrent programming but com seems to add a lot of complexity to it and all my trials so far end in eithera crash with no error message at allmy dll only partially working thisplaying only part of its ui and then closing and still not giving me any error at alli am out of ideas and resources about how to handle threads within a com dll and i would appreciate any hint or helpso far the biggest part of the code i have changed to make my method asynchronous my public method called by the external systempublic int comparedsearchstring application out string errmsg errmsg try actionstring asyncop asynccomparedsearch asyncopbegininvokeapplication null null catch ex return 0private int asynccomparedsearchstring application my actual method doing the work that was the called method beforeany hint or useful resource would be appreciatedthank youupdate 1following answers and clues below especially about the synchronizationcontext and with the help of this example i was able to refactor my code and making it to work but only when called from another window application in c and not through comthe legacy system encounters a quite obscure error when i call the function and does not give any details about the crashupdate 2latest updates in my trials i managed to make the multithreading work when the calls are made from a test project and not from the uniface systemafter multiple trials we tend to think that our legacy system does not support well multithreading in its current config but that is not the point of the question any more here is a exerpt of the code that seems to workstring applicationsynchronizationcontext context my public method called by the external systempublic int comparedsearchstring application out string errmsg thisapplication application context windowsformssynchronizationcontextcurrent thread t new threadnew threadstartasynccomparedsearchandshowdocs tstart errmsg return 0private void asynccomparedsearch any work that as nothing to do with ui contextsendnew sendorpostcallback delegateobject state methods that manage ui somehow nullwe are now considering other solutions than modifying this com assembly like encapsulating this library in a windows service and creating an interface between the system and the service it should be more sustainable,['c#'] +436438,render pdf to single canvas using pdfjs and imagedata i am trying to read an entire pdf document using pdfjs and then render all the pages on a single canvasmy idea render each page onto a canvas and get the imagedata contextgetimagedata clear the canvas do the next page i store all the imagedatas in an array and once all pages are in there i want to put all the imagedatas from the array onto a single canvasvar pdf nullpdfjsthisableworker truevar pages new array prepare some things var canvas documentgetelementbyidcv var context canvasgetcontext2d var scale 15 pdfjsgetdocumenturlthenfunction getpdfhelloworld pdf pdf pdf render all the pages on a single canvas forvar i 1 i pdfnumpages i pdfgetpageithenfunction getpagepage var viewport pagegetviewportscale canvaswidth viewportwidth canvasheight viewportheight pagerendercanvascontext context viewport viewport pagesi1 contextgetimagedata0 0 canvaswidth canvasheight contextclearrect0 0 canvaswidth canvasheight poutprerendered page i now we have all dem pages in pages and need to render em out canvasheight 0 var start 0 forvar i 0 i pageslength i ifcanvaswidth pagesiwidth canvaswidth pagesiwidth canvasheight canvasheight pagesiheight contextputimagedatapagesi 0 start start pagesiheight so from the way i understnad thing this should work rightwhen i run this i end up with the canvas that is big enought to contain all the pages of the pdf but does not show the pdfthank you for helping,['javascript'] +436455,jquery splits huge array into many new callbacks while parsing i stumbled upon a small problemi get back an json response which includes a byte array with 67615 entriesnow well it adds a154156jquery1910039778258679286416 1363006432850181104every 7300 charactersnow when i use the ajax method to parse it how it normaly works it gives me an error because the callbacks invalidate the response syntaxerror missing after element list 18412665140862161942101741jquery17203250109862964784 13639643449so its not valid anymorei use this to parse itajax url url cache false datatype jsonp crossdomain true success functionroot consolelogroot could this be a problem with the asp server giving me the object or is there something wrong with the parsingthanks in advanceedit1 webmethoddescription enablesession truescriptmethodusehttpget true responseformat responseformatjsonpublic borrower getsessionedborrowerheaderref sysmessage amessage if uservalidatedref amessage return null borrowercontrol borrowercontrol new borrowercontrollocalconnectionstringdb webconnectionstringdb statsconnectionstringdb libconnectionstringdb catconnectionstringdb libconnectionstringdb session borrower returnobj borrowercontrolgetsessionedborrowerheaderref amessage borrowercontrolthispose return returnobjif you need more code tell me im not into asp edit2what to dohere is the json answer,"['javascript', 'jquery', 'asp.net']" +436463,how can i set a path for a file to upload if an element is not visible and only reference by an anchor tag with webdriver if the element is of typefile i can usually just to a sendkeys directly to the element and it works beautifullyunfortunately the situation i have now there is a custom button used that has an anchor tag referring to the input elementanchor tag which is a custom button referring to non visible file input element a idimageuploadbutton classcontrol button button hrefcreate channeladdimage dataemberaction151refers to this file input element which is not visible input idimageselectorbutton nameimageselector typefile claselectimagebtn action selectimage onchange targetview action onblur onblur targetapprouterimageselectorview action onfocus onfocus targetviewin this case sendkeys does not work on the anchor tagdriverfindelementbyidimageuploadbutton sendkeysacmyfilebmpaerrororgopenqaseleniumwebdriverexception focuselement execution failed failed to send keys because cannot focus elementnor does sendkeys work the nonvisible file input elementdriverfindelementbyidimageselectorbutton sendkeysacmyfilebmpaerrororgopenqaseleniumelementnotvisibleexception element must be thisplayed to clicki have tried injecting javascript to set the path value on the nonvisible input element a few different ways see below but nothing seems to work any ideas on how i can set this pathnothing happens when i try thisjavascriptexecutor js javascriptexecutor driverjsexecutescriptwindowdocumentgetelementbyidimageselectorbuttonsetattributevaluecmyfilejpg i tried firing a change even first as well and that did not appear to do anything eitherjsexecutescriptvar eldocumentgetelementbyidimageselectorbutton function fireevttype if documentcreateevent var evt documentcreateeventhtmlevents evtinitevent evttype false false elthispatcheventevt else if documentcreateeventobject elfireeventon evttype fireelchange any help or suggestions would be greatly appreciated,['javascript'] +436466,how can i define an enumeration where multiple values map to a single label suppose for the sake of this example that i am trying to parse a file which specifies that two arbitrary bytes in the record represent the day of the week thuslydayofweek 0 monday 1 tuesday 2 wednesday 3 thursday 4 friday 5 saturday 6 sunday 715 reserved for future usei can define an enumeration to map to this field thuslypublic enum daysofweek monday 0 tuesday 1 wednesday 2 thursday 3 friday 4 saturday 5 sunday 6 reservedforfutureusebut how can i define valid values for reservedforfutureuse ideally i would like to do something likepublic enum daysofweek monday 0 tuesday 1 wednesday 2 thursday 3 friday 4 saturday 5 sunday 6 reservedforfutureuse 7891012131415 this problem is only exacerbated with more complicated fields suppose for example that both 7 and 8 in this case map to the same error case or something how can one capture this requirement in a c enumeration,"['c#', '.net']" +436476,avoid grey background on ie 10 anchors links how do you avoid the annoying grey background that ie 10 applies to anchors when you click them,['css'] +436487,passing a pointer of inaccessible private base type to the derived class method this code example would describe the language feature i find nonintuitiveclass a public a class b private apublic b class c public bpublic c void processaa a int main c ccompilation of this code with apple llvm version 42 on mac produces an testcc16 error aclass aa is inaccessibletestcc16 error within this contextreplacing void processaa a with void processaa a would make it build but i do not understand why should i use absolute class name hereis it a language feature that is there to avoid certain kind of errors or is it just a dark c grammar corner like requirement to put space between angle brackets in templates parametrized with other templatesthanks,['c++'] +436495,adding cookie session store back to rails api app i have a railsapi app more or less out of the box but i want to add back cookiebased session store here is what i have doneappcontrollersapplication controllerrb include actioncontrollercookiesconfigapplicationrb configmiddlewareinsert after activerecordquerycache actionthispatchcookies configmiddlewareinsert after actionthispatchcookies actionthispatchsessioncookiestorecreated configinitializerssecret tokenrb namespaceapplicationconfigsecret token tokencreated configinitializerssession storerb namespaceapplicationconfigsession store cookie store key namespace keywhen i inspect the session in a controller it resultsracksessionabstractsessionhash0x3fdadc5daa24 not yet loadedhowever it does appear that data is being written to and usedbut in my browser the cookie itself is being named as session id instead of namespace keyi thought i added back every piece required for cookie based session storage but i appear to be missing something else any ideas,['ruby-on-rails'] +436531,clear input fields on form submit i know this is continuously asked anew and i have checked out different answers and tried different solutions but to no avail in some cases it can be really be a case by case thing depending on how the code has been redactedi would like to simply have the two input fields in my page to clear when i click submit enter unless its a separate event that is for another thread considering i always press enter as opposed to clicking this is a site just meant for my usei have of course a input tag type submit and its working fine but i also already have a specific onsubmit function function onsubmitforme epreventdefault var var1 documentgetelementbyidname var var2 documentgetelementbyidreview arrayonepush namevar1valuereviewvar2value localstoragefilmdatabase jsonstringifyarrayone documentgetelementbyideyedeeinnerhtml p span classname var1value span span classreview var2value spani am guessing its just about putting one line of right code most probably at the end of the block but i just could not figure it out thanks a lot for the help,['javascript'] +436534,update multiple rows with multiple where clauses for each individual row i am trying to update my table like thisupdate mytable set value 1 where game id 1 x 4 y 8set value 2 where game id 1 x 3 y 7set value 3 where game id 2 x 5 y 2i can do a foreach but that will send over 50 separate queries which is very slowthat is why i want it to be combined into 1 big query i do use an id for each row but the combination of game id x and y is what i use to identify the row i need the update batch function from codeigniter described hereupdate batch with codeigniterwas helpful and almost perfect but it only allows for 1 single where clause you cannot as far as i understood and tried enter an array with multiple where clausesi have also checked out this questionmysql update set on the same column but with multiple where clausesbut it only allows for multiple row updates containing only a single different where clause and i need multiple where clauses anwsers can be in simple sql or with the use of php and codeigniter or in a different way i would this problem to be solved in any possible way i can really use the advicehelp d,"['mysql', 'sql']" +436538,custom background for activatedbackgroundindicator on actionbarsherlock does not work i am using actionbarsherlock and i am trying to customize the activatedbackgroundindicator attribute for the row backgroundif i use the latest android sdk without the actionbarsherlock i am able to customize the background creating the following style on resvaluesstylexml and defining it on androidmanifestxml as androidthemestylethemecustom xml version10 encodingutf8resources style namethemecustom parentandroidthemehololightdarkactionbar item nameandroidactivatedbackgroundindicatordrawableactivated backgrounditem styleresourcesthen my resdrawableactivated backgroundxml contains the next code selector xmlnsandroid item androidstate activatedtrue androiddrawablecolorrow activated item androiddrawableandroidcolortransparent selectorfinally the code used to define each row in the listview isxml version10 encodingutf8linearlayout xmlnsandroid androidorientationvertical androidlayout widthfill parent androidlayout heightwrap content androidbackgroundandroidattractivatedbackgroundindicator textview androidididtest row androidlayout widthfill parent androidlayout heightwrap content androidtextstringsample string androidtextappearanceandroidattrtextappearancemedium androidpadding15dplinearlayoutthe result is shown on the screenshoot is a simple application with only a listview with listviewchoice mode single and getlistviewsetitemcheckedposition true when list item clicked the blue color of the standard selected row now is yellow and works perfectlythe problem appears when i want to apply the same customization using the actionbarsherlocknow the style file is the next and the background appears blue instead the custom yellowxml version10 encodingutf8resources style namethemecustom parentthemesherlocklightdarkactionbar item nameactivatedbackgroundindicatordrawableactivated backgrounditem item nameandroidactivatedbackgroundindicatordrawableactivated backgrounditem style style nameactivatedbackgroundindicator item nameandroidbackgroundandroidattractivatedbackgroundindicatoritem styleresourcesi do not know if actionbarsherlock supports the androidactivatedbackgroundindicator feature or if i forgot to implement something needed to be able to change the default colorany ideas,['android'] +436542,nsinputstream stops running sometimes throws exc bad access updated this is the problem in a nutshell in ios i want to read a large file do some processing on it in this particular case encode as base64 string and save to a temp file on the device i set up an nsinputstream to read from a file then in voidstreamnsstream stream handleeventnsstreameventeventcodei am doing most of the work for some reason sometimes i can see the nsinputstream just stops working i know because i have a line nslogstream got event x stream unsignedeventcodein the beginning of voidstreamnsstream stream handleeventnsstreameventeventcode and sometimes i would just see the output stream nscfinputstream 0x1f020b00 got event 2which corresponds to the event nsstreameventhasbytesavailable and then nothing afterwards not event 10 which corresponds to nsstreameventendencountered not an error event nothing and also sometimes i even get a exc bad access exception which i have no idea at the moment how to debug any help would be appreciatedhere is the implementation everything starts when i hit a submit button which triggers ibactionsubmitidsender p spinner startanimating self performselector selectorsenddata withobject nil afterdelay 0 here is senddatavoidsenddata tempfilepath nsfilemanager defaultmanager createfileatpath tempfilepath contentsnil attributesnil self setupstreamsforinputfile selfp mediaurl path outputfile tempfilepath p spinner stopanimating pop back to previous vc selfnavigationcontroller popviewcontrolleranimatedno here is setupstreamsforinputfile called above voidsetupstreamsforinputfilensstring inpath outputfilensstring outpath selfp istream nsinputstream alloc initwithfileatpathinpath p istream setdelegateself p istream scheduleinrunloopnsrunloop currentrunloop formodensdefaultrunloopmode p istream open finally this is where most logic occurs voidstreamnsstream stream handleeventnsstreameventeventcode nslogstream got event x stream unsignedeventcode switcheventcode case nsstreameventhasbytesavailable if stream selfp istream if tempmutabledata tempmutabledata nsmutabledata data if streamdata length0 we want to write to the buffer only when it has been emptied by the output stream unsigned int buffer len 240read in chunks of 240 uint8 t bufbuffer len unsigned int len 0 len p istream readbuf maxlengthbuffer len iflen tempmutabledata appendbytesconst void buf lengthlen nsstring base64encdata base64 encodebase64withdata tempmutabledata streamdata base64encdata datausingencodingnsutf8stringencoding encode the data as base64 string tempfilehandle writedata streamdatawrite the data tempfilehandle seektoendoffile and move to the end tempmutabledata nsmutabledata data reset mutable data buffer streamdata nsdata alloc init release the data buffer break case nsstreameventendencountered stream close stream removefromrunloopnsrunloop currentrunloop formodensdefaultrunloopmode stream nil do some more stuff here break case nsstreameventhasspaceavailable case nsstreameventopencompleted case nsstreameventnone case nsstreameventerroroccurred note when i posted this first i was under a wrong impression the issue had something to do with using gcd as per robs answer below i removed the gcd code and the issue persists,"['ios', 'objective-c']" +436552,get yesterdays date in python dstsafe i have a python script that uses this call to get yesterdays date in ymmdd formatstrdatetoday timedeltadays1it works most of the time but when the script ran this morning at 20130311 035 cdt it returned 20130309 instead of 20130310presumably daylight saving time which started yesterday is to blame i guess the way timedeltadays1 is implemented it subtracted 24 hours and 24 hours before 20130311 035 cdt was 20130309 2335 cst which led to the result of 20130309so whats a good dstsafe way to get yesterdays date in python updateafter bukzor pointed out that my code should have worked properly i went back to the script and determined it was not being used it sets the default value but a wrapper shell script was setting the date explicitly so the bug is in the shell script not the python script,['python'] +436560,call lambda without binding it to an identifier browsing some internet board i encountered this little challenge implement a recursive anonymous function in your favorite languageobviously this is easy using a stdfunctionfunction pointerwhat i am really interested in is if this is possible without binding the lambda to an identifiersomething like ignoring the obvious infinite recursion this,['c++'] +436583,scipymisc module has no attribute imread i am trying to read an image with scipy however it does not accept the scipymiscimread part what could be the cause of this import scipy scipymiscmodule scipymisc from cpython27libsitepackagesscipymisc init pyc scipymiscimreadtesttiftraceback most recent call last file pyshell11 line 1 in module scipymiscimreadtesttifattributeerror module object has no attribute imread,['python'] +436603,using autolayout constraints programmatically i am trying to use autolayout in my ios app programmaticallyi have a simple view controller with this init codeuiview innerview uiview alloc initwithframeselfviewboundsuibutton button1 uibutton buttonwithtypeuibuttontyperoundedrectbutton1 setframecgrectmake50 50 150 50button1 settitlebutton1 forstateuicontrolstatenormaluibutton button2 uibutton buttonwithtypeuibuttontyperoundedrectbutton2 setframecgrectmake250 50 150 50button2 settitlebutton2 forstateuicontrolstatenormalinnerview addconstraintsnslayoutconstraint constraintswithvisualformatbutton1button2button1 optionsnslayoutformatalignallbaseline metrics0 viewsnsdictionaryofvariablebindingsbutton1 button2innerview addsubviewbutton1innerview addsubviewbutton2selfview addsubviewinnerviewbut when i am trying to run this i am getting this errorterminating app due to uncaught exception nsinvalidargumentexception reason unable to parse constraint format unable to interpret character because the related view does not have a superview button1button2button1 whats wrong with itand when i am trying to remove pipes in constraintswithvisualformat i am getting this warningunable to simultaneously satisfy constraintsprobably at least one of the constraints in the following list is one you do not want try this 1 look at each constraint and try to figure out which you do not expect 2 find the code that added the unwanted constraint or constraints and fix it note if youre seeing nsautoresizingmasklayoutconstraints that you do not understand refer to the documentation for the uiview property translatesautoresizingmaskintoconstraints nsautoresizingmasklayoutconstraint0x716be10 h v uiroundedrectbutton0x71631f0midx 325 nsautoresizingmasklayoutconstraint0x7169940 h v huiroundedrectbutton0x715fb80150 nsautoresizingmasklayoutconstraint0x7169860 h v uiroundedrectbutton0x715fb80midx 125 nslayoutconstraint0x7164cd0 uiroundedrectbutton0x71631f0width uiroundedrectbutton0x715fb80width nslayoutconstraint0x7164940 huiroundedrectbutton0x715fb800uiroundedrectbutton0x71631f0will attempt to recover by breaking constraint nslayoutconstraint0x7164940 huiroundedrectbutton0x715fb800uiroundedrectbutton0x71631f0break on objc exception throw to catch this in the debuggerthe methods in the uiconstraintbasedlayoutdebugging category on uiview listed in uikituiviewh may also be helpfuland as result of this my constraints have no effect at allwhat am i doing wrong,['objective-c'] +436650,why does not floor return an integer just now i stumbled upon the fact that the c function floor returns the same type you pass to it be it float double or suchaccording to this reference the function returns a down rounded integral value why is not this an integer,"['c++', 'c']" +436651,is consoletime safe in nodejs i have a little snippet of nodejs code in front of me that looks like thisconsoletimequerytimedoasyncioboundthingfunctionerr results consoletimeendquerytime process the resultsand of course when i run this on my otherwise idle development system i get a nice console message like thisquerytime 564mshowever if i put this into production would not there likely be several async calls in progress simultaneously and each of them will overwrite the previous timer or does node have some sort of magical execution context that gives each thread of execution a separate console timer namespace,['javascript'] +436725,how to check which compiler was used to build python is there a way to tell which compiler was used to build a python install on a specific linux machinei tried using ldd on the python dynamic libraries 1 but i did not manage to understand if it was compiled with gcc or intel compiler1 ldd libpython27so10linuxvdsoso1 0x07f4a5ff0libpthreadso0 lib64libpthreadso0 0x02ab8de8ae0libdlso2 lib64libdlso2 0x02ab8deac90libutilso1 lib64libutilso1 0x02ab8deccd0libmso6 lib64libmso6 0x02ab8deed10libcso6 lib64libcso6 0x02ab8df1540lib64ldlinuxx8664so2 0x03b9a40,['python'] +436729,how come the behavior of drawablestart does not match the android documentation i have created a very basic layoutrelativelayout xmlnsandroid xmlnstools androidlayout widthmatch parent androidlayout heightmatch parent linearlayout androidlayout widthmatch parent androidlayout heightwrap content button androidididbutton1 androidlayout widthmatch parent androidlayout heightwrap content androidtextbutton androiddrawablestartdrawableic launcher linearlayoutrelativelayoutaccording to the documentation for drawablestartthe drawable to be drawn to the start of the texthowever when run on my android 404 phone i instead see thiswhy is there such a large gap between the icon and the text according to this answerwith android 40 api level 14 you can use androiddrawablestart attribute to place a drawable at the start of the textbut this is not the behavior i observe why is not the attribute working,['android'] +436787,how to use a python context manager inside a generator in python should withstatements be used inside a generator to be clear i am not asking about using a decorator to create a context manager from a generator function i am asking whether there is an inherent issue using a withstatement as a context manager inside a generator as it will catch stopiteration and generatorexit exceptions in at least some cases two examples followa good example of the issue is raised by beazleys example page 106 i have modified it to use a with statement so that the files are explicitly closed after the yield in the opener method i have also added two ways that an exception can be thrown while iterating the resultsimport osimport fnmatchdef find filestopdir pattern for path dirname filelist in oswalktopdir for name in filelist if fnmatchfnmatchname pattern yield ospathjoinpathnamedef openerfilenames f none for name in filenames print f before open s f f opennamer with opennamer as f print fname s f d name ffileno yield f print f after yield s fdef catfilelist for if in enumeratefilelist if i 20 cause and exception fwritefoobar for line in f yield linedef greppatternlines for line in lines if pattern in line yield linepylogs find filesvarloglogfiles openerpylogslines catfilespylines greppython linesi 0for line in pylines i 1 if i 10 raise runtimeerroryoure hosedprint counted d linesn iin this example the context manager successfully closes the files in the opener function when an exception is raised i see the trace back from the exception but the generator stops silently if the withstatement catches the exception why does not the generator continuewhen i define my own context managers for use inside a generator i get runtime errors saying that i have ignored a generatorexit for exampleclass cmanagerobject def enter self print enter return self def exit self exctype value tb print exit excptype s value s exctype value return truedef foon for i in xrangen with cmanager as cman cmanval i yield cman case1 for item in foo10 print pass val d itemval case2for item in foo10 print fail val d itemval itemnot an attributethis little demo works fine in case1 with no exceptions raised but fails in case2 where an attribute error is raised here i see a runtimeexception raised because the with statement has caught and ignored a generatorexit exceptioncan someone help clarify the rules for this tricky use case i suspect it is something i am doing or not doing in my exit method i tried adding code to reraise generatorexit but that did not help,['python'] +436830,javascript preloaderprogresspercentage i am having trouble finding any good information on how to make a javascriptor jquery progress bar with text that tells you the percentagei do not want a plug in i just want to know how it works so that i can adapt it to what i need how do you preload images and get a variable for the number of images that are preloaded also how do you change htmlcss andor call a function based on the number of images that are loaded already,"['javascript', 'jquery']" +436838,access objects from another process i am making an xna game where i often test things that cannot be edited without rebuilding the whole game application edit and continue does not work getting to the point where i actually test things can take quite some time because the game needs to load its resourceswhat i would like to do is to be able to load resources to some backing application and access them from the game app somehow eliminating the need to reload game assets most of the time is it possible in net applications or is there some other approach i should know aboutmy xna game relies heavily on texture2d instances specifically a library class with several dictionarystring texture2d objectsi think what i would like to be able to do is to have direct access to those dictionaries in the backing app from within the game app xna games can only be targeted at 32bit platforms and i would like the backing app to be 64bit so it could hold more than 15 gigabyte of resource data if that is possibleunit testing approach or whatever implies not using some of the resources would not work for me in this case since i am developing visual effects and it involves every texture i have,"['c#', '.net']" +436894,how to create the following type of json array using javascript how to create the following type of json array using javascriptxaxis categories jan feb mar apr may jun jul aug sep oct nov dec,['javascript'] +436935,python spliting a list based on a delimiter word i have a list containing various string values i want to split the list whenever i see word the result will be a list of lists which will be the sublists of original list containing exactly one instance of the word i can do this using a loop but is there a more pythonic way to do achieve this example a word b c word dresult a wordbcworddthis is what i have tried but it actually does not achieve what i want since it will put word in a different list that it should be indef split excel cellsdelimiter cell data result temp for cell in cell data if cell delimiter tempappendcell resultappendtemp temp else tempappendcell return result,['python'] +436945,performance issue javatextmessageformatformat vs stringbuilder i want to know in compare of messageformat or stringbuilder classlet say an example i have a string for performance wise which one is fast amongjavatextmessageformatformat or stringbuildertest appendhello string txt javatextmessageformatformattest 0 hello string txt1 new stringbuildertest appendhello i just want to know which one is use in case of best practice or performance wise,['java'] +436989,auto generated javascript jaxrs client i would like to have something generate for me javascript service stubs based on jaxrs annotationsi found something in resteasy but i cannot make it work when using resteasy configured on springmvc it seems it works only if resteasy is configured as servlethowever i would like to have js code generated on build time instead runtimedo you know any solution that may do sometking like this,"['java', 'javascript']" +437040,tables in pdf with horizontal page breaks does someone know a preferably opensource pdf layout engine for java capable of rendering tables with horizontal page breaks horizontal page breaking is at least how the feature is named in birt but to clarify if a table has too many columns to fit across the available page width i want the table to be split horizontally across multiple pages eg for a 10column table the columns 14 to be output on the first page and columns 510 on the second page this should of course also be repeated on the following pages if the table has too many rows to fit vertically on one pageso far it has been quite difficult to search for products i reckon that such a feature may be named differently in other products making it difficult to use aunt google to find a suitable solutionso far i have triedbirt claims to support this but the actual implementation is so buggy that it cannot be used i though it is selfevident for such a functionality that the row height is kept consistent across all pages making it possible to align the rows when placing the pages next to each other birt however calculates the required row height separately for each pagejasper has no supporti also considered apache fop but i do not find any suitable syntax for this in the xslfo specificationitext is generally a little bit too low level for this task anyway making it difficult to layout other parts of the intended pdf documents but does not seem to offer supportsince there seem to be some dozens other reporting or layout engines which may or may not fit and i find it a little bit difficult to guess exactly what to look for i was hoping that someone perhaps already had similar requirements and can provide at least a suggestion in the right direction it is relatively important that the product can be easily integrated in a java server application a native java library would be idealnow to keep the rows aligned across all pages the row heights must be calculated as followsrow1height maxa1height b1height c1height d1heightrow2height maxa2height b2height c2height d2heightwhile birt currently seem to do something likepage1row1height maxa1height b1heightpage2row1height maxc1height d1heightpage1row2height maxa2height b2heightpage2row2height maxc2height d2height,['java'] +437063,how to find out deadlock and prevent it in c i had an interview just 5 minutes back i did not answer 3 questions could someone please help mequestionhow to look for deadlock scenarios in multithreaded application function and prevent it answer i gavei gave definition of deadlock and lock mutex monitor semaphore he told me that these are tools but how to look for a deadlock scenario as because when we use these tools blindly it costs the performance he said please help me understand this,"['c#', 'asp.net', '.net']" +437072,using linqpad with smo i am trying to use the smo for sql server 2008 r2 standard but i am running into an issue whenever i try to dump an objectthe relevant codevoid main var connectionstring serverlocaltrusted connectiontrue server server new servernew serverconnectionnew sqlconnectionconnectionstring serverconnectioncontextconnect serverdump error database database new databaseserver master databaserefresh databasedump error ienumerabletable tables databasetablescasttable tablesdump erroredita work around that i found is to use the dump method with a fixed recursion depth eg dump1 but the exception is at a different level for each object,['c#'] +437189,returning two variables in a c function i would like to return two double variables when calling a function that i have createdaccording to some tutorials which deal with the basics of the c i would be unable to do thatis there a way to do so,['c++'] +437220,php property access and dollar sign i have been stepping up my php game lately coming from javascript i have found the object model to be a little simpler to understandi have run into a few quirks that i wanted some clarifying on that i cannot seem to find in the documentationwhen defining classes in php you can define properties like soclass myclass public myprop myprop static anotherprop anotherpropwith the public variable of myprop we can access it using assuming myclass is referenced in a variable called myclass myclassmyprop without the use of the dollar sign we can only access static variables using so we can access the static variable like myclassanotherprop with a dollar signquestion is why do we have to use dollar sign with and not editthis is code i would assume would work and doesclass sethensclass static public sethensprop this is my propmyclass new sethensclassecho myclasethensprop,['php'] +437226,c is set terminate local to every thread should set terminateget terminate set a different terminate exception processor for several threads in c 2011 or c 2003eg if i have program and sets terminate handler to func 1 then i start 3 threads what are terminate handlers in new threads what if in every thread i will set terminate handler to func 2 in first thread func 3 in second thread and so on n3242 c 2011 draft says nothing about it in handlerfunctions or in supportexceptionexceptionterminateps you may answer for c2011 or for c2003 of for any popular implementation of these standardspps there is fcd comment for this c fcd comment status rev 5 n3249 2011gb 71 18624 18822 18832 the thread safety of stdset new handler stdset unexpected stdset terminate is unspecified making the the functions impossible to use in a thread safe manner the thread safety guarantees for the functions must be specified and new interfaces should be provided to make it possible to query and install handlers in a thread safe way lwg 1365 accepted with modifications see paper n3189,['c++'] +437244,connection between two users i run my own website where people have the ability to have friends this is how i store friendshipsid1 id2 1 2 1 3 2 4basically user id 1 is friends with user id 2 and id 3 and user 2 is friends user id 4what i am trying to get is how for example are 1 and 4 connected currently it is like that1 2 4if it is about between 4 and 3 it would be4 2 1 3the idea is to find as quick link between those two as possiblethe only way i can think about is creating a massive big loop with a lots of loops and stuff like that which probably can be better and more efficient,"['php', 'mysql']" +437254,unboundlocalerror local variable referenced before assignment when reading from file i have also tried searching for the answer but i do not understand the answers to other peoples similar problemstfile openhomepathtofiler def temp skylreq breq for line in tfile data linesplit if absfloatdata0 lreq 01 and absfloatdata1 breq 01 t data2 return tprint temp sky60 60print temp sky10 10i get the following error 737052488traceback most recent call lastfile tskypy line 25 in module print temp sky10 10file tskypy line 22 in temp sky return tunboundlocalerror local variable t referenced before assignmentthe first print statement works correctly but it would not work for the second i have tried making t a global variable but this makes both answers the same please help,['python'] +437310,border thickness transition is there a way to easeinout between 2 border thicknessesmy codenav a borderbottom 1px solid aada4bnav ahover borderbottom 3px solid aada4bthanks very much for the helpsam,['css'] +437316,get thread by name i have a multithreaded application and i assign a unique name to each thread through setname property now i want functionality to get access to the threads directly with their corresponding namesomethings like the following functionpublic thread getthreadbynamestring threadname thread tmp null setthread threadset threadgetallstacktraceskeyset thread threadarray threadsettoarraynew threadthreadsetsize for int i 0 i threadarraylength i if threadarrayigetnameequalsthreadname tmp threadarrayi return tmpthe above function checks all running threads and then returns the desired thread from the set of running threads maybe my desired thread is interrupted then the above function would not work any ideas on how to incorporate that functionality,"['java', 'android']" +437319,how does this line work n1 i need some explaination how this specific line worksi know that this function counts the number of 1s bits but how exactly this line clears the rightmost 1 bit int fint n int c for c 0 and 0 c and and n 1 return ccan some explain it to me briefly or give some proof,['c++'] +437321,changing div content via jquery with another html files content to begin i have spent the last few hours browsing stackoverflow on related topics many of them seemed very similar to the issue i am having there was even a couple that resembled mine almost perfectly however the fixes that worked for them do not seem to be working for me i think it would be best for me to post my code and have others look them over i will try to be as detailed as possiblewhat i am trying to doi have a page setup with links inside lis and when it is clicked it is supposed to pull some html content from another page i made more specifically it is supposed to pull out the html content from a specific div id in that page i am having trouble pulling anything out from it and having it posted to my main pages divmy html part with the navigation menuul idnav main li classnavlinklink hereliulthe div that is supposed to change dynamically on click is labeled as thisdiv idmain content ppdivthe other html file that i pull data from has a div that looks like thisdiv idoneblahbalhblahblahlbhalbhlahdivthe part i am having difficulty with is the javascript code i have tried using load and get and neither seem to be working here is my skeleton codedocumentreadyfunction nav main lionclick function here was my first attempt main content ploadcontentholderhtml one my second attempt using get getcontentholderhtml functiondata main content phtmldata my problem with this is that the main content does not seem to be changing i think the problem is that the load and get attempts are not working they do not seem to be pulling the data out as it is supposed to all these files are on my local drive any help would be greatly appreciated,"['javascript', 'jquery', 'html']" +437336,using htaccess prevent users from accessing resource directories and yet allow the sourcecode access resources apologies if my question is unclear but i am not quite up with the jargon by resource directories i mean my css php scripts images javascript ecti used an htaccess file in my images directory that containeddeny from allto do this though this prevented people from typing wexamplecomimages into their browser and accessing my images directory the images stopped appearing on my websitei assume this is because the htaccess file is even denying my source code from accessing the images how can i let my source code access directories i also have a cron job running a php script every night the cron job also needs to be allowed to access the scripts directoryalso is using htaccess files even the best way to secure a site,['php'] +437340,magento module to change dashboard graph i am following along with this post change the dashboard graph in version 17112 of magento to allow the sales of processing orders to show up on the dashboard graph my files are below and within the right directories as well as showing up as active in configadvanced i have also reindexed refreshed cache and refreshed lifetime statistics i am seeing no errors in the logs can you see what is wrong i have firegento and have enabled logging but that is not working eitheredit the revenue total on the dashboard seems correct but its not reflecting on the timeline graph for example there may be a net 30 terms order of 20 at 10am but it does not show on the time graph bounty for whoever can fix the script below to reflect on the timeline for mecaitlinhavenerdashboardetcconfigxmlxml version10config modules caitlinhavener dashboard version10version caitlinhavener dashboard modules global models caitlinhavener dashboard classcaitlinhavener dashboard modelclass caitlinhavener dashboard reports resource rewrite order collectioncaitlinhavener dashboard model reports resource order collectionorder collection rewrite reports resource models globalconfigcaitlinhavenerdashboardmodelreportsresourceordercollectionphp php show all orders not only the invoiced one class caitlinhavener dashboard model reports resource order collection extends mage reports model resource order collection protected function preparesummaryliverange customstart customend isfilter 0 thissetmaintablesalesorder adapter thisgetconnection reset all columns because result will group only by created at field thisgetselectresetzend db selectcolumns expression sprintfs s s s s s adaptergetifnullsqlmain tablebase total invoiced 0 adaptergetifnullsqlmain tablebase tax invoiced 0 adaptergetifnullsqlmain tablebase shipping invoiced 0 adaptergetifnullsqlmain tablebase total refunded 0 adaptergetifnullsqlmain tablebase tax refunded 0 adaptergetifnullsqlmain tablebase shipping refunded 0 expression sprintfs s s s s s adaptergetifnullsqlmain tablebase total invoiced main tablebase grand total adaptergetifnullsqlmain tablebase tax invoiced main tablebase tax amount adaptergetifnullsqlmain tablebase shipping invoiced main tablebase shipping amount adaptergetifnullsqlmain tablebase total refunded 0 adaptergetifnullsqlmain tablebase tax refunded 0 adaptergetifnullsqlmain tablebase shipping refunded 0 if isfilter 0 thisgetselectcolumnsarray revenue new zend db expr sprintfsums s expression adaptergetifnullsqlmain tablebase to global rate 0 else thisgetselectcolumnsarray revenue new zend db exprsprintfsums expression daterange thisgetdaterangerange customstart customend tzrangeoffsetexpression this gettzrangeoffsetexpression range created at daterangefrom daterangeto thisgetselect columnsarray quantity countmain tableentity id range tzrangeoffsetexpression bof modification wheremain tablestate not in array mage sales model orderstate pending payment mage sales model orderstate new eof modification orderrange zend db selectsql asc grouptzrangeoffsetexpression thisaddfieldtofiltercreated at daterange return this protected function calculatetotalsliveisfilter 0 thissetmaintablesalesorder thisremoveallfieldsfromselect adapter thisgetconnection basetotalinvoiced adaptergetifnullsqlmain tablebase grand total 0 basetotalrefunded adaptergetifnullsqlmain tablebase thiscount refunded 0 basetaxinvoiced adaptergetifnullsqlmain tablebase tax amount 0 basetaxrefunded adaptergetifnullsqlmain tablebase tax refunded 0 baseshippinginvoiced adaptergetifnullsqlmain tablebase shipping amount 0 baseshippingrefunded adaptergetifnullsqlmain tablebase shipping refunded 0 baseshippingrefunded adaptergetifnullsqlmain tablebase shipping refunded 0 basetotalinvoiced adaptergetifnullsqlmain tablebase total invoiced main tablebase grand total this will check if there is no invoice it will calculate based on the grand totals so when you generate and invoice you will have no issues with the numbers also basetotalrefunded adaptergetifnullsqlmain tablebase total refunded 0basetaxinvoiced adaptergetifnullsqlmain tablebase tax invoiced main tablebase tax amount same here for taxesbasetaxrefunded adaptergetifnullsqlmain tablebase tax refunded 0baseshippinginvoiced adaptergetifnullsqlmain tablebase shipping invoiced main tablebase shipping amount same here for shipping baseshippingrefunded adaptergetifnullsqlmain tablebase shipping refunded 0 revenueexp sprintfs s s s s s basetotalinvoiced basetaxinvoiced baseshippinginvoiced basetotalrefunded basetaxrefunded baseshippingrefunded taxexp sprintfs s basetaxinvoiced basetaxrefunded shippingexp sprintfs s baseshippinginvoiced baseshippingrefunded if isfilter 0 rateexp adaptergetifnullsqlmain tablebase to global rate 0 thisgetselectcolumns array revenue new zend db exprsprintfsums s revenueexp rateexp tax new zend db exprsprintfsums s taxexp rateexp shipping new zend db exprsprintfsums s shippingexp rateexp else thisgetselectcolumns array revenue new zend db exprsprintfsums revenueexp tax new zend db exprsprintfsums taxexp shipping new zend db exprsprintfsums shippingexp thisgetselectcolumnsarray quantity countmain tableentity id wheremain tablestate not in array mage sales model orderstate pending payment mage sales model orderstate new return this,['php'] +437351,restsharp restrequestaddbody not using newtonjson attributes var obj new myobjecti am having an issue getting restsharp restrequestaddbodyobj to serialize the object correctlyclass myobject jsonpropertypropertynamea public agetset jsonpropertypropertynameb public bgetsetproblem is the addbody serializer is not taking into account my jsonproperty attributes and i can seem to figure out how to set the serializer on the restrequest or the restclient,['c#'] +437362,how can i subtract these lists faster i want to subtract two arraylists so i can have the child that are not in the other list i do it this wayremoveidsarraylistinteger storedidscloneremoveidsremovealldownloadedidsdownloadidsarraylistinteger downloadedidsclonedownloadidsremoveallstoredidsthe problem is that both lists contain 50childs and it takes almost 4 seconds on my androidphoneis there a fast way to do thisis using sets fasteri dont have duplicate values in the listsi develop an android app,"['java', 'android']" +437363,how do you convert a razor view to a string i would like to use my razor view as some kind of template for sending emailsso i would like to save my template in a view read it into controller as a string do some necessary replacements and then send iti have solution that works my template is hosted somewhere as an html page but i would like to put it into my application ie in my view i do not know how to read a view as a string in my controller,"['c#', '.net']" +437475,why is jar bundler gone in mac os x mountain lion 1082 there was a application from apple called jar bundler which got thistributed by apple with xcode in the pastthe purpose of jar bundler was to create mac os x application bundles app directories for java applications until version 6 16x for mac os x user convenienceas of now you can still get jdk 160 43 from apple aka java for os x 2013002 developer package mar 4 2013 for the current mac os x mountain lion 1082 via but you cannot get jar bundleri am using an up to date mac os x 1082 and up to date xcode 46 4h127 with all command line tools installed after all research i did i would expect it hereusrsharejavatoolsjar bundlerappbut there is not any jar bundler even a global search sudo find name jar bundlerapp did not really find jar bundlerso my question is what is the last known xcode version coming with jar bundlernote i know there are other ways to achieve what jar bundler is doing here like for example using mac os x jarbundler ant task or build the whole application package by hand but thats not the question,['java'] +437482,model binding to a list mvc 4 is there a pattern to bind an ilist of items to the view i seem to be having issues with the httppost i know phil haack wrote a nice article but it is dated and he said they might have a fix with mvc 4,['c#'] +437493,how to selectively import module in python i have several different modules and i need to import one of them depending on different situations for exampleif check situation 1 import helper 1 as helperelif check situation 2 import helper 2 as helperelif else import helper 0 as helperthese helpers contain same dictionaries dict01 dict02 dict03but have different values to be called in different situationsbut this has some problemsimport sentences are all written in the top of a file but check situation function here needs prerequisites so that it is now far from topmore than 1 file needs this helper module so it is hard and ugly to use this kind of importso how to rearrange these helpers,['python'] +437504,twitter api applicationonly authentication with tweetsharp i am trying to retrieve public tweets from a serverside application using applicationonly authentication no user contextthe following code works finevar service new twitterserviceconsumer key consumer secretserviceauthenticatewithaccess token access token secret var options new listtweetsonusertimelineoptions screenname billgates foreach var tweet in servicelisttweetsonusertimelineoptions consolewritelinetweettexthowever i gather from this diagram that it should not be necessary to provide the access tokensecrethowever when i remove the call to authenticatewith listtweetsonusertimeline returns nullit is a limitation of the library if not how can i do iteditaas far as i can tell this calls the get statusesuser timeline method that should support applicationonly authentication as per the documentationapi methods that support this form of authentication will contain two rate limits in their documentation one that is per user for applicationuser authentication and the other is per app for this form of applicationonly authenticationthe get statusesuser timeline method has these 2 limits shown in its documentation,['c#'] +437512,how do i call a getter or setter in c i understand how to create a getters and setterspublic myclass public int myval get set more stuffbut i do not understand how to call it later onpublic myotherclass public myotherclass myclass localmyclass new myclass localmyclaset 42 intelisense does not seem to give any obvious options after i enter the period how should i set the value of myval in localmyclass,['c#'] +437522,uiimagepickercontroller record video with landscape orientation how can we force uiimagepickercontroller controller to record video only in landscape modei know that this class should be used for portrait recording but i need to have it in landscapehave found several similar questions but there is not any solution which works for me ios 61for example observation of device orientation does not work for me this answer if i implement uiimagepickercontroller category like the following import uiimagepickercontrollernonrotatinghimplementation uiimagepickercontroller nonrotating boolshouldautorotate return yesnsuintegersupportedinterfaceorientations return uiinterfaceorientationmasklandscape uiinterfaceorientationpreferredinterfaceorientationforpresentation return uiinterfaceorientationlandscaperightendit almost works but i see some strange behavior of some controls and wrong video orientation during recording the result video is ok1 start cancel and recording button in the right positions but other controls in wrong and video is rotated2 recording timer and video are wrong 3 recording finished all good and the result video is rightdo you have any ideasupdate i need to lock the screen in landscape orientation during the recording process,"['iphone', 'ios', 'objective-c']" +437523,while inserting multiple rows what does the statement select 1 from dual do while inserting multiple rows into a table using the following style insert allinto ghazal current ghazalnamerating valuesajab apna haal hota jo visaaleyaar hota5into ghazal current ghazalnamerating valuesapne hothon par sajana chahta hun4into ghazal current ghazalnamerating valuesshaam se aankh mein nami si hai4into ghazal current ghazalnamerating valuestumhe yaad ho ke na yaad ho3select 1 from dualwhat does the statement select 1 from dual mean what is it here for,['sql'] +437524,scapy send function without output does anyone know how to send a packet using scapy and not receive any outputthis is the command sendpacketifaceeth0 this is the output sent 1 packetsi am trying to get it not to print the packet count line at all,['python'] +437604,bluetooth socket freeze phone i am developing an application for android this app should communicate with a bluetooth bt device sending some bytes i have a problem with debuggingrunning this app on my device samsung galaxy mini when i create a bt socket and stop debugging phone freeze and i have to restart it by getting out the battery in case of running this app from eclipse everything is ok but when i try to run it again phone freeze and app is not installed if i try to unninstall this app manualy before second run phone freeze again here is a problematic codeprivate final bluetoothdevice mmdeviceprivate uuid uuidpublic connectionthreadbluetoothdevice device logdtag create connectionthread uuid uuidfromstring0110101080805f9b34fb bluetoothsocket tmp null mmdevice device try tmp mmdevicecreaterfcommsockettoservicerecorduuid catch ioexception e mmsocket tmp socketconnected truethis is a constructor of thread when i comment the line tmp mmdevicecreaterfcommsockettoservicerecorduuidthe phone doesna t freeze so problem is with creating socket not connecting restarting phone after each debugging or running is pretty annoying and i have to do a lot of work yetif i run this app from a phone thisconnected from eclipse it works without any problems any ideas where could be a problem or how to fix it thank you,"['java', 'android']" +437622,ignoring a route in aspnet mvc i am just learning to work with routing in aspnet mvc and am trying to understand the ignoreroute methodi am trying to prevent users from accessing contentfilenamehtml i have placed this as the first call in my registerroutes method here is my codepublic static void registerroutesroutecollection routes routesignoreroutecontentfilenamehtml routesignorerouteresourceaxdpathinfo routesmaproutemyroute controlleractionidcatchall new controller home action index id urlparameteroptional new controller action indexabout new urlsandroutesaditionalcontrollers routesmaproutemyroute2 controlleractionidcatchall new controller home action index id urlparameteroptional new controller action indexabout new urlsandroutescontrollers routesmaprouteshopschema2 shopoldaction new controller home action index routesmaprouteshopschema shopaction new controller home routesmaproute xcontrolleraction routesmaproute name url controlleraction defaults new controller home action index if i try to access a link like localhost53907contentstatichtml it should not allow me to thisplay the file from what i understand so far but it does thisplay itwhat am i doing wrong,['c#'] +437683,scrapy define items dynamically as i started to learn scrapy i have come accross a requirement to dynamically build the item attributes i am just scraping a webpage which has a table structure and i wanted to form the item and field attributes while crawling i have gone through this example scrapy scraping data without having to explicitly define each field to be scraped but could not make much of it should i be writing an item pipleline to capture the info dynamically i have also looked at item loader function but if anyone can explain in detail it will be really helpful,['python'] +437698,styling the arrow on bootstrap tooltips i am trying to style tootltips usingtooltipinnerbut i am having troubles cause i cannot find how to style tooltip small arrowas shown on screenshot the arrow of the tooltip is black i want to add new color on thatany suggestion,['css'] +437756,how to prevent interface builder from adding 20pt padding around subview content see that 20px pts rather of padding ib does it automatically in two cases when you hit cmd to autosize the superview to fit subview contents and when you choose editor embed in uiview uiscrollview etc the later is especially annoying as it takes what should be a one step time saver and turns it into a repositioning hassle that is only marginally better than doing it manually and losing the relative positioning of all the subviews when you drag them into a different place in the hierarchy also with the embed in option ib shifts the positioning of the new superview wrapper by 20 20 as if that makes it betteram i missing something here is there a way to prevent this padding,['ios'] +437759,how to count time elapsed for a method with an utility class i am writing a very simple utility class with the aim to measure the time executed for any method passed in of any typein my case membershipvalidateusermodelusername modelpassword return bool so i get an exceptioni would like if would be possible write a utililty class of this type an a sample of code on how to fix itdoes it make sense use dynamic in stead of actiontracinglogmembershipvalidateusermodelusername modelpassword membershipvalidateuserpublic static class tracing public static void logaction action string message default details for the log string ssource trace string slog application create the log if eventlogsourceexistsource eventlogcreateeventsourcessource slog measure time elapsed for an action stopwatch stopwatch stopwatchstartnew action stopwatchstop timespan timeelapsed stopwatchelapsed write the log eventlogwriteentryssource timeelapsed timeelapsed tostring message eventlogentrytypewarning 234,"['c#', 'asp.net', '.net']" +437791,delay event handling until events have been fired in c whats the best way to delay handling of all known events until an entity has been fully modifiedsay for example that an entity myentity has the properties id name and description public class myentity public int32 id get set public string name get set public string description get set when modifying each of these properties an event is fired for each modificationsometimes the id is the only property modified and sometimes all properties are modified i want the registered listeners of the modification event to wait until all properties being modified in the batch have been modifiedwhat is the best way to accomplish thisin my head something similar to the unitofworkpattern where it is possible to wrap a using statement around the method call in the top level of the call stack but have no clue how to implement such a thingeditas a clarification listeners are spread out through the application and are executing in other threads another actor sets for example the name it must call the myentityname property to set the value due to the design the modification of the name property can trigger other properties to change thus the need for listeners to know that the modification of properties have been completed,['c#'] +437820,android dex unexpected toplevel exception already added my app depends on a library project this library project depends on the android compatibility package v4 i have not exported the library projects dependency in my own project i have added acl v13 as a dependency but when compiling i get the error that essentially there is a duplicate dependency i thought not exporting the library projects dependency would resolve this issue but it is nothow can i resolve thiseditalso according to android tools docs special case for androidsupportv4jar and androidsupportv13jarwe make a special case for these two libraries because v13 contains a full version of v4 inside if both are found then only v13 will be usedso it should just work,['android'] +437840,linq to sql sort query by arbitrary propertycolumn name i have a largermore complex problem but for simplicity sake let us consider the followinglet us say that i have table in the sql database called product having two columns id int primary key and name varcharstring i also have a simple linq datacontexti have a query constructed and handed to amya function let us say it is something like though it may be a bit more complexiqueryableproduct query from p in dbproducts select ponce my method gets this query passed in as a parameter it has to change the sort order egiqueryableproduct sortedquery queryorderbyx xnamei would like to make this more generic ie to specify the field to sort on normally i can do a switch statement that takes a string however i would like to know if there is a way to pass the parameter directly i intend to extend this to other database tables so these switch statements would get tedious i was trying something like iqueryableproduct sortedquery queryorderbyx typeofproductgetpropertyanameabut this does not work i also want to ensure that the linq to sql is maintained ie the sort to be done on the sql server hence if i debug i should get a sql query from this linq querythank you in advance for your help,['c#'] +437876,how to convert json string with dynamic fields to object i have the followed snipets of json string networks tech11 id 1 name iden tech12 id 2 name evdo b i use some methods to convert this string to object private static gson mgson new gson public static webobjectresponse convertjsontoobjectstring jsonstring webobjectresponse webobjectresponse null ifjsonstring null jsonstringlength 1 webobjectresponse mgsonfromjsonjsonstring webobjectresponseclass return webobjectresponsewhere webobjectresponse is class that should represent above mentioned stringits not complicated if i get static fieldsbut in my case the values have different names tech11 tech12 i can use serializedname but its works in specific cases like convert class to class as you see networks object defined as list of tech objects but with different postfix public class webobjectresponse private datainfolist networks null this is static implementation i defined 2 values tech11 and tech12 but next response might be techxxpublic class datainfolist private datainfo tech11 null private datainfo tech12 nullpublic class datainfo private string id null private string name nullwhat is the good way to convert current json string to object where list of elements are objects too and have different namesthank you,['java'] +437942,laravel 4 how do i create a nonprimary auto incrementing column with migrations i am currently working on a laravel 4 project consisting of a master server and many clients the clients create data and send this to the master server to avoid conflicts i am using uuid v4 as the primary keyhowever once the data is created on the server i want to assign a unique autoincrementing integer so it is easier for users to identify the data for example instead of speaking about item 5a8e896d3ab448d29d39faeb5227f012 a user can speak about item 24567to keep my app managable i am using migrations my current migration for this table looks like thispublic function up schematableitems functiontable tablecreate tablestringidprimary id for the purpose of keeping the orm working this field stores the uuid tableintegernumber true the human readable item number the second parameter is true for autoincrement tabletextotherdata tabletimestamps the problem is that laravel automagically creates a primary key when defining autoincrement and so the migration ends up failing because there are two primary keysexception sqlstate420 syntax error or access violation 1068 multiple primary key defined sql alter table items add primary key items id primaryid bindings array is there any way to have a table with a primary key and a seperate autoincrementing field using laravel 4 migrations,"['php', 'mysql']" +437961,angular routing without changing location chrome packaged apps have a rather strict content security policy one result of this is that manipulating the location like clicking on a link results incannot open samewindow link to chromeextensionlkjasdfjklbdskjasdfjkhfdshjksadderphtml try target blank target blank will open the link in chrome which is not what i want can angularjs routing work in such a lockeddown environmentthey docs give an example of an angular app but conspicuously does not use routingupdatehere is the link that when clicked gives the error a classwalruslink nghrefpaystubswalrusidwalrus ida,['javascript'] +437970,in python is it possible to escape newline characters when printing a string i want the newline n to show up explicitly when printing a string retrieved from elsewhere so if the string is abcndef i do not want this to happen printlineabcdefbut instead this printlineabcndefis there a way to modify print or modify the argument or maybe another function entirely to accomplish this,['python'] +437983,chrome showing canceled on successful file download 200 status not sure if this is an actual problem or not but i am writing a file out in aspnet and even though the file always successfully goes through in chromes developer tools network tab i always see the line in red marked canceledi have tried lots of ways of doing this for simplicity i am trying this with a simple text file but it is true for pdf and other file types as wellwebforms i have tried it with lots of combinations of the followingresponseclear andorneitherresponseclearheaders with and without thisresponsebuffer trueresponsecharset orneitherresponsecharset utf8 applicationpdf for pdf also tried applicationoctetstreamresponsecontenttype textplain with and without thisresponseaddheadercontentlength byteslengthtostringresponseaddheadercontentthisposition attachment filename1txt bytes is the utf8 bytes for a string or the pdf contentsnew memorystreambyteswritetoresponseoutputstream orresponsewrite12345 any combination of the following 3 or none at allresponseflushresponsecloseresponseendmvc 2 and 3 have not tried 4byte filecontents encodingutf8getbytes12345return filefilecontents textplain 1txt orreturn filectemp1txt textplain 1txtit is always the same the file goes through just fine but dev tools shows me thisi am thinking of just ignoring it and moving on with life but the red just bothers me any idea how i can deal with that,['asp.net'] +438005,mvc4 bundles returns 404 i have a project that works with bundling when you run it from within visual studio however after you do a deployment the bundling handler never seems to pick up the route it ends up going to the static file handler instead which returns a 404 responseany ideas i see the optimization assembly in the bin of the website under iis it is using the 40 app pool and integrated modei am wondering if anyone has any ideas or suggestionsthanks update based on questions vs2012targetframework45i also added some code into the view to show which modules were loaded and i can see the bundle module listed there bundleconfig is the default provided when using the internet application mvc4 project templatethe site is being deployed into the root it is odd as when i set enableoptimizations true due to running in debug mode via visual studio f5 it works perfect i can navigate to contentcss and it spits out the combined css i deploy it over and everything else works but bundling,['c#'] +438018,transforming a boostgeometry polygon into an stl object how do i get a boostgeometry polygon into an stl objecti am sure this must be simple because i cannot find examples anywhere in the documentation yet i have spent about 4 full work days trying to do this tiny thing i am new to c long time r programer but these small data conversion things are driving me insane yes there is a question whose title is much like mine getting the coordinates of points from a boost geometry polygonbut the code is so complex and the poster kept changed it so many times that i cannot make heads or tails of it nor can i imagine that other c newbies will be able tothis is a simple example that should translate to some of the other boostgeometry data types so hopefully anyone can follow it include iostream include boostgeometryhpp include boostgeometrygeometriespolygonhpp include boostgeometrygeometriesadaptedboost tuplehpp boost geometry register boost tuple cscscartesian one thing i tried is a function to use with for each point so i set that up first template typename point void get coordinatespoint const p using boostgeometryget stdcout get0p get1p stdendl int main typedef boosttupledouble double point typedef boostgeometrymodelpolygonpoint polygon polygon poly boostgeometryread wktpolygon20 13 24 17 28 18 34 12 37 16 34 20 41 30 53 26 54 12 49 08 29 07 20 13 poly polygon hull boostgeometryconvex hullpoly hull now i know i can dsv and print to the screen like this using boostgeometrydsv stdcout hull dsvhull stdendl andor i can use my function with for each point boostgeometryfor each pointhull get coordinatespointreturn 0how do i get these coordinates into an stl container i would prefer two stdvector one for x and one for y but anything will do,['c++'] +438046,is there a c equivalent to c stdpartial sort i am trying to implement a paging algorithm for a dataset sortable via many criteria unfortunately while some of those criteria can be implemented at the database level some must be done at the app level we have to integrate with another data source we have a paging actually infinite scroll requirement and are looking for a way to minimize the pain of sorting the entire dataset at the app level with every paging callwhat is the best way to do a partial sort only sorting the part of the list that absolutely needs to be sorted is there an equivalent to cs stdpartial sort function available in the net libraries how should i go about solving this problemedit heres an example of what i am going forlet us say i need to get elements 2140 of a 10 element set according to some sorting criteria in order to speed up the sort and since i have to go through the whole dataset every time anyway this is a web service over http which is stateless i do not need the whole dataset ordered i only need elements 2140 to be correctly ordered it is sufficient to create 3 partitions elements 120 unsorted but all less than element 21 elements 2140 sorted and elements 4110 unsorted but all greater than element 40,['c#'] +438059,how to silently uninstall python 27 on windows does anyone know how to silently uninstall python 27 ie uninstall it unattended with no need for user interaction i need to do it as part of an uninstallation script that installs a bunch of software silently i have tried running msiexec with the x and qn flags on the msi file that was originally installed but it fails it just throws up the general help message implying that i am using invalid optionsi have done a google search and can find help for earlier versions they can be uninstalled silently by running the unwiseexe that is installed with them with the right options but 27 does not seem to include an unwiseexe so i cannot do thatdoes anyone know how to do thisedit the answer turned out to be embarrassingly simple those were the correct commandline options all along it is just that the order matters the correct command wasmsiexec x python273amd64msi qnthe important thing was to have the qn option after the msi file,['python'] +438068,play html5 video when scrolled to is there anyway to autoplay a html5 video only when the user has the video or a certain percentage of the video in the browser viewport,"['javascript', 'jquery']" +438083,what should be the viewmodel members visibility i have came across an interesting issue for which i have found no explanation yetgiven the very simple mvvm wpf application below why is the list bound to the combo box only if its visibility in the viewmodel is set to public changing the testlist visibility to internal raises no error or warning at compile time but leaves the combo box empty at run timequoting the official documentation internal types or members are accessible only within files in the same assemblyand this issue is happening despite the fact that the view and the viewmodel are defined in the same assemblyhere is how the code looks likemodelclass testmodel internal liststring musketeers get private set public testmodel musketeers new liststring athos porthos aramis viewwindow xclasstestwpfapplicationmainwindow xmlns xmlnsx grid combobox width250 height25 itemssourcebinding testlist gridwindowviewmodelclass testviewmodel inotifypropertychanged testmodel mymodel new testmodel public liststring testlist get return mymodelmusketeers inotifypropertychanged members are below,['c#'] +438149,passing argument 1 thiscards qualifiers from pointer target type my main function is as followsint mainint argc char const argv huffencargv1 return 0the compiler returns the warning huffencc76 warning passing argument 1 of ahuffenca thiscards qualifiers from pointer target typefor reference huffenc takes a char input and the function is executed with the sample input senselessness via huffenc senselessnesswhat could this warning mean,['c'] +438166,convert vbscript to javascript busy debugging a strange issue relating to the way some flash content communicates a users progress from a scorm module back to moodleon ie 6 7 8 9 chrome and firefox everything works fine on ie 10 progress tracking from the flash module is not reaching the serverin the scorm launcher an event handler is created using the following ancient codescript languagevbscripton error resume nextsub preloader fscommandbyval command byval args call preloader dofscommandcommand argsend subscriptdebugging on chrome i can see that the function is called as expected attempting to debug in ie 10 fails as the code is never called how would i translate this code to javascript trying to remove the vbscript as it appears to be part of the problem i tried the following code without succescript function preloader fscommand command args preloader dofscommandcommand args scriptpreloader dofscommand is defined elsewhere in code and is called just fine on chromefirefoxetc but not on ie 10update seems that part of the problem is related to ie 10 no longer supporting fscommand in standards mode question now becomes what would be a suitable workaround which does not require the flashscorm content to change,['javascript'] +438172,how to calculate with imaginary numbers in javascript recently i am trying to calculate using some equations that involve the imaginary number i in them however unlike e or i there is not any methods or native functions that will return i a quick search in google did not get me any answer any ideas on how to achieve itfunction imaginary return rational this imaginary 2i magic code that does this numberprototypeimaginary imaginary,['javascript'] +438265,playing video using mediaplayer class i am trying to make use of mediaplayer class for playing a video file the problem is video is not getting thisplayed at all though i can hear the sound in the video playingfollowing is the code of activitypublic class mainactivity extends activity implements onclicklistener private surfaceview surfaceviewprivate button btnplayoverrideprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main init addlistenerprivate void init todo autogenerated method stub surfaceview surfaceview findviewbyidridsurfaceview1 btnplay button findviewbyidridbtnplayprivate void addlistener todo autogenerated method stub btnplaysetonclicklistenerthismediaplayer mediaplayer nulloverridepublic void onclickview v todo autogenerated method stub switch vgetid case ridbtnplay try if mediaplayer null mediaplayerreset mediaplayerrelease else getwindowsetformatpixelformatunknown mediaplayer mediaplayer mediaplayercreatethis rrawwildlife surfaceholder surfaceholder surfaceviewgetholder surfaceholdersetfixedsize176 144 surfaceholdersettypesurfaceholdersurface type push buffers mediaplayersetthisplaysurfaceholder mediaplayerstart catch exception e toastmaketextgetapplicationcontext egetmessage toastlength longshow break default break following is the code of layout xmlrelativelayout xmlnsandroidxmlnstoolsandroidlayout widthmatch parentandroidlayout heightmatch parentandroidpaddingbottomdimenactivity vertical marginandroidpaddingleftdimenactivity horizontal marginandroidpaddingrightdimenactivity horizontal marginandroidpaddingtopdimenactivity vertical margintoolscontextmainactivity surfaceview androidididsurfaceview1 androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentbottomtrue androidlayout alignparentlefttrue androidlayout alignparentrighttrue androidlayout alignparenttoptrue button androidididbtnplay styleandroidattrbuttonstylesmall androidlayout widthwrap content androidlayout heightwrap content androidlayout alignrightidsurfaceview1 androidlayout aligntopidsurfaceview1 androidtextstringplay relativelayoutplease tell me what needs to be donethanks in advance,['android'] +438274,automatic spell checker for xcode is there any spell checker or plugin for xcode that will automatically spell check all my strings egselflabeltext spell check this,['ios'] +438294,get each selected value using chosen jquery plugin i am using chosen multiple select what i want to do is that if user selects any option i want that value and then i will do some functionality depending on that valuein chosen without multiple select i can get selected value by using foll codeselectidchosenchangefunction selectedvalue thisfindoptionselectedvalbut in multiple select i get the first selected value again and againcan anybody help me by finding the current selected value in multiple select element,"['javascript', 'jquery']" +438307,jquery not finding elements inside of results from jqueryparsehtml i am writing tests with qunit and using ajax to pull in html for some of the tests from the the dev site running on my localadd elements functionlocation selector ajaxlocation async falsedonefunctiondata storels selector parsehtmldata storelsappendtobody using this function at a certain location i get the following data passed to my done callback doctype htmlhtml langenhead titlehometitle meta nameviewport contentwidthdevicewidth initialscale10 link hrefstaticcssbootstrapmincss relstylesheet mediascreenheadbodydiv idappcontainer classcontainerfluid div classpageheader h1 a hrefhomea smalltextsmall h1 div div idherounits classcarouselinner slide div classherounit home item active h1 text text text h1 p more text p div idappnav a idletsgo classbtn btnprimary btnlarge navforward hrefwhatup let us go a div div divdivscript srcstaticjsjqueryjsscriptscript srcstaticjsunderscorejsscriptscript srcstaticjsbackbonejsscriptscript srcstaticjsbootstrapjsscriptscript srcstaticjssitefiddlejsscriptscript srcstaticjssitejsscriptbodyhtmleverything works if selector is herounits or herounit but selector parsehtmldata returns nothing if selector is appcontainer and i want a jquery object for the divappcontainer element and here is what kills meparsehtmldata does contain the divappcontainer element it is just parsehtmldata7 yet appcontainer parsehtmldata is an empty arraydiv parsehtmldata includes all the divs inside of divappcontainer but not divappcontainer itselfwhats going on here it appears that whats happening is that is not looking at any of the toplevel elements returned by parsehtmldata or parsehtmldata and just their childrenhow can i get a jquery object for divappcontainer from this parsehtmldataanswerthe selector parsehtmldatastyle lookup uses find since i am looking for an element that is toplevel in this jquery object i should use filter instead voila,"['javascript', 'jquery']" +438343,django no module named app django barfs withimporterror at storeno module named storebut right there is the debug message there is the settinginstalled apps djangocontribauth djangocontribcontenttypes djangocontribsessions djangocontribsites djangocontribmessages djangocontribstaticfiles djangocontribadmin djangocontribadmindocs storeenvironmentrequest method getrequest url httplocalhost80django version 145python version 273installed applicationsdjangocontribauth djangocontribcontenttypes djangocontribsessions djangocontribsites djangocontribmessages djangocontribstaticfiles djangocontribadmin djangocontribadmindocs storeinstalled middlewaredjangomiddlewarecommoncommonmiddleware djangocontribsessionsmiddlewaresessionmiddleware djangomiddlewarecsrfcsrfviewmiddleware djangocontribauthmiddlewareauthenticationmiddleware djangocontribmessagesmiddlewaremessagemiddlewaretracebackfile usrlibpython27sitepackagesdjangocorehandlersbasepy in get response 1 response callbackrequest callback args callback kwargsfile homepaulcs462storestoreviewspy in main 37 return redirectreversedjangocontribauthviewsloginfile usrlibpython27sitepackagesdjangocoreurlresolverspy in reverse 476 return iri to uriresolver reverse with prefixview prefix args kwargsfile usrlibpython27sitepackagesdjangocoreurlresolverspy in reverse with prefix 363 possibilities selfreverse dictgetlistlookup viewfile usrlibpython27sitepackagesdjangocoreurlresolverspy in reverse dict 276 self populatefile usrlibpython27sitepackagesdjangocoreurlresolverspy in populate 253 for name in patternreverse dictfile usrlibpython27sitepackagesdjangocoreurlresolverspy in reverse dict 276 self populatefile usrlibpython27sitepackagesdjangocoreurlresolverspy in populate 265 lookupsappendlistpatterncallback bits p pattern patterndefault argsfile usrlibpython27sitepackagesdjangocoreurlresolverspy in callback 216 self callback get callableself callback strfile usrlibpython27sitepackagesdjangoutilsfunctionalpy in wrapper 27 result funcargsfile usrlibpython27sitepackagesdjangocoreurlresolverspy in get callable 105 not module has submoduleimport moduleparentmod submodfile usrlibpython27sitepackagesdjangoutilsimportlibpy in import module 35 import nameexception type importerror at exception value no module named storethe shell works just fine for what i try but this error is thisplayed at every page i have does not having store in the apps means that the module is importededit i have used django for project many times this was working a few hours ago there is a blank init py file in store moreover by using a print statement i was able to determine that this gets executed twice urlspy and modelspy also are executed but not viewspy i have no idea what i could do to get this error,['python'] +438354,jquery check if button is clicked i have two buttons in a form and want to check which one was clickedeverything works fine with radiobuttonsifinputnameclasscheckedval aon simple submit button everything crashthanks,"['javascript', 'jquery', 'html']" +438362,stackoverflowexception caused by recursion i am currently writing a program to help write lore every book object can be a parent and have children which means that every child can have children etc into infinity i was working on a tostring method that could account for this using recursion but i keep getting a stackoverflowexceptioni know what it means but i am in doubt as to how i fix it i am fairly new to c but have quite a lot of java experience so if you know a trick or something that i have missed then please let me knowso my question is how do i avoid a stackoverflow exception the problem is in getallchildreneditafter running a test i should get something like thisname achildrenbc dewith the code from lc i get the following outputname achildren no children bce bce bcehere is the classclass book private string name private book children private stringbuilder text private boolean isparent public bookstring name book children stringbuilder text boolean isparent thisname name thischildren children thistext text thisisparent isparent most likely all possible constructors public bookstring name book children thisname children new stringbuilderno text true public bookstring name string text thisname new book0 new stringbuildertext false public bookstring name stringbuilder text thisname new book0 text false public bookstring name thisname new book0 new stringbuilderno text false public bookbook children string text thisunnamed book children new stringbuildertext true public bookbook children stringbuilder text thisunnamed book children text true public bookbook children thisunnamed book children new stringbuilderno text true public bookstringbuilder text thisunnamed book new book0 text false public book thisunnamed book new book0 new stringbuilderno text false public string name get return name set name value public book children get return children set children value will return the stringbuilder object of this text public stringbuilder text get return text set text value public boolean isparent get return isparent set isparent value private void getallchildrenbook book stringbuilder sb if bookisparent getallchildrenbook sb else sbappendt foreach book b in children sbappendbname n public override string tostring stringbuilder schildren new stringbuilderno children if childrenlength 0 getallchildrenthis schildren return name name n children schildrentostring,['c#'] +438460,take photo from camera in fragment in my fragment i try to take picture from my camera but the onactivityresult of my fragment is not called after taking photo this fragment is not showing and is switching to my first fragment in there any other way for capturing photos in a fragment or what am i doing wronghere is my current codepublic void takephoto intent intent new intentandroidmediaactionimage capture file photo new fileenvironmentgetexternalstoragedirectory picjpg intentputextramediastoreextra output urifromfilephoto imageuri urifromfilephoto photoslistfragmentthisstartactivityforresultintent 100 override public void onactivityresultint requestcode int resultcode intent data superonactivityresultrequestcode resultcode data switch requestcode case 100 if resultcode activityresult ok uri selectedimage imageuri getactivitygetcontentresolvernotifychangeselectedimage null contentresolver cr getactivitygetcontentresolver bitmap bitmap try bitmap androidprovidermediastoreimagesmedia getbitmapcr selectedimage viewholderimageviewsetimagebitmapbitmap toastmaketextgetactivity selectedimagetostring toastlength longshow catch exception e toastmaketextgetactivity failed to load toastlength short show logecamera etostring,['android'] +438472,find out uitextfields end editing without resigning first responder when user is typing in uitextfield and he stops for 2 seconds the cursor is still on uitextfield so how we can identify this event ie i want to check the whether the editing is end or not without resigning the first responser from that uitextfieldwhat is the way to do that,['ios'] +438524,c systeminvalidoperationexception generali am trying to write a very simple tcpip client server in c to connect to an ip address with a port number and ask quite simple line commands and then place the replies in a gridbox graph or other thisplay optioni have looked online and found a down loadable utility that does just this written by jayan nair and this appears to send the message correctly and receive the reply okthe problem comes when i try and load the reply data into a richtext or gridviewthe error message i am getting is systeminvalidoperationexceptioni have asked microsoft forums and they have given me a very complicated ambiguous and overly involved indication as to what i should do and this involves something called invoke and begininvoke and they whole things seems to be a project in its own rightwhat i am after is just an example that works without being too complicatedheres the code try socketpacket thesockid socketpacketasynasyncstate int irx thesockidthissocketendreceiveasyn char chars new charirx 1 systemtextdecoder d systemtextencodingutf8getdecoder int charlen dgetcharsthesockiddatabuffer 0 irx chars 0 systemstring szdata new systemstringchars richtextrxmessagetext szdata fails textbox1text szdata also fails waitfordata and heres the error message base systemwindowsformstextboxbase text systemwindowsformsrichtextbox systemwindowsformsrichtextboxrichtextrxmessagetext threw an exception of type systeminvalidoperationexceptionadditional information is szdata contains about 6300 characters including tabs 9 and returns 13 and is consistant with the message sent from the serveri have also tried it with using a textbox instead of richtext same resultfor those interested heres the microsoft link here is just 2 of the code amendments that i have tried both fail on the same error conditioni think what i need to do is start c at a much lower level and not just jump in and hope for the best public void ondatareceivediasyncresult asyn int inputrx int charlen char inputchars systemtextdecoder inputdecode systemstring szdata bool ifinvokerequired try socketpacket thesockid socketpacketasynasyncstate inputrx thesockidthissocketendreceiveasyn get size of input array inputchars new charinputrx 1 put i char array inputdecode systemtextencodingutf8getdecoder charlen inputdecodegetcharsthesockiddatabuffer 0 inputrx inputchars 0 szdata new systemstringinputchars ifinvokerequired richtextrxmessageinvokerequired if ifinvokerequired true richtextrxmessageinvokemethodinvokerdelegate thistext szdata fails richtextrxmessagebegininvokenew methodinvoker richtextrxmessagetext szdatafails as well,['c#'] +438532,intermittent invalid viewstate error in aspnet web pages storyim developing a chart that is thisplaying vacations annual vacation used vacation etc the for the selection a year business unit and a department from a combo box so far im happy whit the result it is working but if switch between this departments after some time doing this i get this strange error the state information is invalid for this page and might be corruptedno relevant source linesso i scrolled little bit down and found this viewstateexception invalid viewstate client ip 1 port 27968 referer httplocalhostholidaytrackerreportvacationchartaspx path holidaytrackerreportvacationchartaspx useragent mozilla50 compatible msie 100 windows nt 61 wow64 trident60 viewstate so i checked my view states and i have not found a error or something else private htbusinessunit selectedbu get return htbusinessunitviewstateselectedbu set viewstateselectedbu value private htdepartment selectdep get return htdepartmentviewstateselecteddep set viewstateselecteddep value private string selectedyear get return viewstateselectedyear null viewstateselectedyeartostring set viewstateselectedyear value here is the error message argumentexception invalid token for impersonation it cannot be duplicated systemsecurityprincipalwindowsidentitycreatefromtokenintptr usertoken 3597947 systemsecurityprincipalwindowsidentityctorserializationinfo info 187 systemsecurityprincipalwindowsidentityctorserializationinfo info streamingcontext context 51targetinvocationexception exception has been thrown by the target of an invocation systemruntimemethodhandleserializationinvokeiruntimemethodinfo method object target serializationinfo info streamingcontext context 0 systemruntimeserializationobjectmanagercompleteiserializableobjectobject obj serializationinfo info streamingcontext context 298 systemruntimeserializationobjectmanagerfixupspecialobjectobjectholder holder 45 systemruntimeserializationobjectmanagerdofixups 230 systemruntimeserializationformattersbinaryobjectreaderdeserializeheaderhandler handler binaryparser serparser boolean fcheck boolean iscrossappdomain imethodcallmessage methodcallmessage 137 systemruntimeserializationformattersbinarybinaryformatterdeserializestream serializationstream headerhandler handler boolean fcheck boolean iscrossappdomain imethodcallmessage methodcallmessage 186 systemruntimeserializationformattersbinarybinaryformatterdeserializestream serializationstream 15 systemwebuiobjectstateformatterdeserializevalueserializerbinaryreader reader 1873 systemwebuiobjectstateformatterdeserializevalueserializerbinaryreader reader 334 systemwebuiobjectstateformatterdeserializevalueserializerbinaryreader reader 420 systemwebuiobjectstateformatterdeserializevalueserializerbinaryreader reader 432 systemwebuiobjectstateformatterdeserializevalueserializerbinaryreader reader 420 systemwebuiobjectstateformatterdeserializestream inputstream 139argumentexception the serialized data is invalid systemwebuiobjectstateformatterdeserializestream inputstream 203 systemwebuiobjectstateformatterdeserializestring inputstring purpose purpose 481 systemwebuiobjectstateformattersystemwebuiistateformatter2deserializestring serializedstate purpose purpose 8 systemwebuiutildeserializewithassertistateformatter2 formatter string serializedstate purpose purpose 40 systemwebuihiddenfieldpagestatepersisterload 127viewstateexception invalid viewstate client ip 1 port 27795 referer httplocalhostholidaytrackerreportvacationchartaspx path holidaytrackerreportvacationchartaspx useragent mozilla50 compatible msie 100 windows nt 61 wow64 trident60 viewstate wepdwullte2otyymja5mzkpfgqecnnlbgvjdgvkqnuy1p4baaeadaqamagaelib2xpzgf5vhjhy2tlckrhdgesifzlcnnpb249ms4wljaumcwgq3vsdhvyzt1uzxv0cmfslcbqdwjsawnlzxlub2tlbj1udwxsdamabvu3lzdgvtlkrhdgeurw50axr5lcbwzxjzaw9uptqumc4wljasien1bhr1cmu9bmv1dhjhbcwguhvibgljs2v5vg9rzw49yjc3ytvjntyxotm0zta4oqubakehvbglkyxlucmfja2vylkrhdgeutw9kzwwushrcdxnpbmvzc1vuaxqfad19cdxnpbmvzc1vuaxrjzavftmftzq9ft3jnyw5pc2f0aw9uswqbrw50axr5t2jqzwn0k19yzwxhdglvbnnoaxbzf0vudgl0eu9iamvjdctfzw50axr5s2v5aaeabaqicdntexn0zw0urgf0ys5pymply3rzlkrhdgfdbgfzc2vzlljlbgf0aw9uc2hpce1hbmfnzxidafvn5c3rlbs5eyxrhlkvudgl0eutleqmacafayeabuztlultdgakfacqyafbqadntexn0zw0urgf0ys5pymply3rzlkrhdgfdbgfzc2vzlljlbgf0aw9uc2hpce1hbmfnzxicabl9vd25lcg5fcmvsyxrpb25zaglwcwqdkehvbglkyxlhttpexception 0x804005 the state information is invalid for this page and might be corrupted systemwebuiviewstateexceptionthrowerrorexception inner string persistedstate string errorpagemessage boolean macvalidationerror 198 systemwebuihiddenfieldpagestatepersisterload 266 systemwebuipageloadpagestatefrompersistencemedium 88 systemwebuipageloadallstate 36 systemwebuipageprocessrequestmainboolean includestagesbeforeasyncpoint boolean includestagesafterasyncpoint 6704 systemwebuipageprocessrequestboolean includestagesbeforeasyncpoint boolean includestagesafterasyncpoint 245 systemwebuipageprocessrequest 72 systemwebuipageprocessrequestwithnoasserthttpcontext context 21 systemwebuipageprocessrequesthttpcontext context 58 aspreport vacationchart aspxprocessrequesthttpcontext context in cwindowsmicrosoftnetframeworkv4030319temporary aspnet filesholidaytrackerad68c35456d80455app web k5s5ajkf1cs0 systemwebcallhandlerexecutionstepsystemwebhttpapplicationiexecutionstepexecute 341 systemwebhttpapplicationexecutestepiexecutionstep step boolean completedsynchronously 69here is my globalasaxcsnamespace holidaytracker public class global systemwebhttpapplication void application startobject sender eventargs e code that runs on application startup void application endobject sender eventargs e code that runs on application shutdown void application errorobject sender eventargs e code that runs when an unhandled error occurs void session startobject sender eventargs e code that runs when a new session is started if httpcontextcurrentuser null httpcontextcurrentuser is htuser htuser user htuserhttpcontextcurrentuser sessionuserid useruserid sessionuser userlastname userfirstname if userhtdepartmentsany userhtdepartmentssingleordefaulthtbusinessunit null int businessunitid userhtdepartmentsfirsthtbusinessunitbusinessunitid sessionbusinessunnitid businessunitid void session endobject sender eventargs e code that runs when a session ends note the session end event is raised only when the sessionstate mode is set to inproc in the webconfig file if session mode is set to stateserver or sqlserver the event is not raised if sessionuserid null responseclearcontent responsewritenot agine responseend else responsewritesessionuseridtostring protected void windowsauthentication onauthenticateobject source windowsauthenticationeventargs e if requestcookiesgetconstantsauthorization cookie name null return string struseridentity formsauthenticationticket formsauthticket httpcookie httpcook string strencryptedticket adlookup adlookup new adlookup struseridentity eidentityname bool loggedin false string email null string role null email struseridentity htuser userinfo null if email null email userinfo htusergetbylogineidentity email if userinfo null userinfousernamelength 0 loggedin true role htusergetuserrolestringuserinfo checks if user is in domain else userinfo adlookupgetaduserbyusernamehtusergetusernamefromdomainstringemail if userinfo null userinfousernamelength 0 loggedin true role userrolesuser if loggedin formsauthticket new formsauthenticationticket1 email datetimenow datetimenowaddminutes60 false role strencryptedticket formsauthenticationencryptformsauthticket httpcook new httpcookieconstantsauthorization cookie name strencryptedticket responsecookiesaddhttpcook httpcontextcurrentuser userinfo else httpcontextcurrentuser null i you need something more feel free to ask me thanks for help and fast answer,"['c#', 'asp.net']" +438559,angular equivalent of jquery map i am transitioning from relying on jquery to building apps in angularjs it is recommended in a number of places to not mix jquery and angular codeone thing i miss though is the jquery map function for arrays i know this could be rewritten using the native javascript map function but this is not implemented in all browsers notably ie v9so is there an angular equivalent or should i got back to writing for var x 0 x foo x 1 so i can stop including jquery update sometimes knowing what to search for is all you need bergie says look for polyfills heres a reference guide from the modernizr crew for a bunch of resources for making modern code work on older browsers html5 cross browser polyfills,"['javascript', 'jquery']" +438581,clever asynchronous repaint in java i have a usecase coming from a gui problem i would like to submit to your sagacity use casei have a gui that thisplays a computation result depending on some parameters the user set in a gui for instance when the user moves a slider several events are fired that all trigger a new computation when the user adjust the slider value from a to b a dozens of events are firedbut the computation can take up to several seconds whereas the slider adjustment can fire an event every few 100 mshow to write a proper thread that would listen to these events and kind of filter them so that the repaint of the results is lively ideally you would like something likestart a new computation as soon as first change event is receivedcancel the first computation if a new event is received and start a new one with the new parametersbut ensure that the last event will not be lost because the last completed computation needs to be the one with last updated parameters what i have trieda friend of mine a cardona proposed this low level approach of an updater thread that prevents too many events to trigger a computation i copypaste it here gplhe puts this in a class that extends threadpublic void doupdate if isinterrupted return synchronized this request notify public void quit interrupt synchronized this notify public void run while isinterrupted try final long r synchronized this r request call refreshable update from this thread if r 0 refresh will trigger recomputation synchronized this if r request request 0 reset wait else loop through to update again catch exception e eprintstacktrace public void refresh execute computation and paint it everytime an event is sent by the gui stating that parameters have been changed we call updaterdoupdate this causes the method refresh to be called much less but i have no control on thisanother wayi was wondering if there is another way to do that that would use the jacaconcurrent classes but i could not sort in the executors framework what would be the one i should start withdoes any of you have some experience with a similar use case thanks,['java'] +438639,import project with no project file i am trying to import a project in eclipse it is the google play services library to use with google maps android api v2 downloaded from the sdk manager and located on my computer at androidsdkfolderextrasgooglegoogle play serviceslibprojectgoogleplayservices libit is not working and from what i have found because of the absence of the project file at the root of the project eclipse says no projects are found to importhere is a screenshotthanks for your help,['android'] +438662,fermat primality test i have tried to write a code for fermat primality test but apparently failedso if i understood well if p is prime then apap0 where pa0my code seems to be ok therefore most likely i misunderstood the basics what am i missing hereprivate bool isprimeint candidate checking if candidate 0 1 2 int a candidate 1 candidate cannot be divisor of candidate1 if mathpowa candidate a candidate 0 return true return false,['c#'] +438695,board game pawn movement algorithm i have been working on a board game with a friend of mine we have managed to get most of it working the game is called jeu de barricade maybe you know it the whole board gets created using a linked list so every field has a linknorth linkeast linksouth and linkwest variable here is the board to give you an idea of how it looks like now there is one thing we just cannot seem to figure out how to do currently a pawn can be selected and it can be moved to any field on the board this of course is not good what we need to do now is write a method with some sort of algorithm that returns an array or list of the fields the pawn is able to move to this way we can check if the selected pawn is actually able to move to the field you clicked on with the thrown dice number a random number from 1 till 6 is generatedone more thing though every field class has a barricadepawn variable when this variable contains a barricadepawn object barricadepawn null the pawn should not be able to move over it the pawn should be allowed to move onto that field but not any further when the player lands exactly on a barricade he can move it but we already implemented that so do not worry about thatso in short i want to create a method in our pawn class which returns an array or list of all the fields that the pawn should be able to move to the pawn should be able to move on barricades but not over them the pawn has to move exactly the amount thrown by the dice so to get on the finish or on a barricade you have to throw exactly the right amount we have these in our pawn classcurrentlocation contains the field that the selected pawn is currently standing onprivate modelfield startlocationprivate modelfield currentlocation public listmodelfield getpossiblemovesmodelfield curspot int remainingmoves listmodelfield movehistory listmodelfield retmoves new listmodelfield if remainingmoves 0 retmovesaddcurspot return retmoves else movehistoryaddcurspot if curspotlinknorth null movehistorycontainscurspotlinknorth retmovesaddrange getpossiblemoves curspotlinknorth remainingmoves 1 movehistory if curspotlinkeast null movehistorycontainscurspotlinkeast retmovesaddrange getpossiblemoves curspotlinkeast remainingmoves 1 movehistory if curspotlinksouth null movehistorycontainscurspotlinksouth retmovesaddrange getpossiblemoves curspotlinksouth remainingmoves 1 movehistory if curspotlinkwest null movehistorycontainscurspotlinkwest retmovesaddrange getpossiblemoves curspotlinkwest remainingmoves 1 movehistory and this is our field classpublic class field protected field linknorth linkeast linksouth linkwest protected controllerpawn pawn protected modelbarricadepawn barricadepawn protected int x y properties public field linknorth get return linknorth set linknorth value public field linkeast get return linkeast set linkeast value public field linksouth get return linksouth set linksouth value public field linkwest get return linkwest set linkwest value public controllerpawn pawn get return pawn set pawn value public barricadepawn barricade get return barricadepawn set barricadepawn value public int x get return x set x value public int y get return y set y value if anyone could help us with this it would be much appreciated we have not been able to come up with anything,['c#'] +438728,how to get latitude and longitude from google maps v3 api i am trying create a map using google maps v3 api i have found the below code over internet and i want to show the latitude and logitude in map window instead of addrescript function initialize var mapoptions center new googlemapslatlng338688 1512195 zoom 13 maptypeid googlemapsmaptypeidroadmap var map new googlemapsmapdocumentgetelementbyidmap canvas mapoptions var input documentgetelementbyidsearchtextfield var autocomplete new googlemapsplacesautocompleteinput autocompletebindtobounds map var infowindow new googlemapsinfowindow var marker new googlemapsmarker map map googlemapseventaddlistenerautocomplete place changed function infowindowclose markersetvisiblefalse inputclassname var place autocompletegetplace if placegeometry inform the user that the place was not found and return inputclassname notfound return if the place has a geometry then present it on a map if placegeometryviewport mapfitboundsplacegeometryviewport else mapsetcenterplacegeometrylocation mapsetzoom17 why 17 because it looks good var image url placeicon size new googlemapssize71 71 origin new googlemapspoint0 0 anchor new googlemapspoint17 34 scaledsize new googlemapssize35 35 markerseticonimage markersetpositionplacegeometrylocation markersetvisibletrue var address if placeaddress components address placeaddress components0 placeaddress components0short name placeaddress components1 placeaddress components1short name placeaddress components2 placeaddress components2short name join infowindowsetcontentdivstrong placename strongbr address infowindowopenmap marker sets a listener on a radio button to change the filter type on places autocomplete function setupclicklistenerid types var radiobutton documentgetelementbyidid googlemapseventadomlistenerradiobutton click function autocompletesettypestypes setupclicklistenerchangetypeall setupclicklistenerchangetypeestablishment establishment setupclicklistenerchangetypegeocode geocode googlemapseventadomlistenerwindow load initialize script head body div input idsearchtextfield typetext size50 input typeradio nametype idchangetypeall checkedchecked label forchangetypeallalabel input typeradio nametype idchangetypeestablishment label forchangetypeestablishmentestablishmentslabel input typeradio nametype idchangetypegeocode label forchangetypegeocodegeocodeslable div div idmap canvasdiv bodyhtmlplease some one help me to get and show latitude and longitudethanksenamul,['javascript'] +438811,calling custom functions from python using rpy2 is there a way to call functions defined in a file say myfuncr myfuncr myfunc function returnc12345678910getname function returnchart title python how to call getname here any help would be greatly appreciated,['python'] +438816,are all thread methods like getnamesetname threadsafe is it safe to use threads methods like setname getname and some others from different threads api does not say anything but judging by the source codeprivate char namepublic final void setnamestring name checkaccess thisname nametochararraypublic final string getname return stringvalueofnameit seems that it may cause memory consistency errors,['java'] +438884,notifydatasetchange not working from custom adapter when i repopulate my listview i call a specific method from my adapterproblemwhen i call updatereceiptslist from my adapter the data is refreshed but my listview does not reflect the change questionwhy does not my listview show the new data when i call notifydatasetchangedadapterpublic class receiptlistadapter extends baseadapter public listreceipt receiptlist private context context private layoutinflater inflater private datehelpers dateh public receiptlistadapteractivity activity context mcontext listreceipt rl context mcontext receiptlist rl collectionsreversereceiptlist inflater layoutinflateractivitygetsystemservicecontextlayout inflater service dateh new datehelpers override public int getcount try int size receiptlistsize return size catchnullpointerexception ex return 0 public void updatereceiptslistlistreceipt newlist receiptlist newlist thisnotifydatasetchanged override public receipt getitemint i return receiptlistgeti override public long getitemidint i return receiptlistgetigetreceiptid private string getpuntenstringreceipt r ifrgetpointsequals1 return 1 punt return rgetpoints punten override public view getviewint position view convertview viewgroup parent view viconvertview final receipt receipt receiptlistgetposition receiptviewholder receiptviewholder typeface tf hn typefacecreatefromassetcontextgetassets helveticaneuettf typeface tf hn bold typefacecreatefromassetcontextgetassets helveticaneuebdttf if vi null convertviewnull receiptviewholder new receiptviewholder vi inflaterinflaterlayoutview listitem receipt null visetonclicklistenernull visetonlongclicklistenernull visetlongclickablefalse receiptviewholdershop textview vifindviewbyidridtv listitemreceipt shop receiptviewholderdate textview vifindviewbyidridtv listitemreceipt date receiptviewholderprice textview vifindviewbyidridtv listitemreceipt price receiptviewholderpoints textview vifindviewbyidridtv listitemreceipt points receiptviewholdershopsettypefacetf hn bold receiptviewholderpricesettypefacetf hn bold visettagreceiptviewholder elseconvertview is not null receiptviewholder receiptviewholdervigettag receiptviewholdershopsettextreceiptgetshop receiptviewholderdatesettextdatehtimestamptodatestringlongparselongreceiptgetpurchasedate receiptviewholderpricesettexta receiptgetprice receiptviewholderpointssettextgetpuntenstringreceipt visetclickablefalse return vi public static class receiptviewholder public textview shop public textview date public textview price public textview points public object getfilter x autogenerated method stub return null editfound workaroundjust to have some functional code i do nowlistviewsetadapter new receiptlistadapteractivitymcontext new datasetworks but not how it is supposed to work,['android'] +438907,fontface svg not working properly in chrome i have an issue with a specific font and the way it is rendered in chromefirefox shows the font properly due to using ttf chrome does not use antialias and the font is too sharp and ugly this is the css declaration i used fontface fontfamily helveticaneuelt std thin src urlfontsh2eot src urlfontsh2svgtest formatsvg urlfontsh2woff formatwoff urlfontsh2ttf formattruetypefontweight normalfontstyle normali have come to the conclusion that the problem is with the svg declarationfont fileif i do not use the hash tag at all and leave it as only svg it renders antialiased but at a different lineheight with slightly off positioning if i add svganything it does not antialias it at all and looks ugly any suggestions are welcome to help me fix this rather annoying problemps windows antialiasing is ok i tested this i also tried out the media screen and webkitmindevicepixelratio0 declaration for the svg font only to no successi realize this may be a repost but having tried all the solutions from the related questions i am a bit desperate,['css'] +438931,nginx showing blank php pages i have setup an nginx server with php5fpm when i try to load the site i get a blank page with no errors html pages are served fine but not php i tried turning on thisplay errors in phpini but no luck php5fpmlog is not producing any errors and neither is nginxnginxconfserver listen 80 root homemikew606club index indexphp indexhtml server name mikeglazcom wmikeglazcom error log varlognginxerrorlog location php fastcgi pass 12700190 with php5fpm fastcgi pass unixvarrunphp5fpmsock fastcgi index indexphp include fastcgi params editheres my nginx error log20130315 035255 error 10200 55 open homemikew606clubrobotstxt failed 2 no such file or directory client 199302040 server mikeglazcom request get robotstxt http11 host mikeglazcom,['php'] +438995,is it a good idea to index datetime field in mysql i am working on designing a large database in my application i will have many rows for example i currently have one table with 4 million records most of my queries use datetime clause to select data is it a good idea to index datetime fields in mysql databaseselect field1 field2field15from table where field 20 between now and now 30 days i am trying to keep my database working good and queries being run smoothly more what idea do you think i should have to create a high efficiency database,['mysql'] +439012,are left outer joins and left joins the same i have seen joins called left outer join or right outer join in some places i have seen left join or right join i am confused by this i posted a question 2 days ago but i am unable to understand the links the solutions provideare these types of joins both the same or is there some difference between the two,"['mysql', 'sql']" +439017,ctags jsctagsdoctorjs tagbar step by step i need help on setting up ctags jsctags and tagbar so i can have a workable javascript editing envrionment i got everything installed but could not get an idea how ctags and jsctags work together so i do not know how to configure properly i have done quite a bit google around but the information is pretty broken and lacks consistency i got an error similar to this post ctags and tagbar configuration are out of sync i am on os x mountain lion and iterm2any help would be greatly appreciated a step by step instructions would be excellent thx,['javascript'] +439051,how to handle post request in nodejs hi i am a newbie to nodejs currently i am trying to handel the post request using nodejsi have written a java script file with a name serverjs which thisplay a form on the browser i want to use the form values and post it in html for example form contains username repository branch and a submit button so i want that after filling the form when the user commit it using submit button then he should be able to see those values in terms of htmlmy server js code is var http requirehttphttpcreateserverfunction request response responsewritehead200 contenttype texthtmlresponseendhtmlbody h1xyz repository commit monitorh1 form methodpost action enctypeapplicationxwformurlencodedfieldset divlabel forusernameuser namelabelinput typetext idusername nameusername div divlabel forrepositoryrepositorylabelinput typetext idrepository namerepository div divlabel forbranchbranchlabelinput typetext idbranch namebranch valuemaster div divinput idlistcommits typesubmit valuelist commits div fieldsetform bodyhtmllisten8124consolelogserver running at now i want to handle this post request and present the data in html form after user fill the form and commit it,['javascript'] +439091,java bigdecimal subraction failing i tried the following code but getting different result when subtracting using bigdecimal double d1 01 double d2 01 systemoutprintlndouble result d2d1 float f1 01f float f2 01f systemoutprintlnfloat result f2f1 bigdecimal b1 new bigdecimal001 bigdecimal b2 new bigdecimal001 b1 b1subtractb2 systemoutprintlnbigdecimal result b1result double result 00float result 00bigdecimal result 0e59i am still working on this can anyone please clarify,['java'] +439156,setting uibutton titleedgeinsets and imageedgeinsets is slow with autolayout i have a view with a couple of buttons various sizes all of them has a title and an image i wanted to have the image on top the title on the bottom centered this works fine with the following code voidcenteralignimageandtextforbuttonuibuttonbutton cgfloat spacing 5 cgsize imagesize buttonimageviewframesize buttontitleedgeinsets uiedgeinsetsmake0 imagesizewidth imagesizeheight spacing 0 cgsize titlesize buttontitlelabelframesize buttonimageedgeinsets uiedgeinsetsmaketitlesizeheight spacing 0 0 titlesizewidthhowever i notice a little pause before entering this view time profiler in instruments shows that 99 of the time spent in viewdidload is caused by calling my method for the buttons2830ms xviewcontroller viewdidload2820ms xviewcontroller centeralignimageandtextforbutton1410ms uibutton imageview 980ms uiviewhierarchy layoutbelowifneeded1410ms uibutton titlelabel1030ms uiviewhierarchy layoutbelowifneededvarious layout related things are called within uiviewhierarchy layoutbelowifneeded like uiviewadditionallayoutsupport recursivelayoutenginedidchange or nslayoutconstraint addtoenginei know it would be possible to set these insets in interface builder but not only that is a tedious work need to guess the width of the text the app will also be localized so the insets that are good for one language would not be for another where text size differs i am using base localization for storyboards and strings files instead of duplicating the whole storyboard for each language so for me it seems setting the insets programmatically is the way to go but the lag it causes is not really acceptableany thoughts how this could resolved,"['ios', 'objective-c']" +439228,how to target tablets but not ie9 using a media query i am finding that ie9 is taking on tablet styles for my sitemedia mindevicewidth 768px and maxdevicewidth 1024px and orientation portrait mindevicewidth 768px and maxdevicewidth 1024px and orientation landscape tablet styles the above media query is applied in ie9 when the browsers width is 1024pxhaving done some research i found the following questionsolution and it offers an explanation as to why this is happeningmedia query not working in ie9from what i can tell it comes down to ie9 not interpreting mindevicewidth and maxdevicewidthaccording to it does not support those properties only minwidth and maxwidthin addition states that the browser is supposed to ignore properties that it does not recognize not so with ie9 it seemsi also found this question good widths for media queries on responsive site but it does not give me a solution how can i apply my stylesheet only to tablets and not to desktop browsers like ie9 at a 1024px width,['css'] +439230,how to render django template from code instead of file i am writing a google app engine webapp that renders some html to a django template i want to either render the template using either a file or just some json thats very similar to that in file is it possible to use django to render this to a file that is read in and stored in database the oldapihtml is just an old version of apihtml but with some small changes rendering django to the apihtml file works finei understand that you cannot store files on gae how can i dynamically use django to render to html stored in memorypath oldapi apiversionget by key nameversionif oldapi is none path ospathjoinospathdirname file apihtmltemplate values responsedict responsedict if path selfresponseoutwritetemplaterenderpath template values else selfresponseoutwritetemplaterenderoldapihtmltemplate values,['python'] +439246,mapfragment in fragment alternatives i need your help i work on it until 3 days my app is working with fragmentsone of these fragments has to thisplay a map from the google maps v2 api for androidcurrently i am using a mapfragment but no surprise a fragment in a fragment is not a good idea but it works the map is thisplaying i can edit it but when i switch of main fragment and return on itcaused by javalangillegalargumentexception binary xml file line 59 duplicate id 0x7f070041 tag null or parent id 0x7f070040 with another fragment for comgoogleandroidgmsmapsmapfragmentat androidappactivityoncreateviewactivityjava4252at androidviewlayoutinflatercreateviewfromtaglayoutinflaterjava673this is the cause when i go on another fragment and return to the one which contains the mapi am searching until 3 days to fix this but no great resultsto resume for you i have an activity which calls a fragment which contains a mapfragment in the layout fileif you need more just ask thanksedit here is the code to change fragment in the main activityprivate void swtichfragmentfragment fragment bundle bundlefragmentsetbundlethis bundlefragmentmanager fragmentmanager getfragmentmanagerfragmenttransaction fragmenttransaction fragmentmanagerbegintransactionfragmenttransactionreplaceridrightfragmentplaceholder fragmentfragmenttransactioncommitmrightfragment fragment,['android'] +439314,grails hibernatesearchable stops server to start by giving the exception below we are using grails 211 and searchable plugin 064 in our grails applications and implemented searchable on some domains which are indicated below with all the mappingsclass user static hasmany usereducations usereducations userworkings userworkings static searchable content spellcheck include all termvector yes usereducations component true userworkings component true class usereducations schools schools static belongsto user user static searchable content spellcheck include all termvector yes schools component true class userworkings organizations organizations static belongsto user user static searchable content spellcheck include all termvector yes organizations component true class schools static searchable true class organizations static searchable true the data is saving successfully with correct mapping and constraintsthe problem starts when we have the drowslike below in table user with relationshipuser a1 usereducations b1 schools d1 and user a2 usereducations b2 schools d1oruser a1 userworkings c1 organizations e1 and user a2 userworkings c2 organizations e1we are not sure about above fact may be the problem happened due to large no of datathen when we try to start the server then we receive below exception and server wouldnt startwe have tried by removing searchable index and restarting again then it also not startthe server starts only when we truncate tables corresponding to above 5 domains183054133 compass gps index pool5thread5 error indexerscrollablehibernateindexentitiesindexer hibernate failed to index the databaseorgcompasscoreenginesearchengineexception processor 4 failed to add job job create alias organizations uid organizations456 resource organizations storeduncompressedindexedomitnormsaliasorganizationsstoreduncompressedindexedomitnormsomittforganizationsid456storeduncompressedindexedactivetruestoreduncompressedindexeddatecreated201302281403050pmstoreduncompressedindexedtokenizeda109122482450911storeduncompressedindexedlastupdated201302281403050pmstoreduncompressedindexedtokenizednameascstoreduncompressedindexedversion0storeduncompressedindexedomitnormsomittfuidbs456 after 10ms and backlog size 100 at orgcompasscoreluceneenginetransactionsupportabstractconcurrenttransactionprocessorprocessoraddjobabstractconcurrenttransactionprocessorjava496 at orgcompasscoreluceneenginetransactionsupportabstractconcurrenttransactionprocessorcreateabstractconcurrenttransactionprocessorjava158 at orgcompasscoreluceneenginelucenesearchenginecreateorupdatelucenesearchenginejava290 at orgcompasscoreluceneenginelucenesearchenginecreatelucenesearchenginejava268 at orgcompasscoreimpldefaultcompasessioncreatedefaultcompasessionjava413 at orgcompasscoreimpldefaultcompasessioncreatedefaultcompasessionjava397 at orgcompasscoreimplexistingcompasessioncreateexistingcompasessionjava305 at orgcompassgpsdevicehibernateindexerscrollablehibernateindexentitiesindexerrowbufferflushscrollablehibernateindexentitiesindexerjava212 at orgcompassgpsdevicehibernateindexerscrollablehibernateindexentitiesindexerrowbufferclosescrollablehibernateindexentitiesindexerjava206 at orgcompassgpsdevicehibernateindexerscrollablehibernateindexentitiesindexerperformindexscrollablehibernateindexentitiesindexerjava151 at orgcompassgpsdevicesupportparallelconcurrentparallelindexexecutor11doincompasswithoutresultconcurrentparallelindexexecutorjava104 at orgcompasscorecompasscallbackwithoutresultdoincompasscompasscallbackwithoutresultjava29 at orgcompasscorecompasstemplateexecutecompasstemplatejava133 at orgcompassgpsimplsinglecompassgpsexecuteforindexsinglecompassgpsjava147 at orgcompassgpsdevicesupportparallelconcurrentparallelindexexecutor1callconcurrentparallelindexexecutorjava102 at javautilconcurrentfuturetasksyncinnerrunfuturetaskjava334 at javautilconcurrentfuturetaskrunfuturetaskjava166 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava10 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava603 at javalangthreadrunthreadjava679our problem is similar to below postwe have tried our best to sort out the problem but no luckplease help us to solve this problem,['mysql'] +439333,are there compiler settings in visual studio 2010 to ensure the writing of portable c i receive c source code from a developer who is compiling using visual studio 2010 that i then need to recompile under various different compilers gcc llvm other versions of visual studio etc sometimes the code that he sends me that compiles without warnings in vs2010 fails to compile under the other compilersare there any compiler settings he can set in vs2010 to increase the likelihood that his code will be cleanly portable,['c++'] +439359,spring data service layer unit testing in my project i am having trouble doing unit testing one issue is that just doing an integration test is much faster to write and also tests that the components actually work together unit testing novel algorithms or so seems much easier unit testing service classes it just feels wrong and useless i am using mockito to mock spring data repository and hence db access the thing is if i tell the mocked repository to return entity a on method call getbyid it will obviously return that and the service will return it too yes the service does some extra stuff but very minor things like load lazy collections from hibernate obviously i do not have any lazy collections proxies in a unit testexampletestpublic void testgetbyid systemoutprintlngetbyid testcompound expresult new testcompoundid test compound 9 null null null testcompoundrepository mockedrepository mocktestcompoundrepositoryclass whenmockedrepositoryfindoneidthenreturnexpresult reflectiontestutilssetfieldtestcompoundservice testcompoundrepository mockedrepository testcompoundrepositoryclass testcompound result testcompoundservicegetbyidid assertequalsexpresult resulthooray the rest succeeds what a surprise not really no can some one explain to me what i am doing wrong or else what the point of such a test is i mean i tell to return expresult and then it is returned wow what a surprise feels like i am testing if mockito works and not my serviceeditthe only benefit i see if some were stupid error happens like leaving an unwanted line there that sets return value to null or something similar stupid such cases would be caught by the unit test still the rewardeffort ratio seems bad,['java'] +439376,generate series of a month by week interval in postgresql i am trying to generate a series of a month by week but with some constraints i need all the weeks to start on a monday and get cut when they start or end in another month examplefor february 2013 i want to generate a series like this start20130201 020130204 020130211 020130218 020130225 0the query that i have until now looks like thisselect greatestdate truncweek datesd date truncmonthdatesd as startfrom generate seriesto timestamp1359676800to timestamp13620959 1 week as datesdthis query gets me the first 4 weeks but it is missing the week from the 25th is it possible to get the last week,['sql'] +439410,mysql error 1364 field does not have a default values my table looks likecreate table try name varchar8 created by varchar40 not nulland then i have a trigger to auto populate the created by field create trigger autopopulateatinsert before insert on try for each row set newcreated byuserwhen i do an insert using insert into try name values abcthe entry is made in the table but i still get the error messagefield created by does not have a default value error no 1364is there a way to suppress this error without making the field nullable and without removing the triggfer otherwise my hibernate will see these exceptions even though the insertions have been made and then application will crash,['mysql'] +439460,using custom routeduicommand in xaml throws exception i have followed this article and some others to create a custom routeduicommandi am using infragistics ribbon but i dont think the problem comes from thereigribbonxamribbonwindow xclassmyribbonwindowxmlnsxmlnsx xmlnsigribbonxmlnsmcxmlnsdxmlnsmynamespacetagclrnamespacemynamespacexmlnsigwpf mcignorabled windowstatemaximized igribbonxamribbonwindowresources some datatempaltes here igribbonxamribbonwindowresourcesigribbonribbonwindowcontenthost xnameribbonwindowcontenthost igribbonribbonwindowcontenthostribbon igribbonxamribbon xnamexamribbon themecurrent igribbonxamribbonapplicationmenu igribbonapplicationmenu igribbonapplicationmenufootertoolbar igribbonapplicationmenufootertoolbar igribbonbuttontool nameappmenuoptions captionopt ions igribbonapplicationmenufootertoolbar igribbonapplicationmenufootertoolbar igribbonapplicationmenu igribbonxamribbonapplicationmenu igribbonxamribbon igribbonribbonwindowcontenthostribbon contentcontrol contentbinding mycontent contenttemplateselectorstaticresource mycontenttemplateselector igribbonribbonwindowcontenthost igribbonxamribbonwindowwe needed to change the look and feel of the infragistics ribbon and a team member from infragistics comunity suggested an style to be added the problem is that when we added it to the resources section of the ribbon it did not workso we were forced to do the followingvar resourcedictionary new resourcedictionaryresourcedictionarysource new uri mynamespacecomponentresourcesribbonresourcesxaml urikindrelativeorabsolutexamribbonresourcesmergeddictionariesaddresourcedictionarythis applies correctly the styles in the ribbon but in that ribbonresourcesxaml we have a buttonbutton namemybutton commandmynamespacetagmycommandsmycommand stylestaticresource xstatic toolbarbuttonstylekey image sourcemyimagepng width16 height16 buttonthe mycommand and mycommands class have been created exactly as the article i mentionedbut when i run the application i get the following errorxamlparseexception failed to create a command from the text mynamespacemycommandsmycommand innerexception type reference cannot find type named clrnamespacemynamespacemycommandsif i use the command like this insteadcommandxstatic mynamespacetagmycommandsmycommandi get the following exceptionxamlparseexception provide value on systemwindowsmarkupstaticextension threw an exception innerexception type reference cannot find type named clrnamespacemynamespacesmycommandsin the codebehind we are binding the command like thiscommandbindingsadd new commandbinding mycommandsmycommand show canshowif we put the button directly where we have the xamribbonwindow it works finei am still pretty new with wpf and i cannot figure out what i am doing wrong,['c#'] +439468,replacing item in observablearray i am trying to replace all of the contents of an item in an observablearray with new contentvar oldlocation koutilsarrayfirstselflocations function item return itemid valueidselflocationsreplaceselflocationsindexofoldlocation new locationvalueselflocationsvaluehasmutatedi have also triedselflocationsselflocationsindexoflocation new fizikomodelslocationvaluebut nothing is working the index is being properly retrieved but the update of the item is not happening,['javascript'] +439499,why does toolkitgetdefaulttoolkitbeep not work in windows when i try to get a beep by using toolkitgetdefaulttoolkitbeep it does not seem to work on any of my windows computers i also know someone who has the same problem but they say it works on other oss does anyone know why,['java'] +439535,vertically center responsive image i am wondering if there is a simple way to vertically center a responsive image please refer to the following jsfiddle basic htmlimg classmobiletitlesize src altlogobasic cssmobiletitlesize position absolutetop 25left 6width 70maxwidth 300pxthis is the mobile header that uses the same image that is thisplayed on tablet and desktop viewports since the image is already being loaded anyway i am looking to use this same image resize it smaller and vertically align it so that i can use one image for all viewportsthe problem on browser resize the image does get smaller but it does not vertically align in the centerthe goal even though the width overlaps badly in this example it is not an issue on my site the goal is only to vertically center the image as the browser resizesi am okay with using a javascriptjquery solution but of course simple css is preferredany help is greatly appreciated,"['jquery', 'css']" +439582,whats the best practice to do event driven development in angularjs apps i am adding some websocket functional to our angular app the websocket object is wrapped in a service ideally we would like our wrapped socket object to have a standard event api so that we can use it in the controller like the following sorry for the coffeescriptangularmodulemyappcontroller myctrl scope socket update msg scopeapply do something regarding to the msg socketon message update unregister socketoff message update whats the best practicelibrary for us to achieve this use jquery backboneevents any suggestion will be helpful thanks,['javascript'] +439593,javascript canvas curve with fixed length i want to draw any randomized curve with givenstart pointend pointcurve lengthhow can i do such a thing limited by canvas boundaries plus the curve can not cross i was trying to find some solution but i cannot figure this out thanks for your timehere is more detailed view of what i want to accomplishthis is quadratic curve drawn on canvas everything is fine question is how to draw this without all the points just with the fixed length in pixels random points bounded by canvas size and non crossingthe code could look something like thisfunction fixedcurve a b length forint i a i b i calculate random point with propper thistance to get first base point random direction could be calculated before loop basicly this loop should calculate integrate of the curve and draw it each step,['javascript'] +439598,how can i make my navibar the same across my html with each new page i have to update the navigation panel which means i go from page to page copying and pasting my navigation bar the more pages i add the harder it gets now i have inconsistent navigation bars so what i am looking for is a way to make an html file that contains only the navigation bar then embed it into my code like i would do with css and javascript that way if i edit the one file all other pages get updated if i use the iframe tag there would be way to many problems but i know of no other tag that can do what i need so what should i do i have done some research but all i can find is the iframe tag what should i do,['html'] +439658,java minimax alphabeta pruning recursion return i am trying to implement minimax with alphabeta pruning for a checkers game in java my minimax algorithm works perfectly my code runs with the alphabeta code in place unfortunately when i play 10 games vs the standard minimax algorithm the alphabeta algorithm always comes out behind by 50 games or so since alphabeta pruning should not be reducing the quality of the moves just the time it takes to achieve them something has to be wrong however i have taken out pen and paper and drawn hypothetical leaf node values and used my algorithm to predict whether it will calculate the correct best move and there does not appear to be any logic errors i used the tree from this video alphabeta pruning to trace my algorithm it logically should make all of the same choices and therefore be a functioning implementation i have also put print statements into the code they have been removed to reduce the clutter and values are being returned correctly it appears and pruning does happen despite my best efforts i have been unable to find where the logic error lies this is my third different attempt at implementing this and all of them have had the same issuei cannot post the full code here it is much too long so i have included the methods that are relevant to the error i am not certain but i suspect the problem may likely be in the nonrecursive move method though i cannot find a logical error in it so i would just be thrashing around in it more probably making things worse rather than better without having a rhyme or reasonis there a trick to recovering multiple integer values from recursive calls in a for loop it works fine with both my minimax and negamax implementations but alphabeta pruning seems to produce some strange resultsoverridepublic gamestate movegamestate state int alpha infinity int beta infinity int bestscore integermax value gametreenode gametreeroot new gametreenodestate gamestate bestmove null forgametreenode child gametreerootgetchildren ifbestmove null bestmove childgetstate alpha mathmaxalpha minimaxchild plydepth 1 alpha beta ifalpha bestscore bestmove childgetstate bestscore alpha return bestmoveprivate int minimaxgametreenode currentnode int depth int alpha int beta ifdepth 0 terminalnodecurrentnodegetstate return getheuristiccurrentnodegetstate ifcurrentnodegetstategetcurrentplayerequalsselfcolor forgametreenode child currentnodegetchildren alpha mathmaxalpha minimaxchild depth 1 alpha beta ifalpha beta return beta return alpha else forgametreenode child currentnodegetchildren beta mathminbeta minimaxchild depth 1 alpha beta ifalpha beta return alpha return beta checks to see if the node is terminalprivate boolean terminalnodegamestate stateifstategetstatusequalswin stategetstatusequalslose stategetstatusequalsdraw return true else return false,['java'] +439665,how do i ensure an idempotent database insert with entity framework 5 i want to ensure that my database sql server updates are idempotent similar in functionality to the blog post below but using entity framework v5 database firsthowever if i add an operation parameter to my insert proc i get error 2037 a mapping function bindings specifies a function but does not map the following function parameters operationthe operation would be a guid generated by the app allowing the app to retry with the same guid if it does not get a success response from the proc the proc would write the guid to a log table and only perform the insert if the guid does not exist thus ensuring an idempotent transactionis there an elegant solution,['c#'] +439682,static fields in inner classes if i have class structure like that public class foo declaring fields and methods fooint k bara k public class bar public final static int a and if i create many instances of foo how does static field in class bar acts i mean it is the same instance for all foo objects or for each instance there is different static field,['java'] +439694,creating two custom buttons can some one please help me on creating custom buttons like below is it possible have searched a lot and was able to find only some things which again turn out to be rectangularsquare shapes but i want two buttons to be triangular and to be arranged on up on the other and clickable only on their particular occupied areas code snippets are appreciated,['android'] +439712,htmlcss text background transparent but text not so i am having a problem i have looked around and looked around but no luck i would like to make the background of my body transparent but leave the text non transparent as it is right now i keep making both the same opacity here is my code charset utf8body font 10014 verdana arial helvetica sansserif backgroundcolor 42413c margin 0 padding 0 color 0 elementtag selectors ul ol dl padding 0 margin 0h1 h2 h3 h4 h5 h6 p margintop 0 paddingright 15px paddingleft 15px opacity1a img border nonealink color 42413c textdecoration underlineavisited color 6e6c64 textdecoration underlineahover aactive afocus textdecoration nonecontainer width 750px margin 0 autocontent padding20px width710px positionrelative backgroundc opacity 05fltrt float right marginleft 8pxfltlft float left marginright 8pxclearfloat clearboth height0 fontsize 1px lineheight 0pxheader top0 width 750px height 200px backgroundimage urlimagesheaderpng backgroundrepeatnorepeat backgroundpositioncenternavbar height 50px width 750px position relative zindex 2bg position fixed top 25 left 15 zindex 1div thisplay blockhere is my website click the link dont type tccraftnet in your url it will take you to a facebook page thank you,"['html', 'css']" +439725,create object instance of a class having its name in string variable i do not know the thing i am asking is available or not but i just want to know if it exists and how it works so here is my questioni have 23 custom model class of my own for example customer employee and product now i have class name in a string and based on the class name coming in a string i have to create its object and return to a view how could i achieve thisi know a option of if else statement but i want to try a betterdynamic way,"['c#', '.net']" +439733,django function object has no attribute objects my apps allow you to like a picture then it redirects you to the same pagei get then error when i try to like a picture i can create a like objects with the shell prompt but why i get this error thank for helping meattributeerror at like3function object has no attribute objectsrequest method get request url exception value function object has no attribute objects tracebackfile cpython26libsitepackagesdjangocorehandlersbasepy in get response1 response callbackrequest callback args callback kwargsfile comysitepetviewspy in like195 new like created likeobjectsget or createuserrequestuser picture idpicture idthis is parts of my viewspydef likerequestpicture id pid picture id new like created likeobjectsget or createuserrequestuser picture idpicture id p pictureobjectsgetpkpid if created httpresponseredirectreverseworldurl name else httpresponseredirectreverseworldurl namemy urlconf urlparts of my model rlikepd petviewslike name like my boathtml if picture ul for pet in picture libdescriptionb petdescriptionbr if petimage li a href url worldlike petid img src petimageurl stylecursorpointer a li endif endfor ul endif a href url worldpicturecreator add pictures to your boardabrmy modelspyclass picturemodelsmodel user modelsforeignkeyuser board modelsforeignkeyboardblankfalsenullfalse image modelsfilefieldupload toimagesblanktrue description modelstextfield is primary modelsbooleanfielddefaultfalse def unicode self return selfdescriptionclass likemodelsmodel user modelsforeignkeyuser picture modelsforeignkeypicture created modelsdatetimefieldauto now addtrue,['python'] +439752,how to debug sharing violation when trying to delete a file i have a multi threaded c application which creates files opens them for processing then deletes them once finished this application can expect anywhere from 1 100 files to be processed somewhat randomly most likely attributed to the multi threaded nature of the application i get a sharing violation when i try to delete a file after processing my gut says well vic you did not properly closethispose the file before trying to delete it and i would go with my gut if it happened for every file but it does not so i am trying to find out where i am making a mistake anyone out there have any pointers on how to debug this type of an exception i would love to see a stack trace on the file if that makes sense i will attempt to show pseudo code however my question is more on how to debug this type of exception application events operation start create new processor transfer file processorprocessfile and add new document object to processors document collection as path not fileoperation complete processoraggregate files create new file containing contents of files when this method is finished it calls processorfinished processor events processor finished application cleanupprocessor in this method i thispose of the processor which in turn thisposes of a document object which deletes the file,['c#'] +439769,remove element from json object i have a json array which looks something like this id 1 children id 2 children id 3 children id 4 children id 2 children id 3 children id 4 children id 2 children id 3 children id 4 children id 2 children id 3 children id 4 children id 2 children id 3 children id 4 children id 2 children id 3 children id 4 children id 2 children id 3 children id 4 children i would like to have a function which removes the elements which has the children empty how can i do it i am not asking for the answer only suggestions,"['javascript', 'jquery']" +439778,mysql install db gives fatal error could not find mydefaultcnf i have download mysql and i am trying to setup the mysql grant tables but when i typescriptsmysql install db basedirusrlocali get the error abovei am not sure how to fix it as mydefaultcnf is in the support files directory and i believe i am setting the basedir correctlythis is on mac btw,['mysql'] +439788,why cannot we initialize class members at their declaration i wonder if there is a reason why we cannot initialize members at their declarationclass foo int bar 42 this is invalidas an equivalent of using constructor initialization listsclass foo int barpublic foo bar42 my personal understanding is that the above example is much more expressive and intentional moreover this is a shorter syntax and i do not see any possibility of confusion with other language elementsis there any official clarification about this,['c++'] +439806,why when i deserialize with jsonnet ignores my default value i am using jsonnet as my main serializerthis is my model look that i have setted some jsonproperties and a defaultvaluepublic class assignmentcontentitem jsonpropertyid public string id get set jsonpropertyqty defaultvalue1 public int quantity get set when i serialize a listassignmentcontentitem it doing a good workprivate static jsonserializersettings s new jsonserializersettings defaultvaluehandling defaultvaluehandlingignore nullvaluehandling nullvaluehandlingignore outputidq0idq4idq7but when i would like to deserialize this jsoncontent the property qty is always 0 and is not set to the default value i mean when i deserialize that jsoncontent as defaultvalue for quantity should be one instead of 0 public static listassignmentcontentitem deserializeassignmentcontentstring jsoncontent return jsonconvertdeserializeobjectlistassignmentcontentitemjsoncontent s what should i do,['c#'] +439832,independent column scroll in html page i have two columns in my html page div idcontent div idleftdiv div idrightdivdiveach of them occupies half of the pageleft float left width 50right float left width 50is it possible to make it so that they flow independently i mean i want to be able to scroll down the left column but remain at the top of the right column instead of having to scroll down both columns at the same time,"['html', 'css']" +439836,what should own the model in an mvc pattern i have been making ios apps since i can remember but i have not matured my programming style much until recently when i got an internship programming i learned many oo concepts early on because i realized that life sucked with out an understanding of them but one thing that i never made myself learn was the mvc patternto give context let us say that i am drawing a solar system inside of a single solarsystemview a subclass of uiview should my solarsystemview have an instance variable of class solarsystem a class containing a data structure with all of the important planetary and stelar properties or should that be under ownership of an instance of a solarsystemviewcontroller or is it something completely different i cannot find any example code that gives a satisfactory answeri imagine that if the view owned the model operations would be very smooth but that also does not feel like good style after all the solarsystem instance has to change dynamically somehow and with the same or similar rate that the solarsystemview updates,"['ios', 'objective-c']" +439861,replace preg replace e modifier with preg replace callback i am terrible with regular expressions i am trying to replace thispublic static function camelizeword return preg replace aze strtoupper2 wordwith preg replace callback with an anonymous function i do not understand what the 2 is doing or for that matter exactly how preg replace callback works what would be the correct code for achieving this,['php'] +439906,selection animation why does not the animation property works on selection selector in cssdemo page basic test case body colorblue keyframes slc 50 colorred webkitkeyframes slc 50 colorred custom selection styles selection backgrounde animation04s slc infinite mozselection backgrounde animation04s slc infinitewebkitselection backgrounde webkitanimation04s slc infinite,['css'] +439912,send headers with avplayer request in ios is it possible to send headers with an http request to an audio file when using avplayer i need to be able to inspect the content of the header when received by the server in order to restrict access to the file being requested,['ios'] +439948,opengl es objects away from view centre are stretched so i have generated a sphere in opengl es specifically opengl es 20 in java for android when this sphere is placed at the same position as the centre used for my view matrix it is fine but when off centre the sphere is pretty badly warped see belowwhy is this happening and how do i stop itthat is the same sphere the one in the upper right is just translated in x and y not zsome snippets of the code from my implementation of glsurfaceviewrendererpublic void onsurfacecreatedgl10 unused eglconfig config gles20glclearcolor00f 00f 00f 10f gles20glenablegles20gl cull face gles20glenablegles20gl depth test both centred on 0 of radius 10 outersphere new sphere centresphere new spherepublic void onsurfacechangedgl10 unused int width int height gles20glviewport0 0 width height ratio float width height final float left ratio final float right ratio final float bottom 10f final float top 10f final float near 10f final float far 10f matrixfrustummprojmatrix 0 left right bottom top near farpublic void ondrawframegl10 unused gles20glcleargles20gl depth buffer bit gles20gl color buffer bit float eyex 00f float eyey 00f float eyez 100f final float lookx 00f final float looky 00f final float lookz 00f final float upx 00f final float upy 10f final float upz 00f matrixsetlookatmviewmatrix 0 eyex eyey eyez lookx looky lookz upx upy upz set identity matrix as input for translations matrixsetidentitymoutermodelmatrix 0 translate outer sphere by 5 in x and y matrixtranslatemoutermodelmatrix 0 50f 50f 00f mvp matrix projection view model matrixmultiplymmcentremvpmatrix 0 viewmatrix 0 centremodelmatrix 0 matrixmultiplymmcentremvpmatrix 0 projectionmatrix 0 centremvpmatrix 0 matrixmultiplymmoutermvpmatrix 0 viewmatrix 0 outermodelmatrix 0 matrixmultiplymmoutermvpmatrix 0 projectionmatrix 0 outermvpmatrix 0 outerspheredrawoutermvpmatrix centrespheredrawoutermvpmatrixand my shaders are simplyprivate final static string vertexshadercode uniform mat4 you mvpmatrix attribute vec4 a position uniform vec4 you color void main gl position you mvpmatrix a position private final static string fragmentshadercode precision mediump float uniform vec4 you color void main gl fragcolor you color i have left out almost all code from the sphere class and other things that i do not think are necessary but if they are needed i will put them up,['android'] +439950,persistentstoremanagedobjectcontext vs mainqueuemanagedobjectcontext good eveningso i have been having some trouble understanding what the hell is going on while saving my data in core data first of all a quick question1 when should i be using the persistentstoremanagedobjectcontext and when should i be using the mainqueuemanagedobjectcontext right now i always use the persistentmanagedobjectcontext but i can see that a restkit call getobjectspath the object will have the mainqueueobjectcontext why is thatthanks,['ios'] +439969,angularjs dependency injection in services factories filters etc so i have some plugins and libraries i want to use in my angular app and currently i am simply referencing those functionsmethods as they were intended in 99 of apps in a way that completely ignores dependency injectioni have for example the javascript library momentjs which deals with formatting and validating dates and i have uses for it throughout my app in controllers services and filters the way that i have learned using angularjs is to create a service that references the function and it is methods and inject that service into my controllers which works greatthe problem is that i really need to reference this library in all different kinds of components from services to filters to controllers and everything else so i guess my question is how do you do dependency injection in filters services and everything else that is not a controlleris this possible is this even beneficial any help would be greatly appreciated,['javascript'] +439980,enable pdf fast web view using java how do i enable fast web view property of a pdf using java code or any open source java librariesnote this is also known as a linearized pdf,['java'] +439998,make an image responsive simplest way i have been searching for a solution to this for a while now with no luck i notice that my code is responsive in the fact that if i scale it down to the size of a phone or tablet all of the text links and social icons scale accordinglyhowever the only thing that does not is my image in the body which is wrapped in paragraph tags with that being said is there a simple way to make the image responsive as wellthank you heres the code that i used to have my image show in the bodybody center pa hrefmy website link target blankimg srcimage link border0 altnullap centerbody,"['html', 'css']" +440005,how to find a template in an image using a mask or transparency with opencv and python let us assume we are looking for this templatethe corners of our template are transparent so the background will vary like soassuming we could use the following mask with our template it would be very easy to find itwhat i have triedi have tried matchtemplate but it does not support masks as far as i know and using the alpha channel transparency in the template does not achieve this as it compares the alpha channels instead of ignoring those pixelsi have also looked into region of interest which i thought would be the solution but with it you can only specify a rectangular area i am not even sure if it works on the template or noti am sure this is possible to do by writing my own algorithm but i was hoping this is possible via standard opencv to avoid reinventing the wheel not to mention it would most likely be more optimised than my ownso how could i do something like this with opencv python,['python'] +440064,stddefault random engine generato values betwen 00 and 10 i want to be able to generate random values between 00 and 10 i have tried to use stddefault random engine generatorstduniform real thistributionfloat thistribution00 10float myrand thistributiongeneratorgenerating random value in a loop gives me always these values0220085032060135308916110967956018969005149760398008026290607435120089548what can i do to really get random valuesdoes not seem that random if i always get the same ones,['c++'] +440070,how to compare socket address in c i mean which fields of struct sockaddr should i compare when i check whether two struct sockaddrs have the same ip address and port number and what about sockaddr incan i just cast sockaddr in to sockaddr and compare it to a real sockaddr,['c'] +440082,best javascript library to create and interactive flow chart i would like to create an interactive problem solving type flow chart that is made up out div elements i would like to do something very similar to what the new york times have done in this examplesomeone suggested raphael so i have been learning a bit of that and it is awesomeis there any other library worth consideringalso if raphael is suitable for this task is it a widely used library if i am going to learn new skills it is in my best interest to learn popular code so i can re apply it with different jobs i get not some exotic thing that ill never use or no one will ever want me to use againthanks very much,['javascript'] +440106,do i need to kill a thread written like this or will it automatically end using code like the code below will the new thread created end on its own after the function returnsnew thread functionstarti am pretty new to threading so i wondered,['c#'] +440213,how to match arabic words with reg exp i have a string like this 3uu 1u which is a two word arabic phrase i want to match first word with regular expression if it was english i would test azaz how can i do it with arabic,['javascript'] +440271,futures promises and exceptions stdpromiseint p1auto f p1get future stdpromiseint p2stdmoveprbool valid fvalid truefwait does not throw or fail but returns immediatelyfget throws an exceptionis there any way to check if a future is going to throw before calling get i hoped valid would check i am not really sure how to get valid to return false destroying the promise without setting a value does not do it,['c++'] +440292,cursoradapter backed listview delete animation flickers on delete i am trying to implement swipe to delete and in a listview using the swipetothismissundolist library which extends roman nuriks swipetothismiss samplemy issue is in the delete animation since the listview is backed by a cursoradapter the animation triggers the onthismiss callback in onanimationend but this means that the animation has run and reset itself before the cursoradapter updates with the deletethis ends up looking like a flicker to the user where they delete a note by swiping it away then the view is back for a split second and then thisappears because the cursoradapter has picked up the data changehere is my onthismisscallbackprivate swipethismisslistonthismisscallback thismisscallback new swipethismisslistonthismisscallback override public swipethismisslistundoable onthismisslistview listview final int position cursor c madaptergetcursor cmovetopositionposition final int id cgetintquery id final item item itemfindbyidgetactivity id if loglogv logvdeleting item item final contentresolver cr getactivitygetcontentresolver crdeleteitemsbuilditemuriid null null madapternotifydatasetchanged return new swipethismisslistundoable public void undo if loglogv logvrestoring item item contentvalues cv new contentvalues cvputitems id itemgetid cvputitemsitem content itemgetcontent crinsertitemscontent uri cv,['android'] +440312,when is this json structure getting converted to all strings i am sending a json structure to my nodeexpress server and saving the object into a database the problem is that i send json with integers and booleans but everything gets saved as stringshere is my nodeexpress codevar express requireexpressvar app expressappenablejsonp callbackappuseexpressbodyparser allow cross origin scripting to get data from devices directlyappall functionreq res next resheaderaccesscontrolalloworigin resheaderaccesscontrolallowmethods put get post delete options resheaderaccesscontrolallowheaders contenttype nextapostdepartures functionreq res i started using this to convert back to integers but need to solve the problem for var i in reqbodydata reqbodydataisiteid parseintreqbodydataisiteid consolelogsaving data jsonstringifyreqbodydata positionprovidersavereqbodydata function resjsonstatussuccess here is how i am posting with jquery var data siteid123 ajax type post url serverurl departures data data data success functionresp alertsaved departure data jsonstringifydata error functionerr consolelogerror posting to server consolelogerr the jquery side reports that it sent siteid123 but the node side reports that it received siteid123where is the integer getting converted to a string,['jquery'] +440337,how to avoid an implicit return in coffeescript in conditional expressions i am implementing a function that has deferred value to return and within the function i have many nested conditional expressionsegdeferred qdeferfsreadfilefootxt utf8 error text if error deferredrejectnew errorerror else deferredresolvetextreturn deferredpromisewhich than will be compiled intovar deferreddeferred qdeferfsreadfilefootxt utf8 functionerror text if error return deferredrejectnew errorerror else return deferredresolvetext return deferredpromisei need only the last return but not the ifelse returns ie return in the compiled codehow can i avoid such a behavior implicit returns where they are do not needed of the coffeescript compiler,['javascript'] +440340,ios and objectivec most of cpu time is spent in nsobject release and nsobject retain but class method is not doing any memory operations an image processing applications runs fast on the simulator but is really slow on a real device iphone 4gswhen running the application under instruments i see the following call treenote that the calls within the red circle are reported to take almost all of the cpu time of the methodthe method in question is a class method not an instance method with the following codeimplementation line2f cgfloatsigntestedpoint2f tested p1point2f p1 p2point2f p2 return line2f signtestedxtestedx testedytestedy p1xp1x p1yp1y p2xp2x p2yp2y cgfloatsigntestedxcgfloattestedx testedycgfloattestedy p1xcgfloatp1x p1ycgfloatp1y p2xcgfloatp2x p2ycgfloatp2y return testedx p2x p1y p2y p1x p2x testedy p2y endcan anyone explain why is most of the cpu time is spent on nsobject release and nsobject retain,"['ios', 'objective-c']" +440349,run exe file as an embedded resource in c i have a 3rd party exe i just need to run this from my c application my prime target is to copyright that 3rd party executable from my c file is there any better way to do this how can i do this thank youmenaka,['c#'] +440364,check if all elements satisfy a condition i need a jquery filtermapeach type function to check if all elements satisfy a conditionfunction areallvalidinputs return somefunctioninputs functioninput return inputlength 0 if all inputs have length 0 somefunction should return true anything like this in jquery,['jquery'] +440392,right to left bracket thisplay wrong when the label text value ends with end bracket the result in right to left is wrong like exampletext abc 123result abc 123expected result abc 123is there any solution to fix it,"['c#', '.net']" +440393,add user control to a form i have created a user control with a textbox and two buttons but i have not created events just i place them to user control when i want to add the user control to my form it says cannot move task controlcs the destination folder is the same as the source folder i do not understand why thank you,['c#'] +440413,how to set an input directory for doxygen i have a directory in which all source and header files are saved i would like to run doxygen to generate documentation for these source code however i do not want to change anything in this directory in particular i cannot add sub directories in which doxygen documentation will be savedhow can i achieve what i need i am using doxygen for the first time so detailed instructions would be very appreciatedi think i need to do the following i create and go to the documentation directory in this directory i execute doxygen g to create a template configuration file named doxyfile then i think i need to modify the doxyfile to indicate that the source code is not in the current directory by the way the output will be automatically by default saved in the directory in which doxygen is executed,['c++'] +440417,using virtualenv with spaces in a path i set up a virtualenv environment on my mac but cannot get pip to install packages it fails with the following errorvolumesmacintosh bad interpreter no such file or directoryi tracked the problem down to there being a space in the path as is answered here the path being volumesmacintosh hdpythonmy projectbut that is a bit of a problem the proposed solution is tojust put your virtualenv environment in a path without a spacebut the part with the space is the volume itself all of my paths would have a space unless i stored them in a directory of and i do not think store your stuff outside of user space is a good solutionis there a better solution to this,['python'] +440545,how to set up new jenkins slave i recently inherited a jenkinsdriven java project where the primary developer just upped and quit he had deployed the jenkins war to a tomcat instance on a virtual server and that is what was considered to be the build serverthis build server had a slave configured for building and deploying to myserverexamplecom another virtual server over the weekend the systems staff retired the physical server that the myserverexamplecom virtual lived on producing the following exception for any jenkins job configured to deploy to that slavewhen i click on the see log for more details link i see the following console output031813 081331 ssh opening ssh connection to myserverexamplecom22javaioioexception there was a problem while connecting to myserverexamplecom22 at comtrileadssh2connectionconnectconnectionjava755 at comtrileadssh2connectionconnectconnectionjava546 at hudsonpluginshslaveshlauncheropenconnectionsshlauncherjava650 at hudsonpluginshslaveshlauncherlaunchsshlauncherjava283 at hudsonslavesslavecomputer1callslavecomputerjava200 at javautilconcurrentfuturetasksyncinnerrunfuturetaskjava303 at javautilconcurrentfuturetaskrunfuturetaskjava138 at javautilconcurrentthreadpoolexecutorworkerruntaskthreadpoolexecutorjava886 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava908 at javalangthreadrunthreadjava662caused by javanetnoroutetohostexception no route to host at javanetplainsocketimplsocketconnectnative method at javanetplainsocketimpldoconnectplainsocketimpljava351 at javanetplainsocketimplconnecttoaddressplainsocketimpljava213 at javanetplainsocketimplconnectplainsocketimpljava200 at javanetsockssocketimplconnectsockssocketimpljava366 at javanetsocketconnectsocketjava529 at comtrileadssh2transporttransportmanagerestablishconnectiontransportmanagerjava342 at comtrileadssh2transporttransportmanagerinitializetransportmanagerjava450 at comtrileadssh2connectionconnectconnectionjava699 9 more031813 081334 ssh connection closedthis makes sense since the slave the myserverexamplecom virtual is offline however having no real previous experience with jenkins i am not sure of what the proper steps are for configuring the jenkins master to builddeploy these jobs to a new slave and how to set up the new slave for instance do i need to install anything on the new slave or do any kind of setupconfig thanks in advance,['java'] +440548,unit testing an asynchronous service in angularjs i am trying to unit test a service which has asynchronous methods but am having no lucki have tried to implement with promises by using the q support in angularjsany help would be appreciatedangularmodulemyapp myserviceangularmodulemyservice factorymyservice functionq var ls lsdoit function var deferred qdefer settimeoutfunction deferredresolve5 30 return deferredpromise return lsdescribeservices function beforeeachmodulemyservice itshould equal 2 injectfunctionmyservice myservicedoitthenfunctionreturned expectreturnedtoequal2,['javascript'] +440569,pack a software in python using py2exe with libiomp5mddll not found i have python 27 on window 7 os i wish to pack my projectpy in an executable using py2exe following the instruction i wrote a setuppy filefrom thistutilscore import setupimport py2exesetupconsoleprojectpy and i got this messagei tried to exclude libiomp5mddllfrom thistutilscore import setupimport py2exesetupconsolesegmentationaccuracypydll excludes libiomp5mddllbut always i got the same error message error libiomo5mddll no such file or directorymy executable containsimport mathimport osimport numpy as npimport sysimport ogrfrom progressbar import progressbarfrom shapelygeometry import polygonnan npnan,['python'] +440580,how to add githubs mantle to xcode using cocoapods i have added githubs mantle project to a ios 6 project using cocoapods pod search mantle vim podfile here i added pod mantle pod install this installs mantle 10 then i have added the inherited variable to the header search paths of projects build settings section before my custom search paths when importing the mantle header file xcode complains withimport mantleh mantlemtljsonadapterh file not foundam i missing some step i have other pods installed as well afnetworking and sskeychain but only mantle is giving me issuesi have also added sstoolkit but following the instructions on its getting started ie not using cocoapods,['objective-c'] +440590,is there a way to determine when a java thread started i have got a request to create an analysis of running threads within a jvm to monitor for long running jobs is there any way to find the starting datetime of a java thread i have no problem getting the threads but i cannot figure out any way to to find out how long the thread has been active or when it started to get the threads i am simply enumerating over the threadgroupnote that i have no control over the actual threads themselves so i cannot put in any time or property and log the start time myself all i have it the actual thread itself and need to determine the data from that i can find two methods on the thread getthreadcputime and getthreadusertime but i am not sure those are enough since apparently the thread will occasionally invoke a sleep method and i am afraid that the sleep time would not be included in either of these methodsis there any way to determine the start time for a thread or will either of the two time methods return how long a thread has been active,['java'] +440648,seamless left to right activity transition animation in android i have two activities and i want that when the user touches a button on the first activity the new activity slides in from the left and moves to the right while the first activity does the same it moves to the right and slides out so it would give an effect in which the new activity pushes the old one to the right and replaces it in order to do that i have written the following xmlsin animationxml version10 encodingutf8 set xmlnsandroid translate androidfromxdelta100 androidtoxdelta0 androidduration1250 setout animationxml version10 encodingutf8 set xmlnsandroid translate androidfromxdelta0 androidtoxdelta100 androidduration1250 seti call the overridependingtransitionranimanim inranimanim out function in the oncreate method of the new activity in the resulting effect the new activity moves from the left to right correctly but the first older activity moves into the opposite direction it moves to the left i want to revert the moving direction of this first activity how can i do that is there a xml property which serves to this purpose,['android'] +440652,programmatically trigger uitableviewcell delete button i would like to add a custom button on my cells that do the same thing as swipetodelete function so when clicking on my custom button this one will be hide to let appear the official red delete buttonso i did something like that controllerm brief delete icon button pressed trigger thisplay of delete full button ibactiondeletedrugidsender eventidevent nsindexpath indexpath self indexpathforbuttonsender eventevent uitableviewcell cell selftableview cellforrowatindexpathindexpath cell seteditingyes animatedyes customcellm voidseteditingboolediting animatedboolanimated super seteditingediting animatedanimated hide show modify button when entering in edit mode switch editing case yes selfdeletebuttonhidden yes break case no selfdeletebuttonhidden no break default break at this moment my custom button are getting hide when clicking on them but the official red delete button is not appearingdo someone know how to handle this,['ios'] +440664,what is the use of an ioc framework in an mvc application i am trying to understand the use of an ioc framework like structuremap but i cannot help thinking that these design patterns are just nonsense making code just more complexlet me start with an example where i think an ioc is somewhat usefulli think an ioc can be usefull when dealing with the instantiation of controller classes in an mvc framework in this case i am thinking about the net mvc frameworknormally the instantiation of the controller class is handled by the framework so that means you cannot really pass any parameters to the constructor of your controller classthis is where an ioc framework can come in handy somewhere in an ioc container you specify what class should be instantiated and passed to your controllers constructor when the controller class is invokedthis is also handy when you want to unit test the controller because you can mock the object that is passed to itbut like i said i can somewhat understand why people want to use it for their controller classes but not outside of that from there on you can simply do normal dependency injectionbut why not simply do it like thispublic class somecontroller public somecontroller this new someobj publiv somecontrollersomeobj obj thisobj obj now you do not have to use any 3rd party ioc framework which also means a lower learning curve since you do not have to go into the specs of that framework aswellyou can still mock the object in your unit tests so no problem there eitherthe only thing you can say is but now your class is tightly coupled to someobjthis is true but who cares it is a controller class i am not going to reuse that class ever so why on earth should i worry about that tight coupling i can mock the object that is passed to it that is the only important thingso why should i bother using an ioc am i really missing the point to me the ioc pattern is just some overrated pattern adding more complex layers to your application,"['c#', '.net']" +440666,knockoutjs setting an empty selection i am trying to use knockoutjs to populate and manage a select box i would like the initial value to be emptyhowever i am having trouble trying to force the managed value to be null at any time let alone initiallyfor example consider this fiddlehtml select databindoptions myoptions value myvalueselect akaspan databindtext myvaluespandiv button databindclick setmyvaluenullclear the selectionbutton button databindclick setmyvalueoneselect onebutton button databindclick setmyvaluefourselect fourbuttondivul databindforeach log limessage span databindtext messagespanliuljsfunction model var self this selfmyoptions one two three four selfmyvalue koobservable selfsetmyvalue function val return function thislogpush message ok trying to set value as val selfmyvalueval selflog koobservablearrayvar model new modelkoapplybindingsmodelthe select one and select four buttons work to change the selection by forcing an update of myvalue however the clear the selection button does not work the selection is not cleared by myvaluenull which is what i thought was the proper way to do itwhat am i doing wrong,['javascript'] +440684,how java implement the access to the enclosing class from an inner inner class i have created an inner class in an inner class public class enclosingclass public class innerclass private enclosingclass getenclosing return enclosingclassthis public class innerinnerclass private innerclass getenclosing return innerclassthis private enclosingclass getenclosingofenclosing return enclosingclassthis i have been surprised that java allows the innerinnerclass to access directly the enclosingclass how is this code implemented internally by javathe innerinnerclass keeps two pointers one on the innerclass and the other on the enclosingclass or the innerinnerclass access the enclosingclass through the innerclass,['java'] +440762,why am i getting typeerror objaddeventlistener is not a function heres my codefunction addevent obj type fn if objattachevent objetypefn fn objtypefn functionobjetypefn windowevent objattachevent ontype objtypefn else objaddeventlistenertype fn falsefunction alertwinner alertyou may be a winnerfunction showwinner var atag documentgetelementsbytagnamea addeventatag click alertwinnershowwinnerbasically i am working in the firebug console and trying to get an alert to pop up when any a tag is clickedi cannot see the problem that results in this not working and giving me the error stated in my questions title viewed in firebug anybody,['javascript'] +440777,threadpoolexecutor with unbounded queue not creating new threads my threadpoolexecutor is failing to create new threads in fact i wrote a somewhat hacky linkedblockingqueue that will accept any task ie it is unbounded but call an additional handler which in my application spews warning trace that the pool is behind which gives me very explicit information that the tpe is refusing to create new threads even though the queue has thousands of entries in it my constructor is as follows private final executorservice s3uploadpool new threadpoolexecutor1 40 1 timeunithours unboundedloggingqueuewhy is it not creating new threads,['java'] +440799,making a tree structure in django models i want to have a model with 2 fields children and parent how do i do this in django i have something like thisfrom djangodb import modelsclass foomodelmodelsmodel parent modelsforeignkeyself blanktrue nulltrue children modelsmanytoonerelself blanktrue nulltrue def init self args kwargs superfoomodel self init args kwargs selfparentchildrenaddselfbut i do not think i am supposed to use the manytoonerel like this especially because it is giving me a keyword error on blank any advice,['python'] +440826,angularjs jasmine comparing objects i am just starting out writing tests for my angularjs app and am doing so in jasminehere are the relevant code snippetsclientcontrolleruse strictadminconsoleappcontrollerclientcontroller function clientcontrollerscope client get list of clients scopeclients clientqueryfunction preselect first client in array scopeselectedclient scopeclients0 necessary for databinding so that it is accessible in child scopes scopeselected current page scopecurrentpage starthtml for client nav bar scopeclientnavitems destination featureshtml title features set current page scopesetcurrent function title destination if destination scopecurrentpage destination return path to current page scopegetcurrent function return partialsclients scopecurrentpage for nav bar highlighting of active page scopeisactive function destination return scopecurrentpage destination true false reset current page on client change scopeclientchange function scopecurrentpage starthtml clientcontrollerspecuse strictvar response id 10 name client plus ref clientplus id 13 name client minus ref clientminus id 23805 name shaun qa ref saqa describeclientcontroller function var scope beforeeachinjectfunctioncontroller httpbackend rootscope scope rootscope httpbackendwhengethttplocalhost3001clientsrespondresponse controllerclientcontroller scope scope httpbackendflush itshould preselect first client in array function this fails expectscopeselectedclienttoequalresponse0 itshould set current page to starthtml function expectscopecurrentpagetoequalstarthtml the test failschrome 250 mac clientcontroller should preselect first client in array failed expected id 10 name client plus ref clientplus to equal id 10 name client plus ref clientplus error expected id 10 name client plus ref clientplus to equal id 10 name client plus ref clientplus at nullanonymous usersshaunsandboxzongadminconsoleapptestunitcontrollersclientcontrollerspecjs4339 does anyone have any ideas on why this might be happeningalso as i am new to writing angularjs tests any comments on whether i am setting up my test wrong or whether it can be improved will be welcomeupdateincluding clientserviceuse strictadminconsoleappservicesfactoryclient function resource api is set up such that if clientid is passed in will retrieve client by clientid else retrieve all return resourcehttplocalhostportclientsclientid port 3001 clientid clientid also i got around the problem by comparing ids insteaditshould preselect first client in array function expectscopeselectedclientidtoequalresponse0id,['javascript'] +440829,hide or change the value label for a range input in ie10 i have a range input with a custom label thisplaying text which corresponds to the inputs value this works well except that internet explorer 10 also thisplays its own tooltiplike label containing the value the trouble is that this tooltip obscures my label it also thisplays an integer value where the actual value of the control is a floati cannot figure out how to hide the label or modify its text it is separate from the tooltip and does not respond to the title attribute it does not respond to zindex either so i cannot just position my label above it i see no property mentioned in the documentation that would provide access to the labeldemo jsfiddlenetkzwrs,['javascript'] +440927,auto layout error i had a similar problem to this poster and i used jrturtons suggestion to move the code for customizing the buttons into viewdidlayoutsubviews it was working well until i received this errornsinternalinconsistencyexception reason auto layout still required after sending viewdidlayoutsubviews to the view controller viewcontrollers implementation needs to send layoutsubviews to the view to invoke auto layouti am very clueless on graphics and the only thing i could think of was to put selfview layoutsubviews but that did not fix anything it worked when i unchecked auto layout in my storyboard but that changed the dimensions of my buttons and i was wondering if there was another way to fix itcodevoidviewdidlayoutsubviews nsarray arrayofbuttons nsarray arraywithobjectsselfdecimalbutton selfbuttonone selfbuttontwo selfbuttonthree nil for uibutton button in arrayofbuttons button settitlecoloruicolor whitecolor forstateuicontrolstatenormal button settitlecoloruicolor redcolor forstateuicontrolstatehighlighted buttonlayerborderwidth 025f buttonlayerbordercolor uicolor graycolor cgcolor cagradientlayer btngradient cagradientlayer layer btngradientframe buttonbounds btngradientcolors nsarray arraywithobjects iduicolor colorwithred1220f 2550f green1880f 2550f blue2550f 2550f alpha10f cgcolor iduicolor colorwithred960f 2550f green1710f 2550f blue2480f 2550f alpha10f cgcolor nil buttonlayer insertsublayerbtngradient atindex0,"['ios', 'objective-c']" +440943,subview appears underneath superviews layerborder i have a uiview in which i define it is border in the following manner selflayerbordercolor uicolor blackcolorcgcolor selflayerborderwidth 3i attach a subview to this uiview and when i move the subview over the border it goes underneath it is this the intended behavior is there anyway to make the subview go on top of it,"['iphone', 'ios']" +441062,remove all whitespaces from string but keep one newline i have this input string containg tabs spaces linebreaks that is a test seems to work pretty good working another test againedit i should have provided the string for better testing as stackoverflow removes all special characters tabs string testcontent ntntntdas ist ein test ntsoweit scheint das ttganze zu funktionierenttnttnt nt and tn tnoch ein testn tn tn tand i want to reach this statethat is a testseems to work pretty good workinganother test againstring expectedoutput das ist ein testnsoweit scheint das ganze zu funktionierenoch ein testnany ideas can this be achieved using regexesreplacealls is not what i am looking for if this regex would preserve exactly 1 newline of the ones existing it would be perfecti have tried this but this seems suboptimal to mebufferedreader bufreader new bufferedreadernew stringreadertestcontentstring line nullstringbuilder newstring new stringbuilderwhile line bufreaderreadline null string temp linereplacealls if temptrimequals newstringappendtemptrim newstringappendn,['java'] +441066,what is the difference between dependencyresolversetresolver and httpconfigurationdependecyresolver in webapi i have existing project which uses autofac as ioc in the registration code i have these linesvar resolver builderbuilddependencyresolversetresolvernew autofacdependencyresolverresolverconfigdependencyresolver new autofacwebapidependencyresolverresolverso my question is what is the difference between dependencyresolversetresolver and httpconfigurationdependecyresolver why should i assign both of them,['c#'] +441108,textarea value undefined when using getelementsbytagname i stuck in a very simple thing that i need to do and i cannot explain why is this happening i have a textarea with no id or class or name so the only way of selecting it with js is to use getelementsbytagname it is the only textarea in my html so it is pretty obvious to use the followingvar thesrc documentgetelementsbytagnametextarea0valuehowever when alerting thesrc i always get undefined any ideas why is this happeningheres the demo,['javascript'] +441129,how to log in utf8 using enterpriselibrarylogging i am kind of stuck with my searches concerning enterpriselibraryloggingi have a listener and formatter set up like thisadd namenormalloglistener typemicrosoftpracticesenterpriselibraryloggingtracelistenersrollingflatfiletracelistener microsoftpracticesenterpriselibrarylogging listenerdatatypemicrosoftpracticesenterpriselibraryloggingconfigurationrollingflatfiletracelistenerdata microsoftpracticesenterpriselibrarylogging filenamelogsmvc22log footer formattershortlogformatter header rollintervalday timestamppatternymmdd maxarchivedfiles14 add typemicrosoftpracticesenterpriselibraryloggingformatterstextformatter microsoftpracticesenterpriselibrarylogging templatetimestamplocal severity category message nameshortlogformatter i use this in multiple projects and it is working fineexcept for one thing i want enterpriselibrary to create my log file with utf8encoding i get ansi files per default but unfortunately i have no clue how to do thati have special characters in strings that i want to be able to log into my file such as umlauts i see the logging works fine when i convert my file to utf8 and let it be used further but i really want to have it created that waycan this be done in the xml configuration or somewhere elsethanks for any help in advance,['c#'] +441138,change input placeholder color darker follow this article style text input placeholder i can change the color of the text input placeholder to red color but it is always a lightred color not red exactly is there any way to make it a red color exactlyupdatethe color on chrome is red this is correct the color on firefox is not red it is lightred or blurred i guessed thatedit from the op answerplease check this example the color is red on chrome but lightred on firefoxi want the color on firefox same with the chrome,['css'] +441145,trapezoid in html with css3 gradient applied to it i want to make a trapezoid in html5 i know it can be done using border radius and a height of 0trapezoid borderbottom 100px solid red borderleft 50px solid transparent borderright 50px solid color here height 0 width 100pxhowever i want to apply a css3 gradient and the above method only allows solid colorsthe following style will make a parallelogram but is there a way to skew only one of the sides instead of bothwebkittransform skew20deg,['html'] +441157,what does t stands for in a cstring what does the t represents in a string for example thelloi have seen this in projects where unicode support is neededwhat it actually tells the processor,['c++'] +441183,stdstring operations ie stol stoi not found ndk8d i try to set up my first android project using ndk r8d with c11 supportsome c11 mechanisms work fine ie lambada expressions but when i tryto use one of the new string operations the compile fails error stol is not a member of std here are myproject settingsapplicationmkapp modules mylib app cppflags stdgnu0x app cppflags frttiapp cppflags fexceptionsapp cppflags ddebug app abi armeabiv7aapp platformandroid14 app stl gnustl staticapp gnustl cpp features rtti exceptionsndk toolchain version47are those functions actually not working,['android'] +441193,find in stdvector i have a vector of pairs the first in the pair is of type stdstring and the second is of type containerwhat convenient functionality exists in std or boost so that i can return a container given the string value as key updateit has been commented that i could use a stdmap instead but i actually need to preserve the order of my items in the order that i push them to the vector,['c++'] +441220,how to achieve inset shadow effect in wpf i have designed an interface in html and wish to translate this into wpf but am having troubles with inset shadowboxshadow inset 0 2px 7px 0 rgba0 0 0 05the effect im looking for is here in this jsfiddle how can i translate this into wpf exactlyupdatewhat i currently have based on richards answer is below its still not showing a shadow thoughborder gridrow1 cornerradius3 gridcolumn0 margin130120 borderthickness0 borderbrushd2d2d2 cliptoboundstrue backgroundf0f0f0 border backgroundtransparent borderbrushblack cornerradius3 borderthickness0 margin0 bordereffect dropshadoweffect shadowdepth2 blurradius7 colorblack direction270 opacity05 bordereffect borderborder,['.net'] +441232,protecting extra data in android intent i am using an intent to start a new activity in a new task this intent carries some private data needed by that activity in its extras this data should not be readable by other applicationsweve investigated whether this data is indeed not leaked we found out that by using recenttaskinfo from getrecenttasks this extra data is readable by any arbitrary application that has get task permissionthis is not very secureweve stopped searching once we found this leak are there more ways this data is leakedand how can i ensure the data in the extra is not readable by other applications,['android'] +441240,string literal in templates different behavior of compilers suppose we have the following codetemplate typename tvoid fooconst tint main foostrdemonstrationgcc 472 clang 32 icc 1301undefined reference to void foochar 4char const 4msvc110unresolved external symbol void cdecl foochar const 4char const 4 fooby03cbdyaxaay03cbdznotice char4 in the first output and char const4 in the second outputwhy and whos right can you quote the standard please,['c++'] +441241,open specific view when opening app from notification i have just added push notifications to my app i am wanting to have so that when a user opens the app from a notification it will open a specific view controller and not my rootviewcontroller any help would be greatly appreciated here is my appdelegateimport kfbappdelegatehimport kfbviewcontrollerhimport aboutushimport contactushimport kyfbhimport kfbnavcontrollerviewcontrollerhimport kfbtabbarviewcontrollerhimport rsfmhimport legislatorinfohimport eventshimport actionalertsviewcontrollerhimport uairshiphimport uapushhimport uaanalyticshimplementation kfbappdelegate boolapplicationuiapplication application didfinishlaunchingwithoptionsnsdictionary launchoptions this prevents the ua library from registering with uiapplcation by default when registerforremotenotifications is called this will allow you to prompt your users at a later time this gives your app the opportunity to explain the benefits of push or allows users to turn it on explicitly in a settings screen if you just want everyone to immediately be prompted for push you can leave this line out uapush setdefaultpushenabledvalueno create airship options dictionary and add the required uiapplication launchoptions nsmutabledictionary takeoffoptions nsmutabledictionary dictionary takeoffoptions setvaluelaunchoptions forkeyuairshiptakeoffoptionslaunchoptionskey call takeoff which creates the uairship singleton passing in the launch options so the library can properly record when the app is launched from a push notification this call is required populate airshipconfigplist with your apps info from uairship takeofftakeoffoptions set the icon badge to zero on startup optional uapush shared resetbadge register for remote notfications with the ua library this call is required uapush shared registerforremotenotificationtypesuiremotenotificationtypebadge uiremotenotificationtypesound uiremotenotificationtypealert handle any incoming incoming push notifications this will invoke handlebackgroundnotification on your uapushnotificationdelegate uapush shared handlenotificationlaunchoptions valueforkeyuiapplicationlaunchoptionsremotenotificationkey applicationstateapplicationapplicationstate selftabbarcontroller uitabbarcontroller alloc initwithnibnamekfbviewcontroller bundlenil kfbviewcontroller rootview kfbviewcontroller alloc initwithnibnamekfbviewcontroller bundlenil kfbnavcontrollerviewcontroller navcontroller kfbnavcontrollerviewcontroller alloc initwithrootviewcontrollerrootview navcontrollerdelegate rootview uiviewcontroller aboutus aboutus alloc initwithnibnameaboutus bundlenil kfbnavcontrollerviewcontroller navcontroller1 kfbnavcontrollerviewcontroller alloc initwithrootviewcontrolleraboutus uiviewcontroller contactus contactus alloc initwithnibnamecontactus bundlenil kfbnavcontrollerviewcontroller navcontroller2 kfbnavcontrollerviewcontroller alloc initwithrootviewcontrollercontactus uiviewcontroller kyfb kyfb alloc initwithnibnamekyfb bundlenil kfbnavcontrollerviewcontroller navcontroller3 kfbnavcontrollerviewcontroller alloc initwithrootviewcontrollerkyfb uiviewcontroller rsfm rsfm alloc initwithnibnamersfm bundlenil kfbnavcontrollerviewcontroller navcontroller4 kfbnavcontrollerviewcontroller alloc initwithrootviewcontrollerrsfm uiviewcontroller li legislatorinfo alloc initwithnibnamelegislatorinfo bundlenil kfbnavcontrollerviewcontroller navcontroller5 kfbnavcontrollerviewcontroller alloc initwithrootviewcontrollerli uiviewcontroller events events alloc initwithnibnameevents bundlenil kfbnavcontrollerviewcontroller navcontroller6 kfbnavcontrollerviewcontroller alloc initwithrootviewcontrollerevents selfwindow uiwindow alloc initwithframeuiscreen mainscreen bounds selfviewcontroller kfbviewcontroller alloc initwithnibnamekfbviewcontroller bundlenil selfwindowrootviewcontroller selfviewcontroller selftabbarcontroller kfbtabbarviewcontroller alloc init selftabbarcontrollerviewcontrollers navcontroller navcontroller1 navcontroller2 navcontroller3 selftabbarcontrollercustomizableviewcontrollers nil selfwindowrootviewcontroller selftabbarcontroller selfwindowbackgroundcolor uicolor whitecolor selfwindow makekeyandvisible return yes voidapplicationwillresignactiveuiapplication application sent when the application is about to move from active to inactive state this can occur for certain types of temporary interruptions such as an incoming phone call or sms message or when the user quits the application and it begins the transition to the background state use this method to pause ongoing tasks thisable timers and throttle down opengl es frame rates games should use this method to pause the game voidapplicationdidenterbackgrounduiapplication application use this method to release shared resources save user data invalidate timers and store enough application state information to restore your application to its current state in case it is terminated later if your application supports background execution this method is called instead of applicationwillterminate when the user quits voidapplicationwillenterforegrounduiapplication application called as part of the transition from the background to the inactive state here you can undo many of the changes made on entering the background voidapplicationdidbecomeactiveuiapplication application restart any tasks that were paused or not yet started while the application was inactive if the application was previously in the background optionally refresh the user interface ua ldebugapplication did become active set the icon badge to zero on resume optional uapush shared resetbadge voidapplicationwillterminateuiapplication application called when the application is about to terminate save data if appropriate see also applicationdidenterbackground uairship land voidapplicationuiapplication application didregisterforremotenotificationswithdevicetokennsdata devicetoken updates the device token and registers the token with ua uapush shared registerdevicetokendevicetoken voidapplicationuiapplication application didfailtoregisterforremotenotificationswitherrornserror error ua lerrfailed to register for remote notifications with error error voidapplicationuiapplication application didreceiveremotenotificationnsdictionary userinfo ua linforeceived remote notification userinfo send the alert to ua so that it can be handled and tracked as a direct response this call is required uapush shared handlenotificationuserinfo applicationstateapplicationapplicationstate optionally provide a delegate that will be used to handle notifications received while the app is running uapush shareddelegate your custom push delegate class conforming to the uapushnotificationdelegate protocol reset the badge after a push received optional uapush shared resetbadgensuintegerapplicationuiapplication application supportedinterfaceorientationsforwindowuiwindow window return uiinterfaceorientationmaskallbutupsidedownendand here is the view controller i want to open when opening a notificationimport actionalertsviewcontrollerhimport rsschannelhimport rssitemhimport webviewcontrollerhimport customcellbackgroundhimplementation actionalertsviewcontroller uiactivityindicatorview loadingindicatorsynthesize webviewcontroller voidviewdidload selftableview uitableview alloc initwithframecgrectzero styleuitableviewstylegrouped selftitle action alerts loadingindicator uiactivityindicatorview alloc initwithactivityindicatorstyleuiactivityindicatorviewstylegray loadingindicatorcenter cgpointmake160 160 loadingindicatorhideswhenstopped yes selfview addsubviewloadingindicator loadingindicator startanimating uirefreshcontrol refresh uirefreshcontrol alloc init refreshattributedtitle nsattributedstring alloc initwithstringpull to refresh refresh addtargetself actionselectorrefreshviewforcontroleventsuicontroleventvaluechanged selfrefreshcontrol refresh voidparsernsxmlparser parser didstartelementnsstring elementname namespaceurinsstring namespaceuri qualifiednamensstring qname attributesnsdictionary attributedict nslog found a element self elementname if elementname isequalchannel if the parser saw a channel create new instance store in our ivar channel rsschannel allocinit give the channel object a pointer back to ourselves for later channel setparentparserdelegateself set the parsers delegate to the channel object parser setdelegatechannel nsintegertableviewuitableview tableview numberofrowsinsectionnsintegersection return 0 nslogchannel items d channel itemscount return channel itemscount uitableviewcell tableviewuitableview tableview cellforrowatindexpathnsindexpath indexpath return nil uitableviewcell cell tableview dequeuereusablecellwithidentifieruitableviewcell if cell nil cell uitableviewcell allocinitwithstyleuitableviewcellstyledefault reuseidentifieruitableviewcell celltextlabelfontuifont systemfontofsize160 rssitem item channel itemsobjectatindexindexpath row cell textlabelsettextitem title cellbackgroundview customcellbackground alloc init cellselectedbackgroundview customcellbackground alloc init celltextlabelbackgroundcolor uicolor clearcolor celltextlabelhighlightedtextcolor uicolor darkgraycolor return cell voidfetchentries create a new data container for the stuff that comes back from the service xmldata nsmutabledata allocinit construct a url that will ask the service for what you want note we can concatenate literal strings together on multiple lines in this way this results in a single nsstring instance nsurl url nsurl urlwithstring put that url into an nsurlrequest nsurlrequest req nsurlrequest requestwithurlurl create a connection that will exchange this request for data from the url connection nsurlconnection allocinitwithrequestreq delegateself startimmediatelyyes idinitwithstyleuitableviewstylestyle self super initwithstylestyle if self self fetchentries return self this method will be called several times as the data arrives voidconnectionnsurlconnection conn didreceivedatansdata data add the incoming chunk of data to the container we are keeping the data always comes in the correct order xmldata appenddatadata voidconnectiondidfinishloadingnsurlconnection conn we are just checking to make sure we are getting the xml nsstring xmlcheck nsstring allocinitwithdataxmldata encodingnsutf8stringencoding nslogxmlcheck xmlcheck loadingindicator stopanimating create the parser object with the data received from the web service nsxmlparser parser nsxmlparser allocinitwithdataxmldata give it a delegate ignore the warning here for now parser setdelegateself tell it to start parsing the document will be parsed and the delegate of nsxmlparser will get all of its delegate messages sent to it before this line finishes execution it is blocking parser parse get rid of the xml data as we no longer need it xmldata nil reload the table for now the table will be empty nsmutablearray notactionalerts nsmutablearray array for rssitem object in channelitems if objectisactionalert notactionalerts addobjectobject for rssitem object in notactionalerts channelitems removeobjectobject self tableviewreloaddata nslogn n n channel channel title channel infostring voidconnectionnsurlconnection conn didfailwitherrornserror error release the connection object were done with it connection nil release the xmldata object were done with it xmldata nil grab the description of the error object passed to us nsstring errorstring nsstring stringwithformatfetch failed error localizeddescription create and show an alert view with this error thisplayed uialertview av uialertview allocinitwithtitleerror messageerrorstring delegatenil cancelbuttontitleok otherbuttontitlesnil av show voidtableviewuitableview tableview didselectrowatindexpathnsindexpath indexpath push the web view controller onto the navigation stack this implicitly creates the web view controllers view the first time through self navigationcontrollerpushviewcontrollerwebviewcontroller animatedyes selfnavigationcontroller pushviewcontrollerwebviewcontroller animatedno grab the selected item rssitem entry channel itemsobjectatindexindexpath row construct a url with the link string of the item nsurl url nsurl urlwithstringentry link construct a request object with that url nsurlrequest req nsurlrequest requestwithurlurl load the request into the web view webviewcontroller webviewloadrequestreq webviewcontrollerhackyurl url set the title of the web view controllers navigation item webviewcontroller navigationitemsettitleentry title voidrefreshviewuirefreshcontrol refresh refreshattributedtitle nsattributedstring alloc initwithstringrefreshing data custom refresh logic would be placed here nsdateformatter formatter nsdateformatter alloc init formatter setdateformatm d hmm a nsstring lastupdated nsstring stringwithformatlast updated on formatter stringfromdatensdate date refreshattributedtitle nsattributedstring alloc initwithstringlastupdated refresh endrefreshingendhere is the chunk of code i have added to my didfinishlaunchingwithoptions method i have gotten almost everything working the web views work now when selecting a row and the navigation bar is there and seemingly works as it should the only trouble i am having now is getting the tab bar to show up here is the chunk of code i am currently usinguilocalnotification notification launchoptions objectforkeyuiapplicationlaunchoptionsremotenotificationkey if notification actionalertsviewcontroller actionalerts actionalertsviewcontroller alloc initwithstyleuitableviewstyleplain webviewcontroller wvc webviewcontroller allocinit actionalerts setwebviewcontrollerwvc kfbnavcontrollerviewcontroller navcontroller7 kfbnavcontrollerviewcontroller alloc initwithrootviewcontrolleractionalerts selfwindowrootviewcontroller presentviewcontrollernavcontroller7 animatedno completionnil,['ios'] +441250,android url override does not work on redirect i have a url that i am overriding in my android app clicking a link from an email to that link pops up the intent chooser dialog complete this using however clicking the same link in an a tag from within chrome on android 4 redirects me to that url and does not offer the intent chooser if i replace the link in the a tag with a link to the google play store then clicking the link pops up the intent chooser again is there something special with the google play store and chrome or have i done something wrong configuring my url is there something i can do in html to make this workheres the intentfilteractivity androidlabelstringapp name androidname intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter intentfilter action androidnameandroidintentactionview category androidnameandroidintentcategorydefault category androidnameandroidintentcategorybrowsable data androidschemehttps androidhostwexamplecom data androidschemehttp androidhostwexamplecom intentfilteractivityredirecting to the url also does not pop up the intent chooser dialog but i figured my situation above more pointedly expresses my issuealso of note i am fairly certain this was all working while my domain was down as soon as my domain came online this stopped working this could be a figment of my imagination as i was not 100 focused on this problem at the time is it possible that chrome treats google play store urls special otherwise it waits for a non200 response from a url before opening the intent chooser,['android'] +441319,delete many rows from a table using id in mysql i am a linux admin with only basic knowledge in mysql queries i want to delete many table entries which are ip address from my table using idcurrently i am using delete from tablename where id1delete from tablename where id2but i have to delete 254 entriesso this method is going to take hourshow can i tell mysql to delete rows that i specifycoz i want to skip deleting some entries out of this 254deleting whole table and importing needed entries is not an option,"['mysql', 'sql']" +441323,openmp conditional pragma if else i have a for loop that can be executed using schedulestatic or scheduledynamic 10 depending on a condition currently my code is not dry do not repeat yourself enough and to accommodate the previous functionality it has the following repetitionboolean isdynamic can be true or falseifisdynamic pragma omp parallel for num threadsthread count defaultshared private scheduledynamic 10 for for code inside else pragma omp parallel for num threadsthread count defaultshared private schedulestatic for same for code inside in fact this is the exact same for as before after reading these threads i noticed that openmp has an ifexpression pragmaopenmp conditional use of pragmachoose openmp pragma according to conditionconditional pragma ompbut although i have seen many people with my problem there seems to be lacking a general solution the best solution is to transform the body of the for loop into a function and then have the function called but this solution is not good enough for me so i wonder does openmp have an ifexpression else sort of pragmasomething likeifisdynamic pragma omp parallel for num threadsthread count defaultshared private scheduledynamic 10 else pragma omp parallel for num threadsthread count defaultshared private schedulestaticor am i forced to place my for loop body into a separate function and call it that way,['c++'] +441339,check if image is in cache universal image loader i guess the title says it all i tried imageloadergetmemorycachegetkey with the image uri as key but it always return nullalthough i enabled caching in the config,['android'] +441341,release build contains extra files do i need these i built my program with visual studio 2012 express binrelease contains some other files as well as the exe do i need to thistribute these filesmyappexeconfigmyapdbmyappvshostexemyappvshostexeconfigmyappvshostexemanifest,"['c#', '.net']" +441431,trouble introducing a variable timestep i am currently in university doing computer games programming in the process of creating a physics engine in ci have been asked to introduce a timestep via the gettickcount method despite the inaccuracies as it is suitable for the current depth that were going into time steppingmy problem is that now i have introduced timestep based movement the objects that have been drawing to screen through two different overrides of an update function do not seem to workthrough adding breakpoints in the code it looks as if melapsedtime does not seem to get passed any value and i am stumpedsorry if this post is too wordy or some is off topic i tried to provide as much context as possible and this is my first post any help is appreciatedframestarttime parameter just takes a tick count before the frame is updated and drawnedit melapsed time of type float for easier multiplication in the updates of the particle class eg posx velocityx timestep and this is the reason for the cast from an unsigned long to a float is it still redundantvoid simulationgameloopdelaydword framestarttime dword presetframeinterval 16 dword frameprocessingtime gettickcount framestarttime if frameprocessingtime presetframeinterval sleeppresetframeinterval frameprocessingtime melapsedtime floatframeprocessingtime 10f,['c++'] +441461,how can i add a sub folder to the raw folder in my android app of course i can right click the raw folder and add new folder but when i export the project the apk file does not contain the new sub folder,['android'] +441470,resteasy client proxy overhead i am creating a resteasy service using client proxies and it works fine so far however i did notice that in a few of my functions i see the same line of codemyclass client proxyfactorycreatemyclassclass httplocalhost8080is it better to take that out of the functions and make it a member variable of the class to reduce possible overhead this service will handle load of 10 reqsmin thanks,['java'] +441494,does stdmt19937 require warmup i have read that many pseudorandom number generators require many samples in ordered to be warmed up is that the case when using stdrandom device to seed stdmt19937 or can we expect that it is ready after construction the code in questioninclude randomstdrandom device rdstdmt19937 genrd,['c++'] +441560,why does 103100 2 but 103100 1 in python why does 103100 2 but 103100 1 in python i cannot seem to understand why,['python'] +441586,how to insert a new line character in a string to printstream then use a scanner to reread the file i have several classes designed to simulation a book catalog i have a book class isbn title etc a booknode class a bookcatalog which is a linkedlist of books and a driver class guimy problem is that i have a tostring method in bookcatalog that supposed to return a string representation of all the books the book class also overrides tostring i am supposed to have each field of the book separated by a tab and each book separated by a new line when i try to use printstream to print the book catalog to a txt file the and does not registeri have tried to change it to systemgetpropertylineseparator which thisplays the bookcatalog correctly but now i have a problem where the scanner will not read the file correctly and throws a nosuchelementexception how do i get the scanner to 1 ignore the lineseparator or 2 have printstream use nbookjavapublic string tostring return isbntlastnametfirstnamettitletyeart stringformat2fpricebookcatalogjavapublic string tostring booknode current front string s systemoutprintlns while currentnull each book is listed on separate line scurrentgetdatatostringn systemgetpropertylineseparator current currentgetnext return s driverjavapublic void loaddirectory throws filenotfoundexception if fexists scanner input new scannerf while inputhasnextline string bookline inputnextline processbooklinebookline public void processbooklinestring line scanner input new scannerline string isbn inputnext string lastname inputnext string firstname inputnext string title inputnext while inputhasnext inputhasnextintwhile next token is not an integer title inputnext int year inputnextint double price inputnextdouble book book bookcreatebookisbn lastname firstname title year price if booknull catalogaddbook,['java'] +441587,get path object from file is it possible to get a path object from a javaiofilei know you can convert a path to a file using tofile method but i could not find the opposite conversion is there a way to do this in java 6 or lower,['java'] +441604,access mat file containing matlab classes in python i have a mat file generated from matlab 2012b it contains a variable with a userdefined matlab classwhen loading the file using scipyioloadmat in python 33 i get the followingmatscipyioloadmatdtestmatmat header bmatlab 50 matfile platform pcwin64 created on fri feb 22 152628 2013 function workspace array 0 1 73 0 0 0 dtypeuint8 globals version 10 none matlabopaque bfutureds bmcos bcstream 3707764736 2 1 1 1 1 dtypes0 o s1 o s2 o arr oi am looking to access the futureds object of type cstream but seem unable to do so using matnone calling matnone simple results inmatlabopaque bfutureds bmcos bcstream 3707764736 2 1 1 1 1 dtypes0 o s1 o s2 o arr oi am stuck here i am new to python and trying to port my old work from matlab any help would be appreciatedthank you,['python'] +441619,how to compare lists using fluentassertions i want to compare a list of objects ignoring the order of the objects in the list and only comparing some of the properties in the objects currently i am using the following code to perform this comparison actualshouldnotbenullactualcountshouldbeexpectedcountcompare ignoring orderforeach var exp in expected actualshouldcontainact actindividualidequalsexpindividualid actemailequalsexpemail actfirstnameequalsexpfirstname actlastnameequalsexplastname however this seems less than ideal as when there is a failure you do not get a print out of the expected values is there a built in mechanism for performing this comparison using fluent assertions,['c#'] +441622,where are the int and string classes defined int a 0int b new int3consolewriteline agettype consolewriteline bgettype the type of a is systemint32 which is a structthe type of b is inti can see the definition of int32 in visual studio where is the definition of int located,['c#'] +441630,toolprovidergetsystemjavacompiler returns null usable with only jre installed i am trying to use the javacompiler class when i call toolprovidergetsystemjavacompiler it returns null i think this is because i am using a jre instead of a jdkthe problem is i want it to run on all platforms regardless of weather the user is using a jre or a jdk if anyone knows how to fix this or an alternative method to use please comment any help would be appreciated,['java'] +441698,check multiple values exists php array i have an array in phppermission array admin moderator guest and i have another arrayuserroles array admin moderator i checked with in array but it does not work with multiple valueshow can i check atleast one value in userroles exists on permission without looping thanks in advance,['php'] +441762,how do cursorloader automatically updates the view even if the app is inactive i have been working on a small todo list app i used cursorloader to update the todolistview from a content provider i have a written a function onnewitemadded which is called when user enters a new item in the text view and clicks enter refer below public void onnewitemaddedstring newitem contentresolver cr getcontentresolver contentvalues values new contentvalues valuesputtodocontentproviderkey task newitem crinserttodocontentprovidercontent uri values getloadermanagerrestartloader0 null this commented for the sake of testing override protected void onresume superonresume getloadermanagerrestartloader0 null this commented for the sake of testing public loadercursor oncreateloaderint id bundle args cursorloader loader new cursorloaderthis todocontentprovidercontent uri null null null null logegopal in the oncreateloader return loader public void onloadfinishedloadercursor loader cursor cursor int keytaskindex cursorgetcolumnindexorthrowtodocontentproviderkey task logegopal in the onloadfinished todoitemsclear ifcursormovetonextfalse logegopal empty cursor else while cursormovetonext todoitem newitem new todoitemcursorgetstringkeytaskindex todoitemsaddnewitem aanotifydatasetchanged aa is arrayadapter used for the listview i have read cursorloader automatically updates the view whenever there is a data change in the content provider db that means i suppose getloadermanagerrestartloader0 null this has to be called implicitly whenever there is a change in data right but that is not happening whenever i add a new item the item is added to the db from onnewitemadded but restartloader is not explicitly called pause this activity and resume it back i do not see any implicit call to restartloadereven though db is changed and the listview also is not updated with new item added why is that how does a cursorloader automatically updates the view even if app is not activethanks edit i have also used getcontextgetcontentresolvernotifychangeinsertedid null in insert of my content provider,['android'] +441764,if 123 10 0 returns false i recently came across what seems to puzzle my logic of maths in a piece of codeif12310 0for some reason c is claiming that this is false but if one were to think logically 0123 is larger than 0is there any reason that it is claiming that 0123 is smaller than 0i have read that there will be a comparison issue with double that is base 2 and it would be better to use decimal which is base 10could someone enlighten me,['c#'] +441808,how to run a callback function on a jquery triggerclick i need to trigger a custom event in the callback of a trigger call but i cannot get it to worki tried thisvar input uipopupcontainer find input eq2function runtests consolelogclicked the inputinputtriggerclick runtests and thisvar input uipopupcontainer find input eq2inputtriggerclick function consolelogclicked the inputneither of which worksquestionhow do i get a callback function to run when i am triggering a click on an element,"['javascript', 'jquery']" +441813,how is android database cursor implemented in details i am interesting about the implementation details of the cursor in android i know that basically it is just an interface that provides random readwrite access to the result set returned by a database query i wonder about the particular cursor implementationsis it a some kind of data structure which stores result set from databaseor it is just a structure which handles only one row,"['java', 'android']" +441844,thisplaying a fan page in a uiwebview with an authenticated user session using facebooks access token were developing an app for ios and android that has a rather odd requirement one of the tabs of the app opens up the clients facebook page so heres our desired functionalitythe user logs in using facebooks sdks for iphone and androidwe retrieve the access token and our application flow startswhen the user clicks the facebook page tab we load a uiwebview pointing to the url of facebook pagethe user should be able to interact with the facebook page right awayso what happens is steps 13 work normally however because this uiwebview has not been authenticated on facebook before it does not have a valid session hence the user is required to login again in this web view in order to interact with the pageis there a way to use the token that we have from the facebook login process when loading the uiwebview in order to avoid having to sign in againthanks,"['android', 'objective-c']" +441850,initializing entire 2d array with one value with the following declaration int arrayrowcolumn0i get the array with all zeroes but with the following oneint arrayrowcolumn1i donat get the array with all one value the default value is still 0why this behavior and how can i initialize with all 1edit i have just understood that using memset with value as 1 will set each byte as 1 and hence the actual value of each array cell wont be 1 but 16843009 how do i set it to 1,['c'] +441855,google warning resource interpreted as font but transferred with mime type applicationoctetstream i have a warning in google for my fontfaceresource interpreted as font but transferred with mime type applicationoctetstream contentfontsiconfontfit works even if i have this warning but i prefer avoid this warning here is my declarationfontface fontfamily iconfont src urlfontsiconfonteotiefix formatembeddedopentype urlfontsiconfontsvgiconfont formatimagesvgxml urlfontsiconfontwoff formatfontxwoff urlfontsiconfontf formattruetype fontweight normal fontstyle normali already search on other posts but no luck so farplease note that my server is iis from microsoftany idea how can i avoid this warningthanks,['css'] +441859,info illegal access this web application instance has been stopped already could not load javanetinetaddress i am experiencing this kind of exception can someone help me about this problemjavalangillegalstateexceptionat orgapachecatalinaloaderwebappclassloaderloadclasswebappclassloaderjava1566at orgapachecatalinaloaderwebappclassloaderloadclasswebappclassloaderjava1526at orgquartzutilsupdatecheckergetclientidupdatecheckerjava149at orgquartzutilsupdatecheckerbuildparamsstringupdatecheckerjava120at orgquartzutilsupdatecheckerbuildupdatecheckurlupdatecheckerjava114at orgquartzutilsupdatecheckerdocheckupdatecheckerjava55at orgquartzutilsupdatecheckercheckforupdateupdatecheckerjava47at orgquartzutilsupdatecheckerrunupdatecheckerjava39at javautiltimerthreadmainloopunknown sourceat javautiltimerthreadrununknown sourcei am also getting the same exception with could not load javaneturlencoder and could not load javaneturlconnection i am using eclipse indigo sr1 and tomcat v60,['java'] +441873,call method after 5 millisecond how to call record method after 5 millisecond playing audio with mediaplayer i tried something like that but i do not know and i did not find any good examples to end thiswhilempisplaying ifrecord0 forint i0 i5millisec i how to define 5 millisec or is any better solution startrecord record1 mpstopmpreleasempnull,['android'] +441918,how to safely call an async method in c without await i have an async method which returns no datapublic async task myasyncmethod do some stuff async do not return any datai am calling this from another method which returns some datapublic string getstringdata myasyncmethod this generates a warning and swallows exceptions return hello worldcalling myasyncmethod without awaiting it causes a because this call is not awaited the current method continues to run before the call is completed warning in visual studio on the page for that warning it statesyou should consider suppressing the warning only if youre sure that you do not want to wait for the asynchronous call to complete and that the called method would not raise any exceptionsi am sure i do not want to wait for the call to complete i do not need to or have the time to but the call might raise exceptionsi have stumbled into this problem a few times and i am sure it is a common problem which must have a common solutionhow do i safely call an async method without awaiting the resultupdatefor people suggesting that i just await the result this is code that is responding to a web request on our web service aspnet web api awaiting in a ui context keeps the ui thread free but awaiting in a web request call will wait for the task to finish before responding to the request thereby increasing response times with no reason,['c#'] +441938,permgen space error when deploying tomcat 7 i installed tomcat 7 to upgraded my jira projeect version from 50 to 6 after i place the project folder in tomcats webapps i run this localhost8080jiraafter long time running it throws some error message please help us to fix this problem thanks in advancejavalangruntimeexception permgen space at comatlassianeventinternalsingleparametermethodlistenerinvokerinvokesingleparametermethodlistenerinvokerjava54 at comatlassianeventinternalasynchronousableeventthispatcher2runasynchronousableeventthispatcherjava66 at comatlassianeventinternalasynchronousableeventthispatcher1executeasynchronousableeventthispatcherjava32 at comatlassianeventinternalasynchronousableeventthispatcherthispatchasynchronousableeventthispatcherjava60 at comatlassianeventinternaleventpublisherimplinvokelistenerseventpublisherimpljava160 at comatlassianeventinternaleventpublisherimplpublisheventpublisherimpljava79 at comatlassianplugineventimpldefaultplugineventmanagerbroadcastdefaultplugineventmanagerjava84 at comatlassianpluginmanagerdefaultpluginmanageraddpluginsdefaultpluginmanagerjava768 at comatlassianpluginmanagerdefaultpluginmanagerinitdefaultpluginmanagerjava200 at comatlassianjirapluginjirapluginmanagerstartjirapluginmanagerjava63 at comatlassianjiracomponentmanagerpluginsystemstartcomponentmanagerjava635 at comatlassianjiracomponentmanagerstartjiracomponentmanagerjava214 at comatlassianjiracomponentmanagerquickstartcomponentmanagerjava208 at comatlassianjiracomponentmanagerstartcomponentmanagerjava193 at comatlassianjiraupgradepluginsystemlauncherstartpluginsystemlauncherjava23 at comatlassianjirastartupdefaultjiralauncher3rundefaultjiralauncherjava107 at comatlassianjiraconfigdatabasedatabaseconfigurationmanagerimpldonoworenqueuedatabaseconfigurationmanagerimpljava323 at comatlassianjiraconfigdatabasedatabaseconfigurationmanagerimpldonoworwhendatabaseactivateddatabaseconfigurationmanagerimpljava211 at comatlassianjirastartupdefaultjiralauncherpostdblaunchdefaultjiralauncherjava100 at comatlassianjirastartupdefaultjiralauncheraccess100defaultjiralauncherjava27 at comatlassianjirastartupdefaultjiralauncher1rundefaultjiralauncherjava66 at comatlassianjirautildevspeedjiradevspeedtimerrunjiradevspeedtimerjava33 at comatlassianjirastartupdefaultjiralauncherstartdefaultjiralauncherjava61 at comatlassianjirastartuplaunchercontextlistenercontextinitializedlaunchercontextlistenerjava54 at orgapachecatalinacorestandardcontextlistenerstartstandardcontextjava4797 at orgapachecatalinacorestandardcontextstartinternalstandardcontextjava5291 at orgapachecatalinautillifecyclebasestartlifecyclebasejava150 at orgapachecatalinacorecontainerbaseaddchildinternalcontainerbasejava901 at orgapachecatalinacorecontainerbaseaddchildcontainerbasejava877 at orgapachecatalinacorestandardhostaddchildstandardhostjava633 at orgapachecatalinastartuphostconfigdeploydescriptorhostconfigjava657 at orgapachecatalinastartuphostconfigdeploydescriptorrunhostconfigjava1637 at javautilconcurrentexecutorsrunnableadaptercallunknown source at javautilconcurrentfuturetasksyncinnerrununknown source at javautilconcurrentfuturetaskrununknown source at javautilconcurrentthreadpoolexecutorrunworkerunknown source at javautilconcurrentthreadpoolexecutorworkerrununknown source at javalangthreadrununknown sourcecaused by javalangoutofmemoryerror permgen space,['java'] +441963,service vs intentservice can someone please show me an example of something that can be done with an intentservice that cannot be done with a service and viceversai also believe that an intentservice runs in a different thread and a service does not so as far as i can see starting a service within its own thread is like starting an intentservice is it noti would appreciate if someone can help me with both of my questions,['android'] +441996,overloading generic methods when calling a generic method for storing an object there are occasionally needs to handle a specific type differently i know that you cannot overload based on constraints but any other alternative seems to present its own problemspublic bool savett entity where t class some storage logic what i would like to do is something like the followingpublic bool savespecificclasst entity special logic in the past our team has created oneoff methods for saving these classes as followspublic bool savespecificclaspecificclass sc special logic however if you do not know that function exists and you try to use the generic save then you may run into a host of problems that the oneoff was supposed to fix this can be made worse if a new developer comes along sees the problem with the generic and decides he is going to fix it with his own oneoff functionsowhat are the options for working around this seemingly common issuei have looked at and used unitofwork and right now that seems to be the only option that actually resolves the problem but seems like attacking a fly with a sledgehammer,['c#'] +442009,efficient computation of a power of 2 i have a requirement to compute k as the smallest power of 2 which is an integer value n n is always 0currently i am usingdefine log2x logxlog2define roundx intx05k roundpow2ceillog2nthis is in a performance critical functionis there a more computationally efficient way of calculating k,['c'] +442096,is this a good technique using data holder to eliminate anonymous class to reduce memory leak risk anonymous class can easily cause memory leak especially in android world where activity or fragment can suddenly destroyed due to configuration changes here are one of many examples leaks made easythe reason is that creating an anonymous class in activity or fragment the anonymous class will always hold an implicit reference to the activity or fragment so when activity tends to go out of life due to configuration changes it cannot be garbage collected if the anonymous class is being exposed and hold by outside worldso i was wondering whether using a data holder technique is a good way to completely eliminate anonymous class to reduce risk of memory leakage or am i over paranoidusing anonymous classpublic class homemenufragment private parcelable selectedinfo null private listview homemenurows new arraylistview private void fun rowsetonclicklistenernew onclicklistener override public void onclickview arg0 homemenurows is member variable for view r homemenurows rsetselectedfalse rowsetselectedtrue selectedinfo is member variable selectedinfo watchlistinfo refactor using data holder techniquepublic class homemenufragment private static class holder public parcelable selectedinfo null public final listview homemenurows new arraylistview private final holder holder new holder private static class myonclicklisnter implements onclicklistener private final holder holder private final linearlayout row private final watchlistinfo watchlistinfo public myonclicklisnterholder holder linearlayout row watchlistinfo watchlistinfo thisholder holder thisrow row thiswatchlistinfo watchlistinfo override public void onclickview arg0 for view r holderhomemenurows rsetselectedfalse rowsetselectedtrue holderselectedinfo watchlistinfo private void fun rowsetonclicklistenernew myonclicklisnterholder row watchlistinfo,"['java', 'android']" +442097,different mvc4 action based on get variable is there a way to get mvc4 to call different actions based on a get variable in the urlfor example let us say i have the following two actionshttppostpublic actionresult submitcrashcrashreport rawdata return viewhttppostpublic actionresult submitbugbugreport data return viewis there a way i can use the following urls to have mvc4 choose which action to callhttpmysitesubmitcrash calls submitcrash httpmysitesubmitbug calls submitbugupdatei am very much aware that i can use actions urls the way they are and do stuff with routing to make it happen which is what i am doing now but i am really interested in the get vars part of the question,['c#'] +442101,java thread sleep and interrupted exception why does a sleep thread need a try catch to catch interrupted exceptionwhy does a sleep even emit an interrupted exception errorthis are the two questions i really wanna find out about in java programmingi have been searching through google and i have still have not found a clear explanation is to why this two things happen,['java'] +442143,html textarea ignores 1st new line character why could you explain why thisscript typetextjavascript documentwritetextarea cols10 rows10 nhellonbaben textareascriptrenders a textarea with one new line at the bottom but no new line at the toptested ie8 ff11 safari 51 chrome 24and it is not a js issue even when you write html in page you get the same result ietextarea cols10 rows10hellobabetextareathe 1st new line is still missingi need to add another new line at the top in order to show onedocumentwritetextarea cols10 rows10 nnhellonbaben textarea,"['javascript', 'html']" +442145,aspnet mvc 4 clientside validation not working i am using visual studio 2012 and i cannot get a custom attribute client side logic to workto reproduce at a smaller scale i created a new mvc 4 project i created the following model and attribute that will never validatepublic class mymodel public int id get set required public string lastname get set nevervaliderrormessageserverside will never validate public string firstname get set public class nevervalidattribute validationattribute iclientvalidatable public override bool isvalidobject value return false protected override validationresult isvalidobject value validationcontext validationcontext return new validationresultthiserrormessage new validationcontextmembername public ienumerablemodelclientvalidationrule getclientvalidationrulesmodelmetadata metadata controllercontext context yield return new modelclientvalidationrule errormessage thiserrormessage validationtype nevervalid i then have the following actions added to the homecontrollerpublic actionresult index return viewnew mymodelhttppostpublic actionresult indexmymodel model if modelstateisvalid will always be invalid return viewmodelthere is also a javascript file called nevervalidjsfunction validatoraddmethodnevervalid function return false clientside should not postback validatorunobtrusiveadaptersaddboolnevervalidand the index viewmodel customattributemodelsmymodel viewbagtitle home pageusing htmlbeginform htmlvalidationsummarytrue fieldset legendmymodellegend htmlhiddenformodel modelid div classeditorlabel htmllabelformodel modellastname div div classeditorfield htmleditorformodel modellastname htmlvalidationmessageformodel modellastname div div classeditorlabel htmllabelformodel modelfirstname div div classeditorfield htmleditorformodel modelfirstname htmlvalidationmessageformodel modelfirstname div p input typesubmit valuesave p fieldsetsection scripts scriptsrenderbundlesjqueryval scriptsrenderscriptsnevervalidjsthe relevant areas in my webconfig look like thisappsettings add keywebpagesversion value20 add keywebpagesenabled valuefalse add keypreserveloginurl valuetrue add keyclientvalidationenabled valuetrue add keyunobtrusivejavascriptenabled valuetrue appsettingswhen the page loads the following files are loaded got this from network tab under chromes f12httplocalhost7440httplocalhost7440contentsitecsshttplocalhost7440scriptsmodernizr253jshttplocalhost7440scriptsjquery171jshttplocalhost7440scriptsjqueryunobtrusiveajaxjshttplocalhost7440scriptsjqueryvalidatejshttplocalhost7440scriptsjqueryvalidateunobtrusivejshttplocalhost7440scriptsnevervalidjsand my custom attribute adds relevant looking data stuff to the first name input like so input classtextbox singleline valid datavaltrue datavalnevervalidserverside will never validate idfirstname namefirstname typetext valueso i ask you why oh why does this thing have to postback to do serverside validation while i have some perfectly looking javascript code here do i have to sacrifice some animal on a moonless night on top of a hill somewhere,"['jquery', 'asp.net']" +442153,handling time in a textbased game java i am trying to work up a basic textbased game as i am learning java i would like to be able to count rounds in the game as a means of managing the pacing of certain events for instance changing rooms could be limited to once per round a second in the test code a small creature might attack or change rooms at a higher rate whereas a larger one might be more cumbersome good so far greatso i cooked this up and immediately realized that i would be hitting a block each time the while loop waited for the player to input a command codeprivate void startplaying declare clockround variables int lastround 0 int currentround 0 long lasttime systemcurrenttimemillis long currenttime while playergetisplaying clocking currenttime systemcurrenttimemillis if lasttime 10 currenttime lasttime currenttime lastround currentround currentround systemoutprintlncurrent roundt currentround tcurrent timet currenttime editnote this is just a test line to observe the loop end if clocking command command new command string commandstring commandsetall array gets parsed elsewhere playerdocommandcommandstring class player extends pawn extends actor pawn has most command methods finishplayingend startplayingso here is my question is there a way i could use a separate method to log timerounds concurrent to the while loop presenting the player with a command promptif not is there a different way to make this a nonissue that i am just not seeingpracticed in yet,['java'] +442167,what would be a hello world example for stdref can somebody give a simple example which demonstrates the functionality of stdref i mean an example in which some other constructs like tuples or data type templates are used only if it is impossible to explain stdref without themi found two questions about stdref here and here but in the first one it goes about a bug in a compiler and in the second one examples of use of stdref do not contain stdref and they involve tuples and data type templates which make understanding of these examples complex,['c++'] +442184,method to show native datepicker in chrome i use input typedate fields that gracefully fallback to jquery when the browser does not have support for the field relatively recently chrome started offering a native date picker which is great but i have found that many users miss the little arrow that brings up the calendar and therefore miss the fact that there is an easy calendar for date selectionto make this more intuitive it would be great if i could bring up the native datepicker ui when the user moves the focus to the input or clicks another element like a small calendar iconis there a method that i can use in chrome to trigger the datepicker ui,"['javascript', 'html']" +442199,error in gae with ndb badqueryerror cannot convert falsenode to predicate i have an application running on google app engine with pythonmodel classes extend from ndb googleappengineextndb classesone of my views makes async calls to the database something more or less like exerciselistlog is a ndb model class start current end current are dates student id is a string contents is a list of keysexercise log query exerciselistlogqueryndbandexerciselistlogcreation start current exerciselistlogcreation end current exerciselistloguser id student idexercise log query exercise log queryfilterexerciselistlogcontentincontentsfuture exercise log querycount asynccount futureget result this throws badqueryerrorthis is throwing an error on get resultbadqueryerror cannot convert falsenode to predicatebut it only happens when i deploy my code to the google cloud when i run it locally it works finei have no idea what this error means and looking it up on google is not helping muchanyone knows whats wrong hereheres the full stacktrace from gaes logstraceback most recent call last file basedatahomeappssqmagtest1366092357976105290zenwebgaeconventionpy line 48 in make convention methodargs kwargs file basedatahomeappssqmagtest1366092357976105290corewebqmhandlerpy line 48 in wrapper return methodself args kwargs file basedatahomeappssqmagtest1366092357976105290coreuserloginsecuritypy line 36 in wrapper methodself args kwargs file basedatahomeappssqmagtest1366092357976105290coreusersecuritypy line 17 in wrapper methodself args inner kwargs file basedatahomeappssqmagtest1366092357976105290pluginswebdesempenhoestatisticaspy line 127 in class activities school classcontent file basedatahomeappssqmagtest1366092357976105290pluginswebdesempenhoestatisticaspy line 178 in get exercise video and total weekly series exercise log count exercise count futuresiget result file python27 runtimepython27 libversions1googleappengineextndbtaskletspy line 325 in get result selfcheck success file python27 runtimepython27 libversions1googleappengineextndbtaskletspy line 371 in help tasklet along value gensendval file python27 runtimepython27 libversions1googleappengineextndbquerypy line 1227 in count async dsquery self get queryconn file python27 runtimepython27 libversions1googleappengineextndbquerypy line 873 in get query filters filters to filter file python27 runtimepython27 libversions1googleappengineextndbquerypy line 599 in to filter for node in self nodes file python27 runtimepython27 libversions1googleappengineextndbquerypy line 600 in genexpr if isinstancenode postfilternode post file python27 runtimepython27 libversions1googleappengineextndbquerypy line 425 in to filter cannot convert falsenode to predicatebadqueryerror cannot convert falsenode to predicate,['python'] +442244,multi criteria sorting of a list of objects with guava ordering i have a class which cannot implement comparable but needs to be sorted based on 2 fields how can i achieve this with guavalet us say the class is class x string stringvalue javautildate datevalue and i have a list of these listx lotsofxi want to sort them based on the value field first and then based on datevalue descending within each group of value fieldswhat i have been doing so far is listx sortedlist immutablelistcopyoforderingnaturalonresultofdatevaluesortfunctionreversesortedcopylotsofxsortedlist immutablelistcopyoforderingnaturalonresultofstringvaluesortfunctionsortedcopysortedlistthe functions are defined aspublic class datevaluesortfunctionx implements functionx long override public long applyx input return inputgetdatevaluegettime returns millis time andpublic class stringvaluesortfunctionx implements functionx integer override public integer applyx input ifinputgetstringvalueequalsignorecasesomething return 0 else ifinputgetstringvalueequalsignorecasesomething else return 1 else return 2 expected output in sortedlist issomething 03182013something 03172013something else 03202013something else 03192013my approach works but is obviously inefficient for traversing the list twice is there a better way of doing thisnote using this in a gwt app implementing comparable is not an option,['java'] +442298,phonegap build how to open external url in device browser on android external urls do not open in the systems browser in my phonegap android application i am using phonegap build 230 according to the cordova documentation i used target systemwindowopen systemin my configxml i haveplugin nameinappbrowser valueorgapachecordovainappbrowser access origin browseronlytrue but still the links open in my apps webview how to solve this,"['javascript', 'android']" +442312,installing ruby 20 and rails 400beta on aws ec2 installing ruby 200 and rails 400beta1 on the default amazon ec2 linux install amazon linux ami 2012091 goes smoothlybut openssl gets in the way eg and weird either prevent openssl from getting installed or causing the rubygem package manager from installing railshow can i work around these problems,['ruby-on-rails'] +442315,how to solve boostbad any cast failed conversion using boostany cast when using boost program options using boost program options to read command line and config file data include boostprogram optionshpp using namespace std using namespace boost namespace po boostprogram optionsint main int argc char argv pooptions description configconfiguration configadd options ipaddressiip address portpport povariables map vm postorepoparse command lineargc argv configvm ponotifyvm cout valuesn string address vmipaddressasstdstring c str string port vmportasstdstringc str cout vmipaddressas string c str cout vmportasstringc str return 0are the inputted values somehow unprintablehere is gdb output seems to be be cast problemterminate called after throwing an instance of boostexception detailclone impl what boostbad any cast failed conversion using boostany cast program received signal sigabrt aborted 0x03afd835935 in raise from lib64libcso6string address vmipaddressasstdstring c stris where the error occurs i have tried stdstring and string with the same resultstestboostpo i 192168110 p 50is the command linei tried declaring the types like soconfigadd options ipaddressi povaluestdstring ip address portp povaluestdstring portbut the error still occurredcould this be a genuine bug,['c++'] +442318,python popen write to stdout and log file simultaneously i am using popen to call a shell script that is continuously writing its stdout and stderr to a log file is there any way to simultaneously output the log file continuously to the screen or alternatively make the shell script write to both the log file and stdout at the same time i basically want to do something like this in pythoncat file 21 tee a logfile cat file will be replaced with some scriptagain this pipes stderrstdout together to tee which writes it both to stdout and my logfile i know how to write stdout and stderr to a logfile in python where i am stuck is how to duplicate these back to the screensubprocesspopencat file shelltrue stdoutlogfile stderrlogfileof course i could just do something like this but is there any way to do this without tee and shell file descriptor redirectionsubprocesspopencat file 21 tee a logfile shelltrue,['python'] +442319,db2 sql convert decimal to character pad with zeros how can i convert db2 decimal11 from 12345678 to character value 012345678,['sql'] +442360,using list with azure table storage i am currently making use of the windows azure table storage mechanism having a class which extends tableentity however one of the fields of this class is a list when getting the entity back from the table it is returned as a dynamictableentity rather than a normal table entity is there a way to obtain the list from the table rather than serializing the list and storing it on a blob,['.net'] +442367,linq firstordefault then select i have the following linq query that fires and exception when the firstordefault returns null ideally i would like to avoid the null check is there a way to do this i wish to return 0 if there are no cpoffsets that satisfy the firstordefault calldouble offset orderedoffsetsfirstordefaulto ooffsetdatetime cptimecpoffsetthe only way i can see to achieve this is the followingcpoffset cpoffset orderedoffsetsfirstordefaulto ooffsetdatetime cptimedouble offset cpoffset null cpoffsetcpoffset 0is there another more succinct way using select after the firstordefault does not compile but i thought might be appropriate here,['c#'] +442378,invoke method in objective c code from html code using uiwebview i have html file in my ios app html file has few div blocks with onclick methodswhen i tap on these blocks i invoke some javascript code in web view but i need also know about these events in my source codefor example when i tap on web element and onclick is called i need to invoke some method in the code eg voiddidtouchedwebelementwithidcan i do this stuff thanks,"['javascript', 'ios']" +442400,is doing transaction management in the controller bad practice i am working on a phpmysql app using the yii frameworki have come across the following situationin my videocontroller i have a actioncreate which creates a new video and actionprivacy which sets the privacy on the video the problem is that during the actioncreate the setprivacy method of the video model is called which currently has a transaction i would like the creation of the video to be in a transaction as well which leads to an error since a transaction is already activein the comment on this answer bill karwin writes so there is no need to make domain model classes or dao classes manage transactions just do it at the controller leveland in this answersince youre using php the scope of your transactions is at most a single request so you should just use containermanaged transactions not servicelayer transa that is start the transaction at the start of handling the request and commit or rollback as you finish handling the requestif i manage the transactions in the controller i would have a bunch of code that looks likepublic function actioncreate trans yiiappgetdbbegintransaction action code transcommitthat leads to duplicated code in a lot of places where i need transactions for the actionor i could refactor it into the beforeaction and afteraction methods of the parent controller class which would then automatically create transactions for each action being performedwould there be any problems with this method what is a good practice for transaction management for a php app,"['php', 'mysql']" +442466,in c is it better to cap a value using stdmin or an if branch a very common pattern in programming is to cap a value at a maximum after some kind of update what i would like to know is if there is a difference between the following two pieces of code and if one should be preferredvalue incrementvalue stdminvalue valuemaxvsvalue incrementif value valuemax value valuemaxmy thinking is that this comes down to whether cpus have instructions for taking two values and producing the minumum if so the call to stdmin should result in this instruction and avoid an unnecessary branch if not the second version avoids an unnecessary assignment when value valuemaxi am not very good with this kind of thing but i am sure there is oldschool assembly hackers who would know this to them i ask which is better,['c++'] +442501,jw player is not working in ie 8 i am just checking jw players in compatibility with all browser but not even a blank screen is coming in ie 8 browser in other browsers it works welli have already read the link jwplayer not working for internet explorer 8 but could not get any helphtmlheadscript typetextjavascript srcjwplayerjsscriptheadbodyscriptifwindowouterwidth windowouterwidth 640 documentbodyclientwidth documentbodyclientwidth 640alerterror scriptdiv idmyelementloading the player divscript typetextjavascript jwplayermyelementsetup file myvideomp4 image myposterjpg scriptul li onclickjwplayerplaystart playbackli li onclickalertjwplayergetvolumeget audio volumeli li onclickjwplayerpausepauseliulbodyhtml,['javascript'] +442532,how grunt watch files in sub folders my codes folders and files like this you never know how many sub folders in itjssub1ajsjssub2bjsjssub3sub31cjsjssub4sub41sub411djshere is part of the gruntfilejsgruntinitconfig watch src files jsjs tasks grunt cannot watch the changes of my all javascript files by using jsjs so how to write the correct file path expression,['javascript'] +442533,template argument deductionsubstitution failed when using stdfunction and stdbind i have a compile error when using stdfunction in a templated member function the following code is a simple exampleinclude functionalinclude memoryusing stdfunctionusing stdbindusing stdshared ptrclass test public template typename t void setcallbackfunctionvoid t int cb template typename tvoid testsetcallbackfunctionvoid t int cb do nothingclass testa public void testaint a int b int main testa testa test test testsetcallbackbindtestatesta testa stdplaceholders 1 stdplaceholders 2 return 0and come with the following compile errortesttemplatecpp in function aint mainatesttemplatecpp2992 error no matching function for call to atestsetcallbackstd bind helperint int testa const std placeholder1 const std placeholder2typeatesttemplatecpp2992 note candidate is testtemplatecpp107 note template void testsetcallbackstdfunctiontesttemplatecpp107 note template argument deductionsubstitution failedtesttemplatecpp2992 note astd bindtesta std placeholder1 std placeholder2a is not derived from astdfunctionai am using c11 and g 47,['c++'] +442575,javalangnoclassdeffounderror comgoogleapiclientgoogleapisextensionsandroidgmsauthgoogleaccountcredential i am trying to implement google drive in my android applciation and getting javalangnoclassdeffounderror comgoogleapiclientgoogleapisextensionsandroidgmsauthgoogleaccountcredential error so anyone who know how to solve thisi tried still nowsuccessfully import all the jar required for google drive import google play service lib in my project successfullytried to restart eclipse and check but same error is cominggot an api key and client id from google drive api or play service for androidalready visit some solution as hereand trying same as herehere is my logcat 0321 150355194 eandroidruntime940 fatal exception main0321 150355194 eandroidruntime940 javalangnoclassdeffounderror comgoogleapiclientgoogleapisextensionsandroidgmsauthgoogleaccountcredential0321 150355194 eandroidruntime940 at comexamplealltaskassgoogledriveoncreategoogledrivejava530321 150355194 eandroidruntime940 at androidappinstrumentationcallactivityoncreateinstrumentationjava10480321 150355194 eandroidruntime940 at androidappactivitythreadperformlaunchactivityactivitythreadjava170321 150355194 eandroidruntime940 at androidappactivitythreadhandlelaunchactivityactivitythreadjava17520321 150355194 eandroidruntime940 at androidappactivitythreadaccess1500activitythreadjava1230321 150355194 eandroidruntime940 at androidappactivitythreadhhandlemessageactivitythreadjava9930321 150355194 eandroidruntime940 at androidoshandlerthispatchmessagehandlerjava990321 150355194 eandroidruntime940 at androidoslooperlooplooperjava1260321 150355194 eandroidruntime940 at androidappactivitythreadmainactivitythreadjava39970321 150355194 eandroidruntime940 at javalangreflectmethodinvokenativenative method0321 150355194 eandroidruntime940 at javalangreflectmethodinvokemethodjava4910321 150355194 eandroidruntime940 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava8410321 150355194 eandroidruntime940 at comandroidinternaloszygoteinitmainzygoteinitjava5990321 150355194 eandroidruntime940 at dalviksystemnativestartmainnative methodbut still i am stuck for this errorand dont know how to solve this please guide methank you in advance,['android'] +442581,what happens when all activities of an application finishes scenarioi have four activities in my android application lets say a b c and d there is one constantsjava class in the app which extends application class in order to maintain global application state the constants class have all the constants variables of the app the activity flow is like this abcd when back button is being pressed from activity a i am calling finish method which will finishes the activity a and closes the application after that if i am opening the app from all apps there is a variable in constantsjava whose value persists from the last launch the same thing is not happening when i am doing systemexit10 followed by processkillprocessprocessmypid from activity aon back pressedquestionswill finishing all activities by calling finish of each activity will close the applicationits processhow the value of a variable persists even if its all activities are finishedclosed is it fair to call systemexit10 followed by processkillprocessprocessmypid for exiting the applicationupdatehow can i clear the application constants on exit of the applicationback press of the homeactivity,['android'] +442627,how to fix invalid byte 1 of 1byte utf8 sequence i am trying to fetch the below xml from db using a java method but i am getting an errorcode used to parse the xmldocumentbuilderfactory dbf documentbuilderfactorynewinstancedocumentbuilder db dbfnewdocumentbuilderinputsource is new inputsourcenew bytearrayinputstreamcondgetbytesdocument doc dbparseiselement elem docgetdocumentelement here we expect a series of datanamennamevaluevvaluedatanodelist nodes elemgetelementsbytagnamedatatableid jobid new tableid processinstanceidjob myjob jobquerybyid clientcontext jobid trueif nodesgetlength 0 logleveldebug no data found on condition xmlfor int i 0 i nodesgetlength i loop through the data in the xml element datatags element nodesitemi string name getchildtagvaluedatatags name string value getchildtagvaluedatatags value loglevelinfo userdatavalue name value myjobsetbulkuserdataname valuemyjobsavethe datacontactdetails307896043contactdetailscontactname307896043contactnamepreferred completion datepreferred completion dateservice addressaend address 1st helierst helierjt2 3xp832the cables 1 poonha lanest helier je jt2 3xpservice addreserviceorderid315473043serviceorderidserviceordertypeid50serviceordertypeidcustdesireddate20130320t181204custdesireddateorderid307896043orderidcreatewhocsmusercreatewhoaccountinternalid201003accountinternalidserviceinternalid20766093serviceinternalidserviceinternalidresets0serviceinternalidresetsprimary offer name actiondelmymobile blue 1634499 12 month termprimary offer namethisc reason actiondel8thisc reasonsup offer actiondel80257sup offerservice type actiondela0100service typepriority actiondel4priorityaccount number actiondel0account numberoffer actiondel80257offermsisdn actiondel447797142520msisdnimsi actiondel234503184imsisim actiondel5535simocb9 arm actiondelfalseocb9 armport in required actiondelport in requiredocb9 mob actiondelnoneocb9 mobocb9 mob bb actiondelocb9 mob bbocb9 landline actiondelocb9 landlineocb9 landline bb actiondelocb9 landline bbcontact 2contact 2acc middle nameacc middle namemarketcode7marketcodeacc last nameport outacc last namecontact 1contact 1acc first nameacc first nameemaiidemaiidthe error orgapachexercesimpliomalformedbytesequenceexception invalid byte 1 of 1byte utf8 sequencei read in some threads it is because of some special characters in the xmlhow to fix this issue,['java'] +442684,modify default value in sql server i am trying to change the default value of a column using a sql statement in sql server 2008 i have found in many places how to set the default value when you create a tableadd a column but not how to set itmodify it once the column already existsthis is what i can use to set it on addingalter table mytable add mycolumn int not null default 0and that works but if i try to modify it lateralter table mytable alter column mycolumn int not null default 1alter table mytable alter column mycolumn int not null set default 1none of those are syntactically correct and i do not find the syntax to do what i pretend anywhere the only option i come with is to add a new column copy values from previous column then remove previous column and new column to make the change but that does not seem right to meis there a way of doing what i want in just one simple sentencethanks,['sql'] +442716,php namespaces with curly braces vs without php offers two syntaxes for declaring namespaces it can be done without bracesnamespace foobarclass anyor with bracesnamespace foobar class anywhat difference in behaviour if any is there between these two syntaxes and is there any reason to favour one over the other,['php'] +442791,how to get transparent background of webview for 40 version i am looking for a piece of code which is able to get a transparent background in a webview for version 40 and above my code is working fine with version 23 but it is getting a white background when i run it on version 40 and 42 i am providing my code which is working for version 23 but not in 40 and 42 please help me thanks in advancein xmlwebview androidididwebview androidlayout margintop6dp androidlayout belowidimage androidlayout widthmatch parent androidlayout heightfill parent androidhardwareaccelerated true in activity filewebview webview findviewbyidridwebviewbackbutton imageview findviewbyidridbackbuttonwebviewsetbackgroundcolor0 webviewloadurlfileandroid assetinfohtmlwebviewsetbackgroundcolorcolortransparent this is used to make the background white after loading the file on screen,['android'] +442801,efficient screenshots of a view tldr since getdrawingcache seems to trigger a complete redraw of a view when hardware acceleration is enabled is there an alternative means of getting a bitmap or something along those lines that avoids this perhaps by reading data populated into a hardware software layer when the view was last drawnsome backgroundandroid has had the ability to mirror the screen since android 30 such as to an attached hdmi thisplay this can be used for presentations but it means the audience sees the same thing as the presenter which is not always idealandroid 42 added presentation to allow apps to put arbitrary stuff on the second screen eg hdmi attached thisplay in this case at times it would be useful for the second screen to be showing part of what is on the main tablet us thisplay if you think of presentation software like microsoft powerpoint libreoffice impress and the like in typical dualscreen setups the audience sees the current presentation slide while the presenter sees the current slide and a timer and speaker notes andfor noninteractive content like a png representing a slide this is simply a matter of showing the same image in both screens alongside other stuff on the primary screenhowever for interactive content like a webview it is sometimes difficult to do this sort of mirroring for example we have no good way of knowing when the content of a webview might change as it may do so based on stuff purely within the webview itself eg completion of ajax calls not something we do separately and even if we did know when the content of the webview changed we have no good way of getting some other webview to render that same contentso i figured i would try to set up a mirroringframelayout that would use getdrawingcache to retrieve a bitmap of the containers contents and deliver that to somebody who can render it onscreen eg an imageview shown in a presentationhowever with hardware acceleration enabled setdrawingcacheenabledtrue is somewhat of a noopenabling the drawing cache is similar to setting a layer when hardware acceleration is turned off when hardware acceleration is turned on enabling the drawing cache has no effect on rendering because the system uses a different mechanism for acceleration which ignores the flag calling getdrawingcache in these cases forces a full draw of the view to a bitmapbacked canvas rather than actually using a cache since draw may be expensive doing draw frequently say triggered via postonanimation results in jankhence i am trying to determine if there is some other drawing cache beyond getdrawingcache that we can use with hardware acceleration enabled that could be used to set up this mirroring and that is more efficient from what i can see there is no such cache as layers are effectively writeonly from the standpoint of sdk apps however i am hoping that perhaps i am missing some solutionthanks in advance,['android'] +442838,is this a safe way of throwing an exception from a destructor i know that throwing from a destructor is in general a bad idea but i was wondering if i could use stduncaught exception to safely throw from a destructorconsider the following raii typestruct raiitype raiitype do stuff if somethingbadhappened assume that if an exception is already active we do not really need to detect this error if stduncaught exception throw stdruntime errordata corrupted is this ub in c11 is it a bad design,['c++'] +442840,dom xpath to find text nodes and wrap in paragraph tag i would like to find all rootlevel text nodes or those with div parents which should be wrapped inside a p tag in the following text there should be three or even just two final root p tagsdiv this text should be wrapped in a p tagdivthis also should be wrappedbandb thisthe idea is to format the text nicer so that text blocks are grouped into paragraphs for html thisplay however the following xpath i have been working out seems to fail to select the text nodes phphtml div this text should be wrapped in a p tagdivthis also should be wrappedbandb thislibxml use internal errorstruedom domdocumentloadhtmlhtmlxp new domxpathdomxpath textnotparentp and normalizespaceforeachxpqueryxpath as node element domcreateelementp nodeparentnodereplacechildelement node elementappendchildnodeprint domsavehtml,"['php', 'html']" +442854,how to see preparedstatements sql string when we create a preparedstatement we use chars to then be replaced by setted parameters how can we see the final sql string after these parameters are set,['java'] +442861,replace a textnode with html text in javascript i was directed to the linkify project on github for finding and linkifying urls and domains just floating in textit is awesome it totally works on texthowever i am not quite sure how to make it work on a textnode which has the text i want to linkifyi understand the textnode only has textcontent since it is all text since this linkify function returns html as text is there a way to take a textnode and rewrite the html within it with the linkify outputi have been playing with it on jsfiddle here function replnode var nodesnodechildnodesfor var i0 mnodeslength im i var nnodesi if nnodetypentext node do some swappy text to html here ntextcontent linkifyntextcontent else repln,"['javascript', 'html']" +442923,javafx stop opening url in webview open in browser instead the embedded webview browser i am using needs special handling for particular urls to open them in the native default browser instead of webview the actual browsing part works fine but i need to stop the webview from thisplaying that page as well i can think of several ways to do it but none of them work here is my codethiswvgetenginelocationpropertyaddlistenernew changelistenerstring override public void changedobservablevalue extends string observable string oldvalue string newvalue desktop d desktopgetdesktop try uri address new uriobservablegetvalue if addressgetquery indexof openmodaltrue 1 wvgetengineloadoldvalue 1 wvgetenginegetloadworkercancel 2 wvgetengineexecutescripthistoryback 3 dbrowseaddress catch ioexception urisyntaxexception e thisplayerrore a bit more info about what happens in each of three cases1 loading the previous addresswvgetengineloadoldvaluethis kills the jvm funnily enough the page opens fine in the native browser a fatal error has been detected by the java runtime environment exception access violation 0xc05 at pc0x05b8fef38 pid7440 tid80 jre version 70 09b05 java vm java hotspottm 64bit server vm 235b02 mixed mode windowsamd64 compressed oops problematic frame c jfxwebkitdll0x2fef38 java com sun webpane platform backforwardlist bflitemgeticon0x184f58 failed to write core dump minidumps are not enabled by default on client versions of windows an error report file with more information is saved as cusersgreg balagaeclipsecompanyapphs err pid7440log if you would like to submit a bug report please visit the crash happened outside the java virtual machine in native code see problematic frame for where to report the bug2 cancelling the workerwvgetenginegetloadworkercanceldoes nothing the page loads in both the webview and native browser3 using historybackwvgetengineexecutescripthistorybacksame as above no effect4 reacting to stage changes insteadi have also tried to instead of looking the locationproperty of webengine listen on chenges for stateproperty of the worker and fire the same opening code if newstate statescheduled there was no difference in result from previous method apart from not actually being able to use 1updatethe code i am using now still crashes the jvmthiswvgetenginelocationpropertyaddlistenernew changelistenerstring override public void changedobservablevalue extends string observable final string oldvalue string newvalue desktop d desktopgetdesktop try uri address new urinewvalue if addressgetquery indexof openmodaltrue 1 platformrunlaternew runnable override public void run wvgetengineloadoldvalue dbrowseaddress catch ioexception urisyntaxexception e thisplayerrore workaroundok i managed to make it work by tearing down the webview and rebuilding itthiswvgetenginelocationpropertyaddlistenernew changelistenerstring override public void changedobservablevalue extends string observable final string oldvalue string newvalue desktop d desktopgetdesktop try uri address new urinewvalue if addressgetquery indexof openmodaltrue 1 platformrunlaternew runnable override public void run grid layoutgetchildrenremovewv wv new webview grid layoutaddwv 0 1 wvgetengineloadoldvalue dbrowseaddress catch ioexception urisyntaxexception e thisplayerrore,['java'] +442931,android intentgetstringextra returns null this is how strings are being added to extrasintent i new intentiputextraname edt namegettextiputextradescription edt descgettextiputextrapriority skb priorgetprogresetresultresult ok ifinishthis is how i try to extract them in onactivityresultstring name datagetstringextranamestring desc datagetstringextradescriptionint prior datagetintextrapriority 50but after the second code block name and desc are nulls though prior has it is proper valuemoreover in debugger i can see that datamextrasmmap contains needed strings but only after first request to it,['android'] +442940,python sqlalchemy label usage i know i can use the label method for alias but i cannot figure out how to use the labeled element later in the query something like the followingsessionqueryfoobarlabelfoobarfilterfoobar 10allof course this does not work since there is no variable called foobar how could this be accomplishedthe over simplified example was just for easy comprehension,['python'] +443027,php how to get internal arguments given the commandusrbinphp c pathtocustomphpini pathtoscriptphpi would like to get the internal optionsc pathtocustomphpinithings i have tried that do not workargv contains pathtoscriptphpgetoptc contains env does not contain it server does not contain iti have also looked for a php constant such as php binary but cannot find one for these argumentsis there any way to get these arguments note that i am not trying to obtain the loaded ini file but any arguments that might be present here,['php'] +443106,implement singletap and doubletap in objectivec i add singtap and doubletap to a view like the code belowvoidawakefromnib self setuserinteractionenabledyes uitapgesturerecognizer doubletapgesture uitapgesturerecognizer alloc initwithtargetself actionselectorhandledoubletapgesture doubletapgesturenumberoftapsrequired 2 self addgesturerecognizerdoubletapgesture uitapgesturerecognizer singletapgesture uitapgesturerecognizer alloc initwithtargetself actionselectorhandlesingletapgesture singletapgesturenumberoftapsrequired 1 self addgesturerecognizersingletapgesturevoidhandlesingletapgestureuitapgesturerecognizer singletapgesture self delegate singletaponviewvoidhandledoubletapgestureuitapgesturerecognizer doubletapgesture self delegate doubletaponviewwhen doubletap the singletap also fire how to thisable singletap when doubletap thanks,"['ios', 'objective-c']" +443126,createwindowsurface failed egl bad match the version android is 221 the device is a samsung galaxy ii the full crash log isjavalangruntimeexception createwindowsurface failed egl bad matchat androidopenglglsurfacevieweglhelperthroweglexceptionglsurfaceviewjava1077at androidopenglglsurfacevieweglhelpercreatesurfaceglsurfaceviewjava981at androidopenglglsurfaceviewglthreadguardedrunglsurfaceviewjava1304at androidopenglglsurfaceviewglthreadrunglsurfaceviewjava16this is the relevant code to the crashoverride public void oncreatebundle savedinstancestate superoncreatesavedinstancestate requestwindowfeaturewindowfeature no title getwindowsetflagswindowmanagerlayoutparamsflag fullscreen windowmanagerlayoutparamsflag fullscreen glview new glsurfaceviewthis glviewseteglconfigchooser8 8 8 8 16 0 glviewsetrendererthis setcontentviewglview etci used seteglconfigchooser because the app would crash on api17 if it wasnt in there so for this specific device that it is crashing on i been looking around and it has something to do with the pixelformat for the devicewhat im wondering is how can i use some code so this will not crash on the samsung galaxy ii android version 221 i cant test this in an emulator and i dont have the device to test it in i just need for sure code and im not sure how to change it up,['android'] +443138,when should i use a linear algebra library like mathnet i am not certain there is one correct answer to the question but here we go while numerous numerical problems can be stated in a linear algebra form it seems from my limited experience that there is a performance overhead for simple operations in using mathnet over writing equivalent operations on raw arrays as a test case i wrote code to compute the thistance between a vector and the closest vector in a list with 3 versions operating on arrays operating on dense vectors and operating on dense vectors with the mkl provider working on arrays ran about 4x faster than on vectors and 3x faster than using the mkl provider the downside is that i had to write by hand a thistance computation instead of leveraging the builtin norm function the upside is that it is much faster note i did not post the code will be happy to do so if needed i might also be using mathnet improperly so my question is as follows it seems to me that using higherlevel abstractions comes at a performance cost is that in general the case or are there situations like sparse matrices for instances where using mathnet would be expected to outperform manually written operations on arrays if that is the case i would tend to think that using the linear algebra part of mathnet would be mostly useful for real algebra that involves matrices to avoid reimplementing more complex calculationsalgorithms and potentially for code readability but that for operations which are more simple vector by vector operations it might be a better idea to work on raw arrays any light on when it is a good idea to use the library vs when you should roll your own would be appreciated,['.net'] +443141,php datew vs mysql yearweeknow can someone kindly explain me why these two give different resultsi execute this with phpdateywmktime0 0 0 3 22 2013 outputs 201312and when i execute this with mysqlselect yearweeknow outputs 201311,"['php', 'mysql']" +443143,how to set back default uisegmentedcontrol appearance i have set the appearance of uisegmentedcontrol using following codeuiimage segmentselected uiimage imagenamedsegment unselectedpng resizableimagewithcapinsetsuiedgeinsetsmake0 12 0 12uiimage segmentunselected uiimage imagenamedsegment selectedpng resizableimagewithcapinsetsuiedgeinsetsmake0 12 0 12uisegmentedcontrol appearance setbackgroundimagesegmentunselected forstateuicontrolstatenormal barmetricsuibarmetricsdefaultuisegmentedcontrol appearance setbackgroundimagesegmentselected forstateuicontrolstateselected barmetricsuibarmetricsdefaultuisegmentedcontrol appearance settitletextattributesnsdictionary dictionarywithobjectsandkeys uicolor colorwithred7702550 green4502550 blue802550 alpha1uitextattributetextcolor uicolor clearcolor uitextattributetextshadowcolor nsvalue valuewithuioffsetuioffsetmake0 0 uitextattributetextshadowoffset uifont fontwithnamehelveticaneuebold size160 uitextattributefont nil forstateuicontrolstatenormaluisegmentedcontrol appearance settitletextattributesnsdictionary dictionarywithobjectsandkeys uicolor whitecoloruitextattributetextcolor uicolor clearcolor uitextattributetextshadowcolor nsvalue valuewithuioffsetuioffsetmake0 0 uitextattributetextshadowoffset uifont fontwithnamehelveticaneuebold size160 uitextattributefont nil forstateuicontrolstateselecteduisegmentedcontrol appearance setdividerimageuiimage imagenamedsegmentedcontrol dividerpng forleftsegmentstateuicontrolstatenormal rightsegmentstateuicontrolstatenormal barmetricsuibarmetricsdefaultand i got the perfect output but now i want to set default appearance of uisegment likeso what i have to do,"['ios', 'iphone', 'objective-c']" +443205,scikit learn svm how to saveload support vectors using python scikit svm after running clffitx y you get your support vectorscould i load these support vectors directly passing them as paramter when instantiate a svmsvc object which means i do not need to running fit method each time to do predication,['python'] +443216,change the text not background color of a spinner when an item is selected i have a spinner with several options each thisplaying a simple string initially the text is all white however if the user selects an option causing it to become what is thisplayed on top i would like that text to become red how can i do thisedit solved public void onitemselectedadapterview parent view view int pos long id textview arg1settextcolorcolorparsecolore3170d,['android'] +443289,what is a good alternative of ltrim and rtrim in java what is a good alternative of javascript ltrim and rtrim functions in java,['java'] +443315,what is the difference between hostfactoryrun and hostfactorynew i have a need to use topshelf in the project i am in and have a simple question i hope everything works just fine when i am using hostfactoryrun but i thought that it seemed more reasonable to use hostfactorynew by just reading the name on the function and that is used here apihtmlhowever in the more simple example the hostfactoryrun is used insted of hostfactorynew so what is the difference,['.net'] +443318,confused when boostasioio service run method blocksunblocks being a total beginner to boostasio i am confused with io servicerun i would appreciate it if someone could explain to me when this method blocksunblocks the documentations statesthe run function blocks until all work has finished and there are no more handlers to be thispatched or until the io service has been stoppedmultiple threads may call the run function to set up a pool of threads from which the io service may execute handlers all threads that are waiting in the pool are equivalent and the io service may choose any one of them to invoke a handlera normal exit from the run function implies that the io service object is stopped the stopped function returns true subsequent calls to run run one poll or poll one will return immediately unless there is a prior call to resetwhat does the following statement mean no more handlers to be thispatched while trying to understand the behavior of io servicerun i came across this example example 3a within it i observe that io servicerun blocks and waits for work orders workerthread invines io servicerunvoid workerthreadboostshared ptrboostasioio service io servicevoid calculatefibsize tboostshared ptrboostasioio service io service new boostasioio serviceboostshared ptrboostasioio servicework work new boostasioio serviceworkio service boostthread group worker threadsforint x 0 x 2 x worker threadscreate threadboostbindworkerthread io serviceio servicepost boostbindcalculatefib 3io servicepost boostbindcalculatefib 4io servicepost boostbindcalculatefib 5workresetworker threadsjoin allhowever in the following code that i was working on the client connects using tcpip and the run method blocks until data is asynchronously receivedtypedef boostasioiptcp tcpboostshared ptrboostasioio service io service new boostasioio serviceboostshared ptrtcpsocket socketnew tcpsocketio service connect to 1270019100tcpresolver resolverio servicetcpresolverquery query127001 boostlexical cast stdstring 9100tcpresolveriterator endpoint iterator resolverresolvequerysocketconnectendpoint iteratorendpoint just blocks here until a message is receivedsocketasync receiveboostasiobufferbuf client 30 0 clientreceiveeventio servicerun write responseboostsystemerror code ignored errorstdcout sending message nboostasiowritesocket boostasiobuffersome data ignored errorany explanation of run that describes its behavior in the two examples below would be appreciated,['c++'] +443344,best java server implementation for socketio i wanted to use socketio to push data from server to browser but the project is java tomcat one and there are many implementation in github for the server implementation of socketio most of them say they are deprecated or better ones are availablecan anyone suggest me a good implementationand i see lot of demo and sample code about broadcasting with socketio my requirement is to push different messages to different clients could someone point me to some good demo or tutorial dealing with such stuffthanks,['java'] +443386,zooming uiimageview in uiscrollview goes out of bounds i have successfully implemented zooming of uiimageview in my uiscrollview but i have faced with a strange problem that irritates mebasically when i zoom in the imagei can pan the view to actually scroll out of the image border and i am left with a black area like thisand as i zoom in more i can make the black border to fill the whole screenmeanwhile in the iphone photo app you cannot zoom out the actual image whats wrong here in my implementationit looks like thisuiimage imagetothisplay uiimage imagewithdatatmpimagedataimageviewmainimage imagetothisplayimageviewmainframe cgrectmake0 0 scrollviewmainframesizewidth scrollviewmainframesizeheightimageviewmaincontentmode uiviewcontentmodescaleaspectfitscrollviewmaindelegate selfscrollviewmainminimumzoomscale 10scrollviewmainmaximumzoomscale 90scrollviewmainautoresizingmask uiviewautoresizingflexiblewidth uiviewautoresizingflexibleheightscrollviewmaincontentsize imageviewmainframesizeselfview addsubviewscrollviewmainscrollviewmain addsubviewimageviewmainand i also implement this method uiviewviewforzoominginscrollviewuiscrollview scrollview return imageviewmainthanks in advanceeditwhen i first load the view i shrink my uiimageview to fit the scroll view and the image looks like this,"['iphone', 'ios', 'objective-c']" +443397,angularjs not refreshing ngrepeat when updating array i am having serious troubles understanding angularjs sometimes so i have a basic array in my controller likescopeitems abci am ngrepeating in my template over the items array ngrepeatitem in items super straightfoward so far after a couple of ux actions i want to push some new stuff to my array scopeitemspushsomethingso 50 of the time the new element is added to the view but the other 50 nothing happens and it is like super frustrating bc if i wrap that within scopeapply i got a digest already in progress error wrapping that into timeout does not help eitherand when i inspect my element scope using the chrome extension i can see the new data is there and the scopeitems value is correct but the view is just not taking care of adding that to the domthanks,['javascript'] +443415,fragment inner class should be static i have a fragmentactivity class with inner class that should thisplay dialog but i am required to make it static eclipse offers me to suppress error with suppresslintvalidfragment is it bad style if i do it and what are the possible consequencespublic class caractivity extends fragmentactivity code suppresslintvalidfragment public class networkconnectionerror extends dialogfragment private string message private asynctask task private string taskmessage override public void setargumentsbundle args supersetargumentsargs message argsgetstringmessage public void settaskcaractivitycarinfo task string msg thistask task thistaskmessage msg override public dialog oncreatedialogbundle savedinstancestate use the builder class for convenient dialog construction alertdialogbuilder builder new alertdialogbuildergetactivity buildersetmessagemessagesetpositivebuttongo back new dialoginterfaceonclicklistener override public void onclickdialoginterface dialog int id intent i new intentgetactivitygetbasecontext mainscreenclass startactivityi buildersetnegativebuttonretry new dialoginterfaceonclicklistener override public void onclickdialoginterface dialog int id startdownload create the alertdialog object and return it return buildercreate startdownload starts asynctask,['android'] +443428,how to configure proguard to only remove android logging calls i am trying to configure proguard to only remove calls to androidutillog from my android app for the release build i specifically do not want proguard to do any obfuscation or minification of the codethis is the configuration i have tried but it does not remove the log calls i assume because of the keep class optimizationpasses 5dontusemixedcaseclassnamesdontskipnonpubliclibraryclassesdontpreverifyverboseoptimizations codesimplificationarithmeticfieldclassmergingkeepattributes exceptionsinnerclassessignaturedeprecatedsourcefilelinenumbertableannotationenclosingmethodkeep class assumenosideeffects class androidutillog is what i am asking even possible with proguard,['android'] +443438,why can webmethod access session state without enablesessionstate i have a method on a page marked as a webmethod that uses some session state as part of its operation after i wrote this code i suddenly had a flash of memory that you need to use enablesessionstate when you use session state in a webmethod eg see here but it seems to be working fine whysample code behindprotected void page loadobject sender eventargs args thissessionvariable hey theresystemwebserviceswebmethodpublic static string getsessionvariable return stringhttpcontextcurrentsessionvariablesample body htmlscript srcscriptsjquery141minjs typetextjavascriptscriptscript typetextjavascript function getsession ajax type post url defaultaspxgetsessionvariable data contenttype applicationjson charsetutf8 datatype json success function msg documentgetelementbyidshowsessionvariableinnerhtml msgd return false scriptform idform1 runatserver div idshowsessionvariablediv button onclickreturn getsessionget session variablebuttonform,['asp.net'] +443459,hour by hour timeline thisplay of events mysql php i have been googling for a while but have not come up with anything great as yetwhat i want to do is take mysql data belowand thisplay it in an hourly timeline something likeanyone got any good links or tutorials on how to make this happennot looking for an exact solutionalthough that helps but just some direction t get me startedso mysql db with php and jquerythanks,"['php', 'jquery', 'mysql']" +443464,check two floatdouble values for exact equality what is an elegant readable and nonverbose way of comparing two floating point value for exact equality as simple as it may sound its a wicked problem the operator does not get the job done for nan and also has special treatment for zero00 00 truedoublenan doublenan falsebut i want to determine if two values are exactly the same but i do not care for different nan patterns so any nan any other nan truei can do this with this ugly monster piece of codedoubledoubletolongbitsa doubledoubletolongbitsbis there a better way to write this and make the intent obvious,['java'] +443535,espannablestringbuilder18909 span exclusive exclusive spans cannot have a zero length getting the above error in log cat i found quite some hits on this in google but they do not seem to apply to my case currently i have no idea where to start looking or what codelayout to post to get help from you guysso where in my code shall i start looking to get rid of this error the app seems to work as it should but still i would like to get rid of the error you never know,['android'] +443537,can objectivecs new literal syntax mimic the addobject i know that i can do this to nsmutablearray objects objectone objecttwo mutablecopynsobject someobject nsobject newobjects0 someobjectbut is there a way for the new literal syntax to mimic addobject,['objective-c'] +443550,bitwise negation gives unexpected result i am trying to write a bitwise calculator in java something that you could input an expression such as 101 and it would give back 10 however when i run this codeimport javautilscannerpublic class test public static void mainstring args integer a integervalueof101 2 systemoutprintlnintegertostringa2 it outputs 110 why,['java'] +443578,how introjs achieve the highlighted areas came across introjs a very cool way to guide users on how to use software interfaces i havnt looked at the source in depth but was wondering if anyone could briefly explain what the code does to achieve the highlighted areas specifically dimensionspositionzindexing to achieve the effectthanks in advancejaylink,['javascript'] +443597,dynamically adjust skitter slideshow images size how to resize scale slide images to a different size from jquery or css or any other waysit always load the main images full width and height and controlling with following ways does not work you can download sample full working skitter sample and test it easily yourself no help is found inside it is possible to resize the images slider container by following sample code but if the images if larger than 530 px it will only shows some part of itdocumentreadyfunction box skitter largecsswidth 530 height 110skitter theme minimalistnumbers align center scriptalso setting images width and height in img tags does not help the following is the more specific scenario in the original question which may helpi wrote the below code to dynamically adjust images size on window resize using skitter and jquery but its not working pls help scriptbox skitter normaladdclassz1skitterlabel false numbers false box skitter normal2addclassz2skitterlabel false numbers falsewindowresizefunction box skitter normaladdclassz1skitterlabel false numbers false box skitter normal2addclassz2skitterlabel false numbers falsescript,"['javascript', 'jquery', 'html']" +443634,how to use lambda in linq select statement i am trying to select stores using a lambda function and converting the result to a selectlistitem so i can render it however it is throwing a type of expression in select clause is incorrect errorienumerableselectlistitem stores from store in databasestores where storecompanyid curcompanyid select s new selectlistitem value sid text sname viewbagstoreselector storeswhat am i doing wrongeditalso how do i convert int to string in this situation the following does not workselect s new selectlistitem value sidtostring text sname select s new selectlistitem value sid text sname edit 2figure out the int to string conversion it is so typical of microsoft to forget to include an int2string conversion function here is the actual workaround everyone is using with fully working syntaxselect new selectlistitem value sqlfunctionsstringconvertdoublestoreid text storename to call this situation absurd is an understatement,['c#'] +443645,ios support for google cloud messaging i saw in googles developer console that gcm allows to generate a api key for ios i searched in the web for any kind of documentation about how to implement push notifications throught gcm in an ios app but i did not find answers is it really possible to implement push notifications jet using gcm in ios apps documentation examples or something to learn how to do thisthanks,['ios'] +443660,how to export table from heroku production database locally to excel from console using ruby i know how to export table in rails to formated excel file but how to do that from console,['ruby'] +443672,max heapify algorithm results i have been playing around with some of the algorithms in the intro to algorithms textbook in specific i am trying get a binary heap to work 100 correctly i have a curious feeling that the example that i am working with is not correct and i was wondering if anyone can help point me in the right direction given the arrayint arr 1 2 3 4 7 8 9 10 14 16 the result i get from maxheapify is 16 14 9 10 7 8 3 1 4 2 however after doing a few google searches i found that people who use this exact array as an example expect the result to be 16 14 10 8 7 9 3 2 4 1 what confuses me is that the result that my maxheapify method gives satisfies the heap property but it is different than what is expected below is my implementation in javapublic static void buildmaxheap int arr for int i intmathfloor arrlength 1 i 0 i maxheapify arr i public static void maxheapify int arr int i int left 2 i 1 int right 2 i 2 int largest i if left arrlength arr left arr largest largest left if right arrlength arr right arr largest largest right if largest i int temp arr i arr i arr largest arr largest temp maxheapify arr largest,['java'] +443689,how to block 10 individual ip addresses introductionhow do you block large number of ip address from your web applicationserver obviously that can easily be done in php or any programming language iplist array list or from databaseif in arraygetip iplist log ip access information header redirect exit exit or using htaccessorder allowdenydeny from 1234567deny from 012345 the list continuesallow from allthe issues am trying to block a whole 100k plus individual ips not subnets am trying to avoid user getting to php before blocking such ip10 is over 15mb and that is a lot if information to be loading in htaccess all the timedatabase of ip still growing and they would be nee to dynamically add more valuesto set bans in iptables for 10 is just ridiculous might be wrongstupid idea order allowdenydeny from database not sure if this is possibleallow from allquestion is it possible for htaccess to get the list from database rethiscrunchbasemongo mysql or even sqlite anyis there a visible solution to manage such kind of issue in production i know the best solution is block the ips at the firewall level is there any way to pragmatically addremove ip to the firewallfinally my approach might be totally wrong all i want is a visible solution since spammers and botnets are on the rise please this has nothing to do with dos attack its a simple get lost responseupdatefirewall cisco pix 515ur,['php'] +443707,optimal performance for joining on range of values i have a really big table that contains integer representations of ip addresses and a second table that has starting and ending ranges of integers representations of ip addresses the second table is used to return the country as per several stackoverflow articles although this returns the required results the performance is fairly poor is there any higher performing alternative to joining on a range below is a sample set of code that shows how the join works currentlycreate table basetable someintegervalue int primary keyinsert into basetable someintegervalueselect someintegervaluefrom values 123 456 789 data someintegervaluecreate table rangelookuptable rangestartvalue int primary key rangeendvalue int not nullinsert into rangelookuptable rangestartvalue rangeendvalueselect rangestartvalue rangeendvaluefrom values 0 100 101 200 201 300 301 400 401 500 501 600 701 800 901 10 data rangestartvalue rangeendvalueselect from basetable btjoin rangelookuptable rlt on btsomeintegervalue between rltrangestartvalue and rltrangeendvalue,['sql'] +443722,autoformat code from command line is it possible to run autoformat code for all or for specific file in solution like ctrlk ctrld formatting in visual studio but from its command line or use resharpers cleanup also from command line for solution files,['c#'] +443766,assets would not precompile when deploying with capistrano to production on amazon ec2 i worked on being able to deploy to production using capistrano i face several issues and while fixing most of them we still have a last oneour precompile assets options are not properly compiling them on production and because of that we are unable to use the last developed features as they rely heavily on jswithout trying to influence on how anyone would analyze this problem this is some of what i did trying to make it workprecompiled assets locally pushed to github repo cap deployed from local machines to ec2 cap deploy is local the code being pushed to ec2 is the one on githubtried using capistrano tasks as suggested using load deployassets in the capfile and letting the cap deploysetup task do its thingused the option cap deployassetsclean and then cap deployassetsprecompiletried removing assets from public and then use a pipeline precompile task in deployrbexpired assets forcing rails to precompile everything changing assetsversions in applicationrbtried different combinations on configassets in environmentsproductionrbfinally tried deleting publicassets in production and precompiling up there using rails envproduction bundle exec rake assetsprecompilethe app is just not using the new js files if you check the code either on the repo or in the server itself i introduced a simple comment to the namejscoffee shows and hides menus depending on the data on db on line x and this is not in the compiled assetsjs in production this is a quick test to be sure the recent assets are being usedthe whole problem here is the js and css files not so much rails which is why it is so difficult to test or find thus one of the reasons for the popularity of js frameworks lately in case of problems you do not have to kill yourself looking for where the problem is if the prob is in ruby or rails usually does not take that long to find out once you get to js css and cross browser compatibility well this is the problem at handheres my deployrb file running rails 3212 ruby193p327 unshiftfileexpand pathlib envrvm path load rvms capistrono pluginsrequire rvmcapistranorequire bundlercapistranoset rvm type userset user usernameset domain ip addreset application app proset keep releases 2 it keeps on two old releases git repo detailsset scm git you can set scm explicitly or capistrano will make an intelligent guess based on known version control directory namesset repository userappgitset scm username userset git enable submodules 1set git shallow clone 1set branch master or accurev bzr cvs darcs git mercurial perforce subversion or nonerole web domain your http server apacheetcrole app domain this may be the same as your web serverrole db domain primary true ec22323156118compute1amazonawscom this is where rails migrations will run role db your slave dbserver here deply optionsdefault run optionspty trueset ssh options forward agent trueset ssh options auth methods publickeyset ssh options keys downloadskeypemset deploy to homeuserappdirset deploy via remote cacheset use sudo false if you want to clean up old releases on each deploy uncomment thisafter deployrestart deploycleanup if youre still using the scriptreaper helper you will need these process scripts if you are using passenger mod rails uncomment thisnamespace deploy do task start do run commandetcinitdnginx restart invoke sudo1 run sudo etcinitdnginx restart exit end after deploystart deploycleanup task stop do end task restart roles app except no release true do run touch filejoincurrent pathtmprestarttxt end task setup config roles app do run mkdir p shared pathconfig put filereadconfigdatabaseexampleyml shared pathconfigdatabaseyml puts now edit the config file database in shared path end after deploysetup deploysetup config desc symlink shared resources on each release not used task symlink config roles app do run ln nfs shared pathconfigdatabaseyml release pathconfigdatabaseyml end after deployfinalize update deploysymlink config desc it helps to seed database with values task seed do run cd current path bundle exec rake dbseed rails envrails env end task create schema do run cd current path bundle exec rake dbcreate rails envrails env trace endendonworking newalternative deploy new2rb file onworking newalternative deployrb filerequire rvmcapistranorequire bundlercapistranoset rvm type userset application ip addreset domain ip address rolesrole web domainrole app domainrole db domain primary truedeployment detailsset deploy via remote cacheset user usernameset copy compression bz2set git shallow clone 1set scm verbose trueset use sudo falseset deploy to homeuserdirdefault run optionspty trueset ssh options forward agent trueset ssh options auth methods publickeyset ssh options keys downloadskeypemrepo detailsset scm gitset repository userappgitset scm username userset keep releases 2set branch masternamespace deploy do task start roles app except no release true do not need to restart nginx every time run service nginx start run cd release path touch tmprestarttxt end after deploystart deploycleanup after deploycleanup deploysymlink config you do not need reload nginx every time eventhought if you use passenger or unicorn task stop roles app except no release true do run service nginx stop end task graceful stop roles app except no release true do run service nginx stop end task reload roles app except no release true do run cd release path touch tmprestarttxt run service nginx restart end task restart roles app except no release true do run cd release path touch tmprestarttxt end if you enable assetsdeploy in capfile you do not need this task pipeline precompile do run cd release path rails envrails env bundle exec rake assetsprecompile precompile assets before deploy and upload them to server run locallyrails envrails env rake assetsclean rails envrails env rake assetsprecompile topupload publicassets release pathpublicassets via scp recursive true endend you do not need to this because you already add require bundlercapistrano before deployassetsprecompile bundleinstalland capfileload deploy uncomment if you are using rails asset pipelineload deployassetsload configdeploy remove this line to skip loading any of the default tasksthank you in advance for any help let me know if you need more info,['ruby-on-rails'] +443767,how does dropbox protect its python code i know that dropbox uses a lot of python code in its application so i am wondering how it protects the code from being stolen because it seems pretty difficult to obfuscate python code protecting python code i have read about software that converts python code to executables ie pyinstaller does dropbox use software like that to protect their code,['python'] +443782,too many arguments in beginx for fromasync i have an async method with the following signatureiasyncresult begingetmynumberstring foo string bar string bat int bam asynccallback callback object statei want to execute it using factoryfromasync like thisvar result taskintfactoryfromasync instancebegingetmynumber instanceendgetmynumber afooa abara abata 100 bam nullbut i get the following errorargument 1 cannot convert from method group to systemfuncit seems there is no suitable overloaded fromasync method it only supports up to 5 arguments including callback and state on the beginx methodother than refactoring the beginx method to take an object rather than six arguments is there a way to execute it using fromasync,['c#'] +443791,android textview text background color how can i achieve such an effect with an android textview it looks somehow like selected text and i could not find something similar in the apithis is not a background color for the view but a background color only for the text you can see how it stops at line breaks and has a thin white line between text lines,['android'] +443847,ios need to sort an array of dictionaries value based on key price m facing problem to sort the values based on key using dictionary object actually what i am storing is each dictionary object having different data type in that dictionary all the data type taking as a string how to convert this string type to specific data type and sort it price vise my code and out put is bellow please help me on this one ibactionpricesortidsender nssortdescriptor sort nssortdescriptor alloc initwithkeyprice ascendingtrue nsarray sa symbolarray sortedarrayusingdescriptorsnsarray arraywithobjectsort nslogpricesaout put volume 2496752 yield 1049 marcap 829 price 0715 symbol saipi,"['iphone', 'ios']" +443862,signalr persistent connection with query params i have a persistent connection which i would like to start with some seed info using query params here is the override in the connection protected override task onconnectedirequest request string connectionid get query params here return baseonconnectedrequest connectionid now i have my route setup in globalasax file which looks like this routetableroutesmapconnectionmyconnection myconnectionand the client code looks like this var connection connectionmyconnectionconnectionstart done can someone tell me how i can pass query string params to this connecton so i can read them in the override as i seem to be hitting a brick wall on this cheers hope someone can helpdave,"['javascript', 'asp.net']" +443869,calculated column in ef code first i need to have one column in my database calculated by database as sum of rows sum of rowsb i am using codefirst model to create my databasehere is what i meanpublic class income key public int userid get set public double insum get set public class outcome key public int userid get set public double outsum get set public class firsttable key public int userid get set public double sum get set this needs to be calculated by db as select suminsum from income where userid thisuserid select sumoutsum from outcome where userid thisuseridhow can i achieve this in ef codefirst,['c#'] +443882,are php ticks nonblocking i randomly came across things likephp declareticks1 using a function as the callback register tick functionmy function true using an objectmethod object new my class register tick functionarrayobject my method truewhich can be found at register tick functioni wanted to know if using this in php was blocking or noteditwhat i mean by this if i have more then one php tick running started on the same thread is it able to handle io in the background while the other ticks run or does it need to wait for each tick to give over control,['php'] +443895,java sorting list i got a list in java i get values from a sql querypublic void reloadpages throws exception try connection conn frameworkgetdatabasemanagergetbonegetconnection try resultset set conncreatestatementexecutequeryselect from habbo shop pages while setnext int id setgetint1 pagesputid new catalogpageset systemoutprintlnloaded pagessize catalog pagesthen i store it all in another function i want to retrieve certain pages from a parentidpublic linkedlistcatalogpage getsubpagesint parentid linkedlistcatalogpage pages new linkedlist for catalogpage page thispagesvalues if pagegetparentid parentid continue pagesaddpage return pageshow do i order the list now id 4 is above in the shop and 1 at the bottom but i want it ordered by id order by in query does not work,['java'] +443940,best practices use of throws in phpdoc and how it could be handle let us say i have a class with a method like this loads the user from username param string username the username return userinterface throws usernotfoundexception if the user is not found public function getuserusername somefunction return an userinterface class if found or null if not user somefunctionselect username if user null throw new usernotfoundexception return usernow let us say that somefunction could throw a invalidargumentexception runtimeexception pdoexception for xyz reasons what should i do and what notnumber 1add all the possible exceptions that could throw somefunction in phpdocs loads the user from username param string username the username return userinterface throws usernotfoundexception if the user is not found throws invalidargumentexception throws number 2add a trycatch block to ensure that the method should throw exceptions only documented loads the user from username param string username the username return userinterface throws usernotfoundexception if the user is not found throws runtimeexception public function getuserusername try user somefunctionselect username catch exception e throw new runtimeexception if user null throw new usernotfoundexception return usernumber 3do not do anything,['php'] +443961,fragmentpageradapter getitem is not being triggered currently with a fragmentactivity i toggle among 2 type of fragments using the following codeprivate void toggle fragment oldfragment getsupportfragmentmanagerfindfragmentbyidridcontent fragment fragment null if oldfragment instanceof colorfragment fragment new viewpagerfragment else fragment new colorfragmentandroidrcolorblack getsupportfragmentmanagerbegintransactionreplaceridcontent fragmentcommitallowingstateloss2 fragments are being togglecolorfragment a simple fragment which fill up its background with solid black colorviewpagerfragment a fragment contains viewpager user can swipe between a purple color fragment and a blue color fragmentthe code which responsible for swiping purple and blue color fragments are as belowprivate static class myfragmentpageradapter extends fragmentpageradapter public myfragmentpageradapterfragmentmanager fm superfm override public int getcount return 2 override public fragment getitemint position switch position case 0 return new colorfragmentandroidrcolorholo purple default return new colorfragmentandroidrcolorholo blue bright however i encounter the weird behavior during togglingblack color fragment was showntogglingview pager which can swipe between purple and blue fragments showntogglingblack color fragment was showntogglingnothing shown as myfragmentpageradapters getitem is not being triggeredi think my situation is similar to fragmentpageradapter getitem is not calledhowever i prefer not to use fragmentstatepageradapter because of the cost of potentially more overhead when switching between pagesany workaround to overcome this problemi include a complete workable source code to demonstrate this problem,['android'] +444002,dbcontext query performance poor vs objectcontext i recently moved my entity model from an objectcontext using 41 to a dbcontext using 50 i am starting to regret doing that because i am noticing some very poor performance on querys using the dbcontext vs objectcontext heres the test scenario both contexts use the same database with about 600 tables lazyloading and proxycreation is turned off for both not shown in code example both have pregenerated viewsthe test first makes 1 call to load up the metadata workspace then in a for loop that gets executed 100 times i new up a context and make one call that takes the first 10 i am creating the context inside the for loop because this simulates being used in a wcf service which would create the context every timefor int i 0 i 100 i using myentities db new myentities var a dbmyobjecttake10tolist when i run this with the objectcontext it takes about 45 seconds when i run it using the dbcontext it takes about 17 seconds i profiled this using redgates performance profiler for the dbcontext it seems the major culprit is a method called updateentitysetmappings this is called on every query and appears to retrieve the metadataworkspace and cycle through every item in the ospace asnotracking did not helpedit to give some better detail the problem has to do with the creationinitialization of a dbset vs an objectset not the actual query when i make a call with the objectcontext it takes on average 42ms to create the objectset when i make a call with the dbcontext it takes about 140ms to create the internal dbset both objectset and dbset do some entityset mapping lookups from the metadataworkspace what i have noticed is that the dbset does it for all the types in the workspace while the objectset does not i am guessing have not tried it that a model with fewer tables that the performance difference is less,"['c#', '.net']" +444017,how to make java 6 which fails ssl connection with ssl peer shut down incorrectly succeed like java 7 i am seeing an ssl connection from a client running java 6 fail with an exception likecaused by javaxnetsslsslhandshakeexception remote host closed connection during handshake at comsunnetsslinternalsslsslsocketimplreadrecordsslsocketimpljava882 at comsunnetsslinternalsslsslsocketimplperforminitialhandshakesslsocketimpljava1188 at comsunnetsslinternalsslsslsocketimplstarthandshakesslsocketimpljava1215 at comsunnetsslinternalsslsslsocketimplstarthandshakesslsocketimpljava1199 at sunnetwprotocolhttpshttpsclientafterconnecthttpsclientjava434 at sunnetwprotocolhttpsabstractdelegatehttpsurlconnectionconnectabstractdelegatehttpsurlconnectionjava166 at sunnetwprotocolhttpshttpsurlconnectionimplconnecthttpsurlconnectionimpljava133 35 morecaused by javaioeofexception ssl peer shut down incorrectly at comsunnetsslinternalsslinputrecordreadinputrecordjava462 at comsunnetsslinternalsslsslsocketimplreadrecordsslsocketimpljava863 41 morethe server is a tomcat 7based app running on java 7 linux and on amazon ec2 for what that is worthi have found a lot of suggestions on possible casues including connecting accidentally to a nonssl port etc i believe i have ruled it all out mostly because the exact same client works when running java 7 with no change os x in both casesbelow i include the debug output from java 6s and java 7s ssl connection procedure my question to experts is does this suggest that some possible cipher or protocol setting maybe a default in java 7 could be enabled in java 6 to make it workjava 6allow unsafe renegotiation falseallow legacy hello messages trueis initial handshake trueis secure renegotiation false no cached client session clienthello tlsv1randomcookie gmt 1363993281 bytes 77 153 100 72 45 178 253 243 195 167 17 151 39 247 148 102 213 129 39 17 26 139 157 154 63 88 41 160 session id cipher suites ssl rsa with rc4 128 md5 ssl rsa with rc4 128 sha tls rsa with aes 128 cbc sha tls rsa with aes 256 cbc sha tls dhe rsa with aes 128 cbc sha tls dhe rsa with aes 256 cbc sha tls dhe dss with aes 128 cbc sha tls dhe dss with aes 256 cbc sha ssl rsa with 3des ede cbc sha ssl dhe rsa with 3des ede cbc sha ssl dhe dss with 3des ede cbc sha ssl rsa with des cbc sha ssl dhe rsa with des cbc sha ssl dhe dss with des cbc sha ssl rsa export with rc4 40 md5 ssl rsa export with des40 cbc sha ssl dhe rsa export with des40 cbc sha ssl dhe dss export with des40 cbc sha tls empty renegotiation info scsvcompression methods 0 main write tlsv1 handshake length 81main write sslv2 client hello message length 110main received eofexception errormain handling exception javaxnetsslsslhandshakeexception remote host closed connection during handshakemain send tlsv1 alert fatal description handshake failuremain write tlsv1 alert length 2main called closesocketjava 7ignoring unavailable cipher suite tls ecdhe rsa with aes 256 cbc shaignoring unavailable cipher suite tls dhe rsa with aes 256 cbc shaignoring unavailable cipher suite tls ecdh rsa with aes 256 cbc shaignoring unsupported cipher suite tls dhe dss with aes 128 cbc sha256ignoring unsupported cipher suite tls dhe dss with aes 256 cbc sha256ignoring unsupported cipher suite tls dhe rsa with aes 128 cbc sha256ignoring unsupported cipher suite tls ecdh rsa with aes 128 cbc sha256ignoring unsupported cipher suite tls dhe rsa with aes 256 cbc sha256ignoring unsupported cipher suite tls ecdhe rsa with aes 256 cbc sha384ignoring unsupported cipher suite tls ecdh ecdsa with aes 256 cbc sha384ignoring unsupported cipher suite tls rsa with aes 256 cbc sha256ignoring unavailable cipher suite tls ecdhe ecdsa with aes 256 cbc shaignoring unsupported cipher suite tls ecdhe rsa with aes 128 cbc sha256ignoring unsupported cipher suite tls ecdhe ecdsa with aes 256 cbc sha384ignoring unavailable cipher suite tls dhe dss with aes 256 cbc shaignoring unsupported cipher suite tls ecdh rsa with aes 256 cbc sha384ignoring unsupported cipher suite tls ecdhe ecdsa with aes 128 cbc sha256ignoring unsupported cipher suite tls ecdh ecdsa with aes 128 cbc sha256ignoring unavailable cipher suite tls ecdh ecdsa with aes 256 cbc shaignoring unavailable cipher suite tls rsa with aes 256 cbc shaignoring unsupported cipher suite tls rsa with aes 128 cbc sha256allow unsafe renegotiation falseallow legacy hello messages trueis initial handshake trueis secure renegotiation falsemain setsotimeout0 called no cached client session clienthello tlsv1randomcookie gmt 1363993435 bytes 131 83 80 186 215 90 171 131 231 18 184 183 249 155 197 204 73 1 74 79 32 142 236 28 1 37 58 255 session id cipher suites tls ecdhe ecdsa with aes 128 cbc sha tls ecdhe rsa with aes 128 cbc sha tls rsa with aes 128 cbc sha tls ecdh ecdsa with aes 128 cbc sha tls ecdh rsa with aes 128 cbc sha tls dhe rsa with aes 128 cbc sha tls dhe dss with aes 128 cbc sha tls ecdhe ecdsa with rc4 128 sha tls ecdhe rsa with rc4 128 sha ssl rsa with rc4 128 sha tls ecdh ecdsa with rc4 128 sha tls ecdh rsa with rc4 128 sha tls ecdhe ecdsa with 3des ede cbc sha tls ecdhe rsa with 3des ede cbc sha ssl rsa with 3des ede cbc sha tls ecdh ecdsa with 3des ede cbc sha tls ecdh rsa with 3des ede cbc sha ssl dhe rsa with 3des ede cbc sha ssl dhe dss with 3des ede cbc sha ssl rsa with rc4 128 md5 tls empty renegotiation info scsvcompression methods 0 extension elliptic curves curve names secp256r1 sect163k1 sect163r2 secp192r1 secp224r1 sect233k1 sect233r1 sect283k1 sect283r1 secp384r1 sect409k1 sect409r1 secp521r1 sect571k1 sect571r1 secp160k1 secp160r1 secp160r2 sect163r1 secp192k1 sect193r1 sect193r2 secp224k1 sect239k1 secp256k1extension ec point formats formats uncompressedextension server name server name host name ec2xcompute1amazonawscom,['java'] +444027,nglist input not updating when adding items to array i am running into a strange issue where an input using nglist is not updating when adding items to the model i have created a fiddle to better illustrate the issue does not update nglist inputscopetagspushtag does update nglist inputvar tags angularcopyscopetagstagspushtagscopetags tagsthis does not seem like expected behavior especially since scopetags is being properly updated as illustrated by the pre tag in the jsfiddle above,['javascript'] +444028,if a struct is a value type why can i new it in c structs are value types but i am able to new them as if they are reference types why is this,['c#'] +444037,ruby 200p0 irb warning dl is deprecated please use fiddle i just uninstalled my older versions of ruby removed all of my gemsincluding rails and installed ruby 20 in other words a totally clean reinstall upon starting irb i received this messagedl is deprecated please use fiddlenote i am on a windows machinewhat does this message mean,['ruby'] +444118,can laravel 4 log to a mysql database if so how can it be done by default l4 writes to a text file i notice that monolog can log to database on its github page,['php'] +444140,jersey how to post a list of json objects i am building a restful webservice in java using jersey 1 and have problems implementing a method which consumes a list of jsonised entities the single instance method works finethe error i get isstatus 400 bad request the request sent by the client was syntactically incorrectmy method signature looks like thispostpathsomepathsomeparamproducesmediatypeapplication jsonconsumesmediatypeapplication jsonpublic string createbatchlistmyentity myents pathparamsomeparam string someparam the json i am sending in the requests is an array of myentity json objectsfield1 value1 field2 value2 field1 value3 field2 value4 similar questions have been asked before and one straight forward suggestion was to change the consumed media type to text and deserialize the json manually but i would prefer a cleaner solutionis the json i am sending even valid in this context or do i need a toplevel ie a wrapper entity this would also seem a bit unnaturalthank youdavid,['java'] +444203,apple push notification not working in production we are totally stucked please helpi and my team made a iphone application and this is the first time we try on ioseverything is fine until we submitted our app and became available on appstore the push notification service is not working i searched around the web and tried double check on our app by peoples advices but i could not find whats wrong so this question is posted here these are what we didwe build the application suppose it is named appmasterwe created appid on ios provisioning portal called pushtest this id enabled the push notification on both development and production we created a provisioning for development named appmasterpushtest from the appid above this provisioning is for inside test everyone of the team installed it on their macour server is implemented by java and we used the javaapn package during the test we downloaded the certification file for development and write out the p12 file and pushed our message to the sandbox server by using the packages api withsandboxdestination with that p12 file test goes fine notifications are received i thought we were ready so we created another appid called appmaster and enable push notification only for production this id is written in the apps bundle identifierwe made another provisioning for production named appmaster from appid in step 5 with thistribution method set as app store downloaded it and rebuild app this one was submitted to apple and goes alive on appstroeserver side we downloaded the certification for production and write out the p12 file again and made program to push message to production server by using the api withproductiondestination with the p12 just been write outwe installed the app from app store sadly the notification was never deliveredis there something we missed btw the id we created in step5 was looks like xcomcompanyappname but in the apps bundle identifier we just set comcompanyappname part without prefix is this could be the problemany idea is welcomedplease be our saver thanks,"['iphone', 'ios']" +444211,permission denied when opening localhost i had recently installed apache php and mysql in ubuntu and copied the files i created to the varw directory but when i open httplocalhost it is showingwarning unknown failed to open stream permission denied in unknown on line 0fatal error unknown failed opening required varwindexphp include pathusrsharephpusrsharepear in unknown on line 0how can i run my project normally it was working fine in windows,['php'] +444212,pinvokestackimbalance not caused by callingconvention i have no idea what the problem is here i have a ton of pinvoke calls that are working without incident except this onei have managed to reduce my problem to the following sample codeif i remove either struct member either the double or the int it works fine i am assuming the problem is somehow related to the layout of the struct but when i do a sizeof in c and a marshalsizeof in c they both return the same value so if the struct size is the same in c and c what could the problem bei am obviously missing something basic heresampledllcodecpragma pack1typedef struct samplestruct double structvalueone int structvaluetwo samplestruct declspecdllexport samplestruct cdecl samplemethodvoidsamplestruct samplemethodvoid return samplestruct 1 2 build scriptgcc stdc99 pedantic o0 c o sampledllcodeo sampledllcodecgcc shared outimplib o sampledlldll sampledllcodeo c codeusing systemusing systemruntimeinteropservicesnamespace sampleapplication structlayoutlayoutkindsequential pack1 public struct samplestruct public double structvalueone public int structvaluetwo class program dllimportsampledlldll callingconvention callingconventioncdecl public static extern samplestruct samplemethod static void mainstring args samplestruct sample samplemethod,"['c#', 'c']" +444244,cannot call methods prior to initialization attempted to call method refresh i would like to update the value of a linkbutton by clicking on the item of a menuhtmldiv idmenu ul datarolelistview dataiconfalse lia hrefvalue aali lia hrefvalue bali uldiva href idselected datarolebuttonajquerymobileselectedhidemenu li aonclickfunction selectedhtmlthishtmlslidedownbuttonrefreshtext update works fine but button css is not properly updatedi get the following error uncaught error cannot call methods on button prior to initialization attempted to call method refreshwhich initialization are we talking about page and button are already initialized are not theyediti also tried this documentonmobileinit function selectedhide menu li aonclickfunction selectedhtmlthishtmlslidedownbuttonrefresh no error message any more but no text update,['jquery'] +444246,android listview add items to top without list view scroll i have a listview and i want to add new items to the top of the list view but i dont want list view to scroll its content i want user to look at the same item as he was looking before new items were addedthis is how i add new items to listviewthiscommentslistviewadapteraddrangetotopcommentsthiscommentslistviewadapternotifydatasetchangedand this is addrangetotop methodpublic void addrangetotoparraylistcomment comments for comment comment comments thisinsertcomment 0 this is my listviewlistview androidididcommentslistview androidlayout widthfill parent androidlayout heightfill parent androidlayout aboveidaddcommentlayout androidstackfrombottomtrue listviewwhat i want to do is to load old comments when user scrolls to the topthank you for your help,['android'] +444259,register to local broadcast inside a custom view i have created a custom view which can be placed on different places in the application i cannot avoid using a broadcastreceiver inside the view to get messages from the rest of the applicationi have read it is not recommended where should i unregisterreceiver in my own view but in case i choose to use it is there a place to unregister the view from the broadcastmanager,['android'] +444265,ioerror errno 22 invalid mode r or filename cpython27testtxt what is wrong with the followingtest fileopencpython27testtxtr,['python'] +444281,extern with global definition of variable in c i have the following source code which interests meinclude stdiohextern int fooint foo 32int mainprintfd foothis a perfectly normal piece of code and when i compile it withgcc wall wextra pedantic fooci get no warningsand it seems weird because a variable is defined both as external and also global in the same filei am quite sure that it is easy to the linker to find the reference for the external variable in the same file but does not it look like a coding error and if so why does not the compiler warn about this,['c'] +444333,how to use property injection with autofac in a console application i am using log4net and in the main method i am getting the logger object now i would like to make this log object available in all my classes by letting all the classes inherit from a baseclass which has a ilog property and is supposed to be set by property injection rather than constructor injectioni am using autofac ioc container how to inject my log object to the log property of my every classwhats the besteasiest way to achieve thisis there any way to automatically resolve typesbelow is my test applicationnamespace consoleapplication1 class program static ilog log static icontainer container static void mainstring args initializelogger initializeautofac the below works but could it be done automatically without specifying the name of each class productlog containerresolveilog tried below but did not inject ilog object into the product containerresolveproduct runtest consolereadline private static void runtest var product new product productdo private static void initializeautofac var builder new containerbuilder builderregisterc logasilog builderregistertypeproductpropertiesautowired container builderbuild private static void initializelogger log4netconfigxmlconfiguratorconfigure log logmanagergetloggerloggername public class product public static ilog log get set public void do this throws exception because log is not set logdebugsome debug,"['c#', 'asp.net']" +444394,how to style thisabled options in a form i am using a form with a dropdown menu that contains some options thisabled so the users cannot select them i am trying to customize via css these elements but i have some problems with chrome and ie78910htmldiv classformbody select nameformcategoria idcategoria classrsformselectbox option selectedselected valuescegli una categoriaoption option thisabledthisabled valueimpresa option select span classformvalidation span idcomponent50 classformnoerrorscegli una categoriaspan spandivcselect optionthisabled color 0 fontweight bold this code works only with firefox and does not work with chrome and ie all versionany idea to solve this problembelow the html code for selectboxdiv classformbodyselect nameformcategoria idcategoria classrsformselectbox option selectedselected valuescegli una categoriaoptionoption thisabledthisabled valueimpresa optionoption valueserviziservizioptionoption valueinformaticainformaticaoptionoption valuecommerciocommerciooptionoption valuetelecomunicazionitelecomunicazionioptionoption valueeditoriastampaeditoriastampaoptionoption valuemeccanicaelettricameccanicaelettricaoptionoption valuealimentarealimentareoptionoption valuechimicafarmaceuticachimicafarmaceuticaoptionoption thisabledthisabled valueedilizia optionoption valuetessilemodatessilemodaoptionoption valuemobiliarredamentimobiliarredamentioptionoption valuealberghiristorantialberghiristorantioptionoption valuetrasportologisticatrasportologisticaoptionoption valuefinanzafinanzaoptionoption valuealtroaltrooptionoption thisabledthisabled valueprofessionista optionoption valuecommercialistacommercialistaoptionoption valueragioniereragioniereoptionoption valuenotaionotaiooptionoption valuetributaristatributaristaoptionoption valueavvocatoavvocatooptionoption valueconsulente del lavoroconsulente del lavorooptionoption valuealtroaltrooptionoption thisabledthisabled valuepa locale optionoption valueregioneregioneoptionoption valueprovinciaprovinciaoptionoption valuecomunecomuneoptionoption valuecomunitagrave montanacomunitagrave montanaoptionoption valueaslasloptionoption valuecciacciaoptionoption valuealtroaltrooptionoption thisabledthisabled valuepa centrale optionoption valueassociazione di categoriaassociazione di categoriaoptionoption valueprivatoprivatooptionoption valuealtroaltrooptionselectspan classformvalidationspan idcomponent50 classformnoerrorscegli una categoriaspanspandiv,['css'] +444441,python comprehension with multiple for clauses and single if imagine a thiscrete xyz space i am trying to create an iterator which will return all points which lie within a sphere of some radial thistance from a point my approach was to first look at all points within a larger cube which is guaranteed to contain all the points needed and then cull or skip points which are too far awaymy first attempt was xyz001thist2this does not workit 0xxpyypzzp for xp in rangethistthist1 for yp in rangethistthist1 for zp in rangethistthist1 if xxp2yyp2zzp2 thist2sysfloat infoepsilon a simplefor def in it 0 printdef print xd2ye2zf2 thist2sysfloat infoepsilon defverifies that it 0 does not produce correct results i believe it is applying the conditional only to the third ie z for clausethe following worksit 1xxpyypzzp for xp in rangethistthist1 for yp in rangethistthist1 for zp in rangethistthist1it 2filter lambda p xp02yp12zp22 thist2sysfloat infoepsilon it 1it collects all the points then filter those which do not fit the conditionali was hoping there might be a way to correct the first attempted implementation or make these expressions more readable or compact,['python'] +444467,replace multiple strings with multiple other strings i am trying to replace multiple words in a string with multiple other words the string is i have a cat a dog and a goathowever this does not produce i have a dog a goat and a cat but instead it produces i have a cat a cat and a cat is it possible to replace multiple strings with multiple other strings at the same time in javascript so that the correct result will be producedvar str i have a cat a dog and a goatstr strreplacecatgi dogstr strreplacedoggi goatstr strreplacegoatgi catthis produces i have a cat a cat and a catbut i wanted to produce the string i have a dog a goat and a cat,['javascript'] +444486,uitableviewheaderfooterview unable to change background color i am trying to change the background color of uitableviewheaderfooterview although the view is appearing the background color remains the default color i am getting a log from xcode sayingsetting the background color on uitableviewheaderfooterview has been deprecated please use contentviewbackgroundcolor insteadhowever none of the following options workmytableviewheaderfooterviewcontentviewbackgroundcolor uicolor blackcolormytableviewheaderfooterviewbackgroundviewbackgroundcolor uicolor blackcolormytableviewheaderfooterviewbackgroundcolor uicolor blackcolori have also tried changing the background color of the view in the xib file any suggestions thanks,"['iphone', 'ios']" +444547,how to create bootstrap popover close option as you can see in the jquery i have used the answer from this question to make a bootstrap popover thisappear on an outside click now i am looking to add an x in the top right corner that closes the popover on click is there a simple way to create a clickable x on the top right corner of the popover that would close the popover when clickedhtml h3live demoh3div classbsdocsexample stylepaddingbottom 24px a href classbtn btnlarge btndanger datatogglepopover titlea title datacontentand heres some amazing content it is very engaging rightclick to toggle popoveradivjqueryvar isvisible falsevar clickedaway falsebtndangerpopover html true trigger manualclickfunctione thispopovershow clickedaway false isvisible true epreventdefaultdocumentclickfunctione if isvisible clickedaway btndangerpopoverhide isvisible clickedaway false else clickedaway true,"['javascript', 'jquery', 'html', 'css']" +444556,java interface throws an exception but interface implementation does not throw an exception i read this code where the interface throws an exception but the class which implements it does not throw one or catch one why is that is it legal or safe in java import javarmipublic interface myremote extends remote public string sayhello throws remoteexceptionimport javarmiimport javarmiserverpublic class myremoteimpl extends unicastremoteobject implements myremote public string sayhello return server says hey public myremoteimpl throws remoteexception public static void main string args try myremote service new myremoteimpl namingrebindremotehello service catchexception ex exprintstacktrace,['java'] +444574,ruby gem rmagick would not install on mac os x i understand that this question has been asked a lot earlier but none of the solutions worked for me and i am really desperate right nowi am trying to get rmagick to install using gem for an installation of diaspora i already installed imagick via homebrew and when trying to run gem install rmagick i receive this errorerror error installing rmagick error failed to build gem native extension userstobischweigerrvmrubiesruby193p385binruby extconfrbchecking for ruby version 185 yeschecking for gcc42 yeschecking for magickconfig nocannot install rmagick 2132 cannot find magickconfig in userstobischweigerrvmgemsruby193p385diasporabinuserstobischweigerrvmgemsruby193p385globalbinuserstobischweigerrvmrubiesruby193p385binuserstobischweigerrvmbinusrbinbinusrsbinsbinusrlocalbinoptx11binusrlocalgitbin extconfrb failed could not create makefile due to some reason probably lack ofnecessary libraries andor headers check the mkmflog file for moredetails you may need configuration optionsprovided configuration options withoptdir withoutoptdir withoptinclude withoutoptincludeoptdirinclude withoptlib withoutoptliboptdirlib withmakeprog withoutmakeprog srcdir curdir rubyuserstobischweigerrvmrubiesruby193p385binrubygem files will remain installed in userstobischweigerrvmgemsruby193p385diasporagemsrmagick2132 for inspectionresults logged to userstobischweigerrvmgemsruby193p385diasporagemsrmagick2132extrmagickgem makeouti am not very experienced with gem and homebrew and i am wondering if somebody could help me out,['ruby'] +444659,understanding deleting and deleting relations in greendao first question is when does greendao generate a delete function for a entity and whats the difference between calling the entitydelete and the sessiongetentitydaodeleteentitysecond if i delete a parent entity with a child that has toone relation to the parent i have to remove the child by myself do not i actually no automatic dependency cleaning is done is that right,['android'] +444669,what is the difference between platform driver and normal device driver i previously had a thought about the platform driver as well as normal device driver like platform driver is for those devices that are on chip and normal device driver are for those that are interfaced to the proccesor chipbefore coming across one i2c driverbut here i am reading through multi function i2c driver defined as platform driver i had gone through but still could not get clear idea to come to an conclusion on how to define drivers like for both onchip as well interfaced devicesi went through this link too please somebody explain,['c'] +444679,show linenumbers from the richtextbox in wpf i found an example how to show the linenumbers from a richtextbox in windows formshave somebody an example for it in wpfeditdoes someone have work with avalonedit because he wanted to show linenumbers in his programm and can help me by my problem,['c#'] +444681,unregister broadcast receiver registered through manifest is it possible to unregister a broadcastreceiver that has been registered through manifestalso please let me know if it possible to ignore the broadcastreceiver without making any code changes as this broadcastreceiver is of no use to me now thanks,['android'] +444717,how do i make an file play continuously on all pages i am wondering how i make get an audio file to play continuously on all pages so if the audio file has played for 20 seconds then when navigating on another page it will continue from where it left off i also am trying to get the volume to decrease after navigating away from my home page any tips or advice would me appreciated thanks daudio srcsongforsitemp3 looptrue autoplaytrue controlsunsupported in firefoxaudio,['html'] +444726,c why is a function call faster than manual inlining i have measured the execution time for two ways of calculating the power of 21 inlineresult b b2 with a simple function callresult powerbwhen running in debug mode everything is as expected calling a function is considerably more expensive than doing the calculation in line 385 ms in line vs 570 ms function callin release mode i would expect the compiler to speed up execution time of the function call considerably because the compiler would inline internally the very small power function but i would not expect the function call to be faster than the manual inlined calculationmost astonishingly this is the case in the release build the first run needs 109 ms and the second run with the call to power needs only 62 mshow can a function call be faster than manual inlininghere is the program for your reproductionclass program static void mainstring args consolewritelinestarting test 1 calculating inline without function call stopwatch sw stopwatchstartnew for double d 0 d 10 d double res d d swstop consolewritelinechecked swelapsedmilliseconds 2 calulating power with function call stopwatch sw2 stopwatchstartnew for int d 0 d 10 d double res powerd sw2stop consolewritelinefunction sw2elapsedmilliseconds consolereadkey static double powerdouble d return d d,['c#'] +444737,does randomaccessfile in java read entire file in memory i need to read last and lines from a large file say 2gb the file is utf8 encoded would like to know the most efficient way of doing it read about randomaccessfile in java but does the seek method read the entire file in memory it uses native implementation so i was not able to refer the source code,['java'] +444764,gcc aliasing checks wrestrict pointers consider the following two snippetsdefine align bytes 32define assume alignedx x builtin assume alignedx align bytesvoid fn0const float restrict a0 const float restrict a1 float restrict b int n assume aligneda0 assume aligneda1 assume alignedb for int i 0 i n i bi a0i a1ivoid fn1const float restrict restrict a float restrict b int n assume aligneda0 assume aligneda1 assume alignedb for int i 0 i n i bi a0i a1iwhen i compile the function as gcc472 ofast marchnative stdc99 ftreevectorizerverbose5 s testc wall i find that gcc inserts aliasing checks for the second functionhow can i prevent this such that the resulting assembly for fn1 is the same as that for fn0 when the number of parameters increases from three to say 30 the argumentpassing approach fn0 becomes cumbersome and the number of aliasing checks in the fn1 approach becomes ridiculous assembly x8664 avx capable chip aliasing cruft at lfb10fn0lfb9 cfi startproc testl ecx ecx jle l1 movl ecx r10d shrl 3 r10d leal 0r108 r9d testl r9d r9d je l8 cmpl 7 ecx jbe l8 xorl eax eax xorl r8d r8d p2align 410 p2align 3l4 vmovaps rsirax ymm0 addl 1 r8d vaddps rdirax ymm0 ymm0 vmovaps ymm0 rdxrax addq 32 rax cmpl r8d r10d ja l4 cmpl r9d ecx je l1l3 movslq r9d rax salq 2 rax addq rax rdi addq rax rsi addq rax rdx xorl eax eax p2align 410 p2align 3l6 vmovss rsirax4 xmm0 vaddss rdirax4 xmm0 xmm0 vmovss xmm0 rdxrax4 addq 1 rax leal r9rax r8d cmpl r8d ecx jg l6l1 vzeroupper retl8 xorl r9d r9d jmp l3 cfi endproclfe9 size fn0 fn0 p2align 415 globl fn1 type fn1 functionfn1lfb10 cfi startproc testq rdx rdx movq rdi r8 movq 8rdi r9 je l12 leaq 32rsi rdi movq rdx r10 leaq 32r8 r11 shrq 3 r10 cmpq rdi r8 leaq 0r108 rax setae cl cmpq r11 rsi setae r11b orl r11d ecx cmpq rdi r9 leaq 32r9 r11 setae dil cmpq r11 rsi setae r11b orl r11d edi andl edi ecx cmpq 7 rdx seta dil testb dil cl je l19 testq rax rax je l19 xorl ecx ecx xorl edi edi p2align 410 p2align 3l15 vmovaps r9rcx ymm0 addq 1 rdi vaddps r8rcx ymm0 ymm0 vmovaps ymm0 rsircx addq 32 rcx cmpq rdi r10 ja l15 cmpq rax rdx je l12 p2align 410 p2align 3l20 vmovss r9rax4 xmm0 vaddss r8rax4 xmm0 xmm0 vmovss xmm0 rsirax4 addq 1 rax cmpq rax rdx ja l20l12 vzeroupper retl19 xorl eax eax jmp l20 cfi endproc,['c'] +444792,c90 does not allow lf use in printf why i am a beginner programming student just wanted to learn the reason behind thiswhen i use this codeinclude stdiohint main double pi 31415926535897932 printflfpi return 0compiler gives this warning iso c90 does not support the alfa gnu printf format wformati use the gcc compiler in ubuntu terminal with o wall ansi pedanticerrorswhats the reason behind this i searched web and found this use is allowed in c99 why c90 did not allow lf use in printf i can use 16lf or 16f and both print with the same precision so whats the matter that makes lf bad in c90,['c'] +444847,getting results from several asynctasks hi and thanks for your helpi have a method that calls an asynctask to retrieve some data from the netthe method is called several times in sequence and therefore launches several asynctasksfrom each launch of the method i need to get back the correct result from the relative asynctask and not from some other asynctask which was called before or afterany help very much appreciatededit edit edit editadded rest of code please note the whole process runs inside a service public static class updateservice extends service override public int onstartcommandintent intent int flags int startid int appwidgetids intentgetintarrayextrawidgetsids final int and appwidgetidslength appwidgetmanager manager appwidgetmanagergetinstancethis for int i 0 i n i int appwidgetid appwidgetidsi logeiintegertostringi di integertostringn remoteviews view buildupdategetapplicationcontext appwidgetids managerupdateappwidgetappwidgetid view return start not sticky override public ibinder onbindintent intent return null private static remoteviews buildupdatecontext ctxt int appwidgetids remoteviews updateviews new remoteviewsctxtgetpackagename rlayoutwidget updateviewssettextviewtextridprice1 getpricelistget0 getsymbol this method is called several times in sequence private static string getpricestring symbol string result updatetaskprice up new updatetaskprice upexecutesymbol null null here i want the result from onpostexecute return resultthis is the asynctask which is launched several timespublic class updatetaskprice extends asynctaskstring void string override protected void onprogressupdatevoid progress override protected void onpostexecutestring result here i receive the result from doinbackground i need to pass it back to getprice override protected string doinbackgroundstring symbol string result defaulthttpclient client new defaulthttpclient string srt string url contextgetstringrstringurlaternativoconcat symbol0 httpget getmethod new httpgeturl try responsehandlerstring responsehandler new basicresponsehandler srt clientexecutegetmethod responsehandler int inizio srtindexoflast data int fine srtindexof inizio 12 result srtsubstringinizio 12 fine catch throwable t logeerror error t here i get the result i want and pass it to onpostexecute return result,['android'] +444863,how do i tell intellij to start gradle with java 16 jdk a simple question i could not figure out even after hours of trying and searchingi have both java 6 and 7 installed how do i tell intellij to start gradle builds with a jdk version 16no matter what i do intellij keeps starting my gradle with cprogram filesjavajdk170 10jrebinjava dgradlehomec coding gradle14 i triedall project modules are set to use 16java home is set to cprogram filesjavajdk160 38setting idea jdk did nothinggradle v recognizes 16 as its jdk on command linerestarting intellij andor computer did not change the behavioris there a setting somewhere to avoid java 17 from being invoked,['java'] +444866,android htmlfromhtml with images my android application receives html content with images in it is it possible to make fromhtml function to thisplay the images in the html string it receivesif not how can i retrieve the images in the html string and convert them to textview imagesthanks,"['java', 'android']" +444937,changing androidinstalocation from preferexternal to internalonly i have an app on google play market and i added androidinstalocationpreferexternal to manifestxml file and released long time ago now i would like to add android home screen widget so i need to change it to androidinstalocationinternalonly if i do that what happens when a user upgrades because a user already installed the old app on sd card what is the best solution for this situationif someone has this kind of experience please advise methanks in advance,['android'] +444951,jquery datepicker done button is there any way to handle the event of pressing the done button in jquery ui datepickeri have a datepicker that allows only to choose between year and month as in herethe problem is that using the onclose event prevents me from clearing the field if i click the datepicker pops up then if i close the current selected month and year are put into the fieldi would like not to use an additional clear button outside the datepicker so i though i could use the done button,['jquery'] +444952,polygons with double coordinates i have some questions about polygons with points of double typewhat i have to do is given points create the polygon and then test if 1 concrete point is inside the polygon or notso i kwnow that in java there is a class called polygon and is used like that triangleint valoresx 100 150 200 int valoresy 100 200 100 int and valoresxlengthpolygon city new polygonvaloresxvaloresynbut my polygons has to be of double type not int easy exampledouble valoresx 1010 15010 20010 double valoresy 10010 20010 10010 in my project i dont really need to paint it on an applet or similar i just need to calculate if the point is inside or notso my question isis any way to do polygons with double coordenates that allow to calcultate if the pointdouble is inside the polygon or notthanks for allshudy,['java'] +444954,js uncaught typeerror object is not a function onclick edit heres a jsfiddleedit2 the error is on this line input typebutton valuetotalbandwidthresult onclickjavascripttotalbandwidth trying to have a button perform a calculation the required variables are below as well as the html where i am getting an error onclick uncaught typeerror object is not a function indexhtml71onclickhere is my javascriptfunction totalbandwidth var fpsnumberdocumentcalculatorfpsvalue var bitratenumberdocumentcalculatorbitratevalue var numberofcameras numberdocumentcalculatornumberofcamerasvalue var encoding documentcalculatorencodingvalue if encoding mjpeg storage bitratefps else storage bitrate totalbandwidth numberofcameras storage 10 documentcalculatortotalbandwidthresultvalue totalbandwidth the htmlform namecalculator classformtable div classformrowlabel forrcnamerc namelabel input typetext namercnamediv div classformrowlabel forfpsfpslabel input typetext namefps div div classformrowlabel forbitratebitratelabel input typetext namebitrate div div classformrowlabel fornumberofcamerasnumber of cameraslabel input typetext namenumberofcameras div div classformrowlabel forencodingencodinglabel select nameencoding idencodingoptions option valueh264h264option option valuemjpegmjpegoption option valuempeg4mpeg4optionselectdiv total storage input typetext nametotalstorage total bandwidth input typetext nametotalbandwidth input typebutton valuetotalbandwidthresult onclickjavascripttotalbandwidth basically it seems that there may be something wrong with the syntax i used in the js but i am not sure,"['javascript', 'html']" +444979,how to understand the equal sign symbol in imap email text i am currently using python imaplib to process email texti use fetch command to fetch the raw data email from gmail server however i found one thing really tricky the equal sign it is not a normal equal sign but a special symbolfor example sometimes acts as the hyphenation mark at the end of text linedepending upon your module selections course lecturers may also contact you with preparatory work over the next few weeks it would be wise to start reviewing the preparatory reading lists provided on the module syllabi now sometimes it acts as a escape mark similar to for examplea20b is actually aspaceb46rom here is actually from herei am totally confused about such weird notation i think there must be a guidance to handle this because gmail can handle such thing correctly in their appsi see that this is related to html encoding just like will be encoded but the problem is all i get from the imap response is a string that contain this symbol how should i handle this using regular expression,"['python', 'html']" +444980,log4j cannot find the log file i am having trouble with an application that crashes when i deploy it to other computers who are running jre 17 when i run this inside of netbeans or even directly from the jar file on my pc everything is fine but on another computer it fails at specific events button clicks during executionso i learned about logging using the log4j library this gave me some information on a problem in my application and the logging works perfectly again on my computer but when i deploy the jar file to other computers who are only running jre java 7 update 17 i can find no traces of any log fileshere is my log4jproperties file root logger option log4jrootloggerinfo file stdout direct log messages to a log file log4jappenderfileorgapachelog4jrollingfileappender log4jappenderfilefileclogginglog log4jappenderfilemaxfilesize1mb log4jappenderfilemaxbackupindex1 log4jappenderfilelayoutorgapachelog4jpatternlayout log4jappenderfilelayoutconversionpatterndymmdd hhmmss 5p c1l mn direct log messages to stdout log4jappenderstdoutorgapachelog4jconsoleappender log4jappenderstdouttargetsystemout log4jappenderstdoutlayoutorgapachelog4jpatternlayout log4jappenderstdoutlayoutconversionpatterndymmdd hhmmss 5p c1l mnon my computer i can see the logginglog file right inside of the project folder to that extent everything works perfectly however on the user pc there is no sign of this file at all not in c where i thought it would be not in cprogram files x86 or anywhere else i have done a complete search of my hard thisk but nothing comes backwhere should this file be stored are my properties set correctly very confusedthank you,['java'] +445001,how can i thisable href if onclick is executed i have an anchor with both href and onclick attributes set if clicked and javascript is enabled i want it to only execute onclick and ignore href likewise if javascript is thisabled or unsupported i want it to follow the href url and ignore onclick below is an example of what i am doing which would execute the js and follow the link concurrently usually the js is executed and then the page changesa href onclickyes js loginlog inawhats the best way to do thisi am hoping for a javascript answer but i will accept any method as long as it works especially if this can be done with phpi have read a href link executes and redirects page before javascript onclick function is able to finish already but it only delays href but does not completely thisable it i am also looking for something much simpler,['html'] +445010,c pointer anomaly please explain i have a function the basic idea of the function is to change what a points to the first version works however the second version does not could someone please help me to understand what is going on here this worksvoid swapint a int temp mallocsizeofint 3 temp0 0 temp1 1 temp2 2 a temp this does notvoid swapint a a mallocsizeofint 3 a0 0 a1 1 seg fault occurs on this line a2 2i am calling the function like soint main int b 01 int a b swapa return 0also both functions do not belong to the same file at the same time,['c'] +445035,how to only change the text in a dom element without replacing any child elements hi i have a simple html structureh1title text spaninner textspanh1what i want is to replace only the text title text without thisturb the span text is this possiblei do not want to add any other dom element i would like to keep that structure i been doing this of courseh1textnew textbut you can guess will replace all the innert text and the span text element as wellpossible solutioni was thinking in copy in a variable the text of the span and then concatenate it with the new h1 text but i think maybe exist a better and clean way to do it,"['javascript', 'jquery', 'html']" +445048,how to detect if any external libraries are calling uidevice currentdevice uniqueidentifier so since apple is now rejecting apps that access udid on our companys current project we need to eliminate all apis that make a call to this propertyuidevice currentdevice uniqueidentifierwe have eliminated all the calls in our own code but need to be sure that the many external libraries we are using are not making calls to this propertywhat is the most reliable method for determining if a library is calling on this propertythank you in advance,['ios'] +445061,why does scipyoptimizecurve fit not fit to the data i have been trying to fit an exponential to some data for a while using scipyoptimizecurve fit but i am having real difficulty i really cannot see any reason why this wouldnt work but it just produces a strait line no idea whyany help would be much appreciated from future import divisionimport numpyfrom scipyoptimize import curve fitimport matplotlibpyplot as pyplotdef funcxabc return anumpyexpbxcydata numpyloadydatanpyxdata numpyloadxdatanpytrialx numpylinspacexdata0xdata110 fit a polynomial fitted numpypolyfitxdata ydata 101y numpyzeroslentrailxfor i in rangelenfitted y fitteditrialxi fit an exponentialpopt pcov curve fitfunc xdata ydatayexp functrialx poptpyplotfigurepyplotplotxdata ydata labeldata markeropyplotplottrialx yexp rls labelexp fitpyplotplottrialx y label 10 deg polypyplotlegendpyplotshowxdata 1e06 2e06 3e06 4e065e06 6e06 7e06 8e069e06 1e05 2e05 3e054e05 5e05 6e05 7e058e05 9e05 01 0203 04 05 0607 08 09 0102 03 04 0506 07 08 09 001ydata 6374206067e09 113082012115e08152835756975e08 219214493931e08 271258852882e08 338556130078e08 355765277358e08413818145846e08 472543475372e08 485834751151e08 953876562077e08 145110636413e071830627931e07 210138415308e07 243503982686e07 272107045549e07 302911771395e07326499455951e07 348319349445e07 513187669283e07 598480176303e07 6570282701e07698347073045e07 7286930335e07 750686502279e07 77015576866e07 787147246927e07799607141001e07 861398763228e07 884272900407e07 896463883243e07 904105135329e07908443443149e07 912391264185e07 9150842683e07 916878548643e07 9183890067e07,['python'] +445064,how to get flowlayoutpanelautosize to work with flowbreak i have a problem with a flowlayoutpanel and i do not know how to solve iti am placing two flowlayoutpanels inside another the second inner flp has 3 buttons insidethe properties from flowlayoutpanel child areflowdirection lefttorightautosize trueautosizemode growandshrinkwrapcontents truenow i set for each button the flowbreak property to true however the behavior i see is not the one i want i want the flowlayoutpanel to shrink to the width of the buttonschanging flowdirection to uptodown is not an optionanyone know why the autosize is not workingthis is the codeflowlayoutpanel1thisflowlayoutpanel1autosizemode systemwindowsformsautosizemodegrowandshrinkthisflowlayoutpanel1controlsaddthisflowlayoutpanel3thisflowlayoutpanel1location new systemdrawingpoint84 77thisflowlayoutpanel1minimumsize new systemdrawingsize10 10thisflowlayoutpanel1name flowlayoutpanel1thisflowlayoutpanel1size new systemdrawingsize308 265thisflowlayoutpanel1tabindex 0flowlayoutpanel3thisflowlayoutpanel3autosize truethisflowlayoutpanel3autosizemode systemwindowsformsautosizemodegrowandshrinkthisflowlayoutpanel3controlsaddthisbutton1thisflowlayoutpanel3controlsaddthisbutton2thisflowlayoutpanel3controlsaddthisbutton3thisflowlayoutpanel3location new systemdrawingpoint127 3thisflowlayoutpanel3minimumsize new systemdrawingsize10 10thisflowlayoutpanel3name flowlayoutpanel3thisflowlayoutpanel3size new systemdrawingsize162 87thisflowlayoutpanel3tabindex 1button1thisflowlayoutpanel3setflowbreakthisbutton1 truethisbutton1location new systemdrawingpoint3 3thisbutton1name button1thisbutton1size new systemdrawingsize75 23thisbutton1tabindex 0thisbutton1text button1thisbutton1usevisualstylebackcolor truebutton2thisflowlayoutpanel3setflowbreakthisbutton2 truethisbutton2location new systemdrawingpoint3 32thisbutton2name button2thisbutton2size new systemdrawingsize75 23thisbutton2tabindex 1thisbutton2text button2thisbutton2usevisualstylebackcolor truebutton3thisbutton3location new systemdrawingpoint3 61thisbutton3name button3thisbutton3size new systemdrawingsize75 23thisbutton3tabindex 2thisbutton3text button3thisbutton3usevisualstylebackcolor true,['c#'] +445086,connect qml signal to c11 lambda slot qt 5 connecting a qml signal to a regular c slot is easy qmlrectangle signal foo c oldstyleqobjectconnectsome qml container signalfoo some qobject slotfooslot workshowever no matter what i try i cannot seem to be able to connect to a c11 lambda function slot c11qobjectconnectsome qml container signalfoo response failsqobjectconnectsome qml container foo response failsboth attempts fail with a function signature error no qobjectconnect overload can accept these parameters however the qt 5 documentation implies that this should be possibleunfortunately qt 5 examples always connect a c signal to a c lambda slot c11qobjectconnectsome qml container qmlcontainerfoo response worksthis syntax cannot work for a qml signal as the qmlcontainerfoo signature is not known at compiletime and declaring qmlcontainerfoo by hand defeats the purpose of using qml in the first placeis what i am trying to do possible if so what is the correct syntax for the qobjectconnect call,['c++'] +445115,offseting the center of the mapfragment for an animation moving both the target latlng and the zoom level i have got a ui that has a mapfragment with a transparent view overlaid on top of it the map takes up the entire screen whereas the view is just the left third of the screen as a result the default center of the map is off when someone clicks on a marker i want to center that marker in the wholly visible area of the mapfragment not the center of the mapfragment itselfsince this is hard to describe with words let me use a few pictures suppose this is how my ui lookswhen the user clicks a marker i want to both center it and zoom in to see it closer without any adjustments this is what youll getwhat i want is for the marker to be centered but in the space to the right like thisit is very easy to achieve this feat if youre not changing the zoom level using the maps projection offset the target latitudelongitude by preset xy intslatlng target new latlnglatitude longitudeprojection projection getmapgetprojectionpoint screenlocation projectiontoscreenlocationtargetscreenlocationx offsetxscreenlocationy offsetylatlng offsettarget projectionfromscreenlocationscreenlocation animate to the calculated latlnggetmapanimatecameracameraupdatefactorynewlatlngoffsettargethowever if youre changing the zoom level at the same time the above calculations do not work since the latlng offsets change at different zoom levelslet me run down a list of attempted fixeschanging the zoom level quickly doing the calculations zooming back to the original camera position then animating unfortunately the sudden camera change even if it is only for a split second is unfortunately very obvious and i would like to avoid the flickeroverlaying two mapfragments on top of each other having one do the calculations while the other thisplays i have found that mapfragments are not really built to be layered on top of each other there are unavoidable bugs down this routemodifying the screen locations xy by the difference in zoom level squared theoretically this should work but it is always off by quite a bit 1 latitudelongitude which is enough to be way offis there a way to calculate the offsettarget even with the zoom level changing,['android'] +445127,java initialize a hashmap of hashmaps i am new to java and practicing by creating a simplistic naivebayes classifier i am still new to object instantiation and wonder what to do to initialize a hashmap of hashmaps when inserting new observations into the classifier i can create a new hashmap for an unseen feature name in a given class but do i need to initializeimport javautilhashmappublic class naivebayes private hashmapstring integer class counts private hashmapstring hashmapstring integer class feature counts public naivebayes class counts new hashmapstring integer do i need to initialize class feature counts public void insert todo i think i can create new hashmaps on the fly here for class feature counts public string classify stub return naive scoring p c f 1 f n pc pf 1c pf nc private double get scorestring category hashmap features stub return 00 public static void mainstring args naivebayes bayes new naivebayes todo note this question is not specific to naive bayes classifiers just thought i would provide some context,['java'] +445172,android expandable textview with animation i have a textview which firstly shows a small portion of a long textthe user can press a see more button to expand the textview and see the rest of that textmaking tests i can reach that by simply interchange the value of textviewsetmaxlines between 4 for collapsing and integermax value for expandingnow i would like that this behavior would be accompanied by an animation i know that in this question one solution is almost done but i tried to implement it and i have no succesomeone can help me with thisthanks in advance,['android'] +445202,determine whether a com is a inproc or localserver i got an application that use a com library just wondering how can i know whether that application use that com library as a localserver or inproci looked at the code being constructed in this waydatcomlibitemulationptr pte uuidofdatcomlibtemulation,['c++'] +445204,how do i loop next i have 3 divs with same class i am adding class selected to next div on click and removing it from previous class its working fine but i want to loop itcurrently its going from 1 2 3 i want it to loop 31 please helphtmldiv idalldiv clasection selectedonedivdiv clasectiontwodivdiv clasectionthreedivdivbr a hrefjavascript idbuttonclickacselectedbackgroundredjsbuttonclickfunction sectionselectedremoveclaselectednextsectionaddclaselected js fiddle link,['jquery'] +445205,sharing with facebook twitter on ios on the android os there is an easy feature for share with facebook twitter and otherssee this link is there the same type of thing of ios or would we need to add specific buttons like share on facebook share on twitter for all types of sharing,"['iphone', 'ios', 'objective-c']" +445314,android manual screen orientation without restarting the activity i need to make an app playing video with a button for fullscreen on the video the button is used to manually switch between landscape and portrait of the video thisplay we do not want the auto rotation detect so the manifest file is set as belowactivity androidnamevideoactivity androidscreenorientationportrait androidconfigchangeskeyboardhiddeni used setrequestedorientationactivityinfoscreen orientation sensor landscape or setrequestedorientationactivityinfoscreen orientation sensor portrait to manually set the orientation it works but it restarts the activity the oncreate was found called so the video playback restarts from the beginning unexpectedly i cannot make it smooth as like as using onconfigurationchanged the auto rotation detect methodso how to make manual screen orientation change without restarting the activitythank you,['android'] +445323,protecting login and comment forms against csrf i have read many articles about csrf protection this is a good one and various questions here on so but none of them seem to be informative enough to answer my questioni am developing my own cms and i want to secure my login and comment forms i am going to allow anonymous users to comment on my websiteall of the forms on my website are secured using tokens i already know about that approach but the problem is that it needs an active session that is after the user logs in the problem with the login and comment forms is that they are accessible to just about anyone and do not require you to log in what would be the best protection against csrf in this caseon the link above i read that it could be possible to create a presession when the user tries to log in and then proceed to the usual anticsrf methods like assigning a token to the users session but i have no insight on how to achieve thisthe referrer header is a weak solution so i guess i should not bother the origin header is as far as i have tested only supported in google chrome what about custom headers xmlhttprequest seems like a possibility however i have spent literally more than three hours on google looking up some information about how should one implement such a security measure on their website but even if i could use a custom header does not it make it useless since the http headers can be faked completelyso the question how should i protect my login and comment forms against csrfedit heres some additional information from the link that i provided abovewe recommend strict referer validation to protect against login csrf because login forms typically submit over https where the referer header is reliably present for legitimate requests if a login request lacks a referer header the site should reject the request to defend against malicious suppressionandsecret validation tokens can defend against login csrf but developers often forget to implement the defense because before login there is no session to which to bind the csrf token to use secret validation tokens to protect against login csrf the site must irst create a apresessiona implement tokenbased csrf protection and then transition to a real session after successful authenticationi just cannot put an end to this argument after reading the above quotes one of them mentions using the referrer header but i am not quite sure whether it really adds much to the security of the webappedit 2 what about using captchas,['php'] +445382,what makes a template different from a generic i understand the aspects of templates in c that are different from generics in java and c c is a reification java uses type erasure c uses duck typing etc there are a number of things c templates can do that java and c generics cannot eg template specialization but there are a number of things java generics can do that c and c cannot eg make a bounded type parameter of a family of generics like class foot extends comparable and a number of things c generics can do that java and c cannot eg runtime generic reflection edit apparently java generics are much weaker than i thought which is saying something in any case despite their ineptness they are still considered generics along with cs genericswhat i do not understand is what conceptually makes templates different from generics what parts of c templates are things that cannot be done in something that is not a template but is a generic for example if i were to implement a language that supported templates what would absolutely need to be in it what could i leave out that would be necessary for the language to support genericsmy guess is that templates are a superset of generics or they are a way to implement generics but i do not really understand what separates a true template from a true generic,"['c#', 'java', 'c++']" +445443,what is the difference between pthread recursive mutex initializer and pthread recursive mutex initializer np when statically initializing a recursive mutex what is the difference betweenstatic pthread mutex t foo mutex pthread recursive mutex initializerand static pthread mutex t foo mutex pthread recursive mutex initializer npand why should i want the one instead of the other,['c'] +445453,nesting ngviews in angular js i had two different apps in angular during integration to a single application i had to nest ngviews for sample indexhtml isdoctype htmlhtml langen ngappmyappheadmeta charsetutf8titlemy angularjs apptitlelink relstylesheet hrefcssappcssheadbodyul classmenulia hrefview1view1alilia hrefview2view2aliuldiv ngviewdivdivangular seed app vspan appversionspandivscript srclibangularangularjsscriptscript srcjsappjsscriptscript srcjsservicesjsscriptscript srcjscontrollersjsscriptscript srcjsfiltersjsscriptscript srcjsdirectivesjsscriptbodyhtmlone of my app view is view2htmldiv classngviewdivpthis is the partial for view 1p current version is vversion interpolate now this application has different views once again inside iti tried but the page is not loading is there a possibility to nest ngviews if not possible can it be explainedthanks in advance,['javascript'] +445457,optimizing mysql search query need yours help optimizing one mysql query lets take simple table for example create table modules id int11 not null auto increment modulename varchar100 not null menuname varchar255 not nullprimary key idkey modulename modulename engineinnodb default charsetutf8lets fill it with some datainsert into modules modulename menunamevalues abc1 name1 abc name2 ddf name3 c name4 fer name5and some sample string let it be abc deftraditionally we are trying to find all the rows containing search stringon the contrary my task is to find all rows which contains modulename in input string for now i have following query to get desired resultselect modulename menuname from modules where abc def likeconcatmodulenamethis will return modulename menuname abc name2the problem is that this query is not using index is there some way to force it to use one,['mysql'] +445488,is there a standard solution for gauss elimination in python is there somewhere in the cosmos of scipynumpy a standard method for gausselimination of a matrix one finds many snippets via google but i would prefer to use trusted modules if possible,['python'] +445505,empty files uploaded in android native browser i am creating a website for mobile phones that resizes photos and uploads them imgpreview canvaseachfunctionpindex vformdataappendpindex canvastojpegblobthis0 vissueid attachment0 pindex jpgajax url apiobissuefileupload data vformdata processdata false contenttype false type postdonefunctionpdata windowlocation issueid vissueidfailfunctionpjqxhr alertmystringsuploadfailedthis works in chrome for android and in safari on ios but in the native android browser the files have a contentlength of 0 and name blob a uid when the file is added to the formdata the size also seems rather large 900k opposed to 50k in chromethe canvastojpegblob functionfunction canvastojpegblobpcanvas var vmimetype imagejpeg vdatauri vbytestring vblob varraybuffer vuint8array i vblobbuilder vdatauri pcanvastodataurlvmimetype 08 vbytestring atobvdataurisplit1 varraybuffer new arraybuffervbytestringlength vuint8array new uint8arrayvarraybuffer for i 0 i vbytestringlength i vuint8arrayi vbytestringcharcodeati try vblob new blobvuint8arraybuffer type vmimetype catche windowblobbuilder windowblobbuilder windowwebkitblobbuilder windowmozblobbuilder windowmsblobbuilder if ename typeerror windowblobbuilder vblobbuilder new blobbuilder vblobbuilderappendvuint8arraybuffer vblob vblobbuildergetblobvmimetype else if ename invalidstateerror vblob new blobvuint8arraybuffer type vmimetype else alertmystringsunsupportedfile return vblobis there any way to get this working in the native android browser,"['javascript', 'android']" +445542,facebook ios sdk 321 nserror fberrorshouldnotifyuser unrecognized selector sent to instance i just upgraded my app from facebook ios sdk 31 to 321 and i am trying to take advantage of the new error handling provided by the new fberror category on nserror the code is at the bottom it compiles fine but when a fb error occurs i get the following at run time nserror fberrorshouldnotifyuser unrecognized selector sent to instancethis seems like a linker error where the category is not getting linked in from the the facebooksdk static library i tried adding both the objc and all load flags under the other linker flags in the target i read this but still no luckbasically the same code works fine in the sample projects provided by facebook thanks for any suggestions open the facebook session voidopensession nsarray permissions nsarray alloc initwithobjectsemail nil open or reopen the active session fbsession openactivesessionwithreadpermissionspermissions allowloginuiyes completionhandlerfbsession session fbsessionstate state nserror error self sessionstatechangedsession statestate errorerror voidhandleautherrornserror error nsstring alertmessage alerttitle if errorfberrorshouldnotifyuser if the sdk has a message for the user surface it this conveniently handles cases like password change or ios6 app slider state alerttitle something went wrong alertmessage errorfberrorusermessage else if errorfberrorcategory fberrorcategoryauthenticationreopensession it is important to handle session closures as mentioned you can inspect the error for more context but this sample generically notifies the user alerttitle session error alertmessage your current session is no longer valid please log in again else if errorfberrorcategory fberrorcategoryusercancelled the user has cancelled a login you can inspect the error for more context for this sample we will simply ignore it nsloguser cancelled login else for simplicity this sample treats other errors blindly but you should refer to for more information alerttitle unknown error alertmessage error please try again later nslogunexpected error error if alertmessage uialertview alloc initwithtitlealerttitle messagealertmessage delegatenil cancelbuttontitleok otherbuttontitlesnil show handle facebook session state changed voidsessionstatechangedfbsession session statefbsessionstatestate errornserror error if error self handleautherrorerror else switch state case fbsessionstateopen self onsessionopensession break case fbsessionstateopentokenextended self onsessionopensession break case fbsessionstateclosedloginfailed self onsessioncloseerror break case fbsessionstateclosed noop see session is closed but token is still cached for later use break default nslogsessionstatechanged unknown state d state break updatea friend advised that i check if the selector actually exists in the linked binary i followed the instructions here to find the location of the debug binary in the finder where is my application binary in xcodethen i rightclicked on myappapp and chose show package contents found the binary file it was the largest file in the list dragged it into vim and searched for fberrorshouldnotifyuser i could not find this selector or any of the fberror selectorsi also tried clearing xcodes derived data still no luckupdate 2ugh sometimes you totally miss the obvious answer it turns out i did not have the objc flag properly set for my debug builds see screenshotthanks to dkendall for getting me to check this again,['ios'] +445552,mfc tooltips only show up on special occasions i have been tasked with assigning tooltips to each item in a configuration menu i have completed adding the tooltip to each control on the page but it seems sometimes the tooltip shows up and sometimes it does not depending on the position of the control on the screen to tooltiperize the pages i firstenabletooltipstruein each cpropertypages oninitdialog method i then add the notification mapon notify exttn needtext 0 ontooltiptextwith the function ontooltiptext looking as suchbool ccfgprefpageontooltiptext uint id nmhdr pnmhdr lresult presult tooltiptext pt tooltiptext pnmhdr uint nid pnmhdridfrom if ptuflags ttf ithishwnd nid getdlgctrlidhwndnid ifnid if nid getdlgitemidc pickthist editgetdlgctrlid tcsncpy sptsztext ttool tip text truncate else if nid getdlgitemidc endpttol editgetdlgctrlid tcsncpy sptsztext ttool tip text truncate ptlpsztext ptsztext sanity check pthinst afxgetresourcehandle do not think this is needed at all return true return falseit seems for some of my controls the tool tip will not show up for most of the check box controls the tool tip thisplays but for a few they just do not show there are no other controls covering them up they are not thisabledanother thing if i use the nonstandard cursor windows repeatedly flashes the tool tip so much so it is unreadable in some cases how can i fix this this is not a problem on cedit controls so why is it a problem elsewhereedit update the controls that have been on the pages for years seem to show tool tips any control that i try to add nowtoday will not show tool tips at all no matter the position control type settings i cannot get a single tool tip to show on a newly inserted control,['c++'] +445555,how to animate jquery addclassremoveclass functions i want to know how to animate jquery addclassremoveclass functionsfor animate function it seems that i have to put some css properties but what about if i have a class which makes element thisplayed as block each time i trigger a click function while all elements are thisplayed as hidden in css how can i animate this processheres my codescript srcjsjquery191minjsscriptscript var allslides li nextslideclickfunction var nextslide activenext if nextslidelength 0 var nextslide allslidesfirst activeremoveclassactive nextslideaddclassactive return false prevslideclickfunction var prevslide activeprev if prevslidelength 0 var prevslide allslideslast activeremoveclassactive prevslideaddclassactive return false script,['jquery'] +445579,why is resharper suggesting a possible nullreferenceexception on a dynamic type if i write the following code resharper is warning me for a possible nullreferenceexception however i am explicitly checking for null in the statement above is there something about dynamic i do not know about is it assuming it might be backed by a ienumerable or something like that or is this a glitch with resharper or something elsedynamic user connectionqueryselect firstordefault dapper extensionif user null return nullreturn new useruserusername local variable dynamic user possible systemnullreferenceexception,['c#'] +445600,strange behavior from net regarding file paths i could not find any information on this through professor google so here i am take the given path name and paste it into windows explorer i stumbled across this after thiscovering bug in my code that generated the paths with an extra in the path name before a directory separatorcpathtofileextin code net will accept the path when calling filecreate and a file will be generated but at this pathcpathtofileextcopying cpathtofileext into windows explorers address bar and watch the thisappear and take you to cpathtofileextis it normal behavior for net and windows to it is not causing an issue because the is being removed by both net and windows when passed into file operations the real issue is that all the files in the db have filenames with a but exists in paths that do not have a and fileexists works too although the path is not the real physical locationwhats going on here,"['c#', '.net']" +445604,hide empty i want to hide all the li if they are empty or if there any blank space in lii am doing it like thisliemptyfilterfunctionivreturn trimvtextlength 0cssthisplay noneis this the wrong syntaxif i create a class to make empty li invisible it works fine like thisliclasshidelifilterfunctionivreturn trimvtextlength 0cssthisplay nonebut i do not know which li will be empty can anybody help me plzi want to do thisplaynone if the li is emptyhere is my codescript srcscriptscript documentreadyfunction tdemptycssthisplay none divemptycssthisplay none trimliemptyhide liclasshidelifilterfunctionivreturn trimvtextlength 0cssthisplay none scriptul li styleborderred solid 1px hili li stylebordergreen solid 1px li li styleborderblue solid 1px classhideli li ulthanks,"['jquery', 'html']" +445609,bad notification posted from package could not expand remoteviews i have a problem some times my service is forcefully closed with this logcat0326 204849 eandroidruntime12080 fatal exception main0326 204849 eandroidruntime12080 androidappremoteserviceexception bad notification posted from package byflipdevvkspy could not expand remoteviews for statusbarnotificationpkgbyflipdevvkspy id1 tagnull score0 notnnotificationpri0 contentviewbyflipdevvkspy0x1090071 vibratenull soundnull defaults0x0 flags0x2 kindnull0326 204849 eandroidruntime12080 at androidappactivitythreadhhandlemessageactivitythreadjava13740326 204849 eandroidruntime12080 at androidoshandlerthispatchmessagehandlerjava990326 204849 eandroidruntime12080 at androidoslooperlooplooperjava1370326 204849 eandroidruntime12080 at androidappactivitythreadmainactivitythreadjava49310326 204849 eandroidruntime12080 at javalangreflectmethodinvokenativenative method0326 204849 eandroidruntime12080 at javalangreflectmethodinvokemethodjava5110326 204849 eandroidruntime12080 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava7910326 204849 eandroidruntime12080 at comandroidinternaloszygoteinitmainzygoteinitjava5580326 204849 eandroidruntime12080 at dalviksystemnativestartmainnative methodthis is my code to add add notificationsprotected void addnotificationfinal bitmap avatar final int small image id final int notify id final string text final string title final boolean ongoing final boolean ticker final string tickertext final boolean autocancel final string notificationcategory final int notificationvalue try final intent notificationintent new intent getapplicationcontext checkeractivityclass notificationintent putextranotificationcategory notificationvalue notificationintentsetflagsintentflag activity clear top intentflag activity single top final pendingintent contentintent pendingintentgetactivity getapplicationcontext notify id notificationintent pendingintentflag update current final notificationmanager nm notificationmanager context getsystemservicecontextnotification service final notificationcompatbuilder builder new notificationcompatbuilder context if ticker buildersetcontentintentcontentintent setsmalliconsmall image id setongoingongoing setlargeiconavatarsettickertickertext setwhensystemcurrenttimemillis setautocancelautocancelsetcontenttitletitle setcontenttexttext onn n2 341412 n else buildersetcontentintentcontentintent setsmalliconsmall image id setlargeiconavatar setongoingongoing setwhensystemcurrenttimemillis setautocancelautocancelsetcontenttitletitle setcontenttexttext onn n2 341412 n final notification and buildergetnotification nmnotifynotify id n catch final exception e todo add exception handling code why is my service killed,['android'] +445612,auto column width in epplus how to make columns to be auto width when texts in columns are longi use this code worksheetcolumncolindexautofitcolumn on all columns worksheetcellsautofitcolumns worksheetcolumncolindexbestfit true on all columnsnone of these methods are workingis there any ways to make it worknotesome of my texts use unicode,"['c#', '.net']" +445622,rounding bigdecimal to always have two decimal places i am trying to round bigdecimal values up to two decimal placesi am usingbigdecimal rounded valueroundnew mathcontext2 roundingmodeceilingloggertracerounded to value roundedbut it does not do what i want consistentlyrounded 0819 to 082rounded 1092 to 11rounded 1365 to 14 should be 137rounded 2730 to 28 should be 274rounded 0819 to 082i do not care about significant digits i just want two decimal places how do i do this with bigdecimal or is there another classlibrary better suited to this,['java'] +445683,richtextbox and tab key i created a richtextbox and i noticed that when i press tab key it is not doing anythingit is suppose to do some space but it do nothow can i access it,['c#'] +445734,how to determine first week day in ios i am using tapkus calendar in my application and i want to determine if the week should start on a sunday or a monday depending on the users settings i am calling firstweekday but for some reason it returns 1 sunday on a device where the builtin calendar starts the weeks on mondays and hence it should return 2nscalendar cal nscalendar alloc initwithcalendaridentifiernsgregoriancalendarcal firstweekdayany suggestions as to what i might be missing,"['ios', 'objective-c']" +445757,flattening a list of dictionaries so my aim is to go fromfruitcolourmapping apple red banana yellowto finalmap apple red banana yellowa way i got is from itertools import chain fruits listchainfrom iterabledkeys for d in fruitcolourmapping colour listchainfrom iterabledvalues for d in fruitcolourmapping return dictzipfruits colouris there any better more pythonic way,['python'] +445907,how to check if cd drive is open or closed in linux i am making an application that requires the knowledge of whether a cd drive is open or closedeject opens the cd drive and checks how long it takes to open a shorter amount of time says it is open and a longer well but i cannot use this technique because the application actually opens the drive and i do not want to reopen the drive if it is closed neither do i want to close the drive if it is openhow would i do this on linux i saw that it is possible to do this under windows might be wrong though but i have not seen a way of doing this on linuxif it is not possible using linux api calls is it possible to implement a lowlevel function that could do this,"['c++', 'c']" +445982,how to detect double precision floating point overflow and underflow i have following variablesdouble dblvar1double dblvar2they may have big values but less than double maxi have various arithmetic on above variables like addition multiplication and powerdouble dblvar3 dblvar1 dblvar2 double dblvar4 dblvar1 dblvar2double dblvar5 powdblvar1 2in all above i have to check overflow and underflow how can i achieve this in c,['c++'] +445986,java beginner cannot find symbol i have been scouring the java textbook for hours trying to determine what i am doing wrong the error i am getting back is cannot find symbol on line 13 which is the line with the code systemoutprintlnthe three initials are getinitialsharry joseph hackerthe instructions are commented in the code i am pretty sure it has to do with the names i have set up but i am not surepublic class initialstest gets the initials of this name params first middle and last names return a string consisting of the first character of the first middle and last name public static void mainstring args systemoutprintlnthe three initials are getinitialsharry joseph hacker public static string getinitialsstring one string two string three string initials onesubstring01 twosubstring01 threesubstring01 return initials,['java'] +445989,import csv into sql server including automatic table creation i have several csv files which i want to import into an sql server database i know if this is possible with bulk insert but i want a solution so that also the import table is automatically created before on basis the first row of the csv filesare the column names,['sql'] +446001,upgrading a varchar column to enum type in postgresql we have a varchar column in a table that we need to upgrade to enum typeall the values in the varchar column are valid values in the enumeration there is no null values in the varchar columnalter table tablename alter column varcharcolumn type enum typeerror column varcharcolumn cannot be cast to type enum typesql state 42804the round about way is tocreate another new column with enum typeupdate the enum type column with the varchar column after typecastingdrop the varchar columnrename the enum type column name to the varchar column nameis there a better way to achieve thisthanks in advance,['sql'] +446021,is it possible to execute a java code string at runtime in android i want to get a line of java code from user and execute it in android for examplestring strexecutable int var var 4 3object obj alibraryevalstrexecutableit is not java script and i want to run a java codeis it possible if yes howi have studied links like this but they are questions about jvm not android dalvik,"['java', 'android']" +446099,how to create ui elements lazily in wpf we are creating a wpf application which makes heavy use of highly decorated input elements a simple example of decorated element is a textbox which looks like a readonly textblock when it does not have focus and turns into a textbox after receiving focus also additional visual feedback is provided when the changed value is being saved to database the problem is that showing a view that contains lots of these elements let us say 100 is very slow and makes application very unresponsivewe have implemented this decorator as usercontrol which contains all required elements for example the textblock to show unfocused text and rotating image for busy indicator then we add the input element as child of this decorator control meaning that in addition to all extra elements the decorator also contains the input element in its visual tree in xaml this would look likecustomdecorator contextbinding valuehelper textbox textbinding valuehelpertextcustomdecoratorthis makes it easy for us to decorate any input element we want be it either text box date picker combobox or any custom element now back to the problem let us say we have a view which contains 100 decorated text boxes and we navigate to that view what happens at least my quadcore laptop freezes for a long time because it has to create many hundred text blocks rectangles images etc to provide the visual feedback for every decorated element although no decorations are visible yet what really would be required is only 100 textblocks because that is what is visible on the screen it is only after element receives mouse over event or focus when other elements are needed also only one element is being edited at a time so only one input element in this case textbox would be enough for the whole applicationso what would be the best way to achieve same decorations without creating all decorating elements or the actual input element for every element in the viewan example of decorated textbox to clarify usecasethe text box looks like a readonly textblock when it does not have focus or mouse cursor is not currently on top of it state 1 also three dots are shown because element does not currenly have any value when mouse cursor is moved on top of the element a dotted green rectangle appears around textblock to indicate that element can be modified state 2 the color would be red if textbox happened to be readonly after receiving focus element turns into actual textbox which can be used to modify the actual value state 3 the value is stored into database after textbox loses its focus and to show that the value is currently being saved a busy indicator appears to left side of element state 4 finally the value has been saved and element returns to its idle state showing the new value state 5 actually the elements have even more states related to validation and other specific requirements but you certainly got the point that elements really are highly decorated,['c#'] +446106,how to stop toast alertdialog losing focus on my edittext filter updatelatest update getchanges method has been addedsecond update i have added the whole of my shoppinglistjava classfirst update after 2 people liking the question but no answers i have opened up a bounty for this questionquestioni have had similar issues to this where i am unable to to refilter my listview once i start a new intent and then return back to the original page this was solved with the use of an overiding the onresume method and recalling my filter code from another filter methodthe latest issue im having is should a dialogbuilder or a toast message be used on my app page then once again the filter text is blanked ie any text entered into my filter edittext is ignored by my filterhere are some screenshots to highlight the issueloaded listview of the itemsa search term is entered into the filter edittext and filter correctlythe first item a is edited to ab the toast message confirms the actionthis is the issue the dialogbuilderwhich is how the item is edited and toast message are complete a new filter term is entered into the edittext and the filter no longer filtershere is my filter codepackage comexampleflybaseapp public class shoppinglist extends listactivity implements onclicklistener button additembutton showshoplistview showitemssimplecursoradapter cursoradapterlong itemidtextview totalpricestring itemdescriptionint itemamountint itempriceedittext itemnameeditdbhandlershop getconsdialog e1overrideprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutshoppinglistlayout additem button findviewbyidridbtnadditem showshop button findviewbyidridbtnsearchshops showitems listview findviewbyidandroidridlist totalprice textview findviewbyidridtotallistprice additemsetonclicklistenerthis showshopsetonclicklistenerthis setlist int setprice updatetotal totalpricesettextintegertostringsetprice itemnameedit edittext findviewbyidridinputitemname showitemssettextfilterenabledtrue itemnameeditaddtextchangedlistenernew textwatcher override public void aftertextchangededitable s override public void beforetextchangedcharsequence s int start int count int after override public void ontextchangedcharsequence s int start int before int count cursoradaptergetfilterfilterstostring showitemsrefreshdrawablestate getcons new dbhandlershopthis null null getconsopen cursoradaptersetfilterqueryprovidernew filterqueryprovider public cursor runquerycharsequence constraint return getconsgetchangesconstrainttostring showitemssetadaptercursoradapteroverridepublic void onclickview clickedadd switch clickedaddgetid case ridbtnadditem show break case ridbtnsearchshops intent checkgps new intentcomexampleflybaseappcheckgps startactivitycheckgps break overrideprotected void onlistitemclicklistview l view v int position long idd superonlistitemclickl v position idd itemid idd final charsequence items edit item delete item builder alertdialogbuilder new alertdialogbuildershoppinglistthis alertdialogbuildersettitleitem options alertdialogbuildersetitemsitems new dialoginterfaceonclicklistener public void onclickdialoginterface dialog int item if itemsitemequalsedit item alertdialogbuilder builder new alertdialogbuilder shoppinglistthis buildersettitleedit item dbhandlershop setedit new dbhandlershop shoppinglistthis null null seteditopen string itemname seteditgetitemitemid int itemamount seteditgetitemquanitemid int itemprice seteditgetitemcostitemid seteditclose linearlayout layout new linearlayout shoppinglistthis layoutsetorientationlinearlayoutvertical final edittext titlebox new edittext shoppinglistthis titleboxsettextitemname titleboxsethintitem name layoutaddviewtitlebox final edittext quantitybox new edittext shoppinglistthis quantityboxsettextintegertostringitemamount quantityboxsethintitem quantity layoutaddviewquantitybox final edittext pricebox new edittext shoppinglistthis priceboxsettextintegertostringitemprice priceboxsethintitem price layoutaddviewpricebox buildersetviewlayout buildersetpositivebuttonok new dialoginterfaceonclicklistener public void onclick dialoginterface dialog int whichbutton editable valueitem titlebox gettext editable valueamount quantitybox gettext editable valueprice pricebox gettext string itemdescription valueitem tostring string s valueamounttostring int itemamount integer parseints string a valuepricetostring int itemprice integerparseinta try dbhandlershop update new dbhandlershop shoppinglistthis null null int totalcombined itemamount itemprice updateopen updateupdateitemitemid itemdescription itemamount itemprice updateclose int setprice updatetotal totalpricesettextinteger tostringsetprice catch exception e toastmaketext getapplicationcontext items not updated toastlength short show finally toastmaketext getapplicationcontext items updated toastlength short show setlist buildersetnegativebuttoncancel new dialoginterfaceonclicklistener public void onclick dialoginterface dialog int whichbutton buildershow else if itemsitemequalsdelete item try dbhandlershop delete new dbhandlershop shoppinglistthis null null deleteopen deletedeleteitemitemid deleteclose dbhandlershop findprice new dbhandlershop shoppinglistthis null null findpriceopen int returnedcost findprice getitemcostitemid findpriceclose int cost updatetotal int newtotal cost returnedcost totalpricesettextintegertostringnewtotal catch exception e toastmaketextgetapplicationcontext item failed to be deleted toastlength shortshow finally toastmaketextgetapplicationcontext item deleted from the list toastlength shortshow setlist alertdialogbuildershowsuppresswarningsdeprecationprivate void setlist dbhandlershop dbshop new dbhandlershopthis null null dbhandlershop searchitems new dbhandlershopthis null null searchitemsopen cursor cursor searchitemsgetitems startmanagingcursorcursor searchitemsclose string from new string dbshopkey itemshop dbshopkey itemnum dbshopkey itemprice int to new int ridtxtsetitem ridtxtsetamount ridtxtsetprice cursoradapter new simplecursoradapterthis rlayoutsetshoppinglist cursor from to showitemssetadaptercursoradapterprivate int updatetotal dbhandlershop total new dbhandlershopthis null null int totalprice 0 totalopen cursor totalprices totalgettotals totalclose if totalprices null startmanagingcursortotalprices if totalpricesmovetofirst do int cost totalpricesgetint3 int amount totalpricesgetint2 int totalcost cost amount totalprice totalcost while totalpricesmovetonext return totalprice else return totalprice return 0private void show alertdialogbuilder builder new alertdialogbuildershoppinglistthis buildersettitleenter item details linearlayout layout new linearlayoutthis layoutsetorientationlinearlayoutvertical final edittext titlebox new edittextthis titleboxsethintitem name layoutaddviewtitlebox final edittext quantitybox new edittextthis quantityboxsethintitem quantity layoutaddviewquantitybox final edittext pricebox new edittextthis priceboxsethintitem price layoutaddviewpricebox buildersetviewlayout buildersetpositivebuttonok new dialoginterfaceonclicklistener public void onclickdialoginterface dialog int whichbutton try editable valueitem titleboxgettext editable valueamount quantityboxgettext editable valueprice priceboxgettext itemdescription valueitemtostring string s valueamounttostring itemamount integerparseints string a valuepricetostring itemprice integerparseinta dbhandlershop additem new dbhandlershop shoppinglistthis null null additemopen additeminsertitemsitemdescription itemamount itemprice additemclose catch exception e toastmaketextgetapplicationcontext item failed to be added toastlength short show finally toastmaketextgetapplicationcontext item added to your list toastlength short show int cost updatetotal totalpricesettextintegertostringcost setlist buildersetnegativebuttoncancel new dialoginterfaceonclicklistener public void onclickdialoginterface dialog int whichbutton buildershowoverrideprotected void onresume superonresume setlist showitemssettextfilterenabledtrue itemnameeditaddtextchangedlistenernew textwatcher override public void aftertextchangededitable s override public void beforetextchangedcharsequence s int start int count int after override public void ontextchangedcharsequence s int start int before int count cursoradaptergetfilterfilterstostring showitemsrefreshdrawablestate getcons new dbhandlershopthis null null getconsopen cursoradaptersetfilterqueryprovidernew filterqueryprovider public cursor runquerycharsequence constraint return getconsgetchangesconstrainttostring showitemssetadaptercursoradaptergetchanges from the database handler classpublic cursor getchangesstring constraintpassed string columns new stringkey rowshopid key itemshop key itemnum key itemprice cursor c null ifconstraintpassedequals c ourdatabasequerydatabase tableshop columns null null null null null else c ourdatabasequerydatabase tableshop columns key itemshop like constraintpassed null null null key itemshop asc null if c null cmovetofirst return c do i need to implement a lifecycle method once the edit has been made if so could someone push me in the right direction of which is needed as i have tried onresume and onrestart to no avail,"['java', 'android']" +446112,ckeditor automatically strips classes from div i am using ckeditor as a back end editor on my website it is driving me round the bend though as it seems to want to change the code to how it sees fit whenever i press the source button for example if i hit source and create a divdiv classmyclasome contentdivit then for no apparent reason strips the class from the div so when i hit source again it has been changed todivsome contentdivi presume this irritating behaviour can be turned off in the configjs but i have been digging and cant find anything in documentation to turn it off,['html'] +446140,compile requirejs to remove amd dependency i am using requirejs to manage my dependencies in development but at production i would like to remove all dependencies on an amd loader it looks like the requirejs optimizer creates a file that still uses an amd load at runtime i am just looking to have a static nonamd dependent but still amd compatible file such as what jquery produces from looking at jquery source it appears they manually order their dependencies in their grunt file is this possiblei am open to using other libraries other than requirejs as wellnote this is similar to my other question javascript requirejs in development but compiled in production but in this case i want to remove amd all together,['javascript'] +446168,html5 canvas strokestyle i am trying to map an image to a 3d grid that simulates cloth using strokestyle and canvas i have the image included but it is currently acting as a background image and not actually flowing with the cloth as is ripples ie the image is static as the grid flowsheres the jsfiddle which is self explanatory only works in chrome any help is much appreciatedhere is the javascript that renders the image into the background how do i stop from rendering as a background image and only make it fill the grid function update var img new image imgsrc texturesimagesfreestonewalltexture002jpg imgonload function create pattern var ptrn ctxcreatepatternimg repeat ctxclearrect0 0 canvaswidth canvasheight physicsupdate ctxstrokestyle ptrn ctxbeginpath var i pointslength while i pointsidraw ctxstroke requestanimframeupdate herss the original codepen i am working from updated fiddle with image outside function updateit currently seems to actually fill the cells as well as applying it as a background image is there any way to stop it becoming a background image and only apply it to fill the grid i have tried this ctxfillstyle ptrnand removing line 260ctxstrokestyle ptrnbut it seems to remove the background image just thisplaying it as a black grid thank you again for the patience,['javascript'] +446207,getresource puts a leading before the thisk name using java 17 windows 7 the following gives a leading slash before the thisk namehow can i avoid thatstring pngpath getclassgetresourceresourceslenapnggetpathsystemoutprintlnpngpath pngpathgives pngpath cusersjgrimsdaledocumentsnetbeansprojectshellocvbuildclassesresourceslenapng,['java'] +446213,adb is not starting no error message i am trying to run adb when i run adb startserver it hangs during a while and then no messageafter that the command adb getstate receive the answer error protocol fault no statusif i run then adb killserver the answer is server not running i am using windows 7 an admin has elevated my rights to local admin but it did not solve anything i used resources monitor to verify if any other app is using the ports of adb but it is not the caseon the step 3 indicates to enable usb web debugging under settings advanced devtoolsbut on my test phone there is no advanced category in the chrome settings i could not find out either what is the version of chrome installedsomewhere on the web i saw a suggestion to change the rights of tmpandroid to allow read write for all users but in cusersmeappdatalocalandroidandroidsdktemp there is no android folderso i am pretty desperate now any help would be immensely appreciatedthanksolivieredit 1 i couldt find enable usb web debugging because it was android browser and not chrome a bit ridiculous yes i did not know that using another device with a proper chrome installed i could check the option there but adb is still crashing at startupedit 2 i did a wild guess that there was some write issue with the platformtools folderso i uninstalled everything using the sdk manager i deleted the whole adtbundlewindowsx86 64 then i unzipped it elsewhere on c strange thing is when i launch sdkmanagerexe several packages are already marked as installed toolsandroid sdk toolstoolsandroid sdk plateformtoolsandroid 422sdk plateformandroid 422arm eabi v7a system imageextrasandroid support libraryi tried deinstall them again delete the folder unzip again and reinstall but still same result it seems that somehow it is installed wrong but refuses to uninstall properly anyone knows how to force the unistallation edit 3 output of adb startserver after having used set adb trace1cadtbundlewindowsx86 6420130219sdkplatformtoolsadb startserversystemcoreadbadbcmainhandling commandlinesystemcoreadbadb clientc adb connect adb connect hostversionsystemcoreadbsysdeps win32csocket loopback clientsocket loopback client port 5037 type tcp fd 100systemcoreadbtransportcwritexwritex fd100 len4 30303063 0csystemcoreadbtransportcwritexwritex fd100 len12 686f73743a76657273696f6e hostversionsystemcoreadbtransportcreadxreadx fd100 wanted4systemcoreadbtransportcreadxreadx fd100 thisconnectedsystemcoreadbsysdeps win32cadb closeadb close 100loclient5037systemcoreadbadb clientcadb connectadb connect service hoststartserver,['android'] +446259,delete one specific fragment from the android backstack for a android tablet application i use 2 fragments one on the left side on the screen and one on the right side when you click on a button at the right fragment another fragment wil be added on the top of the right fragment this fragment is added to the backstack fragmenttransaction ft getfragmentmanagerbegintransaction ftaddridfragmentlayout fragment2ftaddtobackstackfragment2ftcommitthe backstack is nowfragment 1 fragment 2on the left side is also a button that opens a fragment on top of the left fragment same as fragment2 and adds it to the backstack the backstack is nowfragment 1 fragment 2 fragment 3on fragment 2 is a button to close that fragment getfragmentmanagerpopbackstackfragment2 fragmentmanagerpop back stack inclusivethe problem is when i only want to close fragment 2 fragment 3 will also be destroyed i can remove the fragment manualy by callingfragmenttransaction ft getactivitygetsupportfragmentmanagerbegintransactionftremovefragment2commitbut the backstack will remainfragment 1 ghost fragment 2 fragment 3so you need to press back one time more to close the applicationis there a way to only remove fragment 2 from the backstack and leave fragment 3 on the screen,['android'] +446267,jsfiddle what is my fiddles javascript js url so i can reuse it by src what is the url to get and only get this fiddles javascript code so later on i may use it for tests by calling it using a script rel srcscript link something like script relscript srcscriptjsfiddle store versions of our scripts which my ide does notedit iam aware of the show page my question is is there an independant js page edit as of march 2013 the following patterns works pls 1 dannys answershow jsshow cshow html,"['javascript', 'jquery']" +446269,google signin for serverside apps auth not working i trying to add google auth for wordpress sitewhat i want after auth in google if user not registered on site i redirect him to page where he enters his username if user already registered it will be logged inhere my js codefunction dogoogleplusloginauthresult if authresultcode jquerysigninbuttonattrstyle thisplay none jqueryajax url php echo site url wpadminadminajaxphp type get datatype json data action login gplus code authresultcode success functionresult else if authresulterror here my php codefunction login gplus response arrayif isset getcode empty getcode session start client new google client clientsetapplicationnametest clientsetaccesstypeoffline clientsetclientidget optionsocial gplus client id clientsetclientsecretget optionsocial gplus client secret clientsetdeveloperkeyget optionsocial gplus api key clientsetredirecturiget optionsocial gplus redirect uris clientsetapprovalpromptauto code getcode clientauthenticatecode token json decodeclientgetaccesstoken requrl token tokenaccess token req new google httprequestrequrl tokeninfo json decode clientgetio authenticatedrequestreq getresponsebody if tokeninfoerror responsetest tokeninfoerror send json responseresponse die if tokeninfoaudience get optionsocial gplus client id responsetest tokens client id does not match apps send json responseresponse die responsetest succesfully connected with token print rtoken truesend json responseresponsedieuser successfully authorized in google but in php i got thisfatal error uncaught exception google authexception with message error fetching oauth2 access token message redirect uri mismatch in varwhtmlv4wpcontentpluginssocialgoogleplusgoogleapiauthgoogle oauth2php113stack trace0 varwhtmlv4wpcontentpluginssocialgoogleplusgoogleapigoogle clientphp131 google oauth2authenticatearray 4scmptqeiwt0sj1 varwhtmlv4wpcontentpluginssocialgoogleplusfunctionsphp35 google clientauthenticate4scmptqeiwt0sj2 internal function login gplus3 varwhtmlv4wpincludespluginphp406 call user func arraylogin gplus array4 varwhtmlv4wpadminadminajaxphp74 do actionwp ajax nopriv 5 main thrown in varwhtmlv4wpcontentpluginssocialgoogleplusgoogleapiauthgoogle oauth2php on line 113in app settings redirect uris specified as what do i do wrongeditgoogle signin button definitionspan idsigninbutton span classgsignin datacallbackdogooglepluslogin dataclientidphp echo thisgplus client id datacookiepolicysingle host origin dataaccesstypeoffline datarequestvisibleactions datascope spanspansocial gplus redirect uris is examplecomwpadminadminajaxphpactionlogin gplus,"['php', 'javascript']" +446293,can do i use testacular to test web pages that are not not on my localhost can do i use testacular to test web pages that are not not on my localhostthe external app was developed using angularjsin my test i tried doing browsernavigatetotest app which is not on localhosti cannot verify the url in my test i get this error locationurltypeerror object object object has no method injector at objectanonymous localhost pathangularscenariojs2540730,['javascript'] +446298,when is a python operator a line continuation the following is syntactically invalidif extremely long condition that takes up a whole line and another condition do somethingthe following is validif extremely long condition and another condition do somethingwhy are these different more generally why is 2 okay but 1 somehow dangerousambiguous i cannot see how the first statement is or generalizes to an ambiguous statement,['python'] +446310,why can dd read from a pipe faster than my own program using ifstream i have two programs that pass data to each other via linux pipes named or otherwise i need to hit a transfer rate of 2600 mbs between the two programs but am currently seeing a slower rate of about 2200 mbs however i found that if i replace my 2nd process with dd instead the transfer rate jumps to over 30 mbs is there something about the way my program is reading from the pipe that is less efficient than the way dd does it what can i do to improve this throughput is ifstream inherently slower than other methods of reading binary data from pipeto summarize the two scenariosscenario 1program 1 named pipe program 2yields 2200 mbs transfer ratescenario2program 1 named pipe dd ifpipename ofdevnull bs8myields 30 mbs transfer ratehere is the way my program 2 currently reads from pipeifstream inputfileinputfileopeninputfilenamec str iosin iosbinarywhile keeplooping inputfilereadbuffer0 810241024 bytesread inputfilegcount do something with dataupdatei have now tried using readfd buffer0 810241024 instead of istream seemed to show a mild improvement but not as much as ddi also tried using streamrdbufsgetnbuffer0 810241024 instead of streamread which did not help,['c++'] +446336,fstream would not create a file i am simply trying to create a text file if it does not exist and i cannot seem to get fstream to do thisinclude fstreamusing stdfstreamint mainint argc char argv fstream file fileopentesttxt file test fileclosedo i need to specify anything in the open function in order to get it to create the file i have read that you cannot specify iosin as that will expect an already existing file to be there but i am unsure if other parameters need to be specified for a file that does not already exist,['c++'] +446359,asynchronous downloading of images for uitableview with gcd i am downloading images for my uitableview asynchronously using gcd but there is a problem when scrolling images flicker and change all the time i tried setting image to nil with every cell but it does not help muchwhen scrolling back up fast all images are wrong what can i do about thathere is my method for cells uitableviewcell tableviewuitableview tableview cellforrowatindexpathnsindexpath indexpath static nsstring cellidentifier cell uitableviewcell cell tableview dequeuereusablecellwithidentifiercellidentifier forindexpathindexpath if selfloaderparseddataindexpathrow nil cellimageviewimage nil thispatch queue t queue thispatch get global queuethispatch queue priority high 0ul thispatch asyncqueue void nsdata imagedata nsdata datawithcontentsofurlnsurl urlwithstringselfloaderparseddataindexpathrow objectforkeyimagelr uiimage image uiimage alloc initwithdataimagedata thispatch asyncthispatch get main queue cellimageviewimage image cell setneedslayout celltextlabeltext selfloaderparseddataindexpathrow objectforkeyid return cell,"['ios', 'objective-c']" +446365,how to stylize the input checkbox in twitter bootstrap i have to make a input checkbox simple but could not find some kind of optional class at bootstrap also searched on github some library and could not find anything simple as making foundationthanks for help,['css'] +446386,prevent iphone autolock but permit screen dimming i have an application which works in a hands busy environment so the user rarely touches the device of course the phone goes into autolock and my app stops working i used this code uiapplication sharedapplication setidletimerthisabledyesto prevent the device and that is fine however i would still like the screen to autodim the above code keeps the screen from autodimming as well as autolockingthis question shows me how i can dim the screen manually and that just may be a good enough solution but i would rather use system settings not app settingsso how can i prevent autolock while still getting the autodim,['ios'] +446397,option sql select limitdefault i have a mysql database on netbeans and i want to see that view data but i have a error 1064 option sql select limitdefault how can i fix thanks,"['java', 'mysql']" +446422,does a static function need the static keyword for the prototype in c my c programming book says that when i want to create a static function i need to put the static keyword in front of the function definition it does not mention anything explicitly about the prototype also the examples do not use prototypes and simply put the static functions at the top of the file so that they do not need prototypes i am assumingso does a static function need the static keyword for the prototype or do i only put it in front of the definition,['c'] +446458,android silent push i am new to android and i am playing around trying some features here and therei wanted to know what is the way to use silent push meaning get a push notification on the device without any alarm notification or vibration ie without the user to be aware of itif someone have a tutorial he can refer me to i will be more than gratefull,['android'] +446473,referenceerror inject is not defined when i run the specrunner html file i get this errorlooking around this is due to angularmocksjs not being referenced in my case it is being referencedspecrunnerhtml link relstylesheet typetextcss hreflibjasmine131jasminecss script typetextjavascript srclibjasmine131jasminejsscript script typetextjavascript srclibjasmine131jasminehtmljsscript script typetextjavascript srclibangularmocksjsscript include source files here script typetextjavascript srcmainstaticjscontrollersnormdefinitionscontrollerjsscriptwhen the tests are run i get this exception referenceerror inject is not definedi can see that angularmocksjs is referenced and it is not a caching issue as i can see it using firebuglooking in angularmocksjs i can see the full reference angularmockinject function i have tried this as a reference too and get the exception referenceerror angular is not defined,['javascript'] +446605,slowly changing dimension always updating i have a dimension to load which has a field called description with a data type of varchar50 its collation is sql latin1 general cp1256 cs as and it contains arabic data such as uu2 u1u its source has the same type size and collation but every time i load the dimension this field gets updated why does this happen,['sql'] +446612,backbonejs validate collection backbonejs offers validation for models but there is no a simple way to check all models in collection are valid no isvalid property for collectionsi use a hack like this isempty filtermycollectionmodels functionm return mvalidationerroris there more optimized way to validate collection,['javascript'] +446631,difference of connection pool jdbc and jndi i need to know my understanding on above are correctin connection pool you set multiple connection with the use of javasqldatasourcein jdbc we directly specify the connection url and oraclejdbcdriveroracledriver and its always one connection where another request has to wait until the connection finish processing and with jndi its similar to direct jdbc where we refer the jdbc setting via a name so that we can specify the connection url and other setting in the application server and not bound to the application right,['java'] +446646,error failed to install apk on device emulator54 timeout i have run my application using an emulator its taking so long time of about 5 mins to upload 2 mins of installing my application on my emulator after the two minutes it failsthis is the error console20130328 141318 newwaterreadingapp 20130328 141318 newwaterreadingapp android launch20130328 141318 newwaterreadingapp adb is running normally20130328 141318 newwaterreadingapp performing comexamplenewwaterreadingappmainactivity activity launch20130328 141318 newwaterreadingapp automatic target mode using existing emulator emulator56 running compatible avd newavd water electricity reading20130328 141318 newwaterreadingapp uploading newwaterreadingappapk onto device emulator5620130328 141831 newwaterreadingapp installing newwaterreadingappapk20130328 142035 newwaterreadingapp failed to install newwaterreadingappapk on device emulator5620130328 142035 newwaterreadingapp null20130328 142037 newwaterreadingapp launch canceledmy application is located in eprojects folder and i have increased my adb timeout to 150ms but still i see that my application is not loaded on to emulator,['android'] +446678,android emulator error system ui has stopped i have recently set up my android development environment every thing is alright but when i run my emulator it takes to much time with an error dialog on the emulator screen says unfortunately system ui has stopped and no application runs on iti have recently shifted to 64bit windows7 and using jdk7 and eclipse juno for 64bitmy emulator configuration is given belowcan anyone suggest me what is wrong with it,['android'] +446681,how to share business logic among multiple applications we have to develop and maintain many java web based applications for the same company of different sizes scopes and lifespans some of them are huge and other ones are just simple pages that may live only a few months or days some are already implemented and need refactoring there have one thing in common though they need access to almost the same informationproblemdue to the complexity of the data the company handles we have to deal with many different sources some of them inherited from the ancient times our domain objects may be mapped across many of those sources as an example a contract domain object is mapped to our main database but its related physical files are stored in a document server and the activity related to it is stored in a nosql database therefore adding removing searching any of these objects involves many internal operationsour data sources are although it could be anyas400 using db2 as a databasedocumentum document managermongo dbexternal web servicesother legacy sourceswe normally use glassfish as the application server and maven as our build toolgoal our goal is to create a business layer or library that all of our applications can access and it iscompactconsistanteasy to useeasy to maintainaccessible from many different clientswhat we have found so farwe have been struggling for weeks and still we cannot find anything fully satisfactory some solutionspack all the business logic in one or more jars very easy to share but all the applications will have to contain all the jar dependencies and configuration files and take care of security caching and other stuff difficult to maintain we have to update the jars for every project when there are changescreate an ejb project containing all the logic and access it remotely easy to maintain security caching and configuration only implemented once we are afraid of the penalty of the remote calls as we have noticed in our research it seems to be a bad practice we do not have much experience with ejbscreate an ear project with everything inside and use local access well this is faster than the remote version but it is a hell to maintaingo for osgi we are a bit afraid of this one since it is not as popular as ejb and we have never used it seriouslyis there a common practice for this kind of problemmany thanks,['java'] +446718,how to reduce background image in div tag in my html file i have used a sprytabbledpanels plugin in that there are three div tagsin one div tag my data is less and another div tag my data is more i used hover for that when i hover on first div tag it shows data but there is much empty space at the bottom and in another div tag there is not much spaceso please can i change the height of background image in div tagfollowing is css for background imagemaincontent margin0px 225px marginleftauto marginrightauto margintop35px width900px width100 heightauto height1053px background mozlineargradienttop f c background webkitgradientlinear left top left bottom e5e5e5 toc background filter progiddximagetransformmicrosoftgradientstartcolorstrf endcolorstr0 bordertopleftradius48px bordertoprightradius48px borderbottomleftradius48px borderbottomrightradius48px paddingbottom20px minheight1450px backgroundurlresbackimgpng repeat following are screenshots,"['html', 'css']" +446737,jquery if element does not have parent with specific class i am trying to create an if statement in jquery for elements that have a parent with a specific classthis is what i have come up with so far but it is not rightifmyelemparentsmydiv consolelogtestcan anyone point me in the right direction please,"['javascript', 'jquery']" +446742,why does pygmentrb not highlight tags within properly ie google prettify friendly tags i am calling it in my view like this markdown questionbody this is what my applicationhelper looks likemodule applicationhelper class htmlwithpygments redcarpetrenderhtml def block codecode language pygmentshighlightcode lexerlanguage end end def markdowntext renderer htmlwithpygmentsnewhard wrap true options autolink true no intra emphasis true fenced code blocks true lax html blocks true strikethrough true superscript true redcarpetmarkdownnewrenderer optionsrendertexthtml safe endendbut when it encounters tags like thispre classlangcpp prettyprintoverrideit does not apply the color highlights to that code why is thatps this is generated for instance by stack overflow by doing this language langcpp edit 1or more specifically it seems that it would not format the code tags that are within pre tags once code is not within pre it seems to format it fine how do i remedy thatedit 2the problem seems to be the data that pygmentrb is acting on it is html as can be seen in this gist so what i want to be able to do is to have pygment properly format the code returned in the body attribute of that object in my gist how do i do thatedit 3this is the html code that i would like pygmentrb and redcarpet to perform syntax highlighting onphere is a piece of c code that shows some very peculiar performance for some strange reason sorting the data miraculously speeds up the code by almost 6xppre classlangcpp prettyprintoverridecodeinclude ltalgorithmgtinclude ltctimegtinclude ltiostreamgtint main generate data const unsigned arraysize 32768 int dataarraysize for unsigned c 0 c lt arraysize c datac stdrand 256 with this the next loop runs faster stdsortdata data arraysize test clock t start clock long long sum 0 for unsigned i 0 i lt 10 i primary loop for unsigned c 0 c lt arraysize c if datac gt 128 sum datac double elapsedtime static castltdoublegtclock start clocks per sec stdcout ltlt elapsedtime ltlt stdendl stdcout ltlt sum ltlt sum ltlt stdendlcodepreulliwithout codestdsortdata data arraysizecode the code runs in strong1154strong secondsliliwith the sorted data the code runs in strong193strong secondsliulhrpinitially i thought this might be just a language or compiler anomaly so i tried it in javappre classlangjava prettyprintoverridecodeimport javautilarraysimport javautilrandompublic class main public static void mainstring args generate data int arraysize 32768 int data new intarraysize random rnd new random0 for int c 0 c lt arraysize c datac rndnextint 256 with this the next loop runs faster arrayssortdata test long start systemnanotime long sum 0 for int i 0 i lt 10 i primary loop for int c 0 c lt arraysize c if datac gt 128 sum datac systemoutprintlnsystemnanotime start 10 systemoutprintlnsum sum codeprepwith a similar but less extreme resultphrpmy first thought was that sorting brings the data into cache but my next thought was how silly that is because the array was just generatedppwhat is going on why is a sorted array faster than an unsorted array the code is summing up some independent terms the order should not matterpyou can see the current way that this particular question is being rendered at it is the most popular question on that site the first one that you see you will notice that the code simply has a grey background and is indented there is no pretty highlighting like pygmentrb promises and does on other code snippets similarly to how rorra has illustrated in other examples in his answeri cannot strip out the html because i want to parse it properly ie make sure the spacing etc is included properly the only difference that i want is to get syntax highlighting on the code represented in the body of the question,['ruby-on-rails'] +446755,webapi controller with two get actions i want to have two different get action to query the data by name and id i have these routes configroutesmaphttproute name actionapi routetemplate apicontrolleractionid defaults new id routeparameteroptional configroutesmaphttproute name actionapibyname routetemplate apicontrolleractionname defaults new name routeparameteroptional configroutesmaphttproute name defaultapi routetemplate apicontrollerid defaults new id routeparameteroptional and these actions in the controller httpget public companymodel companyidguid id do something httpget public companymodel companynamestring name do something while a call like this httplocalhost519apicompaniescompanyid3cd97fbc524e47cd836cd709e94c5e1e works and gets to the companyid methoda similar call to httplocalhost519apicompaniescompanynamesomething gets me to 404 not foundbut thishttplocalhost519apicompaniescompanynamenamesomething works finecan anyone explain this behaviour and what am i doing wrong,['c#'] +446827,windows forms toolstripitem visible property is always set to false i am working on a mdi windows forms application my parent form has toolstrip menu and some toolstripdropdownbuttons i want to change the visible property of the toolstripdropdownbutton or to some of the toolstripitems sub buttons that it has accordingly to the permission of the user here is the part of the method that i have wrote to manage thisprivate void settoolstripdropdownvisibilitytoolstripdropdownbutton mainbtn params toolstripitem item mainbtnvisible false foreach toolstripitem tempitem in item tempitemvisible true i am passing as first argument the toolstripdropdownbutton and all other sub buttons as params list however when i get into debug mode in the part foreach toolstripitem tempitem in item the tempitem visible property is marked as false in the designer however this property is set to true you can see that i even try explicitly to change the value to true tempitemvisible true but it seems as if this line is doing nothing the value of visible remains false and i cannot change it this is just the begining of the method and i cannot think of other code that can mess up with the toolstrip items i tried to change the value of mainbtnvisible to true or false thinking that maybe there is any connection but it seems this is not the issues so any idea why this is happening why i cant change the visible value and of course any way to do it,['c#'] +446845,recursive approach versus stack for depth first search i have a method as below which searches a collection and evaluates a condition recursivelypublic static bool recursethis inodeviewmodel node funcinodeviewmodelbool predicate inodeviewmodel currentnode node return predicatecurrentnode nodechildrenselectx recursex predicateanyfound foundalternatively this can be implemented using a stack to avoid recursion as belowpublic static bool usingstackthis inodeviewmodel node funcinodeviewmodel bool predicate var stack new stackinodeviewmodel stackpushnode whilestackany var current stackpop if predicatecurrent return true foreach var child in currentchildren stackpushchild return falsemy question is does the stack version offer any performance benefits when the depth of the tree is large compared to the recursive version,['c#'] +446853,what primitive is used to implement the synchronized keyword when we use synchronized keyword in java which synchronization primitive is used exactly lock semaphore monitor mutex edit how jvm implements the lock at the native level,['java'] +446869,simple way to assign default value with xmlelement defaultvalue annotation i have a simple pojo annotated class via jaxb like that public class mypojo implements serializable private final static long serialversionuid 1234l xmlelementname type required true defaultvalue none notnull protected seismicdataacquisitionsystemtype type xmlelementname ipaddress required true notnull patternregexp 10909204092505310909204092505 protected string ipaddress xmlelementname sealservertcpport defaultvalue 1477 notnull protected int sealservertcpport xmlelementname pamservertcpport defaultvalue 1485 notnull protected int pamservertcpport obtient la valeur de la propriata type return possible object is link seismicdataacquisitionsystemtype public seismicdataacquisitionsystemtype gettype return type dafinit la valeur de la propriata type param value allowed object is link seismicdataacquisitionsystemtype public void settypeseismicdataacquisitionsystemtype value thistype value public boolean issettype return thistype null obtient la valeur de la propriata ipaddress return possible object is link string public string getipaddress return ipaddress dafinit la valeur de la propriata ipaddress param value allowed object is link string public void setipaddrestring value thisipaddress value public boolean issetipaddress return thisipaddress null obtient la valeur de la propriata sealservertcpport public int getsealservertcpport return sealservertcpport dafinit la valeur de la propriata sealservertcpport public void setsealservertcpportint value thissealservertcpport value public boolean issetsealservertcpport return true obtient la valeur de la propriata pamservertcpport public int getpamservertcpport return pamservertcpport dafinit la valeur de la propriata pamservertcpport public void setpamservertcpportint value thispamservertcpport value i try to initialize my pojo with default valuelike that mypojo mypojo new mypojomypojogetpamservertcpport return 0setdefaultvaluesmypojo assign attributes with annotated default valuesmypojogetpamservertcpport return 1485i am trying programmaticaly with the method setdefaultvaluesmypojo lomypojo that parse class with javalangannotation api and javalangreflect api but my code is ugly and does not work with my own enumerate default valuei have to mentionned that i cannot modify original class mypojo because it is itself generated by xsd parsing via jaxbany idea,['java'] +446888,why does a static namespace variable accessed from inside an inline class method work i saw this code recently in a header file and was surprised that it workednamespace ns static int uid 0 class x public static int getuid return uid if the static method nsxgetuid is called from several different c source files i was surprised to find that it correctly generated a unique id unique across translation units i thought that a static variable in a namespace scope had internal linkage to the translation unit whats going on here does the inline static method in class x have it is own translation unit and that is why it generates a unique id or is it working for me due to a quirk in my compilerdoes the above code rely on safe welldefined behavior if so this is a surprisingly concise method of generating a unique id in an inline or template class even if it looks a bit kludgy or is it better to generate a new c source file for a static unique id function like this and move the static id inside the classupdatefor a test case i wrote several functions like this in different files file1cpp file2cpp etcinclude static defh name of the above header filevoid func1 int uid1 nsxgetuid int uid2 nsxgetuid stdcout file1 uid1 uid1 uid2 uid2 stdendlthe suprising output after calling these from main wasfile1 uid1 0 uid2 1file2 uid1 2 uid2 3,['c++'] +446914,android contacts provider get only phone contacts with all emails i need to get all phone contacts and their email address and photo urithis is what am doingprivate void getcontacts contentresolver cr getcontentresolver cursor cur crquerycontactscontent uri null null null contactsthisplay name if curgetcount 0 while curmovetonext if integerparseintcurgetstringcurgetcolumnindexcontactscontractcontactshas phone number 0 contact contact new contact string id curgetstringcurgetcolumnindexcontactscontractcontacts id uri uri getcontactphotourilongparselongid set photouri contactsetcontactphotouriuri set name contactsetcontactnamecurgetstringcurgetcolumnindexcontactscontractcontactsthisplay name get the phone number cursor pcur crquerycontactscontractcommondatakindsphonecontent uri null contactscontractcommondatakindsphonecontact id new string id null while pcurmovetonext set phone munber contactsetcontactnumberpcurgetstringpcur getcolumnindexcontactscontractcommondatakindsphonenumber contactsaddcontact pcurclose get email and type cursor emailcur crquerycontactscontractcommondatakindsemailcontent uri null contactscontractcommondatakindsemailcontact id new string id null while emailcurmovetonext this would allow you get several email addresses if the email addresses were stored in an array set email contactsetcontactemailemailcurgetstringemailcur getcolumnindexcontactscontractcommondatakindsemaildata contactsaddcontact emailcurclose curclose contactadapter new contactadapterthis ridcontactlist contacts public uri getcontactphotourilong contactid uri photouri contenturiswithappendedidcontactscontent uri contactid photouri uriwithappendedpathphotouri contactsphotocontent directory return photouri my problem am getting all contacts including gmail contacts i dont want gmail contacts to be included and the time taken is also very slow how do i optimize this i know its taking time coz i am using many cursors but dont know how to make a single cusror that can give me name email number photo uri thanksupdated finalprivate void getcontacts contentresolver cr getcontentresolver cursor cur crquerydatacontent uri new string datacontact id datamimetype emailaddress contactsthisplay name phonenumber null null contactsthisplay name contact contact if curgetcount 0 while curmovetonext string id curgetstringcurgetcolumnindexdatacontact id string mimetype curgetstringcurgetcolumnindexdatamimetype if allcontactscontainskeyid update contact contact allcontactsgetid else contact new contact allcontactsputid contact set photouri contactsetcontactphotourigetcontactphotourilongparselongid if mimetypeequalsstructurednamecontent item type set name contactsetcontactnamecurgetstringcurgetcolumnindexcontactsthisplay name if mimetypeequalsphonecontent item type set phone munber contactsetcontactnumbercurgetstringcurgetcolumnindexphonenumber if mimetypeequalsemailcontent item type set email contactsetcontactemailcurgetstringcurgetcolumnindexemailaddress curclose get contacts from hashmap contactsclear contactsaddallallcontactsvalues remove null contacts for contact contact contacts if contactgetcontactname null contactgetcontactnumber null contactgetcontactemail null contactsremove contact break contactadapter new contactadapterthis ridcontactlist contacts contactadapternotifydatasetchangedpublic uri getcontactphotourilong contactid uri photouri contenturiswithappendedidcontactscontent uri contactid photouri uriwithappendedpathphotouri contactsphotocontent directory return photouri,['android'] +446933,reset mysql field to default value is there a command in mysql to reset a field to its default value you know in favor of the do not repeat yourself rule i do not want to write the quite long default value multiple times in code only once in the dbi looked around quite some time in google found nothing i am starting to suspect such command does not exist but nevertheless if it does sy heres going to know about it,['mysql'] +446934,how to allocate array of pointers for strings by malloc in c i have this struct in cexample typedef struct const char array pointers of strings 30 etc messagei need copy this array pointers of strings to new array for sort strings i need only copy adresswhile i 30 new array i new messagearray pointers of strings i i need only copy adress of stringsmy question is how to allocate new array i by malloc for only adress of strings,['c'] +446947,tablefooterview property does not fix the footer at the bottom of the table view i am setting a footer view in the viewdidload methoduiview fview uiview alloc initwithframecgrectmake0 718 239 50fviewbackgroundcolor uicolor yellowcolorselftabletablefooterview fviewunfortunately the footer is not drawing in the specified xy specified above but it stick with the cells so if the table view has 4 cells the footer will be drawn in the 5th celli even tried the protocol method tableviewviewforfooterinsection uiview tableviewuitableview tableview viewforfooterinsectionnsintegersectionuiview fview uiview alloc initwithframecgrectmake0 0 239 50fviewbackgroundcolor uicolor yellowcolor return fviewthe problem is not resolved i am sure tablefooterview property should fi the footer view at the bottom of the table view but i am not sure what i may be missing here thanx in advance,['ios'] +447096,does assignment with advanced indexing copy array data i am slowly trying to understand the difference between views and copys in numpy as well as mutable vs immutable typesif i access part of an array with advanced indexing it is supposed to return a copy this seems to be truein 1 import numpy as npin 2 a npzeros33in 3 b nparraynpidentity3 dtypeboolin 4 c abin 5 c 9in 6 aout6 array 0 0 0 0 0 0 0 0 0since c is just a copy it does not share data and changing it does not mutate a however this is what confuses mein 7 ab 1in 8 aout8 array 1 0 0 0 1 0 0 0 1so it seems even if i use advanced indexing assignment still treats the thing on the left as a view clearly the a in line 2 is the same objectdata as the a in line 6 since mutating c has no effect on itso my question is the a in line 8 the same objectdata as before not counting the diagonal of course or is it a copy in other words was as data copied to the new a or was its data mutated in placefor example is it likex 123x 4or likey 123y 4i do not know how to check for this because in either case aflagsowndata is true please feel free to elaborate or answer a different question if i am thinking about this in a confusing way,['python'] +447098,retrieving the many end of a generic foreign key relationship in django in django when i request a resource that has a manytomany relationship i end up getting all the items in child part of the relationship even those not directly related to the parent it will be easier if i show you with code classes trimmed down to only show whats necessarymodelsclass reportmodelsmodel name modelscharfieldmax length255 slug autoslugfield slug populate fromname wells modelsmanytomanyfieldwell nulltrue uuid uuidfieldeditablefalse blanktrue version4 uniquetrueclass wellmodelsmodel slug autoslugfield slug populate fromname name modelscharfieldmax length255class nodemodelsmodel property def wellself raise notimplementederrorthe well field must be implemented irrelevant gfk omitted page content type modelsforeignkeycontenttype nulltrue blanktrue related namepage page object id modelspositiveintegerfieldblanktrue nulltrue page content object genericgenericforeignkeypage content type page object idresourcesclass reportresourcemodelresource wells fieldsmanytomanyfieldwellresource wells fulltrue stock fieldsforeignkeytickerresource stock fulltrue class meta queryset reportobjectsall resource name ticker reportsclass wellresourcemodelresource nodes fieldstomanyfieldwellsapinoderesource nodes fulltrue type fieldsforeignkeywelltyperesource type fulltrue class meta queryset wellobjectsall resource name wellsclass noderesourcemodelresource order fieldsintegerfield content object genericforeignkeyfield content uuidonlycontentresource content object fulltrue class meta queryset nodeobjectsall resource name nodes filtering ticker report all with relations a ticker report has many wells and these wells are shared across all ticker reports what is different is that you can tie nodes to wells for a given ticker report the only nodes that should thisplay are the ones that are related to that ticker report so for a given ticker report and a set of wells only the nodes that share that genericforeignkey to that ticker report should be shownrelationshipspage object idpage content object page content type is a genericforeignkey relationship to reportcurrently all nodes are shown this is a bugin tastypie how do i tell it to only show the related objects and not all objectsheres a short python console that shows the problem more succicintly r reportobjectsgetid1 for well in rwellsall for node in wellnodesall print node in well 0 is 1formatwell node node in well the areas you must watch theareasyoumustwatch fancy list is apple content 1apple 0 node in well the areas you must watch theareasyoumustwatch fancy list is first solar content 1first solar 0 node in well risks risks headline and lead is apple content 2apple 0 node in well risks risks headline and lead is first solar content 2first solar 0 sql actual outputselect nodeid nodeuuid nodeordernodecontent type id nodeobject id nodepage content type id nodepage object id nodewell id from node where nodewell id 1 order by nodeorder asc modified to make it easier to readexpected sql outputselect nodeid nodeuuid nodeordernodecontent type id nodeobject id nodepage content type id nodepage object id nodewell id from node where nodewell id 1 and nodepage content type id 99 report content typeid and nodepage content object id 1 reportidorder by nodeorder asc expected outputnode in well the areas you must watch is apple content 1node in well risks is apple content 2apple 0how can i filter out the child end of a manytomany relationship with django and tastypie though this problem is apparent without tastypie as well leaving me to believe it is a structural issue,['python'] +447155,how to convert a simple html to pdf using wkhtmltopdf here is what i didcreated a linux virtual machine in the amazon cloudfollowed the instructions from to download and compile the source code of wkhtmltopdfqt and of wkhtmltopdf in the end i have a static build of wkhtmltopdftook this html fnd8ctjbhtml head style typetextcsspfontfamily sansserifstyle head body plet us testp bodyhtmlran wkhtmltopdf testhtml testpdfcopied testpdf to my windows desktop opened it and got this i followed the guide closely the qt configuration options were taken from wkhtmltopdfstatic qt conf base and wkhtmltopdfstatic qt conf linux as the guide suggests needless to say i am a bit thisappointed with the result can anyone explain me what am i doing wrongpsin reality i need to convert a much more complex html but there is no point to talk about it when i fail to convert a trivial oneediti wish to emphasize that i do not work on linux i only open a terminal to an amazon hosted linux box meaning i do not have an x11 environmentthis is what i get when i try using the predefined wkhtmltopdf packageubuntuip1024578162 which wkhtmltopdfubuntuip1024578162 usrbinwkhtmltopdfbash usrbinwkhtmltopdf no such file or directoryubuntuip1024578162 sudo aptget install wkhtmltopdfreading package lists donebuilding dependency treereading state information donethe following new packages will be installed wkhtmltopdf0 upgraded 1 newly installed 0 to remove and 120 not upgradedneed to get 0 b104 kb of archivesafter this operation 303 kb of additional thisk space will be usedselecting previously unselected package wkhtmltopdfreading database 36679 files and directories currently installedunpacking wkhtmltopdf from wkhtmltopdf 0993 amd64deb processing triggers for mandb setting up wkhtmltopdf 0993 ubuntuip1024578162 l testrwrr 1 ubuntu ubuntu 123 mar 30 1246 testhtmlubuntuip1024578162 cat testhtmlhtml head style typetextcsspfontfamily sansserifstyle head body plet us testp body htmlubuntuip1024578162 usrbinwkhtmltopdf testhtml testpdfwkhtmltopdf cannot connect to x serverubuntuip1024578162edit2i have downloaded 64ospackagesuurwfonts2414fc19noarchrpmfollowed instructions from to convert the rpm to a deb formatinstalled the debproduced pdf but still seeing just the squareshere is the transcriptubuntuip1024578162 sudo alien urwfonts2414fc19noarchrpm scriptswarning urwfonts2414fc19noarchrpm header v3 rsasha256 signature key id fb4b18e6 nokeywarning urwfonts2414fc19noarchrpm header v3 rsasha256 signature key id fb4b18e6 nokeywarning urwfonts2414fc19noarchrpm header v3 rsasha256 signature key id fb4b18e6 nokeywarning urwfonts2414fc19noarchrpm header v3 rsasha256 signature key id fb4b18e6 nokeywarning urwfonts2414fc19noarchrpm header v3 rsasha256 signature key id fb4b18e6 nokeywarning urwfonts2414fc19noarchrpm header v3 rsasha256 signature key id fb4b18e6 nokeywarning urwfonts2414fc19noarchrpm header v3 rsasha256 signature key id fb4b18e6 nokeywarning urwfonts2414fc19noarchrpm header v3 rsasha256 signature key id fb4b18e6 nokeywarning urwfonts2414fc19noarchrpm header v3 rsasha256 signature key id fb4b18e6 nokeywarning urwfonts2414fc19noarchrpm header v3 rsasha256 signature key id fb4b18e6 nokeywarning urwfonts2414fc19noarchrpm header v3 rsasha256 signature key id fb4b18e6 nokeywarning urwfonts2414fc19noarchrpm header v3 rsasha256 signature key id fb4b18e6 nokeywarning urwfonts2414fc19noarchrpm header v3 rsasha256 signature key id fb4b18e6 nokeywarning urwfonts2414fc19noarchrpm header v3 rsasha256 signature key id fb4b18e6 nokeywarning urwfonts2414fc19noarchrpm header v3 rsasha256 signature key id fb4b18e6 nokeywarning urwfonts2414fc19noarchrpm header v3 rsasha256 signature key id fb4b18e6 nokeywarning urwfonts2414fc19noarchrpm header v3 rsasha256 signature key id fb4b18e6 nokeyurwfonts 2415 alldeb generatedubuntuip1024578162 sudo dpkg i urwfonts 2415 alldebselecting previously unselected package urwfontsreading database 38529 files and directories currently installedunpacking urwfonts from urwfonts 2415 alldeb setting up urwfonts 2415 processing triggers for fontconfig ubuntuip1024578162 wkhtmltopdfbinwkhtmltopdf testhtml testpdfloading pages 16counting pages 26resolving links 46loading headers and footers 56printing pages 66doneubuntuip1024578162edit3i have installed the xvfbrun package and now the default version usrbinwkhtmltopdf can be run through it indeed it is able to convert the simple testhtml to pdf however it fails to do so for a complex html page with javascript code it appears as though usrbinwkhtmltopdf is unable to run any javascript code on the page being convertedi am still puzzled why the compiled version does not workedit4i have been unjust with the default wkhtmltopdf version it is capable to understand javascript in the page it successfully converts the following htmlhtml head style typetextcss body fontfamily sansserif style head body idbody script documentgetelementbyidbodyinnerhtml hello world script bodyhtmli will try to understand why does it fail with a real page but i do not know how can i troubleshoot it except by trying to get a minimal failing page by throwing away pieces of the original oneedit5ok here is the minimal example that does not work with the default wkhtmltopdf versiondoctype htmlhtml head style typetextcss html body height 100 overflow hidden style head body hello world bodyhtmlthe created pdf is empty here is the transcriptubuntuip1024578162 cat test2htmldoctype htmlhtml head style typetextcss html body height 100 overflow hidden style head body hello world bodyhtmlubuntuip1024578162 xvfbrun usrbinwkhtmltopdf test2html test2pdf l test2pdfloading page 12printing pages 22donerwrr 1 ubuntu ubuntu 1266 mar 31 16 test2pdfubuntuip1024578162 cat test2html sed 6d xvfbrun usrbinwkhtmltopdf test2pdf l test2pdfloading page 12printing pages 22donerwrr 1 ubuntu ubuntu 4284 mar 31 16 test2pdfubuntuip1024578162notice how removing the 6th line height 100 changes the size of the created pdf fileedit6the custom version is linked statically whereas the default one depends on quite a few of the webkit shared librariesthe custom versionubuntuip1024578162wkhtmltopdfbin l wkhtmltopdfrwxrxrx 1 ubuntu ubuntu 35020224 mar 31 26 wkhtmltopdfubuntuip1024578162wkhtmltopdfbin ldd ldd wkhtmltopdf linuxvdsoso1 0x07f195ff0 libxrenderso1 usrlibx86 64linuxgnulibxrenderso1 0x07fefc06db0 libx11so6 usrlibx86 64linuxgnulibx11so6 0x07fefc03a70 libdlso2 libx86 64linuxgnulibdlso2 0x07fefc01a20 librtso1 libx86 64linuxgnulibrtso1 0x07fefbff9a0 libpthreadso0 libx86 64linuxgnulibpthreadso0 0x07fefbfd7d0 libstdcso6 usrlibx86 64linuxgnulibstdcso6 0x07fefbfa7c0 libmso6 libx86 64linuxgnulibmso6 0x07fefbf780 libgcc sso1 libx86 64linuxgnulibgcc sso1 0x07fefbf56a0 libcso6 libx86 64linuxgnulibcso6 0x07fefbf1aa0 lib64ldlinuxx8664so2 0x07fefc08ef0 libxcbso1 usrlibx86 64linuxgnulibxcbso1 0x07fefbef8c0 libxauso6 usrlibx86 64linuxgnulibxauso6 0x07fefbed880 libxdmcpso6 usrlibx86 64linuxgnulibxdmcpso6 0x07fefbeb820ubuntuip1024578162wkhtmltopdfbinnow the default versionubuntuip1024578162usrbin l wkhtmltopdfrwxrxrx 1 root root 233512 may 7 2011 wkhtmltopdfubuntuip1024578162usrbin ldd wkhtmltopdf linuxvdsoso1 0x07f031ff0 libqtwebkitso4 usrlibx86 64linuxgnulibqtwebkitso4 0x07f28a33bc0 libqtguiso4 usrlibx86 64linuxgnulibqtguiso4 0x07f28a26ee0 libqtnetworkso4 usrlibx86 64linuxgnulibqtnetworkso4 0x07f28a23a10 libqtcoreso4 usrlibx86 64linuxgnulibqtcoreso4 0x07f28a1ecf0 libstdcso6 usrlibx86 64linuxgnulibstdcso6 0x07f28a1bcf0 libgcc sso1 libx86 64linuxgnulibgcc sso1 0x07f28a19b80 libcso6 libx86 64linuxgnulibcso6 0x07f28a15f90 libsqlite3so0 usrlibx86 64linuxgnulibsqlite3so0 0x07f28a13560 libxrenderso1 usrlibx86 64linuxgnulibxrenderso1 0x07f28a114b0 libgstapp010so0 usrlibx86 64linuxgnulibgstapp010so0 0x07f28a0f3f0 libgstinterfaces010so0 usrlibx86 64linuxgnulibgstinterfaces010so0 0x07f28a0d2d0 libgstpbutils010so0 usrlibx86 64linuxgnulibgstpbutils010so0 0x07f28a0b090 libgstvideo010so0 usrlibx86 64linuxgnulibgstvideo010so0 0x07f28a08ed0 libgstbase010so0 usrlibx86 64linuxgnulibgstbase010so0 0x07f28a069a0 libgstreamer010so0 usrlibx86 64linuxgnulibgstreamer010so0 0x07f28a03b20 libgobject20so0 usrlibx86 64linuxgnulibgobject20so0 0x07f28a01630 libglib20so0 libx86 64linuxgnulibglib20so0 0x07f289fe6e0 libpthreadso0 libx86 64linuxgnulibpthreadso0 0x07f289fc50 libx11so6 usrlibx86 64linuxgnulibx11so6 0x07f289f91c0 libmso6 libx86 64linuxgnulibmso6 0x07f289f620 libfontconfigso1 usrlibx86 64linuxgnulibfontconfigso1 0x07f289f3e90 libaudioso2 usrlibx86 64linuxgnulibaudioso2 0x07f289f1d10 libpng12so0 libx86 64linuxgnulibpng12so0 0x07f289efa90 libzso1 libx86 64linuxgnulibzso1 0x07f289ed910 libfreetypeso6 usrlibx86 64linuxgnulibfreetypeso6 0x07f289eaf50 libsmso6 usrlibx86 64linuxgnulibsmso6 0x07f289e8ed0 libiceso6 usrlibx86 64linuxgnulibiceso6 0x07f289e6d20 libxiso6 usrlibx86 64linuxgnulibxiso6 0x07f289e4c30 libxextso6 usrlibx86 64linuxgnulibxextso6 0x07f289e2b20 libdlso2 libx86 64linuxgnulibdlso2 0x07f289e0ad0 librtso1 libx86 64linuxgnulibrtso1 0x07f289dea50 lib64ldlinuxx8664so2 0x07f28a517e0 liborc04so0 usrlibx86 64linuxgnuliborc04so0 0x07f289dc290 libgmodule20so0 usrlibx86 64linuxgnulibgmodule20so0 0x07f289da250 libxml2so2 usrlibx86 64linuxgnulibxml2so2 0x07f289d6ca0 libffiso6 usrlibx86 64linuxgnulibffiso6 0x07f289d4c10 libpcreso3 libx86 64linuxgnulibpcreso3 0x07f289d2840 libxcbso1 usrlibx86 64linuxgnulibxcbso1 0x07f289d0650 libexpatso1 libx86 64linuxgnulibexpatso1 0x07f289ce3b0 libxtso6 usrlibx86 64linuxgnulibxtso6 0x07f289cbd50 libxauso6 usrlibx86 64linuxgnulibxauso6 0x07f289c9d10 libuuidso1 libx86 64linuxgnulibuuidso1 0x07f289c7cc0 libxdmcpso6 usrlibx86 64linuxgnulibxdmcpso6 0x07f289c5c50ubuntuip1024578162usrbinedit7guys i do not understand how wkhtmltopdf works for you i have started from scratch totallycreated a brand new ubuntu amazon micro instance free tiersudo aptget updatesudo aptget upgradesudo aptget install libx11devsudo aptget install libfontconfig1devwget rc1staticamd64tarbz2tar xjf wkhtmltopdf0110 rc1staticamd64tarbz2created test2html with the contents from edit5 see the edit5 transcriptran wkhtmltopdfamd64 on test2html the produced pdf is emptyremove line 6 or 7 from the test2html css property width or overflow and suddenly it workscan anyone retrace my steps and confirm itedit8installed centos 64 in a vmware vm on my laptop same results wkhtmltopdf does not work on the aforementioned trivial html file,['html'] +447174,how do i build a suite of qunit tests that all have their own qunit fixtures i have two xtesthtml files each similar to thishtml head link relstylesheet href script srcpublicscriptscommonsomeutilsjsscript head body div idqunitdiv div idqunitfixture div idfindmesomething specific for the code under testdiv div script srcscript script srcsomeutilstestjsscript bodyhtmleach has their own qunitfixture so the html file is equivalent to a junit test class i realize qunit considers modules as roughly the same thing as a test class but that is very limiting whats the best way to have a master html file that will execute tests within other html files or whats the correct way to separate out tests that need their own fixtures in the qunit world,['javascript'] +447185,javascript wait function i want to create a javascript wait functionwhat should i edit function waitwaitsecssettimeoutdonothing waitsecsfunction donothing,"['javascript', 'html']" +447188,programatically create initial window of cocoa app os x usually i am making ios app but now i am trying to make an os x app and i am lost at the very beginning say the style i make the ios apps are totally programmatic there is no xib files or whatsoever just because that i have a lot more control by typing than dragging however in os x programming it starts with some xib files with the menu items and a default window there are quite a lot of items in the menu items so that is probably not something i want to mess around but i want to programatically create my first window myselfso i did this voidapplicationdidfinishlaunchingnsnotification anotification nsuinteger windowstylemask nstitledwindowmasknsresizablewindowmasknsclosablewindowmasknsminiaturizablewindowmask nswindow appwindow nswindow alloc initwithcontentrectnsmakerect200 200 1280 720 stylemaskwindowstylemask backingnsbackingstorebuffered deferno appwindowbackgroundcolor nscolor lightgraycolor appwindowminsize nsmakesize1280 720 appwindowtitle sample window appwindow makekeyandorderfrontself appwindowcontroller appwindowcontroller alloc initwithwindowappwindow appwindowcontroller showwindowselfso here i have created a window first and use that windowcontroller to init this window the window does show up in this way but i can only specify the inner elements like buttons and labels here but not in the windowcontroller it makes me feel bad so i tried another way voidapplicationdidfinishlaunchingnsnotification anotification appwindowcontroller appwindowcontroller alloc init appwindowcontroller showwindowselfand after this i want to set the other elements in the loadwindow function in the windowcontroller like this voidloadwindow selfwindow setframensmakerect200 200 1280 720 thisplayyes selfwindowtitle sample window selfwindowbackgroundcolor nscolor lightgraycolor nsbutton samplebutton nsbutton alloc initwithframensrectfromcgrectcgrectmake100 100 200 23 samplebuttontitle sample button samplebutton setbuttontypensmomentarylightbutton samplebutton setbezelstylensroundedbezelstyle selfwindowcontentview addsubviewsamplebutton nslogloaded window selfwindow makekeyandorderfrontnilunfortunately this never works the loadwindow never gets called nor windowdidload where did they goand please do not ask why i do not use nibs i wish to make some highly customized views inside possibly opengl so i do not think nibs can handle it i am greatly appreciated if anyone could help thanksand also who knows how to even start the menu items from scratch programmaticallyi am using the latest xcode,['objective-c'] +447196,declaring char hexadecimal constants in c11 in various lowlevel parts of our code we are required to send specific bytes to a device in order to make things happen as such we have plenty of code that looks likeconst char magic bytes 0x01 0xfa 0x92 which results in the error on gcc 472test charcpp651 warning narrowing conversion of a250a from ainta to aconst chara inside is illformed in c11 wnarrowingsince 0xfa is outside the range 128 to 127there are two workarounds that i can think ofconst char magic bytes static castchar0x01 static castchar0xfa static castchar0x92 orconst unsigned char magic bytes 0x01 0xfa 0x92 both of which are either ugly the first case or have other drawbacks having to cast to const char in the case of the latteris there a better way to declare these strings,['c++'] +447211,connecting to a mysql database using phonegap ajax and jquery mobile i am in a team developing an android application that will rely greatly on the use of a remote database we are using phonegap and jquery mobile and have been attempting to connect to our mysql database using ajax and json calls currently we are having trouble in our testing phase which is to verify we even have a connection at all by pulling a hardcoded user of ted from mysql input via mysql workbenchfrom what we have gathered the process of data transmission works as thison our html file we have a script typetextjavascript srcconnectjsscript which should run the connectjs script correct so from there connectjs is ranconnectjs runs connecting it to our serverfilephp that is hosted on an external web service allowing it to run php to connect to the mysql database and pull information run the following code whenever a new pseudopage is createdpagenamelivepageshow functionevent cache this page for later use inside the ajax function var this this make an ajax call to your php script getjson function response create a variable to hold the parsed output from the server var output if the php script returned a success if responsestatus success iterate through the response rows for var key in responseitems add each response row to the output variable outputpushli responseitemskey li if the php script returned an error else output an error message outputpushlino data foundli append the output to the datarolecontent div on this page as a listview and trigger the create event on its parent to style the listview thischildrendatarolecontentappendul datarolelistview outputjoin ultriggercreate here is serverfilephp this should connect to the mysql database make the select statement and then send the output to the browser encoded in the json format phpsession startconnection mysql connectcsmathisondhcpbsuedu clbavender changeme db mysql select dbcs397 clbavender connection include your database connection code include oncedatabaseconnectionphpquery your mysql server for whatever information you wantquery mysql queryselect from users where username ted db or trigger errormysql errorcreate an output arrayoutput arrayif the mysql query returned any resultsif mysql affected rows 0 iterate through the results of your query while row mysql fetch assocquery add the results of your query to the output variable output row send your output to the browser encoded in the json format echo json encodearraystatus success items output else if no records were found in the database then output an error message encoded in the json format echo json encodearraystatus error items outputyet nothing is showing here what do we do from here,"['javascript', 'jquery', 'sql']" +447214,type inference on nested generic functions i have searched a bit about type inference but i cannot seem to apply any of the solutions to my particular problemi am doing a lot of work with building and passing around functions this seems to me like it should be able to infer the int type the only thing i can think of is that the lambda return type is not checked by the type inference algorithm i have stripped unnecessary logic to show the issue more clearlyfunct testtfuncfunct func return functhis compilesfuncint x testint int i 0 return i but this gives the error the type arguments for method cannot be inferred from the usage try specifying the type arguments explicitlyfuncint x test int i 0 return i i guess i would just like to know why it works this way and any workarounds,['c#'] +447215,get gcc to use carry logic for arbitrary precision arithmetic without inline assembly when working with arbitrary precision arithmetic eg 512bit integers is there any way to get gcc to use adc and similar instructions without using inline assemblya first glance at gmps sourcecode shows that they simply have assembly implementations for every supported platformhere is the test code i wrote which adds two 128bit numbers from the command line and prints the result inspired by minigmps add ninclude stdiohinclude stdinthinclude stdlibhint main int argc char argv uint32 t a4 uint32 t b4 uint32 t c4 uint32 t carry 0 for int i 0 i 4 i ai strtoul argvi1 null 16 bi strtoul argvi5 null 16 for int i 0 i 4 i uint32 t aa ai uint32 t bb bi uint32 t r aa carry carry r carry r bb carry r bb ci r printf 08x08x08x08x 08x08x08x08x n a3 a2 a1 a0 b3 b2 b1 b0 printf 08x08x08x08xn c3 c2 c1 c0 return 0gcc o3 stdc99 does not produce any adc instructions as checked by objdump my gcc version is i686pcmingw32gcc gcc 452,['c'] +447231,android layout layoutweight and weightsum i need to build a layout with the set of linear layouts the layout has to occupy a defined percentage of the screen i need to do this to have a similar look in all the devicesissuei have a textview in the top right layout green color box whenever i add some data in the textview it thisturbs the entire layout as shown below in the 2nd image but i need to have the data wraps automatically when it reaches the right end of the screenlayout please help me to resolve this thanks in advanceimage1 graphical view as per the xml shown belowimage2 shows how the layout automatically changes when i add some data in the textviewxmllinearlayout xmlnsandroidandroidlayout widthfill parentandroidlayout heightfill parentandroidbackgrounddrawablebackgroundandroidorientationvertical androidweightsum100linearlayout androidlayout widthmatch parent androidlayout heightwrap content androidorientationhorizontal androidlayout weight91 androidweightsum100 linearlayout androidlayout widthwrap content androidlayout heightmatch parent androidorientationvertical androidlayout weight40 androidweightsum235 linearlayout androidlayout widthmatch parent androidlayout heightmatch parent androidorientationvertical androidgravitycenter androidbackgroundff0 androidlayout weight100 textview androidididtextview1 androidlayout widthwrap content androidlayout heightwrap content androidtextcolor0 linearlayout linearlayout androidlayout widthmatch parent androidlayout heightmatch parent androidorientationvertical androidbackgroundf00 androidlayout weight45 viewflipper androidididview flipper androidlayout widthmatch parent androidlayout heightmatch parent androidlayout belowidtvitemname linearlayout androidlayout widthmatch parent androidlayout heightmatch parent androidorientationvertical linearlayout viewflipper linearlayout linearlayout androidlayout widthmatch parent androidlayout heightmatch parent androidorientationvertical androidbackgroundf androidlayout weight90 linearlayout linearlayout linearlayout androidlayout widthwrap content androidlayout heightmatch parent androidorientationvertical androidlayout weight60 androidweightsum100 linearlayout androidlayout widthmatch parent androidlayout heightmatch parent androidorientationvertical androidlayout weight30 androidbackground00ab00 androidweightsum100 textview androidididtextview1 androidlayout widthmatch parent androidlayout heightfill parent androidtextcolor0 androidtexttest data linearlayout linearlayout androidlayout widthmatch parent androidlayout heightmatch parent androidorientationvertical androidbackgroundcd00ab androidlayout weight70 linearlayout linearlayoutlinearlayoutlinearlayout androidlayout widthmatch parent androidlayout heightwrap content androidbackgroundab0 androidlayout weight9linearlayoutlinearlayout,['android'] +447244,error c2143 syntax error missing before type i am new to programming c please tell me what is wrong with this program and why i am getting this error error c2143 syntax error missing before typeextern void funcint mainint argc char argv func int i1 fori5 i register int number 7 printfnumber is dn number getch,['c'] +447268,margin auto is not centering in the following style from the website exercisesexercise4htmlstyle typetextcss sponsors marginauto margintop50px overflow hidden width auto thisplay inlineblock divimage img margin 3px border 1px solid f divimage ahover img border 1px solid styleheadbody h1sponsors of 6470h1 div idsponsors div classimagea hrefimg srcimagesappianpng width150 height85adiv div classimagea hrefimg srcimagesdropboxpng width150px height85pxadiv div classimagea hrefimg srcimagesfacebookpng width150px height85pxadiv div classimagea hrefimg srcimagesnextjumppng width150px height85pxadiv div classimagea hrefimg srcimagespalantirpng width150px height85pxadiv div classimagea hrefimg srcimagesquorapng width150px height85pxadiv div classimagea hrefimg srcimagestripadvisorpng width150px height85pxadiv div classimagea hrefimg srcimagesvecnapng width150px height85pxadiv divbodyif the width auto is removed from sponsors then the divsponsors is not center aligned even though margin auto is used similarly if instead of textalign center is replaced by margin auto in body style above then the h1 will not be center aligned which is preposterous because i have used margin auto a lot of times and it was able to center the content without any issue so hence help me and i will appreciate this a lotps i used firefox and besides use the doctype tag it is still not able to center with margin auto,['css'] +447301,broadcast receiver for checking internet connection in android app hello i am developing an android broadcast receiver for checking internet connectionbut the problem is that my broadcast receiver for two times secondly i want to get it called only when network is available if it is unavailable i will not want to get notifiedthis is the broadcast receiverpublic class networkchangereceiver extends broadcastreceiver override public void onreceivefinal context context final intent intent final connectivitymanager connmgr connectivitymanager context getsystemservicecontextconnectivity service final androidnetnetworkinfo wifi connmgr getnetworkinfoconnectivitymanagertype wifi final androidnetnetworkinfo mobile connmgr getnetworkinfoconnectivitymanagertype mobile if wifiisavailable mobileisavailable do something logdnetwork available flag no 1 this is the manifestxmlmanifest xmlnsandroid packagecomexamplebroadcastreceiverforinternetconnection androidversioncode1 androidversionname10 usessdk androidminsdkversion8 androidtargetsdkversion17 usespermission androidnameandroidpermissionaccess network state application androidallowbackuptrue androidicondrawableic launcher androidlabelstringapp name androidthemestyleapptheme receiver androidnamenetworkchangereceiver intentfilter action androidnameandroidnetconnconnectivity change action androidnameandroidnetwifiwifi state changed intentfilter receiver applicationmanifest,"['java', 'android']" +447310,springrequest method post not supported first of all say apology to ask this repeated questionactually in my spring application i have userjsp and professionaljsphear is my userjsp formform actionprofileuser modelattributeprofile div jspinclude pageprofessionaljspjspinclude divformformand hear is my prodessionaljsp taglib prefixform uri taglib prefixc urifieldset idprofile proffiesional formform actionprofileproffiesional modelattributeprofessional methodpost p label forpositionpositionlabel forminput pathposition tabindex4 p p label forlocationlocationlabel forminput pathlocation tabindex5 p p label fordescriptiondescriptionlabel forminput pathdescription tabindex5 p p input typesubmit valueadd p formformfieldsetand hear is my controller class controllerrequestmappingvalue profilepublic class userprofilecontroller autowired private userservice userservice autowired private sessiondata sessiondata requestmappingvalue user method requestmethodget public string usermodel model throws exception modeladdattributeprofessional new userprofessionalform modeladdattributeeducational new usereducationalform modeladdattributeawards new userawardsform return profileuser requestmappingvalue proffessional method requestmethodpost public responsebody string forgotpassworduserprofessionalform professionalform bindingresult result model model userprofilevo userprofilevo new userprofilevo userprofilevosetusersessiondatagetuser userservicesaveuserprofileuserprofilevo modeladdattributeprofessional professionalform return your professional details updated problem is when we are click add button in professionaljsp there is no response in server console but below warning message shown 29 mar 2013 10351 pm orgspringframeworkwebservletmvcsupportdefaulthandlerexceptionresolver handlehttprequestmethodnotsupportedwarning request method post not supportedwhy this warning coming i am already specified methodpostplease help me,['java'] +447325,compound class names are not supported error in webdriver i have a method to count the number of elements in divs and to return their number public int getnumberofopenbets openbetsslip driverfindelementbyidform open bets openbets openbetsslipfindelementsbyclassname cashout nocash return openbetssize that is the page sourceform idform open bets methodpost nameform open betsinput typehidden value nameactioninput typehidden value namebet idinput typehidden value namecashout priceinput idtarget page typehidden value nametarget pagediv idbyid claslipwrapper div idopenbets headerdivdiv idcashout 1626 class cashout nocashdiv idcashout 1625 class cashout nocashdiv idcashout 1615 class cashout nocashdiv idcashout 1614 class cashout nocashdiv idcashout 1613 class cashout nocashdivwebdriver is throwing the following error compound class names are not supported consider searching for one class name and filtering the results or use css selectorsorgopenqaseleniuminvalidselectorexception compound class names are not supported consider searching for one class name and filtering the results or use css selectorsfor documentation on this error please visit selector exceptionhtmlbuild info version 2310 revision 1bd294d185a80fa4206dfeab80ba773c04ac33c0 time 20130227 135126system info osname windows 7 osarch amd64 osversion 61 javaversion 170 17driver info driverversion unknown at orgopenqaseleniumbyclassnamebyjava131 at elementsbetslipbetslipgetnumberofopenbetsbetslipjava136 at testsomethingsomethingtestjava117 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokeunknown source at sunreflectdelegatingmethodaccessorimplinvokeunknown source at javalangreflectmethodinvokeunknown source at orgjunitrunnersmodelframeworkmethod1runreflectivecallframeworkmethodjava47 at orgjunitinternalrunnersmodelreflectivecallablerunreflectivecallablejava12 at orgjunitrunnersmodelframeworkmethodinvokeexplosivelyframeworkmethodjava44 at orgjunitinternalrunnersstatementsinvokemethodevaluateinvokemethodjava17 at orgjunitrunnersparentrunnerrunleafparentrunnerjava271 at orgjunitrunnersblockjunit4classrunnerrunchildblockjunit4classrunnerjava70 at orgjunitrunnersblockjunit4classrunnerrunchildblockjunit4classrunnerjava50 at orgjunitrunnersparentrunner3runparentrunnerjava238 at orgjunitrunnersparentrunner1scheduleparentrunnerjava63 at orgjunitrunnersparentrunnerrunchildrenparentrunnerjava236 at orgjunitrunnersparentrunneraccess0parentrunnerjava53 at orgjunitrunnersparentrunner2evaluateparentrunnerjava229 at orgjunitrunnersparentrunnerrunparentrunnerjava309 at orgeclipsejdtinternaljunit4runnerjunit4testreferencerunjunit4testreferencejava50 at orgeclipsejdtinternaljunitrunnertestexecutionruntestexecutionjava38 at orgeclipsejdtinternaljunitrunnerremotetestrunnerruntestsremotetestrunnerjava467 at orgeclipsejdtinternaljunitrunnerremotetestrunnerruntestsremotetestrunnerjava683 at orgeclipsejdtinternaljunitrunnerremotetestrunnerrunremotetestrunnerjava390 at orgeclipsejdtinternaljunitrunnerremotetestrunnermainremotetestrunnerjava197editas it turned out werbdriver does not support spaces in the class names omg could you guys please help me to use css selector in this situaltion in order to find the elements,"['java', 'css']" +447341,google maps api map is not loaded i have been trying to embed a google map in my site but with not much successi have used the next code section i am using an actual api key on my own computerscript typetextjavascript srcsensortruescriptscript typetextjavascript function initialize var mapoptions center new googlemapslatlng34397 150644 zoom 8 maptypeid googlemapsmaptypeidroadmap var map new googlemapsmapdocumentgetelementbyidmapcanvas mapoptions googlemapseventadomlistenerwindow load initializescriptinside body section i have added div idmapcanvas stylewidth 40 height 40div how could i handle this problem thanks in advance,['javascript'] +447398,i cannot locate the android sdk on my computer i installed the android sdk on my computer a few months ago and now i have finally motivated myself to begin developingat the moment i am trying to install the plugin for eclipse and i need to set the location of the sdk on my computer but i cannot find iti know it is installed since the sdk manager says it is but i do not know wherethere is no android folder in program files or in csearching for android in explorer did not yield anything relevantso does anybody know where i can find the sdkit does not seem to be in the default locationthanks,"['java', 'android']" +447431,unexpected complexity of common methods size in java collections framework recently i have been surprised by the fact that some java collections do not have constant time operation of method sizewhile i learned that concurrent implementations of collections made some compromises as a tradeoff for gain in concurrency size being on in concurrentlinkedqueue concurrentskiplistset linkedtransferqueue etc good news is that this is properly documented in api documentationwhat concerned me is the performance of method size on views returned by some collections methods for example treesettailset returns a view of the portion of backing set whose elements are greater than or equal to fromelement what surprised me a lot is that calling size on returned sortedset is linear in time that is on at least that is what i managed to dig up from the source code of openjdkin treeset is implemented as wrapper over treemap and within a treemap there is entrysetview class whose size method is as followsabstract class entrysetview extends abstractsetmapentrykv private transient int size 1 sizemodcount public int size if fromstart toend return msize if size 1 sizemodcount mmodcount sizemodcount mmodcount size 0 iterator i iterator while ihasnext size inext return size this means that first time size is called is on and then it is cached as long as backing map is not modified i was not able to find this fact in the api documentation more efficient implementation would be olog n with memory tradeoff in caching of subtree sizes since such tradeoffs are being made for avoiding code duplication treeset as wrapper over treemap i do not see a reason why they should not be made for performance reasonsthisregarding me being right or wrong with my very brief analysis of the openjdk implementation of treeset i would like to know is there a detailed and complete documentation on performance of many such operations especially ones which are completely unexpected,['java'] +447435,getting the timezone string from a date on ie google chromenew datereturns fri mar 29 2013 175525 gmt0530 ist ie8 new datereturns fri mar 29 174846 utc0530 2013i need to extract ist part from the date on ieon chrome i could do datestringsubstring to extract it but on ie i cannot do thatthe method gettimezoneoffset gives me the offset in minutes is there a way to get the string using the offset or do i need to research for all the timezone strings corresponding to the offsets and create an object out of it then use it,['javascript'] +447457,change random strings into colours consistently i have some ids that i want to generate random colours for making random colours is not the issue but it has to be consistenti could md5 or some other kind of hash the ids so the code could know how much characters to expect but the bottomline is it has to generate the same random colour for the same idhashstring,['php'] +447490,find largest area in 2d array in c i need to write recursive function in c that finds largest area of number 1 in 2d array that contains only 1 or 0exampleint arr58 0 0 0 0 1 1 0 0 1 0 0 1 1 1 0 0 1 1 0 1 0 1 1 0 0 0 0 1 1 1 1 0 0 1 1 0 0 0 0 0 visual example largestpnglargest area of this array is 12 second largest is 3 and third largest is 2i was thinking to do this with something similar to flood fill algorithm but just cannot figure out how,['c++'] +447494,python getting the row which has the max value in groups using groupby i hope i can find help for my question i am searching for a solution for the following problemi have a dataframe like sp mt value count0 mm1 s1 a 31 mm1 s1 and 22 mm1 s3 cb 53 mm2 s3 mk 84 mm2 s4 bg 105 mm2 s4 dgd 16 mm4 s2 rd 27 mm4 s2 cb 28 mm4 s2 uyi 7my objective is to get the result rows whose count is max between the groups like 0 mm1 s1 a 31 3 mm2 s3 mk 84 mm2 s4 bg 10 8 mm4 s2 uyi 7somebody knows how can i do it in pandas or in pythonupdatei did not give more details for my question for my problem i want to group by spmt let take a second example like this sp mt value count4 mm2 s4 bg 105 mm2 s4 dgd 16 mm4 s2 rd 27 mm4 s2 cb 88 mm4 s2 uyi 8for the above example i want to get all the rows where count equals max in each group eg mm4 s4 bg 10mm4 s2 cb 8mm4 s2 uyi 8,['python'] +447498,ignore virtual properties we have mvc4 project with entity framework for storagefor our tests we recently started using autofixture and it is really awesomeour models graph is very deep and usually creating one object by autofixture creates the whole graph person team departments company contracts etcthe problem with this is time object creation takes up to one second and this leads to slow testswhat i find myself doing a lot is things like this var contract fixturebuildpersoncontract withoutc cperson withoutc cpersoncontracttemplate withoutc coccupation withoutc cemploymentcompany createpersoncontractand this works and it is quick but this overspecification makes tests hard to read and sometimes i loose the important details like withc cpersonid 42 in the list of unimportant without all these ignored objects are navigational properties for entity framework and all are virtual is there a global way to tell autofixture to ignore virtual membersi have tried creating ispecimentbuilder but no luckpublic class ignorevirtualmembers ispecimenbuilder public object createobject request ispecimencontext context if requestgettypeisvirtual this does not exist return null i cannot seem to find a way in ispecimenbuilder to detect that object we are constructing is a virtual member in another class probably ispecimenbuilder this is not the right place to do this any other ideas,['c#'] +447557,rake before task hook is there a straight forward way to modify a rake task to run some bit of code before running the existing task i am looking for something equivalent to enhance that runs at the beginning rather than the end of the taskraketasklameenhancei run afterwards ha ha,['ruby'] +447566,unknown provider rootscopeprovider i am trying to inject scope into a jasmine test but get the exception unknown provider rootscopeprovider rootscopemy spec file is thisdescribewith data returned from normdefinitions api function const dummydata id 1 name name 1 description description 1 id 2 name name 2 description description 1 var scope mockservice query function return dummydata beforeeachinjectfunction rootscope scope rootscopenew itit can be instantiated injectfunctioncontroller var controller controllernormdefinitionscontroller scope scope myservice mockservice expectcontrollernottobenull what am i missingthanksdave,['javascript'] +447577,why does java mask shift operands with 0x1f in java0xf 1 0xfe 0b10 0xf 30 0xe0 0b10xf 30 0xc0 0b110xf 31 0x80 0b10however0xf 32 0xf 0b1logically this makes no sense but what i believe to be happening is java performing an operation similar to a b integersize edit apparently a b 0x1fthis applies to and too obviously shifting by 32 in the case of an integer removes all data from the datatype but there are times when this is useful for exampleint value 0x3f43f466 any valueint shift 17 any value 0int carry value 1 integersize shiftif carry 0 codeof course this can be fixed but finding these bugs can be quite time consuming i just spent hours tracking a similar one down so my question is there reason for not returning the logical value when shifting all bits outupdatei tried this in c99 using the followingincludestdiohmain int i val for i 0 i 36 i val 1 i printfd tdn i val i found that it behaves the same as java masking i 0x1f whereas it provides a warning at compilation when given a constant valuewarning left shift count width of type,['java'] +447624,autoloading classes in phpunit using composer and autoloadphp i have just installed phpunit version 3719 by sebastian bergmann via composer and have written a class i would like to unit testi would like to have all my classes autoloaded into each unit test without having to use include or require at the top of my test but this is proving to be difficultthis is what my directory structure looks like a trailing slash indicates a directory not a filecomposerjsoncomposerlockcomposerpharlibreturningphptestsreturningtestphpvendorbinphpunitcomposerphpunitsymfonyautoloadphpmy composerjson file includes the followingrequire phpunitphpunit 37 phpunitphpunitselenium 12my returningphp class file includes the followingphpclass returning public var function construct thisvar 1 my returningtestphp test file includes the followingphpclass returningtest extends phpunit framework testcase protected obj null protected function setup thisobj new returning public function testexample thisassertequals1 thisobjvar protected function teardown however when i run vendorbinphpunit tests from the commandline i get the following errorphp fatal error class returning not found in filescodephpdbtestsreturningtestphp on line 8i noticed that composer produced an autoloadphp file in vendorautoloadphp but not sure if this is relevant for my problemalso in some other answers on stack overflow people have mentioned something about using psr0 in composer and the namespace command in php but i have not been successful in using either oneplease help i just want to autoload my classes in phpunit so i can just use them to create objects without worrying about include or requireupdate 14th of august 2013i have now created an open source project called phpunit skeleton to help you get up and running with phpunit testing easily for your project,['php'] +447641,mysql select thistinct count user id video id 1 1 1 1 1 2 2 1 2 2 i have a table setup similar to the one above i would like to return a total count from my queryfor each user id they need to have a thistinct video id so above user id 1 would have 2 unique video ids and user id 2 would have 2 unique video ids this would make the total 4 i am not sure the best way to organize my query to achieve the desired resultbasically for each user id i need something like countthistinct video idi would like the final result just to return total count of everything,['mysql'] +447642,garbarge collection in ruby with circular object references i am having an issue with garbage collection in ruby where an object that i think should be garbage collection is not being garbage collectedrequire rubymassdef find dependencies object id mapped mapped mapped points to object massreferencesmass object id ids points to objectkeysmapx dmatchxcapturesfirstto i mapped object id ids unmapped ids mappedkeys unmappedeach do x new deps find dependenciesxmapped mappedmergenew deps end mappedenddo some stuff that makes the objects and find the relevant object id gcstart then find dependencies144789180 14478918061895480 144786340 147807540 61895480144789180 144786340144789180 147807540144789180it looks like there is a circular reference pattern here but it is all completely contained in these four objects so the markandsweep collector should find them and remove themso either there is a bug in my find dependencies function the mass gem or rubys garbage collector how do i narrow this down to find out what the problem is and solve this memory leak,['ruby'] +447651,elementstyle in chrome element inspector when i inspect elements in chrome under my styles i have elementstyle what does this refer to it contains styles i am not including in my code source,['css'] +447669,javascript library to implement command line in browser i would like to allow powerusers to perform certain actions on the site in a commandline like interface think quake console that slides in from above is there a library that already implements the basics of what i need in the browser tasks like getting the input from the user command history etc me and my colleagues will have limited time to implement this during a hackathon so we want to have as much time as possible to implement the actual commands interfacing with our app,['javascript'] +447709,load iframe links into parent window i have this iframe codeiframe src border0 framespacing0 marginheight0 marginwidth0 vspace0 hspace0 scrollingyes width100 frameborder0 height100iframewhat i am trying to do iswhen i click any link in iframe pagethen i will go to it and the page will load and i will getout from the current page to the iframe link as a new pagesomething like target self not like the normal iframe which will go to this link without any changes in browser itselfexample iframe src when i click learn html inside the iframe pagethen i will go to and my browser url will change to it tooso i just clicked a link inside the iframe and i go to itany ideas,['html'] +447778,pragma warning thisable restore i have used c to create a first project i have many warning errors and all these warning errors are to be single errorinternal compiler error see the console log for more information for reducing the warning errors i used pragma warning thisable pragma warning restorefront and back of the problematic codei have doubt that in my final build i should leave that pragma warning thisable restore as it is in the program or do i need to remove that egpragma warning thisableif thisplayerinstance null ctrtore keepit thisplayerinstancesetfielderprofile ipragma warning restorefor final build do i need to remove that or not,"['c#', '.net']" +447799,numbering an ordered list like an array with brackets around the numbers i have this listol start0 litokyo skytreeli licanton towerli licn towerli liostankino towerli lioriental pearl towerliolwhich shows something like this1 tokyo skytree2 canton tower3 cn tower4 ostankino tower5 oriental pearl towernow what i want is to have something like this1 tokyo skytree2 canton tower3 cn tower4 ostankino tower5 oriental pearl towerideally i want a 0based array like0 tokyo skytree1 canton tower2 cn tower3 ostankino tower4 oriental pearl toweri have read about css numbering style and css lists w3c draft but i cannot figure out a solution that works,['css'] +447844,string to biginteger java i am trying to read some really big numbers from stdin and adding them togetherhowever to add to biginteger i need to use bigintegervalueoflongprivate biginteger sum bigintegervalueof0private void sumstring newnumber biginteger is immutable reassign the variable sum sumaddbigintegervalueoflongparselongnewnumberthat works fine but as the bigintegervalueof only takes a long i cannot add numbers greater than longs max value 9223372036854775807whenever i try to add 9223372036854775808 or more i get a numberformatexception which is completely expectedso i am really asking myself whats the point of using biginteger if i can only add longswhy is not there something like bigintegerparsebigintegerstring as in integer long boolean etc,['java'] +447872,zend framework 2 with zfcrbac database population there are numerous getting started tutorials out there on how to implement zfcuser and zfcrbac into zend framework 2 the github pages for zfcuser and zfcrbac are clear and the implementation is indeed pretty easy as stated on many of the tutorials i also found the sql schemes which are needed for both zfcuser and zfcrbac vendorzfcommonszfcuserrbacdatathe creation of a user into the database is easy since zfcuser already sets this up for you everything fine so far now i want to populate the roles but it is not clear to me on how to populate the rbac tables correctly the lack on information about this surprises me since the zfcrbac component is a popular module for the zend frameworki understand the principal of role based access control and the population of the tables for the permissions and the table linking the permissions and roles together are clear it is the role table that is not clear to me i understand that you can have a role which has a parent role but it is not clear how to populate the table with a parent role since there is a foreign key constraint which states the parent role id has to be a role idbelow is the sql for the role table this is the sql provided by zfcrbaccreate table rbac role role id int11 unsigned not null auto increment parent role id int11 unsigned not null role name varchar32 null primary key role id key parent role id parent role id engineinnodb default charsetutf8 auto increment1 alter table rbac role add constraint rbac role ibfk 1 foreign key parent role id references rbac role role idwith the foreign key in place adding a parent role seems impossibleinsert into rbac role parent role id role name values null adminbasically my question is and i feel very stupid for asking this but how does an insert for a parent role look like and if the insert statement i presented is in fact correct do i always need to remove the foreign key before inserting a parent role,['php'] +447892,search arabic letters in arabic words here ny working code doctype html html head meta httpequivcontenttype contenttexthtml charsetutf8 head body php arabic uu 3 u1u u3auu uu aa 1 u uu u u1 u french que voulez vous direif isset postsearch search postsearchkey postkeytd substr countarabic keyecho tdecho br arabicfunction count occurenceschar string haystack case sensitive trueif case sensitive false char string strtolowerchar string haystack strtolowerhaystackcharacters preg splitu char string 1 preg split no emptycharacters str splitchar stringcharacter count 0foreach characters as character character count character count substr counthaystack characterreturn character countform nameinput action methodpostinput type text namekey valueinput type submit namesearch value find it form bodyhtmlfor the french it works good however with arabic no of course there is no error but if i enter forexample to search for that letter it shows always 0 forevery letter i enteris there some wrong or im missing something with arabic i dont know why in french works good if i enter v it shows 2 in resultany help please,"['php', 'html']" +447911,jade change active menu item in parent template i have a navigation bar in my parent jade template and i would like to highlight the item which is currently in view so if i am on the blog page ul li home liactive blog li contact us li aboutwithout copying the navigation bar structure into each child template is there a way to have the parent template see what page it is extending and apply the active class accordingly,['html'] +447924,pickleload raising eoferror in windows this is how the code is with openpickle f r as fhand obj pickleloadfhandthis works fine on linux systems but not on windows its showing eoferrori have to use rb mode to make it work on windows now this is not working on linuxwhy this is happening and how to fix it,['python'] +447929,with xtable and type html how to add a class to a specific td tag i am trying to create a table in html with xtable but i need to add a class to specific td tag because i going to do an animation the problems is that i cannot do it without xtable because it is so slow may be i need to represent this but with xtablemyrendertablefunction table table fori in 14862 table pastetabletrtditdsep forj in 15 ifj 5 table pastetabletd class somethingijtdsep else table pastetabletdijtdsep table pastetabletrtable returntableif i do it with xtable my app takes 15sec but if i do it with myredertable function my app takes 2 minutes so how can i do to put this class in a td with xtablei am working with r and shiny,"['html', 'css']" +447932,python ospipe vs multiprocessingpipe recently i am studying parallel programming tools in python and here are two major differences between ospipe and multiprocessingpipedespite the occasion they are used ospipe is unidirectional multiprocessingpipe is bidirectionalwhen putting things into pipereceive things from pipe ospipe uses encodedecode while multiprocessingpipe uses pickleunpicklei want to know if my understanding is correct and is there other difference thank you,['python'] +447946,why does this angular controller throw error unknown provider nprovider jsfiddle of the codediv ngapp div ngcontrollerfirstctrl input typetext ngmodeldatamessage datamessage world divdivfunction firstctrlscope scopedata message hello i am just starting to learn angular using the videos on eggheadio following along i got stuck on the 2nd video where john thiscusses controllers it works in his video fails on my machinethe code is so basic i cannot figure out whats throwing this error error unknown provider nprovider n at error anonymous at at objectc as get at at c at d at objectinstantiate at at at and this error gets thrown if i use the google cdn as well from the error i thought perhaps it was the cdns fault,['javascript'] +447955,if fn fn or fn fn i have seen many times that fn fn is an optimization of if fn fnmy question are why and what is the generated code for both solutions,['javascript'] +447959,sql between for text vs numeric values between is used used in a where clause to select a range of data between two valuesif i am correct whether the ranges endpoint are excluded or not is dbms specificwhat i can not understand in the followingif i have a table of values and i do the following query select food name from health foods where calories between 33 and 135 the query returns as results rows including calories 33 and calories 135 ie range endpoints are included but if i doselect food name from health foods where food name between g and oi do not get rows with food name starting with o ie the end of the range is excludedfor the query to work as expected i typeselect food name from health foods where food name between g and p my question is why is there such a difference for between for numbers and text data,"['mysql', 'sql']" +448063,how make middle div to fill space between floating elements i have three div elements left middle and rightleft and right are fixed and floating what i want is the middle div to fill the gap in between themthis is my codedoctype htmlhtmlhead style border dotted 1px red left width 200px float left middle float left right width 200px float right styleheadbody div idleft left div div idmiddle middle div div idright right divbodyhtmlany ideas on how to do this i tried different solutions but did not manage to do what i want,['html'] +448070,ironpython on xamarin i am having difficulty getting ironpython running in a xamarinandroid app xamarin states they have limited dlr supporti installed the latest version of iron python on my pc in my xamarinandroid project in xamarin studio i added references to ipy install dirplatformsandroiddll when i compile i get cprogram files x86msbuildxamarinandroidxamarinandroidcommontargets22 error exception while loading assemblies systemiofilenotfoundexception could not load assembly microsoftscripting version11020 cultureneutral publickeytoken7f709c5b713576e1 perhaps it does not exist in the mono for android profilefile name microsoftscriptingdll at monodroidtunermonodroidresolverresolveassemblynamereference reference readerparameters parameters at xamarinandroidtasksresolveassembliesaddassemblyreferenceslist1 assemblies assemblydefinition assembly at xamarinandroidtasksresolveassembliesexecute ipyscripterif xamarinandroid has iron python support how do i go about implementing it the goal for my app is for the user to be able to create and run ipy scripts,['android'] +448084,write a mode method in java to find the most frequently occurring element in an array the question goes write a method called mode that returns the most frequently occurring element of an array of integers assume that the array has at least one element and that every element in the array has a value between 0 and 100 inclusive break ties by choosing the lower valuefor example if the array passed contains the values 27 15 15 11 27 your method should return 15 hint you may wish to look at the tally program from earlier in this chapter to get an idea of how to solve this problembelow is my code that almost works except for singleelement arrayspublica statica inta modeinta na a a a arrayssortna a a a int count2 0 int count1 0 int pupular1 0 int popular2 0 for int i 0 i nlength i pupular1 ni count1 0 see edit for int j i 1 j nlength j if pupular1 nj count1 if count1 count2 popular2 pupular1 count2 count1 else ifcount1 count2 popular2 mathminpopular2 pupular1 return popular2edit finally figured it out changed count1 0 to count1 1 everything works now,['java'] +448098,copy one 2d array to another 2d array i used this code to copy one 2d array to another 2d arrayarraycopyteamperformance 0tempperformance0 teamperformancelengthhowever when i change some data in tempperformance then these changes also apply to teamperformancewhat should i do to control that,['c#'] +448106,css animation similar to mac os x 108 invalid password shake on the mac os x 108 password screen if you enter an invalid password it will shake back and forth aka left and right i am trying to achieve an similar effect for an html password input field using css animationsi created a password shake jsfiddle that seems to emulate this behavior however it does not seem quite right i am not sure the explicit keyframes and the linear timing function are the right approach this is my first attempt at a css animation and i am looking for feedback on the right way to achieve thishtmldiv classbox input typepassword iddemopassword placeholderpassword autofocus divjavascriptdemopasswordonkeyup function e var input this var val triminputval inputremoveclassinvalid if ewhich 13 val return if val password inputselect inputaddclassinvalid cssdemopasswordinvalid outlinecolor red also need animation and mozanimation webkitanimation shake 6s linear also need keyframes and mozkeyframes webkitkeyframes shake 0 left10px 16 left9px 33 left6px 50 left5px 66 left2px 83 left1px 100 left 0px editi did find animatecss which has a shake animation i have included the non browser prefixed css below instead of setting left is does a transform translatex which likely has a better chance for hardware accelerationanimated animationduration 1s animationfillmode bothkeyframes shake 0 100 transform translatex0 10 30 50 70 90 transform translatex10px 20 40 60 80 transform translatex10pxshake animationname shake,['html'] +448134,vertically center items with flexbox i am trying to vertically center items with css flexbox and i know how to do it with the nonvendorprefixed code but even with the vendor prefixes i cannot get it to work in webkit chromei am trying to vertically align the spans in triggerhere is my csstrigger 2009 syntax thisplay webkitbox thisplay box current syntax thisplay webkitflex thisplay flextrigger span 2009 syntax webkitboxalign center current syntax webkitalignitems center flexalign centerany ideas what i am doing wrongand if you know the other vendor prefixes versions of the properties that i am using feel free to share them so that this can work in more than just webkit,['css'] +448141,why write code jquery like this why write code jquery like thisfunction function jquery,['jquery'] +448160,using python logging in multiple modules i have a small python project that has the following structure project pkg01 test01py pkg02 test02py loggingconfi plan to use the default logging module to print messages to stdout and a log fileto use the logging module some initialization is required import loggingconfigloggingconfigfileconfigloggingconflogr logginggetloggerpyapplogrinfotestingat present i perform this initialization in every module before i start logging messages is it possible to perform this initialization only once in one place such that the same settings are reused by logging all over the project,['python'] +448216,role based security for osgi i am searching for a security framework that allows role based security for osgi services as well as cxf webservicessome time ago i already used spring security but as we now switched to blueprint it is not an option anymore as far as i understood to configure the access rules i would like to mainly use the standard rolesallowed annotation so what are my best starting points i also thought about implementing this myself as a blueprint extension but i would prefer an existing solution,['java'] +448318,database context and return dynamic result set in aspnet mvc in mvc 4 and ef 5 i want to run dynamic query var returndata contextdatabasesqlquerytype strsql nulli do not know how many fields it will return and name out of this result i want to make table structure that will thisplay on viewquestion what should i passed as typemy query return below resultfield 1 field 2 field 3 field 4 field 5row1row2appreciate any suggestion,['c#'] +448330,using jmeter to test a socket i would like to use jmeter to test an application that communicates over sockets it is done in java in the server i have the typicalmyserversocket new serversocket1025for every connection a thread reads and understands a lineand in clients i have the typicalclientsocket new sockethostcm 1025out new printwriterclientsocketgetoutputstream trueoutprintlnsome bit string herei would like to use jmeter or any other load testing tool to send lots of requests at the same time and make my stress and load testing but i dont know how to prepare a test is is possible to do this in jmeter at all,['java'] +448336,how many reflows does attaching a documentfragment cause using documentframgment allows us to attach dom elements to each other without causing a browser reflow ie work with offline dom trees a lot of libraries like jquery use document fragments to improve performancethe document fragment can have a complicated structure for example let us say it represents something likediv span a hrefasdasda span span a hrefasd2asd2a span div div hello world div divdivor a document fragment that contains multiple childrenh2title 1h2plorem ipsumpplorem ipsumph2title 2h2plorem ipsumpplorem ipsumpoften when we finish building the the fragment we attach it to the main dom treehow many reflows happen when we do this does it depend on the number of direct children of the document fragmentupdatei got a response from addy osmani who is on the chrome team at googlejust one dom reflow ps were moving more towards referring to reflow as layout as it is basically an event triggering layoutrepaint in the page,"['javascript', 'html']" +448342,why is app not compatible with tablets after update i have an app that is been available for over 2 years and supported on tablets for as long as tablets have been around i have an asus transformer tablet that i use for tablet testing before i made the update the app was compatible with tablet devices for my recent set of changes then only thing i changed in the android manifest file was the app version number and app version string everything else is exactly the same as before however after the update when i search for the app in google play the app does not appear when i view the app in a browser on my tablet it says your device is not compatible with this versionhow exactly can this new version be incompatible with tablets when no permissions were modified inside of the android developer console when i view my app it says that 2673 devices are supported and it says 0 devices are excluded that is right zero devices well if that is true how can i possibly get an incompatibility message also when i view the list of supported devices my asus tablet is listed therenote that the app size is only 119 mb and that i actually have 2 executables for the same app but the other executable is specifically for android 15 and lower and its version code is 0300800 so it is lower than the version code for the executable that supports android 16 and higher using the compatibility packagealso i am able to load the app directly onto the tablet when connected to my computer using adb the only reason i even realized this problem was occurring now is because i received emails from a couple of tablet users who said they were getting the same message as me except they had different tablets that i dohere is my manifest file again it is unchanged aside from the version numberxml version10 encodingutf8manifest xmlnsandroid packagemy package androidversioncode0400921 androidversionname921 androidinstalocationautousespermission androidnameandroidpermissionwrite external storageusespermission androidnamecomandroidvendingcheck license usespermission androidnameandroidpermissionaccess network state supportsscreens androidanydensitytrueapplication androidicondrawableicon androidlabelstringapp name activity androidnameapp androidlabelstringapp name intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activityactivity androidnameactivity1 androidlabelactivity1activitymore activitiesapplicationusessdk androidminsdkversion4 androidtargetsdkversion8,['android'] +448357,dynamic thispatch in c using virtual method table i am hoping to find a hint preferably by good example for implementing dynamic thispatch in ci am learning c and as practice i want to translate from java to c using dynamic thispatch virtual method tablefor example i have a java code abstract class foo public abstract int val public abstract boolean errorclass fail extends foo public int val return 0 public boolean errorreturn trueclass intfoo extends foo int v public intfooint valuethisvaluev public int val return v public boolean errorreturn falseand i could just translate some basic stuff like thistypedef struct foo voidvtablefootypedef struct fail voidvtable struct foo inheritedfailtypedef struct intfoo voidvtable struct foo inheritedintfooi am stuck while trying to complete this because i do not knowhow to define these methods in cset the address of these methods in vtable so that the compilerrecognizes the right method to callwhat else to define to make it work,"['java', 'c']" +448366,dynamically creating a proxy class i am trying to create a proxy class dynamically i know there are some very good frameworks out there to do this but this is purely a pet project as a learning exercise so would like to do it myselfif for example i have the following class implementing an interfaceinterface imyinterface void myprocedureclass myclass imyinterface void myprocedure consolewritelinehello world to intercept methods to this class in order to log them i am creating another class my version of a proxy class which implements the same interface but contains a reference to the real class this class performs an action eg logging and then calls the same method on the real classfor exampleclass proxyclass imyinterface private imyinterface realclass get set void myprocedure log the call consolewritelinelogging call the real method realclassmyprocedure the caller then calls all methods on the proxy class instead i am using a basic homebrew ioc container to inject the proxy class in place of the real class i am using this method because i would like to be able to swap out realclass at run time to another class implementing the same interfaceis there a way to create proxyclass at run time and populate its realclass property so it can be used as a proxy for the real class is there a simple way to do this or do i need to use something like reflectionemit and generate the msil,"['c#', '.net']" +448373,typescript how to check if an array index exist i am trying to check whether an array index exist in typescript by the following way just for examplevar somearray fill the array with dataif index in somearray do somethinghowever i am getting the following compilation errorthe in operator requires the left operand to be of type any or the string primitive type and the right operand to be of type any or an object typeanybody knows why is that as far as i know what i am trying to do is completely legal by jsthanks,['javascript'] +448454,android app using webviewjavascript what can be security concern i am creating an android web app using webview and javascript making addjavascriptinterfacetruemy app will content datahtml that will be loaded from an external sitei worried about the crositescripting xsecurity of my app as i am enabling addjavascriptinterfacetruewhat are the things i should be taking care so that any malicious code should not run on my app,"['javascript', 'android']" +448525,python a quick way to return list without a specific element if i have a list of card suits in arbitrary order like sosuits h c d sand i want to return a list without the cnoclubs h d sis there a simple way to do this,['python'] +448546,dynamic css not applied in my menu tiles spring 30 i am using spring 30 tiles i have created the common menu with anchor tag for all the pages and applied the css for the same i am using jquery for dynamically changing the css class for the menu when the menu is clickedwhen the menulink is selected aselectedtaba css class is to be applied and for all the normal links ataba css class is to be applied i am facing the problem that with each requestclick on the menu the style class is applied and then after the response it gets unapplied again that is the style remains applied between the request and response but not after the response the code for menu links is as underdiv idmenu class mainpagelayout clearfix stylewidth980pxmargin0 auto a iddashboard claselectedtab hrefdashboardhtml onclickreturn changecssdashboard spandashboardspan a a idprojects classtab hrefprojectscontrollerhtml onclickreturn changecssprojects spanprojectsspan a a idmilestones classtab hrefmilestoneshtml onclickreturn changecssmilestones spanmilestonesspan a a idtasks classtab hreftaskshtml onclickreturn changecsstasks spantasksspan a a idthiscussions classtab hrefmessageshtml onclickreturn changecssthiscussions spanthiscussionsspan a a idreports classtab hrefreportshtml onclickreturn changecssreports spanreportsspan a a idhistory classtab hrefprojectshistoryhtml onclickreturn changecsshistory spanhistoryspan a a idtemplates classtab stylefloat right hrefprojectsusershtml onclickreturn changecsstemplates spanproject templatesspan a a idusers classtab stylefloat right hrefprojectsprojecttemphtml onclickreturn changecssusers spanusersspan adivthe jquery for the same isfunction changecssaid alertaidjquerymenu aremoveclaselectedtabjquerymenu aaddclasstabjquery aidremoveclasstabjquery aidaddclaselectedtabthe css classes for the menu areaselectedtabhover studiotopnavigationpanel contentsection navigationbox a selectedtabactive backgroundcolor b8d9ed backgroundimage urlimagestab selected bgpng backgroundposition center top backgroundrepeat repeatx color 3 cursor pointer thisplay block float left fontsize 14px marginright 3px padding 5px 12px textdecoration none studiotopnavigationpanel contentsection navigationbox atab studiotopnavigationpanel contentsection navigationbox atabvisited studiotopnavigationpanel contentsection navigationbox atabhover studiotopnavigationpanel contentsection navigationbox atabactive backgroundcolor ecf3f7 backgroundimage urlimagestab bgpng backgroundposition center top backgroundrepeat repeatx color 3 cursor pointer thisplay block float left fontsize 14px marginright 3px padding 5px 12px textdecoration nonestudiotopnavigationpanel contentsection navigationbox aselectedtab studiotopnavigationpanel contentsection navigationbox aselectedtabvisited studiotopnavigationpanel contentsection navigationbox aselectedtabhover studiotopnavigationpanel contentsection navigationbox aselectedtabactive backgroundcolor b8d9ed backgroundimage urlimagestab selected bgpng backgroundposition center top backgroundrepeat repeatx color 3 cursor pointer thisplay block float left fontsize 14px marginright 3px padding 5px 12px textdecoration noneplease tell where i am wrong and provide appropriate solution for the same as soon as possible,"['java', 'jquery']" +448556,should use size t or ssize t at my code i do not use int or unsigned int i only use size t or ssize t for portable for exampletypedef size t intc instead of unsigned inttypedef ssize t uintc instead of intbecause strlen string vector all use size t so i usually use size t and i only use ssize t when it may be negativebut i find thatthe unsigned integer types are ideal for uses that treat storage as a bit array using an unsigned instead of an int to gain one more bit to represent positive integers is almost never a good idea attempts to ensure that some values are positive by declaring variables unsigned will typically be defeated by the implicit conversion rulesin the book the c programming languageso i am puzzled am i wrong why does the stl not abide by the suggest on the book,['c++'] +448644,prevent expiration of individual sessions based on custom conditions a website i am working on is very data centric some reports take more than an hour to complete whenever a user submits a request for a report a new thread is created which generates the report the user is then redirected to a page which says that the report in progress and to please refresh to download the report if the user again refreshes the page and the report is still in progress the same message is shown otherwise a download link is providedall reportuser relations are saved in the application variable that works fine except when the user is inactive for more than 20 min while the report is being processed and then the user is logged out if the user logs in again the report can still be downloadedi do not want to increase the session expiration time but i need to stop the expiration if the user has something going in background like a report being processedin session end i am able to retrieve the the userid and match it in applicationwork to see the user has pending work or nothowever i am clueless as to how i can defer the session end in the above caseedit every one has suggested as a workaround from maintaining a contact to using query string maintaining the contact looked the most promising to me but it fails in the following scenarios a when browser is closedcomputed goes in standby mode during lunch etc b when user goes to another nonaspnet section it is a legacy siteis not it possible to cancel the session end event itself,"['c#', 'asp.net']" +448652,if condition inside switch case i am trying to convert an if statement to switch cases for readability 1 i have read switch statements are aweful in general is that true2 the statement goes like thisswitch show case thisplayexpense if expectedexpense true break case thisplaynonexpense if expectedexpense true break case thisplayall code break error is control cannot fall through from one case label case 1 to anotherthis is the original if statementif show thisplayall expectedexpense true show thisplayexpense expectedexpense false show thisplaynonexpense code,['c#'] +448678,unable to receive proper udp packets using ssdp i am trying to implement a very simple ssdp functionality into my android app taken from heremy application sends some udp packets containing a relevant msearch message to the broadcasting address without any issue the problem is i should be getting a proper response back from other devices that is running a upnp server for some reason i am only receiving the exact same packets back i sent from my android devicemainactivityjavaoverride protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate wifimanager wm wifimanagergetsystemservicecontextwifi service wifimanagermulticastlock multicastlock wmcreatemulticastlockmulticastlock multicastlocksetreferencecountedtrue multicastlockacquire setcontentviewrlayoutactivity main buttonthisfindviewbyidridbtnsendssdpsearchsetonclicklistenerthis override public void onclickview v switch vgetid case ridbtnsendssdpsearch new threadnew runnable override public void run sendmsearchmessage start default break private void sendmsearchmessage ssdpsearchmsg searchcontentdirectory new ssdpsearchmsgssdpconstantsst contentdirectory ssdpsearchmsg searchavtransport new ssdpsearchmsgssdpconstantsst avtransport ssdpsearchmsg searchproduct new ssdpsearchmsgssdpconstantsst product ssdpsocket sock try sock new ssdpsocket for int i 0 i 2 i socksendsearchcontentdirectorytostring socksendsearchavtransporttostring socksendsearchproducttostring while true datagrampacket dp sockreceive here i only receive the same packets i initially sent above string c new stringdpgetdata systemoutprintlnc catch ioexception e todo autogenerated catch block logemsearch egetmessage ssdpsocketjava where the udp packet transmission is actually donepublic class ssdpsocket socketaddress mssdpmulticastgroup multicastsocket mssdpsocket inetaddress broadcastaddress public ssdpsocket throws ioexception mssdpsocket new multicastsocket55325 bind some random port for receiving datagram broadcastaddress inetaddressgetbynamessdpconstantsaddress mssdpsocketjoingroupbroadcastaddress used to send ssdp packet public void sendstring data throws ioexception datagrampacket dp new datagrampacketdatagetbytes datalength broadcastaddresdpconstantsport mssdpsocketsenddp used to receive ssdp packet public datagrampacket receive throws ioexception byte buf new byte1024 datagrampacket dp new datagrampacketbuf buflength mssdpsocketreceivedp return dp public void close if mssdpsocket null mssdpsocketclose ssdpsearchmsgjava for constructing ssdp broadcast stringprobably unrelated to the problem i am experiencing but just in casepublic class ssdpsearchmsg static final string host host ssdpaddress ssdpport static final string man manssdpthiscover static final string newline systemgetpropertylineseparator int mmx 3 seconds to delay response string mst search target public ssdpsearchmsgstring st mst st public int getmmx return mmx public void setmmxint mmx thismmx mmx public string getmst return mst public void setmststring mst thismst mst override public string tostring stringbuilder content new stringbuilder contentappendssdpsl msearchappendnewline contentappendhostappendnewline contentappendmanappendnewline contentappendmstappendnewline contentappendmx mmxappendnewline contentappendnewline return contenttostring ssdpconstantsjavapublic class ssdpconstants new line definition public static final string newline rn public static final string address 239255255250 public static final int port 1900 definitions of start line public static final string sl notify notify http11 public static final string sl msearch msearch http11 public static final string sl ok http11 200 ok definitions of search targets public static final string st rootdevice st rootdevice public static final string st contentdirectory st urnschemasupnporgservicecontentdirectory1 public static final string st avtransport st urnschemasupnporgserviceavtransport1 public static final string st product st urnavopenhomeorgserviceproduct1 definitions of notification sub type public static final string nts alive ntsdpalive public static final string nts bye ntsdpbyebye public static final string nts update ntsdpupdatei also made sure that the manifest includes relevant permissions usespermission androidnameandroidpermissioninternetusespermission androidnameandroidpermissionchange wifi multicast state usespermission androidnameandroidpermissionaccess wifi state usespermission androidnameandroidpermissionaccess network state i am testing the app on an actual device not on emulatorany assistance would be appreciatededit upon commentmulticast itself should work without issue i have downloaded an app called bubbleupnp to test the ssdp functionality sure enough wireshark properly captures all messages sent from the phone to the broadcasting address in ssdp protocolmsearch http11man ssdpthiscovermx 3host 2392552552501900st urnschemasupnporgserviceavtransport1and the responsehttp11 200 oksturnschemasupnporgservicecontentdirectory1usnuuidd5829e9073ce42139ad14e75dbdd0232urnschemasupnporgservicecontentdirectory1locationopt ns0101nls05f3dd08b4b4b5aafa1fe983fa447f49cachecontrolmaxage900servermicrosoftwindowsnt51 upnp10 upnpdevicehost10so yeah this is without a doubt an implementation issue nothing wrong with the device,"['java', 'android']" +448700,is the literal 0xf int or unsigned in c according to this integer literals without type suffix are always ints however both gcc and clang interpret 0xf or any literal which explicitly sets the sign bit other than using the as unsigned which is correct according to this the compilers are,['c++'] +448708,whats the correct way to trigger jquery dom manipulation from within a controller so i keep reading that jquery manipulation from within a controller is bad practice but i am not clear on why or how to correct below is code from a youtube tutorial which even the video creator comments is a bad idea but does not explain why and continues to use the bad behavior anywayfrom scopedelete function var id thistodoid tododeleteid id function todo idfadeout solutionbased on langdons answer below i have arrived at the following working code for my own work which derives slightly from the example code abovevar projectlistctrl function scope project scopeprojects projectquery scopedelete function var thiselem this var thisproject thiselemproject var id thisprojectid projectdeleteid id function var idx scopeprojectsindexofthisproject if idx 1 thiselemdestroyremoveitemidx scoperemoveitem functionidx scopeprojectsspliceidx 1 appdirectivefadeondestroy function return functionscope elem scopedestroy functionfunccomplete elemfadeout complete function scopeapplyfunccomplete this differs from langdons answer in a few ways i wanted to avoid adding a parameter to the ngclick callback so i am storing it in thisproject also the example and my code needs to call destroy from within a http success callback so instead of this which is no longer relevant i am storing the clicked element in thiselemupdate 2updated my solution further to reflect that funccomplete was not actually modifying the original scope,['javascript'] +448724,type punning with void without breaking the strict aliasing rule in c99 i recently came across the strict aliasing rule but i am having trouble understanding how to use void to perform type punning without breaking the rulei know this breaks the ruleint x 0xdeadbeefshort y short xy 42int z xand i know that i can safely use a union in c99 for typepunningunion int x short y datadatax 0xdeadbeefdatay 42int z dataxbut how do i use void to safely perform typepunning in c99 is the following correctint x 0xdeadbeefvoid helper void xshort y short helpery 42int z xi suspect that code will still break the strict aliasing rule since the memory at variable xs address can be modified by both x and a dereferenced yif typepunning is undefined via void what is the purpose of the void in c99,['c'] +448769,helvetica font not working in wkhtmltopdf i have been trying to use helvetica font while creating the pdf but the font is not reflected back in pdfi did some google and found some solutions but none are workabletried solution 1i found similar thing here font issuetried the last solution mentioned over thereworkaround is to define fontface in your css and have src link to external host that is accessible by wkhtmltopdfbut the solution is not workingtried solution 2i also tried to use google font api but result is still not workablehelvetica fonthere is an exampleexample of custom fonttried solution 3i tried doing it using css property page but that also is not workingwhat is the approach for a workable solution,"['html', 'css']" +448788,using linq to find duplicates but get the whole record so i am using this code var duplicates mggroupbyi new iaddr1 iaddr2 whereg gcount 1 selectggkey gridview1datasource duplicates gridview1databindto find and list the duplicates in a table based on addr1 and addr2 the only problem with this code is that it only gives me the pair of addr1 and addr2 that are duplicates when i actually want to thisplay all the fields of the records all the fields like id addr1 addr2 city stateany ideas,['c#'] +448809,how do i write the escape char to code how can i write in c the escape character i could not make google understand what i am asking,['c#'] +448845,can i get a python object from its memory address i am learning how to use qt with pyqt and i have a qtabelview with a standarditemmodel i have populated the model successfully and hooked up the itemchanged signal to a slot i would ld like to mess around with whatever object is returned in ipython so currently i have the line def itemchangedslotepw item new data itemdata print new data print itemwhich printspyqt4qtguiqstandarditem object at 0x07c5f930pyqt4qtcoreqvariant object at 0x07d331f0in the ipython session is it possible to get the object using this memory address i am not seeing anything on google maybe i do not have my terminology right,['python'] +448879,setting the html for attribute in javascript how do you set the for attribute of an html label element in javascript without using jquery or any other library,['javascript'] +448881,handling with boostprogram options before you say overkill i do not carehow can i make boostprogram options handle the required cat option i have visiblepooptions description optionsoptionsoptionsadd optionsu povaluebool write bytes from the input file to the standard output without delay as each is readpopositional options description file optionsfile optionsaddfile 1povariables map vmpostorepocommand line parserargc argvoptionsoptionspositionalfile optionsrun vmponotifyvmbool immediate falseifvmcountu immediate trueifvmcountfile supportprintvmfileasvectorstringwhich throws an exception when i run cat unrecognised option i want it to see as a positional argument and i need it in the correct order in the full file list how could i achieve thisupdatei have a half fix i needed pooptions description optionsoptionsoptionsadd optionsu povaluebool write bytes from the input file to the standard output without delay as each is read file povalue vectorstring input filepopositional options description file optionsfile optionsaddfile 1problem is i seem to only get 2 of the three when i output the argumentsifvmcountfile supportprintvmfileasvectorstringwhere supportprint nicely handles the vector and stuff,['c++'] +448972,is stdregex thread safe related to is a static boostwregex instance threadsafe but for the standarized version can i call regex search from several threads with the same regex object,['c++'] +448990,python mock requests and the response i am a beginner to using mock in python and trying to use please tell me the basic calls to get me working in below scenario i am using pythons requests modulein my viewspy i have a function that makes variety of requestsget calls with different response each timedef myviewrequest res1 requestsgetaurl res2 requestgetburl res3 requestgetcurlin my test class i want to do something like this but cannot figure out exact method callsstep 1mock the requests modulewhen mockedrequestsgetaurl is called then return a responsewhen mockedrequestsgetburl is called then return b responsewhen mockedrequestsgetcurl is called then return c responsestep 2call my viewstep 3 verify response contains a response b response c responseplease help me to complete step 1,['python'] +449017,how to set a custom keystore for debugging in eclipse for android i have a custom keystore that i use for signing my apk now i want to use the same keystore for debugging when i go to eclipsewindowspreferencesandroidbuild and set my custom key store i get keystore was tampered with or password was incorrect,"['java', 'android']" +449024,interrupt child called from ruby why interrupting ruby process with child created using call to system does not interrupt ruby process itself they should belong to the same group so should be both interrupted also this is not valid for ruby20given ruby 187 patch 371 ruby 193 patch 392 and ruby20 patch 0running ruby18 e system sleep 100 p sleep in bash and pressing ac kills only inner call to sleep 100ruby 19 behaves identicallythough running ruby20 e system sleep 100 p sleep interrupts both inner command and ruby process itself200p0editreading sources i have found that handling sigint sigquit and sighup is switched to ignored in rb syswait method which than waits for created sub process to finish and then restores handlers rb syswait in ruby v187p370 ruby v193p362 and without blocking handlers in ruby v200p0why is it done and why only for system and iopopen not x or fork,['ruby'] +449029,how to gzip while uploading into s3 using boto i have a large local file i want to upload a gzipped version of that file into s3 using the boto library the file is too large to gzip it efficiently on thisk prior to uploading so it should be gzipped in a streamed way during the uploadthe boto library knows a function set contents from file which expects a filelike object it will read fromthe gzip library knows the class gzipfile which can get an object via the parameter named fileobj it will write to this object when compressingi would like to combine these two functions but the one api wants to read itself the other api wants to write itself neither knows a passive operation like being written to or being read fromdoes anybody have an idea on how to combine these in a working fashionedit i accepted one answer see below because it hinted me on where to go but if you have the same problem you might find my own answer also below more helpful because i implemented a solution using multipart uploads in it,['python'] +449031,if a noclassdeffounderror is caused by a classnotfoundexception why does java expect you to catch both throwables when i run this code the app exits with a classnotfoundexceptionuncaught classnotfoundexceptiontry class clazz defineclassnull bytes 0 byteslength null tableputclazzgetname clazzcatch noclassdeffounderror ewhen i attempt to compile this code the compiler complains that the classnotfoundexception is not reachable because it is not thrown from within the tryclause of the trycatch statementwould not compiletry class clazz defineclassnull bytes 0 byteslength null tableputclazzgetname clazzcatch classnotfoundexception ewhen i run this code the only throwable that is caught is a noclassdeffounderrorcatches throwable of type javalangnoclassdeffounderrorwith a javalangclassnotfoundexception as its causetry class clazz defineclassnull bytes 0 byteslength null tableputclazzgetname clazzcatch throwable e systemoutprintlnegetclassgetname systemoutprintlnegetcausegetclassgetnamethe following code will compile and catch the error and only the error but it is clumsypossible workaroundtry class clazz defineclassnull bytes 0 byteslength null tableputclazzgetname clazz if 1 0 throw new classnotfoundexception we want the code to compilecatch classnotfoundexception e systemoutprintlnexcatch noclassdeffounderror e systemoutprintlnerrand yet when i write the following i can get away without a catch clause for the cause of the errorand yet this works just finetry throw new errornew ioexceptioncatch error e systemoutprintlnerrexample 3 would lead me to conclude that the throwable was a noclassdeffounderrorexample 1 would lead me to conclude that the throwable was a classnotfoundexceptionand yet example 2 shows that java would not even let me write code to properly catch the classnotfoundexceptionjust when i was about to conclude that the problem here is the errorcausedbyanexception i ran the code shown in the previous example which shows that that is not the rulecan someone please explain whats going on hereps this is the stack trace javalangnoclassdeffounderror commypckagemyclassat javalangclassloaderdefineclass1native methodat javalangclassloaderdefineclassclassloaderjava791at mainmyclassloadergetclassesmainjava78at mainmainmainjava109 caused by javalangclassnotfoundexception commypckagemyclassat javalangclassloaderfindclassclassloaderjava522at javalangclassloaderloadclassclassloaderjava423at javalangclassloaderloadclassclassloaderjava356 4 more,['java'] +449046,scipy sparse matrices purpose and usage of different implementations scipy has many different types of sparse matrices available what are the most important differences between these types and what is the difference in their intended usage i am developing a code in python based on a sample code1 in matlab one section of the code utilizes sparse matrices which seem to have a single annoying type in matlab and i am trying to figure out which type i should use2 in python 1 this is for a class most people are doing the project in matlab but i like to create unnecessary work and confusion apparently2 this is an academic question i have the code working properly with the csr format but i am interesting in knowing what the optimal usages are,['python'] +449064,change text color of selected option in a select box i have a select box the options have been styled with different colors via a css file that has been referenced i want to be able to select an option and change the text color of the closed select box to the color of the chosen optionselect idmyselect classyellowtext option classgreentext valueapple appleoption option classredtext valuebanana bananaoption option classbluetext valuegrape grapeoptionselectso if i select banana the text should change from yellow to redi have triedonchangethisstylecolor thisoptionsthisselectedindexstylecolorbut this only works if i define my styles within the option tags inside html documenti have also tried javascriptfunction setselectcolorthiselementvar thiselem documentgetelementbyidthiselementvar thisoption thiselemoptionsthiselemselectedindexvar newcolor getstylethisoptioncoloralertnew color newcolorbut this always returns the color white the getstyle function works everywhere else i use it so i do not believe that is the problem i got getstyle from this very websitefunction getstyleoelm strcssrule var strvalue ifdocumentdefaultview documentdefaultviewgetcomputedstyle strvalue documentdefaultviewgetcomputedstyleoelm getpropertyvaluestrcssrule else ifoelmcurrentstyle strcssrule strcssrulereplacewg function strmatch p1 return p1touppercase strvalue oelmcurrentstylestrcssrule return strvaluehow can i solve this with javascript,"['html', 'css']" +449078,android is jdbc supported in android devices i am doing an android application using jdbc to send data to database without using any web services i did an experiment using android 22 emulator and i am able to send data to mysql db localhost after that i tried to send using android 22 device i changed the path from jdbcmysql100223306 with jdbcmysqlx3306 x is from ipconfig of my localhost machine but it is not working in the device what could be the reasonmain doubtsdo android devices currently support jdbcwill android 22 support jdbcif supported which android versions will support jdbc,"['android', 'mysql']" +449098,guava immutablemap has noticably slower access than hashmap while working on a memory benchmark of some highthroughput data structures i realized i could use an immutablemap with only a little refactoring thinking this would be an improvement i threw it into the mix and was surprised to thiscover that not only was it slower than hashmap in a singlethreaded environment it appears to be consistently slower even than concurrenthashmapyou can see the full benchmark here the meat of the test is pretty simple time how long it takes to get a large number of random strings that may exist in the mappublic static void timeaccessmapstringstring map random rnd new randomseed int foundcount 0 long start systemnanotime forint i 0 i loop i string s mapgetrndstringbuildrnd ifs null foundcount long stop systemnanotime start systemoutprintlnfound foundcount strings out of loop attempts stringformat2f10foundcountloop success rate systemoutprintlnmapgetclassgetsimplename took stringformat4f stop1 0 0 0 seconds systemoutprintlnand running this against a hashmap a concurrenthashmap and an immutablemap all containing the same values consistently showed a dramatic slowdown when using immutablemap often upwards of 15 slower the more sparse the map ie the more often mapget returned null the greater the thisparity heres the result of a sample runfound 35312152 strings out of 10 attempts 3531 success ratehashmap took 294538 secondsfound 35312152 strings out of 10 attempts 3531 success rateconcurrenthashmap took 321465 secondsfound 35312152 strings out of 10 attempts 3531 success rateregularimmutablemap took 379709 secondsis this a documented expected issue the guava docs indicate immutable is more memory efficient but says nothing about speed for slowdowns of this magnitude i am inclined to deal with the memory costs and avoid immutable when speed is an issue and when is not it am i missing somethingsee also topicguavathiscussi7yppa5hlpg,['java'] +449122,php function call using javascript please helpi am trying to call a php function from an external php file into the javascript my code is different and largeso i am writing a sample code here this is my php codephpfunction addab cab return cfunction multab cab return cfunction divideab cab return cthis is my javascript codescript var phpadd add12 call the php add function var phpmult mult12 call the php mult function var phpdivide divide12 call the php divide functionscriptso this is what i wanna domy original php file doesnt include these mathematical functions but the idea is sameif somehow it doesnt have proper solution then please suggest me the alternative but it should call values from external phpplease help,"['php', 'javascript']" +449153,limit the amount of workers per queue in sidekiq i have been trying to limit the amount of workers per queue using the sidekiqlimit fetch gem and sidekiq seems to see the imposed limits in the log but when i watch the workers the limits are ignoredheres the part from the log where sidekiq sees the limits20130402t054719z 748 tid11ilcw debug queues recommendvariations recommendvariations recommendvariations recommendphenotypes recommendphenotypes recommendphenotypes preparse preparse preparse parse parse parse zipgenotyping zipgenotyping zipfulldata deletegenotype fitbit frequency genomegov mailnewgenotype mendeley details mendeley pgp plos details plos snpedia fixphenotypes concurrency5 require environmentproduction timeout8 profilefalse verbosetrue pidfiletmpsidekiqpid logfilelogsidekiqlog limits recommendvariations1 recommendphenotypes1 preparse2 parse2 zipgenotyping1 zipfulldata1 fitbit3 frequency10 genomegov1 mailnewgenotype1 mendeley details1 mendeley1 pgp1 plos details1 plos1 snpedia1 fixphenotypes1 strictfalse config fileconfigsidekiqyml tagsnprand heres the sidekiqyml judging from the webinterface of sidekiq the limits are ignored right now i got 2 workers on the recommendvariationsqueue but that should be 1i start the workers over bundle exec sidekiq e production c configsidekiqymlhas anyone else ever encountered this,"['ruby-on-rails', 'ruby']" +449167,android service need to run alwaysnever pause or stop i created a service and want to run this service always until my phone restart or force closedthe service should run in backgroundsample code of created service and start servicesstart the serviceintent service new intentgetapplicationcontext myserviceclassgetapplicationcontextstartserviceservicethe servicepublic class myservice extends service override public int onstartcommandintent intent int flags int startid todo do something useful hflag true smshandlersendemptymessagedelayedthisplay data 10 return servicestart not sticky override public ibinder onbindintent intent todo for communication return ibinder implementation return null manifest declarationservice androidnamemyservice androidicondrawableic launcher androidlabelstringapp name serviceis it possible to run this service always as when the application pause and anything elseafter some time my application goes pause and the services also going pause or stopso how can i run this service in background and always,"['java', 'android']" +449228,android how to have this type of time picker i am developing an application in which i want to show time picker to set a time for reminder right now i am able to show a timepicker using preference screen like this orgexampleandroidtimepreference androiddefaultvalue1200 androidkeycheck time androidsummaryset your desired time for check androidtitlecheck time timepreferencejava file is inherited from this timepicker in preferencescreen link but i want to show this on button click in particular activity and set it values in edittext or in textview i do not want to use preferencessoi want to make the layout of this screen like below imageany idea and advice will be appreciated thanks regards,['android'] +449232,code for adding to ienumerable i have an enumerator like thisienumerablesystemwindowsdocumentsfixedpage pagehow can i add a page eg dnewfiletxt to it i have tried add append concat etc but nothing worked for me,['c#'] +449278,download file with original file name in my project i am uploading a file while uploading i am saving its original file name and extension in a database and saving that file with some guid on server generated guid is also stored in database along with file name and extensionfor example file name for uploading is questionsdocxthen orignalfilename will be questionsfileextension will be docxfile be get uploaded with file name as 0c1b96d3af5440d1814db863b7528b1cuploading is working finebut when i am downloading some file it gets downloaded with file name as the guid in above case its 0c1b96d3af5440d1814db863b7528b1chow can i download a file with its original file name ie questionsdocxcode added code to thisplay files on browser file file null fileinputstream fis null bytearrayoutputstream bos null try cdocumentlibrary path of evidence library string filename urlencoderencodefilerepogetrname utf8 filename urldecoderdecodefilename iso8859 1 responsesetcontenttypeapplicationxmsdownload responsesetheadercontentthisposition attachment filename filename string newfilepath cdocumentlibrary systemfilename file new filenewfilepath fis new fileinputstreamfile bos new bytearrayoutputstream int readnum byte buf new byte1024 try for readnum fisreadbuf 1 boswritebuf 0 readnum catch ioexception ex servletoutputstream out responsegetoutputstream boswritetoout catch exception e todo handle exception finally if file null file null if fis null fisclose if bossize 0 bosflush bosclose is this code is perfect,['java'] +449288,does google play inapp billing version 3 support refunds i have gotten iab v3 working and i was able to make a purchase for a managed item however to continue developing and testing i wanted to refund the purchase so i could try making the same purchase again i logged into my google checkout merchant account and successfully refunded the purchase however the app still thinks that the user has the item purchased it has already been several weeks since i made the refund so its not a delay issue basically in my queryinventoryfinishedlistener implementation inventoryhaspurchasesku remove ads always returns true even after the refund sku remove ads is the sku for item i am selling i was expecting it to return false after the refund had been processedif you look at the handling refunds section of the iab reference it says that your app needs to be listening to the in app notify messages however the documentation for in app notify is specific to v2 of inapp billing it does not seem to be something that is available in v3 since its not mentioned anywhere in the v3 reference nor can i find any reference for it in the sample trivialdrive app that they are using to demonstrate iab v3so does v3 of iab support refundscancelling purchases has any one tried it and got it working,['android'] +449295,cannot listen to global event in jquery another question on stackoverflow pointed out that it should be possible to trigger an event on all listning objects usingeventtriggercustomeventhowever this does not seem to work for me in an example likebodybindcustomevent function alertworking am i doing something completely wrong or has this great functionality been thisabled,"['javascript', 'jquery']" +449335,concatenate requirejs modules into single file i am trying to concatenate all my requires modules and a few text templates into a single concatenated and uglified mainminjs so i can include that file in my html i figured out concatenation and uglifying part however i am not able to actually run any code in the browser theni created a barebone project on github to reproduce the problemfile structuremainjsindexhtmllogjsbuildproductionlibrequirejsnode modulesrequirebinrjsi concatenate mainjs logjs and requirejs using the build file buildproductionnode modulesrequirejsbinrjs o buildproductionjsmainjsrequireconfig paths requirelib librequirerequire waitseconds 10consolelogloading mainjsdefinefunctionrequire var log requirelog consolelogloaded logfinemain loadedbuildproductionjs mainconfigfile mainjs include requirelib name mainjs out mainminjs indexhtmlscript srcmainminjs typetextjavascriptscriptso indexhtml in a browser should print outloading mainjs loaded loaded mainbut it only prints out the first lineloading mainjsanybody knows why that is the case,['javascript'] +449346,what makes the text on a element vertically centered it seems there is some magic around the buttonelement that i do not understandconsider this markupbutton classbuttonsome textbuttondiv classbuttonsome textdivand this cssbutton background darkgrey height 40px border 2px solid grey width 100 boxsizing borderbox fontsize 14px fontfamily helvetica textalign center marginbottom 20px i am aware i could use this to center it lineheight 40pxwhat makes the text in the button element vertically centered webkit seems to predefine a webkitboxalign with a value of center for the button element if i set that to initial the text is no longer aligned to the center but that does not seem to be the full magic since on the other hand i had no luck centering the text on the div using the webkitboxalign propertyhere is a fiddle,"['html', 'css']" +449379,actionbar setprogressbarindeterminatevisibilityfalse is not working on android 23 the setprogressbarindeterminatevisibilityfalse is not working for 23 androidi am using the code belowthe progress bar is show always and is not hidden the same code is working on android 4x and the progress bar is hidden the activity is extending from sherlockfragmentactivity and there is no call like setsupportprogressbarindeterminatevisibilitytrue that will make the progress bar visiblemy complete codeoverrideprotected void oncreatebundle savedinstancestate sherlockfragmentactivity jbactivitythis requestwindowfeaturelong comactionbarsherlockviewwindowfeature indeterminate progress superoncreatesavedinstancestate setsupportprogressbarindeterminatevisibilityfalse thisplaymetrics metrics new thisplaymetrics getwindowmanagergetdefaultthisplaygetmetricsmetrics restart false actionbar getsupportactionbar if selecteditemsisnull restart true try string jsonstring savedinstancestate getstringselecteditems selecteditemsbuildjsonstring catch exception e intent mainintent new intentjbactivitythiscitylistclass mainintentaddflagsintentflag activity clear top startactivitymainintent finish there is no place in the code where i call can you please suggest a way so i can hide the progress bar on android 2x thanks,['android'] +449380,darkening an image with css in any shape so i have seen quite a few ways to darken images with css including ones with rounded corners but my problem is differentlet us say i have an png image that looks like a little dog just go with it i do not have any good examples when i place it on my page i give it dimensions of 100 x 100but i cannot just overlay something on it or tint the entire image as it will cause the background of the dog to be tinted as well which looks uglyis it possible to tint an image of arbitrary shape with cssi am assuming you understand my point and useless code is not necessarythanks,['css'] +449397,does a c11 rangebased for loop condition get evaluated every cycle forauto entity memorymanagergetitems entityupdatemframetimeif memorymanager contains 10 items does memorymanagergetitems get called 10 times or only one at the beginning of the loopdoes the compiler run any optimization with o2 or o3memorymanagergetitems returns a stdvectorentity,['c++'] +449427,appfog mysql tunnel error encryption not available on this eventmachine weve established a connection to appfog using caldecott and af tunnel command we try to connect to a mysql service to load and execute a big sql file to populate the db we tried it from 3 different machines ubuntu on virtualbox feora 18 on virtualbox and native ubuntu we also tried it on another account but we keep getting this errorlaunching mysql protocoltcp hostlocalhost port10 useruzvqhghbyezyb passwordpnu1l6xbxvhbj d39d6d0e6344b41a4aaeada16dfca2a46terminate called after throwing an instance of stdruntime error what encryption not available on this eventmachineerror 2013 hy0 lost connection to mysql server at reading initial communication packet system error 0aborted core dumped,"['mysql', 'ruby']" +449551,failed to generate the sample for media type applicationxwformurlencoded i recently started creating a aspnet web apifor some reason i keep receiving this error when viewing the auto generated help documentationthis is for a post methodsamples show up fine for applicationjson and applicationxmli am not quite sure but the applicationxwformurlencoded keeps showing upi have googled the error quite a bit but cannot quite find what might be causing thisi truly appreciate any help that can be provided also please let me know if you have any questions,"['c#', 'asp.net']" +449566,mongoose cast to objectid failed for value i am trying to specify the schema of my db in mongoose at the moment i do thisvar schema mongooseschema var today new date2011 11 12 0 0 0 0var personschema new schema id number name type string required true tel type string required true email type string required true newsitems type schematypesobjectid refnewsitemvar taskschema new schema id number description type string required true startdate type date required true newsitems type schematypesobjectid refnewsitemvar newsschema new schema id number creator type schematypesobjectid ref person task type schematypesobjectid ref task date type date requiredtrue loc type string required true var newsitem mongoosemodelnewsitem newsschemavar person mongoosemodelperson personschemavar task mongoosemodeltask taskschemavar tony new person id0 name tony stark tel234234234 email var firsttask new task id0 descriptionget an interview with the president startdatetodayvar newsitem1 new newsitem id0 creator tonyid task firsttaskid date today loc nynewsitem1savefunction err if err consolelogerr firsttasksavefunction err if err consolelogerr tonysavefunction err if err consolelogerr newsitemfindone loc ny populatecreatorpopulatetaskexecfunction err newsitem if err consolelogerr consolelogthe creator is s newsitemcreatornamei create the schemas and try to save some data the error message cast to objectid failed for value 0 at path creator name casterror type objectid value 0 path creator i wrote this code based on the db i try to create looks like this specify schema in mongoose how can i fix this,['javascript'] +449594,angular updating scope on hover i would like some child div of a main div be hidden by default an visible when you hover over the main divi am trying to have that native in angular and forget the hover way in jqueryi though about using ngshow on the child div and then updating the binding when i hover the main div is there a directive to listen for hovering,['css'] +449606,unwrap selected element javascript or jquery this is my htmlspan idcurrent classgreen unselctable dataoriginaltitle title lorem ipsum is simply dummyspani am selecting with with current but if i use the jquery unwrap function the parent tag gets removedis there any way to remove the span in javascript or jquery without parsing the string and appending it to the domediti wanna keep the content of the div i just want the tag removed,"['javascript', 'jquery']" +449608,firefox exception javascript component does not have a method named available i am building a web app with django i have a bunch of api calls in javascript via ajax jquery v183most of them work but a particular one results in a return object with status 0 and this message as the statustextexception javascript component does not have a method named available when calling method nsiinputstreamavailable nsresult 0x80570030 ns error xpc jsobject has no function named location js frame send line 8434 data nothe corresponding line in jquery is xhrsend shascontent sdata null however this occurs only in firefox chrome works fine again other requests do work the only thing which sets this one apart is the delete http methodthe request is as follow http network data shown in chrome a firebug does not show anything in firefoxrequest url request method deletestatus code 400 bad request this is expectedrequest headersaccept applicationjson textjavascript q001contentlength 15contenttype applicationjsonorigin referer xrequestedwith xmlhttprequestrequest payloadobject objectresponse headerscachecontrol nocachecontenttype texthtml charsetutf8date tue 02 apr 2013 191835 gmtserver wsgiserver01 python272on the server i do not receive any requestthe js code is taken directly from firebug watch at breakpointoptions contenttype applicationjson data object datatype json processdata false type delete url apireservation13 error function success functionajaxoptionsi also did try to thisable all extensions in ff i run v200,['javascript'] +449709,make script execution to unlimited i need to run a script into localhost xampp which will generate 14400 records and adds them into database i have set the max execution time 50 i dont know if i can make it unlimited by setting it to 0 or 1 but i tried this script before with this max execution time to 50 and yet it stoped at certain point i dont know what else could limit the execution time i have been running this a lot of times and i am tired of waiting and failing again what should i change before i run this script again and this time to finish the job,['php'] +449713,php 547 compiling ext php printer my knowledge base is i can get around in php i never worked with c c c or any compilersi upgraded from xampp 173 which used php 53 to 181 which includesapache 243mysql 5527php 547it is being installed on windows 7 pro windows xp pro and windows server 2008 r2 but i am trying to get it to working on windows 7 currentlyi upgraded because i needed a newer version of apache and mysql for security reasons i do not have the option to downgrade i use the php printerdll for the ability to print raw data to the printerprinter set optionhandle printer mode rawmy code worked fine in php 53 but broke in php 54after receiving the error fatal error call to undefined function printer open in i checked the php error log and received the following informationphp warning php startup printer unable to initialize modulemodule compiled with module api20090626php compiled with module api20100525these options need to matchi have looked for hours trying to find a precompiled php printerdll for php 547 to no avail i have concluded that i will have to compile it from source files in the pecl peclphpnetpackageprinterhaving never had to do this before i did what any internet user should do i googled it and found some information hereit took me all day but the php build worked but then tried to create the php printerdllfirst i tried svn co peclprinterbut it said svn is not recognized as an internal or external command operable program or batch fileso i just downloaded the files myself fromsvnphpnetrepositorypeclprintertrunkand put them incphpsdkphp54devvc9x86php54201303311430extprinteri made sure to download the libraries both fromwindowsphpnetdownloadsphpsdkdepsvc9x86also just thedeps54vc9x867zi tried one then the other however every time i received the following when i tried to nmakecphpsdkphp54devvc9x86php54201303311430nmakemicrosoft r program maintenance utility version 9003072901copyright c microsoft corporation all rights reservedprintercextprinterprinterc266 error c2065 pval undeclared identifierupdatei got some help on another forumby hackattack142 a 03 april 2013 2351helloopen printerc and replace all instances of pval with zval and it should compilethank you hackattack one step closer i hopecphpsdkphp54devvc9x86php54201303311430buildconfcphpsdkphp54devvc9x86php54201303311430configure thisableall enablecli enableprintercphpsdkphp54devvc9x86php54201303311430nmakemicrosoft r program maintenance utility version 9003072901copyright c microsoft corporation all rights reservedinternal functionscprinterc creating library release tsphp5tslib and object release tsphp5tsexp creating library release tsphplib and object release tsphpexpsapi sapicli build completeit seemed to have compiled however i cannot find a printerdll or a php printerdll which is the outcome i was hoping for in the release tsext folder there is a folder named printer it contains the following filesprinterobjprintersbrvc90idbi also did the last stepcphpsdkphp54devvc9x86php54201303311430cd release tscphpsdkphp54devvc9x86php54201303311430release tsphp mphp modulescoredateeregpcreprinterreflectionsplstandardzend modulescphpsdkphp54devvc9x86php54201303311430release tshelp from another forumconfigure thisableall enablecli enableprintersharedit worked and i created the php printerdll however when i tried to use itin php error log15apr2013 153453 utc php warning php startup invalid library maybe not a php library php printerdll in unknown on line 0i had to grab 547 files as i was using 5415 but xampp 181 uses 547 programming languagephpold php8227and put it in cphpsdkphp54devvc9x86php547then put the printer files in the ext folder and did all the above processes andconfigure enableprintersharedand it workedphp version 547 php printerdll printer 547zip,['php'] +449730,reference detection in array from another function so i am using the pin method but the reference is detected one level too latepin timefunction wraparr testarrfunction testarr global pin ifin arraypin arr return print ref arr pin foreacharr as v ifv pin ifis arrayv return testv print v array array1 2 3array4 arraywraparrayi get 1 2 3 1 2 3 recbut i expect 1 2 3 recif i just do testarr then it works but the problem is that i need to wrap the test function inside another one that accepts values not references is there any way i can detect the reference at the right moment with my wrapper function too,['php'] +449756,uitableviewcell reuse cell thisplaying incorrectly not being reused as expected i have created a multiselection list that allows the selection of multiple ingredientsin my tableview cells can either be enabled or thisabled based on the list property of an ingredient if the ingredients list property is set the cell will be thisabledhowever when a cell is reused it is not thisplaying as i would expect the images below explain the problem more effectively than i canthe ingredients that should not be enabled are cake icing condensed milk and cournflourthe first image shows the three ingredients thisabled and annotated as expectedhowever in the second image scrolling down reveals that some ingredients are shown to be thisabled but you can select them and they have full interactionthe third image shows the list after scrolling back up to the top some ingredients have been greyed out and notice how cornflour is thisplayed as enabled even though you cannot interactselect itthe issue is to do with cell reuse it appears that the cell is not getting reset when reused and so is keeping some of its old appearancebelow is the code from cellforrowatindexpath as i am sure this is where the problem is although i cannot see whats wrong uitableviewcell tableviewuitableview tableview cellforrowatindexpathnsindexpath indexpath static nsstring cellidentifier cell uitableviewcell cell tableview dequeuereusablecellwithidentifiercellidentifier if cell nil cell uitableviewcell alloc initwithstyleuitableviewcellstylesubtitle reuseidentifiercellidentifier fetches the corresponding ingredient from the ingredientarray ingredient ingredient selfingredientarray objectatindexindexpathrow if ingredientlist isequaltostringlardr celluserinteractionenabled no celldetailtextlabeltext already in your lardr else if ingredientlist isequaltostringshopping list celluserinteractionenabled no celldetailtextlabeltext already on your shopping list else celluserinteractionenabled yes celldetailtextlabeltext add a checkmark accessory to the cell if the ingredient is on the selectedingredients array if selfselectedingredients containsobjectingredient cellaccessorytype uitableviewcellaccessorycheckmark else cellaccessorytype uitableviewcellaccessorynone celltextlabeltext ingredientname return celli am at my wit is end trying to figure this out and i have read all so questions that are even remotely related but to no avail whats the problemmy logic is that for each cell the textlabel detailtextlabel userinteractionenabled and accessorytype properties are set no matter which execution path through the if statements so i cannot see why even after reuse the cell is not thisplaying correctlyedit in an attempt to figure out the root of the problem i have tried resetting the cell back to it is default by adding the following right above the line which fetches the corresponding ingredient but to no availcelluserinteractionenabled yescelltextlabeltext nilcelldetailtextlabeltext nilcellaccessorytype uitableviewaccessorynonehowever what is interesting and completely illogical when i moved the following line celltextlabeltext ingredientname to directly underneath the line that reads ingredient ingredient selfingredientarray objectatindexindexpathrow absolutely no styling is applied to any cell even though userinteraction is set further below and the relevant cells are thisabled as expectedi am thinking does the order in which a cells properties are set matter i know it should not but the appearance changes based on the above update i have solved the issue see my answer below,"['iphone', 'ios']" +449762,why do i have to do sysstdin codecsgetreadersysstdinencodingsysstdin i am writing a python program which uppercases all input a replacement for the nonworking tr lowers upper the locale is ru ruutf8 and i use pythonioencodingutf8 to set the stdinstdout encodings this correctly sets sysstdinencoding so why do i still need to explicitly create a decoding wrapper if sysstdin already knows the encoding if i do not create the wrapping reader the upper function does not work correctly does nothing for nonascii charactersimport sys codecssysstdin codecsgetreadersysstdinencodingsysstdin why do i need thisfor line in sysstdin sysstdoutwritelineupperwhy does stdin have encoding if it does not use it,['python'] +449803,javaxnamingnoinitialcontextexception java here is my codeimport javaxnaminginitialcontextimport javaxjmsqueueimport javaxjmssessionimport javaxjmstextmessageimport javaxjmsqueuesenderimport javaxjmsdeliverymodeimport javaxjmsqueuesessionimport javaxjmsqueueconnectionimport javaxjmsqueueconnectionfactorypublic class sender public static void mainstring args throws exception get the initial context initialcontext ctx new initialcontext lookup the queue object queue queue queue ctxlookupqueuequeue0 lookup the queue connection factory queueconnectionfactory connfactory queueconnectionfactory ctx lookupqueueconnectionfactory create a queue connection queueconnection queueconn connfactorycreatequeueconnection create a queue session queuesession queuesession queueconncreatequeuesessionfalsesessiondups ok acknowledge create a queue sender queuesender queuesender queuesessioncreatesenderqueue queuesendersetdeliverymodedeliverymodenon persistent create a simple message to say hello textmessage message queuesessioncreatetextmessagehello send the message queuesendersendmessage print what we did systemoutprintlnsent messagegettext close the queue connection queueconnclose eclipse is not reporting any errors in the above code i am able to compile successfully however when i try running it i get the following exceptionexception in thread main javaxnamingnoinitialcontextexception need to specify class name in environment or system property or as an applet parameter or in an application resource file javanamingfactoryinitial at javaxnamingspinamingmanagergetinitialcontextunknown source at javaxnaminginitialcontextgetdefaultinitctxunknown source at javaxnaminginitialcontextgeturlordefaultinitctxunknown source at javaxnaminginitialcontextlookupunknown source at sendermainsenderjava21can anyone please help me fix the bug i tried fixing it for a few hours but still cannot figure it out,['java'] +449851,how to correctly reference a dll in visual studio 2010 i have a solution that contains a c dll project and a c project that will use this dll by using pinvokethe dll is being built to the x64release folder in my solution folder which makes sense because that way the c project does not have to poke into the dll projects foldersi wonder what would be the correct way to reference it now though right now the dll project is a dependency of the c project my intuition told me that that should have been enough but the c project says it cannot find the dllshould i just add the dll file as a reference too i thought this might work now but break things in the long run when project settings might get changed around,"['c#', 'c++']" +449853,remove embedded document in mongoose i am new to nodejs and mongodb i am using the mongoose library for accessing mongodb with nodejs i have two schemas book and author author belongs to a book and book has many authori have this in my schemasvar mongoose require mongoose var schema mongooseschemavar book new schema title string isbn string authorid type schematypesobjectid ref author updated at datevar author new schema name string updated at datemongoosemodel book book mongoosemodel author author mongooseconnect mongodblocalhostlibrary the problem is that when i delete a document from author which is embedded with book it is deleted without checking the referential integrity my scenario is that if the author document is embedded with the book it cannot be deleted is mongoose automatically check the author document embedded in the book is it possible then how,['javascript'] +449867,how to use googletest failures into breakpoints i recently thiscovered the failures into breakpoints option from googletest using the command line option gtest break on failure or by defining the gtest break on failure environment variablei gave it a try using gtest break on failure from command line i saw no effect to be honest i had the glimpse of hope that vs2010 would be registered as debugger and somehow magically would pop up and point to the error sourceusing it in the vs environment as command line argument a failed assertion triggered a break but the call stack did not include the test method that caused the failure i found the work around to step f10 until i reached my test code but that does not really seem to be convenientis it somehow possible to use the option from command line has anybody a recommendation how to get the correct call stack in the environment,['c++'] +449905,how to install php pthreads extension on ubuntu i would like to install the pthreads php extension on ubuntu i am using ubuntu 12041 lts and i can upgrade if needed i really do not want to compile anything from source for example recompile php from source sounds like a horrible idea to mein my view the best option is to install this extension with aptitude command for example like aptitude install php5mysql another good idea is to use pecl pecl install pthreads but is does not work for me because of the following errorchecking checking for zts configure error pthreads requires zts please recompile php with zts enabledlet me explain why i do not like the idea to recompile php from sourcei guess i should uninstall original php package then and all the dependencies because if i compile it over standard php then any packages update would overwrite my changes and yes another option is to keep php from updating anyway this introduces some extra work and makes the setup more complicated we work in the thistributed team and i do not want other people to deal with this complicated setup on production serversi want to install updates on servers and i do not want to recompile php because of security fixes etci do not want to compile anything on production servers and do this many times then i should build my own packages and update them with new versions etc sorry but i am not smart enough to do this may be in 23 years but not now because there are a lot of things to keep in mind here for example how to replace standard php package with custom package while still satisfying all dependenciessome referencesdynamically configure php for thread safety enablemaintainerzts or use yum to install pthreadshow to use pthreads php extension in ubuntu some talks about what i am going to do herebuilding pthreadsthis article seems to be old and not actual i will keep it for reference only and i guess it should be read as php was not thread safe 3 years agodonat believe the lies php isnat threadsafe yet,['php'] +449985,angularjs inlineediting i am trying to find the best approach of inlineediting with angularjs in my case it is kind of a datagrid with an edit button so it is inside ngrepeatwhat i have seen people do is have both actual data and editing inputs in the same row with editing inputs being hidden and shown on click of the edit buttonbut it does not seem right it is a lot of useless dom in my opinionso i thought i would be better to do something like this you click on the edit button which is gonna have a directive which would 1 hide the td with data 2 find buttons parent which should be the tr and inject a template with into it 3 on save remove those editing tds and show the data tds again so i started with making the directive inside i had elementclick function which found the parentvar parent elementclosesttr found all the data tdsvar tds parentfindtd hidden them tdshidenow heres the problem next i thought about doing something like this append input with editing tds into parentparentappendtdinput typetext ngmodelentryname entryname tdbut then it wouldnt bind or even parse the would it what method would i have to use instead of jquerys append docu on directives says thistemplate element the element where the directive has been declared it is safe to do template transformation on the element and child elements onlyso i cannot use template transoformation on the elementparentwould it help if i made the directive on the tr and even if i did i would then transform my whole tr which means i would lost the original template and i would have to have another directive or something that would transform it back to the original state wouldnt ieditsince this questions seems pretty popular firstly my original worry of rendering additional element with each ngrepeat iteration is unfounded because 1 you can use ngif which means it is not gonna be rendered at all until the condition is true 2 you could append a template just as i intended then just use compile and it is gonna work just fine it is definitely not gonna be expensive since you are doing it just for the one element there are many many ways to approach this but ngif is the simpliest if supermashers way does not suit you that is,['jquery'] +450027,mysql create stored procedure syntax with delimiter i am trying to create a stored procedure in mysql using a delimiter like thisuse amdelimiter create procedure addfieldsbegin declare done int default false declare acc int16 declare validid int default 0end delimiter it gives me an error1304 procedure addfields already existswhat is the proper syntax for making a stored procedure with a delimiter and dropping it if it exists first,"['mysql', 'sql']" +450060,what is 206 partial content img srcimgpngi have some images on the site like above when i try to load them they are loading only half when i checked the requests in console i see that the response is 206 partial contenti googled it and it says that if there is a range set in header it will be like this but where does these headers actually set and how to avoid this and load full images,['html'] +450068,call method only if it exists is there some hidden rubyrailsmagic for simply calling a method only if it existslets say i want to callresourcephone numberbut i do not know beforehand if resource responds to phone number a way to do this isresourcephone number if resourcerespond to phone numberthat is not all that pretty if used in the wrong place i am curious if something exists that works more along the lines of how try is used resourcetryphone number,"['ruby-on-rails', 'ruby']" +450108,framework and database adapter with hexagonal architecture and dci pattern i try to design a web based application in ruby i have developed a simple core application implementing dci paradigm in hexagonal architecture without framework and database there are small hexagons in core hexagon and adapters such as web database logs etc every hexagons run itself without database and framework how can i provide relation with database models and entity classes as independent with database in this approach i want to change framework from rails to sinatra in future or database in fact how can i implement database adapter or framework adapter that is exactly isolated rails and mongodb in this core hexagon any ideas,"['ruby-on-rails', 'ruby']" +450118,purpose of the outer extra parenthese on javascript closure function what is the purpose of the outer extra parentheses on the below javascript closure function i have been told in other posts that they are not strictly necessary but they are a convention to make it clear that the result of the function is being passed not the function itself the below quote from however conflicts which is correctnotice the around the anonymous function this is required by the language since statements that begin with the token function are always considered to be function declarations including creates a function expression insteadfunction all vars and functions are in this scope only still maintains access to all globals,['javascript'] +450156,what is the difference between float pointer and int pointer address i tried to run this codeint pfloat qq 66p qthough it will be a warning but i think q and p are of same size so p can have an address of q but when i print q and p i am getting different outputthis is my outputp 660 q 0 p 0x40d3 q 0x7fe2fa3c8c what is that i am missingand p and q is same when both pointer and variable type is samemy complete code isincludestdiohvoid main int p float q q 66 p q printfp f and q f p p q p npqpq,['c'] +450165,java iterator for primitive types i have a java class of the following formclass example private byte data public exampleint s data new bytess public byte getterint x int y return bytexy public void setterint x int y byte z bytexy z i would like to be able to externally iterate over the private data using an iterator like so forbyte b example do stuff i tried to implement a private iterator class but i ran into problemsprivate class exampleiterator implements iterator private int curr x private int curr y public exampleiterator curr x0 curr y1 public boolean hasnext return curr x fieldlength1 curr y fieldlength1 is not the last cell public byte next error is here wants to change return type to object would not compile ifcurr yfieldlength curr x curr y0 return fieldcurr xcurr y public void remove does nothinghow would i implement an external iterator for primitive types not generics is this possible in java,['java'] +450173,how important is it to use a variable for datetimetoday when concerned about performance i just saw this upvoted commentiirc datetimetoday is a quite expensive call so you better store the value in a variable firstit was in response to a post that contained the codevar first new datetimedatetimetodayyear datetimetodaymonth 1addmonths1var last new datetimedatetimetodayyear datetimetodaymonth 1adays1if i am looking to improve performance how important is it to store datetimetoday in a variable instead of calling it multiple times and roughly how many uses of datetimetoday would justify creating a variable for itedit i realize i should test my program to see if there are performance problems first before worrying about something as trivial as this for the sake of this question assume that i have already done this and determined that additional optimization is needed,['c#'] +450242,what causes a java library to behave differently when called by jruby i am new to the java world but am familiar with ruby i am trying to write a program that interacts with some thirdparty jar fileswhile the libraries seem to behave fine if called from java they behave incorrectly when i call them in jruby this is a problem because i would really like to use jruby for example the two programs below try to do exactly the same thing but they produce different outputthis java program behaves correctlyi developed the java program below in netbeans and ran it by pressing f6 run main project the libraries folder for the project is set to cprogram files x86microchipmplabxmplab idelibnblibrariesproperties when i run it it prints pins 17package pinbug1 import commicrochipmplabmdbcoreassembliesassemblyimport commicrochipmplabmdbcoreassembliesassemblyfactoryimport commicrochipmplabmdbcoresimulatorpinsetimport commicrochipmplabmdbcoresimulatorsimulatorimport orgopenideutillookuppublic class pinbug1 public static void mainstring args assemblyfactory assemblyfactory lookupgetdefaultlookupassemblyfactoryclass assembly assembly assemblyfactorycreatepic18f14k50 simulator simulator assemblygetlookuplookupsimulatorclass int num simulatorgetdatastoregetprocessorgetpinsetgetnumpins systemoutprintlnpins num prints pins 17 this jruby program behaves incorrectlyi ran the jruby program below by just typing jruby bug reproducerb and it printed pins 0 i would expect it to print pins 17 like the java programmplab idemdbcoremodulesjar mplab idemplablibsmodulesjar mplab idemplablibsmodulesextjar mplab ideplatformliborgopenideutiljar mplab idemdbcoremodulesextorgopenidefilesystemsjareach do pattern dirglobcprogram files x86microchipmplabx patterneach do x require x endendassemblyfactory orgopenideutillookupgetdefaultlookupcommicrochipmplabmdbcoreassembliesassemblyfactoryjava classassembly assemblyfactorycreatepic18f14k50simulator assemblygetlookuplookupcommicrochipmplabmdbcoresimulatorsimulatorjava classnum simulatorgetdatastoregetprocessorgetpinsetgetnumpinsputs pins num pins 0more detailsthere are about 80 thirdparty jar files they are provided by microchip as part of mplab x and implement a simulator for their microcontrollers the jar files come with mplab x and i also downloaded the mplab x sdk to get help with using them i am using lots of undocumented features of the libraries but i do not see any alternativei am using windows 7 64bit sp1 i have the following javarelated things installed and listed under programs and featuresjava 7 update 17java 7 update 17 64bitjava se development kit 7 update 17 64bitjavatm 6 update 22 64bitjavatm 6 update 29javatm se development kit 6 update 22 64bitjruby 173intellij idea community edition 1204netbeans ide 73mplab x ide v170i used systemgetpropertyjavaversion to verify that both of my programs are running under java 160 22 that is good because i followed the instructions in the mplab x sdk that say for best results use the exact same jdk that built the idemdbcore your code will be talking to for mplab x v170 this is jdk 6u22 from oracle i only installed jdk 7u17 after i encountered this problem and it did not make a differencei was able to find a workaround to the specific problem identified in the examples but then i continued my development and ran into another problem where the libraries behaved differently this makes me think that i am doing something fundamentally wrong in the way i use jrubythinking that a differing class path might cause this problem i tried getting the java program to print out its class path and then edited my jruby program to require precisely the files in that list but it made no differencequestionsdo you know of anything that might cause code in jar files to behave differently when called from jruby instead of javawhat version of the jdk does jruby 173 use or does that question even make senseupdate solvedthanks to d3mon1stvfw for actually getting mplab x and solving my problem for me for those who are interested in the nitty gritty details the number of pins was 0 because the pins are lazy loaded when they are accessed with pinsetgetpinstring normally all pins would have been loaded because the peripherals load them but under jruby no peripherals were detected this is because the periphal document could not be found this is because perdocumentlocatorfinddocs returned an empty list perdocumentlocator failed because commicrochipmplabopenutilpathretrievalpathretrievalgetpathcommicrochipmplablibsmplabdocumentlocatormplabdocumentlocatorclass was returning the wrong thingconsider the following code which is similar to what is happening inside pathretrievalgetpath except there it was written in javacommicrochipmplablibsmplabdocumentlocatormplabdocumentlocatorjava classresourcemplabdocumentlocatorclassgetfileif i follow d3mon1stvfws tip and add jar files to the classpath then that code returnsfilecprogram files x86microchipmplabxmplab idemplablibsmodulescommi crochipmplablibsmplabdocumentlocatorjarcommicrochipmplablibsmplabdocum entlocatormplabdocumentlocatorclasshowever if i do not add things to the class path then that code strangely returnsfilec5cprogram20files20x865cmicrochip5cmplabx5cmplab ide5cmplablibs 5cmodules5ccommicrochipmplablibsmplabdocumentlocatorjarcommicrochipmpl ablibsmplabdocumentlocatormplabdocumentlocatorclassthe 5c is actually the code for a backslash the microchip code in pathretrievalgetpath does a lot of string manipulation and does not properly handle the case where slashes are represented by 5c if anyone has any further insight about why the 5cs are appearing i would be interested to know but my problem is solvedconclusion sometimes javas getresource returns a url with 5c instead of slashes in it and this is affected by what is on the classpath if you want to be safe add the jar file to classpath before requiring it like thisrequire javaclasspath jar filenamerequire jar filename,"['java', 'ruby']" +450287,continuous integration ensure new commits are covered with tests i am working on a project that has a lot of legacy code that is not covered with tests is there any way that i could set up the integration server to check that all new commits have a minimum amount of tests say coverage is 70essentially i see two optionssomehow set up the ci server to fail the build when the committed changes are not covered with unit tests this will ensure that every piece of new code will have tests and that tests for the legacy code will increase with each changeset a coverage threshold for the whole project and fail the build if the coverage percentage decreases after a commit the problem with this is that if i delete a class containing 100 instructions and add a new class with 50 instructions the coverage percentage will go up without me writing any testsi like option 1 more because it forces changes in legacy code to be unit tested this should increase the overall test coverageright now were using jenkins as our ci server and jacoco for test coverage maven is used for building the project and svn is our main source control,['java'] +450362,random object per page request with silverstripe lets say you show a random statement per page request and use a function to return a random object likestatementgetsortrandlimit1but now in the template you want to reference it twice in different places but it should be the same statement and not a randomly different one how would you make sure to get the same random object per page request,['php'] +450369,differences between iequatable iequalitycomparer and overriding equals when using linq on a custom object collection i am having some difficulty using linqs except method when comparing two collections of a custom objecti have derived my class from object and implemented overrides for equals gethashcode and the operators and i have also created a compareto methodin my two collections as a debugging experiment i took the first item from each list which is a duplicate and compared them as followsitemlista0equalsitemlistb0 trueitemlista0 itemlistb0 trueitemlista0comparetoitemlistb0 0in all three cases the result is as i wanted however when i use linqs except method the duplicate items are not removedlistmyobject newlist itemlistaexceptitemlistbtolistlearning about how linq does comparisons i have thiscovered various conflicting methods that say i need to inherit from iequatablet or iequalitycomparert etci am confused because when i inherit from for example iequatablet i am required to provide a new equals method with a different signature from what i have already overridden do i need to have two such methods with different signatures or should i no longer derive my class from objectmy object definition simplified looks like thispublic class myobject object public string name get set public datetime lastupdate get set public int comparetomyobject other public override bool equalsobject obj allows some tolerance on lastupdate public override int gethashcode unchecked int hash 17 hash hash 23 namegethashcode hash hash 23 lastupdategethashcode return hash overrides for operatorsi noticed that when i inherit from iequatablet i can do so using iequatablemyobject or iequatableobject the requirements for the equals signature change when i use one or the other what is the recommended waywhat i am trying to accomplishi want to be able to use linq thistinctexcept as well as the standard equality operators and without duplicating code the comparison should allow two objects to be considered equal if their name is identical and the lastupdate property is within a number of seconds userspecified toleranceeditshowing gethashcode code,['c#'] +450391,show div on scrolldown after 800px i want to show a hidden div when scrolling down after 800px from the top of the page by now i have this example but i guess it needs modification in order to achive what i am looking foreditand when scrollup and the height is less the 800px this div should hidehtmldiv classbottommenu content divcssbottommenu width 100 height 60px bordertop 1px solid 0 position fixed bottom 0px zindex 100 opacity 0jquerydocumentreadyfunction windowscroll function bottommenueach functioni var bottom of object thispositiontop thisouterheight var bottom of window windowscrolltop windowheight if bottom of window bottom of object thisanimateopacity1500 here is a fiddle of my current code,"['jquery', 'html', 'css']" +450394,open with o creat was it opened or created i have 10 processes which try open the same file more or less at the same time using openo creat call then delete it is there any robust way to find out which process actually did create the file and which did open already create file for instance if i want to accurately count how many times that file was opened in such scenarioi guess i could put a global mutex on file open operation and do a sequence of open calls using o creat and o excl flags but that does not fit my definition of robust,['c'] +450407,best way to store large amount of data of users i store files of users in their own name directory something like usernamefile01jpgusernamefile02mp4usernamefile03mp3but if more users come and upload more files then this creates problem because this will lead to migration of some or many users to another drivei choose username directory solution first because i dont want filenames to be mixed i dont want to change filename too also if another user upload same filename then it creates problem if the files are stored with original namewhat could be the best way to do this i have one solution but want to ask community is this the best way i will use sequential folders and then hash the file name to some thing very unique and store into the directory what i will do is store the original name of file and username into database and hashvalue of filename which is stored in thiskwhen anyone want to access that filei will read that file through php either replace the name or will do something at that point so that the file is downloaded as original filenamei have only this proposed solution in mind do you guys have any other better than this oneediti use folder system too and possibly for 2nd way i will use virtual foldersmy database is mongodbguys all your answers were awesome and really helpful i wanted to give bounty to everyone thats why i left it so that community can provide automatically thanks all for your answersi really appreciate it,['php'] +450437,is there a linked hash set in c java has a linkedhashset which is a set with a predictable iteration order what is the closest available data structure in ccurrently i am duplicating my data by using both a set and a vector i insert my data into the set if the data inserted successfully meaning data was not already present in the set then i push back into the vector when i iterate through the data i use the vector,['c++'] +450451,add unique constraint to combination of two columns i have a table and somehow the same person got into my person table twice right now the primary key is just an autonumber but there are two other fields that exist that i want to force to be uniquefor example the fields areid name active personnumber i only want 1 record with a unique personnumber and active 1so the combination of the two fields needs to be uniquewhat is the best way on an existing table in sql server i can make it so if anyone else does an insert with the same value as an existing value it fails so i do not have to worry about this in my application code,['sql'] +450473,is it possible to make a 9patch drawable for a callout graphic i am trying to make a callout graphic in android i am not married to the idea of using a 9patchdrawable but i think it is the right way to go i am essentially trying to make a button with a little nub at the bottom i would like the nub to be centered regardless of the size of the content here are some example graphics showing what look i am going foris there a way to keep the bottom little nub centered using a 9patch drawable,['android'] +450481,vertically aligning single line text within a minimum height div i have a certain class of div that contains an icon in the upperleft corner as the background image and text in the remainder of the div the div has a minimum height of 32px so that all of the icon is shownwhen there is multiple lines of text the lines look fine as they stretch the div down longer than the minimum height but when there is only one line it is not vertically aligned with the centre of the iconjsfiddle hereis there any way to get the single line to vertically align but not mess it up when there are multiple linestest backgroundcolor 98c5ff color 093d80 width 400px minheight 32px backgroundimage url backgroundrepeat norepeat paddingleft 42pxdiv classtestpshort messagepdivhr div classtestprather long message that should hopefully wrap on to a second line at some pointpdivhr div classtestpmessagebr withbr manybr linesbr pdiv,"['html', 'css']" +450482,inherit constructors from template base class without repeating template arguments how do i inherit constructors from a template base class without repeating the template arguments and without using macrosfor example this does not work using gcc 48template typename tstruct base template typename ustruct derived baseu using basebaseit does work if i repeat the template arguments of the base classtemplate typename tstruct base template typename ustruct derived baseu using baseubasethe problem is that u might be something very complex and that is annoying and error prone to repeat for example here is one of my original motivating examplesinclude boostmulti index containerhppinclude boostmulti indexkey extractorshppinclude boostmulti indexordered indexhppinclude boostmulti indexsequenced indexhppusing namespace boostmulti indexstruct as list tag struct as set tag template typename tstruct unique list multi index container t indexed by sequencedtagas list tag ordered uniquetagas set tag identityt using multi index container t indexed by sequencedtagas list tag ordered uniquetagas set tag identityt multi index container using as list as list tag using as set as set tag i ended up working around this by using a macrodefine make unique listtemplate paramstemplate typename tstruct unique list multi index container template params using multi index container template params multi index container using as list as list tag using as set as set tag make unique list t indexed by sequencedtagas list tag ordered uniquetagas set tag identityt undef make unique listis there a better way to approach this some syntax trick i am missing,['c++'] +450508,java initialize subclass from superclass public class base long list of attributes no constructor using fields no init methode i cannot change this classnow i extended the base class likepublic class subclass extends base private boolean selected getter und setter i become a list of base object listbase but i need the same list but as listsubclassis there a way to initialize the subclass from the base classexampleforbase b list subclass sub subclassb thats wrong i know if subsetselectedtrue newlistaddsubi try to avoid the manual init of each attribute of the base class to the subclassi update my question as requested in the commentsthe design above is just an example my questin exactly iswhy converting baseclass into subclass sence subclass extends baseclass is not possible why java dosnt allow me to do the followingexampleclass base private string nameclass subclass extends base private string titlethenbase b dbcontrollergetbyidsubclass sub subclassb after that the object sub should have the attribute name from the object band the title attribute is nullwhy is this not the case in javasorry for my bad englishthanks,['java'] +450536,filewrite bufferedwriter and printwriter combined ok so i am learning about io and i found the following code in one of the slides can someone please explain why there is a need to have a filewrite bufferedwriter and printwriter i know bufferedwriter is to buffer the output and put it all at once but why would they use filewriter and printwriter dont they pretty much do the same with a bit of difference in error handling etc and also why do they pass bw to printwriter filewriter fw new filewriter file bufferedwriter bw new bufferedwriter fw printwriter outfile new printwriter bw,['java'] +450564,oracle alternative for mysql replace into in mysql we usereplace intoto insert if a row does not exist and to update if it existsis there a corresponding command in oracle,['mysql'] +450573,unnecessary casting to object used for calling tostring in mscorlib in stringwriter mscorlibdll i found a codeprivate stringbuilder sb public override string tostring return object this sbtostring i do not see reason for that so is my r but it is sometimes wrong tostring is virtual so the casting does not change behaviour what kind of optimization is being done here,['c#'] +450576,jquery change event callback how to call a function once after change event completefor example something like this i know jquery does not have callback method as default elementchange function do something on change milestonesselectmultiselect minwidth 120 height 200px selectedlist 4 multiselectfilter some animation calls function do something after complete alertanother codes has completed when i called is it possible to call a single callback after all the codes on change method done except call a complete callback for every functions on iti need to do something after the change event has completedshall i need to set order to methods in change handler,"['javascript', 'jquery']" +450587,require old password to make new password right now every time i change anything in useredit the form requires the user to set a new password i would like for it to require the current password how can i ask for current password only incase a new password is entered how can i achieve this thanks a lot for this form foruser html multipart true do f render sharederror messages object fobject ftext field name placeholder name ftext field email placeholder email fpassword field password placeholder enter new password fpassword field password confirmation placeholder confirm new password fsubmit save changes class btn btnlarge btnprimary end,['ruby-on-rails'] +450596,how to print an exception using logger i have a situation in which i want to print all the exception caught in catch block using logger try file file new filecclassnamemkdir fh new filehandlercclassnameclassnamelog loggeraddhandlerfh loggersetuseparenthandlersfalse simpleformatter formatter new simpleformatter fhsetformatterformatter catch exception e loggerinfoe i got the error logger cannot be applied to javaioexceptionmy concern is if i do so many thing in try block and i keep only one catch block as catchexception e then is there any way using logger that print any kind of exception caught in catch block note we are using javautillogginglogger apikindly guide me thanks in advance,['java'] +450605,how to change format of a column of excel sheet in c i am creating an excel sheet dynamically and inserting values in to the samebut value in some cells are getting inserted in the wrong formatfollowing is my excel sheet value in the selected cell should have been 029343 but it is inserted as feb43this due to some wrong format for that columncolumnd in the excel sheeti need to change the whole columnd all cells comming under heading d data2 to text format before entering the data following is the code for creating the excel sheet and inserting data excel new application excelvisible false wb workbookexcelworkbooksaddsystemreflectionmissingvalue sheet wbsheetsadd sheetname testsheet1 sheetcells1 avalue2 id sheetcells1 bvalue2 name sheetcells1 cvalue2 data1 sheetcells1 dvalue2 data2 sheetcells1 evalue2 data3 for int i 0 i 10 i id i result object data jsonconvertdeserializeobjectresult name data null dataname stringempty data1 data null datadata1 stringempty data2 data null datadata2 stringempty data3 data null datadata3 stringempty sheetcellsi 2 avalue2 name sheetcellsi 2 bvalue2 data1 sheetcellsi 2 cvalue2 data2 sheetcellsi 2 dvalue2 data3 string excelpath some path wbsaveasexcelpathxlfileformatxlworkbooknormal null null false false xlsaveasaccessmodexlshared false false null null null wbclosetrue excelquitnow before the loop i need to change the format of cells under columnd to text formathow to do the same from code in c,"['c#', 'asp.net']" +450631,how to add two view controllers in uipageviewcontroller i m using uipageviewcontroller on ipad where i need to show a firstviewcontroller in the first page and contentviewcontroller in the next page in landscapeif i set the nsarray with two viewcontrollers the app is crashes at selfpagviewcontroller setviewcontroller with the following exceptionthe number of provided view controllers 2 does not match the number required 1 for the requested spine location uipageviewcontrollerspinelocationminbelow is the codepragma mark uipageviewcontrollerdatasource methods uiviewcontroller pageviewcontrolleruipageviewcontroller pageviewcontroller viewcontrollerbeforeviewcontrolleruiviewcontroller viewcontroller nsuinteger currentindex selfmodelarray indexofobjectcontentviewcontroller viewcontroller textcontents ifcurrentindex 0 return nil contentviewcontroller contentviewcontroller contentviewcontroller alloc init contentviewcontrollertextcontents selfmodelarray objectatindexcurrentindex 1 return contentviewcontroller uiviewcontroller pageviewcontrolleruipageviewcontroller pageviewcontroller viewcontrollerafterviewcontrolleruiviewcontroller viewcontroller nsuinteger currentindex selfmodelarray indexofobjectcontentviewcontroller viewcontroller textcontents ifcurrentindex selfmodelarraycount1 return nil contentviewcontroller contentviewcontroller contentviewcontroller alloc init contentviewcontrollertextcontents selfmodelarray objectatindexcurrentindex 1 return contentviewcontrollerpragma mark uipageviewcontrollerdelegate methods uipageviewcontrollerspinelocationpageviewcontrolleruipageviewcontroller pageviewcontroller spinelocationforinterfaceorientationuiinterfaceorientationorientation ifuiinterfaceorientationisportraitorientation set the array with only 1 view controller uiviewcontroller currentviewcontroller selfpageviewcontrollerviewcontrollers objectatindex0 nsarray viewcontrollers nsarray arraywithobjectcurrentviewcontroller selfpageviewcontroller setviewcontrollersviewcontrollers directionuipageviewcontrollernavigationdirectionforward animatedyes completionnull important set the doublesided property to no selfpageviewcontrollerdoublesided no return the spine location return uipageviewcontrollerspinelocationmin else nsarray viewcontrollers nil contentviewcontroller currentviewcontroller selfpageviewcontrollerviewcontrollers objectatindex0 nsuinteger currentindex selfmodelarray indexofobjectcontentviewcontroller currentviewcontroller textcontents ifcurrentindex 0 currentindex 2 0 uiviewcontroller nextviewcontroller self pageviewcontrollerselfpageviewcontroller viewcontrollerafterviewcontrollercurrentviewcontroller viewcontrollers nsarray arraywithobjectscurrentviewcontroller nextviewcontroller nil else uiviewcontroller previousviewcontroller self pageviewcontrollerselfpageviewcontroller viewcontrollerbeforeviewcontrollercurrentviewcontroller viewcontrollers nsarray arraywithobjectspreviousviewcontroller currentviewcontroller nil now set the viewcontrollers property of uipageviewcontroller selfpageviewcontroller setviewcontrollersviewcontrollers directionuipageviewcontrollernavigationdirectionforward animatedyes completionnull return uipageviewcontrollerspinelocationmid voidviewdidload super viewdidload appdelegate appdelegate uiapplication sharedapplication delegate instantiate the model array selfmodelarray nsmutablearray alloc init selfvcs nsmutablearray allocinit for int index 1 index 2 index selfmodelarray addobjectnsstring stringwithformatpage dindex step 1 instantiate the uipageviewcontroller selfpageviewcontroller uipageviewcontroller alloc initwithtransitionstyleuipageviewcontrollertransitionstylepagecurl navigationorientationuipageviewcontrollernavigationorientationhorizontal optionsnil step 2 assign the delegate and datasource as self selfpageviewcontrollerdelegate self selfpageviewcontrollerdatasource self step 3 set the initial view controllers appdelegatecontentviewcontrollertextcontents selfmodelarray objectatindex0 nsarray viewcontrollers nsarray arraywithobjectsappdelegatefirstviewcontrollerappdelegatecontentviewcontrollernil selfpageviewcontroller setviewcontrollersviewcontrollers directionuipageviewcontrollernavigationdirectionforward animatedno completionnil step 4 viewcontroller containment steps add the pageviewcontroller as the childviewcontroller self addchildviewcontrollerselfpageviewcontroller add the view of the pageviewcontroller to the current view selfview addsubviewselfpageviewcontrollerview call didmovetoparentviewcontroller of the childviewcontroller the uipageviewcontroller instance in our case selfpageviewcontroller didmovetoparentviewcontrollerself step 5 set the pageviewcontrollers frame as an inset rect cgrect pageviewrect selfviewbounds pageviewrect cgrectinsetpageviewrect 400 400 selfpageviewcontrollerviewframe pageviewrect step 6 assign the gesturerecognizers property of our pageviewcontroller to our views gesturerecognizers property selfviewgesturerecognizers selfpageviewcontrollergesturerecognizers,"['ios', 'objective-c']" +450637,how to integrate payment gateway feature in android how to integrate payment gateway feature in android app i have made a shopping cart app in which now i want to add payment gateway feature please suggest me the best way to allow user to do paymentsshould i need to use some readymade classes or need to import any payment sdk,['android'] +450672,where to find design patterns best practices for eclipse plugin development our team is developing a eclipse based ide typically a plugins currently we are progressing good but i feel somehow we are feeling smell of bad practices in code example i can give here is eventlisteners consider we have button named button1 and in the same java file just below the button we are adding selection listener to it likebutton1addselectionlistenernew selectionlistener remaining code herewhich i feel is completly bad idea and my question is there any design pattern best practices etc available for eclipse plugin development or do you have any small tipssuggestions for the same i know there are books available like code complete 2 etc etc but i need bit suggestions respect to eclipse plugin development i tried in google and did not get much good informations regarding same i got this ibms article but i feel it is not very useful any suggestions or tip is appreciatednote please let me know if it is not appropriate here or is it good for anyother stackexchange networks like programmers i can move it there,['java'] +450715,javascript ordinal suffix for numbers with specific css class i am trying to thisplay numbers within a particular table with ordinal suffixes the table always shows three numbers which come from an xml file the numbers show ranks so for example they may be 6th 120th 131st the output is a table that would look like thistable tr td classordinal6td td classordinal120td td classordinal131td trtablei would ideally like to use javascript and i found a few very good solutions on stackoverflow for example this one however i am struggling to apply the function to all numbers within the table rather than putting in each number individually i tried using a css class so that my function looks like thisscript typetextjavascriptfunction ordinaleachfunction var j i 10 if j 1 i 11 return i st if j 2 i 12 return i nd if j 3 i 13 return i rd return i th scriptbut it is not working probably because i screwed up the code somewhere maybe somebody here can help me out and tell me where i went wrong thank you very much for your help,"['javascript', 'jquery']" +450730,unordered map with custom hashingequal functions functions do not get called this is weird the following code which i managed to compile thanks to cassio neri is compiling without any error by the way either hashing func nor key equal func do get called the couts are not showing in the console windowinclude iostreaminclude stringinclude unordered mapinclude algorithminclude functionalusing namespace stdunsigned long hashing funcstring key cout hashing called unsigned long hash 0 forint i0 ikeysize i hash 71hash keyi 5 return hashtemplateclass t bool key equal fnt t1 t t2 return t1 t2template bool key equal fnstringstring t1 string t2 cout equal called return t1comparet2int main unordered mapstring stringsize type and 5 unordered mapstring string mymapn const stdhashstring hashing func const stdequal tostring functionboolstringstringkey equal fnstring bool case insensitive mymapkey eqtesttest mymappaul jenna mymapfrank ashley ifmymappaul mymapfrank cout equal endl return 0i am using msvc2012 any hint on what could be the problem,['c++'] +450785,searching for gray log 2 api or a way to query elasticsearch i have a question regarding gray log 2 in the company i work for all systems report exceptions to gray log server which has predefined streamsi need to build an external dashboard which retrieves data from different streamsi have not found any gray log 2 api to use for this i read that there is a possibility to query elastic search directly can you please advise how do i do so or if there is any gray log 2 apimy dashboard will be written or in jsf or in net still not sure about which is best to usei would be very grateful for detailed answer on this question links will help too,"['java', '.net']" +450791,should i use enum static class dictionary or struct to represent these labeled floats in c i have a constant data structure that represents the relative height of each human vertebra normalized in relation to total spine height this is derived from anthropometric studies etci have implemented it in python as a tuple of tuples each tuple containing a stringname and doublevalue like thisvertebral heights c7 0t1 00391914t2 00785479t3 01183993t4 01590759t5 02009076t6 02442244t7 02893564t8 03366337t9 03863861t10 04389439t11 04946370t12 05537954l1 06167492l2 06838284l3 07553630l4 08316832l5 09131188s1 10my first thought was to create a dictionary but that would need a class to be used as a container then the idea of an enum came to mind but i have read enums are for ints and i have doubles then there are class and struct but to this point i am utterly confused and i believe my current understanding of the best practices of doing this stuff in c is not enough yetmy intended use is to have a map between the application model the numeric part of the elements and the user model the named domainrelated part of the elementsany suggestion,['c#'] +450818,typejuggling and strict greaterlesserthan comparisons in php php is famous for its typejuggling i must admit it puzzles me and i am having a hard time to find out basic logicalfundamental things in comparisonsfor example if a b is true and b c is true must it mean that a c is always true toofollowing basic logic i would say yes however i am that puzzled i do not really trust php in this maybe someone can provide an example where this is not the casealso i am wondering with the strict lesserthan and strict greaterthan operators as their meaning is described as strictly which i only knew in the past from the equality comparisons if it makes any difference if left and right operands are swapped with strictly unequal values preconditionif a b throw new exception both are strictly equal can not compare strictly for greater or smaller a b b afor most of all type comparison combinations these greater lesser comparison operators are not documented so reading the manual was not really helpful in this case,['php'] +450833,detect history back using angular is it possible to detect that a user entered a page through using the history back button in his browser preferably i want to detect this action using angularjsi do not want to use angular routing it should also work if a user submits a form and after a successful submit to the server and a redirect it should also be possible if the user goes back to the form using the back button of the browser,"['javascript', 'jquery']" +450844,how to pass complex object to aspnet webapi get from jquery ajax call i have the following complex object in javascript which contains filter optionsvar filtercaseidentifitergft1userid2which i want to pass to an aspnet mvc4 webapi controller gethttpgetpublic ienumerablejhsrepositoryviewmodelscaselist getfrombodyrepositoryinputmodelscaselistfilter filter try return caselistfilter catch exception exc handle exception here return null using an jquery ajax callvar request ajax url type get data jsonstringifyfilter contenttype applicationjson charsetutf8 cache false datatype jsonthe filter object in the aspnet controller method is null if i change it to a post the filter object is passed correctly is there a way to pass a complex object to a geti do not want to separate out the parameters to the url as there will be a number of them which would make it inefficient it would be hard to have optional parameters and this way the method signature stays constant even if new parameters are added,['c#'] +450853,handling unhandled exception in gui i am mostly writing a small tools for tech savvy people eg programmers engineers etc as those tools are usually quick hacks improved over time i know that there are going to be unhandled exceptions and the users are not going to mind i would like the user to be able to send me the traceback so i can examine what happened and possibly improve the applicationi usually do wxpython programming but i have done some java recently i have hooked up the taskdialog class to the threaduncaughtexceptionhandler and i am quite happy with the result especially that it can catch and handle exceptions from any threadi was doing something similar in wxpython for a long time howeveri had to write a decoratorhack to be able to print exceptions from another thread welleven when functional the result is quite uglyhere is the code for both java and wxpython so you can see what i have donejavaimport javaawteventqueueimport javaxswingjframeimport javaxswinguimanagerimport javaxswingunsupportedlookandfeelexceptionimport javaxswingjbuttonimport javaawtgridbaglayoutimport javaawtgridbagconstraintsimport javaawteventactionlistenerimport javaawteventactioneventimport comezwaredialogtasktaskdialogspublic class swingexceptiontest private jframe frame public static void mainstring args try uimanagersetlookandfeeluimanagergetsystemlookandfeelclassname catch classnotfoundexception e catch instantiationexception e catch illegalaccessexception e catch unsupportedlookandfeelexception e threadsetdefaultuncaughtexceptionhandlernew threaduncaughtexceptionhandler public void uncaughtexceptionthread t throwable e taskdialogsshowexceptione eventqueueinvokelaternew runnable public void run try swingexceptiontest window new swingexceptiontest windowframesetvisibletrue catch exception e eprintstacktrace public swingexceptiontest initialize private void initialize frame new jframe framesetbounds100 100 600 400 framesetdefaultcloseoperationjframeexit on close gridbaglayout gridbaglayout new gridbaglayout gridbaglayoutcolumnwidths new int0 0 gridbaglayoutrowheights new int0 0 gridbaglayoutcolumnweights new double00 doublemin value gridbaglayoutrowweights new double00 doublemin value framegetcontentpanesetlayoutgridbaglayout jbutton btnnewbutton new jbuttonthrow btnnewbuttonaddactionlistenernew actionlistener public void actionperformedactionevent arg0 onbutton gridbagconstraints gbc btnnewbutton new gridbagconstraints gbc btnnewbuttongridx 0 gbc btnnewbuttongridy 0 framegetcontentpaneaddbtnnewbutton gbc btnnewbutton protected void onbutton thread worker new thread public void run throw new runtimeexceptionexception workerstart wxpythonimport stringioimport sysimport tracebackimport wxfrom wxlibdelayedresult import startworkerdef thread guardf def thread guard wrapperargs kwargs try r fargs kwargs return r except exception exc sysexc info output stringiostringio tracebackprint exceptionexc0 exc1 exc2 fileoutput raise exceptionthread guardnn outputgetvalue return thread guard wrapperthread guarddef thread func return 1 0def thread doneresult r resultget print rclass mainwindowwxframe def init self args kwargs wxframe init self args kwargs selfpanel wxpanelself selfbutton wxbuttonselfpanel labelthrow selfbuttonbindwxevt button selfonbutton selfsizer wxboxsizer selfsizeraddselfbutton selfpanelsetsizerandfitselfsizer selfshow def onbuttonself e startworkerthread done thread funcapp wxapptruewin mainwindownone size600 400appmainloopnow the questioncan i do easily something similar to java solution in wxpython or maybe is there a better way in either java or wxpython,"['java', 'python']" +450876,convert short array to string c is it possible to convert short array to string then show the textshort a new short 0x33 0x65 0x66 0xe62 0xe63there are utf16 thai characters contains in the array how can it output and show the thai and english wordsthank you,['c#'] +450883,is there already preexisting code for supporting dojo amd nodejs require and browser windowsomething for a javascript micro library i have some code which supports writing a microlibrary and having it loaded in dojo amd nodejs require and the browsers normal windowsomething but i was wondering if there are already established means of doing this and i just reinvented the wheel or if the code is worth while i did do a good search around the internetthe code i created is at if people have comments great but i am much more interested in finding out if there is a proper method of doing this,['javascript'] +450909,angularjs select box options thisappear when an item is selected i have created a select box bound to a model using angularjsthe select box options load correctly but as soon as select any single option all options thisappear from the select box what is the reason this is occuring and how do i keep my options from thisappearingplunker link demonstrating the issuehtmlhtml xmlns ngapp head titleangular test prjoect hometitle script typetextjavascript srcscript script typetextjavascript srcclinicjsscript head body div ngcontrollerclinicctrl select ngoptionsitem as itemstart itemend itempatientname for item in appointments ngmodelappointments select div bodyhtmljavascriptfunction clinicctrlscope scopeappointments start 900 end 930 provider 1 patient nameallendob8121977 start 10 end 1045 provider 1 patient name allen dob 8121971 start 1030 end 1100 provider 2 patient name david dob 11221973 start 1100 end 1145 provider 2 patient name francine dob 3181987 start 1230 end 1530 provider 3 patient name george dob 451997 start 1300 end 1500 provider 3 patient name kirkman dob 6281970,['javascript'] +450942,subprocess and type str doesnt support the buffer api i havecmd subprocesspopendirshelltruestdoutsubprocesspipefor line in cmdstdout columns linesplit print columns3have error in line 3 type str doesnt support the buffer apiwhat am i doing wrong i am on python 33,['python'] +450975,java bitwise operation i have this line of codeint b1 0xf content128 0xff content11i have a bytearray content in little endian and need to recreate a 2 byte value this code does the job just fine but prior to testing i had it written like thisint b1 0xf content128 content11and the result was not right my question is why is 0xff necessary in this scenario,['java'] +450983,pandas dataframe concat vs append i have a list of 4 pandas dataframe containing a day of tick data that i want to merge into a single data frame i find cannot seem to understand the behavior of concat on my timestamps see details belowdataclass pandascoreframedataframedatetimeindex 35228 entries 20130328 070890200 to 20130328 1859203570200data columnsprice 4040 nonnull valuesvolume 4040 nonnull valuesbidqty 35228 nonnull valuesbidprice 35228 nonnull valuesaskprice 35228 nonnull valuesaskqty 35228 nonnull valuesdtypes float646class pandascoreframedataframedatetimeindex 33088 entries 20130401 03170470200 to 20130401 1859581750200data columnsprice 3969 nonnull valuesvolume 3969 nonnull valuesbidqty 33088 nonnull valuesbidprice 33088 nonnull valuesaskprice 33088 nonnull valuesaskqty 33088 nonnull valuesdtypes float646class pandascoreframedataframedatetimeindex 50740 entries 20130402 0327470200 to 20130402 1859581720200data columnsprice 7326 nonnull valuesvolume 7326 nonnull valuesbidqty 50740 nonnull valuesbidprice 50740 nonnull valuesaskprice 50740 nonnull valuesaskqty 50740 nonnull valuesdtypes float646class pandascoreframedataframedatetimeindex 60799 entries 20130403 03069940200 to 20130403 185958180200data columnsprice 8258 nonnull valuesvolume 8258 nonnull valuesbidqty 60799 nonnull valuesbidprice 60799 nonnull valuesaskprice 60799 nonnull valuesaskqty 60799 nonnull valuesdtypes float646using append i getpddataframeappenddataclass pandascoreframedataframedatetimeindex 179855 entries 20130328 070890200 to 20130403 185958180200data columnsaskprice 179855 nonnull valuesaskqty 179855 nonnull valuesbidprice 179855 nonnull valuesbidqty 179855 nonnull valuesprice 23593 nonnull valuesvolume 23593 nonnull valuesdtypes float646using concat i getpdconcatdataclass pandascoreframedataframedatetimeindex 179855 entries 20130327 22070890200 to 20130403 165958180200data columnsprice 23593 nonnull valuesvolume 23593 nonnull valuesbidqty 179855 nonnull valuesbidprice 179855 nonnull valuesaskprice 179855 nonnull valuesaskqty 179855 nonnull valuesdtypes float646notice how the index changes when using concat why is that and how would i go about using concat to reproduce the results obtained using append since concat seems so much faster 246 ms per loop vs 302 s per loopthank you for your help,['python'] +451003,dynamically add c properties at runtime i know there are some questions that address this but the answers usually follow along the lines of recommending a dictionary or collection of parameters which does not work in my situationi am using a library that works through reflection to do lots of clever things with objects with properties this works with defined classes as well as dynamic classes i need to take this one step further and do something along these linespublic static object getdynamicobjectdictionarystringobject properties var myobject new object foreach var property in properties this next line obviously does not work myobjectaddpropertypropertykeypropertyvalue return myobjectpublic void main var properties new dictionarystringobject propertiesaddproperty1acustomclassinstance propertiesaddproperty2teststring2 var myobject getdynamicobjectproperties then use them like this or rather the plug in uses them through reflection var customclass myobjectproperty1 var mystring myobjectproperty2the library works fine with a dynamic variable type with properties assigned manually however i do not know how many or what properties will be added beforehand,['c#'] +451008,bash ruby command not found hyperrjasserv1 rbenv global193p392hyperrjasserv1 rbenv local193p392hyperrjasserv1 which rubybuildusrlocalbinrubybuildhyperrjasserv1 rbenv versions 193p392 set by homehyperrjasrubyversionhyperrjasserv1 rbenv version193p392 set by homehyperrjasrubyversionhyperrjasserv1 rbenv rehashhyperrjasserv1 ruby vbash ruby command not foundhyperrjasserv1 env grep pathpathhomehyperrjasrbenvbinusrlocalsbinusrlocalbinusrsbinusrbinsbinbinusrgamesnode pathusrlibnodejsusrlibnode modulesusrsharejavascripthyperrjasserv1 export pathhomerbenvbinpathhyperrjasserv1 ruby vbash ruby command not foundi am working with ubuntu 1204this is my profile file profile executed by the command interpreter for login shells this file is not read by bash1 if bash profile or bash login exists see usrsharedocbashexamplesstartupfiles for examples the files are located in the bashdoc package the default umask is set in etcprofile for setting the umask for ssh logins install and configure the libpamumask packageumask 022 if running bashif n bash version then include bashrc if it exists if f homebashrc then homebashrc fifi set path so it includes users private bin if it existsif d homebin then pathhomebinpathfiexport pathhomerbenvbinpatheval rbenv init eval rbenv init eval rbenv init i have installed ruby last version with rbenv and when i try ruby v i get bash ruby command not found,"['ruby-on-rails', 'ruby']" +451018,calculate mean across dimension in a 2d array i have an array a like thisappend4010aappend5011so it looks like this a40 10 50 11i need to calculate the mean for each dimension separately the result should be this4510545 being the mean of a0 and 105 the mean of a1what is the most elegant way of solving this without going to a loop,['python'] +451038,jquery support invalid selector i get the following console message160401292 error syntax error unrecognized expression unsupported pseudo invalid httplocalhost8080assetsjsjquery191minjs4when i try something likeif etargetisinvalid how do i fix thisheres an example try changing the jquery version stops working after 19,"['javascript', 'jquery', 'html']" +451076,why is the result of two function definitions joined by a comma why does the following code alert 2var f function x return 1 function y return 2 alertfwhat i can see is that somehow the y function is getting executed and x function is ignored i have made sure that i put alert in both functions and only the alert in y is called which make me believe that the x function is not being called at alland if i remove the y function then it alerts 1whats going on,['javascript'] +451088,ruby csv utf8 encoding error while reading this is what i was doingcsv csvopenfile name ri used this for testingline csvshiftwhile not linenil puts line line csvshiftendand i ran into thisargumenterror invalid byte sequence in utf8i read the answer here and this is what i triedcsv csvopenfile name r encoding windows1251utf8i ran into the following errorencodingundefinedconversionerror x98 to utf8 in conversion from windows1251 to utf8then i came across a ruby gem charlock holmes i figured i would try using it to find the source encodingcharlockholmesencodingdetectordetectfilereadfile name typetext encodingwindows1252 confidence37 languagefrso i did thiscsv csvopenfile name r encoding windows1252utf8and still got thisencodingundefinedconversionerror x8f to utf8 in conversion from windows1252 to utf8,['ruby'] +451172,c function returns a rvalue but that can be assigned a new value the code is as follows include iostream using namespace std class a a rtbyvalue return a void passbyrefa aref do nothing int main a aa rtbyvalue aa compile without errors passbyrefrtbyvalue compile with error return 0 the g compiler gives the following errordcpp in function aint mainadcpp1923 error invalid initialization of nonconst reference of type a from an rvalue of type adcpp126 error in passing argument 1 of avoid passbyrefaait says that i cannot pass an rvalue as an argument of a nonconst reference but what i am confused about is why i can assign to this rvalue just as the code shows,['c++'] +451179,where and how to handle stripe exceptions i am building a small proof of concept with stripe and ruby on rails 32 so far i have watched the railscast on how to implement stripe in a ror app and it is working really welli have built my app by following railscast 288 billing with stripe now my users can add and edit their credit cards and even register to classes and have their credit card billed upon completionnow i have been testing with stripes numerous test credit cards and i want to catch as many exceptions when raised i am using stripes example errors in my registration model as show hereclass registration activerecordbase belongs to user belongs to session attr accessible session id user id session user stripe payment id validates user id uniqueness scope session id def save with paymentuser stripe card token if valid if userstripe customer idpresent charge stripechargecreate customer userstripe customer id amount selfsessionpriceto i 100 description registration for selfsessionname idselfsessionid currency cad else customer stripecustomercreate email useremail card stripe card token description username charge stripechargecreate customer customerid amount selfsessionpriceto i 100 description registration for selfsessionname idselfsessionid currency cad userupdate attributestripe customer id customerid end selfstripe payment id chargeid save end rescue stripecarderror e body ejson body err bodyerror loggerdebug status is ehttp status loggerdebug type is errtype loggerdebug code is errcode loggerdebug param is errparam loggerdebug message is errmessage rescue stripeinvalidrequesterror e invalid parameters were supplied to stripes api rescue stripeauthenticationerror e authentication with stripes api failed maybe you changed api keys recently rescue stripeapiconnectionerror e network communication with stripe failed rescue stripestripeerror e thisplay a very generic error to the user and maybe send yourself an email rescue e something else happened completely unrelated to stripe endendi am merely rescuing from errors right now and not really taking action after one being raised and ultimately i would like to stop the current class registration from happening and redirect a user with a flash errori have read about rescure from but i am not sure what is the best way to handle of all the possible stripe errors i know cannot redirect from the model how would you experts handle thisheres my registration controllerclass classroomregistrationscontroller applicationcontroller before filter authenticate user def new if paramssession id session sessionfindparamssession id registration registrationnewuser current user session session else flasherror course session is required end rescue activerecordrecordnotfound render file public404 status not found end def create if paramssession id session sessionfindparamssession id registration registrationnewuser current user session session if registrationsave with paymentcurrent user paramsstripe card token flashnotice course registration saved with success loggerdebug course registration saved with success mixpaneltrack registered to a session thistinct id current userid id sessionid name sessionname description sessiondescription course sessioncoursename mixpanelincrement current userid sessions registered 1 mixpaneltrack chargecurrent userid sessionpriceto i else flasherror there was a problem saving the registration loggerdebug there was a problem saving the registration end redirect to root path else flasherror session required redirect to root path end endendthanks for taking the time to respond much appreciatedfrancis,['ruby-on-rails'] +451188,sorting an nsdictionary descending how do i send options with the compareoptions selector i am attempting to sort an nsdictionaryfrom the apple docs i see you can use keyssortedbyvalueusingselectornsdictionary dict nsdictionary dictionarywithobjectsandkeys nsnumber numberwithint63 mathematics nsnumber numberwithint72 english nsnumber numberwithint55 history nsnumber numberwithint49 geography nilnsarray sortedkeysarray dict keyssortedbyvalueusingselectorselectorcomparewhich gives sortedkeysarray contains geography history mathematics englishbut i want sortedkeysarray contains english mathematics history geographyi have read that you can use compareoptions and an nsstringcompareoptions to change the comparison to compare in the other directionhowever i do not understand how you send compareoptions with an option in the selectori want to do something like thisnsarray sortedkeysarray dict keyssortedbyvalueusingselectorselectorcompareoptionsnsorderdescendinghow should i switch the order of the comparisonrelatedtstart0,"['ios', 'objective-c']" +451199,should i use this keyword when i want to refer to instance variables within a method my teacher says that when i try to access an instance variable within a method i should always use the this keyword otherwise i would perform a double search a local scope search and then an instance scope searchexamplepublic class test int cont0 public void method systemoutprintlncontshould i use thiscont instead i hope he is wrong but i cannot find any argument,['java'] +451365,ordering of instance variable initializers it seems intuitively clear that in java instance variable intitializers are executed in the order in which they appear in the class declarationthis certainly appears to be the case in the jdk i am using for example the followingpublic class clazz int x 42 int y thisz int z thisx void print systemoutprintfd d dn x y z public static void mainstring args new clazzprint prints 42 0 42 in other words y picks up the default value of zis this ordering actually guaranteed i have been looking through the jls and cannot find any explicit confirmation,['java'] +451390,core data predicate date comparison im trying to fetch all the objects in an entity matching a user selecteddate it is an nsdatethe core data code is fine but my predicate keeps returning 0 results the dates are the same in the database as the user is selectinghow should the selecteddate be compared with a date from an entity using a predicatenspredicate predicate nspredicate predicatewithformatedate selecteddate,['objective-c'] +451391,the operation couldnat be completed comfacebooksdk error 2 ios6 hi i am ussing ios6 for facebook login and i am getting this error as native popupthe operation couldnat be completed comfacebooksdk error 2 this is the scenario ive used i am running this on simularori have logged in to the facebook app through settings and i tried to login to my app and its working fine then i logged out of the facebook from settings and logged in again with different user then i tried to login to the app i am getting this error i tried loging out of the app using the commandfbsessionactivesession closeandcleartokeninformationbut no use the bundle identifier in the facebook app is same as in my ios app this is the code i used to loginnsarray permissions nsarray alloc initwithobjectsemail nil fbsession openactivesessionwithreadpermissionspermissions allowloginuiyes completionhandler fbsession session fbsessionstate state nserror error self sessionstatechangedsession statestate errorerror any help is appreciated this is the error i am getting domaincomfacebooksdk code2 the operation couldnat be completed comfacebooksdk error 2 userinfo0x9535330 comfacebooksdkerrorloginfailedreasoncomfacebooksdksystemloginthisallowedwithouterror comfacebooksdkerrorsessionkey expirationdate null refreshdate null attemptedrefreshdate 011230 0 0 permissionsnullnotei got the same error on a different occation at that time it was a bug in my codeinstead of giving permission as nsarray permissions nsarray alloc initwithobjectsemailbirthday nili was wrongly doing it as nsarray permissions nsarray alloc initwithobjectsemailbirthday nilsolutioneven after correcting the code i was getting the same error i have to logout and login the facebook from ios settings screen once i did that the correct code never caused any problem note that the problem only occured on the device that previously executed the buggy code note sure what caused the problem hope this info helps someone,['ios'] +451501,python try except 0 i am reading some python code written a while ago and found thistry do some stuffexcept 0 exception handling stuffand i am just not sure what except 0 means i do have my guesses supposed to catch nothing ie let the exception propagate or it could be some sort of switch to turn debugging mode on and off by removing the 0 which will then catch everything can anyone lend some insight a google search yielded nothingthankssome sample code by request try if logerrors dbstuffersetstatustoerrorprop id obj dbcommit except 0 tracebackprint exc,['python'] +451507,matplotlib change math font size i am making some plots with matplotlib and i have come across a problem with the tex rendering it seems that the mathtext xheight is is a bit smaller than the normal bitstream vera sans see the following examplex linspace0 30 300y 05rand30020numpypowerx15 24xlabelromega radcdothzylabelrintensity2titlerwhy is mathtext so much smaller than normal textas you can see it is particularly noticeable with greek letters and numbers ideally i would be able to define some scaling factor that would just make the math text a bit bigger at each font size is there any way to do this simply i do not want to simply use computer modern everywhere i also do not want to compile a new tex math font if that is even possibleone solution that i would be on board with is using sansserif fonts for the greek letters and numerals but for whatever reason matplotlib ignores formatting on thosetitlewhy does matmathsfplotlib ignore formatting for mathsf2 mathsftwo mathbf2 mathbftwo and mathsfomegai assume it is something to do with the nature of how these things are typeset but is there any way to fix it,['python'] +451536,how can i use iboutletcollection to connect multiple uiimageviews to the same outlet i have 10 uiimageviews which do the same thing they have some void methods that change their image with a timermy uiimageview is an outlet and i want to connect all the 10 imageviews to the same outlet but interface builder does not allow me i found that there is a solution iboutletcollection can anyone explain to me how to use this to connect multiple imageviews to the same outlet,"['ios', 'objective-c']" +451546,inet aton normalization of a ipv4 address does not inet aton suppose to normalize the dot version of the internet address why do i get different output values for the example belowint main char user ip16 192168002025 char user ip216 192168225 struct sockaddr in addr struct sockaddr in addr2 inet atonuser ip2 addrsin addr inet atonuser ip addr2sin addr printfaddrsin addrlun addrsin addr printfaddr2sin addrlun addr2sin addr return 0outputaddrsin addr419604672addr2sin addr352495808,['c'] +451551,vlc rtsp live stream to android for my app i have to stream from a decklink card to an android app i must be a live stream so either hls or rtsp seems to be good solutions since my app targets android 3 i recompiled vlc with the decklink sdk and i am able to live stream to another pc over the network but it works only 60sec with rtsphere is what i tried http stream vlc v decklink souttranscodevcodecmp4vacodecmpgavb56ab24channels1standardaccesshttpusekeyframesmuxtsdst3001streammpegit is working in android vlc 0011 but only in wifi not in 3g and i am not able to play it in my app with a videoview here is the code i used and the corresponding error messages string url videoview videoview videoview thisfindviewbyidridvideoviewvideoviewsetvideouriuriparseurl videoviewsetmediacontrollernew mediacontrollerthisvideoviewrequestfocus videoviewstarterror messages 0408 152646272 dmediaplayer16349 could not open file on client side trying server side0408 152646272 vchromiumhttpdatasource7680 connect on behalf of uid 10808677890408 152646272 ichromiumhttpdatasource7680 connect to 00408 152646302 iawesomeplayer7680 awesomeplayerawesomeplayerin0408 152646302 iawesomeplayer7680 awesomeplayerawesomeplayeraftermclientconnect0408 152646302 iawesomeplayer7680 setdatasource l0408 152646302 wmediaplayer16349 infowarning 701 00408 152646302 vchromiumhttpdatasource7680 connect on behalf of uid 100670408 152646302 ichromiumhttpdatasource7680 connect to 00408 152646342 iactivitymanager272 thisplayed frifremertestrtspmainactivity 183ms0408 152646382 imediaplayer16349 info 70100408 152707592 emediaplayer16349 error 1 21474836480408 152707592 emediaplayer16349 error 12147483648rtsp i used the encoding options recommended by google on this page eg video codec h264audio codec aacvideo bitrate 56audio bitrate 24audio channels 1size 176x144vlc v decklink soutffmpegstrict2 souttranscodewidth176height144vcodech264acodecmp4avb56ab24channels1rtpdst13424663169portvideo54portaudio56sdprtsp1342466316954streamsdpi am able to play the stream in vlc desktop but not in android even in the android vlc version or the default google video player if i do not specify a muxer i can also play it it quicktime if i specify the muxer either ts or ps i have no video if i try another muxer vlc tells me that i am only allowed to use ts or ps in rtpif i try with the google video player i get these messages in the locat 0408 153245792 dmediaplayer13688 could not open file on client side trying server side0408 153245802 wmediaplayer13688 infowarning 701 00408 153245812 imediaplayer13688 info 70100408 153245812 dmediaplayer13688 getmetadata0408 153245812 emediaplayerservice7680 getmetadata failed 380408 153245852 imyhandler7680 connection request completed with result 0 success0408 153245882 iartspconnection7680 status rtsp10 200 ok0408 153245882 imyhandler7680 describe completed with result 0 success0408 153245882 iasessiondescription7680 v00408 153245882 iasessiondescription7680 o 15352003113363922923 15352003113363922923 in ip4 to63169ifremerfr0408 153245882 iasessiondescription7680 sunnamed0408 153245882 iasessiondescription7680 ina0408 153245882 iasessiondescription7680 cin ip4 134246631690408 153245882 iasessiondescription7680 t0 00408 153245882 iasessiondescription7680 atoolvlc 2050408 153245882 iasessiondescription7680 arecvonly0408 153245882 iasessiondescription7680 atypebroadcast0408 153245882 iasessiondescription7680 acharsetutf80408 153245882 iasessiondescription7680 acontrolrtsp1342466316954streamsdp0408 153245882 iasessiondescription7680 maudio 56 rtpavp 960408 153245882 iasessiondescription7680 bas240408 153245882 iasessiondescription7680 brr00408 153245882 iasessiondescription7680 artpmap96 mpeg4generic480408 153245882 iasessiondescription7680 afmtp96 streamtype5 profilelevelid15 modeaachbr config118856e500 sizelength13 indexlength3 indexdeltalength3 profile10408 153245882 iasessiondescription7680 acontrolrtsp1342466316954streamsdptrackid00408 153245882 iasessiondescription7680 mvideo 54 rtpavp 960408 153245882 iasessiondescription7680 bas560408 153245882 iasessiondescription7680 brr00408 153245882 iasessiondescription7680 artpmap96 h26490408 153245882 iasessiondescription7680 afmtp96 packetizationmode1profilelevelid640bspropparametersetsz2qac6zzqstvac0albadaeayjxqplgaaovssiw0408 153245882 iasessiondescription7680 acontrolrtsp1342466316954streamsdptrackid10408 153245982 iartspconnection7680 status rtsp10 200 ok0408 153245982 imyhandler7680 setup1 completed with result 0 success0408 153245982 imyhandler7680 server specified timeout of 60 secs0408 153245992 wmyhandler7680 missing source field in transport response using rtsp endpoint address0408 153245992 iapacketsource7680 dimensions 176x1440408 153246012 iartspconnection7680 status rtsp10 200 ok0408 153246022 imyhandler7680 setup2 completed with result 0 success0408 153246022 imyhandler7680 server specified timeout of 60 secs0408 153246022 wmyhandler7680 missing source field in transport response using rtsp endpoint address0408 153246022 wmyhandler7680 server picked an odd rtp port it should have picked an even one well let it pass for now but this may break in the future0408 153246082 iartspconnection7680 status rtsp10 200 ok0408 153246082 ddalvikvm13688 gc for alloc freed 303k 7 free 9289k9927k paused 35ms total 36ms0408 153246092 imyhandler7680 play completed with result 0 success0408 153246092 imyhandler7680 this is a live stream0408 153248262 daudiohardware7680 audiohardware pcm playback is going to standby0408 153248262 daudiohardware7680 closepcmout l mpcmopencnt 10408 153256092 wmyhandler7680 never received any data switching transports0408 153256112 iartspconnection7680 status rtsp10 200 ok0408 153256122 imyhandler7680 teardown completed with result 0 success0408 153256122 imyhandler7680 connection request completed with result 0 success0408 153256152 iartspconnection7680 status rtsp10 200 ok0408 153256152 imyhandler7680 describe completed with result 0 success0408 153256152 iasessiondescription7680 v00408 153256152 iasessiondescription7680 o 15352003157473632156 15352003157473632156 in ip4 to63169ifremerfr0408 153256152 iasessiondescription7680 sunnamed0408 153256152 iasessiondescription7680 ina0408 153256152 iasessiondescription7680 cin ip4 134246631690408 153256152 iasessiondescription7680 t0 00408 153256152 iasessiondescription7680 atoolvlc 2050408 153256152 iasessiondescription7680 arecvonly0408 153256152 iasessiondescription7680 atypebroadcast0408 153256152 iasessiondescription7680 acharsetutf80408 153256152 iasessiondescription7680 acontrolrtsp1342466316954streamsdp0408 153256152 iasessiondescription7680 maudio 56 rtpavp 960408 153256152 iasessiondescription7680 bas240408 153256152 iasessiondescription7680 brr00408 153256152 iasessiondescription7680 artpmap96 mpeg4generic480408 153256152 iasessiondescription7680 afmtp96 streamtype5 profilelevelid15 modeaachbr config118856e500 sizelength13 indexlength3 indexdeltalength3 profile10408 153256152 iasessiondescription7680 acontrolrtsp1342466316954streamsdptrackid00408 153256152 iasessiondescription7680 mvideo 54 rtpavp 960408 153256152 iasessiondescription7680 bas560408 153256152 iasessiondescription7680 brr00408 153256152 iasessiondescription7680 artpmap96 h26490408 153256152 iasessiondescription7680 afmtp96 packetizationmode1profilelevelid640bspropparametersetsz2qac6zzqstvac0albadaeayjxqplgaaovssiw0408 153256152 iasessiondescription7680 acontrolrtsp1342466316954streamsdptrackid10408 1532562 iartspconnection7680 status rtsp10 461 unsupported transport0408 1532562 imyhandler7680 setup1 completed with result 0 success0408 1532562 iapacketsource7680 dimensions 176x1440408 153256242 iartspconnection7680 status rtsp10 461 unsupported transport0408 153256252 imyhandler7680 setup2 completed with result 0 success0408 153256272 emediaplayer13688 error 1 21474836480408 153256272 emediaplayer13688 error 121474836480408 153256272 dvideoview13688 error 12147483648i guess the problem is pointed with the status rtsp10 461 unsupported transport but i do not see what can i change i already open the ports i use and i do receive the video on another computeron the android phone i can play some rtsp streams i found on the web for exemple this one rtsp18472239149vodmp4bigbuckbunny 115kmov so it should be possibleif anyone can help,['android'] +451568,making pyplothist first and last bins include outliers pyplothist documentation specifies that when setting a range for a histogram lower and upper outliers are ignoredis it possible to make the first and last bins of a histogram include all outliers without changing the width of the binfor example let us say i want to look at the range 03 with 3 bins 01 12 23 let us ignore cases of exact equality for simplicity i would like the first bin to include all values from minus infinity to 1 and the last bin to include all values from 2 to infinity however if i explicitly set these bins to span that range they will be very wide i would like them to have the same width the behavior i am looking for is like the behavior of hist in matlabobviously i can numpyclip the data and plot that which will give me what i want but i am interested if there is a builtin solution for this,['python'] +451620,where should i put angularjs factories services i am working to cleanly structure my angularjs app according to best practices which includes separating the controllers and app into different script files quick question where should i put my factories and services i am asking in the context of having factories services that will be accessed outside of the scope of a single controller as well as having some that are within the scope of a single controller,['javascript'] +451674,average visit duration spikes at midnight last thursday i implemented a change to our ga script i added the enhanced link attribution and added the setdomainname attribute since then most of our stats are fine but the average visit duration has gone completely insane we went from averaging around 4minsvisit to massive spikes every morning after midnight of visit times exceeding two hours i figure it must be something i did wrong as it started going out of control about the same hour that i deployed the changei do not want to flail about making changes on production until i can figure out the cause any help or suggestions would be greatly appreciated hourly analytics for average visit durationthe current ga scriptvar gaq gaq var pluginurl wgoogleanalyticscompluginsgainpage linkidjs gaqpush require inpage linkid pluginurl gaqpush setcustomvar 1 locale en ca 2 gaqpush setaccount redacted gaqpush setsitespeedsamplerate 10 gaqpush setdomainname redacted gaqpush trackpageviewfunction var ga documentcreateelementscript gatype textjavascript gaasync true gasrc https documentlocationprotocol httpsl httpw googleanalyticscomgajs var s documentgetelementsbytagnamescript0 sparentnodeinsertbeforega s,"['javascript', 'html']" +451675,android thisambiguating file paths in my app users pick files internally i store information about the file which i key based on the file path next time that file is used i do stuff with the stored information trouble is i instantiate my files withfile file1 new fileenvironmentgetexternalstoragedirectory testtxtand then on a particular jb device file1getcanonicalpath gives storageemulated0testtxtthe trouble is that when other apps launch my app with a file path in an intent the paths they send tend to look like mntsdcardtesttxtis there a smart strategy to thisambiguate these two paths possibly i should be instantiating my files differently edit the trouble is the two canaonical paths for the two files are not equal for the below cp1mntsdcardtesttxt and cp2storageemulated0texttxtfile file1 new filemntsdcardtesttxtfile file2 new filestorageemulated0testtxtstring cp1 file1getcanonicalpathstring cp2 file2getcanonicalpath,['android'] +451711,how to add angularenabled elements to dom i would like to add some angularenabled dom elements programmatically actually i probably will need to add custom components how can i do itheres a trivial fiddle to demonstrate the issue htmldiv ngappmain div ngcontrollermyctrl button ngclickadd addbutton div idcontainer divtestdiv div divdivjsangularmodulemain controllermyctrl functionscope scopeadd function containerappenddivtestdiv scopetest test messagejust in case i expect it to add a div showing test message for each click not testwhy do i need it well i would like to have a few sortable columns in jquery sortable sense with portlets i imagine each portlet could be a componentam i climbing the wrong hill what is the angular way to solve thisedit i hoped this simplistic example wouldnt end that way but anyway the ultimate goal is not to thisplay a div for each element in an arraywhat i really want is a more complex controller i need a portlet container with some interesting behavior it may need to decide to place each portlet in a different column it may offer changing the layout and have a decent way to reorganize portlets in such event and so on,['javascript'] +451745,inheritance within javascript i am studying the concept of inheritance in javascript and the tutorial i am looking at uses this code define the student classfunction student call the parent constructor personcallthis inherit personstudentprototype new person correct the constructor pointer because it points to personstudentprototypeconstructor studentmy question is why is it necessary to both call the parent constructor personcallthis and set the student prototype equal to a new person object ie studentprototype new person,['javascript'] +451774,padding bars remain when scrolling gridview i have this gridview see screenshot that contains items that all need about 12 dip spacing however when i set padding on the gridview it seems that i cannot scroll across this paddingm which i do want to do how do i achieve thisnote the slice of space above the top two pictures that i want to scroll away fromcodegridview androidididfeed grid androidlayout widthfill parent androidlayout heightwrap content androidcolumnwidth96dp androidgravitycenter androidhorizontalspacingdimengrid view margins androidnumcolumnsauto fit androidpaddingdimengrid view margins androidstretchmodecolumnwidth androidscrollbarstyleoutsideinset androidverticalspacingdimengrid view margins,['android'] +451780,using image404 with azurereader2 in aspnet i am using following plugin to resizes images in aspnet application azurereader2 works fine image404 works fine seprately but when i try to access blob url it does not redirect and it is giving the remote server returned an error 404 not foundany one used image404 with azurereader2 is it compatible with this,['asp.net'] +451802,crawling multiple sites with python scrapy with limited depth per site i am new to scrapy and i am trying to crawl multiple sites from a text file with crawlspider however i would like to limit the depth of scraping per site and also the total number of crawled pages again per web site unfortunately when the start urls and allowed domains attributes are set the responsemetadepth always seems to be zero this does not happen when i am trying to scrape individual sites setting the depth limit in the settings file does not seem to do anything at allwhen i remove the init definition and simply set the start urls and allowed domains things seem to be working finehere is the code sorry for the indentation this is not the issueclass downloadspidercrawlspider name downloader rules rulesgmllinkextractor callbackparse item followtrue def init self urls file n10 data openurls file rreadlinesn selfallowed domains urlparseihostnamestrip for i in data selfstart urls http domain for domain in selfallowed domains def parse start urlself response return selfparse itemresponse def parse itemself response print responseurl print responsemetadepththis results in responsemetadepth always equal to zero and the cralwer only crawls the very first site of each element of start urls ie it does not follow any links so i have two questions1 how to limit the crawl to a certain depth per each site in start urls2 how to limit the total number of crawls per site irrespective of the depththanks,['python'] +451818,python why do functions in math module accept decimal objects as arguments bizzarely every function from pythons math module seems to work just fine with decimal objects for example frexp exp coswhen i type printmathfrexpdecimaldecimal234112412 python prints the correct answer which is 057156 12 and does not throw any exceptionsi would assume that the math module would be written in lowlevel c relying as heavily as possible on hardware math operations for efficiency so why would it work for decimal objectsdid they put a type check into the math functions and switch to a different implementation if the argument is a decimal i did not see anything like that mentioned in the docs it could also be that the decimal is automatically being converted to a float but that does not make any sense eitheryeah i am confused,['python'] +451824,jquery ui autocomplete search from multiple attributes of one array hi i am trying to get the jquery ui autocomplete widget to work so that it searches for matches from multiple attributes of my array not just one that it does by defaulti have messed around with their example however i am still unsure how to solve thisheres my array format in scriptvar projects value jquery label jquery desc the write less do more javascript library other 9834275 9847598023 753425828975340 82974598823 value jqueryui label jquery ui desc the official user interface library for jquery other 98 83475 9358 949078 8 40287089754 345 2345 value sizzlejs label sizzle js desc a purejavascript css selector engine other 49857 2389442 573489057 89024375 928037890 what i am seeking is that if you type write the first element should pop up in autocomplete similarly if you type jq the first 2 elements should pop upaccording to the documentationarray an array can be used for local data there are two supported formatsan array of strings choice1 choice2 an array of objects with label and value properties label choice1 value value1 the label property is thisplayed in the suggestion menu the value will be inserted into the input element when a user selects an item if just one property is specified it will be used for both eg if you provide only value properties the value will also be used as the label how do i hardcode it so the source uses 2 labels label and desc instead of the one labelsorry i have searched for many similar questions however they all aim at multiple sources which is not here since i only have 1 array is it,['jquery'] +451829,uiwebview is loading very slowly on the first time it is thisplayed in a specific uiviewcontroller i have a product details uiviewcontroller on my storyboard which has a uiwebview to thisplay rich text basically bold and italic the web view is loaded using a string fetched from coredata loadhtmlstring the problem is that the first time the view is thisplayed there is at least a one second delay before the web view is rendered further product details views that are loaded all load fine it is only the first product details web view which takes the time to loadthis is what i have tried with no joythisplaying a uiwebview with text on the first screen to warm up the uiwebviewwhen it comes time to show the details view init the web view in the prepare for segue method and pass it to the product details view controlleri have tried various combinations of having the web view in the storyboard not in the storyboard in a scroll view etci would be very interested if others have had this problem and how they got over it worked around it i find it strange i have not been able to find many similar problems on so i must be doing something stupidnote i am using a uiwebview so i can thisplay rich text i understand i can thisplay rich text using other controls but the program that makes the text that i want to thisplay can only export rich text using html,"['ios', 'objective-c']" +451887,how to create a ruby datetime from existing timezone for rails i have users entering in dates in a ruby on rails website i parse the dates into a datetime object with something likedate datetimenewparamsyearto i paramsmonthto i paramsdayto i paramshourto i paramsminuteto iordate datetimeparseparamsdateboth datetimes will not be in the time zone of the user which i previously set with something liketimezone pacific time us canadahow do i parse the above datetimes to be in the right time zone i know the datetimenew method has a 7th argument for the time offset is there an easy way to look up the offset for a time zone in a given time or should i be using something other than datetime,"['ruby-on-rails', 'ruby']" +451916,generalized hough transform and opencv iam looking for an opencv implementation of generalized hough transform or at least something in cdespite i searched for a while iave not been able to find nothing interestingany suggestion,['c++'] +451945,ambiguous overload for operator if conversion operator to int exist i am trying to implement the vector like and the map like operator for a class but i get error messages from my compilers g and clang found out that they only occurs if the class has also conversion operators to integer typesnow i have two problems the first is that i do not know why the compiler cannot thistinguish between const stdstring and when the class has conversion operators to intsthe second i need the conversion and the index operator does anyone know how to fix thatthanks in advance and best regards from meworksinclude stdinthinclude stringstruct foo foo operatorconst stdstring foo foo operatorsize t index int main foo f ffoo f2does not workinclude stdinthinclude stringstruct foo operator uint32 t foo operatorconst stdstring foo foo operatorsize t index int main foo f ffoo f2compiler errormaincpp in function int mainmaincpp149 error ambiguous overload for operator in ffoomaincpp149 note candidates aremaincpp149 note operatorlong int const char builtinmaincpp77 note foo foperatorconst stringmaincpp87 note foo foperatorsize t near matchmaincpp87 note no known conversion for argument 1 from const char 4 to size t aka long unsigned int,['c++'] +451957,android edit text how to start typing at the top left i have this edittextlinearlayout xmlnsandroid androidlayout widthmatch parent androidlayout heightmatch parent androidorientationvertical edittext androidlayout widthfill parent androidlayout heightwrap content androidinputtypetextmultiline androidlines5 androidsinglelinefalse androidtextstringapp name linearlayoutmy problem is that typing starts at the middle of the edittextmy question is how to start typing at the top left of the edittext,['android'] +451971,adding whitespaces to the string i am getting string as parameterevery string should take 30 characters now after i check it is lenght i want to add whitespaces to the end if passed string is 25 characters long i want to add 5 more whitespacesquestion is how to add whitespaces to the string,['c#'] +451977,how do i add a title to my menu group i want to differentiate the groups by giving them a title or divider but i cannot find a title option for the group elementis there a way to add a title or dividergroup androidididmenu group sort item androidididmenu sort relevance androidshowasactionnever androidtitlestringsort relevance item androidididmenu sort rating androidshowasactionnever androidtitlestringsort rating group,['android'] +452001,active admin how to customize labels for select filter this seems like it should be fairly simple buy i have not been able to find any documentation on the subjecti have the following filterfilter archived as selectwhich gives me a working filter in the form of a select box with options any yes and nomy question is how do i customize these labels such that the functionality remains the same but the labels are instead all live and archived,['ruby-on-rails'] +452003,is there a working oauth library for python 3 whats the most current form of oauth for python 3i am trying to create a stock screener using my brokers api which uses oauth most of the info i find is out of date or conflicting i have seen the following modules referencedoauth seems to be the original now outdated i get an error of module object has no attribute consumeroauth2 newer version apparently also outdated the one most referenced one online glitches out in pipcannot figure out how to install itoauthlib iirc claims to be the new replacement for oauth and oauth2rauthoauth2service also potentially replacement for oauth and oauth2requests oauth hook pyoauth2 i get an error about not having a module named client in pyoauth2s initnone of them seem to work as expected and i have a feeling that this is due to low oauth 3 support have you gotten oauth to work in python 3 if so how did you do it,['python'] +452007,how to set connection timeout and operation timeout in openssl libcurl has timeout options like thesecurlopt connecttimeout maximum time in seconds that you allow the connection to the server to takecurlopt timeout maximum time in seconds that you allow the libcurl transfer operation to takei would like to implement a similar timeout mechanism in opensslwhat changes would be required in the code below so that a timeout value is applied to bio do connect bio write and bio readi am connecting to a server and sendingreceiving data tofrom the server using bio writebio read that openssl provides my code is based on the following sample code available from hereint main bio bio ssl ssl ssl ctx ctx int p char request get http11x0dx0ahost wverisigncomx0dx0ax43onnection closex0dx0ax0dx0a char r1024 set up the library err load bio strings ssl load error strings openssl add all algorithms set up the ssl context ctx ssl ctx newsslv23 client method load the trust store if ssl ctx load verify locationsctx truststorepem null fprintfstderr error loading trust storen err print errors fpstderr ssl ctx freectx return 0 setup the connection bio bio new ssl connectctx set the ssl mode auto retry flag bio get sslbio ssl ssl set modessl ssl mode auto retry create and setup the connection bio set conn hostnamebio wverisigncomhttps ifbio do connectbio 0 fprintfstderr error attempting to connectn err print errors fpstderr bio free allbio ssl ctx freectx return 0 check the certificate ifssl get verify resultssl x509 v ok fprintfstderr certificate verification error in ssl get verify resultssl bio free allbio ssl ctx freectx return 0 send the request bio writebio request strlenrequest read in the response for p bio readbio r 1023 ifp 0 break rp 0 printfs r close the connection and free the context bio free allbio ssl ctx freectx return 0i am crosscompiling for arm on ubuntu eclipse with codesourcery lite,['c'] +452019,is nsapp terminateid deprecated i have been searching for how to terminate my application programmatically i found in many topics people using nsapp terminateidin xcode terminateid is crossed is this method deprecated should i use it to terminate my application if no which is the right way to do it updatepicture of what i mean when i say that it is crossed,['objective-c'] +452033,setting the height of a row in a jtable in java i have been searching for a solution to be able to increase the height of a row in a jtable i have been using the setrowheightint int method which compiles and runs ok but no rows have been increased when i use the getrowheightint method of the row i set the height to it does print out the size i increased the row to so i am not sure what is wrong the code below is a rough illustration how i am trying to solve it my class extends jframestring columnnames column 1 column 2 column 1 3jtable table new jtablenew defaulttablemodelcolumnnames peoplesizedefaulttablemodel model defaulttablemodel tablegetmodelint count 1forperson p people modelinsertrowcountnew objectcount pgetname pgetage pgetnationality counttablesetrowheight1 15try set height to 15 i have tried highercan anyone tell me where i am going wrong i am trying to increase the height of row 1 to 15 pixels,['java'] +452073,how do you use stdsystem error with getlasterror if i call a win32 function that reports errors via getlasterror for example registerclassex how do i throw a stdsystem error for that error,['c++'] +452101,why do we need both client side and server side validation the argument for using both client side validation javascript and server side validation using a validator is this if the client browser does not support javascript then the user cannot use client side validation my question is how good is this argument in practice in theory it makes sense but in practice if javascript is thisabled in the browser then most website features will not even work the user probably cannot even load the page without javascript let alone submit a form,['javascript'] +452103,how do i simulate floating list items right in an unordered list without reversing the order i have a navigation menu on my site which is an unordered list items are naturally thisplayed lefttoright and in the proper order it looks like this12345678910obviously if i float all the list items li to the right they will show up in the position that i want them to shop up in but in the reversed order43218765109i like the positioning but i do not want the reversed order i need it to look like this12345678910the limitation that i present is that i cannot rewrite the menu html in the reverse order i want to do this in css alone supposedly this can be done by floating the unordered list ul to the right and floating the list items li to the left however i have been unsuccessful in doing this and since my css is so minimal i am not sure what i could be missingis the desired styling possible without changing the html,['css'] +452129,how can i access a newlyopened tabs window object in a firefox extension i am attempting to convert a greasemonky script to an extension for firefox and i am trying to make my extension automatically attach a simple script to any webpage when a new tab is opened i am converting the script from greasemonkey because i would like to take advantage of advanced preferences and menu optionsi access the tab using thisvar container gbrowsertabcontainercontaineraddeventlistenertabopen tabadded falsefunction tabaddedevent var newtabwindow eventtarget i do not know what goes hereattach script to newtabwindowand my goal is to append the script to the document in the new tab once it loads using this functionfunction scriptrunnertargetwindow var myscript targetwindowcontentdocumentcreateelementscript myscripttype textjavascript myscriptsetattributesrcchromeaddonnamecontentaddonscriptjs targetwindowcontentdocumentgetelementsbytagnamehead0appendchildmyscriptthis function works fine to attach the script to the current page when attached to a toolbar button with oncommandscriptrunnerwindow but i do not know how i could access the window in the newly opened tab or if i should cut out the window from the equation and access the document another way,['javascript'] +452175,removing fragments from an activity fragmantclass rsum new fragmantclassgetsupportfragmentmanagerbegintransactionremoversumcommit i am trying to remove this fragment when i load switch another fragment the above fragment does not get removed here is the method i am calling to switch fragmentspublic void switchcontentfragment fragment fragmantclass rsum new fragmantclass getsupportfragmentmanagerbegintransactionremoversumcommit mcontent fragment getsupportfragmentmanager begintransaction replaceridcontent frame fragment commit getslidingmenushowcontent,['android'] +452260,what happens when createwaitabletimer is set for nonexisting datetime the daylight saving time united states in 2013 began at 200 am on sunday march 10 so say now is march 9 2013 and i call the following api on an already created waitable timer handlefiletime ftwhen points as absolute time to march 10th 2013 at 210 amsetwaitabletimerhtimer ftwhen 0 null null truemarch 10th 2013 210 am is a nonexistent time because the time will be adjusted one hour ahead so instead of 2 am it will be 3 amso my question what will happen to my timer i cannot seem to find documentation for this case,['c++'] +452290,how can i remove a whole indexeddb database from javascript how can one remove a whole indexeddb database from javascript as opposed to just an object store i am using the indexeddb shim which may use websql as its backendi would mainly like to know how to do this for the phantomjs headless browser although chrome safari on ipad and ie10 are other important browsers,['javascript'] +452316,c preprocessor using the closing bracket of a parent macro i have this code which worksinclude stdiohdefine ax x bdefine bx cxdefine cxy y xint main void printf a1 2 3 it prints 132 the point of the a macro is to swap the thing which follows its parameters in brackets with everything after that until another closing bracketbut if i use that within another macrodefine zx xprintf z a1 2 3 i get the compile error unterminated functionlike macro invocationi realise that this happens because the compiler is trying to process the arguments of z independently but i need to use its closing bracket as a marker is there a way i can make this work within macros changing the calling syntax is not really an optionps before i get any responses talking about what an awful thing this is to do rest assured this is not for real code it is a problem which came up while making a toy program which uses define to simulate a new language inside c,['c'] +452326,a generic error occured in gdi in bitmapsave method i am working on to upload and same a thumnail copy of that image in a thumbnail forderi am using following linkbut newbmpsavedirectory tn filename is causing exception a generic error occurred in gdii have tried to give permission on folder also tried to use a new separate bmp object when savingedit protected void resizeandsavepropbannerimage objpropbannerimage create a bitmap of the content of the fileupload control in memory bitmap originalbmp new bitmapfuimagefilecontent calculate the new image dimensions int origwidth originalbmpwidth int origheight originalbmpheight int sngratio origwidth origheight int thumbwidth 100 int thumbheight thumbwidth sngratio int bannerwidth 100 int bannerheight bannerwidth sngratio create a new bitmap which will hold the previous resized bitmap bitmap thumbbmp new bitmaporiginalbmp thumbwidth thumbheight bitmap bannerbmp new bitmaporiginalbmp bannerwidth bannerheight create a graphic based on the new bitmap graphics ographics graphicsfromimagethumbbmp set the properties for the new graphic file ographicssmoothingmode smoothingmodeantialias ographicsinterpolationmode interpolationmodehighqualitybicubic draw the new graphic based on the resized bitmap ographicsdrawimageoriginalbmp 0 0 thumbwidth thumbheight bitmap newbitmap new bitmapthumbbmp thumbbmpthispose thumbbmp null save the new graphic file to the server newbitmapsaveimagethumbs t objpropbannerimageimageid imageformatjpeg ographics graphicsfromimagebannerbmp set the properties for the new graphic file ographicssmoothingmode smoothingmodeantialias ographicsinterpolationmode interpolationmodehighqualitybicubic draw the new graphic based on the resized bitmap ographicsdrawimageoriginalbmp 0 0 bannerwidth bannerheight save the new graphic file to the server bannerbmpsaveimage objpropbannerimageimageid jpg once finished with the bitmap objects we deallocate them originalbmpthispose bannerbmpthispose ographicsthispose,['c#'] +452377,generate tail call opcode out of curiosity i was trying to generate a tail call opcode using c fibinacci is an easy one so my c example looks like this private static void mainstring args consolewritelinefibintmaxvalue 0 public static int fibint i int acc if i 0 return acc return fibi 1 acc i if i build it in release and run it without debugging i do not get a stack overflow debugging or running it without optimizations and i do get a stack overflow implying that tail call is working when in release with optimizations on which is what i expectedthe msil for this looks like thismethod public hidebysig static int32 fibint32 i int32 acc cil managed method start rva 0x205e code size 17 0x11 maxstack 8 l 0 ldarg0 l 01 brtrues l 05 l 03 ldarg1 l 04 ret l 05 ldarg0 l 06 ldci41 l 07 sub l 08 ldarg1 l 09 ldarg0 l 0a add l 0b call int32 consoleapplication2consoleapplication2programfibint32int32 l 0010 ret i wouldve expected to see a tail opcode per the msdn but it is not there this got me wondering if the jit compiler was responsible for putting it in there i tried to ngen the assembly using ngen install exe navigating to the windows assemblies list to get it and load it back up in ilspy but it looks the same to memethod public hidebysig static int32 fibint32 i int32 acc cil managed method start rva 0x3bfe code size 17 0x11 maxstack 8 l 0 ldarg0 l 01 brtrues l 05 l 03 ldarg1 l 04 ret l 05 ldarg0 l 06 ldci41 l 07 sub l 08 ldarg1 l 09 ldarg0 l 0a add l 0b call int32 consoleapplication2consoleapplication2programfibint32int32 l 0010 ret i still do not see it i know f handles tail call well so i wanted to compare what f did with what c did my f example looks like thislet rec fibb i acc if i 0 then acc else fibb i1 acc iconsolewriteline fibb 3 0and the generated il for the fib method looks like thismethod public static int32 fibbint32 i int32 acc cil managed method start rva 0x2068 code size 18 0x12 custom instance void fsharpcoremicrosoftfsharpcorecompilationargumentcountsattributectorint32 int32monocecilcustomattributeargument maxstack 5 l 0 nop l 01 ldarg0 l 02 brtrues l 06 l 04 ldarg1 l 05 ret l 06 ldarg0 l 07 ldci41 l 08 sub l 09 ldarg1 l 0a ldarg0 l 0b add l 0c stargs acc l 0e stargs i l 0010 brs l 0which according to ilspy is equivalent to thismicrosoftfsharpcorecompilationargumentcountsmonocecilcustomattributeargumentpublic static int32 fibbint32 i int32 acc label1 if i 0 return acc i 1 i acc acc i goto label1so f generated tail call using goto statements this is not what i was expecting i am not trying to rely on tail call anywhere but i am just curious where exactly does that opcode get set how is c doing this,['c#'] +452386,how to check google publisher tag ad slot is empty or not i am using google publisher tags to fetch the adshow to check whether i am getting an ad or any empty ad for an specific ad sloti am using the below codegoogletagdefineslot1234travel 300250300x600 divgptad1234567890 div iddivgptad1234567890 stylewidth 728px height 90px script typetextjavascript googletagcmdpushfunction googletagthisplaydivgptad1234567890 script divhow to check this divdivgptad1234567890 contains an ad or not,"['javascript', 'jquery']" +452395,the most efficient way to delete all duplicate rows from table i have a table foo bar a abc b def c ghi d jkl a mno e pqr c stu f vwx i want to delete all rows containing duplicates by foo column so that the table should look like this foo bar b def d jkl e pqr f vwx what is the most efficient way to do this,['mysql'] +452413,ios uiimage imagenamed returns null on device uiimage imagenamedfilenamethis method returns null only on the devicei know it is known problem and it is usually due to the fact that simulator is case insensitivei have tried solutions proposed here uiimage imagenamed returns nilbut nothing worked out for methe case is simple i have 4 files namedbar2xipadpng bar2xiphonepng baripadpng bariphonepngall of them are in project with target checkbox checkednsloguiimage imagenamedbarthat line of code gives me null for device and i really have no idea what i am doing wrong right now,['ios'] +452428,how to find duplicate items in list i have liststring list new liststring a a b b r t how can i get only abi tried to do like thisliststring list new liststring a a b b r t liststring test list new liststring test list listthistincttolistnow test list has a b r tand thentest list test listexceptlisttolistso that was my fail point cause except deleted all elementscould you help me with solution,['c#'] +452458,center button under form in bootstrap i have some problems with bootstrap i centered form and button by using span6 offset3 and do not know how to center button under this form right now i tried with textalign center but still it is more on the leftdiv classcontainer div classrow div claspan6 offset3 form input classinputxxlarge typetext placeholderemail p stylelineheight 70px textalign centerbutton typesubmit classbtnconfirmbuttonp form div divdiv,"['html', 'css']" +452476,testing a concern module that uses activerecord scenarioi have extracted a concern called taggable it is a module that allows any model to support tagging i have included this concernmodule into models like user location places projectsi want to write tests for this module but do not know where to startquestion1 can i do isolation testing on the taggable concernin the example below the test fails because the test is looking for a dummy class table i am assuming it is doing this because of the has many code in taggable so as a result it expects dummyclass to be an activerecord object appmodelsconcernstaggablerbmodule taggable extend activesupportconcern included do has many taggings as taggable dependent destroy has many tags through taggings end def tagname namestrip tag tagfind or create by namename selftaggingsfind or create by tag idtagid endend testmodelsconcernstaggable testrbrequire test helpersclass dummyclassenddescribe taggable do before do dummy dummyclassnew dummyextendtaggable end it gets all tags do dummytagdummy tag dummytagsmust be instance of array endendpart of me thinks if i just test a model that has this module included inside of it like user that is enough of a test but i keep reading that you should test modules in isolation looking for some guidance strategy on what the right approach is,"['ruby-on-rails', 'ruby']" +452489,android terminalide terminalgcc error armeabigcc not found i am using terminalide as my development environment google code site herei am running terminalide v 202 the very latest my android versions areandroid 403software version 2145313 71ordthe rest are not likely pertinent but more on requesti am in a suitable development directory with a simple enough c source code file ready and run makei have never yet gotten any compilation to work successfully most likely there is a version mismatch with regard to what executable is available versus what the software is looking forheres the command and error messageterminalgcc c wall idatadatacomspartacusrexspartacusidefileslocalinclude testerc o testerodatadatacomspartacusrexspartacusidefilessystembinterminalgcc43 armeabigcc not foundmake testero error 127snafu of course i am not at all sure how to find out what the right compiler file names should be because on this nonrooted phone i do not have permissions to hunt through the path and find the actual executablesit may also be that path is set wrong all input appreciated,['android'] +452549,python custom logging across all modules taski have a collection of scripts and i would like them to produce unified logging messages with minimum alterations to modules doing logging the actual messagesi have written a small module custom logger which i plan to call from the main application once have it return a logger which i would then continue usingthe submodules i would be importing into the app should only or rather i wish them toshould only import logging as log so that nothing specific to my site is required to make them just run if someone else finds them usefulshould just log messages with loginfoerrormessage without adding anything sitespecific to themshould use the already configured root logger with all its formatting and handers and not affect the root loggers configurationcustom loggerpyimport loggingimport logginghandlersimport osimport sysdef getloggernameroot loglevelinfo logger logginggetloggername if logger name already exists return it to avoid logging duplicate messages by attaching multiple handlers of the same type if loggerhandlers return logger if logger name does not already exist create it and attach handlers else set loglevel to loglevel or to info if requested level is incorrect loglevel getattrlogging loglevelupper logginginfo loggersetlevelloglevel fmt asctimes filename18s levelname8s messages fmt date ymdttz formatter loggingformatterfmt fmt date handler loggingstreamhandler handlersetformatterformatter loggeraddhandlerhandler if loggername root loggerwarningrunning s s ospathbasenamesysargv0 joinsysargv1 return loggerthen comes the submodule which has a few test messages with examples of what works and what does notsubmodulepyimport sysimport custom loggerimport loggingclass subclassobject def init self nok no idea why since by default no name parameter it should return the root logger log logginggetlogger loginfomessage from subclass init ok works as expected log logginggetloggerroot loginfomessage from subclass init ok works as expected log custom loggergetloggerroot loginfomessage from subclass init def somemethodself ok but i would have to define log for every method which is unacceptable please see question below all code snippets log custom loggergetloggerroot loginfomessage from subclass somemethodand the main app apy nothing special hereusrbinpythonimport custom loggerimport submodulelog custom loggergetloggerroot logleveldebuglogdebugdebug messageloginfoinfo messagelogwarningwarning messagelogerrorerror messagea submodulesubclass this should produce a log messageasomemethod so should thisoutput that i am after and that i am getting just in an exteremely ugly way apy 20130408t030746bst custom loggerpy warning running apy 20130408t030746bst apy debug debug message20130408t030746bst apy info info message20130408t030746bst apy warning warning message20130408t030746bst apy error error message20130408t030746bst submodulepy info message from subclass init 20130408t030746bst submodulepy info message from subclass somemethodi want to be able to define a logger in the apy and then in the submodules only use the standard python logging library to make use of an already configured logger in the apyalso an ugly workaround if i place the below code after the imports in submodulepylog custom loggergetloggerrootit will be executed before my logger is configured in apy effectively making the submodule not my app configure logginganother workaround i considered within the constuctor of the subclass class i could define selflog custom loggergetloggerrootand then use selflogerrorsome error there must be a nicer way if you can suggest something useful or point out where i misunderstood the documentation i would be very gratefulps i have spent quite a bit reading the python logging howto basic and advanced and the cookbook so if i have missed something useful there please point it outthank you,['python'] +452643,what is the best way to return error message from function if face a logic error error such expired user invalid id then what is the best way to tell the parent method of this error from the following 1 throwing customized exception like the following tryif id does not match then throw new customexception1id does not matchcatchcustomexception exthrow excatchexception exthrow new customexceptionexerrorcodeexmessage2 return error message and code like if id does not match then thiserrorcode 1thismessage id does not match,"['c#', '.net']" +452649,adding new tab in product admin page like features tab attributes tab etc in prestashop version 153 i would like to add a new tab in product admin page like features tab attributes tab etc in ps version 15x with a custom modulei am adding this tab to the product edit page so that i can add option to upload product video to the adminhere is the screenshot of what i am trying to achieveediti found a solution here,['php'] +452670,determine if a view is on screen android i am a little bit stuck with this one first and foremost the following link has been useful however i have come up with a bit of an issue with visibilitythe link check view visibilityi have a scroll view parent and a number of subviews linearlayout tablelayout etc there are a number of items i set to viewgone within the xml androidvisibilitygonei have some simple code to determine whether it is visible or not using getvisibility however when i set the item to viewvisible and try to immediately getdrawingrect i get a rect with zeros across the board any further click gets the correct coordinatesnow this could be because the view has never been drawn as defined in the xml causing it to return no coordinates however i do set viewvisible before trying to determine screen visibility could it be that i need to get some kind of callback from say the ondraw or perhaps set the view visibility of hidden items within code a bit annoying some coderect scrollbounds new rectscrollgethitrectscrollboundsrect viewbounds new rectif viewgetvisibility viewgone viewsetvisibilityviewvisble viewboundsgetdrawingrectviewbounds if rectintersectsscrollbounds viewbounds do somthing layouts area as followsscrollviewlinearlayouttablelayoutbuttonhiddenviewof course it is highly likely i am going about this the wrong way altogether basically i just want to make sure that the scrollview positions itself so the view that has become visible can be seen in it is entiretyif any other information is required let me know,['android'] +452680,js get element by part of name or id here is an example of my form only inputs that i want but there is many others form nameinputform action methodpostinput typehidden nameid qtedje 77 idid qtedje 77 value0input typetext idid qte 77 nameprestation detail fields77qte collecte value0input typetext idid rec 77 nameprestation detail fields77reliquat conforme value0input typetext idid ren 77 nameprestation detail fields77reliquat non conforme value0input typecheckbox nameprestation detail fields77dechet non present value1 another tr input typehidden nameid qtedje 108 idid qtedje 108 value0input typetext idid qte 108 nameprestation detail fields108qte collecte value0input typetext idid rec 108 nameprestation detail fields108reliquat conforme value0input typetext idid ren 108 nameprestation detail fields108reliquat non conforme value0input typecheckbox nameprestation detail fields108dechet non present value1formwhat i want is to get values of inputs but as the form is built in php i do not know the line identifier 77 108is there a way to do something like getelementbynameid qtedje note i am not using any library and i do not plan to use one,['javascript'] +452748,overload a method or use default values c i am still relatively new to c and i cannot seem to figure out the difference in the following two ways of coding a function that may take one parameter or maybe two or three or more anyway heres my pointfunction overloadint aclassdosomethingint required do somethingint aclassdosomethingint required int optional do somethinghow is this different to default valueint aclassdosomethingint required int optional 0 do somethingi know in different circumstances one may be more suitable than another but what kinds of things should i be aware of when choosing between each of these options,['c++'] +452757,eclipse stops highlighting references after a while when i open a java file for editing in eclipse references highlighting works well for a while but then suddenly stops working after some minuteson this example parameters was the last variable correctly highlighted but now it is no longer working and not highlighting anything else it should highlight passwordtoggling mark occurrences off and back on does not solve it i have already tried restarting eclipse and rebooting the computer had this problem for weeks actuallythe only workaround i found so far is closing the file and reopening it but then it stops working again after some timefor info i am using eclipse 422 on windows 7 64 bit machine,"['java', 'android']" +452771,array initialization with a ternary operator i do not have access to the c11 specification therefore i cannot investigate this bug the following declaration rises an error during compilation int why2 1 1 12 34 the error is expected expression before and expected expression before,['c'] +452789,setting uiimageview content mode after applying a cifilter thanks for lookingheres my code ciimage result vignetteoutputimageselfmainimageviewimage nilselfmainimageviewcontentmode uiviewcontentmodescaleaspectfitselfmainimageviewimage uiimage imagewithciimageresultselfmainimageviewcontentmode uiviewcontentmodescaleaspectfitin here vignette is correctly set up filter and image effect is applying to the image correctly i am using a source image with resolution 500x375 my imageview has almost iphone screens resolution so to avoid stretching i am using aspectfitbut after applying effect when i am assigning the result image back to my imageview it streches no matter which uiviewcontentmode i use it does not work it seems it always applies scaletofill regardless the filter i have givenany idea why is this happening any suggestion is highly appreciated,"['iphone', 'ios', 'objective-c']" +452822,jquery add class to href if link contains specific text i have some dynamically populated links in a list on my site that link to files is it possible to use jquery to see if the name of the file ends with pdf and add a class to the href or similar if the link text ends with mp3for example i have the following links in my listdocument1pdfsong1mp3song2m4adocument2doci would like to detect the end letters and add different classes to the links so to the link which has the text document1pdf i would add the class pdf to the anchor element and the link with the text song1mp3 i would add the class mp3 to the anchor element,['jquery'] +452825,using moq how to setup a method call with an input parameter as an object with expected property values using moq how to setup a method call with an input parameter as an object with expected property values var storagemanager new mockistoragemanager storagemanagersetupe eadditisanyusermetadataadd method expects a usermetadata object which has firstname propertyi would like to make sure that an object of type usermetadata with the firstname of firstname1 has been passed,['c#'] +452837,thisabling horizontal scroll on an iphone website i am developing an iphone version of a wordpress driven website and i was wondering if there is any method to thisable horizontal scrolling when the website is open in safari for iphone right now i am half way through the development and just to check if i could thisable horizontal scrolling i have hidden any of the elements which were exceeding the screen width but still i can scroll horizontally to the right i tried putting the following code inside the style tags in the head but that did not helpbody overflowx hidden i have put the following meta code inside the head file to echo if the user is viewing the website from an iphone but it only thisables userpinching ie you cannot zoom in and zoom out by pinching the screenmeta nameviewport contentwidthdevicewidth initialscale10 maximumscale10 userscalablenoi am currently using an iphone 4 to check the website and the website can be accessed by going to this link looking forward to a solution from you guys thankssolution as suggested by riskbreaker there were a few elements which were exceeding the width of 312px which is why i could still swipe to the left and after adjusting the width of all such elements i thisabled horizontal swipe one thing which i learned is that hiding overflowx does not help in the case of an iphoneipad you have to reduce the width of all the elements to that of the width of your screen otherwise youll still be able to swipe horizontally,"['iphone', 'ios', 'css']" +452874,is there a memory overhead associated with heap memory allocations eg markers in the heap thinking in particular of c on windows using a recent visual studio c compiler i am wondering about the heap implementationassuming that i am using the release compiler and i am not concerned with memory fragmentation packing issues is there a memory overhead associated with allocating memory on the heap if so roughly how many bytes per allocation might this bewould it be larger in 64bit code than 32biti do not really know a lot about modern heap implementations but am wondering whether there are markers written into the heap with each allocation or whether some kind of table is maintained like a file allocation tableon a related point because i am primarily thinking about standardlibrary features like map does the microsoft standardlibrary implementation ever use its own allocator for things like tree nodes in order to optimise heap usage,['c++'] +452921,is it safe to use readerwriterlockslim in an async method since the readerwriterlockslim class uses thread id to see who owns the lock is it safe to use with async methods where there is no guarentee that all the method will be executed on the same thread for example systemthreadingreaderwriterlockslim readerwriterlock new systemthreadingreaderwriterlockslim private async task test readerwriterlockenterwritelock await taskyield do work that could yield the task readerwriterlockexitwritelock potentailly exit the lock on a different thread,"['c#', '.net']" +452924,creating one nuget package from multiple projects in one solution i have a solution that i am working on that contains 4 class library projects a b c d a and b could be considered the top level projects in the solution both a and b reference c and d stands alonethese four projects represent a group of services that i have made that handle an automated workflow they are all closely related and will only be used in one location the service manager so i do not want to split them into different solutionsmy problem is that i want to create a single nuget package that will contain all 4 libraries without having to build them all and gather up their dlls manually i know that i could technically achieve this by having either a or b reference the remaining projects but that is not a true relationship and i feel it should be avoidedi have done a lot of searching on this problem and i cannot find a solution other than manually collecting the dlls and building the package myself is there a way to achieve the result that i want using nugets featuresabilitiesnote in case the tags do not make it clear i am currently using vs2010 with a teamcity build server in case it is relevant i am also using git through a stash serveredit i just realized this might be important enough to mention these projects do reference other nuget packages that i will need to mark as dependencies,['c#'] +453001,validate a value in property so i heard that validating a value in a property like thisdummy example let us assume that i want my value without dotspublic string myprop set ifvaluecontains throw new argumentexceptionmust not contain value is wrong and i should avoid itbut in earlier days i was told that this is the good way we could use encapsulation there is just one place to check dry etcwhats wrong with my little example,['c#'] +453002,execute a method in java with restricted permissions is there any way i can use accesscontrollerdoprivileged with a new accesscontrolcontext to restrict access to classesmethods i would like to have a subroutine that can call untrusted code without access to touch the file system or open sockets the specific use case is allowing end users to provide fragments of code or scripts for example javascript or groovy that can execute with limited permissionswhat i am looking for is something like a normal security policy file scoped to the userprovided code rather than the whole jvm,['java'] +453029,c httpclient put for some reason my below code that used to work now consequently raises an exceptionpublic static async taskstring httpputstring inurl string infilepath using var handler new httpclienthandler allowautoredirect false using var client new httpclienthandler var content new streamcontentnew filestreaminfilepath filemodeopen fileaccessread fileshareread buffersize 4096 useasync true using var content new streamcontentnew filestreaminfilepath filemodeopen contentheadersremovecontenttype contentheadersaddcontenttype applicationoctetstream using var req new httprequestmessagehttpmethodput inurl string authinfo stringformat01 programconfigmediastoragelistfindo oname viz media engine testusername programconfigmediastoragelistfindo oname viz media engine testpassword authinfo converttobase64stringencodingdefaultgetbytesauthinfo reqheadersaddauthorization basic authinfo reqheadersremoveexpect reqheadersaddexpect reqheaderstransferencodingchunked true reqcontent content ignore certificate validation failures aka untrusted certificate certificate chains servicepointmanagerservercertificatevalidationcallback sender certificate chain sslpolicyerrors true using httpresponsemessage resp await clientsendasyncreq this part is specific to the setup on an expo were at if respstatuscode httpstatuscoderedirect respstatuscode httpstatuscodetemporaryredirect string redirecturl respheaderslocationtostring if redirecturlcontainsvmestore redirecturl redirecturlreplacevmestore 10230011 return await httpputredirecturl infilepath respensuresuccestatuscode return await respcontentreadasstringasync the exception i am getting issystemnotsupportedexception was unhandledhresult2146233067messagethe stream does not support concurrent io read or write operationssourcesystemstacktrace at systemnetconnectstreaminternalwriteboolean async byte buffer int32 offset int32 size asynccallback callback object state at systemnetconnectstreambeginwritebyte buffer int32 offset int32 size asynccallback callback object state at systemnethttpstreamtostreamcopybufferreadcallbackiasyncresult ar end of stack trace from previous location where exception was thrown at systemruntimecompilerservicestaskawaiterthrowfornonsuccesstask task at systemruntimecompilerservicestaskawaiterhandlenonsuccessanddebuggernotificationtask task at systemruntimecompilerservicestaskawaiter1getresult at vizwolfinnerservertoolshttpconnectorhttpputd 39movenext in cuserschristerdocumentsvisual studio 2012projectsvizwolfnewvizwolfinnerservertoolshttpconnectorcsline 202 end of stack trace from previous location where exception was thrown at systemruntimecompilerservicestaskawaiterthrowfornonsuccesstask task at systemruntimecompilerservicestaskawaiterhandlenonsuccessanddebuggernotificationtask task at systemruntimecompilerservicestaskawaiter1getresult at vizwolfinnerservertoolsvizapiconnectorvmeuploadmediad 0movenext in cuserschristerdocumentsvisual studio 2012projectsvizwolfnewvizwolfinnerservertoolsvizapiconnectorcsline 187 end of stack trace from previous location where exception was thrown at systemruntimecompilerservicesasyncmethodbuildercorethrowasyncb 1object state at systemthreadingexecutioncontextruninternalexecutioncontext executioncontext contextcallback callback object state boolean preservesyncctx at systemthreadingexecutioncontextrunexecutioncontext executioncontext contextcallback callback object state boolean preservesyncctx at systemthreadingqueueuserworkitemcallbacksystemthreadingithreadpoolworkitemexecuteworkitem at systemthreadingthreadpoolworkqueuethispatchinnerexception i am having a very hard time finding proper documentation and examples for httpclient and i am struggling with figuring out why this suddenly does not work a totally similar method with stringcontent instead of streamcontent works perfectlyit originally gets called from it is own thread and then like thispublic static async void vmeuploadmediastring inuploadlink string infilepath string result await httpconnectorhttpputinuploadlink infilepathanyone spot anything obviousthanksupdateturns out getting the expoguys to map their storagename with it is ip so i could go back to my original code was the best solution the problem i was having is something to do with allowautoredirect false the exception occured on httpresponsemessage resp await clientsendasyncreq even if there was no redirection really going on i am kind of lost as to why it was even happening but using this code everything is working nowpublic static async taskstring httpputstring inurl string infilepath using var client new httpclient using var content new streamcontentfileopenreadinfilepath contentheadersremovecontenttype contentheadersaddcontenttype applicationoctetstream using var req new httprequestmessagehttpmethodput inurl string authinfo stringformat01 programconfigmediastoragelistfindo oname viz media engine testusername programconfigmediastoragelistfindo oname viz media engine testpassword authinfo converttobase64stringencodingdefaultgetbytesauthinfo reqheadersaddauthorization basic authinfo reqheadersremoveexpect reqheadersaddexpect reqcontent content ignore certificate validation failures aka untrusted certificate certificate chains servicepointmanagerservercertificatevalidationcallback sender certificate chain sslpolicyerrors true using httpresponsemessage resp await clientsendasyncreq respensuresuccestatuscode return await respcontentreadasstringasync thanks to the people who were trying to help,['c#'] +453065,php trigger fatal error i would like to be able to throw a fatal uncatchable error in my php class when a user of my class abuses it for something i did not intend i do not want himher to be able to recover with a catch clausei know about trigger error but i can only make it issue warnings or notices,['php'] +453091,group objects by property in javascript how to convert this food apple type fruit food potato type vegetable food banana type fruitinto this type fruit foods apple banana type vegetable foods potatousing javascript or underscore,['javascript'] +453109,rake dependency not executing but invoke works i have been trying to run rake dbtestclone structure but it keeps failing to rebuild the database i finally looked at the task itselftask clone structure dbstructuredump dbtestload structure when i run the trace i have noticed that dbtestload structure is not getting executed rake dbtestclone structure trace invoke dbtestclone structure first time invoke dbstructuredump first time invoke environment first time execute environment execute dbstructuredump invoke dbtestpurge first time invoke environment execute dbtestpurge execute dbtestclone structurenow when i change the clone structure task to invoke load structuretask clone structure dbstructuredump dbtestload structure do db namespacetestload structureinvokeendeverything suddenly works rake dbtestprepare trace invoke dbtestclone structure first time invoke dbstructuredump first time invoke environment first time execute environment execute dbstructuredump invoke dbtestpurge first time invoke environment execute dbtestpurge execute dbtestclone structure invoke dbtestload structure first time invoke dbtestpurge execute dbtestload structure invoke dbstructureload first time invoke environment invoke dbload config first time execute dbload config execute dbstructureloadwhat could possibly be causing this behavior i am using rails 3214 and rake 1010updated i upgraded rails to 3213 from 3211 and it is still a problemupdated the second i upgraded rails to 3214 and rake to 1010 and it is still a problem,['ruby'] +453136,iabresult billing service unavailable on device response 3billing unavailable i am trying to use inapp billingmiabhelper new iabhelperthis billing key miabhelperstartsetupnew iabhelperoniabsetupfinishedlistener override public void oniabsetupfinishediabresult result if resultissuccess logdtag problem setting up inapp billing result and getting the errorproblem setting up inapp billing iabresult billing service unavailable on device response 3billing unavailablewhy tried to clear cache of the play store did not work for me,['android'] +453137,nested attributes unwanted validation despite of reject if all blank i am new to rails so any advise is greatly appreciatedi have a class entry with nested attributes addressesappmodelsentryrbclass entry activerecordbase has many addresses dependent destroy accepts nested attributes for addresses allow destroy true reject if all blankendwith class addresses like thisappmodelsaddressrbclass address activerecordbase belongs to entry validates zip presence trueendand in the nested form i have appviewentries formhtmlslim simple form forentry do f ferror notification entryaddressesbuild forminputs fsimple fields for addresses do address render address form f addressthe idea is that when the form is rendered the build will create a empty address in addition to the current addresses listed in database when the changes are saved if the new address created is still empty it will get rejected and not saved to the databasehowever the validation in the addressrb is doing the validation before the saving hence the user cannot proceed with the saving action is there anything i left out,['ruby-on-rails'] +453170,localization for security identity in net i was looking to implement a named pipe for serviceclient communication in net and came across this code that while initializing server side of the pipe had to set up a security descriptor for the pipe they did it this waypipesecurity pipesecurity new pipesecurity allow everyone read and write access to the pipepipesecuritysetaccessrulenew pipeaccessruleauthenticated users pipeaccessrightsreadwrite accesscontroltypeallow allow the administrators group full access to the pipepipesecuritysetaccessrulenew pipeaccessruleadministrators pipeaccessrightsfullcontrol accesscontroltypeallowbut i am looking at it and i am concerned about specifying sids as strings or authenticated users and administrators parts what is the guarantee that they will be called that say in chinese or some other language,"['c#', '.net']" +453217,has anyone figured out how to make a javafx tableview act like a jtable i followed example 1311 alternative solution of cell editing from the offical tableview tutorial but i want my tableview to act like a jtable this means that when a cell gets focus it is ready to be edited and using the arrow keys or the enter key should instantly commit the edit and move to the next cellthis is what i have gone so farfirst i addedtablegetselectionmodelsetcellselectionenabledtruethen i tried to modify the class editingcellclass editingcell extends tablecellperson string private textfield textfield public editingcell override public void updateselectedboolean selected superupdateselectedselected if selected createtextfield settextnull setgraphictextfield textfieldrequestfocus textfieldselectall else string value textfieldgettext if value null commiteditvalue else commiteditnull override public void canceledit supercanceledit settextstring getitem setgraphicnull override public void updateitemstring item boolean empty superupdateitemitem empty if empty settextnull setgraphicnull else if isediting if textfield null textfieldsettextgetstring settextnull setgraphictextfield else settextgetstring setgraphicnull private void createtextfield textfield new textfieldgetstring textfieldsetminwidththisgetwidth thisgetgraphictextgap 2 textfieldfocusedpropertyaddlistenernew changelistenerboolean override public void changedobservablevalue extends boolean arg0 boolean arg1 boolean arg2 if arg2 commitedittextfieldgettext textfieldsetonkeypressednew eventhandlerkeyevent override public void handlekeyevent t if tgetcode keycodeenter tgetcode keycodeup tgetcode keycodedown tgetcode keycodeleft tgetcode keycoderight tconsume string value textfieldgettext if value null commiteditvalue else commiteditnull else if tgetcode keycodeescape canceledit private string getstring return getitem null getitemtostring the tableview i got is a mess i have to click enter key twice to end editing and it would not commit the edit but instead cancels itcan anyone point me in the right direction,['java'] +453233,how to createreadwrite json files in qt5 qt5 has a new json parser and i want to use it the problem is that it is not too clear about what the functions do in laymans terms and how to write code with it that or i could be reading it wrongi want to know the code on creating a json file in qt5 and what encapsulates mean,['c++'] +453272,does phantomjs support geolocations i am trying to run qunit test cases with phantomjs one of my tests are hanging in when phantomjs try to access the navigatorgeolocation function of dom same test is working fine in the browser just hangs in the console with phantomjs doe phantomjs support geolocations any suggestionbreaks in the following if condition ifnavigatorgeolocation windownavigatorgeolocationwatchpositionupdatelocation null frequency 30,['javascript'] +453308,java is it bad practice not to have a class constructor i want to make a helper class that deals with formatting ie has methods to remove punctuation and convert between types as well as reformatting names etc this does not seem like it will need any fields its only purpose is to get passed things to convert and return them reformatted is it bad practice to leave out a constructor if so what should my constructor be doing i was looking at this link and noticed that the class it describes lacks a constructor,['java'] +453335,under what conditions might instancesrespondtoselector return true but performselector throw an exception i have code thistributed in a library which looks like thisif nsstring class instancesrespondtoselector selectorjsonvalue nsstring jsonstring nsstring alloc initwithdata jsondata encoding nsutf8stringencoding autorelease dict jsonstring performselector selectorjsonvaluefor some reason a nscfstring jsonvalue unrecognized selector sent to instance exception is getting thrown when the performselector method gets called this is code that is thistributed in a library that i wrote but i cannot reproduce or debug it myself instead a thirdparty is reporting this problem under what conditions could instancesrespondtoselector while actually calling the method using performselector throw an exceptioneditthere is a case which could explain why this occurs but it does not make sense if the developers were to do something like thisimplementation nsstring ourhappycategory boolinstancesrespondtoselectorselaselector return yesendit would explain why the code is executing but it would of course be a very bad thing to do is there a way this problem could occur that makes sense,"['ios', 'objective-c']" +453355,open source static source code analysis tool security oriented for java i am looking for an open source static source code analysis tool that can be used for security testing of an android application i need to make sure that my application is pci compliantan example of a nonopen source tool is fortifyanyone can help in providing a list of recommended software,"['java', 'android']" +453358,how to execute a function after some time javascript i want to write a javascript code where i can excute a function after exactly 30 minutessay i have a function called getscore and another function called getresult i want those functions to be executed after exactly 30 minutesit is for a quiz purpose the quiz duration is 30 minutes so after the time passesboth functions should be executed,['javascript'] +453419,how to convert rgba to a transparencyadjustedhex i am wondering if there is a tool to convert rgba into hex which can translate the visible rgbacolor including transparency into a hex valuesay i have this rgba01292554which is sort of a light blue i would like to know if there is a way to get the same light blue visible color in hex so i do not want the converted 0081ff but something close to the color visible on screenquestionhow to convert rgba to a transparencyadjustedhex,['css'] +453424,php locked ip address i lock the ip addressdoes this mean than user can only login in with the same ip address or will the user logout and have to relogin to get a new sessionif isset sessionlast ip false sessionlast ip serverremote addr if sessionlast ip serverremote addr session unset session destroy,['php'] +453429,observing changes in android content observer for audiomediaexternal content uri hello everyone sorry if you think that this question is repeated but i am asking this question because seriously i am not getting the solution for itactually i am developing an android app in which i have to detect changes in android sd card for audio files with the file name file path and operation performed upon it example if i am adding a file in my sd card then i want to knowname of the file which is addedpath of the fileoperation addpreviously i have tried file observer but for that i have to apply it on each and every directory so i searched for some other solution and got the info about audiomediaexternal content uri then i created a content observer like thisuriobserverjava which is a content observerclass uriobserver extends contentobserver public uriobserverhandler handler superhandler todo autogenerated constructor stub override public void onchangeboolean selfchange todo autogenerated method stub superonchangeselfchange logdinstant getting changes this is the code for registration for ituriobserver observer new uriobservernew handlerlogdinstant registered content observerthisgetapplicationcontext getcontentresolver registercontentobserver mediastoreimagesmediaexternal content uri false observerlogdinstant registered content observerit let me know that some change has been occur in sdcard related to audio files but it does not gives any sort of info about which file has been added edited or deletedthen i searched for for solution and got this postandroid how to detect a change in mediastore when connected over mtpin this post some code is given by bhiefer as an answer which i think it could work so i tried to implement but i am not able to do so i do not have the privilege of comment anywhere in my stackoverflow account so i am not able to contact bhiefe for asking him for some helpso anyone could suggest me what can i do for this if any body has some solution for it or anybody who can guide me how to find solution for iti will be very grateful to you all if you can help meupdate wednesday 10 april 2013 144736 istif anyone knows methods for querying audiomediaexternal content uri for its latest changes the it could help but mcursor contextgetcontentresolverquery audiomediaexternal content uri null null null idmcursormovetolastdoesnt give the latest changes so any other method to get the latest changes,['android'] +453443,thisplay a checkbox list instead of multiple select i have a model mymodel with a serialized attribute a describing an array of symbolsthis code works form for my model do f fselect a mymodelas multiple true end the parameters are correct my model a a value1 a value2 i want to transform this multiple select into a set of checkboxes like this form for my model do f mymodelaseach do a value fcheck boxa value end end it works too but the parameters are not the same at all my model a value1 1 a value2 1 i think of 2 solutions to return to the first solutiontransform my check box into check box tag replace multiple select and add some javascript to check select values when user clic on check box tags then the parameter will be the same directly in the controlleradd a litte code into the controller for adapting my paramswhat solution is the less ugly or is there any other one,['ruby-on-rails'] +453461,is it possible to get a notification when any location provider is enabledthisabled and ascertain what action occurred i wish to receive a notification when the user enables or thisables either network or gps locations and importantly i wish to know which one they have changed and how i have a broadcast receiver for the androidlocationproviders changed broadcast intent and this is receiving the correct broadcast i now need to try and determine which action has occurred ie enable or thisable and which provider has been changed i know that i could keep the state of each provider and then when i receive notification that they have changed then i could work out what has changed i am looking for a more standard method of doing this the broadcast intent does not seem to have any extras to indicate which provider has changedthis is the code i have currently public class locationproviderchangedreceiver extends broadcastreceiver private final static string tag locationproviderchangedreceiver override public void onreceivecontext context intent intent if intentgetactionmatchesandroidlocationproviders changed logitaglocation providers changed bundle bundle intentgetextras if bundle null logdtag no extras data else logdtag bundle received of size bundlesize and this is a small extract from my manifest usespermission androidnameandroidpermissionaccess coarse location usespermission androidnameandroidpermissionaccess fine location receiver androidnamelocationproviderchangedreceiver androidexportedfalse intentfilter action androidnameandroidlocationproviders changed category androidnameandroidintentcategorydefault intentfilter receiverthis would be perfect if there was an extra within the broadcast that stated which provider had changed and whether it was enabled or thisabled unfortunately this is not the case is anyone aware of any mechanism by which i can determine what state has changed without maintaining my own state variablesin an ideal world i would monitor for changes constantly but only listen for location changes occasionally i would like to avoid constantly monitoring for location changes,['android'] +453488,resetremove css styles for element only i am sure this must have been mentionedasked before but have been searching for an age with no luck my terminology must be wrongi vaguely remember a tweet i saw a while ago that suggested there was a css rule available that would remove any styles previously set in the stylesheet for a particular elementa good use example might be in a mobilefirst rwd site where much of the styling used for a particular element in the smallscreen views needs resetting or removing for the same element in the desktop viewa css rule that could achieve something likeelement all noneeaxmple usage mobile first element margin 0 10 transform translate3d0 0 0 zindex 50 thisplay block etc etcmedia only screen and minwidth 980px element all none so we could quickly remove or reset styling without having to declare every propertymake sense,['css'] +453531,expression that takes a datetimeoffset causes visual studio internal compiler error i was trying to mock an interface which takes a datetimeoffset as one of its parameters all of a sudden visual studio started reporting an internal compiler error and that it has stopped working after a lot of trials i started removing files one by one and then code line by line this reduced to the below code which reproduces this errorpublic class testclass public interface itest void testdatetimeoffset date public void test2 var mock new mockitest mocksetupx xtestnew datetime2012 1 1 the issue seems to be the line mocksetupx xtestnew datetime2012 1 1if i comment it the compiler works fine also the issues is that i am setting up a new datetime which fits in a datetimeoffsetis this a bug in moq or vs2012 anyone ever got this error beforeupdatethe following code sample also results in a compile error both with the regular visual studio 2012 compiler and with roslyn ctp september 2012using systemusing systemlinqexpressionspublic interface itest void testdatetimeoffset datepublic class testclass expressionactionitest t x xtestnew datetime2012 1 1the error1csc error cs0583 internal compiler error 0xc05 at address 00d77afb likely culprit is bindthis code has nothing to do with moq,['c#'] +453568,sql and delphi recursive mechanism for creating a tree from a table the dbms i am working with is mysql the programming environment is delphi 7 which does not really matter for this examplei have a table called subject where i store all book subjects in the system subjects can have a parentchild relationship like science can be divided let us say into math and physics whereas math can be subdivided into calculus algebra geometry and on we gowhat i would like is create a tree populated with the date from that table please help me do that it even does not matter what language you use for illustration purposes it simply can be pseudocodethe database diagram for the subject table looks like thisthe subject table definitiondrop table if exists subjectcreate table if not exists subject comment subject id int unsigned not null auto increment subject id subject varchar25 not null subject name parent id int unsigned null default null parent id as seen from primary key subject id the diagram refers to unique subject the subject id field index parent id constraint fk subject parent foreign key parent id references subject subject id on delete restrict on update cascade engineinnodb default charsetutf8populating the subject table with some dummy datainsert into subject subject parent id values science null mathematics 1 calculus 2 algebra 2 geometry 2 languages null english 6 latin 6select statement returns thisselect from subjecta subject id a subject a parent id aa a 1 a science a null aa 2 a mathematics a 1 aa 3 a calculus a 2 aa 4 a algebra a 2 aa 5 a geometry a 2 aa 6 a languages a null aa 7 a english a 6 aa 8 a latin a 6 astored proceduresdelimiterdrop procedure if exists get parent subject listcreate procedure get parent subject list begin select subject id subject from subject where parent id is null order by subject ascenddrop procedure if exists get child subject listcreate procedure get child subject list in parentid intbegin select subject id subject from subject where parent id parentid order by subject ascenddelimiter next is my delphi procedure that attempts to populate a tree view with data but as can be seen further it cannot get any deeper than the second levelprocedure tform1createsubjecttreeviewsender tobjectvar i integerbegin i 0 q1sqlclear q1sqladdcall get parent subject list q1open q1first while not q1eof do begin treeviewitemsaddnil q1fields1value q2sqlclear q2sqladdcall get child subject list vartostrq1fields0value q2open q2first while not q2eof do begin treeviewitemsaddchildtreeviewitemsitemi q2fields1value q2next end i treeviewitemscount q1next endendthis is what this snippet of code does science mathematics languages english latinbut i would like it to look like this science mathematics calculus algebra geometry languages english latin,"['mysql', 'sql']" +453580,unexpected performance penalty in java i implemented a gapbuffer list in java and i cannot figure out why it is getting such a performance penalty similar code written in c behaves as expected inserting to the middle of the list is much faster than cs implementation of list but the java version is behaving strangelyhere is some benchmarking informationaddingremoving 10 items the end of the dynamic arrayarraylist 683 millisecondsgapbufferlist 416 millisecondsaddingremoving 10 items a random spot in the dynamic array arraylist add 721 milliseconds arraylist remove 612 millisecondsarraylist 13 milliseconds gapbufferlist add 1293 milliseconds gapbufferlist remove 2775 millisecondsgapbufferlist 4068 millisecondsaddingremoving 10 items the beginning of the dynamic arrayarraylist 2422 millisecondsgapbufferlist 13 millisecondsclearly the gapbufferlist is the better optionas you can see when you insert to the beginning of the list the gap buffer behaves as expected it is many many many times better than arraylist however when inserting and removing at a random spot in the list the gap buffer has a strange performance penalty that i cannot explain even stranger is the fact that removing items from the gapbufferlist is slower than adding items to it according to every test i have run so far it takes about three times longer to remove an item than it does to add one despite the fact that their code is almost identicaloverridepublic void addint index t t if index 0 index backlength gapsize throw new indexoutofboundsexception if gappos index int diff gappos index for int q 1 q diff q backgappos q gapsize backgappos q else if index gappos int diff gappos index for int q 0 q diff q backgappos q backgappos gapsize q gappos index if gapsize 0 increasesize backgappos t gapsizeoverridepublic t removeint index if index 0 index backlength gapsize throw new indexoutofboundsexception if gappos index 1 int diff gappos index 1 for int q 1 q diff q backgappos q gapsize backgappos q else int diff index 1 gappos for int q 0 q diff q backgappos q backgappos gapsize q gapsize return backgappos indexthe code for the gap buffer can be found at here and the code for the benchmark entrypoint can be found here you can replace any reference to flowexception with runtimeexception,['java'] +453602,can elements contain blocks in bem i have been told i was wrong for writing the code like i have below i suppose elements can not contain blocks and its bad bemul classbnav li classbnav item a href classbnav item link item a li uli thought about writing it this way but it does not show the hierarchy as wellul classbnav li classbnav item a href classbnav link item a li ulhere is another way but to me it seems worse than the example aboveul classbnav li classbnav item a href classblink item a li ulis the way i originally coded it wrong if so why and what is the best alternative,"['html', 'css']" +453633,how to make the font lucida sans unicode render the same way in ie9 and chrome i am using the font lucida sans unicode on a project and i have encountered an issue with it in ie9 there is some space beneath the text and i do not know why this is happening in chrome there is not as much space here is an example the border you see is from the select element on click function in the developer tool in ie9this is in browser mode ie9 and document mode ie9 standardsand this is browser mode ie8 and document mode ie8as you can see there is less space beneath the p chrome thisplays it the same way as ie8 modethe difference in rendering is causing trouble when i want to align stuff when it is ok in one browser it is not ok in the otherdoes anyone know why this is happening and more importantly how to fix itthanks in advance for all replieseditfiddle,"['html', 'css']" +453669,show mysql tables starting with prefix i am trying to get mysql tables by name starting with prefix someprefix but i get wrong resultsi tried to execute show columns like someprefix but problem is that i have also tables with prefix someprefix2 and those tables are also being returned in resultmy question is is there a way to exclude tables with similar prefix from result,"['php', 'mysql']" +453681,what xamarinios does with memory management when it compiles c to native code what xamarinios does about memory management with usual il we have garbage collector which takes care of objects not in use and reliefs programmer from calling delete how this works when xamarin compiles code to native who cleans objects which are not used anymorethis question answers how compilation works but does not explain the memory management part how monotouch works,['c#'] +453685,how to add a header to a csv file in python i have tried many solutions to add a header to my csv file but nothings working properly here they are i used the writerow method but my data are overwriting the first rowi used the dictwriter method but i do not know how to fill it correctly here is my codecsv csvdictwriteropendirectory csvcsv wt fieldnames stuff1 stuff2 stuff3 delimiter csvwriteheaderstuff1 stuff2 stuff3i got a 2 arguments instead of one error and i really do not know whyany advice,['python'] +453765,java gc tuning for strings profiling the application i figured out that there are a lot of strings on heap in my situation strings are created on heap and not interned and they are not literals are there are specific gc tuning techniques to follow when the number of strings in the application are very high i stumbled across the gc settings xxusecompressedstrings or xxusestringcache but not sure this will help did any body try these settingsjava version 160 22javatm se runtime environment build 160 22b04java hotspottm 64bit server vm build 171b03 mixed mode,['java'] +453808,retrieving a braintree customers subscriptions i want to collect all of a braintree customers subscriptions when i browse to a customers page in the gateway i can see their subscriptions but it does not seem that a method like subscriptions exists for braintreecustomer or that i can search for braintreesubscriptions by customer idthere are roundabout ways that i can access all of a customers subscriptions but they are very slow for example i can retrieve all of the customers transactions and for each transaction get the subscription id if it exists and then retrieve the subscription with that id this involves a lot of communication with the braintree api and i was hoping for a more efficient solutionoh and i am programming this in rails but the question does not seem railsspecific,"['ruby-on-rails', 'ruby']" +453828,how to set multiple tags to a button i have 16 buttons and i tag them to pair some terms set to buttons and imported from sqlite database so i tag them like this labelforbutton and tagforbutton class mystruct public mystruct string lab string t label lab tag t private string label private string tag mdbhelperopen cursor c mdbhelpergetspojnicegeneratewhereclause arraylistmystruct labelsa new arraylistmystruct arraylistmystruct labelsb new arraylistmystruct labelsaaddnew mystructcgetstring2 1 this tag should be the same to button that matches labelsbaddnew mystructcgetstring3 1 labelsaaddnew mystructcgetstring4 2 labelsbaddnew mystructcgetstring5 2 labelsaaddnew mystructcgetstring6 3 labelsbaddnew mystructcgetstring7 3 labelsaaddnew mystructcgetstring8 4 labelsbaddnew mystructcgetstring9 4 labelsaaddnew mystructcgetstring10 5 labelsbaddnew mystructcgetstring11 5 labelsaaddnew mystructcgetstring12 6 labelsbaddnew mystructcgetstring13 6 labelsaaddnew mystructcgetstring14 7 labelsbaddnew mystructcgetstring15 7 labelsaaddnew mystructcgetstring16 8 labelsbaddnew mystructcgetstring17 8 collectionsshufflelabelsa collectionsshufflelabelsb a1settextlabelsaget0label a1settaglabelsaget0tag a1setonclicklistenerclicklistener b1settextlabelsbget0label b1settaglabelsbget0tag b1setonclicklistenerclicklistener a2settextlabelsaget1label a2settaglabelsaget1tag a2setonclicklistenerclicklistener b2settextlabelsbget1label b2settaglabelsbget1tag b2setonclicklistenerclicklistenerso i need a1 and b1 to have same tags also a2 and b2 and so onbut i also need for some other reason to all a buttons have tag for example a and all the bs b so how to set multiple in my case two tags to one buttonediti added this to my stringxmlitem typeid namekolona1item typeid namekolona2then added tagsa1settagridkolona1 labelsaget0tagb1settagridkolona2 labelsaget0tag,"['java', 'android']" +453839,overriding return type in function template specialization i would like to specialize a function template such that the return type changes depending on the type of the template argumentclass returntypespecializationpublic templatetypename t t item normally just return the template typetemplatetypename tt returntypespecializationitem when a float is specified return an int this does not worktemplatefloatint returntypespecializationitem is this possible i cannot use c11,['c++'] +453848,where should rx be used i am thinking about bringing in rx to my workplace but the more i learn about it the more i think it does not really give you an advantagewe have a lot of server apps that take input data at one end and output it at the other end which is perfect for the actor model and infinite threading scalability till now i have used concurrentqueues to implement message passing and i thought that rx might be a good more functional alternative that can make concurrency more implicit that helps me move some of the data flow decisions from imperative code to the declarations of observablesbut reading about it and trying it i do not see much advantage over using regular old threads with concurrentqueues for message passing what advantages does rx give me it is always said that even though net 45 made a lot of rx obsolete though async and dataflow it is still good for handling event streams what cases present event streams and how do i identify them,['c#'] +453877,what is the proper way to cast hibernate querylist to list i am a newbie with hibernate and i am writing a simple method to return a list of objectsmatching a specific filter listfoo seemed a natural return typewhatever i do i cannot seem to make the compiler happy unless i employ an ugly suppresswarningsimport javautillistimport orghibernatequeryimport orghibernatesessionpublic class foo public session acquiresession all db opening connection etc removed since the problem is in compilation not at runtime return null suppresswarningsunchecked public listfoo activeobjects session s acquiresession query q screatequeryfrom foo where active return listfoo qlist i would like to get rid of that suppresswarnings but if i do i get the warningwarning unchecked cast from list to listfooi can ignore it but i would like to not get it in the first place and if i remove the generic to conform to list return type i get the warningwarning list is a raw type references to generic type listeshould be parameterizedi noticed that orghibernatemapping does declare a list but it is a different type altogether query returns a javautillist as a raw type i find it odd that a recent hibernate 40x would not implement parameterized types so i suspect that it is me instead doing something wrongit looks very much like cast hibernate result to a list of objects but here i have no hard errors the system knows type foo and i am not using a sqlquery but a straight query so no joyi have also looked at hibernate class cast exception since it looked promising but then i realized that i do not actually get any exception my problem is just that of a warning a coding style if you willdocumentation on jbossorg hibernate manuals and several tutorials do not seem to cover the topic in such detail or i did not search in the right places when they do enter into detail they use onthefly casting and this on tutorials that werent on the official jbossorg site so i am a bit warythe code once compiled runs with no apparent problem that i know of yet and the results are the expected onesso am i doing this right am i missing something obvious is there an officialor recommended way to do it,['java'] +453878,phantom js synchronous ajax request network err xmlhttprequest exception 101 i am making a synchronous ajax call ajax settings async false this works wellnow i am trying to write an automated test for this in phantomjs and i am getting this errornetwork err xmlhttprequest exception 101 i checked my service logs and it seems like service is not getting any request,['javascript'] +453908,throwing a 401 header with php without redirect i have a php function which adds bad ips to a mysql tableeach page on my site then checks the table and throws a http 401 header if a match is foundifbadcrawler headerhttp11 401 unauthorized headerlocation error401phpis it possible to do this without changing the urlthanks,['php'] +454035,corrupted actionbar look i have noticed this issue a long time ago but only now i was able to prepare demo which clearly reproduces it the issue is presend on 21 emulator and on my ics 403 devicein application i have asynctask which may adjust visibility of actionbar indeterminate progress and reinit menu by calling invalidateoptionsmenu this should hide refresh icon this is working ok until i modify listview data model and call notifydatasetchanged on adapter after such action actionbar may have broken viewexpected viewbroken view last item thisappears forever or blank space added insted of in some casesthe causing code is in onpostexecute override protected void onpostexecutevoid result superonpostexecuteresult for int i 0 i 10 i adapteritemsaddi adapternotifydatasetchanged activitystoploading void stoploading if loadersdecrementandget 0 setsupportprogressbarindeterminatevisibilityfalse invalidateoptionsmenu any idea why is this happening and in most cases because of updating listview adapter or perhaps some over view updates if i remove line adapternotifydatasetchanged actionbar will not be broken in the demo but in real application it may be broken because of another reason also cannot determine exactly all the issue causesproject demonstrating an issue opened actionbarsherlock issue updkeep digging on this issue seems that not exactly adapternotifydatasetchanged causes invalid look but the requestlayout call by the adapterviewadapterdatasetobserver which is listening for the data set changed event in the listviewthe workaround exists i can call invalidateoptionsmenu and setsupportprogressbarindeterminatevisibility in the handlerpost but it forces to use even custom implementation of fragmentpageradapter which calls fragmentsethasoptionsmenu in the delayed handlerpostwhat i want is to find the most efficient way to invalidate view and actionbar without corrupting it,['android'] +454045,call jquery function i have a jquery function like the followingfunction myfunction messagershow titlemy title msgthe message content showtypefade style right bottom if certain condition is true i would like to invoke myfunction and a popup message will thisplay how can i call myfunction so that it will be something like onclick,['jquery'] +454058,how to make grid view scroll horizontally not vertically in android i have a dynamic grid view means its content varies so if the number of items increases it makes vertical scroll i want to make it as horizontal scroll please suggest some solution for this,['android'] +454100,closing the c windows form by avoiding textbox validation this is a winform c question i have a textbox with a validating event listener to validate the content of the textbox against a regular expressionafter the validation if entered value is not properi am showing the messagebox and i am cancelling the event so that mouse cursor move back to the textbox which has improper valuethis is working fine when i move out from that textbox to other buttonstextboxesbut when i enter improper value and close the form with the close button on right top corner it validates the textbox contents and throws up the messagebox and form doesnot close as i am cacelling the eventthe problem is when i click the x button on the right top corner of the form i do not want the validation to be fired because i am closing the form anyway how can i do thisi will post the code snippet as soon as possible,['c#'] +454122,http status 500 error instantiating servlet class pkgcoreservlet i am creating simple servlet and deploying it in tomcat server but i am getting the following errorhttp status 500 error instantiating servlet class pkgcoreservletfile structure on the tomcat serverwebapps aarya webinf webxml srcfolder pkg coreservletclasswebxmlxml version10 encodingutf8webapp version24 xmlns xmlnsxsi xsischemalocation 2 4xsdservlet servletnameaaryaservletservletname servletclasspkgcoreservletservletclaservletservletmapping servletnameaaryaservletservletname urlpatterncoreservleturlpattern servletmappingwebappcoreservletjavapackage pkgimport javaioimport javaxservletimport javaxservlethttp public class coreservlet extends httpservlet private static final long serialversionuid 1lpublic void dogethttpservletrequest reqhttpservletresponse res throws servletexceptionioexception printwriter out resgetwriter ressetcontenttypetexthtml outprintlnthis is first servlet example url i am giving is httplocalhost8080aaryacoreservleti try by restarting tomcat but i am getting same error where i am doing wrong,['java'] +454156,gcc nullptr issue i am porting existing code to compile under gcc 472 and have run into a strange issue with nullptr i have managed to boil it down to a simple test caseinclude stdiohconst char g marker original valuevoid setmarker const char s g marker schar test1 return setmarker i was here 1 nullptrchar test2 setmarker i was here 2 return nullptrchar test3 return setmarker i was here 3 charnullint main char returnvalue test1 printf sn g marker compile this with g testcpp o test stdc0xthe output i would expect is i was here 1 but i get original value indicating that setmarker is never calledcalling either test2 or test3 gives the expected outputthe code i am working with uses the pattern seen in test3 originally without the cast in front of the null that gave an error on invalid conversion from int to char so i started changing all those nulls to nullptr unfortunately that just does not behave correctlyi am likely forced to change the code to use the pattern in test2 which i prefer anyway but i am curious to know if this is a bug in the compiler or if i am missing something,['c++'] +454201,adding comment in properties files by using following block of code in buildxml filepropertyfile filedefaultproperties commentdefault properties entry keysourcedir value1 entry keydirpublish value1 entry keydirpublishhtml value1 propertyfilei am able to generate defaultproperties file with following file contentssourcedir1dirpublish1dirpublishhtml1i want to know how can i add my comments in the generated file eg the generated properties should have the following content default configurationsourcedir1dirpublish1 source configurationdirpublishhtml1how can i do it dynamically using ants buildxml,['java'] +454228,stop the webcam streaming of getusermedia without page refreshing i am trying to close the webcam with javascript function it has to be closed after receive some ajax response but it seems impossible to close without refreshing the page all the methods for close it like videosrc null videopauseetc do not work at all in any browser the unique way is to close the stream passed as parameter on the success functions so there is any way to use this object outside the function success to close the webcami know that this question has been asked before stopclose webcam using getusermedia and rtcpeerconnection chrome 25 but my needs are different so i would need some help to solve this problemthanksedit my working code trying to close the webcamnavigatorgetusermedia navigatorgetusermedia navigatormozgetusermedia navigatorwebkitgetusermedia navigatormsgetusermediaifnavigatorgetusermedia var video constraints mandatory maxheight 480 maxwidth 640 optional var self this selfnavigatorgetusermedia audio false video video constraints selfonsuccess onerrorelse alertan error has occurred starting the webcam stream please revise the instructions to fix the problemfunction onsuccestream var video documentgetelementbyidwebcam ifnavigatorwebkitgetusermedia navigatormozgetusermedia videosrc windowurlcreateobjecturlstream else ifnavigatormsgetusermedia future implementation over internet explorer else videosrc stream selflocalstream stream videoplayfunction onerror alertthere has been a problem retrieving the streams did you allow accessfunction closewebcamconnection thislocalstreamstopuffit is really complicated to post here the code xd,['javascript'] +454240,jquery how to return the appended element i use jquery api append to add a new elementselectorappenddiv classtestdivi want the expression return the just appended element for my further use however it returns selector so how can i let jquery to return the just appended element to avoid reselecting it,"['javascript', 'jquery']" +454253,using address instead of longitude and latitude with google maps api i have heard that it is possible to submit an address instead of longitude and latitude and this would be much more feasible for my system the user has to input their address when creating their profile and their profile afterwards will then thisplay a google maps of their house i currently have the google maps api working perfectly with longitude and latitudehead meta httpequivcontenttype contenttexthtml charsetutf8link relstylesheet typetextcss hrefcsscss titlelogin pagetitlemeta nameviewport contentinitialscale10 userscalableno style typetextcss html height 100 body height 100 margin 0 padding 0 mapcanvas height 100 stylescript typetextjavascript srcsensorfalsescriptscript typetextjavascript function initialize var mapoptions center new googlemapslatlng52640143128685 zoom 15 maptypeid googlemapsmaptypeidroadmap var map new googlemapsmapdocumentgetelementbyidmap mapoptionsvar marker new googlemapsmarker position new googlemapslatlng52640143128685 map map title mark on map googlemapseventadomlistenerwindow load initializescriptheadplease could somebody assist me to alter my code so that it enables the google maps api to request an address in its place because i want to read the address of the user directly from mysql database,['javascript'] +454263,set uiwebview content not to move when keyboard is shown i have done large enough research but could not find answer to my questionsuppose i have a webview in which i have some text fields some of them are placed on the bottom of screen so that when keyboard appears it should hide that fields after keyboard appears the content of webview slides up in order to make that fields visible the problem is that i do not want the content to slide upquestion is how can i thisable that feature of webview or somehow make the content not scroll upthanks any help would be appreciated,['objective-c'] +454277,multiple string resource files with similar keys in android i have an android application that needs to thisplay strings found under the resources but there can be multiple stringsxml files ie strings1xml strings2xml and so third the string key can reside in different stringsnxml files now if a key is found in lets say strings1xml it should be thisplayed without looking into the other string files with the same keyis it possible in android i have done this thing in my net application but seems not doable in android infact android gives the compilation error when i enter values against duplicate keys in multiple stringsxml fileseditthe reason for doing this is there are different clients running my application lets assume for clienta i added the key company with the value abc and in my default stringsxml file there is already a default company name with the same key company but with the defualt value default company now if clienta opens my application the company name should be abc and default company for clients otherthan clienta,['android'] +454330,numerical ode solving in python i am new to python so at this moment in time i can only very basic problemshow do i numerically solve an ode in pythonconsider ddotuphi u sqrtuwith the following conditions u0 149907anddotu0 0with the constraint 0 phi 7pithen finally i want to produce a parametric plot where the x and y coordinates are generated as a function of uthe problem is i need to run odeint twice since this is a second order differential equationi tried having it run again after the first time but it comes back with a jacobian error there must be away to run the twice all at oncehere is the errorodepackerror the function and its jacobian must be callable functionswhich the code below generates the line in question is the sol odeintimport numpy as npfrom scipyintegrate import odeintimport matplotlibpyplot as pltfrom numpy import linspacedef fu t return u npsqrtutimes linspace01 7 nppi 10y0 149907yprime0 0yvals odeintf yprime0 timessol odeintyvals y0 timesx 1 sol npcostimesy 1 sol npsintimesplotxypltshowediti am trying to construct the plot on page 9classical mechanics taylorhere is the plot with mathematicain27 sol ndsolveyt yt sqrtyt y0 166707928 y0 0 y t 0 10piin28 ysol yt sol1in30 parametricplot1ysolcost 1ysolsint t 0 7 pi plotrange 2 2 25 25,['python'] +454336,how to set event listener breakpoints in chromes elements tab i am struggling with setting breakpoints in dynamically generated dom elements where different event handlers are also binded from javascript this basically means that i have a nice looking dom structure which is not part of the initially received http response it is purely built on client sidenow the problem is that chromes elements tab only allows me to set breakpoints forsubtree modification orattribute modification ornode removalis it possible to set a breakpoint in the dynamically created dom elements dynamically created event listener somehow see image attached i want to set the breakpoint into the listenerbodynote that i cannot use sourcesscripts tab either since it only shows me the initially received static http content response and i cannot set breakpoint either in the code referenced in the event listeners accordion since it will only show me the event listener when it is getting attached not when it is getting firedany ideas,['javascript'] +454339,postgresql select statement very slow due to small joinwhere filter 20130529 updated question with latest configuration and extra info earlier i was testing in a virtualbox image now i am testing on the productive server which reflects the real world much better question should be fully clear now if you have helped me before read again carefullycurrently i have found a query that is very slow in postgresql though i do not understand how it can be slow i scaled it down a bit so it is much smaller to post here and much faster but still slowlittle background in this project i have adverts that belong to users users are part of an area within the country an area can have multiple child areas so the area table is a tree a network is assigned to an area when filtering on a network it should filter on that area and all its area childs in the tree because i cannot query against a endless tree i have table that flattens this full treeso with 1 query select area id from network area flatdeep where network id 1 i get all areas that belong to network 163 64 65 66 67 68 69 70this makes querying very easythe slow query before testing everything has been vacuum analyzedexplain analyze select a0 id as id0from advert a0 inner join member m6 on a0 user id m6 id inner join area a7 on m6 area id a7 idwhere a0 status in 1 and m6 status in 1 and a7 id in select area id from network area flatdeep where network id in 1order by a0 created date desclimit 60 query plan limit cost41103469553 rows60 width12 actual time9327134581 rows60 loops1 nested loop cost4110229127669 rows3967 width12 actual time9326134534 rows60 loops1 join filter a7 id m6 area id rows removed by join filter 22566 nested loop cost411082163016 rows317633 width24 actual time004939638 rows226 loops1 index scan backward using advert created date idx on advert a0 cost0762064 rows317633 width16 actual time00134357 rows2834 loops1 filter status 1 rows removed by filter 21 materialize cost41107338 rows15 width8 actual time04 rows8 loops2834 nested loop cost41107330 rows15 width8 actual time00310073 rows8 loops1 hashaggregate cost41104118 rows8 width4 actual time00230026 rows8 loops1 bitmap heap scan on network area flatdeep cost4374106 rows15 width4 actual time00110015 rows8 loops1 recheck cond network id 1 bitmap index scan on idx c29e880034128b91 cost0436 rows15 width0 actual time0707 rows8 loops1 index cond network id 1 index only scan using area pkey on area a7 cost0401 rows1 width4 actual time0203 rows1 loops8 index cond id network area flatdeeparea id heap fetches 8 index scan using member pkey on member m6 cost0461 rows1 width8 actual time0203 rows1 loops226 index cond id a0 user id filter status 1 rows removed by filter 0 total runtime 134698 ms23 rowsthe subquery itself isexplain analyze select area id from network area flatdeep where network id in 1 query plan bitmap heap scan on network area flatdeep cost4374106 rows15 width4 actual time002024 rows8 loops1 recheck cond network id 1 bitmap index scan on idx c29e880034128b91 cost0436 rows15 width0 actual time00120012 rows8 loops1 index cond network id 1 total runtime 0051 ms5 rowswhich results in 63 64 65 66 67 68 69 70so i have tried to hard code in the ids and expected it to be faster but is notexplain analyze select a0 id as id0from advert a0 inner join member m6 on a0 user id m6 id inner join area a7 on m6 area id a7 idwhere a0 status in 1 and m6 status in 1 and a7 id in 63 64 65 66 67 68 69 70order by a0 created date desclimit 60 query plan limit cost17558821755897 rows60 width12 actual time5659456670 rows60 loops1 sort cost17558821756007 rows498 width12 actual time5659356621 rows60 loops1 sort key a0 created date sort method topn heapsort memory 27kb nested loop cost01754162 rows498 width12 actual time004753808 rows4478 loops1 nested loop cost0390399 rows286 width4 actual time002717492 rows8004 loops1 seq scan on area a7 cost014478 rows8 width4 actual time070823 rows8 loops1 filter id any 63646567686970integer rows removed by filter 5081 index scan using idx 70e4fa78bd0f409c on member m6 cost046838 rows152 width8 actual time001208 rows10 loops8 index cond area id a7 id filter status 1 rows removed by filter 2 index scan using idx 54f1f40ba76ed395 on advert a0 cost04749 rows19 width16 actual time0203 rows1 loops8004 index cond user id m6 id filter status 1 rows removed by filter 1 total runtime 56744 ms18 rowstime 57995 msi tried to put the subquery in the inner joinexplain analyze select a0 id as id0from advert a0 inner join member m6 on a0 user id m6 id inner join area a7 on m6 area id a7 id and m6 area id in select area id from network area flatdeep where network id in 1where a0 status in 1 and m6 status in 1 order by a0 created date desclimit 60 query plan limit cost4373496673 rows60 width12 actual time295742443 rows60 loops1 nested loop cost437231159910 rows3967 width12 actual time295642394 rows60 loops1 nested loop semi join cost437230217351 rows3967 width20 actual time294942099 rows60 loops1 join filter m6 area id network area flatdeeparea id rows removed by join filter 223 nested loop cost0223085309 rows316797 width16 actual time002818612 rows2829 loops1 index scan backward using advert created date idx on advert a0 cost0762064 rows317633 width16 actual time00123802 rows2834 loops1 filter status 1 rows removed by filter 21 index scan using member pkey on member m6 cost0461 rows1 width8 actual time0303 rows1 loops2834 index cond id a0 user id filter status 1 rows removed by filter 0 materialize cost4374114 rows15 width4 actual time04 rows8 loops2829 bitmap heap scan on network area flatdeep cost4374106 rows15 width4 actual time090015 rows8 loops1 recheck cond network id 1 bitmap index scan on idx c29e880034128b91 cost0436 rows15 width0 actual time0606 rows8 loops1 index cond network id 1 index only scan using area pkey on area a7 cost0237 rows1 width4 actual time0203 rows1 loops60 index cond id m6 area id heap fetches 60 total runtime 42538 ms22 rowsi tried to get rid of the subquery and make a proper join statement to network area flatdeep i strongly prefer this versionexplain analyze select a0 id as id0from advert a0 inner join member m6 on a0 user id m6 id inner join area a7 on m6 area id a7 id inner join network area flatdeep n14 on a7 id n14 area id and n14 network id in 1 where a0 status in 1 and m6 status in 1 order by a0 created date desclimit 60 query plan limit cost30031183003133 rows60 width12 actual time6296863045 rows60 loops1 sort cost30031183003351 rows934 width12 actual time6296762991 rows60 loops1 sort key a0 created date sort method topn heapsort memory 27kb nested loop cost029892 rows934 width12 actual time015760280 rows4478 loops1 nested loop cost0440166 rows536 width4 actual time002920488 rows8004 loops1 nested loop cost012069 rows15 width8 actual time00150084 rows8 loops1 index scan using idx c29e880034128b91 on network area flatdeep n14 cost06047 rows15 width4 actual time090019 rows8 loops1 index cond network id 1 index only scan using area pkey on area a7 cost0401 rows1 width4 actual time0405 rows1 loops8 index cond id n14 area id heap fetches 8 index scan using idx 70e4fa78bd0f409c on member m6 cost028388 rows152 width8 actual time001278 rows10 loops8 index cond area id a7 id filter status 1 rows removed by filter 2 index scan using idx 54f1f40ba76ed395 on advert a0 cost04757 rows19 width16 actual time0303 rows1 loops8004 index cond user id m6 id filter status 1 rows removed by filter 1 total runtime 63125 ms21 rowschanging in to does not helper eitheri tried using exists as suggested by wilderplasser with an answer belowwhen i either remove the order by or the network criteria the query is fast 2ms but why cannot they play nice togethernow then when i change the network id from 1 to 10 the query is extremely fast like i want 10 is a root network that contains all areas so apperently the less results the join needs to filter out the faster the query isthe structure looks like thisarea mapped to network 10 which contains 5089 areas in flat table and is fast area 1 network 1 which contains 8 areas in flat table and is slow more areas alot more areas etcchanging network 1 to 10 gives 3265 msto summarize the differencenetwork 1 has 8 areas in network area flatdeepnetwork 10 has 5089 areas in network area flatdeepso inner join using network 1 is very slow inner join using network 10 is very fast same behavior with subqueriesadvert table353804 rows table publicadvert column type modifiers storage stats target description id integer not null default nextvaladvert id seqregclass plain user id integer not null plain advert category id integer not null plain currency id integer not null plain advert kind id integer not null plain advert price id integer plain external source id integer plain status integer not null plain type integer not null plain title character varying60 not null extended description text not null extended price numeric192 default nullnumeric main accepting bids boolean not null plain promoted boolean not null plain edited date timestamp0 without time zone default nulltimestamp without time zone plain created date timestamp0 without time zone not null plain archived date timestamp0 without time zone default nulltimestamp without time zone plain views integer not null plain checked date timestamp0 without time zone default nulltimestamp without time zone plain archived by cron boolean not null plain unarchived by cron boolean not null plain containting forbidden words boolean not null plain external id character varying255 default nullcharacter varying extended new product boolean not null plain indexes advert pkey primary key btree id advert external idx uq unique btree external id external source id advert archived date idx btree archived date advert checked date idx btree checked date advert created date idx btree created date advert edited date idx btree edited date advert external id idx btree external id advert price idx btree price advert status idx btree status advert type idx btree type advert views idx btree views idx 54f1f40b38248176 btree currency id idx 54f1f40b54b67d66 btree advert price id idx 54f1f40b9a2e6cff btree advert kind id idx 54f1f40ba76ed395 btree user id idx 54f1f40bb167b375 btree external source id idx 54f1f40bd4436821 btree advert category idforeignkey constraints fk 54f1f40b38248176 foreign key currency id references currencyid on delete restrict fk 54f1f40b54b67d66 foreign key advert price id references advertpriceid on delete restrict fk 54f1f40b9a2e6cff foreign key advert kind id references advertkindid on delete restrict fk 54f1f40ba76ed395 foreign key user id references memberid on delete cascade fk 54f1f40bb167b375 foreign key external source id references externalsourceid on delete restrict fk 54f1f40bd4436821 foreign key advert category id references advertcategoryid on delete restrictreferenced by table advert photo constraint fk 1c939974d07eccb6 foreign key advert id references advertid on delete cascade table banner constraint fk 6f9db8e7d07eccb6 foreign key advert id references advertid on delete set null table advertbid constraint fk fccdba75d07eccb6 foreign key advert id references advertid on delete cascadehas oids noarea table5089 rows table publicarea column type modifiers storage stats target description id integer not null default nextvalarea id seqregclass plain network id integer plain parent id integer plain selectable boolean not null plain indexes area pkey primary key btree id idx d7943d6834128b91 btree network id idx d7943d68727aca70 btree parent idforeignkey constraints fk d7943d6834128b91 foreign key network id references networkid on delete restrict fk d7943d68727aca70 foreign key parent id references areaid on delete cascadereferenced by table network area flat constraint fk 10aae5b2bd0f409c foreign key area id references areaid on delete cascade table area language constraint fk 17d42f7dbd0f409c foreign key area id references areaid on delete cascade table area zip code constraint fk 62a3bf90bd0f409c foreign key area id references areaid on delete cascade table member constraint fk 70e4fa78bd0f409c foreign key area id references areaid on delete restrict table network area flatdeep constraint fk c29e8800bd0f409c foreign key area id references areaid on delete cascade table area constraint fk d7943d68727aca70 foreign key parent id references areaid on delete cascadehas oids nomember table182450 rows table publicmember column type modifiers storage stats target description id integer not null default nextvalmember id seqregclass plain language id integer not null plain area id integer not null plain company id integer plain external source id integer plain email character varying255 not null extended password character varying40 not null extended status integer not null plain name character varying150 not null extended zip code character varying20 extended phone number character varying120 default nullcharacter varying extended using email service boolean not null plain edited date timestamp0 without time zone default nulltimestamp without time zone plain created date timestamp0 without time zone not null plain hiding on own network boolean not null plain staff boolean not null plain superuser boolean not null plain external id character varying255 default nullcharacter varying extended last login date timestamp0 without time zone default nulltimestamp without time zone plain deleted adverts integer not null plain indexes member pkey primary key btree id user email idx uq unique btree email user external idx uq unique btree external id external source id idx 70e4fa7882f1baf4 btree language id idx 70e4fa78979b1ad6 btree company id idx 70e4fa78b167b375 btree external source id idx 70e4fa78bd0f409c btree area id user external id idx btree external id user name idx btree name user status idx btree statusforeignkey constraints fk 70e4fa7882f1baf4 foreign key language id references languageid on delete restrict fk 70e4fa78979b1ad6 foreign key company id references companyid on delete set null fk 70e4fa78b167b375 foreign key external source id references externalsourceid on delete restrict fk 70e4fa78bd0f409c foreign key area id references areaid on delete restrictreferenced by table user link constraint fk 4c2dd538a76ed395 foreign key user id references memberid on delete cascade table advert constraint fk 54f1f40ba76ed395 foreign key user id references memberid on delete cascade table banner constraint fk 6f9db8e7a76ed395 foreign key user id references memberid on delete set null table user admin module permission constraint fk 74fee7cea76ed395 foreign key user id references memberid on delete cascade table user admin resource permission constraint fk c9fcf279a76ed395 foreign key user id references memberid on delete cascadehas oids nonetwork area flatdeep table10177 rows table publicnetwork area flatdeep column type modifiers storage stats target description id integer not null default nextvalnetwork area flatdeep id seqregclass plain network id integer not null plain area id integer not null plain created date timestamp0 without time zone not null plain indexes network area flatdeep pkey primary key btree id area flatdeep idx uq unique btree area id network id created date idx c29e880034128b91 btree network id idx c29e8800bd0f409c btree area idforeignkey constraints fk c29e880034128b91 foreign key network id references networkid on delete cascade fk c29e8800bd0f409c foreign key area id references areaid on delete cascadehas oids noshort server config version postgresql 924 on x86 64unknownlinuxgnu compiled by gcc gcc 447 20120313 red hat 4473 64bit name current setting source shared buffers 1800mb configuration file work mem 4mb configuration fileconclusionthe more data less filtered out the faster the query is i am a bit clueless now how can postgresql be so slow on this again 40ms does not look extremely slow but with the real query with a big select statement queries are 15s most of the time and can take up to 3sall filtering is done on indexes the ordering is done on an index toodoes anyone have an idea how to improve this simple filter i clearly need to separate data,['php'] +454405,is it possible to horizontally center an inline element without extra markup or styling parent containers the question is basically already stated in the title but to clarify i am trying to horizontally center an anchor a in a main content areai would like to do this withoutusing fixed widthsadding extra markup an extra parent div for examplestyling the parent container so setting the parent to textaligncenter for examplesetting the a as a full width block i would like to keep the clickable area a big as the link itselfso basically i would like to do this just by styling the anchor itself in css in a dynamic shrinkwrap way i have been trying but have not found a way yet does anyone know how to do this,"['html', 'css']" +454472,how to use fused multiplyadd fma instructions with sseavx i have learned that some intelamd cpus can do simultanous multiply and add with sseavx flops per cycle for sandybridge and haswell sse2avxavx2i like to know how to do this best in code and i also want to know how it is done internally in the cpu i mean with the superscalar architecture let us say i want to do a long sum such as the following in ssesum a1b1 a2b2 a3b3 where a is a scalar and b is a simd vector eg from matrix multiplicationsum mm set1 ps00fa1 mm set1 psa0 b1 mm load psb0sum mm add pssum mm mul psa1 b1a2 mm set1 psa1 b2 mm load psb4sum mm add pssum mm mul psa2 b2a3 mm set1 psa2 b3 mm load psb8sum mm add pssum mm mul psa3 b3my question is how does this get converted to simultaneous multiply and add can the data be dependent i mean can the cpu do mm add pssum mm mul psa1 b1 simultaneously or do the registers used in the multiplication and add have to be independentlastly how does this apply to fma with haswell is mm add pssum mm mul psa1 b1 automatically converted to a single fma instruction or microoperation,['c'] +454492,unable to select a result from the select2 search results i am using the select2 for on of my search boxes i am getting the results from my url but i am not able to select an option from it i want to use the productproductname as the text to be shown after selection is there anything that i have missed out or any mistake that i have made i have included select2css and select2minjsjqueryjs function dataformatresultproduct var markup table classproductresulttr markup td classproductinfodiv classproducttitle productproductname div if productmanufacturer undefined markup div classproductsynopsis productmanufacturer div else if productproductoptions undefined markup div classproductsynopsis productproductoptions div markup tdtrtable return markup function dataformatselectionproduct return productproductname documentreadyfunction e7select2 placeholder search for a product minimuminputlength 2 ajax url myurl datatype json data functiontermpage return productname term results functiondatapage return results dataresult object formatresult dataformatresult formatselection dataformatselection dropdowncssclass bigdrop escapemarkup functionm return m this is my resut objectresult objectproductnamesamsung galaxy s3manufacturersamsungproductoptionscolormemoryproductoptiondescsilver32gbproductnamesamsung salaxy s3manufacturersamsungproductoptionscolormemoryproductoptiondescgraphite32gbproductnamesamsung galaxy s3manufacturersamsungproductoptionscolormemoryproductoptiondescsilver16gb,"['php', 'html']" +454510,how to expose behavior from a directive with isolated scope how can i expose a method from a directive i know that i should use attributes for data but i really want to expose behavior not data something that the parent controller can calet us say my dom looks likediv ngappmain div ngcontrollermyctrl button ngclickcall callbutton div idcontainer mydirective div divdivjavascriptangularmodulemain controllermyctrl functionscope scopecall function scopemyfn directivemydirective function return scope controller functionscope scopemyfn function consolelogmyfn called jsfiddle if the scope is commented out ie the directive does not have isolated scope it works just fine when i press the button myfn is called and logs to consoleas soon as i uncomment scope it does not work myfn is defined on child scope and not easily available to the parentin my case i think that polluting the parent scope is a bad idea and i would really like to avoid itso how can i expose a function from directive to the parent controller or how can i invoke a method on directive from parent controller,['javascript'] +454521,python filetell giving strange numbers i am using python 330 on windows 64bit i have a text file as shown below see bottom for download link at mediafirehellodata1blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blahdata2blah blah blah blah blah blah blah blah blah blah blahdata3 emptydata4 emptyi am trying to navigate around the file and thus i use tell to figure out what my position is however when reading through the lines of the file as shown below i get a very strange resultfopentesttxtwhile true a freadline print formatrepraftell if a breakthe resulthellon 7n 9data1blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blahn 18446744073709551714n 99n 101data2blah blah blah blah blah blah blah blah blah blah blahn 164data3 emptyn 179n 181data4 empty 194 194whats with the 18446744073709551714 for the 3rd line though it looks like an impossible value fseek18446744073709551714 is an acceptable value that apparently does bring me to the end of the 3rd line though i cannot seem to figure out whyeditopening in binary mode gives no problems with tellfopentesttxtrbwhile true a freadline print formatrepraftell if a b breakthe resultbhellorn 7brn 9bdata1blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blahrn 97brn 99brn 101bdata2blah blah blah blah blah blah blah blah blah blah blahrn 164bdata3 emptyrn 179brn 181bdata4 empty 194b 194the testtxt text file is downloadable here just a tiny 194 bytes,['python'] +454527,what does new auto do what does it mean when i use new auto consider the expressionnew auto5what is the type of the dynamically allocated object what is the type of the pointer it returns,['c++'] +454536,sqlite and storing images i wonder which way is better to store images in memorystoring images as blob in dborsaving images to file and store only path to it in databasewhat way is more efficient i suppose that storing files paths requires more operations because we need to refer to db and then to file but i am not sure if this is less efficent than keeping whole images in db,['android'] +454547,how to show page preloader only once while entering through domain name so i have jquery page preloader on main page like thisscript typetextjavascript windowloadfunction preloaderdelay700fadeoutslow div idpreloader classpreloaderdivthis shows 4 timeswhen i enter the site through domain namewhen i refresh main page by f5when i click on logo i must go to main page when i clicked thatwhen i click ahomea menu itembut i want to show it only on first two timesso the first idea which came in my mind is delete div class to not show preloader image over whole page when i clicking logo or menu item by js and have used thisdocumentgetelementbyidpreloaderclassname testbut then i realized that by clicking menu item to load main page again i create new copy of document so my preloader has his class again and showed up so i decided to use ajax and to not reload whole page by clicking menu item or logo now i use this script typetextjavascript documentreadyfunction blog logoclickfunction containerloadblog documentgetelementbyidpreloaderclassname test scriptso when i click logo or menu item i load my category called abloga in container and my side bar looks like this a hrefjavascript idlogoi classlogoiali classm bloga idblog hrefjavascripti classiconiblogaliso it works preloader appear only when you open site through domain name but 1 problem appear when i open category avideoa i have adress like this mysitecomvideoand when i came back to main page through logo or menu i have same adress because content loading without reload whole page and adress does not change how i can fix it help me please i just want to show my preloader only once when i came through domain name or refresh main page by f5 i already feel dizzy because i only know html and css but today start to learn ajax and jquery help me in this matter,"['javascript', 'jquery']" +454549,is there any way to detect if a database table exists with laravel i want to be able to create a table usingschemacreatemytablefunctiontable tableincrementsid tablestringtitlebut before that i would like to check if the table already exists perhaps something likeschemaexistsmytablehowever the above function does not exist what else can i use,['php'] +454553,force browser to reload all cache after site update is there a way to force the clients of a webpage to reload the cache ie images javascript etc after a server has been pushed an update to the code base we get a lot of help desk calls asking why certain functionality no longer works a simple hard refresh fixes the problems as it downloads the newly updated javascript filefor specifics we are using glassfish 3x and jsf 21x this would apply to more than just jsf of courseto describe what behavior i hope is possiblewebsite a has two images and two javascript files a user visits the site and the 4 files get cached as far as i am concerned no need to redownload said files unless user specifically forces a hard refresh or clears their cache once a site is pushed an update to one of the files the server could have some sort of metadata in the header informing the client of said update if the client chooses the new files would be downloadedwhat i do not want to do is put metatag in the header of a page to force nothing from ever being cachedi just want something that tells the client an update has occurred and it should get the latest once something has been updated i suppose this would just be some sort of versioning on the client sidethanks for your time,['javascript'] +454557,getting contentmessage from httpresponsemessage i am trying to get content of httpresponsemessage it should be messageaction does not existsuccessfalse but i do not know how to get it out of httpresponsemessagehttpclient httpclient new httpclienthttpresponsemessage response await httpclientgetasynchttpactiontxtblocktext converttostringresponse wrongin this case txtblock would have valuestatuscode 200 reasonphrase ok version 11 content systemnethttpstreamcontent headers vary acceptencoding keepalive timeout15 max100 connection keepalive date wed 10 apr 2013 204637 gmt server apache2216 server debian xpoweredby php5337squeeze14 contentlength 55 contenttype texthtml,['c#'] +454560,kinect sdk align depth and color frames i am working with kinect sensor and i am trying to align depth and color frames so that i can save them as images which fit into each other i have spent a lot of time going through msdn forums and modest documentation of kinect sdk and i am getting absolutely nowherebased on this answer kinect converting from rgb coordinates to depth coordinatesi have the following function where depthdata and colordata are obtained from nui locked rectpbits and mappeddata is the output containing new color frame mapped to depth coordinatesbool mapcolorframetodepthframeunsigned char depthdata unsigned char colordata unsigned char mappeddata inuicoordinatemapper coordmapper get coordinate mapper m psensornuigetcoordinatemappercoordmapper nui depth image point depthpoints new nui depth image point640 480 hresult result coordmappermapcolorframetodepthframenui image type color nui image resolution 640x480 nui image resolution 640x480 640 480 reinterpret castnui depth image pixeldepthdata 640 480 depthpoints if failedresult return false int pos 0 int colorrun reinterpret castintcolordata int mappedrun reinterpret castintmappeddata for each pixel of new color frame for int i 0 i 640 480 i find the corresponding pixel in original color frame from depthpoints pos depthpointsiy 640 depthpointsix set pixel value if it is within frame boundaries if pos 640 480 mappedruni colorrunpos return trueall i get when running this code is an unchanged color frame with removed white all pixels where depthframe had no information,['c++'] +454567,how to rename root key in json serialization with jackson i am using jackson for json serialization of a list of objectshere is what i getarraylistid1nametest namebut i want this rootnameid1nametest name ie showing the string i want as the root namebelow is my approach to thisinterfacepublic interface myinterface public long getid public string getnameimplementation classjsonrootnamevalue rootnamepublic class myimpl implements myinterface private final long id private string name public myimplfinal long idfinal name thisid id thisname name getters json serializationpublic class myserializer public static string serializelistfinal listmyinterface lists check for null valuethrow exception final objectmapper mapper new objectmapper mapperconfigureserializationconfigfeaturewrap root value true return mapperwritevalueasstringlists testfinal listmyinterface list new arraylistmyimplmyimpl item new myimpl1ltest namelistadditemfinal string json myserializerserializelistlistsystemoutprintlnjsonhere is what i getarraylistid1nametest namebut i want this rootnameid1nametest name ie showing the string i want as the root namei have tried all suggested solutions i could find but failed to achieve my goal i have looked atjackson custom collection serialization to jsonhow do i rename the root key of a json with java jacksonjackson custom collection serialization to jsonor am i missing something i am using jackson 1912 for this any help in this regard is welcome,['java'] +454590,sql server create table with foreign key i want to validate the proper handling of foreign keys in table here are my two tables being created below it is possible that a person may not have an address listed so i want it to be null otherwise i would like to reference a primary key from the address table and store it in the person table as a foreign key it is also possible that we may have an address object without a persontable for a personcreate table person personid int identity primary key fname varchar50 null mi char1 null lname varchar50 null addressid int foreign key references addressaddressid nulltable for addresscreate table address addressid int identity primary key street varchar60 null city varchar50 null state varchar2 null zip varchar10null intersection1 varchar60 null intersection2 varchar60 nullalso q2 i have never worked with triggers but i am assuming the way to handle an insert would be to use a stored procedure to insert the address first get the primary key then pass it to a stored procedure to insert into person table,['sql'] +454601,determining querys progress oracle plsql i am a developer on a web app that uses an oracle database however often the ui will trigger database operations that take a while to process as a result the client would like a progress bar when these situations occuri recently thiscovered that i can query vsession longops from a second connection and this is great but it only works on operations that take longer than 6 seconds this means that i cannot update the progress bar in the ui until 6 seconds has passedi have done research on wait times in vsession but as far as i have seen that does not include the waiting for the queryis there a way to get the progress of the currently running query of a session or should i just hide the progress bar until 6 seconds has passed,['sql'] +454609,sql check if entry in table a exists in table b i have a definition table that i know is not being maintained very well lets call this table a i have another table call it table b that is much smaller and ideally should be a subset of table a but i know that table a is somewhat stale and does not contain new entries that are in table bnote that tables a and b have different columnstable aid name blah blah blah blahtable bid namei want all rows in table b such that the id in table b does not exist in table a so this is not does not match a row in table a i want only rows in table b where the id does not exist at all in table a,['sql'] +454662,can i install laravel without using composer i would like to know if i can install or use the laravel php framework on any webserver without using composer php packagedependency manager every timei am learning php and frameworks and i am working on a cms based on laravel for practicei would like to be able to drop it onto any webserver without having to use composer every timeif i run composer install the first time locally then all the dependencies should be present correctthen i should be able to drop it onto any server with all of the files including the vendor directory,['php'] +454663,how can we split one 100 gb file into hundred 1 gb file this question came to mind when i was trying to solve this problemi have harddrive with capacity 120 gb of which 100 gb is occupied by a single huge file so 20 gb is still freemy question is how can we split this huge file into smaller ones say 1 gb each i see that if i had 100 gb free space probably it was possible with simple algorithm but given only 20 gb free space we can write upto 20 1gb files i have no idea how to delete contents from the bigger file while reading from it any solution it seems i have to truncate the file by 1 gb once i finish writing one file but that boils down to this questonis it possible to truncate a part of a file how exactlyi would like to see an algorithm or an outline of an algorithm that works in c or c preferably standard c and c so i may know the lower level details i am not looking for a magic function script or command that can do this job,"['c++', 'c']" +454667,how to get utc time in python i have search a bunch on stackexchange for a solution but nothing does quite what i need in javascript i am using the following to calculate utc time since jan 1st 1970function utcnow var now new date var utc dateutcnowgetutcfullyear nowgetutcmonth nowgetutcdate nowgetutchours nowgetutcminutes nowgetutcseconds nowgetutcmilliseconds return utcwhat would be the equivalent python code,['python'] +454670,placeholder text misaligned in uitextfield of uisearchbar i am trying to customize uisearchbars font through appearance proxy it works but somehow the placeholder text is not centered vertically i tried to set the vertical alignment property the placeholder text would get centred but text entered would be slightly below the center line is there any way to fix thisedit code i used to add custom fontuitextfield appearancewhencontainedin uisearchbar class nil setfont uifont customfontwithsize 17,"['iphone', 'ios']" +454688,how do i thisplay todays date on ssrs report i want to show up todays date as report generated date on ssrs reporthow can i do that should i use any variable please help me i am newbie to ssrsfor example refer this image,['sql'] +454708,qsort and issues with it the following is my code and qsort produces strange resultinclude stdiohinclude stdlibhchar values 0x020x040x0b0x160x240x300x480x6cint compare const void a const void b return inta intb int main int i qsort values 8 sizeofchar compare for i 0 i 8 i printf 0x values i return 0the output of this is program is2 6c 48 30 24 4 b 16though it should have been the same as the input can someone please explain the reason why it is so and how i can correct it,['c'] +454720,deck of cards java i have created my deck of cards that deals every card and a suit until there is no card remaining for my project i need to split it up into 3 classes which includes a driver class i first created one class with everything so i knew how to make it all workpublic class deckofcards2 public static void mainstring args int deck new int52 string suits spades hearts diamonds clubs string ranks ace 2 3 4 5 6 7 8 9 10 jack queen king initialize cards for int i 0 i decklength i decki i shuffle the cards for int i 0 i decklength i int index intmathrandom decklength int temp decki decki deckindex deckindex temp thisplay the all the cards for int i 0 i 52 i string suit suitsdecki 13 string rank ranksdecki 13 systemoutprintln rank of suit now trying to split it up into 3 classes i am getting red sqiggle lines on all my decksuit variables on my deckofcards class i dont know how to fix itpublic class deckofcards private card thecard private int remainingcards 52 deckofcards thecard new card public void shuffle for int i 0 i decklength i int index intmathrandom decklength int temp decki decki deckindex deckindex temp remainingcards public void deal for int i 0 i 52 i string suit suitsdecki 13 string rank ranksdecki 13 systemoutprintln rank of suit systemoutprintlnremaining cards remainingcards card classpublic class card int deck new int52 string suits spades hearts diamonds clubs string ranks ace 2 3 4 5 6 7 8 9 10 jack queen king card for int i 0 i decklength i decki i dealer classpublic class dealer public static void mainstringargs systemoutprintlnthe deck will randomly print out a card from a full deck each time deckofcards player new deckofcards playerdeal,['java'] +454739,mocking a method that return generics with wildcard using mockito i am using mockito 195 i have the following codepublic class classa public list extends myinterface getmyinterfaces return nullpublic static void testmock listmyinterface interfaces new arraylist classa classamock mockclassaclass whenclassamockgetmyinterfacesthenreturninterfaces i get a compilation error for the thenreturninterfaces sayingthe method thenreturnlistcapture1of extends myinterface in the type ongoingstubbinglistcapture1of extends myinterface is not applicable for the arguments listmyinterfacehowever when i use the thenanswer method of mockito i do not get the error can anyone tell me whats going on why do i get the error when i use the thenreturn methodis there any other way to solve this problem when classa is provided by a 3rd party and cannot be modified,['java'] +454869,sql ranking query to compute ranks and median in sub groups i want to compute the median of y in sub groups of this simple xy table x y groups gid x y medians gid x y 01 4 00 01 4 00 01 402 3 00 02 3 07 5 10 07 5 10 07 515 1 20 15 1 19 6 20 19 6 21 5 20 21 5 20 21 527 1 30 27 1 30 27 1in this example every x is unique and the table is already sorted by xi now want to group by roundx and get the tuple that holds the median of y in each groupi can already compute the median for the whole table with this ranking queryselect ax ay from xy table axy table bwhere ay bygroup by ax ayhaving count select roundcount12 from xy tableoutput 01 40but i did not yet succeed writing a query to compute the median for sub groupsattention i do not have a median aggregation function available please also do not propose solutions with special partition rank or quantile statements as found in similar but too vendor specific so questions i need plain sql ie compatible to sqlite without median functionedit i was actually looking for the medoid and not the median,['sql'] +454973,detect the number of line breaks in textblock with wrap is there any way to detect the number of lines breaks in a textblock with textwrappingwrapi am considering using a nonmonospaced font i need this because i am creating a new and personalized messagebox window which has a big text title animations the logo of my application and the theme of my applicationit is clear that i need to change the size of the window according to the number of linebreaks of the body message similar to how the default messagebox window behaves,['c#'] +454976,javascript error uncaught typeerror property of object object object is not a function i am trying to insert a script in a joomla module the script is a percentage loader in js i am had some issues with another js but i finally managed to solve themthe error i am getting isuncaught typeerror property of object object object is not a function anonymous functioni am trying to import the percentage loader jquery pluginand the js code is function var toploader dttoploaderpercentageloaderwidth 256 height 256 controllable true progress 05 onprogressupdate functionval toploadersetvaluemathroundval 10 var toploaderrunning false dtanimatebuttonclickfunction if toploaderrunning return toploaderrunning true toploadersetprogress0 toploadersetvalue0kb var kb 0 var totalkb 9 var animatefunc function kb 17 toploadersetprogresskb totalkb toploadersetvaluekbtostring kb if kb totalkb settimeoutanimatefunc 25 else toploaderrunning false settimeoutanimatefunc 25 i tried changing the first line from function to jqueryfunction as i read many topics on stackoverflow but still cannot fix it,"['javascript', 'jquery']" +454985,video compression on android using new mediacodec library in my app i am trying to upload some videos that the user picked from gallerythe problem is that usually the android video files are too big to upload and so we want to compress them first by lower bitrate resolution i have just heard about the new mediacodec api that introduce with api 16 i perviously tried to do so with ffmpegwhat i am doing right now is the followingfirst decode the input video using a video decoder and configure it with the format that was read from the input filenext i create a standard video encoder with some predefined parameters and use it for encoding the decoder output buffer then i save the encoder output buffer to a fileeverything looks good the same number of packets are written and read from each input and output buffer but the final file does not look like a video file and cannot be opened by any video playerlooks like the decoding is ok because i test it by thisplaying it on surface i first configure the decoder to work with a surface and when we call releaseoutputbuffer we use the render flag and were able to see the video on the screenhere is the code i am using init decoder mediacodec decoder mediacodeccreatedecoderbytypemime decoderconfigureformat null null 0 decoderstart bytebuffer codecinputbuffers decodergetinputbuffers bytebuffer codecoutputbuffers decodergetoutputbuffers init encoder mediacodec encoder mediacodeccreateencoderbytypemime int width formatgetintegermediaformatkey width int height formatgetintegermediaformatkey height mediaformat mediaformat mediaformatcreatevideoformatmime width height mediaformatsetintegermediaformatkey bit rate 40 mediaformatsetintegermediaformatkey frame rate 25 mediaformatsetintegermediaformatkey color format mediacodecinfocodeccapabilitiescolor formatyuv420semiplanar mediaformatsetintegermediaformatkey i frame interval 5 encoderconfiguremediaformat null null mediacodecconfigure flag encode encoderstart bytebuffer encoderinputbuffers encodergetinputbuffers bytebuffer encoderoutputbuffers encodergetoutputbuffers extractorselecttrack0 boolean sawinputeos false boolean sawoutputeos false boolean sawoutputeos2 false mediacodecbufferinfo info new mediacodecbufferinfo bufferinfo encoderinfo new mediacodecbufferinfo while sawinputeos sawoutputeos sawoutputeos2 if sawinputeos sawinputeos decodeinputextractor decoder codecinputbuffers if sawoutputeos int outputbufindex decoderdequeueoutputbufferinfo 0 if outputbufindex 0 sawoutputeos decodeencodeextractor decoder encoder codecoutputbuffers encoderinputbuffers info outputbufindex else if outputbufindex mediacodecinfo output buffers changed logdlog tag decoding info output buffers changed codecoutputbuffers decodergetoutputbuffers else if outputbufindex mediacodecinfo output format changed final mediaformat oformat decodergetoutputformat logdlog tag decoding output format has changed to oformat else if outputbufindex mediacodecinfo try again later logdlog tag decoding dequeueoutputbuffer timed out if sawoutputeos2 int encodingoutputbufferindex encoderdequeueoutputbufferencoderinfo 0 if encodingoutputbufferindex 0 sawoutputeos2 encodeouputoutputstream encoder encoderoutputbuffers encoderinfo encodingoutputbufferindex else if encodingoutputbufferindex mediacodecinfo output buffers changed logdlog tag encoding info output buffers changed encoderoutputbuffers encodergetoutputbuffers else if encodingoutputbufferindex mediacodecinfo output format changed final mediaformat oformat encodergetoutputformat logdlog tag encoding output format has changed to oformat else if encodingoutputbufferindex mediacodecinfo try again later logdlog tag encoding dequeueoutputbuffer timed out clear some stuff hereand those are the method i use for decode encode private boolean decodeinputmediaextractor extractor mediacodec decoder bytebuffer codecinputbuffers boolean sawinputeos false int inputbufindex decoderdequeueinputbuffer0 if inputbufindex 0 bytebuffer dstbuf codecinputbuffersinputbufindex input1count int samplesize extractorreadsampledatadstbuf 0 long presentationtimeus 0 if samplesize 0 sawinputeos true samplesize 0 logdlog tag done decoding input input1count else presentationtimeus extractorgetsampletime decoderqueueinputbufferinputbufindex 0 samplesize presentationtimeus sawinputeos mediacodecbuffer flag end of stream 0 if sawinputeos extractoradvance return sawinputeos private boolean decodeoutputtofilemediaextractor extractor mediacodec decoder bytebuffer codecoutputbuffers mediacodecbufferinfo info int outputbufindex outputstream output throws ioexception boolean sawoutputeos false bytebuffer buf codecoutputbuffersoutputbufindex if infoflags mediacodecbuffer flag end of stream 0 sawoutputeos true logdlog tag done decoding output output1count if infosize 0 output1count byte outdata new byteinfosize bufgetoutdata outputwriteoutdata 0 outdatalength else logdlog tag no data available infosize bufclear decoderreleaseoutputbufferoutputbufindex false return sawoutputeos private boolean encodeinputfromfilemediacodec encoder bytebuffer encoderinputbuffers mediacodecbufferinfo info filechannel channel throws ioexception boolean sawinputeos false int inputbufindex encoderdequeueinputbuffer0 if inputbufindex 0 bytebuffer dstbuf encoderinputbuffersinputbufindex input1count int samplesize channelreaddstbuf if samplesize 0 sawinputeos true samplesize 0 logdlog tag done encoding input input1count encoderqueueinputbufferinputbufindex 0 samplesize channelposition sawinputeos mediacodecbuffer flag end of stream 0 return sawinputeos any suggestion on what i am doing wrongi did not find too much examples for encoding with mediacodec just a few samples code for decodingthanks a lot for the help,['android'] +455048,horizontal progress bar width in actionbar i am thisplaying an horizontal progress bar in my action barmy problem is the progress bar width is not the action bar width but smaller but centered is that a normal behavior how can i give it the screen widthi am using this in oncreate requestwindowfeaturewindowfeature progressand this in my methodspublic void setshowindeterminateprogressboolean val setprogressbarindeterminatetrue setprogressbarvisibilityvalthanks in advance,['android'] +455061,how to view current database schema for heroku app in terminal i am trying to view my heroku apps schema in terminal mac os x lion and stumbled upon a command that does just that in terminal i run heroku run more dbschemarb but it seems to thisplay an older schema version i just migrated the heroku db and i noticed that none of the new columns are listedi cannot seem to find anything helpful in herokus documentation does anyone know a command to view the current database schema for a heroku appby the way i inherited the code for the app and for some reason all of the migration files are commented out there are probably 40 files so i cannot just run rake dbmigrate locally to update the schema hence i would like to see the heroku apps schema directlyany suggestions,['ruby-on-rails'] +455084,the breakpoint will not currently be hit a different version of script file has been loaded by debugged process i have strange behavior in vs 2012 with javascript as if it were caching old version it appears to not load the latest changes made to the js file when debugging the breakpoint suggests the breakpoint will not currently be hit a different version of this script file has been loaded by the debugged process the script file may need to be reloadedis there anyway to clear it out so that i can always run with latest changes this only started happening recently possible cause vs 2012 update 2 i have used 2012 for months now and never had this issue thanks,['javascript'] +455113,insert dictionary into mongodb with c driver i am in a situation where i cannot predict which fields my mongodb document is going to have so i can no longer create an object with an id field of type bsonid i find it very convenient to create a dictionary hashtable and add my datetime and string objects inside as many times as i need it i then try to insert the resulting dictionary object into mongodb but default serialization failsheres my object of type hashtable like a dictionary but with varied types inside idmetadata1asaadmetadata2metadata3isodatesomedatehereand the error from the driver i get isserializer dictionaryserializer expected serialization options of type dictionaryserializationoptions not documentserializationoptionsi googled it but could not find anything useful what am i doing wrong,['c#'] +455147,how to read pdfs created with an unknown random owner password requirement is to process a batch of pdfs one at a time and on success encrypt each of them with an user passwordhowever these pdfs were encrypted previously with randomly generated dynamic owner password not know to any one to prevent any editsi use itext for encryption as shown belowbyte userpass usergetbytesbyte ownerpass ownergetbytespdfreader reader new pdfreadermiscpdfpdfstamper stamper new pdfstamperreader new fileoutputstreamprocessed encryptedpdfstampersetencryptionuserpass ownerpasspdfwriterallow printing pdfwriterencryption aes 128 pdfwriterdo not encrypt metadatastamperclosereaderclosebut this code throws an comitextpdftextexceptionsbadpasswordexception pdfreader not opened with owner password can some one guide on how to resolve this error bypass owner passwordhere i would like to make clear that we legally own these pdfs so no crime hacking is committedps solution is not limited to itext can use any other java library free or licensed too,['java'] +455162,running matlab code from php as the title indicates i have a matlab code for isolated spoken words recognition and i want to be able to integrate this project with another one made with php for some purposei have not used to deal with such problem before in other words it is the first time for me when i need to integrate php and matlab so i really do not know where to start and howi have read a couple of articles but i could not make it validi have php 549 matlab r2012a and windows 7 osthe matlab project files can be seen on githubany help would be greatly appreciated,['php'] +455181,avfoundation image orientation off by 90 degrees in the preview but fine in camera roll something really strange is happening i am trying to capture an image using avfoundation the camera roll image seems just fine but the image preview has the image rotated by 90 degreesthis is the code i am using to capture an imageavcaptureconnection videoconnection nilfor avcaptureconnection connection in stillimageoutputconnections for avcaptureinputport port in connection inputports if port mediatype isequalavmediatypevideo videoconnection connection break if videoconnection break nslogabout to request a capture from stillimageoutputstillimageoutput capturestillimageasynchronouslyfromconnectionvideoconnection completionhandler cmsamplebufferref imagesamplebuffer nserror error cfdictionaryref exifattachments cmgetattachment imagesamplebuffer kcgimagepropertyexifdictionary null if exifattachments do something with the attachments nslogattachements exifattachments else nslogno attachments nsdata imagedata avcapturestillimageoutput jpegstillimagensdatarepresentationimagesamplebuffer uiimage image uiimage alloc initwithdataimagedata selfvimageimage image uiimagewritetosavedphotosalbumimage nil nil nil,['ios'] +455206,when should use jquery mobile what is the proper use case according to so is faq questions addressing software tools commonly used by programmers are appropriate so here goesi like the ui for jquery mobile but i am just really getting into responsive design whereby my site responds based on screen size media queries etc so where does jquery mobile fit into the mix say for examplei have already designed the look and feel of my site at all my screen sizesmy design does not currently use any of the jquery mobile ui elements at any sizeso how would my site benefit by using jquery mobilewouldnt i literally have to redo my whole site to use jquery mobile or is jquery mobile just or primarily for mobile appsit is amazing i see so many tutorials that jump straight into the how to use it but skip right over the why and when to use it,['jquery'] +455247,c generics cast generic type to value type i have a generic class which saves value for the specified type tthe value can be an int uint double or floatnow i want to get the bytes of the value to encode it into an specific protocoltherefore i want to use the method bitconvertergetbytes but unfortunately bitconverter does not support generic types or undefined objects that is why i want to cast the value and call the specific overload of getbytesmy questionhow can i cast a generic value to int double or floatthis does not workpublic class genericclasst where t struct t value public void setvaluet value this value value public byte getbytes int x intthis value iftypeoft typeofint return bitconvertergetbytesintthis value else if typeoft typeofdouble return bitconvertergetbytesdoublethis value else if typeoft typeoffloat return bitconvertergetbytesfloatthis value is there a possibility to cast an generic valueor is there another way to get the bytes,['c#'] +455270,is there a builtin function version of and andor or in python this question is for fun i do not expect the answer to be usefulwhen i see people doing things with reduce in python they often take advantage of a builtin function in python often from the operator modulethis worksresult reducelambda a b a b range5but usually you would see thisfrom operator import addresult reduceadd range5whats strange to me is that the operator module does not seem to have a function for logical and it does have bitwise and but not logical andso suppose you are doing thisresult reducelambda a b a and b range1 6is there a builtin function that can be used herei am also wondering if there is a builtin function that can replace orif you map the arguments to booleans first you can use the bitwise and from operator or just directly use bool and like sofrom operator import and result reduceand mapbool range1 6result reducebool and mapbool range1 6and likewise with operatoror or bool or for the or operation but i am looking for a function that does not need the values mapped to booleansif you knew for certain that your values are all integers you could use operatormul for and and operatoradd for or this would be a crude hack and i do not want this answer especially considering how expensive the multiplications would get if many numbers were encountered and none of them were zeronote i am aware of all and any which are better replacements for this use of reduce as i said at the top i am asking this for funnote a function that has the sideeffect of forcing all values to bool would be an acceptable answer the builtin and keyword does not do thisx 3 and 5 sets x to 5 not to truebut for the purpose of this question i am just interested in a function that can work with reduce to do logical and or or operations,['python'] +455301,phpstorm how do i setup less to output to css directory with file watcher how do using file watchers in phpstorm do i set up less file watchers output path to do thisi wantprojectpathlessdirfilelessto output toprojectpathcssdirfilecssorprojectpathlessfile2lessto output toprojectpathcssfile2cssi am not seeing a clear way to make this happen with the output path macros in phpstorm with the filedirrelativetoprojectroot macro i am able to get the path to the current directory but there is no clear way to replace less with css in the path,['css'] +455314,align printf output in java i need to thisplay a list of items with their prices from an array and would like to align the prices i almost have it working but needs improvements below is the code and the output any ideas how to make all prices aligned so far some work but some do not thanks in advancefor loopsystemoutprintfd s tt 2fn i 1 book typei costioutput1 newspaper 1002 paper back 7503 hardcover book 104 electronic book 2005 magazine 300,['java'] +455336,how jsp page should check authentication i am new to web programming i am asking a common pattern to do things like checking authentication here is the scenariothe website has a login page for visitors it will take username and encrypted password and sent them to server then get either a error code usernamepassword does not matchor an auth key from the server when the user logged in successfully i want the website automatically jump to the mainjsp page that presents the main functionality of the website in this case i want mainjsp check the user authentication that is i do not want such thing happens like user can directly open wexamplecommainjsp and if they did thing like this i want to redirect them to login page so how could i pass authentication information across page and how could i prevent user from directly accessing the mainjsp without login do i need to use session or anything,['javascript'] +455352,function name convention for convert foo to bar i have a very common pattern of given a foo return a bar for example given a user id return a useris there a conventional naming pattern for these sorts of functions following joel on software i have personally used a lot of bar from foo but i rarely see other people do this and it quickly becomes verbose egwidgets user widgets from useruser from param mapparamsis there a conventional way to name or namespace eg userfrom map in any of the popular languages out there i am particularly interested in python but any language you can think of would br useful,"['javascript', 'python', 'ruby']" +455355,stop animation and start transition on hover i have a link that is running an infinite animation with the background color i want to stop the animation and transition into a different background color on hoverstartlink backgroundcolor206a9e colorf borderradius15px fontfamily myriad pro webkitanimationchangecolor 34s infinite webkittransitionall 02s easeinstartlinkhover webkitanimationplaystate paused backgroundcolor 014a2awebkitkeyframes changecolor 0 background206a9e 50 background012c4a 100 background206a9ewhy is this code not working and is there an alternate way to get this done preferably without javascript,['css'] +455380,how to synch javascript callbacks i have been developing in javascript for quite some time but net yet a cowboy developer as one of the many things that always haunts me is synching javascripts callbacksi will describe a generic scenario when this concern will be raised i have a bunch of operations to perform multiple times by a for loop and each of the operations has a callback after the for loop i need to perform another operation but this operation can only execute successfully if all the callbacks from the for loop are done code examplefor in myfunc1callback callbacks are executed asynchlymyfunc2 can only execute properly if all the myfunc1 callbacks are donesuggested solutioninitiate a counter at the beginning of the loop holding the length of the loop and each callback decrements that counter when the counter hits 0 execute myfunc2 this is essentially to let the callbacks know if it is the last callback in sequence and if it is call myfunc2 when it is doneproblemsa counter is needed for every such sequence in your code and having meaningless counters everywhere is not a good practiceif you recall how thread conflicts in classical synchronization problem when multiple threads are all calling var on the same var undesirable outcomes would occur does the same happen in javascriptultimate questionis there a better solution,['javascript'] +455451,how to create customizable dynamic grid layout using css and javascript i am working on a project that involves a lot of css the customer wants to have a grid layout on the home page where he wants to be able to rearrange ui components with drag and drop these ui components could be of different sizes 1x1 2x2 and 3x3 when i drop an ui item at the desired new location it should push the other components aside any possible holes should be filled with 1x1 componentshow it should workbefore i have draged a componentdraging the 2x2 componentdropping the component in the middle the two 1x1 components make room and adapt around the 2x2note that the size of the grid is not limited to 8 1x1 but the height as well as the width of it should be possible to expand and make smalleriall rather not use tables but other than that i am open to suggestions right now i have just used inlineblock divs which i can drag and drop to switch the jquery dom objects the effect is not quite what the customer wantshow it is now,"['javascript', 'css']" +455463,await in parallelforeach i have an async method which will be used in parallelforeach in the async method there is await for a taskhowever in the test seems there are no await behavior the await task did not complete whats the problem below is the codepublic void method1 iliststring testlist new iliststring123 parallelforeachtestlist method2 public async void method2 await taskrun some other codes here,['c#'] +455490,fastest implementation of log2int and log2float the question isare there any other andor faster implementations of a basic 2logapplicationsthe log2int and log2float operations are very useful in a lot of different contexts to name a few compression algorithms 3d engines and machine learning in almost all of these contexts they are used in the lowlevel code that is called billions of times especially the log2int operation is very usefulbecause i find myself using log2 all the time i do not want to give a specific application i am working on here what is the same is the fact that this is a real performance drainer as shown by performance tests of various applications for me it is key to get this as fast as possiblethe complete source code to test all implementations is added at the bottom so you can see for yourselfand of course run your tests at least 3 times and make sure the counters are big enough to hit multiple seconds also i do the add operation to ensure the whole loop is not magically removed by the jitter so let us get started with the real worktrivial implementationthe trivial implementation of a 2log in c isintmathlogx mathlog2this implementation is trivial but also very slow it requires 2 log operations that are in itself quite slow already of course we can optimize this by making 10mathlog2 a constant note that we need to modify this constant a bit to get the right results as a result of floating point errors or add a small number to get the correct results i chose the latter but it does not really matter the end result is slow in all casestable lookupa faster solution for this is to use a lookup table while you can use a lookup table of any power of 2 i usually use a table size of 256 or 64k entries first we create the lookup tablelookup new int256for int i 1 i 256 i lookupi intmathlogi mathlog2next we implement the 2log as followsprivate static int loglookupint i if i 0x10 return lookupi 24 24 else if i 0x10 return lookupi 16 16 else if i 0x100 return lookupi 8 8 else return lookupi as you can see table lookups are a much much faster implementation but as a con it cannot be used to calculate log2floatbranch removalas we all know processors are not very good at branching so i figured that table lookups can be improved by removing the branches instead of the bunches of ifs i introduced a second table with the values and shift bits around to find the entry in the tablenobranch new int16 0 0 8 8 16 16 16 16 24 24 24 24 24 24 24 24 private static int logdoublelookupint i int and i i 4 and n n 2 and n n 1 and n 0x10 21 n 0x10 14 n 0x100 7 n 1 int br nobranchn return lookupi br brif you run this test you will find that it is actually slower than the ifthenelse solutionand then there was the intel 80386intel understood years ago that this is an important operation so they implemented bitscanforward bsf into their processors other processors have similar instructions this is by far the fastest way to do a 2log that i know of but unfortunately i know of now way to use these nice functions from c i do not like the idea of having an implementation that does not run anymore when a new tablet or phone hits the market and i do not know of any crossplatform solution that enables me to use this function directlyother implementationsas l4v pointed out thanks there are a couple of other implementations specificallytrivial loop i omitted this because it is trivial this is not really fast implemented in testtrivial64bit ie int unions that can be used implemented in testfloatdebruijn lookup tables implemented in testdebruijnbinary search implemented in testbinaryapart that i like the name the debruijn lookup tables are just as fast as the normal lookup tables making it one of the fastest algorithms here all the other algorithms i have tried are much slowercomplete test codepublic class log2test public static void testnaive stopwatch sw new stopwatch swstart int and 0 for int i 1 i 10 i and intmathlogi mathlog20 swstop consolewritelineresult 0 naive implementation took 10s n swelapsedtotalseconds public static int logtrivialloopint v int r 0 while v 1 0 unroll for more speed r return r public static void testtrivialloop stopwatch sw new stopwatch swstart int and 0 for int i 1 i 10 i and logtrivialloopi swstop consolewritelineresult 0 loop implementation took 10s n swelapsedtotalseconds public static int logfloatint v helper h new helper u1 v u2 0x4330 hd 45035996273704960 return hu2 20 0x3ff public static void testfloat stopwatch sw new stopwatch swstart int and 0 for int i 1 i 10 i and logfloati swstop consolewritelineresult 0 ie float implementation took 10s n swelapsedtotalseconds structlayoutlayoutkindexplicit private struct helper fieldoffset0 public int u1 fieldoffset4 public int u2 fieldoffset0 public double d public static void testconstant double c 10 mathlog20 stopwatch sw new stopwatch swstart int and 0 for int i 1 i 10 i and int01 mathlogi c swstop consolewritelineresult 0 naive 2 implementation took 10s n swelapsedtotalseconds private static int loglookupint i if i 0x10 return lookupi 24 24 else if i 0x10 return lookupi 16 16 else if i 0x100 return lookupi 8 8 else return lookupi public static void testlookup lookup new int256 for int i 1 i 256 i lookupi intmathlogi mathlog2 stopwatch sw new stopwatch swstart int and 0 for int i 1 i 10 i and loglookupi swstop consolewritelineresult 0 table lookup implementation took 10s n swelapsedtotalseconds private static int logdoublelookupint i int and i i 4 and n n 2 and n n 1 and n 0x10 21 n 0x10 14 n 0x100 7 n 1 int br nobranchn return lookupi br br public static void testdoublelookup lookup table was already constructed earlier stopwatch sw new stopwatch swstart int and 0 for int i 1 i 10 i and logdoublelookupi swstop consolewritelineresult 0 double table lookup implementation took 10s n swelapsedtotalseconds private static int logbinaryint v this is the worst implementation ever apparently c is a slowbranching language int b 0x2 0xc 0xf0 0xff00 0x7f0 int s 1 2 4 8 16 int r 0 result of log2v will go here for int i 4 i 0 i unroll for speed if v bi 0 v si r si return r int r v 0xf 0x10 0 v r int shift v 0xff 0x8 0 v shift r shift shift v 0xf 0x4 0 v shift r shift shift v 0x3 0x2 0 v shift r shift r v 1 return r public static void testbinary lookup table was already constructed earlier stopwatch sw new stopwatch swstart int and 0 for int i 1 i 10 i and logbinaryi swstop consolewritelineresult 0 binary search implementation took 10s n swelapsedtotalseconds private static readonly int multiplydebruijnbitposition new int32 0 9 1 10 13 21 2 29 11 14 16 18 22 25 3 30 8 12 20 28 15 17 24 7 19 27 23 6 26 5 4 31 private static int logdebruijnint v v v 1 first round down to one less than a power of 2 v v 2 v v 4 v v 8 v v 16 return multiplydebruijnbitpositionuintv 0x07c4acddu 27 public static void testdebruijn lookup table was already constructed earlier stopwatch sw new stopwatch swstart int and 0 for int i 1 i 10 i and logdebruijni swstop consolewritelineresult 0 de bruijn implementation took 10s n swelapsedtotalseconds private static int lookup private static readonly int nobranch new int16 0 0 8 8 16 16 16 16 24 24 24 24 24 24 24 24 static void mainstring args testconstant testnaive testdebruijn testbinary testfloat testtrivialloop testlookup testdoublelookup consolereadline,"['c#', '.net']" +455500,let the user choose the keyword for my omnibox chrome extension i just created a chrome extension using the omnibox apiomnibox keyword a i found out that it is not possible to use multible keywordsor let the user choose a keyword for my extension although the extension is listed on the search engines settings pagei addition to that the priority of the extension keyword is by far the lowestif a user already defined a keyword in the default search engines other search engines sections the extension keyword is not usable does anyone know a solution for at least one of these issues maybe by using the npapi,['javascript'] +455503,caused by javasecurityunrecoverablekeyexception cannot recover key i am supplied with a jks keystore named abcc clientstore when i import this keystore to cacerts and try connecting it says no such algorithm error pfa the stacktrace caused by javasecuritynosuchalgorithmexception error constructing implementation algorithm default provider sunjsse class comsunnetsslinternalssldefaultsslcontextimpl at javasecurityproviderservicenewinstanceproviderjava1245 at sunsecurityjcagetinstancegetinstancegetinstancejava220 at sunsecurityjcagetinstancegetinstancegetinstancejava147 at javaxnetsslsslcontextgetinstancesslcontextjava125 at javaxnetsslsslcontextgetdefaultsslcontextjava68 at javaxnetsslsslsocketfactorygetdefaultsslsocketfactoryjava102 at orgapacheaxiscomponentsnetjssesocketfactoryinitfactoryjssesocketfactoryjava61 at orgapacheaxiscomponentsnetjssesocketfactorycreatejssesocketfactoryjava79 32 morecaused by javasecurityunrecoverablekeyexception cannot recover key at sunsecurityproviderkeyprotectorrecoverkeyprotectorjava311 at sunsecurityproviderjavakeystoreenginegetkeyjavakeystorejava121 at sunsecurityproviderjavakeystorejksenginegetkeyjavakeystorejava38 at javasecuritykeystoregetkeykeystorejava763 at comsunnetsslinternalsslsunx509keymanagerimplltinitgtsunx509keymanagerimpljava113 at comsunnetsslinternalsslkeymanagerfactoryimplsunx509engineinitkeymanagerfactoryimpljava48 at javaxnetsslkeymanagerfactoryinitkeymanagerfactoryjava239 at comsunnetsslinternalssldefaultsslcontextimplgetdefaultkeymanagerdefaultsslcontextimpljava170 at comsunnetsslinternalssldefaultsslcontextimplltinitgtdefaultsslcontextimpljava40 at sunreflectnativeconstructoraccessorimplnewinstance0native method at sunreflectnativeconstructoraccessorimplnewinstancenativeconstructoraccessorimpljava39 at sunreflectdelegatingconstructoraccessorimplnewinstancedelegatingconstructoraccessorimpljava27 at javalangreflectconstructornewinstanceconstructorjava513 at javalangclassnewinstance0classjava355 at javalangclassnewinstanceclassjava308 at javasecurityproviderservicenewinstanceproviderjava1221 39 morebut if i use this keystore independently ie without adding it to cacerts it works some googling led to me to which says that password might me different for the key and the keystore,['java'] +455517,uiview animation warning i am using following codeuiview animatewithduration10 delay005 optionsuiviewanimationcurveeasein animations code completionbool finished i am getting the following warningimplicit conversion from enumeration type enum uiviewanimationcurve to different enumeration type uiviewanimationoptions aka enum uiviewanimationoptionshow to solve this,"['ios', 'objective-c']" +455525,is nsnotificationcenter thread safe can i post a notification in a given queue and receive it on another i want to use notifications to communicate different queues but i am not sure if this is safe,['objective-c'] +455566,using jquery deferred to sync animation and ajax i am trying to get my head around the whole deferred concept and i am trying to use it to synchronize a fadeinfadeout animation together with an ajax callbasically i am switching content on page doingfetch content with ajaxon response fadeoutreplace contentfadeinhowever if i understand deferreds right i might be able to do something like thisfadeout and at the same time initialize fetch content with ajaxwhen both the fadeout and the fetch content are complete change contentfadeinsome code of the original solutiongeturl functionpage contentfadeto100 0 linear function thishtmlpagetextfadeto400 1 linear i am trying to do something like thisvar deferred1 geturlvar deferred2 contentfadeto100 0 linearpromisewhendeferred1 deferred2donefunction contenthtmlpagetextfadeto400 1 lineari just cannot really get clear on how to use it and should i use done or then should i use pipe in a clever way do i need promisewhat would be the more standardized way to implement this,['jquery'] +455567,encrypt files using pgp in php i want to use pgp encryption to encrypt a csv files i am generating through a php script and then send that file to client via email client will give me the encryption key which i need to use for encryption filesi googled about pgp and found it is pretty good privacy also i found openpgp and gnupg what are these two types of pgp and which one should i usealso how to encrypt a files using pgp in php with the key that my client will providei have heard this term first time can anyone please help in understanding this and implementing this in php,['php'] +455578,is there a max javascript filesize what can browsers handle engineering incredibly large webapps do we have any top or limit or best practice for filesizes in these large projects the biggest i have seen is probably twittergmail which had around 1mb minified javascript but how much can a browser handlewhat if there is a large app with 5mb 10mb or 100mb javascript minified when does it severely affect performance or memory usage even if the app is very well written and optimized can the jit handler take whatever are there any diminishing returnsis there any real example of apps beeing this big except for the usual suspects such as gmail twitter facebook googledocs etcthanks,['javascript'] +455604,html email in outlook table width issue content is wider than the specified table width my html email template is thisplaying correctly without major problems in gmail apple mail and ios mail outlook however is a horrifying mess and i cannot for the life of me figure out what i have done wrongmy email template is not using any overly crazy css and uses tables for the layout i have fixed pixel widths for everythingthe problem is every table in my layout stretches to 100 despite me setting it to 580px for the container and 450px for the inner contentthe codedoctype html public w3cdtd xhtml 10 transitionalen html xmlns head meta httpequivcontenttype contenttexthtml charsetutf8 facebook sharing information tags meta propertyogtitle contentmcsubject titlemcsubjecttitle style typetextcss clientspecific styles outlook apadding0 force outlook to provide a view in browser button bodywidth100 important force hotmail to thisplay emails at full width bodywebkittextsizeadjustnone prevent webkit platforms from changing default text sizes reset styles bodymargin0 padding0 imgbordernone fontsize14px fontweightbold heightauto lineheight100 outlinenone textdecorationnone texttransformcapitalize style head body bgcolor4 center table border0 cellpadding0 cellspacing0 width580px stylebackgroundcolor 0290ba tr td aligncenter valigntop img alt src width580px td tr tr td aligncenter valigntop table border0 cellpadding0 cellspacing0 width450px tr td aligncenter valigntop width450px br img alt src headerpng width450px td tr table table border0 cellpadding0 cellspacing0 width450px tr td aligncenter valigntop width214px br div stylecolor004c63 fontfamily georgia serif fontsize 17px lineheight100 textalignleft fontstyle italic we consider ourselves partners in your business with the specific purpose of making your profit grow div td td width236pxtd tr table table border0 cellpadding0 cellspacing0 width450px tr td aligncenter valigntop width214px p stylelineheight 150 color f textalign justify fontsize 10px we have been pretty busy for the last 2 12 years getting our business up and running busy doing day to day and long term projects for our clients but it is come to our attention not everyone is aware of all the cool and not so cool but just as important things we do so were going to show off a bit tell you a bit more about what we do so you can benefit from our wide range of skills services and experiences this email is the start of that process were going to show you a small we do not want to annoy you with too much stuff but diverse selection of projects each month to hopefully inspire you then if you want any information or ideas on how we could do something similar for you just let us know wed love to help we are also in the process of building ourselves a new web site finally well let you know when its live but check out our temporary page in the mean time here p td td width236px p stylelineheight 150 color f textalign justify fontsize 10px img alt src width110 stylemarginleft 20px p br td tr table td tr tr stylebackgroundcolor d82445 td aligncenter valigntop img alt src showcasepng width580px td tr tr stylebackgroundcolor d82445 td aligncenter valigntop table border0 cellpadding0 cellspacing0 width450px tr tdnbsptd tr tr td valigntop width124px img alt src image1png width124px td td width10pxtd td table border0 cellpadding0 cellspacing0 width316px tr td valigntop div stylecolor6c1e2c fontfamily georgia serif fontsize 17px lineheight100 textalignleft fontstyle italic fontweight 500 title goes here div td tr tr td valigntop width150px p stylelineheight 150 color f textalign justify fontsize 10px sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat ut wisi enim ad minim veniam quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat duis autem p td td width10pxtd td valigntop width160px p stylemargintop 20px a hrefimg alt src showcase forwardpng stylemargintop 10px a br br a hrefimg alt src showcase moreinfopng a p td tr table td tr tr tdnbsptd tr tr td valigntop width124px img alt src image1png width124px td td width10pxtd td table border0 cellpadding0 cellspacing0 width316px tr td valigntop div stylecolor6c1e2c fontfamily georgia serif fontsize 17px lineheight100 textalignleft fontstyle italic fontweight 500 title goes here div td tr tr td valigntop width150px p stylelineheight 150 color f textalign justify fontsize 10px sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat ut wisi enim ad minim veniam quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat duis autem p td td width10pxtd td valigntop width160px p stylemargintop 20px a hrefimg alt src showcase forwardpng stylemargintop 10px a br br a hrefimg alt src showcase moreinfopng a p td tr table td tr tr tdnbsptd tr tr td valigntop width124px img alt src image1png width124px td td width10pxtd td table border0 cellpadding0 cellspacing0 width316px tr td valigntop div stylecolor6c1e2c fontfamily georgia serif fontsize 17px lineheight100 textalignleft fontstyle italic fontweight 500 title goes here div td tr tr td valigntop width150px p stylelineheight 150 color f textalign justify fontsize 10px sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat ut wisi enim ad minim veniam quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat duis autem p td td width10pxtd td valigntop width160px p stylemargintop 20px a hrefimg alt src showcase forwardpng stylemargintop 10px a br br a hrefimg alt src showcase moreinfopng a p td tr table td tr tr tdnbsptd tr table br td tr tr stylebackgroundcolor fdac57 td aligncenter valigntop img alt src footerpng width580px td tr tr stylebackgroundcolor fdac57 td aligncenter valigntop table width450px aligncenter cellspacing0 cellpadding0 border0 tr td table tr tdnbsptd tr tr td valigntop width215px div stylecolor6c1e2c fontfamily georgia serif fontsize 17px lineheight100 textalignleft fontstyle italic fontweight 500 drop us a line br visit our website or br forward this to a friend div td td valigntop width40px nbsp td td valigntop width195px div stylecolor6c1e2c fontfamily georgia serif fontsize 17px lineheight100 textalignleft fontstyle italic fontweight 500 get in touch br today youall br love working with us div td tr tr td valigntop width215px p stylelineheight 150 color f textalign justify fontsize 10px donat worry if it is an odd hour leave a message and we will get back to you at your convenience p td td valigntop width40px nbsp td td valigntop width195px p stylelineheight 150 color f textalign justify fontsize 10px 163 bateau bay rd bateau bay br nsw 2261 br australia p td tr tr td valignbottom width215px p stylelineheight 150 color f textalign justify fontsize 10px a hrefimg alt src stylepadding0 paddingright 5px margin 0 a a hrefimg alt src stylepadding0 paddingright 5px margin 0 a a hrefimg alt src stylepadding0 paddingright 5px margin 0 a a hrefimg alt src stylepadding0 paddingright 5px margin 0 a p td td valigntop width40px nbsp td td valigntop width195px p stylelineheight 150 color f textalign justify fontsize 10px br br br com br p td tr table br table width450px tr td width144px aligncenter a hrefimg alt src footer forwardpng a td td width6pxnbsptd td width144px aligncenter a hrefimg alt src footer visitpng a td td width6pxnbsptd td width144px aligncenter a hrefimg alt src footer getintouchpng a td tr table br td tr table td tr tr stylebackgroundcolor fdfdfd td aligncenter valigntop br img alt src br p stylelineheight 150 color 0 textalign center fontsize 10pxcopy copyright 2013 hicksads sent with love p td tr table center body htmlany help is greatly appreciated like unbelievably appreciated,['html'] +455623,error when i try run phpunit from phpstorm i have little problem when i am trying to run phpunit test in ide phpstormi use composer file which looks require phpunitphpunit 3719 now when i run test i recive exceptionphp fatal error uncaught exception phpunit framework exception with message class phpunit extensions repeatedtest does not extend phpunit framework testcasewhat is wrong when i included pear installed version test working okeditsample test class class readertest extends phpunit framework testcase test public function shouldgetreadedvalue thisasserttruetrue edit2traceusrbinphp tmpidephpunitphp noconfiguration pathtomyprojecttesting started at 1453 php fatal error uncaught exception phpunit framework exception with message class phpunit extensions repeatedtest does not extend phpunit framework testcase in pathtomyprojectvendorphpunitphpunitphpunitframeworktestsuitephp183stack trace0 pathtomyprojectvendorphpunitphpunitphpunitframeworktestsuitephp315 phpunit framework testsuite constructobjectreflectionclass1 pathtomyprojectvendorphpunitphpunitphpunitframeworktestsuitephp389 phpunit framework testsuiteaddtestsuiteobjectreflectionclass2 pathtomyprojectvendorphpunitphpunitphpunitframeworktestsuitephp416 phpunit framework testsuiteaddtestfilevarwphpsh3 pathtomyprojectvendorphpunitphpunitphpunitrunnerbasetestrunnerphp96 phpunit framework testsuiteaddtestfilesarray4 pathtomyprojectvendorphpunitphpunitphpunittextuicommandphp150 phpunit runner basetestrunnergettestvarwphpsh a in pathtomyprojectvendorphpunitphpunitphpunitframeworktestsuitephp on line 183process finished with exit code 255,['php'] +455624,aspnet compiler complaining of mismatching framework versions with miniprofiler i have an mvc3 project that i upgraded from vs2010 to vs2012 the project also has a reference to miniprofiler our application compiles and runs fine in vs2012 without any warningserrors both assemblies load fine when running with iis express when using the aspnet compiler tool however i get the following warningmicrosoft r aspnet compilation tool version 403031917929 utility to precompile an aspnet application copyright c microsoft corporation all rights reserved0 warning the following assembly has dependencies on a version of the net framework that is higher than the target and might not load correctly during runtime causing a failure miniprofiler version2100 cultureneutral publickeytokenb44f9351044011a3 the dependencies are systemdatalinq version40 cultureneutral publickeytokenb77a5c561934e089 you should either ensure that the dependent assembly is correct for the target framework or ensure that the target framework you are addressing is that of the dependent assemblywe do not have an explicit reference to systemdatalinq up until the update to vs2012 we did not have any errors the miniprofiler version is indeed targeting net 40 as is our application what could be causing this warning,"['asp.net', '.net']" +455639,can 32 bit and 64 bit work together can 64 bit library work in a 32 bit application for example my application gui uses 32 bit qt and my business core is a 64 bit library the os is 64 bit can they work together and how thanks,['c++'] +455644,keypath not found in entity i want to show a formatted date in the section header of a table viewi used the following codebut its throwing an exception terminating app due to uncaught exception nsinvalidargumentexception reason keypath datesectionidentifier not found in entity nssqlentity expense id1guess the exception is coming when adding a sort descriptornsmutablearray sortdescriptors nsmutablearray alloc initwithcapacity20nssortdescriptor mainsortdescriptor nssortdescriptor alloc initwithkeydatesectionidentifier ascendingnosortdescriptors addobjectmainsortdescriptorfetchrequest setsortdescriptorssortdescriptorsexpensehnsstring datesectionidentifierexpensemdynamic datesectionidentifiernsstring datesectionidentifierself willaccessvalueforkeydatesectionidentifiernsstring tempdate self primitivedatesectionidentifierself didaccessvalueforkeydatesectionidentifieriftempdate nsdateformatter dateformatter nsdateformatter allocinit dateformatter setdateformatd m y tempdate dateformatter stringfromdateself date self setprimitivedatesectionidentifiertempdate dateformatter releasereturn tempdate,"['ios', 'objective-c']" +455645,how to show progress bar until video play in live stream android i am working on an application where i need to play video from a remote server as live streamwhich is done by me successfullyi managed every thing in my appbut when video is loading i need to show a progress dialog over videoviewi tried using onpreparedlistener as how to show the progress bar before playing the videooverridepublic void onpreparedmediaplayer mp progressbarsetvisibilityviewgone mpstartbut video play after 57 sec of progressbar gonei searched a lot on google but not found any solution for itcould anyone help methanks in advance,"['java', 'android']" +455701,how to reset asking for permission for chrome desktop notification windowwebkitnotificationsrequestpermission originally showed the prompt to the user asking them to allow or deny at one point when my notification showed up i clicked on the little wrench and then thisable from optionthen windowwebkitnotificationsrequestpermission no longer prompted me did i permanently stop my site from receiving or even allowing to request for permission i even went into chrome settings and opted in for allow notifications from all siteshow can i get that prompt to show up again currently checkpermission is 1 and i want to make it 0 again,['javascript'] +455709,instantiation of template member function in classhclass class public template typename t void functiont valuein classcpptemplatetypename t void classfunctiont value do sthin maincppinclude classhint mainint argc char argv class a afunction1 return 0i get a linked error because classcpp never instantiate void classfunctiont you can explicitly instantiate a template class with template class stdvectorinthow do you explicitly instantiate a template member of a nontemplate class thanks,['c++'] +455711,ipython install new modules i am used to the r functionality of installing packages and i am trying to do the same thing with ipython sometimes the following method works but then again sometimes it does not and i would like to finally find out why it only works half the time normally to install a module like the requests module for example i would type the following after opening a fresh terminal sudo pip install requestspassword this would then be followed by a message indicating that the install was succesfull or that it has already been installed requirement already satisfied use upgrade to upgrade requests in libraryframeworkspythonframeworkversions27libpython27sitepackagescleaning up which suggests that the code can be accessed and indeed if i run python now from the terminal it shows a good response without any errors whatsoever pythonactivepython 2725 activestate software inc based onpython 272 default jun 24 2011 122015 gcc 421 apple inc build 5664 on darwintype help copyright credits or license for more information import requests i now open pylab through alfred and it gives me an error welcome to pylab a matplotlibbased python environment backend wxaggfor more information type helppylabin 1 import requestsimporterror traceback most recent call lastusersvincentwarmerdamipythoninput1686486c241c8 in module 1 import requestsimporterror no module named requestsi have read some help from another question on stackoverflow here which suggests that i install the module from ipython shell this gives an even more baffeling response in 2 pip install requestsrequirement already satisfied use upgrade to upgrade requests in libraryframeworkspythonframeworkversions27libpython27sitepackagescleaning upin 3 import requestsimporterror traceback most recent call lastusersvincentwarmerdamipythoninput3686486c241c8 in module 1 import requestsimporterror no module named requeststhis seems very strange to me are there multiple versions of python installed on the system how could i check this do i need to point ipython to the location of the installed code,['python'] +455712,implementing action bar tabs with fragments so recently i needed to implement action bar tabs that would swap out the current fragment with a new fragment despite hours of intensive searching i was unable to find a clear solution so i thought i would present how i solved the problem here two of the fragments contained list views which turned out to be a major complicating factor,['android'] +455731,how do i get the different parts of a flask requests url i want to detect if the request came from the localhost50 or fooherokuappcom host and what path was requested how do i get this information about a flask request,['python'] +455774,list of all header files included by a c file i am trying to arm compile a c fileit includes lot of header files recursivelyi am trying to find the list of these header filesis there a easier way to find the list of all the header files it includes,"['c++', 'c']" +455838,android views background color randomly changed i have an app with many different screens running on acer a501 and samsung galaxy tab 101 1 and 2 devices sometimes without doing anything differently some viewgroup and textview views on the screen get their background colors changed i cannot reproduce this with any consistency but even after i call setbackgroundcolorcolorwhite on each of my views they still get randomly colored green red yellow etci am using a custom theme but only to change the look of edittext viewshas anyone seen this or have a solution to prevent my views from being colored randomlythanksadam,['android'] +455846,monodroid unhandled exception recovery i am trying to add a default handler to my application so i can recover from otherwise unhandled exceptionsi have found three mechanisms provided by androidmonodroid that as far as i can tell should make this possible but i cannot get any of them to work heres my codeusing systemusing androidappusing androidcontentusing androidruntimeusing androidviewsusing androidwidgetusing androidosnamespace testapp androidappactivitylabel testapp mainlauncher true icon drawableicon public class mainactivity activity protected override void oncreatebundle bundle baseoncreatebundle setcontentviewnew linearlayoutthis set up handlers for uncaught exceptions java solution javalangthreaddefaultuncaughtexceptionhandler new exceptionhandlerthis monodroid solution 1 androidenvironmentunhandledexceptionraiser androidenvironment unhandledexceptionraiser monodroid solution 2 appdomaincurrentdomainunhandledexception delegate new alertthis appdomaincurrentdomainunhandledexception error throw an exception to test throw new exceptionuncaught exception void androidenvironment unhandledexceptionraiserobject sender raisethrowableeventargs e found a suggestion to set the handled flagtrue but it has no effect new androidruntimeraisethrowableeventargseexceptionhandled true new alertthis androidenvironmentunhandledexceptionraiser error public class exceptionhandler javalangobject javalangthreadiuncaughtexceptionhandler private context context public exceptionhandlercontext c context c public void uncaughtexceptionjavalangthread thread javalangthrowable ex new alert context java exception handler public class alert public alertcontext c string src string title alert androidappalertdialogbuilder builder new androidappalertdialogbuilderc buildersettitletitle buildersetmessagesrc buildersetpositivebuttonok delegate androidappalertdialog alert buildercreate alertshow any help would be appreciated thanks,"['c#', 'android']" +455858,proper practice for subclassing uiview i am working on some custom uiviewbased input controls and i am trying to ascertain proper practice for setting up the view when working with a uiviewcontroller it is fairly simple to use the loadview and related viewwill viewdid methods but when subclassing a uiview the closest methosds i have are awakefromnib drawrect and layoutsubviews i am thinking in terms of setup and teardown callbacks in my case i am setting up my frame and internal views in layoutsubviews but i am not seeing anything onscreen what is the best way to ensure that my view has the correct height and width that i want it to have my question applies regardless of if i am using autolayout although there might be two answers whats the proper best practice,"['ios', 'objective-c']" +455909,how can i perform a culturesensitive startswith operation from the middle of a string i have a requirement which is relatively obscure but it feels like it should be possible using the bclfor context i am parsing a datetime string in noda time i maintain a logical cursor for my position within the input string so while the complete string may be 3 january 2013 the logical cursor may be at the jnow i need to parse the month name comparing it against all the known month names for the cultureculturesensitivelycaseinsensitivelyjust from the point of the cursor not later i want to see if the cursor is looking at the candidate month namequickly and i need to know afterwards how many characters were usedthe current code to do this generally works using compareinfocompare it is effectively like this just for the matching part there is more code in the real thing but it is not relevant to the matchinternal bool matchcaseinsensitivestring candidate compareinfo compareinfo return compareinfocomparetext position candidatelength candidate 0 candidatelength compareoptionsignorecase 0however that relies on the candidate and the region we compare being the same length fine most of the time but not fine in some special cases suppose we have something like u00e9 is a single code point for eacutevar text x bu00e9d yint position 2 e followed by u0301 still means eacute but from two code pointsvar candidate beu0301dnow my comparison will fail i could use isprefixif compareinfoisprefixtextsubstringposition candidate compareoptionsignorecasebutthat requires me to create a substring which i would really rather avoid i am viewing noda time as effectively a system library parsing performance may well be important to some clientsit does not tell me how far to advance the cursor afterwardsin reality i strongly suspect this would not come up very often but i would really like to do the right thing here i would also really like to be able to do it without becoming a unicode expert or implementing it myself raised as bug 210 in noda time in case anyone wants to follow any eventual conclusioni like the idea of normalization i need to check that in detail for a correctness and b performance assuming i can make it work correctly i am still not sure how whether it would be worth changing over all it is the sort of thing which will probably never actually come up in real life but could hurt the performance of all my users i have also checked the bcl which does not appear to handle this properly either sample codeusing systemusing systemglobalizationclass test static void main var culture cultureinfo cultureinfoinvariantcultureclone var months culturedatetimeformatabbreviatedmonthnames months10 beu0301d culturedatetimeformatabbreviatedmonthnames months var text 25 bu00e9d 2013 var pattern dd m y datetime result if datetimetryparseexacttext pattern culture datetimestylesnone out result consolewritelineparsed result0 result else consolewritelinedid not parse changing the custom month name to just bed with a text value of bed parses fineokay a few more data pointsthe cost of using substring and isprefix is significant but not horrible on a sample of friday april 12 2013 202842 on my development laptop it changes the number of parse operations i can execute in a second from about 460k to about 400k i would rather avoid that slowdown if possible but it is not too badnormalization is less feasible than i thought because it is not available in portable class libraries i could potentially use it just for nonpcl builds allowing the pcl builds to be a little less correct the performance hit of testing for normalization stringisnormalized takes performance down to about 445k calls per second which i can live with i am still not sure it does everything i need it to for example a month name containing a should match ss in many cultures i believe and normalizing does not do that,['.net'] +455999,cassandra client java apis i have recently started working with cassandra database now i am in the process of evaluating which cassandra client we should go forward with i have seen various post on stackoverflow about which client to use for cassandra but none has very definitive answer my team has asked me to do some research on this and come up with certain pros and cons for each cassandra client apias in javaas i mentioned i recently got involved with cassandra so not have that much idea why certain people choose pelops client and why certain people go with astyanax and some other clients i know brief things about each of the cassandra clients by which i mean i am able to make that work and start reading and writing to cassandra databasebelow is the information i have so farcassandra apishector productionreadythe most stable of the java apis ready for primetimeastyanax the up and comera clean java api from netflix it is not as widely used as hector but it is solid kundera the nosql ormjpa compliant this is handy when you want to interact with cassandra via objectsthis constrains you somewhat in that you would not be able to have a dynamic number of columnsnames etc but it does allow you to port over orms or centralize storage onto cassandra for more traditional usespelopsi have only used pelops briefly it was a straight forward api but did not seem to have the momentum behind it playorm orm without the constraintsi just heard about this it looks like it is trying to solve the impedance mismatch between traditional jpabased orms and nosql by introducing jql it looks promisingthrift avoid methis is the lowlevel apibelow are our priorities in deciding cassandra clientfirst priorities are low latency overhead asynch api and reliabilitystability for production environmenteg a more userfriendly apis that can be had in the dal that wraps the clientconnection pooling and partition awareness are some other good feature to haveable to detect any new nodes that got addedgood support as well as pointed by dean belowcan anyone provide some thoughts on this and also any pros and cons for each cassandra client and also which client can fulfill my requirements will be of great help as welli believe mainly i will be revolving around astyanax client or new datastax client that uses binary protocol i guess basis on my research so far but do not have certain information to back my research and present it to my teamany comparison between astyanax client and new datastax clientwhich uses new binary protocol will be of great helpit will be of great help to me in my research and will get lot of knowledge on this from different people who have used different clients in the past,['java'] +456005,javaxnetsslsslexception unrecognized ssl message plaintext connection i am trying to send a mail from spring application i have included all the jar files but it is showing this exceptionjavaxmailmessagingexception exception reading response nested exception is javaxnetsslsslexception unrecognized ssl message plaintext connection at comsunmailsmtpsmtptransportreadserverresponsesmtptransportjava1611 at comsunmailsmtpsmtptransportopenserversmtptransportjava1369 at comsunmailsmtpsmtptransportprotocolconnectsmtptransportjava412 at javaxmailserviceconnectservicejava310 at javaxmailserviceconnectservicejava169 at javaxmailserviceconnectservicejava118 at javaxmailtransportsend0transportjava188 at javaxmailtransportsendtransportjava118 at orgsymbleavemanagementmailsamplemailsentmailsamplemailjava65 at orgsymbleavemanagementcontrolleradmincontrollerprocessregistratinguseradmincontrollerjava196 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava57 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43 at javalangreflectmethodinvokemethodjava601 at orgspringframeworkwebbindannotationsupporthandlermethodinvokerinvokehandlermethodhandlermethodinvokerjava175 at orgspringframeworkwebservletmvcannotationannotationmethodhandleradapterinvokehandlermethodannotationmethodhandleradapterjava421 at orgspringframeworkwebservletmvcannotationannotationmethodhandleradapterhandleannotationmethodhandleradapterjava409 at orgspringframeworkwebservletthispatcherservletdothispatchthispatcherservletjava774 at orgspringframeworkwebservletthispatcherservletdoservicethispatcherservletjava719 at orgspringframeworkwebservletframeworkservletprocessrequestframeworkservletjava644 at orgspringframeworkwebservletframeworkservletdopostframeworkservletjava560 at javaxservlethttphttpservletservicehttpservletjava641 at javaxservlethttphttpservletservicehttpservletjava722 at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava305 at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava210 at orgapachecatalinacorestandardwrappervalveinvokestandardwrappervalvejava224 at orgapachecatalinacorestandardcontextvalveinvokestandardcontextvalvejava169 at orgapachecatalinaauthenticatorauthenticatorbaseinvokeauthenticatorbasejava472 at orgapachecatalinacorestandardhostvalveinvokestandardhostvalvejava168 at orgapachecatalinavalveserrorreportvalveinvokeerrorreportvalvejava98 at orgapachecatalinavalvesaccesslogvalveinvokeaccesslogvalvejava927 at orgapachecatalinacorestandardenginevalveinvokestandardenginevalvejava118 at orgapachecatalinaconnectorcoyoteadapterservicecoyoteadapterjava407 at orgapachecoyotehttp11abstracthttp11processorprocessabstracthttp11processorjava987 at orgapachecoyoteabstractprotocolabstractconnectionhandlerprocessabstractprotocoljava579 at orgapachetomcatutilnetjioendpointsocketprocessorrunjioendpointjava309 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava10 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava603 at javalangthreadrunthreadjava722caused by javaxnetsslsslexception unrecognized ssl message plaintext connection at sunsecuritysslinputrecordhandleunknownrecordinputrecordjava541 at sunsecuritysslinputrecordreadinputrecordjava374 at sunsecuritysslsslsocketimplreadrecordsslsocketimpljava893 at sunsecuritysslsslsocketimplperforminitialhandshakesslsocketimpljava1294 at sunsecuritysslsslsocketimplreaddatarecordsslsocketimpljava848 at sunsecuritysslappinputstreamreadappinputstreamjava102 at comsunmailutiltraceinputstreamreadtraceinputstreamjava110 at javaiobufferedinputstreamfillbufferedinputstreamjava235 at javaiobufferedinputstreamreadbufferedinputstreamjava254 at comsunmailutillineinputstreamreadlinelineinputstreamjava88 at comsunmailsmtpsmtptransportreadserverresponsesmtptransportjava1589 38 more,['java'] +456033,django get thisplay name choices i am trying to find a solution to my problemmodelspyclass articlemodelsmodel title modelscharfieldmax length100 slug modelsslugfield description modelstextfielddef archive qualityself return selfarchive setorder byqualitythistinctvalues listquality flattrueclass archivemodelsmodel choices quality 1 hd yb 2 hd bj 3 hd poqd 4 hd anbc article modelsforeignkeyarticle quality modelscharfieldmax length100 choiceschoices qualityarhiveshtml for article in articles article for quality in articlearchive quality qualityget quality thisplay this is not working endfor endfor updatethe function archive quality is important because it prevents recurrence in the template objectsexamplearticle my article onearchive quality 123 without the function quality 123 with function,['python'] +456041,how to set a default prompt when nothing selected for select using css is it possible to set a default prompt when nothing is selected for select box using css or is there an elegant way to deal with this other than optionselect hereoption,"['html', 'css']" +456066,apps would not run on gae unable to bind to localhost0 i recently upgraded google app engine to 177 and have not been able to run any apps locally since this includes apps that worked before the update and apps i have created since i have not come across any other references to this specific problem unable to bind to localhost0 so any insights into clearing this hurdle would be much appreciatedi am including the log for a new hello world app i added today using python 27 via activepython on os x 1068 running dev appserver with the following flags skip sdk update checkyes port12084 admin port8007python command usrlocalbinpythonwinfo 20130413 063731627 devappserver2py498 skipping sdk update checkwarning 20130413 063731691 api serverpy328 could not initialize images api you are likely missing the python pil modulewarning 20130413 063731692 simple search stubpy977 could not read search indexes from varfoldersagag25hklmfeg1p0plbbx5mktitmpappenginebinderrorbsearch indexestraceback most recent call last file applicationsgoogleappenginelauncherappcontentsresourcesgoogleappenginedefaultbundlecontentsresourcesgoogle appenginedev appserverpy line 193 in module run file file globals file applicationsgoogleappenginelauncherappcontentsresourcesgoogleappenginedefaultbundlecontentsresourcesgoogle appenginedev appserverpy line 189 in run file execfilescript path globals file applicationsgoogleappenginelauncherappcontentsresourcesgoogleappenginedefaultbundlecontentsresourcesgoogle appenginegoogleappenginetoolsdevappserver2devappserver2py line 662 in module main file applicationsgoogleappenginelauncherappcontentsresourcesgoogleappenginedefaultbundlecontentsresourcesgoogle appenginegoogleappenginetoolsdevappserver2devappserver2py line 655 in main dev serverstartoptions file applicationsgoogleappenginelauncherappcontentsresourcesgoogleappenginedefaultbundlecontentsresourcesgoogle appenginegoogleappenginetoolsdevappserver2devappserver2py line 626 in start apisstart file applicationsgoogleappenginelauncherappcontentsresourcesgoogleappenginedefaultbundlecontentsresourcesgoogle appenginegoogleappenginetoolsdevappserver2api serverpy line 151 in start superapiserver selfstart file applicationsgoogleappenginelauncherappcontentsresourcesgoogleappenginedefaultbundlecontentsresourcesgoogle appenginegoogleappenginetoolsdevappserver2wsgi serverpy line 296 in start raise binderrorunable to bind ss selfbind addrgoogleappenginetoolsdevappserver2wsgi serverbinderror unable to bind localhost0update i was able to deploy the hello world app through gae launcher without any issues i ran the command errinfo c n googleappenginelauncherapp which uses the included dtrace and then attempted to run three apps then closed them here is the output which is somewhat beyond me exec syscall err count desc googleappengine madvise 12 1 cannot allocate memory googleappengine thisable threadsignal 0 2 googleappengine access 0 3 googleappengine bsdthread register 22 3 invalid argument googleappengine chdir 0 3 googleappengine close nocancel 0 3 googleappengine fcntl nocancel 0 3 googleappengine fork 0 3 googleappengine getdtablesize 0 3 googleappengine getpid 0 3 googleappengine open nocancel 0 3 googleappengine setsid 0 3 googleappengine sigprocmask 0 3 googleappengine stat64 0 3 googleappengine wait4 0 3 googleappengine workq open 0 3 googleappengine write 0 3 googleappengine lstat64 0 4 googleappengine pipe 0 6 googleappengine thread selfid 0 6 googleappengine gettimeofday 0 7 googleappengine dup2 0 9 googleappengine madvise 0 17 googleappengine munmap 0 31 googleappengine mmap 0 33 googleappengine sigaction 0 87 googleappengine getattrlist 0 102 googleappengine fstat64 0 118 googleappengine open 0 118 googleappengine geteuid 0 208 googleappengine dup 0 10418 googleappengine read 0 10532 googleappengine close 0 10584 googleappengine workq kernreturn 0 20752 googleappengine close 9 21459 bad file descriptor googleappengine kevent 0 72543 update 2 16 august i installed the newest version of gae launcher 183 and everything now works,['python'] +456122,get the closest value for combinations of an array js i am looking for an algorithm that i can use for combining values in array to get as close as possible to another valuefor instance the number i want to find out what combination that gives the closes result to is 25 and my array is 05 10 15 20 30 the combination in this case would be 200527 would yield the same combo 25 is the closest while 37 would yield 3005 and 70 would be 303010i have been reading up on different algorithms to create available combinations and such a for instance this one however i am having difficulties to write a function that allows for the same value to be used multiple times like my example with 70 this makes the number of combinations quite largeanyone having a good example tucked away or have any pointers to giveeditzkar told me about the knapsack problem i may add that for my example the sought after value are in a specified range 10 and 100 a which limits the the combinations somewhat,"['javascript', 'jquery']" +456146,optimal way to find common negative space in map of student ids to class times i am writing a proof of concept for a scheduling application in php i have a 2d array of the student schedule in the format of str class time array student ids printout at this point in the processing i need to determine which class time is the most appropriate to host a new course with say 10 students requesting it to this end i would i want to determine how many students have n class times available ideally stored as class time student ids and available class timesso what is an ideal way to buildsearch this data the end result is a list of all class times and an idea of what students can utilize a given class as each new course is scheduled this allows me to sort by available class times to find the students who are most constrained in their schedule and who need priority in being schedule to a given class given how hard it would be to schedule them in the future given a number of presentpotential constraints,['php'] +456150,android record square video i am currently trying to record a video with the mediarecorder and a camera but for my application i need to record a video in squareformat like instagram does with pictures to be independet of device orientation is there any way to automatically crop and preview a video in a squareresoultion fi 800x800 or do i have to crop the video manually i have ffmpeg available on the androiddevice,['android'] +456164,why concurrency control uses the classic twocondition algorithm while reading the source code of arrayblockingqueue i found a comment explaining that it uses the classic twocondition algorithm found in any textbook concurrency control uses the classic twocondition algorithm found in any textbook main lock guarding all access private final reentrantlock lock condition for waiting takes private final condition notempty condition for waiting puts private final condition notfullwhy does it use the classic twocondition notempty notfull algorithm,['java'] +456172,calayers never calls it is delegates drawlayerincontext even after layer setneedsthisplay and layer thisplay i cannot figure out why the calayers i am creating are not calling their drawlayer method i have created a drawlayer delegate object for them yet it never gets called from a uiview subclass idinitwithframecgrectframe self super initwithframeframe if self uiview bg uiview alloc initwithframeselfbounds i have a property called bg to reference the child uiview selfbg bg self addsubviewselfbg an nsobject subclass i use as a calayer delegate mylayerdelegate drawer mylayerdelegate new selfdrawer drawer cagradientlayer layer cagradientlayer layer layerdelegate selfdrawer layername bg selfbglayer addsublayerlayer layer setneedsthisplay layer thisplay return selfin selfdrawer i have voiddrawlayercalayer layer incontextcgcontextrefcontext nsloglayer called drawlayer some drawing goes herei have tried many different things i have tried setting setneedsthisplay on selfbglayer i have tried setneedsthisplay on selfbg i have tried layer setneedsthisplay before and after addsublayer i have tried layer thisplay before and after addsublayer i have tried with and without layer thisplay and layer thisplayifneededwhy does the layer refuse to draw,"['ios', 'objective-c']" +456186,testing for empty or nilvalue string i am trying to set a variable conditionally in ruby i need to set it if the variable is nil or empty 0 length string i have come up with the followingvariable id if variablenil variablenil variableemptywhile it works it does not seem very rubylike to me is the a more succinct way of expressing the above,"['ruby-on-rails', 'ruby']" +456306,is there a use case for not using this when calling gcsuppressfinalizethis i was just implementing the thispose pattern and when i just typed the gcsuppressfinalizethis line i was wondering if there is ever a use case for using something other than this as the parameter to the methodthis is the typical patternpublic void thispose thisposetrue gcsuppressfinalizethis right heredoes it ever make sense to call gcsuppressfinalize with something other than thispublic void thispose thisposetrue gcsuppressfinalizefoo should this ever happen,['c#'] +456358,style the nth letter in a span using css i havespan idstring12h12m12sspanand i am looking to make the h m and s smaller than the rest of the text i have heard of the nthletter pseudo element in css but it does not seem to be workingstringnthletter3stringnthletter6stringnthletter9 fontsize 2emi know i could use javascript to parse the string and replace the letter with surrounding span tags and style the tags however the string is updated every second and it seems parsing that often would be ressource intensive,"['javascript', 'css']" +456369,joda datetime to timestamp conversion i am trying to change the value of timestamp by datetimezone in joda datetime dt new datetimersgettimestampanytimestampcolumn datetimezoneforidanytimezone timestamp ts new timestampdtgetmillisfor datetime value is 20130413t2256270300for timestamp value is 20130413 2256270timestamp is coming without timezone difference how can i get the correct timestamp with timezone for example i want to get 20130513 0156270thanks in advanceedit using mysql column type is timestamp of course rs is resultset,['java'] +456380,c11 safely join a thread without using a try catch block according to the documentation here and here the join method of a c11 thread will throw a stdsystem error if joinable false thus the natural way to wait for a thread to complete execution is something along the lines ofif thread2joinable thread2joinhowever this has the possibility to throw a stdsystem error consider thread 1 calls thread2joinable returns true indicating that the thread2 is still running then the scheduler pauses thread1 and switches contexts to thread 2 thread 2 completes and then thread 1 resumes thread 1 calls thread2join but thread2 has already completed and as a result stdsystem error is throwna possible solution is to wrap the whole thing in a try blocktry thread2joincatch stdsystem error e but then when a legitimate stdsystem error is thrown possibly to indicate that the thread failed to join the program continues on acting as though everything is fine and dandy is there a proper way to join a thread besides using a trycatch block like this,['c++'] +456510,reading and writing from xls and xlsx excel file in java i am writing a program which needs to read and write from excel files irrespective of the formatxls or xlsxi am aware of the apache poi but it seems it has different classes to handle xls filehssf and xlsxxssf filesanyone aware of how i might achieve what i am trying to do hereideas for using an api other than poi are also welcome,['java'] +456565,write a file in hdfs with java i want to create a file in hdfs and write data in that i used this codeconfiguration config new configuration filesystem fs filesystemgetconfig path filenamepath new pathinputtxt try if fsexistsfilenamepath fsdeletefilenamepath true fsdataoutputstream fin fscreatefilenamepath finwriteutfhello fincloseit creates the file but it doest write anything in it i searched a lot but did not find anything what is my problem do i need any permission to write in hdfsthanks,['java'] +456574,eclipse error unbound classpath container i recieved two error messages after i made my projectthe project cannot be built until build path errors are resolved unbound classpath container jre system library osgiminimum12 in project method testi think that if i figure out the second error the first one will go away however i am running eclipse juno on a 1058 mac and i cannot install the necessary jre from the oracle website as they do not it compatible for mac,['java'] +456637,laravel 4 file upload i am trying to upload some photos and handle this with the build in laravel functions but i cannot for the life of me figure out how to do this properly i have been able to actually upload something but i have run into a few problems this is the code i have right nowif looked at the documentation and found this function file inputfilephoto i have used this function and what the content of file becomes is an instance of symfonycomponenthttpfoundationfileuploadedfile which as the documentation tells us extends the php splfileinfo class and provides a variety of methods for interacting with the file then i used this function inputfilephotomovedestinationpath which should but the file in the desired folder on the server and it did but now comes the problem now all uploaded files have a filename like phpgojnlc and without an extensioni have looked at the functions available from splfileinfo and tried getextension which give me an empty string and getfilename which also gives me something like phpgojnlcthen i looked around on the internet and found a few part of code from laravel 3 where they did something like thisfilename strrandom20 fileextensioninputfilephotonamebut the result of this is give me only the result from strrandom20 followed by a dot again no file extensionso what am i doing wrong how to upload a file with laravel 4,['php'] +456645,wait for and seconds then next line of code without freezing form hi i am trying to find a method of waiting a number of milliseconds before moving to the next line of codei have looked into threadsleep but this will freeze the main form i would like this to remain activei tried timers and stopwatches and both freeze the main form when they should be posting to a console when they tick i could not find a way of using taskdelay or background worker in the wait i wanted eitherpseudo codewait 2 6 secondslog waitinglog waitinglog waitingstop waiting run next line of codethe methods i have tried just freeze up the form and fill the log afterwards i just want a simple method of waiting without freezing the form and without having to deal with events being called which would mean the next line is not run any help would be awesome because i am still new to c and its been driving me a bit mad,['c#'] +456697,when i type nonascii characters using a windows keyboard i get when i type nonascii characters using a windows keyboard in the language bar i get question marks where the nonascii characters should gocopyandpaste works fine and the unicode characters are thisplayed in the text widgeti am using the lakota allinone keyboard found here this particular keyboard is listed in the windows language bar under the us locale,['python'] +456756,how to organize list by frequency of occurrence and alphabetically in case of a tie while eliminating duplicates basically if given a listdata apple pear cherry apple pear apple bananai am trying to make a function that returns a list like thisapple pear banana cherryi am trying to make the return list ordered by most frequently occurring word first while breaking ties by ordering them alphabetically i also am trying to eliminate duplicatesi have made lists already of the counts of each element and the indices of each element in datax ncount for and in dataz nindex for and in datai do not know where to go from this point,['python'] +456821,python how to hash a string into 8 digits is there anyway that i can hash a random string into a 8 digit number without implementing any algorithms myself thanks,['python'] +456875,move semantics with unique ptr i am using visual studio 2012 update 2 and am having trouble trying to understand why stdvector is trying to use the copy constructor of unique ptr i have looked at similar issues and most are related to not having an explicit move constructor andor operator if i change the member variable to a string i can verify that the move constructor is called however trying to use the unique ptr results in the compilation errorerror c2248 stdunique ptr tyunique ptr cannot access private member declared in class stdunique ptr tyi am hoping someone can point me to what i am missing thanks include vectorinclude stringinclude memoryclass myobjectpublic myobject ptrstdunique ptrintnew int myobjectmyobject other ptrstdmoveotherptr myobject operatormyobject other ptr stdmoveotherptr return this private stdunique ptrint ptrint mainint argc char argv stdvectormyobject s for int i 0 i 5 i myobject o spush backo return 0,['c++'] +456877,integration testing with rethis i have started using rethis in my project with the help of the jethis library all is working fine but now i have a problem that my functional tests requires rethis to be up which i want to avoid in my continuous integration what is the best way to do this,['java'] +456895,jquery file upload restricting number of files i am using jquery file upload to upload the files to the server i want to restrict the user to upload maximum 6 files i search the wiki jquery file upload but didnt find the parameter for it is there any way that i can restrict the user on number of uplaods,['jquery'] +456921,the entity type name is not part of the model for the current context i create a model using ef and generated its context using dbcontext 5x generator now i renamed class name of one of my entities now when i run my code i get the entity type student2 is not part of the model for the current context errorvar context new myentitiesconnectionstringforeachvar student in contextstudents consolewritelineclassnametostringin my data contextpublic partial class myentities dbcontext public myentities basenamemyentities protected override void onmodelcreatingdbmodelbuilder modelbuilder throw new unintentionalcodefirstexception public dbsetstudent students get set origional public dbsetstudent2 student get set i renamed student to student2how to fix this i need to rename my class due to some conflicts,['c#'] +456933,merge 2 arrays using linq i have two simple array and i would like to merge using join linq int num1 new int 1 55 89 43 67 3 int num2 new int 11 35 79 23 7 10 var result from n1 in num1 from n2 in num2 select result,['c#'] +456935,how can i invoke an action on the same selection of spinner value i select the value from spinner and when i select the same value again then no action is performed on the click,['android'] +456943,run a function on first time page load not on page refresh in javascript i would like a function to be executed only on the first page load and not when page is refreshedfor example it should not execute when the user clicks on the submit button or on other page refreshi can avoid it in net by using the ispostback property but how can i do this in javascript,['javascript'] +456947,when time zone of china it goes work as good java will not as some game developing might use the date time which is in the past or in the future and in any time zone of a date time emulation even we never reach them in reality for this assumption not saying that i am calculating on fake date times but for the correctness of calculation on any date time in any time zone like it was in reality i previously asked a question about the time zone issue of china in java which was regarded as a duplicate question and i so deleted it however from this comment thread i am aware that it is some kind of time rewindtransition issue in java not just about the time zone change and now i repost this question in a different manner to present this issue with the following code in java import orgjodatimeimport javautilclass pandatest static long subtract date minuend date subtrahend datetimezone zone long millis ifnullzone millisminuendgettimesubtrahendgettime else long rhs new localdatetimesubtrahendtodatetimezone getmillis long lhs new localdatetimeminuendtodatetimezone getmillis millislhsrhs return millis10 static date maketime int year int month int day int hour int minute int second calendar calendar calendargetinstancetimezonegettimezoneprc calendarsetyear month1 day hour minute second return calendargettime static void putsstring arg0 systemoutprintlnarg0 static void showdurationdatetimezone zone date args int argcargslength puts putstime zone nullzonezonetostringunspecified forint i0 argc0 i putstime i argsi ifi0 long durationsubtractargsi argsi1 zone putsduration duration public static void mainstring args date retainsofthedaymaketime1900 1 1 8 5 510 date somewhereintimemaketime1900 1 1 8 5 511 datetimezone zonedatetimezoneforidprc showdurationnull retainsoftheday somewhereintime showdurationzone retainsoftheday somewhereintime the problem occurs if i constructed a localdatetime of jodatime from a date of java the version of jdk is 7u17 and jodatime is 22 it does not happen in c with nodatime i put an alternative version of code at the rear of this post for contrasting question how the transition occurs is it exact as the unix epoch i possibly use the term transition in a wrong way what i mean is the strange result of subtracting 190011 8552 by 190011 8551 in java there is not a time zone change at that time does something like this only occur in the specific time zone or all of the time zonesmaybe at some different instantif one would possibly calculate on arbitrary date times in any time zone expecting the result would always be correct should date and calendar be used if yes how to use them without the issue occurs should we no longer to use date and calender in java once we possibly calculate on date times before 1970 or after 2038 alternative code the code contains content both in c and java that we can contrast the result in c and java conveniently like java like sharp the code contains content either in java or c an odd number of slashstarslash at the beginning to compile in java an even number of slashstarslash at the beginning to compile in c ps zero would be treated as an even numberusing datesystemdatetimeusing nodatimetimezonesusing nodatimeusing systemcollectionsgenericusing systemlinqusing system import orgjodatimeimport javautil clockcant in java class clockcant public static date maketime int year int month int day int hour int minute int second calendar calendar calendargetinstancetimezonegettimezoneprc calendarsetyear month1 day hour minute second return calendargettime public static datetimezone getzonefromidstring id return datetimezoneforidid public static string getyourzoneid return datetimezonegetdefaultgetid public static long subtract date minuend date subtrahend datetimezone zone long millis ifnullzone millisminuendgettimesubtrahendgettime else long rhs new localdatetimesubtrahendtodatetimezone getmillis long lhs new localdatetimeminuendtodatetimezone getmillis millislhsrhs return millis10 a minimum implementation of clike listt for javaclass listt public t toarray return items public int count return itemslength public listt args itemsargs t items clockcant in cclass clockcant public static date maketime int year int month int day int hour int minute int second return new dateyear month day hour minute second public static datetimezone getzonefromidstring id return datetimezoneproviderstzdbid public static string getyourzoneid return datetimezoneproviderstzdbgetsystemdefaultid public static long subtract date minuend date subtrahend datetimezone zone long ticks ifnullzone ticksminuendsubtractsubtrahendticks else var rhs localdatetimefromdatetimesubtrahend inzonelenientlyzone var lhs localdatetimefromdatetimeminuend inzonelenientlyzone tickslhstoinstantrhstoinstantticks return tickstimespantickspersecond extension for javalike methods in cstatic partial class javaextensions public static string tostringthis object x return xtostring class pandatest class pandatest in java public static void mainstring args languagejava mainargs static void putsstring arg0 systemoutprintlnarg0 static void showdurationdatetimezone zone date args showdurationzone new listdateargs in c static void putsstring arg0 consolewritelinearg0 static void showdurationdatetimezone zone params date args showdurationzone argstolist the following code are for both c and java static void showdurationdatetimezone zone listdate args int argcargscount date argvargstoarray puts putstime zone nullzonezonetostringunspecified forint i0 argc0 i putstime i argvi ifi0 long durationclockcantsubtractargvi argvi1 zone putsduration duration static void mainstring args date retainsofthedayclockcantmaketime1900 1 1 8 5 510 date somewhereintimeclockcantmaketime1900 1 1 8 5 511 datetimezone zoneclockcantgetzonefromidprc putscurrent time zone clockcantgetyourzoneid putslanguage language showdurationnull retainsoftheday somewhereintime showdurationzone retainsoftheday somewhereintime static string languagecto compile in java add a at the beginning of the code as the following like java like sharp,"['c#', 'java']" +456966,how to add object multi nsarray in one nsmutablearray i want add object from 2 nsarray to nsmutablearray i dont know about thisthis my codeinterface viewcontroller uitableviewcontroller nsarray animal nsarray color nsmutablearray allimplementation viewcontroller voidviewdidload super viewdidload animal nsarray allocinitwithobjectsliontigerdogcatsheepwolf nil color nsarray allocinitwithobjectsblueredyellowgreenblack nil all how to add object from animal and color array in all,"['ios', 'objective-c']" +457005,android activity getting destroyed after calling camera intent i am having two activities a1 a2 a1 calls a2 and from a2 i am calling the camera intent as belowlaunchintent new intentandroidprovidermediastoreaction image capturelaunchintentputextramediastoreextra outputphotopath startactivityforresultlaunchintentcamera requestit opens the camera and i can take the picture but the problem arises once i click the save button tick button in s3 my onactivityresult is not called instead a2s ondestroy method is called i have few logics to be done in the onactivityresult fni had read some post in stackoverflow regarding this but i couldnt get useful output from thati have my manifest like this for my second activitya2androidconfigchangeskeyboardhiddenorientationlocaleandroidscreenorientationportraitnote in htc one x my onactivityresult fn is getting called but in my s3 second activitya2 is getting destroyedplz share your thoughts on this thanks in advance,['android'] +457033,jquery mobile best way to create pop up and content dynamically i have the following code creating a pop up using jquery mobile the pop up is created and a form is created and appended to the popup along with two buttons this code does work but i am wondering if there is a better way to achieve my intended goal create a div for the popup var popup divpopup thismissible false theme a overlyatheme a transition pop bindpopupafterclose function remove the popup when closing thisremove create a title for the popup h2 text purchase title appendtopopup create a message for the popup p text purchase text appendtopopup create a form for the pop up formappendinput type password name password placeholder password input placeholder appendtopopup create a submit buttonfake a text submit btn txt buttonmarkup inline true icon check bindclick function popuppopupclose thatsubscribetoassetcallback appendtopopup create a back button a text back btn txt datajqmrel back buttonmarkup inline true icon back appendtopopup popuppopupopentriggercreate,['jquery'] +457064,how can i implement simple serverless p2p browser to browser messaging with minimal overhead i am trying to create some basic implementations of simple games tic tac toe is the starting project which can be played over the internet without requiring a central server the page would not even need to be hosted and could be run locally on the machine or it could be hosted on a web server when hosting the game the page would inform the host of his ip address which could then be sent by any method phone instant message etc to a friend that friend would type or copypaste the ip into a join dialog and be able to play the game in question i would like these 2 parties to be able to do this without installing any additional software and without contacting a central server of any kindi have looked into many potential solutions involving nodejs webrtc websockets flash java etc each one of these has a problem associated with it such as requiring a central server or requiring the client to potentially have to download something that is not already installed on their computer or only transferring audio and video and not being useful for sending data messages it may seem trivial to tell someone that they need to download java or for me to develop the application with flash but that is all contrary to my ultimate goalsif it just is not possible to do what i am trying to do entirely in javascript then it just is not possible but i do not see why it could not be considering that browsers are capable on their own of sending and receiving text data to urls which resolve to ips or directly to ips other solutions are welcome but if this is not possible to do it really should bethe simple explanation of the exact requirements for what i am trying to do isshould use entirely free as in beer technologies no flash i realize that web apps for flash player can be coded for free but peer to peer in stratum requires a signup for a beta key which assuming i could obtain for free wouldnt necessarily remain free foreverno external servers or false peer to peer again as in flash or unity based solutions where the imitation of peer to peer can be acheived as long as you use their central serverno client downloads sure most people have java or flash installed but many do not and java is a pretty hefty download and not friendly for computer illiterate users it even tries to install toolbars now on top of this many of my users would not be willing to download anything at all including java or unity which have their own issues relating to this project as already mentionedin summary if ajax can send a request to a specified ip and listen for a response why cannot i get simple peer to peer messaging in pure js or can ii should not need to host a full blown web server or a seperate application or plugin of any kind to send and receive dataam i missing something,['javascript'] +457116,position fixed changes width of element when using percentages when i apply positionfixed to an element it is width changes the element is inside a container with a width set in percentage how do i make it keep the same width as in positionstatic or inherit the exact same width as its parent,['css'] +457136,slow performance of multidimensional array initialiser i have some weird performance results that i cannot quite explainit seems that this lined new double4 41 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1is 4 times slower than this oned new double4 4d0 0 1 d0 1 0 d0 2 0 d0 3 0 d1 0 0 d1 1 1 d1 2 0 d1 3 0d2 0 0 d2 1 0 d2 2 1 d2 3 0d3 0 0 d3 1 0 d3 2 0 d3 3 1and that is not even considering the fact that in this example i could leave out all those 0 assignmentsi know that looping over a multidimensional array in c can be slow due to the boundary checks but there is no loop here no boundary checks are required and the whole array initializer line can be resolved at compile time the second code block however has to first initialize the array to zero then overwrite each value individuallyso what is the problem here and what would be the best way to initialize this array if performance is an issuei used the following code to measure performanceusing systemusing systemdiagnosticsclass program public static double d global static variable to prevent the jit optimizing it away static void mainstring args stopwatch watch int numiter 10 repeat all tests this often double d2 new double4 41 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 use arrayinitializer slowest watch stopwatchstartnew for int i 0 i numiter i d new double4 41 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 consolewritelinearrayinitializer t00ms watchelapsedmilliseconds 10 numiter use arraycopy faster watch stopwatchstartnew for int i 0 i numiter i d new double4 4 arraycopyd2 d d2length consolewritelinenew arraycopy t00ms watchelapsedmilliseconds 10 numiter direct assignment fastest watch stopwatchstartnew for int i 0 i numiter i d new double4 4 d0 0 1 d0 1 0 d0 2 0 d0 3 0 d1 0 0 d1 1 1 d1 2 0 d1 3 0 d2 0 0 d2 1 0 d2 2 1 d2 3 0 d3 0 0 d3 1 0 d3 2 0 d3 3 1 consolewritelinedirect assignment t00ms watchelapsedmilliseconds 10 numiter the resultsarrayinitializer 07917msnew arraycopy 02739msdirect assignment 02281ms,['c#'] +457269,youtube iframe embeds throw javascript errors in internet explorer 8 it seems that simple youtube iframe embeds throw javascript errors when viewed in internet explorer 8 hopefully someone can find what i am doing wrong unless this is a new bughow to reproduceopen up internet explorer 8 and hit f12 to bring up the developer toolsswitch to the console tab to watch the javascript consolevisit which is an iframe embed copied directly from youtubecom and view the javascript errorserrorsscript5007 unable to get value of the property getactivated object is null or undefined ie8youtubehtml line 28 character 128script5020 expected in regular expression html5playervflr cx32js line 675 character 708script438 object does not support property or method setreturnvalue wembedvflqdunf8js line 66 character 56script438 object does not support property or method setreturnvalue uvlr4eyknjy line 1 character 1anyone have any insight into this,"['javascript', 'html']" +457273,how to access network file using namespace stdofstream myfilemyfileopen zabctxt fails z is a network drivemyfileopenctempabctxt okmyfileopenznetwork02010echs fails znetwork is a network folderif myfileis open cout file is open endlelse cout file fails to open endlmyfileclosequestion it seems that ofstreamopen does not support to open a file on a network driveis there a simply way to solve this issue,['c++'] +457308,how do i clone a javascript class instance how do i clone a javascript class instancei tried the normal jquery extend but that just returns a vanilla object i have looked through many other answers on stack but could not find how to clone an instancefunction parentname thisname nameparentprototypesayhello function consoleloghello my name is thisnamefunction childname parentcallthis namechildprototype objectcreateparentprototypevar child new childbillyvar clone extendtrue childclonename bobchildsayhelloclonesayhelloconsolelogchild instanceof childconsolelogclone instanceof childi would prefer that the clone was deeprecursive ie all properties that are objects are cloned as well,"['javascript', 'jquery']" +457336,recreate versions carrierwavefogaws i am trying to recreate the images that i have uploaded using the following in my model postalleach do ym ymavatarcache stored file ymavatarretrieve from cacheymavatarcache name ymavatarrecreate versions ymsave endunfortunately i get the following errorundefined method body for nilnilclassmy uploader is named avataruploader and is for my post model any advice on how to fix this,['ruby-on-rails'] +457348,is sample code for atomic compare exchange weak at cppreference correct at compare exchange the following example code is presented as an example use of stdatomic compare exchange weakvoid appendlist s node n node head do head shead nnext head while stdatomic compare exchange weakshead head nmy understanding is that this has the the effect of comparing shead with head when what i believe is desired is to compare shead with head should the first argument to stdatomic compare exchange weak in this example be shead or am i missing somethingupdate the spec for stdatomic compare exchange weak saysbool atomic compare exchange weakvolatile a object c expected c desired noexceptbool atomic compare exchange weaka object c expected c desired noexcepteffects atomically compares the contents of the memory pointed to by objectfor equality with that in expectedi took this to mean that object was compared with expected but further research suggests that the actual meaning is that object is compared with expected ie that in expected means pointed to by expected this would imply that the answer to my original question is no there is no need to take the address of shead in the example code at cppreference but the fact that object must point to a stdatomict and expected must point to a t makes it hard for me to figure out how to correct the code at cppreference so that it will compile we want to compare the head of the list with a copy of the head of the list but if the head of the list is of type stdatomict the copy would have to be of type t if the call to stdatomic compare exchange weak is to compile and i cannot find a way to assign a stdatomict to a t without a reinterpret cast even then the third parameter to stdatomic compare exchange weak would need to be of type t but the example at cppreference shows both the second and third parameters to be of the same type this suggests to me that the example at cppreference is broken i tried to fix it but i was stymied by the need to use a reinterpret cast that just feels wronginterestingly in my attempts to figure this stuff out i checked out the msdn page for stdatomic compare exchange weak and i was thismayed to see that that page thisplays the prototypes for stdatomic compare exchange strongcan somebody post plausible code that uses stdatomic compare exchange weak to insert a node at the front of a singlylinked list there is no need to worry about the aba problem or do anything fancy i would just like to see skeletal code that compiles,['c++'] +457359,cardio mono for android xamarin studio has anybody successfully created a cardio wrapper they are willing to share that can be used in a mono for android application or can somebody shed some light on what i am doing wrongcreate a new android java bindings library projectadd the jar and so files from cardio sdk 303 be sure to use the existing folder structureadd the following to transformsenummethodsxml to resolve a compiler errormapping jniclassiocardpaymentcardioactivity method jninameonactivityresult parameterp1 clrenumtypeandroidappresult mappingadd a reference to the above library in my main applicationeverything compiles and i can access the cardio classesusing iocardpaymentprivate void wireupscancardbutton logdebugthisgettypename wireupscancardbutton thisscancardbuttonclick delegate logdebugthisgettypename scancardclick var intent new intentthis typeofcardioactivity required for authentication with cardio intentputextracardioactivityextraapptoken my private token here customize these values to suit your needs intentputextracardioactivityextranocamera false intentputextracardioactivityextrasuppressmanualentry true intentputextracardioactivityextrarequireexpiry false intentputextracardioactivityextrarequirecvv false intentputextracardioactivityextrarequirezip false run the activity thisstartactivityforresultintent 0 however i am always presented with the following errorthis device can not use camera to read card numbersnotesi have tried running on several different physical devicesthe cardiojar file has a build action of embeddedjarthe so files have a build action of embeddednativelibraryi have explicitly set the abi for each so file in the project itemgroupi am very new to androidxamarin so spend more time researching than codingthe so files do not appear to be in the apk fileeditthe so files do seem to get picked up by the compilerafter compilation if i check the objrelease folder there is a subfolder native library imports that contains the so files in appropriate subfolders according to the supported abi typehowever the so files still do not appear in the final apk filelogcat output0418 081220462 dactivityaddpaymentsource 5824 scancardclick0418 081220472 eactivitymanager 191 exception bwwritejavaioioexception transport endpoint is not connected0418 081220472 iactivitymanager 191 starting intent cmpcomonetabandroidiocardpaymentcardioactivity has extras from pid 58240418 081220472 dpowermanagerservice 191 acquirewakelock flags0x1 tagactivitymanagerlaunch0418 081220492 dactivityaddpaymentsource 5824 onpause0418 081220492 esensors 191 gssensor line 83 handle0en1n0418 081220502 esensors 191 gssensorsetdelay line 113 handle0ns1553152n0418 081220502 esensors 191 gssensorsetdelay line 113 handle0ns2135896001n0418 081220542 wcardio 5824 cardioscanerrornodevicesupport this device cannot use the camera to read card numbers0418 081220572 eactivitymanager 191 exception bwwritejavaioioexception transport endpoint is not connected0418 081220572 dpowermanagerservice 191 acquirewakelock flags0x1 tagactivitymanagerlaunch0418 081220582 esensors 191 gssensor line 83 handle0en0n0418 081220622 dactivityaddpaymentsource 5824 onresumethanks,['android'] +457369,always show previous next links using codeigniter pagination class problem descriptionwhen i am at the first page the previous link is not showing up and so do the next link when i am at the last page i set configprev linkprevious and confignext linknextquestionhow to always present using the codeigniter pagination class the previous and next links as p tags when they are not in usedupdateend up solving it myself see solution below working on v213,['php'] +457401,how to call numpyscipy c functions from cython directly without python call overhead i am trying to make calculations in cython that rely heavily on some numpyscipy mathematical functions like numpylog i noticed that if i call numpyscipy functions repeatedly in a loop in cython there are huge overhead costs egimport numpy as npcimport numpy as npnpimport arraycimport cythondef myloopint num elts cdef double value 0 for and in xrangenum elts call numpy function value nplog2this is very expensive presumably because nplog goes through python rather than calling the numpy c function directly if i replace that line withfrom libcmath cimport log calling libc function logvalue log2then it is much faster however when i try to pass a numpy array to libcmathlogcdef npndarraylong ndim1 foo nparray1 2 3logfooit gives this errortypeerror only length1 arrays can be converted to python scalarsmy questions are is it possible to call the c function and pass it a numpy array or can it only be used on scalar values which would require me to write a loop eg if i wanted to apply it to the foo array aboveis there an analogous way to call scipy functions from c directly without a python overhead which how can i import scipys c function libraryconcrete example say you want to call many of scipys or numpys useful statistics functions eg scipystats on scalar values inside a for loop in cython it is crazy to reimplement all those functions in cython so their c versions have to be called for example all the functions related to pdfcdf and sampling from various statistical thistributions eg see continuouspdfhtmlscipystatsrv continuouspdf and scipyhtml if you call these functions with python overhead in a loop it will be prohibitively slowthanks,['python'] +457412,jquery event handling bind to document or body element i have noticed the use of document and body when we want to reference the entire page especially when binding eventsdocumentonclick myelement functionandbodyonclick myelement functionwhat is the difference performancewise if document binds the event to the entire html document why do we not use body to bind events like click insteadnote that this question is not referring to the use of the ready function but the use of on or delegate binding,['jquery'] +457416,what exactly triggers avplayeritemdidplaytoendtimenotification so i know avplayeritemdidplaytoendtimenotification is sent when a movie has played to its end timemy question is how does the player know if an item reaches its end time i was playing a live stream generated by a 3rd party generator it keeps updating the m3u8 and creating new ts files which live streaming should do but at some point my player receives an avplayeritemdidplaytoendtimenotification and thus invokes my exit methods and quit the 3rd party stream generator is still running ok though i can restart the player and watch the streamssince the playing item is a live stream playeritemduration is not a readable duration number which makes finding the end time more like a black magic to mereally confused on how does the player thinks it is end my guess is maybe the ts file was problematic and made the player think the whole playing is over but if so should the player change its status to say sth instead of silently finish playingps i also tried different ways like make one ts missing from the m3u8 list or stop generating new ones so that the player would play current m3u8 and play past the last ts nothing made the avplayeritemdidplaytoendtimenotification magic happeni registered the notification as following nsnotificationcenter defaultcenter addobserverself selectorselectorplayeritemdidreachend nameavplayeritemdidplaytoendtimenotification objectselfplayeritem,['objective-c'] +457441,custom qt widgets with python for qt designer i am trying to write a custom widget for the qt designer using only python i was following a couple of tutorials i found online but none of them were working or anything close to what i would call to be a minimum working exampleso my questions arewhat steps are involved to make a a custom widget appear in the widget box of qt designerif you can spare the time please provide a minimum working example like a widget with a label in it saying a truly minimal working qt custom widget exampleor is it maybe not possible at all to include a custom widget using only python,['python'] +457468,fosjsroutingbundle route x does not exist i am facing a really weird problem with fosjsroutingbundle first of all here is my configuration i am working on symfony 2023 and with jquery on windows 7 64 bits with a wamp apache 242 and php 543 i have done all the settings from the fosjsroutingbundles github and haved exposed my routes almost all the related problems i could find by googling on fosjsroutingbundles githubhere and on different forums were because people have not exposed their routes but i tried php appconsole fosjsroutingdebug and i do see my routesthe js is added to the layout code of the layout at the endtrying to generate url for routes in js at the beginning i wanted to generate two different routes but for test i created the js code below code inside this function is workingselectchangefunction paramthisoptionsthisselectedindexvalue test1routinggeneratemybundle step3 myparam param alerttest1 windowlocationroutinggeneratemybundle step2code inside this one is also workinginputtypecheckboxchangefunction testroutinggeneratemybundle step2changethis is not workingtestroutinggeneratemybundle step2alerttestwith this code i get the javascript error the route mybundle step2 does not exist though the first part still works alert gives me the link created and the redirection goes well if i remove the second function i do not get the javascript error anymore if in the second function i replace step2 by step3 the error becomes the route mybundle step3 does not existi tried to clear the cache and to run php appconsole assetinstall symlink again but no resultshere is the controller corresponding code the real code is a bit long and i do not think it is relevant if you think so i could put it anyways namespace mybundlecontrollerclass individucontroller extends controller public function step2action some code public function step3actionmyparam some code the routingyml config file relative to the bundle mybundle step2 pattern step2 defaults controller mybundleindividustep2 options expose truemybundle step3 pattern step3myparam defaults controller mybundleindividustep3 options expose truethe appconfigroutingyml file fos js routing resource fosjsroutingbundleresourcesconfigroutingroutingxmlmybundle resource mybundleresourcesconfigroutingyml prefix the layouts relevant informations jquery via google local fallback see h5bpcom script srcajaxgoogleapiscomajaxlibsjquery171jqueryminjs script scriptwindowjquery documentwritescript srcjsjquery171minjsscriptscript javascripts bootstrapjsbootstrapjs bundlesfosjsroutingjsrouterjs bundlescrrisuapsjssuapsjs script typetextjavascript src asset url script endjavascripts script src pathfos js routing js callback fosroutersetdata script bodyhtmlresult of php appconsole routerdebug i left only the relevant informations i left the undefined variable notice just in case it is a notice i got since i added this library still the library works and i do not think the problem could come from here cwampwsuapsreposuapsphp appconsole routerdebugnotice undefined variable kpathurl in cwampwsuapsreposuapsvendorhtml2pdf classtcpdfconfigphp on line 80call stack 070 231536 1 main cwampwsuapsreposuapsappconsole0 00209 685656 2 require oncecwampwsuapsreposuapsappbootstrapphpcache cwampwsuapsreposuapsappconsole10 00212 701752 3 require oncecwampwsuapsreposuapsappautoloadphp cwampwsuapsreposuapsappbootstrapphpcache3 01335 2998152 4 require oncecwampwsuapsreposuapsvendorhtml2pdfhtml2pdfclassphp cwampwsuapsreposuapsappautoloadphp51 01379 3361792 5 require oncecwampwsuapsreposuapsvendorhtml2pdf classmypdfclassphp cwampwsuapsreposuapsvendorhtml2pdfhtml2pdfclassphp19 01385 3393792 6 require oncecwampwsuapsreposuapsvendorhtml2pdf classtcpdfconfigphp cwampwsuapsreposuapsvendorhtml2pdf classmypdfclassphp12router current routesname method pattern assetic 55f0319 any css55f0319css assetic 55f0319 0 any css55f0319 bootstrap 1css assetic 55f0319 1 any css55f0319 bootstrapresponsive 2css assetic 55f0319 2 any css55f0319 style 3css assetic 3608a04 any js3608a04js assetic 3608a04 0 any js3608a04 bootstrap 1js assetic 3608a04 1 any js3608a04 router 2js assetic 3608a04 2 any js3608a04 suaps 3jsfos js routing js any jsrouting formatmybundle homepage any mybundle inscription etape1 any inscriptionetape1mybundle inscription etape2 any inscriptionetape2mybundle inscription etape3 any inscriptionetape3thisciplineselectionresult of php appconsole fosjsroutingdebug i removed the php notice but it happens on every command i make btw cwampwsuapsreposuapsphp appconsole fosjsroutingdebugrouter current routesname method patterncrrisuapsbundle inscription etape2 any inscriptionetape2crrisuapsbundle inscription etape3 any inscriptionetape3thisciplineselectionedit also do not know if it is relevant but when i try php appconsole fosjsroutingdebug mybundle step2 i get the following php error error exceptionwarning missing argument 3 for symfonybundleframeworkbundlecommandrouterdebugcommandoutputroute called in csymfonydirectoryvendorbundlesfosjsroutingbundlecommandrouterdebugexposedcommandphp on line 62 and defined in cserverdirectoryvendorsymfonysrcsymfonybundleframeworkbundlecommandrouterdebugcommandphp line 98,"['php', 'javascript']" +457478,how can i make gdb print unprintable characters of a string in hex instead of octal while preserving the ascii characters in ascii form suppose i have a buffer buf whose c string representation is char buf hello world x1cwhen i print this buf in gdb using the command p buf i get the following 1 hello world 034is there a print command or a gdb setting that will print the following instead1 hello world x1ci have tried various format parameters such as c and x but none of them get the effect that i am looking for i have also played with printf but was unable to achieve the desired effectupdate i am using gnu gdb gdb 701debianupdate i have played with x as well if i do xc it prints octal and decimal for nonprintable characters and then prints printable characters with the ascii and decimal if i do xs it outputs exactly the same as the p command if i do xx it just outputs hex but then we lose the ascii characters for the printable partupdate this reference unless incomplete suggests that what i desire is not available but can anyone confirm,['c'] +457507,getting big decimals back from a yamlserialized field in the database with ruby on rails using ruby on rails i have a couple of fields that are serialized arrays or hashes mostly some of those contain bigdecimals it is very important that those big decimals remain big decimals but rails is turning them into floats how do i get bigdecimals backlooking into this issue i found that serializing a big decimal in plain ruby without rails works as expectedbigdecimalnew4242to yaml rubyobjectbigdecimal 1804242e2nnbut in a rails console it does notbigdecimalnew4242to yaml 4242nthat number is the string representation of the big decimal so it is allright but when i read it back it is read as a float so even if i convert it to bigdecimal something i do not want to do as it is error prone it is possible i will lose precision which is not acceptable for my appi tracked down the culprit to activesupport3211libactive supportcore extbig decimalconversionsrb which overrides the following method in bigdecimalyaml tag tagyamlorg2002floatyaml mapping infinity inf infinity inf nan nan this emits the number without any scientific notation this is better than selfto fto s since it does not lose precision note that reconstituting yaml floats to native floats may lose precisiondef to yamlopts return super if definedyamlengine yamlenginesyck yamlquick emitnil opts do out string to s outscalaryaml tag yaml mappingstring string plain endendwhy would they do that and more importantly how do i workaround it,['ruby-on-rails'] +457530,abstracting jquery in these talks by nicholas zakas and addy osmani they thiscuss the idea of using the facade pattern as a sandbox when building large scale javascript applications in order to decouple the application from the underlying base librariesthis decoupling would in theory allow you to switch out a base library without needing to rewrite your application modules however in practice this seems to be more difficult to implementthere are concrete implementations of this proposed architecture such as aurajs however from looking at the source it seems that the sandbox still has leaky abstractions by returning jquery objects from some of its methodsi am not concerned with aurajs specifically but more the general concept of trying to abstract a library like jquery without losing so much functionalityas an example say my facadesandbox has a dom method findselector i can think of 3 options for what it might returna jquery object this would leak jquery out into the consuming modulesa raw dom element loss of functionality nobody really wants to work with this no chaininga custom jquerylike wrapper could be quite complex but seems like the ideal solutionso my question is how would you abstract a library like jquery without losing too much functionality such that it could be replaced at some point in the future with minimal effort,"['javascript', 'jquery']" +457536,javascript anonymous closure i have read a lot about closures in javascriptwhat are those braces fori read on mozillaorg which says closure should be defined as functionbut on it says the closure function isfunctionwhats the difference or the latter one is wrongwhats the purpose of the last would you put some parameters insidei am looking for a good referenceeditmoreover there is an example on mozillaorgvar makecounter function var privatecounter 0 function changebyval privatecounter val return increment function changeby1 decrement function changeby1 value function return privatecounter why the semicolon is needed for this function if it needs to be invoked immediately after its declaration a should be put before the ending semicolon but there is not,['javascript'] +457552,microsoft jscript runtime error no such method select for tabs widget instance i need select specific tab functionality for the jquery tabs on clicking on the html buttons i am using jquery191js and jqueryui1102customjs file i have implemented below code but does not work for me script languagejavascript typetextjavascript uitabstabs function selecttab bind click event to link uitabstabsselect 2 switch to third tab return false scriptdiv iduitabsul lia hreftabs1nunc tinciduntali lia hreftabs2proin dolorali lia hreftabs3aenean laciniaaliuldiv idtabs1tab1 content divdiv idtabs2tab2 content divdiv idtabs3tab3 content divdiva idnext classbuttonstyle href onclickreturn selecttabselect tabathe problem is statement uitabstabsselect 2 in function selecttab gives me error microsoft jscript runtime error no such method select for tabs widget instance normal selection of tabs on clicking on them working fine but it is not working when done from function call whats going wrong in the implementation or is there any file missing please suggest,['jquery'] +457603,async method does not return aspnet mvc 4 i am having a problem with an async method that i implemented the method basically makes a httprequest to a resource and deserializes the string if the request is successful i wrote a test for the method and it works but the method does never return when i call it from a controller public async taskienumerablet get try var resourcesegmenturi new uri uri urikindrelative var response await clientgetasyncresourcesegmenturi if responseissuccestatuscode var submission await responsecontentreadasstringasync return jsonconvertdeserializeobjectienumerabletsubmission if responsecontent null var message responsecontentreadasstringasync throw new webexceptionmessageresult webexceptionstatusresponsestatuscode catch webexception e loggererrorget request failed with status 0 estatus throw throw new exception code that never returnspublic actionresult index var api new api var test apigetresult never returns return viewtest that workstestpublic void getshouldreturnifsuccessfulrequest var api new api var submission apiget consolewritelinejsonconvertserializeobjectsubmission assertnotnullsubmissiondoes anyone know the problem,"['c#', 'asp.net']" +457651,how facebook app implements draggable floating button ia m trying to get some information about how i could implement such a button like facebook does in the new version of the app actually i am not sure if this button comes from facebook or from facebook messenge app but it was the easiest way to have an example of what i would like to achievethey add a draggable floating button anywhere you are when getting a new message notification anybody has and idea about how they achieved thatthanks in advanceeditedtoucher other app which uses what ia d like to achieve just below can find a link from google playfeaturenav resulttw251bgwsmswxldmsimnvbs5nyxuuz28udg91y2hozwxwzxjlecjd,['android'] +457681,initialize database without xml configuration but using configuration i would like to know how to initialize a database without having to create an xml filei already use this kind of initialization that works fine but in my current case i do not want to create an xmljdbcinitializedatabase datasourcedatasource jdbcscript locationclasspathcomfoosqldbschemasql jdbcscript locationclasspathcomfoosqldbtestdatasqljdbcinitializedatabasei know i can create an embedded database withembeddeddatabasebuilder builder new embeddeddatabasebuilderembeddeddatabase db buildersettypeh2addscriptmyschemasqladdscriptmytestdatasqlbuildin my case the database and schema are created using liquibasei just want to initialize it with spring and with my customized dataset without having to create a new xml file each time just for thatis it possible,['java'] +457694,video compatibility issue android recorded video not played in iphone i am recording a video in android like thislistcamerasize list mycameragetparametersgetsupportedpicturesizes parameters parameters mycameragetparameters parameterssetcoloreffectcoloreffectsgetindex color effect mycamerasetparametersparameters mediarecorder new mediarecorder mycameraunlock mediarecordersetcameramycamera mediarecordersetorientationhint90 mediarecordersetaudiosourcemediarecorderaudiosourcecamcorder mediarecordersetvideosourcemediarecordervideosourcecamera mediarecordersetoutputformatmediarecorderoutputformatmpeg 4 mediarecordersetaudioencoderaudioencoderhe aac mediarecordersetvideoencodervideoencoderh264 mediarecordersetoutputfileconstantsvideourl mediarecordersetmaxduration30 set max duration 60 sec mediarecordersetvideoframerate24 mediarecordersetvideoframerate30 mediarecordersetvideosize720 480 mediarecordersetpreviewthisplaymycamerasurfaceviewgetholdergetsurfacethis recored video and able to play in android well but unable to play on iphoneif if use this code for recording work two mediarecordersetaudiosourcemediarecorderaudiosourcecamcorder mediarecordersetvideosourcemediarecordervideosourcecamera mediarecordersetprofilecamcorderprofilegetcamcorderprofilequality high mediarecordersetoutputfilevideourl mediarecordersetmaxduration30 set max duration 60 sec this records video compatiblewith iphone wellbutthis records 30 seconds video about 47 mbs on samsung note2any help,"['android', 'iphone']" +457716,mutability of the kwargs argument in python consider a case where i change the kwargs dict inside a methoddef print argkwargs print kwargspopkeyif i call the method pop arg with a dictionary like thismydict keyvalueprint argmydictwill mydict be changed by this calli am also interested in a more detailed explanation of the underlying method calling mechanism that lets mydict change or not,['python'] +457789,is it possible to run an android emulator without setting up eclipse is it possible to run an android emulator without setting up eclipse i am working with a contractor that has provided me with the apk filei was hoping i could run it without setting up a whole testing environment,['android'] +457802,what is the best way to resolve rails orphaned migrations i have been switching between branches in a project and each of them have different migrations this is the scenario rake dbmigratestatus status migration id migration name up 20130307154128 change columns in traffic capture up 201303155109 remove log settings up 201303160901 remove log alarm table up 20130320144219 no file up 20130320161939 no file up 20130320184628 no file up 20130322004817 add replicate to root settings up 20130403190042 no file up 20130403195300 no file up 201304032140 no file up 20130405164752 fix ap hostnames up 201304101942 no file the problem is rake dbrollback do not work at all because of the missing fileswhat should i do to be able to rollback again and get rid of the no file messagesbtw rake dbreset or rake dbdrop are not an option i cannot lose data from other tables,['ruby-on-rails'] +457832,robust fast complex polygon with holes triangulation cc library with permissive license i am a developer of the opensource game bitfighter as per the following so post we have used the excellent triangle library for meshzone generation for use with our ingame ai robotspolygon triangulation with holeshowever we ran into a small snag when wanting to package our game for debian the use of the triangle library will make our game be considered as nonfreewe have been extremely pleased with the performance of the triangle library and do not really want to give it up however we do not like dealing with license issues either therefore we have embarked upon a quest to find a suitable permissivelylicensed replacement that can match triangle in its robustness and speedwere looking for a c or c library for dividing large complex areas into triangles that can handle any type of irregular polygons placed together in any manner as well as holes robustness is our primary need with speed almost as importanti have found poly2tri but it suffers from a bug in which it cannot handle polygons with coincident edgeswe have found several libraries but all seem to suffer from one thing or another either too slow or do not handle holes or suffer from some bug currently we are testing out polypartition and we have high hopeswhat are the best alternatives to the great triangle library but have a permissive license,"['c++', 'c']" +457840,calayer place sublayer below storyboard uibuttons i have got a view controller in my storyboard with several uibuttons one of them activates an avfoundation camera preview layer shown in a sublayercapturevideopreviewlayer avcapturevideopreviewlayer alloc initwithsessionsessioncapturevideopreviewlayerframe selfviewboundsselfviewlayer addsublayercapturevideopreviewlayerthis works correctly except for the fact that the preview layer is rendered on top of my buttons so even though the buttons are still clickable they are not able to be seen by the user is there an easy way to place the sublayer below the buttons or an easy way to raise the buttons up in the layer thank you much,['ios'] +457841,progressdialog change text size i create a progressdialog from java codemprogressdialog progressdialogshowthis truei want to change the message text size and its colorhow can i do it,['android'] +457846,can not find java runtime enviornment says argouml i have properly installed jdk in my system i have also set the classpath properly but when i am installing argouml it shows a message the no jre found what should i do please help me thanks for help,['java'] +457895,if i overwrite html is it removed from the dom imagine i have the following codediv iddiv1 div iddiv2original div2divdivdiv iddiv3divif i rundiv1htmldiv3htmldiv iddiv2new div2divdo i end up with problems because i did not use remove to remove div2 from the dom or does clearing the html in this way do that for mewhat if div2 contained some javascript that attached a handler say something likediv2onclickfunction would that also be removed or would i need to off it,['jquery'] +457956,regex to count the number of capturing groups in a regex i need a regex that examines arbitrary regex as a string returning the number of capturing groups so far i havearbitrary regextostringmatchglengthwhich works for some cases where the assumption that any group that starts with a question mark is noncapturing it also counts empty groupsit does not work for brackets included in character classes or escaped brackets and possibly some other scenarios,['javascript'] +457987,creating dynamic type in c i am writing a piece of generic software that will be loaded on to many different variants of the same basic hardware they all have the same processor but with different peripherals and their own functions that need to be carried out the software will know which variant it should run by reading a hardware switch valueheres my current implementation in a nutshellclass mybasepublic mybase virtual run 0class varianta public mybasepublic varianta virtual run run code specific to hardware varianta class variantb public mybasepublic variantb virtual run run code specific to hardware variantb void main mybase variant uint 8 switchvalue readswitchvalue switchswitchvalue case 0 variant new varianta break case 1 variant new variantb break variantrunnow this works just fine i read the hardware value and use a switch statement to create the new corresponding classthe problem is that there are a lot of variants i have to deal with currently about 15 with the potential to add another 2030 in the near future i have really come to despise switch statements that run for hundreds of lines so i am really looking for a better way to do this probably through templatesi want to be able to use my hardware value to look up a type and use that type to create my new object ideally when i add a new variant i create the new class add that class type to my lookup table with it is matching hardware value and it is good to gois this possible at all whats a good solution here,['c++'] +457990,running haxe from ios app a hxrunlibrary error for a client i have developed an ios android app using cordova phonegap for the user interface now as an update to this app i am am attempting to add a game that was written in haxe originally the game was written for the flash target but i have updated it to work with the c targets for android and ioson android it was easy to integrate this with the cordova app using activities the haxe part runs as a separate activity but i am having some trouble achieving a similar result on iosso far i have tried to include all hxcpp generated code in my project in the same way that nme sets up the xcode project when you do nme build ios and i am calling hxrunlibrary from my code when i want the game to runthe problem is that hxrunlibrary seems to want to create its own uiapplication instance which fails with the following error since my main app is already running an instance assertion failure in void uiapplicationinstantiatesingletonclass sourcecacheuikit simuikit238017uiapplicationm2037 terminating app due to uncaught exception nsinternalinconsistencyexception reason there can only be one uiapplication instancei think it might have something to do with sdl which haxe uses for graphics from what i understand sdl needs to run from the main function of the app which created a conflict with cocoa that also needs to run from the main functionis there any easy way around this i have looked in the hxcpp sources but been unable to find the uiapplication related code or any entry code for sdlperhaps someone could point me in the right direction thanks,['ios'] +458030,multilanguage database which method is better i have a website in 3 languageswhich is the best way to structure the db1 create 3 table one for every language eg product en product es product de and retrieve data from the table with an identifiereg on the php page i have a stringlanguage enso i get the data onlyselect from product language2 create 1 table withid language name descrand post on the page only where language language3 create 1 table withid name en descr en name es descr es name de descr dethank you,"['php', 'mysql']" +458065,how can i validate array keys using symfony validation how can i validate array keys using symfony validationsay i have the following and each key of the emails array is an id how can i validate them using a callback or some other constraint say for example a regex constraint rather than a callbackinput emails 7 12 user bob amount 7use symfonycomponentvalidatorvalidationuse symfonycomponentvalidatorconstraintsvalidator validationcreatevalidatorconstraint new constraintscollectionarray emails new constraintsallarray new constraintsemail user new constraintsregexazi amount new constraintsrangemin 5 max 10violations validatorvalidatevalueinput constraintecho violationsusing latest devmaster symfony,['php'] +458096,ruby on rails multiple http request at the same time i am pulling multiple requests its pulling one at a time i was wondering if there is a way pull requests all at the same time if i have something like thisclient instagramclientaccess token sessionaccess tokenuser clientuserrecent media items clientuser recent medialv clienttag recent medialv options count 60lv1 clienttag recent medialv1 options count 60lv2 clienttag recent medialv2 options count 60lv3 clienttag recent medialv3 options count 60each lv makes a request to client i was wondering if there is a way to do such so it can do the request all at once together instead of one finishes the request then goes on to the next request and so onthanks,"['ruby-on-rails', 'ruby']" +458134,best practices for libraries and namespaces what are the best practices for creating librariesi have been developing for nearly 10 years now and have been building my library as i workthe way i currently have it setup follows this patternmylibsomeutilityutilfuncnew mylibsomeprojectprojectclass project specific classessometimes i have classes that extends external librarieslike jquery or kinteticjs objectsnew mylibsomeexternallibraryexternallibraryclassmy library has files in cssjsphpas3 but to avoid confusion i have seperated them each into their separate library like mylib js etcinside the js library for example i have webgl canvas jquery regular js classes if well call them thatas you can see it is a bit of a mess so i am trying to learn what others are doing so i made a list of quick questionshow to handledifferent languagesdifferent platforms is that what it is called webglcanvasjquery etcdifferent projectsexternal libraries and dependenciesas i was researching i thought of google and i asked myself how they handle their google maps library for example they must have a general google library with a bunch of utility functions but there are also files just for google maps and they have a backend maybe php and a js front end so how is it all managedthanks for all your help dps i use git for the version control work,['javascript'] +458166,unfortunate java exception javalangnosuchmethoderror i wrote an application an it was working fine for 3 years buttoday when they try to run this application an unexpected exception raisedinfo jvm 1 20130417 100240 exception in thread thread1 javalangnosuchmethoderror javasqlconnectionisvalidizinfo jvm 1 20130417 100240 at libmysqlconnectionpatchsearchincachemysqlconnectionpatchjava103info jvm 1 20130417 100240 at libmysqlconnectionpatchgetconnectionmysqlconnectionpatchjava79info jvm 1 20130417 100240 at libsqlmanagerestablishsqlconnectionsqlmanagerjava62info jvm 1 20130417 100240 at libsqlmanagerestablishsqlconnectionsqlmanagerjava30info jvm 1 20130417 100240 at libtasksclassessqlexecutequeryexecuteexecutequeryjava49info jvm 1 20130417 100240 at componentsttaskrunttaskjava86info jvm 1 20130417 100240 at componentsthreadtaskrunthreadtaskjava29info jvm 1 20130417 100240 at libtasksclassesforiexecuteforijava66info jvm 1 20130417 100240 at componentsttaskrunttaskjava86info jvm 1 20130417 100240 at componentsthreadtaskrunthreadtaskjava29info jvm 1 20130417 100240 at libtasksclassesforiexecuteforijava66info jvm 1 20130417 100240 at componentsttaskrunttaskjava86info jvm 1 20130417 100240 at componentsthreadtaskrunthreadtaskjava29info jvm 1 20130417 100240 at componentsthreadtaskrunthreadtaskjava44info jvm 1 20130417 100240 at launcherservicelaunchservicerunlaunchservicejava38code of mysqlconnectionpatchjavasearchincache isprivate connection searchincachestring key connection result null try if connectionsisempty result connectionsgetkey catch exception ex if result null boolean isvalid false this is line 103 where exception raised try statement s resultcreatestatement if sexecuteshow status isvalid true sclose catch exception ex isvalid false if isvalid connectionsremovekey messagelogstdwarmysql patch one connection expired force close try resultclose catch sqlexception ex messagelogstderrmysql patch closing connection error exgetmessage result null return resulti wonder why boolean isvalid false raise exception javalangnosuchmethoderror javasqlconnectionisvalidiznote that the only thing differs is jre former was 16 and the new is 17,['java'] +458175,find new control point when endpoint change in cubic bezier curve i am implementing cubic bezier curve logic in my one of android applicationi have implemented cubic bezier curve code on canvas in ondraw of custom view path to draw cubic bezier curvepath cubepath new path move to startpoint200200 p0cubepathmoveto200200 cubic to with controlpoint1200100 c1 controlpoint2300100 c2 endpoint300200 p1cubepathcubicto200100300100300200 draw on canvascanvasdrawpathcubepath painti visualize above code in following imageupdated logic for selecting first control points i have taken basex 200 basey 200 and curve size x of endpoint x of start pointstart point x basex and y baseycontrol point 1 x basex and y basey curve sizecontrol point 2 x basex curve size and y basey curve sizeend point x basex curve size and y baseyi want to allow user to change endpoint of above curve and based on the new end points i invalidate the canvasbut problem is that curve maintain by two control points which needs to be recalculate upon the change in endpointlike i just want to find new control points when endpoint change from 300200 to 250250like in following image please help me to calculate two new control points based on new end point that curve shape will maintain same as previous end pointi refer following reference links during searching curveany reference link also appreciated in answer of this question,['android'] +458187,serialize char data type with xmlserializer i have a class which has property whiches type is char as following xmlrootroot public class testclass xmlelementtest typeofchar public char testproperty get set when value of testproperty is n and if i serialize testclass it will produce following result root test78test rootbut what i want is to have following root testntest rootis it possible without changing type of testproperty to string,['c#'] +458229,long static strings in shortlived objects this might be a stupid question or just make me look stupid however i would be interested in how to work with long string objects in the context of shortlived objectsthink about long sql queries in cron job or anonymous command or functionlike classes these are very shortlived classes and even will use these long strings once in their lifetime for most of the time what is better to construct a string inline and let it be collected with the instance or make it static final anyway and let them sit in the memory useless until the classes next instantiation,['java'] +458242,jquery trigger change event on checkbox is it possible to trigger change event on a checkbox using javascriptjquerysomething like this i run triggerchange on click of a buttonlabelinput typecheckbox idchklabel for chklabelscriptfunction triggerchange chktriggerchangescriptwhen i run the above code i get this error trigger is not a function,"['javascript', 'jquery']" +458293,confusion about constant expressions this is some kind of followup for this topic and deals about a little part of it as with the previous topic let us consider that our compiler has constexpr functions for stdinitializer list and stdarray now let us go straight to the pointthis worksinclude arrayinclude initializer listint main constexpr stdarrayint 3 a 1 2 3 constexpr int a0 a0 constexpr int a1 a1 constexpr int a2 a2 constexpr stdinitializer listint b a0 a1 a2 return 0this does notinclude arrayinclude initializer listint main constexpr stdarrayint 3 a 1 2 3 constexpr stdinitializer listint b a0 a1 a2 return 0it crashes with this errorerror const stdinitializer listintconst intanonymous 3u is not a constant expressioneven though i read some papers about constexpr and constant expressions meanwhile this behaviour still does not make any sense for me how come the first example is considered a valid constant expression and not the second one i would welcome any explanation so that i can rest in peace afterwardsnote i will precise it right away clang will not be able to compile the first snippet since it does not implement the constexpr library additions that are planned for c14 i used gcc 47edit ok here comes the big example to show what is rejected and what is notinclude arrayinclude initializer listconstexpr int foo 42constexpr int bar return foo struct eggs int a b int main constexpr stdarrayint 3 a 1 2 3 constexpr int a0 a0 constexpr int a1 a1 constexpr int a2 a2 from xeo and andy tests constexpr stdarrayint 1 a bar ok constexpr stdarrayint 3 b a0 a1 a2 ok stdinitializer listint b a0 a1 a2 ok constexpr stdinitializer listint b a0 a1 a2 ok constexpr stdinitializer listint b foo ok constexpr stdinitializer listint c bar error constexpr stdinitializer listint b a0 a1 a2 error from matheus izvekov and daniel kra14gler constexpr eggs good 1 2 ok constexpr stdinitializer listeggs bad 1 2 3 4 error constexpr stdinitializer listeggs bad2 good good error return 0,['c++'] +458312,what is the purpose of xxminheapfreeratio and xxmaxheapfreeratio kindly tell me the purpose of those optionsafter googling i thinkminheapfreeratio tells specified minimum percentage of space will be ensured to be free in heap memory after a gcandmaxheapfreeratio tells no more than specified percentage of space will be free in heap memory after a gc if there is excess free memory than the specified percentage those memory will be returned to oswhen i tried these options with 10 as value for both even where there is more than 80 percentage of free heap memory it was not released back to osdetailsjava hotspottm 64bit server vm 150 15b04 mixed mode parallelgc otherwise known as throughput collector which is the default collector in server class vm i specified xms50m and xmx10m as jvm arguments os windows 7 professional 8 gb memory 64 bit osnote i just tried with serialgc too those min and max heap free ratio options were ignored,['java'] +458343,what is the difference between wpf command and event in wpf i was just googling the difference between wpf command and event in wpf i landed on the following page of stackoverflow where the thiscussion is going onwhat is the difference between wpf command and eventi am only able to understand following from therecommands can be written in business layer while event only in presentationa single command can be associated with many controls but event can only be associated with only one controlam i right is there any other difference between them,['c#'] +458362,json object in c net i have a cnet method as given below public string jsontest liststring list new liststring listaddaa listaddbb listaddcc string output jsonconvertserializeobjectlist return output here eventhough im creating a json object by using jsonconvertserializeobject i am getting a string since return type is stringcan i do like below by using a return type jsonresult or somthing like that something like what we can do in mvc return jsonnew data list jsonrequestbehaviorallowgetis it possible to create a json data in aspnetin client side i am using an ajax call to get data from jsontest ajax type get url testaspx in testaspx pageload calling jsontest datatype json success function data alertdata error function data alertin error when i am giving datatype json it will go to error part since the ajax expects json data but it gets string thats why i want to parse it as a json object in server side,"['c#', 'asp.net']" +458366,whats wrong with returning this at the company i work for there is a document describing good practices that we should adhere to in java one of them is to avoid methods that return this like for example inclass properties public properties addstring k string v store kv somewhere return this i would have such a class so that i am able to write propertiesaddname johnaddroleswd i have seen such idiom many times like in stringbuilder and do not find anything wrong with ittheir argumentation is can be the source of synchronization problems or failed expectations about the states of target objects i cannot think of a situation where this could be true can any of you give me an exampleedit the document does not specify anything about mutability so i do not see the diference between chaining the calls and doing propertiesaddname johnpropertiesaddrole swdi will try to get in touch with the originators but i wanted to do it with my guns loaded thats why i posted the questionsolved i got to talk with one of the authors his original intention was apparently to avoid releasing objects that are not yet ready like in a builder pattern and explained that if a context switch happens between calls the object could be in an invalid state i argued that this had nothing to do with returning this since you could make the same mistake buy calling the methods one by one and had more to do with synchronizing the building process properly he admitted the document could be more explicit and will revise it soon victory is mineours,['java'] +458376,android thread wait until visible i have made a custom pie chart view that i want to animate starting when the pie chart is visible currently what i have is the pie chart animating but by the time you can actually see it on the screen the animation is half over this is what i havepublic class singlepiechart extends surfaceview implements surfaceholdercallback chart setting variables private int emptycirclecol strokecolor number total paint for drawing custom view private paint circlepaint private rectf rect private context context private animthread animthread private surfaceholder holder animation variables private float speed private float current 00f private boolean percentscalculated false private float degree private int viewwidth viewheight public singlepiechartcontext ctx attributeset attrs superctx attrs context ctx paint object for drawing in dodraw circlepaint new paint circlepaintsetstylestylestroke circlepaintsetstrokewidth3 circlepaintsetantialiastrue circlepaintsetdithertrue rect new rectf get the attributes specified in attrsxml using the name we included typedarray a contextgetthemeobtainstyledattributesattrs rstyleabledashboardchartsmall 0 0 try get the colors specified using the names in attrsxml emptycirclecol agetcolorrstyleabledashboardchartsmall smcirclecolor 0xff65676e light gray is default strokecolor agetcolorrstyleabledashboardchartsmall smcolor 0xff39b54a green is default default number values total agetintegerrstyleabledashboardchartsmall smtotal 1 number agetintegerrstyleabledashboardchartsmall smnumber 0 finally arecycle thissetzorderontoptrue holder getholder holdersetformatpixelformattransparent holderaddcallbackthis protected void calculatevalues degree 360 number total percentscalculated true speed 10 number total viewwidth thisgetmeasuredwidth viewheight thisgetmeasuredheight float top left bottom right if viewwidth viewheight left 4 right viewwidth 4 top viewheight viewwidth 2 4 bottom viewheight top else top 4 bottom viewheight 4 left viewwidth viewheight 2 4 right viewwidth left rectsetleft top right bottom protected void dodrawcanvas canvas if total 0 number values are not ready animthreadsetrunningfalse return if percentscalculated calculatevalues set the paint color using the circle color specified float last current float start 90 circlepaintsetcolorstrokecolor canvasdrawarcrect start last degree degree last false circlepaint start last number number last last last number 0 last number circlepaintsetcoloremptycirclecol if current 360 current 360 canvasdrawarcrect start 360 current false circlepaint current speed if last 0 number 0 were done animthreadsetrunningfalse public void setnumbersint num int tot number num total tot invalidate requestlayout public void setcolorint col strokecolor col public void redraw calculatevalues animthreadsetrunningtrue invalidate requestlayout override public void surfacechangedsurfaceholder arg0 int arg1 int arg2 int arg3 override public void surfacecreatedsurfaceholder arg0 animthread new animthreadholder context this animthreadsetrunningtrue animthreadstart override public void surfacedestroyedsurfaceholder arg0 animthreadsetrunningfalse boolean retry true whileretry try animthreadjoin retry false catchexception e logvexception occured egetmessage public class animthread extends thread boolean mrun canvas mcanvas surfaceholder surfaceholder context context singlepiechart msurfacepanel public animthreadsurfaceholder sholder context ctx singlepiechart spanel surfaceholder sholder context ctx mrun false msurfacepanel spanel void setrunningboolean brun mrun brun override public void run superrun while mrun mcanvas surfaceholderlockcanvas if mcanvas null msurfacepaneldodrawmcanvas surfaceholderunlockcanvasandpostmcanvas also if you see any programming errors memory leaks poor performing code please let me know i am new to androidhere is the layout that uses the singlepiechart classxml version10 encodingutf8merge xmlnsandroid relativelayout androidlayout widthmatch parent androidlayout height0dp androidlayout weight1 comdavidscovillevokabviewselementssinglepiechart androidididsmallpiechart androidlayout widthmatch parent androidlayout heightmatch parent textview androidididdashsmnumber androidlayout widthwrap content androidlayout heightwrap content androidlayout centerhorizontaltrue androidlayout centerverticaltrue androidtextsize25sp androidtextcolorf relativelayout textview androidididdashsmlabel androidlayout widthmatch parent androidlayout height20dp androidtextsize14sp androidgravitycenter androidtextcolorf merge,['android'] +458388,must all properties of an immutable object be final must immutable objects have all properties be finalaccording to me not but i do not know whether i am right,['java'] +458418,why this method does not change integer value i do have one question why this method does not change integer value to 3 public class someclass private integer value 1public integer getvalue return valuepublic void changevalinteger value value new integer3public static void mainstring args integer a new integer2 someclass c new someclass cchangevala systemoutprinta,['java'] +458439,how to use sass to properly avoid embedding twitter bootstrap class names on html i am working on a rails project that is just starting we want to use twitter bootstrap as a base for our styles at the beginning we would simply use bootstraps class names directly on the html code just like is shown in bootstraps documentation but after reading the following postslessons learned in maintainable css please stop embedding bootstrap classes in your htmlit became clear why that is not the proper why to use bootstrap so after some more readingsdecouple your css from htmlsmacssamong other it seemed that using sass extend was the proper way to avoid using bootstraps class names so instead of doing thisbutton typesubmit classbtnsearchbuttonwe would do thisbutton typesubmit classbuttonsearchbuttonand our sass code would look like thisbutton extend btnthe problem with that approach besides the bunch of extra selectors that will be added each time we extend a bootstrap class just to use a different name is that in cases where bootstrap uses selectors like thisformsearch inputappend btn formsearch forminputappend btn borderradius 0 14px 14px 0 the button would not get the right style because sass will not apply that same rule to our custom class name i mean sass is not doing this formsearch inputappend btn formsearch inputappend button formsearch forminputappend btn formsearch forminputappend button borderradius 0 14px 14px 0 so i wonder is this the right way to avoid embedding bootstraps class names into html if so how should i handle this problem it happens frequently if not what would be a better way to use custom class names but still get the styles from bootstrapi really appreciate your thoughts on this please keep in mind that i am just learning about overall web design css sass less html js etc,['css'] +458470,how do you create an asynchronous method in c every blog post i have read tells you how to consume an asynchronous method in c but for some odd reason never explain how to build your own asynchronous methods to consume so i have this code right now that consumes my methodprivate async void button1 clickobject sender eventargs e var now await counttoasync10 label1text nowtostringand i wrote this method that is counttoasyncprivate taskdatetime counttoasyncint num 10 return taskfactorystartnew for int i 0 i num i consolewriteline0 i continuewithx datetimenowis this the use of taskfactory the best way to write an asynchronous method or should i write this another way,['c#'] +458482,checking at runtime if a class has a specific constructor that is using generics hello all i am trying to chose the right constructor in a class here is the codeconstructor constructors targetclassgetconstructorsconstructor goodconstructor nullfor constructor constructor constructors class parametertypes constructorgetparametertypes if parametertypeslength 1 parametertypes0equalsmapclass here goodconstructor constructor i want to switch from mapclass to mapstring stringclass i vaguely remember that generics are for compile time only so this is why the compiler is complaining how can i check at runtime that the class has the right constructorbest regards,['java'] +458550,angularjs directives change scope not reflected in ui i am trying to making some custom elements with angularjss and bind some events to it then i notice scopevar would not update ui when used in a binding function here is a simplified example that describing the probelmhtmldoctype htmlhtml ngapptest head script srcscript script srcscriptjsscript head bodydiv ngcontrollerctrl2 spanresultspan br button ngclickaabutton button mybuttonbbuttondiv bodyhtmljsfunction ctrl2scope scoperesult click button to change this string scopea function e scoperesult a scopeb function e scoperesult b var mod angularmoduletest moddirectivemybutton function return function scope element attrs change scoperesult from here works but not in bind functions scoperesult b elementbindclick scopeb demo basicly i bind click event to mybutton and want to change scoperesult when user clicked button b similar to ngclicka on button a but the view would not update to the new scoperesult if i do this waywhat did i do wrong thanks,['javascript'] +458577,serverside verification of google play inapp billing version 3 purchase i am unable to find a straight answer as to how i verify an inapp billing purchase on the server before making downloadable content available to the useri use in appbilling version 3 i purchase managed products using code based on the iabhelper class from the trivialdrive sample code everything is fine and dandy and the purchase is successfully completed i get a full purchase object back and the following original json data orderid1297631690547057581364365967744519 packagenamemy package name productid77 purchasetime13662175340 purchasestate0 purchasetokenutfwimslnrrwvglktizikdcdaoj1owz4l5oxz 3d2sawaaugfe3qerkoyix8wusenbw26ntsydmllgoud5lshqiy2p2lnlv4tph4nitb4mjmx98sctzizh7wgf6izw3tfw gfljdkfybgas i understand it i need to pass the purchasetoken and something i see referred to as a signature to the server the server then use a private key to verify the purchase is this correct if so where do i get the signature from and is there really no decent documentation concerning serverside verification of a purchase,['android'] +458603,how to test route constraints with rspec i am working on an application that will be primarily served as an api other than a few minor views such as sessionregistration which will be standard i like the approach that was finalized in railscast 350 versioning an api and so followed it my routes look likenamespace api defaults format json do scope module v1 constraints apiconstraintsnewversion 1 default false do resources posts only create show destroy index end scope module v2 constraints apiconstraintsnewversion 2 default true do resources posts only create show destroy index endendin each route my constraint is a new apiconstraints object which is located in my lib folder the class looks like thisclass apiconstraints def initializeoptions version optionsversion default optionsdefault end def matchesreq default reqheadersacceptincludeapplicationvndmyappvversion endendnow when testing manually everything works as expected in my api i may have between 5 and 10 controllers per version and do not want to test that the api constraints works for each individual controller as that makes no sense i am looking for one spec file that tests my api constraints but i am unsure of where to put that speci have tried adding a specroutingapi specrb file to test things but it is not working properly as it complains that some things are not provided like soit should route an unversioned request to the latest version do expectget apiposts format jsonto route tocontroller apiv1postsendthe above throws an error even though the controller matches properly it fails with the following errorthe recognized options formatjson actionindex controllerapiv1postsdid not match controllerapiv1postsdifference formatjson actionindexnotice that the controller was properly determined but since i do not want to test for the format and action in this test it errors out i would like there to be 3 api specsit should route an unversioned request to the latest versionit should default to the json format if none is specifiedit should return a specified api version when requesteddoes anyone have experience with writing specs for these kinds of routes i do not want to add specs for every controller inside the api as they are not responsible for this functionality,['ruby-on-rails'] +458645,is there any reason for public methods in a package protected class i wonder if it makes any difference if a method is public or package protected in a class that is package protectedclass example public void test instead ofclass example void test i guess the maximum visibility is given by the class and a method can only reduce the visibility and increasing the visibility has no effectbut it is valid syntax so perhaps i have overseen something,['java'] +458666,poor performance of vector in 64bit target with vs2012 benchmarking this clastruct sieve stdvectorbool isprime sieve int and 1 isprimeassign n1 true isprime0 isprime1 false for int i 2 i intsqrtdoublen i if isprimei for int j ii j n j i isprimej false i am getting over 3 times worse performance cpu time with 64bit binary vs 32bit version release build when calling a constructor for a large number egsieve s10i tested sizeofbool and it is 1 for both versionswhen i substitute vectorbool with vectorchar performance becomes the same for 64bit and 32bit versions why is thathere are the run times for s10 release mode 32bit first 64bit secondvectorbool 097s 312svectorchar 099s 099svectorint 157s 159si also did a sanity test with vs2010 prompted by wouter huysentruit is response which produced 098s 088s so there is something wrong with vs2012 implementationi submitted a bug report to microsoft connecteditmany answers below comment on deficiencies of using int for indexing this may be true but even the great wizard himself is using a standard for int i 0 i vsize i in his books so such a pattern should not incur a significant performance penalty additionally this issue was raised during going native 2013 conference and the presiding group of c gurus commented on their early recommendations of using size t for indexing and as a return type of size as a mistake they said we are sorry we were youngthe title of this question could be rephrased to over 3 times performance drop on this code when upgrading from vs2010 to vs2012editi made a crude attempt at finding memory alignment of indexes i and j and thiscovered that this instrumented versionstruct sieve vectorbool isprime sieve int and 1 isprimeassign n1 true isprime0 isprime1 false for int i 2 i sqrtdoublen i if i 17 cout inti16 endl if isprimei for int j ii j n j i if j 4 cout intj16 endl isprimej false automagically runs fast now only 10 slower than 32bit version this and vs2010 performance makes it hard to accept a theory of optimizer having inherent problems dealing with int indexes instead of size t,['c++'] +458668,why does listremoveint throw javalangunsupportedoperationexception i am trying to remove elements from a list and getting javalangunsupportedoperationexception public t extends object void findduplicates string title multimapt chunkid map for t key mapkeyset collectionchunkid ids mapgetkey listchunkid idlist arraysaslistidstoarraynew chunkid0 removeusedidsidlist collectionssortidlist private void removeusedidslistchunkid idlist decrement counter to avoid indexing changed parts of list for int i idlistsize 1 i 0 i if usedidsetcontainsidlistgeti idlistremovei exception thrown here and i getexception in thread main javalangunsupportedoperationexception at javautilabstractlistremoveunknown source at orgxmlcmlsvg2xmlanalyzerpdfindexremoveusedidspdfindexjava104 at orgxmlcmlsvg2xmlanalyzerpdfindexfindduplicatespdfindexjava87 at orgxmlcmlsvg2xmlanalyzerpdfindexfindduplicatesinindexespdfindexjava129 at orgxmlcmlsvg2xmlanalyzerpdfanalyzeranalyzepdfpdfanalyzerjava188 at orgxmlcmlsvg2xmlanalyzerpdfanalyzeranalyzepdffilepdfanalyzerjava115 at orgxmlcmlsvg2xmlanalyzerpdfanalyzermainpdfanalyzerjava398note this is flagged as a duplicate of remove on list created by arraysaslist throws unsupportedexception but it is significantly different that poster knew what the problem was and wanted an explanation i did not know what the problem was and could not find it on so by posting the current question java 6 docs gives no hint of the problem its signature throws indexoutofboundsexception the previous question also used removeall while this question referred to removeint so lexical searching is less precisei therefore asked on so and got rapid and useful answers because i phrased the title exactly unlike the previous question it should be easy for others to find this answer in less than a day it already has nearly as many votes as the previous question in a year and 100 views suggesting that it will be significantly more useful since this question is now linked to the previous one i think it adds to the general usefulness without polluting so the current answers are short and do not unnecessarily repeat informationi have edited the question to remove extraneous code if this question had been available when i encountered the problem it would have saved me an hour,['java'] +458670,d3 substituting d3svgdiagonal with d3svgline i have implemented the following graph with the edges rendered with d3svgdiagonal however when i try substituting the diagonal with d3svgline it does not appear to pull the target and source data what am i missing is there something i do not understand about d3svglinethe following is the code i am referring to followed by the full codevar line d3svgline xfunctiond return dlx yfunctiond return dly var link svgselectallpath datalinks enterappendpath attrdd3svgdiagonal attrclass link attrstroke black attrstrokewidth 2px attrshaperendering auto attrfill none the entire codevar margin top 20 right 20 bottom 20 left 20 width 1500 height 1500 diameter mathminwidth height radius diameter 2var balloon d3layoutballoon sizewidth height valuefunctiond return dsize gap50 var line d3svgline xfunctiond return dlx yfunctiond return dly var svg d3selectbodyappendsvg attrwidth width marginleft marginright attrheight height margintop marginbottom appendg attrtransform translate marginleft radius margintop radius root flarejson rooty0 height 2 rootx0 width 2d3jsonflarejson functionroot var nodes balloonnodesroot links balloonlinksnodesvar link svgselectallpath datalinks enterappendpath attrdd3svgdiagonal attrclass link attrstroke black attrstrokewidth 2px attrshaperendering auto attrfill none var node svgselectallgnode datanodes enter appendg attrclass node nodeappendcircle attrr functiond return dr attrcx functiond return dx attrcy functiond return dy nodeappendtext attrdx functiond return dx attrdy functiond return dy attrfontsize 5px attrfill white styletextanchor functiond return dchildren middle middle textfunctiond return dname a comparison of how the d attribute of the svg thisappears when using line,['javascript'] +458707,bug or meant to be numpy raises valueerror too many boolean indices for repeated boolean indices i am doing some simulations in experimental cosmology and encountered this problem while working with numpy arrays i am new to numpy so i am not sure if i am doing this wrong or if it is a bug i runenthought python thistribution wenthoughtcomversion 731 32bitpython 273 epd 731 32bit default apr 12 2012 112834 gcc 401 apple inc build 5493 on darwintype credits demo or enthought for more information import numpy as np t nparange10 tt 8t 5traceback most recent call last file stdin line 1 in modulevalueerror too many boolean indices i expected it to returnarray0 1 2 3 4since tt 8 should presumably be treated as just another ndarraythe numpy documentation says about boolean arrays as indices as with index arrays what is returned is a copy of the data not a view as one gets with slicesrunning typett 8 also gives ndarray which i guess should have all the properties of a numpy array should i perhaps do this better with list expressions i have not done a timed comparison yet but i would imagine this to be a problem for large 2d arrays,['python'] +458736,capybara not finding meta tags capybara 210 does not seem to find any meta tagsrdb1 p pagefind meta capybaraelementnotfound exception unable to find css metaeven when they appear in pagesourcerdb1 p pagesourcedoctype htmlnhtmlnheadntitlemytitletitlenmeta charsetutf8nmeta contentieedgechrome1 httpequivxuacompatiblenmeta contentwidthdevicewidth initialscale1 nameviewportnmeta namedescription,['ruby-on-rails'] +458747,is there a painless way to make a css sandbox by css sandbox i mean a section in my layout that have a completely independent look i need this because some classes of mine need to output some windows of content in the layout but i do not want the apps css to mess with them they are mostly debug related like printing var contents benchmark graphs or thisplaying some errorexceptionuntil now i was doing some kind of local reset but this gets really annoying to avoid collisions and could fail if i forget some rules exhtml body divehbox margin 0 important padding 0 important border 0 important fontsize 100 important verticalalign baseline important backgroundcolor f important font 12px12px helvetica neue helvetica arial sansserif important marginbottom 20px importanthtml body divehbox margin 0 important padding 0 important border 0 important fontsize 100 important font inherit important verticalalign baseline important color 3 importanthtml body divehbox title fontsize 50px important lineheight 75px important fontweight bold importanthtml body divehbox desc fontsize 24px important lineheight 36px important,"['html', 'css']" +458749,does nsinvocation retainarguments copy blocks nsinvocations retainarguments method is useful for when you do not run the nsinvocation immediately but do it later it retains the object arguments so they remain valid during this timeas we all know block arguments should be copied instead of retained my question is does retainarguments know to copy instead of retain an argument when it is of block type the documentation does not indicate that it does but it seems like an easy and sensible thing to doupdate the behavior seems to have changed in ios 7 i just tested this and in ios 61 and before retainarguments did not copy parameters of block type in ios 7 and later retainarguments does copy parameters of block type the documentation of retainarguments has been updated to say that it copies blocks but it does not say when the behavior changed which is really dangerous for people who support older oss,['objective-c'] +458790,rails stylesheets on heroku on my local machine when i view my rails app my stylesheets are successfully linked at assetsstylesheets but on heroku it is changed to stylesheets presumably in the public directory and does not work how do i get my stylesheets to move to publicstylesheets on compilationeditfile directory after rake assetsprecompileapp assets stylesheets applicationcss applicationmincss homecss homecscss homemincss scaffoldscss scaffoldscscss scaffoldsmincss startupscss startupscscsspublic assets application3701cb84bbc3c20d5a7ec1aac608fbdbjs application3701cb84bbc3c20d5a7ec1aac608fbdbjsgz applicationf7ff7ad51f3528ca1b5c7f2d5b5915css applicationf7ff7ad51f3528ca1b5c7f2d5b5915cssgz manifestad3babc6c84cc0b38f1a98eb594b8235json railsafd7b40a0142ed24738b640e78388de4pnghere is my stylesheet link in applicationhtmlhamlstylesheet link tag flatui homemin media allgem flatuirails is in my gemfile and require flatui is in my applicationcss fileedit 2cleared my publicassets folder added publicassets to my gitignore and pushed to my heroku repo during slug compilation heroku ran the asset pipline and made assetsapplicationb2c82b0573602f3a368a26f36b99542bcss which is also linked in the source code of my site but the styles do not load and i get the page you were looking for does not exist when i try to navigate to the style sheet now whatheres my applicationhtmlhaml 5html head title startupcrawler stylesheet link tag application media all csrf meta tags yield,['ruby-on-rails'] +458803,how can i remove a column from table using rails console it is easily possible to remove a column using rails migrationclass someclass activerecordmigration def selfup remove column table name column name endendi want to know if there is any way to remove a column from table using console,['ruby-on-rails'] +458841,what is the difference between set and unordered set in c came across this good question which is similar but not at all same since it talks about java which has different implementation of hashtables by virtue of having synchronized accessor mutatorsdifferences between hashmap and hashtableso what is the difference in c implementation of set and unordered set this question can be ofcourse extended to map vs unordered map and so on for other c containershere is my initial assessmentset while standard doesnt explicitly asks it to be implemented as trees the timecomplexity constraint asked for its operations for findinsert means it will always be implemented as treeusually as rb tree as seen in gcc 48 which is heightbalancedsince they are height balanced they have predictable timecomplexity for findpros compact compared to other ds in comparisoncon access time complexity is olg nunordered set while standard doesnt explicitly asks it to be implemented as trees the timecomplexity constraint asked for its operations for findinsert means it will always be implemented as hashtablepros faster promises amortized o1 for searcheasy to convert basic primitives to threadsafe as compared to treedscons look up not guaranteed to be o1 therotical worst case is onnot as compact as tree for practical purposes load factors is never 1note the o1 for hashtable comes from the assumption that there are no collision even with loadfactor of 5 every second variable insertion is leading to collisionit could be observed that the loadfactor of hashtable is inversely proportional to the number of operations required for accessing a element in it more we reduce operations sparser hashtable when the element stored are of size comparable to pointer then overhead is quite significantedit since most are saying question contains sufficient answer in it i am changing the question to did i miss any difference between mapset for performance analysis that one should know,['c++'] +458872,scroll issue in jquery datatable i am not sure if i am repeating the question if yes guide to the right place i am using data table and trying to implement horizontal scrolling and found this link initscroll xhtmli used these properties in my data table code and am having issues in uimy data got the horizontal scroll bar but my columns did not expand and not working as expectedi got additional empty column below my normal columnbasically my ui is messed up i saw a old thread thiscussion on the samedatatables header alignment issueare these issues fixed now any solutions adding sample coderesultsdatatable aadata my data aocolumns my columns bpaginate true bsort true bfilter false bjqueryui false bprocessing true sscrollx 100 sscrollxinner 110 bscrollcollapse true,['jquery'] +458881,uncaught error syntax error unrecognized expression unsupported pseudo i have an txtbox and its id is begindatetxtbut jsf makes it j idt8begindatetxtin jquery i try to reach it like that script typetextjavascript documentreadyfunction function j idt8begindatetxtmobiscrolldate theme androidics light modescroller thisplay bottom scriptbut i get below erroruncaught error syntax error unrecognized expression unsupported pseudo begindatetxt why,['javascript'] +458900,setting memory breakpoint in visual studio 2012 i need to set breakpoint that watches a specific address in memory eg 0x0483d7cc that is hit when the content changes i am using visual studio 2012 and c how can i do that,['c++'] +458909,jaxws duplicates complex type when generating wsdl i am developing a web service with several methods taking as input identical complex data types the data types have jaxb annotations and setters and getters and the web service class has jaxws annotationstemplate of my servicejava filewebserviceservicename servicewspublic class sericews private static serviceif serviceimplstatic serviceimpl new serviceimplpublic result method1credentials credentials webparamname credentials credentials credentials return serviceimplmethod1credentials public result method2credentials credentials webparamname credentials credentials credentials return serviceimplmethod2credentialsedit my credentialsjava filexmlaccessortypexmlaccesstypefieldxmltypename proporder name passwordxmlrootelementname credentialspublic class credentials implements mybean xmlelementrequired true protected string name xmlelementrequired true protected string password gets the value of the name property return the name property of the credentials public string getname return name sets the value of the name property param value the name property of the credentials public void setnamestring value thisname value gets the value of the password property return the password property of the credentials public string getpassword return password sets the value of the password property param value the password property of the credentials public void setpasswordstring password thispassword password the service is deployed in tomcat and the wsdl is autogenerated when generating the client stubs with wsimport i get duplicate generation of the credentials type credentials method1credentials and method2credentials ie a different inner class for each methodit seems that the problem arrises when the wsdl and schema are generated xsschema xmlnstns xmlnsxs version10 targetnamespacexselement namecredentials xscomplextype xssequence xselement namename typexsstring xselement namepassword typexsstring xssequence xscomplextypexselement xscomplextype namegetlockboxkeys xssequence xselement namecredentials minoccurs0 xscomplextype xssequence xselement namename typexsstring xselement namepassword typexsstring xssequence xscomplextype xselement how can i make all this work such that i have only one definition of credentials i am quite new to web services jaxws and jaxb so i am not sure i have the annotations rightany help would be greatly appreciated,['java'] +458926,better way to install iis7 programmatically i have a webapp installer that installs all of its prerequisites which includes iis 7 toosince iis does not come as a prerequisite in a visual studio setup project i came up with the following code to install iis from code targeting windows vista and 7private string configureiis7 string output stringempty if environmentosversiontostringcontainsmicrosoft windows nt 5 its windowsxp with or without sp2 messageboxshowiis 60 is not installed on this machine please install the same and proceed with the installation or contact your administratorinstallermessageboxbuttons ok messageboxicon warning throw new systemexceptioniis 60 is not installed on this machine else string cmdtoexecute cmdtoexecute cmd c start w pkgmgr llogetw iuiiswebserverroleiiswebserveriiscommonhttpfeaturesiisstaticcontentiisdefaultdocumentiisdirectorybrowsingiishttperrorsiishttpredirectiisapplicationdevelopmentiisaspnetiisnetfxextensibilityiisaspiiscgisisapiextensionsiisisapifilteriisserversideincludesiishealthanddiagnosticsiishttploggingiislogginglibrariesiisrequestmonitoriishttptracingiiscustomloggingiissecurityiisbasicauthenticationiisurlauthorizationiisrequestfilteringiisipsecurityiisperformanceiishttpcompressionstaticiishttpcompressiondynamiciiswebservermanagementtoolsiismanagementconsoleiismanagementscriptingtoolsiismanagementserviceiisiis6managementcompatibilityiismetabaseiiswmicompatibilityiislegacyscriptsiislegacysnapinwaswindowsactivationservicewasprocessmodelwasnetfxenvironmentwasconfigurationapi process prruniis new process prruniisstartinfo new procestartinfocmdexe cmdtoexecute prruniisstartinfouseshellexecute false prruniisstartinforedirectstandardoutput true prruniisstartinfocreatenowindow true prruniisstart prruniiswaitforexit output prruniisstandardoutputreadtoend return outputthis code has worked perfectly so far my only concern is that the installation part takes a considerable amount of timenow i have the opportunity to rewrite some of the codes and alter the installer ui i just came to this part and wondered if this was the only solution to install iis from code or is there may be some better way i have not foundi am just curious to know what are the other ways to install iis answers targeted for windows 8 are also appreciated,"['c#', '.net']" +459037,what is the purpose of character set connection just read stefan gehrig excellent answer to is set character set utf8 necessary which goes a bit further than mysqls documentation at explaining the stages of interpretting and running a query wrt character sets and collations but i still cannot really see the purpose of character set connection or more specifically transcoding the statement from character set client into character set connectionwhy not just use character set client for the query and transcode straight from character set client to the character set of the column when comparing with column values what is the purpose of this intermediate stage the manual gives the example of comparing literal stings but why would you want to do this in the first place let alone in character set connection as oppose to character set client unless my understanding of this something like select somestr somestr from x is wrongthank you,['mysql'] +459063,does fileappendalltext manage collisions ie multiuser concurrency questiondoes fileappendalltext manage collisions from multiple writersresearchi noticed that the msdn documentation does not really provide a position either way so i decided i would reflect the code and just see what it does below is the called method from fileappendalltextprivate static void internalappendalltextstring path string contents encoding encoding using streamwriter streamwriter new streamwriterpath true encoding streamwriterwritecontents and as you can see it simply leverages a streamwriter so if we dig a little deeper into that specifically the constructor it uses we find that it ultimately calls this constructorinternal streamwriterstring path bool append encoding encoding int buffersize bool checkhost basenull if path null throw new argumentnullexceptionpath if encoding null throw new argumentnullexceptionencoding if pathlength 0 throw new argumentexceptionenvironmentgetresourcestringargument emptypath if buffersize 0 throw new argumentoutofrangeexceptionbuffersize environmentgetresourcestringargumentoutofrange needposnum stream streamarg streamwritercreatefilepath append checkhost thisinitstreamarg encoding buffersize falsewith the following valuespath the path to the fileappend the text to appendencoding utf8nobombuffersize 1024checkhost trueand further we find that the basenull implementation does not really do anything but set the internalformatprovider to null so if we keep digging we find that createfileprivate static stream createfilestring path bool append bool checkhost filemode mode append filemodeappend filemodecreate return new filestreampath mode fileaccesswrite fileshareread 4096 fileoptionssequentialscan pathgetfilenamepath false false checkhostcreates a filestream with these parameter valuespath the path to the filemode filemodeappendaccess fileaccesswriteshare filesharereadbuffersize 4096options fileoptionssequentialscanmsgpath just the file name of the path providedbfromproxy falseuselongpath falsecheckhost truean so now were finally getting somewhere because were about to leverage the windows api and this is where the question really begins because that filestreamctor calls a method named init it is a pretty long method but i am really interested in one linethis handle win32nativesafecreatefiletext3 dwdesiredaccess share secattrs mode num intptrzerowhich of course calls createfile where the parameter values aretext3 the full path to the filedwdesiredaccess 1073741824share 1 file share readsecattrs nullmode 4 open alwaysnum 134217728 1048576 file flag sequential scan file flag posix semanticsso what would windows do if i had two threads trying to access that call at the same time for the same path would it open the file and buffer the writes so that both consumers are allowed to write to the file or do i need to leverage a lock object and lock around the call to appendalltext,"['c#', '.net']" +459091,cakephp how to use a view element inside of a controller i am trying to figure out how to use one of my view elements inside of a controlleri know i know do not do that 99 of the time this is the correct answerbut i think i actually have a good reason the action is handling an ajax request which returns markup the returned markup is a list which i thisplay everywhere else using an element so in an effort to keep my code dry i think it is appropriate to do this here is this possible,['php'] +459155,assertthat vs asserttrue what to preferassertthatobjfoo isequaltotrueorasserttrueobjfoofor me both asserts are equivalent so which one should be prefered,['c#'] +459162,should i check in rubygemset andor rubyversion i have just updated rvm and in place of the old rvmrc it autocreated rubygemset and rubyversioni have always had rvmrc files with contents like rvm use create defaultproject name however rubyversion contains the specific ruby version i am running rather than default i am hesitant to check this inalso i heard someone say on a podcast that one should not check in rubygemset because others may have their own preferences about how to name gemsetswhen should or should not i check in rubygemset andor rubyversionspecificallywhat are some of the tradeoffs how does the type of project affect the decision for example applications vs gemsif they should be checked in how does the type of project affect what should go in these filescitations from from the creators of tools like rvm rbenv etc would be appreciated in an answer,['ruby'] +459187,cannot update view databinding does not work angularjs and phonegap i am trying to make a simple todo application using phonegap for android device i also used angularjs for databinding i want to thisplay the list of tasks saved in database when i debug with chrome debugger i can see the sql request worked but nothing thisplays when i launch the application on an emulator or on the devicedbctrljsvar myapp angularmodulemyapp function dbctrlscope scopeinit function documentaddeventlistenerdeviceready ondeviceready false function ondeviceready var db windowopendatabasedatabase 10 cordova demo 20 dbtransactionpopulatedb errordb successdb function populatedbtx txexecutesqldrop table if exists demo txexecutesqlcreate table if not exists demo id unique todo txexecutesqlinsert into demo id todo values 1 first todo txexecutesqlinsert into demo id todo values 2 second todo function errordberr alerterror processing sql err function successdb var db windowopendatabasedatabase 10 cordova demo 20 dbtransactionquerydb errordb query the databasefunction querydbtx txexecutesqlselect from demo querysuccess errordb query the success callbackfunction querysuccesstx results consolelogreturned rows resultsrowslength scopetodos resultsrowsscopeinitdbindexhtmlbody ngappmyapp div ngcontrollerdbctrl div h1simpletodosh1 div div idmaincontent ul ngrepeattodo in todos litodoidli ul div div classuibar a hrefedithtmladd notea div div script srclibscordova250jsscript script srclibsangular105js typetextjavascript script script srcdbctrljs typetextjavascript scriptbodysomeone knows why the view is not updated do we have any way around,"['javascript', 'android']" +459208,when to replace a global stdunique ptr with a singleton a colleague has insisted on using meyers singleton for all global pointer variables as there is no guarantee the construction of the global unique ptr would not throw so instead ofinclude memorystdunique ptrfoo ptrnullptr apparently this is not safeint mainblah ptrresetnew foowe now haveunique ptrfoo singleton try static unique ptrfoo ptr return ptr catch stdcerr failed to create single instancen exit1 return unique ptrtype int mainto me this seems like a solution looking for a problem does he have a point,['c++'] +459216,why java iterator interface should be implemented as inner class i recently read a book the java tutorials 3rd editionit talks about inner class implementation as the picture showsin the 3rd paragraph it says the stack class itself should not implement the iterator interface becausei cannot find any reason that stack class should not implement iterator the reason given is not persvasivecould you explain it,['java'] +459268,how to point a websocket to the current server i have a jetty 8 server running hopefully soon with websocketsif i want to send some data to the server with an ajax call i can do thisajax url ajaxagetsomedata in this scenario if i connect to my server at 1921681100 the real url where it will get the data from will be 1921681100ajaxagetsomedata but if i connect to another server running the same software at 1921681200 the url will be 1921681200ajaxagetsomedatabut if i want to accomplish the same thing using websockets i cannot find how to do itvar socket new websocketwswexamplecomworks but i want something like a relative urlvar socket new websocketwssocketsagetsomedataso that like the ajax request if i were connecting to my server at 1921681100 the url will be 1921681100socketsagetsomedata and if i connect to 1921681200 the url will be 1921681200socketsagetsomedatahow can i accomplish this,['javascript'] +459309,dropwizard hot deployment i am looking for a simple to use system in java which creates a rest service for me so i found dropwizard but as far as i can use google it turns out it lacks hot deployment although jetty is able to do so when using the mavenshadeplugin it takes at least 10 seconds to build the thing also my ide reports that it cannot use compile on save feature aka hot deployment when the shadeplugin is involvedcan i use hotdeployment somehow or what can i use insteadupdate if nothing will fix this i will probably use a combination of jerseyguice etc which is explained in this post,['java'] +459316,caching linq expressions by equality consider this scenarioyou have a repository that allows certain calls to be made on it these calls use linq and could be relatively expensive in terms of the amount of data returnedgiven that in my case it is not overly bad if the data is old one could implement a cache so that the large and expensive query was not executed every call hey we could even implement some caching policies to determine when to execute that query again based on time or useagethe thing i am trying to wrap my head around is how to key that in a cache one way would be to simply sayquerytype1 particular linq expressionquerytype2 particular linq expressionand then key the cache by a simple string but given were doing linq could we potentially key the cache by the linq expression itself i understand the performance indications but is there anyway to compare whether two linq expressions are the same,['c#'] +459332,set variable in if statement expression i ran across some interesting code today i tried to find out if this is a feature of php or if i am missing something but was unable to find anything on google probably because i do not know the name of itcode iflogo repositorieslogogetlogodataid logo href logolinkthe variable logo is not being set anywhere else it seems like the expression in this if statement is checking to see if the that class method is returning anything and simultaneously setting the variable logo to be used in the statementis this true if so what in the world is this called,['php'] +459399,what is the lifecycle of an angularjs controller can someone please clarify what the lifecycle of an angularjs controller isis a controller a singleton or created destroyed on demandif the latter what triggers the creation destruction of the controllerconsider the below examplevar demoapp angularmoduledemo configfunctionrouteprovider locationprovider routeprovider whenhome templateurl homehtml controller homectrl whenuserstemplateurl usershtml controller usersctrl whenusersuserid templateurl usereditorhtml controller usereditorctrl demoappcontrollerusereditorctrl functionscope routeparams userresource scopeuser userresourcegetid routeparamsuseridegin the above example when i navigate to users1user 1 is loaded and set to the scopethen when i navigate to users2 user 2 is loaded is the same instance of usereditorctrl reused or is a new instance createdif it is a new instance what triggers the destruction of the first instanceif it is reused how does this work ie the method to load the data appears to run on creation of the controller,['javascript'] +459405,check box tag with label tag click action flabel category br check box tag category 1 false label tag community community class category select value 1 check box tag category 2 false label tag food food class category select value 2 check box tag category 3 false label tag music music class category select value 3 br check box tag category 4 false label tag education education class category select value 4 check box tag category 5 false label tag theatre theatre class category select value 5 check box tag category 6 false label tag art art class category select value 6 br check box tag category 7 false label tag culture culture class category select value 7 check box tag category 8 false label tag family family class category select value 8 check box tag category 9 false label tag sports sports class category select value 9 bri would like to be able to have these options show up in my controller under a category array so i named all the options category what i would like to accomplish is for the label tag and check box tag fields to know about each other check box tag community community false label tag community community class category select here if i click on the words the box also gets checked i tried to accomplish this with the values on the label tag but it does not seem to work can this be accomplished,['ruby-on-rails'] +459437,windowisfloating attribute in android theme what does this attribute really doi have read the documentation and i understand what it is supposed to be however when i use it in a theme i created a style with the androidthemedialog as the parent changing the value for this attribute does not seem to have any effect,['android'] +459476,send push notification to ios for chat to offline user openfire xmpp i have an ios chat application that uses openfire what i need to do is send push notification when the message 1 cannot be delivered for any reason 2 app is in suspended state ie cannot generate a notification on its own i have read most of the related questionssuggestions on this on stackoverflow and elsewhere and i have concluded few solutions to my problem i am not an ios developer nor did i know anything about openfire or xmpp before a couple of days so i am afraid my understanding of things may not be complete and my solutions might be flawedkindly confirm my understanding of it and suggest if i am missing something or if there is a better approach please also suggest about how complex it is going to be to implement a particular solution listed belowchallenge here is to identify when the push is required and where the process be initiated so1 one way is to use the xep0184 implementation of xmpp to check if the message is delivered to do this we should have some delivered flag with message in ios database which is updated when the delivered response is received form other end so we need check for this flag after a little while and if the delivered status is false initiate push process with the message looks to be a complicated solution wait for response check flag with some time lag not very impressive 2 a more straight forward approach is to do something in openfire when openfire cannot deliver a message it stores it in offline table we can do some interception on that part and initiate the push process with the message this looks to be the correct approach but i am really afraid of getting that much inside openfire and change somethingit might be easy also somebody who has worked a little with openfire can tell3 this is my last resort and this is not a solution but if i cannot do it correctly within expected timeframe which is a week from now we plan to send a push notification for all the messages oppenfire will takecare of normal chat while a push will be sent from our server for each message but when the app is in foreground we do something to handle the extra push messages that need not be shown otherwise a push is received whenever there is a message what do you guys think of this temporary way around we will of course have to change this as soon as we can is this doable or i am missing something here as wellps can anyone tell how whatsapp and other popular apps handle thismany thanks for your help,['ios'] +459514,render html in label tag in rails 3211 html safe raw not working using rails 3211 ruby 187i am having some serious problem trying to make label tag output html basically it boils down to label tag this will strongnotstrong work i have tried raw label tag this will strongnotstrong work label tag raw this will strongnotstrong work label tag this will strongnotstrong workhtml safe label tag this will strongnotstrong workhtml safe i have installed the gem rails xssnothing workseven though i can find a lot of related problems with escaping html where people having problems with raw and html safe not working nothing is related to label tag i cannot use flabel for this issuethis used to work on the same application but after a few updates where rails 303 3211 was the major one it stopped working i did not notice when this happened so i am not sure what caused the problemcan you replicate do you have a solution,['ruby-on-rails'] +459519,angular ie caching issue for http all the ajax calls that are sent from the ie are cached by angular and i get a 304 response for all the subsequent calls though the request is the same the response is not gonna be the same in my case i wanna thisable this cache i tried adding the cache attribute to httpget but still it didnt help how can this issue be resolved,['javascript'] +459550,tfs build test results were working on visual studio 2010 and tfs 2010 we have our own buildtemplate that is a copy of default template but with some additions like create directory but the main point that all that is in defaulttemplate is leftwe have witten unit tests that also are working i have made build definition that runs all the unit tests have read the information here and a lot of other places alsobuild runs just perfect the only thing that isnt working is a build summary test results code coverage like in the link aboveso when i am watching activity log while building my application it shows thatrun mstest for test assembliescprogram files x86microsoft visual studio 100common7idemstestexe nologo usestderr testsettingscbuilds7projectbuildnamesourcesprogramnameprognameandversionsolutionssolutionnamelocaltestrundebugtestrunconfig searchpathrootcbuilds7projectbuildnamebinaries resultsfilerootcbuilds7projectbuildnametestresults testcontainercbuilds7projectbuildnamebinariestestprojectnamedll publishhttp8080tfsmsln publishbuildbuildbuild14599 teamprojectprojectname platformx86 flavorrelease loading cbuilds7projectbuildnamesourcesprogramnameprognameandversionsolutionssolutionnamelocaltestrundebugtestrunconfigloading cbuilds7projectbuildnamebinariestestprojectnamedllstarting executionresults top level tests failed testfailed testfailed testpassed testpassed testinconclusive testinconclusive testpassed testmany other tests5154 tests passed 147 failed 2 inconclusivesummarytest run failedfailed 147passed 5inconclusive 2total 154results file cbuilds7projectbuildnametestresultstfsbuild tfsbuilder 20130419 10 03 42 x86 releasetrxtest settings local test runand at the end of the build summary is blank1 projectssolutions compiled no test results no code coverage resultswhy does it not show test results like in the link i am a starter in tfs so help me with this by giving advices in simple language,['c#'] +459570,how can we know the caller functions name in c language we can use function to get the current functions namebut if i define a function named a and in b it calls a like belowb anow in the source code there are lots of functions like b which call a eg c d eis it possible for that within a add some code to detect its current execution of a is called by which functionfurthersorry to make th typo to misleading you i correct it alreadyi try to find out which function calls a for debug purpose ido not know how you do when in the same situation and my code is under vxworks but i am not sure whether it is related to c99 orsomething else,['c'] +459576,aspnet mvc custom validation by dataannotation i have a model with 4 properties which are of type string i know you can validate the length of a single property by using the stringlength annotation however i want to validate the length of the 4 properties combined what is the mvc way to do this with data annotationi am asking this because i am new to mvc and want to do it the correct way before making my own solution,"['c#', '.net']" +459588,path of least resistance when unit testing c code in an exe in visual studio 2012 i am in need of some sage advice here long story short i am rebuilding a for me relatively complex app comprised of about 70 lines of code i ran into a number of issues when i created the first iteration of my application and it seems to me that test driven development might just be the ticketi was pleased to see that visual studio 2012 now natively supports tdd in c so i went ahead and read as much as i could unfortunately vs2012 is fairly new and i feel the documentation is somewhat lacking but this is a little beside the point i am relying mainly on the following guide on the msdn siteit fairly clearly states that if the code under testing is to be built as an exe then the way forward is creating a separate test project and linking the output object file i am guessing they mean the object files or maybe noti am honestly a little confused as to how many objs i need to link at first i thought i needed to link every single obj file which is fairly tediousif anyone has experience doing this and could perhaps also recommend which macros or similar short cuts to use in order to make this process as painless as possible i would be much obliged,['c++'] +459598,select multiple fields group by and sum i want to do a query with linq list of objects and i really dont know how to do it i can do the group and he sum but cant select rest fieldsexampleid value name category1 5 name1 category1 1 7 name1 category12 1 name2 category23 6 name3 category33 2 name3 category3i want to group by id sum by value and return all fiedls like thisid value name category1 12 name1 category1 2 1 name2 category23 8 name3 category3thanks in advance,"['c#', 'asp.net']" +459602,stringformat input string was not in correct format for string with curly brackets already as part of the format c i am trying to format a json input to a json rpc for example the json am goint to post is as followingfilter ids 123 124 typesemployeewhich i expect to return users with id 123 124 and of type employee but for the ids parameter i want to may it dynamic so that i can set the value in my c calling method like the followingstringformatfilter ids 0 typesemployee 123 124when doing so i get the format exception input string was not in correct formati know i can build up the string using stringconcat or string builder am just curious if there is any solution to overcome this stringformat exception in the event when a string has curly brackets am assuming this is the cause of the exception already,['c#'] +459631,dynamically loading plugin jars using serviceloader i am trying to create a plugin system for my application and i want to start with something simple every plugin should be packed in a jar file and implement the simpleplugin interfacepackage plugintestpublic interface simpleplugin public string getnamenow i have created an implementation of simpleplugin packed in a jar and put it in the plugin subdirectory of the main applicationpackage plugintestpublic class plugintest implements simpleplugin public string getname return i am the plugin in the main application i want to get an instance of plugintest i have tried two alternatives both using javautilserviceloader1 dynamically extending the classpaththis uses the known hack to use reflection on the system class loader to avoid encapsulation in order to add urls the the classpathpackage plugintestsystemimport plugintestsimplepluginimport javaiofileimport javaioioexceptionimport javaneturlimport javaneturlclassloaderimport javautiliteratorimport javautilserviceloaderpublic class manageplugins public static void mainstring args throws ioexception file loc new fileplugins extendclasspathloc serviceloadersimpleplugin sl serviceloaderloadsimplepluginclass iteratorsimpleplugin apit sliterator while apithasnext systemoutprintlnapitnextgetname private static void extendclasspathfile dir throws ioexception urlclassloader sysloader urlclassloader classloadergetsystemclassloader url urls sysloadergeturls udir dirtouritourl string udirs udirtostring for int i 0 i urlslength i if urlsitostringequalsignorecaseudirs return classurlclassloader sysclass urlclassloaderclass try method method sysclassgetdeclaredmethodaddurl new classurlclass methodsetaccessibletrue methodinvokesysloader new object udir catch throwable t tprintstacktrace the plugins directory is added as expected as one can check calling sysloadergeturls but then the iterator given by the serviceloader object is empty2 using urlclassloaderthis uses another definition of serviceloaderload with a second argument of the class classloaderpackage plugintestsystemimport plugintestsimplepluginimport javaiofileimport javaiofilefilterimport javaioioexceptionimport javaneturlimport javaneturlclassloaderimport javautiliteratorimport javautilserviceloaderpublic class manageplugins public static void mainstring args throws ioexception file loc new fileplugins file flist loclistfilesnew filefilter public boolean acceptfile file return filegetpathtolowercaseendswithjar url urls new urlflistlength for int i 0 i flistlength i urlsi flistitouritourl urlclassloader ucl new urlclassloaderurls serviceloadersimpleplugin sl serviceloaderloadsimplepluginclass ucl iteratorsimpleplugin apit sliterator while apithasnext systemoutprintlnapitnextgetname once again the iterator has never a next elementthere is surely something i am missing since it is the first time i am playing with class paths and loading,['java'] +459671,wpf templating difference between triggers and visualstatemanager i would like to know what difference is between triggers and visualstatemanager i am templating combobox and on the official msdn sites they are using visualstatemanager for changing colors of selected comboboxitem but the same you can do with triggers is there some differences between for example visualstatemanager will be quicklier or i dont know and i would like to know what is better to use i am noob in templating and i dont understand it too much so what i can use right now is triggers that i understand but visualstatemanager and some storyboards are big unknow for me right now,['c#'] +459733,java objecthashcode address or random i am trying to understand the native implementation of the hashcode method what exactly does this method return is it a memory address or is it a random value,['java'] +459749,refresh or change the alertdialog message i create an alertdialogalertdialogbuilder builder new alertdialogbuilderthisalertdialog alert buildercreatealertshowafter a moment i want to change the alertdialog message without closing itis it possible,['android'] +459757,thread safe singleton class i wrote a below singleton class i am not sure whether this is thread safe singleton class or notpublic class cassandraastyanaxconnection private static cassandraastyanaxconnection instance private astyanaxcontextkeyspace context private keyspace keyspace private columnfamilystring string emp cf public static synchronized cassandraastyanaxconnection getinstance if instance null instance new cassandraastyanaxconnection return instance creating cassandra connection using astyanax client private cassandraastyanaxconnection context new astyanaxcontextbuilder forclustermodelconstantscluster forkeyspacemodelconstantskeyspace withastyanaxconfigurationnew astyanaxconfigurationimpl setthiscoverytypenodethiscoverytypering describe withconnectionpoolconfigurationnew connectionpoolconfigurationimplmyconnectionpool setport9160 setmaxconnsperhost1 setseeds1270019160 withastyanaxconfigurationnew astyanaxconfigurationimpl setcqlversion300 settargetcassandraversion12 withconnectionpoolmonitornew countingconnectionpoolmonitor buildkeyspacethriftfamilyfactorygetinstance contextstart keyspace contextgetentity emp cf columnfamilynewcolumnfamily modelconstantscolumn family stringserializerget stringserializerget returns the keyspace return public keyspace getkeyspace return keyspace public columnfamilystring string getemp cf return emp cf can anyone help me with this any thoughts on my above singleton class will be of great helpupdated codei am trying to incorporate bohemian suggestion in my code here is the updated code i gotpublic class cassandraastyanaxconnection private static class connectionholder static final cassandraastyanaxconnection connection new cassandraastyanaxconnection public static cassandraastyanaxconnection getinstance return connectionholderconnection creating cassandra connection using astyanax client private cassandraastyanaxconnection context new astyanaxcontextbuilder forclustermodelconstantscluster forkeyspacemodelconstantskeyspace withastyanaxconfigurationnew astyanaxconfigurationimpl setthiscoverytypenodethiscoverytypering describe withconnectionpoolconfigurationnew connectionpoolconfigurationimplmyconnectionpool setport9160 setmaxconnsperhost1 setseeds1270019160 withastyanaxconfigurationnew astyanaxconfigurationimpl setcqlversion300 settargetcassandraversion12 withconnectionpoolmonitornew countingconnectionpoolmonitor buildkeyspacethriftfamilyfactorygetinstance contextstart keyspace contextgetentity emp cf columnfamilynewcolumnfamily modelconstantscolumn family stringserializerget stringserializerget returns the keyspace return public keyspace getkeyspace return keyspace public columnfamilystring string getemp cf return emp cf can anyone take a look and let me know if this time i got it right or notthanks for the help,['java'] +459758,returning a stdvector right approach i am trying to create a class method that will return a stdvector and am a bit confused about the best way to do thisthe approach i have used is to define the following methodstdvectordouble getbinsvoidand in the method allocate a new stdvector which i fill with data i am returning a pointer to this iestdvectordouble frequencygetbinsvoid stdvectordouble rtnvec new stdvectordouble for itmap mapfreqbegin itmap mapfreqend itmap rtnvecpush back itmapfirst return rtnvec itmap is a classdefined iteratorin my maincpp i have done the following stdvectordouble mybins mybins myfreq3getbins delete mybinsi know with this approach i am going to get a dangling pointer unless i delete the pointer in the maincpp code so it is already a bit dangerous whats the best way to return a new stdvector from a class methodthanks guyspete,['c++'] +459779,symfony produces a white page i have tried to integrate a symfony project on my server but it produces a blank page does not produce any errors even if i on the error thisplay in php after i include configuration file in indexphp nothing works even the die in the first line of project configuration file does not print when i try thismy indexphp file iserror reportinge all ini setthisplay errors 1 require oncedirname file configprojectconfigurationclassphp configuration projectconfigurationgetapplicationconfigurationfrontend prod false sfcontextcreateinstanceconfigurationthispatchi am including the project configuration file also here please check that alsorequire once dirname file libsymfonyautoloadsfcoreautoloadclassphpsfcoreautoloadregisterclass projectconfiguration extends sfprojectconfigurationpublic function setup thisthispatcherconnectrequestfilter parameters arraythis filterrequestparameters public function filterrequestparameterssfevent event parameters request eventgetsubject if preg matchsafari09 requestgethttpheaderuseragent requestsetrequestformathtml return parameters i have included the symfony folder inside the lib folder of the projectit does not produce any error even i tried it in development mode also please not that i have provide full permission to all files including cache and log folder,['php'] +459798,javascript equivalent of pythons dictsetdefault in python for a dictionary ddsetdefaultkey valuesets dkey value if key was not in d and otherwise leaves it as it isis there a clean idiomatic way to do this on a javascript object or does it require an if statement,['javascript'] +459837,using web workers in phonegap i am trying to create a html5 web worker in phonegap but phonegap does not allow me to load a local javascript file at runtimei get the following errorvar web workernew workersocketworkerjsundefinedfilesocketworkerjsfailed to load resource the requested url was not found on this serverdoes anyone have a good suggestion on how i can work around this and get the worker runningthanks,['javascript'] +459840,nomethoderror in postscontrollercreate forgive my ignorance but i am brand new not only to ruby but programming in general i am working through the example on edge guides at rubyonrailsorg and am receiving the following error and despite reviewing every piece of code i have typed since the app last worked i am unable to fix it nomethoderror in postscontrollercreateundefined method permit for title textactivesupporthashwithindifferentaccessand this is what my posts controllerrb looks likeclass postscontroller applicationcontroller def new post postnew end def create post postnewparamspostpermittitle text if postsave redirect to action show id postid else render new end end def show post postfindparamsid end def index posts postall end endwhat am i doing wrongthank you in advance for any help,['ruby'] +459892,how to perform a transform on npm module using browserify by default browserify does not perform transforms on modules included from node modules ie with no pathi made a quick github repo that illustrates it here the indexjs file that gets browserified looks like thisvar fs requirefsvar testmodule requiretestmodulevar trg1 documentgetelementbyidtarget1var trg2 documentgetelementbyidtarget2trg1innerhtml fsreadfilesync dirnamesomethingtxttrg2innerhtml testmoduletestmodule looks like this var fs requirefsexports moduleexports function return fsreadfilesync dirnamedatatxtusing the brfs transform module i want to be able to inline both calls to fsreadfilesync but when i run browserify indexjs t brfs o bundlejs only the call in my main project gets inlined here is the bundlejs result functionetnfunction rniiftnifenvar stypeof requirefunctionrequireifisreturn sn0throw new errorcannot find module nvar otnexportsen0functiontvar ien1treturn riitooexportsreturn tnexportsforvar i0inlengthirnireturn r1functionrequiremoduleexports nothing to see here no file methods for the browser2functionrequiremoduleexportsvar fs requirefsvar testmodule requiretestmodulevar trg1 documentgetelementbyidtarget1var trg2 documentgetelementbyidtarget2trg1innerhtml this is data from a file in the main project folder transformedtrg2innerhtml testmodulefs1testmodule33functionrequiremoduleexportsfunction dirnamevar fs requirefsexports moduleexports function return fsreadfilesync dirnamedatatxt no transformnode modulestestmodulefs12,['javascript'] +459944,android exported receiver does not require permission on receivers meant to receive from system services i have some receivers declared in my manifest receiver no warning androidnamereceiverstriggermonitoringbootreceiver androidenabledfalse intentfilter action androidnameandroidintentactionboot completed intentfilterreceiverreceiver no warning androidnamereceiversscanresultsreceiver androidenabledfalse intentfilter action androidnameandroidnetwifiscan results intentfilterreceiverreceiver warning exported receiver does not require permission androidnamereceiversbatterymonitoringreceiver androidenabledfalse intentfilter action androidnamestringintent action setup alarm action androidnamestringintent action cancel alarm action androidnamestringintent action monitor intentfilterreceiverthe first one is meant to receive a boot completed action the second is meant to receive androidnetwifiscan results the third one is meant to receive some actions i broadcast intent action monitor and some actions broadcasted by the alarmmanager intent action setup alarm etctwo questions why do not i get the warning on all receivers what permissions do i need to set for receivers meant to receive from system services to correct the warning i understand what it is about and i do not want anyone to use my receivers anyway will exportedfalse do for boot receivers wifi receivers alarm receivers etc i thought of using a custom permission with androidprotectionlevelsignatureorsystem but the docs advise against both this protection level and custom permissions so how i should handle this warning links to the docs andor some code will be much appreciated,['android'] +459963,how to associate an object with a dom element i have a master object in my js setup ievar mygarage cars make ford model escape color green inuse false make dodge model viper color red inuse true make toyota model camry color blue inuse false now i loop over my cars and put them in a table in the table i also have a button that lets me toggle the car as in use and not in use how can i associate the dom element of every row with its corresponding car so that if i toggle the inuse flag i can update the master object,"['javascript', 'jquery']" +459980,how to add new column to mysql table i am trying to add a new column to my mysql table using php i am unsure how to alter my table so that the new column is created in my assessment table i have assessmentid q1 q2 q3 q4 q5 say i have a page with a textbox and i type q6 in to the textbox and press a button then the table is updated to assessmentid q1 q2 q3 q4 q5 q6thanks in advancephp include coreinitphpinclude coreadmininitphpinclude includesoveralloverall headerphp adminprotect pageinclude includesadminmenuphp phpmysql queryalter table assessment add newq int1 not null after q10h1input career nameh1 form methodpost action career name input typetext namenewq size20 input typesubmit namesubmit valuesubmitbodyhtml,"['php', 'mysql']" +459982,using json in portable class library i am attempting to load some data in a portable class library the data is in json format i need parse and work with this information unfortunately it does not appear that systemjson is available at the same time i tried to include the jsonnet nuget package without any luck how does one work with json data in a portable class librarythank you,['c#'] +459984,python comparing lists i want to compare two lists and want to know if a element corresponds to another elementexamplea should correspond to bhere it will return truelist1 abcdlist2 badca and b correspond to eachother they share the same spot on lists how do i make a function to return true if they correspondlist1 abcdlist2 cdabthis would return false,['python'] +459990,if int32 is just an alias for int how can the int32 class use an int been browsing through net source code of net framework reference source just for fun of it and found something i do not understand there is a int32cs file with c code for int32 type and somehow that seems strange to me how does the c compiler compile code for int32 type public struct int32 icomparable iformattable iconvertible internal int m value but is not this illegal in c if int is only an alias for int32 it should fail to compile with error cs0523 struct member struct2 field of type struct1 causes a cycle in the struct layout is there some magic in the compiler or am i completely off track,['c#'] +459996,nesting media queries by default i want to give my body element a green border on a device that supports retina thisplay i want to check for size first on an ipad i want to give my body a red border and on an iphone i want to give it a blue border but nesting media queries like so does not work body border 1px solid green media webkitmindevicepixelratio 2 minresolution 192dpi media maxwidth 768px and minwidth 320px body border 1px solid red media maxwidth 320px body border 1px solid blue,['css'] +459997,how to thisableoverride naming containers id generation of content pages control ids we have an existing aspnet web application which we want to convert into using masterpages in the process of doing this i found that the html ids generated for the html elements are prefixed with the contentplaceholders id and this is what can be expected when we set the contentplaceholders clientidmodestaticnow since we have a lot of existing client side scripts that make use of the ids this part breaks when we use masterpages and it is quite a big job to run through all our javascript to make sure we call the javascript using controlclientid as a lot of it is hardcodedis there a way to thisable the prefixing i can succeed doing this if i create every control setting its clientidmodestatic but then again i would prefer settings this once to ensure that all controls are have their clientidmodestatic is that possible or is it possible to override the namingcontainer of the contentplaceholderthe platform is net 40after fixing the above problem with clientidmodestatic in the webconfig as described in the answer below i have bumped into the problem that the name attribute is automatically generated and is not set to whatever it was before i introduced masterpages this gives me a problem with my existing server code which has many requestform any idea what best practice is here to solve this problemthanks jihad,['asp.net'] +459998,calling dot products and linear algebra operations in cython i am trying to use dot products matrix inversion and other basic linear algebra operations that are available in numpy from cython functions like numpylinalginv inversion numpydot dot product xt transpose of matrixarray there is a large overhead to calling numpy from cython functions and the rest of the function is written in cython so i would like to avoid thisif i assume users have numpy installed is there a way to do something like include numpynpy mathhas an extern and call these functions or alternatively call blas directly or whatever it is that numpy calls for these core operations to give an example imagine you have a function in cython that does many things and in the end needs to make a computation involving dot products and matrix inversescdef myfunc do many things faster than python could compute one value using dot products and inv without using import numpy as np np val gammalnsumv sumgammalnv dotv 1t logxthow can this be done if there is a library that implements these in cython already i can also use that but have not found anything even if those procedures are less optimized than blas directly not having the overhead of calling numpy python module from cython will still make things overall fasterexample functions i would like to calldot product npdotmatrix inversion nplinalginvmatrix multiplication taking transpose equivalent of xt in numpygammaln function like scipygammaln equivalent which should be available in ci realize as it says on numpy mailing list topiccythonusersxzjmvsiqnte that if you call these functions on large matrices there is no point in doing it from cython since calling it from numpy will just result in the majority of the time spent in the optimized c code that numpy calls however in my case i have many calls to these linear algebra operations on small matrices in that case the overhead introduced by repeatedly going from cython back to numpy and back to cython will far outweigh the time spent actually computing the operation from blas therefore i would like to keep everything at the ccython level for these simple operations and not go through pythoni would prefer not to go through gsl since that adds another dependency and since it is unclear if gsl is actively maintained since i am assuming users of the code already have scipynumpy installed i can safely assume that they have all the associated c code that goes along with these libraries so i just want to be able to tap into that code and call it from cythonedit i found a library that wraps blas in cython which is close but not what i am looking for i would like to call the numpyscipy c functions directly i am assuming the user has these installed,['python'] +460010,trying to hide and show menu items on action bar i have looked through the questions on stack overflow and cannot find the solutionoverridepublic boolean onprepareoptionsmenumenu menu menuinflater inflater getmenuinflater inflaterinflatermenuthemenu menu menuitem item menufinditemridmenu settings menuitem item2 menufinditemridmenu save itemsetvisibleisdown item2setvisibleisdown return truethis sets my menu items to visible item1 and item2 the onclick works finepublic void inflatetextarea ifisdown true isdown false linearlayout tl linearlayoutfindviewbyidridcontent tlsetvisibilityviewvisible scaleanimation scale new scaleanimation1 1 0 1 scalesetfillaftertrue scalesetduration500 tlstartanimationscale then this sets my isdown boolean to false on stack people say that the onprepareoptionsmenu should fire everytime i click but this is not the casei am able to hide one menu item on the onclick functionoverridepublic boolean onoptionsitemselectedmenuitem item switchitemgetitemid case ridmenu settings logvlogedit item pressed return true but i have multiple menu items that i need to hide and others that i want to showhow can i go about this,['android'] +460151,android javaioioexception service not available description i am using google maps api v2i have implemented android reverse geocoding at touched locationproblem it throws exception on try addresses geocodergetfromlocationlatitude longitude1 catch ioexception e eprintstacktrace ifappconstantsdebuglogvappconstantsdebug tag eprintstacktrace egetmessage i am receiving latitude and longitude values correct but i cannot understand why it throws exception and i have also done google search but it could not helpcan anybody please explain in details,['android'] +460214,in ruby unit tests how to assert that a string contains certain substring in a ruby unit test how do i assert that a string contains a substring something likeassert contains string to test substring to verify,"['ruby-on-rails', 'ruby']" +460250,trigger keypress with jquery on the definitive trigger keypress jquery thread there is no working jsfiddle for the answer and the code that is there does not work for me buttonclickfunction inputfocus var e jqueryeventkeydown ewhich 77 some key code value inputtriggerethere is my code and heres my fiddleon click an m should appear in the input as the input is given focus and having a keydown with the keycode of 77 m triggered on it any ideasedit my true purpose for this is to trigger an m hotkey on a sublime video in order to mute the video programmatically this was my first step to ensure i was firing the m key properly which i am with the help of stack overflow however i am still not able to get an event to fire programmatically on the video i think this is just a problem with sublime video but i am not sure and anyones views on forcing keypresses and clicks would be awesome to hear,['jquery'] +460268,mobile firefox ignores viewport completely i am lost and cannot figure out how to convince mobilefirefox to load my site fully zoomed out i could not find a working solution searching both stackoverflow and the web heres a link to thewebsite there is no separate mobileversion of my website i allow zooming in and out and on iphones ipads and the stock androidbrowser it works flawlessly but using mobilefirefox on my android it loads the page zoomed it and that alone is not the main problemthe clickable area of the page remains the same small box of the initialzoom i cannot slide my sliders i cannot even click on pictures outside of that small activity box to open fancyboxlinks and the like as soon as i pan my site into that little box i can slide click links and interact as i should be able tomy metacode is the following meta nameviewport contentwidthdevicewidth initialscale1i used html5boilerplate as a starting point for my website do you see any conflict that could pose with my viewport problem another user seemed to find a solution getting rid of another metatag pointing to older browsers i find the following in my code but it does not matter whether i erase it or not meta charsetutf8 meta httpequivxuacompatible contentieedgechrome1i also tried to work with the following code snippet to no avail style mozviewport width devicewidth initialscale 1 stylemaybe someone knows a simple solution to this i would be so grateful for any kind of help advice or hint on how to tackle the problem thank you very much in advancecheers merlin,['android'] +460323,heroku rails 4 could not connect to server connection refused using postgreshave not been able to pushtried this without any luckconfigassetsinitialize on precompile false preparing app for rails asset pipeline running rake assetsprecompile rake aborted could not connect to server connection refused is the server running on host 127001 and accepting tcpip connections on port 5432,['ruby'] +460362,how did i get a value larger than 8 bits in size from an 8bit integer i tracked down an extremely nasty bug hiding behind this little gem i am aware that per the c spec signed overflows are undefined behavior but only when the overflow occurs when the value is extended to bitwidth sizeofint as i understand it incrementing a char should not ever be undefined behavior as long as sizeofchar sizeofint but that does not explain how c is getting an impossible value as an 8bit integer how can c hold values greater than its bitwidthcode compiled with gcc472include cstdioinclude stdinthinclude climitsint main int8 t c 0 printfschar min in schar min printfschar max in schar max for int32 t i 0 i 300 i printfc in c printfc in c return 0outputschar min 128schar max 127c 0c 1c 2c 3c 127c 128 the next value should still be an 8bit valuec 129 what that is more than 8 bitsc 130 uhc 131c 297c 298 getting ridiculous nowc 299c 300c 45 check it out on ideone,['c++'] +460397,return css height with jquery not computed but declared i think this might have been the default in a previous version of jquery but when i call cssheight and height it returns the computed height which is not what i want i only want a height value if it is specifically declared in a css file for that elementlike if it is not declared anywhere perhaps it could return auto like it does for top and left sometimesfor example my css looks like thiselement marginleft5px colorredcssmarginleft returns 5px while cssheight returns 20 even though it is not specifically setthanks,"['jquery', 'html', 'css']" +460406,what is the default location for boost library when installed using macport on mac i just now installed boost on mac using macport with following commandsudo port install boostit is installed fine but i have no idea where the boost library got installed towhere should it be how could i search for it,['c++'] +460414,jsch how to keep the session alive and up i am writing java gui program for static route management using ssh my code is as followsimport comjcraftjschimport javaiopublic class konsep string status static string username static string hostname string inputcommand string output static session session jsch jsch new jsch public string statusstring stringstatus stringstatus status return stringstatus public string inputcommandstring inputcommandstatus inputcommandstatus inputcommand return inputcommandstatus public void connectstring usernamelokal string hostnamelokal string password int port jsch jschnew jsch try session sessionlokal jschgetsessionusernamelokal hostnamelokal port sessionlokalsetpasswordpassword userinfo ui new userinfokuinfoku sessionlokalsetuserinfoui sessionlokalsettimeout0 sessionlokalconnect status tersambung n username usernamelokal hostname hostnamelokal session sessionlokal systemoutprintlnusername hostname catch exception e systemoutprintlne status exception and e n public void thisconnect jsch jschnew jsch try session sessionlokal jschgetsessionusername hostname systemoutprintlnusername hostname sessionlokalthisconnect status wes pedhoott n catch exception e systemoutprintlne status exception and e n public void addroute jsch jschnew jsch systemoutprintlnusername hostname try session sessionlokal session jschgetsessionusername hostname channel channel sessionlokalopenchannelexec channelexec channelsetcommandinputcommand channelsetinputstreamnull channelconnect channelexec channelseterrstreamsystemerr inputstream in channelgetinputstream channelconnect byte tmp new byte1024 while true while inavailable 0 int i inreadtmp 0 1024 if i 0 break systemoutprintnew stringtmp 0 i if channelisclosed systemoutprintlnexitstatus channelgetexitstatus break try threadsleep10 catch exception ee channelthisconnect catch exception e systemoutprintlne the problem is when i call the connect method and then calling the addroute the program returns root 192168502root 192168502comjcraftjschjschexception session is downi have been trying to get session status with eithersession sessionlokalsession returns comjcraftjschjschexception channelexecor session sessionlokaljschgetsessionusername hostname returns session is downi have also tried to use keepalive but its not working eithermy intention is to create a session to host log in while leaving the session up execute a command or commands and maybe executing other commands later and then closing the session when its not needed log out i have been searching on this forum and i found this question but the code is create a method to define a command to execute first and then creating the session call the commands method and close the sessionany ideas about how to do as i mentioned above,['java'] +460493,aspnet mvc 4 web api controller dosnt work with unitywebapi my aspnet mvc 4 web api controller dosnt work with unitywebapi in the same project simple controllers works with unitymvc3 properly but when i run web api controller derived from apicontroller i am getting a messageid1messagean error has occurredexceptionmessagetype electrictestscontrollersapidocumentscontroller does not have a default constructorexceptiontypesystemargumentexceptionstacktrace at systemlinqexpressionsexpressionnewtype typern at systemwebhttpinternaltypeactivatorcreatetbasetype instancetypern at systemwebhttpthispatcherdefaulthttpcontrolleractivatorgetinstanceoractivatorhttprequestmessage request type controllertype func1 activatorrn at systemwebhttpthispatcherdefaulthttpcontrolleractivatorcreatehttprequestmessage request httpcontrollerdescriptor controllerdescriptor type controllertypemy apicontrollerpublic class documentscontroller apicontroller private readonly idocumentsrepository repository public documentscontrolleridocumentsrepository repository repository repository public ienumerableformatteddocument getformatteddocuments return repositorygetallformatteddocuments bootstrappercspublic static class bootstrapper public static void initialise iunitycontainer container buildunitycontainer dependencyresolversetresolvernew unitydependencyresolvercontainer private static iunitycontainer buildunitycontainer var container new unitycontainer register all your components with the container here it is not necessary to register your controllers eg containerregistertypeitestservice testservice containerregistertypeidocumentsrepository documentsrepository containerregistertypeiquestionsrepository questionsrepository containerregistertypeitestrepository testsrepository return container where is my mistake,"['c#', 'asp.net']" +460512,is the tag a regular tag that is not thisplayed by default i noticed when looking at a webpage in chrome that the head tag had the css thisplay none assignedthis got me thinking is the head tag just a regular tag that browsers decide not to thisplayeven though this would have no obvious use could i instead use a cheese tag in the place of the head tag and use the css cheese thisplay none to achieve the same function as a head tag,['html'] +460517,facebook url scheme does not work fbpublish i just realized that the facebook uri scheme publish function does not work anymore it opens the facebook app but nothing more is there any way to publish something via an uri schemeyou can find my code belownsstring post nsstring stringwithformatfbpublishprofilemetextfoo uiapplication sharedapplication openurlnsurl urlwithstringpost,"['android', 'iphone', 'ios']" +460611,why does watchservice generate so many operations import javaioimport javaniofilepublic class tmp public static void mainstring args throws ioexception int count 0 path path pathsgetctmp watchservice ws null try ws filesystemsgetdefaultnewwatchservice pathregisterws standardwatcheventkindsentry create standardwatcheventkindsentry delete standardwatcheventkindsentry modify standardwatcheventkindsoverflow catch ioexception ioe ioeprintstacktrace whiletrue watchkey key null try key wstake catchinterruptedexception ie ieprintstacktrace forwatchevent event keypollevents switcheventkindname case overflow systemoutprintlncount overflow break case entry modify systemoutprintlncount file eventcontext is changed break case entry create systemoutprintlncount file eventcontext is created break case entry delete systemoutprintlncount file eventcontext is deleted break default systemoutprintlncount unknown event keyreset when i run this and then opened the notepad and then created a new empty file and saved it as atxt in the ctmp directory i got the output1 file atxt is created2 file atxt is deleted3 file atxt is createdwhy is that it looks like the file was created and then deleted and then created again whywhen i put some text in the file and saved it the output was4 file atxt is changed5 file atxt is changedwhy did it change twice,['java'] +460665,how to escape a single quote in javascript okay i am basically doing thisdocumentgetelementbyidsomethinginnerhtml img srcsomething onmouseoverchangeex1 i do not want double quotes where i put the i only want a single quote so i am trying to not make it put a double when it is used i am trying to reach this in the final outcomeimg srcsomething onmouseoverchangeex1 escaping is not working for me,"['javascript', 'html']" +460702,how to send eof via windows terminal i am trying to comprehend example 19 from the kr book but i do not get how to send eof some sources mentioned ctrz but that simply terminates the program i somehow managed to send eof with a combination of enter and ctrlz and maybe ctrlv but i cannot reproduce itinclude stdiohdefine maxline 10main int len int max char linemaxline char savemaxline max 0 whilelen getline myline maxline 0 iflen max max len copyline save ifmax 0 printfs savegetline mys limchar sint lim int c i fori0 i lim1 c getchar eof c n i as long as the condition is fulfilled si c if c n si c i si 0 returnicopys1 s2char s1char s2 int i i 0 whiles2i s1i 0 i,['c'] +460729,afnetworking setauthenticationchallengeblock my server requires a client certifiacte after some time searching and reading examples in afnetworking docs i tried to set setauthenticationchallengeblock and provide a client certificatein browser provided certifacete works finerequestoperation setauthenticationchallengeblocknsurlconnection connection nsurlauthenticationchallenge challenge nslogauthenticationchallenge nsstring thepath nsbundle mainbundle pathforresourceclient oftypepfx nsdata pkcs12data nsdata alloc initwithcontentsoffilethepath cfdataref inpkcs12data bridge cfdatarefpkcs12data secidentityref identity self extractidentityinpkcs12data identity seccertificateref certificate null secidentitycopycertificate identity certificate const void certs certificate cfarrayref certarray cfarraycreatekcfallocatordefault certs 1 null nsurlcredential credential nsurlcredential credentialwithidentityidentity certificates bridge nsarraycertarray persistencensurlcredentialpersistencepermanent challengesender usecredentialcredential forauthenticationchallengechallenge requestoperation startbut the code inside block is never being called and server returns 403 error as expectedthe code in other blocks such as setuploadblock etc works fineany idea where is my mistake,['ios'] +460741,launchyapplicationnotfounderror trying to get save and open page to work at all gives me the following error1 index page my first test failureerror save and open page launchyapplicationnotfounderror no application found to handle csitessublist v2tmpcapybaracapybara201304211638563116158687html specfeaturescomics page specrb6in block 2 levels in top requiredspecrequire spec helperfeature index page do scenario my first test do visit root path save and open page launchyopen endendif i uncomment the launchy line it works fine so i am not sure what the trouble is maybe a problem with the path cgemfilegroup development test do gem sporkrails gem rspecrails gem factory girl railsendgroup test do gem faker gem capybara gem launchy gem database cleaner gem shouldamatchersend,['ruby-on-rails'] +460763,laravel 4 testing phpunit is not recognized says after installing a new laravel application simply run phpunit on the command line to run your testsphpunit is not recognized i also tried php artisian test and php artisan phpunitis phpunit in some weird folder or is it actually not included with laravel i do not want to install it and have two if it is,['php'] +460764,correct way to generate random numbers in cython what is the most efficient and portable way to generate a random random in 01 in cython one approach is to use int max and rand from the c libraryfrom libcstdlib cimport randcdef extern from limitsh int int maxcdef float randnum rand floatint maxis it ok to use int max in this way i noticed that it is quite different from the constant you get from pythons max intimport sysprint int maxprint sysmaxint yields2147483647 c max int9223372036854775807 python max intwhich is the right normalization number for rand edit additionally how can the random seed be set eg seeded based on current time if one uses the c approach of calling rand from libc,['python'] +460767,dompdf with css float i am not sure why but the html page thisplays just fine but the dompdf does not utilize the floatscode is 2300 line long so to long to post here but it is all inline cssdiv stylefloatleft divi have tried both wrapping the css in a style tag and inline with no luckthis is the html page reportsdaily vehicle check sheetphpid5this is the dompdf link reportsform daily vehicle checkphpid5i am not sure why but the html page thisplays just fine but the dompdf does not utilize the floatscode is 2300 line long so to long to post here but it is all inline css,"['php', 'html']" +460823,angularjs basic example to use authentication in single page application i am new to angularjs and gone through their tutorial and got a feel for iti have a backend for my project ready where each of the rest endpoints needs to be authenticatedwhat i want to doa i want to have a single page for my project b once a user hits the url in browser based on if user is logged in or not he is presented with a home pageview or login pageview under the same url c if a user is not logged in it fills out the form and server sets a user token in session so all further requests to endpoints will be authenticated based on user token my confusionsa how can i handle clientside authentication using angularjs i saw here and here but did not understand how to use themb how can i present different views to user based on if user is logged in or not under same url i am using angularjs for the very first time and really getting confused as to how to start any advices andor resources are very much appreciated,['javascript'] +460824,should i explicitely scope variables this is more of a style question because i am aware that in practice most compilers will probably optimize to give the same effect but i keep reading that in general you should always declaredefine variables in the scope that they are used so in situations where i cannot inline the declaration such as the following snippet i have thought about enclosing the index variables in scoping brackets curly brackets not sure what you call them in this case in order to explicitely limit the scope of those variables is this good practice if so can you please explain why size t i 0 this variable has no use outside of the rangebased for loop for auto const input input vector neuron sequenceiforcesignalinput i,['c++'] +460837,why does a virtualenv environment contain argparse thistribute and wsgiref i am using virtualenv version 1712 with python 273 to create virtual python ennvironments but when i create such an environment and activate it i can see the following packages are installed using pip freezeargparse121thistribute0624wsgiref012why is that what does that mean,['python'] +460909,what does this parameter type constraint mean i am looking at some code and i do not understand what a particular constraint means in the following class definitioninternal abstract class entityt entity where t entityt i do not understand what this implies about parameter type t,['c#'] +460938,drag and drop in tkinter what is the correctofficialproperrecommended way of accomplishing dragdrop in tkinter my documentation section 2411 includestkdnd draganddrop support for tkinter this is experimental and should become deprecated when it is replaced with the tk dndbut i can find no other official documentation does tkinter have dragdrop support at all is this something version dependant is this something not yet included in tktcl which will then filter through to tkinteri should stress that i am talking about dragdrop between different applications and that i am currently using python 2 although any solution which relies on python 3 would still be of interest,['python'] +460956,replace single backslash with double backslashes i have string with file path i want to replace all single backslashes with double backslashes var replaceablestring casdflkjklsdffjkl var part g var filepath replaceablestring replacepart consolelogfilepathconsole showed me it casdlkjklsdfjkli found something like this unfortunately it did not workreplacing with,['javascript'] +460965,executing a php script with a cron job i would like to run a php script every day at midnight after research on how to do this it appears that the best way to achieve this is to use a cron jobif my php script was located at can somebody be able to show the most simple example of what this cron command would look likei have looked through numerous posts but i cannot find a simple enough example for me to learn and build uponthanks in advancedan,['php'] +460968,find out where mysql is installed on mac os x how do i find out where mysql is installed on mac os x 1079 i have mamp installed so i presume that it is bundled with this install,['mysql'] +460970,debugging python with compiled extensions i use python with compiled cython and fortran extensions wrapped using modern fortrans iso c binding module and cython for number crunchingso far i do not have a convenient debugging strategy i use pudb for the python part although i might be able to use gdb on the cythonfortran parts of the project i find myself to be using console text output print insteadi would like to know if there are tools that make the different levels of code transparent for debugging ie i am looking for a onetooldebugsitall solution that does not care whether it steps python cython or fortran codei would prefer tools that allow userfriendly interaction such as the aforementioned pudb does such a jack of all trades debugging tool exist is the python mode of gdb the best i can get,['python'] +460998,how to use contain in list i have country database likes countryenglandgermanyitalyi get this data source as dbcountriestolistwhat i want to do is to check new added country is already exists or not just likes ifdbcountriestolistcontainsnewaddedcountry but i do not know how to convert newaddedcountrystring to systemcollectionsgenericlistcountry,"['c#', 'asp.net']" +461000,setting tempdata within a actionfilterattribute i have a custom action filter that inside the onactionexecuting depending on certain criteria logs out a user and redirects them to the home page of the site the stripped back code for the redirect part is below filtercontextcontrollertempdataaddkey message filtercontextresult new redirectresultas above i am also setting a tempdata message because the user has been logged out when they hit the home page the authorize attribute will redirect them to the login get page on the login view i am thisplaying any messages from within tempdata however in this situation the tempdata is empty this is very similar behavior to how my login post works if invalid it redirects to home which redirects to login and thisplays the tempdata message that was set in the login post this code can be seen below tempdataaddkey errormessage return redirectthe reason i am doing it this way rather than redirecting specifically to the login page is because this code is thistributed across many sites so we dont know what the login get url isdoes anyone have any information as why this is working for the login post but not for the actionfilter redirecteditif i remove the logout call within the custom action filter the tempdata is still set within the home action however this doesnt explain why it works for the login post but not the action filter,['c#'] +461065,how can i update a row in a javascript array based on a key value i have an array of data like thisvar nameinfo name moroni age 50 name tiancum age 43 name jacob age 27 name nephi age 29 name enos age 34if i have an object like thisvar nameinfo name moroni age 51is there a simple way that i can update the variable nameinfo the keybetween these is the name column i know there is a way that i could do this by searching for the row removing and adding but i would liketo have a way to do this where i updated the row note that if it helps i do have underscorejs loaded,['javascript'] +461070,how to map keys to values for an individual field in a mysql select query supposing we have a field status 0 for thisabled 1 for enabled and we need to get the literal values directly using mysql in other words if we requested the queryselect status from tablewe need the column to appear like this status thisabled enablednot as following status 0 1knowing that we do not have a mysql status table to join with and get the values as usual,"['mysql', 'sql']" +461078,assign variable value inside ifstatement i was wondering whether it is possible to assign a variable a value inside a conditional operator like soifint v somemethod 0 return vis there some way to do this in java because i know it is possible in while conditions but i am not sure if i am doing it wrong for the ifstatement or if it is just not possible,['java'] +461125,mylocation button of googlemaps v2 android not thisplayed i am doing an app with google maps but when i try to add mylocation button as the reference says does not workthats how i doprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main map supportmapfragment getsupportfragmentmanagerfindfragmentbyidridmapgetmap locmanager locationmanagergetsystemservicelocation service providerslist locmanagergetallproviders provider locmanagergetproviderproviderslistget0 precision providergetaccuracy req new criteria reqsetaccuracycriteriaaccuracy fine inside false mapgetuisettingssetmylocationbuttonenabledtrue buildpolygon drawpolygon startlocalization i used mapgetuisettingssetmylocationbuttonenabledtrue as shows in the reference of google i do not know whats going on,"['java', 'android']" +461164,c11 when clearing shared ptr should i use reset or set to nullptr i have a question about c11 best practices when clearing a shared ptr should i use the reset function with no parameter or should i set the shared ptr to nullptr for examplestdshared ptrstdstring foonew stdstringfoofooresetfoo nullptris there any real difference or are there advantagesthisadvantages to either approach,['c++'] +461201,using directive vs using declaration swap in c please refer to the code belowinclude algorithmnamespace n template typename t class c public void swapwithc c using namespace std 1 using stdswap 2 swapa ca private int a template typename t void swapct c1 ct c2 c1swapwithc2 namespace std templatetypename t void swapnct c1 nct c2 c1swapwithc2 as written above the code does not compile on visual studio 20082010 the error isvoid nswapnct nct could not deduce template argument for nct from inthowever if i comment out 1 and uncomment 2 it will compile ok what is the difference between using namespace std and using stdswap that explains this behavior,['c++'] +461228,conditional replacement in pandas i have a dataframe spanning several years and at some point they changed the codes for ethnicity so i need to recode the values conditional on the year which is another column in the same dataframe for instance 1 to 3 2 to 3 3 to 4 and so on old 1 2 3 4 5 91new 3 3 4 2 1 6and this is only done for the years 1996 to 2001 the values for the other years in the same column ethnicity must not be changed hoping to avoid too many inefficient loops i tried recode years range19962002 for year in recode years dfethnicitydfyearyearreplaceold new inplacetruebut the original values in the dataframe did not change the replace method itself replaced and returned the new values correctly but the inplace option seems not to affect the original dataframe when applying a conditional this may be obvious to experienced pandas users but surely there must be some simple way of doing this instead of looping over every singel elementedit x2 her is an an example of another approach which also did not work length of replacements must equal series length and typeerror array cannot be safely cast to required type oldnewmap 12 23df2 dataframeyear202020200120012001ethnicity121231df2ethnicitydf2year20 df2ethnicitydf2year20mapoldnewmapedit it seems to be a problems specific to the installationversion since this works fine on my other computer,['python'] +461241,php aws sdk throwing unknown error i have been working with amazon s3 for media storage for a ecommerce site but i ran into this error and have no idea how to fix ituse of undefined constant curle couldnt resolve host assumed curle couldnt resolve hostits coming from curlbackoffstrategy witch is as the documentation statesstrategy used to retry when certain curl error codes are encounteredi am assuming this is software incompatibility some were but i am no sure where to lookthis code dose work on my local test environment but when the server gets it it just failsi have updated php and curl to the same as my test environment but to no availif anyone has any idea on what this error message means or a direction to point me in would be greatly appreciated,['php'] +461248,cygwin g linker does not find shared library i have been creating a library when i compile it as a static library it works fine now i wanted to turn it into a shared library the library is created and in the proper place but when i try to compile the client code the linking phase says that it cantt find the libraryi already tried to rename it to al or dylib but that does not help either when i put the v flag on the linking i can see that my library path is there i also tried different paths i use a relative path but also with a full path it does not find itthe makefile form the librarysuffixessuffixes o cppsuffixes o dcc glnk gcxxflags release fpic shared o2 wall fmessagelength0cxxflags debug fpic shared g wall fmessagelength0 d debugcxxflags cxxflags debugobjdir objsrcdir srchdir includeinclude paths iinclude iincludeinterfaces iincludesupportcpp files propertyfilepropertyfilecpp propertyfilepropertyitemcpp propertyfilepropertyfactorycpp helperstring helpercppobj patsubst cppobjdiro cpp filessrc patsubst cppsrcdiro cpp fileslibs target libsupportsoall targettarget obj lnk o target obj shared cp target lib cp r include clean rm f obj asm targetinclude patsubst cppobjdird cpp filesobjdiro srcdircpp objdird mkdir p dirname cc cxxflags c o include pathsobjdird srcdircpp mkdir p dirname cc cxxflags mm mt mf objdird c include pathsand here ist the makefile for the applicationsuffixessuffixes o cppcc gld gcxxflags release o2 wall fmessagelength0cxxflags debug g wall fmessagelength0 d debugcxxflags cxxflags debugobjdir objsrcdir srcinclude paths iinclude iincludelibs l cygdrivedsrcclib lsupportcpp files nohupshdcpp daemoncpp taskcppobj patsubst cppobjdiro cpp filessrc patsubst cppsrcdiro cpp filestarget nohupshdall targettarget obj ld o target obj libsclean rm f obj asm targetinclude patsubst cppobjdird cpp filesobjdiro srcdircpp objdird mkdir p dirname cc cxxflags c o include pathsobjdird srcdircpp mkdir p dirname cc cxxflags mm mt mf objdird c include paths,['c++'] +461259,getting illegal use of explicit template arguments when doing a pointer partial specialization for a class method hello i am having problems with partial specialization what i want to do is have a class that has a template member function that will interpret a given value to one specified by the user for instance the class name is value and here is a snippet of what i want to doint ptr1 new intptr1 10value val1 ptr1int ptr2 val1getvalueintvalue val2 1int testval val2getvalueinthere is how i implemented such clastruct value valuevoid p val1p valueint i val2i templatetypename t t getvalue void val1 int val2templatetypename tt valuegetvaluet return reinterpret casttval1templateint valuegetvalueint return val2when i compile i am getting the following errorerror c2768 valuegetvalue illegal use of explicit template argumentsbasically its complaining about the pointer template part of the codetemplatetypename tt valuegetvaluet return reinterpret casttval1i know this problem can be implemented with a simple union but this code is a stripped down version of a bigger codedoes someone know what the problem could be what i would like to do is separate one code for when using pointers and other for when not using pointers i am really stuck and i always investigate instead of asking but i have not found any good info about it,['c++'] +461263,storage size of sockaddr in variable is not known i have a piece of code that used to work in some environment a long time ago i am pretty sure it was a freebsd machine so i got freebsd 83 and i am trying to make this file but it is not working when i try to compile it it complains with fc in function tcpfc24 error storage size of socket stru is not knownfc29 error ipproto tcp undeclared first use in this functioni have been looking around and i see these are all specified in the syssocketh file this is my actual fileinclude stdiohinclude stringhinclude netdbhinclude syssockethinclude unistdhinclude fhint tcp4 in addr t ip int port int qsize struct sockaddr in socket stru line 24 socket strusin family af inet socket strusin port htonsport socket strusin addrs addr ip int actual socket socketpf inet sock stream ipproto tcp line 29i feel like my code somehow does not read the syssocketh file so it does not know about socket stru and ipproto tcp but i am just really lost any ideas,['c'] +461305,type mismatch cannot convert from stringbuilder to string this method returns the source of the given url private static string geturlsourcestring url try url localurl null localurl new urlurl urlconnection conn localurlopenconnection bufferedreader reader new bufferedreader new inputstreamreaderconngetinputstream string line string html stringbuilder ma new stringbuilder while line readerreadline null maappendline return ma catch exception e logeerregetmessage it gives me this errortype mismatch cannot convert from stringbuilder to stringand two choiceschange the return type to stringbuilderbut i want it to return a stringchange type of ma to stringafter changing a string has no append method,"['java', 'android']" +461315,why is my program so slow someone decided to do a quick test to see how native client compared to javascript in terms of speed they did that by running 10 0 0 sqrt calculations and measuring the time it took the result with javascript 0096 seconds and with nacl 4241 seconds how can that be is not speed one of the reasons to use nacl in the first place or am i missing some compiler flags or somethingheres the code that was runclock t t clockfloat result 0forint i 0 i 10 i result sqrtit clock t float tt floattclocks per secppvar var reply ppvarttpostmessagevar replyps this question is an edited version of something that appeared in the native client mailing list,['c++'] +461333,sqlalchemy init not running i have the following code session scoped sessionsessionmakerautocommitfalse autoflushtrue bindenginebase declarative basebasequery sessionquery propertyclass commonbaseobject created at columndatetime defaultdatetimedatetimenow updated at columndatetime defaultdatetimedatetimenow onupdatedatetimedatetimenowclass lookbase commonbase tablename looks id columninteger primary keytrue def init self print init is run base init self selffeedback none def set feedbackself feedback status can either be 1 for liked 0 no response or 1 thisliked assert feedback in 1 0 1 selffeedback feedback def get feedbackself return selffeedbackand i am getting the following error traceback most recent call last file volumesdata2dropboxprojectsgiordanovenvlibpython27sitepackagesflaskapy line 1701 in call return selfwsgi appenviron start response file volumesdata2dropboxprojectsgiordanovenvlibpython27sitepackagesflaskapy line 1689 in wsgi app response selfmake responseselfhandle exceptione file volumesdata2dropboxprojectsgiordanovenvlibpython27sitepackagesflaskapy line 1687 in wsgi app response selffull thispatch request file volumesdata2dropboxprojectsgiordanovenvlibpython27sitepackagesflaskapy line 1360 in full thispatch request rv selfhandle user exceptione file volumesdata2dropboxprojectsgiordanovenvlibpython27sitepackagesflaskapy line 1358 in full thispatch request rv selfthispatch request file volumesdata2dropboxprojectsgiordanovenvlibpython27sitepackagesflaskapy line 1344 in thispatch request return selfview functionsruleendpointreqview args file volumesdata2dropboxprojectsgiordanosrcgiordanowebbackendpy line 94 in wrapped ret fargs kwargs file volumesdata2dropboxprojectsgiordanosrcgiordanowebbackendpy line 81 in decorated return fargs kwargs file volumesdata2dropboxprojectsgiordanosrcgiordanowebbackendpy line 187 in next json ret geencoderesults automatically pulls the tags file systemlibraryframeworkspythonframeworkversions27libpython27jsonencoderpy line 201 in encode chunks selfiterencodeo one shottrue file systemlibraryframeworkspythonframeworkversions27libpython27jsonencoderpy line 264 in iterencode return iterencodeo 0 file volumesdata2dropboxprojectsgiordanosrcgiordano init py line 54 in default jsonable selfconvert to jsonableobj file volumesdata2dropboxprojectsgiordanosrcgiordano init py line 40 in convert to jsonable image urlobjimage url feedbackobjget feedback file volumesdata2dropboxprojectsgiordanosrcgiordanomodelspy line 100 in get feedback return selffeedbackattributeerror look object has no attribute feedbackit seems to me that my init method is not run as i cannot see any print statements in my log can someone explain why my init is not run and what can i do for this,['python'] +461381,scrollview is showing only the last added subview i am getting strange behavior with uiscrollview subviews the idea is to create programmatically an instance of uiview with a customized nib file which is a form in my case fill that form with data from a model class and add it as subview for my uiscrollview the problem is when i deal with more than one subview the uiscrollview only keep the latest subview so if i created three subviews the scrollview will show only the third the latest subview although the page control is set to the coreect number of subviews threethe project is too long so i will try to explain brievely my issue with the relevant code voidviewdidload nsarray sorted apparray sortedarrayusingdescriptorsnsarray arraywithobjectsortdescriptorthis array contains the data from model i debugged that to make sure i got the exact data no more no less loop all nsmanaged objects for example let us say i have 3 model objects do not worry about how i get data etc because i debugged all and maked sure all data objects number are exact etc for app table apptable in sorted this looped 3 times as expected i debugged that also and maked sure on each iteration i got the data i expected to have app table is a subclass of nsmanagedobject it is my model class and get its data from coredata file self addmoreviewcall this method will create a new subview and add it as subview to the uiscrollview it will also update the page control update the content size property etc apptableview apptableview apptableview selfscrollview subviews lastobjectremember addmoreview method create a new instance of apptableview and add it as subview for the uiscrollview property then i get that subview to fill it with data here apptableviewtxtaddresstext apptableaddressfill in the form no need to write all the form fields code because it is the same way scroll to first page selfpagecontrolcurrentpage 0 selfscrollview scrollrecttovisiblecgrectmake0 0 viewwidth viewheight animatedyes selfscrollviewcontentsize cgsizemakeviewwidthnoofitems viewheightset the content size to the sum of subviews width i also debugged that to check it is correct selfscrollviewdelegate self super viewdidloadok so when i have three subviews the scrollview will load with the width of three subviews as calculated with the line aboveselfscrollviewcontentsize cgsizemakeviewwidthnoofitems viewheightset the content size to the sum of subviews width i also debugged that to check it is correctand i can scroll till 3 moves which is the number of subviews and the uipagecontrol is also set to three dots but only one subview is visible only the latest one i can see the two other subviews thisappeared the scroll view calculated content size for them but they are not visible any thoughts thanxeditit is worth to note that the first time i edit the view all goes fine when i deal with 3 subviews they are all visible but when i go to another view and get back to this view only the last subview is visiblealso i am working on an ipad project for that with a split vieweditthis is the code of the method which draw new subview for the uiscrollview ibaction addmoreview nsarray arr nsbundle mainbundle loadnibnamedapptableview ownerself optionsnil apptableview aview arr objectatindex0 aview setframecgrectmakestartx 0 aviewboundssizewidth aviewboundssizeheight selfscrollview addsubviewaview selfscrollviewcontentsize cgsizemakeselfscrollviewcontentsizewidthaviewframesizewidth selfscrollviewcontentsizeheight startx startx aviewframesizewidthupdate the x position first 0 then 600 1200 and so on selfscrollview scrollrecttovisibleaviewframe animatedyes nslogfselfscrollviewcontentsizewidth nslogfselfscrollviewcontentsizeheight suppose i have 3 subviews the method above will be called 3 times since it is put inside the for loop so here is the result of nslogs for the above methodnslogfselfscrollviewcontentsizewidthnslogfselfscrollviewcontentsizeheight first iteration 60 0 second iteration 120 0 third iteration 180 0editthe command suggested by rob mayoff allows me to see why this happen apptableview 0x1eef4700 frame 0 18 600 430 autoresize lmrmtmbm tag 990 layer calayer 0x1eef4790 apptableview 0x1ee3f380 frame 0 18 600 430 autoresize lmrmtmbm tag 991 layer calayer 0x1ee3f410 apptableview 0x1ee56910 frame 0 18 600 430 autoresize lmrmtmbm tag 992 layer calayer 0x1ee3f410all three subviews are drawn in the same frame so they are above each other but when i debug that with breakpoints in runtime the x is changing first time 0 then 600 then 1200 which make me think it is drawing correctly how to fix that especially that the x value is being incremented correctly so whats the problem and why they still drawing on the same x coordinate,"['ios', 'objective-c']" +461424,ruby hash default value behavior i am going through ruby koans and i hit 41 which i believe is thisdef test default value is the same object hash hashnew hashone uno hashtwo dos assert equal unodos hashone assert equal unodos hashtwo assert equal unodos hashthree assert equal true hashoneobject id hashtwoobject idendit could not understand the behavior so i googled it and found strange ruby behavior when using hash default value eg hashnew that answered the question nicelyso i understand how that works my question is why does a default value such as an integer that gets incremented not get changed during use for exampleputs text please text getschompwords textsplit frequencies hashnew0wordseach word frequenciesword 1 this will take user input and count the number of times each word is used it works because the default value of 0 is always usedi have a feeling it has to do with the operator but i would love an explanation,['ruby'] +461606,how to write visitor pattern for a abstract syntax tree in c i have to write a visitor pattern to navigate the ast can anyone tell me more how would i start writing itas far as i understand each node in ast would have visit method that would somehow get called from where that about concludes my understandingto simplify everything suppose i have nodes root expression number op and the tree looks like this root op number5 op number2 number4,['c#'] +461627,refresh datgui with new values i would like to refresh the datgui menu with new values i have loaded a model and thisplay in folder the name of the objects inside a gui folderhow can i thisplay the new object name when i reload a other model or it is possible to resetclear the gui,['javascript'] +461694,how to use snmp with java i am writing an application that accesses a network printer as a part of that application i need to know the status of the printer the only way the printer advertises its status is through snmp java itself does not have any tools that speak the snmp protocol so i am not sure what to do how can i access the printers snmp status updates from a java application,['java'] +461726,keyboard accessibility of hidden contents using css and html only how can i make this snippet accessiblediv tabindex0 show more ul lia hrefhidden contentali lia hrefhidden contentali lia hrefhidden contentali uldivcssdiv ul thisplaynonedivhover ul divfocus ul thisplayblocki wonder if it is possible to make ul visible also with keyboard navigationwhile focusing its contents,"['html', 'css']" +461768,jquery to loop through table rows and cells where checkob is checked concatenate i have a table with multiple rows there are several columns in the table with checkboxes i need to loop through each of the checkboxes where it is checked concatenatejoin the input from that particular cell to other inputs from the same rowyou can see a fiddle herehow can i in addition to looping through the row loop through each td once i have this td how can i look for an input whose name starts with x in that td once found concatenate join the input from that to the inputs in the rowi hope that makes senseessentiallyi want to join the family to the size to the grade where family and grade are on the same row and there are several sizes on each row each result must be written to the td currently being processedi have got up to this point but have got stuckfunction createcodes alertrunning run through each row authorslist treachfunction processing this row how to process each celltable td where there is checkbox thisfindinputnamelineval thisfindinputnamefamilyval common inputfamily on row use for all table cellstd thisfindinputnamesizeval this cells input called size unique to this cell only thisfindinputnamegradeval common inputgrade on row use for all table cellstd end of cell row processing end of rows processingthanks as always my html istable classauthorslist border1 idordertable tr td input typetext idproduct1 nameproduct1 classrounded value38114crtd td input typetext size5 idqty1 nameqty1 classrounded value10td td classtdcheckbox input typecheckbox idh09 1 nameh09 1 checked classrounded input typetext idline 1 09 nameline 1 09 input typetext idsize 1 09 namesize 1 09 value09 td td classtdcheckbox input typecheckbox idh12 1 nameh12 1 classrounded input typetext idline 1 12 nameline 1 12 value input typetext idsize 1 12 namesize 1 12 value12 td td classtdcheckbox input typecheckbox idh15 1 nameh15 1 checked classrounded input typetext idline 1 15 nameline 1 15 input typetext idsize 1 15 namesize 1 15 value15 td tdinput typetext namecubespercheck 1 idcubespercheck 1 value0 size5td tdinput typetext nameskufamily 1 idskufamily 1 value38114td tdinput typetext nameskugrade 1 idskugrade 1 valuecrtd trtableinput typebutton idcontinue valuecontinuekeep in mind there are multiple rows thanks,['jquery'] +461853,confusion on call java interface method let us say i have an interface a define as belowpublic interface a public ait include a method called ai have a class implement this interface let us say public class aimpl implements a public void a printlndo something this class only implement this methodshere is my question so if in the main class i call interface method will it call the method in the class which implement the interface for examplepublic static void mainstring args a aa awill it call the method in the class aimpl and output do something,['java'] +461899,why does contains compare objects differently than object t 4object s 4if t s falselistobject q new listobject t boolean found qcontainss found truein the above code i am not surprised by t s returning false it is comparing references to two objects and the references are not the samebut i am surprised the the contains is returning true obviously it is not just comparing object referencesit is like it is comparing the unboxed values of 4 and 4but how and why does it know to unbox the objects to compare them i am trying to understand the bigger pricniple at play here,"['c#', '.net']" +461922,proper repository pattern design in php preface i am attemping to use the repository pattern in a mvc architecture with relational databasesi have recently started learning tdd in php and i am realizing that my database is coupled much too closely with the rest of my application i have read about repositories and using an ioc container to inject it into my controllers very cool stuff but now have some practical questions about repository design consider the follow examplephpclass dbuserrepository implements userrepositoryinterface protected db public function constructdb thisdb db public function findall public function findbyidid public function findbynamename public function createuser public function removeuser public function updateuser issue 1 too many fieldsall of these find methods use a select all fields select approach however in my apps i am always trying to limit the number of fields i get as this often adds overhead and slows things down for those using this pattern how do you deal with thisissue 2 too many methodswhile this class looks nice right now i know that in a real world app i need a lot more methods for examplefindallbynameandstatusfindallincountryfindallwithemailaddresetfindallbyageandgenderfindallbyageandgenderorderbyageetcas you can see there could be very very long list of possible methods and then if you add in the field selection issue above the problem worsens in the past i would normally just put all this logic right in my controllerphpclass mycontroller public function users users userselectname email statusbycountrycanadaorderbynamerows return viewmakeusers arrayusers users with my repository approach i do not want to end up with thisphpclass mycontroller public function users users thisrepoget first name last name email username status by country order by namecanada return viewmakeusers arrayusers users issue 3 impossible to match an interfacei see the benefit in using interfaces for repositories so i can swap out my implementation for testing purposes or other my understanding of interfaces is that they define a contract that an implementation must follow this is great until you start adding additional methods to your repositories like findallincountry now i need to update my interface to also have this method otherwise other implementations may not have it and that could break my application by this feels insanea case of the tail wagging the dogspecification patternthis leads me to believe that repository should only have a fixed number of methods like save remove find findall etc but then how do i run specific lookups i have heard of the specification pattern but it seems to me that this only reduces an entire set of records via issatisfiedby which clearly has major performance issues if youre pulling from a databasehelpclearly i need to rethink things a little when working with repositories can anyone enlighten on how this is best handled,['php'] +461971,parameterized queries with rodbc i have a variable in r that i would like to pass to a database i could use paste like many suggest when reading google results but that is unsafe because of sql injection vulnerabilities i would rather prefer something like thisx 42sqlquerydb select id name from people where age bindcxis it possible to use parameterized queries with rodbc if not is there an alternative library that supports themi am using sql server rodbc 136 and r 300,['sql'] +462000,how to control power button press shutdown i am working on a kiosk style application where i need to control the shutdownrestart of the pc when the power button is pressed thanks to this post i am about 90 of the way therein control panel set the acpi power button press action to shutdownlisten for the wndproc message wm queryendsessionwhen received issue the completely undocumenteddllimportuser32dll setlasterror truestatic extern int cancelshutdownreturn from the wndproc and bring up my own message box asking the user to shutdown restart or cancel and respond to their actioneverything works well if i do a start shutdown from the task bar i can issue theses as fast as i want everything also works well the first time i press the power button on subsequent power button presses though i see a minute or so delay before i receive the wm queryendsession messageis there a setting or registry entry about how often windows will issue an acpi event i know it is not the hardware because under linux the same machine will fire the acpi event as fast as i can press the buttonthanks,['c#'] +462056,jquery programtically select value odd issue i have got an interesting issue occurring which i cannot seem to resolve using select2 and fullcalendarupon clicking an event i am trying to preselect the select2 dropdown with whats in the database calendarfullcalendar eventclick functioncalevent jsevent view view eventmodal launches bootstrap modal client list editselect2 client list editselect2val caleventclientid heres what i cannot figure out when i eventclick the first time it does not prepopulate with the information however when i eventclick a second time or eventclick any other event on the calendar for that matter it works properly selects and thisplays the proper value any ideas on this one,"['javascript', 'jquery']" +462059,custom android image crop i just want to share this piece of code that i wrote i tried searching for a custom crop activity but most of them leads to the default comandroidcameraactioncrop despite the question custom crop or freehand crop activity anyway i just made one for myself and hopefully it will help you guyspublic class cropview extends imageview paint paint new paint private int initial size 300 private static point lefttop rightbottom center previous private static final int drag 0 private static final int left 1 private static final int top 2 private static final int right 3 private static final int bottom 4 private int imagescaledwidthimagescaledheight adding parent class constructors public cropviewcontext context supercontext initcropview public cropviewcontext context attributeset attrs supercontext attrs 0 initcropview public cropviewcontext context attributeset attrs int defstyle supercontext attrs defstyle initcropview override protected void ondrawcanvas canvas superondrawcanvas iflefttopequals0 0 resetpoints canvasdrawrectlefttopx lefttopy rightbottomx rightbottomy paint override public boolean ontoucheventmotionevent event int eventaction eventgetaction switch eventaction case motioneventaction down previoussetinteventgetx inteventgety break case motioneventaction move ifisactioninsiderectangleeventgetx eventgety adjustrectangleinteventgetx inteventgety invalidate redraw rectangle previoussetinteventgetx inteventgety break case motioneventaction up previous new point break return true private void initcropview paintsetcolorcoloryellow paintsetstylestylestroke paintsetstrokewidth5 lefttop new point rightbottom new point center new point previous new point public void resetpoints centersetgetwidth2 getheight2 lefttopsetgetwidthinitial size2getheightinitial size2 rightbottomsetlefttopxinitial size lefttopyinitial size private static boolean isactioninsiderectanglefloat x float y int buffer 10 return xlefttopxbufferxrightbottomxbuffer ylefttopybufferyrightbottomybuffertruefalse private boolean isinimagerangepointf point get image matrix values and place them in an array float f new float9 getimagematrixgetvaluesf calculate the scaled dimensions imagescaledwidth mathroundgetdrawablegetintrinsicwidth fmatrixmscale x imagescaledheight mathroundgetdrawablegetintrinsicheight fmatrixmscale y return pointxcenterximagescaledwidth2pointxcenterximagescaledwidth2pointycenteryimagescaledheight2pointycenteryimagescaledheight2truefalse private void adjustrectangleint x int y int movement switchgetaffectedsidexy case left movement xlefttopx ifisinimagerangenew pointflefttopxmovementlefttopymovement lefttopsetlefttopxmovementlefttopymovement break case top movement ylefttopy ifisinimagerangenew pointflefttopxmovementlefttopymovement lefttopsetlefttopxmovementlefttopymovement break case right movement xrightbottomx ifisinimagerangenew pointfrightbottomxmovementrightbottomymovement rightbottomsetrightbottomxmovementrightbottomymovement break case bottom movement yrightbottomy ifisinimagerangenew pointfrightbottomxmovementrightbottomymovement rightbottomsetrightbottomxmovementrightbottomymovement break case drag movement xpreviousx int movementy ypreviousy ifisinimagerangenew pointflefttopxmovementlefttopymovementy isinimagerangenew pointfrightbottomxmovementrightbottomymovementy lefttopsetlefttopxmovementlefttopymovementy rightbottomsetrightbottomxmovementrightbottomymovementy break private static int getaffectedsidefloat x float y int buffer 10 ifxlefttopxbufferxlefttopxbuffer return left else ifylefttopybufferylefttopybuffer return top else ifxrightbottomxbufferxrightbottomxbuffer return right else ifyrightbottomybufferyrightbottomybuffer return bottom else return drag public byte getcroppedimage bitmapdrawable drawable bitmapdrawablegetdrawable float x lefttopxcenterxdrawablegetbitmapgetwidth2 float y lefttopycenterydrawablegetbitmapgetheight2 bitmap cropped bitmapcreatebitmapdrawablegetbitmapintxintyintrightbottomxintlefttopxintrightbottomyintlefttopy bytearrayoutputstream stream new bytearrayoutputstream croppedcompressbitmapcompressformatpng 100 stream return streamtobytearray what i did was i extended the imageview and added cropping powers it is pretty easy to use once the class is saved just use it in the layout like this your package namecropview androidididimage preview androidlayout widthfill parent androidlayout heightmatch parent thats it hope it helps if you encounter any problem please feel free to ask,['android'] +462077,how to use max on a subquery result i am new to oracle and the sql world i have a slight issue with a query that i cannot figure out for the life of me i have spent a few hours trying different approaches and i cannot get the result i expect so heres my queryselect fromselect membershipmem descmembershipmem max rentalsmembership historymem type countmembership historymem type as membership count from membership history join membership on membershipmem type membership historymem type group by membership historymem typemembershipmem descmembershipmem max rentals gwhere gmembership count select maxmembership count from g so the inner query works perfectly and returns two results now that i have these two values i am trying to figure out how to return the row with the maximum value of membership count which is where i keep getting stuck in the above query i tried using the max in the where clause but inside that select i keep getting the error table not foundmeaning g so my question is how do i use the max function on the results of my subquery any thoughts or suggestions would be greatly appreciated,['sql'] +462099,oracle find the position of an error in dynamic sql using sql or plsql how can i find the position of an error in a dynamic sql statement in plsql or sqlfrom sqlplus i see the position of an error in for example an invalid sql dml statementsysorcl select 2 x 3 from 4 tablex 5 tablex error at line 4ora00942 table or view does not existsqlplus shows the error with the line number and prints and marks that line with an asterisk where the error is foundconverting to dynamic sql i can get the error code sqlcode and error message sqlerrmsysorcl set serveroutput onsysorcl begin 2 execute immediate select x from tablex 3 exception 4 when others then 5 dbms outputput linesqlcode sqlcode 6 dbms outputput linesqlerrm sqlerrm 7 end 8 sqlcode942sqlerrmora00942 table or view does not existbut how do i get the position of the error in the dynamic sql stringi see that oracle provides a sql communications area sqlca that contains interesting information about an error in particularthe sqlcode and sqlerrm fields that might be the source of the data retrieved with the respective plsql functionsthe sqlerrd field where the sqlerrd5 element that gives the parse error offset is it possible to access sqlerrd from plsql or sql if so how if not what other technique can give the location of the error from plsql or sqlhere 01appdev1b31231chapter8htmbabigbff the sqlca is documented and accessed with procthe answer here how to declare sqlcasqlerrd seems to indicate that sqlerrd is not defined in plsql and therefore not accessiblethe thiscussion here why doesnt oracle tell you which table or view does not exist gives some suggestions to show bad sql using trace files and to show the location of errors in some development tools,['sql'] +462112,arial font for text in android i want to show text in arial font but arial font is not available in android system fonts i do not want to use arial ttf file in my application is there any other way to apply text with arial font,['android'] +462178,html5 is not based on sgml so what is it based on then doctypeasphtml5 is not based on sgml and therefore does not require a reference to a dtdon what standard is html 5 based on if not on sgml,['html'] +462190,linking freeimage as a static library in vs2010 i need a image library and i have been looking into freeimage i want to link it statically with my applicationi have tried downloading the binaries and link it with but i get 2019 linker errors when i try to call their functions even though i am positive i linked it correctso then i tried to download their source converted their freeimagelib2008 to vs2010 and built it it builds just fine on its own but i still have the same problem when linking against it my application that uses it still complaints about linker errors i also set all the project configuration to match my other projects so there is no conflict with mdd or mtd etci did some digging in their source and there are macros like freeimage lib which suggests it should be defined when building a static library and it is defined yet still it dosnt worki have googled around and cannot find any solid answers to this issue the answer on getting freeimage to work with visual studio 2010 makes no difference i already defined the macro either before including the header or as a preprocessor argument but it dosnt workis this library not meant to be used as a static library or what could possibly be the issuehas anyone been able to link freeimage statically on vs2010thanks,['c++'] +462208,jquery foreach not working in ie8 i have created this little interaction for one of the platforms at work it works fine in all browsers apart form ie8 when i run the console it seems to be this section that it is having problems witharrayprototypeforeachcal functionitem apushjqueryitemtext can someone show me an ie8 friendly alternative so i can make it compatible for the versions required,"['javascript', 'jquery', 'html']" +462219,a section registered as allowdefinitionmachinetoapplication beyond application level after adding the assebly of systemdataentity to my web config i got this errorit is an error to use a section registered as allowdefinitionmachinetoapplication beyond application level this error can be caused by a virtual directory not being configured as an application in iis i have deleted the obj and bin folders i removed the line authenticationwindows tried to reopen as some has said it worked i have checked that there is only 1 webconfig within the main folder entity framework folder for forms model dal and bll what other reasons is there that this will happen i searched everywhere and it is basically the above reasons i foundthis is my webconfig if it makes a difference configuration connectionstrings add nameapplicationservices connectionstringdata sourcesqlexpressintegrated securitysspiattachdbfilenamedatadirectoryaspnetdbmdfuser instancetrue providernamesystemdatasqlclient add namecstringvkb connectionstringdata sourceinitial catalogvkbpersist security infotrueuser idwebsiteservicepasswordwebsiteservice providernamesystemdatasqlclient connectionstrings systemweb compilation debugtrue optimizecompilationstrue targetframework40 assemblies add assemblysystemdataentity version40 cultureneutral publickeytokenb77a5c561934e089 assemblies compilation authentication modewindows forms loginurlaccountloginaspx timeout2880 authentication membership providers clear add nameaspnetsqlmembershipprovider typesystemwebsecuritysqlmembershipprovider connectionstringnameapplicationservices enablepasswordretrievalfalse enablepasswordresettrue requiresquestionandanswerfalse requiresuniqueemailfalse maxinvalidpasswordattempts5 minrequiredpasswordlength6 minrequirednonalphanumericcharacters0 passwordattemptwindow10 applicationname providers membership profile providers clear add nameaspnetsqlprofileprovider typesystemwebprofilesqlprofileprovider connectionstringnameapplicationservices applicationname providers profile rolemanager enabledfalse providers clear add nameaspnetsqlroleprovider typesystemwebsecuritysqlroleprovider connectionstringnameapplicationservices applicationname add nameaspnetwindowstokenroleprovider typesystemwebsecuritywindowstokenroleprovider applicationname providers rolemanager systemweb systemwebserver modules runallmanagedmodulesforallrequeststrue systemwebserverconfigurationwhat can i do to solve this,['asp.net'] +462257,python tkinter scrollbar for frame my objective is to add a vertical scroll bar to a frame which has several labels in it the scroll bar should automatically enabled as soon as the labels inside the frame exceed the height of the frame after searching through i found this useful post based on that post i understand that in order to achieve what i want correct me if i am wrong i am a beginner i have to create a frame first then create a canvas inside that frame and stick the scroll bar to that frame as well after that create another frame and put it inside the canvas as a window object so i finally come up with thisfrom tkinter import def data for i in range50 labelframetextigridrowicolumn0 labelframetextmy textstrigridrowicolumn1 labelframetextgridrowicolumn2def myfunctionevent canvasconfigurescrollregioncanvasbboxallwidth200height200roottksizex 800sizey 600posx 100posy 100rootwm geometrydxd sizex sizey posx posymyframeframerootreliefgroovewidth50height100bd1myframeplacex10y10canvascanvasmyframeframeframecanvasmyscrollbarscrollbarmyframeorientverticalcommandcanvasyviewcanvasconfigureyscrollcommandmyscrollbarsetmyscrollbarpacksiderightfillycanvaspacksideleftcanvascreate window00windowframeanchornwframebindconfiguremyfunctiondatarootmainloopam i doing it right is there bettersmarter way to achieve the output this code gave mewhy must i use grid method i tried place method but none of the labels appear on the canvaswhat so special about using anchornw when creating window on canvasplease keep your answer simple as i am a beginner thanks for your help,['python'] +462290,how to access more than 10 items detail in amazon api using php i am working with amazon api and have used code from online sources i would like to get more than 10 products detail when i make a search query using amazon api i am aware about the amazon api policy of getting 10 data per call but is it possible to get more data by creating loop or somethingwhen i make a request i have assigned following parameteres parameters arrayoperation itemsearch searchindex electronics responsegroup imagesitemattributeseditorialreviewoffers itempage10 keywords search so even though i have asked for 10 pages of result i am unsure of how to thisplay data from every page 1 to 10 so in total i get 100 items when i make a query i get following response when i try to make run the code simplexmlelement object request simplexmlelement object isvalid true itemsearchrequest simplexmlelement object itempage 10 keywords laptop responsegroup array 0 images 1 itemattributes 2 editorialreview 3 offers searchindex electronics totalresults 3383691 totalpages 338370 moresearchresultsurl creative12734locationhttp3a2f2fwamazoncouk2fgp2fsearch3fkeywords3dlaptop26url3dsearchand on,['php'] +462357,rake dbmigrate how do i undo all migrations and redo them is there a quick rake dbrollback command for all of the migrations,['ruby-on-rails'] +462373,how can i see change mysql connection timeout settings i have a java program when i log in after 60 milliseconds i actually tried several times and its always 60 thats why i think theres somewhere set up a timeout for 60 miliseconds my database connection crashes and my program no longer works it always needs to be connected to database it gives me communication link failure error i here are my mysql connection settingsimport javasqlimport javaxswingpublic class mysqlconnect connection conn null public static connection connectdb try classfornamecommysqljdbcdriver connection conn drivermanagergetconnectionjdbcmysqlserver namedatabase nameuser nameuser password return conn catch exception e joptionpaneshowmessagedialognull cant connect to db return null i tried adding autoreconnecttrue tcpkeepalive to my code but no luck is there any way to go to phpmyadmin and change some setting there increase the timeout time,"['java', 'mysql']" +462384,syntax to route rails form for to custom controller have tried forums documentation and blog suggestions they converge on syntax that for me does not properly save and route through desired controllerbig picture i have two software applications that share functionality to implement shared functionality i had rails generate sharedwidgets this mvc works just fine no problem viewing updating creating or deleting using standard sharedwidgets etc routingthen for the productspecific functionality i created two controllers product1widgets and product2widgets both inherit from sharedwidgets controller both are empty except for productspecific layoutsthis scheme almost works when i route to product1widgets it sets layout to product1 and invokes index method of sharedwidgets the result is thisplay of sharedwidgetsindexhtmlerb with product1 layout similarly when i route to product2widgets this sets product2 layout and invokes index method of sharedwidgets the result is thisplay of sharedwidgetsindexhtmlerb with product2 layout perfectbut now we get to the form for because it implements the rails magic it really really wants to route directly to sharedwidgets controller but that is not what i want i want it to route to the appropriate product controller so as to set layout the rails generated form for was something like thisform forshared widget html class form do fi triedform forproduct1 widget html class form do f but that duplicates namespace product1 widget shared widget pathi tried the following three formats all of which seem to route correctly and save the record but the record is empty columns are blankform forwidget url product1widget html class form do f form forwidget url url forcontroller widget html class form do f form forwidget url url forcontroller widget action create html class form do f any help if the above code has spelling errors it is due to transcription the actual code i used passed the interpreter thank you,['ruby-on-rails'] +462414,how to invalidate cache data outputcache from a controller using aspnet mvc 3 i have a controller which output is being cached using attributes outputcache outputcachepublic controllerai would like to know if is possible to invalidate the cache data server cache for a specific controller or generally all the cache data calling a nother controllerpublic controllerb calling this invalidate the cache,['c#'] +462428,what happens when you close a file using ios protected unless open encryption apples documentation says the followingprotected unless open files are encrypted a closed file is inaccessible when the device is locked after the device is unlocked your app can open and use the file if the user has a file open and locks the device for example by pressing the sleep button your app can continue to access the fileenabling store technologiesand alsocomplete unless already open the file is encrypted a closed file is inaccessible while the device is locked after the user unlocks the device your app can open the file and use it if the user locks the device while the file is open though your app can continue to access it specify the nsdatawritingfileprotectioncompleteunlessopen option nsdata or the nsfileprotectioncompleteunlessopen attribute nsfilemanagerprotecting data using onthisk encryptionthis seems like a great option for allowing me to finish up any remaining work on the file and then closing it myself what the documentation does not say is what happens to the file when i close it for instance what happens whenuser opens app and opens file within appuser locks device file remains unprotected because it is openapp performs remaining operations on fileapp closes the filenow is the file protected since it is now closed or can it be reopened,['ios'] +462443,converting a gregorian date string to islamic date gives correct incorrect results i have the following two date strings 1 24042013 and 2 19032013 i am trying to convert these dates into islamic um al qura dates i am using this code block to do so nsdateformatter df nsdateformatter alloc init dfdateformat ddmmy dfcalendar nscalendar alloc initwithcalendaridentifiernsgregoriancalendar nsdate dateingrogrian df datefromstring24042013 nsdateformatter df2 nsdateformatter alloc init nscalendar cal nscalendar alloc initwithcalendaridentifiernsislamiccalendar df2 setcalendarcal df2 setdateformatddmmy nslogconverted date to islamic df2 stringfromdatedateingrogrian if the input string was 24042013 the nslog thisplayedconverted date to islamic 14061434 which is correct according to the formal islamic calendar which is used in all islamic countries but if the input string was 19032013 the nslog thisplayedconverted date to islamic 08051434 which is incorrect according to the islamic calendar the correct date must be 07051434 whichs 1 day behindnotes to consider before you suggest an answer1 i have tried to use the calendar identifier nsislamiccivilcalendar instead of nsislamiccalendar but to no avail one of the converted dates was correct and the other was wrong 1 day behind2 i have tried to use gmt time zone like this df2 settimezone nstimezone timezonewithnamegmt this produced a correct converted date for day 2 but incorrect for day 1 1 day behind3 i have tried combinations of solutions nsislamiccivilcalendar with without gmt time zone nsislamiccalendar with without gmt time zone but also to no avail can anybody provide a code block that satisfies both dates so i ensure that any provided gregorian date string is correctly converted into islamic date stringthank you so much,"['ios', 'objective-c']" +462475,how to add button to notifications in android my app plays music and when users open notifications screen by swiping from the top of the screen or generall from the bottom right of the screen on tablets i want to present them a button to stop the currently playing music and start it again if they wanti am not planning to put a widget on users homescreen but just into notifications how can i do this,['android'] +462488,group list entries with linq i have the following modelpublic class entry public int useraccountid get set public int companyid get set public datetime creationdate get set public string target get set public string message get set and a list with a lot of entrieslistentry entries get all entriesexamplei would now like row 2 and 3 to be grouped because they have the same userid same companyid same target and almost and this is the difficult part let us say in a range of 5 seconds the same date time after grouping my list should look like thisis there any easy approach for this problem any advicesi bet linq will help me around but i am not sure howeditthank you all for your feedbacki decided to change the design and to ensure that the datetime is now really the same so grouping with linq is now very easy,['c#'] +462559,get url path in php i have a quick question in phpi need to get the current page url and then find the path for example if the current url isi would want thisexampletesthiphprandomvariable1thank you,['php'] +462586,rails 32 mysql error field created at does not have a default value insert into i created a new migration where is mentionedttimestampsin the created table are added these two columns created at datetime no null null default updated at datetime no null null default when i want to create a new item i always get the error messagemysql2error field created at does not have a default value insert into table name first col second col values a bam i missing something i sent this miniapp to a friend of mine and he is able to run successfully run it the record is created in databasewhat am i missing,"['mysql', 'ruby-on-rails', 'ruby']" +462627,orm doctrine manytoone on update cascade symfony i have two entitiesclass promotor ormmanytoonetargetentityciudad inversedbypromotor ormjoincolumnnameciudad id referencedcolumnnameid nullablefalse protected ciudadand class ciudad var integer ormcolumnnameid typeinteger ormid ormgeneratedvaluestrategyauto private id var string ormcolumnnamenombre typestring length50 private nombrea promotor can live in one ciudad city and in a ciudad city can live many promotoresif i add ondeletecascade in joincolumn ormmanytoonetargetentityciudad inversedbypromotor ormjoincolumnnameciudad id referencedcolumnnameid nullablefalse ondeletecascade protected ciudadit generate the next codealter table promotor drop foreign key fk bf20a37fe8608214alter table promotor add constraint fk bf20a37fe8608214 foreign key ciudad idreferences ciudad id on delete cascadebut also i like do cascade on update i try with onupdatecascade but it doesn workdoctrinecommonannotationsannotationexceptioncreation error the annotation ormjoincolumn declared on property webpromotorbundleentitypromotorciudad does not have a property namedonupdate available properties name referencedcolumnname unique nullable ondelete columndefinition fieldnameby the error i understand that the property onupdate does not exist but is there any way to do cascade on update,['php'] +462694,how to convert int to int c i have an int array in one dimension var intarraynew 1 2 3 4 5 6 and i want to convert it to two dimensions such as var intarray2dnew 1 2 3 4 5 6 how do i achieve this with c,['c#'] +462696,i want to apply delay on mouse out in css i am trying to apply a delay before starting a css transition on mouse out event my css code is below please let me know how to apply time delay before css transition on mouse out starts i want to achieve that the menu stays stable for some time eg for 3 seconds after the user moves mouse pointer out of the menu timnav li dropdown width auto minwidth 0px maxwidth 230px height 0 position absolute overflow hidden zindex 9 backgroundrgba255 255 255 08 timnav lihover dropdown minheight 60px maxheight 500px height auto width 100 padding 0 webkittransition delay 5s easeinout moztransition delay 5s easeinout otransition delay 5s easeinouttimnav li dropdown ul margin 0 margintop7pxtimnav li dropdown ul li thisplay block width 100 float left textalign left height auto borderradius none paddingbottom2px timnav li dropdown dropdown2 thisplay none width 100 float left textalign left height auto borderradius none timnav li dropdown ul lihover dropdown2 thisplay block width 100 float left textalign left height auto borderradius none timnav li dropdown dropdown2hover thisplay block width 100 float left textalign left height auto borderradius none timnav li dropdown dropdown2 li a thisplay block paddingleft7px important height6 important paddingtop8px background urlimagesnavbgjpg repeat colorftimnav li dropdown ul li a thisplay block lineheight 26px height 22px padding 10px background urlimagesnavcrrentjpg repeat colorftimnav ul dropdown ul lifirstchild a borderradius 0timnav li dropdown li ahover background urlimagesnavbgjpg repeat color0,"['html', 'css']" +462706,ember handling clicks outside of view wondering if anyone has come up with a better way for handling a click outside a div while using ember i know of the jquery way with a global click handler that you must specify each action to take for certain instances but am hoping someone has come up with a way to declare this inside an ember view as well i tried the ol give a div a tab index and use the on blur but ember actions do not seem to allow this,"['javascript', 'jquery']" +462755,javascript comparing to null vs ok so i installed linter on my sublime editor while working on my nodejs app one of the things that it caught said that i should always use to compare an object to null i usually use so i changed itbut then i noticed that the was not workingi have this scenariovar x nullif x null consolelogx is not equal to nullwhen i use the the console printed that line even though it was obviously not true when i switched it back to it behaved normallyso my question is why is linter telling me to use if it does not do what i want it toi know i am missing somethingupdateok so it may be a bit more complicated than i originally thought in my real code i was using with the nodejs global objectconsolelogglobal user globaluserif globaluser null consoleloguser is not nullthe console line prints even when globaluser is nullperhaps this object is specialupdate 2ok so after reading through the comments and looking at my code i have learned that can have issues if the object is undefined rather than null see this post why is null an object and whats the difference compared to undefinedso in my case my global variable could be depending on when this method is called undefined null or full of data i am going to go back and update my code so that it is never undefined and then will work consistentlythanks for the helpthanksdavid,['javascript'] +462767,whats a thist installation location in php composer looking at the help for php composers install command i see the following two options composer help installoptions prefersource forces installation from package sources when possible including vcs information preferthist forces installation from package thist even for dev versionswhats a thist installation i poked around the composer site and google but there did not seem to be anything that addressed this so i assume it is something core and obvious to folks familiar with composer aa apologies for the newbie questioni am assuming prefersource is where composer will ask packagist for the repository location and then checkoutcloneexportetc the project itself if so then where does preferthist download from what does it download,['php'] +462805,pythonbeautifulsoup how to remove all tags from an element how can i simply strip all tags from an element i find in beautifulsoup,['python'] +462838,css outsetinset border and outline what is exact difference between css outsetinsetborder and outlinereally coufused about this and what properties can be applied togetherwhich browsers support which of the above properties short example on above properties will be good thanks,"['jquery', 'html', 'css']" +462901,should i inflate a layout or programmatically create it regarding android programmingthis question has been bothering me for a while should i inflate layout as much as possible or should i programmatically create the layouts as much as possible if we put convenience aside which is better faster saferany concrete inputs are greatly appreciatedregards,['android'] +463064,how to convert base64 string to image i am converting an image to base64 string and sending it from android device to the server now i need to change that string back to an image and save it in the databaseany help,['python'] +463067,upload base64 image facebook graph api i am trying to upload a base64 image to a facebook page using nodejs i have managed to get the upload working with all the multipart data etc should i read the file from the filesystem ie using fsreadfilesynccajpghowever should i use the base64 encoded image and try upload it it give me the following error errormessage1 an unknown error occurredtypeoauthexceptioncode1i have tried converting it to binary by new bufferb64string base64 and uploading that but no lucki have been struggling with this for 3 days now so anyhelp would be greatly appreciatededit if anyone also knows how i could convert the base64 to binary and successfully upload it that would also work for meedit code snippetvar postdetails separator newlineconstant contentthisposition formdatanameaccess token newlineconstant newlineconstant accesstoken newlineconstant separatorpostdetails postdetails newlineconstant contentthisposition formdata namemessage newlineconstant newlineconstant message newlineconstantadd the image informationvar filedetailsstring var index 0var multipartbody new buffer0imagesforeachfunction currentimage filedetailsstring filedetailsstring separator newlineconstant contentthisposition file namesource filenameimage index newlineconstant contenttype imagejpeg newlineconstant newlineconstant index multipartbody bufferconcatmultipartbody new bufferfiledetailsstring currentimage this is what i would use if bianry data was passed in currentimage new buffer currentimagetostringbase64 base64 the following lines are what i would use for base64 image being passed in the appropriate lines would be enabledthisabled if i was using binarybase64 multipartbody bufferconcatmultipartbody new bufferfiledetailsstring currentimagemultipartbody bufferconcatnew bufferpostdetails multipartbody new bufferfooter,['javascript'] +463076,does rails provide default session timeout duration if yes where is it specified i already know how to set expiry time duration in rails app which has been documented very well on web but what i want to know is what is the default time duration for session expiry in rails and if there is one where to find it,['ruby-on-rails'] +463152,python getting text of a regex match i have a regex match object in python i want to get the text it matched say if the pattern is 13 and the search string is abc123xyz i want to get 123 how can i do thati know i can use matchstringmatchstartmatchend but i find that to be quite cumbersome and in some cases wasteful for such a basic queryis there a simpler way,['python'] +463159,uncaught typeerror object object object has no method live getting this erroruncaught typeerror object object object has no method livefrom this javascript and jquery codeinit functionoptions var form this if formdatajqv formdatajqv null options methods saveoptionsform options bind all formerror elements to close on click formerrorliveclick function getting error here uncaught typeerror object object object has no method live return thiswhy is method live missing,['jquery'] +463166,system clear property does not work how can it be i really do not understandi run unit tests which contains cod string progdir progdir systemclearpropertyprogdir systemoutprintlnsystemgetpropertyprogdirand on console i see prog dir path although there must be nulli setting this variable in setup block this is junit test this variable need for all other test but not for that so i tried to clean it in the start of this test method if i remove setting of this var from setup block this test will pasystemsetproperty work finehow can it bethanx,['java'] +463167,in servicestack is it possible to mock the requestoriginalrequest object for unit tests i would like to make my servicestack service testablepresently i haverequireformsauthenticationpublic object deletedeleterequest request var originalrequest httprequestrequestoriginalrequest var identity originalrequestrequestcontexthttpcontextuseridentity return othercodeidentitywhere requireformsauthentication ispublic class requireformsauthenticationattribute requestfilterattribute public override void executeihttprequest req ihttpresponse res object requestdto var originalrequest httprequestreqoriginalrequest var identity originalrequestrequestcontexthttpcontextuseridentity if identityisauthenticated resstatuscode inthttpstatuscodeforbidden resendservicestackrequestskipheaders true i have mocked out all the dependencies used by othercode and all that is left is the stuff that is in the base class service is there a patternstrategyapproachsomething i am missing that makes this trivial,['c#'] +463172,enforce trailing slash in rails routing adding a trailing slash in your links is easy enough with trailing slash true but this does not account for if a user types in a nonslashed url is there a way to enforce trailing slashes via redirects in the routerget controllerid redirectparams paramscontrollerparamsid the above leads to a circular loopwhya relative link of subclass onparent1is much different thanparent1,['ruby-on-rails'] +463230,is it possible for a jvm to run more than one program at the same time is it possible for a jvm to run more than one program at the same time if so how if not whyto run a program we simply dojava programnamebut can we use the same jvm instance to run another program,['java'] +463231,understanding the nodejs event queue and processnexttick i am having trouble understanding exactly how processnexttick does its thing i thought i understood but i cannot seem to replicate how i feel this should workvar handler functionreq res reswritehead200 contenttype texthtml foofunction consolelogbar consolelogreceived resendhello worldfunction foocallback var i 0 whilei10 i processnexttickcallbackrequirehttpcreateserverhandlerlisten30while foo is looping i will send over several requests assuming that handler will be queued several times behind foo with callback being enqueued only when foo is finishedif i am correct about how this works i assume the outcome will look like thisreceivedreceivedreceivedreceivedbarbarbarbarbut it does not it is just sequentialreceivedbarreceivedbarreceivedbarreceivedbari see that foo is returning before executing callback which is expected but it seems that callback is next in line rather than at the end of the queue behind all of the requests coming in is that the way it works maybe i am just not understanding how exactly the event queue in node works and please do not point me here thanks,['javascript'] +463302,nginx can not forward the request protocol correctly to upstream i have a website in rails 4 beta it is running on nginx unicorn i want nginx to forward the request protocol http or https to unicorn so that i can work with them however i am not able to make it worki put requestssl and requestprotocol in the view file for testing my nginx server config file is as followingupstream unicorn server unixtmpunicornblogsock fail timeout0server listen 80 listen 443 server name examplecom root homeexample ssl on ssl certificate etcnginxsslservercrt ssl certificate key etcnginxsslserverkey location assets gzip static on expires max add header cachecontrol public try files uriindexhtml uri unicorn location unicorn proxy set header xforwardedproto https line 1 proxy set header xforwardedfor proxy add x forwarded for proxy set header host http host proxy set header xforwardedssl on line 2 proxy redirect off proxy pass httpunicorn error page 500 502 503 504 500html client max body size 4g keepalive timeout 10i found that the 2 lines i marked are not acting right here is my test resultline 1 commented out line 2 commented out too visit requestssl false requestprotocol httpvisit requestssl false requestprotocol httpline 1 commented out line 2 is not orline 2 commented out line 1 is not orneither is comments outvisit requestssl true requestprotocol httpsvisit requestssl true requestprotocol httpsthat is to say if one of those two lines appears nginx forward https to upstream no matter what the actual protocol is but if none of those two lines appears nginx forward http to upstream no matter what the actual protocol isplease can someone tell me how to write the nginx config file so that it can forward the protocol correctly thank you very much,['ruby-on-rails'] +463327,using print inside recursive functions in python3 i am following the book introduction to computing using python by ljubomir perkovic and i am having trouble with one of the examples in recursion section of the book the code is as followsdef patternn prints the nth pattern if and 0 base case print0 end else recursive step and 0 patternn1 print n1st pattern printn end print n patternn1 print n1st patternfor say pattern1 the output should be 0 1 0 and it should be thisplayed horizontally when calling the function pattern1 nothing prints out however but if this is followed by a print statement without arguments then the results are thisplayedpattern1print0 1 0if i remove the end argument of the print functions inside the recursive function i get correct output albeit it thisplays it vertically pattern1010this makes me think that the recursive code itself is correct plus i confirmed it was with the source provided by the books website and with the errata sheet i am not sure however why the print statement is not printing the output as the functions run if the end parameter is included any help would be greatly appreciated,['python'] +463385,can i reuse an rvalue reference parameter to return an rvalue reference consider the following codestruct mystring some ctors mystring operator const mystring other implemented correctlymystring operator const mystring lhs const mystring rhs mystring nrv lhs nrv rhs return nrvmystring operator mystring lhs const mystring rhs lhs rhs return stdmove lhs return the rvalue reference we received as a parameterthis works for the following usecasemystring a b c initialized properlymystring result a b cbut it creates a dangling reference forconst mystring result a b cnow i understand why that is and how to fix it returning an ravlue instead of an rvalue reference but i consider it a usage error if someone writes the above as the code looks like it is asking for trouble is there any canonical realworld example where the above operator returning a rvalue reference is a problem what is a convincing reason why i should always return an rvalue from operators,['c++'] +463390,why multiple dbcontext classes when i program using linq with a dbml file there is only one context but when i do an mvc site it seems like i have separate contexts for each entity which is the way the mvc tutorial showed me how to do it with movies contexti havepublic class accountscontext dbcontext public accountscontext basedefaultconnection public dbsetaccount accounts get set and i havepublic class clientscontext dbcontext public clientscontext basedefaultconnection public dbsetclient clients get set when i call these i have to create separate contexts likeprivate accountscontext db new accountscontextprivate clientscontext clientscontext new clientscontext which is both annoying and it seems redundant since i know that when i use linq i only have to instantiate a single database objectis there a way to use only one context and is this recommended,['c#'] +463498,passing variable to partial undefined local variable or method error here is the code in my view to call the partial renderpartial tabs locals class name science y 36 and now here is whats in tabshtmlerbdivh1 class name h1divi expect html output ofdivh1 science h1divbut instead i get the error undefined local variable or method class name for class0x007f873b156c280x007f873b1f9540i have closed and restarted aptana the ide i use and restarted the server multiple timesthanks in advance for your time,['ruby-on-rails'] +463534,thisplay uiviewcontroller as popup in iphone since there is no complete definitive answer to this common recurring question i will ask and answer it hereoften we need to present a uiviewcontroller such that it does not cover full screen as in the picture belowapple provides several similar uiviewcontroller such as uialertview twitter or facebook share view controller etchow can we achieve this effect for a custom controller,"['ios', 'iphone']" +463536,set the caret position always to end in contenteditable div in my project i am trying to set the caret position always to the end of the text i know this is default behaviour but when we add some text dynamically then the caret position changes to starting point in chrome and firefox ie is fine amazing anyway to make it to work properly in chrome and firefoxhere is the fiddlediv idresult contenteditabletruedivbutton classclickclick to add textbuttovar result resultclickclickfunction var prehtml resulthtml resulthtmlprehtml hello resultfocusi tried adding setstart and setend as mentioned in this link but no use,"['javascript', 'jquery', 'html']" +463551,fast way to replace elements in array c let us say we have an array of ints like thisconst int size 10int arraysizeset some items to 0 and other items to 1i would like to replace all items that have value of 1 with another value for example 123456 this can be trivially implemented withforint i 0 i size i ifarrayi 0 arrayi 123456out of curiosity is there a faster way to do this by some kind of x86 trickery or is this the best code for the processor,['c'] +463571,c and net garbage collector performance i am trying to make a game in c and net and i was planning to implement messages that update the game objects in the game world these messages would be c reference objectsi want this approach because doing it this way would be easier to send them over a network if i want the game to be multiplayerbut if i have a lot of messages would not it be quite stressful for the garbage collector and would not that affect gameplay the message classes themselves are quite small with 4 or 5 members at mostthese messages will be generated a couple of times per second for each object in the game world,['c#'] +463598,how to expose raw byte buffers with boostpython i have got third party c library in which some class methods use raw byte buffers i am not quite sure how to deal in boostpython with itc library header is something likeclass csomeclass public int load unsigned char pinbufferdata int iinbuffersize int save unsigned char poutbufferdata int ioutbuffersize in stuck with the boostpython codeclass csomeclasscsomeclass init defload csomeclassload args what do i put here defsave csomeclasave args what do i put here how do i wrap these raw buffers to expose them as raw strings in python,['python'] +463612,guard would not load wdm i am working through michael hartls rails tutorial which is excellent so far i am on the advanced setup chapter where he goes through configuring the rails environment in a way conducive to tdd i installed guard and it runs properly all the way through running the tests i have in my spec folder but then it spits out this errorcrailsinstallerruby193librubygems191gemslisten102liblistenadapterrb195in require cannot load such file wdm loaderrori have wdm installed i do not know why it cannot load it it seems like listen is having problems loading up wdm it quits after it says guard is now watchingi have not reproduced the rest of the stack trace for obvious reasons i installed rails using the latest rails installer whats going on here do i need to worry about this it appears to work at least partially,"['ruby-on-rails', 'ruby']" +463645,can transient keywords mark a method in a java class javautillocale i find that the keyword transient marked a method public final class locale implements cloneable serializable private static class localenamegetter implements sunutillocaleserviceproviderpoollocalizedobjectgetter public transient string getobjectlocalenameprovider localenameprovider locale locale string s object aobj ifassertionsthisabled aobjlength 2 throw new assertionerror int i integeraobj0intvalue string s1 stringaobj1 switchi case 0 0 return localenameprovidergetthisplaylanguages1 locale case 1 001 return localenameprovidergetthisplaycountrys1 locale case 2 002 return localenameprovidergetthisplayvariants1 locale ifassertionsthisabled throw new assertionerror else return null can someone tell me why can this be,['java'] +463699,google play inapp billing giving an item for free i already have a completely free app published at google play store since the app is more popular than i have thought i decided to lock some of the features and demand inapp billing before using it however i prefer that all existing users will continue to enjoy have the premium features for freeso i thought about the followingupload a version with inapp billing for free so that the existing userswill purchase it for freeafter certain amount of time start charging for the items but sincehe existing users already own the premium items they wouldnt behurtis there a way to grant some users an item for free in the inapp billing documentation is written that there must be a price for all inapp billing items,['android'] +463700,unable to purchase in app product from google play i am using in app purchase in my app for few days back it was working however when i try to purchase through an app i am getting following error message in dialog your payment could not be processed at this time you may receive an email asking you to verify your account and purchase failed in notification bari searched for this error got the one solution here is the link but no luck by this linkpfa image for transaction history of my purchased item via google account added to google play,['android'] +463707,android making translations and objectanimator on the same xml file i have been trying to make a 3d cube rotation effect while sliding from one fragment to anotherfirst i was using a translate effect on xml calling with fragmenttransactionsetcustomanimations and then when openingclosing the fragment i was playing with the camera classe to make the rotationthis was working fine but seems that i have too do not ask me why use all of this animation using only xml file after a long search i found out that i should use objectanimator to make the rotation followed the google sample and i manage to make the flip animation now i need to translate the fragments making them sliding in and sliding out seems that i cannot use objectanimator and translate effect on the same xml file since this error appearsjavalangruntimeexception unknown animator name translate at any ideas on how i can make the sliding effect and use the objectanimator on the same time thank you for your timecode i have been usingcard flip right inxmlset xmlnsandroid before rotating immediately set the alpha to 0 objectanimator androidduration0 androidpropertynamealpha androidvaluefrom10 androidvalueto00 rotate objectanimator androiddurationintegercard flip time full androidinterpolatorandroidinterpolatoraccelerate decelerate androidpropertynamerotationy androidvaluefrom180 androidvalueto0 halfway through the rotation see startoffset set the alpha to 1 objectanimator androidduration1 androidpropertynamealpha androidstartoffsetintegercard flip time half androidvaluefrom00 androidvalueto10 setfragment calling another fragment cube rotation should be visible between this 2private void launcharticleint prev int pos articlefragment newfragment new articlefragment bundle args new bundle argsputstringpos pos argsputintprev prev newfragmentsetargumentsargs androidappfragmenttransaction transaction getfragmentmanagerbegintransaction fragment currfrag fragmentgetfragmentmanagerfindfragmentbyidridheadlines fragment if currfrag null transactionhidecurrfrag transactionsetcustomanimations ranimatorcard flip right in ranimatorcard flip right out ranimatorcard flip left in ranimatorcard flip left out transactionreplaceridfragment container newfragment pos transactionaddtobackstacknull transactioncommitupdatei have manage to solve the previous problem using a class that extends my framelayout of the fragments i am usingslidingframelayoutjavapublic class slidingframelayout extends framelayout private static final string tag slidingframelayoutclassgetname public slidingframelayoutcontext context supercontext public slidingframelayoutcontext context attributeset attrs supercontext attrs public float getxfraction final int width getwidth ifwidth 0 return getx getwidth else return getx public void setxfractionfloat xfraction final int width getwidth setxwidth 0 xfraction width 9 public float getyfraction final int height getheight ifheight 0 return gety getheight else return gety public void setyfractionfloat yfraction final int height getheight setyheight 0 yfraction height 9 and by adding this to the objectanimator move objectanimator xmlnsandroid androiddurationintegercard flip time full androidinterpolatorandroidanimlinear interpolator androidpropertynamexfraction androidvaluefrom1 androidvalueto0 this is working better but the rottation axes are in the middle of the framelayout and it is not making the illusion of a cube is it possible to set the rotation axes on a certain point,['android'] +463721,suitable library for combining with d3js to allowing drawing to webgl 2d here is what i am trying to do but i want to do that in webgl 2d because svg performance is very slow randering 10k svg only already drops to 12 fpson a quick search i found several webgl2d libs cocos2dhtml5 pixijsthreejs and webgl2dabandonedthey seems to be pretty easy but what i want to do is data visualizationcocos and pixijs are 2d game libraries i am new to webgl and those libraries so experts at so can you guys recommend summary of things i needinteraction rectangular selection inside plots click to select on some elementszoom and pan support semitic zooming if possiblerenderer webgl2d according to benchmarks webgl is fastest,['javascript'] +463733,determine if function called as a result of a native browser event is there a way to determine if a given function is called as a result of a native browser eventin modern browsers if you call the function windowopen from a scope chain that originated with a click handler a page will open with no problemhowever if you try to call it directly the browser will generate a popup warningso the browser keeps track of the execution context and somehow flags it so the first use of the function succeeds without the presence of this flag it blocks the second useis there any way to get access to this flag to internally block certain functions from executing if they are called directly as opposed to from a real native browser eventi have looked at event object my functions receive but i cannot spot anything that is different between a real native event and an event generated by triggering the event manuallyis what i want actually possible,['javascript'] +463736,d3js force layout auto zoomscale after loading i am using this nice force layout from flowingdatacom to create a network diagrammy diagram currently shows between 5 and 750 nodes with their relations it works great with some custom changes to fit my needs however one thing i cannot get to work i have a viewbox with preserveaspectratio to auto fit the container it is in but depending on the amount of nodes there are always some nodes around the edges mainly top and buttom that get cut off and if there are very little nodes it shows them in the middle with huge empty space around it it is a big container it is inis there any way to auto zoom or scale the layout to auto fit so that a big layout gets somewhat zoomed out and a small layout zoomed in i have a zoom event setup so scrolling and panning works like a charm but can it automatically do that to fit the contentsthe d3js startup code vis d3selectselection appendsvg attrviewbox 0 0 width height attrpreserveaspectratio xmidymid meet attrpointerevents all calld3behaviorzoomscaleextent1 3 onzoom redrawappendg,['javascript'] +463765,i screwed up the system version of python pip on ubuntu 1210 i wanted to update pip on my main install of python specifically to get the list command which also includes the list updates capabilityso i ran sudo pip install upgrade pipall looked good on the install but then i went to run pip and got this end of install included if it helps installing pip script to usrlocalbin installing pip27 script to usrlocalbinsuccessfully installed pipcleaning uptomtomsam pip list obash usrbinpip no such file or directorytomtomsam pipbash usrbinpip no such file or directorysomewhat obviously i am hosed since this is my system install of python i read a few answers here but have not been able to determine the easiest fix,['python'] +463779,android check if file exists without creating a new one i want to check if file exists in my package folder but i do not want to create a new onefile file new filefilepathiffileexists return truedoes this code check without creating a new file,['android'] +463812,center content in a absolute positioned div i have an absolutly positioned element with content inside it can be a h1 or a few p tag so i do not know the height of the content how can i vertically center the content inside the absolutly positioned divhtml div idabsolute div classcenterd h1heloh1 spanhi againspan divdiv css absolute positionabsolute top10px left10px width50 height50 backgroundyellowcenterd thisplaytablecell verticalalignmiddlefiddle,['css'] +463815,java userdir property what exactly does it mean i want to use userdir dir as a base dir for my unit tests that creates a lot of files is it correct that this property points to the current working directory eg set by the cd command,['java'] +463826,chrome remembers scroll position i am running into a problem that is actually a feature on chromeas most of you might know chrome remembers a scroll position that it returns to whenever you come back to a page and i kind of have a problem with thatis there any way to override this without the user noticingmeesfailed tryoutsscrolltop on documentready,"['javascript', 'html']" +463859,dynamically add new lambda expressions to create a filter i need to do some filtering on an objectset to obtain the entities i need by doing this query thisobjectsetwherex xtypeid 3 this is just an examplelater in the code and before launching the deferred execution i filter the query again like this query querywhereanother lambda here that works quite well so farhere is my problem the entities contains a datefrom property and a dateto property which are both datatime types they represent a period of timei need to filter the entities to get only those that are part of a collection of periods of time the periods in the collection are not necessarily contiguous so the logic to retreive the entities looks like that entitieswherex xdatefrom period1datefrom and xdateto period1datetoentitieswherex xdatefrom period2datefrom and xdateto period2dateto and on and on for all the periods in the collectioni have tried doing that foreach var rateperiod in rateperiods var period rateperiod query querywherede dedate perioddatefrom dedate perioddatetobut once i launch the deferred execution it translates this into sql just like i want it one filter for each of the periods of time for as many periods there is in the collection but it translates to and comparisons instead of or comparisons which returns no entities at all since an entity cannot be part of more than one period of time obviouslyi need to build some sort of dynamic linq here to aggregate the period filtersupdatebased on hattens answer i have added the following member private expressionfunct bool combinewithortexpressionfunct bool firstexpression expressionfunct bool secondexpression create a parameter to use for both of the expression bodies var parameter expressionparametertypeoft x invoke each expression with the new parameter and combine the expression bodies with or var resultbody expressionorexpressioninvokefirstexpression parameter expressioninvokesecondexpression parameter combine the parameter with the resulting expression body to create a new lambda expression return expressionlambdafunct boolresultbody parameterdeclared a new combinewithor expression expressionfuncdocumententry bool resultexpression and falseand used it in my period collection iteration like this foreach var rateperiod in rateperiods var period rateperiod expressionfuncdocumententry bool expression de dedate perioddatefrom dedate perioddateto resultexpression thiscombinewithorresultexpression expressionvar documententries querywhereresultexpressioncompiletolisti looked at the resulting sql and it is like the expression has no effect at all the resulting sql returns the previously programmed filters but not the combined filters why update 2i wanted to give feo2xs suggestion a try so i have rewritten my filter query like this query queryasenumerable wherede rateperiods anyrp rpdatefrom dedate rpdateto dedateas you can see i added asenumerable but the compiler gave me an error that it cannot convert the ienumerable back to iqueryable so i have added toqueryable at the end of my query query queryasenumerable wherede rateperiods anyrp rpdatefrom dedate rpdateto dedate toqueryableeverything works fine i can compile the code and launch this query however it does not fit my needswhile profiling the resulting sql i can see that the filtering is not part of the sql query because it filters the dates inmemory during the process i guess that you already know about that and that is what you intended to suggestyour suggestion works but since it fetches all the entities from the database and there are thousands and thousands of them before filtering them inmemory it is really slow to get back that huge amount from the database what i really want is to send the period filtering as part of the resulting sql query so it would not return a huge amount of entities before finishing up with the filtering process,['c#'] +463897,selenium get current url after loading a page i am using selenium webdriver in java i want to get the current url after clicking the next button to move from page 1 to page 2 heres the code i have webdriver driver new firefoxdriver string starturl a starting url string currenturl null webdriverwait wait new webdriverwaitdriver 10 foodriverstarturl go to next page ifdriverfindelementbyxpathidsomeidisthisplayed driverfindelementbyxpathidsomeidclick drivermanagetimeoutsimplicitlywait30 timeunitseconds waituntilexpectedconditionsvisibilityofelementlocatedbyxpathidsomeid currenturl drivergetcurrenturl systemoutprintlncurrenturl i have both the implicit and explicit wait calls to wait for the page to be fully loaded before i get the current url however it is still printing out the url for page 1 it is expected to be the url for page 2,['java'] +463907,html telephone link for phones format i am making an html link for a phone this is what i havea hreftel18 18awill phones recognize this or do i need to change it to a hreftel18 18a,['html'] +463921,making radio buttons look like buttons instead i would like to have a set of radio buttons for a donation form however i want them to look like buttons instead of the circle dialswhat is the best approach to making something like that also keep in mind it has to work with ie8heres what i have so far donatenow liststyletypenone margin25px 0 0 0 padding0donatenow li floatleft margin0 5px 0 0donatenow label padding5px border1px solid c cursorpointerdonatenow labelhover backgroundthank you,"['jquery', 'html', 'css']" +463935,share a session across multiple servers with different domains i am having a little problem i am developing an application in php that is divided into modules each module is completely independent is on a separate server and has an own domain egwmoduloprincipalcombr wmodulo2combr wmodulo3combr etc the problem is that i need that when a user to authenticate to one of the modules either the user can access the same user other modules without having to authenticate againcurrently each application is on a different server but if necessary they are in the same server it would not be a problemimportantread several threads but found no solution really safe will be interesting to use oauth currently the application uses session to authenticate users but you can use cookie smoothlyi am using codeignitertranslated by google translate sorry,['php'] +463939,app crashing with proguard enabled my app runs perfectly without proguard enabled but when i enable it the app crashes right away i have tried many combinations in the configuration to no availis there something that i should be keeping that i am missingproguard config unobfuscated log onsuccess,"['java', 'android']" +463940,django detailview how to use request in get context data i am trying to modify context data so i overrided get context data i need request variable for modify this context so how can i get request variable in get contextdata,['python'] +463941,jquery sortable style function with empty spots in the interest of learning how to do this more efficiently i am curious to any thoughts of how to improve this or if i am walking down the wrong road all together so far i have written this handles basically what i want it to on a small scalethere are some bugs and i do not feel confident at all that this is as good as it could be written might be an idiot for not trying to latch onto jquery ui sortable but with needing to do this without a simple list of items and with wanting to expand this to include multiple drag and drop i wanted to at least walk through what i needed to do to make this happen even if it was just to learn how sorting functions like these work the problem childthis is all in a function called on the over event of the droppablei have an array of empty spots var emptyholders pipelineholdereachfunction ifthishasclassholderempty var eid thisattrid emptyholderspusheidsubstring14 cid is the droppable element that youre over top of so i find the next open slot using for var i 0 i emptyholderslength i var currentempty emptyholdersi if currentempty cid nextempty currentempty i emptyholderslength else prevempty parseintcurrentempty if there is a an empty slot further down the list i use a for loop to loop through moving the items around the dom to make the space needed to drop the element if nextempty null var moveme nextempty 1 for var i moveme i cid i var nextcount i 1 var me pipelinerank i var next pipelinerank iparentspipelinerankrownextfindpipelineholder var pid pipelinerank ifindcontentwrapperattrid nextappendpipelinerank ifindcontentwrapper nextremoveclassholderempty nextsiblingsremembermypositionhoverhtmlpid pipelinerank cidaddclassholderempty if there is not one further down the list i do the same thing in reverse to check if there is a spot above the droppable to push items up intoany thoughts are extremely appreciated,"['javascript', 'jquery']" +463942,mockito how to mock and assert a thrown exception i am using mockito in a junit test how do you make an exception happen and then assert that it has generic pseudocode,['java'] +463958,is the qt defines doing the same thing as define in c what does the defines includthisvariable do in qt for a pro fileif it works like the define in c where is includethisvariable defined so that the preprocessor can replace includethisvariable with the value i seti understand what define does in c because you set the value beside what you define however here it seems like you just list a namethe qt docs did not help explain this for me,['c++'] +464000,how to create a simple sysfs class attribute in linux kernel v32 i am learning how to use sysfs in my linux modules but i am having the hardest time finding current documentation on these topics the linux device drivers 3rd edition book i have been using seems to be rather dated in this area unfortunately eg the class device appears to be completely gone in current linux versionsi am simply trying to get an attribute to appear under the respective sysfs class for my module that will allow me to read the value of a module variable from kernel spacein my code i have a class created that allows udev to create a device node at devfoo for my moduledev t foo devalloc chrdev regionfoo dev 0 1 barstruct class bar class createthis module bardevice createbar null foo dev null foostruct cdev foo dev filecdev initfoo dev file fops fops defined earlier cdev addfoo dev file foo dev 1when i insert the module i get a sysfs class directory created and populated with some default attributes at sysclassbarfoo how can i create attributes that show up under this new directoryi have the concepts down pretty well i believe create attribute structure define sysfs ops functions etc my problem is that i do not know which particular kernel structure to use class attribute nor how to make these attributes appear under the right sysfs directorywould anyone point me to a tutorial or article detailing the process for current linux kernels,['c'] +464007,what is the convention in rails with asset pipeline for internationalization inside css i know css is not supposed to have content but it does like this nice box below extracted from the twitter bootstrap documentation css echo out a label for the example bsdocsexampleafter content examplei do not care for example i use something like that as a mixinbox legend echo out a label for the example after content legend then i do not need really dynamic css i can easily include the mixin in a class but instead of passing observation i need to pass t boxobservationobservation box t boxobservation rails is supposed to follow conventions over configuration it is very easy to just add a static csslescss and it is already included in all pages in a single minified css what is the convention for internationalized css for example where i am supposed to put declarations like that of observation,"['css', 'ruby-on-rails']" +464038,programmatically scroll to a supplementary view within uicollectionview i am using uicollectionview to thisplay photos in sections each section has a supplementary view as a header and is supplied via the method viewforsupplementaryelementofkind i have a scrubber on the side that allows the user to jump from section to section for now i am scrolling to the first item in the section using scrolltoitematindexpathatscrollpositionanimated but what i really want is to scroll the collectionview so that that sections header is at the top of the screen not the first cell i do not see an obvious method to do this with do any of you have a work aroundi suppose i could scroll to the first item of the section and then offset that by the supplementary height plus the offset between the items and header if it comes down to that there is a method for scrolling to point coordinates of the contentview however if there is a simpler way i would like to know thanks,"['iphone', 'ios']" +464137,changing file permission in python i am trying to change permission of a file accessoschmodpath modei want to make it read onlyoschmodpath 04is there any other way make a file read only,['python'] +464164,android holo loading spinner in css i need to know how can i make the android holo loading spinner in css without images i have tried but i do not know how can i do it this is what i need animated like in androidhow can i do it in css without images,['css'] +464185,hidden divs taking up space i have set up all my navigation for my website as hideshow divs using behavioursit all works pretty well but i have now realised the problem of the divs taking up space even when they are hidden extending the height of my wrapper far too muchi really want the height to extend and contract according to the amount of content on thisplaythe divs are absolutely positioned and set to visibilityhiddenany help appreciated please let me know if you need more info,['html'] +464246,how to convert country names to iso 31661 alpha2 values using python i have a list of countries likecountriesamerican samoa canada francei want to convert them like thiscountriesas ca fris there any module or any way to convert them,['python'] +464273,full screen dialogfragment over actionbar in android im having some problems in show dialogfragment in full screen in my application i have an fragment that when you click in some button it calls a dialogfragment but the dialogfragment just fills the area of the fragment below the action bar i would like it fills all the screen like that any help public class itensactivity extends fragment public void opendialogitens dialog new itemdialog dialogshowgetfragmentmanager getfragmentmanagerexecutependingtransactions public static class itemdialog extends dialogfragment suppresswarningsdeprecation override public dialog oncreatedialogbundle savedinstancestate alertdialogbuilder builder new alertdialogbuildergetactivity buildersetviewgetcontentview dialog dialog buildercreate dialogsetcanceledontouchoutsidetrue windowmanagerlayoutparams lp new windowmanagerlayoutparams lpcopyfromdialoggetwindowgetattributes lpwidth windowmanagerlayoutparamswrap content lpheight windowmanagerlayoutparamsfill parent dialoggetwindowrequestfeaturewindowfeature no title dialoggetwindowsetattributeslp return dialog private view getcontentview layoutinflater inflater getactivitygetlayoutinflater view view inflaterinflaterlayoutpopup item null return view,['android'] +464322,final variable case in switch statement final int a 1 final int b b 2 final int x 0 switch x case abreak ok case bbreak compiler error constant expression required compiler result constant expression required case bbreak 1 error why am i getting this sort of error if i would have done final int b 2 everything works,['java'] +464508,sql server querying hierarchical and referenced data i am working on an asset database that has a hierarchy also there is a referenceasset table that effectively points back to an asset the reference asset basically functions as an override but it is selected as if it were a unique new asset one of the overrides that gets set is the parent idcolumns that are relevant to selecting the heirarchyasset id primary parent idasset reference id primary asset id foreignkeyasset parent id always an assetedited 527 sample relevent table data after joins id asset id name parent id milestone type 3 3 suit null march shape 4 4 suit banker 3 april texture 5 5 tie null march shape 6 6 tie red 5 march texture 7 7 tie diamond 5 june texture 5 6 tie red 4 march texturethe id 0 like the last row signify assets that are referenced referenced assets have a few columns that are overidden in this case only parent id is importantthe expectation is that if i select all assets from april i should do a secondary select to get the entire tree branches of the matching queryso initially the query match would result in 4 4 suit banker 3 april texturethen after the cte we get the complete hierarchy and our result should be this so far this is working 3 3 suit null march shape 4 4 suit banker 3 april texture 5 6 tie red 4 march textureand you see the parent of id5 is there but what is missing that is needed is the referenced asset and the parent of the referenced asset 5 5 tie null march shape 6 6 tie red 5 march texturecurrently my solution works for this but it is limited to only a single depth of references and i feel the implementation is quite uglyeditedhere is my primary selection function this should better demonstrate where the real complication lies the assetreference select aid as id aid as asset id anameaparent id as parent id asubpath tname as typename a2name as parent name bname as batchname lname as locationnameaoowner name as ownername tid as typeidmname as milestonename adeleted as bdeleted 0 as reference wphase name wstatus namefrom asset as a inner join type as t on atype id tidinner join batch as b on abatch id bidleft join location l on alocation id lidleft join asset a2 on aparent id a2id left join assetowner ao on aowner id aoowner idleft join milestone m on amilestone id mmilestone idleft join workflow as w on wasset id aidwhere adeleted showdeletedunion select 1arid as id arasset id as asset id aname arparent id as parent id asubpath tname as typename a2name as parent name bname as batchname lname as locationnameaoowner name as ownername tid as typeidmname as milestonename adeleted as bdeleted 1 as reference null as phase name null as status namefrom asset as a inner join type as t on atype id tidinner join batch as b on abatch id bidleft join location l on alocation id lidleft join asset a2 on arparent id a2id left join assetowner ao on aowner id aoowner idleft join milestone m on amilestone id mmilestone idinner join assetreference ar on arasset id aidwhere adeleted showdeletedi have a stored procedure that takes a temp table temp and finds all the elements of the hierarchy the strategy i employed was thisselect the entire system heirarchy into a temp table treeids represented by a comma separated list of each entire tree branchget entire heirarchy of assets matching query from tempget all reference assets pointed to by assets from heirarchyparse the heirarchy of all reference assetsthis works for now because reference assets are always the last item on a branch but if they werent i think i would be in trouble i feel like i need some better form of recursion here is my current code which is working but i am not proud of it and i know it is not robust because it only works if the references are at the bottomstep 1 build the entire hierarchywith recursive cte as select castid as varchar100 as hierarchy parent id id from assetidswhere parent id is nullunion all select castparenthierarchy casttid as varchar100 as varchar100 as hierarchy tparent id tid from recursive cte parent inner join assetids t on tparent id parentidselect thistinct hid hierarchy as idlist into treeidsfrom select hierarchy id from recursive cte parent cross apply dbosplitidshierarchy as hstep 2 select the branches of all assets that match the queryselect thistinct lid into relativeids from treeidscross apply dbosplitidsidlist as lwhere treeidsid in select id from tempstep 3 get all reference assets in the branchesreference assets have negative id values hence the id 0 partselect asset id into reflinks from allassets where id in select allassetsasset id from allassets inner join relativeids on allassetsid relativeidsid where relativeidsid 0step 4 get the branches of anything found in step 3select thistinct lid into extrarelativeids from treeidscross apply dbosplitidsidlist as lwhere exists select reflinksasset id from reflinks where reflinksasset id treeidsid and not exists select id from relativeids where id treeidsidi have tried to just show the relevant code i am super grateful to anyone who can help me find a better solution,['sql'] +464521,releasing memory of huge numpy array in ipython update this problem solved itself after a machine reboot not yet able to figure out why this error was happening beforei have a function that loads a huge numpy array 980mb and returns itwhen i first start ipython and call this function it loads the array into the variable without any problembut if i run the same command again it exits raising a memory errori tried the followingdel hugearraystill the same error was occurringi even tried the followingdel hugearraygccollectgccollectinitially gccollect returned 145 and the second call returned 48but even after this when i call the function it was still raising a memory errorthe only way i could load again was to restart ipythonis there something i can do to free all memory in ipython so that i do not have to restart itupdatefollowing is the output of whosvariable type datainfogc module module gc builtingr module module generate4mramp rom generate4mramppycnp module module numpy from usagesnumpy init pycplt module module matplotlibpyplosmatplotlibpyplotpycout of this gr is my module containing the function which i used to load the data cubehow to reproduce the errorthe following simple function is able to reproduce the errorimport numpy as npimport gcdef functionh cubenpzeros20010241024 return cubetestcubefunctionh runs without any issue del testcubetestcubefunctionh raises memory errordel testcubegccollectgccollecttestcubefunctionh still raises memory errorthis error is occurring only in ipython in simple python after giving del testcube there is no memory error,['python'] +464583,c stdmap get values whose key starts with a particular string i am using stdmap in such a wayinclude mapinclude stringinclude iostreamusing namespace stdint mainint argc char argv mapstring int my map my mapinsertpairstring intab 1 my mapinsertpairstring intabb 2 my mapinsertpairstring intabc 3 my mapinsertpairstring intabd 4 my mapinsertpairstring intac 5 my mapinsertpairstring intad 5 coutmy maplower boundabsecondendl coutmy mapupper boundabsecondendl return 0i would like to get all values whose key starts with a particular string for example ab i can easily get the begin iterator using maplower bound but how can i get an upper bound do i have to iterate the whole set starting at lower bound and check every key if it still starts with ab,['c++'] +464588,android thistributed application primary key strategy i am going to implement a thistributed application with multiple mobile clients and a web based server application so each client and also the server are allowed to generate table entries therefore i need unique primary keys over all participants and i want to be able to generate keys offlinewhat is the best approach for generating primary keys you are using on thistributed environments for a similar question see what is the best primary key strategy for an onlineoffline multiclient mobile application with sqlite and azure sql database as the central storei am aware that uuid key generation is a good approach for that scenario but i want to stick to a key with name id and type long as suggested by the android platformi do not want to have a composite id with device also server is a device id and local id this approach wouldnt work well anyway since the server should be able to generate entries for a certain client in that case i would have to use the device id also on the servertherefore my current favorite is to build my key with datatype long i did this before in another project i think i will use the highlow approach see for example here whats the hilo algorithm and have a key which consists ofclient id eg 28 bits generated from the server low value eg 4 bits incremented on client never persistedhigh value eg 32 bits incremented on client persisted on client onlythe client id must be fetched from the server at first start of the mobile application so the first start needs a network connection this might be a downside of this approach when having the client id on the device i can generate keys without a network connectionnormally the high id is a unique value over the database when a user deinstalls the application and installs it again i have to treat him as a new client and have to give him a new client id otherwise i would have to save the current high id on the server to be able to restore it on loss or on reinstallation not worth the effortwhat is the best approach for getting the high id on android an autoincrement key is not a solution i need something like a generator function and it has to be executed inside its own transaction not the user transaction has anyone experiences with that approach on android and can anyone point me in the right direction i only found this answerwhat key strategy are you using for your multi client application online and offline,['android'] +464592,change backgroundcolor with jquery mobile i want to change the global backgroundcolor for my app but things do not workadding css to the body does not work neither does adding css to html elementbody backgroundcolor2b2e31adding ids to my divelements works sometimes but i am not gonna add an id to all my elementsdoes anybody know how to solve this,['jquery'] +464627,android how to draw view over top of everything i want to make an app that can create notification on the screen on top of anything that is currently being thisplayedsomething like this app drawn elements called as chat head or like the go sms message popupit would be even better if it is possible to draw it dynamically including touch events etcwhat is the conventional or standard way to do thisexample like an icon that can be clicked or dragged no matter whether you are on homescreen or app drawer or other appseditsincere apologies i should have added these pictures earlierpay attention to the circular icons near the edges of the screen you can drag them anywhere in any appsee this image link,"['java', 'android']" +464692,find out if matrix is positive definite with numpy i need to find out if matrix is positive definite my matrix is numpy matrix i was expecting to find any related method in numpy library but no success i appreciate any help,['python'] +464760,how to upload multiple files with zend framework even if i select 2 or more images only one gets uploadedi have a simple formform actionimagesthumbs methodpost enctypemultipartformdata input namefile idfile typefile multiple input typesubmit nameupload images valueupload imagesformthen in my controllerpublic function thumbsaction request thisgetrequest if requestispost if isset postupload images names filesfilename the names will be an array of names foreachnames as name path application pathpublicimgname echo path will return all the paths of all the images that i selected uploaded application model functionsuploadpath echo uploaded will return true as many times as i select pictures though only one file gets uploaded and the upload methodpublic static function uploadpath upload new zend file transfer adapter http uploadaddfilterrename array target path overwrite true try uploadreceive return true catch zend file transfer exception e echo emessage any ideas why i get only one file uploaded,['php'] +464773,creating native iosandroid apps from html5 is there a toolapproach to automatically generate an app on an ios or android device from html5 or jquery mobile code so that the app loadsruns entirely on the mobile device itself without requiring web access and without the corresponding delay in load time ie not a webappi have looked into a whole range of tools for this html5 jquery mobile triggerio phonegap appcelerator others and read lots of documentation and stackoverflow and other forum posts however i have not yet been able to find the answer to this very basic questionmany of the tools out there eg triggerio boast that they are creating native apps however when i built a sample ios app to try to answer the question above for myself the app will only run properly when the device is connected to the web leading me to assume that it is actually a hybrid or webapp with some native componentsfunctionalityi suppose that for folks who have been developing apps for some time this is supposed to be obvious but for somebody starting from fresh it is notare the existing tools able to essentially translate html5jquery mobile into objective c or just linke to web contentis it possible to create a mobile app using the easytouse crossplatform tools that exist i especially like jquery mobile and codiqa as i was able to build a prototype so quickly that runs fully locally on an ios or android device or do you end up having to manually code the app eg in objective c if you want it to be fully local to the device not a webapp thanks,['ios'] +464776,using rethis as a cache for a mysql database i need to create a solution using php with a mysql database with lots of data my program will have many requisitions i think that if i work with cache and an oo database i will have a good result but i do not have experiencei think for example if i cache the information that is saved in mysql in a rethis database performance will be improved but i do not know if this is a good idea so i would like someone to help me to choosesorry if my english is not very good i am from brazil,['php'] +464904,check if java arraylist contains object consider i have object aint elementa int elementb these objects are stored in an arraylist arraylista listobjhow can i perform contains operation just using part of object a properties eg considering only elementa for finding if object newaelementa is already in the listfor object a i have defined equal where i consider only the elementa part of object a however this is not enough so it would be nice to get some ideas how contains can be applied and used for parts of objects writing my own function is an option however interesting if standard functionality could deal with this problem,['java'] +464920,get filename without extension from full path i am making a program to store data from excel files in database i would like the user to give in console the full path of the file and after the program to take only the file name to continuethe code for loading the full path is string strfullpath scanner scanner new scannersysteminsystemoutprintlnplease enter the fullpath of the filestrfullpath scannernextlinestring file strfullpathsubstringstrfullpathlastindexof 1systemoutprintlnfilesubstring0 fileindexofafter that i would like to have string filename the full path that the user would type would be like this cusersmyfilesdocumentstest9xlsthe filename that i would create would take only the name without the xlscould anyone help me how i would do thishow i would do it if i would like to take as filename test9xls a,['java'] +464955,jquery serialize exclude all elements within divclassname i am trying to exclude invisible form values from serialize jquery output invisible inputsselects are inside divuitabshide divs not the children of it but descendants so basically i need to include all elements input select witin divs without uitabshide class and exclude all elements input select within divs with uitabshide class in one form right now with what i tried it includes all form elements but i think i did not specify selectors right see below the code to reproduce the issuedoctype htmlhtml head script srcscript script typetextjavascript documentreadyfunction var formdata outboundcallnotuitabshide input uitabshide selectserialize consolelogformdata script meta charsetutf8 titlejs bintitle head body form idoutboundcall div classcontent div classtabs uitabs uiwidget uiwidgetcontent uicornerall ul classuitabsnav uihelperreset uihelperclearfix uiwidgetheader uicornerall li classuistatedefault uicornertop uitabsselected uistateactive a hreftabs1credit carda li li classuistatedefault uicornertop a hreftabs2chequea li li classuistatedefault uicornertop a hreftabs3direct debita li ul div idtabs1 classuitabspanel uiwidgetcontent uicornerbottom input typehidden value1 nameleadpaymentmethod div div idtabs2 classuitabspanel uiwidgetcontent uicornerbottom uitabshide pcheque functionality is not currently availablep div div idtabs3 classuitabspanel uiwidgetcontent uicornerbottom uitabshide input typehidden value3 nameleadpaymentmethod div div div form bodyhtmlhere is jsbin with this code,"['javascript', 'jquery', 'html', 'css']" +465003,i can not run c3p0connectionprovider my hibernatecfgxmlproperty nameconnectiondriver classorgpostgresqldriverproperty property nameshow sqltrueproperty property nameconnectionurljdbcpostgresqllocalhost5432piratesproperty property nameconnectionusernamepostgresproperty property nameconnectionpasswordm8property property namedialectorghibernatedialectpostgresqldialectproperty property nameshow sqlfalseproperty property namehbm2ddlautoupdateproperty property namecurrent session context classthreadproperty property nameconnectionprovider classorghibernateconnectionc3p0connectionproviderproperty property namehibernatec3p0min size5property property namehibernatec3p0max size200property property namehibernatec3p0timeout300property property namehibernatec3p0max statements50property property namehibernatec3p0idle test period30property property namehibernategenerate statisticstruepropertymy libraryhibernatecommonsannotations401finaljarhibernatecore4110finaljarhibernatejpa20api101finaljarhibernatevalidator420finaljarjbossjta4164finaljarjbosslogging310gajarjbosstransactionapi 11 spec100finaljaropenjdk6b14jarvalidationapi100gajarhibernatec3p04110finaljarand my error29042013 140243 orghibernateservicejdbcconnectionsinternalconnectionproviderinitiator getconfiguredconnectionprovidernamewarn h0208 orghibernateconnectionc3p0connectionprovider has been deprecated in favor of orghibernateservicejdbcconnectionsinternalc3p0connectionprovider that provider will be used instead29042013 140243 orghibernateservicejdbcconnectionsinternalconnectionproviderinitiator instantiateexplicitconnectionproviderinfo h0130 instantiating explicit connection provider orghibernateservicejdbcconnectionsinternalc3p0connectionproviderfailed to create sessionfactory objectorghibernateservicespiserviceexception unable to create requested service orghibernateservicejdbcconnectionsspiconnectionprovider29042013 140243 orgapachecatalinacorestandardwrappervalve invokesevere servletservice for servlet request in context with path pirates threw exception servlet execution threw an exception with root causejavalangclassnotfoundexception could not load requested class orghibernateservicejdbcconnectionsinternalc3p0connectionprovider at orghibernateserviceclassloadinginternalclassloaderserviceimpl1findclassclassloaderserviceimpljava99 at javalangclassloaderloadclassunknown source at javalangclassloaderloadclassunknown source at javalangclassforname0native method at javalangclassfornameunknown source at orghibernateserviceclassloadinginternalclassloaderserviceimplclassfornameclassloaderserviceimpljava138 at orghibernateservicejdbcconnectionsinternalconnectionproviderinitiatorinstantiateexplicitconnectionproviderconnectionproviderinitiatorjava189 at orghibernateservicejdbcconnectionsinternalconnectionproviderinitiatorinitiateserviceconnectionproviderinitiatorjava114 at orghibernateservicejdbcconnectionsinternalconnectionproviderinitiatorinitiateserviceconnectionproviderinitiatorjava54 at orghibernateserviceinternalstandardserviceregistryimplinitiateservicestandardserviceregistryimpljava69 at orghibernateserviceinternalabstractserviceregistryimplcreateserviceabstractserviceregistryimpljava176 at orghibernateserviceinternalabstractserviceregistryimplinitializeserviceabstractserviceregistryimpljava150 at orghibernateserviceinternalabstractserviceregistryimplgetserviceabstractserviceregistryimpljava131 at orghibernateenginejdbcinternaljdbcservicesimplbuildjdbcconnectionaccessjdbcservicesimpljava223 at orghibernateenginejdbcinternaljdbcservicesimplconfigurejdbcservicesimpljava89 at orghibernateserviceinternalstandardserviceregistryimplconfigureservicestandardserviceregistryimpljava75 at orghibernateserviceinternalabstractserviceregistryimplinitializeserviceabstractserviceregistryimpljava159 at orghibernateserviceinternalabstractserviceregistryimplgetserviceabstractserviceregistryimpljava131 at orghibernatecfgsettingsfactorybuildsettingssettingsfactoryjava71 at orghibernatecfgconfigurationbuildsettingsinternalconfigurationjava2277 at orghibernatecfgconfigurationbuildsettingsconfigurationjava2273 at orghibernatecfgconfigurationbuildsessionfactoryconfigurationjava1742 at hibernatehibernateinitfactoryhibernatejava39 at hibernatehibernategetfactoryhibernatejava23 at hibernatehibernateopensessionhibernatejava49 at actionactioninitactionjava96 at actionactionperformactionactionjava65 at servletsrequesthandlerservletservicerequesthandlerservletjava39 at javaxservlethttphttpservletservicehttpservletjava722 at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava305 at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava210 at orgapachecatalinacorestandardwrappervalveinvokestandardwrappervalvejava225 at orgapachecatalinacorestandardcontextvalveinvokestandardcontextvalvejava169 at orgapachecatalinaauthenticatorauthenticatorbaseinvokeauthenticatorbasejava472 at orgapachecatalinacorestandardhostvalveinvokestandardhostvalvejava168 at orgapachecatalinavalveserrorreportvalveinvokeerrorreportvalvejava98 at orgapachecatalinavalvesaccesslogvalveinvokeaccesslogvalvejava927 at orgapachecatalinacorestandardenginevalveinvokestandardenginevalvejava118 at orgapachecatalinaconnectorcoyoteadapterservicecoyoteadapterjava407 at orgapachecoyotehttp11abstracthttp11processorprocessabstracthttp11processorjava9 at orgapachecoyoteabstractprotocolabstractconnectionhandlerprocessabstractprotocoljava565 at orgapachetomcatutilnetjioendpointsocketprocessorrunjioendpointjava307 at javautilconcurrentthreadpoolexecutorworkerruntaskunknown source at javautilconcurrentthreadpoolexecutorworkerrununknown source at javalangthreadrununknown source,['java'] +465011,how to use link to with nested resources i am a totally newbie in railsi have created a web application i can access through posts123comments or posts123commentsnew but i do not know how to use link to in the index view to show a concrete comment when i try to link it appears no route or undefined symboli have a nested have many relation between posts and comments defined in the models and in the routesrb and post comments get postspost idsensorsformat commentsindex appears when i execute rake routeshow i can do it,"['ruby-on-rails', 'ruby']" +465053,get inapp billing user account details i am creating an android application that implements subscriptions to digital content on my backend server what i wish to do is obtain the name and email associated with the play account that made the purchase namely the same information i can get if i go to my merchant account and view an orderusing the trivialdrive inapp billing example i am able to access the inapp purchase data and send that information to my backend server as the checking subscription documentation recommends subscriptionshtmlthe documentation lists a typical implementation workflow and sayswhen the user successfully purchases a new subscription your app notifies a backend server which stores the purchase token user name and other information in a secure locationalthough i can store the purchase token and other inapp purchase data how do i obtain the user name or email for that matter from what i can piece togehter i suspect the account details like user name email subscripion expiration date must be requested from my back end server it seems using the purchase token on my backend server is the key to accessing order information but at this point i have not found any clear way to go about doing this any suggestions would be appreciatedregards,['android'] +465073,is passing a reference through function safe is the following function safe in c03 or c11 or does it exhibit ubstring const minstring const a string const b return a b a bint main cout mina bis it ok to return a reference to an object passed to the function byreference is it guaranteed that the temporary string object isnot destroyed too soonis there any chance that the given functionmin could exhibit ub if it does not in the given context is it possible to make an equivalent but safe function while still avoidingcopying or moving,['c++'] +465094,css3 flexbox thisplay box vs flexbox vs flex i became yesterday a website in the school which use the css3 flexbox statement i never used that before so i google it a bit and found a lot of different styles of the flexbox statementssome guys write thisplay box some use thisplay flexbox and other thisplay flexso what are the differents which i should use,['css'] +465097,relative path with pragma commentlib using visual studio 2010 i would like to specify a path in a pragma commentlib relative to the cpp file including iti triedpragma commentlib file foolibin foocpp and it seems to work however this appears hackish to meis there a less hackish way,['c++'] +465144,why does not java allow casting boolean int i was wondering why java does not allow casting from a boolean to an int like soboolean foo trueint bar intfoothis can be done in one line of code for examplebar foo 1 0but it seems like an better and easiertoread way would be to allow typecasting as with double and int why does not java include this feature,['java'] +465158,find centerpoint of polygon in javascript i have a place object from google maps which has a set of coordinates that represent a bounding box for a given location say london each set of coordinates has a latitude and longitudei have written the below code to find the centerpoint but i am not sure if it does actually produce the centerpoint what if the polygon has 5 points instead of 4 also can this be done in a more efficient way with less operationsfunction averagearray add together and then divide by the length return reducearray function sum num return sum num 0 arraylength i have a twodimensional array that i want to get the average ofvar coords 12 51 13 52 18 59 19 58 so i get the first columnvar lats coordsmapfunction coord return coord0 then the secondvar longs coordsmapfunction coord return coord1 and average each column outconsolelogaveragelats averagelongsexample,['javascript'] +465174,most efficient way to loop through an eigen matrix i am creating some functions to do things like the separated sum of negative and positive number kahan pairwise and other stuff where it does not matter the order i take the elements from the matrix for exampletemplate typename t int r int cinline t sumconst eigenmatrixtrc xs t sump0 t sumn0 for size t i 0 nrows xsrows ncols xscols i nrows i for size t j 0 j ncols j if xsij0 sump xsij else if xsij0 ignore 0 elements improvement for sparse matrices i think sumn xsij return sumpsumnnow i would like to make this as efficient as possible so my question is would it be better to loop through each column of each row like the above or do the opposite like the the followingfor size t i 0 nrows xsrows ncols xscols i ncols i for size t j 0 j nrows ji suppose this depends on the order that the matrix elements are allocated in memory but i could not find this in eigens manualalso are there other alternate ways like using iterators do they exist in eigen that might be slightly faster,['c++'] +465314,angularjs location service apparently not parsing url i am using angular in an application which is basically a table with search results access to this table can be achieved via an url like httpmyappclientclientnamean angular controller is instantiated for the table among other things for opening a modal dialog also angularbased with bootstrapui with the row detailsthese row details are brought via a service which has some common functionality for both controllers the one for the table and the one for the modalnow within this service i have the following snippet to retrieveservicefetchrelatedelements functionelement cb var url searchjsonresults20typeelementtype if locationsearchclient url client locationsearchclient return dofetchurl cb actual server json getthe goal is to know if the table already has this specific client parameter set as a filterif i put a breakpoint at the beginning of this call i see that locationabsurl returns the current browser url which in my case has the client parameter i am interested inbut locationsearch returns an empty objecti am injecting the location service within my service with the defaults that is not configuring it by a config calland as doc says the location service parses the url in the browser address bar based on the windowlocation and makes the url available to your applicationam i missing something should not the url at this point be parsedthanksupdate i have managed to make it work the problem was exactly that i was not configuring at all the service i did so because i assumed that in that way it would take defaults but it seems that that is not the way it works,['javascript'] +465371,randomly colored us map using jvector i have issues with coding us map that would allow randomly assing colors to the us states map using jvector api here is the codehtml script srcscriptsjquery182jsscript script srcscriptsjqueryjvectormap122minjsscript script srcscriptsjqueryjvectormapusaeaenjsscriptbody div idusmap styleposition relative width 800px height 600pxdiv script i commented out this piece of script it works fine this is a test trial to load the map function usmapvectormapmap us aea en i have issues with the following function it does not even load the map what it should do is to generate random colors for the map as the update button is pressed function var palette 66c2a5 fc8d62 8da0cb e78ac3 a6d854 generatecolors function var colors key for key in mapregions colorskey palettemathfloormathrandompalettelength return colors map map new jvmusmap map us aea en container map series regions attribute fill mapseriesregions0setvaluesgeneratecolors updatecolorsbuttonclickfunctione epreventdefault mapseriesregions0setvaluesgeneratecolors script div bodyhtmlhere is the link to my scripts folder where i keep the js fileswhat is wrong with the function,['javascript'] +465415,how to hide the softkey bar on android phone awhen my app starts i would like to hide the soft keys bar in red rectangle to have a larger screenhow can i hide itdo i need to show the bar purposely when the app quits or it will restore itself automatically after the app quitsandroid 41 with no hardware keys on phone front,['android'] +465521,numerical integration over a matrix of functions sympy and scipy from my sympy output i have the matrix shown below which i must integrate in 2d currently i am doing it elementwise as shown below this method works but it gets too slow for both sympympmathquad and scipyintegratedblquad for my real case in which a and its functions are much bigger see edit belowfrom sympy import matrix sin cosimport sympyimport scipysympyvar x t a matrixsin201xsintxcos201xcostxcos301xcost cos201xsintxsin201xcostxsin301xcost cos201xsintxcos201xsintxsin301xsint integration intervalsx1x2t1t2 30 75 0 2scipypi elementwise integrationfrom sympyutilities import lambdifyfrom sympympmath import quadfrom scipyintegrate import dblquada int1 scipyzeros ashape dtypefloat a int2 scipyzeros ashape dtypefloat for ij expr in scipyndenumeratea tmp lambdify xt expr math a int1ij quad tmp x1 x2 t1 t2 or in scipy a int2ij dblquad tmp t1 t2 lambda xx1 lambda xx2 0i was considering doing it in one shot like but i am not sure if this is the way to goa eval lambdify xt a math a int1 sympyquad a eval x1 x2 t1 t2 or in scipya int2 scipyintegratedblquad a eval t1 t2 lambda x x1 lambda x x2 0editthe real case has been made available in this link just unzip and run shadmehri 2012py is the author from were this example was taken from shadmehri et al 2012i have started a bounty of 50 for the one who can do the followingmake it reasonably faster than the proposed questionmanage to run without giving memory error even with a number of terms m15 and n15 in the code i managed up to m7 and n7 in 32bitthe current timing can be summarized belowmeasured with m3 and n3 from there it can be seen that the numerical integration is the bottleneckbuild trial functions 0evaluating differential equations 2lambdifying k1 22integrating k1 74lambdifying and integrating k2 2extracting eigenvalues 0related questions about lambdify,['python'] +465552,error using etree in lxml i want to use xpath in python i triedimport xmletrelementtree as etsince this library has limited usage i had to use lxml after a long session of search on google i had several problems during installation and finally i installed lxml but when i use from lxml import etreeit throws back an error as below could you please tell me the solution to this problemtraceback most recent call lastfile pyshell0 line 1 in modulefrom lxml import etreeimporterror dll load failed 1 is not a valid win32 applicationcan any1 tell me what the problem would bethanks for assistance,['python'] +465574,post image in instagram question in my app i need to post image in instagram just like fb or twitterwhat i have already done login and fetched photographs from the instagram to my own app but not getting any way for image posting in instagram,['android'] +465579,what memory management algorithms are used by the major compiler vendors this is a subset of a previous questionas an exercise i am writing a memory manager that is the code which implements malloc realloc and free or new and delete the rtl for my language delphi allows the rtls memory manager to be replaced easily for those of you using c this is similar to but lowerlevel than overriding new and delete it hooks into the rtl itself rather than being a language featurei am looking for resources about highquality approaches others have taken to the same problem and am trying to find out what algorithms other major compiler vendors use while delphis is well documented i cannot find any information about the implementations used by ms vc net or objective c these vendors do not seem to allow their rtl to be hooked into like delphi does all documentation seems to be higherlevel such as nsautoreleasepool to pick a random example far too highlevel for this questionwhat memory management algorithms do major vendors microsoft vc and net and apple objective c use in their runtime libraries embarcadero delphi and c builder is well documentedlinuxseems to use buddy although i suspect this information is out ofdatems vc unknownnet unknownobjective c unknownan example of a great answer would be a document describing the memory manager implementation such as this one or a link to a published paper an example of a useful answer would be the algorithm the vc runtime uses the hoard allocator,['objective-c'] +465598,image upload from iphone strips exif data i have built a website which allows image uploading and once an image is uploaded some specific information about the photo is thisplayeduploading pictures from computers works just fine the problem comes up when i am trying to upload an image from a smartphone the upload success but it seems like a major part of the data that is thisplayed when uploading from computer is now missingthis code section is the one that actually retrieves and thisplay the data location filespictmp namedata exif read datalocationvar dumpdatathe var dumpdata actually dumps different data in computers and smartphonesedit apparently it works just fine with andoroid smartphones the problem only comes up when i try to upload images from iphonefor example var dump from computer upload array49 filename string10 php2d4tmp filedatetime int1367318152 filesize int30357 filetype int2 mimetype string10 imagejpeg sectionsfound string24 any tag ifd0 exif gps computed array6 html string24 width320 height240 height int240 width int320 iscolor int1 byteordermotorola int1 aperturefnumber string5 f28 make string5 apple model string8 iphone 4 orientation int3 xresolution string4 721 yresolution string4 721 resolutionunit int2 software string5 613 datetime string19 20130426 235743 ycbcrpositioning int1 exif ifd pointer int204 gps ifd pointer int594 exposuretime string4 115 fnumber string4 145 exposureprogram int2 isospeedratings int10 exifversion string4 0221 datetimeoriginal string19 20130426 235743 datetimedigitized string19 20130426 235743 componentsconfiguration string4 shutterspeedvalue string9 48891250 aperturevalue string9 42811441 brightnessvalue string10 35811451 meteringmode int5 flash int24 focallength string5 7720 subjectlocation array4 0 int1295 1 int967 2 int699 3 int696 flashpixversion string4 0100 colorspace int1 exifimagewidth int2592 exifimagelength int1936 sensingmethod int2 exposuremode int0 whitebalance int0 focallengthin35mmfilm int35 scenecapturetype int0 gpslatituderef string1 n gpslatitude array3 0 string4 311 1 string8 5854100 2 string3 01 gpslongituderef string1 e gpslongitude array3 0 string4 341 1 string8 4684100 2 string3 01 gpstimestamp array3 0 string4 201 1 string4 571 2 string8 4272100 gpsimgdirectionref string1 t gpsimgdirection string9 48089465 var dump from smartphone uploadarray12 filename string9 phpszwfpw filedatetime int1367318054 filesize int1778041 filetype int2 mimetype string10 imagejpeg sectionsfound string19 any tag ifd0 exif computed array5 html string26 width2592 height1936 height int1936 width int2592 iscolor int1 byteordermotorola int1 orientation int3 exif ifd pointer int38 colorspace int1 exifimagewidth int2592 exifimagelength int1936 heres the computer var dump files array1 pic array5 name string18 leaf2jpg type string10 imagejpeg tmp name string14 tmpphpzedus9 error int0 size int46439 heres the iphone results var dump files array1 pic array5 name string9 imagejpg type string10 imagejpeg tmp name string14 tmpphplpuzky error int0 size int14577 edit here is the uploading form html code form actionresultsphp iduploadimage methodpost enctypemultipartformdata div classfileupload fileuploadnew dataprovidesfileupload div classfileuploadpreview thumbnail stylewidth 200px height 150pxdiv div span classbtn btnfilespan classfileuploadnewselect imagespanspan classfileuploadexistschangespaninput typefile namepic idpic acceptimagespan a href classbtn fileuploadexists datathismissfileuploadremovea button typesubmit classbtnuploadbutton br span classuploaderrorspan div formwhat might cause it,"['php', 'jquery', 'iphone']" +465627,macro representing maximum value for uint64 t i am seeking for a macro representing the maximum value of uint64 t as uint max is for unsigned intie i need this value to guaranteed to be 1641i tried to use uint64 max but compiling with g results in uint64 max was not declared in this scopeit is worth to mention that i have this line define stdc limit macros in the code before using uint64 maxi was surprised to not find helpful information around the web about it,['c++'] +465632,android actionbar showhide tabs dynamically is it possible to removerestore the tab bar from the action bar dynamically up to now i did this by changing the navigation mode of the action bar i used following code to remove and restore the tab baroverride public void restoretabs getsupportactionbar setnavigationmodeactionbarnavigation mode tabs thissupportinvalidateoptionsmenuoverridepublic void removetabs getsupportactionbar setnavigationmodeactionbarnavigation mode standard thissupportinvalidateoptionsmenuthat works but there is a big problem everytime i call setnavigationmode ontabselected is called in the tablistener and the currently opend tab gets recreated,['android'] +465686,gridlayout vs tablelayout i am unsure as to what the differences between the two of them are and which i should use for my purpouseswhat i am trying to do is create a custom virtual numpad with text inputs and that can dynamically change its contents to have a date pickerso i need a layout system which supports many different sized cells inside itwhich better suits my needs and whats the difference,['android'] +465759,how to stop and reverse a uiview animation i have animated a uiview so that it shrinks when the user touches a toggle button and it expands back to its original size when the user touches the button again so far everything works just fine the problem is that the animation takes some time eg 3 seconds during that time i still want the user to be able to interact with the interface so when the user touches the button again while the animation is still in progress the animation is supposed to stop right where it is and reversein the apple qas i have found a way to pause all animations immediatelybut i do not see a way to reverse the animation from here and omit the rest of the initial animation how do i accomplish this ibactiontogglemeteridsender if selfmyviewhidden selfmyviewhidden no uiview animatewithduration3 animations selfmyviewtransform expandmatrix completionnil else uiview animatewithduration3 animations selfmyviewtransform shrinkmatrix completionbool finished selfmyviewhidden yes,['ios'] +465805,real time vectorbased osm renderer in ios using opengl es i am looking into a solution that will allow to use openstreetmap data to render a 2d topview vectorbased map in ios instead of using prerendered tiles from a server similar to apple and google maps in ios6i have done extensive research on this matter but did not found too much informationthere are a number of ios apps that do this but no information on how they implement it a couple of these apps areforevermap 2 by skobblergalileo offline mapsoffmaps 2the first 2 apps work similar to apple and google maps the map is drawn in real time whenever the zoom changesthe last one appears to be using a slightly different approach it renders the vector data at specific zoom levels and creates tiles which are then used as normal tiles downloaded from a tile server so the rendering engine could actually be a tile source for the routeme library but instead of downloading the tiles it renders them on the flythe first method is preferredq i guess one could switch between methods fairly easy once the opengl es renderer is in place i mean you could use the renderer as a source for routeme to create tiles or you could use it as a realtime drawer similar to a game am i rightthe closest solution i found is openstreetpad however it is using core graphics instead of opengl es so the rendering is not hardware acceleratedmapbox stated they are working on vector tiles and they will probably provide an ios solution for rendering however it may use mapnik so i am not sure how efficient will that be and there is no eta on since mid 2013q do you know of any other libraries papers guides examples or some other useful information on how to approach this basically how to handle the osm data and how to actually use opengl es glkit to draw that data on the device maybe some of the people who have done it can share a few things,['ios'] +465808,how to check against all joins when generating a score using mysql i am finding this fairly hard to explain so please bare with me herei am using mysql to generate a score for each result returned by a query the results are then ordered by the score the part that does not seem to be working properly is when i am trying to add a score for each tag that has been searched and the result is assigned to so lets say i do a search for the tags example test and tag and one of my results is assigned to the tags example test someothertag it should come up with a score of 10 since there are 2 matcheswhat is actually happening is i am getting a score of 5 if there is a match regardless of how many tags are matched and 0 if no tags are matchedhere is an example of one of the queries that is generated from a search select thistinct results 5matchtagsname againstself employed in boolean mode 5matchtagsname againstrental income in boolean mode 5matchtagsname againstcommission income in boolean mode 5matchtagsname againstbankruptcy in boolean mode 5matchtagsname againstcondo approval in boolean mode 1usefulness 10shares as score from results inner join categories c on resultsid cresult id inner join tags on resultsid tagsresult id where cname in purchase condo va and tagsname self employed or tagsname rental income or tagsname commission income or tagsname bankruptcy or tagsname condo approval and resultsscope all or resultsscope hi and published 1 group by resultsid having countthistinct cc id 3 order by score desc limit 8 offset 0,['mysql'] +465824,how to install phpunit with wamp i am a newbie programmer and i have tried for an embarrassingly long time to get phpunit set up and working with wamp i have read the documentation and went through various sites to see what i am doing wrong but i give up i need someone to explain this to me like i am mildly retardedi have probably seen all the guides on how to set it up but feel free to link me to something you believe is foolproof,['php'] +465880,jasperreports images are always blurry a simple report with only a png in itpngs dpi is 96 which looks pretty sharp however every time i export the report be it to docx or to pdf only an awfully blurry image appearsi have tried settingnetsfjasperreportsimagedpi to 300 and to 96both in ireports and directly on the reports jrxml as a propertynothing worksexceptioni have lost many days googling this matter but still no answersupdate 1i have been able to trace the cause of this strange behavior to itext it seems that it has to do something with itupdate 2heres the jrxml codexml version10 encodingutf8jasperreport xmlns xmlnsxsi xsischemalocation namecarta policia pagewidth612 pageheight792 columnwidth572 leftmargin20 rightmargin20 topmargin20 bottommargin20 uuidfbda9a687549438ca8adb3aedaf0b2d4 property nameireportzoom value10 property nameireportx value0 property nameireporty value0 property nameireportbackgroundimage valuecusersthouworkspacecujillowebcontentresourcesreportsfondopng property nameireportbackgroundimageproperties valuefalsetrue0250 property namenetsfjasperreportsimagedpi value96 parameter namesubreport dir classjavalangstring isforpromptingfalse defaultvalueexpressioncdatacusersthouworkspacecujillowebcontentresourcesreportsdefaultvalueexpression parameter parameter namer radicado classjavalangstring parameter namesubreport data source classnetsfjasperreportsenginejrdatasource parameter namer asunto classjavalangstring parameter namer localidad classjavalangstring parameter namer image renderer classnetsfjasperreportsenginejrrenderable isforpromptingfalse parameter namer print background classjavalangstring background band height752 background title band height371 splittypestretch image scaleimagerealsize reportelement uuiddbadb5004011415bbd984236532783c4 x234 y147 width75 height63 imageexpressioncdatacusersthouworkspacecujillowebcontentresourcesreportsalcaldia mayorpngimageexpression image image scaleimageclip reportelement uuidecf7dbe3436941a8ba49db98ba5ef478 x309 y151 width75 height63 imageexpressioncdatacusersthouworkspacecujillowebcontentresourcesreportsalcaldia mayorjpgimageexpression image band title pageheader band splittypestretch pageheader columnheader band splittypestretch columnheader detail band height104 splittypestretch detail columnfooter band splittypestretch columnfooter pagefooter band height11 splittypestretch pagefooter summary band height209 splittypestretch summaryjasperreport,['java'] +465970,jquery autocomplete vs gmail autocomplete what makes gmail autocomplete much faster than jquery autocompleteeverytime i type something in jquery i need to pause for several millisecond noticeable stop before the choice come out compare to gmail where i do not need to stop typing,"['javascript', 'jquery']" +465995,how to addopen a bundle file in a test target i have a static library that gets linked to by an application the library code opens a file that is in bundle that is in the application bundle the opening is done asnsstring plistpath nsbundle mainbundle pathforresourceconfig oftypeplistthis is working finehowever i want to add some unit test code to the library and so i have a logic test target for it as the file is in the bundle for the application and not in the bundle for the static library i copied the configplist file and added it to the test code target via copy bundle resources however when i execute the test code the file cannot be found why is thatin that the above is confusing heres a summary of the workspace structureworkspace contains application project with application target which contains x configplist a library project which contains library target which contains the code opening the file in the bundle b test library target which contains y a copy of the configplist cso if i build x then when b runs it can find a but when i build y when it runs then b cannot find c,"['ios', 'objective-c']" +466083,file path or file location for java new file i have the following structure for my projectin eclipsemyporjectname src comexamplemyproject ajava comexamplemyprojectdata bxmlin ajava i want to read bxml file how can i do that specifically in ajava i used the following codedocumentbuilderfactory docbuilderfactory documentbuilderfactorynewinstancedocumentbuilder docbuilder docbuilderfactorynewdocumentbuilderdocument doc docbuilderparse new filedatabxmlthis code cannot find bxml however if i change the path to srccomexamplemyprojectdatabxml then it works the current location seems to be in the root of my project file but i see other peoples examples if bxml and ajava are in the same folder then we can directly use new filebxml but i try putting bxml in the same folder of ajava rather than putting in the sub folder but it still does not work if this works then in my case i should be able to use new filedatabxml right i really do not understand why this is not working,['java'] +466146,how to switch tabs programatically in android from fragment i have implemented a tabactivity which extends fragmentactivity it has 5 tabs each tab is a fragment what i am looking for is to switch between the tabs programaticallyfor eg if i am in tab4 on button click i want to move from tab4 to tab1 tried a lot but could not find the solution for thistried with the following but id does not helpsfrom secondtabpublic void switchtabinactivitystring value firsttab parent parent firsttab getactivitygetparent parentswitchtabvaluetabactivity to change tabpublic void switchtabstring tabno thisontabchangedtabno,['android'] +466180,sort string as number in sql server i have a column that contains data like this dashes indicate multi copies of the same invoice and these have to be sorted in ascending order7907117901091790109117901092i have to sort it in increasing order by this number but since this is a varchar field it sorts in alphabetical order like this7901091790109117901092790711in order to fix this i tried replacing the dash with empty and then casting it as a number and then sorting on thatselect castreplaceinvoiceid as decimal as invoicesortorder by invoicesort ascwhile this is better and sorts like this invoicesort790711 790711 this is wrong now as it should come later than 7901097901091 79010917901092 790109279010911 79010911someone suggested to me to split invoice id on the dash and order by on the 2 split partslike order by split1 ascsplit2 asc 7901091 which would work i think but how would i split the column the various split functions on the internet are those that return a table while in this case i would be requiring a scalar functionare there any other approaches that can be used the data is shown in grid view and grid view does not support sorting on 2 columns by default i can implement it though so if any simpler approaches are there i would be very niceedit thanks for all the answers while every answer is correct i have chosen the answer which allowed me to incorporate these columns in the gridview sorting with minimum re factoring of the sql queries,['sql'] +466288,why need to use semicolon before defining a function i have seen some strange at the beginning of a function in some jquery plugins source code like thisfunction can someone explain why they need to use in this case,"['javascript', 'jquery']" +466308,android oncreate is called after locking the screen when i lock the screen while my app is running on top the system calls almost immediately oncreate screen is still black what could be the reason for this destructive behaviour,['android'] +466386,100 height div between header and footer i am trying to create a webpage layout with a headerfooter 100 width 145px height a main area between the headerfooter 100 width dynamic height and a container around the content that is a unique background color 860px width dynamic height but is always flush against the footer see example for a visual the problem i am having is i cannot seem to have the content container always be flush with the footer when there is minimal content using a setup like the original example results in the footer floating over the content if there is a respectablenormal amount of content or if the window is resizedand the following css results in a gap between the content and the footerhtmlbody margin0 padding0 height100 backgroundyellowwrap minheight100 positionrelativeheader backgroundblue padding10px content height100 width 400px margin0 auto backgroundorange padding30pxfooter backgroundblue positionabsolute bottom0 width100 height60pxhow can i make the content container be the full height of the screen when content is minimal and have the footer stick to the bottom of the page while also being dynamic to resize appropriately if there is a normal amount of content footer is always at the bottom of the contentthank you,"['html', 'css']" +466413,submitting html form using jquery ajax im trying to submit a html from using ajax by using this example my html codeform idformoid actionstudentforminsertphp title methodpostdivlabel classtitlefirst namelabelinput typetext idname namename divdivlabel classtitlenamelabelinput typetext idname2 namename2 divdivinput typesubmit idsubmitbutton namesubmitbutton valuesubmitdivmy scriptscript typetextjavascript documentreadyfunction formoidajaxformfunction alertthank you for your comment scriptthis is not working i am not getting even the alert messageand when i submit i dont want to call another page i just want to show alert messageis there a simple way of doing itps i have several fields just put 2 as an example,['jquery'] +466424,stop page from scrolling if hovering div i have a div that is scrollable but whenever you reach the bottomtop of it it begins to scroll the entire page that could be annoying for users who scroll fast and then the entire page starts scrolling unexpectedlyi need something where if you are hovering over the div the page is not scrollablei have tried this by adding css when i hover the divbody overflowhiddenit works but there is one problem the scrollbar thisappears and that looks kind of stupid to have it thisappearingreappearing any way to achieve the same effect but keep the scrollbar visible i have seen it done with facebook chat,"['javascript', 'jquery', 'html', 'css']" +466514,cannot cancel bluetooth thiscovery process i need to do a scan of bluetooth devices in the surrounding area for 6 to 12 seconds after this time i need to stop the thiscovery of new devicesthe following code shouldstart scanning for bluetooth devicesprint out any which are foundafter 6 seconds cancel all thiscovery and repeat processthe problem is that the bluetooth thiscovery is never cancelled after this code runs for a minute or two onreceive will get called tens of times in the same second public void starttrackingbuttonview view logdmain track button pressed istracking istracking if istracking istracking false else istracking true thread keepscanning new threadnew runnable override public void run while istracking if mbluetoothadapteristhiscovering logdmain cancelling thiscovery logdmain stringvalueofmbluetoothadaptercancelthiscovery mbluetoothadaptergetstate mbluetoothadapter bluetoothadaptergetdefaultadapter starttracking try threadsleep60 catch interruptedexception e todo autogenerated catch block eprintstacktrace keepscanningstart private void starttracking logdmain starting thiscovery mbluetoothadapterstartthiscovery create a broadcastreceiver for action found broadcastreceiver mreceiver new broadcastreceiver public void onreceivecontext context intent intent logdmain device found string action intentgetaction when thiscovery finds a device if bluetoothdeviceaction foundequalsaction get the bluetoothdevice object from the intent bluetoothdevice device intent getparcelableextrabluetoothdeviceextra device add the name and address to an array adapter to show in a listview logdmain devicegetname n devicegetaddress register the broadcastreceiver intentfilter filter new intentfilterbluetoothdeviceaction found registerreceivermreceiver filter do not forget to unregister during ondestroyhere is my logcat outputonreceive gets called many times in the same second0501 220956949 dmain3757 cancelling thiscovery0501 220956969 dmain3757 false12 this should be true0501 220956969 dmain3757 starting thiscovery0501 221003009 dmain3757 starting thiscovery0501 221003579 dmain3757 device found0501 221003579 dmain3757 tomselleck0501 221003579 dmain3757 06070809a1a10501 221003579 dmain3757 device found0501 221003579 dmain3757 tomselleck0501 221003579 dmain3757 06070809a1a10501 221003589 dmain3757 device found0501 221003589 dmain3757 tomselleck0501 221003589 dmain3757 06070809a1a10501 221003589 dmain3757 device found0501 221003589 dmain3757 tomselleck0501 221003589 dmain3757 06070809a1a10501 221003589 dmain3757 device found0501 221003589 dmain3757 tomselleck0501 221003589 dmain3757 06070809a1a1does anybody know how i can properly cancel all current and pending bluetooth thiscoverythanks for your helpps the reason i need to repeat the process is to get fresh signal strength values from nearby devices,['android'] +466527,append element to top of body in jquery right now facebook wants me to throw this ugly div at the top of my page directly under bodydiv idfbrootdivi would like to avoid this by instead appending it via javascriptappenddiv idfbrootdivthis places it at the bottom of the pageheadbody headertestheader div idfbrootdivbodyhow can i append it to the topheadbody div idfbrootdiv headertestheaderbody,"['javascript', 'jquery']" +466600,maintaining orientation of parent view after modal view has been presented with different orientation so i am developing an ipad app that supports only landscape mode except for on one modal view controller the issue i am having is that once i present the modal view and change the orientation to portrait then thismiss the view the parent view which should only support landscape is in portrait mode until i rotate the device in which it then goes back to landscape and stays that way i have been beating myself up trying to figure out how to keep the parents view original orientation but have not been able to find a solutioni have the following code in my app delegate to allow orientation changes on only that single modal view galleryphotoviewer nsuintegerapplicationuiapplication application supportedinterfaceorientationsforwindowuiwindow windownsuinteger orientations uiinterfaceorientationmaskallbutupsidedown ifselfwindowrootviewcontroller uiviewcontroller presentedviewcontroller uinavigationcontroller selfwindowrootviewcontroller viewcontrollers lastobject support portrait mode only on photoviewer if presentedviewcontroller presentedviewcontroller iskindofclassgalleryphotoviewcontrollerclass orientations uiinterfaceorientationmaskall else orientations presentedviewcontroller supportedinterfaceorientations return orientationsfrom the parent class photosviewcontroller i am calling galleryphotoviewcontroller gpview galleryphotoviewcontroller newself presentviewcontrollergpview animatedyes completionnilalso in my parent and other views i have the following code to thisallow portrait mode nsuintegersupportedinterfaceorientations return uiinterfaceorientationmasklandscapeleft uiinterfaceorientationmasklandscaperight boolshouldautorotatetointerfaceorientationuiinterfaceorientationinterfaceorientation ifinterfaceorientation uiinterfaceorientationportrait return yes else return no any ideas on how i can keep the orientation on my parent view i was thinking about possibly just programmatically changing the orientation on the parent in the viewwillappear method once the modal is thismissed but then i wouldnt know what the previous orientation was not to mention i have not been able to find code to do this regardless for ios6editsolution so i found a solution and what i ended up doing was leaving the applicationsupportedinterfaceorientationsforwindow code and just adding the uinavigation subclass to the parent view that was presenting the modal view and everything worked as expected and the parent retained its original orientation while the modal was able to change freely in my parent to make sure that this view remains in landscapeimplementation uinavigationcontroller rotation ios6boolshouldautorotate return selfviewcontrollers lastobject shouldautorotatensuintegersupportedinterfaceorientations return selfviewcontrollers lastobject supportedinterfaceorientationsendthanks matt for the suggestions,['ios'] +466602,check if two generic types are equal i need to find if a type is a certain generic typeclass mytypet var instance new mytypeintvar type instancegettypethis check does not work but this is what i want to check if the type is of that generic type regardless of what t istype typeof mytype this does work but feels dirty it could also be wrong since it is not the fullnametypename typeof mytype namei am assuming there is a way to do this but i have not found one using isassignablefrom will not work because i need to know if the current type and not one of it is parents are equal,['c#'] +466621,android listview adapter wont refresh i am having a lot of trouble refreshing a list view with a custom adapter i have been searching online for the past hour and i cannot seem to find any solution that will make my list view refresh i have tried notifydatasetchanged and also listviewinvalidate but nothing seems to be working any help would be greatly appreciated i can see the data being updated using logcat but it is not being refreshed on the screen and i have no idea whybelow is the codearrayliststudent students new arrayliststudentlistview listview findviewbyidridlistviewadapter new studentadapterthis rlayoutlistitemlayout students listviewsetadapteradaptercustom adapterpublic class studentadapter extends arrayadapterstudent context context int layoutresourceid arrayliststudent data null public studentadaptercontext context int layoutresourceid arrayliststudent data supercontext layoutresourceid data thislayoutresourceid layoutresourceid thiscontext context thisdata data public void updatestudentslistarrayliststudent newlist dataclear data newlist thisnotifydatasetchanged public void updatestudenttime for student s data supdateelapsedtime thisnotifydatasetchanged override public view getviewint position view convertview viewgroup parent view row convertview ifrow null layoutinflater inflater activitycontextgetlayoutinflater row inflaterinflatelayoutresourceid parent false student student datagetposition textview title textviewrowfindviewbyidridtxttitle titlesettextstudentgetfirstname studentgetlastname textview subtitle textviewrowfindviewbyidridtxtsubtitle subtitlesettextstudentgetstudentid textview duration textviewrowfindviewbyidridtextduration durationsettextstudentgetelapsedtime return row i update the data using a thread every so oftenrunnable runnable new runnable public void run runonuithreadnew runnable public void run updates how long the student is in the centre adapterupdatestudenttime adapternotifydatasetchanged listviewinvalidate logidebug running on ui thread handlerpostdelayedthis 10 handlerpostdelayedrunnable 10,['android'] +466634,how to get facebook user access token in android i am using restfb api to access my friends photos in java and to access these photos i generate access code manually using graph api explorer and pass this as a parameter to the restfb api call but now i want to generate this access token through code programmatically i have seen fb android samples particularly hackbook i do not see any access code being generated which i can use for my own application do i need to create a new app and get some secret etc any suggestion will be appreciated i have seen these solutions solution1 solution2 on stackoverflow but i am still not getting where to startupdate1 i am using following code to login and getting access token for logged in user but the problem is that it only works for the account with which i had created an app on facebook to generate an app id it does not get a call back for other accounts any suggestion pleaseand just in case if you do not know where to start follow step6 to create a new app from scratchpublic class mainactivity extends activity implements onclicklistener button login textview accesstoken override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main login button findviewbyidridlogin accesstoken textview findviewbyidridaccesstoken loginsetonclicklistenerthis start facebook login override public boolean oncreateoptionsmenumenu menu inflate the menu this adds items to the action bar if it is present getmenuinflaterinflatermenumain menu return true override public void onactivityresultint requestcode int resultcode intent data superonactivityresultrequestcode resultcode data sessiongetactivesessiononactivityresultthis requestcode resultcode data override public void onresume session session sessiongetactivesession ifsession null if sessionisopened toastmaketextthis sessiongetaccesstoken toastlength longshow accesstoken textview findviewbyidridaccesstoken accesstokensettextsessiongetaccesstoken systemoutprintln sessiongetaccesstoken superonresume override public void onclickview v start facebook login sessionopenactivesessionthis true new sessionstatuscallback callback when session changes state override public void callsession session sessionstate state exception exception if sessionisopened make request to the me api requestexecutemerequestasyncsession new requestgraphusercallback callback after graph api response with user object override public void oncompletedgraphuser user response response if user null textview welcome textview findviewbyidridwelcome welcomesettexthello usergetname,['android'] +466682,arraysort in with nontrivial comparison function consider the following code from c 50 in a nutshell p 289int numbers 1 2 3 4 5 arraysort numbers x y x 2 y 2 0 x 2 1 1 1 which gives result 3 5 1 2 4i tried this on a paper and got 1 3 5 2 4why computer sorting gave 3 5 1,['c#'] +466697,short way to include css and javascript tags with haml when including javascript or css in haml you would normally have to do the following to include csslinktype textcss rel stylesheet href cssmycsscssand for javascriptscripttype textjavascript src jsmyscriptjsi was wondering if haml does not have a short way of including these tags to get content from a source of course not inline that omits the need for the type and rel attributes since these are invariable anywaynote that ruby on rails provides this feature via a function but i am not using rails,['ruby'] +466720,global name in python i want to find out whether two numbers n1 and n2 are the permutations of the same digits for example 123 and 321 are permutations of the same digits where as 234 and 123 are not i have used python to solve the problem of which i am not an experti am using idle python gui on windows 7 the specifications are python 273 default apr 10 2012 233126 msc v1500 32 bit intel on win32 the python code is shown belowdef kn m s1 n s2 m k 0 fl 0 while k 10 arr1k 0 arr2k 0 k k 1 while s1 0 t s1 10 arr1t 1 t s2 10 arr2t 1 s1 s1 10 s2 s2 10 k 0 while k 10 if arr1k arr2k fl 1 k k 1 return fli saved the file as kpy and imported using the following command import k but when i tried to execute the code as kk123 321 i am getting the following error traceback most recent call last file pyshell7 line 1 in module kk123321 file kpy line 7 in k global arr2nameerror global name arr1 is not definedi tried to declare the arrays as followsarr1 arr2 i also triedglobal arr1 global arr2 and global arr1global arr2but i am still getting the same error what is wrong with my codei have checked the following answers in so but i could not solve my problemhelp defining global namesuse of global keyword in pythonwhat i believed was that in python you do not have to declare any variables instead you can simply use them am i wrong about this assumption any suggestions thank you,['python'] +466736,how to check whether 2 lines segments intersect how do i check whether 2 line segments l1p1p2 and l2p3p4 intersect with each other i do not need the intersection point i just need to know whether they intersect or not since my application calculating this a lot i need to find a fast solutionthanks,['java'] +466759,is circular reference between objects a bad practice i have a model that will carry modelvalidator a validator instance with it and i need the validator to have access to the models attributes so what i have come up with is the followingvar validator functionmodel thismodel modelvar model function this attributes thisvalidator new validatorthisvar model new modelthis code creates a circular reference between those 2 objects is this a bad practice that will cause memory leaks any other ideas on how to implement itps i have seen such circular references between objects in angularjs scopes,['javascript'] +466833,android playing music in background i have my activity code like belowpublic class player extends activity implements oncompletionlisteneronpreparedlistener onerrorlistener onbufferingupdatelistener musicfocusable private boolean playstate false private string station public static final float duck volume 01f private string artistname null private string trackname null private textview artist private textview track private textview status private button play enum audiofocus nofocusnoduck we do not have audio focus and cannot duck nofocuscanduck we do not have focus but can play at a low volume ducking focused we have full audio focus private audiofocus maudiofocus audiofocusnofocusnoduck private mediaplayer mplayer null private androidshoutcastlib shoutcast private audiomanager maudiomanager audiofocushelper maudiofocushelper null handler handler new handler override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity player maudiomanager audiomanager getsystemserviceaudio service create the audio focus helper if the audio focus feature is available sdk 8 or above if androidosbuildversionsdk int 8 maudiofocushelper new audiofocushelpergetapplicationcontext this else maudiofocus audiofocusfocused no focus feature so we always have audio focus status textview findviewbyidridstatus artist textview findviewbyidridartist artistsetselectedtrue track textview findviewbyidridtrack tracksetselectedtrue play button findviewbyidridplay playsetonclicklistenernew onclicklistener override public void onclickview btn if playstate playsettextpause handlerpostdelayedhandleplayrequest 300 else playsettextplay statussettextpress play handlerpostdelayedhandleplayrequest 300 shoutcast new androidshoutcastlib try shoutcastsetshoutcasturlstation catch invalidstreamurlexception e todo autogenerated catch block eprintstacktrace shoutcastsetonmetadatachangedlistenernew metadatalistener override public void onmetadatachangedmetadata item artistname itemartist trackname itemtrack updatemeta setvolumecontrolstreamaudiomanagerstream music public void ondestroy superondestroy shoutcast null handlerremovecallbackshandleplayrequest public void updatemeta handlerpostnew runnable override public void run this gets executed on the ui thread so it can safely modify views artistsettextartistname tracksettexttrackname private final runnable handleplayrequest new runnable public void run if playstate logdplayer stop called giveupaudiofocus mplayerstop mplayerreset mplayerrelease shoutcaststopstream mplayer null playstate false else logdplayer play called createmediaplayer getaudiofocus try mplayersetdatasourceshoutcaststartstream catch illegalargumentexception e todo autogenerated catch block eprintstacktrace catch securityexception e todo autogenerated catch block eprintstacktrace catch illegalstateexception e todo autogenerated catch block eprintstacktrace catch malformedurlexception e todo autogenerated catch block eprintstacktrace catch ioexception e todo autogenerated catch block eprintstacktrace catch invalidstreamurlexception e todo autogenerated catch block eprintstacktrace mplayerprepareasync private void createmediaplayer mplayer new mediaplayer make sure the media player will acquire a wakelock while playing if we do not do that the cpu might go to sleep while the song is playing causing playback to stop remember that to use this we have to declare the androidpermissionwake lock permission in androidmanifestxml mplayersetwakemodegetapplicationcontext powermanagerpartial wake lock we want the media player to notify us when it is ready preparing and when it is done playing mplayersetonpreparedlistenerthis mplayersetoncompletionlistenerthis mplayersetonerrorlistenerthis private void startplayer mplayersetvolume10f 10f if mplayerisplaying logdplayer starting playback mplayerstart playstate true statussettextstreaming private void getaudiofocus if maudiofocus audiofocusfocused maudiofocushelper null maudiofocushelperrequestfocus maudiofocus audiofocusfocused private void giveupaudiofocus if maudiofocus audiofocusfocused maudiofocushelper null maudiofocushelperabandonfocus maudiofocus audiofocusnofocusnoduck override public boolean oncreateoptionsmenumenu menu inflate the menu this adds items to the action bar if it is present getmenuinflaterinflatermenuactivity player menu return true override public void onbufferingupdatemediaplayer arg0 int arg1 todo autogenerated method stub override public boolean onerrormediaplayer mp int what int extra playstate false handlerposthandleplayrequest return false override public void onpreparedmediaplayer arg0 startplayer override public void oncompletionmediaplayer arg0 todo autogenerated method stub override public void ongainedaudiofocus todo autogenerated method stub override public void onlostaudiofocusboolean canduck todo autogenerated method stub my requirement is to convert this activity to service classi have tried but not gettingbecause i am new to android as well as new to programingcould any one help,['android'] +466854,how to know if a type is a specialization of stdvector i have been on this problem all morning with no result whatsoeverbasically i need a simple metaprogramming thing that allows me to branch to different specializations if the parameter passed is a kind of stdvector or notsome kind of is base of for templatesdoes such a thing exist,['c++'] +466886,python equivalent of rs mclapply the r package multicore has a function mclapply which applies a specified function over a list of things and takes advantage of multiple cores it is easy to use and results in big speed boostsis there a python equivalent thanks,['python'] +466938,creating a composite type from two enum classes ready for stl map i would like to create a composite type out of two enum classesenum class color red green blueenum class shape square circle triangleclass object color color shape shapepublicin order to use object in an stl container like stdmap i would need to overload the lessthan operator however in order to flatten both enum classes into one linear index i somehow need the number of elements noe of the enum classesfriend bool operator const object lhs const object rhs return noeshapelhscolorlhsshape noeshaperhscolorrhsshapehow can this be done without entering the same information number of elements in two places in the program in a nice way nice way means no first element last element preprocessor magic etcquestion number of elements in an enum is similar but does not address enum classesi would like to know what is the best way to implement this kind of composite types in c11 is the enum class definition strong enough or is it necessary to sayenum class color red0 green1 blue2enum class shape square0 circle1 triangle2,['c++'] +466991,has many nested form with a has one nested form within it i am currently trying to make a form for a model which has a dynamic number of nested models i am using nested forms as described in railscasts 197 to make things even more complicated each of my nested models has a has one association with a third model which i would also like to be added to the formfor any who are wondering about over normalization or an improper approach this example is a simplified version of the problem i am facing in reality things are slightly more complex and this is the approach weve decided to takesome example code to illustrate the problem belowmodelsclass test attr accessible test name test description questions attributes has many questions accepts nested attributes for questionsendclass question attr accessible question answer attributes belongs to test has one answer accepts nested attributes for answerendclass answer attr accessible answer belongs to questionendcontrollerclass testscontroller applicationcontroller get testsnew def new test testnew questions testquestionsbuild answers questionsbuild answer endendview form for test do f flabel test name ftext box test name flabel test description ftext area test description ffields for questions do questions builder questions builderlabel question questions buildertext box question questions builderfields for answer do answers builder answers builderlabel answer answers buildertext box answer end end link to add fields new f questions end this code example works fully for the first instance of question the issue occurs when another question is dynamically added to be created the answer fields are not thisplayed i believe this is because they are only built for the first question in the controller is there a way to achieve this using nested attributes,"['ruby-on-rails', 'ruby']" +467008,how to thisable viewpager adapter on touching specific views i have a viewpager which switches between tabs when swiping leftrightin my second tab i have some custom views which have listeners for pinching and dragging but when i try to pinch or drag the viewpager starts to swipe the pagea solution comes to my mind is to thisable swiping when touching those specific views and only swipe when touching outside those viewsis this possibleupdatedasok kindly provided the solution but then updated the code which wouldnt work in my case so i post the previous piece of code which worked for mepublic class customviewpager extends viewpager private boolean swipeable truepublic customviewpagercontext context supercontextpublic customviewpagercontext context attributeset attrs supercontext attrs call this method in your motion events when you want to thisable or enable it should work as desiredpublic void setswipeableboolean swipeable thisswipeable swipeableoverridepublic boolean onintercepttoucheventmotionevent arg0 return thisswipeable superonintercepttoucheventarg0 falselets suppose i have a draggable view and i need to thisable swipping when dragging start and re enable when dragging finished so in touchevent of my so called view overridepublic boolean ontoucheventmotionevent event switcheventgetaction case motioneventaction downthisable swiping when the button is touchedactivityoriginal getactivitysetswipeablefalsethe rest of the code break case motioneventaction move break case motioneventaction upre enable swipping when the touch is stoppedthe rest of the codeactivityoriginal getactivitysetswipeabletrue break return true,['android'] +467033,image in widget i am trying to set image in image view in widget layout in onupdate but image is not updating override public void onupdatecontext context appwidgetmanager appwidgetmanager int appwidgetids logitag onupdate called for int appwidgetid appwidgetids bitmap bitmapimageutilsgetbitmapcontext appwidgetid remoteviews remoteview new remoteviewscontextgetpackagename rlayoutwidget remoteviewsetimageviewbitmapridimgviewbitmap appwidgetmanagerupdateappwidgetappwidgetid remoteview xml layout for widgetlinearlayout xmlnsandroid androidlayout widthmatch parent androidlayout heightmatch parent androidorientationvertical imageview androidididimgview androidlayout widthfill parent androidlayout heightfill parent androidsrcdrawableic launcher linearlayoutmanifest fileapplication androidallowbackuptrue androidicondrawableic launcher androidlabelstringapp name androidthemestyleapptheme activity androidnamecomdemomainactivity androidlabelstringapp name intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity activity androidnamewidgetconfig androidlabelstringapp name intentfilter action androidnameandroidappwidgetactionappwidget configure intentfilter activity receiver androidnamebasicwidgetprovider intentfilter action androidnameandroidappwidgetactionappwidget update intentfilter metadata androidnameandroidappwidgetprovider androidresourcexmlwidget info receiver receiver androidnamebasicwidgetprovider intentfilter action androidnameandroidappwidgetactionappwidget update data androidschemewidget intentfilter metadata androidnameandroidappwidgetprovider androidresourcexmlwidget info receiver applicationwidget infoxmlappwidgetprovider xmlnsandroid androidminwidth25dp androidminheight25dp androidinitiallayoutlayoutwidget androidconfigurecomdemowidgetconfig androidwidgetcategoryhome screenkeyguard androidpreviewimagelayoutwidget androidresizemodehorizontalvertical androidinitialkeyguardlayoutlayoutwidget androidminresizeheight5dp androidminresizewidth5dpappwidgetproviderbut when try to load widget i get a toast app isnt installed i am not showing any such toast from where does it comeswhy is image not setting how to fix it,['android'] +467060,how to set table cell height dynamically depending on text label length i am trying to learn objc and ios programming but am still very new i decided to try and make a simple reddit client application i am trying to thisplay the front page posts within a uitableview with each post represented by its own cellon the cell here is how i am setting the titlecelltextlabelnumberoflines 0celltextlabeltext tempdictionary objectforkeydata objectforkeytitle celltextlabel sizetofithowever the cell ends up clipping itself if the title text is too long heres a picturehow can i make my cells automatically adjust their heights to accommodate longer title labels without intersecting other cells or the detail text labelthank you for any help,"['ios', 'objective-c']" +467066,why the copy constructor is not called in this codeinclude iostreamusing stdcoutclass foo public foo egg0 fooconst foo other egg1 int eggfoo bar foo baz bazegg 3 return bazint mainvoid foo spambar cout spamegg return 0the output is 3 while i expected it to be 1that means the copy constructor is not called in the line foo spambar i guess it is because the bar function does not return a referencecould you please explain whats really going on at the initialization of spami apologize in advance if that is a dumb questionthanks,['c++'] +467067,ios html5 date picker would not accept width 100 i have a html5 date picker in my form for a mobile version of my site all my text inputs are set to width100 and its parent td is set to paddingright15px to make it fit this means my fields are nicely formatted and adjust to always fill up half of the container when the orientation of the device changes however the date picker does not behave in the same way can anyone helpformform methodget actionhometable idformtrtdinput typetext nametitle classtbox placeholdertitle tdtdinput typetext namegenre classtbox placeholdergenre tdtrtrtdinput typetext namelocation classtbox placeholderlocation tdtdinput typedate namedate classtbox placeholderddmmyy tdtrtrtdinput typetext namepostcode classtbox idpostcode placeholderpostcode tdtdinput typenumber nameradius classtbox placeholdermile radius br tdtrtableinput typesubmit valuesearch formrelevant csstbox backgroundcolor a1c9ffborder 1px solid 003f94width 100height 30pxmargin 3px 2pxpadding 0 5pxborderradius 15pxfontsize 18pxfloat lefttableform tr td overflow hiddenpaddingright 15px,"['ios', 'css']" +467068,take a screenshot from a website from commandline or with python i will take a screenshot from this page pgpa1img1w2500 or save the image that it outputsbut i cannot find a way with wgetcurl i get an unavailable error and also with others tools like webkit2pngwkhtmltoimagewkhtmltopngis there a clean way to do it with python or from commandlinebest regards,['python'] +467084,mapping memory address of unsatisfyable nslayoutconstraints to ui controls i appreciate that xcode will catch the unsatifyable nslayoutconstraints and gives you some information about it however i do not know how to take the memory addresses of the controlsconstraints and map that to the actual controls that have problem my app is fairly large around 20 screens some are large uiviewcontrollers with several child view controller within them some are uitableviews with custom cells and uicollectionviews with custom cells i am having a hell of a time tacking down the cause of this error which happens on landscape rotation here is the information from my console 20130502 1853225 smile7519c07 unable to simultaneously satisfy constraints probably at least one of the constraints in the following list is one you do not want try this 1 look at each constraint and try to figure out which you do not expect 2 find the code that added the unwanted constraint or constraints and fix it note if youre seeing nsautoresizingmasklayoutconstraints that you do not understand refer to the documentation for the uiview property translatesautoresizingmaskintoconstraints nsautoresizingmasklayoutconstraint0x16083b60 h v uiview0xa5a1d00width uiwindow0xa09e0width nslayoutconstraint0xa5a2180 vuiview0xa59f160954 names uiview0xa5a1d00 nslayoutconstraint0xa5a2140 v0uiview0xa59f160 names uiview0xa5a1d00 nsautoresizingmasklayoutconstraint0xa593340 h v huiwindow0xa09e0768will attempt to recover by breaking constraint nslayoutconstraint0xa5a2180 vuiview0xa59f160954 names uiview0xa5a1d00 break on objc exception throw to catch this in the debuggerthe methods in the uiconstraintbasedlayoutdebugging category on uiview listed in uikituiviewh may also be helpfulas you can see there are memory addresses listed pasting those into the watch windows search bar does not reveal much also sifting though the thread and queue call stacks i only get thisassembled code on this breakpoint exception breakpoint,"['iphone', 'ios']" +467089,does new return void in c this is a simple question does using new operator return a pointer of type void referring to what is the difference between newdelete and mallocfree answer it says new returns a fully typed pointer while malloc void but according to throwing 1 void operator new stdsize t size throw stdbad allocnothrow 2 void operator new stdsize t size const stdnothrow t nothrow value throwplacement 3 void operator new stdsize t size void ptr throwwhich means it returns a pointer of type void if it returns void i have never seen a code like myclass ptr myclass new myclassi have got confused editas per example stdcout 1 myclass p1 new myclass allocates memory by calling operator new sizeofmyclass and then constructs an object at the newly allocated space stdcout 2 myclass p2 new stdnothrow myclass allocates memory by calling operator new sizeofmyclastdnothrow and then constructs an object at the newly allocated spaceso myclass p1 new myclass calls operator new sizeofmyclass and since throwing 1void operator new stdsize t size throw stdbad alloc it should return void if i understand the syntax correctlythanks,['c++'] +467108,keydown keyup events for specific keys i am trying to make the background color change when certain keys are held down for example when the r key is being held down the background should be red when the r key is not being pressed anymore the background should default to whitedocumentreadyfunction bodykeydownfunctione ifekeycode 114 thiscssbackgroundred ifekeycode 121 thiscssbackgroundyellow bodykeypressfunctione ifekeycode 114 thiscssbackgroundred ifekeycode 121 thiscssbackgroundyellow bodykeyupfunctione ifekeycode 114 thiscssbackgroundwhite ifekeycode 121 thiscssbackgroundwhite the problem i am having is that keyup is not working specifically for each individual key bodykeyupfunctione thiscssbackgroundwhite i know if i remove the if conditionals from keyup altogether then it will behave how i said i wanted it to a but i want to be able to do different things later on using keyup with specific keys for example when just the b key is released maybe it will say something on the screen like you just released the b key how can i keep track of keydown and keyup events for specific keys and make different things happen for each i know this is not very organized either i am pretty new to this stuff so if there is a completely different and better way of doing this,"['javascript', 'jquery']" +467115,android iab error refreshing inventory querying prices of items developer error i have been setting up android in app billing v3 using the iabhelper class and following the example code provided by google i have it mostly working all the way through purchase with signed apk and real credit card chargehowever in the course of testing today i started to get a new error in my queryinventoryfinishedlistener from the queryinventoryasync methodiabresult message error refreshing inventory querying prices of itemsiabresult response 5developer errorweird thing 1 is that this occurs after the oniabsetupfinished callback returns with the customary hooray message weird thing 2 is that i can subsequently successfully process an in app purchase using the launchpurchaseflow methodi found a patch here that addresses the same symptoms i am experiencing but it did not work for mei have tried using different devices using different gmail accounts and building a new product from scratch i even getting the error on earlier versions of my app that ran correctly whatmy question is why cannot i query the product inventory even after iabhelper has confirmed the set up was successful what could be causing this error and how can i fix itthank you for any insightupdatei was able to get the inventory query transactions to work again by ditching the account i was testing with and switching to a new account no code changemy tentative conclusion is that something got corrupted in the user account i was using during testing i had hit it pretty hard with a lot of purchases of different inapp products but i still need to find out what happened and make sure this does not happen to any of my usersplease let me know if you have any experience with this thanks,['android'] +467212,how to avoid a databinding events hell on a complex screen this is more of an architecture design question i have run into a few projects in the past written in wpfwindows forms etc that have complex screens with a lot of fields and these fields are connected to each other their values depend on each other with some logic involvedthese projects i have taken on after they were implemented and i found a lot of events data bind hell what i mean by this is that because all these fields are depending on others they have implemented inotifypropertychanged and other fields are being modified as a result this causes the same fields being updated 56 times when the screen loads and the order in which fields are populated causes horrible bugs for example date was set before job type instead of after job type so i end up with a different job feeto make matters worse some hacks are implemented on ui events for example dropdown changed to update field x while others are in the domain model that the ui binds tobasically it is a huge mess and i just want to know what the best way to implement something like this is if i was to start from scratch or is it a good idea to avoid such a complex screen in the first place,['c#'] +467250,mysql mysql2error incorrect string value so i built a scraper and am pulling in some objects the issue is some are foreign languages and it is tripping the mysql db up a bit this is the error i got any idea what i can do with this thanksmysql2error incorrect string value xc5x8dga for column description at row 1 insert into sammiches country created at description image name updated at values japan 20130503 011706 a hot dog bun stuffed with fried noodles frequently topped with pickles such as beni shaga with mayonnaise wikifileyakisoba sandwich by kaex0rjpg yakisobapan 20130503,['mysql'] +467352,appviewaddjavascriptinterface does not work on api 17 i am able to use java function from my phonegap java script function and android 22 but same code is not run on api 17 what should i have to do to call native java code on from java script in api 17 i use this code in my java file objcustomnativeaccess new customnativeaccessthis appview appviewaddjavascriptinterfaceobjcustomnativeaccess customnativeaccess superloadurlfileandroid assetwindexhtmlmy customnativeaccess class ispublic class customnativeaccess private webview mappview private droidgap mgap constructor param gap param view public customnativeaccessdroidgap gap webview view mappview view mgap gap get the device phone number return public jsonobject loginstring email string password jsonobject object new jsonobject objectputlogin status login status objectputdate datestring return object and in my java script i use this line to call this login function var value windowcustomnativeaccessloginemailpaso using this i successfully call this on api 22 but when i run this code on api 17 it give me erroruncaught typeerror object object object has no method login at fileandroid assetwindexhtml81how i can i use this on api 17,"['java', 'javascript', 'android']" +467415,will the c compiler remove unused local if it is assigned a property this might be a silly question i know that compiler will remove unused locals but if i write my code like thisclass myclass public int someproperty get public void somefunction will this line be removed if i is never used int i someproperty i am wondering that if i will be removed by compiler because of optimization there is logic inside the getter of someproperty that i wish to execute if i will be removed i have to change someproperty to a functionbtw is there a way to know which line will be optimized by compiler,['c#'] +467434,mvc for advanced php developers i need some help from more experienced programmers i want to improve my mvc skills but i could not find a good tutorial on google for mvc google always gives mvc for beginnersi understand what mvc is and i can make it but i am not experienced enough to do something practical in oopif anyone knows a good objectoriented tutorial for mvc please direct me to the right place a i am looking for good links books etc,['php'] +467449,string format a json string gives keyerror why does this code give a keyerroroutput format file filename success success errormessage error msg logidentifier log identifier print output formatformatfilenamemy file name successtrue error msg log identifier123error messagekeyerror file,['python'] +467466,a preferred way to check if aspnet web application is in debug mode during runtime during compile time i can do a check like if debug logsomethingendifbut what would be the preferred to check if debugfalse is set in webconfig during runtime,"['c#', 'asp.net']" +467488,nspredicate unable to parse the format string i am trying to write a nspredicate to fetch rows with my column value with this string 193e00a75148b4006a451452c618ccec and i get the below crashterminating app due to uncaught exception nsinvalidargumentexception reason unable to parse the format string my column193e00a75148b4006a451452c618ccecmy predicate statementfetchrequestpredicatenspredicate predicatewithformatnsstring stringwithformatattributenameitemvaluealso tried thisfetchrequestpredicatenspredicate predicatewithformatnsstring stringwithformat attributenameitemvaluethisfetchrequestpredicatenspredicate predicatewithformatnsstring stringwithformat attributenameitemvalueand thisfetchrequestpredicatenspredicate predicatewithformatnsstring stringwithformatattributenameitemvalueplease helpi found out this when i was trying with martin rs answerfetchrequestpredicatenspredicate predicatewithformatattributenameitemvalueattributename i pass comes with a so i took off attributename and hardcoded it then it works fine,['ios'] +467549,find out whether a pointer is pointing at the stack heap or program text is there a way to find out whether a pointer is pointing at a location inthe stackthe heap or the program and if so which section eg elf textalso can this be done portably linux 6432 bit osx and windows 7follow upi am not trying to find out if something has been mallocdi want to efficiently thistinguish void pointers to functions in the program from void pointers to data on the stack or heap this is for a language runtime written in c not a normal c programthis answer has been the most useful so far checking if something was malloced,['c'] +467552,how to find out number of files currently open by java application suppose a lot of what your application does deals with reading contents of the files goes without saying that files that are open then closed and life is good unless new files come in faster then old files get closed this is the pickle of a situation i found myself innow is there a way to reliably know how many files are open by the process something that as reliable as looking at ls procmy pidfd wc l from inside the jvmi suspect answer may be os specific so let me add that i am running java on linux,['java'] +467556,does sql join order affect performance i was just tidying up some sql when i came across this queryselect jmimei jmmaxspeedkm jmmaxaccel jmmaxdeccel jmjourneymaxleft jmjourneymaxright jmthistancekm jmidletimeseconds jmwebuserjourneyid jmlifetime odo metres jmdescriptorfrom dboreporting webusers as wu with nolock inner join dboreporting journeymaster90 as jm with nolock on wuwebusersid jmwebusersid inner join dboreporting journeys as j with nolock on jmwebuserjourneyid jwebuserjourneyidwhere wuisactive 1 and jjourneyduration 2 and jjourneyduration 10 and jjourneythistance 0 my question is does it make any performance difference the order of the joins as for the above query i would have done from dboreporting journeymaster90 as jmand then joined the other 2 tables to that one,['sql'] +467584,uiscrollview zooming out of a view with a ve origin i have a uiscrollview in this i have a uiview which has a frame with a negative origin i need to limit the scroll view so that you cannot scroll around the entire viewi have implemented zoom in this scrollview when zooming the scroll view will adjust the size of the zoomable view according to the scale but it does not adjust the originso if i have a view with a frame of 0 500 10 10 the i zoom out to a scale of 05 this will give me a new frame of 0 500 500 500clearly this is not good the entire view is zoomed out of the scrollview i want the frame to be 0 250 500 500i can fix things a bit in the scrollviewdidzoom method by adjusting the origin correctly this does work but the zoom is not smooth changing the origin here causes it to jumpi notice in the documentation for uiview it says regarding the frame propertywarning if the transform property is not the identity transform the value of this property is undefined and therefore should be ignorednot quite sure why that isam i approaching this problem wrong what is the best way to fix itthanksbelow is some source code from the test app i am usingin the viewcontroller voidviewdidload super viewdidload selfbigview bigview alloc initwithframe cgrectmake0 400 10 10 selfbigscroll addsubview bigview selfbigscrolldelegate self selfbigscrollminimumzoomscale 02 selfbigscrollmaximumzoomscale 5 selfbigscrollcontentsize bigviewboundssizeuiview viewforzoominginscrollviewuiscrollview scrollview return bigview voidscrollviewdidzoomuiscrollview scrollview bigviewframe cgrectmake0 400 scrollviewzoomscale bigviewframesizewidth bigviewframesizeheight bigviewcenter cgpointmake500 scrollviewzoomscale 100 scrollviewzoomscaleand then in the view voiddrawrectcgrectrect drawing code cgcontextref ctx uigraphicsgetcurrentcontext cgcontextsetfillcolorwithcolorctx uicolor whitecolorcgcolor cgcontextsetstrokecolorwithcolorctx uicolor whitecolorcgcolor cgcontextfillrectctx cgrectmake100 500 10 10 for int i 0 i 10 i 100 cgcontextstrokerectctx cgrectmake0 i 10 3 note that here the jumpiness is more apparent at larger zoom scales in my real app where there is much more drawing and processing going on the jump is more apparent at all times,"['ios', 'objective-c']" +467674,about error attempt to modify property of nonobject can anyone tell me why the following code will have different results unset object propertys new stdclassunsetsab it is working fineunsetsxyz it is got an error attempt to modify property of nonobjectunset array indexa arrayunseta12 it is working fineunseta345 it is working fine,['php'] +467708,128bit integers supporting and in the intel c compiler gcc and clang have the int128 t and uint128 t extensions for 128bit integer arithmetici was hopeful that m128i would give something similar for the intel c compiler but if it is even possible it looks to me like i would have to write explicit sse2 function calls in order to use m128i instead of using builtin operators like and i was hoping to do something like this this does not workif defined intel compiler defined sse2 include xmmintrinh typedef u128 uint128 telif defined gnuc typedef uint128 t uint128 telse error for 128bit arithmetic we need gcc or icc or uint128 tendifis there 128bit integer support with the operators and somewhere buried in icc,['c'] +467713,weakmap implementation in ecmascript5 i have run across a javascript library that implement a crossbrowser weakmap in es5 weakmap is slated for es6how can this possibly work without support in the javascript language itselfedit just to be clear i am referring to a weak map not a regular map i tested this project out using chromes profiler and the keys are not held by strong references they get gced without having to remove them from the weakmap,['javascript'] +467729,controlling group order in a kendo ui grid is there a way to control the order of the grouping in a kendo ui grid there is a group i would like to go before all other groups but it seems kendo ui grid sorts the groups alphabetically i know that adding a space to the grouping name works but that is seems very hackishthanksleo,"['c#', 'html']" +467740,safevarargs and java 6 interoperability i have a method with a generic varargs parameter in my api i want my api to be java 6 source and binary compatible but it would be nice if java 7 api consumers wouldnt suffer from unnecessary varargs warningsa trick that i can think of is to add my own javalangsafevarargs annotation to my api and ship it with my deliverable as an effectjava 6 compilers wouldnt recognise this annotation and just ignore itjava 7 compilers would recognise this annotation and probably classload the one from the jdk first and thus they wouldnt produce the annoying warnings anymoreapart from license concerns is this guaranteed to work it seems to work with javac or are there configurations where redefining an annotation from the jdk has undesireable sideeffects at the callsite or is there another way to solve this java 67 interoperability issuea related questionusing java 7 sdk features in java 6,['java'] +467820,how can i use jsonnet to handle a value that is sometimes an object and sometimes an array of the object i notice there are some other results on stackoverflow for this question but they do not seem to work or are vague using the most popular result i have put together thisthe problem is that when json comes back and is being serialised into one of my custom types one of the bits of json is sometimes an array and sometimes just a string if my custom type has a string and the json is an array i get an error the same happens the other way around if the json is an object and my custom type is an array it just cannot map it to the propertyi decided to solve this i want to override the deserialisation of this particular property and if it is an object i want to convert it into an array of 1 objectin the object i am serialising to i added a jsonconverter which i think is going to override the way it is deserialisedjsonconvertertypeofarrayorsingleobjectconverterstringpublic liststring person get set the idea is that the custom converter will convert a single object to an array so if the json is hello it will set person to be a list containing hello instead of throwing an exception saying cannot convert string to listif it is already an array it should just leave it alonethe converter looks like thispublic class arrayorsingleobjectconvertert jsonconverter public override bool canconverttype objecttype return true not sure about this but technically it can accept an array or an object so everything is game public override object readjsonjsonreader reader type objecttype object existingvalue jsonserializer serializer if objecttype typeoflistt return serializerdeserializelisttreader else var singleobject serializerdeserializetreader var objectaslist new listt objectaslistaddsingleobject return objectaslist public override void writejsonjsonwriter writer object value jsonserializer serializer throw new notimplementedexception it does not work the above code throws an exception trying to deserialize a a single string saying it cannot cast it into a list inside the if statement the objectype is however a listi am struggling to understand exactly what the read and write methods are doing in the other answer on stackoverflow it suggests throwing a notimplementedexception in the read method but if i do that the read method is called and the exception throws i think i am on the right track but i need a nudge in the right direction i think i am a little confused about what the readjson method is doing and what its parameters meani do not really understand where the value is coming from that it is deserializing since i did not specify it in the deserialize method calli am a bit out of my depth on this one,['c#'] +467822,tkinter adding line number to text widget trying to learn tkinter and python i want to thisplay line number for the text widget in an adjacent framefrom tkinter import root tktxt textroottxtpackexpandyes fillbothframe frameroot width25framepackexpandno filly sideleftrootmainloopi have seen an example on a site called unpythonic but its assumes that line height of txt is 6 pixels i am trying something like this1 binding anykeypress event to a function that returns the line on which the keypress occurstextpadbindanykeypress linenumberdef linenumbereventnone line column textpadindexendsplit creating line number toolbar try linelabelpack forget linelabeldestroy lnbarpack forget lnbardestroy except pass lnbar frameroot width25 for i in range0 lenline linelabel labellnbar texti linelabelpacksideleft lnbarpackexpandno fillx sideleftunfortunately this is giving some weird numbers on the frameis there a simpler solution how to approach thisthnks,['python'] +467827,cannot create an index catalog in localdb v110 sql statementcreate table dboindextable mapid varchar 50 not null keyword varchar 900 null primary key clustered mapid ascgocreate fulltext catalog ftsearchthis is the error i getcreating ftsearch sql72014 net sqlclient data provider msg 9982 level 16 state 100 line 1 cannot use fulltext search in user instancei am using localdbv110 that is installed along with visual studio 2012,['sql'] +467880,rest rql java implementation is there any java implementation of rql resource query language there is an implementation of fiql feed item query language here but it is part of cxf so my questions are can i use the fiql engine of cxf implementation separably from using cxf in case i am using spring mvcis there implementation of rql rql vs fiql,['java'] +467932,improving speed of python module import the question of how to speed up importing of python modules has been asked previously speeding up the python import loader and python speed up imports but without specific examples and has not yielded accepted solutions i will therefore take up the issue again here but this time with a specific example i have a python script that loads a 3d image stack from thisk smooths it and thisplays it as a movie i call this script from the system command prompt when i want to quickly view my data i am ok with the 700 ms it takes to smooth the data as this is comparable to matlab however it takes an additional 650 ms to import the modules so from the users perspective the python code runs at half the speedthis is the series of modules i am importingimport numpy as npimport matplotlibpyplot as pltimport matplotlibanimation as animationimport scipyndimageimport scipysignalimport sysimport osof course not all modules are equally slow to import the chief culprits arematplotlibpyplot 300msnumpy 110msscipysignal 200msi have experimented with using from but this is not any faster since matplotlib is the main culprit and it is got a reputation for slow screen updates i looked for alternatives one is pyqtgraph but that takes 550 ms to import i am aware of one obvious solution which is to call my function from an interactive python session rather than the system command prompt this is fine but it is too matlablike i would prefer the elegance of having my function available from the system prompt i am new to python and i am not sure how to proceed at this point since i am new i would appreciate links on how to implement proposed solutions ideally i am looking for a simple solution are not we all because the code needs to be portable between multiple mac and linux machines,['python'] +467951,cannot import flask from project directory but works everywhere else so i have run into a funny problem when trying to use flask i can only run it from home and not from projectsprojectfolder i am using python 274 installed via their homepage virtualenv and virtualenvwrapper every time it is the same mkvirtualenv projectnew python executable in projectbinpythoninstalling setuptoolsdoneinstalling pipdonethen i install flask pip install flasksuccessfully installed flask werkzeug jinja2cleaning upthen i open python from my home directoryproject python from flask import flaskthen i quit and go to my project folderproject cd projectsexampleproject python from flask import flasktraceback most recent call last file stdin line 1 in module file flaskpy line 1 in module from flask import flaskimporterror cannot import name flaskand i am a bit lost as to why this is happening anybody have any ideas,['python'] +467982,action bar home button not functional with nested preferencescreen i found a workaround to actually enable the actionbar home button on the nested preferencescreen however it does not call onoptionsitemselected in my preferenceactivity anyone know a way to actually use the home button on a nested preferencescreenmodification of post 35 hereoverride public boolean onpreferencetreeclickpreferencescreen preferencescreen preference preference superonpreferencetreeclickpreferencescreen preference if preferencenull if preference instanceof preferencescreen if preferencescreenpreferencegetdialognull preferencescreenpreferencegetdialoggetactionbarsethomebuttonenabledtrue return false,"['java', 'android']" +468010,ubuntu cannot install rmagick how to install the rmagick gem to ubuntu i found a few threads here on so some of there directly pointed out to the installation on ubuntu systems but none of them is working for mehere is the output that i got if i run sudo gem install rmagickbuilding native extensions this could take a whileerror error installing rmagick error failed to build gem native extension optbitnamirubybinruby extconfrbchecking for ruby version 185 yeschecking for gcc yeschecking for magickconfig yeswarning found more than one imagemagick installation this could cause problems at runtime optbitnamicommonbinmagickconfig reports version 675 q16 is installed in optbitnamicommon usrbinmagickconfig reports version 669 q16 is installed in usrusing 675 q16 from optbitnamicommonchecking for imagemagick version 649 yeschecking for hdri thisabled version of imagemagick yespackage magickcore was not found in the pkgconfig search pathperhaps you should add the directory containing magickcorepcto the pkg config path environment variableno package magickcore foundpackage magickcore was not found in the pkgconfig search pathperhaps you should add the directory containing magickcorepcto the pkg config path environment variableno package magickcore foundpackage magickcore was not found in the pkgconfig search pathperhaps you should add the directory containing magickcorepcto the pkg config path environment variableno package magickcore foundpackage magickcore was not found in the pkgconfig search pathperhaps you should add the directory containing magickcorepcto the pkg config path environment variableno package magickcore foundchecking for stdinth yeschecking for systypesh yeschecking for wandmagickwandh nocannot install rmagick 2132 cannot find magickwandh extconfrb failed could not create makefile due to some reason probably lack ofnecessary libraries andor headers check the mkmflog file for moredetails you may need configuration optionsprovided configuration options withoptdir withoutoptdir withoptinclude withoutoptincludeoptdirinclude withoptlib withoutoptliboptdirlib withmakeprog withoutmakeprog srcdir curdir rubyoptbitnamirubybinrubygem files will remain installed in optbitnamirubylibrubygems191gemsrmagick2132 for inspectionresults logged to optbitnamirubylibrubygems191gemsrmagick2132extrmagickgem makeoutit is on amazon ec2 serversif i try to run just gem install rmagick i geterror while executing gem gemfilepermissionerror you do not have write permissions into the optbitnamirubylibrubygems191 directorycould you help me please how to fix this issuethank you very muchedit what i have triedsudo aptget install libmagickwanddevreading package lists donebuilding dependency treereading state information donelibmagickwanddev is already the newest versionthe following packages were automatically installed and are no longer required libgraphicsmagick3 libmagick4 libgraphicsmagick3 libgraphicsmagick1dev libgraphicsmagickperl libperl514 libgraphicsmagick1devuse aptget autoremove to remove them0 upgraded 0 newly installed 0 to remove and 40 not upgradedsudo aptget install libmagickwanddev imagemagickreading package lists done building dependency tree reading state information done imagemagick is already the newest version libmagickwanddev is already the newest version the following packages were automatically installed and are no longer required libgraphicsmagick3 libmagick4 libgraphicsmagick3 libgraphicsmagick1dev libgraphicsmagickperl libperl514 libgraphicsmagick1dev use aptget autoremove to remove them 0 upgraded 0 newly installed 0 to remove and 40 not upgradedaptget install libmagickwanddeve could not open lock file varlibdpkglock open 13 permission deniede unable to lock the administration directory varlibdpkg are you rootsudo aptget install libmagickwanddevreading package lists donebuilding dependency treereading state information donelibmagickwanddev is already the newest versionthe following packages were automatically installed and are no longer required libgraphicsmagick3 libmagick4 libgraphicsmagick3 libgraphicsmagick1dev libgraphicsmagickperl libperl514 libgraphicsmagick1devuse aptget autoremove to remove them0 upgraded 0 newly installed 0 to remove and 40 not upgradedbut still the same error message above,"['ruby-on-rails', 'ruby']" +468018,how to ensure that a static constructors is called without calling any member i have a class with a static constructori want the static constructor to be called without calling or using any of its members but only if the constructor has not been called alreadyi tried using reflection with reflection i can invoke the static constructor many times but i cannot find out if it has already been called beforehow do i do thiseditthis is not only one class i am talking about it could be more lets say all classes marked with a special attribute,['c#'] +468033,using bootstrap and django i am trying to get bootstrap working in my django project and followed the tutorial herebut it did not work when i visit the my local project in the browser it just shows a blank page with 4 blue links not exaclty what i was expecting in pycharm my ide it tells me that i have an unresolved refrence to static url in my template i think the problem is that by just placing bootstrap in my project and defining it in my settings wasnt enough any ideassorry basically here is how my project is set upmain project app 1 app 2 media templates main projectso should i put boostrap under the first main project or the secondalso here is my settings in case it mattersstatic root ospathjoinsite root static files url prefix for static files example static url static,"['python', 'html']" +468147,android imageview fill the screen width here my layout filescrollview xmlnsandroidxmlnstoolsandroidorientationverticalandroidlayout widthmatch parentandroidlayout heightmatch parentandroidpaddingbottomdimenactivity vertical marginandroidpaddingleftdimenactivity horizontal marginandroidpaddingrightdimenactivity horizontal marginandroidpaddingtopdimenactivity vertical marginandroidbackground0toolscontextcproductdetails linearlayout androidorientationvertical androidlayout widthmatch parent androidlayout heightwrap content androidbackgrounddrawableshape bg imageview androidididproduct image androidlayout widthmatch parent androidlayout heightwrap content androidsrcdrawableic tweet placeholder photo dark error androidscaletypecenter textview androidididproduct name androidlayout widthmatch parent androidlayout heightwrap content androidtextisselectabletrue androidtextcolor95ab56 androidtextsize20sp androidlayout margintop7dip textview androidididproduct price androidlayout widthmatch parent androidlayout heightwrap content androidtextisselectabletrue androidtextsize20sp androidtextcolorefea textview androidididproduct commerce androidlayout widthmatch parent androidlayout heightwrap content androidtextisselectabletrue androidtextsize20sp textview androidididproduct city androidlayout widthmatch parent androidlayout heightwrap content androidtextisselectabletrue androidtextsize15sp androidlayout margintop10dip androidlayout marginbottom10dip textview androidididproduct township androidlayout widthmatch parent androidlayout heightwrap content androidtextisselectabletrue androidtextsize15sp androidvisibilitygone androidlayout marginbottom10dip androiddrawableleftdrawablelocation place androiddrawablepadding7dip textview androidididproduct website androidlayout widthmatch parent androidlayout heightwrap content androidtextisselectabletrue androidautolinkweb androidtextsize15sp androiddrawableleftdrawablelocation web site androiddrawablepadding7dip androidvisibilitygone textview androidididproduct tel androidlayout widthmatch parent androidlayout heightwrap content androidtextisselectabletrue androidtextsize20sp androiddrawableleftdrawabledevice access call androiddrawablepadding7dip androidvisibilitygone linearlayoutthe result in a phoneand the result in a 7in tableti want to make the image fill the screen width also in tablet like twitter app for example,['android'] +468271,clang in xcode start with weverything and manually thisable particular warnings i like to use weverything for the compiler to catch all possible warnings but sometimes i get warnings that i do not want to fix how can i manually thisable those particular warnings as they occur,['objective-c'] +468377,how to integrate simplegui with python 27 and 30 shell i am learning python from coursera in this course they use simplegui module on codeskulptor can anyone tell me how to integrate simplegui with python 27 and 30 shell,['python'] +468402,evaluate a string with a switch in c i want to evaluate a string with a switch but when i read the string entered by the user throws me the following errorincludeiostreamusing namespace std int main string a cina switch stringa case option 1 coutit pressed number 1endl break case option 2 coutit pressed number 2endl break case option 3 coutit pressed number 3endl break default coutshe put no choiceendl break return 0 error invalid cast from type stdstring aka stdbasic string to type int,['c++'] +468457,how to initialize a static sparsearray how can i initialize a static unmodifiable instance of androidutilsparsearray,"['java', 'android']" +468460,difference between class and class in java what is the difference between class and classobject in java afaik java erasure changes to it is upper bound which in this case would be object anyway so what is this for,['java'] +468469,constructing a php array from separate files i am new to this but have tried to learn as much as i can before asking questions here unfortunately it is unlikely that i have the vocabulary to ask a clear question apologies and thanks in advanceis it possible to build an array out of data from several files say i had a series of text files and the first line of each file was three tags separated by commas that i wanted to be stored in an array of all of the tags from all of the text files how would i go about thatfor example my file might contain tags the title of the page and its contentsocial movements handout internationalhaiti and the politics of resistancehaiti officially the republic of haiti is a caribbean country it occupies the western smaller portion of the island of hispaniola in the greater antillean archipelago which it shares with the dominican republic ayiti land of high mountains was the indigenous taano or amerindian name for the island the countrys highest point is pic la selle at 2680 metres 8793 ft the total area of haiti is 27750 square kilometres 10714 sq mi and its capital is portauprince haitian creole and french are the official languagesmy desired outcome is a page containing all of the tags used in all of the text files that can each be clicked on to see list of all of the pages containing those tagsnever mind for now that i want to remove duplicate tags do i need to read the first line of the first file explode that line and then write those values to an array and then do the same with the next file i have attempted to do this with firstlycontent filemytextfilenametxtfirst line content0echo content0that i found here followed by stuff about explode that i found herecontent explodecontentprint content0this did not work probably obviously but i am in no position to figure out why not if i have not explained myself well then please ask so that i can attempt to clarify my questionthank you for your help adam,['php'] +468472,how can i get a bootstrap column to span multiple rows i am trying to figure out how to do the following grid with bootstrap i am not sure how i would create the box number 1 that spans two rows the boxes are generated programmatically in the order they are laid out box 1 is a welcome messageany ideas on the best way to go with this,['css'] +468538,how to download files from url and store in document folder i created one application that has two page first page for show list of data and second page for show detail datawhen click on any cell go to next page and in next page exists one button with name downloadthat i want when i click on that button this file download and save in document folderi dont know about it please guide me that how download any file and store in document folderi searching in internet but i dont understand about itplease tell me with code that how downloaded any file with one button im sorry if i not good english,"['ios', 'objective-c']" +468551,application not in the app store search i just got an email this morning saying my application fuel is ready for sale so i rushed to my iphone and typed fuel in the app store search to not find my application not there why is my app in itunes connect preview but not in the app store search menu this is my first app in the app store,['ios'] +468616,how to extract certain values from an array example from here input arraya b c d eoutput array sliceinput 2 returns c d and eoutput array sliceinput 2 1 returns doutput array sliceinput 0 3 returns a b and cbut how to get for example a d and elike output array sliceinput 0 1output array sliceinput 3 1output array sliceinput 1 1but in one variable is it possibleupdate want to use 1st 3rd and last element of array as if extract 1st 3rd and last element and create new array only with the 3 elements,['php'] +468659,dotnetnuke 7 skinning tutorial i am looking for a decent tutorial on creating skins for dotnetnuke 7 i have not been able to find anything for the most up to date version of dnn and although i have had some success modifying existing skins it would be a lot easier to be able to build them from scratchany suggestions,"['c#', 'asp.net']" +468697,when do i have to use boostasiostrand reading the document of boostasio it is still not clear when i need to use asiostrand suppose that i have one thread using io service is it then safe to write on a socket as follows void connectionwriteboostshared ptrstring msg io servicepostboostbindconnection do writethismsgvoid connection do writeboostshared ptrstring msg if write in progress msg queuepush backmsg else write in progresstrue boostasioasync write socket boostasiobuffermsgget boostbindconnection handle writethis boostasioplaceholderserror void connection handle writeboostsystemerror code const error iferror if msg queueempty boostshared ptrstring msg msg queuefront msg queuepop front boostasioasync write socket boostasiobuffermsgget boostbindconnection handle writethis boostasioplaceholderserror else write in progressfalse where multiple threads calls connectionwrite or do i have to use asiostrand,['c++'] +468726,unable to get log4net working with net windows service i have a windows service with an appconfig and a log4netconfigappconfig configsections section namelog4net typelog4netconfiglog4netconfigurationsectionhandler log4net configsections log4net configsourcelog4netconfig log4netconfiglog4net appender namelogfileappender typelog4netappenderrollingfileappender param namefile valuedprojectsintegrationinterface modulebinlogsmyfirstloggerlog lockingmodel typelog4netappenderfileappenderminimallock appendtofile valuetrue rollingstyle valuesize maxsizerollbackups value2 maximumfilesize value1mb staticlogfilename valuetrue layout typelog4netlayoutpatternlayout param nameconversionpattern valued t 5p c mn layout appender root level valueall appenderref reflogfileappender rootlog4neti have added this in assemblyinfocs tooassembly log4netconfigxmlconfiguratorwatch trueand in one of my classes i haveprivate readonly ilog log logmanagergetloggermethodbasegetcurrentmethoddeclaringtypeand loginfocontenti have given all users full permissions to my logs folder my bin folder which the service is running from has both my appconfig and log4netconfigbut no logging file got generated what settings did i missupdated on 4march2014if you are using a separate config file like i did log4netconfig do remember to set the copy to output directory setting to copy always in the solution explorer,"['c#', '.net']" +468780,resharper generates this file annotationscs why in a setup with visual studio 2012 update 2 and resharper 711 this file annotationscs is generated when creating a new projects i can not find any article describing why resharper does that and if it possible to thisable this i think of resharper as an enhancement of the ide and i do not expect resharper to add files my projects behind my back,['c#'] +468788,c how to use posix semaphores on forked processes i want to fork multiple processes and then use a semaphore on them here is what i triedsem initsem 1 1 semaphore pshared value ifpid 0 parent process waitnull wait all child processes printfnparent all children have exitedn cleanup semaphores sem destroysem exit0else child process sem waitsem p operation printf childd is in critical sectionni sleep1 p i3 increment p by 0 1 or 2 based on i printf childd new value of pdnip sem postsem v operation exit0and the output ischild0 forkedchild1 forked child0 is in critical section child1 is in critical sectionchild2 forked child2 is in critical sectionchild3 forked child3 is in critical sectionchild4 forked child4 is in critical section child0 new value of p0 child1 new value of p1 child2 new value of p3 child3 new value of p3 child4 new value of p4parent all children have exitedthis clearly means the semaphore did not work as it was supposed to can you explain how i should use semaphores on forked processes,['c'] +468818,what does thisplayclass name mean when calling lambda according to this answer when code uses local variables from inside lambda methods the compiler will generate extra classes that can have name such as c thisplayclass1 for example the following completely useless codeclass program static void main try implmain catch exception e consolewritelineetostring static void implmain for int i 0 i 10 i invoke consolewritelinei throw new invalidoperationexception static void invokeaction what what outputs the following call stacksysteminvalidoperationexceptionat consoleapplication1programc thisplayclass2implmainb 0at consoleapplication1programinvokeaction whatat consoleapplication1programimplmainat consoleapplication1programmainnote that there is c thisplayclass2 in there which is a name of a class generated by the compiler to hold the loop variableaccording to this answer c thisplayclass meansc anonymous method closure class thisplayclassokay but what does thisplayclass mean herewhat does this generated class thisplay in other words why is it not magicclass or generatedclass or any other name,"['c#', '.net']" +468865,how to prevent space in output due to line break in the html code i have seen this question up here and some are solving it by comment tags or breaking tags like this it does not work on the first level with tabspace 2 beside it looks horrible a nnoyinga is it noti remember as if i have seen some trick likeadont put here space please tricky ampersand codeis there any such thingi am using now jinja2 python template engine does it have some spacepreventing trickupdatewith jinja2 thanks to dav1d the shortest way i could come up with isa if true no space in the output before this texta endif nor afteris there any shorter way of doing this,['html'] +468876,viewpager background color bleeds through first page i have a viewpager inside a fragment that is exhibiting the following behaviour pages 2 onwards thisplay correctly but the first page is thisplayed as if it were behind the background of the container view as if it had a lower zindex than the background where zindices increase towards the user refer to the images linked belowthe code for page instantiation ispagersetadapternew pageradapter override public void destroyitemviewgroup container int position object item containerremoveviewview item override public int getcount return mimagessize override public view instantiateitemviewgroup container final int position layoutinflater inflater layoutinflater getactivitygetsystemservicecontextlayout inflater service final view layout inflaterinflaterlayoutimage selector null false final imageview image imageview layoutfindviewbyidridimage imagesetimageresourcemimagesgetposition containeraddviewlayout return layout override public boolean isviewfromobjectview view object item return itemequalsview nothing particularly speciallayout for the viewpager fragment isxml version10 encodingutf8relativelayout xmlnsandroid androidlayout widthmatch parent androidlayout heightmatch parent androidbackgroundff2288dd textview androidididtext1 androidlayout widthmatch parent androidlayout heightwrap content androidtextstringhelp1 androidsupportv4viewviewpager androidididpager androidlayout widthmatch parent androidlayout heightmatch parent androidlayout belowidtext1 androidlayout aboveidtext2 androidlayout margin12dip textview androidididtext2 androidlayout widthmatch parent androidlayout heightwrap content androidlayout alignparentbottomtrue androidtextstringhelp2 relativelayoutand for the perpage imagexml version10 encodingutf8relativelayout xmlnsandroid androidlayout widthmatch parent androidlayout heightmatch parent imageview androidididimage androidlayout widthmatch parent androidlayout heightmatch parent androidadjustviewboundstrue relativelayoutagain nothing out of the ordinarybehaviour is present on froyo 22 and gingerbread 23 on physical devices and emulators as well as a physical device running 42the odder part is that when an image is touched to select it a new fragment replaces the original viewpager fragment and if the selected image is from the first page of the viewpager the described behaviour is present there too despite the fragments having entirely different layouts and the new fragment having no defined backgroundlayout for the selectedimage fragmentxml version10 encodingutf8relativelayout xmlnsandroid androidlayout widthmatch parent androidlayout heightmatch parent imageview androidididimage androidlayout widthmatch parent androidlayout heightmatch parent androidadjustviewboundstrue relativelayoutreference images belowfirst pagetransition to second pagedoes anyone have any idea what might be going on,['android'] +468900,why does not documentaddeventlistenerload function work in a greasemonkey script it does not give an error and i put a consolelogloaded userscript wifiautologin the consolelog works but the intended effect of the documentaddeventlistener does not happen after doing a bit more debugging making it print that the addeventlistener was called i thiscovered that it was not being calledsource of script userscript name wifiautologin namespace lfns description hopefully autologins to a captive portal include 1 version 1 runat documentend userscriptdocumentaddeventlistenerload submitaction,['javascript'] +468903,how can i log what is being garbage collected in my javascript code i have built an application that wastes 40 of its time collecting garbage and i am at my wits end trying to find out where it is coming from i have corralled any possible problems in my own code yet it persists i am beginning to suspect some third party code of being the problem and i would like to know if i can somehow track down what is being garbage collected if there is a chromespecific answer that would be great but i will take anything at this point,['javascript'] +468914,how to set default font family for entire android app i am using the roboto light font in my app to set the font i have to add the androidfontfamilysansseriflight to every view is there any way to declare the roboto font as default font family to entire app i have tried like this but it did not seem to workstyle nameappbasetheme parentandroidthemelightstylestyle nameapptheme parentappbasetheme item nameandroidfontfamilysansseriflightitemstyle,['android'] +468935,postgres listennotify rails ryan bates mentions the listennotify functionality of postgres when thiscussing push notifications in this episode but i have not been able to find any hint on how to implement a listennotify in my rails apphere is documentation for a wait for notify function inside of the pg adaptor but i cannot figure out what exactly that doesis designed fordo we need to tap directly into the connection variable of the pg adaptor,['ruby-on-rails'] +468957,enable thisable jquery ui button with ajax i am struggling to understand the options of enablingthisabling jquery ui buttonstypically in the past for any kind of button i have usedjquerymybuttonpropthisabled falsedepending on whether you want it enabledthisabled it would be falsetruethis seemed to work for jquery ui buttons as well what i was doing was checking a certain count and thisabling the button when you first load the pagebut someone could change the count value by deleting something via ajax calldelete jquerydocumentonclick deletebutton function if confirmare you sure you want to delete var hash jquerythisdatadelete var this jquerythis jqueryajax url indexphpoptioncom camtaskdeletehash hash gettoken1formatraw datatype json type post success functiondata if datatype error error message printed to user else thisclosesttrremove deleted so decrement and check if you have exceeded your limit countcount1 if count limit thisable buttons jquery mybutton button option thisabled true else enable add buttons and hide message jquery mybutton button option thisabled false jquerymybuttonattrthisabled false jquerymybuttonpropthisabled false then this should enable the button back again neither prop or attr or this post seemed to work for me only when i did thisjquery mybutton button option thisabled false i guess i do not understand why prop does not work in this context when it does work to thisable my buttons is the best practice to always use the button setter,['jquery'] +468993,using servicestack mini profiler in selfhosted console application is it possible to use servicestack mini profiler in selfhosted console application if it is where should i put profiler enablethisable code in aspnet hosted servicestack it is usually in application beginrequest and application endrequest methods,['c#'] +469010,extracting specific leaf value from nltk tree structure with python i have some questions about nltks tree functions i am trying to extract a certain word from the tree structure like the one given belowtest treeparserootsbarqwhadvpwrb howsqvbp donp prp youvpvb asknpdt ajj totalnn strangerprt rp outpp in onnp dt ann dateprint input tree testprint testleavessbarq whadvp wrb how sq vbp do np prp you vp vb ask np dt a jj total nn stranger prt rp out pp in on np dt a nn datehow do you ask a total stranger out on a datei can find a list of all the words using the leaves function is there a way to get a specific leaf only for example i would like to get the firstlast noun from the np phrase only the answer would be stranger for the first noun and date as the last noun,['python'] +469025,nsdictionary dictionary vs init alloc vs new suppose i want to for example start creating keyvalue pairs using an nsmutabledictionary i then seem to have at least three options for creating an empty mutable dictionary with an unspecified capacitynsmutabledictionary mutdict nsmutabledictionary alloc init 1nsmutabledictionary mutdict nsmutabledictionary new 2nsmutabledictionary mutdict nsmutabledictionary dictionary 3now as i understand it nsobject new is practically if not exactly the same as nsobject alloc init so we can basically merge those two options as far as i am concerned regarding the nsdictionary dictionary method though the documentation saysdictionarycreates and returns an empty dictionary iddictionaryreturn valuea new empty dictionarythiscussionthis method is declared primarily for use with mutable subclasses of nsdictionaryif you donat want a temporary object you can also create an empty dictionary using alloc and initi have a couple of questions regarding this documentation to begin withfirstly why is it even declared in nsdictionary instead of nsmutabledictionary if that is where it is intended to be usedsecondly what do they mean by temporary object in this contextin summary is there a difference between the third alternative above compared to the first two could it have something to do with autoreleasing objects does that even matter in an automatic reference counting arc contextnote that this question applies to other classes as well for example nsdata data and nsarray arrayi am using xcode 461 and ios 61 does it matter which one i use these days using arc perhaps from some perspective on performancethank you for any clear information on this,['objective-c'] +469242,omniauthtwitter email id is not fetched from twitter in ruby on rails i am using omniauthtwitter gem to enable twitter login in my rails application here is my code gemfile gem omniauth 1gem omniauthtwitterroutesrb match authtwittercallback to userstwitter login match authfailure to static pageshomeuser controllerrb def twitter login auth requestenvomniauthauth authentication authenticationfind by provider and uidauthproviderauthuid if authentication sign in authenticationuser redirect to root url else ifuserwhereemail authextraraw infoemailexists flashnotice you already have account in ibetter redirect to root url else user usernew userapply omniauthauth if usersavevalidate false sign in user flashnotice welcome to ginfy redirect to root url else flasherror error while creating a user account please try again redirect to root url end end end endsession helperrb def sign inuser cookiespermanentremember token userremember token selfcurrent user user enduserrb model before save user useremail emaildowncase def apply omniauthauth selfemail authextraraw infoemail selfname authextraraw infoname authenticationsbuildprovider authprovider uid authuid token authcredentialstoken enderb code link to image taglogintwitterpng alt twitter authtwitterclass popup datawidth 600 dataheight 400 email id is not fetched from twitter please help,"['ruby-on-rails', 'ruby']" +469278,setting property source to orgeclipsejstjeeservergestorcontenidows did not find a matching property try all the solutions this is my first post here but not the first time that i visit the page i found a lot of solutions here first of all sorry for my english i will try to explain myself as best i canthis question appears another time in this page but i tried all the solutions that the people post and i still with this problem well here we goi made a project on eclipseindigo for launch like a webservice i did it before with succes is not my first time and when i run on servertomcat7 all seems fine and the appears this warningwarning setpropertiesruleserverserviceenginehostcontext setting property source to orgeclipsejstjeeservergestorcontenidows did not find a matching propertythen appear in the web perspective of eclipse the page http 404 i am telling this because i read in other post that this warning is not a problem but seems that it is for me the project is also vinculated with a jpa persistencei found two solutions for make thissappear this warning first go to server overview and select the option publish module contexts to separate xml files and then try to run on server again but did not workthe other option was remove the project from the server from the server view then run the project under the same server for recreated serverxml but did not work alsoanybody can help me maybe the problem of this http 404 requested resource gestorcontenidows is not available is in another part or its because this warningthe code of my serverxml without comments is this xml version10 encodingutf8 server port8005 shutdownshutdown listener sslengineon classnameorgapachecatalinacoreaprlifecyclelistener listener classnameorgapachecatalinacorejasperlistener listener classnameorgapachecatalinacorejrememoryleakpreventionlistener listener classnameorgapachecatalinambeansglobalresourceslifecyclelistener listener classnameorgapachecatalinacorethreadlocalleakpreventionlistener globalnamingresources resource authcontainer descriptionuser database that can be updated and saved factoryorgapachecatalinausersmemoryuserdatabasefactorynameuserdatabase pathnameconftomcatusersxml typeorgapachecatalinauserdatabase globalnamingresources service namecatalina connector connectiontimeout20 port8080 protocolhttp11redirectport8443 connector port8009 protocolajp13 redirectport8443engine defaulthostlocalhost namecatalinarealm classnameorgapachecatalinarealmlockoutrealmrealm classnameorgapachecatalinarealmuserdatabaserealmresourcenameuserdatabase realm host appbasewebapps autodeploytrue namelocalhost unpackwarstrue valve classnameorgapachecatalinavalvesaccesslogvalve directorylogs patternh l u t quotrquot s b prefixlocalhost access log suffixtxt context docbasegestorcontenidows pathgestorcontenidows reloadabletrue sourceorgeclipsejstjeeservergestorcontenidowshostengine servicethank you,['java'] +469285,best way to prevent sql injections in joomla i take variables from post method and query them on mysql with joomla 25what is the most secured method to use currently i am using jrequestgetvar with mysql real escape string is it correct post with mysql real escape string password mysql real escape string postpwdjrequestgetvar with mysql real escape stringpassword mysql real escape stringjrequestgetvarpwd postjrequestgetvar password jrequestgetvarpwd postjinputpassword jinputgetpwd stringjinput with mysql real escape stringpassword mysql real escape stringjinputgetpwd stringor something else edit 1i found another method which escape characters using mysql real escape string here is my query codedb jfactorygetdboquery dbgetquerytruequeryselectarrayusername password statenamequeryfrom dbusersquerywhereusername loginusername and password loginpassword and state 1dbsetqueryqueryresults dbloadobjectlistedit 2 framework 1 escape method for mysqlpublic function escapetext extra false result mysql real escape stringtext thisgetconnection if extra result addcslashesresult return resultsince escape use mysql real escape string will it be safe to use as below loginusername mysql real escape stringjrequestgetvaruser poststring,"['php', 'mysql']" +469288,how to find sidekiq is running or not in one of my project i am using sidekiqis there any inbuilt sidekiq console methodmethod that helps me to find whether sidekiq is running or notmy requirement is kind of a pre check condition where if sidekiq is not running i will raise a error i tried using the grep likeps ef grep sidekiq but it is not solving my purposethe method i am looking for should be something likesidekiqis running thanks in advancei also triedsidekiq not running193p392 021 system ps aux grep sidekiqankitgupta 6683 00 00 2432768 600 s001 r 1147am 0 grep sidekiqankitgupta 6681 00 00 2433432 916 s001 s 1147am 01 sh c ps aux grep sidekiq truesidekiq is running193p392 022 system ps aux grep sidekiqankitgupta 6725 00 00 2432768 600 s001 s 1157am 0 grep sidekiqankitgupta 6723 00 00 2433432 916 s001 s 1157am 0 sh c ps aux grep sidekiqankitgupta 6707 00 13 3207416 1608 s002 s 1156am 00746 sidekiq 2112 project name 0 of 25 busy true it is always returning true i want to catch the process when it runs,['ruby'] +469453,how to avoid public access to private fields for example let us declareprivate readonly liststring strings new liststringpublic ienumerablestring strings get return strings and now we can do the followingliststring objstringsaddhackedso were really not hiding the list from usage but only hide it behind interface how to hide the list in such example without copying strings in the new collection to restrict modification of the list,"['c#', '.net']" +469515,nspredicate fetch one of each kind i want to create an nsfetchrequest for objects like thisthe object is car which has an attribute colori have four carscar1color redcar2color redcar3color bluecar4color greeni want to create an nspredicate that selects only one car for each colorit does not matter which car it selectshow can i achieve thisin fact i am looking for something similar like a thistinct in sql,"['iphone', 'ios', 'objective-c']" +469526,changing a links href after click with jquery i am trying to create a link that when clicked on switches its href attribute and then goes to that locationmy html isa href relgroup datawpurlawhen clicked i would like the browser to go to the datawpurl location not href location the reason i am using a data attribute is because of the application i am using requires use of the hrefnot relevant heremy jquery isarelgrouponclick functione epreventdefault var wpurl thisattrdatawpurl thisattrhref wpurli am using epreventdefault to prevent the browser from taking the user to the href after the data attribute is assigned to the href how do i then trigger a click using triggerclick and click do not workany ideas,['jquery'] +469532,make an item in list align to right using css3 i have a list as follows ul idmenu lia hrefhomeali lia hrefworka ul lia hrefcss developmentali lia hrefgraphic designali lia hrefdevelopment toolsali lia hrefweb designali ul li lia hrefaboutali lia hrefcontact usali lia hreffeedbackaliuli am attaching image of so far what i have donein this menui want to align feedback to right sidecan anyone tell how to do it,['css'] +469601,login failed for user iis apoolmyapool i having the following error messagecannot open database smallbackery requested by the login the login failed login failed for user iis apoolmyapoolhow can correct this i am using windows 7 enterprise edition and sql server 2012,['asp.net'] +469604,add menu on every listview item so i am developing this app which has a listview in it but i want to add the threedot icon in the corner and when you press it an awesome menu will popup like this in the google play app i have seen many apps that have it so it couldnt be that hard i have googled a lot but to be honest i do not know really what i should google on this must probably be the shortest dumbest question on stackoverflow but i did not really know what my other options was i have a thought that it may just be an spinner that somehow is hidden and when you press the threedot icon it will just pop up in an awesome way or is this implemented in the android sdki would really appreciate if someone want to help me and answer my queation thanks in advance sorry for bad englishguiceu,['android'] +469683,a good way to make long strings wrap to newline in python 3x in my project i have a bunch of strings that are read in from a file most of them when printed in the command console exceed 80 characters in length and wrap around looking uglyi want to be able to have python read the string then test if it is over 75 characters in length if it is then split the string up into multiple strings then print one after the other on a new linei also want it to be smart not cutting off full words ie the quick brown newline fox instead of the quick bronewlinewn foxi have tried modifying similar code that truncates the string after a set length but just trashes the string instead of putting it in a new linewhat are some methods i could use to accomplish this,['python'] +469757,convert a list into an observablecollection i have a listt which is being populated from json i need to convert it into an observablecollectiont to bind it to my gridviewany suggestions,['c#'] +469815,how to use zxing library wihtout installing barcodescanner app i have been developing an android app to scan the barcode and qr code and send the results to some other application http i have read most of the documentation over internet and here in stack over flow and got it working i could able to run the stand alone zxing android app on my device also i could run my own separate android app to use zxing intent to scan the bar code but even after reading so many questions here and some of the blogs in internet i could not get my strict requirements i want to achieve following things 1 i do not want to install a separate barcode scanner app in my device to get my own app to work to scan the barcode2 i used following codeintent intent new intentcomgooglezxingclientandroidscanstartactivityforresultintent 0and when i run the app in my devide it asks select the application to complete this action and it shows google and google goggles and it opens the google page default camera and scans the barcode i wanted captureactivtiy default capturing page to come not googles one to scan the bar code 3 i have tried using zxing in my own app as library but it did not work could you please tell where exactly i am going wrong to get this done,['android'] +469852,use cases for stdadd const and similar some type transformations in type traits can also be expressed using core language syntax eg stdadd constype isseems equivalent to const t dtto for stdadd lvalue reference and perhaps others what is the use for these type traitsi fully understand the standard would be providing an incomplete toolbox without them and i can imagine use in a meta way something like thistemplatetypename in template typename class modifierstruct apply typedef typename modifierttype outapplyint stdadd constare there any other use cases for these traits which can be expressed syntactically or are they just included out of a sense of completeness and for the occasional metause,['c++'] +469926,should i delete temp folder when publishing umbraco when i publish content to my server should i publish appdatatemp folder as welogic is not to do that but cannot find information online about it,['.net'] +469955,c does char pointer to stdstring conversion copy the content when i convert a char to stdstring using the constructorchar ps hellostdstring strpsi know that std containers tend to copy values when they are asked to store them is the whole string copied or the pointer onlyif afterwards i do str bye will that change ps to be pointing to bye,['c++'] +470000,railsrspec testing a redirect in the controller so i am currently writing a test for a controller in an existing controller that just didnt have one before what i want to test is a redirect that happens when someone is not allowed to edit something vs someone that is allowed to edit itthe controller action being edit def edit if scorecardreviewed admin company scorecardcompany custom css include confirmation page else redirect to back endendso if a scorecard has been reviewed then only an admin can edit that scorethe routes for that controller scorecardsresources scorecards do member do get report end resources inaccuracy reports only new createendand finally the test require spec helper describe scorecardscontroller do describe get edit do beforeeach do agency factoryagency va factoryva user agency agency admin factoryadmin company factorycompany scorecard factoryscorecard level 1 company company agency agency reviewed true requestenvhttp referer scorecard end context as a admin do beforeeach do controllerstubcurrent userand return admin end it allows you to edit a reviewed scorecard do get edit id scorecardid responsestatusshould be200 end end context as a va user do beforeeach do controllerstubcurrent userand return va end it does not allow you to edit a reviewed scorecard do get edit id scorecardid responseshould redirect to back end end endendso a va when trying to edit a reviewed score will be redirected back where a admin wontbut when running this through rspec i getscorecardscontroller get edit as a admin allows you to edit a reviewed scorecard as a va user does not allow you to edit a reviewed scorecard failed 1failures 1 scorecardscontroller get edit as a va user does not allow you to edit a reviewed scorecard failureerror responseshould redirect to back expected response to be a redirect to scorecard but was a redirect to speccontrollersscorecards controller specrb33in block 4 levels in top requiredfinished in 048517 seconds2 examples 1 failureso i dont know if its working or not since i set the requestenvhttp referer scorecard as the place that should be the back as it where or am i missing the idea all together looking at httpstatus there are the 300 responses that i could use but i wouldnt know where to startany help would be awesome editi could test it by doing it like thisresponsestatusshould be302but i got the idea from this question and it sounds like this could be powerful as it specifies the url redirected toany one have a working test like this,['ruby-on-rails'] +470013,split string in two on given index and return both parts i have a string that i need to split on a given index and then return both parts seperated by a comma for examplestring 8211 8211 98700 98700so i need to be able to split the string on any given index and then return both halves of the string built in methods seem to perform the split but only return one part of the splitstringslice only return extracted part of the stringstringsplit only allows you to split on character not indexstringsubstring does what i need but only returns the substringstringsubstr very similar still only returns the substring,['javascript'] +470018,how to return json object i am using a jquery plugin that need a json object with following structurei will be retrieving the values from database results id 1 value abc info abc id 2 value jkl info jkl id 3 value xyz info xyz here is my classpublic class results int id string value string info public int id get return id set id value public string value get return value set value value public string info get return info set info value this is the way i serialize itresults result new resultsresultid 1resultvalue abcresultinfo abcstring json jsonconvertserializeobjectresultbut this will return only one row can you please help me in returning more than one result how can i get the result in the format specified above,['c#'] +470063,common css media queries break points i am working on a responsive web site with css media queriesis the following a good organization for devicesphone ipad landscape portrait desktop and laptop large screenwhat are the common media queries breakpoint values i am planning to use the following breakpoints320 smartphone portrait481 smartphone landscape641 or 768 ipad portrait 961 ipad landscape small laptop 1025 desktop and laptop1281 wide screenwhat do you think i have a few doubts as points,['css'] +470071,how to return a char array from a function in c i want to return a character array from a function then i want to print it in main how can i get the character array back in main functionincludestdiohincludestringhint main int i0j2 char sstring char test testsubstringijs printfstest return 0char substringint iint jchar ch int mnk0 char ch1 ch1charmallocji11 nji1 whilekn ch1kchi ik return char ch1please tell me what am i doing wrong,['c'] +470082,how to get arraybag of elements from hive group by operator i want to group by a given field and get the output with grouped fields below is an example of what i am trying to achieveimagine a table named sample table with two columns as belowf1 f2001 1001 2001 123002 2002 3003 5i want to write hive query that will give the below output001 1 2 123002 2 3003 5in pig this can be very easily achieved by something like thisgrouped relation group sample table by f1can somebody please suggest if there is a simple way to do so in hive what i can think of is to write a user defined function udf for this but this may be a very time consuming option,['sql'] +470085,flask application timeout with amazon load balancer i am trying to use a flask application behind an amazon load balancer and the flask threads keep timing out it appears that the load balancer is sending a connection keepalive header and this is causing the flask process to never return or takes a long time with gunicorn in front the processes are killed and new ones started we also tried using uwsgi and simply exposign the flask app directly no wrapper all result in the flask process just not respondingi see nothing in the flask docs which would make it ignore this header i am at a loss as to what else i can do with flask to fix the problemcurl and direct connections to the machine work fine only those via the load balancer are causing the problem the load balancer itself does not appear to be doing anything wrong and we use it successfully with several other stacks,['python'] +470094,dynamically update grunt config fields i have few projects in separate directories and want to build them in the same wayi want to define project name from task as param grunt tasks will use this project path as root path but i have several subfolders and do not want to update it manually i just want to update the project there is any chance to do thatgruntinitconfig paths project null projectstylesheets pathsproject stylesheets gruntregistertaskserver functionproject project some name var paths gruntconfiggetpaths pathsproject project gruntconfigsetpaths paths project some name projectassets stylesheets i was thinking about using js functions outside he config but not sure is this the best practice,['javascript'] +470133,align left edge to center relativelayout i have the following requirement drastically simplifiedtext 2 must start from the center of the screeni could only achieve this using linearlayoutsmore codemore codelinearlayout androidbaselinealignedfalse androidweightsum2 androidlayout widthmatch parent androidlayout heightwrap content linearlayout androidlayout weight1 androidorientationhorizontal androidlayout width0dp androidlayout heightwrap content textview androidlayout widthwrap content androidlayout heightwrap content androidtexttest one textview androidlayout widthwrap content androidlayout heightwrap content androidtexttest two linearlayout linearlayout androidlayout weight1 androidorientationhorizontal androidlayout width0dp androidlayout heightwrap content textview androidlayout widthwrap content androidlayout heightwrap content androidtexttest three textview androidlayout widthwrap content androidlayout heightwrap content androidtexttest four linearlayout linearlayoutmore codemore codesince i have already too many nested views thus getting a myfilexml has more the 10 levels bad for performance warning i would like to know if i can get the same result with one relativelayout i have been through the documentation but i could not find a property that allows me that,['android'] +470175,how to execute python script from java i can execute linux commands like ls or pwd from java without problems but could not get a python script executedthis is my codeprocess ptry systemoutprintlnsend string cmd bashbin c echo password python scriptpy packettostring systemoutprintlncmd p runtimegetruntimeexeccmd bufferedreader br new bufferedreadernew inputstreamreaderpgetinputstream string s brreadline systemoutprintlns systemoutprintlnsent pwaitfor pdestroy catch exception e nothing happened it reached send but it just stopped after iti am trying to execute a script which needs root permissions because it uses serial port also i have to pass a string with some parameters packet,"['java', 'python']" +470218,how to get pythondev for windows we are trying to install pil and getting the errorerror command gcc failed with exit status 1many similar questions including this one installing reportlab error command gcc failed with exit status 1 suggest installing the pythondev packagewhere can this be sourced for windows 7 pip install pythondev did not work,['python'] +470255,javascript replace single quote with double quote the following code replaces only one single quote i need to replace all the single quote with double quotes how do i do itvar a column1value0column2value1column3value2var b areplace,['javascript'] +470265,android valgrind build fails hello i am trying to build valgrind for androidarm on linux mint 13 it fails with makeecho this is a generated file composed of the following suppression rules defaultsuppecho expsgchecksupp xfree3supp xfree4supp glibc2xdrdsupp glibc234567nptlhelgrindsupp glibc2xsupp defaultsuppcat expsgchecksupp xfree3supp xfree4supp glibc2xdrdsupp glibc234567nptlhelgrindsupp glibc2xsupp defaultsuppmake allrecursivemake1 entering directory homemattdesktopvalgrindvalgrind381making all in includemake2 entering directory homemattdesktopvalgrindvalgrind381includemake2 nothing to be done for allmake2 leaving directory homemattdesktopvalgrindvalgrind381includemaking all in vexmake2 entering directory homemattdesktopvalgrindvalgrind381vexmake allammake3 entering directory homemattdesktopvalgrindvalgrind381vexgcc dhave config h i i i iinclude ivexpub dvga arm1 dvgo linux1 dvgp arm linux1 dvgpv arm linux vanilla1 ipriv m32 o2 g wall wmissingprototypes wshadow wpointerarith wstrictprototypes wmissingdeclarations wnoformatzerolength fnostrictaliasing fnobuiltin marm mcpucortexa8 wbadfunctioncast wcastqual wcastalign fstrictaliasing wnolonglong wnopointersign fnostackprotector mt libvex arm linux amain globalso md mp mf depslibvex arm linux amain globalstpo c o libvex arm linux amain globalso test f privmain globalsc echo privmain globalscgcc warning amcpua is deprecated use amtunea or amarcha insteadcc1 error unrecognised command line option amarmaprivmain globalsc10 error bad value cortexa8 for mtune switchmake3 libvex arm linux amain globalso error 1make3 leaving directory homemattdesktopvalgrindvalgrind381vexmake2 all error 2make2 leaving directory homemattdesktopvalgrindvalgrind381vexmake1 allrecursive error 1make1 leaving directory homemattdesktopvalgrindvalgrind381make all error 2i am using ndkr8e and valgrind 381 the configure ends with maximum build arch arm primary build arch arm secondary build arch build os linux primary build target arm linux secondary build target platform variant vanilla primary dvgpv string dvgpv arm linux vanilla1 default supp files expsgchecksupp xfree3supp xfree4supp glibc2xdrdsupp glibc234567nptlhelgrindsupp glibc2xsupp what can i do to fix this alternatively are there any prebuilt androidarm valgrind binaries that i can use,['android'] +470301,tornado requestbody my tornado application accepts post data through http body requestin my handler i am able to get the request def postself data selfrequestbodythe data i am getting is in the from of strdictionary is there a way to receive this data in the form of a python dictionaryi do not want to use eval on the server side to convert this string to a python dictionary,['python'] +470317,async methods return null if i try to mock a type containing an async method such as interface foo taskint barthen the mocks bar method is returning null i guess moq is choosing defaulttaskint as default return value for my method which is indeed null however moq should rather choose something like taskfromresultdefaultint as default value can i force moq to make async methods returning nonnull tasks,['c#'] +470356,raytracer refraction bug i am writing a raytracer in c and i have been having some issue with refractions i am rendering a sphere and a ground plane and the sphere should refract however it looks more like a sphere within a sphere the outer sphere looks to be shaded properly but not refracting while the inner sphere looks like it is being selfshadowed heres a link to what it looks like heres the relevant codeinside main raytrace function ifrefraction 00f the surface is refractive calculate refraction vector ray refractintersection objlistbestobjrefractedray raydirintersectioncos thetar0 recurse refrcolor raytracerefract else no refraction refrcolor background refractedrayvec3vec3floatfloat initialize variables do geometric transforms into air out of obj ifdotraynormal 0 n1 ior n2 10f cos dotraynormal into obj out of air else n1 10f n2 ior cos dotraynormal normal normal check value under sqrt float and n1n2 float thisc 1pown21powcos2 ifthisc 0 total internal reflection return ray 2cosnormal reflection vector return nrayncossqrtthiscnormalthe sphere used to look worse then i remembered to normalize my vectors and it looks like this previously it looked like only the inner sphere all throughout inside the main raytrace function i do the refraction the same way as reflection just using the refracted ray instead i have also tried modifying the incoming point of intersection and ray with epsilon to check for selfrefracting as you can get in shadowingany help would be appreciated,['c++'] +470358,mysql myisam how to perform a read without locking a table my question is a follow up to this answer i want to find out how to perform a select statement without locking a table with myisam engine the answer states the following if you have innodb but not myisam what is the equivalent for myisam engine set transaction isolation level read uncommitted select from table name commit,"['mysql', 'sql']" +470396,advantage of t4 templates over class files what is the advantage of t4 templates over class files in aspnetlike we are generating strongly typed class using t4 templates we can do the same using c class files in aspnet so what is the advantage of t4 template over normal class filesanyone please point out the scenerio wher t4 can be implemented over class filesregardssujith,"['c#', 'asp.net']" +470426,bind complex json form data automatically my json data coming in requestbodyasformurlencodedgetrecordsstringfootermid793340stringbartermid460288my form definitionpublic static class myform constraintsrequired public listmapstringstring records public string somefieldit does not bind the records automatically then i tried with a pojo insteadpublic static class record public string string public string termid public void setstringstring string thisstring string public void settermidstring termid thistermid termid and adapted the formpublic static class myform constraintsrequired public listrecord records public string somefieldit does not bind the data automatically either do i really need to use low level apis like jackson for this simple use case any pointer could not find a copypaste example and from jackson i have orgcodehausjackson and comfasterxmljackson on my classpathupdate 20130510 added a secondary field somefield to clarify that the records is just one field not the whole data structure the answer below from i cannot see the answers on this edit screens so never mind there is just one works but only with the records heres an exampleprivate listrecord recordsfromrequest string jsondata requestbodyasformurlencodedgetrecords formrecord recorddummyform formformrecordclass iteratorjsonnode it jsonparsejsondata0iterator listrecord records new arraylist while ithasnext recordsaddrecorddummyformbinditnextget return recordsfor the other form fields i do as usual formmyform form playdataformformmyformclassbindfromrequestso right now i get to all the posted form data and my problem is solved this way thanks however it is a bit ugly what i cannot figure out yet is how to have all post data in one object if someone replies to this then i will update the question and remove this part otherwise i will accept the single answer in a couple of days,['java'] +470482,can javascript ajax lead to deadlocks i have a thought experiment in my code i have a global variable say var changeme and i am making few ajax calls call one third param is the callback function ajaxfunctionurl1 paramsfunctiondata changeme data call two ajaxfunctionurl2 paramsfunctiondata changeme data so changeme value will depend on which ajax call finishes last which means the call that finishes last will overwrite the valuewhat if both calls finish exactly at the same time same timestampsince javascript is singlethreaded we normally would not get this problem but this may arise in the case of settimeout and ajax calls i do not know how i can replicate this issue with precision so it still remains a thought experimentso how in multithreaded conditions is a deadlock handledi prefer an answer like changeme will be url1 or url2 and a clear situation explanationthanks in advance,['javascript'] +470491,python equivalent of zip for dictionaries if i have these two listsla 1 2 3lb 4 5 6i can iterate over them as followsfor i in rangeminlenla lenlb print lai lbior more pythonicallyfor a b in zipla lb print a bwhat if i have two dictionariesda a 1 b 2 c 3db a 4 b 5 c 6again i can iterate manuallyfor key in setdakeys setdbkeys print key dakey dbkeyis there some builtin method that allows me to iterate as followsfor key value a value b in common entriesda db print key value a value b,['python'] +470512,google maps api v2 zooming near the marker i am using google maps api v2 in android i have placed a marker by using latitude and longitude the marker is shown at correct place but i want the the map should show area around the marker only ie i want to zoom to markers position when the map is shown so it shows nearby region of the marker onlyany help would be great,['android'] +470606,ie conditional operator or if is greater than ie9 or not ie i want to only include history and ajaxify if the browser is ie9 or greater or is not ieif gte ie 9 script typetextjavascript srcassetsjspluginshistoryjsscript script typetextjavascript srcassetsjspluginsajaxifyjsscriptendifhow can i use the or operator to say thisif gte ie 9 ie thanks,['html'] +470615,how to detect collisions between fast moving objects generally to detect collisions in canvas games i use something likefunction collidesa b return ax bx bwidth ax awidth bx ay by bheight ay aheight bybut this only detects collisions if the objects are touching at the time the frame is processed if i have a sprite whose speed in pixelsframe is greater than the width of an obstacle in its path it will pass through the obstacle without the collision being detected how would i go about checking whats in between the sprite and its destination,['javascript'] +470628,visual c not inlining simple const function pointer calls dear stackoverflowersi got a simple piece of code which i am compiling on microsoft visual studio c 2012int addint x int y return x ytypedef int func tint intclass apublic const static func t fpconst func t afp addint main int x 3 int y 2 int z afpx y return 0the compiler generates the following codeint main013fba2430 sub rsp28h int x 3int y 2int z afpx y013fba2434 mov edx2 013fba2439 lea ecxrdx1 013fba243c call qword ptr afp 013fba45c0h return 013fba2442 xor eaxeaxi compiled this on the full optimisation obx flag and any suitable for inline function expansion ob2 flagi was wondering why the compiler does not inline this call expecially since it is const does any of you have an idea why it is not inlined and if it is possible to make the compiler inline itchristianedit i am running some tests now and msvc fails to inline the function pointers too wheni move the const pointer out of the class and make it globali move the const pointer out of the class and make it local in maini make the pointer nonconst and move it in locallywhen i make the return type void and giving it no parametersi kind start believing microsoft visual studio cannot inline function pointers at all,['c++'] +470634,how to add facebook share button on my website i have this code that suppose to work but does not work if this helps you in anyway that would be greatscript src usalljsscript pa onclickposttofeed return falseimg srcimagesfbpng ap p idmsgp script fbinitappid 338334836292077 status true cookie true function posttofeed calling the api var obj method feed redirect uri link picture name facebook dialogs caption reference documentation description using dialogs to interact with users function callbackresponse documentgetelementbyidmsginnerhtml post id responsepost id fbuiobj callback scripti want to add facebook share button on my website that should just post my websites content on the wall who want to share iti have researched a lot but did not get anything pleas help me in this thanks in advance,['javascript'] +470720,how can i generate notifications that data written via a filestream is on the thisk i would like to read a file after i have been notified that a certain amount of data has been written to it via another thread my intial attempt was to create a reactive subject in my writer class that calls onnext after the write to the binarywriter it is composed with this binarywriter uses a filestreamthis does not seem to work though i am assuming i am not guaranteed that the write has been flushed i would rather not manually call flush is there an existing way to do this,['c#'] +470733,limit json stringification depth when stringifying an object using jsonstringify or something similar is there a way to limit the stringification depth ie only go n levels deep into the object tree and ignore everything that comes after that or better put placeholders in there indicating something was left out i know that jsonstringify takes a replacer function of the form function key value but i did not find a way to get the depth in the original object of the current keyvaluepair handed to the replacer functionis there a way to do this with the default jsonstringify implementation or have i reached a point where i should just implement the stringification myselfor is there another stringification library you can recommend that has this option,['javascript'] +470734,adjusting and image size to fit a div bootstrap i am trying to get an image to fit within a specific size div unfortunately the image is not conforming to it and is instead proportionally shrinking to a size that is not big enough i am not sure what the best way is to go about getting the image to fit inside it is if this is not enough code i would be happy to supply more and i am open to fixing any other errors that i am overlookinghere is the htmldiv claspan3 top1 div classrow div claspan3 food1 img srcimagesfood1jpg alt div div div classrow div claspan3 name1 heres the name div div div classrow div claspan3 description1 heres where i describe and say read more div div divmy csstop1 height390px backgroundcolorf margintop10pxfood1backgroundcolor0height230pxname1backgroundcolor5height90pxdescription1backgroundcolor7height70px,"['html', 'css']" +470740,get userfriendly name for generic type in c is there an easy way without writing a recursive method which will give a user friendly name for a generic type from the type classeg for the following code i want something like listdictionaryint instead of the shorthand or full name given by the following codevar list new listdictionaryint stringvar type listgettypeconsolewritelinetypenameconsolewritelinetypefullname,"['c#', '.net']" +470769,css3 how to calculate height and width after scale is there any jquery solution that to find exact thisplay height of the webkittransform scale07851the scale value may vary that is why looking for proper solution tested these options unfortunately did not find solution yet heightinnerheightouterheightouterheighttruei think this issue only can fix one the basis of mathematics,"['javascript', 'jquery']" +470799,access requirejs path configuration i notice in the documentation there is a way to pass custom configuration into a modulerequirejsconfig baseurl js paths jquery libsjquery191 jqueryui libsjqueryui192 config baz color blue which you can then access from the moduledefinemodule function module var color moduleconfigcolor bluebut is there also a way to access the toplevel paths configuration something like thisdefinemodule require function module require consolelog modulepaths no method paths consolelog requirepaths no method pathsfyi this is not for a production site i am trying to wire together some odd debugconfig code inside a qunit test page i want to enumerate which module names have a custom path defined this question touched on the issue but only lets me query known modules not enumerate them,['javascript'] +470804,using if else to determine a select into statement i am having some strange issues using if else to determine which one or two select statements to execute the error message i am getting when running the full statement is that my temporary table already exists but that does not occur if i run two separate executions of two separate if statements here is the code in sql serverif select businessdaycount from calendartbl 1 begin select into temp1 from previousmonthtbl endelse begin select into temp1 from currentmonthtbl end,['sql'] +470817,duplicate all rows in a table and prevent duplicate keys i am tring to do thisget all rows in a blogs named tablecopy them in a temporary databaseedit the language field of this temporary table recordsinsert into the blogs tableand i am trying it like thiscreate temporary table tmptable select from blogs where lan 2update tmptable set lan 1insert into blogs select from tmptable dump database tmptablebut of corse i get duplicated key errorhow can i prevent itediti triedcreate temporary table tmptable select from blogs where lan 2update tmptable set lan 1alter table tmptable drop idinsert into blogs select from tmptable dump database tmptablebut then the column count does not match value count at row 1 editi believe this will work and it did cause i know how many records existcreate temporary table tmptable select from blogs where lan 2update tmptable set lan 1update tmptable set id id 10insert into blogs select from tmptablebut how can i do it properly just set the next avaliable autoincrement value for primary keyid without phpalike editmaybe something like thiscreate temporary table tmptable select from blogs where lan 2update tmptable set lan 1update tmptable set id id select id from blogs order by id desc limit 1insert into blogs select from tmptable,"['mysql', 'sql']" +470836,render form errors with the label rather than field name i would like to list all form errors together using formerrors in the template this produces a list of form fields and nested lists of the errors for each field however the literal name of the field is used the generated html with an error in a particular field might look like thisul classerrorlist li target date mdcy ul classerrorlist lithis field is requiredli ul liuli would like use the errorlist feature as it is nice and easy however i want to use the label target date say rather than the field name actually i cannot think of a case in which you would want the field name thisplaying for the user of a webpage is there way to use the rendered error list with the field label,['python'] +470837,data compression algorithms i was wondering if anyone has a list of data compression algorithms i know basically nothing about data compression and i was hoping to learn more about different algorithms and see which ones are the newest and have yet to be developed on a lot of asics i am hoping to implement a data compression asic which is independent of the type of data coming in audiovideoimagesetcif my question is too open ended please let me know and i will revise thank you,"['c++', 'c']" +470868,make some of datagrid cells span multiple columns ok i have searched for pretty long time for solution of this problem i am developing simple printing system for wpf datagrids and have managed to print tables with uniform cell placement using datatable and setting it as datagrids itemsourcehowever i needed some rows to contain only one cell you can think of it like row group header inside the tableso since i have not found anything about datatables cells spanning multiple columns if this can be made it would be a great thing to know how i figured i would have to add rows to datagrid manually and solve it something like thismake new datagrid with desired columnsadd rows one by one setting the datagridcellpanel that spans or not spans through rowsthe second point is where i have the problem if it is right that is i need to add row to a datagrid that uses simple array of strings as cell data index in array should mach the cell index is there an easy way to do something like that,['c#'] +470871,is there a way to terminate a java application that uses java3d without calling systemexit java3d starts several system threads and does not set the isdaemon flag on them when i thispose the only jframe of my application it would not terminate because these threads are still runningcalling systemexit seems to be the only way to terminate the application or killing it from outside of courseas i do not like to call systemexit i have tried the following but without successcalling removealocales on the virtualuniverse this terminates most of the threads but still there is one named j3drenderer1 remainingusing reflection to obtain a reference to the the field threadgroup rootthreadgroupp in javaxmediaj3dmastercontrol and seting isdeamon true on that threadgroup this did not seem to have any effectgeting a reference to the threadgroup named java3d and calling interrupt on it this caused the java3d threads to write interruptedexception to stderr but nothing elselocate the sources of the java3dcore library and propose a patch i found a repository here and here the later one looks official but shows the last change in it happened 5 years ago and the former one looks like a private fork to mei am close to giving up and make that call to systemexit but i still do not like it do you know a better way,['java'] +470903,responsive jquery ui dialog and a fix for maxwidth bug with many sites leveraging jquery ui there are some major shortcomings that have to be overcome because jquery ui does not support responsive design and there is a longstanding bug when maxwidth is used in conjunction with widthautoso the question remains how to make jquery ui dialog responsive,"['jquery', 'css']" +470911,edit json response from curl response phpjson url idxcallbackangularcallbacks 0curl curl initcurl setoptcurl curlopt url json urlcurl setoptcurl curlopt header falsecurl setoptcurl curlopt returntransfer 1curl setoptcurl curlopt http version curl http version 1 1response curl execcurljsonstring json encoderesponse truedatajson decodejsonstringecho preprint rdataprestatus curl getinfocurlcurl closecurlthe output isangularcallbacks 0 thisclaimer xx license xx timestamp 1368136869 base usd rates aed 3672819 afn 53209 all 107953875 aoa 96358934 ars 5214887 xof 501659003 xpf 914876 zmk 52271083 zmw 5314783 zwl 322387247 but i need to edit this output to this one only with three rates aedafnaoa so basically edit the json response in the section of rates how can i do thatangularcallbacks 0 thisclaimer xx license xx timestamp 1368136869 base usd rates aed 3672819 afn 53209 aoa 107953875,['php'] +470946,let keyword in the for loop ecmascript 6s let is supposed to provide block scope without hoisting headaches can some explain why in the code below i in the function resolves to the last value from the loop just like with var instead of the value from the current iterationuse strictvar things for let i 0 i 3 i thingsfun i function consolelogi thingsfun0 prints 3thingsfun1 prints 3thingsfun2 prints 3according to mdn using let in the for loop like that should bind the variable in the scope of the loops body things work as i would expect them when i use a temporary variable inside the block why is that necessaryuse strictvar things for let i 0 i 3 i let index i thingsfun i function consolelogindex thingsfun0 prints 0thingsfun1 prints 1thingsfun2 prints 2i tested the script with traceur and node harmony,['javascript'] +470979,setting value for javascript variable from code behind c i understand the difference between clientside and serverside scripting i have a javascript function and variable in my masterpagescript languagejavascript typetextjavascript var needtoconfirm false windowonbeforeunload confirmexit function confirmexit if needtoconfirm needtoconfirm false return currently in edit mode if you leave the page now then you will lose unsaved changes scriptgiven the fact that on my aspnet clientside i can change the value of my needtoconfirm variable to true onclientclick but by default it is false heres an example aspbutton idbtnedit runatserver text edit onclickbtnedit click onclientclickneedtoconfirm true now the question here is when on the c serverside i have to set the needtoconfirm to true under an ifstatement but not necessarily on page loadprivate void setdefault if sessiondefid cust null i want to change the variable value here thanksupdatei am using net 20 classic and webforms,"['c#', 'javascript', 'asp.net']" +470984,alter data type of a column to serial in pgsql is there a way to have a table of several values and choose one of them say other id find out what its highest value is and make every new entry that is put in the table increment from that valuei suppose this was just too easy to have had a chance of workingalter table address alter column new id type serial error type serial does not existthanks much for any insight,['sql'] +471013,using servicestack to upload image files we have a requirement to upload images using servicestack apis i am aware of two possible ways1 use json object to upload file using base64 string2 use multipartformdatais there any other way of uploading files using servicestack which is better in terms of best practices,['c#'] +471033,how to store data from website to parsecom and how to to fetch data of it in my application i want to use the parse database for developing web app since data will upload from the desktop pc and retreival of the same will be done in parse mobile applicationis it possible to use the parse database for website backend since i want to use same parse database for application and desktop versioncan anyone please help me by providing some idea how to achieve thatthanks in advance,['android'] +471059,correct way to get the corethispatcher in a windows store app i am building a windows store app and i have some code that needs to be posted to the ui threadfor that i would like to retrieve the corethispatcher and use it to post the codeit seems that there are a few ways to do so first waywindowsapplicationmodelcorecoreapplicationgetcurrentviewcorewindowthispatcher second waywindowcurrentthispatcheri wonder which one is correct or if both are equivalent,['c#'] +471072,scrolling up and down by a set amount of pixels using jquery scrolltop i have a list of links in a div with overflow what i want to happen is that the user can navigate in this menu of links with an up and down button i want the div to scroll up or down by the height of 1 link element every time the user clicks the corresponding button i tried out some code but i cannot seem to figure out how to make it scroll the right amount in both directions can anyone help me outall the links have the same classedit i have already managed to scroll up and down now i just need to scroll in little steps of the height of 1 linkfunction var ele scrollervar speed 10 scroll 5 scrollingscrollerbtnupclickfunction scroll the element up scrolling windowsetintervalfunction elescrolltop elescrolltop scroll speedscrollerbtndownclickfunction scroll the element down scrolling windowsetintervalfunction elescrolltop elescrolltop scroll speedscrollerbtnup scrollerbtndownbind click functione prevent the default click action epreventdefault mouseleave function if scrolling windowclearintervalscrolling scrolling false,"['javascript', 'jquery']" +471088,collection was modified enumeration operation may not execute in vs winforms designer since converting our company inhouse winforms application from a vs2008 to vs2012 project i have problems using the winforms designersometimes the designer falls into an error state giving the following error messagecollection was modified enumeration operation may not execute with the call stack sayinginstances of this error 1 1 hide call stack at systemthrowhelperthrowinvalidoperationexceptionexceptionresource resourceat systemcollectionsgenericlist1enumeratormovenextrareat systemcollectionsgenericlist1enumeratormovenextat microsoftvisualstudiodesignvstyperesolutionserviceassemblyspecfoundlist1 assemblies string assemblyfullnameat microsoftvisualstudiodesignvstyperesolutionserviceadependenciesassembly a string filenameat microsoftvisualstudiodesignvstyperesolutionserviceassemblyentryget assemblyat microsoftvisualstudiodesignvstyperesolutionservicesearchbyshortnamestring partialname string fullname assemblyentry entries assembly assemblyat microsoftvisualstudiodesignvstyperesolutionservicesearchnormalentriesassemblyname assemblyname string typename boolean ignoretypecase assembly assembly boolean fastsearchat microsoftvisualstudiodesignvstyperesolutionservicesearchentriesassemblyname assemblyname string typename boolean ignorecase assembly assembly referencetype reftypeat microsoftvisualstudiodesignvstyperesolutionservicesearchentriesassemblyname assemblyname string typename boolean ignoretypecase assembly assemblyat microsoftvisualstudiodesignvstyperesolutionservicesystemcomponentmodeldesignityperesolutionservicegetassemblyassemblyname name boolean throwonerrorat microsoftvisualstudiodesignvstyperesolutionservicesystemcomponentmodeldesignityperesolutionservicegetassemblyassemblyname nameat microsoftvisualstudiodesignvsdynamictypeserviceonassemblyresolveobject sender resolveeventargs eat systemappdomainonassemblyresolveeventruntimeassembly assembly string assemblyfullname it seems that the designer is trying to change the list of referenced assemblies maybe because of some invalid assemblieswhile trying to solve the issue i figured out that changing the enable clickonce security option under projectpropertiessecurity can bring the designer back to work but if the option is turned on and i get the designer error turning it off and rebuild all can solve the problem from time to time and vice versa that is why i am a little lost right now,['c#'] +471101,partialview the model item passed into the dictionary is of type customer but this dictionary requires a model item of type userprofile model customerhtmlpartial userprofile userprofilemodeluserprofilewhen i run this code i get this errorthe model item passed into the dictionary is of type customer but this dictionary requires a model item of type userprofilepartial view userprofile is strongly typedi want to be able to edit these field any suggestions,['c#'] +471122,arraysort stability in different browsers arraysort sorting stability in different browsersthis is an old question i think it would be helpful if we collect the most recent data hereplease click this fiddle and share your resultsfiddle codea forvar i 0 i 10 i apushkey100 mathroundmathrandom 100 val i 10 asortfunctionx y return xkey ykey b forvar i 0 i 10 i bpushaikey 10 aivalc bslice0bsortstable bjoin cjoindocumentbodyinnerhtml navigatoruseragenttostring br stable stable unstable,['javascript'] +471163,update select2 data without rebuilding the control i am converting an input typehidden to a select2 dropdown and feeding it data through the query methodinputhiddenselect2 query function query querycallback data the data is in the format select2 expects and all works well the problem is i needed to hack the select2 ui and position two buttons on top of the search bar that when clicked will perform ajax calls and will have to update the select2 contentnow i need those updates to occur without rebuilding the select2 entirely but rather just refreshing the items on the dropdown i cannot find a way to pass a new set of data to an already created select2 control is that possible,['jquery'] +471172,allowed html tags in javadoc the checkstyle rule javadocstyle does not allow the tag u according to the docs the checks were patterned after the checks made by the doccheck doclet available from sun unfortunately i have not found doccheck anywhere neither have i found any official documentation about allowed html tags in javadoc is there any,['html'] +471229,how to load in pythonrsa a public rsa key from a file generated with openssl i generated a private and a public key with the following commandsopenssl genrsa out private keypem 512openssl rsa in private keypem pubout out public keypemi then tried to load them with a python script using pythonrsaimport osimport rsawith openprivate keypem as privatefile keydata privatefilereadprivkey rsaprivatekeyload pkcs1keydatapemwith openpublic keypem as publicfile pkeydata publicfilereadpubkey rsapublickeyload pkcs1pkeydatarandom text osurandom8generate signaturesignature rsasignrandom text privkey md5print signatureverify tokentry rsaverifyrandom text signature pubkeyexcept print verification failedmy python script fails when it tries to load the public keyvalueerror no pem start marker begin rsa public key found,['python'] +471246,how to implement dom data binding in javascript please treat this question as strictly educational i am still interested in hearing new answers and ideas to implement thistldrhow would i implement bidirectional databinding with javascriptdata binding to the domby data binding to the dom i mean for example having a javascript object a with a property b then having an input dom element for example when the dom element changes a changes and vice versa that is i mean bidirectional data binding here is a diagram from angularjs on what this looks likeso basically i have javascript similar tovar a b3then an input or other form element likeinput typetext valuei would like the inputs value to be abs value for example and when the input text changes i would like ab to change too when ab changes in javascript the input changesthe questionwhat are some basic techniques to accomplish this in plain javascriptin specific i would like a good answer to refer tohow would binding work for objectshow listening to change in the form might workis it possible in a simple way to only have the html modified on the template level i would like to not keep track of the binding in the html document itself but only in javascript with dom events and javascript keeping reference to the dom elements usedwhat have i triedi am a big fan of mustache so i tried using it for templating however i ran into issues when trying to perform the data binding itself since mustache processes html as a string so after i get its result i have no reference to where the objects in my viewmodel are the only workaround i could think for this was modifying the html string or created dom tree itself with attributes i do not mind using a different templating enginebasically i got a strong feeling that i was complicating the issue at hand and there is a simple solutionnote please do not provide answers that use external libraries especially ones that are thousands of lines of code i have used and like angularjs and knockoutjs i really do not want answers in the form use framework x optimally i would like a future reader who does not know how to use many frameworks to grasp how to implement bidirectional databinding herself i do not expect a complete answer but one that gets the idea across,"['javascript', 'html']" +471247,centralized api provider oauth or not i am a bit lost with the overflow of information and i need some guidance on the best way i can support providing apis access only to trusted clientscurrent environmentwe currently have a centralized server that handles user authenticationauthorization via apache shiro we have inhouse apis that communicate internally with the centralized server to authenticate and manage tokens thus enabling ssocommunication between our client applications and apis are secured over ssl tokenbased authentication is usedtargetour target is to allow 3rd party applications and apis to communicate with our centralized authentication server but our main concern is phishing as we only want valid parties to communicate with us and preferably thisallow exposing the authentication information on the 3rd partys sidequestions1 what is the best way to implement such an architecture should we go ahead with oauth if yes is there a good way to integrate it with shiro2 would oauth do its job well on mobile applications as well eg restrict access to rest api unless the application is trusted3 is there an oauth provider library i can use with java or is oauth simply a standard that i have to implement myself such as for example implementing restful apis4 is sso easily support with oauthsorry for vague questions i just need general guidance and advice,['java'] +471307,wifi position triangulation i need to understand how wifi triangulation basically works the scene is as portrayed in above diagram inorder to implement wifi triangulation i need a minimum of 3 wifi hotspots and their positions the setup 1 for simplicity let us assume i have a 1 sqkm by 1 sqkm area and i have 3 wifi hotspots in this area the coordinate system is as follows 1 corner of the square area is 0 and the diagonally furthest corner will have coordinates 1 all position determination is to be done relative to this coordinate system alone for simplicity i do not want global xyz coordinates within this i have 3 wifi hotspots at x1y1z1 x2y2z2 x3y3z32 we have a person with a device capable of receiving wifi signals and calculating the strength of the signal at position xyz the device could be a phone a tablet etcthe problem calculate position xyz of the person dynamically as they move around when you now have following inputs1 signal strength of signals received from each of the wifi hotspots2 coordinates of the wifi hotspots previously stored in variables or a database first question how do i calculate position from above inputs i assume signal strength is directly proportional to thistance from router but whats the exact relation how does skyhook do this so accuratelysecond question i believe the above inputs are sufficient is there anything else required thanks,"['android', 'ios']" +471348,using websocket to stream in video tag i am trying to stream a webm or mp4 video from nodejs to html5 using websockets the websocket library is socketio on both server and client the browser in use is the latest version of chrome version 260141064 mi saw here that it is possible to push a video stream in the video tag from a file using the mediasource object my idea is to read chunks of data from the websocket instead of a filecan someone please post an example using websockets to accomplish that or explain me how to do itthanks in advance,['javascript'] +471396,python regex extraneous matchings i want to split a string using and whitespace as delimiters i want to keep the delimiter unless it is whitespacei have tried to achieve this with the following codedef tokenizes import re pattern recompiles return patternsplitsprinttokenizehello therei expected the output to behello therehowever i gothello none none therewhich is almost what i wanted except that there are quite a few extraneous nones and empty stringswhy is it behaving this way and how might i change it to get what i want,['python'] +471423,why write an app if a web server will do i have a client who wants an app for iphone android windows 8 phone etcfrom his specifications i see no good reason to need an app per se seems to me cssjs and html can do the job as long as it is all written with a phones thisplay in mindif his app needed to access localized cpu power or features of a phone device that would be one thing but it is nothing but interaction with a server followed by a thisplay of the resultsam i not appreciating something here thanks in advance,"['javascript', 'android', 'iphone', 'html', 'css']" +471454,is there a miracast clientserver for mac or windows i was wondering if anyone knows any mac or windows clientsservers that support the miracast standardat my company we demo our applications very often via video conferencesskypejoinmeetc so it would be grate if i could share the screen of my android device via miracast to my mac or winpcsharing to a tv that supports is not an option unfortunatelyi have seen a lot of devices that have hdmi output and support miracast ie netgearptv30 but i could not find any info related to this devices which notes that they would work with a mac or win workstation,['android'] +471472,how often can you update a textview without mess suppose a textviewtextview tvsum findviewbyidridsumtexviewidif i want to change the thisplayed text i do thistvsumsettexta0now supposing i do this regularly say every time a button is pressed perhaps showing the sum entered on a till in this example you press one it says 1p then you press two and it says 12p and so oni find that if i do this the text becomes thistorted after a while for the sequence 12345 to start with all is good nothing pressed yet 1 pressed then 2 pressed then 3 pressedhowever after that things get messy then 4 pressed then 5 pressedit never gets any better thereafter i have not posted code because the code really is very simple a bunch of buttons and only writing one short string to one textview nothing in the code should cause this honest yes i have checked the string being written is correct by putting it up on toast has anyone else come across this and if so what resolved it,['android'] +471506,how to overload constructors on signature of a stdfunction i am trying to write a class with overloaded constructors that accept stdfunction objects as parameters but of course every damn thing can be implicitly cast to a stdfunction of any signature which is really helpful naturallyexampleclass foo foo stdfunctionvoid fn code foo stdfunctionint fn code foo a void return calls first constructorfoo b int return 1 calls second constructorthis would not compile complaining that both constructors are essentially identical and ambiguous which is nonsense of course i have tried enable if is same and a bunch of other things accepting function pointers is out of the question because that would prevent the passing of stateful lambdas surely there must be a way to achieve thismy templating skills are a little lacking i am afraid normal template classes and functions are easy enough but playing silly buggers with the compiler is a little out of my league can someone help me out pleasei know variants of this question have been asked before but they generally focus on normal functions rather than constructors or overloading by arguments instead of return types,['c++'] +471517,colorplot of 2d array matplotlib so i thought this was going to be really simple but i have been having a lot of difficult finding exactly what i am looking for in a comprehensible examplebasically i want to make phase plots so assuming i have a 2d array how can i get matplotlib to convert this to a plot that i can attach titles axes and legends color bars toi am looking for an extremely simple bare bones solution that only uses what is required that will work with any 2d arrayi am certain this is simple and i am just being thick somehow but i am really having a lot of trouble with thisi have been tooling with the examples but they do not seem well suited to what i am trying to do i like the general appearance of this graph i would just like to be able to pass in a 2darray and have this same resultimport numpy as npimport matplotlib as mlimport matplotlibpyplot as plth 123456789101213141516fig pltfigurefigsize6 32ax figadd subplot1axset titlecolormapxy npmeshgridxedges yedgespltpcolormeshx y haxset aspectequalcax figadd axes012 01 078 08caxget xaxisset visiblefalsecaxget yaxisset visiblefalsecaxpatchset alpha0caxset frame onfalsepltcolorbarorientationverticalpltshow,['python'] +471531,close bootstrap modal i have a bootstrap modal dialog box that i want to show initially then when the user clicks on the page it thisappears i have the followingfunction modalmodaltoggle div classmodal idmodal div classmodalheader button typebutton classclose datathismissmodal ariahiddentrueabutton h3 idmymodallabelerrorh3 div div classmodalbody pplease correct the following errorsp div div divthe modal is thisplayed initially but it does not close when clicked outside of the modal also the content area is not greyed out how can i get the modal to thisplay initially then close after the user clicks outside the area and how can i get the background to be grayed out as in the demo,['jquery'] +471532,why is inlined function slower than function pointer consider the following codetypedef void fnvolatile long sum 0inline void accu sum4static const fn map4 accu accu accu accuint mainint argc char argv static const long and 10l if argc 1 for long i 0 i n i accu accu accu accu else for long i 0 i n i for int j 0 j 4 j mapj when i compiled it withg o3 testcppi am expecting the first branch to run faster because the compiler could inline the function call to accu and the second branch cannot be inlined because accu is called through function pointer stored in an arraybut the results surprised metime aout real 0m0108suser 0m0104ssys 0m0stime aout 1real 0m0095suser 0m0088ssys 0m04si do not understand why so i did an objdumpobjdump dsttrr aout asand the thisassembly does not seem to explain the performance result i got8048300 main8048300 55 push ebp8048301 89 e5 mov espebp8048303 53 push ebx8048304 bb 80 96 98 00 mov 0x989680ebx8048309 83 e4 f0 and 0xf0esp804830c 83 7d 08 01 cmpl 0x10x8ebp8048310 74 27 je 8048339 main0x398048312 8d b6 00 00 00 00 lea 0x0esiesi8048318 e8 23 01 00 00 call 8048440 z4accuv804831d e8 1e 01 00 00 call 8048440 z4accuv8048322 e8 19 01 00 00 call 8048440 z4accuv8048327 e8 14 01 00 00 call 8048440 z4accuv804832c 83 eb 01 sub 0x1ebx804832f 90 nop8048330 75 e6 jne 8048318 main0x188048332 31 c0 xor eaxeax8048334 8b 5d fc mov 0x4ebpebx8048337 c9 leave8048338 c3 ret8048339 b8 80 96 98 00 mov 0x989680eax804833e 66 90 xchg axax8048340 8b 15 18 a0 04 08 mov 0x804a018edx8048346 83 c2 04 add 0x4edx8048349 89 15 18 a0 04 08 mov edx0x804a018804834f 8b 15 18 a0 04 08 mov 0x804a018edx8048355 83 c2 04 add 0x4edx8048358 89 15 18 a0 04 08 mov edx0x804a018804835e 8b 15 18 a0 04 08 mov 0x804a018edx8048364 83 c2 04 add 0x4edx8048367 89 15 18 a0 04 08 mov edx0x804a018804836d 8b 15 18 a0 04 08 mov 0x804a018edx8048373 83 c2 04 add 0x4edx8048376 83 e8 01 sub 0x1eax8048379 89 15 18 a0 04 08 mov edx0x804a018804837f 75 bf jne 8048340 main0x408048381 eb af jmp 8048332 main0x328048383 90 nop8048440 z4accuv8048440 a1 18 a0 04 08 mov 0x804a018eax8048445 83 c0 04 add 0x4eax8048448 a3 18 a0 04 08 mov eax0x804a018804844d c3 ret804844e 90 nop804844f 90 nopit seems the direct call branch is definitely doing less than the function pointer branchbut why does the function pointer branch run faster than the direct calland note that i only used time for measuring the time i have used clock gettime to do the measurement and got similar results,['c++'] +471534,removing input placeholder on a printable version of an html page i have a form with input fields each input field has a placeholder attributethere is also a link thisplaying the printable version of the same formmy problem is that if i leave the placeholder attribute unchanged and the input field is empty then the placeholder is actually printed which is not very goodi am looking for a way to resolve this unfortunate behavior right now the only thing i can think of is traverse the dom in javascript and remove all the placeholder attributes when the printable version is given of course when reverting back to the normal page view the placeholder attributes must be restored toothis is not hard but is also not very elegant i wonder if there is a better solution,"['javascript', 'html']" +471574,slideshow in android viewpager i have problem with android viewpager slideshow i want to show the viewpager layout after a minimum time period here is my code sample my main class public class mainactivity extends activity private viewpager mviewpager private swipeadapter adapter override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main mviewpager viewpager findviewbyidridpager set the adapter adapter new swipeadaptermainactivitythis mviewpagersetadapteradapter mviewpagersetonpagechangelistenernew onpagechangelistener override public void onpageselectedint position override public void onpagescrolledint arg0 float arg1 int arg2 override public void onpagescrollstatechangedint arg0 my adapter classpublic class swipeadapter extends pageradapter private layoutinflater minflater private static int mlayouts rlayoutview layout1 rlayoutview layout2 rlayoutview layout3 rlayoutview layout4 swipeadaptercontext context minflater layoutinflaterfromcontext override public void destroyitemviewgroup container int position object object containerremoveviewview object override public object instantiateitemviewgroup container int position viewgroup pageview viewgroup minflaterinflatemlayoutsposition container false containeraddviewpageview getitempositionpageview return pageview override public int getcount return mlayoutslength override public boolean isviewfromobjectview view object obj return view obj suppose that i want to make the viewpager layout auto sliding after 10 seconds how can it possible,['android'] +471624,visual studio 2012 test categories hierarchy test explorer i am testing a quite big project c vs2012 and i need to arrange my unit test in test hierarchy eg now i have 43 test cases i do really need the hierarchyi have test categories defined already and the test explorer shows test cases by traits i have categories in this way one test have several categoriestestcase01 maintesttype subtesttype subsubtesttypetestcase10 maintesttype subtesttype subsubtesttypetestcase11 maintesttype subtesttype2 subsubtesttype2testcase15 maintesttype subtesttype2 subsubtesttype2defined like this testmethod testcategorymaintesttype testcategorysubtesttype testcategorysubsubtesttype public void mytestcase etc but test explorer shows the nextmaintesttype all tests having category maintesttypesubtesttype all tests having category subtesttypeetcso i really miss the hierarchy i have tried cat1cat2cat3 or even with but no hierarchy thisplayed do you know how to do it or a free addon which can do it for me i also will need these type of categorization because we run often tests from command line and mstestexe can run tests for one category eg all maintesttype or subtesttype i stick to mstest because half of the team uses vs2010 but the solution is enough for vs2012thank you in advance,['c#'] +471631,refer to group inside group with regex i am trying to find a regex that groups a word that ends on two identical symbols followed by ter and splits it on the two symbolsexample the word letter should be grouped into let and teri am using python and this is what i have gotten so farmatch researchrww1er strprint matchgroup1 should print letprint matchgroup2 should print terthe problem is that the w1 does not refer to the right group because it is a group inside a group how is this solvedthanks in advance,['python'] +471689,how to get android gps location cheers i am trying to get the current gpslocation via android i followed this tutorial and vogellas article aswell though it am not working when using locationmanagernetwork provider i am always getting a latitude of 51 and longitude of 9 no matter where i stand when using locationmanagergps provider i am getting nothing at all though everything works when using gmaps s no idea why how can i get the current gps location like gmaps doesheres my codepackage comexamplegpslocationimport androidlocationlocationimport androidlocationlocationlistenerimport androidlocationlocationmanagerimport androidosbundleimport androidappactivityimport androidcontentcontextimport androidutillogimport androidviewmenupublic class gps location extends activity implements locationlistener overrideprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity gps location locationmanager locationmanager locationmanager getsystemservicecontextlocation service locationmanagerrequestlocationupdateslocationmanagergps provider 0 0 thisoverridepublic boolean oncreateoptionsmenumenu menu inflate the menu this adds items to the action bar if it is present getmenuinflaterinflatermenugps location menu return trueoverridepublic void onlocationchangedlocation location todo autogenerated method stub int latitude int locationgetlatitude int longitude int locationgetlongitude logigeo location latitude latitude longitude longitudeoverridepublic void onproviderthisabledstring provider todo autogenerated method stuboverridepublic void onproviderenabledstring provider todo autogenerated method stuboverridepublic void onstatuschangedstring provider int status bundle extras todo autogenerated method stub,"['java', 'android']" +471701,how do i interpret anr tracestxt when my code does not appear on stack i am trying to debug a persistent anr application not responding in my android applicationi have read these threadsandroid how do i investigate an anrhow to debug android anrinterpreting an anr stack tracethe overriding message is to use strictmode which i will dohowever i would still like to interpret the cause of the anr stack i am repeatedly seeing first i do not see any main thread instead i see many threads in the main group including one thread named waitforactivitystart on none of the threads do i see my code so i am confused as to how this anr can be happening due to my own code the only code i see from a library that i installed was google analytics ga which you can see titled gathread could that be the culprit if so could someone explain how i could deduce that from this reporthere is the output from tracestxt that i pulled using adb on a nexus 7 running 422 pid 15370 at 20130511 1204 cmd line comappspotmyappdalvik threadsmutexes tll0 tsl0 tscl0 ghl0waitforactivitystart prio5 tid12 wait groupmain scount1 dscount0 obj0x41d63a98 self0x658cafd0 systid16096 nice0 sched00 cgrpapps handle1736692928 states schedstat 275540 1387110 1319 utm2 stm0 core0 at javalangobjectwaitnative method waiting on 0x41d63a98 a javautiltimertimerimpl at javalangobjectwaitobjectjava364 at javautiltimertimerimplruntimerjava214binder 5 prio5 tid32 native groupmain scount1 dscount0 obj0x41dd6570 self0x678fa458 systid29473 nice0 sched00 cgrpapps handle17326432 states schedstat 5780 1060 3 utm0 stm0 core0 00 pc 016fe4 systemliblibcso ioctl8 01 pc 02a97d systemliblibcso ioctl16 02 pc 016ba1 systemliblibbinderso androidipcthreadstatetalkwithdriverbool132 03 pc 017363 systemliblibbinderso androidipcthreadstatejointhreadpoolbool154 04 pc 01b15d systemliblibbinderso 05 pc 011267 systemliblibutilsso androidthread threadloopvoid114 06 pc 04679f systemliblibandroid runtimeso androidandroidruntimejavathreadshellvoid66 07 pc 010dcd systemliblibutilsso 08 pc 0e3d8 systemliblibcso thread entry72 09 pc 0dac4 systemliblibcso pthread create160 at dalviksystemnativestartrunnative methodbinder 4 prio5 tid31 native groupmain scount1 dscount0 obj0x41dd7568 self0x67beb3d0 systid29471 nice0 sched00 cgrpapps handle1740371672 states schedstat 8890 176520 4 utm0 stm0 core0 00 pc 016fe4 systemliblibcso ioctl8 01 pc 02a97d systemliblibcso ioctl16 02 pc 016ba1 systemliblibbinderso androidipcthreadstatetalkwithdriverbool132 03 pc 017363 systemliblibbinderso androidipcthreadstatejointhreadpoolbool154 04 pc 01b15d systemliblibbinderso 05 pc 011267 systemliblibutilsso androidthread threadloopvoid114 06 pc 04679f systemliblibandroid runtimeso androidandroidruntimejavathreadshellvoid66 07 pc 010dcd systemliblibutilsso 08 pc 0e3d8 systemliblibcso thread entry72 09 pc 0dac4 systemliblibcso pthread create160 at dalviksystemnativestartrunnative methodthread591 prio5 tid1 vmwait groupmain scount1 dscount0 obj0x420e8b20 self0x4008dbf8 systid15370 nice0 sched00 cgrpapps handle1075213276 states schedstat 413992010 189806580 4984 utm3147 stm992 core0 00 pc 018104 systemliblibcso futex syscall38 01 pc 0e41c systemliblibcso pthread cond timedwait relative48 02 pc 0e478 systemliblibcso pthread cond timedwait60 03 pc 04a471 systemliblibdvmso 04 pc 03a19d systemliblibdvmso 05 pc 047571 systemliblibandroid runtimeso androidandroidruntimestartchar const char const452 06 pc 0db7 systembinapp process 07 pc 01271f systemliblibcso libc init38 08 pc 0ae8 systembinapp process at dalviksystemnativestartrunnative methodpool5thread1 prio5 tid35 wait groupmain scount1 dscount0 obj0x42313ee0 self0x67a998c0 systid15727 nice0 sched00 cgrpapps handle1739169040 states schedstat 372180 133540720 1531 utm0 stm3 core0 at javalangobjectwaitnative method waiting on 0x42314090 a javalangvmthread held by tid35 pool5thread1 at javalangthreadparkforthreadjava1231 at sunmiscunsafeparkunsafejava323 at javautilconcurrentlockslocksupportparklocksupportjava159 at javautilconcurrentlocksabstractqueuedsynchronizerconditionobjectawaitabstractqueuedsynchronizerjava2019 at javautilconcurrentlinkedblockingqueuetakelinkedblockingqueuejava413 at javautilconcurrentthreadpoolexecutorgettaskthreadpoolexecutorjava1013 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava1073 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava573 at javalangthreadrunthreadjava856binder 3 prio5 tid34 native groupmain scount1 dscount0 obj0x41d60f08 self0x67b39348 systid15539 nice0 sched00 cgrpapps handle1737253696 states schedstat 14750 137252770 1713 utm5 stm9 core0 00 pc 016fe4 systemliblibcso ioctl8 01 pc 02a97d systemliblibcso ioctl16 02 pc 016ba1 systemliblibbinderso androidipcthreadstatetalkwithdriverbool132 03 pc 017363 systemliblibbinderso androidipcthreadstatejointhreadpoolbool154 04 pc 01b15d systemliblibbinderso 05 pc 011267 systemliblibutilsso androidthread threadloopvoid114 06 pc 04679f systemliblibandroid runtimeso androidandroidruntimejavathreadshellvoid66 07 pc 010dcd systemliblibutilsso 08 pc 0e3d8 systemliblibcso thread entry72 09 pc 0dac4 systemliblibcso pthread create160 at dalviksystemnativestartrunnative methodthread558 prio5 tid25 native groupmain scount1 dscount0 obj0x41a47528 self0x67653008 systid15453 nice0 sched00 cgrpapps handle1696217960 states schedstat 3601330 138026620 2116 utm18 stm18 core0 00 pc 017ee4 systemliblibcso epoll wait12 01 pc 0012b949 systemliblibchromium netso 02 pc 0012b755 systemliblibchromium netso 03 pc 058415 systemliblibchromium netso 04 pc 056b13 systemliblibchromium netso messageloopruninternal114 05 pc 056b71 systemliblibchromium netso messagelooprun16 06 pc 0771d9 systemliblibchromium netso basethreadthreadmain188 07 pc 076c93 systemliblibchromium netso 08 pc 0e3d8 systemliblibcso thread entry72 09 pc 0dac4 systemliblibcso pthread create160 at dalviksystemnativestartrunnative methodintentservice10200585435 prio5 tid30 native groupmain scount1 dscount0 obj0x41bab2c8 self0x658e8d78 systid15445 nice0 sched00 cgrpapps handle1732697176 states schedstat 658020 136900730 1380 utm3 stm3 core0 00 pc 017ee4 systemliblibcso epoll wait12 01 pc 014b09 systemliblibutilsso androidlooperpollinnerint96 02 pc 014d71 systemliblibutilsso androidlooperpollonceint int int void104 03 pc 05ed53 systemliblibandroid runtimeso androidnativemessagequeuepollonce jnienv int22 04 pc 01e290 systemliblibdvmso dvmplatforminvoke112 05 pc 04d411 systemliblibdvmso dvmcalljnimethodunsigned int const jvalue method const thread396 06 pc 0214 devashmemdalvikjitcodecache deleted at androidosmessagequeuenativepolloncenative method at androidosmessagequeuenextmessagequeuejava125 at androidoslooperlooplooperjava124 at androidoshandlerthreadrunhandlerthreadjava60pool2thread3 prio5 tid29 wait groupmain scount1 dscount0 obj0x41dbf1c0 self0x652f9308 systid15436 nice0 sched00 cgrpapps handle1697608048 states schedstat 14919480 149064980 27824 utm100 stm49 core0 at javalangobjectwaitnative method waiting on 0x41dbf2e0 a javalangvmthread held by tid29 pool2thread3 at javalangthreadparkforthreadjava1231 at sunmiscunsafeparkunsafejava323 at javautilconcurrentlockslocksupportparklocksupportjava159 at javautilconcurrentlocksabstractqueuedsynchronizerconditionobjectawaitabstractqueuedsynchronizerjava2019 at javautilconcurrentlinkedblockingqueuetakelinkedblockingqueuejava413 at javautilconcurrentthreadpoolexecutorgettaskthreadpoolexecutorjava1013 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava1073 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava573 at javalangthreadrunthreadjava856pool2thread2 prio5 tid28 wait groupmain scount1 dscount0 obj0x41dd7218 self0x652f8cb0 systid15435 nice0 sched00 cgrpapps handle1697608112 states schedstat 14084750 143857130 28965 utm82 stm58 core0 at javalangobjectwaitnative method waiting on 0x41dd74f0 a javalangvmthread held by tid28 pool2thread2 at javalangthreadparkforthreadjava1231 at sunmiscunsafeparkunsafejava323 at javautilconcurrentlockslocksupportparklocksupportjava159 at javautilconcurrentlocksabstractqueuedsynchronizerconditionobjectawaitabstractqueuedsynchronizerjava2019 at javautilconcurrentlinkedblockingqueuetakelinkedblockingqueuejava413 at javautilconcurrentthreadpoolexecutorgettaskthreadpoolexecutorjava1013 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava1073 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava573 at javalangthreadrunthreadjava856pool2thread1 prio5 tid27 wait groupmain scount1 dscount0 obj0x41dd2f50 self0x652f8658 systid15434 nice0 sched00 cgrpapps handle1697610152 states schedstat 12900690 140789450 26535 utm80 stm49 core0 at javalangobjectwaitnative method waiting on 0x41dd3348 a javalangvmthread held by tid27 pool2thread1 at javalangthreadparkforthreadjava1231 at sunmiscunsafeparkunsafejava323 at javautilconcurrentlockslocksupportparklocksupportjava159 at javautilconcurrentlocksabstractqueuedsynchronizerconditionobjectawaitabstractqueuedsynchronizerjava2019 at javautilconcurrentlinkedblockingqueuetakelinkedblockingqueuejava413 at javautilconcurrentthreadpoolexecutorgettaskthreadpoolexecutorjava1013 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava1073 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava573 at javalangthreadrunthreadjava856cookiesyncmanager prio5 tid26 native groupmain scount1 dscount0 obj0x41d57ea0 self0x65118458 systid15427 nice10 sched00 cgrpappsbg non interactive handle1695647912 states schedstat 722840 3242180 1453 utm5 stm2 core0 00 pc 017ee4 systemliblibcso epoll wait12 01 pc 014b09 systemliblibutilsso androidlooperpollinnerint96 02 pc 014d71 systemliblibutilsso androidlooperpollonceint int int void104 03 pc 05ed53 systemliblibandroid runtimeso androidnativemessagequeuepollonce jnienv int22 04 pc 01e290 systemliblibdvmso dvmplatforminvoke112 05 pc 04d411 systemliblibdvmso dvmcalljnimethodunsigned int const jvalue method const thread396 06 pc 0276e4 systemliblibdvmso 07 pc 0fedd0 unknown at androidosmessagequeuenativepolloncenative method at androidosmessagequeuenextmessagequeuejava125 at androidoslooperlooplooperjava124 at androidwebkitwebsyncmanagerrunwebsyncmanagerjava90 at androidwebkitcookiesyncmanagerruncookiesyncmanagerjava58 at javalangthreadrunthreadjava856webviewcorethread prio5 tid24 suspended groupmain scount1 dscount0 obj0x41d68058 self0x65163bc0 systid15425 nice0 sched00 cgrpapps handle1750731264 states schedstat 43167270110 24012360 3061982 utm352956 stm78716 core1 at androidosmessageclearforrecyclemessagejava416 at androidosmessagerecyclemessagejava249 at androidoslooperlooplooperjava154 at androidwebkitwebviewcorewebcorethreadrunwebviewcorejava812 at javalangthreadrunthreadjava856timer2 daemon prio5 tid20 timed wait groupmain scount1 dscount0 obj0x41a40d40 self0x61e0fa60 systid15416 nice0 sched00 cgrpapps handle1761429616 states schedstat 6835530 130445920 2664 utm35 stm33 core0 at javalangobjectwaitnative method waiting on 0x41a40d40 a javautiltimertimerimpl at javalangobjectwaitobjectjava401 at javautiltimertimerimplruntimerjava238timer1 prio5 tid17 timed wait groupmain scount1 dscount0 obj0x41a4da68 self0x61e0efc0 systid15415 nice0 sched00 cgrpapps handle1752179848 states schedstat 17309070 128204070 4622 utm93 stm80 core0 at javalangobjectwaitnative method waiting on 0x41a4da68 a javautiltimertimerimpl at javalangobjectwaitobjectjava401 at javautiltimertimerimplruntimerjava238asynctask 5 prio5 tid21 wait groupmain scount1 dscount0 obj0x4159d0 self0x61e0f410 systid15399 nice10 sched00 cgrpappsbg non interactive handle1752193288 states schedstat 9936890 341128820 25528 utm64 stm35 core0 at javalangobjectwaitnative method waiting on 0x41258e38 a javalangvmthread held by tid21 asynctask 5 at javalangthreadparkforthreadjava1231 at sunmiscunsafeparkunsafejava323 at javautilconcurrentlockslocksupportparklocksupportjava159 at javautilconcurrentlocksabstractqueuedsynchronizerconditionobjectawaitabstractqueuedsynchronizerjava2019 at javautilconcurrentlinkedblockingqueuetakelinkedblockingqueuejava413 at javautilconcurrentthreadpoolexecutorgettaskthreadpoolexecutorjava1013 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava1073 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava573 at javalangthreadrunthreadjava856asynctask 4 prio5 tid19 wait groupmain scount1 dscount0 obj0x415a1498 self0x64fb3440 systid15397 nice10 sched00 cgrpappsbg non interactive handle1740995712 states schedstat 2942660 330255250 4122 utm14 stm15 core0 at javalangobjectwaitnative method waiting on 0x413ccdd0 a javalangvmthread held by tid19 asynctask 4 at javalangthreadparkforthreadjava1231 at sunmiscunsafeparkunsafejava323 at javautilconcurrentlockslocksupportparklocksupportjava159 at javautilconcurrentlocksabstractqueuedsynchronizerconditionobjectawaitabstractqueuedsynchronizerjava2019 at javautilconcurrentlinkedblockingqueuetakelinkedblockingqueuejava413 at javautilconcurrentthreadpoolexecutorgettaskthreadpoolexecutorjava1013 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava1073 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava573 at javalangthreadrunthreadjava856asynctask 3 prio5 tid18 wait groupmain scount1 dscount0 obj0x415aa1e0 self0x64fb2ff0 systid15396 nice10 sched00 cgrpappsbg non interactive handle1637810544 states schedstat 4633520 334187860 16118 utm24 stm22 core0 at javalangobjectwaitnative method waiting on 0x41434770 a javalangvmthread held by tid18 asynctask 3 at javalangthreadparkforthreadjava1231 at sunmiscunsafeparkunsafejava323 at javautilconcurrentlockslocksupportparklocksupportjava159 at javautilconcurrentlocksabstractqueuedsynchronizerconditionobjectawaitabstractqueuedsynchronizerjava2019 at javautilconcurrentlinkedblockingqueuetakelinkedblockingqueuejava413 at javautilconcurrentthreadpoolexecutorgettaskthreadpoolexecutorjava1013 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava1073 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava573 at javalangthreadrunthreadjava856gathread prio5 tid16 wait groupmain scount1 dscount0 obj0x413a02d0 self0x67fca048 systid15392 nice0 sched00 cgrpapps handle1741546872 states schedstat 2717670 124927830 3617 utm16 stm11 core0 at javalangobjectwaitnative method waiting on 0x413a07a0 a javalangvmthread held by tid16 gathread at javalangthreadparkforthreadjava1231 at sunmiscunsafeparkunsafejava323 at javautilconcurrentlockslocksupportparklocksupportjava159 at javautilconcurrentlocksabstractqueuedsynchronizerconditionobjectawaitabstractqueuedsynchronizerjava2019 at javautilconcurrentlinkedblockingqueuetakelinkedblockingqueuejava413 at comgoogleanalyticstrackingandroidgathreadrungathreadjava518asynctask 2 prio5 tid15 wait groupmain scount1 dscount0 obj0x41336e00 self0x68c253a8 systid15391 nice10 sched00 cgrpappsbg non interactive handle1739175192 states schedstat 1612680 334242070 2235 utm14 stm2 core0 at javalangobjectwaitnative method waiting on 0x41337138 a javalangvmthread held by tid15 asynctask 2 at javalangthreadparkforthreadjava1231 at sunmiscunsafeparkunsafejava323 at javautilconcurrentlockslocksupportparklocksupportjava159 at javautilconcurrentlocksabstractqueuedsynchronizerconditionobjectawaitabstractqueuedsynchronizerjava2019 at javautilconcurrentlinkedblockingqueuetakelinkedblockingqueuejava413 at javautilconcurrentthreadpoolexecutorgettaskthreadpoolexecutorjava1013 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava1073 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava573 at javalangthreadrunthreadjava856comgooglecommonbaseinternalfinalizer daemon prio5 tid14 wait groupmain scount1 dscount0 obj0x41597f60 self0x687b1950 systid15390 nice0 sched00 cgrpapps handle17385180 states schedstat 337160 119627530 1419 utm0 stm3 core0 at javalangobjectwaitnative method waiting on 0x415bd708 a javalangrefreferencequeue at javalangobjectwaitobjectjava401 at javalangrefreferencequeueremovereferencequeuejava102 at javalangrefreferencequeueremovereferencequeuejava73 at comgooglecommonbaseinternalfinalizerrunfinalizerjava127asynctask 1 prio5 tid11 wait groupmain scount1 dscount0 obj0x415b4808 self0x68ef9008 systid15384 nice10 sched00 cgrpappsbg non interactive handle1759288072 states schedstat 13135370 348467580 40646 utm66 stm65 core0 at javalangobjectwaitnative method waiting on 0x414d7b08 a javalangvmthread held by tid11 asynctask 1 at javalangthreadparkforthreadjava1231 at sunmiscunsafeparkunsafejava323 at javautilconcurrentlockslocksupportparklocksupportjava159 at javautilconcurrentlocksabstractqueuedsynchronizerconditionobjectawaitabstractqueuedsynchronizerjava2019 at javautilconcurrentlinkedblockingqueuetakelinkedblockingqueuejava413 at javautilconcurrentthreadpoolexecutorgettaskthreadpoolexecutorjava1013 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava1073 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava573 at javalangthreadrunthreadjava856binder 2 prio5 tid10 native groupmain scount1 dscount0 obj0x41259730 self0x400c4890 systid15382 nice0 sched00 cgrpapps handle1749727712 states schedstat 1628090 1297650 1817 utm4 stm12 core0 00 pc 016fe4 systemliblibcso ioctl8 01 pc 02a97d systemliblibcso ioctl16 02 pc 016ba1 systemliblibbinderso androidipcthreadstatetalkwithdriverbool132 03 pc 017363 systemliblibbinderso androidipcthreadstatejointhreadpoolbool154 04 pc 01b15d systemliblibbinderso 05 pc 011267 systemliblibutilsso androidthread threadloopvoid114 06 pc 04679f systemliblibandroid runtimeso androidandroidruntimejavathreadshellvoid66 07 pc 010dcd systemliblibutilsso 08 pc 0e3d8 systemliblibcso thread entry72 09 pc 0dac4 systemliblibcso pthread create160 at dalviksystemnativestartrunnative methodbinder 1 prio5 tid9 native groupmain scount1 dscount0 obj0x41259528 self0x686e9b50 systid15381 nice0 sched00 cgrpapps handle17425472 states schedstat 168070 12929180 1689 utm5 stm11 core0 00 pc 016fe4 systemliblibcso ioctl8 01 pc 02a97d systemliblibcso ioctl16 02 pc 016ba1 systemliblibbinderso androidipcthreadstatetalkwithdriverbool132 03 pc 017363 systemliblibbinderso androidipcthreadstatejointhreadpoolbool154 04 pc 01b15d systemliblibbinderso 05 pc 011267 systemliblibutilsso androidthread threadloopvoid114 06 pc 04679f systemliblibandroid runtimeso androidandroidruntimejavathreadshellvoid66 07 pc 010dcd systemliblibutilsso 08 pc 0e3d8 systemliblibcso thread entry72 09 pc 0dac4 systemliblibcso pthread create160 at dalviksystemnativestartrunnative methodfinalizerwatchdogdaemon daemon prio5 tid8 wait groupsystem scount1 dscount0 obj0x41256478 self0x68e87008 systid15380 nice0 sched00 cgrpapps handle1749728624 states schedstat 294180 124021230 1347 utm0 stm2 core0 at javalangobjectwaitnative method waiting on 0x40b2f4f0 a javalangdaemonsfinalizerwatchdogdaemon at javalangobjectwaitobjectjava364 at javalangdaemonsfinalizerwatchdogdaemonwaitforobjectdaemonsjava230 at javalangdaemonsfinalizerwatchdogdaemonrundaemonsjava207 at javalangthreadrunthreadjava856finalizerdaemon daemon prio5 tid7 wait groupsystem scount1 dscount0 obj0x412562c8 self0x67fd5c98 systid15379 nice0 sched00 cgrpapps handle1744330952 states schedstat 9398540 132198740 23293 utm44 stm49 core0 at javalangobjectwaitnative method waiting on 0x40b1b610 a javalangrefreferencequeue at javalangobjectwaitobjectjava401 at javalangrefreferencequeueremovereferencequeuejava102 at javalangrefreferencequeueremovereferencequeuejava73 at javalangdaemonsfinalizerdaemonrundaemonsjava170 at javalangthreadrunthreadjava856referencequeuedaemon daemon prio5 tid6 wait groupsystem scount1 dscount0 obj0x41256160 self0x68c25b58 systid15378 nice0 sched00 cgrpapps handle1752190528 states schedstat 2027370 126175780 5722 utm8 stm12 core0 at javalangobjectwaitnative method waiting on 0x40b1b538 at javalangobjectwaitobjectjava364 at javalangdaemonsreferencequeuedaemonrundaemonsjava130 at javalangthreadrunthreadjava856compiler daemon prio5 tid5 vmwait groupsystem scount1 dscount0 obj0x41256070 self0x68a0c008 systid15377 nice0 sched00 cgrpapps handle1739196488 states schedstat 16217530 129814180 10901 utm77 stm85 core0 00 pc 018104 systemliblibcso futex syscall38 01 pc 0e41c systemliblibcso pthread cond timedwait relative48 02 pc 0e478 systemliblibcso pthread cond timedwait60 03 pc 072aed systemliblibdvmso 04 pc 053ec3 systemliblibdvmso 05 pc 0e3d8 systemliblibcso thread entry72 06 pc 0dac4 systemliblibcso pthread create160 at dalviksystemnativestartrunnative methodjdwp daemon prio5 tid4 vmwait groupsystem scount1 dscount0 obj0x41255f88 self0x686f5218 systid15376 nice0 sched00 cgrpapps handle1751126616 states schedstat 4549610 135457390 5922 utm21 stm24 core0 00 pc 01710c systemliblibcso select20 01 pc 060af3 systemliblibdvmso 02 pc 063685 systemliblibdvmso 03 pc 053ec3 systemliblibdvmso 04 pc 0e3d8 systemliblibcso thread entry72 05 pc 0dac4 systemliblibcso pthread create160 at dalviksystemnativestartrunnative methodsignal catcher daemon prio5 tid3 runnable groupsystem scount0 dscount0 obj0x41255e90 self0x68707510 systid15375 nice0 sched00 cgrpapps handle1750229976 stater schedstat 1081490 122860710 1367 utm3 stm7 core2 at dalviksystemnativestartrunnative methodgc daemon prio5 tid2 vmwait groupsystem scount1 dscount0 obj0x41255db0 self0x400c3120 systid15374 nice0 sched00 cgrpapps handle1737473208 states schedstat 8091150 1343630 1840 utm78 stm2 core0 00 pc 018104 systemliblibcso futex syscall38 01 pc 0e41c systemliblibcso pthread cond timedwait relative48 02 pc 0e478 systemliblibcso pthread cond timedwait60 03 pc 07189f systemliblibdvmso 04 pc 053ec3 systemliblibdvmso 05 pc 0e3d8 systemliblibcso thread entry72 06 pc 0dac4 systemliblibcso pthread create160 at dalviksystemnativestartrunnative methodnative threadspspotmyapp systid15395 nice0 sched00 cgrpapps states schedstat 274040 125099740 1316 utm0 stm2 core0webviewcorethre systid15428 nice0 sched00 cgrpapps states schedstat 648810 140610640 1376 utm4 stm2 core0signalsender systid15429 nice0 sched00 cgrpapps states schedstat 795126630 705114510 1497804 utm1896 stm6055 core1webviewcorethre systid15455 nice0 sched00 cgrpapps states schedstat 46170 140017760 1413 utm1 stm3 core0texturesgenerat systid15459 nice0 sched00 cgrpapps states schedstat 1103270 134804260 1402 utm9 stm2 core0 end 15370,['android'] +471765,how to organize different versioned rest api controllers in laravel 4 i know there is a way to create versioned urls for rest apis with routes but whats the best way to organize controllers and controller files i want to be able to create new versions of apis and still keep the old ones running for at least some time,['php'] +471770,how can i use a javascript library on the server side of a nodejs app when it was designed to run on the client i am diving into nodejs and express it is so complicated to me to build a realtime web app at the moment i am trying to understand how i can use an existing javascript library on the server side the problem is the library appears to be designed to run on the client side and as a result the instructions only show you how to use it on the client side the library i am talking about can be found herequestionssince a nodejs web app is built on javascript is it fair to say i can run any nongui javascript library on the server sidecan anyone offer some guidance on how i can add that jsrepl library to my express 30 app in a way that allows me to use it in the same way that i would use it on the client side in a browser do i have to modify the jsrepl code and add exports to the methods i want to usemeaning on the server side i can execute the following codevar jsrepl new jsrepl input inputcallback output outputcallback result resultcallback error errorcallback progress progresscallback timeout time 30 callback timeoutcallback thanks in advance for all your wisdom i am doing my best to understand all this,['javascript'] +471790,csrf exempt failure apiview csrf django rest framework i have the following codethe problem is when i try to access userlogin i get an errorcsrf failed csrf cookie not setwhat can i doi am using the django rest frameworkurlspyurlruserlogin csrf exemptloginviewas view nameuserloginviewspyclass loginviewapiviewlist all snippets or create a new snippetdef getself request formatnone startups startupobjectsall serializer startupserializerstartups manytrue return responseserializerdatadef postself request formatnone profile requestpost if user name not in profile or email address not in profile or oauth secret not in profile return response error no data statusstatushttp 400 bad request username l profileuser name email address profileemail address oauth secret profileoauth secret password oauth secret,['python'] +471805,why do i get a not exposed to the weaver warnings when making my spring project i seem to get a bunch of warnings like this when i make my spring project the project uses compile time weaving and various spring annotations like transactional autowired and configurablei have three questions what are they whats the effect should i be concerned about them and what can i do to remove themajc this affected type is not exposed to the weaver commyappdomainuserentity xlinttypenotexposedtoweaverlet me know what you need to help me solve this issue i can post relevant parts of the pom file parts of my java spring configuration files or whatever i dont really know what is required so let me knowi saw it on the spring forum but that place is a ghost town several people have asked this question but there are no answersi am using java configuration for spring and ctw,['java'] +471836,read specific columns from csv file with python csv i am trying to parse through a csv file and extract the data from only specific columnsexample csvid name address city state zip phone opeid ipeds 10 c 130 w mo al 3 334 01023 10063 i am trying to capture only specific columns say id name zip and phonecode i have looked at has led me to believe i can call the specific column by its corresponding number so ie name would correspond to 2 and iterating through each row using row2 would produce all the items in column 2 only it does not heres what i have done so farimport sys argparse csvfrom settings import command argumentsparser argparseargumentparserdescriptioncsv to postgres fromfile prefix chars parseradd argumentfile helpcsv file to import actionstoreargs parserparse argscsv file argsfile open csv filewith opencsv file rb as csvfile get number of columns for line in csvfilereadlines array linesplit first item array0 num columns lenarray csvfileseek0 reader csvreadercsvfile delimiter included cols 1 2 6 7 for row in reader content listrowi for i in included cols print contentand i am expecting that this will print out only the specific columns i want for each row except it does not i get the last column only,['python'] +471856,threadstop deprecated why is threadstop deprecated in java on their website i see the followingwhy is threadstop deprecated because it is inherently unsafe stopping a thread causes it to unlock all the monitors that it has locked the monitors are unlocked as the threaddeath exception propagates up the stack if any of the objects previously protected by these monitors were in an inconsistent state other threads may now view these objects in an inconsistent state such objects are said to be damaged when threads operate on damaged objects arbitrary behavior can result this behavior may be subtle and difficult to detect or it may be pronounced unlike other unchecked exceptions threaddeath kills threads silently thus the user has no warning that his program may be corrupted the corruption can manifest itself at any time after the actual damage occurs even hours or days in the futurei dont understand what they mean by monitors regardless my question is if theres no way to stop a thread in java then how to stop a thread whats the best cleanest way to stopping a thread thank you,['java'] +471887,numpy difference between aij and aij coming from a lists background in python and that of programming languages like cjava one is used to the notation of extracting elements using aij approach but in numpy one usually does aij both of these would return the same resultwhat is the fundamental difference between the two and which should be preferred,['python'] +471914,generating a dense matrix from a sparse matrix in numpy python i have a sqlite database that contains following type of schematermcountdoc num term countthis table contains terms with their respective counts in the documentlikedoc1 term1 12doc1 term 22 2docnterm1 10this matrix can be considered as sparse matrix as each documents contains very few terms that will have a nonzero valuehow would i create a dense matrix from this sparse matrix using numpy as i have to calculate the similarity among documents using cosine similaritythis dense matrix will look like a table that have docid as the first column and all the terms will be listed as the first rowand remaining cells will contain counts,['python'] +471998,implementing a backtrack search with heuristic i am getting quite interested in search algorithms and backtrack programming for now i have implemented algorithm x see my other post here determine conflictfree sets to solve an exact cover problem this works very well but i am now interested in solving this with a more basic variant of backtracking i just cannot figure out how this can be done the problem description is the same as beforesuppose you have a bunch of sets whereas each set has a couple of subsetsset1 banana pineapple orange apple kale cucumber onion garlic set2 banana cucumber garlic avocado tomato setn the goal now is to select one subset from each set whereas each subset must be conflict free with any other selected subset one element is not contained in any of the other chosen subsetsas an example i wrote two java classes that the sets are identified by a single character and the elements are plain numbersi specifically have two problemshow to iterate over all setssubsets in such a way that the use of a heuristic is possible choose subset with minimum elements minimum cost how to maintain the selected setssubsets and their contained elementsall other examples i can find are either sudoku or nqueens and are all using fixed forloops in addition to that i was thinking about a rather general approach where a function ispossiblepartialsolution may be used to check if a chosen pathset may be in conflict with a previously chosen subsetelementhere are the two java classesimport javautilarraylistpublic class main public static void mainstring args arraylistset allsets buildrandomtest forset r allsets systemoutprintset with id rid is subset in collection rname and contains forinteger and rlistofelements systemoutprint and systemoutprintln public static int myrandomrangeint low int high return int mathrandom high low lowpublic static arraylistset buildrandomtest arraylistset myset new arraylistset int numberofsets myrandomrange10 12 forint i0 inumberofsets i string nameofset charactertostringchar myrandomrange65 67 set tmp new setnameofset i arraylistinteger listofelements new arraylistinteger int elementsinlist myrandomrange2 4 forint j0 jelementsinlist j listofelementsaddmyrandomrange130 tmplistofelements listofelements mysetaddtmp return mysetandimport javautilarraylistpublic class set public string namepublic int idpublic arraylistinteger listofelementspublic setstring name int id thisname name thisid id listofelements new arraylistinteger,['java'] +472004,a possible php bug with date default timezone set and date suppose this codephpdate default timezone setutctime gmmktime14 50 0 5 12 2013echo dateymd his o timebr echo gmdateymd his o timebr date default timezone setgmttime gmmktime14 50 0 5 12 2013echo dateymd his o timebr echo gmdateymd his o timeon my local server i get the output20130512 1450 020130512 1450 020130512 1450 020130512 1450 0but on production the same code produces20130512 1050 040020130512 1450 020130512 1450 020130512 1450 0changing time of the machine does not affect the output in any waysome info date zgmt date z0php 5325 cli built may 11 2013 095400centos release 59 final,['php'] +472147,calling a method on a new object in java without parentheses order of operations violation according to this table of java operator precedence and associativity member access has higher precedence than the new operatorhowever given a class myclass and a nonstatic member function myfunction the following line of code is validnew myclassmyfunctionif is evaluated before new how can this line be executed in other words why are not parentheses requirednew myclassmyfunctionmy guess is that since shares precedence with the myclass is evaluated first and so the compiler knows even before evaluating the new keyword that the myclass constructor with zero parameters is being called however this still seems to imply that the first line should be identical to new myclassmyfunction which is not the case,['java'] +472155,why is my css style not being applied i have got this htmlp span classfancifyparting is such sweet sorrowspanspan bill rattleandrollspeerspanpand this css added to the bottom of sitecssfancify fontsize 15em fontweight 800 fontfamily consolas segoe ui calibri sansserif fontstyle italicso i would expect the quote parting is such sweet sorrow to be italicized and of a different font than the name of the quotee bill rattleandrollspeer since its span tag has the class fancify attached to it the class should certainly be seen as the file in which it appears references the layout file which uses the sitecss filewhat rookie mistake am i making nowupdatei thought maybe the problem was that i had added the new class in sitecss following this section in that file mobile styles media only screen and maxwidth 850px but i moved it above there and it is still not working and not seen via f12 inspect element for the label in questioni moved the reference to sitecss below the bootstrapcss file which does indeed change the appearance of that text but still not italicized and still not seen in the element inspectorupdate 2heres how the html is coming downp span label classfancifyparting is such sweet sorrowlabeland heres my css rule in sitecssp span label fancify fontsize 15em fontweight 800 fontfamily consolas segoe ui calibri sansserif fontstyle italic thisplay inline but it is not being recognized i consider this a breech of csshtml protocol and should be adjudicated by some world body then again i could be making some silly mistake somewhere,"['html', 'css']" +472161,reasons for not using threadjoin lately i have been told by senior developers not to use threadjoin to wait for another thread to finish i have also seen several such questions on so asking alternates to joinin my research i could not find anything wrong with join in fact it is widely usedso i would like to know why not use join what is wrong with it does it promotes poor programming or architecture,['java'] +472177,massive memory leak in ios uiwebview looking for mem leaks elsewhere in our system i created a 20 mb web page with a meta refresh tag the idea was to move a lot data through our datapath code to confirm mem stabilityhtmlmeta httpequivrefresh content1bodydiv styleborder 1px solid red content loadingdiv 20mb worth of comments bodyhtmlwhat i found was the uiwebview thisplaying that meta refresh page leaks memory very very fast the app memory hits 300mb in about 2 minutes and gets shot on a low mem warning even when our code is not in playi have stopped the refresh loading and tried to dealloc the webviewi have tried loadurlaboutblank loadhtml javascript document closei also tried writing a recursive removefromsuperview and removefromparentviewcontroller reading that the private scrollview in the webview is a memory problem but that memory is never freed i cannot seem to find a reliable way to close dealloc a webview when we are done with itwe have lived with a slow rate of webview leaking for quite a while and really want to find a way of assuring a webview can be fully cleaned up when we are done with it we recently converted the app to arc which did not change the memory ratei am considering trying a recursive loop through all the objects in the webview and see if they can be freed instruments shows 20 mb of cfdatas alive for each refresh of the 20mb page but does not show them as leaks if i only deliver the response header and done to the urlprotocol client we run stably so was ale to confirm the memleaks in the rest of the data path but this is such a dramatic test case result am hoping to find a webview mem leak solution once and for all does any one have any better ideas or has anyone tried recursing through the objects in a uiwebview,['ios'] +472250,seek bar increse height currently i m working with seek bar that works perfectly fine but there is an issue i want to increase the height of the progress bar as native height is not as much highso how change the height of the progress bar either dynamically or through xml find many thing on google but could not retrive any handy solution so how to do that thingthankx in advance,['android'] +472271,pandas using unix epoch timestamp as datetime index my application involves dealing with data contained in a csv which is of the following formepoch number of seconds since jan 1 1970 value13684311492031368431150214currently i read the csv using numpy loadtxt method can easily use read csv from pandas currently for my series i am converting the timestamps field as followstimestamp datedatetimedatetimefromtimestamptimestamp columni for i in rangelentimestamp columni follow this by setting timestamp date as the datetime index for my dataframe i tried searching at several places to see if there is a quicker inbuilt way of using these unix epoch timestamps but could not find any a lot of applications make use of such timestamp terminology is there an inbuilt method for handling such timestamp formatsif not what is the recommended way of handling these formats,['python'] +472274,junit parameterized tests how do i run only 1 specific test from intellijeclipse i have a parameterized junit test that spawns 50 testsrunwithparameterizedclasspublic class nurserosteringsolveallturtletest parameterizedparametersname index 0 public static collectionobject getsolutionfilesasparameters return returns 50 files public nurserosteringsolveallturtletestfile unsolveddatafile test public void solvedatafile running it takes an hour and it is impossible to shorten that time they are integration tests test 28 failshow do i run test 28 alone without running the other 49 tests without changing the actual code by simply configuring a d or something similar in intellijs or eclipses run configuration,['java'] +472292,difference between eclipse indigo and eclipse juno currently i am using eclipse indigo v37 for selenium webdriver automation tests with java there is also eclipse juno v38 42 available that i have never usedwhats the difference between eclipse indigo and eclipse juno,['java'] +472366,usort issue with decimal numbers i am currently trying to sort a multidimensional array by its subvaluesthe structure of the array is0 array id 87 sold 50 stock 991 speed 15 days left 66067 1 array id 97 sold 20 stock 120 speed 12 days left 100 2 array id 36 sold 2 stock 1020 speed 102 days left 10 the code i am using isusortdata functiona b return a getsortby b getsortby where the getsortby variable equals the keyso far so good everthing is working it sorts all values correctly except the speedfirst i thought it has something to do with the decimal numbers but the days left include also decimals and are sorted correctly correct output days left0 array id 97 sold 20 stock 120 speed 12 days left 100 1 array id 87 sold 50 stock 991 speed 15 days left 66067 2 array id 36 sold 2 stock 1020 speed 102 days left 10 wrong output speed0 array id 97 sold 20 stock 120 speed 12 days left 100 1 array id 87 sold 50 stock 991 speed 15 days left 66067 2 array id 36 sold 2 stock 1020 speed 102 days left 10 hope anybody can help me,['php'] +472391,boostasioacceptor accept new incoming connections while old ones still open i am writing proxy server based on boost asio in the part of my code responsible for accepting incoming connections from browser to proxy server i am facing the behaviour i am not fully understandso i am creating acceptor object with next constructor acceptor io service boostasioiptcpendpointboostasioiptcpv4 port truestart listening here start accept new connectionresetnew connection io servicesfront connection id acceptorasync accept new connectionget socket boostbindserverhandle accept this boostasioplaceholderserrorand handle acceptif error new connectionstart continue waiting for incoming connectionsstart acceptin general my code for accepting incoming connections is the same as in the http server 2 examplethe problem appears only when first incoming connection was not closed then second incoming will be queued and pending till first one will be closedaccording to this two answers boostasio acceptor reopen and async read after eofhow to launch an event when my boostasio tcp server just start running aka io servicerun the acceptor object will add all incoming connections into the queue and will not accept them till pending connection will not be closedi want to achieve immediate processing for all incoming connections so they are not pending in the acceptors queue and i did not find any solution so far could you please help me what is right way to implement thisconnectionstart functionvoidconnectionstart bsocketasync read someboostasiobuffer bbuffer boostbindconnectionhandle browser read headers shared from this boostasioplaceholderserror boostasioplaceholdersbytes transferred graphical representationupdate boost asio logsasio136846099538962901 acceptasio13684610038551131ecsystem0asio136846100385511312 receiveasio13684610038551132ecsystem0bytes transferred318asio136846100385611313 acceptasio13684610038561131asio136846100385611324 resolveasio13684610038561132asio13684610038661144ecsystem0asio136846100386611445 connectasio13684610038681144asio13684610042041335ecsystem0asio136846100420413356 sendasio13684610042041335asio13684610042041336ecsystem0bytes transferred302asio136846100420413367 receiveasio13684610042041336asio13684610046131567ecsystem0bytes transferred16384asio136846100461315678 sendasio13684610046141577asio13684610046141578ecsystem0bytes transferred16384asio136846100461415789 receiveasio13684610046141578asio13684610046141579ecsystem0bytes transferred1946asio1368461004614157910 sendasio13684610046141579asio136846100461415710ecsystem0bytes transferred1946asio13684610046141571011 receiveasio136846100461415710asio136846100461815711ecsystem0bytes transferred14080asio136846100461815712 sendasio136846100461915711asio136846100461915712ecsystem0bytes transferred14080asio13684610046191571213 receiveasio136846100461915712asio136846101924899413ecasiomisc2bytes transferred0asio136846101924899413asio136846101924899413asio136846101924899413asio13684610192539940asio13684610192539943ecsystem0asio1368461019253994314 receiveasio1368461019254994315 acceptasio13684610192549943asio136846101925499414ecsystem0bytes transferred489asio13684610192549941416 resolveasio136846101925499414asio136846101928199516ecsystem0asio13684610192819951617 connectasio136846101928299616asio136846101929399617ecsystem0asio13684610192939961718 sendasio136846101929399617asio136846101929399618ecsystem0bytes transferred470asio13684610192939961819 receiveasio136846101929399618asio136846101931599719ecsystem0bytes transferred11001asio13684610193159971920 sendasio136846101934919asio136846101934920ecsystem0bytes transferred11001asio136846101934920asio136846101934920asio136846101934920asio13684610193490i found that acceptors behaviour depends on functions i am using for read data from server socket connection class reads data from browser modifies request url connects to host and sends request then reading response from server and writing it back to browser so at the moment when i need to read server body i use this function ssocketasync read someboostasiobuffer sbuffer boostbindconnectionhandle server read body shared from this boostasioplaceholderserror boostasioplaceholdersbytes transferred if contentlength was not specified in service response headers i am reading till eof if async read some function was called and there is no more data to read on socket it is waiting 15 sec before eof will be raised all new incoming connections during this 15 sec will not be accepted by acceptorbut if i am using another variant of async read boostasioasync read ssocket boostasiobuffer sbuffer boostbindconnectionhandle server read body shared from this boostasioplaceholderserror boostasioplaceholdersbytes transferred incoming connections are accepted just fine but it boostasioasync read works a bit slow it is waiting for bunch of data to be read from socket and does not call handler till that data will be read so i thought i will specify transfer at least boostasioasync read ssocket boostasiobuffer sbuffer boostasiotransfer at least1 boostbindconnectionhandle server read body shared from this boostasioplaceholderserror boostasioplaceholdersbytes transferred yep it became better but problem with accepting new connections returns what is real differences between async read some and boostasioasync read it feels like something is blocked,['c++'] +472420,intersecting mongoid inqueries according to the mongoid documentation on explicit merging queryablein defaults to intersect i would expect the following querycontactinid a binid b cto result in something like this mongoidcriteria selector idinb options class contact embedded falsebut instead i get an overwrite for all imaginable cases1 prymain contactinid a binid b c mongoidcriteria selector idinb c options class contact embedded false2 prymain contactinid a bintersectinid b c mongoidcriteria selector idinb c options class contact embedded false3 prymain contactinid a bunioninid b c mongoidcriteria selector idinb c options class contact embedded falseam i doing something wrong,['ruby-on-rails'] +472430,python pandas plot is a noshow when i run this codeimport pandas as pdimport numpy as npdef add propgroup births groupbirthsastypefloat groupprop birthsbirthssum return grouppieces columns name sex birthsfor year in range1880 2012 path yobdtxt year frame pdread csvpath names columns frameyear year piecesappendframe names pdconcatpieces ignore index truetotal births namespivot tablebirths rows year cols sex aggfunc sumtotal birthsplottitle total births by sex and yeari get no plot this is from wes mckinneys book on using python for data analysiscan anyone point me in the right direction,['python'] +472470,is javascript synchronousblocking or asynchronousnonblocking by default i am trying to grasp on javascript asynchronous functions and callbacksi got stuck on the concept of callback functions where i am reading on some places they are use to have sequential execution of code mostly in context of jquery eg animateand some places specially in the context of nodejs they are use to have a parallel execution asynchronous and avoid blocking of codeso can some expert in this topic please shed light on this and clear this fuzz in my mind examples so i could make my mind for the usage of callback function or that is solely depends on the place of where you are callingplacing a callback function in your code thanksps i am scared that this question would be close as subjective but still i could expect concrete answer for this perhaps some examples edit actually this is the example from internet which makes me ambigousfunction do a simulate a time consuming function settimeout function consolelog do a this takes longer than do b 10 function do b consolelog do b this is supposed to come out after do a but it comes out before do a do ado bresult do b this is supposed to come out after do a but it comes out before do ado a this takes longer than do bwhen js is sequential then do b should always come after do a according to my understanding,['javascript'] +472511,split string by character i have a case in which i am doing the followingfinal string columns rowsplitdelimitertostringwhere delimiter is a characterthis works fine when i need to split based on tabs by providing t as the delimiter however when i want to split on a pipe i pass in a delimiter of and this does not work as expectedi have read several posts about how is a special character which means null or empty therefore it splits on every character it encounters though i do not want this behaviori could do a simple check in my code for this pipe case and get around the issueif equalsdelimitertostring columns rowsplit delimitertostringelse columns rowsplitdelimitertostring but i did not know if there was an easier way to get around this also are there any other special characters that act like the does that i need to take into account,['java'] +472564,jetbrains intellij keyboard shortcut to collapse all methods i am working on some legacy code that has a class that is 10 lines of code and has 100s of methods is there a shortcut for any jetbrains ide since the shortcut would likely be shared across all of them to collapse all the methods functions so that only the method signatures are shown something like this public string mymethodstring arg1 int arg2public string mysecondmethodstring arg1 int arg2,['java'] +472594,matplotlib update position of patches or set xy for circles inspired by this example i am trying to write a little matplotlib program that allows the user to drag and drop datapoints in a scatter plot dynamically in contrast to the example which uses a bar plot and thus allows dragging of rectangles my goal was to achieve the same with other patches like for instance a circle any patch that is more scatterplotcompatible than a rectangle would do however i am stuck at the point of updating the position of my patch while a rectangle provides a function set xy i cannot find a direct analog for cirlce or ellipse obtaining the position of a circle is also less straightforward that for a rectangle but is possible via obtaining the bounding box the missing piece now is to find a way to update the position of my patch any hint on how to achieve this would be great the current minimal working example would look like thisimport numpy as npimport matplotlibpyplot as pltimport matplotlibpatches as patchesclass draggablepatch def init self patch selfpatch patch selfstoredposition none selfconnect def getposofpatchself marker ext markerget extentsget points x0 ext00 y0 ext01 x1 ext10 y1 ext11 return 05x0x1 05y0y1 def connectself connect to all the events we need selfcidpress selfpatchfigurecanvasmpl connectbutton press event selfonpress selfcidmotion selfpatchfigurecanvasmpl connectmotion notify event selfonmove def onpreself event on button press we will see if the mouse is over us and store some data contains attrd selfpatchcontainsevent if contains selfstoredposition selfgetposofpatchselfpatch eventxdata eventydata def onmoveself event how to update an circle contains attrd selfpatchcontainsevent if contains and selfstoredposition is not none oldpos oldeventxdata oldeventydata selfstoredposition dx eventxdata oldeventxdata dy eventydata oldeventydata newx oldpos0 dx newy oldpos1 dy print now i would like to move my patch to newx newydef mypatchxy return patchescirclexy radius05 alpha05n 10x nprandomrandomny nprandomrandomnpatches mypatchxi yi for i in rangenfig pltfigureax figadd subplot1drs for patch in patches axadd patchpatch dr draggablepatchpatch drsappenddrpltshow,['python'] +472597,will i receive gcm messages if android kill my app and if i do a force close from the settings i am a newbie to android development and i am interested in two things which is connected to google cloud messagingdoes android absolutely kill applications if they run for a long time in background as ios does and if so will i receive gcm notifications after my app was killed by androidis there some difference between force close from the settings menu and when the app is killed by android and if i do force close will i receive gcm notifications,"['java', 'android']" +472600,using directinput to receive signal after plugging in joystick i have a c program that enumerates all the input devices using direct input at the start of the program if the program is started and then i plug in another controller this controller would not be recognized until the program is restarted anyone know of an event i can use that will cause my program to enumerate all of the devices after a new one is plugged in,['c++'] +472662,deserializing a json string with newtonsoft or restsharp i have a string that comes out of a database which is in json formati have tried to deserialize it withrestsharpdeserializersjsondeserializer deserial new jsondeserializervar x deserial deserializecustomermystringfromdbbut the deserialize function expects an irestresponseis there a way to use restsharp to just deserialize raw strings,['c#'] +472769,ajax timeout callback function is there a way to run a function if jquerys ajax function hits it is timeoutieajaxtimeout10do something if timeout,['jquery'] +472826,why does not python always require spaces around keywords why can spaces sometimes be omitted before and after key words for example why is the expression 2if1e1else 1 validseems to work in both cpython 27 and 33 python2python 273 default nov 12 2012 095025 gcc 421 compatible apple clang 41 tagsappleclang42166 on darwintype help copyright credits or license for more information 2if1e1else 12 python3python 330 default nov 12 2012 100155 gcc 421 compatible apple clang 41 tagsappleclang42166 on darwintype help copyright credits or license for more information 2if1e1else 12and even in pypy pypypython 272 341e1e3821ff jun 07 2012 154254pypy 190 with gcc 421 on darwintype help copyright credits or license for more informationand now for something completely different pypy 16 released 2if1e1else 12,['python'] +472831,sum values in foreach loop php foreachgroup as keyvalue echo key value brfor exampledoc1 8doc2 7doc3 1i want to count value so the result is 871 16 what should i dothanks,['php'] +472874,php remove empty array strings in multidimensional array i have this arrayarymain arrayarrayhellobye arrayarray it is formed by reading a csv file and the array are the empty rows at the end of the file how can i remove them i have tried arymain array filterarymain but it is not working thanks a lot,['php'] +472884,executing stored procedure and returning row count back to code via output and sql parameters i have the following code that matches user input via session variables the stored procedure returns the row count if the data in the session variable matches the data in the databaseeverything works except i want to return the row count which will always be a single rowin a nutshell you visit a form add info and hit submit the data is stored in session and the stored procedure returns the data when matchedeven though the program works the intreccount variable is always zero rather than the row countstored procedurecreate procedure dbouspconfirmation recordid char36 lname varchar30 fname varchar30 minit char1 recordcount int outputasselect from registrationwhere recordid recordid and lname lname and fname fname and minit minitset recordcount rowcountreturnmethodcodepublic static dataset confirmation sqlcommand cmdsql new sqlcommanduspconfirmation connectioncmdsqlcommandtype commandtypestoredprocedurecmdsqlparametersaddnew sqlparameterrecordid sqldbtypevarchar 36cmdsqlparametersrecordiddirection parameterdirectioninputcmdsqlparametersrecordidvalue recordidsessioncmdsqlparametersaddnew sqlparameterlname sqldbtypevarchar 30cmdsqlparameterslnamedirection parameterdirectioninputcmdsqlparameterslnamevalue lnamesessioncmdsqlparametersaddnew sqlparameterfname sqldbtypevarchar 30cmdsqlparametersfnamedirection parameterdirectioninputcmdsqlparametersfnamevalue fnamesessioncmdsqlparametersaddnew sqlparameterminit sqldbtypechar 1cmdsqlparametersminitdirection parameterdirectioninputcmdsqlparametersminitvalue mnamesessioncmdsqlparametersaddnew sqlparameterrecordcount sqldbtypeintcmdsqlparametersrecordcountdirection parameterdirectionoutput then a variable to hold the row count via an output variable int32 intreccount converttoint32cmdsqlparametersrecordcountvaluesqldataadapter da new sqldataadaptercmdsqldataset ds new datasetdafilldstry connectionopen cmdsqlexecutenonquerycatch exception ex dbmsg exmessage finally connectionclose cmdsqlthispose cmdsqlparametersclearreturn ds,"['c#', 'sql']" +472890,class name convention in java what is the naming convention of classes in java for example should all classes be in upper case like myclassjava as some classes like comsunorgapachebcelinternalgeneric anewarray can be found in suns library as wellnote i have read all naming convention from oracle but i could not find anything which says we should name a class with all uppercase,['java'] +472916,javascript date from string giving different output from chrome to firefox i am trying to write some javascript code to format a date as i want but i have troubles making it work on firefox it is working as i want on chromethe input i have in a form is 050113 mmddyy and i want 20130501 ymmddfor that what i did is something like this var formdate documentgetelementbyidstartvaluevar mydate new dateformdatevar startdate new datestartdatesetmonthmydategetmonth 1startdatesetfullyearmydategetfullyearvar formatteddate startdategetfullyear startdategetmonth 10 0 startdategetmonth 01 the day is always 01alertformatteddateyou can try it on both browsers here on google chrome this code gives me for example 20130501 for may but on firefox i have 19130501i know i could have written something like 20 startdategetyear but i was wondering why the results were different from chrome to firefox and maybe if you have a better way of writing the code i pasted here please let me know thanks,['javascript'] +472934,ios certificate generation error thisc quota exceeded i am trying to generate an ios development certificate after i select the certsigningrequest file from my desktop and click on generate i get the following errorprocessing of multipartformdata request failed thisc quota exceededwhy is this happening and how can i generate my certificate,['ios'] +473042,mysql delete constraint i have a table with below structure create table lm help id int10 not null auto increment section int10 not null language int10 not null title varchar255 not null text text not null timestamp timestamp not null default current timestamp primary key id unique key unique help sectionlanguage key language constraint language constraint language constraint foreign key language references lm languages id constraint section constraint foreign key section references lm help sections id engineinnodb auto increment4 default charsetlatin1i need to remove unique help key but i am getting foreign key constraint errordue to this error i not able to remove anything among these section constraint language constraint unique helpbelow are other tables that refer to this create table lm languages id int11 not null auto increment name varchar255 not null code varchar255 not null status int11 default null created at datetime not null updated at datetime not null primary key id engineinnodb auto increment6 default charsetlatin1create table lm help sections id int11 not null auto increment name varchar255 not null primary key id engineinnodb auto increment2 default charsetlatin1,['mysql'] +473054,facebook auth dialog developer warning concerning the use of thisplay type popup starting today we receive developer warnings in the auth dialog with the following messageyou are using a thisplay type of popup in a large browser window or tab for a better user experience show this dialog with our javascript sdk without specifying an explicit thisplay type the sdk will choose the best thisplay type for each environment alternatively set height and width on your windowopen call to properly size this dialog if you have special requirements precluding you from using the sdk this message is only visible to developers of your applicationwe have the following situationwith javascript we open a new popupthe src of the popup is set with facebooks phpsdk method getloginurlpopup itself has a size of 400px by 580pxthe phpsdk itself references the proper use of thisplaypopup within it is own codeif you are using the generated url with a windowopen call in javascript you can pass in thisplaypopup as part of the paramsthe jssdk documentation says that the maximumsize of the opened popup should be 400x580for use in a browser popup no bigger than 400px by 580px use this thisplay type to maintain context for the user without needing to perform a fullpage redirectso to sum up according to the docs the implementation above should be ok is anyone else having this warning or a solution for this,['javascript'] +473148,wpf caliburnmicromvvm navigation i am building a project and one of the biggest problems i have come across until now is navigationi have been looking for some time now for examples of caliburnmicromvvm navigation but they all seem to be really long and i could not really understand much of it beginner heresome info about my projecti want there to be an outer windowshell with menu linkstabs that open pages according to the button clicked inside an inner part of the shell and be able to open change the page from within a onei currently have shellviewmodelcs mainviewmodelcs my models and my viewsfor now all i need to know is how to make mainviewmodel load inside shellviewmodel on startupusing contentcontrolframes and how to move from one page to anotheryou could also just write it in points and link me to some useful examples and i believe i could continue from there it would be best to get a thorough explanation of stuff if possible,['c#'] +473175,logging in rails is there any performance hit rails comes bundled with rubys logger class in the standard library the available log levels are debug info warn error and fatali was wondering if i add extensive logging in my rails application with log level set to debug for development and testing will there be a performance impact when running in production with logging turnedoff or set at higher level such as configlog level fatal,"['ruby-on-rails', 'ruby']" +473181,autofixture how to createanonymous from a systemtype i need to create an object from autofixture using nothing more than a systemtype however there does not appear to be an overload of createanonymous that simply takes a type they all expect a compile time generic t is there a way to convert a systemtype to tedit with usage detailsi am using automapper which has a hook for injecting components to support complex mapping scenariosvoid constructservicesusingsystemfunctypeobject constructoras you can see from the signature clients can register a func which automapper invokes anytime it needs an injected service mostly valueresolver implementations in production builds this method calls into my structuremap container to retrieve a component however when unit testing my mapping code i must provide stub implementations otherwise automapper throws an exception since i am using autofixture moq as my automocking container it seems natural to let af new up a fully hydrated stub so i can concentrate on writing unit test code,['c#'] +473202,fx cop could not resolve type reference systemwindowsinputicommand having troubles with fxcop on our buildagent only and only through the command line tool onlyi am using the caliburnmirco framework and added a custom trigger so i can use the delete button this class implements the icommand interfacethe error is the following error was encountered while reading module myprojectui could not resolve type reference system version40 cultureneutral publickeytokenb77a5c561934e089systemwindowsinputicommandthe full error logxml version10 encodingutf8xmlstylesheet typetextxsl hrefcbuildagentworkprogram filesmicrosoft fxcop 136xmlfxcopreportxslfxcopreport version100 localized string keycategorycategorystring string keycertaintycertaintystring string keycollapseallcollapse allstring string keycheckidcheck idstring string keyerrorerrorstring string keyerrorserrorsstring string keyexpandallexpand allstring string keyhelphelpstring string keylinelinestring string keymessagesmessagesstring string keylocationnotstoredinpdblocation not stored in pdbstring string keyprojectprojectstring string keyresolutionresolutionstring string keyrulerulestring string keyrulefilerule filestring string keyruledescriptionrule descriptionstring string keysourcesourcestring string keystatusstatusstring string keytargettargetstring string keywarningwarningstring string keywarningswarningsstring string keyreporttitlecode analysis reportstring localized exceptions exception keywordca01 kindengine typemicrosoftfxcopsdkfxcopexceptiontype exceptionmessagean unhandled exception was encountered during loadtargetsforanalysisexceptionmessage innertypemicrosoftfxcopsdkinvalidmetadataexceptioninnertype innerexceptionmessagethe following error was encountered while reading module myprojectui could not resolve type reference system version40 cultureneutral publickeytokenb77a5c561934e089systemwindowsinputicommandinnerexceptionmessage innerstacktrace at microsoftfxcopsdkreaderhandleerrormodulenode mod string errormessage at microsoftfxcopsdkreadergetdummytypenodeidentifier namesp identifier name modulenode declaringmodule typenode declaringtype boolean expectstruct at microsoftfxcopsdkreadergettypefromrefint32 i boolean expectstruct at microsoftfxcopsdkreaderdecodeandgettypedeforreforspecint32 codedindex at microsoftfxcopsdkreadergetinterfacesint32 i int32 firstinterfaceindex interfacecollection interfaces at microsoftfxcopsdkreadergettypefromdefhelperint32 i at microsoftfxcopsdkreadergettypefromdefint32 i at microsoftfxcopsdkreadergettypelistmodulenode module at microsoftfxcopsdkmodulenodeget types at microsoftfxcopenginesintrospectionintrospectionanalysisengineloadtargetsforanalysistargetfiledictionary targetfiles int32 loadthreadcount at microsoftfxcopenginesintrospectionintrospectionanalysisengineanalyzeinternalinnerstacktrace exception exception keywordca01 kindengine typemicrosoftfxcopsdkfxcopexceptiontype exceptionmessagean unhandled exception was encountered during globalbeforeanalysisexceptionmessage innertypesystemnullreferenceexceptioninnertype innerexceptionmessageobject reference not set to an instance of an objectinnerexceptionmessage innerstacktrace at microsoftfxcopsdkinternalutilitiesglobalbeforeanalysis at microsoftfxcopenginesintrospectionintrospectionanalysisengineanalyzeinternalinnerstacktrace exception exceptionsfxcopreport,['c#'] +473229,writing temp file in tomcat 70 fails i try to write a temporary file from a tomcat 70 application it failsservlet code snippet file formfile filecreatetempfiledocument pdfexception javaioioexception no such file or directory at javaiounixfilesystemcreatefileexclusivelynative method at javaiofilecreatetempfilefilejava1879 at javaiofilecreatetempfilefilejava1923 at gogetservlettestjava20i guess catalinapolicy is in the wayhow can i enable temp files for web applications,['java'] +473242,what does i ran across this example and realized i do not fully understand whats going on hereif a b return falsewhat is in java,['java'] +473311,why is fast inverse square root so odd and slow on java i am trying to implement fast inverse square root on java in order to speed up vector normalization however when i implement the singleprecision version in java i get speeds about the same as 1f floatmathsqrt at first then quickly drops to half the speed this is interesting because while mathsqrt uses i presume a native method this involves floating point division which i have heard is really slow my code for computing the numbers is as followspublic static float fastinversesquarerootfloat x float xhalf 05f x int temp floatfloattorawintbitsx temp 0x5f3759df temp 1 float newx floatintbitstofloattemp newx newx 15f xhalf newx newx return newxusing a short program i have written to iterate each 16 million times then aggregate results and repeat i get results like this1f mathsqrt took 65209490 nanosecondsfast inverse square root took 65456128 nanosecondsfast inverse square root was 0378224 percent slower than 1f mathsqrt1f mathsqrt took 64131293 nanosecondsfast inverse square root took 26214534 nanosecondsfast inverse square root was 59123647 percent faster than 1f mathsqrt1f mathsqrt took 27312205 nanosecondsfast inverse square root took 56234714 nanosecondsfast inverse square root was 105895914 percent slower than 1f mathsqrt1f mathsqrt took 26493281 nanosecondsfast inverse square root took 56004783 nanosecondsfast inverse square root was 1392402 percent slower than 1f mathsqrti consistently get numbers which are about the same speed for both followed by an iteration where fast inverse square root saves about 60 percent of the time required by 1f mathsqrt followed by several iterations which take about twice as long for fast inverse square root to run as the control i am confused why fisr would go from same 60 percent faster 100 percent slower and it happens every time i run my programedit the above data is when i run it in eclipse when i run the program with javacjava i get completely different data1f mathsqrt took 57870498 nanosecondsfast inverse square root took 88206794 nanosecondsfast inverse square root was 52421004 percent slower than 1f mathsqrt1f mathsqrt took 54982400 nanosecondsfast inverse square root took 837562 nanosecondsfast inverse square root was 52371599 percent slower than 1f mathsqrt1f mathsqrt took 215822 nanosecondsfast inverse square root took 76705152 nanosecondsfast inverse square root was 263259133 percent slower than 1f mathsqrt1f mathsqrt took 20159210 nanosecondsfast inverse square root took 80745616 nanosecondsfast inverse square root was 300539585 percent slower than 1f mathsqrt1f mathsqrt took 21814675 nanosecondsfast inverse square root took 85261648 nanosecondsfast inverse square root was 290845374 percent slower than 1f mathsqrtedit2 after a few responses it seems the speed stabilizes after several iterations but the number it stabilizes to is highly volatile anyone have any idea whyheres my code not exactly concise but heres the whole thingpublic class fastinversesquareroottest public static fastinversesquareroottest conducttest float result 0f long starttime endtime midtime starttime systemnanotime for float x 1f x 4 0 0f x 025f result 1f float mathsqrtx midtime systemnanotime for float x 1f x 4 0 0f x 025f result fastinversesquarerootx endtime systemnanotime return new fastinversesquareroottestmidtime starttime endtime midtime public static float fastinversesquarerootfloat x float xhalf 05f x int temp floatfloattorawintbitsx temp 0x5f3759df temp 1 float newx floatintbitstofloattemp newx newx 15f xhalf newx newx return newx public static void mainstring args throws exception for int i 0 i 7 i systemoutprintlnconducttesttostring private long controldiff private long experimentaldiff private double percenterror public fastinversesquareroottestlong controldiff long experimentaldiff thisexperimentaldiff experimentaldiff thiscontroldiff controldiff thispercenterror 100d experimentaldiff controldiff controldiff override public string tostring stringbuilder sb new stringbuilder sbappendstringformat1f mathsqrt took d nanosecondsn controldiff sbappendstringformat fast inverse square root took d nanosecondsn experimentaldiff sbappendstring formatfast inverse square root was f percent s than 1f mathsqrtn mathabspercenterror percenterror 0d slower faster return sbtostring,['java'] +473349,setting phantomjs viewportsize in qunit test i need to test my script at different viewport sizes in my tests i would like to change the viewport size of phantomjs by setting pageviewportsize i am running my tests through gruntcontribqunit and phantomjs is not accessible in my test code is there a way to gain access to it,['javascript'] +473390,why does iterative elementwise array multiplication slow down in numpy the code below reproduces the problem i have encountered in the algorithm i am currently implementingimport numpyrandom as randimport timex randnormalsize30050y randnormalsize30050for i in range10 t0 timetime y x print 4f timetimet0 y ymax to prevent overflowsthe problem is that after some number of iterations things start to get gradually slower until one iteration takes multiple times more time than initiallya plot of the slowdowncpu usage by the python process is stable around 1718 the whole timei am using python 274 32bit versionnumpy 171 with mklwindows 8,['python'] +473396,c thisplaying characters i am learning and improving my programming skills from think like a programmer book and i was asked to thisplay this kind of pyramid i did it with this codeforint i 0 i 4 i forint k 0 k i k cout forint j 0 j 8 i 2 j cout cout nbut the questions was using the same rule as the shapes programs from earlier in the chapter onlytwo output statementsaone that outputs the hash mark and one that outputsan endofline write a program that produces the following shapei am not sure but is it possible to thisplay something like this with only 2 statements and without using space charactereditthanks for an answer guys but according to author i should do this with only cout and cout n and here is my point because it seems that manipulating with some methods or functions is not an option write a program that uses only two output statements cout and cout nto produce a pattern of hash symbols shaped like a of course with use of loops p,['c++'] +473421,what is the advantage of using restangular over ngresource ngresource already seems really simple to implement things withwhat are the advantages thisadvantages of using restangular over ngresource113 resource will return promises and can be implimented using latest pr commit will future support be offered to resource to support additional verbs that restangular does and if that happens restangular seems like it will thisappear and become irrelivant,['javascript'] +473434,how can i slow down a loop in python if i have a list ll 0 1 2 3 4 5 6 7 8 9is there a way to control the following for loop so that the next element in the list is only printed one second after the previousfor i in l print iin other words is there a way to elegantly slow down a loop in python,['python'] +473449,how do i return data via ajax using plupload on upload complete i have been trying for the last few hours to get something anything back from the pluploader upon completion of the queue to no availhere is my js codevar uploader pluploaddivpluploadbootstrapuploaderbinduploadcomplete functionup files var obj parsejsonresponseresponse alertobjresulton the very last line of the uploadphp script i havediejsonrpc 20 result requestunitid id idthis makes sense to me but it is not working the files upload without problems but the alert does not even fire off there is no response whatsoeverthoughtsedit with new code as a solutionthe js that i am using thanks jblvar uploader pluploaddivpluploadbootstrapuploaderbindfileuploaded functionupldr file object var mydata try mydata evalobjectresponse catcherr mydata eval objectresponse vehicle id valuevalmydataresultuploadphp script stayed the same last line of codediejsonrpc 20 result requestunitid id idso basically when i create the shell row to associate images to in the upload script i pass the row id back to the original form into a hidden input field via the fileuploaded event that is bound to the plupload objectinput typehidden namevehicle id value idvehicle id value value works like a charm,"['php', 'jquery']" +473486,how to get a users entire youtube watch history i am trying to get a full list of the watched videos for a given user in my youtube api application i want to add up the total duration of all videos they have watched on youtube when i get the list of videos in the history playlist the api caps it at 50 i know there is the pagination thing but the total in the playlist is 50 not just the total on this page i cannot access more data with the api it appears is there any way i can get this playlist without the data cap i am hoping for another method of using the api or a way to do it without the api i know youtube stores this data because i can view my entire history far more that 50 videos on the sitei am using this codevar requestoptions playlistid playlistid part snippet maxresults 50gapiclientyoutubeplaylistitemslistrequestoptionswhere playlistid is the id of the history playlist i got from a gapiclientyoutubechannelslist request,['javascript'] +473499,setting thumb to a particular positionnot the offset of seekbar programaticaly i have a customized seekbar in which am updating the progress and maximum amplitude of the sound so the seekbar varies according to sound detection and thumb shows the maximum amblitude of sound i want to set the position of the thumb to a particular positionmax amblitude like we set the progress in seekbar i had gone through loads of questions and answers and also i ran through the developer docs in developer docs its mentioned that only offsets can be given which maintains the thumb off the track of progressfrom developer docsetthumboffsetint thumboffsetsets the thumb offset that allows the thumb to extend out of the range of the trackis there any possible way to set the thumb to a particular position sample is shown below in this i had set the thumbs offset for just showing a sample instead of this i want to set thumb to an accurate position,['android'] +473579,pylint ignore multiple in rcfile in my django project i am using an externally written app which is badly written now i want to ignore this app from my pylint reporting however i cannot get pylint to ignore it pylint is already ignoring the south migrations like thismasterignoremigrationshowever the documentation states that multiple ignores can be specified but i have tried a few and could not get them to workdoes not workmasterignoremigrationsbadappalso does not workmasterignoremigrationsignorebadappmy project structure is like this goodapp modelspy testspy viewspy badapp modelspy testspy viewspy managepyi would rather not sprinkle my code with pylint skipfile but rather configure pylint using the rcfile,['python'] +473606,process a single aes128ecb block using cc and openssl i want to en and decode a single 16 bytes block of data using aes128ecb cipherfirst i did it via the openssl command line utility using the ascii 16 characters string a key simple key as the key and the ascii 16 characters string 1234567890uvwxyz as the message the command line utility printed the hexadecimal string 142f 7d9e ad8c 0682 30e0 f165 a52f f789 as ciphered message and then successfully decoded it back to original message see below echo n 1234567890uvwxyz openssl aes128ecb k echo n a key simple key xxd ps nopad xxd0 142f 7d9e ad8c 0682 30e0 f165 a52f f789 0e echo 142f 7d9e ad8c 0682 30e0 f165 a52f f789 xxd r ps openssl aes128ecb d k echo n a key simple key xxd ps nopad 1234567890uvwxyznow i have written a short c program which should do the same it does not work there are 2 issuesthe output of encoding part is 32 bytes long instead of 16 bytes the first half of these 32 bytes is exactly the ciphered text i expected to seethe decoding part is failing in the finalization step with the following openssl message error06065064digital envelope routinesevp decryptfinal exbad decrypti suspect that the both issues are somehow connected to padding but i do not understand what is wrong exactly and how to fix it here is the full output of the program g wall g sslaes128ecbc lcrypto lssl aout 21 lessencoding failencoding 1234567890uvwxyz t9ead8cf820e0f1ea5f789xa0pudacerf8ara8a97gferror06065064digital envelope routinesevp decryptfinal exbad decryptaborting in you string decodeu string you string at sslaes128ecbc56and here is the c program itself with line numbers01 include string02 include iostream03 include opensslevph04 include opensslerrh05 include opensslsslh06 define abort fprintfstderr snaborting in s at sdn err error stringerr get error null pretty function file line abort 00708 typedef stdbasic stringunsigned char you string09 static you string encodeu string key you string data10 static you string decodeu string key you string data12 echo n 1234567890uvwxyz openssl aes128ecb k echo n a key simple key xxd ps nopad xxd13 echo 142f 7d9e ad8c 0682 30e0 f165 a52f f789 xxd r ps openssl aes128ecb d k echo n a key simple key xxd ps nopad1415 int main16 17 ssl load error strings1819 you string key unsigned char a key simple key20 you string clear text unsigned char 1234567890uvwxyz21 you string secret txt unsigned char x14x2f x7dx9e xadx8c x06x82 x30xe0 xf1x65 xa5x2f xf7x8923 stdcerr encoding encodekey clear textsecret txt ok fail stdendl24 stdcerr encoding charclear textc str charencodekey clear textc str stdendl25 stdcerr decoding decodekey secret txtclear text ok fail stdendl26 stdcerr decoding charsecret txtc str chardecodekey secret txtc str stdendl2728 return 029 3031 static you string encodeu string key you string data32 33 evp cipher ctx ctx34 evp cipher ctx initctx35 evp cipher ctx set paddingctx false36 evp encryptinit ex ctx evp aes 128 ecb null keyc str null37 unsigned char buffer1024 pointer buffer38 int outlen39 evp encryptupdate ctx pointer outlen datac str datalength or abort40 pointer outlen41 evp encryptfinal exctx pointer outlen or abort42 pointer outlen43 return you stringbuffer pointerbuffer44 4546 static you string decodeu string key you string data47 48 evp cipher ctx ctx49 evp cipher ctx initctx50 evp cipher ctx set paddingctx false51 evp decryptinit ex ctx evp aes 128 ecb null keyc str null52 unsigned char buffer1024 pointer buffer53 int outlen54 evp decryptupdate ctx pointer outlen datac str datalength or abort55 pointer outlen56 evp decryptfinal exctx pointer outlen or abort57 pointer outlen58 return you stringbuffer pointerbuffer59,"['c++', 'c']" +473614,find whether check boxes are checked inside a servlet i have several check box in a form i just wanna way to check whether they are checked or not if checked i need to store their id in the databasethat i can do it but my question is how to determine whether are checked or not instead of checking for each check box on at a time i need to check whether its checked or not inside a servletthis is my codedoctype html public w3cdtd html 401 transitionalen htmlheadmeta httpequivcontenttype contenttexthtml charsetiso88591titleinsert title heretitleheadbodyrole idinput typetext nameroll idbrrole nameinput typetext nameroll namebrrole descriptiontextarea nameroll desctextareabrbrbrscreen1brtab1brinput typecheckbox names1 t1 view values1 t1 view viewbrinput typecheckbox names1 t1 add values1 t1 add addbrinput typecheckbox names1 t1 edit values1 t1 edit editbrinput typecheckbox names1 t1 delete values1 t1 delete deletebrtab2brinput typecheckbox names1 t2 view values1 t2 view viewbrinput typecheckbox names1 t2 add values1 t2 add addbrinput typecheckbox names1 t2 edit values1 t2 edit editbrinput typecheckbox names1 t2 delete values1 t2 delete deletebrscreen2brtab1brinput typecheckbox names2 t1 view values2 t1 view viewbrinput typecheckbox names2 t1 add values2 t1 add addbrinput typecheckbox names2 t1 edit values2 t1 edit editbrinput typecheckbox names2 t1 delete values2 t1 delete deletebrtab2brinput typecheckbox names2 t2 view values2 t2 view viewbrinput typecheckbox names2 t2 add values2 t2 add addbrinput typecheckbox names2 t2 edit values2 t2 edit editbrinput typecheckbox names2 t2 delete values2 t2 delete deletebrinput typesubmit namesumbit textsubmitbodyhtmlbut in my code i have several check boxes i need to hardcode that for every check box is there way so that i put it in a loop and check for all check boxes,"['java', 'html']" +473631,jquery alt accordion not closing for a variety of reasons i have created an accordion that has a specified height overflowhidden and opens full on click i cannot however get it to collapse when i click on the required buttonthis is the relevant jsdocumentready function liww slidesaddclasslivequeryappendspan classnavspan liww slidesclickfunction liww slidesremoveclassactive thisaddclassactive spannavaddclassopencssbottom0 spanopenclickfunction thisparentremoveclassactive this is the relevant cssww main preview ul liactive marginbottom 10px paddingbottom 10px height autoimportant ww main preview ul liactive spannav backgroundposition top center ww main preview ul lilivequery overflow hidden height 76px marginbottom 10px paddingbottom 10px how do i get the liww slides to close on click of the relevant spannavopen,"['jquery', 'html', 'css']" +473693,get underlying thispatch queue t from nsoperationqueue i seem to have some confusion between thispatch queue t and nsoperationqueue queuesby default afnetworkings afimagerequestoperation will execute the success callback block on the applications main thread to change this afhttprequestoperation has the property successcallbackqueue which lets you choose on which queue to run the callbacki am trying to execute the success callback on the same background queue background threads which already did the http request instead of returning to the main thread the nsoperationqueue which ran the http request should run the callback as well since there are some heavy calculations i need to do using some of the returned imagesmy first try was to set successcallbackqueue to the nsoperationqueue instance on which the afimagerequestoperation ran however the successcallbackqueue property is of type thispatch queue t so i need a way to get the underlying thispatch queue t of my nsoperation instance if there is such a thingis that possible or do i need to create a separate thispatch queue tthe reason i ask it is somewhat strange that afnetworking inherits from nsoperation but expects us to use thispatch queue t queues for the callbacks kind of mixing the two paradigmas thispatch queue t and nsoperationqueuethanks for any hints,['ios'] +473698,need empty div with background image to force height and must be responsive i need the followingemtpy div with no content background image set to the div thebackground image to be fluidresponsive on resize i cannot set fixeddimensions on the diveverything i try fails to force the div open to support the size of the background image any help is greatly appreciatedheader idheaderdiv classwrapperdiv classinnerdiv classtop bannerdivdivdiv classcleardivdivheaderfront header top banner background urlimagesbg frontjpg norepeat backgroundsize cover,['html'] +473705,begintransaction endtransaction and settransactionsuccessful what exactly do they do i have to provide synchronization when inserting querying updating and deleting items from a database as far as i understand begintransaction and begintransactionnonexclusive are the methods i need besides sqlite documentation describes exclusive immediate and deferred quite well transactions can be deferred immediate or exclusive deferred means that no locks are acquired on the database until the database is first accessed if the transaction is immediate then reserved locks are acquired on all databases as soon as the begin command is executed without waiting for the database to be used after a begin immediate no other database connection will be able to write to the database or do a begin immediate or begin exclusive other processes can continue to read from the database however an exclusive transaction causes exclusive locks to be acquired on all databases after a begin exclusive no other database connection except for read uncommitted connections will be able to read the database and no other connection without exception will be able to write the database until the transaction is completeit seems to provide some protection from unwanted insertions and queries while some thread is working with the database but i am not sure that it guarantees synchronizationthere is the insert method of my contentprovideroverridepublic uri inserturi baseuri contentvalues values try mdatabase mhelpergetwritabledatabase mdatabasebegintransaction exclusive switch surimatchermatchbaseuri case uricodescountries case uricodescontinents case uricodesorgs string table baseurigetlastpathsegment long rowid mdatabaseinserttable null values uri uri uriwithappendedpathbaseuri longtostringrowid mdatabasesettransactionsuccessful return uri default mdatabaseendtransaction throw new illegalargumentexceptionunsupported uri space baseuri finally mdatabaseendtransaction i have not had any problems without begintransaction endtransaction and settransactionsuccessful before do i really need to add them,['android'] +473716,in version 2 map view does not show map map activity does not showing map it is appear as just white screen with zoom control buttonsmanifest file like this xml version10 encodingutf8manifest xmlnsandroid packagecomexampledemomap androidversioncode1 androidversionname10 usessdk androidminsdkversion8 androidtargetsdkversion17 permission androidnamecomexampledemomappermissionmaps receive androidprotectionlevelsignature usespermission androidnamecomexampledemomappermissionmaps receive usespermission androidnameandroidpermissioninternet usespermission androidnameandroidpermissionwrite external storage usespermission androidnamecomgoogleandroidprovidersgsfpermissionread gservices usespermission androidnameandroidpermissionaccess coarse location usespermission androidnameandroidpermissionaccess fine location application androidallowbackuptrue androidicondrawableic launcher androidlabelstringapp name androidthemestyleapptheme activity androidnamecomexampledemomapmainactivity androidlabelstringapp name intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity metadata androidnamecomgoogleandroidmapsv2api key androidvalueaizasyctqzocxfs3rpnsve79hhn1xojat2mbt4 application usesfeature androidglesversion0x020 androidrequiredtrue manifestmy xml file like thesexml version10 encodingutf8fragment xmlnsandroid androidididmap androidlayout widthmatch parent androidlayout heightmatch parent classcomgoogleandroidgmsmapssupportmapfragment log cat error0515 171516255 egoogle maps android api26201 failed to load map error contacting google servers this is probably an authentication issue but could be due to network errorsplease help me,['android'] +473721,simple physical quantity measurement unit parser for java i want to be able to parse expressions representing physical quantities likeglms2mskgmskgkgmsaflbs2and so on in the simplest way possible is it possible to do so using something like pyparsing if such a thing exists for java or should i use more complex tools like java cupedit to answere mrds question the goal is to make conversion between quantities so for example convert g to kg this one is simple or maybe afkgs2 to klbh2 supposing h is four hour and lb for pounds,['java'] +473744,iboutlets strong or weak outlets can be created like thisinterface searchviewcontroller uiviewcontrolleruisearchbardelegate iboutlet uiview viewsearchbar iboutlet uiscrollview scrollvieww iboutlet uilabel lblnameand also like thisinterface searchviewcontroller uiviewcontrolleruisearchbardelegate propertynonatomic weak iboutlet uiscrollview scrollviewwpropertynonatomic weak iboutlet uiview viewsearchbarpropertynonatomic weak iboutlet uilabel lblnameendi know the nonatomicatomic strongweak in arc but in the first example what are they strong weak nonatomic or atomicplease explain or link me to some detail,"['ios', 'objective-c']" +473798,how can i train a genetic programming algorithm onto a variable sequence of descriptors i am currently trying to design a genetic programming algorithm that analyses a sequence of characters and assigns a value to those characters below i have made up an example set every line represents a data point the values that are trained are realvaluedexamplefor the word abcde the algorithm should return 10 example datasetabcde 1abcdef 10abcdegh 3abcdelka 50aasd 3the dataset could be as large as it is needed since this is all just made up lets assume the rule that the gp should figure out is not too complicated and that its explained by the datawhat i would like the algorithm to do is to approximate the values from my dataset when given the input sequence my problem now is that each sequence can consist of a different number of characters i would prefer not to need to write some fancy descriptors myself if possible how can i train my gp preferably using tinygp or python to build this model since there was so much thiscussion here a diagram says a thousand wordswhat i want to do is just put a data point and put that into a function then i get a value which is my result unfortunately i do not know this function i just have a dataset that has some examples maybe 10 examples just an example now i use the genetic programming algorithm to find an algorithm that is able to convert my datapoint into a result this is my model the problem that i have in this case is that the data points are of differing lengths for a set length i could just specify each of the characters in the string as a input parameter but beats me what to do if i have a varying number of input parameters thisclaimer i have gotten to this problem multiple times during my studies but we could never work out a solution that would work out well like using a window descriptors etc i would like to use a gp because i like the technology and would like to try it out but during uni we also tried this with anns etc but to no avail the problem of the variable input size remains,['python'] +473808,release history of the app in itunes connect do you guys know how i can see the release dates of the previous versions of my app in itunes connect i had shipped several updates in the past and i would like to know when exactly i uploaded them etc i checked everywhere and i cannot find any information about the release history of the app thereis it just me or itunes connect lacks such a basic featurethanks for the help,['ios'] +473855,create a mysql connection in playframework with slick i am trying to connect to a mysql database with slick 100what i have done so farin buildscala i have addedval appdependencies seq anorm mysql mysqlconnectorjava 5124 comtypesafeslick slick 210 100 orgslf4j slf4jnop 164in applicationconfdbdefaultdrivercommysqljdbcdriverdbdefaulturlurl to mysql dbdbdefaultuseruserdbdefaultpasspasswordand now i am trying to read an entry from the db for this i have a model package modelsimport scalaslickdrivermysqldriversimple import databasethreadlocalsessionobject organisations extends tableint stringorganisation def id columnintid oprimarykey def name columnstringname def id nameand now i would like to just output the entriesval orgs for o organisations yield onameprintlnlength orgstostringbut it does not work i am sure i have made plenty of errors but there do not seem to be andy slick tutorials with mysqlthank you for your patience and i hope my explanations are clear,['mysql'] +473867,determine if a number only apears once in an array so this is kind of a homework question i have been thinking about it for quite a while and came up with a couple of solutions but i think a better one existswhats the fastest way to determine if there is an element int in the array that appears only once any element can appear any number of times 3 1 4 1 4 3 will return false while 3 1 4 1 4 1 would return true 3 appears oncewe are only allowed to use things we already learned all the basics recursion oop searching and sorting algos including quicksort so making a hash table is not an optionso far the best practical solution i came up with is sorting it using quicksort then going through it onlogn the best unpractical solution i came up with is making a big array the size of all possible int values and then using it is place similar to a hash table but that array is way too big to actually implement on is there another practical way to do this in on timeedit just got an answer from the ta the suggested on solution that i heard about was an unpractical one the same or similar to what i suggested and hence they told us not to use it i am 99 sure now that the best practical answer without hash tables is onlogn time thanks for all the suggestions and ideas everyone,['java'] +473872,knockout viewmodel base class javascript inheritance i have been using knockoutjs for a lot of projects lately and i am writing a lot of repetitive code i would like to be able to define a baseviewmodel class and have my pagespecific viewmodels inherit from it i am a bit confused about how to do this is javascript here is my basic baseviewmodelfunction ko undefined kobaseviewmodel function var self this selfitems koobservable selfnewitem selfdirtyitems kocomputedfunction return selfitemsfilterfunction item return itemdirtyflagisdirty selfisdirty kocomputedfunction return selfdirtyitemslength 0 selfload function koi would like to be able to list signatures for methods like load in the baseviewmodel and then give them definitions in the inheriting viewmodel is any of this possible i have found a few solutions online but they all rely on defining functionsclasses to make the inheritance work,['javascript'] +473874,using objc setassociatedobject with weak references i know that objc association assign exists but does it zero the reference if the target object is dealloced or is it like the old days where that reference needs to get niled or we risk a bad access later on,['objective-c'] +473917,how to capture stdout output from a python function call i am using a python library that does something to an objectdo somethingmy objectand changes it while doing so it prints some statistics to stdout and i would like to get a grip on this information the proper solution would be to change do something to return the relevant informationout do somethingmy objectbut it will be a while before the devs of do something get to this issue as a workaround i thought about parsing whatever do something writes to stdouthow can i capture stdout output between two points in the code egstart capturingdo somethingmy objectout end capturing,['python'] +473931,what is the purpose of i have not really come across this syntax during my programming classes in uni before and i am curious as to what it meansthe only times i have had to implement it waswhen i had to create a backgroundworker that had to be added to the progresschanged eventinvokemethodinvoker updatepingint euserstatewhen researching tutorials on using the caliburnmicro mvvm frameworknotifyofpropertychange counti have tried searching around on what this notation means but the special characters it uses seem to mess with google search and i have no idea what it is called,['c#'] +473940,error javalangclassnotfoundexception comgoogleandroidgmsmapsmapfragment in google map v2 i am using google map v2 api for the map i have copied the googleplayservicesjar in libs folder and set in the build path of eclipse i am getting exception as i added logcat please help to get solve this issuehome map viewxml fragment androidididmap androidlayout widthfill parent androidlayout heightfill parent androidnamecomgoogleandroidgmsmapsmapfragment androidlayout marginbottom60dpandroidmanifestxmlmanifest xmlnsandroid packagecomexampleapp androidversioncode1 androidversionname10 usessdk androidminsdkversion8 androidtargetsdkversion17 permission androidnamecomexampleapermissionmaps receive androidprotectionlevelsignature usespermission androidnameandroidpermissioninternet usespermission androidnameandroidpermissionaccess fine location usespermission androidnameandroidpermissionaccess coarse location usespermission androidnameandroidpermissioncall phone usespermission androidnameandroidpermissionaccess network state usespermission androidnamecomexampleapermissionmaps receive usesfeature androidglesversion0x020 androidrequiredtrue application androidicondrawableic launcher androidlabelstringapp name metadata androidnamecomgoogleandroidmapsv2api key androidvaluekey activity androidnamemainactivity androidlabelstringapp name androidcleartaskonlaunchtrue androidconfigchangesorientation androidscreenorientationportrait intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity activity androidnamehomemapview androidlabelstringtitle home androidconfigchangesorientation androidlaunchmodesingletop applicationmanifesthomemapviewjavapublic class homemapview extends fragmentactivity implements ontabchangelistener private googlemap mapview override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayouthome map view getting reference to supportmapfragment of the activity main supportmapfragment fragment new supportmapfragment getsupportfragmentmanagerbegintransaction addridmap fragmentcommit getting map for the supportmapfragment mapview fragmentgetmap mapviewsetmylocationenabledtrue logcat0515 231752843 eandroidruntime19782 fatal exception main0515 231752843 eandroidruntime19782 javalangruntimeexception unable to start activity componentinfocomexampleappcomexampleapphomemapview androidviewinflateexception binary xml file line 13 error inflating class fragment0515 231752843 eandroidruntime19782 at androidappactivitythreadperformlaunchactivityactivitythreadjava16510515 231752843 eandroidruntime19782 at androidappactivitythreadhandlelaunchactivityactivitythreadjava16670515 231752843 eandroidruntime19782 at androidappactivitythreadaccess1500activitythreadjava1170515 231752843 eandroidruntime19782 at androidappactivitythreadhhandlemessageactivitythreadjava9350515 231752843 eandroidruntime19782 at androidoshandlerthispatchmessagehandlerjava990515 231752843 eandroidruntime19782 at androidoslooperlooplooperjava1300515 231752843 eandroidruntime19782 at androidappactivitythreadmainactivitythreadjava36870515 231752843 eandroidruntime19782 at javalangreflectmethodinvokenativenative method0515 231752843 eandroidruntime19782 at javalangreflectmethodinvokemethodjava5070515 231752843 eandroidruntime19782 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava8670515 231752843 eandroidruntime19782 at comandroidinternaloszygoteinitmainzygoteinitjava6250515 231752843 eandroidruntime19782 at dalviksystemnativestartmainnative method0515 231752843 eandroidruntime19782 caused by androidviewinflateexception binary xml file line 13 error inflating class fragment0515 231752843 eandroidruntime19782 at androidviewlayoutinflatercreateviewfromtaglayoutinflaterjava5870515 231752843 eandroidruntime19782 at androidviewlayoutinflaterrinflatelayoutinflaterjava6230515 231752843 eandroidruntime19782 at androidviewlayoutinflaterinflatelayoutinflaterjava4080515 231752843 eandroidruntime19782 at androidviewlayoutinflaterinflatelayoutinflaterjava3200515 231752843 eandroidruntime19782 at androidviewlayoutinflaterinflatelayoutinflaterjava2760515 231752843 eandroidruntime19782 at comandroidinternalpolicyimplphonewindowsetcontentviewphonewindowjava2160515 231752843 eandroidruntime19782 at androidappactivitysetcontentviewactivityjava16600515 231752843 eandroidruntime19782 at comexampleapphomemapviewoncreatehomemapviewjava610515 231752843 eandroidruntime19782 at androidappinstrumentationcallactivityoncreateinstrumentationjava10470515 231752843 eandroidruntime19782 at androidappactivitythreadperformlaunchactivityactivitythreadjava16150515 231752843 eandroidruntime19782 11 more0515 231752843 eandroidruntime19782 caused by androidsupportv4appfragmentinstantiationexception unable to instantiate fragment comgoogleandroidgmsmapsmapfragment make sure class name exists is public and has an empty constructor that is public0515 231752843 eandroidruntime19782 at androidsupportv4appfragmentinstantiatefragmentjava3950515 231752843 eandroidruntime19782 at androidsupportv4appfragmentinstantiatefragmentjava3630515 231752843 eandroidruntime19782 at androidsupportv4appfragmentactivityoncreateviewfragmentactivityjava2640515 231752843 eandroidruntime19782 at androidviewlayoutinflatercreateviewfromtaglayoutinflaterjava5630515 231752843 eandroidruntime19782 20 more0515 231752843 eandroidruntime19782 caused by javalangclassnotfoundexception comgoogleandroidgmsmapsmapfragment in loader dalviksystempathclassloadersystemframeworkcomgoogleandroidmapsjardataappcomexampleapp2apk0515 231752843 eandroidruntime19782 at dalviksystempathclassloaderfindclasspathclassloaderjava2400515 231752843 eandroidruntime19782 at javalangclassloaderloadclassclassloaderjava5510515 231752843 eandroidruntime19782 at javalangclassloaderloadclassclassloaderjava5110515 231752843 eandroidruntime19782 at androidsupportv4appfragmentinstantiatefragmentjava3850515 231752843 eandroidruntime19782 23 more,['android'] +473964,read wcf service endpoint address by name from webconfig here i am trying to read my service endpoint address by name from webconfigclientsection clientsection clientsectionconfigurationmanagergetsectionsystemservicemodelclientvar el clientsectionendpointssecservice i do not want to use index here as more endpoints may get added and its order may changestring addr eladdresstostringis there a way i can read end point address based on namehere is my webconfig filesystemservicemodel client endpoint addresshttpsfirstservicesvc bindingwshttpbinding bindingconfiguration1servicebinding contractabcfirstcontractname behaviorconfigurationfirstservicebehavior namefirstservice endpoint addresshttpssecservicesvc bindingwshttpbinding bindingconfiguration2servicebinding contractabcseccontractname behaviorconfigurationsecservicebehavior namesecservice endpoint addresshttpsthirdservicesvc bindingwshttpbinding bindingconfiguration3servicebinding contractabc3rdcontractname behaviorconfigurationthirdservicebehavior namethirdservice client systemservicemodelthis will work clientsectionendpoints0 but i am looking for a way to retrieve by nameie something like clientsectionendpointssecservice but it is not working,['c#'] +473977,give text of selected tab a different color using viewpagerindicator i have tried to let the sampletabsstyled demo from the viewpagerindicator change the color of the text of the currently selected tab without successhowever the sampletitlesstyledtheme demo does change its text color when switching between titlestabswhen looking inside the styles xmlresources style namecustomtitlepageindicator item nameandroidbackground18ff0item item namefootercolorffaa2item item namefooterlineheight1dpitem item namefooterindicatorheight3dpitem item namefooterindicatorstyleunderlineitem item nameandroidtextcoloraa0item item nameselectedcolorff0item item nameselectedboldtrueitem style style namecustomtabpageindicator parentwidgettabpageindicator item nameandroidbackgrounddrawablecustom tab indicatoritem item nameandroidtextappearancestylecustomtabpageindicatortextitem item nameandroidtextcolorff5item item nameandroidtextsize16spitem item nameandroiddividerdrawablecustom tab indicator divideritem item nameandroiddividerpadding10dpitem item nameandroidshowdividersmiddleitem item nameandroidpaddingleft8dpitem item nameandroidpaddingright8dpitem item nameandroidfadingedgehorizontalitem item nameandroidfadingedgelength8dpitem style style namecustomtabpageindicatortext parentandroidtextappearancemedium item nameandroidtypefacemonospaceitem style resourcesi see that the sampletitlesstyledtheme demo uses the customtitlepageindicator style which defines a selectedcolor item so perhaps naively i thought to additem nameselectedcolorff0itemto the style the sampletabsstyled demo is using customtabpageindicator but alas that did not workthe question seems obvious but i will ask anyway is there a way using the present styles xml to let the currently selected text of a tab in the sampletabsstyled demo have a different color than the other tabs if so howeditoh and i am using this in combination with actionbarsherlock in case that is important,['android'] +473986,deprecation behavior using the obsolete attribute while removing some obsolete code i came across an unexpected scenario recreated belowclass program static void mainstring args viablemethod consolewriteline softdeprecatedmethodcompiler warning harddeprecatedmethodcannot call that from here compiler error consolereadkeytrue public static void viablemethod consolewritelineviablemethod calls softdeprecatedmethod softdeprecatedmethodcompiler warning harddeprecatedmethodcannot call that from here compiler error obsoletesoft false public static void softdeprecatedmethod consolewritelinesoftdeprecatedmethod calls harddeprecatedmethod harddeprecatedmethod obsoletehard true public static void harddeprecatedmethod consolewritelineharddeprecatedmethod based in the output it seems that functions deprecated with a warning are permitted to call functions deprecated with an error and the code will execute my expectation was that i would see a compiler error complaining that the call to harddeprecatedmethod from softdeprecatedmethod is not permittedthe observed behavior seems odd to me does anyone know if this is the desired behavior and if so why or could this be a flaw in the implementation of the obsolete attribute,"['c#', '.net']" +473992,reading shared preferences i am using shared preferences for the settings menu of my android appit is working very well but i did not know how to use these settings on my codefor example how to use the selected language and use it in another activity preferencecategory androidtitlegeneral settings androidkeygeneral settings listpreference androidkeylanguage androidtitlelanguage androidsummarydefine the default language androiddefaultvaluespanish androidentriesarraylanguages androidentryvaluesarraylanguagesvalues,['android'] +474056,htmltextarea values in mvc razor view it is hard for me to clearly state the problem i am having i am trying to understand how to retain values in form fields created in a loop after validation fails i have a more complicated real world form that has a bunch of elements created in the loop and validation i have reduced it to a simple example included belowwhen validation fails i would like the textareas named comment that have been created in the loop to retain the values that are shown in the presubmit image belowwhen i debug the form submission the values from each of the fields are successfully connected to the ilist variable named comment found in the model this is what i want so i can loop through and locate them based on indexafter submitting each textarea produced by the loop shows the comma separated representation of the ilist variable comment in the model it appears that the field in the view and in the model are connecting because they share a name they connect properly on the way in but not on the way out i would like the view to only show the value associated with the commenti instead of the entire list so that the values remain constant between form submissionsscreenshots and sample code belowfirst loadpresubmit form changesform as seen after first submitform as seen after second submitmodel codeusing systemcollectionsgenericnamespace uimodelsforms public class templistmodel contentmodel public templistmodel comment new liststring public iliststring comment get set comments for each url in the list view codemodel uimodelsformstemplistmodel using htmlbeginformtemptest test new id 1 formmethodpost new id listform name listform ul for int i 0 i modelcommentcount i li div classllformlabel notes divmodelcommentidiv htmltextareacomment modelcommenti 4 63 new id comment i title comment div li ul input typesubmit valuesave changes controller codeusing systemcollectionsgenericusing systemwebmvcusing uimodelsformsnamespace uicontrollers public class testcontroller controller acceptverbshttpverbspost public actionresult temptesttemplistmodel model this function executes after the user submits the form if server side validation fails then the user should be shown the form as it was when they submitted modelcomment getcomments in my real world example this comes from a database if true modelstateisvalid in my real world code this is a validation step that may fail return viewmodel acceptverbshttpverbsget public actionresult temptestint id in the real world example there is a lot going on in this function it is used to load data from databases and set up the model to be thisplayed var model new templistmodel modelcomment getcomments return viewtemptest templayout model private static iliststring getcomments simple sample function used for demo purposes iliststring comments new liststring commentsaddcomment 1 commentsaddcomment 2 commentsaddcomment 3 return comments,"['c#', 'html']" +474093,android studio issue with android sdk on windows 7 im having a issue with the latest developer tool announced at google io 2013 android studio i have successfully installed the program and am able to launch just fine i can import exsisting projects and edit them just fine however when i attempt to click the sdk manager icon or the avd manager icon or when i attempt to create a new project i get the following error please specify android sdk now i have already gone into file other settings default project structure under platform settings sdks i have created a android sdk item with the source to my android sdk folder therefore i do not understand why android studio doesnt recognize it the only thing that im doing somewhat different is not using the included sdk folder in the actual android studio folder however when trying it it says its not a real sdk homeany ideas thanks in advance,['android'] +474114,problems importing project into android studio regarding actionbarsherlock is anyone else having problems importing a project with actionbarsherlock i have a total of 100 errors and 17 warnings this worked perfectly in eclipse i followed the steps to create a gradle build file there were no import errors until i tried to build the project i also tried redownloading abs fresh and replace into my projectwere there known issues with abs and intellij which of course android studio is now basedhere are a few errors i am seeing java workspaceactionbarsherlocksrccomactionbarsherlockappsherlockfragmentjava4 cannot find symbol symbol class fragment location package androidsupportv4app java workspaceactionbarsherlocksrccomactionbarsherlockappsherlocklistfragmentjava4 cannot find symbol symbol class listfragment location package androidsupportv4app java workspaceactionbarsherlocksrccomactionbarsherlockwidgetsuggestionsadapterjava33 package androidsupportv4widget does not existany help really appreciatededit seems there are no issues using standard intellij idea many guides online for setting it up with abs also as jake mentioned he is actually been developing the thing in intellijhere is an example guidehowever i am still unsure why its not working in android studioedit2 solution in answer below in short i downloaded abs latest version extracted deleted the old version of abs from my project then file import module to import actionbarsherlock directory into my existing project nb in my particular case i had an issue with junit compilation error and needed to delete testjunit,"['java', 'android']" +474185,uicollectionview custom uicollectionreusableview not works i am trying to use custom uicollectionreusableview which has own class and xib in my uicollectionview header but after fetching data in the place of header i have nothingmy stepsregistering class in viewdidload selfcollectionview registerclasscollectionviewheader class forsupplementaryviewofkind uicollectionelementkindsectionheader withreuseidentifierheaderviewtrying to show uicollectionreusableview collectionviewuicollectionview collectionview viewforsupplementaryelementofkindnsstring kind atindexpathnsindexpath indexpathuicollectionreusableview reusableview nilif kind uicollectionelementkindsectionheader collectionviewheader collectionheader selfcollectionview dequeuereusablesupplementaryviewofkinduicollectionelementkindsectionheader withreuseidentifierheaderview forindexpathindexpath nsinteger section indexpath section id nsfetchedresultssectioninfo sectioninfo fetchrecipes sectionssection collectionheaderheaderlabeltext blablabla reusableview collectionheaderreturn reusableviewcan anybody tell me whats wrong thanks for any advice,['ios'] +474204,how to check wifi is connected but no internet access in android i would like to know why wifi is connected but there is no internet access in android how can i check itmy code isconnectivitymanager cnconnectivitymanagergetsystemservicecontextconnectivity service networkinfo nfcngetactivenetworkinfoifnf null nfisconnected flag2false logenetwork 1 if cngetactivenetworkinfoisconnectedorconnecting logenetwork 1 else logenetwork 2 else logenetwork 2,['android'] +474209,avd for samsung galaxy s4 not working i have created an avd compatible to samsung galaxy s4here is the details for that1080 x 1920api 14 android 42but when i try to run this emulator it thisplay nothing but a blank screen seems not working at allam i missing something can any body share his experience of working with galaxy s4,"['java', 'android']" +474267,nsurl urlwithstringrelativetourl is clipping relative url i am trying to implement an ios app which uses restkit in all examples i have seen so far the following code is used to create the urlsnsurl baseurl nsurl urlwithstringnsurl relativeurl nsurl urlwithstringfilessearch relativetourlbaseurlbut then relativeurl absolutestring will return so i tried a few examplesnsurl baseurl1 nsurl urlwithstringnsurl baseurl2 nsurl urlwithstringnsurl baseurl3 nsurl urlwithstringv1 relativetourlnsurl urlwithstringnsurl relativeurl1 nsurl urlwithstringfilessearch relativetourlbaseurl1nsurl relativeurl2 nsurl urlwithstringfilessearch relativetourlbaseurl2nsurl relativeurl3 nsurl urlwithstringfilessearch relativetourlbaseurl3nsurl relativeurl4 nsurl urlwithstringfilessearch relativetourlbaseurl1nsurl relativeurl5 nsurl urlwithstringfilessearch relativetourlbaseurl2nsurl relativeurl6 nsurl urlwithstringfilessearch relativetourlbaseurl3nslog1 relativeurl1 absolutestringnslog2 relativeurl2 absolutestringnslog3 relativeurl3 absolutestringnslog4 relativeurl4 absolutestringnslog5 relativeurl5 absolutestringnslog6 relativeurl6 absolutestringand this is the output1 2 3 4 5 6 so the only example returning what i want is 4 can anyone explain why,['ios'] +474352,why does thisplayblock not stretch buttons or input elements i am trying to understand the reason behind this problemwhats the underlying reason behind button or input elements not behaving like other elements when set to thisplayblocki am not looking for workarounds to fix this problem so please do not point me to this answer because it does not answer the questionheres a jsfiddle that illustrates the problemupdate 1 pete is correct the default size attribute of an element is what sets the size even on block as you can in this fiddle the size and cols attribute of input and textarea changes their width that solves part of my questionwith that in mind my question is now why is the button element not behaving like other block elements it is a mystery to me,"['html', 'css']" +474387,delegating to the default move constructor i often find myself writing tedious move constructors for classes with many member variables they look something like the followingaa rhs astdmoverhsa bstdmoverhsb cstdmoverhsc dstdmoverhsd some extra workthat is they perform all of the actions associated with the default move constructor then peform some mundane extra task ideally i would delegate to the default move constructor then perform the extra work however the act of defining my own move constructor prevents the default implementation from being defined meaning there is nothing to delegate tois there a nice way to get around this antipattern,['c++'] +474389,typeerror objectid is not json serializable my response back from mongodb after querying an aggregated function on document using python it returns valid response and i can print it but can not return iterror typeerror objectid51948e86c25f4b1d1c0d303c is not json serializableprintresult id objectid51948e86c25f4b1d1c0d303c api calls with key 4 api calls per day 0375 api calls total 6 api calls without key 2 ok 10but when i try to returntypeerror objectid51948e86c25f4b1d1c0d303c is not json serializableit is restfull callappv1routev1analyticsdef get api analytics get handle to collections in mongodb statistics sldbstatistics objectid objectid51948e86c25f4b1d1c0d303c analytics statisticsaggregate match owner objectid project owner owner api calls with key cond eq apikey none 0 1 api calls without key cond ne apikey none 0 1 group id owner api calls with key sum api calls with key api calls without key sum api calls without key project api calls with key api calls with key api calls without key api calls without key api calls total add api calls with key api calls without key api calls per day divide add api calls with key api calls without key dayofmonth datetimenow printanalytics return analyticsdb is well connected and collection is there too and i got back valid expected result but when i try to return it gives me json error any idea how to convert the response back into joson thanks,['python'] +474403,nodejs async to sync how can i make this workvar asynctosync syncfuncfunction syncfunc var sync true var data null queryparams functionresult data result sync false whilesync return datai tried to get sync function from async one i need it to use freetds async query as sync one,['javascript'] +474427,heap dump error on centos 64bit and openjdk 7 i am trying to generate a heap dump on my machine that is running a glassfish 312 using a openjdk7 javai am using the following command jmap dumpliveformatbfiledumpt f 24935but i keep getting this error attaching to process id 24935 please waitdebugger attached successfullyserver compiler detectedjvm version is 237b01dumping heap to dumpt exception in thread main javalangreflectinvocationtargetexception at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava57 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43 at javalangreflectmethodinvokemethodjava601 at suntoolsjmapjmapruntooljmapjava197 at suntoolsjmapjmapmainjmapjava128caused by sunjvmhotspotutilitiesassertionfailure expecting gencollectedheap g1collectedheap or parallelscavengeheap but got sunjvmhotspotgc interfacecollectedheap at sunjvmhotspotutilitiesassertthatassertjava32 at sunjvmhotspotoopsobjectheapcollectliveregionsobjectheapjava605 at sunjvmhotspotoopsobjectheapiterateobjectheapjava244 at sunjvmhotspotutilitiesabstractheapgraphwriterwriteabstractheapgraphwriterjava51 at sunjvmhotspotutilitiesheaphprofbinwriterwriteheaphprofbinwriterjava416 at sunjvmhotspottoolsheapdumperrunheapdumperjava56 at sunjvmhotspottoolstoolstarttooljava221 at sunjvmhotspottoolsheapdumpermainheapdumperjava77 6 morehere is my full java version ufasoli java versionjava version 170 19openjdk runtime environment rhel2391el6 4x86 64openjdk 64bit server vm build 237b01 mixed modethe exact centos version is centos release 63 finalany ideas,['java'] +474439,make a foreground view clickthrough i do not find the way to make this workmy application has 2 framelayouts with many child views suppose imageviews for simplicity stacked one over the other my problem is i need the framelayout on top and all its children to let touches pass through them reaching the underlying framelayout and its children something like pointereventsnone in html applied to all imageviews of the top framelayouti have tried setclickablefalse and setenabledfalse both on the framelayout and its children but if i click a thisabled children for example an imageview the touch will not reach an underlying imageview that is child of the bottom framelayoutthe following code is my best attempt to thisable a framelayout and its children mslidelayout is the parent framelayout layer is each imageview children am i missing something create the layers structure into the layout void create layers context contextgetactivity mslidelayoutremoveallviews for funqlayer layermlayers if layernull view vlayerinit internalcontext mslidelayout constructs the child layer suppose it is an imageview if vnull mismutetouches vsetenabledfalse vsetclickablefalse this should obviously let touches pass through but it doesnt if mismutetouches also do the same in the framelayout itself with no luck mslidelayoutsetenabledfalse mslidelayoutsetclickablefalse,['android'] +474440,reset appearance settings for uinavigationbar back to default i have been using the fantastic uinavigationbar appearance set to set application wide appearances for my ui however i am using the skstoreproductviewcontroller and want to remove all of my styling so that it shows the default apple ui weirdly without doing anything i get a mish mash of normal ui and my custom ui which i do not really understand i have tried countering all my ui changes like this storecontrollernavigationcontrollernavigationbar setbackgroundimagenil forbarmetricsuibarmetricsdefault storecontrollernavigationcontrollernavigationbar settitletextattributes nsdictionary dictionarywithobjectsandkeys nil uitextattributetextcolor nil uitextattributetextshadowcolor nil storecontrollernavigationcontrollernavigationbar settitleverticalpositionadjustment0 forbarmetricsuibarmetricsdefault storecontrollernavigationcontrollernavigationitemleftbarbuttonitem setbackgroundverticalpositionadjustment0 forbarmetricsuibarmetricsdefaultbut that does not seem to work making no difference at all how can i set it back to the default ui settingsregards mike,"['iphone', 'ios', 'objective-c']" +474464,cs most vexing parse again taken directly from while widget w is clear for me i have no idea how can the below code be a function declaration same problem gadget and doodad are typeswidget w gadget doodad pitfall not a variable declarationhow is this possible,['c++'] +474485,remove ns2 as default namespace prefix i have a file that is printed with a default namespace the elements are printed with a prefix of ns2 i need this to be removed how it is with my codens2foo xmlnsns2httpnamespace how i want it to befoo xmlnshttpnamespace this is how i have coded it something which as i see it should be enough for the ns2 to go awayxml version10 encodingutf8xsschema xmlnsxs xmlnsbarhttpnamespace targetnamespacehttpnamespace elementformdefaultqualifiedthe generated packageinfo turns out like thisjavaxxmlbindannotationxmlschemanamespace httpnamespace elementformdefault javaxxmlbindannotationxmlnsformqualifiedpackage comfoobari create the file like thisjaxbcontext jaxbcontext jaxbcontextnewinstancegeneratedclassespackagemarshaller marshaller jaxbcontextcreatemarshallermarshallersetpropertymarshallerjaxb formatted output booleantruemarshallermarshalnew jaxbelementfoonew qnamehttpnamespace foofooclass rootfoo outputstreamgeneratedclassespackage is the package where packageinfojava and the elements arethe foo object is defined and has elements like thisxmlaccessortypexmlaccesstypefieldxmltypename proporder groupxmlrootelementname foopublic class foo xmlelementname group required true protected listgroup groupis it something i have missed or have i misunderstood how this works,['java'] +474504,javascript calculate date from week number how i can calculate the date in javascript knowing weeknumber and the year for week number 20 and year 2013 to obtain 5162013i am trying sodateprototypedayofyear function var d new datethisgetfullyear 0 0 return mathfloorenter code here this d 864e 7,['javascript'] +474543,how does mac os x determine that an application needs java i am responsible for a java application which is deployed on multiple platforms including os x with recent versions of the application we thistribute two separate bundles for os x one which uses the javaapplicationstub provided by apple and another one which includes a bundled jdk 7 and uses a launcher produced inhouse a modification of oracles javaapplauncherthe issue is with the latter bundle mac os x still insists on you having java 6 installed if you try to run the application specifically the message saysto open application you need a java se 6 runtime would you like to install one nowif you do not install java se 6 you are unable to run the application despite the fact that jdk 7 is bundled and if you do install java 6 it nevertheless runs with the bundled java 7what i am struggling to figure out is how os x decides that the application requires java i have tried renaming the java dictionary in the infoplist file and renaming the java subfolder within the resources folder without success does anyone have any ideas surely it is possible to have an application with a bundled jdk run without requiring a system jdk to be installed,['java'] +474544,shutdown application gracefully upon power loss i know the importance of using a ups to prevent immediate shutdowns of a server how do i listen for such an event in a java application say my ups will continue to run under full load for 5 minutes when the power is thiscontinued they server will continue to run but how will my application know that its time to start shutting things down properlythis particular app is mostly deals with client to database transactions i am mostly concerned with corrupted data in the case of a the server losing power immediately in the middle of mysql transactions are the points below a proper way of handling a power situationpower goes out ups battery mode app detects thisapplication somehow blocks all incoming requests any suggestions on doing this would be helpfulwithin a few minutes all transactions that were in process should be completeshutdown applicationif battery runs out server goes downwait to restoreis there a way to automatically restart the server and applications upon the power resuming or will this have to be done manually,['java'] +474596,preventdefault when a tab key is clicked inside of a textarea in chrome i know that similar questions have been asked before but the behavior i am seeing is a little different than what i have been able to find on soi have a form that i am breakingup into several jquery accordion tabs i want the user to be able to fillout a textfield under tab 1 and then keydown the tab key to automatically open tab 2 and put focus on the textfield in that tab the problem i am having is preventing the default tab keydown behavior in chromeformnew storykeydownfunction e ife var e windowevent var keycode ekeycode ewhich if keycode 9 epreventdefault alerttab was keyed i have tested this in chrome ff and safari works well in ff and safari but when a user who is using chrome keys down the tab key an actual tab is entered into the textfield prior to the event triggering i would like to stop this behavior but the tab is clearly being entered before the event even triggers is there a way to stop this,"['javascript', 'jquery']" +474597,get scrolltop while scrolling on ipadiphone i am trying to get the scrolltop value while scrolling a website on the ipadiphonewindowscrollfunction consolelogwindowscrolltopi am using this code for normal desktop browsers it even works while safari mac scrolls along bouncerubberbanddoes not know the right wording and i the console shows every pixel but on the ipad i get the value first when scrolling has stopped how can i get every scrolltop value while scrolling,"['javascript', 'jquery', 'ios']" +474644,extends in javascript can someone please help me understand this code seems too convoluted to mevar extends this extends function d b function thisconstructor d prototype bprototype dprototype new var pageview function super use strict extendsmypageview super function mypageviewrootelement viewmodelparameter calendarweeksviewmodel,['javascript'] +474656,ruby character encoding when using base64encode looking at the source of rubys base64encode i cannot determine what character encoding a string is converted to if at all before encoding that data in base64 a utf8 string encoded in base64 is going to be a lot different than a utf16 string encoded in base64 does ruby make any promises regarding this operation,['ruby'] +474680,why is make unique thisallowed assume namespace std throughoutthe c14 committee draft n3690 defines stdmake unique thusn3690 20914 unique ptr creation uniqueptrcreatetemplate class t class args unique ptrt make uniqueargs args1 remarks this function shall not participate in overload resolution unless t is not an array2 returns unique ptrtnew tstdforwardargsargstemplate class t unique ptrt make uniquesize t n3 remarks this function shall not participate in overload resolution unless t is an array of unknown bound4 returns unique ptrtnew typename remove extentypentemplate class t class args unspecified make uniqueargs delete5 remarks this function shall not participate in overload resolution unless t is an array of known boundnow this seems to me to be about as clear as mud and i think it needs more exposition but this editorial comment aside i believe i have decoded the meanings of each varianttemplate class t class args unique ptrt make uniqueargs argsyour bogstandard make unique for nonarray types presumably the remark indicates that some form of static assertion or sfinae trick is to prevent the template from being successfully instantiated when t is an array typeat a highlevel see it as the smartpointer equivalent to t ptr new targstemplate class t unique ptrt make uniquesize t na variant for array types creates a dynamicallyallocated array of n ts and returns it wrapped in a unique ptrtat a highlevel see it as the smartpointer equivalent to t ptr new tntemplate class t class args unspecified make uniqueargsthisallowed unspecified would probably be unique ptrtnwould otherwise be the smartpointer equivalent to something like the invalid tn ptr new keep the dimension please the dimension is constexpr tnfirst of all am i correct and if so whats going on with the third functionif it is there to thisallow programmers from attempting to dynamicallyallocate an array while providing constructor arguments for each element just as new int5args is impossible then that is already covered by the fact that the first function cannot be instantiated for array types is not itif it is there to prevent the addition to the language of a construct like tn ptr new tn where n is some constexpr then well why wouldnt it be completely possible for a unique ptrtn to exist that wraps a dynamicallyallocated block of n ts would this be such a bad thing to the extent that the committee has gone out of its way to thisallow its creation using make uniquewhy is make uniquetn thisallowed,['c++'] +474681,how to read custom dimension attribute from java code i made my custom component just putting few textviews together now i want to be able to init my custom control directly from code passing text sizes independently for each of of tvsmy attributes definitionresources declarestyleable namebasicgauge attr namevaluetextsize formatdimension attr nametitletextsize formatdimension attr nameunitstextsize formatdimension declarestyleableresourcessample initialization of componentplcomdigitabikecomputeruicustomviewsbasicgauge androidididbasicgauge1 androidlayout width0dp androidlayout heightwrap content androidlayout weight1 androidpadding10dp valuetextsize40spplcomdigitabikecomputeruicustomviewsbasicgaugehow i try to read those attributes in components constructorfinal int and typedarraygetindexcountfor int i 0 i n i int attribute typedarraygetindexi switch attribute case rstyleablebasicgauge valuetextsize valuetextsize typedarraygetstringattribute break case rstyleablebasicgauge titletextsize titletextsize typedarraygetstringattribute break case rstyleablebasicgauge unitstextsize unitstextsize typedarraygetstringattribute break typedarrayrecycleproblemafter creation all of my values are still null 40sp is exactly my desired value,['android'] +474691,animation duration for uicollectionview selectitematindexpathanimatedscrollposition i have tried to set the duration with the normal methods that i would try for setting the animation duration for uicollectionviews selectitematindexpathanimatedscrollposition method or the scrolltoitematindexpathatscrollpositionanimated method i have tried uiview setanimationduration and i have tried wrapping it in a catransaction i have been unsuccessful up to this point at changing that animation duration although i admit that i could have made a mistake in this logicthoughtsupdate i have tried a good number of approaches here the closest solution is to do what we would normally do for uiscrollview animation by setting the animated argument to no and wrapping it in a uiview animation block this works perfectly fine for the scrollview however this screws with the uicollectionview creation process for some reasoni have included an example below using two approaches each approach assumes that you have 4 sections with 4 items in each section in addition the animation assumes you are moving from 00 to 33using default animationpart of the issue here certainly seems tied to uicollectionview if you take the following approach using the default animation option all works fineselfcollectionview scrolltoitematindexpathnsindexpath indexpathforitem3 insection3 atscrollpositionuicollectionviewscrollpositioncenteredhorizontally animatedyeswhen this is being executed each cell inbetween the current visible cells and the destination cell is created i have included logging on the collectionviewcellforitematindexpath method20130518 093324366 defcvtesting75463c07 transitioncell created for index path nsindexpath 0x8913f40 2 indexes 0 1cell created for index path nsindexpath 0x75112e0 2 indexes 0 2cell created for index path nsindexpath 0xfe1a6c0 2 indexes 0 3cell created for index path nsindexpath 0x89159e0 2 indexes 1 0cell created for index path nsindexpath 0x8a10e70 2 indexes 1 1cell created for index path nsindexpath 0x7510d90 2 indexes 1 2cell created for index path nsindexpath 0x75112a0 2 indexes 1 3cell created for index path nsindexpath 0x8915a00 2 indexes 2 0cell created for index path nsindexpath 0x751c0 2 indexes 2 1cell created for index path nsindexpath 0xfe17f30 2 indexes 2 2cell created for index path nsindexpath 0xfe190c0 2 indexes 2 3cell created for index path nsindexpath 0xfe16920 2 indexes 3 0cell created for index path nsindexpath 0x75112a0 2 indexes 3 1cell created for index path nsindexpath 0xfe1a4f0 2 indexes 3 2cell created for index path nsindexpath 0x75142d0 2 indexes 3 3using custom animationwhen wrapping the scrolltoitematindexpath method in a uiview animation block items are not created correctly see code sample hereuiview animatewithduration50 delay00 options0 animations selfcollectionview scrolltoitematindexpathnsindexpath indexpathforitem3 insection3 atscrollpositionuicollectionviewscrollpositioncenteredhorizontally animatedno completionbool finished nslogcompletedthe currently visible cells thisappear and only the destination one is created i have included the same logging on the collectionviewcellforitematindexpath methodtransitioncell created for index path nsindexpath 0x71702f0 2 indexes 3 3completed,['iphone'] +474699,sql join on multiple columns in same tables i have 2 subqueries but i am having trouble joining columns together from the same tables i triedselect fromselect userid listid from user views tablewhere date20130515 and view typelists ajoinselect sourceid destinationidfrom actions tablewhere date20130515 and payloadtypelists user and actiontypedelete bon auserid bsourceidon alistid bdestinationidif i simply end the query with on auserid bsourceid it works but how can i also join these tables on another column also on alistid bdestinationid any help appreciated,['sql'] +474718,tesseract ocr simple example hi can you anyone give me a simple example of testing tesseract ocrpreferably in ci tried the demo found herei download the english dataset and unzipped in c drive and modified the code as followingsstring path cpicmytextjpgbitmap image new bitmappathtesseract ocr new tesseractocrsetvariabletessedit char whitelist 0123456789 if digit onlyocrinitctessdata eng false to use correct tessdatalisttessnet2word result ocrdoocrimage rectangleemptyforeach tessnet2word word in result consolewriteline0 1 wordconfidence wordtextunfortunately the code does not work the program dies at ocrinit line i could not even get an exception even using trycatchi was able to run the vietocr but that is a very large project for me to follow i need a simple example like above thanks,['c#'] +474729,android studio import error just trying out android studio i have exported my project gradle file from eclipse and imported it into android studiothe project will not build in android studio it fails with a message saying illegalstateexception unable to find gradle home directory for project nvrrclubapp unable to find gradle home directory for project nvrrclubappi have no idea what my gradle home directory should be or even where to set it i was hoping the import would have fixed that for meany ideas how to start fixing this,['android'] +474736,nltkdownload hangs on os x nltkdownload is hanging for me on os x here is what happenspython python 272 default oct 11 2012 201437 gcc 421 compatible apple clang 40 tagsappleclang418060 on darwin import nltk nltkdownloadshowing info dataafter that it completely freezesi installed everything according to the ntlk install page i am on os x 1083 on my linux box it just works with no problemsany ideas,['python'] +474750,binding custom objects list that have sublists to a grid by pivoting the sublist i would like to bind a list of coursedetails listcoursedetails to a grid xtragrid each coursedetail has a property studentlist of type liststudent the list of students should be pivoted so that the result looks like thismy questionhow can i pivot every student in the studentlist so that i can databind a listcoursedetails to the same xtragrid var courselist listcoursedetails courselistaddcd1 courselistaddcd2i have at least three problems i can not solvehow to pivot the studentlist within an instance of coursedetailshow to union two coursedetail objects cd1 cd2 or and n 130 together that for each student a seperate column is createdhow can an object like coursedetails be bound to the xtragriddemo linqpad on gista demo linqpad program can be found on gist class coursedetailsthe following class represents a course in a school public class coursedetails public int id get set public course course get set public teacher teacherget set public room roomget set public liststudent studentlistget setlist of listcoursedetailseach object in a listcoursedetails contains a list of students sometimes there are only a few students 2 to 5 in a studentlist and sometimes each studentlist has 15 to 40 students the students between coursedetails can be overlapping but they could also be thisjunct not intersecting not overlappingthe first var cd1 new coursedetails contains 3 students in the liststudentvar cd1 new coursedetails id 1 course new coursecourseid 435 coursenamec ninja teacher new teacherteacherid48 teachernamej skee room new roomroomid32 roomnamebase floor r001 studentlist new liststudent new studentid 101 studentnameamy new studentid 104 studentnamekoothrap new studentid 105 studentnamecooper the second var cd2 new coursedetails contains 2 students in the liststudent var cd2 new coursedetails id 1 course new coursecourseid 201 coursenamesql basics teacher new teacherteacherid30 teachernamem gra room new roomroomid80 roomname2th floor r100 studentlist new liststudent new studentid 101 studentnameamy new studentid 102 studentnamepenny to make it easy the screenshot use a tuplestring string but for the grid i would like to have each column the datatype of the underlying property int string date the first line starting with id course teacher amy would be the header of the grid,['c#'] +474763,navigation drawer rendering error in adt layout editor framelayout androidididcontent frame androidlayout widthmatch parent androidlayout heightmatch parent listview androidididleft drawer androidlayout width240dp androidlayout heightmatch parent androidlayout gravitystart androidbackground1 androidchoicemodesinglechoice androiddividerandroidcolortransparent androiddividerheight0dp adding that to the layout xml as per create a navigation drawer documentation produces exception raised during rendering drawerlayout must be measured with measurespecexactlyexception details are logged in window show view error logjavalangillegalargumentexception drawerlayout must be measured with measurespecexactly at androidsupportv4widgetdrawerlayoutonmeasuredrawerlayoutjava591 at androidviewviewmeasureviewjava15518 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava4825 at androidwidgetframelayoutonmeasureframelayoutjava310 at androidviewviewmeasureviewjava15518 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava4825 at androidwidgetlinearlayoutmeasurechildbeforelayoutlinearlayoutjava1404 at androidwidgetlinearlayoutmeasureverticallinearlayoutjava695 at androidwidgetlinearlayoutonmeasurelinearlayoutjava588 at androidviewviewmeasureviewjava15518 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava4825 at androidwidgetlinearlayoutmeasurechildbeforelayoutlinearlayoutjava1404 at androidwidgetlinearlayoutmeasureverticallinearlayoutjava695 at androidwidgetlinearlayoutonmeasurelinearlayoutjava588 at androidviewviewmeasureviewjava15518 at comandroidlayoutlibbridgeimplrendersessionimplmeasureviewrendersessionimpljava607 at comandroidlayoutlibbridgeimplrendersessionimplrenderrendersessionimpljava509 at comandroidlayoutlibbridgebridgecreatesessionbridgejava334 at comandroididecommonrenderinglayoutlibrarycreatesessionlayoutlibraryjava325 at comandroidideeclipseadtinternaleditorslayoutgle2renderservicecreaterendersessionrenderservicejava440 at comandroidideeclipseadtinternaleditorslayoutgle2graphicaleditorpartrenderwithbridgegraphicaleditorpartjava1545 at comandroidideeclipseadtinternaleditorslayoutgle2graphicaleditorpartrecomputelayoutgraphicaleditorpartjava1302 at comandroidideeclipseadtinternaleditorslayoutgle2graphicaleditorpartactivatedgraphicaleditorpartjava1059 at comandroidideeclipseadtinternaleditorslayoutlayouteditordelegatedelegatepagechangelayouteditordelegatejava686 at comandroidideeclipseadtinternaleditorscommoncommonxmleditorpagechangecommonxmleditorjava360 at orgeclipseuipartmultipageeditorpart2widgetselectedmultipageeditorpartjava292 at orgeclipseswtwidgetstypedlistenerhandleeventtypedlistenerjava248 at orgeclipseswtwidgetseventtablesendeventeventtablejava84 at orgeclipseswtwidgetswidgetsendeventwidgetjava1276 at orgeclipseswtwidgetswidgetsendeventwidgetjava1300 at orgeclipseswtwidgetswidgetsendeventwidgetjava1285 at orgeclipseswtwidgetswidgetnotifylistenerswidgetjava1079 at orgeclipseswtcustomctabfoldersetselectionctabfolderjava3028 at orgeclipseswtcustomctabfolderonmousectabfolderjava1749 at orgeclipseswtcustomctabfolder1handleeventctabfolderjava278 at orgeclipseswtwidgetseventtablesendeventeventtablejava84 at orgeclipseswtwidgetswidgetsendeventwidgetjava1276 at orgeclipseswtwidgetsthisplayrundeferredeventsthisplayjava3562 at orgeclipseswtwidgetsthisplayreadandthispatchthisplayjava3186 at orgeclipsee4uiinternalworkbenchswtpartrenderingengine9runpartrenderingenginejava1053 at orgeclipsecoredatabindingobservablerealmrunwithdefaultrealmjava332 at orgeclipsee4uiinternalworkbenchswtpartrenderingenginerunpartrenderingenginejava942 at orgeclipsee4uiinternalworkbenche4workbenchcreateandrunuie4workbenchjava86 at orgeclipseuiinternalworkbench5runworkbenchjava588 at orgeclipsecoredatabindingobservablerealmrunwithdefaultrealmjava332 at orgeclipseuiinternalworkbenchcreateandrunworkbenchworkbenchjava543 at orgeclipseuiplatformuicreateandrunworkbenchplatformuijava149 at orgeclipseuiinternalideapplicationideapplicationstartideapplicationjava124 at orgeclipseequinoxinternalappeclipseapphandleruneclipseapphandlejava196 at orgeclipsecoreruntimeinternaladaptoreclipseapplauncherrunapplicationeclipseapplauncherjava110 at orgeclipsecoreruntimeinternaladaptoreclipseapplauncherstarteclipseapplauncherjava79 at orgeclipsecoreruntimeadaptoreclipsestarterruneclipsestarterjava353 at orgeclipsecoreruntimeadaptoreclipsestarterruneclipsestarterjava180 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava39 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava25 at javalangreflectmethodinvokemethodjava597 at orgeclipseequinoxlaunchermaininvokeframeworkmainjava629 at orgeclipseequinoxlaunchermainbasicrunmainjava584 at orgeclipseequinoxlaunchermainrunmainjava1438 at orgeclipseequinoxlaunchermainmainmainjava1414,['android'] +474782,testing equality to nsnull below is a code block that is supposed to test to see if a dictionary is null and if it is not pull out the correct object however for some reason despite the fact that the if check fails the code still executes is there some quirk with how nsnull works that i do not understand or is this an apple bugif svcuser svcuser idnsnull null return svcuser objectforkeyaccess levelconsole response lldb print svcuser svcuser idnsnull nullbool 0 falselldb continuensnull objectforkey unrecognized selector sent to instance 0x2b51678,['objective-c'] +474789,difference between class and type being new to java i am confused between the concepts of class and typefor example should the object hello world belong to the type string or class string or maybe both,['java'] +474809,how do i change android studio editors background color i want the grey shade as shown in previews but mine has white as default i tried to search in filesettings but without much success also i could not find projectclean or any such option any help will be appreciated thanks,['android'] +474830,custom list view with custom headers android i have to make a custom list view with custom header different text in each headers and different number of items below each header i have been going through various section indexing examples but i think they are not relevant much to my answeranybody please suggest me a good means to move around such type of list view in android,['android'] +474863,noclassdeffounderror android project first of all i know there are plenty of questionsanswers about this topic i have read most of them but still getting the error0517 025706522 eandroidruntime17073 javalangnoclassdeffounderror arcomtucubondiandroidmainactivitythe project worked just fine until i updated eclipse from 21 to 22i have tried everything i could i checked the manifest cleaned the project checked my build path tried the app in different android version set java compliance level to 16 libraries too etc i just cannot figure out what the problem isheres my manifest i could not find anything wrong with itxml version10 encodingutf8manifest xmlnsandroidpackagearcomtucubondiandroidandroidversioncode1androidversionname10 usesfeature androidglesversion0x020 androidrequiredtrue usessdk androidminsdkversion8 androidtargetsdkversion17 usespermission androidnameandroidpermissioninternetusespermission androidnameandroidpermissionaccess network stateusespermission androidnameandroidpermissionwrite external storageusespermission androidnamecomgoogleandroidprovidersgsfpermissionread gservicesusespermission androidnameandroidpermissionaccess coarse locationusespermission androidnameandroidpermissionaccess fine locationpermission androidnamearcomtucubondiandroidpermissionmaps receive androidprotectionlevelsignatureusespermission androidnamearcomtucubondiandroidpermissionmaps receiveapplication androidallowbackuptrue androidicondrawableic launcher androidlabelstringapp name androidthemestylethemesherlocklightdarkactionbar androidhardwareacceleratedtrue metadataandroidnamecomgoogleandroidmapsv2api keyandroidvaluemy key activity androidnamearcomtucubondiandroidsplashscreen androidlabelstringapp name androidnohistorytrue androidscreenorientationportrait androidthemeandroidstylethemeblacknotitlebar androidwindowsoftinputmodestatehidden intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity activity androidnamearcomtucubondiandroidmainactivity androidlogodrawablelogo androidscreenorientationportrait androidwindowsoftinputmodestatehidden activity activity androidnamearcomtucubondiandroidsearchform androidlabelstringtitle activity search form androidparentactivitynamearcomtucubondiandroidmainactivity metadata androidnameandroidsupportparent activity androidvaluearcomtucubondiandroidmainactivity activityapplicationmanifestany help is welcome i will keep researching if i get the answer i will post iteditheres the mainactivity codepackage arcomtucubondiandroidimport androidannotationsuppresslintimport androidcontentintentimport androidosbundleimport androidsupportv4appdialogfragmentimport androidviewkeyeventimport androidviewviewimport androidwidgettoastimport comactionbarsherlockviewimport comgoogleandroidgmscommonconnectionresultimport comgoogleandroidgmscommongoogleplayservicesutilimport comgoogleandroidgmsmapscameraupdatefactoryimport comgoogleandroidgmsmapsgooglemapimport comgoogleandroidgmsmapssupportmapfragmentimport comgoogleandroidgmsmapsmodellatlngimport comjeremyfeinsteinslidingmenulibslidingmenuimport comjeremyfeinsteinslidingmenulibslidingmenuoncloselistenerimport comjeremyfeinsteinslidingmenulibslidingmenuonopenlistenerimport comjeremyfeinsteinslidingmenulibappslidingfragmentactivitysuppresslintnewapipublic class mainactivity extends slidingfragmentactivity private slidingmenu menuprivate toast toastprivate long lastbackpresstime 0private googlemap mapoverridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main slidemenu setbehindcontentviewrlayoutmenu setslidingactionbarenabledfalse menu getslidingmenu menusettouchmodeaboveslidingmenutouchmode fullscreen menusetshadowwidthresrdimenshadow width menusetshadowdrawablerdrawableshadow menusetbehindoffset100 menusetfadedegree035f menusetslidingenabledfalse menusetoncloselistenernew oncloselistener override public void onclose menusetslidingenabledfalse menusetonopenlistenernew onopenlistener override public void onopen menusetslidingenabledtrue getsupportactionbarsetthisplayshowcustomenabledtrue getsupportactionbarsetthisplayhomeasupenabledfalse slide menu map supportmapfragment getsupportfragmentmanager findfragmentbyidridmapgetmap getting google play availability status int status googleplayservicesutil isgoogleplayservicesavailablegetbasecontext if status connectionresultsuccess toastmaketextthis google maps no esta thisponible toastlength longshow else para centrar el mapa en tucuman mapmovecameracameraupdatefactorynewlatlngzoomnew latlng 268175915814614 65274105834958 13 enabling mylocation layer of google map mapsetmylocationenabledtrue overridepublic boolean oncreateoptionsmenumenu menu inflate the menu this adds items to the action bar if it is present getsupportmenuinflaterinflatermenumain menu return truepublic boolean onoptionsitemselectedmenuitem item switch itemgetitemid case androidridhome toggle return true case ridaction search final int result 1 startactivityforresultnew intentmainactivitythis searchformclass result return true case ridaction lineas showdialoglineas return true case ridaction acercade showdialogacercade return true return superonoptionsitemselecteditemoverridepublic boolean onkeydownint keycode keyevent event if keycode keyeventkeycode back menuismenushowing if thislastbackpresstime systemcurrenttimemillis 40 toast toastmaketextthis presione atras nuevamente para cerrar toastlength long toastshow thislastbackpresstime systemcurrenttimemillis else if toast null toastcancel superonbackpressed return true return superonkeydownkeycode eventpublic void onresultadosclickedview view showmenupublic void showdialoglineas dialogfragment dialog new lineasdialog dialogshowgetsupportfragmentmanager lineaspublic void showdialogacercade dialogfragment dialog new acercadedialog dialogshowgetsupportfragmentmanager acerca,['android'] +474898,delaunay triangulation opencv c i made a delaunay triangulation with opencv thanks to this code example code in partiluclar draw subdivhowever when i want to thisplay the triangulation i get the mesh and lines who do not belong to triangulationthis lines are due to the fact that the triangulation algorithm starts its job considering triangles posted at infinitycan you explain me how to draw only the mesh into the convex hull please without this lines thisplay function void draw subdivmat img subdiv2d subdiv scalar delaunay color vectorvec6f trianglelist subdivgettrianglelisttrianglelist vectorpoint pt3 forsize t i 0 i trianglelistsize i vec6f t trianglelisti pt0 pointcvroundt0 cvroundt1 pt1 pointcvroundt2 cvroundt3 pt2 pointcvroundt4 cvroundt5 lineimg pt0 pt1 delaunay color 1 lineimg pt1 pt2 delaunay color 1 lineimg pt2 pt0 delaunay color 1 main function mat image imreadargv1 1 creat delaunay scalar delaunay color255 255 255 point color00255 rect rect00imagecols imagerows subdiv2d subdivrect forint i 0 i pointgetdim i point2f fppointgetcoordireal pointgetcoordiimag subdivinsertfp draw subdivimage subdiv delaunay color imwritedatadelaunayjpg imageresult,['c++'] +474906,how perform click operation on marker custom info window on google map v2 in android i am implementing google map v2 in my appi have added custom info window to markerthere are three images canceldelete editonclick cancel image window hidedelete data delete on edit dialog open for editingmy problem is how perform click operation on on these images,['android'] +474910,embedded chromium or webkit in android app for our android app we would like to embed our own browserrendering engine the most likely candidate for this is webkitchromium we are looking for something similar to webview essentially but backed by a browser version that we controlbackgroundsignificant parts of our app consist of web page fragments embedded in the view served by the app itself we try to do this as transparently as possible from a visualuser experience standpoint so far we have been using webview for this and that works for the most part except when it does not some phone vendors have unfortunately decided to tweak the standard android browser here and there in some cases this breaks our app or makes the fact the we embed a web page more noticeableour ideawed like to have a component similar to webview but where we control what version of webkitchromium or some other rendering engine is being used it wouldnt necessarily have to be the latest and greatest version it is more important that we can get our app to work consistently across as many android devices as possibleso farour research so far has not turned up anything useful we have found three dead attempts to port webkit to ndk the bare webkit for android port uses functionality not available in the ndk and thus not to app developerswebkit android port by company 100 no updates for over two yearsmogobrowser their last revision was to delete all source codendk webkit officially abandoned by its authorlooking on stackoverflow we have also found a number of similar questions most of which being solved by pointing to webview we already do that and it is not good enoughwebkit component for androidembed basic webkit v8 in my appembedding a newer version of webkit with android appwe are currently investigating whether chromium for android or parts of it can be turned into a library that our app could use has anyone else done thisupdateafter having a look at the chromeview project on github accepted answer we decided that wed rather wait for google to release a chromebased webview on future android devices the chromium rendering engine turns out to be fairly large 40mb which does not leave much space for the actual app,['android'] +474914,wpf program launches super fast on one computer but super slow on another my wpf program has a strange problem regarding the startup performance on different computer with same specs one computer loads my program less than a second another computer with the same spec loads 10 secswith the help of visualstudio performance profiler i notice that two computers loads the program differently which is so strange my problem is basically the same as this postc wpf very slow application launchthe performance profiler on the fast computeri mean start the program fast shows that the program starts with systemwindowsapplicationrunwhereas the slow one shows that it starts with systemwindowsapplicationruninternalwith the additional internal the boots time increased 10 times even though two computers are of the same spec and the source code are the same actually it is just plain mvvm light wpf start fileany ideas,"['c#', '.net']" +474950,google play developer console beta test paid apps for free i have uploaded an apk as a beta version beta testing section in google play developer console and i would like to let my users to test it final version will be paid and you cannot change this choice after testing so i had to set it as paid at the beginning the problem is i do not want to charge my users for testing and it seems there is no way to do so is there,['android'] +474961,interface android robotium testing with teamcity as this was not answered maybe did i not find it previously i investigated on the following question how to perform automated functional tests on android devices with robotium and report them to continuous integration server like teamcity,['android'] +475014,nsnull length unrecognized selector sent to json objects i am developing an ios 50 app with latest sdki get a very strange error with this code nsmutableurlrequestsetuprequestwithservicensstringservice andmethodnsstringmethod nsstring url nsstring stringwithformatsvc serverurl service method nsmutableurlrequest request nsmutableurlrequest alloc initwithurlnsurl urlwithstringurl set authentication token nslog authenticationtoken if authenticationtoken nil nslognull authtoken if authenticationtoken isequalnsnull null nslognsnull authtoken if request nil nslognull request request addvalueauthenticationtoken forhttpheaderfieldrequest header auth token return requestthis is my log nullnsnull authtokennsnull length unrecognized selector sent to instance 0x3b5a5090 terminating app due to uncaught exception nsinvalidargumentexception reason nsnull length unrecognized selector sent to instance 0x3b5a5090it seems that authenticationtoken is null but i do not understand that if authenticationtoken is null why i do not see null authtoken on the logi get this error the second time i run that method the first time i do not get any error this is my log nullnull authtokenby the waynsstring authenticationtokenany advicemaybe there is a memory leak somewhere,['ios'] +475017,flexslider animation slide animationloop true conflict i have an issue with flexslider 2 under some specific circumstances i am using it as a content slider what i need is to have the animation slide rather than fade and loop the slides i have 3 slides with div content and more lists inside them to show a gallery type setup the issue i am running into is that when i set the options i need the slider shows the last slide first then slides on to slide 2 then 3 then 1 it would not show the first slide as the first slide the startat parameter has no effecteverything works perfectly when i set the slider to use the followingflexsliderflexslider animation slide animationloop falseit also works if i set it toflexsliderflexslider animation fade animationloop truebut if i set animation to slide and loop to true it shows the last slide first again and would not show the slides in the correct order is there anything i can do about this seems to be a conflict between animation slide and loopingi need the following code to work but it does notflexsliderflexslider animation slide animationloop truenot getting any console errors any ideas,['jquery'] +475084,classnotfoundexception after adt update i have recently updated android sdk eclipse adt plugin to latest version now when i try to run a preexisting android project the logcat shows a classnotfoundexceptioni tried to create a new device but the problem still existsmanifestxml version10 encodingutf8manifest xmlnsandroidpackagecomexamplemyappandroidversioncode1androidversionname10 usessdk androidminsdkversion8 androidtargetsdkversion17 usespermission androidnameandroidpermissioninternet usespermission androidnameandroidpermissionwrite external storage usespermission androidnameandroidpermissionaccess network state application androidallowbackuptrue androidicondrawableic launcher androidlabelstringapp name androidthemestyleapptheme activity androidnamecomexamplemyappmainactivity androidlabelstringapp name androidwindowsoftinputmodestatehidden intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activityapplicationlogcat0517 130956357 eandroidruntime969 fatal exception main0517 130956357 eandroidruntime969 javalangruntimeexception unable to instantiate activity componentinfocomexamplemyappcomexamplemyappmainactivity javalangclassnotfoundexception did not find class comexamplemyappmainactivity on path dataappcomexamplemyapp1apk0517 130956357 eandroidruntime969 at androidappactivitythreadperformlaunchactivityactivitythreadjava21060517 130956357 eandroidruntime969 at androidappactivitythreadhandlelaunchactivityactivitythreadjava22300517 130956357 eandroidruntime969 at androidappactivitythreadaccess600activitythreadjava1410517 130956357 eandroidruntime969 at androidappactivitythreadhhandlemessageactivitythreadjava12340517 130956357 eandroidruntime969 at androidoshandlerthispatchmessagehandlerjava990517 130956357 eandroidruntime969 at androidoslooperlooplooperjava1370517 130956357 eandroidruntime969 at androidappactivitythreadmainactivitythreadjava50410517 130956357 eandroidruntime969 at javalangreflectmethodinvokenativenative method0517 130956357 eandroidruntime969 at javalangreflectmethodinvokemethodjava5110517 130956357 eandroidruntime969 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava7930517 130956357 eandroidruntime969 at comandroidinternaloszygoteinitmainzygoteinitjava5600517 130956357 eandroidruntime969 at dalviksystemnativestartmainnative method0517 130956357 eandroidruntime969 caused by javalangclassnotfoundexception did not find class comexamplemyappmainactivity on path dataappcomexamplemyapp1apk0517 130956357 eandroidruntime969 at dalviksystembasedexclassloaderfindclassbasedexclassloaderjava650517 130956357 eandroidruntime969 at javalangclassloaderloadclassclassloaderjava5010517 130956357 eandroidruntime969 at javalangclassloaderloadclassclassloaderjava4610517 130956357 eandroidruntime969 at androidappinstrumentationnewactivityinstrumentationjava10540517 130956357 eandroidruntime969 at androidappactivitythreadperformlaunchactivityactivitythreadjava20970517 130956357 eandroidruntime969 11 morei noticed that the new apk file is called myapp1apk while it was usually called myappapkcan someone tell me how to fix,['android'] +475124,is it possible to make razor sections optional if i have a page withbody section somestuff spanthis is a section i just adderedspan bodyis it possible for the layout to not render this section or is that contrary to how this should work conceptually seems like it would be useful to be able to not render certain sections on a page unless i am thinking about this incorrectlyeditincluding the error message may be helpful when i put a section into the main page the layout page fails with the following sections have been defined but have not been rendered for the layout page viewslayouts layout1cshtml somestuff as if it is forcing me to render every section on the page or somethingin otherwords in layoutcshtml i do not call rendersection but in indexhtml i have a section called somestuff defined is that legal seems like it is forcing me to render all sections in the page but that seems like sections should be optional no,['c#'] +475150,how to tell whether the forward or backward button was pressed using the popstate event i have been doing some research and it appears that the popstate event fires any time that the history is changed but there does not seem to be a built in way to determine whether the user clicked the back button or the forward button in the browsermy use case is that when going back in the history or forward in the history i have directional animations that occur when transitioning routes in an ajax application i need to determine if the user is going backwards or forwards so the animations make sense it is a shame that the popstate event does not support the direction of the eventi will also mention that my application is an angularjs application in case there is a angular specific answer although a more general purpose javascript solution would be optimal,['javascript'] +475173,sizing a textarea with css vs with cols and rows whats the difference between sizing a textarea with cols and rows and sizing a textarea with height and widthtextarea idtextarea1 cols73 rows12with cols rowstextareatextarea idtextarea2 styleheight200px width600pxwith csstextareajsfiddle,['html'] +475179,laravel 4 how insert raw html to label is there some easy way how put raw html tag to label i have this formlabelfirstname first name emem arrayclass input tag and it produceslabel classinput tag forfirstnamefirst name ltemgtltemgtlabelbut tag em is not interpreted as it should be what i want islabel classinput tag forfirstnamefirst name ememlabel,['html'] +475229,eclipse declare variable based on return or get shortcut i am not sure how to phrase this in a search however i was curious if there is a shortcut in eclipse to allow us to declare a variable type based on whats after the equalfor examplefirstname usergetfirstname the minute you press enter it would add string to the beginning of the line so it becomesstring firstname usergetfirstnameor even a shortcut key would sufficethere are times when a class name might be long or something like iteratorentrystring string which is long enough that a shortcut or auto add would be handyi am not sure if this exists thoughthanks guys,['java'] +475236,is volatile read happensbefore volatile write i try to understand why this example is a correctly synchronized programa volatilethread1xathread2a5because there are conflicting accesses there is a write to and read of a so in every sequential consistency execution must be happensbefore relation between that accessessuppose one of sequential execution1 xa2 a5is 1 happensbefore 2 why,['java'] +475265,saving wav file recorded in chrome to server i have seen many partial answers to this here and elsewhere but i am very much a novice coder and am hoping for a thorough solution i have been able to set up recording audio from a laptop mic in chrome canary v 29x and can using recorderjs relatively easily set up recording a wav file and saving that locally a labut i need to be able to save the file onto a linux server i have running it is the actual sending of the blob recorded data to the server and saving it out as a wav file that is catching me up i do not have the requisite php andor ajax knowledge about how to save the blob to a url and to deal as i have been given to understand with binaries on linux that make saving that wav file challenging indeed i would greatly welcome any pointers in the right direction,"['php', 'javascript']" +475272,form submit with ajax passing form data to php without page refresh can anyone tell me why this bit of code is not workinghtml head script srcscript script function formbindsubmit function ajax type post url postphp data formserialize success function alertform was submitted return false script head body form input nametime value0br input namedate value0br input namesubmit typebutton valuesubmit form bodyhtmlwhen i push submit nothing happens in the receiving php file i am using posttime and postdate to put the data in a mysql query but it is just not getting the data any suggestions i am assuming it is something to do with the submit button but i cannot figure it out,"['php', 'jquery']" +475277,complete wix sample wxs to download and install a specific version of net framework if it is not available there are many incomplete questions and answers about how to download and install net frameworks if they are not available but none complete code seems to be available on internetcan you provide a minimal compilable code or a link to a clear example that generates a setupexemsi i do not think rtfm applies to this question since msi and bootstrap installers has a lot of idiosyncrasies that are not easily deductible,['.net'] +475283,thread behaving strangely in junit i am trying to write a unit test that requires mulitple threads however it seems that the threads just stop part way through execution consider the following codepublic class test orgjunittest public void testthreads new threadnew runnable public void run for int i 1 i 10 i systemoutprintlni start if i run this unit test it will generally stop thisplaying output somewhere between 140180 if i convert this code into a regular class and run it it works fine does anybody have any idea what i am missing herethanks andrew,['java'] +475332,how to use machinekeyprotect for a cookie i want to encrypt the id that i am using in a cookie i am using aspnet 45 so i want to use machinekeyprotect to do it code public static string protectstring text string purpose if stringisnulloremptytext return stringempty byte stream encodingunicodegetbytestext byte encodedvalue machinekeyprotectstream purpose return httpserverutilityurltokenencodeencodedvalue public static string unprotectstring text string purpose if stringisnulloremptytext return stringempty byte stream httpserverutilityurltokendecodetext byte decodedvalue machinekeyunprotectstream purpose return httpserverutilityurltokenencodedecodedvalue when i use the following test dataprotectinput 775119337output cookie hyv7shlrb61cm9hwohl2lujtgmlmxln60q27xwl7ae1wpv31p7sjqfrdd8tmosr8n8ppn1k7k7lsrjqwh6ap17oblk3mapsdqrqla8xj9a1unprotectoutput nwa3aduamqaxadkamwazadca0 the output is not correct of course it should be the original id i inputhow do i get decrypt the cookie using machinekeyunprotect,['c#'] +475339,google play alpha app bmpph01 error i have an app that i am making and have uploaded to the google play through my console and would like some people to test iti have created a google group and also added a different account for myself but get the following errorbmpph01has anyone else seen or know what this means,['android'] +475348,how to specify application data package in xcode schemes i would like to specify an application data package using xcode schemes so that i can customize and deploy to the device during testing however by default the scheme option application data combo box has no items in it i guess i would need to create the package and add it to my xcodeproj but i cannot find any documentation about this not even in the bulky book xcode4 unleashed i also tried to build for archive first but after that still no data under the option page,['ios'] +475373,cannot resolve symbol googlecloudmessaging gcm i am trying to get gcm working in my app to notify users when our hours change or when we have any promos going on but i keep getting the error cannot resolve symbol googlecloudmessaging when trying to use the google cloud messaging apii am using the newly released android studio ide to code thishere is my gcmbroadcastrecieverjava code import androidrimport androidappactivityimport androidappnotificationmanagerimport androidapendingintentimport androidcontentbroadcastreceiverimport androidcontentcontextimport androidcontentintentimport androidwidgettoastpublic class gcmbroadcastreceiver extends broadcastreceiver static final string tag gcmdemo public static final int notification id 1 private notificationmanager mnotificationmanager context ctx googlecloudmessaging gcm i get the error here override public void onreceivecontext context intent intent googlecloudmessaging gcm googlecloudmessaginggetinstancecontext error ctx context string messagetype gcmgetmessagetypeintent cannot resolve method here if googlecloudmessagingmessage type send errorequalsmessagetype error sendnotificationsend error intentgetextrastostring else if googlecloudmessagingmessage type deletedequalsmessagetype error sendnotificationdeleted messages on server intentgetextrastostring else sendnotificationreceived intentgetextrastostring setresultcodeactivityresult ok put the gcm message into a notification and post it private void sendnotificationstring msg mnotificationmanager notificationmanager ctxgetsystemservicecontextnotification service pendingintent contentintent pendingintentgetactivityctx 0 new intentctx activityclass 0 toastmaketextctx msg toastlength shortshow,"['java', 'android']" +475398,cannot wire to subview in ib quick question using ib i have a subview in a viewcontroller in that subview i have a label which i would like to wire to my custom subview class however ib will not let me what am i missing i also tried to add the label programmatically however it appears that the frame was not ever set i could hard code the size of the label but i could not make it dependent on the frame size of my subview because the frame and the bounds were always zero rects even after the view showed up in my view controller at a non zero size any ideas here would also be much appreciated,"['ios', 'objective-c']" +475410,tagging query with group concat using the database schema for tagging from this questions accepted answer is it possible to have a query using group concat that works with a large amount of data i need to get items with their tags for all items tagged with tag x using a query with group concat having 5 million tags is very slow at 15 seconds without group concat items without tags it is 005 secondsas a side question how does so solve this problem,['mysql'] +475430,how to know the indexpathrow on button click of tableview cell in a uitableview i created a tableview having a custom uitableviewcell a button is associated with each row of tableview now i want to know the row number on click of a button so that i would know that of which row button has been clicked i have given a try to few things found on stack but nothing is workingi have tried this code voidbutton1tappedidsenderuibutton senderbutton uibutton senderuitableviewcell buttoncell uitableviewcell senderbutton superviewuitableview table uitableview buttoncell superviewnsindexpath pathofthecell table indexpathforcellbuttoncellnsinteger rowofthecell pathofthecell rownslogrowofthecell d rowofthecellbut this is also not workingthanks for helping me out,"['iphone', 'ios']" +475443,wrapping div is not resized when inner image scales a result of window resize i want my images to resize as the window height changes while keeping the containing div shrink wrapping the image i tried usingdiv img src altdivhtml body height 100 width 100div height 90 backgroundcolor black thisplay inlineblockimg height 100 width autobut it does not seem to work as expected the div does not shrink it actually does once i play around with the css properties in debuggerhere is the fiddle try resizing the result panelupdatenow this is strange since i first posted this question the browser behaviour changed originally chrome when i resized the window the image would shrink proportionally as expected but the wrapping div would keep its original width what happens now chrome update is that the image does not shrink horizontally and the div alsoi tried it with the latest safari and firefox both shrink the image but keep original div width so please be kind to check your solutions on other browsers as wellupdate 2the div has to stay of block type as i need to place other elements in the corners of the image,"['html', 'css']" +475459,cannot create app engine connected android project in eclipse creation of element failed i am not able to create an app engine connected android project by wizard in eclipse anymore when i click the finish button the following error message appearscreation of element failedcomandroidideeclipseadtinternalprojectandroidnaturesetupprojectnatureslorgeclipsecoreresourcesiprojectlorgeclipsecoreruntimeiprogressmonitorvi use windows 7 x64eclipse juno 42jre7google app engine sdk 180 android sdk api 8 and 17it is a fresh installation before new install of eclipse it worked i have also inserted correct values for project number and api keythe wizard only creates one file named project with following contentxml version10 encodingutf8projectdescription nametestname commentcomment projects projects buildspec buildspec natures naturesprojectdescriptionexception stack tracejavalangreflectinvocationtargetexception at orgeclipsejfaceoperationmodalcontextrunmodalcontextjava421 at orgeclipsejfacewizardwizarddialogrunwizarddialogjava1028 at orgeclipsejdtinternaluiwizardsnewelementwizardperformfinishnewelementwizardjava134 at comgooglegdteclipsemobileandroidwizardsnewandroidcloudprojectwizardperformfinishnewandroidcloudprojectwizardjava1 at orgeclipsejfacewizardwizarddialogfinishpressedwizarddialogjava827 at orgeclipsejfacewizardwizarddialogbuttonpressedwizarddialogjava432 at orgeclipsejfacedialogsdialog2widgetselecteddialogjava624 at orgeclipseswtwidgetstypedlistenerhandleeventtypedlistenerjava248 at orgeclipseswtwidgetseventtablesendeventeventtablejava84 at orgeclipseswtwidgetswidgetsendeventwidgetjava1053 at orgeclipseswtwidgetsthisplayrundeferredeventsthisplayjava4169 at orgeclipseswtwidgetsthisplayreadandthispatchthisplayjava3758 at orgeclipsejfacewindowwindowruneventloopwindowjava825 at orgeclipsejfacewindowwindowopenwindowjava801 at orgeclipseuiinternalhandlerswizardhandlernewexecutehandlerwizardhandlerjava259 at orgeclipseuiinternalhandlerswizardhandlerexecutewizardhandlerjava279 at orgeclipseuiinternalhandlershandlerproxyexecutehandlerproxyjava290 at orgeclipseuiinternalhandlerse4handlerproxyexecutee4handlerproxyjava76 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokeunknown source at sunreflectdelegatingmethodaccessorimplinvokeunknown source at javalangreflectmethodinvokeunknown source at orgeclipsee4coreinternaldimethodrequestorexecutemethodrequestorjava56 at orgeclipsee4coreinternaldiinjectorimplinvokeusingclassinjectorimpljava231 at orgeclipsee4coreinternaldiinjectorimplinvokeinjectorimpljava212 at orgeclipsee4corecontextscontextinjectionfactoryinvokecontextinjectionfactoryjava131 at orgeclipsee4corecommandsinternalhandlerserviceimplexecutehandlerhandlerserviceimpljava171 at orgeclipseuiinternalhandlerslegacyhandlerserviceexecutecommandlegacyhandlerservicejava515 at orgeclipseuiinternalactionscommandactionrunwitheventcommandactionjava157 at orgeclipsejfaceactionactioncontributionitemhandlewidgetselectionactioncontributionitemjava584 at orgeclipsejfaceactionactioncontributionitemaccess2actioncontributionitemjava501 at orgeclipsejfaceactionactioncontributionitem5handleeventactioncontributionitemjava411 at orgeclipseswtwidgetseventtablesendeventeventtablejava84 at orgeclipseswtwidgetswidgetsendeventwidgetjava1053 at orgeclipseswtwidgetsthisplayrundeferredeventsthisplayjava4169 at orgeclipseswtwidgetsthisplayreadandthispatchthisplayjava3758 at orgeclipsee4uiinternalworkbenchswtpartrenderingengine9runpartrenderingenginejava1053 at orgeclipsecoredatabindingobservablerealmrunwithdefaultrealmjava332 at orgeclipsee4uiinternalworkbenchswtpartrenderingenginerunpartrenderingenginejava942 at orgeclipsee4uiinternalworkbenche4workbenchcreateandrunuie4workbenchjava86 at orgeclipseuiinternalworkbench5runworkbenchjava588 at orgeclipsecoredatabindingobservablerealmrunwithdefaultrealmjava332 at orgeclipseuiinternalworkbenchcreateandrunworkbenchworkbenchjava543 at orgeclipseuiplatformuicreateandrunworkbenchplatformuijava149 at orgeclipseuiinternalideapplicationideapplicationstartideapplicationjava124 at orgeclipseequinoxinternalappeclipseapphandleruneclipseapphandlejava196 at orgeclipsecoreruntimeinternaladaptoreclipseapplauncherrunapplicationeclipseapplauncherjava110 at orgeclipsecoreruntimeinternaladaptoreclipseapplauncherstarteclipseapplauncherjava79 at orgeclipsecoreruntimeadaptoreclipsestarterruneclipsestarterjava353 at orgeclipsecoreruntimeadaptoreclipsestarterruneclipsestarterjava180 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokeunknown source at sunreflectdelegatingmethodaccessorimplinvokeunknown source at javalangreflectmethodinvokeunknown source at orgeclipseequinoxlaunchermaininvokeframeworkmainjava629 at orgeclipseequinoxlaunchermainbasicrunmainjava584 at orgeclipseequinoxlaunchermainrunmainjava1438 at orgeclipseequinoxlaunchermainmainmainjava1414caused by javalangnosuchmethoderror comandroidideeclipseadtinternalprojectandroidnaturesetupprojectnatureslorgeclipsecoreresourcesiprojectlorgeclipsecoreruntimeiprogressmonitorv at comgooglegdteclipsemobileandroidwizardshelpersandroidprojectcreatorcreateandroidprojectcreatorjava121 at comgooglegdteclipsemobileandroidwizardsnewandroidcloudprojectwizardfinishpagenewandroidcloudprojectwizardjava170 at orgeclipsejdtinternaluiwizardsnewelementwizard2runnewelementwizardjava118 at orgeclipsejdtinternalcorebatchoperationexecuteoperationbatchoperationjava39 at orgeclipsejdtinternalcorejavamodeloperationrunjavamodeloperationjava728 at orgeclipsecoreinternalresourcesworkspacerunworkspacejava2344 at orgeclipsejdtcorejavacorerunjavacorejava5204 at orgeclipsejdtinternaluiactionsworkbenchrunnableadapterrunworkbenchrunnableadapterjava106 at orgeclipsejfaceoperationmodalcontextmodalcontextthreadrunmodalcontextjava121root exceptionjavalangnosuchmethoderror comandroidideeclipseadtinternalprojectandroidnaturesetupprojectnatureslorgeclipsecoreresourcesiprojectlorgeclipsecoreruntimeiprogressmonitorv at comgooglegdteclipsemobileandroidwizardshelpersandroidprojectcreatorcreateandroidprojectcreatorjava121 at comgooglegdteclipsemobileandroidwizardsnewandroidcloudprojectwizardfinishpagenewandroidcloudprojectwizardjava170 at orgeclipsejdtinternaluiwizardsnewelementwizard2runnewelementwizardjava118 at orgeclipsejdtinternalcorebatchoperationexecuteoperationbatchoperationjava39 at orgeclipsejdtinternalcorejavamodeloperationrunjavamodeloperationjava728 at orgeclipsecoreinternalresourcesworkspacerunworkspacejava2344 at orgeclipsejdtcorejavacorerunjavacorejava5204 at orgeclipsejdtinternaluiactionsworkbenchrunnableadapterrunworkbenchrunnableadapterjava106 at orgeclipsejfaceoperationmodalcontextmodalcontextthreadrunmodalcontextjava121session dataeclipsebuildidm201302041200javaversion170javavendororacle corporationbootloader constants oswin32 archx86 64 wswin32 nlde deframework arguments product orgeclipseepackagejeeproductcommandline arguments os win32 ws win32 arch x86 64 product orgeclipseepackagejeeproduct,['android'] +475462,how do i add a library project to the android studio and use itsome asked dontt take effect how do i add a library project to the android studio and use itsome asked question dontt take effecti try to found answer on how do i add a library project to the android studio or how to import relative project with the android studioi14not jari14 but it does not workit also says error retrieving parent for item no resource found that matches the given name themesherlocklight etcmy sdk tools rev is 22,['android'] +475494,borderradius does not work on ie10 i need to have a container div with rounded corners the following code works perfectly on all browsers except my ie10 i have no clue how to do in order to make it workaboutkader width 200px height 180px float left margin 0px auto backgroundcolor 9bafc4 padding 3px borderradius 5px mozborderradius 5px webkitborderradius 5px khtmlborderradius 5px msborderradius 5px behavior urlborderradiushtcand heres the html part pleasediv idaboutkaderdivthere is no way to make any round corner visible on ie10 the version i have is 100920016576 update versions 1005 kb289530,['css'] +475500,enhanced for loop exception created the below code whilst playing with loops the code below stores the fibonacci values into an array and then prints them using for loops int numbers numbers new int25 numbers0 1 numbers1 1 systemoutprintlninitializing the array values forint i 2 i numberslength i numbersi numbersi1 numbersi2 systemoutprintlnprinting out fibonacci values forint i 0 i numberslength i systemoutprintnumbersi the above code works fine the first time i threw it together though i used an enhanced for loop to print out the values the second for loop in the code this compiles fine but when i run it i get the followinginitializing the array valuesprinting out fibonacci values1 1 2 3 8 34 377 17711 exception in thread main javalangarrayindexoutofboundsexception 34at arraydemomainarraydemojava21i do not get what went wrong changing the second loop should not change the values youll notice the fibonacci values are wrong ie missing values and i do not get why a simple enhanced for loop would skip indexes now this is not really a big deal because this is not for a project or anything it just bugs me that i cannot figure out why it is doing it any clues the enhanced for loop just looked like thisforint i numbers systemoutprintnumbersi,['java'] +475560,how to see preview of xml in android studio i installed android studio and when i open an xml file i cant preview it or see pallete if i go to viewtool windows palette it wont show againi want to see preview of xml file like in eclipse,['android'] +475562,detect whether the mouse is touching the ground or if it is in the air my sister and me are writing a program to help people that suffer from tremor trembling in handsthe program recognizes if the mouse cursor is getting slower and then makes the cursor easier controllable and slower to make using a mouse with trembling hands easierthe program works so far and there is only one problem if the user lifts the mouse to another position the speed is 0 for a short span of time the program assumes that the cursor has to be slowed down but this should not happenis there any way to detect whether the mouse is touching the mouse padgroundwe are programming in c,"['c#', '.net']" +475610,can android studio be used to run standard java projects for those times when you want to isolate the java and give it a quick testcan you run nonandroid java projects in android studio as in eclipse,"['java', 'android']" +475617,how is the line and file constants implemented in ruby it seems the file and line constants are dynamically updated with the current file and line numbers under execution i am wondering how is the behaviour implemented in rubyi have greped the source code but there are too many noises for line and file appearance i am wonder anyone could help me point to the source code and provide a clue to understand its behaviour explanation in either rubinis or mri will be fine,['ruby'] +475628,wkhtmltopdf not loading local css and images i have seen multiple questions that are very similar to this one so i was hesitant at first to post it but nothing suggested resolved my issue and i cannot seem to figure out whats wrong myselffor a project i made for one client they wanted to ability to convert quotes for their customers generated using an online form to pdfs simple enough as the entire project was in php i used the following simple procesave the quote as a temporary html fileuse wkhtmltopdf to convert the html file to a pdfoutput this pdf fileclean up delete temporary filesthis worked until they changed servers the new server has a firewallat first the pdf conversion step was returning a firewall page saying that the server could not make outbound connections to resolve this i fed the html file directly instead of linking to it varwmysitetemp18382html instead of wmysitecomtemp18382html this converted the html but the firewall prevented the loading of css and imagesi can overcome the css by simply embedding it directly in the site instead of linking to it using the style tags but this does not work for imagesi tried using relative links first i changed img src to img srcimagejpg this did not worknext i tried img srcfilevarwmysitetempimagejpg but this did not work eitheri read around and look through the wkhtmltopdf manual and i tried several different command line arguments like enablelocalfileaccess enable varwmysitetemp and images but nothing seems to fix it,"['php', 'html']" +475645,angularjs and ngswitchwhen emulating enum i wanted to introduce some enum to my controller logic for some type safety so for example i created something like thisvar app angularmodulemyapp var stateenum objectfreezelogin1 logout2function logincheckctrlscope scopestateenum stateenum scopelogindata stateenumlogin scopelogin function consolelogscopelogindata logged in not logged in scopelogindata stateenumlogout scopelogout function consolelogscopelogindata logged in not logged in scopelogindata stateenumlogin and in my example page i would have something like thisdiv ngcontrollerlogincheckctrl div ngswitch onlogindata div ngswitchwhenstateenumlogin ngincludelogindiv div ngswitchwhenstateenumlogout ngincludelogoutdiv divdivscript typetextngtemplate idlogin button ngclickloginloginbuttonscriptscript typetextngtemplate idlogout button ngclicklogoutlogoutbuttonscriptbut ngswitchwhen does not want to work it only works if i substitute values in ngswithwhen manually with integers for example 12here are fiddles to demonstrate thisnow as you can see the first one clearly does not work and second one works meaning it changes button when button is clickedthe problem i think is this var stateenum objectfreezelogin1 logout2is is possible to use my enum in my html so ngswitchwhen will work properly as in second fiddle,['javascript'] +475673,twitter oauth 1 post requests not working i am creating an application for ios and i am using this oauth library get requests seem to work fine but as soon as i try to make post requests i get the following error code 32 could not authenticate you now i am not quite sure what is happening as post requests are generated pretty similarly to the get requests any ideas what is causing this error here is the code generating the request nsurlrequest preparedrequestforpathnsstring path parametersnsdictionary queryparameters httpmethodnsstring httpmethod oauthtokennsstring oauth token oauthsecretnsstring oauth token secret if httpmethod oauth token return nil nsmutabledictionary allparameters self standardoauthparameters allparametersoauth token oauth token if queryparameters allparameters addentriesfromdictionaryqueryparameters nsstring parametersstring chquerystringfromparameterswithencodingallparameters nsutf8stringencoding nsstring request url api url if path request url request url stringbyappendingstringpath nsstring oauth consumer secret consumer secret nsstring basestring httpmethod stringbyappendingformat request urlutf8andurlencode parametersstringutf8andurlencode nsstring secretstring oauth consumer secretutf8andurlencode stringbyappendingformat oauth token secretutf8andurlencode nsstring oauth signature selfclass signcleartextbasestring withsecretsecretstring allparametersoauth signature oauth signature nsstring querystring if queryparameters querystring chquerystringfromparameterswithencodingqueryparameters nsutf8stringencoding if querystring request url request url stringbyappendingformat querystring nsmutableurlrequest request nsmutableurlrequest requestwithurlnsurl urlwithstringrequest url requesthttpmethod httpmethod nsmutablearray parameterpairs nsmutablearray array allparameters removeobjectsforkeysqueryparametersallkeys for nsstring name in allparameters nsstring apair name stringbyappendingformat allparametersname utf8andurlencode parameterpairs addobjectapair nsstring oauthheader oauth stringbyappendingformat parameterpairs componentsjoinedbystring request setvalueoauthheader forhttpheaderfieldauthorization if httpmethod isequaltostringpost queryparameters nil nsdata body querystring datausingencodingnsutf8stringencoding request sethttpbodybody return requesteditthe very last lines of the code where i set the http body seem to cause the problem when i remove the lines nsdata body querystring datausingencodingnsutf8stringencoding request sethttpbodybodyeverything works fine except when the parameters are exceptionally bigger like sending a base64 encoded image where it obviously fails what could i possibly do to fix this,"['ios', 'objective-c']" +475807,python pip still looking for previous installation after experiencing this brew issue with sqlite3 i didbrew rm sqlite python python3then brew install python python3this installed python275 as the default interpreter and as brew installs pip along with python i thought i would be able topip install virtualenvto install virtualenv for the new python275 however i am getting bash usrlocalsharepythonpip usrlocalcellarpython273binpython bad interpreter no such file or directoryhow can i get aroundfix this should i be creating a symlink between usrlocalsharepythonpip usrlocalcellarpython275binpip27,['python'] +475813,ensuring retrieved json is validated from the correct server for javascript games i am currently trying to establish a technique to verify some data from my server for a simple javascript game i understand that there are many issues with trying to protect your javascript application as by definition all of the code is available clientside for example as it is a game if var playerscore 100to stop people from simply editing the javascript and running it as such var playerscore 10i will validate it on the server however this to me seems to just add a very trivial extra step to hack the game could not the hackertweaker just change the destination of my ajax request to their own local filesi thought about maybe trying to compare an onthefly keyencryption of some common value eg date between client and the server but again the encryption methods would be visible so trivial to avoidi know this is a very broad subject but are there any best practices that you anyone can recommend i have seen this post prevent javascript games tweakinghacking and it was helpful with regards to preventing certain tampering but i am not sure about how to verify the correct serverside validation is taking placeas always many thanks in advance,['javascript'] +475823,phonegap make phone call within application is there a way to initiate a phone call within an application using phonegapi know it is possible to use tel hyperlinks to invoke the dialer but this means that the application is paused i am trying to get this to work from within the applicationany ideas,['javascript'] +475857,how to convert a sql date to a datetime i have a column with the date type in my sql database how can i convert it to c datetime and then back again to a sql date,"['c#', 'asp.net']" +475864,java accessing static variables inside static block analyzing some weird scenario in following static block static systemoutprintlninside static block i100 compilation successful why systemoutprintlni compilation error cannot reference a field before it is definedprivate static int i100while same code is working fine while using static systemoutprintlninside static block i100 compilation successful why systemoutprintlnmyclassi compiles okprivate static int i100not sure why variable initialization do not need variable access using class name while sop requires,['java'] +475874,android google map clicked marker opens new activity or bigger window i have been searching for help on implementing onmarkerclicklistener but nothing i have found has worked this is my marker below and when clicked it only changes colourlight blue i am looking for it to open a bigger window so i can put in more info is this possible googlemapaddmarkernew markeroptions positionnew latlng4937803904 titlehello world snippetthis is my test app iconbitmapdescriptorfactorydefaultmarkerbitmapdescriptorfactoryhue orangethe marker works fine above on my map but now i would like to click on the marker and for it to open a new activitypage or a bigger window what ever is easier to work with as i am a real novice at making apps if anyone who has successfully got a working example please could you put up a link or some codethanks in advanceeditfrom the tutorial that was suggested i have changed some of the mainactivityjavai have added in onmarkerclicklistener and have chosen to add unimplemented methods to the public class public class mainactivity extends activity implements locationlistener onmarkerclicklistener underneath private void setupmap i have added to my code private marker mymarker the setonmarkerclick listener and mymarker private marker mymarker googlemapsetonmarkerclicklistenerthismymarker googlemapaddmarkernew markeroptions positionnew latlnglatlng titlehello world snippetmy first app iconbitmapdescriptorfactorydefaultmarkerbitmapdescriptorfactoryhue orange in the unimplemented method at the bottom i have override public boolean onmarkerclickmarker arg0 todo autogenerated method stub return falsewhat do i need to change in the public boolean onmarkerclick parti am not getting any errors but its just not working what else do i have to add in or changeany help is appreciated,['android'] +475881,laravel 4 upload image form i am trying to make a form that allows uploading a file and store it in the publicupload folder of the applicationmy form isform actionimagesave methodpostinput nameimage typefile input typesubmit valuesaveformand the controllerpublic function savefile inputfileimagedestinationpath uploadfilename filegetclientoriginalnameinputfileimagemovedestinationpath filenamebut when i run it i get the following errorcall to a member function getclientoriginalname on a nonobject,['php'] +475897,cannot find the class comgoogleandroidgmslocationlocationclient android i have download a demo project from and i think i do not lost any steps but i cannot find which jar file contain the acomgoogleandroidgmslocationlocationclientclassa filewe found all googleplayservicesjar and mapsjar and androidjar all versions do not contain the locationclientclass,['android'] +475903,recaptcha styling is broken i implemented recaptcha into the following website i used recaptchalibphp from google code and did not change anything in the php filehowever the result recaptcha in my website seems to broke the buttons have weird white space above them it works just fine but it is not pretty here is the website that has problemhere is the code that i used to echo recaptcha formrequire oncerecaptchalibphppublickey x you got this from the signup pageecho recaptcha get htmlpublickeybest regards,['php'] +475913,cannot implicitly convert type systemeventhandler to systemeventhandler for storyboard complete i have read already a few threads about this but i still do not know how to solve it in my case i come from java and mostly new to ci want to attach listener when animation finishesmystoryboardcompleted new eventhandleronmystoryboardcompletedandprivate void onmystoryboardcompletedobject sender eventargs e and i get the error in the title i tried mystoryboardcompleted new eventhandlerobjectonmystoryboardcompletedbut then i getno overload for onmystoryboardcompleted matches delegate systemeventhandlerobjectso it seems that the signature is not compatible with eventhandlerobject and i could not find how to make it compatible i also do not know if this approach is correcti readunderstanding events and event handlers in cc dynamic template implicit conversion error from systemeventhandler to systemeventhandlerteventargsdefining event handler for tick event of thispatchertimer in windows 8 appbut still do not find the solution for this casethanks in advance,['c#'] +475934,whats the maximum pixel value of css width and height properties what are the largest valid px values that css width and height properties accept i am currently building a webapp that creates a very large zoomable container element and i want to know what are the actual limits,['css'] +476023,how to determine the learning rate and the variance in a gradient descent algorithmi14 i started to learn the machine learning last week when i want to make a gradient descent script to estimate the model parameters i came across a problem how to choose a appropriate learning rate and varianceai found thati14different learning ratei14variance pairs may lead to different results some times you even cannot convergence also if change to another training data set a wellchose i14learning ratei14variancei14pair probably will not work for examplescript belowi14when i set the learning rate to 01 and variance to 01 for data1 i can get the suitable theta0 guess and theta1 guess but for adata2a they cannot make the algorithem convergence even when i tried dozens of i14learning ratei14variancei14pairs still cannot reach to convergence so if anybody could tell me that are there some criteria or methods to determine the i14learning ratei14variancei14pairimport sysdata1 095364693 1097217205 2075195834 3060105519 4049342380 5037400286 6051057128 7025500619 805259608 90639151 109409936 110 4383926 12022858197 130377583 14045606221data2 2104400 1600330 2400369 1416232 30540def create hypothesistheta1 theta0 return lambda x theta1x theta0def linear regressiondata learning rate01 variance01 theta0 guess 1 theta1 guess 1 theta0 last 100 theta1 last 100 m lendata while abstheta1 guesstheta1 last variance or abstheta0 guess theta0 last variance theta1 last theta1 guess theta0 last theta0 guess hypothesis create hypothesistheta1 guess theta0 guess theta0 guess theta0 guess learning rate 1m sumhypothesispoint0 point1 for point in data theta1 guess theta1 guess learning rate 1m sum hypothesispoint0 point1 point0 for point in data return theta0 guesstheta1 guess points floatxfloaty for xy in data1res linear regressionpointsprint res,['python'] +476096,how can i detect url not found error in php curl how can i detect this error using php curl curl return success even if the url does not exist not foundthe requested url fooindexphpitemsedit was not found on this servermy codepost fields arrayinfo json encodefields curl setoptchcurlopt urlurl curl setoptchcurlopt postcountpost fields curl setoptchcurlopt postfieldspost fields curl setoptchcurlopt returntransfertrue curl setoptchcurlinfo content typeapplicationxwformurlencoded charsetutf8 result curl execch echo result ifcurl errorch result curl errorch curl closech return result else curl closech return json decoderesulttrue,['php'] +476155,how to exclude directoriesfiles from meteors bundler meteor watches the current projects directory for file changes so that it can automatically restart the server as my project grew in size i noticed that the time it takes for each refresh has gone up from 1 seconds to 8 secondsi am looking to exclude some files and directories and i am wondering if i should edit applibbundlerjs or if there is a better waythanks,['javascript'] +476162,cannot run load tests because visual studio opens them with an xml editor usually when i open a loadtest file in visual studio the file is being opened with a graphic ui which allows me among other things to run the load tests i am using visual studio 2010 on a different machine now and the loadtest file is being opened with an xml editor how do i make visual studio open the file with the load tests guii cannot find any load test gui option when right clicking the file and choosing open with,['c#'] +476228,return value using string resultcommandexecutescalar error occurs when result returns null i want to fetch 1st row 1st cell value from database it works well with below code but when there is no result found it throws exceptionhow to handle with dbnull should i change my query which return some value if theirs no record systemnullreferenceexception object reference not set to an instance of an objectcode public string absentdaynodatetime sdate datetime edate string idemp string result0 string myqueryselect countidemp atd absentdayno from td atd where myquery absentdate atd between sdate and edate myquery and idemp atdidemp group by idemp atd sqlcommand cmd new sqlcommandmyquery conn connopensystemnullreferenceexception occurs when their is no dataresult string getvalue cmdexecutescalartostring if getvalue null result getvaluetostring connclose return result,"['c#', 'sql', 'asp.net']" +476233,how to use android device as a bluetooth headset for another mobile phone i want to make my android device working as a bluetooth headseti search the android apis but i just find some interface whichcan make android device working as a masters not as a devicebluetooth headseti am also ready to modify the source codes of android os and rebuild the oswhat i hope is when android devices connect to a mobile phone with bluetooth the android devices can work as a bluetooth headseti do not know whether there are interfaces can do this or i should modify the android osthank you,['android'] +476236,maxwidth vs minwidth most of the tutorials i am reading on using media queries are demonstrating the use of minwidth but i am rarely seeing people using maxwidthis this some sort of design trend or pattern why people are using minwidth over maxwidthfor example i am designing a site starting from mobile working up to the desktop i am using foundation 4 but using media queries to remove various elements on the page and reposition the source orderon thing i am facing is a custom navigation for any device whos width is 360px or less i want them to have a vertical navigation rather than an inline horizontal so my idea was to use maxwidth to target these devicesshould i be using minwidth if i am designing mobile first ie all the default styles are for mobile and thus using minwidth to progressively enhance the layout,['css'] +476241,static binding and dynamic binding i am really confused about dynamic bindingstatic binding i have read that determining the type of object at compile time is called static binding and determining at runtime is called dynamic bindingwhat happens in the below codestatic binding or dynamic bindingand wht kind of polymorphism class animal void eat systemoutprintlnanimal is eating class dog extends animal void eat systemoutprintlndog is eating public static void mainstring args animal anew animal aeat,['java'] +476253,twitter bootstrap 100 height accordion jump i am trying to implement a 100 height accordion using the twitter bootstrap collapse component exactly as described in this questioni am manually setting the heights of the accordioninner elements as described in this answerhowever i am experiencing bouncy behaviour when expandingcollapsing the panels i have removed all paddingmarginborder from the accordioninner elements to eliminate that possibilityit is most noticeable in ie10 however the problem is also evident in chromesee this exampleany ideas what is causing this jumpy behaviour,"['html', 'css']" +476256,how to set a particular font for a button text in android i want my button text to be in the copperplate gothic light font and i yet have not come across a simple clean code for a simple function as this help ps since android comes with ariel and a few other fonts on its own we need to import apologies for the lack of a better word since im new to this the font we wish to use this is all i have been able to gather till yet and this is where the trail ends for me help needed,['android'] +476275,emojis support in apple push notification i am working on iphone app named interstizioin this i have implemented functionality like chat between usersin this user can send textlocation and text with emojis symbolif the app is not in open mode at receiver end then from backend push is generated and thisplay to receiveri am able to thisplay message in push like username hello but i also want to thisplay emojis symbol like username hay in push message so anyone have idea regarding how i can achieve this type of push message using emojis codelike for smile apple code is u263a of applei have followed the solution given in this link but it returns the same code that i have passed in functionits working fine on web pages but not in push messagehere i am attaching one screen shot of the push how it looks at my endin it you can see that i have thisplayed smiley and lighting symbol but its thisplayed using html supported code like below code of php scriptlightning html entity decode57661ent noquotesutf8 add this to the alert portion of your apns payload message you just got the lightningshockerlightningbut in my case i have thisplayed inbuilt emojis keyboard from apple and using below code i am able to get emojis code store code of emojis at backend nsdata data txtspeechtext datausingencodingnsnonlossyasciistringencoding nsstring valueunicode nsstring alloc initwithdatadata encodingnsutf8stringencodingthisplay emojis in mobile chat windownsdata data objchatstrchat datausingencodingnsutf8stringencoding nsstring valueemoj nsstring alloc initwithdatadata encodingnsnonlossyasciistringencoding celltxtchattextvalueemojusing above code i am able to store and thisplay emojis in chat window but if receiver user have closed app then in push message i am not able to thisplay emojis symbol in push messagethanks,"['php', 'iphone', 'ios']" +476292,is there a way to create one gif image from multiple images in java i am trying to set up a simple java program that creates one single animated gif from multiple other images jpg can anyone give me a hook on how to achieve this in java i already searched google but could not find anything really helpfulthank you guys,['java'] +476298,proximity sensor on galaxy s4 air gestures the new samsung galaxy s4 have and interesting new type of gestures called air gesture that use an infrared sensor to process users hand movement in front of the screen adding a pretouchproximity event in wich the fingers are detected before the touch i would like to use this floating touch event in one of my apps i searched both on google and in the samsung developers center but i coudnt find any api or information about that are the api available or is too early does someone have any linkinfo,['android'] +476373,am charts javascript version does not show complete number of lables on category axis everyonei am using the amcharts to generate graphic but when the size of the div is not big as it wants it will somewhat collapse labels in category axisfor example in category axis suppose to show 1 2 3 4 5 6 instead it will show 1 3 5 in the axis i wonder how could i either turn it off or enable the complete list of label to be thisplay even when the div is too small or any solution that can be provided for this issueupdatefor reading and research convinence i put the link where show the chart in live herein here you can see that the country name is not thisplayed fully in each column because the constrain of spaceso again question is that how to thisable this or somehow enable it to thisplay all the column name in a way that fit them in or shrink the textthank you,"['javascript', 'jquery']" +476388,nodejs require cannot find custom module here is the project structure appjs packagejson node modules app configjson frontend assets and html tpls modules couchjs raeumejs usersjsi require configjson raeumejs and usersjs from appjs and it all works finevar config requireappconfigvar raeume requireappmodulesraeumevar users requireappmodulesusersthen i require configjson and couchjs from userjs the same way and it would not find anythingvar couch requireappmodulescouchvar config requireappconfigi guess it should find it after some research i saw a diverse landscape of problems inclusive how node is compiled thus included i work on osx 108 with node v0107,['javascript'] +476395,return generated pdf using spring mvc i am using spring mvc i have to write a service that would take input from the request body add the data to the pdf and returns the pdf file to the browser the pdf document is generated using itextpdfhow can i do this using spring mvc i have tried using thisrequestmappingvaluegetpdf methodrequestmethodpost public document getpdfhttpservletrequest request httpservletresponse response requestbody string json throws exception responsesetcontenttypeapplicationpdf responsesetheadercontentthisposition attachmentfilenamereportpdf outputstream out responsegetoutputstream document doc pdfutilshowhelpemp return docshowhelp function that generates the pdf i am just putting some random data in the pdf for time beingpublic static document showhelpemployee emp throws exception document document new document pdfwritergetinstancedocument new fileoutputstreamctmpreportpdf documentopen documentaddnew paragraphtable documentaddnew paragraphnew datetostring pdfptable tablenew pdfptable2 pdfpcell cell new pdfpcell new paragraph table cellsetcolspan 2 cellsethorizontalalignment elementalign center cellsetpadding 100f cellsetbackgroundcolor new basecolor 140 221 8 tableaddcellcell arrayliststring rownew arrayliststring string datanew string2 data01 data12 string data1new string2 data103 data114 rowadata rowadata1 forint i0irowsizei string colsrowgeti forint j0jcolslengthj tableaddcellcolsj documentaddtable documentclose return document i am sure this is wrong i want that pdf to be generated and saveopen dialog box to be opened through the browser so that it can be stored in the clients file system please help me out,['java'] +476414,in a java synchronized block are writes visible on all fields or just the synchronized variable say you have this codeprivate string cachedtokenprivate final object lockobject new objectretrievetoken synchronizedlockobject if cachedtoken null cachedtoken gogetnewtoken return cachedtoken will the write to cachedtoken be visible to all threads that have locked on lockobject,['java'] +476430,how to compare two object which have string values i use this code and get true result object text1 test object text2 test consolewritelinetext1 text2 text1 text2 returntruebut when i try to lowerobject text2 testtoloweri get false result object text1 testtolower object text2 testtolower consolewritelinetext1 text2 text1 text2a returnfalse,['c#'] +476487,javaxpersistencepersistenceexception no persistence provider for entitymanager named i am trying to set up a simple jpa 20 project by following the information provided by my teachers documentation i have been on this for hours now but no matter what i do i always get this exception when i try to create a entitymanagerfactoryi have found quite a few similar questions regarding this exception but no solutions that i am able to get to work what am i doing wrong herei created this project from eclipse no command promptexception in thread main javaxpersistencepersistenceexception no persistence provider for entitymanager named course at javaxpersistencepersistencecreateentitymanagerfactorypersistencejava56 at javaxpersistencepersistencecreateentitymanagerfactorypersistencejava34 at messagesavemessagemainsavemessagejava8directory structuremy persistencexmlpersistence xmlns xmlnsxsi xsischemalocation 2 0xsd version20 persistenceunit namecourse transactiontyperesource local providerorghibernateejbhibernatepersistenceprovider properties property namehibernatedialect valueorghibernatedialectmysql5innodbdialect property namehibernatehbm2ddlauto valueupdate property namejavaxpersistencejdbcdriver valuecommysqljdbcdriver property namejavaxpersistencejdbcurl valuejdbcmysqllocalhost3306studentdb property namejavaxpersistencejdbcuser valueroot property namejavaxpersistencejdbcpassword valuepasapas2005 properties persistenceunitpersistencemy class package messageimport javaioserializableimport javaxpersistenceentitypublic class message implements serializable private long id private string text public message public messagelong id string text thissetidid thissettexttext id public long getid return id public void setidlong id thisid id public string gettext return text public void settextstring text thistext text my my tester main classpackage messageimport javaxpersistencepublic class savemessage public static void mainstring args entitymanagerfactory emf persistencecreateentitymanagerfactorycourse entitymanager em emfcreateentitymanager entitytransaction tx emgettransaction txbegin message message new message1 hello world empersistmessage txcommit emclose systemoutprintlnmessage saved,['java'] +476508,adding textfield to graphics in java does anyone know how to add jtextfield into graphics name bufferstrategygetdrawgraphicstryed to pain it into graphics something like this private jtextfield input new jtextfieldbufferstrategy bs getbufferstrategyif bs null createbufferstrategy3 returnfinal graphics gcommands bsgetdrawgraphicsgraphics gcc bsgetdrawgraphicsinputrequestfocusinputpaintgccinputsetbounds800250 35020inputsetborderborderfactorycreatelinebordercolorblack 0inputseteditabletrueinputsetbackgroundgetbackgroundinputsetforegroundgetforegroundinputaddkeylistenerkeybut eventhough it thisplayed i could not edit it even the inputsetbounds800250 35020 did not work this method that is written above is being called inside a gameloop can anyone help me,['java'] +476531,why does floatparse return wrong value i have a problem when i parse a string like 05 to float or double it works fine on my computer but when i install my program to my clients computer it returns 5 both my computer and my clients computer are using windows 7 x64 here are my examplespublic float getfloat float mn floatparse05 double mn2 converttodouble05 return mn,['c#'] +476541,how can i avoid app names in inapp item titles returned from google play getskudetails i would like the use the getskudetails call from the inapp billing v3 api to dynamically thisplay a list of inapp purchase options with properly translated titles and relevant pricehowever the title property from getskudetails seems to always be of the form item title app name which is less than useful how can i get only the item title itself without the app name without hacking the string,['android'] +476550,adt error exporting with gradle i am trying to export my android project from adt using gradle so that i can import into android studioi select generate gradle build files and select my project in the export menu but when i click finish it flashes the creating gradle build progress bar for a millisecond then stays on the export menu screen a new error is created in the error log the message is blank plugin is comandroidideeclipseadtthis is the full error log outputentry comandroidideeclipseadt 4 0 20130520 161645168message stack 0javalangreflectinvocationtargetexception at orgeclipsejfaceoperationmodalcontextrunincurrentthreadmodalcontextjava477 at orgeclipsejfaceoperationmodalcontextrunmodalcontextjava372 at orgeclipsejfacewizardwizarddialogrunwizarddialogjava1028 at comandroidideeclipseadtinternalwizardsexportgradlegradleexportpagegeneratebuildfilesgradleexportpagejava293 at comandroidideeclipseadtinternalwizardsexportgradlegradleexportwizardperformfinishgradleexportwizardjava32 at orgeclipsejfacewizardwizarddialogfinishpressedwizarddialogjava827 at orgeclipsejfacewizardwizarddialogbuttonpressedwizarddialogjava432 at orgeclipsejfacedialogsdialog2widgetselecteddialogjava624 at orgeclipseswtwidgetstypedlistenerhandleeventtypedlistenerjava248 at orgeclipseswtwidgetseventtablesendeventeventtablejava84 at orgeclipseswtwidgetswidgetsendeventwidgetjava1053 at orgeclipseswtwidgetsthisplayrundeferredeventsthisplayjava4169 at orgeclipseswtwidgetsthisplayreadandthispatchthisplayjava3758 at orgeclipsejfacewindowwindowruneventloopwindowjava825 at orgeclipsejfacewindowwindowopenwindowjava801 at orgeclipseuiinternalhandlerswizardhandlerexportexecutehandlerwizardhandlerjava103 at orgeclipseuiinternalhandlerswizardhandlerexecutewizardhandlerjava279 at orgeclipseuiinternalhandlershandlerproxyexecutehandlerproxyjava293 at orgeclipsecorecommandscommandexecutewithcheckscommandjava499 at orgeclipsecorecommandsparameterizedcommandexecutewithchecksparameterizedcommandjava508 at orgeclipseuiinternalhandlershandlerserviceexecutecommandhandlerservicejava169 at orgeclipseuiinternalhandlersslavehandlerserviceexecutecommandslavehandlerservicejava241 at orgeclipseuiinternalactionscommandactionrunwitheventcommandactionjava157 at orgeclipseuiinternalactionscommandactionruncommandactionjava171 at orgeclipseuiactionsexportresourcesactionrunexportresourcesactionjava116 at orgeclipseuiactionsbaseselectionlisteneractionrunwitheventbaseselectionlisteneractionjava168 at orgeclipsejfaceactionactioncontributionitemhandlewidgetselectionactioncontributionitemjava584 at orgeclipsejfaceactionactioncontributionitemaccess2actioncontributionitemjava501 at orgeclipsejfaceactionactioncontributionitem5handleeventactioncontributionitemjava411 at orgeclipseswtwidgetseventtablesendeventeventtablejava84 at orgeclipseswtwidgetswidgetsendeventwidgetjava1053 at orgeclipseswtwidgetsthisplayrundeferredeventsthisplayjava4169 at orgeclipseswtwidgetsthisplayreadandthispatchthisplayjava3758 at orgeclipseuiinternalworkbenchruneventloopworkbenchjava2701 at orgeclipseuiinternalworkbenchrunuiworkbenchjava2665 at orgeclipseuiinternalworkbenchaccess4workbenchjava2499 at orgeclipseuiinternalworkbench7runworkbenchjava679 at orgeclipsecoredatabindingobservablerealmrunwithdefaultrealmjava332 at orgeclipseuiinternalworkbenchcreateandrunworkbenchworkbenchjava668 at orgeclipseuiplatformuicreateandrunworkbenchplatformuijava149 at orgeclipseuiinternalideapplicationideapplicationstartideapplicationjava124 at orgeclipseequinoxinternalappeclipseapphandleruneclipseapphandlejava196 at orgeclipsecoreruntimeinternaladaptoreclipseapplauncherrunapplicationeclipseapplauncherjava110 at orgeclipsecoreruntimeinternaladaptoreclipseapplauncherstarteclipseapplauncherjava79 at orgeclipsecoreruntimeadaptoreclipsestarterruneclipsestarterjava353 at orgeclipsecoreruntimeadaptoreclipsestarterruneclipsestarterjava180 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokeunknown source at sunreflectdelegatingmethodaccessorimplinvokeunknown source at javalangreflectmethodinvokeunknown source at orgeclipseequinoxlaunchermaininvokeframeworkmainjava629 at orgeclipseequinoxlaunchermainbasicrunmainjava584 at orgeclipseequinoxlaunchermainrunmainjava1438 at orgeclipseequinoxlaunchermainmainmainjava1414caused by javalangillegalargumentexception path must include project and resource name settingsgradle at orgeclipsecoreruntimeassertislegalassertjava63 at orgeclipsecoreinternalresourcesworkspacenewresourceworkspacejava2169 at orgeclipsecoreinternalresourcescontainergetfilecontainerjava208 at comandroidideeclipseadtinternalwizardsexportgradlebuildfilecreatorcreatebuildfilesbuildfilecreatorjava139 at comandroidideeclipseadtinternalwizardsexportgradlegradleexportpage6rungradleexportpagejava274 at orgeclipsejfaceoperationmodalcontextrunincurrentthreadmodalcontextjava464 53 moreroot exceptionjavalangillegalargumentexception path must include project and resource name settingsgradle at orgeclipsecoreruntimeassertislegalassertjava63 at orgeclipsecoreinternalresourcesworkspacenewresourceworkspacejava2169 at orgeclipsecoreinternalresourcescontainergetfilecontainerjava208 at comandroidideeclipseadtinternalwizardsexportgradlebuildfilecreatorcreatebuildfilesbuildfilecreatorjava139 at comandroidideeclipseadtinternalwizardsexportgradlegradleexportpage6rungradleexportpagejava274 at orgeclipsejfaceoperationmodalcontextrunincurrentthreadmodalcontextjava464 at orgeclipsejfaceoperationmodalcontextrunmodalcontextjava372 at orgeclipsejfacewizardwizarddialogrunwizarddialogjava1028 at comandroidideeclipseadtinternalwizardsexportgradlegradleexportpagegeneratebuildfilesgradleexportpagejava293 at comandroidideeclipseadtinternalwizardsexportgradlegradleexportwizardperformfinishgradleexportwizardjava32 at orgeclipsejfacewizardwizarddialogfinishpressedwizarddialogjava827 at orgeclipsejfacewizardwizarddialogbuttonpressedwizarddialogjava432 at orgeclipsejfacedialogsdialog2widgetselecteddialogjava624 at orgeclipseswtwidgetstypedlistenerhandleeventtypedlistenerjava248 at orgeclipseswtwidgetseventtablesendeventeventtablejava84 at orgeclipseswtwidgetswidgetsendeventwidgetjava1053 at orgeclipseswtwidgetsthisplayrundeferredeventsthisplayjava4169 at orgeclipseswtwidgetsthisplayreadandthispatchthisplayjava3758 at orgeclipsejfacewindowwindowruneventloopwindowjava825 at orgeclipsejfacewindowwindowopenwindowjava801 at orgeclipseuiinternalhandlerswizardhandlerexportexecutehandlerwizardhandlerjava103 at orgeclipseuiinternalhandlerswizardhandlerexecutewizardhandlerjava279 at orgeclipseuiinternalhandlershandlerproxyexecutehandlerproxyjava293 at orgeclipsecorecommandscommandexecutewithcheckscommandjava499 at orgeclipsecorecommandsparameterizedcommandexecutewithchecksparameterizedcommandjava508 at orgeclipseuiinternalhandlershandlerserviceexecutecommandhandlerservicejava169 at orgeclipseuiinternalhandlersslavehandlerserviceexecutecommandslavehandlerservicejava241 at orgeclipseuiinternalactionscommandactionrunwitheventcommandactionjava157 at orgeclipseuiinternalactionscommandactionruncommandactionjava171 at orgeclipseuiactionsexportresourcesactionrunexportresourcesactionjava116 at orgeclipseuiactionsbaseselectionlisteneractionrunwitheventbaseselectionlisteneractionjava168 at orgeclipsejfaceactionactioncontributionitemhandlewidgetselectionactioncontributionitemjava584 at orgeclipsejfaceactionactioncontributionitemaccess2actioncontributionitemjava501 at orgeclipsejfaceactionactioncontributionitem5handleeventactioncontributionitemjava411 at orgeclipseswtwidgetseventtablesendeventeventtablejava84 at orgeclipseswtwidgetswidgetsendeventwidgetjava1053 at orgeclipseswtwidgetsthisplayrundeferredeventsthisplayjava4169 at orgeclipseswtwidgetsthisplayreadandthispatchthisplayjava3758 at orgeclipseuiinternalworkbenchruneventloopworkbenchjava2701 at orgeclipseuiinternalworkbenchrunuiworkbenchjava2665 at orgeclipseuiinternalworkbenchaccess4workbenchjava2499 at orgeclipseuiinternalworkbench7runworkbenchjava679 at orgeclipsecoredatabindingobservablerealmrunwithdefaultrealmjava332 at orgeclipseuiinternalworkbenchcreateandrunworkbenchworkbenchjava668 at orgeclipseuiplatformuicreateandrunworkbenchplatformuijava149 at orgeclipseuiinternalideapplicationideapplicationstartideapplicationjava124 at orgeclipseequinoxinternalappeclipseapphandleruneclipseapphandlejava196 at orgeclipsecoreruntimeinternaladaptoreclipseapplauncherrunapplicationeclipseapplauncherjava110 at orgeclipsecoreruntimeinternaladaptoreclipseapplauncherstarteclipseapplauncherjava79 at orgeclipsecoreruntimeadaptoreclipsestarterruneclipsestarterjava353 at orgeclipsecoreruntimeadaptoreclipsestarterruneclipsestarterjava180 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokeunknown source at sunreflectdelegatingmethodaccessorimplinvokeunknown source at javalangreflectmethodinvokeunknown source at orgeclipseequinoxlaunchermaininvokeframeworkmainjava629 at orgeclipseequinoxlaunchermainbasicrunmainjava584 at orgeclipseequinoxlaunchermainrunmainjava1438 at orgeclipseequinoxlaunchermainmainmainjava1414i tried looking up the java errors and path must include project and resource name settingsgradle as it pertains to adt but i was not able to find anything i am not familiar with gradle so i am not sure whats causing this any help you can provide would be much appreciated,['android'] +476566,the type initializer for crystaldecisionscrystalreportsenginereportdocument threw an exception i am deploying a desktop application to my clients that uses the crystal reports api to thisplay and print forms i am building my installer using installshield 2012 i have also included the net 40 framework along with all of the crystal assemblies i have 2 kinda related concerns1 whenever i tried to run the application on the client machine i get the following errorthe type initializer for crystaldecisionscrystalreportsenginereportdocument threw an exceptioni have no idea what i am forgetting here the crystaldecisionscrystalreportsengine dll is being registered in the gac correctly as are about 10 other crystal assemblies 2 i have asked this question on the sap forums and i was told i needed to include the net 20 framework along with the net 40 framework i tried including the net 20 rethistributable in my installer package but the installer does not install it does the installer see that i have 40 installed so it skips the 20 installation,"['c#', '.net']" +476610,volley android networking library i have few questions around using volley in my projectscan this library be used in any java project or just androidi see multiple branches here and no documentation on which branch is to start with which branch should i use to start withhow do you integrate this library in your own project what approach is better make volley as a standalone library project and spin a jar and put it in your project or copy the all source code inside your project,['android'] +476611,return already resolved promise i have an existing project that has a lot of asynchronous functions that return promises i am adding some caching so that in some cases the asynchronous functions will complete synchronously and would like to make this code shorterbetter if possible return deferredfunctiondef defresolve promisefor example i have a data service class that handles most ajax requests that looks like thisfunction dataservice var self this selfmakerequest functionfunctionname data return deferredfunctiondef var jsondata jsonstringifydata ajax type post url webserviceasmx functionname data jsondata contenttype applicationjson charsetutf8 datatype json error functionxhr status error var ex try ex eval xhrresponsetext exmessage exmessage exmessage undefined catch ex2 ex message invalid response from serverrn xhrresponsetext if exmessage loginrequired appviewmodelsmainloginrequiredtrue else appshowerrorexmessage defrejectexmessage promise then i have a function in another class that currently always calls makerequestselfdeleteme function return appdataservicemakerequestdeleteitemi want to update the deleteme function so that it does not always call makerequest and instead just does some synchronous work and then returns it needs to return a promise though because whatever called it will be expecting that but it needs to be an already completedresolved promise currently i am using the first set of code above to do that seems like there must be a better way,['jquery'] +476650,analyze audio input from microphone javascript i am planning to create a music visualizer on a website there are objects that should change in size and shape based off of the current music that is playing a nonclassical multiline song probably such as do not stop believing i want to at least be able to know the volume of the music and if possible any pitches that can be picked up is fft possible in javascript are there sound apis out there that that will let me do this in javascript or at least online,['javascript'] +476655,webforms unobtrusivevalidationmode requires a scriptresourcemapping for jquery please add a scriptresourcemapping named jquerycasesensitive i am building a web application using visual studio 2012 i am attempting to add word count into my textbox however after adding the the javascript codes and the html codes i receive the error as stated abovehere is my javascript codedscode function validatelimitobj divid maxchar objdiv get objectdividif thisid obj thisvar remaningchar maxchar trimenterobjvaluelengthif objdivid objdivinnerhtml remaningchar characters leftif remaningchar 0 objvalue objvaluesubstringmaxchar 0 if objdivid objdivinnerhtml 0 characters left return falseelse return true function get objectid var object nullif documentlayers object documentlayersid else if documentall object documentallid else if documentgetelementbyid object documentgetelementbyididreturn objectfunction trimenterdatastr return datastrreplacernrng server codes in master page script typetextjavascript srcjsjscriptjs scriptaspx codes html codes trth stylewidth 595px height 135pxofficial report thtd colspan4 styleheight 135px asptextbox idtbofficial runatserver height121px textmodemultiline width878px maxlength500 tooltipsummary500 characters onkeyupreturn validatelimitthis lblmsg1 500 asptextbox div idlblmsg1500 characters leftdivasprequiredfieldvalidator idrequiredfieldvalidator1 runatserver controltovalidatetbofficial thisplaydynamic setfocusonerrortrueasprequiredfieldvalidator br asplabel idlblmsg runatserverasplabel br br aspbutton idbtnsubmit runatserver textsubmit onclickbtnsubmit click aspbutton idbtnclear runatserver textclear onclickbtnclear click tdtr,"['html', 'asp.net']" +476685,count sql syntax count value multiple columns hello im trying to learn about count in sql but i cant even count how many times a value is in a specific column my database structure is this table natural id one two three 1 34 45 80 2 41 34 7 3 7 18 22 4 8 7 45 im trying this resultmysql queryselect countone as total from naturalwhere one7or dieerror mysql errordatamysql fetch assocresultecho datatotalbut even with just 1 column in count i cant get the resultwhat i need is count how many times is a value for example 7 in all the columnslike in this example value 7 3 total multiple columns how can i make a sql like thatedit trying this where is my syntax problemresultmysql queryselect countthistinct id totalcount from tblname where 7 in one two threeor dieerror mysql errordatamysql fetch assocresultecho datatotalcounti suck thanks for your answers but i think my problems is with mysql query cause i always got a syntax problem with all your answers and its obviously meresultmysql queryselect sumcase when one 7 then 1 else 0 end sumcase when two 7 then 1 else 0 end sumcase when three 7 then 1 else 0 end totalcount from naturalor dieerror mysql errordatamysql fetch assocresultecho datatotalcountto fix this last code just use one and two so on and natural thats the correct syntax d,"['php', 'mysql', 'sql']" +476686,difference between pltclose and pltclf in python what is the difference between pltclf and pltclosewill they function the same way,['python'] +476754,orgjsonjsonexception unterminated string at character 1834 i am fetching the data from webservice which i am parsing to json string while parsing i am this exception orgjsonjsonexception unterminated string at character 1834 my code isstring jsonstringgetjsonstringresponsejsonobject json new jsonobjectjsonstringthe string islotdescriptiondavid weekley homes traditional collection in baxter village offers floor plans featuring innovative design and unsurpassed quality this charming community combines work play and living all within the village in baxter village yoursquoll enjoynbsp parks playgroundsit is parsing till the word village and the raising the exception while parsing youll which seems to be some html contentwhat is the solution for this,"['java', 'android']" +476756,in java should i escape a single quotation mark in string double quoted in java denotes a single quotation mark single quote character and denotes a double quotation mark double quote characterso string s i am a human works wellhowever string s i am a human does not make any compile errors eitherlikewise char c works but char c also worksin java which is better to use in html or css things like stylefontfamilyarial unicode ms are more often and for such tags i think it is the only way to use quotation marks but in java i usually saw people use escape characters like i am a human,['java'] +476791,mvc 4 forms authentication not working with authorize i am learning mvc4 right now and i am following the pro asp net mvc4 4th edition book to create a sports store projecti have always developed in webforms and i am trying to figure out how the forms authentication is working in mvc4here is what i have achievedwebconfigauthentication modeformsforms loginurlaccountlogin timeout2880 authenticationaccountcontroller login actionhttppost public actionresult loginloginviewmodel model string returnurl if modelstateisvalid if authproviderauthenticatemodelusername modelpassword return redirectreturnurl urlactionindex admin else modelstateaddmodelerror incorrect username or password return view else return view auth providerpublic bool authenticatestring username string password bool result formsauthenticationauthenticateusername password if result formsauthenticationsetauthcookieusername false return result i am setting the authcookie and now i would like to know how to protect other controllersand actions out of the accountcontrollerthe application has a controller called admincontroller where you can edit products and theproduct list in under the following controlleractionadminindexso if i am not missunderstanding the theory if the user is not logging in the accountcontroller they should not be able to call actions with authorize tagon declaration public class admincontroller controller private iproductrepository repository public admincontrolleriproductrepository repo repository repo authorize public actionresult index return viewrepositoryproducts the thing is i can call the index action of the admin controller without any problem and without introducing the logini need some guidance to understand how this works i have done some research and could not find anything and the book is not covering this topicthanks in advanceedit i closed chrome browser and worked without changing anything i was working with tabs and i guess the cookie was active even stopping and starting debugging,['c#'] +476826,which download for net source following this question looking here you see this list currentlyproduct name version view download net 80dotnetfx1434 vistawin2k8sp1 507271434fxupdate3074 507273074aspnet mvc 10wcf 35sp1wf 35sp1dotnetfx vista sp2 507274016dotnetfx win7 351 351aspnet mvc 20net 4net 35 sp1 rethist 507273053aspnet mvc 3netfx 351 win7sp1 351net 45net 45update1i am not sure what ones i need to download i have vs2010 and vs2012 net 45update1 sounds good for vs2012 but after download the read me says seamless integration with visual studio 20082010 but i assume that is just out of date readmewhat is net 80 and why are there so many different 35 versions,['.net'] +476896,overriding with difference access specification c i came across a question while taking ikm test there was a base class with two abstract methods with private access specifier there was a derived class which was overriding these abstract methods but with protectedpublic access specifieri never came across such thing where overridden methods in derived class had different access specification is this allowed if yes does it comply to is a relation between base and derived ie safely substitutablecould you point me to some references which can provide more details on such usages of classes thank you,['c++'] +476936,hiding a toolbar element when uitableview scrolls similar to facebooks app how i can achieve this effect,"['ios', 'objective-c']" +476993,generate javascript representation of enums i have a few flags enums in my code i would like to expose to javascript without copypasting signalr seems to be doing something similar for their hubproxies by mapping an url to an action returning the javascript stubs generated by reflection since the code is generated at runtime it does not seem possible to be included into the bundlesas an alternative i implemented a t4 template to generate a js file at design time template debugfalse hostspecifictrue languagec assembly namesystemcore assembly nameenvdte import namespaceenvdte import namespacesystemlinq import namespacesystemtext import namespacesystemcollectionsgeneric output extensionjs enums var visualstudio host as iserviceprovidergetservicetypeofenvdtedte as envdtedte var project visualstudiosolutionfindprojectitemthishosttemplatefile containingproject as envdteproject foreachenvdteprojectitem item in getprojectitemsrecursivelyprojectprojectitems if itemfilecodemodel null continue foreachenvdtecodeelement elem in itemfilecodemodelcodeelements if elemkind envdtevscmelementvscmelementnamespace foreach codeelement innerelement in elemchildren if innerelementkind vscmelementvscmelementenum codeenum enu codeenuminnerelement enuname dictionarystring string values new dictionarystring string foreach codeelement child in enumembers codevariable value child as codevariable if value null string init valueinitexpression as string int unused if inttryparseinit out unused foreach keyvaluepairstring string entry in values init initreplaceentrykey entryvalue init init valuesaddvaluename init writelinett valuename init public listenvdteprojectitem getprojectitemsrecursivelyenvdteprojectitems items var ret new listenvdteprojectitem if items null return ret foreachenvdteprojectitem item in items retadditem retaddrangegetprojectitemsrecursivelyitemprojectitems return ret however this feels fragile with envdte especially the logic to handle enums likeflagspublic enum access none 0 read 1 write 2 readwrite read writewith composite values is a dirty hack with string replacements the t4 template above will generateenums access none 0 read 1 write 2 readwrite 1 2 is there a cleaner way to achieve this ideally some kind of designtime reflection to generate the js file so it is available for bundling,['c#'] +477023,google play store suspension whereabouts edited editdue to the certain number of complaints from the people i cooperate with i would like to reopen this issue due to the new google content policy strategies in mind google unlike apple is very stingy with the real explanation why your application is suspended i am an ios developer too and i have experience with app store rejections but backed up with screenshots and actual explanations i was even amazed how did they manage to find those well hidden news and take actual screenshots yes it was a news apprecently i reworked and updated an old hybrid app to be fully native one i have changed nothing related to the content but only to make it a fully native one that app got rejected for not complying to the gambling content policy after 2 monthsthis is a new problem and i would like if we could share problems solutions here advices can come in handy tooyou can read this too same situation with different contentremove these edits if this is not covered elsewhereoriginalbeen looking for a guide to app suspension from google play and been struggling to find one so based on trawling stack overflow and the official android developer forum have put together a guide for what occurs when an app is suspended from the google play android marketplace there are some questions interspersed so if you have firsthand experience of this would be good to hear from you thanksmay be worth bearing in mind that googles play store tos is updated from time to time and that if your app is currently compliant that may change at the whim of google at some point in futureif your app is suspended from the google play you will receive a notification email from google to the developer email associated with your publisher account google will list the applicable tos rules that your app is in breach of they donat usually go into too much detailyou can reply to the notification email and appeal the decision having proof to back up your claims will certainly help for example if your app was suspended due to copyright infringement being able to prove you have an agreement with the rights holder should be sufficient to ensure your app is reinstatedbased on your appeal google may unsuspend your app this usually happens within a day or two if your app is unsuspended youall have the option to republish it via your google play publisher account under the same package existing users will be able to keep their existing settings and inapp purchasesdo inapp purchases need to be restoredgoogle may choose not to reply to your appeal in which case your app may remain suspended suspended apps are no longer live in the google play store and their package is no longer available to publish to what does having a suspended app mean to the end user are they blocked from opening the app or just not able to access itas page on the google play store and they will no longer receive updates what options are open to users that have made inapp purchases on suspended appsif your appeal was unsuccessful you can choose to try to fix this issues google outlined and republish your app under a different package but youall of course be starting from scratch with no users and no way to transfer inapp purchases unless you maintained a separate database of purchases not sure on the last pointgoogle can choose to close publisher accounts that are repeat offenders when a publisher account is closed by google all apps associated with that account are also suspended,['android'] +477028,where can the using directive be placed in aspnet razor pages i have traditionally always put using directives in my aspnet razor pages at the top along with the model directive however for my overall layout i want to make sure the doctype declaration is at the very beginning of the document so i want to push the using down a bit would you following be validdoctype htmlhtml using mylibrary head titletest web pagetitle also is there any documentation on where the using directive can be used in razor pages i cannot seem to find any is it valid to use it after some other razor code for example or does it have to appear first,"['asp.net', '.net']" +477054,why does malloc or new never return null i am writing an application which needs a lot of memory for caching purposes as i described he here now i am playing around with some malloc new constructions to figure out how i could realise it i made a strange observationinclude stdiohinclude stdlibhint mainvoid while1 char foo charmalloc1024 new char1024 iffoo null printfcould not allocn fflushstdout return 0 return 0why does that printf never be reached if my system runs out of memory malloc is said to return null as it is explained here but i always receive sigkill i am using linux,"['c++', 'c']" +477080,caliburnmicro rebind contentcontrol on navigation goback i am using caliburnmicro within winrt applicationhere is my main vmpublic class mainviewmodel conductorscreen protected override void onactivate if activeitem null activateitem viewmodellocatorlocateforviewtypetypeofnewsfeedview as screen baseonactivate here i use conductor because i want to load different controls in contentcontrol but now i have only this code here is my content control in main viewcontentcontrol xnameactiveitem gridcolumn1 gridrow1 when i running the application everything work fine mainviewmodelactivate gets called and activeitem set to newsfeedviewmodel and contentcontrol loads newsfeedviewthe problemwhen i navigate in newsfeedview control to another view using navigationservicenavigatetoviewmodel method and then in that view use navigationservicegoback i am returning to mainview and in that moment when mainviewmodelactivate gets called activeitem is not null but contentcontrolcontent is null i have tried use viewmodel attached property for contentcontrol but no luck how to make it rebindeditfinally i am setup logger in caliburn to see what happens and i found an error when mainview loaded after navigationg back this events occuringattaching viewsmainview to viewmodelsmainviewmodelviewmodel bound on activeitemusing cached view for viewmodelsnewsfeedviewmodelsystemreflectiontargetinvocationexception exception has been thrown by the target of an invocation systemexception unspecified errorat windowsuixamlcontrolscontentcontrolput contentobject value some winrt stackat caliburnmicroviewsetcontentpropertycorethough it was not so informative i have used intelitrace to get more info and got this message element is already child of another element i suppose newsfeedview stored somewhere and when time comes to put it in contentcontrol this exception thrown how to solve this,"['c#', '.net']" +477162,can someone break this lambda expression down for me i am looking at the solution from token replacement and identificationstring result regexreplace text rcd match dictintparsematchgroups1valueand i am not understanding how the matchevaluator was overloadedi understand some of the lambda expression it takes the input match and then looks up a integer from the dictionarybut where does the value for match come from and where does the value returned from match dictintparsematchgroups1value goedit some of you have mentioned delegate surprisingly after three years in university for cs i have not come across this term what is the delegate and what does it do in this specific situationlast editi tried writing my own delegate with the following codewhere my tokens are in the form of sometokennamepublic void createscriptdictionarystringstring dictionary string path used in the regex to identify the string to replace var pattern 09afaf read in the file found at the path var lines filereadalinespath int linecounter 0 foreach string line in lines line regexreplaceline pattern match dictionarytrygetvaluematchgroups0value but i keep getting a cannot convert lambda expression to type int because it is not a delegate type whats the difference between the line i wrote and the one found in the solution,"['c#', '.net']" +477201,intellij artifact has invalid extension i have strange a problem with deploying an artifact on jboss after generating the default springmvc project in intellij i tried to run it but intellij showed in rundebug configuration a message that my artifact xyzwar exploded has invalid extensioni found advice on stackoverflow change extension but i have correct war extensionwhat is wrong,['java'] +477279,making a same domain iframe secure tldr can i execute untrusted scripts on an iframe safelyback storyi am trying to make secure jsonp requests a lot of older browsers do not support web workers which means that the current solution i came up with is not optimali figured i could create an iframe and load a script inside it that script would perform a jsonp request creating a script tag which would post a message to the main page the main page would get the message execute the callback and destroy the iframe i have managed to do this sort of thingfunction jsonpurl data callback var iframe documentcreateelementiframe iframestylethisplay none documentbodyappendchildiframe var iframedoc iframecontentdocument iframecontentwindowdocument sc documentcreateelementscript sctextcontent functionp cb functionresultppostmessageresultparent sctextcontent alertcb iframedocbodyappendchildsc var jr documentcreateelementscript var getparams serialize the get parameters for var i in data getparams i datai jrsrc url callbackcb getparams iframedocbodyappendchildjr windowonmessage function e callbackedata documentbodyremovechildiframe jsonp foo bar function result alertresult jsonstringifyresultthe problem is that since the iframes are on the same domain the injected script still has access to the external scope through top or parent and suchis there any way to create an iframe that can not access data on the parent scopei want to create an iframe where scripts added through script tags will not be able to access variables on the parent window and the dom i tried stuff like topparentnull but i am really not sure that is enough there might be other workarounds i tried running a for in loop but my function stopped working and i was unable to find out whynote i know optimally webworkers are a better isolated environment i know jsonp is a bad technique i even had some random guy tell me he would never use it today i am trying to create a secure environment for scenarios where you have to perform jsonp queries,['javascript'] +477284,rendering extjs 4 mvc application in a html div howto all examples that i have found so far explain how to render extjs 42 mvc application within the viewport which in other words means full browser screen and occupying whole html bodyi would like to render application within the existing html page within named div so that i can have html design around the application div idappdiv application runs here divi have seen some sites with extjs 4 examples that use trick to render extjs app within the page by using iframe is it possible to avoid iframe and if it is how skeleton of extjs 42 application shall look like if it will be rendered within a div notes in extjs 3 i have found the solution by creating a panel as main container which renders within named div however version 42 and possibly earlier 4xs suggests mvc application approach that seem far superior editsi have realised that i have to put starting points for this questionsource for this example is generated by extjss cmd command that generates application framework skeletonskeleton of application is consisted of many files including engine reference and other references so i would not be able to include here all sources in application dirfolder skeleton of application can be done using cmd in the fashion sencha sdk myuserrootsenchacmd311274 generate app extgenapp mywebroothtdocsextja genapp this generates files and folders and copies all necessary files in the placeuser activity area is in app dir app dir has subdirs for views controllers models and additional stuff as in many other frameworks you are expected to keep folder structure so that framework can find appropriate files and initialise themlist of filesindexhtml in the root of the generated application doctype html html head meta charsetutf8 titleextgenapptitle xcompile xbootstrap link relstylesheet hrefbootstrapcss script srcextextdevjsscript script srcbootstrapjsscript xbootstrap script srcappappjsscript xcompile head body h1html beforeh1 div idappboxdiv h1html afterh1 body htmlappappjs this file is generated and updated by sencha cmd you can edit this file as needed for your application but these edits will have to be merged by sencha cmd when it performs code generation tasks such as generating new models controllers or views and when running sencha app upgrade ideally changes to this file would be limited and most work would be done in other places such as controllers if sencha cmd cannot merge your changes and its generated code it will produce a merge conflict that you will need to resolve manually do not delete this directive is required for sencha cmd packages to work require packageoverrides extapplication name extgenapp views main appboxview controllers main launch function new extviewappboxview renderto appbox generates error note originally there is no launch function but there is auto generate viewport one gets that by default generatorappcontrollermainjs extdefineextgenappcontrollermain extend extappcontroller appviewappboxviewjs extdefineextgenappviewappboxview extend extpanelpanel requires exttabpanel extlayoutcontainerborder layout type border items region west xtype panel title west width 150 region center xtype tabpanel items title center tab 1 this shall be initial layout on the screen afaik and finallyappviewmainjs extdefineextgenappviewmain extend extcomponent html hello world which shall as i understood be the contentas is it generates an error of not founding extviewappboxview and how it looks to me framework do not initialise the application,['javascript'] +477407,update mysql table with select query from another database i have two databases and i want to update one table with values from another database tablei am using the following query but it does not workupdate database1table1set field2 database2table1field2where database1table1field1 database2table1field1i have also tried the following query but it does not work eitherupdate database1table1set field2 select field2 from database2table1where database1table1field1 database2table1field1,"['php', 'mysql', 'sql']" +477438,how i can create android sample project in android studio is there any easy way to createimport android sample project in eclipse terminology in android studioi mean something like eclipse new projectandroid sample project dialog,['android'] +477453,function to get yesterdays date in javascript in format ddmmy i have been looking for a while to get yesterdays date in format ddmmyheres my current codevar today new datevar dd todaygetdatevar mm todaygetmonth1 january is 0var y todaygetfullyearifdd10dd0dd ifmm10mm0mm today ddmmywith this i get todays date in format ddmmy thanks sobut when i try thisvar yesterday todaygetdate1as recommended on this site somewhere else lost the link i get an error saying that getdate was not found for this objecti am using my script with sahi but i do not think it is linked as sahi has no trouble with javascriptthank you in advance,['javascript'] +477462,facebook ios sdk 351 openactivesessionwithreadpermissions completion handler called twice i have a button to share a link i am using basically two callsopenactivesessionwithreadpermissions and requestnewpublishpermissionsso this is the button action ibaction sharefacebookbuttonactionidsenderif fbsession activesession isopen nsarray permissions read friendlists email fbsession openactivesessionwithreadpermissionspermissions allowloginuiyes completionhandlerfbsession session fbsessionstate state nserror error if fb issessionopenwithstatesession state self prepareshare else show alert view with error else self prepareshare and with this i am asking for publish permission if no permissione are found in sessionvoid prepareshare if fbsessionactivesessionpermissions indexofobjectpublish actions nsnotfound fbsessionactivesession requestnewpublishpermissions nsarray arraywithobjectpublish actions defaultaudiencefbsessiondefaultaudiencefriends completionhandlerfbsession session nserror error if error self share else error else self share share just posts somethingvoid share nsmutabledictionary params dict nsmutabledictionary dictionary setting some params fbrequestconnection startwithgraphpathmefeed parametersparams dict httpmethodpost completionhandlerfbrequestconnection connection id result nserror error if result sharing succedeed do something else if error sharing failed do something else first time i try to share already logged on fb in ios6 and app already authorized completion handler of openactivesessionwithreadpermissions is being called twiceonce with fbsessionstateopen and once with fbsessionstateopentokenextended from the opensessionforpublishpermissions callas a consequence share is also called twice first time in the else part of prepareshare if i already have publish permissions and the second time in the completion handler of opensessionforpublishpermissionsso i have a double post on facebook wall just the first time i ever share in the app i also had a crash report for fbsession it is not valid to reauthorize while a previous reauthorize call has not yet completed i could not be able to make it happen againwhat is the proper way to handle this situation,"['iphone', 'ios']" +477485,jinja2 template for loop did not find another post which has the similar problem i am trying to generate some checkboxes with flask and wtforms at the moment i have got this piece of codediv classcontrolgroup pstrongcheck the enabled bri portsstrongp label classcheckbox inline formbri1value1 formbri1label label label classcheckbox inline formbri2value1 formbri2label label label classcheckbox inline formbri3value1 formbri3label label label classcheckbox inline formbri4value1 formbri4label labeldivthis works so far but now i try to do this with a simple forloop likediv classcontrolgroup pstrongcheck the enabled bri portsstrongp for and in range16 label classcheckbox inline formbrinlabel endfor divi tried with and is this even possible,['python'] +477508,aspnet mvc htmlcheckboxfor i have checkboxes in my formi added at my model using system using systemcollectionsgeneric using systemlinq using systemweb namespace corepartners site2models public class careerform public listcheckboxes employmenttype get set public class checkboxes public string text get set public bool checked get set and added at my formhtmlcheckboxformodel modelemploymenttype new id employmenttype 1 htmlcheckboxformodel modelemploymenttype new id employmenttype 2 htmlcheckboxformodel modelemploymenttype new id employmenttype 3 but i get the mistakewhats wrong,"['c#', '.net']" +477529,fragment unknown animation name objectanimator i am trying to do a flipping card animation between two fragment like in thisplaying card flip animations by usingprivate void switchfragmentfragment fragment fragmentmanager fragmentmanager getsupportfragmentmanager fragmenttransaction fragmenttransaction fragmentmanager begintransaction if fragment null fragmentequalscurrentfragment if transactionbymenu fragmenttransactionsetcustomanimationsandroidranimfade in androidranimfade out else fragmenttransactionsetcustomanimations ranimatorcard flip right in ranimatorcard flip right out fragment nextfragment fragment fragmenttransactionhidecurrentfragment fragmenttransactionshownextfragment currentfragment nextfragment fragmenttransactioncommit the transaction in iftransactionbymenu works but not in elsei would check my libs and stuff and i am currently target higher than api 11 but i still have this error message0522 113234706 eandroidruntime6801 fatal exception main0522 113234706 eandroidruntime6801 javalangruntimeexception unknown animation name objectanimator0522 113234706 eandroidruntime6801 at androidviewanimationanimationutilscreateanimationfromxmlanimationutilsjava1240522 113234706 eandroidruntime6801 at androidviewanimationanimationutilscreateanimationfromxmlanimationutilsjava1140522 113234706 eandroidruntime6801 at androidviewanimationanimationutilscreateanimationfromxmlanimationutilsjava910522 113234706 eandroidruntime6801 at androidviewanimationanimationutilsloadanimationanimationutilsjava720522 113234706 eandroidruntime6801 at androidsupportv4appfragmentmanagerimplloadanimationfragmentmanagerjava7100522 113234706 eandroidruntime6801 at androidsupportv4appfragmentmanagerimplhidefragmentfragmentmanagerjava11870522 113234706 eandroidruntime6801 at androidsupportv4appbackstackrecordrunbackstackrecordjava6100522 113234706 eandroidruntime6801 at androidsupportv4appfragmentmanagerimplexecpendingactionsfragmentmanagerjava14310522 113234706 eandroidruntime6801 at androidsupportv4appfragmentmanagerimpl1runfragmentmanagerjava4200522 113234706 eandroidruntime6801 at androidoshandlerhandlecallbackhandlerjava7250522 113234706 eandroidruntime6801 at androidoshandlerthispatchmessagehandlerjava920522 113234706 eandroidruntime6801 at androidoslooperlooplooperjava1370522 113234706 eandroidruntime6801 at androidappactivitythreadmainactivitythreadjava50410522 113234706 eandroidruntime6801 at javalangreflectmethodinvokenativenative method0522 113234706 eandroidruntime6801 at javalangreflectmethodinvokemethodjava5110522 113234706 eandroidruntime6801 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava7930522 113234706 eandroidruntime6801 at comandroidinternaloszygoteinitmainzygoteinitjava5600522 113234706 eandroidruntime6801 at dalviksystemnativestartmainnative methodandroidmanifestxmlxml version10 encodingutf8manifest xmlnsandroid packagepackagestagestackoverflow androidversioncode3 androidversionname201 usessdk androidminsdkversion11 androidtargetsdkversion17 permission androidnamepackagestagestackoverflowpermissionmaps receive androidprotectionlevelsignature usespermission androidnamepackagestagestackoverflowpermissionmaps receive usespermission androidnameandroidpermissioninternet usespermission androidnameandroidpermissionaccess network state usespermission androidnameandroidpermissionwrite external storage usespermission androidnameandroidpermissionaccess fine location usespermission androidnameandroidpermissionaccess coarse location usespermission androidnamecomgoogleandroidprovidersgsfpermissionread gservices usesfeature androidglesversion0x020 androidrequiredtrue application androidallowbackuptrue androidicondrawableic launcher androidlabelstringapp name androidthemestylesampletheme useslibrary androidnamecomgoogleandroidmaps activity androidnamepackagestagestackoverflowmyfragmentactivity androidlabelstringapp name androidlaunchmodesingletop androidscreenorientationportrait intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity metadata androidnamecomgoogleandroidmapsv2api key androidvaluemy key applicationmanifestit is been two day iam stuck with this thank you in advance,['android'] +477559,pure virtual operator i have a project for school in c and i am stuck on one part i have to overload the operators and to work with geometrical figures that was no problem but here it where it doesnat work i have to declare the operator as a pure virtual method in an abstract class that all other classes derive from includeiostreamusing namespace stdclass figabs protected int felpublic int getfel return fel virtual figabs operator 0 this is where i get an error function returning abstract class afigabsa is not allowed function figabsoperator is a pure virtual function class coord public int cx cy public coord cx cy 0 coord const int x const int y cx x cy y coord const coord din cx dincx cy dincy coord void setxconst int val cx val void setyconst int val cy val int getx return cx int gety return cy class point public coord public figabs one of the figurespublic point setx0 sety0 fel 0 pointconst int x const int y coord xy fel 0 pointconst point din coord din fel dinfel point point operator const coord vector this works perfectly when i delete the declaration from the abstract class figabs but i donat know how to make them work together int xp cx vectorcx int yp cy vectorcy return point xp yp point operator const coord vector point temp tempcx cx vectorcx tempcy cy vectorcy return temp thank you and please be patient with me it is my first contact with c,['c++'] +477562,casting a generic superclass to a subclass this is my first so question i hope it is useful enough both for readers and myself i have googled and ducked the world around with this for the past two daysi have abstract model and storage classes from which concrete model and storage classes are derivedabstract class food abstract class foodstoraget extends food abstract void setfoodt foodclass apple extends food class basket extends foodstorageapple override void setfoodapple apple save that apple to the basket no problem now i would like to be able to call a save directly on an apple instance persisting it to its basket without having to bother about the basket and have that implemented in the abstract classes the best i have found yet is thisabstract class foodt extends foodts s extends foodstoragets abstract s getstorage void save getstoragesetfoodtthis unchecked cast warning abstract class foodstoraget extends foodts s extends foodstoragets abstract void setfoodt foodclass apple extends foodapplebasket basket basket new basket or basketgetinstance override basket getstorage return basket class basket extends foodstorageapplebasket override void setfoodapple apple save that apple to the basket which works but intellij gives me a warning about the unchecked cast in save indeed i am casting from foodts to tquestion how can i implement this applesave in a typesafe wayi do not want any wildcards appearing in the client code so changing abstract void setfoodt food to abstract z extends foodts void setfoodz food is not the solution obviously i am avoiding supresswarningsunchecked alsoi am aware of java generics how to avoid unchecked assignment warning when using class hierarchy of generics cast issue and of the getput principle but i still cannot get my head around itthanks in advance,['java'] +477596,how to show loading status in percentage for ajax response i want to show the user percentage of the ajax response loaded with a progressbaris there a way to achieve itright now i am showing just an imagehere is my code sample loadingdivshowajax type get url myurl success functionresponse loadingdivhide populatedataresponse error functionx e loadingdivhide if xstatus 500 xstatus 404 alertno data found html codediv idloadingdiv img srcloadingimgpngdiv,"['javascript', 'jquery']" +477610,ssrs grey out parameter based on result from other parameter i wondered if it was possible to grey out a parameter based on the the result from another parameter in this case if specify date is set to no then start date and end date should be greyed outas you can see from the screenshot this has not happened despite setting specify date to either yes or no start date and end date will expect a value unless you tick the null value the report will run fine if both the null boxes are ticked beside both the start and end dates but if they are automatically greyed out based on no it will make the process a lot easier for usersso in short if no dates greyed out if yes thisplay is this possible and if so howmany thanks in advance for any replies,['sql'] +477691,android navigation drawer i was trying to explore the new navigation drawer that is standardized by google finally we have the official code as well i was trying to understand the best way to implement the same in my appmy structure of the app is as followsmainactivityfeatured tabfavorites tabon clicking of any element in either tab it will take me belowcontentactivityinfo tabmap tabnow what i am confused is all the above has to be placed into the new view for the nav drawerand as the nav drawer structure is something like thisan activity with a layout which contains navdrawview and intern it contains contentlayout and drawer layout on clicking an option in the drawer should i replace the content layout all together or should i open a new activity,['android'] +477714,ssl pinning on ios to improve my apps security and protect the user from mitm attacks i am trying to do ssl pinning with my selfsigned certificate following the content of this postso i am using the following code to compare the certificate that i get from the server with the one that bundled in the app voidconnectionnsurlconnection connection willsendrequestforauthenticationchallengensurlauthenticationchallenge challenge sectrustref servertrust challengeprotectionspaceservertrust seccertificateref certificate sectrustgetcertificateatindexservertrust 0 nsdata remotecertificatedata cfbridgingreleaseseccertificatecopydatacertificate nslogremote certificate data length dremotecertificatedata length nsstring cerpath nsbundle mainbundle pathforresourceapache oftypecrt nsdata localcertdata nsdata datawithcontentsoffilecerpath nsloglocal certificate data length dlocalcertdata length if remotecertificatedata isequaltodatalocalcertdata nsurlcredential credential nsurlcredential credentialfortrustservertrust challenge sender usecredentialcredential forauthenticationchallengechallenge else challenge sender cancelauthenticationchallengechallenge the only things that are different between my code and the one in the blog post i linked are the name and the extension cer to crt for the resource representing my certificate and the two nslogs i added that will come handy later to show what the problem isin fact when this code is executed i get this output20130522 1608531 https test5379c07 remote certificate data length 88020130522 160901346 https test5379c07 local certificate data length 1249obviously the comparison between the local and the remote certificates fails because the length of the data is different and so it also fails the pinningwhy does this happen and how could i solve this problem,['ios'] +477733,why resetting prototype does not remove the property from objects im trying to get my head around javascript prototyping possible inheritance but i am certainly missing something let us start with simple constructor function counter adding simple property and instantiation of objectfunction counter thisa first counterprototypeb secondvar counter new counterat this point countera returns first counterb returns second and counterc is of course undefined which is all understandable let us add another property to constructors prototypecounterprototypec third right now counterc would return third but weve changed our mind lets get rid of those propertiescounterprototype using simple logic while overwriting counter prototypes prototype property we would lose the properties for counter which weve added before to counterprototype but that is not the case counterc returns third i am lost here so let us try overwriting the valuecounterprototypec fourth hohohonothing changes counterc still returns thirdwhy did it not succeed to remove the properties what am i missing,['javascript'] +477788,how to cancel a request in beforesendrequest when using the iclientmessageinspector interface can i cancel a request from the beforesendrequest method returning null sends the request anyway public object beforesendrequestref message request iclientchannel channel ifcondition return null i want cancel my send else return request,['.net'] +477826,is there a pry debug setup that works with ruby 20 i am using ruby 200p195 on osx prydebugger does not work stepcontinuenext all appear to work like continue is there a pry debugging gem that works with ruby 20update prydebugger and prybyebug both appear to work with with ruby 200p195 in a simple project i have some other conflict that is causing both to fail when using bindingpry in testsupdate prybyebug is working for me with the latest ruby 20 release 200p247 with prybyebug 1 byebug 150,['ruby'] +477868,passing a type to a generic method at runtime i have something like thistype mytype typegettypefromsomewhereelsevar lists contextgetlistmytypetolisti would like to get the type which is mytype in this case and pass it to the generic type method getlistthis is the error i am gettingthe type or namespace name mytype could not be found are you missing a using directive or an assembly reference,['c#'] +477913,how to use curl to get json data and decode the data so i have a link that returns a json object and i need to have it decoded and put into variables in php urlapiphpactiongetthreadshash123fajwersanode id4order bypost dateorderdesclimit1grab contentcontent limit1this is the object that it returns count 1 threads 38752 thread id 38752 node id 4 title the shadycraft beta launch reply count 45 view count 946 user id 2 username shady post date 1366956695 sticky 0 thiscussion state visible thiscussion open 1 thiscussion type first post id 226167 first post likes 7 last post date 1369094302 last post id 228226 last post user id 2 last post username shady prefix id 19 tinhte xentag tags a4i0s9minecrafti2s4newsi3s14private serveri1s10shadycraft content count 1 content 226167 post id 226167 thread id 38752 user id 2 username shady post date 1366956695 message attachfull4143attachn nweve completely restructured shadycraft and today will be the launch of the shadycraft betan ncurrent featuresnlistntownsnnationsnall out warsna live update mapnno whitelistnearn moneyngriefing allowed where possiblenlistnthese are just some features which have a lot more things behind them for instance there is town and nation upkeep tax kingdoms mayors and kingsn nwe really wanted to have the server selfgoverned and this is why griefing and pvp are allowed where ever they are possible all towns and nations cannot be griefed by other members you can create a town and buy plots for it and expand the town as you wishn nsize4all of this is shown in the live updating map located urlhereurlsizen nsize4size6join the beta nowsizesizensize6serverip 5076116sizen and nuser118053frenchyuser and user4863wolfbaneuser ip id 747429 message state visible attach count 1 position 0 likes 7 like users a5i0a2s7user idi105699s8usernames6kvothei1a2s7user idi146724s8usernames12graveyard219i2a2s7user idi70182s8usernames9wmbrown18i3a2s7user idi5473s8usernames9obliviousi4a2s7user idi118053s8usernames7frenchy warning id 0 warning message anonymous posting real user id 0 anonymous posting real username i am really only interested in the titlethe shadycraft beta launch reply count45 view count 946 user id2 usernameshady post date1366956695 sticky0 thiscussion statevisiblethiscussion open1and finally the message attachfull4143attachweve completely restructured shadycraft and today will be the launch of the shadycraft betacurrent featureslisttownsnationsall out warsa live update mapno whitelistearn moneygriefing allowed where possiblelistthese are just some features which have a lot more things behind them for instance there is town and nation upkeep tax kingdoms mayors and kingswe really wanted to have the server selfgoverned and this is why griefing and pvp are allowed where ever they are possible all towns and nations cannot be griefed by other members you can create a town and buy plots for it and expand the town as you wishsize4all of this is shown in the live updating map located urlhereurlsizesize4size6join the beta nowsizesizesize6serverip 5076116sizeuser118053frenchyuser and user4863wolfbaneuserso how can i extract the json object and put it in to correct variables in php that i can later use variables like username user id message title thiscussionstate and so oni just need to know how i can retrieve the json object then extract the data into variables in php i am now able to get the php array but i am having some troubles calling the correct values here is the arrayarray count 1 threads array 13 array thread id 13 node id 4 title forum integration nearly complete reply count 0 view count 0 user id 59 username faeron post date 1369257302 sticky 0 thiscussion state visible thiscussion open 1 thiscussion type first post id 23 first post likes 0 last post date 1369257302 last post id 23 last post user id 59 last post username faeron prefix id 1 content array count 1 content array 23 array post id 23 thread id 13 user id 59 username faeron post date 1369257302 message it is been quite a while since we began to integrate the phanime forums with the main site we have now finished the integration with the phanime forums and the main site you will no longer notice that there are two platforms running phanime but instead only one our next step is to theme the forums to make it look like the main site ip id 268 message state visible attach count 0 position 0 likes 0 like users a0 warning id 0 warning message now lets say this array was named array then to get the first elements value count cannot i just say the following print arraycount this returns an error what about the element that has a value as an array itself which is the threads element how do i get perhaps the thread id elements value,['php'] +477918,how to kick off pubsub subscriber in rails app i have a rails web app that i need to add a rethis pubsub subscriber too below is my pubsubsubscriber class which i need to kick off then the app starts upthe rethis connection is created in a resquerb initializer file i tried pubsubsubscribernew after the connection but when i try to start the rails server it hangs at booting thin rails 3213 application starting in development on call with d to detach ctrlc to shutdown serveras opposed to when the server starts successfully booting thin rails 3213 application starting in development on call with d to detach ctrlc to shutdown server thin web server v151 codename straight razor maximum connections set to 1024 listening on 050 ctrlc to stopany idea why the server hangs when i try to instantiate the pubsubsubscriber class in the initializer is there a better place to start this up example modified from class pubsubsubscriber def initialize rethispsubscribe channel one do on onpsubscribe do event total end onpmessage do pattern event message message received kick off some workers end onpunsubscribe do event total end end endend,"['ruby-on-rails', 'ruby']" +477922,get how much time python subprocess spends i would like to time how long does the subprocess takei tried to use start timetimesubprocesscallelapsed timetime starthowever it is not very accurate not sure related to multiprocess or sth elseis there a better way i can get how much time the subprocess really spendsthank you,['python'] +477993,vector is not a template i am currently trying to follow a tutorial on making a simple 2d tile engine for topdown rpgs for some reason though i get the intellisense errorvector is not a templatethe word vector is underlined with red why does this not work why is it telling me that it is a template and why does the mean the program would not workifndef imagemanager hdefine imagemanager hinclude vectorinclude sfmlgraphicshppclass imagemanagerprivate vectorsftexture texturelistpublic imagemanager imagemanager void addtexturesftexture texture sftexture gettextureint indexendiferrors i get no doubt some of these spawn from the error of this part aboveerror 1 error c2143 syntax error missing before cusersvipardropboxcomputer scienceprogrammingvisual studio 2012projectssfmlappsfmlappimagemanagerh 10 1 sfmlapperror 2 error c4430 missing type specifier int assumed note c does not support defaultint cusersvipardropboxcomputer scienceprogrammingvisual studio 2012projectssfmlappsfmlappimagemanagerh 10 1 sfmlapperror 3 error c2238 unexpected tokens preceding cusersvipardropboxcomputer scienceprogrammingvisual studio 2012projectssfmlappsfmlappimagemanagerh 10 1 sfmlapperror 4 error c2143 syntax error missing before cusersvipardropboxcomputer scienceprogrammingvisual studio 2012projectssfmlappsfmlappimagemanagerh 10 1 sfmlapperror 5 error c4430 missing type specifier int assumed note c does not support defaultint cusersvipardropboxcomputer scienceprogrammingvisual studio 2012projectssfmlappsfmlappimagemanagerh 10 1 sfmlapperror 6 error c2238 unexpected tokens preceding cusersvipardropboxcomputer scienceprogrammingvisual studio 2012projectssfmlappsfmlappimagemanagerh 10 1 sfmlapperror 7 error c2065 texturelist undeclared identifier cusersvipardropboxcomputer scienceprogrammingvisual studio 2012projectssfmlappsfmlappimagemanagercpp 22 1 sfmlapperror 8 error c2143 syntax error missing before cusersvipardropboxcomputer scienceprogrammingvisual studio 2012projectssfmlappsfmlappimagemanagerh 10 1 sfmlapperror 9 error c4430 missing type specifier int assumed note c does not support defaultint cusersvipardropboxcomputer scienceprogrammingvisual studio 2012projectssfmlappsfmlappimagemanagerh 10 1 sfmlapperror 10 error c2238 unexpected tokens preceding cusersvipardropboxcomputer scienceprogrammingvisual studio 2012projectssfmlappsfmlappimagemanagerh 10 1 sfmlapp 11 intellisense vector is not a template cusersvipardropboxcomputer scienceprogrammingvisual studio 2012projectssfmlappsfmlappimagemanagerh 10 2 sfmlapp,['c++'] +478024,back button on uiwebview i am trying to figure out how to create a back button that allows the user to go back one page i read through apples docs which still go way over my head and found out that i need to setup the cangoback and gobacks i have tried this but for some reason it is not working my uiwebview is named viewweb and i created and attached an outlet to my back button named backbutton and also tagged it as 1 here is my code that i wrote in the view controller back buttonvoidactionsheetuiactionsheet actionsheet clickedbuttonatindexnsintegerbuttonindex if buttonindex 1 backbutton addtarget viewweb actionselectorgoback forcontroleventsuicontroleventtouchdown if viewweb cangoback nslogback button pressed viewweb goback else returndoes anyone know what i need to change add to get this working,"['ios', 'objective-c']" +478096,when to use wildcards in java generics this is from headfirst java page 575 thispublic t extends animal void takethingarraylistt listdoes the same thing as thispublic void takethingarraylist extends animal listso here is my question if they are exactly same why do not we writepublic extends animal void takethingarraylist listorpublic void takethingarraylistt extends animal listalso when would it be useful to use a instead of a t in a method declaration as above with generics or for a class declaration what are the benefits,['java'] +478111,count how many rows have the same value how do i write an sql query to count the total number of a specific num value in the num column of a tableeg select where num 1result 2 name num sam 1 bob 1 jake 2 john 4,"['mysql', 'sql']" +478174,arp request and reply using c socket programming i am trying to receive and send arp packets using c programming in linux ubuntumy program works fine ie runs without any error but i cannot trace the packets using wireshark source code include syssockethinclude sysioctlhinclude systimehinclude asmtypeshinclude mathhinclude stringhinclude stdiohinclude stdlibhinclude unistdhinclude signalhinclude linuxif packethinclude linuxif etherhinclude linuxif arphdefine buf size 42define device eth0define eth p null 0x0define eth mac len eth alendefine eth arp 0x0806int s 0 socketdescriptorvoid buffer nulong total packets 0long answered packets 0void sigintint signumstruct attribute packed arp header unsigned short arp hd unsigned short arp pr unsigned char arp hdl unsigned char arp prl unsigned short arp op unsigned char arp sha6 unsigned char arp spa4 unsigned char arp dha6 unsigned char arp dpa4int mainvoid buffer voidmallocbuf size buffer for ethernet frame unsigned char etherhead buffer pointer to ethenet header struct ethhdr eh struct ethhdr etherhead another pointer to ethernet header unsigned char arphead buffer 14 struct arp header ah unsigned char src mac6 our mac address struct ifreq ifr struct sockaddr ll socket address int ifindex 0 ethernet interface index int i int length length of received packet int sent printfserver started entering initialiation phasen open socket s socketaf packet sock raw htonseth p all if s 1 perrorsocket exit1 printfsuccessfully opened socket in s retrieve ethernet interface index strncpyifrifr name device ifnamsiz if ioctls siocgifindex ifr 1 perrorsiocgifindex exit1 ifindex ifrifr ifindex printfsuccessfully got interface index in ifindex retrieve corresponding mac if ioctls siocgifhwaddr ifr 1 perrorsiocgifindex exit1 for i 0 i 6 i src maci ifrifr hwaddrsa datai printfsuccessfully got our mac address 02x02x02x02x02x02xn src mac0src mac1src mac2src mac3src mac4src mac5 prepare sockaddr ll socket addresll family pf packet socket addresll protocol htonseth p ip socket addresll ifindex ifindex socket addresll hatype arphrd ether socket addresll pkttype packet otherhost socket addresll halen 0 socket addresll addr6 0x00 socket addresll addr7 0x00 establish signal handler signalsigint sigint printfsuccessfully established signal handler for sigintn printfwe are in production state waiting for incoming packetsn while 1 wait for incoming packet length recvfroms buffer buf size 0 null null if length 1 perrorrecvfrom exit1 ifhtonsehh proto 0x806 unsigned char buf arp dha6 unsigned char buf arp dpa4 ah struct arp header arphead ifhtonsaharp op 0x01 continue printfbuffer is s ncharah printfhd type x proto type x naharp hdaharp pr printfhd leng x proto leng x naharp hdlaharp prl printfoperation x n aharp op printfsender mac address 02x02x02x02x02x02xn aharp sha0 aharp sha1 aharp sha2 aharp sha3 aharp sha4 aharp sha5 printfsender ip address 02d02d02d02dn aharp spa0 aharp spa1 aharp spa2 aharp spa3 ifaharp spa010aharp spa100aharp spa200aharp spa301 printfsender ip is bam bamn systemsudo arp s 101 001e7391040d printftarget mac address 02x02x02x02x02x02xn aharp dha0 aharp dha1 aharp dha2 aharp dha3 aharp dha4 aharp dha5 printftarget ip address 02d02d02d02dn aharp dpa0 aharp dpa1 aharp dpa2 aharp dpa3 printfn printfether dst mac address 02x02x02x02x02x02xn ehh dest0 ehh dest1 ehh dest2 ehh dest3 ehh dest4 ehh dest5 printfether src mac address 02x02x02x02x02x02xn ehh source0 ehh source1 ehh source2 ehh source3 ehh source4 ehh source5 memcpy voidetherhead const voidetherheadeth mac len eth mac len memcpy voidetherheadeth mac len const voidsrc mac eth mac len ehh proto eth arp printf n printfether dst mac address 02x02x02x02x02x02xn ehh dest0 ehh dest1 ehh dest2 ehh dest3 ehh dest4 ehh dest5 printfether src mac address 02x02x02x02x02x02xn ehh source0 ehh source1 ehh source2 ehh source3 ehh source4 ehh source5 aharp hd ntohsaharp hd aharp pr ntohsaharp pr aharp op 0x02 buf arp dpa0 aharp dpa0 buf arp dpa1 aharp dpa1 buf arp dpa2 aharp dpa2 buf arp dpa3 aharp dpa3 aharp dha0 aharp sha0 aharp dha1 aharp sha1 aharp dha2 aharp sha2 aharp dha3 aharp sha3 aharp dha4 aharp sha4 aharp dha5 aharp sha5 aharp dpa0 aharp spa0 aharp dpa1 aharp spa1 aharp dpa2 aharp spa2 aharp dpa3 aharp spa3 aharp spa0 buf arp dpa0 aharp spa1 buf arp dpa1 aharp spa2 buf arp dpa2 aharp spa3 buf arp dpa3 change the sender mac address aharp sha0 0x00 aharp sha1 0x1e aharp sha2 0x73 aharp sha3 0x78 aharp sha4 0x9a aharp sha5 0x0d socket addresll addr0 ehh dest0 socket addresll addr1 ehh dest1 socket addresll addr2 ehh dest2 socket addresll addr3 ehh dest3 socket addresll addr4 ehh dest4 socket addresll addr5 ehh dest5 printfn printfsender mac address 02x02x02x02x02x02xn aharp sha0 aharp sha1 aharp sha2 aharp sha3 aharp sha4 aharp sha5 printfsender ip address 02d02d02d02dn aharp spa0 aharp spa1 aharp spa2 aharp spa3 ifaharp spa010 aharp spa10 aharp spa20 aharp spa31 printf101n printftarget mac address 02x02x02x02x02x02xn aharp dha0 aharp dha1 aharp dha2 aharp dha3 aharp dha4 aharp dha5 printftarget ip address 02d02d02d02dn aharp dpa0 aharp dpa1 aharp dpa2 aharp dpa3 printfhd type x proto type x naharp hdaharp pr printfhd leng x proto leng x naharp hdlaharp prl printfoperation x n aharp op sent sendtos buffer buf size 0 struct sockaddrsocket address sizeofsocket address if sent 1 perrorsendto exit1 answered packets total packets void sigintint signum clean up struct ifreq ifr if s 1 return strncpyifrifr name device ifnamsiz ioctls siocgifflags ifr ifrifr flags iff promisc ioctls siocsifflags ifr closes freebuffer printfserver terminatingn printftotally received ld packetsn total packets printfanswered ld packetsn answered packets exit0,['c'] +478183,how to delete a module in android studio is there a way to delete a module within android studiowhen i right click on a module i cannot find an option for deletion is it elsewhere,['android'] +478205,implode data from a multidimensional array i am a novice at php and i need a quick solution to the following problem but cannot seem to come up with onei have a multidimensional array like soarray 0 array blogtags id 1 tag name google inserted on 20130522 095134 inserted by 2 1 array blogtags id 2 tag name technology inserted on 20130522 095134 inserted by 2 i want to use the implode to somehow return a commaseparated string containing values of tag name key like so google technologyis it possible to achieve this effect with the said function if not then please suggest an alternate solution,['php'] +478289,android navigation drawer over the tabs i am using the new navigation drawer available from the support library when using the drawer along with tabs the drawer menu is getting thisplayed below the tabs as shown below how can i make sure the drawer menu is shown on the tabs it should thisplay the drawer menu as if there are no tabs drawer menu without tabsdrawer menu with tabs,['android'] +478334,json date to nsdate issue i have a date string in json format it looks like this20130522t105440437and i am trying to convert it to nsdate nsstring datefromstringnsstring datestring convert string to date object nsdateformatter dateformat nsdateformatter alloc init dateformat setdateformatymmddthhmmss nsdate date dateformat datefromstringdatestring date is nil here nsdateformatter newdateformatter nsdateformatter allocinit newdateformatter setdateformatmmddy nsstring newstring newdateformatter stringfromdatedate nslogdate datestring return newstringbut date is nil after datefromstring does anyone know what i did wrong herethanks,['objective-c'] +478360,visual studios javascript code formatting in for loops the default code formatting for javascript in visual studio 2012 does this with for loopsfor var a b a c afor var a b a c afor var a b a c afor var a b a c anotice the spaces after b c b and cwhere is the option to remove those spaces or does vs just have a phobia of frowning winky faces,['javascript'] +478494,android emulator httpproxy ssl handshake failure i have a local http proxy set up for debugging json request and response data from my android application i deploy it to a nexus one emulator image running android 422 with the command line option httpproxy httplocalhost8 i am using a stock adt build v2110569685 i can validate that the http proxy can handle https connections with the following code snippet i run using groovyimport javasecuritykeystoreimport javasecuritycertcertificateimport javasecuritycertcertificatefactoryimport javaxnetsslhttpsurlconnectionimport javaxnetsslsslcontextimport javaxnetsslsslsocketfactoryimport javaxnetssltrustmanagerfactoryfileinputstream fis new fileinputstream mitmproxymitmproxycacertpem bufferedinputstream bis new bufferedinputstream fis certificatefactory cf certificatefactorygetinstance x509 keystore ks keystoregetinstance keystoregetdefaulttype ksload nulltochararray while bisavailable 0 certificate cert cfgeneratecertificate bis kssetcertificateentry mitmproxy cert systemoutprintln certtostring trustmanagerfactory tmf trustmanagerfactorygetinstance trustmanagerfactorygetdefaultalgorithm tmfinit ks sslcontext ctx sslcontextgetinstance tls ctxinit null tmfgettrustmanagers null sslsocketfactory sslfactory ctxgetsocketfactorytry string url proxy proxy new proxy proxytypehttp new inetsocketaddress 127001 8 httpsurlconnection conn httpsurlconnection new url url openconnection proxy connsetsslsocketfactory sslfactory string s new scanner conngetinputstream utf8 usedelimiter a next systemoutprintln s catch exception e eprintstacktracethis snippet fetches the https resource just fine logs the request and response unencrypted and works beautifully the proxy also works when accessing https resources from a browser configured to use it as its proxy so i am pretty sure the problem is not with the proxy based on the certificate you can tell i am using the mitmproxy but this code also works with the owasp zap proxy but with either proxy after installing the appropriate ca root certificate on the android image https requests from the image fail with the following events being logged to the mitmproxy event log12700156210 connect12700156210 400 ssl handshake error 1 unexpected eof12700156210 thisconnect handled 0 requestson the android side the following exception is thrown0523 161330109 ehttpurlconnectionclient827 network error0523 161330109 ehttpurlconnectionclient827 javaxnetsslsslhandshakeexception javaxnetsslsslprotocolexception ssl handshake aborted ssl0x2a180890 failure in ssl library usually a protocol error0523 161330109 ehttpurlconnectionclient827 error140770fcssl routinesl23 get server hellounknown protocol externalopensslssls23 clntc766 0x45dc2ba80x0523 161330109 ehttpurlconnectionclient827 at orgapacheharmonyxnetproviderjsseopensslsocketimplstarthandshakeopensslsocketimpljava4200523 161330109 ehttpurlconnectionclient827 at comintegralbluehttpresponsecachecompatlibcorenethttphttpconnectionsetupsecuresockethttpconnectionjava2190523 161330109 ehttpurlconnectionclient827 at comintegralbluehttpresponsecachecompatlibcorenethttphttpsurlconnectionimplhttpsenginemakesslconnectionhttpsurlconnectionimpljava4800523 161330109 ehttpurlconnectionclient827 at comintegralbluehttpresponsecachecompatlibcorenethttphttpsurlconnectionimplhttpsengineconnecthttpsurlconnectionimpljava40523 161330109 ehttpurlconnectionclient827 at comintegralbluehttpresponsecachecompatlibcorenethttphttpenginesendsocketrequesthttpenginejava2940523 161330109 ehttpurlconnectionclient827 at comintegralbluehttpresponsecachecompatlibcorenethttphttpenginesendrequesthttpenginejava2440523 161330109 ehttpurlconnectionclient827 at comintegralbluehttpresponsecachecompatlibcorenethttphttpurlconnectionimplgetresponsehttpurlconnectionimpljava2860523 161330109 ehttpurlconnectionclient827 at comintegralbluehttpresponsecachecompatlibcorenethttphttpurlconnectionimplgetinputstreamhttpurlconnectionimpljava1810523 161330109 ehttpurlconnectionclient827 at comintegralbluehttpresponsecachecompatlibcorenethttphttpsurlconnectionimplgetinputstreamhttpsurlconnectionimpljava2730523 161330109 ehttpurlconnectionclient827 at comehinationalmobilenetworkhttpurlconnectionclientsendhttpurlconnectionclientjava1780523 161330109 ehttpurlconnectionclient827 at comehinationalmobilenetworkappclientsendappclientjava2120523 161330109 ehttpurlconnectionclient827 at comehinationalmobilenetworkmsiclientsendmsiclientjava870523 161330109 ehttpurlconnectionclient827 at comehinationalmobileservicessimpleservicerunservicesimpleservicejava1340523 161330109 ehttpurlconnectionclient827 at comehinationalmobiletaskinittaskdoinbackgroundinittaskjava840523 161330109 ehttpurlconnectionclient827 at comehinationalmobiletaskinittaskdoinbackgroundinittaskjava10523 161330109 ehttpurlconnectionclient827 at androidosasynctask2callasynctaskjava2870523 161330109 ehttpurlconnectionclient827 at javautilconcurrentfuturetaskrunfuturetaskjava2340523 161330109 ehttpurlconnectionclient827 at androidosasynctaskserialexecutor1runasynctaskjava2300523 161330109 ehttpurlconnectionclient827 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava10800523 161330109 ehttpurlconnectionclient827 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava5730523 161330109 ehttpurlconnectionclient827 at javalangthreadrunthreadjava8560523 161330109 ehttpurlconnectionclient827 caused by javaxnetsslsslprotocolexception ssl handshake aborted ssl0x2a180890 failure in ssl library usually a protocol error0523 161330109 ehttpurlconnectionclient827 error140770fcssl routinesl23 get server hellounknown protocol externalopensslssls23 clntc766 0x45dc2ba80x0523 161330109 ehttpurlconnectionclient827 at orgapacheharmonyxnetproviderjssenativecryptossl do handshakenative method0523 161330109 ehttpurlconnectionclient827 at orgapacheharmonyxnetproviderjsseopensslsocketimplstarthandshakeopensslsocketimpljava3780523 161330109 ehttpurlconnectionclient827 20 moreother http requests get logged and recorded as expected what am i missing in the ssl setup for the android image to complete the ssl handshake with the http proxy successfully,['android'] +478590,major design differences between angular react and blaze clientside meteor i have seen the angular vs react vs meteor questions asked a number of times on the meteor side inevitably the answer to that question is an explanation of how meteor is much larger in scope has ddp deployment all the server side stuff and all the other things it providesi want to restrict this question to only the blaze engine and things where they do somewhat overlap especially where either one may provide additional features andor capability in terms of writing or structuring the client side codewhere are they complementary to each other eg what does angularjs bring to the tableassuming the above brings certain advantages how do you compensate for that if using pure meteor given that angular encourages a fairly strict separation of code on the client for mvc how should one structure good code on the client in meteor to follow its mvvm pattern does it just come inherently from having template client modules and a model,['javascript'] +478614,mutable variable is accessible from closure how can i fix this i am using typeahead by twitter i am running into this warning from intellij this is causing the windowlocationhref for each link to be the last item in my list of itemshow can i fix my codebelow is my codeautosuggestprototypeconfig function var me this var comp options var gotourl 01 var imgurl img srcicon0gif var target for var i 0 i metargetslength i target metargetsi if targetinputidlength 0 options source function query process where to get the data processmeresults set max results to thisplay items 10 matcher function item how to make sure the result select is correctmatching we check the query against the ticker then the company name comp memapitem var symbol compstolowercase return thisquerytrimtolowercase symbolsubstring0 1 compctolowercaseindexofthisquerytrimtolowercase 1 highlighter function item how to show the data comp memapitem if typeof comp undefined return spanno match foundspan if compt 0 imgurl compv else if compt 1 imgurl meformatimgurl empty else imgurl meformatimgurl compt return nspan idcompvenue imgurl span nspan idcompsymbolb comps bspan nspan idcompname compc span sorter function items sort our results if itemslength 0 itemspushobject return items the problem starts here when i start using target inside the functions updater function item what to do when item is selected comp memapitem if typeof comp undefined return thisquery windowlocationhref meformatgotourl comps targetdestination return item targetinputidtypeaheadoptions lastly set up the functions for the buttons targetbuttonidclickfunction windowlocationhref meformatgotourl targetinputidval targetdestination with cdhowies help some more code i will update the updater and also the href for the clickupdater function inner target what to do when item is selected return function item comp memapitem if typeof comp undefined return thisquery windowlocationhref meformatgotourl comps inner targetdestination return itemtarget,['javascript'] +478620,vagrant on windows w precise64 runs php very slowly so i am have vagrant set up with virtual hosts on my development machine but when i try a very simple echo of hello world it hangs for like 10 seconds before processing the file html files render very quickly where do i even start to troubleshoot this after doing some research others have complained of slow performance with php and virtualboxvagrant many have claimed that the use of the shared folder between hostguest is the cause of this i have tried changing the shared folder location so that it is not pointed at varwi have also tried removing the shared folder configuration completely by removing the configvmsynced folder statementin each case i have reprovisioned the box but still get the same performance issues at least a 10 second hang when hitting a simple php script in the web browserother things i have triedrunning the same php script from the command line this works just fine immediate responsehitting an html page from the web browser also i get a quick response this leads me to believe that the problem is somehow with the apachephp part of the stacknot sure what else to do,['php'] +478652,google play game services multiplayer with activity switching in my android game i have a turnbased multiplayer users wait for opponents in the lobby and whenever exactly 3 are matched they go to a new game room together which is another activity than the lobbythe docs suggest to let the activities extend basegameactivity but as i switch the activity while players are already connected doni need to place the connectivity parts in a service which my activity then binds tohas anyone tried already with game services how to begin if i cannot use basegameactivity,['android'] +478682,rails if has many relationship changed i have got these two classes class article activerecordbase attr accessible body issue name page image video brand ids has many publications has many docs through publicationsendclass doc activerecordbase attr accessible issue id cover id message article ids user id created at updated at issue code title template id has many publications dependent destroy has many articles through publications order publicationsposition has many edits dependent destroy accepts nested attributes for articles allow destroy falseendhow would i write a conditional statement to see if docarticles has changed after updating docif docarticleschanged endthe above gives me an error i cannot find the correct syntax,['ruby-on-rails'] +478691,lvalue required as unary aa operand i have the following lines of code define port 9987and char ptr char portthis seems to work in my server code but as i wrote it in my client code it gives this error message lvalue required as unary aa operandwhat am i doing wrong,['c'] +478695,object methods of same class have same id class parentobject classmethod def a class methodcls print in class method s cls staticmethod def a static method print static method def useless funcself pass p1 p2 parentparent idp1 idp2 false idp1useless func idp2useless func truein the above code i dont understand why is the useless func has same id when it belongs to two different objects,['python'] +478761,check if a property exists on magically set properties there is a lot of so questions about the subject notably this one but it does not help methere is an ambiguity between property exists and isset so before asking my question i am going to pointing it outproperty existsproperty exists checks if an object contains a property without looking at its value it only looks at its visibilityso in the following examplephpclass testa private a nullclass testb extends testatest new testaecho var dumpproperty existstest a true parents private property becomes invisible for its childtest new testbecho var dumpproperty existstest a falseissetisset checks if a value exists in a property considering that is is not set if a value equals false and nullphpvar nullecho var dumpissetvar falsevar echo var dumpissetvar truevar falseecho var dumpissetvar truevar 0echo var dumpissetvar truevar 0echo var dumpissetvar trueisset and property existss behaviour on magically added propertiesa property can exist with a null value so i cannot use isset magic method to know if a property exist or not i also cannot use property exists as properties are added using magic methodshere is a sample but this is just a sample because in my app properties magically set are stored outside the objectclass test private data array public function getkey echo get keyn return array key existskey data datakey null public function setkey value echo set key valuen thisdatakey value public function issetkey echo sprintfisset key returns b issetthisdatakey return issetthisdatakey test new testtestx 42issettestx 1testy nullissettesty 0property existstest y 0so here is my question is there a magic method or an spl interface to implement property exist with magically added properties,['php'] +478814,what is a reasonable order of java modifiers abstract final public static etc what is a reasonable order of java modifiersabstractfinalnativeprivateprotectedpublicstaticstrictfpsynchronizedtransientvolatileupdate i have changed the wording from recommended to reasonable in order to calm down the thiscussions whether the order is recommended or not,['java'] +478815,sqlalchemy bulk update performance problems i need to increment values in a column periodically with data i receive in a file the table has 40 rows so far all my attempts result in very poor performance i have written an experiment that reflects my requirementscreate tableengine create enginesqlitebulk updatedb echofalsemetadata metadatasometable tablesometable metadata columnid integer sequencesometable id seq primary keytrue columncolumn1 integer columncolumn2 integersometablecreateengine checkfirsttrueinitial populationconn engineconnectnr of rows 50insert data column1 i column2 0 for i in range1 nr of rowsresult connexecutesometableinsert insert dataupdateupdate data col1 i increment randint1 500 for i in range1 nr of rowsprint nr of rows nr of rowsprint start time strdatetimetimedatetimenowstmt sometableupdate wheresometableccolumn1 bindparamcol1 valuessometableccolumn2 sometableccolumn2 bindparam incrementconnexecutestmt update dataprint end time strdatetimetimedatetimenowthe times i get are thesenr of rows 10start time 102901753938end time 102916247651nr of rows 50start time 103035236852end time 103639070423so doing a 40 amount of rows will take much too longi am new to sqlalchemy but i did do a lot of doc reading and i just cannot understand what i am doing wrongthanks in advance,['python'] +478838,difference between returnbyrvalueref returnbyvalue when you return using stdmove considering the following codeinclude iostreamusing namespace stdstruct i ii rv cout imvcotr endl struct c i i i foo return movei int main c c i i cfooc contains i and cfoo allows you to move i out of c what is the difference between the member function used abovei foo return movei return rvalue refand the following replacement member functioni foo return movei return by valueto me they seem to do the same thing i i cfoo leads to a call to iwhat consequences will there be that is not covered in this example,['c++'] +478867,errorandroid dex cannot find file androidsdkpathplatformtoolslibdxjar i got the latest android sdk several days ago i encountered the problem such as the title when i build my android application with intellij idea i knew the latest android sdk move the dxjar from platformtools to a new folder called buildtools so i want to know how to fix it,['android'] +478874,msbuild item include wildcard not expanding this is very weird weve been trying to figure it out for a while but it really does not make any senseour web project imports a targets file that has a target similar to thistarget namecsscheckinternal itemgroup cssfiles includemsbuildprojectdirectorycss itemgroup csschecker filescssfiles targetat the moment one branch is building perfectly executing the task as desired but the other branch is failing on the above targetthe failure is because the cssfiles item when received by the task appears not to be expanding into an itaskitem arraythe task is written as follows up to the point where i get the fullpath metadatapublic class csschecker task required public itaskitem files get set public override bool execute string fullfilepath null if files null foreach var item in files fullfilepath itemgetmetadatafullpath iffileexistsfullfilepath throw new invalidoperationexception stringformat0 does not exist fullfilepath rest of the code elidedthe build that is failing is throwing the invalidoperationexception on the last line there like thisfile does not exist ccodeprojectcss so it would seem that msbuild instead of expanding the wildcard in the include attribute is merely passing the string over thus creating only one itaskitem on the taskthe target folder does exist on the thisk and the only difference between the broken project file and the working one is a single file include much earlier in the project fileupdatei asked sayed hashimi on twitter wrote the msbuild book and through that tried taking out the folder wildcard and it is now started working this is not really suitable as the task is meant to be reusable between projects but it would appear to be something to do with thisend updateplease if anyone knows under what situation msbuild would not correctly expand a wildcard it would be a great help,['c#'] +478911,how to get every element in a list of list of lists i am making a heart game for my assignment but i do not know how to get every element in a list of listcards qs5has2h8h7c9h5cjh7dand what comes to my mind is for values in cards for value in valuesbut i think i just got element that has 2 list how to calculate the one that has 3 and 1 list in the cards,['python'] +478945,why is there a huge performance difference between 32 and 64 bit jdk so i have been doing project euler and i found two ways to solve problem 57 however there seems to be a huge difference in performance between using a 32bit jdk and a 64bit jdk public static int fractionsolution int lint count 0for int i 1 i l i bigfraction f iteratefractionisubtractnew bigfraction11 iffgetdenominatortostringlength fgetnumeratortostringlength count return countpublic static bigfraction iteratefractionint n ifn1 return new bigfraction25 else bigfraction base new bigfraction11 bigfraction two new bigfraction21 return twoaddbasedivideiteratefractionn1 public static int patternsolution int l biginteger and new biginteger3 biginteger d new biginteger2 int count 0 for int i 1 i l i and nadmultiplynew biginteger2 d nsubtractd ifntostringlength dtostringlength count return countif i run the fractionsolution on 64 bit jdk it will take 30 seconds but on 32bit it will take 90 seconds if i run patternsolution on 64 bit jdk it will take about 80 ms but on 32 bit it will take about 40 ms why is there such a huge difference between the jdks which one should i usei am using java se 7 jdk 17here are screen caps of my program so you do not have to run it you can tell which jdk it is from the file paths,['java'] +478957,change the file extension for files in a folder in python i would like to change the extension of the files in specific folder i read about this topic in the forum using does ideas i have written following code and i expect that it would work but it does not i would be thankful for any guidance to find my mistake import ossys folder e1936342gtest for filename in oslistdirfolder infilename ospathjoinfolderfilename if not ospathisfileinfilename continue oldbase ospathsplitextfilename infile openinfilename r newname infilenamereplacegrf las output osrenameinfilename newname outfile openoutputw,['python'] +478961,referenceerror gm xmlhttprequest is not defined i get a referenceerror in the following userscript code userscript name namespace description include grant gm xmlhttprequest userscriptconsoleloggm infotry consoleloggm xmlhttprequest method get url synchronous true readystatecatch e consolelogeit first logs gm info successfully then logs the referenceerror i am using firefoxfirebugreferenceerror gm xmlhttprequest is not definedwhy do i get this error,['javascript'] +478978,how to tell thistutils to use gcc i want to wrap a test project containing c and openmp code with cython and build it with thistutils via a setuppy file the content of my file looks like thisfrom thistutilscore import setupfrom thistutilsextension import extensionfrom cythonbuild import cythonizefrom cythonthistutils import build extmodules extensioninterface interfacepyx parallelcpp language c extra compile argsfopenmp extra link argsfopenmpfor e in modules ecython directives embedsignature truesetupnameinterface cmdclassbuild ext build ext ext modulesmodulesthe fopenmp flag is used with gcc to compile and link against openmp however if i just invokecls workspacecythonopenmpsrc python3 setuppy buildthis flag is not recognized because the compiler is clangrunning buildrunning build extskipping interfacecpp cython extension uptodatebuilding interface extensioncc wnounusedresult fnocommon dynamic dndebug g o3 wall wstrictprototypes iusrlocalinclude iusrlocaloptsqliteinclude iusrlocalcellarpython30frameworkspythonframeworkversions33includepython33m c interfacecpp o buildtempmacosx108x86 6433interfaceo fopenmpclang warning argument unused during compilation fopenmpcc wnounusedresult fnocommon dynamic dndebug g o3 wall wstrictprototypes iusrlocalinclude iusrlocaloptsqliteinclude iusrlocalcellarpython30frameworkspythonframeworkversions33includepython33m c parallelcpp o buildtempmacosx108x86 6433parallelo fopenmpclang warning argument unused during compilation fopenmpparallelcpp2410 warning unknown pragma ignored wunknownpragmas pragma omp parallel for 1 warning generatedc bundle undefined dynamic lookup lusrlocallib lusrlocaloptsqlitelib buildtempmacosx108x86 6433interfaceo buildtempmacosx108x86 6433parallelo o buildlibmacosx108x86 6433interfaceso fopenmpld library not found for lgompclang error linker command failed with exit code 1 use v to see invocationerror command c failed with exit status 1i have unsucessfully tried to specify gcls workspacecythonopenmpsrc python3 setuppy build compilerg47running buildrunning build exterror do not know how to compile cc code on platform posix with g47 compilerhow can i tell thistutils to use gcc,['python'] +478983,images breaking when sending mail using smtpclient i am sending a mail using c using the smtpclient class i am doing the following things before sending the mailvar mailmessage new mailmessagemodeltoaddressesforeachto mailmessagetoaddtomailmessagesubject test email by yassermailmessagebody stringformat012 htmlbody getemailcontentmodel bodyhtmlmailmessageisbodyhtml truereturn mailservicesendemailmailmessageand below is my mailservice classpublic class mailservice public static bool sendemailmailmessage mailmessage var smtpclient new smtpclient try smtpclientsendmailmessage return true catchexception exp return false now when i send the mail the mail gets sent here is what i get as the content of the mail in outlook when i press the view source below is the content of the email with view source obviously i have kept only a part of the image datahtmlbody h1testh1 h2hello worldh2 h3missing close h3 tagh3 p a hrefwgooglecom img srcdataimagegifbase649j4aaqskzjrgabageayabgaad4q8hrxhpzgaat a pbodyhtmlso this appears brokenthe images in the mail but when i copy this source and paste it into an editor and open the file using a browser all seems good even the imagesupdate added image of the mail from outlookany ideas,"['c#', 'html']" +478995,prevent large image flickering on src change i have a problem with image flickering with large imagesin my body i have 5 imagesimg idimg1 srcimg1png width250img idimg2 srcimg2png width250img idimg3 srcimg3png width250img idimg4 srcimg4png width250img idimg5 srcimg5png width250and one i am dragging one of them with jquery ui all are changing their src and on dragend as wellfunction dragstart img2attrsrcnewimg2png img3attrsrcnewimg3png img4attrsrcnewimg4png img5attrsrcnewimg5png so fine so good but i need to use large images 20 x 20px because all images can be clicked and then they will animate to the full size of the viewport that they dont pixelatethisanimate width 1800 top 650 left 250 duration 40 easing easeoutelastic i think because of the size of every image they are flickering does anyone of you have an idea how to prevent this flickering on images if all src change at the same time thanks for your effort,"['javascript', 'jquery', 'html']" +478997,google map not showing up in android 1 it is showing empty map with grey color only with zoom in and zoom out buttons2 i extracted the sha1 key from the debugkeystore and generated the map api v2 key in the console3 i pasted that key in the manifest file4 google map api v2 switched onand i use my nexus 7 for debuggingusb debugginglogcat message failed to load map error contacting google servers this is probably an authentication issue but could be due to network errorsplease help if i went somewhere wrong in these filesandoidmanifestxmlxml version10 encodingutf8 manifest xmlnsandroid packagemetrotailors androidversioncode1 androidversionname10 usessdk androidminsdkversion10 androidtargetsdkversion17 permission androidnamemetrotailorspermissionmaps receive androidprotectionlevelsignature usespermission androidnamemetrotailorspermissionmaps receive usespermission androidnameandroidpermissioninternet usespermission androidnameandroidpermissionaccess network state usespermission androidnameandroidpermissionwrite external storage usespermission androidnamecomgoogleandroidprovidersgsfpermissionread gservices usespermission androidnameandroidpermissionaccess coarse location usespermission androidnameandroidpermissionaccess fine location usesfeature androidglesversion0x020 androidrequiredtrue application androidallowbackuptrue androidicondrawableic launcher androidlabelstringapp name androidthemestyleapptheme activity androidnamemetrotailorsmainactivity androidlabelstringapp name intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity activity androidnamemetrotailorsfactorsactivity androidlabelstringtitle activity factors activity activity androidnamemetrotailorsladiescategoryactivity androidlabelstringtitle activity ladies category activity activity androidnamemetrotailorsgentscategoryactivity androidlabelstringtitle activity gents category activity activity androidnamemetrotailorsmapactivity androidlabelstringtitle activity map activity metadata androidnamecomgoogleandroidmapsv2api key androidvalueaizasya2pmjiapfwlz2ykarnmzhykqky applicationmanifestthis the xml file of the mapactivity xml version10 encodingutf8 fragment xmlnsandroid androidididmap androidlayout widthmatch parent androidlayout heightmatch parent androidnamecomgoogleandroidgmsmapsmapfragmentmapactivityjava package metrotailors import androidosbundle import androidappactivity public class mapactivity extends activity override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity map,['android'] +479004,generating a random unique 8 character string using mysql i am working on a game which involves vehicles at some point i have a mysql table named vehicles containing the data about the vehicles including the column plate which stores the license plates for the vehiclesnow here comes the part i am having problems with i need to find an unused license plate before creating a new vehicle it should be an alphanumeric 8char random string how i achieved this was using a while loop in lua which is the language i am programming in to generate strings and query the db to see if it is used however as the number of vehicles increases i expect this to become even more inefficient it is right now therefore i decided to try and solve this issue using a mysql querythe query i need should simply generate a 8character alphanumeric string which is not already in the table i thought of the generatecheck loop approach again but i am not limiting this question to that just in case there is a more efficient one i have been able to generate strings by defining a string containing all the allowed chars and randomly substringing it and nothing more any help is appreciated,"['mysql', 'sql']" +479006,what is the difference between htmlvalueforxxpropertyname and modelpropertyname htmlvalueforxxpropertyname modelpropertynameit seems like these two razor commands do the exact same thing is there any special circumstance or benefit of using one over the other,"['c#', 'asp.net']" +479074,joomla controller task that returns json data i have the task run in my controller i want it to return json data as it stands i am getting my json data wrapped inside the template html how do i tell joomla to just return json data from the controller this is the function i havepublic function run jfactorygetdocumentsetmimeencoding applicationjson jresponsesetheadercontentthispositionattachmentfilenameprogressreportresultsjson jrequestsetvartmplcomponent data array foo bar echo json encode data and this returnshtml xmlns xmllangengb langengb dirltrheadbody classcontentpanediv idsystemmessagecontainerdiv foobarbodyhtmli would like to getfoobar,['php'] +479120,eclipse cdt plugin for running tests and browsing report googles answers hear hear and eclipse market place search results on this topic simply drive me crazy and apparently the proposed so answers are not really helpful eitheri am looking for an eclipse plugin that allows me to browse a junit report xml compliant unit test report produced from a google test runnernice to have featuresjump to the source from failure reportsrun the tests automatically after buildingi am pretty sure a free plugin suitable for eclipse cdt exists that realizes these requirements i am just too stupid to find it may be any smarter guygal here,['c++'] +479124,rest api test cucumber steps best practice trying to write up cucumber feature steps for rest api testi am not sure which approach is bettergiven i log in with username and passwordwhen i add one tv into my cartand i check my cartthen i should see the item tv is in my cartorgiven the client authenticate with username and passwordwhen the client send post to cartadd with body item body then the response code should be 200and the response body should expect success truewhen the client send get to cart then the response code should be 200and the response body should expect items tvis there any convention to follow when people trying to write cucumber steps for rest api,['ruby'] +479196,where do we find the restrospector tool mention in wwdc 2012 session 208 wwdc 2012 session 208 is about uikit state preservation and restoration pretty much at the end the debugging tool restrospector is mentioned it should visualize the persisted state on thiskthe state itself is persisted to the file datadata in the saved application state directory when you open it it is an xml file but part of it are not human readablei did search the apple developer forums and developer site but there were only people asking for this tool as well but nobody had an answer maybe stack overflow can help,"['ios', 'objective-c']" +479238,ngclick does not fire javascript global function i am new to angularjs and i have put an ngclick on a radio button generated byngrepeat and the click event refuses to fire if i use a simple onclickthat does work thoughthis works and i see the alertdiv claspan2 leftjustify ngrepeatchoice in physicalmode choices input typeradio namephysical layer value choiceprivate onclickalertfoo required ngmodelparentnetworkoptionsphysicalmode nbspspan ngbindchoicepublicspandivbut this does notdiv claspan2 leftjustify ngrepeatchoice in physicalmode choices input typeradio namephysical layer value choiceprivate ngclickalertfoo required ngmodelparentnetworkoptionsphysicalmode nbspspan ngbindchoicepublicspandivcan i not do this with an ngclick or am i misunderstanding what an expression isthanksmike,['javascript'] +479242,how can i debug an android style inheritance issue when doing web development you can inspect an element and see which classes provide which css rules is there an equivalent for android developmenttldr heres an example of a style inheritance problem that i had and solvedi had a dialog has the holo theme but the text color was dark even when i tried to set the text color to whitethis is the dialog layoutxml version10 encodingutf8relativelayout xmlnsandroid androidlayout widthwrap content androidlayout heightwrap content listview androididandroididlist androidlayout widthwrap content androidlayout heightwrap content stylestylethemedialogrelativelayoutin the stylexml resourcestyle namethemedialog parentandroidstylethemeholodialog item nameandroidwindowtitlestyleandroidstyletextappearancelargeitem item nameandroidtextcolorcolorsolid whiteitem item nameandroidwindownotitletrueitemstyleit turned out that i was using a fragment whose activity was a listactivity and it defined getview which created the view from an xml style that set the text color to be dark it would have liked to see what was setting the text color,['android'] +479245,uicollectionview scrolling is slow i have just created a uicollectionview in which the user can add images from their phone to the photo album feature in the app i have the images save to the a subdirectory in the documents directory so more can be added and removed however when i scroll up and down the collection view it is very laggy how can i make the scroll nice and smoothmy code the first 16 images are preset images everything after that are from a subdirectory in documents directory uicollectionviewcell collectionviewuicollectionview collectionview cellforitematindexpathnsindexpath indexpath collectioncell cell collectionview dequeuereusablecellwithreuseidentifiercustom forindexpathindexpath current index number int indexindexpathsection noofsection indexpathrow check if its the preset photos ifindex16 nsstring namerecipephotos objectatindexindexpathsection noofsection indexpathrow cellimageviewimageuiimage imagenamedname not preset photos so retrieve the photos the user added else nsdata data nsdata datawithcontentsoffilerecipephotos objectatindexindex uiimage theimageuiimage imagewithdatadata cellimageviewimagetheimage datanil return celltime profiler gave me thisrunning time self symbol name5680ms 631 00 main thread 0x40483200ms 355 00 pthread start 0x405e3200ms 355 00 thread start3200ms 355 00 pthread start3200ms 355 00 0x1084be9603100ms 344 10 0x1084be6f070ms 07 00 mach msg20ms 02 20 objc msgsend10ms 01 10 nsautoreleasepool release40ms 04 00 thispatch mgr thread 0x405240ms 04 00 thispatch mgr thread40ms 04 00 thispatch mgr invoke40ms 04 40 kevent30ms 03 00 thispatch worker thread2 0x62b2430ms 03 10 start wqthread30ms 03 00 thispatch worker thread2 0x62a8430ms 03 00 start wqthread30ms 03 00 pthread wqthread30ms 03 00 thispatch worker thread230ms 03 00 thispatch queue invoke30ms 03 00 thispatch queue drain30ms 03 00 thispatch client callout20ms 02 00 my io execute passive block10ms 01 00 86nspersistentuimanager writepublicplistwithopenwindowidsoptionallywaitinguntildone block invoke 083510ms 01 00 nspersistentuimanager writepublicplistdata10ms 01 00 nsurlnsurlpathutilities urlbyappendingpathcomponent10ms 01 00 nsurl getresourcevalueforkeyerror10ms 01 00 cfurlcopyresourcepropertyforkey10ms 01 00 block global 210ms 01 00 nspersistentuimanager writerecordswithwindowinfosflushingstaledata10ms 01 00 thispatch call block and release10ms 01 00 0x1084b858010ms 01 00 mach msg send10ms 01 00 mach msg10ms 01 10 mach msg trap10ms 01 00 pthread struct init 0x62a8310ms 01 00 start wqthread10ms 01 00 pthread wqthread10ms 01 10 pthread struct init10ms 01 00 start wqthread 0x62a7f,['ios'] +479254,when do you need to pass arguments to threadnew local variables defined outside of a thread seem to be visible from inside so that the following two uses of threadnew seem to be the samea foothreadnewputs a foothreadnewaa puts a foothe document gives the examplearr a b c 1 2 3threadnewabcd e f arr d e fjoinarr 1 2 3but since a b c are visible from inside of the created thread this should also be the same asarr a b c 1 2 3threadnewd e f a b c arr d e fjoinarr 1 2 3is there any difference when do you need to pass local variables as arguments to threadnew,['ruby'] +479263,what does it mean when a member function is volatile i normally see the const specifier used to indicate a const member function but what does it mean when the volatile keyword is usedvoid f volatile this compiles fine for me but i do not understand what this is for i could not find any information about this in my search so any help is appreciatedupdate to make it clear i know what volatile is for i just do not know what it means in this context,['c++'] +479308,custom model binder inheriting from defaultmodelbinder i am attempting to build a custom model binder for mvc 4 that will inherit from defaultmodelbinder i would like it to intercept any interfaces at any binding level and attempt to load the desired type from a hidden field called assemblyqualifiednameheres what i have so far simplifiedpublic class mywebapplication systemwebhttpapplication protected void application start modelbindersbindersdefaultbinder new interfacemodelbinder public class interfacemodelbinder defaultmodelbinder public override object bindmodelcontrollercontext controllercontext modelbindingcontext bindingcontext if bindingcontextmodeltypeisinterface controllercontextrequestcontexthttpcontextrequestformallkeyscontainsassemblyqualifiedname modelbindingcontext context new modelbindingcontextbindingcontext var item activatorcreateinstance typegettypecontrollercontextrequestcontexthttpcontextrequestformassemblyqualifiedname funcobject modelaccessor item contextmodelmetadata new modelmetadatanew dataannotationsmodelmetadataprovider bindingcontextmodelmetadatacontainertype modelaccessor itemgettype bindingcontextmodelname return basebindmodelcontrollercontext context return basebindmodelcontrollercontext bindingcontext example createcshtml file simplifiedmodel modelsscheduledjob begin form htmlhiddenassemblyqualifiedname modeljobgettypeassemblyqualifiednamehtmlpartial jobparameters end form the above partial jobparameterscshtml looks at the modeljobs properties and builds the edit controls similar to htmleditorfor but with some extra markup the scheduledjobjob property is of type ijob interfaceexample scheduledjobscontrollercs simplifiedhttppostpublic actionresult createscheduledjob scheduledjob scheduledjobjob here is not null but has only default valueswhen i save the form it interprets the object type correctly and gets a new instance but the properties of the object are not being set to their appropriate valueswhat else do i need to do to this to tell the default binder to take over the property binding of the specified type,['c#'] +479325,how to use crontab in android i cannot find answer to my question is it possible to run crontab to reboot android using busybox or other meanstried to run crontab and it complain about unknown uid 0tried to run reboot and it does nothingor i am asking for the impossible right now,['android'] +479329,nginx and phpfpm is downloading indexphp instead of processing it i recently installed nginx and phpfpm on a centos6 server i am able to view other php pages on my site but for some reason my indexphp file gets downloaded rather than processed like a normal php pagehere is the nginx config the default serverserver listen 80 default serverserver name examplecomcharset koi8raccess log logshostaccesslog mainlocation root varwhtml index indexphp indexhtml indexhtmerror page 404 404htmllocation indexphp root varwhtml redirect server error pages to the static page 50xhtmlerror page 500 502 503 504 50xhtmllocation 50xhtml root usrsharenginxhtml proxy the php scripts to apache listening on 12700180location php proxy pass pass the php scripts to fastcgi server listening on 12700190location php root varwhtml fastcgi pass 12700190 fastcgi index indexphp fastcgi param script filename document rootfastcgi script name include fastcgi params deny access to htaccess files if apache is document root concurs with nginxs onelocation ht deny all,['php'] +479330,difference between arraysaslistarray vs new arraylistarraysaslistia in java what is the difference between 1listinteger list1 new arraylistintegerarraysaslistia copy2listinteger list2 arraysaslistiawhere ia is array of integersi came to know that some operations are not allowed in list2 why is it sohow is it stored in memory references copywhen i shuffle the lists list1 does not affect the original array but list2 does but still list2 is somewhat confusing how arraylist being upcasted to list differs from creating new arraylistlist1 differs from 1arraylistinteger list1 new arraylistintegerarraysaslistia,['java'] +479333,difference between int array and int array in a function parameter i have seen that the array values aawill change if the function parameter is int arr or int arr where is the differenceint arrayvoid myfunctionint arr int size for int i 0 i size i arri 1int arrayvoid myfunctionint arr int size for int i 0 i size i arri 1both functions change the array valuesint main int array3 array0 0 array1 0 array2 0 myfunctionarray 3 return 0,['c++'] +479342,locationmanagerisproviderenabledlocationmanagernetwork provider is not reliable why one user of my app reported that app tells network for location is off even he did turn it on he sent me few screen shots and they made me thinklocationmanagerisproviderenabledlocationmanagernetwork provideris not working properly his phone is running android 412 and first i thought this is the cause of this issue but it was not the case he sent me a screen shot of that setting toothen i googled and found this the question seems to help me but unfortunately answer was not helpful for this case and questioner did not pursue farthermy app is related to location and have been using locationmanagerisproviderenabled to know gps and network for location is on or off i have never been told my app is not properly knowing those settings until recently he is the first user who reported the issue i learned there are another method to know gps and network for location settings by seeing securelocation providers allowed to see how this method work on his phone i wrote simple app and asked him to run this app does simple task and shows text on screenlocationmanager locationmanager locationmanagergetsystemservicecontextlocation serviceiflocationmanagerisproviderenabledlocationmanagergps provider string gpsonnelse string gpsoffniflocationmanagerisproviderenabledlocationmanagernetwork provider string networkonnelse string networkoffnstring status androidprovidersettingssecuregetstringgetcontentresolver securelocation providers allowedifstatuscontainsgps string gpsonnelse string gpsoffnifstatuscontainsnetwork string networkonnelse string networkoffnhe sent back screen shot again it looksgpsonnetworkoffgpsonnetworkonthis result did not make me happy there could be some possibilities for thisas other person questioned before this issue has been there on some phonesgoogle broke this with 412 isproviderenabled does not work on this versionalthough not documented starting 412 isproviderenabled would not work as it did beforeno google changed anything this is a bug for this particular phonenow my questions areis locationmanagerisproviderenabled still valid for android 412 and laterdoes seeing securelocation providers allowed have some drawbackspit holes when i gave up using locationmanagerisproviderenabledthanks in advanceedit1here you can download test app from google play to try or ask someone to tryedit6i removed test app since this question is answerededit2i released my app which checks network provider is usable by seeing securelocation providers allowed and got exception on limited phonesthese are acras reportsome phone running os 411javalangillegalargumentexception requested provider network does not exisit at androidosparcelreadexceptionparceljava1434 at androidosparcelreadexceptionparceljava1384 at androidlocationilocationmanagerstubproxyrequestlocationupdatesilocationmanagerjava675 at androidlocationlocationmanager requestlocationupdateslocationmanagerjava686 at androidlocationlocationmanagerrequestlocationupdateslocationmanagerjava508some phone running os 412javalangillegalargumentexception providernetwork at androidosparcelreadexceptionparceljava1439 at androidosparcelreadexceptionparceljava1389 at androidlocationilocationmanagerstubproxyrequestlocationupdatesilocationmanagerjava659 at androidlocationlocationmanager requestlocationupdateslocationmanagerjava690 at androidlocationlocationmanagerrequestlocationupdateslocationmanagerjava512i have never seen those exceptions until i changed a method to check network provider for location is usable or not so i think locationmanagerisproviderenabled is safe and seeing securelocation providers allowed is risky but this will put me back to original issue why locationmanagerisproviderenabledlocationmanagernetwork provider returns false and there is not really when securelocation providers allowed tells there is is android os poorly designed or i have just seeing issues tied only to specific but there are at least 2 of them phonesedit3i updated test app to show gpsnetwork location provider seems really usable or not by accessing with requestlocationupdatesand i thisclose 2 phones name1 sbm200sh os412 softbank mobile sharp corporation2 htx21 infobar a02 os411 kddi htcedit4i found 3rd phone3 sbm203sh os412 softbank mobile sharp corporation edit5sharp corporation is running thiscussion space for mobile developers i posted topic by presenting this so is question i hope someone at sharp corporation takes action for this i will keep this updated,['android'] +479350,how to convert a list to variable argument parameter java i have a method which takes a variable length string string as parameter i have a liststring with me how can i pass this to the method as argument,['java'] +479367,getresources from fragmentstatepageradapter inside an activity class i have this class from android samples public static class democollectionpageradapter extends fragmentstatepageradapter public democollectionpageradapterfragmentmanager fm superfm override public fragment getitemint i fragment fragment new questionfragment bundle args new bundle argsputintquestionfragmentarg object i fragmentsetargumentsargs return fragment override public int getcount return questionlistlength override public charsequence getpagetitleint position return title na position 1 i would like to change this return title na position 1to return getactivitygetresourcesgetstringrstringquestiontabtitle position 1but the activity is undefined how could i get the string resource that i need,['android'] +479369,all projects referencing subproject must install nuget package microsoftbclbuild cwindows phone 7 i am having a particularly difficult refactoring session involving a c solution with multiple projects in visual studio 2012 i needed to pull out a bunch of code into their own assemblies so that code could be shared across several projects all in the same solution however no matter what i try i get warnings for the projects that reference the new shared projects that all projects referencing shared project name must install nuget package microsoftbclbuildi have been over the dependent projects and the shared projects with a finetooth comb verifying in detail that they all use the same version and exact same dll for the microsoftbcl version 10119 and microsoftbclasync version 1016 packagessystemruntimesystemthreadingtasksmicrosoftthreadingtaskmicrosoftthreadingtasksextensionsmicrosoftthreadingtasksextensionsphonethe dll paths are all resolved and identical the xap file does build but i still get that warning telling me that microsoftbclbuild is not referenced in the dependent projects despite the fact that i can see that it isif i try instead to uninstall and then reinstall those two packages using nuget for each project involved i get references with empty paths and the warning icon for the 5 dll references involved for some reason nuget adds the references but cannot find the dlls also if i do this i find myself with the problem frequently of having projects where i get the cannot add reference error when trying to add a reference then i have close and reopen the solution and that leads to a project failed to load error so i have to edit the project file manually remove the faulty package import statements and reload the projecthow can i fix this problem and what is the general technique for avoiding this headache in the future letting nuget manage missing packages did not help at al,['c#'] +479381,caemittercell does not respect birthrate change i would like to create a particle effect which is only emitting while the user touches the screen but i cannot change the caemittercell birthrate property once is set to a non zero valuei have a subclass of uiview which sets up my caemitterlayer and my caemittercell just the way i want them i am defining two properties on that classproperty strong nonatomic caemitterlayer emitterlayerproperty strong nonatomic caemittercell emittercellthen in my view controller i am tracking touches setting the position of the emitterlayer and emittercell birthratevoidtouchesbegannsset touches witheventuievent event uitouch touch touches anyobject cgpoint tappedpt touch locationinviewtouchview nslogbegan xf yftappedptx tappedpty emitterviewemittercellbirthrate 42 emitterviewemitterlayeremitterposition tappedptvoidtouchesmovednsset touches witheventuievent event uitouch touch touches anyobject cgpoint tappedpt touch locationinviewtouchview nslogmoved xf yftappedptx tappedpty emitterviewemitterlayeremitterposition tappedptvoidtouchesendednsset touches witheventuievent event nslogending f emitterviewemittercellbirthrate emitterviewemittercellbirthrate 0 nslogended f emitterviewemittercellbirthratethe log reports that the emitterviewemittercellbirthrate changesbegan x4020 y39850ending 420ended 0when i touch the screen the emitter starts as expected the layer follows the touch but when i end the touch the emitter cell happily emits whatever value was set initially set the value set in touchesbegan whatever i do i cannot seem to be able to change the birthrate value once is set to a non zero value log reports that the values are set properly but the emitter keeps emittinghowever if i change the touchesended method to change the position of the layer after i set the birthrate on emittercell then everything works as expectedvoidtouchesendednsset touches witheventuievent event uitouch touch touches anyobject cgpoint tappedpt touch locationinviewtouchview nslogbegan xf yftappedptx tappedpty nslogending f emitterviewemittercellbirthrate emitterviewemittercellbirthrate 00 nslogended f emitterviewemittercellbirthrate emitterviewemitterlayeremitterposition tappedptcan someone please explain why,['ios'] +479394,why copy constructor is not called to copy the temporary object to the new defined object include iostreamusing namespace stdclass y public yint cout yintn yconst y cout yconst yn int main y obj1 2 line 1output yintexpected output yint yconst yquestion based on my understanding line 1 will first create a temporary object y2 and then assign the temporary object to obj1 thus i expect both yint and yconst y are called but the output from vs2010 only reports the first oneie yint why,['c++'] +479433,why declare properties on the prototype for instance variables in javascript i am trying to get my head around this black art called javascript and i must admit pretty excited about it i have been looking at code examples mainly from easeljs since that is what i will be using mainly and i am a bit confusedi think i understand the difference between using the prototype for functions or properties that are class variables and using thissomeprop for instance variables yes i understand that there are no classes in javascript the code i have looked at and am using as templates for my own code declare prototype variables and then refers to them with this iein the constructor thisname namethen a declaration objectprototypenameand later thisname freddythis is within functions called with new so in this case as i understand it this refers to the current object what puzzles me is what the prototype declaration is doing and why do we use it for instance variablesthanks daveok a bit of clarification in the following code i do not see what the prototype declaration of radius is achievingfunction constructor function mycircleradius thisradius radius mycircleprototyperadius thisarea function return 314thisradiusthisradius windowmycircle mycircle,['javascript'] +479555,hibernate two tables per one entity i have one entity user it is described by userclasshibernate creates one table per entity so when i call sessionsaveuser my data is always saved to this tablenow i need another table for data of same user type and i need to save my entity to that table onlydata structure something like thistable users 1 table string id string usernametable users 2 table string id string usernamework with thissessionsaveuser1users 1 tablesessionsaveuser2users 2 tableand in result i should have user1 in users 1 table and user2 in users 2 tabledue to system limitation i can not put these two objects in one table even creating extra field is bad ideacan i do this without subclassing using programmaticaly hibernate configuration,['java'] +479629,javascript memory leak with html5 canvas getimagedata in chrome browser for mac osx this problem was fixed in the new chrome versionversion 3501916114in chrome for mac osx canvasrenderingcontext2dgetimagedata function will make memory leaks how can i avoid this problem here is the test case and result it is only happened in chrome browser safari is okdoctype htmlhtmlhead titlecanvasrenderingcontext2dgetimagedata bug in chrometitle script typetextjavascript var g function init g documentgetelementbyidcanvasgetcontext2d gfillstyle blue gfillrect10 10 100 100 gfillstyle green gfillrect60 60 100 100 function getimagedata var i 0 whilei 100 var c ggetimagedata0010 10 delete c function todataurl var i 0 whilei 100 var c gcanvastodataurl delete c scriptheadbody onloadinitbutton onclickgetimagedatacall getimagedata 100 times then memory will grow cannot gcbuttonbutton onclicktodataurlcall todataurl 100 times it is okbuttonbrcanvas idcanvas width600px height500pxbodyhtml,['javascript'] +479653,thisplay activity as overlay window on tablets how do you present an activity as an overlay window on tablets an example of this is the new google app as seen hereimportantly i want the actionbar to be part of the window and for the activity beneath to be dimmed as seen in the screenshotthanks,['android'] +479663,phonegap facebook connect plugin settings i am using phonegap plugin to connect to facebookthis one i am confused about facebook app settings when i call fbinit i get this error messagegiven url is not allowed by the application configuration one or more of the given urls is not allowed by the apps settings it must match the website url or canvas url or the domain must be a subdomain of one of the apps domains i edited website with facebook login site url to http localhost without the space ofcourse i only added it because stackoverflow does not allow a link with localhost in it and i waited for several minutes more than one day for it to work but it is still not workingany idea how can i get it to work thanks,['javascript'] +479672,unable to write code in pydev for django project i am just the beginner in django i use pydev eclipse in windows 8 first i write a hello world program and thisplay the string in browser but when i changed the code the change in the output is not appear whatever i change nothing change in output but when i close the eclipse and shutdown the computer and restart then i change the program and run it the code output is changed but now further to change my program i again need to restart my computer what is happening,['python'] +479714,pad a string with leading zeros so it is 3 characters long in sql server 2008 i have a string that is up to 3 characters long when it is first created in sql server 2008 r2i would like to pad it with leading zeros so if its original value was 1 then the new value would be 001 or if its original value was 23 the new value is 023 or if its original value is 124 then new value is the same as original valuei am using sql server 2008 r2 how would i do this using tsql,['sql'] +479740,fontcreatefont set color and size javaawtfont i would like to create a new font object using a ttf file it is really simple to create a font object but i do not know how to set color and size because i cannot find a method for itinputstream is new fileinputstreamhelveticattffont helvetica fontcreatefontfonttruetype font is,['java'] +479781,how to export library to jar in android studio i have downloaded some library sources and would like to export it as a jar file usingandroid studio is there a way to export to jar file using android studio edit the library i want to export as jar is an android libraryit is called standout and can be downloaded from github,['android'] +479788,why does javac not optimize empty tryfinally blocks i wrote a classclass test1 void foo and another class with a lot of try and finallystatements doing nothingclass test2 void foo try finally try finally try finally try finally try finallycompiled them with javac sunjdk16037 linux3813amd64 and compared the files with odtest1class 0 066143 071541 020163 062564 072163 020061 005173 073012 020 064557 020144 067546 024157 020051 020173 005175 076412 040test2class 0 177312 137272 0 031400 010400 012 03 003415 020 0070 07 0417 0030 064474 064556 037164 01 040 024003 053051 01 041404 062157 0545 007400 064514 060 062556 072516 061155 071145 060524 066142 0545 001400 0100 067546 0557 006400 072123 061541 046553 070141 060524 0120 066142 003545 010 01 051412 072557 061562 043145 0140 066151 0545 0050 062564 072163 027062 060552 060566 0160 014 04 0405 002400 062564 072163 0462 010 0200 060552 060566 066057 067141 027547 0617 062552 072143 0220 01 065023 073141 027541 060554 063556 052057 071150 0240 073557 061141 062554 020 0010 001400 0 0 0260 0010 0 0020 002400 0400 0030 0 016400 0300 0400 0400 0 002400 133452 0400 0261 0 0320 01 07 0 06 01 0 01 0 0340 010 05 01 06 0 0204 01 06 0360 0 123443 0030 025514 123677 0030 026115 123677 0400 0030 026516 123677 0040 002072 002031 123677 0040 0420 002472 002431 130677 002400 001400 0020 001400 0 0440 004400 0050 004400 0 007400 010 007400 0 0460 012400 013400 012400 0 016400 017400 016400 0 0500 0010 003400 0 0030 0400 0 001400 004400 0520 0 015400 0050 003503 0050 041002 07 001012 0540 003502 0050 041002 07 002012 003502 0050 04 0560 01 013 0 02 014 0571why is the second class so much bigger although they both do nothing why does javac not optimize the second code is there any reason,['java'] +479794,admob invalid or nonexistent app url while creating an ad i am trying to create a housead campaign for my android application but unfortunately encountered a problem while providing an urlplease find error message belowthere were problems with your submissioninvalid or nonexistent app urlwhat is strange when i provide an address for any website not linking to google play application followed by http there is no problem at allhas anyone of you also encounter such a bug on admob websitefor your information i have checked this behavior on google chrome ie7 and firefox no changethis may be possibly a duplicate ofadmob cannot create any ads admob wizard crappy but i have decided to find a solution in new threadbest regardsbartosz ostrowski,['android'] +479807,what is the difference between rubys openuri and nethttp gems it seems like both of these gems perform very similar tasks can anyone give examples of where one gem would be more useful than the other i do not have specific code that i am referring to i am more wondering about general use cases for each gem i know this is a short question i will fill in the blanks upon request thanks,['ruby'] +479823,does pandas support quarterly dates of the form yqp eg 2013q2 i am importing a csv of macroeconomic data and have not been able to figure out how to get pandas to interpret this type of date is there a way to do it automatically or will i need to parse it myselfwhen i ask the parser to try i get file datetimepxd line 133 in datetime string to dts pandastslibc31399valueerror unable to parse 2002q1,['python'] +479859,java skipping a line when reading user input into an array for loop heres my code the objective is to enter some basic info age name gender for x number of patients public static void mainstring args int numpatients 2 int age new intnumpatients string gender new stringnumpatients string name new stringnumpatients scanner in new scannersystemin obtaining patients details name gender age first create a scanner input variable to read the data for int i 0 i numpatients i systemoutprintlnenter name of patient i1 namei innextline systemoutprintlnenter gender malefemale of patient i1 genderi innextline systemoutprintlnenter age of patient i1 agei innextint the issue i am having is when the loop goes to the 2nd variable ie i am not able to enter a value for the name of the patient it seems to skip taking the input there and goes directly to the next input which is gender enter name of patient 1markenter gender malefemale of patient 1maleenter age of patient 134enter name of patient 2 skipped could not enter input hereenter gender malefemale of patient 2jennaany idea why that happens is it better to use bufferedreader instead,['java'] +479860,what is the optimal way to find words in a string in any order with regex in c so i have a string i have a big red cari want a user to be able to put in part of the string in any order so they can write car big red and the string will be found i know i can do this by doing multiple ismatch calls with a regex string or i could use one string with anchors such as carredbig i was wondering what would be the best option or is there an even better optionnote i am using c so any net regex should workall suggestions are welcome,['c#'] +479883,sorting algorithm to keep equal values separated psychology experiments often require you to pseudorandomize the trial order so that the trials are apparently random but you do not get too many similar trials consecutively which could happen with a purely random ordering let us say that the visual thisplay on each trial has a colour and a sizethisplay list colours 0 red 1 blue 2 green 3 yellowsizes 1 20 2 20 3 20 4 20 5 20 6 20for i in range120 thisplay listappendcolour coloursi 4 size sizesiprintthisplay listand we can look at the maximum number of consecutive trials that has the same value for either property using this functiondef consecutive propertiesseq field longest run 0 prev value none current run 0 for d in seq if dfield prev value current run 1 else current run 1 if current run longest run longest run current run prev value dfield return longest runoutput printconsecutive colours consecutive propertiesthisplay list colourconsecutive colours 1 printconsecutive sizes consecutive propertiesthisplay list sizeconsecutive sizes 20are there any algorithms you know of that would allow minimizing the consecutive runs of either or both properties or at least keep these runs below a specified length if the latter let us say no more than 4 in a row of the same colour or sizewhat i have triedthe solution i have now basically does a slightly intelligent bogosort which has to be horribly inefficient basicallyyou break the entire list into chunks containing all the permutations of the properties if you break down thisplay list into chunks of length 24 each chunk has each colour paired with each size let us assume that the trial list can always be broken down into these permutation chunks since you know what the permutations are from the design of the experimentyou choose a maximum run length per chunkyou shuffle each chunk until the run lengths for each chunk are below the maximum value this actually means that in the overall trial list your runs might be double that length since you could have a run of this length at the end of one chunk and the start of the next,['python'] +479896,core data reverts to previous state without apparent reason a few customers of a core data based ios application report that they occassionally lose data the reports are very odd which is the reason i would like to ask for your take on this the customers report that when they reopen the application after some time minutes hours or next day some of their data is lost as if the underlying database reverted to a previous statei have been working with core data for several years and have never run in an issue like this before the application is fairly simple which means i only use one managed object context and the changes are committed before the application goes to the backgroundi realize that this is a long shot but what could be some potential causes of this type of problem or what checks can i make to gather more information unfortunately i cannot reproduce the issue myself which would make all this a lot easierupdate nspersistentstorecoordinator persistentstorecoordinator if persistentstorecoordinator return persistentstorecoordinator nsurl storeurl self applicationdocumentsdirectory urlbyappendingpathcomponentprimesqlite nserror error nil persistentstorecoordinator nspersistentstorecoordinator alloc initwithmanagedobjectmodelself managedobjectmodel if persistentstorecoordinator addpersistentstorewithtypenssqlitestoretype configurationnil urlstoreurl options nsmigratepersistentstoresautomaticallyoption yes nsinfermappingmodelautomaticallyoption yes errorerror error handling return persistentstorecoordinator,['ios'] +479905,efficient linq to entities query i have an entity collection of readingseach reading is linked to an entity called meterand each meter holds multiple readingseach reading holds a field for meter id int and a field for timehere is some simplified code to demonstrate itpublic class reading int id int meterid datetime timepublic class meter int id icollectionreadings readings given a specific period and list of meterids what would be the most efficient way to get for each meterthe first and last reading in that time periodi am able to iterate through all meters and for each meter to obatinfirst and last reading for the periodbut i was wandering if there is a more efficient way to acheive thisand a bonus question same question but with multiple periods of time to get data forinstead of just one period,"['c#', '.net']" +479943,understanding popencommunicate i have a script named 1stpy which creates a repl readevalprintloopprint something to printwhile true r raw input if r n print exiting break else print continuingi then launched 1stpy with the following codep subprocesspopenpython1stpy stdinpipe stdoutpipeand then tried thisprint pcommunicate0it failed providing this tracebacktraceback most recent call last file 1stpy line 3 in module r raw inputeoferror eof when reading a linecan you explain what is happening here please when i use pstdoutread it hangs forever,['python'] +479967,implementations of emoji emoticon viewkeyboard layouts i am trying to figure out how the emoji emoticon selections are implemented on the facebook app and the google hangouts app i looked into the softkeyboard demo app in the android api samples but the thisplay of these emoji views does not look like a softkeyboard it looks and behaves more like a custom dialog view does anyone have an idea of how these are implemented facebook appgoogle hangouts appalso is unicode the best way to send emoticons or is there an alternative i noticed that some unicode sequences like u1f601 do not render the corresponding emoticon and instead that sequence just shows up as 1 edittext messageinput edittext findviewbyidridmessage inputmessageinputgettextappendu1f601,['android'] +479995,cython python and keyboardinterrupt ignored is there a way to interrupt ctrlc a python script based on a loop that is embedded in a cython extensioni have the following python scriptdef main intantiate simulator sim pysimulator simrunif name main try to deal with ctrlc to abort the running simulation in terminal does not work try sysexitmain except keyboardinterrupt systemexit print n received keyboard interrupt quitting threadsnthis runs a loop that is part of a c cython extensionthen while pressing ctrlc the keyboardinterrupt is thrown but ignored and the program keeps going until the end of the simulationthe work around i found is to handle the exception from within the extension by catching the sigint signal include execinfohinclude signalhstatic void handlerint sig catch exceptions switchsig case sigabrt fputscaught sigabrt usually caused by an abort or assertn stderr break case sigfpe fputscaught sigfpe arithmetic exception such as divide by zeron stderr break case sigill fputscaught sigill illegal instructionn stderr break case sigint fputscaught sigint interactive attention signal probably a ctrlcn stderr break case sigsegv fputscaught sigsegv segfaultn stderr break case sigterm default fputscaught sigterm a termination request was sent to the programn stderr break exitsigthen signalsigabrt handlersignalsigfpe handlersignalsigill handlersignalsigint handlersignalsigsegv handlersignalsigterm handlercannot i make this work from python or at least from cython instead as i am about to port my extension under windowsmingw i would appreciate to have something less linux specific,['python'] +480007,visual studio c code formatting return type classnamefunc indentation i am using visual studio 2012 for developing c code i am used to format my code as follows voidsomethingdoessomething brilliant code however when using vs2012 code formatter it always turns my code into thisvoid somethingdoessomething still brilliantis there a way to avoid this indentation of the classnamefunc in the line below the return type without completely turning off auto indentation,['c++'] +480021,function pointer to different functions with different arguments in c i have two functions with variable number and types of argumentsdouble my func onedouble x double a double b double c return x a b c double my func twodouble x double p double c return x p0 p1 c i want to use a pointer to a function to the functions i defined above based on a some condition getting true egif true condition 1 pfunc my func oneelse if true condition 2 pfunc my func two the function that will use the function i passed to it swap functiona b pfuncmy question is for this scenario can i at all define a function pointer if yes howmy understanding is that the prototype of function pointer should be the same for all those functions it can be pointed totypedef double pfunctionint intin my case they are not the same is there any other way to do thislanguagei am developing in c and i am using gcc 443 compilerlinker,['c'] +480088,ruby unable to parse a csv file csvmalformedcsverror illegal quoting in line 1 ubuntu 1204 ltsruby ruby 193dev 20110923 revision 323 i686linuxrails 329following is the content of my received csv filedatetimesettlement idtypeorder idskudescriptionquantitymarketplacefulfillmentorder cityorder stateorder postalproduct salesshipping creditsgift wrap creditspromotional rebatessales tax collectedselling feesfba feesother transaction feesothertotalmar 1 2013 120354 am pst5481545091order10809385677009852als2gl36ledsolar two directional 36 bright white led security flood light with motion activated sensor1amazoncomamazonpasadenaca911041056430032503250645375003280however when i am trying to parse the csv file i am getting error193dev 016 options col sep quote char col sep quote char 193dev 022 csvforeachtmpmy datacsv options row puts row csvmalformedcsverror illegal quoting in line 1 from homejigneshgohelrvmrubiesruby193rc1libruby191csvrb1925in block 2 levels in shift from homejigneshgohelrvmrubiesruby193rc1libruby191csvrb1887in each from homejigneshgohelrvmrubiesruby193rc1libruby191csvrb1887in block in shift from homejigneshgohelrvmrubiesruby193rc1libruby191csvrb1849in loop from homejigneshgohelrvmrubiesruby193rc1libruby191csvrb1849in shift from homejigneshgohelrvmrubiesruby193rc1libruby191csvrb1791in each from homejigneshgohelrvmrubiesruby193rc1libruby191csvrb1208in block in foreach from homejigneshgohelrvmrubiesruby193rc1libruby191csvrb1354in open from homejigneshgohelrvmrubiesruby193rc1libruby191csvrb1207in foreach from irb22 from homejigneshgohelrvmrubiesruby193rc1binirb16in mainthen i tried simplifying the data ienameageemailjignesh30however still i am getting the same error 193dev 023 csvforeachtmpmy datacsv options row puts row csvmalformedcsverror illegal quoting in line 1 from homejigneshgohelrvmrubiesruby193rc1libruby191csvrb1925in block 2 levels in shift from homejigneshgohelrvmrubiesruby193rc1libruby191csvrb1887in each from homejigneshgohelrvmrubiesruby193rc1libruby191csvrb1887in block in shift from homejigneshgohelrvmrubiesruby193rc1libruby191csvrb1849in loop from homejigneshgohelrvmrubiesruby193rc1libruby191csvrb1849in shift from homejigneshgohelrvmrubiesruby193rc1libruby191csvrb1791in each from homejigneshgohelrvmrubiesruby193rc1libruby191csvrb1208in block in foreach from homejigneshgohelrvmrubiesruby193rc1libruby191csvrb1354in open from homejigneshgohelrvmrubiesruby193rc1libruby191csvrb1207in foreach from irb23 from homejigneshgohelrvmrubiesruby193rc1binirb16in mainagain i tried simplifying the data like thisnameageemailjignesh30and it workssee the output below 193dev 024 csvforeachtmpmy datacsv row puts row name age email jignesh 30 nil but i will be receiving the csv files having quoted data so removing quotes solution is not actually i am looking fori am unable to figure out what is causing the error csvmalformedcsverror illegal quoting in line 1 in my earlier examplesi have verified that in the csv there are no leadingtrailing spaces by enabling show whitespace characters and show line endings in my text editoralso i have verified the encoding using following 193dev 026 fileopentmpmy datacsvreadencoding encodingutf8 note i tried using csvread too but same error with that methodcan anybody please help me getting out of the problem and make me understand where it is going wrongi just found following post at and tried following file data fileread file datagsub arr of arrs csvparsefile data arr of arrseach do arr railsloggerdebug arr endand got the following output xefxbbxbfdatetime settlement id type order id sku description quantity marketplace fulfillment order city order state order postal product sales shipping credits gift wrap credits promotional rebates sales tax collected selling fees fba fees other transaction fees other total mar 1 2013 120354 am pst 5481545091 order 10809385677009852 als2gl36led solar two directional 36 bright white led security flood light with motion activated sensor 1 amazoncom amazon pasadena ca 911041056 4300 325 0 325 0 645 375 0 0 3280which messed up reading the data properly as the default col sep used is a comma characterhowever i tried using quote char option like this arr of arrs csvparsefile data quote char but it ended up the following error csvmalformedcsverror illegal quoting in line 1thanksjignesh,['ruby'] +480126,bootstrap how to create a series of div on one line hiding the overflowing divs i have a site built with bootstrap and i want to create a table with swipeable header using the jquerydragscroll plugin but preserving the fluid grid builtin bootstrapso i want to create the headers of the table and i am using this htmldiv classrowfluid div claspan12 div styleoverflowhiddenwidth90 div stylethisplayinlineblockwidth100pxsome contentdiv div stylethisplayinlineblockwidth100pxsome contentdiv div stylethisplayinlineblockwidth100pxsome contentdiv div stylethisplayinlineblockwidth100pxsome contentdiv div stylethisplayinlineblockwidth100pxsome contentdiv div stylethisplayinlineblockwidth100pxsome contentdiv div stylethisplayinlineblockwidth100pxsome contentdiv div stylethisplayinlineblockwidth100pxsome contentdiv div stylethisplayinlineblockwidth100pxsome contentdiv div stylethisplayinlineblockwidth100pxsome contentdiv div stylethisplayinlineblockwidth100pxsome contentdiv div stylethisplayinlineblockwidth100pxsome contentdiv div divdivthe code is here as we can see in the fiddle all the divs are visible on two rows my objective is to have all the divs on a single row hiding the overflowing divsi hope the question is clear,['css'] +480129,listen to all onclick events of all children in jquery i can listen to all mrow click events of a div using sometihng likemydivonclick mrow function var moo thisattrid if handlersid eventstoppropagation handlersidcan i use a similar setup to listen on all click events of all the children of the div without setting up separate listeners for every type some part of the tree have handler functions and some do not and i want these requests to propagate up within the div until one that has a handler is found,['jquery'] +480236,calculate time difference between pandas dataframe indices i am trying to add a column of deltat to a dataframe where deltat is the time difference between the successive rows as indexed in the timeseries valuetime 20120316 2350 120120316 235600 220120317 0800 320120317 0010 420120317 001200 520120317 0020 620120320 004300 7desired result is something like the following deltat units shown in minutes value deltattime 20120316 2350 1 020120316 235600 2 620120317 0800 3 1220120317 0010 4 220120317 001200 5 220120317 0020 6 820120320 004300 7 23,['python'] +480248,why does s3 using with boto and djangostorages give signed url even for public files this is strange i have mix of public as well as private files i want normal urls in public files and signed urls in private filesi tried to change aws querystring auth to false as i see by default it is true in djangostorages but when i change it my private files url is not signed thus not accessiblemay be i am missing something here what can be solutionthanks in advance,['python'] +480271,legal calls and determination of overloaded functions in java i am doing some selfstudy over the summer and i came across this problem i am unsure of and i was wondering if anyone could help out i am unsure of the last number but i included my previous answers if anyone would be willing to check those as well this is not homework for any class i just want to make sure i understand what i am doing before i move forwardi am considering the following definitions1 void m object o long x long y2 void m string s int x long y3 void m object o int x long y4 void m string s long x int ywhich these declarationsobject ostring vint along band i am examining these callsmvab calls 2 because it is the most specificmvaa not legal because 2 and 4 could both be called not specific enoughmvba calls 4 because it is the most specific mvbb calls 1 because it is the only one that will fit long cannot shorten to intmobb calls 1 similar reasoning as above answermoaa unsure i am not sure of the precedencethanks in advance,['java'] +480321,python module object is not callable calling method in another file i have a fair background in java trying to learn python i am running into a problem understanding how to access methods from other classes when they are in different files i keep getting module object is not callablei made a simple function to find the largest and smallest integer in a list in one file and want to access those functions in another class in another fileany help is appreciated thanksclass findtherange def findlargestself list candidate list0 for i in list if i candidate candidate i return candidate def findsmallestself list candidate list0 for i in list if i candidate candidate i return candidate import random import findtherange class driver numberone randomrandint0 100 numbertwo randomrandint0100 numberthree randomrandint0100 numberfour randomrandint0100 numberfive randomrandint0100 randomlist numberone numbertwo numberthree numberfour numberfive operator findtherange largestinlist findtherangefindlargestoperator randomlist smallestinlist findtherangefindsmallestoperator randomlist printlargestinlist is the largest number in the list smallestinlist is the smallest number in the list,['python'] +480346,in java why is assert a keyword and not a method why is assert in java a keyword and not a methodthe method assert could look like thispublic static void assertboolean condition ifcondition throw new assertionerror,['java'] +480351,http get with headers using resttemplate how can i send a get request using the spring resttemplateother questions have used post but i need to use getwhen i run this the program continues to work but it seems that the network is clogged because this is in an asynctask and when i try to run another asynctask after i click on the button for this one they would not worki tried doing string url whitespace1 multivaluemapstring string map new linkedmultivaluemapstring string mapaddbearer accesstoken httpheaders headers new httpheaders headerssetcontenttypemediatypeapplication form urlencoded copied this from somewhere else not sure what its for httpentitymultivaluemapstring string request new httpentitymultivaluemapstring stringmap headers httpmessageconverterstring stringconverter new stringhttpmessageconverter formhttpmessageconverter formconverter new formhttpmessageconverter listhttpmessageconverter msgconverters new arraylisthttpmessageconverter msgconvertersaddformconverter msgconvertersaddnew mappingjacksonhttpmessageconverter msgconvertersaddstringconverter templatesetmessageconvertersmsgconverters setsearchresponsedata is my custom class to store the incoming json responseentitysetsearchresponsedata result templateexchangeurl httpmethodget request setsearchresponsedataclass if i was using post i could have done setsearchresponsedataresponse resttemplatepostforobjecturl request setsearchresponsedataclass,['android'] +480388,rails how to populate parent object id using nested attributes for child object and strong parameters i have got a situation much like is presented in railscast 196197 nested model form however i have encountered a conflict between this approach and strong parameters i cannot figure out a good way to populate the parent record id field on the child object since i do not want that to be assignable through the form to prevent users from associating child records to parent records they do not own i have a solution see code below but this seems like the kind of thing rails might have a clever easy way to do for meheres the codethere is a parent object call it survey that has many child objects call them questions appmodelssurveyrbclass survey belongs to user has many questions accepts nested attributes for questionsend appmodelsquestionrbclass question validates survey id presence true belongs to surveyendthere is a form that allows users to create a survey and the questions on that survey at the same time for simplicity the code below treats surveys as though they have only question appviewssurveysedithtmlerb form for survey do f flabel name ftext field name br ffields for questions do builder builderlabel content question buildertext area content rows 3 br end fsubmit submit end the problem is the controller i want to protect the survey id field on the question record via strong parameters but in doing so the questions do not pass validation since the survey id is a required field appcontrollerssurveys controllerrbclass surveyscontroller def edit survey surveynew surveyquestionsbuild end def create survey current usersurveysbuildsurvey params if surveysave redirect to survey else render new end end private def survey params paramsrequiresurveypermitname questions attributes content endendthe only way i can think to solve this problem is to build the questions separately from the survey like thisdef create survey current usersurveysbuildsurvey params if surveysave if paramssurveyquestions attributes paramssurveyquestions attributeseach value do q question params actioncontrollerparametersnewq surveyquestionsbuildquestion paramspermitcontent end end redirect to survey else render new endendprivatedef survey params paramsrequiresurveypermitnameendrails 4 beta 1 ruby 2updateperhaps the best way to handle this problem is to factor out a form object as suggested in this code climate blog post i am leaving the question open though as i am curious to other points of view,['ruby-on-rails'] +480412,do object references take up extra memory lets say you have the following complex objectvar object1 something complexedthis takes up x amount of memory in your js application now lets say you have some other objects that reference object1var otherobject something true value yes object object1 var anotherobject color f object object1 have i tripled the amount of memory that object1 originally took up or do the references to object1 not add to the overhead of the memory usedi am not sure how to test this myself in order to determine the answer bonus points if you can tell me how to point me to a tool that helps benchmark this,['javascript'] +480453,python data scraping with scrapy i want to scrape data from a website which has textfields buttons etc and my requirement is to fill the text fields and submit the form to get the results and then scrape the data points from results pagei want to know that does scrapy has this feature or if anyone can recommend a library in python to accomplish this taskeditedi want to scrape the data from the following websitemy requirement is to select the values from comboboxes and hit the search button and scrape the data points from the result pageps i am using selenium firefox driver to scrape data from some other website but that solution is not good because selenium firefox driver is dependent on firefoxs exe ie firefox must be installed before running the scraperselenium firefox driver is consuming around 100mb memory for one instance and my requirement is to run a lot of instances at a time to make the scraping process quick so there is memory limitation as wellfirefox crashes sometimes during the execution of scraper do not know why also i need window less scraping which is not possible in case of selenium firefox drivermy ultimate goal is to run the scrapers on heroku and i have linux environment over there so selenium firefox driver would not work on herokuthanks,['python'] +480501,apply effect to video frame captured by camera i noticed that there is androidmediaeffect for developer to use in api level 17 there is also a sample helloeffect for developer to render however the sample is focus on a picture i read the file of effect class and found it must apply an effect to gl textures i am new on opengl and i want to apply an effect to the video frame captured by the camera can anyone give me some hints thanks,['android'] +480521,what is the best way to execute sandboxed java code i am trying to reproduce an api for executing java like ideonecom has but so far i am having a lot of difficulties running java sandboxed selinux sandbox does not worki have heard about the securitymanager but i am trying to figure out whats the easiest way to run java code in a sandbox kind of like a java applet running in the browser instead of writing my own jail server using the securitymanager,['java'] +480543,how do i get the font name from an otf or ttf file i have used a custom font in my previous appthe file name was proximanovaregularotf and to load the font i just useduifont fontwithnameproximanovaregular size20this worked perfectlynow in this new app i have three font filesdude willieotfimpacthandseanttfbut i am not sure how to load thesei have trieduifont fontwithnamethe file name size20but this just falls back to using helveticahow can i find what name to use,['ios'] +480545,import all classes or functions in all files in folder as if they were all in the init file i have a folder with multiple files containing a lot of different classes these could all be in one big file but for the sake of making it a bit easier to read i have split it up in multiple files depending on what the classes belongs toi would like to import all classes from all files in the folder into the init file so that i can import anything from the folder without knowing in what file it belongs toexamplekitchen init py fridgepy stovepy cupboardpynow i have to dofrom kitchenfridge import milkwhen i would like to dofrom kitchen import milkthe equivalent of this i can get through in init py dofrom kitchenfridge import from kitchenstove import from kitchencupboard import and then i can dofrom kitchen import milkbut i would like it to take all files in the folder without having to specify it explicitly so that files can be dumped there and then usedis there any way of doing this,['python'] +480568,google share stopped working i have an android app and i am implementing share following these instructions i manage to get it working i came back to it the next day and i get this output in logcat g on connection failed connectionresultstatuscodesign in required resolutionpendingintent422d8470 androidosbinderproxy422d8410i have triple checked the api console removed my oauth clientid and input again fresh this has not fixed it any idea about what i can look into to fix it,['android'] +480571,what is the difference between javaeeapi and javaeewebapi i realise these dependencies are required for compiling against java servlet specification and so on but i am not clear on the differences between them and when i should use one as opposed to the otherwhat is the difference between them is one a superset of the otherdependency groupidjavaxgroupid artifactidjavaeeapiartifactid version60version scopeprovidedscopedependencydependency groupidjavaxgroupid artifactidjavaeewebapiartifactid version60version scopeprovidedscopedependency,['java'] +480584,can i force a c11 lambda to return by reference this does not compile since the lambda expression returns by valueinclude iostreamclass itempublic int freturn data private int data 0int main item item auto lambda item itemreturn itemf lambdaitem 42 lambdaitem is a rvalue compile time error stdcout itemf stdendl return 0is there a way around this can i force a lambda to return by reference,['c++'] +480613,valgrind stack misses a function completely i have two c filesacvoid main getvtablefunctionthe vtable is pointing to a function that is located in bcvoid function malloc42now if i trace the program in valgrind i get the following294 4155 bytes in 831 blocks are definitely lost in loss record 26 of 28294 at 0x402cb7a malloc in usrlibvalgrindvgpreload memcheckx86linuxso294 by 0x40a24d2 below main libcstartc226so the call to function is completely ommited on the stack how is it possible in case i use gdb a correct stack including function is showndebug symbols are included linux 32bitupdanswering the first question i get the following output when debugging valgrinds gdb server the breakpoint is not coming while it comes when i debug directly with gdbstasikgemini gdb qgdb set confirm offgdb target remote vgdbremote debugging using vgdbrelaying data between gdb and process 11665switching to thread 116650x040011d0 in gdb file homestasikleaksoreading symbols from homestasikleaksodonegdb break functionbreakpoint 1 at 0x110c file sourceleakclassc line 32gdb commandstype commands for breakpoints 1 one per lineend with a line saying just endsilentendgdb continuecontinuingprogram received signal sigtrap tracebreakpoint trap0x0404efcb in gdb source threadframespystack level 0 frame at 0x42348a0 eip 0x404efcb saved eip 0x4f2f544c called by frame at 0x42348a4 arglist at 0x4234898 args locals at 0x4234898 previous frames sp is 0x42348a0 saved registers ebp at 0x4234898 eip at 0x423489cstack level 1 frame at 0x42348a4 eip 0x4f2f544c saved eip 0x6e492056 called by frame at 0x42348a8 caller of frame at 0x42348a0 arglist at 0x423489c args locals at 0x423489c previous frames sp is 0x42348a4 saved registers eip at 0x42348a0stack level 2 frame at 0x42348a8 eip 0x6e492056 saved eip 0x205d6f66 called by frame at 0x42348ac caller of frame at 0x42348a4 arglist at 0x42348a0 args locals at 0x42348a0 previous frames sp is 0x42348a8 saved registers eip at 0x42348a4stack level 3 frame at 0x42348ac eip 0x205d6f66 saved eip 0x61746144type return to continue or q return to quit called by frame at 0x42348b0 caller of frame at 0x42348a8 arglist at 0x42348a4 args locals at 0x42348a4 previous frames sp is 0x42348ac saved registers eip at 0x42348a8stack level 4 frame at 0x42348b0 eip 0x61746144 saved eip 0x65736162 called by frame at 0x42348b4 caller of frame at 0x42348ac arglist at 0x42348a8 args locals at 0x42348a8 previous frames sp is 0x42348b0 saved registers eip at 0x42348acstack level 5 frame at 0x42348b4 eip 0x65736162 saved eip 0x70616d20 called by frame at 0x42348b8 caller of frame at 0x42348b0 arglist at 0x42348ac args locals at 0x42348ac previous frames sp is 0x42348b4 saved registers eip at 0x42348b0stack level 6 frame at 0x42348b8 eip 0x70616d20 saved eip 0x2e646570 called by frame at 0x42348bc caller of frame at 0x42348b4 arglist at 0x42348b0 argstype return to continue or q return to quit locals at 0x42348b0 previous frames sp is 0x42348b8 saved registers eip at 0x42348b4stack level 7 frame at 0x42348bc eip 0x2e646570 saved eip 0x0 called by frame at 0x42348c0 caller of frame at 0x42348b8 arglist at 0x42348b4 args locals at 0x42348b4 previous frames sp is 0x42348bc saved registers eip at 0x42348b8stack level 8 frame at 0x42348c0 eip 0x0 saved eip 0x0 caller of frame at 0x42348bc arglist at 0x42348b8 args locals at 0x42348b8 previous frames sp is 0x42348c0 saved registers eip at 0x42348bcgdb continuecontinuingprogram received signal sigtrap tracebreakpoint trap0x0404efcb in gdb continuecontinuing,"['c++', 'c']" +480626,detect scroll up scroll down in listview i have the following requirementat first data for page no 2 is fetched from the server the itemsare populated in a listviewconsidering that both the prev page next page are available in a scenario the following code has been added ifprevpageno 0 mlistviewactualsetonscrolistenerthis ifnextpageno 0 mlistviewactualsetonscrolistenerthis what conditions should i put to detect scroll up scroll down on the following methodsvoid onscrollabslistview view int firstvisibleitem intvisibleitemcount int totalitemcountvoid onscrollstatechangedabslistview view int scrollstateafter the action scroll up scroll down is detected accordingly a service will be called with either the prev page no or next page no to fetch the items to be populated in the listviewany inputs will be helpfulgone through the following links but its not returning the correct scroll up scroll down actionlink 1link 2,['android'] +480633,how to include neccessary files to the output of independent client project my solution consists ofclient startup project ui layer depends on appapp library application layer assembler depends on lib1 lib1 library business logic layer needs a specific file to work properly thirdpartydlli have added thirdpartydll to the lib1 project add existing item add and set copy to output directory property of dll file to copy always now the dll file is copied to the lib1 output and to the app output but not to the client output where i need it to bewhat is the right simple obvious way to copy thirdpartydll to the output of client on each solution buildupdthirdpartydll is not a reference actually that is another reference dependence my question is applied to any file that needs to be in the folder of running applicationrecorded video to be sure i am doing it right,['c#'] +480639,which numbers in list 2 are bigger and smaller than each number in list 1 i am using python i have two lists list 1 is 70 integers long list 2 is 250 integers i want to go through each number in list 1 and find the closest number in list 2 that is bigger and the closest number that is smaller than each number in list 1 and then calculate the difference between these two numbers in list 2 so far i havefor i in list1 for j in list 2 if list2jlist1i a maxlist2 elif list2jlist1i b minlist2 interval bathis does not seem to work i want to find the explicit numbers in list 2 that are less than a specific number in list 1 and know the maximum and then find out the smallest number in list 2 that is bigger than the number in list 1 does anyone have any ideas thanks,['python'] +480648,inject css in firefox add on sdk i failed to inject css in firefox extension here is my codevar tbb requiretoolbarbuttontoolbarbutton id button label usbutton image selfdataurlimgonpng oncommand function tabsactivetabattach contentscriptfile selfdataurljqueryjqueryminjs selfdataurljqueryjqueryuijs selfdataurlrecuperationjs selfdataurldialogjs contentstylefile selfdataurljqueryjqueryuicssi use toolbar buttons by erik vold contentstylefile does not seem to work when i click to the button the jquery dialog appears but without the css file,['jquery'] +480665,looking for alternatives to 32bit only microsoft common controls listview i have a legacy application developed in vbaexcel which uses listview controls unfortunately it looks like these controls cannot be used with 64bit versions of excelnative 64bit processes in office 2010 cannot load 32bit binaries this includes the common controls of mscomctl such as listviews an alternative must be found for existing microsoft office vba solutions that utilize these controls when the code is migrated to 64bit office 2010i need to migrate that legacy application to excel 201013 x64 the process is mostly painless except for those listview controlswhat are my main options to replace the listview control and which would be the most effective from a timedifficulty to implement perspectivenotesthis issue has been raised on ms forums but no practical answer has been givenadding net tag as i suspect some solutions could come from thereto make it clearer here is a snapshot of the excel user form the bottom part is the list view i have hidden confidential information which has sortable column allows the user to select multiple nonconsecutive lines,['.net'] +480696,jquery animate border color and width i cannot seem to get this jquery animation working for applying a border to an image on mouseenterdiv img src mkv9fhdbds1rmc58qo1 500jpg divjquerydiv imgmousenterfunction thiscssborder 0px solid f37736animate borderwidth 4px bordercolor f37736 500mouseleavefunction thisanimate borderwidth0px bordercolorf37736 500i also tried removing the css part for the jquery but does not work either,['jquery'] +480717,google maps in an actionbarsherlock tab i am trying to get google maps v2 working in my app i have seen several examples showing how you can open up supportmapfragment inside an activity the idea being that your activity will call setcontentviewrlayoutmap layout where map layoutxml links to the fragment with the linesandroidnamecomgoogleandroidgmsmapssupportmapfragment xmlnsmapthe name line effectively says that this layout is to be controlled by a fragment of type supportmapfragmentmy complication is that i am attempting to get the map to appear in an activity with tabs implemented with actionbarsherlock this means that whatever fragment corresponds to a tab selection must implement a tablistener but supportmapfragment does not so now presumably i need to create a new fragment like sopublic class mymapfragmentwithtablistener extends supportmapfragment implements tablistenerbut now i have got all confused about how to write the contents of mapfragmentwithtablistener in particular oncreateview should i be inflating some layout surely i cannot be inflating exactly the same map layoutxml from the examples because that already declares that it is controlled by supportmapfragment whereas in this implementation it should be controlled by mymapfragmentwithtablistener do i need a slightly different xml file to inflate if so what should it look like or should i be creating my view programatically,['android'] +480728,rotate image with javascript i need to rotate an image with javascript in 90degree intervals i have tried a few libraries like jquery rotate and raphaal but they have the same problem the image is rotated around its center i have a bunch of content on all sides of the image and if the image is not perfectly square parts of it will end up on top of that content i want the image to stay inside its parent div which has maxwith and maxheight setusing jquery rotate like this var angle 0buttononclick function angle 90 imagerotateangleresults in thisand this is the result i would like insteadanyone have an idea on how to accomplish this,"['javascript', 'jquery']" +480738,get new xy positions of element after scroll using jquery lets say i have an a tag as followsbody div classwrapper a href classa1click mea divbodyand my css arebody padding10pxwrapper height10px width500pxcurrently i am using offset of jquery to get the xy positions of a tagvar offset a1offsetvar top offsettopvar left offsetleftnow when i scroll the page and check of a tags xy coordinates they remain the same ie ineffective of page scrollingi want to get the new xy positions of a tag after scrolling the page related to the screenif this a tag gets hidden after scrolling down i want its position in negative values check this fiddle please help,['jquery'] +480757,using cocoapods with multiple projects i have a workspace that containsmyiphonexcodeprojsharedstuffsharedstuffxcodeprojsharedstuffxcodeproj builds a static library that is a dependency to myiphonexcodeproj for simplicity assume that each project has a single targetnow i want to add a library through cocoapods that should be available to both projectsmy podsfile looks like thisworkspace myworkspacexcworkspaceplatform iostarget myiphone do xcodeproj myiphonexcodeproj pod mbprogresshud 06endtarget sharedstuff do xcodeproj sharedstuffsharedstuffxcodeproj pod mbprogresshud 06endwhen i build i get these errors diff podfilelock no such file or directory diff manifestlock no such file or directory error the sandbox is not in sync with the podfilelock run pod install or update your cocoapods installationanyone have a clue whats going on hereupdatefrom the looks of it the pods root variable is not set when the check pods manifestlock build phase is executed,['ios'] +480773,cast object to a generic type i have not slept in a while so this is probably easier than i think it isi have a generic class that is more or less thispublic class referencet where t apiresource apiresource is abstract btw private t value null public t value get return value elsewhere in a custom serialize method someone is passing in an object that is actually an instance of referencesomething i simply want to skip to the value property that every reference object has so i want to gostring serializeobject o return baseserialize reference ovalue of course life is not that simple because as the compiler puts itusing the generic type referencet requires 1 type argumentshow can i do what i want to do,['c#'] +480800,less css nested attributes hoverafter is it possible to do this with lessa after background red hover after background blue i cant get the after to change color when hovering over a,['css'] +480837,why are generic and nongeneric structs treated differently when building expression that lifts operator to nullable this looks like a bug in lifting to null of operands on generic structsconsider the following dummy struct that overrides operatorstruct mystruct private readonly int value public mystructint val this value val public override bool equalsobject obj return false public override int gethashcode return basegethashcode public static bool operator mystruct a mystruct b return false public static bool operator mystruct a mystruct b return false now consider the following expressionsexpressionfuncmystruct mystruct bool expra valuea valueb valuea valuebexpressionfuncmystruct mystruct bool exprb nullablevaluea nullablevalueb nullablevaluea nullablevaluebexpressionfuncmystruct mystruct bool exprc nullablevaluea valueb nullablevaluea valueball three compile and run as expected when they are compiled using compile they produce the following code paraphrased to english from the ilthe first expression that takes only mystruct not nullable args simply calls op equality our implementation of operator the second expression when compiled produces code that checks each argument to see if it hasvalue if both do not both equal null returns true if only one has a value returns false otherwise calls op equality on the two valuesthe third expression checks the nullable argument to see if it has a value if not returns false otherwise calls op equality so far so goodnext step do the exact same thing with a generic type change mystruct to mystructt everywhere in the definition of the type and change it to mystructint in the expressionsnow the third expression compiles but throws a runtime exception invalidoperationexception with the following messagethe operands for operator equal do not match the parameters of method op equalityi would expect generic structs to behave exactly the same as nongeneric ones with all the nullablelifting described aboveso my questions arewhy is there a difference between generic and nongeneric structswhat is the meaning of this exceptionis this a bug in cnetthe full code for reproducing this is available on this gist,['c#'] +480838,google play geofence onhandleintent i am developing android app with geofence which released in this yearmy understanding is when the users get into or out of the fence it should trigger onhandleintent method however i have difficulty to trigger to onhandleintent method i have checked for 3 days to figure it out but i evetually could notso i need anyones helpthere is my code i really hope anyone could help me out mainactivity package comexamplegeofence import javautilarraylist import javautillist import androidapendingintent import androidcontentbroadcastreceiver import androidcontentcontext import androidcontentintent import androidcontentintentfilter import androidosbundle import androidsupportv4appfragmentactivity import androidsupportv4contentlocalbroadcastmanager import androidtexttextutils import androidutillog import androidwidgettoast import comgoogleandroidgmscommonconnectionresult import comgoogleandroidgmscommongoogleplayservicesclientconnectioncallbacks import comgoogleandroidgmscommongoogleplayservicesclientonconnectionfailedlistener import comgoogleandroidgmscommongoogleplayservicesutil import comgoogleandroidgmslocationgeofence import comgoogleandroidgmslocationlocationclient import comgoogleandroidgmslocationlocationclientonaddgeofencesresultlistener import comgoogleandroidgmslocationlocationrequest import comgoogleandroidgmslocationlocationstatuscodes public class mainactivity extends fragmentactivity implements connectioncallbacks onconnectionfailedlistener onaddgeofencesresultlistener private intentfilter mintentfilter private locationclient locationclient private locationrequest locatrequest private pendingintent intent private listgeofence mgeolist private context mcontext private geofence companylocation private geofencesamplereceiver mbroadcastreceiver override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main mcontext this locatrequest null mgeolist new arraylistgeofence intent null locationclient new locationclientthisthisthis mintentfilter new intentfilter mintentfilteraddactioncomexamplegeofenceaction geofences added mintentfilteraddcategorycomexamplegeofencecategory location services mbroadcastreceiver new geofencesamplereceiver override protected void onstart companylocation new geofencebuilder setrequestid1 settransitiontypesgeofencegeofence transition enter geofencegeofence transition exit setcircularregion 49220531 122986772 float50 setexpirationdurationgeofencenever expire build mgeolistaddcompanylocation locationclientconnect superonstart override public void onconnectedbundle arg0 todo autogenerated method stub intent gettransitionpendingintent locatrequest locationrequestcreate locatrequestsetprioritylocationrequestpriority balanced power accuracy locatrequestsetinterval50 try addgeofence catchunsupportedoperationexception e toastmaketextthis add geofences already requested error toastlength longshow locationclientrequestlocationupdateslocatrequest intent public void addgeofence locationclientaddgeofencesmgeolistintent this private pendingintent gettransitionpendingintent create an explicit intent intent localintent new intentthis receivetransitionsintentserviceclass return the pendingintent return pendingintentgetservice this 0 localintent pendingintentflag update current override protected void onstop locationclientthisconnect superonstop override public void onaddgeofencesresultint statuscode string geofencerequestids todo autogenerated method stub intent broadcastintent new intent iflocationstatuscodessuccess statuscode toastmaketextthis success toastlength shortshow broadcastintentsetactioncomexampleandroidgeofenceaction geofences added addcategorycomexampleandroidgeofencecategory location services putextracomexampleandroidgeofenceextra geofence statustest else toastmaketextthis addgeoerror toastlength shortshow localbroadcastmanagergetinstancemcontextsendbroadcastbroadcastintent override public void onconnectionfailedconnectionresult arg0 todo autogenerated method stub int code googleplayservicesutilisgoogleplayservicesavailablethis switchcode case connectionresultservice missing toastmaketextthis service missing code connectionresultservice missing connectionresultservice missing toastlength shortshow break case connectionresultservice version update required toastmaketextthis service version update required code connectionresultservice version update required connectionresultservice version update required toastlength shortshow break default toastmaketextthis start code toastlength shortshow override protected void ondestroy todo autogenerated method stub superondestroy override protected void onpause todo autogenerated method stub superonpause override protected void onresume todo autogenerated method stub localbroadcastmanagergetinstancethisregisterreceivermbroadcastreceiver mintentfilter locationclientconnect superonresume override public void onthisconnected todo autogenerated method stub locationclient null handle results returned to this activity by other activities started with startactivityforresult in particular the method onconnectionfailed in geofenceremover and geofencerequester may call startresolutionforresult to start an activity that handles google play services problems the result of this call returns here to onactivityresult calls override protected void onactivityresult int requestcode int resultcode intent data define a broadcast receiver that receives updates from connection listeners and the geofence transition service public class geofencesamplereceiver extends broadcastreceiver define the required method for broadcast receivers this method is invoked when a broadcast intent triggers the receiver override public void onreceivecontext context intent intent check the action code and determine what to do string action intentgetaction intent contains information about errors in adding or removing geofences if textutilsequalsaction comexamplegeofenceaction geofences added handlegeofencestatuscontext intent intent contains information about a geofence transition else if textutilsequalsaction comexamplegeofenceaction geofence transition handlegeofencetransitioncontext intent the intent contained an invalid action else toastmaketextcontexterror toastlength longshow if you want to thisplay a ui message about adding or removing geofences put it here param context a context for this component param intent the received broadcast intent private void handlegeofencestatuscontext context intent intent report geofence transitions to the ui param context a context for this component param intent the intent containing the transition private void handlegeofencetransitioncontext context intent intent if you want to change the ui when a transition occurs put the code here the current design of the app uses a notification to inform the user that a transition has occurred report addition or removal errors to the ui using a toast param intent a broadcast intent sent by receivetransitionsintentservice private void handlegeofenceerrorcontext context intent intent receivetransitionsintentservice package comexamplegeofence import javautillist import androidappintentservice import androidappnotificationmanager import androidapendingintent import androidcontentcontext import androidcontentintent import androidsupportv4appnotificationcompat import androidsupportv4apptaskstackbuilder import androidutillog import androidwidgettoast import comgoogleandroidgmslocationgeofence import comgoogleandroidgmslocationlocationclient public class receivetransitionsintentservice extends intentservice sets an identifier for the service private context mcontext public receivetransitionsintentservicecontext c superreceivetransitionsintentservice mcontext c handles incoming intents param intent the intent sent by location services this intent is provided to location services inside a pendingintent when you call addgeofences override protected void onhandleintentintent intent first check for errors toastmaketextmcontext onhandleintent toastlength longshow if locationclienthaserrorintent get the error code with a static method int errorcode locationclientgeterrorcodeintent log the error logereceivetransitionsintentservice location services error integertostringerrorcode you can also send the error code to an activity or fragment with a broadcast intent if there is no error get the transition type and the ids of the geofence or geofences that triggered the transition else int transitiontype locationclientgetgeofencetransitionintent iftransitiontype geofencegeofence transition enter transitiontype geofencegeofence transition exit listgeofence geofences locationclientgettriggeringgeofencesintent string geofenceids new string geofencessize forint i 0 i geofencessize i geofenceidsi geofencesgetigetrequestid string ids 1 string transition transitiontype geofencegeofence transition enter you are inyou are out toastmaketextmcontext transition toastlength longshow sendnotificationtransitionids for the notification notificationmanager mnotificationmanager notificationmanager getsystemservicecontextnotification service private void sendnotificationstring transitiontype string ids create an explicit content intent that starts the main activity intent notificationintent new intentgetapplicationcontextmainactivityclass construct a task stack taskstackbuilder stackbuilder taskstackbuildercreatethis adds the main activity to the task stack as the parent stackbuilderaddparentstackmainactivityclass push the content intent onto the stack stackbuilderaddnextintentnotificationintent get a pendingintent containing the entire back stack pendingintent notificationpendingintent stackbuildergetpendingintent0 pendingintentflag update current get a notification builder that is compatible with platform versions 4 notificationcompatbuilder builder new notificationcompatbuilderthis set the notification contents buildersetsmalliconrdrawableic notification setcontenttitle transitiontype geofence transition notification title ids setcontentintentnotificationpendingintent get an instance of the notification manager notificationmanager mnotificationmanager notificationmanager getsystemservicecontextnotification service issue the notification mnotificationmanagernotify0 builderbuild,['android'] +480897,imported maven project does not appear as java project shows folders i checked out the existing project source code from svn to a folder in my systemthen i opened eclipse import project existing maven projectit imported without issues however project explorer shows it as just folders instead of packages like when we create a package and then add classes to it it shows a different icon for package root i opened navigator and package explorer as well but they are showing them as folders as welli triedmvn eclipsecleanmvn eclipseeclipseon the root of the project but it did not helpcan anyone help on this onemy folder structureecs ecsejb srcjavamaincomx pomxml ecsear srcjavamaincomx pomxml pomxml,['java'] +480953,parsing wifi packets libpcap i have been working on a way to have an openwrt router log wifi probe requests to a mysql db it stores mac address and rssi info for each probe request packet along with other routerspecific dataafter researching libpcap quite a bit i have been able to cobble together a basic little program that simply sniffs packets on a monitor interface mon0 using a filter expression wlan subtype probereq and then prints out the raw packets in hex with the info that is available online on libpcap this part was fairly straightforwardnow heres where i am stuck how do i parse the wifi packet to retrieve the info i am looking for rssi and source mac addressto be clear i am not asking for the code to do it although i would not complain if youd like to supply some d i am just looking for some sort of guide for understanding which byte is which a wifi packet road map if you willthere are a few good tutorials out there for parsing packets that come in over ethernet but i have not been able to find anything to help with parsing headers spcifically related to wifi i assume it will be a pretty simple process just grabbing the relevant bytes for rssi and source mac but again i have not been able to find any documentation on which byte is whichi know this has been done before but i will be honest i am completely lost when looking through the source code for tcpdumpso does anyone know of a good resource for how to parse wifi packetscheersedit more specific answerrssi is found in the radiotap header well on linux it is pulling the rssi out of the packet is fairly straightforward using radiotapparserc along with the files it depends on found in the same directory as the file i linked to if anyone is having trouble with using the radiotapparserc functions feel free to get in touchpulling out the source mac address is made pretty easy by the radiotap functions because the radiotap header struct contains the length of the radiotap header it len which is variable since i am parsing only probe requests which have a fixed length check out page 17 here it is just a matter of making a pointer that points to packet it len 10 the source mac address starts 10 bytes after the beginning of the mac frame which begins where the radiotap header ends the 6 bytes that start at that pointer are addr2 in the 80211 frame again see page 17 here,['c'] +480976,tips for making spaces work like tabs in visual studio at work we have the convention on using 4 spaces for code indentation i am accustomed to using tabs for indentation but want to follow the conventionnote it is not my intention to start a thiscussion on spaces vs tabs herei adjusted my visual studio settings to replaces tabs with 4 spaces but i have some issues adjusting to using spacesfor examplehow can i easily unindent code with tab chararaters i onlyneeded to use backspace one time with spaces i need to use backspace4 timeshow can i make sure that there is always the correct amount of spacesnot three or fivehow can i navigate through my code as fast as i could with tabs arrow left or right jumpsto the next indentation with tabs but moves only a single position with spaceshow can i ignore whitespace changes when comparing filesidealy i would like these 4spaces for indentation to work equally to tab charactersi work mainly with c and xmlbased filesany tips are welcome,['c#'] +480982,whats the difference between tests and specs i decided to try out minitest and noticed pretty quickly that it supported something called specs i had seen these referenced before but thought it was just an alternate test syntax associated with factories but if that were the case then why would minitest need to support them bothwe only covered tests when i was taught ruby on rails so i do not really know anything about specs when i google specs i find a lot of stuff about how to write good ones but nothing explaining what they are whats the difference between tests and specs,['ruby-on-rails'] +480991,linearlayout dividers are not showing i am working on an android project and i have a linearlayout which contains 2 horizontal buttons using borderless button style i am trying to show dividers in between each button but they are not showing up but i cannot see any reason why not below is the xml layoutlinearlayout androidididcall log select host button group androidlayout widthfill parent androidlayout heightwrap content androidorientationhorizontal androidlayout alignparentbottomtrue androiddividerf androidshowdividersmiddle androiddividerpadding22dp button androidididcall log select btncancel androidlayout width0dp androidlayout heightwrap content androidlayout weight1 androidtextcancel styleandroidattrborderlessbuttonstyle button androidididcall log select btnblock androidlayout width0dp androidlayout heightwrap content androidlayout weight1 androidtextblock styleandroidattrborderlessbuttonstyle linearlayoutthanks for any help you can provide,['android'] +481006,avplayer video blank but hear sound i am switching from mpmovieplayercontroller to avplayer as i need finer grained control over video swapping the mov file i was playing with mpmovieplayercontroller played fine but after switching to avplayer i hear the audio from the video but the video just shows the view background that i added the avplayerlayer to heres how i am initializing the avplayerselfplayer avplayer alloc initwithurlvideoavplayerlayer playerlayer avplayerlayer playerlayerwithplayerselfplayerplayerlayerframe selfplayercontainerboundsselfplayercontainerlayer addsublayerplayerlayerthen later i just issue aselfplayer playwhen the video plays i hear the audio but see no video i also tried setting the zposition to no luckplayerlayerzposition 1,"['iphone', 'ios', 'objective-c']" +481063,accessing c union members via pointers does accessing union members via a pointer as in the example below result in undefined behavior in c99 the intent seems clear enough but i know that there are some restrictions regarding aliasing and unionsunion int i char c uint ip uichar ic ucip 0ic aprintfcn uc,['c'] +481093,is it practical to store string columns in indexes suppose we have this example structuredatasee fiddle at 81f85e1 set global innodb file per table1drop table if exists mysql index reading myisamcreate table if not exists mysql index reading myisam id int not null auto increment str varchar50 not null enm enumthatis thequestion not null cnt tinyint not null primary key id index str cnt str cnt index enm cnt enm cnt enginemyisam charsetlatin1insert into mysql index reading myisam str enm cnt values tobeornottobe thatis 1 tobeornottobe thatis 2 tobeornottobe thatis 3 tobeornottobe thatis 4 tobeornottobe thatis 5drop table if exists mysql index reading innodbcreate table mysql index reading innodb like mysql index reading myisamalter table mysql index reading innodb engine innodbinsert into mysql index reading innodb select from mysql index reading myisamexplain select cnt from mysql index reading myisam where str tobeornottobeexplain select cnt from mysql index reading innodb where str tobeornottobeexplain select cnt from mysql index reading myisam where enm thatisexplain select cnt from mysql index reading innodb where enm thatislet us check how it is stores internally egrep ignorecase onlymatching text tobeornottobethatis mysql index reading innodbfrmthatismysql index reading innodbibdtobeornottobemysql index reading innodbibdtobeornottobemysql index reading innodbibdtobeornottobemysql index reading innodbibdtobeornottobemysql index reading innodbibdtobeornottobemysql index reading innodbibdtobeornottobemysql index reading innodbibdtobeornottobemysql index reading innodbibdtobeornottobemysql index reading innodbibdtobeornottobemysql index reading innodbibdtobeornottobemysql index reading myisamfrmthatismysql index reading myisammydtobeornottobemysql index reading myisammydtobeornottobemysql index reading myisammydtobeornottobemysql index reading myisammydtobeornottobemysql index reading myisammydtobeornottobemysql index reading myisammyitobeornottobemysql index reading myisammyitobeornottobein both engines enums are stored in frm as it should be okin both engines data stored in data and dataindex files okin myisam index has two recordsin innodb index has all five records in correct casewhat i have found alreadyin some cases a query can be optimized to retrieve values without consulting the data rows if a query uses only columns from a table that are numeric and that form a leftmost prefix for some key the selected values may be retrieved from the index tree for greater speedselect key part3 from tbl name where key part11using index to read data some storage engines myisam and innodb included can also use index to read the data hence avoiding to read the row data itself this is not simply savings of having 2 reads per index entry instead of one but it can save io orders of magnitude in some cases a indexes are sorted at least on the page boundary so doing index range scan you typically get many index entries from the same page but the rows itself can be scattered across many pages requiring potentially a lot of ios on top of that if you just need access to couple of columns index can be simply much smaller than the data which is one of the reason covering indexes help to speed up queries even if data is in memory if mysql is only reading index and not accessing rows you will see ausing indexa in explain outputthen in sources of sql selectcc selectccl12834 we can remove binary fields and numerical fields except float as float comparison is not 100 secure we have to keep normal strings to be able to check for end spacesif fieldbinary fieldreal type mysql type string fieldreal type mysql type varchar fieldtype mysql type float fielddecimals 0 return store val in fieldfield right item check field warnso my questions areis it practical to store in indexes string columns that needed only as datafor example table with 20 columns and we often need strcolumn that is searched by intcolumnis it good to create index like intcolumnstrcolumn or we realy need only intcolumn heredoes mysql in innodb engine really does some extra actions forretrieving the data when we see using where using indexalso same happens for enums it happens because enum fieldsreal type returns mysql type string does it do same for enumscan we then assume that enums is super evil and we should alwaysuse just simple reference table insteadfor myisam it is undertandable as it stores in index not all valuesbut then why do it is stores two values not oneif this is all really happens is it just current restrisctions ofmysql kernel that does not depend of concrete handler implementationps i see that this question is something huge if someone will help to reformulatebreak it it will be niceupdate1 adding another sql about using index vs using index using wheresee fiddle at 83f2872drop table if exists tabcreate table if not exists tab id int not null auto increment num1 tinyint not null num2 tinyint str3 char1 not null primary key id index num1 num2 num1 num2 index num1 str3 num1 str3 index num2 num1 num2 num1 index str3 num1 str3 num1 engineinnodbinsert into tab num1 num2 str3 values 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6 6 6 7 7 7 8 8 8 9 9 9 0 0 0insert into tab num1 num2 str3 select num1 num2 str3 from tab using indexexplain select num2 from tab where num1 5explain select str3 from tab where num1 5 using where using indexexplain select num1 from tab where num2 5explain select num1 from tab where str3 5questions 2why in case of search by not null int we see just using indexbut in case of nullable int or string we see also using wherewhat additional actions does mysql do there,['mysql'] +481096,accessing querystring in a custom authorizeattribute i am using web api and have setup a simple authentication and authorization mechanism where the caller passes a token that i have issued to them in the query string so they submit a request likeissuedtokeni have an apiauthorizeattribute like thispublic class apiauthorizeattribute systemwebhttpauthorizeattribute public apipermission permission get set public override void onauthorizationsystemwebhttpcontrollershttpactioncontext actioncontext switch permission case apipermissionnone return case apipermissionwrite case apipermissionread string query actioncontextrequestrequesturiquery var nvc systemwebhttputilityparsequerystringquery string token nvctoken my code to map the token to an authorization for the request apiauthorization auth apitokengetauthorizationtoken if auth null authhaspermissionpermission return handleunauthorizedrequestactioncontext return default throw new argumentexceptionunexpected permission then i can decorate my apis like this note this is just an example a real call would read data from their account an account identifier is encrypted within their token and return it summary ping service that requires a token with read permission returns success summaryapiauthorizepermission apipermissionreadhttpgetpublic string ping return successas you might note i could not access the querystring anywhere from httpactioncontext parameter and had to build it myself it seems like they explicitly removed querystring from this request object i donat want to add atokena it to each and every api method in order to get it in the route dataso my questions areis the querystring in there somewhere and i am just missing it if not any idea why microsoft does not include it with this request object ie maybe this is a bad thing to dois there a better way to deal with getting the token in the authorizeattribute again without adding it to each callbtw i realize there are other probably better options for authorization such as basic authentication and oauth and i do not want to debate that topic here,['c#'] +481138,is this guaranteed to point to the start of an object in c i want to write an object into a sequential file using fwrite the class is likeclass a int a int bpublic interfaceand when i write an object into a file i am wandering that could i use fwrite this sizeofint 2 fo to write the first two integersquestion is is this guaranteed to point to the start of the object data even if there may have a virtual table exist in the very beginning of the object so the operation above is safe,['c++'] +481167,java constructors pattern i use the pattern quite a lotclass blah int a double b string c date d public blahint a double b string c date d super possibly thisa a thisb b thisc c thisd d this is indeed a great deal of boilerplate for something so simple i was thinking of a generic object factory to do this with introspection but this feels very evil special cases inheritance and speed issues guice could be used and the constructor skipped altogether but then manual object creation is going to be ugly is this something i will have to live with in java or is there a way to avoid this boilerplate,['java'] +481241,html5 getusermedia record audio save to web server after certain time i am having some difficulties with getusermedia with html5 whilst developing my web page this is the first time i have tried to implement this to record a users audio input flash is not an option for this project as it has to be used on mobile devices tooi come here to see if anyone has experience with and knows how to implement an html5 with getusermedia to record a users microphone for a certain amount of time done with a session in php and then saves and sends the audio file to a web serverif this is not possible then is there any other way perhaps with a java appletthe jsscript var onfail functione consolelogrejected e var onsuccess functions var context new webkitaudiocontext var mediastreamsource contextcreatemediastreamsources recorder new recordermediastreamsource recorderrecord audio loopback mediastreamsourceconnectcontextdestination windowurl windowurl windowwebkiturl navigatorgetusermedia navigatorgetusermedia navigatorwebkitgetusermedia navigatormozgetusermedia navigatormsgetusermedia var recorder var audio documentqueryselectoraudio function startrecording if navigatorgetusermedia navigatorgetusermediaaudio true onsuccess onfail else consolelognavigatorgetusermedia not present function stoprecording recorderstop recorderexportwavfunctions audiosrc windowurlcreateobjecturls scriptthe html linked to recorderjs from here script typetextjavascript srcrecorderjs script input onclickstartrecording typebutton valuestart recording input onclickstoprecording typebutton valuestop recording and play,['php'] +481262,detecting c structure is updated from unit test i have a family of data structures that should be passed from one layer to over using boostserializationfor example struct datatype1 stdstring field1 stdstring field2 templateclass archive void serializearchive ar const unsigned int version ar field1 ar field2 i want to write unit tests on this just to be sure that i did no miss some fields there are a lot of structures and fieldsthe problem is if i add new field in structure i will definitely do and forget to update unit test this field will not covered by unit test my question is how to detect that structure or class is changed my idea was to use static assertsizeofdatatype1 hard coded value but it suffers from difference in structure size in different compilers platforms x64 x86 and configurations release debugany good idea how to handle this,['c++'] +481263,whats tiered compilation in java 7 please help me knowing tiered compilation in deeper which was a new feature in java se 7thanks in advance,['java'] +481270,devise 3 rails 4 cannot update user without password i am trying to update a user without having to provide a password but approaches that worked on older deviserails versions no longer work with devise 3 and rails 4 strong parametersi am using my user controller to update but i have also tried using a custom devise registration controller with devise parameter sanitizer without successthe form does not require a password has no password field and the user controller handling the update looks like so patchput users1def update if user paramspasswordblank railsloggerinfo entered if statement user paramsdelete password user paramsdelete password confirmation railsloggerinfouser paramsinspect end user current user if userupdateuser params redirect to user notice user was successfully updated else railsloggerinfousererrorsinspect render action edit endendprivatedef user params paramsrequireuserpermitscreen name full name email about location profile pic password password confirmation current passwordend the log after a submit looks likestarted patch users13 for 127001 at 20130529 1818 0100processing by userscontrollerupdate as htmlparameters utf8a authenticity token20avah2ozaovubaiamsgvbyeq4iijewqqmno7xd4ry userscreen namedarcbar full namebarry darcy about location website url twitter username email commitsave changes id13user load 05ms select users from users where usersid 13 order by usersid asc limit 1entered if statementscreen namedarcbar full namebarry darcy email about location twitter username website url02ms beginuser exists 08ms select 1 as one from users where usersemail and usersid 13 limit 102ms rollbackactivemodelerrors0x007fedf45bb640 baseuser id 13 username darcbar full name barry darcy about location email encrypted password 2a10mb4zsrppqz9cyz0zdlmbu62nyikt8s6zwurtwwov3 reset password token nil reset password sent at nil remember created at nil sign in count 9 current sign in at 20130528 175120 last sign in at 20130528 164252 current sign in ip 127001 last sign in ip 127001 authentication token nil created at 20130527 140341 updated at 20130528 175120 screen name darcbar profile pic file name nil profile pic content type nil profile pic file size nil profile pic updated at nil messagespasswordplease enter a password with at least 5 characters please enter a password with at least 5 charactersrendered usersedithtmlhaml within layoutsapplication 30msrendered partialshead user optionshaml 18mscompleted 200 ok in 74ms views 121ms activerecord 17msdoes anyone know why the password errors are present,['ruby-on-rails'] +481281,how to bind an 2d array bool to a wpf datagrid oneway i have a matrix kind datagrid like thisthis grid is designed entirely in xaml now how to insert values into these datagridcell with 2 dimensional array the values which is needed to be inserted must be of bool datatype either true or falseany ideas,['c#'] +481320,how can i override inline styles with external css i have markup that uses inline styles but i do not have access to change this markup how do i override inline styles in a document using only css i do not want to use jquery or javascripthtmldiv stylefontsize 18px color red hello world how can i change the color to bluedivcssdiv color blue this is not working,['css'] +481391,should rbenv be installed systemwide or at a user level i am building a vagrant setup and part of that is installing rbenv i am using librarianchef to manage all my chef cookbooks and it installs rbenv and rubybuildhowever when i tried to ssh into my vagrant vm and type ruby v i got the standard systeminstalled ruby 187 20120208 patchlevel 358 x86 64linux thinking that maybe rbenv was not installed i tried running rbenv versions but rbenv was in fact installedvagrantprecise64 rbenv versions system set by optrbenvversionso then i tried rbenv install versionvagrantprecise64 rbenv install 193p327build failedtest z optrbenvversions193p327include binmkdir p optrbenvversions193p327includebinmkdir cannot create directory optrbenvversions193p327 permission deniedthat failed with permission denied i tried installing again with sudosudo rbenv install 193p327and that worked then i tried running rbenv versions againvagrantprecise64 rbenv versions system set by optrbenvversionbut it still says only system ruby is installed however if i run it with sudovagrantprecise64 sudo rbenv versions system set by homevagrantrbenvversion 193p327rbenv versions now shows 193 was installedso there seems to be a thisconnect in that that rbenv and my ruby version are now installed on a system level and not on the user leveli am using the rbenvcookbook i would like to have rbenv set up with chef because that saves me from setting it up manually postinstallthe other issue i am having is that it seem like everything that is rubycontrolled such as gem is also suffering the same thisconnectvagrantprecise64 gem install bundlerfetching bundler135gem 100error while executing gem gemfilepermissionerror you do not have write permissions into the optvagrant rubylibrubygems18 directory,['ruby'] +481398,do mock objects get reset for each test i am using the mockito framework to create mock objects in my junit tests each mock knows what methods have been called on it so during my tests i can writeverifymymock atleastoncemymethodi am wondering if this internal mock knowledge of what it has called will persist across my tests if it does persist then i could be getting false positives when using the same verify method in two testsa code examplerunwithmockitojunitrunnerclasspublic class emractivitiesimpltest mock private myclass mymock before public void setup whenmymockmymethodthenreturnhello test public void test1 some logic verifymymock atleastoncemymethod test public void test2 some other logic verifymymock atleastoncemymethod mock state is persisted test2 will pass regardless since test1s verify method passedmock state is reset test2 will fail if mymockmymethod is not called,['java'] +481408,fire iframe type magnificpopup programmatically i am trying to figure out how to implement magnific popup from the onitemclick event of jquerygantt fortunately it lets us implement code via a self executing function which it passes data to from the clicked elementwhat i am having issues with now is building the appropriate call to magnific popup in order to load an iframe type popup via jquery i have tried it a few different ways and unfortunately because i do not have a solid fundamental understanding of either of these jquery plugins nor jquery for that matter i am playing at monkeysee monkeydofunctiondata magnificpopuptype iframe iframe src httpserverpageaspxid data magnificpopupopenthis seems close i get type error magnificpopup is not a function when i try to fire this function how can i fire an iframe type popup born completely out of javascript,['jquery'] +481419,getting robolectric to work with volley i am trying to get volley working with robolectric i can see that my http request is getting called and parsenetworkresponse is getting called i am sending a custom subclass of jsonrequest but my listener is not getting called any advice here is a code sampletestpublic void testtypeaheadclient throws exception robolectricgetfakehttplayerintercepthttprequestsfalse mremoterequestqueue and mcustomrequest are set up previously mremoterequestqueueaddmcustomrequestprivate static class customrequest extends jsonrequestmyobject public customrequeststring url responselistenermyobject listener responseerrorlistener errorlistener superrequestmethodget url null listener errorlistener override protected responsemyobject parsenetworkresponsenetworkresponse response systemoutprintlnin parsenetworkresponse try myobject myobject new myobjectnew jsonarraynew stringresponsedata utf8 return responsesuccessmyobject httpheaderparserparsecacheheadersresponse catch exception e eprintstacktrace return responseerrornew parseerrore,['android'] +481461,how does one use basic authentication with volley on android i am looking through examples and code but i do not see anything implemented is this possible at this stage,['android'] +481469,ruby rails how do i change the timezone of a time without changing the time i have a record in the database which has start time and timezone attributesthe start time is a time with zone utc 20010101 1420 for examplethe timezone is a string americanew york for examplei want to create a new time object with start time but whose timezone is timezone i do not want to load the start time and then convert to timezone because rails will be clever and update the time from utc to be consistent with that timezonet foostart time 20101 1420 utctzone utctin time zoneamericanew york sat 01 jan 20 0920 est 0500instead i want to see sat 01 jan 20 1420 est 0500ie i want to sayt 20101 1420 utctzone americanew york americanew yorkt 20101 1420 est,"['ruby-on-rails', 'ruby']" +481511,autofixtureautomoq supply a known value for one constructor parameter i have just started to use autofixtureautomoq in my unit tests and i am finding it very helpful for creating objects where i do not care about the specific value after all anonymous object creation is what it is all aboutwhat i am struggling with is when i care about one or more of the constructor parameters take examplecomponent belowpublic class examplecomponent public examplecomponentiservice service string somevalue i want to write a test where i supply a specific value for somevalue but leave iservice to be created automatically by autofixtureautomoqi know how to use freeze on my ifixture to keep hold of a known value that will be injected into a component but i cannot quite see how to supply a known value of my ownhere is what i would ideally like to dotestmethodpublic void create examplecomponent with known somevalue create a fixture that supports automocking ifixture fixture new fixturecustomizenew automoqcustomization supply a known value for somevalue this method does not exist string knownvalue fixturefreezestringmy known value create an examplecomponent with my known value injected but without bothering about the iservice parameter examplecomponent component thisfixturecreateexamplecomponent exercise component knowning it has my known value injected i know i could do this by calling the constructor directly but this would no longer be anonymous object creation is there a way to use autofixtureautomock like this or do i need to incorporate a di container into my tests to be able to do what i wantediti probably should have been less absract in my original question so here is my specific scenarioi have an icache interface which has generic tryreadt and writet methodspublic interface icache bool tryreadtstring key out t value void writetstring key t value other methods not shown i am implementing a cookiecache where itypeconverter handles converting objects to and from strings and lifespan is used to set the expiry date of a cookiepublic class cookiecache icache public cookiecacheitypeconverter converter timespan lifespan usual storing of parameters public bool tryreadtstring key out t result read the cookie value as string and convert it to the target type public void writetstring key t value write the value to a cookie converted to a string set the expiry date of the cookie using the lifespan other methods not shownso when writing a test for the expiry date of a cookie i care about the lifespan but not so much about the converter,['c#'] +481515,page not secured after log out and click back button in my previous employment i was experiencing a well known problem of being unable to prevent the user from being able to navigate the site using the back button after logging out my technologies include spring javascript and potentially the mobile module of the java ajax library zk besides navigating using the back button authorised access worked otherwise i no longer have access to the application code the application was a mobile one of which i was not the original authori have tried the following common solutionshave tried adding a webcontentinterceptor as instructed here defined my own filter using a combination of this filter question and this answer about inserting additional filters filter code is not executed during debugadded requestmappinghandleradapter to set cacheseconds to 0we have the following definition in t2springsecuritycontextxmlhttp autoconfigtrue intercepturl patternmobileindex accessrole admin intercepturl patternt2metrics accessrole admin intercepturl patternt2monitor accessrole admin formlogin loginpageloginjsp authenticationfailureurlloginerrorjsp defaulttargeturlmobileindexjsp logout logoutsuccessurlloginjsp invalidatesessiontruehttpother details about our implementationjava methods are called using requestmapping from javascript on a class annotated as controller ie t2metricsjsp has js to fire to url matching request mappingtried adding securityglobalmethodsecurity to application context and role annotation to method have scriptlet code to thisable caching to the jsp pages and that did nothing also fired up the application in debug within intellij and a debug point within my define filter is not hit once they have used the back button to return into the application the user can still navigate around the applicationmy only remaining idea was that the problem involves our client code javascript or libraries incorrect integration with spring security for from the view because debug did not hitting the spring security filter chain,['javascript'] +481594,how to refresh gridview after pressed a button in aspnet i am trying to make a simple library database i list the search results in a gridview then i have a textbox and a button user enters the isbn and clicks loan button then if there is enough number of items itemnumber0 it is loaned by user here is the screenshot of user interfacemy question is when user clicks loan button the loan may or may not be succesful in both cases i print a message indicating whether loan is succesful or not and i also want the updated gridview to be thisplayed the problem is after pressing the loan button the gridview thisappears and i just see the textbox button and the message on the screen how can i show the updated version of gridview after pressing loan buttonhere is the code file page languagec autoeventwireuptrue codefilesearchresultsaspxcs inheritspages searchresults doctype html public w3cdtd xhtml 10 transitionalen html xmlnshead runatservertitletitleheadbodyform idform1 runatserverdivdivaspgridview idgridview1 runatserver autogeneratecolumnsfalse datakeynamesisbn datasourceidsqldatasource1 onselectedindexchangedgridview1 selectedindexchanged onrowcommandgridview1 rowcommand columns aspboundfield datafieldtitle headertexttitle sortexpressiontitle aspboundfield datafieldisbn headertextisbn readonlytrue sortexpressionisbn aspboundfield datafieldauthorname headertextauthorname sortexpressionauthorname aspboundfield datafieldauthorlname headertextauthorlname sortexpressionauthorlname aspboundfield datafielditemtype headertextitemtype sortexpressionitemtype aspboundfield datafieldpublishyear headertextpublishyear sortexpressionpublishyear aspboundfield datafieldnumofcopies headertextnumber of copies sortexpressionnumofcopies columnsaspgridviewaspsqldatasource idsqldatasource1 runatserver connectionstring connectionstringsconnectionstring selectcommandselect from items where title like title selectparameters aspformparameter formfieldtsearchbox nametitle typestring selectparametersaspsqldatasourcebr asplabel idlabel1 runatserver texttype isbn to loanasplabel and here is the cs fileusing systemusing systemcollectionsgenericusing systemlinqusing systemwebusing systemwebuiusing systemwebuiwebcontrolsusing systemdatasqlclientpublic partial class pages searchresults systemwebuipageprotected void page loadobject sender eventargs eprotected void gridview1 selectedindexchangedobject sender eventargs e responseredirectdefaultaspxprotected void gridview1 rowcommandobject sender gridviewcommandeventargs e sqlconnection con new sqlconnection conconnectionstring data sourcesqlexpressattachdbfilenameduserssuuserdocumentsvisual studio 2010projectslibrarylibwebsiteapp datalibdatabasemdfintegrated securitytrueuser instancetrue int32 verify string title gridview1headerrowcells0text isbn gridview1headerrowcells1text name gridview1headerrowcells2text lname gridview1headerrowcells3text type gridview1headerrowcells4text year gridview1headerrowcells5textprotected void bloanbutton clickobject sender eventargs e sqlconnection con new sqlconnection conconnectionstring data sourcesqlexpressattachdbfilenameduserssuuserdocumentsvisual studio 2010projectslibrarylibwebsiteapp datalibdatabasemdfintegrated securitytrueuser instancetrue string user select currentid from currentuser sqlcommand cmd1 new sqlcommanduser con conopen string get cmd1executescalartostring string query1 insert into loantablestudidisbnonborrow values get tloanboxtext 1 string numquery select numofcopies from items where isbn tloanboxtext sqlcommand cmdnumquery new sqlcommandnumquery con sqlcommand cmd2 new sqlcommandquery1 con int result int numconverttoint32cmdnumqueryexecutescalar result cmd2executenonquery if num 0 if result 0 responseredirectloansuccesfullaspx else notavailablevisible true concloseand here is the code for loan button protected void bloanbutton clickobject sender eventargs e sqlconnection con new sqlconnection conconnectionstring data sourcesqlexpressattachdbfilenameduserssuuserdocumentsvisual studio 2010projectslibrarylibwebsiteapp datalibdatabasemdfintegrated securitytrueuser instancetrue string user select currentid from currentuser sqlcommand cmd1 new sqlcommanduser con conopen string get cmd1executescalartostring string query1 insert into loantablestudidisbnonborrow values get tloanboxtext 1 sqlcommand cmd2 new sqlcommandquery1 con int result result cmd2executenonquery if result 0 loansuccesfulvisible true responseredirectloansuccesfullaspx conclosei appreciate any help thanks,['asp.net'] +481609,linq expression tree any inside where i am trying to generate the following linq queryquery the database for all adaccountalerts that have not had notifications sent outthen get the entity adaccount the alert pertains to and find all accounts thatare subscribing to alerts on that entityvar x datacontextalertswherea anotificationssent null oftypeadaccountalert tolist groupjoindatacontextalertsubscriptions a new tupleint stringaadaccountid typeofadaccountname s new tupleint stringsentityid sentitytype alert subscribers new tupleadaccountalert ienumerablealertsubscription alert subscribers wheres sitem2any todictionarykvp alertkvpitem1 kvp kvpitem2selects susernameusing expression trees which seems to be the only way i can do this when i need to use reflection and runtime types note that in the real code see below the adaccountalert is actually dynamic through reflection and a forloopmy problem i can generate everything up to the where clause the whereexpression method call blows up because of incompatible types normally i know what to put there but the any method call has me confused i have tried every type i can think of and no luck any help with both the where and todictionary would be appreciatedheres what i have so farvar alerttypes appdomaincurrentdomaingetassemblies singlea afullnamestartswithalertsentities gettypes wheret typeofalertisassignablefromt tisabstract tisinterfacevar alertsubscribers new dictionaryalert ienumerablestringusing tuples for joins to keep everything stronglytypedvar subscribabletype typeoftupleint stringvar doubletuple typegettypesystemtuple2 mscorlib trueforeach var alerttype in alerttypes type foreignkeytype getforeignkeytypealerttype if foreignkeytype null continue iqueryablealert unnotifiedalerts datacontextalertswherea anotificationssent null generates oftypealerttype methodcallexpression alertsoftype expressioncalltypeofenumerablegetmethodoftypemakegenericmethodalerttype unnotifiedalertsexpression generates tolist which is required for joins on tuples methodcallexpression unnotifiedalertslist expressioncalltypeofenumerablegetmethodtolistmakegenericmethodalerttype alertsoftype generates a new aentityid entitytype typeofadaccountname parameterexpression alertparameter expressionparameteralerttype a memberexpression adaccountid expressionpropertyalertparameter alerttypegetpropertyalerttypegetforeignkeyid newexpression outerjoinobject expressionnewsubscribabletypegetconstructornew type typeofint typeofstring adaccountid expressionconstantforeignkeytypename lambdaexpression outerselector expressionlambdaouterjoinobject alertparameter generates s new sentityid sentitytype type alertsubscriptiontype typeofalertsubscription parameterexpression subscriptionparameter expressionparameteralertsubscriptiontype s memberexpression entityid expressionpropertysubscriptionparameter alertsubscriptiontypegetpropertyentityid memberexpression entitytype expressionpropertysubscriptionparameter alertsubscriptiontypegetpropertyentitytype newexpression innerjoinobject expressionnewsubscribabletypegetconstructornew type typeofint typeofstring entityid entitytype lambdaexpression innerselector expressionlambdainnerjoinobject subscriptionparameter generates alert subscribers new tuplealert ienumerablealertsubscriptionalert subscribers var joinresulttype doubletuplemakegenerictypenew type alerttype typeofienumerablealertsubscription parameterexpression alerttupleparameter expressionparameteralerttype alert parameterexpression subscriberstupleparameter expressionparametertypeofienumerablealertsubscription subscribers newexpression joinresultobject expressionnew joinresulttypegetconstructornew type alerttype typeofienumerablealertsubscription alerttupleparameter subscriberstupleparameter lambdaexpression resultsselector expressionlambdajoinresultobject alerttupleparameter subscriberstupleparameter generates groupjoindatacontextalertsubscriptions a new aadaccountid typeofadaccountname s new sentityid sentitytype alert subscribers new tuplealert ienumerablealertsubscriptionalert subscribers iqueryablealertsubscription alertsubscriptions datacontextalertsubscriptionsasqueryable methodcallexpression joinexpression expressioncalltypeofenumerable groupjoin new type alerttype alertsubscriptionselementtype outerselectorbodytype resultsselectorreturntype unnotifiedalertslist alertsubscriptionsexpression outerselector innerselector resultsselector generates wheres sitem2any parameterexpression subscribersparameter expressionparameterresultsselectorreturntype s memberexpression tuplesubscribers expressionpropertysubscribersparameter resultsselectorreturntypegetpropertyitem2 methodcallexpression hassubscribers expressioncalltypeofenumerable any new type alertsubscriptionselementtype tuplesubscribers lambdaexpression wherelambda expressionlambdahassubscribers subscriptionparameter methodcallexpression whereexpression expressioncalltypeofenumerable where new type joinresulttype joinexpression wherelambda,['c#'] +481632,scroll while using html5 drag and drop i just found that when using html5 drag and drop attempting to use the mousewheel or mouse pad to scroll the page will not work and listeners for the event onmousewheel are not getting calledas an example see here jquery var dragging null itembinddragstart functione dragging ecurrenttarget itembinddragover functione epreventdefault estoppropagation itembinddrop functione epreventdefault estoppropagation draggingunbind dragginginsertbeforeecurrenttarget the example shows 20 divs with scrollbar so you can try dragging item and attempting to scroll the screen the same timei found there is a bug open for firefox for a few years now bugcgiid41708and someone created an extension to support this behaviori could not find any similar bug in chrome is there a solution for this that works in chrome as welledit this does work in safari so the behavior exists in chrome and firefox,['javascript'] +481660,android studio do not know where is java i am getting this errorcannot run program usrlibjvmjava170openjdki386binjava in directory homesergiyandroidstudiopreviewsystemcompileserver error2 no such file or directorythis happens after i remove all jdk open and other some time before i installed oracle jdk from official site so new folder of jdk named jdk170java homeusrlibjvmjdk170jdk homeusrlibjvmjdk170java version 170 21javatm se runtime environment build 170 21b11java hotspottm server vm build 2321b01 mixed modeandroid studio starts without any errors i think that a must rename path to jdk in android studio but how,"['java', 'android']" +481667,angularjs how to orderby the value of an arraylike object in an ngrepeat i have an object that looks like this 03 apple 02 banana 01 cranberryand it orders it by the keys which makes sense in my ngrepeat this results in the labels being out of alphabetical order cranberry being first how do i make it so that it orders my repeater by the values alphabeticallyi can supply it in the order i want to the ngrepeat but it sorts it by the key if i could make it not do that then that would also work,['javascript'] +481682,select multiple records based on list of ids with linq i have a list containing ids of my userprofile table how can i select all userprofiles based on the list of ids i got in a var using linqvar idlist new int1 2 3 4 5var userprofiles datacontextuserprofilewherei got stuck right here i can do this using for loops etc but i would rather do this with linq,['c#'] +481709,how to convert microtime to hhmmssuu i was measuring some curl requests and i used microtimetrue the example output would be 31745569706this is 31745569706 seconds i want to convert that to a somewhat more readable format let us say 0317455 hoursminutessecondsmillisecondsmaxwaittime 31745569706echo gmdatehisu maxwaittime which returns010echo datehisu maxwaittime which returns18010that looks wrong i am not quite sure what i am missing herehow do i convert microtime to hhmmssuu,['php'] +481711,google maps api v3 adding multiple markers w info windows w custom text i am making a website over cyclists killed in norway for my project i have been using google maps api v3 but i have vague familiarity with javascript you can see my result so far here basicly i want to have multiple markers with infowindows on each one each one of the infowindows will containname agelocationdate of deathread more which will be linked to a page on the website itselflike this example here i tried working with just one marker and infowindow and that worked just fine when i want to add new markers with custom info windows on each i get stuck at the moment i have 3 markers on different locations as seen in the first link but none of the info windows appear when i click the markerhow do i go around it to code it so the infowindows appear and how can i have custom text in every infowindow i am going to have about 3040 markers on the map when it is done all of the info windows will have different types of informationfunction initialize var mapoptions center new googlemapslatlng6518303 2047852 zoom 5 maptypeid googlemapsmaptypeidroadmap map controls start maptypecontrol true pancontrol true pancontroloptions position googlemapscontrolpositiontop right zoomcontrol true zoomcontroloptions style googlemapszoomcontrolstylelarge position googlemapscontrolpositionleft top streetviewcontrol true streetviewcontroloptions position googlemapscontrolpositionleft top map controls end var map new googlemapsmapdocumentgetelementbyidmap mapoptions marker 1 var marker1 new googlemapsmarker position new googlemapslatlng5996384 1104120 map map icon imgbike5png marker 1s info window var infowindow1 new googlemapsinfowindow content namebr locationbr datebr br a href target blankread moretest linka end of infowindow code adding a click event to the marker googlemapseventaddlistenermarker1 click function calling the open method of the infowindow infowindow1openmap marker end of 1st marker marker 2 var marker2 new googlemapsmarker position new googlemapslatlng6063040 856102 map map icon imgbike5png marker 2s info window var infowindow2 new googlemapsinfowindow content namebr locationbr datebr br a href target blankread moretest linka end of infowindow code adding a click event to the marker googlemapseventaddlistenermarker2 click function calling the open method of the infowindow infowindow2openmap marker end of 2nd marker marker 3 var marker3 new googlemapsmarker position new googlemapslatlng6039126 532205 map map icon imgbike5png marker 3s info window var infowindow3 new googlemapsinfowindow content namebr locationbr datebr br a href target blankread moretest linka end of infowindow code adding a click event to the marker googlemapseventaddlistenermarker3 click function calling the open method of the infowindow infowindow3openmap marker end of 3rd marker googlemapseventadomlistenerwindow load initializewould be great if some could give me a clue i have tried searching around a bit but i cannot really find my answer thanks in advance,['javascript'] +481719,do associative arrays perform like a hash table so imagine that you have an associative array in javascript as suchvar hashtable hashtablered ff0hashtablegreen 00ff00hashtableblue 0ffwhat happens when you retrieve a value like thisvar blue hashtableblueis the performance similar to that of a hashtable from another language i mean is there an actual hash function that is used to determine the location of the property or is there a looped search such asfor var color in hashtable if hashtablehasownpropertycolor look for matching key does the implementation vary from browser to browser i could not find anything related to this specific topic thanks,['javascript'] +481742,how to touch a habtm relation if you have 2 models video and category and they have a has and belongs to many relation with each other how do you perform a touch to invalidate the cache when one of them changesyou cannot put touch on them like you can with a onetomany relation now when i change a category name the videos that belong to that category do not know about the change until i invalidate the cache my view templates show the name of the category for each video,['ruby-on-rails'] +481755,pcntl fork returning fatal error call to undefined function pcntl fork i am trying to fork a command line run xampp php process using pcntl fork when i run the command belowpid pcntl forkifpid 1 file put contentstestloglogrnfork testfile append return 1 errorelse ifpid return 0 successelse file put contentslog running file appendi getfatal error call to undefined function pcntl forkcan anyone suggest how to fix this,['php'] +481766,uiwebview webpage caching for offline viewing first of all i am pretty sure that i have checked every answer here and nothing does what i would like to do in this question for answer is given asihttprequest which is dead project how do i download an entire webpage with images on the iphonein this question user proposed rncachingurlprotocol which is really great but i had a few problems after closing app completely closing it in taskbar after that i did not get css or images only html was loaded cache a single webpage for use when offline in xcode uiwebviewthere are few more answers but none is good there must be some simple implementation for what i am searchingi would like to when app opens it loads some webpage i want to save that webpage completely now user can quit or do whatever he wants just not uninstall as long as there is some internet connection i check that using reachability class webpage loads normally and it is being saved if user opens app and there is no internet connection i just want to show message that it might not be up to date bla bla boa and show complete saved webpage that was saved last time application has internet connectionwhat would be the best way up to date to save complete webpage iv found something about mknetworkkit but i am not sure how to use that any help would be appreciated,"['ios', 'objective-c']" +481803,android studio error output path is not specified for modules i just recently upgraded to the newest version of android studio 011 but i also used android studio to relocate my project to my dropbox folder so i am not exactly sure which one is causing this problem when i build or try to run my project i get this errorcannot start compilation the output path is not specified for modules actionbarsherlockempubliteempublitespecify the output path in configure projecti cannot find any reference to configure project and the project structure option under file no longer works in this release,['android'] +481811,what is the alternative to nvl function in ms access 2007 i wrote an sql query in ms acceselect nvlcountrerule status0 from validation result re validation rules ru where recycle nbrcycle nbr and rerule responserurule desc and rerule statusfail and rurule categorynaming convention group by rerule statusbut the output is null i want to convert it to zero if i use nvl function then ms access does not accept it i tried nz function also but that also gives the same output ie null instead of zero,['sql'] +481854,getexpresscheckoutdetails returns session expired 10411 error in aspnet only on some computers i got paypal integrated in my aspnet web site its works perfectly on some computers while others it doesntedit found the problem but looking for a solution the problem is as fallowingthings seem to work fine i can pay with paypal and then when it calls getexpresscheckoutdetails it returns 10411 error this express checkout session has expiredi call getexpresscheckoutdetails with the fallowing codepublic bool getdetailsstring token ref nvpcodec decoder ref string retmsg if bsandbox pendpointurl pendpointurl sb host host sb setcredentialsapiusername sb apipassword sb apisignature sb nvpcodec encoder new nvpcodec encodermethod getexpresscheckoutdetails encodertoken token string pstrrequestfornvp encoderencode string pstresponsenvp httpcallpstrrequestfornvp decoder new nvpcodec decoderdecodepstresponsenvp string strack decoderacktolower if strack null strack success strack successwithwarning return true else retmsg errorcode decoderl errorcode0 desc decoderl shortmessage0 desc2 decoderl longmessage0 return false this only happens on some computers and it happens right away not the session should not expire yetany idea what i did wrong can any one please please helpthank you very very much,"['c#', 'asp.net']" +481863,encrypt a column in sql 20 via code or sql script i am using sql 20 a string column password is there in a table users it has around 3k rows my requirement is to encrypt all the values of the password columnalso i should be able to decrypt those encrypted password fields whenever it is neededi know from sql 2005 onward there are inbuilt functionalists for these requirements but i am concerned for sql 20please suggest if there is any way to achieve my requirement via vb code or sql script not with any third party tools i have searched many places but with no successthanks,['sql'] +481883,how to click an element visible after hovering with selenium i want to click a button which is visible after hovering its html is span classinfospani used this codeimport seleniumwebdriver as webdriverfrom seleniumwebdrivercommonaction chains import actionchainsurl driver webdriverfirefoxdrivergeturlelement driverfind element by class nameinfohov actionchainsdrivermove to elementelementhovperformelementclickit is not working though i got a an error connected with the last line of code elementclickseleniumcommonexceptionselementnotvisibleexception message uelement is not currently visible and so may not be interacted with any suggestions please,['python'] +481890,how to convert csv to json in nodejs i am trying to convert csv file to json i am using example csvabcd12345678desired jsona 1b 2c 3d 4a 5b 6c 7d 8i tried nodecsv parser librarybut the output is like array not like i expectedi am using node 08 and expressjs and would like a recommendation on how to easily accomplish this,['javascript'] +481922,saving an uploaded file with httppostedfilebasesaveas in a physical path i would like to save an uploaded file to a physical path by the method httppostedfilebasesaveaswhen i choose a physical path an exception appears indicates that the path must be virtual var filename pathgetfilenamefileurlfilename var path cprojets filename fileurlsaveasservermappathpathhow can i change my code to be able to save the file every where i want,"['c#', 'asp.net']" +481928,why we do create object instance from interface instead of class i have seen many times an interface instance generated from a classwhy does use an interface in this wisean interface instance created only itself with the help of the derived class and we can access only this interface members through this instancehow does this give an advantagei am so confusedinterface iprint void printclass sample iprint public void print consolewritelineprint public void sample consolewritelinesample class program static void mainstring args iprint print new sample printprint,['c#'] +481941,knockoutjs with aspnet mvc just started learning the new aspnet mvc4 spa template noticed that knockout is being used so give me reference to any book video which describes aspnet mvc with knockoutjs from scratch,['c#'] +481954,why does the mongodb java driver use a random number generator in a conditional i saw the following code in this commit for mongodbs java connection driver and it appears at first to be a joke of some sort what does the following code doif ok true mathrandom 01 return resedit the code has been updated since posting this question,['java'] +481988,using times word in html changes to a i am using the following codehtml code div classtesttimesdivjavascriptalerttesthtmli am getting a in alert i need to get times as resultanybody knows or faces this problem please update your suggestions,"['javascript', 'jquery', 'html']" +482010,aspnet web api xml in camelcase we are using web api with mvc 4 and are required to have our requestresponses in camel casewe have done that for json with the following codevar jsonformatter configformattersoftypejsonmediatypeformattersinglejsonformatterserializersettingscontractresolver new camelcasepropertynamescontractresolverthe same code unfortunately does not work for the xmlmediatypeformatterwhat would be the most elegant workaround to format xml in camel case,"['c#', 'asp.net']" +482026,i want to show native alert box for iphone using jquery mobile i have written following code to show a native alert box on iphone using jquery mobile htmlalertid not match it is giving me the native alert but i want to be able to change the titleplease tell me how to changegive a title to an alert box this is how the alert is thisplayed on iosalso see my custom dialog but it does not look like a native alert dialogmy custom dialog does not look native please help me,"['javascript', 'jquery']" +482033,fastest way to check if a string can be parsed i am parsing csv files to lists of objects with stronglytyped properties this involves parsing each string value from the file to an iconvertible type int decimal double datetime etc using typedescriptor i am using a try catch to handle situations when parsing fails the exact details of where and why this exception occurs is then logged for further investigation below is the actually parsing codetry parsedvalue typedescriptorgetconvertertypeconvertfromstringdatavaluecatch exception ex log failureproblemwhen values are successfully parsed the process is quick when parsing data with lots of invalid data the process can take thousands of times slower due to catching the exceptioni have been testing this with parsing to datetime these are the performance figuressuccessful parsing average of 32 ticks per parsefailed parsing average of 146296 ticks per parsethat is more than 4500 times slowerquestionis it possible for me to check to see if a string value can be successfully parsed without having to use my expensive try catch method or perhaps there is another way i should be doing thisedit i need to use typedescriptor and not datetimetryparse because the type is determined at runtime,"['c#', '.net']" +482132,why is home button missing in retina thisplay iphone simulator the latest ios on which i worked was ios 43 however continuing with ios development now on switching to ios 6 i found a lot of different features one interesting and confusing feature is the new look of iphone simulator it has a new shape and does not have home button i was looking at this link and learnt that this was true for devices after iphone 4 including itmy question is why is home button absent for new iphone simulators not considering that former would appear after scaling the latter,['iphone'] +482174,fixing debugkeystore to work with adt 22 and google maps v1 api key after updating my android sdk to revision 2201 and updating the eclipse adt i found that i could no longer install a debug build on a device the console shows this errorinstallation error install parse failed no certificatesi found that i could work around this by deleting my debugkeystore file and letting the sdkadt recreate it this let me build and install a debug packagehowever the app uses the google maps v1 api which requires an api key that is tied to the signature of debugkeystore recreation of debugkeystore invalidated that api key and google is no longer providing new v1 api keys so when i run my debug build the map view is blankthis is not a showstopper as a release build still works fine but is there any way that i can fix my original debugkeystore such that it works with adt 22 and matches my maps v1 api keyfwiw here is the output of keytool list v keystore debugkeystore storepass androidkeystore type jkskeystore provider sunyour keystore contains 1 entryalias name androiddebugkeycreation date feb 20 2012entry type privatekeyentrycertificate chain length 1certificate1owner cnandroid debug oandroid cusissuer cnandroid debug oandroid cusserial number 4f427735valid from mon feb 20 113917 est 2012 until sun nov 16 113917 est 2014certificate fingerprints md5 c8a54e32688a5090c5f5a15b3e9aca86 sha1 0cc45b667f54c84d2c2dd72e9f662994630a197d signature algorithm name sha1withdsa version 3,['android'] +482284,explanation of migrators fluentmigrator could someone explain the concept of migrators specifically fluentmigratorhere are the possibly confused facts ive gleaned on the subjectis it a way to initially create then maintain updates for a databaseby way of versioningthe first migration or initial version of thedatabase would contain all the tables relationships and propertiesrequired done either fluently or using a chunk of sql in a scriptwhen you want to push a change to a database you would create a newmigration method up and down something like add a new table or modify a fieldto deploy one of these migrations you would use acommand line specifying the dll containing the migration theconnection string and the required versionif you had a rather complex set of data models wouldnt it be rather difficult and time consuming to create a migration definition for all of thati know with nhibernatefluent you can easily generate tables for a database without having to define anything other than the models and map files is there a way to make this configuration compatible with the migratorversioningwhen nhibernatefluent is in charge of generating a database i do not necessarily need to define every thing aspect of the tables its done either via convention or via the mapping files with the migrators i would need to define this level of detail,['c#'] +482371,reference to the segue source view controller within my viewdidload i would like some custom code based upon the previous controllerhow can i access the segue source controller or the previous segue identifier in the source controllers viewdidload to handle this,['ios'] +482396,when using multiple when matched statements do they all execute or does only one get executed if i have multiple when matched statements in a merge statement do they all execute if they are truemy exampledeclare x bit nullskipping the merge statement straight to when matchedwhen matched and a 1 x 0when matched and b 1 x 1what is the state of x in each of the 4 possibilitiesabx011011basically i am curious if there is an implicit break after each when matched clause,['sql'] +482413,mysql why is not foo is null optimized away mysql 5528 i have two tables person and message and the latter has a foreign key to the former each table has id as the primary key column and the person table also has a column personid which is uniquely indexedthe query below should take advantage of the personid key index but instead mysql requires scanning the entire message table for some reasonmysql explain select m from message as m left join person as p on mperson pid where m002649397 is null or ppersonid m002649397 id select type table type possible keys key key len ref rows extra 1 simple m all null null null null 273220 1 simple p eq ref primary primary 8 pcommperson 1 using where 2 rows in set 0 secbut when i comment out the m002649397 is null or clause which has no effect on the result the query suddenly gets more efficientmysql explain select m from message as m left join person as p on mperson pid where m002649397 is null or ppersonid m002649397 id select type table type possible keys key key len ref rows extra 1 simple p const primarypersonid personid 767 const 1 using index 1 simple m ref fk9c2397e7a0f6ed11 fk9c2397e7a0f6ed11 9 const 3 using where 2 rows in set 001 secmy question is why is not mysql smart enough to realize that m002649397 is null is always false optimize it away and save having to needlessly scan every row in a huge tablein other words does the mysql optimizer not know that m002649397 is null is always false or is it failing to apply that optimization to the query when constructing its query plan,['mysql'] +482506,java what can and what cannot be serialized if the serializable interface is just a markerinterface that is used for enabling somesort of metadata about classes in java i am a bit confusedafter reading the process of javas serialization algorithm metadata bottomtotop then actual instance data toptobottom i cannot really understand what data cannot be processed through that algorithmand in short and formal what data may cause the notserializableexception and how should i know that i should not add the implements serializable for my class,['java'] +482537,how to implement the deprecated methods of notification i have a small problem but dont understand how to get out of thisi created a class for providing notifications but these lines are marked deprecatednotification notification new notificationicon text time deprecated in api level 11notificationsetlatesteventinfothis title text contentintent deprecated in api level 11alternative methods arenotification noti new notificationbuildermcontext setcontenttitlenew mail from sendertostring setcontenttextsubject setsmalliconrdrawablenew mail setlargeiconabitmap build available from api level 11 and onwardscan i write a code something likeifapi level 11 notification notification new notificationicon text time deprecated in api level 11 notificationsetlatesteventinfothis title text contentintent deprecated in api level 11 else notification noti new notificationbuildermcontext setcontenttitlenew mail from sendertostring setcontenttextsubject setsmalliconrdrawablenew mail setlargeiconabitmap build available from api level 11 and onwards i providing the minimum sdk version as 8editi did like belowint currentapiversion androidosbuildversionsdk int if currentapiversion androidosbuildversion codeshoneycomb notification notification new notificationicon text time pendingintent contentintent pendingintentgetactivitythis 0 new intentthis taskdetailsclass 0 notificationsetlatesteventinfothis title text contentintent notificationflags notificationflag auto cancel mnmnotifynotification notification else what to write here what can i write for else portion,['android'] +482565,run task before compilation using android gradle plugin i have a very simple buildgradle file with the following contentbuildscript repositories mavencentral dependencies classpath comandroidtoolsbuildgradle041 apply plugin androidandroid buildtoolsversion 1700 compilesdkversion 17 sourcesets main manifestsrcfile androidmanifestxml ressrcdirs res assetssrcdirs assets task generatesources dofirst def script python generatesourcespyexecute scriptineachline line println line scripterreachline line println error line scriptwaitfor what i want is to run generatesources task before java compilation is started i found several solutions how to do that like compilejavadependsongeneratesources but unfortunately they give an errora problem occurred evaluating root project android could not find property compilejava on root project androidi do not know gradle and cannot understand whats wrong with this code so i would like to know how i can fix this error,['android'] +482578,how to properly handle innodb deadlocks in javajdbc i am working on a theory basis here i want to make sure all my bases are coveredi have read quite a bit into innodb with java and how deadlocks can occur no matter what query you are running although i am pretty clued in with the theory and best practices i am pretty much clueless on how to implement the catch all mechanism of reissuing transactions when a deadlock occursare there specific exceptions to listen out for is the exception only thrown after i call connectioncommit or can it occur as soon as i execute a preparedstatement should things be running in a loop with a limit to how many times the loop runsi essentially just need a bare bones java code example of how this thing is generally handled as i am not sure where things factor in such as do i reinstantiate preparedstatement objects or close them first etc etc it is all very confusing same goes for resultset objects tooedit i should probably mention that i am working with transactions setting auto commit to 0 etcedit 2 am i on the right track with this pseudo code i have no cluedo deadlock false try auto commit 0 select query update query delete query commit transaction catch deadlockspecificexception e deadlock true finally close resources statementclose resultsetclose etc or do i reuse them somehow and close them after the dowhile loop this stuff confuses me a lot too while deadlock true,"['java', 'mysql']" +482605,sqlconnection and avoiding promotion to msdtc when we need to do database access in our application we use the following patternsfor querying we have a static factory class with a method createopenconnection which does nothing more than new sqlconnectionmyconnectionstring and calls open on it this method gets called before we do a query and the connection is thisposed after the query returnsfor insertsupdatesdeletes we use a unit of work pattern where the changes are batched up and submitted to the database with a call to workcommit like soworkcommitusing var transcope new transactionscopetransactionscopeoptionrequiresnew using var conn dapperfactorycreateopenconnection var count changetrackercommitchangesconn transcopecomplete return count this seems to work great for general usage as part of a webservice but is currently giving me msdtc trouble when i try to use this in combination with rebus from what i can tell rebus when it handles a message in the queue creates a new transactionscope so that in case of a failure to handle the message stuff can be rolled back now this in itself has worked fine so far i can open a new sqlconnection inside a rebus message handler without any issues however using our legacy entity framework queries and manual sqlconnections inside the same rebus transactionscope does not work but i do not consider that an issue right now but yesterday i asked the following questionserial processing of a certain message type in rebusto which the answer seems to be to use the saga feature of rebus i tried implementing this and configured it so that the rebus saga gets persisted to a new sql server database with a thistinct connection string presumably using that sql server persistence opens a sqlconnection of its own because any time i try to create a sqlconnection now i get the following exceptionnetwork access for thistributed transaction manager msdtc has been thisabled please enable dtc for network access in the security configuration for msdtc using the component services administrative toolenabling msdtc is something i would very very much like to avoid doing with regards to configuration and performance overhead and i may be wrong but it also just does not seem necessary what i presume is happening here is that rebus creates an ambient transactionscope and that the sqlconnection it creates enlists to that scope and when i try to create my own sqlconnection it also tries to enlist to that ambient scope and because multiple connections are involved it gets promoted to msdtc which fails i have an idea on how to fix this but i do not know if it is the right thing to do what i would do isadd enlistfalse to my applications connection string so that it never enlists to ambient transactionsmodify the commit method so that it does not create a new transactionscope which my connection would not subscribe to any more because i just told that it should not but that it uses connbegintransactionlike sovar transaction connbegintransactiontry var count changetrackercommitchangesconn transactioncommit return countcatch transactionrollback throwfinally transactionthisposei am just not sure if this is the right approach and what the possible drawbacks are any tipsupdate to clarify it is not the workcommit that is been giving me problems i am quite sure that it would work but i never get there because my querying is what fails an example of what failspublic int getwarehouseidint appid var query select top 1 id from organizationunits owhere typeid 16 16 warehouse using var conn dapperopenconnection var id connqueryintqueryfirstordefault return id this gets called when a transactionscope has been created by rebus as well as after a sqlconnection is opened by rebus upon opening my sqlconnection it tries to enlist and crashes,['c#'] +482620,check words definitions using ibooks app dictionary i see that ibooks app and safari have a builtin dictionary can i access this dictionary words definitions by my own app,['ios'] +482636,are there any drawbacks to using localstorage instead of cookies on my previous websites i used to use a cookie to thisplay a prehome page only on the first visit that worked great see for example here but using cookies is not so trendy today so i want to avoid it as much as possiblenow my new website projects almost always have prehome launched via javascript showing a modalbox so i do not need to do any action on the server side i am considering to use html5 localstorage instead of cookies with a fallback on cookies if the browser does not have localstorage is this a good idea what is the impact in terms of usability privacy protection and website performanceusing localstorage will improve usability for users that have thisabled cookies but i know that some html5 features are only optin like geolocalisation in some browser is there any restriction like that for localstorage on any browser is there any case where i will get a js error if localstorage is available but deactivated for my site,"['javascript', 'html']" +482655,is there a matlab accumarray equivalent in numpy i am looking for a fast solution to matlabs accumarray in numpy the accumarray accumulates the elements of an array which belong to the same index an examplea nparange1 array 1 2 3 4 5 6 7 8 9 10accmap nparray01011221result should be array13 25 17what i have done so fari have tried the accum function in the recipe here which works fine but is slowaccmap nprepeatnparange10 20a nprandomrandnaccmapsizetimeit accumaccmap a npsum 1 loops best of 3 293 ms per loopthen i tried to use the solution here which is supposed to work faster but it does not work correctlyaccum npaccmap a array 1 2 12 13 17 10is there a builtin numpy function that can do accumulation like this or any other recommendations,['python'] +482668,how to execute jquery code depending upon the value received through querystring let me explain the question in detail i am using php and smarty i am getting a value opback from querystring but this is not going to happen everytime the php file runs so when opback is the value i have to fir a click event on a specific link my php file code snippet is given below php include onceincludesteacherapplicationheaderphp prepare request request empty get post get op requestop objteachclasub new teacherclassessubjects global teacher profile from session teacher id teacher profile from sessionteacher id teacher classes subjects objteachclasubgetclasubjectmappingsbyteacheridteacher idsmartyassignteacher classes subjects teacher classes subjects smartyassignopop smartythisplayteacherdetailstpl now the code snippet from smarty file is as belowliteralscript srcscriptscript typetextjavascriptscriptliteraltable width100 border0 aligncenter cellpadding0 cellspacing0 tr td alignleft valigntop h3teacher detailsh3 td trtabletable width99 border0 cellpadding0 cellspacing0 classmanage box tr td table cellpadding0 cellspacing0 border1 width100 tr td width25 if teacher classes subjects foreach fromteacher classes subjects itemclasses subjects ba href idclasses subjectsclass idclasses subjectsclass nameabbr if classes subjectsclass subjects div idclass subjects classes subjectsclass id foreach fromclasses subjectsclass subjects itemclass subjects ia id back hrefchapter detailsphpclass idclasses subjectsclass idcs map idclass subjectscs map idclass subjectssubject nameaibr foreach div br if foreach if td td width75 if chapter details ul foreach fromchapter details itemchapter lia hrefchapter detailsphpopget chapter theorychapter idchapterchapter idclass idclass idcs map idcs map idchapter titlechapterchapter titlechapterchapter titleali foreach ul if include filefile to show td aly what is tr table td td alignleft idsubject container valigntop td td alignleft idchapter container valigntop td trtablenow what i want to achieve is to write a jquery code in the above smart template file which will execute if the op value is backieopback actually what is expected is when the opback click event should get fire on the following linka id back hrefchapter detailsphpclass idclasses subjectsclass idcs map idclass subjectscs map idclass subjectssubject nameacan anyone explain me how to achieve this functionality thanks in advance,"['php', 'jquery']" +482711,messagebox not showing focused after savefiledialog for some reason after my savefiledialog my app will never show the messagebox is there something i am missing or is this a threading issuei run the application as a windows form application using vs 2010 expressi do not get any exceptionsto add when i step through the code all seems to go well which is weird so i believe it is a timing issuepointed out by larstech and others the messageboxes do show up however the focus is gone in other words the messagebox is pushed behind other windows or minimized this is a problemusing systemusing systemcollectionsgenericusing systemlinqusing systemtextusing systemwindowsformsusing systemglobalizationusing systemionamespace speeddating class program stathread static void mainstring args string filename testtest args0 string ext filenamesubstringfilenamelastindexof savefiledialog dialog new savefiledialog dialogtitle speeddating app dialogrestoredirectory true dialogcheckfileexists false dialogcheckpathexists false dialogfilename datetimenowtostringymmdd ext dialogresult result dialogshowdialog if result dialogresultok dialogfilename try filestream outfs filecreatedialogfilename filestream infs fileopenfilename filemodeopen infscopytooutfs infsclose outfsclose catch notsupportedexception ex messageboxshowprobably removed the original file else messageboxshowno path found to write to messageboxshowi came here and all i got was this louzy printline,['c#'] +482720,how should i serialize domain model snapshots for event sourcing we are building an application using the lmax thisruptor when using event sourcing you often want to persist periodic snapshots of your domain model some people call this the memory image patterni need a better solution than what we are currently using to serialize our domain model when taking a snapshot i want to be able to prettyprint this snapshot in a readable format for debugging and i want to simplify snapshot schema migrationcurrently we are using googles protocol buffers to serialize our domain model to a file we chose this solution because protocol buffers are more compact than xml json and using a compact binary format seemed like a good idea to serialize a big java domain modelthe problem is protocol buffers were designed for relatively small messages and our domain model is quite big so the domain model does not fit in one big hierarchical protobuf message and we end up serializing various protobuf messages to a file like thisfor each account write simple account fields id name description as one protobuf message write number of user groups for each user group convert user group to protobuf message and serialize it for each user convert user to protobuf message and serialize it for each sensor convert sensor to protobuf message and serialize it this is annoying because manipulating a stream of heterogenous protobuf messages is complicated it would be a lot easier if we had one big protobuf message that contained all of our domain model like thispublic class aggregateroot listaccount accounts convert to big hierarchical protobuf message using some mapping codemessage aggregaterootmessage repeated accountmessage accounts 1 persist this big message to a fileif we do this it is easy to prettyprint a snapshot simply read the big protobuf message then prettyprint it using protobufs textformat with our current approach we need to read the various protobuf messages one by one and prettyprint them which is harder since the order of the protobuf messages in the stream depends on the current snapshot schema so our prettyprinting tool needs to be aware of thati also need a tool to migrate snapshots to the new snapshot schema when our domain model evolves i am still working on this tool but it is hard because i have to deal with a stream of various protobuf messages instead of dealing with just one big message if it were just one big message i could take the snapshot file parse the file as a big java protobuf message using the proto schema for the previous snapshot version convert this big protobuf message into a big protobuf message for the new version using dozer and some mapping code write this new protobuf message in a new file using the proto schema for the new versionbut since i am dealing with a stream of protobuf messages of various types my tool needs to handle this stream in the correct orderso yeah i guess my questions aredo you know any serialization tool that can serialize a big domain model into a file without protobufs limitations possibly using streaming to avoid outofmemorryerrorsif you use event sourcing or memory images what do you use to serialize your domain model json xml protobuf something elseare we doing it wrong do you have any suggestions,['java'] +482738,mmh who are you priu64 i am new to c and i am confronted withinclude stdiohinclude inttypeshint mainvoid uint64 t foo 10 printffoo is equal to priu64 n foo return 0and it works i do not understand why can somebody help me about thisthanks a lottorr,['c'] +482757,ruby best practice if not empty each do else in one operator 1i cannot find an elegant way to write this codeif arrayempty process empty arrayelse arrayeach do el process el endendi would like to have one loop without writing array twice i read this but there is no solution good enough2i am actually in an haml template same question if arrayempty p no result else ul arrayeach do el li el,['ruby'] +482778,how should one use stdoptional i am reading the documentation of stdexperimentaloptional and i have a good idea about what it does but i do not understand when i should use it or how i should use it the site does not contain any examples as of yet which leaves it harder for me to grasp the true concept of this object when is stdoptional a good choice to use and how does it compensate for what was not found in the previous standard c11,['c++'] +482789,android dialog rounded corners and transparency i am trying to make a custom android dialog with rounded corners my current attempts have given me this result as you can see the corners are rounded but it leaves the white corner still intact below is the xml that i put in the drawable folder to create the blue dialog with the red border with the rounded cornersxml version10 encodingutf8layerlist xmlnsandroid item shape androidshaperectangle solid androidcolorcolortransparent black corners androidradiusdimenborder radius shape item item androidleftdimenborder width androidrightdimenborder width androidtopdimenborder width androidbottomdimenborder width shape androidshaperectangle solid androidcolorcolorblue corners androidradiusdimenborder radius shape item layerlistbelow is the layout of the dialogxml version10 encodingutf8linearlayout xmlnsandroidstylestylefillandroidorientationverticalandroidlayout margindimenspacing normalandroidpaddingdimenspacing normalandroidbackgrounddrawableborder error dialog relativelayout stylestyleblock androidlayout gravitycenter imageview androidididimageview1 stylestylewrap androidlayout alignparentlefttrue androidlayout centerhorizontaltrue androidcontentdescriptionstringcontent description filler androidsrcdrawableic launcher textview androidididtextview1 stylestyleerror text androidlayout centerverticaltrue androidlayout torightofidimageview1 androidtextstringerror login relativelayoutbutton androidididbutton1 stylestylewrap androidlayout gravitycenter androidtextbutton linearlayoutand below is the activity in which i create the dialogoverrideprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main button b1 button findviewbyidridbutton1 b1setonclicklistenernew viewonclicklistener override public void onclickview v alertdialogbuilder alertdialogbuilder new alertdialogbuildermainactivitythis view child getlayoutinflaterinflaterlayoutdialog custom tom null alertdialogbuildersetviewchild alertdialog alertdialog alertdialogbuildercreate alertdialogshow,['android'] +482805,java android getresourcesgetidentifier how do i get the int id value from r for an id when i use getidentifier its just returns 0 int i getargumentsgetintselection number string drawerselection getresourcesgetstringarrayrarraydrawerselection arrayiint panelid thisgetresourcesgetidentifierdrawerselectiontolowercaseidgetactivitygetpackagenameeditxmllinearlayout xmlnsandroidandroidlayout widthmatch parentandroidlayout heightmatch parentandroidorientationvertical listview androidididbus schedules androidlayout widthmatch parent androidlayout heightwrap content listviewlinearlayoutlog0610 212430372 isystemout3572 selection bus schedules0610 212430372 isystemout3572 panelid 0rjava public static final class id public static final int bus schedules0x7f0904 public static final int basemenu0x7f0905 public static final int content frame0x7f0901 public static final int drawer layout0x7f090 public static final int left drawer0x7f0902,"['java', 'android']" +482809,selenium get elements html rather text value via that code i have extracted all desired text out of a html document private void runthroughsearchstring url private iwebdriver driver driver new firefoxdriver inavigation nav drivernavigate navgotourlurl var div driverfindelementbyidresults var element driverfindelementsbyclassnamesa wrthough as i need to refine results of extracted document container header title of a given block url link to the relevant block text body of a given blockcontaineras you can see in my code i am able to get the value of the text part as a text value that was fine but what if i want to have the value of the container as html and not the extracted text div classcontainer div classheader titlediv div classurl wexamplecoildiv div classresconent bla divdivso the container is about 10 times in a page i need to extract it is innerhtml any ideas using selenium,['c#'] +482855,jquery animate and backgroundcolor i am trying to create a simple pulse effect by changing the background color using jquery however i cannot get the backgroundcolor to animatefunction show userdnid dnid is html id of a div if dnidisvisible dnidshow html bodyanimatescrolltop dnidoffsettop dnidanimatebackgroundcolor db1a35 1200whats strange is that this alternate animation worksdnidanimateopacity toggle 1200but it is not what i want at alladditionally the show and scroll functionality in the function work fine it is just the background color animation that does notthe function above is called by this link a href onclickjavascriptshow user9e4cde88b904ea722e9e129ed83747locate meacould someone help me animate the background colorthanks everyone for the help lots of similar answers heres what i ended up within my headerscript srcscriptthen in my show user function right after the scroll animationvar bgcol dnidcssbackgroundcolordnidanimatebackgroundcolor db1a35 20dnidanimatebackgroundcolor bgcol 20that gives a relatively quick red pulse that will draw the users eyesagain thanks for the help,"['javascript', 'jquery', 'css']" +482874,android localstorage thisappear after erasing the app from ram i am using cordovawebview and trying to use localstorage to cache users username and password however though it is suggested that the localstorage is lasting i find that every time i erase the app from the ram the localstorage goes away so how to prevent this from happening by erasing the app from ram i mean the action of killing the apps process from the background eg in android 40 holding the home button and click on the cross,['android'] +482886,mvvm propertychanged in model or viewmodel i have gone through a few mvvm tutorials and i have seen this done both ways most use the viewmodel for propertychanged which is what i have been doing but i came across one that did this in the model are both methods acceptable if so what are the benefitsdrawbacks of the different methods,['c#'] +482889,setting the height to a div to a multiple of line height how do you express the height of a div as a multiple of its line height in pure css without hardcoding line height or font sizebackgroundi have a box a div that contains status text the text will sometimes span multiple lines and often need only one the status is updated several five times per second and this causes the bottom border and everything below the box to jump up and down as the box changes size to fits its contentsone solution to the jumping would be to set the minheight of the div to the height of two lines status text with more than two lines is rare so that degree of jumping would be acceptablealternatively i could set the height to the exact height of two lines and use overflowhide to truncate the text that would eliminate all jumping at the expense of some informationwhich raises the question how do i express height as a multiple of line height the status text inherits its appearance from the global style sheet and does not know font size family line height or anythinghalfsolutioni can use the em unit to express height without knowing anything about the font but that still leaves the line height property which also affects the final line heightideally i would prefer to inherit line height but if i override it to a known multiplier then i can force the box to become exactly two lines tallprogrestatus lineheight 11 height 22emthis solution is good enough for my needs but i am curious if there is a better solution that does not involve javascript,['css'] +482926,how to completely hide superclass method in java recently i am thinking about making my own date libraryand i am finding a problem here here it ishow do i hide a superclass method in subclass so it would not be detected in subclass examplei have a class that extends to date and another class that extends to the previous classin my new subclass it detects all the methods from date like getdate etcwhat i want is that in my subclass all the methods from date are undetected not throwing an exception but completely undetectedthanks in advance,['java'] +482928,what does vendor mean in web file structure every now and then i see vendor being used in a directory structure on web appslike thisscript srcjsvendormodernizr262minjsscript what does this mean why do people use itmore importantly should i use it i make web apps using php and javascript,"['php', 'html']" +482959,javafx illegalstateexception when thisposing jfxpanel in swing i have just come across an oddity with javafx and swingwhen thisposing a javafx panel that had been added to a jframe or jpanel readding a new jfxpanel will throw an illegalstateexception platformexit has been calledin my case this has happened after i removed some jpanels with jfxpanels inside and then tried to readd them,['java'] +482984,accessing posted json data in php script i am using the requests for php library to post some json data to another php script i am using laravels responsejson method to generate the json outputpublic function postindex input inputget data responsejsoninput url response requestsposturl arraycontenttype applicationjson data return responsestatus codei need the script on the receiving end to decode and process the json but i am having a hard time accessing it i setup a simple test script that emails me the contents of post but it comes up empty every timepost data print r posttruemailpost datapost datawhat am i doing wrong here,['php'] +482985,vector in namespace std does not name a type i am developing a c application using codeblocks 1005 on debian 700for some reason the following codeinclude iostreamstdvector int delaunaydivconst stdvector int t vp cvrect boundrect stdvectorint triangles int numtriangles bool lookrightreturns the following errorerror vector in namespace std does not name a type,['c++'] +483017,pre increment vs post increment in array i am new to stackoverflow and this is my first post i am learning programming and i have started from c language i was reading let us c book and i was going through this program in that bookmain int a5 5 1 15 20 25 int i j k 1 m i a1 j a1 m ai printf nd d d i j m my understanding was it will print i as 2 j as 1 and m as 15but somehow it is printing as i as 3 j as 2 and m as 15 why is it sobelow is my understandingb xin this example suppose the value of variable axa is 5 then value of variable aba will be 5 because old value of axa is usedb yin this example suppose the value of variable aya is 5 then value of variable aba will be 6 because the value of aya gets modified before using it in a expressionis there anything wrong in my understanding,['c'] +483060,test if string is not equal to either of two strings i am just learning ror so please bear with me i am trying to write an if or statement with strings here is my code if controller name sessions or controller name registrations i have tried many other ways using parentheses and but nothing seems to work maybe its because of my js backgroundhow can i test if a variable is not equal to string one or string two,['ruby'] +483075,inconsistent scope of use strict on different web browsers concerning argumentscallee and caller situationi found something strange concerning strict mode in javascripti am using an external thirdparty javascript library whichwas minifiedhas over 40 lines of codeis not using use strict at all andis using argumentscalleei am using use strict in my own code scoped within a functionwhen i call one of the functions provided by the library it throws an error howeverthe error is thrown only if i am using use strictthe error is thrown in all browsers except chromecodei have removed all the unrelated stuff and reduced the code into this online demo on jsfiddle this comes from the minified external js library it creates a global object foofunction foo foobar function e return function var a5 argumentscallee while a5 a5 a5caller error on this line in all browsers except chrome any value here heres my codefunction use strict i enable strict mode in my own function only foobar alertdonetest result browser os error chrome 270145394 m win no error opera 1215 win unhandled error illegal property access firefox 210 win typeerror access to strict mode caller function is censored safari 517 win typeerror type error ie 10 win script5043 accessing the caller property of a function or arguments object is not allowed in strict mode chrome 270154393 mac no error opera 1215 mac unhandled error illegal property access firefox 210 mac typeerror access to strict mode caller function is censored safari 604 mac typeerror functioncaller used to retrieve strict caller note for os win windows 7 mac mac os 1075my understandingall modern desktop browsers support use strict see can i usethe use strict is scoped within my function so everything defined outside its scope is not affected see this stack overflow questionquestionso are all browsers except chrome wrong or is it the other way round or is this undefined behaviour so the browsers may choose to implement it in either way,['javascript'] +483088,why is namespace composition so rarely used in his book the c programming language third edition stroustrup teaches to define individual components in their own namespace and import them in a general namespacefor examplenamespace array api struct array void printconst array namespace list api struct list void printconst list namespace api using array apiarray using list apilisti looks interesting but i have never seen this approach used in practicewhy is this technique is almost never used,['c++'] +483155,how to split a delimited nsstring into nsarray i have a little problem when i try to split delimited string into an array basically i want to pass result from mecard qrcode and add new entry to addressbookhere is my code for firstname field only nslogfound cbnslog codetext codecontentabaddressbookref addressbook abaddressbookcreateabrecordref person abpersoncreatensstring and nsstring stringwithformat codetext codecontentnsarray n and componentsseparatedbystringnslog codetext nabrecordsetvalueperson kabpersonfirstnameproperty name nilabaddressbookaddrecordaddressbook person nilcfreleaseaddressbookabnewpersonviewcontroller c abnewpersonviewcontroller alloc initc setnewpersonviewdelegateselfc setthisplayedpersonpersoncfreleasepersonselfnavigationcontroller pushviewcontrollerc animatedyesc releasemecard qrcode is well decoded viewcontroller appears but all the url as mecardnnameorgcompanytel89878978 etc goes in first field fistname fieldwhat am missing to separate my mecard url send right data in right field thanks for your answers any help will be greatly appreciated have a good day,['ios'] +483224,does stdatomic work appropriately i am reading through anthony williams c concurrency in action and in chapter 5 which talks about the new multithreadingaware memory model and atomic operations and he statesin order to use stdatomicudt for some userdefined udt this type must have a trivial copy assignment operatoras i understand it this means that we can use stdatomicudt if the following returns truestdis trivially copyableudtvalueby this logic we should not be able to use stdstring as a template argument for stdatomic and have it work correctlyhowever the following code compiles and runs with expected outputinclude atomicinclude threadinclude iostreaminclude stringint main stdatomicstdstring atomicstring atomicstringstore teststring1 stdcout atomicstringload stdendl atomicstringstore teststring2 stdcout atomicstringload stdendl return 0is this a case of undefined behaviour which just happens to behave as expectedthanks in advance,['c++'] +483243,used gem install rails and now i have 400rc1 i want rails 3 how can i switch backi installed rvm then installed ruby 193 then ran gem install railsrunning rails v i can see that i have rails 400rc1 and i do not want to use that version as it is not supported on my hosting providerhow can i install rails 3213 and have that be used as default when running rails new commands,"['ruby-on-rails', 'ruby']" +483262,cannot connect to database from file i try to connect through microsoft sql server database file sqlclient but i recieve errorthe attempt to attach to the database failed with the following information a networkrelated or instancespecific error occurred while establishing a connection to sql server the server was not found or was not accessible verify that the instance name is correct and that sql server is configured to allow remote connections provider sql network interfaces error 52 unable to locate a local database runtime installation verify that sql server express is properly installed and that the local database runtime feature is enabledso i click connect to database in server explorerthis window show up in which i choose microsoft sql server database file sqlclient and then browse my mdf database file clicking ok gives error mentioned beforeserver is running i use windows authentication in databaseany sugestions,['c#'] +483333,sharing data between angularjs controllers how do i store the items i have selected in a checkbox with other controllersmy attempt see the plnkr for viewsscriptjs controllersvar myapp angularmodulemyapp myappfactorycooselection function return selectedcoo function coolistctrlscope cooselection scopecoos coos spark nark hark quark scopecoo list selection cooselection scopecheckselection function item if scopecoo list selectionindexofitem 1 scopecoo list selectionpushitem else scopecoo list selectionsplicescopecoo list selectionlastindexofitem 1 coolistctrlinject scope cooselectionfunction debugcoolistscope cooselection scopecoo selection cooselectiondebugcoolistinject scope cooselection,['javascript'] +483346,how to port existing c code to c11 we are working on a module that is developed in c but given the new c11 i am thinking about migrating to thathow to proceed are both the same or is there some compiler dependencymy software currently supports windows and linux i am using microsoft visual studio as well as gcc to build itoverall what changes are needed if any,['c++'] +483405,selenium webdriver js explicit wait i am using the seleniumwebdriverjs i want to wait for a certain element to be thisplayed for which i have created an explicit wait as follows and it works just finevar thisplayed falsedriverwaitfunction driverfindelementlocatoristhisplayedthenfunctionvalue thisplayed value return thisplayed timeoutis this the best i can do or is there a better way to do this the reason i ask is that the first time ever the wait callback is called in my case it will always return false only subsequently when the isthisplayed promise is executed will the value of thisplayed change,['javascript'] +483421,equivalent of movement for python files for languages with to denote blocks vim has the almighty key what is the equivalent movement thing for python code or at least to move to next previous line with the same indent,['python'] +483469,error could not fetch model of type basicideaproject using gradle thistribution in windows when i try to open a project by clicking at my buildgradle i see this messagecould not fetch model of type basicideaproject using gradle thistribution the supplied javahome seems to be invalid i cannot find the java executable tried location cprogram files x86jetbrainsintellij idea community edition 121jrebinjavaexei think this happens because intellij searches jre at the wrong folder because in my intellij directory i have this sctructure cprogram files x86jetbrainsintellij idea community edition 121jrejrebinjavaexeof course i can move the jrejrebin folder to the jre but if i do this i see this another message when try openning the projecterror could not open cprogram files x86jetbrainsintellij idea community edition 121jrelibi386jvmcfgthat is it cannot find the lib folder again i can copy the jrejrelib folder to the jre folder but already there is a folder called lib at the jre folder that contains only the file toolsjar so how can i do intellij to search at right folderupdatethis is my java homecprogram files x86javajre7,"['java', 'android']" +483475,dialogfragment not resizing when keyboard shown i am trying to use a sherlockdialogfragment to ask some input from the user everything works fine on my phone galaxy nexus 42 but on a smaller phone emulator 233 when the keyboard shows up it covers the two buttons of the dialogfragment like thismy layout is inside a scrollview and i am changing the softinputmode to soft input adjust resize on my onviewcreated i also tried soft input adjust pan and it did not workmycustomdialogjavapublic class addtaskdialog extends sherlockdialogfragment implements ondatesetlistener override public void onviewcreatedview view bundle savedinstancestate superonviewcreatedview savedinstancestate getdialoggetwindowsetsoftinputmodewindowmanagerlayoutparamssoft input adjust resize public dialog oncreatedialogbundle savedinstancestate use the builder class for convenient dialog construction alertdialogbuilder builder new alertdialogbuildergetactivity thisinflater getactivitygetlayoutinflater view mainview inflaterinflaterlayoutcustom dialog null buildersetviewmainview thistasknote edittext mainviewfindviewbyidridet tasknote thistasktext edittext mainviewfindviewbyidridet tasktext thistaskvalue edittext mainviewfindviewbyidridet taskvalue other stuff buildersettitlegetstringrstringnew task htypetostring setpositivebuttonrstringdialog confirm button new dialoginterfaceonclicklistener public void onclickdialoginterface dialog int id setnegativebuttonrstringdialog cancel button new dialoginterfaceonclicklistener public void onclickdialoginterface dialog int id user cancelled the dialog create the alertdialog object and return it return buildercreate and here is my layoutcustom dialogxmllinearlayout androidlayout widthmatch parentandroidlayout heightmatch parentandroidorientationvertical androidbackgroundcolorabs background holo light linearlayout androidlayout widthmatch parent androidlayout heightwrap content androidpaddingleftdimenactivity vertical margin androidpaddingrightdimenactivity vertical margin textview androidididtv tasktext androidlayout widthwrap content androidlayout heightwrap content androidtextstringtask text androidtextappearanceandroidattrtextappearancelarge edittext androidididet tasktext androidlayout width0dip androidlayout heightwrap content androidlayout weight1 androidems10 androidhintstringcreate task hint androidinputtypetextnosuggestions androidsinglelinetrue linearlayout linearlayout androidlayout widthmatch parent androidlayout heightwrap content androidpaddingleftdimenactivity vertical margin androidpaddingrightdimenactivity vertical margin textview androidididtv tasknote androidlayout widthwrap content androidlayout heightwrap content androidtextstringtask note androidtextappearanceandroidattrtextappearancelarge edittext androidididet tasknote androidlayout width0dip androidlayout heightwrap content androidminlines2 androidlayout weight1 androidems10 androidinputtypetextmultiline androidhintstringtask note hint edittext linearlayout linearlayout androidididrepeat days androidlayout widthwrap content androidlayout height48dp androidlayout gravitytop androidorientationhorizontal androidvisibilitygone androidpaddingleftdimenactivity vertical margin androidpaddingrightdimenactivity vertical margin day buttons are put here programatically linearlayoutlinearlayoutso could you help me and guide me on how to show those buttons either to pan the view or let it resize,['android'] +483487,css background gradient with offset i applied a gradient as background image to my body then i added 255px offset at the top using backgroundposition0 255pxit looks quite good except one little issue of course the gradient does not end at the bottom of the page but 255px underneathis there any easy way to let the gradient end at the bottom but start with offset from to weinertar6jc,['css'] +483512,date to string in social format i am trying to achieve letas say asociala date format i already have a solution but it feels like a better one should exist why social and what do i meanif we look into facebook time stamps of the posts we can thistinguish between next optionsx seconds agox minutes agox hours agoyesterday at 1107 amfriday at 936 pmmay 5 at 500 pmnovember 20 at 905 pm 2012i made next visual timeline for better explanationfor example if the current time is 533 pm 20 sec wednesday the social post happened between 0 am tuesday 533 pm 20 sec tuesday then the date format should be like yesterday at 1107 am solution i havei check each option 7 in count and return social date stringthis is how i check for option 1date postdate getpostdatedate nowdate getnowdate check passed secondsint passedseconds getpassedsecondspostdate nowdateif passedseconds 60 return passedseconds seconds ago this is how i check for option 4 check yesterdaydate startyesterdaydate getzerodaybeforedaysnowdate 1int compare comparestartyesterdaydate postdate if postdate comes after startyesterdaydateif compare 1 return yesterday at getstringpostdate hhmmai check other options in the same mannersome methods i use in my if statements abovepublic static string getstringdate date string format format formatter new simpledateformatformat localeus string s formatterformatdate return s for example today 1 day param date param numofminusdays return public static date getdateminusdaysdate date int numofminusdays calendar calendar calendargetinstance calendarsettimedate calendaraddcalendarday of month 0 numofminusdays return calendargettime get the day before today at 0 ambr means if passed day bnov 5 1304b then returned date will be bnov 4 0b for days 1 param date param days numner of days to reduce return public static date getzerodaybeforedaysdate date int days calendar yesterday calendargetinstance yesterdaysettimegetdateminusdaysdate days yesterdaysetcalendarhour of day 0 yesterdaysetcalendarminute 0 yesterdaysetcalendarsecond 0 yesterdaysetcalendarmillisecond 1 return yesterdaygettimefinally my questionsis there a better way of converting the difference between two dates to social string format as i said i feel that some other way like maybe extending dateformat object could be used but i am not surehow to localize the strings like yesterday and at such that different local set will change the strings to suitable language sorry for such a long question but i could not find shorter way to explain the needthanks,['java'] +483524,how to thisable eclipse cdt code formatter for a code block the cdt code formatter has a pretty decent selection of options but it does not seem to have to a feature that allows one to tell it to ignore a block of code this feature exists in the java code formatter formatteroff code that should not be formatted formatterondoes this feature exist and i just do not know about it or does anyone know of any decent workaroundsin my particular case i am trying to define data structures enum types and arrays of strings that i want to have specific layouts,['c++'] +483536,edit namephone number of contact programmatically i am trying to modify thisplayed name of a contact programmatically try arraylistcontentprovideroperation ops new arraylistcontentprovideroperation opsaddcontentprovideroperationnewupdatedatacontent uri withselectioncontactscontractcommondatakindsphone id new string contact id withvaluecontactscontractcommondatakindsphonethisplay name anything build contentproviderresult result getcontentresolverapplybatchcontactscontractauthority ops catch exception e logwupdatecontact egetmessage forstacktraceelement ste egetstacktrace logwupdatecontact t stetostring context ctx getapplicationcontext int duration toastlength short toast toast toastmaketextctx update failed duration toastshow contact id is contactscontractcommondatakindsphone id gathered in previous activitycode executes fine but contentproviderresult result is nullcontact name remains unchangedi have experimented also with datathisplay name but with same effecti read the manual but i do not want to call native intentthanks,['android'] +483575,ios app programmatically get build version is there a way to programmatically get the build version of my app i need to be able to detect when the user has updated the app through the appstore in order to execute some code for adjustments,"['ios', 'objective-c']" +483616,on windows 7 how does java jvm set userhome system property i am using jre 17 and i thiscovered the userhome system property is very unusual how does the jvm set this value,['java'] +483617,running phantomjs from javascript jsp or java hi i am new to phantomjsi have generated html to pdf by using command but i want to generate pdf by clicking a button on the page and call phantomjs by some way to generate my given url to pdfyou can also suggest some api that generate generate pdf as html with charts and images and can easily integrated with jsp and servlet,"['java', 'javascript']" +483637,uibarbuttonitem sizes differ i have an app which uses storyboards to thisplay two screens the first one is a list referred on screenshot as lista and the second one is a map tarkap each view has a left and a right navigation button pressing the right button pushes the map view to the navigation controller the back button is hidden manually from the maps viewdidload methodthe question is that why do the bar button items have different size on each screen how can i control the size of the buttonsthe images on the buttons are in the same size skinning is done in appdelegate through appearance settings navbar backgrounduinavigationbar appearance setbackgroundimageuiimage imagenamedbgtitlebarpng forbarmetricsuibarmetricsdefault navbar button backgrounduibarbuttonitem appearance setbackgroundimageuiimage imagenamedbtnmainpng resizableimagewithcapinsetsuiedgeinsetsmake40 40 40 40 resizingmodeuiimageresizingmodestretch forstateuicontrolstatenormal barmetricsuibarmetricsdefaultuibarbuttonitem appearance setbackgroundimageuiimage imagenamedbtnmainactivepng resizableimagewithcapinsetsuiedgeinsetsmake40 40 40 40 resizingmodeuiimageresizingmodestretch forstateuicontrolstatehighlighted barmetricsuibarmetricsdefault back button backgrounduibarbuttonitem appearance setbackbuttonbackgroundimageuiimage imagenamedbtnbackpng resizableimagewithcapinsetsuiedgeinsetsmake40 120 40 40 resizingmodeuiimageresizingmodestretch forstateuicontrolstatenormal barmetricsuibarmetricsdefaultuibarbuttonitem appearance setbackbuttonbackgroundimageuiimage imagenamedbtnbackactivepng resizableimagewithcapinsetsuiedgeinsetsmake40 120 40 40 resizingmodeuiimageresizingmodestretch forstateuicontrolstatehighlighted barmetricsuibarmetricsdefault,"['iphone', 'ios']" +483654,remove a prefix from a string i am trying to do the following in a clear pythonic waydef remove prefixstr prefix return strlstripprefixprint remove prefixtemplateextensions templatethis givesxtensionswhich is not what i was expecting extensions obviously stupid me because i have used lstrip wrongly lstrip will remove all characters which appear in the passed chars string not considering that string as a real string but as a set of characters to remove from the beginning of the stringis there a standard way to remove a substring from the beginning of a string,['python'] +483660,publish one web project from solution with msbuild i am trying to deploy one of the web projects in my solution to a server i am using msbuild on teamcity like somsbuild mysolutionsln twebsiterebuild pdeployonbuildtrue ppublishprofileprod however when i run it msbuild still tries to build my webservice project even though my website project does not depend on it but it does depend on a services project also in the solution how do only publish one project aka just websitei have also tried building the project file usingmsbuild websitewebsitecsproj pdeployonbuildtrue but it then complains that it cannot restore packages074717websitewebsitecsprojteamcity build target build074717websitewebsitecsprojteamcity restorepackages074717restorepackages exec074717exec cteamcitybuildagentworkcab8a3d752df3a51nugetnugettargets90 15 error msb4064 the logstandarderroraserror parameter is not supported by the exec task verify the parameter exists on the task and it is a settable public instance property074717exec cteamcitybuildagentworkcab8a3d752df3a51nugetnugettargets89 9 error msb4063 the exec task could not be initialized with its input parameters 074717websitewebsitecsprojteamcity project websitewebsitecsprojteamcity failedwhen i thisable nuget package restore corecompile csc fails with errors i have never heard of and should not be happening075443websitewebsitecsprojteamcity build target build 13s075455websitewebsitecsprojteamcity corecompile075455corecompile csc075456csc areasapiservicestripservicecs19 104 error cs0241 default parameter specifiers are not permitted075456csc helpersstatisticsutilitycs11 35 error cs1031 type expected075456csc helpersstatisticsutilitycs11 53 error cs1002 expected075456csc helpersstatisticsutilitycs16 28 error cs1519 invalid token in class struct or interface member declaration075456csc helpersstatisticsutilitycs16 37 error cs1519 invalid token in class struct or interface member declaration075456csc helpersstatisticsutilitycs17 27 error cs1519 invalid token in class struct or interface member declaration075456csc helpersstatisticsutilitycs17 32 error cs1519 invalid token in class struct or interface member declaration075456csc helpersstatisticsutilitycs23 17 error cs1519 invalid token for in class struct or interface member declaration075456csc helpersstatisticsutilitycs23 26 error cs1519 invalid token in class struct or interface member declaration075456csc helpersstatisticsutilitycs23 45 error cs1519 invalid token in class struct or interface member declaration075456csc helpersstatisticsutilitycs23 51 error cs1519 invalid token in class struct or interface member declaration075456csc helpersstatisticsutilitycs24 34 error cs0270 array size cannot be specified in a variable declaration try initializing with a new expression075456csc helpersstatisticsutilitycs24 37 error cs1519 invalid token in class struct or interface member declaration075456csc helpersstatisticsutilitycs24 51 error cs1519 invalid token in class struct or interface member declaration075456csc helpersstatisticsutilitycs24 63 error cs1519 invalid token in class struct or interface member declaration075456csc helpersstatisticsutilitycs25 41 error cs1519 invalid token in class struct or interface member declaration075456csc helpersstatisticsutilitycs25 53 error cs1519 invalid token in class struct or interface member declaration075456csc helpersstatisticsutilitycs27 36 error cs1519 invalid token in class struct or interface member declaration075456csc helpersstatisticsutilitycs27 48 error cs1519 invalid token in class struct or interface member declaration075456csc helpersstatisticsutilitycs28 36 error cs1519 invalid token in class struct or interface member declaration075456csc helpersstatisticsutilitycs29 37 error cs1519 invalid token in class struct or interface member declaration075456csc helpersstatisticsutilitycs29 48 error cs0270 array size cannot be specified in a variable declaration try initializing with a new expression075456csc helpersstatisticsutilitycs29 50 error cs1519 invalid token in class struct or interface member declaration075456csc helpersstatisticsutilitycs30 33 error cs1519 invalid token in class struct or interface member declaration075456csc helpersstatisticsutilitycs30 44 error cs0270 array size cannot be specified in a variable declaration try initializing with a new expression075456csc helpersstatisticsutilitycs30 50 error cs1519 invalid token in class struct or interface member declaration075456csc helpersstatisticsutilitycs32 21 error cs0116 a namespace does not directly contain members such as fields or methods075456csc helpersstatisticsutilitycs35 50 error cs1518 expected class delegate enum interface or struct075456csc helpersstatisticsutilitycs38 21 error cs0116 a namespace does not directly contain members such as fields or methods075456csc helpersstatisticsutilitycs40 50 error cs1518 expected class delegate enum interface or struct075456csc helpersstatisticsutilitycs42 21 error cs1022 type or namespace definition or endoffile expected075456csc helpersurlhelperextensionscs8 59 error cs1031 type expected075456csc helpersurlhelperextensionscs8 80 error cs1002 expected075456csc helpersurlhelperextensionscs10 55 error cs1519 invalid token in class struct or interface member declaration075456csc helpersurlhelperextensionscs10 60 error cs1520 class struct or interface method must have a return type075456csc helpersurlhelperextensionscs10 82 error cs1002 expected075456csc helpersurlhelperextensionscs13 23 error cs1518 expected class delegate enum interface or struct075456csc helpersurlhelperextensionscs15 60 error cs1518 expected class delegate enum interface or struct075456csc helpersurlhelperextensionscs18 23 error cs1518 expected class delegate enum interface or struct075456csc helpersurlhelperextensionscs20 25 error cs1518 expected class delegate enum interface or struct075456csc helpersurlhelperextensionscs23 28 error cs1518 expected class delegate enum interface or struct075456csc helpersurlhelperextensionscs26 28 error cs1518 expected class delegate enum interface or struct075456csc helpersurlhelperextensionscs29 24 error cs1518 expected class delegate enum interface or struct075456csc helpersurlhelperextensionscs29 84 error cs1518 expected class delegate enum interface or struct075456csc helpersurlhelperextensionscs32 28 error cs1518 expected class delegate enum interface or struct075456csc helpersurlhelperextensionscs35 9 error cs1022 type or namespace definition or endoffile expected075456csc helpersurlhelperextensionscs23 26 error cs0101 the namespace global namespace already contains a definition for 075456csc helpersurlhelperextensionscs26 26 error cs0101 the namespace global namespace already contains a definition for 075456csc helpersurlhelperextensionscs29 22 error cs0101 the namespace global namespace already contains a definition for 075456csc helpersurlhelperextensionscs29 83 error cs0101 the namespace global namespace already contains a definition for 075456csc helpersurlhelperextensionscs32 26 error cs0101 the namespace global namespace already contains a definition for 075456csc controllerssessioncontrollercs13 51 error cs0241 default parameter specifiers are not permitted075456csc helpersjsonnetresultcs13 44 error cs1031 type expected075456csc helpersjsonnetresultcs13 72 error cs1041 identifier expected object is a keyword075456csc helpersjsonnetresultcs13 91 error cs1002 expected075456csc helpersjsonnetresultcs16 38 error cs1519 invalid token in class struct or interface member declaration075456csc helpersjsonnetresultcs16 59 error cs1519 invalid token in class struct or interface member declaration075456csc helpersjsonnetresultcs17 64 error cs1519 invalid token in class struct or interface member declaration075456csc helpersjsonnetresultcs17 90 error cs1519 invalid token in class struct or interface member declaration075456csc helpersjsonnetresultcs18 32 error cs1519 invalid token in class struct or interface member declaration075456csc helpersjsonnetresultcs18 46 error cs1519 invalid token in class struct or interface member declaration075456csc helpersjsonnetresultcs19 33 error cs1519 invalid token in class struct or interface member declaration075456csc helpersjsonnetresultcs22 23 error cs1518 expected class delegate enum interface or struct075456csc helpersjsonnetresultcs25 37 error cs1518 expected class delegate enum interface or struct075456csc helpersjsonnetresultcs32 23 error cs1518 expected class delegate enum interface or struct075456csc helpersjsonnetresultcs35 37 error cs1518 expected class delegate enum interface or struct075456csc helpersjsonnetresultcs40 9 error cs1022 type or namespace definition or endoffile expected075456csc mailersitripmailercs13 132 error cs0241 default parameter specifiers are not permitted075456csc mailerstripmailercs54 85 error cs0241 default parameter specifiers are not permitted075456csc servicesimplauthorizationservicecs12 70 error cs0241 default parameter specifiers are not permitted075456csc servicesimplauthorizationservicecs43 77 error cs0241 default parameter specifiers are not permitted075456websitewebsitecsprojteamcity project websitewebsitecsprojteamcity failed,['c#'] +483668,c non template method in template class is it posible to write implementation of non template method in template clastruct at cpp file i have read that template method should be written on h but my method is not template method although it belongs to template class here is the code in my hinclude iostreamifndef key value hdefine key value husing namespace stdnamespace types template class t class u struct key value t key you value static key valuet u maket key you value key valuet u kv kvkey key kvvalue value return kv string serialize code to serialize here i want to write in cpp but fails endif key value h i tried to write the implementation of method serialize in cpp file like thisinclude key valuehusing namespace typestemplate class t class ustring key valuet userialize code here returning stringended up with error redefinition of serialize how is the proper way to doing this,['c++'] +483682,mysql after insert trigger which updates another tables column i am trying to write a trigger i have following tables bookingrequest field type null key default extra idrequest int11 no pri null auto increment roomclass int11 no null indate date no null outdate date no null numofbeds int11 no null status int11 no mul null iduser int11 no mul null status table field type null key default extra idstatus int11 no pri null namestatus enumunderconsiderationapprovedrejected yes null occupiedroom field type null key default extra idoccupation int11 no pri null auto increment idroom int11 no null idrequest int11 no null i need a trigger which will change status in bookingreques to 1 if request with the same id is inserted into occupiedroom table so i tried something like thiscreate trigger occupy trig after insert on occupiedroom for each rowbegin if bookingrequestidrequest newidrequest then update bookingrequest set status 1 where idrequest newidrequest end ifendand it does not work so any suggestions would be very appriciated,['mysql'] +483687,tailing log file and write results to new file i am not sure how to word this so i will type it out and then edit and answer any questions that come upcurrently on my local network device php4 based i am using this to tail a live system log file this works well and every 1 second it loads an external page logfilephp that does a tail n 100 logfilelog the script does not do any buffering so the results it thisplayes onscreen are the last 100 lines from the log filethe logfilephp contains logtailphp cmd tail 10 pathtoyourlogssomelog execcmd 21 outputforeachoutput as outputline echo outputlinenthis part is working welli have adapted the logfilephp page to write the outputline to a new text file simply using fwritefpoutputlinenwhilst this works i am having issues with duplication in the new file that is createdobviously each time tail n 100 is run produces results the next time it runs it could produce some of the same lines as this repeats i can end up with multiple lines of duplication in the new text filei cannot directly compare the line i am about to write to previous lines as there could be identical matchesis there any way i can compare this current block of 100 lines with the previous block and then only write the lines that are not matching again possible issue that block a b will contain identical lines that are neededis it possible to update logfilephp to note the position it last tooked at in my logfile and then only read the next 100 lines from there and write those to the new file the log file could be upto 500mb so i do not want to read it all in each timeany advice or suggestions welcomethanksupdate 1630i have sort of got this working using file logssystloghandle fopenfile rifisset sessionftell clearstatcache fseekhandle sessionftell while buffer fgetshandle echo bufferbr ob flush flush fclosehandle sessionftell ftellhandle else fseekhandle 1024 seek end fclosehandle sessionftell ftellhandlethis seems to work but it loads the entire file first and then just the updateshow would i get it start with the last 50 lines and then just the updates thanks update 04062013whilst this works it is very slow with large filesi have tried this code and it seems faster but it does not just read from where it left ofunction last linespath line count block size 512 lines array we will always have a fragment of a noncomplete line keep this in here till we have our next entire line leftover fh fopenpath r go to the end of the file fseekfh 0 seek end do need to know whether we can actually go back block size bytes can read block size ifftellfh block size can read ftellfh go back as many bytes as we can read them to data and then move the file pointer back to where we were fseekfh can read seek cur data freadfh can read data leftover fseekfh can read seek cur split lines by n then reverse them now the last line is most likely not a complete line which is why we do not directly add it but append it to the data read the next time split data array reverseexploden data new lines array slicesplit data 0 1 lines array mergelines new lines leftover split datacountsplit data 1 whilecountlines line count ftellfh 0 ifftellfh 0 lines leftover fclosefh usually we will read too many lines correct that here return array slicelines 0 line countany way this can be amend so it will read from the last known position thanks,"['php', 'jquery']" +483713,inapp purchase for autorenewal subscriptions notifications i have been reading the various threads on inapp purchases autorenewal subscriptions and i think i have pieced together most of the information i need but there are a few missing pieces i am hoping someone can help methe situationi have various subscription packages the user can subscribe to eg package a for a1 a month package b for a2 a month etc i store the users subscription information in my database when the user logs in i check which package he is on and if it is expired or not my website android and ios all use the same database hence this approach seems to make sensesubscribing users via inapp purchase seems straight forward enough i check paymentqueue and once the payment is cleared i can update my databasemy questions1 my understanding is the user can use itunes to manage their subscription say they go in to itunes and cancel their subscription how can i be notified so i can update my database do i need a daemon that checks expired subscriptions to see if the user renewed2 if the user wants to upgrade their subscription from package a to package b how do i handle the pricing say on jan 1st they buy package a i charge them a100 and set the expiry date to jan 31st on jan 15th they want to upgrade to package b via inapp purchase ideally i would charge them a2 for package b minus a050 of credit they have for package a and set the new expiry date to feb 14th however apple forces me to associate each package with a tier price how can i handle this i do not want the user to wait until the end of the month to put them on a higher tier packageif they upgraded midmonth it means they want the new content package b will deliver to them immediatelyany help appreciatedthanks,['ios'] +483734,how to get unique array of objects in javascripts i want to get array having unique objects say i have array of objects abcdab and i want unique value of array ieabcdis there any simplest way to do this,"['javascript', 'jquery']" +483765,how to declare stdunique ptr and what is the use of it i try to understand how stdunique ptr works and for that i found this document the author starts from the following exampleinclude utility declarations of unique ptrusing stdunique ptr default constructionunique ptrint up creates an empty object initialize with an argumentunique ptrint uptr new int3double pd new doubleunique ptrdouble uptr2 pd overloaded and uptr2 235unique ptrstdstring ups new stdstringhelloint lenupssizewhat is confusing to me is that in this lineunique ptrint uptr new int3we use integer as an argument between round brackets and hereunique ptrdouble uptr2 pdwe used an pointer as an argument does it make any difference what is also not clear to me is how pointers declared in this way will be different from the pointers declared in a normal way,['c++'] +483775,c custom compare function for stdsort i want to create custom compare function for stdsort to sort some keyvalue pairs stdpairhere is my function template typename k typename v int comparepairsconst void left const void right ifpairkvleftfirst pairkvrightfirst return 1 else return 1 then inside some class i have vector of pairs class membervectorpairkv items and some method for sort this vector by keys using stdsortstdsortitemsbegin itemsend comparepairskvi have compilation errors within which said cannot convert parameter number from stdpair ty1 ty2 to const void what is a mistake,['c++'] +483784,spring autowiring service does not work in my controller i have problems in order to autowire a service in my controller i have this errororgspringframeworkbeansfactorybeancreationexception error creating bean with name mycontroller injection of autowired dependencies failed nested exception is orgspringframeworkbeansfactorybeancreationexception could not autowire field private esunicanmeteoserviceuserservice esunicanmeteocontrollermycontrolleruserservice nested exception is orgspringframeworkbeansfactorynosuchbeandefinitionexception no matching bean of type esunicanmeteoserviceuserservice found for dependency expected at least 1 bean which qualifies as autowire candidate for this dependency dependency annotations orgspringframeworkbeansfactoryannotationautowiredrequiredtrueit seems that the userservice is not registered so that the controller cannot get the bean i thought that my config was ok because it works with the tests in the tests i have thisclasspathxmlapplicationcontextwebinfappconfigxmland i can get the bean ok from the applicationcontextxmlmy package structure is the followingesunicanmeteocontroller mycontrollerjavaesunicanmeteoservice userservicejavaesunicanmeteoserviceimpl userserviceimpljavawebcontentwebinf mythispatcherservletservletxml appconfigxml webxmlthe clases userserviceimpljava servicepublic class userserviceimpl implements userservice autowired private usermapper usermapper public void setusermapperusermapper usermapper thisusermapper usermapper mycontrollerjava controllerpublic class mycontroller autowired private userservice userservice requestmappingmethodrequestmethodget valuehome public string handlerequest return welcome requestmappingmethodrequestmethodget valuegetusers public responsebody listuser getusersinjson return userservicegetusers webxml thisplaynamespring mvcthisplayname servlet servletnamemythispatcherservletservletname servletclassorgspringframeworkwebservletthispatcherservletservletclass servlet servletmapping servletnamemythispatcherservletservletname urlpatterngourlpattern servletmappingwebapp appconfigxml xml version10 encodingutf8beans xmlns xmlnsxsi xmlnscontext xmlnsp xmlnsmvc xsischemalocation scans the classpath of this application for components to deploy as beans contextcomponentscan basepackageesunicanmeteo configures the controller programming model mvcannotationdriven bean iddatasource classorgspringframeworkjdbcdatasourcedrivermanagerdatasource pdriverclassnameorgapachederbyjdbcembeddeddriver purljdbcderbyctoolsderbydb pconnectionproperties pusernameapp ppassword bean idtransactionmanager classorgspringframeworkjdbcdatasourcedatasourcetransactionmanager property namedatasource refdatasource bean bean idsqlsessionfactory classorgmybatisspringsqlsessionfactorybean property namedatasource refdatasource property nameconfiglocation valuemybatisconfigxml bean bean idusersmapper classorgmybatisspringmappermapperfactorybean property namemapperinterface valueesunicanmeteodaousermapper property namesqlsessionfactory refsqlsessionfactory bean bean idrolesmapper classorgmybatisspringmappermapperfactorybean property namemapperinterface valueesunicanmeteodaorolemapper property namesqlsessionfactory refsqlsessionfactory bean beans mythispatcherservletxml xml version10 encodingutf8beans xmlns xmlnsxsi xmlnscontext xmlnsmvc xsischemalocation enabling spring beans autothiscovery contextcomponentscan basepackageesunicanmeteocontroller enabling spring mvc configuration through annotations mvcannotationdriven defining which view resolver to use bean class orgspringframeworkwebservletviewinternalresourceviewresolver property nameprefix valuewebinfviews property namesuffix valuejsp beanspring mvc logger trace193854119 debug http80801 supportdefaultlistablebeanfactory430 creating instance of bean mycontroller193854170 debug http80801 annotationinjectionmetadata60 found injected element on class esunicanmeteocontrollermycontroller autowiredfieldelement for private esunicanmeteoserviceuserservice esunicanmeteocontrollermycontrolleruserservice193854174 debug http80801 supportdefaultlistablebeanfactory504 eagerly caching bean mycontroller to allow for resolving potential circular references193854206 debug http80801 annotationinjectionmetadata85 processing injected method of bean mycontroller autowiredfieldelement for private esunicanmeteoserviceuserservice esunicanmeteocontrollermycontrolleruserservice193854224 debug http80801 supportdefaultlistablebeanfactory217 creating shared instance of singleton bean userserviceimpl193854226 debug http80801 supportdefaultlistablebeanfactory430 creating instance of bean userserviceimpl193854234 debug http80801 annotationinjectionmetadata60 found injected element on class esunicanmeteoserviceimpluserserviceimpl autowiredfieldelement for private esunicanmeteodaousermapper esunicanmeteoserviceimpluserserviceimplusermapper193854237 debug http80801 supportdefaultlistablebeanfactory504 eagerly caching bean userserviceimpl to allow for resolving potential circular references193854256 debug http80801 annotationinjectionmetadata85 processing injected method of bean userserviceimpl autowiredfieldelement for private esunicanmeteodaousermapper esunicanmeteoserviceimpluserserviceimplusermapper193854268 info http80801 supportdefaultlistablebeanfactory433 destroying singletons in orgspringframeworkbeansfactorysupportdefaultlistablebeanfactory56088b29 defining beans mycontrollerroleserviceuserserviceimplorgspringframeworkcontextannotationinternalconfigurationannotationprocessororgspringframeworkcontextannotationinternalautowiredannotationprocessororgspringframeworkcontextannotationinternalrequiredannotationprocessororgspringframeworkcontextannotationinternalcommonannotationprocessororgspringframeworkwebservletmvcmethodannotationrequestmappinghandlermapping0orgspringframeworkformatsupportformattingconversionservicefactorybean0orgspringframeworkwebservletmvcmethodannotationrequestmappinghandleradapter0orgspringframeworkwebservlethandlermappedinterceptor0orgspringframeworkwebservletmvcmethodannotationexceptionhandlerexceptionresolver0orgspringframeworkwebservletmvcannotationresponsestatusexceptionresolver0orgspringframeworkwebservletmvcsupportdefaulthandlerexceptionresolver0orgspringframeworkwebservlethandlerbeannameurlhandlermappingorgspringframeworkwebservletmvchttprequesthandleradapterorgspringframeworkwebservletmvcsimplecontrollerhandleradapterorgspringframeworkwebservletviewinternalresourceviewresolver0orgspringframeworkcontextannotationconfigurationclasspostprocessorimportawarebeanpostprocessor0 root of factory hierarchy193854279 error http80801 servletthispatcherservlet457 context initialization failedi have reviewed some questions about this topic but i do not find a solution to my problem maybe i am skipping something but i do not know certainly i tried to change the componentscan with no resultswhen i try to access to springmvcgetusersgo appears those errorsi do not know if the beans must be placed in appconfig applicationcontext or in the servletxml because it is a little bit confusingthank you,['java'] +483821,oraclepl sqlsql null comparison on where clause just a question about dealing will null values in a queryfor example i have the following table with the following fields and valuestablexcolumn11 2 3 4 5 column2nullabcnulli am passing a variabley on a specific procedure inside the procedure is a cursor like this cursor c results is select from tablex where column2 variableynow the problem is variabley can be either null a b or cif the variabley is null i want to select all record where column2 is null else where column2 is either a b or ci cannot do the above cursorquery because if variabley is null it would not work because the comparison should be cursor c results is select from tablex where column2 is nullwhat cursorquery should i use that will accomodate either null or string variablesorry if my question is a bit confusing i am not that good in explaining things thanks in advance,['sql'] +483922,what is the difference between policy15 and policy12 i have got a basic service hostm host new servicehostm service m baseaddreservicemetadatabehavior behavior new servicemetadatabehaviorbehaviorhttpgetenabled truebehaviormetadataexporterpolicyversion policyversionpolicy15m hostdescriptionbehaviorsaddbehaviorm hostaddserviceendpoint typeofimanagerservice new basichttpbinding m soapaddressm hostopenmy question is how do i know which policyversion to use the msdn is not very helpful it seems to think i should know already if i want 12 or 15policyversionpolicy15 propertypolicyversionpolicy12 property,['c#'] +483931,angularjs ngrepeat across multiple elements this question has been partly addressed here angularjs ngrepeat across multiple trshowever that is just a workaround really it does not actually address the core issue which is how can one use ngrepeat across multiple elements without a wrapperfor example jqueryaccordion requires you to repeat an h3 and div element how could one do this with ngrepeat,"['javascript', 'jquery']" +483963,how to implement decision matrix in c i need to make a decision based on a rather large set of 8 codependent conditions a b c d e f g hdecision01 0 1 1 0 1 1decision02 1 0 0 0 1 decision11 1 0 1 1 1 1 1each of the conditions from a to h can be true 1 false 0 or nonrelevant for the decisionso with a given input of a b c d e f g h 1 0 1 0 0 1 1 1it should evaluate to decision02the decisions are unambiguous so from any given set of input conditions it is clear which decision has to be made and in a case that is not covered by the decision matrix an exception shall be thrownthe developer who worked before me on this project tried to implement this as a 500 line long nestedif behemoth which of course is buggy as hell and is not maintainableso i searched for the best way to implement such a piece of logic and i have come upon decision tableslookup tablescontrol tablesi have found a lot of decision table generators but not a single piece of code on how to implement the decision making process i can make the decision table in the underlying mssql database or in code or xml or whatever it takes i just need some pointers on how to implement this at all whats the best practice to implement this logic dictionary multidimensional array something completely different,['c#'] +483975,why does boost include two different versions of strong typedefhpp as i was building a project recently i noticed that i got a compiler warning turned to error about the boost strong typedef macro being redefined upon further investigation i noticed that there are two different versions of strong typedefhpp included in boost one at the top level and one within serializationthere is actually a difference between the two versions as well not just a duplicate version of the macro the top level version does not explicitly valueinit its t while the serialization version doescode snipsbooststrong typedefhpp t t explicit dconst t t tt d dconst d t tt t boostserializationstrong typedefhpp t t explicit dconst t t tt d t dconst d t tt t why are there two different versions of the macro and which one makes more sense as the implementation the one that will force builtin types to be initialized or the one that does not as closely as possible mimicing the underlying type being strongly typedeffed,['c++'] +483983,overriding fontface src url we are using fontawesome with bootstrap however when we try to use fa with our custom minifier it attempts to load the fonts from a relative path which returns a 404 due to the way the minified url structure is setupso we figured the best way to fix this was to add an additional css file to our minify list that would override the fontface src urls that fontawesomes font uses we basically just copied the fontface definition from fontawesome and specified absolute url locationshowever now what happens is our correct urls load the fonts and the originally specified urls from the fontawesome css are attempted resulting in the same 404 errors as before are we doing something wrong or is there really no way to override the fontface src urls so that upstream definitions are totally ignored,['css'] +484000,local storage mysql vs json i am working on an app that is going to be parsing processing and formatting a lot of data blocks stellar position and brightness data a single night of data can have a dozen files each consisting of several hundred lines i have two options for storage and access of the raw data database mysql or json files this is all in a local environment so bandwidth and request times are virtually negligible but i do not know enough about either option to say which is optimalcan you the enlightened so community share your knowledge as to whether or not one is the clear choice i do not really need to fragment the data so mysqls relational capabilities are moot just wondering if one is faster or more lightweighttried my best to dodge the which is better taboo if i can reword or clarify please let me knowedit seriously anonymous close votes are not helpful i would like to learn how to form my questions better so as not to waste everyones time tell what i can do to change it,['mysql'] +484001,memory leaks with custom font for set custom font the following code for setting custom fonts slows down my whole app how do i modify it to avoid memory leaks and increase the speed and manage memory wellpublic class fonttextview extends textview private static final string tag fonttextview public fonttextviewcontext context supercontext public fonttextviewcontext context attributeset attrs supercontext attrs setcustomfontcontext attrs public fonttextviewcontext context attributeset attrs int defstyle supercontext attrs defstyle setcustomfontcontext attrs private void setcustomfontcontext ctx attributeset attrs typedarray a ctxobtainstyledattributesattrs rstyleablefonttextview string customfont agetstringrstyleablefonttextview customfont setcustomfontctx customfont arecycle public boolean setcustomfontcontext ctx string asset typeface tf null try tf typefacecreatefromassetctxgetassetsfonts asset catch exception e logetag could not get typeface egetmessage return false settypefacetf return true,['android'] +484012,select2 programmatically controlling placeholder i want to change the placeholder on a select2 enhancing control upon an eventso i have got thisselect idmyfoo placeholderfight some foowhich is then enhancedinit function myfooselect2so now it has its correct placeholderbut then i want it to react to an event and clear the placeholdersomebuttonpress function myfooplaceholder myfooattrplaceholder myfooselect2placeholder myfooselect2placeholder none of these workthis seems so basic yet i am stumpedcannot find anything in the docs or am i looking in the wrong place,['jquery'] +484022,backbonejs collection containing multiple models with same id i have a merged collection in backbone which contains photos and albumsto thistinguish between them i have added a field type which is either photo or album when i populate the collection i create different models within the collectionmodel method model attrs options switch attrstype when album then new appmodelsalbumattrs options when photo then new appmodelsphotoattrs optionsnow i have thiscoverd a strange bug where adding a photo and an album with the same id let us say 2 results in a mergei have tracked this down to these loc in the source code it seems that it is undoable without creating a fork of backbone itself i have tried it but it also fails 35 testsi thought of 4 different ways of doing this i do not know which of them is the better onei could add a prefix to the id let us say photo 2 this causes a change in the backend as well as some changes in the frontend to do not hit the server at photosphoto 2i could fork backbone and change these loci could create two separate collections but have to deal with a merge and a sort in the view which effects clients performance and requires a rewriting of the backendi could start with a photo id of let us say 10 this would extremely decrease the probability that a given user which has uploaded a photo with a given id has also created an album with the same id,['javascript'] +484024,connect to device with bluetooth address on string i am doing an android app and where i have the mac of another device as a string 17 characters long and need to use that one in order to connect to that device thread that initiates a bluetooth connectioni have been playing around with it all afternoon and cannot figure out how to do it the problem is that it does not allow me to set the bluetoothdevice equal to a string is there a way that this canhas to be donedecided not to put any of my attempts here as code seeing how they were full of errorsit has to communicate with another tablet that is running the exact same application i looked through this page earlier and most of my app is based on that my main problem is when using the connectthread example i have a string with the mac address how do i connect to that macany help would be highly appreciated,['android'] +484067,is it possible to serializedeserialize json to java dto with extra fields going into a map i have a dto like thispublic foo public int bar 123 public mapstring object params key1v1 key2v2 etci would like it to serialize tofrom the following json bar 123 key1 v1 key2 v2 does anyone know how to do this using jackson or genson basically i want automatic type conversions for the fields declared in the dto but any extras to go into the params map,['java'] +484084,cannot access nonstatic method in static context given this codepublic class calibrationviewmodel viewmodelbase private filesystemwatcher fsw public calibrationviewmodelcalibration calibration fsw new filesystemwatcher path cusersuserdesktoppathtofiletest 1234txt filter test 1234txt notifyfilter notifyfilterslastwrite fswchanged o e var lastline filereadalinesefullpathlast thispatcherbegininvokeactionstring writelinetosamplescollection lastline line that cites error private void writelinetosamplescollectionstring line do some work why am i getting the error cannot access nonstatic method begininvoke in static contexti have looked at several other examples on se and most cite trying to use a field before the object is created as if they were trying to use a nonstatic field in a static manner but i do not understand what it is about my code that is invoking the same errorlastly what can i do to fix this specific issuecodeupdate fixed title to reflect issue with a method and not a property i also added that the class implements viewmodelbase,['c#'] +484141,how to get an array of all words used on a page so i am trying to get an array of all the words used in my web pageshould be easy rightthe problem i run into is that bodytextsplit returns an array where the words at the beginning of one element and end of another are joined as oneiediv id1hello div id2worlddivdivreturns helloworld when i want it to return hello worldi also triedwordarr function gettexttarget ifthischildren thischildrenfunctiongettextthis else var testarr thistextsplit forvar i 0 i testarrlength i wordarrpushtestarri gettextbodybut nodechildren is truthy for any node in the dom that exists so that did not worki am sure i am missing something obvious so i would appreciate an extra set of eyesfor what it is worth i do not need unique words just every word in the body of the document as an element in the array i am trying to use it to generate context and lexical cooccurrence with another set of words so duplicates just up the contextual importance of a given wordthanks in advance for any ideassee fiddle,"['javascript', 'jquery']" +484157,is anyone out there using robolectric without maven on intellij all the examples of using robolectric i can find seem to be maven based is anyone not using maven if so i would really like to understand your intellij project setuphaving read this post androidunittestapproachesit seems sensible to have a tiered approach to unit testig android projects with a combination of pure junit robolectric android test framework tests if anyone who is doing this with or without maven i would love to understand a little bit about how you configured your projects in intelliji am guessing i will need multiple projects modules any wisdom on this gratefully received,['android'] +484162,how to use query syntax to create permutations i have tried to write a method which returns the permutation of a given enumerable as simple as possible the code using systemcollectionsgenericpublic static partial class permutable static ienumerableienumerablet permuteiteratort ienumerablet source int offset var count0 foreachvar dummy in source ifcountoffset foreach var sequence in permutablepermuteiterator sourceexchangeoffset count1 1offset yield return sequence ifoffsetcount1 yield return source public static ienumerableienumerablet aspermutablet this ienumerablet source return permutablepermuteiteratorsource 0 public static ienumerablet exchanget this ienumerablet source int index1 int index2 exchange elements at index1 and index2 as the code has simplified within the iterator block i am trying to make it simply a single query expression of linq there is a recursion in the nested foreach with this code even another possibly yield outside the foreach and which is the difficult part for me to rewrite it in query syntax i have read this answerc string permutationbut i guess it is not the solution for me i tried various ways and think it is not so easy to do how can i get it donethe exchange method is another problem and i have asked a question how to exchange the items of enumeration by interating only oncebut i guess it is not the matter here,['c#'] +484178,strongly typed string the settingi have a prototype class typedstringt that attempts to strongly type dubious meaning strings of a certain category it uses the canalogue of the curiously recurring template pattern crtpclass typedstringtpublic abstract class typedstringt icomparablet iequatablet where t typedstringt public string value get private set protected virtual stringcomparison comparisontype get return stringcomparisonordinal protected typedstringstring value if value null throw new argumentnullexceptionvalue thisvalue parsevalue may throw formatexception protected virtual string parsestring value return value public int comparetot other return stringcomparethisvalue othervalue comparisontype public bool equalst other return stringequalsthisvalue othervalue comparisontype public override bool equalsobject obj return obj is t equalsobj as t public override int gethashcode return valuegethashcode public override string tostring return value the typedstringt class can now be used to eliminate code duplication when defining a bunch of different string categories throughout my project an example simple usage of this class is in defining a username classclass username examplepublic class username typedstringusername public usernamestring value basevalue protected override string parsestring value if valueany throw new formatexceptionusername must contain at least one character if valueallcharisletterordigit throw new formatexceptionusername may only contain letters and digits return value this now lets me use the username class throughout my whole project never having to check if a username is correctly formatted if i have an expression or variable of type username it is guaranteed to be correct or nullscenario 1string getuserrootdirectoryusername user if user null throw new argumentnullexceptionuser return pathcombineusersdirectory usertostringi do not have to worry about formatting of the user string here i already know it is correct by nature of the typescenario 2ienumerableusername getfriendsusername user here the caller knows what it is getting as the return just based on the type an ienumerablestring would require reading into the details of the method or documentation even worse if someone were to change the implementation of getfriends such that it introduces a bug and produces invalid username strings that error could silently propagate to callers of the method and wreak all kinds of havoc this nicely typed version prevents thatscenario 3systemuri is an example of a class in net that does little more than wrap a string that has a huge number of formatting constraints and helper propertiesmethods for accessing useful parts of it so that is one piece of evidence that this approach is not totally crazythe questioni imagine this kind of thing has been done before i already see the benefits of this approach and do not need to convince myself any moreis there a downside i may be missingis there a way this could come back to bite me later,['c#'] +484185,tinymce is not defined jquery have been working on this error for 2 days and cannot get tinymce to work i am using the jquery version of tinymce below is my html code with a form that contains a textarea i use google inspect element and under the console tab i get the following error uncaught referenceerror tinymce is not defined any help would be appreciatedform idadd update form action methodpost titleadd blogp classfeedbackp labelcreatedlabelinput typetext namecreated labeltitlelabelinput typetext nametitle classinputblocklevellabelcontentlabeltextarea width100 rows10 cols10 namecontent classinputblockleveltextareadiv classcleardivformscript srcajaxgoogleapiscomajaxlibsjquery180jqueryminjs typetextjavascriptscriptscript srcphp echo base urljsportaltinymcejquerytinymceminjsscriptscript typetextjavascripttinymceinitselector textareaplugins advlist autolink lists link image charmap print preview anchor searchreplace visualblocks code fullscreen insertdatetime media table contextmenu paste moxiemanagertoolbar insertfile undo redo styleselect bold italic alignleft aligncenter alignright alignjustify bullist numlist outdent indent link imagescript,['jquery'] +484222,how to do integration testing on android with the new gradle build system our android app needs automated testing and our group is using robotium to handle that for us this is no problem for unit tests but were also writing a set of endtoend integration tests to exercise not only the client by the backend servers as well i have got some tests that do this but if possible i would like to break them out separately from the unit tests so that our continuous integration builds do not require a live server to be running in order to completewere using the shiny new gradle build system i am wondering if i could do something like a testonly flavor or a subproject that depends on the parent apk to make it go i tried making this work with a separate project altogether using the robotium instructions for testing a sourceless debug apk but it did not work maybe because i was on real hardware and not an emulator i have had poor luck with the emulator even with the hardware acceleration installedany advice or should i just hold my breath and roll with my builds requiring the integration server to be available when builds are happening,['android'] +484223,thisplayformat not working with nullable i am trying to format some datetimes in mvc but the thisplayformat is not being applied to the nullable object and i cannot figure out why it worked perfectly fine on createddatetime but not lastmodifieddatetimethisplayformatapplyformatineditmode true dataformatstring 0mmddyy hhmm ttpublic datetime createddatetime get set thisplayformatapplyformatineditmode true dataformatstring 0mmddyy hhmm ttpublic nullabledatetime lastmodifieddatetime get set below is the view div classeditorfield htmlthisplayformodel modelcreateddatetime br htmlrawtimeagogetstringtimemodelcreateddatetime div if modellastmodifieddatetimehasvalue div classeditorlabel htmllabelformodel modellastmodifieddatetime div div classeditorfield htmlthisplayformodel modellastmodifieddatetime br htmlrawtimeagogetstringtimemodellastmodifieddatetimevalue by htmlthisplayformodel modellastmodifiedby div,['c#'] +484249,get row with highest or lowest value from a group by i am trying to get the row with the highestlowest number after performing a group byhere is my test datamysql select from test id value name 1 10 row1 2 12 row2 3 10 row2 4 5 row2 4 rows in set 0 secto get the lowest value i will use minmysql select id name minvalue as value from test group by name id name value 1 row1 10 2 row2 5 2 rows in set 0 secnow the id row2 is 2 but it should be 4i also tried with a joinmysql select t1 from select id name minvalue as value from test group by name as t1 inner join test as t2 on t1id t2id id name value 1 row1 10 2 row2 5 2 rows in set 0 sechow can i get the correct id for each result based on what the lowest value is,"['mysql', 'sql']" +484261,where is the documentation for fragmentoncreateanimator the entire documentation for the fragmentoncreateanimatorint boolean int method consists of the following textcalled when a fragment loads an animationthat is it no explanation about the parameterswhat do the parameters mean even the source code does not reveal much,['android'] +484365,what is the primary usage of upstream messaging in gcm cloud connection server what is the usage of cloud connection server that was announced at google io 2013i am interested to know whether i can use the upstream messaging feature to send specific messages to gcm server for example can i send a command to delete a gcm notification that is stored on the gcm server or is it only used to send custom messages if so why do we need it at all,['android'] +484401,can not scroll the viewpager when touching textviewwith androidgravitycenter in it in my viewpager there was a imagebutton and textview hold by linearlayout and now i change them to one textview with coupound drawable xml version10 encodingutf8comiclinuxandroidcustom viewsnoscrolltextview xmlnsandroid xmlnsiclinux androidclipchildrenfalse androidlayout widthwrap content androidlayout heightwrap content androidsinglelinetrue androidgravitycenter androidpaddingleft8dp androidpaddingright8dp androiddrawabletopdrawableicon bg stylestyleellipsizedsinglelinetextview androidtextsizedimengrid item title size comiclinuxandroidcustom viewsnoscrolltextviewmy question is i can not flip left or right when touching the textview but if removed androidgravitycenter it works unfortunately the text is not centered anywaypublic class noscrolltextview extends textview public noscrolltextviewcontext context supercontext public noscrolltextviewcontext context attributeset attrs supercontext attrs public noscrolltextviewcontext context attributeset attrs int defstyle supercontext attrs defstyle override public boolean ontoucheventmotionevent event if eventgetaction motioneventaction move return false return superontoucheventevent what happened here thanks a lot,['android'] +484490,thisplay product price in two currencies at the same time how do i modify prestashop 15 to thisplay product prices in two currencies at the same time ie base currenct and visitors currency on products listed in product categories pagesi think i should be modifying productcontrollerphp and producttpl is this correctbelow is one solution for the product page that i find on a forum but it is for prestashop 14xoverride productcontrollerphp in controllersproductcontrollerphpphpclass productcontroller extends productcontrollercore public function thisplaycontent global currency second currency usd productpricewithtax productgetpricestaticthisproductid true null 6 if product taxcalculationmethod ps tax inc productpricewithtax toolsps roundproductpricewithtax 2 productpricewithoutecotax floatproductpricewithtax thisproductecotax current currency currencyiso code default currency currencygetdefaultcurrencyiso code currency array currencygetcurrenciesobject false active 1 if current currency default currency foreach currency array as arr if stringarriso code second currency second currency price toolsps roundproductpricewithoutecotax floatarrconversion rate 2 selfsmartyassignsecond currency price second currency price second currency parentthisplaycontent modify producttplif pricethisplay 0 pricethisplay 2 span idour price thisplayconvertprice priceproductpricespantoif pricethisplay 0 pricethisplay 2 second currency price span idour price thisplayconvertprice priceproductpricespanin above example usd is the second currency second currencyusd i was wondering if it would be possible to modify this code for prestashop 15 which has changed significantly since 14x,"['javascript', 'php']" +484499,jquery ui 110 dialog and zindex option i have to make an dialog to apear when an image onclick the problem is that i have some realy big zindex there 500 for example and the ui dialog is on the back of that elements here is the page you need to log in user raducup and pass1 another problem is that when i click close ont the dialog the object desapearsthis is the function i call when a image is clickfunction openitemobiect obiect csszindex9 obiect dialog dialogclass noclose modal true draggable true overlay backgroundcolor red opacity 05 buttons text ok click function this dialog close reparazindex,"['javascript', 'jquery', 'html', 'css']" +484551,encapsulating retries into with block i am looking to encapsulate logic for database transactions into a with block wrapping the code in a transaction and handling various exceptions locking issues this is simple enough however i would like to also have the block encapsulate the retrying of the code block following certain exceptions i cannot see a way to package this up neatly into the context manageris it possible to repeat the code within a with statementi would like to use it as simply as this which is really neatdef do work this is ideal with transactionretries3 atomic db statements i am currently handling this with a decorator but i would prefer to offer the context manager or in fact both so i can choose to wrap a few lines of code in the with block instead of an inline function wrapped in a decorator which is what i do at the momentdef do work this is not ideal transactionretries3 def perform in transaction atomic db statements perform in transaction,['python'] +484563,what is the purpose of the serverphp file in laravel 4 in the app directory in laravel 4 there is a file called serverphp the contents of this file look like thisphpuri parse url serverrequest uri php url pathuri urldecodeuripaths require dir bootstrappathsphprequested pathspublicuri this file allows us to emulate apache is mod rewrite functionality from the builtin php web server this provides a convenient way to test a laravel application without having installed a real web server software hereif uri and file existsrequested return falserequire once pathspublicindexphpit seems that this file is in someway used to mimic apache is mod rewrite functionality however i cannot find anything in the laravel documentation that mentions it or it is usei currently am trying to utilize laravel on an iis server that i do not manage i do not have the ability to modify the url rewrite module options on iis i will in the future but would like to get started working with the framework now if possible this serverphp file seems like it may be a stopgap solution to do just thatcan anyone shed some light on the purpose of the serverphp file and how to useactivate it if the purpose is really to emulate apache is mod rewrite functionality,['php'] +484580,why is a bindingredirect added to the appconfig file after adding the microsoftbclasync package i was wondering why nuget added the following code to my applications appconfig file after installing the microsoftbclasyncruntime assemblybinding xmlnsurnschemasmicrosoftcomasmv1 dependentassembly assemblyidentity namesystemruntime publickeytokenb03f5f7f11d50a3a cultureneutral bindingredirect oldversion025190 newversion25190 dependentassembly dependentassembly assemblyidentity namesystemthreadingtasks publickeytokenb03f5f7f11d50a3a cultureneutral bindingredirect oldversion025190 newversion25190 dependentassembly assemblybindingruntimeif i remove this xmlelement from the config the app will not work properlyas far as i understand it we can use the bindingredirect to make the app load a newer or older version of an assembly in case the version we were using when compiling the exe is gonehowever i am using exactly the version 25190 why would i need a redirect thenwhy do i need this bindingredirect,"['c#', '.net']" +484640,is abrecordid a reliable way to identify unique contacts my app uploads contacts and in the future will need to update them is using the abrecordid a reliable way to identify people or is it possible for a new record to obtain the id of a deleted recordto optimize uploads i would like to upload only the records that have been modified or created since the last upload i am currently storing a copy of the persons contacts using core data i would like to slim down the footprint of my app and speed up the execution time of scanning through the persons address book looking for modifiednew contacts and limit the amount that needs to be uploaded after analyzing some peoples address books the number of contacts can range from 30 to around 30 dealing with 30 contacts is a nightmare,['ios'] +484662,open source java cms can anyone suggest a good open source cms for java i have not used any java cms but i have used wordpress looking around google i have short listed opencms dotcms and liferay has anyone used these which one of these would be a good cms it would be good if it has good documentations and online community it can be integrated with other java tech eg frameworks like spring framework simple to learni just do not want to spend time on one and then realise there is a better option out thereit would be good to get others view on thisthanks in advance,['java'] +484687,how do i deep copy a set of data and change fk references to point to all the copies suppose i have table a and table b table b references table a i want to deep copy a set of rows in table a and table b i want all of the new table b rows to reference the new table a rowsnote that i am not copying the rows into any other tables the rows in table a will be copied into table a and the rows in table b will be copied into table bhow can i ensure that the foreign key references get readjusted as part of the copyto clarify i am trying to find a generic way to do this the example i am giving involves two tables but in practice the dependency graph may be much more complicated even a generic way to dynamically generate sql to do the work would be fineupdatepeople are asking why this is necessary so i will give some background it may be way too much but here goesi am working with an old desktop application that is been moved to a clientserver model but the application still uses a rudimentary inhouse binary file format for storing data for its tables a data file is just a header followed by a series of rows each of which is just the binary serialized field values the order of which is determined by a schema text file the only thing good about it is that it is very fast it is terrible in every other respect i am moving the application to sql server and trying not to degrade the performance too badlythis is a kind of scheduling application the datas not critical to anybody and there is no audit tracking etc necessary it is not a supermassive amount of data and we do not necessarily need to keep very old data around if the database grows too largeone feature that they are accustomed to is the ability to duplicate entire schedules in order to create whatif scenarios that they can muck with any user can do this as many times as they want as often as they want in the old database the data files for each schedule are stored in their own data folder identified by name so copying a schedule was as simple as copying the data folder and renaming iti must be able to do effectively the same thing with sql server or the migration will not work maybe youre thinking that i can just only copy the data that actually gets changed in order to avoid redundancy but that honestly sounds too complicated to be feasibleto throw another wrench into the mix there can be a hierarchy of schedule data folders so a data folder may contain a data folder which may contain a data folder and the copying can occur at any levelin sql server i am implementing a nested set hierarchy to mimic this i have a data set table like thiscreate table dbodata set data set id uniqueidentifier primary key name nvarchar128 not null lft int not null rgt int not nullso there is a tree structure of data sets each data set represents a schedule and may contain child data sets every row in every table has a data set id fk reference indicating which data set it belongs to whenever i copy a data set i copy all the rows in the table for that data set and every other data set into the same table but referencing new data setsso heres a simple concrete examplecreate table foo foo id bigint primary key data set id bigint foreign key references data setdata set id not nullcreate table bar bar id bigint primary key data set id bigint foreign key references data setdata set id not null foo id uniqueidentifier primary keyinsert into fooselect 1 1 union allselect 2 1 union allselect 3 1 union allinsert into barselect 1 1 1select 2 1 2select 3 1 3so let us say i copy data set 1 into a new data set of id 2 after i copy the tables will look like thisfoofoo id data set id1 12 13 14 25 26 2barbar id data set id foo id1 1 12 1 23 1 34 2 45 2 56 2 6as you can see the new bar rows are referencing the new foo rows it is not the rewiring of the data set ids that i am asking about i am asking about rewiring the foreign keys in generalso that was surely too much information but there you goi am sure there are a lot of concerns about performance with the idea of bulk copying the data like this the tables are not going to be huge i am not expecting more than 10 records in any table and most of the tables will be much much smaller than that old data sets can be deleted outright with no repercussionsthankstedderz,['sql'] +484710,how fix this error kernel requirerb45in require cannot load such file i have the following structure of filesexecuterblibmy classrbin the executerb i have the code bellowusrbinrubyrequire libmy classmy object myclassnewmy objectsome methodand this is the code of my classrbclass myclass def some method puts ok endendso i tried run the executerbruby executerbbut i receive this errorhomevagrantrvmrubiesruby200p195librubysite ruby200rubygemscore extkernel requirerb45in require cannot load such file libmy class loaderror from homevagrantrvmrubiesruby200p195librubysite ruby200rubygemscore extkernel requirerb45in require from executerb3in maincan anyone help me i will appreciate any helpthanks a lot,['ruby'] +484740,php differences in calling a method from a child class through parentmethod vs thismethod say i have a parent classclass parentclass public function mymethod echo parent mymethod was called and the following child classclass childclass extends parentclass public function callthroughcolons parentmymethod public function callthrougharrow thismymethod myvar new childclassmyvarcallthroughcolonsmyvarcallthrougharrowwhat is the difference in using the two different ways to call mymethod from within an inheriting class the only difference i can think of is if childclass overrides mymethod with his own version but are there any other significant differencesi thought the double colons operator was supposed to be used to call static methods only but i do not get any warning when calling myvarcallthroughcolons even with e strict and e all on why is thatthank you,['php'] +484760,python convert to binary and keep leading zeros i am trying to convert an int to binary using the bin function in python however it always removes the leading zeros which i actually need such that the result is always 8bitexamplebin1 0b1 what i would likebin1 0b01does anybody know a way of doing this,['python'] +484791,python selenium phantomjs render to pdf is it possible to use phantomjss rendering to pdf capabilities when phantomjs is being used in combination with selenium and python ie mimic pagerenderfilepdf behaviour inside python via seleniumi realize that this uses ghostdriver and ghostdriver does not really support much in the way of printingif another alternative is possible that is not selenium i am all ears,['python'] +484817,does modifying the result of a getter affect the object itself i have a question about using getter methods in javasuppose i had this classclass test private arrayliststring array new arrayliststring public arraylist getarray return thisarray public void initarray arrayaddtest 1 arrayaddtest 2 class start public static void mainstring args initarray getarrayremove0 my question iswould the actual arraylist object be modified test 1 removed from it i think i have seen this in places but i thought that getters were simply providing a copy of that object not a reference to it if it did work that way as a reference then would this work as well would the arraylist object of the class test be altered by this as wellclass start public static void mainstring args initarray arraylist avar getarray avarremove0,['java'] +484845,foreign keys in laravel 4 migrations issue i have just created a new laravel 4 project and am finding strange things happening with the foreign key aspect of the schema builder if i use the foreign method in any of my migrations i get thrown mysql errors 150 and general error 1005 according to the documentation at laravelcomdocs the two scenarios at the bottom should work anyone know why they do notthe following does work schemacreateareas functiontable tableengine innodb tableincrementsid tableintegerregion idreferencesidonregions tablestringname 160 tabletimestamps but these two do not work schemacreateareas functiontable tableengine innodb tableincrementsid tableforeignregion idreferencesidonregions tablestringname 160 tabletimestamps schemacreateareas functiontable tableengine innodb tableincrementsid tableintegerregion id tableforeignregion idreferencesidonregions tablestringname 160 tabletimestamps,['mysql'] +484857,fastest way to get number of white pixels in a binary image using opencv what is the fastest way to get number of white pixels in a binary picture using opencv is there something faster than using two for loops and accessing the image pixel by pixel,['c#'] +484930,creating an index view for a devise user this is a new project so scraping and restarting would be easy if someone has advice in that direction essentially i created users with devise by usingrails generate devise usersbut now i want to create a route to something like a usersindex page to thisplay all the users i could not find any routes that seemed like they were applicable when i ran rake routesmy next thought was to use rails generate scaffold user to try and generate such views and controller functions this did not worki am relatively new to rails but have a pretty general grasp of it i have just started using devise so that part confuses me most i am using it for validation i have looked around for help and have studied the devise page quite a bit but to no availjust some extra info when i try the route httplocalhost30users i get uninitialized constant userscontroller but when i added a users controller it just complained about something else i have tried several other things but do not want to dilute the question by going into all of them,['ruby-on-rails'] +484934,download app from google play programatically i need to download a few apps from google play for analysis purpose but i do not want to do it manually i have to do it often and each time the apps that i want to download changeso the question is whether i can write a program to download the apps or not if it is possible howi have seen this plugin for chromebut i cannot trust the author the app requires google user and pass and device id and have decide to implement my own program,"['java', 'android']" +484938,remove last and items from list using c i am working on a dynamic listing of scores which is frequently updated ultimately this is used to produce an overall rating so older entries based on some parameters not time need to be removed to prevent heavy weighting on the overall it will be adding multiple values at once from a separate enumeration listint scorelist new listint foreachitem x in items scorelistaddxscore what i need help with ifscorelistcount itemscount 3 i need to remove the last set first in first out of values size itemscount from the list if anyone can help it would be much appreciated i had to make the code a bit generic because it is written rather cryptically did not write the methods,['c#'] +484944,makefile4 missing separator stop this is my makefilealc gcc c wall werror 02 cc llc o ll clean rm fr llwhen i try to make clean or make make i get this errormakefile4 missing separator stophow can i fix it,['c'] +484990,mysql ranking based on category and branch i am having a hard time figuring out and trying how to fix this can you help me give a logic or idea how can get the ranking of each category for each branch based on salesfor examplerank 1 for branch code id 9 is accicular since it has 30 salesrank 2 for branch code id 9 is wlo since it has only 20salessame as with other branches i only need the rank of category for each branch code idi cannot figure out how to loop this one rank will be placed in the r column as you can see in the excel output by the way heres the sql statement i used to get the result you see in the screenshotselect aid adate abranch code id sumbamount ccategory from sales add h as a inner join sales add i as b on aid bsales h id inner join control panel item create as c on bitem code id cid group by ccategory abranch code id bamount order by sumbamount descthanks guys,"['php', 'mysql']" +484992,set input height 100 of parent i have a little problem with setting input type text height to fit 100 of parents td height i even tried to iterate through every input and set it height manually with jquery but it takes quite a lot of time site i am working on has a lot of cells and still does not work on ie 7 and 8 i have to make site work under those too here is a sample it would be greatly appreciated if anybody knows any solutionhack,"['html', 'css']" +484998,what does link href do i stumbled upon the following snippet in a source code of a web sitelink href idcolourscheme relstylesheetwhat does this do,"['html', 'css']" +485038,populate list with the same value with linq i want to populate a liststring with the same string value for a specified number of timesin straight c it isliststring mylist new liststringfor int i 0 i 50 i mylistaddmystringis it possible to do this with linq,['c#'] +485075,sharepoint 2013 add javascript after whole page load thisclaimer i have no experience with sharepoint2013i have problem i must includefire some javascript functions after the whole page has been loaded i tried listening to domdocumentready and windowload events but sharepoint render the rest of page after those eventsmy question is what i should do to be able to run script after whole page with ajax is rendered also i noticed that page navigation is based on hash part obviously i must detect that moment alsoany help or even link to right page in documentation would be great,['javascript'] +485083,architecture modifying the model in different ways problem statementi have a model class that looks something like extremely simplified some members and many many methods omitted for clarityclass mymodelitempublic enum itemstate state1 state2 qstring text const itemstate state constprivate qstring text itemstate stateit is a core element of the application and is used in many different parts of the codeit is serializeddeserialized intofrom various file formatsit can be written into or read from a databaseit can be updated by an import that reads a file and applies changes to the currently loaded inmemory modelit can be updated by the user through various gui functionsthe problem is this class is has grown over the years and now has several thousands lines of code it has become a prime example of how to violate the single responsibility principleit has methods for setting the text state etc directly after deserialization and the same set of methods for setting them from within the ui which has side effects like updating the lastchangeddate and lastchangeduser etc some methods or groups of methods exist even more than twice with everyone of them doing basically the same thing but slightly differentwhen developing new parts of the application you are very likely using the wrong of the five different ways of manipulating mymodelitem which makes it extremely time consuming and frustratingrequirementsgiven this historically grown and overly complex class the goal is to separate all different concerns of it into different classes leaving only the core data members in itideally i would prefer a solution where a mymodelitem object has nothing but const members for accessing the data and modifications can only be made using special classesevery one of these special classes could then contain an actual concrete implementation of the business logic a setter of text could do something like if the text to be set begins with a certain substring and the state equals state1 set it to state2first part of the solutionfor loading and storing the whole model which consists of many mymodelitem objects and some more the visitor pattern looks like a promising solution i could implement several visitor classes for different file formats or database schemas and have a save and load method in mymodelitem which accept such a visitor object eachopen questionwhen the user enters a specific text i want to validate that input the same validation must be made if the input comes from another part of the application which means i can not move the validation into the ui in any case uionlyvalidation is often a bad idea but if the validation happens in the mymodelitem itself i have two problems againthe separation of concerns which was the goal to begin with is negated all the business logic code is still dumped into the poor modelwhen called by other parts of the application this validation has to look differently implementing different validatingsettermethods is how it is done right now which has a bad code smellit is clear now that the validation has to be moved outside both the ui and the model into some sort of controller in a mvc sense class or collection of classes these should then decoratevisitetc the actual dumb model class with its datawhich software design pattern fits best to the described case to allow for different ways of modifying the instances of my classi am asking because none of the patterns i know solves my problem entirely and i feel like i am missing something herethanks a lot for your ideas,['c++'] +485108,iframe size with css on ios there is an iframe which basically has more content than fits into the frame the sizing of the frame is based on the browser screen size and lets the overflow scroll which works perfectly on all browsers except for ios on ios safari decides to resize the frame to fit the content not what youd expectexample code on jsfiddletry it out on your ios devicesthe htmldiv classframe holder iframe classmy frame the content iframedivthe cssbody position relative background f0f0f0frame holder position absolute top 50px bottom 50px left 50px right 50px background fmy frame width 100 height 100 border 1px solid e0e0e0,"['ios', 'css']" +485128,android create custom overflow menu item i want to create a custom overflow menu item in my actionbar in addition at the setting item like described in the image belowbut if there is few space in the actionbar i do not want that the item1 and item2 go into the setting item as overflow but into my overflow itemthis is my menu xml codemenu xmlnsandroiditem androidiconandroiddrawableic menu agenda androidtitleitem1 androidshowasactionifroomwithtext item androidiconandroiddrawableic menu add androidtitleitem2 androidshowasactionifroomwithtext item androidididpick action provider androidiconandroiddrawableic menu sort by size androidshowasactionalways androidtitleoverflow menu item androidididaction sort size androidiconandroiddrawableic menu camera androidtitleitem3 item androidididaction sort alpha androidiconandroiddrawableic menu sort alphabetically androidtitleitem4 menu itemitem androidididaction settings androidorderincategory100 androidshowasactionnever androidtitlestringaction settingsmenu,['android'] +485146,in what javascript engines does functionprototypetostring not return the source code of that function edit to be explicit i am not looking for advice or opinions on the qualitative merit of the various issues implied by the functionality in question a neither am i looking for a reliable solution to a practical problem i am simply looking for technical verifiable answers to the question in the title i have appended the question with a list of nonconforming browsersusing a functions tostring method will typically render the source code for that function the problem is that this behaviour is not specified a the spec refrains from making any commitment as to what the behaviour should be when applied to functions chromes console will even tell you when you pass anything other than a function to functiontostringcall that functionprototypetostring is not genericthis blog post suggests this can be used as a method to produce a readable syntax for multiline strings by storing the string as a multiline comment in the body of a noop function the author suggests this usage in the context of writing nodejs applications with the clause that this behaviour is only reliable because nodejs runs in a controlled environment but in javascripts native web anything can come along and interpret it and we should not rely on unspecified behaviourin practice though i have set up a fiddle which renders a select box whose contents are determined by a large multiline string to test the code and every browser on my workstation chrome 27 firefox 21 opera 12 safari 5 internet explorer 8 executes as intendedwhat current javascript engines do not behave as followsgiven thatfunction uncommentfn return fntostringsplitnngslice11jointhe followinguncommentfunctionergargshould outputergarglist of nonconforming browsersfirefox 16a,['javascript'] +485147,how to use ms office with proprietary java backend document system currently i have a document system that launches documents in star office or libreoffice in an iframemoving to the future i ideally want to retain the document system i have but integrate this into sharepoint so as to enable us to open and edit documents using ms officeas there is no java api to integrate with ms office this is why i have chosen to go with sharepointi can manage to get my documents to load from a link on a sharepoint page but then comes the hard part of manipulating the save features in ms office and ensuring that my document does not get saved in sharepointhas anyone done anything similarbasically i just want to use ms office to interact with my documents without storing things in sharepoint so i need to get access to the save functions etcas far as i see apache poi is not a viable solution as it does not physically open the document and allow user to click file save my understanding is that it can manipulate documents by manipulating them in code but cannot use any of the controls in officei have read here voffice12aspxcssavelang1cslangvbcodesnippet2 that you can repurpose the commands in office and modify the ribbonthanks for any adviceit appears it is possible with wopi and office web apps basically needing to create a wopi application,['java'] +485156,xamarin studio folder structure issue in ios project i am having trouble with xamarin folders currently i am writing xamarin ios project in xcode i used directories for grouping images there could be several levels of nested folders but when i was building project for device or ios simulator these resources where simply being copied to main bundle without any folder structure i cannot reach the same behaviour in xamarin studio whenever i create folders in my project and put pictures or other resources in them this folder structure is recreated on the actual device and thus i struggle against different paths when loading images how can i make xamarin studio simply copy the files in the folders to main bundle instead of recreating folder structurethanks for help,['ios'] +485159,is it necessary to use template parameters to refer to same class inside definition is this necessary template typename t class a tpoint at somefunction instead of returning just a not at will somefunction implicitly return the a of the same type as the class being defined because outside the class you can only refer to this type as afloat or similar so i would assumed this was necessary inside the class as well i thiscovered it compiles without the so this made wonder if it is a safe habit to omit the brackets,['c++'] +485175,does not name a type error in c i do not know what to search to find an explanation for this so i am askingi have this code which reports errorstruct settings int width int height settingssettingswidth 800 settings does not name a type errorsettingsheight 600 settings does not name a type errorint main cout settingswidth settingsheight endlbut if i put the value assignment in main it worksstruct settings int width int height settingsmain settingswidth 800 no error settingsheight 600 no errorcan you explain me whyeditregarding to ralph tandetzkys answer here is my full struct code could you show me how to assign the values as you did with my snippet structstruct settings struct dimensions int width int height screen struct build menudimensions int border width build menu settings,['c++'] +485239,jquery selector performance a curious case i tested the differences between 2 id selectors the first is normal loland the second is the same but placed between multiple parenthesis loli launched a test on jsperf with firefox and chromeresults are interesting with firefox the first normal selector is 40 slower with chrome the second is 084 slowerwhy such a difference can someone explain this is jsperfcom reliable you can see the test here i will test on others browsers for funedit i am on mac os x by the way,['jquery'] +485243,how atomicity is achieved in the classes defined in javautilconcurrentatomic package i was going through the source code of javautilconcurrentatomicatomicinteger to find out how atomicity is achieved by the atomic operations provided by the class for instance atomicintegergetandincrement method source is as followspublic final int getandincrement for int current get int next current 1 if compareandsetcurrent next return current i am not able to understand the purpose of writing the sequence of operations inside a infinite for loop does it serve any special purpose in java memory model jmm please help me find a descriptive understanding thanks in advance,['java'] +485270,how to create a placeholder for div that act like textfield div do not have a placeholder attributediv ideditable contenteditabletruedivi want please your enter your name to show in div when the user backspace the whole text in the div or no text on inside how can i do it,['html'] +485275,exception on bitmapframecreate bug in wpf framework i implemented a c application that recevies frame rgb at framerate of 30fpsthe event of frame arrive is managed with this codevoid client colorframereadyobject sender colorframereadyeventargs e mycounter consolewritelinenew frame received mycounter if writer null count if count 2 0 using var frame bitmapimage2bitmapecolorframebitmapimage using var thumb resizebitmapframe 320 240 writerwritevideoframethumb else writerclose with the if condition i manage only one of two frameswhen my code call bitmapimage2bitmap i obtain this exceptionthe exception in english should bea first chance exception of type systemnotsupportedexception occurred in presentationcoredlladditional information bitmapmetadata is not available on bitmapimagethe strange thing is that my application works well because the frames are correctly inserted in the output filei have read this so the problem seems a bug in wpf framework,"['c#', '.net']" +485335,how to build eclipse jdt core from source code via git i want to build eclipse jdt core from source code via git naa vely i cloned gitgiteclipseorggitrootjdteclipsejdtcoregit and tried to run mvn validate the most basic of maven phases from the git master branch but this failed with errors belowi am a debian linux user with maven 305 and jdk 17 installedi am interested to hack on class astparser which can parse java code i realise building eclipse projects is hard but i cannot find the definitive recipe page anywhere on the net for building this projectin my eclipse juno installation updated to latest this is my jdt core jar file orgeclipsejdtcore 383v20130121145325jar i tried to build on this tag v20130121145325 but i get a similar errorlog from mvn validate on git branch masterkcacwbsavemegiteclipsejdtcore mvn validateinfo scanning for projectsinfo computing target platform for mavenproject orgeclipsejdtorgeclipsejdtannotation110snapshot homekcasavemegiteclipsejdtcoreorgeclipsejdtannotationpomxmlinfo adding repository info adding repository info adding repository info adding repository info adding repository info adding repository info adding repository info adding repository info adding repository info adding repository info adding repository info adding repository info adding repository info adding repository info resolving dependencies of mavenproject orgeclipsejdtorgeclipsejdtannotation110snapshot homekcasavemegiteclipsejdtcoreorgeclipsejdtannotationpomxmlinfo resolving class path of mavenproject orgeclipsejdtorgeclipsejdtannotation110snapshot homekcasavemegiteclipsejdtcoreorgeclipsejdtannotationpomxmlinfo computing target platform for mavenproject orgeclipsejdtorgeclipsejdtcompilertool10200snapshot homekcasavemegiteclipsejdtcoreorgeclipsejdtcompilertoolpomxmlinfo resolving dependencies of mavenproject orgeclipsejdtorgeclipsejdtcompilertool10200snapshot homekcasavemegiteclipsejdtcoreorgeclipsejdtcompilertoolpomxmlinfo cannot complete the request generating detailsinfo cannot complete the request generating detailsinfo osgiwsgtk osgioslinux osgiarchx86 orgeclipseupdateinstallfeaturestrueerror cannot resolve project dependencieserror software being installed orgeclipsejdtcompilertool 10200qualifiererror missing requirement orgeclipsejdtcore 390qualifier requires bundle orgeclipsetext 310400 but it could not be founderror cannot satisfy dependency orgeclipsejdtcompilertool 10200qualifier depends on bundle orgeclipsejdtcore 330400error error internal error javalangruntimeexception no solution found because the problem is unsatisfiable unable to satisfy dependency from orgapacheant 182v201303080311 to bundle orgeclipseosgi 0 unable to satisfy dependency from orgapacheant 183v201303080312 to bundle orgeclipseosgi 0 unable to satisfy dependency from orgapacheant 184v201303080030 to bundle orgeclipseosgi 0 unable to satisfy dependency from orgeclipsejdtcore 390qualifier to bundle orgeclipsetext 310400 unable to satisfy dependency from orgeclipsejdtcore 390qualifier to bundle orgeclipsecoreruntime 330400 unable to satisfy dependency from orgeclipsejdtcore 390qualifier to bundle orgeclipsecorefilesystem 100200 unable to satisfy dependency from orgeclipsejdtcore 390qualifier to bundle orgeclipsecoreresources 330400 no solution found because the problem is unsatisfiable help 1orgapachemaveninternalerrorexception internal error javalangruntimeexception no solution found because the problem is unsatisfiable unable to satisfy dependency from orgapacheant 182v201303080311 to bundle orgeclipseosgi 0 unable to satisfy dependency from orgapacheant 183v201303080312 to bundle orgeclipseosgi 0 unable to satisfy dependency from orgapacheant 184v201303080030 to bundle orgeclipseosgi 0 unable to satisfy dependency from orgeclipsejdtcore 390qualifier to bundle orgeclipsetext 310400 unable to satisfy dependency from orgeclipsejdtcore 390qualifier to bundle orgeclipsecoreruntime 330400 unable to satisfy dependency from orgeclipsejdtcore 390qualifier to bundle orgeclipsecorefilesystem 100200 unable to satisfy dependency from orgeclipsejdtcore 390qualifier to bundle orgeclipsecoreresources 330400 no solution found because the problem is unsatisfiable at orgapachemavendefaultmavenexecutedefaultmavenjava168 at orgapachemavenclimavencliexecutemavenclijava537 at orgapachemavenclimavenclidomainmavenclijava196 at orgapachemavenclimavenclimainmavenclijava141 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava57 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43 at javalangreflectmethodinvokemethodjava601 at orgcodehausplexusclassworldslauncherlauncherlaunchenhancedlauncherjava290 at orgcodehausplexusclassworldslauncherlauncherlaunchlauncherjava230 at orgcodehausplexusclassworldslauncherlaunchermainwithexitcodelauncherjava409 at orgcodehausplexusclassworldslauncherlaunchermainlauncherjava352caused by javalangruntimeexception no solution found because the problem is unsatisfiable unable to satisfy dependency from orgapacheant 182v201303080311 to bundle orgeclipseosgi 0 unable to satisfy dependency from orgapacheant 183v201303080312 to bundle orgeclipseosgi 0 unable to satisfy dependency from orgapacheant 184v201303080030 to bundle orgeclipseosgi 0 unable to satisfy dependency from orgeclipsejdtcore 390qualifier to bundle orgeclipsetext 310400 unable to satisfy dependency from orgeclipsejdtcore 390qualifier to bundle orgeclipsecoreruntime 330400 unable to satisfy dependency from orgeclipsejdtcore 390qualifier to bundle orgeclipsecorefilesystem 100200 unable to satisfy dependency from orgeclipsejdtcore 390qualifier to bundle orgeclipsecoreresources 330400 no solution found because the problem is unsatisfiable at orgeclipsetychop2resolverabstractresolutionstrategynewresolutionexceptionabstractresolutionstrategyjava98 at orgeclipsetychop2resolverprojectorresolutionstrategyresolveprojectorresolutionstrategyjava88 at orgeclipsetychop2resolverabstractresolutionstrategyresolveabstractresolutionstrategyjava63 at orgeclipsetychop2implresolverp2resolverimplresolvedependenciesp2resolverimpljava126 at orgeclipsetychop2implresolverp2resolverimplresolvedependenciesp2resolverimpljava81 at orgeclipsetychop2resolverp2targetplatformresolverdoresolveplatformp2targetplatformresolverjava374 at orgeclipsetychop2resolverp2targetplatformresolverresolvedependenciesp2targetplatformresolverjava350 at orgeclipsetychocoreresolverdefaulttychodependencyresolverresolveprojectdefaulttychodependencyresolverjava109 at orgeclipsetychocoremaventychomavenlifecycleparticipantafterprojectsreadtychomavenlifecycleparticipantjava82 at orgapachemavendefaultmavendoexecutedefaultmavenjava274 at orgapachemavendefaultmavenexecutedefaultmavenjava156 11 moreerror error to see the full stack trace of the errors rerun maven with the e switcherror rerun maven using the x switch to enable full debug loggingerror error for more information about the errors and possible solutions please read the following articleserror help 1,['java'] +485363,c unicode characters printing i need to print some unicode characters on the linux terminal using iostream strange things happen though when i writecout u2780i get a which is almost exactly what i want however if i writecout u2780i get 14851712the problem is i do not know the exact character to be printed at compiletime therefore i would like to do something likeint x some calculationscout charu2780 xwhich prints i12 using wcout or wchar t instead do not work either how do i get correct printingfrom what i found around on the internet it seems important that i use g 472 compiler straight from debian wheezy repository,['c++'] +485400,how to use opengl in javafx i want to write a very simple java 3d editorfor experiment i know the basic javafx usage and i know enough opengl knowledge but all my opengl experience is from working with cc could i make a canvas in javafx application and map opengl viewport on it,['java'] +485500,qunit error assertion outside test context i have searched all over and it appears this error is due to not using asynctest properly however per the documentation it appears that i am doing it correctly i am guessing i am missing a small detail somewhere and need an extra pair of eyes i am trying to test some code that makes an ajax request to get a page and then loads it in a lightbox lightboxcontent does not show up in the dom until after the ajax call has completed and can be thisplayed so i can only check for it in my oncomplete call back which is where i have my test to see if it loaded it correctlyhere is my codeasynctestmytest 1 function utilslightboxshowlogin oncomplete function oklighboxcontentisvisible lightbox loaded the login page start i get the erroruncaught error assertion outside test context was at htmldivelementwindowutilscan anyone see where i am going wrong,['javascript'] +485513,circular reference detected exception while serializing object to json just as mentioned in this post i am getting a json serialization error while serializing an entity framework proxya circular reference was detected while serializing an object of type systemdataentitydynamicproxiespurchaseorder 446b939192f161cdbc740067f174f7a6059b0f9c0e68cd3ebbd63cf9af5bd0but the difference is i do not have a circular reference in my entities and it only occurs in our production environment locally everything works finemy entitiespublic interface ientity guid uniqueid get int id get public class entity ientity public int id get set public guid uniqueid get set public class purchaseorder entity public string username get set public string company get set public string supplierid get set public string suppliername get set public virtual icollectionpurchaseorderline lines get set public class purchaseorderline entity public string code get set public string name get set public decimal quantity get set the getcurrent action on my purchaseordercontroller throwing the exceptionpublic class purchaseordercontroller controller private readonly iunitofwork unitofwork public purchaseordercontrolleriunitofwork unitofwork unitofwork unitofwork public jsonresult getcurrent return jsonensurepurchaseorder jsonrequestbehaviorallowget private purchaseorder ensurepurchaseorder var company routedatagetrequiredstringcompany var repository unitofworkgetrepositorypurchaseorder var purchaseorder repository includep plines firstordefault p pcompany company pusername useridentityname if purchaseorder null purchaseorder repositorycreate purchaseorderuniqueid guidnewguid purchaseordercompany company purchaseorderusername useridentityname unitofworksavechanges return purchaseorder,['c#'] +485537,osx bundler install command not found i am getting this errorcould not find i18n061 in any of the sourcesrun bundle install to install missing gemswhen i try to run bundle install i get thisbash bundle command not foundi have googled and tried to solve this for a while now with no hope please help,"['ruby-on-rails', 'ruby']" +485538,best way to send http get requests ansynchronously in android in an android app i have to make multiple get requests to a url in order to transmit data to an external server that is how the third party api worksdata comes in sporadically i store this data in a queue and want to send it to the server in a background asynchronously without slowing down the main ui thread each unit of data in the queue requires a get request the queue has to be emptied even if the app closeswhats the best practice to do this please postdirect me to codetutorials,['android'] +485549,combine questionnaire with user entity in form symfony2 i need to add questionnaire of multiple choice questions to my registration form the questions and options are in two entitiesphpnamespace meuserbundleentityuse doctrineormmapping as ormuse doctrinecommoncollectionsarraycollection question ormtablenamequestion ormentityrepositoryclassmeuserbundleentityquestionrepository class question var integer ormcolumnnameid typeinteger ormid ormgeneratedvaluestrategyauto private id var string ormcolumnnamequestiontext typetext private questiontext var boolean expanded ormcolumnnameexpanded typeboolean private expanded var boolean multiple ormcolumnnamemultiple typeboolean private multiple var questionnaire questionnaire ormmanytoonetargetentityquestionnaire inversedbyquestions ormjoincolumnnamequestionnaire referencedcolumnnameid ondeletecascade private questionnaire var doctrinecommoncollectionsarraycollection options ormonetomanytargetentityoption mappedbyquestion cascadeall private optionspublic function construct thisexpanded false thismultiple false thisoptions new arraycollection get id return integer public function getid return thisid set questiontext param string questiontext return question public function setquestiontextquestiontext thisquestiontext questiontext return this get questiontext return string public function getquestiontext return thisquestiontext param mixed options public function setoptionsoptions thisoptions options return this return mixed public function getoptions return thisoptionsfunction tostring return thisgetquestiontext param boolean expanded public function setexpandedexpanded thisexpanded expanded return boolean public function getexpanded return thisexpanded param boolean multiple public function setmultiplemultiple thismultiple multiple return boolean public function getmultiple return thismultiple param meuserbundleentityquestionnaire questionnaire public function setquestionnairequestionnaire thisquestionnaire questionnaire return meuserbundleentityquestionnaire public function getquestionnaire return thisquestionnaireand phpnamespace meuserbundleentityuse doctrineormmapping as orm questionoption ormtablenameoption ormentityrepositoryclassmeuserbundleentityoptionrepository class option var integer ormcolumnnameid typeinteger ormid ormgeneratedvaluestrategyauto private id var integer ormcolumnnamequestionid typeinteger private questionid var string ormcolumnnameoptiontext typestring length255 private optiontext ormmanytoonetargetentityquestion inversedbyoptions ormjoincolumnnamequestionid referencedcolumnnameid ondeletecascade private question get id return integer public function getid return thisid set optiontext param string optiontext return option public function setoptiontextoptiontext thisoptiontext optiontext return this get optiontext return string public function getoptiontext return thisoptiontext return mixed public function getquestion return thisquestion param mixed question public function setquestionquestion thisquestion question param int id public function setidid thisid idfunction tostring return thisgetoptiontexti also have a questionnaire entity though i do not think i really need it because users would not be creating questionnaires only filling the single questionnaire during registrationmy user entityphpnamespace meuserbundleentityuse doctrineormmapping as ormuse doctrinecommoncollectionsarraycollection user ormtablenameuser ormentityrepositoryclassmeuserbundleentityuserrepository class user var integer ormcolumnnameid typeinteger ormid ormgeneratedvaluestrategyauto private id var string ormcolumnnamefirstname typestring length50 private firstname var string ormcolumnnamemiddleinitial typestring length50 private middleinitial var string ormcolumnnamelastname typestring length50 private lastname var string ormcolumnnamehomephonearea typestring length3 private homephonearea var string ormcolumnnamehomephonenumber typestring length7 private homephonenumber var string ormcolumnnameemail typestring length50 private email var doctrinecommoncollectionsarraycollection public questionspublic function construct thisquestions new arraycollection get id return integer public function getid return thisid set firstname param string firstname return user public function setfirstnamefirstname thisfirstname firstname return this get firstname return string public function getfirstname return thisfirstname set middleinitial param string middleinitial return user public function setmiddleinitialmiddleinitial thismiddleinitial middleinitial return this get middleinitial return string public function getmiddleinitial return thismiddleinitial set lastname param string lastname return user public function setlastnamelastname thislastname lastname return this get lastname return string public function getlastname return thislastname set homephonearea param string homephonearea return user public function sethomephoneareahomephonearea thishomephonearea homephonearea return this get homephonearea return string public function gethomephonearea return thishomephonearea set homephonenumber param string homephonenumber return user public function sethomephonenumberhomephonenumber thishomephonenumber homephonenumber return this get homephonenumber return string public function gethomephonenumber return thishomephonenumber set email param string email return user public function setemailemail thisemail email return this get email return string public function getemail return thisemail return doctrinecommoncollectionsarraycollection public function getquestions return thisquestionsmy user controllerpublic function newaction user new user em thisgetdoctrinegetmanager questions emgetrepositorymeuserbundlequestionfindall if questions throw thiscreatenotfoundexceptionunable to find questions builder thiscreateformbuilder optionentities array foreach questions as question options array foreach questiongetoptions as option optionsoptiongetid optiongetoptiontext optionentitiesoptiongetid option builderaddquestion questiongetid choice array label questiongetquestiontext expanded questiongetexpanded multiple questiongetmultiple choices options usergetquestionsaddquestions form thiscreateformnew myformtype arrayuser user return thisrendermeuserbundleusernewhtmltwig array entity user form formcreateview the form type as it stands todayphpnamespace meuserbundleformuse symfonycomponentformabstracttypeuse symfonycomponentformformbuilderinterfaceuse symfonycomponentoptionsresolveroptionsresolverinterfaceclass myformtype extends abstracttypeprotected questionspublic function construct questions thisquestions questionspublic function buildformformbuilderinterface builder array options builder addquestions collection array type new questiontype addfirstname addmiddleinitial addlastname addhomephonearea addhomephonenumber addemail public function setdefaultoptionsoptionsresolverinterface resolver resolversetdefaultsarray public function getname return myform typethis setup does not work to get the questions and their associated options and thisplay them in the same user creation form i have seen instructions and docs for combining forms but not creating forms with this kind of configuration any guidance would be appreciated,['php'] +485550,what is define function in javascript i see this being used all the time in javascript defineparam1 param2 function what is the define function,['javascript'] +485592,difference between rescolor and resvaluescolorsxml in android resources folder is there any reason why in the resources folder we have two folders in which we can define colors according to android developer page this is the quote from android developer pagevalues xml files that contain simple values such as strings integers and colorscolor xml files that define a state list of colors see color state list resourceis there any difference between colors stored in rescolors and resvalues which one is more preferable,"['java', 'android']" +485610,why copy constructor is not invoked sorry for the overly ambiguous titledue to the lack of my english skill please suggest a better titleplease consider the following code struct a typedef stdvectordouble state template class args aargs args aargs template class args aargs args astdforwardargsargs aconst a default aa default state aint main a a32 a b a this line triggers an errorgcc 480 failed to compile it with the error message error no matching function for call to stdvectordoublevectora astdforwardargsargsi cannot understand why this code is wrong in my opinion the compiler should invoke copy constructor in the line a b a however if i replace the constructor by the commented onewhich simply takes values it does compile furthermore now the lines for default copyand move constructors are not needed what happens here,['c++'] +485621,toolsjar is not in android studio classpath i tried installing android studio on a samsung chromebook series 3 with an arm processor but i am stuck with the java any help would be appreciateddownloaded and extracted android studiodownloaded and extracted java 170 21 jdk armcompleted the below commands except the javaws commands as they errored out does not existtar xzvf downloadsjdk7u21linuxarmtargz sudo mv jdk170 21 usrlibjvm sudo updatealternatives install usrbinjava java usrlibjvmjdk170 21binjava 1 sudo updatealternatives install usrbinjavac javac usrlibjvmjdk170 21binjavac 1 sudo updatealternatives install usrbinjavaws javaws usrlibjvmjdk170 21binjavaws 1 sudo updatealternatives config java sudo updatealternatives config javawsi tried the java homeusrlibjvmjdk170 21 command and it would still give me the error,['android'] +485645,how to reset my uiscrollviews position after returning from a modal transition i have a simple view containing a long view with many buttons with the whole thing being in a uiscrollview the scroller works well and i can scroll to the bottom and click a button every button triggers a modal seque to another view that new view is then thismissed by user interaction causing the original uiscrollviews view to load againheres the problem if i click on a button toward the top of the uiscrollview i enter the modal segue thismiss the new view and return to the uiscrollviews view without a problem but if i click on one of the buttons toward the bottom of the uiscrollview when i return seque out and then transition back my scrolling is all messed up i can only see the area beneath my scroller and cannot scroll back up to the top anymorei am pretty sure there must be some way to reset the uiscrollviews starting and ending points upon viewwillappear but i cannot figure it out any help is appreciatedalso fyi i simply added the uiscrollview through interface builder and have not implemented or synthesized it anywhere yet,"['ios', 'objective-c']" +485710,remove chrome extension via code i have created a chrome application when the user adds it to the chrome browser a form is opened as a part of the installation i want to delete the added extension when the installation is not done correctlyhow do i trigger deletion of a chrome extension,['javascript'] +485716,c global and static variable storing in memory from what i have learned about global and static variablesif a c variable is declared outside all functions in a source file as int a this variable can be accessed by other files once it has an extern declaration for it in that filebut if the same variable is declared as static int athen this variable can be used only by the current file any other file wont be able to see this variablewhen the program is loaded into the memory at run time both global and static variable are present in the data section of this programi want to understand that as both are stored in the same memory segment how is the static variable protected from not getting used in any instruction out of its scopewhat i think is that the scope of the variable and its access will be taken care of by the compiler please comment if i am wrong and add if i am missing any detailregarding extern variableifint a is defined in file file1c and is declared in file file2c as extern int a both files belongs to different processes let it be process1 and process2 respectivelyso when process1 is running and its address space is loaded in the memory its data section variable a will be availablei have a doubt here that is when process2 is running will this variable also be loaded in process2s data section or how it is managedplease help me clear my above mentioned doubts i have searched on the web and read a few articles and need to confirm if i have understood is correctlyaso please do suggest me a good article or book which will help me understand the above concepts clearly,['c'] +485746,what does processthispose actually do in c class process inherits from class component that implements ithisposable and so i can call thispose on any process object do i really have to how do i know if i really have tosuppose i have the following code var allprocesses systemdiagnosticsprocessgetprocesses var processesnames processesselect p pprocessname output process names herenow it looks like i have an array of process objects and i have craft a tryfinally to traverse the array and thispose each object that is definitely lots of extra codewhat does that thispose do for process objects do i really need to thispose every process object and how do i decide if i need to do so,"['c#', '.net']" +485760,how do i create a facade class with laravel i am having a little problem with creating a facade model class with laravel i have followed but i guess i am missing somethingi have created a folder in appmodels called foo in that folder i have two files first file foophpphpnamespace mynamespaceclass foo public function method second file foofacadephpphpuse illuminatesupportfacadesfacadeclass foo extends facade protected static function getfacadeaccessor return foo then i added foo mynamespacefoo to the aliases array in appconfigaphp and ran composer update and composer dumpautoloadnow when i try to run foomethod i get nonstatic method mynamespacefoomethod should not be called statically what am i doing wrong,['php'] +485772,how to sign dynamic jnlp files for osx and gatekeeper my company produces java applications for servers and delivers jnlp files to start local applications since osx 1084 it is required to sign jnlp files with a developer id to keep gatekeeper happy it is actually in the release notes at the very bottomthe question is how to accomplish this afaik you can sign apps we have some java apps signed with developer ids but jnlp files are just that filesnext how to do this with generated jnlp files we have to modify them as they come from a server eg properties base url and so forthafaik java has a certain mechanism to say jnlp files are signed via their respective jar file the one that holds the main class but jar files are signed with a different certificate they will not satisfy gatekeeper as welli did find one reference on how to sign tools and stuff but it does not apply the scenario of dynamic fileswhat i do not want as answers rightclick and open to override the gatekeeper or change the system or java settings this is not an option updatesince osx 1095 you also have to sign using osx 109 and have valid version 2 signatures how will this be done,['java'] +485835,whats the difference between requireconfig and requirejsconfig i am trying to set up requirejs and then optimise it using rjs but then i am confuse with these method i have used requireconfig before but then i saw they also have requirejsconfig and i do not know whats the difference sample coderequireconfig baseurl jslib paths app app requirejsconfig baseurl jslib paths app app they both do the same thing and when i optimise it the result is exactly the same i want to know whats the difference when should i use on or the other,['javascript'] +485841,chosen harvesthq resize width dynamically how can you have a harvesthq chosen dropdown with a dynamic width styleby default it has a fixed width and if you try to modify it with css you will have several problems to reach a good result,['jquery'] +485855,mvvmcross gesturerecognized binding to viewmodel action there is such ability to bind buttons actions directly like thisvar set thiscreatebindingsetsetbindbuttontox xgobut whats about uitapgesturerecognizer for instance how should i bind it it is tap action in such elegant waythank you,"['iphone', 'ios']" +485871,debug javascript in visual studio 2012 when using chrome or firefox is it possible to debug javascript code in visual studio when using chrome or firefox with ie it works but also when i enabled source maps in chrome it does not workin webstorm it works by the way so it is technically possible in general,['javascript'] +485875,cropping the borders of image based on color in windows phone above is the image i am using what i am trying to achieve is removing the red portion of the border from the image how can i achieve this programmatically in windows phone i found writeablebitmapextensionscrop method but i am confused with the arguments how i can find the xy position of the image as well as the size and the widthalso another issue i am facing is i will get the images with differently sized borders so i cannot hardcode the x or y valuescan anyone suggest a solution or guide me to solve the issue,['c#'] +485889,t4 template adding assembly of existing project in solution hi i need to add the assembly of an an existing project in my solution in my t4 template filethe problem is that my t4 template is in a project called projectwebapi and the class that i need in my t4 template is inside a project called projectcommonwebapii have tryed importing the namespace like this import namespaceprojectcommonwebapit4templateattribute but i get this errorthe type or namespace name project could not be found are you missing a using directive or an assembly reference i have tryed adding the assembly like this assembly nameprojectcommonwebapi and i got this errorcompiling transformation metadata file projectcommonwebapi could not be foundmy project that contains the t4template projectwebapi has a reference to the projectcommonwebapi but from what i read t4template does not use the references in the projectshow can i solve this issues,['c#'] +485897,how to add a custom adapter to an autocompletetextview is there any simple way to set a 2 textview dropdown to an autocompletetextviewthere is androidrlayouttwo line list item which i could not find any examples how to useso i tried thispublic class twolinedropdownadapter extends baseadapter private layoutinflater minflater null private activity activity public arraylisttwolinedropdown values new arraylisttwolinedropdown public twolinedropdownadapteractivity a arraylisttwolinedropdown items values items activity a minflater layoutinflater activity getsystemservicecontextlayout inflater service public int getcount return valuessize public twolinedropdown getitemint position return valuesgetposition public long getitemidint position return position public static class viewholder public textview title public textview description public view getviewfinal int position view convertview viewgroup parent viewholder holder if convertview null holder new viewholder convertview minflaterinflaterlayoutdropdown text twoline parent false holdertitle textview convertview findviewbyidridtext1 holderdescription textview convertview findviewbyidridtext2 convertviewsettagholder else holder viewholder convertviewgettag return convertview public void addtwolinedropdown ei valuesaddei but i face a problem heretwolinedropdownadapter autocompleteadapter new twolinedropdownadapterthis itemsmyautocompletesetadapterautocompleteadapterwhile setting the adapter it saysbound mismatch the generic method setadaptert of type autocompletetextview is not applicable for the arguments twolinedropdownadapter the inferred type twolinedropdownadapter is not a valid substitute for the bounded parameter how to solve thisthank you,['android'] +485900,calling python script from c and using its output i want to call a python script from c and wish to use the output csv file generated by this script back into c i tried this in mainstdstring filename homeabcxyzscriptpystdstring command python command filenamesystemcommandc strthis does call and execute the python script edit 2 the print commands in the python are being executedthings are being printed on the screen when the script is called so far so good but it is not creating the csv file part of the same script like i had a trainingcsv file with 100 entries i called the python script with little changes to the script so that the trainigcsv file now should contain only 50 entries instead of 100 its overwritten but no such thing happening rest of the commands in script print etc are working perfectlythe trainingcsv file is to be read with c normally using fstream and getlineany idea how to do it edit using linuxthanks,"['c++', 'python', 'c']" +485961,phonegap readasdataurl i am writing my first android app using phonegap but i am a little confused by the documentation for the filereader i need to take an image file and convert it to a base64 string using the readasdataurl method from their documentationfunction winfile var reader new filereaderreaderonloadend functionevt consolelogread success consolelogevttargetresultreaderreadasdataurlfilevar fail functionevt consolelogerrorcodeentryfilewin faili understand pretty much all of that except for the last line entryfilewin fail nowhere is entry defined but i assume it is a fileentry object the problem is that i have not had much luck finding documentation on how to generate the fileentry object and at what point i pass in a file path,"['javascript', 'android']" +485976,function with sql query has no destination for result data i am trying to create a function that returns a selected resultset when i call my postgres function like this select from tst dates func i get an error as shown belowerror query has no destination for result datahint if you want to thiscard the results of a select use perform insteadcontext plpgsql function tst dates func line 3 at sql statement error error query has no destination for result datasql state 42601hint if you want to thiscard the results of a select use perform insteadcontext plpgsql function tst dates func line 3 at sql statementhere is the function i createdcreate or replace function tst dates func returns table date value date date id int date desc varchar asbody begin select adate value adate id adate desc from dates tbl aendbody language plpgsqli am not sure why i am getting the above error i would like to run select from tst dates func and get data back or further join the result set if needed what is the problem here,['sql'] +485996,what to do with extra http header from proxy our environment requires the use of an outbound proxy for offsite services normally this is not a problem in this case with twilio the extra header returned breaks the clientoutgoing headerspost 20100401accountsfoosmsmessagesjson http11authorization basic foouseragent twiliophp3100host apitwiliocomaccept acceptcharset utf8contenttype applicationxwformurlencodedcontentlength 108response headershttp10 200 connection establishedhttp11 201 createdserver nginxdate thu 06 jun 2013 143924 gmtcontenttype applicationjson charsetutf8contentlength 551connection closexpoweredby php5311i can only assume the proxy is adding the extra http header the twilio client does check forlisthead body parts0 http11 100 continue as i understand it there are times or versions of curl that will automatically add an expect header in the request and the http 100 would be returned in the response but in this case it is not and the response is 200 connection established for what it is worth adding an empty expect or an expectbacon did not change the resultsi would really prefer not to hack on the twilio client too much here and i especially would like to avoid just adding a parts0 http10 200 connection established as it seems like that is messyis it possible to send a request header in the that will suppresshide the extra header or a curl option i am not seeing to ignore it the outbound proxy is linuxsquid,['php'] +486017,reusing code from different ipython notebooks i am using ipython and want to run functions from one notebook from another without cutting and pasting them between different notebooks is this possible and reasonably easy to do,['python'] +486022,what should i do when i am forced to write unreachable code i have this simple piece of codepublic static int getintint number int ints new int 3 7 9 intmaxvalue foreach int i in ints if number i return i return intmaxvalue this should be unreachable code since the last int is intmaxvalue and number intmaxvalue is allways true so the above code will allways returnthe problem is that the compiler says that not every execution path returns a value so i have to write code that will be never reached my question is what should i do in a situation like this should i return some default value or should i throw an exception also if i want to throw an exception what exception is suitable for throwing i did not find anything like unreachablecodeexception,['c#'] +486087,mysql error 1215 cannot add foreign key constraint i am trying to forward engineer my new schema onto my db server but i cannot figure out why i am getting this error i have tried to search for the answer here but everything i have found has said to either set the db engine to innodb or to make sure the keys i am trying to use as a foreign key are primary keys in their own tables i have done both of these things if i am not mistaken any other help you guys could offerexecuting sql script in servererror error 1215 cannot add foreign key constraint table alternative pathwaysclients has staff create table if not exists alternative pathwaysclients has staff clients case number int not null staff emp id int not null primary key clients case number staff emp id index fk clients has staff staff1 idx staff emp id asc index fk clients has staff clients idx clients case number asc constraint fk clients has staff clients foreign key clients case number references alternative pathwaysclients case number on delete no action on update no action constraint fk clients has staff staff1 foreign key staff emp id references alternative pathwaysstaff emp id on delete no action on update no actionengine innodbsql script execution finished statements 7 succeeded 1 failedhere is the sql for the parent tablescreate table if not exists alternative pathwaysclients case number int not null first name char10 null middle name char10 null last name char10 null address char50 null phone number int10 null primary key case number engine innodbcreate table if not exists alternative pathwaysstaff emp id int not null first name char10 null middle name char10 null last name char10 null primary key emp id engine innodb,['mysql'] +486094,what is the most efficent way to detect even numbers in java what would be the most efficient manner to determine that a number is even using java and why would it be using modulo or subtraction or some other manner that i have not actually thought of one imagines i could determine this doing a simple test class and i can but that really wouldnt explain why would iti am not doing some crazypants performance tuning for some lofty goal of processing that many items faster but i was curious if one method should be preferred over the other as common practice in the same way we wouldnt use in place of why use when we can use,['java'] +486102,how do i notify windows task scheduler when my application fails i have a wpf application scheduled in task scheduleri want to notify the task scheduler when the application failsin task scheduler window in section task status at the column run result i always get success even when the app throws an internal exceptioni used applicationcurrentshutdown1 on an attempt to notify a fail to task scheduler but with i was not successfulhow can this be done,['c#'] +486202,link in alert boxes javascript i have a simple question i have the following codealertare you sure you want to add n redirurl the variable redirurl is an actual working url i would like it to be clickablethank you in advance,"['javascript', 'jquery']" +486215,xamarin ios simulator running old code when i debug my xamarinios project from visual studio it builds installs on the simulator and launches the app without issue but on launching i am seeing a bunch of debug tracing from a method that does not even exist in my c code anymore i can also set breakpoints on the class from which i removed the method at the same line numbers where this method used to be and i will see the removed method in the call stack when the debugger stopsi have closed and reopened visual studio reset the connection to the mac build server cleaned and rebuilt my solution and manually deleted the solution output on the mac i have closed and reopened the simulator and tried reset content and settings which does clear out the app but the situation still persists even after all that is there something else can i try on the mac to make sure that all cached copies of old code have been deleted,['ios'] +486232,if is obsolete what is preferred the html code a namesome bookmarktexta is very useful for creating links to specific sections of a page eg pagehtmlsome bookmark however the w3c spec now marks the name attribute of the a tag as obsoleteif this is the case then what is preferred is there a new bookmark tag or similar,['html'] +486268,set multiple variables to the same value in javascript i have initialized several variables in the global scope in a javascript filevar moveup movedown moveleft moverightvar mousedown touchdowni need to set all of these variables to false this is the code i currently havemoveup falsemovedown falsemoveleft falsemoveright falsemousedown falsetouchdown falseis there any way that i can set all of these variables to the same value in one line of code or is the code i currently have the best way to do this,['javascript'] +486301,benefits and drawbacks of method chaining and a possibility to replace all void return parameters by the object itself i am mostly interested in java but i think it is a general question recently i have been working with arquillian framework shrinkwrap that uses a lot of method chaining other example of method chaining are methods in stringbuilder stringbuffer there are obvious benefits of using this approach reduced verbosity is one of them now i was wondering why are not all methods which have void return parameter implemented as chainable there must be some obvious and objective drawback in chaining because if all methods are chainable i can still choose not to use it i am not asking to change the existing code in java which might break something somewhere but explanation why was not it used would be nice as well i am more asking from a future framework written in java design perspective i have found a similar question but the original asker is actually wondering why it is considered a good practice method chaining why is it a good practice or notwhile there are some answers available i am still not sure what are all the benefits and drawbacks of chaining and whether it would be considered useful to have all void methods chainable,['java'] +486311,custom uibarbuttonitem i am trying to create a custom uibarbuttonitem that uses just a png with transparency so that i only have an icon as button when i try to set the button image set the background as white and set the style to plain i still get an inner shadow and black border around itwhat givesi have tried the below code and it still puts the black border around ituiimage background uiimage imagenamedthismiss normalpnguiimage backgroundselected uiimage imagenamedthismiss selectedpngselfclosebutton uibutton buttonwithtypeuibuttontypecustomselfclosebutton addtargetself actionselectorclosebuttonpressed forcontroleventsuicontroleventtouchupinside adding actionselfclosebutton setbackgroundimagebackground forstateuicontrolstatenormalselfclosebutton setbackgroundimagebackgroundselected forstateuicontrolstateselectedselfclosebuttonframe cgrectmake0 0backgroundsizewidth backgroundsizeheightselfclosebuttonitem uibarbuttonitem alloc initwithcustomviewselfclosebuttonselfnavigationitemleftbarbuttonitem selfclosebuttonitemwhat i noticed is if i do a modal segue the button with the code above still has a black border around it but if i do a push segue it does not wtf,"['ios', 'objective-c']" +486319,how do i restrict a template class to certain builtin types this issue has been thiscussed a few times but all the solutions i have found either did not work or were based on boosts static assert my problem is simple i have a class and i only want to allow real types double and float i want a compiletime error if i try to instantiate the class with a type other than float or double i am using visual c 11 here is what i have triedtemplate typename realtypeclass a warning c4346 static assertstdis samerealtype doublevalue stdis samerealtype floatvaluetemplate typename realtypeclass a error c2062 type unknown unexpected static assertdecltyperealtype double decltyperealtype floatany ideas thanks in advance,['c++'] +486336,how to convert milliseconds to date in sqlite i store date from calendargettimeinmilliseconds in sqlite dbi need to mark first rows by every month in select statement so i need convert time in milliseconds into any date format using sqlite function only how can i avoid this,['android'] +486367,add google maps api v2 in a fragment i am trying to show the map from the google maps api v2 in fragment i tried with the supportmapfragment but i cannot get the expected outputalso i am a beginner on this platform what i really want is just a way to put a map from the google maps api v2 for android in a fragment please share your ideas and referencesthanks in advance,['android'] +486409,android google maps thisable dragging in mapfragment can i thisable drag functionality when the user tries to drag the map with his fingers without thisturbing the zoom in and zoom out any one please suggest an idea of doing this thanks for your precious help,['android'] +486448,regex with latin characters i have this regexif cadenamatchesazaz return trueit is accepting from a to z as lowercase and uppercase also accepting spacesbut this is working just for english for instance in catalan weve the a character also weve characters with a or a etcdid some google and i could not find any way to do thisi found out that i can filter for utf8 but this would accept characters that are not really a letterhow can i implement this,['java'] +486468,why no front method on stdmap and other associative containers from the stl the stl reference seems to make a conceptual difference between sequence containers array vector deque forward list list on one handassociative containers set multiset map multimap unordered set unordered multiset unordered map unordered multimap on the other handalso it seems like we have all containers implementing a begin method returning an iterator pointing to the first element in the containeronly the sequence containers having a front method returning a reference to the first element in the containermy understanding is that the front method could easily be defined in terms of the begin method by just dereferencing its return valuethus my question is why is not the front method defined for all objects defining the begin method which should be every container reallyi guess that from a semantic point of view it does not make as much sense to get the first element from a map as it does for the first element from a vector but i was wondering if there was a more valid explanation,['c++'] +486497,pandas combine timegrouper with another groupby argument i have the following dataframedf pddataframebranch a a a a a bsplitbuyer carl mark carl joe joe carlsplitquantity 135893date dtdatetime2013130dtdatetime2013135dtdatetime2013101200dtdatetime2013102100dtdatetime2013122120 dtdatetime2013122140from pandastseriesresample import timegrouperhow can i group this data by the branch and on a 20 day period using timegrouperall my previous attempts failed because i could not combine timegrouper with another argument in the groupby functioni would deeply appreciate your helpthank youandy,['python'] +486550,why eclipse does not see implemented interfaces i have imported jfreechartfse from here and i have imported this to eclipse as maven projectafter that i have many problems for example in class chartpanel in orgjfreechart paskage eclipse does not see implements section and noticeoverride public void actionperformedactionevent event as a problem the same situation is in many other casescan you tell what is wrong with that,['java'] +486606,runwith and contextconfiguration weird behaviour i have this very simple class runwithspringjunit4classrunnerclass contextconfigurationlocationsclasspathapplicationcontextthisdoesnotexistxml public class htmlsourceextractorimpltest autowired applicationcontext context test public void test string beans contextgetbeandefinitionnames forstring bean beans systemoutprintlnbean systemoutprintlntesting this context file that is specified in classpath does not exist i can put virtually any name i want and the code does not break i mean the test runs just fine as if that file really existsif i do a small change from classpath to classpath then it beaks saying that this file does not exist which is the behavior i would expect in the first case alsospring version 323release can someone explain this weird behavior editthings from logs as suggested 204726923 info genericapplicationcontext refreshing orgspringframeworkcontextsupportgenericapplicationcontext3df6c65c startup date fri jun 07 204726 pdt 2013 root of context hierarchyi even tried to output all beans from application context orgspringframeworkcontextannotationinternalconfigurationannotationprocessor orgspringframeworkcontextannotationinternalautowiredannotationprocessor orgspringframeworkcontextannotationinternalrequiredannotationprocessor orgspringframeworkcontextannotationinternalcommonannotationprocessor orgspringframeworkcontextannotationconfigurationclassprocessorimportawareprocessorseems to me that in case of a wildcard spring will create a default empty application context,['java'] +486668,game center gkmatch gksenddatareliable packet lost i have been using gkmatch for quite a while successfully in an app i have been chasing down and issue with the game occasionally stopping and have tracked it down to packets being sent but not received this happens only occasionally but i cannot seem to track down why it happensall messages are sent using gksenddatareliablelogging has shown that the packet is being sent from one device successfully but it is never received at the target devicecode sample of sending methodselfmodelmatch is a gkmatch instance bool senddatatoallplayersnsdata data errornserror error selfmodeldebugger addtologgkmanager sending data return selfmodelmatch senddatatoallplayersdata withdatamodegksenddatareliable errorerror code sample of receiving method the match received data sent from the playervoidmatchgkmatch match didreceivedatansdata data fromplayernsstring playerid selfmodeldebugger addtologgkmanager received data super didreceivedatadata fromplayerplayeridwhat i see happen is that periodically maybe 1 in 100 messages is sent without error from the senddatatoallplayers method but the receiving device never hits the didreceivedata method my understanding is that using gksenddatareliable should send messages and then would not send another until it receives an acknowledgement messages are not received but new messages are sent from the same devicethe sending method returns yes and error is nil but the didreceivedata is never hithas anyone ever seen this does anyone have any ideas what this could be i do not know what else i could do to debug this,['ios'] +486669,apache httpd using up mem until hang it appears we might have a growing memory issue in our apache httpd somewhere quick pic notice that it is been running fine on the original physical server for a while now on the new vm with more memory and cpu it runs but slowly eats away at memswap until the system hangsif i restart the httpd the mem jumps back up if we catch ithttpdx86 64 22376el5 9 installedphp 516 cli built jun 22 2012 062025mysql server version 5095i do not think it can be any of the scripts that are runetc as they ran fine for years on the physical machine weve tried to match all configs http php etc on new machine but cannot figure out why httpd keeps growing ps ylc httpd sortrs uid pid ppid c pri ni rss sz wchan tty time cmds 0 13814 1 0 78 0 29208 68382 0 httpds 48 20854 13814 0 76 0 34876 70930 semtim 0 httpds 48 20853 13814 0 75 0 36592 71387 semtim 0 httpds 48 13822 13814 0 75 0 36780 71430 semtim 0 httpds 48 20696 13814 0 75 0 37092 71520 semtim 0 httpds 48 13821 13814 0 75 0 37184 71529 semtim 01 httpds 48 13820 13814 0 75 0 37220 71527 01 httpds 48 13824 13814 0 75 0 37236 71513 semtim 01 httpds 48 13818 13814 0 75 0 37636 71547 semtim 01 httpds 48 13819 13814 0 75 0 37636 71617 semtim 01 httpds 48 13823 13814 0 75 0 378 71689 semtim 01 httpds 48 13825 13814 0 75 0 37900 71676 semtim 01 httpdupdate while writing this question out maybe 1015 minutes i reran the above and the rss are all sitting at 51072 instead of the above at 370 heres a run from the python program private shared ram used program snipped out 2080 mib 255 mib 2335 mib httpd 12 4771 mibphp mem settingsmax execution time 30 max input time 60 memory limit 152m modules apachectl mhttpd could not reliably determine the servers fully qualified domain name using 19216812 for servernameloaded modules core module static mpm prefork module static http module static so module static auth basic module shared auth digest module shared authn file module shared authn alias module shared authn anon module shared authn dbm module shared authn default module shared authz host module shared authz user module shared authz owner module shared authz groupfile module shared authz dbm module shared authz default module shared ldap module shared authnz ldap module shared include module shared log config module shared logio module shared env module shared ext filter module shared mime magic module shared expires module shared deflate module shared headers module shared usertrack module shared setenvif module shared mime module shared dav module shared status module shared autoindex module shared info module shared dav fs module shared vhost alias module shared negotiation module shared dir module shared actions module shared speling module shared userdir module shared alias module shared rewrite module shared proxy module shared proxy balancer module shared proxy ftp module shared proxy http module shared proxy connect module shared cache module shared suexec module shared thisk cache module shared file cache module shared mem cache module shared cgi module shared version module shared perl module shared php5 module shared proxy ajp module shared python module shared ssl module sharedsyntax okhttpdconf settingsifmodule preforkc ignore format on these tagsstartservers 8minspareservers 5maxspareservers 20serverlimit 256maxclients 256maxrequestsperchild 40 worker mpmstartservers 2maxclients 150minsparethreads 25maxsparethreads 75threadsperchild 25maxrequestsperchild 0using the program at i have gottencheck apache httpd mpm config limits version 24by jeansebastien morisset httpd binary config etchttpdconfhttpdconf exe usrsbinhttpd mpm prefork root etchttpd version 22httpd processes pid 10860 httpd 10693 mb 395 mb shared pid 13814 httpd 2852 mb 636 mb shared excluded from averages pid 13818 httpd 18028 mb 429 mb shared pid 13819 httpd 18267 mb 404 mb shared pid 13820 httpd 18245 mb 408 mb shared pid 13821 httpd 18553 mb 404 mb shared pid 13822 httpd 17612 mb 436 mb shared pid 13823 httpd 18005 mb 404 mb shared pid 13824 httpd 18221 mb 405 mb shared pid 13825 httpd 17936 mb 404 mb shared pid 20696 httpd 18010 mb 404 mb shared pid 20853 httpd 18039 mb 403 mb shared pid 20854 httpd 18079 mb 404 mb shared pid 21003 httpd 15977 mb 405 mb shared httpdrealavg 16609 mb excludes shared httpdsharedavg 405 mb httpdrealtot 2576 mb excludes shared httpdrunning 14httpd config startservers 8 serverlimit 256 minspareservers 5 maxspareservers 20 maxrequestsperchild 40 maxclients 256server memory cached 67146 mb memfree 54788 mb memtotal 381989 mb swapfree 595189 mb swaptotal 595199 mbcalculations summary otherprocsmem 37074 mb memtotal cached memfree httpdrealtot httpdsharedavg freememnohttpd 344915 mb memfree cached httpdrealtot httpdsharedavg maxlimithttpdmem 4252309 mb httpdrealavg maxclients httpdsharedavg allprocstotalmem 4289383 mb otherprocsmem maxlimithttpdmemmaximum values for memtotal 381989 mb startservers 8 no change default is 5 serverlimit 21 256 21 maxclients minspareservers 5 no change default is 5 maxspareservers 20 no change default is 10 maxrequestsperchild 40 no change default is 10 maxclients 21 256 21 memfree cached httpdrealtot httpdsharedavg httpdrealavg resulterror allprocstotalmem 4289383 mb exceeds memtotal 381989 mb and free swap 595189 mb by 3312205 mb,['php'] +486684,c using templates instead of virtual functions i do not have a precise description of the problem so i am just asking if this is possible and if it is some other information would be greata programmer told me that not to incur in runtime overhead due to virtual functions polymorphism one may use templates in a way similar to thisclass derived public basederived but i did not understand this last passage how can one use templates to substitute normal virtual functions polymorphism did i get it wrong,['c++'] +486719,stringification how does it work i know thatdefine foo 4 define strs swith strfoo writes out foo because stringify is executed first of text expansion but this define xstrs strs define strs s define foo 4with xstrfoo writes out 4why what are the steps involved in the process,"['c++', 'c']" +486937,how to change div contenteditable from true to false i got a page which let user change the text inside div and save the html code into db however when i thisplay back the html code i want to change the div contenteditable into false is there any way html head titlegenerate postertitle link relstylesheet typetextcss hrefstyle1css link href relstylesheet typetextcss link href relstylesheet typetextcss link relstylesheet href script srcscript script srcscript script srcfunctionjsscriptheadbodyh1h1h1div classdragdiv idbox stylepaddingleft 45px background url2pngdiv classlinedivision1 stylemargintop 100px backgroundcolor 003663divdiv idsubtitle contenteditabletruespanyoure in for aspandivdiv idtitle contenteditabletruewild font color90a6b9ridefontdivdiv classlinedivision1 stylemargintop 20px backgroundcolor 003663divdiv classdate1 contenteditabletruethis january 21st 2014divdiv classdate1 contenteditabletrue1337 accelerator kldivdiv classlinedivision1 stylewidth 150px height22px float left backgroundcolor 003663 margintop 50pxdivdiv classlinedivision1 stylewidth 150px height22px float right backgroundcolor 003663 margintop 50px marginright 50pxdivdiv classdate1 stylefontsize 80px width 500px contenteditabletruejoin usdivbrdiv classdate1 stylefontsize 38px margintop 20pxfor a ride of your life timedivimg srcwatermpng stylezoom30 margintop 280px marginleft 20px divdiv,['javascript'] +486970,adding custom property to marker google map android api v2 when using google map api v3 i can add custom property in the following wayvar marker new googlemapsmarker position userlocation map mygooglemap animation googlemapsanimationdrop icon avatar title username customproperty1 bla customproperty2 bla customproperty3 bla i am wondering if i can do the same for api v2 android the reason i want to do this is that each info window of each marker need to know some information of that marker and i am trying to achieve this in render function belowprivate void rendermarker marker view view int badge rdrawableandroid face if markercustomproperty here i need to know this property to decide which image to use badge rdrawablebla imageview viewfindviewbyidridbadge setimageresourcebadge,['android'] +486985,compare two strings using regex i am using two strings for a matching program like thisstring s1 5461301221234511011string s2 61301221and i am going to write a regex matching function which compares each part string between each separately and calculates the match percent which is the number of matches occurring in each stringfor example in this example we have these matches61301221in this example the match percent is 131001587currently i am using the function below but i think it is not optimized and using regex may be fasterpublic double matchpercentstring s1 string s2 int percent0 user s1splittoarray policy s2splittoarray for int i 0 i s1length 2 i int you userisplitwherea a selectn converttoint32nthistincttoarray int p policyisplitwherea a selectn converttoint32nthistincttoarray var co uintersectp if cocount 0 percent 1 return mathroundpercent 100 s1length,['c#'] +486997,dropzonejs how to do something after all files are uploaded i am using dropzonejs for my dragdrop file upload solution i am stuck at something where i need to call a function after all the files are uploaded in this casedropzoneoptionsfiledrop maxfilesize 4096 init function thisoncomplete function file dosomething dosomething will be called for each file that has been uploaded how can i call a function after all the files are uploaded,"['javascript', 'jquery']" +487026,how to avoid unassigned local variable defined inside a trycatch block this is one error that i regularly face although i manage to circumvent it using some way or another it really annoys mein the code snippet below i want to safe guard against exceptions from myrequestgetresponse webrequest myrequest webrequestcreatebaseurioriginalstring webresponse myresponse stream mystream streamreader reader try myresponse myrequestgetresponse mystream myresponsegetresponsestream reader new streamreadermystream catch webexception status txtconsoleappendtexterror in getlinkswebexceptionn statusresponse txtconsoleappendtextenvironmentnewline catch txtconsoleappendtextsome error in getlinks txtconsoleappendtextenvironmentnewline regex regex new regexsihrefs regexoptionsignorecase matchcollection splits regexmatchesreaderreadtoendnow when i try to buildcompile the code it says use of unassigned local variable readernow my question if try statement runs smoothly without any exceptions being thrown why cannot the compiler access the value assigned to reader inside the try block,['c#'] +487068,scrapy why extracted strings are in this format i am doingitemdesc siteselectatextextractbut this will be printed like thisun a mano liberan what must i do to tim and remove strange chars like un the traling space and i cannot trim stripexceptionsattributeerror list object has no attribute stripand if converting to string and then stripping the result was the string above which i suppose to be in utf8,['python'] +487080,how to run unittest thiscover from python setuppy test i am trying to figure out how to get python setuppy test to run the equivalent of python m unittest thiscover i do not want to use a run testspy script and i do not want to use any external test tools like nose or pytest it is ok if the solution only works on python 27in setuppy i think i need to add something to the test suite andor test loader fields in config but i cannot seem to find a combination that works correctlyconfig name name version version url url test suite test loader is this possible using only unittest built into python 27fyi my project structure looks like thisproject package init py modulepy tests init py test modulepy run testspy i want to delete this setuppyupdate this is possible with unittest2 but i want find something equivalent using only unittestfrom unittest2 includes a very basic setuptools compatible test collector specify test suite unittest2collector in your setuppy this starts test thiscovery with the default parameters from the directory containing setuppy so it is perhaps most useful as an example see unittest2collectorpyfor now i am just using a script called run testspy but i am hoping i can get rid of this by moving to a solution that only uses python setuppy testheres the run testspy i am hoping to removeimport unittestif name main use the default shared testloader instance test loader unittestdefaulttestloader use the basic test runner that outputs to sysstderr test runner unittesttexttestrunner automatically thiscover all tests in the current dir of the form testpy note only works for python 27 and later test suite test loaderthiscover run the test suite test runnerruntest suite,['python'] +487088,camera intent and priority queue in android i am currently writing an android app api level 233 that involves taking the 300 highest grayscale values from a photo taken via camera intent following functions mainly maths and some calendarclock based are performed on the resultant value i am using eclipseemulated camerathe camera will activate and the photo is taken without a problem it is when i try to save the photo and when the pixel sorting and mathematicalcalendar functions are to occur the app crashesi tested the app with just the camera intent and a dummy value for the main variable y and this worked finewhat is going wrongbelow is the relevant section of codeint pixels button button button findviewbyidridbutton buttonsetonclicklistenernew viewonclicklistener override public void onclickview v string path environmentgetexternalstoragedirectory fileseparator sunpicjpg file file new file path uri outputfileuri urifromfilefile intent intent new intent androidprovidermediastoreaction image capture intentputextramediastoreextra output outputfileuri startactivityforresultintent 1 overrideprotected void onactivityresultint requestcode int resultcode intent data superonactivityresultrequestcode resultcode data switchrequestcode case 1 if resultcode result ok uri outputfileuri datagetdata try bitmap bmp androidprovidermediastoreimagesmediagetbitmapthisgetcontentresolver outputfileuri bmpgetpixelspixels 0 bmpgetwidth 0 0 bmpgetwidth bmpgetheight forint x 0 x bmpgetwidth x forint y 0 y bmpgetheight y int index y bmpgetwidth x int r pixelsindex 16 0xff int g pixelsindex 8 0xff int b pixelsindex 0xff double grey 0299 r 0587 g 0114 b int topsize 300 priority queue to save the largest topsize values priorityqueuedouble pq pq new priorityqueuedoubletopsize1 double nv greyfloatvalue if pqsize topsize pqpeek nv remove the smallest value from the queue only if it is full if pqsize topsize pqpoll pqaddnv double sum 0 fordouble d pq sum d double y sum 300in the xml manifest i haveusespermission androidnameandroidpermissioncamerausespermission androidnameandroidpermissionwrite external storageusesfeature androidnameandroidhardwarecameralogcat errorswarnings0609 021040076 esurfaceflinger37 rosflcd density must be defined as a build property0609 021041646 etrace4464 error opening trace file no such file or directory 20609 021049907 wactivitymanager289 launch timeout has expired giving up wake lock0609 021050817 esurfaceflinger37 rosflcd density must be defined as a build property0609 021051106 wactivitymanager289 activity idle timeout for activityrecord40ec7900 inactivity0609 0210547 wactivitymanager289 unable to start service intent actcomandroidemailaccount intent u0 not found0609 0210587 wegl emulation4464 eglsurfaceattrib not implemented0609 021056477 wactivitymanager289 unable to start service intent actcomandroidemailaccount intent u0 not found0609 021056487 eactivitythread707 service comandroidexchangeexchangeservice has leaked serviceconnection comandroidemailcommonserviceserviceproxyproxyconnection40cfe978 that was originally bound here0609 021056487 eactivitythread707 androidappserviceconnectionleaked service comandroidexchangeexchangeservice has leaked serviceconnection comandroidemailcommonserviceserviceproxyproxyconnection40cfe978 that was originally bound here0609 021056487 eactivitythread707 at androidapploadedapkservicethispatcherinitloadedapkjava9690609 021056487 eactivitythread707 at androidapploadedapkgetservicethispatcherloadedapkjava8630609 021056487 eactivitythread707 at androidappcontextimplbindservicecontextimpljava14180609 021056487 eactivitythread707 at androidappcontextimplbindservicecontextimpljava14070609 021056487 eactivitythread707 at androidcontentcontextwrapperbindservicecontextwrapperjava4730609 021056487 eactivitythread707 at comandroidemailcommonserviceserviceproxysettaskserviceproxyjava1570609 021056487 eactivitythread707 at comandroidemailcommonserviceserviceproxysettaskserviceproxyjava1450609 021056487 eactivitythread707 at comandroidemailcommonserviceserviceproxytestserviceproxyjava1910609 021056487 eactivitythread707 at comandroidexchangeexchangeservice7runexchangeservicejava18500609 021056487 eactivitythread707 at comandroidemailcommonutilityutility2doinbackgroundutilityjava5510609 021056487 eactivitythread707 at comandroidemailcommonutilityutility2doinbackgroundutilityjava5490609 021056487 eactivitythread707 at androidosasynctask2callasynctaskjava2870609 021056487 eactivitythread707 at javautilconcurrentfuturetaskrunfuturetaskjava2340609 021056487 eactivitythread707 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava10800609 021056487 eactivitythread707 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava5730609 021056487 eactivitythread707 at javalangthreadrunthreadjava8560609 021056510 estrictmode707 null0609 021056510 estrictmode707 androidappserviceconnectionleaked service comandroidexchangeexchangeservice has leaked serviceconnection comandroidemailcommonserviceserviceproxyproxyconnection40cfe978 that was originally bound here0609 021056510 estrictmode707 at androidapploadedapkservicethispatcherinitloadedapkjava9690609 021056510 estrictmode707 at androidapploadedapkgetservicethispatcherloadedapkjava8630609 021056510 estrictmode707 at androidappcontextimplbindservicecontextimpljava14180609 021056510 estrictmode707 at androidappcontextimplbindservicecontextimpljava14070609 021056510 estrictmode707 at androidcontentcontextwrapperbindservicecontextwrapperjava4730609 021056510 estrictmode707 at comandroidemailcommonserviceserviceproxysettaskserviceproxyjava1570609 021056510 estrictmode707 at comandroidemailcommonserviceserviceproxysettaskserviceproxyjava1450609 021056510 estrictmode707 at comandroidemailcommonserviceserviceproxytestserviceproxyjava1910609 021056510 estrictmode707 at comandroidexchangeexchangeservice7runexchangeservicejava18500609 021056510 estrictmode707 at comandroidemailcommonutilityutility2doinbackgroundutilityjava5510609 021056510 estrictmode707 at comandroidemailcommonutilityutility2doinbackgroundutilityjava5490609 021056510 estrictmode707 at androidosasynctask2callasynctaskjava2870609 021056510 estrictmode707 at javautilconcurrentfuturetaskrunfuturetaskjava2340609 021056510 estrictmode707 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava10800609 021056510 estrictmode707 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava5730609 021056510 estrictmode707 at javalangthreadrunthreadjava8560609 021056557 wactivitymanager289 unbind failed could not find connection for androidosbinderproxy40e697800609 021102557 wiinputconnectionwrapper4464 getcursorcapsmode on inactive inputconnection0609 021103158 esurfaceflinger37 rosflcd density must be defined as a build property0609 0214797 ewvmextractor40 failed to open libwvmso0609 0215637 ewvmextractor40 failed to open libwvmso0609 021122179 esurfaceflinger37 rosflcd density must be defined as a build property0609 021123076 wegl emulation1762 eglsurfaceattrib not implemented0609 021123256 wactivitymanager289 launch timeout has expired giving up wake lock0609 021123716 wactivitymanager289 activity idle timeout for activityrecord40fb5d68 u0 comandroidcameracamera0609 021124146 esurfaceflinger37 rosflcd density must be defined as a build property0609 021124166 esurfaceflinger37 rosflcd density must be defined as a build property0609 021129237 winputconnectionwrappericc378 timed out waiting on iinputcontextcallback0609 021134387 waudiotrack40 releasebuffer track 0x2a02af18 name0x1 thisabled restarting0609 0211360 wiinputconnectionwrapper4464 getcursorcapsmode on inactive inputconnection0609 021136087 wiinputconnectionwrapper4464 showstatusicon on inactive inputconnection0609 021138667 wactivitymanager289 activity pause timeout for activityrecord40fb5d68 u0 comandroidcameracamera0609 021138950 waudioflinger40 session id 9 not found for pid 400609 021139047 wdalvikvm4464 threadid1 thread exiting with uncaught exception group0x40a719300609 021139057 waudioflinger40 session id 10 not found for pid 400609 021139377 eandroidruntime4464 fatal exception main0609 021139377 eandroidruntime4464 javalangruntimeexception failure delivering result resultinfowhonull request1 result1 datanull to activity irradianceaerosolopticaldepthirradianceaerosolopticaldepthmainactivity javalangnullpointerexception0609 021139377 eandroidruntime4464 at androidappactivitythreaddeliverresultsactivitythreadjava33190609 021139377 eandroidruntime4464 at androidappactivitythreadhandlesendresultactivitythreadjava33620609 021139377 eandroidruntime4464 at androidappactivitythreadaccess1100activitythreadjava1410609 021139377 eandroidruntime4464 at androidappactivitythreadhhandlemessageactivitythreadjava12820609 021139377 eandroidruntime4464 at androidoshandlerthispatchmessagehandlerjava990609 021139377 eandroidruntime4464 at androidoslooperlooplooperjava1370609 021139377 eandroidruntime4464 at androidappactivitythreadmainactivitythreadjava50410609 021139377 eandroidruntime4464 at javalangreflectmethodinvokenativenative method0609 021139377 eandroidruntime4464 at javalangreflectmethodinvokemethodjava5110609 021139377 eandroidruntime4464 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava7930609 021139377 eandroidruntime4464 at comandroidinternaloszygoteinitmainzygoteinitjava5600609 021139377 eandroidruntime4464 at dalviksystemnativestartmainnative method0609 021139377 eandroidruntime4464 caused by javalangnullpointerexception0609 021139377 eandroidruntime4464 at irradianceaerosolopticaldepthmainactivityonactivityresultmainactivityjava730609 021139377 eandroidruntime4464 at androidappactivitythispatchactivityresultactivityjava52930609 021139377 eandroidruntime4464 at androidappactivitythreaddeliverresultsactivitythreadjava33150609 021139377 eandroidruntime4464 11 more0609 021139897 wactivitymanager289 force finishing activity irradianceaerosolopticaldepthmainactivity0609 021140199 estrictmode1762 a resource was acquired at attached stack trace but never released see javaiocloseable for information on avoiding resource leaks0609 021140199 estrictmode1762 javalangthrowable explicit termination method release not called0609 021140199 estrictmode1762 at dalviksystemcloseguardopencloseguardjava1840609 021140199 estrictmode1762 at androidviewsurfaceinitsurfacejava2890609 021140199 estrictmode1762 at androidviewsurfaceviewinitsurfaceviewjava960609 021140199 estrictmode1762 at javalangreflectconstructorconstructnativenative method0609 021140199 estrictmode1762 at javalangreflectconstructornewinstanceconstructorjava4170609 021140199 estrictmode1762 at androidviewlayoutinflatercreateviewlayoutinflaterjava5870609 021140199 estrictmode1762 at androidviewlayoutinflateroncreateviewlayoutinflaterjava6430609 021140199 estrictmode1762 at comandroidinternalpolicyimplphonelayoutinflateroncreateviewphonelayoutinflaterjava660609 021140199 estrictmode1762 at androidviewlayoutinflateroncreateviewlayoutinflaterjava6600609 021140199 estrictmode1762 at androidviewlayoutinflatercreateviewfromtaglayoutinflaterjava6850609 021140199 estrictmode1762 at androidviewlayoutinflaterrinflatelayoutinflaterjava7460609 021140199 estrictmode1762 at androidviewlayoutinflaterrinflatelayoutinflaterjava7490609 021140199 estrictmode1762 at androidviewlayoutinflaterparseincludelayoutinflaterjava8300609 021140199 estrictmode1762 at androidviewlayoutinflaterrinflatelayoutinflaterjava7360609 021140199 estrictmode1762 at androidviewlayoutinflaterinflatelayoutinflaterjava4890609 021140199 estrictmode1762 at androidviewlayoutinflaterinflatelayoutinflaterjava3960609 021140199 estrictmode1762 at androidviewlayoutinflaterinflatelayoutinflaterjava3520609 021140199 estrictmode1762 at comandroidinternalpolicyimplphonewindowsetcontentviewphonewindowjava2700609 021140199 estrictmode1762 at androidappactivitysetcontentviewactivityjava18810609 021140199 estrictmode1762 at comandroidcameracameraoncreatecamerajava11310609 021140199 estrictmode1762 at androidappactivityperformcreateactivityjava51040609 021140199 estrictmode1762 at androidappinstrumentationcallactivityoncreateinstrumentationjava10800609 021140199 estrictmode1762 at androidappactivitythreadperformlaunchactivityactivitythreadjava21440609 021140199 estrictmode1762 at androidappactivitythreadhandlelaunchactivityactivitythreadjava22300609 021140199 estrictmode1762 at androidappactivitythreadaccess600activitythreadjava1410609 021140199 estrictmode1762 at androidappactivitythreadhhandlemessageactivitythreadjava12340609 021140199 estrictmode1762 at androidoshandlerthispatchmessagehandlerjava990609 021140199 estrictmode1762 at androidoslooperlooplooperjava1370609 021140199 estrictmode1762 at androidappactivitythreadmainactivitythreadjava50410609 021140199 estrictmode1762 at javalangreflectmethodinvokenativenative method0609 021140199 estrictmode1762 at javalangreflectmethodinvokemethodjava5110609 021140199 estrictmode1762 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava7930609 021140199 estrictmode1762 at comandroidinternaloszygoteinitmainzygoteinitjava5600609 021140199 estrictmode1762 at dalviksystemnativestartmainnative method0609 021140647 estrictmode1762 a resource was acquired at attached stack trace but never released see javaiocloseable for information on avoiding resource leaks0609 021140647 estrictmode1762 javalangthrowable explicit termination method release not called0609 021140647 estrictmode1762 at dalviksystemcloseguardopencloseguardjava1840609 021140647 estrictmode1762 at androidviewsurfaceinitsurfacejava2890609 021140647 estrictmode1762 at androidviewsurfaceviewinitsurfaceviewjava970609 021140647 estrictmode1762 at javalangreflectconstructorconstructnativenative method0609 021140647 estrictmode1762 at javalangreflectconstructornewinstanceconstructorjava4170609 021140647 estrictmode1762 at androidviewlayoutinflatercreateviewlayoutinflaterjava5870609 021140647 estrictmode1762 at androidviewlayoutinflateroncreateviewlayoutinflaterjava6430609 021140647 estrictmode1762 at comandroidinternalpolicyimplphonelayoutinflateroncreateviewphonelayoutinflaterjava660609 021140647 estrictmode1762 at androidviewlayoutinflateroncreateviewlayoutinflaterjava6600609 021140647 estrictmode1762 at androidviewlayoutinflatercreateviewfromtaglayoutinflaterjava6850609 021140647 estrictmode1762 at androidviewlayoutinflaterrinflatelayoutinflaterjava7460609 021140647 estrictmode1762 at androidviewlayoutinflaterrinflatelayoutinflaterjava7490609 021140647 estrictmode1762 at androidviewlayoutinflaterparseincludelayoutinflaterjava8300609 021140647 estrictmode1762 at androidviewlayoutinflaterrinflatelayoutinflaterjava7360609 021140647 estrictmode1762 at androidviewlayoutinflaterinflatelayoutinflaterjava4890609 021140647 estrictmode1762 at androidviewlayoutinflaterinflatelayoutinflaterjava3960609 021140647 estrictmode1762 at androidviewlayoutinflaterinflatelayoutinflaterjava3520609 021140647 estrictmode1762 at comandroidinternalpolicyimplphonewindowsetcontentviewphonewindowjava2700609 021140647 estrictmode1762 at androidappactivitysetcontentviewactivityjava18810609 021140647 estrictmode1762 at comandroidcameracameraoncreatecamerajava11310609 021140647 estrictmode1762 at androidappactivityperformcreateactivityjava51040609 021140647 estrictmode1762 at androidappinstrumentationcallactivityoncreateinstrumentationjava10800609 021140647 estrictmode1762 at androidappactivitythreadperformlaunchactivityactivitythreadjava21440609 021140647 estrictmode1762 at androidappactivitythreadhandlelaunchactivityactivitythreadjava22300609 021140647 estrictmode1762 at androidappactivitythreadaccess600activitythreadjava1410609 021140647 estrictmode1762 at androidappactivitythreadhhandlemessageactivitythreadjava12340609 021140647 estrictmode1762 at androidoshandlerthispatchmessagehandlerjava990609 021140647 estrictmode1762 at androidoslooperlooplooperjava1370609 021140647 estrictmode1762 at androidappactivitythreadmainactivitythreadjava50410609 021140647 estrictmode1762 at javalangreflectmethodinvokenativenative method0609 021140647 estrictmode1762 at javalangreflectmethodinvokemethodjava5110609 021140647 estrictmode1762 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava7930609 021140647 estrictmode1762 at comandroidinternaloszygoteinitmainzygoteinitjava5600609 021140647 estrictmode1762 at dalviksystemnativestartmainnative method0609 021142377 wactivitymanager289 activity pause timeout for activityrecord40ec7900 u0 irradianceaerosolopticaldepthmainactivity0609 021143637 esurfaceflinger37 rosflcd density must be defined as a build property0609 021147517 wactivitymanager289 unable to start service intent actcomandroidemailaccount intent u0 not found0609 021148175 wactivitymanager289 launch timeout has expired giving up wake lock0609 021148647 winputthispatcher289 channel 40fc3848 irradianceaerosolopticaldepthirradianceaerosolopticaldepthmainactivity server consumer closed input channel or an error occurred events0x90609 021148647 einputthispatcher289 channel 40fc3848 irradianceaerosolopticaldepthirradianceaerosolopticaldepthmainactivity server channel is unrecoverably broken and will be thisposed0609 021148767 winputthispatcher289 attempted to unregister already unregistered input channel 40fc3848 irradianceaerosolopticaldepthirradianceaerosolopticaldepthmainactivity server0609 021149668 wactivitymanager289 unable to start service intent actcomandroidemailaccount intent u0 not found0609 021150137 eactivitythread707 service comandroidexchangeexchangeservice has leaked serviceconnection comandroidemailcommonserviceserviceproxyproxyconnection40d0b180 that was originally bound here0609 021150137 eactivitythread707 androidappserviceconnectionleaked service comandroidexchangeexchangeservice has leaked serviceconnection comandroidemailcommonserviceserviceproxyproxyconnection40d0b180 that was originally bound here0609 021150137 eactivitythread707 at androidapploadedapkservicethispatcherinitloadedapkjava9690609 021150137 eactivitythread707 at androidapploadedapkgetservicethispatcherloadedapkjava8630609 021150137 eactivitythread707 at androidappcontextimplbindservicecontextimpljava14180609 021150137 eactivitythread707 at androidappcontextimplbindservicecontextimpljava14070609 021150137 eactivitythread707 at androidcontentcontextwrapperbindservicecontextwrapperjava4730609 021150137 eactivitythread707 at comandroidemailcommonserviceserviceproxysettaskserviceproxyjava1570609 021150137 eactivitythread707 at comandroidemailcommonserviceserviceproxysettaskserviceproxyjava1450609 021150137 eactivitythread707 at comandroidemailcommonserviceaccountserviceproxygetdeviceidaccountserviceproxyjava1160609 021150137 eactivitythread707 at comandroidexchangeexchangeservicegetdeviceidexchangeservicejava12490609 021150137 eactivitythread707 at comandroidexchangeexchangeservice7runexchangeservicejava18560609 021150137 eactivitythread707 at comandroidemailcommonutilityutility2doinbackgroundutilityjava5510609 021150137 eactivitythread707 at comandroidemailcommonutilityutility2doinbackgroundutilityjava5490609 021150137 eactivitythread707 at androidosasynctask2callasynctaskjava2870609 021150137 eactivitythread707 at javautilconcurrentfuturetaskrunfuturetaskjava2340609 021150137 eactivitythread707 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava10800609 021150137 eactivitythread707 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava5730609 021150137 eactivitythread707 at javalangthreadrunthreadjava8560609 021150387 esurfaceflinger37 rosflcd density must be defined as a build property0609 021150650 estrictmode707 null0609 021150650 estrictmode707 androidappserviceconnectionleaked service comandroidexchangeexchangeservice has leaked serviceconnection comandroidemailcommonserviceserviceproxyproxyconnection40d0b180 that was originally bound here0609 021150650 estrictmode707 at androidapploadedapkservicethispatcherinitloadedapkjava9690609 021150650 estrictmode707 at androidapploadedapkgetservicethispatcherloadedapkjava8630609 021150650 estrictmode707 at androidappcontextimplbindservicecontextimpljava14180609 021150650 estrictmode707 at androidappcontextimplbindservicecontextimpljava14070609 021150650 estrictmode707 at androidcontentcontextwrapperbindservicecontextwrapperjava4730609 021150650 estrictmode707 at comandroidemailcommonserviceserviceproxysettaskserviceproxyjava1570609 021150650 estrictmode707 at comandroidemailcommonserviceserviceproxysettaskserviceproxyjava1450609 021150650 estrictmode707 at comandroidemailcommonserviceaccountserviceproxygetdeviceidaccountserviceproxyjava1160609 021150650 estrictmode707 at comandroidexchangeexchangeservicegetdeviceidexchangeservicejava12490609 021150650 estrictmode707 at comandroidexchangeexchangeservice7runexchangeservicejava18560609 021150650 estrictmode707 at comandroidemailcommonutilityutility2doinbackgroundutilityjava5510609 021150650 estrictmode707 at comandroidemailcommonutilityutility2doinbackgroundutilityjava5490609 021150650 estrictmode707 at androidosasynctask2callasynctaskjava2870609 021150650 estrictmode707 at javautilconcurrentfuturetaskrunfuturetaskjava2340609 021150650 estrictmode707 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava10800609 021150650 estrictmode707 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava5730609 021150650 estrictmode707 at javalangthreadrunthreadjava8560609 021150677 wactivitymanager289 unbind failed could not find connection for androidosbinderproxy411501780609 021150927 wegl emulation407 eglsurfaceattrib not implemented0609 021151347 eactivitythread707 service comandroidexchangeexchangeservice has leaked serviceconnection comandroidemailcommonserviceserviceproxyproxyconnection40d0a990 that was originally bound here0609 021151347 eactivitythread707 androidappserviceconnectionleaked service comandroidexchangeexchangeservice has leaked serviceconnection comandroidemailcommonserviceserviceproxyproxyconnection40d0a990 that was originally bound here0609 021151347 eactivitythread707 at androidapploadedapkservicethispatcherinitloadedapkjava9690609 021151347 eactivitythread707 at androidapploadedapkgetservicethispatcherloadedapkjava8630609 021151347 eactivitythread707 at androidappcontextimplbindservicecontextimpljava14180609 021151347 eactivitythread707 at androidappcontextimplbindservicecontextimpljava14070609 021151347 eactivitythread707 at androidcontentcontextwrapperbindservicecontextwrapperjava4730609 021151347 eactivitythread707 at comandroidemailcommonserviceserviceproxysettaskserviceproxyjava1570609 021151347 eactivitythread707 at comandroidemailcommonserviceserviceproxysettaskserviceproxyjava1450609 021151347 eactivitythread707 at comandroidemailcommonserviceserviceproxytestserviceproxyjava1910609 021151347 eactivitythread707 at comandroidexchangeexchangeservice7runexchangeservicejava18500609 021151347 eactivitythread707 at comandroidemailcommonutilityutility2doinbackgroundutilityjava5510609 021151347 eactivitythread707 at comandroidemailcommonutilityutility2doinbackgroundutilityjava5490609 021151347 eactivitythread707 at androidosasynctask2callasynctaskjava2870609 021151347 eactivitythread707 at javautilconcurrentfuturetaskrunfuturetaskjava2340609 021151347 eactivitythread707 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava10800609 021151347 eactivitythread707 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava5730609 021151347 eactivitythread707 at javalangthreadrunthreadjava8560609 021152498 wactivitymanager289 activity idle timeout for activityrecord40f7a298 u0 comandroidlaunchercomandroidlauncher2launcher,['android'] +487133,why has the stdvectorresize signature been changed in c11 what are the reasons behind the change in stdvectorresize from the prec11void resize size type count t value t to the compatible c11 formvoid resize size type count void resize size type count const value type value,['c++'] +487150,stringbuilder modified by multiple threads the question i am asking is related to stringbuilder and stringbuffer in java but not the same i want to see what really happens if a stringbuilder is modified by two threads at the same timei wrote the following classespublic class threadtester public static void mainstring args throws interruptedexception runnable threadjob new myrunnable thread mythread new threadthreadjob mythreadstart for int i 0 i 100 i threadsleep10 stringcontaineraddtosba systemoutprintln1 stringcontainergetsb systemoutprintln1 length stringcontainergetsblength public class myrunnable implements runnable override public void run for int i 0 i 100 i try threadsleep10 catch interruptedexception e eprintstacktrace stringcontaineraddtosbb systemoutprintln2 stringcontainergetsb systemoutprintln2 length stringcontainergetsblength public class stringcontainer private static final stringbuffer sb new stringbuffer public static stringbuffer getsb return sb public static void addtosbstring s sbappends initially i kept a stringbuffer in the stringcontainer since stringbuffer is threadsafe at a time only one thread can append to it so the output is consistent either both threads reported the length of the buffer as 200 like1 abababababababababbaabababababababbaababababababababababababbabaabbababaabbaababababbababaabbababaabababbaabababbababababaababababababababbababaabbaababbaababababababbaababbababaababbabaabbababababaab1 length 2002 abababababababababbaabababababababbaababababababababababababbabaabbababaabbaababababbababaabbababaabababbaabababbababababaababababababababbababaabbaababbaababababababbaababbababaababbabaabbababababaab2 length 200or one of them reported 199 and the other 200 like2 abbabababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababab2 length 1991 abbababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababa1 length 200the key is that the last thread to complete reports a length of 200now i changed stringcontainer to have a stringbuilder instead of stringbuffer ie public class stringcontainer private static final stringbuilder sb new stringbuilder public static stringbuilder getsb return sb public static void addtosbstring s sbappends i expect some of the writes to be overwritten which is happening but the contents of the stringbuilder and the lengths do not match sometimes1 ababbabababaababbaabbabababababaab1 length 1372 ababbabababaababbaabbabababababaab2 length 137as you can see the printed content has only 34 chars but the length is 137 why is this happeningextreme coders i just did one more test run2 ababbabababaabbababaabbababaababaabbaababbababbaabbabbabbabababbabababababababbaabababbabaababaababbaabaababababbaababababababbababaab1 ababbabababaabbababaabbababaababaabbaababbababbaabbabbabbabababbabababababababbaabababbabaababaababbaabaababababbaababababababbababaab1 length 1502 length 150java version 160 45 and i am using eclipse version eclipse java ee ide for web developersversion juno service release 2build id 201302250426update 1 i ran this outside eclipse and now they seem to be matching but i am getting arrayindexoutofboundsexception sometimes java versionjava version 160 27openjdk runtime environment icedtea6 1125 6b2711250ubuntu012041openjdk server vm build 200b12 mixed mode java threadtester1 abababbabababababaababbaabaabababababbabababbabbabababaabaabababaabbabaababababababbababab1 length 1232 abababbabababababaababbaabaabababababbabababbabbabababaabaabababaabbabaababababababbababab2 length 123 java threadtester 2 abbabaabababababababababababababababbabaababbababababaabbaab2 length 1151 abbabaabababababababababababababababbabaababbababababaabbaab1 length 115 java threadtester exception in thread main javalangarrayindexoutofboundsexception at javalangsystemarraycopynative method at javalangstringgetcharsstringjava862 at javalangabstractstringbuilderappendabstractstringbuilderjava408 at javalangstringbuilderappendstringbuilderjava136 at stringcontaineraddtosbstringcontainerjava14 at threadtestermainthreadtesterjava142 ababababababaabbabababababaabaabaababababaab2 length 114the arrayindexoutofboundsexception is also happening when running from eclipseupdate 2there are two problems happening the first problem of the contents of the stringbuilder not matching the length is happening only in eclipse and not when i run in command line at least the 100 times i ran it on command line it never happenedthe second problem with arrayindexoutofboundsexception should be to do with the internal implementation of stringbuilder class which keeps an array of chars and does an arrayscopyof when it expands the size but it still beats me how a write is happening before the size is expanded no matter what the order of execution isbtw i am inclined to agree with greybeardedgeeks answer that this whole exercise is a huge waste of time sometimes we get to see only the symptoms ie the output of some code and wonder what is going wrong this question declared a priori that two threads are modifying a very wellknown thread unsafe objectupdate 3 here is the official answer from java concurrency in practice p 35 in the absence of synchronization the compiler processor andruntime can do some downright weird things to the order in whichoperations appear to execute attempts to reason about the order inwhich memory actions must happen in insufficiently synchronizedmultithreaded programs will almost certainly be incorrect reasoning about insufficiently synchronized concurrent programs isprohibitively difficultthere is also a nice example novisibility in the book on p 34,['java'] +487158,capybara how to assert a given number of elements exist i have upgraded my whole stack from a rails 30 based project to 31 i have specs passing but my features are now being a bit picky the issue i am currently having is this stepthen i should see d menu items within do count selector pagefindcss selector count countto iendand in the feature itself i might putthen i should see 5 menu items within trmenu item rowthe message i get isthen i should see 5 menu items within trmenu item row featuresstep definitionsadmin menu stepsrb1 ambiguous match found 5 elements matching css trmenu item row capybaraambiguous featuresstep definitionsadmin menu stepsrb2in i should see d menu items within featuresadmin menufeature30in then i should see 5 menu items within trmenu item rowas far as i can tell the 5 elements match the 5 that were actually found did i write this code wrong or has something major changed thanks,['ruby-on-rails'] +487179,what is the situation in 2013 with notnull annotations in java it seems like there are quite a few different annotations to indicate the nullability status of method parameters and return values in java and the situation has been evolvingwhat are best practices in 2013 for annotating my methods for nullabilityi am aware of this question but it is from 3 years ago and i suspect the situation has changed since thenwhich notnull java annotation should i usei personally use intellij idea but would hope for a solution that does not tie my project to that ide i use maven for dependency management,['java'] +487199,for loop without the second condition ie the boolean check i have to write a function that calculates the floor of log base 16 of an unsigned int passed in there are restrictions as to what operators and what constants we are allowed to use and we can only use specifically for loops for clarity we cannot use any conditional statementsif else switch the function prototype is int floor log16unsigned int x allowed operators allowed constants 1 2 3 4 8 16i wrote a version of the program as followsint floor log16unsigned int x int index1 int count11 count for indexx index4 count return countwhich seems to work as desired however i realized that based on the later functions and description of the needed functionality we have to write i noticed that under allowed operators sometimes and were listed i deduce this implies that since for the floor log16 function listed above we werent explicitly told to use or i can only assume that the solution posted above will not be accepted this leaves me rather confused because i do not understand how you can possibly have a for loop without a boolean check is not the whole idea of a loop to iterate while a condition is met,['c'] +487218,angular ngchange for select not calling the declared method i have the following html form select statementselect ngchangesetbillgroup ngmodelbillgroupid claspan8 ngoptionsdid as dname for d in groupsselectand the jsmyappcontrollermyappcontroller functionscope myappservice function setbillgroup consolelogsetbillgroup method called but for some reason the setbillgroup never seems to get called when i select something or the other in the form,"['javascript', 'html']" +487220,dynamically created audio object not playing in android chrome browser i am trying to write a ria which can be used on both mobile as well as desktop browsers one main objective of this app is to play sounds there could be x many as of now there are 150on a certain user action i want to create a new audio object load a certain clip and play it ideally i would create a new audio object set the src wait for load then play this works on various desktop browsers however seems to fail on android 42 chrome and stock browsersi have tried 4 different ways of including audioincluding in html just an audio block have it load at runtime and calling play this works however it means i must create 150 audio blocks this works everywherecreate a new instance of audio and dynamically setting the src attribute then on loadcomplete calling play this seems to works only on desktop browsers not on my mobileuse jquery to create new audio tag add to dom wait for load then play this seems to works only on desktop browsers not on my mobileadd audio tags in html with telling it to not load wait for user interaction then load it wait for it to get ready then play this works everywhereso the big question is any idea why this is not working edit i know that only 1 file can be played at a time and that is what i am trying to do here project is functionally similar to a phone service where you have 1 person record the numbers 0 9 then it speaks a phone number so 501 etc so 1 audio stream out at a time is perfectly acceptable it is just getting it to play which is the issueas of right now i have the following code which can also be found heredoctype htmlhtml xmlnsheadtitletesttitlescript srcajaxgoogleapiscomajaxlibsjquery1101jqueryminjsscriptscript var a1 a2 a3 a4 documentready function setupvars addlisteners function setupvars a1 audio1 a2 audio2 a3 audio3 a4 audio4 function addlisteners a1click handleaudio1 a2click handleaudio2 a3click handleaudio3 a4click handleaudio4 function handleaudio1 america0play function handleaudio2 var a new audio aoncanplay function aplay ifacanplaytypeaudiomp3 asrc audiotest2mp3 else ifacanplaytypeaudioogg asrc audiotest2ogg function handleaudio3 var x audio idsays source srcaudiotest3mp3 source srcaudiotest3ogg audio xoncanplay function x0play audiocontappendx function handleaudio4 var x cat xoncanplay function x0play x0load scriptheadbody input typebutton idaudio1 valueplay audio tagbr input typebutton idaudio2 valueplay audio objectbr input typebutton idaudio3 valueplay dynamic audio tagbr input typebutton idaudio4 valueplay load audio tag then playbr audio idamerica source srcaudiotest1mp3 source srcaudiotest1ogg audio audio idcat source srcaudiotest4mp3 source srcaudiotest4ogg audiobodyhtml,"['javascript', 'android']" +487229,bootstrap 23 css responsive left with a white space on the right i am creating a website and i am a noob at this i am working on the functionality portion of design and i will have someone do graphics latercurrently when it goes into responsive mobile view it leaves a 2px margin on the right that is movable on a mobile browser and scrollable i cannot for the life of me get rid of thatif i turn on overflowx hidden then it does become non scrollable but still movablei want that extra space to go away i do not see it defined as padding in any of the cssusing bootstrap 23,['css'] +487286,why comfacebooksettingspublishinstallasync in onresume i looked into the facebook sdk 30 to try and find out how to track installs coming from a facebook campaign and saw this in the documentationfor the fb android sdk 30 add the following to onresume of each activity in your app comfacebooksettingspublishinstallasynccontext your app idi have 2 basic questionswhy is this happening in every activity instead of in the launcher activitywhy is this happening in the onresume method instead of onstart android recommends not doing things like this in the onresumeedit even though it is asynchronous doing this over and over seems stupid and un necessary,['android'] +487296,randomized svd for lsalsi on windows environment i am working on a project which includes the use of latent semantic analysis lsathis requires the usage of singular value decomposition svd sometimes on large data setsis there an implementation of randomizedsvd rsvd available for windowsvisual studio environment i saw a project called redsvd but it seems that it is supported on linux only,['c#'] +487301,when to use kvo i have read many docs on kvo but i am still confused as to when to use itin case obja wants to monitor a certain property of objb like soselfobjb objb alloc initselfobjb addobserverself forkeypathaddress options0 contextnilso if objbs property changes and it can only be changed by self why not just do thisselfobjbproperty newvalueself dosomethingbasedonnewvalueofobjbnewpropertyinstead of voidobservevalueforkeypathnsstring keypath ofobjectidobject changensdictionary change contextvoid context ifkeypath address self dosomethingbasedonnewvalueofobjbnewproperty it may be useful when used with a singleton like selfobjb objb sharedinstance where properties may be changed by other objects is this the only use case,['objective-c'] +487329,error 1396 hy0 operation create user failed for usernamelocalhost identified by mypassword mistakenly i deleted my root user from my mysqluser tabledelete from mysqluser where userusernameto make same root user i am trying to fire below querycreate user usernamelocalhost identified by passwordi get error as error 1396 hy0 operation create user failed for usernamelocalhostas per this so answer i tried flush privileges but still i get same errorany idea what is going wrongansweri also had to delete the same from mysqldb tabledelete from mysqldb where userusernamethat is it,['mysql'] +487342,recognise an out of memory crash ios our apps are live on the app storei wish to recognise crashes of out of memory that some users are gettingi understand there is no way to 100 recognise an out of memory crashis there any way to recognise these crasheswith a pretty large probability by doing some logic in the applicationdidreceivememorywarning i am not talking about finding it in xcode during development time i am talking about code that will recognise the out of memory crash from actual users and will log something to file,"['iphone', 'ios']" +487350,locking files when building in visual studio 2010 hello there stackoverflowrecently when i have been programming in visual studio 2010 i have been getting the problem with vs locking the bindebugprojectnameexe file when trying to build and gives me the error below after trying to build the project 10 timesunable to copy file objx86debugtileengineexe to binx86debugtileengineexe the process cannot access the file binx86debugtileengineexe becuase it is being used by another processthe problem appears when i edit the source and then try to debugi have checked using different programs and the only program using the file is visual studioif i wait for about 10 minutes before trying to build it seems to work properly but when trying different things it is not good needing to wait 10 minutes before trying somethingi have tried different solutions both on this site as well as everywhere i can find on googlesome solutions i have found but have not worked for mesolution 1 using a prebuild scriptin some different questions here on stackoverflow i have found one solution being that you go into project properties build events and then in the prebuild event command line addif exist targetpathlocked del targetpathlockedif not exist targetpathlocked move targetpath targetpathlockedthis made it possible for me to build the project one more time than i usually could but when editing the code again and then building the same error appearednote trying to build a release instead of a debug build seems to break the prebuild script and it exits with the code 1 which seems to make vs unable to build properly removing the prebuild script makes it work like normal again still with the same error thoughsolution 2 running visual studio as administratorthis is another solution i have found but havent worked either for me so i assume that visual studio already have all the permissions required and running as administrator does not actually make any differencesolution 3 changing the assemblyversionin this question visual studio build fails unable to copy exefile from objdebug to bindebug i found another solution that included changing the assemblyversion in the propertiesassemblyinfocs file to 20this however have not made any difference whatsoever for mesolution 4 closing usercontrol designers before buildingaccording to some different answers here and there on the internet visual studio apparently uses the built project executable to render the usercontrol designer in my case this is probably not it though since i use xna mostly and it does not use the usercontrol designersolution 5 cleaning up resources when application quitsthis might be a solution that i have failed to implement properly i am just thinking though that if this is the solution how come i have not been required to do it before i assume xna unloads everything that gets loaded through the content pipeline therefore this solution wouldnt make any real senseif there is anyone that is able to spread some light on this issue it would be really awesome as it is stopping me from programming anything really because i do not like waiting for 10 minutes because i have made a 2 second change all the time,['c#'] +487397,is it possible to cache custom sql queries in rails in the home controller of my rails 4 app i perform a custom sql query and save the results to an instance variablestudentscoring activerecordbaseconnectionexecute sql string studenti then after setting caching to true in config development configaction controllerperform caching true and restarting the application set up caching around the relevant variable in the view cache studentscoring do for lawyer in studentscoring div claspan2 div classrow tiny gravatar for lawyername lawyeremail div code ommitted div end end refreshing the browser three times shows that the query is run three separate times and the last run of the query actually takes 7ms longer than the first so i am assuming caching is not working or i am not doing it correctly can you tell me what i am doing wrongnot being an expert by any standards i do not understand how caching can be triggered from the view with the cache do syntax since by the time the view is loading have not the controller queries already been run therefore it is too late to tell rails to use a cached copyfrom the server logsfirst 11ms with cte scoring as select usersid usersname usersemail select coalescesumvalue0 from answer votes where answer votesuser id usersid and created at current date interval 7 day select coalescesumvalue0 from best answers where best answersuser id usersid and created at current date interval 7 day select coalescesumvalue0 from contributions where contributionsuser id usersid and created at current date interval 7 day total score from users where usersstudent true select id name email total scorefrom cte scoringorder by total score desclimit 5 3rd 18ms with cte scoring as select usersid usersname usersemail select coalescesumvalue0 from answer votes where answer votesuser id usersid and created at current date interval 7 day select coalescesumvalue0 from best answers where best answersuser id usersid and created at current date interval 7 day select coalescesumvalue0 from contributions where contributionsuser id usersid and created at current date interval 7 day total score from users where usersstudent true select id name email total scorefrom cte scoringorder by total score desclimit 5 updatethe logs show that it is reading a fragment after the queries above are run so why would the queries have different times and the later query be slower i would have thought the queries wouldnt be run at all if there was a fragment to read fromread fragment viewsid75nameretarded studentemailtotal score0id83namejim beamemailtotal score0id79nameweird studentemailtotal score0id80namevegetablestudentemailtotal score0c9638e467bfd0fbf5b619ab4182256 03ms,['ruby-on-rails'] +487439,railspostgres foreign keys stored in array to create 1many association can postgres arrays be used to create a onetomanyhas many association in rails 4 i am aware that a foreign key type array is not possibleexample a task has multiple assignees traditionally i would solve this using an association table tasksassigneesusers using arrays this would not be necessary as multiple foreign keys could be storedthe following query could then be used to get all tasks assigned to meselect from tasks where in tasksassignees,"['ruby-on-rails', 'ruby']" +487454,facebook sdk 30 callback fires twice i have the following activity and i am using facebooks loginbutton onsessionstatechange is being called multiple times i have an asynctask that i want to run after a successful login that also opens a new activity once complete right now this starts multiple async tasks how can i find the final state so it will not fire twice ive looked through all of the examples and facebook says that sessionisopened should work but its still firing multiple times updateafter removing the session code from onresume it only gets called once but according to i need that code in onresume for certain situationspublic class loginactivity extends sherlockactivity private static final string tag loginactivityprivate context contextprivate int statuscodeprivate string emailaddress nullprivate string password nullprivate graphuser fbuserprivate uilifecyclehelper uihelperprivate sessionstatuscallback callback new sessionstatuscallback override public void callsession session sessionstate state exception exception onsessionstatechangesession state exception called when the activity is first created overridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity login context getapplicationcontext uihelper new uilifecyclehelperthis callback uihelperoncreatesavedinstancestate final loginbutton fbbtn loginbutton findviewbyidridfacebook login fbbtnsetreadpermissionsarraysaslistbasic info email fbbtnsetonclicklistenernew viewonclicklistener override public void onclickview v intent intent new intentcontext mainactivityclass startactivityintent finish overrideprotected void onpause superonpause uihelperonpauseoverrideprotected void ondestroy superondestroy uihelperondestroyoverrideprotected void onresume superonresume for scenarios where the main activity is launched and user session is not null the session state change notification may not be triggered trigger it if it is openclosed session session sessiongetactivesession if session null sessionisopened sessionisclosed onsessionstatechangesession sessiongetstate null uihelperonresumeoverridepublic void onsaveinstancestatebundle outstate superonsaveinstancestateoutstate uihelperonsaveinstancestateoutstateoverridepublic void onactivityresultint requestcode int resultcode intent data superonactivityresultrequestcode resultcode data logdfblogin result code is resultcode uihelperonactivityresultrequestcode resultcode dataprivate void onsessionstatechangesession session sessionstate state exception exception if session null sessionisopened logitag logged in logitag access token sessiongetaccesstoken if state sessionstateopened requestexecutemerequestasyncsession new requestgraphusercallback override public void oncompletedgraphuser user response response if user null logitag user id usergetid logitag email userasmapgetemail fbuser user fbregistertask fbreg new fbregistertaskloginactivitythis user fbregexecute finish else if sessionisclosed logitag logged out,['android'] +487509,keep action bar stable during activity transition animation i am using the action bar in my android application and i am using sliding animation during activity transition by callingstartactivityforresulti all okoverridependingtransitionranimslide in ranimslide outwhere in my xml files i have the following codeset xmlnsandroid translate androidfromxdelta100p androidtoxdelta0 androidduration400 setandset xmlnsandroid translate androidfromxdelta0 androidtoxdelta100p androidduration400setthe animation is executed successfully but the slide also include the action baris there a way that the action bar will stay stable during the activity transition,['android'] +487519,why and how does evaluate to the letter i while reading this article posted on dzone i found a snippet of javascript originally posted on twitter by marcus lagergren the following code apparently prints the string failthis involves implicit type casting and i am trying to understand how exactly this line is interpretedi have isolated each character prints f prints a prints i prints li have also managed to break down the expressions returning each letter apart from iletter f an empty array is an object which according to ecmascript documentation point 92 evaluates to true when converted to a boolean so this is falsefalse as per point 1161 both arguments of the binary operator get converted to string therefore we get false which evaluates false a unary plus operator causes a tonumber conversion followed by a toprimitive conversion if the argument is an object the result of such conversion is determined by calling the defaultvalue internal method of the object in case of an empty array it defaults to 0ecmascript documentation sections 1146 93 91 false0 were accessing the character at index 0 hence the fletter asame story the only difference here are additional conversions in the part in square brackets which evaluates to a number to point at another character in the string false triggered by the use of unary and operators evaluates to 0 as explained above0 evaluates to true as defined in section 92 and section 1149 first 0 is converted to a boolean false and then the operator inverts the valuetrue again the unary plus triggers a tonumber conversion which returns a 1 for binary truesection 1146 and 93false1 returns the second character in the string which is aletter l evaluates to true as explained abovetruetrue using the binary on primitives triggers a tonumber conversion in case of true its result is 1 and 11 equals 2false2 self explanatoryletter iwhat leaves me stumped is the letter i i can see that the second part in square brackets evaluates to the string 10 and that the first part in parentheses returns falseundefined but i cannot make heads or tails of how this is happening could someone explain it step by step especially the magic that happens with square brackets arrays and array accessif possible i would like each step to contain a link to the underlying ecmascript ruleswhat i find the most cryptic is this part,['javascript'] +487540,are nested tryexcept blocks in python a good programming practice i am writing my own container which needs to give access to a dictionary inside by attribute calls the typical use of the container would be like thistemp container dictcontainerdict containerfoo barprint dict containerfooi know that it might be stupid to write something like this but that is the functionality i need to provide i was thinking about implementing this in a following waydef getattribute self item try return object getattribute item except attributeerror try return selfdictitem except keyerror print the object does not have such attributei am not sure whether nested tryexcept blocks are a good practice so another way would be to use hasattr and has keydef getattribute self item if hasattrself item return object getattribute item else if selfdicthas keyitem return selfdictitem else raise attributeerrorsome customised erroror to use one of them and one try catch block like thisdef getattribute self item if hasattrself item return object getattribute item else try return selfdictitem except keyerror raise attributeerrorsome customised errorwhich option is most pythonic and elegant,['python'] +487551,nodejs mysql needing persistent connection i need a persistent mysql connection for my node web app the problem is that this happens about a few times a dayerror connection lost the server closed the connectionat protocolend varwnnode modulesmysqllibprotocolprotocoljs7313at socketonend streamjs7910at socketeventemitteremit eventsjs11720at stream readablejs89516at process tickcallback nodejs41513error forever detected script exited with code 8error forever restarting script for 2 timeinfo socketio startedhere is my connection code yes i know multiplestatements can be dangerous in the wrong handsvar sql mysqlcreateconnection host localhost user my username password my password database my database multiplestatements truesqlconnectfunction handlethisconnectconnection connectiononerror functionerr if errfatal return if errcode protocol connection lost throw err consolelogreconnecting lost connection errstack sql mysqlcreateconnectionconnectionconfig handlethisconnectsql sqlconnect handlethisconnectsqlas you can see the handlethisconnect code does not work,['mysql'] +487558,how can i prevent zombie child processes i am writing a server that uses fork to spawn handlers for client connections the server does not need to know about what happens to the forked processes a they work on their own and when they are done they should just die instead of becoming zombies what is an easy way to accomplish this,['c'] +487592,mongodb vs mysql why one is better than another in some aspects i am really new to database and am interested in some high level basic knowledge i have read this wonderful so post i under one is better than another in some cases but not sure why why is mysql faster than mongodb at join operations why does mongodb scale better in thistributed system why is mongodb faster if i am just selecting a bunch of tables and putting all the objects together aka what most people do in a web app thanks a lot,"['mysql', 'sql']" +487637,asynchronous logging right now in my applicationat certain points we are logging some heavy stuff into the log filesbasically only for logging we are creating json of the data available and then logging into log filesthis is business requirement to log data in json format now creating json from the data available and then logging to file takes lot of time and impacts the original request return timenow idea is to improve the sitation one of the things that we have thiscussed is to create a thread pool usingexecutorsnewsinglethreadexecutor in our code and then submitting the task to it which does the conversion of data into json and subsequent loggingis it a good approach to do this as we are managing the thread pool itself is it going to create some issuesi would appreciate if someone can share better solutionssomeway to use log4j for this i tried to use asyncappender but didnt achieve any desired resultwe are using ejb 3jboss 50log4jjava6,['java'] +487678,how to do multicolumn header multi layer header in slickgrid i am using slickgrid to thisplay an editable tablelike this one the one on the right but seems currently slickgrid does not support thishow can this be donethank you,"['javascript', 'html']" +487702,thiscussion on generic numeric type in c i wonder if there is a way in c to have a type based on a primitive type and duplicate it to use other primitives insteadi know it is not very clear i do not really know how to explain this and english is not my mothertongue sorry for that so i will try to explain it using pseudocodea quick examplepublic struct vector2d public double x public double y arithmetic methods length normalize rotate operators overloads etcthe problem is that i would like to have a float and a int32 version of this typewhat i am doing actually valid c codethis type contains all useful methodspublic struct vector2d public float x public float y public vector2f asfloat return new vector2ffloatx floaty public vector2f asinteger return new vector2iintx inty arithmetic methodsthese types are only here to be casted fromto all the arithmetics methods are on the doublebased typepublic struct vector2f public float x public float y public vector2f asdouble return new vector2dx y public vector2f asinteger return new vector2iintx inty public struct vector2i public int x public int y public vector2f asfloat return new vector2fx y public vector2f asdouble return new vector2dx y it works but it is not sexy and in case of extensive casts using the asx methods there will inevitably be an impact on performancesideally i would have arithmetics methodes on all of three types but it would be a pain to maintainwhat would be the ideal solution pseudocode not valid cpublic struct vector2t where t numeric public t x public t y public t length return tmathsqrtx x y y other arithmetic methodsi know this is not possible in c for the moment but here is the true questiondo you have any idea on how to nicely and efficiently handle this what i have been thinking to pseudocode not valid c the type defined constant should be used by vector2body instead of plain typed double float etcpublic struct vector2d define type double import vector2bodypublic struct vector2f define type float import vector2bodypublic struct vector2i define type int import vector2bodythat way i wouldnt have duplicated code easier to maintainwaiting for your ideas ps if a moderator have ideas on how to better format my question feel free to edit it,['c#'] +487788,progress bar with apc and codeigniter trouble with ie and chrome i am trying to make a progress bar with codeigniter and apcheres my form form methodpost action idupload file enctypemultipartformdata targetresult frameinput typehidden valuephp echo uniqid idprogress key nameapc upload progress plabel foruserfileseacuteleacutectionnez un fichierlabelbr input typefile nameuserfile iduserfile size20 nbspbutton classbtn btnprimary typesubmit namesubmit idsubmit valuesubmitspan classiconuploadspannbspvaliderbuttonp when the user hits the submit button it fires the upload process here is my checkprogress function function checkprogress ajax type post url fbe uploadindexphpfbeuploadupload progress async true datatype json data session unid progress keyval success success functiondata progress liveprogress dataprogress progress bar progressbar idrowattrclass progress progrestriped active progressbar idrow divbarcsswidth parseintliveprogress tdpc idrowhtmlparseintliveprogress teacuteleacutechargeacutes end success error error function erreur alerterror ajax end progress 100if liveprogress 100 call function again settimeoutcheckprogress 800elseelse if liveprogress 100 progress bar progressbar idrowattrclass progress progrestriped active progressbar idrow divbarcsswidth 100 tdpc idrowhtml100 teacuteleacutechargeacutes message tdfilename idrowhtmlifinalisation en coursi this function manage the end of the upload process message buttons settimeoutendupload 4800 else end else settimeoutcheckprogress 1200checkprogress endand here is my php file function upload progress keykey upload postsession unidstatus apc fetchkeyprogresscal ceilstatuscurrent statustotal 100echo json encodearrayprogress calso when the user clicks on submit his file is uploaded i used this to write my upload function and the function checkprogress is called after 15 swith firefox everything works fine i have got the right values and the progress bar behaves like i want with ie and chrome it does not work properly for the progress value ie always returns 420 and chrome 410 so it is like the upload process is already finished but it is not by the way these values aado not correspond to the size of the file or something else i do not understand how it is possible that firefox computes and returns the right value and not the other browserswith firefox array total 791309142 current 113631842 filename uprar name userfile done 0 start time 13708646359486with chrome array total 410 current 410 rate 227015099338 filename name userfile cancel upload 4 done 1 start time 13708644083726in my phpini i have this extensionphp apcdllapcapcenabled 1apcmax file size 50mapcrfc1867 onapcmmap file mask cwamptmpfile template stmpapcshm segments 1apcshm size 64mapcstat1does anybody have a suggestion it will be much appreciatedthanks,['javascript'] +487826,jaxb xmladapter map list adapter marshall only i have a mapstring stringthe first idea everyone has is to convert it to a listpairstringstring pair being a custom classi have tried a xmladapter like thispublic class mappropertiesadapter extends xmladapterlistproperty mapstringstring but eclipse moxy the jaxb impl i use ended up with a classcastexception cannot convert hashmap to collectionis this conversion supported by jaxb or did i overlook some documentation part which explains why it is notpsi wanted to get xml like thisproperties property nameprotocol property namemarshaller property nameunmarshaller property nametimeout propertiesi got it only had to use an intermediate class also described athandle npe in xmlcompositeobjectmappingnodevaluemarshalsinglevalue xmlcompositeobjectmappingnodevaluejava161,['java'] +487852,find the type of boost python object i have been embedding python into c and i would like to know if there is a way to find thetype of the boostpythonobject which is a result after executing a function of a python module i have my code like thisboostpythonobject module boostpythonimportlibnameboostpythonobject result module attrfunctionnamearg1 arg2suppose if the result is intint a boostpythonextractintresult from the above code snippet what i would like to know is if there is way to find the typeof the result before extracting it in the above code the result might be any type like list tuple,"['c++', 'python']" +487870,h264 video encoder in javascript i am looking to make a video encoder entirely in javascript the idea is that the user will be able to specify an existing video easy enough or a range of images and then be able to encode it to h264 for publishing i understand that encoding content is not supported right now but i was wondering if this is something that is possible entirely in javascript or a flash bridge or notthanks,['javascript'] +487882,override compareto what to do with null case what should be returned in a compareto method when the given object is nullthe msdn library shows a example where 1 is returned but i would have expected to throw an error because comparing to null is not possiblei expect different opinions to this answer what could be a best practice approach,['c#'] +487891,make string first letter capital in java as of now i am using this code to make my first letter in a string capitalstring output inputsubstring0 1touppercase inputsubstring1this seems very dirty to me is there any direct or elegant way,['java'] +487924,c datagridview column order in my application i have a datagridview which it is data source varies depening on the button you clickeg clicking total downloads it will bedatagridview1datasource totaldownloadsor the downloads per playerdatagridview1datasource playerdownloadseach method obtains data via sql query and returns a datatable of this informationhowever with my following codedatagridview1datasourcegetstatspublic datatable getstats datatable table1 new datatabletotals table1columnsaddpark name table1columnsaddauthor table1columnsaddtotal downloads table1columns2datatype typeofint table1columnsaddrating max 5 table1columns3datatype typeoffloat table1rowsaddnameauthordownload rating return table1 i expected to see the colums in the order park name author total downloads ratinghowever they come in downloads park name author ratingi have read that adding datagridview1autogeneratecolumns falsewill fix thishowever this makes no difference to the order at allthanks for the help,['c#'] +487945,using a private class in place of a field performancememory penalty i am reviewing someones code and came across this private classclass customtype dictionaryint someothercustomtype this is empty nothing omitted herecustomtype is then used all over the parent class this is neat of course since customtype is shorter thandictionaryint someothercustomtypemy question is what are the performancememory implications of having an inner class just for a shortcut in a performance sensitive application does this contribute even slightly to higher memory andor cpu usage,"['c#', '.net']" +487966,qt5 c qgraphicsview images do not fit view frame i am working on program which shows user some picture that is selected by him but there is a problem because i would like to fit this picture in qgraphicsviews frame and the picture is really smaller than the frameso heres my codeimage new qimagedataabsolutefilepath variable data is defined when calling this methodscn new qgraphicsscenethis object defined in headeruigraphicsviewsetscenescnscnaddpixmapqpixmapfromimageimageuigraphicsviewfitinviewscnitemsboundingrectqtkeepaspectratioi was trying a lot of solutions that i found on web but no one did not help me the picture is in size around 40 x 60 px when the frame is 200 x 400 px what could be wronghere is some example of what is produced with code above and what i want to get out,['c++'] +487992,mockito different behavior on subsequent calls to a void method i have got a save method that returns a void something likepublic void save mything throws savefailureexception the call to save has retry logic to handle the exception and i want to test it by mocking out the first call to save throwing an exception and the second call succeedingmockito has a nice way of handling successive behavior for non void methodswhen mocksave thenthrow thenreturn how do i do the same with methods that have return a void,['java'] +488000,thisplay goodlooking math formula in android it is sad to see that science and math is never given enough attention in android platform maybe this is an easy problem but i am a total dude in javascript so i am struggling to understand how to solve this problemwhat i want to do is simple i just need to use render mathematic equation it can be mathjax or jqmath or anything that is small and fast if i have to do it in a webview how can i show plain text in paragraph and formatted equation within the same webviewanyone comes out with other methods which obviously works i will consider that as solution alsowhat i have done so fari started with using mathjax to put formula into webview i dunno if there is any successful jqmath use case out there anyone care to share their experience i can reproduce all the functionalities just like that of the standalone mathjax app in that app a user keys in a string into edittext field and mathjax will render the formula in latex once user presses a button to confirmi do not need user to confirm i thought this should be easier because there is no userinteraction but somehow the equation never gets thisplayed i know i must be missing something because the codes in the standalone mathjax is meant for user input which part of the code should i modify to directly render an equation from a string say sqrtb24ac here is the initial header for webviewwebview w webview findviewbyidridwebviewwgetsettingssetjavascriptenabledtruewgetsettingssetbuiltinzoomcontrolstruewloaddatawithbaseurlhttpbar script typetextxmathjaxconfig mathjaxhubconfig showmathmenu false jax inputtexoutputhtmlcss extensions tex2jaxjs tex extensions amsmathjsamssymbolsjs noerrorsjsnoundefinedjs script script typetextjavascript srcfileandroid assetmathjaxmathjaxjs scriptspan idmathspantexthtmlutf8and here is how the original webview loads when user presses a button after input to edittextwebview w webview findviewbyidridwebviewedittext e edittext findviewbyidrideditwloadurljavascriptdocumentgetelementbyidmathinnerhtml doubleescapetexegettexttostring wloadurljavascriptmathjaxhubqueuetypesetmathjaxhubprivate static string doubleescapetexstring s string t for int i0 i slength i if scharati t if scharati n t scharati if scharati t return ti attempted to replace with a hardcoded string wloadurljavascriptdocumentgetelementbyidmathinnerhtml doubleescapetexsample string but it does not work the text sample string would not even show up in the webviewsolution see joes answer to elaborate on his answer this is an example on how to set a sentence in plain text and then thisplay a formatted equation in thisplay form all in a single webviewreplace the last line above atscriptspan idmathspantexthtmlutf8withscriptspan idtextthis is plain textspan span idmathspan texthtml utf8 then callwsetwebviewclientnew webviewclient override public void onpagefinishedwebview view string url superonpagefinishedview url if urlstartswithhttpbar return wloadurljavascriptdocumentgetelementbyidmathinnerhtml doubleescapetexsqrtb24ac wloadurljavascriptmathjaxhubqueuetypesetmathjaxhub this will set a string this is plain text in normal font and centerthisplay the formula in webviewedit android 44 issuestarting with android kitkat you have to replace all the lines loadurl with evaluatejavascript but this is only available for kitkat api 19 or above so you need to do an sdk version check first for exampleif androidosbuildversionsdk int 19 wloadurljavascriptmathjaxhubqueuetypesetmathjaxhub else wevaluatejavascriptjavascriptmathjaxhubqueuetypesetmathjaxhubnullupdate as of mathjax 25because there are folders changes previous code would not work on latest version of mathjax besides the recommended way to minimalize the size of local mathjax is now using grunt the template to reduce size of mathjax can be found hereassuming you have successfully reduced the size of mathjax and assuming output of htmlcss here is a simple version that can load mathjaxoverridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain final webview w webview findviewbyidridwebview wgetsettingssetjavascriptenabledtrue wgetsettingssetbuiltinzoomcontrolstrue string url style script typetextxmathjaxconfig mathjaxhubconfig showmathmenu false jax inputtexoutputhtmlcss outputcommonhtml extensions tex2jaxjsmathmenujsmathzoomjs chtmlpreviewjs tex2jax inlinemath processescapes true tex extensionsamsmathjsamssymbolsjs noundefinedjs script script typetextjavascript srcfileandroid assetmathjaxmathjaxjs script p stylelineheight15 padding 16 16 alignjustify span demo thisplay equation url this is a thisplay equation pfracfa url this is also an identical thisplay equation with different formatpfracfa equations aligned at equal sign url you can also put aligned equations just like latex string align beginaligned f p times a 40 times 02 800 textnendaligned url align url this is an inline equation sqrtb24ac finally must enclose the brackets url spanp mwebviewloaddatawithbaseurlhttpbar url texthtml utf8 mwebviewsetwebviewclientnew webviewclient override public void onpagefinishedwebview view string url superonpagefinishedview url if urlstartswithhttpbar return if buildversionsdk int buildversion codeskitkat viewloadurljavascript else viewevaluatejavascriptjavascript null unlike joess answer there is no need to separate text or math types mathjax will just format them accordinglyhowever it appears that there is a bug that webview in kitkat devices cannot render capital letter a anyone who knows a way is welcome to provide a workaround for this,"['javascript', 'android']" +488054,php traversable type hint i have a relatively simple function which uses a foreachfunction foot result foreacht as val result dosomethingresult val return resulti would like to type hint and traverable seems to be the exact type hint i need function footraversable t however this gives a e recoverable error when using an array which is ofcourse usable in a foreach example argument 1 passed to foo must implement interface traversable array givenis there a way to type hint or is this not possible,['php'] +488056,could not execute build using gradle thistribution there is a error in the android studio if the project is builtthe error in the android studiogradle der befehl cprogram ist entweder falsch geschrieben oderkonnte nicht gefunden werdenfailure build failed with an exception what went wrongexecution failed for task myapplicationdexdebug running cusersmichaelappdatalocalandroidandroidstudiosdkbuildtoolsandroid422dxbat failed see output tryrun with stacktrace option to get the stack trace run with info or debug option to get more log outputthe output in the command window for gradlew compiledebug stacktrace isthe taskcontaineradd method has been deprecated and is scheduled to be removed in gradle 20 please use the create method insteadmyapplicationpreparedebugdependenciesmyapplicationcompiledebugaidl uptodatemyapplicationgeneratedebugbuildconfig uptodatemyapplicationmergedebugassets uptodatemyapplicationcompiledebugrenderscript uptodatemyapplicationmergedebugresources uptodatemyapplicationprocessdebugmanifest uptodatemyapplicationprocessdebugresources uptodatemyapplicationcompiledebug uptodatebuild successfultotal time 27437 secsthe output for the command gradlew clean build isthe taskcontaineradd method has been deprecated and is scheduled to be removed in gradle 20 please use the create method insteadmyapplicationcleanmyapplicationpreparedebugdependenciesmyapplicationcompiledebugaidlmyapplicationgeneratedebugbuildconfigmyapplicationmergedebugassetsmyapplicationcompiledebugrenderscriptmyapplicationmergedebugresourcesmyapplicationprocessdebugmanifestmyapplicationprocessdebugresourcesmyapplicationcompiledebugmyapplicationdexdebugder befehl cprogram ist entweder falsch geschrieben oderkonnte nicht gefunden werdenmyapplicationdexdebug failedfailure build failed with an exception what went wrongexecution failed for task myapplicationdexdebug running cusersmichaelappdatalocalandroidandroidstudiosdkbuildtoolsandroid422dxbat failed see output tryrun with stacktrace option to get the stack trace run with info or debugoption to get more log outputbuild failedtotal time 33459 secscusersmichaelandroidstudioprojectsmyapplicationprojectanyone an idea,['android'] +488074,how to make a variadic is same how can i make a class template that returns whether any of its variadic types are equal to the first type i want to be able to do thisis samet a b cvalue true if t is one of a b or cand if t is equal to any one of those types its static value member will be true otherwise false how can i do this,['c++'] +488099,clear data inside text file in c i am programming on c in my code i create a text file write data to the file and reading from the file using stream after i finish the sequence i desire i wish to clear all the data inside the txt file can someone tell me the command to clear the data in the txt file thank you,['c++'] +488100,can anyone give me an example for phps curlfile class i had a very simple php code to upload a file to a remote server the way i was doing it as has been suggested here in some other solutions is to use curl to upload the file heres my codech curl init curl setoptch curlopt returntransfer truecurl setoptch curlopt post truecurl setoptch curlopt postfields arrayfileupload filesfiledatatmp name echo curl execch the server is running php 550 and it appears that filename has been deprecated in php 550 as stated here under the curlopt postfields description and therefore i am getting this errordeprecated curl setopt the usage of the filename api for file uploading is deprecated please use the curlfile class instead in interestingly there is absolutely nothing about this class on phpnet aside from a basic class overview no examples no description of methods or properties it is basically blank here i understand that is a brand new class with little to no documentation and very little realworld use which is why practically nothing relevant is coming up in searches on google or here on stackoverflow on this classi am wondering if there is anyone who has used this curlfile class and can possibly help me or give me an example as to using it in place of filename in my codeediti wanted to add my uploadphp code as well this code would work with the traditional filename method but is no longer working with the curlfile class codefolder trypath folder basename filesfiletmp name ifmove uploaded file filesfiletmp name path echo the file basename filesfiletmp name has been uploadedfinal editwanted to add final working code for others looking for similar working example of the scarcelydocumented curlfile class curlphp local serverform actionphp echo serverphp self methodpost enctypemultipartformdatalabel forfilefilenamelabel input typefile namefiledata idfiledata br input typesubmit namesubmit valuesubmit formphpif postsubmit uploaddir uploads realtitleid filesfiledataname ch curl init curl setoptch curlopt returntransfer true curl setoptch curlopt post 1 curl setoptch curlopt returntransfer true argsfile new curlfile filesfiledatatmp namefileexgpdrealtitleid curl setoptch curlopt postfields args result curl execch uploadphp remote serverfolder trypath folder filesfilename ifmove uploaded file filesfiletmp name path echo the file basename filesfilename has been uploaded,['php'] +488132,how to simulate hardware media control buttons on an android emulator android supports hardware play pause buttons on headsets and attached devices i am trying to find a way to test support for those devices on an emulator the android documentation talks about how to add support for hardware playback controls but unfortunately i cannot find documentation of how to emulate them thanks,['android'] +488181,play 21 ssl configuration i am new to play and in the process of configuring ssl for production i can successfully run in dev mode with a self signed certificate but when i try to use a signed certificate the initial client handshake fails and play generates the following stack traceplay error loading https keystore from confkeystorejksjavasecuritynosuchalgorithmexception rsa keymanagerfactory not availableat sunsecurityjcagetinstancegetinstancegetinstancejava159 na170 11at javaxnetsslkeymanagerfactorygetinstancekeymanagerfactoryjava139 na170 11at playcoreservernettyserverplaypipelinefactoryanonfunsslcontext1applynettyserverscala74 play 210jar211at playcoreservernettyserverplaypipelinefactoryanonfunsslcontext1applynettyserverscala62 play 210jar211at scalaoptionmapoptionscala145 scalalibraryjarnaat playcoreservernettyserverplaypipelinefactorysslcontextlzycomputenettyserverscala62 play 210jar211i am running play 211 and java 170 11 i have configured ssl support as followsgenerate a csrkeytool certreq alias server keyalg rsa file servercsr keystore keystorejksload root and intermediate certskeytool import alias godaddy keystore keystorejks file gd bundlecrtload signed certkeytool import alias server keystore keystorejks file servercrtlaunch play with system parameters to run sslsudo jarsplay211play dhttpsport443 dhttpskeystoreconfkeystorejks dhttpskeystorepasswordredacted dhttpskeystorealgorithmrsa rundoes anyone know how javasecuritynosuchalgorithmexception rsa keymanagerfactory not available error,['java'] +488193,how to return an html document from java servlet this works to return a stringimport javaxservlethttpsuppresswarningsserialpublic class monkeyservlet extends httpservlet public void dogethttpservletrequest req httpservletresponse resp throws ioexception respsetcontenttypetextplain respgetwriterprintlngot this far but i cannot get it to return an html document this does not workimport javaxservlethttpsuppresswarningsserialpublic class blotservlet extends httpservlet public void dogethttpservletrequest req httpservletresponse resp throws ioexception respsetcontenttypetexthtml respgetwriterprintlnhtmlmypagehtml sorry for being noobediti already have the html in separate documents so i need to either return the document or readparse it somehow so i am not just retyping all the htmlediti have this in my webxmlservlet servletnamemonkeyservletname servletclasscomselfedumonkeyservletservletclass servlet servletmapping servletnamemonkeyservletname urlpatternmonkeyurlpattern servletmappingis there something else i can put in there so it just returns a file likeservletmapping servletnamemonkeyservletname filetoreturnblothtmlfiletoreturn servletmapping,['java'] +488217,java 8 extension methods why are they not called mixins or traits as far as i know groovy already has mixins scala has traits c family has multiple inheritance so why is the new functionality in java called extension methods is it just a different name for the same thing or was there another reason what are the differences from traits and mixins what do they add and what do they lackpersonaly i see them more as implementation methods than extension methods,['java'] +488226,converting jsonarray to arraylist i am downloading a json string and converting it to jsonarray im putting it into a listview and need to be able to delete from that listview later and since jsonarray has no remove method thanks obama i am trying to convert it to an arraylisthere is my json the arraytostringthumb urltb1370913834jpgevent id15count44event taglinethis is a taglineevent name5th birthdayevent end1370919600event start1370876400i need to get it into an array and be able to call the strings by their respective keys appreciate any help,['android'] +488273,newtonsoft json deserialize my json is as followst1339886atruedatatypeantsbiztroi found the newtonsoft jsonnet deserialize library for c i tried to use it as followobject jsonde jsonconvertdeserializeobjectjson how can i access to the jsonde object to get all the type data i tried it with a loop but it is not working because the object does not have an enumerator,['c#'] +488300,vertical regex matching in an ascii image note this is a question about possibilities of modern regex flavors it is not about the best way to solve this using other methods it is inspired by an earlier question but that one is not restricted to regexthe problemin an ascii imageartmapstring likexi would like to find a simple vertical line formation of three xsxthe number of lines is variable in the image and the width of each line is variable toothe questionswith regex pcrephp perl net or similar is it possible todetermine if such a formation existscount the number of such formationsmatch the starting point of them all 4 in the above example,"['php', '.net']" +488325,javascript function to rotate a base 64 image by x degrees and return new base64 i want a javascript function that will rotate a base64 image by x degrees and return the new base64 imageexample i wish to call a function with something likevar newimg rotateimgimagedata 90 which should return a base64 string of the original image rotated 90 degreessample base64 image string at the bottomideally the function will be backwards compatible with non html5 browsers but pure canvas solutions are welcome for simplicityi have been battling with this for daysi understand that the solution will probably be load an image object with the original string create a temp canvas object and context then rotate context then convert canvas back to image string but just can get it to work please helpsample image stringdataimagepngbase64ivborw0kggoansuheugaciabbcamacdyyeabgdbtueaalgpcxhbqawbqtfrfpi8jl5fin5v0paijnzafjiiavshnlpabcnb6ih0xz2z4gh6bnjm2pashu7nvoqgdoi8prdwnnz40vrl4qjtgpqkng3projbl8ujpj08njecnckqhwgg5erh0q2rxcnkyyct8pob391vrtaerqzsqsqz8xsaba38svgxu0ji6spkkudlplk4vefxacjid2ufbmo5tc5bwcdx6nojtzwlikkyavmi5fu61gfnlmjn4y39gpexjvly99gyknb19afnli186st58t0cupv09azb8fx1wnjqdp5s3dgthmzhlgrcex8fk4tzspoysdnnxpkbxko51tkrg5d6ig4b1181vx2bgfxeqwfe8w1ddiyuvdg5l5nqyraqza2lmamppy15agh5shyn8d3nocg1fexhya15bry6847fpepewjv0e28ztw76ktxb3cpm3nvakpkecvsjjoukxgkj9io7eznnqgts69tf3pt9votvyy9d46uwvhx0mzm6hv6ammzjh8uws5t6jywd78e2rveqq7qzcq9jsrcy7dlnvapziqpmw1rki7evzxrgm7u4ih24lg30uyl0krp5hnpqi0sdhzkem3twej4tp7uie69dy3mekxsb62zz8jrkjbwfdzxlpfua0otsm9ib5olb0bo0d7cxq8h8t4dsk9sbgii7nklmqlh4mmlpzgmvcqodhvj4ly4xnjiu1c99iim0ziuamvlpuenp15wvbfjisreye9dqftkk6rea3nju5s5oimy5jag0bafdwcqpwn7s8fwvlxyaehe2fhqpmysgqevamh8voccyou1ns18ayvq72aew4dypugdhqzamxwhhkz5c4ee5dashbamyavnpskpmgrcfh9vmat9yblsdyzaly0yvqcjyunjfawmlojk5qebguakcugfsa0bjcegih4eab9oa9wa1h7cggagd0uk5t4vlqwedsx83xzcxoynrzxll4netbrkmvhl8f38vh9vv7v3vs2jmryxxktd5cn8p7vylkbv9gmvnpvvpj5ktds398jk8mf7ef7rqhlir9ftmvij8icq8damxyifiazysurbvejhhdyhubnzgabg568fmdx7avrkyekgaik0osuasiqksmevfccwcgcgkqvgic9sqxrpownidcvikuakcsn3djclnufmtob2cl88v7fv3vv108n9j0cithou1dqrhy2odxx2d4kxtluypwietls1lywkn4rgdct1jsmigqytcwoufex2pyjla7xwsvjaunwwrmyjzdfx3dzm1d3ldveklwxb6cjir2gakon3zn0adb1zx1ryknlm3wsp8nbdu1ftfnipps7ufet37o7sxk2n5d3syq9ksjdivyi98uy7tqorhdm58nrt7s3uaixxwvvukkyi4k9lopijgtj812pdnyywcbpuer5it92e0resft5uk8txyh4s4nphci2uvj7pbmpeqmeirgd6twkpvnbc6xcdnawlfrnpny54id0vlzq1hbrfiqyfwuetwafzom8x27yzzpv7qqopcyseyujasaoo8qopimc588afz8f2ryvrdbxw4dozfgvuykuehqvhlgdu1khi5zzlywxcqw1lxjwiyq0pz7xclylaiykgz1d4daad1kft63mqlcwsby8x9lz3ymgdi4eckxrjcpgtpjmquxpmktzrpbierpup9twoostkdxssippzc7x5gcpyy68paypbpwhspk4qjaj7z4tlxxehm8ce1ptdfzxccg9u17kk6phbnnutk43ioztybz5kdazoq9iaeubr1k0jzr5ikrylnmatizjtmiiv0jadnbz06anbvabl6wjwsa0ptomwcg7sllowwbjolsir7dcsd37r3t41mgegozc7kqgcwgp0cx42q4le0c0flfwnlb0anvvuozoofwmojmnecsn96guepsghsy1nfytkgxodu11wawlq1uovtrjfikhlrxg23hr5ubt1lvqunukt7spvy8qrqrmyxwakksw3rtfdije7qudmhvpsf1bwvmzocn6aypnpaknvlwdcww9xqtsyqxynagbuvo4ffoqtkkigwqxntmbl5w5kqlcm4cedqhfhqenb1setwost0ijuarq0yont80dmh486fj0q9b292uvff8xt1lalxjhof7weuzadecquvewwtzuoeocjfczclmjujzpd86anvrc2nhbbujm5aqfq2oiabu9pzk1cymogtncirk7oakbhzuji6o9ndw1czqf8hsh5elkbdikthpcy5erbfi7zahcf0oekjpijnr6tjgq7narlmbcwg6nmgwmar5kzp43yedlitlyrzqoeayvnubgzmggtkfaornxhcds0y3qiihwghh4whjakz4nnq88sxci1uedhehgvxeqnvu1dbbsajgu6jg8xciliivmhoeq51zwqdoyxwgjtjbeqluacljy0ndz2pzmgdvhecifwmmv5cwqpn8tdptceskhpdw148jxwrdiyg9g77rtzyq21o49vs5x4ydaz7xranc8fewleppmzwvh4lgyskyjxow2q3dofmefnlp5hppxc642hw29mtozddg5acwuk6lroutpxoqcehbo6xhylz3pg1q2ebynfskzivlvfxl5eyyz2njgvdzfuhizo4jawdec4cwj3upkhh7llvtabftb28ruext7nedac6nkwftprtggcl2jo1ktyctjukmmlvlo4sekjwdyvea2szm7is6w3eywymeye3vspvtdaieqth571ejyoqa8wnee2jvbhja7aeith0loxafdpfwoveh8sxf3fxrod9zaog2l5in9vzklfiv7kjfgq80cvajdcdidszcic6neche3w9x5wr4vgd5uqzar949jvw1fndsrmjtuocynoo50piwtzwnzygom2hxpagq9v1thy6anicxikcdzabz7q1tddakrwufizuam9abl1d1a6uij1rpsnh6n2teah3p7lqw5abdfydwinjivgwyb9kokuztrext7nozniobkv5prntg0i6alro7b07bav9br4czaafwndobzi6vwtgosn2zyumup6siidhgwvro9ubny0xmye8vrtsbqyspgukfglhqfqetixnosbwghqbqwfzr0gvlu3bt2sjd9lodotvvlyw8hfxeyomkbjxzr4qkcbmh8rin8abof4kyptwasuvork5ciia,"['javascript', 'jquery']" +488378,android edittexttextbox auto capitalizing first letter of each word while user typing i know this question has asked several times but non of the answers worked in my casei found some of the same sort of questions and answers in the following links which did not work for me at alink1link2in my layout file i have defined my edittext as follows edittext androidididtest edittext androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentlefttrue androidlayout alignparenttoptrue androidlayout marginleft16dp androidlayout margintop90dp androidinputtypetextcapwords androidems10 also in the activity class in the oncreate method i have added the following code edittext testedittext edittext findviewbyidridtest edittext testedittextsetinputtypeinputtypetype class text inputtypetype text flag cap words if someone have experienced the same issue and solved it would like to hear what i have done wrong in my case thanks editsfollowing above explained steps i am unable to make this get it doneauto capitalizing the first letter of each word while user typingaccording to my code when user typing it thisplays first charater in all the words including first word in lower case,['android'] +488393,storing changes on entities is mysql the proper solution i want to store changes that i do on my entity table this should be like a log currently it is implemented with this table in mysqlcreate table entitychange id int11 unsigned not null auto increment entity id int10 unsigned not null entitytype enumstring 1string 2someboolsomedoublesometimestamp not null default string 1 when timestamp not null value text primary key id engineinnodb default charsetlatin1entity id the primary key of my entity tableentitytype the field that was changed in the entity table sometimes only one field is changed sometimes multiple one change one rowvalue the string representation of the new value of the fieldexample when changing field entitysomedouble from 3 to 2 i run those queriesupdate entity set somedouble 2 where entity id 123insert into entitychange entity identitytypevalue values 123somedouble2i need to select the changes of a specific entity and entitytype of the last 15 days for example the last changes with somedouble for entity id 123 within the last 15 daysnow there are two things that i thislikeall data is stored as text although most less than 1 is not really text in my case most values are double is this a big problemthe table is getting really really slow when inserting since the table already has 200 million rows currently my server load is up to 1015 because of thismy question how do i address those two bottlenecks i need to scalemy approaches would bestore it like this 2df9d0 click on browse store the changes in the entitychange table and then store the value according to its datatype in entitychange booltimestampdoublestringuse partitioning by hashentity id i thought of 50 partitions should i use another database system maybe mongodb,['mysql'] +488404,windows authentication does not works when i run project from visual studio windows authentication works good when i host my aspnet mvc project on iis but if i run it from visual studio it does not here is my webconfigauthentication modewindows authorization deny users authorizationam i missing something,"['asp.net', '.net']" +488426,python dump dict to json file i have a dict like thissample objectinterpolator 1629 pointinterpolator 1675 rectangleinterpolator 2042i cannot figure out how to dump the dict to a json file as showed below name interpolator children name objectinterpolator size 1629 name pointinterpolator size 1675 name rectangleinterpolator size 2042 is there a pythonic way to do this you may guess that i want to generate a d3 treemap,['python'] +488441,horizontally center zurb foundation top bar menu with multiline items vertically centered using foundation i am trying to adjust the topbar menu in order to have menu items looks something like thatparent container topbar topbarsection item item item item item item menu menu menu menu menu menu 01 02 03 04 05 06 topbarsection topbar ethis means thatitems have a fixed widthitems may have one or more lines usually no more than 3 lines but they must be alway vertically centeredall items height must be the same as the highest itemsubmenus dropdown must open below the hovered itemi have tried several option thisplay set to tablecell or inlineblock with vertical align set to middle and looked around the web but i cannot find a solution that meet all the requirements aboveanyone ever tried to do that,['css'] +488456,android actionbar menuitem lowercase i want to make menuitem title in the actionbar to lowercasemy menuxml item androidididregister androidtitleregister androidshowasactionifroomwithtext item androidididunregister androidtitleunregister androidshowasactionifroomwithtexton the actionbar it sees register and unregister but i want that it sees as register and unregisteris it possible to make first letter upper and next letters lower at menuitemand how i can do that,['android'] +488537,android paint how to get airbrush effect hi and thank you for your helpplease i am following the fingerpaint demo in the api demosplease i would need to get an airbrush effect in the sense that when i draw over the same spot it gets darker and darkerplease see the imageas you can see the center is darker because i passed with the paint on the same spot more than one timeplease how do i get the same effect of getting darker a spot if drawn over more than one timethank youedit edit editthe suggested mpaintsetalpha0x80 kind of work but only if i release touch and then touch again if i do not release and keep the finger on the screen the effect is not reachedthe point is that you do not reach the effect if you do not release your finger from the screen if you keep on drawing without releasing the touch it does not get darker when paint over if you release the touch and then draw again you get the effectthis is the result i get and i do not wantthis would be the desired resultthis is is the code taken form the api demospublic class fingerpaint extends activity overrideprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewnew myviewthis mpaint new paint mpaintsetantialiastrue mpaintsetdithertrue mpaintsetcolor0x44ff0 mpaintsetstylepaintstylestroke mpaintsetstrokejoinpaintjoinround mpaintsetstrokecappaintcapround mpaintsetstrokewidth12private paint mpaintpublic class myview extends view private static final float minp 025f private static final float maxp 075f private bitmap mbitmap private canvas mcanvas private path mpath private paint mbitmappaint public myviewcontext c superc mpath new path mbitmappaint new paintpaintdither flag override protected void onsizechangedint w int h int oldw int oldh superonsizechangedw h oldw oldh mbitmap bitmapcreatebitmapw h bitmapconfigargb 8 mcanvas new canvasmbitmap override protected void ondrawcanvas canvas canvasdrawcolor0xffa canvasdrawbitmapmbitmap 0 0 mbitmappaint canvasdrawpathmpath mpaint private float mx my private static final float touch tolerance 4 private void touch startfloat x float y mpathreset mpathmovetox y mx x my y private void touch movefloat x float y float dx mathabsx mx float dy mathabsy my if dx touch tolerance dy touch tolerance mpathquadtomx my x mx 2 y my 2 mx x my y private void touch up mpathlinetomx my commit the path to our offscreen mcanvasdrawpathmpath mpaint kill this so we do not double draw mpathreset override public boolean ontoucheventmotionevent event float x eventgetx float y eventgety switch eventgetaction case motioneventaction down touch startx y invalidate break case motioneventaction move touch movex y invalidate break case motioneventaction up touch up invalidate break return true,"['java', 'android']" +488544,how to label google column chart bars i am using google chart api to create chart for values which goes from 1 to millions problemthe bars which are representing smaller values ex less than 50 or so are invisible on graph and no way i can see what values correspond to certain xaxisthis would be solved if i can somehow print yaxis values on top of barsbut i could not find any mention in the api doc on how to do itthere is similar problem here but it does not answers my questionput labels on top of inside bar in google interactive bar chartthere are some other more than year old unanswered questions here i am hoping someone might have found a solution or a workaround by now that is why asking this question againgoogle visualization column chart simple question but cant find the answerhow to show values on the the top of columns google chart apican you show me how to achieve what i want using how can i customize this google bar chart,"['javascript', 'jquery']" +488598,c operator overloading why does the below c program output acca why is operator int called twiceinclude stdafxhinclude iostreamusing namespace stdclass base public baseint m var1im var couta basebase base coutb ibasei operator int coutc return i private int iint main base obj obj objobj return 0,['c++'] +488601,opsworks overriding databaseyml ignoring custom json when i deploy a rails app with opsworks a new databaseyml gets created in the shared directory it ignores the existing databaseyml which rightfully should not be in the repo and i have also tried specifying custom json but nothing works maybe i have the structure wrong deploy myappname database adapter mysql2 encoding unicode host xrdsamazonawscom port 3306 database dbname pool 5 username username password password,['ruby-on-rails'] +488687,bad file descriptor heroku foreman i am trying to run hellopy from this python heroku tutorial my problems began after running this command foreman start i got the following error even though i installed the heroku toolbeltforeman is not recognized as an internal or external command operable program or batch fileso i added the location of the foreman file version 0630 to my pathcprogram files x86herokuruby192binand restarted the command prompt and reran foreman start now i am getting this errormicrosoft windows version 629200c 2012 microsoft corporation all rights reservedcusersmedesktopcodeheroku python appvenvscriptsactivatevenv cusersmedesktopcodeheroku python appforeman startbad file descriptorcprogram files x86herokuruby192librubygems191gemsforeman0630libforemanenginerb372in read nonblockcprogram files x86herokuruby192librubygems191gemsforeman0630libforemanenginerb372in block 2 levels in watch for outputcprogram files x86herokuruby192librubygems191gemsforeman0630libforemanenginerb368in loopcprogram files x86herokuruby192librubygems191gemsforeman0630libforemanenginerb368in block in watch for output125738 web1 exited with code 1125738 system sending sigkill to all processesvenv cusersmedesktopcodeheroku python apphellopyimport osfrom flask import flaskapp flask name approutedef hello return hello worldprocfile web gunicorn helloappedit 1after reading this answer i did the followinggem uninstall foreman gem install foreman v 0610however when i reran foreman start i am getting this error nowvenv cusersmedesktopcodeheroku python appforeman start141320 web1 started with pid 252141320 web1 exited with code 1141320 system sending sigkill to all processes141320 traceback most recent call last141320 file cusersmedesktopcodeheroku python appvenvscriptsgunicornscriptpy line 9 in modulevenv cusersmedesktopcodeheroku python appany assistance will be really appreciated thanks in advance,['python'] +488699,webview would not scroll in android 2x i have a problem with the webview i am opening a webpage in this webview and it would not scroll in android 2x but it will scroll in android 3xany idea what can i do to fix thatthis is the configuration i use for this webviewwview webview findviewbyidridwebview1wviewgetsettingssetjavascriptenabledtruewviewsethorizontalscrollbarenabledtrueand in the layout linearlayout xmlnsandroid xmlnstools androidlayout widthmatch parent androidlayout heightmatch parent androidbackground0 toolscontextmainactivity androidorientationvertical webview androidididwebview1 androidlayout widthmatch parent androidlayout heightmatch parent androidscrollbarshorizontal linearlayout,"['java', 'android']" +488736,android viewpager with scrollviews with viewpagers inside the scrollviews so i have my activity which has a main viewpager and inside of the viewpager each page has the whole content as a scrollview and inside of that scrollview there is another viewpagerthis might sound crazy but basically the outer viewpager contains news articles and the articles are long so there is a scrollview and inside the scrollview there are multiple thumbnailspictures that they can swipe through as welli have tried a few different custom viewpagers with different touch event interception but cannot seem to get it perfect it either completely will absorb all touch events so that the vertical scrolling of the scrollview does not work in that area or it will be really touchydifficult to get the inner one to scroll horizontallyanyone have a perfect solution,['android'] +488741,why is mallocs pool called a heap can anyone explain why the pool of memory managed by malloc free is called a heapbased on 1 sadsntz1usgafqjcnhaqlotbbkkwyqxiiywn1146bwzfw doug leas explanation of how his malloc worksit is not obvious that the data structure which we call a heap is being used at alldo we call it a heap because it is common for malloc implementations to use bestfit selection of the memory chunk to return and that is historically been implemented using a minheap of chunks sorted by chunk size,['c'] +488748,ruby on rails could not find file jqueryui i have just done a fresh install and was able to access the default rails page at localhost30 but when i installed the activeadmin gem i had a problem when accessing admin and received the following error on adminlogin i was redirected but this is what i saw on the pagewhat do i do i have done bundle update and it is not fixed itheres the partial error messagesprocketsfilenotfound in active admindevisesessionsnewshowing usrlocalrvmgemsruby193p392gemsactiveadmin060appviewslayoutsactive admin logged outhtmlerb where line 12 raisedcould not find file jqueryui in usrlocalrvmgemsruby193p392gemsactiveadmin060appassetsjavascriptsactive adminbasejs2here is my gem filesource gem rails 3212 bundle edge rails instead gem rails git gitgithubcomrailsrailsgitgem sqlite3 gems used only for assets and not required in production environments by defaultgroup assets do gem sassrails 323 gem coffeerails 321 see for more supported runtimes gem therubyracer platforms ruby gem uglifier 103endgem jqueryrailsgem activeadmin to use activemodel has secure password gem bcryptruby 300 to use jbuilder templates for json gem jbuilder use unicorn as the app server gem unicorn deploy with capistrano gem capistrano to use debugger gem debugger,['ruby-on-rails'] +488759,cannot resolve symbol r in android studio in every instance in all of my classes where i reference ridsomething the r is in red and it says cannot resolve symbol r also every time there is rlayoutsomething it is underlined in red and says cannot resolve method setcontentview the project always builds fine it is annoying to see this all the time i have read many other questions on here about something similar but most involved importing projects from eclipse i am using what i believe to be the most recent version of android studio and the project was created with android studio and worked without any cannot resolve r problems i would like to know what causes this if anyone knowsupdatesolution at the time android studio was brand new and i was also a brand new developer i should never had been using android studio i never realized how unfinished it was thanks everyone for the support in trying to help since this has been posted ironically the actual answer to this question has been deleted and cannot be undeleted i feel that my original answer is the solution to this problem,['android'] +488761,set data type in mysql my knowledge of relational databases is more limited but is there a sql command that can be used to create a column that contains a set in each rowi am trying to create a table with 2 columns 1 for specific ids and a 2nd for sets that correspond to these idsi read abouthowever the set data type requires that you know what items may be in your set however i just want there to be a variablenumber list of items that do not repeat,['mysql'] +488766,java exception classes i am new to java and i was looking at exception handling when we catch java exceptions we declare and use an object of the exception class without initializing it iecatchnullpointerexception e eprintstacktraceso my question is how are we able to use object reference e without instantiating it,['java'] +488775,ice cube and recurring select gems and occurrences i am attempting to utilize the awesome functionality of ice cube and recurring select gems to handle recurring events i have got a schedule text column in my database and the following in the event model def schedulenew schedule write attributeschedule recurringselectdirty hash to rulenew scheduleto yaml end def converted schedule schedulefrom yamlselfschedule start date override selfstart date end looking at the schedule column in psql it appears to be storing the schedule correctly heres my formcontrolgroup flabel date class controllabel controls ftext field start date class datepickercontrolgroup flabel recurring class controllabel controls fselect recurring schedule allow blank truehowever when i attempt to output converted schedule it only shows the start date and would not show any additional dates i have a few suspicions that i have tinkered with no success perhaps the yaml is not being converted correctly for the converted schedule method perhaps i need an enddate i do not see where this functionality is available on recurring select,['ruby-on-rails'] +488809,how can i produce an effect similar to the ios 7 blur view i am trying to replicate this blurred background from apples publicly released ios 7 example screenthis question suggests applying a ci filter to the contents below but that is a whole different approach it is obvious that ios 7 does not capture the contents of the views below for many reasonsdoing some rough testing capturing a screenshot of the views below and applying a cigaussianblur filter with a large enough radius to mimic ios 7s blur style takes 12 seconds even on a simulatorthe ios 7 blur view is able to blur over dynamic views such as a video or animations with no noticeable lagcan anyone hypothesize what frameworks they could be using to create this effect and if it is possible to create a similar effect with current public apisedit from comment we do not exactly know how apple is doing it but are there any basic assumptions we can make we can assume they are using hardware right is the effect selfcontained in each view such that the effect does not actually know whats behind it or must based on how blurs work the contents behind the blur be taken into consideration if the contents behind the effect are relevant can we assume that apple is receiving a feed of the contents below and continuously rendering them with a blur,['ios'] +488851,how can i tell if a each call was aborted prematurely first some psuedopsuedocodesomeselectorlogiceachfunction if somelogicthis return false otherwise do stuff related to thissomemoreexcitingcodein this example were getting a collection of dom elements based on some selector logic then iterating over each one for each element were calling somelogic if that returns true we abort the each loop otherwise we perform some logic on the element and then move on to the next element once weve worked through all the elements we continue on and call somemoreexcitingcodei would like to know before calling somemoreexcitingcode whether or not the loop was aborted prematurely obviously you can do something like thisvar aborted falseeachfunction if somelogicthis aborted true return false but this feels sloppy to me like jquery should be providing me with this information in another way is there a more idiomatic way of achieving this that i do not know about,"['javascript', 'jquery']" +488880,how much optimized is vala generated c code over hand written c code is vala generated code are optimized like normal handwritten c code is there any performance overhead in using gobject system over not using itnote in my next c project i am researching over to use vala or not the project is not a gui application it is an interpreter kind of application which has to be platform independent i am using gcc as compiler,['c'] +488934,cc include formating best practice in my time with cc i have encountered different ways to handle the file path for the include directive when including your h file in your cppc file the google style guide alludes to using part of the file path in your include that being said i currently work on a project albeit a small one where a nicely laid out makefile for g and structure was laid out for me when i inherited the code namely there is a directory named project name and inside is the makefile and several subdirectories for example project nameinc holds the h files and project namesrc holds the cpp files the makefile is set to look into each subdirectory to compile the source codemy question is given the directory structure and the makefile what is the preferred method for include the two alternatives i am successful with using are listed belowinclude mycodeh no knowledge of path assumes structure that i describedinclude project nameincmycodeh seems a bit convoluted but shows the file structure betterare there any other options that i am missing thanks for the help,"['c++', 'c']" +488942,why is select count slower than select in hive when i am running queries in virtualbox sandbox with hive i feel select count is too much slower than the select can anyone explain what is going on behindand why this delay is happening,['sql'] +488965,need to change lowercase underscore string to camelcase i need to change string underbar lowercase uppercaseand the oppositemy name mynameis there any library or something to help this out,['java'] +489008,custom view is missing constructor used by tools for adapter i got the following warningcustom view comexampleviewadaptersomeadapter is missing constructor used by tools context or contextattributeset or contextattributesetintin my class someadapter which extends some baseadapter which extends arrayadapterpublic class someadapter extends baseadapterpublic abstract class baseadapter extends arrayadaptersomemodelthe warning exists in the concrete adapter but not in the abstract baseadapterhas anyone ever heard of this warning in that contextafaik android checks classes for they are extending views by checking the name of the super classes via viewconstructordetector private static boolean isviewclassclasscontext context classnode node string supername nodesupername while supername null if supernameequalsandroidviewview nonnls1 supernameequalsandroidviewviewgroup nonnls1 supernamestartswithandroidwidget nonnls1 supernameendswithadapter nonnls1 supernameendswithcontroller nonnls1 supernameendswithservice nonnls1 supernameendswithprovider nonnls1 supernameendswithfilter nonnls1 return true supername contextgetdrivergetsuperclasupername return falseas far as i can see my class names do not match the pattern abovedoes anyone has any idea how to fix or suppress this warninggetview in baseadapteroverridepublic final view getviewfinal int position final view convertview final viewgroup parent view view convertview if null view view createnewviewparent position else reuseoldviewview position return view,['android'] +489024,how to write a basic json parsing class could some one guide how to write a class which would take a json data and would try to parse it into a simple buffered list from which we could read the data backex json name john age 56 will be parsed into a table of key value pairsname johnage 56how to write a parse method which would help to create a faster and simpler kindly do not suggest any existing library provide a concept for parsing json,['java'] +489045,what happens in beginprocessrequest we are using newrelic to provide serverside application traceswe have noticed that some of our applications consistently spend about 100ms in the method systemwebmvcmvchandlerbeginprocessrequestthis happens before any custom controller code is called which is logged separately and not cumulatively it is not obvious why it would be spending so much time in this methodwhat kinds of things will mvc do in this method could this simply be request queuingedit as suspected scalayers answer below was spoton we removed optimized away all our session dependencies and saw a massive increase in application scalability stability,"['c#', 'asp.net']" +489050,utf8 encoding for subject in contact form email on this sites website link contact form i need to send the subject for email in utf8where in the code we need to do declare the utf8 encodingkontaktphprequire once phpsendmailclassphpsendmail new sendmailif serverrequest method postsendmailsetparams postsendmailparsebodysendmailsetheadersif sendmailsend headerlocation kontaktphpsuccess1sendmailclassphpclass sendmail var to email set contact emailvar name var subject var email var body var error arrayvar headers arrayfunction setheaders thisheaders from thisemailrn thisheaders mimeversion 10rn thisheaders contenttype texthtml charsetutf8rnfunction parsebody message htmlbody message table rulesall stylebordercolor 6 cellpadding10 message tr stylebackgroundcolor etdstrongnamestrong tdtd thisname tdtr message trtdstrongemailadressestrong tdtd thisemail tdtr message trtdstrongbetreffstrong tdtd thissubject tdtr message trtdstrongtextstrong tdtd thisbody tdtr message table message bodyhtml thisbody messagefunction send if thiserror return false if mailthisto thissubject thisbody thisheaders return true else thiserror fehler beim senden return false in the subject i need the utf 8 german characters encoding where do we need to declare it in the code for the message i found out what to do but for the subject i found no solution,['php'] +489121,phpunit debug still thisplays only dots i want to see which test is currently executed during a phpunit runi use the debug param but still only get dots phpunit debug phpunit 3719 by sebastian bergmannconfiguration read from homefoobarphpunitxmlsicontents of phpunitxmlphpunit backupglobalstrue bootstraptestsbootstrapphp backupstaticattributesfalse cachetokensfalse colorstrue converterrorstoexceptionstrue convertnoticestoexceptionstrue convertwarningstoexceptionstrue forcecoversannotationfalse maptestclassnametocoveredclassnamefalse printerclassphpunit textui resultprinter processisolationfalse stoponerrorfalse stoponfailurefalse stoponincompletefalse stoponskippedfalse testsuiteloaderclassphpunit runner standardtestsuiteloader strictfalse verbosetrue testsuites testsuite namefoo tests directorytestsdirectory testsuite testsuites filter whitelist adduncoveredfilesfromwhitelisttrue directory suffixphpsrcdirectory whitelist filter logging log typecoverageclover targetcloverxml loggingphpunitwhat can be the reason for this,['php'] +489156,joining byte list with python i am trying to develop a tool that read a binary file makes some changes and save it what i am trying to do is make a list of each line in the file work with several lines and then join the list againthis is what i triedfile openmyfileexe rbalist for line in f alistappendlinehere im going to mutate some linesnew file joinalistand give me this errortypeerror sequence item 0 expected str instance bytes foundwhich makes sense because i am working with bytesis there a way i can use join function o something similar to join bytesthank you,['python'] +489171,error sqlh not found when installing rubyodbc gem on ubuntu attempting to install rubyodbc gem on debianubuntu results in the following errorerror sqlh not found,['ruby'] +489173,read a file synchronously in javascript i would like to read a file and convert it into a base64 encoded string using the filereader object heres the code i use var reader new filereader readeronloadend functionevt file is loaded result base64 evttargetresult readerreadasdataurlfile but in this case i get the result of the conversion in the event handler onloadend event i would like a synchronous method is there a way the readasdataurl method can return directly the value of the result base64 variable thanks,['javascript'] +489202,javascriptserializer utc datetime issues our client wanted to show the date and time values in the browser exactly as they are in the database and we are storing them as utc in the databaseat first we had some problems with the serialization and javascript side the datetime values got shifted twice at first to match the local time zone of the machine and then to match the time zone in the browser we fixed it by adding a custom converter to the javascriptserializer we marked the datetime to be of datetimekindutc in the serialize override it was a bit hard to feed the data back from the serialize but we found some uri hack which helped to return datetime values in the same javascriptserializer date286769410010 format but without shifting to the local time on the javascript side we patched the kendoui js library to offset the constructed date objects so they appear as if they are utcthen we started to work on the other side deserialization again we had to adjust our code to use a custom stringify instead of jsonstringify which again offsets the data when converting from the local time to utc everything seemed good so farbut look at this test public void deserialisedatestest var dateexpected new datetime1979 2 2 2 10 10 10 datetimekindutc this how the dates look like after serializing anothe issue unrelated to the core problem is that the might get stripped out when dates come back from the browser so i have to add missing or else deserialize will break string s date286769410010 this get deserialized to utc date by default javascriptserializer js new javascriptserializer var dateactual jsdeserializedatetimes assertareequaldateexpected dateactual assertareequaldatetimekindutc dateactualkind but some javascript components like kendoui sometimes use jsonstringify for javascript date object thus producing the following s 19790202t021010z dateactual jsdeserializedatetimes if your local computer time is not utc this will fail assertareequaldateexpected dateactual and the following fails always assertareequaldatetimekindutc dateactualkind why does javascriptserializer deserialize date286769410010 strings to utc time but 19790202t021010zto local timewe tried to add a deserialize method to our custom javascriptconverter but the problem is that the deserialize is never called if our javascriptconverter has the following types public override ienumerabletype supportedtypes get return new listtype typeofdatetime typeofdatetime i guess deserialize would be called only if supportedtypes contained types of some complex entities which have datetime fieldsso javascriptserializer and javascriptconverter have two inconsistenciesserialize takes into account simple types in supportedtypes for every data item but deserialize ignores it for simple typesdeserialize deserializes some dates as utc and some as local timeis there any simple way to fix these issues we are a bit afraid to replace javascriptserializer with some other serializer because maybe some of the 3rd party libraries we are using are relying upon some certain featuresbugs of javascriptserializer,['.net'] +489245,default argument for template parameter for class enclosing codetemplate typename element type typename container type stddequeelement type class stack public stack template typename ct stackct temp containertempbegin tempend bool empty private container type containertemplate typename element type typename container type stddequeelement type bool stackelement type container typeempty return containeremptywhen i compile it gives the errordefault argument for template parameter for class enclosing bool stackelement typecontainer typeemptywhy is the compiler complaining and how can i make it work,['c++'] +489254,best practice for returning a variable length string in c i have a string function that accepts a pointer to a source string and returns a pointer to a destination string this function currently works but i am worried i am not following the best practice regrading malloc realloc and freethe thing that is different about my function is that the length of the destination string is not the same as the source string so realloc has to be called inside my function i know from looking at the docsthat the memory address might change after the realloc this means i have cannot pass by reference like a c programmer might for other functions i have to return the new pointerso the prototype for my function isdecode a uri encoded stringchar net uri to textchar i do not like the way i am doing it because i have to free the pointer after running the functionchar chr output net uri to texttesting1235a5b5cabcprintfsn chr output testing123zabcfreechr outputwhich means that malloc and realloc are called inside my function and free is called outside my functioni have a background in high level languages perl plpgsql bash so my instinct is proper encapsulation of such things but that might not be the best practice in cthe question is my way best practice or is there a better way i should followfull examplecompiles and runs with two warnings on unused argc and argv arguments you can safely ignore those two warningsexamplecinclude stdiohinclude stringhinclude stdlibhchar net uri to textchar int mainint argc char argv char chr input testing1235a5b5cabc char chr output net uri to textchr input printfsn chr output freechr output return 0decodes uriencoded stringsend pointer to source stringreturn pointer to destination stringwarning you must use freechr result after youre done with it or you will get a memory leakchar net uri to textchar chr input define variables int int length strlenchr input int int new length int length char chr output mallocint length char chr output working chr output char chr input working chr input int int output working 0 unsigned int uint hex working while not a null byte whilechr input working 0 if if chr input working then put correct char in sscanfchr input working 1 02x uint hex working chr output working charuint hex working printfspecial charc c dn chr output working charuint hex working uint hex working realloc chr input working chr input working int new length 2 chr output reallocchr output int new length output working must be the new pointer plys how many chars weve done chr output working chr output int output working else put char in chr output working chr input working increment pointers and number of chars in output working chr input working chr output working int output working last null byte chr output working 0 return chr output,['c'] +489265,systemconsolewriteline vs printfn in f what is the difference between the following two statements in fare they any advantages or thisadvantages compared to each other excluding the obvious syntax differencesi understand that writeline is part of net but do not understand what implications this might havethe sample codeprintfn this is an integer d 5systemconsolewritelinethis is an integer 0 5,['.net'] +489310,how to upload and save an attachment via xpages java bean i get how you can use expression language to bind xpages controls to a java bean then it accesses the setters and getters automaticallybut how do you handle a file attachment what does that look like i would like to be able to i guess bind the file upload control to the bean save the attachment to whatever doc whether it is the current or external document the bean should be able to handle that logici guess i do not know how to get that file attachment into the in memory bean to be able to do anything with it like saving to a documentany advice would be appreciatedupdate this is a similar question to this how to store uploaded file to local file system using xpages upload controlbut in that question the user wants to save to local thisc i am looking to save to a documentthanks,['java'] +489343,python why a method from super class not seen i am trying to implement my own version of a dailylogfile from twistedpythonlogfile import dailylogfileclass ndailylogfiledailylogfile def init self name directory rotateaftern 1 defaultmodenone dailylogfile init self name directory defaultmode why do not use super here lisibility maybe selfrotateaftern rotateaftern def shouldrotateself rotate when and days have passed since file creation delta datetimedateselftodate datetimedateselftodateselfcreatedon return delta datetimetimedeltaselfrotateaftern def getstate self state baselogfile getstate self del staterotateaftern return statethreadablesynchronizendailylogfilebut it looks like i miss a fundamental of python subclassing processas i get this error traceback most recent call last file hometwistedtestproxy04py line 88 in module import ndailylogfile file homendailylogfilepy line 56 in module threadablesynchronizendailylogfile file homeltmpv0libpython26sitepackagestwistedpythonthreadablepy line 71 in synchronize sync syncklass klass dict methodnamekeyerror writeso i need to explicitly add and define others methods like write and rotate method like thisclass ndailylogfiledailylogfile def writeself data why must i add these dailylogfilewriteself data def rotateself as we do nothing more than calling the method from the base class dailylogfilerotateselfthreadablesynchronizendailylogfilewhile i thought it would be correctly inherit from the base mother class notice that i do nothing only calling superplease can someone explain why i am wrong on my first idea that it was not necessary to add the write methodis there a way to say to python inside my ndailylogfile that it shoud have all the methods dailylogfile that are not defined directly from its mother class so that it prevents this king of error syncklass klass dict methodname and that avoid to specify excplicitly original code of dailylogfile that inspired me it taken from the twisted source here edit about using super i get file homeltinworkndailylogfilepy line 57 in write superwriteself dataexceptionsattributeerror type object super has no attribute writeso will not use it my thoughs was it was right i must have definitively missed something,['python'] +489359,how can i make the text of this div wrap i have a simple html structure that looks likediv classcontainer div classcaption div classtitlethis is a very very long titlediv div classdetailsdetailsdiv div div classcontentdivdivi have styled this very simply container minwidth 200pxcaption overflow hiddentitle float leftdetails float rightcontent height 200px backgroundcolor c0c0c0which looks likeif i shrink the window enough eventually the details div will wrap to the next linewhat i would like to happen is the text inside the title div wrap to the next line but keep both title and details at the same line not wrapping something likethis is a very very detailslong titlewith the title only wrapping once there is not enough space as the window is resizedcan anyone point me in the right direction for achieving thishere is a jsfiddle of the above code if anyone is interestededit to clarify i would like to not specify a fixed width for title if possible in most cases i would like to let this div get as wide as it needs,"['html', 'css']" +489416,cannot install xcode 462 on os x mavericks i am unable to install xcode 462 on os x mavericks i upgraded from mountain lion to os x mavericks and it was running during that time i uninstalled it because i thought it was behaving in a strange manner and when i tried to reinstall i got the error xcode canat be installed on amacintosh hda because the version of os x is too newlooked up this error online and people recommended clearing cache but that did not helpfollowed the step on apples site but that did not solve the problem either not sure why its happening,['ios'] +489421,identical listviews thisplay differently columns do not stretch on one i have run into a bizarre problem i am thisplaying a usercontrol within a usercontrol and at the moment each contains a completely identical listview as in i copied and pasted it from one to the other on the parent usercontrol the listview thisplays properly but on the subusercontrol whatever it is called the listview columns refuse to stretch to fit their content i have no idea why this is happening since the code of both listviews is exactly the same both are placed directly on the gridon the top left is the listview from the parent control and on the bottom right is that of the child control here is the code for both listviewslistview itemssourcebinding adventurers nameadvlistview horizontalalignmentstretch gridcolumn2 gridcolumnspan1 gridrow2 scrollviewercancontentscrollfalse borderthickness3 iinteractiontriggers ieventtrigger eventnamemousedoubleclick cmdeventtocommand commandbinding showadvwindowcommand commandparameterbinding elementnameadvlistview pathselecteditem passeventargstocommandfalse ieventtrigger iinteractiontriggers listviewitemcontainerstyle style targettypelistviewitem setter propertyhorizontalcontentalignment valuestretch setter propertyverticalcontentalignment valuestretch style listviewitemcontainerstyle listviewresources datatemplate xkeynametemplate textblock gridcolumn1 gridrow0 textbinding name verticalalignmentcenter texttrimmingcharacterellipsis datatemplate datatemplate xkeystatustemplate textblock margin21 textbinding status verticalalignmentcenter datatemplate listviewresources listviewview gridview gridviewcolumn headername celltemplatestaticresource nametemplate gridviewcolumn headerstatus celltemplatestaticresource statustemplate gridview listviewview listviewwhy would this work on one and not the other i am really at a loss at this pointupdate in the parent usercontrol the grid layout isgrid backgroundwhite gridcolumndefinitions columndefinition width columndefinition width columndefinition width columndefinition width columndefinition width gridcolumndefinitions gridrowdefinitions rowdefinition heightauto rowdefinition height rowdefinition height rowdefinition height rowdefinition heightauto gridrowdefinitions listview here among other controlsgridin the childgrid gridcolumndefinitions columndefinition width gridcolumndefinitions gridrowdefinitions rowdefinition height gridrowdefinitions listview heregridmodifying gridrow gridcolumn rowspan or columnspan to be correct does not fix the problemupdate a bit more info that may be relevant when i try to use snoop on my program i get this errorbindingfailure was detected the assembly with thisplay name snoopxmlserializers failed to load in the loadfrom binding context of the appdomain with id 1 the cause of the failure was systemiofilenotfoundexception could not load file or assembly snoopxmlserializers version2800 cultureneutral publickeytokennull or one of its dependencies the system cannot find the file specified snoop has no problem with other programs i do not know if this is related to the issue at all but i figured i would post it anywaysupdate i do not think this would matter but just to be thorough here is where the child usercontrol is created within the parentgrid other controls usercontrol gridcolumn3 gridrow3 visibilitybinding adventurerinfovisibility viewadventurerinfoview usercontrolgridat this point i am completely stumped i can create a copy of the listview in the parent usercontrol and have it thisplay properly but for some reason it does not want to behave in the child usercontrol i am open to any ideas and if you need more code i would be more than happy to provide it,['c#'] +489490,how to resize and save an image which uploaded using file upload control in c i have developed a web application using aspnet mvc4 and razor in my application there is a file upload control to upload an image and save in a temporary locationbefore save image should resized to a specific size and then save in the temporary location givenhere is the code i have used in controller classpublic class fileuploadcontroller controller get fileupload public actionresult index return view public actionresult fileupload return view acceptverbshttpverbspost public actionresult fileuploadhttppostedfilebase uploadfile if uploadfilecontentlength 0 string relativepath img pathgetfilenameuploadfilefilename string physicalpath servermappathrelativepath fileuploadmodelresizeandsaverelativepath uploadfilefilename uploadfileinputstream uploadfilecontentlength true return viewobjectrelativepath return view and here is the code used in model classpublic class fileuploadmodel required public httppostedfilewrapper imageuploaded get set public static void resizeandsavestring savepath string filename stream imagebuffer int maxsidesize bool makeitsquare int newwidth int newheight image image imagefromstreamimagebuffer int oldwidth imagewidth int oldheight imageheight bitmap newimage if makeitsquare int smallerside oldwidth oldheight oldheight oldwidth double coeficient maxsidesize doublesmallerside newwidth converttoint32coeficient oldwidth newheight converttoint32coeficient oldheight bitmap tempimage new bitmapimage newwidth newheight int cropx newwidth maxsidesize 2 int cropy newheight maxsidesize 2 newimage new bitmapmaxsidesize maxsidesize graphics tempgraphic graphicsfromimagenewimage tempgraphicsmoothingmode smoothingmodeantialias tempgraphicinterpolationmode interpolationmodehighqualitybicubic tempgraphicpixeloffsetmode pixeloffsetmodehighquality tempgraphicdrawimagetempimage new rectangle0 0 maxsidesize maxsidesize cropx cropy maxsidesize maxsidesize graphicsunitpixel else int maxside oldwidth oldheight oldwidth oldheight if maxside maxsidesize double coeficient maxsidesize doublemaxside newwidth converttoint32coeficient oldwidth newheight converttoint32coeficient oldheight else newwidth oldwidth newheight oldheight newimage new bitmapimage newwidth newheight newimagesavesavepath filename jpg imageformatjpeg imagethispose newimagethispose but when i run the application it occurs an argumentexceptionit says parameter is not valid in following code linebitmap tempimage new bitmapimage newwidth newheighthow do i pass valid and appropriate parameters herepublic static void resizeandsavestring savepath string filename stream imagebuffer int maxsidesize bool makeitsquare,['c#'] +489493,how to correctly set alpha of uiview ios i have uiview with lots of subviews uilabel uitextview etcif a set alpha 06 to main view all the subviews takes this alphahow to set alpha separately of main view,['ios'] +489508,can not found npoixssfusermodel i wanna use npoi to manipulate xlsx files in vs20122010 to do so i should import npoixssfusermodel but when i add the npoidll and try to import that there is no xssf type of npoi at using part i mean that there is no using npoixssfany help,"['c#', '.net']" +489511,cxf jaxrs return custom response from interceptor we need to return custom error code and error message when exception occurs during rest invocation we have created a exception mapper provider it works well for the exceptions from the application code however it does not work when exception occurs from the cxf code eg form the customvalidationinterceptor that i wrotefor example if i request with invalid path parameter eg invalid phonenumber in this case we need to return a custom error code and error message in json format but it does not work even though we have a exception mapper provider created to handle webapplicationexception is there any way to handle exceptions from cxf interceptors and return response to user with something like the following errordetail errorcode 404errormessage bad requestcode snippet of my customvalidationinterceptor public class customvalidationinterceptor extends abstractphaseinterceptormessage public customvalidationinterceptor superphasepre invoke put this interceptor in this phase public void handlemessagemessage message metadatamapstring string metadatamap metadatamapstring string messagegetjaxrstemplateparameters ifnull metadatamap liststring list metadatamapgetphonenumber ifnull list string phonenumber listget0 boolean result validatephonenumberphonenumber ifresult throw new telusserviceexceptionresponsestatusresponsestatusbad requestbuild 400 phone number not valid else throw new telusserviceexceptionresponsestatusresponsestatusbad requestbuild 400 phone number not valid else throw new telusserviceexceptionresponsestatusresponsestatusbad requestbuild 400 phone number not valid public boolean validatephonenumberstring phonenumber pattern pattern patterncompile19d9 matcher matcher patternmatcherphonenumber if matchermatches return false return true code snippet of my custom exception mapper providerpublic class telusexceptionhandler implements exceptionmappertelusserviceexception public response toresponsetelusserviceexception exception return responsestatusexceptiongeterrordetailgeterrorcodeentityexceptiongeterrordetailbuild code snippet of telusserviceexceptionpublic class telusserviceexception extends webapplicationexception constructors and other methods private errordetail errordetail null public errordetail geterrordetail return errordetail public void seterrordetailerrordetail errordetail thiserrordetail errordetail public telusserviceexceptionresponse response int errorcode string errormessage superresponse errordetail new errordetail errordetailseterrorcodeerrorcode errordetailseterrormessageerrormessage code snippet of errordetail classxmlrootelementnameerrordetailpublic class errordetail private int errorcode private string errormessage xmlelementname errorcode public int geterrorcode return errorcode public void seterrorcodeint errorcode thiserrorcode errorcode xmlelementname errormessage public string geterrormessage return errormessage public void seterrormessagestring errormessage thiserrormessage errormessage,['java'] +489515,unit testing python how tos i am new to github i am new to writing unit test cases i have contributed to a project but the owner has asked me to provide unit testcases that fail before the fix and work after the fix how can i go about doing it shall i write them all together as at one time i will have one copy of the code ie with fix or without fix i am using python and importing unittest i am confused before the fix i get an exception so should i use assertraises for that i did read a lot but am not able to start,['python'] +489569,i want to call google plus callback function when clicking on the google plus button i have used a google plus button in my project built in codeigniter here i have added the following codespan idsigninbutton span classgsignin gooconnect datacallbacksignincallback dataclientidmy project client id datacookiepolicysingle host origin datarequestvisibleactions datascope spanspanthen i added the javascript code provided by googlescript typetextjavascript function var po documentcreateelementscript potype textjavascript poasync true posrc var s documentgetelementsbytagnamescript0 sparentnodeinsertbeforepo s function signincallbackauthresult if authresultaccess token ajax urlbase urlindexphpusergetuserprofile typepost dataaccessauthresultaccess token beforesend function loadingimagebeforeresultshowslow success functionresp loadingimagebeforeresulthideslow if resp exist windowlocationhrefbase urlindexphpusermy deals else link for geniepagetriggerclick error functionresp else if authresulterror there was an error possible error codes access denied user denied access to your app immediate failed could not automatially log in the user consolelogthere was an error authresulterror script it is working fine for me but if i log in my gmail account in a separate tab and then i go to my login page the callback function just auto logins with my gmail credentials and redirects me to my dashboardi want that unless i click on that google plus button the callback function should not work how can i do this please help me,"['javascript', 'jquery']" +489616,why does modifying project output directories cause ioexception was unhandled cannot locate resource appxaml in an attempt to consolidate project settings into property sheets for both c and c projects the following property sheet was constructedxml version10 encodingutf8project defaulttargetsbuild toolsversion40 xmlns trying to support both c and c projects by introducing derived properties and setting the appropriate output properties propertygroup labelusermacros projectorassemblyname conditionassemblynameprojectnameprojectorassemblyname projectorassemblyname conditionprojectnameassemblynameprojectorassemblyname shortplatform conditionplatformwin32x86shortplatform shortplatform conditionplatformx86x86shortplatform shortplatform conditionplatformx64x64shortplatform shortplatform conditionplatformanycpuanycpushortplatform propertygroup propertygroup outputpathoutputrelativepathprojectorassemblyname shortplatform configurationoutputpath baseintermediateoutputpathoutputrelativepathobj exeprojectorassemblyname shortplatformbaseintermediateoutputpath intermediateoutputpathbaseintermediateoutputpath configurationintermediateoutputpath intdirintermediateoutputpathintdir outdiroutputpathoutdir propertygroupprojectthis property sheet will move all build output to a separate location outputrelativepath defined in separate property sheet or directly in project file outside directories that contain source code for easier cleanup etc however after setting this up and build works fine and all unit tests work fine it was clear that a wpf executable project was not fine since running the application with above property sheet results in the infamousioexception was unhandled cannot locate resource appxamlwhy does changing the output paths result in this error and how can it be determined that the cause is project build output paths can this be seen in generated code i could not find it and is not this a bugnote using the following property sheet works but only if intermediateoutputpath contains baseintermediateoutputpathxml version10 encodingutf8project defaulttargetsbuild toolsversion40 xmlns propertygroup outputpathoutputrelativepathassemblyname platform configurationoutputpath baseintermediateoutputpathoutputrelativepathobj exeassemblyname platformbaseintermediateoutputpath intermediateoutputpathbaseintermediateoutputpath configurationintermediateoutputpath propertygroupprojectso it appears that somehow it is expected that output paths contain the assemblyname properties or similarupdate for xaml styles in another assembly the same applies to xaml resourcedictionary if these eg brushesxaml are located in another assembly and this assembly has changed the outputpath also this also throws an exceptionxamlparseexception was unhandled for set property source with innerexception cannot locate resource brushesxaml so all in all it appears output location changes the xaml resource names so these cannot be thiscovered at runtime somehow the odd thing is it is not a problem at design timeupdate minimal steps to reproduce the exceptionopen visual studio 2013create new c project wpf application eg xamlintermediateoutputpathbugunload projectedit project fileafter first propertygroup insert new propertygroup as propertygroup outputrelativepathprojectdirbuildoutputrelativepath outputpathoutputrelativepathassemblyname platform configurationoutputpath baseintermediateoutputpathoutputrelativepathobj exeassemblyname platformbaseintermediateoutputpath intermediateoutputpathbaseintermediateoutputpath configurationintermediateoutputpath intdirintermediateoutputpathintdir outdiroutputpathoutdirpropertygroup delete outputpath properties in remaining propertygroups eg outputpathbindebugoutputpath and outputpathbinreleaseoutputpath this should then throw an ioexception on start for mainwindowxaml this is due to the assemblynamegresources embedded resource is given the following name mresource public buildobj exexamlintermediateoutputpathbug anycpu debugxamlintermediateoutputpathbuggresources as build obj exe xamlintermediateoutputpathbug anycpu debug xamlintermediateoutputpathbuggresources offset 0x0 length 0x03bcmresource public buildobj exexamlintermediateoutputpathbug anycpu debugxamlintermediateoutputpathbugpropertiesresourcesresources as build obj exe xamlintermediateoutputpathbug anycpu debug xamlintermediateoutputpathbugpropertiesresourcesresources offset 0x03c0 length 0x0b4as can be seen with ildasmexe and opening the manifest for the assembly as can also be seen the normal resources also gets a wrong name with the output path prefixed this can however be fixed by setting the logicalname in the project file for this resource see missingmanifestresourceexception when running tests after building with msbuild mresource has path in manifest this does not appear to be possible for xaml resourceshaving looked at the configuration i noticed i use at the end of the outputpath and intermediateoutputpath removing these it appears to work see belowpropertygroup outputrelativepathprojectdirbuildoutputrelativepath outputpathoutputrelativepathassemblyname platform configurationoutputpath baseintermediateoutputpathoutputrelativepathobj exeassemblyname platformbaseintermediateoutputpath intermediateoutputpathbaseintermediateoutputpath configurationintermediateoutputpath intdirintermediateoutputpathintdir outdiroutputpathoutdirpropertygroup i find this rather curious any insight into why this would be the case or if this is actually true is appreciated note that the c intdir and outdir instead must have a trailing backslash otherwise you will get warnings about this,['c#'] +489624,adding inertia to a uipangesturerecognizer i am trying to move a sub view across the screen which works but i also want to add inertia or momentum to the object my uipangesturerecognizer code that i already have is belowthanks in advanceuipangesturerecognizer pangesture uipangesturerecognizer alloc initwithtargetself actionselectorhandlepanself addgesturerecognizerpangesturevoidhandlepanuipangesturerecognizer recognizer cgpoint translation recognizer translationinviewselfsuperview recognizerviewcenter cgpointmakerecognizerviewcenterx translationx recognizerviewcentery translationy recognizer settranslationcgpointmake0 0 inviewselfsuperview if recognizerstate uigesturerecognizerstateended selfdelegate cardselftag movedtoselfframeorigin again thanks,['ios'] +489625,i want to do animation of an object along a particular path i have to move the small rectangle on the path the rectangle moves after a click inside the canvasi am not able to animate it as the object just jumps to the required pointplease find the code on fiddlehtmlcanvas idmycanvas width578 height200canvascssmycanvas width578px height200px border2px thinjavascriptvar myrectangle x 100 y 20 width 25 height 10 borderwidth 1documentreadyfunction mycanvascssborder 2px solid black var canvas documentgetelementbyidmycanvas var context canvasgetcontext2d var cntxt canvasgetcontext2d drawpathcontext drawrectmyrectangle cntxt mycanvasclickfunction function animatemyrectangle canvas cntxt starttime var time new dategettime starttime var linearspeed 10 var newx mathroundmathsqrt100 100 160 160 if newx canvaswidth myrectanglewidth myrectangleborderwidth 2 myrectanglex newx contextclearrect0 0 canvaswidth canvasheight drawpathcontext drawrectmyrectangle cntxt request new frame requestanimframefunction animatemyrectangle canvas cntxt starttime drawrectmyrectangle cntxt myrectanglex 100 myrectangley 121 settimeoutfunction var starttime new dategettime animatemyrectangle canvas cntxt starttime 10 documentkeypressfunction e if ewhich 13 mycanvasclick function drawrectmyrectangle cntxt cntxtbeginpath cntxtrectmyrectanglex myrectangley myrectanglewidth myrectangleheight cntxtfillstyle cyan cntxtfill cntxtstrokestyle black cntxtstrokefunction drawpathcontext contextbeginpath contextmoveto100 20 line 1 contextlineto200 160 quadratic curve contextquadraticcurveto230 200 250 120 bezier curve contextbeziercurveto290 40 300 200 400 150 line 2 contextlineto500 90 contextlinewidth 5 contextstrokestyle blue contextstroke,"['javascript', 'jquery']" +489689,windows phone 8 applicationsettings not persisted i have the following strange behaviour in my windows phone 8 c appi am saving a setting withprivate void savepropertytt property string propertyname if isolatedstoragesettingsapplicationsettingscontainspropertyname isolatedstoragesettingsapplicationsettingspropertyname property else isolatedstoragesettingsapplicationsettingsaddpropertyname property isolatedstoragesettingsapplicationsettingssave when the app runs i can read all settings i stored in isolatedstoragesettingsapplicationsettingsbut when i reopen my app open it from the app list the isolatedstoragesettingsapplicationsettingsdictionary contains zero 0 keys and valuesam i missing somethingi used the isetoolexe to take snapshots of the isolatedstorage of my app thanks to chepenei saw this behaviour when i wrote the settings that means after the savepropertyt function finished and the app is still running i have the settings saved in applicationsettings this agrees with my observation that i can read from the isolatedstoragesettingsapplicationsettings when the app is runningthe applicationsettingsfile also exists when the is tombstoned or not running when i can access it by holding the backbutton of the phone and when the app is closed with the backbuttonbut when the app is opened again via the app list the applicationsettingsfile is gonei also see that when i am writing a file into the isolatedstorage withsharedstorageaccessmanagercopysharedfileasync windowsstorageapplicationdatacurrentlocalfolder filenameorig windowsstoragenamecollisionoptionreplaceexisting fileidand when i then do not read this file it is gone when i open the app the next timeby the way to avoid confusion i am not reinstalling the app each time i open itif you need more information please askany help appreciated,['c#'] +489726,is there a managed api to manage iis 8 in iis7 you used to be able to use the microsoftwebadministration dll to manage iisi have added this reference to my project however running the following code results in a notimplementedexception at sitestopusing var server new servermanager var site serversitesfirstordefaults sname instancename if site null sitestop is there an updated version of this api or an alternate method to manage iis from neti would prefer not to use wmi or have to spawn an instance of appcmd if at all possible,['c#'] +489744,flatten an nsarray i have an array like thisarray httpaproduct8 1371121323png httpaproduct14 1371123271png httpaproduct9 1371121377png and i have to create another array from that one like thisarray httpaproduct8 1371121323png httpaproduct14 1371123271png httpaproduct9 1371121377pnghow can i do that is it possible to combine all the objects and separate them using some string,['objective-c'] +489759,tabhost how to change tab text in xml i know the solution on how to change it programically however i would like to set the text in xml how do you do that i have looked here but found no solution,['android'] +489765,using just bootstrap modal i am integrating my modal from bootstrap with another site that does not use iti see that bootstrap lets you separate the javascript for each component but what about the css if i link to bootstrapcss the whole site will change i just want enough css for the modal to work i tried going thru the css file and just guessing what i needed but it did not work,['css'] +489797,difference comsunjersey and orgglassfishjersey what is the difference between comsunjersey and orgglassfishjerseycurrently i have my rest service working on comsunjersey and i want to write tests but i cannot find a good tutorial for this nothing seems to work however i can find good documentation about the orgglassfishjersey tests,['java'] +489858,access the application object inside a window class in wpf can we access the current systemwindowsapplication object inside a window class in wpf,"['c#', '.net']" +489878,how can i more easily suppress previous exceptions when i raise my own exception in response considertry import someproprietarymoduleexcept importerror raise importerrorit appears that someproprietarymodule is not installedwhen run if someproprietarymodule is not installed one seestraceback dataimporterror unknown module someproprietarymoduleduring handling of the above exception another exception occurredtraceback dataimporterror it appears that someproprietarymodule is not installedperhaps i do not want the during handling of the above exception line and the lines above it to appear i could do this moduleinstalled truetry import someproprietarymoduleexcept importerror moduleinstalled falseif not moduleinstalled raise importerrorit appears that someproprietarymodule is not installedbut that feels like a bit of a hack what else might i do,['python'] +489949,integer value read from systemin is not the value typed i am a newbie to java and as an exercise wanted to wap a simple program to print required no of characters according to the user but somehow the output of this code always remains similarpackage starspublic class stars public static void mainstring args int no stars0 try systemoutprintenter the number of stars no stars intsysteminread catch exception e systemoutprintlnerror invalid argument systemoutprintln printstarsno stars public static void printstarsint n int i fori0ini systemoutprintln if i replace with i i can see that it loops upto 505254 even though i run the loop no stars timeswhat seems to be the problem here,['java'] +489961,how do i unittest https requests in flask for certain pages in a flask app i am creating i have an https redirection system as followsdef requires httpsf code302 defaults to temp redirect 301 is permanent wrapsf def decoratedargs kwargs passthrough conditions requestis secure requestheadersgetxforwardedproto http https localhost in requesturl if not anypassthrough conditions if requesturlstartswithhttp url requesturlreplacehttp https r redirecturl codecode return r return decoratedif youre not requesting the https version of the page it redirects you to it i want to write unit tests for this service i have written one that makes sure that youre redirected to the https version check for a 301 or a 301 basically i want to test that if you are requesting the https version of the page and are already on https it does not redirect you basically for a 200 how do i get flask to send an https request in the unit test,['python'] +489963,how do i loop through children objects in javascript i have this code in a functiontablefields tablefieldschildrenfor item in tablefields do stuffaccording to a consolelog of tablefields i am getting an array back as i assume i need to do a consolelog of item within the loops returns undefined what do i have to do to loop through tablefields and insert each object into a tableconsole log of tablefieldshtmlcollectionlabel input label input 25 label input input input remove0label1input2label3input 254label5input6input7 input removedescriptioninputhoursinputinvoice numberinputgetlength8rateinput 25itemitemiteratoriteratornameditemnameditem proto htmlcollectionprototype itemitem nameditemnameditem iteratoriteratorhere is the entire section of code as i have so farthistitletest thisdefaultmenu select names customergetnames foreach names as id name select option valueid if thiscustomerid id select selected select nameoption form script typetextjavascriptvar counter 0function isevenintint numberintreturn int2 0function morelabor var table documentgetelementbyidedittable var tablefields documentgetelementbyidreadroot tablefields tablefieldschildren consolelogtablefields for item in tablefields if isevencounter var tablerow tableinsertrow1 var label tablerowinsertcell1 consolelogtablefieldsitem labelappendchildtablefieldsitem else var field tablerowinsertcell1 fieldinnerhtml iteminnerhtml counter consolelogvar inserthere documentgetelementbyidwriterootwindowonload function documentgetelementbyidmorelaboronclick function morelabor morelaborscriptdiv idreadroot stylethisplay nonetr tdlabel forhourshourslabeltd tdinput typetext namehours value tdtrtr tdlabel forrateratelabeltd tdinput typetext namerate value25 tdtrtr tdlabel fordescriptiondescriptionlabeltd tdinput typetext namedescription value tdtrinput typehidden nameinvoice number valuethisnumber tr tdinput typebutton valueremove onclickthisparentnodeparentnoderemovechildthisparentnode tdtrdivform methodpost classinvoice idedittable idedittable tr tdlabelwork order numberlabeltd tdinput typetext namenumber valuethisnumbertd tr tr tdlabelcustomerlabeltd tdselect namecustomeridselectselecttd tr span idwriterootspan tr tdinput typebutton idmorelabor valueadd labortd tdinput typesubmit namesave valuesave td tr if is nullthisid form input typehidden nameid valuethisid form tableform thiscomponentform,['javascript'] +490002,whats the difference between the mysqli functions bind result store result and fetch i am running into problems knowing when and what to call after mysqli stmt executehow do you know when to callmysqli stmt bind resultmysqli stmt store resultmysqli stmt fetch,['php'] +490018,css auto change ul width when li increase floating left i have a problem to auto fix uls width that li can float straightlyif i change css set ul with a width like 10px not auto that what i want can be done however is there other any settings only by css also can achieve same result because i want to auto change uls width as increasing number of li now is like div uldiv ul li li li li i want to be like this div div ulul li li li li htmldiv classtest ul lili lili lili lili uldivcsstest width 500px height 100px overflow hiddentest ul liststylenone width auto height 100 backgroundcolor9 thisplay block padding 0px margin 0pxtest ul li float left thisplay block height 100 width 180px backgroundcolor99c marginright10pxthank you very much for your advice,"['html', 'css']" +490049,why use bzero over memset in a systems programming class i took this previous semester we had to implement a basic clientserver in c when initializing the structs like sock addr in or char buffers that we used to send data back and forth between client and server the professor instructed us to only use bzero and not memset to initialize them he never explained why and i am curious if there is a valid reason for thisi see here that bzero is more efficient due to the fact that is only ever going to be zeroing memory so it does not have to do any additional checking that memset may do that still does not necessarily seem like a reason to absolutely not use memset for zeroing memory thoughbzero is considered deprecated and furthermore is a not a standard c function according to the manual memset is preferred over bzero for this reason so why would you want to still use bzero over memset just for the efficiency gains or is it something more likewise what are the benefits of memset over bzero that make it the de facto preferred option for newer programs,['c'] +490173,android gradle code coverage i have a simple android project with test casesprojnameprojectbuildgradleprojnamebuildgradlei see that by default androids new build system provides basic test results by default hooraynow i want to see code coverage as well i know how to set this up using emma and ant scripts however i do not want to run ant scripts here i feel that would defeat the purpose of me using the new build systemi have tried a few cobertura plugins that were found on github one in particularhowever if i try to use the plugin in the projname build file then i get errors about the java plugin i read on toolsandroidcom that adding the java plugin will generate this behavior i am not applying it so the cobertura plugin must beif i try to use the plugin in the main build file then i do not see the java errors but now i seecould not find netsourceforgecoberturacobertura1941 required by projnameprojectunspecifiedwhat do i do,['android'] +490182,is there a way to convert a dynamic or anonymous object to a strongly typed declared object if i have a dynamic object or anonymous object for that matter whose structure exactly matches that of a strongly typed object is there a net method to build a typed object from the dynamic objecti know i can use a linq dynamiclistselectdynamic new typed type thing or i can use automapper but i am wondering if there is not something specially built for this,['.net'] +490332,phpexcel freezepane not working for char a char z char objphpexcelgetactivesheetsetcellvaluechar540for i1i100i objphpexcelgetactivesheetsetcellvalueaigeneraterandomstringobjphpexcelgetactivesheetfreezepaneb write the phpexcel object to browser as htmlobjwriter phpexcel iofactorycreatewriterobjphpexcel htmlobjwritersavephpoutputobjphpexcelgetactivesheetfreezepanebfreeze not happened for the a first column columnattached screen shot fyifreeze not happened for the a first column columnwhen i scroll col a not freeze col a also hidding,['php'] +490382,convert dataset to list here is my c codeemployee objemp new employeelistemployee emplist new listemployeeforeach datarow dr in dstables0rows emplistaddnew employee name converttostringdrname age converttoint32drage it uses a loop to create a list from a datasetis there any direct method or shorter method or one line code to convert dataset to list,['c#'] +490422,how do i find the sum of the values entered in certain fields that were created dynamically using javascript i have written code that creates a form thisplayed as a table on a html page i have written javascript to allow the user to add rows or delete selected rows the add and delete functionalities work but i want the final column of a row to thisplay the sum of the previous three values and that is just not happeningheres the html codeinput typebutton valueadd row onclickaddrowdatatable input typebutton valuedelete row onclickdeleterowdatatable table iddatatable width350px border1 form namef1 idf1 tr tdb select btd tdb sno btd tdb subject btd tdb mark 1 btd tdb mark 2 btd tdb mark 3 btd tdb total btd tr tr td input typecheckbox namechktd td 1 td td input typetext namesubject td td input typetext namemark td td input typetext namemarka td td input typetext namemarkb td td input typetext nametotal td tr formtableinput typebutton valuesum onclicksumdatatable and the javascript that i have been using script languagejavascript var k0 function addrowtableid k var table documentgetelementbyidtableid var rowcount tablerowslength var row tableinsertrowrowcount var cell1 rowinsertcell0 var element1 documentcreateelementinput element1type checkbox element1namechkk cell1appendchildelement1 var cell2 rowinsertcell1 cell2innerhtml rowcount var cell3 rowinsertcell2 var element2 documentcreateelementinput element2type text element2name subjectk cell3appendchildelement2 var cell4 rowinsertcell3 var element3 documentcreateelementinput element3type text element3name markk cell4appendchildelement3 var cell5 rowinsertcell4 var element4 documentcreateelementinput element4type text element4name markak cell5appendchildelement4 var cell6 rowinsertcell5 var element5 documentcreateelementinput element5type text element5name markbk cell6appendchildelement5 var cell7 rowinsertcell6 var element6 documentcreateelementinput element6type text element6name totalk cell7appendchildelement6 function deleterowtableid try var table documentgetelementbyidtableid var rowcount tablerowslength forvar i0 irowcount i var row tablerowsi var chkbox rowcells0childnodes0 ifnull chkbox true chkboxchecked tabledeleterowi rowcount i catche alerte forvar j1 jrowcount j var mytable documentgetelementbyidtableid mytablerowsjcells1innerhtml j function sumtableid var table documentgetelementbyidtableid var rowcount tablerowslength forvar i1irowcounti tablerowsicells6namevaluetablerowsicells3namevalue tablerowsicells4namevalue tablerowsicells5namevalue scriptalso the first row does not get deleted in firefox that works only in internet explorer facepalmwhat should i do,['javascript'] +490440,django log filter for slow sql queries i am currently logging all sql queries thanks to the following logging settingslogging version 1 thisable existing loggers false filters require debug false djangoutilslogrequiredebugfalse formatters standard format asctimes levelnames nameslinenos messages datefmt dby hms handlers mail admins level error filters require debug false class djangoutilslogadminemailhandler console logging handler that outputs log messages to terminal class loggingstreamhandler level debug message level to be written to console logfile leveldebug classlogginghandlersrotatingfilehandler filename ospathjoinospathdirnameospathdirnameospathabspath file log logfile maxbytes 50 backupcount 2 formatter standard loggers djangorequest handlers mail admins level error propagate true djangodb handlers logfile level debug propagate false django also has database level logging what i actually get in my logfile is14jun2013 135419 debug djangodbbackends51 0 select django content typeid django content typename django content typeapp label django content typemodel from django content type where django content typeapp label sites order by django content typename asc argsusitesi would like to filter only queries that takes above 300ms to completehow should i write the filters section of my logging configuration and what would look like the class that do the filtering,['sql'] +490450,maximum amount of errors in csharpcodeprovidercompileassemblyfromfile i use csharpcodeprovider to compile instant plugins for my appright now it is possible to try to compile a file that looks good but generates many errors for example a c code glued with a binary file there are many characters that are treated with error cs1056 unexpected characterthis behaviour is expected but a compilation process of such a malicious file is very time consumingone solution that i find reasonable would be to limit the number of errors after which csharpcodeprovidercompileassemblyfromfile returnsis it possible to set such a limiti do not really want to inspect the file very carefully in the first place if it is possible to avoid,['c#'] +490470,update angular model after setting input value with jquery i have this simple scenario input element which value is changed by jquerys val methodi am trying to update the angular model with the value that jquery set i tried to write a simple directive but it is not doing what i want heres the directivevar myapp angularmodulemyapp myappdirectivetestchange function return functionscope element attrs elementbindchange function consolelogvalue changed this is the jquery part function buttonclickfunction inputvalx and htmldiv ngappmyapp div ngcontrollermyctrl input testchange ngmodelfoo spanfoospan divdivclickmehere is the fiddle with my trycan someone please point me in the right direction thanks,['jquery'] +490488,unit test of html5 file upload is there a way to do a javascript unit test for uploading a file using the html 5 file api for example i have the codeform methodpost enctypemultipartformdata input typefile idfileselect namefileselect multiplemultipleformscript typetextjavascript function fileselecthandlere var files etargetfiles edatatransferfiles at this point files is a filelist object var fileselect documentgetelementbyidfileselect fileselectaddeventlistenerchange fileselecthandler falsescriptso i want to automate this with javascript so i can unit test it so i need to fire the change event and pass the files somehow in the end each file should be a html 5 file object with a custom path that i want,['javascript'] +490489,randomly pick element in array then remove from the array i have an array of phrases i would like to randomly pick phrases from the array in a loopi do not want to pick the same phrase more then once in the loopi thought i could randomly pick the phrase and then delete it before the next loop php fori0 i16 i phrases arrayhello sailoracid testbear gardenbotch a jobdark horse in the redman uppan outquid pro quorub it inturncoat yes manall wetbag ladybean feastbig wig ran num array randphrases ran phrase phrasesran num unsetphrasesran phrase echo ran phrasern echo countphrasesrn is it possible to randomly pick a different phrase from the array on each loop,['php'] +490494,integer contains using linq i am having some difficulty writing a linq query that will check whether the consecutive digits in an integer are contained in the primary key of a table so suppose there is a table called employees with a primary key on the column employeesid suppose this primary key is of sql server datatype int i would like to write a linq query using entity framework code first that will return all employees whose primary key contains the string 456 something likestring filter 456var results from e in mydbcontextemployees where eidcontainsfilter select ethe problem is that the contains method is not offered for integer datatypes in c,['c#'] +490515,android studio suddenly cannot resolve symbol r i was having a project open in android studio it was generated by the wizard and working finei did some small changes to activity mainxml and when i changed back to mainactivityjava i get the error in several places that it cannot resolve r i might have done something to cause this but ia m not sure what since it appered when i edited the xmldoes anyone know what might be the solution to this i can find the rjava in rreleasepackegecom and it looks fine,['android'] +490527,laravel 4 authattempt always returns false i am trying the laravels auth class but everytime i attempt to log in a user the method returns false heres my coderoutesphproutegetnewuser function return viewmakeregisterroutepostnewuser function name inputgetname email inputgetemail password hashmakeinputgetpassword user new user username name useremail email userpassword password usersave routegetlogin function return viewmakelogin routepostlogin function user array email inputgetemail password hashmakeinputgetpassword if authattemptuser return redirectintendeddashboard return ok else return wrong viewsloginbladephp formopenarrayurl login method post h1loginh1 p formlabelemail email formtextemail br formlabelpassword password formpasswordpassword br p p formsubmitlogin p formclose configauthphpreturn array driver eloquent model user table users reminder array email emailsauthreminder table password reminders the database has the email password fields and the password field is varchar60whenever i send the login info to login it returns me wrongi really cannot see whats wrong here,['php'] +490547,python and numba for vectorized functions good day i am writing a python module for some numeric work since there is a lot of stuff going on i have been spending the last few days optimizing code to improve calculations timeshowever i have a question concerning numbabasically i have a class with some fields which are numpy arrays which i initialize in the following waydef initself a numpyarange0 selfmax i 1 selfvibr energy selfcalculate vibr energyadef calculate vibr energyi return numpyexpselfharmonic i selfanharmonic i 2so the code is vectorized and using numbas jit results in some improvement however sometimes i need to access the calculate vibr energy function from outside the class and pass a single integer instead of an array in place of ias far as i understand if i use numbas jit on the calculate vibr energy it will have to always take an array as an argumentso which of the following options is better1 create a new function calculate vibr energy singlei which will only take a single integer number and use numba on it too2 replace all usages of the function that are similar to this onemyclasscalculate vibr energy1with thistmp nparray1myclasscalculate vibr energytmp0or are there other more efficient or at least more pythonic ways of doing that,['python'] +490730,how to add readonly inline on django admin i am using django 14 and i have a many2many field so when creating the admin site i wanted to add this field as an inline here is some codeclass summaryinlineadmintabularinline model parsererrorsummariesthroughclass myclassadminadminmodeladmin list thisplay classifier name err count supported fields classifier name err count err classifier supported inlines summaryinline readonly fields classifier err countso my question is how can i make the inline field readonly,['python'] +490762,iterating thru object properties produces different results in different browsers i am creating a very basic object in javascript and looping thru its properties thisplaying property namevar name a dataa b datab c datac d datad e datae for var propname in name documentgetelementbyidresultinnerhtml propname nbspin ie and firefox it produces expected resulta b c d e but in chrome same code produces0 1 2 3 4 5 6 7 8 9 10 11 12 13 14any idea why does keyword name hold some significance in chrome,['javascript'] +490775,how to copy table between two models in mysql workbench i am doing some databese thing i need copy one table from one model to another but i try many ways there no effectis there any way for doing this,['mysql'] +490851,how to expand msexplorer to automatically handle connected files sidecar files xmp belonging to jpg if you locally save a hmtl page using firefox or ms internet explorer you will get a html file and a sidecar folder containing images that belongs to the pageif you move the html file using windows explorer the related sidecar folder is moved tooi want to implement a similar behavior for xmp sidecar files that belong to jpg images and contain infos about the picture similar to exifexampleusing windows explorer if i move testhtml to a different directory the sidecar folder testdateien is moved too on a german windows 7i want to implement similar if i move testjpg i also want to move testxmpdoes anybody know how this can be done is there already a solution for this can this be done with a kind of plugin do i have to implement a service can this be done in cdotnet update added the microsoft term connected files to title,['c#'] +490933,use of deleted functions in c here is a class i have createdclass a private some private data members 2 const integers 2 integers 2 const strings public ctor dtor void fconst a in the constructing of every object of this class there are no explicit dynamic allocations only primitive types assignmentsby no explicit dynamic allocations i mean other than how string class handles memorywhen i try thisvoid fconst a item do some thing this item do other stuff i get the following erroruse of deleted function a aoperatorconst a now i know that the compiler is supposed to provide me a default assignment operatorand my question is why the compiler refers to it is default assignment operator as a deleted function and how do i fix this without assigning all the data member functions manually thanks a lotgal,['c++'] +490942,pass arraylist as argument to function i have an arraylist a of integer type i created it as arraylistinteger a new arraylistintegernow i want to pass it as an argument to function analysearray how can i achieve this,['java'] +490948,how to use listlistindex queries in python i tried the following code in python idle but i did not seem to find the elements swapped a 1234567 ifaindex2aindex4 aaindex2aaindex4 aaindex4aaindex2according to the code it should reverse the positions of 2 and 4 correct me if i am wrong,['python'] +490949,c win32 console color i know a bit how to do colors in win32 c console but it is not really efficiant for example systemcolor 01slows down a lot on your process also handle h getstdhandle std output handle word woldcolorattrs console screen buffer info csbiinfo first save the current color information getconsolescreenbufferinfoh csbiinfo woldcolorattrs csbiinfowattributes set the new color information setconsoletextattribute h foreground red works great but it does not have much colors also foreground red is darkredso what i want to ask is not there a way like clr property consoleforegroundcolor set so you can use any color from the consolecolor enum,['c++'] +490976,using shared ptr in c interfaces i have a c library that i am porting to c that makes heavy use of manually referencecounted structs i have considered using shared ptr to automatically handle the reference counting but i also want to maintain the c api the old signatures look something like thisobject object createvoidobject object retainobject ovoid object releaseobject oif i use shared ptr is there any way to effectively expose this manual reference counting in a c api,"['c++', 'c']" +490981,how are global variables in shared libraries linked suppose i have shared library with this function where i is some global variableint foo return iwhen i call this function from multiple processes the value of i in each process is independent on the other processesthis behavior is quite expectedi was just wondering how is usually this behavior implemented by the linker from my understanding the code is shared between processes so the variable has to have the same virtual address in all address spaces of every program that uses this library that condition seems quite difficult to accomplish to me so i guess i am missing something here and it is done differentlycan i get some more detailed info on this subject,"['c++', 'c']" +490987,pandas nested sort and nan i am trying to understand the expected behavior of dataframesort on columns with nan valuesgiven this dataframein 36 dfout36 a b0 1 91 2 nan2 nan 53 1 24 6 55 8 46 4 5sorting using one column puts the nan at the end as expectedin 37 dfsortcolumnsaout37 a b0 1 93 1 21 2 nan6 4 54 6 55 8 42 nan 5but nested sort does not behave as i would expect leaving the nan unsortedin 38 dfsortcolumnsabout38 a b3 1 20 1 91 2 nan2 nan 56 4 54 6 55 8 4is there a way to make sure the nans in nested sort will appear at the end per column,['python'] +491047,why is string abbreviated into a in standard c library function names standard c utility library stdlibh has these function namesstring as aatofatoiitoastring as strstrtoulstrtolstrtodwhy is a string sometimes called an a and sometimes called an str,['c'] +491121,css suggestion maxright or workaround are there plans to add this to cssminright10 maxbottom100px something like div styleminleft10px minright10 maxleft1200px positionfixed divis there any workaround to apply today answers may include javascript jquery plugins etcfor some backgroundour fixed div in the example above will at 1280 windowwidth be starting at 10 128px from the right but not starting earlier than 10px from the left thus being at most 152 pixel wide limited by the horizontal positions 10px and 1152px with equal gap to those marks if that div is within another with a centered align if instead you try div stylearight10left10px maxwidth calc9010 positionfixed not the same will happend but the maxwidth will be forced always and our div will be forced to be be both 10px from left and 10 from right even when it is content actually wants just way fewer pixels widthand to explain why now also maxleft1200px is necessary if the windows width will be greater for example 1600px then of course again the min gap to the right end of the windows will be 10 160 pixel and to the left 10 so the maxwidth of the the div will result in 440px but what if it only has 100px today then we additionally want to make sure it starts somewhere between 10 and 1200 from the left and not only 10 from the right even if the inherited align should be acentered or aright and the div just including 10px of content that shall not result in it to be in 1235px thistant from the left or even 1430px but not at most 1200px,['css'] +491125,how to use exception manager enterprise library 60 when using enterprise library 60 this error occurs in the code belowbool rethrow exceptionpolicyhandleexceptionex replacepolicy1must set an exceptionmanager in the exceptionpolicy class using the setexceptionmanager methodin enterprise library 50 this code workedpublic static bool handleexceptionexception exception string policyname exceptionmanager exmanager enterpriselibrarycontainercurrentgetinstanceexceptionmanager exceptionpolicysetexceptionmanagerexmanager bool rethrow exceptionpolicyhandleexceptionex replacepolicy1 return rethrowbut in enterprise library 60 the enterpriselibrarycontainer class is not foundi want get instance of exceptionmanagerhow do i solve this problem,['c#'] +491163,error publishing to tomcat v60 server at localhost i wave problem with tomcat when i try to run a jsf page i get next errordetails publishing the configuration error copying file to cprogram filesapache software foundationtomcat60backupcatalinapolicy cprogram filesapache software foundationtomcat 60backupcatalinapolicy the system cannot find the path specified cprogram filesapache software foundationtomcat 60backupcatalinapolicy the system cannot find the path specified error copying file to cprogram filesapache software foundationtomcat 60backupcatalinaproperties cprogram filesapache software foundationtomcat 60backupcatalinaproperties the system cannot find the path specified cprogram filesapache software foundationtomcat 60backupcatalinaproperties the system cannot find the path specified error copying file to cprogram filesapache software foundationtomcat 60backupcontextxml cprogram filesapache software foundationtomcat 60backupcontextxml the system cannot find the path specified cprogram filesapache software foundationtomcat 60backupcontextxml the system cannot find the path specified error copying file to cprogram filesapache software foundationtomcat 60backupserverxml cprogram filesapache software foundationtomcat 60backupserverxml the system cannot find the path specified cprogram filesapache software foundationtomcat 60backupserverxml the system cannot find the path specified error copying file to cprogram filesapache software foundationtomcat 60backuptomcatusersxml cprogram filesapache software foundationtomcat 60backuptomcatusersxml the system cannot find the path specified cprogram filesapache software foundationtomcat 60backuptomcatusersxml the system cannot find the path specified error copying file to cprogram filesapache software foundationtomcat 60backupwebxml cprogram filesapache software foundationtomcat 60backupwebxml the system cannot find the path specified cprogram filesapache software foundationtomcat 60backupwebxml the system cannot find the path specifiedwho have same error how to solve it i try few hours but no result i have switch the location and set use tomcat installations butalso no result,['java'] +491168,android studio local path does not exist i imported my eclipse project into android using gradleat first i had problems with rjava but i resolved them by adding gen folder as sources in project settingshowever even though android studio does not show any errors any more when i am trying to deploy the project onto my android device i get the errorwaiting for devicetarget device 01c47c94e112d5fbuploading filelocal path cusersszymoneclipseandroid appbuildapkandroid appdebugunalignedapkremote path datalocaltmpszym10androidapplocal path does not existi checked my android app folder and there is no build folder that is true but why did not android studio generate iti found someone had a similar problem here however i have no idea how to run the gradlew packagedebug in android studio any ideas,['android'] +491175,obtaining length of list as a value in dictionary in python 27 i have two lists and dictionary as follows var11234 var2567 dict1var12var2i want to find the size of the mutable element from my dictionary ie the length of the value for a keyafter looking up the helpdict i could only find the function to return number of keys ie dict len i tried the java methodhoping that it could work ie lendictitems0 but it evaluated to 2i intend to find thislength of value for first key 4length of value for second key 3when the lists are a part of the dictionary and not as individual lists in case their length is lenlistany suggestions will be of great help,['python'] +491189,is it okay to make integerkeyed maps in java just like in title is it okay to make something like thishashmapinteger object foo new hashmapor maybe there is better container that allow adding values at any index when saying better i mean having better performance and then having less ram usagearraylistobject bar new arraylistbaradd10 0 new objecta want to do something like in this code above but this of course does not work with arraylist the list that i want to make is sparse the indexes are spread that is why i was thinking about hashmap and not arraylistregards,['java'] +491195,building shared libraries in subdirectories i am trying to build an r package that uses some c code i have a c library that is compiled into an executable that can be called from the command line there is a makefile associated with it i am trying to grok the information here where it saysif you want to create and then link to a library say using code in a subdirectory use something like phony all mylibs all shlib shlib mylibs mylibs cd subdir make be careful to create all the necessary dependencies as there is a no guarantee that the dependencies of all will be run in a particular order and some of the cran build machines use multiple cpus and parallel makesif i create a new subdirectory of the src folder in my package called somelibrary with the code and makefile unchanged and in turn in the original makevars file for my package i add the above code unchanged then i will be able to build that shared library to be exported using usedynlibedit 1following information here i changed the makefile to create a shared library by adding cflag fpic g o3 ldflags sharedhowever this leads to the problem that the so file is not exported directly to the libs directory of the package if i hard code the path into the target then the file is sent to the libs directory of the package this is all by the way of calls to r cmd install mypackage edit 2lastly i would like to know how to make calls to the shared library given that it has a main method that i could call from the command line executablewhat is the procedure to expose this to the r namespace so that it can be called via callps please let me know if i should make the last bit a separate question,['c'] +491217,tableview not working uiviewcontroller tableviewnumberofrowsinsection unrecognized selector sent to instance i am trying to init a uitableview using xib but when i run the app in simulator the below exception is thrown20130616 104048552 coredataexample60661c07 uiviewcontroller tableviewnumberofrowsinsection unrecognized selector sent to instance 0x81765a020130616 104048554 coredataexample60661c07 terminating app due to uncaught exception nsinvalidargumentexception reason uiviewcontroller tableviewnumberofrowsinsection unrecognized selector sent to instance 0x81765a0below the steps that i have followed trying to start the tableviewadd uitableviewdelegate and uitableviewdatasource in my viewcontrollerinsert the tableview into a view in my viewcontrollerxibcreate datasource and delegate in it filess owner pressing control key and draging the mouses arrow from component to files owner and selecting the option delegate for exampleimplement the methods nsintegertableviewuitableview tableview numberofrowsinsectionnsintegersection and uitableviewcell tableviewuitableview tableview cellforrowatindexpathnsindexpath indexpath in my viewcontrollermbelow the implemetation of two methods nsintegertableviewuitableview tableview numberofrowsinsectionnsintegersection return 10 uitableviewcell tableviewuitableview tableview cellforrowatindexpathnsindexpath indexpath uitableviewcell cell nil static nsstring identifier identifier cell tableview dequeuereusablecellwithidentifieridentifier ifcell nil cell uitableviewcell alloc initwithstyleuitableviewcellstylesubtitle reuseidentifieridentifier celltextlabeltext ola celldetailtextlabeltext subtitle cell setaccessorytypeuitableviewcellaccessorydetailthisclosurebutton return cellviewcontrollerh belowinterface cdemainviewcontroller uiviewcontroller uitableviewdelegate uitableviewdatasource uitableviewcell tableviewuitableview tableview cellforrowatindexpathnsindexpath indexpath nsintegertableviewuitableview tableview numberofrowsinsectionnsintegersectionend,"['ios', 'objective-c']" +491264,overlay a backgroundimage with an rgba color with a css3 transition earlier today i asked overlay a backgroundimage with an rgba backgroundcolor my goal is to have a div with a backgroundimage and when someone hovers the div the backgroundimage gets overlayed with an rgba color in the answer a solution with after was giventhediv backgroundimage urlsomeurlthedivhoverafter content position absolute left 0 right 0 top 0 bottom 0 backgroundcolor rgba05i now would like to have the same but with a css transition i would like the background color to fade in i tried adding transition all 1s to the thediv css but that did not work i also try to add it to thedivhover and thedivafter but that did not work eitheris there a pure css way to add a fading in overlay to a div with a backgroundimage,['css'] +491416,how to parse a string and return a nested array i want a python function that takes a string and returns an array where each item in the array is either a character or another array of this kind nested arrays are marked in the input string by starting with and ending with thus the function would act like this1 fooabc a b c2 fooabc a b c3 fooabc a b c4 fooabc error closing bracket is missing5 fooabc error opening bracket is missing6 fooabc error opening bracket is missingnote i would prefer a solution that is purely functional,['python'] +491449,what are the expression syntax over types c support i was working with a templated class which takes a set of integers the code was liketemplateunsigned idxstruct work then i realized user may need to provide either a set of integers or a range of integers so i changed the syntax little to support instantiation likeworkindexes1324 instead of work1324workspan14 same as work1234 while in c we have large number of operators and can be used to formulate exotic expression templates say boostxpressive boostlambda boostspirit etc possibilities for type manipulation is much lessin a boostcon keynote by sean parent he noted one still can not write pairint to denote a pair of integers in my persinal library i made a syntax like tupleint3 to denote a tuple of 3 integers instead of writing a tuple with 3 int in the type arguments noting that i do not write a raw array as tuple argument anywhere note stdarrayint3 is not same as the above as stdarray can not store references while tuple can say stdtupleintintint is possibleso i want to know what are the different kind of type expressions i can write so far i can think of object type function type reference type withwithout cv modifiers pointers etc eg templateclass t struct tpl using t1 tplintsimple type function can have function pointerreference also eg voidintfloat or voidintfloat using t2 tplvoidintfloat array can have pointer reference also eg int4 or int 4 using t3 tplint4 using t4 tplint using t5 tplint constwith cv modifiers using t6 tplintwith pointer using t7 tplintwith reference or using t8 tpltplint template itself using t9 tplvoid variadic functions using t10 tplr c pointer to memberbut i believe many more are possiblenote this question is purely theoretical i just want to know all kinds of syntax i can write inside as type argument and not about the readabilitymorality aspect of it or even how can i implement some of the examples i had given like the work class,['c++'] +491454,char 0 escape sequence what does it mean i am reading this examplethe real hello world for cudawhat does the 0 in char str16 hello 0stand fori am not sure why the 16 char str has hello inside it and then all zeroes then this is not a global variable how can i be sure that it just contains zeroes,"['c++', 'c']" +491482,add a dynamic div on click i have a requirement to add multiple input boxes to enter the data initially there will be only one input box and there is an add button next to each generated input boxes to generate multiple text boxesif you look at my fiddle there are 3 levels of text boxes in 1st level it has option to enter only 1 level of data but when it comes to level 2 there should be an option to create second level of same parent block so that we can enter the sub data of the main heading for example if i write state name then i should be able to enter sub categorieshere is the code for the 1st level menu documentreadyfunction radioclickfunction testhide var show thisattrdatashow showshow300 sorthide filtr filtr filtronclick add function thisclosestloopcloneappendto thisclosesttest sortshow filtronclick del function thisclosestloopremove 1lev 2lev 3levhide for sort updown function moveupitem var prev itemprev if prevlength 0 return prevcsszindex 9csspositionrelativeanimate top itemheight 250 itemcsszindex 10cssposition relativeanimate top prevheight 300 function prevcsszindex csstop cssposition itemcsszindex csstop cssposition iteminsertbeforeprev function movedownitem var next itemnext if nextlength 0 return nextcsszindex 9cssposition relativeanimate top itemheight 250 itemcsszindex 10cssposition relativeanimate top nextheight 300 function nextcsszindex csstop cssposition itemcsszindex csstop cssposition iteminsertafternext filtrsortable items loop thistance 10 documentonclick buttonsort function var btn this var val btnval if val up moveupbtnparentsloop else movedownbtnparentsloopfiddlerequired result how to clone the classfiltr div as second level panel which works exactly the same as 1st level panelexpected code structure should be like this div classfiltr well clone this one div classtest id2lev div classloop button valueup clasortupbutton button valuedown clasortdownbutton input typetext button classbtn delxbutton button classbtn addaddbutton button classbtn levelbuttonneed to add this div here div classfiltr well clone this one div classtest div classloop button valueup clasortupbutton button valuedown clasortdownbutton input typetext button classbtn delxbutton button classbtn addaddbutton div div here divneed to add this div here div div here div,"['javascript', 'jquery']" +491512,modify connect timeout period i have done a bit of searching and cannot seem to find the answer i am looking for the only answers i could find were to use select to see if the socket had timed out which is what i am already doingwhat i want to know is there anyway to change the length of time before connect would timeout i am currently using select which returns with errno set to einprogress until eventually returning with etimedout is there anyway i can change the amount of time it takes before this etimedout would occur currently it happens after about 60 seconds i have tried adjusting the timeout value i pass into the select call however this only affects how long it takes before select will time out,"['c++', 'c']" +491517,how to set volatile array to zero using memset volatile uint8 t reset mask768 0now i am setting the values of this array elements to 1 during one of internal operationsin another functional call i need to set all the elements of this array to 0 one way is by using for loop but i believe better way to assign all the elements of array is by using memset memsetreset mask 0 sizeofreset maskbut i am getting this error cast from type volatile uint8 t aka volatile unsigned char to type void casts away qualifiersin case we cannot use memset here is there a better way to set all elements of this volatile array in one go,['c++'] +491532,how to map func closure entries to variable names i have a lambda object that is created in this functiondef add url ruleself rule endpointnone view funcnone options selfrecordlambda s sadd url rulerule endpoint view func optionsusing func closure of the lambda function object i can access the closure scope of the lambda functioncell at 0x3eb89f0 str object at 0x2fb4378 cell at 0x3eb8a28 function object at 0x3cb3a28 cell at 0x3eb8a60 str object at 0x3ebd090 cell at 0x3eb8b08 dict object at 0x3016ec0a closer look at the cell contents attribute of each cell object shows me this ccell contents for c in funcfunc closurecategorythisplay function indicowebflaskutilrhcategorythisplay categid that lambda function was created by this calladd url rulecategid categorythisplay rh as viewrhcategorythisplayas you can see the order does not match the argument order of the function or the order in which the arguments are used inside the lambda while i could easily find out which element is what based on its typecontent i would like to do it in a cleaner wayso my question is how can i associate it with their original variable names or at least positions in case of function arguments,['python'] +491606,mysql sort category according to parent id this is the table structureid parent id name1 0 bmw2 0 mercedez3 0 porsche4 1 3 series5 2 e606 1 5 series7 3 cayennehow can i show the table asbmw3 series5 seriesmercedeze60porschecayenne the above table shows ascending id followed by parent id associated with that id then go to second id and so on i need in a single query is it possible to do as such,"['mysql', 'sql']" +491652,check if column is not null i have a column in my db which is currently defined as not nulli would like to update this column to allow nullsi have the following script to do this however i would like to check first if the column is already null or not null as it may have been changed previously alter table dboaud alter column actname nvarchar50 nullany help appreciated,['sql'] +491683,validating nonprivate ip addresses with php i am trying to check whether or not an ip address is an internalonly ie private ip but i am getting a curious resultfilter var1731946694 filter validate ip filter flag no priv range returns 1731946694filter var19216801 filter validate ip filter flag no priv range returns falsefilter var127001 filter validate ip filter flag no priv range returns 127001surely 127001 counts as a private ip i found this bug report from 2010 which reports this as an issue but it is marked as fixed is this a regression or am i misunderstanding what this filter does i am using php 546,['php'] +491721,does any library exist which provides a fluent way to construct java format strings the syntax for javas format strings can get complicated for example 110s210s320snit would seem to be ripe for someone to create a fluent dsl to aid with the construction of these format strings similar to what jooq does for sqldoes such a thing exist,['java'] +491759,how to restore a builtin that i overwrote by accident i accidentally overwrote set by using it as a variable name in an interactive python session is there any way that i can get access to the original set function without just restarting my session i have so much stuff in that session that i would rather not have to do that although of course i can if necessary,['python'] +491766,multiple transforms using compass i am in the case where i have multiple transforms on one element so my question is how do you translate this into compass while keeping the named transforms webkittransform translatey100 scale05 moztransform translatey100 scale05 transform translatey100 scale05 mstransform translatey100 scale05something like include translatey100 scale05thank you,['css'] +491777,fitting iframe inside a div i am trying to fit an iframe inside a div my problem is that i cannot seem to get it to nest to 100 of the width of the div i need to specify pixel width of the iframei would like the iframe to be inside the div so that if the div is resized by a smaller browser the iframe gets resized toothis is my codediv classrowfluid div claspan9 idstandard div classheaderbox p classheader bla bla headerp div div idwrap iframe idframe srcframeborder0iframe div divmore things in the rowdivand csswrap width 1130px height 100 padding 0 overflow hidden positionrelativeframe width 100 height 100 border 1px solid black positionrelative frame zoom 075moztransform scale075moztransformorigin 0 0otransform scale075otransformorigin 0 0webkittransform scale075webkittransformorigin 0 0below is what happenswhen the browser is resized,"['css', 'html']" +491794,error refreshing iventory querying prices of items response 6error i am facing exactly same problem asinapp billing v3 unable to query items without network connection or in airplaneflight modeit do not always occur you need to switch your phone to airplane mode or turn off wifi wait for several hour only the problem will occur the following error message will be shownfailed to query iventory iabresult error refreshing iventory querying prices of items response 6errorauthor suggested usingliststring skulist new arrayliststringskulistaddmy sku name1skulistaddmy sku name2mhelperqueryinventoryasynctrue skulist mgotinventorylistenerto solve the problemhowever it does not work for me same problem still occurany workaround on this problem thanks,['android'] +491819,speed up mouse wheel in jscrollpane jquery i have a div with a fixed height and in it a ullist and many liitems i apply to the div a jscrollpane for which i want to customize the appearance of the scrollbar my code is likefunction mydivjscrollpane showarrows true arrowscrollonhover true wheelspeed 120 as jscrollpane i use the scripts of and it is kind of working but the speed of the mouse wheel velocity of scrolling is much too slow although i tried to set the speed up as you can see in my example abovedoes anybody has had the same effect and can give me a hint how i can speed it up,['jquery'] +491823,what are the advantages of using data rather than x prefix for custom attributes angularjs documentation says optionally the directive can be prefixed with x or data to make it html validator compliantexample markupno prefix input ngmodelnamedata input datangmodelnamex input xngmodelnamethe x prefix is faster to type than data but the tutorials i have seen used either no prefix or data so my question is are there any reasons i might want to use data rather than x,['html'] +491859,compare properties automatically i want to get the names of all properties that changed for matching objects i have these simplified classespublic enum persontype student professor employee class person public string name get set public persontype type get set class student person public string matriculationnumber get set class subject public string name get set public int weeklyhours get set class professor person public listsubject subjects get set now i want to get the objects where the property values differlistperson oldpersonlist listperson newpersonlist listdifference getdifferencesoldpersonlist newpersonlistpublic listdifference getdifferenceslistperson oldp listperson newp how to check the properties without casting and checking for each type and individual property can this be done with reflection even in listsin the end i would like to have a list of differences like thisclass difference public liststring changedproperties get set public person newperson get set public person oldperson get set the changedproperties should contain the name of the changed properties,['c#'] +491872,android is navigation drawer from right hand side possible according to this doc it does not say if it is possible to implement drawer from right hand side is it even possible,['android'] +491884,make sublime text treat i have been doing a lot of work with knockout templates lately and i have been using sublime to do it one thing that i have noticed though is that when using a template which needs to be defined in a block like thisscript typetexthtmlscriptit treats the contents as javascript which means i am missing out on a lot of html tools which i have installed i would like to make it treat that content as html instead of javascript is there any setting which i could use to do this,['html'] +491982,android ndk r8e missing stdlibh i am testing some native library code with the android ndk androidndkr8e the native library is being built from its makefile rather than androids modified build system using the makefile rather than androids build system is a project requirement openssl and fipsthe library needs to be built for api 14 android 40 api 16 android 41 and api 17 android 42 though its using the librarys makefile we are using the prebuilt toolchain from androidndkr8elinuxx86 64 armlinuxandroideabi47 and friendsit appears stdlibh is missing from 2 of the 3 apis for example below is an attempt to compile for api 17armlinuxandroideabigcc i i iinclude dopenssl fipscanister fpic dopenssl picdopenssl threads d reentrant ddso dlfcn dhave dlfcn h wanoexecstack marcharmv7amandroid ioptandroidndkr8eplatformsandroid17archarmusrincludeboptandroidndkr8eplatformsandroid17archarmusrlib o3 fomitframepointer walldopenssl bn asm mont dopenssl bn asm gf2m dsha1 asm dsha256 asm dsha512 asm daes asmdghash asm c o cryptlibo cryptlibcin file included from cryptlibc1170cryptlibh6220 fatal error stdlibh no such file or directorybased on feedback from auselen and chris i tried to build a toolchain for api 17 it failed android ndk rootbuildtoolsmakestandalonetoolchainsh platformandroid17 installdirandroidtestautoconfig toolchainarmlinuxandroideabi46invalid platform name android17please use platformname with one of android14 android3 android4 android5 android8 android9how does one handle missing headers in the ndk find optandroidndkr8e iname stdlibhoptandroidndkr8eplatformsandroid5archarmusrincludestdlibhoptandroidndkr8eplatformsandroid14archmipsusrincludestdlibhoptandroidndkr8eplatformsandroid14archx86usrincludestdlibhoptandroidndkr8eplatformsandroid14archarmusrincludestdlibhoptandroidndkr8eplatformsandroid9archmipsusrincludestdlibhoptandroidndkr8eplatformsandroid9archx86usrincludestdlibhoptandroidndkr8eplatformsandroid9archarmusrincludestdlibhoptandroidndkr8eplatformsandroid8archarmusrincludestdlibhoptandroidndkr8eplatformsandroid4archarmusrincludestdlibhoptandroidndkr8eplatformsandroid3archarmusrincludestdlibhoptandroidndkr8esourcescxxstlstlportstlportstdlibhoptandroidndkr8esourcescxxstlgnulibstdc46includetr1stdlibhoptandroidndkr8esourcescxxstlgnulibstdc47includetr1stdlibhoptandroidndkr8esourcescxxstlgnulibstdc443includetr1stdlibh,['android'] +491998,php extend method like extending a class i have 2 classclass animal public function walk walk class human extends animal public function walk with2legs this way if i call humanwalk it only runs with2legsbut i want the run the parents walk tooi know i can modify it this wayclass human extends animal public function walk parentwalk with2legs but the problem is i have many subclasses and i do not want to put parentwalk into every child walk is there a way i can extend a method like i extend a class without overriding but really extending the method or is there better alternativesthanks,['php'] +492122,coredata ordered relationships batch unfaulting using nsfetchrequest background batch unfaultingnsfetchrequest allows batch unfault for example use a query of 10 results it would bring all as faults then it would unfault x objects at a time ie index 020 then 2140 etcthis behavior is great when used in nsfetchresultscontroller for a uitableviewdatasource and it allows fast ui scrolling as it does not unfault objects onebyonenow to my problemi am using ordered relationships for lists of objects let us say postssince a post may appear on a lot of lists on my model i cannot store its index in every lists on post entity and use it as a param for ordering resultsas for now i have not found a way for nsfetchrequest to fetch according to this order so i cannot use its batch unfaulting so i am addressing to the relationship with an index and i end up unfaulting onebyone which causes bumpy scrollingis there any way for nsfetchresultscontroller to fetch according to order relationshipsor is there a batch unfaulting api which is not private,['ios'] +492163,using pandas to create dataframe with series resulting in memory error i am using pandas library for remote sensing time series analysis eventually i would like to save my dataframe to csv by using chunksizes but i run into a little issue my code generates 6 numpy arrays that i convert to pandas series each of these series contains a lot of items prcpseriesshape12626172i would like to add the series into a pandas datafram df so i can save them chunk by chunk to a csv filed prcp pdseriesprcpseries tmax pdseriestmaxseries tmin pdseriestminseries ndvi pdseriesndviseries lstm pdserieslstmseries evtm pdseriesevtmseriesdf pddataframedoutfile fdataoutputrun1 strioutdfto csvoutfile header false chunksize 10d nonedf nonebut my code get stuck at following line giving a memory errordf pddataframedany suggestions is it possible to fill the pandas dataframe chunk by chunk,['python'] +492236,android viewpager automatically change page i want to schedule an action to change automatically my viewpager pagesi have triedoverride public void oncreatebundle savedinstancestate superoncreatesavedinstancestate swipetimer new timer swipetimerschedulenew timertask override public void run if currentpage num pages currentpage 0 featureviewpagersetcurrentitemcurrentpage true 100 500but i am always gettingeandroidruntime5381 fatal exception timer0eandroidruntime5381 javalangillegalstateexception must be called from main thread of processi am already in main thread right how can i solve thisthanks for your timeeditthanks for all your answers based on these responses i came across 2 solutionssolution 1 swipetimer new timer swipetimerschedulenew timertask override public void run runonuithreadnew runnable override public void run if currentpage num pages currentpage 0 featureviewpagersetcurrentitemcurrentpage true 500 30solution 2final handler handler new handler final runnable update new runnable public void run if currentpage num pages currentpage 0 featureviewpagersetcurrentitemcurrentpage true swipetimer new timer swipetimerschedulenew timertask override public void run handlerpostupdate 500 30which one is better or they are the samethanks once again,['android'] +492245,c code preprocessing in perl i work on the c code parser in perlat the moment i need to preprocess the codeimplementation of the preprocessing seems to be a lot of work so i am looking for a script or library that will allow to preprocess the filei found the following possibilitiestextcppfiltercppboth of these require cpp which i do not have on my windows machine is there any other options,['c'] +492289,adding masonry to angular without jquery i am trying to get masonry working as an angular directive which is in part documented online although i am having the following issues on the following codehtml codediv ngcontrollergridctrl classgridwrapper div classmasonry div ngrepeatitem in griditems ngclassitemclass h3itemnameh3 img ngsrcitemimage br button ngrepeatbutton in itembuttonsbuttontextbutton div divdivangular directive codeuse strictangularmodulehomecourtarenaappdirectivemasonry function parse return restrict ac link function scope elem attrs elemmasonry itemselector masonryitem columnwidth parseattrsmasonryscope angularmodulehomecourtarenaappdirectivemasonryitem function return restrict ac link function scope elem attrs elemimagesloadedfunction elemparentsmasonrymasonryreload scss codegridwrapper position absolute top 0 left 0 right 0 bottom 0 width auto paddingleft 40 overflowx scroll overflowy hidden masonry position absolute width 2600px maxheight 1080px masonryitem poster float left width 465px padding 15px margin 12px 12px 0 0 boxshadow 1px 1px 4px 3px rgba5025 masonryitem background fafafa height 295px h3 width 100 textalign left fontsize 28px color 3d4a thisplay block img thisplay block padding 50px 0 10px margin 0 auto poster height 631px background 0 position relative h3 color f fontfamily adineuebold fontsize 68px position absolute top 410px left 20px zindex 2 img position absolute left 0 top 0 zindex 1 margin 0 padding 0 button position absolute zindex 2 left 20px top 590px button padding 12px 15px fontsize 15px marginright 10px fontfamily adihausregular color f texttransform uppercase border none background lineargradientto bottom rgba571342021 0rgba3751461 100 after content background urlimgspritepng norepeat 156px 9px width 16px height 16px marginleft 30px thisplay inlineblock then also crucially how my scripts are layered in my index filescript srcscriptsappjsscriptscript srcscriptsdirectivesmasonryjsscriptscript srcscriptscontrollersmainjsscripti keep getting an error in the console which would suggest i am not defining the masonry somewhere correctlyuncaught typeerror cannot call method create of undefinedthen alsotypeerror object object object has no method masonrycan anyone see where i am going wrongi would like to avoid using jquery possibly as there is a newer masonry available that does not use it,['javascript'] +492365,run command on rails console startup is there a way to run a specific command when the rails console starts i would like it to print out whether or not i am connected to the remote or local database in big letters i do not mind writing a custom method to determine thata i am just asking how to write to the console i have seen errors and alerts there beforefor example rails c prints out loading development environment rails 3211using remote database 193p125 001,"['ruby-on-rails', 'ruby']" +492383,insert vs emplace vs operator in c map i am using maps for the first time and i realized that there are many ways to insert an element you can use emplace operator or insert plus variants like using value type or make pair while there is a lot of information about all of them and questions about particular cases i still cannot understand the big pictureso my two questions arewhat is the advantage of each one of them over the otherswas there any need for adding emplace to the standard is there anything that was not possible before without it,['c++'] +492422,check if extended property description already exists before adding so i have a script that adds extended properties some describing a table some describing a column how can i check if the extended property exists before adding it so that the script does not throw an error,['sql'] +492511,rails fields for form not showing up nested form i have created an simple rails project all worked fine until i tried to add a new model paintings that belongs to treatment and an patient that has many paintings through treatment so somehow the nested form i created does not show up i believe it has to do with the controller thanks and greetings from germanytreatments controllerclass treatmentscontroller applicationcontroller def create patient patientfindparamspatient id treatment patienttreatmentscreateparamstreatment redirect to patient pathpatient end def destroy patient patientfindparamspatient id treatment patienttreatmentsfindparamsid treatmentdestroy redirect to patient pathpatient endendand the form for treatments with nested fields for that does not show up form forpatient patienttreatmentsbuild do f div classfield flabel content ftext area content cols 30 rows 10 div div classfield flabel category id fcollection select category id categoryfindall id typ div ffields for paintings do ff div classfield fflabel name tag fftext field name div end div classfield fsubmit nil class btn btnsmall btnprimary div end updateshow site patienttreatmentseach do treatment tr td treatmentcategorytrytyp td td treatmentcontent td td treatmentday td tddiv classarrowdivtd tr tr,"['ruby-on-rails', 'ruby']" +492522,xcode 5 to xcode 4 project run i have a project that i started in ios sdk 6 i downloaded xcode 5 beta with ios 7 and ran it successfullyhowever to submit the project i need to go back to sdk 6 and xcode 4 when i do i get following message for every xib file i have in the projecthow do i fix this so i can compile and run from sdk 6 and xcode 4,['ios'] +492571,jquery full calendar thisplays events next day i am trying to integrate the jquery calendar plugin into my custom cmsmy issue is that events are shown the next day that the original value in database is setthis is how i am retrieving my eventsquery select idavatar titulo as titletexto as name unix timestampstart date as startunix timestampend date as end start date end date from blogs where unix timestampstart date start or unix timestampend date end and post type event and lan lan echo query year datey month datem result mysql queryquery array array i 0 while row mysql fetch arrayresult raw row rawurl blogurls amigablesrawtitlerawid rawstart show prettydatetimerawstart date rawend show prettydatetimerawend date arrayi raw i echo json encodearrayand this is how i am showing them into the jquery calendarcalendariofullcalendar events includesjsoneventsphp eventdrop functionevent delta alerteventtitle was moved delta daysn should probably update your database loading functionbool if bool loadingshow else loadinghide eventmouseover function event jsevent view var item this var image ifeventavatar image img srceventavatar ifitemfindnubelength 0 var info span classnubeh2eventtitleh2image p classtexteventnameppeventstart show br eventend showppa hrefeventurlread moreapspan itemappendinfo ifparseintitemcsstop 200 itemfindnubecsstop 20bottomauto itemparentfindfceventaddclassz0 ifparseintitemcssleft 500 itemfindnubecssright 0leftauto itemparentfindfceventaddclassz0 itemfindnubestoptruetruefadein consolelogparseintitemcssleft eventmouseout function event jsevent view var item this itemfindnubestoptruetruefadeout header left prevnext today center title right monthagendaweekagendaday eventrender functionevent element the problem here is that unix timestampstart date would generate the next day in the calendarex if is stored the start date in day 17 of the month in the calendar will appear in the day 18thand i am not sure what i have missed all this i made it by following their specsany idea where am i failing jquery mysql or timezone settingsediti kind of fixed it byrowstart rowstart 606024 one day so now start date and start make sense together in the calendarplease tell me you know a better solution,"['php', 'javascript', 'jquery']" +492624,dll missing dependencies on windows 7 files i have built a c dll to use from dot net when i run the progran i get an error dll not foundthe dll is there but i checked it with dependency walker and got for the followingapimswincorecoml110dllapimswincorewinrterrorl110dllapimswincorewinrtl110dllapimswincorewinrtrobufferl110dllapimswincorewinrtstringl110dllapimswinshcorescalingl110dlldcompdllerror opening file the system cannot find the file specifiedi did a search apparently these are win 7 files an d i have windows 7 but did not find themwhat can i do i am using vs2010 windows 7,['c++'] +492677,debugging nuget packages symbols with sources not showing i am trying to build out both the nuget packages and symbols for my library i am using teamcity to build the packages then pushing them to my internal symbolsource repoeverything seems to be buildingpackagingpushing fine but when i go to debug into the my nuget package using vs2012 the source code is not correct better yet i cannot find the method names it is showing me anywhere in the librarymy project structuremyproject bin release myprojectdll variousfolders csfilescs variouscsfilescs myprojectcsproj myprojectnuspecin my nuspec file note the v40 and v45 directories are handled on teamcity sidexml version10package metadata idmyprojectid version00version titlemyprojecttitle authorsmeauthors ownerspossibly youowners requirelicenseacceptancefalserequirelicenseacceptance descriptionsweet descriptiondescription releasenotesreleasenotes copyrightcopyright 2013copyright metadata files file srcmyprojectcs targetsrc file srcmyprojectbinreleasev40dll targetlibnet40 file srcmyprojectbinreleasev40pdb targetlibnet40 file srcmyprojectbinreleasev45dll targetlibnet45 file srcmyprojectbinreleasev45pdb targetlibnet45 filespackageinspecting the teamcity produced myproject00nupkglib net40 myprojectdll net45 myprojectdllinspecting the teamcity produced myproject00symbolsnupkglib net40 myprojectdll myprojectpdb net45 myprojectdll myprojectpdbsrc variousfolders csfilescs variouscsfilescsso the problem i assume is that when i push the package up to my internal symbol repo i go look at the file structure it is as followsdata myproject 00 bianaries myproject some hash myprojectdll myprojectpdb myprojecttxt sources empty myproject00nupkgthe sources folder is empty 100 empty i cannot seem to get any cs file into that sources folder but then again i do not know whats really going on between the nuget push to my repo the actual dumping into the data folder and vs2012 magically pulling in the debug symbolsso i am at a complete loss for where to check next,['c#'] +492694,allow uiinterfaceorientationlandscape during uiwebview video playback my iphone app is a portrait orientation only app and in my app i have a uitableview that has a uiwebview in the first uitablecell the uiwebview shows an embedded youtube video when i click on the video to play it enters fullscreen mode what i need to do is allow the user to rotate their device and play the video in landscape mode then when the video is stopped only allow portrait again i setup to listen for the notification when the video enters fullscreen and leaves full screen but i do not know how to programmatically allow the user to rotate the interface orientationso basically i have 2 methods called when the notification is passednsnotificationcenter defaultcenter addobserverself selectorselectoryoutubestarted nameuimovieplayercontrollerdidenterfullscreennotification objectnilnsnotificationcenter defaultcenter addobserverself selectorselectoryoutubefinished nameuimovieplayercontrollerdidexitfullscreennotification objectnilvoidyoutubestartednsnotification notification entered fullscreen code goes herevoidyoutubefinishednsnotification notification left fullscreen code goes herewhat would i put in those 2 methods to allow orientation change only during the video playback,"['iphone', 'objective-c']" +492700,compiler error on java generic interface with a list method i do not understand the compiler error resulting from the following code i define a generic interface see task with two methods u dosomethingstring value and listinteger getids the dosomething method actually uses the generic type as the type of its return value but does not seem to be causing problems the getids method returns a list which is unrelated to the type of task but it is causing problems when using foreach statement to iterate over the return value the following compiler error occurserror incompatible types for integer value taskgetidsrequired integerfound objectit seems that the type erasure on the interface is causing the compiler to forget the declared type on the second method which is unrelated to the generic type or in other words why is the generic type on the interface affecting how the compiler understands the return value on the getids method and specifically in the context of a foreach statementapparently if i get reference to the list outside of the foreach there is no problem but not directlypublic class interfacetest public static void mainstring args task task new mytask no complaints about the type here listinteger values taskgetids getting a compiler error for this line for integer value taskgetids interface tasku you dosomethingstring value listinteger getidsthe implementation of the interface is not necessary to demonstrate the point but i did not want to leave the reference task task null and have answers telling me that is the problemclass mytask implements taskboolean override public boolean dosomethingstring value systemoutprintlnvalue return false override public listinteger getids return arraysaslist 1 2 3 4,['java'] +492854,android studio new project vs new module android studio uses the concept of modules whereas other ides like eclipse use projectshowever as file menu has the option to create a new module as well as a new projectwhat are the differences between these two if anywhich one is recommended to use,['android'] +492933,css3 circle glow like a moon light glow i am trying to create a moon with light glow same as in imagesi have tried but not much successfuli do not wants to use image in website i wants to create only this with css3my circle is creating very small and also glow is in small area i want glow in large radius area kumarezufg6htmldiv spanglowspandivcssdiv margin 20px 10px 10px textalign center fontfamily sansserifspan thisplay inlineblock paddingtop 40px background whitesmoke width 100px height 60px textalign center verticalalign middle webkitboxshadow 0 0 10px f8a50e mozboxshadow 0 0 10px f8a50e boxshadow 0 0 10px f8a50e webkitborderradius 50px mozborderradius 50px borderradius 50px webkittransition boxshadow 4s ease moztransition boxshadow 4s ease mstransition boxshadow 4s ease otransition boxshadow 4s ease transition boxshadow 4s easespanhover webkitboxshadow 0 0 10px red mozboxshadow 0 0 10px red boxshadow 0 0 0 10px red,['css'] +493041,passing multiple columns in mybatis i want to know how do we pass multiple columns in a mybatis association tagfor example i have the following xml snippet in one my mapperxml fileresultmap typecommysitedomaincoursebuildercourses idresultmapwithassmnts extendsbaseresultmap association propertytotalassignmentcnt columncourse id selectselecttotalassgnmentscnt association propertytotalassessmentcnt columncourse id selectselecttotalassesmentscnt see this association association propertysubscription columncourse id selectcommysitepersistencemybatiscoursesubscriptionmapperselectbyusercid resultmapas you can see the association with property subscription has only one column course idi want to pass 2 columns to it and therefore the resultant code how do we do thati tried the following combinations none workedcolumncourse iduser id nullnull are passed as parameters columncourse iduser id nullnull are passed as parameters columncourse idcourse iduser iduser id nullnull are passed as parameters but if i pass single columncourse id or columncourse idworks without any issuesany idea guys,['java'] +493070,how to get column by number in pandas whats the difference betweenmaandp sanyo geslotenout119 time20120801 011 020120801 0510 020120801 001011 020120801 002010 020120801 002510 020120801 003009 020120801 004010 020120801 005009 020120801 010510 020120801 011010 020120801 011510 020120801 012510 020120801 013010 020120801 013509 020120801 014010 020120830 223509 020120830 224510 020120830 225009 020120830 225510 020120830 2309 020120830 230510 020120830 231009 020120830 231510 020120830 232009 020120830 232510 020120830 233509 020120830 234010 020120830 234509 020120830 235010 020120830 235511 0name p sanyo gesloten length 7413 dtype int64andmaand1out120 ltclass pandascoreframedataframegtdatetimeindex 7413 entries 20120801 011 to 20120830 235511data columns total 1 columnsp sanyo gesloten 7413 nonnull valuesdtypes int641how can i get data by columnindexnumberand not by an indexstring,['python'] +493204,is it possible to create a new type that is more dynamic probably not the correct word but i want to create a new type in javascript it would have the simple property that one could do thisvar inst new sometypeinstkey1key2 somethinginstkey1key1key3 somethingbasically you wouldnt have to declare an object literal to extend further it would create one automaticallythis would allow me to build complex structures without having to worry about checking for the existence of a property to extend off ofinstead of doinginstkey1 instkey1key2 dataone could just doinstkey1key2 dataand theinstkey1 would be automatic ie would happen internallythis does have a practical purpose particularly i have a registry pattern which i would use this new type to organize data using a more hierarchical approachalso i see a pattern common in libraries that tests for the existence of an object literal and then creates one if it does not existthis is a common idiom it seems,['javascript'] +493235,angularjs pass filter to directive bidirectional attribute i need to use sublist directive in few places of the page and it should contain sometimes full fields list but sometimes filtered here is my naive approachhtml div ngcontrollermainctrl sublist fieldsfields this one is ok sublist fieldsfields filter rumba this one raises error divjavascriptangularmodulemyapp directivesublist function return restrict e scope fields template div ngrepeatf in fieldsfdiv controllermainctrl functionscope scopefields samba rumba cha cha cha when i try to use filter i am getting this errorerror 10 digest iterations reached abortingis there a solution for this problem,['javascript'] +493236,what is surfaceview surfaceholder surface camera api android i am using camera api and bit confused with the terminologyin simpler terms android needs a view on which the camera preview can be drawn by android sdkapplication writer has to provide a view class to android there are a few restrictions and workaround so to say which i am curios but do not know where to lookso what is the difference between surfaceview surfaceholder and surfaceholder looks like a container to hold the surface but why it is needed can anyone please explain these 3 terms,['android'] +493252,memoryerror on large merges with pandas in python i am using pandas to do an outer merge on a set of about 1020 csv files each csv file has an identifier column id which is shared between all the csv files but each file has a unique set of columns of 35 columns there are roughly 20 unique id rows in each file all i want to do is merge these together bringing all the new columns together and using the id column as the merge indexi do it using a simple merge callmerged df first df first csv file dataframefor next filename in filenames load up the next df merged df merged dfmergenext df onid howouterthe problem is that with nearly 20 csv files i get a memoryerror in the merge operation thrown by pandas i am not sure if this is a limitation due to a problem in the merge operationthe final dataframe would have 20 rows and roughly 20 x 3 60 columns this is large but not large enough to consume all the memory on the computer i am using which has over 20 gb of ram is this size too much for pandas manipulation should i be using something like sqlite instead is there something i can change in the merge operation to make it work on this scalethanks,['python'] +493319,php how to get the base domainurl function url ifisset serverhttps protocol serverhttps serverhttps off https http else protocol http return protocol serverhttp hostfor example with the function above it works fine if i work with the same directory but if i make a sub directory and work in it it will give me the location of the sub directory also for example i just want examplecom but it gives me examplecomsub if i am working in the folder sub if i am using the main directorythe function works fine is there an alternative to serverhttp hostor how could i fix my functioncode to get the main url only thanks,['php'] +493330,c convert from 1 char to string i really did not find any answer that closethe opposite way is pretty simple like str0but i need to cast only 1 char to stringlike thischar c 34string1cthis does not work the string is always emptystring scalso does not workboostlexical caststringintcalso return nullthanks,['c++'] +493340,alembic autogenerates empty flasksqlalchemy migrations i am using alembic to handle migrations for flask alembic revision autogenerate should in theory autogenerate a migration based on changes in my database however alembic is simply generating a blank migration with the above commandthere is a question very similar to this one where the issue was that the proper models werent being imported however i have imported the models from my flask app as shown in envpy import settings from flaskalembic config configget sectionconfigconfig ini sectionfrom start import appfrom models import user item recipient models are imported here from modelspyalembic configsqlalchemyurl appconfigsqlalchemy database uriengine engine from config alembic config configget sectionconfigconfig ini section prefixsqlalchemy poolclasspoolnullpoolas well as imported db metadata in envpy start is the name of my flask apps main filefrom start import dbtarget metadata dbmetadatarunning alembic revision autogenerate m initial rev then generates an empty migration although my flask app would beg to differinitial revrevision id 45296fd29540revises nonecreate date 20130619 173238392268 revision identifiers used by alembicrevision 45296fd29540down revision nonefrom alembic import opimport sqlalchemy as sadef upgrade commands auto generated by alembic please adjust pass end alembic commands def downgrade commands auto generated by alembic please adjust pass end alembic commands edithere is a gist that shows the file structure for my app as well as some additional code it seems the issue is that alembic does not like having the db imported from databasepy without being initialized first in init py however this is not possible when blueprints are used because of cyclical imports explained in this so answer so the question is how can alembic be used when flask blueprints are used as welledit 2i even tried printing dbmetadatasorted tables to make sure the database metadata was being imported correctly sure enough the whole database schema was piped to the terminal so why is alembic generating blank upgradedowngrade functionsedit 3i have concluded that the issue has something to do with the differences of dbinit appapp and db sqlalchemyapp but i am not quite sure what is causing the issue to test this theory i replaced from database import db in envpy to be db sqlalchemyapp probably a bad idea but i wanted to see what would happen for debugging purposesalembic autogenerated and filled the upgrade and downgrade methods except they were reversed upgrade dropped all three of my tables while downgrade created them with all the proper columns and metadata i have no idea why this is but i hope it is helpful to people trying to figure out this problem,['python'] +493363,c is it possible to determine whether a pointer points to a valid object i am learning c and reading c primer there is a question i would like to know the answergiven a pointer p can you determine whether p points to a valid object if so how if not why notthanks,['c++'] +493395,why does the fragments oncreateview oncreate onactivitycreated are called i have an app that deals with fragments and viewpager i have three fragments in a viewpager when you switch between them it always causes the other two fragments to call theirs oncreateview methods how to do it only once only when fragmentactivity is createdi have read some questions and tried the solutions but the fragments still have the same behaviorlistfragment oncreate called twiceoncreate and oncreateview invokes a lot more than required fragments here is some code if it helps you guysmainactivity public class startingactivity extends fragmentactivity implements viewonclicklistener viewpager viewpager circlepageindicator pageindicator button thiscount button qrcode button pay tabhost tabhost public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutstarting layout viewpager viewpager findviewbyidridpager if savedinstancestate null fragment firstpage fragmentinstantiatethis findtovarfragmentclassgetname fragment secondpage fragmentinstantiatethis mainwindowactivityclassgetname fragment thirdpage fragmentinstantiatethis mapactivityclassgetname if firstpage null firstpageisdetached secondpage null secondpageisdetached thirdpage null thirdpageisdetached listfragment viewpagerfragments new arraylistfragment viewpagerfragmentsaddfirstpage viewpagerfragmentsaddsecondpage viewpagerfragmentsaddthirdpage pageadapter pageadapter new pageadaptergetsupportfragmentmanager viewpagerfragments viewpagersetadapterpageadapter pageindicator circlepageindicator findviewbyidridcircle pageindicatorsetviewpagerviewpager pageindicatorsetcurrentitempageadaptergetcount 2 mapactivity public class mapactivity extends fragment implements onmylocationlistener n3 n 343342 private static final string tag mapactivity listaddress addresslist private static final string string location arraylisttorgcentr randomtorgcentr arrayliststring torgcentrnames context context autocompletetextview searchtorgcentr overlaymanager overlaymanager mapcontroller mapcontroller textview textview double longitude double latitude double itemlongitude double itemlatitude override public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate logdtag mapactivity oncreateview view view linearlayout inflaterinflaterlayoutmap layout container false final mapview mapview mapview viewfindviewbyidridmap textview textview viewfindviewbyidridsearchlocation searchtorgcentr autocompletetextview viewfindviewbyidridautocompletetextview mapviewshowbuiltinscreenbuttonstrue mapcontroller mapviewgetmapcontroller context getactivity return view override public void onresume superonresume override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate logdtag mapactivity oncreate public void onactivitycreatedbundle savedinstancestate logdtag mapactivity onactivitycreated context getactivity setrightmapthisplayaddress rightmapthisplayaddress new setrightmapthisplayaddress rightmapthisplayaddressexecutestring location downloadsupermarketsarray supermarketsarray new downloadsupermarketsarray supermarketsarrayexecute overlaymanager mapcontrollergetoverlaymanager overlaymanagergetmylocationsetenabledfalse superonactivitycreatedsavedinstancestate second fragmentpublic class mainwindowactivity extends fragment private static final string tag mainwindowactivity override public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate logdtag mainwindowactivity oncreateview view view relativelayout inflaterinflaterlayoutmain window layout container false if container null return null return view and the third one public class findtovarfragment extends fragment private static final string tag findtovarfragment context context arraylistcategory categories spinner categorycontainer override public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate logdtag findtovarfragment oncreateview view view linearlayout inflaterinflaterlayoutfind tovar main layout container false categorycontainer spinner viewfindviewbyidridcategory return view override public void onactivitycreatedbundle savedinstancestate superonactivitycreatedsavedinstancestate logdtag findtovarfragment onactivitycreated downloadcategory downloadcategory new downloadcategory downloadcategoryexecute logs for mapactivity 0620 110637709 debugmapactivity1290 mapactivity oncreate0620 110637709 debugmapactivity1290 mapactivity oncreateview0620 110638509 debugmapactivity1290 mapactivity onactivitycreatedthen again and again 0620 110753239 debugmapactivity1290 mapactivity oncreate0620 110753239 debugmapactivity1290 mapactivity oncreateview0620 110753429 debugmapactivity1290 mapactivity onactivitycreated0620 110823029 debugmapactivity1290 mapactivity oncreate0620 110823039 debugmapactivity1290 mapactivity oncreateview0620 110823269 debugmapactivity1290 mapactivity onactivitycreatedthank you very much in advance,['android'] +493531,linearlayout animate clips the view clipchildren does not work i am trying to animate the container linearlayout 20dp and btn button 20dp moving them right but they get clipped after the full width of the main linearlayout 40dp i have tried clipchildrenfalse on both but it does not work i cannot use match parent sizes for layouts because it is an overlay app and will block the touches behindany ideasmy layoutlinearlayout androidididmain androidlayout widthwrap content androidlayout heightwrap content androidclipchildrenfalse androidcliptopaddingfalse linearlayout androidididcontainer androidlayout width20dp androidlayout height80dp androidclipchildrenfalse androidcliptopaddingfalse linearlayout imagebutton androidididbtn androidlayout width20dp androidlayout height80dp androidpadding0dp androidbackgrounddrawablebtn linearlayoutmy simplified codesuperoncreate windowmanager windowmanager getsystemservicecontextwindow serviceparams new windowmanagerlayoutparams layoutparamswrap content cannot have match parent layoutparamswrap content cannot have match parent windowmanagerlayoutparamstype system alert windowmanagerlayoutparamstype system overlay windowmanagerlayoutparamsflag not touch modal windowmanagerlayoutparamsflag not focusable pixelformattranslucentlayoutinflater inflater layoutinflatergetsystemservicelayout inflater servicemain linearlayout inflaterinflaterlayoutmainnullbtn imagebuttonmainfindviewbyidridbtncontainer linearlayoutmainfindviewbyidridcontainerbtnsetonclicklisteneronclicklistener windowmanageraddviewmain paramsanimation codepublic void onclickview v btnanimatexby100fsetduration20containeranimatexby100fsetduration20,['android'] +493589,jquery keyup function check if number i am trying to create an input field where the user can only type in numbers this function is already working almost fine for me p firstkeyupfunctionevent ifisnanstringfromcharcodeeventwhich var value thisval thisvalvaluesubstr0valuelength1 but the problem is whe the user holds the key with an character the function keyup is not triggering any ideas how i can forbid this,['jquery'] +493592,converting javautilproperties to hashmap properties properties new propertiesmapstring string map new hashmapstring stringproperties why wrongjavautilproperties is a implement of map and hashmap constructor receive a map type parambut why must convert explicitly,['java'] +493600,select those not found in in list apologies if there is an answer to this already i searched and probably couldnt think up the right keywords to find iti have a table with over 10 tables eg customersi have a query requiring details of a known list of customers eg by customerid 17914100123the in function is what i would like to use for the queryi know to find customers that match the list i would writeselect from customerswhere customerid in 17914100123to find those that are not in the list i would writeselect from customerswhere customerid not in 17914100123questionhow do i find the list of customers that where not returned or did not find a match from the listsuppose the customers table only has 179100 then it would mean 14 and 123 will not be matched how do i find those values that do not find a match i was simplifying in my example my list of items has over 300 ids so using where condition with a long list of or would be cumbersomeclumsy i have thought of combining with self left join and identifying the null paired values which would be 14 and 123is there a more elegant approach,['sql'] +493644,junit testing with gradle for an android project i am trying to get tests junit and robolectric working in an android project but am totally stuck my main problem is that all testing i found with gradle somehow pull in the java plugin and then i get this errorthe java plugin has been applied but it is not compatible with the android pluginsthe only way out i see at the moment is to split into test and app project but i would like to avoid that any exampleshints would be highly appreciatedin the official documentation there is no mention of unittesting only instrumentationtests but i want unittests to get results fast,['android'] +493710,pdo returns integer columns as string in php54 first of all i am aware that there are various similar questions on so such as this and this however when i fetch values from a table integers are always fetched as stringi am using php54 54161dotdeb1 and mysql55 5531dfsg0wheezy1 it is written here that mysql native driver is enabled by default in php540 but i still get string valuesi initialize a pdo object as followstry dsn mysqlhost db host dbname db name charsetutf8 db new pdodsndb userdb pass dbsetattributepdoattr errmode pdoerrmode exception dbsetattributepdoattr emulate prepares false catch pdoexception e headerhttp11 500 exit catch exception e headerhttp11 500 exit when i insert i tried to use executearray format and also used bindvaluepdoparam int but they did not make a differencefor example here is how i insert a new rowpublic function insertlist dbaccount idlist name sql dbprepareinsert into lists values try sqlexecutearraylist name0account id sqlbindvalue1list namepdoparam str sqlbindvalue20pdoparam int sqlbindvalue30pdoparam int sqlbindvalue40pdoparam int sqlbindvalue5account idpdoparam int sqlexecute catch pdoexception e headerhttp11 500 exit catch exception e headerhttp11 500 exit here is how i fetch rows from a tablepublic function fetchlists dbaccount id sql dbprepareselect from lists where account id try sqlexecutearrayaccount id result sqlfetchallpdofetch assoc catch pdoexception e headerhttp11 500 exit catch exception e headerhttp11 500 exit return resultthis did not occur when i tested on xampp for linux 181 which uses php547 i currently use nginx instead of apachewhat is wrong,"['php', 'mysql']" +493753,why are all delegate types incompatible with each other in c all delegate types are incompatible with one another even if they have the same signature as an exampledelegate void d1delegate void d2d1 d1 methodgroupd2 d2 d1 compile time errord2 d2 new d2 d1 you need to do this insteadwhat is the reasoning behind this behaviour and language design decision,['c#'] +493785,python format string unused named arguments let us say i haveaction bond james bondformatbondbond jamesjamesthis wil outputbond james bond next we have action bond james bondformatbondbondthis will outputkeyerror jamesis there some workaround to prevent this error to happen something likeif keyrror ignore leave it alone but do parse otherscompare format string with available named arguments if missing then add,['python'] +493816,ring shape in android i have the following xml in drawable folder circle statusxml to create a ringxml version10 encodingutf8shapexmlnsandroidandroidshaperingandroidinnerradius15dpandroidthickness10dpandroiduselevelfalsesolid androidcolorababf2 shapeand insert the drawable like a background of a relativelayout as nextrelativelayout androidididrelativelayout status androidlayout width100dp androidlayout height100dp androidlayout alignparentrighttrue androidlayout alignparenttoptrue androidbackgrounddrawablecircle status relativelayoutthe problem is in the relativelayout appear a circle not a ring,['android'] +493836,aspnet 35 website missing namespaces in vs 2012 i have an issue that is very similar to this questionaspnet 35 web site stopped importing system namespace by defaulti have an aspnet 35 website not application project in vbnet that compiles fine visual studio 2008 when i open the project in visual studio 2012 or 2010 i get some very weird errors that make it appear as if the system and systemdata namespaces are missing in most cases all of these errors are happening in the app code folder in some instances i can add an imports system to the class and it fixes it i expect this website to compile as soon as i opened it in vs 2012 here is sampling of the errors i am gettingcommandtype is not declared it may be inaccessible due to its protection leveldatetime is not declared it may be inaccessible due to its protection levelhttpcontext is not declared it may be inaccessible due to itsprotection leveli believe vbnet does do some implicit imports but it seems that i am missing them edit the site runs fine in iis and does not produce any compile errorsthe compilation tag of my webconfig file looks likecompilation defaultlanguagevb debugtrue batchfalse assemblies add assemblysystemruntimeserializationformatterssoap version20 cultureneutral publickeytokenb03f5f7f11d50a3a add assemblysystemserviceprocess version20 cultureneutral publickeytokenb03f5f7f11d50a3a add assemblysystemdesign version20 cultureneutral publickeytokenb03f5f7f11d50a3a add assemblysystemwindowsforms version20 cultureneutral publickeytokenb77a5c561934e089 add assemblysystemcore version3500 cultureneutral publickeytokenb77a5c561934e089 add assemblysystemwebextensions version3500 cultureneutral publickeytoken31bf3856ad364e35 add assemblysystemxmllinq version3500 cultureneutral publickeytokenb77a5c561934e089 add assemblysystemdatadatasetextensions version3500 cultureneutral publickeytokenb77a5c561934e089 add assemblysystemsecurity version20 cultureneutral publickeytokenb03f5f7f11d50a3a add assemblysystemdataentity version3500 cultureneutral publickeytokenb77a5c561934e089 add assemblysystemdataentitydesign version3500 cultureneutral publickeytokenb77a5c561934e089 add assemblysystemdatalinq version3500 cultureneutral publickeytokenb77a5c561934e089 assemblies buildproviders add extensionedmx typesystemdataentitydesignaspnetentitydesignerbuildprovider buildproviders compilationi have tried to add system and systemdata but it did not help it should be pulling from the default assemblies from the webconfig file in cwindowsmicrosoftnetframeworkv2050727config as i said before this same solution even though it is a web site project builds in vs 2008editi have narrowed this down to several dlls in my bin folder which each individually are causing this error if i add one of them back the errors reappear one of the trouble dlls is recaptchadll there is nothing special about this dll and it works fine in vs2008 and loads fine in iis,['asp.net'] +493842,why am i not provided with a default copy constructor from a volatile this codeclass x int member volatile x ax b afails with the errorprogcpp67 error no matching function for call to axxvolatile xaprogcpp67 note candidates areprogcpp17 note xxprogcpp17 note candidate expects 0 arguments 1 providedprogcpp17 note xxconst xprogcpp17 note no known conversion for argument 1 from avolatile xa to aconst xais there any way i can get the compiler to generate a volatile copy constructor for me,['c++'] +493914,node npm how to manage globally installed devdependencies i am building a node module with devdependencies that should be globally installed such as jasminenode and jshint what i essentially need is to be able to reference their binaries in my makefile npm scripts section to run tests lint etc in other words i do not wish to require them programmaticallyafter digging around i am still confused on how to handle this1 my first approach was to assume that these modules would be globally installed clarify this in my modules documentation and reference their binaries as globals ie expect them to be globally available this conflicts with this piece of advicemake sure you avoid referencing globally installed binaries instead point it to the local node modules which installs the binaries in a hidden bin directory make sure the module in this case mocha is in your packagejson under devdependencies so that the binary is placed there when you run npm installtaken from this postthis generally sounds right as the aforementioned setup is rather fragile2 my next approach was explicitly including those modules in devdependencies although they are still globally installed on my system and most probably on users contributors systems as well this ensures that appropriate versions of the binaries are there when needed and i can now reference them through node modulesbinhowever i am now in conflict with this piece of adviceinstall it locally if youre going to require ittaken from npm docsregardless of that i do notice that npm install will now actually fetch nothing thisplay no network activity for the globally installed modulesmy questionsare the local versions of globally installed modules that are mentioned in devdependencies just snapshots copies of the global ones taken during npm installis 2 the correct way to go about doing this or is there some other practice i am missing,['javascript'] +494034,creating uiactionsheet i would like to create this kind of menu of course with other menu buttons is there any default viewcontroller representing it or do i have to get images and create this by myself,"['ios', 'objective-c']" +494065,how can i write a fluent datetime value how do i write c code that will allow to compile the following code var date 8september2013 generates a datetime for the 8th of september 2013,['c#'] +494071,how to enable cdi inject in web service jaxrsjersey on java se running grizzly how do i allow cdi injection of resources into restful web service resources i am running on standard java using weld 2 cdi jersey jaxrs and grizzly web server here is my simple web resourceimport trainingstudentstudentrepositoryimport javaxinjectinjectimport javaxwsrspathstudentpublic class studentwebresource inject private studentrepository studentrepository get pathcount producesmediatypetext plain public integer getcount return studentrepositorystudentcount and here is how i have got weld starting my simple web serverpublic class main public static void mainstring args throws exception startcdiapplication public static void startcdiapplication throws exception weld weld new weld try weldcontainer container weldinitialize application application containerinstanceselectwebserverclassget applicationrun finally weldshutdown and the code that i suspect will need to be modified to inform jersey to use weld for cdi inject resolutionimport orgglassfishgrizzlyhttpserverhttpserverimport orgglassfishjerseygrizzly2httpservergrizzlyhttpserverfactoryimport orgglassfishjerseyjacksonjacksonfeatureimport orgglassfishjerseyserverresourceconfigpublic class webserver implements application startup the grizzly http server to make available the restful web services private void startwebserver throws ioexception interruptedexception final resourceconfig resourceconfig new resourceconfigpackagestrainingwebserviceregisternew jacksonfeature final httpserver server grizzlyhttpserverfactorycreatehttpservergetbaseuri resourceconfig serverstart threadcurrentthreadjoin override public void run throws ioexception interruptedexception startwebserver,['java'] +494093,what is the default equality comparer for a set type in the msdn api for the hashset constructor with no arguments it statesinitializes a new instance of the hashset class that is empty and uses the default equality comparer for the set typewhat is the default equality comparer for the set type eg for a custom classbtw is it just me or is the msdn api documentation really a bit thin on explanations i stumble about such questions more than once when reading it,['c#'] +494118,check if element is visible in div i have a div with many lis insidediv lili lili lili lili lilidivtypically when the user is scrolling inside the window some lis get into the overflow and will be hidden i know i can check if an element is in the viewport of the screen with this jquery plugin i would just need this functionality but not for the whole screen but on a single div only so i could update some text when elements are not visibleneed some help thanks in advance,"['javascript', 'jquery', 'html']" +494128,python wildcard subset import we have all been told using from module import is a bad idea however is there a way to import a subset of the contents of module using a wildcardfor examplemodulepymodule var1 hellomodule var2 worldmodule var3 themodule var4 quickmodule var5 brownmodule var10 lazymodule var11 dogmodule var12 nowmodule var13 ismodule var98 thatsmodule var99 allmodule var100 folksdef abs print absolutely useful function s module var1obviously we do not want to use from module import because wed be overriding the abs function but suppose we did want all of the module var variables to be accessible locallysimply putting from module import module var does not work is there a way to accomplish this i used 100 variables as an illustration because doing from module import module var1 module var2 module var3 module var100 would obviously be incredibly unwieldy and wouldnt work if more variables eg module var101 were added,['python'] +494129,android boot completed not received when application is closed i am aware that this question has been asked a lot on the site however i cant seem to find a solution my boot completed receiver is not called when the application is not runningmanifestmanifest xmlnsandroid packagecomexamplestartuptest androidversioncode1 androidversionname10 androidinstalocationinternalonly usespermission androidnameandroidpermissionreceive boot completed usessdk androidminsdkversion8 androidtargetsdkversion17 application androidallowbackuptrue androidicondrawableic launcher androidlabelstringapp name androidthemestyleapptheme activity androidnamecomexamplestartuptestmainactivity androidlabelstringapp name intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity receiver androidnamecomexamplestartupteststartupbootreceiver intentfilter action androidnameandroidintentactionboot completed intentfilter receiver applicationmanifeststartupbootreceiverpublic class startupbootreceiver extends broadcastreceiver override public void onreceivecontext context intent intent logdstartuptest startupbootreceiver intentgetaction if androidintentactionboot completedequalsintentgetaction logdstartuptest startupbootreceiver boot completed if the application is running and i simulate a call withadb shellam broadcast a androidintentactionboot completedthe event is received correctly however if the application is closed the event is not receieved nor is it received at start upi have installed the application then launched it a couple of times to make sure it is registered i am pretty lost on this one so any advice would be highly appreciatededit i can see in the logs that all the other closed applications youtube fileobserver etc receive the boot completed event just not minecheers,['android'] +494133,filter first or join first i originally just wrote a query to find out annual total order number per customer larger than 1in 1query i filtered the result set and join it with another result set which found out customer namecuriously i guess filter first would produce better performance since less results needed to join so i wrote second query to join first and then filter which looks neater than first query result is the same as i expect since all time in the result is lower but i am not sure which time is most important or this case is just a coincident how to think about performance use adventureworks2012set statistics time on1filter firstjoin secondselect tempctemppfirstnametempplastnamefrom select yearorderdate as orderyearcustomeridcountcustomerid as customerorderamtfrom salessalesorderheader group by yearorderdatecustomerid having countcustomerid 1 as tempcjoinselect pfirstnameplastnameccustomeridfrom personperson as p join salescustomer as c on cpersonidpbusinessentityid as temppon tempccustomeridtemppcustomeridorder by tempcorderyeartempccustomeridgo2join firstfilter secondselect yearsoorderdate as orderdatesocustomeridcountsocustomerid as customerorderamtpfirstnameplastnamefrom salessalesorderheader as sojoin salescustomer as c on socustomeridccustomeridjoin personperson as p on cpersonidpbusinessentityidgroup by yearsoorderdatesocustomeridpfirstnameplastnamehaving countsocustomerid1go,['sql'] +494183,during file transfer using smack in android javautilconcurrentexecutionexception no response from client public void receivefile servicethiscoverymanager sdm servicethiscoverymanagergetinstanceforconnection if sdm null sdm new servicethiscoverymanagerconnection logeservice thiscovery sdm sdmaddfeature sdmaddfeaturejabberiqprivacy filetransfermanager manager new filetransfermanagerconnection logeafter manager manager manageraddfiletransferlistenernew filetransferlistener public void filetransferrequestfinal filetransferrequest request new thread override public void run logethread running starting incomingfiletransfer transfer requestaccept file mf environmentgetexternalstoragedirectory logepath mfgetabsolutefiledcim transfergetfilename file file new filemfgetabsolutefiledcim transfergetfilename try transferrecievefilefile whiletransferisdone try threadsleep10l catch exception e loge egetmessage iftransfergetstatusequalsorgjivesoftwaresmackxfiletransferfiletransferstatuserror logeerror transfergeterror iftransfergetexception null transfergetexceptionprintstacktrace logenot null print stack success catch exception e loge egetmessage start public void sndfilefinal string path final string receiver servicethiscoverymanager sdm servicethiscoverymanagergetinstanceforconnection if sdm null sdm new servicethiscoverymanagerconnection logeservice thiscovery sdm sdmaddfeature sdmaddfeaturejabberiqprivacy filetransfermanager manager new filetransfermanagerconnection outgoingfiletransfer transfer managercreateoutgoingfiletransferreceiversmack file file new filepath try transfersendfilefile test file catch xmppexception e eprintstacktrace whiletransferisdone iftransfergetstatusequalsorgjivesoftwaresmackxfiletransferfiletransferstatuserror systemoutprintlnerror transfergeterror logewhile status error error else if transfergetstatusequalsorgjivesoftwaresmackxfiletransferfiletransferstatusrefused transfergetstatusequalsorgjivesoftwaresmackxfiletransferfiletransferstatuscancelled systemoutprintlncancelled transfergeterror logewhile cancelled cancel refuse try threadsleep10l catch interruptedexception e eprintstacktrace iftransfergetstatusequalsorgjivesoftwaresmackxfiletransferfiletransferstatusrefused transfergetstatusequalsorgjivesoftwaresmackxfiletransferfiletransferstatuserror transfergetstatusequalsorgjivesoftwaresmackxfiletransferfiletransferstatuscancelled systemoutprintlnrefused cancelled error transfergeterror logeif cancelled refused cancel else systemoutprintlnsuccess logeif no error success j0 arrlist messagesaddfile transfergetfilenamesent arrlist messagesadd setlistadapter setlistadaptergreen logcat receving0619 112241911 eerror15386 null0619 112241912 wsystemerr15386 error in execution 0619 112241912 wsystemerr15386 caused by javautilconcurrentexecutionexception 0619 112241912 wsystemerr15386 caused by no response from remote client 0619 112241912 wsystemerr15386 at orgjivesoftwaresmackxfiletransferincomingfiletransfernegotiatestreamincomingfiletransferjava1990619 112241912 wsystemerr15386 at orgjivesoftwaresmackxfiletransferincomingfiletransferaccess100incomingfiletransferjava470619 112241912 wsystemerr15386 at orgjivesoftwaresmackxfiletransferincomingfiletransfer1runincomingfiletransferjava1240619 112241912 wsystemerr15386 at javalangthreadrunthreadjava8560619 112241912 wsystemerr15386 nested exception 0619 112241912 wsystemerr15386 javautilconcurrentexecutionexception 0619 112241912 wsystemerr15386 caused by no response from remote client 0619 112241913 wsystemerr15386 at javautilconcurrentfuturetasksyncinnergetfuturetaskjava2330619 112241913 wsystemerr15386 at javautilconcurrentfuturetaskgetfuturetaskjava900619 112241913 wsystemerr15386 at orgjivesoftwaresmackxfiletransferincomingfiletransfernegotiatestreamincomingfiletransferjava1930619 112241913 wsystemerr15386 at orgjivesoftwaresmackxfiletransferincomingfiletransferaccess100incomingfiletransferjava470619 112241913 wsystemerr15386 at orgjivesoftwaresmackxfiletransferincomingfiletransfer1runincomingfiletransferjava1240619 112241913 wsystemerr15386 at javalangthreadrunthreadjava8560619 112241913 wsystemerr15386 caused by no response from remote client 0619 112241914 wsystemerr15386 at orgjivesoftwaresmackxfiletransferfaulttolerantnegotiatorcreateincomingstreamfaulttolerantnegotiatorjava1130619 112241914 wsystemerr15386 at orgjivesoftwaresmackxfiletransferincomingfiletransfer2callincomingfiletransferjava1860619 112241914 wsystemerr15386 at orgjivesoftwaresmackxfiletransferincomingfiletransfer2callincomingfiletransferjava1830619 112241914 wsystemerr15386 at javautilconcurrentfuturetasksyncinnerrunfuturetaskjava3050619 112241914 wsystemerr15386 at javautilconcurrentfuturetaskrunfuturetaskjava1370619 112241914 wsystemerr15386 at orgjivesoftwaresmackxfiletransferincomingfiletransfernegotiatestreamincomingfiletransferjava1900619 112241914 wsystemerr15386 3 more0619 112241914 enot null15386 print stack success0619 112241914 eerror15386 null0619 112241914 wsystemerr15386 error in execution 0619 112241914 wsystemerr15386 caused by javautilconcurrentexecutionexception 0619 112241914 wsystemerr15386 caused by no response from remote client 0619 112241915 wsystemerr15386 at orgjivesoftwaresmackxfiletransferincomingfiletransfernegotiatestreamincomingfiletransferjava1990619 112241915 wsystemerr15386 at orgjivesoftwaresmackxfiletransferincomingfiletransferaccess100incomingfiletransferjava470619 112241915 wsystemerr15386 at orgjivesoftwaresmackxfiletransferincomingfiletransfer1runincomingfiletransferjava1240619 112241915 wsystemerr15386 at javalangthreadrunthreadjava8560619 112241915 wsystemerr15386 nested exception 0619 112241915 wsystemerr15386 javautilconcurrentexecutionexception 0619 112241915 wsystemerr15386 caused by no response from remote client 0619 112241915 wsystemerr15386 at javautilconcurrentfuturetasksyncinnergetfuturetaskjava2330619 112241915 wsystemerr15386 at javautilconcurrentfuturetaskgetfuturetaskjava900619 112241915 wsystemerr15386 at orgjivesoftwaresmackxfiletransferincomingfiletransfernegotiatestreamincomingfiletransferjava1930619 112241915 wsystemerr15386 at orgjivesoftwaresmackxfiletransferincomingfiletransferaccess100incomingfiletransferjava470619 112241915 wsystemerr15386 at orgjivesoftwaresmackxfiletransferincomingfiletransfer1runincomingfiletransferjava1240619 112241915 wsystemerr15386 at javalangthreadrunthreadjava8560619 112241916 wsystemerr15386 caused by no response from remote client 0619 112241916 wsystemerr15386 at orgjivesoftwaresmackxfiletransferfaulttolerantnegotiatorcreateincomingstreamfaulttolerantnegotiatorjava1130619 112241916 wsystemerr15386 at orgjivesoftwaresmackxfiletransferincomingfiletransfer2callincomingfiletransferjava1860619 112241916 wsystemerr15386 at orgjivesoftwaresmackxfiletransferincomingfiletransfer2callincomingfiletransferjava1830619 112241916 wsystemerr15386 at javautilconcurrentfuturetasksyncinnerrunfuturetaskjava3050619 112241916 wsystemerr15386 at javautilconcurrentfuturetaskrunfuturetaskjava1370619 112241916 wsystemerr15386 at orgjivesoftwaresmackxfiletransferincomingfiletransfernegotiatestreamincomingfiletransferjava1900619 112241916 wsystemerr15386 3 more0619 112241916 enot null15386 print stack successlogcat sendingaller requests to read 6415 bytes timeout00619 112530621 dnativecrypto15386 doing ssl read ssl0x691328 appdata0x7737880619 112530621 dnativecrypto15386 returned from ssl read with result 1 error code 2 ssl0x691328 appdata0x7737880619 112530621 dnativecrypto15386 sslselect typeread fd61 appdata0x773788 timeout00619 112530860 dnativecrypto15386 sslselect read fd61 appdata0x773788 timeout0 10619 112530860 dnativecrypto15386 doing ssl read ssl0x691328 appdata0x7737880619 112530860 dnativecrypto15386 returned from ssl read with result 2 error code 0 ssl0x691328 appdata0x7737880619 112530863 dnativecrypto15386 entering sslread caller requests to read 6193 bytes timeout00619 112530863 dnativecrypto15386 doing ssl read ssl0x691328 appdata0x7737880619 112530863 dnativecrypto15386 returned from ssl read with result 1 error code 2 ssl0x691328 appdata0x7737880619 112530863 dnativecrypto15386 sslselect typeread fd61 appdata0x773788 timeout00619 112531088 isystemout15386 refused cancelled error null0619 112531088 eif cancelled15386 refused cancel0619 112531088 eafter manager15386 manager0619 112539797 isystemout15386 close socket01,['android'] +494203,how to run a junit test in android studio i think tests in the instruementtest should relevant to android so need i add an addtional source folder such as srctestjavai14it looking that the testfile in srctestjava did not compiledhow can i run a junit test independentlyhow can i run the junit test only in a command line no the instrumenttest about androidor put and junit test in the instruementtest folder and call gradlew connectedinstrumenttestbutthe unit test would not run at all,['android'] +494207,cell spacing in uicollectionview how do i set cell spacing in a section of uicollectionview i know there is a property minimuminteritemspacing i have set it to 50 still the spacing is not appearing 50 i have implemented the flowout delegate method cgfloatcollectionviewuicollectionview collectionview layoutuicollectionviewlayoutcollectionviewlayout minimuminteritemspacingforsectionatindexnsintegersection return 50stil i am not getting the desired result i think its the minimum spacing isnt there any way by which i can set the maximum spacing,"['ios', 'objective-c']" +494210,freehand image crop draw inside bitmap region trying to achieve freehand cropping of an image so i am able to draw on the image but it goes outside bitmap region i just wanna restrict that user can only draw inside bitmap region check below screen shoti am trying to implement functionality like photoshop lasso toolits drawing outside view region which generates incorrect outputoutputcodeondrawpublic void ondrawcanvas canvas final rect rect new rect0 0 bitmapgetwidth bitmapgetheight canvasdrawbitmapbitmap rect rect null rectf r new rectf matrix matrix new matrix matrixmaprectr logitag rect rleft rtop rright rbottom canvascliprectrleft rtop rright rbottom path path new path boolean first true for int i 0 i pointssize i 2 point point pointsgeti if first first false pathmovetopointx pointy else if i pointssize 1 point next pointsgeti 1 pathquadtopointx pointy nextx nexty else mlastpoint pointsgeti pathlinetopointx pointy canvasdrawpathpath paint oncropbitmap resultingimage bitmapcreatebitmapwidthofscreenheightofscreen bitmap1getconfig canvas canvas new canvasresultingimage paint paint new paint paintsetantialiastrue path path new path for int i 0 i someviewpointssize i pathlinetosomeviewpointsgetix someviewpointsgetiy pathlineto150 0 pathlineto230 120 pathlineto70 120 pathlineto150 0 canvasdrawpathpath paint ifcrop paintsetxfermodenew porterduffxfermodemodesrc in else paintsetxfermodenew porterduffxfermodemodesrc out suggest me to achieve my goal,['android'] +494211,kif how to autorunstress test an ios app to find the cause of a rare ui bug note i added kif to the title just for search indexing puposes considering that most of the answer turned out to thiscuss iti am looking for something like selenium for ios basically a testautomationunit test framework that can run a certain ui scenario many many times until it crashes which would help me narrow down the cause of a ui bug that happens very rarely and randomly and by the way i have nslogged every single line of code of datasourcetable interaction and spent hours analyzing the potential cause but found nothing conclusive again this bug very rarely happensi looked at some of the unit testing frameworks in ios but they seem to be so many i am not sure which to pick also my reference to selenium is based on conjecture as i have worked with qa folks whove used selenium in large web projects in the past and i am assuming that there must be something similar for iosnow that i am a one man team working on an ios project i am gonna have to put a qa hat on and figure this bug out i am facing a classic bug that happens when there is a thiscrepancy between the actual number of rows inserted in a uitableview and the number of rows that the datasource delegate returns this is the error message assertion failure in uitableview endcellanimationswithcontext exception in insertrows invalid update invalid number of rows in section 0the number of rows contained in an existing section after the update 2 must be equal to the number of rows contained in that section before the update 2 plus or minus the number of rows inserted or deleted from that section 1 inserted 0 deleted and plus or minus the number of rows moved into or out of that section 0 moved in 0 moved outi click on a uitableviewcell that takes me into another uitableview sometimes it works and sometimes very rarely it does not with the above error,['objective-c'] +494214,oncreateview in fragment is not called immediately even after fragmentmanagerexecutependingtransactions i read that if we need to create fragment immediately we have to call executependingtransactions method on fragmentmanager well that is what i am trying to do like thisoverrideprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity game fragmentmanager fragmentmanager getfragmentmanager fragmenttransaction fragmenttransaction fragmentmanagerbegintransaction fragmenttransactionaddrlayoutfragmentcontainer new myfragment fragmenttransactioncommit fragmentmanagerexecutependingtransactions foo it is called before myfragments oncreateviewi would like to know why foo method is called before myfragments oncreateview as you see i am calling executependingtransactions in ui thread as it should be i am not messing here with threads at all,"['java', 'android']" +494243,linux c implementing the ability that a program can update itself i am writing a program in c on linux environment debianlenny and would like the program to be updated when an update is available the program gets notified when a new update is available i am looking for a way that the program can update itselfwhat i am thinking is that the main program invokes a new program to handle the update the updater program will haveaccess to the source code and receive the update information about the changes on the source code something like that edit1 line 20 remove column 5 to 20edit2 line25 remove column 47 then add ifx3 from the column4edit3 line 26 enter a new line and insert xthen kill the main process recompile the source code and then replace the new binary with the old oneor is there a better easier and standard way to implement the ability that a program can update itself i use the program to control a system with a linux embedded board therefore i do not want the source code to be accessible to another person if the system is hacked or something if the best way to update a program by using the source code how do you suggest me to secure the source code if you suggest me to encrypt the source code what function linux c can the program use to encrypt and decrypt the source file,['c'] +494248,best way to save and retrieve uicolors to core data i can think of a few ways for instance saving each color component as a float saving an array as transformable saving a color from pattern image could be slightly more complicated but i guess you could save the name of the image as a string and insert that into creation code am i on the right track else what is the best and most efficient to do this task in general,['ios'] +494292,using uiimagepickercontroller in uiview i have button which when i click thisplays the camera works perfectly ibactiongetphotoidsender nslog button clicked imagepicker uiimagepickercontroller alloc init imagepickerdelegate self if uiimagepickercontroller issourcetypeavailableuiimagepickercontrollersourcetypecamera imagepicker setsourcetypeuiimagepickercontrollersourcetypecamera else if the device does not have a camera so use the photos album imagepicker setsourcetypeuiimagepickercontrollersourcetypesavedphotosalbum self addsubviewimagepickerviewafter which i can take an image etc but when i click use nothing happens here is my method the image picker does not thismiss itslelf the application simply does nothing i am trying to take the image i just took and thisplay it inside a cgrect on screen voidimagepickercontrolleruiimagepickercontroller picker didfinishpickingmediawithinfonsdictionary info picker thismissviewcontrolleranimatedyes completionnull uiimageview patientimage uiimageview alloc init patientimageframe cgrectmake625 25 83 103 uiimage chosenimage infouiimagepickercontrollereditedimage selfpatientimageimage chosenimageeven when i hit the cancel button without taking an image the imagepicker camera interface does not thismiss itself any help advice or guidance would be very appreciated,['ios'] +494295,how to access jsonresult data when testing in aspnet mvc i have this code in c mvc controller httppost public actionresult deletestring runid if runid runid null return thisjsonnew error null or empty params try int userid intsessionuserid int run converttoint32runid cloudmgr cloud new cloudmgrsession clouddeleterunuserid run return thisjsonnew success true catch exception ex return thisjsonnew error extostring how i can access my json error field in a controllertest to check if it is null or not testmethod public void deletewrongparam whatifcontroller controller new whatifcontroller controllercontrollercontext testutilscreatemocksessioncontrollercontextobject as controllercontext jsonresult result controllerdeletewhatifnull as jsonresultassertisnotnullresultdataerror is what i would like to do any ideas thanks,['c#'] +494335,using linq to split items within a list i want to separate each item in a list but also within each item split the item if it contains eg string names peterjohnconnorpaulmaryblythenamedumpwill showpeterjohnconnorpaulmaryblythehowever is there any linq that i can use which will provide the following listpeterjohnconnorpaulmaryblythei can do this usingforeach var person in names x personsplittolist foreach var personinlist in x personinlist but that seems very long winded when i am certain linq could be more elegant,['c#'] +494412,xdebug change var dump nesting level hello i enabled the xdebug extension but when i dump a long arraylike 10 positions the xdebug supress the values is it possible to turn off the supression not the xdebug pluginhere an example to you guysobjectstdclass213 public ordergetbystatusresult objectstdclass214 public orderdto array size3 0 objectstdclass215 1 objectstdclass230 2 objectstdclass266,['php'] +494435,ios framework and category import i have just started to create my own framework regrouping some usefull helper utils tools etc everything works fine i just wondered if it was possible to import my categories directly in my main headers framework filefor exemple my framework is named myframework i put a class name myframeworkh in public headers within i wrote all of my imports import mycategoryhelperhimport myothercategoryhelperhimport aclasshthen i build my framework and thistribute it to my team developerswhat i expect is that other developers just have to import to access of all of my frameworks categories it is ok when i subclass instead of using categories but it is not what i expectfor the while i use loadablecategoryh to make my categories work in my framework and specify to my developers that they should use objc flag in other linker flags settings and import each category like this import myframeworkmycategoryhelperhimport myframeworkmyothercategoryhelperhmay be it is not possible but i wonder why i miss something thank you pebieps sorry for my english,"['ios', 'objective-c']" +494508,what is the visual studio dte i have been slowly digging through visual studios sdk but could not yet figure out what dte stands for this is a silly question but i really cannot seem to find it dte is super useful it would be super cool to know what it is as well,['c#'] +494564,laravel 4 using uuid as primary key i am setting up my first laravel 4 app and the specs call for the id fields to be varchar36 and be a uuidusing eloquent my migrations for a sample table looks like this schemacreateusers functiontable tablestringid 36primary tablestringfirst name 50 tablestringlast name 50 tablestringemailunique tablestringpassword 60 tabletimestamps tablesoftdeleteswhen the users table gets created the id field is not defined as pk or unique it gets defined as varchar36 not nullwhy is this happening when i run the migration my original question was about using uuids but i have sense solved that by adding this to my users model in case anyone else sees this postprotected hidden arraypasswordprotected fillable arrayid first name last name email passwordhere is my route for adding a user i am using a function to create the uuidroutepostsignup function userdata array id gen uuid first name inputgetfirst name last name inputgetlast name email inputgetemail password hashmakeinputgetpassword user new useruserdata usersave return viewmakeloginloginwithuserdata userdata,"['php', 'mysql']" +494571,opencv polylines function in python throws exception i am trying to draw an arbitrary quadrilateral over an image using the polylines function in opencv when i do i get the following erroropencv error assertion failed pcheckvector2 cv 32s 0 in polylines file tmpbuilddrosfuerteopencv22421precise201303121306modulescoresrcd rawingcpp line 2065i call the function as like socv2polylinesimg points 1 255255255where points is as numpy array as shown below the image size is 1280x960910 641 206 632 696 488 458 485and img is just a normal image that i am able to imshow currently i am just drawing lines between these points myself but i am looking for a more elegant solutionhow should i correct this error,['python'] +494600,global integer array with no dimension what is the concept when we define a global array with no dimensionthis shows output as 16 include stdioh include stdlibh int arr int mainint argc char argv arr1 16 printfdnarr1 systempause return 0 and even sizeofarr does not work why,['c'] +494606,setting constraints programmatically different from setting them in ib i am new to auto layout in ios i really like the concept in principle but it is driving me nuts trying to get the simplest things done i suspect i am still missing some simple underlying principle i am trying to learn by doing and get the basics right before actually working with it in an app so i am creating very simple test projects heres one as simple as it gets that does not work as expected first the part that works in ib i add a view to fill the entire viewcontroller and xcode automatically sets the constraints to topbottomleadingtrailing and the space to 0 when done with ib it works as expected rotates togreatnow i am trying to do the same thing in code voidviewdidloadsuper viewdidload do any additional setup after loading the view typically from a nibuiview redview uiview alloc initwithframeselfviewboundsredviewbackgroundcolor uicolor redcolorselfview addsubviewredviewredviewtranslatesautoresizingmaskintoconstraints noselfview addconstraintnslayoutconstraint constraintwithitemredview attributenslayoutattributebottom relatedbynslayoutrelationequal toitemselfview attributenslayoutattributebottom multiplier10f constant00fselfview addconstraintnslayoutconstraint constraintwithitemredview attributenslayoutattributeleading relatedbynslayoutrelationequal toitemselfview attributenslayoutattributeleading multiplier10f constant00fselfview addconstraintnslayoutconstraint constraintwithitemredview attributenslayoutattributetrailing relatedbynslayoutrelationequal toitemselfview attributenslayoutattributebottom multiplier10f constant00fselfview addconstraintnslayoutconstraint constraintwithitemredview attributenslayoutattributetop relatedbynslayoutrelationequal toitemselfview attributenslayoutattributeleading multiplier10f constant00fthat is all the code there is other than the default code for a singleview application when i run the above code trying to mirror the same thing as i get with ib programmatically i get this after rotationhow come that the same constraints lead to different results it is probably something really simple and embarrassingly stupid that i am missing help,['ios'] +494609,multiindex sorting in pandas i have a multiindex dataframe created via a groupby operation i am trying to do a compound sort using several levels of the index but i cannot seem to find a sort function that does what i needinitial dataset looks something like this daily sales counts of various products date manufacturer product name product launch date sales0 20130101 apple ipod 20011023 121 20130101 apple ipad 20100403 132 20130101 samsung galaxy 20090427 143 20130101 samsung galaxy tab 20100902 154 20130102 apple ipod 20011023 225 20130102 apple ipad 20100403 176 20130102 samsung galaxy 20090427 107 20130102 samsung galaxy tab 20100902 7i use groupby to get a sum over the date range grouped dfgroupbymanufacturer product name product launch datesum salesmanufacturer product name product launch date apple ipad 20100403 30 ipod 20011023 34samsung galaxy 20090427 24 galaxy tab 20100902 22so far so goodnow the last thing i want to do is sort each manufacturers products by launch date but keep them grouped hierarchically under manufacturer heres all i am trying to do salesmanufacturer product name product launch date apple ipod 20011023 34 ipad 20100403 30samsung galaxy 20090427 24 galaxy tab 20100902 22when i try sortlevel i lose the nice percompany hierarchy i had before groupedsortlevelproduct launch date salesmanufacturer product name product launch date apple ipod 20011023 34samsung galaxy 20090427 24apple ipad 20100403 30samsung galaxy tab 20100902 22sort and sort index just failgroupedsortmanufacturerproduct launch datekeyerror uno item named manufacturergroupedsort indexbymanufacturerproduct launch datekeyerror uno item named manufacturerseems like a simple operation but i cannot quite figure it outi am not tied to using a multiindex for this but since that is what groupby returns that is what i have been working withbtw the code to produce the initial dataframe isdata date 20130101 20130101 20130101 20130101 20130102 20130102 20130102 20130102 manufacturer apple apple samsung samsung apple apple samsung samsung product name ipod ipad galaxy galaxy tab ipod ipad galaxy galaxy tab product launch date 20011023 20100403 20090427 2010090220011023 20100403 20090427 20100902 sales 12 13 14 15 22 17 10 7df dataframedata columnsdate manufacturer product name product launch date sales,['python'] +494614,how to call a controller method from a button in rails 4 so i feel really stupid right now but i cannot seem to find an answerso i have a method which needs to be called exactly once and since this is only the experimental phase i decided that a simple button should suffice however i cannot seem to find out how to if i can simply call the method from a button clickthe method is in home controllerrb and the button is in indexhtmlerbany ideas or is this not something i can do,['ruby-on-rails'] +494629,operatoritemgetter or lambda i was curious if there was any indication of which of operatoritemgetter0 or lambda xx0 is better to use specifically in sorted as the key keyword argument as that is the use that springs to mind first are there any known performance differences are there any pep related preferences or guidance on the matter,['python'] +494674,clang 33 and gcc 47 const vs constexpr i just tried compiling a fairly large body of code using clang 33 with gcc 473 standard library header files on ubuntu 1304 this all went well except one issue this code already compiles with the standard ubuntu clang 32 package on this machine so i am assuming this is some change in the clang 33 compiler the problem related to const and constexpr using the complex header in particular the complex type has the following block of codeifdef gxx experimental cxx0x glibcxx resolve lib defects dr 387 stdcomplex overencapsulated constexpr double real return real m value constexpr double imag return imag m value else double real return real m value const double real const return real m value double imag return imag m value const double imag const return imag m value endifin my compile i enter the first block of code and so the compiler seesconstexpr double real return real m value this results in clang producing an error that the real member function is not const with the followingusrlibgccx86 64linuxgnu47includec47complex12127 note candidate function not viable this argument has type const complexdouble but method is not marked const real return real m value i have read the following post difference between constexpr and const and a few other similar documents but am still not really clear if this is a gcc header problem or a clang compiler problem my feeling is that a member function marked constexpr should be regarded by the compiler as const in which case clang is wrong,['c++'] +494681,how to update xml file with lxml i want to update xml file with new information by using lxml libraryfor example i have this code from lxml import etree tree etreeparsebooksxmlwhere booksxml file has this content i want to update this file with new book new entry etreefromstringbook categoryweb coverpaperback title langenlearning xml 2title authorerik rayauthor year2006year price4995price bookmy question is how can i update tree element tree with new entry tree and save the file,['python'] +494711,python readlines usage and efficient practice for reading i have a problem to parse 10s of text filesaround 30 lines in each file of 400kb size in a folder i did read them using readlines for filename in oslistdir input dir if filenameendswithgz f gzipopenfile rb else f openfile rb file content freadlines fclose len file lenfile content while i len file line file contentisplitdelimiter my logic i 1 this works completely fine for sample from my inputs 50100 files when i ran on the whole input more than 5k files the timetaken was nowhere close to linear incrementi planned to do an performance analysis and did a cprofile analysis the time taken for the more files in exponentially increasing with reaching worse rates when inputs reached to 7k files here is the the cumulative timetaken for readlines first 354 filessample from input and second 7473 files whole input ncalls tottime percall cumtime percall filenamelinenofunction 354 0192 01 0192 01 method readlines of file objects 7473 1329380 0178 1329380 0178 method readlines of file objectsbecause of this the timetaken by my code is not linearly scaling as the input increases i read some doc notes on readlines where people has claimed that this readlines reads whole file content into memory and hence generally consumes more memory compared to readline or readi agree with this point but should the garbage collector automatically clear that loaded content from memory at the end of my loop hence at any instant my memory should have only the contents of my currently processed file right but there is some catch here can somebody give some insights into this issue is this an inherent behavior of readlines or my wrong interpretation of python garbage collector glad to know also suggest some alternative ways of doing the same in memory and time efficient manner tia,['python'] +494801,await works but calling taskresult hangsdeadlocks i have the following four tests and the last one hangs when i run it my question is why this happenstestpublic void checkonceresulttest assertistruecheckstatusresulttestpublic async void checkonceawaittest assertistrueawait checkstatustestpublic async void checkstatustwiceawaittest assertistrueawait checkstatus assertistrueawait checkstatustestpublic async void checkstatustwiceresulttest assertistruecheckstatusresult this hangs assertistrueawait checkstatusprivate async taskbool checkstatus var restclient new restclient taskirestresponsedummyservicestatus restresponse restclientexecutetaskasyncdummyservicestatusnew restrequestmethodget irestresponsedummyservicestatus response await restresponse return responsedatasystemrunningi use this extension method for restsharp restclientpublic static class restclientext public static taskirestresponset executetaskasynctthis restclient client irestrequest request where t new var tcs new taskcompletionsourceirestresponset restrequestasynchandle asynchandle clientexecuteasynctrequest tcssetresult return tcstask public class dummyservicestatus public string message get set public bool validversion get set public bool systemrunning get set public bool skipphrase get set public long timestamp get set why does the last test hang,['c#'] +494893,how to unconditionally stop a thread occasionally we must forcibly stop a thread as a best effort before entirely shutting down the whole jvm usually threadstop is cited as a surefire even if hamhanded and deprecated way to unconditionally stop a thread this is not so however all the rogue thread has to do to keep itself running is catch threaddeath or a superclasspublic static void mainstring args throws interruptedexception final thread t new thread public void run for try threadsleeplongmax value catch throwable t systemoutprintlntgetclassgetsimplename still going on tstart threadsleep200 tinterrupt threadsleep200 tinterrupt threadsleep200 tstop threadsleep200 tstopthis will printinterruptedexception still going oninterruptedexception still going onthreaddeath still going onthreaddeath still going onis there anything else that i could do to really really stop a thread without killing the whole jvm,['java'] +494929,how to show compilation errors in android studio i am very much upset right now already i spent about an hour to know how to show compilation errors in android studio i tried the following one android studio where is the error output windowbut showing another error javac invalid target release 18please anybody who know actual solution please reply,['android'] +494947,link inside a button not working in firefox i have two links inside a button but the links do not seem to work on firefoxbutton classbtn login a hrefloginblog inba a hrefsignupbsign upbabuttoni tried javascript onclick and redirecting even that is not working,"['javascript', 'html']" +494994,unable to create models on flaskadmin i am creating a simple blog on flask and i am trying to implement flaskadmin to manage my posts if i go to the admin area i can see a list of all my post from the db but when i try to create a new one i got the next errorfailed to create model init takes exactly 4 arguments 1 giventhis is my post modelclass postdbmodel tablename news nid dbcolumndbinteger primary key true title dbcolumndbstring100 content dbcolumndbtext created at dbcolumndbdatetime def init self title content selftitle titletitle selfcontent content selfcreated at datetimedatetimenowand this is my code to add the model to the uifrom flask import flask sessionfrom models import db postfrom flaskextadmin import adminfrom flaskextadmincontribsqlamodel import modelviewapp flask name appconfigsqlalchemy database uri mysqlrootpasslocalhostappnamedbinit appappadmin adminappadminadd viewmodelviewpost dbsessioni do can edit models through the admin panel but not create new ones i know i am missing something really stupid but i cannot figure out what it isedit it works if i do not implement init on the model how can i fix this,['python'] +495002,paperclip with sidekiq i am using paperclip for uploading files does anybody have use it with sidekiq for background jobs i was trying to achieve something similar to railscast 383 uploading to amazon s3 but with paperclip and sidekiqi did not find too much information for using it with sidekiq and i am thinking if i should change to carrierwave or if there is any example for paperclip and sidekiq not with fancyuploader and delayed jobs,['ruby-on-rails'] +495033,emulate so tag editor i am trying to implement a tag editor field in my app the same way as so doesright now i got thisedit i have coded this into a jquery plugin atfiddlehtmldiv stylemarginleft auto marginright auto width 400px span stylecolor 3 fontsize small tags az az 09 span div idtags container span idtags queuespan input typetext idtf divdivjsdocumentreadyfunction var rexp azaz09var left 37var right 39var del 8var space 32var comma 188var minlen 3var maxlen 15var current tag nulltffocusattrmaxlength maxlentags containerclickfunction tffocustfkeydownfunction e var code ekeycode ekeycode ewhich ewhich echarcode var txt thisvaltrim handle navigation between tags if code left code right txtlength 0 if current tag if code left current tag tags queue spanlast else current tag tags queue spanfirst if current taglength 0 current tagcssbackgroundcolor 9fc2d6 else current tag exists if code left current tag current tagcssbackgroundcolor b8d0deprev else current tag current tagcssbackgroundcolor b8d0denext if current taglength 0 current tagcssbackgroundcolor 9fc2d6 hit lastfirst clean current tag else current tagcssbackgroundcolor b8d0de current tag null tfkeypressfunction e var token stringfromcharcodeewhich var code ekeycode ekeycode ewhich ewhich echarcode if tokenmatchrexp code del code left code right return false tfkeyupfunction e var code ekeycode ekeycode ewhich ewhich echarcode var txt thisvaltrim if code del txtlength 0 current tag current tagremove current tag null return clean current tag user is typing if current tag code left code right current tagcssbackgroundcolor b8d0de current tag null if txtlength maxlen txt txtsubstring0 maxlen if txtmatchrexp thisval return else if code space code comma if txtlength minlen return var tag spanspan class tag htmltxtappendaa class close tag html times click function thisparentfadeoutfunction thisremove current tagcssbackgroundcolor b8d0de current tag null tags queueappendtag thisval cssdivtags container border 1px solid c paddingbottom 5px borderradius 5px backgroundcolor beige overflow hidden inputtf border 1px solid orange important outline none important backgroundcolor transparent important height 30px margintop 2px paddingleft 5px aclose tag marginleft 5px color f aclose taghover cursor pointer spantag backgroundcolor b8d0de color 1 marginleft 5px margintop 5px padding 5px float left borderradius 5px spantaghover backgroundcolor 9fc2d6 spantags queue marginright 5px verticalalign middle the problem is how can i handle the hidden content using the arrows keys the way so does it looks like i have to handle the cursor position inside the textfields and watch for arrowleft and arrowright eventsand there is also the click on the completed tagsi can think of the following antiso design solutionsremove whitespace nowrap from the tags container div and letthe div grow as the user add more tagsadd overflow scroll to the tags container div very uglyso i appreciate any new ideas on how to approximate the so tageditor behaviourthanks,"['javascript', 'jquery', 'html', 'css']" +495040,how to monitor an external process for events by its pid in c is there any library whichs got some function the allows one to monitor an external process for events by its pid t i mean monitoring whether an external process has exited or whether it has created one or more child processes with fork or whether it has become another executable image via an exec or posix spawn function family call or whether a unix signal was delivered to itediti need something that does not interfere with the execution of the program that is being monitored so i am not supposed to use ptrace since it stops the process which is being monitored when it emits some signal and it is necessary to resume the process whenever this happens,['c'] +495053,removing leading whitespace from indented html source in precode tags i currently have the following html within a precode block pre classprettyprintcode lthtmlgt ltbodygt ltform namequotinputquot actionquothtml form actionaspquot methodquotgetquotgt ltinput typequotradioquot namequotsexquot valuequotmalequotgtmaleltbrgt ltinput typequotradioquot namequotsexquot valuequotfemalequotgtfemaleltbrgt ltinput typequotsubmitquot valuequotsubmitquotgt ltformgt ltpgtif you click the quotsubmitquot button the formdata will be sent to a page called quothtml form actionaspquotltpgt ltbodygt lthtmlgt codepreit is indented within the html source for better structure within the document how can i remove the leading whitespace through the use of javascript or is there a more simple methodthanks,"['javascript', 'jquery', 'html', 'css']" +495081,switching between android navigation drawer image and up caret when using fragments when using the navigation drawer the android devs are recommending that in the actionbar only those screens that are represented in the navigation drawer should actually have the navigation drawer image and that all other screens have the traditional up carat see here for details i am using one activity to control multiple levels of fragments and can get the navigation drawer image to thisplay and function at all levelswhen creating lower level fragments i can call the actionbardrawertoggle setdrawerindicatorenabledfalse to hide the navigation drawer image and have the up caret thisplayed lowerlevelfragment lowfrag new lowerlevelfragmentthisable the toggle menu and show up caratthedrawertogglesetdrawerindicatorenabledfalsegetsupportfragmentmanagerbegintransactionreplaceridfrag layout lowfrag lowerfragaddtobackstacknullcommitthe problem i am having is when i navigate back to the top level fragments the up carat still shows instead of the original navigation drawer image any suggestions on how to refresh the actionbar on the top level fragments to rethisplay the navigation drawer image solutiontoms suggestion worked for me hereas what i didmainactivitythis activity controls all fragments in the appwhen preparing new fragments to replace others i set the drawertoggle setdrawerindicatorenabledfalse like thislowerlevelfragment lowfrag new lowerlevelfragmentthisable the toggle menu and show up caratthedrawertogglesetdrawerindicatorenabledfalsegetsupportfragmentmanagerbegintransactionreplaceridfrag layout lowfragaddtobackstacknullcommitnext in an override of onbackpressed i reverted the above by setting the drawertoggle to setdrawerindicatorenabledtrue like thisoverridepublic void onbackpressed superonbackpressed turn on the navigation drawer image this is called in the lowerlevelfragments setdrawerindicatorenabledtruein the lowerlevelfragmentsin the fragments i modified oncreate and onoptionsitemselected like thisin oncreate added sethasoptionsmenutrue to enable configuring the options menu also set setthisplayhomeasupenabledtrue to enable the in the actionbaroverridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate needed to indicate that the fragment would like to add items to the options menu sethasoptionsmenutrue update the actionbar to show the up carataffordance getactivitygetactionbarsetthisplayhomeasupenabledtruethen in onoptionsitemselected whenever the is pressed it calls the onbackpressed from the activity to move up one level in the hierarchy and thisplay the navigation drawer imageoverridepublic boolean onoptionsitemselectedmenuitem item get item selected and deal with it switch itemgetitemid case androidridhome called when the up affordancecarat in actionbar is pressed getactivityonbackpressed return true a,['android'] +495115,select first and columns of mysql table as it is possible to select top and rows from table is there any way to select first and columns from mysql database tablesthanks for your replies and maybe some parts of code in php,['mysql'] +495195,plural definition is ignored for zero quantity i use plurals to compile a quantity string for an android application i follow exactly what one can find in the tutorialsresgetquantitystring rpluralsnumber of comments commentscount commentscounthere is the definition of the pluralsxml version10 encodingutf8resources plurals namenumber of comments item quantityzerono commentsitem item quantityoneone commentitem item quantityotherd commentsitem pluralsresourcesinteresting enough the output string is odd to what i definiedcommentscount 0 0 comments commentscount 1 one comment commentscount 2 2 commentsi guess this is because the docs state when the language requires special treatment of the number 0 as in arabic for zero quantity is there any way to force my definition,['android'] +495219,bottle py enabling cors for jquery ajax requests i am working on a restful api of a web service on the bottle web framework and want to access the resources with jquery ajax callsusing a rest client the resource interfaces work as intended and properly handle get post requests but when sending a jquery ajax post request the resulting options preflight request is simply denied as 405 method not allowedi tried to enable cors on the bottle server as described here but the after request hook is never called for the options requesthere is an excerpt of my serverfrom bottle import bottle run request responseimport simplejson as jsonapp bottleapphookafter requestdef enable cors print after request hook responseheadersaccesscontrolalloworigin responseheadersaccesscontrolallowmethods get post put options responseheadersaccesscontrolallowheaders origin accept contenttype xrequestedwith xcsrftokenapostcorsdef lvambience responseheaderscontenttype applicationjson return 1the jquery ajax callajax type post url data jsonstringify data contenttype applicationjson charsetutf8 datatype json success functiondata alertdata failure functionerr alerterr the server only logs a 405 error1921681693 23jun2013 171053 options cors http11 405 741post does work but not being able to send put requests would defeat the purpose of a restful serviceso how can i allow the options preflight request to be handled,['jquery'] +495259,is an xpc interruption handler called when launchd kills the process the documentation for the interruptionhandler block of nsxpcconnection statesan interruption handler that is called if the remote process exits or crasheshowever the daemons and services programming guide statesxpc services are managed by launchd which launches them on demand restarts them if they crash and terminates them by sending sigkill when they are idle this is transparent to the application using the service except for the case of a service that crashes while processing a message that requires a response in that case the application can see that its xpc connection has become invalid until the service is restarted by launchdif an xpc process is killed for being idle will i get a callback in my interruptionhandler or will i only get the callback when the app crashes while processing a message i ask because this test case seems like it is impossible to simulate xpc service lifecycle is unfortunately a very black box,['objective-c'] +495315,jquery ui position relative to two elements is it possible to specify jquery ui position where x coordinate is relative to element1 and y coordinate is relative to element2example 1 i want to popup a dialog so that it is centered horizontally but vertically it is centered on some other elementexample 2 i have two items in my dom and i want to postion the third in the outer corner of these two i know i can pick the position of each of them and use x from one and y from the other but it would look so much nicer to do something likejqueryupperrightpostion my right top at right of rightmostitem at top of topmostitem double parameters do not work of courseor jqueryupperrightposition my right ignore at right ignore of rightmostitem postion my ignore top at ignore top of topmostitem where ignore overrides the default centerall attempts so far have been trapped with center being the default not allowed to use my current position in one direction as basis any good ideas are very wellcome,"['javascript', 'jquery']" +495363,crop to face with face detection i am modifying the apple squarecam example face detection app so that it crops the face out before writing to the camera roll instead of drawing the red square around the face i am using the same cgrect to do the cropping as was used for drawing the red square however the behavior is different in portrait mode if the face is in the horizontal center of the screen it crops the face as expected the same place the red square would have been if the face is off to the left or right the crop seems to always be taken from the middle of the screen instead of where the red square would have beenhere is apples original code cgimagerefnewsquareoverlayedimageforfeaturesnsarray features incgimagecgimagerefbackgroundimage withorientationuideviceorientationorientation frontfacingboolisfrontfacing cgimageref returnimage null cgrect backgroundimagerect cgrectmake0 0 cgimagegetwidthbackgroundimage cgimagegetheightbackgroundimage cgcontextref bitmapcontext createcgbitmapcontextforsizebackgroundimagerectsize cgcontextclearrectbitmapcontext backgroundimagerect cgcontextdrawimagebitmapcontext backgroundimagerect backgroundimage cgfloat rotationdegrees 0 switch orientation case uideviceorientationportrait rotationdegrees 90 break case uideviceorientationportraitupsidedown rotationdegrees 90 break case uideviceorientationlandscapeleft if isfrontfacing rotationdegrees 180 else rotationdegrees 0 break case uideviceorientationlandscaperight if isfrontfacing rotationdegrees 0 else rotationdegrees 180 break case uideviceorientationfaceup case uideviceorientationfacedown default break leave the layer in its last known orientation uiimage rotatedsquareimage square imagerotatedbydegreesrotationdegrees features found by the face detector for cifacefeature ff in features cgrect facerect ff bounds nslogfacerect nsstringfromcgrectfacerect cgcontextdrawimagebitmapcontext facerect rotatedsquareimage cgimage returnimage cgbitmapcontextcreateimagebitmapcontext cgcontextrelease bitmapcontext return returnimageand my replacement cgimagerefnewsquareoverlayedimageforfeaturesnsarray features incgimagecgimagerefbackgroundimage withorientationuideviceorientationorientation frontfacingboolisfrontfacing cgimageref returnimage null i am only taking pics with one face this is just for testing for cifacefeature ff in features cgrect facerect ff bounds returnimage cgimagecreatewithimageinrectbackgroundimage facerect return returnimage update based on wains input i tried to make my code more like the original but the result was the same nsarrayextractfaceimagesnsarray features fromcgimagecgimagerefsourceimage withorientationuideviceorientationorientation frontfacingboolisfrontfacing nsmutablearray faceimages nsmutablearray alloc initwithcapacity1 autoreleasecgimageref returnimage nullcgrect backgroundimagerect cgrectmake0 0 cgimagegetwidthsourceimage cgimagegetheightsourceimagecgcontextref bitmapcontext createcgbitmapcontextforsizebackgroundimagerectsizecgcontextclearrectbitmapcontext backgroundimagerectcgcontextdrawimagebitmapcontext backgroundimagerect sourceimagecgfloat rotationdegrees 0switch orientation case uideviceorientationportrait rotationdegrees 90 break case uideviceorientationportraitupsidedown rotationdegrees 90 break case uideviceorientationlandscapeleft if isfrontfacing rotationdegrees 180 else rotationdegrees 0 break case uideviceorientationlandscaperight if isfrontfacing rotationdegrees 0 else rotationdegrees 180 break case uideviceorientationfaceup case uideviceorientationfacedown default break leave the layer in its last known orientation features found by the face detectorfor cifacefeature ff in features cgrect facerect ff bounds nslogfacerect nsstringfromcgrectfacerect returnimage cgbitmapcontextcreateimagebitmapcontext returnimage cgimagecreatewithimageinrectreturnimage facerect uiimage clippedface uiimage imagewithcgimagereturnimage faceimages addobjectclippedfacecgcontextrelease bitmapcontextreturn faceimagesi took three pictures and logged facerect with these resultspic taken with face positioned near left edge of device capture image completely misses face to the rightfacerect972 430312 673312 673312pic taken with face positioned in middle of device capture image is goodfacerect106059 536625 66825 66825pic taken with face positioned near right edge of device capture image completely misses face to the leftfacerect982125 9844 804938 804938so it appears that x and y are reversed i am holding the device in portrait but facerect seems to be landscape based however i cannot figure out what part of apples original code is accounting for this the orientation code in that method appears to only affect the red square overlay image itself,['ios'] +495415,what value to set for minimum required sdk target sdk compile with i know that there are many question on this and i also read this page however i am still confused about the exact choices if i have a mobile phone that runs android 236 i know that the minimum required sdk should be the lowest version of android that my app supportsso for example i will choose android 22 or less than that value say android 15the confusing parts target sdk and compile withi have installed these below there is no android 236 available in the sdk manager android 422 api 17android 30 api 11android 233 api 10android 22 api 8 is the target sdk should be set to the maximum which is android 422 irrespective to what my mobile phone uses which is android 236 choosing android 422 will cover all phones below it is that rightor is it should be set to the exactnearest value as my phone here the available one is android 233 but not exceed my mobile phone android 236is compile with must be set to the maximum android 422 or what,['android'] +495505,c how to check same sign of 2 decimal values using bit i have 2 decimal values a and b how do i use bit operator to check if two value is same sign,['c#'] +495571,bootstrap tooltip hide when another tooltip is click i hope someone can helpi am trying to hide the tooltip when another tooltip icon is clicked it works but when i decide to click the last tooltip again it flashes the tooltipvar hastooltip hastooltiphastooltiponclick functione epreventdefault hastooltiptooltiphidetooltip animation trueparentdelegateclose click function hastooltiptooltiphidehtmla href classhastooltip dataoriginaltitlelorem ipsum dolor sit amet consectetur adipisicing elit h3info 1h3aa href classhastooltip dataoriginaltitlelorem ipsum dolor sit amet consectetur adipisicing elit h3info 2h3aif it helps a following markup is added to the dom when the user clicks on the button to thisplay the tooltipdiv classtooltipdiv,"['javascript', 'jquery']" +495594,how to map a value type which has a reference to an entity i am having a problem with a mapping in entity frameworki have the following classes simplifiedpublic class building public int id get set snip other properties public location location get private set public class location public string street get set public country country get setpublic class country public int id get set public string name get set building and country are entities they are saved in the database location is a value type and should map to the same table as buildinghowever when i map it this way entity framework wants to map location to a table as well and is complaining it has no key i do not want to give it a key since it belongs to the building and should not be an entity at alli have seen workarounds which say you need to put country on the buildingclass but that just does not feel good and is semantically just plain wrong i am using entity framework 5,"['c#', '.net']" +495613,spring web security list of accessible urls i am migrating a webapplication to spring security application uses spring mvc for rendering jsps and controller methods are annotated with securedso at some point after successful login and mvc servlet initialization some spring internals have this information what permissions the user has aka granted authorities controller urls and permission set required for each one of thosewhat i want is to dynamically get a list of urls accessible for the current user to generate a navbar of course i can override some spring beans for that but this approach seems too dirty so any suggestions on how to do that maybe standard solutions,['java'] +495654,python slicing a multidimensional array i am new to python and numpy i have figured out how to slice 1 dimension arratartend and access an element in the array el arowcoltrying something like slice arr0202 where arr is a numpy array does not give me the first 2 rows and columns but repeats the first 2 rows what did i just do and how do i slice along another dimension,['python'] +495708,passing data from controller to view in a php mvc app in almost all tutorials or answers on so i see a common way to send data from a controller to the view the class view often looks something similar than the code belowclass view protected file protected data array public function constructfile this file file public function setkey value this datakey value public function getkey return this datakey public function output if file existsthis file throw new exceptiontemplate this file does not exist extractthis data ob start includethis file output ob get contents ob end clean echo output i do not understand why i need to put the data in an array and then call extractthis datawhy not just put directly some properties to the view from the controller like this viewtitle hello worldthen in my layout or template file i could just doecho thistitle,['php'] +495762,body backgroundcolor works in html but not in css am able to set the backgroundcolor attribute for html body in an inline style commandbut not when the identical command is moved to an external stylesheet a specific exampleis given below in test1html backgroundcolor is set to blue in the html file test2html is identical to test1html except the style command is commented out file stylecss contains a spec for backgroundcolor and also for the h1 element to test that the browser really is reading the stylesheetfirst test produces orange text against a blue background second test produces orangetext but against a white background i have tried this on firefox 21 chrome 19 and ie 9 all give the same resultswhats going on any help would be appreciatedhere are the three sample filestest1htmlhtmlhead link typetextcss relstylesheet hrefstylecstyle typetextcss body backgroundcolor bluestyle headbody h1this is a testh1 body htmltest2htmlhtmlhead link typetextcss relstylesheet hrefstylecss style typetextcss body backgroundcolor blue style headbody h1this is a testh1 body htmlstylecstyle typetextcss body backgroundcolor green h1 color orange stylethank you,"['html', 'css']" +495773,non uniform grid float hey im trying to make a floating grid that has different shapeshere is my goal and whats happening as you can see there is a gap under the horizontal piece im trying to fix it without having to use any positioning so that i can add boxes on later or move them aroundcode html li classmediumbox a hrefimg src height205 width430a li li classlargebox a hrefimg src height430 width430a li li classverticlemediumbox a hrefimg src height430 width205a li li clasmallbox a hrefimg src height205 width205a li li clasmallbox a hrefimg src height205 width205a li li clasmallbox a hrefimg src height205 width205a li li clasmallbox a hrefimg src height205 width205a li uldivbodycssbodybackgroundcolor fdf9height 100width 100contentbackgroundcolor redheight autowidth 900pxmargin 5em auto 0 autowork ulliststyle nonework lifloat leftmargin 10pxwork li athisplay blockwork li smallboxfloat leftthisplay blockwork li mediumboxfloat leftthisplay blockwork li verticlemediumboxfloat leftthisplay blockwork li largeboxfloat leftthisplay blockhere is my codefor some reason the jsfiddle version does not look like my chrome version,"['html', 'css']" +495797,controlling content flow with prawn let us say we want to thisplay a title on the first page that takes up the top half of the page the bottom half of the page should then fill up with our article text and the text should continue to flow over into the subsequent pages until it runs outthis is a pretty basic layout scenario but i do not understand how one would implement it in prawnheres some example code derived from their online documentationpdf prawndocumentnew do text the prince align center size 48 text niccola2 machiavelli align center size 20 move down 42 column box0 cursor columns 3 width boundswidth do textendgsubs nn 20 all the states and governments by which men are or ever have been ruled have been and are either republics or princedoms princedoms are either hereditary in which the bla bla bla bla end endendrenderbut that will just continue to show the title space for every pagewhats the right way to do this,['ruby'] +495826,unit testing a class that tracks state i am abstracting the history tracking portion of a class of mine so that it looks like thisprivate readonly stackmyobject pasthistory new stackmyobjectinternal virtual boolean isanyhistory get return pasthistoryany internal virtual void addobjecttohistorymyobject myobject if myobject null throw new argumentnullexceptionmyobject pasthistorypushmyobjectinternal virtual myobject removelastobject ifisanyhistory throw new invalidoperationexceptionthere is no previous history return pasthistorypopmy problem is that i would like to unit test that remove will return the last added objectaddobjecttohistoryremoveobjecttohistory returns what was put in via addobjecttohistoryhowever it is not really a unit test if i have to call add first but the only way that i can see to do this in a true unit test way is to pass in the stack object in the constructor or mock out isanyhistorybut mocking my sut is odd also so my question is from a dogmatic view is this a unit test if not how do i clean it upis constructor injection my only way it just seems like a stretch to have to pass in a simple object is it ok to push even this simple object out to be injected,"['c#', '.net']" +495880,postgresql exception an io error occured while sending to the backend i am testing some code which processes registration to a website the java code is as follows excerptif requestgetparametermethodequalscheckemail string email requestgetparameteremail resultset rs null preparedstatement ps dbpreparestatementquery pssetstring1 email rs psexecutequery ifrsnext email already present in db else proceed with registrationmost of the time the process executes without any problem but i am getting an intermittent issue where it fails because connection to the database is closing every time it fails it fails at the same point when running the prepared statement above which checks whether the email being submitted is already in the database obviouslyversion of postgres is 8123any help or suggestions appreciated stacktrace is as follows edit sometimes the stacktrace says caused by stream closed and sometimes socket closed as below135300973 error registration334 orgpostgresqlutilpsqlexception an io error occured while sending to the backend at orgpostgresqlcorev3queryexecutorimplexecutequeryexecutorimpljava283 at orgpostgresqljdbc2abstractjdbc2statementexecuteabstractjdbc2statementjava479 at orgpostgresqljdbc2abstractjdbc2statementexecutewithflagsabstractjdbc2statementjava367 at orgpostgresqljdbc2abstractjdbc2statementexecutequeryabstractjdbc2statementjava271 at registrationdopostregistrationjava113 at javaxservlethttphttpservletservicehttpservletjava637 at javaxservlethttphttpservletservicehttpservletjava717 at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava290 at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava206 at orgapachecatalinacorestandardwrappervalveinvokestandardwrappervalvejava233 at orgapachecatalinacorestandardcontextvalveinvokestandardcontextvalvejava191 at orgapachecatalinacorestandardhostvalveinvokestandardhostvalvejava128 at orgapachecatalinavalveserrorreportvalveinvokeerrorreportvalvejava102 at orgapachecatalinavalvesaccesslogvalveinvokeaccesslogvalvejava567 at orgapachecatalinacorestandardenginevalveinvokestandardenginevalvejava109 at orgapachecatalinaconnectorcoyoteadapterservicecoyoteadapterjava293 at orgapachejkserverjkcoyotehandlerinvokejkcoyotehandlerjava190 at orgapachejkcommonhandlerrequestinvokehandlerrequestjava291 at orgapachejkcommonchannelsocketinvokechannelsocketjava769 at orgapachejkcommonchannelsocketprocessconnectionchannelsocketjava698 at orgapachejkcommonchannelsocketsocketconnectionrunitchannelsocketjava891 at orgapachetomcatutilthreadsthreadpoolcontrolrunnablerunthreadpooljava690 at javalangthreadrunthreadjava595caused by javanetsocketexception socket closed at javanetsocketinputstreamsocketread0native method at javanetsocketinputstreamreadsocketinputstreamjava129 at orgpostgresqlcorevisiblebufferedinputstreamreadmorevisiblebufferedinputstreamjava135 at orgpostgresqlcorevisiblebufferedinputstreamensurebytesvisiblebufferedinputstreamjava104 at orgpostgresqlcorevisiblebufferedinputstreamreadvisiblebufferedinputstreamjava73 at orgpostgresqlcorepgstreamreceivecharpgstreamjava259 at orgpostgresqlcorev3queryexecutorimplprocessresultsqueryexecutorimpljava1620 at orgpostgresqlcorev3queryexecutorimplexecutequeryexecutorimpljava257 22 more,['java'] +495920,plugin editor html tinymce vs ckeditor i want to develop a plugin for a html editorwhich webbased html editor can i make a better and fast plugin ia m not sure abouttinymceckeditor,['html'] +495930,how can i efficiently determine if an ienumerable has more than one element given an initialised ienumerableienumerablet enumerablei would like to determine if it has more than one element i think the most obvious way to do this isenumerablecount 1however i believe count enumerates the whole collection which is unnecessary for this use case for example if the collection contains a very large amount of elements or provided its data from an external source this could be quite wasteful in terms of performancehow can i do this without enumerating any more than 2 elements,['c#'] +495948,socketio handling thisconnect event cant handle this thisconnect event dont know why socket its not send to the client client doesnt responseserveriosocketsonconnection function socket socketonnewplayer functiondata1 online online 1 consolelogonline players online consolelognew player connected data1 playersdata1 data1 consolelogplayers socketondelplayer functiondata delete playersdata consolelogplayers consolelogadios data socketonthisconnect function socketemitthisconnected online online 1 client var socket ioconnecthttplocalhost socketonconnect function person name promptwelcome please enter your name socketemitnewplayer person name socketonthisconnected function socketemitdelplayer person name as you can see when a client thisconnects the array objectperson name should be deleted but its not,['javascript'] +495952,must you set references to null for garbage collection to work hi i am attempting to thiscover why my programs usually run slower than i want them so thank you in advance for your helpi have for example a piece of code that i would like some insight into1 whileconditionistrue2 object object new object3 in line 2 i create a new object this will happen thousands of times in my program do i specifically have to null the old object out before gc will destroy it or will gc go behind my program picking up all the memory those other objects usedor another option altogether is this happening a certain amount of memory is being allocated and every time i create a new object it is then assigned to that exact same memorybruno asked me to show a more realistic piece of code so we could figure out why it was running slowly but because of your answer bruno i realized that i had my code like this1 object object null2 whileconditionistrue3 object new object4 so i realized i had strong references to my objects thank you bruno,['java'] +495959,literal types 0x1ull vs 0x1llu my gcc compiler allows me to define an unsigned long long ie 64bit literal asdefine a literal 0x1ull or define a literal 0x1lluis there any difference between these two literal statements is this common to other c compilers,['c'] +495970,highcharts set maximum range for yaxis but keep axis dynamic within that range first of all apologies for the post title but i failed to come up with a better one to describe my problemis there a way in highcharts to set the maximum value for the yaxis to say 10 ie via max 10 but keep it dynamic if the maximum values are lower than the set maximum as an example let us say we have two datasets the first one ranges between 0 and 1500 here any data 10 should not be thisplayed setting yaxis max 10 does the tricknow we update the data series with the second data set which ranges between 0 and 48 now max 10 causes the line to virtually hug the xaxis so here it would be best if highcharts dynamically adjusts the yaxis to range from 050heres a fiddle to illustrate the problem psjust noticed the minrange setting in highcharts now why is not there a maxrange equivalent or is there,['jquery'] +495989,vs backgroundimage css in performance i am building a site that is using a scrolling plugin that basically animates the scrollingi am quite concern about performance as if i insert some images in the site it looks quite choppy when scrollinganimatingthe main problem i can detect with images is the reflowrepaint issue when the image does not have the correct dimensions and therefore is scaled i have to deal with this i know about the best practicewith this statement in mind images will be scaled what should be better image element or divs with those images as backgrounds as for performancei made this jsfiddles that in my chrome browser memory tool show that the background image option uses less memoryimg img src backgroundimage divdivdiv backgroundurl backgroundsize100 100referencesdifference in performance between img tag elements vs divs with background imageswhen to use img vs css backgroundimage,['css'] +496035,how to access parse error in runtimecreated function in php i have this simple php codephpcode echo hello world call user funccreate function codeas you see my code has syntax error when i run this i get this resultparse error syntax error unexpected in filephp4 runtimecreated function on line 1warning call user func expects parameter 1 to be a valid callback no array or string given in filephp on line 4how can i get the parse error into a variable for exampleerror some func to get errorecho error parse error syntax error unexpected in filephp4 runtimecreated function on line 1,['php'] +496127,soap enabler maven build failure trying to run a new sample project with soap enabler and i keep getting a build failed exception i double checked the system variables and everything seems fine in my maven local repoinfo scanning for projectsinfoinfo info building sample 10snapshotinfo infoinfo androidmavenplugin360generatesources defaultgeneratesources sample warning error injecting comjaywaymavenpluginsandroidphase01generatesourcesgeneratesourcesmojojavalangnoclassdeffounderror lorgsonatypeaetherrepositorysystem at javalangclassgetdeclaredfields0native method at javalangclassprivategetdeclaredfieldsclassjava2317 at javalangclassgetdeclaredfieldsclassjava1762 at comgoogleinjectspiinjectionpointgetinjectionpointsinjectionpointjava661 at comgoogleinjectspiinjectionpointforinstancemethodsandfieldsinjectionpointjava366 at comgoogleinjectinternalconstructorbindingimplgetinternaldependenciesconstructorbindingimpljava165 at comgoogleinjectinternalinjectorimplgetinternaldependenciesinjectorimpljava609 at comgoogleinjectinternalinjectorimplcleanupinjectorimpljava565 at comgoogleinjectinternalinjectorimplinitializejitbindinginjectorimpljava551 at comgoogleinjectinternalinjectorimplcreatejustintimebindinginjectorimpljava865 at comgoogleinjectinternalinjectorimplcreatejustintimebindingrecursiveinjectorimpljava790 at comgoogleinjectinternalinjectorimplgetjustintimebindinginjectorimpljava278 at comgoogleinjectinternalinjectorimplgetbindingorthrowinjectorimpljava210 at comgoogleinjectinternalinjectorimplgetproviderorthrowinjectorimpljava986 at comgoogleinjectinternalinjectorimplgetproviderinjectorimpljava1019 at comgoogleinjectinternalinjectorimplgetproviderinjectorimpljava982 at comgoogleinjectinternalinjectorimplgetinstanceinjectorimpljava1032 at orgeclipsesisureflectabstractdeferredclassgetabstractdeferredclassjava44 at comgoogleinjectinternalproviderinternalfactoryprovisionproviderinternalfactoryjava86 at comgoogleinjectinternalinternalfactorytoinitializableadapterprovisioninternalfactorytoinitializableadapterjava55 at comgoogleinjectinternalproviderinternalfactory1callproviderinternalfactoryjava70 at comgoogleinjectinternalprovisionlistenerstackcallbackprovisionprovisionprovisionlistenerstackcallbackjava100 at orgeclipsesisuplexuslifecyclesplexuslifecyclemanageronprovisionplexuslifecyclemanagerjava134 at comgoogleinjectinternalprovisionlistenerstackcallbackprovisionprovisionprovisionlistenerstackcallbackjava109 at comgoogleinjectinternalprovisionlistenerstackcallbackprovisionprovisionlistenerstackcallbackjava55 at comgoogleinjectinternalproviderinternalfactorycirculargetproviderinternalfactoryjava68 at comgoogleinjectinternalinternalfactorytoinitializableadaptergetinternalfactorytoinitializableadapterjava47 at comgoogleinjectinternalinjectorimpl21callinjectorimpljava997 at comgoogleinjectinternalinjectorimplcallincontextinjectorimpljava1047 at comgoogleinjectinternalinjectorimpl2getinjectorimpljava993 at comgoogleinjectscopes11getscopesjava59 at orgeclipsesisulocatorslazybeanentrygetvaluelazybeanentryjava82 at orgeclipsesisuplexuslocatorslazyplexusbeangetvaluelazyplexusbeanjava52 at orgcodehausplexusdefaultplexuscontainerlookupdefaultplexuscontainerjava259 at orgcodehausplexusdefaultplexuscontainerlookupdefaultplexuscontainerjava251 at orgapachemavenplugininternaldefaultmavenpluginmanagergetconfiguredmojodefaultmavenpluginmanagerjava459 at orgapachemavenplugindefaultbuildpluginmanagerexecutemojodefaultbuildpluginmanagerjava97 at orgapachemavenlifecycleinternalmojoexecutorexecutemojoexecutorjava208 at orgapachemavenlifecycleinternalmojoexecutorexecutemojoexecutorjava153 at orgapachemavenlifecycleinternalmojoexecutorexecutemojoexecutorjava145 at orgapachemavenlifecycleinternallifecyclemodulebuilderbuildprojectlifecyclemodulebuilderjava84 at orgapachemavenlifecycleinternallifecyclemodulebuilderbuildprojectlifecyclemodulebuilderjava59 at orgapachemavenlifecycleinternallifecyclestartersinglethreadedbuildlifecyclestarterjava183 at orgapachemavenlifecycleinternallifecyclestarterexecutelifecyclestarterjava161 at orgapachemavendefaultmavendoexecutedefaultmavenjava318 at orgapachemavendefaultmavenexecutedefaultmavenjava153 at orgapachemavenclimavencliexecutemavenclijava5 at orgapachemavenclimavenclidomainmavenclijava214 at orgapachemavenclimavenclimainmavenclijava158 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava57 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43 at javalangreflectmethodinvokemethodjava601 at orgcodehausplexusclassworldslauncherlauncherlaunchenhancedlauncherjava290 at orgcodehausplexusclassworldslauncherlauncherlaunchlauncherjava230 at orgcodehausplexusclassworldslauncherlaunchermainwithexitcodelauncherjava414 at orgcodehausplexusclassworldslauncherlaunchermainlauncherjava357caused by javalangclassnotfoundexception orgsonatypeaetherrepositorysystem at orgcodehausplexusclassworldsstrategyselffirststrategyloadclaselffirststrategyjava50 at orgcodehausplexusclassworldsrealmclassrealmloadclassclassrealmjava244 at orgcodehausplexusclassworldsrealmclassrealmloadclassclassrealmjava230 57 moreinfo info build failureinfo info total time 0827sinfo finished at tue jun 25 123932 idt 2013info final memory 13m247minfo error failed to execute goal comjaywaymavenpluginsandroidgeneration2androidmavenplugin360generatesources defaultgeneratesources on project sample execution defaultgeneratesources of goal comjaywaymavenpluginsandroidgeneration2androidmavenplugin360generatesources failed a required class was missing while executing comjaywaymavenpluginsandroidgeneration2androidmavenplugin360generatesources lorgsonatypeaetherrepositorysystemerror error realm plugincomjaywaymavenpluginsandroidgeneration2androidmavenplugin360error strategy orgcodehausplexusclassworldsstrategyselffirststrategyerror urls0 filecusersshimitam2repositorycomjaywaymavenpluginsandroidgeneration2androidmavenplugin360androidmavenplugin360jarerror urls1 filecusersshimitam2repositorycomandroidtoolsbuildbuilder04builder04jarerror urls2 filecusersshimitam2repositorycomandroidtoolssdklib220sdklib220jarerror urls3 filecusersshimitam2repositoryorgapachehttpcomponentshttpclient411httpclient411jarerror urls4 filecusersshimitam2repositoryorgapachehttpcomponentshttpcore41httpcore41jarerror urls5 filecusersshimitam2repositorycommonsloggingcommonslogging1commonslogging1jarerror urls6 filecusersshimitam2repositorycommonscodeccommonscodec14commonscodec14jarerror urls7 filecusersshimitam2repositoryorgapachehttpcomponentshttpmime41httpmime41jarerror urls8 filecusersshimitam2repositorycomandroidtoolslayoutliblayoutlibapi220layoutlibapi220jarerror urls9 filecusersshimitam2repositorycomandroidtoolsdvlib220dvlib220jarerror urls10 filecusersshimitam2repositoryorgapachecommonscommonscompress10commonscompress10jarerror urls11 filecusersshimitam2repositorycomandroidtoolsbuildbuildertestapi04buildertestapi04jarerror urls12 filecusersshimitam2repositorycomandroidtoolsbuildbuildermodel04buildermodel04jarerror urls13 filecusersshimitam2repositorycomandroidtoolscommon220common220jarerror urls14 filecusersshimitam2repositorycomgoogleguavaguava1301guava1301jarerror urls15 filecusersshimitam2repositorycomandroidtoolssdkcommon220sdkcommon220jarerror urls16 filecusersshimitam2repositorycomandroidtoolsddmsddmlib220ddmlib220jarerror urls17 filecusersshimitam2repositorynetsfkxmlkxml2230kxml2230jarerror urls18 filecusersshimitam2repositorycomandroidtoolsbuildmanifestmerger220manifestmerger220jarerror urls19 filecusersshimitam2repositoryorgbouncycastlebcpkixjdk15on148bcpkixjdk15on148jarerror urls20 filecusersshimitam2repositoryorgbouncycastlebcprovjdk15on148bcprovjdk15on148jarerror urls21 filecusersshimitam2repositoryorgsonatypesisusisuinjectbean211sisuinjectbean211jarerror urls22 filecusersshimitam2repositoryorgsonatypesisusisuguice294sisuguice294no aopjarerror urls23 filecusersshimitam2repositoryorgcodehausplexusplexusinterpolation114plexusinterpolation114jarerror urls24 filecusersshimitam2repositoryorgcodehausplexusplexuscomponentannotations155plexuscomponentannotations155jarerror urls25 filecusersshimitam2repositoryorgsonatypeplexusplexussecthispatcher13plexussecthispatcher13jarerror urls26 filecusersshimitam2repositoryorgsonatypeplexusplexuscipher14plexuscipher14jarerror urls27 filecusersshimitam2repositoryorgapachemavenmavenarchiver25mavenarchiver25jarerror urls28 filecusersshimitam2repositoryemmaemma215320emma215320jarerror urls29 filecusersshimitam2repositoryorgcodehausplexusplexusarchiver23plexusarchiver23jarerror urls30 filecusersshimitam2repositoryjunitjunit381junit381jarerror urls31 filecusersshimitam2repositoryorgcodehausplexusplexusio206plexusio206jarerror urls32 filecusersshimitam2repositoryorgcodehausplexusplexusutils3010plexusutils3010jarerror urls33 filecusersshimitam2repositorycommonsjxpathcommonsjxpath13commonsjxpath13jarerror urls34 filecusersshimitam2repositorycommonsiocommonsio24commonsio24jarerror urls35 filecusersshimitam2repositoryorgow2asmasm41asm41jarerror urls36 filecusersshimitam2repositorycommonslangcommonslang26commonslang26jarerror urls37 filecusersshimitam2repositoryorgsonatypeaetheraetherutil1131aetherutil1131jarerror urls38 filecusersshimitam2repositorycomgithubrtyleyandroidscreenshotpaparazzo19androidscreenshotpaparazzo19jarerror urls39 filecusersshimitam2repositorycommadgaganimatedgiflib10animatedgiflib10jarerror urls40 filecusersshimitam2repositorycomgithubrtyleyandroidscreenshotcelebrity18androidscreenshotcelebrity18jarerror number of foreign imports 1error import entryimport from realm classrealmprojectfrnorsysasoapeitsample10snapshot parent classrealmmavenapi parent nullerrorerror orgsonatypeaetherrepositorysystemerror help 1errorerror to see the full stack trace of the errors rerun maven with the e switcherror rerun maven using the x switch to enable full debug loggingerrorerror for more information about the errors and possible solutions please read the following articleserror help 1 the pom file xml version10 encodingutf8project xmlns xmlnsxsi xsischemalocation 0 0xsd modelversion400modelversion groupidfrnorsysasoapeitgroupid artifactidsampleappartifactid version10snapshotversion packagingapkpackaging properties asoapeversion11asoapeversion properties dependencies dependency groupidfrnorsysasoapegroupid artifactidruntimelibraryartifactid versionasoapeversionversion dependency dependency groupidcomgoogleandroidgroupid artifactidandroidartifactid version16 r2version scopeprovidedscope dependency dependencies build finalnameprojectartifactidfinalname sourcedirectorysrcsourcedirectory plugins plugin groupidfrnorsysasoapegroupid artifactidasoapemavenpluginartifactid versionasoapeversionversion executions execution goals goalgeneratesoapstubgoal goals phasegeneratesourcesphase configuration definitionsdirectoryprojectbasedirwsdldefinitionsdirectory configuration execution executions plugin plugin groupidcomjaywaymavenpluginsandroidgeneration2groupid artifactidandroidmavenpluginartifactid version300version extensionstrueextensions configuration gendirectorygengendirectory sdk pathenvandroid homepath platform4platform sdk deleteconflictingfilestruedeleteconflictingfiles undeploybeforedeploytrueundeploybeforedeploy configuration executions execution idalignapkid phasepackagephase goals goalzipaligngoal goals execution executions plugin plugin groupidorgapachemavenpluginsgroupid artifactidmavencompilerpluginartifactid version232version configuration source15source target15target configuration plugin plugin groupidorgapachemavenpluginsgroupid artifactidmaveneclipsepluginartifactid version28version configuration additionalbuildcommands buildcommandcomandroidideeclipseadtresourcemanagerbuilderbuildcommand buildcommandcomandroidideeclipseadtprecompilerbuilderbuildcommand buildcommandcomandroidideeclipseadtapkbuilderbuildcommand additionalbuildcommands additionalprojectnatures projectnaturecomandroidideeclipseadtandroidnatureprojectnature additionalprojectnatures classpathcontainers classpathcontainercomandroidideeclipseadtandroid frameworkclasspathcontainer classpathcontainers downloadsourcestruedownloadsources excludes excludecomgoogleandroidandroidexclude excludecommonsloggingcommonsloggingexclude excludeorgapachehttpcomponentshttpclientexclude excludeorgapachehttpcomponentshttpcoreexclude excludecommonscodeccommonscodecexclude excludeorgkhronosopenglapiexclude excludexercesxmlparserapisexclude excludexpp3xpp3exclude excludes configuration plugin plugins buildprojectthanks,['android'] +496171,a cycle is detected in the object graph this will cause infinitely deep xml i have two dto objects say a and b which are having getters and setters and are used to take data from the database the problem is when i am calling a b gets called and b again points itself to a and a cycle is created i cannot ignorehide the method which is creating the cycle i need to take the whole data of a and bis there any way to achieve it please helpthis is my code which is causing the problem this is application dto which is calling environment dtoonetomanymappedbyapplication fetchfetchtypelazy cascadecascadetypeall public setenvironmentdto getenvironment return environmentpublic void setenvironmentsetenvironmentdto environment thisenvironment environmentand this is environment dto which is calling the application dtomanytoonetargetentityapplicationdtoclass joincolumnnamefk application id public applicationdto getapplication return applicationpublic void setapplicationapplicationdto application thisapplication applicationhere cycle is getting createdthis is my rest call which will give result in xml format and i think while creating xml cycle is getting createdgetpathgetproducesmediatypeapplication xmlpublic listapplicationdto getallapplications listapplicationdto allapplication applicationservicegetallapplication return allapplicationthis is the application dto classentitytablenameapplicationorghibernateannotationsgenericgeneratorname testincrementstrategystrategy incrementxmlrootelementpublic class applicationdto implements serializable xmlattributepublic long apptypeidprivate static final long serialversionuid 80277210927935073lprivate long applicationidprivate string applicationnameprivate applicationtypedto applicationtypeprivate string applicationdescriptionprivate integer ownerprivate integer createdbyprivate integer assignedtoprivate date createtimeprivate date modifiedtimeprivate setenvironmentdto environmentidgeneratedvaluegenerator testincrementstrategycolumnname applicationidpublic long getapplicationid return applicationidprivate void setapplicationidlong applicationid thisapplicationid applicationidcolumnname applicationnamepublic string getapplicationname return applicationnamepublic void setapplicationnamestring applicationname thisapplicationname applicationnamemanytoonetargetentityapplicationtypedtoclass fetch fetchtypelazy joincolumnnameapplicationtypepublic applicationtypedto getapplicationtype return applicationtypepublic void setapplicationtypeapplicationtypedto applicationtype thisapplicationtype applicationtypecolumnname descriptionpublic string getapplicationdescription return applicationdescriptionpublic void setapplicationdescriptionstring applicationdescription thisapplicationdescription applicationdescriptioncolumnname ownerpublic integer getowner return ownerpublic void setownerinteger owner thisowner ownercolumnname createdbypublic integer getcreatedby return createdbypublic void setcreatedbyinteger createdby thiscreatedby createdbycolumnname assignedtopublic integer getassignedto return assignedtopublic void setassignedtointeger assignedto thisassignedto assignedtocolumnname createtimepublic date getcreatetime return createtimepublic void setcreatetimedate createtime thiscreatetime createtimecolumnname modifiedtimepublic date getmodifiedtime return modifiedtimepublic void setmodifiedtimedate modifiedtime thismodifiedtime modifiedtimeonetomanymappedbyapplication fetchfetchtypelazy cascadecascadetypeall public setenvironmentdto getenvironment return environmentpublic void setenvironmentsetenvironmentdto environment thisenvironment environmentthis is the environment dto classentitytablenameenvironmentorghibernateannotationsgenericgeneratorname testincrementstrategystrategy incrementxmlrootelementpublic class environmentdto implements serializable xmlattributepublic long envtypeidxmlattributepublic long appidprivate static final long serialversionuid 27564269967963698lprivate long environmentidprivate string environmentnameprivate environmenttypedto environmenttypeprivate integer ownerprivate date createtimeprivate setinstancedto instancesprivate applicationdto applicationidgeneratedvaluegenerator testincrementstrategycolumnname envidpublic long getenvironmentid return environmentidprivate void setenvironmentidlong environmentid thisenvironmentid environmentidcolumnname envnamepublic string getenvironmentname return environmentnamepublic void setenvironmentnamestring environmentname thisenvironmentname environmentnamemanytoonetargetentityenvironmenttypedtoclassjoincolumnname envtypepublic environmenttypedto getenvironmenttype return environmenttypepublic void setenvironmenttypeenvironmenttypedto environmenttype thisenvironmenttype environmenttypecolumnname ownerpublic integer getowner return ownerpublic void setownerinteger owner thisowner ownertemporaltemporaltypedatecolumnname createtimepublic date getcreatetime return createtimepublic void setcreatetimedate createtime thiscreatetime createtimeonetomanymappedbyenvironment cascadecascadetypeall fetch fetchtypeeagerpublic setinstancedto getinstances return instancespublic void setinstancessetinstancedto instances thisinstances instancesmanytoonetargetentityapplicationdtoclass joincolumnnamefk application idxmltransient public applicationdto getapplication return applicationpublic void setapplicationapplicationdto application thisapplication application,['java'] +496172,android property animation objectanimator androidpropertynamestring androiddurationint androidvaluefromfloat int color androidvaluetofloat int color androidstartoffsetint androidrepeatcountint androidrepeatmoderepeat reverse androidvaluetypeinttype floattypeok i am learning some animation in android i got it from google developer docs two attributes that actually i am not able to understand areandroidpropertynamestringandroidvaluetypeinttype floattypesome of the values make sense fade rotation alphabut what about others like endyear firstdayofweekand i failed to find any detailed documentation about these or there may be chances that i am not understanding what various tutorials and google docs trying to conveymy doubt is from where i can get all possible values of propertyname and what is valuetype i mean what actually it do how actually it affect the animationi am following this tutorial and was trying to play with properties so as to have better understandingfor say below attached screenshot shows so many possibilities for propertyname but i dont know how they make sensemore over propertyname accepts x and y as it values but they do not come in the windowin case of valuetype if i change floattype to inttype in the below mention snippet of the tutorial for wheelobjectanimator androidduration30 androidpropertynamerotation androidrepeatcountinfinite androidrepeatmodereverse androidvalueto180 androidvaluetypefloattype it stops animatingcan any one explain this issue or a source so as that i can figure it outthis is what is explained in google docsnote i am trying animation for the first time not only with android but in my life too,['android'] +496226,hashing composite objects editthis question is not about bitwise operators and cannot be answered with why are xor often used in java hashcode but another bitwise operators are used rarelyi have seen different approaches for hash calculation of objectclass a public b b public c c override public boolean equals override public int hashcode return chashcode bhashcode xor return chashcode prime bhashcode sum return objectshashbc lib it seems lib method uses sum but why is it better than xoreven though the example is in java this question is more about math and probabilities,['java'] +496238,http error 40314 forbidden mvc 4 with iis express this seems like a question that has already been askedanswered many times its notdevelopment environmentvs 2012 and mvc 4 i am using the built in iis express to run the app this error was not occurring until yesterday it suddenly began to occur and i am stuck its strange that it occurs only in one scenariowhen i try to access httplocalhost49962managescholars it shows me the error http error 40314 forbiddenthe web server is configured to not list the contents of this directorybut using httplocalhost49962managescholarsindex works fine other action methods of same controller also work fine such as httplocalhost49962managescholarscreate all other controllers work fine as welli have tried adding the following to webconfigsystemwebserver validation validateintegratedmodeconfigurationfalse modules runallmanagedmodulesforallrequeststrue handlerssystemwebserveri also have tried running the following command as administratorwindirmicrosoftnetframework64v4030319aspnet regiisexe irbut none of them worked editi have modified my routes they look as follows public static void registerroutesroutecollection routes routesignorerouteresourceaxdpathinfo routesmaproute name managescholarlectures url managelecturesuserfriendlyname defaults new controller mvcmanagelecturesname action mvcmanagelecturesactionnamesindex userfriendlyname urlparameteroptional routesmaproute name managescholaredit url managescholarsuserfriendlyname defaults new controller mvcmanagescholarsname action mvcmanagescholarsactionnamesedit routesmaproute name default url controlleractionid defaults new controller mvchomename action mvchomeactionnamesindex id urlparameteroptional i am using t4mvc templateit still does not work even if i leave the default route at the bottom and remove the first two routes what have i done wrongthanks a lot in advance for your help,['c#'] +496328,why do i get a string encoding issue xe2 from ascii8bit to utf8 i am trying to download a pdf from an email and write the contents to a file for some reason i am getting this erroran encodingundefinedconversionerror occurred in attachmentsinbound xe2 from ascii8bit to utf8 appcontrollersapiattachments controllerrb70in writeheres my codedef inbound if railsenvproduction or railsenvstaging email postmarkmittnewrequestbodyread else email postmarkmittnewfilebinread railsrootapptemp pdfsemailjson end if emailattachmentscount 0 notify aidin that we got an inbound email with no attachments respond to do format formatjson head no content end return end attachment emailattachmentsfirst filename attachment timenowstrftimeymdhmsrand 10roundto s pdf base path railsroottemp attachments unless filedirectorybase path dirmkdirbase path end file filenew base path filename w filewrite base64decode64attachmentsourcecontentencodeutf16be invalidreplace replaceencodeutf8 fileclose write options write options write optionsmetadata filename attachmentfile name content type attachmentcontent type size attachmentsize obj s3 object file fileopen filepath objwritefileread write options fileclose faxattachtrigger objkeysplitlast render nothing true status 202 and return endi read around and it looked like the way to solve this wasfilewrite base64decode64attachmentsourcecontentencodeutf16be invalidreplace replaceencodeutf8but it does not seem to work,"['ruby-on-rails', 'ruby']" +496339,push certificate not appearing when creating a profile in ios dev portal i have created a dev push certificate for my app following these steps and i can see the certificate appearing in the certificates section of the portalnow i am trying to create a provisioning profile which includes the certificate however when the portal asks which certificates to include in the profile the one i just created is not listedi have triplechecked that the app id i used to create the certificate is the same as the app id i am using to create the profile and if i examine the app id the green dot has appeared next to the push enabled sectionso why is the certificate not appearing as an option when creating the profile,['ios'] +496361,access to the registry key global is denied when accessing performance counters i am attempting to read some performance counters from my aspnet application when i do i get the error access to the registry key global is deniedi have tried following the instructions here and here using the user iis apooldefaultapool which is the identity my app pool is configured to usei have added that user to the performance monitor users groupand after adding the user i restarted my computer but i am still getting the errori have also tried adding the users iusr and network service to the performance monitor users group but those do not work either out of desperation i tried adding the user everyone to the performance monitor users group and that actually does work but my goal is to log statistics from my application in production and i do not want to add everyone to that group on the production serverwhat else needs to happen in order to read the performance counters without generating a security exception,['asp.net'] +496373,enhanced for loop starting part way through list im a beginner in java and i had this doubt is it possible to use the enhanced for loop in java on an arraylist but start at the specified point rather than arraylist0for eg arraylistinteger calc new arraylistinteger calc contains 01234567can i use enhanced for loop and start iterating from calc2 rather than calc0 if possible how can i do thatin my particular case using a enhanced for loop would be better rather than a normal for loop,['java'] +496403,pass object list as part of exception i am constructing a list of strings and then want to throw an exception and let the ui handle the list and create the error message for the useris there a way to do that,['c#'] +496517,how to get 2 digit year w javascript i am trying to find some javascript code that will write the current date in this format mmddyyeverything i have found uses 4 digit years and i need 2 digit,['javascript'] +496545,php composer behind http proxy i use composer on a network where the only way to access the internet is using http or socks proxy i have http proxy and https proxy environment variables when compose tries to access https urls i get this file could not be downloaded failed to open stream cannot connect to https server through proxyas far as i know the only way to connect to a https website is using a connect verb how can i use composer behind this proxy,['php'] +496564,blocked a frame with origin from accessing a frame with origin suddenly starts to give this error blocked a frame with origin from accessing a frame with origin httpcom the frame requesting access set documentdomain to facebookcom but the frame being accessed did not both must set documentdomain to the same value to allow access,['javascript'] +496572,ember app requests to rails app cross domain i have two separate apps an ember app and a rails app on the same server right now i am testing locallymy ember requests are not going out to the rails localhost30 i cannot seem to figure out if that is happening because it thinks that it is a crossdomain request will it be considered a crossdomain request even though they are on the same server if so is there anyway to avoid this crossdomain request since they are on the same server without compromising security or do i need to stick to jsonp,"['javascript', 'ruby-on-rails']" +496597,finding middle element of linked list with 1 pass is this a creative useless answer suppose you want to find the middle node of a linked list in as efficient a way possible the most typical best answer given is to maintain 2 pointers a middle and current and to increment the middle pointer when the of elements encountered is divisible by 2 hence we can find the middle in 1 pass efficient right better than brute force which involves 1 pass to the end then 1 more pass until we reach size2but not so fast why is the first method faster than the brute force way in the first method were incrementing the middle pointer approximately size2 times but in the brute force way in our 2nd pass were traversing the list until we reached the size2th node so are not these 2 methods the same why is the first better than the 2nd finding middle element of linkedlist in single pass linkedlistnode current head int length 0 linkedlistnode middle head whilecurrentnext null length iflength2 0 middle middlenext current currentnext iflength2 1 middle middlenext,['java'] +496613,bootstrap affix changing list item width i am using twitter bootstraps affix to affix the left column which currently holds a navigation listdiv classrow div claspan3 ul classnav navlist dataspyaffix dataoffsettop300 li classnavheadernavigationli lia hreflink1ali lia hreflink2ali ul divfrom my understanding this means that affix would not kick in until 300px have been scrolled my problem is that the width of my list item changes after affix kicks inhere is a screenshot of my hovering over a list item before affix kicks in you can based on the hover background the width is correcthere is a screenshot after i have scrolled 300px and affix kicks in you can see that for some reason the width decreasesi want to know why this is happening how to correct it and if i am using affix correctly,"['javascript', 'css']" +496632,crossplatform c implementation of lua i am looking for a way to embed lua into my crossplatform embed application the problem is i have not found any complete stable working implementation of lua on this platform i have tried the following here are the list of repositories and their problemsluainterface require me to compile a dll for every platform unstable since v2 uses windowskopilua errors even their own samples does not workaluminiumlua depends on dll therefore not an implementationnlua based on kopilua and inherits all the problemsunilua it is for unityalso most of these implementations fails when i do a simple testfori0i10i luacallsomefunctionfromluafrom time to time it invokes an error especially on kopilua and luainterfacethe question is is there any complete stable implementation of lua strictly in c without any platform dependencies,"['c#', '.net']" +496643,c class can not thisguise to be another class because gettype method cannot be override there is a statement in the clr via c sayingin c one class cannot thisguise to be another because gettype is virutal and thus it cannot be overridebut i think in c we can still hide the parent implementation of gettypei must missed somethingif i hide the base gettype implementation then i can thisguise my class to be another class is that correctthe key here is not whether gettype is virutal or not the question is can we thisguise one class to be another in cfollowing is the no4 answer from the possible duplicate so my question is more on thisis this kind of thisguise possible if so how can we say that we can prevent class type thisguise in c regardless of the gettype is virtual or notwhile its true that you cannot override the objectgettype method you can use new to overload it completely thereby spoofing another known type this is interesting however i have not figured out how to create an instance of the type object from scratch so the example below pretends to be another typepublic class notastring private string m realstring stringempty public new type gettype return m realstringgettype after creating an instance of this new notastringgettype will indeed return the type for a stringshareeditflag answered mar 15 at 1839dr snooze 213 by almost anything that looks at gettype has an instance of object or at the very least some base type that they control or can reason about if you already have an instance of the most derived type then there is no need to call gettype on it the point is as long as someone uses gettype on an object they can be sure it is the systems implementation not any other custom definition a servy mar 15 at 1854 add comment,['c#'] +496654,pass operator as function template parameter i have to overload the basic arithmetic operators for some very complicated objects i have made so far i have successfully implemented operator now i need operator etc the code for operator is very large but the only difference between operator and operator will be one line where i use instead of on some complex numbers this line will be inside of a loop that gets called many many times so i want it to be efficient which would seem to imply no function pointers correct me if i am wrongthis seems like a perfect use for templates but i am at a loss as to the correct syntax i am thinking something like this inside the complicatedobject class definitiontemplate typename complexbinaryopcomplicatedobject binaryopconst complicatedobject b const do lots of stuff forunsigned int i0 ionebazillion i here the fi are stdcomplexdoubles cfi complexbinaryopfi bfi do some more stuff return cinline complicatedobject operatorconst complicatedobject b const return binaryopstdcomplexoperatorbinline complicatedobject operatorconst complicatedobject b const return binaryopstdcomplexoperatorbthis question is related function passed as template argument but the functions passed as the template arguments are not operatorsi have fiddled with the syntax every way i can think of but the compiler always complains of bad syntax how should i do thiseditfor clarity i include the complete solution in terms of my code above along with the additional generalizations people may needtemplate typename complexbinaryopcomplicatedobject binaryopconst complicatedobject b const do lots of stuff forunsigned int i0 ionebazillion i here the fi are stdcomplexdoubles cfi complexbinaryopfi bfi note extra s do some more stuff return cinline complicatedobject operatorconst complicatedobject b const return binaryopstdplusstdcomplexdouble binline complicatedobject operatorconst complicatedobject b const return binaryopstdminusstdcomplexdouble binline complicatedobject operatorconst complicatedobject b const return binaryopstdmultipliesstdcomplexdouble binline complicatedobject operatorconst complicatedobject b const return binaryopstddividesstdcomplexdouble b,['c++'] +496660,rails 40 sporkactiverecord exception i have been using michael hartls rails tutorial to pick up ruby on rails and have recently been going through the new rails 40 version of the tutorial i have encountered an issue with spork i know that were using a custom fork of spork for rails 40 compatibility and that this may just be a different incompatibility but i wanted to post my issue and see if i was just doing something wrong or if anyone had any ideas whenever i call rspec while spork is running i get an activerecord exception while if i call rspec by itself my tests run successfully an example terminal dump is beloworenvmruby projectstest app rspecexception encountered activerecordconnectionnotestablished activerecordconnectionnotestablishedbacktracehomeorenrvmgemsruby200p195rails 4 0gemsactiverecord400libactive recordconnection adaptersabstractconnection poolrb546in retrieve connectionhomeorenrvmgemsruby200p195rails 4 0gemsactiverecord400libactive recordconnection handlingrb79in retrieve connectionhomeorenrvmgemsruby200p195rails 4 0gemsactiverecord400libactive recordconnection handlingrb53in connectionhomeorenrvmgemsruby200p195rails 4 0gemsactiverecord400libactive recordmigrationrb792in current versionhomeorenrvmgemsruby200p195rails 4 0gemsactiverecord400libactive recordmigrationrb800in needs migrationhomeorenrvmgemsruby200p195rails 4 0gemsactiverecord400libactive recordmigrationrb379in check pendinghomeorenruby projectstest appspecspec helperrb105in top requiredhomeorenrvmgemsruby200p195rails 4 0gemsactivesupport400libactive supportdependenciesrb2in loadhomeorenrvmgemsruby200p195rails 4 0gemsactivesupport400libactive supportdependenciesrb2in block in loadhomeorenrvmgemsruby200p195rails 4 0gemsactivesupport400libactive supportdependenciesrb213in load dependencyhomeorenrvmgemsruby200p195rails 4 0gemsactivesupport400libactive supportdependenciesrb2in loadhomeorenrvmgemsruby200p195rails 4 0gemsspork100rc3libsporkrun strategyforkingrb11in block in runhomeorenrvmgemsruby200p195rails 4 0gemsspork100rc3libsporkforkerrb21in block in initializehomeorenrvmgemsruby200p195rails 4 0gemsspork100rc3libsporkforkerrb18in forkhomeorenrvmgemsruby200p195rails 4 0gemsspork100rc3libsporkforkerrb18in initializehomeorenrvmgemsruby200p195rails 4 0gemsspork100rc3libsporkrun strategyforkingrb9in newhomeorenrvmgemsruby200p195rails 4 0gemsspork100rc3libsporkrun strategyforkingrb9in runhomeorenrvmgemsruby200p195rails 4 0gemsspork100rc3libsporkserverrb48in runhomeorenrvmrubiesruby200p195libruby200drbdrbrb1588in perform without blockhomeorenrvmrubiesruby200p195libruby200drbdrbrb1548in performhomeorenrvmrubiesruby200p195libruby200drbdrbrb1626in block 2 levels in main loophomeorenrvmrubiesruby200p195libruby200drbdrbrb1622in loophomeorenrvmrubiesruby200p195libruby200drbdrbrb1622in block in main loopi can provide any files from my app upon request i am just not sure what would be the most useful i basically followed the first few steps of chapter 3 of the tutorial setting up new app adding staticpages controller setting up rspec and adding the first spec and the instructions for setting up guard and spork sec 362 and 363thanks for your help,['ruby-on-rails'] +496678,php error log has extra carriage returns i use wamp and in my phpini file i haveerror log dphp errorlogwhen i open that file i see26jun2013 053557 utc php warning division by zero in d26jun2013 053557 utc php stack trace26jun2013 053557 utc php 1 main d26jun2013 053557 utc php 2 zend applicationrunetcthe problem is that there are extra carriage returns ie i am expecting to rather have this26jun2013 053557 utc php warning division by zero in d26jun2013 053557 utc php stack trace26jun2013 053557 utc php 1 main d26jun2013 053557 utc php 2 zend applicationrunetcwhat could be causing thisupdatei changed error append string and error prepend string to i also checked and the entries after a line are linecr crlf linecr etcie carriage returns and linefeed symbols,['php'] +496689,switching view controllers using swipe gestures okay so here is the problem i am running intoi am attempting to switch from one viewcontroller that i named menuviewcontroller which contains my menu obviously i have a separate viewcontroller named viewcontroller that contains my mapview i would like to be able to double finger swipe left from my menuviewcontroller over to my mapview i am not exactly sure where to start also i am using xib files and not the storyboard running ios 6,"['ios', 'objective-c']" +496799,make some options in a select menu unselectable i have a select element with a few options but i want some of the options to not be selectablebasically it is like thisselect option city 1 option option city 1 branch a option option city 1 branch b option option city 1 branch c option option city 2 option option city 2 branch a option option city 2 branch b option selectso as you can see i do not want the cities do be directly selectable but only the options that come under each city how can it be done that the user can click on city 1 or city 2 but it would not be selected so the user is forced to choose one of the branches underneath,['html'] +496816,reading v 73 mat file in python i am trying to read a matlab file with the following codeimport scipyiomat scipyioloadmattestmatand it gives me the following errorraise notimplementederrorplease use hdf reader for matlab v73 filesnotimplementederror please use hdf reader for matlab v73 filesso could anyone please had the same problem and could please any sample codethanks,['python'] +496850,detect from a running python script if the optimize flag is o or oo sometime i would like to spawn a child process with the same optimization flags used to start the parenti can use something likeoptimize not debug but this way i match both o and oo flagsis there some python internal status that contains that info,['python'] +496861,explicity thisable image sharing to facebook using mini fb gem i use mini fb to share text and images to facebook my requirement is when share text then it should share only textwhen share text with image then both text and image should be sharedmy problem is when i share text only then a random image from the url is posted to facebook along with text when i searched for it i found that facebook is picking up images with ogimage tag and picking the last image and posted itbut there is no explicit meta tag with property ogimage in my site to avoid this i also put explicit meta tag with property ogimage but the client does not need this can i explicity thisable image sharing to facebook when no image is shared to facebook using mini fb gem,"['ruby-on-rails', 'ruby']" +496867,twitter bootstrap typeahead delay i use twitter bootstrap typeahead for thisplaying some data from server the problem is when user types an letter typeahead makes an ajax call to server and when i try to type 2 or 3 letters fast it will make 2 or 3 ajax calls to server is there a possibility to make an delay when user is typing letters to make only one ajax call to servermy code at the momentsearchinputtypeahead source function query process jqueryajax type get url organisationssearch data search name searchinputval beforesend function searchloadingshow success function data organisations organisations hash eachdata functioni item organisations hashitemnametouppercase itemid organisationspushitemname organisationssort searchloadingaddclasshidden processorganisations error function alerterror async false updater function item searchinputvalitem searchbuttonclick return item items 9 minlength 1,['javascript'] +496872,alternative of formula in jpa is there any alternative sollution for formula which is using in hibernate i need to use it by jpa for instanceformulaselect count1 from market m where mdefaultairportcodeairportcodeprivate boolean isdefault,['java'] +496968,c syntax to initialize custom classobjects through constructor params in array i have a class with minimum 4 variables and i have made a constructor for the class so that i can initialize it with myclass testobj new myclass123456789test text something else fooworks finethen i have an array of these that i need to parse in a loop so i would like to get some static data into this arraymy approach wasmyclass testobjlist new myclass new myclass10011234text 1 abcdefghijklm ding new myclass10022345text xx bla bla dong new myclass10038653text yy blah blah even more bammbut somehow this gives me a weird error about me needing an extra i dunno if i should mention this but i use it for webpages using razorengine 2 but i think this is an ordinary c questionmy workaround is currently to initialize the array with a size then adding the elements one by one through index but i would rather prefere the above solution as i might have to move the items up and down in order when testing and i have a lot more than 3 in the real datawondering what i am missing in the above code,['c#'] +496973,how to declare a dynamic local variable in javascript i want to create a local variable dynamically javascript dynamically creating variables for loops is not exactly what i am looking for i dont want an array i want to access it like a local variablesomething like script typetextjavascript var properties new object propertiesvar1 value1 propertiesvar2 value2 createvariablesproperties function createvariablesproperties this function should somehow create variables in the calling function is there a way to do that documentwriteoutside the function var1 br documentwriteoutside the function var2 br scripti tried the following code script typetextjavascript var properties new object propertiesvar1 value1 propertiesvar2 value2 createvariablesproperties function createvariablesproperties for var variable in properties try evalvariable evalvariable propertiesvariable catche evalvar variable propertiesvariable documentwriteinside the function var1 br documentwriteinside the function var2 br documentwriteoutside the function var1 br documentwriteoutside the function var2 br scriptbut the generated variables are not accessible outside the createvariablesnow i have this solution script typetextjavascript var properties new object propertiesvar1 value1 propertiesvar2 value2 function createvariablesproperties var str for var variable in properties str try str eval variable str eval variable properties variable str str catche str evalvar variable properties variable str return str evalcreatevariablesproperties documentwriteoutside the function var1 br documentwriteoutside the function var2 br scriptthis works but i am looking for an alternativebetter solution is it possible to do it without evaledit 04julyhi i tried a solution similar to what jonathan suggested script typetextjavascript var startfunc function var self this selfinnerfunc function innerfunc var properties new object propertiesvar1 value1 propertiesvar2 value2 propertiesvar3 value3 function createvariablescaller props fori in props calleri propsi callerfunc1 createvariablesself properties consolelog var1 selffunc1 function func1 consolelog in func 1 consolelog var2 innerfunc consolelog var3 startfunc scriptthis all works fine but it is actually creating global variables instead of creating the variables in the functionthe self passed to the createvariables function is window i am not sure why it is happening i am assigning the function scope to the self i am not sure what is happening here it is anyway creating global variables in this caseif my question is not clear what i am after is creating local variables in the caller the scenario is like 1 i am inside a function 2 i invoke another function which returns me a mapthis map contains name and value of a variable 3 i want to dynamically create all the variables if they are not already defined if they are already defined globallocal i want to update them 4 once these variables are created i should be able to access them without any contextjust the variable name script typetextjavascript function mainfunc var varibalestobecreated getvariables createvariablesvaribalestobecreated alertvar1 alertvar2 function createvariablesvaribalestobecreated how can i implement this function such that the variables are created in the caller i do not want these variables this function function getvariables var properties new object propertiesvar1 value1 propertiesvar2 value2 mainfunc script,['javascript'] +496992,accesscontrolalloworigin with multiple domains in my webconfig i would like to specify more than one domain for the accesscontrolalloworigin directive i do not want to use i have tried this syntaxadd nameaccesscontrolalloworigin valuehttplocalhost1506 httplocalhost1502 this one add nameaccesscontrolalloworigin valuehttplocalhost1506 httplocalhost1502 this oneadd nameaccesscontrolalloworigin valuehttplocalhost1506 httplocalhost1502 and this oneadd nameaccesscontrolalloworigin valuehttplocalhost1506 add nameaccesscontrolalloworigin valuehttplocalhost1502 but none of them workwhat is the correct syntax,"['c#', 'asp.net']" +497045,copy chrome default inputs outline style how can i set the default chrome inputs outline style on focus the orange one so it looks the same in every browser chrome style seems to be textareafocusoutline rgb229 151 0 auto 5px outlineoffset 2px however it does not work there is no auto for outlinestyle for other browsers,['css'] +497049,jquery css animatedlength delay after animation finishes on screen i am attempting to create a series of tiles in css j query which represent buildings and the rooms within them when you click on the building some j query animation occurs which removes the other buildings and then shows the rooms within the building once in the building a back tile will trigger further animation to return to original set uphere is a jsfiddle showing thisi have used the following snippet to prevent multiple tiles being clicked at onceif animatedlength return falsehowever there seems to be quite a longe delay from when the animation finishes on screen to the above if statement not returning false on the js fiddle if you click on a tile and click on back as soon as animation finishes you will see this i have placed an alert inside the if statement to show that it is being caught here can any light be shed on why when the animation on screen has finished the if statement is still returning false is there a better method to prevent any clicks until the animation is completed for each step,"['jquery', 'html', 'css']" +497087,how to handle a button click from nscollectionview i have a nscollectionview os x not ios bound to my model each collection view item has a button and a label i am handling the click actions and i have the sender and event arguments but i unable to thistinguish one button from the others most other questions not dealing with collection views say to use the tag property but this is not exposed on the interface builders bindings tab there is an argument and argument2 bindings but they dont seems to correspond to the tag property in the objc code and i do not know how to otherwise access these argumentsvoidimage clickidsender foreventnsevent event nsbutton btn sender nslogimage clicked ld longbtntag image clicked 0how do i differentiate between buttons in objectivec code inside the click actions of a bunch of buttons in a collection view,['objective-c'] +497174,img maxheight 100 causes img to exceed bounds is this a chrome bugheres the htmldivimg srctestpngdivheres the css boxsizing borderbox div height 200px padding 75px 0 60px img maxheight 100 expected result the img should have a height of 65pxresult in chrome v 2701453116 on mac os v 1068 the img has height of 135px and bleeds into the parent divs padding if i change the padding of the div to 50px 0 oddly it renders properlyplay with this in a codepen screenshotsfirst block has padding of 50px 0 second block has padding of 75px 0 60pxfirefox correct resultchrome wrong,['css'] +497210,how does the property decorator work i would like to understand how the builtin function property works what confuses me is that property can also be used as a decorator but it only takes arguments when used as a builtin function and not when used as a decoratorthis example is from the documentationclass cobject def init self self x none def getxself return self x def setxself value self x value def delxself del self x x propertygetx setx delx i am the x propertypropertys arguments are getx setx delx and a doc stringin the code below property is used as decorator the object of it is the x function but in the code above there is no place for an object function in the argumentsclass cobject def init self self x none property def xself i am the x property return self x xsetter def xself value self x value xdeleter def xself del self xand how are the xsetter and xdeleter decorators createdi am confused,['python'] +497233,xna for visual studio 2013 is xna available to be used from within visual studio 2013 ultimate preview i have not heard nor seen anything about xna for vs 2013i have just installed vs 2013 and it is not there i have it in vs 2012 so maybe there is a way to get it to work with 2013,['.net'] +497252,how to check for palindrome using python logic i am trying to check for a palindrome with python the code i have is very forloop intensiveand it seems to me the biggest mistake people do when going from c to python is trying to implement c logic using python which makes things run slowly and it is just not making the most of the languagei see on this website search for cstyle for that python does not have cstyle for loops might be outdated but i interpret it to mean python has its own methods for thisi have tried looking around i cannot find much up to date python 3 advice for this how can i solve a palindrome challenge in python without using the for loopi have done this in c in class but i want to do it in python on a personal basis the problem is from the euler project great site by the waydef ispalindromen lst intn for and in strn llenlst if l0 l1 return true elif lenlst20 for k in range l else while kl12 if list for i in range 9 100 1 for j in range 9100 1 if ispalindromeij printij breaki am missing a lot of code here the five hashes are just reminders for myselfconcrete questionsin c i would make a for loop comparing index 0 to index max and then index 01 with max1 until something something how to best do this in pythonmy for loop in in range 9 100 1 is this a bad way to do it in pythondoes anybody have any good advice or good websites or resources for people in my position i am not a programmer i do not aspire to be one i just want to learn enough so that when i write my bachelors degree thesis electrical engineering i do not have to simultaneously learn an applicable programming language while trying to obtain good results in the project how to go from basic c to great application of python that sort of thingany specific bits of code to make a great solution to this problem would also be appreciated i need to learn good algorithms i am envisioning 3 situations if the value is zero or single digit if it is of odd length and if it is of even length i was planning to write for loopsps the problem is find the highest value product of two 3 digit integers that is also a palindrome,['python'] +497284,static cast not working on precedence as expected include iostreaminclude cstdinttemplateint t void foo stdcout a stdendltemplateuint8 t t void foo stdcout b stdendlint main foostatic castuint8 t42 foostatic castint42 return0any idea why this is not working as expected my gcc 481 is complaining about an ambiguous call but the static cast is not supposed to fix the precedence rule in cases like this one where you have 2 types with the same precedence,['c++'] +497286,initializing variable length array on initializing a variable length array compiler gives an error message error variablesized object may not be initialized code snippetint n printfenter size of magic square scanfdnint boardnn 0how should variable length arrays be initializedand why it is all elements are not initialized to 0 in the way give below int boardnn boardnn 0,['c'] +497338,how to profile lock contentions under gstdmutex questionare there any opensource tools or does anyone have any techniquescode for profiling the degree of stdmutex contentions in running codei would like to count the percentage of lock contention at the granularity either by time or number of each stdmutex instance if there is a dropin tool that does not require recoding that would be even betteri am looking for a technique that will work with stdthread and g at the exit of the application i would like to dump out a profile of mutex contention statistics into a log file so that i can monitor the quality of threading code under actual running contextsnotei have seen this thread unfortunately the answers either require a pile of cash or run on windows,['c++'] +497361,what is the difference between jsonnet datacontractjsonserializer and the newtonsoft json serializer can someone help me whats the difference between the built in jsonnet datacontractjsonserializer and the newtonsoft json serializeris it correct that i can use one or the other with web api and why would i choose one,"['c#', 'asp.net']" +497371,what is the size of this class and why i have two classes as followsclass aclass b int aint main cout sizeofa endl outputs 1 cout sizeofb endl outputs 0 return 0i am familiar that size of empty class is 1but why is the size of class b coming to be zero,['c++'] +497379,typemcetextjavascript gets added in tiny mce editor html in tinymce editor while editing html i have added some js references at the startscript typetextjavascript srcscriptsswipingjsscriptwhich i am using for swiping the divs in my html pagebut sometimes scenario is not exactly getting reproduced mce gets added in the type property of the scriptso it becomesscript typemcetextjavascript srcscriptsswipingjsscriptbecause of this the browser is not recognizing the script and my page swiping logic which is inside the script does not workdoes anyone know the reason why textjavascript is turning into mcetextjavascript,['jquery'] +497403,in galaxy tab oncompletionlistener of videoview is not getting called for video view in android i have added some media player listener such as onpreparedlistener oncompletionlistener etcbut when video get completed then oncompletionlistener is not getting calledalso we observe that something oncompletionlistener get called and sometime notthis issue occurs only for samsung galaxy tabletos version 412and the same code had worked properly on another samsung device such as s2 s3 s4 etcdoes anyone have ideas,['android'] +497431,what does it mean to share internals with an immutable object in java i have been reading effective java and i have come across the statement that not only can you share immutable objects but you can share their internals but i am struggling to figure out what that really means and an example would surely help as no example is given in the book i already know that immutable objects cannot be changed such as a string,['java'] +497534,jni folder in android studio i am trying make helloyjni app in android studio and i have exception0627 131719099 1271412714comexampletestjni2 eandroidruntime fatal exception main javalangexceptionininitializererror at javalangclassnewinstanceimplnative method at javalangclassnewinstanceclassjava1319 at androidappinstrumentationnewactivityinstrumentationjava1071 at androidappactivitythreadperformlaunchactivityactivitythreadjava2166 at androidappactivitythreadhandlelaunchactivityactivitythreadjava2299 at androidappactivitythreadaccess700activitythreadjava154 at androidappactivitythreadhhandlemessageactivitythreadjava1284 at androidoshandlerthispatchmessagehandlerjava99 at androidoslooperlooplooperjava137 at androidappactivitythreadmainactivitythreadjava5306 at javalangreflectmethodinvokenativenative method at javalangreflectmethodinvokemethodjava511 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava1102 at comandroidinternaloszygoteinitmainzygoteinitjava869 at dalviksystemnativestartmainnative method caused by javalangunsatisfiedlinkerror could not load hellojni from loader dalviksystempathclassloaderdexpathdataappcomexampletestjni21apklibrarypathdataapplibcomexampletestjni21 findlibrary returned null at javalangruntimeloadlibraryruntimejava365 at javalangsystemloadlibrarysystemjava535 at comexampletestjni2mainactivityclinitmainactivityjava9 15 moremy structure project looks like thisi added my buildgradle line compile fileslibsarmeabilibhellojnisobut this do not helpedi read gradle and android gradle plugin but i do not find information about working with jni folder i am thinking what it file dependencies but it is not workingmy hellojnic file includjstring java com example testjni2 mainactivity stringfromjni jnienv env jobject thiz return envnewstringutfenv hello from jni my mainactivity file includepublic class mainactivity extends activity static systemloadlibraryhellojni public native string stringfromjni override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main string text stringfromjni logimainactivity text override public boolean oncreateoptionsmenumenu menu inflate the menu this adds items to the action bar if it is present getmenuinflaterinflatermenumain menu return true my androidmk file containtslocal path call mydirinclude clear varslocal module hellojnilocal src files hellojnicinclude build shared librarytell me please where i could make a mistake android studio 017os windows 7 x64,['android'] +497580,change color of one character in a text box htmlcss i am designing a web site and i would like to ask you guys that how can i change the color of just one character in a string in a text box of html by css example stack over flow just the a letter is redthanks guys,"['html', 'css']" +497583,correct use of stdcoutprecision not printing trailing zeros i see many questions about the precision number for floating point numbers but specifically i want to know why this codeinclude iostreaminclude stdlibhint main int a 5 int b 10 stdcoutprecision4 stdcout floatafloatb n return 0shows 05 i expect to see 050 is it because of the original integer data types,['c++'] +497685,my phonegap application looks smaller in android hd phones hdpi and xhdpi phones i am newbie developing an hybrid application using phonegap jquery mobile my application looks fine in mdpi devices but the application ui looks smallershrinks in hdpi xhdpi phonestablets apple devicescurrently am using the viewport meta tag as meta nameviewport contentuserscalableno initialscale1 maximumscale1 minimumscale1 widthdevicewidth targetdensitydpidevicedpi how can i acheieve the same ui in all screen resolutions dpisneed your suggestions,['android'] +497716,jquery get all data attributes from a list i have a long dynamically generated list each with the same class identifier and a data attribute similar to the code belowul li classlist dataid123oneli li classlist dataid124twoli li classlist dataid125threeli li classlist dataid126fourli etculwhat i am trying to achieve is to get all the dataid values and format them in as follows123124125126etcthis would be then passed to a page via ajax and the ids checked for existence in a databasevar delimited datalisteachfunction delimited datathisdataidconsolelogdelimited datathe reason i am asking this question is that i am working on a live system that automatically deploys items in the list columns to different users after 10 mins i just need to be sure that the code is going the right way i also need to check that is there are no list classes on the page ie no way to do the query whether delimited data will be totally empty which i am pretty sure it would beis there a better way than using each in this case as i find it can be rather slow baring in mind that the above function will be run every 30 seconds,"['javascript', 'jquery']" +497798,parse with facebook login server refused renewal request with error code 190 i am working on an ios app that uses parse and facebookfor the facebook login i am following the guides on this page following the guide i have this code that validate the cached session check if this cached session is still valid does nothing if still valid void validatecachedsession fbrequest request fbrequest requestforme request startwithcompletionhandlerfbrequestconnection connection id result nserror error if error handle successful response logobviousfacebook session validated no problem else if erroruserinfofberrorparsedjsonresponsekeybodyerrortype isequaltostringoauthexception since the request failed we can check if it was due to an invalid session logobviousthe facebook session was invalidated announce logged out the persisted session is invalid logout self logout else logobviousthe facebook session was invalidated announce logged out the persisted session is invalid logout self logout as shown above if the cached session is invalid it should call logout void logout pfuser logout over here we will show the login button againin order to test this i first logged into my app using a facebook account then i changed the password and revisit the appthe app correctly recognises the session is invalidated and logout is calledbut when i click login again the login function is returning this erroruh oh an error occurred error domaincomfacebooksdk code5 the operation couldnat be completed comfacebooksdk error 5 userinfo0x1e066140 comfacebooksdkerrorinnererrorkeyerror domaincomappleaccounts code1 server refused renewal request with error code 190 userinfo0x1d56df10 nslocalizeddescriptionserver refused renewal request with error code 190 comfacebooksdkparsedjsonresponsekey body error code 190 error subcode 65001 why even if i terminate the app and restart it the app will now stuck in this state unable to login any help will be appreciatedps to be clear this is my login function to be called when user explicitly clicked a login button void loginbyfacebookwithpermissionsnsarraypermissionsarray logfunctioncalledobvious pffacebookutils loginwithpermissionspermissionsarray blockpfuser user nserror error if user if error nsloguh oh the user cancelled the facebook login else nsloguh oh an error occurred error self logout else if userisnew logobvioususer with facebook signed up and logged in self requestloggedinuserinfo else logobvioususer with facebook logged in self requestloggedinuserinfo ps2 ok upon more investigation so it stuck in this state until i go to the settingsfacebook to reenter the new password is this the correct behaviour should not ios6 promptly remind the user to change password when i changed the facebook password from facebookcom,['ios'] +497821,bootstrap form error undefined method 1 i installed gem bootstrap form2 i wrote in applicationcss that line require bootstrap form before the 3 in my htmlerb bootstrap form forguardian url student guardians pathstudenthtml class formhorizontal method post do f and i am getting the following error undefined methodbootstrap form for for 0xb31a80c,['ruby-on-rails'] +497866,how to change android talkback in case of app name the app i am working on has a name which is mispronounced by the talkback i am able to fix this within the app by changing the spelling but if i change the spelling in the androidlabel in the manifest it is misspelled on the app icon on the phone does anyone have a way around this,['android'] +497888,why cannot i make inclass initialized const const stdstring a static member i have the following working codeinclude stringinclude iostreamclass a public const stdstring test 42 static const stdstring test 42 failsint mainvoid a a stdcout atest nis there a good reason why it is not possible to make the test a static const i do understand prior to c11 it was constrained by the standard i thought that c11 introduced inclass initializations to make it a little bit friendlier i also not such semantic are available for integral type since quite some timeof course it works with the outof class initialization in form of const stdstring atest 42i guess that if you can make it nonstatic then the problem lies in one of the two initializing it outofclass scope normally consts are created during the instantiation of the object but i do not think this is the problem if you are creating an object independant of any other members of the class the second is having multiple definitions for the static member eg if it were included in several cpp files landing into several objectfiles and then the linker would have troubles when linking those object together eg into one executable as they would contain copies of the same symbol to my understanding this is exactly equal to the situation when ones provides the outofclass right under the class declaration in the header and then includes this common header in more than one place as i recall this leads to linker errorshowever now the responsibility of handling this is moved onto userprogrammer if one wants to have a library with a static they need to provide a outofclass definition compile it into a separate object file and then link all other object to this one therefore having only one copy of the binary definition of the symboli read the answers in do we still need to separately define static members even if they are initialised inside the class definition and why i cant initialize nonconst static member or static array in classi still would like to knowis it only a standard thing or there is deeper reasoning behind itcan this be workedaround with the constexpr and userdefinedliterals mechanisms both clang and g say the variable cannot have nonliteral type maybe i can make one maybe for some reason its also a bad ideais it really such a big issue for linker to include only one copy ofthe symbol since it is static const all should be binaryexactimmutable copiesplese also comment if i am missing or missunderstanding something,['c++'] +497912,creating a terminal program with python i recently started learning python i have created some basic webapps with django and wrote some simple scripts after using vim as a python ide i really fell i love with terminal programs is there an official term for this right now i am capable of doing simple things like asking someones age and printing it to the screen however this comes down to running a py script and after this script is done the normal bash return i would like create a program that i can run from the command line and that would allow the same user experience as vim one that you open and close for example i created a simple script to import rss feeds it would be cool if i could open my terminal type the name of my program program would open then i would like to use commands like findsomething basically have real interaction with my program to conclude how would i go about creating such a program what kinds of modules books or site would you recommend,['python'] +497953,8 branches for try with resources jacoco coverage possible i have got some code that uses try with resources and in jacoco it is coming up as only half covered all the source code lines are green but i get a little yellow symbol telling me that only 4 of 8 branches are coveredi am having trouble figuring out what all the branches are and how to write code that covers them three possible places throw pipelineexception these are createstagelist processitem and the implied closenot throwing any exceptions throwing an exception from createstagelistthrowing an exception from processitemthrowing an exception from closethrowing an exception from processitem and closei cannot think of any other cases yet i still only have 4 of 8 coveredcan someone explain to me why it is 4 of 8 and is there anyway to hit all 8 branches i am not skilled with decyrptingreadinginterpreting byte code but maybe you are i have already seen but neither it nor the issue it references help very much other than noting that this is due to compiler generated blockshmm just as i finish writing this i had a thought on what cases might not be not tested by what i mention above i will post an answer if i got it right i am sure this question and it is answer will help someone in any caseedit nope i did not find it throwing runtimeexceptions not handled by the catch block did not cover any more branches,['java'] +497959,c stdasync run on main thread is there a way of running a function back on the main thread so if i called a function via async that downloaded a file and then parsed the data it would then call a callback function which would run on my main ui thread and update the ui i know threads are equal in the default c implementation so would i have to create a shared pointer to my main thread how would i do this and pass the async function not only the shared pointer to the main thread but also a pointer to the function i want to rrun on it and then run it on that main thread,['c++'] +497999,how to add a border just on the top side of a uiview my question is on the titlei do not know how to add a border in a specific side top or bottom any sidelayerborder draws the border for the whole viewhelp please sthanks,"['ios', 'objective-c']" +498023,hibernate sql query result mappingconvert to objectclassbean 1 2 select tableall column is okstring sql select t student from t studentstring sql select t studentidt studentname from t student select all columnsqlquery query sessioncreatesqlquerysqlqueryaddentitystudentclassor queryaddentityalias studentclassqueryliststudent student studentquerysetresulttransformertransformersalias to entity map or other transformerquerylist studentor aliasstudentstudentstudent3 select some columnnot all of is errorstring sql select t studentidt studentnamet studentsex from t studentsqlquery query sessioncreatesqlquerysqlqueryaddentitystudentclassquerysetresulttransformertransformersalias to entity mapquerylist exceptioninvalid columnno columni want 3 to work ok and let the result can be mapped to studentclasslike studentid name sex other field are nulldefaulti have no idea for this error help me please,"['java', 'sql']" +498070,how to thisable particular context menu item dynamically i have added 4 menus in context meni item in that if the start context menu item is clicked i need to thisable that particularstart menuthanks in advancecontextmenu conmenu1 new contextmenupublic form1 initializecomponent conmenu1menuitemsaddstart new systemeventhandlerthisstart click conmenu1menuitemsaddpause new systemeventhandlerthispause click conmenu1menuitemsaddresume new systemeventhandlerthisresume click conmenu1menuitemsaddstop new systemeventhandlerthisstop clickprivate void start clickobject sender eventargs e functionalities to thisable start context menu item,"['c#', '.net']" +498074,how can i showhide a specific alert with twitter bootstrap heres an example of an alert i am usingdiv classalert alerterror idpasswordsnomatchregister span plooks like the passwords you entered do not matchp spandivi know that alertshow and alerthide will showhide all the elements of the alert class however i cannot figure out how to hide a specific alert given its idi want to avoid using alertclose since that permanently removes the alert and i need to be able to recall it,"['javascript', 'jquery', 'html']" +498081,how can i generate a random biginteger within a certain range consider this method that works wellpublic static bool mightbeprimeint n biginteger a rgennext 1 n1 return modexp a and 1 n 1now in order to fulfill a requirement of the class i am taking mightbeprime must accept a biginteger n but that means that i need a different way to generate my random biginteger amy first idea was to do something like biginteger a n1 rgennextdouble but a biginteger cannot be multiplied by a doublehow can i generate a random biginteger between 1 and n1 where and is a biginteger,"['c#', '.net']" +498110,uiwebview contentinset without extra height at bottom i am creating a view controller that uses a web view which slides behind the navigation bar and status bar to do this i am setting the webviewscrollviewcontentinset property to have a top inset of 64however this does not shrink the amount of area the web view wants to take up so if a page is less than a screenful it has 64 px of white space at the bottom to scroll through the web views are in a vertical uipageviewcontroller so this thisrupts paging is there some way to get rid of this extra space,['ios'] +498137,conversion of array list to json object string i have a model class method which returns a list of objects which contains all the registered user details i want to fetch the list resturned by all method and convert the data into json object and pass it to the view like a string how can i do this conversion of this array list to json object i was unable to do this by below objectmapper mapper new objectmapperjsonobject json new jsonobjectjsonnodefactory jsonnode jsonnodefactoryinstanceobjectnode result new objectnodejsonnodefor int i 0 i listsize i jsonputlistgetifname listgeti systemoutprintlnjsongetfnameentityclass mydata extends model id public long id public string fname public string lname public string city public string state readselect operation public static finder long mydata finder new finderlongclass mydataclass public static list mydata all return finderall public static void createusermydata user usersave,"['java', 'javascript', 'jquery']" +498144,provider for javaxxmlparsersdocumentbuilderfactory cannot be found i am not able to get past this problem browsed through many forums pls helporgspringframeworkbeansfactorybeandefinitionstoreexception unexpected exception parsing xml document from servletcontext resource webinfapplicationcontextxml nested exception is javaxxmlparsersfactoryconfigurationerror provider for javaxxmlparsersdocumentbuilderfactory cannot be foundi have included all the jar files in xerces bin following is my webinflib structure,['java'] +498177,how to read a unicode gclef u1d11e from a file the gclef u1d11e is not part of the basic multilingual plane bmp which means that it requires more than 16 bit almost all of javas read functions return only a char or a int containing also only 16 bit which function reads complete unicode symbols including smp sip tip ssp and puaupdatei have asked how to read a single unicode symbol or code point from a input stream i neither have any integer array nor do i want to read a lineit is possible to build a code point with charactertocodepoint but this function requires a char on the other side reading a char is not possible because read returns an int my best work around so far is this but it still contains unsafe castspublic int read code point reader input throws javaioioexception int ch16 inputread if characterishighsurrogatecharch16 return charactertocodepointcharch16 charinputread else return intch16how to do it betterupdate 2another version returning a string but still using castspublic string readchar reader input throws javaioioexception int i16 inputread utf16 as int if i16 1 return null char c16 chari16 utf16 if characterishighsurrogatec16 int low i16 inputread low surrogate utf16 as int if low i16 1 throw new javaioioexception can not read low surrogate char low c16 charlow i16 int codepoint charactertocodepointc16 low c16 return new string charactertocharscodepoint else return charactertostringc16the remaining question are the casts safe or how to avoid them,['java'] +498187,set navigation bar image in ios 7 i want to convert my current project from ios 6 to ios 7 in ios 6 my project is working fine but in ios 7 navigation bar image is not showing properlyi used this code snippet for ios 6uiimage imgnav uiimage imagenamednavigationpngselfnavigationcontrollernavigationbarframe cgrectmake0 0 320 44selfnavigationcontrollernavigationbar setbackgroundimageimgnav forbarmetrics uibarmetricsdefaulthow can i set the navigation bar image in ios 7,['ios'] +498199,constructing a diagonal matrix from vector of integers function eigen i have a vector of integers and i want to construct a diagonal matrix with vectoss element as diagonal entries of the matrix for example if vector is 1 2 3 the diagonal matrix would be1 0 00 2 00 0 3the naive way to do it would be just iterate over it and set elements one by one is there no other direct way to do this in eigen also after constructing the diagonal i want to calculate the inversewhich is just reversing the diagonal entries but there does not seem to be a way to do this toodirectly which would be optimized way too in the library itselfi have looked up the documentation of diagonal matrices in eigen library but it seems like that there is no way if i have missed something obvious while reading the documentation please point outany help appreciated,['c++'] +498380,automatic binding for boostthread in c when doingstdvectorint vecint number 4boostthread workerthreadmethod number vecgiven a methodtemplatetypename tvoid methodint n stdvectort vec does stuffwhy do i have to manually doboostthread workerthreadmethod number boostrefvecwhy does it not automatically pass it by referenceedit so would it be possible theoretically for boostthread to do some macrometaprogramming to adjust this since c has nothing in the way of built in reflectionintrospectionso is a major part of boost c in general passing metainformation around,['c++'] +498427,luavmjs ajax callbacks firing but data not returned it is an issue i raised at that i would like to submit to stackoverflow i may get a faster answer here given the higher exposure just to make sure my question is clearly understood i will restate it how can i reach the callback data from the examples belowthe issue submittedluavmjs is a fantastic piece of software with a huge potential for replacing javascript in the browsera few snippets of code collected from the mailing list wiki issues etc everything works out of the box with no perceived performance impact i only have problems with callback return values on jquery ajax calls and websocket returned messagefor example see script examplehtml belowjsrungetglossaryjson functiondata consolelogdata this worksjqgetglossaryjson functiondata printdata end the callback is firing but data is not returneda workaround using the load functionjqresulthideloadglossaryjson function printjqresulthtml end this works because after the callback is fired we just collect the result from the result divthe following goes into script examplehtml see luavmjs git repository begin script tag example script srcluavmjsscriptscript srcjquery1101jsscript simplest web server for serving static files python m simplehttpserver 8080script typetextlua print contents of tbl with indentation indent sets the initial level of indentationfunction tprint tbl indent if not indent then indent 0 end for k v in pairstbl do formatting stringrep indent k if typev table then printformatting tprintv indent1 else printformatting tostringv end endend function test return ok end for i15 do jsglobalalerttest endlocal jq jsget jqbodyappendplopclickfunction jsglobalalertplop click end local version jqjquery jsglobalalertversion jqresultloadglossaryjsonjqresulthideloadglossaryjson function printjqresulthtml end jqgetglossaryjson functiondata printdata end callback is firing but data is not returned jsrungetglossaryjson functiondata consolelogdata local ws jsnewwebsocketwsechowebsocketorgencodingtext wsonopen function printconnected wssendrock it with html5 websocket end wsonclose function printthisconnected end wsonerror functionerror printerror end wsonmessage functione tprinte using tprint because an empty table is returned instead of the message wsclose endscript end script tag example div idresultdivthe glossaryjson file loaded in the examples above glossary title example glossary glossdiv title s glosslist glossentry id sgml sortas sgml glossterm standard generalized markup language acronym sgml abbrev iso 88791986 glossdef para a metamarkup language used to create markup languages such as docbook gloseealso gml xml glosee markup,"['javascript', 'jquery']" +498470,python slice notation with commalist i have come across some python code with slice notation that i am having trouble figuring outit looks like slice notation but uses a comma and a list list 1 2 3is this syntax valid if so what does it doedit looks like it is a 2d numpy array,['python'] +498471,what is in android manifest how to make use of this using permission and usespermission tags we can give and access permissionsthen why we need permissiontree in which way it is useful,['android'] +498495,why my program does not show compile time error when final class variable is not initialized for following codepublic class staticfinal private final static int i public staticfinal i get compile time errorstaticfinaljava7 variable i might not have been initialized 1 errorwhich is in accordance with jls8312 which says thatit is a compiletime error if a blank final a4124 class variable is not definitely assigned a168 by a static initializer a87 of the class in which it is declared so the above error is completely understoodbut now consider the following public class staticfinal private final static int i public staticfinalthrows instantiationexception throw new instantiationexceptioncannot instantiate do not let the constructor to complete here the constructor is never finished because instantiationexception is thrown in the middle of constructor and this code compiles fine why is it why this code is not showing compile time error about the non initialization of final variable i editi am compiling it using javac 160 25 on command prompt not using any ide,['java'] +498527,simulate button click using gtk using gtk event put and a gdkeventbutton structure this is a followup to how to insert synthetic mouse events into x11 input queuei am trying to create a program that takes input from an external device and generates mouse clicks so that gtk will get and handle the events as if they mouse click happened normallyseems i can use a gdkeventbutton structurebut i am not sure how to determine the values to enter for each field i am looking for a small snippet of sample code or advice from somebody that has used gtk event put with a gdkeventbutton structureedit if anybody knows a different or better way than my answer please let me know,['c'] +498531,android setoncheckedchangelistener calls again when old view comes back i cannot solve an issue with the getgroupviewmethod the problem is that the listener setoncheckedchangelistener is getting invoked to many times let say i check a certain checkboxitem then i scroll it out of view and then scroll back what happends is that the listener is called once again and the problem is that i store checkboxids in an arraylist inside this listener to use it later in the code the consequence is that more elements is added to the arraylist everytime the listener is called and thistortes the data is there a solution to this what should i do should i for instance unregister the listeneroverride public view getgroupviewint groupposition boolean isexpanded view convertview viewgroup parent view view null final int group position groupposition if convertview null layoutinflater inflater layoutinflater contextgetsystemservicecontextlayout inflater service view inflaterinflaterlayoutactivity phrase parent false final viewholder viewholder new viewholder viewholdertext textview viewfindviewbyidridgrouptitle viewholdercheckbox checkbox viewfindviewbyidridcheck viewholdercheckboxsetoncheckedchangelistenernew compoundbuttononcheckedchangelistener override public void oncheckedchangedcompoundbutton buttonview boolean ischecked todo autogenerated method stub if buttonviewischecked checkedaddinteger viewholdercheckboxgettag else checkedremoveinteger viewholdercheckboxgettag viewsettagviewholder viewholdercheckboxsettaggroupposition else view convertview viewholderviewgettagcheckboxsettaggroupposition viewholder holder viewholder viewgettag holdertextsettexttitlesgroupposition for int i 0 i checkedsize i if checkedgeti group position holdercheckboxsetcheckedtrue else if checkedgeti group position holdercheckboxsetcheckedfalse return view,['android'] +498601,capistrano deploymigrate and dbmigrate run all migrations every time so i am diddling around with rails ruby 193p392 rails 32 sqlite3 db and i am trying to deploy the ubiquitous blog tutorial code to a production server apache passenger ubuntu my deployrb looks like thisrequire bundlercapistranorequire rvmcapistranoload deployassetsset rvm ruby string envgem homegsubset rvm type userset user blahset application railstestset domain wblahcomset applicationdir homeseanpublicblahcompublicset scm gitset repository sshhomeblahpublicblacompubliccapdepgitset git enable submodules 1 if you have vendored railsset branch masterset git shallow clone 1set scm verbose trueset use sudo false roles serversrole web domainrole app domainrole db domain primary true deploy configset deploy to applicationdirset deploy via exportset migrate target latest additional settingsdefault run optionspty true forgo errors when deploying from windowsh optionskeys whomeblahsshid rsassh optionsforward agent true if you want to clean up old releases on each deploy uncomment this if you are using passenger mod rails uncomment thisnamespace deploy do task start do end task stop do end task restart roles app except no release true do run try sudo touch filejoincurrent pathtmprestarttxt endendafter deployupdate code deploymigratenow i am sure that must look like a big hot mess to those who know what they are doing with capistrano but i am an utter rube in the end despite my inadequacies the deploy seems to work because when i run the followingcap deploysetupcap deploymy app is up and running and just because i can i add a few rows to a table in the db via the web ui that was created for me by rails now i get bold and create a migration adding a column to a table i push my changes to git to my horror when i run cap deployall the migrations are run which recreates the tables thus destroying all my data i have repeated this painful process several times my schema migrations table looks like this201306202104201306202202292013062821312013062821494620130628223002what am i missing here update i recently gave themahrvins suggestion regarding running deploymigrations at the command line and removing it from the deployrb it did not work once again all migrations were run my muse must have whispered something in my ear because i decided to try running dbmigrate on the server itself i was astonished to see this output after running just rake 20130717230110 createhighscores 20130717230342 creategames 20130717231041 addgametypetogame 20130717233707 addgamepublishertogame 20130717234124 addgameratingtogame 20130731210558 addgamemechanictogameonly the last migrations should be pending so perhaps this is not a problem with capistrano at all i have updated the title of this question to reflect that so why are the previous migrations still being flagged as pending i know they were run in the past both because i saw them in the output and verified the db schema after they ranupdate 2 setup another migration and sshd into the server and cdd my way to the current directory which if i understand capistrano at all fat chance is where the current files are runningbundle exec rake dbmigratestatusgot me status migration id migration name down 20130717230110 create high scores down 20130717230342 create games down 20130717231041 add game type to game down 20130717233707 add game publisher to game down 20130717234124 add game rating to game down 20130731210558 add game mechanic to game down 20130731212454 add publish year to game down 20130731214515 add game rank to game down 20130731214928 add game abbr to game down 20130731215749 add crazy field to gamei cannot help feeling that there is something profoundly wrong with what i am trying to do,"['ruby-on-rails', 'ruby']" +498613,testing code that requires a flask app or request context i am getting working outside of request context when trying to access session in a test how can i set up a context when i am testing something that requires oneimport unittestfrom flask import flask sessionapp flask name approutedef hello world t test hello thello return helloclass test def helloself sessionh hello return sessionhclass myunittestunittesttestcase def test unitself t teststest thello,['python'] +498682,total number of string objects created in the process string str1javastring str2javastring str3new stringjavastring str4new stringjavaintern2 objects will be created str1 and str2 refer to same object because of string literal pool concept and str3 points to new object because using new operator and str4 points to the same object points by str1 and str2 because intern method checks into string pool for string having same valuestr1str2str3str4nullone object will be eligible for gc that is the object created through string str3new stringjava the first string object is always accessible through reference stored in string literal poolis my explanation correct,['java'] +498704,using dropzonejs to upload after new user creation send headers i am using a great plugin dropzonejs dropzonejscom to make my site a little more fancy when registering a new userbasically the user fills out a form drops a couple images into the dropzone and clicks submit which fires an ajax call that posts the form to a php scripti have dropzone parameters set to enqueforuploadfalse which keeps the files from autouploading since i need them to upload into uploadsuserid after the new user id has been created i can give dropzone header params which i am assuming post to the url similar to an ajax call instead of data userid userid dropzone uses headers userid userid however dropzone gets initialized on documentready and as the userid variable is not declared yet dropzone fails to initializei am guessing i am going to need to initialize dropzone with documentready but not give it headers just yet then after the ajax form processing is successful and returns userid call dropzone to upload and give it the headers at that point problem is i do not know what code would need to be called to make that happeninitialize dropzone on readydocumentreadyfunction dropzonedropzone url dropzoneprocessphp maxfilesize 1 paramname photos addremovelinks true enqueueforupload false thensubmitonclick function validation crap here ajax type post url postformphp data various form values here datatype json success functiondata var userid datauserid and this is what i cannot figure out tell dropzone to upload and make it post userid to dropzonephp,"['php', 'jquery']" +498713,create a custom lock screen windows 7 i think the title is pretty self explanatory the material available on the net is largely on setting up custom images during the lock screen time the answer given here talks about invoking the windows provided lock screen by using the user32dll i want to ask if there is any api that would let me use my own lock screen on windows 7 the reason is that i have developed my own face recognition algorithm but i want to integrate it with the windows locking mechanism one application that actually does the same thing is winlockpro that creates custom lock screens for windows 8 it uses custom forms in vb for the images and links the rest to a dllcan someone guide me to some useful resources apis etc for this,['c++'] +498720,how to find the largest power of 2 less than the given number i need to find the largest power of 2 less than the given numberand i stuck and cannot find any solutioncode public class mathpow public int largestpowerof2 int n int res 2 while res n res intmathpowres 2 return res this does not work correctly testing outputarguments actual expected9 16 8 100 256 64 10 65536 512 64 256 32 how to solve this issue,['java'] +498778,enum localization how do you localize enums for a listboxfor where multiple options are possiblefor example an enum that contains rolespublic enum roletype thisplaydescription administrator resourcetype typeofresource administrator 1 thisplaydescription moderator resourcetype typeofresource moderator 2 thisplaydescription webmaster resourcetype typeofresource webmaster 3 thisplaydescription guest resourcetype typeofresource guest 4 etc 5i have seen this done with dropdownlistselectlists but is there a way to do this for a multi select listeditthis is how i would like to use it which is how it works now but does not get translated in a different languagevar roles from role r in enumgetvaluestypeofroletype select new id intenumparsetypeofroletype rtostring name rtostring searchmodelroles new multiselectlistroles id namenote i have renamed the enum from role to roletype,['c#'] +498810,print var in jsfiddle how would i print something to the result screen in jsfiddle from my javascript i cannot use documentwrite it does not allow it neither printwhat should i use,"['javascript', 'jquery']" +498818,responsive web design scenario i am designing a 3 column web page layout like belowto make it responsive i specified widths in min width in pixels and floatleft now if i resize the page all 3 divs 12 and 3 get resized first then 3rd div moves below of 1st div if i resize more then 2nd div moves to below of 1st and 3rd moves below to 2ndthis is because of float property but i want to modify it in such a way that 3rd div should be moved first as it is already being then 1st div should be moved instead of 2nd div 2nd div must be on the tophow can i do this,['css'] +498869,int a int 07 01 10 why a 7 i have question to everybodyint a int 07 01 10after executing of this code a 7i cant understand why because 070108 and 08108can anybody tell me whythanks,['java'] +498931,android edittext in listview issue i have a listview in my application that is basically a questionaire so there are some edittexts that the user needs to fill i have encountered the following issuessome of the edittext require numeric input so i set the inputtype in the corresponding xml type as numeric however as when i click on the edittext the numeric keyboard is shown but almost immediately it thisappears and the regular keyboard is shownas you can imagine i need to store the values that the user inputs in these edittexts the problem i have with this is that after i input some text in some edittexts and i scroll down the text is gone when i go back you can see in my code that i made an attempt to prevent this and i should mention that it works perfectly fine with checkboxesat the beginning i was having problems with losing the focus but i solved it looking at other questions added descendantfocusablitybeforedescendants to the listview and windowsoftinputmodeadjustpan works fine except that when an edittext is below the half of the screen it loses focus as soon as i start typing into itgetview method for list adapterpublic view getviewfinal int positionview resultviewgroup parentfinal viewholder vhfinal question question valuesgetpositionifholderspositionnull vh new viewholderelse vh holderspositionlayoutinflater inflater layoutinflatercontextgetsystemservicecontextlayout inflater serviceifquestiongetquestiontypeequalsquestiontype closed result inflaterinflaterlayoutclosed question list item null vhcb checkboxresultfindviewbyidridcheckbox vhcbsetoncheckedchangelistenernew oncheckedchangelistener override public void oncheckedchangedcompoundbutton buttonview boolean ischecked vhischecked ischecked holdersposition vh vhcbsetcheckedvhischeckedelse result inflaterinflaterlayoutnumeric question list item null vhet edittextresultfindviewbyidridquestion et vhetaddtextchangedlistenernew textwatcher override public void aftertextchangededitable s vhtvvalue stostring holdersposition vh logitagentered aftertextchanged for questiongettext override public void beforetextchangedcharsequence s int startint count int after override public void ontextchangedcharsequence s int startint before int count vhetsettextvhtvvaluevhtv textviewresultfindviewbyidridquestion textvhtvsettextquestiongettextholdersposition vhresultsettagvhreturn result,"['java', 'android']" +498958,rails 4 turbolinks and jquery dynamic links not playing nice i am developing an application in rails 40 and i am having an issue with turbolinks not playing nice with some jquery code i have i have a quote model that has a related quoteitems model i am using accepts nested attributes for and some jquery to populate the line items formwhen i click on a link bringing me to the new quote path the dynamic link does not fire the javascript code when i refresh the page the form works great i like turbolinks as it is super fast but not sure how to get this to work in development heres some codein quotesjscoffeejquery formon click remove line items event thisprevinputtypehiddenval1 thisclosestfieldsethide eventpreventdefaultformon click add fields event time new dategettime regexp new regexpthisdataid g thisbeforethisdatafieldsreplaceregexp time eventpreventdefaultquotes view newhtmlerb form for quote class hello do f fieldset p flabel quote date date of quote br ftext field quote date p p flabel good through br ftext field good through p p flabel quote number br ftext field quote number p p flabel customer id customer br selectquote customer id customerallcollect c cfname cid prompt select customer p ffields for quote items do builder render quote item fields f builder end link to add fields add line item f quote items p fsubmit p fieldset end,"['jquery', 'ruby-on-rails']" +498963,does anaconda create a separate pythonpath variable for each new environment i am starting to work with the anaconda package from continuumio to do scipy work i have been able to get anaconda up and running but i cannot tell whether anaconda creates a new pythonpath environment variable for each new environment it creates or whether it relies on the common system pythonpath i could not find any information on this in the documentation further when i did a printenv i did not see a pythonpath variable in the newly created environmentthough i did find a few new anaconda created environment variables the best i can find is that anaconda added some anaconda directories and the new environment directory to the head of path variablebut this does not necessarily isolate the new package from the system environment but it is close does anyone know the answer to this question or found a way to deal with this concern,['python'] +499010,certificates would not show in code signing identity in build settings i am encountering the errorsno matching provisioning profiles found no provisioning profiles with a valid signing identity ie certificate and private key pair were foundandcodesign error code signing is required for product type application in sdk ios 70xcode is not giving me any option other than automatic ios developer and thistribution options in the code signing area of the build settingsi have tried changing the bundle id to match the certificates exactly as well as a more generic comdomainappname id i have deleted and recreated the provisioning profiles i am really lost it feels like it should be something really simply but i cannot get my certificates to show in the settings,"['ios', 'objective-c']" +499035,prime numbers javascript can someone please give me guidance on getting the primenumbers here this is homework so i do not want the answer but some pointers would be greatly appreciated it is really annoying me i think i am close but this problems i have are number 25 and 35 these are not prime but this function is returning themvar getprimenumber functionn ifn 1 return else ifn 2 return 2 else ifn 3 return 3 else forimathfloormathsqrtni2i consolelogimaybe another var in here ifni 0 n2 0 n3 0 return n 25mathsqrt25 will be equal to zero this is what gives me 25,['javascript'] +499120,which approach is better functionapply args or having a function to accept as argument let us say that i have a functiona defined like thisfunctiona functionmyobject someparams myobjectsave some data someparams myobjectprocessed truei can then call it and pass an object to work on as functionasomeobject someparamsi can however transform this example with applyfunctiona functionsomeparams thissave some data someparams thisprocessed truefunctionaapplysomeobject someparamsboth approaches seems to be achieving the same goal or am i missing somethingbut since apply does exist in javascript what are the benefits of using it instead of having my functions accept this as a first argument,['javascript'] +499132,placement forms of the operator delete functions in his new book tcpl4 stroustrup casts a slightly different light on a once usual practice regarding usercontrolled memory allocation and placement newor more specifically regarding the enigmatical placement delete in the books sect 1124 stroustrup writesthe placement delete operators do nothing except possibly inform a garbage collector that the deleted pointer is no longer safely derivedthis implies that sound programming practice will follow an explicit call to a destructor by a call to placement deletefair enough however is there no better syntax to call placement delete than the obscureoperator deletepthe reason i ask is that stroustrups sect 1124 mentions no such odd syntax indeed stroustrup does not dwell on the matter he mentions no syntax at all i vaguely thislike the look of operator which interjects the matter of namespace resolution into something that properly has nothing especially to do with namespaces does no more elegant syntax existfor reference here is stroustrups quote in fuller contextby default operator new creates its object on the free store what if we wanted the object allocated elsewhere we can place objects anywhere by providing an allocator function with extra arguments and then supplying such extra arguments when using newvoid operator newsize t void p return p void buf reinterpret castvoid0xf00fx p2 newbuf xbecause of this usage the newbuf x syntax for supplying extra arguments to operator new is known as the placement syntax note that every operator new takes a size as its first argument and that the size of the object allocated is implicitly supplied the operator new used by the new operator is chosen by the usual argumentmatching rules every operator new has a size t as its first argumentthe placement operator new is the simplest such allocator it is defined in the standard header newvoid operator new size t void p noexceptvoid operator newsize t void p noexceptvoid operator delete void p void noexcept if p make p invalidvoid operator deletevoid p void noexceptthe placement delete operators do nothing except possibly inform a garbage collector that the deleted pointer is no longer safely derivedstroustrup then continues to thiscuss the use of placement new with arenas he does not seem to mention placement delete again,['c++'] +499135,container of generic types in java i have a generic class foot and parameterized types foostring and foointeger now i want to put different parameterized types into a single arraylist what is the correct way of doing thiscandidate 1public class m public static void mainstring args foostring foostring new foostring foointeger foointeger new foointeger arraylistfoo list new arraylistfoo listaddfoostring listaddfoointeger for foo foo list do something on foo class foot candidate 2public class m public static void mainstring args foostring foostring new foostring foointeger foointeger new foointeger arraylistfoo list new arraylistfoo listaddfoostring listaddfoointeger for foo foo list do something on foo class foot in a word it is related to the difference between foo and the raw type fooupdategrep what is the difference between the unbounded wildcard parameterized type and the raw type on this link may be helpful,['java'] +499287,actionbar menu item onclick i have an action bar that puts everything in a menu in the top right which the user clicks and the menu options open up i inflate the action bar menu with this on each activity i use itoverride public boolean oncreateoptionsmenumenu menu inflate the menu this adds items to the action bar if it is present getmenuinflaterinflatermenumain2 menu return true and my xml for main2xml ismenu xmlnsandroid item androidididaction searchhome androidorderincategory100 androidshowasactionnever androidtitleseachmenumy question is do i put an onclick in the item in the xml and if so where do i put the onclick method it calls do i need to put it in every activity i launch this action bar in,['android'] +499327,androidsupportv4appfragmenttransaction required entering in code like thisfragmenttransaction transaction getsupportfragmentmanagerbegintransactioncomes up with this error androidsupportv4appfragmenttransaction transaction getsupportfragmentmanagerbegintransaction and has this as a quick fix which does in fact remove the errorandroidsupportv4appfragmenttransaction transaction getsupportfragmentmanagerbegintransactionand i am typing this in my main activity which extends fragmentactivity does anybody know why i have includedimport androidsupportv4appfragmentimport androidsupportv4appfragmentactivityimport androidsupportv4appfragmentmanagerimport androidsupportv4appfragmentpageradapterimport androidsupportv4viewviewpageredit descriptionfragment fragment new descriptionfragment androidsupportv4appfragmenttransaction ft getsupportfragmentmanagerbegintransaction ftreplaceridpager fragment ftsettransitionfragmenttransactiontransit fragment open ftcommitchanging getsupportfragmentmanager to getfragmentmanager requires me to change descriptionfragment to androidappfragmentany ideas,"['java', 'android']" +499407,rectangle class functions getx gety etc return in double precision well i know they do according to my experience and the oracle java api documentation but i wonder whythrough the constructor i am only allowed to pass int type arguments to the rectangle class the internal data representation of x y etc are of the type int and also setsize only excepts arguments of the type intbut why do all methods like getx gety getwidth etc return a double when there can not be any precision why not simple ints as expectedediti do understand that it is derived from the rectangle2d class but that is still no reason to just simply not provide any intbased getx and gety functions as in difference with the point and point2d class those methods are not abstract also setlocation is not abstract either,['java'] +499408,is jackson really unable to deserialize json into a generic type this is a duplicate question because the following questions are either messy or they are not answered at alldeserializingagenerictypewithjacksonjacksondeserializeintoruntimespecifiedclassjacksondeserializeusinggenericclassjacksondeserializegenericclassvariablei hope that this question will finally find an answer that makes this clear for goodhaving a model public class agentresponset private t result public agentresponset result thisresult result public t getresult return result json inputresultfirstclientid3testmailmodule3thirdclientid3secondclientid3and two recommended ways of deserializing generic types mapperreadvalueout new typereferenceagentresponsemapstring integer orjavatype javatype mappergettypefactoryconstructparametrictypeagentresponseclass mapclassmapperreadvalueout javatypejackson is never able to deal with the generic type t it figures it is a map from javatype but it finds object type constructor argument because of type erasure and throws an error so is this a jackson bug or am i doing something wrong what else is explicit specification of typereference or javatype forcomfasterxmljacksondatabindjsonmappingexception no suitable constructor found for type simple type class comfgmailsmtpagentresponsejavautilmapjavalangstringjavalanginteger can not instantiate from json object need to addenable type informationat source javaioinputstreamreader4f2d26d line 1 column 2at comfasterxmljacksondatabindjsonmappingexceptionfromjsonmappingexceptionjava164at comfasterxmljacksondatabinddeserbeandeserializerbasedeserializefromobjectusingnondefaultbeandeserializerbasejava984at comfasterxmljacksondatabinddeserbeandeserializerdeserializefromobjectbeandeserializerjava276at comfasterxmljacksondatabinddeserbeandeserializerdeserializebeandeserializerjava121at comfasterxmljacksondatabindobjectmapper readmapandcloseobjectmapperjava28at comfasterxmljacksondatabindobjectmapperreadvalueobjectmapperjava2064,['java'] +499479,what does c str method from string class returns i want to access starting address of the array that is maintained by the string clastring strheychar pointercharstrc stris the pointer pointing to the address of the arraymaintained by the string class or string class will create a new array from dynamic memory and copy the existing string into it and return it is addressif this is not the right way then how to access the starting address of the array that is maintained by the string class,['c++'] +499528,python how to xor two hex strings so that each byte is xored separately i have been posting similar questions here for a couple of days now but it seems like i was not asking the right thing so excuse me if i have exhausted you with my xor questions dto the point i have two hex strings and i want to xor these strings such that each byte is xored separately ie each pair of numbers is xored separately and i want to do this in python and i want to be able to have strings of different lengths i will do an example manually to illustrate my point i used the code environment because it allows me to put in spaces where i want them to beinputs1 48656c6c6fs2 61736bencoding in binary48 65 6c 6c 6f 010010 01100101 01101100 01101100 0110161 73 6b 01101 010011 01101011xoring the strings010010 01100101 01101100 01101100 01101 01101 010011 01101011 01101 01 0100converting the result to hex01101 01 0100 0d 1f 04output0d1f04so to summarize i want to be able to input two hex strings these will usually be ascii letters encoded in hex of different or equal length and get their xor such that each byte is xored separately,['python'] +499542,how to read existing text files without defining path most of the examples shows how to read text file from exact location fe cusersownerdocumentstest1txt but how to read text files without writing full path so my code would work when copied to other computers with visual studio i added 2 text files to project console project and do not know best way to read those files hope i described my problem clearly maybe i needed to add those txt files differentely like directly to same folder as exe file,"['c#', '.net']" +499598,how can we check if the current os is win8 or blue win81 and win8 has the same os version how can we check if the current os is win8 or blue the environmentosversion is giving us the same results environmentosversion 62920 environmentosversionversion 62920 environmentosversionversionmajor 6 environmentosversionversionminor 2,['c#'] +499632,eclipse kepler php code completion not working today i have downloaded eclipse kepler and i have noticed that php code completion is not working anymorewhen i type the first letters of a standard php function then press ctrlspace it gives me an empty list no default proposalthis used to work with the older version i was using juno and i have made no modificationi have already tried removing the php nature and adding it again through right click configure add php support but it did not helpin both versions the only plugin i have installed is aptana studio 350 nightly build but i am using eclipses editor for php not aptanas nor i am using aptanas php nature but eclipses,['php'] +499642,ios 61 with arc class from xib does not get deallocated uiclaswapper have an interesting issue where there is a class that is referenced in an xib layout subclass of uiscrollview and is not being deallocated according to instruments allocations and does not break in it is dealloc routine let us call it sclass1there is a using class let us call it uclass that has the xib file and the outletproperty nonatomic weak iboutlet sclass1 sclass1this is hooked properly to the xib file layoutsclass1 is property allocated when the xib for uclass is loaded uclass does get deallocated and then recreated from time to time and thus we have another instance of sclass1 but sclass1 never goes away and cannot find another reference to itdrill down in instruments shows the one malloc and that is itfyi the class gets started with uiclaswapper initwithcoder,['ios'] +499659,gradle how to customize android manifest permissions for my build system i need to build several app variants each requesting a different set of permissions how can this be done with gradle without invoking a separate script,['android'] +499704,twitter bootstrap caret size i have a caret like thisa classdropdowntoggle datatoggledropdown hrefmylist stylethisplayinlineblockpaddingleft0px b classcaretbais it possible to make this caret bigger with css or etc,['css'] +499710,how to start rails server in production mode using unicorn and config file i add gem unicorn to gemfile and call rails server unicorn e production but i get a load error then i add gem unicorn rails then call rails server unicorn e production but i cannot find the socket file so i am considering if it does not use the configunicornrb file as the configuration so i call unicorn rails c configunicornrb e production d but i get another error text file busyso now i am stuck in this matter could you help me,['ruby-on-rails'] +499766,matplotlib scatter plot legend i created a 4d scatter plot graph to represent different temperatures in a specific area when i create the legend the legend shows the correct symbol and color but adds a line through it the code i am using iscolorsb c y m rlo pltline2drange10 range10 markerx colorcolors0ll pltline2drange10 range10 markero colorcolors0l pltline2drange10 range10 markerocolorcolors1a pltline2drange10 range10 markerocolorcolors2h pltline2drange10 range10 markerocolorcolors3hh pltline2drange10 range10 markerocolorcolors4ho pltline2drange10 range10 markerx colorcolors4pltlegendlola h hh holow outlier lololo average hi hihi high outliernumpoints1 loclower left ncol3 fontsize8i tried changing line2d to scatter and scatter scatter returned an error and scatter changed the graph and returned an errorwith scatter i changed the range10 to the lists containing the data points each list contains either the x y or z variablelo pltscatterxloutlier yloutlier zloutlier markerx colorcolors0ll pltscatterxlolo ylolo zlolo markero colorcolors0l pltscatterxlo ylo zlo markerocolorcolors1a pltscatterxaverage yaverage zaverage markerocolorcolors2h pltscatterxhi yhi zhi markerocolorcolors3hh pltscatterxhihi yhihi zhihi markerocolorcolors4ho pltscatterxhoutlier yhoutlier zhoutlier markerx colorcolors4pltlegendlola h hh holow outlier lololo average hi hihi high outlierscatterpoints1 loclower left ncol3 fontsize8when i run this the legend no longer exists it is a small white box in the corner with nothing in it any advice,['python'] +499778,time going back on android i am developing an app and from time to time i am getting this weird messagewsystemclock11814 time going backwards prev 9003590393023ioctl vs now 9003584533648ioctl tid11856what does it mean why does it happenthanks,['android'] +499783,how to create a fluent query interface i know how to chain class methods with the return this and all but what i am trying to do is to chain them in a smart way have a look at thisalbums dbselectalbumswherex 20limit2orderdescwhat i could understand from this code sample is that the first 3 methods select where limit build the query statement that will be executed and the last one order comes to finish the statement and then executes it and throws back the result right but this is not the case because i can easily drop any of these methods except select of course or more importantly change their order and nothing will go wrong that means that the method select handles the work right then how the other 3 methods add toaffect the query statement after the method select was already called,['php'] +499808,firing watch event manually in angularjs i use this codescopewatchmessage function the codeis there any way to fire change event of message manually so the code will be executed,['javascript'] +499819,hide boundfields but still be able to get values with c i have a grid view and am using a variety of dataaspboundfield datafieldcatagory headertextsupport catagory sortexpressioncatagory aspboundfield datafieldappname headertextapplication name sortexpressionincidentnumber aspboundfield datafieldincidentnumber headertextincident sortexpressionincidentnumber aspboundfield datafieldhours headertexthours sortexpressionhours aspboundfield datafielddescription headertextdescription sortexpressiondescription aspboundfield datafieldcreateddate headertextcreated date sortexpressioncreateddate aspboundfield datafieldpk dailytaskhours headertext sortexpressionpk dailytaskhours readonlytrue aspboundfield datafieldpk nonscrumstory headertext sortexpressionpk nonscrumstory readonlytrue the last two columns however i do not want to show i am using it so i can retrieve the primary keys with this c code string dailytaskhourspk stringevaluespk dailytaskhourstostring string nonscrumstorypk stringevaluespk nonscrumstorytostring sqldatasource4deleteparametersdailytaskhourspkdefaultvalue dailytaskhourspk sqldatasource4deleteparametersnonscrumstorypkdefaultvalue nonscrumstorypkhowever i do not want to thisplay last two columns but when i setvisiblefalseand try to run the program i get the following errorobject reference not set to an instance of an objectdescription an unhandled exception occurred during the execution of the current web request please review the stack trace for more information about the error and where it originated in the code exception details systemnullreferenceexception object reference not set to an instance of an objectwhat am i doing wrong how do i prevent the user from seeing those fields,"['c#', 'asp.net']" +499823,reinitialize an angularjs controller if you have a controller to manipulate scope variables in angularjs is there an idiomatic way toreset the controllers scope andrestart controller initializationfor complex controllers it would be very convenient not to have to reset every variable to it is initial value especially if what you really want is a simple reinitialization of the controller and the scope navigating to the same url again via locationpath does not help thoughedit suppose i cannot use any windowlocation hack because this would violate the csp in chrome packaged apps,['javascript'] +499841,what event fires when item in html selectdropdown list is selected i want to respond to the user selecting an item in a select element yet this jqueryplatypusdropdownselectfunction alertyou selected somethingdoes nothing it shows no alert although jsfiddle sees it as valid jquerythe click event works but it is too fast it fires on clicking the select element prior to making a selectionof course i really want to do something likeplatypusdropdownselectfunction var selection platypusdropdownval getjsonplatypusjson selection data the htmlselect idplatypusdropdown option valueduckbillduckbilloption option valueduckbillplatypusduckbillplatypusoption option valueplatypusplatypusoption option valueplatypiplatypioptionselect,"['javascript', 'html', 'jquery']" +499843,xcode gives apple macho linker error i just compiled a project and xcode returns these two errors which do not seem to be my codes fault how do i fix themundefined symbols for architecture i386 vimageboxconvolve argb8 referenced from uiimageblur boxblurimagewithblur in uiimageblurold symbols not found for architecture i386clang error linker command failed with exit code 1 use v to see invocation,"['ios', 'objective-c']" +499848,ios 7 and helvetica neue ultralight use as default for older ios versions to my knowledge the default font of ios 7 is helvetica neue ultralight which is a lot thinner compared to its bold predecessor to provide a consistent design and make my forthcoming apps look the same across all common ios versions i would like to apply helvetica neue ultralight as the default primary font of the app gladly this new font is available since ios version 50 so it is already supported by versions prior to ios 7 sadly the only way i figured out to use it is to manually call uifont fontwithnamehelveticaneueultralight sizesize on each uiviews font which is tedious and errorprone to inconsistencyso my question is what is your way to do this or how do you handle this design change,"['iphone', 'ios']" +499954,python requests encoding post data version python 273other libraries pythonrequests 123 jinja2 26i have a script that submits data to a forum and the problem is that nonascii characters appear as garbage for instance a name like andra tachina comes out as andraa taachinaaheres how the data is submitted1 data is initially loaded from a utf8 encoded csv file like soentries with codecsopenfilename r utf8 as f for row in unicode csv readerfreadlines1 entriesappenddictzipcsv header rowunicode csv reader is from the bottom of python csv documentation page when i type the entries name in the interpreter i see the name as uandrxe9 txe9chinxe92 next i render the data through jinja2tpl tpl envget templateuforumposthtmlrendered tplrenderentriesentrieswhen i type the name rendered in the interpreter i see again the same uandrxe9 txe9chinxe9now if i write the rendered variable to a filename like this it thisplays correctlywith codecsopenouttxt a utf8 as f fwriterenderedbut i must send it to the forum3 in the post request code i haveparams upost renderedheaders ucontenttype uapplicationxwformurlencodedsessionpostposturl dataparams headersheaders cookiessessioncookiessession is a requests sessionand the name is thisplayed broken in the forum post i have tried the followingleave out headersencode rendered as renderedencodeutf8 same resultrendered urllibquote plusrendered comes out as all xyif i type renderedencodeutf8 i see the followingandrxc3xa9 txc3xa9chinxc3xa9how could i fix the issue thanks,['python'] +500003,should i save a path with or without a trailing slash at the end whats the convention i am always confuse whether i should add a trailing slash at the end of a path and often mix it up leading to some file no foundexample with drupalbase theme sitesallthemesmythemeor base theme sitesallthemesmythemethe image path could extend the base themebase image base themeimagesorbase image base themeimagesis there any convention or i can pick which one i preferi would choose to finish all path with a trailing slash since too many slash is better than no slash,['php'] +500014,what are the differences between the various java plugins for hot class reloading and which one is the most intuitive i am currently trying to implement hot class reloading in a java application however there are so many plugins to choose from and i cannot find a good comparison between the options also the websites of the plugins are not all very clear on what the exact features are and how to use themthere is also the option of making a custom hot class reloading classloader but i feel like that is similar to reinventing the wheel if there are already so many plugins which can do the job do other people agree with thisthe java plugins i found which i think can do the jobjrebeldynamic code evolution virtual machine dcevmfakereplaceapache commons java compiler interace jci filealterationmonitor famagentsmithfeenixplay frameworkjbosswildflyosgiso does anyone happen to know what the differences are between the plugins and also which plugin is the most intuitive to useas a side note what i actually want to do is reloading a jarfile dependency of my java application i have some java code which gets recompiled automatically very often and then converted to a jarfile it is a dependency of my java application and my application needs to use the newest version of this jarfile every timethanks in advancebestpj,['java'] +500023,equivalent of remove if in d recently i have taken an interest in the d programming language i just started learning it and am coming from a c background i am wondering if there is an equivalent of stdremove if i only saw remove looking through docs on the dlang siteif there is not a direct equivalent what is the proper or most idiomatic way of achieving the same result in dedit i should add that i am thinking in the context of eraseremove,['c++'] +500033,why would i not use batchsize on every lazy loaded relationship the batchsize annotation of hibernate allows for batched fetching of lazyloaded entities eg if i got something likepublic class product onetomanyfetchtypelazy batchsizesize10 private productcategory categorynow if i get the category of a product hibernate will fetch the categories of up to ten more products which are in the current session and have not yet had their category field initialized this saves a ton of sql calls to the database so far so good now i wonder why would i not use the batchsize annotation on every lazy loaded relationship after all why would i want extra calls to the database there clearly must be a reason for this otherwise the hibernate guys could have made it the default but i currently cannot see it,['java'] +500061,simple gcd serial queue example like fifo using blocks i read apple documentation on how to use serial queues to ensure that tasks to execute in a predictable order but now i am confused too muchsome how i am able to work serially but still i am not clear so i need simple serial example for my methods to execute seriallyi divided my functionality in to 4 parts and now want them to execute seriallyself readallimagesfromphotoslibraryself writefewimagestodirectoryself gettingbackallimagesfromfolder self movetonextview,['ios'] +500097,maximum size of a method in java 7 and 8 i know that a method cannot be larger than 64 kb with java the limitation causes us problems with generated code from a javacc grammar we had problems with java 6 and were able to fix this by changing the grammar has the limit been changed for java 7 or is it planned for java 8just to make it clear i do not need a method larger than 64 kb by myself but i wrote a grammar which compiles to a very large method,['java'] +500128,cannot convert symbol into string i have the following code in ruby take directly from the getting started with rails guide def create post postnewpost params postsave redirect to postendprivate def post params paramsrequirepostpermittitle text endwhen i run the above create i get the following errorcannot convert symbol into string,['ruby'] +500135,is there any way to get key hash from signed apk is there any way to get key hash from signed apkwe have a signed android apk file and we want to find out key hash of this apk for facebook sdkcan we do that by something like jarsignerany suggestions,['android'] +500145,spring is picking an interface implementation out of many on its own friends below is my code i am trying to run dependency injection with springi have an interface two class implementations of that interfaceone beanxml and one main method classinterface iwriterjavapackage di public interface iwriter public void writerstring s class writerjava package di import orgspringframeworkstereotypeservice service public class writer implements iwriter public void writer string s systemoutprintlns class nicewriterjavapackage diimport orgspringframeworkstereotypeserviceservicepublic class nicewriter implements iwriter public void writer string s systemoutprintlnthe string is s another classpackage diimport orgspringframeworkbeansfactoryannotationautowiredimport orgspringframeworkbeansfactoryannotationqualifierimport orgspringframeworkstereotypeserviceservicepublic class myspringbeanwithdependency autowired private iwriter writer public void run string s this is my test writerwriters mainjavapackage diimport orgspringframeworkbeansfactorybeanfactoryimport orgspringframeworkcontextapplicationcontextimport orgspringframeworkcontextsupportclasspathxmlapplicationcontextimport dimyspringbeanwithdependencypublic class main public static void mainstring args applicationcontext context new classpathxmlapplicationcontextbeansxml beanfactory factory context myspringbeanwithdependency test myspringbeanwithdependency factorygetbeanmyspringbeanwithdependency testrun beanxml xml version10 encodingutf8 beans xmlns xmlnsxsi xmlnsaop xmlnscontext xsischemalocation contextcomponentscan basepackagedi beans when i run the code spring container gives the output of the method of writerjava class i have not anywhere specified which implementation to pick how is spring picking up the implementation of writerjava,['java'] +500152,looking for flipbook frameworks any alternatives to turnjs i have been looking for some time now and cannot find good alternatives to turnjs turnjs seems fine but i would like to see some alternatives before spending the cash if there is opensource alternatives that would be even betterthe main features i am looking for areno flash not mandatoryzoomfastability to customize layout,['javascript'] +500387,create a form dynamically with jquery and submit i am trying to create a form dynamically via jquery and submit it to a php file this creates the form but nothing happens when i click the submit button what is going wrong here method i am using to create a form dynamically is shareappendform actionsharerphp methodpost shareappenddiv class appmsave thisdiv shareappendinput typetext placeholdername nameroutename idrname shareappendinput typetext placeholderdescription idrdescription nameroutedescription class address shareappendinput typetext placeholdertags idtags nameroutetags shareappendbrinput typesubmit idsavebutton value save shareappendform,"['javascript', 'jquery', 'html']" +500391,import android project in adt eclipse from github i am trying to import an android project from github into adt eclipse but it does not find any projects in the repository when i clone it the repo is clearly an android application project from looking at the source but no project is found to import my steps are as followsin package explorer rightclick and select importimport project from gitenter uri just import masterwhen cloning is done the following dialog shows upwhen choosing import existing projects the below dialog showswhy are no projects found to import how can i import the projects into eclipsethanks for help,['android'] +500396,recommended linux thistro for android development workstation i am trying to determine which is the bestpreferredrecommended linux thistribution for native android development i am looking into ubuntu now but am also considering centos i have always liked redhati guess at a bear minimum the os needs to support the latest jdk required by android sdkrun eclipse which means a desktop package is required as well like gnome or kdeat work i develop on windows using mono and visual studio but now that i got 422 loaded on my kindle firei really want to start doing some native android stuff which will hopefully help my monodroid debugging skillsupdate make that a kindle fire hd 89 since my battery started to expand ever so slightly i caught it early it gets worse pushing away the side trim a few millimeters amazon is sending a upgraded replacementthanks,"['android', 'java']" +500410,qml textfield binding loop detected for property text i am using qml with javascripti want to know exactly what the following error means so i can fix itqml textfield binding loop detected for property textsometimes my app gives me this warning and i do not understand it,['javascript'] +500434,correct way to test rails version for gem authoring what is the correct way to manage conditional flow in a gem based on rails versionrails 4 changes some things so i need to conditionally flow based on rails major version being 4 vs 3 or priorthe closest i have come isif railsversionsplitfirstto i 4 do the rails 4 thingelse do it the old wayend,['ruby-on-rails'] +500451,generating all combinations of a list in python heres the questiongiven a list of items in python how would i go by to get all the possible combinations of the itemsthere are several similar questions on this site that suggest using itertoolscombine but that returns only a subset of what i needstuff 1 2 3for l in range0 lenstuff1 for subset in itertoolscombinationsstuff l printsubset1231 21 32 31 2 3as you see it returns only items in a strict order not returning 2 1 3 2 3 1 2 1 3 3 1 2 2 3 1 and 3 2 1 is there some workaround that i cannot seem to come up with anything,['python'] +500474,generating a client certificate on an android device i want to create an android application which will use ssl client certificate authentication i have found sample codes which show me how two use ssl client certificate authentication in an android application this is clear to me my problem is however that i want to generate an ssl client certificate on the device simply stated i want my program to do the followingwhen the program is installed on the device a client certificate should be generated on the device when running it for the first time and a public key finger print will be sent to my server the certificate must be generated on first use how can i generate a client certificate on and android device from my application,['android'] +500492,can i thisallow other assemblies from inheriting from a class i have got something like this this gets implemented by plugin authors to get callbacks about various thingspublic interface externalplugin this gets called by the main application to tell the plugin some data is available or similar void dostuffsomedatablob blob data blob for v1 of apipublic class somedatablob internal somedatablobstring prop prop prop some piece of data that v1 plugins need public string prop get private set future data blob api v2 of apipublic class somedatablobv2 somedatablob can be passed to clients expecting somedatablob no problem internal somedatablobv2string prop string prop2 baseprop prop2 prop2 some piece of data that v2 plugins need v2 plugins can cast to this from somedatablob but still can load successfully into older versions that support only v1 of the api public string prop2 get private set i have to make somedatablob public so that it can be used as a member of the public interface method externalplugindostuff however i would not like to allow clients to inherit from that class and thus be susceptible to the brittle base class problem all derivatives of that class should be kept in the same assemblymarking the class sealed goes too far because i believe removing sealed is a breaking api change and even if that is not once i ship somedatablobv2 clients could still do the wrong thing and inherit from somedatablob directlyis there a way to enforce this kind of pattern,['c#'] +500530,when to use queue over arraylist one basic argument to use a queue over an arraylist is that queue gurnatees fifo behavior but if i add 10 elements to an arraylist and then iterate over the elemetns starting from the 0th elements then i will retrieve the elements in the same order as they were added so essentially that gurantees a fifo behaviorso what is so special about queue as compared to traditional arraylist,['java'] +500562,appsettings in app or web config using a linked file i am trying to reference some common config settings between a windows service and an aspnet mvc website i am doing this by using the file attribute on appsettings in either the appconfig or webconfig respectively the file named commonconfig that is being referenced is a linked file in a separate project in the same solution that commonconfig is set to content with copy always in both projects this stack answer to a similiar question seems to suggest at least for configsource this solution would work i do not want configsource though as i only want a handful of the properties to be common amongst the two projects update i just tried this and the configsource also does not work it cannot find the config file this leads me to believe the commonconfig is not treated as content with copy alwaysexample appconfigxml version10 encodingutf8 configuration appsettings filecommonconfig add keynotcommonkey value1 appsettingsconfigurationexample webconfigxml version10 encodingutf8configuration appsettings filecommonconfig add keynotcommonkey2 value2 appsettingsconfigurationexample commonconfig content copy alwaysappsettings add keycommonkey value1 appsettingsi am using configurationmanager webconfigurationmanager reading from the appsettings propertyany ideas why when the commonconfig is a linked file it is appsettings values are not used and when it is not linked it works as normalthanks,"['c#', 'asp.net', '.net']" +500570,jquery get element from array as jquery element if i callmyclassi get an array of elements if i now want to get the first element as jquery element i would do something like thismyclassget0so i wrap the domelement which i get from the array again with the jquery operator is there a more elegant way to do this some get method which returns a jquery element for example,"['javascript', 'jquery']" +500595,whats the use of the b backspace regex b matches a backspace character apparently i cannot understand how a string could contain a backspace charactercan someone give me a concrete example of how this would be used thanks so much,['javascript'] +500611,autofac register multiple decorators given the followingpublic interface icommandhandlerin tcommand void handletcommand commandpublic class movecustomercommandpublic class movecustomercommandhandler icommandhandlermovecustomercommand public void handlemovecustomercommand command consolewritelinemovecustomercommandhandler public class transactioncommandhandlerdecoratortcommand icommandhandlertcommand private readonly icommandhandlertcommand decorated public transactioncommandhandlerdecoratoricommandhandlertcommand decorated decorated decorated public void handletcommand command consolewritelinetransactioncommandhandlerdecorator before decoratedhandlecommand consolewritelinetransactioncommandhandlerdecorator after public class deadlockretrycommandhandlerdecoratortcommand icommandhandlertcommand private readonly icommandhandlertcommand decorated public deadlockretrycommandhandlerdecoratoricommandhandlertcommand decorated decorated decorated public void handletcommand command consolewritelinedeadlockretrycommandhandlerdecorator before decoratedhandlecommand consolewritelinedeadlockretrycommandhandlerdecorator after i can decorate the movecustomercommandhandler with a transactioncommandhandlerdecorator using the following codevar builder new containerbuilderbuilderregisterassemblytypestypeofmovecustomercommandhandlerassembly astype typegetinterfaces whereinterfacetype interfacetypeisclosedtypeoftypeoficommandhandler selectinterfacetype new keyedservicecommandhandler interfacetypebuilderregistergenericdecorator typeoftransactioncommandhandlerdecorator typeoficommandhandler fromkey commandhandlervar container builderbuildvar commandhandler containerresolveicommandhandlermovecustomercommandcommandhandlerhandlenew movecustomercommandwhich will output transactioncommandhandlerdecorator before movecustomercommandhandler transactioncommandhandlerdecorator after how can i also decorate the transactioncommandhandlerdecorator with the deadlockretrycommandhandlerdecorator to generate the following outputdeadlockretrycommandhandlerdecorator beforetransactioncommandhandlerdecorator before movecustomercommandhandler transactioncommandhandlerdecorator after deadlockretrycommandhandlerdecorator after,['c#'] +500625,how to use input type file in phonegap how to use html file attribute in phonegap so that i can browse any txt file from my android device and upload it to the serveri read file transfer method in phonegap documentation but according to that it is possible to upload files to the server only through urlbut is it possible in normal way like input typefile buttonuploadbuttoninput typefile acceptimage doesnt work in phone gap i looked at this link but that says only for images but how to upload the text files any helpcan anybody answer this,"['javascript', 'android']" +500667,how do i build boost with new visual studio 2013 preview when trying to build boost 154 for visual studio 2013 preview msvc12 it warnsunknown compiler version please run the configure tests and report the resultsand then fails with errorboost 1 54 0boostiteratordetailfacade iterator categoryhpp166 error c2039 assert not arg is not a member of boostmpland looks like old libs from msvc11 are not compatiblei reallyreally want to test new idecompiler version and need boost so is it possible to use boost with new visual studio 2013 preview,['c++'] +500685,how to set value for property of an anonymous object this is my code for examplevar output new netsessionid stringemptyforeach var property in outputgettypegetproperties propertysetvalueoutput test nullit occurs an exception property set method not found i want to know how to create an anonymous type with properties which can be setthanks,"['c#', '.net']" +500696,pointerevents none does not work in ie9 and ie10 the css property pointerevents none works fine in firefox but it does not in internet explorer 910is there a way to achieve the same behaviour of this property in ie any ideas,"['javascript', 'html', 'css']" +500700,setting up a cronjob in windows xampp help needed to set up this command in my xampp windows server0 cd cxampphtdocspluginsmoviefeed php cronphpcould you please point me in the right directionthanks,['php'] +500757,why cannot variables be declared in an if statement the following java code does not compileint a 0ifa 1 int b 0ifa 1 b 1why there can be no code path leading to the program assigning 1 to b without declaring it firstit occurred to me that bs variable scope might be limited to the first if statement but then i wouldnt understand why what if i really do not want to declare b needlessly in order to improve performance i do not like having variables left unused after declarationyou may want to argue than i could simply declare b in the second if statement in that case just imagine that it could be in a loop somewhere else,['java'] +500781,saxparseexception value is not a valid value for date i have an object tree of pojos that represents an xml schema this was created with the following jaxb ant scripti want to validate the root pojo and its children entities against the schema for missing attributesmy code is the following trycatch block omitted inspired by so question how to validate against schema in jaxb 20 without marshallingpublic boolean validateagainstschemapojo pojo jaxbcontext jc jc jaxbcontextnewinstancepojoclass schemafactory sf schemafactorynewinstancexmlconstantsw3c xml schema ns uri schema schema sfnewschemanew classpathresourceschemaxsdgetfile marshaller marshaller jccreatemarshaller marshallersetschemaschema marshallermarshalschema new defaulthandler return trueone of my attributes pojochildentitysomeattribute is a datexsdxsdattribute namesome date userequired xsdsimpletype xsdrestriction basexsddate xsdsimpletypexsdattributejavaxmlattributename somedate required trueprotected xmlgregoriancalendar somedateit gets populate from a javautildate object from another pojo one that is mapped with hibernateprivate static final xmlgregoriancalendar datetocalendardate date if date null return null try gregoriancalendar c new gregoriancalendar csettimedate return datatypefactorynewinstance newxmlgregoriancalendarc catch datatypeconfigurationexception e eprintstacktrace return null the exception isjavaxxmlbindmarshalexception with linked exceptionorgxmlsaxsaxparseexception cvcdatatypevalid121 20010511t0200 is not a valid value for datethis looks like jaxb tries to set both date and time for a field that must carry only the date and xmlgregoriancalendard is simply a datetime containerthe question is what causes the error how to fix,['java'] +500795,theano print value of tensorvariable how can i print the numerical value of a theano tensorvariablei am new to theano so please be patient i have a function where i get y as a parameternow i want to debugprint the shape of this y to the consoleusingprint yshaperesults in the console output i was expecting numbers ie 244shape0or how can i print the numerical result of for example the following code this counts how many values in y are bigger than half the maximumerrorcount tsumtgttabs ytmaxy20errorcount should be a single number because tsum sums up all the valuesbut usingprint errcountgives me expected something like 134sum0,['python'] +500803,how to construct custom views in xamarin is there any tutorial which will enable me to design custom views in xamarini want to build pinch zoom functionality for my android app using xamarini have tried following codebut its not workingi am always getting androidviewinflateexception binary xml file line 1 error inflating class la applicationzoomview errorusing system using systemcollectionsgenericusing systemlinq using systemtext using androidapp using androidcontent using androidos using androidruntime using androidutil using androidviews using androidwidget using androidgraphicsnamespace la application public class zoomview framelayout private scalegesturedetector mscaledetector private static float mscalefactor 10f public zoomview context context base context initialize public zoomview context context iattributeset attrs base contextattrs initialize public zoomview context context iattributeset attrs int defstyle base context attrs defstyle initialize void initialize mscaledetector new scalegesturedetectorcontext new scalelistener public override bool ontouchevent motionevent e mscaledetectorontouchevente return true protected override void ondrawandroidgraphicscanvas canvas baseondrawcanvas canvassave canvasscalemscalefactor mscalefactor canvasrestore private class scalelistener scalegesturedetectorsimpleonscalegesturelistener public override bool onscalescalegesturedetector detector mscalefactor detectorscalefactor do not let the object get too small or too large mscalefactor mathmax01f mathminmscalefactor 50f return true and in layout file xml version10 encodingutf8la applicationzoomview xmlnsandroid androidlayout widthmatch parent androidlayout heightmatch parent androidididmy view activity codeprotected override void oncreate bundle bundle baseoncreate bundle setcontentviewresourcelayoutzoomview some code,['android'] +500814,want to upload a pic to the server using phonegap in android i am doing project in android phonegap and i want to upload pic to the serverbut i am not getting idea where should i put this code i cannot show any buttons to upload photos please helpi am new in this i refereed this code from phonegap documentationi am trying this for hours but cannot get the better solution it is my first android phonegap projectcode head script typetextjavascript charsetutf8 srccordova240jsscript script typetextjavascript charsetutf8 documentaddeventlistenerdeviceready ondeviceready false function ondeviceready navigatorcameragetpictureuploadphoto functionmessage alertget picture failed quality 50 destinationtype navigatorcameradestinationtypefile uri sourcetype navigatorcamerapicturesourcetypephotolibrary function uploadphotoimageuri var options new fileuploadoptions optionsfilekeyfile optionsfilenameimageurisubstrimageurilastindexof1 optionsmimetypeimagejpeg var params paramsvalue1 test paramsvalue2 param optionsparams params var ft new filetransfer ftuploadimageuri encodeuri win fail options function winr consolelogcode rresponsecode consolelogresponse rresponse consolelogsent rbytessent function failerror alertan error has occurred code errorcode consolelogupload error source errorsource consolelogupload error target errortarget script head body h1exampleh1 pupload filep body,['android'] +500829,c function types i have a problem understanding function types they appear eg as the signature template parameter of a stdfunctiontypedef int signatureint the signature in questiontypedef stdfunctionintint std fun 1typedef stdfunctionsignature std fun 2static assertstdis samestd fun 1 std fun 2value they are the same coolint squareint x return xx signature pf square pf is a function pointer easysignature f but what the hell is thisf42 this compiles but does not linkthe variable f can not be assigned but can be called weird what is it good for thennow if i constqualify the typedef i can still use it to build further types but apparently for nothing elsetypedef int constsigint consttypedef stdfunctionintint const std fun 3typedef stdfunctionconstsig std fun 4static assertstdis samestd fun 3 std fun 4value also the same okconstsig pfc square pointer to function type cannot have const qualifierconstsig fc nonmember function cannot have const qualifierwhat remote corner of the language have i hit here how is this strange type called and what can i use it for outside of template parameters,['c++'] +500857,the shift key is just ignored after another key has been depressed poor shift key how do i detect when it is released i have a text input that presently goes transparent when a user presses shift keydown and binds a listener for the shift key going upiefookeydownfunction ifeventwhich16 make foo transparent thiskeyupfunction ifeventwhich16 return foo to its former glory thisunbindkeyup this works fine when no characters are pressed in the interim between depressing and releasing the shift key the problem is that when shift is down and another character is pressed the shift key seems to have been completely forgotten about when the shift key is released no keyup firesi tried triggering a fake keydown with the which property set to 16 to nudge it in the right direction after other characters are pressed but to no availany suggestions would be greatly appreciated,"['javascript', 'jquery']" +500863,outofmemoryerror when compiling my android app with gradle i am trying to build my app via gradle and i am currently having this issue after running a gradlew buildmyappcompiledebugthe system is out of resourcesconsult the following stack trace for detailsjavalangoutofmemoryerror java heap space at comsuntoolsjavacutilpositionlinemapimplbuildpositionjava139 at comsuntoolsjavacutilpositionmakelinemappositionjava63 at comsuntoolsjavadocdoccommentscannergetlinemapdoccommentscannerjava438 at comsuntoolsjavacmainjavacompilerparsejavacompilerjava512 at comsuntoolsjavacmainjavacompilerparsejavacompilerjava550 at comsuntoolsjavacmainjavacompilerparsefilesjavacompilerjava804 at comsuntoolsjavacmainjavacompilercompilejavacompilerjava727 at comsuntoolsjavacmainmaincompilemainjava353 at comsuntoolsjavacapijavactaskimplcalljavactaskimpljava115 at orggradleapiinternaltaskscompilejdk6jdk6javacompilerexecutejdk6javacompilerjava40 at orggradleapiinternaltaskscompilejdk6jdk6javacompilerexecutejdk6javacompilerjava33 at orggradleapiinternaltaskscompilenormalizingjavacompilerdelegateandhandleerrorsnormalizingjavacompilerjava95 at orggradleapiinternaltaskscompilenormalizingjavacompilerexecutenormalizingjavacompilerjava48 at orggradleapiinternaltaskscompilenormalizingjavacompilerexecutenormalizingjavacompilerjava34 at orggradleapiinternaltaskscompiledelegatingjavacompilerexecutedelegatingjavacompilerjava29 at orggradleapiinternaltaskscompiledelegatingjavacompilerexecutedelegatingjavacompilerjava20 at orggradleapiinternaltaskscompileincrementaljavacompilersupportexecuteincrementaljavacompilersupportjava33 at orggradleapiinternaltaskscompileincrementaljavacompilersupportexecuteincrementaljavacompilersupportjava24 at orggradleapitaskscompilecompilecompilecompilejava68 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava39 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava25 at javalangreflectmethodinvokemethodjava597 at orgcodehausgroovyreflectioncachedmethodinvokecachedmethodjava90 at groovylangmetamethoddomethodinvokemetamethodjava233 at groovylangmetaclassimplinvokemethodmetaclassimpljava1047 at groovylangmetaclassimplinvokemethodmetaclassimpljava877 at orggradleapiinternalbeandynamicobjectmetaclassadapterinvokemethodbeandynamicobjectjava216 at orggradleapiinternalbeandynamicobjectinvokemethodbeandynamicobjectjava122 at orggradleapiinternalcompositedynamicobjectinvokemethodcompositedynamicobjectjava147 at orggradleapitaskscompilejavacompile decoratedinvokemethodunknown source at groovylanggroovyobjectinvokemethodcallunknown sourcemyappcompiledebug failedany idea,['android'] +500883,how to split a string with angularjs i wanted to know if i can split a string simply in angularjsi have my scopetest test1test2in my controller and in my viewi wanted to do something like thattest0 splittest1 spliti have seen a lot thing about input and ngchange calling a function in the controller that split the string or something with nglist but nothing works in my casethx to all,['javascript'] +500936,what is a good way of handling abidifferences between libc and the older libstdc what if any is a good way of handling the abi inconsistency between libc and stdlibc on macthe problem many c11 features require the new libc implementation of the c standard library but libc is not abicompatible with the old libstdc while currently most software typically links against the latter for example the system compiler still uses stdlibc which means that all my libraries installed with macports have a different abi for stdclasses like string and are unlinkable with projects that make heavy use of c11my current hackofasolution keep two versions of libraries where this commonly leads to an issue boost opencv etc and link to the appropriate onei guess that one might suggest that if i really want to make use of libc i should purge my system of anything using stdlibc and make sure that anything from macports or anywhere else only links with libc you could see how daunting this task seemshas anyone worked out a nice way of relating to this betweenstdliblimbo that we are living in edit i am making an implied followup question more explicit apple ships both libc and libstdc with their systems assuming one attacks the underlying problem and tries to make a switch to libconly what would be the recommended way of switching from libstdc to libc given that 100 of the libraries currently installed on your system some shipped with the system most of them via macports a few via manual compilation are linked to libstdc if any has anyone done this and survived,['c++'] +500941,how to include a custom class in a symfony bundle i have a symfony bundle where i will have to use a custom class this class does not have to be accessible from all the website but just in a controller of this bundlei have seen a few solutions relative to the vendors but this is quite heavy and not necessary in my casedoes someone have a simpler solution,['php'] +500975,reusing ftpwebrequest i am trying to make a simple method to download a file from an ftp using ftpwebrequest with the method webrequestmethodsftpdownloadfile the problem is that i want to thisplay the progress of downloading and thus need to know the file size ahead to be able to calculate the percentage transfered but when i call getresponse in ftpwebrequest the contentlength member is 1ok so i get the size of the file in advance using the method webrequestmethodsftpgetfilesize no problem then after getting the size i download the filethis is where the problem in question appearsafter getting the size i try to reuse the ftpwebrequest and resets the method to webrequestmethodsftpdownloadfile this causes an systeminvalidoperationexception saying something like cannot perform this action after sending the request may not be the exact formulation translated from the one i get in swethishi have found elsewhere that as long as i set the keepalive property to true it does not matter the connection is kept active this is what i do not understand the only object i have created is my ftpwebrequest object and if i create another one how can it know what connection to use and what credentialspseudo codecreate ftpwebrequestset method property to getfilesizeset keepalive property to trueset credentials property to new networkcredentialget ftpwebresponse from the requestread and store contentlengthnow i got the file size so it is time to download the file setting method know causes the exception mentioned above so do i create a new ftpwebrequest or is there anyway to reset the request to be reused closing the response made no differencei do not understand how to move forward without recreating the object i could do that but it just does not feel right so i am posting here in hope to find the correct way of doing thisheres the non working code inputs are suri sthiskname suser and spwd ftpwebrequest request ftpwebrequestftpwebrequestcreatesurirequestmethod webrequestmethodsftpgetfilesizerequestcredentials new networkcredentialsuser spwdrequestusebinary truerequestusepassive truerequestkeepalive trueftpwebresponse resp ftpwebresponserequestgetresponseint contlen intrespcontentlengthrespcloserequestmethod webrequestmethodsftpdownloadfileresp ftpwebresponserequestgetresponsestream instr respgetresponsestreambyte buff new byte16384sthiskname environmentexpandenvironmentvariablessthisknamefilestream file filecreatesthisknameint readbytescountint readtotal0while readbytescount instrreadbuff 0 bufflength 0 readtotal readbytescount toolstripprogressbar1value 100readtotalcontlen applicationdoevents filewritebuff 0 readbytescountfileclosei hope someone can explain how this is supposed to work thanks in advance,"['c#', '.net']" +501029,iterate over static array in java without array variable in ruby i can do something likefoo bareach do str puts str iterating over an array defined in the statement in which i am using it since i can define an array in java likestring array foo bar i know i can avoid defining the variable by setting up a loop likefor string str new string foo bar but i was hoping java might have something more terse without defining a variable containing the array first and also allow me to avoid the dynamic allocation is there a syntax likefor string str foo bar that is more terse that will work with java that i am missing or is the solution i have got above my only option,['java'] +501053,fork in c using printf there are 2 different programs they are small for exampleint main printf print hello forkint main printf print hellon forkoutput 1 is print helloprint hellooutput 2 isprint hellothe question is why does the one with the n only print once and the first one prints it twice,['c'] +501071,how to store a cbperipheral for use in other views i setup a few ble connections in my view controller sviewcontroller and i need to store the peripherals for use in other view controllers i have tried creating an nsuserdefault object and storing the peripherals in there but i got the error attempt to insert nonproperty value and it never inserted i then tried wrapping it up in an nsdata object and storing it in nsuserdefaults but got the error cbconcreteperipheral encodewithcoder unrecognized selector sent and the app crashed so that definitely did not work i have also tried making the three cbperipheral variables global but i ran into a ton of issues with that i am still very new to programming i then looked into somehow caching them but have read on here that it will not work and to not waste the timedoes anyone know how to store a cbperipheral object so that i can access it and initialize it in other view controllers,"['ios', 'objective-c']" +501163,the current request for action 0 on controller type 1 is ambiguous i have two actions and i want my routes users and usersid to be different however it throws me erroris it possible implement this sorta thing without manually creating every route i will have other controllers that will follow similar pattern and writing custom routes for all of them seems redundant and bad idea in generalerrorthe current request for action index on controller type userscontroller is ambiguous between the following action methods systemwebmvcactionresult index on type apicontrollersuserscontroller systemwebmvcactionresult indexint32 on type apicontrollersuserscontrollercodepublic class userscontroller controller public actionresult index return null public actionresult indexint id return null,['c#'] +501185,why am i receiving a javanetsocketexception connection reset error from web service through soap ui and java client i am converting a visual foxpro application to a java web application and one small but important piece of the application makes a soap request to a web service i have written 3 test clients to call this web service and i have also tested through soap ui every one of my tests to this web service returns the error javanetsocketexception connection reset so i am obviously missing the same thing in every method of test or doing the same thing wrong i have the foxpro code and i have successfully submitted the request via foxpro and received a valid response but i do not have any experience with foxpro so i have been struggling with the difference between the code in foxpro that works and the new code i am writing in java i am hoping that someone with more experience with soap and web services can see my code maybe try it themselves and help me understand what the problem isi will provide the web service url as well as all my code i will also provide the foxpro command line code that works the foxpro code uses createobjectmicrosoftxmlhttp i have learned through my research that this is also used in asp vbnet and c 1 here is the web service that i need to callhost soap endpoint wsdl this web service does not contain wssecurity the credentials are in the request itself i cannot provide those of course but i do not believe they are needed to help me solve the connection reset problem2 first client i created used saaj api here is my codeimport javaiobufferedreaderimport javaiobufferedwriterimport javaioioexceptionimport javaioinputstreamreaderimport javaiooutputstreamwriterimport javanetinetaddressimport javanetsocketimport javautilarraylistimport javautillistimport javaxxmlsoapmessagefactoryimport javaxxmlsoapnameimport javaxxmlsoapsoapbodyimport javaxxmlsoapsoapbodyelementimport javaxxmlsoapsoapconnectionimport javaxxmlsoapsoapconnectionfactoryimport javaxxmlsoapsoapelementimport javaxxmlsoapsoapenvelopeimport javaxxmlsoapsoapexceptionimport javaxxmlsoapsoapmessageimport javaxxmlsoapsoappartimport javaxxmltransformsourceimport javaxxmltransformtransformerimport javaxxmltransformtransformerexceptionimport javaxxmltransformtransformerfactoryimport javaxxmltransformstreamstreamresultimport orgapachelog4jloggerimport commycompanywebappdomaintransactionbusinessentitytransactionimport commycompanywebappdomaintransactionccarspaymentcartimport commycompanywebappdomaintransactionrlisrlistransactionpublic class rlisservice private static logger logger loggergetloggercomcompanyxyzwebappservicetransactionrlisservice public listbusinessentitytransaction getcurrenttransactionspaymentcart paymentcart listbusinessentitytransaction transactionlist new arraylistbusinessentitytransaction listrlistransaction rlislist new arraylistrlistransaction try loggerinfoadding current transactions from rlis system rlislist thisgetcurrenttransactionsviasoaprequest for rlistransaction tx rlislist add transaction received from web service to transactionlist catch unsupportedoperationexception e eprintstacktrace catch soapexception e eprintstacktrace do something with the rlislist the list of rlistransactions return transactionlist private listrlistransaction getcurrenttransactionsviasoaprequest throws unsupportedoperationexception soapexception listrlistransaction rlistransactions new arraylistrlistransaction create soap connection try soapconnectionfactory soapconnectionfactory soapconnectionfactorynewinstance soapconnection soapconnection soapconnectionfactorycreateconnection send soap message to soap server string url soapmessage soapresponse soapconnectioncallcreatesoaprequest url process the soap response printsoapresponsesoapresponse soapconnectionclose catch transformerexception e eprintstacktrace catch ioexception e eprintstacktrace return rlistransactions private static soapmessage createsoaprequest throws soapexception ioexception messagefactory messagefactory messagefactorynewinstance soapmessage soapmessage messagefactorycreatemessage soappart soappart soapmessagegetsoappart string serveruri soap envelope soapenvelope envelope soappartgetenvelope envelopeaddnamespacedeclaration serveruri soap body soapbody soapbody envelopegetbody name bodyname envelopecreatenamegetdailyreceipts rlis soapbodyelement getdailyreceiptselement soapbodyaddbodyelementbodyname name contentlenghname envelopecreatenamecontentlength name consumerpinname envelopecreatenameconsumerpin name agentidname envelopecreatenameagentid name receiptdatename envelopecreatenamereceiptdate soapelement contentlengthelement getdailyreceiptselementaddchildelementcontentlenghname contentlengthelementaddtextnode494 soapelement consumerpinelement getdailyreceiptselementaddchildelementconsumerpinname consumerpinelementaddtextnodemyconsumerpin soapelement agentidelement getdailyreceiptselementaddchildelementagentidname agentidelementaddtextnode0 not a real agent id soapelement receiptdateelement getdailyreceiptselementaddchildelementreceiptdatename receiptdateelementaddtextnode20130701t0this is the soap request string from foxprosoapenvelope xmlnsxsi xmlnsxsd xmlnssoapsoapbodygetdailyreceipts xmlnscontentlength494contentlengthconsumerpinapikeyconsumerpinagentidagentidagentidreceiptdatesaledatereceiptdate getdailyreceipts soapbody soapenvelope soapmessagesavechanges print the request message systemoutprintrequest soap message soapmessagewritetosystemout systemoutprintln return soapmessage private static void printsoapresponsesoapmessage soapresponse throws transformerexception soapexception loggerdebugsoapresponsegetsoapbody transformerfactory transformerfactory transformerfactorynewinstance transformer transformer transformerfactorynewtransformer source sourcecontent soapresponsegetsoappartgetcontent loggerdebugnresponse soap message systemoutprintnresponse soap message streamresult result new streamresultsystemout transformertransformsourcecontent result 3 the next version of my client uses socket and outputstreamwriterimport javaiobufferedreaderimport javaiobufferedwriterimport javaioioexceptionimport javaioinputstreamreaderimport javaiooutputstreamwriterimport javanetinetaddressimport javanetsocketimport javautilarraylistimport javautillistimport javaxxmlsoapmessagefactoryimport javaxxmlsoapnameimport javaxxmlsoapsoapbodyimport javaxxmlsoapsoapbodyelementimport javaxxmlsoapsoapconnectionimport javaxxmlsoapsoapconnectionfactoryimport javaxxmlsoapsoapelementimport javaxxmlsoapsoapenvelopeimport javaxxmlsoapsoapexceptionimport javaxxmlsoapsoapmessageimport javaxxmlsoapsoappartimport javaxxmltransformsourceimport javaxxmltransformtransformerimport javaxxmltransformtransformerexceptionimport javaxxmltransformtransformerfactoryimport javaxxmltransformstreamstreamresultimport orgapachelog4jloggerimport commycompanywebappdomaintransactionbusinessentitytransactionimport commycompanywebappdomaintransactionccarspaymentcartimport commycompanywebappdomaintransactionrlisrlistransactionpublic class rlisservice private static logger logger loggergetloggercomcompanyxyzwebappservicetransactionrlisservice public listbusinessentitytransaction getcurrenttransactionspaymentcart paymentcart listbusinessentitytransaction transactionlist new arraylistbusinessentitytransaction listrlistransaction rlislist new arraylistrlistransaction try loggerinfoadding current transactions from rlis system rlislist thisgetcurrenttransactionsviaxmlhttp for rlistransaction tx rlislist add transaction received from web service to transactionlist catch unsupportedoperationexception e eprintstacktrace do something with the rlislist return transactionlist private listrlistransaction getcurrenttransactionsviaxmlhttp listrlistransaction rlistransactions new arraylistrlistransaction string xmldata soapenvelope xmlnsxsi xmlnsxsd xmlnssoap soapbody getdailyreceipts xmlns contentlength494contentlength consumerpinapikeyconsumerpin agentidagentidagentid receiptdatesaledatereceiptdate getdailyreceipts soapbody soapenvelope try create socket string hostname rlisapimyfwccom int port 443 inetaddress addr inetaddressgetbynamehostname socket sock new socketaddr port socket sock new sockethostname port send header string path bufferedwriter wr new bufferedwriternew outputstreamwritersockgetoutputstreamutf8 you can use utf8 for compatibility with the microsoft virtual machine wrwritepost path http10rn wrwritehost rlisapimyfwccomrn wrwritecontentlength xmldatalength rn wrwritecontenttype textxml charsetutf8rn wrwritern send data wrwritexmldata wrflush response bufferedreader rd new bufferedreadernew inputstreamreadersockgetinputstream string line whileline rdreadline null systemoutprintlnline catch exception e eprintstacktrace return rlistransactions 4 i have a similar test client that uses httpurlconnectionimport javaioioexceptionimport javaioinputstreamreaderimport javaiooutputstreamwriterimport javanethttpurlconnectionimport javanetmalformedurlexceptionimport javaneturlimport javaneturlconnectionpublic class testxmlclient public static void mainstring args string argurl systemoutprintlntest xml client string requestxml xml version10 encodingutf8 soapenvelope xmlnsxsi xmlnsxsd xmlnssoap soapbody getdailyreceipts xmlns contentlength494contentlength consumerpinmyconsumerpinconsumerpin agentid0agentid not real agent id receiptdate20130701t0receiptdate getdailyreceipts soapbody soapenvelope systemoutprintlnrequest requestxml try url url outputstreamwriter writer null inputstreamreader reader null httpurlconnection con null try url new url argurl con httpurlconnection urlopenconnection urlconnection urlc urlopenconnection httpurlconnection httpc httpurlconnectionurlc only interested in the length of the resource httpcsetrequestmethodhead int len httpcgetcontentlength systemoutprintlnlength len specify that we will send output and accept input consetdoinputtrue consetdooutputtrue consetconnecttimeout 20 long timeout but not infinite consetreadtimeout 20 consetusecaches false consetdefaultusecaches false tell the web server what we are sending consetrequestproperty contenttype textxml consetrequestproperty contenttype textxml charsetutf8 consetrequestpropertyconnection close writer new outputstreamwriter congetoutputstream writerwriterequestxml writerflush writerclose reading the response reader new inputstreamreader congetinputstream stringbuilder buf new stringbuilder char cbuf new char 2048 int num while 1 numreaderread cbuf bufappend cbuf 0 num string result buftostring systemerrprintln nresponse from server after postn result catch malformedurlexception e eprintstacktrace catch ioexception e systemoutprintlnegetstacktrace eprintstacktrace catch exception e eprintstacktrace finally if writer null try writerclose catch exception e ignore if reader null try readerclose catch exception e ignore if con null try conthisconnect catch exception e ignore finally in addition to all these test clients i also tried submitting various requests using soap ui interestingly i could not load the wsdl from the url so i saved the wsdl source code to a local file and used ithere is the request generated by soap ui from the wsdl filesoapenvelope xmlnssoap xmlnsrlis soapheader soapbody rlisgetdailyreceipts optional rlisconsumerpinrlisconsumerpin rlisagentidrlisagentid rlisreceiptdaterlisreceiptdate rlisgetdailyreceipts soapbodysoapenvelopewsdl saved locallyxml version10 encodingutf8wsdldefinitions xmlnss xmlnssoap12 xmlnshttp xmlnsmime xmlnstns xmlnssoap xmlnstm xmlnssoapenc targetnamespace xmlnswsdl wsdltypes sschema elementformdefaultqualified targetnamespace selement namegetdailyreceipts scomplextype ssequence selement minoccurs0 maxoccurs1 nameconsumerpin typesstring selement minoccurs1 maxoccurs1 nameagentid typesint selement minoccurs1 maxoccurs1 namereceiptdate typesdatetime ssequence scomplextype selement selement namegetdailyreceiptsresponse scomplextype ssequence selement minoccurs0 maxoccurs1 namegetdailyreceiptsresult typetnsarrayofreceipt ssequence scomplextype selement scomplextype namearrayofreceipt ssequence selement minoccurs0 maxoccursunbounded namereceipt nillabletrue typetnsreceipt ssequence scomplextype scomplextype namereceipt ssequence selement minoccurs1 maxoccurs1 nameorderid typesint selement minoccurs1 maxoccurs1 nametotalsaleamount typesdecimal selement minoccurs1 maxoccurs1 nametaxcollectorfees typesdecimal selement minoccurs1 maxoccurs1 nameorderdate typesdatetime selement minoccurs0 maxoccurs1 nameorderstatus typesstring selement minoccurs1 maxoccurs1 nameamounttoach typesdecimal selement minoccurs1 maxoccurs1 namecustomerid typesint selement minoccurs0 maxoccurs1 namecustomername typesstring selement minoccurs0 maxoccurs1 nameclerkusername typesstring selement minoccurs0 maxoccurs1 nametarpontagbegin typesstring selement minoccurs0 maxoccurs1 nametarpontagend typesstring selement minoccurs0 maxoccurs1 nameerrormessage typesstring ssequence scomplextype sschema wsdltypes wsdlmessage namegetdailyreceiptssoapin wsdlpart nameparameters elementtnsgetdailyreceipts wsdlmessage wsdlmessage namegetdailyreceiptssoapout wsdlpart nameparameters elementtnsgetdailyreceiptsresponse wsdlmessage wsdlporttype namewsreceiptssoap wsdloperation namegetdailyreceipts wsdlinput messagetnsgetdailyreceiptssoapin wsdloutput messagetnsgetdailyreceiptssoapout wsdloperation wsdlporttype wsdlbinding namewsreceiptssoap typetnswsreceiptssoap soapbinding transport wsdloperation namegetdailyreceipts soapoperation soapaction styledocument wsdlinput soapbody useliteral wsdlinput wsdloutput soapbody useliteral wsdloutput wsdloperation wsdlbinding wsdlbinding namewsreceiptssoap12 typetnswsreceiptssoap soap12binding transport wsdloperation namegetdailyreceipts soap12operation soapaction styledocument wsdlinput soap12body useliteral wsdlinput wsdloutput soap12body useliteral wsdloutput wsdloperation wsdlbinding wsdlservice namewsreceipts wsdlport namewsreceiptssoap bindingtnswsreceiptssoap soapaddress location wsdlport wsdlport namewsreceiptssoap12 bindingtnswsreceiptssoap12 soap12address location wsdlport wsdlservicewsdldefinitionsi will also provide you with the foxpro code that workssaledate date1xmlresponse magentid 0mapikey myconsumerpinmcsaledate stryearsaledate4 padlalltrimstrmonthsaledate220 padlalltrimstrdaysaledate220 t0text to xmlhttp noshowsoapenvelope xmlnsxsi xmlnsxsd xmlnssoapsoapbodygetdailyreceipts xmlnscontentlength494contentlengthconsumerpinapikeyconsumerpinagentidagentidagentidreceiptdatesaledatereceiptdategetdailyreceiptssoapbodysoapenvelopeendtextxmlhttp strtranxmlhttpapikeymapikeyxmlhttp strtranxmlhttpagentidmagentidxmlhttp strtranxmlhttpsaledatemcsaledateohttp createobjectmicrosoftxmlhttpohttpopenpost fohttpsetrequestheadercontenttype textxml charsetutf8 ohttpsendxmlhttpdo casecase ohttpstatus 200 xmlresponse ohttpresponsetext release ohttpcase ohttpstatus 201 waitprocessing please wait window nowait release ohttpcase ohttpstatus 202 wait processing please wait window nowait release ohttpcase ohttpstatus 400 release ohttp messageboxrlis bad request error0ccars returncase ohttpstatus 401 release ohttp messageboxrlis unauthorized error0ccars returncase ohttpstatus 403 release ohttp messageboxrlis forbidden error0ccars returncase ohttpstatus 404 release ohttp messageboxconnection to rlis site not available0ccars returncase ohttpstatus 500 release ohttp messageboxrlis internal server error0ccars returnotherwise release ohttp messageboxohttpstatus0ccars messageboxrlis internal server error code strohttpstatus300ccars returnendcasemessageboxxmlresponsehere is the full stacktrace of the errorjavanetsocketexception connection resetat javanetsocketinputstreamreadsocketinputstreamjava168at comsunnetsslinternalsslinputrecordreadfullyinputrecordjava422at comsunnetsslinternalsslinputrecordreadinputrecordjava460at comsunnetsslinternalsslsslsocketimplreadrecordsslsocketimpljava863at comsunnetsslinternalsslsslsocketimplperforminitialhandshakesslsocketimpljava1188at comsunnetsslinternalsslsslsocketimplstarthandshakesslsocketimpljava1215at comsunnetsslinternalsslsslsocketimplstarthandshakesslsocketimpljava1199at sunnetwprotocolhttpshttpsclientafterconnecthttpsclientjava434at sunnetwprotocolhttpsabstractdelegatehttpsurlconnectionconnectabstractdelegatehttpsurlconnectionjava166at sunnetwprotocolhttphttpurlconnectiongetoutputstreamhttpurlconnectionjava1014at sunnetwprotocolhttpshttpsurlconnectionimplgetoutputstreamhttpsurlconnectionimpljava230at comtaxcollectorccarsservicetransactiontestsoapclientmaintestsoapclientjava51from all my research over the last couple of days what i have determined is that this error is most often caused by the server closing the connection prior the client being done reading it at first i thought there was something wrong with the web service itself but since i am able to run the foxpro command and get a valid response that cannot be the case i tried changing many of the preferences in soap ui settings too including the socket timeout also my requests do not go through a proxy serverany suggestions or advice will be greatly appreciatedthank youupdated post followshere is the capture from wireshark simple acks omitted4034 20130705 1034045569010 1921680106 16220925202 sslv2 178 client hello4038 20130705 1034046697140 16220925202 1921680106 sslv3 1386 server hello certificate server hello done4040 20130705 1034048806780 1921680106 16220925202 sslv3 331 client key exchange4041 20130705 1034048851610 1921680106 16220925202 sslv3 72 change cipher spec4042 20130705 1034048878860 1921680106 16220925202 sslv3 127 encrypted handshake message4045 20130705 10340514290 16220925202 1921680106 tcp 54 https 58365 rst ack seq2769 ack445 win4584 len0then the series of messages repeatsso i think what this is showing is that there was first a connection request made from the client which was acknowledged by the serverthen there was a client hello a server hello handshake protocol certificate server hello done client key exchange change cipher spec encrypted handshake message and then finally the connection reset rst from the serveri looked up what the expert info on the last frame means and it looks like it could mean protocol sequence suspicious eg sequence was not continuous or a retransmission was detectedthis still has me scratching my head i do not understand what i may be doing in my code or from soap ui that could cause this connection reset from the server and why it does not happen from the microsoftxmlhttp post in foxpro code could it be that my request is getting sent as fragments and the server would not accept that i think i am going to try to run a wireshark capture while running the foxpro command but that is on a pc with windows 8 so i need to first figure out how to run it under admin the java test client i am running that gets a connection reset is on my macin the meantime does anyone have any further insight,['java'] +501252,saving and loading data c i know of a crude way of saving program data keeping it in a text file the problem is that anyone has access to the text file and can manipulate it for example i want to save and load game data which changes as the game progresses what methods are there to store such data and keep it accessible only within the game program so it is not manipulated by others,['c++'] +501281,play video without using media player winform i want to play a video like that guy did linki am working on c windows form application not nxabut i do not know howi tried using microsoftdirectxaudiovideoplayback but no luckthis is what i tried so far openfiledialog rihanna new openfiledialogifrihannashowdialog dialogresultok video new videorihannafilename videoowner panel1 videostop now what can i do i tried using video class but as i said it just did not worki am able to compile but when i am running the program i do not see the form window,['c#'] +501301,server send emails using gmail smtp gets alerts i did something like this to make my web app sends mails through gmails smtp i tried locally and it worked after i upload to the server which is in another country i get this errorauthentication failure smtp invalid response code received from server code 534 response 579 please log in with your web browser and then try again learn more at 579 579 webloginrequired fl2sm1579003pab23 gsmtpis there a way to ignore this,['php'] +501418,popular today this week this month design pattern i have a system that thisplays entries ordered by one of three fields the most popular today this week and this month each time an entry is viewed the score is incremented by 1 thus changing the orderso if entry 1 is new and viewed 10 times today its scores will betoday 10week 10month 10the current solutionat the moment i simply have 3 fields associated with each entry one for today another for this week and another for this month each time an entry is viewed all three scores are incremented by 1at the end of the day the day score is reset to 0 at the end of the current week the week score is set to 0 and at the end of the current calender month the month score is set to 0the problemalthough this works and uses little space it is not ideal for two reasons1 at the end of the current period dayweekmonth that value is reset to 0 all at once meaning that at 0 every day the ranking is all reset and all daily scores are set to 0 the same is true for end of the week and end of the month at 0 on the 1st of each month all scores are set to 0 loosing all existing ranking data2 because the end of the month usually falls inside a week monsun the monthly scores are reset during the week leading to weekly scores being higher than monthly scorespossible solutioni could use a rolling hourly counter for every hour of the month which is used to calculate the scores for the current dayweekmonth based on the current hour indexarray size 31 24 744 int16 valuesso on the 1st at 4am a view would be placed in hours4hours4the stats calculator would then then use today as the sum of the last 24 values and the this week score would be the sum of the last 247 values finally the this month would be the sum of the last 2431 valuessolution problemsthe major issue with solution 1 is the thiskmemory requirements i have gone from using 3 32 bit values in my current solution to using 744 32 bit values even if i change them to in16 i am still going to be using a lot more memory per entrymemory per entry 3 4 bytes 12 bytes existingmemory per entry 744 2 1488 bytes possible solutionwith this solution my memory usage per entry has jumped 12400can anyone suggest another solution that would meet resolve the issues in my current solution but without using 15k per entrymany thanks,['c#'] +501425,php preg replace remove entire line from a block of many lines if it contains an occurence of a word guys preg replace gurus i am looking for a preg replace snippet that i can use in a php file whereby if a word appears in a particular line that entire line is deletedreplaced with an empty linepseudocodeunwanted linesarrayword1word2word3new block of linespreg replaceunwanted lines block of linesthanxmarco,['php'] +501438,wickettester how to get html output for component i want to check if a given component has a css class set to do this i would like to get the html output for just that specific component wickettester can provide the html output for the entire rendered page what would be the best approach to get just the components htmlstring output,['html'] +501439,techniques to refresh an access token using oauth 2 on ios platform i am writing an app that uses oauth 2 thirdparty app that uses google account fot make the auth the auth is composed of 2 stepsget request to obtain the codepost request to exchange the code obtained in the 1st step with an access token and a refresh tokenwhen the access token about 5 min expires is possible to exchange the refresh token with a new access tokenmy question is must check if my access token is expired or for example every 4 min i must refresh my access token for example using nstimerwich are the typical solution to solve my problem thanks,"['iphone', 'ios', 'objective-c']" +501528,text writing animation like word2013 i was wondering if i can make a textbox or any control that you can write some text on it to be like word 2013 the animation experience is very goodi am now able to do type of animation on the control itself textbox but to do this type of animation to the cursor or on the text itself this is new,"['c#', '.net']" +501543,how to embed an http server like ijetty paw etc in android application how can i integrate an http server like ijetty paw etc in my android application i cannot find any useful tutorial on the internet most of the websites including the official ones just provide the server specification and downloadable server jar files i was looking for some java code to integrate that file in my eclipse project so that it could be used as server component in my application any help please,['android'] +501580,how to position a child view relative to containing view size i want to be able to position my child view 25 the size of the super view from the top nslayoutconstraint toppositionconstraint nslayoutconstraint constraintwithitem containerview attributenslayoutattributetop relatedbynslayoutrelationequal toitem childview attributenslayoutattributeheight multiplier025f constant00fhowever right now i am getting the following exception nsinvalidargumentexception reason nslayoutconstraint constraintwithitemattributerelatedbytoitemattributemultiplierconstant invalid pairing of layout attributeswhy does the error occur and how can i achieve what i want,['ios'] +501608,styling html title attribute using css i am trying to style the title attribute of a input typetext using css so this is what i didinputtypetexttitle fontstyle italic color grayit works okay but when i enter data into the field the data is gray and italic i want the data value to be normal and black and only the title to be italic and grayany ideas,"['html', 'css']" +501629,caliburnmicro cannot match view and viewmodel from different assemblies i just started with caliburnmicroi am trying to bootstrap my simple sample solution placing the shellview usercontrol in an testapp assembly and the shellviewmodel in the testviewmodel assemblywhat i get is a window with the following text cannot find view for caliburntestviewmodelshellviewmodelbut if i move the viewmodel to the app assembly it works perfectlythis is the bootstraper in the caliburnmicrotest assembly executablenamespace caliburnmicrotest public class appbootstrapper bootstrapperbase simplecontainer container public appbootstrapper thisstart protected override void configure container new simplecontainer thiscontainersingletoniwindowmanager windowmanager thiscontainersingletonieventaggregator eventaggregator thiscontainerperrequestishell shellviewmodel protected override object getinstancetype service string key var instance thiscontainergetinstanceservice key if instance null return instance throw new invalidoperationexceptioncould not locate any instances protected override ienumerableobject getallinstancestype service return thiscontainergetallinstancesservice protected override void buildupobject instance thiscontainerbuildupinstance protected override void onstartupobject sender systemwindowsstartupeventargs e thisthisplayrootviewforishell protected override ienumerablesystemreflectionassembly selectassemblies var assemblies new listassembly assemblygetexecutingassembly assemblyloadcaliburnmicrotestviewmodel return assemblies this is my viewmodel in the caliburnmicrotestviewmodel assembly class librarynamespace caliburnmicrotestviewmodel public interface ishell public class shellviewmodel ishell can you help me solve my problem pleasethank you d,"['c#', '.net']" +501634,where does eclipse save the classpath variables values eclipse supports configuring classpath variables window preferences java build path classpath variableswhere does it store the valuesplease note this question does not ask for the classpath file but rather for the classpath variables configuration place people can share the same classpath file using variables and still have their classpath variables configured differently,['java'] +501648,unique ptr to a base class i am trying to use a unique ptr to derived class in a function that takes a unique ptr to a base class something likeclass baseclass derived public basevoid funique ptrbase const baseaunique ptrderived derived unique ptrderivednew derivedfderivedif i understand this answer correctly this code should work but it causes the following compile errorserror c2664 f cannot convert parameter 1 from stdunique ptr ty to const stdunique ptr ty intellisense no suitable userdefined conversion from stdunique ptrderived stddefault deletederived to const stdunique ptrbase stddefault deletebase existsif i change f to take unique ptrderived const derived it works fine but that is not what i wantam i doing something wrong what can i do to work around thisi am using visual studio 2012,['c++'] +501668,defining a javascript prototype what are the functional differences between the following two javascript prototypes and are there any benefits for choosing one over the otheroption 1personprototypesayname functionname alertnameoption 2 personprototype sayname functionname alertname am i correct in assuming that option 2 results in trashing certain functions that are implicitly bound to the prototype,['javascript'] +501708,why the for loop counter does not get destroyed after exiting the loop in javascript forvar i0i5ialertiin javascript this will get us 5other languages like c java c will simply give an error that the i variable is not defined in the contextso why the for loop counter does not get destroyed after exiting the loop in javascript,['javascript'] +501757,how to use pubnub publish callback to find out which message to republish in case of an error the publish callback in pubnub api returns with a message like below 1sent13729639808030640but this does not give any indication as to for which message this callback is for in case of publish error the first value in the return array will be 0 but how do you find out which message to republishthe publisher can be publishing messages at a high rate and not waiting to receive the callback before publishing another message so when the callback is invoked the publisher might have already published 10 more messages,"['java', 'android']" +501798,how can i generate documentation for a python property setter using sphinx i have a python class something like the following with docstrings intended to be converted into documentation by sphinxclass directionobject a direction in which movement can be made def init self self name none property def nameself the unique name of the direction return the direction name rtype string return self name namesetter def nameself value sets the direction name param string value the direction name self name valuethe sphinx output looks something like thisclass directionname a direction in which movement can be madename the unique name of the directionreturns the direction namereturn type stringwhich is fine as far as it goes but note the complete absence of any information about the name setteris there any way to get sphinx to generate documentation for the property setter,['python'] +501805,c boostasio async read until slow i am having an unusual issue i have a c boostasio web server and to handle incoming requests i am using this codeboostasioasync read until socket response rnrn boostbind connectionhandle read headers shared from this boostasioplaceholderserror boostasioplaceholdersbytes transferred where socket is my boostasioiptcpsocket and response is a boostasiostreambufi am trying to just grab the headers of the request then i later do a second async read until with transfer exactly matching the contentlength that was parsed from the request header the problem is that above code is taking 100900ms to return on a very modern server from that read block until handle read headers is called the incoming request looks likepost load http11host wmysitecomaccept acceptencoding gzipdeflatecontenttype applicationxwformurlencodedfrom googlebotatgooglebotcomorigin referer useragent mozilla50 compatible googlebot21 xforwardedfor 6624975103xforwardedport 80xforwardedproto httpcontentlength 287connection keepaliveandtheactualcontentishere 287 bytes worththe headers seem to be terminated with a rnrn and it does trigger the handle read headers function before reading all the way to eof so it is not reading the whole page it actually is tripping the regex and these requests are coming from google so i am quite confident it is not lag on their endis there anything i could be overlooking on why it is taking so long to return any other catches with aync read until i might have missedthankseditupdateokay now i am very confused in trying megabytes suggestion i switched from a streambuf to a character array no luck then i refactored my code to use async read some rather than async read until and just scan for the delimited manually i also reset all os variables sysctrlconf to bone stock default to narrow down possibilities unfortunately i am still seeing 100900ms delays in the following code from calling handle read with the same incoming post requestsocket async read some boostasiobufferresponse boostbind connectionhandle read shared from this boostasioplaceholderserror boostasioplaceholdersbytes transferred where response is nowboostarraychar 4096 response to no avail same 100900ms delays there is no way this is normal any thoughts edit2per the recommendation of rhashimoto i enabled handler tracking and found this oddity in the log20130705 155839 thread 7fae57e3f700 incoming connection 0ms elapsedasio1373054319874916506508 receiveasio1373054319874963506509 acceptasio1373054319875008506asio1373054320609088508ecsystem0bytes transferred512asio1373054320609233508510 receiveasio1373054320609264508asio1373054320609284510ecsystem0bytes transferred40420130705 155840 thread 7fae57e3f700 received packet headers 638 bytes 734ms elapsedthere are over 700 milliseconds between the async accept and async receive in the code it goes from this block virtually straight from the http server 2 of 54 0dochtmlboost asioexamplescpp03 exampleshtml servercpp and connectioncppnew connection startnew connection resetnew connection io service pool get io serviceacceptor async accept new connection socket boostbind serverhandle accept this boostasioplaceholderserror and from the start tovoid connectionstart boostasioasync read until socket response rnrn boostbind connectionhandle read headers shared from this boostasioplaceholderserror boostasioplaceholdersbytes transferred and when handle read headers is called 700ms have passeddoes anyone have any ideas i am completely lostthanks so much,['c++'] +501857,select2 hiding the search box for my more significant selects the search box in select2 is wonderful however in one instance i have a simple select of 4 hardcoded choices in this case the search box is superfluous and looks a little silly being present is it possible to hide it somehow i took a look through the documentation online and could not find any options for this in the constructori could of course just use a regular html select but for consistency i would like to use select2 if possible,['jquery'] +501877,relative path on unit test project c i have a solution which has a console application and unit testvar target new validatorvar targetfile cfoldersubfolderanothersubfolderdevelopmentdevsrcunittesttargetfolderfilexmlbool actual targetvalidatetargetfileassertareequaltrue actualthe validator is located at the console application project while my filexml is located at the folder inside the unit test projectthis unit test is passing however i want to make sure that when i check in this in to my tfs or build server it can still locate my targetfilehow am i gonna change the path of the targetfilethanks in advance,['c#'] +501884,bootstrap datepicker in bootstrap button drop down my requirement i am working on a twitter bootstrap button dropdown and using bootstrapdatepicker in one of the list items as shown in below image as per my requirement i need to have month calendar in last item and clicking on that opens the bootstrapdatepicker and i should be able to select month yearproblem i am facing when i open that datepicker and select any month or year or click on any of the navigation in datepicker to move to another month or year the button drop down hides but the datepicker remains there as in the below image i have been trying but not able to get it workingwhat i think not sure its correct or not when i click on datepicker it is being attached to the body element directly where as all the list items and thier children are deep down in html so even if i try to stop event propagation for any click inside dropdown it wont count for datepicker as it is appended to body just for more info i have some actions defined on click of other list items would really appreciate if someone could help me out with this i really need to get this thing working for my project,['jquery'] +501895,android how to set imageview with percentage in relativelayout i want to build a ui like this here is my xml code for itfor my design i want effect camera to combine as one imageview like shop in the linkso there will be total 5 imageviews and i set the id as they named in the linkthe problem is how can i set the height and width with percentageeffectcamrea height 25width 100collage height 25width 50draw height 25width 50photo height 50width 50shop height 25width 100thank you very much relativelayout androidididmaincontent androidlayout widthfill parent androidlayout heightfill parent androidorientationhorizontal androidbackgroundf imageview androidididimg effectcamera androidlayout widthfill parent androidlayout heightwrap content androidlayout alignparentlefttrue androidsrcdrawablea imageview androidididimg collage androidlayout widthfill parent androidlayout heightwrap content androidlayout alignparentlefttrue androidlayout belowidimg effectcamera androidsrcdrawableb imageview androidididimg draw androidlayout widthfill parent androidlayout heightwrap content androidlayout alignparentrighttrue androidlayout belowidimg effectcamera androidlayout torightofidimg collage androidsrcdrawablec imageview androidididimg photo androidlayout widthfill parent androidlayout heightwrap content androidlayout alignparentrighttrue androidlayout torightofidimg collage androidlayout belowidimg draw androidsrcdrawabled imageview androidididimg shop androidlayout widthfill parent androidlayout heightwrap content androidlayout alignparentlefttrue androidlayout belowidimg photo androidsrcdrawablee relativelayout,['android'] +501899,conditionally show hide aspnet gridview column this is how i navigate to mypageaspx a hrefmypageaspxshowevalid idshoweach runatservershow eachaa hrefmypageaspxshowall idshowall runatservershow allaand i have a gridview in mypageaspxaspgridview idgridview1 runatservercolumnsaspboundfield headertextcolumnone visibletrueaspboundfield headertextcolumntwo visibletruecolumnsaspgridviewwhat i want to do is if query string is equal to allmypageaspxshowall i want to set gridview1s column2s visible to true else set visible to false how can i do it,"['c#', 'asp.net']" +501907,darken background image on hover how would i darken a background image on hover without making a new darker imagecssimage background url width 58px height 58pxjsfiddle link,"['html', 'css']" +501917,how to write a stored procedure in phpmyadmin i am not able to find where to write the stored procedure in phpmyadmin and how to call it using mvc architecture,"['php', 'mysql']" +501928,how to use crypto with jni or ndk for a android application i download from crypto herei find some way to build it with visual studioso i do not know how to use it for our android application with jni or ndk,"['android', 'c++', 'c']" +501933,why do we need nginx with thin on production setup why do we need to install nginx with thin on production setup as thin is itself a web server every blog post people are using rubyrailsnginxthin,"['ruby-on-rails', 'ruby']" +501939,java could not find or load main class im using fedora 19content of helloworldjava class helloworld public static void main string args systemoutprintln hello world i can successfully compile it usingjavac helloworldjavabut i cannot run it usingjava helloworldit gives the following errorerror could not find or load main class helloworldbut i can run it usingsudo java helloworldwhat am i missing here,['java'] +502033,injecting dependencies in config modules angularjs currently in appjs i have the following routesvar gm angularmodulegm gmservicesgmdirectivesgmfiltersgmcontrollersngsanitizegmconfigrouteprovider path functionrouteprovider path routeproviderwhenlogin templateurl pathviewapplicationauthenticationloginhtml controller authcontroller routeproviderwhendashboard templateurl pathviewapplicationdashboardindexhtml controller dashboardcontroller routeproviderotherwise redirectto login im trying to in in ject the path dependency as you can see although i get an error saying it cant find this provider i think this is because config module provicers are execued first before anything else below is my path provider definition in servicesjsgmfactorypath function return view functionpath return appviews path css functionpath return appviews path font functionpath return appviews path img functionpath return appviews path js functionpath return appviews path vendor functionpath return appviews path base functionpath return path how can i inject this provider into a config module,['javascript'] +502070,map containig itself as a value directly from this java doca special case of this prohibition is that it is not permissible for a map to contain itself as a key while it is permissible for a map to contain itself as a value extreme caution is advised the equals and hashcode methods are no longer well defined on such a mapwhy would the hashcode and equals no longer be well defined on such a mapthanks in advance,['java'] +502117,difference between serialize and serializeobject jquery i search a lot but did not find perfect difference between serialize and serializeobject method of jqueryplease help me to understand this,['jquery'] +502135,how can a string be initialized using if string is a class just like any other how can it be initialized using double quotes,['java'] +502141,image gallery with a horizontal scrollview ia m trying to do an easy example of an image gallery using horizontalscrollview and adding the images dynamically i have searched examples but most are too complex is there a simple example of how to do it,['android'] +502152,exclude subview from uitapgesturerecognizer i have a subview and a superview the superview has an uitapgesturerecognizer attached to it uiview superview uiview alloc initwithframecgrectmake0 0 320 480uiview subview uiview alloc initwithframecgrectmake100 100 100 100uipangesturerecognizer recognizer uipangesturerecognizer alloc initwithtarget self action selectorhandletapsuperviewuserinteractionenabled yessubviewuserinteractionenabled nosuperview addgesturerecognizerrecognizerself addsubviewsuperviewsuperview addsubviewsubviewthe recognizer is fired inside the subview as well is there a way to exclude the recognizer from the subview i know this question has been asked before but i did not find a good answer to it,"['ios', 'objective-c']" +502159,nullable datetime with sqldatareader i almost hate to ask this question seems like it has been asked a million times before but even with me researching the other question i still cant seem to figure this out in my case i read that datetime is a nullable type and i tried a few of the examples but i am trying to figure out if it is null in the database my sqldatareader is failingerrorsystemdatasqltypessqlnullvalueexception data is null this method or property cannot be called on null valuesdetailsclassprivate datetime startingdatepublic datetime startingdate get return startingdate set startingdate value constructorpublic detailsclassdatetime startingdate thisstartingdate startingdatedbclass using sqlconnection con new sqlconnectionconnectionstring using sqlcommand cmd concreatecommand listdetailsclass details new listdetailsclass detailsclass dtl try conopen cmdcommandtext stored procedure name cmdcommandtype commandtypestoredprocedure cmdparametersaddwithvaluemyparameter myparameter using sqldatareader reader cmdexecutereader while readerread dtl new detailsclass readergetint32readergetordinalmembershipgen readerisdbnull1 null readergetstringreadergetordinalemail readergetdatetimereadergetordinalstartingdate detailsadtl readerclose return details,"['c#', 'asp.net']" +502199,failed to load map error contacting google servers issue with android google maps api v2 i have been trying to app a google map in my android app using the v2 api for the past two days with no success all i get every time is a google maps android api16603 failed to load map error contacting google servers this is probably an authentication issue but could be due to network errorsi have followed googles setup tutorial tried multiple times with different projects in different workspaces tried different google accounts gone through various answers and suggestions here in stackoverflow but to no availi am using eclipse 422 with android sdk tools 2201 and i have installed google play services rev 7 also i have imported googleplayservices lib into my workspace and added a reference to that to my android projecthere is my codeandroidmanifestxmlxml version10 encodingutf8manifest xmlnsandroidpackagecomexamplegooglemapdemoandroidversioncode1androidversionname10 usessdk androidminsdkversion8 androidtargetsdkversion17 permission androidnamecomexamplegooglemapdemopermissionmaps receive androidprotectionlevelsignature usespermission androidnamecomexamplegooglemapdemopermissionmaps receiveusespermission androidnameandroidpermissioninternet usespermission androidnameandroidpermissionaccess network state usespermission androidnameandroidpermissionwrite external storage usespermission androidnamecomgoogleandroidprovidersgsfpermissionread gservices usespermission androidnameandroidpermissionaccess coarse location usespermission androidnameandroidpermissionaccess fine location usesfeature androidglesversion0x020 androidrequiredtrueapplication androidallowbackuptrue androidicondrawableic launcher androidlabelstringapp name androidthemestyleapptheme activity androidnamecomexamplegooglemapdemomainactivity androidlabelstringapp name intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity metadata androidnamecomgoogleandroidmapsv2api key androidvaluemy api key applicationmanifestactivity mainxmlxml version10 encodingutf8fragment xmlnsandroidxmlnsmapandroidididthe mapandroidlayout widthmatch parentandroidlayout heightmatch parentandroidnamecomgoogleandroidgmsmapssupportmapfragmentmainactivityjavapackage comexamplegooglemapdemoimport androidosbundleimport androidsupportv4appfragmentactivityimport androidviewmenupublic class mainactivity extends fragmentactivity overrideprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity mainoverridepublic boolean oncreateoptionsmenumenu menu inflate the menu this adds items to the action bar if it is present getmenuinflaterinflatermenumain menu return truealso i created an api project on where i have enabled the google maps android api v2 service then i obtained my sha1 debug certificate fingerprint using keytool list v keystore cusersmy user nameandroiddebugkeystore alias androiddebugkey storepass android keypass androidand entered that and the package name in the api console got the api key and put it in the manifest where my api key is this procedure i repeated a number of times regenerating the key but with the same resultcould anyone help with this or suggest anything else i could try any help will be greatly appreciated,['android'] +502244,set alpha of background of uibutton but not the title when i set the alpha of the button it also affects the opacity of the title is there a way to target only the background and leave the title alpha at 10,['ios'] +502247,angularjs does not update img src when model changes i use ngsrc to load images value is loaded from some scope variable like thisimg ngsrccurrentreceiptimagemy issue is that when i run delete scopecurrentreceipt it makes ngsrc attribute empty but does not reflect it in src attribute so as a result i keep seeing that image where i need empty placeholder how can i deal with it,"['javascript', 'html']" +502254,advantage of tap method in ruby i was just reading a blog article and noticed that the author used tap in a snippet something like user usernewtap do u uusername foobar usaveendmy question is what exactly is the benefit or advantage of using tap could not i just do user usernewuserusername foobarusersaveor better yetuser usercreate username foobar,['ruby'] +502262,swap stdunique ptr with lambda as deleter gcc can we use a lambda as a deleter with a stdunique ptr actualy i did it with clang and it was happy to do soi am using stdswap to swap to stdunique ptrobjtype decltypdeleter where auto deleter struct addrinfo ptrif ptr nullptr freeaddrinfoptr clangs swap seems to do not need a copy assignment operator but gccs stdswap did as you can see in those logs in file included from usrincludec481memory810 from homezenolprojsrcprojtcpclientcpp28usrincludec481bitsunique ptrh in instantiation of astdunique ptr tp dp stdunique ptr tp dpoperatorstdunique ptr tp dp with tp addrinfo dp projtcpclientconnectconst projsocketaddress int lambda0ausrincludec481bitsmoveh17611 required from avoid stdswap tp tp with tp stdunique ptraddrinfo projtcpclientconnectconst projsocketaddress int lambda0ahomezenolprojsrcprojsockethelphpp10950 required from avoid projretrieve addressesstdstring int addrinfo addrinfo t u with t stdunique ptraddrinfo projtcpclientconnectconst projsocketaddress int lambda0 you projtcpclientconnectconst projsocketaddress int lambda0 stdstring stdbasic stringcharahomezenolprojsrcprojtcpclientcpp6549 required from hereusrincludec481bitsunique ptrh19316 erreur use of deleted function aprojtcpclientconnectconst projsocketaddress int lambda0 projtcpclientconnectconst projsocketaddress int lambda0operatorconst projtcpclientconnectconst projsocketaddress int lambda0a get deleter stdforwarddeleter type uget deleter homezenolprojsrcprojtcpclientcpp5621 note a lambda closure type has a deleted copy assignment operator auto deleter struct addrinfo ptr what says the standard can i manage to wap those two stdunique ptr are they a workaround maybe encapsulating the lambda inside a stdfunction edit here is a small example that should be more or less the same thing auto deleter struct addrinfo ptrif ptr nullptr freeaddrinfoptr stdunique ptrstruct addrinfo decltypedeleterresources keepernullptr deleterint main decltyperesources keeper plouf1nullptr deleter decltyperesources keeper plouf2nullptr deleter stdswapplouf1 plouf2 return 0the error in file included from usrincludec481bitsstl pairh590 from usrincludec481bitsstl algobaseh64 from usrincludec481memory62 from minicpp1usrincludec481bitsmoveh in instantiation of avoid stdswap tp tp with tp lambda0ausrincludec481tuple38136 required from avoid std tuple impl idx head tail m swapstd tuple impl idx head tail with long unsigned int idx 1ul head lambda0 tail ausrincludec481tuple38235 required from avoid std tuple impl idx head tail m swapstd tuple impl idx head tail with long unsigned int idx 0ul head addrinfo tail lambda0ausrincludec481tuple66733 required from avoid stdtuple t1 t2swapstdtuple t1 t2 with t1 addrinfo t2 lambda0ausrincludec481tuple10507 required from avoid stdswapstdtuple elements stdtuple elements with elements addrinfo lambda0ausrincludec481bitsunique ptrh26921 required from avoid stdunique ptr tp dpswapstdunique ptr tp dp with tp addrinfo dp lambda0ausrincludec481bitsunique ptrh4847 required from avoid stdswapstdunique ptr tp dp stdunique ptr tp dp with tp addrinfo dp lambda0aminicpp2129 required from hereusrincludec481bitsmoveh17611 erreur use of deleted function a lambda0 lambda0operatorconst lambda0a a glibcxx move b minicpp917 note a lambda closure type has a deleted copy assignment operator auto deleter struct addrinfo ptr in file included from usrincludec481bitsstl pairh590 from usrincludec481bitsstl algobaseh64 from usrincludec481memory62 from minicpp1usrincludec481bitsmoveh17711 erreur use of deleted function a lambda0 lambda0operatorconst lambda0a b glibcxx move tmp,['c++'] +502270,hibernate exception unknown name value for enum class im getting unknown name value for enum class when trying to retrieve records from db using jsf 20 jpathe possible values in my db are f or jenumpublic enum tipopessoa fisica f fasica juridica j juradica private final string id private final string descricao private tipopessoastring id string descricao thisid id thisdescricao descricao public string getid return id public string getdescricao return descricao entity columnnullablefalse length1private tipopessoa tipopessoapublic tipopessoa gettipopessoa return tipopessoapublic void settipopessoatipopessoa tipopessoa thistipopessoa tipopessoawhen i try to read the records from db i got the errorwould you please help me on this issue thanksstack trace javaxservletservletexception unknown name value for enum class brcomaxentidadetipopessoa f javaxfaceswebappfacesservletservicefacesservletjava606 brcomafiltrofiltroencodedofilterfiltroencodejava26root causejavaxejbejbtransactionrolledbackexception unknown name value for enum class brcomaxentidadetipopessoa f,['java'] +502318,d3onmouseover event does not work with nested svg elements i have a nested set of elements svg the root element is the graph and the children are elements in the graph lines axis etc simplified exampleg transformtranslate8010 idmaingraph g classline path dpath ggmy problem is that if i bind a mouseovermousemove event with d3onmouseover for example to the maingraph element it only triggers if i move the mouse over one of the child elementsone of the things i read is that there is priority of later elements so i added stylepointereventsnone to all child elements but that did not work,['javascript'] +502344,switching to parent frame from iframe and finding an element in parent frame using selenium webdriver c scenario i have a page with an iframe text editor and a button in the page too i switched from the parent frame to the iframe to read from the text editor body after reading from the body of the text editor i want to click on the button in the parent frame of the page for this i tried to switch back to the parent frame from the iframe using the following statementwebdriverswitchtodefaultcontent but still i am not able to find the button element which resides in the parent framei appreciate your helpthanks,['c#'] +502364,angularjs and enterprise applications we are currently evaluating the use of angularjs in a enterprise application ebanking as a single page applicationmany of the devswork are already convinced that there no other way to go it is the trend it is future proof html css and js it is easy to do less burden on the server etc etcdespite the interesting part of this framework i am not convinced that there are factors that must be considered before going this road these can bemaintainability of codetestability of code not only the ui partcontinuous integration like teamcity or tfsdeveloper friendliness like debugging navigating through codesecurity if there is a riskhas anyone any experience on enterprise apps build like that i would rather go with aspnet mvc4 please no hypothetical answers i do not want to start a war real life experience is really appreciatedregards,['javascript'] +502413,why do i hear a beep on this program i saw this char szprivatekey definition on a source when i was reading so i went to check it out what it was strangely this makes a sound when the program is run is there an easter egg in here or something compiled using visual studio 2003 windowsint tmainint argc tchar argv const unsigned char szprivatekey 0x30 0x82 0x04 0xbb 0x02 0x01 0x00 0x30 0x0d 0x06 0x09 0x2a 0x86 0x48 0x86 0xf7 0x0d 0x01 0x01 0x01 0x05 0x00 0x04 0x82 0x04 0xa5 0x30 0x82 0x04 0xa1 0x02 0x01 0x00 0x02 0x82 0x01 0x01 0x00 0x87 0x1f 0xec 0xfd 0xaf 0xd2 0x2f 0xaa 0x4e 0xc2 0xad 0x5a 0x4c 0x3a 0x7a 0x81 0x9e 0xba 0x28 0x6a 0x84 0xe9 0xb7 0xf9 0x36 0x87 0x56 0x16 0xc5 0xa4 0x1d 0x11 0x67 0x12 0x87 0x81 0xf5 0xfa 0xf6 0x01 0xe7 0x55 0x83 0x4a 0xac 0x40 0x4d 0x2c 0x90 0x62 0x77 0xfc 0x73 0xf9 0x5e 0x7f 0x67 0x8c 0xa7 0x94 0x32 0x28 0xdd 0xef 0x91 0xe5 0x94 0xd6 0x5c 0xb5 0x63 0xc4 0x76 0x2d 0xff 0x03 0x75 0x55 0x85 0x60 0x56 0x44 0x37 0x18 0x08 0xe7 0x0a 0x90 0x74 0xa0 0x9e 0x82 0x4f 0x56 0x4c 0xd9 0xe5 0x73 0x88 0x9e 0x0f 0xd2 0x0c 0x9e 0xf1 0x90 0x65 0xef 0xa4 0x23 0x99 0xcc 0xe8 0x16 0xf7 0x96 0x54 0xda 0xf0 0x45 0x66 0x48 0xfe 0xe6 0x89 0xa9 0xfc 0x57 0xa5 0xd0 0xec 0x48 0x61 0xc7 0x7b 0x8e 0xc9 0x26 0x39 0xb3 0x8d 0x64 0x89 0xab 0x4e 0xf5 0xcd 0x5a 0x72 0xc5 0xee 0x2f 0x73 0x34 0x9e 0x0f 0xa4 0x2e 0x54 0x6d 0x09 0x3b 0x14 0x37 0x6c 0x82 0x75 0x75 0xe0 0x80 0x5d 0xb9 0xa8 0xfc 0x5f 0xe6 0x8f 0x9d 0x23 0x1c 0x4b 0xda 0xc1 0xb2 0x52 0x83 0xea 0xf6 0xe9 0x30 0x47 0x22 0x8c 0x7e 0x74 0x98 0x82 0x05 0x0b 0x39 0xbd 0x47 0x38 0x6b 0xae 0x5f 0xd4 0x21 0x0f 0xe1 0xba 0x86 0x50 0x01 0x40 0x22 0x90 0xe0 0xe4 0xc4 0x11 0x50 0xa6 0x02 0x2f 0x6c 0x66 0xfc 0xbe 0x4b 0x29 0xb0 0x0d 0xe1 0x65 0x87 0xfe 0x8b 0x88 0x59 0x8d 0x22 0xfc 0x67 0xe2 0xe3 0x96 0x99 0xe5 0xab 0x2f 0xa4 0x15 0x22 0x37 0x57 0x02 0x01 0x11 0x02 0x82 0x01 0x00 0x0b 0xec 0x3a 0x8e 0xda 0xce 0xc7 0xf8 0x70 0x5c 0x78 0xb5 0x24 0xd7 0xfb 0xc0 0x24 0x97 0xf4 0x81 0xde 0x8d 0x17 0xc3 0x2a 0x75 0x5a 0x6b 0x6b 0xca 0xb7 0x45 0x4c 0xdb 0xfc 0xe5 0xd1 0xf0 0x7f 0x1e 0x49 0x1e 0x22 0x2c 0x3c 0x60 0x06 0xcf 0x39 0xea 0x92 0x1d 0xcd 0xff 0x6a 0x38 0x6b 0x04 0xe1 0x9c 0x22 0x8b 0x22 0xa4 0x32 0x85 0x32 0xc7 0x9e 0xc4 0xb5 0xfa 0xbf 0x22 0x2d 0x16 0xe4 0xb4 0xb8 0xf1 0xe9 0x7e 0x7d 0x54 0xf1 0xba 0x08 0x76 0x28 0x68 0x86 0x74 0xe8 0xe1 0xf7 0xb8 0xdf 0x8a 0x31 0xb3 0x97 0xfb 0xf2 0x0e 0x06 0x41 0x72 0x67 0xf7 0xe5 0x06 0x0a 0x8c 0xf2 0xf7 0xba 0x70 0xe6 0x24 0x42 0x5b 0xd9 0x43 0xaa 0xee 0x07 0x78 0x25 0xb9 0x18 0xba 0x11 0x92 0xa8 0x0c 0xe8 0x89 0xd9 0x3c 0xc7 0x4e 0xf8 0x16 0x0b 0x6c 0xa1 0x2e 0x39 0x1c 0x8b 0xed 0xd9 0x11 0xe7 0xed 0x2a 0x1a 0x31 0x25 0x25 0x8d 0xd5 0x3a 0x9b 0x3c 0x29 0x9e 0xb0 0x51 0x98 0x6f 0x25 0x8d 0xbc 0x9a 0x55 0x96 0x51 0x15 0x1f 0x1c 0x91 0x5c 0x25 0x55 0xd3 0x24 0xda 0xb5 0xd0 0xfa 0xaa 0x1c 0x60 0x62 0x0a 0x2d 0xa9 0x83 0x78 0xdd 0xdf 0x5d 0x71 0x13 0xf1 0x22 0x15 0x13 0x6c 0x04 0x6c 0x9a 0xe4 0x4a 0xb9 0x4c 0xaf 0xc7 0xd6 0xf6 0x11 0x6c 0x4a 0x9c 0x5b 0x65 0x78 0x6e 0xa3 0x0a 0xff 0xfb 0xda 0x41 0xa6 0x15 0x6b 0x86 0xde 0x77 0xff 0xc2 0x13 0x50 0xd8 0x91 0x3e 0xd2 0xf0 0xb1 0xc3 0x43 0x51 0x0b 0xcd 0x02 0x81 0x81 0x00 0xb6 0x40 0x45 0x5c 0xb8 0x4d 0x50 0x48 0xb7 0x0d 0xa0 0x26 0x03 0xe3 0xfa 0x3c 0x2f 0x04 0x9e 0x72 0x1f 0x1d 0x30 0xec 0xea 0xf4 0xce 0x62 0xe6 0xe0 0xe7 0x3d 0x3d 0x03 0x68 0x3a 0x90 0xe0 0xe3 0xb0 0x29 0x15 0x26 0x69 0xde 0xbb 0x6e 0x1a 0xc2 0x5f 0x5d 0xb7 0x2b 0x27 0x61 0x49 0x98 0x94 0x27 0x40 0x05 0x67 0xf3 0xc1 0x77 0x5b 0x12 0x6d 0x8d 0x75 0xfa 0x13 0x4d 0x26 0x14 0x29 0x06 0x43 0xf8 0x3d 0xb9 0x9f 0x10 0x5e 0xf9 0x30 0x79 0xf9 0x1b 0x7d 0x6a 0x66 0x9f 0xaa 0x88 0x9f 0x5e 0x72 0xd4 0x3e 0xe0 0xc0 0x04 0xc2 0xb2 0xd2 0xdf 0x50 0xab 0x80 0xb9 0x5b 0xf8 0x23 0x7d 0x36 0xbd 0x6f 0xb2 0xfc 0xf3 0x1f 0x14 0xb9 0xc7 0xe9 0xaa 0x25 0x02 0x81 0x81 0x00 0xbd 0xcd 0xbf 0x79 0xd6 0x09 0x98 0xfa 0xa2 0x7a 0x93 0x65 0x5f 0xda 0x40 0x42 0xfb 0x79 0x23 0x0b 0xba 0xcc 0x35 0xa6 0x67 0xfb 0x4f 0xcf 0x94 0x75 0xc8 0x30 0xda 0x1c 0x69 0x1d 0x87 0x1f 0x35 0xf7 0x70 0x00 0xf6 0x50 0xd9 0x3c 0xc7 0x57 0x25 0xa6 0xd6 0x04 0x87 0x99 0x4c 0x16 0xed 0x41 0x77 0x5d 0x81 0xdd 0x3a 0x83 0xd3 0x89 0xb5 0xb7 0x99 0xb8 0x94 0x77 0x48 0x3d 0xab 0xeb 0xc6 0x19 0xae 0xf4 0x7a 0x25 0x22 0xad 0xd0 0xb5 0x77 0x4a 0xba 0xf0 0xa1 0x83 0xe2 0x35 0xfc 0xbf 0xe4 0xed 0xbf 0x68 0xf7 0xa8 0xa8 0x42 0xdf 0x64 0xf3 0x87 0xb5 0x9d 0x81 0x24 0x45 0x02 0x3d 0x00 0xe6 0x88 0x20 0x2a 0x46 0x8e 0xe6 0xef 0xfc 0xf7 0x5c 0xcb 0x02 0x81 0x81 0x00 0xab 0x87 0xc8 0xcf 0xbc 0x85 0x00 0x44 0x70 0x0c 0xd2 0xf6 0x9a 0x3f 0xfa 0x92 0xff 0x13 0x67 0xf2 0xf0 0x1b 0x79 0x57 0x73 0xb9 0x3a 0xb7 0x6f 0xe2 0xbb 0x84 0xee 0x21 0x53 0x09 0xf1 0xc4 0x9a 0x0f 0x35 0xb9 0x8d 0x90 0xd1 0xa1 0x58 0x91 0xa7 0xe1 0x49 0x24 0xdd 0x52 0x3d 0x72 0x71 0x7c 0x61 0x2d 0x32 0x43 0xb8 0x3d 0x9d 0x82 0xe4 0x2a 0xdf 0x7e 0x18 0x8a 0xa2 0xf6 0xa9 0x90 0x05 0xe5 0x9e 0x58 0x36 0x3b 0x5a 0xb3 0xbd 0x5a 0xcd 0x26 0xb0 0x76 0x09 0xc9 0xff 0xaf 0x8f 0xa5 0x0d 0x99 0x40 0x3b 0x2d 0xe1 0xe6 0x5c 0xe4 0x8a 0x3b 0x97 0x38 0x00 0xae 0x74 0xad 0x4e 0x93 0xf7 0x48 0xe1 0x99 0x66 0x8a 0x77 0x9b 0x09 0x34 0x9f 0xaf 0x31 0x02 0x81 0x80 0x6f 0xa6 0x34 0x65 0xc9 0x32 0xd2 0x75 0x50 0x84 0x56 0xb4 0x1a 0x44 0x25 0xcd 0x0c 0x65 0x5f 0xe8 0xc8 0x3b 0xe3 0x52 0xd3 0xc1 0x01 0xc5 0x66 0x63 0x66 0xb3 0x53 0x1f 0xc5 0x5c 0xa9 0xd6 0x1f 0xbe 0xba 0x5a 0xeb 0x3e 0x9d 0xe7 0x84 0x51 0x61 0x71 0x32 0x99 0x40 0xb4 0x87 0x1c 0x8b 0x8f 0xeb 0xdc 0xa6 0xbe 0x5e 0xa7 0xe5 0xd8 0x89 0x02 0x96 0xa8 0xcf 0xcd 0xb2 0x06 0x28 0xe5 0x0b 0x1e 0x2a 0xad 0xed 0x7f 0x41 0x93 0x6b 0xb6 0x09 0xef 0xb9 0x42 0x40 0xe4 0x2a 0xb6 0x58 0x70 0xe1 0x04 0x52 0x79 0xfb 0x17 0xea 0x81 0xb0 0x95 0xbc 0x6d 0xf2 0x5c 0xa6 0x51 0x92 0x01 0x51 0x0f 0x96 0xaa 0x6d 0x46 0x0b 0x63 0x1e 0x6f 0x0d 0x46 0x36 0x95 0x02 0x81 0x80 0x41 0x3e 0xa8 0x3b 0x77 0xdc 0xd7 0xab 0x2d 0xd8 0x82 0x96 0x1c 0x1b 0x3b 0xc6 0x85 0x92 0x88 0xac 0xc8 0xac 0x9f 0x18 0x74 0x9d 0x45 0xb4 0x7b 0x13 0xab 0x78 0x8d 0x8b 0xb5 0x9e 0x9e 0xd2 0xd7 0xf2 0x84 0x34 0xfb 0x08 0xb2 0x23 0xc7 0x0b 0xf0 0xa9 0xca 0x17 0x1a 0xa2 0x6d 0x63 0xd3 0x90 0xef 0xd1 0x62 0xe6 0x46 0x25 0x6d 0x6d 0x23 0x3b 0xb0 0x65 0xea 0xe2 0x22 0x24 0xc9 0x09 0x1b 0x0d 0x42 0x9d 0x77 0xe1 0x63 0xb2 0x03 0x0d 0x4a 0xa2 0xfd 0x2e 0x2d 0xcd 0x4b 0x9e 0x63 0x91 0x0f 0x42 0xc2 0x01 0x24 0x68 0x4c 0xb5 0xa8 0x35 0xe3 0x31 0xe8 0x86 0x32 0xb1 0xa9 0x4f 0xbe 0x23 0x3a 0x3c 0x0a 0x5d 0x26 0xbe 0xa7 0x5d 0xc0 0x60 0x42 0x1d for int i 0 isizeofszprivatekey i cout szprivatekeyi endl return 0,['c++'] +502445,replace the top fragment on the back stack i am having so much trouble with android fragments suppose my back stack looks like thiscbapressing the back button would pop fragment c off and leaving fragment b on the top of the stack now how do i swap fragment c for fragment d while maintaining the back stack note fragment b cannot be seen during the operationc d db ba a this way pressing the back button would pop fragment d off and leaving fragment b on top fragment c is completely removed off the stacki add each fragments to the stack like sofragmenttransaction ft managerbegintransactionftreplaceid instance gettaginstanceftaddtobackstackgettaginstanceftcommiti thought this could be achieved by doing the same calls without addtobackstack but it just made fragment d and fragment b overlapped,['android'] +502472,what is the difference between block and inlineblock with width 100 i have recently been trying to figure out when it is appropriate to use inlineblocks they seem to be far more useful than just a block element in fact an inlineblock element seems to be able to do anything a block element can do but with a little extra stylingis there any reason an element with thisplay inlineblock width 100 is any different than an element with thisplay block aside from the fact that one is longeri have been researching this topic by reading the w3c recommendation i cannot seem to find a difference,['css'] +502492,call objectprototype method on global scope this code throws an errortry alerthasownpropertywindow catche alerte type error cannot convert undefined to objectbut this code does not throws an errortry alertthishasownpropertywindow true if on browser catche through catch block alertelive example live sourceas far as i kwon funcarg is equal to thisfuncarg if this is global object why does such a thing happen,['javascript'] +502517,jfreechart customize piechart to show absolute values and percentages how can this compilable minimal code snippet example which uses jfreechart as plotting api adapted in order to show both absoulte values and percentagesi could not extract this information neither from any code snippet on the internet nor from the jfreechart manual itself the code snippet produces a pie chart showing only percentages the absolute values in my case also matter so i need to thisplay them right under the percentageshere is the code note it lacks the importspublic class myminimalpiechartexample public static void mainstring args defaultpiedataset dataset new defaultpiedataset datasetsetvaluesome data 199 datasetsetvaluesome data 2 77 third adaption jfreechart somechart chartfactorycreatepiechart some chart header dataset true true false pieplot illegallegalrestpieplot4 pieplot somechartgetplot illegallegalrestpieplot4setsectionpaintsome data 1 new color0 255 0 illegallegalrestpieplot4setsectionpaintsome data 2 new color255 0 0 pieplot plot4 pieplot somechartgetplot plot4setexplodepercentsome data 1 04 plot4setsimplelabelstrue piesectionlabelgenerator generator new standardpiesectionlabelgenerator 0 2 new decimalformat0 new decimalformat0 plot4setlabelgeneratorgenerator try chartutilitiessavechartasjpegnew filecmyminimalpiechartexamplejpeg somechart 1200 10 catch exception e systemerrprintlncould not write chart,['java'] +502520,how can i find out what foreign key constraint references a table in sql server i am trying to drop a table but getting the following messagemsg 3726 level 16 state 1 line 3 could not drop object dbouserprofile because it is referenced by a foreign key constraint msg 2714 level 16 state 6 line 2 there is already an object named userprofile in the databasei looked around with sql server management studio but i am unable to find the constraint how can i find out the foreign key constraints,['sql'] +502521,had to load data twice to make webview refresh in android when i first create the activity everything goes fine however after i choose from menu to change some text of the string values and set the webview by webviewloaddataresult texthtml charsetutf8 nullwebviewloaddataresult texthtml charsetutf8 nulli have to do it twice or the webview will keep unchanged is there anyone knows what happens here since the result string is the same why webview force me to loaddata twice,['android'] +502609,printing reciepts with thermal printer in java i have to print receipts through a thermal printer using java i have done everything my program takes the data from the database and converts in one string using special characters tabs and n then the string is passed on to another method that converts it into graphicsthe problem is that when i click the print button white paper comes out i noticed that the first 45 characters of my string are getting printed on the last line of the bill on the right corner at the extreme end of the paper my printer is epson tm t81 public void printthisbill defaulttablemodel mod defaulttablemodel jtable1getmodel dateformat dateformat new simpledateformatddmmy dateformat timeformat new simpledateformathhmm get current date time with date date date new date date time new date string date dateformatformatdate string time timeformatformattime string header super market n date date time timen n name qty rate amtn n string amt n and ntotal amount amt n tax tax n n thank you n string bill header int i 0 do string name modgetvalueati 2 string qty modgetvalueati 3 string rate modgetvalueati 4 string amount modgetvalueati 6 ifnamelength 12 name namesubstring0 12 else forint j namelength12 j namelength j name name ifqtylength5 forint j 0 j qtylength5 j qty qty rate rate string items nametqtytratetamountn bill bill items i whilei modgetrowcount1 bill billamt systemoutprintlnbill printcardbill thispose and the method that prints the bill ispublic static void printcardfinal string bill printable contenttoprint new printable override public int printgraphics graphics pageformat pageformat int page throws printerexception if page 0 return no such page pageformatsetorientationpageformatlandscape graphics2d g2d graphics2dgraphicscreate g2dsetpaintcolorblack g2dsetfontnew fontarial fontbold 10 g2dtranslatepageformatgetimageablex pageformatgetimageablex g2ddrawstringbill 0 0 return page exists printerjob job printerjobgetprinterjob jobsetprintablecontenttoprint you can show a print dialog before printing by job by wrapping the following blocks with a conditional statement ifjobprintdialog try jobprint catch printerexception e systemerrprintlnegetmessage what is the problem and how can i solve it i think that i am not setting the right parameters at drawstring methodor is it something else any help would me appreciated,['java'] +502618,creating a java program that locks file how do i lock a file so that a user can only unlock it using my java program import javaniochannelsimport javaiopublic class filelock public static void mainstring args filelock lock null filechannel fchannel null try file file new filecusersgreendesktoplocktxt fchannel new randomaccessfilefile rwgetchannel lock fchannellock catch exception e this is my sample code it does not give me what i want i want it to deny one access to read or to write the file until i use my java program to unlock it,['java'] +502634,how do i close a searchview programmatically i currently have a searchview in the action bar of my app when i click the search icon the searchview expands and the keyboard pops up as expected clicking the x in the searchview box closes the searchview as expected however when the searchview is activated and i press the back button my app is exited this is the correct behavior but what i am trying to do now is to capture back button press and just have it close the searchview not my app when the searchview is visible is there a way to invoke the searchview oncloselistener programmatically on a back button press for example something like this on a back button press if we are currently searching close the searchview otherwise invoke normal back button behaviorpublic boolean onkeydownint keycode keyevent event if keycode keyeventkeycode back if issearchviewvisible searchview searchview searchview menufinditemridsearchbox getactionview this method does not exist searchviewinvokeclose return true return superonkeydownkeycode event,['android'] +502650,whats the difference between java web application and java enterprise application i have been doing some research about the difference between java web application and enterprise application and what i have found is that they have little bit similar architecture for example enterprise application have client presentation business logic and data tier client tier can be java clients browserbased clients and mobile clientspresentation tier can be javabeans components servlets portals and jsp componentsin business logic tier you can have servers web services soap restful and others and mdb componentsin data tier you can have dbms ldap and data feednow if we compare those components to web application you can use them without creating java enterprise application for example i can use many different technologies to implement my web application such as hibernate maven jsp or jsf databases servlets javabeans and etcmy biggest question is what is the major difference between java enterprise application and web application why i would use java enterprise application,['java'] +502696,jquery image changing on hover okay so i have dynamically generated images via php so not necessarily the same images result and i have spent the last four hours scanning the internet and trying countless things with jquery andor css and i have come up with the following that works a hrefbuildphpx1875y2020img stylebackgroundurlimagestile 4jpg srcimagestile 4jpg onmouseoverthissrcimagesmarketpng onmouseoutthissrcimagestile 4jpg aa hrefbuildphpx1876y2020img stylebackgroundurlimagestile 4jpg srcimagestile 4jpg onmouseoverthissrcimagesmarketpng onmouseoutthissrcimagestile 4jpg aa hrefbuildphpx1877y2020img stylebackgroundurlimagestile 4jpg srcimagestile 4jpg onmouseoverthissrcimagesmarketpng onmouseoutthissrcimagestile 4jpg aa hrefbuildphpx1878y2020img stylebackgroundurlimagestile 4jpg srcimagestile 4jpg onmouseoverthissrcimagesmarketpng onmouseoutthissrcimagestile 4jpg aa hrefbuildphpx1879y2020img stylebackgroundurlimagestile 4jpg srcimagestile 4jpg onmouseoverthissrcimagesmarketpng onmouseoutthissrcimagestile 4jpg amarketpng has a transparent backgroundnow the above works on mouseover it thisplays marketpng with the transparent background part being tile 4jpg and out mouseout it is tile 4jpgwhat i want to know is there any way to accomplish the exact same thing as the above with jquery or css i have not figured it out and i have spent hours trying but i would rather do something else if at all possible since the above with massive repetition the above format is repeated currently around 100 times but i have plans to expand it to over a 10 times will become a bandwidth hog,"['javascript', 'jquery', 'html', 'css']" +502723,is it safe to access a variable from the main thread after it was written to by another thread and after that thread was joined is this threadsafeint x 0stdthread x 1 joinstdcout xvariable x is accessed from two threads without using atomics or locks however the call to join forces the accesses to x to be sequentialis a memory barrier required here,['c++'] +502780,sql server 2012 32bit or 64bit on 64bit machine i am about to install sql server 2012 developer on my 64bit machine for developing purposes but i am not sure if i should install the 32bit or 64bit version my confusion comes from the fact that my visual studio 2012 is 32bit and my laptop is not quite fast intel core2duo p8400 226ghz with 5gb ramgenerally speaking 64bit or 32bit app installation on 64bit machine is the right choice,['sql'] +502798,how can i add items to an empty set in python i have the following proceduredef myprocinvindex keyword d for i in rangelenkeyword if keywordi in invindexkeys dupdateinvindexqueryi return dbut i am getting the following errortraceback most recent call last file stdin line 3 in moduletypeerror cannot convert dictionary update sequence element 0 to a sequencei do not get any error if d contains elements but i need d to be empty at the beginning,['python'] +502859,how to work within individual files rather than projects in pycharm relatively new to python and pycharm and as such most of the work i am doing is single files and therefore is not organized into projectsis there a way to configure pycharm to be used to open single files and not use projectsand equally just run a single pagefile,['python'] +502869,how to hide swt composite so that it takes no space i need to hide a composite and all children inside just setting setvisiblefalse will keep the space of the compositecomposite outer new compositeparent swtnone outersetlayoutnew gridlayout1falseoutersetlayoutdatanew griddatagriddatafill both composite comptohide new mycompositeouter swtnone comptohidesetlayoutnew gridlayoutcomptohidesetvisiblefalse,['java'] +502941,how to make this simple dialog fragment semitransparent i am trying to make this simple dialog semitransparentclass testdialog extends sherlockdialogfragment public testdialog super override public dialog oncreatedialogbundle savedinstancestatebundle alertdialogbuilder builder1 new alertdialogbuildergetactivity get the layout inflater layoutinflater inflater1 getactivitygetlayoutinflater inflate and set the layout for the dialog pass null as the parent view because its going in the dialog layout builder1setviewinflater1inflaterlayoutdlg test null add action buttons setpositivebutton ok new dialoginterfaceonclicklistener override public void onclickdialoginterface dialog int id sign in the user setnegativebutton cancel new dialoginterfaceonclicklistener override public void onclickdialoginterface dialog int id return builder1create the layout is the followinglinearlayout xmlnsandroid androidididtest androidlayout widthwrap content androidlayout heightwrap content androidorientationvertical textview androidididusername androidlayout widthmatch parent androidlayout heightwrap content androidlayout margintop16dp androidlayout marginleft4dp androidlayout marginright4dp androidlayout marginbottom4dp androidhintuser name linearlayouti have tried everything from using a transparent png as the background drawable of the linear layout to setting the alpha field to 05 to using as a drawable a color equal to 0 i am not able to make that dialog semitransparent i do not know even if it is possiblewhat i would like to create is a dialog like the panel in the following image thanksnote1 the min sdk required is version 8 the target is the latest actually v17,['android'] +502960,does compiling an empty file follow the c standard there was an entry in the 1994 obfuscated c contest that qualified as the smallest quine it was just an empty fileis there something in the c spec that allows for compiling empty files if not what is the bare minimum for a valid program i vaguely remember reading somewhere that there was a special case where an empty file is given a default implementation in the c spec but i cannot find the reference i tried this though i do not know that it is necessarily convincing rm main emptycpprm cannot remove main emptycpp no such file or directory touch main emptycpp g o empty main emptycppusrlibgccx86 64linuxgnucrt1o in function starttext0x20 undefined reference to maincollect2 error ld returned 1 exit statuswith a little coddling you can get around the missing main g wldefsym start exit wlundefined exit nostartfiles static o empty main emptycppupdateit was noted that the main emptycpp was redundant if you remove it from the command it compiles the samei added some static junk to the main emptycpp to see if it manifested in different behavior and it did not it did change the executable size howeverinclude iostreamstruct foo foo stdcout hi stdendl fooif you add a main to the file and compile as normal it will output as youd expect with typical static loading,['c++'] +502981,how to format a decimal without trailing zeros i have just learned that a decimal somehow remembers how much trailaing zeros were needed to store a number with other words it remembers the size of the fractionfor example 123mtostring resuls in 12312300mtostring resuls in 12300123450mtostring resuls in 123450i am looking for a formatting string or another tric to get rid of those unneeded trailing zeros but keeping the significant digits so123mtostring resuls in 12312300mtostring resuls in 123123450mtostring resuls in 12345removing the zeros at the end of the new string is not a real option for me because then i have to find out if the string contains a fraction and if so also have to remove the optional or depending on the culture etc,['c#'] +502993,how to assign a domain name to nodejs server i have a nodeja server listining to port 40 the url to access the service is something like thisi bought a domain namewmychatcomhow can i assign it to my server first i used forwarding but then i could not use locationhash anymore to add a chat channel to the url then i used something like headerredirect now the service is reachable under mychatcom but not under wmychatcom moreover the domain name is not shown in the browser window for my chat channel i need something like thiswmychatcom238husd4,['javascript'] +502997,how to create an instance of anonymous class of abstract class in kotlin assume that keyadapter is an abstract class with several methods that can be overriddenin java i can dokeylistener keylistener new keyadapter override public void keypressedkeyevent keyevent how to do the same in kotlin,['java'] +503016,mailto links do nothing in chrome but work in firefox it seems like the mailto links were embedding in our website fail to do anything in chrome though they work in firefoxsimple example here a hrefmailtohi this is a testado we need to do something special to enable mail links in chrome,['html'] +503063,gemfilelock write error permissions i created a rails model model a while ago and now i am trying to run the server after a bundle install i get there was an error while trying to write to gemfilelock it is likely that you need to allow write permissions for the file at path homethiagomodelgemfilelocktried rails s to see what happens andhomethiagorvmgemsruby193p429gemsbundler135libbundlerdefinitionrb235in rescue in lock there was an error while trying to write to gemfilelock it is likely that bundlerinstallerroryou need to allow write permissions for the file at path homethiagomodelgemfilelock from homethiagorvmgemsruby193p429gemsbundler135libbundlerdefinitionrb220in lock from homethiagorvmgemsruby193p429gemsbundler135libbundlerenvironmentrb34in lock from homethiagorvmgemsruby193p429gemsbundler135libbundlerruntimerb43in setup from homethiagorvmgemsruby193p429gemsbundler135libbundlerrb120in setup from homethiagorvmgemsruby193p429globalgemsrubygemsbundler1librubygemsbundlernoexecrb79in setup from homethiagorvmgemsruby193p429globalgemsrubygemsbundler1librubygemsbundlernoexecrb91in from homethiagorvmrubiesruby193p429librubysite ruby191rubygemscore extkernel requirerb110in require from homethiagorvmrubiesruby193p429librubysite ruby191rubygemscore extkernel requirerb110in rescue in require from homethiagorvmrubiesruby193p429librubysite ruby191rubygemscore extkernel requirerb35in require from homethiagorvmgemsruby193p429binruby noexec wrapper9in can i set the permissions for the gemfilelock so i can bundle and run server ls a ltotal 80drwxrxrx 13 root root 4096 may 19 1408 drwx 41 thiago thiago 4096 jul 7 2351 drwxrxrx 8 root root 4096 may 19 1408 appdrwxrxrx 5 root root 4096 may 19 1408 configrwrr 1 root root 155 may 19 1408 configrudrwxrxrx 2 root root 4096 may 19 1408 dbdrwxrxrx 2 root root 4096 may 19 1408 docrwrr 1 root root 765 may 19 1408 gemfilerwrr 1 root root 430 may 19 1408 gitignoredrwxrxrx 4 root root 4096 may 19 1408 libdrwxrxrx 2 root root 4096 may 19 1408 logdrwxrxrx 2 root root 4096 may 19 1408 publicrwrr 1 root root 270 may 19 1408 rakefilerwrr 1 root root 9208 may 19 1408 readmerdocdrwxrxrx 2 root root 4096 may 19 1408 scriptdrwxrxrx 7 root root 4096 may 19 1408 testdrwxrxrx 3 root root 4096 may 19 1408 tmpdrwxrxrx 4 root root 4096 may 19 1408 vendormodel files created incorrectly,['ruby'] +503104,list view item swipe left and swipe right can a list view item respond to swipe left and swipe rightif so how to apply android swipe left or right scrolling to open different intent i want same like call phone or message on contact view in android by defaultthanks,['android'] +503113,how to optimize cc code for a large number of integers i have written the below mentioned code the code checks the first bit of every byte if the first bit of every byte of is equal to 0 then it concatenates this value with the previous byte and stores it in a different variable var1 here pos points to bytes of an integer an integer in my implementation is uint64 t and can occupy upto 8 bytesuint64 t funcchar data uint64 t var1 0 int i0 while datai 7 0 variable variable 7 datai i return variable since i am repeatedly calling func a trillion times for trillions of integers therefore it runs slow is there a way by which i may optimize this codeedit thanks to joe zits indeed a form of uleb128 unpacking,"['c++', 'c']" +503161,does java fail to deduce the generic type parameter when using the ternary operator why is the compiler able to determine the generic type parameter for anassignment but not for the ternary operator i have a question regarding the compiler being able to deduce the generic typeparameter in case of a direct assignment but failing in case of the ternaryoperator my examples uses guavas optional class to make my point buti think the underlying issue is generic and not restricted to optionaloptional has a generic function absentpublic static t optionalt absentand i can assign an optionalt to an optionaldouble no compiler errorfinal optionaldouble o1 optionalabsenthow does the compiler realize that t should be double in this case becausewhen using the ternary operator i need to tell the compiler specificallyto us integer as the generic parameter type mismatch cannot convert from optionalcapture1of extends object to optionalintegerfinal optionalinteger o2 true optionalof42 optionalintegerabsentotherwise i get the following errortype mismatch cannot convert from optionalcapture1of extends object to optionalintegerwhy is there a difference between a direct assignement and using the ternaryoperator or is there something else i am missing,['java'] +503167,percentage transformorigin for svg not obeyed in firefox only sometimes in webkit i have this ice cream cone svg graphic and i want to transform the scoop with a transformorigin of 50 100 center bottom firefox claims to obey ie the inspector notes the correct transformorigin but in fact transforms about the upper left corner webkit bizarrely will only obey if a parent element has fontsize100 setthese are very similar questions but only pertain to firefoxsetting transformorigin on svg group not working in firefoxhow to set transform origin in svgtransform origin not working in firefox,['css'] +503242,strange string pool behavior i have got a question of some strange string pool behaviori am using to compare equal strings to find out whether they are in the pool or notpublic class stringpooltest public static void mainstring args new stringpooltestrun string giveliteralstring return 5 void run string s1 giveliteralstring systemoutprintln5 5 systemoutprintlngiveliteralstring giveliteralstring the output istruefalsewhich is a big surprise for me could anyone explain this pleasei think something about this is taking place at the compilation time but why does adding to a string makes any difference at all,['java'] +503249,object vs class vs function i was wondering whats the difference between javascript objects classes and functionsam i right in thinking that classes and functions are types of objectsand what thistinguishes a class from a function or are they really the same thing just the term for them changes according to how they are usedfunction func alertfoo a functionfunc call the function alerts foovar func2 function alerthello acts the same way as func surelyfunc2 alerts hellovar class function alertbar a classvar c new class an istance of a class alerts barsure classes have methods and properties and can be instantiated but then i could do the same with any old function or not,['javascript'] +503258,php fatal error cannot inherit abstract function i do not understand what i am doing wrongabstract class css abstract protected function parsedataabstract class csselem extends css abstract protected function parsedataclass modifier extends csselem function constructdata null if data thisparse data protected function parsedata some code it gives me mon jul 8 132110 2013 php fatal error cannot inherit abstract function cssparse previously declared abstract in csselem in homearthurnetbeansprojectscapacsselemphp on line 21 mon jul 8 132110 2013 12700141207 500 cannot inherit abstract function cssparse previously declared abstract in csselem in homearthurnetbeansprojectscapacsselemphp on line 21line 21 is abstract protected function parsedata in csselemi am more familiar with oop in java but it seems ok according to the doc,['php'] +503287,position relative not working with thisplay tablecell i have created a horizontal menu composed of buttons i need these buttons to resize in width so that together they occupy 100 of the width of the menu container it should act the same way a td does inside a tableas such heres the code i came up with div idmenubar div idmenu div classbutton buttonbutton 1button div div classbutton buttonbutton 2button div div classbutton buttonbutton 3button div div classbutton buttonbutton 4button div divdivand my cssmenubar width 100 height 100 thisplay table tablelayout fixedmenu thisplay tablerowmenu button position relative thisplay tablecellmenu button button position absolute right 0px bottom 0px top 0px left 0pxthis works perfectly in every browser except mozilla mozilla does not seem to respect the relative position of the button class and as such the buttons all get positioned absolutely one of top of each other instead of absolutely inside the div with class buttonafter some further research it seems this is a known issue with mozilla not respective position relative when thisplay is set to tablecelldoes anyone know a work around to achieve what i am looking to donote the menu is dynamic so i do not know how many buttons there will be so i cannot provide percentage widths for each button,"['html', 'css']" +503320,create bitmap from specified screen area i am trying to create a bitmap from a specific area on the screen for example in the following image how could i capture the windowed area below and convert it into a bitmapi know you can use setdrawingcacheenabledtrue but that captures the whole view when all i want is an area within the view,['android'] +503327,how does trello access the users clipboard when you hover over a card in trello and press ctrlc the url of this card is copied to the clipboard how do they do thisas far as i can tell there is no flash movie involved i have got flashblock installed and the firefox network tab shows no flash movie loaded that is the usual method for example by zeroclipboardhow do they achieve this magicright at this moment i think i had an epiphany you cannot select text on the page so i assume they have an invisible element where they create a text selection via javascript code and ctrlc triggers the browsers default behaviour copying that invisible nodes text value,['javascript'] +503518,is it possible to use a range as a key for a hash in ruby i am trying to create a script to go through an index look at each page number and tell me what chapter of the book that entry is in heres an approximation of what i am doingchapters 1 introductionxhtml 25 chapter1xhtml 610 chapter2xhtml 18 chapter3xhtml 1930 chapter4xhtml def find chapternumber chapterseach do page range chapter name if number page range puts a href chapter name page numberto s numberto s a end endendfind chapter1 will spit out the string i want but find chapter15 does not return anything is it not possible to use a range as a key like this,['ruby'] +503549,where can i find a list of jshint numeric error codes i am using jshint for visual studio it is not uncommon for jshint to issue a warning about an issue that i know it safe to ignore i have been putting ignore jslint on the relevant line but i see that we can also ignore specific error codes from the 100 rc1 release notesthis version adds a unique numeric code to every warning and error message produced by jshint that means that you can now ignore any warning produced by jshint even when there is no corresponding option for it you can do that using the special minus operator for example hereas how you ignore all messages about trailing decimal points w047jshint w047 seems cool but try as i might i cannot find a list of all the error codes visual studios warning list does not provide you with the numeric error code just the error textsurely this list is out there somewhere right i have literally spent an hour googling for this but no success so far,['javascript'] +503568,ann recursive backpropagation i am trying to implement backpropagation with recursion for academic purposes but it seems i have gone wrong somewhere have been tinkering with it for a while now but either get no learning at all or no learning on the second patternplease let me know where i have gone wrong this is javascript syntaxnote errors are reset to null before every learning cyclethisbackpropagate functionoann atargetoutput nlearningrate nlearningrate nlearningrate 1 var onode and 0 for snodeid in oanngetoutputgroupgetnodes onode oanngetoutputgroupgetnodessnodeid onodeseterroratargetoutputn onodegetoutputvalue and for snodeid in oanngetinputgroupgetnodes thisbackpropagatenodeoanngetinputgroupgetnodessnodeid nlearningrate thisbackpropagatenode functiononode nlearningrate var nerror onodegeterror ooutputnodes oconn nweight noutputerror nderivative onodegetoutputvalue 1 onodegetoutputvalue derivative for sigmoid activation funciton ninputvalue onodegetinputvalue n if nerror null dont do the same node twice onodehasoutputs nderivative nderivative 01 ninputvalue ninputvalue 01 ooutputnodes onodegetoutputnodes for n0 nooutputnodeslength n noutputerror thisbackpropagatenodeooutputnodesn nlearningrate oconn oanngetconnectiononode ooutputnodesn nweight oconngetweight oconnsetweightnweight nlearningrate noutputerror nderivative ninputvalue nerror noutputerror nweight onodeseterrornerror return onodegeterror,['javascript'] +503591,reading and writing to the same file using the same fstream i have a file that already contains some data say 8 kb i want to read something from the beginning of the file and then overwrite data starting where i finished reading so i try to use the following codestdfstream streamfilename stdiosin stdiosout stdiosbinarychar bytestreamreadbyte 1 streamseekp1int bytescount 4096auto bytesvec stdvectorcharbytescount cchar bytes bytesvecdatastdcout streambad stdendlstreamwritebytes bytescountstdcout streambad stdendlif i execute this code the first bad returns false but the second one returns true and nothing actually gets writtenif i decrease bytescount to anything smaller than 4096 presumably the size of some internal buffer the second bad returns false but still nothing gets writtenif i uncomment the seekp line the writing starts working bad returns false and the bytes actually get writtenwhy is the seekp necessary here why does not it work without it is the seekp the right way to do thisi am using visual studio 2012 on windows 7,['c++'] +503616,how to install a package using the pythonapt api i am quite a newbie when it comes to python thus i beg foregiveness beforehand that said i am trying to make a script that among other things installs some linux packages first i tried to use subopen as explained here while this can eventually work i stumbled upon the pythonapt api and since i am not a big fan or reinventing the wheel i decided to give a tryproblem comes when trying to find examplestutorials on installing a package using pythonapt searching the documentation i found the packagemanager class that has some methods to install a package i tried some simple code to get this workingapt pkgpackagemanagerinstallpythonthis does not seem to work that easily the install method expects apt pkgpackagemanager instead of a plain string thus looking a bit more i found this example that looks promising but i am a bit reluctant to use since i do not really understand some of what is happening there then has anyone tried to install a package using pythonapt or should i go for using plainold subopen stylethanks,['python'] +503651,sequence of gc and unloading assets in unity3d sometimes we need to release useless resources manually in game developmentbut i am not sure which is better betweensystemgccollectresourcesunloadunusedassetsandresourcesunloadunusedassetssystemgccollectafaik both of them are async operations and there might be no differenceso my question isare there any differenceif so which is better,['c#'] +503676,exceptionally slow javascript loop this is in a way a followup to my previous questioni created a jsperf which compares a number of ways to take a 1dimensional array of rgb pixel valuesvar rgb r g b r g band convert those into rgba values for an html5 canvas where the alpha channel is always 255 fully opaquevar rgba r g b 255 r g b 255in my tests i found that one of the loops i tested titled for loop is astronomically slower than the other loops where other loops were completing the operation hundreds of millions of times per second it weighed in at a whopping 86 times per second the loop can be found in the jsperf link above but heres a bit of code with for loop and 4unrolled skip alpha one of the faster loops in the testsetup for each testfunction newfilledarraylength val var array arraylength for var i 0 i length i arrayi val return arrayvar w 160 widthvar h 144 heightvar and 4 w h number of length of rgba arraysvar s 0 d 0 s is the source array index d is the destination array indexvar rgba filled newfilledarraywh4 255 an rgba array to be written to a canvas prefilled with 255s so writing to the alpha channel can be skippedvar rgb newfilledarraywh3 128 our source rgb array from an emulators internal framebuffer4unrolled skip alpha loop completes exits 185693068 times per secondwhile d n rgba filledd rgbs rgba filledd rgbs rgba filledd rgbs dfor loop loop completes exits 8587 times per secondfor var d 0 d n d rgba filledd rgbs rgba filledd rgbs rgba filledd rgbshow can it be so incredibly similar in syntax yet is so far removed in terms of performance,['javascript'] +503687,how to insert data into table using stored procedures in postgresql create table app for leave sno integer not null eid integer ename varchar20 sd date ed date sid integer status boolean default false constraint pk snoa primary key snobasic insertion is insert into app for leavesno eid sd ed sid status values110120130404201304042f insert into app for leavesno eid sd ed sid status values my requirement how to insert data into a table using stored procedures,['sql'] +503754,how to serialize only the id of a child with jackson is there a builtin way to only serialize the id of a child when using jackson fasterxmljackson 211 we want to send an order via rest which has a person reference the person object however is quite complex and we could refresh it on the server side so all we need is the primary keyor do i need a custom serializer for this or do i need to jsonignore all other properties would that prevent the person data from being sent back when requesting an order object i am not sure yet if i will need that but i would like to have control over it if possible,['java'] +503804,does a hidden input field have to be in a form i have a page where i need to store a value for processing via ajaxjquery i am using a hidden input field to store this value like thisinput typehidden name id value i can access this value through jquery even if it is not in a form ie it is just at the start of my html output question even though it works is it oklegal to do from a correctness perspective to have a hidden input value which is not part of a formgreetingsthanksr,"['jquery', 'html']" +503838,nsmanagedobject sayhello unrecognized selector sent to instance 0x i try to extend nsmanagedobjectusing xcode i created myboxm and myboxh directly from the xcdatamodel filethen i modified these filesimport foundationfoundationhimport coredatacoredatahinterface mybox nsmanagedobjectproperty nonatomic retain nsdate enddateproperty nonatomic retain nsnumber globalidproperty nonatomic retain nsstring nameproperty nonatomic retain nsdate startdatensstring sayhelloendandimport myboxhimplementation myboxdynamic enddatedynamic globaliddynamic namedynamic startdatensstring sayhello return hello endi can fetch all myboxesnsfetchrequest fetchrequest nsfetchrequest alloc init nsentitydescription entity nsentitydescription entityfornamemybox inmanagedobjectcontextcontext fetchrequest setentityentitynsmutablearray myboxes context executefetchrequestfetchrequest errorerrorbut later i callmybox mybox myboxes objectatindexindexpathrow mybox sayhelloit compiles but then i get terminating app due to uncaught exception nsinvalidargumentexception reason nsmanagedobject sayhello unrecognized selector sent to instance 0x8e73fc0if i only read a value likenslog myboxnameit worksi found similar problems here but no solutionthanks for your help,['objective-c'] +503894,create an arraylist of unique values i have in java an arraylist with those values many lines this is just an extract 20032013 233146 6870 6810 6800 6720 6860 6670 6700 6650 6750 6830 34864 34272 20032013 233146 6910 6780 6800 6720 6860 6680 6620 6690 6760 6790 35072 34496where the first two values are strings that containes data and are stored in a single elementwhat i want to do is comparing the string data elements and deleting for example the second one and all the elements referred to that linefor now i have used a for cycle that every 13 elements compares the string in order to compare only data stringsmy question can i implement other better solutionsthis is my codeimport javautilscannerimport javautillistimport javautilarraylistimport javaioimport javatextsimpledateformatimport javautildatepublic class downsampler public static void mainstring args throws exception the input file scanner s new scannernew fileprovatxt saving each element of the input file in an arraylist arrayliststring list new arrayliststring while shasnext listaddsnext sclose arraylist to save modified values arrayliststring ds new arrayliststring int i fori0 ilistsize13 ii14 combining the first to values to obtain data string str listgeti listgeti1 dsaddstr add all the other values to arraylist ds int j forj2 j14 j dsaddlistgetij comparing data values int k fork0 kdssize12 kk13 dsgetk first data string element comparing with other strings and delete todo,['java'] +503942,android nullpointerexception in instrumentationexecstartactivity i keep getting the bellow exception from some usersjavalangnullpointerexception at androidappinstrumentationexecstartactivityinstrumentationjava1414 at androidappactivitystartactivityforresultactivityjava2880 at androidsupportv4appfragmentactivitystartactivityforresultfragmentactivityjava817 at androidappactivitystartactivityactivityjava2986 at comgoogleandroidgmsinternalbb5onclickunknown source at androidviewviewperformclickviewjava2535 at androidviewviewperformclickrunviewjava9130 at androidoshandlerhandlecallbackhandlerjava618 at androidoshandlerthispatchmessagehandlerjava123 at androidoslooperloopsourcefile351 at androidappactivitythreadmainactivitythreadjava3826 at javalangreflectmethodinvokenativenative method at javalangreflectmethodinvokemethodjava538 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava969 at comandroidinternaloszygoteinitmainzygoteinitjava727 at dalviksystemnativestartmainnative methodi have found a similar problem here but it is not taken care of since april all i know is that it was reproduced on a samsung galaxy y gts5360 and i am using google maps android api v2do you have any idea how can i make a workaround for this,['android'] +503969,can you use an element inside a element i am in the process of improving accessibility in my html using html5 and waiariait is ok to have the following set up main content section idmain rolemain h1the main contenth1 this div needs to be here for styling reasons div classthecontent pall the text that goes with the main contentp div the sidebar aside idsidebar rolecomplementary h2a titleh2 psome textp asidesectionthe thing i am not sure of is if i should have the aside element outside of the section and the rolemain container does that matter,['html'] +503970,ios uibutton hidden does this automatically make the button thisabled i just have a knowledge question about uibuttons ios in generallet us say you have a uibutton you set the hidden property to yes this makes it no longer visible in view right but i noticed that while it is no longer visible it is also no longer clickable either so does this mean that setting hidden yes also sets enabled nojust curious thanks yall,['ios'] +503991,full width tabs using bootstrap support ie i am trying to adjust bootstrap tabs to make them span the full width of their container heres my code a minimal working exampledoctype htmlhtml langen head meta charsetutf8 titlefull width tabs using bootstraptitle link href relstylesheet style fullwidthtabs ulnavnavtabs thisplay table width 100 tablelayout fixed to make all columns equal width regardless of content fullwidthtabs ulnavnavtabs li float none thisplay tablecell fullwidthtabs ulnavnavtabs li a textalign center style head body div classtabbable fullwidthtabs ul classnav navtabs li classactivea hreftabone datatoggletabtab 1ali lia hreftabtwo datatoggletabtab 2ali ul div classtabcontent div classtabpane active idtabone i am in tab 1 div div classtabpane idtabtwo howdy i am in tab 2 howdy i am in tab 2 howdy i am in tab 2 howdy i am in tab 2 div div div tabbable script srcscript script srcscript bodyhtmli get this undesired resulthowever i want the tab headers to span the entire width of the tab container and thistribute their individual widths evenly something like this desired resulthow do i achieve thatupdate 1 heres a jsfiddle update 2 i already had a working widget using custom javascript however i am looking for a solution that integrates seemlessly with bootstrap and thus relies only on standard bootstrap javascriptupdate 3 if i remove comment out tablelayout fixed header widths are taking up all horizontal space as needed however their widths are resulting from the length of the header texts and thus not thistributed evenlythis is not what i want eitherupdate 4 the upcoming bootstrap 3 appears to have fullwidth tabs as a standard component using the class navjustified bootstrap 3 navs justified nav,"['html', 'css']" +504015,use different serializers for input and output from a service a default drf resource is limited to accepting the same object it later returns i want to use a different serializer for the input than the output for example i want to implement user registration by accepting a username and password while returning the new user object is it possible to use different serializers for input and outputclass userlistviewgenericslistapiview queryset userobjectsall serializer class userserializerclass imaginarryuserinputserializerserializersmodelserializer class meta model user fields username password password confirmationclass imaginaryuseroutputserializerserializersmodelserializer class meta model user fields id registration date,['python'] +504047,django rest framework serializing optional fields i have an object that has optional fields i have defined my serializer this wayclass productserializerserializersserializer code serializersfieldsourcecode classification serializerscharfieldsourceclassification requiredfalsei thought requiredfalse would do the job of bypassing the field if it does not exist however it is mentioned in the documentation that this affects deserialization rather than serializationi am getting the following errorproduct object has no attribute classificationwhich is happening when i try to access data of the serialized instance does not this mean it is deserialization that is raising thisthis happens for instances that do not have classification if i omit classification from the serializer class it works just finehow do i correctly do this serialize an object with optional fields that is,['python'] +504053,how to thisable a label with jquery how can i thisable a label with jquery i triedsomeidpropthisabled truebut it is not grayed outmy html is label forsomeidlabel herelabelinput idsomeid,"['javascript', 'jquery', 'html']" +504077,change ie background color on unopened focused select box i would like to change the blue background color from ie when a drop down is focused but i cannot seem to find any css to do thisselect idfocusselectoptionoptionoptionselectjsdocumentgetelementbyidfocusselectfocuscselectfocus backgroundcolor redspecifically this is for when the drop down is not open styling the options is not a problemi also cannot find any definitive answer on whether this is possible to do at allsetting the option background color also does not clear the blue coloroption backgroundcolor green,['css'] +504090,how to use the rails date field helper i am completely new to ruby on rails and trying to follow the rails guide on form helpers when i try using a date field helper with date fielduser born on i get an errorundefined method date field for class0x007fa42ffe3dc00x007fa42f82c410am i supposed to include something in order to use certain helpers thanks,['ruby-on-rails'] +504101,import classdump info into gdb is there a way to import the output from classdump into gdbexample code cat testminclude stdiohimport foundationfoundationhinterface testclass nsobject intrandomnumendimplementation testclass intrandomnum return 4 chosen by fair dice roll guaranteed to be randomendint mainvoid printfnum dn testclass randomnum return 0d gcc testm lobjc o test testnum 4 gdb testgdb b testclass randomnumbreakpoint 1 at 0x10e5cgdb d strip test gdb testgdb b testclass randomnumfunction testclass randomnum not definedgdb d classdump a testinterface testclass nsobject intrandomnum imp0x010e50endi know i can now use b 0x010e50 in gdb but is there a way of modifying gdbs symbol table to make it accept b testclass randomnumedit it would be preferably if it would work with gdb v6 and not only gdb v7 as gdb v6 is the latest version with apples patches,['objective-c'] +504138,session variables how much data is too much i have only seen examples of session variables being used to store small amounts of data like a single user id i am wondering if it would be more efficient to instead hold more frequently accessed data in the session variables to avoid querying the databasefor instance i made a user class that gathers regularly requested data for that user upon construction their user id username email password and arrays of site specific data and i hold this instance as a session variable after the users initial log in the database rarely has to be queried to get information about the user because it is already in memoryam i actually being more efficient at all or am i just bogging down the system with memory usageside note i actually find it easier to grab data from the session instead of having to worry about optimising my queries and stuff so i really hope i am not being an idiot,"['php', 'mysql']" +504151,selenium webdriver jquery i am very new to selenium webdriver and i am learning selenium webdriver on how to use jquery selectors for working with elements instead of xpath expressions ids etc could you please help me on providing the link where i can find the basic information on how to use jquery in the selenium webdriver,['jquery'] +504187,android using intent to open a fragment from an activity i am implementing an app which has a gridview of images in one activity and one fragment for each image which contains the image in full screen when i click on any of the images in the grid it should open up the corresponding fragment however we cannot use intent to do thishere is my code public void onitemclickadapterview arg0 view arg1 int position long arg3 todo autogenerated method stub ifposition0 intent inew intentgallerythisimagefrag1class startactivityi and the fragment isimport androidosbundleimport androidsupportv4appfragmentimport androidviewlayoutinflaterimport androidviewviewimport androidviewviewgrouppublic class imagefrag1 extends fragment override public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate inflate the layout for this fragment return inflaterinflaterlayoutimagefrag1 container false this fragment is bound to an activity imagesswipe so how do i achieve the transition between grid view item and its corresponding fragmentthanks,['android'] +504198,how to uninstall an android app from command line on the device i can uninstall an app on the device from my computer using adb uninstall package namebut i would like to do the same with a script on the actual devicei have also tried running an androidintentactiondelete intent using am but it prompts the user for confirmationgiven that the device is rooted is it possible to run a command on the device to uninstall an app without requiring user actionconfirmation,['android'] +504214,python nameerrori14global name a is not defined in my code i haveclass a def a def b a bthen the compiler will say nameerror global name a is not defined if i pull all the stuffs out of the class a it would be no problem but how can i define the method in class a thank you very much,['python'] +504224,how to get a count for each type of an index in elasticsearch i have an index and want to get a count for the entries in every type of one particular index in elasticsearch but might not know the types ahead of timeso for example the index iseventsand the types could beeventstype1eventstype2eventstypenand i would like to query the index and say give me the count of each of the types under index events so maybe a result set likeeventstype1 40eventstype2 20eventstypen 10where events count would give meevents 70editimotovs answer is great i am having trouble figuring how to get it working in javascriptajax easily though i have something like this right nowajaxtype geturl httplocalhost9200events searchsearch typecountdata facets count by type terms field type success functiontext consolelogtextbut am only getting the total count of elements in the es the facets portion of the answer seems to be missing,['javascript'] +504226,edit pandas dataframe using indexes is there a general efficient way to assign values to a subset of a dataframe in pandas i have got hundreds of rows and columns that i can access directly but i have not managed to figure out how to edit their values without iterating through each rowcol pair for examplein 1 import pandas numpyin 2 array numpyarange30reshape310in 3 df pandasdataframearray indexlistabcin 4 dfout4 0 1 2 3 4 5 6 7 8 9a 0 1 2 3 4 5 6 7 8 9b 10 11 12 13 14 15 16 17 18 19c 20 21 22 23 24 25 26 27 28 29in 5 rows acin 6 columns 147in 7 dfcolumnsixrowsout7 1 4 7a 1 4 7c 21 24 27in 8 dfcolumnsixrows 900in 9 dfout9 0 1 2 3 4 5 6 7 8 9a 0 1 2 3 4 5 6 7 8 9b 10 11 12 13 14 15 16 17 18 19c 20 21 22 23 24 25 26 27 28 29i believe what is happening here is that i am getting a copy rather than a view meaning i cannot assign to the original dataframe is that my problem whats the most efficient way to edit those rows x columns preferably inpace as the dataframe may take up a lot of memoryalso what if i want to replace those values with a correctly shaped dataframe,['python'] +504235,python invalid literal for int with base 10 80867 i have a script that parses data from a csv file the following line is giving me problems countdataappendtimestampintmy csvrow5it gives me the following error valueerror invalid literal for int with base 10 80867 the line of the csv file is as follows20130612 150900svcname001080867i have tried running int80867 in a python prompt and it works fine,['python'] +504277,matlab twice as fast as numpy i am an engineering grad student currently making the transition from matlab to python for the purposes of numerical simulation i was under the impression that for basic array manipulation numpy would be as fast as matlab however it appears for two different programs i write that matlab is a little under twice as fast as numpy the test code i am using for numpy python 33 isimport numpy as npimport timea nprandomrand50503tic timetimea0 a1a2 a0a1 a2toc timetime ticprinttocwhereas for matlab 2012a i am usinga rand50503tica1 a2a3 a1a2 a3tocthe algorithm i am using is the one used on a nasa website comparing numpy and matlab the website shows that numpy surpasses matlab in terms of speed for this algorithm yet my results show a 049 s simulation time for numpy and a 029 s simulation time for matlab i also have run a gauseidel solver on both numpy and matlab and i get similar results 165 s vs 95 si am brand new to python and am not extremely literate in terms of programming i am using the winpython 64 bit python thistribution but have also tried pythonxy to no availone thing i have read which should improve performance is building numpy using mkl unfortunately i have no idea how to do this on windows do i even need to do thisany suggestions,['python'] +504335,can i make an array of links using link to in rails i have a list of values in urltitle pairs that i would like to thisplay more specifically each object has its own list of links some with 0 some with 1 some with more i would like them to appear in a list that is commaseparated so i wrote this in my erb file linksmapwl link to wltitle wlurljoin somewhat to my surprise this thisplayed a commaseparated list of the html code for the links i wanted to create that is it was taking all the angle brackets and ampersandencoding them just to make sure there was not anything funny in the higherorder functions i tried a more imperative version a linkseach do wl a link towltitle wlurl end ajoin with of course the same result but i do not think i am misusing link to because if i modify that to linkseach do wl link towltitle wlurl end then it actually creates links it is almost exactly what i want except that there is an extra comma after the last one is there some magic going on under the hood with link to that makes it act differently depending on where its output is heading is there any way to bypass that magic the join semantics would be exactly what i want here and i can obviously figure out how to roll my own using each index i guess but it seems like an awfully heavy and unruby solution to what must be a common problem,"['ruby-on-rails', 'ruby']" +504337,the debugger cannot continue running the process unable to start debugging i used this to use my xna game in visual studio 2012 everything worked perfectly as it looks but when i click on the debug button on the top bar start debugging and start without debugging are grayed out and i click on them i can still click on the start arrow when i do i get the following error message,['c#'] +504342,animated loader like snapchat i was wonder how snapchat animates that ghost thing when you pull down to refresh i wanted to implement that in my app and was wondering how it was done,['objective-c'] +504348,css fade in on hover i am currently attempting to have a with an image fade in when i hover over some text using css i have applied the css code but the effect does not show the div appears but without the fadein also i realize that css transitions do not really work with ie if anyone could point me in the right direction of a workaround for that it would be much appreciated cssthumbnailposition relativezindex 0thumbnailhoverbackgroundcolor transparentzindex 50thumbnail span css for enlarged imageposition relativethisplay nonecolor blacktextdecoration noneopacity00filteralphaopacity0thumbnail span img css for enlarged imageborderwidth 0padding 5pxleft 10pxborder 1px solid graybackgroundcolor fthumbnailhover span css for enlarged image on hoverposition relativethisplay inlinetop 290pxleft 25px opacity10filteralphaopacity100position where enlarged image should offset horizontally webkittransition all 02s easeinoutmoztransition all 02s easeinoutotransition all 02s easeinouttransition all 02s easeinoutnetworking width 200px height 140px marginleft 360px top 115px position absolute backgroundcolor 613286 opacity10filteralphaopacity100 color f textaligncenter borderradius 20px webkittransform rotate14degmoztransform rotate14degmstransform rotate14degotransform rotate14degtransform rotate14deghtmldiv idnetworkinga classthumbnail href152experientialstudioshtmldown4h4networking loungeh4 spanimg srcimagesnet3jpg width250 spanadivthank you,['css'] +504370,understanding sort comparefunction i am working with an ecommerce platform that lacks the ability to reorder the options of our product attribute fields it really sucks because to insert a new option you pretty much have to delete all of the existing ones and start over i am trying to do it clientside instead heres what i am working with this ones for a shoe size9 ee9 12 ee10 ee10 12 ee11 ee11 12 ee9 e9 12 d9 12 e10 e10 12 e11 e9 d11 12 ethese are actually the text of some options in a form the format of the values is x y z wherex is a whole numbery is the string 12 and may not be presentz is a letter code which is either d e e or e and may not be presentthe desired order of the above would be this9 d9 12 d9 ee9 12 ee9 e9 12 e10 ee10 12 ee10 e10 12 e11 ee11 12 ee11 e11 12 ei have learned a little bit about javascripts sort function but have not been able to fully comprehend how the comparison function that you can pass to it works i have got this so farselect option9 eeoption option9 12 eeoption option10 eeoption option10 12 eeoption option11 eeoption option11 12 eeoption option9 eoption option9 12 doption option9 12 eoption option10 eoption option10 12 eoption option11 eoption option9 doption option11 12 eoptionselecti started with the code taken from this answer selecthtmloptionsortfunction a b return atext btext 0 atext btext 1 1which sorts the items like this does not work for even the first criteria10 12 ee10 12 e10 ee10 e11 12 ee11 12 e11 ee11 e9 12 d9 12 ee9 12 e9 d9 ee9 ei see that in javascript 11 9 returns false which in no way makes sense to memdn describes the compare function argument as such and i kind of get itfunction comparea b if a is less than b by some ordering criterion return 1 if a is greater than b by the ordering criterion return 1 a must be equal to b return 0but i have not got a clue how to adapt this to fit my requirements i have tried a few things but i just feel like i am shooting in the dark i have tried to show that i have taken some time to attempt an understanding of this problem i am interested in learning more but for now i would just like to get this issue solved any clues,"['javascript', 'jquery']" +504453,sailsmysql schema datatypes anyone used nodes sails framework using mysql as db i am stuck in models i cannot create the database structurethe datatypes that i need to use to create the schema does not work i have searched everywhere for some documentation but i cannot find anything that can help me sails documentation is not yet complete i guess can anyone please help me in creating models i would highly appreciate if you can help me create the simple schema below using sailsmysql thanks in advancemoduleexports attributes id float social network type enum defaultsto facebook twitter vkweibo country string message text link string comments text userid int username string image link string longitude float latitude float location name string updated at timestamp created at timestamp,['mysql'] +504463,opencv how to find a list of connected components in a binary image i am using opencv for a c application i have a 8 bit binary image that has some objects the objects are all colored 255 whereas everything in the background is colored 0 each object has no vacant black pixels inside it in other words each object is fully white the objects are not connected to each other heres what i want to extract from thisi want to extract some kind of list of objects from which i have some notion of the location of each object in that list this could be using cvconnectedcomponents or anything else i need some indication of where each object is located in the image this could be in the form of bounding rectangle for each object or median or center based on some computation or anything that gives me a measure of the objects location in the image any pointers to what opencv functions to look into,"['c++', 'c']" +504470,what is the best way to parse dates in binder is it good approach in the model binder use the code like thistryparsedateresultattemptedvalue format out parseddate and then format is a variable with different customer specific date format like 12312013 or 31122013 or other onesi have big problem with the format binding because if user puts the date with only 1 digit like 112014 it will not parse because in the format value allowed formats ddmmyi know that it is possible to resolve by replacing this format to dmy and then it works for both case but is it good approach or it is dangerousthank you in advance,['c#'] +504496,sql query change date format in query to ddmmy what i am trying to achieve is fairly straight forward to get one date format to anotherfrom this jan 30 2013 120amto this ddmmy or in this case 30012013however when it is the 1st to the 9th of the month the date format is missing a zero and there is two spaces as shownjul 3 2014 120ami have hunted round for a solution but without success the format of the date is unusual and varies depending on the day of the month however this format is generated by an internal system and cannot be changed would i then have to pattern match in order to change the format how would i go about doing thisan example of part of the query is thisselectprefix tablenamecolumnname1 as nameprefix tablenamecolumnname2 as emailprefix tablenamecolumnname3 as transactiondateprefix tablenamecolumnname4 as ordernumberthe line to be edited is this prefix tablenamecolumnname3 as transactiondate,['sql'] +504539,mysql query for getting restaurant remaining seats i have problem to write mysql select query in which i can get number of free seat in time slotlet me define my problem user mysql querysuppose i have one table restaurant bookingif there are total 25 seats in restaurant and one user want to 15 seat between 200pm 400pm how to check in booking table till this time how many seats are availableif i see this booking table there are 20 seats already booked till this time slot then how should i get only 5 seats are availableif anyone have any idea please let me know thanks,['mysql'] +504642,reflection how to get methodinfo for generic extension method i have an ienumerablet and i want to call the enumerablecontains method by reflection i am just struggling to get the syntax right heres what i currently havevar containsmethod typeofenumerablegetmethodcontains new typeofienumerablet typeoft this just comes back with a nullwhat is the correct way to get the methodinfo,['c#'] +504694,in scipy what is slinear interpolation i cannot find an explanation in the documentation or anywhere online what does slinear stand for and what does it do,['python'] +504696,resultsetgetdate semantics we migrated from to ojdbc6112030 to ojdbc712101 and observed a change in the resultsetgetdate semantics previously the javasqldate returned would be normalized by having set the hours minutes seconds and milliseconds to zero according to the contract specified on javasqldate with ojdbc7this is no longer the case and javasqldate has the hours minutes seconds and milliseconds set according to the value on the databasei looked at the javadoc of resultsetgetdate and it does not explicitly say which of the behaviors is the correct one i would have assumed the old behavior was what the specification intended am i right have we encountered a driver bug,['java'] +504698,wcf error there was no endpoint listening at i am developing a wcf service running iis6 on window server 2003 i have built a test client to talk to the wcf service and i am getting the error below i have been looking at this error for days and went through peoples suggestions on forums but with no luck any help would be appreciated many thanksthere was no endpoint listening at that could accept the message this is often caused by an incorrect address or soap action see innerexception if present for more detailssystemnetwebexception the remote server returned an error 404 not found at systemnethttpwebrequestgetresponse at systemservicemodelchannelshttpchannelfactoryhttprequestchannelhttpchannelrequestwaitforreplytimespan timeoutserver stack trace at systemservicemodelchannelshttpchannelutilitiesprocessgetresponsewebexceptionwebexception webexception httpwebrequest request httpabortreason abortreason at systemservicemodelchannelshttpchannelfactoryhttprequestchannelhttpchannelrequestwaitforreplytimespan timeout at systemservicemodelchannelsrequestchannelrequestmessage message timespan timeout at systemservicemodelthispatcherrequestchannelbinderrequestmessage message timespan timeout at systemservicemodelchannelsservicechannelcallstring action boolean oneway proxyoperationruntime operation object ins object outs timespan timeout at systemservicemodelchannelsservicechannelproxyinvokeserviceimethodcallmessage methodcall proxyoperationruntime operation at systemservicemodelchannelsservicechannelproxyinvokeimessage messageexception rethrown at 0 at systemruntimeremotingproxiesrealproxyhandlereturnmessageimessage reqmsg imessage retmsg at systemruntimeremotingproxiesrealproxyprivateinvokemessagedata msgdata int32 type at iota2010areservationsynch submitrequestreservationsynchrequest request at ota2010aclientiota2010areservationsynch submitrequestreservationsynchrequest request in cdevelopmentworkingfolderwebservicessynxisnewapp codeota2010acsline 57589 at ota2010aclientreservationsynch submitrequestsecurity security datetime timestamp string correlationid string relatestocorrelationid replyto replyto ota hotelresnotifrq ota hotelresnotifrq in cdevelopmentworkingfolderwebservicessynxisnewapp codeota2010acsline 57601 at updatepage loadobject sender eventargs e in cdevelopmentworkingfolderwebservicessynxisnewupdateaspxcsline 72client configxml version10 encodingutf8configuration systemweb compilation debugtrue systemweb systemservicemodel bindings wshttpbinding binding nameota2010aendpoint closetimeout0100 opentimeout0100 receivetimeout0010 sendtimeout0100 bypassproxyonlocalfalse transactionflowfalse hostnamecomparisonmodestrongwildcard maxbufferpoolsize524288 maxreceivedmessagesize65536 messageencodingtext textencodingutf8 usedefaultwebproxytrue allowcookiesfalse readerquotas maxdepth32 maxstringcontentlength8192 maxarraylength16384 maxbytesperread4096 maxnametablecharcount16384 reliablesession orderedtrue inactivitytimeout0010 enabledfalse security modetransport transport clientcredentialtypenone proxycredentialtypenone realm message clientcredentialtypewindows negotiateservicecredentialtrue establishsecuritycontexttrue security binding wshttpbinding bindings client endpoint address bindingwshttpbinding bindingconfigurationota2010aendpoint contractiota2010a nameota2010aendpoint client systemservicemodelconfigurationservice configxml version10configuration systemweb compilation debugtrue targetframework40 assemblies add assemblypervasivedatasqlclient version210034 cultureneutral publickeytokenc84cd5c63851e072 assemblies compilation authentication modewindows pages controlrenderingcompatibilityversion35 clientidmodeautoid systemweb systemservicemodel services service namesynxis behaviorconfigurationsynxiswcf endpoint address namewshttpendpoint bindingwshttpbinding contractsynxis endpoint addressmex bindingmexhttpbinding contractimetadataexchange service services diagnostics messagelogging logentiremessagetrue logmalformedmessagestrue logmessagesatserviceleveltrue logmessagesattransportleveltrue maxmessagestolog300 diagnostics behaviors servicebehaviors behavior namesynxiswcf servicemetadata httpgetenabledtrue httpsgetenabledtrue externalmetadatalocation servicedebug includeexceptiondetailinfaultstrue behavior servicebehaviors behaviors systemservicemodelconfiguration,['c#'] +504737,should an override of equals on a reference type always mean value equality without doing anything special for a reference type equals would mean reference equality ie same object if i choose to override equals for a reference type should it always mean that the values of the two objects are equivalentconsider this mutable person classclass person readonly int id string firstname get set string lastname get set string address get set two objects that represent the exact same person will always have the same id but the other fields might be different over time ie beforeafter an address changefor this object equals could be defined to mean different thingsvalue equality all fields are equal two objects representing the same person but with different addresses would return falseidentity equality the ids are equal two objects representing the same person but with different addresses would return truereference equality ie do not implement equalsquestion which if any of these is preferable for this class or perhaps the question should be how would most clients of this class expect equals to behavenotesusing value equality makes it more difficult to use this class in a hashset or dictionaryusing identity equality makes the relationship between equals and the operator strange ie after a check of two person objects p1 and p2 returns true for equals you might still want to update your reference to point to the newer person object since it is not value equivalent for example the following code reads strangeseems like it does nothing but it is actually removing p1 and adding p2hashsetperson people new hashsetpersonpeopleaddp1 p2 is an new object that has the same id as p1 but different addresspeopleremovep2peopleaddp2related questionswhy does microsoft recommend skip implementing equality operator for reference typesc difference between and equalswhen should a net class override equals when should it notsimplify overriding equals gethashcode in c for better maintainability,"['c#', '.net']" +504766,issue in rails 40 with creating a link to for a delete action this is my first project in rails which is to create a table that will store data about games i am able to thisplay data from the table about winner score loser score etc however i have issues with my table column that contains delete links for each gameheres my code in the games controller for the delete methoddef delete game gamefindparamsgame gamedestroy redirect to action indexenda snippet of my table code which includes the line for the link to command games itemseach do t tr td twinnername td td tlosername td td tchallengername td td twinner score td td tloser score td td link to delete delete game pathid tidtd tr end in the routes file i calledresources gameswhich to my knowledge helps generate the base routing could anyone help me figure out why my link to is not working,"['ruby-on-rails', 'ruby']" +504773,how to document the author in c xml in the list of recommended tags is for my surprise no author tag so i am wondering what is the official or best practice way to document the author of classmethod,['c#'] +504804,environment detection nodejs or browser i am developping a jsapp that needs to work both on the client side and the server side in javascript on a browser and in nodejs and i would like to be able to reuse the parts of the code that are used for both sidesi have found out that window was a variable only accessible on browsers and global in node so i can detect in which environment the code is executing assuming that no script declares the window variablethey are two problemshow should i detect in which browser the code is running for example is this code ok this code is inline meaning that it is surrounded by some global code reused for both environmentsif window totalpath examplespathelse totalpath examplespathhow can i use global variables for both environments now i am doing the following but this really does not feel rightif window windowdocutils windowdocx windowdocxdata else globaldocutils globaldocx globaldocxdata,['javascript'] +504806,better way to generate array of all letters in the alphabet right now i am doingfor char c a c z c alphabetc a cbut is there a better way to do it similar to scalas a to z,['java'] +504857,visual studio 2012 menu analyze code coverage is missing there is this great tool in visual studio 2012 to show the test coverage of the source code on the official msdn homepage it is shown under menu test analyze code coveragebut in my test menu this entry is missing and i couldnt figure out why can someone please explain am i missing an addonpluginupdate visual studio 2012 professional with update 3,['c#'] +504868,insert and select from stored procedure in php i am currently trying to execute a stored proceduretwo inserts and a select through php the stored procedure works no errors are thrown the values are even inserted into the given tables we are storing the result in a json object but it is returning an empty array when we execute the stored procedure containing only a select it returns the correct values all the names have been changed in our tables may have missed some but our code runs can anyone shed light on why our array is not populatinghere is our stored procedure alter procedure asbegininsert into table1loan id doc id borrower name docs drawn funder first payment interest rate loan amountselect loan id select count from table where aloan id loan id as doc id borrower date docs drawn funder payment date interest rate loan amount from view a insert into table2loan id submitted by event class event type event date doc idselect aloan id program as submitted by collateral as event class outstanding as event type current timestamp as event date doc id from table1 as a where not aloan id any select loan id from table2 select loan iddoc idborrower name funder docs drawn first payment loan amount interest rate from table1 where loan id all select loan id from table2 where event type outstanding order by funderendhere is a rough sketch of our phpquery exec storedprocedureresultsqlsrv queryconn querytable arraywhilerow sqlsrv fetch arrayresult table rowecho json encodetable,"['php', 'sql']" +504869,getchildfragmentmanager raise nosuchmethod exception on 403 device but not on 422 i need to use nested fragments for my application and so i would like to use getchildfragmentmanageri have two devicesa real one running on 403a virtual one running on 422it works pretty well on the second one but not on my physical device since the call to this method raise a nosuchmethod exception0710 195351722 eandroidruntime29711 javalangnosuchmethoderror frepitechtest esifragmentsreservationcalendarfragmentgetchildfragmentmanagermy project use a referenced library so i have downloaded the latest android support library from sdk manager and i have added it to both the library and the main projectalso i decided to set the minimum sdk version supported to 403 the version my real device is running onusessdk androidminsdkversion15 androidtargetsdkversion17 for both the main project and libraryif anyone has an idea of what i could do wrong let me know,['android'] +504882,how to pass parameters into image load event when i set the src of an image object it will trigger an onload function how can i add parameters to itx 1y 2imageobj new imageimageobjsrc imageobjonload function contextdrawimageimageobj x yx 3y 4in here i want to use the x and y values that were set at the time i set the src of the image ie 1 and 2 in the code above by the time the onload function would finish x and y could be 3 and 4is there a way i can pass values into the onload function or will it automatically use 1 and 2thanks,['javascript'] +504884,c structs pointer and memory allocation for fields suppose the following codestruct c char nameint mainint argc char argv struct c c1 c1name ana printf snc1name return 0my first reaction would have been to think that i needed to allocate some space either on the heap or by an explicit char name anna but my example above works is the compiler just storing that string in the data segment and pointing to it in other words is that like doing a struct c char name anathanks,['c'] +504927,net stringbuilder check if ends with string what is the best shortest and fastest way to check if stringbuilder ends with specific stringif i want to check just one char that is not a problem sbsblength1 c but how to check if it is ends with longer stringi can think about something like looping from some stringlength and read characters one by one but maybe there exists something more simple at the end i want to have extension method like thisstringbuilder sb new stringbuilderhello worldbool hasstring sbendswithworld,"['c#', '.net']" +504929,programmatically thisable highlight on click of uibutton there must be a way to do this but i cannot find it i have a button i have created programmatically uibutton button uibutton buttonwithtypeuibuttontyperoundedrectbuttonframe cgrectmake25 selfviewframesizeheight4 200 350button settitleinbox forstateuicontrolstatenormalbutton addtargetself actionselectorpopviewcontroller forcontroleventsuicontroleventtouchupinsideselfview addsubviewbuttonall i want is for the button not to highlight or change in appearance in any way when it is touched so far i have tried the following when creating the buttonbutton setbackgroundimageuiimage imagenamednil forstateuicontrolstateselected uicontrolstatehighlightedandbutton setbackgroundimagenil forstateuicontrolstateselectedand button setadjustsimagewhenhighlightednoandbuttonshowstouchwhenhighlighted nothen in the button action i triedsender sethighlightedsenderishighlightedandsender setselectedsenderisselectednone of these work,"['ios', 'objective-c']" +504949,python selenium error when trying to launch firefox i am getting an error when trying to open firefox using selenium in ipython notebook i have looked around and have found similar errors but nothing that exactly matches the error i am getting anybody know what the problem might be and how i fix it i am using firefox 22the code i typed in was as followsfrom selenium import webdriverdriver webdriverfirefoxthe error the code returns is as follows windowserror traceback most recent call lastipythoninput7fd567e24185f in module 1 driver webdriverfirefoxcanacondalibsitepackagesseleniumwebdriverfirefoxwebdriverpyc in init self firefox profile firefox binary timeout capabilities proxy 56 remotewebdriver init self 57 command executorextensionconnection127001 selfprofile 58 selfbinary timeout 59 desired capabilitiescapabilities 60 self is remote falsecanacondalibsitepackagesseleniumwebdriverfirefoxextension connectionpyc in init self host firefox profile firefox binary timeout 45 selfprofileadd extension 46 47 selfbinarylaunch browserselfprofile 48 url httpsdhub host port 49 remoteconnection init canacondalibsitepackagesseleniumwebdriverfirefoxfirefox binarypyc in launch browserself profile 45 selfprofile profile 46 47 self start from profile pathselfprofilepath 48 self wait until connectable 49 canacondalibsitepackagesseleniumwebdriverfirefoxfirefox binarypyc in start from profile pathself path 71 72 popencommand stdoutpipe stderrstdout 73 envself firefox envcommunicate 74 command1 foreground 75 selfprocess popencanacondalibsubprocesspyc in init self args bufsize executable stdin stdout stderr preexec fn close fds shell cwd env universal newlines startupinfo creationflags 677 p2cread p2cwrite 678 c2pread c2pwrite 679 eread errwrite 680 681 if mswindowscanacondalibsubprocesspyc in execute childself args executable preexec fn close fds cwd env universal newlines startupinfo creationflags shell p2cread p2cwrite c2pread c2pwrite eread errwrite 894 env 895 cwd 896 startupinfo 897 except pywintypeserror e 898 translate pywintypeserror to windowserror which iswindowserror error 2 the system cannot find the file specified,['python'] +504971,using enum for factory in java a best practice java allow us to embed data and behaviour on enumi do not want to implement a factory directly on an enum because i think this is not its role but i can put class reference on the enum and contruct object on an external factory comparing to a traditionnal factory pattern what is the best implementation for you which solution is better to use in which case now the codefunction used in both solutions to construct objects usefull to implement flyweight pattern with a map if requiredprivate action getactionclass extends action actionclazz logger error handling return actionclazznewinstance1 with a traditionnal factorypublic enum actionenum load data load configpublic action getactionactionenum action switch action case load config return getactionactionloadconfigclass case load data return getactionactionloaddataclass 2 with enumstyled factory public enum actionenum load dataactionloadconfigclass load configactionloaddataclass public actionenumclass extends action clazz public getclazz return thisclazzpublic action getactionactionenum action return getactionactiongetclazz,['java'] +504972,which ide for phonegap is eclipse enough i am about to jump into phonegap and realize that it does not have an ide of its own i know that i could use eclipse to create androidcentric phonegap apps but what about the ios and perhaps windows phone and perhaps blackberry versions can eclipse be used for all of it what do most phonegappers use as an idedoes phonegap build make it possible to do it all in eclipse and then throw it up to the cloud for the ios etc builds,"['android', 'ios']" +504980,uitableviewheaderfooterview subclass with auto layout and section reloading would not work well together i am trying to incorporate auto layout into my uitableviewheaderfooterview subclass the class is pretty basic just two labels this is the complete subclass implementation mbtabledetailstylefooterviewstatic void mbtabledetailstylefooterviewcommonsetupmbtabledetailstylefooterview self uilabel rightlabel uilabel alloc init selfrightlabel rightlabel rightlabeltranslatesautoresizingmaskintoconstraints no selfcontentview addsubviewrightlabel uilabel leftlabel uilabel alloc init selfleftlabel leftlabel leftlabeltranslatesautoresizingmaskintoconstraints no selfcontentview addsubviewleftlabel nsdictionary views nsdictionaryofvariablebindingsrightlabel leftlabel nsarray horizontalconstraints nslayoutconstraint constraintswithvisualformat10leftlabel10rightlabel10 options0 metricsnil viewsviews selfcontentview addconstraintshorizontalconstraints center views vertically in super view nslayoutconstraint leftcenteryconstraint nslayoutconstraint constraintwithitemleftlabel attributenslayoutattributecentery relatedbynslayoutrelationequal toitem selfcontentview attributenslayoutattributecentery multiplier1 constant0 selfcontentview addconstraintleftcenteryconstraint nslayoutconstraint rightcenteryconstraint nslayoutconstraint constraintwithitemrightlabel attributenslayoutattributecentery relatedbynslayoutrelationequal toitem selfcontentview attributenslayoutattributecentery multiplier1 constant0 selfcontentview addconstraintrightcenteryconstraint same height for both labels nslayoutconstraint sameheightconstraint nslayoutconstraint constraintwithitemleftlabel attributenslayoutattributeheight relatedbynslayoutrelationequal toitemrightlabel attributenslayoutattributeheight multiplier1 constant0 selfcontentview addconstraintsameheightconstraint boolrequiresconstraintbasedlayout return yes idinitwithreuseidentifiernsstring reuseidentifier self super initwithreuseidentifierreuseidentifier mbtabledetailstylefooterviewcommonsetupself return selfendthis class is used as a footer in the first section in a tableview with 2 sections the first section contains dynamic items the second section has only one row which is used to add new items to the first section if there are no items in the first section i hide the footerview so when i add the first new item i have to reload the section so the footerview appears the code that does all this looks like this voidtableviewuitableview tableview didselectrowatindexpathnsindexpath indexpath tableview deselectrowatindexpathindexpath animatedyes if indexpathsection 1 bool sectionneedsreload selfdata count 0 reload section when no data and therefor no footer was present before the add selfdata addobjectnsdate date nsindexpath newindexpath nsindexpath indexpathforrowselfdata count1 insection0 if sectionneedsreload selftableview reloadsectionsnsindexset indexsetwithindex0 withrowanimationuitableviewrowanimationautomatic else selftableview insertrowsatindexpathsnewindexpath withrowanimationuitableviewrowanimationautomatic self configurefootermbtabledetailstylefooterview tableview footerviewforsection0 forsection0 voidconfigurefootermbtabledetailstylefooterview footer forsectionnsintegersection footerleftlabeltext total footerrightlabeltext nsstring stringwithformatd selfdata count uiview tableviewuitableview tableview viewforfooterinsectionnsintegersection mbtabledetailstylefooterview footer nil if section 0 selfdata count footer tableview dequeuereusableheaderfooterviewwithidentifierfooter self configurefooterfooter forsectionsection return footer cgfloattableviewuitableview tableview heightforfooterinsectionnsintegersection cgfloat height 0 if section 0 selfdata count height 200f return heightnothing really fancy however as soon as reloadsectionswithrowanimations is called on my tableview it throws an exception because it is unable to simultaneously satisfy constraints somewhere the tableview added a translated auto resizing mask constraint to my footer nslayoutconstraint0x718a1f0 huilabel0x718913010 names uitableviewheaderfootercontentview0x7188df0 nslayoutconstraint0x7189e30 huilabel0x71892c010uilabel0x7189130 nslayoutconstraint0x718a0a0 h10uilabel0x71892c0 names uitableviewheaderfootercontentview0x7188df0 nsautoresizingmasklayoutconstraint0x7591ab0 h v h uitableviewheaderfootercontentview0x7188df00when i replace reloadsectionswithrowanimations with a call to reloaddata no autoresizing mask constraint is added and everything works fine the interesting thing is that the exception tells me that it tries to break the constraint nslayoutconstraint0x7189e30 huilabel0x71892c010uilabel0x7189130but when i log the constraints in subsequent calls to configurefooterforsection this constraint still exists but the auto resizing mask constraint is gonethe constraints are exactly those that i have set up nslayoutconstraint0x718a0a0 h10uilabel0x71892c0 names uitableviewheaderfootercontentview0x7188df0 nslayoutconstraint0x7189e30 huilabel0x71892c010uilabel0x7189130 nslayoutconstraint0x718a1f0 huilabel0x718913010 names uitableviewheaderfootercontentview0x7188df0 nslayoutconstraint0x718a3f0 uilabel0x71892c0centery uitableviewheaderfootercontentview0x7188df0centery nslayoutconstraint0x718a430 uilabel0x7189130centery uitableviewheaderfootercontentview0x7188df0centery nslayoutconstraint0x718a4b0 uilabel0x71892c0height uilabel0x7189130heightwhere does this auto resizing mask constraint come from where does it go am i missing something the first time i looked into auto layout was like a week ago so this is totally possible,['ios'] +505024,ios determine users country without using cllocationmanager i do not need precise location data and i do not want the user to see the this app wants to determine your location alert i just need to determine the users country assuming they have an internet connection via network or wifiwhat is the best way to do this is there some way to use their ipthis would only work if they had a carriercttelephonynetworkinfo netinfo cttelephonynetworkinfo alloc initctcarrier carrier netinfo subscribercellularprovidernsstring mcc carrier mobilecountrycodeand nslocale is not reliable in that the user can change it in their device settings cannot use the devices language setting for the same reason i need the country based on where they are physically located,['ios'] +505072,eclipse still using java 6 as jre on mac osx i have installed eclipse sdk 371 on my mac which is running mac osx 1084 i am trying to get eclipse to use java 7 which is installed to libraryjavajavavirtualmachinesjdk170 25jdkbut when i view eclipses installation details it is still using to my old java 6 installationeven after addingvmlibraryjavajavavirtualmachinesjdk170 25jdkcontentshomebinjava to the eclipseini filealso edited the infoplist file to point to java 7anyone have any suggestions here i am completely out of ideasplease note i am a newbie with macs any suggestions big or small would be greatly appreciated contents of infoplistxml version10 encodingutf8doctype plist public apple computerdtd plist 10en plist version10dict keycfbundleexecutablekey stringeclipsestring keycfbundlegetinfostringkey stringeclipse 37 for mac os x copyright ibm corp and others 2002 2011 all rights reservedstring keycfbundleiconfilekey stringeclipseicnsstring keycfbundleidentifierkey stringorgeclipseeclipsestring keycfbundleinfodictionaryversionkey string60string keycfbundlenamekey stringeclipsestring keycfbundlepackagetypekey stringapplstring keycfbundleshortversionstringkey string37string keycfbundlesignaturekey stringstring keycfbundleversionkey string37string keycfbundledevelopmentregionkey stringenglishstring keycfbundlelocalizationskey array stringarstring stringcsstring stringdastring stringelstring stringenstring stringesstring stringdestring stringfistring stringfrstring stringhustring stringitstring stringiwstring stringjastring stringkostring stringnlstring stringnostring stringplstring stringpt brstring stringptstring stringrustring stringsvstring stringtrstring stringzh hkstring stringzh twstring stringzhstring array keyeclipsekey array stringvmstringstringlibraryjavajavavirtualmachinesjdk170 25jdkcontentshomebinjavastring stringkeyringstringstringeclipse keyringstring stringshowlocationstring warning if you try to add a single vm argument vmargs here all vmargs specified in eclipseini will be ignored we recommend to add all arguments in eclipseini arraydictplist,['java'] +505081,attach generated csv file to email and send with django i need to generate a csv file based on the queryset result attach the resulting file to an email as attachment and send as you can see i need to iterate over the assigned leads and write it to a file so i thought yield would do the trick now when i run the code i receive the email with attachment with below message instead of the rows i expect if i use return i get the one row from the queryset resultgenerator object data at 0x7f5e508d93c0def send lead reminderrequest usercompany listingobjectsfiltersubmitted byrequestuser assigned leads leadobjectsfilterassigned to inusercompanythistinct def data csvfilestringiostringio csvwriter csvwritercsvfile for leads in assigned leads csvwriterwriterowleadsbusiness name leadsfirst name leadslast name leadsemail leadsphone numberleadsaddress leadscity leadsstate leadszipcode leadssubmission date leadstime frame leadscomments yield csvfilegetvalue message emailmessagehelloyour leads messageattachinvoicecsv data textcsv messageto messagesend return httpresponseredirect,['python'] +505085,why is factorial calculation much faster in haskell than in java one of the programming problems i have come across involves calculation of factorials of large numbers of numbers up to 105 i have seen a simple haskell code which goes like thisfactorial eq x num x x xfactorial 0 1factorial a a factorial a 1which implicitly handles the huge numbers and somehow runs faster even without any caching that is involved in the code when i tried to solve the problem using java i had to use biginteger to hold the huge numbers and also use iterative version of factorialpublic static biginteger factorialiterativeint n ifn 0 and 1 return bigintegervalueof1 biginteger f bigintegervalueof1 forint i 1 i and i f fmultiplybigintegervalueofi return fthe above code exceeded the set time limit of execution for the program i also tried the cached recursive version of factorialpublic static biginteger factorialint n ifcachen null return cachen else ifn 0 return new biginteger1 else cachen n factorialn 1 return cachen which gave me an out of memory error probably due to recursion my question is why are functional programming languages like haskell better in handling these sorts of problems involving huge numbers despite no obvious caching is there a way i can make the java code run as fast as the haskell code,['java'] +505092,how to autoload libraries in laravel 4 i have created a library folder in app folder to add my app libraries i have updated app config file and composerjson to autoload that folder but when i run the command composer dumpautoload i get the next errorerrortypesymfonycomponentdebugexceptionfatalerrorexceptionmessageclass applibrariessearchsearchserviceprovider not foundfiledusersmiguel borgesdocumentstrabalhosteseportalbootstrapcompiledphpline4130php fatal error class applibrariessearchsearchserviceprovider not found in dusersmiguel borgesdocumentstrabalhosteseportalbootstrapcompiledphp on line 4130 finished in 11s with exit code 255my app folder treeapp libraries search searchphp searchfacadephp searchserviceproviderphp lib2 lib3 themephp filtersphp routesphpsearchserviceproviderphpnamespace applibrariessearchuse illuminatesupportserviceproviderclass searchserviceprovider extends serviceprovider register the service provider return void public function register thisappsearch thisappsharefunctionapp return new search composerjson autoload classmap appcommands appcontrollers appmodels applibraries appdatabasemigrations appdatabaseseeds appteststestcasephp psr0 app applibraries basically i need to autoload all the libraries within the libraries folder,['php'] +505116,what does hash do in python i saw an example of code that where hash function is applied to tuple as a result it returns a negative integer i wonder what does this function does google does not help i found a page that explains how hash is calculated but it does not explain why we need this function,['python'] +505117,garbage collection of class instance variables in ruby if i use a method like def selfget service client return service client if service clientnil service client initialize logic endnow service client is an instance variable of a class how long is it in memory can i bank on it to not be reinitialized as long as the class is in memory ie like a static variable,['ruby'] +505152,how can i link a combobox to a folder of images in the body of html i have input typefile idimg multiplebr input typesubmit onclickloadfilesin javascript i havefunction loadfiles var viewer new photoviewer var imagefiles documentgetelementbyidimg fileslength imagefilesfileslength for var i 0 i fileslength i vieweraddslide1imagefilesfilesiname viewershow0here what i am doing is selecting multiple files from the specific folder and those files are showing in the jquery slider but i want to do it as a combobox of folders whichever folder i choose it will show all the images present in that folder using the same jquery sliderform namemyform select idmytextarea namemytextarea size1 option nameone valueone one option option nametwo valuetwo two option option namethree valuethree three option option namefour valuefour four option selectformhow can i can get a link to the folder,"['javascript', 'jquery']" +505236,when to choose mouseover and hover function what are the differences between jquery mouseover and hover function if they are totally same why jquery uses both,['jquery'] +505246,intent for google maps 700 with location at first i know that there are several similar questions on stackoverflow curriently i use the geo scheme for addressing points which can be handled by other appslike in the example of the android documentation by the way it seems to be outdated the rfc it out i tried to use something like thisgeo5095144698725q509514469872520thisneylandso i get a intent chooser where i can select an app which showed me in case of google maps thisneyland with a marker on it now it seems that an update was installed which removes that support i just get the message that this place cannot been foundi tried to understand the rfc 5870 which defines the geo uri scheme i do not get it exactly it is correct that it is not possible at all to define a lablehow can i link now a position to google maps,['android'] +505257,is there a way to know how many parameters are needed for a method using irb we can list methods for particular object by doing followingnamemethodsbut if i want to know how many parameters are needed for a particular method how can i achieve this i mean is there any way by hitting some command on irb we can get number of parameters for particular method instead of referring to docsmethods returns only method names not list of parameters for method,['ruby'] +505393,how to select the first element of n4 elements with css only i am playing around with nthchild selectorsay i have grid with rows of 4 elements each and my first and last element have classes of uifirstchild and uilastchild respectivelyul liuifirstchild li li liuilastchildulwhat i would like to do is select the first element only if there are more than 4 elements using pure cso if there are five elements like this elfirstelelel ellasti want to override bottomcorners on the first elementquestionis it possible with pure cssnthchildfirstlast class to select the first element on a group of elements with number of elements 4thanks,['css'] +505409,what is the proper replacement of the resteasy 3x preprocessinterceptor i am building rest service using an authenticationauthorization mechanism as described in this tutorial basically it uses the preprocessinterceptor interface to scan the target method for annotations from javaxannotationsecurity package which describe the required roles to access that method as the the authenticator here is an interceptor it can cancel the target method invocation returning a 401 unauthorized if neededthe problem here is that the interface orgjbossresteasyspiinterceptionpreprocessinterceptor is deprecated in the current resteasy version 301 and i am having problems trying to implement the same behaviour with the standard jaxrs interfacesi am using the javaxwsrsextreaderinterceptor interface to intercept the call but somehow the server never calls it the interceptor is just ignoredi am registering the interceptorsresources the same way as i did with the former preprocessinterceptor and using the same provider and serverinterceptor annotationsserverapplicationpublic class serverapplication extends javaxwsrscoreapplication private final hashsetobject singletons new linkedhashsetobject public serverapplication singletonsaddnew securityinterceptor singletonsadd add each of my rest resources override public setclass getclasses hashsetclass set new hashsetclass return set override public setobject getsingletons return singletons securityinterceptorproviderserverinterceptorpublic class securityinterceptor implements javaxwsrsextreaderinterceptor override public object aroundreadfromreaderinterceptorcontext context code that is never called so lonely here any insights about how can i solve this problemthank you,['java'] +505479,java generics type erasure i would like to ask about java type erasure rulesif we have classespublic class shapepublic class circle extends shapepublic class baset extends shape t x public void setxt tpublic class mainclass public static void mainstring arg base extends shape bs new basecircle bssetxnew circle compilation problem can you please explain me why calling setx method causes compilation problem,['java'] +505495,qt cannot set qvboxlayout as layout in qmainwindow i am trying to create a simple openfileandshowit program there should be on top a qhboxlayout with a qlabel a qlineedit for the file path and a qpushbutton to load it i have created a qvboxlayout and added the the qhboxlayout with addlayout then i added a qwidget to the qvboxlayoutwhen i try to view the window i get an empty window there is no label or buttonthe header fileclass mainwindow public qmainwindow q objectpublic explicit mainwindowqwidget parent 0 mainwindowprivate qlineedit m pathlineeditpublic q slots void loadfileand the cpp filemainwindowmainwindowqwidget m pathlineedit new qlineedit m nesemulator new nesemulator qvboxlayout vboxlayout new qvboxlayout qhboxlayout hboxlayout new qhboxlayout qlabel label new qlabeltrromimage hboxlayoutaddwidgetlabel hboxlayoutaddwidgetm pathlineedit qpushbutton pushbutton new qpushbuttontrdurchsuchen connectpushbutton signalclicked this slotloadfile hboxlayoutaddwidgetpushbutton vboxlayoutaddlayouthboxlayout vboxlayoutaddwidgetnew qlayout setlayoutvboxlayout,['c++'] +505506,select value if condition in sql server in a query selection i would like to thisplay the result whether a field satisfies a condition imagine that i have a table called stock this table has a column that tells me the number of each item in the stockwhat i would like to do is something like thisselect stockname if stockquantity 20 buy urgent there is enoughfrom stockis there any function in sql server to do that,['sql'] +505538,how to inflate view inside fragment if i try to inflate a view within a fragment i am getting null for examplepublic view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate here i will inflate my view using the layout id return return viewwhenever a button is clicked i need to create a dynamic view eg button add to the linearlayout i would like to perform this operation inside my fragment class like thispublic void addplaces button button new buttonnull buttonsettextbutton name eg like adding button to enter code here linear layout linearlayoutaddviewbutton so if i get inflate linearlayout inside oncreateview and use it in add class i am getting null how to achieve,['android'] +505551,installing mysqlpython on mac i am using osx 108 and pycharm to work on a python development project i have installed mysqlpython for the mac using the instructions on the website environmenterror mysql config not foundhowever running the project gives me this errordjangocoreexceptionsimproperlyconfigured error loading mysqldb module dlopenusersashishagarwalpythoneggsmysql python123py27macosx106inteleggtmp mysqlso 2 symbol not found mysql affected rows referenced from usersashishagarwalpythoneggsmysql python123py27macosx106inteleggtmp mysqlso expected in flat namespace in usersashishagarwalpythoneggsmysql python123py27macosx106inteleggtmp mysqlsothe file mentioned int the error exists at the location usersashishagarwalpythoneggsmysql python123py27macosx106inteleggtmp mysqlso the entire error message is usrlocalbinpython2732 usersashishagarwaloptimusmashpotatobackendmashpotatomanagepy testserver addrport 80running on development servertraceback most recent call last file usersashishagarwaloptimusmashpotatobackendmashpotatomanagepy line 10 in module execute from command linesysargv file libraryframeworkspythonframeworkversions27libpython27sitepackagesdjangocoremanagement init py line 453 in execute from command line utilityexecute file libraryframeworkspythonframeworkversions27libpython27sitepackagesdjangocoremanagement init py line 392 in execute selffetch commandsubcommandrun from argvselfargv file libraryframeworkspythonframeworkversions27libpython27sitepackagesdjangocoremanagement init py line 272 in fetch command klass load command classapp name subcommand file libraryframeworkspythonframeworkversions27libpython27sitepackagesdjangocoremanagement init py line 77 in load command class module import modulesmanagementcommandss app name name file libraryframeworkspythonframeworkversions27libpython27sitepackagesdjangoutilsimportlibpy line 35 in import module import name file libraryframeworkspythonframeworkversions27libpython27sitepackagessouthmanagementcommands init py line 10 in module import djangotemplateloadersapp directories file libraryframeworkspythonframeworkversions27libpython27sitepackagesdjangotemplateloadersapp directoriespy line 23 in module mod import moduleapp file libraryframeworkspythonframeworkversions27libpython27sitepackagesdjangoutilsimportlibpy line 35 in import module import name file libraryframeworkspythonframeworkversions27libpython27sitepackagesdjangocontribadmin init py line 3 in module from djangocontribadminhelpers import action checkbox name file libraryframeworkspythonframeworkversions27libpython27sitepackagesdjangocontribadminhelperspy line 4 in module from djangocontribadminutil import flatten fieldsets lookup field file libraryframeworkspythonframeworkversions27libpython27sitepackagesdjangocontribadminutilpy line 6 in module from djangodb import models file libraryframeworkspythonframeworkversions27libpython27sitepackagesdjangodb init py line 40 in module backend load backendconnectionsettings dictengine file libraryframeworkspythonframeworkversions27libpython27sitepackagesdjangodb init py line 34 in getattr return getattrconnectionsdefault db alias item file libraryframeworkspythonframeworkversions27libpython27sitepackagesdjangodbutilspy line 93 in getitem backend load backenddbengine file libraryframeworkspythonframeworkversions27libpython27sitepackagesdjangodbutilspy line 27 in load backend return import modulebase backend name file libraryframeworkspythonframeworkversions27libpython27sitepackagesdjangoutilsimportlibpy line 35 in import module import name file libraryframeworkspythonframeworkversions27libpython27sitepackagesdjangodbbackendsmysqlbasepy line 17 in module raise improperlyconfigurederror loading mysqldb module s edjangocoreexceptionsimproperlyconfigured error loading mysqldb module dlopenusersashishagarwalpythoneggsmysql python123py27macosx106inteleggtmp mysqlso 2 symbol not found mysql affected rows referenced from usersashishagarwalpythoneggsmysql python123py27macosx106inteleggtmp mysqlso expected in flat namespace in usersashishagarwalpythoneggsmysql python123py27macosx106inteleggtmp mysqlsoprocess finished with exit code 1,['python'] +505553,dynamically choosing class to inherit from my python knowledge is limited i need some help on the following situationassume that i have two classes a and b is it possible to do something like the following conceptually in pythonimport osif osname nt class newclassa class bodyelse class newclassb class bodyso the problem is that i would like to create a class newclass such that it will inherit from different base classes based on platform difference is this possible to do in pythonthanks,['python'] +505559,assertionfailederror has no public constructor i am working with android studio and i need to add a unit tests to my projecti read various tutorials but nothing hepled memy problem istestxmlparserjavapublic class testxmlparser extends activityinstrumentationtestcase2homepageactivity public testxmlparserclasshomepageactivity activityclass superactivityclassoverridepublic void setup throws exception supersetup controllerinitactivitygetcontextoverridepublic void teardown throws exception superteardownpublic void testtrue throws exception asserttruetruewhen i run it i see this messagejunitframeworkassertionfailederror class czcvutkosappjunitteststestxmlparser has no public constructor testcasestring name or testcaseat androidtestandroidtestrunnerruntestandroidtestrunnerjava190at androidtestandroidtestrunnerruntestandroidtestrunnerjava175at androidtestinstrumentationtestrunneronstartinstrumentationtestrunnerjava5at androidappinstrumentationinstrumentationthreadruninstrumentationjava1661i really do not know whyother junit tests works well for example when i usepublic class testxmlparser extends androidtestcase in header this works and tests are running correctlybut i need use the context as a activity to run other code in controller classdo you have any idea how fix itthank you for your comments,"['java', 'android']" +505581,query by boolean properties in springdatajpa without using method parameters is it possible to query by boolean properties in spring data jpa without using method parametersbasically i would like this to work without using custom query annotationqueryselect c from entity c where cenabled truepublic iterableentity findallenabled,['java'] +505673,why would you use float over double or double over long double i am still a beginner at programming and i always have more questions than our book or internet searches can answer unless i missed something so i apologize in advance if this was answered but i could not find iti understand that float has a smaller range than double making it less precise and from what i understand long double is even more precise so my question is why would you want to use a variable that is less precise in the first place does it have something to do with different platforms different os versions different compilers or are there specific moments in programming where its strategically more advantageous to use a float over a doublelong doublethanks everyone,['c++'] +505746,how to get when an imageview is completely loaded in android i am developing an app which draws lines over a bunch of images to choose these images i have a radio group and whenever the user clicks in a radio button the image is load with all its own drawingsin my radio listenner i have the following codebitmap bitmaputilsdecodesampledbitmapfromresourceroot definesandroidcaminho shoppings sdcard nomeimagematual sizex sizeymimagesetimagebitmapbitmapmimagesetdrawlinestruemimagesetimagebitmaploadbitmapfromviewmimagethe decodesampledbitmapfromresource method i got from this link on android developers it loads bitmaps more effitiently and heres the method i call to get a bitmap of a view public static bitmap loadbitmapfromviewview v bitmap b bitmapcreatebitmap vgetlayoutparamswidth vgetlayoutparamsheight bitmapconfigargb 8 canvas c new canvasb vlayout0 0 vgetlayoutparamswidth vgetlayoutparamsheight vdrawc return bi am setting the image bitmap of mimage because i am using imageviewtouch library which enables pinch zooming over an imageview and if i do not do it all the canvas drawing is deleted with any interaction over the image like zooming inout the error log is the following0711 211341567 eandroidruntime20056 javalangillegalargumentexception width and height must be 00711 211341567 eandroidruntime20056 at androidgraphicsbitmapcreatebitmapbitmapjava6380711 211341567 eandroidruntime20056 at androidgraphicsbitmapcreatebitmapbitmapjava620i am almost sure that this error is occuring cause the image bitmap is not completely loaded when i call getbitmapfromview method how can i know when the view is loaded completely,['android'] +505750,log inside sidekiq worker i am trying to log the progress of my sideqik worker using tail f logdevelopmentlog in development and heroku logs in productionhowever everything inside the worker and everything called by the worker does not get logged in the code below only test 1 gets loggedhow can i log everything inside the worker and the classes the worker calls appcontrollerstaskscontrollerrbdef import data railsloggerinfo test 1 shows up in developmentlog dataimportworkerperform async render done end appworkersdataimportworkerrbclass dataimportworker include sidekiqworker def perform railsloggerinfo test 2 does not show up in developmentlog importer importernew importerimport data endend appcontrollersservicesimporterrb class importer def import data railsloggerinfo test 3 does not show up in developmentlog endendupdatei still do not understand why railsloggerinfo or sidekiqloggerinfo do not log into the log stream got it working by replacing railsloggerinfo with puts,"['ruby-on-rails', 'ruby']" +505789,mixing static and dynamic sections in a grouped table view i need a grouped uitableview similar to the one for twitter accounts in settings appthat is a sort of form or menu where some of the sections have a beforehand known set of static cells and some other sections have to be dynamic and allow inserting additional rows the same way the add account does here i am managing the uitableview in a xib file for the static cells i have separated xib files that i can load within the cellforrowatindexpath method in the view controllerhow should i handle this kind of table i dona t find any example code how the cellforrowatindexpath method should look like may i need to keep strong properties for the static cells would it be better to design each static cell directly within the same xib file where the table view is and to set outlets for them though this does not allow to reuse my custom cells designi need some guidelines for achieving this and correctly managing cells and memory thanks in advance,['ios'] +505791,why is nodejs asynchronous nobody has actually asked this from all the suggestions i am getting and also from searching before i asked hereso why is nodejs asynchronousfrom what i have deduced after some researchlanguages like php and python are scripting languages i could be wrong about the actual languages that are scripting languages whilst javascript is not i suppose this derives from the fact that js does not compilenodejs runs on a single thread whilst scripting languages use multiple threadsasynchronous means stateless and that the connection is persistent whilst synchronous is the almost oppositemaybe the answer is found somewhere stated above but i am still not suremy second and last question related to this topic is thiscould javascript be made into a synchronous languageps i know some of you will ask why would you want to make js synchronous in your answers but the truth is that i do not i am just asking these types of questions because i am sure there are more people out there than just myself that have thought about such questions,['javascript'] +505832,how to change the text color of first select option i have a select element which has several items i want to change the color of its first item but it seems the color only showswhen you click on the select dropdown what i want is changed the colorlike color graywhen the page is loaded so users can see the first option color changedsee the example herethanks for the answer it is the very first time i post question heresorry about my english i hope that i make the question clear thanks,['css'] +505967,php handling jsonp output vs json and its parsing i am having a problem parsing jsonp request with phps json decode functionmy questions is a what is the use of call back function in jsonp should i just trip that off or am i suppose to use it in some manner b how can i rectify the syntax error received in jsonp format below i have given the code and the response that i get1 i request a sample url with phps curl url ch curl initcurl setoptch curlopt url url curl setoptch curlopt returntransfer 1 curl setoptch curlopt connecttimeout 5 curl setoptch curlopt ssl verifypeer false curl setoptch curlopt useragent mozilla40 compatible msie 501 windows nt 50 feed curl execchcurl closechecho feed gzdecodefeed success its thisplays the jsonp feed2 then i try to json decode the received output which throws the error no 4 meaning json syntax error the reason i guess is because names of string type in jsonp are not quoted eg categories name position etcjson feed json decodefeederror json last error echo error throws error no 43 raw jsonp output from the urldomain jsonp callback categories nameartifacts position14 count70 imageurls i100s3euwest1amazonawscomsdomaincom1png i120s3euwest1amazonawscomsdomaincom2png i140s3euwest1amazonawscomsdomaincom3png i180s3euwest1amazonawscomsdomaincom4png i220s3euwest1amazonawscomsdomaincom5png i280s3euwest1amazonawscomsdomaincom6png,['php'] +505995,android google maps api v2 center markers is there a way to make a map zoom in as far as possible but keeping all of the markers on screen at the same time i have six markers in a non uniform shape i was thinking of just taking their centre and locating the map to that but i still then do not know how far programmatically i can zoom in the mapthese markers change location every time the map is created ideally i would have a script that zooms the map in so all are included in the viewso you understand i am creating the markers one at a time from json with the following line in a loopmmapaddmarkernew markeroptionspositionnew latlnglatlngtitlecgetstringtitle,"['java', 'android']" +506004,convert existing project to library project in android studio how can i convert an existing android project into an android library project in android studio in eclipse that is possibleactually i want to convert an old android project into an android library project so that i can use existing code of that android project to build a new android project with minor changes in android studio,['android'] +506019,change html5 videoas quality from javascript in youtube we can change the quality of the video from a dropdown like 360p 144p 240p etc can we do the same with html5 video element from javascript,['javascript'] +506029,what is the best approach in python multiple or or in in if statement what is the best approach in python multiple or or in in if statement considering performance and best praticesif cond 1 or cond 2 or cond 3 or cond 4 etc orif cond in 1234thank you,['python'] +506073,best way of creating large bit arrays in lua i want to read a large binary file 1mb in size into memory using lua the target device is mobile so i very much want to minimise the memory footprintfrom a quick look online it seems that lua tabels will use 16b for each sequential integer index key plus the space to store the value which as i am storing binary data will hopefully only use 2 bits but lets just say 1 byte for 1e6 records that will be 1e617 17mb which is hugefrom my brief reading it seems that i can use userdata to implement anything i want in c i have not used c before but it seems that it would use1b 1e6 125kbshall i do this or have i got something very wrong is there an easier way to do this any advice or even namecalling for crappy calculations very much welcome edit some interesting answers below about storing the data in a string thanks and using bitwise ops i just came accross an example in the pil book 3rd edition pg293 that compares storing arrays of booleans in c so they use 3 of the mem while this is cool and useful it may be overkill for me as the solutions below suggest i can fit in 1mb which is fine for meedit came across this c blob impl edit solution i read the file contents into a string as suggested and as im using 51 had to use a 3rd party bit op lib i went with a pure lua implementation luabit thanks everyone,['c'] +506075,cannot resolve the collation conflict between i have moved one of our databases db1 from sql server 2008 to 2012 and when i run the stored procedures i get the following errorcannot resolve the collation conflict between sql latin1 general cp1 ci as and latin1 general ci as in the equal to operationi changed the collation on the database using alter database optimiser set single user with rollback immediatealter database optimiser collate sql latin1 general cp1 ci asalter database optimiser set multi userbut i still get the error whenever the stored procedures run i believe because the sp is using a join to another database ges ihistorian and it has a collation mismatch is there anyway to resolve thison the old server db1 was set as latin1 general ci as and this works fine the new location for the db has a default of sql latin1 general cp1 ci as is it worth changing the collation and db1 on the new server back to latin1 general ci as,['sql'] +506080,opencv videocapture cannot read from my webcam at all i am using opencv 246 on ubuntu 1304 on an acer c7 chromebook and i am using a simple test program to see if my webcam will work with opencv it works fine with cheese and skype so i know that the webcam itself is not the issuehere is my code which compiles without any errorsinclude opencv2opencvhppinclude stdiohinclude stdlibhusing namespace stdusing namespace cvint mainint argc char argv cvvideocapture cap ifargc 1 capopenstringargv1 else capopencv cap any ifcapisopened printferror could not load a camera or videon mat frame namedwindowvideo 1 for waitkey20 cap frame ifframedata printferror no frame datan break imshowvideo frame if i run the program without any arguments since i want it to use cv cap any i geterror could not load a camera or videoinit done opengl support available libpng warning application built with libpng1249 but running with 1512libpng warning application built with libpng1249 but running with 1512libpng warning application built with libpng1249 but running with 1512libpng warning application built with libpng1249 but running with 1512libpng warning application built with libpng1249 but running with 1512libpng warning application built with libpng1249 but running with 1512libpng warning application built with libpng1249 but running with 1512libpng warning application built with libpng1249 but running with 1512libpng warning application built with libpng1249 but running with 1512libpng warning application built with libpng1249 but running with 1512error no frame dataif i specify devvideo0 my only camera as the argument i getdemux wavpack open wv file127 open wv file nonseekable inputs are not supported yeterroricvopenavi xine unable to open source devvideo0init done opengl support available libpng warning application built with libpng1249 but running with 1512libpng warning application built with libpng1249 but running with 1512libpng warning application built with libpng1249 but running with 1512libpng warning application built with libpng1249 but running with 1512libpng warning application built with libpng1249 but running with 1512libpng warning application built with libpng1249 but running with 1512libpng warning application built with libpng1249 but running with 1512libpng warning application built with libpng1249 but running with 1512libpng warning application built with libpng1249 but running with 1512libpng warning application built with libpng1249 but running with 1512gstreamer plugin embedded video playback halted module source reported could not read from resourceerror no frame dataif i specify the path to a video file as the argument it plays the video just finei would appreciate any help thanks in advance,['c++'] +506087,true random numbers with c11 and rdrand i have seen that intel seems to have included a new assembly function to get real random numbers obtained from hardware the name of the instruction is rdrand but only a small amount of details seem accessible on it on internet my questions concerning this new instruction and its use in c11 are the followingare the random numbers generated with rdrand really random each bit generated from uncorrelated white noise or quantum processes is it a special feature of ivy bridge processors and will intel continue to implement this function in the next generation of cpuhow to use it through c11 maybe with stdrandom device but do compilers already call rdrand if the instruction is availablehow to check whether rdrand is really called when i compile a program,['c++'] +506101,pretty printing json from jackson 22s objectmapper right now i have an instance of orgfasterxmljacksondatabindobjectmapper and would like to get a string with pretty json all of the results of my google searches have come up with jackson 1x ways of doing this and i cannot seem to find the proper nondeprecated way of doing this with 22 even though i do not believe that code is absolutely necessary for this question heres what i have right nowobjectmapper mapper new objectmappermappersetserializationinclusionincludenon nullsystemoutprintlnrequeststringwriter sw new stringwritermapperwritevaluesw jsonobject want pretty version of swtostring here,['java'] +506109,set default value of an integer column sqlite i am creating an sqlite database in android dbexecsqlcreate table database table key rowid integer primary key autoincrement key name text not null key worked integer key note integeris it possible to set the default value of key note which is an integer for every row created to be 0 zero if so what should be the correct code,['android'] +506190,access to thisposed closure in c i am investigating microsoft enterprise library data application block the samples slnthey have a sample of reading data asynchronously iasync although the new ver 6 also support asyncbut resharperor visual studio nevermind shows me access to thisposed closure first i will show the image so it will be clearer then i will paste the code code 1 descriptionexecute a command that retrieves data asynchronously2 static void readdataasynchronously3 4 if supportsasyncasyncdb return5 6 usingvar donewaitingevent new manualreseteventfalse7 usingvar readcompleteevent new manualreseteventfalse8 9 try10 11 create command to execute stored procedure and add parameters12 dbcommand cmd asyncdbgetstoredproccommandlistordersslowly13 asyncdbaddinparametercmd state dbtypestring colorado14 asyncdbaddinparametercmd status dbtypestring draft15 execute the query asynchronously specifying the command and the16 expression to execute when the data access process completes17 asyncdbbeginexecutereadercmd18 asyncresult 19 20 lambda expression executed when the data access completes21 donewaitingeventset22 try23 24 usingidatareader reader asyncdbendexecutereaderasyncresult25 26 consolewriteline27 consolewriteline28 thisplayrowvaluesreader29 30 31 catch exception ex32 33 consolewritelineerror after data access completed 0 exmessage34 35 finally36 37 readcompleteeventset38 39 null40 41 thisplay waiting messages to indicate executing asynchronouly42 while donewaitingeventwaitone1043 44 consolewritewaiting 45 46 47 allow async thread to write results before thisplaying continue prompt48 readcompleteeventwaitone49 50 catch exception ex51 52 consolewritelineerror while starting data access 0 exmessage53 54 55 question why is it giving this warning there is a manualresetcheckedsignal which runs in a loop which prevents the using clause to be reached which means no thispose will call so why does it yell warning,"['c#', '.net']" +506193,is it okay to use junit assert api in java production code i want to do null checks for my method arguments like parameters should not be null is it okay to use something like this assertnotnullmap should not be null filepaths in my java codei am trying to avoid iffilepaths null throw new illegalargumentexceptionmaps cannot be nulljust to keep my code clean from all those null checks i know i can write a validator class of my own and have overloaded notnull methods but is there something existing and simple to use to not reinvent the wheelthe only drawback i see of using junit assert is that it throws assertionerror and not illegalargumentexception and so forth,['java'] +506260,codemirror html mode not working i am trying to style code samples with codemirror but it works partially it applies the selected theme to the textarea but the syntax is not highlightedthere is my pagetextarea idtemplatehtml namecode classcodemirror doctype html foobar blahenter your xml here and press the button below to thisplay it as highlighted by the codemirror xml modeblah tag2 foo2 barbar foobartextarealink relstylesheet typetextcss hrefsitecomcsscodemirrorcodemirrorcsslink relstylesheet typetextcss hrefsitecomcsscodemirrorthemeambiancecsslink relstylesheet typetextcss hrefsitecomcsscodemirrorthemesolarizedcscript typetextjavascript srcsitecomjslibscodemirrorcodemirrorjsscriptscript typetextjavascript srcsitecomjslibscodemirrormodejavascriptjavascriptjsscriptscript typetextjavascript var config editor config linenumbers true mode texthtml theme ambiance indentwithtabs false readonly true editor codemirrorfromtextareadocumentgetelementbyidtemplatehtml config function selecttheme editorsetoptiontheme solarized dark settimeoutselecttheme 50scripthere is an image of the result it seems to work but without the syntax highlighting image top i have also tried without my css but the result is the same image bottomthe problem is with mode texthtml which seems to be not working properly if i use mode javascript it colorizes the tags by the javascript syntax rules how can i fix this,['javascript'] +506263,java generics restrict to interface i am not sure if this is possible or not but what i want to accomplish is thispublic static ab extends someclass a b makeba thing essentially using a reflectiongeneration driven process i want to provide a thing of type b where b is of class someclass and implements interface a and a is usersupplied through genericsi am not asking about the mechanics of generating b i have that under control what i am looking for is a way to restrict generic type argument a to interfaces not classes so that i can use the syntax b extends someclass a for clean type safetyis this possible is anyone aware of an alternative approach to this problemedit i guess i did not express myself very clearly as it seems to be causing confusion in the commentsb is intended to be a placeholder for a wildcard so that the client can get a single object that is both a someclass and an a without having to do casting based on trust the client will not have access to the name of the actual class that implements someclass and a because it is being generated at compile time hence this issue regarding type safety,['java'] +506321,c friend constructor i have two classes point that lives only in spaceclass pointprivate pointconst space space int x0 int y0 int z0 int x y z const space m spacethe constructor is intentionally private i do not want it to be called directlyi would like to create points this wayspace myspacepoint mypoint myspacepoint573is there any way to do so thanks,['c++'] +506382,get views frame in uiview that is not superview i would think this is a simple question but i cannot seem to find a way to do this i have a view that is a subview of my uiviewcontroller within that view i have another view to clarify this is the architectureuiviewcontrollerviewsubview asubview bi want to get the frame of subview b within uiviewcontrollerviewis this possible subviewbframe gives me the frame of the view within subview a,"['ios', 'objective-c']" +506387,concatenate a number and in sass i would like to do the following using sasswidth percentwhere percent is a variable containing a number if percent is equal to 50 the precompiled css would bewidth 50what syntax should i use,['css'] +506419,codeigniter setting up directories and files permissions chmod settings since i do not think i got right permissions all over my application folders and files is there anyway to check the right permissions allover themi mean does anyone knowshas a standardtutoriallink to follow for codeigniter to set chmod permissionsthanks any help appriaciatednb when i say allover i mean from the root to all files the application system folders contains also to specify little bit i think i got problems with permissions cause i passed my application through different os and for example macosx setted different permissions on directories than windows etc so it is sort of a hell actually this is my app schemaproject application system css img vendor indexphp htaccess,['php'] +506431,how can i use xbuild to build release binary when i use xbuild it always use debug as target how do i make it use releasefor example i would expect something likexbuild releasebut that does not work,['c#'] +506432,file explorer in android studio can anyone tell where the file explorer is located in android studio i tried to search in windows menu but there is not any option like show view that used to be in eclipse,['android'] +506442,how to clear buffer in receiving multiple strings if i enter str1 longer than length 10 the rest of it remains in the buffer and gets entered into my str2 how to clear the buffer before str2 so i can input itinclude stdiohint mainvoid char str110 char str210 fgetsstr110stdin fgetsstr210stdin putsstr1 putsstr2 return 0,['c'] +506446,how to place datatables column filter on top i am using jquery datatables latest version i want to use individual column filter on every table so am using the column filter plugin but am getting search boxes in footer only i want to place in the header documentreadyfunction var otableexampledatatable bjqueryui true sscrollx 100 alengthmenu 5 15 50 100 5 15 50 l00 ithisplaylength 10 spaginationtype full numbers sdom topifrtbottomlpclear columnfiltersplaceholderhead before aocolumns type text type text null null null null type text null type text type text type text how can i place it on the top of my table,['jquery'] +506452,java library for testing web services i have junit tests for rest web services now i think that junit is not the best tool for that since these tests are integration tests but not unit tests so i probably need a java library which helps to send http requests verify http responses create reports and do that in parallelon the other hand maybe i am mistaken and junit with httpunit etc is good enough and i do not need other toolswhat would you suggest,['java'] +506461,deep clone of hibernate entity i am wondering how can i create a deep copy of a persisted object with all of its associationlet say i have the following modelclass document string title string content person owner setcitation citationsclass person string name setdocument documentsclass citation string title date date setdocument documentsi have a scenario in which a user might want to grab a copy of a particular document from a person and make the document hishers then later he she can change its content and namein that case i can think of one way to implement that kind of scenario which is creating a deep copy of that document with its associationsor maybe if anyone knows of any other possible way to do such thing without doing huge copy of data because i know it may be bad for the app performancei was also thinking of may be creating a reference of to the original document like having an attribute originaldocument but that way i would not be able to know which attribute or maybe association has been changed,['java'] +506478,does cloning a prototype object provide performance improvement over creating objects from scratch you can see two simplified snippets below that do not vary in their outcomepattern 1 objects from scratchforeach recipients as recipient message new message messagesetbodythis is the body of the message messagesetrecipientrecipient transportsendmessagemessage persistersavetodatabasemessage updated line unsetmessagepattern 2 cloning a prototype objectprototype new messageprototypesetbodythis is the body of the messageforeach recipients as recipient message clone prototype messagesetrecipientrecipient transportsendmessagemessage persistersavetodatabasemessage updated line unsetmessageunsetprototypedoes the object cloning pattern 2 provide performance improvements over creating objects from scratch pattern 1 in terms of memory usage garbage collection andor cpu cycles consider also high number of fixed properties that do not change between the instances and high number of loopsupdate i need different object instances in each loop i added savetodatabase call to the examples to resemble that let it for example give an id to the message,['php'] +506480,css circle with four colors and only one div is it possible to create a circle with four different colors one for each quarter using pure cssi want something like one of these four circlesi can imagine using a solution with four divs and borderradius but is this possible using only one div and some fancy css3,['css'] +506482,remove specific element from array in knockoutjs i am creating a multiplayer game over network so i have to react on network events i have this simple code but the removeplayer method doesnt work the addplayer works finetable iduserlist2 classtablesorter cellspacing0 thead tr thnameth thqueueth thpointsth tr thead tbody databindforeach players tr td databindtext nametd td databindtext queuetd td databindtext scoretd tr tbodytablefunction playerviewmodel var self this selfplayers koobservablearray selfaddplayer function name queuepos score selfplayerspush name name queue queuepos score score selfremoveplayer function name for var i 0 i selfplayerslength i if selfplayersiname name consolelogi selfplayerssplicei 1 players new playerviewmodelkoapplybindingsplayersplayersaddplayerplayer1 0 0playersaddplayerplayer2 0 0playersremoveplayerplayer2heres the,"['javascript', 'html']" +506485,laravel 4 cannot run whole raw queries i would like to use the db class of laravel to execute a mysql query but none of the functions provided by laravel are workingnone of those is working dbstatment dbselect dbraw dbupdate dbselectdbrawhere is the code i would like to querydrop table userscreate table users id int10 unsigned not null auto increment u username varchar255 collate utf8 unicode ci not null u email varchar255 collate utf8 unicode ci not null password varchar255 collate utf8 unicode ci not null u regdate datetime not null default 0 0 u birthday date not null default 0 u lastlogin int11 not null u logcout int11 not null default 0 u level tinyint1 not null default 0 u language tinyint1 not null default 0 u status tinyint1 not null default 0 u gender tinyint1 not null default 0 primary key id engineinnodb auto increment6 default charsetutf8 collateutf8 unicode ciinsert into users values1admin2y089sbjh7iyf9yr6xvsienmbosotgpbkzfydvjbyk5fzh4igbvo7je60 090insert into users values2moderator2y0815tikpm8gatszkmey5tuaapl4ljefq7litetyz0h1dkootwp3g0 0insert into users values3helper2y08nttzu9uberlbyjroxwce2db57ofx2bcn8vgeihkqobpra0wt60 0insert into users values4dude122y08y0jwektwxjfrf7ko8q0zkodyewekjcr1ddco6acjh8sskdzq6rc0 0insert into users values5girl12y08ukjjzxduyw7upqelsm1vo2juoqmaai01jfxvldzc6ewjin3yoe0 0i have looked and tried methods from those two topics too but nothing is workingcannotrunrawqueryinlaravel4laravel4howtorunarawsqlerror returned when executing with dbselect dbrawquery or dbstatement sqlstate420 syntax error or access violation 1064 you have an error in your sql syntax check the manual that corresponds to your mysql server version for the right syntax to use near create table users id int10 unsigned not null auto increment u use at line 3 sql drop table users create table users id int10 unsigned not null auto increment u username varchar255 collate utf8 unicode ci not null u email varchar255 collate utf8 unicode ci not null password varchar255 collate utf8 unicode ci not null u regdate datetime not null default 0 0 u birthday date not null default 0 u lastlogin int11 not null u logcout int11 not null default 0 u level tinyint1 not null default 0 u language tinyint1 not null default 0 u status tinyint1 not null default 0 u gender tinyint1 not null default 0 primary key id engineinnodb auto increment6 default charsetutf8 collateutf8 unicode ci insert into users values1admin2y089sbjh7iyf9yr6xvsienmbosotgpbkzfydvjbyk5fzh4igbvo7je60 090 insert into users values2moderator2y0815tikpm8gatszkmey5tuaapl4ljefq7litetyz0h1dkootwp3g0 0 insert into users values3helper2y08nttzu9uberlbyjroxwce2db57ofx2bcn8vgeihkqobpra0wt60 0 insert into users values4dude122y08y0jwektwxjfrf7ko8q0zkodyewekjcr1ddco6acjh8sskdzq6rc0 0 insert into users values5girl12y08ukjjzxduyw7upqelsm1vo2juoqmaai01jfxvldzc6ewjin3yoe0 0 bindings array,"['php', 'mysql']" +506515,implementing a new strcpy function redefines the library function strcpy it is said that we can write multiple declarations but only one definition now if i implement my own strcpy function with the same prototype char strcpy char destination const char source then am i not redefining the existing library function should not this thisplay an error or is it somehow related to the fact that the library functions are provided in object code formedit running the following code on my machine says segmentation fault core dumped i am working on linux and have compiled without using any flagsinclude stdiohinclude stdlibhinclude stringhchar strcpychar destination const char sourceint main char s strcpya b printfnthe function ran successfullyn return 0char strcpychar destination const char source printfin duplicate function strcpy return aplease note that i am not trying to implement the function i am just trying to redefine a function and asking for the consequencesedit 2after applying the suggested changes by mats the program no longer gives a segmentation fault although i am still redefining the functioninclude stdiohinclude stdlibhinclude stringhchar strcpychar destination const char sourceint main char s strcpya b printfnthe function ran successfullyn return 0char strcpychar destination const char source printfin duplicate function strcpy return a,['c'] +506536,python how to read output from pexpect child child pexpectspawn binbashchildsendlinelsprintchildreadlineprint childbefore childafterall i get with this code in my output is lsls but when my code is child pexpectspawnlsprintchildreadlineprint childbefore childafterthen it works but only for the first 2 prints am i using the wrong send command i tried send write sendline and could not find anymore,['python'] +506595,uncaught referenceerror myfunction is not defined at null1 android exception in webview i am calling javascript function from an activity but i am getting uncaught referenceerror myfunction is not defined at null1 error here is my files mainactivityjavapackage comexampleandroidexampleimport androidosbundleimport androidappactivityimport androidcontentcontextimport androidviewmenuimport androidwebkitwebchromeclientimport androidwebkitwebsettingsimport androidwebkitwebviewimport androidwebkitwebviewclientimport androidwidgettoastpublic class mainactivity extends activity override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main webview webview webviewthisfindviewbyidridwebview1 websettings websettings webviewgetsettings enable javascript for interaction websettingssetjavascriptenabledtrue make the zoom controls visible websettingssetbuiltinzoomcontrolstrue allow for touching selectingdeselecting data series webviewrequestfocusfromtouch set the client webviewsetwebviewclientnew webviewclient webviewsetwebchromeclientnew webchromeclient webviewloadurlfileandroid assettesthtml string str books book titlea tale of two cities book title1984 books webviewloadurlfileandroid assettesthtml webviewloadurljavascriptmyfunction webviewloadurljavascriptmyfunctionstr override public boolean oncreateoptionsmenumenu menu inflate the menu this adds items to the action bar if it is present getmenuinflaterinflatermenumain menu return true testhtmlhtmlbodyscript typetextjavascript srcmarknotejsscriptscript typetextjavascriptfunction myfunctionvar str booksbookbookbooksvar parser new marknoteparservar doc parserparsestrvar bookels docgetrootelementgetchildelements for var i0 ibookelslength i var bookel bookelsi alertelement name is bookelgetname scriptbodyhtmli have seen this error occurred when i am using webviewloadurljavascriptmyfunction i want to pass a xml string from java and parse it into javascript please help me to find a solution,"['javascript', 'android']" +506625,canvas trying to use a recycled bitmap android i am continously having this problem and i do not know what to do about iti have used this library and when i get the cropped image i save it in a static variable and move to the next activity when i arrive in the next activity i reference that static variable to get the bitmap and try to scale it down but it gives me errorheres what i am doingpublic void buttoncropclickview view throws ioexception imageviewsetdrawingcacheenabledtrue imageviewbuilddrawingcachetrue snapshotcroppedbitmap imageviewgetdrawingcachetrue imageviewsetdrawingcacheenabledfalse startactivitynew intentthisrecommendationinfoclassin the recommendationinfo class i get the bitmap in the following line snapshotcroppedbitmap imageviewgetdrawingcachetrue then i save this bitmap in the static variable which i reference in next activity and pass it to the following functionpublic static bitmap scaledownbitmap realimageboolean filter float maximagesize heighttoset float ratio mathmin float maximagesize realimagegetwidth float maximagesize realimagegetheight int width mathroundfloat ratio realimagegetwidth int height mathroundfloat ratio realimagegetheight error here bitmap newbitmap bitmapcreatescaledbitmaprealimage widthheight filter return newbitmapi already tried calling bitmaprecycle why am i getting this problem what can i do to solve it heres my logcat0714 030943713 eandroidruntime19653 fatal exception main0714 030943713 eandroidruntime19653 javalangruntimeexception canvas trying to use a recycled bitmap androidgraphicsbitmap4059b8b80714 030943713 eandroidruntime19653 at androidgraphicscanvasthrowifrecycledcanvasjava9550714 030943713 eandroidruntime19653 at androidgraphicscanvasdrawbitmapcanvasjava10120714 030943713 eandroidruntime19653 at androidgraphicsbitmapcreatebitmapbitmapjava4620714 030943713 eandroidruntime19653 at androidgraphicsbitmapcreatescaledbitmapbitmapjava3490714 030943713 eandroidruntime19653 at comexamplelibrariessnapshotscaledownsnapshotjava420714 030943713 eandroidruntime19653 at comexampleandroidtestprojectrecommendationinfosetrecommendationvaluesrecommendationinfojava1950714 030943713 eandroidruntime19653 at comexampleandroidtestprojectrecommendationinfoaccess5recommendationinfojava1830714 030943713 eandroidruntime19653 at comexampleandroidtestprojectrecommendationinfo1onclickrecommendationinfojava1540714 030943713 eandroidruntime19653 at androidviewviewperformclickviewjava25520714 030943713 eandroidruntime19653 at androidviewviewperformclickrunviewjava92290714 030943713 eandroidruntime19653 at androidoshandlerhandlecallbackhandlerjava5870714 030943713 eandroidruntime19653 at androidoshandlerthispatchmessagehandlerjava920714 030943713 eandroidruntime19653 at androidoslooperlooplooperjava1380714 030943713 eandroidruntime19653 at androidappactivitythreadmainactivitythreadjava37010714 030943713 eandroidruntime19653 at javalangreflectmethodinvokenativenative method0714 030943713 eandroidruntime19653 at javalangreflectmethodinvokemethodjava5070714 030943713 eandroidruntime19653 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava8780714 030943713 eandroidruntime19653 at comandroidinternaloszygoteinitmainzygoteinitjava6360714 030943713 eandroidruntime19653 at dalviksystemnativestartmainnative method0714 030945515 etag20039 end of input at character 0 of,['android'] +506645,how to wait for a single event in c with timeout and cancellation so my requirement is to have my function wait for the first instance an event actiont coming from another class and another thread and handle it on my thread allowing the wait to be interrupted by either timeout or cancellationtoken i want to create a generic function i can reuse i managed to create a couple options that do i think what i need but both seem more complicated than i would imagine it should have to beusagejust to be clear a sample use of this function would look like this where serialdevice is spitting out events on a separate threadvar eventoccurred helperwaitforsingleeventstatuspacket cancellationtoken statuspacket onstatuspacketreceivedstatuspacket a serialdevicestatuspacketreceived a a serialdevicestatuspacketreceived a 50 serialdevicerequeststatuspacketoption 1amanualreseteventslimthis option is not bad but the thispose handling of the manualreseteventslim is messier than it seems like it should be it gives resharper fits that i am accessing modifiedthisposed things within the closure and it is genuinely hard to follow so i am not even sure it is correct maybe there is something i am missing that can clean this up which would be my preference but i do not see it offhand heres the codepublic static bool waitforsingleeventteventthis cancellationtoken token actiontevent handler actionactiontevent subscribe actionactiontevent unsubscribe int mstimeout action initializer null var eventoccurred false var eventresult defaulttevent var o new object var slim new manualreseteventslim actiontevent setresult result lock o ensures we get the first event only if eventoccurred eventresult result eventoccurred true resharper thisable accesstomodifiedclosure resharper thisable accesstothisposedclosure if slim null slimset resharper restore accesstothisposedclosure resharper restore accesstomodifiedclosure subscribesetresult try if initializer null initializer slimwaitmstimeout token finally ensures unsubscription in case of exception unsubscribesetresult locko ensure we do not access slim slimthispose slim null lock o ensures our variables do not get changed in middle of things if eventoccurred handlereventresult return eventoccurred option 2apolling without a waithandlethe waitforsingleevent function here is much cleaner i am able to use concurrentqueue and thus do not even need a lock but i just do not like the polling function sleep and i do not see any way around it with this approach i would like to pass in a waithandle instead of a funcbool to clean up sleep but the second i do that i have got the whole thispose mess to clean up againpublic static bool waitforsingleeventteventthis cancellationtoken token actiontevent handler actionactiontevent subscribe actionactiontevent unsubscribe int mstimeout action initializer null var q new concurrentqueuetevent subscribeqenqueue try if initializer null initializer tokensleepmstimeout qisempty finally ensures unsubscription in case of exception unsubscribeqenqueue tevent eventresult var eventoccurred qtrydequeueout eventresult if eventoccurred handlereventresult return eventoccurredpublic static void sleepthis cancellationtoken token int ms funcbool exitcondition var start datetimenow while datetimenow starttotalmilliseconds ms exitcondition tokenthrowifcancellationrequested threadsleep1 the questioni do not particularly care for either of these solutions nor am i 100 sure either of them are 100 correct is either one of these solutions better than the other idiomaticity efficiency etc or is there an easier way or builtin function to meet what i need to do hereupdate best answer so fara modification of the taskcompletionsource solution below no long closures locks or anything required seems pretty straightforward any errors herepublic static bool waitforsingleeventteventthis cancellationtoken token actiontevent onevent actionactiontevent subscribe actionactiontevent unsubscribe int mstimeout action initializer null var tcs new taskcompletionsourcetevent actiontevent handler result tcstrysetresultresult var task tcstask subscribehandler try if initializer null initializer taskwaitmstimeout token finally unsubscribehandler do not thispose task if taskstatus taskstatusrantocompletion oneventtaskresult return true return falseupdate 2 another great solutionturns out that blockingcollection works just like concurrentqueue but also has methods accepting a timeout and cancellation token one nice thing about this solution is that it can be updated to make a waitfornevents fairly easilypublic static bool waitforsingleeventteventthis cancellationtoken token actiontevent handler actionactiontevent subscribe actionactiontevent unsubscribe int mstimeout action initializer null var q new blockingcollectiontevent actiontevent add item qtryadditem subscribeadd try if initializer null initializer tevent eventresult if qtrytakeout eventresult mstimeout token handlereventresult return true return false finally unsubscribeadd qthispose,['c#'] +506676,play audio and restart it onclick i am looking to restart an audio file in a html5 audio player i have defined a audio file and a play buttonaudio idaudio1 src01wavaudiobutton onclickplayplaybuttonwhen i click the play button the audio file starts playing but when i click the button again the audio file does not stop and will not play again until it reaches the end of the filefunction play documentgetelementbyidaudio1playis there a method that would allow me to restart the audio file when i click the button using onclick rather than waiting for the song to stop,"['javascript', 'html']" +506689,nice way to append a vector to itself i want to duplicate the contents of the vector and want them to be appended at the end of the original vector ie vivin for i02n1i am looking for a nice way to do it not with a loop i saw stdvectorinsert but the iterative version forbids a iterator to thisie behaviour is undefinedi also tried stdcopy as followsbut it resulted in segmentation faultcopy xxbegin xxend xxend,['c++'] +506720,release version of apk in android studio i want to submite an application to google market i found there is only one apk file generated in a project its path is project1projectproject1buildapkproject1debugunalignedapkit looks like it is a debug version where do i find if any a release version of an application or how do i generate it,['android'] +506727,javascript runtime error is undefined i have added script in my defaultaspx page i am getting following error,"['javascript', 'jquery', 'asp.net']" +506754,jquery show and hide div on mouse click animate this is my html codediv idshowmenuclick heredivdiv classmenu stylethisplay none ul libutton1li libutton2li libutton3li uldivand i want to show menu on click on showmenu sliding from left to right with animate on click again on showmenu or anywhere in site page menu will hide slide back to lefti use jquery 203i have tried this but it does not do what i wantdocumentreadyfunction showmenutoggle function menuslidedownfast function menuslideupfast can anyone help melots of thanks in advance,"['javascript', 'jquery']" +506776,linking d library to c code recently i learned the beautiful language d which is so more plastic and helps yourself writing stable fast programs but its not popular because few code written on d and so more on c and c therefore after i read the book of andrei alexanderscu where author very superficially described question about linking of d library to c code i tried learn it myself and written some code on d where defined function that returns an instance of completeautomata class which implements automatainterface defined also in c codeifndef automatainterface hdefine automatainterface hclass automatainterface public virtual automatainterface virtual void next 0 virtual void save 0 virtual void restore 0 virtual void zerofile 0 virtual void invertunsigned long x unsigned long y 0 virtual int stateunsigned long x unsigned long y const 0 virtual unsigned long x const 0 virtual unsigned long y const 0automatainterface createautomataunsigned long x unsigned long yendif automatainterface hrelevant d codeimport agregator this is my own libexternc interface automatainterface void next void save void restore void zerofile void invertsize t x size t y int statesize t x size t y const size t x const size t y const automatainterface createautomataulong x ulong y return new completeautomatax y export class completeautomata automatainterface instance variables thissize t x size t y externc override void next others overridden interface methods after code had written i have compiling of d library by two different compilers dmd and gdc with following flagsdmd release o lib odlib ofliblifeh dorgdc frelease o2 wall c dar cq libliblifea owhen i trying link each of received libs to qt project by adding path to library dir l option and adding a lib directly l option i got errors of in both casesin first dmd case i have undefined reference to d newclass and couple of another errorsg wlo1 wlzrelro o automata maino mainwindowo renderareao buttono playbuttono moc mainwindowo moc renderareao moc buttono moc playbuttono lhomenewmenprojectsdlifelib llife lqtgui lqtcore lpthread homenewmenprojectsdlifelibliblifeacomplete automata 1fe 5b0o in function createautomataunsigned int unsigned intcomplete automatadtext z14createautomatajj0x27 undefined reference to d newclasshomenewmenprojectsdlifelibliblifeacomplete automata 1ff 675odata0x0 undefined reference to d14typeinfo class6 vtblzhomenewmenprojectsdlifelibliblifeacomplete automata 1ff 675odata0x50 undefined reference to d6object7 classzhomenewmenprojectsdlifelibliblifeacomplete automata 1ff 675odata0xd0 undefined reference to d14typeinfo class6 vtblzhomenewmenprojectsdlifelibliblifeacomplete automata 1ff 675odata0x120 undefined reference to d6object7 classzhomenewmenprojectsdlifelibliblifeacomplete automata 1ff 675orodata0x68 undefined reference to d6object6object8tostringmfzayahomenewmenprojectsdlifelibliblifeacomplete automata 1ff 675orodata0x70 undefined reference to d6object6object6tohashmfnbnezmhomenewmenprojectsdlifelibliblifeacomplete automata 1ff 675orodata0x78 undefined reference to d6object6object5opcmpmfc6objectzihomenewmenprojectsdlifelibliblifeacomplete automata 1ff 675orodata0x80 undefined reference to d6object6object8opequalsmfc6objectzbhomenewmenprojectsdlifelibliblifeacomplete automata 1ff 675orodata0xf8 undefined reference to d6object6object8tostringmfzayahomenewmenprojectsdlifelibliblifeacomplete automata 1ff 675orodata0x100 undefined reference to d6object6object6tohashmfnbnezmhomenewmenprojectsdlifelibliblifeacomplete automata 1ff 675orodata0x108 undefined reference to d6object6object5opcmpmfc6objectzihomenewmenprojectsdlifelibliblifeacomplete automata 1ff 675orodata0x110 undefined reference to d6object6object8opequalsmfc6objectzbhomenewmenprojectsdlifelibliblifeacomplete automata 1ff 675o in function d17complete automata16completeautomata6 ctormfmmzc17complete automata16completeautomatacomplete automatadtext d17complete automata16completeautomata6 ctormfmmzc17complete automata16completeautomata0x1f undefined reference to d newclasscomplete automatadtext d17complete automata16completeautomata6 ctormfmmzc17complete automata16completeautomata0x46 undefined reference to d newclasshomenewmenprojectsdlifelibliblifeacomplete automata 1ff 675o in function completeautomatanextcomplete automatadtext zn16completeautomata4nextev0x2f undefined reference to d newclasshomenewmenprojectsdlifelibliblifeacomplete automata 1ff 675o in function completeautomatasavecomplete automatadtext zn16completeautomata4saveev0x25 undefined reference to addupthomenewmenprojectsdlifelibliblifeacomplete automata 1ff 675o in function completeautomatarestorecomplete automatadtext zn16completeautomata7restoreev0x33 undefined reference to d newclasshomenewmenprojectsdlifelibliblifeacomplete automata 1ff 675o in function completeautomatazerofilecomplete automatadtext zn16completeautomata8zerofileev0x2f undefined reference to d newclasshomenewmenprojectsdlifelibliblifeaobject 201 8b7o in function no symbolusrincludedmddruntimeimportobjectditext0x6 undefined reference to dmodule refhomenewmenprojectsdlifelibliblifeaobject 201 8b7odata d12typeinfo axi6 initz0x0 undefined reference to d14typeinfo array6 vtblzhomenewmenprojectsdlifelibliblifeaobject 201 8b7o in function d46usrincludedmddruntimeimportobjectdi5137 arrayzusrincludedmddruntimeimportobjectditext d46usrincludedmddruntimeimportobjectdi5137 arrayz0x16 undefined reference to d array boundshomenewmenprojectsdlifelibliblifeaobject 201 8b7o in function d46usrincludedmddruntimeimportobjectdi5138 assertfizvusrincludedmddruntimeimportobjectditext d46usrincludedmddruntimeimportobjectdi5138 assertfizv0x16 undefined reference to d assertmhomenewmenprojectsdlifelibliblifeaobject 201 8b7o in function d46usrincludedmddruntimeimportobjectdi51315 unittest failfizvusrincludedmddruntimeimportobjectditext d46usrincludedmddruntimeimportobjectdi51315 unittest failfizv0x16 undefined reference to d unittestmhomenewmenprojectsdlifelibliblifeaobject 203 875o in function no symbolusrincludedmddruntimeimportobjectditext0x6 undefined reference to dmodule refhomenewmenprojectsdlifelibliblifeaobject 203 875odata d11typeinfo xi6 initz0x0 undefined reference to d14typeinfo const6 vtblzhomenewmenprojectsdlifelibliblifeaobject 203 875odata d11typeinfo xi6 initz0x10 undefined reference to d10typeinfo i6 initzhomenewmenprojectsdlifelibliblifeaobject 203 875o in function d46usrincludedmddruntimeimportobjectdi5157 arrayzusrincludedmddruntimeimportobjectditext d46usrincludedmddruntimeimportobjectdi5157 arrayz0x16 undefined reference to d array boundshomenewmenprojectsdlifelibliblifeaobject 203 875o in function d46usrincludedmddruntimeimportobjectdi5158 assertfizvusrincludedmddruntimeimportobjectditext d46usrincludedmddruntimeimportobjectdi5158 assertfizv0x16 undefined reference to d assertmhomenewmenprojectsdlifelibliblifeaobject 203 875o in function d46usrincludedmddruntimeimportobjectdi51515 unittest failfizvusrincludedmddruntimeimportobjectditext d46usrincludedmddruntimeimportobjectdi51515 unittest failfizv0x16 undefined reference to d unittestmhomenewmenprojectsdlifelibliblifeaagregatoro in function no symbolagregatordtext0x6 undefined reference to dmodule refhomenewmenprojectsdlifelibliblifeaagregatorodata0x10 undefined reference to d3std6random12 moduleinfozhomenewmenprojectsdlifelibliblifeaagregatororodata0x20 undefined reference to d14typeinfo class6 vtblzhomenewmenprojectsdlifelibliblifeaagregatoro in function d9agregator7 arrayzagregatordtext d9agregator7 arrayz0x16 undefined reference to d array boundshomenewmenprojectsdlifelibliblifeaagregatoro in function d9agregator8 assertfizvagregatordtext d9agregator8 assertfizv0x16 undefined reference to d assertmhomenewmenprojectsdlifelibliblifeaagregatoro in function d9agregator15 unittest failfizvagregatordtext d9agregator15 unittest failfizv0x16 undefined reference to d unittestmhomenewmenprojectsdlifelibliblifeaagregator 2 5fdodata0x0 undefined reference to d14typeinfo class6 vtblzhomenewmenprojectsdlifelibliblifeaagregator 2 5fdodata0x50 undefined reference to d6object7 classzhomenewmenprojectsdlifelibliblifeaagregator 2 5fdorodata0x48 undefined reference to d6object6object8tostringmfzayain second case when using gdc i receives message about multiple definition ofg wlo1 wlzrelro o cellular life maino mainwindowo renderareao buttono playbuttono moc mainwindowo moc renderareao moc buttono moc playbuttono lhomenewmenprojectsdlifelib llife lqtgui lqtcore lpthread homenewmenprojectsdlifelibliblifeacomplete automatao in function d17complete automata16completeautomata7restoremrzv14sliceagregator9initvaluemxfmmzicomplete automatadtext0x0 multiple definition of d17complete automata16completeautomata7restoremrzv14sliceagregator9initvaluemxfmmzihomenewmenprojectsdlifelibliblifeacomplete automata 1ff 675ocomplete automatadtext d17complete automata16completeautomata7restoremrzv14sliceagregator9initvaluemxfmmzi0x0 first defined herehomenewmenprojectsdlifelibliblifeacomplete automatao in function completeautomatainvertunsigned long long unsigned long longcomplete automatadtext0x40 multiple definition of completeautomatainvertunsigned long long unsigned long longhomenewmenprojectsdlifelibliblifeacomplete automata 1ff 675ocomplete automatadtext zn16completeautomata6inverteyy0x0 first defined herehomenewmenprojectsdlifelibliblifeacomplete automatao in function completeautomatastateunsigned long long unsigned long long constcomplete automatadtext0x60 multiple definition of completeautomatastateunsigned long long unsigned long long consthomenewmenprojectsdlifelibliblifeacomplete automata 1ff 675ocomplete automatadtext znk16completeautomata5stateeyy0x0 first defined herehomenewmenprojectsdlifelibliblifeacomplete automatao in function completeautomatax constcomplete automatadtext0x80 multiple definition of completeautomatax consthomenewmenprojectsdlifelibliblifeacomplete automata 1ff 675ocomplete automatadtext znk16completeautomata1xev0x0 first defined herehomenewmenprojectsdlifelibliblifeacomplete automatao in function completeautomatay constcomplete automatadtext0xa0 multiple definition of completeautomatay consthomenewmenprojectsdlifelibliblifeacomplete automata 1ff 675ocomplete automatadtext znk16completeautomata1yev0x0 first defined herehomenewmenprojectsdlifelibliblifeacomplete automatao in function completeautomatanextcomplete automatadtext0x140 multiple definition of completeautomatanexthomenewmenprojectsdlifelibliblifeacomplete automata 1ff 675ocomplete automatadtext zn16completeautomata4nextev0x0 first defined herehomenewmenprojectsdlifelibliblifeacomplete automataotbss0x10 multiple definition of d17complete automata16completeautomata4nextmrzv7changerc7changer7changerhomenewmenprojectsdlifelibliblifeacomplete automata 1ff 675otbss0x0 first defined herehomenewmenprojectsdlifelibliblifeacomplete automatao in function completeautomatarestorecomplete automatadtext0x1b0 multiple definition of completeautomatarestorehomenewmenprojectsdlifelibliblifeacomplete automata 1ff 675ocomplete automatadtext zn16completeautomata7restoreev0x0 first defined herehomenewmenprojectsdlifelibliblifeacomplete automataotbss0x8 multiple definition of d17complete automata16completeautomata7restoremrzv9agregatorc9agregator9agregatorhomenewmenprojectsdlifelibliblifeacomplete automata 1ff 675otbss0x8 first defined herehomenewmenprojectsdlifelibliblifeacomplete automataodata0x180 multiple definition of d zn16completeautomata7restoreev14sliceagregator7 classzhomenewmenprojectsdlifelibliblifeacomplete automata 1ff 675odata0x0 first defined herehomenewmenprojectsdlifelibliblifeacomplete automatao in function completeautomatazerofilecomplete automatadtext0x220 multiple definition of completeautomatazerofilehomenewmenprojectsdlifelibliblifeacomplete automata 1ff 675ocomplete automatadtext zn16completeautomata8zerofileev0x0 first defined herehomenewmenprojectsdlifelibliblifeacomplete automataotbss0x0 multiple definition of d17complete automata16completeautomata8zerofilemrzv9agregatorc9agregator9agregatorhomenewmenprojectsdlifelibliblifeacomplete automata 1ff 675otbss0x10 first defined herehomenewmenprojectsdlifelibliblifeacomplete automatao in function completeautomatasavecomplete automatadtext0x290 multiple definition of completeautomatasavehomenewmenprojectsdlifelibliblifeacomplete automata 1ff 675ocomplete automatadtext zn16completeautomata4saveev0x0 first defined herehomenewmenprojectsdlifelibliblifeacomplete automataodata0x80 multiple definition of d17complete automata16completeautomata7 classzhomenewmenprojectsdlifelibliblifeacomplete automata 1ff 675odata0xd0 first defined herehomenewmenprojectsdlifelibliblifeacomplete automatao in function d17complete automata16completeautomata6 ctormfmmzc17complete automata16completeautomatacomplete automatadtext0x9b0 multiple definition of d17complete automata16completeautomata6 ctormfmmzc17complete automata16completeautomatahomenewmenprojectsdlifelibliblifeacomplete automata 1ff 675ocomplete automatadtext d17complete automata16completeautomata6 ctormfmmzc17complete automata16completeautomata0x0 first defined herehomenewmenprojectsdlifelibliblifeacomplete automataorodata0x420 multiple definition of d17complete automata16completeautomata6 vtblzhomenewmenprojectsdlifelibliblifeacomplete automata 1ff 675orodata0xf0 first defined hereusrbinld warning size of symbol d17complete automata16completeautomata6 vtblz changed from 104 in homenewmenprojectsdlifelibliblifeacomplete automata 1ff 675o to 112 in homenewmenprojectsdlifelibliblifeacomplete automataohomenewmenprojectsdlifelibliblifeacomplete automataorodata0x4a0 multiple definition of d17complete automata16completeautomata6 initzhomenewmenprojectsdlifelibliblifeacomplete automata 1ff 675orodata0x90 first defined herehomenewmenprojectsdlifelibliblifeacomplete automataorodata0x4e0 multiple definition of d zn16completeautomata7restoreev14sliceagregator6 vtblzhomenewmenprojectsdlifelibliblifeacomplete automata 1ff 675orodata0x60 first defined hereusrbinld warning size of symbol d zn16completeautomata7restoreev14sliceagregator6 vtblz changed from 48 in homenewmenprojectsdlifelibliblifeacomplete automata 1ff 675o to 56 in homenewmenprojectsdlifelibliblifeacomplete automataohomenewmenprojectsdlifelibliblifeacomplete automataorodata0x520 multiple definition of d zn16completeautomata7restoreev14sliceagregator6 initzhomenewmenprojectsdlifelibliblifeacomplete automata 1ff 675orodata0x0 first defined herehomenewmenprojectsdlifelibliblifeaagregatoro in function d3std7complex14 t7complextez7complex8tostringmxfmdfaxazvayazaya12 lambda1223mfnbnfaxazvagregatordtext0xaf undefined reference to d11typeinfo aa6 initzagregatordtext0xb7 undefined reference to d arrayappendthomenewmenprojectsdlifelibliblifeaagregatoro in function d3std4conv16 t6toimpltitxkz6toimplfnanfxkzi15 dgliteral1389mfnanfzc6object9throwableagregatordtext0xc5 undefined reference to d3std4conv21convoverflowexception7 classzagregatordtext0xca undefined reference to d newclassagregatordtext0xed undefined reference to d3std4conv21convoverflowexception6 ctormfayaayamzc3std4conv21convoverflowexceptionhomenewmenprojectsdlifelibliblifeaagregatoro in function d3std6format17 t9getnthinttxez9getnthintfnanfkxezipart6agregatordtext0x105 undefined reference to d3std6format15formatexception7 classzagregatordtext0x10a undefined reference to d newclassafter two days of attempts to do sorecently i have try add phobos d standard library to linking process for dmd lphobos2 flag and for gdc lgphobos2 flag correspond but it not help mewhen using dmd linker outputg wlo1 wlzrelro o cellular life maino mainwindowo renderareao buttono playbuttono moc mainwindowo moc renderareao moc buttono moc playbuttono lhomenewmenprojectsdlifelib llife lqtgui lqtcore lpthread lphobos2usrlibgccx86 64redhatlinux472lib64libphobos2so undefined reference to curl easy duphandlecurl gnutls 3usrlibgccx86 64redhatlinux472lib64libphobos2so undefined reference to curl easy strerrorcurl gnutls 3usrlibgccx86 64redhatlinux472lib64libphobos2so undefined reference to curl slist free allcurl gnutls 3usrlibgccx86 64redhatlinux472lib64libphobos2so undefined reference to curl global initcurl gnutls 3usrlibgccx86 64redhatlinux472lib64libphobos2so undefined reference to curl easy performcurl gnutls 3usrlibgccx86 64redhatlinux472lib64libphobos2so undefined reference to curl easy initcurl gnutls 3usrlibgccx86 64redhatlinux472lib64libphobos2so undefined reference to curl easy pausecurl gnutls 3usrlibgccx86 64redhatlinux472lib64libphobos2so undefined reference to dmainusrlibgccx86 64redhatlinux472lib64libphobos2so undefined reference to curl easy setoptcurl gnutls 3usrlibgccx86 64redhatlinux472lib64libphobos2so undefined reference to curl slist appendcurl gnutls 3usrlibgccx86 64redhatlinux472lib64libphobos2so undefined reference to curl global cleanupcurl gnutls 3usrlibgccx86 64redhatlinux472lib64libphobos2so undefined reference to curl easy cleanupcurl gnutls 3collect2 error ld returned 1 exit statusmake cellular life error 1and i have try substitute of libcurlgnutls ln s usrlib64libcurlso4 usrlib64libcurlgnutlsso4 then result of linking the same but without message about libcurlgnutlswhen using gdc linker output again talk about multiple definition tohomenewmengccbing wlo1 wlzrelro o cellular life maino mainwindowo renderareao buttono playbuttono moc mainwindowo moc renderareao moc buttono moc playbuttono lhomenewmengcclib64 lhomenewmenprojectsdlifelib llife lqtgui lqtcore lpthread lgphobos2homenewmenprojectsdlifelibliblifeacomplete automatao in function d17complete automata16completeautomata7restoremrzv14sliceagregator9initvaluemxfmmzicomplete automatadtext0x0 multiple definition of d17complete automata16completeautomata7restoremrzv14sliceagregator9initvaluemxfmmzihomenewmenprojectsdlifelibliblifeacomplete automata 1e3 675ocomplete automatadtext d17complete automata16completeautomata7restoremrzv14sliceagregator9initvaluemxfmmzi0x0 first defined herehomenewmenprojectsdlifelibliblifeacomplete automatao in function completeautomatainvertunsigned long long unsigned long longcomplete automatadtext0x40 multiple definition of completeautomatainvertunsigned long long unsigned long longhomenewmenprojectsdlifelibliblifeacomplete automata 1e3 675ocomplete automatadtext zn16completeautomata6inverteyy0x0 first defined herehomenewmengcclib64libgphobos2admain2o in function mainhomenewmenprojectsthistribgcc481x86 64unknownlinuxgnulibphoboslibdruntimelibphoboslibdruntimertdmain2d394 multiple definition of mainmainohomenewmenprojectsdlifeqt viewermaincpp5 first defined hereusrbinld homenewmengcclib64libgphobos2atimeo undefined reference to symbol clock getresglibc 225usrbinld note clock getresglibc 225 is defined in dso lib64librtso1 so try adding it to the linker command linelib64librtso1 could not read symbols invalid operationcollect2 error ld returned 1 exit statusmake cellular life error 1with message about librtso1 at end i inspect usrlib64 and seen there it library filedear magic please tell me how to connect the d library to c code,['c++'] +506813,android facebook applicationid cannot be null error despite correct app id i know this question has been asked before but my problem is that i have set up the manifest and strings files correctlyxml version10 encodingutf8manifest xmlnsandroid packagecomhellofb androidversioncode1 androidversionname10 usessdk androidminsdkversion8 androidtargetsdkversion17 usespermission androidnameandroidpermissioninternet application androidallowbackuptrue androidicondrawableic launcher androidlabelstringapp name androidthemestyleapptheme activity androidnamecomhellofbmainactivity androidlabelstringapp name intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity metadata androidnamecomhellofbapplicationid androidvaluestringapp id activity androidnamecomhellofbloginactivity applicationmanifestapp id string edited for securityxml version10 encodingutf8resources string nameapp namehello fbstring string nameaction settingssettingsstring string namehello worldhello worldstring string nameapp id18031830547xstringresourcesany ideas where i might be going wrong have i by any chance set things up the wrong way any help in the right direction is appreciated,['android'] +506845,whats the sort order of javas collectionssortlist comparator small to big or big to small apparently it is not documented or i missed itheres the link to the documentation and belows the text as an imageedit175 i think too many confused this question to be a comparator question it is not the comparator compares between 2 elements according to that comparison the list sorted how ascending or descendingi will refinesimplify the question even further if the comparator decides that element a is smaller than element b in the sorted list will element a be located at a smaller index than element b,['java'] +506874,useridentityisauthenticated is false after successful login i need to get the userid guid directly after a successful login the following code does not workif membershipvalidateusertxtusernamevalue txtpasswordvalue formsauthenticationsignout formsauthenticationsetauthcookietxtusernamevalue true if httpcontextcurrentuseridentityisauthenticated does not run guid puk guidmembershipgetuserprovideruserkey the following code does workif membershipvalidateusertxtusernamevalue txtpasswordvalue formsauthenticationsignout formsauthenticationsetauthcookietxtusernamevalue true membershipuser user membershipgetusertxtusernamevalue if user null guid puk guiduserprovideruserkey why does this happen is there something more to do besides setauthcookie,"['c#', 'asp.net']" +506919,create hourlyminutely time range using pandas is there a way to generate time range in pandas similar to date rangesomething likepandastime range1100 2130 freq30min,['python'] +506930,why cannot i order by a column alias when using pdo on sql server note the only difference in the following examples is the order by clausegood codesql select date as name from transactions where category id 10 group by date order by date ascstmt dbpreparesqlstmtbindvalue1 test pdoparam strstmtexecutedata stmtfetchallreturns rows in databad codesql select date as name from transactions where category id 10 group by date order by date asc name ascstmt dbpreparesqlstmtbindvalue1 test pdoparam strstmtexecutedata stmtfetchallreturns an empty arraywhy is my second block of code not working if i run either version of this query directly in sql management studio it works either way and if i get rid of the question mark in php and hardcode the value into the query rather than binding it that works too what is going on hereupdate here is a sample php script that better illustrates the problem in this linked sample code i include 5 tests tests 1 2 and 4 all return results while tests 3 and 5 do not and should illustrate the problem,"['php', 'sql']" +506970,ngselected not working in select element i have a bound select select ngmodelcollegeselection ngoptionsc as ccollegename for c in colleges ngselectedccollegename collegeselectioncollegename nameselectcollege idselectcollegeselect but when both ccollegename collegeselectioncollegename match the item still is not selected documentation does not seem to help any ideas,['javascript'] +506983,active android manytomany relationship although this question is about activeandroid anyone who is familiar with orms could probably answer this questionactiveandroid does not seem to give you a way to do manytomany relationships out of the box what i found while searching for a solution was this github issue i understand that it is explicitly creating the relationship table but i do not understand how the following part is supposed to do anything usefulpublic listfoo foos return getmanyfooclass foobarpublic listbar bars return getmanybarclass foobarthis would result in a query like select from foo where foofoobar foobarid this would return at most one foo row am i missing somethingdo not you need a query involving a join,"['android', 'sql']" +507020,path attribute in spring can anyone please explain how path attribute works in binding objects from a html form to a java class in springi am newbie to spring web framework please help,['java'] +507039,c image processing tutorials withuot 3rd party library i want to learn image processing in c but i do not want to use any 3rd party library for image manipulation use of library for thisplaying the images is okay but all manipulations are to be done manuallyplease point me to some good tutorials i am a beginner in this field so i also need to know how to thisplay an image,['c++'] +507050,afnetworking expected content type error i am getting the json string in failure block nsurl url nsurl alloc initwithstring nsurlrequest request nsurlrequest alloc initwithurlurl afjsonrequestoperation addacceptablecontenttypesnsset setwithobjecttexthtml afjsonrequestoperation operation afjsonrequestoperation jsonrequestoperationwithrequestrequest successnsurlrequest request nshttpurlresponse response id json nslog json failurensurlrequest request nshttpurlresponse response nserror error id json nslogrequest failed with error error erroruserinfo operation startoutput request failed with error error domainafnetworkingerrordomain code1016 expected content type textjson textjavascript applicationjson texthtml got textplain userinfo0x71521a0 nslocalizedrecoverysuggestionproptypid1propcatid1proptypflat condo,"['iphone', 'ios', 'objective-c']" +507052,why do the buttons in my window look old in c i just began creating a new windows application in c using vs 2012 and instead of using the premade template for win32 application i simply started a blank project and wrote my window from scratchthe problem is the buttons look like thisthen i realized i needed to embed a manifest which was no issue so i put this inside the codepragma commentlinkermanifestdependencytypewin32 namemicrosoftwindowscommoncontrols version60 processorarchitecture publickeytoken6595b64144ccf1df languageafterward to my thispleasure the button became this equally unattractive little guyfor some reason it is not looking how it is supposed to does anybody have any ideas what the issue might be,['c++'] +507112,how to detect touchend event outside of an element i am trying to handle a button click the button is a custom div that can also contain children the click callback should fire when the user has both clicked and released inside the element if the user clicks inside and then drags and releases outside the handler should not fire i need to get this working on both desktop and mobile hence i am using mousedownmouseup and touchstarttouchend eventsi need to change the button class from pressed to normal even if the user releases outside so i need to add a listener to capture the releasing event over the document var myelement myelement this is a div and can also contain children myelementonmousedown touchstart functione thisaddclasspressed documentonmouseup touchend function listenere myelementremoveclasspressed documentoffmouseup touchend listener var target etarget if targetismyelement targetparentsismyelement fixme alertinside do something here return false else fixme alertoutside let event bubble return false it works fine with clicks but it does not work as expected with touch events i have tested this in chrome for android and when pressing over the element then dragging out the inside alert is shown the problem is in this conditionif targetismyelement targetparentsismyelementi am trying to check whether the touchend event has occurred in the button or any of the the children if the button has no children when clicking on it and then releasing outside the first part of the or clause resolves to true if the button has children and i click in the children then release in any other part of the screen the second part of the clause is truewhat is wrong with this codethanks in advanceupdatei have tested it also in blackberry 10 with the same results apparently the target for the touchend event is the button or the children even when i have clicked outside is this how it is supposed to workupdateand heres why this is what the w3c docs say about the eventthe target of this event must be the same element that received the touchstart event when this touch point was placed on the surface even if the touch point has since moved outside the interactive area of the target element it makes no sense to me but anyway this explain my problem i was assuming the touchend event would be called over the element where the finger was released would it be possible to detect the finger release outside using a different approach updatei have tried to get the coordinates of the touchevent to get the element there using documentelementfrompoint the problem is this event does not contain the coordinates the changedtouches and touches lists are empty i have thorougly inspected the event in the debugger and there is no way to retrieve coords from it other than the original events then i thought i could cache the last touchmove event and get the coords from there but again this event has no own coordinates why on earth do these two events exist when they are useless and i have tested this approach in ios android and bb10 with identical resultsi have given up i will call the callback even if the user clicked outside i cannot believe it is 2013 guys and there is no simple way of doing this i could use the dragdrop api but according to this it is unsupported on mobile gotta love mobile web development,"['javascript', 'jquery']" +507116,change of fontweight to bold is unwantingly changing width of element whilst creating a navigation bar for my site i decided to make the active page tab show up in bold for usability purposes but when i change the fontweight on the element it only slightly makes the element wider an example i made using hover effects instead demonstrates my issue and i have never known a way to solve ithtmlul idmainnav li classnavitem a classnavlink idactivelinklink 1a li li classnavitem a classnavlinklink 2a li li classnavitem a classnavlinklink 3a liulcss fontfamily arial fontsize 14px liststyle none margin 0 padding 0 textdecoration nonemainnav background rgb200 230 240 borderbottom 1px solid rgb0 0 0 height 30px margin 0 auto position relative width 100navitem thisplay block float left position relativenavitemlastchild navlink borderright 1px solid rgb0 0 0navlink borderbottom 1px solid rgb0 0 0 borderleft 1px solid rgb0 0 0 thisplay inlineblock height 30px lineheight 30px padding 0 15px whitespace nowrapnavitemhover navlink background rgb120 200 250 color rgb255 255 255 cursor pointer fontweight boldactivelink background rgb90 170 220 color rgb255 255 255 fontweight boldactivelinkhover background rgb110 190 240navitemhover subnav thisplay block,"['html', 'css']" +507120,zurb foundation 4 how to create a full height column i am trying to create a floating panel it needs be detached from the grid and fill the entire height of the document on the left side like somy experiment so fardiv classrow left div clasmall3 div classpanel panel html div divdivdiv classrow div clasmall6 columnsdiv classpanelmain contentdivdiv div clasmall6 columnsdiv classpanelmain contentdivdivdivproduce the followingi am not sure what is the best practice when using foundation and could not find a reference in their docs appreciate the help,"['html', 'css']" +507178,can you inherit private functions in javascript i am using a closure to create an object with private and public methods it looks like this var dog function function dog var size big var privatesaysize function return i am a size dog dogprototypepublicsaysize function return privatesaysize return dogbut now i would like to have an object that has only private functions and that is inherited by another object but is this possible in javascript,['javascript'] +507185,is the permgen space ever decreased i would like to know if the jvm normally unloads classes in order to decrease the permgen space so here my questionsdo java classes ever get unloaded by default from a jvmdoes closing a jar classloader unloads all the loaded classes from that jarwhat commandsways should be used to allow the unloading of classesfyi i did try some of the solutions on the web but none of them answered my questions for example what does jvm flag cmsclassunloadingenabled actually dops i am referring to java 6 hibernate the class loading is handled by hibernate,['java'] +507314,using python in vimscript how to export a value from a python script back to vim i am struggling with python in vimi still have not found out how i can import a value from a python script in a vim function back to vim pefunction myvimscript python endpython import vim random sys s vimevalmylist do operation with variable s in python endpython import variable s from above do operation with s in vimscriptendfunction1 how can i use s again in vim how can i import s from the python code back to vim i cannot find out as well how to use vimcurrentbuffer with a selection function myvimscript let startline line let endline line python endpython start vimevalstartline end vimevalendline cb vimcurrentbuffer l cbstartend endpythonendfunction2 how can i assign the dynamic value start and end to l,['python'] +507365,python list comprehension double for vec 123 456 789print num for elem in vec for num in elem this 1 2 3 4 5 6 7 8 9this is tricking me outi understand elem is the lists inside of the list from for elem in vici do not quite understand the usage of num and for num in elem in the beginning and the endhow does python interpret thiswhats the order it looks at,['python'] +507440,learning prototype edit for those people seeing this post in the future this site was undoubtedly critical for me to digest javascript if youre coming from a traditional oop background i highly recommend it the umlesq diagrams were amazing i still cannot get my head around what the prototype property in javascript is is it simply a reference to another object or is it a reference to a pointer to another object i come from ccx86 and just cannot see how it works let us look at some examples of how i currently see things it would help to point out my errors to see how things work i do not even know if some of these are valid syntax object and function are the global objectfunction objects respectively1 globalprototype 2 functionprototype 3 4 var obj1 obj1prototype object 5 obj2 obj2prototype object67 var func1 function func1prototype function8 func2 function func2prototype function9 function func3 func3prototype function 10i am so confused 11 var foo function thisprop1 0 12 var foo new foo should it be new foo or new foo13 fooprototype function14 fooprototype foo15 var goo function thisprop2 0 16 var goo new goo17 gooprototype goo18 gooprototype new foo19 gooprop1 now exists i also do not understand swapping prototypes around20 function a 21 thisprop1 122 23 function b 24 thisprop2 225 26 function c 27 thisprop3 328 29 cprototype new b30 var c new c31 cprop1 132 cprop2 233 cprop3 undefined34 cprototype new a35 cprop2 236 cprop3 3i cannot get a grasp on the concept i do not quite understand i do not get how cloned objects get their own local copies of data but changes to the original object the prototype somehow cascade down to the clones i have been fiddling around with figurebug trying things out but mentally i cannot come up with an idea that is consistent with every example ive seen c may be a huge monstrosity but at least i know exactly whats going here i am using my best guess just a new paradigm i suppose anyways thanks if you can help out i am turned upsidedown on this prototype,['javascript'] +507441,inline vs included js and css in an environment with at least 500ms latency over 2g mobile connections 01mbps whats the fastest and most efficient way of sending a about 10kb of css and js in around 510 files on the server to the client i can think of three options combining all js to one file and all css to one filelinking all css and js files one by oneinline everythingi know google uses inline but that is probably just to save server sockets they are even saving ram by running in stateless mode they trust the clients to remember the sessions for them server power is not an issue at allon the other hand facebook seem to autogenerate their css their names are base64 encoded but into over 10 different files sent to the user and they do not even seem to optimize it that heavily only some whitespace removali am already passing all the files through a function that compresses everything so any one of these are feasible i do not want to choose the first alternative because it is easierthe first two takes advantage of caching the second one a bit less than the first one but the second only requires three requests to the server and the third only requires one get request from the server ignoring the few images we might have on some of the pagesdoes android ios cache js and css across restarts of the browser if not then inline sounds better the only goal is to minimize the average load time of the user each user will be spending about 100 page loads on the site per day seeing about 40 css and js files per day the css and js is basically static content it is set to cache 30 days and we change the url if the file changes using pathtofileextmd5hashoffile also everything is gzipped wherever possibleediti think i should clarify the two options i found for number two is it a good idea to use a single file for css and js across the whole site it would only use two requests and remove any double or septuple caching because a single function is in two or more different combined js files but a download of up to 1mb does not sound that good today it is basically one combined css per view so every time you view the same page again the content is cached however some js and css is used on more than one page,"['javascript', 'android', 'html', 'css']" +507508,how to remove all instances of a class in javascriptjquery i have this class called mactive that is used multiple times throughout my htmlbasically what i want to do is remove all instances of that class when a user clicks on an image which does not have the mactive class and add the mactive class to that imagefor instance in a backgrid row you might have a click handler as followsclick function thiseladdclassmactivebut you also want to remove that class from any rows to which it was previously added so that only one row at a time has the mactive classdoes anyone know how this can be done in javascriptjquery,"['javascript', 'jquery']" +507519,can you precache aspnet bundles every time i deploy an mvc web application my server has to recache all js and css bundles because of this it can take several seconds for the first view to render after deploying is there a way to precache bundles after all the files are static at compile time,"['c#', 'asp.net']" +507530,if operator works properly for floatingpoint types why cannot we use it for equality testing properly testing two floatingpoint numbers for equality is something that a lot of people including me do not fully understand today however i thought about how some standard containers define equality in terms of operator i always see people with problems surrounding equality but never with the other relational comparisons there are even silent versions of them to use which include everything except for equality and inequalityassuming operator works properly unlike operator why could not we do thisbool floateqfloat a float b check nan return a b b ain fact i did run a test with an additional overload for doubles as seen here and it seems to have the same pitfalls as comparing them with operatorstdcout floatdouble vs double floateqstatic castdouble07f 07 static castdouble07f 07 noutputfloatdouble vs double 0 0am i to worry about using all comparison operators or is there some other aspect of comparing floatingpoint numbers that i am not understanding correctly,['c++'] +507542,is there a document describing how clang handles excess floatingpoint precision it is nearly impossible to provide strict ie 754 semantics at reasonable cost when the only floatingpoint instructions one is allowed to used are the 387 ones it is particularly hard when one wishes to keep the fpu working on the full 64bit significand so that the long double type is available for extended precision the usual asolutiona is to do intermediate computations at the only available precision and to convert to the lower precision at more or less welldefined occasionsrecent versions of gcc handle excess precision in intermediate computations according to the interpretation laid out by joseph s myers in a 2008 post to the gcc mailing list this description makes a program compiled with gcc stdc99 mnosse2 mfpmath387 completely predictable to the last bit as far as i understand and if by chance it does not it is a bug and it will be fixed joseph s myers stated intention in his post is to make it predictableis it documented how clang handles excess precision say when the option mnosse2 is used and where edit this is an exaggeration it is slightly annoying but not that difficult to emulate binary64 when one is allowed to configure the x87 fpu to use a 53bit significandfollowing a comment by r below here is the log of a short interaction of mine with the most recent version of clang i have hexa clang vapple clang version 41 tagsappleclang42166 based on llvm 31svntarget x86 64appledarwin1240thread model posixhexa cat femcinclude stdiohinclude mathhinclude floathinclude fenvhdouble xdouble y 20double z 10int main x y z printfdn int flt eval methodhexa clang stdc99 mnosse2 femchexa aout 0hexa clang stdc99 mnosse2 s femchexa cat fems a movl 0 esi fldl yrip fldl zrip faddp st1 movq xgotpcrelrip rax fstpl raxa,['c'] +507545,how to determine whether a field exists i am connecting to my mongodb using pymongoclient mongoclientmongo mongoclientlocalhost 27017mongo db mongotestmongo coll mongo dbtest tweets databasei have a cursor and am looping through every recordcursor mongo collfind for record in cursor for all the tweets in the database try msgurl recordentitiesurls look for urls in the tweets except continuethe reason for the tryexcept is because if entitiesurls does not exist it errors out how can i determine whether entitiesurls exists,['python'] +507592,releasing a python package should you include doc and tests so i have released a small library on pypi more as an exercise to see how it is done than anything elsei have uploaded the documentation on readthedocs and i have a test suite in my git reposince i figure anyone who might be interested in running the test will probably just clone the repo and the doc is already available online i decided not to include the doc and test directories in the released package and i was just wondering if that was the right thing to doi know answers to this question will be rather subjective but i felt it was a good place to ask in order to get a sense of what the community considers to be the best practice,['python'] +507622,implementing a web page hit counter in 2013 i am looking to implement a web page hit counter to let the server know what pages are being viewed where i am trying to avoid sending the server repetitive user hits by the same user same page i am not super concerned about them clearing their cache etc and possibly getting counted againi have generally seen something like thisimg srcthehitcounterpageidsome page id and then use a cookie to make sure the hit does not get counted againbut is there any reason to not use ajax to notify the server other than the obvious the user must have javascript enabled i am guessing almost everyone that is not wearing a tinfoil hat these days will have it enabled in their browserwith ajax and javascript i could do something like this and bring local storage into the mix and reduce some network bandwidthif amplifystoresome page id getthehitcounterpageidsome page id amplifystoresome page id what am i missing about the javascript approach,"['javascript', 'html']" +507647,subview would not align trailing edge to its parent uiscrollview i have a uiscrollview with 2 subviews i would like one subview to be leadingaligned leftaligned where its leading edge lines up with the leading edge of the scrollview i would like the other subview to be trailingaligned rightaligned where its trailing edge lines up with the trailing edge of the scrollview for some reason autolayout keeps unexpectedly placing the second trailingaligned subview outside the bounds of the scrollview to the leading left side of the other subview such that the subviews trailing edge lines up with the leading edge of the scrollview i am trying to do this programmatically code is below i am using 2 labels for the 2 subviews the alpha label is correctly leadingaligned but the beta label is not trailingaligned as it should bethis also happens if i try using left and right alignments instead of leading and trailing the rightaligned label show up in the same incorrect place as the trailingaligned labeli have read through the ios 6 release notes and answers here and elsewhere many times and i am just not sure why this is happeningin the view controller void viewdidload super viewdidload create and configure the scroll view uiscrollview scrollview uiscrollview alloc init scrollview settranslatesautoresizingmaskintoconstraintsno for debugging scrollview setclipstoboundsno scrollviewlayerbordercolor uicolor redcolorcgcolor scrollviewlayerborderwidth 10 self view addsubviewscrollview layout scrollview horizontal leading edge to superviews leading edge with indent selfview addconstraintnslayoutconstraint constraintwithitemscrollview attributenslayoutattributeleading relatedbynslayoutrelationequal toitemselfview attributenslayoutattributeleading multiplier10 constant200 horizontal trailing edge to superviews trailing edge with indent selfview addconstraintnslayoutconstraint constraintwithitemscrollview attributenslayoutattributetrailing relatedbynslayoutrelationequal toitemselfview attributenslayoutattributetrailing multiplier10 constant200 vertical top edge to superviews top edge with indent selfview addconstraintnslayoutconstraint constraintwithitemscrollview attributenslayoutattributetop relatedbynslayoutrelationequal toitemselfview attributenslayoutattributetop multiplier10 constant200 vertical bottom edge to superviews bottom edge with indent selfview addconstraintnslayoutconstraint constraintwithitemscrollview attributenslayoutattributebottom relatedbynslayoutrelationequal toitemselfview attributenslayoutattributebottom multiplier10 constant200 create and configure first label which should be leadingaligned with scrollview uilabel labelalpha uilabel alloc init labelalpha settranslatesautoresizingmaskintoconstraintsno labelalpha settextalpha scrollview addsubviewlabelalpha layout first label horizontal leading edge to scrollviews leading edge scrollview addconstraintnslayoutconstraint constraintwithitemlabelalpha attributenslayoutattributeleading relatedbynslayoutrelationequal toitemscrollview attributenslayoutattributeleading multiplier10 constant00 vertical top edge to scrollviews top edge scrollview addconstraintnslayoutconstraint constraintwithitemlabelalpha attributenslayoutattributetop relatedbynslayoutrelationequal toitemscrollview attributenslayoutattributetop multiplier10 constant00 create and configure second label which should be trailingaligned with scrollview uilabel labelbeta uilabel alloc init labelbeta settranslatesautoresizingmaskintoconstraintsno labelbeta settextbeta scrollview addsubviewlabelbeta layout second label horizontal trailing edge to scrollviews trailing edge scrollview addconstraintnslayoutconstraint constraintwithitemlabelbeta attributenslayoutattributetrailing relatedbynslayoutrelationequal toitemscrollview attributenslayoutattributetrailing multiplier10 constant00 vertical top edge to scrollviews top edge scrollview addconstraintnslayoutconstraint constraintwithitemlabelbeta attributenslayoutattributetop relatedbynslayoutrelationequal toitemscrollview attributenslayoutattributetop multiplier10 constant00for reference the output from the view controllers views recursivedescription backs up the misalignment20130715 220423892 middleman5669907 uiview 0x20872960 frame 0 0 320 480 transform 0 1 1 0 0 0 autoresize rmbm layer calayer 0x20871e60 uiscrollview 0x208718a0 frame 20 20 440 280 gesturerecognizers nsarray 0x20871f20 layer calayer 0x208728e0 contentoffset 0 0 uilabel 0x20872ab0 frame 0 0 44 21 text alpha clipstobounds yes userinteractionenabled no layer calayer 0x20872b90 uilabel 0x208730e0 frame 36 0 36 21 text beta clipstobounds yes userinteractionenabled no layer calayer 0x20873170,['ios'] +507651,convert utc time to local time using nodatime i have been provided a time in this format ddmmyyhhmmss i know the time is in utc format i would like to use the nodatime library to convert this to my local timezone but i cannot seem to figure it out my local timezone target is to be new zealandheres what i have tried var pattern localdatetimepatterncreatewithinvariantcultureddmmyyhhmmss var parseresult patternparseutcdatetime if parseresultsuccess throw new invaliddataexceptioninvalid time specified date time var timezone datetimezoneprovidersbclnew zealand standard time var zone new zoneddatetime localdatetime timezone timezonegetutcoffsetsystemclockinstancenow return new datetimezonetoinstantticks,['c#'] +507710,version supported by navigational drawer in android android navigational drawer is supported on minimum which version also can we make custom navigational drawer in android if we can then kindly tell me how to get started i have read the documentation from android developer site but many things i cannot understand and want helpthanks in advance,['android'] +507761,javascript prevent browser to thisplay input history for a field on press of down key is there anyway to prevent the browser from thisplaying previously inputted values for a field on press of the down keyif this is not possible another problem of mine is on press of the down key the list of previously inputted values will be shown and on press of the tab key the currently highlighted value on the list will be chosen and will be set as the value of the field i do not want this i just want the focus to be passed to the next input element wo choosing any valuesare there any ways to override the browser behavior a solution in play javascript is preferred though jquery solutions are fine as well thanks,"['javascript', 'jquery']" +507800,launch google maps application for driving directions in android here is how i am launching native google maps app to show the directions between my target locations string url currentlattitudecurrentlongitudedaddrtargetlattargetlangintent intent new intentandroidcontentintentaction view uriparseurlintentsetclassnamecomgoogleandroidappsmaps comgoogleandroidmapsmapsactivitystartactivityintentis there any way to launch native maps app to show driving and transit modes currently its showing only walking directions,['android'] +507802,set the height of a div to be half of whatever the width is how can i set the height of a div to be exactly half whatever the width is when the width will change depending on the users screen sizei have the following set on a divdiv1 minwidth400px width100 maxwidth1200px height400px backgroundcolorred the width works fine on this it locks at 400 pixels if the screen gets too narrow and it also stops expanding at 1200 pixels if the screen gets too big but i also want the height to change to be exactly half of what the width is at any given time something likediv1 minwidth400px width100 maxwidth1200px heightwidth2 backgroundcolorred that has not worked which i was not really expecting it toi would prefer to use css if it is possible but as i would also like the height to change if the user manually adjusts the size of the internet window too like what happens with the width at the moment i am not sure it is possible with css however if there is a way to achieve this by jquery i would be happy to use that toojsfiddle of the above for referencecan anyone help me,"['jquery', 'css']" +507836,php imagecopyresampled adds black background i have a resize image script that takes a 130x81 image and adds it to a 130x130 image when the imagecopyresampled function runs it adds a black background into the space that is left over even though the base image is white code below i could really appreciate some helpthe image i am trying to merge onto the 130x130 file php created iswidth 130height 130filename processaddjpg 130x81px jpgthis image imagecreatefromjpegfilenamebackground imagecreatetruecolor130130create the background 130x130whitebackground imagecolorallocatebackground 255 255 255 imagefillbackground00whitebackground fill the background with whiteimagecopyresampledbackground this image130width2130height2 0 0 width height width height copy the image to the backgroundimagejpeg backgroundnull100 thisplayi have read on multiple posts to addimagealphablendingbackground falseinto the code which should fix it but it does not make any differencethanks in advance,['php'] +507860,android my app is not supporting galxy s 4 i am trying to update my application on the store to make it compatible with the galaxy s 4my app uses maps v2 it must not be installed on tablets has minsdkversion and targetsdkversion both set to 9this is my manifest filexml version10 encodingutf8manifest xmlnsandroid packageit androidversioncode113 androidversionname113 usessdk androidminsdkversion9 androidtargetsdkversion9 permission androidnameitpermissionmaps receive androidprotectionlevelsignature usespermission androidnameandroidpermissioninternet usespermission androidnameandroidpermissionaccess corse location usespermission androidnameandroidpermissionaccess coarse location usespermission androidnameandroidpermissionaccess fine location usespermission androidnameandroidpermissionaccess gps usespermission androidnameandroidpermissionaccess wifi state usespermission androidnameandroidpermissionaccess network state usespermission androidnameandroidpermissioncamera usespermission androidnameandroidpermissionwake lock usespermission androidnamecomgoogleandroidprovidersgsfpermissionread gservices usespermission androidnameandroidpermissionwrite external storage usesfeature androidglesversion0x020 androidrequiredtrue usesfeature androidnameandroidhardwarecameraautofocus androidrequiredfalse compatiblescreens all small size screens screen androidscreendensityldpi androidscreensizesmall screen androidscreendensitymdpi androidscreensizesmall screen androidscreendensityhdpi androidscreensizesmall screen androidscreendensityxhdpi androidscreensizesmall screen androidscreendensity480 androidscreensizesmall all normal size screens screen androidscreendensityldpi androidscreensizenormal screen androidscreendensitymdpi androidscreensizenormal screen androidscreendensityhdpi androidscreensizenormal screen androidscreendensityxhdpi androidscreensizenormal screen androidscreendensity480 androidscreensizenormal all large size screens screen androidscreendensityldpi androidscreensizelarge screen androidscreendensitymdpi androidscreensizelarge screen androidscreendensityhdpi androidscreensizelarge screen androidscreendensityxhdpi androidscreensizelarge screen androidscreendensity480 androidscreensizelarge compatiblescreens application androiddebuggablefalse androidicondrawableic launcher androidlabel useslibrary androidnamecomgoogleandroidmaps activity list of all the activities activity metadata androidnamecomgoogleandroidmapsv2api key androidvalueaiz jy applicationmanifestdoes someone knows why the galaxy s 4 is not supported when i try to upload my application on the storethis is what i getwhen i look at the compatible devices of my new apk in the android developer consoleps in the screendensity attribute for the screen tag i have to use the value 480 instead of xxhdpi because it is not supportedthat is the error i get if i use xxhdpierror string types not allowed at screendensity with value xxhdpi androidmanifestxml icsmob line 84 android aapt problempps the xxhdpi screen is supported i can see it when i click on the apk line in the dev console and expand the screen layout section here it is,['android'] +507866,how to import other javascript module in phantomjs or casperjs i am trying to build a functional test using casperjscaseperjs is run by a backend test suite using the following commandphantomjs executableclientnode modulesphantomjsbinphantomjs clientext modulescasperjsbincasperjs test clienttestfunctionalinitcoffeein initcoffee i want to importinclude other module file which seats just next to it how to do itthe following does not worksrequireuserall i want is to get a content from other file into initcoffee,['javascript'] +507925,how can it be that this null edit this is not a duplicate of this question as this one is a practical example working with delegatecreatedelegate and the other one is a theoretical thiscussion about il nothing to do one with each other besides the words this and nullrelative to this question i have a situation when an event handler is called on an instance that is null weird look at the imagei do not understand what is happening how an instance method can be called on a null instance,"['c#', '.net']" +507930,loading image with afnetworking resizing first of all i am using this afnetworking methodimageview setimagewithurlnsurl urlwithstring1 this method is asynchronous it will cache the image in iphone2 how can i cropresize this image i have a 800x600 image in the url but my uiimageview is 400x400 i only want to have the url image cropped before being shown to be the same ratio like 600x600 it is not needed to be 400x400 just same ratio like facebook app,"['ios', 'objective-c']" +507937,wpf combobox wrong item is thisplayed this is the initial situationxamlcombobox gridrow0 gridcolumn1 margin03 horizontalalignmentstretch thisplaymemberpaththisplaytext itemssourcebinding objectsource viewmodelpublic collectionmyobjects objectsource get return thisobjectsource set thissetpropertyref thisobjectsource value my objects contains a name string valid from datetime and a thisplaytext string only get which combine the name and valid from for thisplayingin this easy situation i am able to open the combobox an see all entries after selecting one it also thisplay the right thisplaytext inside the comboboxnow i open the the dropdown area again and select an other entrythe result is that the slected item switched as you can see the highligthed item when open the dropdown entry again but the thisplayed item inside the combobox does not changed there is still the thisplaytext of the first selectiondoes anybody has an idea for me why the combobox does not updatethanks in advanceeditthanks all for their help problem was a buggy overriding of equals,['c#'] +507963,codeigniter showing only default controller i useing codeigniter in local wamp here code is working fine but i upload in cpanel inside of examplecom folder name call mysite there i changed asdb name configdatabasephpdb user name configdatabasephpdb password configdatabasephpbase url as configconfigphpuri protocol as request uri configconfigphpand also changed htaccessmysitehtaccess asifmodule mod rewritecrewriteengine on set the rewritebase to your ci installation folderrewritebase mysite send everything to indexphprewritecond request filename frewritecond request filename drewriterule indexphp1 lbut not in mysiteapplicationhtaccess it is emptyproblem is if i go it is showing default page as correctly but if i click any link it is showing same default page but url is changedhelp me pleaseconfigphpconfigbase url configindex page configuri protocol request uriconfigurl suffix configlanguage englishconfigcharset utf8configenable hooks falseconfigsubclass prefix my configpermitted uri chars az 09 configallow get array trueconfigenable query strings falseconfigcontroller trigger cconfigfunction trigger mconfigdirectory trigger dconfiglog threshold 0configlog path configlog date format ymd hisconfigcache path configencryption key configsess cookie name ci sessionconfigsess expiration 7200configsess expire on close falseconfigsess encrypt cookie falseconfigsess use database falseconfigsess table name ci sessionsconfigsess match ip falseconfigsess match useragent trueconfigsess time to update 300configcookie prefix configcookie domain configcookie path configcookie secure falseconfigglobal xss filtering falseconfigcsrf protection falseconfigcsrf token name csrf test nameconfigcsrf cookie name csrf cookie nameconfigcsrf expire 7200configcompress output falseconfigtime reference localconfigrewrite short tags falseconfigproxy ips definecss folder applicationassetscssdefinedefault image url applicationassetsimagesdefaultroutesphproutedefault controller welcomeroute404 override routeuserany userindex,['php'] +507986,how can i add context to an exception in python i would like to add context to an exception like thisdef processvals for key in vals try do somethingvalskey except exception as ex base class not sure what to expect raise with context regarding the key that was being processedi found a way that is uncharacteristically long winded for python is there a better way than thistry do somethingvalskeyexcept exception as ex args listexargs if lenargs 1 args0 formatkey args0 exargs tupleargs raise will retrhow valueerror with new args0,['python'] +508031,multiple linear regression with python i would like to calculate multiple linear regression with pythoni found this code for simple linear regressionimport numpy as npfrom matplotlibpyplot import x nparray1 2 3 4 5y nparray2 3 4 4 5n npmaxxshape x npvstacknponesn xta nplinalglstsqx y0so a is the coefficient but i do not see what 0 means and how can i change the code to obtain multiple linear regressions,['python'] +508181,why is the top portion of my uisegmentedcontrol not tappable while i was playing on my phone i noticed that my uisegmentedcontrol was not very responsive it would take 2 or more tries to make my taps register so i decided to run my app in simulator to more precisely probe what was wrong by clicking dozens of times with my mouse i determined that the top 25 of the uisegmentedcontrol does not respond the portion is highlighted in red with photoshop in the screenshot below i am not aware of any invisible uiview that could be blocking it do you know how to make the entire control tappableselfsegmentedcontrol uisegmentedcontrol alloc initwithitemsnsarray arraywithobjectsuno dos nilselfsegmentedcontrolselectedsegmentindex 0selfsegmentedcontrol addtargetself actionselectorsegmentedcontrolchanged forcontroleventsuicontroleventvaluechangedselfsegmentedcontrolheight 320selfsegmentedcontrolwidth 3100selfsegmentedcontrolsegmentedcontrolstyle uisegmentedcontrolstylebarselfsegmentedcontroltintcolor uicolor colorwithwhite09 alpha10selfsegmentedcontrolautoresizingmask uiviewautoresizingflexibleleftmargin uiviewautoresizingflexiblerightmarginuiview toolbar uiview alloc initwithframecgrectmake0 0 selfviewwidth header heighttoolbarautoresizingmask uiviewautoresizingflexiblewidthcagradientlayer gradient cagradientlayer layer gradientframe cgrectmake toolbarboundsoriginx toolbarboundsoriginy 2 for enough slack when ipad rotates toolbarboundssizewidth 2 toolbarboundssizeheight gradientcolors nsarray arraywithobjects iduicolor whitecolor cgcolor iduicolor colorwithwhite08 alpha10 cgcolor niltoolbarlayer insertsublayergradient atindex0toolbarbackgroundcolor uicolor navigationbarshadowcolortoolbar addsubviewselfsegmentedcontroluiview border uiview alloc initwithframecgrectmake0 header height 1 toolbarwidth 1borderautoresizingmask uiviewautoresizingflexiblewidth uiviewautoresizingflexibletopmarginborderbackgroundcolor uicolor colorwithwhite07 alpha10borderautoresizingmask uiviewautoresizingflexiblewidthtoolbar addsubviewborderselfsegmentedcontrol centerinparentselftableviewtableheaderview toolbar,['ios'] +508183,objectivec priority queue i have started using objectivec for ios programming i switched over from java and i wanted to know if there were any existing libraries like the java collections framework for objc more specifically a priority queue implementation i have done some searches but have been unable to come up with anythingupdate i found this but would have no idea how to use it myself,['objective-c'] +508199,why is kvo sending a change notification when both the new and old values are the same i have an entity which is a subclass of nsmanagedobject called event i have also registered a few modeled attributes of this entity for kvo change notificationsselfevent addobserverself forkeypathnumguests optionsnskeyvalueobservingoptionnew nskeyvalueobservingoptionold contextnumguestscontextselfevent addobserverself forkeypathcheckedin optionsnskeyvalueobservingoptionnew nskeyvalueobservingoptionold contextcheckedincontextselfevent addobserverself forkeypathseatedcount optionsnskeyvalueobservingoptionnew nskeyvalueobservingoptionold contextseatedcontexthowever it seems the observevalueforkeypath method notification is getting triggered even though the value of nskeyvaluechangeoldkey and nskeyvaluechangenewkey in the change dictionary are equal voidobservevalueforkeypathnsstring keypath ofobjectidobject changensdictionary change contextvoid context nsnumber oldvalue change valueforkeynskeyvaluechangeoldkey nsnumber newvalue change valueforkeynskeyvaluechangenewkey if oldvalue isequaltonumbernewvalue return for now i have resorted to just doing a quick sanity check to see if they are equal but i would like to understand why this notification is getting fired to begin withupdate jszumski mentioned in the comments that this most likely is happening because the objects are different although logically equal the event entity object always has the same address however the object i am observing which is an attribute within the entity keeps changing addresses although i am not sure why i am wondering if accessing this value in a bg query thread could cause core data to create new internal objects within the entity with the same value,['ios'] +508201,python convert csv to xlsx in this post there is a python example to convert from csv to xlshowever my file has more than 65536 rows so xls does not work if i name the file xlsx it doesnt make a difference is there a python package to convert to xlsx,['python'] +508209,nltk for persian how to use functions of nltk for persianfor example concordance when i use concordance the answer is not match however there is the parameter of concordance in my textthe input is very simple it contains of hello 3uuwhen parameter of concordance is hello the answer is correct but if it is 3uu the answer is not matchesthe expected output for me is thisplaying 1 of 1 matches import nltk from urllib import urlopen url filehome1html raw urlopenurlread raw nltkclean htmlraw tokens nltkword tokenizeraw tokens tokens12 text nltktexttokens print textconcordance3uu,['python'] +508253,how to sync data between different devices i am planing to implement an app and i have come to a point where i do not know what is the best approachscenarioi have an app where i am making a todo list and i am adding 3 items i use my phone for thisthen i take my tablet and want to continue adding another task then after a while i take my wifes phone and want to add 2 new tasksbasically i want to have a very simple way of storing the tasks online and be able to sync it with the app i am seeing two possible wayshave a web server with a database web service calls this has the thisadvantage of having a host paid learn some extra mysql web service techniques store somehow the data on cloud and allow the app by login to access an account which stores the file i am thinking here at something like google drive dropbox but i do not know how i would be able to sync only the updated values not the whole file because i am thinking if i store all the tasks into one file each time i update the file i will need to upload it fully which is not the best approachi am open to any advices what approach would you recommend,['android'] +508273,when will proper stack traces be provided on windowonerror function exceptionserrors in many other programming languages say java ruby always provide stacktracebacktrace informationin javascript unhandled errors get caught by windowonerroralthough that function does not get the error object so we have no access to the objects stack propertyis there any reliable source of information about when will there be any change on that,['javascript'] +508310,autolayout removefromsuperview removeconstraints throws exception and crashes hard we use auto layout constraints selectively primarily to position labels in relation to editable field elements uitextview uitextfield typically however since implementing auto layout for these fields were seeing a nasty exception and crash whenever were unloading views deallocating etc the exceptions are happening as it is attempting to remove the constraints from a view before unloading itour viewcontroller hierarchy is as suchuitableviewcontroller plain style but with cell appearance to mimic grouped style uitableviewcell uiviewcontroller container for editable form uicollectionviewcontroller editable form uicollectionviewcell uiviewcontroller editable field uilabel field label has constraints uitextview uitextfield field value has constraintsmany times when the upper level table cells are being deallocatedreplacedreloaded we see a huge exception and then crash as it is trying to deallocateunload the view hierarchy withini have attempted to mitigate the crash by catching the exception no help and also by forcefully removing all of the constraints on the affected view and all of the subviews prior to deallocationunload in viewwillthisappear and it does not seem to help i have even tried to remove these constraints one by one to see if there is one in particular that is causing the trouble but all of them are blowing up when we call removeconstraint or removeconstraints on a container in preparation for thisappearingi am baffled heres a snippet of our exception roughly about 30 lines have been chopped out of it so if you need more just askexception while deallocating view rows 0x18911270poserrormarker 4 10x18911270negerror 10x189112f0marker 10x189113f0negerror 10x189113f0poserrormarker 10x18911a60marker 050x1892dae0negerror 050x1892dae0poserrormarker 10x18951520negerror 10x18951520poserrormarker 050x18958090negerror 050x18958090poserrormarker 0x189112b0negerror 12 10x189112b0poserrormarker 10x189112f0marker 10x189113f0negerror 10x189113f0poserrormarker 10x18911a60marker 10x18925530marker 050x1892dae0negerror 050x1892dae0poserrormarker 10x1893e080marker 050x18958090negerror 050x18958090poserrormarker 10x18963640marker 0x18911370negerror 9 10x189112f0marker 10x18911370poserrormarker 10x18925530marker 10x1892dae0negerror 10x1892dae0poserrormarker 10x1893e080marker 10x18963640marker 0x189113b0slackmarker 2 10x189107d0marker 10x18910b90negerror 10x18910b90poserrormarker expletives deleted uitableview0xca2b0contentheight 36 10xc221c00marker uitableview0xca2b0contentwidth 704 10xc239470marker uitableview0xca2b0minx 0 10xc2a23f0marker 050xc2a2590marker uitableview0xca2b0miny 0 10xc2a25d0marker 050xc2a2630marker uitableviewcellcontentview0x18ab13d0height 174 10x18abd4f0marker uitableviewcellcontentview0x18ab13d0width 704 10x18abd470marker expletives deleted nsautoresizingmasklayoutconstraint0x18988bc0 h v uiview0x18911e50midy uiview0x1892d0c0midy marker0x18988bc0marker nsautoresizingmasklayoutconstraint0x18994b40 h v uiview0xc4a6fb0midx uiview0xc4b4990midx marker0x18994b40marker nsautoresizingmasklayoutconstraint0x18998480 h v uiview0x18915180width uiview0xc4c5970width marker0x18998480marker nsautoresizingmasklayoutconstraint0x18aae320 h v tapsectionaltableviewcell0x18a3d270midx 352 marker0x18aae320marker nsautoresizingmasklayoutconstraint0x18aae410 h v htapsectionaltableviewcell0x18a3d270704 marker0x18aae410marker nsautoresizingmasklayoutconstraint0x18aae450 h v tapsectionaltableviewcell0x18a3d270midy 144 marker0x18aae450marker expletives deleted nsautoresizingmasklayoutconstraint0xc2de2f0 h v tapgenericcollectioncell0xc2ac500midx 499 marker0xc2de2f0marker nsautoresizingmasklayoutconstraint0xc2de3b0 h v vtapgenericcollectioncell0xc2ac50034 marker0xc2de3b0marker nsautoresizingmasklayoutconstraint0xc2de430 h v uiview0x18953f80height uiview0xc2acb20height marker0xc2de430marker nsautoresizingmasklayoutconstraint0xc2de520 h v uiview0x18923af0height uiview0xc2ae570height marker0xc2de520marker nsautoresizingmasklayoutconstraint0xc2de560 h v htapgenericcollectioncell0xc2ac500280 marker0xc2de560marker expletives deleted nscontentsizelayoutconstraint0xc2f5730 h uibaselinelayoutstrut0x18994a300 hug250 compressionresistance750 marker0xc2f5730poserrormarker nscontentsizelayoutconstraint0xc2f5730 h uibaselinelayoutstrut0x18994a300 hug250 compressionresistance750 marker0xc2f5730poserrormarker nscontentsizelayoutconstraint0xc2f5770 v uibaselinelayoutstrut0x18994a3018 hug250 compressionresistance750 marker0xc2f5770poserrormarkerinternal error cannot find an outgoing row head for incoming head uiview0x189712b0width which should never happen begin individual field controller this code is from the base individual field controller used in our editable form collection voidviewdidload super viewdidload selfviewclipstobounds yes selfviewopaque yes cgrect viewframe selfviewframe viewframesize self defaultfieldsize selfviewframe viewframe if selfbackgroundcolor selfviewbackgroundcolor selfbackgroundcolor else selfviewbackgroundcolor uicolor whitecolor self createlabelandfield self setlabelandfieldcontraints selfview addconstraintsselflabelvalueconstraints selfview setneedsupdateconstraints voidcreatelabelandfield self removelabelandfield uilabel label uilabel alloc init labelfont selflabelfont labeltextcolor selflabelcolor labellinebreakmode nslinebreakbywordwrapping labeltextalignment nstextalignmentleft labeladjustsfontsizetofitwidth no labelnumberoflines 0 if selfbackgroundcolor labelbackgroundcolor selfbackgroundcolor else labelbackgroundcolor uicolor whitecolor selfview addsubviewlabel selflabel label example valueview initialization from a subclass that handles long text tapeditabletextview textview tapeditabletextview alloc init if selfhaslabelovervalue textviewshouldmimictextfield no else textviewshouldmimictextfield yes textviewdelegate self textviewkeyboardtype uikeyboardtypedefault textviewfont selfvaluefont textviewtextcolor selfvaluecolor textviewtextalignment nstextalignmentleft textviewnormalbackgroundcolor selfbackgroundcolor textvieweditable no textviewtextlines selftextlines selfvaluetextview textview selfvalueview textview selfview addsubviewtextview voidremovelabelandfield self clearconstraints if selflabel selflabel removefromsuperview selflabel nil if selfvalueview selfvalueview removefromsuperview selfvalueview nil voidclearconstraints if selfisviewloaded selflabelvalueconstraints selfview removeconstraintsselflabelvalueconstraints selflabelvalueconstraints nil selflabeltovaluehorizconstraint nil selfvaluewidthconstraint nil this is called in our fields viewdidload after weve created our label and valueview uitextfield uitextview etc voidsetlabelandfieldcontraints self clearconstraints selflabelvalueconstraints nsmutablearray array selflabeltranslatesautoresizingmaskintoconstraints no selfvalueviewtranslatesautoresizingmaskintoconstraints no nslayoutconstraint constraint nil constraint nslayoutconstraint constraintwithitemselflabel attributenslayoutattributeleft relatedbynslayoutrelationequal toitemselfview attributenslayoutattributeleft multiplier10f constantselflabelvaluegap constraintpriority uilayoutpriorityrequired selflabelvalueconstraints addobjectconstraint constraint nslayoutconstraint constraintwithitemselflabel attributenslayoutattributetop relatedbynslayoutrelationequal toitemselfview attributenslayoutattributetop multiplier10f constant0 constraintpriority 550 selflabelvalueconstraints addobjectconstraint constraint nslayoutconstraint constraintwithitemselflabel attributenslayoutattributebottom relatedbynslayoutrelationequal toitemselfview attributenslayoutattributebottom multiplier10f constant0 constraintpriority 400 selflabelvalueconstraints addobjectconstraint constraint nslayoutconstraint constraintwithitemselfvalueview attributenslayoutattributetop relatedbynslayoutrelationequal toitemselfview attributenslayoutattributetop multiplier10f constant0 constraintpriority uilayoutpriorityrequired selflabelvalueconstraints addobjectconstraint constraint nslayoutconstraint constraintwithitemselfvalueview attributenslayoutattributebottom relatedbynslayoutrelationequal toitemselfview attributenslayoutattributebottom multiplier10f constant0 constraintpriority 499 selflabelvalueconstraints addobjectconstraint constraint nslayoutconstraint constraintwithitemselfvalueview attributenslayoutattributeright relatedbynslayoutrelationequal toitemselfview attributenslayoutattributeright multiplier10f constant kthisclosurewidth selflabelvaluegap constraintpriority 901 selflabelvalueconstraints addobjectconstraint constraint nslayoutconstraint constraintwithitemselfvalueview attributenslayoutattributeleading relatedbynslayoutrelationgreaterthanorequal toitemselflabel attributenslayoutattributetrailing multiplier10f constantselflabelvaluegap constraintpriority uilayoutprioritydefaulthigh 1 selflabelvalueconstraints addobjectconstraint selflabeltovaluehorizconstraint constraint constraint nslayoutconstraint constraintwithitemselflabel attributenslayoutattributebaseline relatedbynslayoutrelationequal toitemselfvalueview attributenslayoutattributebaseline multiplier10f constant0f constraintpriority 600 selflabelvalueconstraints addobjectconstraint constraint nslayoutconstraint constraintwithitemselfvalueview attributenslayoutattributewidth relatedbynslayoutrelationequal toitemselfview attributenslayoutattributewidth multiplier1f selflabelwidthpercentage constant0 constraintpriority 305 selflabelvalueconstraints addobjectconstraint selfvaluewidthconstraint constraint self setcompressionandhuggingforlabelviewselflabel self setcompressionandhuggingforvalueviewselfvalueview voidsetcompressionandhuggingforlabelviewuilabel labelview if labelview return labelview setcontentcompressionresistancepriority510 foraxisuilayoutconstraintaxishorizontal labelview setcontentcompressionresistancepriorityuilayoutprioritydefaulthigh foraxisuilayoutconstraintaxisvertical labelview setcontenthuggingpriority450 foraxisuilayoutconstraintaxishorizontal labelview setcontenthuggingpriorityuilayoutprioritydefaulthigh foraxisuilayoutconstraintaxisvertical voidsetcompressionandhuggingforvalueviewuiview valueview if valueview return valueview setcontentcompressionresistancepriority509 foraxisuilayoutconstraintaxishorizontal valueview setcontentcompressionresistancepriorityuilayoutprioritydefaulthigh foraxisuilayoutconstraintaxisvertical valueview setcontenthuggingpriority300 foraxisuilayoutconstraintaxishorizontal valueview setcontenthuggingpriority650 foraxisuilayoutconstraintaxisvertical end individual field controller,['ios'] +508385,create a high priority serial thispatch queue with gcd how can i create a custom serial queue that runs at high priorityright now i am using myqueue thispatch queue createcommyappmyqueue null but this does not seem to allow for setting a priority,['objective-c'] +508430,using jquery in combination with angularjs i am working to develop a single page framework for my company we build lots of sites and we build them quickly so we still rely heavily on multipage server side templates this means frontend developers pretty much only have to deal with css and jquery for some basic dom manipulation it is a great system for what we currently do but moving into the future of js based single page sites it requires lots time for new project resources especially frontend developers to get up to speedcurrently all of our singlepage applications rely on jquery and jqote2 for simple page transitions like the entire container is simply replaced again this works great since many of our sites are simple and straight forward but it becomes a mess when we need to do anything custom and it can sometimes take developers hours to figure out how to make a simple changei have been looking into using angular simply to manage pages and handle thisplaying the correct template based on a server call once angular has thisplayed the page the correct template and page i want the frontend devs to be able to use jquery to manipulate the current page similar to how one would manipulate a multipage sitefor me the big bonus with angular compared to jquery or jqm is the in element directives it is just so clear and easy for a developer to fire the site up take a quick look at the dom and understand how it is being modifiedessentially i want angular to serve as the controller and model when necessary then plop a view down for jquery to interact with is it possible to use angular with jquery in such a manneris angular total overkill for such a simple task i know i can write something custom but angular just seems to kick butt and has the ability to easily expand to our larger sites,['jquery'] +508467,jpasswordfield security with action command i am using a jpasswordfield in my program when i ask getpassword i get a char array but when i add an actionlistener to the jpasswordfield and ask getactioncommand i get the password as a string is this password save in the event object as string is not this a security issue,['java'] +508520,how to select multiple date in custom calendarview i am making custom calendar in android my requirement is that make multiple date selection same as shown in image any one have any suggestiontill now i make calendar on view and trying to draw path according to touch but its not working for mehere is my codepublic class calendarview extends view private float width width of one tileprivate float height height of one tileprivate int selx x index of selectionprivate int sely y index of selectionprivate final rect selrect new rectprivate gregoriancalendar month itemmonth calendar instancesprivate calendaradapter adapter adapter instanceprivate context mcontext private gregoriancalendar pmonthmaxsetprivate gregoriancalendar selecteddateprivate arrayliststring itemsprivate liststring daystringprivate gregoriancalendar pmonth calendar instance for previous month calendar instance for previous month for getting complete view private int firstdayprivate int maxweeknumberprivate int maxpprivate int calmaxpprivate int lastweekdayprivate int leftdaysprivate int mnthlengthprivate string itemvalue curentdatestringprivate dateformat dfprivate canvas macanvasprivate path mpathprivate float cselx x index of selectionprivate float csely y index of selectionpublic calendarviewcontext context supercontext mpath new path rectf mrectf new rectfselrect mpathad month gregoriancalendar gregoriancalendargetinstance itemmonth gregoriancalendar monthclone localesetdefaultlocaleus selecteddate gregoriancalendar monthclone mcontext context monthsetgregoriancalendarday of month 1 thisitems new arrayliststring df new simpledateformatymmdd localeus curentdatestring dfformatselecteddategettime daystring new arrayliststring macanvas new canvas refreshdaysoverrideprotected void onsizechangedint w int h int oldw int oldh width w 7f height w7f getrectselx sely selrect superonsizechangedw h oldw oldhoverrideprotected void ondrawcanvas canvas draw the background paint background new paint backgroundsetcolor colorgray canvasdrawrect0 0 getwidth getheight background draw the board define colors for the grid lines paint foreground new paintpaintanti alias flag foregroundsetcolorcolorred paint dark new paint darksetcolorcolorblue paint hilite new paint hilitesetcolorcolorblue paint light new paint lightsetcolorcolorblue draw the minor grid lines for int i 0 i 6 i canvasdrawline0 i height getwidth i height light canvasdrawline0 i height 1 getwidth i height 1 hilite for int i 0 i 8 i canvasdrawlinei width 0 i widthwidth5 light canvasdrawlinei width1 0 i width1width5 light foregroundsetcolorcolorred foregroundsetstylestylefill foregroundsettextsizeheight 075f foregroundsettextscalexwidth height foregroundsettextalignpaintaligncenter draw the number in the center of the tile fontmetrics fm foregroundgetfontmetrics centering in x use alignment and x at midpoint float x width 2 centering in y measure ascentdescent first float y height 2 fmascent fmdescent 2 int k 0 for int i 0 i 7 i for int j 0 j 5 j string datevalue filldatek canvasdrawtextdatevalue i width x j height y foreground ifmpathnull paint selected new paint selectedsetcolorcolorgreen canvasdrawpathmpathselected canvasdrawcirclex y 25 selected superondrawcanvasprivate void getrectint x int y rect rect rectsetint x width int y height int x width width int y height height public string filldateint index string date separates daystring into parts string separatedtime daystringgetindexsplit taking last part of date ie 2 from 20121202 string gridvalue separatedtime2replacefirst0 checking whether the day is in current month or not if integerparseintgridvalue 1 index firstday setting offdays to white color dayviewsettextcolorcolorwhite dayviewsetclickablefalse dayviewsetfocusablefalse else if integerparseintgridvalue 7 index 28 dayviewsettextcolorcolorwhite dayviewsetclickablefalse dayviewsetfocusablefalse else setting curent months days in blue color dayviewsettextcolorcolorblue if daystringgetindexequalscurentdatestring setselectedv previousview v else vsetbackgroundresourcerdrawablelist item background return gridvaluepublic void refreshdays clear items itemsclear daystringclear localesetdefaultlocaleus pmonth gregoriancalendar monthclone month start day ie sun mon etc firstday monthgetgregoriancalendarday of week finding number of weeks in current month maxweeknumber monthgetactualmaximumgregoriancalendarweek of month allocating maximum row number for the gridview mnthlength maxweeknumber 7 maxp getmaxp previous month maximum day 3130 calmaxp maxp firstday 1 calendar offday starting 2425 calendar instance for getting a complete gridview including the three months previouscurrentnext dates pmonthmaxset gregoriancalendar pmonthclone setting the start date as previous months required date pmonthmaxsetsetgregoriancalendarday of month calmaxp 1 filling calendar gridview for int and 0 and mnthlength n itemvalue dfformatpmonthmaxsetgettime pmonthmaxsetaddgregoriancalendardate 1 daystringadditemvalue private int getmaxp int maxp if monthgetgregoriancalendarmonth month getactualminimumgregoriancalendarmonth pmonthsetmonthgetgregoriancalendaryear 1 monthgetactualmaximumgregoriancalendarmonth 1 else pmonthsetgregoriancalendarmonth monthgetgregoriancalendarmonth 1 maxp pmonthgetactualmaximumgregoriancalendarday of month return maxpoverridepublic boolean ontoucheventmotionevent event switcheventgetaction case motioneventaction down selectint eventgetx width int eventgety height mpathmovetoeventgetx eventgety mpathlinetoeventgetx eventgety break case motioneventaction move invalidate cselx eventgetx csely eventgety mpathlinetocselxcsely break case motioneventaction up case motioneventaction cancel break return trueprivate void selectint x int y selx mathminmathmaxx 0 8 sely mathminmathmaxy 0 8 getrectselx sely selrect invalidateselrect,['android'] +508558,c get the cell text value if dataerror is triggered i have a datagridview and i populate it dynamically from my database via the following codedatagridviewtextboxcolumn colid new datagridviewtextboxcolumncolidheadertext idcoliddatapropertyname idcolidreadonly truecolidvisible falsedtgvloadexcolumnsaddcoliddatagridviewtextboxcolumn colloadexpirydate new datagridviewtextboxcolumncalendarcolumn colloadexpirydate new calendarcolumncolloadexpirydateheadertext loadexpirydatemmddyycolloadexpirydatewidth 158colloadexpirydatedatapropertyname loadexpirydatecolloadexpirydatereadonly falsecolloadexpirydatemaxinputlength 10dtgvloadexcolumnsaddcolloadexpirydatedtgvloadexdatasource data return data table from my databaseas you can see i have a date column when i attempt to edit a cell of that column and type an invalid format the dataerror event will triggerednow i just want to get the error text fromprivate void dtgvloadex dataerrorobject sender datagridviewdataerroreventargs e or any other process in order to get the error text,['c#'] +508591,youtube api v3 where can i find a list of each videocategoryid i am using the youtube api v3 but cannot find documentation for how to filter by categoryheres my coderesults youtubesearchlistsearchidsnippet array q getq maxresults 20 type video videocategoryid whatdoiputherei have been going through their documentation for an hour and cannot seem to find any reference to how i find out what the various categorys ids are in my case i am looking for the videocategoryid for music,['php'] +508697,using urlaction in javascript i am trying to use the urlaction method to correctly generate the required url for an ajax call but i am running into problems when trying to build the routevalues heres the problem line of codevar url urlactionviewfile default new itemid thisdataitemid as you can see i am trying to assign the result of the jquery thisdataitemidto itemid in the routevaluesis there a way using razor syntax which will allow this code to compile,"['c#', 'javascript', 'jquery']" +508717,cross domain jquery ajax request fails for put method put is not allowed by accesscontrolallowmethods i am doing cross domain requests via jquerys ajax to access a restful php apiin order to do so i have set the following headers in phpheaderhttp11 code statusheadercontenttype applicationjsonheaderaccesscontrolalloworigin headeraccesscontrolallowmethods get post putusing the types get and post works without problems however when i do a put ajax call firefox fails completely and shows options apiphp in the network tab of firebugin chrome the same thing happens first option request fails with message method put is not allowed by accesscontrolallowmethods but chrome follows up with the actual put request that actually works then what is the reason for this behaviour,['jquery'] +508764,changing the color of a clicked table row using jquery i need your helphow can i using jquerychange the background color of the selected row in my table for this example let us use the the css class highlightedand if the same row is clicked on again change it back to its default color white select the css class nonhighlighteddoctype htmlhtmlheadstyle typetextcsshighlighted background rednonhighlighted background whitestyleheadbodytable iddata border1 cellspacing1 width500 idtable1 tr tdnbsptd tdnbsptd tdnbsptd tdnbsptd tr tr tdnbsptd tdnbsptd tdnbsptd tdnbsptd tr tr tdnbsptd tdnbsptd tdnbsptd tdnbsptd tr tr tdnbsptd tdnbsptd tdnbsptd tdnbsptd trtablebodyhtml,"['javascript', 'jquery']" +508781,how to create jquery element methods with namespace suffice it to say i am wanting to branch my plugin writing a bit and decided i want to be able to namespace them so far rewriting the method ones to namespacemethod has been easythe problem i am having is making element methods such as elementmethod but to use a namespace for example elementnamespacemethod i have tried a few workarounds and can create fnnamespacemethod however when i call this from within that method i only get fnnamespace and not the element that i would like to getexample if i call bodynamespacetest then inside method test i want this to be the element bodybodyany help figuring out how to pull this off much appreciated probably just overthinking things as usualcurrently trying possible workarounds for something like bodynamespacemethod thus far not working so well p,['jquery'] +508785,ios 7 dynamic blur effect like in control center i am trying to make a controller that will be similar to control center in ios7 from wwdc session 226 i have learnt how to get blurred image with different effects uigraphicsbeginimagecontextwithoptionsimagesize null 0view drawviewhierarchyinrectrectuiimage newimage uigraphicsgetimagefromcurrentimagecontextuigraphicsendimagecontextlightimage newimage applylighteffectso in other words we just capture some image make screenshot perform blur effect and use this blurred image for our needsbut if you open control center above some dynamic content youll notice that control centers blurred background is changing as well as content doesdoes anybody know how to replicate this behaviorthe only way i see it is to capture content and make blur effect with some interval eg half a second but it looks redundantly,"['iphone', 'objective-c']" +508796,adopting a side menu in ios app view controllers structure issue i am designing an app intended to have the following navigation structure i need to have a welcome view with sign up and sign in buttons as most of apps havethis view does not show any navigation bar as it seems to be the common thing if sign in tapped then the login view will be presented modallyand if sign up tapped the welcome view navigates to a form requesting user input to create an accountthen once the user logs in and enters the app i would want it to have side menus similar to facebook youtube or spotifybeing the central panel a uinavigationcontroller left side panel i think it usually is an uiviewcontrollerthe point is i dona t know what the rootviewcontroller of my app should be and what hierarchy of view controllers should i have i have thought about a couple of possibilities1 being the rootviewcontroller an uinavigationcontroller push the welcome view hidding the navigation bar is that possible presenting the sign in view if needed or pushing the sign up view once the user has logged in pop these views from the rootviewcontroller that is a uinavigationcontroller and then push in such navigation controller the custom view controller managing the side menu stuff2 being the rootviewcontroller the side menu custom view controller and setting as its central panel an uinavigationcontroller push there the welcome view and so on without setting any view controller for the leftright panels and then when user has logged in pop those views from the central panels uinavigationcontroller push there the corresponding view and now setting the leftright panelsi hope i have explained myself maybe there is another and better approach to handle this scenario does somebody implemented an app like this i need help with this issue and also i will appreciate being recommended a custom librarycontrol providing the side menu stuff from someone who has used one and it is easy to use and customize i know there are lots of them mmdrawercontroller jasidepanels for example but i would like to have some opinions from people that had developed an app with one of themnote i need to support ipad as well and ios 5thanks a lot,['ios'] +508809,maxwidth does not work with float i am trying to design a responsive page i have 2 divs with the same heightthey both have the maxwidth property and the maxwidth is working once i add the floatleft property the maxwidth does not affect themheres an example jsfiddlediv classcolor1 some textdivdiv classcolor2 bladivdiv styleclear bothand the cssdiv height 100px float leftcolor1 backgroundcolor 6ac1ff maxwidth 400pxcolor2 backgroundcolor bdbcf4 maxwidth 100pxi want them to be align vertically is there another way to make it other than float andkeep the maxwidth,['css'] +508832,gcc failing to warn of uninitialized variable the following code has a variable that may be uninitialized it seems that gcc should be generating a warning but is not cat acint fooint b int a if b a 1 return a gcc47 c wall wmaybeuninitialized o ao ac gcc47 vusing builtin specscollect gccgcc47collect lto wrapperusrlibgccx86 64linuxgnu47ltowrappertarget x86 64linuxgnuconfigured with srcconfigure v withpkgversionubuntulinaro 4732ubuntu11204 withbugurlfileusrsharedocgcc47readmebugs enablelanguagesccgofortranobjcobjc prefixusr programsuffix47 enableshared enablelinkerbuildid libexecdirusrlib withoutincludedgettext enablethreadsposix withgxxincludedirusrincludec47 libdirusrlib enablenls withsysroot enableclocalegnu enablelibstdcxxdebug enablelibstdcxxtimeyes enablegnuuniqueobject enableplugin withsystemzlib enableobjcgc enablemultiarch thisablewerror witharch32i686 withabim64 withmultiliblistm32m64 withtunegeneric enablecheckingrelease buildx86 64linuxgnu hostx86 64linuxgnu targetx86 64linuxgnuthread model posixgcc version 473 ubuntulinaro 4732ubuntu11204any clues on how to get gcc to report the uninitialized variable,['c'] +508848,how to add path with module to python i try to build v8 javascript enginewhen i try to invoke the command python buildgit v8 i get errorfile buildgyp v8 line 48 in module import gypimporterror no module named gyphow i can tell python where search gyp module and what is the correct path to the module in the folder gypmy version of python is 2622 recommended in build instructions,['python'] +508872,true instead of true c the goalreturn true instead of true from controller to viewthe problemi am storing into a variable a boolean that indicates if a product exists or not in a shopping cartsummaryto realize this i am doing the followisadded sessionstorecheckexistanceonsummaryproductproductidbut when i show the value of isadded on the view the return is true or false a and javascript is expecting true or falsewhat i need is to send true or false instead of this way that c is sendingwhat i have already triedi already tried to change the aboves code fragment for thisisadded sessionstorecheckexistanceonsummaryproductproductid true falsebut debugger returns me the following errorerror 5 cannot implicitly convert type string to boola few lines of codethe implementation of checkexistanteonsummary ispublic bool checkexistanceonsummarynullableint productid listproducts productslist listproductssessionsummarysessionindex if productslistwhere product productid intproductidfirstordefault null return false else return trueduplicatedi read this topic but were not helped me,['c#'] +508908,intellij does not find native libraries for opencv when adding jar as a dependency for play project i am currently working on a play 21 project in which requests to the webservice will handle downloading usersupplied images resizing and recropping them and also filtering out known bad photos for example we do not want users to upload company logos we are trying to use opencv to handle the backend work but i cannot seem to get intellij to add the opencv jar in a way that works with the java projecti have been able to build opencv from source without issue this left me with the following folderhomecharlesopencvreleaseinside this folder i have three files of interestbinopencv246jarlibcv2soliblibopencv java246soif i try to add the jar file to intellij as a new java library it seemingly finds all the classesmethods and i can write code using the autocomplete i can also click on the respective classes or methods and it brings me to the right fileshowever when i try to run the play project i get this errorinfo loading project definition from homecharlesgithubimageprojectinfo set current project to imageproject in build filehomecharlesgithubimageproject running the application from sbt autoreloading is enabled info play listening for http on 090server started use altd to stopinfo compiling 1 java source to homecharlesgithubimageprojecttargetscala210classeserror homecharlesgithubimageprojectappcontrollersapplicationjava7 error package orgopencvcore does not existerror import orgopencvcorecoreerror i have also tried adding a copy of the jar file directly into the project so putting opencv246jar into imageprojectlib and then adding the java library from that location instead but that just leaves me with a different errorjavalangunsatisfiedlinkerror no opencv java246 in javalibrarypathi suspect part of the problem may be related to the native libraries that the java opencv wrapper uses file 2 or 3 above in eclipse when you add a jar file you can explicitly set the native library location which makes opencv work fine i have read suggestions of using this to fix the problemdjavalibrarypathhomecharlesopencvreleaselibbut that does not seem to work though maybe i am setting it in the wrong place i have tried setting it as a jvm parameter in the run config for the project and in the ide settings but neither seem to be used or respectednote just to clarify again this is a play2 project not an android project there seems to be some androidspecific help out there that is not relevant in this casethis feels like it should be a rather straight forward thing but i have been spending several days trying to find an answer at this point and still have nothing any ideasadditional detailsi also tried following the running sbt samples of the opencv documentation here javajava dev introhtmland i also get a similar errorcharlescharlesvirtualboxjavasample sbt runinfo loading project definition from homecharlesjavasampleprojectinfo set current project to javasample in build filehomecharlesjavasampleinfo compiling 1 java source to homecharlesjavasampletargetscala210classesinfo running helloopencv hello opencverror runmain javalangunsatisfiedlinkerror no opencv java246 in javalibrarypathjavalangunsatisfiedlinkerror no opencv java246 in javalibrarypath at javalangclassloaderloadlibraryclassloaderjava1856 at javalangruntimeloadlibrary0runtimejava845 at javalangsystemloadlibrarysystemjava1084 at helloopencvmainhelloopencvjava47 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava57 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43 at javalangreflectmethodinvokemethodjava601trace stack trace suppressed run last compilerun for the full outputjavalangruntimeexception nonzero exit code 1 at scalasyspackageerrorpackagescala27trace stack trace suppressed run last compilerun for the full outputerror compilerun nonzero exit code 1error total time 2 s completed jul 17 2013 51139 pm,['java'] +508921,sequelize changing model schema on production were using the orm sequelizejs and have defined a model as suchmoduleexports functionsequelize datatypes var source sequelizedefinesource name type datatypesstring allownull false unique true paranoid true return sourcethis is deployed to production and syncd to the database using sequelizesync next step we add a parametermoduleexports functionsequelize datatypes var source sequelizedefinesource name type datatypesstring allownull false unique true location type datatypesstring paranoid true return sourcehowever when deploying to production sequelizesync does not add this new parameter this is because sync does acreate table if not existsand does not actually update the schema if the table exists this is noted in their documentationthe only option seems to be to force true however this is not okay for a production databasedoes anyone know how to properly update the schema when changes are necessary,['javascript'] +508932,svg image does not show in firefox inside a simple svg element i have an imagechrome version 28 works perfectfirefox 220 no image is drawnopera 1216 image is show 4 times larger than normalcode svg width500px height500px viewbox0 0 70 70 image x0 y0 width10 height10 idknight xlinkhrefimagesknightsvg svg,['html'] +508943,trouble running ssis package programmatically and from command line dtexec i am attempting to execute an ssis package programmatically using capplication app new applicationpackage package apploadpackagepkgfullpath nullpackageexecutei am getting an error sayingerror in microsoftsqlserverdtsruntimetaskhostssispipeline to run a ssis package outside of sql server data tools you must install conditional split of integration services or highererror in microsoftsqlserverdtsruntimetaskhostssispipeline to run a ssis package outside of sql server data tools you must install lookup of integration services or higheri am using ssis in visual studio 2010 but executing the c code from an nunit test in vs 2012 running net 40the package runs fine inside the ssis project in vs 2010 if i launch it with debugging press f5 but it fails with the same error if i try to run it using dtexec from the command line same failure in both 32 and 64 bit version of dtexec it also fails with the same error if i launch it from inside visual studio using ctrl f5 without debuggingi have found articles online that suggest it is related to a 64 bit v 32 bit problem but i am seeing the same error when running both versions of dtexec i am using version 110210060 of dtexec which matches the version of the sql server integration services designer in vs 2010i do not get the error if i run a simple package without a conditional split and lookup do i have to install something extra in order to run this outside of visual studioany ideas,['c#'] +508944,jni passing large amounts of data between java and native code i am trying to achieve the following1 i have a byte array on the java side that represents an image2 i need to give my native code access to it 3 the native code decodes this image using graphicsmagick and creates a bunch of thumbnails by calling resize it also calculates a perceptual hash of the image which is either a vector or a unint8 t array4 once i return this data back to the java side different threads will read it the thumbnails will be uploaded to some external storage service via httpmy questions are1 what would be the most efficient way to pass the bytes from java to my native code i have access to it as a byte array i do not see any particular advantage to passing it as a byte buffer wrapping this byte array vs a byte array here2 what would be the best way to return these thumbnails and perceptual hash back to the java code i thought of a few optionsi i could allocate a byte buffer in java and then pass it along to my native method the native method could then write to it and set a limit after it is done and return the number of bytes written or some boolean indicating success i could then slice and dice the byte buffer to extract the thistinct thumbnails and perceptual hash and pass it along to the different threads that will upload the thumbnails the problem with this approach is i do not know what size to allocate the needed size will depend on the size of the thumbnails generated which i do not know in advance and the number of thumbnails i do know this in advanceii i could also allocate the byte buffer in native code once i know the size needed i could memcpy my blobs to the right region based on my custom packing protocol and return this byte buffer both i and ii seem complicated because of the custom packing protocol that would have to indicate the the length of each thumbnail and the perceptual hashi define a java class that has fields for thumbnails array of byte buffers and perceptual hash byte array i could allocate the byte buffers in native code when i know the exact sizes needed i can then memcpy the bytes from my graphicsmagick blob to the direct address of each byte buffer i am assuming that there is also some method to set the number of bytes written on the byte buffer so that the java code knows how big the byte buffers are after the byte buffers are set i could fill in my java object and return it compared to i and ii i create more byte buffers here and also a java object but i avoid the complexity of a custom protocol rationale behind i ii and i given that the only thing i do with these thumbnails is to upload them i was hoping to save an extra copy with byte buffers vs byte array when uploading them via nioiv define a java class that has an array of byte arrays instead of byte buffers for the thumbnails and a byte array for the perceptual hash i create these java arrays in my native code and copy over the bytes from my graphicsmagick blob using setbytearrayregion the thisadvantage vs the previous methods is that now there will be yet another copy in java land when copying this byte array from the heap to some direct buffer when uploading it not sure that i would be saving any thing in terms of complexity vs i here eitherany advice would be awesomeedit main suggested an interesting solution i am editing my question to follow up on that option if i wanted to wrap native memory in a directbuffer like how main suggests how would i know when i can safely free the native memory,['java'] +508946,i want to create a column of value counts in my pandas dataframe i am more familiar with r but i wanted to see if there was a way to do this in pandas i want to create a count of unique values from one of my dataframe columns and then add a new column with those counts to my original data frame i have tried a couple different things i created a pandas series and then calculated counts with the value counts method i tried to merge these values back to my original dataframe but i the keys that i want to merge on are in the indexixloc any suggestions or solutions would be appreciatedcolor valuered 100red 150blue 50and i wanted to return something likecolor value countsred 100 2red 150 2 blue 50 1,['python'] +509007,why is not a conversion to generictype allowed here this code causes a compile error with javac but notably not with eclipse 422public interface foot class bart implements fooiterablet class test void testfoo extends iterable extends string foo bar bar bar foo the error from javac is thisfoojava9 error inconvertible types bar bar bar foo required bar found foocap1 where cap1 is a fresh typevariable cap1 extends iterable extends string from capture of extends iterable extends stringchanging the cast to bar foo ie using the raw type allows the code to compile as does changing the type of foo to simply foo extends iterableedit hilariously this simple change causes eclipse to reject but javac to acceptvoid testfooiterablestring foo bar bar bar fooand both eclipse and javac reject this onevoid testfooiterable extends string foo bar bar bar foo,['java'] +509095,why does the greet function not return the expected value questionwhy does the greet function not return the expected valuecodefunction personname thisname namepersonprototypegreet functionothername return hi othername my name is namehow do i answer this i create a new person then what do i dovar john new personjohn,['javascript'] +509101,how to alias a table in laravel eloquent queries or using query builder lets say we are using laravels query builderusers dbtablereally long table name selectreally long table nameid geti am looking for an equivalent to this sqlreally long table name as short namethis would be especially helpful when i have to type a lot of selects and wheres or typically i include the alias in the column alias of the select as well and it gets used in the result array without any table aliases there is a lot more typing for me and everything becomes a lot less readable cannot find the answer in the laravel docs any ideas,['php'] +509159,the relationship between coregraphics uiviews and calayers i always used coregraphics and coreanimation i understand how each of them works on their own but not those edge cases when one have to talk with the other i also understand that uiviews are a nice wrapper for calayer where calayer does all the heavy lifting of rendering and the uiview adds the touchbased responsivenessbut all the questions i have seen thus far attack the problem from one side or the other not the interplay between them specially between coregraphics and calayeranyway my question is how does coregraphics relate to calayermy understanding is that a calayer wraps the coregraphics methods to draw itself but does it once and can live with the snapshot of itself until invalidated but how these drawing methods interplay with the sublayers of that layer are they exclusivefor example what happens when i have a uiview that has subviews and i overload the drawrect method how does that affect the drawing of its sublayersis it even a good idea to intermix the two inside the same functionalso i am asking only about ios i understand that mac is a different beast and also have those fancy cifilters bastardsprior researchheres some related questions i have researched beforehandconfusion regarding quartz2d core graphics core animation core images this question asks the differences between each other and the chosen answer indeed delivers but it answers for each individual library as if the other did not existto drawrect or not to drawrect another great question but it addresses only the subject of drawing coregraphics vs handing the problem to uikit but anyway the chosen answer delivers parts of the puzzleanimating pie slices with custom calayer must be one of the most valuable tutorials i have seen in this subject it is the only one that has guided me through to drawing a calayerwhat is different between coregraphics and coreanimation absolutely thisappointed on how quick the asker accepted the answer i feel that there is a whole lot more going in herevarious wwdc videos but i have not seen one that explains in detail the general scope if anyone replies with a wwdc video that does i will consider that a valid answer,['ios'] +509203,html5 javascript iphone file upload preventing phone from going to sleep usecasehtml5 website iphone is used to upload big video files from the gallery big files take considerable time to uploadiphone get into sleep mode within 15 secondswhile in sleep mode formdatamultipart upload is pausedhaving the above in mind it is not practical to upload big files using an iphone websitei must have this implemented using a websiteusing a website and not an app is there any way toprevent the phone from going to sleep while uploadingkeep javascriptupload running while the phone is sleepingany help will be appreciated,"['javascript', 'iphone']" +509214,why does calling a method in my derived class call the base class method consider this codeclass program static void mainstring args person person new teacher personshowinfo consolereadline public class person public void showinfo consolewritelinei am person public class teacher person public new void showinfo consolewritelinei am teacher when i run this code the following is outputtedi am personhowever you can see that it is an instance if teacher not of person why does the code do that,['c#'] +509216,boostspiritqi how to return attributes with nabialek trick following several tutorials eg i want to use the nabialek trick to have a dynamic parser parsing already works fine but i do not get the attributes transported explanations like suggest that attributes should be possible but not argumentsthis is just a small example parsing a string and a number into a struct it is just for showcasing my problem this method should be used in a larger system later on where the dynamic parser is really neededquestion how do i transport attributes with the nabialek tricki am not an spirit expert so please bear with me i am using gcc 481 and boost 154define boost spirit debugdefine boost spirit use phoenix v3include boostfusionadaptedstructhppinclude boostspiritincludeqihppinclude boostspiritincludephoenixhppnamespace qi boostspiritqinamespace phx boostphoenix data structurestruct myline myline n0 s mylineint n stdstring s nn ss void setint n stdstring s and n s s int n stdstring sboost fusion adapt structmyline int n stdstring s parser grammartemplatetypename it typename skipper qispace typestruct parser qigrammarit myline skipper parser parserbase typestart using namespace qi start line string qilexeme qichar one string qiint val phxconstructmyline 2 1 two qiint string keywordaddone onetwo two line keyword a 1 qilazy a on errorfail start stdcout phxvalerror expecting 4 phxval here phxconstructstdstring 3 2 phxvaln boost spirit debug nodesstartlineonetwo private templatetypename attr using rule qiruleit attr skipper rulemyline start one two qiruleit myline skipper qilocalsrulemyline line rulestdstring string qisymbolschar rulemyline keywordint main for const stdstring input stdvectorstdstring one test1 two 2test auto fstdbegininput lstdendinput const static parserdecltypef p myline parsed script bool ok qiphrase parsef l p qispace parsed script if ok stdcout invalid inputn stdcout parsed script and parsed script s stdendl if f l stdcout unparsed stdstringf l stdendl parsing resultstart tryone test1try line tryone test1try one try test1try succesuccess attributes1 t e s tattributes one succesuccess attributesattributeslocals0x43b0e0locals line succesuccess attributes0 attributesstartstart trytwo 2testtry line trytwo 2testtry two try 2testtry succesuccess attributes2 t e s tattributes two succesuccess attributesattributeslocals0x43b110locals line succesuccess attributes0 attributesstart,['c++'] +509217,confusion between c and opengl matrix order rowmajor vs columnmajor i am getting thoroughly confused over matrix definitions i have a matrix class which holds a float16 which i assumed is rowmajor based on the following observationsfloat matrixa16 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 float matrixb44 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 matrixa and matrixb both have the same linear layout in memory ie all numbers are in order according to order this indicates a rowmajor layoutmatrixa0 matrixb00matrixa3 matrixb03matrixa4 matrixb10matrixa7 matrixb13therefore matrixb0 row 0 matrixb1 row 1 etc again this indicates rowmajor layoutmy problem confusion comes when i create a translation matrix which looks like 1 0 0 transx0 1 0 transy0 0 1 transz0 0 0 1which is laid out in memory as 1 0 0 transx 0 1 0 transy 0 0 1 transz 0 0 0 1 then when i call gluniformmatrix4fv i need to set the transpose flag to gl false indicating that it is columnmajor else transforms such as translate scale etc do not get applied correctlyif transpose is gl false each matrix is assumed to be supplied in column major order if transpose is gl true each matrix is assumed to be supplied in row major order why does my matrix which appears to be rowmajor need to be passed to opengl as columnmajor,['c++'] +509302,fullcalendar ignoretimezone does not seems to work i am using full calendar and i think i m doing something wrong as i set the property ignoretimezone true but it does not seems to work it always thisplays the time according to 530local timezone when i set the time by converting in to another timezone using php always thisplays according to 530allday false end thu 18 jul 2013 170 0100 id 5 ignoretimezone true start thu 18 jul 2013 150 0100 title test 2ndas here time shows 150170 but in calendar it thisplays somthing this 19302130 ie adding with 530 instead i set the ignoretimezone to trueany idea,['php'] +509312,fill the outside of a rectangle i would like to draw a rectangle in wpf by code and to fill the outside of ithere is an example the outside of the rectangle is grey with low opacity and the fill of the rectangle is trasparent,"['c#', '.net']" +509318,view model validation vs domain model validation if client validation is done when is it necessary to do domain level validationi use aspnet mvc for my web applications i like to thistinguish between my domain models and view models my domain models contain the data that comes from my database and my view models contain the data on my viewspageslets say i am working with customer datai will have a table in my database called customersi will have a customer class which could look something like thispublic class customer public int id get set public string firstname get set public string lastname get set public datetime dateofbirth get set and i will a create customer view model to represent only the data that i have on my viewvalidatortypeofcustomercreateviewmodelvalidatorpublic class customercreateviewmodel public string firstname get set public string lastname get set public datetime dateofbirth get set i will have a create view that accepts my customercreateviewmodel and binds my input fields to my view modelmodel myprojectviewmodelscustomerscustomercreateviewmodelusing htmlbeginform table tr td htmltextboxforx xfirstname htmlvalidationmessageforx xfirstname td tr tr td htmltextboxforx xlastname htmlvalidationmessageforx xlastname td tr table button idsavebutton typesubmitsavebuttonas you can see i have a customercreateviewmodelvalidator that contains my validation rules after the user has entered some data into the text boxes he will click the submit button if some of the fields are empty then validation fails if all the required fields are entered then validation succeeds i will then map the data from my view model to my domain model like thiscustomer customer mappermapcustomerviewmodelthis customer domain model i take and pass it onto my repository layer and it adds the data to my tablewhen does validation need to be done on a domain model i do all my validation on my view model i can validate my data in my domain model just before i add it to the database but seeing that it was validated on the view model wouldnt it be just replicating the same validation on the client sidecould someone please share some light on this validation matter,"['c#', 'asp.net', '.net']" +509334,multiple linqtables in method i have created a little bit of code which adds data from linqtables dcgtmd financials to a usercontrol for every entry in the database it shows a new usercontrolbut i would like to use this code in a method to reuse it throughout the application my problem is that each time i call the method i would like to use a different table from the database so gtmd financials changesi cannot seem to figure it out and would really appreciate any form of help or example int locationcontrol 78 dataclasses1datacontext dc new dataclasses1datacontext dcgtmd financialstolistforeachx kpientrys uc new kpientrys usercontrol uckpi xkpi add data to properties ucstatus xstatustostring ucgoal xgoaltostring uccurrently xcurrentlytostring bool checkaction xshowaction true ucshowaction true ucshowaction false bool checkstats xshowstats true ucshowstats true ucshowstats false bool checkstatus xstatus xstatussignal ucstatusgood true ucstatusgood false uclocation new point21 locationcontrol thiscontrolsadduc add control to form locationcontrol locationcontrol 34 if something is unclear please let me knowthanks in advance for any helpediti cannot seem to get it working with the help i already got i was able to edit the method a little bit with the help from replys i already got int locationcontrol 78 dataclasses1datacontext dc new dataclasses1datacontext public listcontrol loadkpistablegtmd financial dbtable var controls new listcontrol dbtabletolistforeachx kpientrys uc new kpientrys uckpi xkpi ucstatus xstatustostring ucgoal xgoaltostring uccurrently xcurrentlytostring ucshowaction boolxshowaction ucshowstats boolxshowstats ucstatusgood xstatus xstatussignal uclocation new point21 locationcontrol controlsadduc locationcontrol locationcontrol 34 return controls so let me rephrase my question how can i change the class when i call the method loadkpistablegtmd financial dbtable so gtmd finacial changes,['c#'] +509347,css image overlay with color and transparency i am trying to figure out if i can add an overlay to an image like a tint and change the opacity without adding background color i had no luck so i thought i would ask herei would like to make it red with that opacity here is what i have so far i made an image to overlay it if i have to called overlaypng but do not know if its necessaryimghighlighted opacity04basically i want to do this but reverse for image to tint when hovered not to take the tint away when hoveredcheck it out here,"['html', 'css']" +509350,how can i test several exeptions within one test using an expectedexception rule got a question regarding the usage of junit is expectedexception ruleas suggested here junit expectedexception rulestarting from junit 47 one can test exceptions like this which is much better then the testexpectedexceptionclassrulepublic expectedexception exception expectedexceptionnonetestpublic void testfailuresofclass foo foo new foo exceptionexpectexceptionclass foodostuffnow i needed to test several exceptions in one test method and got a green bar after running the following test and thus thought every test passed testpublic void testfailuresofclass foo foo new foo exceptionexpectindexoutofboundsexceptionclass foodostuff this is not tested anymore and if the first passes everything looks fine exceptionexpectnullpointerexceptionclass foodostuffnull exceptionexpectmyownexceptionclass foodostuffnull exceptionexpectdomainexceptionclass foodootherstuffhowever after a while i realized that the testmethod is quit after the first check passes this is ambiguous to say the least in junit 3 this was easily possibleso here is my questionhow can i test several exeptions within one test using an expectedexception rule thanks,['java'] +509370,how to check android device codename some android devices models are released in many versions i suppose they differ in their firmwares rom which varies according to the region and the carrier it has been sold in the question is how can i check whether my samsung galaxy s3 is md0 m0skt or maybe d2spr the best would be to check it programmatically is it possible,['android'] +509428,gruntjs replace templates when copying a file i am writing a gruntjs script which shouldconcatenate replace template of some js files into target directory contribconcatcopies replace template of some other files contribcopypackage the files into a zip filecontribconcat has a boolean option process to replace templates like pkgversion when processing filescontribcopy also has an option processcontent however i do not know how to trigger template processing with this optionmoduleexports functiongrunt gruntinitconfig meta banner pkgtitle pkgname v pkgversion grunttemplatetodaymmdd n pkghomepage n nn build date grunttemplatetodaymmdd build num processenvbuild number 0 jenkins build number if available version string pkgversion metabuild num thist dir thist pkgversion pkg gruntfilereadjsonpackagejson concat options stripbanners block true process true separator n n banner metabanner thist src srcviewutilityjs srcviewclassjs srcviewclassjs srcmarksclassjs srcviewversionjs dest buildviewjs uglify options mangle except jquery hammer banner metabanner thist src pkgmain dest buildviewminjs copy options processcontent true thist files expand true cwd build src dest metathist dir view expand true cwd src src viewtpjs dest metathist dir view expand true cwd src src pluginjson dest metathist dir compress thist options archive view metaversion string metabuild date zip expand true cwd thist src gruntloadnpmtasksgruntcontribuglify gruntloadnpmtasksgruntcontribconcat gruntloadnpmtasksgruntcontribcopy gruntloadnpmtasksgruntcontribcompress gruntregistertaskdefault concat uglify copy compressprocesscontent above does not work please suggest solutions,['javascript'] +509601,android video filter i am trying to create an app where i am able to add filters to a recorded video basically i want to replicate the functionality that exists in instagram video or viddy i have done research and i cannot piece it all together i have looked into using glsurfaceview to play the recorded video and i know i could use ndk to do the pixel manipulation and send it back to the surfaceview or save it somehow the problem is i do not know how to send the pixel data because there seems to be no function to access it this idea came from the camera function onpreviewframe the function returns a byte array allowing me to manipulate the pixels and thisplay itanother idea is to use glsurfaceview and use opengl to render the filter glsurfaceview has a renderer you can set but i am not very familiar with opengl but again this goes back to actually getting the pixels of each video frame i also read about ripping each frame as a texture and then manipulating the texture in opengl but the answers i have come across are not very detailedlastly i have looked into javacv trying to use ffmpegframegrabber but i have not had much either i wanted to just grab one frame but when i try to write the frames bytebuffer to an imageview i get a buffer not large enough for pixels error any guidance would be great,['android'] +509682,passing parameter to a module javascript i am using module pattern in javascriptis it a way to create instances of a class i am using it in a right way var moduleclass function var a 5return geta function consoleloga var instance moduleclassinstancegetahow can i pass parameters on new instances,['javascript'] +509688,post data not appearing in cakephp controller i am using ajax on a knockoutjs form to post some information that cakephp should receive however cake does not seem to find anything also the alert is not appearing despite a 200 status ok from the postheres the ajaxajax url ordersfinalize payment type post datatype json contenttype json data jsonstringifycustomer customer id success function alertsuccess heres the corresponding action in the orders controller right now i completely stripped it to just the bare minimumfunction finalize paymentid null thislayout false thisautorender false ifthisrequestispost the user has submitted which status to view print rthisrequestdata echo test just to make sure it is reaching this point when i open up the network tab in chrome it shows the request payload ascustomer 1the post shows as success status 200 i checked the response headers and it just showsarraytestdespite chrome showing a payload being sent cakephp is not finding it apparently updatei changed the request from ajax to post and it worked i still have no clue whypostordersfinalize paymentcustomer idcustomer idfunctiondata alertsuccess,"['php', 'jquery']" +509693,cast byte array to float i have a program that needs to take in 4 bytes and convert them to an ie754 float the bytes are transferred out of order but i can put them back in order just fine my problem is casting them to a float the relevant parts of codeunion to store bytes and float on top of each othertypedef union unsigned char b4 float f bfloatcreate instance of the unionbfloat temperatureadd float data using transmitted bytesmmitemperatureb2 0xd1mmiresponsemsg7mmitemperatureb3 0xe1mmiresponsemsg8mmitemperatureb0 0x41mmiresponsemsg9mmitemperatureb1 0xd7mmiresponsemsg10attempting to read the float valuelwholelong floatmmitemperaturefdebuggingstevenfloat floatmmitemperatureflwhole is a long and stevenfloat is a float when debugging i can see that the values i assign to the byte array are being stored correctly however the values of stevenfloat and lwhole are incorrect they seem to hover close to 0 or close to the max floatlong values a long and float are both 32 bits with my compilerdoes anyone know why this is not working it looked correct to me when i received the code to work on and it appears to be a common solution online i am just stumped,"['c++', 'c']" +509789,why does python allow an empty function with docstring body without a pass statement class somethingobject represents something def method oneself this is the first method will do something useful one day def method twoself a b returns the sum of a and b return a bin a recent review of some code similar to the above a colleague askedhow come method one is successfully parsed and accepted by python does not an empty function need a body consisting of just pass ie should not it look like thisdef method oneself this is the first method will do something useful one day passmy response at the time was something likealthough the docstring is usually not considered to be part of the function body because it is not executed it is parsed as such so the pass can be omittedin the spirit of sharing knowledge qa style i thought i would post the more rigorous answer here,['python'] +509801,determine if given class attribute is a property or not python object it is all in the title here is the following exampleclass aobject my var 5 def my methodself drinkbeer return i like s drink property def my propertyself return i do not drink coffeei instantiate an a object and i want to know the type of each attribute and if it is a callable for this i am using dirobj afor attr in dirobj print type s typeobj print is callable s callableattri have to know also if an attribute is a property i am sure that there is a way to know thisall suggestions will be appreciated,['python'] +509816,good way to check if file extension is of an image or not i have this file types filters public const string png png portable network graphics png png public const string jpg jpeg file interchange format jpg jpeg jfif jpgjpegjfif public const string bmp bmp windows bitmap bmp bmp public const string tif tif tagged imaged file format tif tiff tiftiff public const string gif gif graphics interchange format gif gif public const string allimages image file png jpg jpeg jfif bmptif tiff gif public const string allfiles all files static filesfilters imagestypes new liststring imagestypesaddpng imagestypesaddjpg imagestypesaddbmp imagestypesaddtif imagestypesaddgif obs is there any default filters in net or a free library for thati need a static method that checks if a string is an image or not how would you solve this ext pathgetextensionyourpath public static bool isimageextensionstring ext return ext bmp etc etc solution using jeroen vannevel endswith i think it is ok public static bool isimageextensionstring ext return imagestypescontainsext,['c#'] +509832,why is width 100 not working on div thisplay tablecell i am trying to vertically and horizontally center some content overlaying an image slide flexslider there were some similar questions to this one but i could not find a satisfactory solution that applied directly to my specific problem because of the limitations of flexslider i cannot use position absolute on the img tag in my implementationi almost have workaround below working the only problem is i cannot get the width height declarations to work on innerwrapper div with the thisplay tablecell property is this standard behavior or am i missing something with my code if it is standard behavior whats the best solution to my problemhtmlul li img src div classouterwrapper div classinnerwrapper h1my titleh1 h5subtitleh5 div div liulcsshtml body margin 0 padding 0 width 100 height 100ul background c height 100 width 100 liststyleposition outside margin 0 padding 0li width 100 thisplay tableimg width 100 height 410pxouterwrapper position absolute width 100 height 100 top 0 margin 0 padding 0innerwrapper thisplay tablecell verticalalign middle textalign center width 100 height 100note the centered content will be more than 1 element so i cannot use the lineheight trickjsfiddle,"['html', 'css']" +509834,why cannot an anonymous class access variables of its enclosing class i am reading about anonymous classes in java and it says you can access the methods of the enclosing class but not the local variables why is it like this i am talking about thisedit the older example was incorrect not reflecting what i meant this should be a better example according with what its being written here in the section accessing members of enclosing class public class myclass public interface someinterface public void someothermethod public void somemethodint somelocalvar someinterface myclass new someinterface public void someothermethod somelocalvar 0 this must be final to work so what problem is this restriction solving,['java'] +509874,ios app nonretina and retina images concept i am asking this question just for information and to clear my concepts about images in ios application retina and nonretina deviceswhat i currently do iswhen i develop an iphone application and i have to show an image lets say on uibutton using interface builder i take two images lets suppose submitpng button image of following sizes100x100 px submitpng200x200 px for retina thisplay and in interface builder i will set the size of uibutton 100x100 px and its just works perfectlyquestionwhy do not we place only single image lets say submitpng200x200 px submitpngand set uibutton size 100x100 px in interface builder and same image will be used in both retina and nonretina devices what is the actual reason of using two images rather than one single image of retina sizeanother similar question iphone 5 is only available in retina thisplay but we have to place its default images as why at 2x,"['iphone', 'ios']" +509918,inferred type is not a valid substitute for a comparable generic type consider the codepublic abstract class itemt implements comparablet protected t item public int comparetot o return 0 this does not matter for the time being public class myitemt extends itemstring t objectpublic class foot protected arraylistt listpublic class barv extends foomyitemv public void sort collectionssortlist the sort call gives the errorbound mismatch the generic method sortlist t of type collections is not applicable for the arguments arraylist myitem t the inferred type myitem t is not a valid substitute for the bounded parameter t extends comparable super t why is this wrongif myitemv implements comparable then why is it not a substitutesorry if this has been asked but i feel the question is somewhat specific,['java'] +509919,complex shape character outline say i have this character and i want allow user to select it so when it s selected i want to show an outline around itthe character is an object3d with some meshesi tried to clone and set a backside material but it did not work the problem was each cube in the shape was render with backside separately so the outline was wrongdo i need to create another mesh for the outline is there an easier way,['javascript'] +509922,the method managedqueryuri string string string string from the type activity is deprecated when i compile the following codecursor activitymanagedquery imageuri proj null null null i get following warningthe method managedqueryuri string string string string from the type activity is deprecatedthe code is working fine what should i do to avoid this,"['java', 'android']" +509956,does relational operator affect assignment operator operations why the output of below mentioned program is 0 not 20 include stdiohint main int i 10 j 0 if i j i 10 do something printfdnj,['c'] +510031,error could not find or load main class x linux i am very new to linux environmenti am trying to run an simple hello world java class in linux environmenthello java package comutil public class hello param args public static void mainstring args systemoutprintlnhi i have compiled java class in windows environment and uploaded the class file to linux system into homescripts pathmy command is as followsjava cp homescripts comutilhellowhen i am executing this command from this same homescripts where helloclass is there i am gettingerror could not find or load main class comutilhello and not able to proceed furthercan some one help me in this issue,['java'] +510032,sidekiq and rails 4 actionmailer never delivers emails i have setup sidekiq in a rails 4 application for sending emails and processing background jobs i have also devise which i am using devise async and a typical contact form emailer i am using gmail for sending emailsif i remove sidekiq it sends the emails normally through gmail both devise and contact form but when i am enabling it it does not work neither devise async neither contact form sidekiq shows that the background jobs starts and finishes successfully i also see them through the sinatra app that it is been processed but the email never been delivered in development the console shows that the emails sent both with devise async and from contact form as they are processed with sidekiq successfullywhat i have already have tryi have added the github branch for rails4 of sidekiq i have also tried the master i have updated and check rethis version to be greater than24 it is 2614i am running sidekiq with bundle exec sidekiqbut nothing worked i am using ruby 200p247 i have also setup image processing with sidekiq in this app and works perfectly both in development and in productioni am not doing anything fancy but i am adding the code for completionmy mailer code def send message message messagenewmessage params if messagesave contactmailerdelaycontact formmessageid end endmy mailer def contact formmessage id message messagewhereid message idfirst email messageemail message messagetext mailto subject message from contact form endand my configuration for production which it works without sidekiq configaction mailerdelivery method smtp actionmailerbasesmtp settings address smtpgmailcom port 587 domain gmailcom authentication plain enable starttls auto true user name myusername password mypassword configaction mailerdefault url options host mydomaincom and here a typical sidekiq queue homejohnrvmgemsruby200p247clueybundlergemssidekiq4ed6eba8aff1libsidekiqrailsrb14 warning toplevel constant queue referenced by sidekiqclientqueue 20130719t094756z 20112 tid1a5mkc info booting sidekiq 252 with rethis at rethislocalhost63790 20130719t094756z 20112 tid1a5mkc info running in ruby 200p247 20130627 revision 41674 i686linux 20130719t094756z 20112 tid1a5mkc info see license and the lgpl30 for licensing details 20130719t094756z 20112 tid1a5mkc info starting processing hit ctrlc to stop 20130719t094811z 20112 tid1u2z02 deviseasyncbackendsidekiq jid4a7e66a14deab112191e4b49 info start 20130719t094812z 20112 tid1u2z02 deviseasyncbackendsidekiq jid4a7e66a14deab112191e4b49 info done 1214 sec 20130719t094850z 20112 tid1u2z02 deviseasyncbackendsidekiq jid32191822b789f5b6896a5353 info start20130719t094851z 20112 tid1u2z02 deviseasyncbackendsidekiq jid32191822b789f5b6896a5353 info done 0143 sec20130719t094929z 20112 tid1u2z02 sidekiqextensionsdelayedmailer jidc1911e0c4b72295dc067d57f info start20130719t094929z 20112 tid1u2z02 sidekiqextensionsdelayedmailer jidc1911e0c4b72295dc067d57f info done 0152 seci think it has to do with actionmailer and sidekiq but i do not know how to debug everything seems to work but the emails never delivered,"['ruby-on-rails', 'ruby']" +510048,iterating a resultset using the jdbc for oracle takes a lot of time about 16s while result setnext i have use systemnanotime and calculated the time for each iteration the time taken is in milliseconds but the overall loop takes about 16s i am considering a possible reason that the condition test is taking a lot of time the next function fyi i am connecting to a remote database server and the select query that i make is completed in milliseconds again calculated using the above mentioned method any reasons about why it is happening and how i can bring the time to iterate the resultset down to at max a secondediti am dealing with about 40 records and each record contians about 10 columns each having a size of about 10 charsedit2thanks setfetchsize did the magic awesome awesome,['java'] +510083,how to enable mod rewrite in lamp on ubuntu i am using ubuntu 1204 lts linux on my machine i have already installed lamp on it now i want to enable the mod rewrite module i did google a lot and tried lots of tricks but could not be able to enable mod rewrite can anyone help me to enable the mod rewrite thanks in advance,['php'] +510138,equivalent of css class selectors for android views is in android something similar to css class something like rid but usable for multiple views i would like to hide some group of views independently on which position in layout tree they are,['android'] +510156,correct way to check for empty or missing file in python i want to check both whether a file exists and if it does if it is emptyif the file does not exist i want to exit the program with an error messageif the file is empty i want to exit with a different error messageotherwise i want to continuei have been reading about using try except but i am not sure how to structure the code pythonically to achieve what i am afterthank you for all your responses i went with the following codetry if osstaturlfilepath urlfilest size 0 print processing else print empty url file exiting sysexitexcept oserror print url file missing exiting sysexit,['python'] +510236,using an html data attribute consider a line such as this div idabc onclickdosomethingthisiddivnow suppose it is expanded to be something more like thisdiv idabc datasomethingwhatever onclickdosomethingthisiddivthere is no functional difference here yet but this is my question i am looking for a way to pass the value of datasomething to the dosomething function instead of the id i cannot seem to find a method of doing this is it possiblesomething like the following would be nice but of course it is not how it works i am only including it to help illustrate the intended goaldiv idabc datasomethingwhatever onclickdosomethingthisdatasomethingdiv,"['javascript', 'html']" +510298,app not updating for alpha testers on google play my app is being tested using google play i am one of my alpha testers naturally i released a new alpha version of the app i was expecting it to update automatically on my device but it is not updating am i missing a step according to googleonce they install the app and opt in they will automatically be updated to the new test version,['android'] +510301,run process in current console i am writing a basic shell for windows and i was wondering if there is any way to run a subprocess process process so that it uses the current console window by this i mean that i do not want to redirect inputoutput i want the process to take input from the current console and print output directly to the same console windowthe reason is that i want to allow this subprocess to set console colors for output which cannot happen if i redirect the process standard output also i currently use the codewhile processhasexited procestandardinputwritelineconsolereadlineto redirect standard input to the process however if the process exits immediately after an input for example i type exit enter and the process exits this loop will run once more so the console is waiting for input from the user that will never be used by the process it is about to exitso long question short how do i run a process in the current console so that it can set console colors and directly take input from the consoleedit below are the methods that are relevant to this question from my codestatic int runexestring exepath params string args procestartinfo startinfo new procestartinfoexepath args errordialog false useshellexecute false createnowindow true redirectstandardinput true redirectstandardoutput true redirectstandarderror true redirectstandardinput true process process new process startinfo startinfo procestart readthreadstate stdout readthreadprocestandardoutput false readthreadstate stderr readthreadprocestandarderror true while processhasexited procestandardinputwritelineconsolereadline stdoutstop stderrstop true return processexitcodeclass readthreadstate public bool stopprivate static readthreadstate readthreadstreamreader reader bool iserror readthreadstate state new readthreadstate new thread while statestop int current while current readerread 0 if iserror writeerrorcharcurrenttostring consolecolorred else consolewritecharcurrent start return state,['c#'] +510302,why does entity framework create a subquery when selecting from a view i have a table called persontable with the columns personid restarauntid agei have a view called personview that doesselect personid restarauntid restarauntnamerestarauntid as restarauntname age from persontablewhen i do something as simple asvar persons contextpersonviewwherexxpersonid 1 selectx new xpersonid xrestarauntid xrestarauntname xage the above returns 1 record and i would expect the mysql query to beselect personid restarauntid restarauntname age from personviewwhere personid 1but instead it generates the followingselect 1 as c1 tpersonid trestarauntid trestarauntname tagefromselect personid restarauntid restarauntname age from personview as twhere tpersonid 1so it does not matter what i pass to the where clause it always will get all the records first in a subselect this only happens when i query against the view which i need to but i was curious as to why it creates the above query instead of the one i expect it to make is this an entity framework issue or a mysql issue,"['c#', 'mysql']" +510306,does type erasure of java generics cause full type casting i know that when a java compiler compiles a generic type it performs type erasure and removed all references to the generic from the code and my arraylistcheesecake becomes just an arraylistthe question that i have not need a clear answer for is whether this lack of a type and therefore mandatory typecasting causes slow down in order words if i am using the standard java compiler and the standard jvm 17 from oracledoes the bytecode include a type castif yes does it include a runtime check to check if its the correct typedoes the conversion itself take a nontrivial amount of timewould making my own cheesecakelist class that looks identical to arraylist just with all of the objects turned to cheesecakes would i gain anything again just a hypothetical and i am not interested in any side effects of having a larger binary because of more classes nor the duplication in my codei am not interested in any other problems that type erasure causes just a simple answer from someone who understand the jvm better than i doi am most interested in the cost in this examplelistcheesecake list new arraylistcheesecakefor int i 0 i listsize i i know this gets converted to cheesecakelistgetiatme listgetieatme is that cast inside the loop expensive andor significant as compared tocheesecakelist list new cheesecakelistfor int i 0 i listsize i where the return of listget is a cheesecake therefore there is no casting listgetieatme thisclaimer this is mostly a question of academic curiosity i really doubt that there is any significant performance issues with the type cast and removing the need for them wouldnt be even one of the top 5 things i would do if i found a performance bug in my code if you are reading this because you do have a performance issue do yourself a favor and start up a profiler and find out where the bottle neck is if you really believe its in the typecasting only then should you try and optimize it somehow,['java'] +510336,ios calendar monitoring in the background how is it done i am researching how to add notifications to our app when an event is about to start other justcalendar apps provide this functionality but my research has me baffled about how they accomplish thisaccording to the apple docsfor tasks that require more execution time to implement you must request specific permissions to run them in the background without their being suspended in ios only specific app types are allowed to run in the backgroundapps that play audible content to the user while in the backgroundsuch as a music player appapps that keep users informed of their location at all times such asa navigation appapps that support voice over internet protocol voipnewsstand apps that need to download and process new contentapps that receive regular updates from external accessoriesok well a calendar app is none of these if i schedule local notifications for my app to periodically wake up and check the calendar that will not suffice afaict from the reading i have done using the location monitoring option will not suffice what if my user sits in hisher office all day long calendar events can be addeddeleted from other sources beside the phone obviously so setting up a bunch of notifications when my app starts is not a solution how do the calendar apps accomplish preevent notifications i have several calendar apps from the app store and they do this so i know it can be done my app will need to be acceptable by the app store as well so i cannot fake voip as a solution additional info after more research the apps i see doing this do not update when they have been shut down duh but they do some background updates i am still unclear as to how to keep my background process going for a long time eg overnight,['ios'] +510351,how to programmatically scroll a panel i have a systemwindowsformspanel with some contenti am trying to programmatically scroll the panel vertically either up or downi have tried setting the autoscrollposition property to a new point on the panel but that does not seem to do iti have the autoscroll property set to truei even tried to set the verticalscrollvalue twice as suggested here but that does not seem to work eitherthis is what i am currently doingi have tried passing both positive and negative valuespanelautoscrollposition new point5 10the x and y values on autoscrollposition remain 0 and 0any help or direction on this would be greatly appreciated itthanks in advancemarwan,['c#'] +510366,jquery print function to print div content with css i have this function for my wordpress plugin uses jquery that prints the content from the div with class table thisp how can i print the css style along with it function pop print wwindowopennull print page scrollbarsyes wdocumentwritejquerytable thisphtml wdocumentclose wprintany idea,"['jquery', 'css', 'html']" +510372,create new array using content of other arrays in c i would like to know the most efficient way of creating new arrays from the content of other arraysi have several arrays of strings of the typepublic readonly string taiwan tw two public readonly string vietnam hm hn hno public readonly string korea kq ks public readonly string china ss sz public readonly string japan t os ng fu sp q oj jnx ixj kab ja jpx it would be possible to create now a new array of string in a similar way to thispublic readonly string asia taiwan vietnam korea china japanthat would contain all the strings included in the other arrays,['c#'] +510373,backbone example app and javascript apply hi can someone explain why in backbone example app in remaining function is called using apply thiswithoutapplythis thisdone and not thiswithoutthisdone filter down the list of all todo items that are finisheddone function return thiswheredone true filter down the list to only todo items that are still not finishedremaining function return thiswithoutapplythis thisdonethank you updatedebugger outputthiswithoutthisdonechild child child childthiswithoutapplythis thisdonechild child child,['javascript'] +510387,returning first occurrence index of a number in a list i have a bunch of csv files containing time data and numbers i wrote a function to return the first occurrence of a number below a threshold x this way def bounceticklistx and 0 for i in ticklist if floati1 x return n break and 1except that when i loop the execution of the bounce function this way for i in oslistdirresultdir if csv in i csvfile resultdiri print csvfile with opencsvfile rb as f reader csvreaderf ticklist for line in reader ticklistappendline print bounceticklist5it keeps on returning zero even though the first value is above the threshold where am i going wrong here is a sample of one of the csv files 1373289767454535991373289769728528991373289771817576991373289773813036117137328977581098511713732897696417137328977978313412213732897817742551181373289783799892120137328978581296711413732897878169914137328978979083511313732897918112451091373289793880356108137328979584686610713732897978475521061373289799858929106thanks in advance edit after commentshere is the new functiondef bounceticklistx and 0 for i in ticklist if floati1 x return and and 1if i print floati1 it returns the right numbers so it is calling the right files second editfound the problem the level i was feeding it was in fact a str and not an int thanks for everybody who had a look and helped,['python'] +510405,factorygirl build stubbed strategy with a has many association given a standard has many relationship between two objects for a simple example let us go withclass order activerecordbase has many line itemsendclass lineitem activerecordbase belongs to orderendwhat i would like to do is generate a stubbed order with a list of stubbed line itemsfactorygirldefine do factory line item do name an item quantity 1 endendfactorygirldefine do factory order do ignore do line items count 1 end afterstub do order evaluator orderline items build stubbed listline item evaluatorline items count order order end endendthe above code does not work because rails wants to call save on the order when line items is assigned and factorygirl raises an exceptionruntimeerror stubbed models are not allowed to access the databaseso how do you or is it possible to generate an stubbed object where it is has may collection is also stubbed,['ruby-on-rails'] +510446,angularjs cors issues i have searched over 200 sitesmaybe exaggerating but not by much on how to be able to handle cors with angularjs we have a local machine running a web api server we are developing a client that calls on the api for data when running the client from the server we receive data no problem when we run it from a different domain we get a red 200 response when trying to fetch data and a blank response here is some codevar myapp angularmoduleproject ngresourcemyappconfigfunctionrouteprovider routeprovider whennew templateurltemplatesnewhtml controllereditprojectcontroller whenmobile templateurltemplatesmobilehtml controllerprojectcontroller whenit templateurltemplatesithtml controllerprojectcontroller whenwriting templateurltemplateswritinghtml controllerprojectcontroller whenall templateurl templatesallhtml whenlogin templateurl partials loginhtml otherwise redirectto all myappconfighttpprovider function httpprovider httpproviderdefaultsusexdomain truedelete httpproviderdefaultsheaderscommonxrequestedwithmyappcontrollerprojectcontroller function myappscope http projectdataservice userloginservice httpdefaultsusexdomain true scopeloadproject function projectdataservicegetprojectfunctionproject scopeproject project scopeloadprojectmyappfactoryprojectdataservice function resource q var resource resourcehttpwebapiserverapiid id id return getproject function var deferred qdefer resourcequery id project function project deferredresolveproject function response deferredrejectresponse return deferredpromise save function project var deferred qdefer projectid project9 resourcesaveproject function response deferredresolveresponse function response deferredrejectresponse return deferredpromise i have also tried this using http but i get the same response or lack thereofmyappfactoryprojectdataservice function http return getproject function successcb httpgethttpwebapiserverapiproject successfunction data status headers config successcbdata errorfunction data status headers config when i just browse to the url that is serving up the json in the browser it spits out the data on the server we are allowing cross domain origins which is apparent by my previous statement as you can see i am implementing the headers overrides in myappconfig i have even tried putting it directly in my controller no difference3 days now on this taskhelp with this is more than appreciated thanks in advance,['javascript'] +510468,how to print a list with integers without the brackets commas and no quotes this is a list of integers and this is how they are printing7 7 7 7i want them to simply print like this7i do not want brackets commas or quotes what to do,['python'] +510501,making a button persistent across all view controllers i want to have a persistent button in the bottom right corner of my app during all view transitions the button should remain static i am having trouble deciding what view to add the button to i know the button ought to be stored in the appdelegate but i do not know what other view it would be sense to add it to except the window one downside of adding it to the window is that when there is an app running in the background ie phone the added status bar padding will push down the window in general adding it to the window seems to be a hacky solution any thoughts,['ios'] +510539,python under mac os x framework i like to use python with numpy scipy and some other packages i am an absolute python beginner and have some issues with the installation under mac os xi am following these two tutorials to install python 1 and 2 here homebrew is used to install python with pip and virtualenv i do not have an opinion about what is better macports homebrew fink i just found this tutorial inspiring confidence if i understand things correctly os x system python which i should never touch is under systemlibraryframeworkspythonframework and i cannot use this one in xcode because it does not have my wanted packages the homebrew python will be installed somewhere in usrlocal i found a framework there but as the system framework it does not have the additional packages the tutorial explains that it might be better to install additional packages in virtual environments only which is done via pip but i cannot find a framework there so my question is how can i get a python installation in a virtual environment that includes a framework that i can include into xcode,['python'] +510541,javascript symbol type nonstring object keys what is the symbol javascript type as mentioned in this ecmascript 6 draft specificationto quote the specthe symbol type is the set of all nonstring values that may be used as the key of an object propertyeach possible symbol values is unique and immutablesymbol values have a single observable attribute called private whose immutable value is either true or false a private symbol is a symbol value whose private attribute has the value truei thought object keys were strings only and i am not alone to quote this accepted so answeraobject keys are always stringsacould you explain what the symbol type is and demonstrate its usage i am trying to make sense of the specthanks,['javascript'] +510585,check if cross domain url gives 404 with javascript i am trying this code but it gives me a dom exception what i want it to get a truefalse answer from the function using plain javascriptvar url function urlexistsurl var http new xmlhttprequest httpopenhead url false httpsend return httpstatus404urlexistsurlfiddlei got this code from this so answer but as said i cannot get it working,['javascript'] +510695,check if a character is a vowel or consonant is there a code to check if a character is a vowel or consonant some thing like char isvowel or need to hard codecase acase aeacase aiacase aoacase auacase acase aeacase aiacase aoacase aua,['c#'] +510715,avoid using global without confusing new programming students in python i have been teaching 8th9th graders basic computer programming for two weeks and yesterday i tried to show them how they could make real simple textadventure games in pythonscenes are functions eg dragons cave which consist of some print statements and then a call to input asking the player where they want to go next which then gets passed to globals to find the appropriate function and then called i know it is not ideal at what point would the huge chain of functions start becoming a problem but of what crossed my mind it seems to be the simplest for them while involving only a little handwavingmy problem is with global state a ex the player gets a key in one scene and only then can they unlock the gate in another scene when i have global immutables like strings or booleans python wants me to use the global keyword at the beginning of the functionglobal haskeyhaskey truei am pretty okay with that but i have a vague sense picked up from stackoverflow among other places on the internet that global is frowned upon and always has a superior counterpart i could have a global dictionary or wrap everything in a class but i am not sure if i could defend those options clearly to my kids who are still thinking through the implications of variableswhatever i use i want to be able to explain straightforwardly to my kids why we do it this way and why doing it this way is necessary global seems to have both these properties but is it bad,['python'] +510736,how can i set default project location for all projects in intellij idea i am wondering if there is a way to set the default location for all intellij projects something similar to the workspace concept in eclipsebecause i always need to change the idea project location when i create a new project,['java'] +510743,ctrl c interrupt event handling in linux i am developing an application that uses c and compiles using linux gnu c compiler however i want to invoke a function as the user interrupts the script using ctrlc keys what should i do any answers would be much appreciated,"['c++', 'c']" +510775,put item on dynamodb table using aws sdk for nodejs i am new to javascript and nodejs and was wondering if someone can help me figure out the syntax of putting a new item onto an existing table on aws dynamodb through their nodejs sdk heres what i have so far is there an example for what i am trying to do if anyone could point me in the right direction it would be much appreciated var aws requireawssdkawsconfigloadfrompathconfigjsonawsconfigupdateregion useast1var dynamodb new awsdynamodbvar item i need to put the an item with a the primary key of id and an attribute called item i am new to js and nodejs so if somebody could help me understand the documentation http3adocsawsamazoncomawsjavascriptsdklatestawsdynamodb 20120810htmldynamodbputitemtablename log dev item item functionerr data if err consolelogerr an error occurred else consolelogdata successful response,['javascript'] +510812,target database is not up to date i would like to make a migration for a flask app i am using alembichowever i receive the following errortarget database is not up to dateonline i read that it has something to do with this unfortunately i do not quite understand how to get the database up to date and wherehow i should write the code given in the link if you have experience with migrations can you please explain this for methanks,['python'] +510884,img has 5px extra padding at bottom of div i have a div that has a mystery 5px bottom padding added to an image contained within it i have tried resetting css padding and margin for all elements but to no avail what am i missingjsfiddle html div idlist div idboxscroll div classlistresult img srcimagespsresultpng div div classlistresult img srcimagespsresultpng div div classlistresult img srcimagespsresultpng div divdivcsslistresult padding0 margin0 width100 borderbottom 1px 0 solid backgroundf9f9f9listresulthover backgrounde9e9e9list top 100px bottom40px right 20px position absolute width 20 maxwidth300pxboxscroll fontfamilyopen sans backgroundf9f9f9 overflow auto maxheight100 border 8px solid f,['css'] +510885,why do we have to specify the datatype of each formal argument separately if we can declare more than one variable like thisint i j kthen why do i get an error when i write in formal argumentsvoid funint i j kinstead ofvoid funint i int j int k,['c'] +510907,abnormal behaviour of javautillist based on number of elements in it i know that if the collection will be changed while some thread is traversing over it using iterator the iteratornext will throw a concurrentmodificationexceptionbut it shows different behavior depending on the number of elements in the listi tried a code snippet in which i traversed a list in foreach loop and in between it is traversal removed an element from the list using remove method of the listideally it should throw a concurrentmodificationexception in this condition without depending on number of elements in the list but it is not true when number of elements in list are twocase 1 number of elements in list 1 public static void mainstring args liststring listnew arrayliststring listaddone for string string list systemoutprintlnstring listremovestring output oneexception in thread main javautilconcurrentmodificationexceptionthat is was as expectedcase 2 number of elements in list 2 public static void mainstring args liststring listnew arrayliststring listaddone listaddtwo for string string list systemoutprintlnstring listremovestring output oneno exception is throwncase 3 number of elements in list 3 public static void mainstring args liststring listnew arrayliststring listaddone listaddtwo listaddthree for string string list systemoutprintlnstring listremovestring output oneexception in thread main javautilconcurrentmodificationexceptionagain an exception is thrown which is ideal behaviorbut why it runs properly in case2 without throwing any concurrentmodificationexception,['java'] +510908,textarea auto height i want to make height of textarea equal to height of the text within it and remove the scroll barhtmltextarea idnotesome texttextareacsstextareanote width100 directionrtl thisplayblock maxwidth100 lineheight15 padding15px 15px 30px borderradius3px border1px solid f7e98d font13px tahoma cursive transitionboxshadow 05s ease boxshadow0 4px 6px rgba01 fontsmoothingsubpixelantialiased backgroundlineargradientf9efaf f7e98d backgroundolineargradientf9efaf f7e98d backgroundmslineargradientf9efaf f7e98d backgroundmozlineargradientf9efaf f7e98d backgroundwebkitlineargradientf9efaf f7e98djsfiddle,"['javascript', 'html', 'css']" +510978,is there a way to add a device to a provisioning profile without using apple developer portal apple developer portal is down since more than a day is there a way to add a device to a provisioning profile without using i am wondering if xcode 45 has some functionality that allows this however from apples guide it does not seem possibleedit i tried using xcode 45 to add the device to the profile by clicking use this device for development which should i believe add the device to the wildcard provisioning profile however it does not seem to work and i get the followingi believe that the error might be caused from the server being down because i do not get any list of xcode supported ios versions there are other questions tackling this but i believe this is a different use case because we are dealing with a situation where apple developer server is down and hence it might be that my xcode works fine i tried to check for updates in the preferencesdownloadscomponents section but no update seem to be available is this normal here is what i can see from my tab but i find it strange that there is no ios 60 simulator available,['ios'] +510998,firstordefault behavior with int and int i just read a so post that explained that firstordefaults return type will vary based on the value of the element being selectedexampleicollectionstring list new liststringlistaddbyeint a from x in list where x hi select xlengthfirstordefault in this example a will be equal to 0 since the int default value is 0however i can append castint as per the already linked post in order to get null when the query returns 0 resultsint a from x in list where xlengthcastintfirstordefaultwhy do not i get a compiletime error or at least a warning when for my first example i use a nullable int int rather than a regular int if i understand correctly using a int when performing my first query will never result in a value of null,['c#'] +511007,clang 33 in c1y mode cannot parse header i have a project that correctly compiles and runs under g 481 and clang 33 in c11 mode however when i switch to the experimental stdc1y mode clang 33 but not g chokes on the cstdio header that is indirectly included by way of boosttest so i cannot easily change it myself usrincludec48cstdioinclude stdioh get rid of those macros defined in stdioh in lieu of real functions undef gets namespace std using gets error with clang stdc1y with the following error messageusrlibgccx86 64linuxgnu48includec48cstdio11911 error no member named gets in the global namespaceon this tutorial on how to set up a modern c environment a similar lookup problem with max align t is encountered the recommendation there is to use a sed script to surround the unknown symbols with ifdef clang macros but that seems a fragile approachsetup plain 64bit linux mint 15 with g ubuntu 4812ubuntu11304 481 ubuntu clang version 3raring1 branchesrelease 33 based on llvm 33questions what is causing this erorr there is no clang macro anywhere near the code in question and clang in c11 mode has no trouble at all is it a language problem does c14 say something else than c11 about importing c compatible symbols from the global into the std namespace do i need to change something with my include paths i use cmake to automatically select the header paths and switch modes inside cmakeliststxt does clang have a switch to resolve this,['c++'] +511026,newtonsoftjson assembly conflict i use netonsoftjson in my project it works fine until i start integrating paypal sdk in my project my code is as below string accesstoken new paypaloauthtokencredential getaccesstoken this line throwing an error paypalapipaymentsaddress add new paypalapipaymentsaddress addcity textboxcitytext addline1 textboxaddresstext addphone textboxphonenumbertext addpostal code textboxzipcodetext addstate textboxstatetext paypalapipaymentscreditcard cc new paypalapipaymentscreditcard ccnumber textboxcreditcardnumbertext ccfirst name textboxfirstnametext cclast name textboxlastnametext ccexpire month converttoint16textboxexpirymonthtext ccexpire year converttoint16textboxexpiryyeartext cvv2 textboxcvvnumbertext ccbilling address add createaccesstokenand i get error as below systemiofileloadexception could not load file or assembly newtonsoftjson version4500 cultureneutral publickeytoken30ad4fe6b2a6aeed or one of its dependencies the located assemblys manifest definition does not match the assembly reference exception from hresult 0x80131040i search on internet and found some solution to change config file so i change my config file as below assemblybinding xmlnsurnschemasmicrosoftcomasmv1 dependentassembly assemblyidentity namenewtonsoftjson publickeytoken30ad4fe6b2a6aeed cultureneutral bindingredirect oldversion03500 newversion4500 dependentassemblyassemblybindingi also play arroung with assembly properties like copy local specific version but nothing helps me to solve this how can i solve assembly conflict,['c#'] +511034,how to use indexof in jquery ifthisvalindexof4289 do somethingelse do something this works only with that 4289when i try to add other numbers to be indexed next to it using or it does not work how should i put other number eg indexof428978843 i want this to check this numbers and if the number in the input field is not one of this to echo error heres more which happens to die when one revisits the field zipblurfunction if thisvalindexof0860 1thisvalindexof0850 1 status ziphtmlno way thisalterclass success return false elsestatus codehide thisalterclass error thiscssbordercolor f00cssbackgroundcolor ffceffectpulsatetimes42 return true,"['javascript', 'jquery', 'html']" +511052,pythons re module not working i am using pythons re module as followsrequest getprint refindallhgrouphgroup requestall i am doing is getting the html of this site and looking for this particular snippet of codehgroup h3 classalbumartist a hrefgreen daya h3 h2 classalbumtitle warning h2hgrouphowever it continues to print an empty array why is this why cannot refindall find this snippet,['python'] +511059,error on dbmigrate uninitialized constant devisecreateusers i am trying to run the rake dbmigrate command on heroku and i am running into this problem uninitialized constant devisecreateusersappvendorbundleruby200gemsactivesupport3211libactive supportinflectormethodsrb230in block in constantizeappvendorbundleruby200gemsactivesupport3211libactive supportinflectormethodsrb229in eachappvendorbundleruby200gemsactivesupport3211libactive supportinflectormethodsrb229in constantizeappvendorbundleruby200gemsactivesupport3211libactive supportcore extstringinflectionsrb54in constantizeappvendorbundleruby200gemsactiverecord3211libactive recordmigrationrb538in load migrationappvendorbundleruby200gemsactiverecord3211libactive recordmigrationrb533in migrationappvendorbundleruby200gemsactiverecord3211libactive recordmigrationrb528in migrateappvendorbundleruby200gemsactiverecord3211libactive recordmigrationrb720in block 2 levels in migrateappvendorbundleruby200gemsactiverecord3211libactive recordmigrationrb775in callappvendorbundleruby200gemsactiverecord3211libactive recordmigrationrb775in block in ddl transactionappvendorbundleruby200gemsactiverecord3211libactive recordconnection adaptersabstractdatabase statementsrb192in transactionappvendorbundleruby200gemsactiverecord3211libactive recordtransactionsrb208in transactionappvendorbundleruby200gemsactiverecord3211libactive recordmigrationrb775in ddl transactionappvendorbundleruby200gemsactiverecord3211libactive recordmigrationrb719in block in migrateappvendorbundleruby200gemsactiverecord3211libactive recordmigrationrb700in eachappvendorbundleruby200gemsactiverecord3211libactive recordmigrationrb700in migrateappvendorbundleruby200gemsactiverecord3211libactive recordmigrationrb570in upappvendorbundleruby200gemsactiverecord3211libactive recordmigrationrb551in migrateappvendorbundleruby200gemsactiverecord3211libactive recordrailtiesdatabasesrake179in block 2 levels in top requiredhere is the fulltext of my devise create users method that appears to be causing this problem class adevisetocustomers activerecordmigrationdef selfupchange tablecustomers do t database authenticatable tstring email null false default tstring encrypted password null false default recoverable tstring reset password token tdatetime reset password sent at rememberable tdatetime remember created at trackable tinteger sign in count default 0 tdatetime current sign in at tdatetime last sign in at tstring current sign in ip tstring last sign in ip tstring confirmation token tdatetime confirmed at tdatetime confirmation sent at confirmable tstring unconfirmed email only if using reconfirmable lockable tinteger failed attempts default 0 only if lock strategy is failed attempts tstring unlock token only if unlock strategy is email or both tdatetime locked at token authenticatable tstring authentication token uncomment below if timestamps were not included in your original model ttimestamps add index users email unique true add index users reset password token unique true add index users confirmation token unique true add index users unlock token unique true add index users authentication token unique true endendendthis all on a pgsql server on herokuthanks in advance,"['ruby-on-rails', 'ruby']" +511060,javascript module pattern with example i cannot find any accessible examples showing how two or more different modules are connected to work togetherso i would like to ask whether anyone has time to write an example explaining how modules work together,['javascript'] +511095,how to send parallel get requests and wait for result responses i am using apache http client within spring mvc 322 to send 5 get requests synchronously as illustrated how can i send all of these asynchronously in parallel and wait for the requests to return in order to return a parsed payload string from all get requestspublic string mymvccontrollergetdatamethod send 1st request httpclient httpclient new defaulthttpclient httpget httpget new httpgethttpapidatatype1 responsehandlerstring responsehandler new basicresponsehandler string responsebody httpclientexecutehttpget responsehandler send 2st request httpclient httpclient2 new defaulthttpclient httpget httpget2 new httpgethttpapidatatype2 responsehandler2string responsehandler2 new basicresponsehandler string responsebody2 httpclientexecutehttpget responsehandler2 o o o more gets here perform some work hereand wait for all requests to return parse info out of multiple requests and return string results doworkwithmultipledatareturned modeladdattributeresults results return index,['java'] +511137,running in superdevmode i tried superdevmode however when the url httplocalhost9876 is accessedand dev mode on is clicked i am getting thiscannot find any gwt modules on this pagewhat could i be missing i already did mvn gwtcompilemvn gwtruncodeserveri have these versions in the pom gwtversion250gwtversion gwtmavenversion250gwtmavenversiondo i need to update the gwt version or the gwt maven version or what i missing,['java'] +511152,printing long int value in c i have two variables of long int type as shown belowlong int a2147483648 b2147483648aabprintfdai am getting zero i tried changing the type to long long int but i am still not getting the correct answer,['c'] +511155,who is responsible for deleting the facet i have a function that uses the boostdatetime library for generating the current gmtutc date and time string live examplestdstring get curr date auto date boostdate timesecond clockboostposix timeptimeuniversal time boostposix timetime facet facet new boostposix timetime faceta d b y hms gmt stdostringstream os osimbuestdlocaleosgetloc facet os date return osstrthis is mostly based on boostdatetimes exampleexample to customize output to be longweekday longmonthname day year a b d ydate d2005jun25date facet facetnew date faceta b d ystdcoutimbuestdlocalestdcoutgetloc facetstdcout d stdendl saturday june 25 2005my code worked nicely but now i am feeling uneasy because of these particular lines containing newboostposix timetime facet facet new boostposix timetime faceta d b y hms gmtdate facet facetnew date faceta b d yas you can see there is no delete in boostdatetimes so i somehow presumed that it is imperative for me to delete the date facet i used stdunique ptr to wrap the newed time facet objectstdunique ptrboostposix timetime facet facetnew boostposix timetime faceta d b y hms gmthowever i am getting segfault errors as you can see in here i have also tried manually deleteing the newed pointer and am still getting the same errors sorry cannot reproduce error in coliruthe time facet pointer is passed as an argument when constructing an stdlocale object so i am confused whos the one responsible for deleteing the facetso here is the core of my questionam i required to delete the time facet or is the stdlocale object responsible for deleteing itplease note that boostposix timetime facet is derived from boostdate timedate facet which is in turn derived from stdlocalefacet this question might generalized to stdlocalefacet though my problem is specific to time facethere are some docs on stdlocales constructorsmsdncppreferencecom,['c++'] +511200,value of i for i i i 0 to return true in java i have the following if conditionif i i i 0what value of i will return true for this condition in javai am unable to think of any such value of i considering twos complement notation in javai would also love to have algebraic proof of whatever answer this condition has in context with java,['java'] +511252,xamarin ios navigate to next text field with return key i could not find anything in the xamarin documentation about navigating to the next text field in a series of text fields on a form only a small tutorial on removing the keyboardto keep things simple i am using a txtusernametag 1 text field and a txtpasswordtag 2 text field when i implement the following code it is not transferring to xamarin studio does anyone know the way this can be done code in xamarin studio or alternatively if i can transfer the code from xcode to xamarin studioi am using the following code booltextfieldshouldreturnuitextfield txtusername nslogtextfieldshouldreturn if txtusernametag 1 uitextfield txtpassword uitextfield selfview viewwithtag2 txtpassword becomefirstresponder else txtusername resignfirstresponder return yesthanks in advance,['ios'] +511267,when are static and global variables initialized in c i know static and global objects are constructed before the main function but as you know in c there is no such kind initialization procedure before mainfor example in my codeint global int1 5int global int2static int static int1 4static int static int2when are these four variables initializedwhere values for initialization like 5 and 4 are stored during compilation how to manage them when initializationeditclarification of 2nd question in my code i use 5 to initialize global int1 so how can the compiler assign 5 to global int for example maybe the compiler first store the 5 value at somewhere ie a table and get this value when initialization beginsas to how to manage them when initialization it is realy vague and i myself does not how to interpret yet sometimes it is not easy to explain a question overlook it since i have not mastered the question fully yet,['c++'] +511299,mysql how to insert null dates i am having trouble inserting null values into date fields into a mysql table here is the insert queryquery insert into table column s1 column s2 column d1 column d2values string1 string2 date1 date2columns s1 and s2 take string values and d1 and d2 take dates when i run this query with only the string fields there is no problemthe date values can be either set or null so i have not included the quotation marks in the query but have instead added them to the variable earlier on this is the php code i am using to set the date valuesif emptydate1 date1 nullelse date1part explodedate1 date1 date1part2date1part1date1part0when the date values are all set the record is inserted correctly however when either of the dates is null nothing is insertedwhy cannot i just insert null values into mysql like this,"['php', 'mysql']" +511318,jquery uncheck other checkbox on one checked i am having total 6 checkbox may be add more in future and i want to allow only select one so when user checked any of them other should uncheckedi tried with this code and works fine if i defined id but now just wonder how to make it vice versa in efficient way so in future if i add more than it wont be a problemtype1clickfunction type2nottype1removeattrchecked fyi checkboxs are not sibling and are in different td,['jquery'] +511385,refresh table view i think i have a pretty easy task but somehow it does not want to work i am a total beginner in objectivec so i guess it is just a small mistake i still do not really know what i do currently it is more like copypaste programming like i do not really know if i need the iboutlet in the interface or as a property or as both what i havea viewcontroller with a button a label and a table view the button connects to a sharepoints server and reads a list and adds the value to an array this part worksdelegate and datasource outlet is connected to the view controllerwhat i wantthe array should be the datasource of the table view so i just want it to refresh after i have read the new data in the array the test data i add in the viewdidload function to the array shows up so i guess i somehow connected the array to the table view i will give you the full codeviewcontrollerhimport uikituikithinterface viewcontroller uiviewcontroller uitableviewdelegate uitableviewdatasource iboutlet uilabel output iboutlet uitableview tableview nsmutabledata webdata nsstring finaldata nsstring converttostringdata nsmutablestring nodecontentproperty nonatomic retain uilabel outputproperty nonatomic weak iboutlet uitableview tableviewibactioninvokeserviceuibutton senderendviewcontrollermimport viewcontrollerhinterface viewcontroller nsmutablearray foundurlaubendimplementation viewcontrollersynthesize output voidviewdidload super viewdidload some test data this shows up in my table view foundurlaub nsmutablearray allocinit foundurlaub addobjectfirst cell foundurlaub addobjectsecond cell foundurlaub addobjectthird cellibactioninvokeserviceuibutton sender connection to sharepointvoidconnectionnsurlconnection connection didreceiveresponsensurlresponse response nslogdidreceiveresponse webdata setlength0voidconnectionnsurlconnection connection didreceivedatansdata data nslogdidreceivedata webdata appenddatadatavoidconnectionnsurlconnection connection didfailwitherrornserror error nslogerror with the connection nslogerrordescriptionboolconnectionnsurlconnection connection canauthenticateagainstprotectionspacensurlprotectionspace protectionspace nslogcanauthenticateagainstprotectionspace return yesvoidconnectionnsurlconnection connection didreceiveauthenticationchallengensurlauthenticationchallenge challenge nslogdidreceiveauthenticationchallenge nsurlcredential credential nsurlcredential credentialwithuserx passwordx persistencensurlcredentialpersistenceforsession challenge sender usecredentialcredential forauthenticationchallengechallengevoidconnectiondidfinishloadingnsurlconnection connection nslogdone received bytes d webdata length converttostringdata nsstring alloc initwithdatawebdata encodingnsutf8stringencoding nsregularexpression regex nsregularexpression regularexpressionwithpatternows title ows metainfo options0 errornull nsarray matches regex matchesinstringconverttostringdata options0 rangensmakerange0 converttostringdata length here i load some data in the array foundurlaub removeallobjects for nstextcheckingresult match in matches nsrange matchrange match rangeatindex1 nsstring matchstring converttostringdata substringwithrangematchrange nslogmatch matchstring foundurlaub addobjectmatchstring adds 3 strings to array this does not work tableview reloaddata voiddidreceivememorywarning super didreceivememorywarning thispose of any resources that can be recreatednsintegertableviewuitableview tableview numberofrowsinsectionnsintegersection return foundurlaub countuitableviewcell tableviewuitableview tableview cellforrowatindexpathnsindexpath indexpath static nsstring simpletableidentifier tableitem uitableviewcell cell tableview dequeuereusablecellwithidentifiersimpletableidentifier if cell nil cell uitableviewcell alloc initwithstyleuitableviewcellstyledefault reuseidentifiersimpletableidentifier celltextlabeltext foundurlaub objectatindexindexpathrow return cellend,"['ios', 'objective-c']" +511413,how do i translate a query that uses row number into linq my table consists of three columns snonameage i am retrieving this table from the database with extra column row number and i used the following codeselect from select row number over order by sno ascas rowindexsnonameage from tblexample as example where rowindex between pageindex101 and pageindex110note pageindex is the variable that takes some integer value which is passed by the usermy database is sql server 2008 i want to write the same query using linq how do i do that,['c#'] +511437,access the css after selector with jquery i have the following csspagemenu activeafter content margintop 6px thisplay inlineblock width 0px height 0px bordertop 14px solid white borderleft 14px solid transparent borderbottom 14px solid white position absolute right 0i would like to change the borderwidth of the top left and bottom border using jquery what selector to i use to access this element i tried the following but it does not seem to be workingpagemenu activeaftercss bordertopwidth 22px borderleftwidth 22px borderrightwidth 22px,"['jquery', 'css']" +511498,audiorecord buffer overflow i am getting buffer overflow while recording with my app the recording is performed in a service i could not figure out why i am getting this message from audioflingerbelow i instantiate the audiorecord object and set it is callbacksbuffersize audiorecordgetminbuffersizesamplerate channelconfig audioformatarecorder new audiorecordaudiosource samplerate channelconfig audioformat buffersizearecordersetrecordpositionupdatelistenerupdatelistenerbytespersample bitspersample 8int bytesperframe nchannels bytespersampleframeperiod buffersize bytesperframe nr of frames that can be kept in a buffersize dimension int result arecordersetpositionnotificationperiodframeperiod buffer new bytebuffersizethe audiorecord callbackprivate audiorecordonrecordpositionupdatelistener updatelistener new audiorecordonrecordpositionupdatelistener public void onperiodicnotificationaudiorecord recorder int result arecorderreadbuffer 0 bufferlength public void onmarkerreachedaudiorecord recorder i suspect the problem is related to thearecordersetpositionnotificationperiodframeperiod maybe the period is too big for this buffersize and a fastersmaller period will solve the issuecould someone tells me how to get rid of the buffer overflow,['android'] +511530,change service reference url in code i am working in a windows phone 8 project and in order to use some webservices i added a service reference with a specific url my problem is the url because it changes fom time to time so i need to let the user insert the new url from some menu when the app is running i know how to change it in visual studio but now i need to change it in code when the app is runningso my question is how do i change the url in codei have done some search and the file appconfig seems to do the job but i do not have any appconfig in my project and from what i saw windows phone projects do not use such file,['c#'] +511538,type definition exists in two libraries i am building an aspnet web forms web site using net 45the error the type systemcomponentmodeldataannotationsschemaforeignkeyattribute exists in both fprojectsweb sitesrc1iteration05packagesentityframework500libnet40entityframeworkdll and cprogram files x86reference assembliesmicrosoftframeworknetframeworkv45systemcomponentmodeldataannotationsdlli have tried to alias the libraries using csc ref dataannotationsfprojectsweb sitesrc1iteration05packagesentityframework500libnet40entityframeworkdll rcm dataannotationscprogram files x86reference assembliesmicrosoftframeworknetframeworkv45systemcomponentmodeldataannotationsdllbut this only resulted in no source file specified which is equally confusing since the source files were specified as directed here herei did notice that the error was referencing the ef dll in the net40 folder rather than the net45 folder i figure if i used the net45 version the problem would resolve itself however i do not know how to change that reference i changed the targetframework attribute to the entityframework package in the packagesconfig file but that did not make any differencei am a bit stuck since both of the solutions did not seem to do anythingi looked around and found a number of posts here where folks have dealt with similar issues but have received no responses i am hoping that there is someone out there who can helpthanksg,"['c#', 'asp.net']" +511583,javascript full screen exits when user navigates around site i have a series of pages that have next and back buttons i would like the user to be able to go fullscreen through the whole flow fullscreen is working for individual pages but exits when the user goes back or forwards a page in my flow my fullscreen function var el documentdocumentelement rfs elrequestfullscreen elwebkitrequestfullscreen elmozrequestfullscreenrfscallelis there any way to keep the browser in full screen when the user navigates aroundthanks,['javascript'] +511585,renaming a mongo collection in php phps mongo driver lacks a renamecommand function there is reference to do this through the admin database but it seems more recent versions of the mongo driver do not let you just use the admin database if do do not have login privileges on that database so this method no longer works i have also read this does not work in sharded environments although this is not a concern for me currentlythe other suggestion people seem to have is to iterate through the from collection and insert into the to collection with the proper writeconcern fire and forget this could be fairly fast but it still means pulling down each record over the network into the php process and then uploading it back over the network back into the databasei ideally want a way to do it all serverside sort of like an insert into select in sql this way it is fast network efficient and a low load on php,['php'] +511636,symfony2 assets versioning by file questionis it possible on symfony2 use assets version by filebackgroundwe are using assets version and assets version format to manage the files version and force the cache update on cdns and browser cache this is working like charm but we found that there is only one assets version parameters for all the static resources used that is a problem since our webapp has a long amount of static resources and we are deploying changes to prod environment daily this situation kills the cache this is our current configconfigymlframework templating engines twig assets version assets version assets version format stv2s1s assetic configurationassetic debug kerneldebug use controller false java usrbinjava filters cssrewrite closure jar kernelroot dirjavacompilerjar yui css jar kernelroot dirjavayuicompressor246jarsometemplatehtmltwig stylesheets bundleswebappcssfuncommoncss bundleswebappcssfunmobilecss filteryui css link relstylesheet href asset url endstylesheets javascripts bundleswebappjsappjs bundleswebappjsutilsjs filterclosure script src asset url script endjavascripts javascripts bundleswebappjsmodulexjs bundleswebappjsutilsxjs filterclosure script src asset url script endjavascripts when i change any css file or a module js or any other file all paths are changed i would like to manage the version parameter of assets version format by parameter of javascriptstylesheet twig tagthis is what i am looking for javascripts bundleswebappjsappjs bundleswebappjsutilsjs filterclosure versionxx script src asset url script endjavascripts,['php'] +511660,what does double represent in answering a question about double i added a screenshot of linqpads output for that data structurehowever i got to wondering what a double looks like and linqpad would not visualize it for me additionally i do not understand the format of the data which goes into it int foo new int 2 3 3 4 3 4 1 5 can anyone visualize this for me,['c#'] +511670,is begin end for any empty vector i have long assumed that for any empty stdvector v vbegin vend yet i see nothing in the c specification that states this to always be true is it necessarily true or does it just happen to be true on most implementations,['c++'] +511686,cpack deb generator controlfilehasbadpermissions mdsums 0644 0644 i am developing small console application and i was trying to create ubuntu package using cpack ubuntu version is 1304 and my main cpack file is below package is created correctly but while trying to install it using graphic interface basically double click on deb file in ubuntu following warning appearspackage is of bad quality controlfilehasbadpermissions mdsums 0644 0644does anybody know what is the reason of that and more importantly how to fix it cmake version is 28101 but i have also tried to use 28112 and nothing has changedi have seen that they had similar problems here but nothing about the nature of the fixmy main cpack fileincludeinstallrequiredsystemlibraries setcpack generator debsetcpack package name colorsetcpack package version 08setcpack debian package architecture amd64setcpack debian package depends libc6 2316 libgcc1 134212setcpack debian package priority optionalsetcpack package description summary color unix console tool for log syntax coloringsetcpack package description file cmake source dirreadmetxtsetcpack resource file license cmake source dircopyrighttxtsetcpack package version major 1setcpack package version minor 0setcpack package version patch 0setcpack strip files colorsetcpack package executables colorincludecpackif somebody wants to see the package or do more research github repo deb file is in first the release,['c++'] +511717,formshowdialog does not thisplay window with debugging enabled i have created a test within a unit test project in which i want pop up a form using its showdialog functiontestmethodpublic void testdialog this class inherits from form testform servicetestform new testformmy test form servicetestformshowdialog returni expect this test to reach showdialog and run indefinitely until i close the window however when i run this test with debugging the test reaches showdialog and no form appears strangely enough this same exact test works if i run without debuggingi need to be able to run the test with debugging and have the window thisplayother notesshow is not desirable as it does not wait for the window to close to continue besides it does not workthis same code has worked previously on another project utilizing net 35 this is only to say the showdialog strategy has definitely worked before and yes i copied that working code over directlymy question is similar to this one however my form is not a child of another dialog and does not live within a parent ui thread,"['c#', '.net']" +511767,javafx textarea and autoscroll i am trying to get a textarea to autoscroll to the bottom with new text which is put in via an event handler each new entry is just one long string of text with each entry separated by a line break i have tried a change handler which sets setscrolltop to doublemin value but to no avail any ideas of how this could be done,['java'] +511791,cannot get mongoid working with rails 4 i followed the official tutoriali have sqlite3 commented out in my gemfile as well as the following linesgem mongoid 4 github mongoidmongoidgem bson exthowever i keep receiving the specified sqlite3 for database adapter but the gem is not loaded add gem sqlite3 to your gemfilereason seems to be that the databaseyml still lists sqlite as the database how am i supposed to get rails to use the generated mongoidyml replacing databaseymls contents with mongoidyml does not seem to do the trick i get theactiverecordadapternotspecified database configuration does not specify adapter erroris it not compatible with rails 4 or am i missing something simpleedit i think i am getting warmer i have added the adapter as mongoid heres the contents of my databaseyml nowdevelopment adapter mongoid configure available database sessions required sessions defines the default session required default defines the name of the default database that mongoid can connect to required database xboxie provides the hosts the default session can connect to must be an array of hostport pairs required hosts localhost27017 options change whether the session persists in safe mode by default default false safe false change the default consistency model to eventual or strong eventual will send reads to secondaries strong sends everything to master default eventual consistency eventual how many times moped should attempt to retry an operation after failure default 30 max retries 30 the time in seconds that moped should wait before retrying an operation on failure default 1 retry interval 1 configure mongoid specific options optional options test sessions default database xboxie test hosts localhost27017 options consistency strong in the test environment we lower the retries and retry interval to low amounts for fast failures max retries 1 retry interval 0 sqlite version 3x gem install sqlite3 ensure the sqlite 3 gem is defined in your gemfile gem sqlite3 development adapter sqlite3 database dbdevelopmentsqlite3 pool 5 timeout 50 warning the database defined as test will be erased and regenerated from your development database when you run rake do not set this db to the same as development or production test adapter sqlite3 database dbtestsqlite3 pool 5 timeout 50 production adapter sqlite3 database dbproductionsqlite3 pool 5 timeout 50produces the error loaderror could not load active recordconnection adaptersmongoid adapter make sure that the adapter in configdatabaseyml is valid if you use an adapter other than mysql mysql2 postgresql or sqlite3 add the necessary adapter gem to the gemfile,['ruby-on-rails'] +511835,how to run a method before all tests in all classes i am writing selenium tests with a set of classes each class containing several tests each class currently opens and then closes firefox which has two consequencessuper slow opening firefox takes longer than running the test in a classcrashes because after firefox has been closed trying to reopen it really quickly from selenium results in an error 54i could solve the error 54 probably by adding a sleep but it would still be super slowso what i would like to do is reuse the same firefox instances across all test classes which means i need to run a method before all test classes and another method after all test classes so setup class and teardown class are not sufficient,['python'] +511862,underscorejs map array of keyvalue pairs to an object one liner i have been going through the underscore docs but i cannot seem to find a method or nested method call to do the following transformationlet us say i have the following javascript array name secho value 1 name icolumns value 12 and i need to transform it into the following object secho 1 icolumns 12 i am using underscorejs for a reason so it must be a one liner,['javascript'] +511869,why is spring datas mongorepository so limited so i notice that spring datas mongotemplate has a lot of different types of save object operations like save upsert insert and updatefirst spring datas mongorepository interface on the other hand has one persistence method save now obviously if i want create update upsert functionalities i can implement them pretty easily just do a get before you call save and check if the entity exists or not but it seems strange that mongotemplate has such a diversity of options i cannot even figure out what the difference between a save and an upsert is but spring datas repos are so limited do you think it is wasteful lazy to use spring data mongorepositories without customizing its methods if youre going to be using create update semantics or is the difference between a get null check repositorysave vs a mongotemplateinsert too irrelevant to care about,['java'] +511952,how to get change in network connection notification from ios reachability class hi i want to capture whenever user gets a network connectivity in my application for this i have added apples reachability class and below is the snippet i am using in my appdelegate class didfinishlaunchingwithoptions methodreachability reachability reachability reachabilityforinternetconnection reachability startnotifier nsnotificationcenter defaultcenter addobserverself selectorselectorreachabilitychanged namekreachabilitychangednotification objectniland my reachabilitychanged selector method is as below voidreachabilitychangednsnotificationnotification reachability reachability notificationobject ifreachabilitycurrentreachabilitystatus notreachable nsloginternet off else nsloginternet onbut here i am not getting any kind of notification when i switch off my airplane mode and when i get a network connectivity in my phoneam i missing anything,"['ios', 'objective-c']" +511957,how to create a number picker dialog i want to be able to create a dialog that allows the user to pick a number from a specified range i know that there are existing widgetslike those from quietlycoding and the one by simonvt that already does this but i am having hard time integrating those properly into my application also those are primarily widgets i want something that is very similar to the one in the android developers page tutorialsi also checked the documentation for the numberpicker and it said to go check the timepicker and datepicker for examples but they only show how to use time and date pickers and i am having a hard time feeling my way around the code and trying to convert the time picker to just a normal number picker does anyone have any idea where to start i have been looking for solutions for the last 3 hours to no avail,['android'] +511972,finding stateful singleton beans today we found this pattern in our codeclass foo private liststring errors public void adderrorstring error public liststring geterrorswhile the code seems to work this is a singleton spring bean and it is injected in several independent places and the consumers of the bean assume that they each have their own list of errors so this introduces subtle bugsthe obvious solution is to educate developers to avoid this kind of error but i was wondering if there is a static or runtime code analysis tool which can find this kind of bugfor example a bean postprocessor could analyze the bean before it is returned and look for private fields that are not autowired,['java'] +512026,jquery keypress event ignore arrow keys i have an input box that acts like a search similar to facebooki am using the jquery on keypress event which works finethe problem is that i cannot scroll down on the set of the results using the arrow keys every time that one of them is pressed the search results are being regeneratedso is it possible to ignore the arrow keys shift tab etc searchform searchtermsonkeypress function searchitems autocomfadein thanks,"['jquery', 'html']" +512079,how to properly implement arc compatible and alloc init safe singleton class i saw thread safe versionmyclass singleton static thispatch once t pred static myclass shared nil thispatch oncepred shared myclass alloc init return sharedbut what would happen if someone just calls myclass alloc init how to make it return same instance as the myclass singleton method,"['ios', 'objective-c']" +512093,best way to transfer value from an arraylist to another with 2 arraylist i was wondering if the best way from transforming the 1st one into a copy of the second one is to go likemyfirstarrayclearmyfirstarrayaddallmysecondarrayormyfirstarray mysecondarrayclonewhat are the main differences between those two method which on is preferrable and is there another easier or cleaner solution thanks for any tipsedit i use this copy for replacing an array of item im currently working with the one where i store the item i will work with in the next loop at the end of the loop i replace my currentarraylist with my futurarraylist and i clear my futurarraylist in order to add new item in it i hope its clear enough,['java'] +512110,imagesloaded with masonry object has no method imagesloaded getting this error trying to use masonry with imageloadedobject has no method imagesloadedthe links to the necessary scripts are in my headerscript src typetextjavascriptscriptscript srcjsmasonrypkgdminjs typetextjavascriptscriptscript srcjsimagesloadedpkgdminjs typetextjavascriptscriptand here is how the code looks in my footerdocumentreadyfunction archivepostcontainerimagesloadedfunction thismasonry itemselector post columnwidth344 edit addendumplacing the script tags for imagesloaded and masonry in the actual php file for the page i need them on instead of in headerphp gets me this error instead coming from imagesloadeduncaught typeerror undefined is not a function not sure why moving the tags just from the to just under the header would change this but at least now i am getting to imagesloaded,"['javascript', 'jquery']" +512206,mysql 56 headaches on mac osx several of my colleagues and i have recently upgraded from mysql 55 to mysql 56 using homebrew on our macs to test locally before upgrading our servers since this upgrade we all have been experiencing intermittent mysql errors when running our rails codelost connection to mysql server at sending authentication information system error 32we have tried remaking our usernames and passwords in our database and upping the connection timeout but neither have fixed the problem the error logs do not mention the issue the only workaround we have found when we run into the problem is to kill mysql and restart it i have even noticed this error more recently using mysql u root p on the command line it seems that once i start getting this error i cannot exceed my current number of connections no matter what username i use if i close a connection then i can reopen onewe have the following environmentssome of us rails 32 ruby 2 mysql2 0313 mysql 5612 mac osx 1084others of us rails 32 ruby 19 mysql2 0313 mysql 5610 mac osx 1084any ideas what might be causing thisthanksjulie,['mysql'] +512211,how does a block capture the variables outside of its enclosing scope i know that an objectivec block can capture and set the value of variables outside of its enclosing scope how does it do that,['objective-c'] +512220,static and dynamic memory allocation of objects in c in a c program for a class how can we get the counts of the number of active objects at any point of time which are statically created and dynamically created separately,['c++'] +512222,alert called on new window seems to be called from original page if using jquerys methods this is the test caseusing javascriptjsonclick function var newwindow windowopen newwindowdocumentwritespantestspan newwindowdocumentwritescr iptalert1scr iptthis gives the expected result the dialog alert is showing inside the new windowusing jqueryjqueryonclick function var newwindow windowopen newwindowdocumentbodyappendspantestspan scr iptalert1scr iptthe dialog alert is shown inside the main pagewhy the difference am i missing something herethis behaviour has been tested in chromeffsafariieeditas pointed out by mishik this is due to how jquery handles script tags using the globaleval method to run scripts in the global context so a possible workaround for using jquery but not fall back to the pure javascript method could be to set the newwindow variable in the global context too and use it like that egjqueryonclick function newwindow windowopen newwindowdocumentbodyappendspantestspanscr iptnewwindowwindowalert1scr iptdemo,"['javascript', 'jquery']" +512226,scipy stats meaning of parameters for probability thistributions scipy docs give the thistribution form used by exponential as exponpdfx lambda exp lambdaxhowever the fit function takes fitdata loc0 scale1and the rvs function takesrvsloc0 scale1 size1question 1why the extraneous location variable i know that exponentials are just specific forms of a more general thistribution gamma but why include the uneeded information even gamma does not have a location parameter question 2is the out put of the fit in the same order as the input variable by that i meanif i do t fit t will have the form t0 t1should i interpret t0 as the shape and t1 as the scaledoes this hold for all the thistributionswhat about for gamma fitdata a loc0 scale1,['python'] +512312,testing default scope in rspec i am trying to test my default scope line in a modelmy test is as followsit orders by ascending name by default do expectcoasterscopedto sqlto eq coasterordernameto sqlendmy error isexpected select coasters from coasters order by name asc namegot select coasters from coasters order by name ascwhat does the name part at the end of the first line of the error mean and how can i resolve thisupdatemy test describe default scope do letcoaster one factorygirlcreatecoaster name tower of terror letcoaster two factorygirlcreatecoaster name apocalypse it orders by ascending name do coasterallshould eq coaster two coaster one end endmy errorsexpected coaster two coaster one got coaster id 5 name apocalypse height 60 speed 600 length 160 inversions 4 material nil notes nil lat nil lng nil manufacturer id nil park id 408 created at 20130723 204852 updated at 20130723 204852 slug apocalypseataltontowers style nil covering nil ride style nil model nil layout nil order nil dates ridden nil times ridden nil coaster id 4 name tower of terror height 60 speed 600 length 160 inversions 4 material nil notes nil lat nil lng nil manufacturer id nil park id 407 created at 20130723 204852 updated at 20130723 204852 slug towerofterrorataltontowers style nil covering nil ride style nil model nil layout nil order nil dates ridden nil times ridden nil compared using update 2it looks as though rails 4 deprecates the use of default scope so in light of this i have remove the default scope from my model and replaced it with a standard scopethe new scope is nowscope by name asc lambda ordername asc and my associated test is describe scopes do letcoaster one factorygirlcreatecoaster name tower of terror letcoaster two factorygirlcreatecoaster name apocalypse it orders coasters by ascending name do coasterby name ascshould eq coaster two coaster one end endwhen running this test i get 1 coaster scopes orders coasters by ascending name failureerror coasterby name ascshould eq coaster two coaster one expected coaster two coaster one got coaster id 15 name apocalypse height 60 speed 600 length 160 inversions 4 material nil notes nil lat nil lng nil manufacturer id nil park id 528 created at 20130724 223650 updated at 20130724 223650 slug apocalypseataltontowers style nil covering nil ride style nil model nil layout nil order nil dates ridden nil times ridden nil coaster id 14 name tower of terror height 60 speed 600 length 160 inversions 4 material nil notes nil lat nil lng nil manufacturer id nil park id 527 created at 20130724 223650 updated at 20130724 223650 slug towerofterrorataltontowers style nil covering nil ride style nil model nil layout nil order nil dates ridden nil times ridden nil compared using diff 12 12 coaster two coaster one coaster id 15 name apocalypse height 60 speed 600 length 160 inversions 4 material nil notes nil lat nil lng nil manufacturer id nil park id 528 created at 20130724 223650 updated at 20130724 223650 slug apocalypseataltontowers style nil covering nil ride style nil model nil layout nil order nil dates ridden nil times ridden nil coaster id 14 name tower of terror height 60 speed 600 length 160 inversions 4 material nil notes nil lat nil lng nil manufacturer id nil park id 527 created at 20130724 223650 updated at 20130724 223650 slug towerofterrorataltontowers style nil covering nil ride style nil model nil layout nil order nil dates ridden nil times ridden nil specmodelscoaster specrb10in block 3 levels in top requiredany ideas on what is going wrong,['ruby-on-rails'] +512319,send struct over socket in c i am developing a clientserver program and my client has to send messages to the server sample message c structure struct registrationchar multicastgroup24pid t clientpidclient code snippet to serialize struct struct registration regn regnclientpid getpidstrcpyregnmulticastgroup 2261printfpiddn regnclientpid printfmgsn regnmulticastgroupprintfsizedn sizeofregn size is 28data unsigned charmallocsizeofregnmemcpydata regn sizeofregnprintfsizedn sizeofdata size is 4 server code to deserialize data ifrecvfromsd recvbuf recvbufsize 0 struct sockaddrclientaddr len 0 printferror receiving message from clientnelse printfmessage receivedsn recvbuf printfsize dn strlenrecvbuf memcpyregn recvbuf sizeofregn printfpiddn regnclientpid printfmgsn regnmulticastgroupafter copying the struct to unsigned char the size of the array is only 4why is data not fully copied to the array the server is not able to reconstruct the struct from the char arrayplease let me know what am i doing wrong,['c'] +512339,forcing a single page application to update for single page apps what methods are there for forcing the page andor javascript files to be reloaded when there have been updates deployed to the serverone obvious way would be to poll some server resource to see if the current version of the app is running in the browser and if not then load the updated resourcesi am wondering if there are more generally accepted methods that make use of specific http or dom featuresupdatei am reading about the html5 appcache this seems to be geared more towards applications that can run without requiring a server connection i do not think this could be relevant for updating a spas resources including the page itself from the server am i correct,"['javascript', 'html']" +512346,fatal error allowed memory size of 67108864 bytes exhausted tried to allocate 122880 bytes i have two domains webhosted on 0webhost i installed wordpress on them and for some days it functioned well but now it shows me the following error on both of them fatal error allowed memory size of 67108864 bytes exhausted tried to allocate 122880 bytesthe source of the error in is never the same it always changesi found that this error is common but here i do not have a phpini file i understood that i should change the wpconfig filewell heres the catch how should i do thisi understood that i should adefine awp memory limita ama increase limit to m adding 64 96 or 128 thanks to i am not good at programming just a newbie who wants his own domain can you help meplease there me exactly where to put the functionif this is not how to solve the problem please offer me another solution i am quite in a great need of help i cannot post the file here it seems i do not format it well but i can explain the structureintroduction the base configurations of the wordpress after that mysql datathen authentication unique keys and saltswordpress database table prefixwordpress localized language defaults to englishfor developers wordpress debugging mode that is all stop editing happy bloggingso where should i introduce the define function if in this file where if in another which and where,['php'] +512352,how to refresh select2 dropdown menu after ajax loading different content i am using select2 in a combination of dropdown menus i have one menu for countries and one for statesprovinces depending on the country that is chosen the statesprovinces dropdown changes in content the statesprovinces are pulled with ajax from a database and then thisplayed this waythisplay output select stylewidth350px tabindex2 namestate idstate dataplaceholderchoose a country thisplay output option value selectedselect a stateoption while state details thisfetch arraysql select states thisplay output option value state detailsid selected value state detailsid selected state detailssname optionthisplay output selectso far so good all the provinces change correctly however when it initially loads the select2 shows undefined for the states dropdown even though i have it set asdataplaceholderchoose a countryi am assuming it could be because on loading the country selected is united states and it populates a list of states but none of them is default or selected is there any other way to define a default value so that it does not show undefinedand another but less important problem is that when someone chooses united states for example and then chooses arizona if the person then changes to canada as the country the state of arizona still stays but when opening the dropdown the provinces of canada are selectable is there any way to return it to the default value temporarily when someone selects another country until a province is chosen againmy loading code is currently justscriptdocumentreadyfunction stateselect2 script,"['php', 'jquery']" +512394,sql server stored procedure that returns a boolean if table exists c implementation i have created a stored procedure that takes a single argument the name of a table and returns 1 if it exists in the database 0 if it does not in sql server management studio testing my stored procedure works exactly as i would like it to however i am having trouble getting that value for use in my c programmy options seem to be executescalar executenonquery or executereader none of which seem appropriate for the task nor can i get them to even retrieve my stored procedures resulti have tried assigning my parameter with both cmdparametersaddwithvalue and cmdparametersadd again to no avail,['c#'] +512397,is there any way to convert a map to a json representation using jackson without writing to a file i am trying to use jackson to convert a hashmap to a json representationhowever all the ways i have seen involve writing to a file and then reading it back which seems really inefficient i was wondering if there was anyway to do it directly heres an example of an instance where i would like to do itpublic static party readonepartystring partyname party localparty new party ifconnectionnull connection new dbconnection try string query select from pureservlet where party name ps conpreparestatementquery pssetstring1 partyname resultset psexecutequery meta resultsetgetmetadata string columnname value resultsetnext forint j1jmetagetcolumncountj necessary to start at j1 because of mysql index starting at 1 columnname metagetcolumnlabelj value resultsetgetstringcolumnname localpartygetpartyinfoputcolumnname value this is the hashmap within the party that keeps track of the individual values the column name label value is the value public class party hashmap stringstring partyinfo new hashmapstringstring public hashmapstringstring getpartyinfo throws exception return partyinfo the output would look something like thispartyinfo party name vsn party id 92716518 party number 92716518so far every example i have come across of using objectmapper involves writing to a file and then reading it back is there a jackson version of javas hashmap or map thatll work in a similar way to what i have implemented,['java'] +512409,differentiating between user scroll and programatic page change in viewpager i have a androidsupportv4viewviewpager in my application and i would like to differentiate between a programmaticallyinitiated smooth scroll and a userinitiated touch scroll i have had a look at viewpageronpagechangelistener and i believe that the answer may lie in there but i am just not sure how,['android'] +512410,function select all and icheck i want to implement a select all using icheckthis is what i have done so farfunction inputicheck inputallonifchecked ifunchecked functionevent if eventtype ifchecked inputcheckicheckcheck else inputcheckicheckuncheck inputcheckonifunchecked functionevent inputallicheckuncheck fiddle jsfiddlenetn7uyr1i want that when check box 1 check box 2 check box 3 check box 4 are selected select all also gets selectedexactly like this jsfiddlenetivanionutn7uyrhow can i do this,"['javascript', 'jquery']" +512435,getting google map fragment in oncreateview using actionbar tabs i am trying to retrieve the google map fragment while using tabs in an actionbar when i load the tabbed page the map loads fine but i want to get the map object so i can center it add markers etcis there a way to do this and if there is would somebody be so kind to show me howheres the code for my tabbed pagethe specific method i am working with is public static class map extends fragmentpublic class page3activity extends fragmentactivity implements actionbartablistener final context context this static googlemap map static mapview mmapview databasehandler db new databasehandlercontext appsectionspageradapter mappsectionspageradapter viewpager mviewpager suppresslintnewapi public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutpage3 create the adapter that will return a fragment for each of the three primary sections of the app mappsectionspageradapter new appsectionspageradaptergetsupportfragmentmanager colordrawable colordrawable new colordrawable final actionbar actionbar getactionbar colordrawablesetcolor0xff9acc00 actionbarsetbackgrounddrawablecolordrawable actionbarsettitleroad trip calculator actionbarsetsubtitletrip information actionbarsetthisplayshowtitleenabledtrue actionbarsetthisplayshowhomeenabledtrue actionbarsetthisplayoptionsactionbarthisplay show custom actionbarthisplay show home actionbarthisplay show title specify that the homeup button should not be enabled since there is no hierarchical parent actionbarsethomebuttonenabledfalse specify that we will be thisplaying tabs in the action bar actionbarsetnavigationmodeactionbarnavigation mode tabs set up the viewpager attaching the adapter and setting up a listener for when the user swipes between sections mviewpager viewpager findviewbyidridpager mviewpagersetadaptermappsectionspageradapter mviewpagersetonpagechangelistenernew viewpagersimpleonpagechangelistener override public void onpageselectedint position when swiping between different app sections select the corresponding tab we can also use actionbartabselect to do this if we have a reference to the tab actionbarsetselectednavigationitemposition for each of the sections in the app add a tab to the action bar for int i 0 i mappsectionspageradaptergetcount i create a tab with text corresponding to the page title defined by the adapter also specify this activity object which implements the tablistener interface as the listener for when this tab is selected actionbaraddtab actionbarnewtab settextmappsectionspageradaptergetpagetitlei settablistenerthis actionbar top bar code override public void ontabunselectedactionbartab tab fragmenttransaction fragmenttransaction override public void ontabselectedactionbartab tab fragmenttransaction fragmenttransaction when the given tab is selected switch to the corresponding page in the viewpager mviewpagersetcurrentitemtabgetposition override public void ontabreselectedactionbartab tab fragmenttransaction fragmenttransaction a link fragmentpageradapter that returns a fragment corresponding to one of the primary sections of the app public static class appsectionspageradapter extends fragmentpageradapter public appsectionspageradapterfragmentmanager fm superfm switching between tabs override public fragment getitemint i switch i case 0 return new map case 1 return new directions case 2 return new poilist case 3 return new tripinfo default ii1 return null override public int getcount return 4 override public string getpagetitleint position string tabname ifposition 0 tabname map else ifposition 1 tabname directions else ifposition 2 tabname poi list else ifposition 3 tabname trip info return tabname map public static class map extends fragment override public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate view rootview inflaterinflaterlayoutmaptab container false i want to be able to do something like this googlemap map supportmapfragment fm supportmapfragment getsupportfragmentmanagerfindfragmentbyidridmap1 map fmgetmap mapdosomething return rootview directions public static class directions extends fragment override public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate view rootview inflaterinflaterlayoutdirectionstab container false textview rootviewfindviewbyidandroidridtext1settext directions return rootview poi list public static class poilist extends fragment override public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate view rootview inflaterinflaterlayoutpoitab container false textview rootviewfindviewbyidandroidridtext1settext poilist return rootview trip info public static class tripinfo extends fragment override public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate view rootview inflaterinflaterlayouttripinfotab container false textview rootviewfindviewbyidandroidridtext1settext trip info return rootview here is my xml file maptabxml that i have my map fragment inxml version10 encodingutf8linearlayout xmlnsandroid androidlayout widthmatch parent androidlayout heightmatch parent androidorientationvertical fragment androidididmap1 androidlayout widthmatch parent androidlayout heightmatch parent classcomgoogleandroidgmsmapssupportmapfragment linearlayoutsolved public static class map extends fragment mapview mapview googlemap map override public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate view v inflaterinflaterlayoutmaptab container false gets the mapview from the xml layout and creates it mapview mapview vfindviewbyidridmapview mapviewoncreatesavedinstancestate gets to googlemap from the mapview and does initialization stuff map mapviewgetmap mapgetuisettingssetmylocationbuttonenabledfalse mapsetmylocationenabledtrue mapaddmarkernew markeroptionspositionnew latlng5016700319383262 needs to call mapsinitializer before doing any cameraupdatefactory calls try mapsinitializerinitializethisgetactivity catch googleplayservicesnotavailableexception e eprintstacktrace updates the location and zoom of the mapview cameraupdate cameraupdate cameraupdatefactorynewlatlngzoomnew latlng431 879 10 mapanimatecameracameraupdate return v override public void onresume mapviewonresume superonresume override public void ondestroy superondestroy mapviewondestroy override public void onlowmemory superonlowmemory mapviewonlowmemory,['android'] +512458,loop through all descendants of a div js only i have been using jquery to do thiselementfindeachfunction var this this thisremoveattrstyle width align if thisisembed elementappenddiv classvideodiv thisattrwidth 640attrheight 360parentappendto element video but i have been reading that jquerys each method is quite slow when compared to a simple for loop jsperf my question is how can i mimic this with pure js find all elements within a div then loop through the nodesi have tried to search for this but all i can seem to find are jquery answers everywherei have tried other things but this was as close as i got to selecting all descendantsvar children documentgetelementbyididgetelementsbytagnamefor var i 0 ichildrenlengtth i childreniremoveattributestyle consolelogchildreni,['javascript'] +512511,java jaxb generation how do i get a bigdecimal from my xsd i have an xsd annotation that i am trying to get to marshal into a java object i would like the java to end up with bigdecimal for its value what do i enter in the xsd to make it do this i am using an xjc ant taskxjc schemamyxsd destdirgenerated headerfalse extensiontrue here is the relevant xsd complextype namesize attribute nameheight typebigdecimalattribute this is wrongcomplextypei would like to end up with this for the generated class public class size xmlattributename height protected bigdecimal height,['java'] +512540,ios safari runs out of memory with webkittransform crashes most retina devicesios safari easily runs out of memory and crashes when using some webkittransform instructions this approach delivers impressive graphics but especially on retina thisplays just seems to consume a lot of memory and cause crashesthe demo above shows a text thisplayed 150 times that would otherwise run normally on a pc browser the font size and number of elements is exaggerated to cause a crash the webkittransform translate3d0 is intended to force gpu accelerated drawing of each elementin the real application we are using translatexyz scale and others that seem to be connected to gpu use in the same way images and sprites are also used but they are not connected to crashes directlygiven the scenario above1 is it a bug that ios safari is crashing2 plugging in apple instruments memory monitor virtual memory climbs and seems to be the culprit of the crash what exactly is using this memory3 is there any other gpu accelerated approach that would not consume a lot of memory,['ios'] +512552,how to specify that a parameter is a list of specific objects in python docstrings i really like using docstrings in python to specify type parameters when projects get beyond a certain sizei am having trouble finding a standard to use to specify that a parameter is a list of specific objects eg in haskell types i would use string or acurrent standard recognisable by pycharm editordef stringifylistofobjects type listofobjects list return joinmapstr listofobjectswhat i would preferoption 1def stringifylistofobjects type listofobjects listobject return joinmapstr listofobjectsoption 2def stringifylistofobjects type listofobjects object return joinmapstr listofobjectsi suppose that was not a great example the more relevant use case would be one where the objects in the list must be of a specific typebetter exampleclass foodobject def init self calories selfcalories caloriesclass applefood def init self superself 200class personobject energy 0 def eatfoods type foods food is not recognised by editor for food in foods energy foodcaloriesso other than the fact that i am getting hungry this example illustrates that if called with a list of the wrong kind of object the code would break hence the importance of documenting not only that it needs a list but that it needs a list of foodrelated questionhow can i tell pycharm what type a parameter is expected to beplease note that i am looking for a more specific answer than the one above,['python'] +512560,how to call an extension method without using using systemclass runner static void main a a new a how to say aprintstuff without a using consoleread class a namespace extensionmethod static class aextensions public static void printstuffthis a a consolewritelinetext how would i call the extension method without a using and not extensionmethodaextensionsprintstuffa since that does not make use of extension method,['c#'] +512616,return type is a variable in a class i am looking the c reference and i see the template size t i class typestypename tuple element i tupletypes type const getconst tupletypes tpl noexceptand what i cannot understand is the the return type what does the typename tuple element i tupletypes type const meansmy interpertation is that it return a const reference to a general type of tuple elementtype but i think that the tuple elementtype is like belowclass a public int bab but why it can be used as a type i cannot understand it,['c++'] +512617,uicollectionview special horizontal flow multiple sections i have a uicollectionview there is used differently depending on device orientation the image describe what i have and what i need is it possible to get horizontal scrolling as i need it with default flowlayout or do i need to make customflowlayoutguide appreciated or multiple collectionviews,['objective-c'] +512641,onactivityresult returns null data for an image capture overrideprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate filepath getoutputmediafilefilecolumnsmedia type image file file new filefilepath uri output urifromfilefile intent i new intentandroidprovidermediastoreaction image capture iputextramediastoreextra output output startactivityforresulti return file path overrideprotected void onactivityresultint requestcode int resultcode intent data superonactivityresultrequestcode resultcode data data is always null here requestcode return file path resultcode activityresult oki checked the values for file and output uri both are fine and the captured image actually exists at that locationbut the data returned in onactivityresult is always null even after capturing the imageediti checked this questiononactivityresult returns with data nullwhich sayswhenever you save an image by passing extraoutput with camera intent the data parameter inside the onactivityresult always return null so instead of using data to retrieve the image use the filepath to retrieve the bitmapand maybe that solution will work for me but the above code of mine was a working code until now for the same scenario,['android'] +512679,phonegap ios app icon so i am trying to specify my custom ios icons for my app in my configxml file using the guide at however when i use the line of code they give you the app fails to load and throws an error in xcode20130724 093206121 ilens19852c07 assertion failure in cdvconfigparser parserparseerroroccurred applicationsmamphtdocscarlzeissphonegap290ilenscordovalibclassescdvconfigparserm9320130724 093206121 ilens19852c07 terminating app due to uncaught exception nsinternalinconsistencyexception reason configxml parse error line 38 col 40 first throw call stack0x173012 0x28e7e 0x172e78 0x1564665 0x7a352 0x15aca08 0x58e02af 0x58fa745 0x590225a 0x59044e5 0x5903f07 0x15ac8fe 0x15ac890 0x15acb46 0x15acbfa 0x590d2 0x57ea0 0x57f6e 0x83749 0x48de1e 0x5802e 0x837ad 0x8326b 0x3ac157 0x3ac747 0x3ad94b 0x3becb5 0x3bfbeb 0x3b1698 0x3720df9 0x3720ad0 0xe8bf5 0xe8962 0x119bb6 0x118f44 0x118e1b 0x3ad17a 0x3aeffc 0x82f4c 0x82ea9libcabidylib terminate called throwing an exceptionif i remove the gapplatformios part the app loads but the icon does not changedoes anyone have a working example of changing icons through the configxml file pleasenote i do not believe this is a duplicate of the question that has been linked to this question my question is in regards to adding icons through the configxml file as you should be able to do as per the phonegap documents however it turns out that they did not support this option at that time,['ios'] +512730,android grid view place items from right to left i am working on an android application with arabic versionin one of the interfaces i have gridview so to thisplay items in the correct order i have to thisplay items in the gridview from the right to the left and of corse from the top to the bottomto do that i tried to add these attributes in the gridview androidgravityrightandroidlayout gravityrightunfortunately items still thisplayed from the left to the rightany idea to do it in the right way,['android'] +512741,bootstrap tab activation with jquery i have the following codeul classnav navtabs lia hrefa datatoggletabali lia hrefb datatoggletabali lia hrefc datatoggletabcaliuldiv classtabcontent idtabs div classtabpane idacontentdiv div classtabpane idbcontentdiv div classtabpane idcontentdivdivand the following scriptdocumentreadyfunction activatabafunction activatabtab tabpane ahref tab tabshowin this case when the page is ready the second tab will be activate but i allways get a javascript error in the line tabpane ahref tab tabcan anyone help me please,"['javascript', 'jquery']" +512775,how do you install google frameworks play accounts etc on a genymotion virtual device i am currently trying out genymotion and boy it is so much faster than the adt emulatorbut i need to install google play to download some apps into it how do i do this,['android'] +512894,java static import causing compile error probable compiler bug this compiles fine in eclipse jdt but not on 1630 or 1725package dohimport static dohwtfinnerclassinnerclassmethodimport javaioserializablepublic class wtf static class innerclass implements serializable public static void innerclassmethod with javac i get the following compile errorerror cannot find symbol static class innerclass implements serializable symbol class serializablelocation class wtfcommenting out the superfluous static import makes the code compile so does reordering the import statements,['java'] +512907,radio button checkedchecked not changing when option changed i have created a basic 2 radio button form as seen in my example below observing the browser rendering we see item 1 selected we inspect item 1 and 2 when i click item 2 i expect item 1s checkedchecked to be remove i expect item 2 receive the attribute checkedchecked is this not the expected behavior div spanitem 1span input typeradio nameradio1 idradio1 checkedchecked divdiv spanitem 2span input typeradio nameradio1 classcheckbox idradio2 div,"['html', 'css']" +512919,orthogonal projection with numpy i have a list of 3dpoints for which i calculate a plane by numpylinalglstsq method but now i want to do a orthogonal projection for each point into this plane but i cannot find my mistakefrom numpylinalg import lstsqdef vecproductvek1 vek2 return vek10vek20 vek11vek21 vek12vek22def calcplanex y z x y and z are given in lists and lenx sum x sum y sum z sum xx sum yy sum xy sum xz sum yz 0 for i in rangen sum x xi sum y yi sum z zi sum xx xixi sum yy yiyi sum xy xiyi sum xz xizi sum yz yizi m sum xx sum xy sum x sum xy sum yy sum y sum x sum y n b sum xz sum yz sum z abc lstsqm b0 z ax by c ax z by c x bay 1az ca r0 ca 0 0 you ba 1 0 v 1a 0 1 xn yn zn orthogonalize you and v with gramschmidt to get you and w uu vecproductu u vu vecproductv u fak0 vu erg0 valfak0 for val in u w v0erg00 v1erg01 v2erg02 ww vecproductw w p new xu xw for i in rangelenx xu vecproductxi yi zi u xw vecproductxi yi zi w fak1 xu fak2 xw erg1 valfak1 for val in u erg2 valfak2 for val in w erg erg10erg20 erg11erg21 erg12erg22 erg0 r00 xnappenderg0 ynappenderg1 znappenderg2 return xnynznthis returns me a list of points which are all in a plane but when i thisplay them they are not at the positions they should bei believe there is already a certain builtin method to solve this problem but i could not find any,['python'] +512941,map markers with text in google maps android api v2 i have came up with this post but it is for the deprecated google maps apiin the new api i could not find an easy way to do this in fact i could not do it at all basicly i want to have textviews as a marker on the map with 9patch drawable as a background of the text trulia is still doing it with the new api v2 in their current app you can check it herehow can i do this,['android'] +512964,styling jquery ui autocomplete fiddlei am trying to style the sections inside the autocomplete but i do not know what to put in the css for the sections i am specifically trying to makecolor 96f226borderradius 0pxborder 1px solid 454545any suggestions,"['javascript', 'jquery', 'css']" +512982,throwing an exception while handling an exception i am reading the c programming language 4th edition book and have a question regarding a paragraph about exception handlingthere are cases where exception handling must be abandoned for less subtle errorhandling techniques the guiding principles aredo not throw an exception while handling an exceptiondo not throw an exception that cannot be caughtif the exceptionhandling implementation catches you doing either it will terminate your programcould someone give me an example of the first situtation only something like this comes to my mind but it is a valid code according to gtry throw 1catch try throw 2 catch cout ok,['c++'] +512987,what is the difference between web deployment tool 21 and web deploy 35 which one is required for deploys from vs 2010 i am trying to setup publishingdeployment of an aspnet mvc project from visual studio to a box running iis 75windows server 2008 i found this useful tutorial and know i need to install something called web deploy when i go to install this from web platform installer i see a few options web deployment tool 21 web deploy 35 and web deploy 35 for hosting servers which one do i need what is the difference,['asp.net'] +513008,handsontable replace autocomplete values with key before posting i am using handsontable to make editing database tables more interactive on my sitehandsontable fulfils nearly all my requirements except that some columns in my database actually store foreign keys rather than local string valuesin the ui i would like these columns to appear as dropdown menus where the user selects a readable value mapped to the previously mentioned foreign key ie something like an html namevalue selectunfortunately handsontable does not have such a cell type the closest thing to it is autocomplete this allows me to create a dropdown but it only contains values no corresponding keys here is how it is createdsource jebediah bob bill buzzso what i am planning is to send two json strings from the serverone containing the parameters needed by handsontable to render the table data id 1 description crude volume 204 customer jebediah id 2 description hidrogen volume 513 customer bob id 3 description coal volume 67 customer bill id 4 description wood volume 513 customer buzz columns data id type numeric data description type text data volume type numeric data color type autocomplete strict true source jebediah bob bill buzz the second mapping keys to values mappings key 0 value jebediah key 0 value bob key 0 value bill key 0 value buzz so far so good now for the tricky parthandsontable has a function getdata that allows me to retrieve the tables data as a json string ready to be sent back to the servervar jdata myhandsontablegetdatawhere jdata would look something like thisdata id 1 description crude volume 204 customer jebediah id 2 description hidrogen volume 513 customer bob id 3 description coal volume 67 customer bill id 4 description wood volume 513 customer buzz now before posting i would like to replace that values for the customer node with their matching pair key within the mappings json stringhow can i best achieve this in javascriptjquery is there a function that works something as followsjdatareplacenodenode mappingsthanks,"['javascript', 'jquery']" +513077,using flasksqlalchemy without the subclassed declarative base i am using flask for my python wsgi server and sqlalchemy for all my database accessi think i would like to use the flasksqlalchemy extension in my application but i do not want to use the declarative base class dbmodel instead i want to use the base from sqlalchemyextdeclarativedoes this defeat the entire purpose of using the extension my use casei would like the extension to help me manage sessionsengines a little better but i would like to handle all models separatelyi actually wouldnt mind using the extension but i want to write strict models i am porting code from a nonflask application and i will be pushing changes back to that project as i go if flasksqlalchemy allows me to cheat on table metadata for instance that is going to cause problems when the code is pushed back out there are also portions of my code that do lots of type checking polymorphic identities and i also remember reading that type checking on table is not recommended when using the extension,['python'] +513114,aggregate root with entity framework using domain driven design i am building an application using domain driven design that is using entity frameworkmy goal is to allow my domain models that get persisted with ef contain some logic within themout of the box entityframework is pretty nonrestrictive as to how entities get added to the graph and then persistedtake for example my domain as poco without logicpublic class organization private icollectionperson people new listperson public int id get set public string companyname get set public virtual icollectionperson people get return people protected set people value public class person public int id get set public string firstname get set public string lastname get set public virtual organization organization get protected set public class organizationconfiguration entitytypeconfigurationorganization public organizationconfiguration hasmanyo opeoplewithrequiredp porganization mapm mmapkeyorganizationid public class personconfiguration entitytypeconfigurationperson public personconfiguration hasrequiredp porganizationwithmanyo opeople mapm mmapkeyorganizationid public class mydbcontext dbcontext public mydbcontext basedata sourcelocaldbv110initial catalogstackoverflowintegrated securitytrue protected override void onmodelcreatingdbmodelbuilder modelbuilder modelbuilderconfigurationsaddnew personconfiguration modelbuilderconfigurationsaddnew organizationconfiguration public idbsetorganization organizations get set public idbsetperson people get set my example domain is that an organization can have many people a person can only belong to one organizationthis is very simple to create an organization and add people to itusing var context new mydbcontext var organization new organization companyname matthews widget factory organizationpeopleaddnew person firstname steve lastname mcqueen organizationpeopleaddnew person firstname bob lastname marley organizationpeopleaddnew person firstname bob lastname dylan organizationpeopleaddnew person firstname jennifer lastname lawrence contextorganizationsaddorganization contextsavechangesmy test query isvar organizationswithsteve contextorganizationswhereo opeopleanyp pfirstname stevethe above layout of classes does not conform to how the domain works for example all people belong to an organization with organization being the aggregate root it does not make sense to be able to do contextpeopleadd as that is not how the domain worksif we wanted to add some logic to the organization model to restrict how many people can be in that organization we could implement a methodpublic person addpersonstring firstname string lastname if peoplecount 5 throw new invalidoperationexceptionyour organization already at max capacity var person new personfirstname lastname thispeopleaddperson return personhowever with the current layout of classes i can circumvent the addperson logic by either calling organizationpersonsadd or completely ignore the aggregate root by doing contextpersonsadd neither of which i want to domy proposed solution which does not work and is why i am posting it here ispublic class organization private listperson people new listperson protected virtual listperson writablepeople get return people set people value public virtual ireadonlycollectionperson people get return peopleasreadonly public void addpersonstring firstname string lastname do domain logic validation writeablepeopleadd this does not work as the mapping code hasmanyo opeoplewithrequiredp porganization does not compile as hasmany expects an icollectiontentity and not ireadonlycollection i can expose an icollection itself but i want to avoid having add remove methodsi can ignore the people property but i still want to be able to write linq queries against it my second problem is that i do not want my context to expose the possibility to add remove people directly in the context i would wantpublic iqueryableperson people get set however ef will not populate the people property of my context even though idbset implements iqueryable the only solution i can come up with to this to write a facade over mydbcontext which exposes the functionality i want seems overkill and a lot of maintenance for a readonly datasethow do i achieve a clean d model while using entity frameworkediti am using entityframework v5,['c#'] +513171,slow page refresh times during development we have a reasonably large aspnet mvc app that i work on in visual studio 2012 on win 8 i have a strange issue with slow page load times after recompilation usually the actual build time is about 5 seconds then the browser opens up and it takes 12 minutes to load the page some pointsit loads slowly whether i change a view or recompile the project completelythis is not a performance issue everything else works really well there is enough ram etcit happens only with iis express when i switch to the default development server it works fineall the other devs in my team use iis express but they do not have this problem i tried to reinstall iis and to use v75 instead of v8 and recreated all config files no lucki tried to thisable all extensions obviously it did not affect load times toothere is nothing abnormal in task managerit is a virtual machine on my macbook pro but again a this is not a performance problemwhat else can i try,['asp.net'] +513195,how to implement voice search to searchview i want to add voice search function to my application i am populating a searchview in sherlockactivity but i cannot find a solution to add voice search function to searchview objectcan you please give an advice what do i need to docode below public class mainactivity extends sherlockactivity private slidingmenu slidingmenu private slidingmenu slidingmenuright private string mfilterarrays public long lastscrolltime0 en son kaydarma ne zaman yapalda override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main public boolean oncreateoptionsmenumenu menu create the search view searchview searchview new searchviewgetsupportactionbargetthemedcontext searchviewsetqueryhintsearch menuaddsearch seticonrdrawableic search inverse setactionviewsearchview setshowasactionmenuitemshow as action if room menuitemshow as action collapse action view return true mainfestactivity androidnamecompaeabcpmainactivity androidlabelstringapp name intentfilter action androidnamecompaeabcpmainactivity category androidnameandroidintentcategorydefault action androidnameandroidintentactionsearch intentfilteractivity,['android'] +513203,django thisplay imagefield i just start to use django and i have not found a lot of info on how to thisplay an imagefield so i made thismodelspy class carmodelsmodel name modelscharfieldmax length255 price modelsdecimalfieldmax digits5 decimal places2 photo modelsimagefieldupload tosite mediaviewspydef imagerequest carx car variables requestcontextrequest carxcarx return render to responseimagehtmlvariablesimagehtml extends basehtml block content img srccarx endblock i already save an image since terminal and i know is there also if a do this in imagehtml block content carx endblock the ouput is car objectcan anyone tell me where is my errorthanks a lot,['python'] +513374,adb not responding you can wait more or kill adbexe windows 8 when i try to test my android application with an android emulator as always i now suddenly get an error message i am working with windows 8 so far i tried the following things which unfortunately could not solve the problemreinstalling eclipse with android adtreinstalling javainstalling android studios first solved the problem but after one day mysteriously also here adb stopped working with the error message given in the title adb not responding furthermore i unsuccessfully tried out some advice from mr googlestopping adbexe via taskmanager and restarting eclipse android studiosadb killserver then startserver via command promptsetting the path to adbexe as an environment variableswitching off any antivirus or firewallstarting the ides as an administratorupdating the idesthe only thing i can remember doing which may have destroyed adb on my computer for all times i connected my motorola smartphone to my laptop and installed the motorola usb drivers but as i said the adb also would not work with the emulatorany help would be kindly appreciated the issue bothers me for more than an entire day now maybe someone had similar problems on windows 8,['android'] +513416,leaving android app with back button i want the users of my android app to leave my app when they press back at a certain activity can this be done,['android'] +513433,check entered value is number or not i have tried this snippet but it does not worktry integerparseintenteredidgettexttostring logienteredid value enterdid is numeric flag1 catch numberformatexception e flag1 logienteredid value enterdid is not numerictake care that it can accept either username or id to check the valuei do not want it to accept only numbers,['android'] +513454,pass template args by const or i have this example programinclude iostreamtemplatetypename message typename decoration typename printimplvoid print surroundedmessage msg const decoration decoration const printimpl print impl print impldecoration should forward be used print impl print implstdforwardmessagemsg print impl print impldecorationtemplatetypename message typename printimplvoid pretty printmessage msg const printimpl print impl print surroundedstdforwardmessagemsg print implint main pretty printso pretty const char msg stdcout msg i also posted it on coliruas you can see i use different ways to pass the argumentsmessage is passed as a universal reference because it eventually needs to be forwarded to the printimpl functiondecoration is passed as const ref here because its value is used twice and i am not sure if using forward twice would be safe it might be moved away by the first forwardprintimpl is passed as const reference because i do not see any reason to use forward however i am not certain if this is wise should i pass by if yes should i also use stdforwardam i making the right choices,['c++'] +513475,is there a way to determine if a email is a replyresponse using ews c i am writing a support system and this is my first time using ews thus far i have been quite successful with it i can extract the info i need send emaisl and everything is working great i do have one small headache is there a way to tell if an email is in fact a reply the basic idea of the app is someone sends an email we reply and give them a reference number this is done and working great now if they reply to this same address we need to log it a bit different in our database thus i need some magical way to tell if the email is a reply thus far i am stuck any suggestions will be greatly appreciated as i am new in the programming industry and thus far googling turned up nothing useful i include a section of code here finditemsresultsitem findresults servicefinditemswellknownfoldernameinbox view foreach item myitem in findresultsitemswherei i is emailmessage var mailitem myitem as emailmessage if mailitemisread load primary properties and get a text body type mailitemloadpropertyset update the item to isread in email mailitemisread true mailitemupdateconflictresolutionmodeautoresolve check if it is a reply and mark the msg as such add message to list supportemailmessage msg new supportemailmessage msgsubject mailitemsubject msgmessagebody mailitembodytext msgdatesent mailitemdatetimesent msgsender mailitemsenderaddress toreturnlistaddmsg,['c#'] +513524,newtonsoftjson custom datetime serialization i have a class with two datetime properties i need to serialize each of the properties with different format how can i do it i triedjsonconvertserializeobjectobj formattingnone new isodatetimeconverter datetimeformat mmddythis solution does not work for me because it applies date format to all the properties is there any way to serialize each datetime property with different format maybe there is some attribute,"['c#', '.net']" +513558,highcharts hide and show legend i would like to be able to toggle the visibility of the legend of a chart when the user clicks a buttoni have tried hiding the legend using the undocumented destroy method however when i try to rerender the legend and it is items the items appear in the top left of the chart instead of within the legend the items also do not seem to have any of their event handlers attached clicking on an item no longer toggles a seriesis there a better way to do this i have to support both svg and vml implementations so am looking for a solution that would address bothjsfiddle exampleupdatelegendonclick function e var enable chartoptionslegendenabled chartoptionslegendenabled enable if enable chartlegenddestroy hide legend else var allitems chartlegendallitems add legend items back to chart for var i 0 i allitemslength i var item allitemsi itemlegenditemadd itemlegendlineadd itemlegendsymboladd rerender the legend chartlegendrender,"['javascript', 'jquery']" +513563,ajax posting validateantiforgerytoken without form to mvc action method i have been looking at examples of how to do this on so and as far as i can tell i have tried all the examples i can find with no success so far i have tried altering some of the implementations to my scenario but this has thus far failed as welli have this on my page in layoutcshtml so i always have a token availableform id ajaxantiforgeryform action methodpost htmlantiforgerytokenformi also have this method in my javascript utils fileaddantiforgerytoken function data data requestverificationtoken ajaxantiforgeryform inputname requestverificationtokenval return datathis is all working as expected and i get an anti forgery token my actual posting code ismypagesavedata function var saveurl exercisespostdata var mydata jsonstringifymypagecontextsarrays ajax type post async false url saveurl data addantiforgerytoken myresults mydata success function alertsaved datatype json contenttype applicationjson charsetutf8 my action method looks like this httppost validateantiforgerytoken jsonexceptionfilter public jsonresult postdatalistresultsdc myresults return json apiclientsubmitresultsmyresults i have been testing this with the various implementations i have been trying and the response is alwayserrormessagethe required antiforgery form field requestverificationtoken is not presenti am not posting a form it is just an array of data but checking the data that actually gets posted the json does not look right it is all encoded but the requestverificationtoken parameter name is there and the token value is also presenti am pretty confused by all this at the moment and cannot find the correct way to send the token so that my mvc action is invoked if i remove the validateantiforgerytoken attribute and have jsonstringifymypagecontextsarrays as the data the json looks correct unencoded and it maps finehow do i get this token posted properly without a form,['jquery'] +513624,is activerecords order method vulnerable to sql injection i know it is not safe to use interpolated strings when calling whereeg thisclientwhereorders count paramsordersshould be rewritten asclientwhereorders count paramsordersis it safe to use interpolated strings when calling order if not how should the following be rewrittenclientordersome value 1 some value 2,['sql'] +513642,spring mvc patch method partial updates i have a project where i am using spring mvc jackson to build a rest service let us say i have the following java entitypublic class myentity private integer id private boolean aboolean private string averybigstring getter setterssometimes i just want to update the boolean value and i do not think that sending the whole object with its big string is a good idea just to update a simple boolean so i have considered using the patch http method to only send the fields that need to be updated so i declare the following method in my controllerrequestmappingmethod requestmethodpatchpublic void patchrequestbody myvariable myvariable calling a service to update the entitythe problem is how do i know which fields need to be updated for instance if the client just wants to update the boolean i will get an object with an empty averybigstring how am i supposed to know that the user just wants to update the boolean but does not want to empty the string i have solved the problem by building custom urls for instance the following url post myentities1abooleantrue will be mapped to a method that allows to only update the boolean the problem with this solution is that it is not rest compliant i do not want to be 100 rest compliant but i do not feel comfortable with providing a custom url to update each field especially given that it causes problems when i want to update several fieldsanother solution would be to split myentity into multiple resources and just update these resources but i feel like it does not make sense myentity is a plain resource it is not composed of other resourcesso is there an elegant way of solving this problem,['java'] +513683,push view controller black screen i am pushing to a new view controller and passing some data to it when i run the application i can press the button and push to a new view but the screen is completely black any help is appreciated ibactionbuttonidsender nsstring firstfield selffieldtext nsstring secondfield selffield2text selfresultsarray nsarray alloc initwithobjectsfirstfield secondfield nil nsuinteger randomresult arc4random uniformselfresultsarraycount selflabeltext selfresultsarray objectatindexrandomresult imagesviewcontroller ivc imagesviewcontroller alloc init ivclabel selflabeltext selfnavigationcontroller pushviewcontrollerivc animatedyes,['ios'] +513903,numpy vector n1 dimension n dimension conversion i have a question regarding the conversion between n dimension arrays and n1 dimension arrays for example y is 2 dimensionanparray1234xnparray12ynpdotaxyshapeout6 2but the following will show y2 to be 21 dimension x2xnpnewaxisy2npdotax2y2shapeout14 2 1what would be the most efficient way of converting y2 back to y without copyingthankstom,['python'] +513949,stringjoin cannot convert from ienumerable to string very simple extension method not compilingpublic static string jointhis string text params string stringstojoin return stringjoin stringstojoinwheres stringisnulloremptysi get cannot convert from systemcollectionsgenericienumerable to stringwhat am i missing,"['c#', '.net']" +513969,vector does not clear memory after out of scope i have encountered the following problem and i am not really sure whether i am wrong or its a really weird bug i fill a huge array of strings and want it to be cleared at a certain point heres a minimal exampleinclude stringinclude vectorinclude unistdh sleepinclude iostreamint main stdvectorstdstring strvec forlong i 0 i 10 i stdstring out this is gonna be a long string just to fill up the memory used by this fucking pthreadn strvecpush backout stdcout finished loading 1stn sleep10 to monitor any changes stdcout out of scopen sleep10 return 0my problem is if i monitor memory usage with top the memory usage decreases just by a very small amount i think its probably the vector overhead but the most seems not freed how comes i tested the same scenario with long long but here everything went rightthe stdvector reference states that if the contained values are no pointers the destructors are invoked seems not true for string thoughi appreciate every answerfor convenience i am using debian linux 64bit with g 472edit thanks for the answers so farby now i have profiled heap usage with vagrind massif and yeah actually as expected it gets properly freed at the point it should but why do i in fact see a change in usage with a huge integer but not with the strings also whithin topi need to be a little considerable about that because i need to be able to free my memory at certain times for a multithreaded server application which will probably run several weeks or more without being restarted when do i actually know when the c memory manager decides to give some mem back to the os,['c++'] +514025,flask url for with multiple parameters the problemi have an a input button in a form that when its submitted should redirect two parameters search val and i to a more results function listed below but i get a type error when wsgi builds the error is typeerror more results takes exactly 2 arguments 1 givenhtml form action url formore results past valsearch val indi methodpost input idnext hutch typesubmit valueget the next hunch nameaction formflask functionapprouteresultsmore past val hunches methodspostdef more resultspast val ind if requestformaction get the next hunch ind 1 queried resturants hffind lunchpast val method to generate a list queried resturants queried resturantsind return render template show entrieshtml queried resturantsqueried resturants search valpast val iind any idea on how to get past the build error what i have triedcreating link to an url of flask app in jinja2 templatefor using multiple paramters with url forbuild error with variables and url for in flasksimilar build errosas side note the purpose of the function is to iterate through a list when someone hits a next page button i am passing the variable i so i can have a reference to keep incrementing through the list is there a flask jinja 2 method that would work better i have looked into the cycling list feature but it does not seem to able to be used to render a page and then rerender it with cycling listnext,"['python', 'html']" +514035,what is the exact order of execution for try catch and finally in this java code import javaioioexceptionpublic class copy public static void mainstring args if argslength 2 systemerrprintlnusage java copy srcfile dstfile return int filehandlesrc 0 int filehandledst 1 try filehandlesrc openargs0 filehandledst createargs1 copyfilehandlesrc filehandledst catch ioexception ioe systemerrprintlnio error ioegetmessage return finally closefilehandlesrc closefilehandledst static int openstring filename return 1 assume that filename is mapped to integer static int createstring filename return 2 assume that filename is mapped to integer static void closeint filehandle systemoutprintlnclosing file filehandle static void copyint filehandlesrc int filehandledst throws ioexception systemoutprintlncopying file filehandlesrc to file filehandledst if mathrandom 05 throw new ioexceptionunable to copy file systemoutprintlnafter exception the output that i expect is copying file 1 to file 2io error unable to copy fileclosing file 1closing file 2however sometimes i get this expected output and at other times i get the following output copying file 1 to file 2closing file 1closing file 2io error unable to copy file and sometimes even this output io error unable to copy filecopying file 1 to file 2closing file 1closing file 2and whether i get the first second or third output seems to happen randomly during every execution i found this post that apparently talks about the same problem but i still do not understand why i sometimes get output 1 2 or 3 if i understand this code correctly then output 1 should be what i get every time the exception occurs how do i ensure that i get output 1 consistently or be able to tell when i will be getting output 1 or when i will be getting output 2 or 3,['java'] +514039,python how to parse the body from a raw email given that raw email does not have a body tag or anything it seems easy to get the fromtosubjectetc viaimport emailb emailmessage from stringab bfromc btoassuming that a is the rawemail string which looks something like thisa from thu jul 25 192859 2013received from a1localtld localhost 127001 by a1localtld 81448144 with esmtp id r6q2sxeq003866 for thu 25 jul 2013 192859 0700received from rootlocalhost by a1localtld 81448144submit id r6q2sxbh003865 thu 25 jul 2013 192859 0700from subject oto cc xoriginatingip 19216815127xmailer webmin 1420messageid 13748057393861a1date thu 25 jul 2013 192859 0700 pdtmimeversion 10contenttype multipartmixed boundarybound1374805739this is a multipart message in mime formatbound1374805739contenttype textplaincontenttransferencoding 7bitobound1374805739the questionhow do you get the body of this email via python so far this is the only code i am aware of but i have yet to test itif emailis multipart for part in emailget payload print partget payloadelse print emailget payloadis this the correct way or maybe there is something simpler such asimport emailb emailmessage from stringab bbody,['python'] +514046,how to make cross domain request as you know the security of the web browser thisallows the making of cross domain requests i read a book which says that you should use xmlhttprequest only if you can put the files on the server means put the page you will load to the same requested domain if you cannot you should search for an alternativemy questions arewhat is the cross domain alternative to xmlhttprequestwhat about websockets does this technology allow cross domain requesteditit still is not clear to mefor example i pull my page from wdomain1com and i need to request javascript from wdomain2com so the pulled page should include something likescript srcwdomain2comscriptjsscriptto avoid cross domain restrictionsand i can use jsonp and request will look likebut is not it the same i just pull js from the another domain do it avoid cross domain restrictions,['javascript'] +514076,combine ibeacon bluetooth low energy with android 43 i am looking for a way to detect ibeacon ios 70 feature from an android device i read the android documentation where it seem that the ibeacon is some kind of gatt server which sends its position while the android documentation says that i should not poll that data but for the detection this would be nessesaryi google a lot but this topic is quite new i even created a new tag ibeacon so i would be happy if i get some links to ressources from the ios world which descripes the implementation also if there are some android libs which i did not find yet would be nice,['android'] +514190,how do draw italic text on android canvas in my app i am drawing text on android canvasnow to support underline and bold i am taking help of paint object paint paint new paint paintsetunderlinetexttrue paintsetfakeboldtexttrue paintsetcolorcolor paintsettextsize font size canvas objdrawtexttextxypaintwith this code i am getting bold and underlined texti also like to make it italici am developing app for android 22 onwardshow to do it editi am setting typeface object created with an external font file to support external font for italic i am using following codepaintsettypefacetypefacecreateexternal font type facetypefaceitalicthis also not workingtested on samsung galaxy ace android 22,['android'] +514219,understanding attachthreadinput detaching lose focus i got a little problem fully understanding attachthreadinputi know it is connecting the message queue of 2 threads which what i want to do allows me for example to force my window winforms in foregroundwhich i can do with this methodprivate void setforegroundwindowexintptr hwnd uint sw show 5 uint appthread getcurrentthreadid uint foregroundthread getwindowthreadprocessidgetforegroundwindow intptrzero if foregroundthread appthread attachthreadinputforegroundthread appthread true bringwindowtotophwnd showwindowhwnd sw show attachthreadinputforegroundthread appthread false else bringwindowtotophwnd showwindowhwnd sw show however both of the windows lose focus as soon as the threads detachif i wait for the message queue to empty applicationdoevents and activate my window which is now in foreground but not focused it will regain the focus and keep itif i do it before the message queue is empty it will lose focus againso i would guess something of the detaching takes the focus from my windows but i have no idea what that is or how to prevent itthis is the first thing i do not quite understandthe second thing i do not get is if i do not set my window to foregroundattachthreadinputforegroundthread appthread trueattachthreadinputforegroundthread appthread falseapplicationdoeventsthisactivatewait for the message queue to empty and activate my window this time it is not in foreground and the other window still has the focus it actually gets activated even though the threads are not attached anymoreperhaps someone with a better understanding of attachthreadinput can answer me these 2 questionsinfoi need to steal the focus in this case because my app gets called via an api the other app that calls mine waits for feedback from my app and in most times freezes until it gets the infoin case the other app is fullscreen many user do not notice the blinking in the taskbar and think the other app crashed and kill it with the taskmamanger since i do not necessarily have control over the other app i cannot tell it to set the focus to my windowthis method would not get called if it is not absolutelly necessary in this case this behavior which is hostile i know that is as well wanted by myself as by the user,['c#'] +514324,is multiplication faster than float division in cc you can set up the following codedouble a b cc a b 2this does the exact same thing asc a b 05i am wondering which is better to use is one operation fundamentally faster than the other,"['c++', 'c']" +514365,apply css to popover in bootstrap i want to apply custom css to the title and content of a popover in bootstrap however it seems that my css is being ignoredfor example div classpopdiv a idpoplink hrefjavascriptvoid0popa div classpoptitletitle herediv div classpopcontentcontent heredivdivhtml body width 100 height 100popdiv fontsize 13px margintop 100pxpoptitle thisplay none color blue fontsize 15pxpopcontent thisplay none color red fontsize 10pxpoplinkpopover html true placement right trigger hover title function return poptitlehtml content function return popcontenthtml how can i apply specific css to the title and the content respectively,"['html', 'css']" +514374,passing reference to stl vector over dll boundary i have a nice library for managing files that needs to return specific lists of strings since the only code i am ever going to use it with is going to be c and java but that is using c through jni i decided to use vector from the standard libraries the library functions look a little bit like this where file manager export is platformdefined export requirementextern c file manager export void get all filesvectorstring files filesclear for vectorfile structiterator i file structsbegin i file structsend i filespush backifull path the reason i used the vector as a reference instead of return value is an attempt to keep memory allocations sane and because windows was really unhappy me having extern c around a c return type who knows why my understanding is that all extern c does is prevent name mangling in the compiler anyway the code for using this with other c is generally as followsif defined win32 include windowsh define get method getprocaddress define open libraryx loadlibrarylpcstrx define library pointer type hmodule define close library freelibraryelse include dlfcnh define get method dlsym define open libraryx dlopenx rtld now define library pointer type void define close library dlcloseendiftypedef void getallfilestypevectorstring filesint mainint argc char argv library pointer type manager load librarylibrarydll just an example actual name is platformdefined too getallfilestype get all files pointer getallfilestype get methodmanager get all files vectorstring files get all files pointerfiles do something with files return 0the library is compiled through cmake using add libraryfile manager shared file managercpp the program is compiled in a separate cmake project using add executablefile manager command wrapper command wrappercpp there are no compile flags specified for either just those commandsnow the program works perfectly fine in both mac and linux the problem is windows when run i get this errordebug assertion failedexpression pfirstblock pheadthis i have found out and kind of understand is because of separate memory heaps between executables and loaded dlls i believe this occurs when memory is allocated in one heap and deallocated in the other the problem is for the life of me i cannot figure what is going wrong the memory is allocated in the executable and passed as a reference to the dll function values are added via the reference and then those are processed and finally deallocated back in the executablei would reveal more code if i could but intellectual property at my company states i cannot so all of the above code is merely examplesanyone with more knowledge of the subject able to help me understand this error and point me in the right direction to debug and fix it i am unfortunately not able to use a windows machine for debugging since i develop on linux then commit any changes to a gerrit server which triggers builds and tests through jenkins i have access to the output console upon compile and testi did consider using nonstl types copying the vector in c to a char but the memory allocation was a nightmare and i was struggling to get it working nicely on linux let alone windows and it is horrible multiple heapsedit it definitely crashes as soon as the files vector goes out of scope my current thought is that the strings put into the vector are allocated on the dll heap and deallocated on the executable heap if this is the case can anyone enlighten me as to a better solution,['c++'] +514403,instance methods and threadsafety of instance variables i would like to known if each instance of a class has its own copy of the methods in that classlets say i have following class myclasspublic myclass private string s1 private string s2 private string method1string s1 private string method2string s2 so if two differents users make an instance of myclass likemyclass instanceofuser1 new myclassmyclass instanceofuser2 new myclassdoes know each user have in his thread a copy of the methods of myclass if yes the instance variables are then threadsafe as long as only the instance methods manipulate them righti am asking this question because i often read that instance variables are not threadsafe and i can not see why it should be like that when each user gets an instance by calling the new operator,['java'] +514436,python numpy and memory efficiency pass by reference vs value i have recently been using python more and more in place of cc because of it cuts my coding time by a factor of a few at the same time when i am processing large amounts of data the speed at which my python programs run starts to become a lot slower than in c i am wondering if this is due to me using large objectsarrays inefficiently is there any comprehensive guide just to how memory is handled by numpypython when things are passed by reference and when by value when things are copied and when not what types are mutable and which are not,['python'] +514443,setting cell formats with xlwt format strings i have looked around for several different xlwt formats for cells but i cannot find a comprehensive listexcel provides the following options for cell content formattinggeneral number currency accounting date time percentage fraction scientific text special customobviously custom is not what i want but what are the formatting strings for all these different options for example i have seendate format xfstyledate formatnum format str ddmmycurrency format xfstylecurrency formatnum format str 0is there somewhere i can get a comprehensive list of those formatting strings the documentation on does not have much and the tutorial at the bottom only seems to have dates,['python'] +514451,null checks in nested objects i have several plain old c objects that are returned by an api and have several layers of pocos nested within them i need to access fields contained deep within these structures but because the api leaves these nested objects as null when data is missing i find myself having to do lots of null checks just to get at the field i really wantifobj null objinner null objinnerinnerer null the shortest form i have come up with is using the ternary operatorobj null objinner null objinnerinnerer null objinnerinnererfield nulldoes c have any way to do this without having to write out all those comparisons i would really like something short and simple likeobjinnerinnererfield nullbut that only checks field for null,['c#'] +514453,where can i find a list of icon images for the dojo toolkit dijit widgets simple question i guess but despite some googling i am no closer to finding an answer does anyone know where to find a list of the icons available in the dojo toolkit,"['javascript', 'css']" +514458,how were livicons made i am wondering if any one can give me a basic break down on how these icons were made i see they are svg and animated with raphael js but is each icon drawn on the canvas or are the icons actual svg file that are just each animated independently with raphaeljsi have an icon i want to use of my own and see if i can animate it my own way similar to those icons does any one have a idea or tutorial regarding this technique i have been reading through raphael js but it looks like it is mainly for drawing a svg and then animating it so i am not 100i have been trying to read through the inspector as well but i cannot really understand what each animation is doing how does it know which part of the icon to manipulate etcthanks anyone,['javascript'] +514482,delegates vs action func in c this might seem a silly question but it is just for curiositys sakewe have two particular alreadydefined delegates in cactiontfunct tresultaction encapsulates any void method that takes 0 or more parametersfunc encapsulates any method that returns a specific value type and takes 0 or more parametersmy question is in which cases it is recommended to define a custom delegatewhy would you need to do thatthanks in advance,['c#'] +514511,will a static block execute without main method today i attended a java quiz and there was a question likethe static block even executed without main method in application program 1 true 2 falsei have answered the question as 2 false but after checking my result i was puzzled out because it was the wrong answer as per the quiz now i have rechecked my answer with my own sample code and it does not execute anything nor show any errors heres my sample codepublic class staticblockdemo static systemoutprintlnhello world which one is the right answer i am using java 7,['java'] +514520,inconsistent events fired on textarea in safari on ios i have run into an infuriating bug on safari for ipad that i cannot fixarchitecturebackbone 099jquery 172jquery mobile 131user agentios 511 ipadsafari 51 mobilefull user agent string mozilla50 ipad cup os 5 1 1 like mac os x applewebkit53446 khtml like gecko version51 mobile9b206 safari7534483i have a 10 instances of the same view each of which has a nested view that contains a textarea element for some reason when you tap the textarea it randomly does not focus i have read that safari mobile is wonky when you attempt to trigger focus events that do not come from a tapclick event but this is a direct tap and it still does not focus reliably heres the strippeddown code for the viewsvar parentview backboneviewextend render function thiselhtmldiv classtextareacontainerdiv thistextareaview new textareaview el thiselfindtextareacontainer thistextareaviewrender var textareaview backboneviewextend events tap mytextarea handletextareatap render function thiselhtmltextarea rows4 cols80 classmytextareatextarea handletextareatap functionevent consolelogtapped var i 0while i 10 var view new parentview viewrender bodyappendviewel ithe tap event handler fires 100 of the time the console correctly thisplays tapped each time but most of the time the user agent fails focus in the textarea i added the following line into the textareaview to see exactly which events safari is firing and in what ordervar textareaview backboneviewextend render function thiselhtmltextarea rows4 cols80 classmytextareatextarea thiselfindmytextareaonblur change click contextmenu copy cut dblclick focus focusin focusout hashchange keydown keypress keyup load mousedown mouseenter mouseleave mousemove mouseout mouseover mouseup mousewheel paste reset scroll select submit textinput unload wheel tap touch scrollstart scrollstop swipe swipeleft swiperight vclick vmousecancel vmousedown vmousemove vmouseout vmouseover vmouseup touchstart touchend touchmove touchcancel functionevent consolelogeventtype heres the event order i get when the textarea focuses correctly touchstart vmouseover vmousedown touchend vmouseup vclick tap vmouseout mousemove mousedown focusin focus mouseup click focusout blurheres the event order i get when the textarea fails to focus touchstart vmouseover vmousedown touchend vmouseup vclick tap vmouseout mousemovefor some reason the events after mousemove fail to fire i have tried manually triggering these events as well but the textarea element still does not focus nor does the keyboard pop up egvar textareaview backboneviewextend handletextareatap functionevent this still does not work thiselfindmytextareatriggerfocus neither does waiting for the synthesized webkit events to fire var this this settimeoutfunction thiselfindmytextareatriggerfocus 10 i have poured over apples event handler documentation to no avail and i cannot find any bug reports relating to this in any of the repos on githubtwo other weird behaviors that i do not understandthe first instance of the textarea always works correctlythe textarea focuses despite a blur event being calledany insight would be appreciatedcheers,['jquery'] +514543,mysql inner join update i am trying to perform a relational update using an innjer join and cannot seem to get the syntax correctthe rows are as followscataloguecategory idcataloguevisiblecategoriescategory idcategoriescategory namei am trying to update the value of the visible field when the category id numbers match and correspond the the correct nameupdate catalogue set visible 0 from catalogue inner join categories on cataloguecategory id categoriescategory id and categoriescategory name basesapologies if it comes down to a stupid syntax mistake i am not the most experienced with relational databases,"['php', 'sql']" +514680,how to fill a image with pattern let us say i have a image now i want to fill that image with and my final image should look like thishow to do itso far i was able to change the color of that image but was not able to fill patterncan i do it with html5 canvas pattern is there any way to do it with php or any web platform,"['php', 'jquery']" +514707,locationclient getlastlocation returning null i am new to android programming and wanted to start by creating a very basic app that thisplays the latitude and longitude of the current location on screeni am developing for my samsung galaxy s3 and read that you need to kickstart the phone to return the gps i have tried doing this in the onconnected method with the requestlocationupdates method call on the locationmanager however i find that the locationclient is still returning a null locationcan anyone tell me what i am doing wrongheres my mainactivity import androidcontentcontextimport androidlocationlocationimport androidlocationlocationlistenerimport androidlocationlocationmanagerimport androidosbundleimport androidsupportv4appfragmentactivityimport androidviewmenuimport androidwidgettextviewimport androidwidgettoastimport comgoogleandroidgmscommonconnectionresultimport comgoogleandroidgmscommongoogleplayservicesclientimport comgoogleandroidgmslocationlocationclientpublic class mainactivity extends fragmentactivity implements googleplayservicesclientconnectioncallbacks googleplayservicesclientonconnectionfailedlistener private locationclient mlocationclient private location mcurrentlocation override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main mlocationclient new locationclientthis this this override protected void onstart superonstart mlocationclientconnect override protected void onstop mlocationclientthisconnect superonstop override public boolean oncreateoptionsmenumenu menu inflate the menu this adds items to the action bar if it is present getmenuinflaterinflatermenumain menu return true override public void onconnectionfailedconnectionresult arg0 todo autogenerated method stub override public void onconnectedbundle arg0 toastmaketextthis connected toastlength shortshow locationmanager manager locationmanager this getsystemservicecontextlocation service managerrequestlocationupdateslocationmanagernetwork provider 0 0 new locationlistener override public void onstatuschangedstring provider int status bundle extras override public void onproviderenabledstring provider override public void onproviderthisabledstring provider override public void onlocationchangedfinal location location mcurrentlocation mlocationclientgetlastlocation textview lattextview textview findviewbyidridlatitude text lattextviewsettextdoubletostringmcurrentlocationgetlatitude textview longtextview textview findviewbyidridlongitude text longtextviewsettextdoubletostringmcurrentlocationgetlongitude override public void onthisconnected toastmaketextthis thisconnected please reconnect toastlength shortshow my android manifest looks like this usessdk androidminsdkversion8 androidtargetsdkversion17 usespermission androidnameandroidpermissionaccess coarse location usespermission androidnameandroidpermissionaccess fine location usespermission androidnameandroidpermissioninternet usespermission androidnamecomgoogleandroidprovidersgsfpermissionread gservices application androidallowbackuptrue androidicondrawableic launcher androidlabelstringapp name androidthemestyleapptheme activity androidnamecomexamplewilligetwetmainactivity androidlabelstringapp name intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity applicationmanifestwhen running the debugger i find that mcurrentlocation is null after the call to mlocationclientgetlastlocationi would be very grateful for any help,"['java', 'android']" +514743,searching list c by containing letters i have a liststring with some words i want to get all of elements witch contains letters in this schemaa00b0c0d 0 is random char abcd are constantly chars in stringhow can i do this can i do this only with regex there is not any other solution,"['c#', '.net']" +514768,no mapping found for http request with uri spring mvc heres my webxml thispatcherservlet orgspringframeworkwebservletthispatcherservlet contextconfiglocation webinfspringservletcontextxml 1 servletmapping servletnamethispatcherservletservletname urlpatternurlpatternservletmappinglistener listenerclass orgspringframeworkwebcontextcontextloaderlistener listenerclasslistenermy servletcontextxml bean classorgspringframeworkwebservletviewinternalresourceviewresolver property nameprefix valuewebinfviewsvalue property property namesuffix valuejspvalue property beanand lastly the handler class which is under comspringexamplecontrollerimplcontrollerpublic class indexcontrollerimpl implements indexcontroller requestmapping public string index return index however on going to localhost8080projectname it returns a 404 error jul 27 2013 81831 pm orgspringframeworkwebservletthispatcherservlet nohandlerfoundwarning no mapping found for http request with uri tasklistwebinfviewsindexjsp in thispatcherservlet with name thispatcherservletjul 27 2013 81837 pm orgspringframeworkwebservletthispatcherservlet nohandlerfoundwarning no mapping found for http request with uri tasklistindex in thispatcherservlet with name here is my project structure,['java'] +514777,example of c memory barrier i was reading the answer to this question regarding the volatile keywordthe person saysthe solution to preventing reordering is to use a memory barrier which indicates both to the compiler and the cpu that no memory access may be reordered across this point placing such barriers around our volatile variable access ensures that even nonvolatile accesses would not be reordered across the volatile one allowing us to write threadsafe codehowever memory barriers also ensure that all pending readswrites are executed when the barrier is reached so it effectively gives us everything we need by itself making volatile unnecessary we can just remove the volatile qualifier entirelyhow is this memory barrier implemented in ceditcould someone give a simple code example please,['c++'] +514868,what is the main use of the python builtin compile when looking through the list of python builtin functions i struggle with understanding the usefulness the method compile all of the examples i could find point to a simple hello world it make sense what it does but not when to use itis this the same method python uses to generate the pyc files can this be used to remove some of the dynamic nature of python to improve performance on certain blocks of code knowing full well that a module in c is the way to go precompiled modules,['python'] +514911,using css when converting markdown to pdf with pandoc i am trying out pandoc on os x and results thus far are impressive one blocking problem however is getting css styles to work on inline code samples i am converting from markdown to pdfi have this string in my source create a simple html document span classfilenamesimplehtmlspan and load it into the browser via the file systemi have also tried this create a simple html document simplehtmlfilename and load it into the browser via the file systemi would like to apply the class filename to the enclosed text in each case but it does not seem to do anything to the output however the manual sayssome output formats can use this information to do syntax highlighting currently the only output formats that uses this information are html and latexheres my commandpandoc output outputpdf css sourcestylescss sourceendocsinputmdi am converting to pdf which is written by latex by pandoc internally can i get this to work or can i use a style defined using a latex command it does not have to be css however it must be a style system it is not workable to change italicfontcolour attributes on each occasioni have tried sending output temporarily to html and in that situation the styles are imported directly from the specific style asset so my stylesheet specification and span markup is correct at least for one output formataddendaa couple of afterthoughtsthe solution does not have to be pandoc or markdown however it does need to be a trivial textbased markup language that can convert reliably to pdf as i want to store the document files on git for easy forking and merging i am not keen an html as it is verbose and engines to convert it are not that great though admittedly my formatting requirements are modestthe html output from pandoc is fine so if i can find something that converts the simple htmlcss to pdf reliably i will be fine of course pandoc should be able to do this but inline styles for the background colour on code fragments are not rendered this might be a faff as i will have to reintroduce things like pagebreaks which can be nontrivial in htmltopdf converters,['css'] +515009,mallet how to implement crf based edit thistance i am looking for somebody who writeknow mallet classes in details i know that it is a great tool for ml problems and now i try to implement crf based thistance algorithm described here andrew mccallum kedar bellare and fernando pereirathe authors told that they have realized the proposed model as mallet fst class it is sadly that java is not language that well known for me as ruby thats why i have some problems to understand how to use their model eg which classes i stuck with lack of documentation in huge mallet classes structureit will be nice to hear some guiding information how to implement the algorithm with mallet,['java'] +515084,android navigation drawer calling activities with abstractmainactivity i want to have a abstractmainactivity which creates the navigation drawer in there i should also handle the clicks on the menu items and then call new activities in those activities i want to again use the same navigation draweri would extend in the subclasses with the abstractmainactivity and call the getlayoutresourceid differently from each subclass as suggested here android how to create my own activity and extend it the problem is that now in the abstractmainactivity where i want to build the navigation drawer i do not have any access to the navigation drawer layout xml element as i of course want to have a different base layout for the subclasseswould i need to include layout in all the subclasses layout files but this does not work what do i do wrong if i want to use activities instead of fragments with the navigation drawerpublic abstract class mainactivity extends activity private string menuitemsprivate drawerlayout mdrawerlayoutprivate listview mdrawerlistoverridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main setcontentviewgetlayoutresourceid menuitems getresourcesgetstringarrayrarraymenu items mdrawerlayout drawerlayout findviewbyidriddrawer layout mdrawerlist listview findviewbyidridleft drawer set the adapter for the list view mdrawerlistsetadapternew arrayadapterstringthis androidrlayoutsimple list item 1 menuitems set the lists click listener mdrawerlistsetonitemclicklistenernew draweritemclicklistenerprotected abstract int getlayoutresourceidoverridepublic boolean oncreateoptionsmenumenu menu inflate the menu this adds items to the action bar if it is present getmenuinflaterinflatermenumain menu return trueprivate class draweritemclicklistener implements listviewonitemclicklistener override public void onitemclickadapterview parent view view int position long id selectitemposition swaps fragments in the main content view private void selectitemint position fragment fragment new planetfragment bundle args new bundle argsputintplanetfragmentarg planet number position intent intent new intentmainactivitythis productlistactivityclass startactivityintent public class productlistactivity extends mainactivity overridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestateoverridepublic boolean oncreateoptionsmenumenu menu inflate the menu this adds items to the action bar if it is present getmenuinflaterinflatermenuoptions menu menu return trueoverrideprotected int getlayoutresourceid todo autogenerated method stub return rlayoutactivity product listthis is the layout of the product list subclass activity product listxmlrelativelayout xmlnsandroidxmlnstoolsandroidlayout widthmatch parentandroidlayout heightmatch parentandroidpaddingbottomdimenactivity vertical marginandroidpaddingleftdimenactivity horizontal marginandroidpaddingrightdimenactivity horizontal marginandroidpaddingtopdimenactivity vertical margintoolscontextproductlist include layoutlayoutactivity mainlistview androidididlistview1 androidlayout widthmatch parent androidlayout heightwrap content androidlayout centerhorizontaltrue androidlayout centerverticaltrue listviewthis is the layout of the navigation drawer activity mainxmlandroidsupportv4widgetdrawerlayout xmlnsandroidxmlnsandroid1androidididdrawer layoutandroidlayout width300dpandroidlayout height500dp the main content view framelayout androidididcontent frame androidlayout widthmatch parent androidlayout heightmatch parent the navigation drawer listview androidididleft drawer androidlayout width240dp androidlayout heightmatch parent androidlayout gravitystart androidchoicemodesinglechoice androiddividerandroidcolortransparent androiddividerheight0dp androidbackgroundc3c3c3but the does not work but if i do not have it i get nullpointer exceptions when my subclass calls the oncreate of the abstract class where i want to build the navigation drawer it does not find the layoutelements to set the lists and layout ridleft drawer or riddrawer layout,['android'] +515207,selenium with python how to modify an element css style i am trying to change css style of an element example from visibility hidden to visibility visible using selenium execute script any other method through seleniumpython would be accepted gracefullymy codedriver webdriverfirefoxdrivergetelem driverfind element by idcopy linkelemexecute script area of my problem what do i need to do in order to play with the css of the webpage,['python'] +515212,screen support multiple devices using layoutlargelayoutnormal and layoutxlarge folders i created layoutlarge layoutnormal and layoutxlarge in the res folder and i copied all the xml files to those layout folders first i want to ask what is the difference between layout the default and layoutnormal folderi know if i run the application on big screen size the app will take the xml files from layoutxlargeso i made all the elements in layoutxlarge look as i want using framelayout in tap2 101 but when i run it in note2 or s3 mobile it looks different because the screen size is not sameso how can i make the the application run in tap2 101 1280 x 800 and note2 or s3 mobile 1280 x 720 size,['android'] +515223,byte and char conversion in java if i convert a character to byte and then back to char that character mysteriously thisappears and becomes something else how is this possiblethis is the codechar a a line 1 byte b bytea line 2 char c charb line 3systemoutprintlncharc intcuntil line 2 everything is finein line 1 i could print a in the console and it would show ain line 2 i could print b in the console and it would show 56 that is 200 because byte is signed and 200 is a so it is still finebut whats wrong in line 3 c becomes something else and the program prints 65480 that is something completely differentwhat i should write in line 3 in order to get the correct result,['java'] +515247,fitting data using univariatespline in scipy python i have a experimental data to which i am trying to fit a curve using univariatespline function in scipy the data looks like x y13 240407012 158813411 176011210 177136009 186008708 195578907 191040806 165591105 177895204 262471903 169809902 302260701 3303135 here is what i am doingimport matplotlibpyplot as pltfrom scipy import interpolateyinterp interpolateunivariatesplinex y s 5e8x pltplotx y bo label originalpltplotx yinterp r label interpolatedpltshowthat is how it looks i was wondering if anyone has thought on other curve fitting options which scipy might have i am relatively new to scipy thanks,['python'] +515267,is groovy a potential development language for android i have recently started using groovy as an alternative to java and i would like to develop android apps in groovy all the examples i have investigated seem to be quite oldso i was wondering if it is possible to develop android apps in groovy,['android'] +515289,when should stdatomic compare exchange strong be used there are two atomic cas operations in c11 atomic compare exchange weak and atomic compare exchange strongaccording to cppreferencethe weak forms of the functions are allowed to fail spuriously that is act as if obj expected even if they are equal when a compareandexchange is in a loop the weak version will yield better performance on some platforms when a weak compareandexchange would require a loop and a strong one would not the strong one is preferablethe following is an example for using the weak version i thinkdo expected currentvalue desired fexpected while currentatomic compare exchange weakexpected desiredcould someone give an example where the compareandexchange is not in a loop so that the strong version is preferable,['c++'] +515332,binding a wpf datagrid to a datatable i am not good at english because i am not a native speaker i apologize if i have made mistakes in the language i am new in c and wpf and i am trying to bind a wpf datagrid to a datatable in twoway now when i edit the values in the datagrid data in the datatable change correctly when i try to fill the datatable with the following codeoledbdataadapter adapter new oledbdataadaptera query a connectionadapterfilldatatablethe code works and the datagrid seems all right but when i try thisdatatablerows01 some objectthe thisplay value does not change i try to check the values in the datagrid in the following waymessageboxshowsomedatagriditems0 as datarowviewrow1tostringand it turns out no problem i am wondering why the thisplay values are like thisheres my datagridcellstyle in xamldatagridcellstyle style targettypedatagridcell setter propertytemplate settervalue controltemplate targettypedatagridcell grid horizontalalignmentstretch verticalalignmentstretch backgroundtemplatebinding background datagriddetailspresenter horizontalalignmentstretch verticalalignmentcenter contenttemplatebinding content grid controltemplate settervalue setter styletriggers triggers styletriggers styledatagridcellstylei have been stuck on this problem for several days thanks for any help,['c#'] +515336,is there a list of all ascii characters in pythons standard library is there a field or a function that would return all ascii characters in pythons standard library,['python'] +515370,ios developer program certificate transfer i have some problems with my developer certificate and profile i have certificate of developer program on my office mac i want to develop and test the app on my device at home so i have added my device and generated provision profile from office mac download and install cer and provision on my home mac but i saw the errorthe identity iphone developer does not match any valid nonexpired certificateprivate key pair in your keychainshow to transfer keys from office mac to my home mac,['ios'] +515400,how specify two css classes from property and conditional class i know that in knockout has the ability to specify class from observable property like thisdiv databindcss color knockout also provides the ability to specify conditional class rendering like thisdiv databindcss myclass somebooleanproperty but which markup should be specified if i need those features of knockout css binding togetheri tried this but with no luckdiv databindcss color myclass somebooleanproperty i have got the errorerror unable to parse bindings syntaxerror unexpected token i not found any example in google or in official docsupdatei found a workaround build up style string in code and put it to property like thisitemadditionalcsscolor resultissortable myclass nulland specify this class in htmldatabindcss additionalcss but i little bit puzzled i think it is dirty approach i think it would be better to achieve the same result in markup how can accomplish that with markup,['css'] +515421,cannot execute script insufficient memory to continue the execution of the program i have a 123mb sql file which i need to execute in my local pc but i am getting cannot execute script insufficient memory to continue the execution of the programhow to solve this issue,['sql'] +515434,how to thisable the particular list item in listview in android how to thisable the particular list item in listview in androidi mean if once i selected any one of item from a listviewthat item suppose to be thisabled which means that item should not be selectable againhow to do thissuggestions please thanks for your precious time,['android'] +515488,how to query multiindex index columns values in pandas code examplein 171 a nparray11 11 33 33 55 66in 172 b nparray1 2 2 3 3 7in 173 c randint10 99 6in 174 df pddataframezipa b c columnsa b cin 175 dfset indexa b inplacetruein 176 dfout176 ca b 11 1 20 2 3133 2 24 3 65 3 2266 7 74 now i want to retrieve a valuesq1 in range 33 66 expected return value 33 55 66 or 33 33 55 66 in case last inclusive and 33 55 or 33 33 55 if notq2 in range 20 40 expected return value 33 or 33 33 same for any other multiindex dimension for example b valuesq3 in range 1 500 with repetitions as number of data rows in range expected return value 1 2 2 3 3 more formallet us assume t is a table with columns a b and c the table includes n rows table cells are numbers for example a double b and c integers let us create a dataframe of table t let us name it df let us set columns a and b indexes of df without duplication ie no separate columns a and b as indexes and separate as data ie a and b in this case multiindex questions how to write a query on the index for example to query the index a or b say in the labels interval 1200 5400 labels 1200 and 5400 exist i must clarify that i am interested only in the list of indices as a response to the queryhow to the same but in case of the labels 1200 and 5400 do not exist but there are labels by value lower than 120 higher than 120 and less than 540 or higher than 540in case the answer for q1 and q2 was unique index values now the same but with repetitions as number of data rows in index rangei know the answers to the above questions in the case of columns which are not indexes but in the indexes case after a long research in the web and experimentation with the functionality of pandas i did not succeed the only method without additional programming i see now is to have a duplicate of a and b as data columns in addition to indexthanks in advance for helpslava,['python'] +515542,pylint does not point to virtualenv python i am pretty new to python and currenty i am trying to use pylint for checking code quality i am getting a problem my pylint does not point to virtualenv python interpreter here is the output that i get when i run pylint version pylint version pylint 0211 astng 0201 common 0503 python 266 r26684292 jul 10 2013 224845 gcc 447 20120313 red hat 4473in virtualenv i have python 27 installed will appretiate you help if someone can point me to how to solve that,['python'] +515548,picking up meteorjs user logout is there any way to pick up when a user logs out of the website i need to do some clean up when they do so using the builtin meteorjs user accountsi will be doing some validation using it so i need a solution that cannot be trigger on behalf of other users on the client side preferably something completely server side,['javascript'] +515551,override identifier after destructor in c11 does the override identifier after virtual destructor declaration have any special meaningclass basepublic virtual base virtual int method const class derived public basepublic virtual derived override virtual int method override error marked override but does not override missing const using override identifier on virtual method is useful as check compiler will report error when the base virtual method is actualy not overridendoes override on virtual destructor has any meaningfunction too,['c++'] +515580,admob banner sizes on android i am currently integrating admob into my android game i have difficulties integrating smart banners into my framelayoutbased layout because they take up different amounts of screen real estate on different devicesfor example if i thisplay a smart banner on my acer a500 mdpi 1280x800 i receive one of the size 1280x90px whereas on my nexus 7 i receive one with 1279x66px tvdpi 1280x800 and on my galaxy nexus hdpi 1280x720 with 1196x64px according to the admob documentation that might be understandable behaviour considering that the values given in the documentation are dphowever this behaviour is a great problem for me since a smartbanner with a height of 90px on a 1200x800px mdpi screen takes up a lot more screen real estate than a smart banner with a height of 64px on an hdpi screen see screenshots below so here are my questions how much space should i reserve at least for a smart banner has anyone tried something similar and how did you deal with thatnote unfortunately using a layout different to framelayout is not an option at the moment additionally xml layouts can not be used to integrate the adsbest regardslorenzscreenshots a500,['android'] +515785,uirefreshcontrol on viewdidload i am using the following code to create a uirefreshcontrol void viewdidload super viewdidload uirefreshcontrol refreshcontrol uirefreshcontrol alloc init refreshcontrol addtargetself actionselectordoload forcontroleventsuicontroleventvaluechanged selfrefreshcontrol refreshcontrol void doload thispatch asyncthispatch get global queue0 0 instead of sleeping i do a webrequest here nsthread sleepfortimeinterval 5 thispatch asyncthispatch get main queue tableview reloaddata selfrefreshcontrol endrefreshing it works great if i navigate to my view drag the table the code runs and the data thisplayshowever what i would like to do is have the view in the loading state as soon as it appears that way the user knows something is going on i have tried adding the following voidviewdidappearboolanimated super viewdidappearanimated selfrefreshcontrol beginrefreshingbut it does not seem to work when i navigate to the view it looks like a regular view refresh control is not visible plus when i try to pull the refresh control it never finished loadingobviously i am going about this the wrong way any suggestions on how i should handle this,['ios'] +515829,actionbarcompat on gingerbread fills whole screen so weve successfully stripped actionbarsherlock from the zappos app in favor of the new actionbarcompat and it works great on honeycomb but on gingerbread the action bar expands to fill the whole screen and i cannot figure out why it is happening we basically just changed all the themesstylesreferences to actionbarsherlock to be the equivalents in actionbarcompat below is a screen shot of the issue anyone else run across this on gb and know of a fix it is holding up a release for us,['android'] +515939,clean way to convert qstring to char not const char i have an ugly code for this stuff create a c char pointer and copy the qstring in it but maybe exist in qt an elegant way actual code qstring maquina is a method parameterchar c maquina new charmaquinalength 1strcpyc maquina maquinatostdstringc strjust for information i need a real char not a simple const char so this code not work idmaquinatolatin1datai cannot use can i convert a qstring to char and vice versa,['c++'] +515944,unresolved specs during gemspecificationreset when launching guard i am getting this output guardwarn unresolved specs during gemspecificationreset lumberjack 102 ffi 050warn clearing out unresolved specsplease report a bug if this causes problemswhats this mean and how do i fix thiscontents of guardfileguard livereload do watchrcssjshtmlendguard sass input css style compressed extension mincss,['ruby'] +515951,how to find average intensity of opencv contour in realtime i have a image with about 50 to 100 small contours i wish to find the average intensity1 of each of these contours in realtime2 some of the ways i could think of wasdraw contour with filled option for each contour use each image as a mask over the original image thus find the average but i presume that this method would not be realtime at first glancestudy opencv implementation of drawcontour function with the filled option and access the pixels enclosed by the contour in the same manner but the code seems really complex and not readily understandable calculate the minimum area rectangle find all the points inside the rectangle using transformation and find average of points that are nonzero again seems complex approachis there an easier efficient way to do this1 average of all pixel intensities enclosed by each of the nonoverlapping contours2 about 25 960 x 480 pixel images per sec on a 266 ghz desktop pc,['c++'] +515996,threadinterrupt in java whats the point i understand perfectly what it does at least i hope so it does not really interrupt the thread it makes threadisinterrupted true and the code is supposed to check what method and stop the thread itself my question is why do we even need this method it seems perfectly replaceable by declaring a boolean flag stating whether this thread should be stopped does not any java textbook use this boolean flag as the best example of how volatile keyword should be used i am particularly confused as there seems to be no way to uninterrupt the thread as threadresume is deprecated that makes interrupt even less useful than a boolean flag i write by myself other than being perhaps a bit easier to write does threadinterrupt do anything different from my boolean flag,['java'] +516012,why are javascript primitives not instanceof object today i happened to have too much time to kill and i played a bit with the node v01013 command line 1 instanceof objectfalse 1 proto 1 proto instanceof objecttrue 1 proto proto objectprototypetruenow according to mdn what instanceof does isthe instanceof operator tests whether an object has in its prototype chain the prototype property of a constructorbut clearly objectprototype is in 1s prototype chain so why is 1 instanceof object false perhaps because 1 is a primitive not an object to begin withokay i accept that and i did more tests 1 proto 2 proto true a proto b proto true 1 proto a proto false 1 proto proto a proto proto true 1 proto type numbernumber a proto type stringstring 2typenumber 15typenumber btypestringso apparently all number primitives inherit from one object and all string primitives inherit from another object both these 2 objects inherit from objectprototypenow the question is if numbers and strings are considered primitives why inherit them from other objects or inversely as they inherit from other objects why not consider them objects too it seems nonsensical to me that the child of an object is not an objectby the way i have also tested these in firefox 22 and got the same result,['javascript'] +516059,finding out what the gcc include path is i am trying to programmatically find the include path on linux which as i understand it in practice means finding what gcc considers it to be is that quite true how does clang do itaccording to some of the components involve the cpu architecture and the gcc version the latter in particular seems tricky i suppose it could be obtained by running gcc version and parsing the output or gcc v but this seems inelegant at best and fragile at worst doing it from within ones code assuming ones program is being compiled with gcc might be another option but it would require depending on that assumptionwhats the recommended way to do it,['c'] +516070,how to find the duration of difference between two dates in java i have two objects of datetime which need to find the duration of their difference i have the following code but not sure how to continue it to get to the expected results as followingexample 110314 093058 110314 093343 elapsed time is 02 minutes and 45 seconds 110314 093058 110315 093058 elapsed time is a day 110314 093058 110316 093058 elapsed time is two days 110314 093058 110316 093558 elapsed time is two days and 05 mintuescode string datestart 110314 092958 string datestop 110314 093343 custom date format simpledateformat format new simpledateformatyymmdd hhmmss date d1 null date d2 null try d1 formatparsedatestart d2 formatparsedatestop catch parseexception e eprintstacktrace get msec from each and subtract long diff d2gettime d1gettime long diffseconds diff 10 60 long diffminutes diff 60 10 60 long diffhours diff 60 60 10 systemoutprintlntime in seconds diffseconds seconds systemoutprintlntime in minutes diffminutes minutes systemoutprintlntime in hours diffhours hours,['java'] +516123,equivalent of eclipses problems view on android studio i used to code for android on eclipse and have become accustomed to the problems view which lists all warnings and errors in the whole project making it easy to zoom into exactly which lines of code were causing issuesi have since migrated to android studio but i cannot seem to find a view that performs a similar function instead the errors are only shown to me when i click into an individual file which is too much hassleis there an equivalent of the problems view in eclipse for android studio,['android'] +516125,using activerecord on multiple databases i am writing a payroll system that will integrate with a preexisting system the original system had a master database that handled user management and some global configuration below that there are multiple databases each identical in structure basically each database is one companies payroll database all these are tied to the main database because it belongs to a parent company who has many subsidiaries each with their own hr departmentwhat i was wondering is if there is any way that i can based on either a cookie or another method that stores what company they wish to connect to dynamically change the activerecords target database based on their input using a before filterheres an exampleuser a logs in to the site page loads with available companies that the user has permission to access user will then select a company they have admin privileges in that company they add an employee before that action is run rails will switch the connection to the appropriate database then add the record,"['ruby-on-rails', 'ruby']" +516140,java setter getter and constructor i am a bit confused about the use of gettersetters and constructors see the below code for an example public class exampleclass private int value 0 public exampleclass value 0 public exampleclass int i thisvaluei public int getvalue return value public void setvalueint val thisvalueval public static void mainstring args exampleclass example new exampleclass 20 examplesetvalue20 both lines above do same thing why use constructor systemoutprintlnexamplegetvalue all i have learned is that we need getterssetters for security and that they can also be used to change or edit values later on my question is that if the constructor is the point of initialization and a default constructor is always present why use a constructor with parameters to initialize values instead of getterssetters wouldnt using the getter and setter provide security as well being able to easily change values at any stage please clarify this point for me,['java'] +516141,how to start each from div id small to biggest number how i can make the each to starts with the div id small number 1 to the big number 5 1 2 3 4 5lets say i have this divsdiv classtid 5tid 5divdiv classtid 4tid 4divdiv classtid 3tid 3divdiv classtid 2tid 2divdiv classtid 1tid 1divi have this jquery what im using but starts with the first div class id number 5 but i need to start with number 1 divclasstid eachfunction code is come here,"['javascript', 'jquery']" +516181,decorators and ithisposable i have a subclass of dbcontextpublic class mycontext dbcontext and i have an iunitofwork abstraction around mycontext that implements ithisposable to ensure that references such as mycontext are thisposed of at the appropriate timepublic interface iunitofwork ithisposable public class unitofwork iunitofwork private readonly mycontext context public unitofwork context new mycontext unitofwork thisposefalse public void thispose thisposetrue gcsuppressfinalizethis private bool thisposed protected virtual void thisposebool thisposing if thisposed return if thisposing if context null contextthispose thisposed true my unitofwork is registered with a lifetime scope of per web request i have decorators of iunitofwork that could be registered as transient or lifetime scoped and my question is what should they do with regard to implementing ithisposable specifically should they or should they not pass on the call to thisposepublic class unitofworkdecorator iunitofwork private readonly iunitofwork decorated public unitofworkdecoratoriunitofwork decorated decorated decorated public void thispose do we pass on the call decoratedthispose i see 2 options i am guessing option 2 is the correct answerit is expected that each decorator will know whether it is transient or lifetime scoped if a decorator is transient then it should not call thispose on the decorated instance if it is lifetime scoped it shouldeach decorator should only be concerned with thisposing of itself and should never pass on the call to the decorated instance the container will manage the call to thispose for each object in the call chain at the appropriate time an object should only thispose of instances that it encapsulates and decorating is not encapsulation,['c#'] +516223,prevent activity restarting when orientation changes i am new to android development i have separate screens for portrait and landscape modewhen i change my orientation corresponding screen gets loaded and activity restarts now i do not want my activity to restart when i change the orientation but should load its corresponding screenaxml i have tried activity label myactivityconfigurationchangesandroidcontentpmconfigchangesorientationthe above line stops activity getting restarted but it loads the same screenaxmlplease suggest thanks,['android'] +516241,space key event behaviour on numeric input field i created two edittext with androidinputtypenumber propertyhere i am using hardware keyboard so when i perform space key event on textfield focus control directly shift from edittext view to some other random view of screen in normal text field type it took it as an another character that is fineany one have idea how can use space key event to retain focus on same field,['android'] +516262,apache is not running from xampp control panel error apache shutdown unexpectedly this may be due to a blocked port i have installed xampp xamppwin321820vc9installerexe on windows 7 successfully but unfortunately the following error was found during running apache from xampp control panel 53838 pm apache error apache shutdown unexpectedly53838 pm apache this may be due to a blocked port missing dependencies 53838 pm apache improper privileges a crash or a shutdown by another method53838 pm apache press the logs button to view error logs and check53838 pm apache the windows event viewer for more clues53838 pm apache if you need more help copy and post this53838 pm apache entire log window on the forums,['php'] +516292,a recursive template type for a container typename forwarding is there any way to get a recursive template type i have a container for which i want to specify an underlying storage strategy the inner template must however use the outer templates type so it causes a loop in the type definition which is not possible to specifyabout what i wanttemplatetypename cstruct inner c object16templatetypename t typename innerstruct container t value innercontainer holderc11 solutions are fine though i am still on gcc 463,['c++'] +516311,how to compile code from stdin the code is quite simple test cat testcppint mainis there a way to compile the code that is coming from a standard outputi have tried this cat testcpp g and some variations but none produced executablejust some clarifications i have a program which preprocess a file and produces another file which i want to compile i thought about not creating this intermediate file but to instead produce the object file directly,['c++'] +516365,flip vertically a backgroundimage every time it repeaty i am searching for a trick that repeat my background image vertically but every time the image is repeated i want to flip it verticallyi tried all the things in my mind with repeaty but i do not found a solution even searching for it in googleexample straight backgroundimage flipped backgroundimage when it repeaty and then flipped again to straightthere is a method to obtain that positioni will accept the solution in jscript and library of it only if there is not a solution with pure css thank you all,"['javascript', 'css']" +516369,friend function from a templated class i have a class like thisinclude blargh class foo public bar static double m value and another one like thistemplateclass x class yclass blarg public bar void setvaluedouble val foom value val since foos m value is private and i would like to keep it that way i thought i would declare the setvalue function as a friend to the foo class so that it could access the static member when needed i have tried declarations along these lines within foos public areatemplateclass x class y friend void blargx ysetvaluedouble valtemplateclass x class y friend void blargsetvaluedouble valfriend void blargsetvaluedouble valbut no luck in compiling what is the proper syntax for this if possible,['c++'] +516377,multiple instances of nodejs on different cores i would like to set up 4 different nodejs instances each on their own core does nodejs stack new instances on the same core or set them on new cores alsothe instances are unrelated and receive requests individually i would like the cpu load spread out evenlyi have not been able to find a definitive answer to this question,['javascript'] +516413,navigatorappexitapp is not working i am developing windows phone 8 phonegap app using navigatorappexitapp i am quiting the app from home screen in windows phone 7 but when i tried the same in windows phone 8 i am getting the error unable to get property exitapp of undefined or null reference i would like to know why it is undefined in windows phone 8 and not in window phone 7 phonegap app also i would like to know is there any way to quit the app programmatically in windows phone 8 phonegap app,['javascript'] +516416,android actionbar not visible i am trying to add an option menu in actionbar to my existing app but still not working intsead of if i make a new project with hello world default app i can see the button in action bar the oncreateoptionmenu method seems never caught in debug with breakpoint whats wrong i am working with api 14 on both app and this is my mainactivity codeimport androidappactivityimport androidosbundleimport androidviewmenupublic class principale extends activity called when the activity is first created overridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutecran d acceuilpublic boolean oncreateoptionmenumenu menu getmenuinflaterinflatermenuprincipale menu return true my menu xml codemenu xmlnsandroid item androidididaction settings androidorderincategory100 androidshowasactionnever androidtitlestringaction settingsmenumanifestxmlxml version10 encodingutf8manifest xmlnsandroid packagecomexamplemyapp androidversioncode1 androidversionname10 usessdk androidminsdkversion14 androidtargetsdkversion14 usespermission androidnameandroidpermissioninternet usespermission androidnameandroidpermissionaccess fine location usespermission androidnameandroidpermissionaccess coarse location usespermission androidnameandroidpermissionwrite external storage usespermission androidnameandroidpermissionread external storage application androidallowbackuptrue androidicondrawableic launcher androidlabelstringapp name androidthemestyleapptheme activity androidnamecomexamplemyaprincipale androidlabelstringapp name intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity activity androidnamecomexamplemyapphome androidlabelstringtitle activity home activity activity androidnamecomexamplemyapplistdir androidlabelstringtitle activity list dir activity applicationmanifest,['android'] +516469,cakephp backe shell error database connection amysqla is missing or could not be created i have an issue here with backingi have read the previous answers to similar questions but the solutions seem to not apply herei cannot backe because the error i receive is database connection amysqla is missing or could not be createdif i run which php the php it is reading is the correct path within mampif i check the pdo modulesphp i grep pdopdopdo support enabledpdo drivers sqlite pgsql mysqlpdo driver for mysql enabledpdo driver for postgresql enabledpdo driver for sqlite 3x enabledmy application or what i have completed on it so far has no trouble connecting to the databasei am completely stuck all answers around the web point to pdo not being enabled or the incorrect path for php but neither of those apply in my casei am willing to provide you any information you require to help me repair this,['php'] +516523,resources on sibling sub module gradle project i am trying to migrate my companys project from maven to gradle so far i have been able to convert all poms to the corresponding buildgradle files but i ran across an issue in a sub module when building coreui utils fieldpanelsthe sub module fieldpanel uses colors and other resources defined in utils i tried adding the utils project as a dependency but it did not work what am i missinghomedevelopmentandroidstudioprojectscomprojectcoreuicommonandroidfieldpanelsbuildbundlesdebugreslayoutbase summary step layoutxml2 error error no resource found that matches the given name at background with value colorwizard summary bgutils gradlebuildbuildscript repositories mavencentral dependencies classpath comandroidtoolsbuildgradle052 apply plugin androidlibraryandroid sourcesets main manifest srcfile androidmanifestxml res srcdirs res compilesdkversion 15 buildtoolsversion 170 dependencies compile group comcompanyiposandroid name commonsposmicroposapi version 0035snapshot compile group orgslf4j name slf4japi version 165 repositories maven credentials username mavenuser password mavenpassword url repourl maven credentials username mavenuser password mavenpassword url libsreleasesurl maven credentials username mavenuser password mavenpassword url libssnapshotsurl fieldpanels gradlebuildbuildscript repositories mavencentral dependencies classpath comandroidtoolsbuildgradle052 apply plugin androidlibraryrepositories maven credentials username mavenuser password mavenpassword url repourl maven credentials username mavenuser password mavenpassword url libsreleasesurl maven credentials username mavenuser password mavenpassword url libssnapshotsurl android dependencies compile group comcompanyiposandroid name commonsposmicroposapi version 0035snapshot compile group comcompanyiposandroid name commonandroidutils version 0035snapshot compile projectcommonandroidutils compile group orgslf4j name slf4japi version 165 sourcesets main manifest srcfile androidmanifestxml res srcdirs res compilesdkversion 15 buildtoolsversion 170,['android'] +516528,performance of row vs column operations in numpy there are a few articles that show that matlab prefers column operations than row operations and that depending on you lay out your data the performance can vary significantly this is apparently because matlab uses a columnmajor order for representing arrays i remember reading that python numpy uses a rowmajor order with this my questions arecan one expect a similar difference in performance when working with numpy if the answer to the above is yes what would be some examples that highlight this difference,['python'] +516550,make an inlineblock div take 100 of the remaining width i have 3 div blocks inside another divwhat i wanted to do is to put them inline but the first 2 div blocks should take a width according to their content and the last div take the remaining spacediv classcontainer div classredreddiv div classgreengreendiv div classbluebluedivdivi try to avoid the use of fixed widths because i need to use this in a responsive designhow can i make the blue div in this fiddle take the rest available space of its parent and act responsive if the screen is resized,"['html', 'css']" +516594,reset select2 value and show placeholdler how do i set the placeholder on value reset by select2 in my example if locations or grade select boxes are clicked and my select2 has a value than the value of select2 should reset and show the default placeholder this script is resetting the value but would not show the placeholder locations grade changefunction e6select2data placeholder studiengang wahlen id null text e6select2 placeholder studiengang wahlen width resolve id functione return esubject minimuminputlength 2 ajax url indexphpoptioncom unistasksearchlocatortmplcomponentphp echo jsessiongetformtoken 1 datatype json data functionterm page return q term search term g grade optionselectedval o locations optionselectedval results functiondata page return results data formatresult subjectformatresult formatselection subjectformatselection dropdowncssclass bigdrop escapemarkup functionm return m,['jquery'] +516621,pandas select from dataframe using startswith this works using pandas 12 devtable2tabletablesubdivision invernessthen i realized i needed to select the field using starts with since i was missing a bunchso per the pandas doc as near as i could follow i tried criteria tablesubdivisionmaplambda x xstartswithinvernesstable2 tablecriteriaand got attributeerror float object has no attribute startswithso i tried an alternate syntax with the same resulttablexstartswithinverness for x in tablesubdivisionreference section 4 list comprehensions and map method of series can also be used to produce more complex criteriawhat am i missing,['python'] +516655,how to feed datepicker widget with other calendar sytems is there anyway to use datepicker widget with other calendar systems i need a picker for jalali persian calendar system but i dont know how to feed datepicker with my datai have studied methods related to datepicker but could not find anything that allows me to do thati also found a custom widget called androidwheel its a iosstyled widget and does not feel native but it allows me to implement thisso is there anyway to have a nativelooking datepicker widget that allows me to pick date for jalali calendar system and have month names in persian update i have previously answered my question and it solves the problem but mohamad amin has created a great library for that and i strongly advise you to use his library thanks mohamad amin,['android'] +516668,convert datetime to timespan good day guysi want to convert a datetime instance into a timespan instance is it possible i have looked around but i could not find what i want i only find time difference more specefically a want to convert datetime instance into milliseconds to save it in isolatedstorage,"['c#', '.net']" +516691,how can i see raw mongodb queries with mongoid i followed this page to see mongodb queries as a result i could see moped logbut i cannot see raw mongodb querieshow can i thisplay mongodb queries in the rails consoleserveri did like the below in rails rootconfigenvironmentsdevelopmentrb mongoidloggerlevel loggerdebugmopedloggerlevel loggerdebugmongoidlogger loggernewrailsrootlogmongoid developmentlogmopedlogger loggernewrailsrootlogmoped developmentlog in rails rootlogmongoid developmentlog show nothing in rails rootlogmoped developmentlogmoped ip address27017 query databasedatabase name collectioncollection name selectorqueryscreen namets 3156 orderby id1 flagsslave ok limit1 skip0 batch sizenil fieldsnil 546286mshow can i see raw mongodb queries with mongoidi want to see like the belowdbcollection namefind query screen namets 3156 orderby id1 i can see raw mongodb queries in varlogmongomongologbut i want to see raw queries in ormmongoids log,['ruby-on-rails'] +516733,random number generator between 0 10 in c i need help in writing a program that will generate 100 random numbers between 0 and 10 the out put needs to be thisplayed in a windows message box i am stuck as to what code i have use to get the numbers in the box and to only have 100 random numbers,['c#'] +516839,where is the default welcome aboard page located in my app i scoured my apps directories and i cannot find the html page for the default rails welcome aboard page i also cannot find a route for the default welcome aboard page in routesrb how does my rails app route httplocalhost30 to a nonexistent page in my appthe rails server produces this informationstarted get for 127001 at 20130731 020013 0600processing by railswelcomecontrollerindex as html rendered users7studrvmgemsruby200p247railstutorial rails 4 0gemsrailties400librailstemplatesrailswelcomeindexhtmlerb 01mscompleted 200 ok in 3ms views 25ms activerecord 00msso it looks to me like there is a controller buried in a gem somewhere that handles the request,['ruby-on-rails'] +516856,addition of chars adding one character in front what i am trying to implement is a function that increments a string by one character for examplea 1 aabaaz 1 abaz 1 ai have implemented function for the first two cases however i cannot think of any solution for the third caseheres my code def new skus s s1 already added false new sku str for i in s if not already added if i z already added true new sku chrordi16526 65 else new sku i return new sku1any suggestions,['python'] +516877,twitter bootstrap 3 sticky footer good morning i have been using the twitter bootstrap framework for quite a while now and they recently updated to version 3i am having trouble getting the sticky footer to stick to the bottom i have used the starter template supplied by the twitter bootstrap website but still no luck any ideas,"['html', 'css']" +516878,firefox for android does not launch app when link is clicked firefox does not fire intents for clicked links the way it should therefore one cannot launch their app by clicking a link in firefox which is possible in chrome and other browsersthe desired behavior is the followingon my website i have a link that when clicked should launch my android app if the app is not installed preferably its page in google play should be opened to download itmethodthe way i implement it is with an intent uri of the formintentmyhostcomintentschememyschemepackagecommyappendin the app i register an intent filter in my manifest and listen for an intent that matches however it is up to the browser to fire such an intent when the link is clicked so that my app can starti have tested this method with various browsers and it works on most of them with the notable exception of firefox with other browsers either my app launches or its page in google play loads in case it is not installed on the devicethe method with the intent uri is the recommended one by google it works perfectly on chrome and on some other browsersthere are also other methods i have read many threads and articles about the possibilities the main alternatives arealternative methodsusing a custom scheme like myschememywebsitecomusing a regular http link like alternative 1 is not recommended for two reasons i do not own such a scheme it does not exist globally it is wrong google was also using market to start the google play app but they have admitted that this is wrong and should change if my app is not currently installed it will not be started and most browsers thisplay an error page which is obviously undesirablealternative 2 does not work on most browsers and seems to be deprecated in favor of the intent uri methodfirefox in particularonly works with the custom scheme alternative 1 in the case of a regular http link alternative 2 it just loads the link and shows the website in the case of the recommended intent uri method it does nothing actually it shows a dialog asking whether you want to launch the app but when you click yes nothing happens so it seems firefox recognizes links like intent but does not handle them properlyq what is the recommended method for launching an app from a link in firefox why is not the intent uri method supported by firefoxrelated links keep in mind that the thread is quite old,['android'] +516889,two implementations of a method vs2012 resharper 71 when i rightclick a method and select go to implementation i am often presented with two implementations one in my source code and one as a referencein this example emailservice is in a different project that is loaded into the current visual studio solution and referenced as a project referenceselecting the reference one seems to do nothing whereas selecting the source code one takes me to the implementation of the method as expectedthis has happened on a couple of different development machines in different projectswhat is causing this and is it possible to resolve the issue so that go to implementation takes me directly to the source code implementationthis is happening in visual studio 2012 with resharper 71 installed,['c#'] +516895,phpstorm how to refresh folder content or whole project tree this may be a dumb question but i can not find an option to refresh folder content in project tree phpstorm ideis this really basic feature missingi know that content is refreshed automatically but in some types of folders where files are generated and changed often this does not work,['php'] +516904,convert iterator to array i need to return a string array i use guava to split the string please see the code belowiterablestring arrayofvalues splitteronsplitmystringit return the iterator list but i need a string is there are any way to give iterator element and convert that to array many thanks,['java'] +516911,visual studio 2010 how to force project reference to use exact path not gac or program files were forever having this problem we have a number of solutions and an adjacent components folder all the dlls we want to reference are in this folder some of them weve built from source to use a specific version number that only existins in the components binary but when a user on a different machine getslatest of everything from tfs and so has the exact on thisk structure visual studio still changes the references to ones that are installed in program files the gac or elsewhere have tried manually editing the proj file to include hintpath egreference includefoo version5 cultureneutral processorarchitecturemsil specificversionfalsespecificversion hintpathcomponentsfoodllhintpathreferenceto no avail how do we force visual studio to respect this path,['.net'] +516920,improve matching of feature points with opencv i want to match feature points in stereo images i have already found and extracted the feature points with different algorithms and now i need a good matching in this case i am using the fast algorithms for detection and extraction and the bruteforcematcher for matching the feature pointsthe matching codevector vectordmatch matchesusing either flann or bruteforceptrdescriptormatcher matcher descriptormatchercreatealgorithmnamematcherknnmatch descriptors 1 descriptors 2 matches 1 just some temporarily code to have the right data structurevector dmatch good matches2good matches2reservematchessize for size t i 0 i matchessize i good matches2push backmatchesi0 because there are a lot of false matches i caluclated the min and max thistance and remove all matches that are too badcalculation of max and min thistances between keypointsdouble max thist 0 double min thist 100for int i 0 i descriptors 1rows i double thist good matches2ithistance if thist min thist min thist thist if thist max thist max thist thistfind the good matchesvector dmatch good matchesfor int i 0 i descriptors 1rows i if good matches2ithistance 5min thist good matchespush back good matches2i the problem is that i either get a lot of false matches or only a few right ones see the images belowi think it is not a problem of programming but more a matching thing as far as i understood the bruteforcematcher only regards the visual thistance of feature points which is stored in the featureextractor not the local thistance xy position which is in my case important too has anybody any experiences with this problem or a good idea to improve the matching resultsediti changed the code that it gives me the 50 best matches after this i go through the first match to check whether it is in a specified area if it is not i take the next match until i have found a match inside the given areavector vectordmatch matchesptrdescriptormatcher matcher descriptormatchercreatealgorithmnamematcherknnmatch descriptors 1 descriptors 2 matches 50 look if the match is inside a defined area of the imagedouble tresholdthist 025 sqrtdoubleleftimagegreysizeheightleftimagegreysizeheight leftimagegreysizewidthleftimagegreysizewidthvector dmatch good matches2good matches2reservematchessize for size t i 0 i matchessize i for int j 0 j matchesisize j calculate local thistance for each possible match point2f from keypoints 1matchesijqueryidxpt point2f to keypoints 2matchesijtrainidxpt double thist sqrtfromx tox fromx tox fromy toy fromy toy save as best match if local thistance is in specified area if thist tresholdthist good matches2push backmatchesij j matchesisize i think i do not get more matches but with this i am able to remove more false matches,['c++'] +516939,warning path is not properly set up usually this is caused by shell initialization files whenever i go to a folder with a rvmrc file there is a warningwarning path is not properly set up homemervmgemsruby200p247bin is not available usually this is caused by shell initialization files check them for path entries to fix run rvm use ruby200p247i did rvm use ruby200p247 but the warning is still presentnote there are no errors im able to run my application just fine but the warning is very annoying any ideas,['ruby'] +516949,could not resolve comandroidtoolsbuildgradle05 i am trying to build a project in android studio the project uses gradleat the time mavenorg is experiencing some problems and i get following errorsgradle a problem occurred configuring project myproject could not resolve all dependencies for configuration myprojectclasspath could not resolve comandroidtoolsbuildgradle05required byandroidmyprojectunspecified could not head received status code 503 from server service temporarily unavailableit made me think i do not want to depend on mavenorg and internet connection for my builds is there a way i could drop these dependencies and make android studio selfsufficient i would like to be able to build my android projects even without internet connection and even if mavenorg never recovereditif i understand it right there is a way to setup local maven repository and then use repositories mavenlocalinstead ofrepositories mavencentral in buildgradle files unfortunately i am not sure if it is the way and what are downside of this approachupdate december 2013android studio now supports gradle offline mode since version 040 more information can be found in release notes for the studio,['android'] +516967,ios core bluetooth not asking for pair in my recent project i need to communicate a hardware bluetooth low energyi have implement all the delegate methods code i am able to connect hardware and device but i am not getting pairing alert attached screen shot why not it is asking for pairing thank you import btwcentralconnectionmanagerh implementation btwcentralconnectionmanager synthesize cbcmanager synthesize thiscoveredperipheral synthesize findmeservicecharacteristic synthesize findmeservice synthesize delegate delegate static nsstring kfindmeserviceuuid1802 static nsstring kfindmecharacteristicuuid2a06 static btwcentralconnectionmanager connectionmanager nil btwcentralconnectionmanager sharedconnectionmanager synchronizedself if connectionmanager connectionmanagerself alloc init return connectionmanager return nil voidfindme byte code0x02 ifselfthiscoveredperipheral selfthiscoveredperipheral writevaluensdata datawithbytescode length1 forcharacteristicselffindmeservicecharacteristic typecbcharacteristicwritewithoutresponse else uialertview alertviewuialertview alloc initwithtitletest messageinvalid charactersitcs delegatenil cancelbuttontitlenil otherbuttontitlesok nil alertview show alertviewnil voidsearchfordevices selfcbcmanagercbcentralmanager alloc initwithdelegateself queuenil voidconnect nsdictionary connectoptions nsdictionary dictionarywithobjectnsnumber numberwithboolyes forkeycbconnectperipheraloptionnotifyonthisconnectionkey selfcbcmanager connectperipheralselfthiscoveredperipheral optionsconnectoptions voidthisconnect self cleanup voidcentralmanagerdidupdatestatecbcentralmanager central switch centralstate case cbcentralmanagerstatepoweredon selfcbcmanager scanforperipheralswithservices cbuuid uuidwithstringkfindmeserviceuuid optionscbcentralmanagerscanoptionallowduplicateskey no break scans for any peripheral default uialertview alertviewuialertview alloc initwithtitletest messagecental manager did change state delegatenil cancelbuttontitlenil otherbuttontitlesok nil alertview show alertviewnil break voidcentralmanagercbcentralmanager central didthiscoverperipheralcbperipheral peripheral advertisementdatansdictionary advertisementdata rssinsnumber rssi stops scanning for peripheral selfcbcmanager stopscan if selfthiscoveredperipheral peripheral selfthiscoveredperipheral peripheral selfdelegate diddevicethiscoverdselfthiscoveredperipheralname voidcentralmanagercbcentralmanager central didfailtoconnectperipheralcbperipheral peripheral errornserror error selfdelegate diddeviceconnectionfailederror self cleanup voidcentralmanagercbcentralmanager central didconnectperipheralcbperipheral peripheral selfdelegate diddeviceconnected selfthiscoveredperipheral setdelegateself selfthiscoveredperipheral thiscoverservicescbuuid uuidwithstringkfindmeserviceuuid voidperipheralcbperipheral aperipheral didthiscoverservicesnserror error if error nsstring strmsgnsstring stringwithformatdidthiscoverservices error uialertview alertviewuialertview alloc initwithtitletest messagestrmsg delegatenil cancelbuttontitlenil otherbuttontitlesok nil alertview show alertviewnil self cleanup return for cbservice service in aperipheralservices if serviceuuid isequalcbuuid uuidwithstringkfindmeserviceuuid selffindmeserviceservice selfthiscoveredperipheral thiscovercharacteristicscbuuid uuidwithstringkfindmecharacteristicuuid forserviceselffindmeservice void peripheralcbperipheral peripheral didthiscovercharacteristicsforservicecbservice service errornserror error iferror nsstring strmsgnsstring stringwithformatdidthiscovercharacteristicsforservice error uialertview alertviewuialertview alloc initwithtitletest messagestrmsg delegatenil cancelbuttontitlenil otherbuttontitlesok nil alertview show alertviewnil forcbcharacteristic character in service characteristics ifservice uuid isequalcbuuid uuidwithstringkfindmeserviceuuid character uuid isequalcbuuid uuidwithstringkfindmecharacteristicuuid nsstring strmsgnsstring stringwithformatdidthiscovercharacteristicsforservice character uialertview alertviewuialertview alloc initwithtitletest messagestrmsg delegatenil cancelbuttontitlenil otherbuttontitlesok nil alertview show alertviewnil selffindmeservicecharacteristic character void peripheralcbperipheral peripheral didupdatevalueforcharacteristiccbcharacteristic characteristic errornserror error nsstring strmsgnsstring stringwithformatdid update value for characteristic new value error characteristic characteristic value error uialertview alertviewuialertview alloc initwithtitletest messagestrmsg delegatenil cancelbuttontitlenil otherbuttontitlesok nil alertview show alertviewnil voidperipheralcbperipheral peripheral didupdatenotificationstateforcharacteristiccbcharacteristic characteristic errornserror error if error nslogerror changing notification state errorlocalizeddescription exits if it is not the transfer characteristic if characteristicuuid isequalcbuuid uuidwithstringkfindmecharacteristicuuid return nsstring strmsgnsstring stringwithformatdidupdatenotificationstateforcharacteristic reason characteristic error uialertview alertviewuialertview alloc initwithtitletest messagestrmsg delegatenil cancelbuttontitlenil otherbuttontitlesok nil alertview show alertviewnil void peripheralcbperipheral peripheral didwritevalueforcharacteristiccbcharacteristic characteristic errornserror error if error nsstring strmsgnsstring stringwithformatfailed to write value for characteristic reason characteristic error uialertview alertviewuialertview alloc initwithtitletest messagestrmsg delegatenil cancelbuttontitlenil otherbuttontitlesok nil alertview show alertviewnil else nsstring strmsgnsstring stringwithformatdid write value for characterstic new value characteristic characteristic value uialertview alertviewuialertview alloc initwithtitletest messagestrmsg delegatenil cancelbuttontitlenil otherbuttontitlesok nil alertview show alertviewnil voidcleanup if selfthiscoveredperipheralisconnected return if selfthiscoveredperipheralservices nil for cbservice service in selfthiscoveredperipheralservices if servicecharacteristics nil for cbcharacteristic characteristic in servicecharacteristics if characteristicuuid isequalcbuuid uuidwithstringkfindmeserviceuuid if characteristicisnotifying selfthiscoveredperipheral setnotifyvalueno forcharacteristiccharacteristic return selfcbcmanager cancelperipheralconnectionselfthiscoveredperipheral selfdelegate diddevicethisconnectedend,"['iphone', 'ios']" +516984,javascript promise not passing all arguments using q i am having trouble passing all arguments my promise callback only receives one instead of threevar asyncfunction functionresolve settimeoutfunction resolvesome string that is passed and another third 10var promisefunction function var deferred qdefer asyncfunctiondeferredresolve return deferredpromisepromisefunctionthenfunction only one argument is passed here instead of 3 0 some string that is passed consolelogarguments any idea what i am doing wrong,['javascript'] +516989,converting utc to local time returns strange result i have a solution of three projectscoreoutlook addinaspnet websiteboth the outlook addin and the website use the same methods from core project to get data from sql server when i write my data into database i convert all datetime values of two tables into utc timepoll start poll end20130731 120 20130801 120andpick date20130731 120048020130731 1300120when i get the data in my outlook addin this is the correct resultwhen opening the same in my website the picks are finebut my start and end time are broken the offset is added bute the wrong hours are usedheres the code for my converting that both outlook and the website useprivate static void converttolocaltimepoll item itempoll start itempoll startfromutc itempoll end itempoll endfromutcprivate static void converttolocaltimepick pick if pickpick date null pickpick date datetimepickpick datefromutcand the implementation of datetimefromutcpublic static datetime fromutcthis datetime value var local timezoneinfolocal return timezoneinfoconverttimevalue timezoneinfoutc locali had the same result with datetimetolocaltimeanyone an ideaedit 1this is how the start and end gets thisplayed on the website end with end instead of startvar startcell new tablecell text stringformat a href0 title2 target blank1ddmmy hhmm utcza commongettimeanddatehyperlink pollstart vote start pollstart converttolocaltimezone cssclass infocontent and the picksanswercell new tablecell text stringformat a href0 title2 target blank1a commongettimeanddatehyperlinkaotime aorealanswer aorealanswer converttolocaltimezone aorealanswer returns the formated datetime stringreturn stringformatwholetime true 0d 0ddmmy hhmm utcz time,"['c#', 'asp.net']" +517006,atomic increment with entity framework i have a mysql server which i access using entity framework 40 in the database i have a table called works into which some counts i develop web site with aspnet this table acesable one more user same time and this situation causes wrong incerement problemmy code like thatdbentities myentity new dbentitiesvar currentwork myentityworkswherex xrid 208firstordefaultconsolewritelineaccess workif currentwork null consolewritelineaccess is not null currentworkwordcount 5default wordcount is 0 consolewritelinecount changed myentitysavechanges consolewritelinesave changesconsolewritelinecurrent count currentworkwordcountif one more than thread access the database same time only last changes remain current outputt1 thread one t2 thread twot1 access workt2 access workt2 access is not nullt1 access is not nullt1 count changedt2 count changedt1 save changest2 save changest1 current count 5t2 current count 5expected outputt1 access workt2 access workt2 access is not nullt1 access is not nullt1 count changedt2 count changedt1 save changest2 save changest1 current count 5t2 current count 10i know why apeear this problem because this code is not atomic how can i turn atomic operation,"['c#', 'asp.net', 'mysql']" +517026,dynamicmethod and type checks can someone explain or point to explanation why runtime types check not occurs in sample below string property can be set to any type value stuck with this in very unexpected place and was really surprisedusing systemusing systemreflectionusing systemreflectionemitnamespace dynamicsinternal class program private static void mainstring args var a new a aname name consolewritelineanamegettypename propertyinfo pi agettypegetpropertyname dynamicmethod method new dynamicmethod dynamicsetvalue name null return type new type typeofobject 0 objsource typeofobject 1 value parameter types typeofprogram owner true skip visibility ilgenerator gen methodgetilgenerator genemitopcodesldarg 0 genemitopcodesldarg 1 genemitopcodescall pigetsetmethodtrue genemitopcodesret setvalue setmethod setvaluemethodcreatedelegatetypeofsetvalue int val 123 setmethoda val consolewritelineanamegettypename a anothera new a anotheraname another a setmethoda anothera consolewritelineanamegettypename public class a public string name get set public delegate void setvalueobject obj object val,"['c#', '.net']" +517035,how to execute raw sql in sqlalchemyflask app how do you execute raw sql in sqlalchemyi have a python web app that runs on flask and interfaces to the database through sqlalchemy i need a way to run the raw sql the query involves multiple table joins along with inline views i have triedconnection dbsessionconnectionconnectionexecute sql here but i keep getting gateway errors,"['python', 'sql']" +517054,how to get current zoom level from google map for ios i use method camera with digital value like thiscamera gmscameraposition camerawithlatitude3735 longitude1220 zoom6and i need automatically redraw map with current position via timervoidgmapredraw nsloggmapredraw selfmapviewcamera locationmanager startupdatinglocation nsloglat f lon f locationmanagerlocationcoordinatelatitude locationmanagerlocationcoordinatelongitude camera gmscameraposition camerawithlatitudelocationmanagerlocationcoordinatelatitude373637813193386 longitudelocationmanagerlocationcoordinatelongitude12201449629815120 zoom6 selfmapviewcamera cameravoidtimer nstimer scheduledtimerwithtimeinterval05 targetself selectorselectorgmapredraw userinfonil repeatsyesbut how i can get current zoom if i change it via touch,['ios'] +517077,inheriting from themeappcompat currently working on migrating to actionbar in the support libraries currently trying to migrate my old themes to inherit from themeappcompatlightdarkactionbar but it is not going very smoothlyit is fine if i apply the theme in the manifest as suchactivity androidnamecomfitsbyloginactivity androidscreenorientationportrait androidthemestylethemeappcompatlightdarkactionbar activitybut i get a runtime error stating that loginactivitysubclass of actionbaractivity must have a theme which inherits from themeappcompat when i do the followingin stylesxmlstyle nameapptheme parentstylethemeappcompatlightdarkactionbar item nameandroidtypefacesansitem style and in the manifestactivity androidnamecomfitsbyloginactivity androidscreenorientationportrait androidthemestyleapptheme activityany ideas why that is happening i do not see a problem since apptheme clearly inherits from one of the appcompat themes,['android'] +517088,how to solve javalangnoclassdeffounderror i am pretty new to java and i have just started learning about packages in java i have tried both the example in oracles java tutorials they both compile fine but at runtime both come up with this errorexception in thread main javalangnoclassdeffounderror graphicsshapessquare at mainmainmainjava7caused by javalangclassnotfoundexception graphicsshapessquare at javaneturlclassloader1runurlclassloaderjava366 at javaneturlclassloader1runurlclassloaderjava355 at javasecurityaccesscontrollerdoprivilegednative method at javaneturlclassloaderfindclassurlclassloaderjava354 at javalangclassloaderloadclassclassloaderjava424 at sunmisclauncherappclassloaderloadclasslauncherjava308 at javalangclassloaderloadclassclassloaderjava357 1 morei think i might have the mainjava file in the wrong folder here is the directory hierarchygraphicsa mainjavaa shapes a squarejava a trianglejavaa linepoint a linejava a pointjavaa spaceobjects a cubejava a rectprismjavaand here is mainjavaimport graphicsshapesimport graphicslinepointimport graphicsspaceobjectspublic class main public static void mainstring args square s new square2315 line l new line1523 cube c new cube1332 what am i doing wrong hereany help would be appreciated thanksupdatethanks for the answers they really helpedafter i put put the main class into the graphics package i added package graphics to it set the classpath to test folder containing graphics compiled it and ran it using java graphicsmain from the command line it workedreally late update 2i was not using eclipse just notepad and the jdk and the above update solved my problem however it seems that many of these answers are for eclipse and intellij but they have similar conceptsthanks a lot for the answers,['java'] +517094,notification not getting shown in one of ios device i am facing problem with notification notification is not getting shown in device from last 12 hours it was working earlier sending to other devices works fine i checked notification center and other thing notification is enabled for app after following indexhtmli have enabled enabling push status messages on ios on console device is printing some information likeerror kdataattachstatusnotification sent wasattached 1 isattached 1what does it mean is it getting notification from server side and failing to show and receive due to some reason editafter syncing logs with itunes logs says something like20130801 105106 0530 apsd76 getclientidentity already had identity secidentityref some value herewasup no isup no linkqualitybelowandwowavail yes wantsinterfaceassertion yes avoidwwanoncall no20130801 105106 0530 apsd76 getclientidentity already had identity secidentityref some value here20130801 105106 0530 apsd76 peer68 received xpc error connection invalid,"['iphone', 'ios']" +517125,substring of variable length i have a table with a column which contains strings like below rtspp lz aenrtspp lz cpsrtspp lz houstonrtspp lz lcrartspp lz northrtspp lz raybnrtspp lz southrtspp lz westrtspp bte cc1 rtspp bte pun1 rtspp bte pun2i need to get the substring from the second occurrence of till the end of string and as you can see the substring is not of fixed length the first part is not always fixed it can change as of now i am using the following code to achieve it select substringstringcharindex stringcharindex string100from tableas you can see i am taking an arbitrary large value as the length to take care of variable length is there a better way of doing it,['sql'] +517146,ios adding observer to a uiviews frameoriginy i am trying to monitor and react to the changing value of the origin of a uiviews framemy codecellbottomview addobserverself forkeypathframeorigin optionsnskeyvalueobservingoptionnew contextnullvoidobservevalueforkeypathnsstring keypath ofobjectidobject changensdictionary change contextvoid context nslog changed keypathi am getting the following error message that i do not understandan instance 0x7587d10 of class nsconcretevalue was deallocated while key value observers were still registered with it observation info was leaked and may even become mistakenly attached to some other object set a breakpoint on nskvodeallocatebreak to stop here in the debugger heres the current observation infonskeyvalueobservationinfo 0x7587fd0 nskeyvalueobservance 0x7587f70 observer 0x7587bd0 key path origin options new yes old no prior no context 0x0 property 0x7587ff0really i am only interested in the y position of the origin but the code would not even compile if i set the keypath to frameoriginyif i set the keypath to simply frame there are no errors but the method observevalueforkeypath never gets called i guess a change to a frames origin does not count as a change to the framehow do i accomplish adding an observer to a uiviews frameoriginy,['ios'] +517155,get product flavor or build variant in an android app i have an android app with a number of different product flavors configured in my buildgradle file egproductflavors someflavor anotherflavor in my application code i want to be able to get hold of the name of the currently compiled flavor or build variant one solution is thisproductflavors someflavor buildconfig public static final string product flavor someflavor anotherflavor buildconfig public static final string product flavor anotherflavor and then in my android app call buildconfigproduct flavoris there some way i can get gradle to do this automatically or is there some other api in android i can use to get the product flavor name,['android'] +517194,google maps ios sdk integration not loading maps i am using google maps ios sdk in my iphone application i am showing a place mark on the map and it is working fine in my iphone device using my apple developer account certificates but when i sent build to testing team using a different enterprise apple developer account certificatesenterprise account the maps are not loading up it only shows the place mark on a blank screen with the maps loading upi have also tried on my iphone devices with the enterprise apple developer account and it is not loading the mapjust a pin on blank screen but with my own apple developer account certificates it is working absolutely fine i am assuming that the problem is in enterprise apple developer accountmight be i have change some settings on apple developer account for my app id i am not able to find out a solution for this can anybody help me out on this if you need more information on this please ask me in a comment thanks in advance,"['iphone', 'ios', 'objective-c']" +517201,pandas looking up the list of sheets in an excel file the new version of pandas uses the following interface to load excel filesread excelpath to filexls sheet1 index colnone na valuesnabut what if i do not know the sheets that are available for example i am working with excel files that the following sheetsdata 1 data 2 data n foo barbut i do not know n a prioriis there any way to get the list of sheets from an excel document in pandas,['python'] +517239,invisible characters ascii is there any invisible character exist i have checked google for invisible characters i end up with many answers but not sure about those can someone in so tell me about it also i have checked a profile in facebook and found that the user do not have any name to his profile how come it is possible is it any database issue hacking or some thingwhen i searched over internet found 200d is an ascii value with invisible character is it true refer linkfb profiledo know me is it a valid question to ask here else i can remove it i felt confusing that is why asked,['php'] +517248,angularjs need some combination of routechangestart and locationchangestart my problem is actually very similar to the one found hereangularjs cancel route change eventin short i am using routechangestart and trying to change the current route using location when i do the console shows me that the original page is still loads and is quickly overwritten by the new pagethe solution provided was to use locationchangestart instead of routechangestart which should work for preventing the extra redirect unfortunately i am using additional data in the routeprovider that i need to access while changing the route i use it to track page restrictions heres an examplerouteprovider whenlogin controller loginctrl templateurl apartialloginhtml access false whenhome controller homectrl templateurl apartialhomehtml access true otherwise redirectto login rootscopeonroutechangestart functionevent next current ifnextaccess do stuff else locationpathlogin this will load the current route first ie home and then redirect the user to the correct login route with routechangestart i can use the next and current parameters see angularjs route as objects to retrieve my access values with locationchangestart those two parameters return url strings not objects so there seems to be no way to retrieve my access valuesis there any way i can combine the redirectstopping power of locationchangestart with the objectflexibility of routechangestart to achieve what i need,['javascript'] +517275,jgit pull noheadexception when is try to execute the following method uses jgit library private void pullrepo throws ioexceptiongitapiexception wrongrepositorystateexception invalidconfigurationexception detachedheadexception invalidremoteexception canceledexception refnotfoundexception noheadexception git git new gitlocalrepo gitpullcall i get the following runtime exceptionorgeclipsejgitapierrorsnoheadexception pull on repository without head currently not supportedat orgeclipsejgitapipullcommandcallpullcommandjava161does someone know how to solve thisthe localrepo i use is the same as i use for the clonerepository method which works perfectlythanksbgvv1983,['java'] +517303,pass by reference constant reference rvaluereference or constant rvaluereference i was learning passing by reference and here is the test i didinclude iostreamusing namespace stdint i 0if this is uncommented compiler gives ambiguous definition errorvoid paramcheck string s cout i param is varnvoid paramcheck const string s cout i param is const refnvoid paramcheck string s cout i param is nonconst refnvoid paramcheck const string s cout i param is const rvaluereferencenvoid paramcheck string s cout i param is nonconst rvaluereferencenint mainint argc char argv function call test paramcheck paramcheckstring string s3 paramchecks3 const string s4 paramchecks4 illegal string s paramchecks const string s5s3 paramchecks5 string s6 paramchecks6 illegal const string ss1 onstfps reference test string a s3 a a changed s3 cout s3 string b s3 b b changed after assigning s3n cout s3 is now s3 b s4 b b changed after assigning s4n cout s3 is now s3 cout s4 is now s4 cinget return 0and here is the result i get1 param is nonconst rvaluereference2 param is nonconst rvaluereference3 param is nonconst ref4 param is const ref5 param is const ref6 param is nonconst refs3 is now b changed after assigning s3s3 is now b changed after assigning s4s4 is nowmy question isif we pass a constant expression it always triggers nonconstant rvaluereference under what condition it will trigger constant rvaluereference and why s6 is not trigging itwhy nonconstant reference and constant rvaluereference are illegali expected a cannot change s3 but why b in the inner scope can change s3 if assigning a new object s3 to b is assigning a new reference why when i assign s4 to it and s3 got changed and s4 is empty afterwardssorry for asking too many questions i will increase the points when all questions are answered the reference just brings my confusion from pointer to a whole new leveli do not know how to increase the point so will wait for 2 days till eligible for bounty then choose the answer,['c++'] +517355,javalangclassnotfoundexception for servlet in tomcat with eclipse i am starting to develop a java web application in eclipse using servlets and am testing it with tomcat server on my localhost i have deployed the application in tomcat but when i try to load the target url in my browser i get the following stack trace jul 31 2013 25831 pm orgapachecatalinacoreapplicationcontext loginfo marking servlet imageservlet as unavailablejul 31 2013 25831 pm orgapachecatalinacorestandardwrappervalve invokesevere allocate exception for servlet imageservletjavalangclassnotfoundexception testimageservlet at orgapachecatalinaloaderwebappclassloaderloadclasswebappclassloaderjava1714 at orgapachecatalinaloaderwebappclassloaderloadclasswebappclassloaderjava1559 at orgapachecatalinacoredefaultinstancemanagerloadclassdefaultinstancemanagerjava527 at orgapachecatalinacoredefaultinstancemanagerloadclassmaybeprivilegeddefaultinstancemanagerjava509 at orgapachecatalinacoredefaultinstancemanagernewinstancedefaultinstancemanagerjava137 at orgapachecatalinacorestandardwrapperloadservletstandardwrapperjava1144 at orgapachecatalinacorestandardwrapperallocatestandardwrapperjava865 at orgapachecatalinacorestandardwrappervalveinvokestandardwrappervalvejava136 at orgapachecatalinacorestandardcontextvalveinvokestandardcontextvalvejava123 at orgapachecatalinaauthenticatorauthenticatorbaseinvokeauthenticatorbasejava502 at orgapachecatalinacorestandardhostvalveinvokestandardhostvalvejava171 at orgapachecatalinavalveserrorreportvalveinvokeerrorreportvalvejava99 at orgapachecatalinavalvesaccesslogvalveinvokeaccesslogvalvejava953 at orgapachecatalinacorestandardenginevalveinvokestandardenginevalvejava118 at orgapachecatalinaconnectorcoyoteadapterservicecoyoteadapterjava408 at orgapachecoyotehttp11abstracthttp11processorprocessabstracthttp11processorjava1023 at orgapachecoyoteabstractprotocolabstractconnectionhandlerprocessabstractprotocoljava589 at orgapachetomcatutilnetaprendpointsocketprocessorrunaprendpointjava1852 at javautilconcurrentthreadpoolexecutorrunworkerunknown source at javautilconcurrentthreadpoolexecutorworkerrununknown source at javalangthreadrununknown source the imageservlet class is quite clearly located in the myprojectsrctest folder in my eclipse workspace where myproject is the name of the eclipse project and test is the package webxml is located in myprojectwebwebinfwebxml and myprojectxml is located at myprojectmyprojectxml the contents of webxml are xml version10webapp xmlnsxmlnsxsixsischemalocation 2 4xsdversion24 servlet servletnameimageservletservletname servletclasstestimageservletservletclass servlet servletmapping servletnameimageservletservletname urlpatternimageurlpattern servletmappingwebappand the contents of myprojectxml arecan anyone show me how to fix my code so that it does not throw the classnotfoundexception,['java'] +517468,angular animate ngcloak opacity i cannot seem to animate ngcloak essentially i am trying to animate a div from containterngcloak to containerngbindingbut it does not seem to workaangular loads the div with container ngbinding classes straight away ignoring the transition rulei even tried using transitiondelay set to a couple seconds no dice htmldiv classcontainer ngcloak ngcontrollerappctrlcsscontainerngcloakcontainerngbinding opacity 0 transition opacity 800ms easeinoutcontainerngbinding opacity 1worth notingtransitioning backgroundcolor from blue to red seemed to work as expectedi omitted vendorprefixes for the sake of brevitythanks in advance,"['html', 'css']" +517471,how can i get the applications icon from the package name i have tried various solution from stack overflow with no luck what i wanti know package name of different applicationsi want to get application icon from those package nameshow those icons in image viewfor example i have a package name comexampletestnotification how to get this apps icon and show it in an imageview,['android'] +517490,how to instantiate an object in java i am new in programming and i would like to know where did i go wrong in instantiating an object below is the codepublic class testing private int sampleint c int a 1 int b 2 c a b return c public static void mainstring args sample mytest new sample systemoutprintlnc,['java'] +517498,datagridcolumn with header already exists in the columns collection of a datagrid i have a wpf application with mvvm pattern in one of my view i have to bind an observablecollection to view in that view i have one listbox and one datagrid both bind to the same observablecollection but doing different things like events style etc i need only one of these controls thisplayed at a time and what i did is created two user controls one for datagrid and other for listbox and i switched between them by placing a contentcontrol on the main viewsomething similar to this blog the default view is datagrid and when click on a button the other view is thisplayedie listbox up to this are working fine one more thing to keep in mind that the data grid columns are generated dynamically by using the solution described in the following link so when i go back to datagrid view it is throwing an error while adding columns to data grid in foreach statement pls refer the answer of the previous link like datagridcolumn with header ord already exists in the columns collection of a datagrid datagrids cannot share columns and cannot contain duplicate column instancesbut i am sure that before adding columns to datagrid its count property is zerodatagridcolumnscount so how the datagrid header properties are persisted is there any way to clear the header valuesplease suggest,['c#'] +517528,combine get and post request methods in spring i have a resource that supports both get and post requests here a sample code for a sample resourcerequestmappingvalue books method requestmethodgetpublic modelandview listbooksmodelattributebooksfilter booksfilter filter two requestparam parameters httpservletrequest request throws parseexception long coderequestmappingvalue books method requestmethodpostpublic modelandview listbookspostmodelattributebooksfilter booksfilter filter bindingresult result throws parseexception same long code with a minor differencethe code in the two methods is practically the same except for lets say a variable definition the two methods can be easily combined using method requestmethodpost requestmethodget and a simple if inside i tried but it does not work because the two methods have a different parameter at the end ie httpservletrequest and bindingresult the requestparams are not required and therefore not needed in the post request any ideas how to combine the two methods,['java'] +517571,forloop performance storing array length in a variable consider two versions of the same loop iterationfor var i 0 i nodeslength i andvar len nodeslengthfor var i 0 i len i is the latter version anyhow faster than the former one,['javascript'] +517615,scanning a list i need to scan a list in python i am able to load it from file and do simple operation but i was trying to do the followingl 12345678starting from the first element i want to produce the following output1 2345678 345678 45678 5678 678 78 82 345678 45678 5678 678 78 83 45678 5678 678 78 84 5678 678 78 8and so oni was trying something like thisfo opensysargv1 rl foreadlinesfor i in rangelenl print strli for j in rangelenl1i print strlij1could you help me,['python'] +517684,getting a pages complete source using javascript i am trying to capture and post all js errors in a page to a django view i am doing something like thisscript windowonerror functionerrormsg file linenumber post data error errormsg file file location windowlocationhref linenumber linenumber ua navigatoruseragent jquerypostjs errors post data scriptthe question i would like to add the actual line as well how do i get the line from the page source given the line numberso far i have tried this accounting for all kinds of newline charactersdocumentgetelementsbytagnamehtml0outerhtmlsplitrnlinenumberhowever this does not give me the correct line number what am i missing here,"['javascript', 'jquery', 'html']" +517687,installing python packages in nitrousio i have just started trying to use nitrousio i have made a box with python and am trying to use pip to install a python package called praw it downloads all of the information fine but on running the install script i get an error stating that it could not create a file due to permission restrictions in the usr directory is there any way to get around this as i need the package for my application to work properly,['python'] +517698,dlls loaded from wrong aplicationbase when trying to load mixed c and ccli dlls in a new appdomain we have a large net solution with both c and ccli projects which reference each other we also have several unit testing projects weve recently upgraded from visual studio 2010 net 40 to visual studio 45 net 45 and now when we try to run the unit tests there seem to be a problem loading some of the dlls during the testthe problem appears to happen because unit testing is performed on a separate appdomain the unit testing process for example nunitagentexe creates a new appdomain with appbase set to the test projects location but according the fusion log some of the dlls are loaded with nunit is executables directory as the appbase instead of the appdomains appbasei have managed to reproduce the problem with a simpler scenario which creates a new appdomain and tries to run the test there heres how it looks i changed the names of the unit test classes methods and the location of the dll to protect the innocentclass program static void mainstring args var setup new appdomainsetup applicationbase cdirectoryofmyunittestdll appdomain domain appdomaincreatedomainmydomain null setup objecthandle handle activatorcreateinstancefromdomain typeoftestrunnerassemblycodebase typeoftestrunnerfullname testrunner runner testrunnerhandleunwrap runnerrun appdomainunloaddomain public class testrunner marshalbyrefobject public void run try htmltransformerunittest test new htmltransformerunittest testsetup testtransform httpequiv refresh timeout catch exception e consolewritelinee this is the exception i get when trying to execute the unit test as you can see the problem happens the the c dll is initialized and tries to load the c dll i changed the names of the dlls involved to cplusplusdll and csharpdllsystemtypeinitializationexception the type initializer for threw an exception moduleloadexceptionhandlerexception a nested exception occurred after the primary exception that caused the c module to fail to load systemtypeinitializationexception the type initializer for threw an exception moduleloadexception the c module failed to load during vtable initialization systemiofilenotfoundexception could not load file or assembly csharpdll version880 cultureneutral publickeytokennull or one of its dependencies the system cannot find the file specified at a0xb992d574 e 7cappletactioncplusplusdllsomenamespace6bymxxz at initterm mfnptr pfbegin fnptr pfend in fddvctoolscrt bldself x86crtsrcpuremsilcodecppline 219 at languagesupportinitializevtableslanguagesupport in fddvctoolscrt bldself x86crtsrcmstartupcppline 331 at languagesupport initializelanguagesupport in fddvctoolscrt bldself x86crtsrcmstartupcppline 491 at languagesupportinitializelanguagesupport in fddvctoolscrt bldself x86crtsrcmstartupcppline 702 end of inner exception stack trace at throwmoduleloadexceptionstring errormessage exception innerexception in fddvctoolscrt bldself x86crtsrcminternalhline 194 at languagesupportinitializelanguagesupport in fddvctoolscrt bldself x86crtsrcmstartupcppline 712 at cctor in fddvctoolscrt bldself x86crtsrcmstartupcppline 754 end of inner exception stack trace at systemruntimeinteropservicesmarshalthrowexceptionforhrinternalint32 errorcode intptr errorinfo at systemruntimeinteropservicesmarshalthrowexceptionforhrint32 errorcode at docallbackindefaultdomainintptr function void cookie in fddvctoolscrt bldself x86crtsrcminternalhline 406 at defaultdomaininitialize in fddvctoolscrt bldself x86crtsrcmstartupcppline 277 at languagesupportinitializedefaultappdomainlanguagesupport in fddvctoolscrt bldself x86crtsrcmstartupcppline 342 at languagesupport initializelanguagesupport in fddvctoolscrt bldself x86crtsrcmstartupcppline 539 at languagesupportinitializelanguagesupport in fddvctoolscrt bldself x86crtsrcmstartupcppline 702 end of inner exception stack trace at thrownestedmoduleloadexceptionexception innerexception exception nestedexception in fddvctoolscrt bldself x86crtsrcminternalhline 184 at languagesupportcleanuplanguagesupport exception innerexception in fddvctoolscrt bldself x86crtsrcmstartupcppline 662 at languagesupportinitializelanguagesupport in fddvctoolscrt bldself x86crtsrcmstartupcppline 710 at cctor in fddvctoolscrt bldself x86crtsrcmstartupcppline 754 end of inner exception stack trace this is what i am seeing in the fusion log i have changed the name of the dll to somedlldll instead of the original assembly binder log entry 812013 014748 pm the operation failedbind result hr 0x800702 the system cannot find the file specifiedassembly manager loaded from cwindowsmicrosoftnetframeworkv4030319clrdllrunning under executable cusersyshanydocumentsvisual studio 2012projectsmytestermytesterbindebugmytesterexe a detailed error log follows prebind state information log user wfilyshanylog thisplayname somedll version880 cultureneutral publickeytokennull fullyspecifiedlog appbase filecusersyshanydocumentsvisual studio 2012projectsmytestermytesterbindebuglog initial privatepath nulog dynamic base nulog cache base nulog appname mytesterexecalling assembly unknownlog this bind starts in default load contextlog using application configuration file cusersyshanydocumentsvisual studio 2012projectsmytestermytesterbindebugmytesterexeconfiglog using host configuration file log using machine configuration file from cwindowsmicrosoftnetframeworkv4030319configmachineconfiglog policy not being applied to reference at this time private custom partial or locationbased assembly bindlog attempting download of new url filecusersyshanydocumentsvisual studio 2012projectsmytestermytesterbindebugsomedlldlog attempting download of new url filecusersyshanydocumentsvisual studio 2012projectsmytestermytesterbindebugsomedllsomedlldlog attempting download of new url filecusersyshanydocumentsvisual studio 2012projectsmytestermytesterbindebugsomedllexelog attempting download of new url filecusersyshanydocumentsvisual studio 2012projectsmytestermytesterbindebugsomedllsomedllexelog all probing urls attempted and failedas you can see the problem is that the appbase is where mytesterexe resides instead of where somedlldll resides which is the same location as the unit test dll this happens for several dlls including both of the dlls mentioned in the exception abovei also tried to reproduce with a simpler unit test project a small vs2012 solution with 3 projects a c project which references a ccli project which references another c project but the problem did not reproduce and it worked perfecty as i mentioned before the unit tests were ok before we upgraded to vs2012 net 45what can i dothanks,['c#'] +517742,why do i need to synchronize a list returned by collectionssynchronizedlist i found this at dosoraclecompublic static list synchronizedlistlist listreturns a synchronized threadsafe list backed by the specified list in order to guarantee serial access it is critical that all access to the backing list is accomplished through the returned list it is imperative that the user manually synchronize on the returned list when iterating over it list list collectionssynchronizedlistnew arraylist synchronizedlist iterator i listiterator must be in synchronized block while ihasnext fooinext my question is why do i have to synchronize the list to iterate it if collectionssynchronizedlist is supposed to return an already synchronized list im just accesing the list in two threads one thread just add and the other thread to get and delete what other classes you recommend to use for this scenario thanks for reading,['java'] +517750,open external links in the browser with android webview i have this code but not because it works it keeps opening in webview and what i want is that the links do not belong to my website open in your default browser any idea thanksprivate class customwebviewclient extends webviewclient override public boolean shouldoverrideurlloadingwebview view string url ifurlcontainsmessage2spaceesvu viewloadurlurl return true else return supershouldoverrideurlloadingview url,['android'] +517763,best practice to prevent further instantiation of java classes i have some class storing keys with important information no one else is allowed to create a key since a key relys on static information like certain directory structures etcpublic final class keyconstants private keyconstants could throw an exception to prevent instantiation public static final keymyclass my class data new keymyclasomeid myclassclass public static class keyt public final string id public final classt clazz private keystring id classt clazz thisid id thisclazz clazz this example is simplyfiedi wanted to test the consequences of a wrong key exception handling etc and instantiated the class via reflection in a junit test caseconstructor c keyconstantskeyclassgetdeclaredconstructorstringclass classclasscsetaccessibletruesuppresswarnings uncheckedkeyconstantskeymyclass r keyconstantskeymyclass cnewinstancewrongid myclassclassthen i asked myself how could i prevent further instantiation of the key class i e preventing further object creating via reflectionenums came to my mind but they do not work with genericspublic enum keyt syntax error enum declaration cannot have type parametersso how can i keep a set of n instances of a generic class and prevent further instantiation,['java'] +517810,array map inline anonymous function i tested inline anonymous function with array map hereand it worked but when i tried same with user meta it is not working user meta array interest array 0 array type array 0 array user status array 0 deny firstname array 0 lastname array 0 b email user meta array mapfunctiona return a0 user metaparse error syntax error unexpected t function expecting inhere is the test link showing error,['php'] +517833,multidimensional arrays with different sizes i just had an idea to test something out and it worked string arr new string44 arr2 new string5 forint i 0 i arrlength i systemoutprintlnarrilength the output obviously is4454so my questions areis this good or bad style of codingwhat could this be good forand most of all is there a way to create such a construct in the declaration itselfalso why is it even possible to do,['java'] +517845,sql get all records older than 30 days now i have found a lot of similar so questions including an old one of mine but what i am trying to do is get any record older than 30 days but my table field is unix timestamp all other examples seem to use datetime fields or something tried some and could not get them to workthis definitely does not work below also i do not want a date between a between date i want all records after 30 days from a unix timestamp stored in the database i am trying to prune inactive userssimple examples does not work select from profiles where last login unix timestampnow interval 30 day and tried thisselect from profiles where unix timestamplast login interval 30 day not too strong at complex date queries any help is appreciate even though the question was accepted i do not like trigger happy people closing the question as a duplicate it is clearly not a duplicate because i did not ask what the alternative to the mysql function is i asked exactly how to get records older than 30 days and that duplicate question does not answer that or even show me how to get it i think people need to read the questions,['sql'] +517846,android map api v2 not showing map on some devices i am developing an android application showing a mapi am using a mapfragment in which i thisplay my mapi obtained an api key and added all the needed permissions to my manifestso far so good everything works fine when debugging the app on my htc one s on android 412 the map shows including controls and everything elsewhen i debug the same application on my galaxy s4 running android 422 the map stays blank and only controls showinternet connection is definitely availablewhy is that the caseis there any difference between android 41 and 42 concerning the v2 map apiis there any difference between samsung and htc concerning the issuedo i need a new key for some devicesthe error message i get on the galaxy s4 is failed to load map could not contact google serviceshere is my manifestusessdk androidminsdkversion14 androidtargetsdkversion18 usespermission androidnameandroidpermissioninternetusespermission androidnameandroidpermissionwrite external storageusespermission androidnameandroidpermissionaccess network stateusespermission androidnameandroidpermissionaccess wifi stateusespermission androidnamecomgoogleandroidprovidersgsfpermissionread gservices usespermission androidnameandroidpermissionaccess coarse location usespermission androidnameandroidpermissionaccess fine location usespermission androidnamecommypackagepermissionmaps receive androidprotectionlevelsignaturepermission androidnamecommypackagepermissionmaps receive androidprotectionlevelsignature usesfeature androidglesversion0x020 androidrequiredtrue metadata androidnamecomgoogleandroidmapsv2api key androidvaluemyobtainedkey again everything works fine on my htc one s i am looking for the reason why the map is not loading on the s4things i already trieduninstall the app and reinstall it againupdate reinstall google play servicesuse wifi only use data connection onlyrestart the deviceclean the project,['android'] +517888,how jvm finds method parameter with the closest matching to call in case of function overloading the jvm decides which overloaded method to call at compile time i have one examplepublic class mainclass public static void golong n systemoutprintlntakes long public static void goshort n systemoutprintlntakes short public static void goint n systemoutprintlntakes int public static void mainstring args short y 6 long z 7 goy goz goshorty according to my understanding it should print the followingtakes shorttakes longtakes short but the actual output istakes inttakes longtakes shorthowever if i have the following three functions public static void gointeger n systemoutprintlntakes integerpublic static void golong n systemoutprintlntakes long public static void goshort n systemoutprintlntakes short and call it usingint a 10 and goi output takes integer why there is there a difference for short and int,['java'] +517905,no outline on mouse focus but still have outline on keyboard focus when elements of a page have focus such as a link or button they show an outline i would like this outline to only thisplay when that element was given focus by the keyboard not by the mouseis it possible to determine how that element got its focus with javascript if so how do i then control the browsers own outlining feature,"['javascript', 'jquery', 'html', 'css']" +517948,java generic methods in generics classes if you create a generic class in java the class has generic type parameters can you use generic methods the method takes generic type parametersconsider the following examplepublic class myclass public k k dosomethingk k return k public class mygenericclasst public k k dosomethingk k return k public k listk makesingletonlistk k return collectionssingletonlistk as you would expect with a generic method i can call dosomethingk on instances of myclass with any objectmyclass clazz new myclastring string clazzdosomethingstringinteger integer clazzdosomething1however if i try to use instances of mygenericclass without specifying a generic typei calling dosomethingk returns an object regardless of what k was passed inmygenericclass untyped new mygenericclass this does not compile incompatible types required string found objectstring string untypeddosomethingstringoddly it will compile if the return type is a generic class eg listk actually this can be explained see answer belowmygenericclass untyped new mygenericclassliststring list untypedmakesingletonliststring this compilesalso it will compile if the generic class is typed even if only with wildcardsmygenericclass wildcard new mygenericclastring string wildcarddosomethingstring this compilesis there a good reason why calling a generic method in an untyped generic class should not workis there some clever trick relating to generic classes and generic methods that i am missingeditto clarify i would expect an untyped or rawtyped generic class not to honour the generic clas type parameters because they have not been provided however it is not clear to my why an untyped or rawtyped generic class would mean that generic methods are not honoured it transpires that this issue has already been raised on so cf this question the answers to this explain that when a class is untyped in its rawform all generics are removed from the class including typing of generic methodshowever there is not really an explanation as to why this is the case so allow me to clarify my questionwhy does java remove generic method typing on untyped or rawtype generic classes is there a good reason for this or was it just an oversightedit thiscussion of jlsit has been suggested in answer to the previous so question and to this question that this is treated in jls 48 which statesthe type of a constructor a88 instance method a84 a94 or nonstatic field a83 m of a raw type c that is not inherited from its superclasses or superinterfaces is the raw type that corresponds to the erasure of its type in the generic declaration corresponding to c it is clear to me how this relates to an untyped class the class generic types are replaced with the erasure types if the class generics are bound then the erasure type corresponds to those bounds if the they are not bound then the erasure type is object eg unbound class typespublic class mygenericclasst public t dosomethingt t return t mygenericclass untyped new mygenericclassobject t untypeddosomethingstring bound class typespublic class myboundedgenericclasst extends number public t dosomethingt t return t myboundedgenericclass bounded new myboundedgenericclassobject t1 boundeddosomethingstring does not compilenumber t2 boundeddosomething1 does compilewhilst generic methods are instance methods it is not clear to me that jls 48 applies to generic methods the generic methods type k in earlier example is not untyped as it is type is determined by the method parameters only the class is untyped rawtyped,['java'] +517952,cordova webview timeout error with android i am trying a simple application where i want to thisplay my mobile website inside a native wrapper in android i am following the documentation where the only change i am making is with loadurl where instead of loading the cordovawebview with indexhtml from assets folder i will be pointing it to a mobile website say the webview app comes up but there isn a cordovawebview timeout error received following are the snippets from my codepublic class cordovawebviewactivity extends activity implements cordovainterface private cordovawebview webview private static final string tag cordova webview activity override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity cordova web view webview cordovawebviewfindviewbyidridwebview webviewloadurl override public activity getactivity return this other overrided methods from interfaceand when i run the code i get the following error in my console ddms0731 205608737 ddalvikvm2016 gc for alloc freed 42k 6 free 2780k2928k paused 23ms total 25ms0731 205608746 idalvikvmheap2016 grow heap frag case to 3887mb for 1127536byte allocation0731 2056087 ddalvikvm2016 gc for alloc freed 2k 4 free 3879k4032k paused 36ms total 36ms0731 205608836 dcordovawebview2016 cordovawebview is running on device made by unknown0731 205608836 djsmessagequeue2016 set nativejs mode to 20731 205608996 dgralloc goldfish2016 emulator without gpu emulation detected0731 205609376 ecutilstrace2016 error opening trace file no such file or directory 20731 205609687 dtilesmanager2016 starting tg 0 0x2a26cc400731 205628874 ecordovawebview2016 cordovawebview timeout errori have configxml in my resxml folder that has the followingxml version10 encodingutf8widget idiocordovahellocordova version200 xmlns namehello cordovaname description a sample apache cordova application that responds to the deviceready event description author email href apache cordova team author content srcindexhtml feature nameapp param nameandroidpackage valueorgapachecordovaapp feature access origin preference nameusebrowserhistory valuetrue preference nameexitonsuspend valuefalse preference namefullscreen valuetrue preference namewebviewbounce valuetrue widgetand i also have a cordovaxml in my resxml folderxml version10 encodingutf8cordova access origin allow local pages access origin log leveldebug preference nameusebrowserhistory valuefalse cordovaplease help what am i missing or doing wrong,['android'] +517954,are flexible array members really necessary a struct with a flexible array member apparently is not intended to be declared but rather used in conjunction with a pointer to that struct when declaring a flexible array member there must be at least one other member and the flexible array member must be the last member in that struct let us say i have one that looks like thisstruct example int n int flm then to use it i will have to declare a pointer and use malloc to reserve memory for the structures contents struct example ptr mallocsizeofstruct example 5sizeofint that is if i want my flm array to hold five integers then i can just use my structlike thisptrflm0 1 my question is should not i be able to just use a pointer instead of this not only would it be compatible prec99 but i could use it with or without a pointer to that struct considering i already have to use malloc with the flm should not i just be able to do thisconsider this new definition of the example struct struct example int n int notflm struct example test 4 mallocsizeofint 5 i would even be able to use the replacement the same way as the flexible array member would this also work provided the above definition of example with notflmstruct example test testn 4 notflm mallocsizeofint 5,['c'] +517987,flaskadmin blueprint creation during testing i am having trouble with the creation of blueprints by flaskadmin when i am testing my appthis is my view class using sqlalchemy all views that only admins are allowed to see should inherit from this classclass authviewmodelview def is accessibleself return current useris adminclass userviewauthview column list name email role codethis is how i initialize the views flaskadminadminadd viewuserviewuser dbsessionadmininit appapphowever when i try to run more then one test the fault always occurs on the second test and all the other tests that follow i always get following error messageerror test send email teststest viewstestusertraceback most recent call last file libpython27sitepackagesnosecasepy line 133 in run selfruntestresult file libpython27sitepackagesnosecasepy line 151 in runtest testresult file libpython27sitepackagesflask testingpy line 72 in call self pre setup file libpython27sitepackagesflask testingpy line 80 in pre setup selfapp selfcreate app file teststest initpy line 27 in create app app create apptestconfig file fboneapy line 41 in create app configure extensionsapp file fboneapy line 98 in configure extensions adminadd viewuserviewuser dbsession file libpython27sitepackagesflask adminbasepy line 484 in add view selfappregister blueprintviewcreate blueprintself file libpython27sitepackagesflaskapy line 62 in wrapper func return fself args kwargs file libpython27sitepackagesflaskapy line 885 in register blueprint blueprint selfblueprintsblueprintname blueprintnameassertionerror a blueprints name collision occurred between flaskblueprintsblueprint object at 0x110576910 and flaskblueprintsblueprint object at 0x1103bd3d0 both share the same name userview blueprints that are created on the fly need unique namesthe strange thing is that this only happens on the second test and never when i just run the appwhen i debugged the tests the first time it did exactly what i expected and added the blueprint to the app after the init appapp the second time however the process immediately stopped when reaching the add view step which i think is strange because the blueprints get registered in the init appapp call,['python'] +518041,desktop api is not supported on the current platform i have encountered this errorjavalangunsupportedoperationexception desktop api is not supported on the current platformi would open a file from my java application i use this method desktopgetdesktopopennew filereporthtmlhow can i solve this problem,['java'] +518046,how difficult is sourcelevel detection of arrays of runtime bounds the accepted proposal for runtimesized arrays with automatic storage duration n3639 asserts thatstack overflow becomes more likely in particular if the size depends on external input and is not properly checked some environments might therefore prohibit the use of the feature such a prohibition can be easily enforced with a static analysis tooli do not consider enforcement to be easy if it requires the analyzer to implement a full c compilerconsider the following codetemplatetypename tinline void array user const t x int aftraitstomegait looks to me like the analysis needs to be repeated for each use of array usert and considerapplicable specializations of traitst thiscoverable at the point of use of array usertwhether traitstomega is a compiletime constant expression either via constexpr or c03 approaches such as enumthe type of traitstomegawhether the applicable overload of f at the point of use of array usert and possibly found via adl is constexpram i missing something is it possible to enforce such a restriction without going through full compilationcan code be written in such a way to simplify verification of nonuse of runtime bounds,['c++'] +518077,are there practical uses of c11s garbage collection abi c11 introduced an interface to garbage collectors from what i see it provides a standardized way to communicate with the gc eg declare no pointers and to get information about how thisguised pointers are handled eg get pointer safetyhowever there is no standardized way in c11 yet to allocate a raw block of memory which you do not have to free manually there are use cases where that would help even if destructors are not called one example is to implement efficient concurrent data structures as mentioned by herb sutter without having to deal with complicated cleanup protocolsso far so good my question from the perspective of an ordinary develper not a gc library developeris there a realworld example where the new c11 gc interface has helped youat least from my perspective the world has not changed if you need gc you still have to find a nonstandard library for example boehm gc and learn how to integrate and use it the new standardized interface would not help very much in that respect it will also not solve portability issuesin the long term the common interface defined by the c11 standard hopefully pays off however my question targets only the immediate future,['c++'] +518109,calling superclass constructors in python with different arguments class a def init self x y selfx x selfy yclass b def init self z0 selfz z class abab def init self x y z0 how can i make the constructor of ab call the constructors for a and b with the proper argumentsi have triedclass abab def init self x y z0 a init xy b init zbut this gives me an error,['python'] +518127,ios autolayout causing uiscrollview to not scroll i have set up a uiscrollview with which i want to thisplay 12 images only 8 fit on screen laid out horizontally in the following image you can see the problem i am having which makes my scroll view not scroll my constraints and the uiscrollview which i have added on storyboardi have called the following method on voidviewdidload where i set upmy scrollview itemlist is my scroll view property and itemnames a array with the imagesnames voidsetuphorizontalscrollview selfitemlistdelegate self selfitemlist settranslatesautoresizingmaskintoconstraintsno selfitemlist setbackgroundcoloruicolor blackcolor selfitemlist setcancancelcontenttouchesno selfitemlistindicatorstyle uiscrollviewindicatorstylewhite selfitemlistclipstobounds no selfitemlistscrollenabled yes selfitemlistpagingenabled no nsinteger tot0 cgfloat cx 0 for tot if tot12 break uiimageview imageview uiimageview alloc initwithimageuiimage imagenamedselfitemnames objectatindextot cgrect rect imageviewframe rectsizeheight 40 rectsizewidth 40 rectoriginx cx rectoriginy 0 imageviewframe rect selfitemlist addsubviewimageview cx imageviewframesizewidth selfitemlist setcontentsizecgsizemakecx selfitemlist boundssizeheighti have added the selfitemlist settranslatesautoresizingmaskintoconstraintsno because i saw this suggestion on other posts but it does not work with or without it the only way it works is if i uncheck use autolayout on the storyboard but that moves the uiimageviewi use to look as a navigation bar to the bottom of the screeni do not know what to do anymore any help is appreciated,['ios'] +518146,how to change font size in html i am trying to make a website and i want to know how to change the size of text in a paragraph i want paragraph 1 to be bigger than paragraph 2 it does not matter how much bigger as long as it is bigger how do i do thismy code is belowhtmlheadstyle p color red styleheadbodypparagraph 1paragraph 2pbodyhtml,['html'] +518182,nodejsexpressjs app only works on port 30 i have a nodejsexpressjs app running on my server that only works on port 30 and i am trying to figure out why heres what i have foundwithout specifying a port applisten the app runs but the web page does not loadon port 3001 applisten3001 or any other port that is not in use the app runs but the web page does not load on port 29 the app throws an error because something else is using that porton port 30 the app runs and the web page loads finei know that express apps default to port 30 but strangely my app only runs when i explicitly make it run on port 30 applisten30i found this on line 220 of usrbinexpressappsetport processenvport 30which is doing as previously stated setting the port to what is specified or to 30 if nothing is specifiedhow could i make my app work on a different port such as 8080 or 3001thanksedit code sample very simple nodeexpress appvar express requireexpressvar app expressappget functionreq res ressendhello world only works on 30 regardless of what i set environment port to or how i set value in appsetport valueapplisten30,['javascript'] +518205,how to increase transportdump size from 256 bytes to 512 or more bytes in ksoap2 i have httptransportse object from ksoap2 libraryi want to dump response file which may contains mote then simple 9697 charactercurrently i am doing it by making transporttransportdebug truesystemoutprintlnresponse transportresponsedumpbut it gives me half response with at lastin its internal coding structure i found that it is using 256 bytes for creating and destroying it is responsedump like shown belowpackage orgksoap2transportimport javaiobytearrayinputstreamimport javaiobytearrayoutputstreamimport javaioioexceptionimport javaioinputstreamimport javaiooutputstreamimport javanetmalformedurlexceptionimport javanetproxyimport javaneturlimport javautillistimport orgksoap2headerpropertyimport orgksoap2soapenvelopeimport orgxmlpullv1xmlpullparserexceptionpublic class httptransportse extends transport private serviceconnection connection public httptransportsestring url supernull url public httptransportseproxy proxy string url superproxy url public httptransportsestring url int timeout superurl timeout public httptransportseproxy proxy string url int timeout superproxy url timeout public void callstring soapaction soapenvelope envelope throws ioexception xmlpullparserexception callsoapaction envelope null public list callstring soapaction soapenvelope envelope list headers throws ioexception xmlpullparserexception if soapaction null soapaction byte requestdata createrequestdataenvelope thisrequestdump thisdebug new stringrequestdata null thisresponsedump null thisconnection getserviceconnection thisconnectionsetrequestpropertyuseragent ksoap20 if envelopeversion 120 thisconnectionsetrequestpropertysoapaction soapaction thisconnectionsetrequestpropertycontenttype textxml thisconnectionsetrequestpropertyconnection close thisconnectionsetrequestpropertycontentlength requestdatalength if headers null for int i 0 i headerssize i headerproperty hp headerpropertyheadersgeti thisconnectionsetrequestpropertyhpgetkey hpgetvalue thisconnectionsetrequestmethodpost thisconnectionconnect outputstream os thisconnectionopenoutputstream oswriterequestdata 0 requestdatalength osflush osclose requestdata null list retheaders null inputstream is try thisconnectionconnect is thisconnectionopeninputstream retheaders thisconnectiongetresponseproperties catch ioexception e is thisconnectiongeterrorstream if is null thisconnectionthisconnect throw e if thisdebug bytearrayoutputstream bos new bytearrayoutputstream byte buf new byte256 while true int rd isreadbuf 0 256 if rd 1 break boswritebuf 0 rd bosflush buf bostobytearray thisresponsedump new stringbuf isclose is new bytearrayinputstreambuf parseresponseenvelope is return retheaders public serviceconnection getconnection return serviceconnectionsethisconnection protected serviceconnection getserviceconnection throws ioexception return new serviceconnectionsethisproxy thisurl thistimeout public string gethost string retval null try retval new urlthisurlgethost catch malformedurlexception e eprintstacktrace return retval public int getport int retval 1 try retval new urlthisurlgetport catch malformedurlexception e eprintstacktrace return retval public string getpath string retval null try retval new urlthisurlgetpath catch malformedurlexception e eprintstacktrace return retval you found that its only int rd isreadbuf 0 256so is there any options to increase responsedump size,['android'] +518225,where memory for extern variable will be stored and by which file i read about extern variable but no where found answer related to its memory allocation my question is who will allocate memory for extern variable and in which memory segmentint a file 1extern int a file 2here file 1 will allocate memory for a or file 2 in data segment or in stack thanks,['c++'] +518233,c firing events within the thread they are added consider two classes producer and consumer the same as classical pattern each with their own threads is it possible for producer to have an event which consumer can register to and when the producer triggers the event the consumers event handler is run in its own thread here are my assumptionsconsumer does not know if the producers event is triggeredwithin his own thread or anotherneither producer nor consumer are descendants of control so they do not havebegininvoke method inheritedps i am not trying to implement producer consumer pattern these are two simple classes which i am trying to refactor the producer so it incorporates threadsupdateto further expand my problem i am trying to wrap a hardware driver to be worked with in the simplest way possible for instance my wrapper will have a statechanged event which the main application will register to so it will be notified when hardware is thisconnected as the actual driver has no means other than polling to check its presence i will need to start a thread to check it periodically once it is not available anymore i will trigger the event which needs to be executed in the same thread as it was added i know this is a classical producerconsumer pattern but since i am trying to simplify using my driverwrapper i do not want the user code to implement consumerupdatedue to some comments suggesting that there is no solution to this problem i would like to add few lines which might change their minds considering the begininvoke can do what i want so it should not be impossible at least in theory implementing my own begininvoke and calling it within the producer is one way to look at it it is just that i do not know how begininvoke does it,['c#'] +518237,embedding jetty 9 where is jettyalljar i am trying to embed jetty 9 in my project and the tutorial at suggests i need a file called jettyalljar but i cannot seem to find this in the download thistribution where do i get it from i am not using maven,['java'] +518273,pycharm and pypy unresolved reference for some weird reason my pycharm loves to show unresolved errors everywherebut only with pypy the source runs just fine even pycharm can run the code perfect but the red lines everywhere are really annoyingthe problem ps i tried the invalidate cache method but it did not help,['python'] +518297,what is httprequestmessageproperties what is the purpose of httprequestmessagepropertiesi am wondering if it provides something useful for my application,"['c#', '.net']" +518313,draw diagonal lines in div background with css i have div for preview boxhtmldiv classpreviewcontentpreviewdivcsspreviewcontent background urldataimagepngbase64ivborw0kggoansuheugaqaecayacp8z5agkleqvqiw2nkygd4d8smqawgcay2abbkdbuavuycbqpd34sasuvork5cyii repeat width 100 minheight 300px maxheight 300px lineheight 300px textalign center verticalalign middle fontsize 2emq how to add diagonal lines to div background like in picturenote with css only if possiblethank you in advance,['css'] +518400,action bar menu item text color how to change text color of menu item title i tried to change it as belowstyle namethemekankuactionbartitletextstyle parentandroidstyletextappearanceholowidgetactionbartitle item nameandroidtextcolorcolorwhiteitemstylebut it change color only of action bar title text but not menu item text,['android'] +518403,in app billing iab setup successful but quaryinventory reports iab helper not set up i am trying to implement in app billing i have used the trivialdrivesample as it ispublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main load game data loaddata string base64encodedpublickey my key create the helper passing it our context and the public key to verify signatures with logdtag creating iab helper mhelper new iabhelperthis base64encodedpublickey enable debug logging for a production application you should set this to false mhelperenabledebugloggingtrue start setup this is asynchronous and the specified listener will be called once setup completes logdtag starting setup mhelperstartsetupnew iabhelperoniabsetupfinishedlistener public void oniabsetupfinishediabresult result logdtag setup finished if resultissuccess oh noes there was a problem complainproblem setting up inapp billing result return hooray iab is fully set up now let us get an inventory of stuff we own logdtag setup successful querying inventory mhelperqueryinventoryasyncmgotinventorylistener button purchaseb buttonfindviewbyidridpurchase button ifpurchaseb null purchasebsetonclicklistenernew viewonclicklistener public void onclickview v onupgradeappbuttonclickednull its working perfectly and i am able to purchase from my test accountbut problem is that i have to comment the code line mhelperqueryinventoryasyncmgotinventorylistenerso i am not able to query inventory on dubugging i found that variable is setup done boolean msetupdone false in iabhelper class is false and it raises an exception the log just after saying setup successfull its saying iab helper not setup0802 160242453 dpacklist10346 creating iab helper0802 160242453 dpacklist10346 starting setup0802 160242468 diabhelper10346 starting inapp billing setup0802 160242515 dpacklist10346 creating iab helper0802 160242539 diabhelper10346 billing service connected0802 160242546 diabhelper10346 checking for inapp billing 3 support0802 160242562 diabhelper10346 inapp billing version 3 supported for comxx0802 160242570 diabhelper10346 subscriptions available0802 160242570 dpacklist10346 setup finished0802 160242570 dpacklist10346 setup successful querying inventory0802 160242578 eiabhelper10346 inapp billing error illegal state for operation queryinventory iab helper is not set up,['android'] +518440,add extra header row at top of excel sheet epplus i am working with a web application therei am supposed to export data to excel for thati have made use of epplusi searched alot but cant find out a way to add extra row at top of excel sheet please have a look at below image to better understand the ideai tried merging the headerbut then i wont get other headersso i think add extra row at top wil be a better phrase for thisi am not bounded to use epplus if there is other ways availablei will surely approach itcan any one help me with this i really appreciate the response,"['c#', 'asp.net']" +518442,save matplotlib animation i am trying to make an animation of a wave package and save it as a movie everything except the saving is working can you please tell me what i am doing wrong when going into the line anisavemovwavemp4 he tells me writer writerslist0indexerror list index out of rangei tried googling it of course but i do not even know what it meansupdate i can call ffmpeg in console now it says i have ffmpeg version 0107601070jon1precise installed i updated the code and ran the program but now i get the following errortraceback most recent call last anisavemovwavempeg writerffmpeg writergrab frame dpiselfdpi selfcanvasprint figureargs kwargs selffiguredpi origdpi selfdpi scale transclearscaledpi dpi self mtx npidentity3 from numpy import eye file frozen importlib bootstrap line 1609 in handle fromlistunicodedecodeerror utf8 codec cannot decode byte 0xff in position 0 invalid start byteupdate 2 apparently there is a bug when using python 33 as doctorlove pointed out i am now trying to use python 27 instead now it creates an mpegfile but it cannot be played and it is only about 150 kb bigupdate 3 okay so i tried the exact same code on my win7 machine and it also works in python 33 but i have the same problem i had earlier with python 27 the mpegfile created cannot be played and is only a few hundred kb codingutf8import numpy as npimport matplotlibpyplot as pltimport matplotlibanimation as animationimport timetimeclockdef fftxy x x1x0leny f nplinspace2nppix22nppix2leny f npfftfftshiftnpfftfftynpsqrtleny returnffdef functionk 0dxct y npexp1jk 0xctnpexpxct2dx2 2nppidx214 kf fftxcty returnxykfparametern 10x nplinspace030nk 0 5dx 1c 1l k 0cdxfig pltfiguremoving wavepackage and it is fftsub1 pltsubplot211sub2 pltsubplot212sub2set xlim1010sub1set titlemoving wavepackage and it is fftsub1set ylabelrepsixtsub1set xlabeltsub2set ylabelrepsik xtsub2set xlabelk xn 50t nplinspace030nimg for i in rangen xykf functionk 0dxcti imgappendpltplotxnprealycolorred axespltsubplot211 imgappendpltplotknprealfcolorred axespltsubplot212ani animationartistanimationfig img interval20 blittrue repeat delay0anisavemovwavempeg writerffmpegprinttimeclockpltshow,['python'] +518448,android get text from browser i want to get text from browser by using uiautomatorhow can i do iti have parsed structure of chrome and there is only androidviewviewi have tried to use gettext function but it is not helpedany help appreciatedmaybe somebody know how can i do it by calling some chrome instance or with any other methodany solution with info how to save android browser page as htmltext will be enough or how to select whole page except touchinglong pressing text,['android'] +518489,is there a pure promisebased approach for mappingconcatenating collections async vs q generallyi am learning nodejs development and trying to wrap my brain around strategies for managing asynchronous callback hell the two main strategies i have explored are caolan mcmahons async module and kris kowals promisebased q module like many other people i am still struggling to understand when you should use one vs the other however generally speaking i have found promises and qbased code to be slightly more intuitive so i have been moving in that directionmappingconcatenating collections generallyhowever i am still stuck using the async modules functions for managing collections coming from a java and python background most of the time when i work with a collection the logic looks like thisinitialize a new empty collection in which to store resultsperform a foreach loop with the old collection applying some logic to each element and pushing its result into the new empty collectionwhen the foreach loop ends proceed to use the new collectionin clientside javascript i have grown accustomed to using jquerys map function passing in that step 2 logic and getting the step 3 result as a return value feels like the same basic approachmappingconcatenating collections with async and qthe nodeside async module has similar map and concat functions but they do not return the concatenated result back at the original scope level you must instead descend into the callback hell to use the result examplevar deferred qdefervar entries some array of objects with id attributesasyncconcatentries function entry callback callbacknull entryid function err ids we now have the ids array holding the id attributes of all items in the entries array optionaly perhaps do some sorting or other postprocessing on ids deferredresolveidsreturn deferredpromisesince my other functions are becoming promisebased i have this code returning a promise object so it can be easily included in a then chain do i really need boththe ultimate question that i am struggling to articulate is do i really need both async and q in the code example above i am learning how to replace the async modules control flow with qstyle promise chains generally but it has not yet clicked for me how to do mapping or concatenation of collections with a promisebased approach alternatively i would like to understand why you cannot or why it is not a good ideaif async and q are meant to work together as i am using them in the example above then so be it but i would prefer not to require the extra library dependency if i could cleanly use q alonesorry if i am missing something outrageously obvious the asynchronous eventdriven model is a very different world and my head is still swimming,['javascript'] +518537,css flexbox not working in ie10 in ie10 this code is not working correctlyflexbox form thisplay webkitflex thisplay mozflex thisplay msflex thisplay oflex thisplay flex webkitflexdirection row mozflexdirection row msflexdirection row oflexdirection row flexdirection rowflexbox form inputtypesubmit width 31pxflexbox form inputtypetext width auto thisplay webkitflex thisplay mozflex thisplay msflex thisplay oflex thisplay flex webkitflex auto 1 mozflex auto 1 msflex auto 1 oflex auto 1 flex auto 1what should happen is that inputtypesubmit should be 31px wide with inputtypetext taking up the rest of the available space within form what happens is inputtypetext just defaults to 263px for some reason this works fine in chrome and firefox,['css'] +518575,how to make supported on all browsers any alternatives i am working with html5 elements input attributes and only google chrome supports the date time attributes i tried modernizr but i cannot understand on how to integrate it on my websiteon how to code itwhat is the syntaxincludes any code snippet there on how to work with date time attributes to all browsers,"['javascript', 'jquery', 'html']" +518580,1062 duplicate entry 1 for key primary i am at a complete loss here i have two databases one on my localhost site that i use for development and one on my remote site that i use for my live production site i manage both of them through phpmyadmin as i have been doing for months now when i need to update the live site i dump the related database and import the database from my localhost sitenow no matter what i try i keep getting this errorerrorsql query dumping data for table oc address typeinsert into oc address type address type id address type name values 1 billing 2 shipping mysql said documentation1062 duplicate entry 1 for key primary i tried creating a new blank database on my localhost and importing into that but same results i have validated all of the tables and indexes and cannot find anything wrong thereany suggestions please as i am completely down until this gets resolvedby the way i am completely dropping all tables and importing structure and data this has always worked until today,"['mysql', 'sql']" +518603,findobjectsinbackgroundwithblock gets data from parse but data only exists inside the block i made the following test class to try out retrieving data from parsevoidretrievedatafromparse pfquery query pfquery querywithclassnametestobject query findobjectsinbackgroundwithblocknsarray objects nserror error iferror for pfobject object in objects nsstring namefromobject nsstring stringwithformat object objectforkeyname nsstring datefromobject nsstring stringwithformat object createdat nsstring scorefromobject nsstring stringwithformat object objectforkeyscore self addnewscorescorefromobject anddatedatefromobject forusernamenamefromobject nslogthe dictionary is selfscoredictionary here it works printing out the whole dictionary else nslogerror error error userinfo nslogthe dictionary is selfscoredictionary but after the block is called here the dictionary is again emptyper the commented section inside the code when i print selfscoredictionary inside the code it works out fine and i see my entire dictionary as it incrementally gets filled however after the block ends when i print the dictionary again it is now empty i double checked with the query api docs but i still am unsure what i am doing incorrectly,"['ios', 'objective-c']" +518628,silex securityserviceprovider throws identifier securityauthentication providers is not defined i cannot figure out how to use securityserviceprovider in silex my configuration isappsecurityfirewalls array admin array pattern admin form arraylogin path admin check path adminlogin check logout arraylogout path adminlogout users array admin arrayrole admin 5fz2z8qika7utz4bykocgsr appregisternew silexprovidersecurityserviceproviderthis just throwsfatal error uncaught exception invalidargumentexception with message identifier securityauthentication providers is not definedaccording to the documentation in some cases when you want to access security features outside of the handling of a request you have to call appboot but this is not my situationif i call appboot before appregister it does not raise any exception but it probably does not boot at all because then in generating login form twig throwsunable to generate a url for the named route admin login check as such route does not existthere is an issue a few months ago with probably the same problem but it is closed so i guess it should be fixed now,['php'] +518631,download a file programmatically in multiple chunks in parallel in restartable mode i need to download a large file using http protocol via a quite slow network connection when doing it manually the download speed sometimes is unbearably slow and the process sometimes freezes or terminates for manual downloads the situation can be greatly improved by using a download manager eg fdm a a class of programs that was inthispensable and extremely popular a decade or so ago but whose usage quickly diminishes nowadays because of better and faster networking available a it starts multiple download sessions of the same file in parallel in chunks starting from different positions automatically restarts failed or stale sessions implements work balancing after a successful download of a chunk splits some of the remaining chunks still being downloaded into two sessions and eventually stitch all downloaded chunks into a complete single file overall it allows to make file downloading robust and much faster on poor connectionsnow i am trying to implement the same download behavior in c for automatic unattended downloads i cannot see any of existing classes in net framework implementing this so i am looking for advice how to implement it manually possibly with an aid of some opensource net libraries,"['c#', '.net']" +518659,javalangnosuchmethodexception userauthuser i have the class with validationpublic class user sizemin3 max20 messageuser name must be between 3 and 20 characters long patternregexpazaz09 messageuser name must be alphanumeric with no spaces private string name sizemin6 max20 messagepassword must be between 6 and 20 characters long patternregexp09azazazaz09 messagepassword must contains at least one number private string password public userstring name string password super name name password password public string getname return name public string getpassword return password public void setpasswordstring newpassword password newpassword when i validate values i got the messagesevere servletservice for servlet osappservlet threw exceptionjavalangnosuchmethodexception userauthuserinitwhere is the problem,['java'] +518675,php ternary operator checking if variable contains something consider the following simplified to the bare bonesabstract class validator public function constructdata null thisdata data inputall validation new pagevalidatordatainputall is returning an array data is also an arraythe bit i am struggling with isthisdata data inputalli think it is essentially doing this ifdata thisdata inputall else thisdata data but i do not really understand how,['php'] +518703,recursively build hierarchical json tree in python i have a database of parentchild connections the data look like the following but could be presented in whichever way you want dictionaries list of lists json etc linkstomdickdickharrytomlarrybobleroybobearlthe output that i need is a hierarchical json tree which will be rendered with d3 there are thiscrete subtrees in the data which i will attach to a root node so i need to recursively go though the links and build up the tree structure the furthest i can get is to iterate through all the people and append their children but i cannot figure out to do the higher order links eg how to append a person with children to the child of someone else this is similar to another question here but i have no way to know the root nodes in advance so i cannot implement the accepted solution i am going for the following tree structure from my example datanamerootchildren nametom children namedick children nameharry namelarry namebob children nameleroy nameearl this structure renders like this in my d3 layout,['python'] +518720,pygobject2286 would not configure no package gobjectintrospection10 found how do i resolve i am trying to get pygobject2286 to compile in cygwin version in repository is 2284 which has some issues here is the tail of configurechecking for glib version 2240 yes version 2343checking for ffi checking for ffi yeschecking for gio yeschecking for giounix yeschecking for gi noconfigure error package requirements glib20 2240 gobjectintrospection10 0102 were not metno package gobjectintrospection10 foundconsider adjusting the pkg config path environment variable if youinstalled software in a nonstandard prefixalternatively you may set the environment variables gi cflagsand gi libs to avoid the need to call pkgconfigsee the pkgconfig man page for more detailsi have gobjectintrospection 13423 installed as seen here whereis gobjectintrospectiongobjectintrospection libgobjectintrospection usrlibgobjectintrospectionand here whereis gobjectintrospection10gobjectintrospection1 usrsharegobjectintrospection10i have tried setting gi cflags and gi libs in configure to lib and usrlib and even usrshare but to no avail what else can i do to try and resolve this thank you for your time,['python'] +518760,python setuptools how can i list a private repository under install requires i am creating a setuppy file for a project which depends on private github repositories the relevant parts of the file look like thisfrom setuptools import setupsetupnamemy project install requires public package other public package private repo 1 private repo 2 dependency links accountprivate repo 1mastertarball accountprivate repo 2mastertarball i am using setuptools instead of thistutils because the latter does not support the install requires and dependency links arguments per this answerthe above setup file fails to access the private repos with a 404 error which is to be expected since github returns a 404 to unauthorized requests for a private repository however i cannot figure out how to make setuptools authenticatehere are some things i have trieduse gitssh instead of https in dependency links as i would if installing the repo with pip this fails because setuptools does not recognize this protocol unknown url type gitssh though the thistribute documentation says it should ditto githttps and githttphttpsusernamepasswordgithubcom still get a 404 this method does not work with curl or wget from the command line either though curl u username repo url o output file name does workupgrading setuptools 097 and virtualenv 110 to the latest versions also tried installing thistribute though this overview says it was merged back into setuptools either way no dicecurrently i just have setuppy print out a warning that the private repos must be downloaded separately this is obviously less than ideal i feel like there is something obvious that i am missing but cannot think what it might be duplicateish question with no answers here,['python'] +518839,fetch youtube highest thumbnail resolution i want to get youtube highest thumbnail maxresdefaultjpglike this onei am using this simple php codephpyoutub id cj6ho1g6twecho youtub idmaxresdefaultjpgthe problem with the code above is there is videos like this one not hdand the result is gray small 404 image of youtubeso how to get the highest youtube thumbnail so if maxresdefault not available get the next big thumbnail hqdefault if not get the next mqdefault etc i tried to use gdata youtube but either way the video hd or not maxresdefault not showing,['php'] +518922,css change image src on imghover i need to change img source url on hoveri have tried this but would not work htmlimg idmyimg srccssmyimghover content urljsfiddleany help would be appreciatedupdatethis only works for webkit google chrome,"['html', 'css']" +518950,how to improve insert performance on a very large mysql table i am working on a large mysql database and i need to improve insert performance on a specific table this one contains about 200 millions rows and its structure is as followsa little premise i am not a database expert so the code i have written could be based on wrong foundations please help me to understand my mistakes create table if not exists items id int not null auto increment name varchar200 not null key varchar10 not null busy tinyint1 not null default 1 created at datetime not null updated at datetime not null primary key id name unique key name key unique key name key index name index name enginemyisampartition by linear keynamepartitions 25every day i receive many csv files in which each line is composed by the pair namekey so i have to parse these files adding values created at and updated at for each row and insert the values into my table in this one the combination of name and key must be unique so i implemented the insert procedure as followscreate temporary table temp items id int not null auto increment name varchar200 not null key varchar10 not null busy tinyint1 not null default 1 created at datetime not null updated at datetime not null primary key id enginemyisamload data local infile file to processcsv into table temp itemsfields terminated by optionally enclosed by name key created at updated at insert into items name key busy created at updated at select temp itemsname temp itemskey temp itemsbusy temp itemscreated at temp itemsupdated at from temp items on duplicate key update busy1 updated atnowdrop temporary table temp itemsthe code just shown allows me to reach my goal but to complete the execution it employs about 48 hours and this is a problem i think that this poor performance are caused by the fact that the script must check on a very large table 200 millions rows and for each insertion that the pair namekey is uniquehow can i improve the performance of my script thanks to all in advance,['mysql'] +518958,logging swiftmailer send activity in symfony2 im using swiftmailer for sending mails from my symfony22 project is there a way to log globally all email info and send results it would be great if mailer send method have trigger soma event but i cannot see it does,['php'] +518960,set background color android how do i set the background color of my android app when i trylinearlayout lilinearlayoutfindviewbyidridmylayoutlisetbackgroundcolorcolorparsecolorggbbmy app always crashes could someone help me out thanks,"['java', 'android']" +518986,java setting private fields inside constructors common design practice is to make instance variables private and have public getters and setters to access them but many times i have seen code samples on the internet that have constructors that assign values directly to the private instance variable instead of using the setters inside constructors am i missing somethingpublic class person private string name public personstring name is this right seems like the whole encapsulation purpose is defeated thisname name should not this be used setnamename public string getname return thisname public void setnamestring name thisname name,['java'] +519035,cannot find vsix dlls with dllimport i have a vsix extension which depends on code deployed from an unmanaged dll i have included the dll with the vsix and i cracked open the vsix with a zip program to confirm that it is deployed correctly however when i use the dllimport attribute the net framework claims that it cannot find it how can i import functions from a dll packaged inside my vsix,['c#'] +519044,groovy class not found the following groovy script fails with a javalangclassnotfoundexception commysqljdbcdriver exceptiongrapes grabmysqlmysqlconnectorjava5125import groovysqlsqldef sql sqlnewinstance jdbcmysqllocalhostbooks root commysqljdbcdriveri looked into the jar file stored at cusersdusangroovygrapesmysqlmysqlconnectorjavajarsmysqlconnectorjava5125jar and it contains the driver classwhat can be wrong,['mysql'] +519065,how could the command pattern be replaced by lambda expressions this is kind of a followup to another question reuse code for looping through multidimensionalarray where my specific problem was resolved by using the commandpattern my problem was that i had multiple methods performing operations on every element of a twodimensional array and therefore a lot of duplicate code instead of having many methods like sovoid method for int i 0 i foolength i for int j 0 j fooilength j perform specific actions on fooij i solved it like thisinterface command void executeint i int jvoid foreachcommand c for int i 0 i foolength i for int j 0 j fooilength j cexecutei j void method foreachnew command public void executeint i int j perform specific actions on fooij now if we had lambda expressions in java how could this be shortened how would that look like in general sorry for my poor english,['java'] +519114,c wpf combobox strange issue i have two comboboxes one above another the problem appear if you open the form that contain this comboboxes and avoid mouse over at lower combobox you just click on first combobox and from drop down list choose item that is located right over the second combobox once you click on an item the drop down list will close but your mouse will remain over the second combobox but this combobox will not highlight and react on your clicks at all take a look at this picture pleaseboth comboboxes iseditable false but if you move your mouse out of the 2nd combobox and back over to it everything will works fine help me please how to fix thisupd xamlcombobox backgroundxnull height33 horizontalalignmentleft iseditablefalse isenabledtrue margin1015100 namecombobox2 verticalalignmenttop width239 verticalcontentalignmentcenter fontsize14 isreadonlyfalse text selectionchangedcombobox2 selectionchanged tabindex6 horizontalcontentalignmentleft padding103 fontweightsemibold allowdropfalse cursorhand istabstoptrue combobox backgroundxnull fontsize14 height33 horizontalalignmentleft iseditablefalse isenabledtrue margin10190 namecombobox3 verticalalignmenttop verticalcontentalignmentcenter width439 isreadonlyfalse text selectionchangedcombobox3 selectionchanged tabindex8 horizontalcontentalignmentleft padding103 fontweightsemibold cliptoboundsfalse cursorhand ishittestvisibletrue snapstodevicepixelstrue uselayoutroundingtrue,['c#'] +519163,django get only date from datetimestrptime i have start date field in database as date not datetime in my save method in formspy i am using datetimestrptimedate string ymd to convert string to date the method returns me formatted date along with time ie 20060803 0i want just the date and no time because i get an invalid date format error saying it must be in ymmdd format i am stuck on this and frustrated can anyone help me out with this,['python'] +519207,using cstring address of stack memory associated with local variable returned i am not a c programmer so i am not that familiar with cstring but new i have to use a c library so here is a shortened version of my code to demonstrate my problem char readlineimplmy completion char matches1 matches0 add return matchesi am getting a warningwarning address of stack memory associated with local variable matches returnedand my application does not seem to work properly might be because of this warningwhat is the warning and will it cause any problemsthanks in advance,['c++'] +519232,stop executing further code in java i have looked in the javadoc but could not find information related to thisi want the application to stop executing a method if a code in that method tells it to do soif that sentence was confusing heres what i want to do in code public void onclick ifcondition true stopmethod madeup code stringsettextthis string should not change if condition trueso if the boolean condition is true the method onclick has to stop executing further codethis is just an example there are other ways for me to do what i am trying to accomplish in my application but if this is possible it would definitely help,['java'] +519288,volley or service with cursor loader i almost always use a service when i download data from a web service i store the result in a database and thisplays the result in my view using a cursor loader but after google released the network library volley i have become a bit confused the volley library uses async tasks instead of a service and it does not use cursors i thought that i was supposed to avoid async task and store my data in a database so that i could handle orientation changes properly without loosing data and having the need to download the data again so my question is when should i use volley instead of my own download strategy,['android'] +519329,c generics any way to refer to the generic parameter types as a collection i need to write a bunch of methods that take 1n generic type parameters egint foot1int foot1t2int foot1t2t3int foot1t2t3tninside foo i would like to do something for each type egint foot1t2t3 thisdata new byte3 allocate 1 array slot per typeis there any way to parameterize this so that i am not editing every variation of foo something analogous toint foot1t2t3 thisdata new byte number of generic parametersideally i would also like to be able to get an array or collection of the types as wellint foot1t2t3 thisdata new byte number of generic parameters can do this type types new type t1 t2 t3 but would rather do this type types array or collection of the generic parameters,"['c#', '.net']" +519401,uitableview make footer stay at bottom of screen i have a uitableview with a footer filled with a tabbar in a custom view done using the following code cgfloattableviewuitableview tableviewheightforfooterinsectionnsintegersection differ between your sections or if you have only on section return a static value return 49 uiview tableviewuitableview tableview viewforfooterinsectionnsintegersection iffooterview nil allocate the view if it does not exist yet footerview uiview alloc init footerview addsubviewselftabbarview return the view for the footer return footerviewwhich is working lovely apart from when the table has less rows than are needed to fill the screen this causes the footer to move up the screen as the table no longer creates empty rows due to having a footerso does anyone know of a way to either lock the custom footer to the bottom of the screen or to make the tableview create empty rows as it used to dothanksgareth,"['iphone', 'objective-c']" +519475,intent putextra arraylist does anyone know how to add an arraylistnamevaluepair to an intent as an extraarraylistnamevaluepair namevaluepairs new arraylistnamevaluepairnamevaluepairsaddnew basicnamevaluepairfirst name first namenamevaluepairsaddnew basicnamevaluepairlast name last namenamevaluepairsaddnew basicnamevaluepairemail emailnamevaluepairsaddnew basicnamevaluepairpassword password move on to step 2 intent intent new intentregisteractivity1this registeractivity2classintentputextranvp namevaluepairsstartactivityintenthere is the class declaration for registeractivity2public class registeractivity2 extends activity implements serializable the error in the logcat is parcel unable to marshal value first namewhateverafter implementing the suggestion by ted hopp i still get an error here is the stack trace0804 221016095 eandroidruntime5065 fatal exception main 0804 221016095 eandroidruntime5065 javalangruntimeexception unable to start activity componentinforegisteractivity2 javalangruntimeexception parcelable encountered ioexception reading a serializable object name databasenvp 0804 221016095 eandroidruntime5065 at androidappactivitythreadperformlaunchactivityactivitythreadjava2070 0804 221016095 eandroidruntime5065 at androidappactivitythreadhandlelaunchactivityactivitythreadjava2095 0804 221016095 eandroidruntime5065 at androidappactivitythreadaccess600activitythreadjava135 0804 221016095 eandroidruntime5065 at androidappactivitythreadhhandlemessageactivitythreadjava1201 0804 221016095 eandroidruntime5065 at androidoshandlerthispatchmessagehandlerjava99 0804 221016095 eandroidruntime5065 at androidoslooperlooplooperjava137 0804 221016095 eandroidruntime5065 at androidappactivitythreadmainactivitythreadjava4849 0804 221016095 eandroidruntime5065 at javalangreflectmethodinvokenativenative method 0804 221016095 eandroidruntime5065 at javalangreflectmethodinvokemethodjava511 0804 221016095 eandroidruntime5065 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava795 0804 221016095 eandroidruntime5065 at comandroidinternaloszygoteinitmainzygoteinitjava562 0804 221016095 eandroidruntime5065 at dalviksystemnativestartmainnative method 0804 221016095 eandroidruntime5065 caused by javalangruntimeexception parcelable encountered ioexception reading a serializable object name databasenvp 0804 221016095 eandroidruntime5065 at androidosparcelreadserializableparceljava2144 0804 221016095 eandroidruntime5065 at androidosparcelreadvalueparceljava2016 0804 221016095 eandroidruntime5065 at androidosparcelreadlistinternalparceljava2235 0804 221016095 eandroidruntime5065 at androidosparcelreadarraylistparceljava1655 0804 221016095 eandroidruntime5065 at androidosparcelreadvalueparceljava1986 0804 221016095 eandroidruntime5065 at androidosparcelreadmapinternalparceljava26 0804 221016095 eandroidruntime5065 at androidosbundleunparcelbundlejava223 0804 221016095 eandroidruntime5065 at androidosbundlegetserializablebundlejava1254 0804 221016095 eandroidruntime5065 at androidcontentintentgetserializableextraintentjava4268 0804 221016095 eandroidruntime5065 at registeractivity2oncreateregisteractivity2java24 0804 221016095 eandroidruntime5065 at androidappactivityperformcreateactivityjava5244 0804 221016095 eandroidruntime5065 at androidappinstrumentationcallactivityoncreateinstrumentationjava1082 0804 221016095 eandroidruntime5065 at androidappactivitythreadperformlaunchactivityactivitythreadjava2034 0804 221016095 eandroidruntime5065 11 more 0804 221016095 eandroidruntime5065 caused by javaioinvalidclassexception orgapachehttpmessagebasicnamevaluepair illegalaccessexception 0804 221016095 eandroidruntime5065 at javaioobjectstreamclassresolveconstructorclassobjectstreamclassjava694 0804 221016095 eandroidruntime5065 at javaioobjectstreamclassnewinstanceobjectstreamclassjava655 0804 221016095 eandroidruntime5065 at javaioobjectinputstreamreadnewobjectobjectinputstreamjava1816 0804 221016095 eandroidruntime5065 at javaioobjectinputstreamreadnonprimitivecontentobjectinputstreamjava787 0804 221016095 eandroidruntime5065 at javaioobjectinputstreamreadobjectobjectinputstreamjava2003 0804 221016095 eandroidruntime5065 at javaioobjectinputstreamreadobjectobjectinputstreamjava1960 0804 221016095 eandroidruntime5065 at androidosparcelreadserializableparceljava2142 0804 221016095 eandroidruntime5065 23 more,['android'] +519536,uitableview overlaps status bar on ios7 beta 4 here is a uitableview that worked fine in ios6 overlapping the status bar in ios7 what is the best way to solve this problem using ios7 beta 4 this behavior existed since beta 1metacomplain about me thisobeying nda to apple directly at 8002752273 or stack overflow at 2122328294 or help me solve this problem here which is clearly superior to apples forums,"['iphone', 'ios']" +519596,typeerror not all arguments converted during string formatting python the program is supposed to take in two name and if they are the same length it check if they are the same word if it is the same word it will print the names are the same if they are the same length but of different letters it will print the names are different but the same length the part i am having a problem with is at the bottom 4 or lines when i run it it saysusrbinenv python enter your code for whats in the length of a name herename1 inputenter name 1 name2 inputenter name 2 lenname1lenname2if lenname1 lenname2 if name1 name2 print the names are the same else print the names are different but are the same length if lenname1 lenname2 print 0 is longer than 1 name1 name2 elif lenname1 lenname2 print 0is longer than 1 name2 name1when i run this code it thisplaystraceback most recent call last file programpy line 13 in module print 0 is longer than 1 name1 name2typeerror not all arguments converted during string formattingany suggestions are highly appreciated,['python'] +519616,horizontalscrollview in tabhost adding extra space on the end in order to easily switch between fragments i am embedding a horizontalscrollview into my tab layout like soxml version10 encodingutf8tabhost xmlnsandroid androididandroididtabhost androidlayout widthmatch parent androidlayout heightmatch parent linearlayout androidorientationvertical androidlayout widthmatch parent androidlayout heightmatch parent horizontalscrollview androidlayout widthwrap content androidlayout heightwrap content androidfillviewporttrue androidscrollbarsnone tabwidget androididandroididtabs androidlayout heightwrap content androidlayout widthwrap content tabwidget horizontalscrollview framelayout androididandroididtabcontent androidlayout widthmatch parent androidlayout heightwrap content linearlayouttabhostbut after adding fragments in my code shown below there suddenly shows up some extra whitespace at the end of the horizontalscrollviewbefore scrollingafter scrollingthe code is quite complex but i will try to show the important parts mtabhost tabhost childlayoutfindviewbyidandroidridtabhost mtabhostsetup framelayout tabsfl framelayout childlayoutfindviewbyidandroidridtabcontent tabsflsetidtabs frame id for int i 0 i listsize i mtabhostaddtabnewtabstringvalueofi listgetigettitle tabsflgetid mtabhostsetontabchangedlistenernew tabhostontabchangelistener override public void ontabchangedstring tabid updatetabtabid integerparseinttabid list manually load first fragment mtabhostsetcurrenttabmcurrenttab updatetabstringvalueofmcurrenttab mcurrenttab listprivate tabspec newtabstring tag string tablabel int tabcontentid int count integerparseinttag count 1 view indicator inflaterinflaterlayoutdetails tab viewgroup childlayoutfindviewbyidandroidridtabs false textview indicatorfindviewbyidridtextsettextcount tablabel tabspec tabspec mtabhostnewtabspectag tabspecsetindicatorindicator tabspecsetcontenttabcontentid return tabspecprivate void updatetabstring tabid int id arraylistcustomobject frags mcurrenttab id fragmentmanager fm activitygetsupportfragmentmanager fmbegintransaction replacetabs frame id detailsfragmentnewinstancefragsgetid tabid commitallowingstatelossalso unrelated but i also have a problem where the first tab does not load manually clicking tabs loads the fragments perfectly just the very first one does not load for some reason,['android'] +519625,how to use youtubedl from a python program i would like to access the result of the shell commandyoutubedl g wyoutubecomto print its output direct url to file from within a python programimport youtubedlfromurlwyoutubecom geturlyoutubedlmagiclyextracturlfromurlfromurlis that possible i tried to understand the mechanism in the source but got lost youtube dl init py youtube dlyoutube dlpy info extractors,['python'] +519632,what is callback in android i want to understand the concept of callback i have searched on internet about the callbacks and there are many examples using interface and one class is calling a method of another class using that interface but still i cannot get the main concept of callbacks what is the purpose of using callbacks,"['java', 'android']" +519662,rdotnet vs r scripting when is it an advantagethisadvantage to be using rdotnet for making statistical calculations as opposed to generating an r script text file and running it from the application using eg procestart or is there some other better wayi need to execute a large number of commands and have a feeling that sending them one by one to r takes a lot of time,['c#'] +519665,android studio vs eclipse ide i am new to android and i started development on eclipse but it is creating lot of issues as emulator is taking lot of time to start and in between it hangs aswelljust now learnt there is another tool android studio can i use android studie instead of eclipse are there any performance issues with android studioplease anyone suggest me to clear the confusion i am ready to shift to android studio if it is more user friendly than eclipsethankssiva,['android'] +519668,whats the difference between using instanceof and checking the constructor why do the following two lines return different resultstest instanceof string returns falsetestconstructor string returns truetested in the console of chrome version 280150095 mdoes it work slightly differently for native types,['javascript'] +519695,can i declare use some variable in linq or can i write following linq clearer can i declare use some variable in linqfor example can i write following linq clearervar q from propertydescriptor t in typedescriptorgetpropertiesinstance where tcomponenttypegetpropertytname null select tcomponenttypegetpropertytnameare there ways to not write call tcomponenttypegetpropertytname two times here,['c#'] +519700,column order manipulation using collgpush and collgpull in twitter bootstrap 3 i am now reading documentation on twitter bootstrap 3 and tried to follow column ordering as shown in this page but hit the wall i do not understand why such a code works nor how to correctly specify the setting what i want to show is one grid which is consisted of length 5 and the other length 5 and finally one length 2 gridso mine is something like this5 5 2and what i want to achieve is when it is viewed on desktop the layout above is thisplayed but when it is viewed on mobile i want to show the second length 5 object first then the first length 5 object and finally the length 2 object vertically like this5 second5 first2 while i tried to follow the step explained in the above documentation i got the first length 5 object over the second one despite being on mobile platforms which as i said should thisplay second length 5 object on the top in other words i got this5 first5 second2 so how can i correctly put the second one over the first or since i use the same length object could the column ordering not workheres my code for your informationdiv classrowdiv classcollg5 collgpush5divdiv classcollg5 collgpull5divdiv classcollg2divdivalso the documentation does not clarify what pull or push means so am i missing somethingthanks,['css'] +519748,python attributeerror on del i have a python class object and i want to assign the value of one class variableclass groupclassworkerclass worker class count 0 def init self initialize time groupclasscount 1 selfmembercount 0 selfmembers def del self delte a worker data groupclasscount 1if name main group1 groupclassthis execution result is correct but there is an error message that saysexception attributeerror nonetype object has no attribute count in bound method groupclass del of main groupclass instance at 0x00ba6710 ignoredcan someone tell me what me i did wrong,['python'] +519767,understanding javascript forloop better while reading code from a js editor tern i have come across various uses for the forloop as seen in the snippets belowcode snippet 1 lines 463468for some code code snippet 2 lines 97100for var i 0 i some code on the same note i also have come across a forloop with an empty body egfor var p p p somevalue empty body i am trying to understand what happens in code execution flowmy take is that for code in snippet 1 the for loop has no conditions so it may continue endlessly for code in snippet 2 i is continually incremented without a limit for the third one the loop continues till p is assigned something that evaluates to falsethese are the ideas i have in my mind yet i am not sure please assist,['javascript'] +519785,manually trigger touch event i searched for the past 30 minutes but did not find a solutioni want to trigger a touchstart event on an elementthis fires the touchstart eventvar e documentcreateeventmouseeventeinitmouseeventtouchstart true true window 1 screenx screeny clientx clienty ctrlkey altkey shiftkey metakey button relatedtargettargetthispatcheventenote that the variables are defined by my functionbut there is a problem with that the event object does not have a touches property so something like this would not workvar touch etouches0is there a way to trigger a touchstart event manually it should work on android 40 and chrome with touch enabled devtools please note that i do not want to use any framework like jquery with jquery it is easy to create a touchevent on an element,['javascript'] +519816,ruby if objectnil or if object are they the same when used in an ifelseend statement what do you usually do i am wondering if there are any subtle differences or edge cases where object and objectnil would respond differently,['ruby'] +519832,splitting a string in java on more than one symbol i want to split a string when following of the symbols encounter i am using split function but this function can take only one argumentmoreover it is not working on i am using following codestringnamesplitsymbolthanks,['java'] +519837,uitableview scroll to section is it possible to scroll to a section instead of a row if so howbtw i am using a method to remove the floating headershere is the code that i use to move to the selected sections first rowif selfopensectionindex nsnotfound selftableview scrolltorowatindexpathnsindexpath indexpathforrow0 insectionsection atscrollpositionuitableviewscrollpositiontop animatedyesthis is the code to remove the floating headers voidscrollviewdidscrolluiscrollview scrollview if selfopensectionindex nsnotfound if scrollviewcontentoffsetydefault header heightscrollviewcontentoffsety0 scrollviewcontentinset uiedgeinsetsmakescrollviewcontentoffsety 0 0 0 else if scrollviewcontentoffsetydefault header height scrollviewcontentinset uiedgeinsetsmakedefault header height 0 0 0 this is somehow what i want but i would rather also show the header right now the header is hidden offscreen in the top,['ios'] +519849,checkers game not error checking correctly i am making a checkers game for an assignment the whole thing is running the way it should except for one weird thing heres my boardi move by giving the source row and column then the destination row and columnmoveint srcr int srcc int destr int destci am supposed to print out an error if i try to move a piece to an invalid spot not diagonally so if i try to move a piece from 5 2 4 2 it gives me an error messageifdestr srcr1 destr srcr1 destc srcc1 destc srcc1 code code codeelse message invalid move can only move diagonally one spacefor most things it works but if i try to move directly down one space for example 2 3 3 3 it is moving the piece and not giving me the error messagei am stuck any ideas why this may be happening i can post more code if needed,['java'] +519923,csrf in mobile applications the situationalice uses an online banking website which stores a cookie of her credentialsbefore the cookie expires eve sends alice a malicious url which subsequently causes alice to withdraw money from her bank account and send it to evethis a common csrf example for web applications but how feasible is it to do this inside of a mobile applicationwhat if alice uses a banking application on her phone which stores a cookie and then visits a site from eve which has a similar outcomewill a cookie on alices mobile device from a native or hybrid application be vulnerable to manipulation or are these cookies typically sand boxed on the device somehowi would assume cookies on ios android etc work the same as a normal browser but is this actually the caseeditthis question was originally meant to be generic across all mobile devices even something such as creating a cookie in javascript and then using phonegap or titanium could be relevant i believe after reading more into this i am also curious if compiling the javascript using one of these other technologies would affect native devices cookies and how they store themthe main point of using cookies would be to maintain credentials of the user so they wouldnt have to log out and log back in every time with their bank account after reading more about this issue it seems like there are different scenarios for each particular device and it is in fact possible to csrf an application as an example shared preferences in android are sand boxed to prevent other applications from accessing the values,"['android', 'ios']" +519956,how do i do tls with bouncycastle does anybody know about examples of tls with bouncycastle i was surprised by the lack of them on internet if there are really none let us collect them as answers,['java'] +520002,why should i not override gethashcode my search for a helper to correctly combine constituent hashcodes for gethashcode seemed to garner some hostility i got the impression from the comments that some c developers do not think you should override gethashcode often certainly some commenters seemed to think that a library for helping get the behaviour right would be useless such functionality was considered useful enough in java for the java community to ask for it to be added to the jdk and it is now in jdk 7is there some fundamental reason that in c you do not need to or should definitely not override gethashcode and correspondingly equals as often as in java i find myself doing this often with java for example whenever i create a type that i know i want to keep in a hashset or use as a key in a hashmap equivalently net dictionary,"['c#', 'java', '.net']" +520061,android studio failed to find target android18 i have a problem with android studio 023when i run my project the build stops and appears message that saysgradle execution failed for task appnamecompiledebugaidl failed to find target android18although i have installed the sdk platform of android 43 api 18 and i tried to reinstall all the sdk i have also added the android home variable in the system variableswhat seems to be the source of this error,"['java', 'android']" +520073,capybara notsupportedbydrivererror when trying to simulate pressing i am writing a spec using capybara to test the functionality of a search bar on my website after following the instructions on this page on how to simulate pressing the enter key in rspeccapybara i get the following error when i run my tests failureerror pagedriverexecute scriptkeypress capybaranotsupportedbydrivererror capybaradriverbaseexecute scriptam i doing something wrong here are the contents of my spec filerequire spec helperdescribe search do it thisplays no results when nonexistent things are looked up do visit root path pagefirstsearchiconsmallclick fill in search with nonexistent simulate pressing enter keypress var e eventkeydown keycode 13 bodytriggere pagedriverexecute scriptkeypress pageshould have contentno results end it thisplays content that exists do clients client clientnew clientname gerard leskovar clientsave visit root path pagefirstsearchiconsmallclick fill in search with leskovar keypress var e eventkeydown keycode 13 bodytriggere pagedriverexecute scriptkeypress pageshould have contentgerard leskovar endendi appreciate your assistance,['ruby-on-rails'] +520102,what does the following piece of code do short rtimer arch nowvoid short t1 t2 do t1 ta1r t2 ta1r whilet1 t2 return t1ta1r is a the timer a register i still dont get why there is a loop if they want to return the time whydont they simply return ta1r what is the loop for,['c'] +520114,laravel 4 remember me expire time i am fairly new to laravel and had a question regarding the remember me functioni have successfully enabled the remember me function by attaching a second argument to the authattempt method like soif authattemptarrayemail email password password true the user is being rememberedas noted in the documentation this enables remember me indefinitely or until an user manually logs outi essentially want to set an expire date on the remember me functionlooking at the console i can see that enabling remember me generates a remember hash cookiewhat would be the best way to overwrite the expire date specified in this cookie to let say a week in the future the cookie currently sets the date in the past which makes it last foreverkeep in mind that i had to set lifetime 0 in sessionsphp so that i can trigger the remember me function based on user preference so changing this into a week would not work in my casethanks,['php'] +520204,how i can remove all newline from a variable in sql server how i can remove all newline from a variable in sql serveri use sql server 2008 r2i need remove all newline in a variable in a tsql commandfor example declare a nvarchar500 set a 12345 25487 154814 print a and it printed like this 12345 25487 154814 but i want get string like this12345 25487 154814i write this query but it not work set a replaceachar13,['sql'] +520220,sort list in reverse order i have list list1 in direct order liststring list orderingnaturalsortedcopyasu2how to change order and i do not know how to rewrite methods from extends class please write with examples or speak clearly thanks,['java'] +520222,how to get a phones azimuth with compass readings and gyroscope readings i wish to get my phones current orientation by the following methodget the initial orientation azimuth first via the getrotationmatrix and getorientationadd the integration of gyroscope reading over time to it to get the current orientationphone orientationthe phones xy plane is fixed parallel with the ground plane ie is in a textingwhilewalking orientationgetorientation returningsandroid api allows me to easily get the orientation ie azimuth pitch roll from getorientationplease note that this method always returns its value within the range 0 pi and o pimy problemsince the integration of the gyroscope reading denoted by dr may be quite big so when i do currentorientation dr the currentorientation may exceed the 0 pi and o pi rangeswhat manipulations are needed so that i can always get the current orientation within the the 0 pi and o pi rangesi have tried the following in python but i highly doubt its correctnessrotation scipyintegratetrapzgyroseries timeseries integrationif headingdirection rotation nppi headingdirection 2 nppielif headingdirection rotation nppi headingdirection 2 nppi complementary filterheadingdirection alpha headingdirection rotation 1 alpha npmeanazimuthnparraystepnotolist iif headingdirection nppi headingdirection 2 nppielif headingdirection nppi headingdirection 2 nppiremarksthis is not that simple because it involves the following troublemakersthe orientation sensor reading goes from 0 to pi and then directly jumps to pi and gradually gets back to 0 via pi2the integration of the gyrocope reading also leads to some trouble should i add dr to the orientation or subtract drdo please refer to the android documentations first before giving a confirmed answerestimated answers will not help,['android'] +520238,jquery validate element without form working on validation with aspnet webformsaspnet by default adds a form at root level which mean we need to add all the controls with in the form onlyhowever i need to define a small portion of the page which requires validation i used jquery validation pluginhtml html body form methodpost actionassetdetailsaspx idform1 enctypemultipartform data other page content goes here which doesnt require validation form classformhorizontal idvalidationform methodget div classrowfluid div classwidgetheader headercolorblue2 h5 step 1h5 div input typeemail namectl00maincontentassettabsdefinecriticalityemail idemail claspan6 div form form bodyhtmljavascript documentreadyfunction alertvalidationformlength gives 0 because this form nested under another form generated by aspnet validationformvalidate errorelement span errorclass helpinline focusinvalid false rules email required true email true messages email required please provide a valid email email please provide a valid email errorplacement function error element errorinsertafterelement but the problem is i am getting error this0 is undefined in jquery validation file i found that validationform is not found in the dom since this form is inside that stupid aspnet generated rootparent elementhow do we handle this is there a way we validate element using jquery validate plugin with out a formedit got some workaround solutionfinally i made this work with parent form and adding rules based on the field name once again aspnet webform started giving trouble by generating control name field differentlyhere is the work around code var validationparams errorelement span errorclass helpinline focusinvalid false rules messages invalidhandler function event validator alerterror loginformshow highlight function e eclosestcontrolgroupremoveclassinfoaddclasserror success function e eclosestcontrolgroupremoveclasserroraddclassinfo eremove errorplacement function error element errorinsertafterelement submithandler function form invalidhandler function form var emailfieldname emailattrname validationparamsrulesemailfieldname required true validationparamsmessagesemailfieldname required email is required form1validatevalidationparamsis there any other better way of doing it,"['jquery', 'html', 'asp.net']" +520278,thisable laravel routing for a specific folderroute i am wondering how to thisable the routing on laravel for a specific directoryi am hoping to run my main website off of laravel i am rewriting it into the framework but i would like to retain my current forum software the problem is when laravel sees the localhostforums it looks for a forums controller or route i would like it to simply go to the literal forums directory,['php'] +520309,ios push notification issue i am doing a project in which push notification feature is one of the key featureit is working fine when i am in the app i receive notification and handle that notificationbut the issue is when i am in background and notification receives i see badge on my app iconand when i click on the icon my app is launching but the didreceiveremotenotification method is not called so i am unable to handle that notificationand another issue is some times it shows the notification message in device notification list and some times it did not when i am entering in my app through clicking on notification list item the didreceiveremotenotification calls and i am successfully able to handle notificationi write following code in didfinishlaunchingwithoptionsnsdictionary launchoptions methodnsdictionary remotenotif launchoptions objectforkeyuiapplicationlaunchoptionsremotenotificationkeyif remotenotif nil nslogdidfinishlaunchingwithoptionsnnotification recievednremotenotif notificationdatansdictionary allocinitwithdictionaryremotenotif notif savenotificationremotenotifhelp me to resolve this thanks in advance,"['iphone', 'ios']" +520338,get a list of all the prefixes of a string is there any inbuilt function in the ruby string class that can give me all the prefixes of a string in ruby something likerubyall prefixes ruby rub ru rcurrently i have made a custom function for thisdef all prefixes search string dup string search stringdup return list whiledup stringlength 0 return list dup stringdup dup stringchop end return list endbut i am looking for something more rubylike less code and something magicalnote of course it goes without saying original string should remain as it is,['ruby'] +520432,devise secret key was not set i am developing a rails 4 app using the active admin gem for the administration back end active admin in turn uses devise for user authentication now when i try to deploy the app using capistrano on the vps server i get the below errorrake aborteddevisesecret key was not set please add the following to your devise initializerconfigsecret key secret key a google search does not do much for this error any suggestions why it is throwing an error should i add the secret key to devise initializer as i cannot find any place to set such config key in initializersdeviserb,['ruby-on-rails'] +520438,what is the selectlist class in c i am trying to understand c aspnet mvc4 and keep coming across selectlist i can seem to find an explanation of what it is other that thisdoes anyone have a link to a simple explanation of it and how to use it,['c#'] +520454,python flask and custom client error messages i am currently writing a rest api for an app i am working on the app is written in python using flask i have the followingtry profile profile namerequestjsonname passwordprofileget salted passwordblablabla emailrequestjsonemail created by1 last updated by1 except assertionerror abort400session databaseenginegetsessionsessionadd profiletry sessioncommitexcept integrityerror abort400the error handler looks like thisapperrorhandler400def not founderror return make responsestandard responsenone 400 bad request 400i am using the error 400 to denote both a problem with a sqlalchemy model validator and a unique constraint when writing to the database and in both cases the following error is sent to the client data null error msg bad request no 400 success falseis there a way to still use abort400 but also set the error somehow so that the error handler can take care of adding additional information for the error object in the resulti would like it to be more in line with data null error msg integrityerror duplicate key value violates unique constraint profile email key no 400 success false,['python'] +520456,javafx audio output selection i am looking for a way to specify an output device with javafxi have a similar issue as this question javafx specific audio output but with different needsi need a way to get a list of all possible audio output devices like the one you see in your user preferences and allow the user to select which one they want the audio to come out of in javafx this seems like a really basic feature that should be in any musicmedia api and is essential for most audio software i am using the mediaplayer in javafx though if there is another class i am happy to use it note though that i need the same functionality for video specifying audio output so i need a clasolution that works for both if there is something in javafx 8 that will help i can always wait until it is releasedwhat i really expected there to be was the same thing as the screens clascreengetscreens gets an observable list of all screensi am fine with hackish solutions really anything that works,['java'] +520485,remember me with aspnet web pages i realize that this question may have been asked before but i cannot find anything that matches my situation exactlyi created a website using the webmail helper in aspnet web pages not web forms and webmatrix users are required to login to the website and there is a remember me box that in theory will keep the user logged in until heshe chooses to log out the website does keep users logged in if they close the browser and reopen it within 2030 minutes however after 2030 minutes of not accessing the website the user is logged out as an aside this problem seems to exist even with the webmatrix template starter sitei have tried multiple solutions many of which were posted on stack overflow but nothing seems to work,"['c#', 'asp.net']" +520489,how to bind parameters via odbc c i need to bind parameters on odbc query from c this is the sample code but vs tells me that there is one parameter missingodbccommand cmd conncreatecommandcmdcommandtext select from user where id idcmdparametersaddid odbctypeintvalue 4odbcdatareader reader cmdexecutereaderwhat is the syntax for binding values on odbc,['c#'] +520536,laravel class not found with onetomany i am trying to return an object contract and all of it is related project i can return all of the contracts but when i try to get the contracts project i get a class estimateproject not found error i have run composer dumpautoload to reload the class mappings but i still get the error any ideas heres my class setupedit just wanted to add that laravelbookardentardent is an extension of laravels modelphp it adds validation to model on the save function i have made ardent extend another plugin i have added that is a mongodb version of the eloquent ormestimatecontractphpphp namespace testtools use laravelbookardentardent class estimatecontract extends ardent this sets the value on the mongodb plugins collection protected collection contracts public function projects return thishasmanyestimateproject contractid estimateprojectphpphp namespace testtools use laravelbookardentardent class estimateproject extends ardent this sets the value on the mongodb plugins collection protected collection projects public function contract return thisbelongstoestimatecontract contractid estimatecontractcontrollerphpphp use testtoolsestimatecontract class estimatecontractscontroller extends basecontroller thisplay a listing of the resource return response public function index contracts estimatecontractall echo contracts foreachcontracts as contract ifcontractprojects echo contractprojects,['php'] +520636,python having trouble accessing usb microphone using gstreamer to perform speech recognition with pocketsphinx on a raspberry pi so python is acting like acting like it cannot hear anything from my microphone at allheres the problem i have a python 27 script that is suppose to be using gstreamer to access my microphone and do speech recognition for me via pocketsphinx i am using pulse audio and my device is a raspberry pi my microphone is a playstation 3 eyenow off the bat i have already gotten pocketsphinx continuous to run correctly and recognize the words i have defined in my dict and lm files the accuracy is around 8590 accurate after a couple trial runs i have had so off the bat i know my microphone is picking up sound normally via pocketsphinx pulse audio fyi i ran the followingpocketsphinx continuous lm homepidevscarlettpiconfigspeechlmscarlettlm dict homepidevscarlettpiconfigspeechdictscarlettdic hmm homepidevscarlettpiconfigspeechmodelhmmen ushub4wsj sc 8k silprob 01 wip 1e4 bestpath 0in my python code i am attempting to do the same thing but i am using gstreamer to access the microphone in python note i am a bit new to python here is my code thanks josip lisec for getting me this far import pifrom pibecore import scarlettconfigfrom recorder import recorderfrom brain import brainimport osimport jsonimport tempfileimport sysimport pygtkpygtkrequire20import gtkimport gobjectimport pygstpygstrequire010gobjectthreads initimport gstscarlett configscarlettconfigclass listener def init self gobject gst selffailed 0 selfpipeline gstparse launch joinpulsesrc audioconvert audioresample vader namevader autothresholdtrue pocketsphinx lm scarlett configgetlm dict scarlett configgetdict hmm scarlett configgethmm namelistener fakesink listener selfpipelineget by namelistener listenerconnectresult self result listenerset propertyconfigured true print keywords were looking for scarlett configgetourkeywords bus selfpipelineget bus busadd signal watch busconnectmessageapplication self application message selfpipelineset stategststate playing def resultself hyp uttid if hyp in scarlett configgetourkeywords selffailed 0 selflisten else selffailed 1 if selffailed 4 pispeak scarlett configgetscarlett owner if you need me just say my name selffailed 0 def listenself selfpipelineset stategststate paused piplaypilistening recorderself def cancel listeningself piplaypicancel selfpipelineset stategststate playing question sound recording def answerself question piplaypicancel print contacting google destf tempfilemktempsuffixpiresult ossystemwget postfile s useragentmozilla50 macintosh intel mac os x 10 6 8 applewebkit5357 khtml like gecko chrome16091277 safari5357 headercontenttype audioxflac rate160 o s q langenus question destf ossystemspeech2text s s question destf b opendestf result bread bclose osunlinkquestion osunlinkdestf if lenresult 0 print nop piplaypicancel else brain brainjsonloadsresult if brainthink false print nop2 piplaypicancel selfpipelineset stategststate playing def result self listener text uttid struct gststructureresult structset valuehyp text structset valueuttid uttid listenerpost messagegstmessage new applicationlistener struct def application message self bus msg msgtype msgstructureget name if msgtype result selfresultmsgstructurehyp msgstructureuttidthe application is suppose to match on the keyword scarlett then perform an action after thatwhen i run my application i get the following outputpiscarlettpi devscarlettpiscriptspibin pi usrlibpython27thistpackagesgtk20gtk init py57 gtkwarning could not open thisplay warningswarnstre gtkwarninginfo cmd lnc691 parsing command linegstpocketsphinx samprate 80 cmn prior fwdflat no bestpath no maxhmmpf 20 maxwpf 20 current configurationname deflt valueagc none noneagcthresh 20 20e00alpha 097 970e01ascale 200 20e01aw 1 1backtrace no nobeam 1e48 10e48bestpath no nobestpathlw 95 950e00bghist no noceplen 13 13cmn current priorcmninit 80 80compallsen no nodebug 0dict dictcase no nodither no nodoublebw no nods 1 1fdict feat 1s c d dd 1s c d ddfeatparams fillprob 1e8 10e08frate 100 100fsg fsgusealtpron yes yesfsgusefiller yes yesfwdflat yes nofwdflatbeam 1e64 10e64fwdflatefwid 4 4fwdflatlw 85 850e00fwdflatsfwin 25 25fwdflatwbeam 7e29 70e29fwdtree yes yeshmm input endian little littlejsgf kdmaxbbi 1 1kdmaxdepth 0 0kdtree latsize 50 50lda ldadim 0 0lextreedump 0 0lifter 0 0lm lmctl lmname default defaultlogbase 101 10100e00logfn logspec no nolowerf 134 13e02lpbeam 1e40 10e40lponlybeam 7e29 70e29lw 65 650e00maxhmmpf 1 20maxnewoov 20 20maxwpf 1 20mdef mean mfclogdir min endfr 0 0mixw mixwfloor 01 10e07mllr mmap yes yesncep 13 13nfft 512 512nfilt 40 40nwpen 10 10e00pbeam 1e48 10e48pip 10 10e00pl beam 1e10 10e10pl pbeam 1e5 10e05pl window 0 0rawlogdir remove dc no noround filters yes yessamprate 160 80e03seed 1 1sendump senlogdir senmgau silprob 01 10e01smoothspec no nosvspec tmat tmatfloor 01 10e04topn 4 4topn beam 0 0toprule transform legacy legacyunit area yes yesupperf 68554976 6855498e03usewdphones no nouw 10 10e00var varfloor 01 10e04varnorm no noverbose no nowarp params warp type inverse linear inverse linearwbeam 7e29 70e29wip 1e4 10e04wlen 0025625 2562500e02info cmd lnc691 parsing command line nfilt 20 lowerf 1 upperf 40 wlen 0025 transform dct round filters no remove dc yes svspec 01213252638 feat 1s c d dd agc none cmn current cmninit 5631 varnorm no current configurationname deflt valueagc none noneagcthresh 20 20e00alpha 097 970e01ceplen 13 13cmn current currentcmninit 80 5631dither no nodoublebw no nofeat 1s c d dd 1s c d ddfrate 100 100input endian little littlelda ldadim 0 0lifter 0 0logspec no nolowerf 134 10e00ncep 13 13nfft 512 512nfilt 40 20remove dc no yesround filters yes nosamprate 160 80e03seed 1 1smoothspec no nosvspec 01213252638transform legacy dctunit area yes yesupperf 68554976 40e03varnorm no noverbose no nowarp params warp type inverse linear inverse linearwlen 0025625 250e02info acmodc246 parsed modelspecific feature parameters from usrlocalsharepocketsphinxmodelhmmen ushub4wsj sc 8kfeatparamsinfo featc713 initializing feature stream to type 1s c d dd ceplen13 cmncurrent varnormno agcnoneinfo cmnc142 mean0 1200 mean112 00info acmodc167 using subvector specification 01213252638info mdefc517 reading model definition usrlocalsharepocketsphinxmodelhmmen ushub4wsj sc 8kmdefinfo mdefc528 found byteorder mark bmdf assuming this is a binary mdef fileinfo bin mdefc336 reading binary model definition usrlocalsharepocketsphinxmodelhmmen ushub4wsj sc 8kmdefinfo bin mdefc513 50 ciphone 143047 cdphone 3 emitstatephone 150 cisen 5150 sen 27135 senseqinfo tmatc205 reading hmm transition probability matrices usrlocalsharepocketsphinxmodelhmmen ushub4wsj sc 8ktransition matricesinfo acmodc121 attempting to use schmm computation moduleinfo ms gaudenc198 reading mixture gaussian parameter usrlocalsharepocketsphinxmodelhmmen ushub4wsj sc 8kmeansinfo ms gaudenc292 1 codebook 3 feature size info ms gaudenc294 256x13info ms gaudenc294 256x13info ms gaudenc294 256x13info ms gaudenc198 reading mixture gaussian parameter usrlocalsharepocketsphinxmodelhmmen ushub4wsj sc 8kvariancesinfo ms gaudenc292 1 codebook 3 feature size info ms gaudenc294 256x13info ms gaudenc294 256x13info ms gaudenc294 256x13info ms gaudenc354 0 variance values flooredinfo s2 semi mgauc903 loading senones from dump file usrlocalsharepocketsphinxmodelhmmen ushub4wsj sc 8ksendumpinfo s2 semi mgauc927 begin file format descriptioninfo s2 semi mgauc1022 using memorymapped io for senonesinfo s2 semi mgauc1296 maximum topn 4 topn beams 0 0 0info dictc317 allocating 4120 20 bytes 80 kib for word entriesinfo dictc332 reading main dictionary homepidevscarlettpiconfigspeechdictscarlettdicinfo dictc211 allocated 0 kib for strings 0 kib for phonesinfo dictc335 13 words readinfo dictc341 reading filler dictionary usrlocalsharepocketsphinxmodelhmmen ushub4wsj sc 8knoisedictinfo dictc211 allocated 0 kib for strings 0 kib for phonesinfo dictc344 11 words readinfo dict2pidc396 building pid tables for dictionaryinfo dict2pidc404 allocating 503 2 bytes 244 kib for wordinitial triphonesinfo dict2pidc131 allocated 30200 bytes 29 kib for wordfinal triphonesinfo dict2pidc195 allocated 30200 bytes 29 kib for singlephone word triphonesinfo ngram model arpac477 ngrams 112 218 317info ngram model arpac135 reading unigramsinfo ngram model arpac516 12 unigrams createdinfo ngram model arpac195 reading bigramsinfo ngram model arpac533 18 bigrams createdinfo ngram model arpac534 3 prob2 entriesinfo ngram model arpac542 3 bo wt2 entriesinfo ngram model arpac292 reading trigramsinfo ngram model arpac5 17 trigrams createdinfo ngram model arpac556 2 prob3 entriesinfo ngram search fwdtreec99 12 unique initial diphonesinfo ngram search fwdtreec147 0 root 0 nonroot channels 12 singlephone wordsinfo ngram search fwdtreec186 creating search treeinfo ngram search fwdtreec191 before 0 root 0 nonroot channels 12 singlephone wordsinfo ngram search fwdtreec326 after max nonroot chan increased to 152info ngram search fwdtreec338 after 12 root 24 nonroot channels 11 singlephone wordskeywords were looking for scarlett scarlett but it fails to match on anything i almost think python can not hear anything from the microphone there are not even any attempts to recognize anything in pocketsphinx continuious it usually prints out a ready state when its prepared to start listeningi expect the same in pythonhere are my python packagespiscarlettpi devscarlettpiscriptspibin dpkg l grep i pythonii idle 2734 all ide for python using tkinter default versionii idlepython27 2736 all ide for python v27 using tkinterrc idle3 3236 all ide for python using tkinter default versionii libpyside11armhf 13 armhf python bindings for qt 4 base filesii libpython26 26811 armhf shared python runtime library version 26ii libpython27 2736 armhf shared python runtime library version 27ii libshiboken11armhf 1 armhf cpython bindings generator for c libraries shared libraryii python 2734 all interactive highlevel objectoriented language default versionii pythonalsaaudio 05svn361 armhf alsa bindings for pythonii pythoncairo 1881 armhf python bindings for the cairo vector graphics libraryii pythondbg 2734 all debug build of the python interpreter version 27ii pythondbus 1 armhf simple interprocess messaging system python interfaceii pythondbusdev 1 all main loop integration development files for pythondbusii pythondev 2734 all header files and a static library for python defaultii pythongi 32 armhf python 2x bindings for gobjectintrospection librariesii pythongidbg 32 armhf python bindings for the gobject library debug extensionii pythongidev 32 all development headers for gobject python bindingsii pythongobject 32 all python 2x bindings for gobject transitional packageii pythongobject2 228610 armhf deprecated static python bindings for the gobject libraryii pythongobject2dbg 228610 armhf deprecated static python bindings for the gobject library debug extensionii pythongobject2dev 228610 all development headers for the static gobject python bindingsii pythongobjectdbg 32 all python 2x debugging modules for gobject transitional packageii pythongobjectdev 32 all python 2x development headers for gobject transitional packageii pythongst010 010223 armhf generic mediaplaying framework python bindingsii pythongst010dbg 010223 armhf generic mediaplaying framework python debug bindingsii pythongst010dev 010223 armhf generic mediaplaying framework python bindingsii pythongst010rtsp 01083 armhf gstreamer rtsp server plugin python bindingsii pythongtk2 22403 armhf python bindings for the gtk widget setii pythoniplib 113 all python library to convert amongst many different ipv4 notationsii pythonlibxml2 280dfsg17nmu1 armhf python bindings for the gnome xml libraryii pythonminimal 2734 all minimal subset of the python language default versionii pythonnumpy 116212 armhf numerical python adds a fast array facility to the python languageii pythonpexpect 241 all python module for automating interactive applicationsii pythonpip 113 all alternative python package installerii pythonpkgresources 06241 all package thiscovery and resource access using pkg resourcesii pythonpyalsa 10251 armhf official alsa python binding libraryii pythonpyside 13 all python bindings for qt4 big metapackageii pythonpysidephonon 13 armhf qt 4 phonon module python bindingsii pythonpysideqtcore 13 armhf qt 4 core module python bindingsii pythonpysideqtdeclarative 13 armhf qt 4 declarative module python bindingsii pythonpysideqtgui 13 armhf qt 4 gui module python bindingsii pythonpysideqthelp 13 armhf qt 4 help module python bindingsii pythonpysideqtnetwork 13 armhf qt 4 network module python bindingsii pythonpysideqtopengl 13 armhf qt 4 opengl module python bindingsii pythonpysideqtscript 13 armhf qt 4 script module python bindingsii pythonpysideqtsql 13 armhf qt 4 sql module python bindingsii pythonpysideqtsvg 13 armhf qt 4 svg module python bindingsii pythonpysideqttest 13 armhf qt 4 test module python bindingsii pythonpysideqtuitools 13 armhf qt 4 ui tools module python bindingsii pythonpysideqtwebkit 13 armhf qt 4 webkit module python bindingsii pythonpysideqtxml 13 armhf qt 4 xml module python bindingsii pythonrpigpio 053a1 armhf python gpio module for raspberry pi pythonsetuptools 06241 all python thistutils enhancements setuptools compatibilityii pythonsimplejson 2521 armhf simple fast extensible json encoderdecoder for pythonii pythonsupport 1015 all automated rebuilding support for python modulesii pythontk 2731 armhf tkinter writing tk applications with pythonii pythonyaml 3104 armhf yaml parser and emitter for pythonii pythonyamldbg 3104 armhf yaml parser and emitter for python debug buildii python26 26811 armhf interactive highlevel objectoriented language version 26ii python26minimal 26811 armhf minimal subset of the python language version 26ii python27 2736 armhf interactive highlevel objectoriented language version 27ii python27dbg 2736 armhf debug build of the python interpreter version 27ii python27dev 2736 armhf header files and a static library for python v27ii python27minimal 2736 armhf minimal subset of the python language version 27piscarlettpi devscarlettpiscriptspibin also just to confirm that pocketsphinx is complied correctly against the right libariespiscarlettpi ldd usrlocalbinpocketsphinx continuous usrlibarmlinuxgnueabihflibcofi rpiso 0xb6f9b0 libpocketsphinxso1 usrlocalliblibpocketsphinxso1 0xb6f5a0 libsphinxadso0 usrlocalliblibsphinxadso0 0xb6f4e0 libsphinxbaseso1 usrlocalliblibsphinxbaseso1 0xb6f070 libpulseso0 usrlibarmlinuxgnueabihflibpulseso0 0xb6ea80 libpulsesimpleso0 usrlibarmlinuxgnueabihflibpulsesimpleso0 0xb6e9c0 libpthreadso0 libarmlinuxgnueabihflibpthreadso0 0xb6e7d0 libmso6 libarmlinuxgnueabihflibmso6 0xb6e0c0 libcso6 libarmlinuxgnueabihflibcso6 0xb6cdd0 libjsonso0 libarmlinuxgnueabihflibjsonso0 0xb6ccd0 libpulsecommon20so usrlibarmlinuxgnueabihfpulseaudiolibpulsecommon20so 0xb6c6b0 libdbus1so3 libarmlinuxgnueabihflibdbus1so3 0xb6c290 libcapso2 libarmlinuxgnueabihflibcapso2 0xb6c1e0 librtso1 libarmlinuxgnueabihflibrtso1 0xb6c0f0 libdlso2 libarmlinuxgnueabihflibdlso2 0xb6c040 libgcc sso1 libarmlinuxgnueabihflibgcc sso1 0xb6bdb0 libldlinuxarmhfso3 0xb6fa80 libx11xcbso1 usrlibarmlinuxgnueabihflibx11xcbso1 0xb6bd20 libx11so6 usrlibarmlinuxgnueabihflibx11so6 0xb6abe0 libxcbso1 usrlibarmlinuxgnueabihflibxcbso1 0xb6a9f0 libiceso6 usrlibarmlinuxgnueabihflibiceso6 0xb6a820 libsmso6 usrlibarmlinuxgnueabihflibsmso6 0xb6a730 libxtstso6 usrlibarmlinuxgnueabihflibxtstso6 0xb6a670 libwrapso0 libarmlinuxgnueabihflibwrapso0 0xb6a570 libsndfileso1 usrlibarmlinuxgnueabihflibsndfileso1 0xb69ee0 libasyncnsso0 usrlibarmlinuxgnueabihflibasyncnsso0 0xb69e20 libattrso1 libarmlinuxgnueabihflibattrso1 0xb69d40 libxauso6 usrlibarmlinuxgnueabihflibxauso6 0xb69ca0 libxdmcpso6 usrlibarmlinuxgnueabihflibxdmcpso6 0xb69be0 libuuidso1 libarmlinuxgnueabihflibuuidso1 0xb69b10 libxextso6 usrlibarmlinuxgnueabihflibxextso6 0xb699b0 libxiso6 usrlibarmlinuxgnueabihflibxiso6 0xb69860 libnslso1 libarmlinuxgnueabihflibnslso1 0xb696a0 libflacso8 usrlibarmlinuxgnueabihflibflacso8 0xb691f0 libvorbisencso2 usrlibarmlinuxgnueabihflibvorbisencso2 0xb67b20 libvorbisso0 usrlibarmlinuxgnueabihflibvorbisso0 0xb67820 liboggso0 usrlibarmlinuxgnueabihfliboggso0 0xb67750 libresolvso2 libarmlinuxgnueabihflibresolvso2 0xb67610piscarlettpi and if you need to see any information about my microphone ps3 eye had to throw this in pastebin ran out of room in this postdoes anyone have any ideas why this is not working please let me know if my question needs any clarification or if i can provide any more information to aid with debuggingthanks,['python'] +520658,how do i generate a sql script from my diagram in mysql workbench i have created an eer diagram with tables foreign keys etc in mysql workbench and now i want to generate a sql script that will create this database how do i do that,"['mysql', 'sql']" +520687,data truncated for column after changing the data type of a mysql column in order to store twilio call ids 34 char strings i try to manually change the data in that column withupdate calls set incoming cidca9321a83241035b4c3d3e7a4f7aa6970d where id1however i get an error which does not make sense seeing as the columns data type was properly modified level code message warning 1265 data truncated for column incoming cid at row 1,['mysql'] +520702,what is the purpose of data uris why are resources sometimes embedded in data uris rather than using a regular uri that links to a resource stored as a file on a server,['html'] +520718,moving a uiview on top of uitableview touching the top uiview still selects table rows i have a uiview which contains three containerscontainer a contains a uitableviewcontainer b contains container c and container ocontainer c contains a uitableview touch event touch event b a c an event happens where i shift the frame of container b and i show a view labeled o to the right of b which is not important now container b is overlapping container ao other view unimportant original location of touch b a o c but now when i try to select a row in container cs uitableview by touching the left edge of the row the touch is being registered by container as uitableview or even if i touch on the view above the table the corresponding row in a is selectedi can solve part of the problem by changing the width of the container as uitableview but then i still have the problem where if i touch table c the cs row does not select it is like it things the start of the table c is in the old location so what can i do so that tapping at the new location will select the correct row in cedit with some codethis is code i do in container b it is a very straight forward animation of bs frame selfview is container bs uiview all the views are on the screen the other container is hidden through the storyboard other container is a subview of b this code basically aligns the other container to the rightoffscreen of container b yes extending beyond the frame of b but this part works finecgrect othercontainerframe selfothercontainerviewframeothercontainerframeoriginx cgrectgetmaxxselfviewframeselfothercontainerview setframeothercontainerframeselfothercontainerview sethiddenno i am going move container b by the width of the other viewfloat offset cgrectgetwidthselfothercontainerviewframecgrect frame selfviewframeframeoriginx offsetuiview animatewithduration35 animations selfview setframeframe please let me know what other code you want to see,"['ios', 'objective-c']" +520719,how to join mysql tables using a nullable column i am a little bit out of practice with mysql so i hope i can find some advice for my problem herebasically i have two tables call them a and b just for convenience both tables have a nullable column c of type varchar when i join a and b using c i lose all the rows where c is null in either table i know this is normal in mysql but what i would like to get is a join that includes combinations of rows where c is null in both tablesi found out that the query below seems to work wellselect from a join bon ac is null and bc is null or ac is not null and bc is not null and ac bcso my question is is this query the best i can get or is there a way to make this join better thanks,"['mysql', 'sql']" +520736,nsobject description and custom summaries in xcode i override objects nsstringdescription however xcode always thisplays error summary string parsing error in summary field in variables viewmy current implementation is the following nsstringdescription return nsstring stringwithformat p xf yf selfclass self x yif i type po objectname in console lldb shows a fine output as expected however xcode and command p objectname always indicate error so whats the proper debug description format to make summary field work worth to notice that the output of p command is the same as a summary message that you see in xcode for instances of foundation classesupdateas far as i can see from wwdc 2012 session debugging in xcode custom summaries can be implemented using custom python script only nsstringdescription or nsstringdebugdescription methods are not connected anyhow to summary messages i thought they are because i got an error thisplayed but it seems it is a standard message for classes that do not have their own formatters,['objective-c'] +520787,whats with 181783497276652981 and 8682522807148012 in random java 7 why were 181783497276652981 and 8682522807148012 chosen in randomjavaheres the relevant source code from java se jdk 17 creates a new random number generator this constructor sets the seed of the random number generator to a value very likely to be thistinct from any other invocation of this constructor public random thisseeduniquifier systemnanotimeprivate static long seeduniquifier lecuyer tables of linear congruential generators of different sizes and good lattice structure 19 for long current seeduniquifierget long next current 181783497276652981l if seeduniquifiercompareandsetcurrent next return next private static final atomiclong seeduniquifier new atomiclong8682522807148012lso invoking new random without any seed parameter takes the current seed uniquifier and xors it with systemnanotime then it uses 181783497276652981 to create another seed uniquifier to be stored for the next time new random is calledthe literals 181783497276652981l and 8682522807148012l are not placed in constants but they do not appear anywhere elseat first the comment gives me an easy lead searching online for that article yields the actual article 8682522807148012 does not appear in the paper but 181783497276652981 does appear as a substring of another number 1181783497276652981 which is 181783497276652981 with a 1 prependedthe paper claims that 1181783497276652981 is a number that yields good merit for a linear congruential generator was this number simply miscopied into java does 181783497276652981 have an acceptable meritand why was 8682522807148012 chosensearching online for either number yields no explanation only this page that also notices the dropped 1 in front of 181783497276652981could other numbers have been chosen that would have worked as well as these two numbers why or why not,['java'] +520788,int promotion to unsigned int in c and c have a look at this c codeint main unsigned int y 10 int x 2 if x y printfx is greater else printfy is greater return 0output x is greater i understand why the output is x is greater because when the computer compares both of them x is promoted to an unsigned integer typewhen x is promoted to unsigned integer 2 becomes 65534 which is definitely greater than 10but why in c does the equivalent code give the opposite resultpublic static void mainstring args uint y 10 int x 2 if x y consolewritelinex is greater else consolewriteliney is greater output y is greater,['c#'] +520829,meteor collection transform is it done on the server or on the client or it depends i want to use transform to make a virtual field out of a collection however the new field i am adding within the transform function is adding quite a bit of data to the returned document this is fine if the transform is taking place inside the client if it is done on serverside then there will be bandwidth concernsso i am wondering if the transform is done on the server or on the client or it depends on how i findfetch the document,['javascript'] +520832,how can i center twitterbootstrap 3 navbar buttons how can i center the buttons in the jsfiddle i set up so that the buttons are equally spaced and centered within and throughout the navbari have tried different methods such asthisplayinlineblockmargin0 auto textaligncenterbut i cannot get it to workif you could give a little explanation instead of just fixing the css as i want to learn so i do not have to keep coming back hereeditjust like how they are centered here,['css'] +520902,android 43 keychain example i am trying to understand the keychain concept in android 43 and i will really appreciate it if i can get a example to understand it,['android'] +520924,ios compatible input type date setting min max value i am trying to set the date using jquerymobile in uiwebview ios app value is set properly but the min and max attribute date setting is not workinginput typedate dataclearbtnfalse namedate1 iddate1 min20130415 max20130915 value 20130815 and inputtypedatevalymmddwhen i run it on simulator when the date field is selected date picker is visible but the min max date is not set,['ios'] +520937,released unknown bitmap reference i am trying to set icon of a marker in google maps v2i am downloading some images over network and change their background in code after that i am setting them as icons to markers at first creation of the map it works fine but after rotation there is an exceptionandroid version i run this on 43my code is as follows urlimageviewhelperloadurldrawabletuvaletlermapactivitythis iconurl new urlimageviewcallback override public void onloadedimageview iv bitmap bm string arg2 boolean arg3 bitmap bitmap venueshelpericonizebitmapbm markerseticonbitmapdescriptorfactory frombitmapbitmap and venueshelpericonizebitmap is as followspublic static bitmap iconizebitmapbitmap bm bitmap bitmap bitmapcreatebitmapbmgetwidth bmgetheight bmgetconfig canvas canvas new canvasbitmap canvasdrawcolorcolorparsecolor33b5e5 canvasdrawbitmapbm 0 0 null return bitmapstack trace is as follows0807 101650684 eandroidruntime19001 fatal exception main0807 101650684 eandroidruntime19001 javalangillegalargumentexception released unknown bitmap reference0807 101650684 eandroidruntime19001 at mapsasiaunknown source0807 101650684 eandroidruntime19001 at mapsahobunknown source0807 101650684 eandroidruntime19001 at mapsahbnaunknown source0807 101650684 eandroidruntime19001 at bixontransactsourcefile2040807 101650684 eandroidruntime19001 at androidosbindertransactbinderjava3470807 101650684 eandroidruntime19001 at comgoogleandroidgmsinternaldmaafunknown source0807 101650684 eandroidruntime19001 at comgoogleandroidgmsmapsmodelmarkerseticonunknown source0807 101650684 eandroidruntime19001 at combehlultuvaletbultuvaletlermapactivitytuvaletliyuklecallbacks1onloadedtuvaletlermapactivityjava2500807 101650684 eandroidruntime19001 at comkoushikduttaurlimageviewhelperurlimageviewhelper2runurlimageviewhelperjava6150807 101650684 eandroidruntime19001 at comkoushikduttaurlimageviewhelperurlimageviewhelper3onpostexecuteurlimageviewhelperjava6530807 101650684 eandroidruntime19001 at comkoushikduttaurlimageviewhelperurlimageviewhelper3onpostexecuteurlimageviewhelperjava10807 101650684 eandroidruntime19001 at androidosasynctaskfinishasynctaskjava6310807 101650684 eandroidruntime19001 at androidosasynctaskaccess600asynctaskjava1770807 101650684 eandroidruntime19001 at androidosasynctaskinternalhandlerhandlemessageasynctaskjava6440807 101650684 eandroidruntime19001 at androidoshandlerthispatchmessagehandlerjava990807 101650684 eandroidruntime19001 at androidoslooperlooplooperjava1370807 101650684 eandroidruntime19001 at androidappactivitythreadmainactivitythreadjava51030807 101650684 eandroidruntime19001 at javalangreflectmethodinvokenativenative method0807 101650684 eandroidruntime19001 at javalangreflectmethodinvokemethodjava5250807 101650684 eandroidruntime19001 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava7370807 101650684 eandroidruntime19001 at comandroidinternaloszygoteinitmainzygoteinitjava5530807 101650684 eandroidruntime19001 at dalviksystemnativestartmainnative method,['android'] +520949,new phonegap 30 the import orgapachecordova cannot be resolved i am installing the new phone gap 30 with the allmighty command line cordova create hello comexamplehello helloworldcordova platform add androidwhen i open the android project in eclipse i get this error on helloworldjavathe import orgapachecordova cannot be resolvedi guess i have a missing library but how to i solve this if the only way to install 30 is thought the command line,"['java', 'javascript', 'android']" +520961,java how to check if a string value is a type of given class alright this is kind of a complicated question and i am completely lostassume you have a string and a generic class like thisstring stringclass clazzhow would you check to see if the string represented a value that the class could equalfor example lets say thatstring string trueclass clazz booleanclasshow would i check and see that the string true is in fact a booleanhere is another example lets say thatstring string trueclass clazz integerclasshow would i check and see that the string true is not an integer,['java'] +520964,adb hell command not a typo i have a question about adb does anyone know what is the difference betweenadb shell adb hell commandsi am wondering if except the hellish terminal coloronly on linux in windows you just get some prefixes there are any other differencesseriously check yourself,['android'] +520974,unit test for only root user in python does unit test library for python especially 3x i do not really care about 2x has decorator to be accessed only by root useri have this testing functiondef test blabla as root selfassertequalblabla 1blabla function can only be executed by root i want root user only decorator so normal user will skip this testsupportroot onlydef test blabla as root selfassertequalblabla 1does such decorator exist we have supportcpython only decorator though,['python'] +520979,how to get raw text from pdf file using java i have some pdf files using pdfbox i have converted them into text and stored into text files now from the text files i want to removehyperlinksall special charactersblank linesheaders footers of pdf filesa1aa2a a abulletsa etci want to get valid text line by line like thiswe propose ontogain a method for ontology learning from multiword concept terms extracted from plain text ontogain follows an ontology learning process dened by thistinct processing layers building upon plain term extraction a concept hierarchy is formed by clustering the extracted concepts the derived term taxonomy is then enriched with nontaxonomic relations several dierent stateoftheart methods have been examined for implementing each layer ontogain is based upon multiword term concepts as multiword or compound terms are vested with more solid and thistinctive semantics than plain single word terms we opted for a hierarchical clustering method and formal concept analysis fca algorithm for building the term taxonomy furthermore an association rule algorithm is applied for revealing nontaxonomic relations a method which tries to carry out the most appropriate generalization level between a relations concepts is also implemented to show proof of concept a system prototype is implemented the ontogain allows transformation of the derived ontology into owl using jena semantic web framework1 ontogain is applied on two separate data sources a medical and computer corpus and its results are compared with similar results obtained by text2onto a stateoftheartontology learning method the analysis of 115 ccd11 results indicates that ontogain performs better than text2onto in terms of precision extracts more correct concepts while being more selective extracts fewer but more reasonable conceptshow can i achieve this,['java'] +521045,an input in a form named action overrides the forms action property is this a bug i have a form marked up as form classform1 methodpost actionform1php stylewidth405pxordinarily i could access the action of the form in javascript by referring to the action of the form object for exampledocumentforms0actionwhich would return the valueform1phphowever if i have as a component of the form an item named action this action becomes the content of the forms action that is if the form markup contains for example input nameaction typehidden valuecheck then documentforms0actionreturns the value input nameaction typehidden valuecheck now i did work out how to get around this by using documentforms0getattributeactionhowever it is a nasty gotcha that confused me for too long is this a bug a known gotcha of dom management or should i just get into the habit of using getattribute,['javascript'] +521046,how to set a background image in rails from css i am using rails 32 and i have to set a background for one of the page and i have tried many ways and nothing went right so looking for some good help i have tried background url asset path backgroundjpg background urlpublicbackgroundjpgbackgroundimageurlassetsimagesbackgroundjpgand nothing worked please help me,"['css', 'ruby-on-rails']" +521066,what is the difference between setbackgroundresource and setbackgrounddrawable could anyone tell me what is the difference between setbackgroundresourceresourceid and setbackgrounddrawablegetresourcegetdrawabledrawableid in android,['android'] +521105,java experimenting with generics lastly i experimenting with generics a little bit i came up with this piece of codepublic class test static t void ft x x t integer 1234 systemoutprintlnx public static void mainstring args fa f1 fa f15 fnew linkedliststring fnew hashmapstring string i ran this and got this output123412341234123412341234with no exceptions how is it possible,['java'] +521122,for loop in array reads remove i just experienced the strangest thing this is the code i am actually using for iter in datalist consolelogiteras you would expect the log should give the number of each row 0 1 2 instead it gives me this 012removeknowing that my array only has 3 rowsdid anybody ever encountred this,['javascript'] +521270,nsnotification sent once but is received multiple times i am communicating between two classes with nsnotificationcenter my problem is that although i tap a button once and that button only fires off once i am unintentionally producing increasing numbers of notifications from only one call to the nsnotificationcenterhere is a better explanation of the problem with codemy two classes are the mainview class and the menu classwhen a view in the mainview class is tapped it launches a view created and governed by the menu class this code is called when the mainview is initializedmenumymenu alloc inituitapgesturerecognizer tapuitapgesturerecognizer alloc initwithtargetself actionselectorontappedtap setnumberoftapsrequired1container addgesturerecognizertapnsnotificationcenter defaultcenter addobserverself selectorselectoronchangeitem nameitemchange objectnilthis gesture recognizer fires off this method also in the mainview class void ontapped uigesturerecognizer recognizer nslogtap menu thisplaymenuthis is how the menu class initializes mymenu init selfsuper init uicollectionviewflowlayout layoutuicollectionviewflowlayout alloc init menuviewuicollectionview alloc initwithframecgrectmake0 0 200 200 collectionviewlayoutlayout menuview setdatasourceself menuview setdelegateself menuview registerclassuicollectionviewcell class forcellwithreuseidentifiercell menuview setautoresizessubviewsyes menuview setautoresizingmaskuiviewautoresizingflexibleheight uiviewautoresizingflexiblewidth menuview setbackgroundcoloruicolor clearcolor menuview setindicatorstyleuiscrollviewindicatorstylewhite return selfand this is the thisplaymenu method inside the menu class void thisplaymenu viewformenu addsubviewmenuviewthe menu class also has a clearmenu method void clearmenu menuview removefromsuperviewthis is the code for each cell in the uicollectionview contained within my menu class uicollectionviewcell collectionviewuicollectionview collectionview cellforitematindexpathnsindexpath indexpath uicollectionviewcell cellcollectionview dequeuereusablecellwithreuseidentifiercell forindexpathindexpath cell settagindexpathrow uitapgesturerecognizer tapuitapgesturerecognizer alloc initwithtargetself actionselectoronbuttontapped tap setnumberoftapsrequired1 cell addgesturerecognizertap nslogbutton tapped dindexpathrow return cellthis calls the onbuttontapped method also within my menu class void onbuttontappeduigesturerecognizer recognizer nsinteger buttontappedrecognizer view tag nsnotificationcenter defaultcenter postnotificationnameitemchange objectnil userinfoselectedbuttontappedself clearmenuthis notification is picked up by my mainview class with this codensnotificationcenter defaultcenter addobserverself selectorselectoronchangeitem nameitemchange objectnilthis calls the onchangeitem method inside my mainview class void onchangeitem nsnotification notification nslogchange item to dnotification userinfo objectforkeyclock intvalueso that is the codeok heres the problem the first time the menu thisplays i get this in my log4302311f03 tap4302311f03 button tapped 14302311f03 change item to 1and this is fine this is what i expect however second time around i get this4302311f03 tap4302311f03 button tapped 14302311f03 change item to 14302311f03 change item to 1third time around i get this4302311f03 tap4302311f03 button tapped 14302311f03 change item to 14302311f03 change item to 14302311f03 change item to 14302311f03 change item to 1and so on each successive tap on a menu item doubles the amount of notification callsto begin with i thought i was adding multiple views and thus resulting in multiple button taps and therefore multiple notifications calls however as you can see from my logs this is not the case the buttons are only receiving 1 tap event this is firing off only 1 notification but receiving class gets sent multiple notificationscan anyone explain this to mesorry for the lengthy post,['objective-c'] +521347,devicepolicymanagerlocknow does not turn off screen when security settings are set to slidenone the user expects my app to switch off the screen after being used at the moment i achieve this with device administrator rights and devicepolicymanagerlocknow which works fine if the security settings are set to pinpatternfaceunlock etc however if using slidenone the above command just takes the user to the homescreen or does not do anything which is understandable since there is nothing to lock is there any way to achieve turning off the screen in such a situation my app requires sdk16 if that mattersso i guess my question is how can an app reliably switch off the screen i am not holding a wakelock i am using the windowmanagerflags flag turn screen on in onattachedtowindowthe flow of my app is activity is started by an intent while the screen is off shows above the keyguardswitches on the screen with the abovementioned flags user actively thismisses my activity i am calling locknow and finish and the user expects the screen to turn off if the user is using the noneslide lock this does not work and instead the users homescreen is shownthanks,['android'] +521352,c count vowels i am learning to program c and i am trying to count the vowels i am getting the program to loop through the sentence but instead of returning vowel count it is just returning the length of the string any help would be greatly appreciated static void main int total 0 consolewritelineenter a sentence string sentence consolereadlinetolower for int i 0 i sentencelength i if sentencecontainsa sentencecontainse sentencecontainsi sentencecontainso sentencecontainsu total consolewritelineyour total number of vowels is 0 total consolereadline,['c#'] +521364,processing a string with antlr4 i am trying to convert my grammar from v3 to v4 and having some trouble finding all the right piecesin v3 to process a string i usedpublic static dataextractor createstring dataspec charstream stream new antlrstringstreamdataspec dataspecificationlexer lexer new dataspecificationlexerstream commontokenstream tokens new commontokenstreamlexer dataspecificationparser parser new dataspecificationparsertokens return parserdataspechow do i change this to work in v4,['java'] +521414,git cant diff or merge cs file in utf16 encoding a friend and i were working on the same cs file at the same time and when there is a merge conflict git points out there is a conflict but the file isnt loaded with the usual head stuff because the cs files were binary files so we added numerous things cs text and so on to our gitattributes file to make git treat it as a text file which didnt work thats when we realized that git could diff other cs files and just not this one the reason for that is because its in unicode encoding as it contains some chinese characters so how do we make git diff or merge files that are in utf16 or utf8 formatthe furstrating thing is that if i push gitlab shows exactly whats different so i dont get how git can diff on the server but not with bash,['c#'] +521504,python catch ctrlc command prompt really want to quit yn resume execution if no i have a program that may have a lengthy execution in the main module i have the following import signaldef run program time consuming executiondef exit gracefullysignal frame log exiting information close any open files sysexit0if name main signalsignalsignalsigint exit gracefully run programthis works fine but i would like the possibility to pause execution upon catching sigint prompting the user if they would really like to quit and resuming where i left off in run program if they decide they do not want to quitthe only way i can think of doing this is running the program in a separate thread keeping the main thread waiting on it and ready to catch sigint if the user wants to quit the main thread can do cleanup and kill the child threadis there a simpler way,['python'] +521529,gwt custom event trigger in javascript i have an application that is half gwt and half backbonejs were transitioning the app from gwt to backbone so as we add new components they are in backbone were also replacing some existing components with backbone as well there is a component that i am attempting to replace that still needs to be able to let its gwt container know when certain events occur so that the container can impact other gwt components i have a native function in gwt that references a global namespace on which a function is defined in javascript that function renders the backbone component so gwt does not have a reference to the component itselfi tried defining a custom dom event in gwt and then triggering that event from the backbone code but either i did it wrong or that is not the way to do iti referenced these questions in creating my custom event how to add css animationend event handler to gwt widget gwt custom eventsi made two attempts at triggering the custom event from backbone and having gwt listen for it neither workedi need help triggering an event or calling a callback or something equivalent from javascript backbonejs that will be heard or called or whatever in gwtcode code common between two attempts is how the backbone component is rendered and how the event is triggeredfrom class backbonecontrollerjavapublic static void loadmessageentryfinal string selector final string type final quipuid conversationid final quipuid messageid final boolean enterissubmit string messageidstring messageidgetid string enterrole enterissubmit submit newline ifmessageidequalsquipuidnull messageidstring showmessageentryselector type conversationidgetid messageidstring enterroleprivate static native void showmessageentrystring selector string type string messageid string conversationid string enterrole var intervaltimer wndsetintervalfunction ifwndnamespacemessageentry wndnamespacemessageentrythisplaymessageentryselector type messageid conversationid enterrole wndclearintervalintervaltimer 500from class myclientbootstrapjsnamespacemessageentry namespacemessageentry namespacemessageentrythisplaymessageentry functionselector type conversationid messageid enterrole var messageentry instancename selectorslice1 ifckeditorinstancesinstancename ckeditorinstancesinstancenametriggershow else messageentry new messageentry model new rtemodelmode inline type type conversationid conversationid messageid messageid enterrole enterrole selectorappendmessageentryel from class messageentryviewjs called when the upload button is clickedopendocumentuploader function thismodelgetidtriggermessageentrydocumentuploadfrom class messageentryjavaattempt 1 private native void registermessageentryeventhandlerfinal element messageentry final messageentryhandler handler var callback function onmessageentryeventlmypathclientmessageentryevent messageentryaddeventlistenermessageentry callback false private void initlayout initwidgetmaindocklayoutpanel conversation model conversationcontrollergetmodel messageentrypanelgetelementaddclassnamerichtextareaid modelgetid backbonecontrollerloadmessageentryrichtextareaid modelgetid message modelgetid quipuidnull booleanpreferencesmodelgetinstanceisautosubmit registermessageentryeventhandlermessageentrypanelgetelement new messageentryhandler override public void onmessageentryeventmessageentryevent event ifeventgeteventtype documentupload messageentrythisswitchtodocumentupload maindocklayoutpaneladdstylenamemessageentrybundleinstancecsscontainer modesimplepaneladdmessageentrypanel maindocklayoutpaneladdmodesimplepanelattempt 2 private void initlayout initwidgetmaindocklayoutpanel conversation model conversationcontrollergetmodel messageentrypanelgetelementaddclassnamerichtextareaid modelgetid backbonecontrollerloadmessageentryrichtextareaid modelgetid message modelgetid quipuidnull booleanpreferencesmodelgetinstanceisautosubmit adomhandlernew messageentryhandler override public void onmessageentryeventmessageentryevent event ifeventgeteventtype documentupload messageentrythisswitchtodocumentupload messageentryeventgettype maindocklayoutpaneladdstylenamemessageentrybundleinstancecsscontainer modesimplepaneladdmessageentrypanel maindocklayoutpaneladdmodesimplepaneleditmade another attempt this has a few more differences than between the first two when we create our namespace we do extendnamespace backboneevents so that we can trigger events from gwt that the backbone code will listen for i decided to try getting it to work in the other direction it did notattempt 3from messageentryviewjsopendocumentuploader function namespacetriggernamespaceeventsuploadfrom messageentryjava private native void registeruploadlistenermessageentry msgentry wndnamespaceonwndnamespaceeventsupload function switchtodocumentupload private void initlayout initwidgetmaindocklayoutpanel conversation model conversationcontrollergetmodel messageentrypanelgetelementaddclassnamerichtextareaid modelgetid backbonecontrollerloadmessageentryrichtextareaid modelgetid message modelgetid quipuidnull booleanpreferencesmodelgetinstanceisautosubmit registeruploadlistenerthis maindocklayoutpaneladdstylenamemessageentrybundleinstancecsscontainer modesimplepaneladdmessageentrypanel maindocklayoutpaneladdmodesimplepanel,"['java', 'javascript']" +521629,using css to set default font i have a file cssfontstylecss containing this codecourier fontfamily courierand my aspx file has this code page title languagec masterpagefilesitemaster autoeventwireuptrue codebehindtut1aspxcs inheritsrtwtut1 aspcontent idcontent1 contentplaceholderidstatuslabel runatserveraspcontentaspcontent idcontent3 contentplaceholderidmaincontent runatserver link relstylesheet hrefcssfontstylecss h2unsigned vs signed integersh2lots of text is below herehowever the font remains in time new roman i can use other css files from the same folder find not sure why this one does not workthanks in advance,['css'] +521674,can we use same csr to create certificates for different companies i have a quick question i develop ios apps for multiple clients each client has their own apple accounts and i create certificates for them from my machine my question here is can i use the same csr file to create certificates for different companies thanks,['ios'] +521697,dynamically changing the fragments inside a fragment tab host i have one main activity which is fragment activity here i am setting two tabs with two fragments a and b in the b fragment i have one button when the user click on the button i want to change fragment b to fragment c but the tabs above are visiblehow i can achieve replacing fragments inside tabsany solution are greatly appreciated,['android'] +521711,sql query thistinct with row number i am fighting with the thistinct keyword in sqli just want to thisplay all row numbers of unique thistinct values in a column so i tried select thistinct id row number over order by id as rownum from table where fid 64however the below code giving me the thistinct values select thistinct id from table where fid 64but when tried it with row numberthen it not workingany help would be appreciatedthanx,['sql'] +521731,how to capture the onswipedown event on google glass using a native app i was able to capture most of the events triggered by the touchpad of a google glass using the simpleongesturelistener in a native appwith the following code you can capture these eventsmainactivityjavaprivate gesturedetector gesturedetectoroverrideprotected void oncreatebundle savedinstancestate gesturedetector new gesturedetectorthis new mygesturelisteneroverridepublic boolean ongenericmotioneventmotionevent event gesturedetectorontoucheventevent return truemygesturelistenerpublic class mygesturelistener extends androidviewgesturedetectorsimpleongesturelistener override public boolean onflingmotionevent start motionevent finish float velocityx float velocityy check for velocity direction to identify swipe forward backward up and down return true i found two different sources for gesture processing i triedcapture glass dpad events in androidcapturing gesture controls for use in native android glass appsbut with none of them i was able to catch the swipedown eventthe callback onfling is only called on swipe forward swipe backward and swipe up but never called when i do a swipe downany hints or have you already managed to catch the swipe down i am really clueless here,['android'] +521787,set arguments of fragment from activity i want to pass arguments from my activity to a fragment embedded into the activity fragment is embedded statically in xml layouti tried to call setargument like thissetcontentviewrlayoutdetail activitydetailfragment detailfragment detailfragment getfragmentmanagerfindfragmentbyidriddetailfragmentdetailfragmentsetargumentsgetintentgetextrasbut it is already too late because setarguments has to be called immediately after fragments creation the only was i see it to getarguments and the change the bundle any better way,['android'] +521791,hibernate which naming strategy is default when researching how to implement a custom naming strategy for table names only i stumbled upon an inconsistency which i cannot resolvei am using hibernatecore 366final on jboss 610final with postgresql 919there seem to be three builtin implementations for namingstrategydefaultnamingstrategyejb3namingstrategyimprovednamingstrategythe default seems to be set to ejb3namingstrategy in orghibernatecfgconfigurationhowever the table names seem to be set according to a strategy that matches none of the aboveexampleclass name packageclassnameresulting table name classname strategies 1 and 2 simply call stringhelperunqualify classname which simply removes all package names and dots so the result should be classnamestrategy 3 removes all package names and dots then puts an underscore before each camelcased letter and finally converts to lowercase which should yield class namesource code of hibernate 410final seems to be unchanged in these classescould anyone help me clarify this,['java'] +521805,how to protect against csrf when using backbonejs to post data backbonejs handles posting data to server under the hood so there is no easy way to insert a csrf token in the payload how can i protect my site against csrf in this situationin this so answer the suggestion is to verify the xrequestedby header to be xmlhttprequest is this enough to block all csrf attemptsin django docs the suggestion is to add csrf token in another custom header in every ajax request is this necessaryi understand if the attack uses hidden form i am safe by just assuring the request is from xmlhttprequest but is there any csrf attack tricks that can forge the header,['javascript'] +521823,how was the first c compiler written is it true that the first c compiler was written in c itself then how was it executed and compiled or was this compiler written in assembly language,['c'] +521830,stackoverflowerror in mathrandom in a randomly recursive method this is the context of my programa function has 50 chance to do nothing 50 to call itself twice what is the probability that the program will finish i wrote this piece of code and it works great apparently the answer which may not be obvious to everyone is that this program has 100 chance to finish but there is a stackoverflowerror how convenient when i run this program occuring in mathrandom could someone point to me where does it come from and tell me if maybe my code is wrongstatic int bestdepth 0static int numberofprograms 0testpublic void testproba forint i 0 i 10 i long time systemcurrenttimemillis bestdepth 0 numberofprograms 0 loop0 loggerinfobest depth bestdepth in systemcurrenttimemillistimems public boolean loopint depth numberofprograms ifdepth bestdepth bestdepth depth ifproba return true else return loopdepth 1 loopdepth 1 public boolean proba return mathrandom05javalangstackoverflowerrorat javautilrandomnextdoublerandomjava394at javalangmathrandommathjava695i suspect the stack and the amount of function in it is limited but i do not really see the problem hereany advice or clue are obviously welcomefabienedit thanks for your answers i ran it with java xss4m and it worked great,['java'] +521900,android 43 btle as server how to start advertisements i am trying to implement a btle server on the nexus 7 with the new btle api in 43 i am running into several problems first there are no examples with the sdk the only example is for a client second the documentation actually tells you to do the wrong thing it states that one must use the bluetoothadaptergetprofileproxy with a bluetoothprofilegatt server parameter to obtain the bluetoothgattserver object this approach will work but one will be unable to link ones implementation of the bluetoothgattservercallback to the ble stack this callback is how one responds to client read and write requests among other things however after stumbling on issue 58582 a developer pointed to the new bluetoothmanageropengattserver method which takes your callback as a parameter and returns a bluetoothgattserver object well one problem solvedthe next issue is more problematic the bluetoothgattserver documentation states that one can use this class to create and advertise bluetooth le services and characteristics creating the services etc was not problem but they neglect to say how to start advertising there is no method in the class itself or any other of the classes that i can finddoes anyone know how to do this at the moment all i can see is to use the same approach as used by the client but that approach involves scanning which is not advertising all the documentation further suggests that the bluetoothadapterstartlescan is indeed just for scanningso how do i invoke advertisements once all my services characteristics and descriptors are in place,['android'] +521904,how to insert multiple documents at once in mongodb through java i am using mongodb in my application and was needed to insert multiple documents inside a mongodb collection the version i am using is of 16 i saw an example here in the bulk insert multiple documents section where the author was passing an array to do this when i tried the same but why it is not allowing and please tell me how can i insert multiple documents at once package comimport javautildateimport commongodbbasicdbobjectimport commongodbdbimport commongodbdbcollectionimport commongodbmongoclientpublic class app public static void mainstring args try mongoclient mongo new mongoclientlocalhost 27017 db db mongogetdbat dbcollection collection dbgetcollectionpeople basicdbobject document new basicdbobject documentputname mkyong documentputage 30 documentputcreateddate new date tableinsertdocument string mystringarray new string a b c collectioninsertmystringarray compilation error at this line saying that the method insertdbobject in the type dbcollection is not applicable for the arguments string catch exception e eprintstacktrace please let me know what is the way so that i can insert multiple documents at once through java,['java'] +521939,what is the convention for passing in a list to a constructor and then storing it let us say i have code like this private ilistvector3 vertices private ilistuint indices public meshilistvector3 vertices ilistuint indices to make it clear i want to store the vertices and indices inside it in the constructor i have not worked very much with c so i am not sure how the convention looks am i supposed to make a copy of the entire list or can i just copy the reference whats the convention,"['c#', '.net']" +521951,count the uppercase letters in a string i am trying to figure out how i can count the uppercase letters in a statement i have only been able to find lowercasedef and lower charsstring return summapstrislower stringexample of what i am trying to accomplishtype word hello capital letters 3when i try to flip it it reads errorsdef and upper charsstring return summapstrisupper string,['python'] +521953,selecting id any number in jquery i am new to stackoverflow and jquery altogether so i am having a little trouble making a simple functioni basically have in my website a random number of links with id filtro some number and i want to write only one code to the action of clicking in any of them that would later impact on the class with same filtro some number eg click filtro3 do something on filtro3the problem is i do not know how to write the string in jquery for any number i am thinking about doing something like thisfunction filtro some numberclickfunction do something with the element filtro some number any ideas thank youps this is my first question and i apologize if i made any mistakessolved dystroys solution worked like a charmfor future reference to others i was making this code to make a simple filter menu for a picture gallery this way i could hideshow pictures of certain topics,"['javascript', 'jquery']" +521986,android dragging marker without having to hold in map api v2 i am implementing a feature in my app that allows user to manually locate themselves on a map so i use a pin to represent their location and let user drag it to the place they currently are the simple solution is to use setdraggabletrue on the marker but this requires users to hold the marker for 3 or 5 seconds until it is draggable i think this is quite confusing for many user to use the feature so what i want is to make the dragging more responsive by letting users drag them immediately without having to hold it for a while like how foursquare doeswhat should i do to implement my own dragging feature if you have any suggestions please help me and thanks,['android'] +522027,android listview does not highlight when a onclicklistener is set i have a listview populated with custom xml listitems this is the xmlrelativelayout xmlnsandroid androidlayout widthmatch parent androidlayout heightandroidattrlistpreferreditemheight androidpadding6diprelativelayoutthe listview shows correctly on screen and if i click or hold on an item it becomes blue i am using holo light themethe problem comes when i try to assign an onclicklistener to the view inside getview in my activity that extends baseadapteroverridepublic view getviewint position nullable view convertview viewgroup parent convertview inflateutilsinflatemcontext rlayoutlist item convertviewsetonclicklistenernew viewonclicklistener override public void onclickview view toastmaketextmcontext test 20show after doing that the list item highlight color is no more shown when i click or hold on a list item it is background stays whiteanyway the onclicklistener is perfectly workingdo you have any suggestion to get the highlight color while keeping the default styles of hololight,['android'] +522040,how to suppress noise from requests when running rspec feature specs i am using rspec feature specs and when i run them i get output such asstarted get sign up for 127001 at 20130808 105200 0700started post accounts for 127001 at 20130808 105201 0700started get for 127001 at 20130808 105201 0700started get sign in for 127001 at 20130808 105202 0700started post userssign in for 127001 at 20130808 105202 0700started get for 127001 at 20130808 105202 0700 etchow can i suppress the messages from the requests in my output i have tried setting log levels to no avail any ideas would be appreciated thankseditthis is a rails 4 project using ruby 20specspec helperrbenvrails env testrequire fileexpand pathconfigenvironment file require rspecrailsrequire rspecautorunrequire factory girlrequire capybararailsrequire capybararspecrequire webmockrspecdirrailsrootjoinspecsupportrbeach f require f activerecordmigrationcheck pending if definedactiverecordmigrationrspecconfigure do config configmock with mocha configinclude factorygirlsyntaxmethods configuse transactional fixtures true configinfer base class for anonymous controllers false configorder randomendspecfeaturessign in specrbrequire spec helperfeature sign in do background do account createaccount admin accountadmin end scenario user signs into the application do visit sign in path fill in user email with adminemail fill in user password with adminpassword click button sign in expectpageto have content signed in successfully endend,['ruby-on-rails'] +522084,what is the nicest way to dynamically implement an interface in c i often find it quite a thistraction to have to implement an interface just because i need it once for some method call i have to create a class somewhere else implement the interface etc etcjava has a feature called anonymous classes that allows one to implement the interface inline my question is thus what is the nicest way you can think of of accomplishing something similar in c using existing syntax and i realise that nicest is subjective i am looking for nice syntax not necessarily performancei implemented the following as poc in cgiveninterface ifoobar boolean foobarstring sifoobar foo implementinterfaceifoobarnew foobar new funcstring booleans s foobarthis uses an anonymous object and some reflectionemit to implement the ifoobar interface overlooking properties generic methods and overloading but i am not a fan of the new func stuff but cannot do withoutlooking around i noticed a library called impromptu interface but was not impressed by its syntax to support methods is there a nicer wayedit i am not looking for java vs c flame wars,['c#'] +522098,do not launch simulator when running unittests some backgroundi have ios application with a target configured to run unittests and i am running build automation tool jenkins on my macbook which automatically builds this application and run all tests using command line xcodebuild tooleverything worked fine with xcode 4 this build automation tool was running under different user and was running all these testsi switched to xcode 5 recently and it started to fail because it cannot launch simulatorthe problemi have a scheme unittests which is configured to run tests logic tests a i run these test using one of two methodscommand you in xcodeor command line usrbinxcodebuild scheme unittests sdk iphonesimulator configuration release clean build test after buildyes in both cases it tries to start simulator however per my understand it does not need it anyway it runs on top x86 and it does not look like any apps are installed on simulatoris there a way to get rid of this pesky simulator start because it breaks my build automation update 1seems to find very similar question but cannot get it workingrun logic tests in xcode 4 without launching the simulatorupdate 2i found very relevant and interesting questionanswer apple ci xcode service and jenkins,['ios'] +522135,assign static ip address for wifi network on android 3x and 4x im working on one project and there should be a functionality for setting static ip address dns netmask gateway for wifi if user want it my initial and actual solution is an usage of androidprovidersettingssystem class that allows this feature but this solution works successfully only for android 2x devicesit is nice definitely i am not on totally zero but it would be nice to get it work also for higher versions of android os it do not know exactly why it does not workif i use this simple method for checking actual statuspublic static final boolean hasstaticipcontext c try return settingssystemgetintcgetcontentresolver settingssystemwifi use static ip 1 catch settingnotfoundexception e logitag settings not found egemessage return false it returns true for both android 2x and also android 4x but in second case changes are definitely not reflected in wifi i found this a little hardcoded solution but it did not work as expectedis there anyone that faced against same problemi will be glad for any working solution and also for rooted devices maybe some command in linux since it is easy to check status of whether cellphone is rooted or notthanks in advance,['android'] +522186,how to eliminate minification errors when using controller in angularjs angularmodulemainapp controllerdynamicroutecontroller scope controller routeparams functionscope controller routeparams ifdtestrouteparamspageorname scopecontroller controllerthiscontroller scope scope constructor scopetemplateurl wthispage else scopecontroller controllerthatcontroller scope scope constructor scopetemplateurl wthatpage this minifies touse strictangularmodulemainappcontrollerdynamicroutecontrollerscopeaacontrollerrouteparamsfunctionabcdtestcpageornameacontroaallerbthiscontrollerscopeaconstructoratemplateurlwthispageacontrollerbthatcontrollerscopeaconstructoratemplateurlwthatpagethis is having issues minifying i think its because of the scope scope being altered first time i have run into thisused this method anyone know a better way to write this so it minifies correctlyedit so whats happening is that it is passing the scope a which is fine but on that referenced controller when its minified that scope has become a or b or e depending so if i write the code preminified meaning i literally find what letter represents scope in the other controller i can get it to work but thats so hacky again any ideasusing grunt for minificationangular 105 maybe fixed in later versions2nd edit a decent answer is to throw both controllers into the same file explicitly which is ugly but it works so with in one controller i am declaring 2 sub controllers which is lame if you know of another way please share with the class,['javascript'] +522192,short cut for close html tag in sublime text 2 is there a shortcut to close the html tag youve just opened in sublime text 2,['html'] +522193,aspnet web api output datetime with the letter t the data in the db look like this20110907 144322520but my web api outputs the data and replace the space with the letter t20110907t144322520i can replace the letter t with a space again in jquery but can i fix this problem from the web api make the web api output the original datai also do not want the miliseconds at the end how can i get rid of them,"['javascript', '.net']" +522205,parse time with strptime using timezone i am trying to parse a datetime with time class in ruby 20 i cannot figure out how to parse date and get it in a specified timezone i have used timezoneparse to parse a date where i first call timezone and set it to a specified timezone in the below example i set the zone but it does not effect strptime i have tried doing timezoneparsedate but i cannot get it parse a date like the one belowtimezone central time us canada central time us canadairbmain0860 timestrptime08262013 0330 pmmdy im p 20130826 1530 0400,['ruby'] +522226,how do i connect bower components with sailsjs i would like to be able to install javascript dependencies through bower and use them in a sailsjs app but i cannot figure out a way to do this with out just copying an pasting files from the bower components folder to the sails assets folderideally i think i would like to use requirejs and point to the bower components in the mainjs file i may be trying to pound a square peg in a round hole please let me know if so any thoughts on managing componentslibraries with sails are welcome,['javascript'] +522242,python string in operator implementation algorithm and time complexity i am thinking of how the in operator implement for instance s1 abcdef s2 bcd s2 in s1truein cpython which algorithm is used to implement the string match and what is the time complexity is there any official document or wiki about this,['python'] +522244,using c11 in macos x and compiled boost libraries conundrum i am trying to compile a c project that uses c11 standards extensively everything was going well with just stdc11 until i tried to use unordered map and macos simply does not have the unordered map header file anywhere in usrinclude i did some research and found that using stdliblibc would fix it not sure how this seems like magic to me if the include file is nowhere in the filesystem it certainly did it compiled well but the linker cannot link to the boostprogram options that my program also uses extensively without stdliblibc boost links perfectly but i lose the unordered mapwhat should i do to have the latest c11 features with the mac os clang compiler and still be able to link to boost libraries which were built from sources on this very macps all works fine in my arch linux boxmy makefile libs lboost program options cxxflags stdliblibc stdc11 wall g obj fastqo fastq readero maino degenerateo interleaveo complemento interval utilso intervalo interval utils test toolofoghorn obj linkcc o libsthe output using stdliblibc make c stdliblibc stdc11 wall g c o fastqo fastqcpp c stdliblibc stdc11 wall g c o fastq readero fastq readercpp c stdliblibc stdc11 wall g c o maino maincpp c stdliblibc stdc11 wall g c o degenerateo degeneratecpp c stdliblibc stdc11 wall g c o interleaveo interleavecpp c stdliblibc stdc11 wall g c o complemento complementcpp c stdliblibc stdc11 wall g c o interval utilso interval utilscpp c stdliblibc stdc11 wall g c o intervalo intervalcpp c stdliblibc stdc11 wall g c o interval utils test toolo interval utils test toolcpp c stdliblibc stdc11 wall g o foghorn fastqo fastq readero maino degenerateo interleaveo complemento interval utilso intervalo interval utils test toolo lboost program options undefined symbols for architecture x86 64 boostprogram optionsto internalstd 1basic string std 1allocator const referenced from std 1vector std 1allocator std 1allocator std 1allocator boostprogram optionsto internal std 1allocator std 1vector std 1allocator std 1allocator std 1allocator const in maino clipped output for readabilityld symbols not found for architecture x86 64 clang error linker command failed with exit code 1 use v to see invocation make foghorn error 1,['c++'] +522252,using session in flask app i am sure there is something that i am clearly not understanding about session in flask but i want to save an id between requests i have not been able to get session to work so i tried a simple flask app below and when i load it i get an internal server errorusrbinenv pythonfrom flask import flask sessionapp flask name approutedef run sessiontmp 43 return 43if name main apprunwhy cannot i use store that value in session,['python'] +522269,how to write html code inside i want to create table inside php script is there any way that i could create table inside php scriptphp html code to create table,"['php', 'html']" +522271,conflicting threads on a local variable why is it that in the following code and does not end up being 0 it is some random number with a magnitude less than 10 each time somtimes even a negative numberstatic void mainstring args int and 0 var up new thread for int i 0 i 10 i n upstart for int i 0 i 10 i n upjoin consolewritelinen consolereadlinedoes not upjoin force both for loops to finish before writeline is calledi understand that the local variable is actually part of a class behind the scenes think it is called a closure however because the local variable and is actually heap allocated would that affect and not being 0 each time,['c#'] +522272,integer check with ternary how to check for integer in one linesampleaddrangestatisticsselectplayer new stats seasonfromyear converttoint32seasonfromyear this one is working for me int aseasonfromyear inttryparseseasonfromyear out a a defaultint but for every property i need to declare one variable like a without that is it possible to check in one linesomething like this sampleaddrangestatisticsselectplayer new stats seasonfromyear is integer then value else default value,['c#'] +522364,custom transaction does not work with database cleaner in rspec in our rails 40 application using mysql we use rspec together with the database cleaner gem configured with strategy transaction to cleanup our database for every test case if we have custom transactions which should be rollbacked it does not workwithout database cleaner gem and just using the standard wayconfiguse transactional fixtures trueeverything works as aspected but for running feature tests with javascript we need database cleaner to change the fixture deletion strategy to truncationhow can we use database cleaner together with custom transactions and why does it differ to the standard rspec transaction strategy,['ruby-on-rails'] +522403,what is path of jdk on mac im using mac only at work and i need to set java home to proper path of jdk i downloaded jdk installed it and now i cannot find it anywhere i was looking at the internet for the solution but there is no folder librariesjava,['java'] +522451,how do i simulate placeholder functionality on input date field it is impossible to use placeholder on date fields but i really need iti want two date inputs with texts from and to on each one as placeholders,['html'] +522467,how come my callback says undefined is not a function i am calling a function with a callback like thisfunction get all the items searchinitresult tbody tr searchparseresultsfunctionannouncementid query every single page var mycompany new companyannouncementid mycompanyrequestpagefunction on response parse the data mycompanyparsedata var myperson new personmycompany mypersongetphonefunction consolelogtest it is the last callback with consolelogtest that is the problemthis is the getphonefunctionpersonprototypegetphone functioncallback thisattempt if thisattempt 1 var who thislastname var where thisadress thispostal else ifthisattempt 2 var who thisfirstname thislastname var where thisadress thispostal else var who thisfirstname thislastname var where thisadress thispostal var url whowhere consoledebug consoledebugfail consoledebugurl consoledebugthis return var self this var url whowhere gm xmlhttprequest method get url url onload functiondata data parsehtmldataresponse var vcard datafindvcard if vcardlength 1 var phone vcardfindtelrow amapfunction return thistext get selfofficephone phone0 ifphonelength 1 selfmobilephone phone1 else selfmobilephone callback else ifvcardlength 1 selfgetphone the callback gets triggered when it is supposed to but when the callback is present i get the errorundefined is not a function,"['javascript', 'jquery']" +522484,best way to append vector to vector stdvectorint astdvectorint bstdvectorint ci would like to concatenate these three vectors by appending bs and cs elements to a which is the best way to do this and why1 by using vectorinsertareserveasize bsize csizeainsertaend bbegin bendainsertaend cbegin cendbclearcclear2 by using stdcopyareserveasize bsize csizestdcopybbegin bend stdinsertera aendstdcopycbegin cend stdinsertera aendbclearcclear3 by using stdmove from c11areserveasize bsize csizestdmovebbegin bend stdinsertera aendstdmovecbegin cend stdinsertera aendbclearcclear,['c++'] +522500,slide right to left android animations hey i am working on an android project that requires the slide animations on android webviewwhen the user swipes from left to right it moves to the new page and when it does that from right to left it moves to previous page but android has only two transitions for that namely slide out right and slide in left after using them the left to right sliding work is flawless but the other one looks weirdopposite any solutions for it i want slide out left animations to be more precise,['android'] +522561,jquery scroll element to the middle of the screen instead of to the top with an anchor link i am building a onepage site with a fixedpositioned navigation bar which scrolls smoothly to the different section elements through anchor links the default behaviour for scrolling to an element is to align it to the top of the browser window instead i want to align the element to the middle of the screeni use this markup for navigationnav classmainnav a hreftoptopa a hrefsection1section 1a a hrefsection2section 2a a hrefsection3section 3a a hrefsection4section 4a a hrefsection5section 5anavi use kswedbergs jquery smooth scroll plugin to smooth the scrolling i initiate it like thismainnav asmoothscroll offset 0 speed 700i want to set the offset to be windowheight 2 element height 2 so that it is vertically centered but i need help to figure out how to execute it properlyi need it toget the height of the window and divide it by twoget the height of the element and divide it by two subtract the former from the latterif possible align it to the top as per default if the element is higher than the windowsince there are many anchor links i assume i either need to check the height of the element the anchor link that was clicked links to or initiate smoothscroll for every anchor linkdoes anybody know how to do this,"['javascript', 'jquery', 'html']" +522608,java best way to return multiple object types from a method in my dao i have a method where i build 2 different objects and i want to return both of those objects but i am not sure what the best way is to do it i have looked at using extends myobject creating another class that holds both of my objects that i want to return and just using listobjectlong story short on why i need these similar objects is to thisplay 1 on the screen and the other to use with primefaces dataexporter which does not handle lists in an object as far as i am awareclass personpublic class person firstname null lastname null listprograms programs new arraylistprograms getters and settersclass dataexporterpersonpublic class dataexporterperson firstname null lastname null string program null getters and settersdao methodpublic listsomething getpeople query db for people build both objects return now i understand i can very easily create another object like the one below but that seems like an inefficient way to do things because i am basically creating an object just to return from 1 method public class persontransporter person person null dataexporterperson nullwhat is the best way to handle this scenarioeditthe reason that i am trying to return 2 objects in 1 method is because this is a dao method that queries the database and builds 2 objects based on the data in the query i do not want to break it up into 2 methods because i do not want to query the db twice if i do not need to,['java'] +522690,does an unused import declaration eat memory in java does an unused import like so import androidwidgetrelativelayout eat memoryjust want to know about how much or just is it valuablemaybe this is stupid question but i have not found answer,['java'] +522691,in activityoncreate why does intentgetextras sometimes return null this was probably a false alarm see my own answer original question belowan activity has a button that takes the user to another activity to launch the new activity we populate our intent with extras and oncreate the new activity reads from those extras via intentgetextras we assumed the returned bundle would be nonnull but as customer crash reports thiscovered getextras sometimes returns nullnullguarding the extras as this answer shows is perfectly fine but if you populate the intents extras then why would it ever return null later is there a better place like onresume to read the extrasedit it may be because we are not following the name convention required for the keysthe name must include a package prefix for example the app comandroidcontacts would use names like comandroidcontactsshowallthis is from the intentputextras javadoc what happens if you do not follow this name convention is the behavior even definedheres the relevant codeclass fromactivity extends activity imagebutton button override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutfrom view button imagebuttonfindviewbyidridbutton buttonsetvisibilityviewvisible buttonsetonclicklistenernew viewonclicklistener override public void onclickview v intent i new intentfromactivitythis toactivityclass iputextratoactivityserver param iputextratoactivityuuid param iputextratoactivitytemplate param startactivityforresulti 0 overridetransitionranimslide left in ranimslide left out class toactivity extends activity public static final string server param server public static final string uuid param uuid public static final string template param template override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate bundle extras getintentgetextras if extras null finish return do stuff with extras here is a sample stack trace of this problemjavalangruntimeexception unable to start activity componentinfotoactivity javalangnullpointerexception at androidappactivitythreadperformlaunchactivityactivitythreadjava2355 at androidappactivitythreadhandlelaunchactivityactivitythreadjava2391 at androidappactivitythreadaccess600activitythreadjava151 at androidappactivitythreadhhandlemessageactivitythreadjava1335 at androidoshandlerthispatchmessagehandlerjava99 at androidoslooperlooplooperjava155 at androidappactivitythreadmainactivitythreadjava5493 at javalangreflectmethodinvokenativenative method at javalangreflectmethodinvokemethodjava511 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava1028 at comandroidinternaloszygoteinitmainzygoteinitjava795 at dalviksystemnativestartmainnative method caused by javalangnullpointerexception at toactivityoncreatesourcefile49 at androidappactivityperformcreateactivityjava5066 at androidappinstrumentationcallactivityoncreateinstrumentationjava1101 at androidappactivitythreadperformlaunchactivityactivitythreadjava2311 11 more javalangnullpointerexception at toactivityoncreatesourcefile49 at androidappactivityperformcreateactivityjava5066 at androidappinstrumentationcallactivityoncreateinstrumentationjava1101 at androidappactivitythreadperformlaunchactivityactivitythreadjava2311 at androidappactivitythreadhandlelaunchactivityactivitythreadjava2391 at androidappactivitythreadaccess600activitythreadjava151 at androidappactivitythreadhhandlemessageactivitythreadjava1335 at androidoshandlerthispatchmessagehandlerjava99 at androidoslooperlooplooperjava155 at androidappactivitythreadmainactivitythreadjava5493 at javalangreflectmethodinvokenativenative method at javalangreflectmethodinvokemethodjava511 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava1028 at comandroidinternaloszygoteinitmainzygoteinitjava795 at dalviksystemnativestartmainnative method,"['java', 'android']" +522792,transclude in angular directive putting elements inside a single span here is my directivemyappdirectiveenvtable function return restrict e replace true transclude true template table classtable ngtranscludetablethis is how i use it in html using bootstrap cssenvtable tr tdostd tdenvosnametd tr tr tdos versiontd tdenvosversiontd tr envtablehowever the code generated looks like this in chrometable classtable ngtranscludespan classngscope ngbinding os windows 8 os version 62 spantableas you can see angular just ignored all my trtd tags and put the contents in a single span element why is this happeningbtw as an experiment i tried using just a transcluded p tag in the envtable instead of the trtd tags and in that case angular just adds a ngscope class to the p tag so why does it screw up these trtd tags,['javascript'] +522800,how to avoid the copy when i return i have a function which returns a vector or setsetint foo setint bar create and massage bar return barsetint afoo fooin this case i create a temporary memory space in function foo and thenassign it to afoo by copying i really want to avoid this copy any easy way ican do this in c11 i think this has to do with the rvalue thingok update to the question if i am going to return an object defined by myselfnot the vector or set thing does that mean i should define a move constructorlike thisclass value to return value to return value to return other how to write it here i think stdmove is supposed to be used thanks,['c++'] +522943,how do i stdbind a nonstatic class member to a win32 callback function wndproc i am trying to bind a nonstatic class member to a standard wndproc function i know i can simply do this by making the class member static but as a c11 stl learner i am very interested in doing it by using the tools under the functional headermy code is as followsclass mainwindow public void create wndclassexw windowclass windowclasscbsize sizeofwndclassex windowclastyle m clastyles windowclasslpfnwndproc stdfunctionlresulthwnd uint wparam lparam stdbindmainwindowwindowproc this stdplaceholders 1 stdplaceholders 2 stdplaceholders 3 stdplaceholders 4 windowclasscbclsextra 0 windowclasscbwndextra 0 windowclasshinstance m hinstance windowclasshicon loadiconwm hinstance makeintresourcewidi window windowclasshcursor loadcursornull idc arrow windowclasshbrbackground hbrush color window windowclasslpszmenuname makeintresourcewidr menu windowclasslpszclassname m classnamec str windowclasshiconsm loadiconwm hinstance makeintresourcewidi window small registerclassexwwindowclass m hwnd createwindowex in dword extendedstyles in opt lpctstr m classnamec str in opt lpctstr m windowtitlec str in dword m styles in int m x in int m y in int m width in int m height in opt hwnd hwnd desktop in opt hmenu null in opt hinstance windowclasshinstance in opt lpvoid null private lresult callback windowproc in hwnd hwnd in uint umsg in wparam wparam in lparam lparam return defwindowprochwnd umsg wparam lparam when i run it as is it gives the error messageerror no suitable conversion function from stdfunctionlresulthwnd uint wparam lparam to wndproc,['c++'] +522982,java generics function return type i have a situation like thisi have a class which looks likepublic class testclasst class body hereand i have a method that looks like thispublic class anothertestclassk private testclassk testclass public anothertestclasstestclassk testclass thistestclass testclass public k testmethod call methods on param object and pass a value of the same type as testclass k returnval thistestclassdosomething return returnval now i have a factory method which returns an object of type testclasspublic testclass samplefactoryint i if i1 return new testclassinteger if i2 return new testclassdouble if i3 return new testclastringbut i cant use that method to pass parameter to my testmethod whats the solution for thiscurrently i am writing if else chain blocks to get correct instance i know its not correct as its impractical to write if else blocks when there are multiple parameters like the one above please suggest an elegant way for thisedit sample usagepackage myimport javautilarraylistimport javautillistpublic class genericsspike public static void main string args testclass1 tc1 new testclass1integer 123 testclass2 tc2 new testclass2integer 123 anothertestclass atc new anothertestclassinteger tc1 tc2 atctestmethod class testclass1t private t value testclass1 t val value val class body here public t getvalue return value class testclass2t private t value testclass2 t val value val class body here public t getvalue return value class anothertestclassk public testclass1k testclass1 testclass2 public anothertestclass testclass1k testclass testclass2k testclass2 thistestclass1 testclass public k testmethod any logic can come here systemoutprintln testclass1getvalue systemoutprintln testclass2getvalue return testclass1getvalue in this case if tc1 and tc2 are coming from a factory which creates these objects i want to know whats the decent way to create instance of anotherclass,['java'] +523022,how to extract the left most common characters in a string list assume i have the following list of string objectsabc1 abc2 abc whateverwhats the most efficient way to extract the left most common characters from this list so i would get abc in my case,['java'] +523034,add text label to d3 node in force directed graph and resize on hover i am trying to add text label to nodes in d3 force directed graph there seems to be an issuethis is my fiddlewhen i add the node name like thisnodeappendtext attrclass word attrdy 35em textfunctiond consolelogdname return dname there is no change but the names are getting loggedwhen i tried using bounding box the node labels appeared but the nodes are stacked up on the topleft corner of box while the node links are finethis fiddle is the outcome of that effort i put in can anyone tell me what am i doing wrong,['javascript'] +523072,how to search hierarchical data with linq i need to search a tree for data that could be anywhere in the tree how can this be done with linqclass program static void mainstring args var familyroot new family name familyroot var familyb new family name familyb familyrootchildrenaddfamilyb var familyc new family name familyc familybchildrenaddfamilyc var familyd new family name familyd familycchildrenaddfamilyd there can be from 1 to and levels of families search all children grandchildren great grandchildren etc for familyd and return the object public class family public string name get set listfamily children new listfamily public listfamily children get return children,['c#'] +523113,what are the typical layers in an onion architecture i am currently studying the domain driven design and try to apply it for a wpf project i watched some tutorial videos and read many articles like onion archicecture dependencies in the same layer infrastructure and web communicatingdomain driven design domain service application servicei understood the focus on interfaces and inversion of control i read there were some recurrent layer names domaincore for the representation of the sphere of knowledge infrastructures for persistance application for i do not understand but they change depending of articles i read some even do not appearwould it be possible to have an list of all layers that in theory are required in an onion architecture to face all needs and problems with their intent what kind of code do they contain what kind of need do they try to fulfill which layer do they need to reference please,"['c#', '.net']" +523135,how do i use the data attribute to pass values with jquery i would like to know more about using data attributes with html and its use within jquery i am simply trying to retrieve dataattributenamea value with data and or attr both are logging as undefined with the following methods below how do i use the data attribute to pass values with jqueryhtmlli classalsitem a datalocsubjecttest value img srcclockpng abeachlijs alsitem clickfunctione epreventdefaultvar data alsitemdatadatalocsubjectvar attrmethod alsitemattrdatalocsubject consolelogdata consolelogattrmethodjsfiddle,['jquery'] +523184,whats the best way to wrap a c callback with a c11 interface let us say this is a c function to be wrappedvoid fooint stdcall callbackthe two main pitfalls with c function pointer callbacks arenot being able to store bind expressions not being able to store capturing lambdas i would like to know the best way to wrap functions like these to do so the first is particularly useful for a member function callback and the second for an inline definition that uses surrounding variables but those are not the only usesthe other property of these particular function pointers is that they need to use the stdcall calling convention this to my knowledge eliminates lambdas as an option completely and is a bit of a nuisance otherwise i would like to allow at least cdecl as wellthis is the best i am able to come up with without things starting to bend back to relying on support that function pointers do not have it would typically be in a header here is the following example on coliruinclude functionalc function in another header i have no control overextern c void fooint stdcall callback callbacknamespace detail stdfunctionint callback pretend extern and defined in cpp compatible with the api but passes work to above variable extern c int stdcall proxycallback pretend defined in cpp possible additional processing return callback templatetypename f takes anythingvoid wrappedfoof f detailcallback f foodetailproxycallback call c function with proxy int main wrappedfoo int return 5 there is however a major flaw this is not reentrant if the variable is reassigned to before it is used the old function will never be called not taking into account multithreading issuesone thing i have tried that ended up doubling back on itself was storing the stdfunction as a data member and using objects so each would operate on a different variable but there was no way to pass the object to the proxy taking the object as a parameter would cause the signature to mismatch and binding it would not let the result be stored as a function pointerone idea i have but have not played around with is a vector of stdfunction however i think the only real safe time to erase from it would be to clear it when nothing is using it however each entry is first added in wrappedfoo then used in proxycallback i am wondering if a counter that is incremented in the former and decremented in the latter then checked for zero before clearing the vector would work but it sounds like a more convoluted solution than necessary anywayis there any way to wrap a c function with a function pointer callback such that the c wrapped versionallows any function objectallows more than just the c callbacks calling convention if it is critical that it is the same the user can pass in something with the right calling conventionis threadsafereentrantnote the obvious solution stated as part of mikael perssons answer is to make use of the void parameter that should exist however this is sadly not a beall endall option mostly due to incompetence what possibilities exist for those functions that do not have this option is where this can get interesting and is the primary route to a very useful answer,['c++'] +523204,mysql date format i am trying to format date using mysql date format my query isselect first name middle name last name date formatadded datedmy as adatefrom profilesadded date is the date field on profile table when i run that query it brings null for adate any suggestionthanks,['mysql'] +523209,how do i refresh dbcontext i want to refresh all entities of my dbcontext without recreating it i tried the following and none of them make sensevar context iobjectcontextadaptermydbcontextobjectcontextvar refreshableobjects from entry in contextobjectstatemanagergetobjectstateentries entitystateadded entitystatedeleted entitystatemodified entitystateunchanged where entryentitykey null select entryentitycontextrefreshrefreshmodestorewins refreshableobjectsforeach var entry in thisormchangetrackerentries entrystate entitystateunchangedthisormchangetrackerdetectchangesand the only one which refreshes my dbcontextforeach var i in thisormchangetrackerentries ireloadbut it is too slow can you help me choosing the right way,['c#'] +523222,what is the use of fflushstdin in c programming i have the following programinclude stdiohinclude stdlibhint main char ans8 int i fori1i3i printfn what is the unit of traffic scanfsans fflushstdin ifstricmpansearlang0 printfnanswer is correct exit1 else ifi3 printfn try againn printfn nunit of traffic is earlangwhat is the use of fflushstdin in this program,['c'] +523223,what is the meteor concurrency model i am writing serverside logic for a meteor app that has to update inmemory state in response to requests from the client this application needs strong concurrency guarantees in particular i want to be sure that there is only one update executed at a timei am trying to figure out if meteors concurrency model supports this the documentation mentions that meteor is multithreaded which would be a problem but after searching around i get the impression that meteor is actually uses fibers explicitly scheduled threads if that is true then i am safe as long as the part of my code that needs to run atomically does not make any meteor calls which involve io and thus yield the execution lockis this the case where can i find more information on meteors concurrency model,['javascript'] +523360,creating a percentage based ios layout i am trying to replicate a layout that i currently have in an android application but i do not know how to go about it in ios especially because of the tallness of the iphone 5i know how to explain this in android terms but i have been trying for the past few days to do this in ios but i cannot quite get it to workbest way to explain iti want two layouts the top layout must take up 40 and the bottom must take up 60in the top layout they must be three buttons that fill up all space possible essentially 13 of the spacein the bottom layout i want an imageview and then a textview on top of thatthis is a paint mockup is this possible to do in ios i feel that layouts are much harder to create than android,['ios'] +523362,how do i center these twitter bootstrap 3 navbar links i am wondering on how i can center the bootstrap 3s navbar menu items i know they have included a navjustified class but that will just conflict with navbarnav if used together i belive it is being looked into by the dev teamso is there any work around with css that i can achieve a navbar that will keep the navbar menu itemslinks justified even when the container it is in is resizedheres a jsfiddle for you if you need it,"['html', 'css']" +523391,why extension method behaves different derived class contains a count method which perform some actions on class derivedon the other hand i have an extension method which is also targets the class derivedderived derived new derivedderivedcountby calling above snippet will execute count method inside the derived class why c compiler not warns and identify the extension method in this situation how framework internally handling thisbase classpublic class base public virtual string count return stringempty derived classpublic class derived base public override string count return basecount extension methods for derived classpublic static class extensionmethods public static derived countthis derived value return new derived,['c#'] +523406,passing character array as parameter c kernel code i am trying to print something on screen using my print functioni have stumbled on a small problem when i pass the character array like thischar s abcprintsit works fine but when i call it like this there is no effectprintabchere is my function declarationprint function void printchar messageam i missing something printf works the same way and you can pass the string by the second wayeditdefinitionsvoid print atchar message int col int row ifcol 0 row 0 set cursorget screen offsetcolrow int i 0 whilemessagei 0 print charmessagei11white on black void printchar message print atmessage 11edit2objdump of kernelovoid start clear screen char s abc printabc prints while1thisassembly of section text0 start 0 55 push ebp 1 89 e5 mov ebpesp 3 83 ec 28 sub esp0x28 6 e8 00 00 00 00 call b start0xb clear screen b c7 45 f4 61 62 63 00 mov dword ptr ebp0xc0x636261 bca 12 c7 04 24 00 00 00 00 mov dword ptr esp0x0 19 e8 00 00 00 00 call 1e start0x1e print 1e 8d 45 f4 lea eaxebp0xc 21 89 04 24 mov dword ptr espeax 24 e8 00 00 00 00 call 29 start0x29 print 29 eb fe jmp 29 start0x29 2b 90 nopedit3since this might be something with the way i am initilising the enviroment here are the 2 files responsiblepmodeasm initializes segments and jumps to start of kernelbits 16switch to pm cli switch interuppts off lgdt gdt descriptor load global descriptor table mov eax cr0 set control registers first bit to protected mode or eax 0x1 mov cr0 eax jmp code seginit pm flush cache by far jumpbits 32init pm mov ax data seg mov ds ax mov ss ax mov es ax mov fs ax mov gs ax mov ebp 0x90 mov esp ebp call begin pmhere is how i build the gdt gdt gdt start gdt null the mandatory null descriptor dd 0x0 dd means define double word ie 4 bytes dd 0x0 gdt code the code segment descriptor base 0 x0 limit 0 xf 1 st flags present 1 privilege 00 descriptor type 1 1001 b type flags code 1 conforming 0 readable 1 accessed 0 1010 b 2 nd flags granularity 1 32 bit default 1 64 bit seg 0 avl 0 1100 b dw 0xf limit bits 015 dw 0x0 base bits 015 db 0x0 base bits 1623 db 10011010b 1 st flags type flags db 11001b 2 nd flags limit bits 1619 db 0x0 base bits 2431 gdt data the data segment descriptor same as code segment except for the type flags type flags code 0 expand down 0 writable 1 accessed 0 0010 b dw 0xf limit bits 015 dw 0x0 base bits 015 db 0x0 base bits 1623 db 10010010b 1 st flags type flags db 11001b 2 nd flags limit bits 1619 db 0x0 base bits 2431 gdt end the reason for putting a label at the end of the gdt is so we can have the assembler calculate the size of the gdt for the gdt decriptor below gdt descriptior gdt descriptor dw gdt end gdt start 1 size of our gdt always less one of the true size dd gdt start start address of our gdt define some handy constants for the gdt segment descriptor offsets which are what segment registers must contain when in protected mode for example when we set ds 0 x10 in pm the cpu knows that we mean it to use the segment described at offset 0 x10 ie 16 bytes in our gdt which in our case is the data segment 0 x0 null 0 x08 code 0 x10 data code seg equ gdt code gdt start data seg equ gdt data gdt start,['c'] +523430,never annotate functions involving dynamic memory allocation as noexcept assume you have a function that normally can never fail for examplestdstring convert integer to stringint xin pricipal this would be a candidate for noexcept however the implementation most likely involves involves dynamic memory management so it could always throw a stdbad alloc when allocating memory with the new operatoris it recommended to annotate the function as noexceptfrom a practical point of view it is extremely difficult to handle outofmemory situations in a reasonable way most programs just assume that there is enough memory available calling stdterminate as it would happen if a noexcept function throws stdbad alloc seems to be reasonable in that case for me noexcept is some form of documentation it is a promise that you or the optimizer can safely assume that this function will never throw if you are programming an application that does not care about outofmemory situations it is still a valid assumptioni guess the safest recommendation is to never use noexcept if a stdbad alloc exception could be thrown on the other hand i wonder if there are advantages to use noexcept anyway assuming that you do not care about outofmemory situations ie if stdterminate is ok,['c++'] +523432,how to change navigation bar color in ios 7 or 6 i want to change the color of the navigation bar color but i am not sure whether or not i should change the tint or the background i know ios 7 is going for a more flat design even recommending removing gradients but i am having trouble deciphering the two even if i set a background color it does not do anythingin this image the background is set to green but the bar is still blue,['ios'] +523458,how can i be notified of a banner notification in ios i am writing an ios application and i would like to pause my apps motion content when the operating system decides to show a banner notification like this oneis there a system nsnotification that i can observer or a method that gets called which i can react to i have triedapplicationwillresignactive but that is not called in this case,"['iphone', 'ios', 'objective-c']" +523515,how to add a title to a html select tag how would i go about setting a title in select tag here is my select boxselect option valuesydneysydneyoption option valuemelbournemelbourneoption option valuecromwellcromwelloption option valuequeenstownqueenstownoptionselectwhen i visit the site by default it shows sydney but i want to thisplay a title such as what is the name of your city,['html'] +523525,less unrecognised input i am trying to learn less with the help of web essentials 2012right from the start this less codemaincolor redmegawarning fontsize 24px color maincoloris giving a compile error less unrecognised input and the compilation stops when i declare the variable maincolor inside the megawarning class scope everything worksmegawarning maincolor red fontsize 24px color maincolorwhat am i missing,"['asp.net', 'css']" +523530,how to use nsnumber or cgfloat constant in autolayout visual format language i am trying to set top and bottom paddings to a view in autolayout using the visual format language the code compiles and works if i write the paddings as integers in visual format string but it fails when i try to replace it with a constant heres the error i am gettingterminating app due to uncaught exception nsinvalidargumentexception reason unable to parse constraint format it is not possible to set a space equal to the width or height of a view perhaps you want to use a view as a spacer view1spacerview1view2 vktopandbottompaddingmessagetextviewktopandbottompaddingand this is my codecgfloat const spmtvc ktopandbottompadding 50 create my own nsdictionary of variable bindingsnsdictionary variablebindings messagetextview messagetextview contentview selfcontentview ktopandbottompadding nsnumber numberwithfloatspmtvc ktopandbottompadding constraints in the horizontal axis basically just pins the view to the left and right of superviewnsmutablearray constraints nslayoutconstraint constraintswithvisualformath0messagetextviewcontentview0 optionsnslayoutformatalignaleading metricsnil viewsvariablebindings mutablecopy constraints in vertical axis give 5point padding from superviews top bottomconstraints addobjectsfromarraynslayoutconstraint constraintswithvisualformatvktopandbottompaddingmessagetextviewktopandbottompadding optionsnslayoutformatalignalltop metricsnil viewsvariablebindingsfor nslayoutconstraint constraint in constraints selfcontentview addconstraintconstrainti think the error message means that the compiler thinks ktopandbottompadding is a uiview when it is an nsnumber as defined in the dictionary is there a way to do this right,"['iphone', 'ios', 'objective-c']" +523554,is java evaluation order guaranteed in this case of method call and arguments passed in i did some reading up on jls 1574 and 151242 but it does not guarantee that there would not be any compilerruntime optimization that would change the order in which method arguments are evaluatedassume the following codepublic static void main string args myobject obj new myobject methodrelyingonevalorderobj objmymethodpublic static object methodrelyingonevalordermyobject obj object input if objmyboolean return null else return inputis it guaranteed that the compiler or runtime will not do a false optimization such as the following this optimization may appear correct but it is wrong when the order of evaluation mattersin the case where calling objmymethod alters the value that will be returned by objmyboolean it is crucial that objmymethod be called first as methodrelyingonevalorder requires this alteration to happen firstunwanted optimization possiblepublic static void main string args myobject obj new myobject methodrelyingonevalorderobjpublic static object methodrelyingonevalordermyobject obj if objmyboolean return null else return objmymethodif possible please show some sources or java documentation that supports your answernote please do not ask to rewrite the code this is a specific case where i am questioning the evaluation order guarantee and the compilerruntime optimization guarantee the execution of objmymethod must happen in the main method,['java'] +523581,overriding an automatic property since thispublic int myint get setis equivalent toprivate int myintpublic int myint getreturn myint set myint value when you make the automatic property virtualpublic virtual int myint get setand then override this property in a child classpublic override int myint getreturn somevar setsomevar value does this child class now have an unwelcomed and hidden allocation of myint,['c#'] +523611,check if my qmainwindow is currently visible in qt i would like to know if my qmainwindow is currently visible and not overlapped by another windows of another applicationsi need to achieve this for windows linux and mac,['c++'] +523651,lifetime and multiple use of an antiforgerytoken i am trying to implement antiforgerytokens to an angular applications ajax requestsis there a lifetime attached with the antiforgerytoken if i have the app open for a long while in a web browser whithout touching it say for a month will the ajax requests fail due to a stale tokencan the token be reused for multiple calls can i keep one token somewhere in the page and retrieve it for all ajax calls,['asp.net'] +523665,check if function is in c or lua implemented i have created a table and assigned a method with lua pushcfunction named mytablemyfunction in a different callback context it is necessarily that myfunction will be overriden inside the lua script for some reasons if i call myfunction from the c host i need to know if myfunction is still the c function or was replaced by the scriptis there a way to test from c if the c method is still attached or is replaced by some lua code,['c'] +523673,facebook key hash for play store release i have created a hash key for my android app which is using facebook sdk however now i want to create the hash key for release version of my app for that i am using a different keystorei have the following syntax keytool exportcert alias my alias here keystore pathtomyandroidkeystore openssl sha1 binary openssl base64here my alias here is the alias present in that keystore file or something other also the password is android or something else like the password for that alias in keystore filethanks a lot,['android'] +523687,javascript jquery exporting data in csv not working in ie i need to export data thisplayed in a table to csv format i have tried lot many things but could not get it working for ie 9 and abovei have created a dummy fiddle with my codevar data name1 city1 some other info name2 city2 more infosome dummy datavar csv converttocsvdataconvert it to csv formatvar filename testname the file which will be dynamicif navigatoruseragentsearchmsie 0 this peice of code is not working in ie we will working on this todo var uricontent dataapplicationoctetstreamfilename filename csv escapecsv windowopenuricontent filename csv else var uri datatextcsvcharsetutf8 escapecsv var downloadlink documentcreateelementa downloadlinkhref uri downloadlinkdownload filename csv documentbodyappendchilddownloadlink downloadlinkclick documentbodyremovechilddownloadlinki have seen many of the links in stackoverflow but could not find anything that is working with ie9 or above like terry young explains in howtodataexporttocsvusingjqueryorjavascriptalso triedvar csv converttocsv tempobj var filename csvexportfilename if navigatorappname microsoft internet explorer windowopendatatextcsvcharsetutf8 escapestr else var popup windowopen csv popupdocumentbodyinnerhtml pre str pre not sure how to fix it i do not want to hit the server and export my csv the requirement say so,['javascript'] +523707,how to add html special character rightarrow using content property of css i am trying to add html special character using its code its working fine when i use it inside my div but how can i do this using cssi have tried as followingrightarrowafter content9658demoeditwhat i wanted is not there in matt balls answer because i wanted code for right arrow and in that question there is code for down arrow only so its not duplicate,"['html', 'css']" +523761,unable to start debugging on the web server unable to connect to the webserver i am running visual studio 2008 iis 75 on windows 7 x32 i am able to run the aspnet web site in iis 75 without debugging just fine but when i press f5 to debug it i getunable to start debugging on the web server unable to connect to the webserver verify that the web server is running and that incoming http requests are not blocked by a firewall,"['asp.net', '.net']" +523789,what is the difference between android ndk r9 legacy tool chain and android ndk r9 on windows 64 i want to upgrade my android ndk to r9 but in the windows option for 64 bit i see the above two optionsi cannot seem to find the difference between them onlinecan someone please elaborate,['android'] +523798,rails 3 best way to preview image before upload i need to preview an image prior to submitting a form i work with rails 3 and needs something that is browser compatibleany ideas how i can achieve that,['ruby-on-rails'] +523821,how do annotations work internally can anybody explain me how annotation work internally in javai know that how we can create custom annotation by using javalangannotation library in java but still i do not get enough idea how it is working internally like override annotationi really thankful if anyone explain it in details,['java'] +523825,can i searchindex a custom datasource in orchard via lucene i am currently working on a site to allow users to search through a custom product catalog i have been looking around and would love to leverage orchard cms to help me develop this site i have currently gone through ron petersons youtube series on custom orchard modules and the skywalker blog seriesi feel like my goal is possible but i am looking for some validation on whether my strategy will work within the orchard frameworkthis is my current situationi have an default orchard configuration pointing to a sql db namedproductorchardi have a custom dal that points to another sql db named productsproducts are made up of your typical information product name description price etcthe custom dal has a poco model called product with a repository to interact with with the properties name description pricenow based on the information i read about creating orchard modules it seems like the method of creating a custom module with custom content is tocreate a module through code gen tools well call it productmodulecreate a custom content part productpartcreate a custom content part record productpartrecord to act as the data model for the partcreate a custom contentparthandler productparthandler that handles the persistance of the content partcreate a custom driver that is the entry for preparing the shapes for rendering of the uipotentially create a service that interacts with the driversthis is where things start to get jumbled and i am not sure if this is possible or not what i would like to do is to create a custom content type that is backed by my custom dal rather than having the data be stored through the contentpartrecord inside the productorchard db but still allow it to be indexed by the lucene module to allow for searching of the product catalogis it possible to create a custom contenttype andor contentpart that is backed by a different datasource and still leverage the lucene search capabilitiesin high level terms i would like a product contenttype where the contentitems are actually stored in my secondary database not the orchard database and still want to be able to leverage lucene search via projections,"['c#', '.net']" +524010,how to program intel xeon phi with c i am a c programmer with some c experience all on windows with this skill set are there any options to develop for intel xeon phi processor found this link but not sure if that is the bestonly waythanks for your advice,['c#'] +524012,passing arguments in anonymous functions in javascript sometimes i see javascript that is written with an argument provided that already has a set value or is an object with methods take this jquery example for instanceselectorchildreneachfunctioni consolelogiwhen logging i you would get the value of whatever i is in that iteration when looking at the selectors children in the jquery each methodtake this nodejs examplehttpcreateserverfunctionrequest response responsewritehead200 contenttype textplain responsewritehello world responseendlisten8you can see here that request and response are being passed and they contain their own methods that can be acted onto me this looks like were passing a function to the createserver function with two arguments that have methods already attached to themmy question is a multipart onewhere do these arguments come from if these are just anon functions how do they receive arguments that can be acted on like other functionshow do i create functions that can take my own arguments like this does this use the power of closures,['javascript'] +524119,running an ember controller function when route loads to set property that controls a checkbox i have set up an ember checkboxview embercheckbox checkedbindingischeckedthis checkbox is bound to this controller appsettingscontroller embercontrollerextendischecked falseisitchecked function var me this getjsonajaxcheckifuselowresphp functiondata consolelogdata meischecked data mesetischecked data consolelogmeischecked sendsetting function var ischecked thisischecked thissetischecked ischecked consolelogischecked postajaxsetlowresphp uselowres ischecked appnamespacesetneedsrefresh trueobservesischeckedessentially it is a checkbox which posts a setting my problem is setting the original state of the checkbox when i load the route i want to have isitchecked run to set the checkboxs original state example 1 i go in to settings click the checkbox2 i leave the site and come back to the settings pagehere is where i want the isitchecked function to run to query the server and see if the setting is setif it is set the get request returns true i want the checkbox to be checked hence setting meischecked to data trueas of right now i cannot figure out how to do this can anyone help mei have tried setting it in my appsettingsroutes model but that does not seem to be able to run the function in my controllerthanksjsbin,['javascript'] +524157,where are the assemblies for an aspnet web site when running iis express i know that with dynamic compilation under an aspnet web site code behind files get compiled into assemblies where do these dlls get stored when running iis express is it in memory only i do not see them in the bin folder or in the temp directory cwindowsmicrosoftnetframework64v4030319 typically i generate them when precompiling them whenever i publish in this case though i do not see themam i missing somethingthanksupdatei did see dlls under cusersadministratorappdatalocaltemptemporary aspnet filesrootso i am thinking it stores them there this is visual studio 2012 net 45,"['asp.net', '.net']" +524165,what are the common usage of exceptions at catch site my understanding about exception handling is very limited while i find it is easy to throw an exception or i can pack it using expectedt for later consumption i have very little idea about what to do with an exceptionpresently my knowledge is limited toclean my own resources and rethrow the exception to be handled at appropriate location egptr p allocallocatentry uninitialized copyfirstlastpatomic granularity all or nonecatch allocdeallocatepn throwbut i guess this can be equivalently transformed in a raii pattern asalloc guardptr pallocallocatenuninitialized copyfirstlastpgetpcommitcatch the exception at a top level compose print a nice message and exitegint mainint argcchar argv try app t the appargcargv the apprun catchstdruntime error e instead of what i can also compose the mesage here based on locale stdcoutewhatstdendl so all i do is in a top level function such as main catch the exception and print an appropriate message and closewhile implementing a library with a nice set of api using various external libraries as back end for implementation i realized that third party library exceptions are part of my api specification as they cross my library boundary and land in user codeso my library api leaked all exceptions from external libraries and each one having their own exception hierarchy that i was using to the user code this leads to my question what all can be done when i catch any exception more specificallycan i translate the caught exception from external library to my own exception and throw that in a generic way say the mapping between third party library exception hierarchy and my exception api is provided as a mplmap can i do something more useful than printing a messagecall stack say resume the function at the throw site with different input parameter say when i get that a file not found or thisk error rerun the function with a different fileany other pattern which is valuable to knowthanks,['c++'] +524184,get unique combinations of elements from a python list editthis is not a exact duplicate of python code to pick out all possible combinations from a listthis topic is about finding unique combinations while the other topic is about finding all combinationsif i have a python list l 1234whats the best way to get all the possible unique combinations of 3 elements from the list like below123 124 234 341the order of the elements in the combinations does not matter for example 123 and 321 will be considered the same combinationi can probably write a few loops to do this but i think there might be a oneliner which can do the same,['python'] +524198,bootstrap 3 grid with no gap i am trying to create a 2 column grid with literally a 50 with no margins or padding how do i achieve this with bootstrap 3 i tried this but end up with negative margins at tabletdesktop break pointshtmldiv classcontainer div classrow div classcolsm6 offset0col 1div div classcolsm6 offset0col 2div divdivcsscontainer background green overflow hiddenrow background blue color frow firstchild background redoffset0 paddingleft 0 paddingright 0demo,['css'] +524207,django can we use exclude on get in django querysets can we use myclassobjectsgetdescriptionhiexcludestatusunknown,['python'] +524214,how to get pdf page width and height i have a pdf and i want to get the width and height for each page in pdf using itextsharpgiven this is the pdf i want to work with string sourcedpdftestpdfpdfreader reader new pdfreadersource,['c#'] +524251,spring transaction rollbackfor and norollbackfor both defined here is the problem i got in an application i have to maintain i have a first class with the annotation transactionalrollbackfor customexceptionaclassthen in the following code i call a method of transactionalnorollbackfor customexceptionbclass nb customexceptiona or customexceptionb have only one common ancestor wich is exceptionand of course when i execute the code an exception is raised wich is neither of type customexceptiona or customexceptionb nor does it subclasses themso the question is simple what happens to the transaction in that case does it commit does it rollback does it hold on an unfinished state waiting for the application to do something which is actually an answer that might explain some ugly things seen in this application and moreover why thanks for your help and time,['java'] +524264,java abstract classes returning this pointer for derived classes i am currently trying to write some custom exceptions with helper methods for setting the variables like thispublic class keyexception extends runtimeexception protected string idprotected keyexceptionstring message supermessageprotected keyexceptionstring message throwable cause supermessage causepublic string getid return keyidpublic keyexception withidfinal string id thisid id return thishowever in my derived classes i cannot use the withid method as it only returns the base class is there anyway to return the this pointer without having to override the method in every single derived class,['java'] +524305,do i need to explicitly thispose sqldataadapter in this thread there is a suggestion that after the operation the instance of sqldataadapter is thisposed of explicitly like sostring connstring your connection string herestring query select from tablesqlconnection conn new sqlconnectionconnstring sqlcommand cmd new sqlcommandquery connconnopensqldataadapter da new sqldataadaptercmddafilldatatableconnclosedathisposeis it really necessary what about gc,['c#'] +524323,ios translation and scale animation i am working on uibutton animation wherethe uibutton is set in the bottom center of the screen and scaled to a small size menubtntransform cgaffinetransformmakescale01f 01fwhen the app starts it should be moving to the bottom left side of the screen as it scales or grow to its original size voidviewdidload super viewdidload menubtnframe cgrectmake160 513 30 30 menubtnsuperviewframe cgrectmake160 513 30 30 menubtntransform cgaffinetransformmakescale01f 01f nslog menubtn menubtnsuperview menubtn menubtnsuperview uiview beginanimationsnil contextnil uiview setanimationdelegateself uiview setanimationduration5 uiview setanimationcurveuiviewanimationcurveeaseout cgaffinetransform scaletrans cgaffinetransformmakescale10f 10f cgaffinetransform lefttorighttrans cgaffinetransformmaketranslation20f00f menubtntransform cgaffinetransformconcatscaletrans lefttorighttrans uiview commitanimationsproblemwhen the animation starts the button starts moving from the bottom right side of the screen and not in the bottom center where it is and should be any help log resultnslog mybtn20130814 092238913 gjcoolnavi339c07 uibutton 0x813ea30 frame 0 0 0 0 opaque no autoresize tmbm layer calayer 0x813eaf0thats before doing the animationand the result after the animation is20130814 093025719 gjcoolnavi612c07 uibutton 0x71206d0 frame 160 294 0 0 opaque no autoresize tmbm animations transformcabasicanimation 0x7536a80 positioncabasicanimation 0x7537dd0 layer calayer 0x7120790,"['iphone', 'ios', 'objective-c']" +524354,adding table rows dynamically in android i am trying to create a layout where i need to add table rows dynamically below is the table layout xmltablelayout xmlnsandroid androidlayout widthmatch parent androidlayout heightmatch parent androidididthisplaylinear androidbackgroundcolorbackground df androidorientationvertical tablerow androidlayout widthwrap content androidlayout heightwrap content androidididthisplay row androidlayout margintop280dip tablelayoutthe activity file where rows are being added dynamically ispublic void init menudb new menudbadapterthis ll tablelayout findviewbyidridthisplaylinear tablerow rowtablerowfindviewbyidridthisplay row for int i 0 i 2 i checkbox new checkboxthis tv new textviewthis addbtn new imagebuttonthis addbtnsetimageresourcerdrawableadd minusbtn new imagebuttonthis minusbtnsetimageresourcerdrawableminus qty new textviewthis checkboxsettexthello qtysettext10 rowaddviewcheckbox rowaddviewminusbtn rowaddviewqty rowaddviewaddbtn lladdviewrowi but when i run this i am getting below error0813 162746437 eandroidruntime23568 javalangruntimeexception unable to start activity componentinfocomexampleromscomexampleromsthisplayactivity javalangillegalstateexception the specified child already has a parent you must call removeview on the childs parent firsti understand that this is due to command lladdviewrowi but when i remove this its adding all stuff in a single row rather tan creating a new row for next item i tried with giving index too as rowaddviewaddbtni but still its not populating correctly please advise thanks,['android'] +524364,how to make ordinary webrequest async and awaitable i need to make the following code async and awaitablei need to get a lot of data from the web server and then this data will be used to populate the xaml page in my applicationso i need the deflogin method to be awaitableis it possiblepublic void deflogin postdata my data to post var url new uriurl to post to urikindabsolute webrequest webrequestcreateurl webrequestmethod post webrequestcontenttype textxml webrequestbegingetrequeststreamnew asynccallbackgetrequeststreamcallback webrequest public void getrequeststreamcallbackiasyncresult asynchronousresult webrequest httpwebrequestasynchronousresultasyncstate stream poststream webrequestendgetrequeststreamasynchronousresult byte bytearray encodingutf8getbytespostdata poststreamwritebytearray 0 bytearraylength poststreamclose debugwritelinestart begingetresponse webrequestbegingetresponsenew asynccallbackgetresponsecallback webrequest public void getresponsecallbackiasyncresult asynchronousresult try httpwebrequest webrequest httpwebrequestasynchronousresultasyncstate httpwebresponse response response httpwebresponsewebrequestendgetresponseasynchronousresult stream streamresponse responsegetresponsestream streamreader streamreader new streamreaderstreamresponse string response streamreaderreadtoend streamresponseclose streamreaderclose responseclose if response show some error msg to the user debugwritelineerror else your response will be available in response debugwritelineresponse catch webexception error i saw this question on stackoverflow converting ordinary http post web request with async and await but i could not understand the answer properlyplease can anyone help i would be really grateful,['c#'] +524436,what is the difference between assert and static assert i know that static assert makes assertions at compile time and assert at run time but what is the difference in practice as far as i understand deep down they are pieces of code likeif condition false exitcan someone give me an example of where only static assert will work or only assertdo they do anything a simple if statement cannot dois it bad practice to use them,['c++'] +524441,responsivefluid jqgrid with twitter bootstrap i started creating application uses jqgrid in many places now the customer wanted to use twitter bootstrap so they can view the site nicely in ipadwe have atmost done everything except jqgrid plugin it uses a px width for defining width of the grid and column widthjquerylist2jqgrid urlserverphpq2 datatype json colnamesinv nodate client amounttaxtotalnotes colmodel nameidindexid width55 nameinvdateindexinvdate width90 namenameindexname asc invdate width100 nameamountindexamount width80 alignright nametaxindextax width80 alignright nametotalindextotal width80alignright namenoteindexnote width150 sortablefalse rownum10 rowlist102030 pager pager2 sortname id viewrecords true sortorder desc captionjson examplejquerylist2jqgridnavgridpager2editfalseaddfalsedelfalsei have no idea about how to deal this responsive issue with jqgrid alternatively i can replace jqgrid with datatable plugin for responsiveness but we use jqgrid in many place and functions very well we dont want to break existing functionalityany ideasuggestions to use jqgrid as responsivenessfluid layout support,"['jquery', 'html', 'css']" +524443,what is the execution order of an mvc razor viewlayout i have a razor layout likeusing var context setupsomecontext div some content here renderbody divand a view like layout mylayoutcshtmldivsomethingthatdependsoncontextbeingsetupdivwhen the view renders somethingthatdependsoncontextbeingsetup executes before setupsomecontext and fails this seems weird because i would expect that not to execute until renderbody is called in the layout when i switch this to use a pagecontent section instead of renderbody everything works as expected can anyone explain this behavior,['c#'] +524449,glassfish 40 w jersey returns 500 internal server error without exception i am using a glassfish 40 server and serversided jpabased classes which i want to deliver via jaxrs this works fine so far for simple entities however if i have a onetomany relation for example and there is a linked entity the server returns a 500 internal server error in that case nothing is logged to the server log in order to find the error i created a small custom jsp page to get more info about what happened the code is just thisstatus pagecontextgeterrordatagetstatuscode throwable pagecontextgeterrordatagetthrowable unfortunately the output is just status 500 throwable nullmy own serversided code seems to run properly did some debug output but however some error emerges in this example the user and issue classes can be retrieved without a problem unless there is a linked issuecomment entityuser classpackage myapplicationmodelimport static javaxpersistencefetchtypelazyimport javaioserializableimport javautillistimport javaxpersistencecolumnimport javaxpersistenceentityimport javaxpersistencegeneratedvalueimport javaxpersistencegenerationtypeimport javaxpersistenceidimport javaxpersistenceonetomanyimport javaxpersistencetableimport javaxxmlbindannotationxmlrootelement the persistent class for the user database table xmlrootelemententitynameusertablenameuserpublic class user implements serializable private static final long serialversionuid 1l id generatedvaluestrategy generationtypeidentity columnnameid private int id columnnamefailedlogin private short failedlogin columnnamefirstname private string firstname columnnamelastname private string lastname columnnamemiddlename private string middlename columnnamepassword private string password columnnameusername private string username bidirectional manytoone association to issuecomment onetomanymappedbyuser fetch lazy private listissuecomment issuecomments bidirectional manytoone association to signalcomment onetomanymappedbyuser fetch lazy private listsignalcomment signalcomments bidirectional manytoone association to signalmeasure onetomanymappedbyuser fetch lazy private listsignalmeasure signalmeasures public user public int getid return thisid more getters and setters autogenerated by eclipse user classpackage myapplicationmodelimport javaioserializableimport javautildateimport javautillistimport javaxpersistencecolumnimport javaxpersistenceentityimport javaxpersistencegeneratedvalueimport javaxpersistencegenerationtypeimport javaxpersistenceidimport javaxpersistencenamedqueryimport javaxpersistenceonetomanyimport javaxpersistencetableimport javaxpersistencetemporalimport javaxpersistencetemporaltypeimport javaxxmlbindannotationxmlrootelementnamedquery name getsingleissue query select i from issue i where iid id the persistent class for the issue database table xmlrootelemententitynameissuetablenameissuepublic class issue implements serializable private static final long serialversionuid 1l id generatedvaluestrategygenerationtypeidentity columnnameid private int id columnnameconcernedmodule private string concernedmodule columnnamecreatedate temporaltemporaltypetimestamp private date createdate columnnameduedate temporaltemporaltypetimestamp private date duedate columnnamepriority private int priority columnnamereminderdate temporaltemporaltypetimestamp private date reminderdate columnnameresponsibleuserid private int responsibleuserid columnnamesendingmodule private string sendingmodule columnnameseverity private int severity columnnamestatus private int status columnnametitle private string title bidirectional manytoone association to issuecomment onetomanymappedby issue private listissuecomment issuecomments public issue public int getid return thisid more getters and settersissuecommentpackage myapplicationmodelimport javaioserializableimport javaxpersistenceimport javautildate the persistent class for the issuecomment database table entitynameissuecommenttablenameissuecommentpublic class issuecomment implements serializable private static final long serialversionuid 1l id generatedvalue columnnameid private int id lob columnnamecomment private string comment temporaltemporaltypetimestamp columnnametime private date time bidirectional manytoone association to issue manytoonefetch fetchtypeeager joincolumnnameissueid private issue issue bidirectional manytoone association to user manytoonefetch fetchtypeeager joincolumnnameuserid private user user public issuecomment public int getid return thisid public void setidint id thisid id getterssettersthe webservice is as followspackage myapplicationserverwebserviceimport javaxwsrsgetimport javaxwsrspathimport javaxwsrsproducesimport javaxwsrsqueryparamimport javaxwsrscoremediatypeimport javaxwsrsextproviderimport orgglassfishjerseyserverresourceconfigimport myapplicationdatauserstorageimport myapplicationloggerloggerimport myapplicationmodelsignalimport myapplicationmodelsignalcommentimport myapplicationmodeluserproviderpathuserpublic class userservice extends resourceconfig private userstorage storage new userstorage public userservice thispackagesmyapplicationmodel producesmediatypeapplication xml pathload get public user getuserqueryparamid int id try loggergetinstancelogfetching id id user you storagegetuserid loggergetinstancelognumber of signal comments ugetsignalcommentssize signalcomment sc ugetsignalcommentsget0 loggergetinstancelogsignal 0 comment scgetcomment signal s scgetsignal loggergetinstancelogsignal subject sgetsubject return u catch exception e eprintstacktrace this code is not being reached so no errors in this method loggergetinstancelogexception has been thrown return null i left away the client source code since it is serversided and can be reproduced with a normal browser so no necessity for client code here imho,['java'] +524450,best method to download image from url in android i am using below method to download single image from urlpublic static bitmap getbitmapstring url try inputstream is inputstream new urlurlgetcontent bitmap d bitmapfactorydecodestreamis isclose return d catch exception e return null sometimes i get an outofmemory exceptioni am unable to catch outofmemory exception the app will close how to prevent this is there a better method for downloading images that is also faster,['android'] +524501,how to identify a generator vs list comprehension i have this sum ii for i in xrange5my question is in this case am i passing a list comprehension or a generator object to sum how do i tell that is there a general rule around thisalso remember sum by itself needs a pair of parentheses to surround its arguments i would think that the parentheses above are for sum and not for creating a generator object wouldnt you agree,['python'] +524593,what is the right way to use djangoallauth with tastypie i am writing a django app that uses djangoallauth for facebook integration and uses djangotastypie for a backend for an ios app the ios app will use the native facebook ios sdk i would like to be able to sign up and verify both facebook and nonfacebook users from the ios app in addition to the websitethe issue is that djangoallauth does not seem to have an api that can be accessed externally the only clean way to plugin to allauths functionality seems to be via django template tags is there a way i can expose this functionality to be used with tastypiedjangoallauth is all open source so i have tried to parse through the code my initial idea is to authenticate users on the ios side using the native facebook sdk and then manually fill in information for socialaccount socialtoken and add the socialaccount to socialapp those are all djangoallauth models however that seems to be quite a hacky solution i would love a way to cleanly create all those models given a facebook id or something similarupdatethere is been some thiscussion concerning this issue on the github basically there is no builtin functionality yet i am going to whip up a custom solution that only deals with facebook because that is all i am using in my application i will post what i did here later if it works,['python'] +524600,how to use hibernate in a multi threaded application i am trying to use hibernate for a multi threaded application wherein each thread retrieves an object and tries to insert it into a table my code looks like below i have local hibernate session objects per thread and in each insertdata i do begintransaction and commit the problem i am facing is that many times i get orghibernatetransactionexception nested transactions not supportedsince i am new to hibernate i do not know if what i am doing is correct or not please let me know what is the correct way to use hibernate in multi threaded app and how to avoid the above mentioned exceptionthanks public class worker extends thread private session session nullworker sessionfactory sf hibernateutilgetsessionfactory singleton session sfopensession sessionsetflushmodeflushmodealwayspublic void run some loop which will run thousand of times for insertdatab sessionclose blogpost table has pk id autogenerated datetime blogdescription etc private void insertdatablogpost b sessionbegintransaction long id long sessionsaveb bsetidid sessiongettransactioncommitmy hibernate config file has c3p0min size10 and c3p0max size20,['java'] +524647,how to create folder with php code can we create folder with php code i want that whenever a new user create his new account his folder automatically creates and a php file also createdis this possible,['php'] +524749,validate fields using jquery validation without any submit i have a html5 web application with numerous userentered fields and i would like to do some clientside validation on those fields in javascript before sending them to the server easy right just use jquery validation plugin but there is a catch my web app has no forms there is no submit anywhere in the html instead there is a jquery change handler on every userchangeable element and when the user changes the value of one of those element an ajax call is made this nonstandard user interaction architecture makes sense for this application i would like to validate the field before the ajax call and use the jquery validation plugin to do that but i cannot figure out how is it possible to use the jquery validation plugin without a submit anywhere how would i do this or is another approach better,['jquery'] +524761,github link to function in source i know i can have anchors to a certain line but if the source changes that line might become irrelevant examplesourcephpl33 line 33 may become line 40 later is there some way to tell github to link to a certain function or property from the source without specifying the linethe source is written in php code,['php'] +524872,how to set different background of keys for android custom keyboard i am working on custom keyboard application this is code for background color of inputxml in softkeyboard override public view oncreateinputview logeonstartinputview on startinput view called sharedpreferences preferences preferencemanagergetdefaultsharedpreferencesthis string backgroundcolour preferencesgetstringbackgroundcolour logebrithnes backgroundcolour ifbackgroundcolourequalsignorecaseblack thisminputview keyboardview getlayoutinflaterinflate rlayoutinput null else thisminputview keyboardview getlayoutinflaterinflate rlayoutinput1 null thisminputviewsetb thisminputviewsetonkeyboardactionlistenerthis thisminputviewsetkeyboardthismqwertykeyboard return thisminputview override public void onstartinputvieweditorinfo attribute boolean restarting superonstartinputviewattribute restarting apply the selected keyboard to the input view setinputviewoncreateinputviewi am not getting how to set background image for specific key,['android'] +524885,functional way to check if array of numbers is sequential let us say that an array is sequential when each successful element has the value of previous element 1 suppose i have an array of numbers like 5678 sequential or 125 not sequential is there a nice functional way to check if the array is sequential i can do it with the following code bool issequentialint array for int i 1 i arraylength i if arrayi arrayi 1 1 return false return truei am trying to determine if a poker hand is straight,"['c#', '.net']" +524958,is there a try converttoint32 avoiding exceptions i would like to know if there is a safe way to convert an object to an int avoiding exceptionsi am looking for something like public static bool trytoint32object value out int resulti know i could make something like this public static bool trytoint32object value out int result try result converttoint32value return true catch result 0 return false but i would rather avoid exceptions because they are slowing down the processi think this is more elegant but it is still cheap public static bool trytoint32object value out int result if value null result 0 return false return inttryparsevaluetostring out result anyone has better ideasupdatethis sounds a little like splitting hairs search but converting an object to string forces the implementer to create a clear tostring functionfor example public class percentage public int value get set public override string tostring return stringformat0 value percentage p new percentage pvalue 50 int v if inttryparseptostring out v this goes wrong i can do two things here or implement the iconvertable like below public static bool toint32object value out int result if value null result 0 return false if value is iconvertible result iconvertiblevaluetoint32threadcurrentthreadcurrentculture return true return inttryparsevaluetostring out result but the toint32 of the iconvertible cannot be canceled so if it is not possible an exception cannot be avoidedor two is there a way to check if the object contains a implicit operatorthis is very poor if valuegettypegetmethodsfirstordefaultmethod methodname op implicit methodreturntype typeofint null result intvalue return true,['c#'] +524971,check if utf8 string is valid in qt in qt is there a way to check if a byte array is a valid utf8 sequenceit seems that qstringfromutf8 silently suppresses or replaces invalid sequences without notifying the caller that there were any this is from its documentationhowever invalid sequences are possible with utf8 and if any such are found they will be replaced with one or more replacement characters or suppressed,['c++'] +524972,error mapfragment cannot be cast to androidsupportv4appfragment first i watched out here start fragmentactivity from activity and now i have the following problemmapsactivitypublic class mapsactivity extends fragmentactivity private googlemap mmapoverridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmaps setupmapifneededand want to start it out of the mainactivity withstartactivitynew intentthis mapsactivityclassthe activity is registered in android manifestactivity androidnamedexbjoernxgappmapsactivityactivityerrorfatal exception mainjavalangruntimeexception unable to start activity componentinfodexbjoernxgappdexbjoernxgappmapsactivity androidviewinflateexception binary xml file line 2 error inflating class fragment at androidappactivitythreadperformlaunchactivityactivitythreadjava2308 at androidappactivitythreadhandlelaunchactivityactivitythreadjava2358 at androidappactivitythreadaccess600activitythreadjava153 at androidappactivitythreadhhandlemessageactivitythreadjava1247 at androidoshandlerthispatchmessagehandlerjava99 at androidoslooperlooplooperjava137 at androidappactivitythreadmainactivitythreadjava5227 at javalangreflectmethodinvokenativenative method at javalangreflectmethodinvokemethodjava511 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava795 at comandroidinternaloszygoteinitmainzygoteinitjava562 at dalviksystemnativestartmainnative methodcaused by androidviewinflateexception binary xml file line 2 error inflating class fragment at androidviewlayoutinflatercreateviewfromtaglayoutinflaterjava704 at androidviewlayoutinflaterinflatelayoutinflaterjava466 at androidviewlayoutinflaterinflatelayoutinflaterjava396 at androidviewlayoutinflaterinflatelayoutinflaterjava352 at comandroidinternalpolicyimplphonewindowsetcontentviewphonewindowjava323 at androidappactivitysetcontentviewactivityjava1881 at dexbjoernxgappmapsactivityoncreatemapsactivityjava19 at androidappactivityperformcreateactivityjava5104 at androidappinstrumentationcallactivityoncreateinstrumentationjava1080 at androidappactivitythreadperformlaunchactivityactivitythreadjava2262 11 morecaused by javalangclasscastexception comgoogleandroidgmsmapsmapfragment cannot be cast to androidsupportv4appfragment at androidsupportv4appfragmentinstantiatefragmentjava394 at androidsupportv4appfragmentinstantiatefragmentjava369 at androidsupportv4appfragmentactivityoncreateviewfragmentactivityjava272 at androidviewlayoutinflatercreateviewfromtaglayoutinflaterjava676 20 moreany suggestions how to fix itthanks so far,['android'] +525025,dynamically changing the size of font size based on text length using css and html i need to thisplay user entered text into a fixed size div what i want is for the font size to be automatically adjusted so that the text fills the box as much as possiblei would probably want to start with a maximum font size and while the text is too big to fit the container shrink the font size until it fits and the font must be thisplayed as a single line is it possible to do this using only css and html,"['javascript', 'html', 'css']" +525044,switch combining cases string regex and number is there a way to create multiple cases in a single javascript switch statementin my code i receive the value of a field via jqueryis it possible that one case checks for string regex and another for number of the same variablei am thinking along the lines ofvar field thisvalvar msgswitch field case fieldtestyes msg foon break case 10 msg barn breakalthough i saw here switch statement for string matching in javascriptthat the way to use switch on strings is by sending the switch statement a true valuewhat would be the most concise and correct way to achieve this,"['javascript', 'jquery']" +525064,how can i thisable certain options with select2 and remote data select2 supports thisabled options when it is initialized on a select tag as thiscussed in this issuehowever i cannot find how to achieve the same result with remote datado i need to use a custom format function how do i prevent the user from selecting it thenor is this builtin somewherethanks,"['javascript', 'jquery', 'html']" +525070,how can i do multiple operations inside a c linq foreach loop i have a list of question objects and i use a foreach to iterate through the list for each object i do an add to add it into my entity framework and then the databaselistquestion add problemquestionstolistaddforeach obj uowquestionsadd obji need to modify each of the objects in the foreach and set the assigneddate field to datetimenow is there a way i can do this inside of the foreach loop,['c#'] +525088,android imageview zoomin and zoomout continuously is there any way to zoomin and zoomout an imageview continuously in android i tried using the below code but only one of the zoom function is working zoominxml xml version10 encodingutf8 set xmlnsandroid androidfillaftertrue scale xmlnsandroid androidduration20 androidfromxscale1 androidfromyscale1 androidpivotx50 androidpivoty50 androidtoxscale3 androidtoyscale3 scalesetzoomoutxml xml version10 encodingutf8 set xmlnsandroid androidfillaftertrue scale xmlnsandroid androidduration20 androidfromxscale10 androidfromyscale10 androidpivotx50 androidpivoty50 androidtoxscale05 androidtoyscale05 scalesetand the activity class that i have animation zoomin zoomout declared as publicoverridepublic void oncreatebundle savedinstancestate animation zoomin animationutilsloadanimationthis ranimzoomin zoomout animationutilsloadanimationthis ranimzoomout bgimagesetanimationzoomin bgimagesetanimationzoomout thread t new threadnew zoom tstartprivate class zoom implements runnable override public void run while true bgimagestartanimationzoomin try threadsleep80 catch interruptedexception e eprintstacktrace bgimagestartanimationzoomout here the zoomin animation seems to be working fine is there any way to implement the zoomin and zoomout animation continuously thanks,['android'] +525112,convert string to day of week not exact date i am receiving a string which is a spelled out day of the week eg monday now i want to get the constant integer representation of that day which is used in javautilcalendardo i really have to do ifdayequalsignorecasemondayelse if on my own is there some neat method if i dig up the simpledateformat and mix that with the calendar i produce nearly as many lines as typing the ugly ifelsetoinfitity statetment,['java'] +525118,which http status code should be used for a upload err partial i am developing a rest api and i have some file uploadsphp can generate an upload err partial error when the file was only partially uploaded and i am not sure of which http status code should be used in this casethis usually happens if the user cancels the upload see why might a file only be partially uploaded and file upload errors on phpnet upload err partial is given when the mime boundary is not found after the file data a possibly cause for this is that the upload was cancelled by the user pressed esc etc,['php'] +525144,check if a type implements a generic interface without considering the generic type arguments i have an interfacepublic interface myinterfacetkey tvalueimplementations are irrelevant now i want to check if a given type is an implementation of that interface this method fails forpublic class myclass myinterfaceint stringbut i do not know how to do the checkpublic void checkiftypeimplementsinterfacetype type var result1 typeofmyinterfaceisassignablefromtype false var result2 typeofmyinterfaceintstringisassignablefromtype truewhat do i have to do for result1 to be true,['c#'] +525150,boostfilesystemrecursive directory iterator with filter i need to recursively get all files from directory and it is subdirectory but excluding several directory i know their names is it possible to do with boostfilesystemrecursive directory iterator,['c++'] +525230,how to add a 1 second delay using qtimer i currently have a method which is as followsvoid somemethodint a delay for one sec timerstart10 after one sec someotherfunctionathis method is actually a slot that is attached to a signal i would like to add a delay of one sec using qtimerhowever i am not sure on how to accomplish this since the timer triggers a signal when its finished and the signal would need to be attached to another method that does not take in any parameters any suggestion on how i could accomplish this task update the signal will be called multiple times in a second and the delay will be for a second my issue here is passing a parameter to the slot attached to timeout signal of a timermy last approach would be to store the value in a memeber variable of a class and then use a mutex to protect it from being changed while the variable is being used however i am looking for simpler methods here,['c++'] +525246,wheres the 24th fraction bit on a single precision float ie 754 i found myself today doing some bit manipulation and i decided to refresh my floatingpoint knowledge a littlethings were going great until i saw this 23 fraction bits of the significand appear in the memory format but the total precision is 24 bitsi read it again and again but i still cannot figure out where the 24th bit is i noticed something about a binary point so i assumed that it is a point in the middle between the mantissa and the exponenti am not really sure but i believe he author was talking about this bit binary point sem0 0100 010 this,"['c++', 'c']" +525293,net binary serialization metadata a week ago i got in a situation where i had to read a binary serialized object made by another application made by somebody else i only had the someserializeddatabin file so i tried to manually recreate the class definition for the unknown object and i was able to do so because of the metadata in the serialized fileoddly i could not find any tool on googleq1 why is there no tool that recreates the class definition from a binary serialized filedataand it leads to my second questionq2 is there such case when it is impossible to restore the class definition from the serialized data assuming it is no encrypted or obfuscated in any way i am interested in cases involving the default net binaryserializer properties to thisable type information and metadata included,['c#'] +525312,how to set net 40 as the default framework in monodevelop unity 3d i am using monodevelop version 282 and the default parameters that are available in the net 40 framework my first problem was that every time i reloaded md the net runtime would be reset to 30 and i would have to change it again this was not too annoying but i do also want to know why that kept happening and how i might permanently set itmy real issue now is that the net runtime or whatever it specifically was i cannot remember under the options dropdown no longer appears instead i see a thisabled project optionsi would put an image of what i see here but apparently i need reputationif even one of these issues is fixed i should be fine but right now i cannot rely on the errors messages from the ide and have to switch back to unity,['.net'] +525314,django generic relations error cannot resolve keyword content object into field i am using djangos generic relations to define vote model for question and answer models here is my vote modelmodelspyclass votemodelsmodel user voted modelsforeignkeymyuser is upvote modelsbooleanfielddefaulttrue generic foreign key content type modelsforeignkeycontenttype object id modelspositiveintegerfield content object genericgenericforeignkeycontent type object id class meta unique together content type user votedviewspy user voted myuserobjectsgetidrequestuserid object type requestpostgetobject type object none if object type question object get object or 404question idselfkwargspk elif object type answer object get object or 404answer idselfkwargspk this last line gives me the error vote created voteobjectsget or createuser voteduser voted content objectobjectand then i get this errorfielderror at 1 cannot resolve keyword content object into field choices are answer content type id is upvote object id question user votedwhen i print the object to django console it prints question 1 object so i do not understand why the line content objectobject gives me the field errorany ideas thanks,['python'] +525323,cannot set property innerhtml of null why do i get an error or uncaught typeerror cannot set property innerhtml of nulli thought i understood innerhtml and had it working beforedoctype htmlhtmlheadmeta httpequivcontenttype contenttexthtml charsetutf8titleuntitled documenttitlescript type textjavascript what function what documentgetelementbyidhelloinnerhtml hi scriptheadbodydiv idhellodivbodyhtml,['javascript'] +525401,ignore a property during xml serialization but not during deserialization in c how can i make xmlserializer ignore a property during serialization but not during deserialization or how do i do the same with jsonnetto prevent a property from being serialized you can add the xmlignore attributexmlignorepublic int foobar getsetthis will cause the foobar tag to be omitted during serializationhowever this also means that the foobar tag will be ignored during deserializationin my case i accept an array of items from user in the request and for each item user can specify an action property if they want to add modify or delete the item i want to use the same model object for get list calls and do not want to return this action property i expect this would be a pretty common caseanother use casesay you have a circle objectpublic class circle public double radius get set and you modify it to add a diameter propertypublic class circle2 public double diameter get set public double radius get return diameter 2 set diameter value2 you may want to serialize only the diameter but still be able to deserialize xml files in the old format that contain only the radiusi did my research and did not find anything hence this questionsolution i figured out the solution i can add a shouldserialize property which always return false details at this msdn documentationthis solution could be added as an actual answer if this question is reopened,"['c#', '.net']" +525405,karma uncaught referenceerror jquery is not defined i am running karma on my yeoman based angularjs app i get the following error when running grunt karmachrome 280 mac error uncaught referenceerror jquery is not defined at myngappadminappscriptsbootstrapminjs6chrome 280 mac executed 0 of 0 error 0206 secs 0 secswhen i launch the app on my browser via grunt server everything seems fine there are no errors on the console either my indexhtml also imports jqueryminjs before any other javascript file any idea what is going onupdate i have a feeling the the command grunt karma is looking through all the files in my scripts directory bootstrap is one of the first ones and it probably loads that before jquery and hence the error if this is the case how do i stop this,['jquery'] +525407,uploading photos to instagram via your own ios app instagram recently made a change to their api policy which allowed developers to post pictures to the instagram platform via their own app several other techniques were previously employed to do this one of them was to invoke the instagram application which would essentially open up instagram and do the sharing from there a tutorial on how this can be done can be seen here how to share image to instagram from your own ios app however there are several applications out there that allow for direct sharing to the instagram platform without invoking the instagram application hipstamatics oggl allows for direct sharing to instagram without invoking instagram below i have posted some screen shots of the processonce my picture was taken oggl gave me several other social networks to which i could share my photo to i have selected facebook and instagramafter i selected instagram it opened up safari and it brought me to the following two pages to authorize oggl to post to instagram i entered in my instagram credentials and then it brought me to the authorization page once i authorized oggl i was able to upload to instagram and within seconds i saw the photo on my instagram news feed this type of sharing is very analogous to facebook and twitter sharing it has the same concept how can one go about doing this how can one replicate this exact process in their app the pictures taken in my application are 612px by 612 px so they are compatible with the dimensions for photos taken on instagram i have already implemented sharing to facebook and twitter but i would like to implement uploading to instagram just like how oggl did is this possiblethere are many ios developers out there who can benefit from a well detailed canonical answer to this question thank you,['ios'] +525454,how to integrate karma with rails asset pipeline i would like to use the karma test runner in my angularjs rails project has anyone integrated them successfully more specifically i am interested to know how to integrate with the asset pipeline i have files with extension cofferb which would need to be preprocessed twicei use karma version 0101 and rails 4any help examples would be appreciated,['ruby-on-rails'] +525468,changing uitextfield placeholder font i am changing the placeholder text color with the following code but when i try to add nsfontattribute i get the compiler error too many arguments to method call expect 2 have 3 uicolor color uicolor blackcolor namefieldattributedplaceholder nsattributedstring alloc initwithstringyour name attributesnsforegroundcolorattributename colornsfontattributenamerobotobold this works fine uicolor color uicolor blackcolor namefieldattributedplaceholder nsattributedstring alloc initwithstringyour name attributesnsforegroundcolorattributename color,"['ios', 'objective-c']" +525531,pausing with handler and postdelayed in android i am very new to android programming so please forgive my noobieness i am trying to create a very simple activity that will have one textview in the middle of the layout and just have it switch to a different text every couple of seconds for example the textview will say text1 pause for a couple of seconds then say text2 and pause again eventually i want to add more texts and have them all cycle one after another i know this seems like a super simple thing but i am mainly trying to learn about threads and handlers at this moment anyways i have read up on how we should keep lengthy things off the ui thread to prevent an error so i thought i would use a handler to simply switch between 2 texts on screen unfortunately i cannot get this to work heres some codepublic class mainactivity extends activity string myarray text1 text2int arraylength myarraylengthint counthandler handler new handlertextview mytextsoverrideprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main mytexts textviewfindviewbyidridmy texts mytextssettextmyarray0 thread t new thread new runnable public void run for int count 0 count arraylength count handlerpostdelayednew runnable public void run mytextssettextmyarray1 70 tstart from what i can see in the logcat the handler seems to run postdelayed one right after another in my codes case it does not wait 7 seconds with the postdelay to do another postdelayed also i would like to make the 1 in mytextssettextmyarray1 be the same as count in the for loop so it can be the same as one of the strings in the array but that gives me an error i have been stuck on this for hours and other examples i have found online seem way too complicated for someone like me who mainly wants to get the basics down before i can tackle other things any help at all with any of this would be much appreciated thank you,['android'] +525584,passing arguments to a filter laravel 4 is it possible to access route parameters within a filtereg i want to access the agencyid parameterroutegrouparrayprefix agency function agency dashboard routegetagencyid arrayas agency uses controllersagencydashboardcontrollergetindexi want to access this agencyid parameter within my filterroutefilteragencyauth function check if the user is logged in if sentrycheck store the current uri in the session sessionputloginredirect requesturl redirect to the login page return redirectroutesignin this clearly does not work how do i do this agencyid inputgetagencyid agency sentrygetgroupproviderfindbyidagencyid check if the user has access to the admin page if sentrygetuseringroupagency show the insufficient permissions page return appabort403 just for reference i call this filter in my controller as suchclass agencycontroller extends authorizedcontroller initializer return void public function construct apply the admin auth filter thisbeforefilteragencyauth,['php'] +525585,generate csv for excel via javascript with unicode characters i am trying to generate a csv file on the client side using javascript i have followed the answer on this stackoverflow question i have unicode characters in the content hebrew characters in my casethe file generation succeeds however when i open the file in excel all the unicode characters are shown as funny characters ascii characters english and numbers are presented wellthe weird thing is that if i open the file in notepad the unicode characters show well so i guess this has something to do with excel and the way i am saving the fileany ideas,['javascript'] +525609,how does operator in regex work i thought i understand how regex operators work but now i am really confusedin simplified example i have two stringsmailwowno1commailololowowcomi want to match first one not the secondand i am writing regex simplified version like thismailwowcomand when i run in js method test on both those examples it simply returns true in sublime 2 regex search highlights both strings that means both strings matchedi know that i can make reverse regex that will match second and make logic depending on this but i just want to understand how in regex works and what am i doing wrongthanks,['javascript'] +525625,why does taskwait not deadlock on a nonui thread or am i just lucky first a small bit of background information i am in the process of making existing c library code suitable for execution on winrt as a minor part of this code deep down needs to do a little file io we first tried to keep things synchronous and used taskwait to stop the main thread until all io was donesure enough we quickly found out that leads to a deadlocki then found myself changing a lot of code in a prototype to make it asynchronous that is i was inserting async and await keywords and i was changing the method return types accordingly this was a lot of work too much senseless work in fact but i got the prototype working this waythen i did an experiment and i ran the original code with the wait statement on a separate threadsystemthreadingtaskstaskrun draw cancellationtokenno deadlocknow i am seriously confused because i thought that i understood how async programming works our code does not yet use configureawaitfalse at all so all await statements should continue in the same context as they got invoked in right i assumed that that means the same thread now if this thread has invoked wait this should also lead to a deadlock but it does notdo any of you have a clear rocksolid explanationthe answer to this will determine whether i will really go through messing up our code by inserting a lot of conditional asyncawait keywords or whether i will keep it clean and just use a thread that does a wait here and there if the continuations get run by an arbitrary nonblocked thread things should be fine however if they get run by the ui thread we may be in trouble if the continuation is computationally expensivei hope that the issue is clear if not please let me know,['c#'] +525643,what does this mean ive almost only programmed in objectivec for a couple of months ago i programmed a little in box2d and say this now what does that mean its cant be objectivec it must be from c because box2d is c i one time saw someone using it in objectivec code and i just could not seem to understand what it did google does not support nontext characters so its impossible for me to google it since i do not know what it is,"['c++', 'objective-c']" +525679,rails difference between modelcount and modelcountall is there any difference between usercount and usercountalli upgraded rails to 40 then when i use modelnamecountall it is working well but if i use modelnamecount the following error occursby the way bot of them is working well in rails 32select count from userspgwrongobjecttype error count must be used to call a parameterless aggregate functionline 1 select count from users,['ruby-on-rails'] +525681,how to turn a ruby method into a block is there a way to simplify the following codefilenames is a list of filenames strings eg footxt barc bazyamlfilenamesmap f filesizef is there any way to turn filesize into a proc or block for methods on existing objects i can do method is there something analogous for module level methods,['ruby'] +525693,uploading file using jersey over restfull service and the resource configuration is not modifiable pathfileuploadpublic class uploadfileservice postconsumesmediatypemultipart form datapublic response uploadfile formdataparamfile inputstream uploadedinputstream formdataparamfile formdatacontentthisposition filedetail systemoutprintlnuploadfileservice1 should we use a thisk or db decided to use thisk path should be read from propertiesfiles string uploadedfilelocation uploaded filedetailgetfilename save it writetofileuploadedinputstream uploadedfilelocation string output file uploaded to uploadedfilelocation all went ok return responsestatus200entityoutputbuild warning no injection source found for a parameter of type public javaxwsrscoreresponse cominsameserviceuploadfileserviceuploadfilejavaioinputstreamcomsunjerseycoreheaderformdatacontentthisposition at index 0severe webmoduleinsamestandardwrapperthrowableorgglassfishjerseyservermodelmodelvalidationexception validation of the application resource model has failed during application initializationfatal no injection source found for a parameter of type public javaxwsrscoreresponse cominsameserviceuploadfileserviceuploadfilejavaioinputstreamcomsunjerseycoreheaderformdatacontentthisposition at index 0 sourceresourcemethodhttpmethodpost consumedtypesmultipartformdata producedtypes suspendedfalse suspendtimeout0 suspendtimeoutunitmilliseconds invocableinvocablehandlermethodhandlerhandlerclassclass cominsameserviceuploadfileservice handlerconstructorsorgglassfishjerseyservermodelhandlerconstructor47bee27a handlingmethodpublic javaxwsrscoreresponse cominsameserviceuploadfileserviceuploadfilejavaioinputstreamcomsunjerseycoreheaderformdatacontentthisposition parametersparameter typeclass javaioinputstream sourcefile defaultvaluenull parameter typeclass comsunjerseycoreheaderformdatacontentthisposition sourcefile defaultvaluenull responsetypeclass javaxwsrscoreresponse namebindings at orgglassfishjerseyserverapplicationhandlerinitializeapplicationhandlerjava410 at orgglassfishjerseyserverapplicationhandleraccess500applicationhandlerjava157 at orgglassfishjerseyserverapplicationhandler3runapplicationhandlerjava280 at orgglassfishjerseyinternalerrors2callerrorsjava289 at orgglassfishjerseyinternalerrors2callerrorsjava286 at orgglassfishjerseyinternalerrorsprocesserrorsjava315 at orgglassfishjerseyinternalerrorsprocesserrorsjava297 at orgglassfishjerseyinternalerrorsprocesswithexceptionerrorsjava286 at orgglassfishjerseyserverapplicationhandlerinitapplicationhandlerjava277 at orgglassfishjerseyservletwebcomponentinitwebcomponentjava262 at orgglassfishjerseyservletservletcontainerinitservletcontainerjava167i implemented test service like this under the uploadfileservicegetpathcountproducestextplainpublic string countrest return 1 one 1and i got this exception to logfine websecurity hasresource perm javaxsecurityjaccwebresourcepermission webresourcesfileuploadcount getsevere webmoduleinsamestandardwrapperthrowablejavalangillegalstateexception the resource configuration is not modifiable in this context at orgglassfishjerseyserverresourceconfigimmutablestateregisterresourceconfigjava257warning standardwrappervalvecominsameserviceapplicationconfig allocate exception for servlet cominsameserviceapplicationconfigjavalangillegalstateexception the resource configuration is not modifiable in this context at orgglassfishjerseyserverresourceconfigimmutablestateregisterresourceconfigjava257 at orgglassfishjerseyserverresourceconfigimmutablestateregisterresourceconfigjava205 at orgglassfishjerseyserverresourceconfigregisterresourceconfigjava435 at orgglassfishjerseyservletwebcomponentinitwebcomponentjava261 at orgglassfishjerseyservletservletcontainerinitservletcontainerjava167 at orgglassfishjerseyservletservletcontainerinitservletcontainerjava349environmentnetbeans731glassfish 40jersey 2 with glassfish 40,['java'] +525699,aspnet use sqlconnection connect mysql this is the conection string saved in webconfigappsettings add keyconn valuedrivermysql odbc 51 driverserver127001uidrootpwd1234databasegis serveroption3 appsettingsthis is the code to connect databaseprotected bool checkpasswordbysqlserverstring stremail string strpsw if stremailtolower admin return false string str select idrankrankencparentusercompany from tbl user where usernameusername and password1password private string strconn configurationmanagerappsettingsconntostring sqlconnection sqlconnection new sqlconnectionstrconn bool flag false try try sqlconnectionopen sqlcommand sqlcommand new sqlcommandstr sqlconnection sqlcommandparametersaddwithvalueusername stremail sqlcommandparametersaddwithvaluepassword strpsw sqldatareader sqldatareader sqlcommandexecutereader if sqldatareaderread flag false else thissessionusername stremail thissessionpassword strpsw thissessionlogintype group thissessionfullname sqldatareadercompanytostring if formsauthenticationhashpasswordforstoringinconfigfilestringconcatstremail char43 sqldatareaderranktostringtolower md5 sqldatareaderrankenctostringtrim flag false thissessionclientid sqldatareaderidtostring thissessionmylanguage baserequestcookieslanguagevalue thissessionparentuser sqldatareaderparentusertostringtrim thissessionrank sqldatareaderranktostring thissessionstrconnection thisstrconn flag true sqldatareaderclose catch exception exception thissetlblinfohtmlexceptionmessage finally sqlconnectionclose return flag but fail to connect mysql with this return errorsystemargumentexception keyword not supported driver at systemdatacommondbconnectionoptionsparseinternalhashtable parsetable string connectionstring boolean buildchain hashtable synonyms boolean firstkey at systemdatacommondbconnectionoptionsctorstring connectionstring hashtable synonyms boolean useodbcrules at systemdatasqlclientsqlconnectionstringctorstring connectionstring at systemdatasqlclientsqlconnectionfactorycreateconnectionoptionsstring connectionstring dbconnectionoptions previous at systemdataproviderbasedbconnectionfactorygetconnectionpoolgroupstring connectionstring dbconnectionpoolgroupoptions pooloptions dbconnectionoptions userconnectionoptions at systemdatasqlclientsqlconnectionconnectionstring setstring value at systemdatasqlclientsqlconnectionset connectionstringstring value at systemdatasqlclientsqlconnectionctorstring connectionstring at source loginfrmcheckpasswordbysqlserverstring stremail string strpsw at source loginfrmbtnlogin clickstring strlangis that possible sqlconnection to connect mysql database,"['c#', 'asp.net', 'mysql', '.net']" +525704,creating a numpy array of 3d coordinates from three 1d arrays suppose i have three arbitrary 1d arrays for examplex p nparray10 20 30 40 50y p nparray20 30 40z p nparray80 90these three arrays represent sampling intervals in a 3d grid and i want to construct a 1d array of threedimensional vectors for all intersections something likepoints nparray10 20 80 10 20 90 10 30 80 50 40 90order does not actually matter for this the obvious way to generate themnpoints lenx p leny p lenz ppoints npzerosnpoints 3i 0for x in x p for y in y p for z in z p pointsi x y z i 1so the question is is there a faster way i have looked but not found possibly just failed to find the right google keywordsi am currently using thisnpoints lenx p leny p lenz ppoints npzerosnpoints 3i 0nz lenz pfor x in x p for y in y p pointsiinz 0 x pointsiinz 1 y pointsiinz 2 z p i nzbut i feel like i am missing some clever fancy numpy way,['python'] +525746,android broadcast receiver not receiving intent i have two apps that i made and am trying to send an intent from one to the other but the intent is never getting to the onreceive however this problem is only one way the first app can send to the second but the second cannot send back info i am using a different intent action to send from the second to the first but otherwise they are identical any ideas on why this might not be working i have tried everything i can think of and read most of the posts i could find on here and to no avail it is not crashing or giving me any indications as to what is happening in the logcat it is just doing nothing send function private void sendfinishlogstring id string cond logdme send finish log intent logintent new intent logintentputextraid id logintentputextracond cond logintentsetactioncommeintentfinishlog logdmelogintent logintenttostring logintentgetextrastostring sendbroadcastlogintent receive classpublic class logreceiver extends broadcastreceiver public static arraylistlogdataholder logdata new arraylistlogdataholder private boolean found static simpledateformat dateformat new simpledateformatymmdd hhmmss private static string lasttime private static string now boot time override public void onreceivecontext cont intent logintent logdmeon receive etc receiving app manifest for receiving logs receiver androidname logreceiver androidenabledtrue intent filter action androidnamecommeintentfinishlog intent filter receiver,['android'] +525822,why is it a good idea to avoid nested blocks in a function php i installed a netbeans 74 beta and there is a new hint that says too many nested blocks in function declaration it is good practice to introduce new function i do try to avoid nested blocks within a function for better readability but is there any other reason why this would be a better idea specifically for php if that matters,['php'] +525858,adding 1 to a set containing true does not work i have recently started to learn python and have encountered something a little strange when playing with sets the following code sample does not produce the expected resultsa set true234a setadd1i expected a set to have the values true 1 2 3 4 but instead this code produced true 2 3 4 trying variations on this also produced the same resultsa set 1234a setaddtrueexpected true 1 2 3 4actual 1 2 3 4trying this with false and 0 obtained the same resultsa set false234a setadd0expected false 0 2 3 4actual false 2 3 4a set 0234a setaddfalseexpected false 0 2 3 4actual 0 2 3 4i understand that the bool type is inherited from int and that true 1 and false 0 but was still a little surprised by the above resultsdoes anybody know if this behaviour is by design also is it possible to have a set which contains both true false 0 and 1i did perform quite a bit of googling but was not able to find an answer to my questionsthanks in advanceupdatein response to the comments below i agree that the following question partially answers my questionis false 0 and true 1 in python an implementation detail or is it guaranteed by the languagebut i feel that it does not answer the query i have regarding the behaviour of sets and whether it is possible to have a set containing both true and 1 even though bool is inherited from int they are different types so i found the fact that a set cannot thistinguish between true and 1 to be a little confusing so really this is a question about the behaviour of sets in python not just about true 1,['python'] +525899,embed an interactive 3d plot in pyside what is the best way to embed an interactive 3d plot in a pyside gui i have looked at some examples on here of 2d plots embedded in a pyside guigetting pyside to work with matplotlibmatplotlib interactive graph embedded in pyqtpythonmatplotlibpyside fast timetrace scrollinghowever the functionality that i am looking for is not quite the same the figure needs to rotate and zoom based on mouse input from the user in the same way as if it were drawn in a separate window i am trying to avoid having to go in manually and write functions for transforming mouse click move into a figure rotate and canvas repainteven if that is the only way i am not even sure how to do that but i figure no pun intended that there should be a way to reuse the functionality already present for creating 3d plots in their own windowsheres my code it works as intended but the plot is not interactive any advice is appreciatededit i fixed the use of figurecanvas according to tcaswells corrections i also added a bit from the matplotlib event handling and picking documentation to show that the figure seems to be getting the events upon mouseclickfinal edit the following code now produces the plot as desired coding utf8 from pyside import qtcore qtguiimport numpy as npimport matplotlibimport sys specify the use of pysidematplotlibrcparamsbackendqt4 pyside import the figure canvas for interfacing with the backendfrom matplotlibbackendsbackend qt4agg import figurecanvasqtagg as figurecanvas import 3d plottingfrom mpl toolkitsmplot3d import axes3d unusedimportfrom matplotlibfigure import figure autogenerated code from qt designer class ui mainwindowobject def setupuiself mainwindow mainwindowsetobjectnamemainwindow mainwindowresize750 497 selfcentralwidget qtguiqwidgetmainwindow selfcentralwidgetsetobjectnamecentralwidget selfhorizontallayout 2 qtguiqhboxlayoutselfcentralwidget selfhorizontallayout 2setobjectnamehorizontallayout 2 selfframe 2 qtguiqframeselfcentralwidget selfframe 2setframeshapeqtguiqframestyledpanel selfframe 2setframeshadowqtguiqframeraised selfframe 2setobjectnameframe 2 selfverticallayout qtguiqvboxlayoutselfframe 2 selfverticallayoutsetobjectnameverticallayout selflabel qtguiqlabelselfframe 2 selflabelsetobjectnamelabel selfverticallayoutaddwidgetselflabel selflabel 2 qtguiqlabelselfframe 2 selflabel 2setobjectnamelabel 2 selfverticallayoutaddwidgetselflabel 2 selflineedit qtguiqlineeditselfframe 2 sizepolicy qtguiqsizepolicy qtguiqsizepolicyminimum qtguiqsizepolicyfixed sizepolicysethorizontalstretch0 sizepolicysetverticalstretch0 sizepolicysetheightforwidth selflineeditsizepolicyhasheightforwidth selflineeditsetsizepolicysizepolicy selflineeditsetobjectnamelineedit selfverticallayoutaddwidgetselflineedit spaceritem qtguiqspaceritem 20 40 qtguiqsizepolicyminimum qtguiqsizepolicyexpanding selfverticallayoutadditemspaceritem selfhorizontallayout 2addwidgetselfframe 2 selfframe plot qtguiqframeselfcentralwidget selfframe plotsetminimumsizeqtcoreqsize500 0 selfframe plotsetframeshapeqtguiqframestyledpanel selfframe plotsetframeshadowqtguiqframeraised selfframe plotsetobjectnameframe plot selfhorizontallayout 2addwidgetselfframe plot mainwindowsetcentralwidgetselfcentralwidget selfretranslateuimainwindow qtcoreqmetaobjectconnectslotsbynamemainwindow def retranslateuiself mainwindow mainwindowsetwindowtitleqtguiqapplicationtranslate mainwindow mainwindow none qtguiqapplicationunicodeutf8 selflabelsettextqtguiqapplicationtranslatemainwindow this is a qlabel none qtguiqapplicationunicodeutf8 selflabel 2settextqtguiqapplicationtranslatemainwindow and this is another one none qtguiqapplicationunicodeutf8 selflineeditsettextqtguiqapplicationtranslatemainwindow text goes here none qtguiqapplicationunicodeutf8 autogenerated code from qt designer class mainwindowqtguiqmainwindow def init self parentnone supermainwindow self init parent intialize the window selfui ui mainwindow selfuisetupuiself create the matplotlib widget and put it in the frame on the right selfuiplotwidget mpwidgetparentselfuiframe plotclass mpwidgetfigurecanvas def init self parentnone selffigure figurefacecolor0 0 0 supermpwidget self init selffigure selfsetparentparent plot random 3d data selfaxes selffigureadd subplot1 projection3d selfdata nprandomrandom3 100 selfaxesplotselfdata0 selfdata1 selfdata2 if name main app qtguiqapplicationsysargv mw mainwindow mwshow adjust the frame size so that it fits right after the window is shown s mwuiframe plotsize mwuiplotwidgetsetgeometry1 1 swidth 2 sheight 2 sysexitappexec,['python'] +525915,single iteration multiple output collections from java to scala i am currently trying to convert some java code to scala code the challenge is to ensure that the converted scala code does not end up doing something very inefficient when compared to the original java one for eg when trying to convert the following codeclass person string name integer age character genderpublic class testjava public static void mainstring args final listperson persons new arraylist final listperson males new arraylist final listperson anames new arraylist final listperson seniors new arraylist for final person p persons if pgender m malesaddp if page 60 seniorsaddp if pnamestartswitha anamesaddp since java relies on mutation this code looks logical but now i want to convert this to its scala equivalent without looping over the collection multiple times 3 times in this casei can of course use mutable list from the scala library and achieve the same thing as done by java but was wondering if it was possible to generate multiple collections from a given sequencecollection in a functionalscala way without iterating over the collection for n times where n is the criteria count thanks in advance,['java'] +525986,two inlineblock elements each 50 wide do not fit side by side in a single row doctype htmlhtmlheadtitlewidth issuetitlestyle typetextcssbody margin 0left width 50 background lightblue thisplay inlineblockright width 50 background orange thisplay inlineblockstyleheadbody div idleftleftdiv div idrightrightdivbodyhtmljsfiddle the above code is trying to place the left div and the right div side by side in a single row but as you can see in the above jsfiddle url this is not the casei am able to resolve the issue reducing the width of one of the divs to 49 see but this is not an ideal solution because a small gap appears between the two divsanother way i am able to solve the problem is by floating both the divs see this works finebut my original question remains why when both the divs are kept as inlineblock elements they do not fit side by side,"['html', 'css']" +525990,parsing css in c extracting all urls i need to get all urls url expressions from css files for exampleb background urlimg0 b background urlimg1 b background urlimg2 b background url img3 b background url img4 b background url img5 b background url img6 b background url img7 b background url img8 background urlnoimg0 background urlnoimg1 b background urlnoimg2 b color urlnoimg3 b content urlnoimg4 media screen and maxwidth 1280px b background urlimg9 b background urlimg10 i need to get all img urls but not noimg urls invalid syntax or invalid property or inside commentsi have tried using good old regular expressions after some trial and error i got thisprivate static ienumerablestring parseurlsregex string source var reurls new regexnx url s s url quote url kquote s return reurlsmatchessource castmatch selectmatch matchgroupsurlvaluethat is one crazy regex but it still does not work it matches 3 invalid urls namely 2 3 and 4 furthermore everyone will say that using regex for parsing complex grammar is wronglet us try another approach according to this question the only viable option is excss others are either too simple or outdated with excss i got this private static ienumerablestring parseurlsexcss string source var parser new stylesheetparser parserparsesource return parserstylesheetrulesets selectmanyi ideclarations selectmanyi iexpressionterms wherei itype termtypeurl selecti ivalue unlike regex solution this one does not list invalid urls but it does not list some valid ones namely 9 and 10 looks like this is known issue with some css syntax and it cannot be fixed without rewriting the whole library from scratch antlr rewrite seems to be abandonedquestion how to extract all urls from css files i need to parse any css files not only the one provided as an example above please do not heck for noimg or assume oneline declarationsnb this is not a tool recommendation question as any solution will be fine be it a piece of code a fix to one of the above solutions a library or anything else and i have clearly defined the function i need,"['c#', 'css']" +526022,rendering partials view in a rake task background job model in rails 4 i have read a lot on rendering rails partials and views in rake tasks background jobs models the vast majority of things i have found on stackoverflow and the web describe approaches working in rails 3 but they seem outdated and i did not get them to work even with quite some time spent experimentingso how can i render a partial in a background job in rails 4heres the best approach i have worked out so far demonstrated in the consolec applicationcontrollernewresult crender to stringpartial tweetstweet locals tweet tweetfirst tweet load 08ms select tweets from tweets order by tweetsid asc limit 1 author load 06ms select authors from authors where authorsid 1 order by authorsid asc limit 1 id 1 status load 06ms select statuses from statuses where statusestwitter id 367523226848866304 limit 1 rendered tweets tweet bodyhtmlslim 175ms rendered tweets resolved tweethtmlslim 237ms rendered tweets tweethtmlslim 281ms actionviewtemplateerror undefined method tweet path for class0x007fb21bf797a00x007fb21cb009e8 from usersthomasklemmrbenvversions200p195librubygems200gemsactionpack400libaction thispatchroutingpolymorphic routesrb129in polymorphic urlany ideas thanks in advanceupdate the tweet path mentioned above is indeed not defined this error resulted from linking to a path link to tweet project tweet slim templates using an instance variable that would be present in views inheriting from a certain controller but not when rendered outside of this context i solved this going through the appropriate association instead link to tweet tweetproject tweet,"['ruby-on-rails', 'ruby']" +526033,static html compilation with partials using gruntjs i have been looking all over for something that will let me precompile static websites using grunt it needs to have partials so i can include things like a common headerfooter across the pagesso far i have only really found jade which has a grunt plugin and this plugin for grunt that compiles dustjs templates to static html i do not really like jades syntax and the dust plugin for grunt is less than ideal are there any static html templating languages with gruntgulp support that do not deviate too much from regular html and are still active,['html'] +526103,should i always not catch nullpointerexception effective java recommend that we should not catch nullpointerexceptionis it always rightin many cases of catching nullpointerexception catch body only calls printstacktraceif i do not catch nullpointerexception and call printstacktrace how i can check the place where the exception occurredand also if i catch nullpointerexception and the catch body is empty we cannot get any stack information at that time can weupdatei analyzed statistics of catching runtimeexception in google android source aosp422 r12there are 249 runtimeexceptoin catchings and followings are statistics of catchbody42 throw it again as other exceptions runtimeexception 33 others 832 just return null or 0falsetrue or other default values14 just call log or printstacktrace5 just comment like fall through ignore not a valid type system process dead do nothing2 empty body3 thisplay error messages or send fail codes ex network service thiscovery failed replytomessagemsg nsdmanagerstop thiscovery failed nsdmanagerfailure internal error 3 intialize or reset related variablesin almost cases dalvik and external handle npe by throwing other exceptionsbut frameworks usually handle by returning null or other valuesdo you think that throwing other exceptions in catchbody is not bad or good handlingif npe occured in higher levelsex applications and the developer confirms the exception is not critical because the app is fully independent can i accept for our developer to ignore the npe by catchingand one more thing can i conclude that google android framework source code may be some unstable in aspects of runtimeexception,['java'] +526209,how to package opencv java in a jar i have been using opencv 245 with java for a while building an application and would now like to thistribute the app the library is loaded using the followingstatic systemloadlibraryopencv java245 which works fine however when exporting it does not work when running from the jarjava jar build1jar the opencv java245jar file is included as a user library with a native file libopencv java245dylib connected to it when running the executable jar generated from eclipse i get the unsatisfiedlinkerror below despite things compilingrunning fine in eclipse exception in thread main javalangunsatisfiedlinkerror no opencv java245 in javalibrarypath at javalangclassloaderloadlibraryclassloaderjava1860 at javalangruntimeloadlibrary0runtimejava845 at javalangsystemloadlibrarysystemjava1084 at comdrawbridgemainclinitmainjava12 at javalangclassforname0native method at javalangclassfornameclassjava266 at orgeclipsejdtinternaljarinjarloaderjarrsrcloadermainjarrsrcloaderjava56anyone know a simple way of packaging opencv in the jarupdate i have now exhausted everything i can add the library to my build path and not use systemloadlibrary and that works in eclipse but not when packaged in the jar i have tried everything i also checked the type of dynamic library i am trying to load it is macho 64bit x86 64 dynamically linked shared librarywhich seems like it should work fine i have used d64 and d32 to test and get the same result with both,['java'] +526214,sql select where tag value like i am attempting to make a calendar service within that calendar service there are events and events can be tagged with metadata which is searchablei want to be able to search for records where all tags must exists mandatory tags andor where any tags exist optional tagsi have managed to create a query where this works when the tag value matches exactly but i cannot work out how to return results where the tag value is like valuehere is my current implementation tables and datacreate table events id int eventtext varchar500create table eventdates id int eventid int startdate datetime enddate datetime archived bitcreate table tags id int description varchar50create table eventtags eventid int tagid int value varchar50insert into events values 1 event name 1insert into events values 2 event name 2insert into eventdates values 1 1 20130101 20130102 0insert into eventdates values 2 1 20130107 20130108 0insert into eventdates values 3 2 20130102 20130103 0insert into tags values 1 tag name 1insert into tags values 2 tag name 2insert into eventtags values 1 1 value 1insert into eventtags values 1 1 value 2insert into eventtags values 1 2 value 1insert into eventtags values 1 2 value 2insert into eventtags values 2 1 value 1querydeclare mandatorytagxml xmldeclare optionaltagxml xmldeclare startdate datetimedeclare enddate datetimedeclare searchtypeid smallintset startdate 20130101set enddate 20130131set searchtypeid 1 tags that it must match all ofset mandatorytagxml tags tag descriptiontag name 1description valuevalue 1value tag tags tags that it can match one or more ofset optionaltagxml tags tag descriptiontag name 2description valuevalue 2value tag tags declare mandatoryidtable table eventid bigint eventdateid bigint declare optionalidtable table eventid bigint eventdateid bigintifmandatorytagxml is not nullbegin select ids with matching mandatory tags with mandatorytags as select tagvaluevaluevalue1 nvarchar100 as value tagvaluevaluedescription1 nvarchar100 as description from mandatorytagxmlnodestagstag as ttagvalue insert into mandatoryidtable records where all tags match exactly select eid eventid edid eventdateid from dboevents e inner join dboeventdates ed on edeventid eid where edstartdate startdate and edenddate enddate and edarchived 0 and not exists select tid cvalue from mandatorytags c join tags t on cdescription tdescription except select ttagid tvalue from eventtags t where teventid eid endelse select all records begin insert into mandatoryidtable records where all tags match exactly select eid eventid edid eventdateid from dboevents e inner join dboeventdates ed on edeventid eid where edstartdate startdate and edenddate enddate and edarchived 0end with optionaltags as select tagvaluevaluevalue1 nvarchar100 as value tagvaluevaluedescription1 nvarchar100 as description from optionaltagxmlnodestagstag as ttagvalue insert into optionalidtable records any tags match exactly select eid eventid edid eventdateid from dboevents e inner join dboeventdates ed on edeventid eid where edstartdate startdate and edenddate enddate and edarchived 0 and exists select tid cvalue from optionaltags c join tags t on cdescription tdescription intersect select ttagid tvalue from eventtags t where teventid eid determine if we need to factor in optional tags in result setif optionaltagxml is not nullbegin select results that exist in both optional and mandatory tables select thistinct m from mandatoryidtable m inner join optionalidtable o on oeventid meventid and oeventdateid meventdateidendelsebegin select results that exist in mandatory table select thistinct m from mandatoryidtable mendi have created an sqlfiddle demo for itmy idea is to use searchtypeid to switch between exact match searching and like match searchingnote i am not a dba so there may be better ways to do this i am open to suggestionscan anyone offer suggestions as to how to get like matches on tag valuesmany thanks,['sql'] +526238,scale out signalr without rethis for a highmessaging traffic web app in this video on channel9mmsdncom about signalr the lecturer does not recommend using rethis for applications that needs to deliver a very high amount of concurrent messages he suggested other three theoratical alternatives but without any implementation guide i want to how can i scale out signalr on commudity machines on amazon web services andor whether there is already a ready open source solution availablefrom aspnetusing a backplane the maximum message throughput is lower than it is when clients talk directly to a single server node that is because the backplane forwards every message to every node so the backplane can become a bottleneckthe lecturer explained in his lecture that rethis is can be the bottleneck i am aware of the windows serve service bus on windows azure but i intend to develop my project for aws thanks,['asp.net'] +526260,fixed positioningzindex issue in mobile safari so the site in question the main content below scrolls up over the top of the countdown and under the navigation which are both fixed elements this works fine on desktop but on mobile safari the content scrolls behind the countdown as the user moves up but once touch is released it pops in frontjust wondering whether this is a bug or it is something that can be fixedheres the cssheader position fixed width 100 top 0px zindex 10 content width 100 position relative top 650px zindex 7 banner position fixed width 100 position fixed background url norepeat center bottom f paddingtop 185px zindex 1 defaultcountdown maxwidth 70 height auto and html main structurediv idheader div idnav ul lia classactive hrefindexphpstartali lia hrefultrasoundimagesphpultrasound picsali lia hrefpinkorbluephppink or blueali ul divdivdiv idbanner div iddefaultcountdowndivdivdiv idcontentdiv,"['html', 'css']" +526277,android native browser duplicating html5 canvas fine in chrome this is a weird issue that i am only experiencing on a native browser on samsung galaxy tab 2 and galaxy s2 in the native browser this has also been tested on other android phones and tablets such as the nexus 7 galaxy s4 but their native browser is chrome so it appears fine this issue is also not present on any ios browsers windows desktop browsers or mac desktop browsersit is almost asif the webpage is loaded twice ontop of itself as there is a duplicate canvas element that updates as the main canvas doeshere it appears asthough it only happens when rotated in landscape mode but i beleive that in portrait mode the canvas are perfectly aligned over the topwhat is even weirder the menu button that you see is a toggle button tap to open menu tap to close menu on this device when you tap it it opens and closes instantly the same happens for the mute button togglei am completely at a lossi have done some javascript debugging throwing in a few alerts here and there and the initialisation functions that create references to the canvas and so on are only called oncei have read and heard about hardware acceleration causing issues but solutions i have potentially found are only relative to building native apps not html5 canvas webpagesany insight on this could be would be greatthanks in advanceediti also put in this test alertdocumentgetelementsbytagnamecanvaslength to see if there was 2 canvas in the dom but it returns 1,"['javascript', 'android']" +526284,access multiple elements of list knowing their index i need to choose some elements from the given list knowing their index let say i would like to create a new list which contains element with index 1 2 5 from given list 2 1 5 3 8 5 6 what i did isa 2153856b 125c ai for i in bis there any better way to do it something like c ab,['python'] +526313,why is drawing on jframe so much slower than on a jpanel my question is why is the same swingcustompainting routine nearly 16 times faster when drawing on a jpanel compared to directly on the jframe is it just doublebuffering it cannot be surelybackground i had a problem with the custompainting not being refreshed when the jframe was unobscured especially having been only partially obscured after searching so i decided to bitethebullet and figureout how to wire a subclass of jpanel into a bluddynetbeansformdesigner formfor anyone in the same situation in netbeans you need to create a new standard class not a jpanel form that just happens to extend jpanel and manually code everything therein no gui designer like the goodoledays sigh then you add a standard jpanel to your form set it is size then rightclick and select customize code and select custom creation in the combobox where it creates a new javaxswingjpanel substitute your subclass thereofso this allowed me to do it properly and paint on a component instead of directly on the form also the panelskeylistener a much neater solution than hijacking the frames keyeventthispatcheranyway now the profiler says that exactly the same custompaintingcode executes nearly 16 times faster in jpanels paintcomponent as apposed jframes paint and i was wondering if anybody could please explain whythank you in advance keithedit this question is based on misinterpreted metrics the profiler does not includereport the jpanels paintcomponent method in the awteventqueue thread whereas my baseline profile does include jframes paint i should have looked more carefully before asking a silly question my bad,['java'] +526325,the correct way to initialize a dynamic pointer to a multidimensional array i have been having bad luck with with dynamic pointers when i range them to 2 dimensions and higher for example i want a pointer to a 2d array i know thatint a34int p4 ais completely legit even if i do not completely understand why taking into consideration thatint p new int4works i imagined thatint p new int57would also work but it is not this code states the errorerror a value of type 7 cannot be used to initialize an entity of type int by seeing this the new part becomes a pointer to an array of 7 integers i madeint p4 new int74and this does work but it is not what i want to accomplish by doing it like that i am limited to at least using a constant value for any subsequent dimension but i want it to be fully defined at run time and therefore dynamichow could i go and make this multidimensional pointer work,['c++'] +526330,center twitter bootstrap 3 glyphicons in buttons i am now using twitter bootstrap 3 rc2 as well as twitter bootstrap which has moved into a separate repository i have noticed if used in a button with text the icon is not centered very wellthe icon and the text have the same bottom line but i believe for a good looking button the icon should be centered based on the text should not it any idea how to achieve this,['css'] +526333,c char to const char conversion in c why is it not possible to pass a char as an argument to a function that accepts const char when a conversion from char to const char is possible as shown belowvoid f1const char avoid f2const char bint mainint argc char const argv char c f1c does not work f2c works return 0the compiler output is testcpp in function int mainint const chartestcpp1510 error invalid conversion from char to const char fpermissivetestcpp16 error initializing argument 1 of void f1const char fpermissive,['c++'] +526378,why do not unordered containers provide an interface for defining minimum load factor i was trying to understand why hash table unordered containers such as unordered map or unordered set do not provide an interface for querying or setting minimum load factorsay c is a unordered set i can usecmax load factorfor querying and cmax load factorvalfor settingwhy does not c11 provide an interface for querying min load factor are there implementation details which would explain also c stl by josuttis mentions thatthe minimum load factor which is used to force rehashing when the number of elements in the container shrinks cannot be influenced,['c++'] +526397,hibernate criteria thistinct entities and then limit i have a criteria that returns all data the application requires basicallycriteria criteria sessioncreatecriteriaclientclasscriteriacreatealiasaddress addresscriteriasetresulttransformercriteriathistinct root entitycriteriasetfirstresultinitcriteriasetmaxresultsmaxlistclient clients criterialistthe problem is that the relation client address is bidirectional on client has one address and one address may belong to more than one clienti want to retrieve single client objects based on their pk of course some number of clients as they are thisplayed in a tablebecause the setfirstresultsetmaxresults are executed first i am getting duplicated clients within the already applied limits after application level as not group by was used hibernate gets rids of the duplicate clients so i end up with less clients that the maximum specified in the setmaxresultscannot group by projection group as it would not return all columns required in clientaddresses only the group the query is grouping byto sum up my table has 100 results per page but after thiscarding duplicates i have 98 results instead of 100 that is because the limit limit 0100 is applied before hibernate groups when it should be performed after,['java'] +526447,why cannot i see the keys of an error object i am mystified by the fact that when i create a new error object i can see its message or name but i cannot see a list of its keys by using the standard ways why is that err new erroran errorerror an error errmessagean error errnameerror objectkeyserr jsonstringifyerr,['javascript'] +526498,are there any official ways to write an immediately invoked function expression something like thisvar myobject new myclass x selecty do stuff if 2 2 5 return i like cookies else if 2 2 3 return i like muffins more conditions else return i am a bitter old man i realize select is not intended to be used this way but yeah what are some other ways to do the same thing,['c#'] +526518,systemtimerstimer elapsed event executing after timerstop is called background i have a timer that i am using to keep track of how long it has been since the serialport datareceived event has been fired i am creating my own solution to this instead of using the built in timeout event because i am getting a continuous stream of data instead of sending a query and getting one response the problemin the datareceived handler i have a statement to stop the timer so that is does not elapse the problem is that a lot of the time it still executes the elapsed handler afterword i have read that is is possible to use synchronizingobject to solve this problem but i am not sure how to accomplish thathere is my code i tried to cut out everything that i did not think was relevant private systemtimerstimer timeout private systemtimerstimer updatetimer public void start thread1 new thread record thread1start public void requeststop thisstop true thiswaiteventtestset private void record timeout new systemtimerstimer500 5 sec updatetimer new systemtimerstimer500 5 sec timeoutelapsed timeout elapsed updatetimerelapsed updatetimer elapsed updatetimerautoreset true comportopen comportthiscardinbuffer comportwritecommand continuousmode r stopwatchreset stopwatchstart recordingstarttrigger fire recording started event timeoutstart updatetimerstart thiswaithandletestwaitone wait for test to end timeoutstop updatetimerstop comportwritecommand commandmode environmentnewline comportthiscardinbuffer comportclose recordingstoptriggerstatus fire recording stopped event stopwatchstop events handlers private void comdatareceived handlerobject sender serialdatareceivedeventargs e double force 10 string temp 10 timeoutsynchronizingobjectinvokenew action timeoutstop new object sender e timeoutstop i removed my action code here keep things simple timeoutstart private void timeout elapsedobject sender systemtimerselapsedeventargs e timeoutstop updatetimerstop fire delegate that gui will be listening to to update graph if eventcomtimeout null thisstop false if eventcomtimeoutthis new eventargscomtimeoutcomportportname read retry true comportwritecommand continuousmode r updatetimerstart timeoutstart else thisstop true retry false thiswaiteventtestset status eventargsstoppedstatusfailed void updatetimer elapsedobject sender systemtimerselapsedeventargs e fire delegate that gui will be listening to to update graph listreading temp new listreadingreportreadings force eventnewdatathis new eventargsnewdatatemp,"['c#', '.net']" +526522,rearrange a list of points to reach the shortest thistance between them i have a list of 2d points for example11 22 13 45 21the thistance between these points is known using mathhypot for example i want to sort the list so that there is a minimum thistance between them i am ok with any possible solution order as long as the points are in the shortest orderwhat is the most pythonic way to achieve thisi was considering working out the thistance between any item and any other item and choosing the smallest each time but this would be a slow algorithm on the lists i am working on 10 items would not be unusual,['python'] +526556,thisable css styles in google maps 314 infowindow in google maps version 314 there are some new css rules added for the custom infowindow i use the infobox plugin and now many of my elements styles are overwrittenfor examplegmstyle divgmstyle spangmstyle labelgmstyle a fontfamily robotoarialsansserif fontsize11px fontweight400gmstyle divgmstyle spangmstyle label textdecorationnonegmstyle agmstyle label thisplayinlinegmstyle div thisplayblockgmstyle img border 0 padding 0 margin 0is there any way to change that except that i have to overwrite this google styles via importanteditthe font roboto will be also loaded if you care about performance then that is not really greatedit2ok important is not necessary overwriting the google styles is also possible with increasing the specificity of the css selectors but this does not change that i have to overwrite all google styles and the roboto font will loaded too,"['javascript', 'css']" +526582,oswalk iterates in what order i am concerned about the order of files and directories given by oswalk if i have these directories 1 10 11 12 2 20 21 22 3 30 31 32 what is the order of the output listis it ordered by numeric values1 2 3 10 20 30 11 21 31 12 22 32or ordered by ascii values like what is given by ls1 10 11 12 2 20 21 22 3 30 31 32and how can i get a specific order,['python'] +526607,how does google autobackup my photos on ios in the background how is the google apps photo autobackup feature implemented given ios 6x constraints it seems to able to upload my camera roll photos even when i am no longer running the google app the ios developer docssay for short processes you need to perform a single finitelength task and for longrunning processes photo upload does not seem to be one of the approved uses,['ios'] +526609,java package orgapachecordova does not exist when compliling cordova in android studio new to android dev world and am just getting started here well trying to anyway i have downloaded cordova 28 might need to upgrade this java jdk 17 and the new android studio the andriod sdk installed all the 4x packages with that and installed ant 192 everything seems to be working as far as that goes problem is when i can create a cordova project from the command line load it up in studio using the import feature not tweaking anything just accepting as i read to do so on some blog out there and everything seems to load ok and the project is there in studio until i try to make it at this point i get and error java package orgapachecordova does not exist this is followed by several other errors which i feel may be related i am not nor am i trying to do anything fancy here just get the stock up and runninganybody know what i am missing do i need to copy a file somewhere or compile something extra or am i using the wrong version of something thanks,"['java', 'android']" +526681,is it possible to define my own errors in eclipse is there a way to define my own compile errors for eclipse i want to throw compile errors if certain objects are not instantiatedto give you exactly what i want to doi have an assets class that holds null variables for all resources images sounds etc and a loadingscreen class that initializes all of these resource objects if i add a resource to the assets class but not to the loadingscreen class it will mess up the whole application i want to see an error in eclipse if the variables in the assets class are not also initialized in loadingscreenis this possible,['java'] +526697,horizontal data update is not working on scroll i have a big array and i need to render it into a table instead of rendering all items i am rendering only few items horizontally and vertically then on scroll based on mouse scroll whether happened vertical horizontal updating table values but i have two problems in this here are problems with my code when scrolling horizontally data is not updatedscrolling horizontally is flickering the screen alsohorizontal elements are not aligned properlyhere is the jsbin link here is the js code i know code is not clean but i will clean it latervar matrix function function matrixdata holder hidescrollbar config var header h configheader 150px var data h configheader 90px data function fake data will be removed later data new array50 for var i 0 l datalength i l i var dummy mathrandomtostring36substring5 var dum for var j 0 j 26 j dumpushdummy i datai dum hidescrollbar hidescrollbar false var heightforcer holderappendchilddocumentcreateelementdiv heightforcerid heightforcer var view null get the height of a single item var dimensions function generate a fake item and calculate dimensions of our targets var div documentcreateelementdiv divstyleheight auto divinnerhtml div classrowheaderfakedivdiv classrowdatafakediv holderappendchilddiv var output row divfirstchildoffsetheight header divfirstchildoffsetwidth data divlastchildoffsetwidth holderremovechilddiv return output function refreshwindow remove old view if view null viewinnerhtml else create new view view holderappendchilddocumentcreateelementdiv var firstitem mathfloorholderscrolltop dimensionsrow var lastitem firstitem mathceilholderoffsetheight dimensionsrow 1 if lastitem 1 datalength lastitem datalength 1 var hfirstitem mathfloorholderscroleft dimensionsdata var hlastitem hfirstitem mathceilholderoffsetwidth dimensionsdata 1 if hlastitem 1 datafirstitemlength hlastitem datafirstitemlength 1 position view in users face viewid view viewstyletop firstitem dimensionsrow px viewstyleleft hfirstitem dimensionsdata px var div add the items for var index firstitem index lastitem index div documentcreateelementdiv var curdata dataindexslicehfirstitem hlastitem divinnerhtml div classrowheader curdatajoindivdiv classrowdata div divclassname listitem divstyleheight dimensionsrow px viewappendchilddiv consolelogviewing items firstitem to lastitem heightforcerstyleheight datalength dimensionsrow px heightforcerstylewidth data0length dimensionsdata px if hidescrollbar work around for nonchrome browsers hides the scrollbar holderstylewidth holderoffsetwidth 2 viewoffsetwidth px refreshwindow function delayinghandler wait for the scroll to finish settimeoutrefreshwindow 10 refreshwindow if holderaddeventlistener holderaddeventlistenerscroll delayinghandler false else holderattacheventonscroll delayinghandlerreturn matrix new matrixundefined documentgetelementbyidlistholder false header 150px data 90px headercolumns 2please help me on this,['javascript'] +526709,linker errors when trying to install new google analytics 30 beta i believe just today google released a new update to their ios analytics frame work version 30 when i follow the instructions and try to run the code i getundefined symbols for architecture armv7 inflate referenced from l002 in libgoogleanalyticsservicesansdatazlibo deflate referenced from l001 in libgoogleanalyticsservicesansdatazlibo inflateinit2 referenced from l002 in libgoogleanalyticsservicesansdatazlibo deflateend referenced from l001 in libgoogleanalyticsservicesansdatazlibo objc class asidentifiermanager referenced from objcclassref in libgoogleanalyticsservicesatagadvertiserido objcclassref in libgoogleanalyticsservicesatagadvertisingtrackingenabledmacroo objcclassref in libgoogleanalyticsservicesatagmobileadwordsuniqueidmacroo inflateend referenced from l002 in libgoogleanalyticsservicesansdatazlibo scnetworkreachabilitycreatewithname referenced from l027 in libgoogleanalyticsservicesagaireachabilitycheckero l002 in libgoogleanalyticsservicesatagnetreachabilityo scnetworkreachabilitysetcallback referenced from l027 in libgoogleanalyticsservicesagaireachabilitycheckero l002 in libgoogleanalyticsservicesatagnetreachabilityo l003 in libgoogleanalyticsservicesatagnetreachabilityo deflateinit2 referenced from l001 in libgoogleanalyticsservicesansdatazlibo scnetworkreachabilityschedulewithrunloop referenced from l027 in libgoogleanalyticsservicesagaireachabilitycheckero l002 in libgoogleanalyticsservicesatagnetreachabilityo scnetworkreachabilityunschedulefromrunloop referenced from l027 in libgoogleanalyticsservicesagaireachabilitycheckero l003 in libgoogleanalyticsservicesatagnetreachabilityo ld symbols not found for architecture armv7 clang error linker command failed with exit code 1 use v to see invocationpossible they forgot to include a lib i need to add some other aspects of the instructions they forgot to change as well otherwise have followed their instructions to a tee and still not getting the needed results,['ios'] +526735,customizing devise with strong parameters i am using rails 400 and devise 302 and trying to configure devise with strong parameters following this instruction within the devise readmei wrote code like this in the application controllerrbclass applicationcontroller actioncontrollerbase before filter configure permitted parameters if devise controller protected def configure permitted parameters devise parameter sanitizerforsign up nick endendthen i visited httplocalhost30userssign up i got a nomethoderror in deviseregistrationscontrollernew which saysundefined method for actioncontrollerparametersand points to the exact line where i wrote devise parameter sanitizerforsign up nickis there anything i did wrong thanks for your help,['ruby-on-rails'] +526775,stringsplit how do i treat consecutive delimiters as one for two sample strings in variable temp such as these1 ryvg192 ryvg19i want to do the followingstring splitrating tempsplitbut i want the result to be the same which issplitrating0 splitrating1 ryvgsplitrating2 1splitrating3 9this means that i need to treat that double as one delimiter is there any way to do this while still using stringsplit,['java'] +526776,what happens if i use extern c with a c toolchain my question is mainly about the fact that a c toolchain understands both c and c so if i feed some code with an extern c to a c toolchain i assume it can understand what to do with that but what if i feed code with extern c to a c toolchain what is the expected behaviour,"['c++', 'c']" +526818,change rails version used by rvm here are my local gems gem list local gems actionmailer 400 3214actionpack 400 3214activemodel 400 3214activerecord 400 3214activerecorddeprecated finders 103activeresource 3214activesupport 400 3214arel 400 302atomic 13builder 314 304bundler 135bundlerunload 101erubis 270hike 123i18n 065journey 104json 180mail 254mimetypes 124minitest 475multi json 179polyglot 033rack 152 145rackcache 12rackssl 133racktest 062rails 3214railties 400 3214rake 1010rdoc 3122rubygemsbundler 122rubygemsupdate 207rvm 138sprockets 2100 2sprocketsrails 200thor 0181thread safe 012tilt 141treetop 1415tzinfo 0337but when i type rails v i get this rails vrails 400 which railsuserspoloniumrvmrubiesruby200p247binrailshow can i specify rvm to use rails version 3214 thanks in advance,"['ruby-on-rails', 'ruby']" +526823,how do i implement the oncreateoptionsmenu method in a sherlockfragment i am really struggling to set up the oncreateoptionsmenu method in my sherlock fragment as i usually do not use sherlock fragments that much can someone tell what i have to import and how the implementation works some code that i havepublic class myfragment extends sherlockfragment overridepublic view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate view rootview inflaterinflaterlayoutcustom list container false some code return rootviewoverridepublic boolean oncreateoptionsmenumenu menu,['android'] +526824,python hiding raw input so this is my code and i want to hide my password but i dont know how i have looked around and none of them seem to fit in my coding this is the current coding i mean i have seen show and also getpass but i dont know how to place them into this coding im using python 273 and im coding on a raspberry pians truewhile ans print 1 shutdown 2 items ansraw input please enter a number if ans 1 exit elif ans 2 paraw input please enter password if pa zombiekiller print 1 pi password 2 shutdown peraw input please enter a number if pe 1 print pis password is adminofpi import time timesleep1 exit elif pe 2 exit else print you have entered an inccoredt option terminating programm import time timesleep1 exit else print you have entered an inccorect password terminating programm import time timesleep1 exit,['python'] +526857,jquery getjson syntax error on a valid json i have the following valid json data titletitle1 value12234 titletitle2 valuesome text titletitle3 value12qwerty234 titletitle4 value1235 i am using jquery to load it with the next codedocumentreadyfunction getjsonjsonjs functionresult eachresult functioni obj formappendlabel foriobjtitlelabel formappendinput idi valueobjvalue typetextbr my problem is that i am getting a syntax error in firefox i load jsonjson as a local filehere is a screenshotnote that form has been generated successfullyedit here is another screenshot from chrome when running python simplehttpserver,['jquery'] +526864,why will stdsort crash if the comparison function is not as operator the following program is compiled with vc 2012include algorithmstruct a a a bool operator const a other const return a othera int aint main a coll8 stdsortcoll0 coll8 crashif i change return a othera to return a othera then the program runs as expected with no exceptionwhy,['c++'] +526918,android limit number of fragments in backstack currently i have one activity and fragments are being added to it search song details settings etc i implemented side based menu navigation so now as a side effect tehres no limit to how many fragments get added to the backstack is there any way i can limit the number of fragments or remove older entries each song details fragment for instance has a recommended song list and through that you can go to another song details fragment it is easily possible to have 30 fragments in the backstack which if you have ddms open you can see the heap size slowly but surely increasingedit one thing i did try to do is if a user clicked one of the side menu options if that fragment is already in the backstack try to go back to that fragment instead of instantiating a new one but of course if a user is on a song details page then he would expect pressing back would take him to that fragment so that would not workedit 2 this is my addfragment method along with phils suggestionpublic void addfragmentfragment fragment fragmentmanager fm getsupportfragmentmanager iffmgetbackstackentrycount 2 fmpopbackstack fmbegintransaction replaceridfragment container fragmentaddtobackstack commiti just tried it and assuming my fragment history is abcd going back from d goes baexiti just went 8 levels deep to test abcdefgh and going back from h same thing happened hbaexitall fragments are getting added through that method above what i would like to see is hgfexit,['android'] +526920,cannot install rmagick gem on ubuntu 1304 when i try to install rmagic withgem install rmagicit gives errorbuilding native extensions this could take a whileerror error installing rmagick error failed to build gem native extension homebiskerbenvversions200p247binruby extconfrbchecking for ruby version 185 yeschecking for gcc yeschecking for magickconfig yeschecking for imagemagick version 649 yeschecking for hdri thisabled version of imagemagick yeschecking for stdinth yeschecking for systypesh yeschecking for wandmagickwandh nocannot install rmagick 2132 cannot find magickwandh extconfrb failed could not create makefile due to some reason probably lack of necessarylibraries andor headers check the mkmflog file for more details you mayneed configuration optionsprovided configuration options withoptdir withoutoptdir withoptinclude withoutoptincludeoptdirinclude withoptlib withoutoptliboptdirlib withmakeprog withoutmakeprog srcdir curdir rubyhomebiskerbenvversions200p247binrubygem files will remain installed in homebiskerbenvversions200p247librubygems200gemsrmagick2132 for inspectionresults logged to homebiskerbenvversions200p247librubygems200gemsrmagick2132extrmagickgem makeouti tried to search for problem and found that i am missing libmagickwanddev i tried to install it withsudo aptget install libmagickwanddevbut it raises errorthe following packages have unmet dependencies libmagickwanddev depends libmagickcoredev 8677105ubuntu2 but it is not going to be installede unable to correct problems you have held broken packagesif i try to install it withsudo aptget install libmagickcoredevit gives errorthe following packages have unmet dependencies libmagickcoredev depends librsvg2dev but it is not going to be installede unable to correct problems you have held broken packagesif i try to install it withsudo aptget install librsvg2devit gives errorthe following packages have unmet dependencies librsvg2dev depends libglib20dev 2240 but it is not going to be installed depends libgdkpixbuf20dev 22352 but it is not going to be installed depends libcairo2dev 120 but it is not going to be installede unable to correct problems you have held broken packagesif i try to install libglib20dev withsudo aptget install libglib20devit gives errorthe following packages have unmet dependencies libglib20dev depends libglib200 23601ubuntu1 but 23601ubuntu2 is to be installed depends libglib20bin 23601ubuntu1e unable to correct problems you have held broken packagesif i install libglib200 withsudo aptget install libglib200it giveslibglib200 is already the newest version0 upgraded 0 newly installed 0 to remove and 0 not upgradedif i install libglib20bin withsudo aptget install libglib20binit givesreading package lists donebuilding dependency tree reading state information donelibglib20bin is already the newest version0 upgraded 0 newly installed 0 to remove and 0 not upgradedthose 2 libs are installed but issuing againsudo aptget install libglib20devit gives same errorthe following packages have unmet dependencies libglib20dev depends libglib200 23601ubuntu1 but 23601ubuntu2 is to be installed depends libglib20bin 23601ubuntu1e unable to correct problems you have held broken packageswhat could be problem herei am using ubuntu 1304 rbenv ruby 200 if that matters,"['ruby-on-rails', 'ruby']" +526921,typescript error ts1005 expected i am trying compile this typescript fileimport http modulehttpimport express moduleexpresswith these parameterscnodejstsccmd sourcemap cheesets module commonjscusernodeexpressprojectcheesets521 error ts1005 expectedcusernodeexpressprojectcheesets624 error ts1005 expectedwhat am i doing wrong even with this i am getting the same errors errorsmodule http module express import http modulehttpimport express moduleexpressusing typescript version 091,['javascript'] +526955,aws elastic beanstalk error importerror no module named flaskextsqlalchemy i deployed my flask application into aws beanstalk and ran into an import errorimporterror no module named flaskextsqlalchemyin my applicationpy file i have this statement from flaskextsqlalchemy import sqlalchemyand it runs fine on my machine but does not work in aws elastic beanstalk anyone ran into a similar issue,['python'] +526962,why can template but not template be defined outside of a namespace block here is some code which does not compilenamespace ns class foo template typename t int bar t template typename tint ns foo bar t this is ok return 0template int ns foo bar int int this is an error return 1the error is specialisation of atemplate int nsfoobarta in different namespace fpermissive from definition of atemplate int nsfoobarthere is a version which does compilenamespace ns class foo template typename t int bar t template typename tint ns foo bar t return 0namespace ns template int foo bar int int return 1 why does the second definition have to be in a namespace ns block when the first one is quite happily defined with a qualified name is it just an oversight in the language design or is there a reason for this,['c++'] +527021,click table rows to select checkbox using jquery as i did not find any question asked before on how to toggle checkbox on click of a table row so i would like to share my approach to this,['jquery'] +527028,html5 resize image and keep exif in resized image how can i resize an image using an html5 canvas element and keep the exif information from the original image i can extract exif info from from original image but i do not know how to copy it to the resized imagethis is how i retrieve the resized image data to send to the serverside codecanvastodataurlimagejpeg 07for exif retrieval i am using the exifjs library,['javascript'] +527060,how to declare a variable as thread local portably c11 introduces the thread local storage class specifier that can be used in combination with the static and extern storage class specifiers to declare a variable as thread local the gnu c compiler suite implements a storage class specifier thread with the same same semanticsunfortunately i did not find any compiler i tried gcc clang and sun studio that actually implements the thread local keywords i currently use the following construct to declare a keyword thread local gcc does not know thread local from c11 yet ifdef gnuc define thread local threadelif stdc version 2012l define thread local thread localelse error do not know how to define thread localendifi know that this probably does not work with msvc and other compilers can anybody suggest me a better method to declare thread local in a way that it works in as many compilers as possibleeditchristoph suggested that microsoft visual c allows declspecthread this is the updated macro definition gcc does not know thread local from c11 yet ifdef gnuc define thread local threadelif stdc version 2012l define thread local thread localelif defined msc ver define thread local declspecthreadelse error cannot define thread localendif,['c'] +527066,first time user guidethrough android library i want to be able to guide the user through a stepbystep process when they first signup for the appi have seen in some of the apps that they have a grayedout background with arrows pointing here and there that has 1 2 3 next to it the user can then click on 1 and type something then 2 and type something does anyone know of a library that does thisi have been struggling to find the right keyword for the searchi have a rather infographicbased page and would like to familiarise the user of what is whatif there is no libraries are there any suggestions of which i can go about,['android'] +527088,switching to actionbarcompat but have theme related build errors i am trying to integrate actionbarcompat to one of my projects i use the gradle build systemi have added the dependency asdependencies compile comandroidsupportappcompatv7180i do not use a custom style i have the theme set in my androidmanifestxml as application androidicondrawableicon androidlabelstringapp name androidthemestylethemeappcompat the thing is that this is in an android library project it was working pretty good with actionbarsherlock but now i get the following errorslibraryprojectbuildresallreleasevaluesvaluesxml764 error error no resource found that matches the given name attr dropdownlistpreferreditemheightlibraryprojectbuildresallreleasevaluesvaluesxml768 error error no resource found that matches the given name attr popupmenustylelibraryprojectbuildresallreleasevaluesvaluesxml813 error error no resource found that matches the given name attr dropdownlistpreferreditemheightlibraryprojectbuildresallreleasevaluesvaluesxml817 error error no resource found that matches the given name attr popupmenustylelibraryprojectbuildresallreleasevaluesvaluesxml848 error error no resource found that matches the given name attr dropdownlistpreferreditemheightlibraryprojectbuildresallreleasevaluesvaluesxml852 error error no resource found that matches the given name attr popupmenustylelibraryprojectbuildresallreleasevaluesvaluesxml912 error error no resource found that matches the given name attr actiondropdownstylelibraryprojectbuildresallreleasevaluesvaluesxml925 error error no resource found that matches the given name attr listchoicebackgroundindicatorlibraryprojectbuildresallreleasevaluesvaluesxml923 error error no resource found that matches the given name attr panelmenulistthemelibraryprojectbuildresallreleasevaluesvaluesxml922 error error no resource found that matches the given name attr panelmenulistwidthlibraryprojectbuildresallreleasevaluesvaluesxml969 error error no resource found that matches the given name attr actiondropdownstylelibraryprojectbuildresallreleasevaluesvaluesxml975 error error no resource found that matches the given name attr listchoicebackgroundindicatorlibraryprojectbuildresallreleasevaluesvaluesxml973 error error no resource found that matches the given name attr panelmenulistthemelibraryprojectbuildresallreleasevaluesvaluesxml972 error error no resource found that matches the given name attr panelmenulistwidthlibraryprojectbuildresallreleasevaluesvaluesxml998 error error no resource found that matches the given name attr actiondropdownstylelibraryprojectbuildresallreleasevaluesvaluesxml1002 error error no resource found that matches the given name attr listchoicebackgroundindicatorwhat can be the problem can anybody suggest a solution,['android'] +527125,are all the stdtuple constructors necessary stdtuple contains amongst others the following constructorsexplicit tuple const types args template class utypes explicit tuple utypes args both have equivalent descriptions in that they initialise each of the elements with the corresponding value in args the only difference is that in the second the parameters are forwardedfrom what i have understood about rvalue references i do not see why the first version is required since the same parameters could be passed into the second version the references would be forwarded and noone would any the wiser especially as there is no mention of move semanticscan anyone explain what it is that makes both constructors necessary,['c++'] +527216,match parent property for children in a relativelayout in short is it possible to tell a child in a relativelayout to always match the height of that relativelayout regardless of how other children in that same relativelayout behave in short that is it details belowwhat i am trying to achieve is a listview row with at least three views and one of those views would be kind of a stripe at the right side of the list entry the red view below the problem i am having is that there is a textview at the left side and depeding on how much text i have the stripe would not fill the whole layout this is very clearly explained by images belowlistview item layoutrelativelayout xmlnsandroid androidlayout widthwrap content androidlayout heightwrap contentview androidididbottom line androidlayout widthmatch parent androidlayout height5dp androidlayout alignparentbottomtrue androidbackgroundfc0 why match parent does not work in view below view androidididstripe androidlayout width80dp androidlayout heightwrap content androidminheight50dp androidlayout alignparentrighttrue androidlayout alignparenttoptrue androidlayout alignparentbottomtrue androidbackgroundf00 textview androidididtext androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentlefttrue androidlayout toleftofidstripe androidtextthis is a very long line meant to completely break the match parent property of the box at right styleandroidtextappearancelargerelativelayoutresultsetting stripe and root height to match parent makes no difference i did itrepeating the question i want the red stripe to always fill the parent vertically you can see stripe is not aligning to the top of roota note the above example is the simplest selfcontained example i can think of it is just a listactivity with an anonymous arrayadapter populated by a static string array the relevant code in oncreate is at most 8 lines so no worries there it is really the layout besides i have this working with nested linearlayouts already but i am trying to reduce the depth of my layout structure a bit if possible linearlayout works fine as expected,['android'] +527300,jackson deserialize jsonidentityreference alwaysasid true following up on this question question herejsonidentityreferencealwaysasid true and jsonidentityinfogenerator objectidgeneratorspropertygeneratorclass works great from the serialization end but not so well when it comes time to deserialize since it cannot resolve the object id referenceis there a way to get this to deserialize writing a custom deserializer seems like overkill,['java'] +527324,how to serialize uiimage to json i am using imagedata uiimagepngrepresentationimgvwimage and while posting dic setobjectimagedata forkeyimage after nsdata data nsjsonserialization datawithjsonobjectdic optionsnsjsonwritingprettyprinted errortheerrornow app is crashing terminating app due to uncaught exception nsinvalidargumentexception reason invalid type in json write nsconcretemutabledata,['ios'] +527325,how to use typeforwardedto in portable class libraries i am trying to build a portable class library which uses implementations from the platform when available for example lazyt is available on net 45 windows store apps windows phone 8 but it is not available on windows phone 7 silverlight 4 when my pcl is loaded on one of the platforms that has a lazyt implementation i want to use the platforms implementation when it is not available on the platform i want to use my own implementation it seems to be possible because the microsoft bcl is doing it but i have not figured out how to implement iti have read that by using the typeforwardedtoattribute you can redirect the pcl to use the implementation from the platform i am not quite sure how to configure my visual studio projects to achieve this result if corelib is my library and shimlib contains my implementation of lazyt where do i add the typeforwardedtoattribute the attribute requires an actual type reference typeofsystemlazy which does not work when windows phone 7 is targeted in the pcl if i remove windows phone 7 then i cannot add a reference from corelib to shimlib because shimlib does not support all the platforms that corelib does how do i handle this yes i know lazyt is super easy to implement but it is just an example and my actual situation applies to many more classes that are less trivial to implement,"['c#', '.net']" +527378,how can you test how many instructions per second your computer can do is there a quickeasy way to do this for at least a rough estimate i am benchmarking algorithms and i thought it would be cool to know the absolute speed at which my computer is executing instructions and compare that with my asymptotic analysis,"['c++', 'c']" +527388,chrome how to solve maximum call stack size exceeded errors on mathmaxapply math array i have to find the maximum and minimum value of very huge arrays for this i am usingmathmaxapplymath my arraymathminapplymath my arrayit works good on firefox and ie but on chrome i always get maximum call stack size exceeded errors my current array has 221954 elements and that is not my biggestdoes someone know how to solve this error on chrome how can i optimize the search of max and min valuefor those people who cannot believe try this in the console of chromevar x forvar i0 i30 i xpushmathrandommathmaxapplymath x rangeerror maximum call stack size exceeded,['javascript'] +527465,entity framework complex type multiple instances in one model is there a way to have multiple instances of complex type inside the same model using fluent api model builderpublic class contact public int id get set public string firstname get set public string lastname get set public address personaladdress get set public address businessaddress get set public class address public string street get set public string city get set public string postalcode get set protected override void onmodelcreatingdbmodelbuilder modelbuilder baseonmodelcreatingmodelbuilder modelbuilderconfigurationsaddnew contactconfiguration modelbuilderconfigurationsaddnew addressconfigurationpublic class addressconfiguration complextypeconfigurationaddress public addressconfiguration props thispropertyt tstreet isoptional hascolumnnameaddrestreet hasmaxlength1024 thispropertyt tpostalcode isoptional hascolumnnameaddresspostalcode hasmaxlength64 thispropertyt tcity isoptional hascolumnnameaddresscity hasmaxlength512 edit found the solutionif multiple complex type class instances are used in same cf model configuration of these classes is set at cf model level like thispublic class contactconfiguration entitytypeconfigurationcontact public contactconfiguration props for personaladdress instance of address complex type class thispropertyt tpersonaladdressaddrestreet hascolumnnamepersonaladdrestreet thispropertyt tpersonaladdressaddresspostalcode hascolumnnamepersonaladdresspostalcode thispropertyt tpersonaladdressaddresscity hascolumnnamepersonaladdresscity props for businessaddress instance of address complex type class thispropertyt tbusinessaddressaddrestreet hascolumnnamebusinessaddrestreet thispropertyt tbusinessaddressaddresspostalcode hascolumnnamebusinessaddresspostalcode thispropertyt tbusinessaddressaddresscity hascolumnnamebusinessaddresscity,"['c#', '.net']" +527523,can i store javascript in a local storage object and run it let me explain i am developing a javascript application to help people develop websites i wont explicitly go into what it does just know that it works by superimposing its htmlinline css interface over the website that is being developed and offers a variety of tools such as tracing images and code minifiersi have it stored on a server as a js file all people have to do to access my application is copy and paste a small bit of html onto their page to use it like thisscript srcscriptscript srcwexamplecomapplicationjsdiv classapplicationdivthe html and inline css of the interface is then inserted into the application div using jquerys html functionit all works perfectly apart from one thing the load time as a user develops their site they will be continually refreshing their page and this results them having to wait about 3 seconds very annoying as time goes on for the applications interface to loadof course if the browsers cache is turned on the problem thissappears but if youre developing a site youre going to want to have your cache thisabled it is a conundrumthen i thought to use local storage objects to hold strings of the interface svg graphics and then html these strings into inline css it is an elabourate workaround but only developers would use this tool it is not an end user thing and it works beautifully too but the thing is the browser still needs to download the script inorder to know to access the locally stored images processor speed is not bottlenecking it it is bandwidthso i was thinking storing the script itself in a local storage object and having a tiny initialisation script to run itthe initialisation script would simply retrieve the script from the local stroage object as a string parse it accordingly and then run itto reiterate my question running it is the part i cannot do i can insert the script onto the page via htmlscript but then how do i go about running it,"['javascript', 'jquery']" +527593,how can we secure a thirdparty widget i am building a 3rd party widget we drop a script on a clients page and load some contentthe problem i face is how do i secure my widget as a thrid party widget i know there is no 100 way to secure it but trying to work out a good enough approachi want to make it difficult for a non customer to just rip our script off their competitor site and use it on theirsthe solutions i see is pull validate requesting domain which i know could be spoofed not sure if i can guard against thisi had a look at other widgets like olark and olapic that use unique ids per client in their script but cannot see how helpful that iswhat are the best practices to secure a third party widget,['javascript'] +527621,frameless and transparent window qt5 i am quite new to qt and c and i have encountered a problem that i cannot seem to figure out i am wanting to open a frameless and transparent window when i click a button on the main ui i have got the code working to open a new window when i press a button on the main ui but i cannot seem to get the frameless and transparent part workinghere is the source codes for the small program that i wrote to learn thismaincppinclude learnwindowhinclude qapplicationint mainint argc char argv qapplication aargc argv learnwindow w wshow return aexechere is the learnwindowhifndef learnwindow hdefine learnwindow hinclude qmainwindowinclude transwindowhnamespace ui class learnwindowclass learnwindow public qmainwindow q objectpublic explicit learnwindowqwidget parent 0 learnwindowprivate slots void on pushbutton clickedprivate uilearnwindow ui transwindow wintranspublic slots void opentransendif learnwindow hhere is learnwindowcppinclude learnwindowhinclude ui learnwindowhlearnwindowlearnwindowqwidget parent qmainwindowparent uinew uilearnwindow uisetupuithislearnwindowlearnwindow delete uivoid learnwindowopentrans wintrans new transwindow this wintranssetwindowtitlenewwin wintranssetwindowflagsqtframelesswindowhint qtx11bypasswindowmanagerhint wintranssetattributeqtwa translucentbackgroundtrue wintranssetautofillbackgroundfalse wintranssetstylesheetbackgroundtransparent wintransshowvoid learnwindowon pushbutton clicked opentranshere is the transwindowhifndef transwindow hdefine transwindow hinclude qdialognamespace ui class transwindowclass transwindow public qdialog q objectpublic explicit transwindowqwidget parent 0 setwindowflagswindowflags qtframelesswindowhint transwindowprivate uitranswindow uiendif transwindow hand here is transwindowcppinclude transwindowhinclude ui transwindowhtranswindowtranswindowqwidget parent qdialogparent uinew uitranswindow setwindowtitlenewwin setwindowflagsqtframelesswindowhint setattributeqtwa translucentbackgroundtrue uisetupuithistranswindowtranswindow delete uiin the different source codes youll see commented out lines which is the different things that i have tried for the most part the problem is if i uncomment out any of the lines that try to set the qtframlesswindowhint the program runs normally but never opens a new window when i click the button on the main uiif i uncomment out any of the lines where i set the qtwa translucentbackground the new window will open up when when the button is pressed in the main ui but the background of the new window is black not transparentother info that may be pertinentlinux ubunto 1204qt 502 64bitqt creator 271like i stated earlier i am quite new at this and do not understand exactly what i am missing to make this work properly any assistance anyone can provide would be greatly appreciated,['c++'] +527626,initialize all the classes in a module into nameless objects in a list is there a way to initialize all classes from a python module into a list of nameless objectsexamplei have a module rules which contains all child classes from a class rule because of that i am certain they will all implement a method run and will have a attribute name which will be generated during the call of init i would like to have a list of objects dynamically initiated from those classes by dynamically initialized i mean that they do not have to be named explicitly the questions areis it possible to iterate through all classes in a modulecan a nameless object be initiated,['python'] +527693,taking input of a string word by word i just started learning c i was just playing around with it and came across a problem which involved taking input of a string word by word each word separated by a whitespace what i mean is suppose i have name place animal as the input i want to read the first word do some operations on it then read the second word do some operations on that and then read the next word so on i tried storing the entire string at first with getline like this includeiostream using namespace std int main string t getlinecint cout t just to confirm the input is read correctly but then how do i perform operation on each word and move on to the next wordalso since i am new this might seem a stupid question but while googling around about c i saw at many places instead of using using namespace std people prefer to write stdwith everything whys that i think they do the same thing then why take the trouble of writing it again and again,['c++'] +527923,how to route get and post for same pattern in laravel does anyone know of any way in laravel 4 which combines these 2 lines into oneroutegetlogin authcontrollergetloginroutepostlogin authcontrollerpostloginso instead of having to write both you only have to write one since their both using the same method but also the url remains as sitecomlogin instead of a redirect to sitecomauthlogini am curious since i remember ci has something like that where the url remains the same and the controller is never shownroutemethod1method2 controller1,['php'] +527930,bootstrap button radio group default value check attribute not working after countless hours of research i am still dumbfounded on how to get the checked attribute working for button radio groups for bootstrap i am trying to default excellenteven though i know for sure radio inputs are checked and not selected i even tried selected and nothing worksdiv classbtngroup datatogglebuttons label classbtn btndefault input typeradio nameinputwalls idinputwalls valueexcellent checked excellent label label classbtn btndefault input typeradio nameinputwalls idinputwalls valuegood good label label classbtn btndefault input typeradio nameinputwalls idinputwalls valuepoor poor labeldivif clarification is needed please let me know,['html'] +527980,saving buffer data of avplayer i am playing audio from my server using avplayer in my application now i want that when it completely buffer the audio then i can save that data in the application to play it later so any guide or help that how can i access buffer data and save it for later use,"['iphone', 'ios']" +528003,how to create a release signed apk file using gradle i would like to have my gradle build to create a release signed apk file using gradlei am not sure if the code is correct or if i am missing a parameter when doing gradle buildthis is some of the code in my gradle fileandroid signingconfigs release storefile filereleasekeystore storepassword keyalias keypassword the gradle build finishes successful and in my buildapk folder i only see the releaseunsignedapk and debugunalignedapk files any suggestions on how to solve this,['android'] +528010,how to write spring applicationcontextxml file i am using spring320 releases so i was trying to write below applicationcontextxml filexml version10 encodingutf8 standalonenobeans xmlns xmlnsaop xmlnscontext xmlnsjee xmlnstx xmlnsxsi xsischemalocation this will automatically locate any and all property files you have within your classpath provided they fall under the metainf directory the located property files are parsed and their values can then be used within application context files in the form of propertykey contextpropertyplaceholder locationclasspathproperties beansbut this xml file giving error in eclipse editor multiple annotations found at this line cvcelt1 cannot find the declaration of element beans schema reference4 failed to read schema document beans30xsd because 1 could not find the document 2 the document could not be read 3 the root element of the document is not xsdschemaso i changed my applicationcontextxml file like thisxml version10 encodingutf8 standalonenobeans xmlns xmlnsaop xmlnscontext xmlnsjee xmlnstx xmlnsxsi xsischemalocation this will automatically locate any and all property files you have within your classpath provided they fall under the metainf directory the located property files are parsed and their values can then be used within application context files in the form of propertykey contextpropertyplaceholder locationclasspathproperties beansthe only changed you will see xsd declaration previously i was using 30xsd and now 320xsd so now eclipse editor issue gone but now when i am running project into tomcat7 run time i am getting below exceptionorgxmlsaxsaxparseexception schema reference4 failed to read schema document because 1 could not find the document 2 the document could not be read 3 the root element of the document is not xsdschema at orgapachexercesutilerrorhandlerwrappercreatesaxparseexceptionunknown source xercesimpl281jarna at orgapachexercesutilerrorhandlerwrapperwarningunknown source xercesimpl281jarna at orgapachexercesimplxmlerrorreporterreporterrorunknown source xercesimpl281jarna at orgapachexercesimplxmlerrorreporterreporterrorunknown source xercesimpl281jarna at orgapachexercesimplxstraversersxsdhandlerreportschemawarningunknown source xercesimpl281jarna at orgapachexercesimplxstraversersxsdhandlergetschemadocumentunknown source xercesimpl281jarna at orgapachexercesimplxstraversersxsdhandlerparseschemaunknown source xercesimpl281jarna at orgapachexercesimplxsxmlschemaloaderloadschemaunknown source xercesimpl281jarna at orgapachexercesimplxsxmlschemavalidatorfindschemagrammarunknown source xercesimpl281jarna at orgapachexercesimplxsxmlschemavalidatorhandlestartelementunknown source xercesimpl281jarna at orgapachexercesimplxsxmlschemavalidatorstartelementunknown source xercesimpl281jarna at orgapachexercesimplxmlnsdocumentscannerimplscanstartelementunknown source xercesimpl281jarna at orgapachexercesimplxmlnsdocumentscannerimplnscontentthispatcherscanrootelementhookunknown source xercesimpl281jarna at orgapachexercesimplxmldocumentfragmentscannerimplfragmentcontentthispatcherthispatchunknown source xercesimpl281jarna at orgapachexercesimplxmldocumentfragmentscannerimplscandocumentunknown source xercesimpl281jarna at orgapachexercesparsersxml11configurationparseunknown source xercesimpl281jarna at orgapachexercesparsersxml11configurationparseunknown source xercesimpl281jarna at orgapachexercesparsersxmlparserparseunknown source xercesimpl281jarna at orgapachexercesparsersdomparserparseunknown source xercesimpl281jarna at orgapachexercesjaxpdocumentbuilderimplparseunknown source xercesimpl281jarna at orgspringframeworkbeansfactoryxmldefaultdocumentloaderloaddocumentdefaultdocumentloaderjava75 springbeans320releasejar320release at orgspringframeworkbeansfactoryxmlxmlbeandefinitionreaderdoloadbeandefinitionsxmlbeandefinitionreaderjava388 springbeans320releasejar320release at orgspringframeworkbeansfactoryxmlxmlbeandefinitionreaderloadbeandefinitionsxmlbeandefinitionreaderjava334 springbeans320releasejar320release at orgspringframeworkbeansfactoryxmlxmlbeandefinitionreaderloadbeandefinitionsxmlbeandefinitionreaderjava302 springbeans320releasejar320release at orgspringframeworkbeansfactorysupportabstractbeandefinitionreaderloadbeandefinitionsabstractbeandefinitionreaderjava174 springbeans320releasejar320release at orgspringframeworkbeansfactorysupportabstractbeandefinitionreaderloadbeandefinitionsabstractbeandefinitionreaderjava209 springbeans320releasejar320release at orgspringframeworkbeansfactorysupportabstractbeandefinitionreaderloadbeandefinitionsabstractbeandefinitionreaderjava180 springbeans320releasejar320release at orgspringframeworkwebcontextsupportxmlwebapplicationcontextloadbeandefinitionsxmlwebapplicationcontextjava125 springweb320releasejar320release at orgspringframeworkwebcontextsupportxmlwebapplicationcontextloadbeandefinitionsxmlwebapplicationcontextjava94 springweb320releasejar320release at orgspringframeworkcontextsupportabstractrefreshableapplicationcontextrefreshbeanfactoryabstractrefreshableapplicationcontextjava131 springcontext320releasejar320release at orgspringframeworkcontextsupportabstractapplicationcontextobtainfreshbeanfactoryabstractapplicationcontextjava537 springcontext320releasejar320release at orgspringframeworkcontextsupportabstractapplicationcontextrefreshabstractapplicationcontextjava451 springcontext320releasejar320release at orgspringframeworkwebcontextcontextloaderconfigureandrefreshwebapplicationcontextcontextloaderjava383 springweb320releasejar320release at orgspringframeworkwebcontextcontextloaderinitwebapplicationcontextcontextloaderjava283 springweb320releasejar320release at orgspringframeworkwebcontextcontextloaderlistenercontextinitializedcontextloaderlistenerjava112 springweb320releasejar320release at orgapachecatalinacorestandardcontextlistenerstartstandardcontextjava4939 catalinajar7042 at orgapachecatalinacorestandardcontextstartinternalstandardcontextjava5434 catalinajar7042 at orgapachecatalinautillifecyclebasestartlifecyclebasejava150 catalinajar7042 at orgapachecatalinacorecontainerbasestartchildcallcontainerbasejava1559 catalinajar7042 at orgapachecatalinacorecontainerbasestartchildcallcontainerbasejava1549 catalinajar7042 at javautilconcurrentfuturetasksyncinnerrunfuturetaskjava334 na170 25 at javautilconcurrentfuturetaskrunfuturetaskjava166 na170 25 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava1145 na170 25 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava615 na170 25 at javalangthreadrunthreadjava724 na170 25122023289 localhoststartstop1 error oswebcontextcontextloader context initialization failedorgspringframeworkbeansfactoryxmlxmlbeandefinitionstoreexception line 6 in xml document from servletcontext resource webinfapplicationcontextxml is invalid nested exception is orgxmlsaxsaxparseexception linenumber 6 columnnumber 578 cvcelt1 cannot find the declaration of element beans at orgspringframeworkbeansfactoryxmlxmlbeandefinitionreaderdoloadbeandefinitionsxmlbeandefinitionreaderjava396 springbeans320releasejar320release at orgspringframeworkbeansfactoryxmlxmlbeandefinitionreaderloadbeandefinitionsxmlbeandefinitionreaderjava334 springbeans320releasejar320release at orgspringframeworkbeansfactoryxmlxmlbeandefinitionreaderloadbeandefinitionsxmlbeandefinitionreaderjava302 springbeans320releasejar320release at orgspringframeworkbeansfactorysupportabstractbeandefinitionreaderloadbeandefinitionsabstractbeandefinitionreaderjava174 springbeans320releasejar320release at orgspringframeworkbeansfactorysupportabstractbeandefinitionreaderloadbeandefinitionsabstractbeandefinitionreaderjava209 springbeans320releasejar320release at orgspringframeworkbeansfactorysupportabstractbeandefinitionreaderloadbeandefinitionsabstractbeandefinitionreaderjava180 springbeans320releasejar320release at orgspringframeworkwebcontextsupportxmlwebapplicationcontextloadbeandefinitionsxmlwebapplicationcontextjava125 springweb320releasejar320release at orgspringframeworkwebcontextsupportxmlwebapplicationcontextloadbeandefinitionsxmlwebapplicationcontextjava94 springweb320releasejar320release at orgspringframeworkcontextsupportabstractrefreshableapplicationcontextrefreshbeanfactoryabstractrefreshableapplicationcontextjava131 springcontext320releasejar320release at orgspringframeworkcontextsupportabstractapplicationcontextobtainfreshbeanfactoryabstractapplicationcontextjava537 springcontext320releasejar320release at orgspringframeworkcontextsupportabstractapplicationcontextrefreshabstractapplicationcontextjava451 springcontext320releasejar320release at orgspringframeworkwebcontextcontextloaderconfigureandrefreshwebapplicationcontextcontextloaderjava383 springweb320releasejar320release at orgspringframeworkwebcontextcontextloaderinitwebapplicationcontextcontextloaderjava283 springweb320releasejar320release at orgspringframeworkwebcontextcontextloaderlistenercontextinitializedcontextloaderlistenerjava112 springweb320releasejar320release at orgapachecatalinacorestandardcontextlistenerstartstandardcontextjava4939 catalinajar7042 at orgapachecatalinacorestandardcontextstartinternalstandardcontextjava5434 catalinajar7042 at orgapachecatalinautillifecyclebasestartlifecyclebasejava150 catalinajar7042 at orgapachecatalinacorecontainerbasestartchildcallcontainerbasejava1559 catalinajar7042 at orgapachecatalinacorecontainerbasestartchildcallcontainerbasejava1549 catalinajar7042 at javautilconcurrentfuturetasksyncinnerrunfuturetaskjava334 na170 25 at javautilconcurrentfuturetaskrunfuturetaskjava166 na170 25 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava1145 na170 25 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava615 na170 25 at javalangthreadrunthreadjava724 na170 25caused by orgxmlsaxsaxparseexception cvcelt1 cannot find the declaration of element beans at orgapachexercesutilerrorhandlerwrappercreatesaxparseexceptionunknown source xercesimpl281jarna at orgapachexercesutilerrorhandlerwrappererrorunknown source xercesimpl281jarna at orgapachexercesimplxmlerrorreporterreporterrorunknown source xercesimpl281jarna at orgapachexercesimplxmlerrorreporterreporterrorunknown source xercesimpl281jarna at orgapachexercesimplxsxmlschemavalidatorhandlestartelementunknown source xercesimpl281jarna at orgapachexercesimplxsxmlschemavalidatorstartelementunknown source xercesimpl281jarna at orgapachexercesimplxmlnsdocumentscannerimplscanstartelementunknown source xercesimpl281jarna at orgapachexercesimplxmlnsdocumentscannerimplnscontentthispatcherscanrootelementhookunknown source xercesimpl281jarna at orgapachexercesimplxmldocumentfragmentscannerimplfragmentcontentthispatcherthispatchunknown source xercesimpl281jarna at orgapachexercesimplxmldocumentfragmentscannerimplscandocumentunknown source xercesimpl281jarna at orgapachexercesparsersxml11configurationparseunknown source xercesimpl281jarna at orgapachexercesparsersxml11configurationparseunknown source xercesimpl281jarna at orgapachexercesparsersxmlparserparseunknown source xercesimpl281jarna at orgapachexercesparsersdomparserparseunknown source xercesimpl281jarna at orgapachexercesjaxpdocumentbuilderimplparseunknown source xercesimpl281jarna at orgspringframeworkbeansfactoryxmldefaultdocumentloaderloaddocumentdefaultdocumentloaderjava75 springbeans320releasejar320release at orgspringframeworkbeansfactoryxmlxmlbeandefinitionreaderdoloadbeandefinitionsxmlbeandefinitionreaderjava388 springbeans320releasejar320release 23 common frames omittedi am not able to figure out the issue i searched for issue in google but no any solution yet worked could any one help me to write the applicationcontextxml file,['java'] +528036,how to handle expired facebook access tokens on ios and fb sdk 37 i am using facebooks ios sdk 37 on my ios app to handle logins when i request post permissions it looks like the expiration date is about 2 months from the date of logini understand i can check the expiration date using fbsession activesessionaccesstokendataexpirationdate but what happens and how do i handle the token when the token expiresdo i run fbsession openactivesessionwithreadpermissionsallowloginuicompletionhandler again,['ios'] +528115,testing simple sti with factorygirl i have got a class that is the base of some other classes that specializes the behaviorclass task activerecordbase attr accessible type name command validates presence of type name command some methods i would like to testendthe class countertask inherits from taskclass countertask task endthis all works fine until i am trying to test the base class since it must have a typefactorygirldefine do factory task do sequencename n name n sequencecommand n command n endendhow would you test the basic functionality of the superclass,"['ruby-on-rails', 'ruby']" +528282,what is xcontenttypeoptionsnosniff i am doing some penetration testing on my localhost with owasp zap and it keeps reporting this messagethe antimimesniffing header xcontenttypeoptions was not set to nosniffthis check is specific to internet explorer 8 and google chrome ensure each page sets a contenttype header and the xcontenttypeoptions if the contenttype header is unknowni have no idea what this means and i could not find anything online i have tried addingmeta contenttexthtml charsetutf8 xcontenttypeoptionsnosniff httpequivcontenttype but the i still get the alertwhat is the correct way of setting the parameter,['html'] +528319,are there any sha256 javascript implementations that are generally considered trustworthy i am writing a login for a forum and need to hash the password client side in javascript before sending it on to the server i am having trouble figuring out which sha256 implementation i can actually trust i was expecting there to be some kind of authoritative script that everyone used but i am finding loads of different projects all with their own implementationsi realize using other peoples crypto is always a leap of faith unless youre qualified to review it yourself and that there is no universal definition of trustworthy but this seems like something common and important enough that there ought to be some kind of consensus on what to use am i just naiveedit since it comes up a lot in the comments yes we do a more stringent hash again on the server side the client side hashing is not the final result that we save in the database the client side hashing is because the human client requests it they have not given a specific reason why probably they just like overkill,['javascript'] +528385,matching subviews width to it is superview using autolayout goalhave a uiwebview be the same width as it is superview which is a uiscrollview using autolayout constraints codenslayoutconstraint makewidththesameasscrollview nslayoutconstraint constraintwithitemselfquestionwebview attributenslayoutattributewidth relatedby0 toitemselfmasterscrollview attributenslayoutattributewidth multiplier10 constant0selfview addconstraintmakewidththesameasscrollview nslogthe width of questionwebview after adding the constrain is f selfquestionwebviewframesizewidth nslogthe width of scrollview after adding the constrain is f selfmasterscrollviewframesizewidthcurrent resultwhen i log the width of selfquestionwebview the uiwebview it is width does not change when the autolayout constrain is applied questionsis this the correct approach what am i doing wrongps i know it is against apples recommendations to place a uiwebview in a uiscrollview however i have turned off the ability to scroll the uiwebview using the property selfquestionwebviewuserinteractionenabled no and currently using a uiwebview is my best strategy for thisplaying an html table,['ios'] +528406,how do i call eval in ie from c with the advent of ie11 ihtmlwindow2execscript is deprecated the recommended approach is to use eval instead i am automating ie via its c com interfaces and i have been unable to find how to accomplish this can someone point me to the example i have obviously missed in my searching if it is not possible to execute code via eval whats the appropriate way to inject javascript code into a running instance of internet explorer now that execscript is no longer availableedit any solution that will work for the project i am working on must work outofprocess i am not using a browser helper object bho or any type of ie plugin thus any solution that involves an interface that cannot be properly marshaled crossprocess would not work for me,['c++'] +528461,custom programming languagejar in android here is my situation i have a custom programming language that compile down into java byte code i have the jar and i am looking to use some of the classes in an android application i need some advice on how to approach this i can import some of these classes from the jar but im not sure how i can compilerun this on androidany advice is appreciated thanks,"['java', 'android']" +528490,can typename be omitted in the typespecifier of an out of line member definition i ran into this strange behaviour when testing whether or not typename is required by clang both clang and gcc accept this code while msvc rejects ittemplateclass t1struct a templateclass t2 struct b static b f static typename at2template bt1 g templateclass t1templateclass t2typename at2template bt1 ok typenametemplate required at1bt2gtemplateclass t1templateclass t2at1bt2 clanggcc accept msvc rejects missing typename at1bt2fin general a qualifiedid at1bt2 where at1 is a dependent name should be written typename at1template bt2 is the behaviour of gclang incorrect or is there an exception to the general rule quoted below in this particular caseit could be argued that at1 is not a dependent name or that bt2 refers to a member of the current instantiation however at the point of parsing the typespecifier it is not possible to know that the current instantiation is at1 it seems problematic to require the implementation to guess that at1 is the current instantiation146 name resolution tempresa name used in a template declaration or definition and that is dependent on a templateparameter is assumed not to name a type unless the applicable name lookup finds a type name or the name is qualified by the keyword typename142 names of template specializations tempnameswhen the name of a member template specialization appears after or in a postfixexpression or after a nestednamespecifier in a qualifiedid and the object or pointer expression of the postfixexpression or the nestednamespecifier in the qualifiedid depends on a template parameter 1462 but does not refer to a member of the current instantiation 14621 the member template name must be prefixed by the keyword template otherwise the name is assumed to name a nontemplateto further investigate what clang is doing here i also tried thistemplateclass t1struct c templateclass t2 struct d static typename at1template bt2 f static typename at1template bt2 g templateclass t1templateclass t2typename at1template bt2 ok typenametemplate required ct1dt2ftemplateclass t1templateclass t2at1bt2 clang rejects with incorrect error ct1dt2gclang gives error redefinition of g with a different type but the type of g actually matches the declarationi would instead expect to see a diagnostic suggesting the use of typename or templatethis gives credit to the hypothesis that clangs behaviour in the first example is unintended,['c++'] +528551,resolving a vim plugin mapping conflict mapping already exists for t i followed to install a bunch of plugins for python programming in gvim installed on a windows 8 machine it appears that there is a mapping conflict between the commandt and tasklist plugins as i get the following error messageerror detected while processing cuserswillemvimfilesbundletasklistplugintasklistvimline 369e227 mapping already exists for tthen i type map in vim and see that one mapping isn t commandtcris there a good way to resolve this,['python'] +528570,change the background color of a popup dialog i wrote android code that shows a popup dialog but i want to change the background color from black to white and then the color of the writingthis is the dialogs code mprefs preferencemanagergetdefaultsharedpreferencesthis boolean welcomescreenshown mprefsgetbooleanwelcomescreenshownpref false if welcomescreenshown string whatsnewtext getresourcesgetstringrstringtext new alertdialogbuilderthissetmessagewhatsnewtextsetpositivebutton rstringok new dialoginterfaceonclicklistener public void onclickdialoginterface dialog int which dialogthismiss show sharedpreferenceseditor editor mprefsedit editorputbooleanwelcomescreenshownpref true editorcommit very important to save the preference,['android'] +528644,short circuit vs non short circuit operators i understand the difference below at least for javaif true false shortcircuiting boolean operatorif true false nonshortcircuiting boolean operatorbut my question is is there any reason to use the nonshortcircuiting operator when you are dealing with boolean expressions is there some performance benefit or use that wouldnt be considered bad practise,['java'] +528676,youtubelike progress bar i am trying to make a youtubelike progress bar the bar should load at the page startup i have tried this so far here is the code of my scriptproperty 0animateproperty 105 duration 40 step function var percent mathroundthisproperty progresscsswidth percent if percent 105 progressaddclassdone complete function alertcomplete i am also including the jsfiddle of the same in this jsfiddle the progress bar appears but when i use the same code in my ide and run the file no progress bar appears what am i doing wrong or if there is another way to get the bar,['jquery'] +528729,why i get 411 length required error this is how i call a service with netvar requestedurl code client id client id client secret client secret redirect uri redirect uri grant typeauthorization codehttpwebrequest authrequest httpwebrequestwebrequestcreaterequestedurlauthrequestcontenttype applicationxwformurlencodedauthrequestmethod postwebresponse authresponsetwitter authrequestgetresponsebut when this method is invoked i getexception details systemnetwebexception the remote server returned an error 411 length requiredwhat should i do,"['c#', '.net']" +528838,unit testing for ios projects i am still relatively new to ios development and also an absolute stranger to any kind of testing that is not compile run and check whatever comes to your mindthis is obviously a weakness on any developers profile and i am decided to get ride of it now that interesting real projects are coming my wayin my quest to look for the best approach to go from 0 to 100 as soon and well as possible i am coming to the specialized community to get your feedbackat the same time i am asking for your tips i am also getting into amazon to look for wellreviewed books on the subject and google to get the rest i am just coming here to gather the feedback of those willing to spare a minute or to so i can probably hit jackpot with a great advise and better plan my learning strategy,['ios'] +528844,layout manager and positioning how to stick jlabel in glasspane to rellative floating coordinates from jprogressbar without using componentlistener or another listener is there built in notifiers in standard layoutmanagers that can notify about its internal state and can be accesible for override instead my attempt with componentlistener and nulayoutsscce about componentlistener and with nulayoutimport javaawtcontainerimport javaawtdimensionimport javaawtflowlayoutimport javaawtgridbagconstraintsimport javaawteventcomponentadapterimport javaawteventcomponenteventimport javaxswingjbuttonimport javaxswingjcheckboximport javaxswingjframeimport javaxswingjlabelimport javaxswingjprogressbarimport javaxswingjradiobuttonimport javaxswinguimanagerpublic class progresample private jframe frame new jframeglasspane instead of jlayer private jlabel label private gridbagconstraints gbc new gridbagconstraints private jprogressbar progreseven public progresample framesetlayoutnew flowlayout frameaddnew jbuttontest frameaddnew jcheckboxtest frameaddnew jradiobuttontest nothing is thisplayed if value is lover that 6 jprogressbar progresix new jprogressbar0 100 progresixsetvalue2 frameaddprogresix but this works value is higher that 6 progreseven new jprogressbar0 100 progresevenaddcomponentlistenernew componentadapter override public void componentmovedcomponentevent e labelsetbounds int progresevengetboundsgetx int progresevengetboundsgety progresevengetpreferredsizewidth labelgetpreferredsizeheight progresevensetvalue7 frameaddprogreseven label new jlabel labelsettexthtmlblablabla blablablablabr blablabla blablablablabr blablabla blablablablahtml labelsetpreferredsizenew dimension progresevengetpreferredsizewidth labelgetpreferredsizeheight container glasspane container framegetrootpanegetglasspane glasspanesetvisibletrue glasspanesetlayoutnull glasspaneaddlabel gbc framesetdefaultcloseoperationjframeexit on close framepack framesetvisibletrue public static void mainstring args try uimanagersetlookandfeeluimanagergetsystemlookandfeelclassname catch exception e eprintstacktrace progresample dialogtest new progresample,['java'] +528882,angularjs building a dynamic table based on a json given a json like this name john colours id 1 name greenid 2 name blueand two regular html inputsinput typetext namename input typetext namecolor input typesubmit valuesubmit i need to build a table with all the possible variations exjohn greenjohn bluethat means that if a user continues adding values through the inputs new rows will appear building the new variations for instance i also need to have available the id to handle it and i need that when i add new values using the inputs for instance peter black i need to autofill the id colour id dynamically like an auto increment in mysql resulting in something like this colours aid 3 name blackis that possible which options do i have for doing that with angular i am still thinking in the jquery way and i would like to do it in the angular wayi took a look to hgrepeat and used it but i am not figuring out how to deliver the expected result the only thing that come to my mind was to use nested ngrepeats but it didma t workthanks so much in advanceguillermo,['javascript'] +528905,angularjs rootscope property value undefined in service i am currently creating a new property in rootscope and setting its value in one modulerootscopetest 123i am then trying to reference this value later in a service functionfactorytestfactory function location http rootscope return testfunction function consolelogrootscope consolelogrootscopetest when i view the console output in chrome i can see that the value of test is being set properly in the rootscope object but i am unable to reference using the rootscopetest syntax rooscopetest simply returns undefinedis there any reason that you cannot reference property values of rootscope in services or am i attempting to retrieve this value improperlyupdate i have created a plunker that demonstrates the issue that i am running into,['javascript'] +528955,data driven rules engine drools i have been evaluating drools as a rules engine for use in our business web applicationmy use case is a order management applicationand the rules are of following kind if user type is special give an extra 5 thiscount if user has made 10 purchases already give an extra 3 thiscount if product category is old give a gift hamper to the user worth 5 if product category is new give a gift hamper to the user worth 1 if user has made purchases of over 10 in the past shipping is freethe immediate challenge i see is that there is no meaningful ui that i can offer to the end users to modify the rules guvnor ui or any editor to modify drl files is just not acceptable from end user point of view most of these rules will operate on often huge data available in db so i want a way for admin users to specify these rule from within my web app ui could i store these rules in database and then operate on them via drools at least that allows me to modify these rules via my own ui so this is something like a decision table in db what is the best way to go about this,['java'] +528964,how is dynamic cast implemented consider this simple hierarchyclass base public virtual base class derived public base trying to downcast base p to derived is possible using dynamic castderivedp i used to think dynamic cast works by comparing the vtable pointer in p to the one in a derived objectbut what if we derive another class from derived we now haveclass derived2 public derived in this casebase base new derived2derived derived dynamic castderivedbasewe still get a successful downcast even though the vtable pointer in derived2 has nothing to do with a vtable pointer in derived how does it actually work how can the dynamic cast know whether derived2 was derived from derived what if derived was declared in a different libraryi am looking for specific details about how this actually works preferably in gcc but others are fine too this question is not a duplicate of this question which does not specify how it actually works,['c++'] +528995,why cannot i change uibarbuttonitems title i want to change uibarbuttonitems titlebut this code is not working voidviewdidload self smay voidsmay appdelegate apd appdelegateuiapplication sharedapplicationdelegate nsstring smayuse nsstring stringwithformatdd apdnewyearapdnewmonth smay settitlesmayusei do not know how to solve this problemplease tell me a way to solve this problem,"['iphone', 'ios', 'objective-c']" +529040,jtable in jscrollpane how to set background i am using a jscrollpane to wrap a jtable depending on the configuration there is some space that is not occupied by the table it is drawn gray it looks like it is transparent and you can just see the component in the back how can i set this area to be a certain colorhere is a sscce to illustrateimport javaawtcolorimport javautilvectorimport javaxswingjdialogimport javaxswingjscrollpaneimport javaxswingjtablepublic class dialogdemo extends jdialog public static void mainfinal string args final dialogdemo diag new dialogdemo diagsetvisibletrue public dialogdemo super settitlesscce final vectorvectorstring rowdata new vectorvectorstring final vectorstring columnnames new vectorbuilderstringaddcontpropertyaddcontvalue rowdataaddelementnew vectorbuilderstringaddcontloremaddcontipsum rowdataaddelementnew vectorbuilderstringaddcontdoloraddcontsit amet rowdataaddelementnew vectorbuilderstringaddcontconsecteturaddcontadipiscing elit rowdataaddelementnew vectorbuilderstringaddcontpraesentaddcontposuere final jtable table new jtablerowdata columnnames jscrollpane pane new jscrollpanetable make that stuff white tablesetbackgroundcolorwhite tablesetopaquetrue panesetbackgroundcolorwhite panesetopaquetrue make that stuff white addpane pack setlocationrelativetonull setdefaultcloseoperationjdialogthispose on close class vectorbuildert extends vectort public vectorbuildert addcontfinal t elem addelementelem return this and here you can see the area which i want to colorize in the sscce i try to do that by using setopaqueboolean and setbackgroundcolorcolor of the table and scroll pane with no successcan you tell me what i am doing wrong,['java'] +529044,a sql query to select a string between two known strings i need a sql query to get the value between two known strings the returned value should start and end with these two stringsan exampleall i knew was that the dog had been very bad and required harsh punishment immediately regardless of what anyone else thoughtin this case the known strings are the dog and immediately so my query should return the dog had been very bad and required harsh punishment immediatelyi have come up with this so far but to no availselect substringtext charindexthe dog text charindeximmediately texttext being the variable containing the main stringcan someone please help me with where i am going wrong,['sql'] +529104,implementation of a hits in last secondminutehour data structure i think this is a fairly common question but i cannot seem to find answer by googling around maybe there is a more precise name for the problem i do not knowyou need to implement a structure with a hit method used to report a hit and hitsinlastsecondminutehour methods you have a timer with say nanosecond accuracy how do you implement this efficientlymy thought was something like this in psuedocclass hitcounter void hit hits atnow last count int hitsinlastsecond auto before count hits atlower boundnow 1 second if before count hits atend return last count return last count before countsecond etc for minute hour maptime point int hits at int last count 0does this work is it good is something betterupdate added pruning and switched to a deque as per commentsclass hitcounter void hit hitspush backmake pairnow last count int hitsinlastsecond auto before lower boundhitsbegin hitsend make pairnow 1 second 1 if before hitsend return last count return last count before countsecond etc for minute hour void prune auto old upper boundhitsbegin hitsend make pairnow 1 hour 1 if old hitsend hitserasehitsbegin old deqeuepairtime point int hits int last count 0,['c++'] +529213,listview with title is there a way to insert another view above the list in a listview for example i want a title bar textview that sits on top of the list and scrolls out of view as the list scrolls i can think of two ways so far of doing this but both are hacksidea 1 use a linearlayout that pretends to be a listview but the problem is you are unable to take advantage of the smart loadingunloading of views that an adapter providesscrollview linearlayout textview linearlayout androidorientationvertical add listitems here linearlayoutscrollviewidea 2 use a hacky arrayadapter with a getview method similar to thisoverridepublic view getviewint position view convertview viewgroup parent ifposition 0 view view inflaterinflaterlayoutspecial list item null else view view inflaterinflaterlayoutregular list item null return vi,['android'] +529248,stub method only on the first call with rspec how can i stub a method only on the first call and in the second one it should behave as expectedi have the following methoddef method do stuffrescue myexception sleep rand retryendi want to the first call of do stuff to raise myexception but in the second call behaves normally i need to achieve this to test my rescue block without getting an infinite loopis there a way to achieve this,['ruby'] +529262,how to generate rsa private key from pem string in java i want to generate the private key from a stringa pem file in javaprivate static final string test begin rsa private keyn miiepaibaakcaqeavcch8wst1xyrzqq684vpjzof3hn5dnbowz96iepn0btrw2n and so on end rsa private keytry string privkeypem testreplacebegin rsa private keyn privkeypem privkeypemreplaceend rsa private key byte encoded base64decodeprivkeypem pkcs8encodedkeyspec keyspec new pkcs8encodedkeyspecencoded keyfactory kf keyfactorygetinstancersa privatekey privkey kfgenerateprivatekeyspeccatch exception e eprintstacktracethe last linegenerateprivate function is throwing this exceptionjavasecurityspecinvalidkeyspecexception javasecurityinvalidkeyexception ioexception algid parse error not a sequence at sunsecurityrsarsakeyfactoryenginegenerateprivateunknown source at javasecuritykeyfactorygenerateprivateunknown source at testmaintestjava52caused by javasecurityinvalidkeyexception ioexception algid parse error not a sequence at sunsecuritypkcspkcs8keydecodeunknown source at sunsecuritypkcspkcs8keydecodeunknown source at sunsecurityrsarsaprivatecrtkeyimplinitunknown source at sunsecurityrsarsaprivatecrtkeyimplnewkeyunknown source at sunsecurityrsarsakeyfactorygenerateprivateunknown source 3 moreif i change the private key to the value from a der file it works properly but i need to generate the private key file from a pem filei attached a screenshot of the bytes printed as stringonce hardcoded with and and once hardcoded without n and once from the filebigger imagethe weird thing is that the output from the file is different to the output from the stringsif i try to encode a der file with base64 the result is different than the string in the pem file why is that so,['java'] +529265,how to add javascript code into existing iframe using jquery i want to add a javascript snippet into an existing iframe in the page using jquery i have the following codecodecontent script js code scriptiframe idcontentsfindbodyappendcontentbut somehow this is not working i checked some of the existingrelated answers and it seems jquery does not quite recognize the script tags asscript tags the iframe is in the same domainsame portsame host so there is no issue about crosite scripting etc how can i fix this,"['javascript', 'jquery', 'html', 'css']" +529273,change backgound of child if parent hover i want to change the bgcolor of circleicon if postsitem is hovered any idea how to accomplish that possibly without javascriptdiv idscr1 classlarge6 columns timeline div classlinediv ul classposts li classpostsitem div classcircle icondiv h2 classpostsitemtitle a hrefa h2 p clasummaryp li uldiv,['css'] +529307,empty an arraylist or just create a new one and let the old one be garbage collected what are the advantages and thisadvantages of emptying a collection in my case its an arraylist vs creating a new one and letting the garbage collector clear the old onespecifically i have an arraylistrectangle called list when a certain condition occurs i need to empty list and refill it with other contents should i call listclear or just make a new arraylistrectangle and let the old one be garbage collected what are the pros and cons of each approach,['java'] +529313,actionbarcompat transparency i would like to make the actionbar in the support library fully transparent however it seems that changing the background drawable would not suffice since the backgrounds stack if you put a semitransparent background you end up with the default background behind itdoes anyone know a way to remove that backgroundthis is what happensthe code for the background drawableshape xmlnsandroid androidshaperectangle solid androidcolor66336688shapeas you can see the drawable has a transparent blue that overlaps with the default gray background,['android'] +529429,how to convert iqueryable to expression i just want to build a dynamic filtersand finally to return expressionfuncevent booli have tried to use the combine andalso expressions but it was not workin and finally i found that there are iqueryable queries which works good but now how can i convert it to the return type expressionfuncevent boolmy code public iqueryableevent getbysearcheventfilter search iqueryableevent query thiscontexteventsasqueryable expressionfuncevent bool expression null if searchcategoryid 0 query querywherex xcategoryid searchcategoryid if searchsubcategoryid 0 query querywherex xsubcategoryid searchsubcategoryid expression queryexpression as expressionfuncevent bool this convert is not working it returns null return thiscontexteventswhereexpression,['c#'] +529465,attributeerror assignment not allowed to composite field task in protocol message object i am using protocolbuffers python lib to send databut it is have some problems sotraceback most recent call last file test messagepy line 17 in module ptasktask task file buildbthistwin32egoogleprotobufinternalpython messagepy line513 in setterattributeerror assignment not allowed to composite field task in protocol message objectthe src as followsproto filemessage task required int32 id 1 required string msg 2message task info required task task 1python codetask yacctasktaskid 10taskmsg utestptask yacctask info ptasktask task this line happen the runtime error,['python'] +529471,css opacity background color and text not working im making an app for firefox os and i want to make button background opacity 05 and the text opacity 1 but it didnt work check the cssbuttonheight40pxwidth180pxborderradius 100px 100px 100px 100pxborder 1px solid ff9924thisplayinlineblockbackgroundcolorff9924paddingtop5pxopacity05h1 padding 5px 5px 5px 5px textaligncenter fontsize20px fontfamily firstone opacity10on pagediv classmenu div classbuttonh1start the fighth1divdiv,['css'] +529473,toolchain support for the c11 standard i am currently updating my knowledge on c to the new standard it makes me feel like a little kid that just got the awesomest toy i want to play with it all the time but i do not want to lose my friends because of iti am involved in a few open source projects for which some of the new features would be extremely useful so i am quite keen on using them my question is how many users can compile c11 code eg whats the adoption rate of c11complete compilers in the general public does anyone have related informationi know that gcc 481 and clang 33 are c11 feature complete but i have no idea how many people actually use compilers that are up to date i know most codemonkeys surely do but what about the average open source user slapping potential users in the face and telling them to update their compilers is not really an optioni am aware that this question may be criticisedclosed for being similar to these questionshow are you using c11 todayto use or not to use c0x featuresi would like to point out that things are different now since we are talking about an actual approved standard i believe that being aware of its adoption rate is important in practice for programming,['c++'] +529489,tablelayout remove space between columns i am having a problem with the tablelayoutfirst take a look at the screenshotas you can see there is a pretty big space in the middle of the tablelayouti do not know how to reduce the space in the middle so that the tablerows will have more width to coverand also i want to reduce the space between a tablerow and the one below iti am adding the views to the tablelayout programmaticallyalso i have already set the layout weight of the content of the tablerow to 1ftablerow tr tablerow new tablerowmtablelayoutgetcontexttablerowlayoutparams params new tablerowlayoutparamstablerowlayoutparamsmatch parent tablerowlayoutparamswrap contentnormalcard card new normalcardcardsetlayoutparamsnew tablerowlayoutparams0 740 1ftraddviewcardmtablelayoutaddviewtr paramsxml declaration of the tablelayouttablelayout androidididtablelayout androidlayout widthmatch parent androidlayout heightwrap content androidshrinkcolumns androidstretchcolumns androiddividerpadding0dp androidshowdividersnone androiddividernull tablelayouthow do i reduce the space in the middle of the tablelayoutand also how to reduce the space between a tablerow and the one below itthank you upfront,"['java', 'android']" +529505,java heap space out of memory wtih websphere admin console i am not able to open the administrative console of websphere application server v85 the logs report java heap space and out of memory errors i have searched online and the suggestions are to increase the jvm heap size but how should i accomplish that now when even the admin console is not working for me is there a method to free up the heap space somehow,['java'] +529534,how to delete a certain row from mysql table with same column values i have a problem with my queries in mysql my table has 4 columns and it looks something like thisid users id product quantity date 1 2 1 2013 1 2 1 2013 2 2 1 2013 1 3 1 2013id users and id product are foreign keys from different tables what i want is to delete just one row 1 2 1 2013which appears 2 times so i just want to delete it i have tried this query delete from orders where id users 1 and id product 2but it will delete both of them since they are depluicated any hints on solving this problem,['mysql'] +529535,pendingintent get requestcode i use an alarmmanager to start a service when i set up the alarmmanager i use the pendingintent and use a unique requestcode which is equal to a id row in my databasependingintent pendingintent pendingintentgetbroadcastsettingsactivitythis lecturegetid myintent 0 how can i retrieve that id in my service when it starts i basically need only the requestcode parameter i want to use that id to retrieve data from my database and show it in a notification i have implemented all the stuff i just need that requestcode is it possible to get itthanks,['android'] +529600,close all underlying network connections backgroundi have some code that is connecting to a server to pull data however at some point the program got into a state where it was failing to connect to the server the problem we were seeing is that the server was continually timing out when we were attempting to reconnectplugin we have our timeout set to the default values used by our network plugin a thrift plugin these values are 100k millisecond timeout and 300k millisecond readwrite timeout not exactly short timeouts also every time we attempt to reconnect we recreate the plugins class so whatever values it is setting internally are reset each time we attempt to reconnect i believe timeouts are not the issue and i believe the plugin is not the issuenetworkwe saw these repeated timeouts occur for half an hour when we restarted the service not the machine it immediately came back online so i know it was not a network issue that leads me to believe it is something in our code that is getting into an invalid network state also it is a state that we cannot control since our plugin hides all of the good network stuff from usincluding timeouts keepalive flags and connection groups among others we basically do not have access to the httpwebreqest memberquestionwhen our network settings get into this state we attempt to close all connections and reconnect to the server the goal was to kill all the active connections in order to reset whatever state we got into however when we attempt to reconnect were getting timeouts on our reconnectsomehow probably due to the keepalive and tcp pipelining which we cannot control the network connections remain open even though we have closed all connections this leaves us in a bad state and prevents us from cycling our connections to the serverthe questionhow can i kill all underlying connections to a server in order to force a reconnect,"['c#', '.net']" +529617,how to combine stdbind variadic templates and perfect forwarding i want to invoke a method from another through a thirdparty function but both use variadic templates for examplevoid third partyint n stdfunctionvoidint f fnstruct foo template typename args void invokeint n args args auto bound stdbindfooinvoke implargs this stdplaceholders 1 stdforwardargsargs third partyn bound template typename args void invoke implint args foo ffinvoke1 2problem is i get a compilation errorusrincludec47functional120635 error cannot bind ainta lvalue to aintai tried using a lambda but maybe gcc 48 does not handle the syntax yet here is what i triedauto bound this args int k invoke implk stdfowardargsargs i get the following errorerror expected aa before aa tokenerror expected identifier before aa tokenerror parameter packs not expanded with aanote aargsafrom what i understand the compiler wants to instantiate invoke impl with type int while i thought that using in this case would preserve the actual argument typewhat am i doing wrong thanks,['c++'] +529619,variadic template summing class trying to play around with variadic template but for some reason my brain has gone numbi am trying to create a class to sum up variables in compilation time but cannot create the stopping condition correctly i tried to it like this but it does not compile quick help anyoneinclude iostreaminclude type traitsusing namespace stdtemplatesize t head size t reststruct sum static const size t value head sumrestvalue static void print cout value templatestruct sum static const size t value 0int tmainint argc tchar argv sum5print return 0,['c++'] +529643,does ajax post data need to be uri encoded regarding this linevar data encodeuricomponentjsonstringifyobject literali do not understand why this is being uri encoded later data will be sent via ajax post i understand that urls particularly the one you can see in the browser address bar require special characters as described herebut what exactly does this have to do with ajax postingdo both the url address bar and the internal ajax post utilize the same mechanism,"['php', 'javascript']" +529658,turn off bean validation programmatically javaxvalidationconstraints for example we have some entity in whitch several fields are validating with annotation pattern this entity is used everywhere in project but only in one place we need to turn off this validationis there some way to do it programmatically or it is impossible,['java'] +529671,cors not working php i am trying to post form data from wsiteonecom to wsitetwocom via cors my ajax code is thisscriptdocumentreadyfunction submitliveclickfunction var url var data formserialize jqueryajax url url type post data formserialize donefunctionresponse alertresponse failfunctionerror consolelogerrorstatustext return falsescriptand the file corsphp in wsitetwocom is as followsphp headeraccesscontrolalloworigin headeraccesscontrolallowmethods post get options echo haibut still accesscontrolalloworigin error is thrown the error thrown is thisxmlhttprequest cannot load origin is not allowed by accesscontrolalloworigin i came to know that using cors by just allowing the remote website via headers we can use crossdomain request but when i tried like this error is thrown have i missed anything in here here is my requestresponse headersresponse headersconnection keepalivecontentlength 487contenttype texthtml charsetiso88591date fri 23 aug 2013 055320 gmtkeepalive timeout15 max99server apache2215 centoswauthenticate basic realmsite two server restricted arearequest headersaccept acceptencoding gzip deflateacceptlanguage enusenq05contentlength 43contenttype applicationxwformurlencoded charsetutf8host wsitetwocomorigin referer useragent mozilla50 x11 ubuntu linux x86 64 rv230 gecko20100101 firefox230,"['php', 'jquery']" +529682,helvetica neue lightios surprisingly i cannot seem to find another question on this sorry if i am missing something obvious i am trying to use helvetica neue light programatically in my iphone app it seems that the system does not have this built in which seems strange is this the case does this particular font need to be added manually ideally i would like to edit this line of code to accomplish this mylabelfont uifont fontwithnamehelveticaneue size 32,"['ios', 'objective-c']" +529699,c stdthread of a member function i am trying to program a command line server that would receive information from a serial port parse it and record it in an internal objectthen upon request from a client the server would return the requested informationwhat i want to do is put the receiver parser parts in a separated thread in order to have the server running along side not interfering with the data collectioninclude iostreaminclude threadclass exampleclass stdthread processthread public void completeprocess while1 procestep1 if verificationprocestep2 void procestep1 void procestep2 bool verification void runthreaded end example class definition the idea being that this thread runs independently until i call the objects destructorexampleclassrunthreaded stdthread processthreadexampleclasscompleteprocess this unfortunately the program ends up crashing here with cigaret,['c++'] +529739,can code that will never be executed invoke undefined behavior the code that invokes undefined behavior in this example division by zero will never get executed is the program still undefined behaviorint mainvoid int i if0 i 10 return 0i think it still is undefined behavior but i cannot find any evidence in the standard to support or deny meso any ideas,['c'] +529827,how to deal with noexcept in visual studio i am trying to create a custom exception that derives from stdexception and overrides what at first i wrote it like thisclass userexception public stdexceptionprivate const stdstring messagepublic userexceptionconst stdstring message messagemessage virtual const char what const override return messagec str this works fine in vs2012 but it does not compile in gcc 48 with stdc11error looser throw specifier for avirtual const char userexceptionwhat constaso i add noexceptvirtual const char what const noexcept overridethis works fine in gcc but it does not compile in visual studio because vs 2012 does not support noexcepterror c3646 noexcept unknown override specifierwhat is the recommended way to deal with this i want the same code to compile with both compilers and i am using c11 features so i cannot compile with different std,['c++'] +529864,can json array contain objects of different keyvalue pairs can a json array contain objects of different keyvalue pairs from this tutorial the example given for json array consists of objects of the same keyvalue pairexample firstnamejohn lastnamedoe firstnameanna lastnamesmith firstnamepeter lastnamejones if i want to change it to have different keyvalue pairs inside the json array is the following still a valid jsonexample firstnamejohn lastnamedoe fruitapple length100 width60 height30 just want to confirm this if so how can i use javascript to know if the json example field contains the first homogeneous objects or the second heterogeneous objects,['javascript'] +529879,ipython pandas plot does not show i am using the anaconda thistribution of ipythonqt console i want to plot things inline so i type the following from the ipython console pylab inlinenext i type the tutorial at into ipython import matplotlibpyplot as pltimport pandas as pd ts pdseriesrandn10 index pddate range1120 periods10ts tscumsumtsplot and this is all that i get back matplotlibaxesaxessubplot at 0x109253410but there is no plot what could be wrong is there another command that i need to supply the tutorial suggests that that is all that i need to type,['python'] +529898,how to use unicode characters in s3s responsecontentthisposition header were using this code to generate requests and set the filename for the downloadvar request new getpresignedurlrequest withbucketnames3bucketname withexpiresrequestexpirationtime withkeyfiles3key withresponseheaderoverrides new responseheaderoverrides withcontentthispositionattachment filenameunicode filename a testtxtthis generates the following links3pathawsaccesskeyidxexpires13771946responsecontentthispositionattachment3b20filename3dunicode20filename20a20testtxtsignaturexwhich gives this errorerror codeinvalidargumentcode message header value cannot be represented using iso88591 message argumentvalueattachment filenameunicode a filenametxtargumentvalue argumentnameresponsecontentthispositionargumentname requestid368bd60502854514requestid hostid biuuyp4d9ixfk68jkvxwzep25m5je166m0zy1vmopk9pn9a69hlhcff6wivlwk1b hostiderrorhow can we use noniso88591 characters such as unicode in the responsecontentthisposition header,['c#'] +529907,slim templating is it possible to put two elements on the same line i often want to nest elements such as the following navigationul li ahref link name li ahref link name li ahref link name is is possible to put li and a on the same line some syntax like li a would be nice,"['ruby-on-rails', 'ruby']" +529913,devise confirmation token is invalid my userrbclass user activerecordbase devise database authenticatable registerableconfirmabletoken authenticatable recoverable rememberable trackable validatable authentication keys namemy routesdevise for users controllers sessions sessions confirmations confirmations passwords passwords registrations registrations my confirmationscontroller is a standard controller but with different redirecti have link on my email likeusersconfirmationconfirmation token167bad44a15e02b0bd570b51e1bf927b88368d8855d92b9833a24017a2bad4bein database user has confirmation token167bad44a15e02b0bd570b51e1bf927b88368d8855d92b9833a24017a2bad4bebut when i click on that link i only see page withresend confirmation instructions confirmation token is invalidwhat i dont do what else i have to setconfirmationcontrollerdef resource params paramsrequireuserpermitconfirmation token end private resource params def showselfresource resource classconfirm by tokenparamsconfirmation tokenif resourceerrorsempty set flash messagenotice confirmed if is navigational format sign inresource name resource sessionnew user true respond with navigationalresource redirect to after confirmation path forresource name resource else respond with navigationalresourceerrors status unprocessable entity render new end end protected the path used after resending confirmation instructions def after resending confirmation instructions path forresource name new registration pathresource name endi say standard controller because when i remove it and do not use custom controller problem is that same,['ruby-on-rails'] +529927,ruby execute code for every subclass given a parent class is there a way to insert code for every subclass on load iegiven parentclass how do i insert code like soclass childclass parentclass execute function endfor all child classes of parentclass,['ruby'] +529930,use exception for type mismatch in c i am implementing an idictionary interface which has parameter object for its get setobject this object key get set i want to enforce the key to be type of string so in my code i doif keygettype typeofstring i want to throw an exception when this happen however i do not know what the most appropriate exception to use in this case the closest one i can find is typeinitializationexception and argumentexception however it is stated in this document do throw systemargumentexception or one of its subtypes if bad arguments are passed to a member which makes me wonder if mine is the right use case for itwhat should i use my case should i use assert instead of throwing exception,['c#'] +529972,how to programmatically round corners and set random background colors i would like to round the corners of a view and also change the color of the view based on the contents at runtime textview v new textviewcontext vsettexttagslistgeti ifi2 0 vsetbackgroundcolorcolorred else vsetbackgroundcolorcolorblue vsetlayoutparamsnew layoutparamslayoutparamswrap content layoutparamswrap content vsetpaddingtwodp twodp twodp twodp vsetbackgroundresourcerdrawabletags rounded cornersi was hoping setting a drawable and color would overlap but they do not whichever one i execute second is the resulting backgroundis there any way to programmatically create this view keeping in mind that the background color would not be decided until runtimeedit i am only swapping between red and blue now for testing later the color will be choosable by the useredittags rounded cornersxmlxml version10 encodingutf8shape xmlnsandroid corners androidbottomrightradius2dp androidbottomleftradius2dp androidtopleftradius2dp androidtoprightradius2dpshape,['android'] +529991,bootstrap checkboxradio buttons do not change value the javascript page for bootstrap shows some nice use of buttons to style checkboxes and radio fields for example for a checkbox i might writediv classbtngroup datatogglebuttons label classbtn btnprimary input typecheckbox option 1 labeldivhowever the library does not actually change the value of the underlying input field it just changes whether the label field has class active i would have expected it to change the checked attribute on the checkbox apparently i do not just have it misconfigured this is the way the examples on the bootstrap site workis this actually expected behavior if so it seems fairly useless as people are going to want to use the checkbox field if not how do i properly configure bootstrap checkboxesradio buttons,"['javascript', 'html']" +529993,why should iteration be used instead of tail recursion what is the design smell poor practice in recursion once i saw resharper suggesting improvements i quickly looked around on googlesaw numerous comments around refactoring tail recursion to iterations and referring to it as a design smell public static void debugoutput2exception ex if ex null return debugwritelineexmessage if exinnerexception null debugoutput2exinnerexception was refactored topublic static void debugoutputexception ex if ex null return while true debugwritelineexmessage if exinnerexception null ex exinnerexception continue break edit based on c compiler treatment comment looks like it is recursive nowtarget net 45 c 50ildasm output for tail recursion version shows recursive call and not iterationmethod public hidebysig static void debugoutputclass mscorlibsystemexception ex cil managed code size 54 0x36 maxstack 2 locals init 0 bool cs40 il 0 nop il 01 ldarg0 il 02 ldnull il 03 ceq il 05 ldci40 il 06 ceq il 08 stloc0 il 09 ldloc0 il 0a brtrues il 0e il 0c brs il 0035 il 0e ldarg0 il 0f callvirt instance string mscorlibsystemexceptionget message il 0014 call void systemsystemdiagnosticsdebugwritelinestring il 0019 nop il 001a ldarg0 il 001b callvirt instance class mscorlibsystemexception mscorlibsystemexceptionget innerexception il 0020 ldnull il 0021 ceq il 0023 stloc0 il 0024 ldloc0 il 0025 brtrues il 0035 il 0027 nop il 0028 ldarg0 il 0029 callvirt instance class mscorlibsystemexception mscorlibsystemexceptionget innerexception il 002e call void ca1programdebugoutputclass mscorlibsystemexception il 0033 nop il 0034 nop il 0035 ret end of method programdebugoutput,['c#'] +530011,use jquery to set select box value to first option i am dynamically populating a select box with options when i do this i want the value of the select box to be the value of the first option a default option if you like sounds really simple but i just cannot get it to workvar myelement selectnamemyname tried the following three variations myelementfindoptionfirstpropselected selected myelementvalmyelementfindoptionsfirstvalmyelementpropselectedindex 0but the following line gives a blank alertalertmyelementvalwhere am i going wrong,"['javascript', 'jquery']" +530063,when multiple java programs run on the same machine each java application will run in a specific java virtual machine instance i am really getting confused on below aspects and googling has confused me even more different articles on different sitesif i have a web service written in java it will need a jvm instance to runso can jvm be made a daemon processif yes when we run any other java application it will use this instance of jvm or create a new onemain memory available in any machine is constant when we start and java processes simultaneously without providing any initial heap size how is the heap size thistributed among processesis there any process that manages and number of jvm instances or is it managed by os itselfwhen stoptheworld happens during an gc are other jvm instancesdifferent threads i assume affected,['java'] +530168,how to make a field required in rails what is the simplest way to make a field required in railsinquiryrbclass inquiry activerecordbase attr accessible address email id gender message mobile number nameend,['ruby-on-rails'] +530225,java 8 where is trifunction and kin in javautilfunction or what is the alternative i see javautilfunctionbifunction so i can do thisbifunctioninteger integer integer f x y return 0 what if that is not good enough and i need trifunction it does not existtrifunctioninteger integer integer integer f x y z return 0 i guess i should add that i know i can define my own trifunction i am just trying to understand the rationale behind not including it in the standard library,['java'] +530249,seekbar in a navigationdrawer i want to use a seekbar in a navigation drawerbasically i need to slide left and right to set the seekbar and well you guessed it it slides the navigation drawerwhat i would like to do is to slide the seekbar when it is focused and the navigationdrawer when it is nothow should i do thathere is my code when setting an item i have not set the seekbar yetprivate view oncritereviewlayoutinflater inflater viewgroup container bundle savedinstancestate view mview inflaterinflaterlayoutfragment critere container false linearlayout mlinearlayout linearlayout mviewfindviewbyidridcritere linearlayout view mviewelement inflaterinflaterlayoutitem critere null textviewmviewelementfindviewbyidridcritere titlesettextprix maximum mlinearlayoutaddviewmviewelement return mviewhere is the item criterexml with the seekbarxml version10 encodingutf8tablelayout xmlnsandroid androidididcritere item androidlayout widthfill parent androidlayout heightwrap content androidstretchcolumns tablerow androidlayout widthfill parent androidlayout heightfill parent textview androidlayout widthwrap content androidlayout heightwrap content androidtextappearanceandroidattrtextappearancemedium androidtextlarge text androidididcritere title androidlayout gravityleftcenter vertical androidlayout column0 seekbar androidlayout widthmatch parent androidlayout heightwrap content androidididcritere qualifier androidlayout column1 androidlayout span4 tablerow tablerow androidlayout widthfill parent androidlayout heightfill parent textview androidlayout widthwrap content androidlayout heightwrap content androidtextappearanceandroidattrtextappearancesmall androidtextmedium text androidididcritere value androidlayout span4 tablerowtablelayoutthanks in advance,['android'] +530254,how do i set mysql temporarily to readonly through the command line i am creating a bash script which among other things gathers some data from a mysql database my mysql user has write privileges but for safety reasons i would like to temporarily set it to a read only state is it possible to do this from a command line,['mysql'] +530291,exact matches with elasticsearch at query time i have a locations index which has lots of location names and their respective countries i then want to know whether we have locations with title berlin in the country with country code de heres my java code attemptsearchresponse response clientpreparesearchlocations setqueryquerybuildersmatchquerytitle berlin setfilterfilterbuilderstermfiltercountry de execute actiongetbut this gives me too many replies eg results for zoo berlin and so on i need exact matches but please note that i have other scenarios where this substringtext search matching is desired is there a way to decide at querying time rather than at indexing time which behaviour exact vs analyzed text one wants,['java'] +530388,how to set component size inside container with boxlayout faced with the problem of using boxlayoutin my example i try to decrease the height of the text field and change the width of the buttons as shown in green marker in the picture i know about the techniques setprefferedsize and setmaximumsize but it did not work as it should the line addboxcreatehorizontalglue also did not helpthanks for any ideapublic class testy extends jpanel public static void mainstring args swingutilitiesinvokelaternew runnable override public void run constructgui private static void constructgui jframe frame new jframetesty framesetdefaultcloseoperationwindowconstantsexit on close jpanel centerpanel new jpanel centerpanelsetbackgroundcolordark gray centerpanelsetpreferredsizenew dimension100 400 frameaddcenterpanel borderlayoutcenter testy eastpanel new testy frameaddeastpanel borderlayouteast framepack framesetvisibletrue public testy setlayoutnew boxlayoutthis boxlayoutpage axis jbutton button new jbuttonbutton 1 buttonsetpreferredsize buttonsetmaximumsize addbutton button new jbuttonbutton 2 buttonsetpreferredsize buttonsetmaximumsize addbutton button new jbuttonbutton 3 buttonsetpreferredsize buttonsetmaximumsize addbutton jlabel label new jlabellabel labelsetpreferredsize labelsetmaximumsize addlabel jtextfield textfield new jtextfield textfieldsetpreferredsize textfieldsetmaximumsize addtextfield button new jbuttonbutton 4 buttonsetpreferredsize buttonsetmaximumsize addbutton addboxcreatehorizontalglue,['java'] +530417,do not create view folder on rails generate controller this is a trivial question but i am curiousis there a way with the usual generators config to turn off the creation of the view folders and action templates when you run a rails generate controlleri cannot find an option anywhere and the code here does not show me any pointerswe are likely going to be building our own controller resource generators at some point anyway for our api but i was curious if there was a way to turn off this annoyance in the meantime,"['ruby-on-rails', 'ruby']" +530422,python record audio on detected sound i am looking to have a python script run in the background and use pyaudio to record sound files when the threshold of the microphone has reached a certain point this is for a monitor on a two way radio network so hence we only want to record transmitted audiotasks in mindrecord audio input on a n gate thresholdstop recording after so many seconds of silencekeep recording for so many seconds after audiophase 2 input data into mysql database to search the recordingsi am looking at a file structure of the similarhomerecodings20138231233wav would be a recording of the transmision on 23082013 1233wavi have used the code fromdetect and record a sound with pythoni am at a bit of a loss where to go from here now and a little guidance would be greatly appreciatedthank you,['python'] +530427,why does consolewriteline block in callback from streamreadasync i have a callback function in which i am trying to write the data that i read in an overriden readasyncprivate void streamcallbackbyte bytes consolewriteline encodingutf8getstringbytes the whole application is blocked here why if ondatareceived null string data encodingutf8getstringbytes ondatareceiveddata the overriden readasync looks as followspublic override async taskint readasyncbyte buffer int offset int count systemthreadingcancellationtoken cancellationtoken var read await originalstreamreadasyncbuffer offset count cancellationtoken readcallbackbuffer return readwhat i actually want to achieve is to monitor a network stream just before it gets parsed by an xmlreader this relates to my other question reading from same sslstream simultaneously how would i do that updateit is actually encodingutf8getstringbytes that is blocking the application in order for the question to be more complete i am listing the code for reading the xml streamusing xmlreader r xmlreadercreatesslstream new xmlreadersettings async true while await rreadasync switch rnodetype case xmlnodetypexmldeclaration break case xmlnodetypeelement,['c#'] +530437,split a string to groups of 2 chars using split i have this simple string a1a2a3is there any regex expression which can be used with split command so it will split the string to a pairs a1a2a3 i have tried this a1a2a3splitbut it returns a 1 a 2 a3psi can do it with match but im looking if exists for the regex expression which can help me using split,['javascript'] +530463,autoprefixer vs lesass mixins the autoprefixer tool is a css postprocessor that adds the correct vendor prefixes to otherwise naive style declarationshow does this compare in terms of effectiveness and developer experience to mixins provided by less and sass for this same goal of generating vendorspecific styles,['css'] +530474,ios ad hoc installation failing i am getting the following error when i try to install an app via testflightappcomunable to download application helloworld could not be installed at this timei have also tried installing via itunes and the apple configuratorwhen i first got this error i thought it might be due to apples developer program being down a few weeks back so i regenerated all my certificates using the code signing request on my laptop then rebuilt all my provisioning profilesi then deleted all the profiles from my iphone and from xcode and i deleted testflight from my phone then i archived the app uploaded to test flight gave permission to all the devices in the profile and sent the notification emails with the download linkwhen i try to download the progress bar gets nearly all the way to the end then the error pops up this is what i see in the console during installation from the iphone configuration utilityspringboard67 warning killing comhelloworldapp for app installationinstalld53 error 0x2c60 handle install install of varmobilemediadownloads2429066128781955904410631401396950200 requested by itunesstoredinstalld53 error 0x2c60 mobileinstallationinstall server installing app comhelloworldappinstalld53 error aug 23 114537 sectrustevaluate leaf criticalextensions issuercommonnameinstalld53 error 0x2c60 verify signer identity misvalidatesignatureandcopyinfo failed for vartmpinstall staginga1ku9yfoo extractedpayloadhelloworldapphelloworld 0xe8008017installd53 error 0x2c60 do preflight verification could not verify executable at vartmpinstall staginga1ku9yfoo extractedpayloadhelloworldappinstalld53 error 0x2c60 install application could not preflight application installitunesstored71 error 0x183b0 mobileinstallationinstall failed with 1installd53 error 0x2c60 handle install api failedso i have got brand new certificates and profiles the profile has the devices i am trying to install embedded and i have given permission to those devices in testflighti am at a loss now i have fixed similar problems to this in the past so i have run out of all my usual ideasand i have tried increasing the version number as well that is worked in the past but no lucki recently moved the project from my users folder to an external hard drive but i have updated all the necessary paths and i can build the app and run it via xcode so i cannot see how that is the problemupdate thanks to jasons answer i have managed to get a different error from the apple configuratora signed resource has been added modified or deleted402620393comapplemdkamderrorupdate for completeness heres the error i get on the iphone when trying to sync via itunesitunes sync helloworld failed to install,['ios'] +530492,force landscape for one view controller ios i have looked at several answers to questions similar but none of the answer worked i have an app where i need everything portait except for one photo viewer i have in the supported orientations section of the targets menu i only have portrait how do i force my one view to be landscape it is being pushed onto the stack from a nav controller but i am using storyboards to control all that,"['iphone', 'ios']" +530497,using count vs num rows to get number of rows in result set there are two waysis to use query to get countqueryselect count as count from some table where typet1and then retrieving the value of countis getting count via num rows in phpso which one is better performance wise,"['php', 'mysql']" +530532,is there a faster way to test if two lists have the exact same elements than pythons built in operator if i have two lists each 800 elements long and filled with integers is there a faster way to compare that they have the exact same elements and short circuit if they do not than using the built in operator a 6238854486b 6238854486a b trueanything better than this i am curious only because i have a giant list of lists to compare,['python'] +530544,draw an item in a static location relative to the qgraphicsview i would like to draw a notification that always appears in the upper right corner of my qgraphicsview however qgraphicsitems positions are specified in scene coordinates so if the user pannedzoomed to view a different part of the scene this notification would move off screeni have figured out that i could simulate this behavior by moving and scaling the notification any time the current view changes but this seems terribly ineffective and not at all elegantit seems that qgraphicsview should support this kind of behavior the docs mention a flag itemispanel that sounds hopeful but mentions nothing about static placement in the view itemignorestransformations also will help with scalingzooming but not panningis there any builtin qt functionality that supports this behavior,['c++'] +530559,python sort list with none at the end i have homogeneous list of objects with none but it can contain any type of values example l 1 3 2 5 4 none 7 sortedlnone 1 2 3 4 5 7 sortedl reversetrue7 5 4 3 2 1 noneis there way without reinventing the wheel to get list sorted usual for python way but none values at the end of the list like that1 2 3 4 5 7 nonei feel like here can be some trick with key parameter,['python'] +530574,corebluetooth central manager cannot thiscover peripheral in background i have an application that is utilizing bluetooth 40 le the application allows the device to act as a central and a peripheral i want the application to run in the background i have included the uibackgroundmodes with bluetoothcentral and bluetoothperipheral in the infoplist already i am running the application on two different devices that are bluetooth 40 le enabledwhen both devices are running in the foreground everything works perfectly and information is passed both ways when one device is running in the foreground and the other is running in the background the device running in the background is able to scan and advertise but unable to thiscover the other device that is running in the background the device that is running in the foreground is able to thiscover and connect to the device that is running in the backgroundafter reading through apples core bluetooth programming guide i know that connecting to another device and sharing information both ways is possiblei can post any more information upon request thank you,['ios'] +530636,memory usage keep growing with pythons multiprocessingpool heres the programusrbinpythonimport multiprocessingdef dummy funcr passdef worker passif name main pool multiprocessingpoolprocesses16 for index in range010 poolapply asyncworker callbackdummy func clean up poolclose pooljoini found memory usage both virt and res kept growing up till closejoin is there any solution to get rid of this i tried maxtasksperchild with 27 but it did not help eitheri have a more complicated program that calles apply async 6m times and at 15m point i have already got 6g res to avoid all other factors i simplified the program to above versioneditturned out this version works better thanks for everyones inputusrbinpythonimport multiprocessingready list def dummy funcindex global ready list ready listappendindexdef workerindex return indexif name main pool multiprocessingpoolprocesses16 result for index in range010 resultindex poolapply asyncworker index callbackdummy func for ready in ready list resultreadywait del resultready ready list clean up poolclose pooljoini did not put any lock there as i believe main process is single threaded callback is more or less like a eventdriven thing per docs i readi changed v1s index range to 10 same as v2 and did some tests it is weird to me v2 is even 10 faster than v1 33s vs 37s maybe v1 was doing too many internal list maintenance jobs v2 is definitely a winner on memory usage it never went over 300m virt and 50m res while v1 used to be 370m120m the best was 330m85m all numbers were just 34 times testing reference only,['python'] +530684,how to dynamically add row to html table i got a aspnet mvc 40 web application which enable user to dynamically add rows to html tablein my viewdelliveclick function id var rowcount optionstable trlength if rowcount 2 thisparentparentremove addliveclick function id var master thisparentstabledynatable get a new row based on the prototype row var prot masterfindprototypeclone protattrclass protfindidattrvalue id masterfindtbodyappendprottable classdynatable idoptionstable width100 styletextaligncenter border1 tr classprototype htmleditorform modelchillerdetails referring to the template tr theadtablein my template control languagec inheritssystemwebmvcviewusercontrolgmismodelsgmisebmodelschillerplantdetails div idchillerplantdetails td htmleditorform mchillerage td td htmleditorform mchillerbrand td td htmleditorform mchillercapacity td td htmleditorform mchillerrefrigerant td td a href classaddimg src urlcontentcontentimagesaddpng nbspa href classdelimg src urlcontentcontentimagesremovepng tddivin my modelpublic class addhealthcheckformmodel public listchillerplantdetails chillerdetails get set public class chillerplantdetails requirederrormessage please enter chiller capacity thisplayname chiller capacity public string chillercapacity get set requirederrormessage please enter age of chiller thisplayname age of chiller public string chillerage get set requirederrormessage please enter chiller brand thisplayname chiller brand public string chillerbrand get set requirederrormessage please enter chiller refrigerant thisplayname chiller refrigerant public string chillerrefrigerant get set now the question comes to how can i capture the data in the dynamically added rows into my controller and save into database,"['javascript', 'asp.net']" +530719,overiding destructor of stdexception the following program does not compile in g 44 if line 8 is commented why it seems that when i override stdexception constructor i must override its destructor as well whats the reason for thisincludeiostreamincludeexceptionusing namespace stdclass a public exception public astring msg msgmsg a throw line 8 const char what const throw return msgc str private string msgint mainthe compilation error iserror looser throw specifier for avirtual a,['c++'] +530727,laravel 4 extending a section declared in a master template more than once i have a scenario where i have a master template which defines a header section it looks like thisdoctype htmlhtmlheadsectionheader htmlstylecssplanesaleingcss htmlscriptjsjquery1101js htmlscriptjssearch barjs showheadbody div classplanesaleing page headeryieldheader baryieldnav baryieldsearch bar header div classmain page some more code divyieldfooter divbodyhtmlas you can see i have several child views eg nav bar and search bar each of these child views has an accompanying js file so i would like to extend the header section in nav bar like thissectionheaderparent htmlscriptjsanotherjsjs stopand then again in search bar like thissectionheaderparent htmlscriptjsyetanotherjsjs stopthe intention is that the final outputted html file would look like this sectionheader htmlstylecssplanesaleingcss htmlscriptjsjquery1101js htmlscriptjssearch barjs htmlscriptjsanotherjsjs htmlscriptjsyetanotherjsjs show however only the first one actually extends the header all others after this are seemingly ignored is there anyway to use multiple extensionsany advice much appreciated,['php'] +530756,how to change eclipse html formatting when i open an html file in eclipse after i format it it looks like thisform fieldset label formembernamelogin namelabel input typetext namemembername idmembername value classtext uiwidgetcontent uicornerall label formemberpasspasswordlabel input typepassword namememberpass idmemberpass value classtext uiwidgetcontent uicornerall fieldset formbut i want each tag with all of its attributes on the same linehow do i make eclipse understand that,['html'] +530762,returning stdmovef in stdfor each i am writing an implementation of standard c library for studythe c11 standard says that for each returns stdmoveftemplate class inputiterator class functionfunction for eachinputiterator first inputiterator last function freturns stdmovefi thought that function scope local variable is moveconstructed when it is returnedshould i return movef explicitly,['c++'] +530804,in winrt c how do i save an offscreen xaml tree using rendertargetbitmap the following code throws a cryptic systemargumentexception from the renderasync method value does not fall within the expected range if on the other hand my canvas is part of a visible xaml tree it works is it impossible to render some xaml that is not thisplayed on screencanvas c new canvascwidth 40cheight 40cbackground new solidcolorbrushcolorfromargb0xff 0x80 0xff 0x80rendertargetbitmap x new rendertargetbitmapawait xrenderasyncci almost thought this answer would work but no luck i guess it only applies to wpf create wpf element offscreen and render to bitmapupdateso far my best idea is to put the canvas i want to render to into the currently visible page but place it beneath what is normally the root uielement that fills the screen so it is not visible to the usergrid canvas xnamehiddencanvas grid xnamemainelement backgroundstaticresource applicationpagebackgroundthemebrush gridgridit is not beautiful but it seems to work lets see if anyone can do better,['c#'] +530830,no privileges on wamp server phpmyadmin i installed wamp on windows 8 and i am having problems with mysql privileges in phpmyadmin here you can see the screenshotas you can see there is no privileges tab and i cannot a create new database,['mysql'] +530846,missingschemaerror schema has not been registered for model i have a typical project with nodejs express 3 mongodbi am trying to make a query to my model tweet in my routesindexjs and when i run my app crashed24 aug 113507 nodemon starting node appjsapplicationsxamppxamppfileshtdocsocesafanocesanode modulesmongooselibindexjs286 throw new mongooseerrormissingschemaerrorname missingschemaerror schema has not been registered for model teewtuse mongoosemodelname schemaat mongoosemodel applicationsxamppxamppfileshtdocsocesafanocesanode modulesmongooselibindexjs28613at objectanonymous applicationsxamppxamppfileshtdocsocesafanocesaroutesindexjs633at module compile modulejs45626at objectmodule extensionsjs modulejs47410at moduleload modulejs35632at functionmodule load modulejs31212at modulerequire modulejs36417at require modulejs38017at objectanonymous applicationsxamppxamppfileshtdocsocesafanocesaappjs714at module compile modulejs4562624 aug 113507 nodemon app crashed waiting for file changes before startingthis is part of my appjsvar mongoose requiremongoosemongooseconnectmongodblocalhostfanocesavar schema mongooseschemavar objectid schemaobjectidvar teewt new schema cuerpo stringvar teewt mongoosemodelteewt teewtvar app expressappsetport processenvport 30appsetviews dirname viewsappsetview engine jadeappuseexpressfaviconappuseexpressloggerdevappuseexpressbodyparserappuseexpressmethodoverrideappuseapprouterappuseexprestaticpathjoin dirname public development onlyif development appgetenv appuseexpresserrorhandlerappget routesindexappgetusers userlistand this is part of my indexjsvar teewt requiremongoosemodelteewtteewtfind functionerr docs consolelogdocs consolelogdocsexportsindex functionreq res resrenderindex docs docs which would be the correct way to do this query,['javascript'] +530858,why do we need alink why not just a it seems the following variants produce identical results 1 a avisited aactive color black ahover color red 2 a alink avisited aactive color black ahover color red 3 alink avisited aactive color black ahover color red most guidance on the web uses 2 or 3 why not go for the simplest variant which is 1 i cannot find a good reason to ever apply link if all you need is one style for normal links and one for hoveris it bestpractice to not use link why or why noti do not care whether the link is visited or not both receive the same style i only care about hover or not hover this question is not about what the variants do all do the same thing it is about what the best variant is is one of the variants faulty which one is bestpractice,"['html', 'css']" +530877,how to update and include twitter bootstrap 3 on webapp or yo angular i used yo webapp or yo angular to create new a project and i received bootstrap include is version 232 but i want use the latest version of bootstraphow can i update the bootstrap package with command prompt and later update when create new webapp or yo angular choose include twitter bootstrap is last version,['css'] +530882,apache is downloading php files instead of thisplaying them os and server informationcentos 64 finalapache 2215php 551i previously had php 53x installed but decided to upgrade i first uninstalled the php 53x and then installed php 551 but after the installation completed apache did not parse the php files it just downloaded them i have checked similar questions here in stackoverflow but none of them have helped me so farfor the record i have the following lines in my httpdconf and phpconf that should make php work but do notaddhandler applicationxhttpdphp php5 php4 php php3 php2 phtmladdtype applicationxhttpdphp php5 php4 php php3 php2 phtmladdtype applicationxhttpdphpsource phpsaddhandler php5script phpi would really appreciate any helpthank youediti have these lines in the phpconfifmodule workerc loadmodule php5 module moduleslibphp5soifmoduleifmodule workerc loadmodule php5 module moduleslibphp5ztssoifmoduleeditby removing the addtype applicationxhttpdphp php5 php4 php php3 php2 phtmlapache no longer downloads the file now apache is showing the source code but not all of it just part i addedaddtype texthtml phpbut no luck,['php'] +530884,what are the consequences of omitting autoreleasepool in main why do the xcode 4x templates for objectivec commandline and ios programs add the autoreleasepool part wrapping mains code note that this does not happen for the os x application templatewhy do not os x applications do the same why do not both use the same methodfinally since all memory is released when any program exits why is all of this of practical importanceor to ask it differently what are the practical consequences of omitting autoreleasepool in main for a command line or an ios objectivec programthese two pieces of code compile and seem to work equivalently1int mainint argc const char argv autoreleasepool nsarray array hello world nslog array0 return 02int mainint argc const char argv nsarray array hello world nslog array0note i only care about the explanation in the arc context arc forbids the explicit use of autorelease,['objective-c'] +530985,python vectorizing a sliding window i am trying to vectorize a sliding window operation for the 1d case a helpful example could go along the lines of x vstacknparrayrange10nparrayrange10x1npwherex05x00x1x01x1the n1 value for each current value for indices 5 but i get this errorx1npwherex02x00x1x01x1indexerror index 10 out of range 0index9 in dimension 1curiously i wouldnt get this error for the n1 value which would mean indices smaller than 0 it does not seem to mindx1npwherex05x00x1x01x1printx0 1 2 3 4 5 6 7 8 9 0 0 1 2 3 5 6 7 8 9is there anyway around this is my approach totally wrong any comments would be appreciatededit this is what i would like to achieve i flatten a matrix to an numpy array on which i want to calculate the mean of the 6x6 neighborhood of each cellmatriz nparray12345 65432 11223 33221 32132 12312 matrix to vectorvector2 ndarrayflattenmatrizncols intshapematriz1nrows intshapematriz0vector npzerosnrowsncolsdtypefloat64 interior pixelsif i ncols 0 and i1 ncols 0 and incols and incolsnrows1 vectori npmeannparrayvector2incols1vector2incolsvector2incols1vector2i1vector2i1vector2incols1vector2incolsvector2incols1,['python'] +531094,kill python interpeter in linux from the terminal i want to kill python interpeter the intention is that all the python files that are running in this moment will stop without any informantion about this filesobviously the processes should be closedany idea as delete files in python or destroy the interpeter is ok d i am working with virtual machinei need it from the terminal because i write c code and i use linux commandshope for help,['python'] +531124,css backgroundsize cover replacement for mobile safari hi i have several divs on my page which have background images that i want to expand to cover the entire div which in turn can expand to fill the width of the viewportobviously backgroundsize cover behaves unexpectedly on ios devices i have seen some examples of how to fix it but i cannot make them work in my situation ideally i would prefer not to add extra img tags to the html but if it is the only way then i willhere is my htmlbody div idsection1 clasection div div idsection2 clasection div div idsection3 clasection divbodyand the csection margin 0 auto position relative padding 0 0 320px 0 width 100section1 background url 50 0 norepeat fixed backgroundsize cover section2 background url 50 0 norepeat fixed backgroundsize cover section3 background url 50 0 norepeat fixed backgroundsize cover the question is how can i get the background image to completely cover the section div taking into account the variable width of the browser and the variable height of the content in the div,"['html', 'css']" +531155,android gcm message successfully sent but not received i am trying to use the gcm service to send push notifications to my devicesi have followed the android hive tutorial which is now deprecated like many other questions and answers about this for the serverside functions which look to work as expected since i can get this kind of outputs multicast id9131068334342174816success1failure0canonical ids0resultsmessage id013774410988274431d84a26ff9fd7ecdbut according to some answers receiving this response just means that the message has been accepted by gcm servers for sending but not that it has been sent so as expected my broadcastreceiver does not receive anythingheres my broadcastreceiver code public class gcmbroadcastreceiver extends broadcastreceiver override public void onreceivecontext context intent intent logigcm debug pushreceiver onreceive called bundle extras intentgetextras googlecloudmessaging gcm googlecloudmessaginggetinstancecontext string msgtype gcmgetmessagetypeintent ifextrasisempty ifgooglecloudmessagingmessage type send errorequalsmsgtype logigcm debug message send error else ifgooglecloudmessagingmessage type deletedequalsmsgtype logigcm debug message deleted else ifgooglecloudmessagingmessage type messageequalsmsgtype logigcm debug message received extrastostring setresultcodeactivityresult ok and my androidmanifest usespermission androidnameandroidpermissioninternetusespermission androidnameandroidpermissionaccess network stateusespermission androidnameandroidpermissionwrite external storage usespermission androidnameandroidpermissionget accounts usespermission androidnamecomgoogleandroidprovidersgsfpermissionread gservices usespermission androidnamecomgoogleandroidc2dmpermissionreceive permission androidnamemyapermissionc2d message androidprotectionlevelsignature usespermission androidnamemyapermissionc2d message require opengl es2 for gmap usesfeature androidglesversion0x020 androidrequiredtrue because this app is using the gcm library to send messages the min sdk cannot be lowerthan 8 usessdk androidminsdkversion8 androidtargetsdkversion18 application androidallowbackuptrue androidicondrawableic launcher androidlabelstringapp name androidthemestylelovrtheme receiver androidnamegcmbroadcastreceiver androidpermissioncomgoogleandroidgcmc2dmpermissionsend intentfilter action androidnamecomgoogleandroidc2dmintentreceive action androidnamecomgoogleandroidc2dmintentregistration category androidnamemyapp intentfilter receiver service androidnamegcmintentservice and the serverside code url fields array registration ids arraydstregid delay while idle true data arraymessage message headers array authorization key google api key contenttype applicationjson ch curl init curl setoptch curlopt url url curl setoptch curlopt httpheader headers curl setoptch curlopt returntransfer true curl setoptch curlopt ssl verifypeer false curl setoptch curlopt postfields json encodefields result curl execch ifresult false diecurl failed curl closech echo resulti am coding from home so i assume that gcm would not have problems getting in and out of the network since gcm uses a kind of reverseshell connection anyway i do not receive any of the log output i am expectingeditafter leaving my app running for a while logcat sent me the following outputs 0826 048984 1796617966 dgcm ignoring attempt to send heartbeat on dead connection0826 01490 1796617966 dgcm ignoring attempt to send heartbeat on dead connection0826 0201672 433448 wbroadcastqueue permission denial broadcasting intent actcomgoogleandroidc2dmintentreceive flg0x10 pkgmyapp has extras from comgoogleandroidgsf pid17966 uid103 requires comgoogleandroidgcmc2dmpermissionsend due to receiver comnavissallovrcomnavissallovrgcmbroadcastreceiver0826 001709063 1796617966 dgcm ignoring attempt to send heartbeat on dead connection0826 001809086 1796617966 dgcm ignoring attempt to send heartbeat on dead connection0826 002415250 39363951 vmeshclient uri beaconewtkyffdwftlzome7rnizvctnuu9t3sbjgkce72ogohyhgiyab1qikytbeu2nc02qwddtqi4sx7hhu6gpdql8zzdkxfxmcics6zgjmr84yvmx1x9eqdyyw1ui6pehoob9mv4r msq mewfnwuzqrvvgtycktsnkmmirezm1caie 7hdu ustbhz0dhl7cafmhyf74iqi6eyfceorxgv2wts4lshrwekfezubhvind7tecvpquohdvwgmndo qwlo0rpusnfegdfjcyy4l8fzjogpsxdqw2cfsz2s0kujch9uirljfutsgcm5gcfujrq8vwitp07mqpmq7h2fggpxqvjimfcvp81erkvzvlyu3bnpjyqe6mhxsfezrg37kdp2fd3lixfzzsjkllileysdk9rryqo8fey3ph07et1hjqywrhv7wnjcqm6ttyzu914ordpbawx9d3wvbdqlplqxnuwj1huutwaikotplgrazo3mc5vi93vts3row,"['php', 'android']" +531180,how to sort map i have map like thatmapinteger myentry map new hashmapinteger myentrymyentry is thatpublic class myentry private string title private string value public string gettitle return title public void settitlestring title thistitle title public string getvalue return value public void setvaluestring value thisvalue value after putting values in map i want to sort it first element to be smallest and the last element to be biggest,['java'] +531188,can virtual functions be inlined if i define a class like thisclass apublic a virtual a virtual void funcdoes it mean that that the virtual destructor and func are inlined,['c++'] +531198,lambda functions as base classes playing around with lambdas i found an interesting behaviour that i do not fully understandsupose i have a struct overload that derives from 2 template parameters and has a using f1operator clausenow if i derive from two functors i can only access the operator of f1 as i would expectif i derive from two lambda functions this is no longer true i can access the operator from f2 tooinclude iostream i compiled with g gcc 472 20121109 red hat 4728 g wall stdc11 g maincc g wall stdc11 dfunctor g maincc or clang clang version 33 tagsrelease 33rc2 clang wall stdc11 g maincc clang wall stdc11 dfunctor g maincc on a linux localhostlocaldomain 396200fc18i686 1 smp thu jun 13 192940 utc 2013 i686 i686 i386 gnulinux boxstruct functor1 void operator stdcout functor1operatorn struct functor2 void operatorint stdcout functor2operatorintn template typename f1 typename f2struct overload public f1 public f2 overload f1 f2 overloadf1 x1 f2 x2 f1x1 f2x2 using f1operator template typename f1 typename f2auto getf1 x1 f2 x2 overloadf1 f2 return overloadf1 f2x1 x2int mainint argc char argv auto f getfunctor1 functor2 fifdef functor f2 this one does not work imho correctlyendif auto f1 get stdcout lambda1operatorn int stdcout lambda2operatorintn f1 f12 this one works but i do not know why return 0the standard states thatthe type of the lambdaexpression which is also the type of the closure object is a unique unnamed non union class typeso every lambdas types should be uniquei cannot explain why this is so can anyone shed some light on this please,['c++'] +531231,char argument confusion void funcchar arg1int main char container3 first second third char pcon container0 funcpcon this works funccontainer0 no known conversion from char to chari am clearly missing something here my logic says that these two should be the same thing,['c++'] +531238,how to change app theme from ordinary blank activity to masterdetail flow i have an application that works on the basic theme blank activity and what i would like to do is to change it to a masterdetail flow theme i do know that this will make my application work on android sdk 11 android 30 honeycomb that is ok with me the issue is i do not know where to start from what are the basic steps to make this big conversion i could not find any example to help me out with this issue what should i be looking for i am sure this has been done can you at least please give me some pointer on how to do thismy application is not that complicated it uses activities async tasks db custom lists it is very basic i use the custom list to thisplay data and when i click on it it thisplays much more details so i thought what better way to do this in a more professorial matter than the masterdetail flow if you have any tutorial regarding the masterdetail flow that you can hook me up with that might help,"['java', 'android']" +531239,how do i resolve missing host to link to please provide the host parameter ror i am following the ror tutorial and i am stuck at listing 915 i getting the following error after running bundle exec rspec spec 1 authentication authorization as wrong user submitting a patch request to the usersupdate action failureerror specify expectresponseto redirect toroot url argumenterror missing host to link to please provide the host parameter set default url optionshost or set only path to true specfeaturesauthentication pages specrb79in block 5 levels in top requiredmy authentication test code is require spec helperdescribe authentication type request do subject page describe signin page do before visit signin path it should have contentsign in it should have titlesign in end describe signin do before visit signin path describe with invalid information do before click button sign in it should have titlesign in it should have selectordivalertalerterror text invalid describe after visiting another page do before click link home it should not have selectordivalertalerterror end end describe with valid information do letuser factorygirlcreateuser before sign in user it should have titleusername it should have linkprofile href user pathuser it should have linksettings href edit user pathuser it should have linksign out href signout path it should not have linksign in href signin path describe followed by signout do before click link sign out it should have linksign in end end end describe authorization do describe for nonsignedin users do letuser factorygirlcreateuser describe in the users controller do describe visiting the edit page do before visit edit user pathuser it should have titlesign in end describe submitting to the update action do before patch user pathuser specify expectresponseto redirect tosignin path end end end describe as wrong user do letuser factorygirlcreateuser letwrong user factorygirlcreateuser email before sign in user no capybara true describe visiting usersedit page do before visit edit user pathwrong user it should not have titlefull titleedit user end describe submitting a patch request to the usersupdate action do before patch user pathwrong user specify expectresponseto redirect toroot url end end endendi do not know how to resolve this issue so the test passes how do i resolve it could someone explain whats going wrong according to the tutorial the test should be passing,"['ruby-on-rails', 'ruby']" +531371,find duplicate value in multidimensional array from a function i am given a multidimensional array like thisarray 0 array 0 7 1 18 1 array 0 12 1 7 2 array 0 12 1 7 2 13 i need to find duplicate values in the 3 arrays within the main array for example if value 7 repeats in the 3 arrays return 7,['php'] +531387,overflowauto not working in touch devicesios i have implemented a website using twitter bootstrap at the top of the site i have used a nav bar and inside that used a dropdown menu the dropdown menu is made up of ul and li tags i am showing a list of members inside that dropdwon menu when the list of member grows the dropdown menu grows horizontally for which i have added a overflow auto to the dropdownmenu class now its showing an vertical scroll bar and working fine in browser but the same thing is not working in ipad and other ios devices i have googled it and found webkitoverflowscrolling touch should work but it is not working for me lot of other solutions are also present but unfortunately not working for meis there any better solution available may be anything we can do using css itself,"['javascript', 'css']" +531396,menuitemcompatgetactionview always returns null i just implemented the v7 appcompat support library but the menuitemcompatgetactionview always return null in every android version i tested 422 234 the searchview is thisplayed in action bar but it does not respond to touch actions and does not expand to show its edittext and is just like a simple iconoverridepublic boolean oncreateoptionsmenumenu menu menuinflater inflater getmenuinflater inflaterinflatermenumenu menu menuitem searchitem menufinditemridaction search searchview searchview searchview menuitemcompatgetactionviewsearchitem if searchview null searchviewcompatsetonquerytextlistenersearchview monquerytextlistener searchviewseticonifiedbydefaultfalse logdtagsearchview not null else logdtag searchview is null return superoncreateoptionsmenumenumenuxmlxml version10 encodingutf8menu xmlnsandroid xmlnsapp item androidididaction search appshowasactionalwayscollapseactionview androidicondrawableabc ic search androidtitlestringaction bar search androidactionviewclassandroidsupportv7widgetsearchview item androidididaction refresh androidicondrawablerefresh androidtitlestringaction bar refresh appshowasactionifroommenu,['android'] +531415,why is dynamic cast evil or not should i use dynamic cast in this case some say the use of dynamic cast often means bad design and dynamic cast can be replaced by virtual functionswhy is the use of dynamic cast considered bad designsuppose i have i function name funcanimal animal int animaltype the implementation in func is likebool funcanimal animal int animaltype animal is the base class of bear panda fish dynamic cast animal to real animalsbear panda fish according to animaltype do some processing with this specific type of animal using its additional information beyond base class animal is this case a proper use of dynamic cast,['c++'] +531419,is there a 128 bit integer in c i need to store a 128 bits long uuid in a variable is there a 128bit datatype in c i do not need arithmetic operations i just want to easily store and read the value very fasta new feature from c11 would be fine too,['c++'] +531438,increasing the command timeout for sql command i have a little problem and hoping someone can give me some advice i am running a sql command but it appears it takes this command about 2 mins to return the data as there is a lot of data but the default connection time is 30 secs how do i increase this and apply it to this command public static datatable runtotalsstring assetnumberv string assetnumber1v datatable dtgetruntotals try dtgetruntotals new datatablegetruntotals sqlparameter assetnumber new sqlparameterassetnumber sqldbtypevarchar 6 assetnumbervalue assetnumberv sqlparameter assetnumber new sqlparameterassetnumber sqldbtypevarchar 10 assetnumbervalue assetnumberv sqlparameter assetnumber1 new sqlparameterassetnumber1 sqldbtypevarchar 10 assetnumber1value assetnumber1v sqlcommand scgetruntotals new sqlcommandexec spruntotals assetnumberassetnumber1 dataaccessassetconnection scgetruntotalsparametersaddassetnumber scgetruntotalsparametersaddassetnumber scgetruntotalsparametersaddassetnumber1 sqldataadapter sdagetruntotals new sqldataadapter sdagetruntotalsselectcommand scgetruntotals sdagetruntotalsfilldtgetruntotals return dtgetruntotals catch exception ex messageboxshowerror retriving totals details processed with this error exmessage return null,"['c#', 'sql']" +531504,code completion to in android studio a question about the editor i am not sure how to briefly phrase the question so i could not find an answeri have just moved from eclipse to android studio on the mac if in a layout file i start typing androidau assuming i want to choose autotext see screenshothow can i get the completion to go upto the to of auto so that i just have to type the t and then enter to choose autotextsince there are no options without the to i should be allowed to select itplease let me know if my explanation is not clear enough,['android'] +531543,alexa rank to traffic estimation formula anybody have some idea how we can convert alexa rank to estimate the daily visitors of a website previous we can easily do this by alexa site reach percentage but alexa reach is no more available previous i am using this forumulavisitors 20reach100how can we estimate now with alexa rank,['php'] +531580,nullpointerexception in hardwarerenderer i wish i had more information about this error but i just do not i have a tool called bugsensenow it is splunk mint that sends crashes to a remote server and this is all i am gettingjavalangnullpointerexceptionat androidviewhardwarerendererglrenderercheckcurrenthardwarerendererjava960at androidviewhardwarerenderergl20rendererdestroylayershardwarerendererjava1148at androidviewviewrootimpldestroyhardwareresourcesviewrootimpljava576at androidviewviewrootimplperformtraversalsviewrootimpljava973at androidviewviewrootimplhandlemessageviewrootimpljava2448at androidoshandlerthispatchmessagehandlerjava99at androidoslooperlooplooperjava137at androidappactivitythreadmainactivitythreadjava4482at javalangreflectmethodinvokenativenative methodat javalangreflectmethodinvokemethodjava511at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava787at comandroidinternaloszygoteinitmainzygoteinitjava554at dalviksystemnativestartmainnative methodthe interesting thing is that all of the error instances came from blu dash 40they are all rootedthey all had mobile net turned offthey all had at least 12 running appsso what do you think has anyone had a npe in the hardwarerenderer classcould it be a root thing ie an issue with the device being rootedcould it be a hardware thing ie an issue with the blue dash 40,"['java', 'android']" +531585,jquery animate stop scrolling when user scrolls manually i have set up a snippet that scrolls a page section into view when it is clicked the problem is that if the user wants to scroll in the middle of the animation the scroll kinda stutters section clickfunctione htmlbodyanimate scrolltop thispositiontop slow return false how can i stop the jquery animation if the user scrolls manually,"['javascript', 'jquery', 'css']" +531597,how to inject spring bean for factory method requiring myclassclass parameter i am trying to inject a javautilprefspreferences bean in to my master controller the controller looks likecontrollerclass mycontroller autowired private preferences preferencesthe applicationcontextxml file creates the bean for javautilprefspreferences it uses a factory method so i have the following entry for creating the beanbean idpreferences classjavautilprefspreferences factorymethodusernodeforpackage preferencesusernodeforpackageparam takes for a parameter the class related to the preference in this case spring needs to create the bean by performing the call preferencesusernodeforpackagemycontrollerclasshow can a class be passed in to a spring bean instantiated with a factory methodthanksenvironment informationjava 7spring 31,['java'] +531703,setting up the licensing verification library on android studio imtriyng to implement the google licensing verification in a android studio made appby following this lines seems tath as an alternative to adding the lvl as a library project you can copy the library sources directly into your application to do so copy or import the lvls librarysrccom directory into your applications src directoryi have do this but the import ofimport comgoogleandroidvendinglicensinglicensecheckerimport comgoogleandroidvendinglicensinglicensecheckercallbackfailsearching on google i have been noticed that i need to modify the buildgrade file on my project but i cannot find a specific solutionhow can i reference the lvl in my android studio projectthere is some tutorial or examplethankslorenzo,['android'] +531705,have a wpf application ignore dpi settings i have a wpf application that is designed for a 1900x1200 resolution but some of our users have used the windows thisplay settings to resize everything by 125150 is there a way to have an application ignore those settings and still thisplay normallyi have seen something called setprocessdpiaware here but havent had any luck with ithere is a screen shot of the application with the thisplay scaling turned up to 150as you can see the application is way too small and there is no way to get it to be correctly sized,['c#'] +531723,nginx add header not working i am having an intriguing problem where whenever i use add header in my virtual host configuration on an ubuntu server running nginx with php and phpfpm it simply does not work and i have no idea what i am doing wrong here is my config fileserver listen 80 listen for ipv4 this line is default and implied listen 80 default ipv6onlyon listen for ipv6 root varwexamplecomwebroot index indexhtml indexhtm indexphp make site accessible from server name wexamplecom max request size client max body size 20m enable gzip compression gzip on gzip static on gzip min length 10 gzip proxied expired nocache nostore private auth gzip types textplain textcss applicationxjavascript textxml applicationxml applicationxmlrss textjavascript add header accesscontrolalloworigin add header accesscontrolallowcredentials true add header accesscontrolallowheaders authorizationcontenttypeacceptoriginuseragentdntcachecontrolxmxreqtoken add header accesscontrolallowmethods get post options put delete add header ps 1 location first attempt to serve request as file then as directory then fall back to indexhtml try files uri uri indexphpquery string uncomment to enable naxsi on this location include etcnginxnaxsirules location cssjsasfasxwaxwmvwmxavibmpclassdivxdocdocxeotexegifgzgzipicojpgjpegjpemdbmidmidimovqtmp3m4amp4m4vmpegmpgmpemppodbodcodfodgodpodsodtoggogv 1 year 315360 expires 500s access log off log not found off add header pragma public add header cachecontrol maxage315360 public pass the php scripts to fastcgi server listening on 12700190 location php fastcgi split path info php note you should have cgifix pathinfo 0 in phpini with php5cgi alone fastcgi pass 12700190 with php5fpm fastcgi pass unixvarrunexamplesock fastcgi index indexphpquery string include fastcgi params instead i want to get the value from origin request header deny access to hidden files location deny all access log off log not found off error page 403 403server listen 80 server name examplecom rewrite request uri permanenti have tried adding the headers to the other location sections but the result is the sameany help appreciated,['php'] +531732,eclipse hangs on startup i have problem with running my eclipse i tried 37 42 and 43 versions with java 6 and java 7 nothing can help me it shows me popup screen but it does not start to load i dont have chance to choose workspacestarting it with debug console parameters shows that it stops running in this momenttime to load bundles 10starting application 6374osgi i have started jvisualvm but i cannot observe anything special there are no deadlocks etceditmy observations were to deep after 60s pid of eclipse is deadedit 2now it stops on time to load bundles 8orgeclipsem2elogbackconfiguration the orgeclipsem2elogbackconfiguration bundle was activated before the state location was initialized will retry after the state location is initializedstarting application 3557edit 3i have managed to start it but only with clean parameter and with choosing workspace from command line data parameter,['java'] +531781,is nsurlcache persistent across launches i am looking for a network caching solution for my ios application that is persistent across launches i started to read about nsurlcache but did not see any mention regarding persistence does anyone know how this behaves when you use nsurlcache then close and open the app does it persist,['ios'] +531809,continue in cursorforeach i am building an app using meteorjs and mongodb and i have a question about cursorforeachi want to check some conditions in the beginning of each foreach iteration and then skip the element if i do not have to do the operation on it so i can save some timehere is my code fetch all objects in someelements collectionvar elementscollection someelementsfindelementscollectionforeachfunctionelement if elementshouldbeprocessed false here i would like to continue to the next element if this one does not have to be processed else this part should be avoided if not neccessary dosomelengthyoperation i know i could turn cursor to array using cursorfindfetch and then use regular forloop to iterate over elements and use continue and break normally but i am interested if there is something similiar to use in foreach,['javascript'] +531817,ant not working in eclipse kepler java virtual machine launcher a java exception has occured i recently upgraded to eclipse kepler and am having issues with ant i am getting the java virtual machine launcher a java exception has occurred error no matter which target i choose in my build filesi tried reinstalling my jdk and i still get the error i am running the 7u25 version of the jdk i have my java home environment variable set to cprogra1javajdk170 25 so i do not think this is the problem what else could be causing the problemedit i also tested ant in the command line and it works just fine is this a bug in kepleredit 2 here is the log of the errorsorgeclipsecoreruntimecoreexception could not find one or more classes orgapachetoolsantbuildlogger please check the ant classpathat orgeclipseantcoreantrunnerproblemloadingclassantrunnerjava467at orgeclipseantcoreantrunnerrunantrunnerjava380at orgeclipseantinternallaunchinglaunchconfigurationsantlaunchdelegateruninsamevmantlaunchdelegatejava307at orgeclipseantinternallaunchinglaunchconfigurationsantlaunchdelegatelaunchantlaunchdelegatejava260at orgeclipsedebuginternalcorelaunchconfigurationlaunchlaunchconfigurationjava858at orgeclipsedebuginternalcorelaunchconfigurationlaunchlaunchconfigurationjava707at orgeclipsedebuginternalcorelaunchconfigurationlaunchlaunchconfigurationjava700at orgeclipsecoreexternaltoolsinternalmodelexternaltoolbuilderlaunchbuildexternaltoolbuilderjava181at orgeclipsecoreexternaltoolsinternalmodelexternaltoolbuilderdobuildbasedonscopeexternaltoolbuilderjava169at orgeclipsecoreexternaltoolsinternalmodelexternaltoolbuilderbuildexternaltoolbuilderjava88at orgeclipsecoreinternaleventsbuildmanager2runbuildmanagerjava726at orgeclipsecoreruntimesaferunnerrunsaferunnerjava42at orgeclipsecoreinternaleventsbuildmanagerbasicbuildbuildmanagerjava199at orgeclipsecoreinternaleventsbuildmanagerbasicbuildbuildmanagerjava239at orgeclipsecoreinternaleventsbuildmanager1runbuildmanagerjava292at orgeclipsecoreruntimesaferunnerrunsaferunnerjava42at orgeclipsecoreinternaleventsbuildmanagerbasicbuildbuildmanagerjava295at orgeclipsecoreinternaleventsbuildmanagerbasicbuildloopbuildmanagerjava351at orgeclipsecoreinternaleventsbuildmanagerbuildbuildmanagerjava374at orgeclipsecoreinternalresourcesworkspacebuildinternalworkspacejava514at orgeclipsecoreinternalresourcesworkspacebuildworkspacejava423at orgeclipsedebuginternalcorelaunchconfigurationlaunchlaunchconfigurationjava830at orgeclipsedebuginternalcorelaunchconfigurationlaunchlaunchconfigurationjava707at orgeclipsedebuginternaluidebuguipluginbuildandlaunchdebuguipluginjava1018at orgeclipsedebuginternaluidebuguiplugin8rundebuguipluginjava12at orgeclipsecoreinternaljobsworkerrunworkerjava53caused by javalangnoclassdeffounderror orgapachetoolsantbuildloggerat javalangclassgetdeclaredconstructors0native methodat javalangclassprivategetdeclaredconstructorsunknown sourceat javalangclassgetconstructor0unknown sourceat javalangclassnewinstanceunknown sourceat orgeclipseantcoreantrunnerrunantrunnerjava324 24 morecaused by javalangclassnotfoundexception orgapachetoolsantbuildloggerat javaneturlclassloader1rununknown sourceat javaneturlclassloader1rununknown sourceat javasecurityaccesscontrollerdoprivilegednative methodat javaneturlclassloaderfindclassunknown sourceat orgeclipseantinternalcoreantclassloaderfindclassantclassloaderjava54at javalangclassloaderloadclassunknown sourceat javalangclassloaderloadclassunknown source 29 more,['java'] +531830,thisklrucache from android tutorial is missing lots of methods here is the thisk cache tutorial i am following i have downloaded the source code to thisklrucache but none of the methods used in this example exist in the source codedo i need to implement these methods myself or is there a version of thisklrucache that i am missing somewhere,['android'] +531838,abusing objectivec shorthand notation other than giving old school objectivec programmers heart attacks are there any other performance implications to doing thisnsmutablearray derp mutablecopyversus thisnsmutablearray derp nsmutablearray alloc init,['objective-c'] +531861,how can i subtract two strings in python i have a long string which is basically a list like strlamp bag mirror and other itemsi was wondering if i can add or subtract some items in other programming languages i can easily do strstrbag and get strlamp mirror this doesnt work in python i am using 27 on a w8 pcis there a way to split the string across say bag and somehow use that as a subtraction then i still need to figure out how to add,['python'] +531868,guice inject dependency into a class with static helper methods i am still new to guice and have not used any di frameworks before after reading the official wiki and many other documents i am still unable to wrap my head around it completelyin my particular case i want to write a el taglib function that uses some other tobeinjected class as all taglib functions have to be declared as static i cannot just inject my dependency via constructor or setter i thought of using the requeststaticinjection method described in injections but i unable to get it to work and have not been able to find any good tutorialthanks in advance for any helparman,['java'] +531880,namespace ads not bound i am trying to add admob to my android app in android studio i almost there but am getting the error ofnamespace ads not boundhere is also my xml with the adxml version10 encodingutf8scrollview xmlnsandroid androidlayout widthmatch parent androidlayout heightmatch parent linearlayout androidlayout widthmatch parent androidlayout heightwrap content androidorientationvertical comgoogleadsadview androidididadview androidlayout widthwrap content androidlayout heightwrap content adsadunitidmy ad unit id adsadsizebanner adstestdevicestest emulator test device id adsloadadoncreatetrue textview androidididbeertitle androidlayout widthfill parent androidlayout heightwrap content androidems10 androidtextsize20sp androidtextstyle bold androidpadding5dip textview imageview androidididimage androidlayout heightfill parent androidlayout widthfill parent androidlayout margin10dip tablelayout androidididtablelayout1 androidlayout widthmatch parent androidlayout heightmatch parent androidlayout gravitycenter horizontal androidshrinkcolumns androidstretchcolumns tablerow androidididtablestattitles androidlayout widthmatch parent androidlayout heightwrap content androidpadding5dip textview androidididabvtitle androidtextabv androidgravitycenter androidtextstyle bold androidtextsize20sp androidlayout weight1 textview textview androidididibutitle androidtextibu androidgravitycenter androidtextstyle bold androidtextsize20sp androidlayout weight1 textview textview androidididglasstitle androidtextglass androidgravitycenter androidtextstyle bold androidtextsize20sp androidlayout weight1 androidlayout widthwrap content textview tablerow tablerow androidididtablestat androidlayout widthmatch parent androidlayout heightwrap content androidpadding5dip textview androidididabv androidtext androidgravitycenter androidtextsize15sp androidlayout widthwrap content textview textview androidididibu androidtext androidgravitycenter androidtextsize15sp androidlayout widthwrap content textview textview androidididglass androidtext androidgravitycenter androidtextsize15sp androidlayout widthwrap content textview tablerow tablelayout view androidlayout width1dp androidlayout height30dpview linearlayout androidlayout widthmatch parent androidlayout heightwrap content androidorientationhorizontal textview androidididtextview1 androidlayout widthwrap content androidlayout heightwrap content androidtextaverage rating androidtextstyle bold androidtextsize20sp textview androidididbeerrating androidlayout widthwrap content androidlayout heightwrap content androidtext androidtextsize20sp linearlayout view androidlayout width1dp androidlayout height30dpview button androidididbuttonbrewery androidlayout widthfill parent androidlayout heightwrap content androidpadding5dip androidtext androidonclickviewbrewery button androidididbuttonstyle androidlayout widthfill parent androidlayout heightwrap content androidpadding5dip androidtext androidonclickviewstyle view androidlayout width1dp androidlayout height30dpview textview androidididyourportfolio androidtextstyle bold androidlayout widthfill parent androidlayout heightwrap content androidems10 androidtextsize20sp androidtextyour portfolio androidpadding5dip textview linearlayout androidididaddbeerlayout androidlayout widthmatch parent androidlayout heightwrap content androidorientationvertical linearlayout textview androidididbeerdescriptiontitle androidlayout widthfill parent androidlayout heightwrap content androidems10 androidpadding5dip androidtextdescription androidtextsize20sp androidtextstylebold textview textview androidididbeerdescription androidlayout widthfill parent androidlayout heightwrap content androidems10 androidtextsize15sp androidpadding5dip textview button androidididbuttontastetag androidlayout widthfill parent androidlayout heightwrap content androidpadding5dip androidtexttaste profile androidonclickviewtastetags linearlayoutscrollview,['android'] +531917,what are the differences between following two javascript code in some javascript code which uses immediate function it has argument window or document like the followingfunction window document window documenthowever window and document are global objects and can be directly accessed as followfunction var useragent windownavigatoruseragent var el documentgetelementbyid what are the differences between the above two codes which is better way and why,['javascript'] +531942,a typedef function as a parameter of another function typedef int xint y means define a function which named x with an integer parameter you can see this so post for detailsi have tried this in different ways that is my codeincludestdiohincludestdlibhtypedef int xint yvoid f1x a printff1dnavoid f2x a printff2dnaint testint yint main x a f1test f1a f2test f2a x b printfxs sizedn sizeofboutputf14199274f12f24199274f22xs size1my questionfx a is the same as fx asizeofsomefunction is defined or not,['c'] +531958,how to preview selected image in input typefile in popup using jquery in my code i am allowing the user to upload an image now i want to show this selected image as a preview in this same popup how can i do it using jquerythe following is the input type i am using in my popup windowhtml codeinput typefile nameuploadnewimage,['jquery'] +531975,calling virtual methods of other classes in ctors in the question about calling virtual methods in ctors and dtors the following piece of source code is cited from the c standardstruct v virtual void f virtual void gstruct a virtual v virtual void fstruct b virtual v virtual void g bv astruct d a b virtual void f virtual void g d bathis this bbv v a a f calls vf not af g calls bg not dg vg v is base of b the call is welldefined calls bg this line af undefined behavior aas type not a base of b my question is why calling af in bs ctor is an undefined behavior we can safely assume that a is already allocated before passing to bs ctor so why wouldnt that work correctlyv v new va a new ab b new bv a,['c++'] +532002,what is the harm in catching a stackoverflowerror just curious in an answer about catching stackoverflowerrors someone wrote surely there are situations where a stack overflow might leave an application inconsistent just like a memory exhaustion whats so special about stackoverflowerrors that they threaten to corrupt the application state more than say a nullpointerexception thrown in case of a bug one thing i can think of is that a stackoverflowerror can occur in places where normally never ever an exception or other throwable for that matter is thrown eg a simple getter so the program probably is not prepared for this are there more diabolical problems,['java'] +532045,is the check thread safe i know that compound operations such as i are not thread safe as they involve multiple operations but is checking the reference with itself a thread safe operationa a is this threadsafei tried to program this and use multiple threads but it did not fail i guess i could not simulate race on my machineeditpublic class testthreadsafety private object a new object public static void mainstring args final testthreadsafety instance new testthreadsafety thread testingreferencethread new threadnew runnable override public void run long countofiterations 0l whiletrue boolean flag instancea instancea ifflag systemoutprintlncountofiterations flag countofiterations thread updatingreferencethread new threadnew runnable override public void run whiletrue instancea new object testingreferencethreadstart updatingreferencethreadstart this is the program that i am using to test the threadsafetyweird behavioras my program starts between some iterations i get the output flag value which means that the reference check fails on the same reference but after some iterations the output becomes constant value false and then executing the program for a long long time does not generate a single true outputas the output suggests after some and not fixed iterations the output seems to be constant value and does not change outputfor some iterations1494true1495true1496true19970true19972true19974trueafter this there is not a single instance when the condition becomes true,['java'] +532085,pop up window to thisplay some stuff in a fragment i am trying to make something like a popup window that would appear when clicked on a view in a fragment i want this popup window or whatever to not make the fragment dark like a dialog fragment doesand i also want the pop up to be positioned where the view is clickedwould be good if it has its own activity and layout so i can do some custom changes in itcan you plese show me some sample code,['android'] +532104,argumentparser epilog and description formatting in conjunction with argumentdefaultshelpformatter i am using argparse to take in command line input and also to produce help text i want to use argumentdefaultshelpformatter as the formatter class however this prevents me from also using rawdescriptionhelpformatter which would allow me to add custom formatting to my description or epilogis there a sensible method of achieving this aside from writing code to produce text for default values myself according to the argparse docs all internals of argumentparser are considered implementation details not public api so subclassing is not an attractive option,['python'] +532169,prevent user from thismissing notification some apps have notifications which cana t be thismissed by swiping them awayhow can i manage such behaviour,['android'] +532202,jquery autocomplete should skip thisabled element when using keyboard if you see this fiddle demo not done by me how can i then avoid that the keyboard can go down and choose the thisabled element the mouse is working fine not being able to select it but i can go down with the keyboard and select it resulting in an empty search the fiddle demo is from this post how to thisable element in jquery autocomplete listjquery codefunction var availabletags actionscript applescript asp basic c c clojure cobol coldfusion erlang fortran groovy haskell java javascript lisp perl php python ruby scala schemetagsautocomplete source availabletags response function event ui if uicontentlength 3 while uicontentlength 3 uicontentpop uicontentpush label please narrow down your search value datauiautocomplete renderitem function ul item return li itemvalue classuistatethisabled appenda itemlabel a appendtoul,['jquery'] +532205,understanding conditionalweaktable i am trying to understand conditionalweaktable what is the difference betweenclass classa static readonly conditionalweaktableclassa otherclass otherclasstable new conditionalweaktableclassa otherclassandclass classb otherclass otherclass what would be the pros and cons of using classa or classb to reference a nullable field,['.net'] +532265,ie8 respondjs undefined is null or not an object i am using respondjs 1 for that library and i am getting and error to the following function of the objecttranslate function styles href media here i got undefined error in ie 8 var qs stylesmatchmediagi ql qs qslength 0 try to get css path href hrefsubstring0 hreflastindexof var repurls function css return cssreplaceurlg 1 href 23 usemedia ql media if path exists tack on trailing slash if hreflength href if no internal queries exist but media attr does use that note this currently lacks support for situations where a media attr is specified on a link and its associated stylesheet has internal css media queries in those cases the media attribute will currently be ignored if usemedia ql 1 for var i 0 i ql i var fullq thisq eachq eql media attr if usemedia fullq media rulespushrepurlsstyles parse for styles else fullq qsimatchmedia ss regexp1 rulespushregexp2 repurlsregexp2 eachq fullqsplit eql eachqlength for var j 0 j eql j thisq eachqj mediastylespush media thisqsplit0matchonlysazazs regexp2 all rules ruleslength 1 hasquery thisqindexof 1 minw thisqmatchsminwidths09pxems parsefloatregexp1 regexp2 maxw thisqmatchsmaxwidths09pxems parsefloatregexp1 regexp2 applymediaare there any other workarounds i have tried different ones,"['javascript', 'jquery']" +532283,putting two linkedlists together without copying java using standard api i have two linkedlist in my code and i need to make one that have both i will not need this lists anymore just the new one which have all data i need i could use addall but performance is i huge issue and i cant wait to copyadding references everything every time i am looking for something like we normally do if we create our own linkedlist just connect the last node from one to the fist from the second is there a way to do that using the linkedlist class from the java apimerging collections is a different case although the operation means almost the same my issue is just regarding performance and just for linkedlists which normally can do what i need also merging is kind of an ambiguous term what i want is just to put then together no matter what order they are with performance in mindi am not looking if is possible to mergeanother thing my question is just regarding the api i am not looking for building my own code boss requirement and that is why is different from this one merge two lists in constant time in java not useful answers there either,['java'] +532301,how to run eclipse with different java version i am using eclipse for developing blackberry applications i have jdkjre 7 currently on my computer but that makes the blackberry plugins crash actually is a known issue and the only thing need to be done is run eclipse with jdkjre 6 instead of 7i downloaded and installed version 6 however i am pretty sure eclipse still uses 7 i had the same problem a year ago and i remembered i had to configure some system variables and it worked but i cannot really find the solution nowany idea on this one important i do not want to compile in version 6 which means i just have to choose the java version through eclipse what i need is eclipse to start with version 6,['java'] +532373,android adb retrieve database using runas on a nonrooted android device i can navigate to the data folder containing the database using the runas command with my package name most files types i am content with just viewing but with the database i would like to pull if from the android deviceis there a download copy or move command from this part of adb shell i would like to download the database file and view its content using a database browserone answer here involves turning entire application package into a compressed archive but there is no further answer on how to extract that archive once this is done and moved to the machine leaving me very sidetracked when there might be a more direct solution to begin withthank you,['android'] +532398,qt how to embed an application into qt widget in our project we have three independent applications and we have to develop a qt control application that controls these three applications the main window will be seperated to three sub windows each one thisplay another one applicationi thought to use qx11embedwidget and qx11embedcontainer widgets but two problems with that the qx11embed is based on x11 protocol and i dont know if it is supported on nonx11 systems like windows ossince qt 5 these classes are not existing and the qt documentation does not mention whyso that i dont know whether to use it or not i will be happy to get an answersin addition i see that the qt 51 contains qwidgetcreatewindowcontainer function that in some posts it looks like this should be the replacement to the x11embed can anyone please explian me more how can i use this function to create a qt widget that will run another application a calculator for example inside itsi have searched a lot in google and did not find answers to my qscan anyone please help me am i on the right waythanks,['c++'] +532432,set java 16 default over 17 in ubuntu linux here is the output to some inspection that i did java versionjava version 170 21javatm se runtime environment build 170 21b11java hotspottm 64bit server vm build 2321b01 mixed modeand updatejavaalternatives ljava160openjdkamd64 1061 usrlibjvmjava160openjdkamd64and ls usrlibjvmdefaultjava java150gcj46 java160openjdk java160openjdkamd64 java6openjdk java6openjdkamd64 java6openjdkcommon java7openjdkamd64with that in mind how do i go about changing the default to 16 so that when i execute java version it tells me 16thanks,['java'] +532441,weird behavior with button near notification center pulldown on ipad i have got a uibutton the back button in the upper left corner of an ipad application that thismisses a view controller i have thiscovered that if you tap this button slightly too high you can both activate the button and start to pull down the notifications pane at the same time when this happens my viewwillthisappear gets executed and stops the animations in the view but the view does not actually thismiss of course the notifications pane does not come down all the way so the net result looks like my animations crashed and that the back button failed as wellthe obvious solution would be to just move the button down a little bit but as that is undesirable for layout reasons i am curious ifanyone has ever seen this behavior beforeif it is welldefined behavior and if so where does apple describe itare there any known workaroundsedit actually looks like less of an issue after all turns out it is my applicationwillresignactive that is getting called not viewwillthisappear still looks bad but at least the behavior is well defined i am not activating my home button at all just pulling down the notifications pane,"['ios', 'objective-c']" +532495,how to avoid hanging xvfb processes while using pyvirtualthisplay trying to find how to avoid hanging xvfb processes in our python application when using pyvirtualthisplay the essential problem is that calling thisplaystop see code sample below does not seem to properly shut down the xvfb processpyvirtualthisplay is very simply usedfrom pyvirtualthisplay import thisplaythisplay thisplaybackendxvfbthisplaystart some stuff happens herethisplaystopnow the thisplay class has a slight modification to prevent xvfb from using tcp ports basically add nolisten tcp to the executing command the modification is done by overriding the appropriate xfvbthisplay clas cmd propertypropertydef cmdself cmd program dictblackbr whitewrselfbgcolor screen strselfscreen xjoinmapstr listselfsize selfcolor depth selfnew thisplay var nolisten tcp return cmdwhat is the proper way to end the xvfb processes in this context so that they are terminated and do not lingerthanks very much,['python'] +532629,how to load all the images from one of my folder into my web page using jqueryjavascript i have a folder named images in the same directory as my js file i want to load all the images from images folder into my html page using jqueryjavascriptsince names of images are not some successive integers how am i supposed to load these images,"['javascript', 'jquery', 'html']" +532647,hide the src image in an element but show its background image i have an image element to which i have added a different background image using cssimg backgroundimage url importantimg src i want to show the cspecified background image the stack exchange logo in the image element instead of the image specified by the src attribute the stack overflow logois this possible i have a situation where i cannot alter the html or use javascript and am looking for alternatives,['css'] +532653,how to dynamically create keyframe css animations i have a requirement to rotate a div and stop at a particular position the value will be recieved from serveri tried native js to rotate and stop but its eating up my cpu big timei can rotate with css animation but i need to create a class which will dynamically describe where to stop the animation something like webkitkeyframes spinit 100 webkittransform rotatea dynamic value mozkeyframes spinit 100 webkittransform rotatea dynamic value here is one reference thanks in advance,"['javascript', 'jquery', 'html', 'css']" +532658,pointer expressions ptr ptr and ptr recently i have come across this problem which i am unable to understand by myselfwhat do these three expressions really meanptrptrptri have tried ritchie but unfortunately was unable to follow what he told about these 3 operationsi know they are all performed to increment the pointerthe value pointed to i can also guess there may be a lot of things about precedence and order of evaluation like one increments the pointer first then fetches the content of that pointer one simply fetches the content and then increments the pointer etc etc as you can see i do not have a clear understanding about their actual operations which i would like to clear as soon as possible but i am truly lost when i get a chance to apply them in programs for example int main char p hello whilep printfcp return 0gives me this outputellobut my expectation was that it would print hello one final request please give me examples for how each expression works in a given code snippet as most of the time only a mere paragraph of theory gets flown over my headthanks in advance,"['c++', 'c']" +532677,uitableview beginend updates when using voidbeginupdates and voidendupdates on a uitableview do you have to make the changes to the datasource inside callsieif i have a nsmutablearray called datasource driving my tableview could i do this edit the actual data firstdatasource addobjectblah now update the tableselftableview beginupdatesselftableview insertrowsatindexpathsnsindexpath indexpathforrowdatasourcecount 1 insection0 withrowanimationuitableviewrowanimationautomaticselftableview endupdatesor is it necessary to doselftableview beginupdatesdatasource addobjectblahselftableview insertrowsatindexpathsnsindexpath indexpathforrowdatasourcecount 1 insection0 withrowanimationuitableviewrowanimationautomaticselftableview endupdatesjust asking because i have a couple places where i am updating and i could potentially take the common code out to a functionbut only if i can update outside the update calls,"['ios', 'objective-c']" +532680,how convert timespan to 24 hours and minutes string i use this code for converting timespan to string for ex 1453 mytimespantostringhhmmbut this error occursinput string was not in a correct formatwhat is the proper way to do this,['c#'] +532701,which camera will open getusermedia api in mobile device front or rear while using getusermedia api to access camera in desktop it will open web cameraof course it is help to video communicationbut which camera is invoked when it is used in mobile devicefront cam or rear camis there needed code for selecting camera,['javascript'] +532828,why arraylist giving unordered output i have written java program to add integer in arraylist and remove that integer from arraylist but it not giving me proper result here is my codepublic static void mainstring args arraylistinteger anew arraylistinteger aadd6 aadd7 aadd8 aadd9 forint i0iasizei systemoutprintlnremoved elementsaremovei it giving me output as follows removed elements6removed elements8exception in thread main javalangindexoutofboundsexception index 2 size 2 at javautilarraylistrangecheckarraylistjava547 at javautilarraylistremovearraylistjava387 at collectiontempmaincollectiontempjava19why i am getting output like this,['java'] +532829,jdesktoppane resize we have a application with two jframes with two jdesktoppaneswe need to move an internal frame from one frame to anotherthe problem we have is that after we move the internalframe from first window to the second window when we resize the fist window the internal frame of the second window also gets resizedimport javaawteventactioneventimport javaawteventactionlistenerimport javabeanspropertyvetoexceptionimport javaxswingjdesktoppaneimport javaxswingjframeimport javaxswingjinternalframeimport javaxswingjmenuimport javaxswingjmenubarimport javaxswingjmenuitemclass firstframe extends jframe jdesktoppane desktoppane new jdesktoppane secondframe secondframe public firstframesecondframe secondframe thissecondframe secondframe settitlefirstframe example setdefaultcloseoperationexit on close adesktoppane jmenubar menubar new jmenubar jmenu menu new jmenufile jmenuitem item new jmenuitemmove itemaddactionlistenernew actionlistener override public void actionperformedactionevent actionevent moveframe menuadditem menubaraddmenu setjmenubarmenubar public void addaninternalframe jinternalframe frame new jinternalframe framesettitlean internal frame desktoppaneaddframe framesetvisibletrue framesetmaximizabletrue try framesetselectedtrue framesetmaximumtrue catch propertyvetoexception e eprintstacktrace public void moveframe jinternalframe selectedframe desktoppanegetselectedframe desktoppaneremoveselectedframe desktoppanerepaint secondframeaddinternalframeselectedframe class secondframe extends jframe jdesktoppane desktoppane new jdesktoppane public secondframe settitlesecondframe example setdefaultcloseoperationexit on close adesktoppane public void addinternalframejinternalframe frame desktoppaneaddframe public class desktoppaneexample public static void mainstring args throws propertyvetoexception secondframe secondframe new secondframe firstframe firstframe new firstframesecondframe firstframesetsize400 400 firstframesetlocation100 100 firstframesetvisibletrue firstframeaddaninternalframe secondframesetsize400 400 secondframesetlocation520 100 secondframesetvisibletrue in the above sample application to reproduce 1 click menu filemove2 resize the first windownote this is reproducable in java 17 only i use jdk170 03update add more informationthis was not reproducible on java 16 jdk160 21,['java'] +532869,does composition root needs unit testing i was trying to find an answer but it seems it is not directly thiscussed a lot i have a composition root of my application where i create a dicontainer and register everything there and then resolve needed toplevel classes that gets all dependencies as this is all happening internally it becomes hard to unit test the composition root you can do virtual methods protected fields and so on but i am not a big fan of introducing such things just to be able to unit test there are no big problems with other classes as they all use constructor injection so the question is does it make much sense to test the composition root at all it does have some additional logic but not much and in most cases any failures there would pop up during application startsome code that i havepublic void initializesome configuration parameters here m container new unitycontainer regestering dependencies m thistributor m containerresolveisimplefeedmessagethistributor public void start if m thistributor null throw new applicationexceptioninitialize should be called before start m thistributorstart public void close if m thistributor null m thistributorclose,['c#'] +532943,new to laravel php framework routes other than does not work i am a beginner at lavarel framework i know about mvc structure since i have used it before inside aspnet but using laravel is quite confusing to mei have installed laravel inside photozoom directory usingcomposer createproject laravellaravel photozoom preferthistheres my approutesphp phprouteget function return viewmakehelloroutegetusers function return users route is workingwhen i run httplocalhostphotozoompublicusers i get 404 not found error but when i try httplocalhostphotozoompublic the route for is invoked and the corresponding view is calledi even tried to create a view for the users route using laravel documentation i have created two files layoutbladephp html head titlelaravel quickstarttitle head body h1laravel quickstarth1 yieldcontent bodyhtmlusersbladephp extendslayoutsectioncontent usersstopbut still when i call httplocalhostphotozoompublicusers i get 404 not found errorheres my publichtaccess fileifmodule mod rewritec options multiviews rewriteengine on rewritecond request filename d rewritecond request filename f rewriterule indexphp lifmodulei am using php 55 apache 246 any help would be appreciatedsolvedafter enabling mod rewrite i had to enable allowoverride too,['php'] +532993,objective c block semantics consider the following c methodclass workerprivate node nodevoid workerwork nsblockoperation opnsblockoperation blockoperationwithblock tool hammernode hammeruse what exactly does the block capture when it captures node the language specification for blocks is clear for other casesvariables used within the scope of the compound statement are bound to the block in the normal manner with the exception of those in automatic stack storage thus one may access functions and global variables as one would expect as well as static local variables testmelocal automatic stack variables referenced within the compound statement of a block are imported and captured by the block as const copiesbut here do we capture the current value of this a copy of this using workeras copy constructor or a reference to the place where node is storedin particular suppose we say worker fredsomenode fredwork the object fred may not exist any more when the block gets run what is the value of node assume that the underlying node objects live forever but workers come and goif instead we wrotevoid workerwork node mynodenode nsblockoperation opnsblockoperation blockoperationwithblock tool hammermynode hammeruse is the outcome different,['objective-c'] +533041,mp3 parsing in python this is something i have been trying to do for a while and is more of an open ended question if anyone has any knowledge that can help me shed some light on this it would be very much appreciatedi want to decode the audio stream in an mp3 and use that to drive animation all using python as i understand it the audio data in an mp3 is stored in frames of 32 frequency subbands or frequency bins which is ideal for me if i could take an mp3 and extract an amplitude for each subband on each frame that would be perfect for what i want to doi found solution here where all the processing seems to be done in python it is quite slow but even if i could use that to extract what i want it would be good i am struggling to understand whats going on in that code though i also had a solution where i converted to wav and then used fft to extract frequencies from the wav this was very noisy and seems like a stupid way to do it as the data i want is stored directly in the mp3 converting back to a sound wave seems unnecessary this was actually faster than the first one though heres what i ended up with 0forxlk4awell if anyone has any advice or experience they want to share or ideas for libraries i should look at i would really like to hearthankshenry,['python'] +533043,write to stdout using character array not null terminated cc whats the most straightforward way to write to stdout using a character array i want to output a slice of a much larger array and the slice is not nullterminated i want to avoid copying the slice to a proper nullterminated cstring,['c++'] +533052,checking if an input field is required using jquery what would be the easiest way to check if an input is required i have been trying stuff along these lines but always comes up with all required only 46 areformregisterfindinputeachfunction ifthisproprequired undefined consolelognr else consolelogir i have tried attr aswellim trying to use it for form ajax validation im doing it this way at the momentifformregister spanlength formregisterchildrengreenlength inputregistersubpropthisabled false else inputregistersubpropthisabled truethanksedit html addingform idregister action methodpost autocompleteonlabelnicknamelabelinput typetext namename value echo postname required span idregnamespanbr ifusertype l labelemaillabelinput typeemail nameemail value echo postemail required span idregemailspanbr labelpasswordlabelinput typepassword namepassword value echo postpassword required span idregpasswordspanbr labelagainlabelinput typepassword namepasswordtest value echo postpasswordtest required span idregpasswordtestspanbr labelavatarlabelinput typeurl nameavatar value echo postavatar span idregavatarspanbr input typesubmit valueregister thisabled idregistersub,"['javascript', 'jquery']" +533088,nodejs mysql connection pooling i am new to nodejs and as many others i came from phpmysql background i am trying to figure out how to structure my application to use mysql most efficent way i am using nodemysql module other threads here suggested to use connection pooling so i set up a little module mysqljsvar mysql requiremysqlvar pool mysqlcreatepool host localhost user root password root database guessexportspool poolnow whenever i want to query mysql i require this module and then query the databsevar mysql requiredbmysqlpoolvar test functionreq res mysqlgetconnectionfunctionerr conn connqueryselect from users functionerr rows resjsonrows is this good approach i could not really find too much examples of using mysql connections besides very simple ones where everything is done in main appjs script so i do not really know what the convention best practices areshould i always use connectionend after each query what if i forget about it somewherehow to rewrite the exports part of my mysql module to return just a connection so i do not have to write getconnection every time,['mysql'] +533089,how do java runtimes targeting presse2 processors implement floatingpoint basic operations how doesdid a java runtime targeting an intel processor without sse2 deal with floatingpoint denormals when strictfp is seteven when the 387 fpu is set for 53bit precision it keeps an oversized exponent range that forces to detect underflowoverflow at each intermediate result andmakes it difficult to avoid doublerounding of denormalsstrategies include recomputing the operation that resulted in a denormal value with emulated floatingpoint or a permanent exponent offset along the lines of this technique to equip ocaml with 63bit floats borrowing a bit from the exponent in order to avoid doubleroundingin any case i see no way to avoid at least one conditional branch for each floatingpoint computation unless the operation can statically be determined not to underflowoverflow how exceptional overflowunderflow cases are dealt with is part of my question but this cannot be separated from the question of the representation the permanent exponent offset strategy seems to mean that only overflows need to be checked for for instance,['java'] +533090,smtp connect failed message was not sentmailer error smtp connect failed am trying to send mail to a gmail address but it keeps on getting this error smtp error failed to connect to server connection timed out 110smtp connect failed message was not sentmailer error smtp connect failed what could be the problem require classphpmailerphp path to the phpmailer class require clasmtpphp mail new phpmailer mailissmtp telling the class to use smtp mailsmtpdebug 2 mailmailer smtp mailhost sslsmtpgmailcom mailport 587 mailsmtpauth true turn on smtp authentication mailusername smtp username mailpassword mypasswword smtp password mailpriority 1 mailaddaddressname mailsetfromvisitor email name mailaddreplytovisitor emailname mailsubject message from contact form mailbody user message mailwordwrap 50 ifmailsend echo message was not sent echo mailer error mailerrorinfo else echo message has been sent,['php'] +533091,couldnt hide the progressbar after loading image in picasso i was trying to integrate progress bar in ma appbut i could not track the call back methodthe progress bar always showinghow to hide when image is lodedholderimageview imageview localviewfindviewbyidridimageview1holderprogressbar progressbar localviewfindviewwithtagridprogressbar1localviewsettagholderurl getitemparamintpicassowithgetapplicationcontextloadurlplaceholderrdrawableic launchererrorrdrawableic launcherfitintoholderimageview new callback override public void onsuccess holderimageviewsetvisibilityviewvisible holderprogressbarsetvisibilityviewinvisible override public void onerror holderprogressbarsetvisibilityviewvisible holderimageviewsetvisibilityviewinvisible,['android'] +533192,missing map resource i have recently started having this problem with all my projects when my index page loads which contains a reference to the jquery source file my console logs this error get httplocalhost30jslibjquery1102minmap 500 internal server errorthis does not affect my application at all but it is really annoying to see whenever i open up the console does anyone know where this is coming fromedit note that i am not explicitly referencing the map file i am just pointing to script srcjslibjquery1102minjsscript,"['javascript', 'jquery', 'html']" +533277,how to stick the footer to the bottom of the page while moving it upward in a parallaxlike effect i have a project where the requirement is to move the footer footer upward while scrolling down the page in a parallaxlike effect when you start scrolling down the page the footer should start moving upward only until it is visible in the bottom part of the viewportthe footer should have covered most of the preceding div half way up and in full when it has reached the top of the viewportthe page may have a similar html structure like this body div idsectiona classdivfirst sectiondiv div idsectionb classdivsecond sectiondiv div idsectionc classdivthird section div classboxdiv div classboxdiv div classboxdiv div div idfooter classdiv cffooterdivbodythe parallaxlike effect is achieved via javascriptjquery adding a dynamic negative value to the top css property of the relative positioned footer here is the code for what it matters var window jquerywindow footer jqueryfooter viewport windowinnerheight starteffect footeroffsettop viewportfunction footerparallax var scrollpos windowscrolltop starteffect ratio 06 footercss top scrollpos ratio windowscrollfunction footerparallaxthe obvious issue is that as soon as the top property starts getting a negative value the footer starts moving away from the bottom of the pagei have prepared a jsfiddle and assigned colors to each section and body to make it clearer the body darkred is visible under the footer after scrolling to the bottomwhat have i triedmodifying the margintop instead of the top property a this does the trick however the preceding div that has to be covered by the footer sectionc in the example above overlaps the contents of the footer and breaks its layout regardless that it is not visible due to its zindex property added some floating boxes in the fiddle to make it evident a clearfix hack did not help eithersetting a static position to the footer neither top or margintop have effect over a static elementchangingreducing dynamically the height of sectionc instead of top of footer to produce the effect of moving the second upwards a the footer stops moving as soon as height is equal to 0 neither negative size or negative paddings are allowedchanged the height dynamically of the html andor body tags to no avail i have also tried some parallax plugins like skrollr and skrollrstylesheets and some othersthe problem with this solution same with others is that it relays in an specific offset position of the footer measured in px and set in a data attribute but if the content changes dynamically for example using the masonry plugin to arrange elements in another section of the document the measures become inaccurate and the footer may start moving too early or too lateby the way other css stickyfooter techniques would not work because well they actually push the footer to the bottom of the page and here we are doing the oppositei guess the question is either how to keep the footer stick to the bottom of the page while it is moved upwards or how to reduce the gap to 0 between the end of the document and the bottom edge of the footeri am starting to think that this issue has not a real solution the way it is or maybe i am already too tired to see the obvious i am interested in learning alternative solutions or hacks via css javascript jquery or all of the abovebear in mind that i am not asking how to create the parallax effect unless a totally different approach or tweaks to the existing js code solves the position issueimportant please consider that this is a wp site with an xhtml 10 transitional doctype and has installed many other jquery plugins like masonry scrollto jquery ui etc i may have not control to change many things from the original structure and i do not want to so the idea is to implement this without breaking too many things and from a modular scriptedit 1 added a graphic to clarify the questionfigure a shows a regular web page scrolled down to the end the red square represents the viewport and the footer grey is slighted moved to the right for illustration purposes the body has a redthish background color not visible in normal conditions just for illustration purposes too note the height of each section as well as the height of the footer is determined by their content forms images text etc so is not fixedfigure b shows the current issue if footer slides up in a parallaxlike effect see jsfiddle for reference while scrolling down the page it starts covering any preceding section above it without modifying neither its own height or the height of the preceding sections and it also starts separating itself from the bottom of the page therefore the bodys color background becomes visible note the bigger the viewport is fullscreen mode for instance the higher the footer is moved upward and more content is covered by itfigure c is the expected result the footer should be stuck to the bottom of the page in other words it should be the last visible element after the page has been totally scrolled down and not the body background as in figure b notice that the contents and the size of each section including the footer should ideally remain untouched having said that adding padding bottom to the footer or increasing its height is not the expected result since it would break its original visual layout,"['javascript', 'jquery', 'html', 'css']" +533321,why does qmapoperatorconst key key return by value i noticed that the qmapoperatorconst key key has these two overloads t qmapoperatorconst key keyconst t qmapoperatorconst key key constis there a reason for returning by value and since we have move semanticswhen returning by value should we ever return by const valuethe reason why i am asking is thisimagine we haveclass expensivetocopypublic int someproperty const void fconst qmapint expensivetocopy map int lala map4someproperty we need to copy the entire object just to look at someproperty,['c++'] +533323,how to create user from django shell when i create user from djangoadmin user passwords are encrypted but when i create user from django shell userpasword is saved in plain text example date joined 20130828t042256322185 email first name id 5 is active true is staff false is superuser false last login 20130828t042256322134 last name password pbkdf2 sha25610igkbck9ced0b6hwrkyimpngkhcfpvgal2yp4lkup3qwem2ydswwack resource uri apiv1user5 username user4 date joined 20130829t011536414887 email testophio first name id 6 is active true is staff true is superuser true last login 20130829t011536414807 last name password 123test resource uri apiv1user6 username test3 i am trying to make rest style api for a simple blog app when i try to insert a user by post request by passing json password is saved as plain texthow to override this behaviour,['python'] +533343,how to replace space to underscore at same time when i enter the text in input field can you please tell me how to replace space to underscore at same time when i enter the text in input fieldif i have string i used like thatreplace g but i am looking for when user enter text on input field then it automatically replace the space with underscore i used keyup event it only fire first timetestkeyupfunction var textvalue thisval iftextvalue alerthh,['jquery'] +533348,how to use client template expressions in ajax binding of a mvc kendo grid i have a twolayer hierarchical grid that i am moving from server side binding to using ajax the ajax reads for both layers of data are working correctly however i am having difficulty using the clienttemplate to render my columns based on conditional logicbelow is the serverside binding version i understand i have to use clienttemplate and expressions for the same effect but i am having two problemshow to increment variable i for each row so i can use checkboxfor and like html helper methodshow to convert the to use the clienttemplate expression note the conditional logic uses properties of the model of the view and also properties of the bound element myviewmodel with the conditional logic using a mixture of properties from the modelconverting this to an expression would be most helpfulvar i 1htmlkendogridmyviewmodel namegrid columnscolumns columnsboundc cselectedtitle template text i if modelpermissionshasinsertaccess itemstatus statuscreated input typehidden namemyviewmodelsindex valuei htmlcheckboxform mmyviewmodelsiselected text columnsboundc cid templatetexthtmlhiddenform mmyviewmodelsiiditemidtext,['c#'] +533384,memory leak on windows phone 8 i am developing a windows 8 native app my app is getting crash after going back and forth in the application for sometime on analysis using the memory profiler i found that each time i navigate from one page to another the memory usage increases inspite of me setting null all the objects of list webclient string and so on to null and calling gccollect after that on the navigatedfrom eventfirstly i thought it would be due to the images and hence i removed the images from the app and tested but still there is no change in the memory usage of the app somehow the gccollect is not working and freeing the memoryi have tried the below mentioned things but to my bad luck isnt working to release the memory instead the result remains the samei have set the image urisource to null before setting the new source and then call gccollect to free the memory usage but it does not seem to release itsecondly i have set all the objects to null and call gccollect but still it does not free up the space from the memory usage of the phone appi also tried to analyze using the memory profiler but i am not able to track anythingi have also gone through all the post and implemented the suggested things but the gccollect doesnt seem to release the memoryis there any work around for the following issuehow can i free the memory consumed on navigating from one page to another,['c#'] +533512,undefined method add reference i am trying to add a user reference to my post tables with following codeclass adduseridtoposts activerecordmigration def change add reference posts user index true endendbut i have received an error messageundefined method add referenceanyone knows how to solve thisi am using rails 3213,['ruby-on-rails'] +533522,how to use greater than or equal in a switch statement what is the best way to check if variable is bigger than some number using switch statement or you reccomend to use ifelse i found such an example int iifvar1var2 i 1ifvar1var2 i 0ifvar1var2 i 1switch i case 1 do stuff break case 0 do stuff break case 1 do stuff breakwhat can you tell a novice about using greater than or equal in switch statements,['java'] +533560,how to get a datarow out the current row of a datareader ok i would like to extract a datarow out a datareader i have been looking around for quite some time and it does not look like there is a simple way to do thisi understand a datareader is more a collection of rows but it only read one row at the timeso my question is there any way to extract a datarow out the current row of a datareader,['c#'] +533582,comparing time regardless of date i have an object that has properties currently as datetime the object is marked as valid within a time frame the default being 0 to 235959the user enters the value in the ui and the property is set vianew datetimedatetimenowyear datetimenowmonth datetimenowday modelhours modelminutes modelsecondsthis is then converted to utc when it hits the databasetodays date is 29th august 2013 if a colleague in india runs this program it will store the data in the database as 28th august 2013 1830 as they are 55 hours ahead of utc so 29th august 2013 0 becomes yesterdaywhen the logic tries to determine if the object is valid the logic isif datetimeutcnowtimeofday modelmypropertyfromdbtimeofdaywe are trying to determine if the current time is within a range of 0 and 235959this fails as 1400 current time is not greater than 1830what would be the best approach to compare just timeswould storing the values as datetimeoffset help is using tolocal ok other considerations are that a user in india is using the app which is hosted in the uk so it needs to be timezone awarethanks,"['c#', '.net']" +533653,angularjs dynamic stylesheet link tag fires request too soon i am facing an issue similar but not identical please bear with me to the one described in angularjs conditionally rendering css in html headi am also lazily loading a stylesheet getting the filename from a scope variable that i initialize at the very beginning of my controllers link relstylesheet datanghrefcss filename css as i am using nghref here in its data form i am indeed avoiding unwanted requests such as httplocalhostcss7b7b20filename7d7dcssbut it all still fires too soon and i am getting this almost every time httplocalhostcsscsswhich seems to mean the request fires between the moment when angular removes its own markup and the moment it replaces it with the correct value which it does a moment later and then my stylesheet loads properly i reckon it is not even possiblei figured i might be providing a value for the filename scope variable too late but as i said it is the first thing done in my controller angularmodulemycontrollers controllertestctrl scope functionscope scopefilename test some more code i am using angular 115 is there anything i can do about it it is not that big of a deal but it would still be better if i could fix itedit here comes the complete code as requested i would not include page templates as they are irrelevant regarding the issueindexhtml doctype htmlhtml langen datangappmyapphead meta charsetutf8 titlemy apptitle link relstylesheet datanghrefassetscss filename css headbody div idapp classapp stylethisplay none datangviewdiv script srcassetsjslibangularangularminjsscript script srcassetsjsappappjsscript script srcassetsjsappcontrollersjsscriptbodyhtmlappjs var app angularmodulemyapp mycontrollers configlocationprovider routeprovider functionlocationprovider routeprovider locationproviderhashprefix routeprovider when templateurl pathtomytemplatehtml controller testctrl otherwise redirectto appruncontrollersjs angularmodulemycontrollers controllertestctrl scope rootscope functionscope rootscope rootscopefilename stylesheet yes i tried with an empty controller just like this one same issue,"['javascript', 'css']" +533655,how to make an c object from json i get the following response from a webservice data foohugoinfo path logoncgi minversion 1 maxversion 2 foofritztask path fritzprocesscgi minversion 1 maxversion 1 success truehow must the jsonobject look like to deserialize thisor is there another way to get the values of the properties,"['c#', '.net']" +533671,how do i automatically fix an invalid json string from the 2gis api i got the following json string api version 13 response code 200 id 3237490513229753 lon 38969916127827 lat 45069889625267 page url null name atb firm group id 3237499103085728 count 1 city name krasnodar city id 3237585002430511 address turgeneva 1721 create time 20080722 100204 07 modification time 20130809 200436 07 see also id 3237491513434577 lon 38973110606808 lat 45029031211 name advance hash 5698hn745a8ij1h86177uvgn94521j3464he26763737242cf6e654g62j0i7878e ads sponsored article title center advance text businessenglish warning null but python does not recognize itjsonloadsfirm strexpecting delimiter line 1 column 3646 char 3645it looks like a problem with quotes in title center advancehow can i fix it automatically in python,['python'] +533677,warning toplevel constant referenced i have four models document question questiondocument and answer in my answer model i havevalidates text presence unless procnew a aquestionis a questiondocument this gives me the the warningwarning toplevel constant document referenced by questiondocumenthow do i prevent this warning from happening without renaming my classes,"['ruby-on-rails', 'ruby']" +533681,javascript map in leaflet how to refresh i have a basic geojson program in javascript by using leaflet api htmlheadlink relstylesheet href script srcscriptscript srcindiajs typetextjavascriptscriptheadbodydiv id map1 stylewidth 1100px height 400px divscriptvar area lmapmap1 center 278800780800 zoom 4 ltilelayerzxypngaddtoareavar indialayer lgeojsonindia style weight 2 opacity 1 color white dasharray 3 fillopacity 01 areaaddlayerindialayer function clicked thisoptionsstylefillopacity 08 how to refresh layer in the given map indialayeronclick clicked scriptbodyhtmlthe problem is how would i automatically refresh the content of layer on the mapexample here function clicked indialayerstylefillopacity 08 how to refresh layer in the given map indialayeronclick clicked when user click on indialayer the fillopacity variable changes but does not reflect back on map which is understood since i am not refreshing the map i do not know how to do it please help ps these are the functions available on indialayer object ie this object inside clicked functionwhich one to use for this purpose or there exist none propagateevent function setlayerstyle functionadata functionaddeventlistener functionaddlayer functionaddonetimeeventlistener functionaddto functionbindpopup functionbringtoback functionbringtofront functioncallinithooks functionclearalleventlisteners functionclearlayers functioneachlayer functionfire functionfireevent functiongetbounds functiongetlayer functiongetlayerid functiongetlayers functionhaseventlisteners functionhaslayer functioninitialize functioninvoke functionoff functionon functiononadd functiononremove functiononce functionremoveeventlistener functionremovelayer functionresetstyle functionsetstyle functionsetzindex functiontogeojson,"['javascript', 'jquery']" +533711,is rails secret token still important with configsession storecache store i have done my google due diligence and cannot find an explicit answer so good people of stack overflowif in a rails 3 app i am not using cookies to store sessions is it important to securely manage the applicationconfigsecret token furthermore it is used at all,['ruby-on-rails'] +533735,lync inconsistent behavior with contactendpoints i am working on custom ui for companys directory based on lync using lync 2013 i execute this searchcontainerinstancelynccontactmanagerbeginsearchsearchquery searchprovidersglobaladdresslist searchfieldsallfields searchoptionsincludecontactswithoutsiporteluri 500 contactsandgroupscallback searchqueryfor each of matching contacts i try to access their endpoints to thisplay phone numbervar cit contactinformationtypecontactendpointsvar endpoints contactgetcontactinformationcit as listobjectproblemif found contact is in the contact list of account i am using to connect lync then i get access to full details 5 endpoints however if he is not in contact list i get access to only 1 endpointany ideas why is it happening like that is there a global privacy setting i need to turn off or somethinghow can i get access to all endpoints at all timesthank youps i tried to load each contact in the result set individually and still get the same behavior,['c#'] +533805,carmen rails country select wrong number of arguments 3 for 0 trying to get carmen rails up and running to add country and subregionstate to my homerolled user registration and came across an issue i am having w little help from any online searches at least from what i can findinstalled gem carmenrails 100following the github instructions the following code should be inserted into my registration page simple form for user do f finput country code do fcountry select country code object fobject prompt country end end i am currently using rails 400 and bootstrap 3 rc2 so my registration code looks like this along with the standard form setupdiv classformgroup flabel country class colmd4 controllabel div classcolmd8 fcountry select country priority wus ca prompt please select a country class formcontrol divdivand validation section from appmodelsuserrbvalidates country presence truevalidates subregion presence truei get the error below and cannot figure out the root cause or resolution any help is greatly appreciatedwrong number of arguments 3 for 0i was getting the error below but think it was resolved by restarting the rails serverundefined method country select for,['ruby-on-rails'] +533817,exif image rotation issue using carrierwave and rmagick to upload to s3 i have got a photo upload feature in my rails app the app uploads direct to s3 through carrierwave via rmagick and fog the issue i am having is when a photo is uploaded via mobile through the take a photo option in portrait note this is with iphone but i believe android has the same issue once uploaded the image appears fine on mobile however when viewed on desktop the image appears rotated 90 degreesthrough my research it looks to be an issue with exif this stackoverflow responder outlines 2 potential solutions this gist also looks promising as wellso far i have found a few solutions posted but none have worked ideally i would like the photo to be saved to s3 as a portrait then just thisplay the image as isany suggestions are well appreciated below is my codeappuploadersimage uploaderrbclass imageuploader carrierwaveuploaderbase include carrierwavedirectuploader include carrierwavermagick include the sprockets helpers for rails 31 asset pipeline compatibility include sprocketshelpersrailshelper include sprocketshelpersisolatedhelper include carrierwavemimetypes process fix exif rotation process set content type version thumb do process resize to fill 200 200 end def extension white list wjpg jpeg png end def fix exif rotation this is my attempted solution manipulate do img img imgauto orient end endendappmodelss3 imagerbclass s3image activerecordbase attr accessible image name user id mount uploader image imageuploader belongs to user def image name filebasenameimagepath imagefilename if image end class imageworker include sidekiqworker def performid key s3 image s3imagefindid s3 imagekey key s3 imageremote image url s3 imageimagedirect fog urlwith path true s3 imagesave s3 imageupdate columnimage processed true end endendconfiginitializerscarrierwaverbcarrierwaveconfigure do config configfog credentials provider aws aws access key id aws secret access key configfog directory endbtw i used this railscast as a guide for setting up my s3 upload,['ruby-on-rails'] +533821,is it ever possible for the getpath method of a javaneturi object to return null if so when according to the uri javadoc the getpath method returns the decoded path component of this uri or null if the path is undefined emphasis added this would lead me to believe that if my application relies on the return value of getpath i might need to check if it is null however it seems that this can never happen the following code shows my attempts to construct a uri object for which getpath returns null but as you can see i have not yet found such a case could someone please explain how this might happenedit it has come to my attention that a mailto uri does not have a path however what i am really asking is can there be a uri that uses http https ftp or file scheme that has an undefinednull pathimport javaneturiimport javaneturisyntaxexceptionpublic class urigetpathnulltest public static void mainstring args throws exception test1 test2 test3 test4 test5 test6 test7 public static void test1 throws urisyntaxexception string urlstring uri uri new uriurlstring printuriuri output tostring getpath getpath null false public static void test2 throws urisyntaxexception string scheme null string ssp null string fragment null uri uri new uri scheme ssp fragment printuriuri output tostring getpath getpath null false public static void test3 throws urisyntaxexception string scheme null string userinfo null string host null int port 1 string path null string query null string fragment null uri uri new uri scheme userinfo host port path query fragment printuriuri output tostring getpath getpath null false public static void test4 throws urisyntaxexception string scheme null string host null string path null string fragment null uri uri new uri scheme host path fragment printuriuri output tostring getpath getpath null false public static void test5 throws urisyntaxexception string scheme null string authority null string path null string query null string fragment null uri uri new uri scheme authority path query fragment printuriuri output tostring getpath getpath null false public static void test6 throws urisyntaxexception string urlstring somequery uri uri new uriurlstring printuriuri output tostring somequery getpath getpath null false public static void test7 throws urisyntaxexception string urlstring somefragment uri uri new uriurlstring printuriuri output tostring somefragment getpath getpath null false public static void printuriuri uri systemoutprintlntostring uritostring systemoutprintlngetpath urigetpath systemoutprintlngetpath null urigetpath null,['java'] +533827,how to vertically align label and input in bootstrap 3 how to vertically align label and input in bootstrap 3 i would like both the label and input on same line i have played around with different classes and custom css but nothing seems to workthe jsfiddlediv classformgroup div classrow div classcolxs3 label forclass typeh2span class label labelprimaryclass typespanh2label div div classcolxs2 select nameclass type idclass type class formcontrol inputlg stylewidth200px autocompleteoff option economyoption option premium economyoption option club worldoption option first classoption select div divdiv,"['html', 'css']" +533871,how do i nslog an nsdate with the code pasted below i am trying to log an nsdate what am i doing wrong herensdateformatter formatter nsdateformatter alloc initformatter setdateformatymmddnsdate todaysdatetodaysdate nsdate datenslogtodays date is formatter,"['ios', 'objective-c']" +533877,writing ico files java recently i have become interested in creating ico file or windows icon files in java this is the current code i use i have gotten the file format specs from here 28file format29 bufferedimage img new bufferedimage16 16 bufferedimagetype int rgb graphics g imggetgraphics gsetcolorcolorgreen gfillrect0 0 16 16 byte imgbytes getimgbytesimg int filesize imgbyteslength 22 bytebuffer bytes bytebufferallocatefilesize bytesorderbyteorderlittle endian bytesputshortshort 0reserved must be 0 bytesputshortshort 1image type bytesputshortshort 1number of image in file bytesputbyte imggetwidthimage width bytesputbyte imggetheightimage height bytesputbyte 0number of colors in color palette bytesputbyte 0reserved must be 0 bytesputshortshort 0color planes bytesputshortshort 0bits per pixel bytesputintimgbyteslengthimage size bytesputint22image offset bytesputimgbytes byte result bytesarray fileoutputstream fos new fileoutputstreamcusersownerdesktoppictureico foswriteresult fosclose fosflushprivate static byte getimgbytesbufferedimage img throws ioexception bytearrayoutputstream bos new bytearrayoutputstream imageiowriteimg png bos return bostobytearraythe problem is that windows does not seem to be able to open the image giving an error when i try to open the image using windows photo gallery however when i try to open the image using gimp the image opens fine what am i doing wrong i feel like i am messing up something in the file header edit even stranger on the desktop the picture looks right just not when i try to open iton my desktop the image looks like thiswhen i try to open it in windows photo gallery it thisplays this errorafter having failed with the png attempt i tried it with bitmap image instead here is my new codeimport javaawtawtexceptionimport javaawtcolorimport javaawtgraphicsimport javaawtheadlessexceptionimport javaawtrectangleimport javaawtrobotimport javaawtimagebufferedimageimport javaiobytearrayoutputstreamimport javaiofileimport javaiofileoutputstreamimport javaioioexceptionimport javaniobytebufferimport javaniobyteorderimport javautilarraysimport javaximageioimageiopublic class iconwriter public static void mainstring args throws headlessexception awtexception ioexception bufferedimage img new bufferedimage16 16 bufferedimagetype int rgb graphics g imggetgraphics gsetcolorcolorgreen gfillrect0 0 16 16 byte imgbytes getimgbytesimg int filesize imgbyteslength 22 bytebuffer bytes bytebufferallocatefilesize bytesorderbyteorderlittle endian bytesputshortshort 0reserved must be 0 bytesputshortshort 1image type bytesputshortshort 1number of images in file bytesputbyte imggetwidthimage width bytesputbyte imggetheightimage height bytesputbyte 0number of colors in color palette bytesputbyte 0reserved must be 0 bytesputshortshort 0color planes bytesputshortshort 0bits per pixel bytesputintimgbyteslengthimage size bytesputint22image offset bytesputimgbytes byte result bytesarray fileoutputstream fos new fileoutputstreamcusersownerdesktophiico foswriteresult fosclose fosflush private static byte getimgbytesbufferedimage img throws ioexception bytearrayoutputstream bos new bytearrayoutputstream imageiowriteimg bmp bos byte bytes bostobytearray return arrayscopyofrangebytes 14 byteslength now when i try to open my image in photo gallery the image looks like this i have no idea why it is not working now and especially why the weird lines are appearing although i suspect it has to with the color planes attribute in the ico image header,['java'] +533906,whats the meaning of the asterisk in the output of uiwindow keywindow autolayouttrace uiwindow has the private method autolayouttrace that helps you to find ambigous layouts it is very nice and convenient and outputs something like thisuiwindow0x13436fd0 ambiguous layout uiview0xd5e0b30 pbjellycontentcontainerview0xd5e0ff0 uiview0x20710ee0 pbmapcontainerview0x20710c90 mkmapview0x2070df70 uiview0xd1cca20 mkbasicmapview0xd1cd020my question is not about any ambiguity it is about the asterisk in front of some views what is its meaningmy guess would be that it marks all views that are using auto layout but how does the system determine thisupdateit seems that the asterisk marks all views that either have at least one constraint set or that have a subview that has at least one constraint setsetting translatesautoresizingmaskintoconstraints to false without setting a constraint does not give the asterisk,"['iphone', 'ios', 'objective-c']" +533911,is there an auto update option for datetimefield in peewee like timestamp in mysql i would like a timestamp field updating each time the record is modified like in mysqldatetimefielddefaultdatetimedatetimenow will only set it the first time it is createdany have a simple solutionis the only solution is to manually set the column options in mysql db,['mysql'] +533921,how do i change the browser acceptlanguage if the user has their browser set to frca for instance but my site has the option to view the page in another available language like english how can i override the acceptlanguage header so that i can reload using the specified languagei was attempting to simply change the acceptlanguage header and then reload the page but i am not sure how to do this any thoughtsupdateok so i am getting people explaining to me what localization is so i must not have asked this properly my site currently has globalization set to auto in the webconfig so it will automatically set the thread culture to whichever language was negotiated at app start by default the users browser will send the acceptlanguage header based on the language settings for the browser which like someone pointed out below average users have no clue what those are where those are or how to change them in any case let us call this default behavior that the browser will handle the language headers first however as a feature i want to allow the user to change this acceptlanguage header from the page for instance in the application the language settings will normally be determined by cookie or by user preference via profile settings but on the landinglogin page particularly if this your first time logging in on a certain computer i have no idea who you are so i only have your browser settings to go off of but let us say that youre traveling on business and accessing this site from an american computer the page loads in english and you cannot read it and you have no idea how to change the browser language would it not be nice to have the option to choose your language from a drop down menu or icon or something i think it would be so in order to do that i need to be able to change that acceptlanguage header and reload the page this is where i am not sure how to proceedi have tried navigatorlanguage selected language and xhrsetrequestheader but these do not seem to work,"['javascript', 'jquery']" +533982,how to keep shape in ilcube i want to plot some 3d surfaces with ilnumerics i noticed that ilcube does not keep the shape of surface if i rotate it and it is because it tries to fit the cube in the ilpanel if i use ilcamera however it will keep the shape but there is no cube around it here is an exampleprivate void ilpanel1 loadobject sender eventargs e var scene new ilscene ilarrayfloat a ilspecialdatatorus075f 025f var sf new ilsurfacea var pc new ilplotcube pctwodmode false sceneaddpc pcaddsf sfcolormap colormapsjet var cb new ilcolorbar cblocation new pointf1 1f sfchildrenaddcb ilpanel1scene sceneand the result isand for ilcameraprivate void ilpanel1 loadobject sender eventargs e var scene new ilscene ilarrayfloat a ilspecialdatatorus075f 025f var sf new ilsurfacea var cam scenecamera camaddsf sfcolormap colormapsjet var cb new ilcolorbar cblocation new pointf1 1f sfchildrenaddcb ilpanel1scene sceneand the result isis there any way to make the ilcube to keep the shape of the surface or add a cube around the surface to the ilcamera thanks,['c#'] +534011,why should one prefer call user func array over regular calling of function function foobararg arg2 echo function got arg and arg2nfoobaronetwo outputs foobar got one and two call user func arrayfoobar arrayone two outputs foobar got one and two as i can see both regular one and call user func array method both outputs same then why should one prefer itin which scenario regular calling method will fail but call user func array will notcan i get any such example thank you,['php'] +534202,httpmethoddelete not working with resttemplate of springandroid i am trying to use delete method of httpmethod the code that i am using for that is response resttemplateexchangeurl httpmethoddelete requestentity responseclassi am also using jacksonjson for mapping json the delete functionality returns the json which should be mapped to response class but calling the above line does not works and gives internal server error with 500 as response code but the same api does work with restclient in the browser so i guess there is something that i am not doing correctly,['android'] +534244,getting the first non none value from list given a list is there a way to get the first nonnone value and if so what would be the pythonic way to do sofor example i havea objaaddresescountrycode b objbcountrycodec none d cain this case if a is none then i would like to get b if a and b are both none the i would like to get dcurrently i am doing something along the lines of a or b or c or d is there another way,['python'] +534265,how can i use words in php date format i want to use php date to write something likegenerated fri aug 30 2013 at 100pmusingecho generated dated m j y at giahowever i cannot use the at because that is swapped with 00amis there a way to include the word at in the date formation without using two date,['php'] +534266,bootstrap 3 navbar branding colour i am using the bootstrap 3 navbar but cant for some reason change the brand text colour nor the dropdown triangles i have tried a couple of things but still no luck navbar nav navbarbrand a textshadow 0 1px 0 rgba0 0 0 025 color d6d6d6 navbarbrand textshadow 0 1px 0 rgba0 0 0 025 color d6d6d6navbarbrand a textshadow 0 1px 0 rgba0 0 0 025 color d6d6d6,['css'] +534330,doctrine 2 where in clause using a collection of entities i am attempting to build a query in doctrine 2 that finds all vacancy entities which are related to any of the given vacancyworkinghours entitiesthe vacancy entity looks as follows vacancy ormtablenamevacancy ormentityrepositoryclassjaikdeancareersbundleentityvacancyrepository class vacancy var integer ormcolumnnameid typeinteger ormid ormgeneratedvaluestrategyauto private id var vacancyworkinghours ormmanytoonetargetentityvacancyworkinghours inversedbyvacancies ormjoincolumnnamevacancy working hours id referencedcolumnnameid private workinghours other fields and methods are inconsequential my query currently looks as follows but returns no results because of the where clause in this example workinghours is a doctrinecommoncollectionsarraycollection instance containing a number of vacancyworkinghours entitiesq thiscreatequerybuilderv selectv andwherevworkinghours in workinghours setparameterworkinghours workinghourstoarray,['php'] +534336,how to thisable address bar showing on js events in ie 11 on windows 81 there is a web application basically a web page coming from the server which was developed for a client using ms surface tablets which were running windows rt when there was a shortcut tile pinned to the start screen of the tablet and client run it from there it looked like any other metro app no address bar until user dragged edge up or downclient started using windows 81 with ie 11 now when user interacts with web page or javascript showshides something address bar pops up from the bottom edge and hides some contentis there any way to make this page not to show this address bar popupall the application is on one page and there is even no ajax requests during the typical use it is not possible to reconfigure all the users existing and future tablets so it has to be done using js or html,"['javascript', 'html']" +534354,numpy longdouble arithmetic does not seem to be in long double with conversion i have been playing c99s quad precision long double it is my understanding that platform specific numpy supports long double and 128bit floats i have run across something i cannot explain howevergiven import numpy as npcalculate a number that will require more than 64 bits but less than 128 bits to represent as an integer 264218446744073709551618 note the 8 at the end int264218446744073709551618 same obviouslyif i calculate the same number in c99 128 bit long double i get 184467440737095516180now if i use numpy long double anplongdouble2 bnplongdouble64 aba184467440737095516180 all goodwhat about these incorrect results nplongdouble2642184467440737095516160 note 6 appears 264 not done in long double nplongdoubleint2642184467440737095516160 cannot force the use of a python long nint2642 nplongdoublen184467440737095516160 nplongdouble18446744073709551618184467440737095516160 it really does not want to do 8 at the endbut this works nplongdouble2642184467440737095516180question does numpy have issues converting values correctly into long doubles is there something i am doing incorrect,['python'] +534376,core data import not releasing memory my question is about core data and memory not being released i am doing a sync process importing data from a webservice which returns a json i load in in memory the data to import loop through and create nsmanagedobjects the imported data needs to create objects that have relationships to other objects in total there are around 110 but to isolate the problem i am right now only creating the items of the first and second level leaving the relationship out those are 9043 objectsi started checking the amount of memory used because the app was crashing at the end of the process with the full data set the first memory check is after loading in memory the json so that the measurement really takes only in consideration the creation and insert of the objects into core data what i use to check the memory used is this code source void get free memory struct task basic info info mach msg type number t size sizeofinfo kern return t kerr task infomach task self task basic info task info tinfo size if kerr kern success nslogmemory in use in bytes ffloatinforesident size1024010240 else nslogerror with task info s mach error stringkerr my setup1 persistent store coordinator1 main managedobjectcontext mmc nsmainqueueconcurrencytype used to read only reading the data in the app1 background managedobjectcontext bmc nsprivatequeueconcurrencytype undomanager is set to nil used to import the datathe bmc is independent to the mmc so bmc is no child context of mmc and they do not share any parent context i do not need bmc to notify changes to mmc so bmc only needs to createupdatedelete the dataplaformipad 2 and 3 ios i have tested to set the deployment target to 51 and 61 there is no differencexcode 462arcproblemimporting the data the used memory does not stop to increase and ios does not seem to be able to drain the memory even after the end of the process which in case the data sample increases leads to memory warnings and after the closing of the appresearchapple documentation efficiently importing datareducing memory overheadgood recap of the points to have in mind when importing data to core data stackoverflowtests done and analysis of the memory release he seems to have the same problem as i and he sent an apple bug report with no response yet from apple sourceimporting and thisplaying large data sets sourceindicates the best way to import large amount of data although he mentions i can import millions of records in a stable 3mb of memory without calling resetthis makes me think this might be somehow possible sourcetestsdata sample creating a total of 9043 objectsturned off the creation of relationships as the documentation says they are expensiveno fetching is being donecode voidprocessitems selfcontext performblock for int i0 i selfdownloadedrecords count autoreleasepool self get free memory prints current memory used for nsuinteger j 0 j batchsize i selfdownloadedrecords count j i nsdictionary record selfdownloadedrecords objectatindexi item itemself createitem objectscount fills in the item object with data from the record no relationship creation is happening self updateitemitem withrecordrecord creates the subitems fills them in with data from record relationship creation is turned off self procesubitemswithitemitem andrecordrecord context save is done before draining the autoreleasepool as specified in research 5 selfcontext savenil faulting all the created items for nsmanagedobject object in selfcontext registeredobjects selfcontext refreshobjectobject mergechangesno double tap the previous action by reseting the context selfcontext reset self check memory performs a repeated selector to self get free memory to view the memory after the sync measurmentit goes from 1697 mb to 30 mb after the sync it goes down to 28 mb repeating the get memory call each 5 seconds maintains the memory at 28 mb other tests without any luckrecreating the persistent store as indicated in research 2 has no effecttested to let the thread wait a bit to see if memory restores example 4setting context to nil after the whole processdoing the whole process without saving context at any point loosing therefor the info that actually gave as result maintaing less amount of memory leaving it at 20 mb but it still does not decrease and i need the info stored maybe i am missing something but i have really tested a lot and after following the guidelines i would expect to see the memory decreasing again i have run allocations instruments to check the heap growth and this seems to be fine too also no memory leaksi am running out of ideas to testadjust i would really appreciate if anyone could help me with ideas of what else i could test or maybe pointing to what i am doing wrong or it is just like that how it is supposed to work which i doubtthanks for any helpediti have used instruments to profile the memory usage with the activity monitor template and the result shown in real memory usage is the same as the one that gets printed in the console with the get free memory and the memory still never seems to get released,"['ios', 'objective-c']" +534428,speed up sampling of kernel estimate heres a mwe of a much larger code i am using basically it performs a monte carlo integration over a kde kernel density estimate for all values located below a certain threshold the integration method was suggested over at this question btw integrate 2d kernel density estimateimport numpy as npfrom scipy import statsimport time generate some random twodimensional datadef measuren measurement model return two coupled measurements m1 nprandomnormalsizen m2 nprandomnormalscale05 sizen return m1m2 m1m2 get datam1 m2 measure20 define limitsxmin m1minxmax m1maxymin m2minymax m2max perform a kernel density estimate on the datax y npmgridxminxmax100j yminymax100jvalues npvstackm1 m2kernel statsgaussian kdevalues define point below which to integrate the kernelx1 y1 05 05 get kernel value for this pointtik timetimeiso kernelx1y1print iso timetimetik sample from kde thistribution monte carlo processtik timetimesample kernelresamplesize10print resample timetimetik filter the sample leaving only values for which the kernel evaluates to less than what it does for the x1 y1 point defined abovetik timetimeinsample kernelsample isoprint filtersample timetimetik integrate for all values below isotik timetimeintegral insamplesum floatinsampleshape0print integral timetimetikthe output looks something like thisiso 0259208679199resample 0817060470581filtersample 210829401016integral 422088501e05which clearly means that the filtersample call is consuming almost all of the time the code uses to run i have to run this block of code iteratively several thousand times so it can get pretty time consumingis there any way to speed up the filteringsampling processaddheres a slightly more realistic mwe of my actual code with ophions multithreading solution written into itimport numpy as npfrom scipy import statsfrom multiprocessing import pooldef kde integrationm list m1 m2 for item in m list color data m1appenditem0 magnitude data m2appenditem1 define limits xmin xmax minm1 maxm1 ymin ymax minm2 maxm2 perform a kernel density estimate on the data x y npmgridxminxmax100j yminymax100j values npvstackm1 m2 kernel statsgaussian kdevalues out list for point in m list compute the point below which to integrate iso kernelpoint0 point1 sample kde thistribution sample kernelresamplesize10 create definition def calc kernelsamp return kernelsamp choose number of cores and split input array cores 4 torun nparray splitsample cores axis1 calculate pool poolprocessescores results poolmapcalc kernel torun reintegrate and calculate results insample mp npconcatenateresults iso integrate for all values below iso integral insample mpsum floatinsample mpshape0 out listappendintegral return out list generate some random twodimensional datadef measuren measurement model return two coupled measurements m1 nprandomnormalsizen m2 nprandomnormalscale05 sizen return m1m2 m1m2 create list to passm list for i in range60 m1 m2 measure5 m listappendm1tolist m listappendm2tolist call kde integration functionprint integral result kde integrationm listthe solution presented by ophion works great on the original code i presented but fails with the following error in this versionintegral result exception in thread thread3traceback most recent call last file usrlibpython27threadingpy line 551 in bootstrap inner selfrun file usrlibpython27threadingpy line 504 in run self targetself args self kwargs file usrlibpython27multiprocessingpoolpy line 319 in handle tasks puttaskpicklingerror cannot pickle type function attribute lookup builtin function failedi tried moving the calc kernel function around since one of the answers in this question multiprocessing using poolmap on a function defined in a class states that the function that you give to map must be accessible through an import of your module but i still cannot get this code to workany help will be very much appreciatedadd 2implementing ophions suggestion to remove the calc kernel function and simply usingresults poolmapkernel torunworks to get rid of the picklingerror but now i see that if i create an initial m list of anything more than around 6263 items i get this errortraceback most recent call last file gauss kde temppy line 67 in module print integral result kde integrationm list file gauss kde temppy line 38 in kde integration pool poolprocessescores file usrlibpython27multiprocessing init py line 232 in pool return poolprocesses initializer initargs maxtasksperchild file usrlibpython27multiprocessingpoolpy line 161 in init self result handlerstart file usrlibpython27threadingpy line 494 in start start new threadself bootstrap threaderror cannot start new threadsince my actual list in my real implementation of this code can have up to 20 items this issue renders the code unusable line 38 is this onepool poolprocessescoresso apparently it has something to do with the number of cores i am usingthis question cant start a new thread error in python suggests usingthreadingactive countto check the number of threads i have going when i get that error i checked and it always crashes when it reaches 374 threads how can i code around this issueheres the new question dealing with this last issue thread error cant start new thread,['python'] +534453,how can we detect system volume in windows 8 if i have an app that plays sounds it seems like a good idea to indicate why the user is not hearing the sounds is there a way to detect system volume or mute,['c#'] +534502,facebook sdk ios fail to share url error 102 i am trying to integrate a simple url share on my app following the dedicated facebook tutorial linkon my app i simply click on a button which thisplays a dialog where i can type in a commentthis part works find yet when i click on post i get the following error error domaincomfacebookfacebookplatform code102 the operation couldnat be completed comfacebookfacebookplatform error 102 userinfo0x14dd1a10 error messagefailed to authenticate the application because of app name mismatch please check the application name configured by the dialog app id0 error code102in this message i just replaced with zeroes the app id i got from the facebook developer pageon the facebook app settings i set the following as such thisplay name the same name as the app name bundle id with the string return by nsbundle mainbundle bundleidentifierthe app is live not in sandboxdeep linking and connect to fb both activatedwhen i save my settings on the fb dev page i get a warning saying that i did not set an appstore identifier which is not yet available since i am developing the appcan you please tell me the little thing that i did not do correctly thanks in advance for your replyi will be happy to provide you with more info if necessary,['ios'] +534514,map vs object in javascript i just thiscovered chromestatuscom and after losing several hours of my day found this feature entrymap map objects are simple keyvalue mapsthat confused me regular javascript objects are dictionaries so how is a map different from a dictionary conceptually they are identical according to what is the difference between a map and a dictionarythe documentation chromestatus references does not help eithermap objects are collections of keyvalue pairs where both the keys and values may be arbitrary ecmascript language values a thistinct key value may only occur in one keyvalue pair within the mapas collection thistinct key values as thiscriminated using the a comparision algorithm that is selected when the map is createda map object can iterate its elements in insertion order map object must be implemented using either hash tables or other mechanisms that on average provide access times that are sublinear on the number of elements in the collection the data structures used in this map objects specification is only intended to describe the required observable semantics of map objects it is not intended to be a viable implementation modelastill sounds like an object to me so clearly i have missed somethingwhy is javascript gaining a wellsupported map object what does it do,['javascript'] +534543,can bindings create memory leaks in wpf do i need to unbind items as the item thisappears in order to prevent memory leaks i guess i am just a little worried that if i reload and a new template is applied to a control and in that template there exists a binding to an outside element could that prevent the control made for the template from being garbage collected,['c#'] +534597,onchange event on input typerange is not triggering in firefox while dragging when i played with input typerange firefox triggers an onchange event only if we drop the slider to a new position where chrome and others triggers onchange events while the slider is draggedhow can i make it happen on dragging in firefoxhtmlspan idvalboxspaninput typerange min5 max10 step1 onchangeshowvalthisvaluescriptfunction showvalnewval documentgetelementbyidvalboxinnerhtmlnewval,['javascript'] +534656,xpath with multiple contains on different elements is it possible to have xpath expression with multiple contains of different element valuesxmldata person firstnamekerryfirstname lastnamepackerlastname addresscrownaddress person person firstnamekerryfirstname lastnamemurdochlastname addresscaliforniaaddress persondataphpxml simplexml load stringdataelements xmlxpathpersonfirstnamecontains kerr and lastnamecontains ochcurrently above xpath expression is flagged as invalid however if i use it with one element xmlxpathpersonfirstnamecontains kerr then it works fine,['php'] +534682,pandas can only compare identicallylabeled dataframe objects error i am using pandas to compare the outputs of two files loaded into two data frames uat produat uatcustomer numberproductprod prodcustomer numberproductprint uatcustomer number prodcustomer numberprint uatproduct prodproductprint uat prodthe first two match exactly74357 true74356 truename customer number dtype bool74357 true74356 truename product dtype boolfor the third print i get an errorcan only compare identicallylabeled dataframe objects if the first two compared fine whats wrong with the 3rdthanks,['python'] +534776,how to force release on ios i am new to arc but understand how it works and i am trying it out i am on ios so memory is a severe concern i have a myobject class which contains lots of big data i want to release it and load a new set of datamyobject objectobject myobject alloc initwithdatafolder1 load data from folder1 laterobject myobject alloc initwithdatafolder2 load data from folder2this works fine without leaks and i am guessing the arc inserts a object release before the new assignment my problem is the data inside object is released after the new set is allocated and i run out of memory what i really want to be able to do isobject nilfunction to pop the pool wait till everything is deallocatedobject myobject alloc initwithdatafolder2 load data from folder2but i am not sure how to do that i could run the new allocation on a performselector afterdelay but it feels like i am shooting in the dark and a bit of hack there is probably a proper way to do thisps i have tried searching for an answer but all results are about memory leaks and how to make sure variables go out of scope and set variables to nil etc my issue is not about that it is more of a timing thing updatethanks for the answers i would already tried object nilobject myobject alloc initwithdatafolder2and it had not worked i was not sure whether it was supposed to or not now i understand that it is supposed to work but i must have something else holding on to it for that fraction of a second i have nslogs in all of my initdealloc methods and i can see first all the inits of the new instances of classes of myobjects ivars being called and then almost immediately after within a few ms the dealloc of myobject followed by the deallocs of its ivarsi also tried the autorelease but the same thing happensi have searched throughout the project and pasted all the code which i think may be relevant to this interface appdelegate uiresponder uiapplicationdelegate property pbsoundsession soundsessionendimplementation appdelegate ontimer fired at 60hzvoidontimernstimer thetimer oscreceiver readincoming check incoming osc messages then do a bunch of stuff with soundsessionendimplementation oscreceivervoidreadincoming appdelegate appdelegate appdelegateuiapplication sharedapplication delegate parse all incoming messages ifbloadnewsoundbank nsstring newfolder parsenewfolder appdelegatesoundsession nil appdelegatesoundsession myobject alloc initwithdatanewfolder endimplementation guicontroller ontimer fired at 10hzvoidontimernstimer thetimer pbsoundsession soundsession appdelegatesoundsession update gui with received valuesendi thought it might be the soundsession local variable in the guicontrollerontimer holding onto the old appdelegatesoundsession for the duration of that method but to my surprise commenting out all of the gui code in fact thisabling the timer made no difference is there a way of finding out at that point who is still holding onto my appdelegatesoundsession i placed a breakpoint where i set it to nil but could not find any useful information i tried instruments in allocation template but could not find anything useful there either probably because i do not know where to look this is what my allocations track looks like you can see the memory is all deallocated a bit too late,"['ios', 'objective-c']" +534815,how to generate a url for aspnet mvc action including hostname and port my current request isi want thisplay an action url in aspnet view layer url is like thisfull url including httpprotocol hostname port controllername actionname,['asp.net'] +534834,how to implement matlabs mldivide aka the backslash operator i am currently trying to develop a small matrixoriented math library i am using eigen 3 for matrix data structures and operations and i wanted to implement some handy matlab functions such as the widely used backslash operator which is equivalent to mldivide in order to compute the solution of linear systems expressed in matrix formis there any good detailed explanation on how this could be achieved i have already implemented the moorepenrose pseudoinverse pinv function with a classical svd decomposition but i have read somewhere that ab is not always pinvab at least matalb does not simply do thatthanks,['c++'] +534858,implementing glsurfaceviewrenderer issues code derived from the tutoriali am beginning some opengles 20 for the android system i took the following code from public class myrenderer implements glsurfaceviewrenderer public void onsurfacecreatedgl10 unused eglconfig config gles20glclearcolor05f 05f 05f 10f public void ondrawframegl10 unused gles20glcleargles20gl color buffer bit public void onsurfacechangedgl10 unused int width int height gles20glviewport0 0 width height i am receiving the following errorgradle error myrenderer is not abstract and does not override abstract method onsurfacecreatedgl10eglconfig in rendererdoes anyone know how to proceed i need to use the myrenderer class to pass to the glsurfaceview so simply declaring it abstract is not a viable solution can anybody shed some light on my problem,['android'] +534867,unable to add properties to js object i am returning a mongoose document and wish to add some meta data to it before i send it off i am however unable to add any properties and i am not sure why i have checked that it is extensible with objectisextensibledoc and it isitemfindbyidreqparamsidexecfunctionerr doc docblah hello consolelogdoc no trace of blah i can changedelete existing props howeverwhat could be issue,['javascript'] +534885,pandas aggregate count thistinct let us say i have a log of user activity and i want to generate a report of total duration and the number of unique users per dayimport numpy as npimport pandas as pddf pddataframedate 20130401201304012013040120130402 20130402 user id 01 01 02 02 02 duration 30 15 20 15 30aggregating duration is pretty straightforwardgroup dfgroupbydateagg groupaggregateduration npsumagg durationdate20130401 6520130402 45what i would like to do is sum the duration and count thistincts at the same time but i cannot seem to find an equivalent for count thistinctagg groupaggregate duration npsum user id count thistinctthis works but surely there is a better way nogroup dfgroupbydateagg groupaggregateduration npsumagguv dfgroupbydateuser idnuniqueagg duration uvdate20130401 65 220130402 45 1i am thinking i just need to provide a function that returns the count of thistinct items of a series object to the aggregate function but i do not have a lot of exposure to the various libraries at my thisposal also it seems that the groupby object already knows this information so wouldnt i just be duplicating effort,['python'] +534917,what does systemreflectionmissingvalue do i encountered a code given below object omissing systemreflectionmissingvalueodatadoc wrdappdocumentsopenref oname ref omissing ref omissing ref omissing ref omissing ref omissing ref omissing ref omissing ref omissing ref omissing ref omissing ref omissing ref omissing ref omissing ref omissingi dont understand what will ref omissing do will it automatically get the values or something like that please help as soon as possible,['c#'] +534919,backtick in ruby does not work with tail f command the code below does not print the output of tail f why how can i make it workmyapprbls works finetail f filename does not work why,['ruby'] +534927,android studio unable to open png file i am trying to integrate facebook into my app but while running it in android studio i get thisgradle execution failed for task aplikacebeta101mergedebugresources failed to run command cusersdavidappdatalocalandroidandroidstudiosdkbuildtoolsandroid422aaptexe s i cusersdaviddesktopfacebookandroidsdk35facebookandroidsdk35samplesaplikacebeta101projectaplikacebeta101buildexplodedbundlesaplikacebeta101projectlibrariesfacebookunspecifiedaarresdrawablecom facebook profile picture blank squarepng o cusersdaviddesktopfacebookandroidsdk35facebookandroidsdk35samplesaplikacebeta101projectaplikacebeta101buildresalldebugdrawablecom facebook profile picture blank squarepng error code 42 output cusersdaviddesktopfacebookandroidsdk35facebookandroidsdk35samplesaplikacebeta101projectaplikacebeta101buildexplodedbundlesaplikacebeta101projectlibrariesfacebookunspecifiedaarresdrawablecom facebook profile picture blank squarepng error unable to open png fileunable to open png file whatcode is totally the same as in getting started with the facebook sdk for android android studio guide it is really simple this is my mainactivityjavapackage comexampleaplikacebeta101import androidosbundleimport androidappactivityimport androidcontentintentimport androidwidgettextviewimport comfacebookimport comfacebookmodelpublic class mainactivity extends activity override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main start facebook login sessionopenactivesessionthis true new sessionstatuscallback callback when session changes state override public void callsession session sessionstate state exception exception if sessionisopened make request to the me api requestexecutemerequestasyncsession new requestgraphusercallback callback after graph api response with user object override public void oncompletedgraphuser user response response if user null textview welcome textview findviewbyidridwelcome welcomesettexthello usergetname overridepublic void onactivityresultint requestcode int resultcode intent data superonactivityresultrequestcode resultcode data sessiongetactivesessiononactivityresultthis requestcode resultcode dataany ideas i know android studio is still eap but i think this is not caused by android studio,['android'] +534981,gridview with different cells sizes pinterest style backgroundgridview is a class that extends adapterview which means it shows cells in a gridstyle efficiently recycling old views to be shown as new ones when the user scrolls itthe problemsometimes you would want to get a special ui which resembles the windows phone tiles ui having cells of different sizes on top of each othersomething like thisaabbaaccaaddaaddeach letter represents a part of its cell so cell a is 2x4 cell b and cell c take 2x1 each and cell d is 2x2 it could be even more than that where cell d finished a bit above what i have shown and right beneath it there is another cell so the end of d and the end of a are not necessary alignedan example of an app that has this style is pinterest gridview does not allow such a thingin fact every solution i have tried has issues would like to ask if there are any other alternatives or better solutionswhat i have foundthere are multiple ways to handle this problemas a class that extends adapterview gridview has the ability to have a type for each item using the baseadapter which would allow you to set how to layout the cell however it still limits you since you will get rows of items one beneath the other you have to have them alignedgridlayout is a relatively new layout and it is quite flexible google has published a nice compatibility library for it supporing api7 and abovehowever it does not use any recycling of views so it is a bad choice in case you wish to show a lot of itemsif you have a lot of items you would need to create all of the views for them quiltview library extends from gridlayout so basically has the same problem like itstaggeredgridview looks the most promising but has a lot of bugs especially when changing orientation such bugs include empty cells bad scrolling and npes rare but still happens i am also not sure if it supports having customized cells instead of imageviews alone other solutions as mentions here the questiondoes anyone know of another alternative to this problem maybe some workarounds for any of the solutions i have shownedit i think that about staggeredgridview the scrolling and exceptions can be solved by using a normal imageview that you set its size inside the getview i think that the reason for it to work in a weird way is that the sample updates the size of the imageview after it was loaded from the internet however empty cells issue still remains in this library not only that but their sizes change a lot even without changing the orientationedit for now i think the best solution is to use pinterestlikeadapterview library it does not have any issues that i can find however it cannot make items to take more than 1 cell width it is very good neverthelessedit sadly it has issues with notifydatasetchanged i have reported about it here,['android'] +534987,what effect does define x x have in c in the source code of stdboolh in llvm project it reads do not define bool true and false in c except as a gnu extension ifndef cplusplusdefine bool booldefine true 1define false 0elif defined gnuc defined strict ansi define bool bool false true as a gnu extension define bool booldefine bool booldefine false falsedefine true trueendifin the last 4 lines there are three lines of the from define x x why would you do that what difference does it make wouldnt this force compiler to just replace say true with true,"['c++', 'c']" +535021,reading and writing fromto java preferences fails on fresh windows 8 i have a java application that reads from the preferences by usingpreferences prefs preferencesusernodeforpackagemyclassclassprefsgetstringkey on a fresh windows 8 machine this fails withwarning could not opencreate prefs root node softwarejavasoftprefs at root 0x802 windows regcreatekeyex returned error code 5error code 5 is access deniedi cannot find anything i am doing wrong google and so searches give old results relating only to windows vista7 where one was wrongly using systemroot how can i write system preferences with java can i invoke uac the error can be cured by creating hklmsoftwarejavasoftprefs and setting permissions to hklmsoftwarejavasoft as mentioned here java javautilpreferences failing but this is not something i can require my users to do when they install the program so i am looking for a better solution my last ditch effort is to simply write to file but i would like to avoid that this also seems related im trying to use java prefences from xml without using windows registry but i see a registryrelated message but it was down voted without an answerat current i suspect a win8 jvm bugquestionsdoes any one know of a solution that does not involve writing fileswhy does the same code work perfectly fine in windows 7 but fails miserably in windows 8,['java'] +535041,android gradle build fails could not find comgoogleandroidsupportv4r18 editthis issue seemed to thisappear by its own somehow possibly due to the new gradle build system becoming more maturei have two separate android projectsthe 1st project is an android library using androidlibrary plugin for gradle which depends on the supportlibraryv4r18 snippet from dependencies in buildgradlecompile comandroidsupportsupportv41800the support library is fetched from android support repository installed via android sdk manager as explained here this project is then built and published to maven local repository by running gradle uploadarchivesi verified and indeed the library aar is then available under the local maven repositorythe 2nd project is an android app using android plugin for gradle which references the maven dependency of the library produced by the first project here is a snippet from buildgradlerepositories mavenlocal mavencentraldependencies compile comandroidsupportsupportv41800 compile comexamplecoollib100snapshotnote the two projects are completely separated from another meaning that they are not subprojects of the same root projectwhen i try to build the 2nd project by running gradle assemblei get the following errorcould not find comgoogleandroidsupportv4r18required by comexampleaprojectunspecified comexamplecoollib100snapshoti checked the pom file of coollib under my local maven repo folder and i saw that it has the following dependencydependency groupidcomandroidsupportgroupid artifactidsupportv4artifactid version1800version scopecompilescopedependencyfor some reason gradle is trying to get the support libraryv4 r18 for the libproject from maven central repository instead of getting it from android support repository it fails since the latest version in maven central of the supportlibraryv4 is r7is there a way to force gradle to strictly fetch the supportlibraryv4 r18 from android support repository also for external android libraries which are referenced from maven central,['android'] +535064,uisearchthisplaycontroller and uitableview prototype cell crash i have a uiviewcontroller setup in a storyboard with a tableview and uisearchthisplaycontrolleri am trying to use a custom prototype cell from selftableview which is connected to main tableview in the storyboard it works fine if selftableview had returned at least 1 cell when i load my view but if selftableview does not load a cell as there is no data and i load up the uisearchbar and search the cellforrowatindexpath method crashes uitableviewcell tableviewuitableview tableview cellforrowatindexpathnsindexpath indexpath customsearchcell cell selftableview dequeuereusablecellwithidentifiercustomsearchcell forindexpathindexpath self configurecellcell atindexpathindexpath return cellvoidconfigurecellcustomsearchcell cell atindexpathnsindexpath indexpath user user selffetchedresultscontroller objectatindexpathindexpath cellnamelabeltext userusernameerrors assertion failure in uitableviewrowdata rectforrowinsectionheightcanbeguessed terminating app due to uncaught exception nsinternalinconsistencyexception reason request for rect at invalid index path nsindexpath 0x9ef3d00 length 2 path 0 0my fetchedresultscontroller seems to have data 1 section 2 rows at the point the above method is called it crashes on the dequeuereusablecellwithidentifier lineany pointersideas it should dequeue the prototype cell from selftableview but my guess is there was none created in selftableview so this is the cause,"['iphone', 'ios', 'objective-c']" +535068,printing issue with hindi unicode on windows and ubuntu both i am working with hindi text on pdf though hindi text is generating but its showing as misplaced matras suppose i have word like aa14aa a but its showing as if i copy this text and paste on libre office writer then it prints correct i have tried nearly two fonts with tcpdf arial unicode ms as well as lohit hitcpdfsetfontarialuni b 15 falsehtml nl2brresultsonghinditcpdfwritehtmlcell0 20 20 25 htmlwhy its showing character but misplaced their position,['php'] +535075,regarding typedefs of 1element arrays in c sometimes in c you do thistypedef struct foo unsigned int some data foo btw foo t is thiscouraged to use this new type in an oosortofway you might have allocfree pairs like thesefoo foo alloc various constructor params void foo freefoo baror alternatively initclear pairs perhaps returning errorcodesint foo initfoo bar and various constructor params int foo clearfoo bari have seen the following idiom used in particular in the mpfr librarystruct foo unsigned int some datatypedef struct foo foo1 notice 1element array typedef struct foo foo ptr let us create a ptrtype the allocfree and initclear pairs now readfoo ptr foo alloc various constructor params void foo freefoo ptr barint foo initfoo ptr bar and various constructor params int foo clearfoo ptr barnow you can use it all like this for instance the initclear pairsint main foo bar constructed but not initialized yet foo initbar initialize bar object alloc stuff on heap etc use bar foo clearbar clear bar object free stuff on heap etc remarks the initclear pair seems to allow for a more generic way of initializing and clearing out objects compared to the allocfree pair the initclear pair requires that a shallow object has already been constructed the deep construction is done using initquestion are there any nonobvious pitfalls of the 1element array typeidiom,['c'] +535115,opencv python cannot use surf sift i am trying a simple thing like detector cv2siftand get this bad errordetector cv2siftattributeerror module object has no attribute sifti do not understand that because cv2 is installedcv2version isrev 4557 my system is ubuntu 1204maybe someone has got the same problem and could help methanks a loteditlong story short testypypypypyimport cv2detector cv2sifterrortraceback most recent call last file testypypypy line 3 in module detector cv2siftattributeerror module object has no attribute siftif i take surf it works because surf is in dircv2 but if i also take cv2bfmatcher i get the same errorso it is missing and i have to add it but i do not know how,['python'] +535124,how to prevent onnavigationitemselected fires when the activity is launched i want to use spinner in the action bar in my activity below is the oncreateoptionsmenu i use this tutorial to achieve this approach my problem is when the activity is lunch the onnavigationitemselected method fires and the code on the switchcase run and the activity that i set for the position 0 opens what should i do to prevent to run the switchcase when the activity is lunchoverridepublic boolean oncreateoptionsmenumenu menu getsupportmenuinflaterinflatermenumain menu spinneradapter mspinneradapter ifbuildversionsdk int 10 mspinneradapter arrayadaptercreatefromresourcethis rarrayspinner dataandroidrlayoutsimple spinner item else mspinneradapter arrayadaptercreatefromresourcethis rarrayspinner dataandroidrlayoutsimple spinner dropdown item actionbaronnavigationlistener monnavigationlistener new actionbaronnavigationlistener override public boolean onnavigationitemselectedint position long itemid switch position case 0 intent searchintent new intentactivitysearchbusinessthis activityfindbusinesscityclass startactivitysearchintent break case 2 intent dealsintent new intentactivitysearchbusinessthis activitydealsclass startactivitydealsintent break case 3 intent eventsintent new intentactivitysearchbusinessthis activityeventsclass startactivityeventsintent break return true actionbarsetlistnavigationcallbacksmspinneradapter return superoncreateoptionsmenumenu,['android'] +535136,windowbuilder equivalent for intellij there is a plugin for eclipse called windowbuilder is there an equivalent for intellij,['java'] +535139,possible to add mime type to webconfig without possibly breaking the site i had a webconfig in one of the websites on my iis that was adding a support for 7z file extension when i later added a global 7z support at the server level this site was broken iis manager is complaining that it cannot add duplicate collection entry of type mimemap and all web requests to ig css files ended with an http 500 errori was using this in the sites webconfigsystemwebserver staticcontent mimemap fileextension7z mimetypeapplicationx7zcompressed staticcontentsystemwebserveris there maybe some other syntax that would add 7z to the list only if it was not defined yet,['asp.net'] +535187,in the xcode lldb debugger what does mean i am always getting exc bad access so i look to see which variable is pointing to null and all i see is that one of my variables sometimes several has parent is null next to it the problem is i do not really know what this means and i cannot seem to find anything from a google search or anything about it i am thinking this means that that is the null variable i am trying to access but then the message does not make much sense anybody know a little more on this,['ios'] +535235,clock configuration of rtc in stm32l in lsilsehse only i am implementing real time clock on stm32l152rb thiscovery board using iar compiler i have implemented the clock configuration on hsi and using pll i have multiplied it by 4 code enable hsi clock rcc hsicmdenable wait till hsi is ready while rcc getflagstatusrcc flag hsirdy resetrcc pllconfigrcc pllsource hsircc pllmul 4rcc plldiv 2rcc pllcmdenable while rcc getflagstatusrcc flag pllrdy reset set hsi as sys clockrcc sysclkconfigrcc sysclksource pllclkthe problem is while configuring real time clock i have to set the secondary clock lse as the rtc clock source which in my case my source clock is hsi rest of the steps which includes enable pwr controller enable rtc domain access rtc clock source rtc init then settime and gettime are alright as per i know here is the code i tried enable rtc clocks and rtc related functions rcc apb1periphclockcmdrcc apb1periph pwr enablepwr rtcaccesscmdenablercc rtcclkconfigrcc rtcclksource lse this part i think is wrongrcc rtcclkcmdenablertc inittypestructurertc hourformatrtc hourformat 12rtc inittypestructurertc asynchprediv0x7frtc inittypestructurertc synchprediv0xffrtc initrtc inittypestructure end rtc clock rtc timetypetimertc hours18rtc timetypetimertc minutes11rtc timetypetimertc seconds4rtc timetypetimertc h12rtc h12 pmrtc settimertc format bin rtc timetypetimewhile1 f sleepms10 rtc gettimertc format bin rtc timetypetime release msgrdrtc timetypetimertc hoursrtc timetypetimertc minutesrtc timetypetimertc seconds output i get is 0,['c'] +535248,animating uiview transitions like expand dot to circle in my iphone app i need to implement a different type of transitionthat was next view open from the current view it stats like a dot and the dot expands slowly like a circle with in the circle next view is to be thisplayed partially with in the part of the circle finally the circle expands totally the next view appears completelyi search lots of transitions like catransitions and some animations on cocoa controller but i did not find this type of transition can any one help me please,"['iphone', 'ios', 'objective-c']" +535339,how to convert date to a format mmddy i am having a sql table with date column named created ts which holds the dates in different format eg as shown belowfeb 20 2012 1200am112912 82053 pm feb 20 2012 1200am112912 82053 pm feb 20 2012 1200am112912 82053 pm nov 16 2011 1200amfeb 20 2012 1200am112912 82052 pmnow i want to convert these to format mmddy before as i am comparing the dates in where clause of my select query i tried usingconvertvarchar10created ts101but got the result asfeb 20 2012912 feb 20 2012912 feb 20 2012912 nov 16 201feb 20 2012912 i need the result as eg 02202012 in order to compareany help will be appreciated,['sql'] +535361,how to add new seed data to existing rails database i am working on an application that is already deployed to some test and staging systems and various developers workstations i need to add some additional reference data but i am not sure how to add itmost of the advice says use seedrb however my understanding is that this is only run once when the application is initially deployed since we do not want to rebuild the test and staging databases just so that we can add 1 row of reference data is there another way to add the datai am thinking of using a db migration is this the correct approachthanks,['ruby-on-rails'] +535371,httppostedfilebase is null when uploading files with angular i use angular in combination with mvc when i want to upload a file the httppostedfilebase is nullhtmlinput typefile datangmodelfilename onchangeangularelementthisscopefileinputchangedthisangularscopefileinputchanged function element scopeapplyfunction scope consolelogfiles elementfiles eachelementfiles function element index list scopefilespushelement scopeuploaddocuments function var formdata new formdata add uploaded files to form data object forvar i in scopefiles formdataappenduploadedfile scopefilesi create xml http request object var httprequest new xmlhttprequest httprequestuploadaddeventlistenerprogress uploadprogress false httprequestaddeventlistenerload uploadcomplete false httprequestaddeventlistenererror uploadfailed false httprequestaddeventlistenerabort uploadcanceled false httprequestopenpost customeruploaddocuments make progress bar visible scopeprogressvisible true send the request to the server with the form data httprequestsendformdata private functionsfunction uploadprogressevent scopeapplyfunction if eventlengthcomputable scopeprogressvalue mathroundeventloaded 100 eventtotal else scopeprogressvalue kan progressie niet berekenen function uploadcompleteevent scopehideformfalsefunction uploadfailedevent alerthet uploaden van de documenten is misluktfunction uploadcanceledevent scopeapplyfunction scopeprogressvisible false mvcpublic void uploaddocumentshttppostedfilebase filehere is how my request headers look likeacceptacceptencodinggzipdeflatesdchacceptlanguageenusenq08nlq06connectionkeepalivecontentlength380863contenttypemultipartformdata boundarywebkitformboundaryc67wmyyq1t5vamltcookieaspnet sessionidrgwgky0zymvb2ppg3jozrn2s ngdebugfalse aspxautha54883879090e307d871f8293c805b3b50d1ddfad1ce5b05d7284426d895370cbbd75d25b7012d384a69cab265783bda8f05b1ba02e0121814f45b39e15520ec35408f19df3345b5db7f5502886d8696hostlocalhost15982originhttplocalhost15982refererhttplocalhost15982useragentmozilla50 windows nt 62 wow64 applewebkit53736 khtml like gecko chrome290154757 safari53736and here the payloadwebkitformboundaryc67wmyyq1t5vamltcontentthisposition formdata nameuploadedfile filenamedeukjes deur 2jpgcontenttype imagejpegwhat do i have to do to get this working,"['c#', 'javascript']" +535378,why are function template specializations not allowed inside a class after having found answers to many of my questions on stackoverflow i have now come up against a question of which i cannot find the answer and i hope that someone is willing to help memy problem is that i want to do an explicit templatization of a function inside a class in c my compiler g and a look in the c standard a1473 tells me that this specialization has to be done in the namespace in which the class is declared i understand that this implies that i cannot put the specialization inside the class but i do not see the point of this restriction does anyone know if there is a good reason for not letting the specializations be made inside the classi know that there are workarounds eg to put the function inside a struct but i want to understand why the language has this design if there is a good reason for not allowing specialized functions inside the class i guess i should know it before trying to work around itthanks in advanceto make my question a little bit more precise here is some code from a test example which illustrates what i want to doinclude cstdionamespace malintester template size t dimensionalityclass specializationtest public specializationtest privatevariable 5 virtual specializationtest void execute executedimensionality private int privatevariable template size t currentdim static void execute printfthis is the general case current dim is d the private variable is dn currentdim privatevariable executecurrentdim1 template static void execute0 printfthis is the base case current dim is 0n this is not possible g saysspecializationtest fcnh27 error explicit specialization in nonnamespace scope aclass malintesterspecializationtestdimensionalityaspecializationtest fcnh28 error templateid aexecute0a in declaration of primary templateif i put the function execute outside the class in the name space malintester it will look like thisinclude cstdionamespace malintester template size t dimensionality class specializationtest template size t currentdim void execute printfthis is the general case current dim is d the private variable is dn currentdim privatevariable executecurrentdim1 template void execute0 printfthis is the base case current dim is 0n template size t dimensionality class specializationtest public specializationtest virtual specializationtest void execute malintesterexecutedimensionality private int privatevariable 5 and i cannot use privatevariable in the templatized versions of execute as it is private in the class i really want it private as i want to have my data encapsulated as far as possibleof course i can send privatevariable as an argument to the function but i think it would be more beautiful to avoid this and what i really wonder is if there is a good reason for the c standard not to allow explicit specialization as in the first code example abovearne mertz this is the workaround i have tried but it does not allow using privatevariable either and most of all i wonder if it is a good idea to do like this as i am not allowed to make specializations of member functions maybe i should not do specializations of functions encapsulated in structs inside the class eitherinclude cstdionamespace malintester template size t dimensionalityclass specializationtest public specializationtest privatevariable 5 virtual specializationtest void execute loopdimensionality 0execute private int privatevariable template size t currentdim size t dummy struct loop static void execute printfthis is the general case current dim is dn currentdim loopcurrentdim1 0execute template size t dummy struct loop0 dummy static void execute printfthis is the base case current dim is 0n,['c++'] +535411,sql join one to many relationship count number of votes per image okay so i have 2 tablesimages votes image id name square id vote id image id 1 someimg 14 1 45 2 newimg 3 2 18 3 blandimg 76 3 1 n nthis is a one to many relationship each image can have multiple votes but a vote can only be related to one image i am trying to produce a join query which will show the image id and the number of votes it has under a specified condition say based on square id thus the query result would look similar to thisquery resultimage id vote count18 4626 3220 1855 1but the best i can do is thisquery resultimage id vote id18 4618 4518 12726 6626 4355 1see the problem each image id is listed multiple times for each vote id it has this is the query which produces thisselect imagesimage id votesvote id from votes join images on imagesimage idvotesimage idi just cannot seem to create a vote count column which is the sum of all the votes that image has is there some way that i can use the count function to do so that i am simply not aware of,"['mysql', 'sql']" +535439,how to conditionally include code only if above certain ios version i have a piece of code that only works on ios 6 or greatercontroltintcolor uicolor greencoloris there a ready to use compiler directive like ifdef ios6 or greater,"['ios', 'objective-c']" +535442,best bubble chat for ios ui i ve implemented bubbletableview which i found lots of community uses that but when i implemented i realized that nsbubbledata does not take values as array when multiple value exist you need to put data in for loop and it makes 23 minutes to get in messages in nsbubbledata because each for loop it appends nsbubbledata i have to do that because if user opens chat ui first of all he she try to get history from the node serverafter 23 messages send textfield is thisappearing and need to pop that ui and get back again after these issues i found uibubbletableview not useful for complete handle for instant messaging is there any better chatview ui for ios witch is open source also better performance than uibubbletableview best regards,['ios'] +535445,how to import remote library in android studio using gradle i am trying to import androidswipelistview into my android studio module using gradle should not this be possible with buildgradle config alone does anyone have a config files that does the job,['android'] +535459,check if scrollview is higher than screen scrollable how can i check if a scrollview is higher than the screen when the content of a scrollview fits on the screen the scrollview is not scrollable when it is contents exceed the screen height it is scrollable how can i check the condition of a scrollview in that regard,['android'] +535493,app submission icon size error due to forthcoming ios7 release i submitted my app to apple for the first time the app is for ipad only and compiled for ios6i got this reply from the submission process invalid image for ios applications icons included in the binary submission must be in the png formatif your application supports the iphone device family you must include square icons of the following dimensions 57x57 pixels and 120x120 pixels if your application supports the ipad device family you must include square icons of the following dimensions 72x72 pixels 76x76 pixels and 152x152 pixelsi read this morning that this is quite new i always have good chance when for my first attemptsi only used png image files of 72x72 for exemple icon 72pngi understand that when i include a retina file its name becomes icon but what about the other resolutions how should i name them or how can i manage this,"['iphone', 'ios']" +535520,best way to shift an array in c i have an array that holds a history of values and when adding a new value i need to shift all previous values one position to the left to loose the oldest value and make room for the nexti can think of two ways of doing this by using memmovememmovearr0 arr1 sizeofarr sizeofarror by swapping the pointersfor i 0 i sizeofarr 1 i arr i arr i 1is there a performance difference between the two methods and if not which one would be advised,['c'] +535531,how to convert byte array to bytearrayoutputstream i need to convert a byte array to bytearrayoutputstream so that i can thisplay it on screen,['java'] +535548,ruby on rails before filter vs rubys initialize just a thought in my mind what is the difference the followingbefore filterclass applicationcontroller actioncontrollerbase before filter foo def foo mode modelnew endendruby initializeclass applicationcontroller actioncontrollerbase def initialize foo end def foo mode modelnew endenddoes rubys initialize method work as expected in railsif yes then can we use initialize in place a filter has to be applied to all actions in a controller,"['ruby-on-rails', 'ruby']" +535564,android native upnp service thiscovery from android 41 under wifi direct service thiscovery it is suppose to support native upnp service thiscoveryi presume it was developed for wifi direct but the methods available seem to be genericeven the javadoc for methods mention that it searches for all upnp services on the network and not only wifi direct slavesmastershowever i am failing to implement it so that it works i manage to set up all requirements and i get positive onsuccess callbacks but i receive no onupnpserviceavailable callbacks notifying about services on the network i do have 3 services on upnp which i can thiscover using 3rdparty libraryhas anyone tried this feature final channel mchannel final wifip2pmanager mmanager wifip2pservicerequest mrequester mmanager wifip2pmanager getsystemservicecontextwifi p2p service mchannel mmanagerinitializethis getmainlooper new channellistener public void onchannelthisconnected logici channel detected mmanagersetupnpserviceresponselistenermchannel new upnpserviceresponselistener public void onupnpserviceavailableliststring arg0 wifip2pdevice arg1 logisd found device mrequester wifip2pupnpservicerequestnewinstance mmanageraddservicerequestmchannel mrequester new actionlistener public void onsuccess logid addservicerequest success mmanagerthiscoverservicesmchannel new actionlistener public void onsuccess logid thiscoverservices success public void onfailureint reason public void onfailureint reason,"['java', 'android']" +535568,handling 70 clients multithreading tcp hightraffic i am going to create a network system that can handle 70 tcp socket client with 5kbs input clients sends i have looked into this question link they said create 1024 thread to handle 1024 clients i know there is a method named select and i think i cannot open 70 threads to handle 70 clients because my processor or server have got only 8cpu and that means 70 threads are a big mistake now i think i will create 10 thread and i will handle every 7 socket group in this threads but now here is the question if i have same application but i have 2cpu processor i cannot get maximum performance with 10 threads i should create maybe 500 threads otherwise if i have 8cpu processor i cannot get max performance with 10 threads and i need to create maybe 20 threads to handle sockets how can i understand this processor can handle x threads and is this way trueedit i think i can create a profiller that is watching program namely every thread logging i have finished my job in x seconds and profiller handling this messages and decides to create a thread or killing a thread but how to understand threads or cpu status,['c++'] +535577,gridlayout column width i have 2 columns in my gridlayout what i want to do is make those columns take up half of the width of the screen each and then have its child contents fill their own cells widthheight i tried setting the children to fill parent but that just causes the first one to take over the entire layout and it seems gridlayout does not support weight maybe there is a better layout to use but i want a grid style layout so that seems like the natural choice,['android'] +535597,c read windows mobile broadband connection properties first up heres the backgroundwe have a windows forms application written in c net framework 35 currently running on full windows 7 tablets which have a 3g module built in that is used for data connectivity the data connection is configured as a normal mobile broadband connection in windows so windows manages the connectivity itself and the connection shows up in control panel network and internet network connections and it works fine the application is able to communicate over the internet with our web service we will be moving onto a different device likely a full windows 8based tablet at some point in the futurenow what i need to do is read the connection status of this mobile broadband connection ie get the signal strength and the carrier name eg vodafone uk i have found a way to do this using the mobile broadband api part of the windows 7 sdk see here and here however this appears to be os specific as it does not work on windows 8 or at least not with the device i have hereis there a generic way to read the mobile broadband connection properties using the net frameworkalternatively does anyone know of a windows 8 sdk which contains a mobile broadband api like the windows 7 one i am currently usingthanks in advanceupdate i have got this working on a range of different win 7 win 8 devices now even the lenovo device is working ok i will post up example code for the main bits reading connection status configuring the connection checking the sim status as answers the code is a little too long to go into the question annoyingly,"['c#', '.net']" +535657,how to send data from dialogfragment to a fragment i have a fragment that opens a dialogfragment to get user input a string and an integer how do i send these two things back to the fragmenthere is my dialogfragmentpublic class datepickerfragment extends dialogfragment string month int year override public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate getdialogsettitlegetstringrstringdate picker view v inflaterinflaterlayoutdate picker dialog container false spinner months spinner vfindviewbyidridmonths spinner arrayadaptercharsequence monthadapter arrayadaptercreatefromresourcegetactivity rarraymonths rlayoutpicker row monthssetadaptermonthadapter monthssetonitemselectedlistenernew onitemselectedlistener override public void onitemselectedadapterview parentview view selecteditemview int monthplace long id month integertostringmonthplace public void onnothingselectedadapterview parent spinner years spinner vfindviewbyidridyears spinner arrayadaptercharsequence yearadapter arrayadaptercreatefromresourcegetactivity rarrayyears rlayoutpicker row yearssetadapteryearadapter yearssetonitemselectedlistenernew onitemselectedlistener override public void onitemselectedadapterview parentview view selecteditemview int yearplace long id if yearplace 0 year 2012 if yearplace 1 year 2013 if yearplace 2 year 2014 public void onnothingselectedadapterview parent button button button vfindviewbyidridbutton buttonsetonclicklistenernew viewonclicklistener public void onclickview v getdialogthismiss return v i need to send the data after the button click and before getdialogthismisshere is the fragment that data needs to be sent topublic class calendarfragment extends fragment int yearstring monthoverridepublic view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate superoncreatesavedinstancestate int position getargumentsgetintposition string categories getresourcesgetstringarrayrarraycategories getactivitygetactionbarsettitlecategoriesposition view v inflaterinflaterlayoutcalendar fragment layout container false final calendar c calendargetinstance simpledateformat month date new simpledateformatm month month dateformatcgettime year cgetcalendaryear button button button vfindviewbyidridbutton buttonsettextmonth year buttonsetonclicklistenernew viewonclicklistener public void onclickview v new datepickerfragmentshowgetfragmentmanager myprogressdialog return v so once the user selects a date in the dialogfragment it must return the month and year then the text on the button should change to the month and year specified by user,"['java', 'android']" +535699,how i can make an intro logotype animation like skype app i want to question if someone knows how i can make an intro logotype animation like as the skype app i try to do an animation with an xml with looped images but it is shown really weird someone can tell me an advicethank you for all pd i mean to make an animation like the one shown in the video from the second 6 of the next videovideo of skype for android,['android'] +535707,google analytics sdk 30 for ios anonymize ips since the ios sdk 30 of google analytics has been released plenty of changes have been made with the api there is one big problem we encounter that has to do with the anonymize ip featurein germany one has to anonymize the ips by law when using some tracking framework with the previous version of the sdk 20 it worked like thistrackeranonymize yeswhere tracker is an instance of idgaitrackernow with the version 30 one has to use the set method of the trackertracker setkgaianonymizeip valuethe signature of the method is voidsetnsstring parametername valuensstring valueand that is the problem what should the parameter value be yes or no on or off 1 or 0 are these parameters casesensitivethere is no information about the value in the documentary does anyone know what parameter is correct to anonymize the ips,['ios'] +535708,controller function getting called twice using ngshow i have a very simple angular app setup code as followsindexhtmldoctype htmlhtml head script srcscript script srcappjsscript head body ngappapp div ngcontrollermyctrl div ngshowready some content div div bodyhtmland appjsvar app angularmoduleapp appcontrollermyctrl functionscope consolelogmyctrl called scopeready function consolelogready called return true if you run this with your console open you will see myctrl called once and ready called twice i have spent hours trying to figure this out i see no reason why scopeready would be called anything but exactly one timeif you use a angular v115 and use ngif instead of ngshow you will have the same behaviour but if you use nginit it correctly calls scopeready one time in my case i will need ngshow or ngifplunkr clarificationto elaborate on what i am aiming for let us say scopeready at some point later returns false maybe it makes an ajax call that should not be called more than once i would like some content to no longer be visible that is dynamic behaviour based on the result of scopereadyany ideas thank you for the helpfor the record this and this are not the same problem,['javascript'] +535721,using wiremock can i return a body that is dependant on the post request i am trying to test an openid provider class the openid consumer class is making an http request i am mocking the response to this request using wiremock i am trying to mock a valid openid response however the valid response depends on the request parameters using wiremock can i set up a mock request where the body of the response is dependant on the request parameters,['java'] +535722,any way faster than pow to compute an integer power of 10 in c i know power of 2 can be implemented using operator what about power of 10 like 105 is there any way faster than pow105 in c it is a pretty straightforward computation by hand but seems not easy for computers due to binary representation of the numbers let us assume i am only interested in integer powers 10n where and is an integer,['c++'] +535737,set admob banner to match parent width by xml i am trying to set admob banner ad to match it is parent widthi tried as samplecomgoogleadsadview androidididad androidlayout widthmatch parent androidlayout height50dp androidgravitycenter adsadsizebanner adsadunitidapubid adsloadadoncreatetrueand goti also tried withadsadsizesmart bannerin the ide xml preview i gotbut in fact the ad did not match his parent widthanyone,['android'] +535747,android grow linearlayout using animation i am trying to use animation to make a layout appear on screen the idea is that layout will start with height of 0 and grow to 100 i have real troubles with this and need some assistance for some reason no animation is performedhere is my animation xml filexml version10 encodingutf8set xmlnsandroid scale androidinterpolatorandroidanimaccelerate decelerate interpolator androidfromxscale00 androidtoxscale1 androidfromyscale10 androidtoyscale10 androidfillafterfalse setthe layout file is very basic and is designed as followingxml version10 encodingutf8relativelayout androidlayout widthfill parent androidlayout heightfill parent xmlnsandroidlinearlayout androidididdialog androidlayout widthwrap content androidlayout height200dp androidlayout centerhorizontaltrue androidorientationvertical androidlayout centerverticaltrue androidbackgrounddrawableborder textview androidlayout widthwrap content androidlayout heightwrap content androidlayout gravitycenter horizontal androidtextphone androidididtextview textview androidlayout widthwrap content androidlayout heightwrap content androidlayout gravitycenter horizontal androidtextaddress androidididtextview1 button androidididbtn1 androidlayout width200dp androidlayout heightwrap content androidtextaction 1 button androidididbtn2 androidlayout width200dp androidlayout heightwrap content androidtextaction 2 linearlayoutbutton androidlayout widthwrap content androidlayout heightwrap content androidtextanimate androidididbtnanimate androidlayout alignparentlefttrue androidlayout alignparenttoptrue androidonclickanimaterelativelayoutmy activity code is very basic as wellpublic class myactivity extends activity implements animationanimationlisteneroverridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain public void animateview view linearlayout dialog linearlayoutfindviewbyidriddialog dialogsetvisibilitylinearlayoutvisible animation animation animationutilsloadanimationthis ranimanim logianimatebegin animation animationreset animationsetfillaftertrue animationsetanimationlistenerthis dialogsetanimationnull logianimateend animationoverridepublic void onanimationstartanimation animation to change body of implemented methods use file settings file templatesoverridepublic void onanimationendanimation animation to change body of implemented methods use file settings file templatesoverridepublic void onanimationrepeatanimation animation to change body of implemented methods use file settings file templatesthank you,['android'] +535750,what order do before filters occur in what order do before filters occur in specifically what order do the before action filters occur in in regards to inheiritance for example will this workclass a actioncontrollerbase before action set user def set user user something endendclass b a before action set post def show render post end def set post post userpostsfirst endendwill bshow work what are the rules for filter order for future reference i cannot find any of this in the rails documentation,"['ruby-on-rails', 'ruby']" +535766,usage of interceptor within resource how do i use an interceptor within an angular resourcemy json structurevar dgs id 1 driversam type bus segmentsid1originthe backeryarrivalthe store id2originthe store arrivalsomewhere my controller is the followingfunction dgctrlscopehttpdrivegroupsegment scopedgs drivegroupqueryfunction code below may belong in a response interceptor for var i0iscopedgslengthi var segments scopedgsisegments for var j0jsegmentslengthj segmentsj new segmentsegmentsj my services and what i tried using the interceptor objectangularmoduledgservicengresource factorydrivegroupfunctionresource return resource pathdgs updatemethodput fetch methodget this is what i tried interceptor responsefunctiondata consolelogresponsedata responseerrorfunctiondata consolelogerrordata isarraytrue i read resource and it seems like this should work but it does not so i am misunderstanding any suggestions,['javascript'] +535841,java ee sdk 6 is not being installed on windows 7 i am successfully running 64 bit jdk but i now need to install the java ee sdk 6 on the windows 7 machine i have downloaded java ee sdk6u4windowsexe from oracle website but when i try to install it i get the error which is attached in the attached screenshoti have double checked my java home and classpath they are perfectany idea how to get it fixed,['java'] +535909,uicollectionview load more data i want to fetch more data from server if the last cell will thisplay but uicollectionview do not have method willthisplaycell like uitableview so i have no idea about this situation can somebody tell me what should i do thanks,['ios'] +535911,what is datacipid in aspnet mvc and how do i remove it been trying to find information about this with no luckwhen using a html helper in aspnet mvc to generate a textbox as suchhtmltextboxtesti always get input idtest nametest typetext value datacipidtestwhat is this ugly datacipid what function does it have and how do i remove it,['c#'] +535933,how to get values of a specific key from an array of custom model objects i have an array of custom objects which contains a custom object address with properties street area state country i need to get all the the names of the areas from that array so i did some thing like thisnsmutablearray areas nsmutablearray allocinit for address item in addresses areas addobjectitemarea now areas contain all the names of the area is there any other way to get the all the areas of address items with out looping through the array of addresses as above using predicates or some other way,"['iphone', 'ios', 'objective-c']" +536002,ios sdk how to screen shot content of tableview how to screenshot all content of tableview all content visible are not visible areai tried thisuigraphicsbeginimagecontextselftableviewboundssizeselftableviewlayer renderincontextuigraphicsgetcurrentcontextuiimage image1 uigraphicsgetimagefromcurrentimagecontextuigraphicsendimagecontextselfimageviewimage image1but it does not work i mean it is screenshot only visible area i solved it here is the code uiimage captureviewuiscrollview view incontentrectcgrectrect uiimage image nil cgpoint savedcontentoffset viewcontentoffset cgrect savedframe viewframe uigraphicsbeginimagecontextwithoptionsviewcontentsize 1 0 viewcontentoffset cgpointzero viewframe cgrectmake0 0 viewcontentsizewidth viewcontentsizeheight viewlayer renderincontext uigraphicsgetcurrentcontext image uigraphicsgetimagefromcurrentimagecontext viewcontentoffset savedcontentoffset viewframe savedframe uigraphicsendimagecontext after all of this crop image to needed size return utils cropimageimage torectrect,"['ios', 'objective-c']" +536060,when should i use dependency properties in wpf when should i use dependency properties in wpfthey are static so we save a lot on memory compared to using net propertiesother gains of using dependency properties over net properties are1 no need to check thread access2 prompt a containing element to be renderedetcso it seems i should always use dependency properties in my projects where i use wpfmaybe for some trivial properties of helper classes here and there i couldget away with net properties,['c#'] +536082,store login session cookie in browser using ruby mechanize i am trying to login to a website and redirect to a secured page from a rails action my code looks something like this def redirect to external agent mechanizenew page agentget login form pageform withname loginform login formlogin username login formpassword password agentsubmitlogin form cookies agentcookie jarstoremap i i need to store the cookie with a specific in browser redirect to page behind password protection endlogin is successful in the background but actual redirection to the admin page is asking again for authentication in the browser as the session cookie is not stored in the browser tried storing the cookies from cookie jar but could not find the exact way to do that can someone help me in this,"['ruby-on-rails', 'ruby']" +536099,jpa criteria api left join for optional relationships i am using the criteria api basically the first time it is about abstracting queries for a generic builderpublic typedqueryt newquery managert manager criteriabuilder builder thisentitymanagergetcriteriabuilder classt genericclass classt parameterizedtype managergetclassgetgenericsuperclass getactualtypearguments1 criteriaqueryt criteriaquery buildercreatequery genericclass roott root criteriaqueryfrom genericclass the call criteriaqueryfrom genericclass generates sql inner join for all relationships found on the entity by default this is a problem because every relationship being null db null or a db that does not use foreign keys and has an invalid reference those entities will be missing in the result list effectively producing wrong search resultsan example can be found here jpa criteria query pathget left join is it possibilewhat i would like to happen for queries instantiated by this classmethod is that all relationships on the entity here genericclass that are mapped as optional truemanytoone fetchtypeeager optional true joincolumn name close user id referencedcolumnname user id private user closerto generate an sql left outer join instead of inner joinquestionis there standard jpq way to get this done if so howps there is generally no way to know the concrete type beforehand so the only way i might be able to achieve what i need is to use the metamodel of some sort and generate the joins manually which i would like to avoidwe are using eclipselink 23,"['java', 'sql']" +536147,google maps converting address to latitude longitude php backend is it possible to convert in php backendphp address street 1 city country just normal addressto php latlng 100200 latitude lonitudethe code i am currently using is the default onescript typetextjavascript src038sensorfalsescriptscriptfunction initialize var mylatlng new googlemapslatlng100200 var mapoptions zoom 16 center mylatlng maptypeid googlemapsmaptypeidroadmap var map new googlemapsmapdocumentgetelementbyidmap mapoptions var marker new googlemapsmarker position mylatlng map map title this is a caption googlemapseventadomlistenerwindow load initialize scriptdiv idmapdivi have been reading for a while now but i am not experienced enough i guessthanks,['php'] +536165,importerror no module named mpl toolkits with maptlotlib 130 and py2exe i cannot figure out how to be able to package this via py2exe nowi am running the commandpython setup2py py2exevia python 275 and matplotlib 130 and py2exe 069 and 0610devthis worked with matplotlib 12xi have read and tried to implement the suggestions for handling the mpl toolkits since it is having become a namespace packagei am trying to get an answer here too adding an empty init py to mpl toolkits makes it work but this is only a workaround to the problemcan anyone suggest what i need to make py2exe work with mpl toolkitsaxes grid1 in matplotlib 130 test mplpy isfrom mpl toolkitsaxes grid1 import make axes locatable axes sizeif name main print make axes locatable axes sizesetup2py isimport py2exeimport thistutilssysconfigfrom thistutilscore import setup attempts to get it to workimport modulefinderimport matplotlibimport mpl toolkitsaxes grid1 import pkg resourcesdeclare namespacempl toolkits import pkg resourcesdeclare namespacempl toolkitsaxes grid1modulefinderaddpackagepathmpl toolkits matplotlib path 0modulefinderaddpackagepathmpl toolkitsaxes grid1 mpl toolkitsaxes grid1 path 0 end of attempts to get it to workoptionspy2exe packages matplotlib mpl toolkitsaxes grid1 pylab zmq includes zmq six excludes gdk gtk gtkagg tkagg pyqt4uicport v3 tkconstants tkinter tcl dll excludes libgdkwin32200dll libgdk pixbuf200dll libgobject200dll tcl85dll tk85dll skip archive true setupconsoletest mplpy optionsoptionsoutput isrunning py2exe searching for required modules traceback most recent call last file setup2py line 23 in module setupconsoletest mplpy optionsoptions file cpython27libthistutilscorepy line 152 in setup thistrun commands file cpython27libthistutilsthistpy line 953 in run commands selfrun commandcmd file cpython27libthistutilsthistpy line 972 in run command cmd objrun file cpython27libsitepackagespy2exebuild exepy line 243 in run self run file cpython27libsitepackagespy2exebuild exepy line 296 in run selffind needed modulesmf required files required modules file cpython27libsitepackagespy2exebuild exepy line 1308 in find needed modules mfimport hookf file cpython27libsitepackagespy2exemfpy line 719 in import hook return baseimport hookselfnamecallerfromlistlevel file cpython27libsitepackagespy2exemfpy line 136 in import hook q tail selffind head packageparent name file cpython27libsitepackagespy2exemfpy line 204 in find head package raise importerror no module named qnameimporterror no module named mpl toolkits,['python'] +536167,file upload field causing actioncontrollerinvalidauthenticitytoken exception using rails 4 and trying to add a file field to an existing form using simple form and paperclipheres the critical part of the form simple form foremployee html class formhorizontal requires multipart true remote true do f finput avatar end everything works ok unless i actually submit the form with an uploaded file then i get thisactioncontrollerinvalidauthenticitytoken in employeescontrollerupdatewhat am i doing wrong here,['ruby-on-rails'] +536202,monitoring a synchronous method for timeout i am looking for an efficient way to throw a timeout exception if a synchronous method takes too long to execute i have seen some samples but nothing that quite does what i wantwhat i need to do is check that the sync method does exceed its slaif it does throw a timeout exceptioni do not have to terminate the sync method if it executes for too long multiple failures will trip a circuit breaker and prevent cascading failuremy solution so far is show below note that i do pass a cancellationtoken to the sync method in the hope that it will honor a cancellation request on timeout also my solution returns a task that can then be awaited on etc as desired by my calling codemy concern is that this code creates two tasks per method being monitoring i think the tpl will manage this well but i would like to confirmdoes this make sense is there a better way to do thisprivate task timeoutsyncmethod actioncancellationtoken syncaction timespan timeout var cts new cancellationtokensource var outer taskrun try start the synchronous method passing it a cancellation token var inner taskrun syncaction ctstoken ctstoken if innerwait timeout try give the sync method a chance to abort grecefully ctscancel there was a timeout regardless of what the sync method does so throw throw new timeoutexception timeout waiting for method after timeout finally ctsthispose ctstoken return outereditusing timothys answer i am now using this while not significantly less code it is a lot clearer thanks private task timeoutsyncmethod actioncancellationtoken syncaction timespan timeout var cts new cancellationtokensource var inner taskrun syncaction ctstoken ctstoken var delay taskdelay timeout ctstoken var timeouttask taskwhenany inner delay continuewith t try if inneriscompleted ctscancel throw new timeoutexception timeout waiting for method after timeout finally ctsthispose ctstoken return timeouttask,['c#'] +536246,mvc 4 client side validation not working for the form which is loaded using ajax i have an admin page in which the user clicks on links and the corresponding partialview containing a web form is then loaded inside a particular div on the admin page using ajaxall of thescriptsjquery203jsscriptsjqueryunobtrusiveajaxjsscriptsjqueryvalidatejsscriptsjqueryvalidateunobtrusivejsare referenced within the admin page and when the partialview is loaded the jquery client side validation would not workbut when i reference those scripts within the partialview everything works just fine but i do not intend to do this for each partialview because they are numerous and each time each one loads at least two of those js files must be requested from the server again is there any way i can have those scripts inside my parent admin page without this issue,['jquery'] +536248,emacs org mode executing simple python code how can i execute very simple pythoncode in emacs org modethe first example works fine however i cannot make it give me the result of simplest computations worksbegin src pythondef foox if x0 return x10 else return x1return foo50end srcresults 60 does not workbegin src python11end srcresults none does not workbegin src pythonprint11end srcresults nonei set up org mode using the following lines enable python for inbuffer evaluationorgbabeldoloadlanguages orgbabelloadlanguages python t all python code be safedefun myorgconfirmbabelevaluate lang bodynot string lang pythonsetq orgconfirmbabelevaluate myorgconfirmbabelevaluate,['python'] +536261,safari css width transition not working with different unit measurements i am having an issue with webkittransition in safari these transitions work fine in chrome ff and ie10 using the nonprefixed transition propertyin my site there are 3 panels that can be viewed the main one opens by default and the other 2 are collapsed on the right of the window showing a sliver of their content when a collapsed panel is clicked an additional class is added to it via js and it transitions to 100 widthcsspanel1 width 100panel2 width 8rem position absolute top 0 right 0 overflow hidden zindex 500 transition all 05s webkittransition all 05spanel2hover width 10rempanel2panelopen width 100panel3 width 4rem position absolute top 0 right 0 overflow hidden zindex 501 transition all 05s webkittransition all 05spanel3hover width 6rempanel3panelopen width 100the problem seems to be with the difference of measurement units the hover transitions work as intended rem to rem however the width transition rem to on panelopen skips the transition and just snaps open if i switch the default width to a percentage instead of rem the transition works again i cannot do this however as it is a fluid site and the panel collapsed widths need to be static and not relativei have attempted to add a minwidth in but that has not helped any advice on this would be greatly appreciated,['css'] +536280,errors in sql server while importing csv file despite varcharmax being used for each column i am trying to insert a large csv file several gigs into sql server but once i go through the import wizard and finally try to import the file i get the following error reportexecuting errormessageserror 0xc02020a1 data flow task 1 data conversion failed the data conversion for column title returned status value 4 and status text text was truncated or one or more characters had no match in the target code pagesql server import and export wizarderror 0xc020902a data flow task 1 the source train csvoutputsflat file source outputcolumnstitle failed because truncation occurred and the truncation row thisposition on source train csvoutputsflat file source outputcolumnstitle specifies failure on truncation a truncation error occurred on the specified object of the specified componentsql server import and export wizarderror 0xc0202092 data flow task 1 an error occurred while processing file ctraincsv on data row 2sql server import and export wizarderror 0xc0047038 data flow task 1 ssis error code dts e primeoutputfailed the primeoutput method on source train csv returned error code 0xc0202092 the component returned a failure code when the pipeline engine called primeoutput the meaning of the failure code is defined by the component but the error is fatal and the pipeline stopped executing there may be error messages posted before this with more information about the failuresql server import and export wizardi created the table to insert the file into first and i set each column to hold varcharmax so i do not understand how i can still have this truncation issue what am i doing wrong,['sql'] +536286,jquery datatables load large data how to load large data on databases into jquery datatables documentreadyfunction datatablesdatatable spaginationtypefull numbers aasorting 0 asc 1 desc sscrolly 200px bjqueryuitrue total data on xnod kode table 10 records php result mysql queryselect from xnod kode limit 10 no 1 while row mysql fetch arrayresult tr tdphp echo no td tdphp echo rowkodepostd tdphp echo rowkelurahantd tdphp echo rowkecamatantd tr php no,"['php', 'jquery']" +536297,angularjs ngrepeat with custom element inside a table is rendering strangely i am trying to reuse a portion of my html view in multiple places the portion i want to reuse is table cells in an html table the problem is that my custom directive inside a ngrepeat is doing funny things i have reproduced the problem on jsfiddle there are two html tables in the jsfiddle the first is ngrepeat with the table cells written in the view and the second is the table cells coming from a directive myelement chrome dev tools report that the rendered html looks like this note that the custom element appears only once and is outside the tablerendered htmldiv ngcontrollermyctrl classngscope table1 table classtable tablehover tbody ngrepeat p in people tr ngrepeatp in people classngscope td classngbindingname miketd td classngbindingage 20td tr tr ngrepeatp in people classngscope td classngbindingname peter std td classngbindingage 22td tr tbody table brtable2 myelement classngbindingname age myelement table classtable tablehover tbody ngrepeat p in people tr ngrepeatp in people classngscope tr tr ngrepeatp in people classngscope tr tbody tabledivsource htmldiv ngcontrollermyctrl table1 table classtable tablehover tr ngrepeatp in people tdname pname td tdage page td tr table brtable2 table classtable tablehover tr ngrepeatp in people myelementmyelement tr tabledivsource jsvar app angularmodulemyapp appdirectivemyelement function return restrict e template tdname pname tdtdage page td function myctrlscope scopepeople name mike age 20 name peter s age 22 please note the jsfiddle is a trivial example and common sense would lead to just not using directives at all however my target code has a much larger template that i want to reuse i have tried using nginclude as well but the result is similar,"['javascript', 'html']" +536355,samsung galaxyholoeverywhere resource is not a colorstatelist color or path i am getting the following crash on the samsung galaxy aceypocketmini it runs fine on all other devices crashes are only occurring on android 235 or 236there is no ref to my code in the stacktrace it seem to come from the menu layout which i have not customisedi suspect that it is a fault in the galaxy os but cannot confirmmore importantly what can i can do avoid or mitigate this errorandroidviewinflateexception binary xml file line 45 error inflating class at orgholoeverywherelayoutinflater createviewsourcefile382at orgholoeverywherelayoutinflateroncreateviewsourcefile594at orgholoeverywherelayoutinflatercreateviewfromtagsourcefile4at orgholoeverywherelayoutinflaterrinflatesourcefile731at orgholoeverywherelayoutinflaterrinflatesourcefile734at orgholoeverywherelayoutinflaterinflatesourcefile538at orgholoeverywherelayoutinflaterinflatesourcefile488at comandroidinternalviewmenumenuitemimplcreateitemviewmenuitemimpljava592at comandroidinternalviewmenumenuitemimplgetitemviewmenuitemimpljava577at comandroidinternalviewmenumenubuildermenuadaptergetviewmenubuilderjava1173at androidwidgetabslistviewobtainviewabslistviewjava1592at androidwidgetlistviewmeasureheightofchildrenlistviewjava1251at androidwidgetlistviewonmeasurelistviewjava1162at androidviewviewmeasureviewjava8313at androidviewviewgroupmeasurechildwithmarginsviewgroupjava3138at androidwidgetframelayoutonmeasureframelayoutjava250at androidviewviewmeasureviewjava8313at androidviewviewrootperformtraversalsviewrootjava845at androidviewviewroothandlemessageviewrootjava1865at androidoshandlerthispatchmessagehandlerjava99at androidoslooperlooplooperjava130at androidappactivitythreadmainactivitythreadjava3687at javalangreflectmethodinvokenativenative methodat javalangreflectmethodinvokemethodjava507at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava867at comandroidinternaloszygoteinitmainzygoteinitjava625at dalviksystemnativestartmainnative method caused by javalangreflectinvocationtargetexceptionat javalangreflectconstructorconstructnativenative methodat javalangreflectconstructornewinstanceconstructorjava415at orgholoeverywherelayoutinflater createviewsourcefile358 26 more caused by androidcontentresresourcesnotfoundexception resource is not a colorstatelist color or path typedvaluet0x1d0x7f0d014c a3 r0x7f0d014cat androidcontentresresourcesloadcolorstatelistresourcesjava1804at androidcontentrestypedarraygetcolorstatelisttypedarrayjava342at androidwidgettextviewtextviewjava445at orgholoeverywherewidgettextviewsourcefile133at orgholoeverywherewidgettextviewsourcefile129 29 more javalangreflectinvocationtargetexceptionat javalangreflectconstructorconstructnativenative methodat javalangreflectconstructornewinstanceconstructorjava415at orgholoeverywherelayoutinflater createviewsourcefile358at orgholoeverywherelayoutinflateroncreateviewsourcefile594at orgholoeverywherelayoutinflatercreateviewfromtagsourcefile4at orgholoeverywherelayoutinflaterrinflatesourcefile731at orgholoeverywherelayoutinflaterrinflatesourcefile734at orgholoeverywherelayoutinflaterinflatesourcefile538at orgholoeverywherelayoutinflaterinflatesourcefile488at comandroidinternalviewmenumenuitemimplcreateitemviewmenuitemimpljava592at comandroidinternalviewmenumenuitemimplgetitemviewmenuitemimpljava577at comandroidinternalviewmenumenubuildermenuadaptergetviewmenubuilderjava1173at androidwidgetabslistviewobtainviewabslistviewjava1592at androidwidgetlistviewmeasureheightofchildrenlistviewjava1251at androidwidgetlistviewonmeasurelistviewjava1162at androidviewviewmeasureviewjava8313at androidviewviewgroupmeasurechildwithmarginsviewgroupjava3138at androidwidgetframelayoutonmeasureframelayoutjava250at androidviewviewmeasureviewjava8313at androidviewviewrootperformtraversalsviewrootjava845at androidviewviewroothandlemessageviewrootjava1865at androidoshandlerthispatchmessagehandlerjava99at androidoslooperlooplooperjava130at androidappactivitythreadmainactivitythreadjava3687at javalangreflectmethodinvokenativenative methodat javalangreflectmethodinvokemethodjava507at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava867at comandroidinternaloszygoteinitmainzygoteinitjava625at dalviksystemnativestartmainnative method caused by androidcontentresresourcesnotfoundexception resource is not a colorstatelist color or path typedvaluet0x1d0x7f0d014c a3 r0x7f0d014cat androidcontentresresourcesloadcolorstatelistresourcesjava1804at androidcontentrestypedarraygetcolorstatelisttypedarrayjava342at androidwidgettextviewtextviewjava445at orgholoeverywherewidgettextviewsourcefile133at orgholoeverywherewidgettextviewsourcefile129 29 more androidcontentresresourcesnotfoundexception resource is not a colorstatelist color or path typedvaluet0x1d0x7f0d014c a3 r0x7f0d014cat androidcontentresresourcesloadcolorstatelistresourcesjava1804at androidcontentrestypedarraygetcolorstatelisttypedarrayjava342at androidwidgettextviewtextviewjava445at orgholoeverywherewidgettextviewsourcefile133at orgholoeverywherewidgettextviewsourcefile129at javalangreflectconstructorconstructnativenative methodat javalangreflectconstructornewinstanceconstructorjava415at orgholoeverywherelayoutinflater createviewsourcefile358at orgholoeverywherelayoutinflateroncreateviewsourcefile594at orgholoeverywherelayoutinflatercreateviewfromtagsourcefile4at orgholoeverywherelayoutinflaterrinflatesourcefile731at orgholoeverywherelayoutinflaterrinflatesourcefile734at orgholoeverywherelayoutinflaterinflatesourcefile538at orgholoeverywherelayoutinflaterinflatesourcefile488at comandroidinternalviewmenumenuitemimplcreateitemviewmenuitemimpljava592at comandroidinternalviewmenumenuitemimplgetitemviewmenuitemimpljava577at comandroidinternalviewmenumenubuildermenuadaptergetviewmenubuilderjava1173at androidwidgetabslistviewobtainviewabslistviewjava1592at androidwidgetlistviewmeasureheightofchildrenlistviewjava1251at androidwidgetlistviewonmeasurelistviewjava1162at androidviewviewmeasureviewjava8313at androidviewviewgroupmeasurechildwithmarginsviewgroupjava3138at androidwidgetframelayoutonmeasureframelayoutjava250at androidviewviewmeasureviewjava8313at androidviewviewrootperformtraversalsviewrootjava845at androidviewviewroothandlemessageviewrootjava1865at androidoshandlerthispatchmessagehandlerjava99at androidoslooperlooplooperjava130at androidappactivitythreadmainactivitythreadjava3687at javalangreflectmethodinvokenativenative methodat javalangreflectmethodinvokemethodjava507at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava867at comandroidinternaloszygoteinitmainzygoteinitjava625at dalviksystemnativestartmainnative methodhere is the entire themexmlxml version10 encodingutf8resources style namecustomwindowtitletext parenttextappearancesherlockwidgetactionbartitle item nameandroidtextcolorcolorprimary text yellowitem item nameandroidtextstylebolditalicitem style style namecustomwindowtitletextactionbar item nameandroidtextsizedimentextsize miditem style style namecustomwindowsubtitletext parenttextappearancesherlockwidgetactionbarsubtitle style changes the background color of the title bar style namecustomwindowtitlebackground item nameandroidbackgrounddrawablebackground window titleitem style set the theme for the window title note setting androidtextappearance to style defined above style namecustomwindowtitle item nameandroidsinglelinetrueitem item nameandroidshadowcolorbb0item item nameandroidshadowradius275item item nameandroidtextappearancestylecustomwindowtitletextitem item nameandroidpaddingleft40dpitem style due to limitations in androids theming system any theme customizations must be declared in two attributes the normal androidprefixed attributes apply the theme to the native action bar and the unprefixed attributes are for the custom implementation style namecustomactionbar parentwidgetsherlocklightactionbarsolidinverse parentandroidstylewidgetholoactionbar item nameandroidbackgrounddrawablegradient lightpurple darkpurple offitem use background that has color but not icon item nameandroidbackgroundsplitdrawablegradient lightpurple darkpurple offitem use background that has color but not icon item nameandroidtitletextstylestylecustomwindowtitletextactionbaritem item nameandroidsubtitletextstylestylecustomwindowsubtitletextitem item namebackgrounddrawablegradient lightpurple darkpurple offitem use background that has color but not icon item namebackgroundsplitdrawablegradient lightpurple darkpurple offitem use background that has color but not icon item nametitletextstylestylecustomwindowtitletextactionbaritem item namesubtitletextstylestylecustomwindowsubtitletextitem style override properties in the default theme note if you change the windowtitletextsize you must explicitly the windowtitlesize property the title bar will not resize automatically text will be clipped style namejumbleetheme parentholotheme extends themesherlock item nameandroidwindowtitlestylestylecustomwindowtitleitem item nameandroidwindowtitlebackgroundstylestylecustomwindowtitlebackgrounditem item nameandroidwindowbackgrounddrawablegradient off darkpurple offitem item nameandroidwindowactionbartrueitem item nameandroidactionbarstylestylecustomactionbaritem item nameactionbarstylestylecustomactionbaritem style style namejumbleethemegamescreen item nameandroidwindowbackgroundcolorblackitem style facebook theme style namecustomwindowtitletextactionbarfacebook item nameandroidtextcolorcolorprimary text whiteitem style due to limitations in androids theming system any theme customizations must be declared in two attributes the normal androidprefixed attributes apply the theme to the native action bar and the unprefixed attributes are for the custom implementation style namecustomactionbarfacebook item nameandroidbackgrounddrawablebackground window title facebookitem use background that has color but not icon item nameandroidbackgroundsplitdrawablebackground window title facebookitem use background that has color but not icon item nameandroidtitletextstylestylecustomwindowtitletextactionbarfacebookitem item namebackgrounddrawablebackground window title facebookitem use background that has color but not icon item namebackgroundsplitdrawablebackground window title facebookitem use background that has color but not icon item nametitletextstylestylecustomwindowtitletextactionbarfacebookitem style facebook sender activity style namefacebooksendertheme parentholothemelight item nameandroidactionbarstylestylecustomactionbarfacebookitem item nameactionbarstylestylecustomactionbarfacebookitem styleresourcesand the source for primary text yellowxml version10 encodingutf8selector xmlnsandroid item androidstate enabledfalse androidcolorcolortext light thisabled item androidcolorcolorapp yellowselector,['android'] +536368,php shorthand for isset is there a shorthand way to assign a variable to something if it does not exist in phpifissetvar var i would like to do something likevar var,['php'] +536369,progress indicator during pandas operations python i regularly perform pandas operations on data frames in excess of 15 million or so rows and i would love to have access to a progress indicator for particular operationsdoes a text based progress indicator for pandas splitapplycombine operations existfor example in something likedf usersgroupbyuserid requestdateapplyfeature rollupwhere feature rollup is a somewhat involved function that take many df columns and creates new user columns through various methods these operations can take a while for large data frames so i would like to know if it is possible to have text based output in an ipython notebook that updates me on the progreso far i have tried canonical loop progress indicators for python but they do not interact with pandas in any meaningful wayi am hoping there is something i have overlooked in the pandas librarydocumentation that allows one to know the progress of a splitapplycombine a simple implementation would maybe look at the total number of data frame subsets upon which the apply function is working and report progress as the completed fraction of those subsetsis this perhaps something that needs to be added to the library,['python'] +536373,can i group multiple domains in a routing group in laravel let us say i have the followingroutegrouparraydomain arrayadminexamplecom function routegrouparraydomain arrayappexamplecom function routegrouparraydomain arraydevappexamplecom function is there any way to have multiple domains share a routing group something likeroutegrouparraydomain arraydevappexamplecomappexamplecom function,['php'] +536430,android canvas save always javaioioexception open failed enoent no such file or directory i have a canvas application i am trying to create a signature app with canvas ontouchlistenerthis is my save method where i try to save the signature to an imageprivate void save hidemenubar view content this contentsetdrawingcacheenabledtrue contentsetdrawingcachequalityviewdrawing cache quality high bitmap bitmap contentgetdrawingcache string path environmentgetexternalstoragedirectorygetabsolutepath string imgpath pathimotaxcapturespopttdimage temp jpg file file new fileimgpath fileoutputstream ostream try filecreatenewfile ostream new fileoutputstreamfile bitmapcompresscompressformatjpeg 100 ostream ostreamflush ostreamclose toastmaketextgetcontext image saved 50show catch exception e eprintstacktrace logittd etostring toastmaketextgetcontext failed to save 50show showmenubar i do not know why but it always errors or enters the catch statement with this errorjavaioioexception open failed enoent no such file or directory,['android'] +536444,playing a song on another device using bluetooth i have this playlist of the songs in my appi want to play a song from this playlist on anther device iphone using bluetooththis is what i have done so for import browsestationsviewcontrollerhinterface browsestationsviewcontroller gksession gksessionendimplementation browsestationsviewcontroller idinitwithnibnamensstring nibnameornil bundlensbundle nibbundleornil self super initwithnibnamenibnameornil bundlenibbundleornilif self custom initializationreturn self pragma mark voidviewdidload super viewdidload do any additional setup after loading the view self setupsessionnsnotificationcenter defaultcenter nsnotificationcenter defaultcenter register for notifications when the application leaves the background state on its way to becoming the active applicationdefaultcenter addobserverself selectorselectorsetupsession nameuiapplicationwillenterforegroundnotification objectnil register for notifications when when the application enters the backgrounddefaultcenter addobserverself selectorselectorteardownsession nameuiapplicationdidenterbackgroundnotification objectnil voiddidreceivememorywarning super didreceivememorywarning thispose of any resources that can be recreated pragma mark gksession setup and teardown voidsetupsession gksession gksession alloc initwithsessionidnil thisplaynamenil sessionmodegksessionmodepeergksessiondelegate selfgksessionthisconnecttimeout kthisconnecttimeoutgksessionavailable yesselftitle nsstring stringwithformatgksession gksessionthisplayname voidteardownsession gksession thisconnectfromallpeersgksessionavailable nogksessiondelegate nil pragma mark gksessiondelegate protocol conformance voidsessiongksession session peernsstring peerid didchangestate gkpeerconnectionstatestateswitch state case gkpeerstateavailable nslogdidchangestate peer available session thisplaynameforpeerpeerid nsthread sleepfortimeintervalksleeptimeinterval session connecttopeerpeerid withtimeoutkconnectiontimeout break case gkpeerstateunavailable nslogdidchangestate peer unavailable session thisplaynameforpeerpeerid break case gkpeerstateconnected nslogdidchangestate peer connected session thisplaynameforpeerpeerid break case gkpeerstatethisconnected nslogdidchangestate peer thisconnected session thisplaynameforpeerpeerid break case gkpeerstateconnecting nslogdidchangestate peer connecting session thisplaynameforpeerpeerid break selftableview reloaddata voidsessiongksession session didreceiveconnectionrequestfrompeernsstring peerid nslogdidreceiveconnectionrequestfrompeer session thisplaynameforpeerpeeridsession acceptconnectionfrompeerpeerid errornilselftableview reloaddata voidsessiongksession session connectionwithpeerfailednsstring peerid witherrornserror error nslogconnectionwithpeerfailed peer error session thisplaynameforpeerpeerid errorselftableview reloaddata voidsessiongksession session didfailwitherrornserror error nslogdidfailwitherror error errorsession thisconnectfromallpeersselftableview reloaddata pragma mark uitableviewdatasource protocol conformance nsintegernumberofsectionsintableviewuitableview tableview we have 5 sections in our grouped table view one for each gkpeerconnectionstatereturn 3 nsintegertableviewuitableview table numberofrowsinsectionnsintegersection nsinteger rowsnsinteger peerconnectionstate sectionswitch peerconnectionstate case gkpeerstateavailable nsarray availablepeers gksession peerswithconnectionstategkpeerstateavailable rows availablepeerscount break case gkpeerstateconnected nsarray connectedpeers gksession peerswithconnectionstategkpeerstateconnected rows connectedpeerscount break case gkpeerstateunavailable nsarray unavailablepeers gksession peerswithconnectionstategkpeerstateunavailable rows unavailablepeerscount break always show at least 1 row for each gkpeerconnectionstateif rows 1 rows 1return rows nsstring tableviewuitableview tableview titleforheaderinsectionnsintegersectionnsstring headertitle nilnsinteger peerconnectionstate sectionswitch peerconnectionstate case gkpeerstateavailable headertitle available peers break case gkpeerstateconnected headertitle connected peers break case gkpeerstateunavailable headertitle unavailable peers break return headertitle uitableviewcell tableviewuitableview tableview cellforrowatindexpathnsindexpath indexpathnsstring cellid celluitableviewcell cell tableview dequeuereusablecellwithidentifiercellidifcell cell uitableviewcell alloc initwithstyleuitableviewcellstylesubtitle reuseidentifiercellidnsinteger peerconnectionstate indexpathsectionnsarray peers nilswitch peerconnectionstate case gkpeerstateavailable peers gksession peerswithconnectionstategkpeerstateavailable break case gkpeerstateconnected peers gksession peerswithconnectionstategkpeerstateconnected break case gkpeerstateunavailable peers gksession peerswithconnectionstategkpeerstateunavailable break nsinteger peerindex indexpathrowif peerscount 0 peerindex peerscount nsstring peerid peers objectatindexpeerindex if peerid celltextlabeltext gksession thisplaynameforpeerpeerid return cell endnow i have no idea how to proceedcould someone please help me outby selecting a song can it be played on another device,"['iphone', 'ios']" +536449,is it possible to port gnu grep as a library i would like to know if it is possible to port gnu grep as a libary leaving aside the legal complications if any as this is purely for noncommercial but academic use i have seen many ports exist of gnu grep for example gnu grep for win 32 here i wonder why nobody has ever attempted to port grep as a library it would be a huge benefit to applications that exploit string searchingmining as they can use the power of gnu grep internally in the their applications i would like to attempt this feat but since i am new to string searchingmining would love to know the obvious challenges that may arise and why it has not been done as yetedit the advantage of a gnu grep library is that it will do string searching much faster using its own modified version of boyermoore where as when using a regular expression wrapper library such as pcre or boost reg exp or qt reg expressions etc the application has to read the file linebyline and parse each line against the regexp this is the obvious advantage that i see,['c'] +536469,accessing factory defined in another module in angularjs can we call the factory functions defined in one module from another module if so howlet us say my first module is defined in moduleonejs file asvar mymodule angularmodulemyservicemoduleone mymodulefactorynotify function return samplefun function some code to call samplefuntwo and my second module in moduletwojs asvar mymoduletwo angularmodulemyservicemoduletwo mymoduletwofactorynotifytwo function return samplefuntwo function code how to call samplefuntwo from samplefunthanks,['javascript'] +536479,which return type use in spring mvc in requestmapping method i know in spring mvc in controller class in requestmapping method i can returnstring model modelandviewi do not understand differencies between these actionscan you to explain me it,['java'] +536512,get html in uitextview i thisplay html in uitextview byselftextview setvaluebcontentb forkeycontenttohtmlstring after editing content in uitextview i want to get content include html so i useselftextview valueforkeycontenttohtmlstring but app crash how to fix it,['ios'] +536537,why java beans are called beans i am a java developer and i am working with beans everyday i am curious about the history of the name bean does it just comes from coffe bean or is there something else,['java'] +536542,eclipse returns error message java was started but returned exit code 1 i just downloaded and dearchived android sdk for windows im currently using w8 64x,['java'] +536578,android dividing circle into and equal parts and know the coordinates of each dividing point i have requirement that a circle should be divided into and equal parts based on number23n but i want the coordinates of dividing pointsi have a circle whose centrexy and radius150 are knownquestion is there any formula which gives me the coordinates of dividing points as shown in figure can anyone please tell me the formula i want to implement it in java circle image for refrence,['android'] +536591,select elements which start with data how can i select with plan javascript or jquery every element which has an attribute that starts with datai have tried databut it does not work,"['javascript', 'jquery', 'css']" +536654,android service crashes after app is swiped out of the recent apps list i have a service that gets started not bound by an activity if the activity gets destroyed eg by pressing the back button the service continues to run this is of course intendedhowever if i swipe the activity out of the recent apps list the service gets restarted immediately this is reproducible every time the activityapp is swiped out of the list there is a new call to the services oncreatemethod no call to ondestroy in betweenfirst i thought the service gets killed by android even though i saw no reason for the kill neither the activity nor the service do resource consuming things in fact they are minimalistic and do nothing but then i noticed that the service actually crashesvmainactivity856 ondestroy swipe out of the listiactivitymanager287 killing 856comexamplemyappu0a10050 remove taskwactivitymanager287 scheduling restart of crashed service comexamplemyapptestservice in 50msthe code is not noteworthy but here it isactivitypublic class mainactivity extends activity private static final string tag mainactivity override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main logvtag oncreate starting service startservicenew intentthis testserviceclass override protected void onstart superonstart logvtag onstart override protected void ondestroy superondestroy logvtag ondestroy servicepublic class testservice extends service private static final string tag service onbind omitted override public int onstartcommandintent intent int flags int startid logvtag onstartcommand return superonstartcommandintent flags startid override public void ondestroy superondestroy logvtag ondestroy in shortmy service is independent of the activitys lifecycle but only as long as i do not swipe out the app of the recent apps list in that case the service gets restarted but without a call to ondestroyevery time this happens not only the state of the service but also the work the service is doing is lost i just want to know why the swipe is the reason for this,['android'] +536670,why safari on ios is not showing my html5 video poster i have this webpageit have 10 video elements on itfor some reason when i load the page on an ipad it is not showing the video posters try the following load the page on a desktop browser load it on an ipad or ipad simulator and you get a big black box with a play buttonplease tell me why this is happeningheres what i have already ruled outimage contenttype headeri have validated that the image contenttype header is properly setin the example above the contenttype header properly imagejpeginterference with the videojs libraryvideojs is used to show that nice play button on desktop browsers and to customise the controls this library does not interfere with the native player howeverjust to make sure i have created a test video page which does not have the videojs class so the library does not pick up and process that video in fact the test page does not even include any js library it is just htmlbody video controls height400 width600 poster poster 1414bd5fba5a68d0f4b3f61193f6908962jpg src processed 720p 1414mp4 videobodyhtml templatestestzusage of any video attributes that may not be supported on mobile safarithe test page above just has a plain video tag i have tried removing every other attribute except for src and poster it did not helpmost of the stackoverflow questions on the topic just say restart your ipadheres where it gets weirdif you google around on this the answers on stackoverflow that have been accepted often say restart your ipad that did it for meso i have tried doing the same thing at first i just said that it does not work in my casethen i tried thisall of the following on the ipad simulatorgo to the site video posters do not showgo to the test page templatestestz video poster does not showclick home to exit safari or cmdshifth mac shortcut for the simulatordoubleclick home button to get the task switcher outside of safari tap and hold on the safari icon until the kill button showskill safariopen safari restarted at this point if you load the test page the one with just one video the poster will shownow go to the multivideo page video posters do not showgo back to the singlevideo test page the video poster for that one no longer works eitherrepeat steps 3 to 8 to see the process of when video posters stop workingso apparently at some point mobile safari decides it will no longer show any video postersalso apparently my site triggers this conditionclarificationswhen posters no longer work it does not only occur on one domain no video posters will be loaded for any other site regardless whether or not it is on a totally different domain eg the demo video from in order to reset this behaviour from what i have seen you have to kill and restart safari just closing and reopening it does not reset this statedoes anyone have any idea why this is happening is there a way to work around it,['ios'] +536671,what should be the developer payload in android inapp billing v3 api i am implementing inapp billing in my app to unlock premium featuresthe inapp billing sets up correctly everything seems fine except the developer payload thingthe sample app says todo verify that the developer payload of the purchase is correct it will be the same one that you sent when initiating the purchase warning locally generating a random string when starting a purchase and verifying it here might seem like a good approach but this will fail in the case where the user purchases an item on one device and then uses your app on a different device because on the other device you will not have access to the random string you originally generated so a good developer payload has these characteristics 1 if two different users purchase an item the payload is different between them so that one users purchase cannot be replayed to another user 2 the payload must be such that you can verify it even when the app was not the one who initiated the purchase flow so that items purchased by the user on one device work on other devices owned by the user using your own server to store and verify developer payloads across app installations is recommended the sample app uses an empty string as developer payload my question is what string to use as a developer payload can i use the users primary email id,['android'] +536704,how to convert active directory pwdlastset to datetime public static string getpropertysearchresult searchresult string propertyname if searchresultpropertiescontainspropertyname return searchresultpropertiespropertyname0tostring else return stringempty the above method works great for most active directory properties except those that are related to datetime such as pwdlastset maxpwdage etcmy question is how to i get the pwdlastset to a human readable datetime like 8132013 or august 13 2013 etci have tries this but it threw exceptions public static int64 convertadslargeintegertoint64object adslargeinteger var highpart int32adslargeintegergettypeinvokememberhighpart systemreflectionbindingflagsgetproperty null adslargeinteger null var lowpart int32adslargeintegergettypeinvokememberlowpart systemreflectionbindingflagsgetproperty null adslargeinteger null return highpart int64uint32maxvalue 1 lowparti am using the following code to get the time as an int64int64 passwordlastset convertadslargeintegertoint64objresultpropertiespwdlastset0then i plan on using the datetimeint64 constructor to create a datetime,['c#'] +536718,what is the difference between these two methods systemnetmailsmtpclient has two methods for which i am very confused1 sendasyncmailmessage objectsends the specified email message to an smtp server for delivery this method does not block the calling thread and allows the caller to pass an object to the method that is invoked when the operation completes msdn2 sendmailasyncmailmessagesends the specified message to an smtp server for delivery as an asynchronous operation msdnnotice that the names of two methods are different so it is not an overload what exactly is the difference herei am looking for very clear answer as the description given by msdn for both methods is very ambiguous at least for me it is,"['c#', 'asp.net']" +536743,bootstrap horizontal drop down take a look at this picture i want the dropdown menu items to be stack from left to right horizontallyi cannot seem get this to work tried using listinline class mentioned in the official documentation that only makes things worse heres the htmlnav classnavbar navbardefault navbarstatictop rolenavigation ul classnav navbarnav li classdropdown a href classdropdowntoggle datatoggledropdownlist itema ul classdropdownmenu lia href id1ali lia href id2ali lia href id1ali lia href id2ali lia href id3ali lia href id4ali lia href id5ali lia href id6ali ul li ulnav i am using bootstrap 3,"['html', 'css']" +536788,difference between click and tap in android the gesturedetectorongesturelistener1 class has the method onsingletapupmotionevent2notified when a tap occurs with the up motionevent que triggered itthis method has the same onclicks function can i use this method to implement the same behavior i want from the onclick method,['android'] +536857,how to add a search box with icon to the navbar in bootstrap 3 i am using the new twitter bootstrap 3 and am trying to place a search box like this below in the top navbarin bootstrap 2 it could have ben done like thisform classformsearch methodget ids action div classinputappend input typetext classinputmedium searchquery names placeholdersearch value button typesubmit classaddoni classiconsearchibutton divformbut i am not sure how to produce the same in bootstrap 3 as so much has changedthe default html for the navbar search box form in bootstrap 3 isform classnavbarform navbarleft rolesearch div classformgroup input typetext classformcontrol placeholdersearch div button typesubmit classbtn btndefaultsubmitbuttonformhow do i modify it to achieve what i need,"['html', 'css']" +536861,matplotlib adjust figure margin the following code gives me a plot with significant margins above and below the figure i do not know how to eliminate the noticeable margins subplots adjust does not work as expectedimport matplotlibpyplot as pltimport numpy as npfig pltfigureax figadd subplot1axplotrange10range10axset aspectequalplttight layouttight layout eliminates some of the margin but not all of the marginswhat i wanted is actually setting the aspect ratio to any customized value and eliminating the white space at the same timeupdate as pierre h puts it the key is to change the size of the figure container so my question is could you suggest a way to accommodate the size of the figure to the size of the axes with arbitrary aspect ratio in other words first i create a figure and an axes on it and then i change the size of the axes by changing aspect ratio for example which in general will leave a portion of the figure container empty at this stage we need to change the size of the figure accordingly to eliminate the blank space on the figure container,['python'] +536864,assembling a function as needed and computing it fast there are interpreted languages out there such as lisp tcl perl etc that make it easy to define a lambdaprocsub within your code during runtime and to evaluate it within the same sessionthere are compiled languages out there such as c that would execute much faster than the interpreted ones yet defining a function within a compiled program during runtime and executing it is not easy if at all possiblethe problem here is to do the followingdefine a function during runtime for example based on the initial input data derive an analytic model of the dataexecute the above function fast in a loop for example apply the derived analytic model for analysing incoming dataone solution that i saw was not very pretty a procedure representing the analytic model was derived in embedded tcl based on the initial input data a lookup table was created by evaluating the procedure in tcl on an array of sample points that optimistically speaking would cover the applicability rangethe lookup table was passed from the tcl interpreter back to the binary which was developed in cthen the incoming data was analysed by interpolating between close enough values in the lookup tablethe above solution works but has quite a few problems both conceptual and computational thus the question is it possible to define a function purely within c and make it available for execution within the same runtime session conceptually speaking is it possible to do something like create a function as a string compile it inmemory and somehow link it back into the binary that is being executed,['c++'] +536922,detecting thumb position in seekbar prior to api version 16 basically i need to detect when the progress changes in the seekbar and draw a text view on top of the thumb indicating the progress value i do this by implementing a onseekbarchangelistenerand on the public void onprogresschangedseekbar seekbar int progress boolean b method i call rect thumbrect seekbargetthumbgetbounds to determine where the thumb is positionedthis works perfectly fine but apparently getthumb is only available in api level 16 android 41 causing a nosuchmethoderror on earlier versionsany idea how to work around this issue,['android'] +537028,how can i programmatically change the argspec of a function not in a python decorator very closely related to how can i programmatically change the argspec of a function in a python decoratorthe decorator module provides the means to make a decorator function that preserves the argspec of the decorated functionif i define a function that is not used as a decorator is there a way to copy another functions argspecexample use caseclass blahobject def fooself args kwargs a docstr result barargs kwargs result result2 just so it is clear were doing something extra here return resultdef barx y z1 q2 a more useful docstr saying what xyzq do return xyzqi would like to have foos argspec look like bars but the source to stay unchanged ie inspectgetsourcefoo would still show the result junk the main purpose for this is to get sphinx docs and ipythons interactive help to show the appropriate argumentsas the answers to the other question said the decorator package shows a way to do this but i got lost within the meat of that code it seems that the decorator package is recompiling the source or something like that i had hoped a simpler approach eg something like fooargspec barargspec would be possible,['python'] +537045,are there any differences between these two higherorder function definitions are there any differences among 4 statements in maini feel only apply2func makes sense however all 4 return the same value int funcvoid return 1int apply1 int f1void return f1int apply2 int f1 void return f1int main apply1func apply1func apply2func apply2func return 0,"['c++', 'c']" +537111,i need to show an pdf in which text of pdf will auto fit to the screen width and remaining text move to the next line i am showing an pdf form url via google doc in my web view webviewloadurlurl urlpdf it works but i want to use warp content functionality so that text of pdf should auto fit to the screen width and exceeded text move to the new line so i can scroll it i searched many sdks to do this but did not get success below i attached an screen which shows my requirement,['android'] +537135,mapreduce program examples for beginners i am a beginner in mapreduce programs so pardon me if the question is not importanti would like to learn more about mapreduce programs for understanding the programming methods i would like to practise more programs other than the wordcount program can anyone suggest good links for good and simple mapreduce examples other than wordcounti am using eclipse juno and cdh4please help me,['java'] +537168,android byte array to bitmap how to how can i convert byte array received using socketthe c client send image data which is of type ucharat the android side i am receiving this uchar array as byte which is ranges from 128 to 127what i wanted to do is that receives this data and thisplay it for that i was trying to convert to bitmap using bitmapfactorydecodebytearray but no luck i am getting null bitmap am i doing right or any other method availablethanks in advance,['android'] +537212,bootstrap 3 text overlay on image i am using bootstrap 3 thumbnail as follows div classthumbnail img srcimgrobotjpg alt div classcaption postcontent h3robotsh3 plorem ipsum dolor sit ametp div divi want the caption to overlay on image but the way being done on mashablecomi have tried following but no luck postcontent background none repeat scroll 0 0 f opacity 05 margin 54px 20px 12px position relativehow can i overlay a caption div on top of image but just like mashablecom this works but i want it centered just like mashable and centered for every image for some images it is not centered,"['html', 'css']" +537223,what is the difference between the agile scrum and cmmi tfs process templates i want to ask you a very simple question what is the difference between the agile scrum and cmmi tfs process templates from a developers point of viewi am creating a project in team foundation server and it is asking me to chose a project templatei have different options but i am wondering how it is going to affect my development if i choose msf for agile software devlopment or scrum as a layman developer please tell me the difference between these templates your answer should be focused on as a developer what is the diference i am going to feel,['asp.net'] +537262,get all role names in aspnet mvc5 identity system mvc5 uses a new identity system how can i get all role namesi try do access it via identitystore but without success,['c#'] +537305,set to dict python is there any pythonic way to convert a set into a dicti got the following sets 12456and want the following dictc 10 20 30 40 50 60with a list you would do a 123456b while lenb lena bappend0c dictitertoolsizipab,['python'] +537424,javascript crc32 i am looking for a modern javascript implementation of crc32this implementation which may have originated from here and is now here there and everywhere is unacceptable because it is slow 500msmb and depends on over 2kb of space delimited table accessed using substr yuckthere appears to be a few variations of crc32 so i need to match this outputmysql select crc32abcde 2240272485function does not actually need to accept a string however since i am working with byte arrays,['javascript'] +537510,is there a pulldown class for navbar in twitter bootstrap 232 there are pullright and puleft classes to align block elements i am wondering if there is corresponding pulltop and pullbottom workable for navbarheader idnavbar rolebanner classnavbar navbarfixedtop div classnavbarinner div classcontainer btnnavbar is used as the toggle for collapsed navbar content a classbtn btnnavbar datatogglecollapse datatargetnavcollapse span classiconbarspan span classiconbarspan span classiconbarspan a a classlogo puleft href titlehome img srclogopng althome a div classnavcollapse collapse nav rolenavigation ul classmenu nav lili ul nav div div divheaderto goal is to align the menu ulnav to the bottom of navbar,['css'] +537534,fragmentstatepageradapter with childfragmentmanager fragmentmanagerimplgetfragment results in nullpointerexception edit 2i now managed to get rid of the error with using the trick from here so that is the reoson why my last edit is placed on top of my questionbut this led to the next errorjavalangnullpointerexceptionat androidsupportv4appfragmentmanagerimplgetfragmentfragmentmanagerjava569at androidsupportv4appfragmentstatepageradapterrestorestatefragmentstatepageradapterjava211at androidsupportv4viewviewpageronrestoreinstancestateviewpagerjava1281at androidviewviewthispatchrestoreinstancestateviewjava12043at androidviewviewgroupthispatchrestoreinstancestateviewgroupjava2688at androidviewviewgroupthispatchrestoreinstancestateviewgroupjava2694at androidviewviewgroupthispatchrestoreinstancestateviewgroupjava2694at androidviewviewrestorehierarchystateviewjava12021at androidsupportv4appfragmentrestoreviewstatefragmentjava425at androidsupportv4appfragmentmanagerimplmovetostatefragmentmanagerjava949at androidsupportv4appfragmentmanagerimplmovetostatefragmentmanagerjava1104at androidsupportv4appbackstackrecordrunbackstackrecordjava682at androidsupportv4appfragmentmanagerimplexecpendingactionsfragmentmanagerjava1460at androidsupportv4appfragmentmanagerimpl1runfragmentmanagerjava440at androidoshandlerhandlecallbackhandlerjava615at androidoshandlerthispatchmessagehandlerjava92at androidoslooperlooplooperjava137at androidappactivitythreadmainactivitythreadjava4800at javalangreflectmethodinvokenativenative methodat javalangreflectmethodinvokemethodjava511at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava798at comandroidinternaloszygoteinitmainzygoteinitjava565at dalviksystemnativestartmainnative methodand now i do not know where to continueedit 0 first questioni get following exceptionjavalangillegalstateexception no activityat androidsupportv4appfragmentmanagerimplmovetostatefragmentmanagerjava1091at androidsupportv4appfragmentmanagerimplmovetostatefragmentmanagerjava1086at androidsupportv4appfragmentmanagerimplthispatchactivitycreatedfragmentmanagerjava1877at androidsupportv4appfragmentperformactivitycreatedfragmentjava1492at androidsupportv4app holofragmentperformactivitycreated holofragmentjava251at androidsupportv4appfragmentmanagerimplmovetostatefragmentmanagerjava947at androidsupportv4appfragmentmanagerimplmovetostatefragmentmanagerjava1104at androidsupportv4appbackstackrecordrunbackstackrecordjava682at androidsupportv4appfragmentmanagerimplexecpendingactionsfragmentmanagerjava1460at androidsupportv4appfragmentmanagerimpl1runfragmentmanagerjava440at androidoshandlerhandlecallbackhandlerjava615at androidoshandlerthispatchmessagehandlerjava92at androidoslooperlooplooperjava137at androidappactivitythreadmainactivitythreadjava4800at javalangreflectmethodinvokenativenative methodat javalangreflectmethodinvokemethodjava511at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava798at comandroidinternaloszygoteinitmainzygoteinitjava565at dalviksystemnativestartmainnative methodi have no idea where to start i am using the up to date support library v4 rev18everything works fine until i add a fragment which holds a viewpager in combination with fragmentstatepageradapteri am using the support library everywhere i tried the solutions from but nothing worked yeti do not know where to start does anyone have a hintedit 1 background and code1 in my mainactivity i use followingthe third page has the viewpagerpublic void setpageint pos boolean addtobackstack fragment nextfragment null fragmenttransaction transaction null switch pos case 0 if mfragmentallroutines null mfragmentallroutines new routineslistfragment if mfragmentallroutinesisvisible nextfragment mfragmentallroutines break case 1 if mfragmentroutine null mfragmentroutine new routinefragment if mfragmentroutineisvisible nextfragment mfragmentroutine break case 2 if mfragmentday null mfragmentday new routinedayfragment if mfragmentdayisvisible nextfragment mfragmentday break default break if nextfragment null fragment prevfragment getsupportfragmentmanagerfindfragmentbyidridfragment transaction getsupportfragmentmanagerbegintransaction if prevfragment null transactiondetachprevfragment transactionreplaceridfragment nextfragment nextfragmentgetclassgetname transactionattachnextfragment if addtobackstack transactionaddtobackstacknull transactioncommit 2 the third fragmentit is a simple fragment with a viewpager and a fragmentstatepageradapter the fragmentstatepageradapter gets the getchildfragmentmanager as fragmentmanager and somewhere there seems to be the problem,['android'] +537596,is default noargs constructor mandatory for gson gson user guide states that we should define default noargs constructor for any class to work with gson properly even more in the javadoc on gsons instancecreator class said that exception will be thrown if we try to deserialize instance of class missing default constructor and we should use instancecreator in such cases however i have tried to test use gson with class lacking default constructor and both serialization and deserialization work without any troublehere is the piece of code for deserializaiton a class without nonargs constructorpublic class mushroom private string name private double diameter public mushroomstring name double diameter thisname name thisdiameter diameter equals hashcode etcand a testtestpublic void deserializemushroom assertequals new mushroomfly agaric 40 new gsonfromjson namefly agaric diameter40 mushroomclasswhich works fineso my question is could i actually use gson without need to have default constructor or there is any circumstances when it will not work,['java'] +537622,responsive website how to get rid of horizontal scroll bar i am currently creating a responsive website i noticed there is an issue with empty space on the right as you scrolling horizontally i can remove the horizontal scroll by adding overflowx hidden but it will not work on mobile devices such as iphone and ipadso i tried to add minwidth because it will help to get rid of empty space but i cannot put minwidth on fullcss eg minwidth10px because it will set to fullwidth see example belowfullcss wrapper width 10px margin 0 autoresponsivecss less than 10pxwrapper width 100 margin 0i was wondering if you know how to fix this issue let me know if you have a better option for it or should i create a new wrapper id,['css'] +537632,ifelse statement shortcut in c c has the following syntax for a shorthand ifelse statement integer 5 true falsei often find myself requiring only one portion true or false of the statement and use this integer 5 true 0i was just wondering if there was a way to not include the else portion of the statement using this shorthand notation,['c'] +537636,android concurrency usage android has a lot of different facilitations of executing code on separate threads concurrently but i am not sure when each one should be used or what the best practices are for these different ways whenwhy should handlers be usedwhenwhy should loaders be usedwhenwhy should asynctasks be usedwhenwhy should futuretask be used whenwhy should executor be used whenwhy should threadsrunnables be usedwhenwhy should volley be usedhave i missed any thanks very much for the help,"['java', 'android']" +537645,how to implement task async for a timer in c i want a given operation to execute for a certain amount of time when that time has expired send another execution commandstartdoingstuffsystemthreadingthreadsleep200stopdoingstuffrather than have a sleep statement in there that is blocking the rest of the application how can i write this using an asynctaskawait in c,"['c#', '.net']" +537677,linker script placing a section at the end of a memory region i have searched far and wide for how to do this and have failed to come up with an answermy memory layout is as followsfake address section 0 text 7 relocate 15 bss 23 stackat the end of the stack i place the heap which grows up and the stack is a full descending stack for the arm chip i am usingnow what i want to do is place a single section let us call it persist into my ram memory i want it to reside at the very end of ram and i want to program this into my linker scriptso far i have not come up with a good way to do it since i know the ram start address and size it would be trivial to calculate where the section needs to go if i knew the section size however according to the gnu linker documentation pg 74 it seems thatsizeofsection returns the size in bytes of the named section if that section has been allocated if the section has not been allocated when this is evaluated the linker will report an errorso i cannot work out the size of the section in the linker script since i want to calculate the size before i place itallocate itdoes anyone know a good way to do this,"['c++', 'c']" +537694,make bottom of uitableview move up with keyboard i have an application with a uitableview and a uitextview so sometimes the keyboard is up whenever the keyboard is up i cannot access the bottom 34 table cells because they are always stuck behind the keyboard how can i make the uitableview only take up the space above the keyboard while the keyboard is thisplayed,"['ios', 'objective-c']" +537758,uicollectionview current visible cell index i am using uicollectionview first time in my ipad applicationi have set uicollectionview such that its size and cell size is same means only once cell is thisplayed at a timeproblemnow when user scroll uicollectionview i need to know which cell is visible i have to update other ui elements on change i did not find any delegate method for this how can i achieve thiscodeselfmainimagecollection settagmain image collection viewselfmainimagecollection registerclassinspirationmainimagecollectioncell class forcellwithreuseidentifiercellidentifierselfmainimageflowlayout setscrolldirectionuicollectionviewscrolldirectionhorizontalselfmainimageflowlayout setminimuminteritemspacing00fselfmainimageflowlayout setminimumlinespacing00fselfmainimageflowlayoutminimumlinespacing 0selfmainimagecollection setpagingenabledyesselfmainimagecollection setshowshorizontalscrollindicatornoselfmainimagecollection setcollectionviewlayoutselfmainimageflowlayoutwhat i have triedas uicollectionview conforms to uiscrollview i got when user scroll ends with uiscrollviewdelegate methodvoidscrollviewdidenddeceleratinguiscrollview scrollviewbut inside above function how can i get current visible cell index of uicollectionview,"['ios', 'objective-c']" +537810,performance benchmarking of contains exists and any i have been searching for a performance benchmarking between contains exists and any methods available in the listt i wanted to find this out just out of curiosity as i was always confused among these many questions on so described definitions of these methods such as linq ring any vs contains for huge collectionslinq any vs exists whats the differencelinq extension methods any vs where vs existsso i decided to do it myself i am adding it as an answer any more insight on the results is most welcomed i also did this benchmarking for arrays to see the results,['c#'] +537836,any fallback clientside solutions for the html5 download attribute is there a clientside fallback option for browsers that do not support the html5 download attributecurrently this is only properly supported in chrome firefox has support but has taken an obtuse point of view that it should only work on files from the same domain for security issuesthe proper way to handle this is to have a backend server that proxies requested files with a contentthisposition header but in this case its most likely not an optionfirefoxs security theater is not very helpful either since it is an arbitrary mechanism to setup a proxyi was looking at but just realized it only supports file creation not remote file access,['javascript'] +537847,is there any way to control the padding between struct members incl bit field in c i am working on parsing network data stream i am wondering if there is any way i can map the data stream directly to the data structurefor example i want to define the data structure for an rtp protocol as followsclass rtpheader int version2 the first two bits is version int p1 the next bits is an field p int x1 int cc4 int m1 int pt7 int sequencenumber int64 timestamp and using it this wayrtpheader headermemcpyheader steamdata sizeofheaderbut as the c compiler will insert padding between the members is there any way to control that so that no padding are added between members including the bit field membersthis question is not a duplicate of how to get rid of padding bytes between data members of a struct because there can be bit fields in my example,"['c++', 'c']" +537884,doctrine2 multiple insert in one shot i am new to doctrine and there are still some blurred areas for me in this case i am inserting new record in the database using a loop and the entity manager it works fine but i noticed that doctrine make one insert query by entity which can become pretty hugeusing doctrine2 and symfony 23 i would like to know how we can set it up so it would make only 1 insert query with all the values in it we are talking of 1 entity only of coursewhat i mean is changing this insert into dummy table values x1 y1 insert into dummy table values x2 y2intoinsert into dummy table values x1 y1 x2 y2here is my code em thiscontainergetdoctrinegetmanagerforeachitems as item newitem new productitemdatas empersistnewitememflush,"['php', 'mysql']" +537893,uitoolbar standard sizes what are the standard sizes of a uitoolbar for the followingiphonepodiphone 35 inch verticaliphone 35 inch horizontaliphone 4 inch verticaliphone 4 inch horizontalipadipad verticalipad horizontal,"['ios', 'objective-c']" +537911,azure sql database connectivity issues too many connections i have a site which is a white label multiple versions of the same site which i have launched recently there is not a great deal of traffic yet mainly bots but probably 800 users per day it is hosted on azure with an azure database in addition to an admin panel located on a nonazure server both sites connect to the same azure database there are also some worker roles running to process data 99 of the time they are not doing anything but they check regularlyi have always experienced random errors which last a few seconds and then it is ok again such asa transportlevel error has occurred when receiving results from the server provider tcp provider error 0 an existing connection was forcibly closed by the remote hostthis morning however we had a more serious problem it started withsystemcomponentmodelwin32exception an existing connection was forcibly closed by the remote hostthis occurred whilst bots google baidu ahrefsbot wiseguysnl were indexing the site i got one or more errors from these then i gotsystemdatasqlclientsqlexception the service has encountered an error processing your request please try again error code 40143 a severe error occurred on the current command the results if any should be thiscardedthis was during an executereader phase10 minutes later the real problem came which meant that nobody could log in to the admin interface but the azure hosted website appeared ok when i tested it although the bots were still bringing up errors the problem wassystemcomponentmodelwin32exception the wait operation timed outthis continued with random connections working on and off for about an hour then i hit another problemsystemdatasqlclientsqlexception resource id 1 the request limit for the database is 180 and has been reached see for assistancethis occurred on and off for the last hour predominantly for the worker roles i then tried to find out what was taking up all of these requests and i found this commandselect from sysdm exec requests it only returned 1 or 2 requests when i was running it over and overso my questions are1 does anyone else experience relatively regular once maybe twice a day a temporary thisconnect from the server hosted on azure2 does the list of events above indicate a particular problem this could all have occurred when lots of admins were logging in at once3 how can i better debug the number of requests to the database when i get the 180 limit messagethanks in advance,['c#'] +537940,linearlayoutlayoutparams cannot be cast to androidwidgetframelayoutlayoutparams explanation and solution at the bottomi am development one slider layout animation animation work fine but when all process end get next exceptioni guess relativelayout parent have something to do in exception but i do not know resolved it0906 112458952 etrace30884 error opening trace file no such file or directory 20906 112509113 eandroidruntime30884 fatal exception main0906 112509113 eandroidruntime30884 javalangclasscastexception androidwidgetlinearlayoutlayoutparams cannot be cast to androidwidgetframelayoutlayoutparams0906 112509113 eandroidruntime30884 at androidwidgetframelayoutonmeasureframelayoutjava3110906 112509113 eandroidruntime30884 at androidviewviewmeasureviewjava152640906 112509113 eandroidruntime30884 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava49160906 112509113 eandroidruntime30884 at androidwidgetframelayoutonmeasureframelayoutjava3100906 112509113 eandroidruntime30884 at androidviewviewmeasureviewjava152640906 112509113 eandroidruntime30884 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava49160906 112509113 eandroidruntime30884 at androidwidgetlinearlayoutmeasurechildbeforelayoutlinearlayoutjava13900906 112509113 eandroidruntime30884 at androidwidgetlinearlayoutmeasureverticallinearlayoutjava6810906 112509113 eandroidruntime30884 at androidwidgetlinearlayoutonmeasurelinearlayoutjava5740906 112509113 eandroidruntime30884 at androidviewviewmeasureviewjava152640906 112509113 eandroidruntime30884 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava49160906 112509113 eandroidruntime30884 at androidwidgetframelayoutonmeasureframelayoutjava3100906 112509113 eandroidruntime30884 at comandroidinternalpolicyimplphonewindowdecorviewonmeasurephonewindowjava21610906 112509113 eandroidruntime30884 at androidviewviewmeasureviewjava152640906 112509113 eandroidruntime30884 at androidviewviewrootimplperformmeasureviewrootimpljava21290906 112509113 eandroidruntime30884 at androidviewviewrootimplmeasurehierarchyviewrootimpljava12400906 112509113 eandroidruntime30884 at androidviewviewrootimplperformtraversalsviewrootimpljava14330906 112509113 eandroidruntime30884 at androidviewviewrootimpldotraversalviewrootimpljava11250906 112509113 eandroidruntime30884 at androidviewviewrootimpltraversalrunnablerunviewrootimpljava46070906 112509113 eandroidruntime30884 at androidviewchoreographercallbackrecordrunchoreographerjava7470906 112509113 eandroidruntime30884 at androidviewchoreographerdocallbackschoreographerjava5670906 112509113 eandroidruntime30884 at androidviewchoreographerdoframechoreographerjava5360906 112509113 eandroidruntime30884 at androidviewchoreographerframethisplayeventreceiverrunchoreographerjava7330906 112509113 eandroidruntime30884 at androidoshandlerhandlecallbackhandlerjava6150906 112509113 eandroidruntime30884 at androidoshandlerthispatchmessagehandlerjava920906 112509113 eandroidruntime30884 at androidoslooperlooplooperjava1530906 112509113 eandroidruntime30884 at androidappactivitythreadmainactivitythreadjava50860906 112509113 eandroidruntime30884 at javalangreflectmethodinvokenativenative method0906 112509113 eandroidruntime30884 at javalangreflectmethodinvokemethodjava5110906 112509113 eandroidruntime30884 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava8210906 112509113 eandroidruntime30884 at comandroidinternaloszygoteinitmainzygoteinitjava5840906 112509113 eandroidruntime30884 at dalviksystemnativestartmainnative methodactivity homexmlrelativelayout xmlnsandroid xmlnstools androidlayout widthmatch parent androidlayout heightmatch parent linearlayout androidididleftview androidlayout widthmatch parent androidlayout heightmatch parent androidbackgroundcad0 androidorientationvertical linearlayout linearlayout androidididmainview androidlayout widthmatch parent androidlayout heightmatch parent androidbackground8760 androidorientationvertical linearlayout androidlayout widthmatch parent androidlayout height50dp androidbackgroundcecece androidorientationhorizontal button androidididbtnslide stylestylebtn1 androidlayout widthwrap content androidlayout heightwrap content androidtextx linearlayout linearlayoutrelativelayoutactivitypublic class homeactivity extends activity implements onclicklistener userstorage userstorage new userstorage private button btnslide private linearlayout mainview leftview private slideranimation slideanimation override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity home thisleftview linearlayout findviewbyidridleftview thismainview linearlayout findviewbyidridmainview thisbtnslide button findviewbyidridbtnslide thisbtnslidesetonclicklistenerthis thisslideanimation new slideranimationthis thisslideanimationinitializefilteranimationsthismainview thisleftview override public void onclickview v switch vgetid case ridbtnslide thisslideanimationtoggleleftsliding break animationlistenerpublic class slideranimation implements animationlistener private context context private linearlayout mainview leftview private animation mainslidein mainslideout private boolean leftanimated rightanimated false private int devicewidth public slideranimationcontext context thiscontext context thisplaymetrics thisplaymetrics contextgetresources getthisplaymetrics thisdevicewidth thisplaymetricswidthpixels public void initializefilteranimationslinearlayout mainview linearlayout leftview thismainview mainview thisleftview leftview thismainslidein animationutilsloadanimationcontext ranimmain slide in thismainslideinsetanimationlistenerthis thismainslideout animationutilsloadanimationcontext ranimmain slide out thismainslideoutsetanimationlistenerthis public void toggleleftsliding if thisleftanimated thismainviewstartanimationthismainslidein else thismainviewstartanimationthismainslideout override public void onanimationendanimation animation if thisleftanimated linearlayoutlayoutparams params new linearlayoutlayoutparams thisdevicewidth 20 100 thismainviewgetheight paramsleftmargin thisdevicewidth 80 100 thismainviewsetlayoutparamsparams thisleftanimated true else linearlayoutlayoutparams params new linearlayoutlayoutparams thisdevicewidth thismainviewgetheight paramsleftmargin 0 thismainviewsetlayoutparamsparams thisleftanimated false override public void onanimationrepeatanimation animation override public void onanimationstartanimation animation thank you in advanceexplanation and solutionwe must to kwow the parent viewgroup container for the view because each view is filled with its parent layoutparams for measure purposesif we do not know through a simple glance on the xml which is the parent viewgroup for the view we can always get its reference with getparent method from the view instance,['android'] +537970,how to make a custom private plugin in phonegap is there any way to achieve this everywhere i see contributing to plugin development or making use of an existing plugin which are public i would like to make a private plugin is this possible i am aware that through eclipse for android i can do this but anyway to do this using phonegap build process so that i can make use of other advantages of using phonegap build,['android'] +537987,failed to find or load the registered net framework data provider with mysql mvc4 we are getting the following error when we tried running our mvc4 project with azure mysql db in webconfig file we have the followingdbproviderfactories remove invariantmysqldatamysqlclient add namemysql data provider invariantmysqldatamysqlclient descriptionnet framework data provider for mysql typemysqldatamysqlclientmysqlclientfactory mysqldata dbproviderfactorieserrorfailed to find or load the registered net framework data providerdescription an unhandled exception occurred during the execution of the current web request please review the stack trace for more information about the error and where it originated in the code exception details systemconfigurationconfigurationerrorsexception failed to find or load the registered net framework data providersource error line 96 if objectquery null stringisnulloremptypathline 97 line 98 return objectqueryincludepathline 99 line 100source file cphase2freelancefreelanceframeworkdatafreelancedataframeworkentityframeworkextensionscs line 98 stack trace configurationerrorsexception failed to find or load the registered net framework data provider systemdatacommondbproviderfactoriesgetfactorydatarow providerrow 2238858 systemdataentitycliententityconnectiongetfactorystring providerstring 143 systemdataentitycliententityconnectionchangeconnectionstringstring newconnectionstring 641 systemdataentityinternallazyinternalconnectiontryinitializefromappconfigstring name appconfig config 144 systemdataentityinternallazyinternalconnectioninitialize 95 systemdataentityinternallazyinternalconnectioncreateobjectcontextfromconnectionmodel 16 systemdataentityinternallazyinternalcontextinitializecontext 269 systemdataentityinternalinternalcontextgetentitysetandbasetypefortypetype entitytype 26 systemdataentityinternallinqinternalset1initialize 71 systemdataentityinternallinqinternalset1includestring path 25 systemdataentityinfrastructuredbquery1includestring path 1 freelancedataframeworkentityframeworkextensionsincludeiqueryable1 source string path in cphase2freelancefreelanceframeworkdatafreelancedataframeworkentityframeworkextensionscs98 freelancedataframeworkentityframeworkextensionsincludeiqueryable1 source expression1 expression in cphase2freelancefreelanceframeworkdatafreelancedataframeworkentityframeworkextensionscs64 freelancedataframeworkentityframeworkextensionsincludeiqueryable1 source expression1 expressions in cphase2freelancefreelanceframeworkdatafreelancedataframeworkentityframeworkextensionscs79 freelancedataframeworkentityframeworkrepository1getallexpression1 include in cphase2freelancefreelanceframeworkdatafreelancedataframeworkentityframeworkrepositorycs89 freelancebusinesspagebcgetpages in cphase2freelancefreelancebusinessfreelancebusinessadminpagebccs49 freelanceservicespageservicegetpages in cphase2freelancefreelanceservicesfreelanceservicespageservicecs54 freelancewebhelpersdatahelpergetapages in cphase2freelancefreelanceuser interfacefreelancewebhelpersdatahelpercs250 freelancewebresourceconfiggetapages in cphase2freelancefreelanceuser interfacefreelancewebapp startresourceconfigcs64 freelancewebappconfigrun in cphase2freelancefreelanceuser interfacefreelancewebapp startappconfigcs55 freelancewebmvcapplicationapplication start in cphase2freelancefreelanceuser interfacefreelancewebglobalasaxcs40httpexception 0x804005 failed to find or load the registered net framework data provider systemwebhttpapplicationfactoryensureappstartcalledforintegratedmodehttpcontext context httpapplication app 4054645 systemwebhttpapplicationregistereventsubscriptionswithiisintptr appcontext httpcontext context methodinfo handlers 191 systemwebhttpapplicationinitspecialhttpapplicationstate state methodinfo handlers intptr appcontext httpcontext context 352 systemwebhttpapplicationfactorygetspecialapplicationinstanceintptr appcontext httpcontext context 407 systemwebhostingpipelineruntimeinitializeapplicationintptr appcontext 375httpexception 0x804005 failed to find or load the registered net framework data provider systemwebhttpruntimefirstrequestinithttpcontext context 11646640 systemwebhttpruntimeensurefirstrequestinithttpcontext context 141 systemwebhttpruntimeprocessrequestnotificationprivateiis7workerrequest wr httpcontext context 4869909,"['c#', 'mysql']" +538038,how to interpret this stack trace i recently released a windows phone 8 appthe app sometimes seem to crash randomly but the problem is it crash without breaking and the only info i get is a message on output that tells me there were an access violation without giving any detailsso after releasing from the crash reports i was able to obtain some more information but they are kinda cryptical to methe info areproblem function unknown not very usefulexception type c05 this is the code for access violation exceptionstack trace frame image function offset 0 qcdx9um8960 0x035426 1 qcdx9um8960 0x0227e2i am not used to work with memory pointer et similia and i am not used to see a stack trace like thatso i have those questionhow should i interpretread those information whats the meaning of every piece of informationis there a way to leverage those information to target my search for the problemis there a way to get those information while debugging in vs2012notes i am not asking what an access violation isi tagged this as c and c because my code is in c but the exception is generated i am semiguessing by c implementation for the webbrowser componentediti tried setting the debug type to native only this let me obtain the same info i had in the crash report on the dev center this way the debugger break when the exception is thrown and let me see the thisassebled code unfortunately there is no qcdx9um8960 pdb file even on microsoft symbol server so i do not know the function name that caused the error,"['c#', 'c++']" +538165,how and why one would use boost signals2 learning c and trying to get familiar with some patterns the signals2 doc clearly has a vast array of things i can do with slots and signals what i do not understand is what types of applications use cases i should use it for i am thinking along the lines of a state machine thispatching change events coming from a dynamically typed background cjava etc youd use an event thispatcher or a static ref or a callback are there difficulties in c with using crossclass callbacks is that essentially why signals2 exists one to the example cases is a documentview how is this pattern better suited than say using a vector of functions and calling each one in a loop or say a lambda that calls state changes in registered listening class instances class documentpublic typedef boostsignals2signalvoid signal tpublic document connect a slot to the signal which will be emitted whenever text is appended to the document boostsignals2connection connectconst signal tslot type subscriber return m sigconnectsubscriber void appendconst char s m text s m sig const stdstring gettext const return m text private signal t m sig stdstring m textand class textviewpublic textviewdocument doc m documentdoc m connection m documentconnectboostbindtextviewrefresh this textview m connectionthisconnect void refresh const stdcout textview m documentgettext stdendl private document m document boostsignals2connection m connection,['c++'] +538191,how to use a function only if the version is 11 in my code i am using the a function with query text changebut it is only supported from android 11this is a simple search barhow to verify the current version of android and show a different activitythanks,['android'] +538238,angularjs build url with query string how to build a url with query parameters in angularjsi see the api locationsearchthe problem is locationurl is to redirect to the url in my case i want to pass a url and keyvalue pairs for the query params and build the url something likeurl abcparams field1 value1 field2 value2result abcfield1value1field2value2i like to use this url for links i have also seen angular encode characters can i avoid thiseditmy intention was to use the url as href for anchor elements i do use http to send the request but sometimes i need to provide a link with query params based on the current object thanks,['javascript'] +538244,does the clr tail instruction thisable preemptive gc i am attempting to debug a production issue with a windows service that has a tendency to fall over rapidly once a number of concurrent connections are active through the magic of a core dump and debugdiag i was able to thiscover that there was a pending gc operation which could not start until several threads with preemptive gc thisabled completed their work here is a sample thread dump from windbg showing the offending threads26 6e 14 00440 80092 thisabled 0020f88 007a0 0 mta threadpool completion port27 c1 1a0c 00fe0 80092 thisabled 00e90f88 007a0 0 mta threadpool completion port28 b5 17bc 006f0 80092 thisabled 0026800f88 007a0 0 mta threadpool completion port29 89 1f1c 00ab0 80092 thisabled 00a30f88 007a0 0 mta threadpool completion port30 ac 2340 00f70 8009220 thisabled 00d0d08 007a0 1 mta gc threadpool completion port31 88 1b64 00fd0 8009220 enabled 00b2800b48 007a0 0 mta threadpool completion portso here you can see several threads which have preemptive gc thisabled threads 26272829 and one thread 30 which is waiting on those threads to perform the gcmy googlefu lead me to this blog post which describes what sounds like a similar problem only in my case there was no xml involved it gave me enough information to know where to dig though and eventually i thiscovered that one of the common features of the threads with preemptive gc thisabled was a stack trace that looked like this at the topntdllntwaitforsingleobjectantdllrtlpwaitoncriticalsectione8ntdllrtlentercriticalsectiond1ntdllrtlplookupdynamicfunctionentry58ntdllrtllookupfunctionentrya3clrjit tailcalldbdebugdiag also warned me about the criticalsection and it just so happens that the threads with the jit tailcall are the also the only threads with rtlentercriticalsectionso my question is is it in fact the tail instruction that is causing this deadlock and if so what can i do about iti can thisable tailcalls on my fsproj files but it looks like at least one of these is coming from fsharpcoredll and some spelunking in the decompiler seems to confirm the existence of the tail instruction so i do not know that chaning the project config will remove all of the tail instructionshas anyone dealt with something like this beforeupdatesome more info which could be usefulhere is the output of locks for this dumplockscritsec 401680 at 0401680waiterwoken nolockcount 0recursioncount 1owningthread 2340entrycount 0contentioncount bf lockedscanned 1657 critical sectionsthread 2340 is the thread which has started the gc thread 30 in the partial list i included aboveand syncblk is only showing items owned by the zookeeper client which while annoying is not involved in any of the stacks which are keeping gc from startingsyncblkindex syncblock monitorheld recursion owning thread info syncblock owner11 019721a38 1 1 019766e20 638 7 0fb2950 systemcollectionsgenericlinkedlist1zookeepernetpacket zookeepernet waiting threads18 019721c68 1 1 01ae71420 8ac 13 012defc8 systemcollectionsgenericlinkedlist1zookeepernetpacket zookeepernet waiting threadstotal 64ccw 0rcw 0comclassfactory 0free 5,['.net'] +538256,why are arrays covariant but generics are invariant from effective java by joshua blocharrays differ from generic type in two important ways first arrays are covariant generics are invariantcovariant simply means if x is subtype of y then x will also be sub type of y arrays are covariant as string is subtype of object sostring is subtype of objectinvariant simply means irrespective of x being subtype of y or not listx will not be subtype of listymy question is why the decision to make arrays covariant in java there are other so posts such as why are arrays invariant but lists covariant but they seem to be focussed on scala and i am not able to follow,['java'] +538279,how can i check if a string only contains letters in python i am trying to check if a string only contains letters not digits or symbolsfor example only lettershellotrue only lettershe7lofalse,['python'] +538308,unity 3 and error the type name or alias x could not be resolved please check your configuration file and verify this type name is there any way to resolve this problem with unity 3 i have made all that is possible to bypass this message error but i cant resolve i am 2 days trying to resolve and have already did everything i have seen in googles searchesi am almost giving up and trying another di solution please any help will be finemy configuration filexml version10 encodingutf8 configuration configsections section nameunity typemicrosoftpracticesunityconfigurationunityconfigurationsection microsoftpracticesunityconfiguration configsections unity xmlns assembly namebiblioteca assembly namebibliotecacontracts assembly namebibliotecabusiness namespace namebiblioteca namespace namebibliotecacontracts namespace namebibliotecabusiness container register typebibliotecacontractsimantercategoriabo maptobibliotecabusinessmantercategoriabo container unityconfigurationmy interfaceusing bibliotecatransportusing systemlinqnamespace bibliotecacontracts public interface imantercategoriabo iqueryablecategoriadto getall categoriadto getbyidint id void insertcategoriadto dto my concrete classusing bibliotecacontractsusing bibliotecatransportusing bibliotecadatausing systemusing systemlinqnamespace bibliotecabusiness public class mantercategoriabo imantercategoriabo public categoriadto getbyidint id categoriadto dto new categoriadto mantercategoriado categoriado new mantercategoriado dto categoriadogetbyid1 return dto public iqueryablecategoriadto getall throw new notimplementedexception public void insertcategoriadto dto throw new notimplementedexception my globalasaxusing systemwebhttpusing systemwebmvcusing systemweboptimizationusing systemwebroutingusing bibliotecadependencynamespace biblioteca note for instructions on enabling iis6 or iis7 classic mode visit public class mvcapplication systemwebhttpapplication protected void application start arearegistrationregisterallareas webapiconfigregisterglobalconfigurationconfiguration filterconfigregisterglobalfiltersglobalfiltersfilters routeconfigregisterroutesroutetableroutes bundleconfigregisterbundlesbundletablebundles below is a static variable to take the unity container which is on a dependency project globalcontainer bootstrapperinitialise my bootstrapper classusing microsoftpracticesunityusing microsoftpracticesunityconfigurationusing systemconfigurationusing systemwebmvcusing unitymvc4namespace biblioteca public static class bootstrapper public static iunitycontainer initialise var container buildunitycontainer dependencyresolversetresolvernew unitydependencyresolvercontainer return container private static iunitycontainer buildunitycontainer string path configurationmanagerappsettingsunityconfigfilepathtostring var filemap new execonfigurationfilemap execonfigfilename path unityconfig systemconfigurationconfiguration configuration configurationmanageropenmappedexeconfigurationfilemap configurationuserlevelnone var unitysection unityconfigurationsectionconfigurationgetsectionunity this line is firing the error var container new unitycontainerloadconfigurationunitysection return container my dependency project static classusing microsoftpracticesunitynamespace bibliotecadependency public static class global public static iunitycontainer container null public static t resolvet return containerresolvet my ui model class file on mvc 4 project i am using 45 frameworkusing bibliotecacontractsusing bibliotecadependencynamespace bibliotecamodels public class livromodel public void getall if globalcontainer null var categoriabo globalresolveimantercategoriabo categoriabogetbyid1 i think everything is in the right way but i cana t see this di works cause i got an error just in the mapping process in line below on my bootstrapper class buildunitycontainer methodvar container new unitycontainerloadconfigurationunitysectionthe error isthe type name or alias bibliotecacontractsimantercategoriabo could not be resolved please check your configuration file and verify this type namei have double checked all my classes and for me they are ok or is it missing anything i need help cause i have a short time to take care of thisregardsmarcelo,['c#'] +538330,c richeditbox has extremely slow performance 4 minutes loading solved the richeditbox control in c i use vs 2005 has bad performance i load an rtf file of 25 mb with 450 colored lines of text into the control and it takes 4 minutes i load the same rtf into the rtf control in wordpad of windows xp and it loads in 2 secondswordpad performs 120 times faster than my applicationwhat is the reason and how can i fix it,['c#'] +538432,difflibs sequencematcher customized equality i have been trying to create a nested or recursive effect with sequencematcherthe final goal is comparing two sequences both may contain instances of different typesfor example the sequences could bel1 1 foo bar 3l2 1 fo back 2normally sequencematcher will identify only 1 as a common subsequence for l1 and l2i would like sequncematcher to be applied twice for string instances so that foo and fo will be considered equal as well as bar and back and the longest common subsequence will be of length 3 1 foofo barback that is i would like sequencematcher to be more forgiving when comparing string memberswhat i tried doing is write a wrapper for the builtin str classfrom difflib import sequencematcherclass mystring def init self string selfstring string def hash self return hashselfstring def eq self other return sequencematcheraselfstring bselfstringratio 05edit perhaps a more elegant way isclass mystringstr def eq self other return sequencematcheraself botherratio 05by doing this the following is made possible foo mystringfoo fo mystringfo bar mystringbar back mystringback l1 1 foo bar 3 l2 1 fo back 2 sequencematcheral1 bl2ratio075so evidently it is working but i have a bad feeling about overriding the hash functionwhen is the hash used where can it come back and bite mesequencematchers documentation states the followingthis is a flexible class for comparing pairs of sequences of any type so long as the sequence elements are hashableand by definition hashable elements are required to fulfill the following requirementhashable objects which compare equal must have the same hash valuein addition do i need to override cmp as welli would love to hear about other solutions that come to mindthanks,['python'] +538444,getting reference to the view of a container view i am new to ios app development i have connected a tableview controller such that when i select one of the rows i get another uiviewcontroller using didselectrowatindexpath i have a container view inside this uiviewcontroller which thisplays say for the time being index of the row on which didselectrowatindexpath was called i want to do this using a segue but the problem is i do not know how to get a reference to the view controller which is formed by using the container view i know you can get the destination view controller using seguedestinationviewcontroller in the prepareforsegue but how do i get a reference to view controller that will be loaded because of the container view i am building the app for ios 6 also i have used storyboard for the uis thankseditthis question basically comes down to how to get a reference to the uiviewcontroller2 that is being pointed by the uicontainerview which is inside the uiviewcontroller1 the uiviewcontroller1 is triggered by selecting a row of uitableviewcontrolleruitableviewcontroller selecting a row to give uiviewcontroller1 which containscontainerview uiviewcontroller2viewcontroller associated with containerview,"['ios', 'objective-c']" +538464,getting reference to view controller of the container view i have a viewcontroller which contains a containerviewwhich is setting up a viewcontroller i am setting up a segue and in prepareforsegue method i want to get a reference to a viewcontroller which is embedded in the container view how do i do that i know that using seguedestinationviewcontroller we can get a reference to uiviewcontroller but i want to also setup the viewcontroller that is being pointed to by the containerview,['ios'] +538481,defining a html template to append using jquery i have got an array which i am looping through every time a condition is true i want to append a copy of the html code below to a container element with some valueswhere can i put this html to reuse in a smart waya href classlistgroupitem table tr tdimg srctd tdp classlistgroupitemtextptd tr tableajquery searchkeyupfunction listitemshtmlnull eachitems functionindex appending code here,"['javascript', 'jquery']" +538484,angularjs promises q defer editthe first answer is the elegant one but as stated a few times in this question and another questions on stackoverflow the problem is that the service and the controller run their thing before the data actually arrives last comment on the first answeryes the problem is that the api calls finish after the service runs and returns everything to the controller see here screencastcomturkmz1iggpb7 that is my base question how could i wait on all the parts for the data to arriveit is like i am saying it on repeat how do we make a service that populates the array after the successful data retrieval and the controller getting data after all this happens because as you can see in my screenshot things run in a different orderi have this code var deferred qdefer httpgetwordpressapicoreget category postscategory id14 successfunctiondata were emptying the array on every call thedata catname datacategoryslug thedata data thedataname catname aggregateddatapushthedata httpgetwordpressapicoreget category postscategory id15 successfunctiondata thedata catname datacategoryslug thedata data thedataname catname aggregateddatapushthedata httpgetwordpressapicoreget category postscategory id16 successfunctiondata thedata catname datacategoryslug thedata data thedataname catname aggregateddatapushthedata httpgetwordpressapicoreget category postscategory id17 successfunctiondata thedata catname datacategoryslug thedata data thedataname catname aggregateddatapushthedata deferredresolveaggregateddata timeoutfunction deferredresolveaggregateddata 10 deferredrejectthere is a connection problem if myservice initialized rootscopebroadcastpostslist deferredpromise myservice initialized true myservice deferredpromise return deferredpromisefor the life of me i cannot understand why do i have to put a timeout when passing the resulting array to defer should not the principle be like defer waits for the information to come and then returns the promise what is the point of that 1 second there from what i understand defer should be able to wait as long as needed for the api to return the result and the return the promised datai am really confused i have banged my head against the walls for the last two hours because i was not receiving any data in my controller only when i put that timeout there,['javascript'] +538485,how to center and crop an image to square with css i need to always crop a randomsized image to a square 160x160 using only cssthe images should stay centered when croppedmy markup should bea href classcropper img srcimage altdescription asearching on stackoverflow i have found some answers ex this but them does not work for horizontal or vertical imagesi need to be able to transform in a squares bothandwithout know which one is an horizontal rectangle or a vertical rectangle it should also support already squared imagesi have no clues and i cannot neither write some code to try it no idea of where start to write itany suggestion,"['html', 'css']" +538538,cout n 2n or wcout ln 2n whycout n 2nworks well while wcout ln 2ndoes not in qt creator for linux,['c++'] +538611,what is wrong with my checksum algorithm i am doing some practice problems for a competition and i have been working on this algorithm like all day if you want to read the whole problem here it is but i will give you a short explanation because it is kind of a long problemproblemyou have to verify id numbers by plugging the id number into a checksum the id needs to be converted to base10 before you can plug it into the algorithm the id number starts out as lettersz 0 y 1 x 2 w 3 v 4i am not having trouble with the conversion from these letters to base10 my conversion code is good so i will show you the next part of the problempart 2once you have your base10 id number you need to plug it into the following algorithmnote each id number must be 8 digits long 0s will precede a number that is not at least 8 digitschecksum f0 d0 x f1 d1 x f2 d2 so to simplifychecksum fn dn x fn1 dn where and is the index of the digitwhat is most important here is that x is not the operation multiply x is it is own operation defined laternote the most significant digit seems to be d7 but i am not sure the problem is not very clear about ithere are the definitions for fn1 n2 gn and the operator xfn1 n2 gn operator xi assumed mod is the same thing as in my code i was not sure if there was another mod operation i am not familiar withmy structurethis is how i decided i wanted to solve the problemconvert the base10 number into int8put each digit of the int8 through fn dnuse the x operator to then combine them all togethermy codehere are my algorithm functions i can comment them if they are confusing somewhere but they really follow the algorithm listed above exactly this will return the checksum of the id formula f0 d0 x f1 d1 fn dn where and is the current index x multiply x is a defined operator public static int getchecksumint id int result 0 forint x 0x idlengthx ifx 0 result fofxdx idx else result opxresult fofxdx idx return resultpublic static int gofxint x return gofxxpublic static int fofxdint x int d switchx case 0 return d case 1 return gofxd default return fofxdx 1 gofxd public static int opxint num1 int num2 ifnum1 5 num2 5 return num1 num2 5 ifnum1 5 num2 5 return num1 num2 5 5 5 ifnum1 5 num2 5 return num1 5 num2 5 5 return num1 num2 5public static final int gofx 1 5 7 6 2 8 3 0 9 4now here is my mainstring args codenote you can assume the functions parsebase10 and toarray are functioning properly i have checked them with the input output examples in the problempublic static void mainstring args bufferedreader reader new bufferedreadernew inputstreamreadersystemin whiletrue int ids 0 how many ids are we checking try ids integerparseintreaderreadline get user input string list new stringids will hold all of the ids forint x 0x listlengthx listx readerreadline reads all of the ids we will be checking forint x 0x listlengthx lets check the ids individually now string stringid listx the string representation of the id int base10 parsebase10stringid int id toarraybase10 int checksum getchecksumid systemoutprintlnstringid systemoutprintlnbase10 systemoutprintlnarraystostringid systemoutprintlnchecksum catchexception eeprintstacktrace break want to compile it yourselfhere is my full unedited codeimport javaiobufferedreaderimport javaioinputstreamreaderimport javautilarrayspublic class main public static void mainstring args bufferedreader reader new bufferedreadernew inputstreamreadersystemin whiletrue int ids 0 how many ids are we checking try ids integerparseintreaderreadline get user input string list new stringids will hold all of the ids forint x 0x listlengthx listx readerreadline reads all of the ids we will be checking forint x 0x listlengthx lets check the ids individually now string stringid listx the string representation of the id int base10 parsebase10stringid int id toarraybase10 int checksum getchecksumid systemoutprintlnstringid systemoutprintlnbase10 systemoutprintlnarraystostringid systemoutprintlnchecksum catchexception eeprintstacktrace break this will return the checksum of the id formula f0 d0 x f1 d1 fn dn where and is the current index x multiply x is a defined operator public static int getchecksumint id int result 0 forint x 0x idlengthx ifx 0 result fofxdx idx else result opxresult fofxdx idx return result public static int gofxint x return gofxx public static int fofxdint x int d switchx case 0 return d case 1 return gofxd default return fofxdx 1 gofxd public static int opxint num1 int num2 ifnum1 5 num2 5 return num1 num2 5 ifnum1 5 num2 5 return num1 num2 5 5 5 ifnum1 5 num2 5 return num1 5 num2 5 5 return num1 num2 5 this will convert a number to an array equivalent of that number the result will be 8 digites long with leading 0s if possible ex 12345 0 0 1 2 3 4 5 6 public static int toarrayint value int result new int8 forint x resultlength 1x 0x resultx value 10 value 10 return result converts a string sequence and converts it to a base 10 equivalent z 0 y 1 x 2 w 3 v 4 ex yy 11base5 6base10 public static int parsebase10string string throws exception int multiplier 1 int result 0 in base 10 forint x stringlength 1x 0x char letter stringcharatx the letter we are parsing int value 1 initial value set to 1 to check for parsing error forint y 0y valueslengthy ifletter valuesy value y letter found in values ifvalue 1 throw new exceptioncould not parse letter the specified letter was not found result multiplier value this moves the value to the correct digit place by using a multiplier ex current result 45 base10 new value to parse 2 base5 45base10 2base5 25base10 245 correct output multiplier 5 sets up multiplier for next value return result public static final char values z y x w v public static final int gofx 1 5 7 6 2 8 3 0 9 4here is the input i am giving my problem6 wyyxwvzxx ywywyyxwvzyy ywywyyxwvzyx yyzwyyxwvzyx yxxwyyxwvzxw xyxwyyxwxyyhere is what i getwyyxwvzxx12742620 1 2 7 4 2 6 22 0ywywyyxwvzyy813523818 1 3 5 2 3 8 10ywywyyxwvzyx813523828 1 3 5 2 3 8 24yyzwyyxwvzyx598680075 9 8 6 8 0 0 70yxxwyyxwvzxw7353987 3 5 3 9 8 8 85 0xyxwyyxwxyy225204312 2 5 2 0 4 3 13 0where you see the 0s is where i am supposed to be getting 0 but i am getting a different value where is my checksum algorithm messing upreading all of that feel free to ask for clarification on any part of my code,['java'] +538629,border around tr element does not show it seems like chromefirefox do not render borders on tr but it renders the border if the selector is table tr tdhow can i set a border on a tr my try which does not workhtmltable tbody tr td text td tr tbodytablecsstable tr border1px solid blackthis is a similar question set border to table tr works in everything except ie 6 7 but it seems to work everywhere except for ie,"['html', 'css']" +538630,when to catch the exception vs when to throw the exceptions i have been coding in java for a while now but sometimes i do not understand when i should throw the exception and when should i catch the exception i am working on a project in which there are lot of methods the hierarchy is something like thismethod a will call method b and method b will call some method c and method c will call method d and method eso currently what i am doing is i am throwing exceptions in all the methods and catching it in method a and then logging as an errorbut i am not sure whether this will be the right way to do it or should i start catching exceptions in all the methods so that is why this confusion started in my when should i catch the exception vs when should i throw the exceptions i know it is a silly question but somehow i am struggling to understand this major conceptcan someone give me a detailed example of when to catch the exception vs when to throw the exceptions so that my concepts gets cleared on this and in my case should i keep on throwing the exception and then catch it in the main calling method a,['java'] +538666,is c list allocated in contiguous memory if i declare a list of char arrays are they allocated in contiguous memory or does net create a linked list insteadif it is not contiguous is there a way i can declare a contiguous list of char arrays the size of the char arrays is know ahead of time and is fixed they are all the same size,['c#'] +538680,can foreign key refer to primary key in same table i just think that the answer is false because foreign key does not have uniqueness propertybut some people said that it can be in case of self joining the tablei am new to sql if its true please explain how and why employee table e id e name e sala d id 1 tom 50k a 2 billy 15k a 3 bucky 15k b department table d id d name a x b y now d id is foreign key so how it can be primary key and explain something about join what is its use,['sql'] +538691,write and read php object in a text file i want to write a php object in a text file the php object is like that obj new stdclass objname my name objbirthdate ymmdd objposition my positioni want to write this obj in a text file the text file is located in this pathfilepath getcwddirectory separatornotedirectory separatornoticetxti want a simple way to write this object into the text file and want to read the file to get the properties as i defined please help methanks in advance,['php'] +538711,compress images to reduce file size i am building an app that lets the user take a photo or select one from the library on the iphone and upload it to the parse backendthe problem i am facing is regarding to the size of the filei have read about what big players like facebook twitter instagram and google do regarding resolution and file size but i cannot get close to thati am sure they have the best code and tools to do that but i will be happy to implement it as good as possible with ios regular processesthis is what i am doing right now uiimage normalresimageforassetalassetasset convert alasset to uiimage uiimage image self highresimageforassetasset determine output size cgfloat maxsize 10240f cgfloat width imagesizewidth cgfloat height imagesizeheight cgfloat newwidth width cgfloat newheight height if any side exceeds the maximun size reduce the greater side to 1200px and proportionately the other one if width maxsize height maxsize if width height newwidth maxsize newheight heightmaxsizewidth else newheight maxsize newwidth widthmaxsizeheight resize the image cgsize newsize cgsizemakenewwidth newheight uigraphicsbeginimagecontextnewsize image drawinrectcgrectmake00newsizewidthnewsizeheight uiimage newimage uigraphicsgetimagefromcurrentimagecontext uigraphicsendimagecontext set maximun compression in order to decrease file size and enable faster uploads downloads nsdata imagedata uiimagejpegrepresentationnewimage 00f uiimage processedimage uiimage imagewithdataimagedata return processedimagei am trying to make 1024px the maximun allowed size both with ot height to start some restrictions there and then i am applying maximun compression to reduce sizethis works and cuts aproximately 50 of the image size without really damaging jpegs but it is still a lot specially if photos are taken with the phones camera and uploaded the processed image can still easly have 1mb size which is way too muchi am guessing that i could be missing some useful step or using the wrong technique any feedback would be greatly appreciated,['ios'] +538715,a hundred contexts vs one context in html5 canvas i am creating a simple physics engine working with the canvas api what is the best practice in terms of performance is it to create a separate context for ever object in the canvas ex for every ball box etc or to use just one context the latter involves defining the path on the context for every object to be redrawn plus setting the color etcis it a bad idea to use multiple contexts when the number of objects get near a hundredthe reason why i ask is because i do not want to get a surprise a hundred working hours later because i went with the wrong way of doing this,['javascript'] +538756,like and null in where clause in sql i have a store procedure which i have planned to use for search and get all valuesscenarioif the parameter passed is null it should return all the values of the table and if the parameter passed is not null it should return the values according to the condition which is in likequeryalter procedure dbousp getallcustomerdetailskeyword nvarchar20 nullasbeginselect customeridcustomernamecustomertypenamecustomercodecategorynamecustomermobilecustomeremailcustomeraddresscustomercitycustomerstatepincodefrom tblcustomermaster cminner join dbotblcustomertypemaster ctm on ctmcustomertypeid cmcustomertypeinner join dbotblcategorymaster ccm on ccmcategoryid cmcustomercategorywhere customername like keyword in the above query it returns no values when i execute since the null is assumed as string by sql so what should i write in the where clause to get the desired output,['sql'] +538757,how to prepend classmethods this question directly relates to this one but i tried to break it down to the base problem and i did not want to enter even more text into the other question box so here goesi know that i can include classmethods by extending the module classmethods and including it via the moduleinclude hook but can i do the same with prepend here is my exampleclass fooclass foo def selfbar base bar endend class extensionsmodule extensions module classmethods def bar extended bar end end def selfprependedbase baseextendclassmethods endend prepend the extension foosendprepend extensionsclass fooerequire fooclass fooe fooendand a simple startscriptrequire pryrequire fooerequire extensionsputs fooebarwhen i start the script i do not get extended bar like i expect but rather base bar what do i need to change in order to work properly,['ruby'] +538760,docker supervisord and logging how to consolidate logs in docker logs so experimenting with docker supervisord django app via uwsgi i have the whole stack working fine but need to tidy up the loggingif i launch supervisor in nondaemon modeusrbinsupervisord nthen i get the logging output for supervisor played into the docker logs stdout however if supervisord is in daemon mode its own logs get stashed away in the container filesystem and the logs of its applications do too in their own app stderrstdout fileswhat i want is to log both supervisor and application stdout to the docker log is starting supervisord in nondaemon mode a sensible idea for this or does it cause unintended consequences also how do i get the application logs also played into the docker logs,['python'] +538785,iframe embedded with 100 height in a div has strange bottommargin i want to wrap an iframe element with height 100 and width 100 into a div with fixed sizei tried it like thisdiv styleheight 410px width 480px border 1px solid black overflow auto iframe src styleborder none background blue height100 width100iframediv with older doctypes it works perfectly but as soon as i add the html5 doctype doctype html there is a thisturbing scrollbar which makes it possible to move the whole iframe element up and down inside the surrounding div and if you scroll completely down there is a strange space i cannot explainwhen i remove the overflow auto property from the divstyle it works too but this cannot be the solutionthe thing i do not understand is why there is this strange spacemargin below the iframe elementhere is a demo you can try yourself i tried it in safari 70 and firefox 2301,"['html', 'css']" +538854,reverse a string in python without using reversed or 1 i came across a strange codecademy exercise that required a function that would take a string as input and return it in reverse order the only problem was you could not use the reversed method or the common answer here on stackoverflow 1obviously in the real world of programming one would most likely go with the extended slice method or even using the reversed function but perhaps there is some case where this would not worki present a solution below in qa style in case it is helpful for people in the future,['python'] +538931,why do html entity names with dec 255 not require semicolon in a plain html document pound dec 163 renders as a without needing the whereas oelig dec 339 will only render a a with the semicolon it seems that every html entity with a decimal value under 255 will render without needing the semicolon both in firefox and chromewhat gives,['html'] +538980,how to generate and prompt to save a file from content in the client browser i have a situation where i need to give my users the option to save some data stored locally in their client memory to thisk the current workaround i have is having a handler like thisdefinehandler downloaddeck deck json setf headerout contenttype applicationjson headerout contentthisposition attachment deckwhich does exactly what it looks like the client sends their data up and saves the returned file locally this seems stupidplease please tell me there is a better simpler crossbrowser way to let a client save some local data to their thisk with a filesave dialog box every answer i read on the subject either says no you cannot save files with javascript or yes there is this one semidocumented piece of the chrome api that might let you do it in three pages,['javascript'] +538992,multiple has many relationships to same model i have a model user that can create postsuser has many postspost belongs to userhowever i want to also allow users to save posts as bookmarks so i added the followingbookmark belongs to post belongs to useruser has many posts has many posts through bookmarkspost belongs to user has many posts through bookmarksthis cannot be right because it is now ambiguous when i do userposts does that refer to the posts the user wrote or the posts the user bookmarkedhow do you get around this problem,['ruby-on-rails'] +539001,how to avoid momentary stretching on autorotation of ios opengl es apps this has been bugging me recently it is quite straightforward to put together an opengl es app that supports both portrait and landscape but during autorotation the system seems to just forcibly stretch the render buffer to the new dimensions once autorotate and then call the usual layoutsubviews resizefromlayer etc so the drawables can be adjusted to the new viewport dimensionsmost apps i have seen that support both portrait and landscape seem to settle for this easy approach but i wonder if i can do betterperhaps i should intercept the autorotation before it happens using uiviewcontrollers usual methods expand once the render buffer to a perfect square of the longest screen size eg 1136px x 1136px on an iphone 5 so that it bleeds off screen perform the autorrotation no renderbuffer size change and hence no stretching just as when you switch between eg two landscape orientations and finally adjust the framebuffer again to thispose the invisible wasted margins off screen of course i could have a square framebuffer all along but that would be inefficient fillratewiseany suggestions any better way to accomplish this that i have not thought aboutediti modified my resizefromlayer code as followscgrect bounds layer bounds enlarge layer to square of the longest sideif boundssizewidth boundssizeheight boundssizewidth boundssizeheightelse boundssizeheight boundssizewidthlayer setboundsbounds adjust size to match views layer maincontext renderbufferstoragegl renderbuffer fromdrawablecaeagllayer view layer query the new sizeglgetrenderbufferparameterivgl renderbuffer gl renderbuffer width backingwidthglgetrenderbufferparameterivgl renderbuffer gl renderbuffer height backingheight etc you know the drilland it works as it stands right now i have a wasteful offscreenbleeding square renderbuffer all along but this is just a proof of concept on production code i would perform said resizingtosquare just before autorotation and resize back to screen dimensions afterwards,['ios'] +539048,nodejs post causes error socket hang up code econnreset i created a sample to post data to a rest services and i found out that when i have nonascii or nonlatin character please see datafirstname my post request using testrestjs will throw error error socket hang up code econnreset testrestjsvar http requirehttpvar data jsonstringify firstname joaquanvar options host 127001 port 30 path users method post headers contenttype applicationjson contentlength datalength var req httprequestoptions functionres var result resondata functionchunk result chunk resonend function consolelogresult reqonerror functionerr consolelogereqwritedatareqendand on my rest services it throw me error like thissyntaxerror unexpected end of input sun sep 08 2013 232502 gmt0700 pdt at objectparse native at incomingmessageanonymous volumesdataprogram datagithubappnode modulesexpressnode modulesconnectlibmiddlewarejsonjs6627 info at incomingmessageeventemitteremit eventsjs9217 at stream readablejs92016 mon 09 sep 2013 062502 gmt post users http11 400 at process tickdomaincallback nodejs45913if i replace firstname value from joaquan to abc everything works just fine i think i am missing something to support or escape to make it workdoes anyone have any idea how i solve this problem i also tried following requirequerystringescapemodelgivenname and it works but i am not happy with itupdatedi found out that if i comment out appuseexpressbodyparser the error thisappears,['javascript'] +539099,good reason for third argument to stdaccumulate i just wrote a small helper function as a wrapper of stdaccumulatetemplate typename fwditer inlineauto accumulatefwditer begin fwditer end stditerator traitsfwditervalue type return stdaccumulatebegin end stditerator traitsfwditervalue typei am probably overlooking something here why is not this an existing overload of stdaccumulate the function appears so obvious that it cannot have been overlooked someone had a good reason to make that third parameter mandatorysee also understanding stdaccumulate i understand why you want the ability to provide an initial value i just do not understand why it is mandatory,['c++'] +539146,iterating over a list modifying each element is there a faster method i have an list of strings and i would like to trim each element of the listcurrently i am using an arraylist doing a simple loop through the elements and adding the trimmed element to a return list like soint listlen listtotrimsizeliststring trimmedlist new arrayliststring listlen for int i 0 i listlen i trimmedlistadd listtotrimget i trim return trimmedlistfor large lists would there be a more efficient way of doing this,['java'] +539160,merging duplicate elements within an ienumerable i currently have an ienumerablemyobject where myobject has the properties string name and long value if i was to have within the enumerable 10 instances of myobject each with a different name and value with the exception of one having the same name as the otherdoes net or linq have a built in method which will allow me to find the duplicate and if possible merge the value property so that there ends up being only 9 elements within the enumerable each with a thistinct name and the one that had a duplicate has the value that is equal to the sum of its self and the duplicateso far i have found that the only way to iterate over the entire ienumerable and look for the duplicates and generate a new ienumerable of unique items but this seems untidy and slow,"['c#', '.net']" +539228,priority between properties in hibernatejpavendoradapter and jpaproperty i have the following configuration in an application spring jpa hibernate using packagestoscan to avoid having file persistencexml configure jpa implementation bean idjpavendoradapter classorgspringframeworkormjpavendorhibernatejpavendoradapter property namedatabase valuejpadatabase property nameshowsql valuejpashowsql property namedatabaseplatform valuejpadialect property namegenerateddl valuejpagenerateddl bean create the jpa entitymanagerfactory bean identitymanagerfactory classorgspringframeworkormjpalocalcontainerentitymanagerfactorybean property namedatasource refdatasource property namejpavendoradapter refjpavendoradapter property namepackagestoscan list valuecomproyectofinalmodelvalue list property property namejpaproperty props entry keyhibernatecacheuse second level cache valuetrue entry keyhibernatecacheuse query cache valuetrue entry keyhibernatecacheprovider class valuenetsfehcachehibernatesingletonehcacheprovider entry keyhibernateshow sql valuetrue entry keyhibernateuse sql comments valuefalse entry keyhibernateformat sql valuetrue entry keyhibernatedialect valueorghibernatedialectmysqldialect entry keyhibernatetempuse jdbc metadata defaults valuefalse props property beanmy question isis it necessary define in both places properties like show sql or dialectwhich one has priority over the otherwhat place is more appropriate to define itthanks in advance,['java'] +539264,inheriting default combobox to change border color or thisable it i am working in a winforms projecti have a dark theme activated in windows and this is a default combobox when it is focusedand this is when it has no focusan horrible and insane white border appears when the control lost focus i want to avoid that without thisabling xp styles in the projecti know that maybe the only way is inheriting the control to make my own the problem is i do not know what i need to do with the control maybe changing a setstyle property or i do not know,"['c#', '.net']" +539319,can i use non existing css classes i have a table where i showhide a full column by jquery via a css class that does not existtable thead tr thth th classtargetth thth tr thead tbody tr tdtd td classtargettd tdtd tr tr tdtd td classtargettd tdtd tr tbodytablewith this dom i can do this in one line via jquery targetcssthisplaynonethis works perfectly but is it valid to use css classes that are not defined should i create an empty class for itstyletargetstyleare there any side effects or is there a better way to do this,"['html', 'css']" +539342,return results from multiple models with django rest framework i have three models a articles authors and tweets i am ultimately needing to use django rest framework to construct a feed that aggregates all the objects using the article and tweet models into one reverse chronological feedany idea how i would do that i get the feeling i need to create a new serializer but i am really not surethanksedit heres what i have done thus farappserializerspyclass timelineserializerserializersserializer pk serializersfield title serializerscharfield author serializersrelatedfield pub date serializersdatetimefieldappviewspyclass timelineviewsetviewsetsmodelviewset api endpoint that lists all tweetarticle objects in revchrono queryset itertoolschaintweetobjectsall articleobjectsall serializer class timelineserializer,['python'] +539367,header files in c i have been reading about c for a while now and decided lets write a little add program nothing fancy at all my understanding of c headers is that they are interfaces such as like java and other languages but where you can also define variable that either have set values or notso i wrote thisinclude stdiohinclude stdlibhinclude samplehint mainint argc char argv printfhello worldn add12 18 return exit successint addint a int b int value ab printfvalue dn value return 0it has a header file that looks like suchifndef sample h guarddefine sample h guardint addint a int bendifi thought header files and this is where i am lost on their definition was suppose to define the use of add so all i would have to do is call add from my understanding i define the rules of add and then implement the functionality of addalso a lot of the material i have read shows one header file for multiple c files where as a lot of projects today have one header per one c meaning sampleh belongs to samplec and nothing elsecan some one shed some light on thiscould i have done this like somaincinclude stdiohinclude stdlibhinclude samplehint mainint argc char argv printfhello worldn add12 18 return exit successaddcinclude stdiohinclude stdlibhinclude samplehint addint a int b int value ab printfvalue dn value return 0samplehifndef sample h guarddefine sample h guardint addint a int bendifi believe in the book i was reading c programming language they had a calculator example split up like this my question is how does c know where add is defined it knows the rules for it based on the header file i think but not where the actual implementation is there example where they split of the files like such doe not have something like include addc all they do is include the header file in the files that either implement or use this functionalitynote obviously the calculator example and my example are going to be different but fundamentally the same for those who have the book i am just lost on how to use header files effectively and efficiently,['c'] +539402,what does force true mean in the schema file if you look in dbschemarb you will see something likecreate table users force true do twhat does the force true mean,['ruby-on-rails'] +539428,wamp server errors switching apache php versions on fresh install a fresh download and install of wamp server works successfully apache 244 php 5412however as soon as i install a different version of apache in this case 24 to 20 so i can run php 52 54 wamp goes offline with an orange iconif i try to switch back to the original apache version i get this showstopping errorsorrythis apache version does not seem to be compatible with your actual php versionswitch cancelledpress enter to continuethis does not make any sense as this is a fresh install so both the apache php versions are the defaultsheres what the ui is telling methe wamp icon is now orangethe apacheversion244 icon has a red warning icon next to itthe apacheversion2063 icon has a tick next to iti have tried installing other versions of apache too but the issue seems to be with the base 24 wamp installed optionsextra info port 80 is free and i used to use ws 20e all the time without these kinds of issuesthanksdave,['php'] +539488,java hashset vs array performance i have a collection of objects that are guaranteed to be thistinct in particular indexed by a unique integer id i also know exactly how many of them there are and the number would not change and was wondering whether array would have a notable performance advantage over hashset for storingretrieving said elementson paper array guarantees constant time insertion since i know the size ahead of time and retrieval but the code for hashset looks much cleaner and adds some flexibility so i am wondering if i am losing anything performancewise using it at least theoretically,['java'] +539492,what could cause a sudden classnotfoundexception in a long running process we have a very small web service less than 1k lines of code which is run by jetty the service worked always fine even during our stress testing phase however after 13 days of uptime we experienced a classnotfoundexception in two nodes the same day the strange thing is that the class that was not found was already there it is part of the startup routine and it was used constantly servicing previous requests in fact simply restarting the process solved the issue both nodes are in separate machines and are independent of each other they do not depend on external resources except on one jms connection i could not find relevant information while googling this as most of the reported issues are related to missing classes in the class path while starting up the java process which is not our case we suspect there could be a memory leak that in a way corrupted the jvm memory however this cannot explain why the same problem happened in two nodes around the same time weve been running intensive stress testing during the last five days attaching a jvm monitor and a memory leak analyzer and everything seems fine for this tests we decreased the process memory from 2gb to 512mbdetailsusing java hotspottm 64bit server vm build 163b01 mixed modeusing jettyrunner810rc5jar original cmd line java xmx2048m jar jettyrunner810rc5jar port 50 webappwar intel xeon e52680 8 cores x2 16gb ram red hat enterprise linux 6some frameworks in use jboss resteasy spring ioc guavacan you please contribute with ideas regarding what could make the jvm to suddenly forget about the existence of a previously loaded class not being able to load it againcaused by javalangclassnotfoundexception comabcsomeclass at javaneturlclassloader1runurlclassloaderjava202 na160 37 at javasecurityaccesscontrollerdoprivilegednative method na160 37 at javaneturlclassloaderfindclassurlclassloaderjava190 na160 37 at javalangclassloaderloadclassclassloaderjava306 na160 37 at sunmisclauncherappclassloaderloadclasslauncherjava301 na160 37 at javalangclassloaderloadclassclassloaderjava247 na160 37 at orgeclipsejettywebappwebappclassloaderloadclasswebappclassloaderjava424 nana at orgeclipsejettywebappwebappclassloaderloadclasswebappclassloaderjava377 nana at javalangclassforname0native method na160 37 at javalangclassfornameclassjava247 na160 37 at sunreflectgenericsfactorycorereflectionfactorymakenamedtypecorereflectionfactoryjava95 na160 37 at sunreflectgenericsvisitorreifiervisitclasstypesignaturereifierjava107 na160 37 at sunreflectgenericstreeclasstypesignatureacceptclasstypesignaturejava31 na160 37 at sunreflectannotationannotationparserparsesigannotationparserjava370 na160 37 at sunreflectannotationannotationparserparseclassvalueannotationparserjava351 na160 37 at sunreflectannotationannotationparserparsemembervalueannotationparserjava280 na160 37 at sunreflectannotationannotationparserparseannotationannotationparserjava2 na160 37 at sunreflectannotationannotationparserparseannotations2annotationparserjava69 na160 37 at sunreflectannotationannotationparserparseannotationsannotationparserjava52 na160 37 at javalangreflectfielddeclaredannotationsfieldjava1014 na160 37 at javalangreflectfieldgetdeclaredannotationsfieldjava1007 na160 37editsomeone mentioned me that while using nfs mounts under win it could happen that the jvm decides to unload a class and then reloads it when it is needed if in the middle of this process the nfs connection was broken the file handle will be invalid and the reloading will fail with a similar stacktrace in our case we are using linux and all the involved files are in the same mount which is a local hard thisk just for the sake of more testing i have cdd into the jetty temporary directory and manually deleted one well known for one specific service class if the jvm unloads it and then attempts to reload it from the classes directory it will fail while this does not explain the original problem it might put more information on the table,['java'] +539499,ios push notifications uiapplicationstateinactive and fast app switching according to the apple docs in order to find out if a user tapped on your push notification you are supposed to check the applicationstate in applicationdidreceiveremotenotificationif the value is uiapplicationstateinactive the user tapped the action button if the value is uiapplicationstateactive the application was frontmost when it received the notificationi have found that this is not always true for exampledoubletap the home button to reveal the system tray and enter fast app switching mode your application slides up to reveal other running applications and your app is put into the inactive state even though it is still mostyle visible if you receive a push notification in this mode your app delegate will still receive the applicationdidreceiveremotenotification and at this point your applicationstate is uiapplicationstateactive according to the docs you should treat it like the user tapped the alert but in this case they did not not only that the user did not even see the push notification possibly because the top of your application is cut off in this modedoes anyone know of a way to detect being in fast app switching mode or handle the notification correctly,['ios'] +539524,java operator so i was testing out operators because im helping my friend with java and i stumbled across a weird order of programming what is happening when i run the following codepublic static void mainstring args int b 6 first console print out systemoutprintlnbb systemoutprintlnb b 6 second console print out systemoutprintlnbb systemoutprintlnbthe output for the following code is131312 12what causes the second console b math output 12 when it adds 6 to itself followed by which is 1,['java'] +539528,bulk insert list values with sqlalchemy core i would like to bulk insert a list of strings into a mysql database with sqlalchemy coreengine create enginemysqlmysqlconnectormeta metadatametabind enginemy table layout looks like this together with two currently unused columns irrelevant12mytabe tablemytable metacolumnid integer primary keytrue columncolor textcolumnirrelevant1 textcolumnirrelevant2 textunfortunately the following does not work it inserts an empty row whats the right way to do thismytableinsertexecuteblue red green,"['python', 'mysql']" +539571,placeholder vs dataplaceholder in html whats the difference between the twoplaceholder vs dataplaceholderthey both seem to produce the same results select dataplaceholderenter nameselect placeholderenter namewhats the differencewhich ones stronger,['html'] +539588,azure data transfer identity column seed jumped by 10 after inserting the data via sql scriptthat had set identity insert dbotable onset identity insert dbotable offthe identity seed has increased by 10i have tried running reseeddbcc checkident vendors reseed 57439but i get the error saying the dbcc command checkident is not supported in this version of sql serverhow to stop in the future this problem,['sql'] +539653,how can i change the winston log format in my node application i am using winston module to store my application logs we can store the the logs in two format one is json and the other one is string while saving the log as string in winston i am getting below log format 20130910t065134199z error error message timestamp level log messagenow i want change the above log format to the following 20130910t065134199zerrorerror message timestamp level log messagehow can this be achievedmy code var winston requirewinston winstonloggersaddcategory1 file filename pathtosomefilejsonfalse var category1 winstonloggersgetcategory1 category1logerrorerror message,['javascript'] +539682,extend androidutillog to write to file i would like to extend the androidutillog class to also write to a log file in internal storage of the device preferrably also for specific tagsi currently have an implementationpublic class customloggerprivate final static logger filelog loggergetloggermainactivityclassprivate context contextpublic customloggercontext c thiscontext c final logconfigurator logconfigurator new logconfigurator logconfiguratorsetfilenamecontextgetfilesdir fileseparator myapplog logconfiguratorsetrootlevelleveldebug logconfiguratorsetlevelorgapache levelerror logconfiguratorconfigurepublic void istring tag string message printing the message to logcat console logitag message write the log message to the file fileloginfotag messagepublic void dstring tag string message logdtag message filelogdebugtag message as you can see this custom logger logs both to a log file on the internal storage using the androidlogginglog4j library and through the androidutillog class however i would like the standard log entries from the androidutillog class in my log file and if possible only certain custom tagsanybody has an example or any good tips on how to reach thisthanks in advance,['android'] +539690,java bigdecimal can have comma instead dot i have a string value that i want to assign to a bigdecimal when i update the decimal value with a number like 10023 it works fine but when i update it with a number like 10023 the code throws an exception why is that,['java'] +539820,keep list of foreign keys in manytomany entity framework relationship i have a manytomany relationship in my codefirst entity framework model imagine we have two tables company and article that have such relationship in between my simplified code model looks like the followingpublic class article public int id get set public string text get set public virtual icollectioncompany companies get set public class company public int id get set public string name get set public virtual icollectionarticle articles get set using fluent mapping i create manytomany relationshipmodelbuilderentitycompanyhasmanyc carticleswithmanya acompaniesthis works fine ef creates intermediate table but according to my logic it would be very nice to have a collection of foreign keys together with each entity it means i would like to add the following property to corresponding model classespublic virtual icollectionint articlesid get set to companypublic virtual icollectionint companiesid get set to articlei know that one workaround solution is to create intermediate tables model in ef and manually select appropriate ids in every call but maybe ef mapping can provide more convenient way to do such operation thank you in advance for any tips,['c#'] +539833,angular link function scope vs scope in angular directives i have seen in tutorials either link functionscopeelementattrsor link functionscopeelementattrsnow i know that the means a service in angular does this hold here what exactly is the difference between scope and scope same goes to element vs element,['javascript'] +539853,one to zeroorone with hasforeignkey i have two modelspublic class person public virtual int id get set public virtual employee employee get set optionalpublic class employee public virtual int id get set public virtual int personid get set public virtual person person get set requiredpublic class employeeconfiguration entitytypeconfigurationemployee public employeeconfiguration propertyeepersonid i need this property mapped hascolumnnameperson id hascolumntypeint i want to map them using fluent mapping employee table has column person id which is nonnullable i tried followinghasrequirede eperson withoptionalp pemployee mapm mmapkeyperson idbut it fails withsystemdataentitymodelconfigurationmodelvalidationexception one or more validation errors were detected during model generationperson id name each property name in a type must be unique property name person id is already definedi need personid property on its own so what i basically want ishasrequirede eperson withoptionalp pemployee hasforeignkeye epersonid there is no such methodbut there is no such method here as hasforeignkey,['c#'] +539919,parameter count mismatch exception when calling propertyinfogetvalue i am trying to compare two objects at runtime using reflection to loop through their properties using the following methodprivate sub compareobjectsobj1 as object obj2 as object dim objtype1 as type obj1gettype dim propertyinfo objtype1getproperties for each prop as propertyinfo in propertyinfo if propgetvalueobj1equalspropgetvalueobj2 then log difference here end if nextend subwhenever i test this method i am getting a parameter count mismatch exception from systemreflectionruntimemethodinfoinvokeargumentscheck when it calls propgetvalueobj1 this happens no matter the type of obj1 and obj2 nor the type in prop in my test case the first property is a booleanwhat am i doing wrong and how can i fix it so that i can compare the values from the two objectssolutioni added the following lines just inside the for each loopdim paraminfo propgetindexparametersif paraminfocount 0 then continue forthe first property was taking a parameter which was causing the problem for now i will just skip any property that requires a parameter,['.net'] +539943,does a android gcm device id ever change i am building gcm into my app and i want to make sure i do not end up with duplicate device idsis there a best practice for dealing with device ids my original though was when the app loads it calls gcmregister and posts the id to my server and if the key isnt in my database i will store it then when i send out a notification loop through the db and send the messagesbut i as wondering if the id ever changes i do not want to send multiple messages to one device,['android'] +539996,spacing in custom keyboard when making a custom keyboard i can get a leading space space to the left of a key by using androidhorizontalgap625phow do i get trailing space space to the right,['android'] +540029,create a background task in intellij plugin i am developing an intellijidea plugin and want to run code in background task visible in the background tasks dialog and in another thread than the uii found the following helper class and tried it by passing a runnable object and implement its run method but it still blocking the ui and when i tried to do the threading myself i got the following error read access is allowed from event thispatch thread or inside readaction only see comintellijopenapiapplicationapplicationrunreadaction details current thread threadthread69 writeaccesstoken6idea thread group 5324832 our thispatch threadthreadawteventqueue1 1214iu129713 eapfalse6idea thread group 324031064 systemeventqueuethread threadawteventqueue1 1214iu129713 eapfalse6idea thread group 324031064,['java'] +540041,beautifulsoup findall given multiple classes i would like to scrape a list of items from a website and preserve the order that they are presented in these items are organized in a table but they can be one of two different classes in random orderis there any way to provide multiple classes and have beautifulsoup4 find all items which are in any of the given classesi need to achieve what this code does except preserve the order of items as it was in the source codeitems soupfindalltrueclassclass1items soupfindalltrueclassclass2,"['python', 'html']" +540047,using an environment variable in a psql script is it possible to use a linux environment variable inside a sql file i am using the copyselect query to write to an output file and i will like to put that directory in a variable so i want to do something likecopy select from ato outputdiracsvoutputdir would be set in my environment is this possible,['sql'] +540059,embed html5 youtube video without iframe is it possible to embed a an html5 version of a youtube video without using an iframe,"['javascript', 'jquery']" +540091,why is stdtie not marked constexpr for c14 this is a followup question to my previous questions which parts of the c14 standard library could be and which parts will be made constexpr and guidelines to do constexpr operatoroverloadingin the runtime world a nice idiom to overload operator for a struct of several data members is to use stdtie to convert a struct into a stdtuple and piggyback on its operator which does the right thingTM lexicographic comparison on the various membersin c14 many parts of stdtuple are made constexpr in particular make tuple stdget and the earlier mentioned operator however it appears that the seemingly related stdtie is not marked constexpr this is rather annoying because it makes defining userdefined literal types that can be compared at compiletime more verbose than necessaryquestion are there any technical reasons for which stdtie is not marked constexpr for c14 update lwg issue 2301 implemented in libc and libstdc bug 65978update2 fixed by jonathanwakely a little over 3 hours after submutting the libstdc bug report,['c++'] +540111,apache shiro using database to read users roles and permissions currently i have a swing app and i want to implement apache shiro in order to authenticate and delegate permissions to certain roles i have already managed myself to read the users from the shiroini file that i have created for tests it looks something like thisusersadmin 123456 administratorroleadministrator however this was just for testing now i need to read the permits from a database so i have stored in a database a table with the info i need and it looks something like thisusers idpasswordusernameuserroles userid rolerolepermission permissionidpermissionroleidi have been trying to understand tutorials that use a jdbc realm however they use web applications or specials frameworks to manage their connection to the database like apache derby or bonecp and they confuse me even more with these examplesso what i am asking it is how i need to configure the shiroini file if i wanna use a jdbc realm with an oracle database and what classes the shiroini needs any examples or explanation will be appreciated,['java'] +540129,does webrtc work with phonegapcordova edit rephrased my question and titleso if you can tell from the title i am using phonegapcordova and trying to add webrtc to an htmljscss app perfectly works on the desktop browser but not on mobile the reason i ask this question is because i have seen video chat apps on mobileoovooskype but no chat apps in the browser although i am aware webrtc doesnt work on ios but does work on newer versions of chrome but is it possible to run webrtc if i wrap my app in a cordovaphonegap webview and thistribute it as an app because if i can access native components like the camera or accelorometer with phonegap why can i not use video chat with an htmljscss apphas anyone tried this tia,['javascript'] +540141,uialertview addsubview in ios7 adding some controls to uialertview was deprecated in ios7 using addsubview method as i know apple promised to add contentview property ios 7 is released now and i see that this property is not added that is why i search for some custom solution with ability to add progress bar to this alertview something for example similar to tsalertview but more ready for using in ios 7,"['ios', 'objective-c']" +540152,what is the difference between pycod and pyc in gitignore notation what is the difference if any between pyc and pycod notation in ignoring files i am noticing i have both on my git ignore file thanks,['python'] +540178,difference between executorsubmit and executorexecute in this code in java i am learning to use exectorservices to pool threads and send out tasks i have a simple program belowimport javautilconcurrentexecutorserviceimport javautilconcurrentexecutorsimport javautilconcurrenttimeunitclass processor implements runnable private int id public processorint id thisid id public void run systemoutprintlnstarting id try threadsleep50 catch interruptedexception e systemoutprintlnsorry being interupted good bye systemoutprintlninterrupted threadcurrentthreadgetname eprintstacktrace systemoutprintlncompleted id public class executorexample public static void mainstring args boolean iscompletedfalse executorservice executor executorsnewfixedthreadpool2 forint i0 i5 i executorexecutenew processori executor does not accept any more tasks but the submitted tasks continue executorshutdown systemoutprintlnall tasks submitted try wait for the exectutor to terminate normally which will return true if timeout happens returns false but this does not interrupt the threads iscompletedexecutorawaittermination100 timeunitseconds this will interrupt thread it manages catch the interrupted exception in the threads if not threads will run forever and executor will never be able to shutdown executorshutdownnow catch interruptedexception e if iscompleted systemoutprintlnall tasks completed else systemoutprintlntimeout threadcurrentthreadgetname it does nothing fancy but creates two threads and submits 5 tasks in total after each thread completes its task it takes the next onein the code above i use executorsubmit i also changed to executorexecute but i do not see any difference in the output in what way are the submit and execute methods differentthis what the api saysmethod submit extends base method executorexecutejavalangrunnable by creating and returning a future that can be used to cancel execution andor wait for completion methods invokeany and invokeall perform the most commonly useful forms of bulk execution executing a collection of tasks and then waiting for at least one or all to complete class executorcompletionservice can be used to write customized variants of these methodsbut its not clear to me as what it exactly meansthanks,['java'] +540190,create dynamic queues with celery heres my scenariowhen a user logs in to my website i queue up a bunch of tasks for the given user typically each task takes 100s of msecs and there are 100s of tasks per user these tasks are queued to the default celery queue and i have 100s of workers running i use websockets to show the user realtime progress as the tasks complete on the backend life is good if i have just 1 or 2 users activenow if i a few concurrent users login to my site the latter users are queued behind the initial users and their tasks starve since all the tasks go to the same queue my thoughts are to create a dynamic queue per user to ensure fairness however as per celery documentation seems i need to be define the queues staticallyany suggestions on best practices for using celery for my scenario,['python'] +540212,ora06502 plsql numeric or value error character string buffer too small i tried the following code different ways like by taking out the while or the if but when i put both together if and while i always get the error at the endundefine numeroset serveroutput onaccept numero prompt type between 100 and 9 declare i number1 a char25 b char1 c varchar210 d numberbegin c numero d lengthc b substrc i 1 while i d loop if b 1 then a aone end if i i1 end loop dbms outputput linethe number is aenderrorora06502 plsql numeric or value error character string buffer too smallora06512 at line 1306502 0 plsql numeric or value errorsfixed by changing how i declared the variable a toa varchar220,['sql'] +540221,detect if angular dependencies angularroute angularresource etc are loaded for cdn fallback i am using angular js on aspnet mvc 4 and i am using script bundles to load from a cdn and also load from the origin server in case of a cdn failure like sovar jquery new scriptbundlebundlesscriptsjquery ajaxgoogleapiscomajaxlibsjquery203jqueryminjs cdn includescriptsjqueryversionjs local fallbackjquerycdnfallbackexpression windowjquery test existencebundlesaddjqueryandvar angular new scriptbundlebundlesscriptsangular ajaxgoogleapiscomajaxlibsangularjs120rc2angularminjs includescriptsangularjsangularcdnfallbackexpression windowangularbundlesaddangularit is fairly easy to detect if jquery or angularjs exist using windowjquery and windowangular respectively the aspnet bundling mechanism evaluates the cdnfallbackexpression text to see if it needs to fall back to the origin serverhowever in later versions of angularjs other modules such as ngroute and ngresource are separated into their own files to be loaded at the developers thiscretionhow do i detect if other angularjs modules are loaded what could i type in the console to see if nganimate ngroute ngresource etc succeeded in loading from the cdn,['javascript'] +540236,installing numpy on amazon ec2 i am having trouble installing numpy on an amazon ec2 server i have tried using easy install pip pip inside a virtual env pip inside another virtual env using python 27 every time i try it fails with the error gcc internal compiler error killed program cc1 and then further down the line i get a bunch of python errors with easy install i get importerror no module named numpythistutils and with pip i get unicodedecodeerror ascii codec cannot decode byte 0xe2 in position 72 ordinal not in range128 the ec2 instance is running kernel 34434343amzn1x86 64 has anybody solved this problem numpy has always been hard for me to install but i can usually figure it out at this point i do not care whether it is in it is own virtualenv i just want to get it installed,['python'] +540249,why does visual studio increment the loop pointer before dereferencing it i checked out visual studio 2012s assembly output from the following simd code float end arr sz float b otherarr for float a arr a end a 4 b 4 m128 ax mm load psa m128 bx mm load psb ax mm add psax bx mm store psa ax the loop body isll11main movaps xmm1 xmmword ptr eaxecx addps xmm1 xmmword ptr ecx add ecx 16 010h movaps xmmword ptr ecx16 xmm1 cmp ecx edx jb short ll11mainwhy increment ecx by 16 only to subtract 16 when storing to it the next line,['c++'] +540256,ios 7 rewind songs on lock screen using avplayer i havnt found the way how to rewind song from lock screen ios 7 volume slider is available all the buttons work correctly but the upper slider is not availableavplayer is the class i am usingany help is appreciated,"['ios', 'objective-c']" +540277,unknown provider modalprovider i keep receiving this error as i am trying to implement bootstrap modal window what could be the cause of it i have copypasted everything from here,['javascript'] +540302,mvc my url is creating length4 i am creating an mvc4 applicationi have a small issue my code is li idtabheader 2htmlactionlinkcontract contract home new id lnk contract lii am getting urlhttplocalhost2355homecontractlength4i want my url ashttplocalhost2355homecontractmy ruoting is routesmaproute name default url controlleraction defaults new controller home action index id urlparameteroptional if you have answer please help me,['c#'] +540319,bootstrap 3 popover thisplay on hover and on click aka pin a popover making a popover appear with the hover trigger works finemaking a popover appear with the click trigger works finenow how do i go about making the popover appear when the triggering image is hovered over but then if the user clicks on the image cancel the hover and initiate a click toggle in other words hovering shows the popover and clicking pins the popoverthe html is pretty standardliuserspan classglyphicon glyphiconuser relpopover datatriggerclick datacontainerbody dataplacementauto left datacontentbody text dataoriginaltitletitle textspanliand the popover initialization even more boringfunction relpopoverpopover from what i have seen so far it seems likely that the solution is a nice complex set of popovershow popoverhide and popovertoggle calls but my javascript jqueryfoo is not up to the taskedit using the code provided by hajpoj as a base i added a function to listen to the hiddenbspopover event to try to reenable the mouseenter and mouseleave events after triggering the click event but although it does make the hover work again it kills the clickvar btn2 btn2 var entershow function btn2popovershow var exithide function btn2popoverhide btn2popovertrigger manual onmouseenter entershow onmouseleave exithide oneclick function btn2offmouseenter entershow offmouseleave exithide onclick function btn2popovertoggle btn2onhiddenbspopover function btn2onmouseenter entershow onmouseleave exithide,"['javascript', 'jquery']" +540345,converting nsstring to nsdictionary json i have the following data saved as an nsstring key id value content 268 type text key contracttemplateid value content 65 type text i want to convert this data to an nsdictionary containing the key value pairsi am trying first to convert the nsstring to a json objects as follows nsdata data string datausingencodingnsutf8stringencodingid json nsjsonserialization jsonobjectwithdatadata options0 errornilhowever when i try nsstring test json objectforkeyidnslogtest is testi receive the value as null can anyone suggest what is the problem,['objective-c'] +540347,android change color of line below actionbar i want to change the color of the orange line below the actionbari have tried a few things but nothing has helped so farthe current theme on my galaxy s2 is an orange themeso changing the theme also changes the linebut i dona t know how to get access to that line in order to change the color,['android'] +540354,wkhtmltopdf is it possible to merge pdf files using this library wkhtmltopdf is it possible to merge 2 pdf files i need to generate a report and merge the report with some attached documents generation of report is done converting from html to pdf but i need to merge the resulting pdf with some other pdfs,"['php', 'html']" +540395,get xmlenumattribute from enum i have enumpublic enum operation remarks systemxmlserializationxmlenumattribute01 item01 remarks systemxmlserializationxmlenumattribute02 item02 remarks systemxmlserializationxmlenumattribute03 item03 remarks systemxmlserializationxmlenumattribute04 item04how i can get xmlenumattribute valuei am trying at thatvar res operationitem1var result resgettypegetfielditem01getcustomattributestypeofxmlenumattribute true0 as xmlenumattributenamemay be exists better method,['c#'] +540455,rspec any instancestub raises undefined method any instance recorder for for nilnilclass exception here is the class that i am testing contained in foorbclass foo def bar return 2 endendhere is the my test contained in foo specrbrequire foorbdescribe foo do beforeall do puts foo nil fooany instancestubbarand return1 end it should pass this do f foonew fbarshould eq 1 endendi am getting the following outputfalseffailures 1 foo should pass this failureerror fooany instancestubbarand return1 nomethoderror undefined method any instance recorder for for nilnilclass foo specrb6in block 2 levels in top requiredfinished in 0 seconds1 example 1 failurefailed examplesrspec foo specrb9 foo should pass thisi have consulted the doc and the example given is passing on my machine so it is not a problem with the rspec code but it is not giving me any information on what i might be doing wrong the error message is also quite confusing as it is telling me not to call any instance on a nilnilclass but as i proved with my output foo is not nil how am i supposed to call any instancestub on my custom objecti am using ruby 193 and rspec 2145,['ruby'] +540476,compiletime constant thiscrepency update this appears to be a compiler redherring as the following is actually validconst int myint defaultintthe issue lies with datetime not being a valid const not the use of default the main source of the confusion for me was not realising that defaultdatetime is handled specifically in optional parameters and i had arrived at a false conclusion that defaultdatetime was being treated as compiletime constant due to the error message omitting the other possible conditions this is addressed by marcinjuraszek in his answeroriginal questionthis is shamelessly ripped from a comment from marc gravell from this answer to another questionwhy is the following valid no compiler errors defaultdatetime seems to satisfy the compiletime constant requirementpublic static void dosomethingdatetime date defaultdatetime but the following not compiler error constant initializer must be compiletime constantconst datetime mydate defaultdatetime as both appear to want compiletime constants evident if you attempt to provide something like datetimeminvalue to the optional parameter the compiler complains that it is not compiletime constant compiler error default parameter value for date must be a compiletime constantpublic static void dosomethingdatetime date datetimeminvalue what is going on behind the scenes that causes the compiler to treat these differently,['c#'] +540572,emberjs actions call one action from another when wrapped within actions how do you call one action from another action when wrapped within actions in an emberjs controlleroriginal code that uses the now deprecated way to define actionsappjsappindexcontroller emberarraycontrollerextend properties actions actionfoo function thisactionbar actionbar function apphtmldiv classfoo action actionfoo thisdiv classbar action actionbar thishowever with emberjs 100 we get a deprecation warning saying that actions must be put within an actions object within the controller instead of directly within the controller as aboveupdating the code according to recommendationsappjsappindexcontroller emberarraycontrollerextend properties actions actions actionfoo function thisactionbar thisactionbar is undefined thisactionsactionbar thisactions is undefined actionbar function apphtmldiv classfoo action actionfoo thisdiv classbar action actionbar thishowever i find that it is not possible for one function defined within actions to call another as the this object appears to no longer be the controllerhow can i go about doing this,['javascript'] +540595,500 internal server error page in mvc i am trying to set up custom errors for an mvc site i have the 404 page working fine but when testing a server error i get the default messagesorry an error occurred while processing your requestinstead of my custom pagei have set this up in the webconfigcustomerrors modeon defaultredirecterror500 error statuscode404 redirecterror404 error statuscode500 redirecterror500 customerrorsmy error controller is as followspublic class errorcontroller controller actionname404 public actionresult notfound return view actionname500 public actionresult servererror return view i am testing the 500 error page by throwing an exception in one of my viewsactionnamecontactuspublic actionresult contactus throw new dividebyzeroexception return viewwhy is it that only 404 errors are handled how can i thisplay the error page for 500 errors,['c#'] +540611,caching a promise object in angularjs service i want to implement a dynamic loading of a static resource in angularjs using promises the problem i have couple components on page which might or not depends which are thisplayed thus dynamic need to get a static resource from the server once loaded it can be cached for the whole application lifei have implemented this mechanism but i am new to angular and promises and i want to make sure if this is a right solution approachvar data nullvar deferredloaddata nullfunction loaddatapromise if deferredloaddata null return deferredloaddatapromise deferredloaddata qdefer httpgetdatajsonthenfunction res data resdata return deferredloaddataresolve function res return deferredloaddatareject return deferredloaddatapromiseso only one request is made and all next calls to loaddatapromise get back the first made promise it seems to work for request that in the progress or one that already finished some time agobut is it a good solution to cache promises,['javascript'] +540642,how to replace fragment inside viewpager using pageradapter my problemi am using a viewpager to thisplay fragments inside a fragmentactivity viewpager gets fragments from the attached fragmentpageradaptermviewpager viewpager findviewbyidridview pager madapter new homepageradaptergetsupportfragmentmanager mviewpagersetadaptermadaptersuppose viewpager has 3 fragments to thisplay fragment1 fragment2 fragment3 fragment1 is a grid fragment and thisplays a grid fragment2 and fragment3 have their own content to thisplay when the use swipes on the screen viewpager will thisplay the next fragment fragment2 and so onwhat i wantwhat i want is that when an item from the grid thisplayed by fragment1 is clicked fragment1 should be completely replaced with some other fragment say fragment4 this is different fragment and is not returned by the attached adapter user will work on fragment4 and after buttonback click just button iside fragment4 fragment1 with the grid should be thisplayed again meanwhile viewpager should behave the same ie on swipe the next fragment in our case fragment2 will be thisplayedso i just want to get the same behavior as in examplemy questionso is this possible to achieve if yes then how toi would greatly appreciate for your help alexps sorry for my english,['android'] +540647,spring injection into servlet so i have seen this questionspring dependency injection to other instanceand was wondering if my method will work out1 declare beans in my spring application context bean iddatasource destroymethodclose classorgapachecommonsdbcpbasicdatasource property namedriverclassname valuejdbcdriverclassname property nameurl valuejdbcurl property nameusername valuejdbcusername property namepassword valuejdbcpassword property nameinitialsize valuejdbcinitialsize property namevalidationquery valuejdbcvalidationquery property nametestonborrow valuejdbctestonborrow bean bean idapidata classcommydomainapidataapidata property namedatasource refdatasource property nameapilogger refapilogger bean bean idapilogging classcommydomainapidataapilogger property namedatasource refdatasource bean2 override my servlet us init method as shown override public void initservletconfig config throws servletexception superinitconfig applicationcontext ac new classpathxmlapplicationcontextapplicationcontextxml thisapidata apidataacgetbeanapidata thisapilogger apiloggeracgetbeanapilogger will this work or is spring not yet ready to deliver beans to my servlet at this point in the web applications deployment do i have to do something more traditional like putting the beans in webxml,['java'] +540662,passing multiple arguments to consolelog i have a utility function that wraps consolelog with a condition so we only call consolelog if were in the dev environment and consolelog exists console log if environment has debug true or debug initially passed in url metroconlog function return function message if metrositedatadebug metrohashoptionshasownpropertydebug windowconsole message consolelogmessage this has worked very well for normal console logs but i have recently thiscovered the joys of passing more than one argument to consolelog it allows you to prefix a console log with a string so consolelogdebug object outputs the string plus an expandable object whose properties you can inspect how can i change my conlog function to do this i have tried logging out all arguments like thismetroconlog function return function message if metrositedatadebug metrohashoptionshasownpropertydebug windowconsole message consolelogarguments but this outputs the arguments as an array instead of the neat line you get with consolelog you can see the difference in this screenshot can anybody tell me how i can reproduce the original log output,['javascript'] +540697,how to set a default attribute value for a laravel eloquent model if i try declaring a property like thispublic quantity 9it does not work because it is not considered an attribute but merely a property of the model class not only this but also i am blocking access to the actually real and existent quantity attributewhat should i do then,['php'] +540699,intellij idea 12 viewing the call stack i am new to the intellij ide usually work with visual studio and i would like to view the current call stack at a particular breakpoint i have found information on building a call hierarchy but that is not what i am looking for any information on how to view the current call stack would be appreciated,['java'] +540703,storing images in db using django models i am using django for creating one web service and i want that web service to return images i am deciding the basic architecture of my web service what i came up to conclusion after stumbling on google isi should store images in db after encoding them to base64 formattransferring the images would be easy when directly bases64 decoded string is transmittedbut i have one issue how can i store bases64 encoded string in db using django models also if you see any flaw in my basic architecture please guide me i am new to web services and djangothanks,['python'] +540732,how can i have two rows in my table that span multiple columns while still being compatible with bootstrap i am using bootstrap with my web application i am trying to get a table design layout to work while still being able to use bootstraps tablestriped class currently i am using the followingtable thead thidth thnameth thdepartmentth thstartedth thead tbody tr td6td td divjohn doediv div12 sales total 4 march 3 april 12 july 14 augustdiv td tdsalestd tdfeb 12th 2010td tr tbodytablehowever i am wanting the 12 sales total 4 march 3 april 12 july 14 august of the table to appear below john doe sales feb 12th 2010 and not wrap within the column it is in now if i use two separate tr elements to get the layout to work then the tablestriped no longer works properlyeditso here is the current setup this gets what i want except for the issue where the text on the div does not span the other columns and just wraps within the column it is currently in i have tried something earlier that was mentioned in a submitted answer by bryce but this is not compatible with bootstrap it seems,['html'] +540741,ios 7 uinavigationbar with ios 6 style i was developing an app for ios 6 and this is one of my viewsnow i have updated my iphone to ios 7 and this is the resultnow all the views are behind the navigation bar because ios 7 uiviewcontrollers views starts at the top left edge of the screen and not under the uinavigationbar as ios 6now the email field is behind the navigation baris there a way to use the ios 6 stylethanksmarco,['iphone'] +540831,the args and kwds in python super call i am trying to understand the use of args and kwds when creating subclasses in pythoni want to understand why this code behaves the way it does if i leave out the args and kwds in a call to super init i get some strange argument unpackinghere is my test caseclass animalobject def init self moves num legs selfmoves moves selfnum legs num legs def describeself print moves num legs formatselfmoves selfnum legsclass snakeanimal def init self poisonous args kwds selfpoisonous poisonous print i am poisonousformatselfpoisonous this next line is key you have to use args kwds but here i have deliberately used the incorrect form args and kwds and am suprised at what it does supersnake self init args kwdsnow when i create instances of the snake subclass which contains the erroneous call to supera init where i use args and kwds instead of args and kwds i get some interesting aargument unpackingas1 snakefalse movestrue num legs0s2 snakepoisonousfalse movestrue num legs1s3 snakefalse true 3s1describes2describes3describewhat i get ismoves num legs moves true num legs 0moves num legs moves true num legs 1moves true 3 num legs so why is it that in s1 and s2 init assumes that moves true and num legs 0 or 1 are keyword arguments and sets the num legs to a dictin s3 it unpacks both of the variables to moves in class animal as a tuplei stumbled into this as i was trying to understand argument unpacking sorry in advanceai do not know how to frame this question any better,['python'] +540903,scrollto function jquery is not working i need jquerys scrollto function to work for this website i have tried the followingdocumentreadyfunction divbtnlp3clickfunction bodyhtmlscrolltotargetexamples 800 easingelasout and i have tried this toodocumentreadyfunction divbtnlp3clickfunction html bodyanimate scrolltop windowlocationhashoffsettop 10 i cannot seem to get scrollto working at all does anyone have any ideas heres what i have importedscript src script script src script,['jquery'] +540909,how a positive value becomes negative after casting byte in java public class test1 public static void mainstring args byte b140 byte bbyte 128 systemoutprintlnb1 systemoutprintlnb the output is 40 128the first output is 40 i understood but the second output 128 how it is possible is it possible due to it exceeds its range if yes how it works after byte castinghelp me,['java'] +540933,how to load image into bootstrap modal with javascript my setup is 4 links below i want each link to open mymodal but depending on which link gets clicked a different image file should load in the modal i got it working for one of the linkslia hrefmymodal datatogglemodal6 teamsalilia href5 teamsalilia href4 teamsalilia href3 teamsali modal div idmymodal classmodal hide fade tabindex1 roledialog arialabelledbymymodallabel ariahiddentrue stylewidth800pxdiv classmodalheaderbutton typebutton classclose datathismissmodal ariahiddentrueabuttondivdiv classmodalbodyimg srcimagesbrackets6teamdouble1jpgdivdiv classmodalfooterbutton classbtn datathismissmodal ariahiddentrueclosebuttondivdivhow do i get this to work for each link without building a separate modal for each one,['javascript'] +540949,how to thismiss keyboard ios programmatically i created a uitextfield programmatically making the uitextfield a property of the viewcontroller i need to thismiss the keyboard with the return and the touch on the screen i was able to get the screen touch to thismiss but pressing return is not working i have seen how to do it with storyboards and by allocating and initializing the uitextfield object directly without creating it as a property possible to do i am a noob sorry himport uikituikithinterface viewcontroller uiviewcontroller uitextfielddelegateproperty strong atomic uitextfield usernameendmimport viewcontrollerhinterface viewcontroller endimplementation viewcontroller voidviewdidload super viewdidload do any additional setup after loading the view typically from a nib selfviewbackgroundcolor uicolor bluecolor selfusername uitextfield alloc initwithframecgrectmake100 25 80 20 selfusernameplaceholder enter your username selfusernamebackgroundcolor uicolor whitecolor selfusernameborderstyle uitextborderstyleroundedrect if selfusernameplaceholder nil selfusernameclearsonbeginediting no usernamedelegate self selfview addsubviewselfusername username resignfirstresponder voiddidreceivememorywarning super didreceivememorywarning thispose of any resources that can be recreated voidtouchesbegannsset touches witheventuievent event nslogtouchesbeganwithevent selfview endeditingyes super touchesbegantouches witheventeventend,['ios'] +540953,fragment pressing back button i am now having an activity containing fragments 1 2 3 4 if pressing buttons 3 it can be redirected to 4i would like to implement the back button as shown followwhen pressing back at 4 it return to 3when pressing back at 3 it return to 2when pressing back at 1 the activity finisheswhen it comes to the current implementation it finish the activity instead of popping up the fragment would you please tell me what i should do or keep in mind overridepublic boolean onkeydownint keycode keyevent event if keycodekeyeventkeycode back finish return superonkeydownkeycode event,['android'] +540962,saving text in a local file in internet explorer 10 i need to be able to save a string into a local file based on the code in here i got the following goingfunction savetextasfilefilenametosaveas texttowrite var textfileasblob new blobtexttowrite type textplainvar downloadlink documentcreateelementadownloadlinkdownload filenametosaveasdownloadlinkinnerhtml download fileif true windowwebkiturl null chrome allows the link to be clicked without actually adding it to the dom downloadlinkhref windowurlcreateobjecturltextfileasblob else firefox requires the link to be added to the dom before it can be clicked downloadlinkhref windowurlcreateobjecturltextfileasblob downloadlinkonclick destroyclickedelement downloadlinkstylethisplay none documentbodyappendchilddownloadlinkdownloadlinkclickthis works fine for chrome and firefox but not for internet explorer 10 asdownloadlinkclickgivesscript5 access is deniedis there any explanationsolution to this thanks,['javascript'] +540975,printing with indentation in python is there a way to print the followingprint user tt messageso that lengthy messages that are wider than the length of the terminal always wraps starts from the same position so for example thisusername leftleftleftleftleftleftleftrightrightrightshould becomeusername leftleftleftleftleftleftleft rightrightright,['python'] +540980,width and height equal to its superview using autolayout programmatically i have been looking for a lot of snippets in the net and i still cannot find the answer to my problem my question is i have a scrollviewsv and i want to add a button inside scrollviewsv programmatically with same width and height of its superview which is scrollviewsv so that when user rotate the device button will have the same frame of scrollviewsv how to do the nslayoutnslayoutconstraint thanks,['ios'] +540982,knockout mapping fromjs failing on a simple example i am trying to figure out what i am misunderstanding with knockouts mapping library i have stripped it down to a simple example and still can get it to fail rather not update with the mapped variables with the fromjs call what am i getting fundamentally wrong in this example heres my view modelvar viewmodel function thisfirstname koobservablefirst thislastname koobservablelastvar myvm new viewmodelkoapplybindingsmyvm apply to knockout worksmyvmlastnamemaiden name test an update worksvar newdata firstname new lastname person try update the viewmodelkomappingfromjsnewdata myvm no update or error intended result ui updates to new personand the corresponding viewdiv classliveexample pfirst name input databindvalue firstname p plast name input databindvalue lastname p divmy js fiddle example,['javascript'] +541032,what should i use as return type of method ienumerable ilist collection or what i am making a library which is going to be used widely by different applications you can say that it is sort of a public library or sdkcurrently i am working on a function which takes a list of points performs some calculation on these points and then return list of updated points so my question here is what should i use as return type and in my parameters ilist ienumerable or collectionso here it the function i am unaware what user will do with the output how user uses it is on him so what should be best option to use herepublic static ienumerablepoint2d peformsomecalculationienumerablepoint2d points do something return updatedpoints,"['c#', '.net']" +541110,how to hide status bar in uiimagepickercontroller i am new to ios development i am trying to hide status bar in uiimagepickercontroller whenever i click on take photo status bar appears it does not hide i want status bar to be hidden only in uiimagepickercontroller here is my code ibactiontakephotouibutton sender uiimagepickercontroller picker uiimagepickercontroller alloc init pickerdelegate self pickerallowsediting yes pickersourcetype uiimagepickercontrollersourcetypecamera self presentviewcontrollerpicker animatedyes completionnull voidimagepickercontrolleruiimagepickercontroller picker didfinishpickingmediawithinfonsdictionary info self statusbaryes uiimage chosenimage infouiimagepickercontrollereditedimage selfimageviewimage chosenimage picker thismissviewcontrolleranimatedyes completionnull voidimagepickercontrollerdidcanceluiimagepickercontroller pickerpicker thismissviewcontrolleranimatedyes completionnullvoidstatusbarboolstatus uiapplication sharedapplication setstatusbarhiddenstatushow to hide the status bar on uiimagepickercontroller,"['ios', 'objective-c', 'iphone']" +541237,explicitly expressing ownership in delphi i am primarily a c programmer and i have grown used to having class templates like stdunique ptr stdshared ptr etc for expressing ownership of my objects does delphi have anything that is similar in its standard library are there any bestpractices out there for expressing object ownership that i should be following as i write my codeedit since c11 became standard there are two lightweight helper classes stdshared ptr and stdunique ptr if i create a variable of type stdshared ptrint it represents a pointer to an int with shared ownership under the hood is referencecounted and when the refcount reaches zero then the pointer is automatically freed this type expresses a kind of shared ownership where many objects share the responsibility of destroying the resource when they are done with itin contrast stdunique ptr expresses single ownership when the unique ptr goes out of scope the resource is automatically freed stdunique ptr cannot be copied there can be exactly one object owning this resource at a time and there is exactly one object who is responsible to clean the object upcontrast these lightweight classes with a naked pointer to int where it can represent either shared ownership unique ownership or it can just be a reference to an object somewhere else the type tells you nothingmy question is as delphi supports holding references to objects are there any mechanisms for explicitly stating i am the sole owner of this object when i am done with it i will free it vs i am merely keeping a reference to this object around for the purpose of interacting with it but somebody else will clean it up vs i share this object with many other objects and whoever has it last gets to clean it upi know that collectionsgenerics has different collections such as tlist vs tobjectlist where tobjectlist will free the members stored within it but tlist would not you can say that tobjectlist owns it is elements whereas tlist does not this is the essence of my question really when designing my own classes are there ways of directly expressing these kinds of ownership issues within the language or are there any best practicesnaming conventions that are common amongst developers,['c++'] +541245,loading images in gridview using universal image loader i am using the universal image loader 186 library for loading dinamically images taken from webthe imageloaderconfiguration configuration is the followingimageloaderconfiguration config new imageloaderconfigurationbuildergetapplicationcontext memorycacheextraoptions480 800 default device screen dimensions threadpoolsize3 default threadprioritythreadnorm priority 1 default denycacheimagemultiplesizesinmemory memorycachesize2 1024 1024 memorycachesizepercentage13 default thisccachesize50 1024 1024 thisccachefilecount100 imagedownloadernew baseimagedownloadergetapplicationcontext default defaultthisplayimageoptionsthisplayimageoptionscreatesimple default writedebuglogs buildand the thisplayimageoptions configuration isthisplayimageoptions options new thisplayimageoptionsbuilder showstubimagerdrawableno foto showimageforemptyurirdrawableno foto showimageonfailrdrawableno foto buildthe method getview inside my arrayadapter contains the codeivsetimageresourcerdrawableno foto imageloaderthisplayimagebasepathimmagine ivthe first line of the above code is used just for avoid that the recycling of view in gridview allow to set image in the wrong position until the picture has not been downloadedthe actual problem is thisif i open my activity containing the gridview the shown items thanks to the uil library can download the image meanwhile the no fotopng image is shown in each view of the grid when all the views have loaded their own images if i try to scroll down and then i come back scrolling up i have to wait that the images are reloaded because all the views are now occupied by the no fotopng image how can i avoid the reload of these images using universal image loader can i cache the images previous loadednote since my grid can contain many images i would to use an implementation of thisk cache not memory cachei found that thisccachefilecount can be used for setting the maximum number of cached files so why it seems that my files are not cached,['android'] +541248,static java is pass by value then why my program show that output first of all sorry for this question this is very old topicyes i did lots of search that java is pass by valuebut by my program show that out put i cannot understand whymy program is class dog static string dogname dogstring name dognamename public void setnamestring newname dognamenewname public string getname return dogname class javaispassbyvalue public static void mainstring arr dog dog1new dogolddog new javaispassbyvaluethisplaydog1 systemoutprintlndog1getname public void thisplaydog d systemoutprintlndgetname d new dognewdog systemoutprintlndgetname output isolddognewdognewdogbut i am expectingolddognewdogolddogplease anybody tell me where i am thinking wrong,['java'] +541265,is it recommended to explicitly make overriding functions virtual in times before c11 when a virtual function was overriden in a derived class it was recommended to add the virtual keyword also to the derived class function to make the intention clearnowadays such a function is marked override which kind of includes the notion that there must be a virtual base function therefore i am now preferring to omit the virtualclass derived public base public void overriden override instead of virtual void overriden overridehowever this leads to an intellisense error in msvc 2012the override modifier requires a virtual function declaration with an explicit virtual keywordobviously the compiler compiles the class but the error makes me think about it are there still valid reasons to add the virtual keyword,['c++'] +541302,stringbuilder reset or create a new i have a condition that a stringbuilder keeps storing lines matching a pattern from a large flat file 100s of mb however after reaching a condition i write the content of the stringbuilder varialble to a textfile now i wonder if i should use the same variable by resetting the object stringbuilderdelete0stringbuilderlengthorstringbuildernew stringbuilderplease suggest which would do you think is better as far as both performance and oom issues are concerned,['java'] +541306,resolve gcc error when installing pythonldap on redhat enterprise server pythonldap redhat gnashing of teethrecently i spent a few hours tearing my hair or whats left of it out attempting to install pythonldap via pip onto a redhat enterprise serverheres the error message that i would get look familiarmodulesconstantsc365 error aldap control relaxa undeclared first use in this functionerror command gcc failed with exit status 1if only there was someone out there that could help me,['python'] +541320,nsdateformatter date according to currentlocale without year this cannot be too difficulti want to thisplay a date without the year for example aug 2nd usa or 0208 germanyit must work for a bunch of other locales as wellmy only idea so far is to do a normal format with year and then remove the yearportion from the generated string,"['ios', 'objective-c']" +541352,draggable drawer with a handle instead of action bar on top of other apps backgroundwe all know we can use a navigation drawer as a new way to navigate in an app even with a library like this one we also know that some apps can float above others as shown on aircalc and done like so using a system alert window permissioni have noticed that some apps combine expanding collapsing of views that are on top like the next onescalleridsidebar liteeasy controllercontrol centerand many morethe problemwe need to merge the 2 concepts of being on top of other apps and allow dragging a handle to show the content on its left side like a navigation drawermaybe this could show what i meanas far as i know putting anything on top using a systemalert permission requires knowing the size of the viewhowever this is different since i cannot set it to be the entire screen because i do not want to block the rest of the screen in case the user sees only the handle of the navigation drawerthe questionis it possible to merge the 2 concepts how would i allow all states to behave nicely while being on topfor avoiding blocking of touches i would also like to allow the user to drag the handle up and down or maybe customize its position in some way,['android'] +541412,ios7 app backward compatible with ios5 regarding unique identifier my app is compatible with ios5 and ios6until now i had no problem usingnsstring deviceid uidevice currentdevice uniqueidentifiernow with ios7 and with uniqueidentifier not working anymore i changed tonsstring deviceid uidevice currentdevice identifierforvendor uuidstringthe problem is this would not work for ios5how can i achieve backward compatibility with ios5i tried this with no luckif iphone os version min required 60 ios 60 or later nsstring deviceid uidevice currentdevice identifierforvendor uuidstringelse ios 5x or earlier nsstring deviceid uidevice currentdevice uniqueidentifierendif,"['ios', 'objective-c']" +541455,how to test afterpropertiesset method in my spring application i am working on writing some junit test for my spring application below is my application which implements initializingbean interfacepublic class initializeframework implements initializingbean override public void afterpropertiesset throws exception try catch exception e now i want to call afterpropertiesset method from my junit test but somehow i am not able to understand what is the right way to do this i thought i can use reflection to call this method but i do not think it is a right way to do thatcan anyone provide me a simple example for this on how to write a simple junit test that will test afterpropertiesset method in initializeframework class,['java'] +541477,should i thispose all thisposable objects many objects in net sqlcommand for instance implement ithisposable as a general rule if i create an instance of an ithisposable object should i always thispose it,"['c#', '.net']" +541486,what is the difference between spring factorymethod and factorybean i am new springs in bean tag i found factorymethod and factorybean attributes what is the difference between factorymethod and factorybeani am using factorymethod to call my getinstance static method to create singleton objectwhat is factorybean used for for given replies what i understood wasfactorymethod is used for calling a static method to create object in same bean classfactorybean is used for creating a object based on factory design patternex i am asking a eggplant object from vegetablefactory which will return vegetable object which was askedclass by passing my vegetable nameeggplant in this caseplease correct if i am wrong,['java'] +541492,contour irregular data within polygon i need to create filled contour plots of sea surface temperature sst data within a polygon however i am not sure the best way to do this i have three 1d arrays containing data for x y and sst which i plot using the following to create the attached plot ppatchcollectionmypatchescolornone alpha10edgecolorpurplelinewidth20levelsnparangesstminsstmax02datamapmymapscatterxycsst s55 vmin2vmax3alpha10i would like to be able to plot these data as filled contours contourf instead of scatter that are constrained clipped within the polygon boundaries the purple line suggestions for how to achieve this are greatly appreciatedupdatei had originally tried griddata but could not get it to work properly however based on the answer provided by eatham i decided to try again i could not get my scipy griddata to work as it kept hanging at the gridding when selecting method cubic however when i switched to matplotlibmlabgriddata and used linear interpolation it worked the suggestion for masking the boundaries provided a very coarse and not as exact solution as i would preferi searched for options on how to clip contours in matplotlib and i found an answer by pelson at this link i tried the suggested solution implied in the contour set itself does not have a set clip path method but you can iterate over each of the contour collections and set their respective clip paths my new and final solution looks like this see plot below ppatchcollectionmypatchescolornone alpha10edgecolorpurplelinewidth20 levelsnparangesstminsstmax02 grid x grid y npmgridxmin05xminxmax05xmax200j ymin05yminymax05ymax200j grid z griddataxysstgrid xgrid y csmymapcontourfgrid x grid y grid z for poly in mypatches for artist in axget children artistset clip pathpoly axadd patchpoly mymapdrawcountries mymapdrawcoastlines mymapfillcontinentscolorlightgreylake colornone mymapdrawmapboundaryfill colornonethis solution could also be improved particularily in terms of extrapolating the extreme edges in the north suggestions for how to really fillin the full polygon are appreciated i also would like to understand why mlab worked and scipy not,['python'] +541526,how to bind html in angular v12 i was trying to make a blog in angularjs and on the post message section i want to get the message from json and add it to a content div like this div classcontent jsonmessagedivnow my div has a paragraph in it it is practically a html code like thispthis is my messagepbut when i do this i see on the screen this pthis is my messagepas text i understand in previous versions i could use ngbindhtmlunsafe but i am using v12 of angularjs can anyone please show me code similar to ngbindhtmlunsafe so that i can make this work in v12 thank you daniel,"['javascript', 'html']" +541568,why does not the ternary operator find cast type depending on value being looked for a question here raised a question for meternary operations in c say x y a b use the type of either a or b to determine the type of the ternary expression why does not it use the type of x in any given situation is not there an expected return type that it can useedit for the sake of clarity when i say why does not it use the type of xi suppose i meanwhy does not it first try to use the type of xas the documentation states if x and y are the same type then this is the type of theconditional expression otherwise if an implicit conversion section61 exists from x to y but not from y to x then y is the type of the conditional expression otherwise if an implicit conversionsection 61 exists from y to x but not from x to y then x is thetype of the conditional expression otherwise no expression type canbe determined and a compiletime error occurscould this process start withif the resolution type is unambiguous then it is the type of the conditional expression,['c#'] +541572,jquery crossdomain ajax callback when executed backgroundi am loading and executing a script from another server cross domain via jquerys ajax callthere is a bit of code that needs to be executed after the code from the other server has been executed because otherwise some objects are undefined yetmaybe important the remote code does contain another getscript call and i have to wait for this code to be executed as well i cannot simply load this second script from my code because its source is dynamic ie depends on some results of the remote scriptdid not work success callbackapparently a success callback is called after the remote code is laoded but before the remote code is executed coffee scriptexecutelater this bit of code needs to run after the remote code has been executed consolelogyehaagetscriptsuccessexecutelater this gets executed when the remote script is loaded but before the remote script is executeddid not work async falseapparently the async attribute is ignored for crossdomain requests as stated here in the jquery documentation furthermore i would like to avoid the async false setting because it is said to block the browser coffee scriptexecutelater this bit of code needs to run after the remote code has been executed consolelogyehajax datatype script url async false does not work because the request is cross domainsuccessexecutelaterdid not work whenthenusing jquerys whenthen mechanism apparently the then code is executed before the when block is executed coffee scriptexecutelater this bit of code needs to run after the remote code has been executed consolelogyehaawhen ajax datatype script url thenexecutelateredit did work but unusable ajax both scriptsi cannot do this in production as i said above in the background section but if i reduce all cases to one and load the second script which is usually executed by the remote script in my own script all works fine coffee scriptexecutelater this bit of code needs to run after the remote code has been executed consolelogyehaagetscriptsuccess ajax datatype script cache true i do not know this url in production url successexecutelaterthings to avoidi would hate to use constructions like a couple of settimout calls until a certain object is defined an the execute the executelater methodwhat i need a executed callbackit would be perfect to use a kind of executed callback rather than the success callback of the ajax method but so far i have not found this callback coffee scriptexecutelater this bit of code needs to run after the remote code has been executed consolelogyehajax datatype script url executed executelater i need a callback like thisany cluesdoes anyone know how i can execute the executelater method after the remote code has been executed thanksedit sameorigin policyas adeneo pointed out in the comments section javascripts sameorigin policy might be the problem the script which i load with an ajax or getscript call is not allowed to load and execute another script from a remote server in order to prevent a malicious script from calling home this is supported by the following experimentthis does not workhtmlhead script languagejavascript srcscript script languagejavascript jquerygetscript scriptheadbodybodyhtmlthis worksaccording to this stackexchange answer the sameorigin policy allows remote scripts that are loaded by an html script tag to load other remote scripts via ajaxhtmlhead script languagejavascript srcscript script languagejavascript srcscriptheadbodybodyhtmlthe question remains is there a good way to do it with an ajax call or do i have to prove that i own this code by inserting a script tag in to the html document,['jquery'] +541610,converting a csv file into a list of tuples with python i am to take a csv with 4 columns brand price weight and typethe types are orange apple pear plumparameters i need to select the most possible weight but by selecting 1 orange 2 pears 3 apples and 1 plum by not exceeding as 20 budget i cannot repeat brands of the same fruit like selecting the same brand of apple 3 times etci can open and read the csv file through python but i am not sure how to create a dictionary or list of tuples from the csv filefor more clarity heres an idea of the databrand price weight typebrand1 605 32 orangebrand2 805 52 orangebrand3 654 42 orangebrand1 605 32 pearbrand2 705 36 pearbrand3 745 39 pearbrand1 545 27 applebrand2 605 32 applebrand3 643 35 applebrand4 705 39 applebrand1 805 42 plumbrand2 305 22 plumheres all i have right nowimport csvtest file testallposcsvcsv file csvdictreaderopentest file rb brand price weight type,['python'] +541620,is there a standard way to customize the deploy path in spring boot i am exploring the possibilities of spring boot right now and i am at a slight impasse i want to be able to run two spring boot applications at once both on the same server but at different paths one deploys on the other deploys at anotherpathbecause this is an embedded tomcat instance running within spring boot there is no configuration files available for me to changeis there a standard way to do this is it possible,['java'] +541666,cannot get scrolltop to work in both chrome firefox i am having trouble getting the scrolltop method to work in both firefox and chrome i used body htmlscrolltop however it does not work in chrome only bodyscrolltop works in chrome any thoughts would be greatly appreciated below is my codedoctype htmlhtmlhead titledemotitle style typetextcss body height 20px light thisplay block position fixed top 50 left 50 marginleft 400px margintop 200px width 800px height 400px backgroundcolor blue zindex1002 overflow auto styleheadbody div idlight div used the google jquery link for ease of use in this example script typetextjavascript srcscript script typetextjavascript documentreadyfunction windowscrollfunction var offset body htmlscrolltop var view windowheight var total documentheight var percent 1offset total view var widthfactor 800percent var marginfactor 400percent ifpercent 033 lightcss width widthfactor marginleft marginfactor scriptbodyhtml,"['javascript', 'jquery']" +541672,solve error javaxmailauthenticationfailedexception i am not familiar with this function to send mail in java i am getting an error while sending email to reset password hope you can give me a solutionbelow is my codepublic synchronized static boolean sendmailadvancestring emailto string subject string bodystring host appconfigmanagergetpropertysenderemailsmtpaddrestring username appconfigmanagergetpropertysenderemailsmtpusernamestring password appconfigmanagergetpropertysenderemailsmtppasswordstring port appconfigmanagergetpropertysenderemailsmtpportstring starttls appconfigmanagergetpropertysenderemailsmtpstarttlsstring socketfactoryclass appconfigmanagergetpropertysenderemailsmtpsocketclastring fallback appconfigmanagergetpropertysenderemailsmtpallowfallback try javautilproperties props null props systemgetproperties propsputmailsmtpuser username propsputmailsmtphost host propsputmailsmtpauth true propsputmailsmtpdebug true ifequalsport propsputmailsmtpport port propsputmailsmtpsocketfactoryport port ifequalsstarttls propsputmailsmtpstarttlsenablestarttls ifequalssocketfactoryclass propsputmailsmtpsocketfactoryclasocketfactoryclass ifequalsfallback propsputmailsmtpsocketfactoryfallback fallback session session sessiongetdefaultinstanceprops null sessionsetdebugtrue mimemessage msg new mimemessagesession msgsetfromnew internetaddressusername msgsetsubjectsubject msgsettextbody iso88591 msgsetsentdatenew date msgsetheadercontenttype texthtmlcharsetiso88591 msgaddrecipientmessagerecipienttypeto new internetaddressemailto msgsavechanges transport transport sessiongettransportsmtp transportconnecthost username password transportsendmessagemsg msggetallrecipients transportclose return true catch exception mex mexprintstacktrace return false throws the following errordebug setdebug javamail version 141easnapshotdebug getprovider returning javaxmailprovidertransportsmtpcomsunmailsmtpsmtptransportsun microsystems incdebug smtp useehlo true useauth truedebug smtp trying to connect to host smtpgmailcom port 465 isl false 220 mxgooglecom esmtp m4sm5929870pbg38 gsmtpdebug smtp connected to host smtpgmailcom port 465ehlo fatin250mxgooglecom at your service 17513919814250size 358825772508bitmime250auth login plain xoauth xoauth2 plainclienttoken250enhancedstatuscodes250 chunkingdebug smtp found extension size arg 35882577debug smtp found extension 8bitmime arg debug smtp found extension auth arg login plain xoauth xoauth2 plainclienttokendebug smtp found extension enhancedstatuscodes arg debug smtp found extension chunking arg debug smtp attempt to authenticateauth login334 vxnlcm5hbwu6ywnjb3vudebibg9vbwluzy5jb20ubxk334 ugfzc3dvcmq6ymxvb21pbmc535578 username and password not accepted learn more at535 578 m4sm5929870pbg38 gsmtpstdout javaxmailauthenticationfailedexceptionstdout at javaxmailserviceconnectservicejava319stdout at javaxmailserviceconnectservicejava169stdout at comvleeutilmailsendmailsendmailadvancesendmailjava283stdout at comvleeservletecommercedomemberloginfnsendpwddomemberloginjava251stdout at comvleeservletecommercedomemberlogindopostdomemberloginjava72,['java'] +541737,passing a c stdvector to numpy array in python i am trying a pass a vector of doubles that i generate in my c code to a python numpy array i am looking to do some downstream processing in python and want to use some python facilities once i populate the numpy array one of the biggest things i want to do is to be able to plot things and c is a bit clumsy when it comes to that also i want to be able to leverage pythons statistical powerthough i am not very clear as to how to do it i spent a lot of time going through the python c api documentation i came across a function pyarray simplenewfromdata that apparently can do the trick i still am very unclear as far as the overall set up of the code is concerned i am building certain very simple test cases to help me understand this process i generated the following code as a standlone empty project in visual studio express 2012 i call this file project1include pythonhinclude cpython27libsitepackagesnumpycoreincludenumpyarrayobjecthpyobject testcreatarray float farray5 01234 npy intp m 5 pyobject c pyarray simplenewfromdata1mpyarray floatfarray return c my goal is to be able to read the pyobject in python i am stuck because i do not know how to reference this module in python in particular how do i import this project from python i tried to do a import project1 from the project path in python but failed once i understand this base case my goal is to figure out a way to pass the vector container that i compute in my main function to python i am not sure how to do that eitherany experts who can help me with this or maybe post a simple well contained example of some code that reads in and populates a numpy array from a simple c vector i will be grateful many thanks in advance,['c++'] +541739,how to reload a page using angularjs i have a link when user will click in this link then the page will be reloaded i did it by the following wayhtmldiv datanghidebackhide classoffset6 pullright a href datangclickbacklinkclick back br bra divjs scopebacklinkclick function windowlocationreloadfalse in the controller i have used javascript and that seems to me very bad how can i do it using angularjs,['javascript'] +541742,it has no effect when i update invoice in quickbooks online with the v3 sdk for net when i want to update the balance in a invoice the code below is running normally without any error but the balance does not change why var queryservice new queryserviceintuitippdatainvoicecontext ilistintuitippdatainvoice list queryservicewherep truetolist foreach var invoice in list if invoiceid orderaccountingqboid if invoicebalance orderaccountingsurveyamount invoice invo new invoice invoid invoiceid invo commonservicefindbyidinvo invobalance orderaccountingsurveyamounthasvalue orderaccountingsurveyamountvalue 0 invosparse true commonserviceupdateinvo,['.net'] +541771,cc intentional out of range indexing say i have an array like soint val10and i intentionally index it with everything from negative values to anything higher than 9 but without using the resulting value in any way this would be for performance reasons perhaps it is more efficient to check the input index after the array access has been mademy questions areis it safe to do so or will i run into some sort of memory protection barriers risk corrupting memory or similar for certain indicesis it perhaps not at all efficient if i access data out of range like this assuming the array has no built in range checkwould it be considered bad practice assuming a comment is written to indicate were aware of using out of range indices,"['c++', 'c']" +541819,python pip specify a library directory and an include directory i am using pip and trying to install a python module called pyodbc which has some dependencies on nonpython libraries like unixodbcdev unixodbcbin unixodbc i cannot install these dependencies system wide at the moment as i am only playing so i have installed them in a nonstandard location how do i tell pip where to look for these dependencies more exactly how do i pass information through pip of include dirs gcc i and library dirs gcc l l to be used when building the pyodbc extension,['python'] +541856,angular directive with default options i am just starting with angularjs and am working on converting a few old jquery plugins to angular directives i would like to define a set of default options for my element directive which can be overridden by specifying the option value in an attributei have had a look around for the way others have done this and in the angularui library the uibootstrappagination seems to do something similarfirst all default options are defined in a constant objectconstantpaginationconfig itemsperpage 10 boundarylinks false then a getattributevalue utility function is attached to the directive controllerthisgetattributevalue functionattribute defaultvalue interpolate return angularisdefinedattribute interpolate interpolateattributescopeparent scopeparentevalattribute defaultvaluefinally this is used in the linking function to read in attributes asdirectivepagination parse paginationconfig functionparse config controller paginationcontroller link functionscope element attrs paginationctrl var boundarylinks paginationctrlgetattributevalueattrsboundarylinks configboundarylinks var firsttext paginationctrlgetattributevalueattrsfirsttext configfirsttext true this seems like a rather complicated setup for something as standard as wanting to replace a set of default values are there any other ways to do this that are common or is it normal to always define a utility function such as getattributevalue and parse options in this way i am interested to find out what different strategies people have for this common taskalso as a bonus i am not clear why the interpolate parameter is required,['javascript'] +541907,how to get the innerhtml of selectable jquery element i have a php generated list whose list items are selectable using jquery selectable widget the list for all intents and purposes isul idselectimage li classuiwidgetcontentitem 1li li classuiwidgetcontentitem 2li li classuiwidgetcontentitem 3li li classuiwidgetcontentitem 4li li classuiwidgetcontentitem 5li li classuiwidgetcontentitem 6li li classuiwidgetcontentitem 7liuland the jquery selectable is declared asscript function selectimageselectable selected function event ui var variable uiselectedinnerhtml consolelogvariable scriptan event takes place after a list item has been selected in the example it outputs to the browser console the output however is undefined the selector uiselected is correct as it shows as an object in the browsers console where am i going wrong,"['javascript', 'jquery', 'html']" +541926,problems with hex i get some homework but i stack in it maybe you can help me task belowread the keyboard integer in the decimal system and establishment of a new system of numbersoutput in the console number written in the new notationi made for 2 to 10 systems only and i cannot make from 10 to 36 i tried to make in second loop something like thisif result 9 printfc 55number else printfd resultmy codeinclude stdiohint main int number base int i result scanfd d number base if number base printfdn number else for i base i number base i base for int j i j base j base result number j printfd result number number j printfdn numberbase return 0,['c'] +541948,passing reference type in c class test static void funcstringbuilder mystring mystringappend test mystring null static void main stringbuilder s1 new stringbuilder funcs1 consolewriteline s1 the output is test why is not it nullif s1 is passed by reference to func then why does mystringappendtest change it but mystring null does notthanks in advance,['c#'] +541954,how to stop the reactor while several scrapy spiders are running in the same process i have read from here and here and made multiple spiders running in the same process workhowever i do not know how to design a signal system to stop the reactor when all spiders are finishedmy code is quite similar with the following examplefrom twistedinternet import reactorfrom scrapycrawler import crawlerfrom scrapysettings import settingsfrom scrapy import logfrom testspidersspidersfollowall import followallspiderdef setup crawlerdomain spider followallspiderdomaindomain crawler crawlersettings crawlerconfigure crawlercrawlspider crawlerstartfor domain in scrapinghubcom insophiacom setup crawlerdomainlogstartreactorrunafter all the crawler stops the reactor is still running if i add the statementcrawlersignalsconnectreactorstop signalsignalsspider closedto the setup crawler function reactor stops when first crawler closedcan any body show me howto make the reactor stops when all the crawler finished,['python'] +541964,maven unpack files from jar if jar is used copy then extracted files to a directory i have a large webapp which uses many maven dependencies they are included as jar files but i want to have a chance to use some of them as an opened project directly in eclipse then dependent projects are linked with m2efrom some of that jarsprojects resources need to be extractedhow can i do that with mavendependencyplugin if artifact is included as jar unpack it and then copy files to required directory if artifact is included as project it exists on a harddrive and files can be directly accessed and copied without unpackthanks,['java'] +541984,is it safe to push back an element from the same vector vectorint vvpush back1vpush backv0if the second push back causes a reallocation the reference to the first integer in the vector will no longer be valid so this is not safevectorint vvpush back1vreservevsize 1vpush backv0this makes it safe,['c++'] +542064,jquery file upload plugin does not work i am trying to use jquery file upload plugin in my site but at the moment it has been impossible and the documentation is the worst i have ever seen the only things i can see are some demos files with a lot of lines of code without any kind of explanationi have tried to use it in my site with the css and js files included in the demos but the file upload plugin is not rendered as it should after some research i have found that renderupload method of jqueryfileuploadjqueryuijs is never called neither do create method of the same filethose methods are the responsible to add the css classes so that the file upload could look betterthis is the html code i havediv classfileuploadbuttonbar div classfileuploadbuttons span classfileinputbutton spanagregar archivospan input typefile namefiles span button typesubmit clastartimportarbutton div div classfileuploadprogress fade stylethisplaynone the global progress bar div classprogress roleprogressbar ariavaluemin0 ariavaluemax100div the extended global progress information div classprogressextendednbspdiv divdiv table rolepresentationtbody classfilestbodytableand this is the initializationfunction fileuploadfileupload url urlactionimport thisableimageresize false maxfilesize 30 acceptfiletypes csvtxtxlsxlsxi singlefileuploads true autoupload false maxnumberoffiles 1 change function e data alertdatafileslength eachdatafiles function index file import filetextfilename buttonimportattrstyle thisplay spanstatustext add function e data alertdatafiles datacontext buttonimport clickfunction datacontext spanstatustextimportando buttonimportattrstyle thisplay none datasubmit done function e data datacontexttextcompleto administradorestriggerreloadgrid page 1 fileuploadaddclassfileuploadprocessingand finally i told that i am including the following css file jqueryfileuploaduicssand this is the js files in this orderjqueryuiwidgetjs jqueryiframetransportjsjqueryfileuploadjsjqueryfileuploadprocessjsjqueryfileuploadvalidatejsjqueryfileuploaduijsjqueryfileuploadjqueryuijsany help will be greatly appreciatedthanksjaime,['jquery'] +542065,hibernate hql count thistinct not working i have the following classes class user hasmany ratings rating class item hasmany ratings ratingclass rating belongsto user user item itemi want to count the thistinct users that rated on an itemthe following does not work select countthistinctruser from rating as r where ritemitem group by ruserhow do i have to modify the hql query to make it work,['java'] +542087,rails 4 how to use named scope with has many associations in my rails 4 app project model has many videos model i have a named scope in the videos model scope live where is deleted 0 sent to api 1 in one of my project views i do this project is an instance of projectprojectvideoslivesizewhat i expect to get is the number of projects in that specific project but instead i get the number of videos in any project it is as if live is not returning a subset from videos but rather replacing iti see it explained here that chaining named scopes with one another should be combined with logical and but when applied to an association method not sure the proper terminology for videos in this context that does not seem to be happeningwhats the right way to do this,"['ruby-on-rails', 'ruby']" +542109,pythonldap not able to bind successfully i am not having any luck finding answers on this so here it goeswhen i attemtp to connect to an ad server using pythonldap it appears to work successfully for some functions and not for others my connectionimport sysimport ldapl ldapinitializeldapcompanycom389lset optionldapopt protocol version 3lsimple bind spassword97 1 some simple google searching indicated that the 97 meant success although the level of success is a bit wonky but for some reason i cant find anything on the status code 1 if i run some ldap functions on the connection some of them work and some do notlwhoami sucompanycomuserseems to return fine but base dn dccompanydccom retrieveattributes uniquemember searchfilter cnuser lsearch sbase dn ldapscope subtreesearchfilterretrieveattributestraceback most recent call last file console line 1 in module file homeuserenvsscoringlocallibpython27sitepackagesldapldapobjectpy line 552 in search s return selfsearch ext sbasescopefilterstrattrlistattrsonlynonenonetimeoutselftimeout file homeuserenvsscoringlocallibpython27sitepackagesldapldapobjectpy line 546 in search ext s return selfresultmsgidall1timeouttimeout1 file homeuserenvsscoringlocallibpython27sitepackagesldapldapobjectpy line 458 in result resp type resp data resp msgid selfresult2msgidalltimeout file homeuserenvsscoringlocallibpython27sitepackagesldapldapobjectpy line 462 in result2 resp type resp data resp msgid resp ctrls selfresult3msgidalltimeout file homeuserenvsscoringlocallibpython27sitepackagesldapldapobjectpy line 469 in result3 resp ctrl classesresp ctrl classes file homeuserenvsscoringlocallibpython27sitepackagesldapldapobjectpy line 476 in result4 ldap result self ldap callself lresult4msgidalltimeoutadd ctrlsadd intermediatesadd extop file homeuserenvsscoringlocallibpython27sitepackagesldapldapobjectpy line 99 in ldap call result funcargskwargsoperations error info 04dc ldaperr dsid0c0906e8 comment in order to perform this operation a successful bind must be completed on the connection data 0 v1db1 desc operations errori am stumped to why the whoami would work but the search would not i am using a domain admin for the user so it should not have anything to do with permissions to the directory can anyone shed some light,['python'] +542121,how to use momentjs for a certain timezone and thisplay it in real time how do i go about using the momentjs library for an international timezone and thisplay it in real timethis is what i have so far in my index pagecodedoctype htmlhtmlheadscript srcmomentjsscriptscript srcmomenttimezonejsscriptscript srcscriptscript momenttzamericalos angelesformat documentgetelementbyidtimefirstchilddata momentformathhmmss ascriptheadbody span idtimesspanbodyhtmlthis is my first time using momentjs and i dont know if i have implemented it correctly and to thisplay it in real time without refreshing the page constantly,['javascript'] +542126,java resetting inputstream i am dealing with some java code in which there is an inputstream that i read one time and then i need to read it once again in the same methodthe problem is that i need to reset it is position to the start in order to read it twicei have found a hackish solution to the problemismarkintegermax valueread the inputstream is fully try isresetcatch ioexception e eprintstacktracedoes this solution lead to some unespected behaviours or it will work in it is dumbness,['java'] +542150,how to get the index of numpyrandomchoice python is it possible to modify the numpyrandomchoice function in order to make it return the index of the chosen element basically i want to create a list and select elements randomly without replacementimport numpy as np a 14133214 nprandomchoicea 4 a 14133214aremovenprandomchoicea will remove the first element of the list with that value it encounters a1 in the example above which may not be the chosen element eg a7,['python'] +542175,how to detect isnull notnull when building dynamic linq expressions i am building dynamic linq expression that is later evaluated so for example if i want to know if certain property is equal to some value i do memberexpression property int valexpressionequalproperty expressionconstantvalhowever i cannot seem to find a way to detect if val is null or not null can somebody recommend to me how to do that i have tried thisexpressionequalproperty expressionconstantnull propertytypebut obviously that would not work,['c#'] +542198,before pseudoelement causes gap in border i have this piece of html that i want to style the html is a table and actual table which i want to give a borderthe element also had a before pseudoelement which i use to put a small triangle in the top corner the jsfiddle is here i hope it makes sense i stripped down the markup and the css as much as possible because it is actually a small part of a big sitenow the problem is that the combination of having 2 columns having bordercollapse collapse on the table and the before pseudo element cause the top border of the element to partially thisappear it is only there for the length of the first columnyou would assume that it is the pseudo element that is on top of the border but this element is very small and as far as i can tell this could not be the problem i added visibility hidden to the pseudo element to be sure and i can tell that the triangle is gone but the border is still incompleteunfortunately i cannot change the markup since this is outputted by mediawiki but i do have full control over the cssthe htmldiv idglobalwrapperdiv idcolumncontentdiv classthumb trighttable classinfobox vcard style tbody tr th colspan2 classfn org style example textth tr tr throw headth tdcontenttd trthe css generic table styling table bordercollapse collapse borderspacing 0 the box thumbtright tableinfoboxvcard border 3px solid fae104 position relative triangle thumbtright tableinfoboxvcardbefore content position absolute width 0 height 1px bordertop 5px solid transparent top 7px borderleft 10px solid 5 visibility hidden right 1px i already found out that it works when i remove bordercollapse collapse but i am not sure that is a proper solution and even if it is i would really like an explanation of what is going on btw i got this problem both in chrome 29 and in internet explorer 10 have not tested other browsersupdateinstead of using or not using bordercollapse to fix the problem i found out that this also worksthumbtright tableinfoboxvcard tbody thisplay blockso the table itself is still a table the pseudo element is still on the table as is the border positioning etc the tbody which was unstyled before is now a block and the problem is solved in both browsers i found this by trial and error and still wouldnt know the reason behind itupdated fiddle,['css'] +542228,platform of the target fubartests ios 43 is not compatible with kiwi 221 which has a minimum requirement of ios 50 i cannot seem to get past this error and do not know whyi am running xcode 463the projects ios deployment target says ios 61the base sdk is 61my podfile is podfileplatform ios target fubartests exclusive true do pod kiwi end and when i try to run pod install from the command line i get the error about the target being ios 43 why does it think my target is 43 and how can i change it,['ios'] +542275,how to add custom animation on google map v3 marker when i drop each marker one by one this my simple working example of drop each marker onebyone on google map v3i have set the drop animation when marker is added to google mapbut i want to customize the drop with fade animation will it possible using any javascript stuff or other librarygoogle has this options in namespace can we add our custom animation options in namespacegooglemapsanimationdrop googlemapsanimationbouncegooglemapsanimationcustom fade is it possible my working code for google map v3doctype htmlhtml head meta httpequivcontenttype contenttexthtml charsetutf8 titlegoogle maps multiple markerstitle script src typetextjavascriptscripthead body div idmap stylewidth 500px height 400pxdiv script typetextjavascript var locations bondi beach 33890542 151274856 4 coogee beach 33923036 151259052 5 cronulla beach 34028249 151157507 3 manly beach 3380010128657071 15128747820854187 2 maroubra beach 33950198 151259302 1 var map new googlemapsmapdocumentgetelementbyidmap zoom 10 center new googlemapslatlng3392 15125 maptypeid googlemapsmaptypeidroadmap var infowindow new googlemapsinfowindow var marker i function markeri if i locationslength return var marker marker new googlemapsmarker position new googlemapslatlnglocationsi1 locationsi2 animation googlemapsanimationdrop map map var tsettimeoutmarkeri1500 marker0 scriptbodyhtml,"['javascript', 'android', 'jquery']" +542285,how to elegantly return an object that is defaultinitialized i have a class like belowclass veryveryverylongtypename bool is ok veryveryverylongtypename is okfalse veryveryverylongtypename f veryveryverylongtypename v doing something if condition 1 is true return v else return veryveryverylongtypename doing something if condition 2 is true return v else return veryveryverylongtypename i think the statement return veryveryverylongtypename is very tedious and ugly so my question ishow to elegantly return an object that is defaultinitializedor in other words is it a good idea to add a feature into the c standard to make the following statement is legalreturn default instead of return veryveryverylongtypename,['c++'] +542296,drag and drop listitem of a listview to another listviews listitem as shown in screenshoti have listing of folders and associated albumsi have used expandable listview for that listingi have another list besides it which shows imageswhen i click on any albumthe second listview shows images of that particular albumnowi want to move image from existing ablum to another albumand i want to drag and drop desired image to another album to perform this functionalityi would like to have your suggestions to solve the task,['android'] +542330,get name of a method strongly typed think that i have a class like belowpublic class foo public int bar get set public int sumint a int b return a b public int squareint a return a a all you know that i can write a method that returns name of given propertyvar name getpropertynamefoof fbar returns bargetpropertyname method can be implemented easily as belowpublic static string getpropertynametexpressionfunct object exp var body expbody as memberexpression if body null var ubody unaryexpressionexpbody body ubodyoperand as memberexpression return bodymembernamebut i want to get a method name as easily as property name like belowvar name1 getmethodnamefoof fsum expected to return sumvar name2 getmethodnamefoof fsquare expected to return squareis it possible to write such a getmethodname methodnote that getmethodname must be independent from signature or return value of the given method,['c#'] +542333,how to change progressbar color i want to change horizontal progressbar colori have tried this how to change the color of an indefinite progressbarits not working still progress run in blue colorthis is my codeprogressbar androidididmini progress androidlayout marginleft10dip androidlayout marginright10dip styleandroidattrprogressbarstylehorizontal androidlayout widthmatch parent androidlayout height20dip androidlayout gravitycenter horizontal androidindeterminatefalse androidindeterminatebehaviorrepeat androidindeterminateonlytrue androidvisibilitygonehow i can change the color to pink,['android'] +542335,javascript and garbage collection is there any way to control when javascript performs garbage collection i would like to enable it to perform garbage collection at certain times to ensure the smooth operation of my web site,['javascript'] +542340,how to retrieve more than 100 results using twitter4j i am using the twitter4j library to retrieve tweets but i am not getting nearly enough for my purposes currently i am getting that maximum of 100 from one page how do i implement maxid and sinceid into the below code in processing in order to retrieve more than the 100 results from the twitter search api i am totally new to processing and programming in general so any bit of direction on this would be awesome thanksvoid setup configurationbuilder cb new configurationbuilder cbsetoauthconsumerkeyx cbsetoauthconsumersecretx cbsetoauthaccesstokenx cbsetoauthaccesstokensecretx twitter twitter new twitterfactorycbbuildgetinstance query query new querypeace querysetcount100 try queryresult result twittersearchquery arraylist tweets arraylist resultgettweets for int i 0 i tweetssize i status t status tweetsgeti geolocation loc tgetgeolocation if locnull tweetsgeti string user tgetusergetscreenname string msg tgettext double lat tgetgeolocationgetlatitude double lon tgetgeolocationgetlongitude printlnuser user wrote msg located at lat lon catch twitterexception te printlncould not connect te void draw,['java'] +542383,activerecord left outer join with and clause i am using rails 3 with activerecord and i cannot get it to generate the query i want without inserting almost plain sql in iti simply want to execute this sql query actually the query is a little more complex but it is really this part that i cannot get rightselect thistinct users possible datesfrom users left outer join possible dates on possible datesuser id usersid and possible datesevent id my event idwhich i managed to using userincludespossible dates joinsleft outer join possible dates on possible datesuser id usersid and possible datesevent id activerecordbasesanitizeselfid uniqbut i feel that i am missing something to simply add the and condition of the left join using activerecord query methodsi also tried to do something like thisuserincludespossible dates wherepossible datesevent id selfid uniqbut this yields as expected a query with a where clause at the end and not the and clause i want on the joinby the way self in the two snippets above is an instance of my event classthank you for your help,"['sql', 'ruby-on-rails']" +542475,entityframework eager load all navigation properties i am using the repository pattern with di and ioci have created a function in my repositoryt eagergetbyidtguid id string include where t class return dbcontextsettincludeincludefindidthis will eagerly load one navigation property in my entity rightbut if my entity looks like thispublic class blog primarykey public author author getset public icollectionpost posts getsethow would i get eager loading for author and posts would i literally have to do dbcontextsettincludeauthorincludepostsfindidinevitably producing a function like thist eagergetbyidtguid id string include string include2 string include3 where t class return dbcontextsettincludeincludeincludeinclude2includeinclude3findidbecause that would be really inefficient for a generic repositorythanks,['c#'] +542661,is sizeofsize t sizeofvoid always true does the c99c11 standard guarantee that sizeofsize t sizeofvoid is always truesize t fvoid p return size tp is it safevoid fsize t n return voidn is it safe,"['c++', 'c']" +542696,saving into coredata context on background thread i am struggling with this for some time now and apples documentation and so did not help so far i was using managedobjectcontext on a uimanageddocument and the code below worked fine i then decided to use apples template for coredata in appdelegate so model persistent store coordinator and context is created in appdelegate fetching with appdelegates context is no problem but background saving is an issue i should have local context on the thread i am saving and as per apple to have same persistance store coordinator but the code below does not actually save the data can someone here please advise thank you voidfetchandpersist thispatch queue t ffetchq thispatch queue createforfetch null thispatch asyncffetchq nsmanagedobjectcontext securemanagedobjectcontext nspersistentstorecoordinator coordinator appdelegate persistentstorecoordinator if coordinator nil securemanagedobjectcontext nsmanagedobjectcontext alloc init securemanagedobjectcontext setpersistentstorecoordinatorcoordinator find missing date datamanager datamanager datamanager alloc init nsdate missingdate datamanager findmissingdatefromdateselecteddate incontextsecuremanagedobjectcontext if missingdate fetch and parse data datafetcher datafetcher datafetcher alloc init nsdictionary fetchresponse datafetcher parsedatafordatemissingdate persist it in a block and wait for it securemanagedobjectcontext performblock datastore datastore datastore alloc init bool parsingerror datastore persistdatafetchresponse incontextsecuremanagedobjectcontext if parsingerror handle error else thispatch asyncthispatch get main queue perform on main self fetchandpersist,"['ios', 'objective-c']" +542774,how to detect language changes while runtime c i want to detect when the user is changing his language on the keyboardfor example i want to know if the user is using english and then changing the language to frenchi want to detect this change from all the active threads i mean that i want to know when that change happens in the os and not in some specific threadi am using c languageconsole applicationcan anyone help me to figure it out i will be glad to some helpthank you,['c#'] +542777,nancyfx reflect changes immediately for static contents in aspnet whenever i am running my server in debug mode from vs2012any changes i make to static contents jscss etc are reflected immediately upon savingin nancyfx i need to restart my server everytime i make changes to static content i am assuming this is because vs needs to copy the static contents to output directory each time i run the serveris there anyway to reflect the changes made to static contents immediately upon savingheres my configuration for static contentspublic class mainbootstrapper defaultnancybootstrapper protected override void configureconventionsnancyconventions nancyconventions nancyconventionsstaticcontentsconventionsaddstaticcontentconventionbuilderadirectoryscripts baseconfigureconventionsnancyconventions this is probably relavant too i am running this under a console application with nancyfx main loop written like thisclass program const ushort port 64402 const string escapestring terminate static void mainstring args nancyhost host region making new instance of nancyhost var uri new urihttplocalhost port var config new hostconfiguration configurlreservationscreateautomatically true host new nancyhostconfig uri endregion region nancyfx hosting loop try hoststart consolewritestart hosting the fateanother ranking system frontendn t uri n to stop the hosting input escapestring nn do consolewrite while consolereadline escapestring catch exception e consolewritelineunhandled exception has been occuredn emessage consolereadkeytrue finally hoststop consolewritelinegoodbye endregion this will be ran under ubuntu w nginx in case youre wondering why i am not using nancyaspnethosting,"['c#', 'asp.net', '.net']" +542816,in c where does the key words come from if using system is commented for example we know that int type in c is nothing but a structure which is actually systemint32 if that so then if using system is commented in a program then int type should not be able to use but still int type can be used my question is from where these types are coming fromusing systemclass program static void main int x 0 it still work though int is under system namespace why,['c#'] +542824,self assignment in c i was looking through some code i wrote a while ago and realized i made an assumption about the assignment operator in c here is the line of code in question it works as expectedpointschecked pointschecked new listpointpointschecked is a list specified as a parameter to a recursive function it is a default parameter with default value null what i want to do is initialize it once and then build a collection of points that i have already checked so it should only be initialized during the first iterationmy assumption was that c is guarded against selfassignment in the same way that c operator should provide a guard when overloaded ie ifthis righthandside return this however i have not been able to find any resources that explicitly state that this is true for cthe closest example i found was this question about the nullcoalescing operator where it appears that the object is assigned back to itself if it is not null no one said anything about the selfassignment in that example but i want to be certain that this is not a bad practice and that there are no negative side effectssearching on msdn i also found that paraphrasing based on my understanding the value on the right hand side is copied over to the value on the left hand side and returned so i am again unsure if it is a bad thing to do a selfassignmenti know i could do the following to be saferifpointschecked null pointschecked new listpointbut i would rather understand what is actually happening with selfassignment,['c#'] +542829,convert string to binary in python i am in need of a way to get the binary representation of a string in python eg st hello worldtobinarystis there a module of some neat way of doing this,['python'] +542887,python datetime add i have a datetime value in string format how can i change the format from a separated date to a separated date i also need to add 6 hours to let the data be in my time zones 20130811 094849from datetime import datetimetimedeltamytime datetimestrptimesymd hmstime mytimestrftimeymd hmsdt strtimedeltaminutes660 6 hourstimedtprint timeprint dti get the following result where it adds the six hours at the end and not to the nine20130811 0948496060,['python'] +542891,how to force uilabel to draw a text with upper case chars how to force uilabel to draw a text with upper case chars,['ios'] +542904,passing shared ptr to lambda by value leaks memory i have the following code void myclassonopenmodalbtnclicked uimanagerloadldatauitestmodaljson stdshared ptruielement modal uimanagergetelementbyidloginmodal ifmodal modalgetelementbyidclosebuttononclicked modal modalhide this works fine and the modal is closed when the button is clicked onclicked is a stdfunctioni also have this at the beginning of my app if defineddebug defined debug crtsetdbgflag crtdbg alloc mem df crtdbg leak check dfendifthis prints out memory leaks when the app terminateswith the above code i get lots of memory leaks if i change the code to the below they are all gone void myclassonopenmodalbtnclicked uimanagerloadldatauitestmodaljson stdshared ptruielement modal uimanagergetelementbyidloginmodal ifmodal modalgetelementbyidclosebuttononclicked this uimanagergetelementbyidloginmodalhide i am assuming passing in the shared ptr by value increases the ref count by 1 and then this reference never goes out of scope or it goes out of scope after the mem leaks are reported so i tried to call reset inside the lambda after i used the shared ptr but then i get this compiler error error 1 error c2662 void stdshared ptr tyresetvoid throw cannot convert this pointer from const stdshared ptr ty to stdshared ptr ty so the question is how can i use the captured modal and not get those memory leaksedit so i got rid of the compile error by adding mutable to the lambdaifmodal modalgetelementbyidclosebuttononclicked modal mutable modalhide modalreset now if i click the close button and close the app there are no memory leaks since the reset cleans that reference but if the button is never clicked i still get the leaks,['c++'] +542923,testing if a list of integer is odd or even trying to determine if my list of integer is made of odd or even numbers my desired output is a list of true anor false can i perform the following operation on the list lst or do i need to create a loop a is the output list int lst new list int a isoddlst,['c#'] +542937,tomcat 7043 info error parsing http request header i use tomcat 7043 with a websocket application my app works fine in tomcat 7042 but with 43 i get the following output when i try to access my server on websocketssep 16 2013 30834 am orgapachecoyotehttp11abstracthttp11processor processinfo error parsing http request header note further occurrences of http header parsing errors will be logged at debug levelmy browser console shows the following websocket connection to wswtestappcomsocketnotification848df2e62fcf93e1b3xatmospheretrackingiadate0contenttypeapplicationjson20charsetutf8xatmoprotocoltrue failed unrecognized frame opcode 5 here is the access log for that request get socketnotification848df2e62fcf93e1b3xatmospheretrackingid0xatmosphereframework202javascriptxatmospheretransportwebsocketxatmospheretrackmessagesizetruexcachedate0contenttypeapplicationjson20charsetutf8xatmoprotocoltrue http11what has changed in tomcat 7043 what do i have to change,['java'] +542972,webdriverexception message the browser appears to have exited before we could connect the output was error no thisplay specified when run my test case any my test program try to start firefox i got error i am using robotframework selenium2library and python 271login warn keyword capture page screenshot could not be run on failure no browser is open fail webdriverexception message the browser appears to have exited before we could connect the output was error no thisplay specifiedni have xwindows on my centos server i installed firefox using yum my firefox was installed in firefox usrbinfirefox usrlib64firefox usrsharemanman1firefox1gzwhat is wrong here has anyone had similar experiences any references or advices thxeditthe results after i run demoslogin tests login testsinvalid login a test suite containing tests related to inval warn keyword capture page screenshot could not be run on failure no browser is openinvalid username fail parent suite setup failedwebdriverexception message the browser appears to have exited before we could connect the output was error no thisplay specifiedninvalid password fail parent suite setup failedwebdriverexception message the browser appears to have exited before we could connect the output was error no thisplay specifiedninvalid username and password fail parent suite setup failedwebdriverexception message the browser appears to have exited before we could connect the output was error no thisplay specifiednempty username fail parent suite setup failedwebdriverexception message the browser appears to have exited before we could connect the output was error no thisplay specifiednempty password fail parent suite setup failedwebdriverexception message the browser appears to have exited before we could connect the output was error no thisplay specifiednempty username and password fail parent suite setup failedwebdriverexception message the browser appears to have exited before we could connect the output was error no thisplay specifiednlogin testsinvalid login a test suite containing tests related fail suite setup failedwebdriverexception message the browser appears to have exited before we could connect the output was error no thisplay specifiedn 6 critical tests 0 passed 6 failed6 tests total 0 passed 6 failedlogin testsvalid login a test suite with a single test for valid login warn keyword capture page screenshot could not be run on failure no browser is openvalid login fail webdriverexception message the browser appears to have exited before we could connect the output was error no thisplay specifiednlogin testsvalid login a test suite with a single test for val fail 1 critical test 0 passed 1 failed1 test total 0 passed 1 failedlogin tests fail 7 critical tests 0 passed 7 failed7 tests total 0 passed 7 failedoutput rootdownloadsrobotframeworkselenium2librarydemooutputxmllog rootdownloadsrobotframeworkselenium2librarydemologhtmlreport rootdownloadsrobotframeworkselenium2librarydemoreporthtml,['python'] +543033,writing multiline strings to cells using xlwt module python is there a way to write multiline strings into an excel cell with just the xlwt module i saw answers suggesting use of openpyxl modulethe sheetwrite method ignores the and escape sequence so just xlwt is it possible thanks in advance,['python'] +543079,weird storyboard push segue when updating app to ios 7 currently i am updating my app for ios 7 when i build and run the app it works but the layout needs some serious tweaking that is not the problemwhen i navigate to another view in the application the screen gets pushed for about 50 and thisappears then the attached image describes the problemthe application uses a storyboard and the storyboard segue is just a simple push segue within a navigation controller,"['ios', 'iphone', 'objective-c']" +543086,how to place two divs side by side where left one is sized to fit and other takes up remaining space i am trying to place two divs beside each other with the following criteriaboth divs must stay on the same linepriority must be given to the left div as much text as possible should be thisplayed in the left div up to the point where ellipsis is used in case of overflowthe right divs text should be right aligned in the case of overflow ellipsis should be usedtext is dynamic so no percentages or fixed widths can be usedonly needs to work on webkit based browser so css3 solution is preferredhere are some sample images of how it would lookinputdiv classlefti should always fit if not ellipsis should be useddivdiv classrightright align and fit me if space available heredivoutputinput div classlefti should always fit if not ellipsis should be used and some more text and more and more textdivdiv classrightright align and fit me if space available heredivoutputinputdiv classleftthis text is left aligneddivdiv classrightthis text is right aligneddivoutput,['html'] +543124,passing by value and copy elision optimization i came upon the article authors advice donat copy your function arguments instead pass them by value and let the compiler do the copyinghowever i do not quite get what benefits are gained in the two example presented in the article do not t toperatort const x x is a reference to the source t tmpx copy construction of tmp does the hard work swapthis tmp trade our resources for tmps return this our old resources get destroyed with tmp vs do t operatort x x is a copy of the source hard work already done swapthis x trade our resources for xs return this our old resources get destroyed with x in both cases one extra variable is created so where are the benefits the only benefit i see is if the temp object is passed into second example,['c++'] +543129,translation animation for hiding view i need my listview to hide and show using alternative touches hence for hiding the listview on the left side of the screen am using animation animation animation new translateanimation100 00 0 animationsetduration100 animationsetfillaftertrue lvstartanimationanimation lvsetvisibility0and for thisplaying am using lvsetvisibilityviewvisiblemy problem is list view is not getting hide it will go leftside and coming back again i do not know how to hide listview to the left edge completely on touch please help in achieving this,['android'] +543134,phonegap cordova is laggy and slow on android and ios devices i just now started with my first phonegap project using zend studio but after i build and deploy it the application is quite slow both on android and ios the scrolling is lagging and if i press a button it is slow to goto the next page is there any way to improve it is performance thanks in advance,"['android', 'ios']" +543148,are there any advantages of using static import over import consider the following classpublic final class constant public static final string user nameuser1 more constant herethis class in the package bnow i am going to use this in package a consider following two ways which can usemethod 1 use import bconstant import bconstantpublic class validateuser public static void mainstring args ifconstantuser nameequalsuser1 method 2 use import static bconstantuser nameimport static bconstantuser namepublic class validateuser public static void mainstring args ifuser nameequalsuser1 my question is is there any difference or advantage normal import over static import in this case,['java'] +543157,how to get a index value from foreach loop in jstl i have a value set in the request object like the followingstring categorieslistnullcategorieslist enginegetcategorynamesarrayrequestsetattributecategorieslist categorieslist and this is how i iterate in jsp page ifrequestgetattributecategorieslist null cforeach varcategoryname itemscategorieslist lia onclickgetcategoryindex hrefcategorynamealicforeach how do i get index of each element and pass it to javascript function onclickgetcategoryindex,['java'] +543167,what is the hashkey added to my jsonstringify result i have tried looking on the mozilla json stringify page of their docs as well as here on so and google but found no explanation i have used json stringify many time but never come across this resulti have an array of json objects param 2 description 1 param 0 name 1 param 1 version 1 param 2 description 2 param 0 name 2 param 1 version 2 param 2 description 3 param 0 name 3 param 1 version 3 attached to my scope and in order to post them as one paramater i used the jsonstringify method and i get the following param 2 description 1 param 0 name 1 param 1 version 1 hashkey 005 param 2 description 2 param 0 name 2 param 1 version 2 hashkey 006 param 2 description 3 param 0 name 3 param 1 version 3 hashkey 007 i am just curious what exactly is the hashkey as i expected something more similar to the following from the stringify method 1 param 2 description 1 param 0 name 1 param 1 version 1 2 param 2 description 2 param 0 name 2 param 1 version 2 3 param 2 description 3 param 0 name 3 param 1 version 3 i am not sure if it is a factor but i am using angularjs 115 jquery 182 and spring 304 and spring security 307 on the server sideit is not causeing me any issues but i would like to know the cause and reason for the hashkey,"['javascript', 'jquery']" +543202,median filter of masked arrays i have seen several thiscussions in this forum about calculating the median of masked arrays such as images what i want is slightly more subtle it is to apply a median filter on my image i know a way to do it but is far too slow and would appreciate ways of speeding the process upfor example assume i have a masked array of shape 1010 and i want to apply a median filter with a box 33 not using those elements that are masked my goal is to substitute the value in each pixel of the image with the value of the masked median of the box assuming a very simple case we can build the image and the mask as im numpyrandomuniformsize1010 mask numpyzeros likeim mask13 1 masked im numpymaarrayim maskmasknow to actually make the median filter we can do it on a bruteforce way with lx ly imshape side 3 im filt numpyzeros likeim for jj in rangely for ii in rangelx minx maxx maxiiside20 miniiside21lx miny maxy maxjjside20 minjjside21ly im filtiijj numpymamedianmasked imminxmaxx minymaxythis solves the problem and gives a good result but as i said it is painfully slow one to me surprising way to slightly speed up the process is to use the mask and the image separately like im filt2 numpyzeros likeim for jj in rangely for ii in rangelx minx maxx maxiiside20 miniiside21lx miny maxy maxjjside20 minjjside21ly zoom im imminxmaxx minymaxy zoom msk maskminxmaxx minymaxy im filt2iijj numpymedianzoom imzoom msk 0 this brings the execution time from 0018 to 02 which is obviously better why if not by the factor 50 that i was looking for any input,['python'] +543215,devise several models spread across engines i have a rails app comprising several engines that are mounted in combinations at a time there is one engine for b2b side of the app where we have a separate user modellike a company for devise authentication similarly there is one for end customers which again has its own model for authenticationlike users for the company similarly there is another engine for the site admin that is implemented using activeadmin for root level administrationwe might mount one two or three engines at the same time in several combinations the problem is that we have different parent application controllers for each of them and different routers for each of them too something likedeviserb engine1configrouter name engine1configparent controller engine1applicationcontrollerdeviserb engine2configrouter name engine2configparent controller engine2applicationcontrollerbut of course i cannot have multiple conflicting config filesi need help on how i can implement something like this on devise,['ruby-on-rails'] +543301,sqlalchemy sessionrefresh does not refresh object i have the following mapping straight from sa examplesclass userbase tablename users id columninteger primary keytrue name columnstring fullname columnstring password columnstringi am working with a mysql db and the table has an innodb enginei have a single record in my table1user1user1 testpasswordi have opened a session with the following codefrom sqlalchemyormsession import sessionmakerfrom sqlalchemyengine import create enginefrom sqlalchemyormscoping import scoped sessionfrom sqlalchemyextdeclarative import declarative basebase declarative basedb engine create enginemysqllocalhosttest dbcharsetutf8echofalsepool recycle1800session factory sessionmakerbinddb engineautocommitfalseautoflushfalsesession maker scoped sessionsession factorysession session makeruser 1 sessionqueryuserfilteruserid1oneuser 1name this prints uuser1now when i change the records name in the db to user1 change and commit it and then refresh the object like thissessionrefreshuser 1user 1name this still prints uuser1 and not uuser1 changeit still prints uuser1 and not uuser1 changewhat am i missing or setting up wrong herethanks,['python'] +543337,sorting a string vector based on the string size i wanted to know how i can sort a string vector such that the string with the least amount of characters is on top of the vector for instance if the vector has abcdabcdeabc in it abc gets to the topi would be interested to know how this could be achieved with sort if and what the predicate would look like any other methods are also welcome,['c++'] +543352,jquery smooth scroll to div using id value from link so i am having some issues with my jquery which is suppose to scroll to particular divshtmldiv idsearchbycharacter a clasearchbychar href id09 onclickreturn false09 a a clasearchbychar href ida onclickreturn false a a a clasearchbychar href idb onclickreturn false b a a clasearchbychar href idc onclickreturn false c a untill zdivdiv id09 psome contentpdivdiv ida psome contentpdivdiv idb psome contentpdivdiv idc psome contentpdiv untill zjquerywhat i want the code to do is on click event of an searchbychar a tag take the id attributes value and scroll to that searchbychar clickfunction html bodyanimate scrolltop searchbycharattridoffsettop 20,"['javascript', 'jquery', 'html']" +543379,android nullpointerexception on searchview in action bar i have got a problem trying to add a searchview widget to the actionbar in my activity i get a null value when calling getactionview to get my searchview objecti have been following the android developer guide and also went through a ton of so questions as well as some other links on the internet all to no avail it could be something simple but i was not able to figure it out it seems to me my code is basically the same as that from google apart from changing some names etc but it still would not workany help would be appreciatedincluded below are relevant bits of the code please let me know if anythings unclear of if you have any idea as to what could possibly be wrongactivity code private listview workflowlistview private drawerlayout drawerlayout private listview drawerlist private actionbardrawertoggle drawertoggle override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate getwindowrequestfeaturewindowfeature action bar setcontentviewrlayoutactivity workflow list workflowlistview listview findviewbyidridworkflowlistview drawerlayout drawerlayout findviewbyidriddrawer layout drawerlist listview findviewbyidriddrawer list drawertoggle new actionbardrawertoggle this host activity drawerlayout drawerlayout object rdrawableic launcher nav drawer icon to replace up caret rstringapp name open drawer description rstringapp name close drawer description called when a drawer has settled in a completely closed state public void ondrawerclosedview view getactionbarsettitleclosed drawer called when a drawer has settled in a completely open state public void ondraweropenedview drawerview getactionbarsettitleopen drawer drawerlayoutsetdrawerlistenerdrawertoggle actionbar actionbar getactionbar actionbarsetthisplayshowtitleenabledfalse actionbarsetthisplayhomeasupenabledtrue actionbarsethomebuttonenabledtrue actionbarseticonandroidrcolortransparent string testdata a b c d arrayliststring workflowlist new arrayliststring for string s testdata workflowlistadds arrayadapterstring workflowadapter new arrayadapterstringthisgetapplicationcontext rlayoutworkflow list item workflowlist workflowlistviewsetadapterworkflowadapter override public boolean oncreateoptionsmenumenu menu inflate the menu this adds items to the action bar if it is present menuinflater inflater getmenuinflater inflaterinflatermenuworkflow list menu inflaterinflatermenuoptions menu menu associate searchable configuration with the searchview searchmanager searchmanager searchmanager getsystemservicecontextsearch service the below line returned null even though it was used in google sample code searchview searchview searchview menufinditemridsearchgetactionview searchviewsetsearchableinfosearchmanagergetsearchableinfogetcomponentname return superoncreateoptionsmenumenu xmlsearchablexmlxml version10 encodingutf8searchable xmlnsandroid androidlabelstringapp name androidhintstringsearch hint androidincludeinglobalsearchfalse menuoptions menuxmlxml version10 encodingutf8menu xmlnsandroid xmlnsapp item androidididsearch androidtitlestringsearch title androidicondrawableic action search androidshowasactionalwayscollapseactionview androidactionviewclassandroidsupportv7widgetsearchview menu,['android'] +543408,webrtc for realtime scaling i am looking for a cheapo solution to realtime scaling for many users in 1 channeli am using sockjs but scaling is pretty annoying when talking about really large numbersi am thinking about using webrtc to decrease cost with p2p instead of the server connecting to all users it would connect to only limited number of users who would then thistribute their data to the p2p network through webrtc is this sensible whats the easiest way to implementthe information is not private and a few seconds 5s of latency is acceptable,['javascript'] +543444,extend basic types in typescript error this is not defined i am trying to rewrite some of my javascript code in typescript some of this code has references to an extension i added to the string object prototypestringprototypeformat function var formatted this for var i 0 i argumentslength i formatted formattedreplace regexp i g argumentsitostring return formattedhowever adding this with type script has been quite challengingi have seen examples where you declare an extension of a basic interface then assign an function to the prototype to match the interface and provide your functionality like sointerface string showstring stringstringprototypeshowstring string return thisexcept this errors because this is not definedthe other things i have tried is to create a new class to extend stringexport class morestring extends string however this also does not work because you can only extend classes and stringstring are not classes but built in typeswhat is the simplest way to extend string and access my extension method,['javascript'] +543457,how to draw a line on a canvas using fabricjs i am using fabricjs to draw a line on a canvas this is my code but i am not getting any outputlineclickfunction alertline canvasaddnew fabricline50 100 200 200 left 170 top 150 fill red,['jquery'] +543464,android google chrome not firing after lockscreen app i have a lockscreen app my activity is the first when the user hits unlock power button i have a website link on the lockscreenapp when the patternunlock is thisabled chrome gets fired with the the website link but when i enable the security pattern after the user enters his pattern chrome app opens but the website is not fired patternlock enabled mylockscreenapp click the link goes to default lockscreen user enters pattern chrome launches but not the websitepatternlock thisable mylockscreenapp click the link chrome launches but not the websitei am using below to launch the websiteurlhttpany urlintent i new intentintentaction viewisetdatauriparseurlstartactivityiwould be glad to get this solved any experts,['android'] +543552,how to run shell commands on server in capistrano v3 i am new to capistrano and i have tried using capistranos dsl to run shell commands on the server run execute etc but it appears that it was deprecated after searching and searching for a functional equivalent i still am lostcurrent codedesc do somethingtask do something execute echo sometextendoutput cap aborted undefined method execute for mainobject usersjustindropboxcapfile45in block 2 levels in top required usersjustinrvmgemsruby200p247bundlergemscapistrano2dc1627838f9libcapistranoapplicationrb12in run usersjustinrvmgemsruby200p247bundlergemscapistrano2dc1627838f9bincap3in top required usersjustinrvmgemsruby200p247bincap23in load usersjustinrvmgemsruby200p247bincap23in main usersjustinrvmgemsruby200p247binruby noexec wrapper14in eval usersjustinrvmgemsruby200p247binruby noexec wrapper14in main tasks top deploydo something,['ruby'] +543563,initialize an eigenmatrixxd from a 2d stdvector this should hopefully be pretty simple but i cannot find a way to do it in the eigen documentation say i have a 2d vector ie stdvectorstdvectordouble dataassume it is filled with 10 x 4 data set how can i use this data to fill out an eigenmatrixxd matthe obvious way is to use a for loop like thispseudo codeeigenmatrixxd mat10 4for i 1 10 mati 0 datai0 mati 1 datai1 endbut there should be a better way that is native to eigen,['c++'] +543588,an error occurred while installing mysql2 0311 i am a rails beginnerand i get a demo from but when i try to run this demoi got an errori run followbundlei got the erroran error occurred while installing mysql2 0311 and bundler cannot continuemake sure that gem install mysql2 v 0311 succeeds before bundlingbut i can sure i have install mysql2and the gemfile is source ruby 193gem rails 3212group assets do gem sassrails 323 gem coffeerails 321 see for more supported runtimes gem therubyracer platforms ruby gem uglifier 103end bundle edge rails instead gem rails git gitgithubcomrailsrailsgitgem devise 213gem mysql2gem babosagem rails autolinkgem settingslogicgem seo helpergem open graph helpergem google plus helpergem exception notificationgem mobilefugem capistrano group developmentgem rake group testgroup development do gem capistrano gem magic encoding gem annotateendgroup test development do gem rspec gem rspecrails gem simplecov gem capybaraendthen i try to comment this rowgem mysql2but i still got the errorso i do not know why this error occurs,"['ruby-on-rails', 'ruby']" +543613,will using list comprehension to read a file automagically call close does the following syntax close the filelines linestrip for line in opensomefilesomewherebonus points if you can demonstrate how it does or does nottia,['python'] +543616,sql bulk copyinsert in c i am new to json and sqlbulkcopy i have a json formatted post data that i want to bulk copyinsert in microsoft sql using cjson format urls url name google url address url name yahoo url address url name fb url address url name megasearches url address classespublic class urldata public listurl urls getsetpublic class url public string url address getset public string url name getsethow can i do that efficiently,"['c#', '.net', 'sql']" +543651,jersey 22 containerresponsefilter and containerrequestfilter never get executed following the getting started guide on the jersey websitei executed the following build command mvn archetypegenerate darchetypeartifactidjerseyquickstartgrizzly2 darchetypegroupidorgglassfishjerseyarchetypes dinteractivemodefalse dgroupidcomexample dartifactidsimpleservice dpackagecomexample darchetypeversion22i then followed the tutorial onto add a custom containerresponsefilternamebindingretentionretentionpolicyruntimestatic interface corsbinding providerpriorityprioritiesheader decoratorcorsbindingstatic class crossdomainfilter implements containerresponsefilter override public void filtercontainerrequestcontext creq containerresponsecontext cres loggergetloggercomexamplelog levelinfo before 0 cresgetheaders cresgetheadersaddaccesscontrolalloworigin cresgetheadersaddaccesscontrolallowheaders origin contenttype accept authorization cresgetheadersaddaccesscontrolallowcredentials true cresgetheadersaddaccesscontrolallowmethods get post put delete options head cresgetheadersaddaccesscontrolmaxage 1209600 loggergetloggercomexamplelog levelinfo after 0 cresgetheaders providerstatic class myresponsefilter implements containerresponsefilter override public void filtercontainerrequestcontext requestcontext containerresponsecontext responsecontext throws ioexception systemoutprintlnmyresponsefilterpostfilter enter responsecontextsetentity responsecontextgetentity getclassgetsimplename null mediatypetext plain type systemoutprintlnmyresponsefilterpostfilter exit getproducesmediatypetext plaincorsbindingpublic string helloworld return hello worldi tried to register this filter with named binding and with dynamic binding nothing worksto easily reproduce i also tried an example from the official resourcesthe same problem the custom filters do not get executedis this a grizzly problem,['java'] +543673,how to add curling effect in view pager i am using webview in view pager to show html content but now i need to implement curl effect on viewpager i searched a lot but found nothing is it possible to do so if yes then please help me thanks in advance,['android'] +543731,mysql group concat thistinct multiple columns i have a tag field for a blog posts tags have unique id but their thisplayname might be duplicated what i want is a query that selects posts and in all tags field we get couples of idthisplayname is this wayid1name1id2name2id3name3my query looks likeselect concat ws thistinct concat wstagsidtagsthisplayname as all tagsjoin post content join post tags join tags order by postsidthis line causes problemconcat ws thistinct concat wstagsidtagsthisplayname as all tagshow should i modify itsome people use an inner select from but as i have heard it is so inefficienselect postscategoriescreatorseditorsconcat ws thistinct group concatconcat wstagsidtagsthisplayname as all idsfrom posts left join languages on postslanguage idlanguagesid left join users as creators on postscreatoruser idcreatorsid left join users as editors on postslasteditoruser ideditorsid left join userprofiles as editors profile on editorsprofile ideditors profileid left join categories on postscategory idcategoriesid left join posttags on posttagspost idpostsid left join tags on posttagstag idtagsid left join posttags as nodetag checks on nodetag checkspost idpostsid left join tags as tag checks on nodetag checkstag idtag checksid where 9 intag checksidtag checkscached parents or 10 intag checksidtag checkscached parents or 11 intag checksidtag checkscached parents group by postsid order by postscreated desc limit 0 20,['mysql'] +543848,javascript array to csv i have followed this post how to export javascript array info to csv on client side to get a nested js array written as a csv filethe array looks likevar test array name1 2 3 name2 4 5 name3 6 7 name4 8 9 name5 10 11the code given in the link works nicely except that after the third line of the csv file all the rest of the values are on the same lineegname123name245name367name489name51011 etc etccan anyone shed any light on why this is same using chrome or ffthankseditjsfiddle iain,['javascript'] +543889,emberjs trigger an action programmatically i have this view appapplicationview emviewextend templatename application actions myaction function suppose i want to trigger manually that action from another view method such as didinsertelement like appapplicationview emviewextend templatename application actions sidebarshowhome function thissetsidebarishome true thissetsidebarisnotifications false thissetsidebarisarchive false didinsertelement function thisactionssidebarshowhome how could i do it thisactions is undefined from within a view method,['javascript'] +543945,javascript unit testing dom manipulation i am quite new to javacript unit testing one thing keep bothering me when testing javascript we often need to do the dom manipulation it looks like i am unit testing a methodfunction in a controllercomponent but i still need to depend on the html elements in my templates once the idor attributes used to be selectors in my test cases is changed my test cases also need to be changed wouldnt this violate the purpose of unit testing,['javascript'] +543995,saxparseexception srcresolve cannot resolve the name to an type definition component i am trying to do schema validation currently using a javaxxmlvalidationschemafactory unfortunately when i call the newschemasource schema function i get the following errorcaused by orgxmlsaxsaxparseexception systemid filecusersc42056documentsworkspacests320releasececsamplewsintegration2wartargetclasseswebinfschemasxsdindividualprivatecomponenttypes 4 0xsd linenumber 33 columnnumber 88 srcresolve cannot resolve the name utilityobjectstatusdatetype to an type definition componentat orgapachexercesutilerrorhandlerwrappercreatesaxparseexceptionunknown sourceat orgapachexercesutilerrorhandlerwrappererrorunknown sourceat orgapachexercesimplxmlerrorreporterreporterrorunknown sourceat orgapachexercesimplxstraversersxsdhandlerreportschemaerrorunknown sourceat orgapachexercesimplxstraversersxsdhandlerreportschemaerrorunknown sourceat orgapachexercesimplxstraversersxsdhandlergetglobaldeclunknown sourceat orgapachexercesimplxstraversersxsdelementtraversertraversenamedelementunknown sourceat orgapachexercesimplxstraversersxsdelementtraversertraverselocalunknown sourceat orgapachexercesimplxstraversersxsdhandlertraverselocalelementsunknown sourceat orgapachexercesimplxstraversersxsdhandlerparseschemaunknown sourceat orgapachexercesimplxsxmlschemaloaderloadschemaunknown sourceat orgapachexercesimplxsxmlschemaloaderloadgrammarunknown sourceat orgapachexercesimplxsxmlschemaloaderloadgrammarunknown sourceat orgapachexercesjaxpvalidationxmlschemafactorynewschemaunknown sourceat comseiecxmlvalidationsimplexmlvalidatorloadschemasimplexmlvalidatorjava70at comseiecxmlvalidationsimplexmlvalidatorinitsimplexmlvalidatorjava83 75 morethe utilityobjectstatusdatetype element is used in the xsd file which i am passing into the newschemasource schema function i am importing the objectstatusdatetype from another xsd file for which i have tripple checked the file path the utility namespace is also declared properlyheres a snippet of the schema i am passing into the function locatecoverageindexesbyidentifier 3 0xsdxsimport namespace schemalocationutilityinvocationoutcome 1 0xsdxsimport namespace schemalocationutilityobjecthistory 1 0xsdxsimport namespace schemalocationprivatecomponenttypes 4 0xsdxsimport namespace schemalocationindividualtypes 5 0xsd some more stuff xselement namecoverageperiod typeutilityobjectstatusdatetype minoccurs0and this is from objecthistory 1 0xsdxsschema xmlnsxs xmlnstns targetnamespace elementformdefaultqualified attributeformdefaultunqualified version10 some more stuff xscomplextype nameobjectstatusdatetype xssequence xselement nameeffectivedate typexsdate xselement namecanceldate typexsdate minoccurs0 xssequence xscomplextypeand lastly the beanbean idlocateclaimvalidator classcomseiecxmlvalidationsimplexmlvalidator constructorarg valueclasspathwebinfschemasxsdindividualcilocatecoverageindexesbyidentifier 3 0xsd value constructorargbeanhas anybody encountered this type of issue before,['java'] +543997,how to get mic volume in ios 7 there a view to get mic volume in ios 7nsurl url nsurl fileurlwithpathdevnullnsdictionary settings nsdictionary dictionarywithobjectsandkeys nsnumber numberwithfloat 4410 avsampleratekey nsnumber numberwithint kaudioformatapplelossless avformatidkey nsnumber numberwithint 0 avnumberofchannelskey nsnumber numberwithint avaudioqualitymax avencoderaudioqualitykey nilnserror errorrecorder avaudiorecorder alloc initwithurlurl settingssettings errorerrorif recorder recorderdelegate self recorder preparetorecord recordermeteringenabled true recorder record leveltimer nstimer scheduledtimerwithtimeinterval 01 target self selector selectorleveltimercallback userinfo nil repeats yes else nslog mic error message voidleveltimercallbacknstimer timer recorder updatemeters const double alpha 005 double peakpowerforchannel pow10 alpha recorder averagepowerforchannel0 db 20 log10peakpowerforchannel db taraturadb db db 0 0 db lowpassresults alpha peakpowerforchannel 10 alpha lowpassresults if lowpassresults 095 nslogfdbthis that worked in ios6 does not work in ios 7thanks,['ios'] +544013,whats the best way to split a string into fixed length chunks and work with them in python i am reading in a line from a text file using file urllib2urlopenreadsplitlinesand outputting it to an lcd thisplay which is 16 characters wide in a telnetlibwrite command in the event that the line read is longer than 16 characters i want to break it down into sections of 16 character long strings and push each section out after a certain delay eg 10 seconds once complete the code should move onto the next line of the input file and continuei have tried searching various solutions and reading up on itertools etc but my understanding of python just is not sufficient to get anything to work without doing it in a very long winded way using a tangled mess of if then else statements that is probably going to tie me in knotswhats the best way for me to do what i want,['python'] +544041,session control with google analytics api v3 for ios i just replaced ga implementation with api v3 and found this useful session managing featuresince i implemented every session is measured 0did anybody managed to use thisor something is messed in my client codethe time interval based session calculations gives inaccurate data for my needs,['ios'] +544077,complex number equals method i am making a complex number class in java like thispublic class complex public final double real imag public complexdouble real double imag thisreal real thisimag imag methods for arithmetic follow i implemented the equals method like thisoverridepublic boolean equalsobject obj if obj instanceof complex complex other complexobj return thisreal otherreal thisimag otherimag return falsebut if you override equals youre supposed to override hashcode too one of the rules isif two objects are equal according to the equalsobject method then calling the hashcode method on each of the two objects must produce the same integer resultcomparing floats and doubles with does a numeric comparison so 00 00 and nan values are inequal to everything including themselves so i tried implementing the hashcode method to match the equals method like thisoverridepublic int hashcode long real doubledoubletolongbitsthisreal harmonize nan bit patterns long imag doubledoubletolongbitsthisimag if real 1l 63 real 0 convert 00 to 00 if imag 1l 63 imag 0 long h real imag return inth inth 32but then i realized that this would work strangely in a hash map if either field is nan because thisequalsthis will always be false but maybe that is not incorrect on the other hand i could do what double and float do where the equals methods compare 00 00 but still harmonize the different nan bit patterns and let nan nan so then i getoverridepublic boolean equalsobject obj if obj instanceof complex complex other complexobj return doubledoubletolongbitsthisreal doubledoubletolongbitsotherreal doubledoubletolongbitsthisimag doubledoubletolongbitsotherimag return falseoverridepublic int hashcode long h doubledoubletolongbitsreal doubledoubletolongbitsimag return inth inth 32but if i do that then my complex numbers do not behave like real numbers where 00 00 but i do not really need to put my complex numbers in hash maps anyway i just want to do the right thing follow best practices etc and now i am just confused can anyone advise me on the best way to proceed,['java'] +544165,windows 8 thistorts my trayicon windows 8 appears to make tray icons be 20 x 20 pixels it seems as though java still thinks they should be 16 x 16 pixels this is causing some bad thistortion as java scales things down and then windows scales things back up the following example uses these three images to create three tray icons that look like this note the thistortion import javaawtimageimport javaawtsystemtrayimport javaawttoolkitimport javaawttrayiconpublic class traytest public static void mainstring args throws exception final systemtray tray systemtraygetsystemtray trayicon trayicon16 new trayicongetimage16pxbluepng trayaddtrayicon16 trayicon trayicon20 new trayicongetimage20pxredpng trayaddtrayicon20 trayicon trayicon20autosize new trayicongetimage20pxgreenpng trayicon20autosizesetimageautosizetrue trayaddtrayicon20autosize public static image getimagestring resource return toolkitgetdefaulttoolkitcreateimagetraytestclassgetresourceresource this is what the whole thing looks like magnified with pixel lines added opening image in a new tab will give you a clearer viewmy questionhow can i prevent java windows 8 from thistorting my icons,['java'] +544184,how to apply xslt 20 transformations in net i understand that the net xsltcompiledtransformation class supports only xslt 10 transformations and microsoft has no plans to even introduce support for xslt 20i have looked at software for performing xslt 20 transformationsthe problem is that i need an alternative to microsofts xsltcompiledtransformation class that will apply transformations on the fly in my programis there a solution out there that does what i want an opensource solution would be great but a commercial solution could be acceptable too,['.net'] +544188,how to replace session register for php 54 out of the blue i was getting the following error when logging in to one of my sites call to undefined function session registerafter some research i saw that session register is deprecated after php 54 i checked in my hosting control panel and sure enough it says current version i am running is php 5419 i assume they just forced an upgrade which is why this problem seemed to occur out of the blue i looked through several stack overflow posts and reviewed links to php documentation from what i gather session register is deprecated and should be replaced with session instead problem is both of those already appear in my code here is the code in my indexphp file 53 if username 54 session registeradmin 55 sessionadmin username 56 so i hoped just by removing line 54 the deprecated piece then it should work however that is not the case it broke the code when i did that based on other posts i read here and here they seem to be saying that the code i see in line 55 above should by itself do the trick so i am a bit confused why it did not work if anyone can tell me what code i should use i would sincerely appreciate it the developer of the script is not really offering support note also yes there is session start called at the very top of the page,['php'] +544264,composer laravel create project i am trying to use laravel when i start a project and type composer createproject applicationsmamphtdocstest laravel in terminal it shows invalidargumentexception could not find package applicationsmamphtdocstest laravel with stabilit y stable and createproject sstability prefersource preferthist repositoryurl dev nodev noplugins nocustominstallers noscripts noprogress keepvcs package directory versionhow to fix it and is this step equal to create folder and file like i download from laravel git laravelmasterzip mamp php5410,['php'] +544332,touchstart event never be triggered on android chrome at the first time of page loading on android chrome when you create a new tab and access to a page with the content below your touches to touch div have never triggered touchstart events once you reload the page you can trigger the eventwhy and how can i avoid this situationdoctype htmlhtmlhead meta charsetutf8 titletouch start on androidtitle style typetextcss touch click position relative left 100px top 100px width 200px height 200px border solid 1px black styleheadbody div idtouchtouchdiv div idclickclickdiv script typetextjavascript documentgetelementbyidtouchaddeventlistenertouchstart function alert touch false documentgetelementbyidclickaddeventlistenerclick function alertclick false scriptbodyhtmlmy environment isnexus 7 2013android 430 build number jss15qchrome 290154772 webkit version 53736156722 javascript version v8 3191821,"['javascript', 'android']" +544339,bootstrap tr class warning does not work in stripedtable i have got a table defined table classtable tablestriped with some rows like tr clasuccess tr classinfo and tr classwarningthe success and info tablerows show up fine red and blue just as they should be but the warning rows do not show yellow as expected they are just regular zebrastripe white or grayweird thing is if i add tablehover to the tables classes the warning rows will show yellow but only when hovered the success and info rows however always show their colors hover or no,"['html', 'css']" +544382,javalangstringindexoutofboundsexception while playing video in videoview android v 421 i am getting this crash when i play video on videoview in android version 421 i found this out specifically on micromax canvas a210 device it is not showing any message where the error is occurring is this a bug or something wrong in application the crash log is as below 0918 110553245 eandroidruntime2323 fatal exception main0918 110553245 eandroidruntime2323 javalangstringindexoutofboundsexception length11 regionstart0 regionlength10918 110553245 eandroidruntime2323 at javalangstringstartendandlengthstringjava5830918 110553245 eandroidruntime2323 at javalangstringsubstringstringjava14640918 110553245 eandroidruntime2323 at androidwidgetvideoviewopenvideovideoviewjava4070918 110553245 eandroidruntime2323 at androidwidgetvideoview6surfacecreatedvideoviewjava7300918 110553245 eandroidruntime2323 at androidviewsurfaceviewupdatewindowsurfaceviewjava6060918 110553245 eandroidruntime2323 at androidviewsurfaceviewaccess0surfaceviewjava880918 110553245 eandroidruntime2323 at androidviewsurfaceview3onpredrawsurfaceviewjava1830918 110553245 eandroidruntime2323 at androidviewviewtreeobserverthispatchonpredrawviewtreeobserverjava6920918 110553245 eandroidruntime2323 at androidviewviewrootimplperformtraversalsviewrootimpljava21230918 110553245 eandroidruntime2323 at androidviewviewrootimpldotraversalviewrootimpljava11390918 110553245 eandroidruntime2323 at androidviewviewrootimpltraversalrunnablerunviewrootimpljava48790918 110553245 eandroidruntime2323 at androidviewchoreographercallbackrecordrunchoreographerjava7760918 110553245 eandroidruntime2323 at androidviewchoreographerdocallbackschoreographerjava5790918 110553245 eandroidruntime2323 at androidviewchoreographerdoframechoreographerjava5480918 110553245 eandroidruntime2323 at androidviewchoreographerframethisplayeventreceiverrunchoreographerjava7620918 110553245 eandroidruntime2323 at androidoshandlerhandlecallbackhandlerjava7250918 110553245 eandroidruntime2323 at androidoshandlerthispatchmessagehandlerjava920918 110553245 eandroidruntime2323 at androidoslooperlooplooperjava1530918 110553245 eandroidruntime2323 at androidappactivitythreadmainactivitythreadjava52970918 110553245 eandroidruntime2323 at javalangreflectmethodinvokenativenative method0918 110553245 eandroidruntime2323 at javalangreflectmethodinvokemethodjava5110918 110553245 eandroidruntime2323 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava8330918 110553245 eandroidruntime2323 at comandroidinternaloszygoteinitmainzygoteinitjava60918 110553245 eandroidruntime2323 at dalviksystemnativestartmainnative methodother versions and devices that i have tested my app on and is working fine areandroid versions 412 422 43 233 403 404devices samsung galaxy s2 samsung galaxy tab 2 7 and 10 samsung galaxy s plus sony xperia tipo dual samsung galaxy grand quatro and mega nexus 4,['android'] +544414,why phonegap always shows default splashscreen image i am testing a sample ios app now although i set all new launch images in xcode summary tab of project target screen phonegap 30 keeps showing its default splashscreen why even when splashscreen is a plugin and not included by default in phonegap 30 nowios document say about launch images but not splashscreen and it even strongly recommend us to use a first screen similar as launch image not something like about screen are these same,['ios'] +544437,check if list is empty in c i have a list of objects populated from the databasei need to thisplay an error message if the list is empty and thisplay the grid view otherwise,['c#'] +544447,why can reinterpret cast not convert an int to int my compiler is the latest vc 2013 rcvoid f int n1 0 int n2 reinterpret castintn1 error c2440error c2440 reinterpret cast cannot convert from int to intwhy can reinterpret cast not be used in such an obvious case,['c++'] +544491,c11 stdarray vs static array vs stdvector first question is it a good thing to start using c11 if i will develop a code for the 3 following yearsthen if it is what is the best way to implement a matrix if i want to use it with lapack i mean doing stdvectorstdvector type matrix is not easily compatible with lapack up to now i stored my matrix with type matrixnew typen the pointer form with new and delete were important because the size of the array is not given as a number like 5 but as a variable but with c11 it is possible to use stdarray according to this site this container seems to be the best solution what do you think,['c++'] +544573,what is the best way to include custom font using css to make it compatible with maximum browsers i have tried various codes to embed custom font and finally following seems to work in ff ie8 above but it does not support in ie7fontface fontfamily xyzfontsrc urlfontsabcfonteot formateot urlfontsabcfontwoff formatwoff urlfontsabcfontf formattruetypeh1 h2 h3 div span fontfamily xyzfont georgia arial any suggestion to make it more compatible such as ie7 most welcome,"['html', 'css']" +544575,how to detect ie 11 with javascript in aspnet hello i want to detect the browser ie 8 or more will be appropriate for me for this i used following code but it fails for ie 11 for other its detecting properlyfunction getinternetexplorerversion var rv 1 return value assumes failure if navigatorappname microsoft internet explorer var ua navigatoruseragent var re new regexpmsie 091090 if reexecua null rv parsefloatregexp1 return rvbelow is the link which also i tried but could not succeed,"['javascript', 'asp.net']" +544605,how to get to model or viewbag variables in a script tag vs12 aspnet c mvc4 intappltemplate ef code firsthere is my very simple scriptscript classtractsscript addclickfunction e var val viewbagforsection alertval scriptas per example i am wanting to simply set a variable in my script or use a viewbag or modeli have not been able to find an answer in any of the following forums stcktrace1stacktracebetteranswerother things i have triedvar model htmlrawjsonencodemodelalertmodelsectionsalertviewbagforsection,['jquery'] +544614,how to pass complex objects across view functionssessions in flask i am writing a web application that receives a lot of data from a third party server when and only when a user logs in this data is parsed to custom objects and stored in a list now the user works with this data all around the application calling different views eg sending different requestsi am not sure whats the best pattern to pass the list of objects between the view functionsi technically see two possibilities but both have drawbacks in my casethe session dict storing the data in the session is an overkill the whole list would be send back and forth between server and browser on every requestpersisting temporarly persisting the data to a database seem more adequate but i was hoping to not having to use a database at all except for this temporarly data i do not have any data that needs to be stored locally everything else is received from the third party server and sent back to iti am not a very expirienced web developer so maybe i oversee the obviousso is there another way to pass the data between requests maybe some built in flask magic or is persisting to a file or database really the only option,['python'] +544710,comparing two numpy arrays of different length i need to find the indices of the first less than or equal occurrence of elements of one array in another array one way that works is thisimport numpya numpyarray10720b numpyarray10987654321indices numpywhereax00 for x in bindices has the value 0 1 1 1 2 2 2 2 2 3 which is what i need the problem of course is that python for loop is slow and my arrays might have millions of elements is there any numpy trick for this this does not work because they arrays are not of the same lengthindices numpywhereab x raises an exceptionthanks,['python'] +544730,interoping with powershell cmdlets i have been writing some utilities that make use of powershell cmdlets for appv the interesting part is microsoft seems to only document the cmdlets and not the net assemblies used behind the powershell modulesnow i am familiar with pinvoke and com interop and i have learned how to use systemmanagementautomation to create a powershell session and invoke the cmdletsbut something does not smell right to me i am basically writing my own wrapper classes to hide the powershell invocations from the rest of my code it seems like i should either a bypass powershell and go straight for the managed library behind it or b there should be better mechanism for generating interop libraries for powershell cmdletsit seems like microsoft is making a lot of use of ps cmdlets these days that it is essentially becoming a new api to interop witham i missing something whats a good strategy to use in this scenario,"['c#', '.net']" +544742,chrome debugging break on next click event we have a button click events are handled by a 3rd party framework however the framework is buggy somehowwe want to debug the framework however we do not know where the corresponding event handler code resides to set a breakpoint how to generally break on next click event and see where and how this click is handled by the 3rd party framework,['javascript'] +544792,deserialize xml to object array i am trying to deserialize an xml file to an object array but i am receiving empty objectsmy question looks similar to this how to deserialize xml to an array of objects but i cannot seem to create a class which inherits ixmlserializable that said i do not think that approach is necessary am i doing something wrongfile object xmltypefile public class file xmlelementid public string id get set xmlelementcompany name public string company name get set xmlelementdocs public hashsetdoc docs get set doc object xmltypedoc public class doc xmlelementvala public string vala get set xmlelementvalb public string valb get set xmlxml version10 encodingutf8 files file id12345id company nameapplecompany name docs doc valainfovala valbmore infovalb doc docs file file id12345id company namemicrosoftcompany name docs doc valaeven more infovala valblots of itvalb doc docs file filesdeserialization codexmlserializer myserializer new xmlserializertypeoffile new xmlrootattributefilesusing filestream myfilestream new filestreamfilesxml filemodeopen file r r filemyserializerdeserializemyfilestream,['c#'] +544830,change javascript string encoding at the moment i have a large javascript string i am attempting to write to a file but in a different encoding iso88591 i was hoping to use something like downloadify downloadify only accepts normal javascript strings or base64 encoded strings because of this i have decided to compress my string using jszip which generates a nicely base64 encoded string that can be passed to downloadify and downloaded to my desktop huzzah the issue is that the string i compressed of course is still the wrong encoding luckily jszip can take a uint8array as data instead of a string so is there any way to convert a javascript string into a iso88591 encoded string and store it in a uint8arrayalternatively if i am approaching this all wrong is there a better solution all together is there a fancy javascript string class that can use different internal encodings edit to clarify i am not pushing this string to a webpage so it would not automatically convert it for me i am doing something like thisvar zip new jszipzipfilegensavetxt resultreturn zipgeneratecompressiondeflateand for this to make sense i would need result to be in the proper encoding and jszip only takes strings arraybuffers or uint8arraysfinal edit this was not a duplicate question because the result was not being thisplayed in the browser or transmitted to a server where the encoding could be changedthis turned out to be a little more obscure than i had thought so i ended up rolling my own solution it is not nearly as robust as a proper solution would be but it will convert a javascript string into windows1252 encoding and stick it in a uint8arrayvar enc new string transcoderwindows1252var tenc enctranscoderesult this is now a uint8arrayyou can then either use it in the array like i didmake this into a zipvar zip new jszip zipfilegensavetxt tenc return zipgeneratecompressiondeflateor convert it into a windows1252 encoded string using this string encoding libraryvar string textdecoderwindows1252decodetencto use this function either usescript srcweu4editorcomstring transcoderjsscriptor include thisfunction string transcoder target thisencodelist encodingstarget if thisencodelist undefined return undefined initialize the easy encodings if target windows1252 var i for i 0x0 i 0x7f i thisencodelisti i for i 0xa0 i 0xff i thisencodelisti i string transcoderprototypetranscode function instring var res new uint8arrayinstringlength i for i 0 i instringlength i var temp instringcharcodeati var tempencode thisencodelisttemp if tempencode undefined return undefined this encoding is messed up else resi tempencode return resencodings windows1252 0x20ac0x80 0x201a0x82 0x01920x83 0x201e0x84 0x20260x85 0x20200x86 0x20210x87 0x02c60x88 0x20300x89 0x01600x8a 0x20390x8b 0x01520x8c 0x017d0x8e 0x20180x91 0x20190x92 0x201c0x93 0x201d0x94 0x20220x95 0x20130x96 0x20140x97 0x02dc0x98 0x21220x99 0x01610x9a 0x203a0x9b 0x01530x9c 0x017e0x9e 0x01780x9f,"['javascript', 'jquery']" +544856,how do i toggle an elements class in pure javascript i am looking for a way to convert this jquery code which is used in responsive menu section to pure javascriptif it is hard to implement it is ok to use other javascript frameworks btnnavbarclickfunction containerfluidfirsttoggleclassmenuhidden menutoggleclasshiddenphone if typeof masonrygallery undefined masonrygallerythanks in advance,['javascript'] +544866,why does not stringequals check for equality of char value i was looking at the source for javalangstring and noticed the equals method does not check whether the char backing each string is the same object wouldnt this improve compare timessupposed improvement contained in this rewritten versionpublic boolean equalsobject anobject if this anobject return true if anobject instanceof string string anotherstring stringanobject int and count if n anotherstringcount char v1 value char v2 anotherstringvalue int i offset int j anotherstringoffset begin optimization ifv1v2 ij return true end optimization while n 0 if v1i v2j return false return true return false i believe this would improve performance in the case that the two strings were obtained using stringsubstring and possibly even interned stringsdoes anybody know if there is a reason they chose not to implement it this wayupdate for anybody who might not know a lot about the implementation of string there are cases other than the string pool where two string objects can have the same char value int offset and int countconsider the following codestring x i am a string yostring y xsplit 3string z xsubstring714you would end up with a situation like thisalso apparently the valuesharing feature of strings has been done away with in java 7u6 in order to satisfy some benchmarks so if you spent time making your code run in decent time or at all by using stringsubstring rather than string concatenation youre sol,['java'] +544920,debug assertion failed expression pfirstblock phead i am calling into a statically linked dll and i see this errori wrote both the dll and the calling code this error should not be occurring i am wondering if anyone else has encountered it before the dll only contains about 10 lines of code its just a test dll to see how dlls work in general it blows up when i pass a stdstring back out of the dlli am using visual studio 2012 and cwhat i will try nextfrom debug assertion pfirstblock pheadthis problem can occur if one uses the singlethreading libraries in a multithreaded moduletomorrow i will try recompiling the boost static libraries in multithreaded mode my dll is set to multithreaded static modewhat i will try nextsee using strings in an object exported from a dll causes runtime erroryou need to do one of two things make both the dll and the client that use it both link to the dll version of the crt eg not statically or you need to make sure you do not pass dynamically allocated memory such as is contained in string objects across dll boundaries in other words do not have dllexported functions that return string objects joethis seems to match whats going on it blows up at the precise point where i pass a string back across a dll boundary the problem only occurs when everything is linked in static mode now that is fixablesee passing reference to stl vector over dll boundarywhat i will try nextsee unable to pass stdwstring across dllsolutioni have a nice solution see the answer below,['c++'] +544940,trouble installing private github repository using pip to preface i have already seen this question is it possible to use pip to install a package from a private github repositoryi am trying to install a package from a private repository that i have access to using pipi am able to directly clone it like somyenvrobbieubuntugit git clone matherbkdjangomessagesgitcloning into djangomessagesremote counting objects 913 doneremote compressing objects 100 345345 doneremote total 913 delta 504 reused 913 delta 504receiving objects 100 913913 16573 kib doneresolving deltas 100 504504 donebut when i try to install it via pip my virtualenv is activatedmyenvrobbieubuntugit pip install githttpsmatherbkdjangomessagesgitdownloadingunpacking githttpsmatherbkdjangomessagesgit cloning httpsmatherbkdjangomessagesgit to tmppip13ushsbuildpassword for https fatal authentication failed complete output from command usrbingit clone q httpsmatherbkdjangomessagesgit tmppip13ushsbuildcommand usrbingit clone q httpsmatherbkdjangomessagesgit tmppip13ushsbuild failed with error code 128 in nonestoring complete log in homerobbiepippiplogi tried typing in my password but it failed however i am ssh authenticated for myenvrobbieubuntugit ssh t hi robpodosek youve successfully authenticated but github does not provide shell accessi can switch to and it lets me install via pip just finemyenvrobbieubuntugit pip install githttpsmatherbkdjangomessagesgitdownloadingunpacking githttpsmatherbkdjangomessagesgit cloning httpsmatherbkdjangomessagesgit to tmppipsqean9buildpassword for https running setuppy egg info for package from githttpsmatherbkdjangomessagesgit warning no files found matching readmeinstalling collected packages djangomessages running setuppy install for djangomessages warning no files found matching readmesuccessfully installed djangomessagescleaning uphowever i want to do what the first mentioned article does by using so that i do not have to add my username into a requirementstxt file and add that to version controlany thoughts i previously had this working but had to boot up a fresh image thanks ahead of time,['python'] +544948,rspec let method not generating variable i am trying to create a test for my bill total helper method the let method is not generating the bill1 and bill2 variable describe billshelper do letbill1 billcreatename bill 1 amount 100 letbill2 billcreatename bill 2 amount 100 describe bill total do bill1amount 100 bill2amount 100 expectbills helperbill totalto eq200 endenderror usersadrianlelderdocumentsdeveloper resourcessitesbills appspechelpersbills helper specrb18in block 2 levels in top required undefined local variable or method bill1 for class0x007fb3c121b548 nameerror from usersadrianlelderrvmgemsruby200p0gemsrspeccore2131librspeccoreexample grouprb242in module eval from usersadrianlelderrvmgemsruby200p0gemsrspeccore2131librspeccoreexample grouprb242in subclass from usersadrianlelderrvmgemsruby200p0gemsrspeccore2131librspeccoreexample grouprb228in describe from usersadrianlelderdocumentsdeveloper resourcessitesbills appspechelpersbills helper specrb17in block in top required from usersadrianlelderrvmgemsruby200p0gemsrspeccore2131librspeccoreexample grouprb242in module eval from usersadrianlelderrvmgemsruby200p0gemsrspeccore2131librspeccoreexample grouprb242in subclass from usersadrianlelderrvmgemsruby200p0gemsrspeccore2131librspeccoreexample grouprb228in describe from usersadrianlelderrvmgemsruby200p0gemsrspeccore2131librspeccoredslrb18in describe from usersadrianlelderdocumentsdeveloper resourcessitesbills appspechelpersbills helper specrb13in top required from usersadrianlelderrvmgemsruby200p0gemsrspeccore2131librspeccoreconfigurationrb819in load from usersadrianlelderrvmgemsruby200p0gemsrspeccore2131librspeccoreconfigurationrb819in block in load spec files from usersadrianlelderrvmgemsruby200p0gemsrspeccore2131librspeccoreconfigurationrb819in each from usersadrianlelderrvmgemsruby200p0gemsrspeccore2131librspeccoreconfigurationrb819in load spec files from usersadrianlelderrvmgemsruby200p0gemsrspeccore2131librspeccorecommand linerb22in run from usersadrianlelderrvmgemsruby200p0gemsrspeccore2131librspeccorerunnerrb80in run from usersadrianlelderrvmgemsruby200p0gemsrspeccore2131librspeccorerunnerrb17in block in autorunfinished in 24s with exit code 1,"['ruby-on-rails', 'ruby']" +544961,1 duplicate symbol for architecture i386 i am facing a critical problem here xcode throws strange exception while building it is duplicate symbol selected in usersmhgaberlibrarydeveloperxcodederiveddataprojectnameaopcbghvorqhdwbyudzqsyhtekcubuildintermediatesprojectnamebuilddebugiphonesimulatorprojectnamebuildobjectsnormali386classxo usersmhgaberlibrarydeveloperxcodederiveddataprojectnameaopcbghvorqhdwbyudzqsyhtekcubuildintermediatesprojectnamebuilddebugiphonesimulatorprojectnamebuildobjectsnormali386classyo ld 1 duplicate symbol for architecture i386 clang error linker command failed with exit code 1 use v to see invocationi searched a lot but i did not find anything help me please,"['iphone', 'objective-c']" +544971,portable way of setting stdthread priority in c11 what is the correct way in the post c11 world for setting the priority of an instance of stdthreadis there a portable way of doing this that works at least in windows and posix linux environmentsor is it a matter of getting a handle and using whatever native calls are available for the particular os,['c++'] +544974,autowired vs required on setter i am curious to know whats the difference between code like thisclass myclass autowired myservice myserviceand code like thisclass myclass myservice myservice required public void setmyservicemyservice val thismyservice val,['java'] +544979,android buildconfig issues while adding properties through gradle i am adding few properties in buildconfig through buildgradle as belowrelease prod buildconfig public static final string environment prod release dev buildconfig public static final string environment dev the problem is when i build from gradle it works fine but when i compile project in eclipse i get errors because this variable is not present in gen buildconfigmy question is is there a way to add few variables in buildconfig so that its generated from eclipse at buildtimeif not is there anyway i can generate properties from gradle in a separate file other than buildconfig,['android'] +544980,adding a new array element to a json object i have a json format object i read from a json file that i have in a variable called teamjson that looks like this theteamteamid1statuspendingteamid2statusmemberteamid3statusmemberi want to add a new item to the array such as teamid4statuspendingto end up with theteamteamid1statuspendingteamid2statusmemberteamid3statusmemberteamid4statuspendingbefore writing back to the file what is a good way to add to the new element i got close but all the double quotes were escaped i have looked for a good answer on so but none quite cover this case any help is appreciated,['javascript'] +545051,access database securely from ios app i chose mysql after looking between mysql and sqlite for accessing because my iphone app needs to pull information from an online database that is already in mysqli believe the traditional way of accessing information would be to have a php file on the server that does the accessing for youthe iphone app would call this php file and it would return the resultsios app will call and the website would print out the username of id234now how secure is this process i would obviously use prepared statements and https but what if someone found the url for this website how do i protect myself against misuse someone could generate a list of all my users is this the standard way to have your iphone app connect and get info from a databaseedit furthermore lets say i needed to create an app login page i have a mysql database with username and password hashed obviously would it be safe to use get variables to see if they are authenticated like for example passwordc3lyijvtcq14q and have the php print out yes or no picture examples belowi would assume the above method would not be safe to do but i need to be enlightenedalso i would prefer to stay away from calling the database within the app using third party api not supported by apple,"['php', 'mysql', 'iphone', 'ios']" +545070,how to check whether java is installed on the computer i am trying to install java windows application on client machinei want to check whetherrequried jre is installed on the machine or not i want to check it by java program not by cmd command,['java'] +545137,how to make sure only my own website clientside code can talk to firebase backend i have read about firebase and it looks awesome for what i want to do i have read about authentication and how based on rules certain loggedin users are authorized to do different stuff al good however i am unsure about another type of security how do i make sure that only my own site using clientside javascript can talk to my firebasebackend i am asking because afaik there is no way to prevent anyone from looking up my firebase endpoint from the clientside code url pointing to my specific firebase backend and start using that for god knows whatthis is especially worrisome in situations in which i want to open up writes to the anonymous user role eg some analytics perhapsany help in clearing my mind on this much appreciated,['javascript'] +545234,splitting on comma outside quotes my program reads a line from a file this line contains commaseperated text like123test4do not split thismore test1i would like the result of a split to be this123test4do not split thismore test1if i use the stringsplit i would get this123test4do not split thismore test1in other words the comma in the substring do not split this is not a seperator how to deal with thisthanks in advancejakob,['java'] +545252,alternatives to type casting when formatting nsuinteger on 32 and 64 bit architectures with the 64 bit version of ios we cannot use d and u anymore to format nsinteger and nsuinteger because for 64 bit those are typedefd to long and unsigned long instead of int and unsigned intso xcode will throw warnings if you try to format nsinteger with d xcode is nice to us and offers an replacement for those two cases which consists of a lprefixed format specifier and a typecast to long then our code basically looks like thisnslogld longinsloglu unsigned longuwhich if you ask me is a pain in the eye a couple of days ago someone at twitter mentioned the format specifiers zd to format signed variables and tu to format unsigned variables on 32 and 64 bit plattforms nslogzd inslogtu uwhich seems to work and which i like more than typecasting but i honestly have no idea why those work right now both are basically magic values for me i did a bit of research and figured out that the z prefix means that the following format specifier has the same size as size t but i have absolutely no idea what the prefix t means so i have two questionswhat exactly do zd and tu meanand is it safe to use zd and tu instead of apples suggestion to typecast to longi am aware of similar questions and apples 64bit transition guides which all recommend the lu unsigned long approach i am asking for an alternative to type casting,"['ios', 'objective-c']" +545257,rails and minitest add additional folder i use ruby 2 and rails 4 i have a folder testlib where a few tests are locatedbut running rake test does not use them only the other tests models controllers are runningwhere do i have to add the lib folderi already tried minitestrailstestingdefault tasks lib but i get nameerror exception uninitialized constant minitestrails i did not add the minitest gem to my gemfile because ruby 2 uses it by default,['ruby-on-rails'] +545258,get my phone number in android how can i get my phone number in androidwhen i use telephonymanager tmgr telephonymanagerthisgetsystemservicecontexttelephony service string mphonenumber tmgrgetline1numberand useusespermission androidnameandroidpermissionread phone state return nullwhy,['android'] +545269,fixed position div scrollable i have a div positioned fixed on the left side of a web page containing menu and navigation links it has no height set from css the content determines the height the width is fixed the problem is that if the content is too much the div will be larger than the windows height and part of the content will not be visible scrolling the window does not help since the position is fixed and the div would not scrolli tried to set overflowyauto but that does not help either the div does not seem to notice that part of it is outside of the windowhow can i make it is contents scrollable only if needed if the div hangs out of the window,"['html', 'css']" +545274,using retrofit with cookie persistence i guys i am using retrofit and i wonder how to transparently handle the session cookiefor that i extend the given apacheclient and use a cookiestore in the custom call to apacheclientexecutehttpclient httpurirequest client client new apacheclient final cookiestore cookiestore new basiccookiestore override protected httpresponse executehttpclient client httpurirequest request throws ioexception basichttpcontext is not thread safe cookiestore is thread safe basichttpcontext httpcontext new basichttpcontext httpcontextsetattributeclientcontextcookie store cookiestore return clientexecuterequest httpcontext restadapter restadapter new restadapterbuilder setserverapi url setclientclient buildis there a better way to do this with the buildin retrofit api with no httpclient extension,"['java', 'android']" +545283,jquery sparklines and twitter bootstrap 3 tooltip style overrides here it goes i am trying to use jquery sparklines with twitter bootstrap 3 in the process the tooltip of sparklines loose styling and it is clearly that the bootstrap css is overriding something in the sparklines jsas far as i can make out it has to do with the tooltip selectorhere is one example of how it should look this is without the bootstrap css point at the different sparklines and see a pretty tooltip with values hoveringjsfiddle how it should lookhere unfortunately is what happens when i add the bootstrap cssjsfiddle how it looks with bootstrap cssi am sure it is pretty simple but as the default css for sparklines is hardcoded into the js i am out at seaany pointers would be greatly appreciated,"['jquery', 'css']" +545299,angularjs routing with djangos urls i am using angularjs for my frontend and django as a backendi am doing very simple things at the backend so i have not considered using tastypiethe problem where i am stuck is the clientserver routing i am thoroughly confusedwhat i do isrender the entryhtml page from django which has div ngviewdiv in the body i am assuming that after this the routing is handled by angulars routeproviderin my staticjs folder i have a file appjs which defines the route for another template for the form that i want to fillhowever when i run the project and load the apps entry url i do not get redirected to the form all the javascript files are included and i dont see any 404s in my logwhat am i doing wrong here update appjsappconfigrouteprovider functionrouteprovider routeprovider whentemplateurl templatesworkflowrequest formhtml controllerentryctrl otherwiseredirecttoentryhtml extends site basehtml load staticfiles block body div classngapp div classrowfluid ngviewngview div div endblock block extra script script srcscript script src script script srcscript script src script script srcstaticjscontrollerjsscript script srcstaticjsappjsscript script srcstaticjsbootstrapminjsscript script srcstaticjsbootstrapdatepickerjsscript script src ucehuzmcf6uzpnzzavrgsensorfalsescript endblock controllerjsvar app angularmoduleapp ngresourcefunction entryctrlscope http routeparams location master scopeform masterform,"['javascript', 'python']" +545330,ios7 uicollectionview appearing under uinavigationbar i have been building on ios 7 for a while now but i have yet to get this solved i have a number of views with autolayout enabled that were created in storyboard and are thisplayed with a standard uinavigationcontroller the majority are fine but the ones based on uicollectionview always place themselves under the navigation bar unless i set the translucency to no i have tried the edgesextended trick but that does not seem to solve it i do not necessarily mind having the translucency off but i would like to solve it cleaner,['ios'] +545353,passing context to arrayadapter inside fragment with setretaininstancetrue will cause leak i have a listfragment which would show list of items via an arrayadapter i am trying to handle configuration change device rotation i feel passing activity context to array adapter might cause memory leak when activity is restarted on rotation and listfragment adapter is retained because i am using setretaininstancetrue can someone tell me if my understanding is true if so what is the best way to handle this and yes i do not want to null my adapter ondetach and reuse it once fragment view is recreated public class dummyxlistfragment extends robosherlocklistfragment override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setretaininstancetrue override public void onactivitycreatedbundle savedinstancestate superonactivitycreatedsavedinstancestate if adapter null adapter new dummyitemadaptergetactivity androidrlayoutsimple list item 1 list,['android'] +545365,getting the current tabs url from google chrome using c there used to be a way to get the active tabs url from google chrome by using findwindowex in combination with a sendmessage call to get the text currently in the omnibox a recent update seems to have broken this method since chrome seems to be rendering everything itself now you can check with spy ahk window spy or window detectiveto get the current url on firefox and opera you can use dde and w getwindowinfo this does not seem to be possible on chrome anymorethis question has an answer with more info about how it used to work which is this piece of code which as i explained does not work anymore haddressbox is 0var haddressbox findwindowex intptr intptrzero chrome omniboxview intptrzerovar sb new stringbuilder256sendmessagehaddressbox 0x0d intptr256 sbtemp sbtostringso my question is is there a new way to get the currently focused tabs url just the title is not enough,['c#'] +545380,data too long for column why i have written a mysql script to create a database for hypothetical hospital records and populate it with data one of the tables department has a column named description which is declared as type varchar200 when executing the insert command for description i get an error 1406 data too long for column description at row 1 all the strings i am inserting are less than 150 charactersheres the declarationcreate table departmentdescription varchar200and heres the insertion command insert into department values there is some text here there is some more text over hereby all appearances this should be working anyone have some insight,"['mysql', 'sql']" +545383,ios7 excessive navigationbar button padding i am experiencing excessive uibarbuttonitem paddingspacing when using the leftbaritems and rightbaritems see image below the icons used on the uibarbuttonitems do not contain extra padding so i would like to know whats causing this,['objective-c'] +545465,android appengine endpoints auth and inapp billing i have ran into a tricky problem i am using appengine endpoints to implement my server side api this api returns some data to my users application supports in app products purchases my idea is simple as soon as user purchases a certain product api will return additional data the straightforward approach is passing a flag as a parameter to api but i want to make it more secure by enabling oauth authentication to my endpoints so as soon as user purchases something it is verified and remembered on a server thus my api endpoint will always know what data to return to a particular userthe problem however is the following i do not want to force users authenticating unless they want to make a purchase but then there is a situation that users may use another device and not login using their google account through my app this way my api will return only free data but the user has paid products bought i can query purchased products via play services but i still need to either auth on my server or pass a flag to get full datahow are these things usually done can i silently use users first google account which is afaik guaranteed to be the on play store uses to auth on my server or is this wrongthanks,['android'] +545490,boostshared ptrshared ptrconst boostshared ptr is implicitly declared as deleted include iostreaminclude boostshared ptrhppinclude boostmake sharedhppusing namespace stdstruct node nodeint data boostshared ptrint next boostmake sharedint m datadata m nextnext int m data boostshared ptrint m next error cpp11 onlinephp compile and execute c11 online gnu gcc version 472compiling the source codeg stdc11 maincpp o demo lm pthread lgmpxx lgmp lreadline 21maincpp in constructor nodenodeint boostshared ptrmaincpp934 error use of deleted function boostshared ptrshared ptrconst boostshared ptrin file included from usrincludeboostshared ptrhpp170from maincpp2usrincludeboostsmart ptrshared ptrhpp16825 note boostshared ptrshared ptrconst boostshared ptr is implicitly declared as deleted because boostshared ptr declares a move constructor or move assignment operatorquestion i have see the post using stdshared ptr with clang and libstdc however i do not know how to fix itthe solution posted in that question is adding a defaulted copy constructor and copy assignment operator to shared ptr will fix the problem,['c++'] +545571,c unknown type name my structure i have this codemainhifndef mainhdefine mainhinclude my structhvoid some funcmy structure xendifandmy structhifndef utilshdefine utilshinclude mainhtypedef struct abcd int a my structureendifbut i am getting this when i try to compile error unknown type name amy structureaany idea why,['c'] +545610,upgrading to ios 7 and xcode 5 having issues with uiaccelerator uistringdrawing and nsobject i updated my ipad to ios 7 and thiscovered that the enterprise app that i have been working on for over a year crashes ok no problem i will see where in xcode it is crashingok problem i have to upgrade to xcode 5 to debug ios 7 ok no problem i will upgrade to xcode 5ok problem the source code in xcode 5 now shows 19 errors one in nsobjecth three in uistringdrawingh and the rest in uiaccelerometerhand for a bonus it adds one at the bottom too many errors emitted stopping now which is not all that comfortingi have really scoured the internet for answers but i must be using the wrong search terms because i am finding nothing that addresses this surely i am not the only onei have been developing ios apps for almost two years now i think but i am still pretty stupid when it comes down to the nittygritty stuff i usually just hit run and hope it works so far that has been a pretty effective strategy but now i am stumpedcan anyone tell me what i am doing wrong except the obvious being that i should have left everything well enough alonei will also have to update my previous app because it has ios 7 issues too but it scares me to even think of iti appreciate any help anyone can give,"['iphone', 'ios', 'objective-c']" +545621,euclids algorithm function parameters i have written a program for class where i need to recursively evaluate the extended euclids algorithm for a and b returning g the greatest common divisor as well as s and t from asbtgcdab i am fairly certain i have the function written correctly but i am having issues with values being passed to and from the function i have not coded in a while and have only written pseudocode recently so i am a little rusty for example i have written when b0 return a 1 0 but when i input b as 0 i get returned 0 0 0 and cannot figure out why this is happening any help or guidance would be greatly appreciatedinclude iostreamusing namespace stdint extgcd int a int b int g s t g1 s1 t1 if b 0 return a 1 0 g1 s1 t1 extgcdb ab g g1 s s1 t s1 abt1 return g s tint mainint argc char argv int ab g2 s2 t2 temp cout please input a cin a cout please input b cin b if b a temp a a b b temp g2 s2 t2 extgcd a b cout g g2 s s2 t t2 return 0,['c++'] +545630,cannot launch my app in instruments at least one target failed to launch i have all my code signing entitlements set correctly running the app on my phone is fine but launching it in instruments gives me an error messageerror starting recordingat least one target failed to launch aborting runand thentarget failed to run permisson to debug app name was denied the app must be signed with a development identity ie ios developerany ideas how i could stop this from happening does not happen on my ipad,"['iphone', 'ios']" +545648,xcode 5 crashes xcode quit unexpectedly xcode 5 from the app store crashes when i select any file in the project navigator or when i try to edit it i have deleted all plugins and the derived data for the app and it keeps crashingdoes anyone know how to fix this and why this is happeningbelow is the first part of the errorexception type exc crash sigabrtexception codes 0x0 0x0application specific informationproductbuildversion 5a1412assertion failure in sourcecachedvtfoundationdvtfoundation3532frameworkclassesprotocolsdvtinvalidationm243details idesourcecontrolcredentialsvalidator 0x7faec5e3c9b0 was never invalidatedi am not sure this helps but here is the backtracebacktrace for allocation if creationbacktrace is set nullobject idesourcecontrolcredentialsvalidator 0x7f86dceeb080method deallocthread nsthread 0x7f86d8414c80name null num 1hints nonebacktrace 0 0x010e3a1188 ideassertionhandler handlefailureinmethodobjectfilenamelinenumbermessageformatarguments in idekit 1 0x010d137655 dvtassertionhandler in dvtfoundation 2 0x010d137984 dvtassertionfailurehandler in dvtfoundation 3 0x010d20c6a6 dvtinvalidation deallocsuper in dvtfoundation 4 0x010e33e2a3 idesourcecontrolsslauthenticationwindowcontroller cxx destruct in idekit 5 0x07f8c00bfcc object cxxdestructfromclassobjc object objc class in libobjcadylib 6 0x07f8c005922 objc destructinstance in libobjcadylib 7 0x07f8c005fa0 object thispose in libobjcadylib 8 0x010d161995 dvtsetupkvodeallocassertions block invoke 371 in dvtfoundation 9 0x07f865797fa nsresponder dealloc in appkit 10 0x07f864af162 nswindowcontroller dealloc in appkit 11 0x07f86623901 nswindowcontroller release in appkit 12 0x07f867595b0 nsautounbinder dealloc in appkit 13 0x07f8c006230 anonymous namespaceautoreleasepoolpagepopvoid in libobjcadylib 14 0x07f87a0cd72 cfautoreleasepoolpop in corefoundation 15 0x07f8c52447a nsautoreleasepool drain in foundation 16 0x07f8657a27e nsapplication run in appkit 17 0x07f8651ebd6 nsapplicationmain in appkit 18 0x07f91f377e1 start in libdylddylibabort calledthread 0 crashed thispatch queue comapplemainthread0 libsystem kerneldylib 0x07f903ad212 pthread kill 101 libsystem cdylib 0x07f8a7fcb54 pthread kill 902 libsystem cdylib 0x07f8a840dce abort 1433 comappledtidekit 0x010e3a0a93 ideassertionhandler handleassertionwithlogstringreason 7634 comappledtidekit 0x010e3a12ee ideassertionhandler handlefailureinmethodobjectfilenamelinenumbermessageformatarguments 175 comappledtdvtfoundation 0x010d137655 dvtassertionhandler 4216 comappledtdvtfoundation 0x010d137984 dvtassertionfailurehandler 3227 comappledtdvtfoundation 0x010d20c6a6 dvtinvalidation deallocsuper 4808 comappledtidekit 0x010e33e2a3 idesourcecontrolsslauthenticationwindowcontroller cxx destruct 949 libobjcadylib 0x07f8c00bfcc object cxxdestructfromclassobjc object objc class 10010 libobjcadylib 0x07f8c005922 objc destructinstance 91 libobjcadylib 0x07f8c005fa0 object thispose 2212 comappledtdvtfoundation 0x010d161995 dvtsetupkvodeallocassertions block invoke 371 26413 comappleappkit 0x07f865797fa nsresponder dealloc 12914 comappleappkit 0x07f864af162 nswindowcontroller dealloc 61615 comappleappkit 0x07f86623901 nswindowcontroller release 15916 comappleappkit 0x07f867595b0 nsautounbinder dealloc 5117 libobjcadylib 0x07f8c006230 anonymous namespaceautoreleasepoolpagepopvoid 46418 comapplecorefoundation 0x07f87a0cd72 cfautoreleasepoolpop 3419 comapplefoundation 0x07f8c52447a nsautoreleasepool drain 15420 comappleappkit 0x07f8657a27e nsapplication run 73621 comappleappkit 0x07f8651ebd6 nsapplicationmain 86922 libdylddylib 0x07f91f377e1 start 1thread 1 thispatch queue comapplelibthispatchmanager0 libsystem kerneldylib 0x07f903add16 kevent 101 libthispatchdylib 0x07f8641cdea thispatch mgr invoke 8832 libthispatchdylib 0x07f8641c9ee thispatch mgr thread 54thread 2 comapplensurlconnectionloader0 libsystem kerneldylib 0x07f903ab686 mach msg trap 101 libsystem kerneldylib 0x07f903aac42 mach msg 702 comapplecorefoundation 0x07f87a0c233 cfrunloopservicemachport 1953 comapplecorefoundation 0x07f87a11916 cfrunlooprun 10784 comapplecorefoundation 0x07f87a110e2 cfrunlooprunspecific 2905 comapplefoundation 0x07f8c501546 nsurlconnectionloader resourceloadloop 3566 comapplefoundation 0x07f8c55f562 nsthread main 13457 libsystem cdylib 0x07f8a7fb7a2 pthread start 3278 libsystem cdylib 0x07f8a7e81e1 thread start 13thread 30 libsystem kerneldylib 0x07f903ab686 mach msg trap 101 libsystem kerneldylib 0x07f903aac42 mach msg 702 comapplecorefoundation 0x07f87a0c233 cfrunloopservicemachport 1953 comapplecorefoundation 0x07f87a11916 cfrunlooprun 10784 comapplecorefoundation 0x07f87a110e2 cfrunlooprunspecific 2905 comappledtdevicekitbase 0x011466875a dtdkremotedevicedatalistener listenerthreadimplementation 1646 comapplefoundation 0x07f8c55f562 nsthread main 13457 libsystem cdylib 0x07f8a7fb7a2 pthread start 3278 libsystem cdylib 0x07f8a7e81e1 thread start 13thread 4 comapplecfsocketprivate0 libsystem kerneldylib 0x07f903ad322 select 101 comapplecorefoundation 0x07f87a50f46 cfsocketmanager 13022 libsystem cdylib 0x07f8a7fb7a2 pthread start 3273 libsystem cdylib 0x07f8a7e81e1 thread start 13thread 5 dymobiledevicemanager0 libsystem kerneldylib 0x07f903ab686 mach msg trap 101 libsystem kerneldylib 0x07f903aac42 mach msg 702 comapplecorefoundation 0x07f87a0c233 cfrunloopservicemachport 1953 comapplecorefoundation 0x07f87a11916 cfrunlooprun 10784 comapplecorefoundation 0x07f87a110e2 cfrunlooprunspecific 2905 comapplefoundation 0x07f8c5647ee nsrunloopnsrunloop runmodebeforedate 2686 comapplefoundation 0x07f8c4fd1aa nsrunloopnsrunloop run 747 comapplegputoolsmobilefoundation 0x0118afe9bb dymobiledevicemanager devicenotificationthread 1328 comapplefoundation 0x07f8c55f562 nsthread main 13459 libsystem cdylib 0x07f8a7fb7a2 pthread start 32710 libsystem cdylib 0x07f8a7e81e1 thread start 13thread 6 cvthisplaylink0 libsystem kerneldylib 0x07f903ad0fa psynch cvwait 101 libsystem cdylib 0x07f8a7fe9 pthread cond wait 8692 comapplecorevideo 0x07f8b5872a1 cvthisplaylinkruniothread 6893 comapplecorevideo 0x07f8b586fd7 startiothreadvoid 1484 libsystem cdylib 0x07f8a7fb7a2 pthread start 3275 libsystem cdylib 0x07f8a7e81e1 thread start 13thread 70 libsystem kerneldylib 0x07f903ad0fa psynch cvwait 101 libsystem cdylib 0x07f8a7fe9 pthread cond wait 8692 comapplexcodedevtoolscore 0x0113436166 xcblockqueue processblocksinthreadslotnumber 5063 comapplefoundation 0x07f8c55f562 nsthread main 13454 libsystem cdylib 0x07f8a7fb7a2 pthread start 3275 libsystem cdylib 0x07f8a7e81e1 thread start 13thread 80 libsystem kerneldylib 0x07f903ad0fa psynch cvwait 101 libsystem cdylib 0x07f8a7fe9 pthread cond wait 8692 comapplexcodedevtoolscore 0x0113436166 xcblockqueue processblocksinthreadslotnumber 5063 comapplefoundation 0x07f8c55f562 nsthread main 13454 libsystem cdylib 0x07f8a7fb7a2 pthread start 3275 libsystem cdylib 0x07f8a7e81e1 thread start 13thread 90 libsystem kerneldylib 0x07f903ad0fa psynch cvwait 101 libsystem cdylib 0x07f8a7fe9 pthread cond wait 8692 comapplexcodedevtoolscore 0x0113436166 xcblockqueue processblocksinthreadslotnumber 5063 comapplefoundation 0x07f8c55f562 nsthread main 13454 libsystem cdylib 0x07f8a7fb7a2 pthread start 3275 libsystem cdylib 0x07f8a7e81e1 thread start 13thread 100 libsystem kerneldylib 0x07f903ad6d6 workq kernreturn 101 libsystem cdylib 0x07f8a7fdf4c pthread workq return 252 libsystem cdylib 0x07f8a7fdd13 pthread wqthread 4123 libsystem cdylib 0x07f8a7e81d1 start wqthread 13thread 110 libsystem kerneldylib 0x07f903ad6d6 workq kernreturn 101 libsystem cdylib 0x07f8a7fdf4c pthread workq return 252 libsystem cdylib 0x07f8a7fdd13 pthread wqthread 4123 libsystem cdylib 0x07f8a7e81d1 start wqthread 13thread 120 libsystem kerneldylib 0x07f903ad6d6 workq kernreturn 101 libsystem cdylib 0x07f8a7fdf4c pthread workq return 252 libsystem cdylib 0x07f8a7fdd13 pthread wqthread 4123 libsystem cdylib 0x07f8a7e81d1 start wqthread 13thread 130 libsystem kerneldylib 0x07f903ad6d6 workq kernreturn 101 libsystem cdylib 0x07f8a7fdf4c pthread workq return 252 libsystem cdylib 0x07f8a7fdd13 pthread wqthread 4123 libsystem cdylib 0x07f8a7e81d1 start wqthread 13thread 140 libsystem kerneldylib 0x07f903ad6d6 workq kernreturn 101 libsystem cdylib 0x07f8a7fdf4c pthread workq return 252 libsystem cdylib 0x07f8a7fdd13 pthread wqthread 4123 libsystem cdylib 0x07f8a7e81d1 start wqthread 13thread 150 libsystem kerneldylib 0x07f903ad6d6 workq kernreturn 101 libsystem cdylib 0x07f8a7fdf4c pthread workq return 252 libsystem cdylib 0x07f8a7fdd13 pthread wqthread 4123 libsystem cdylib 0x07f8a7e81d1 start wqthread 13thread 160 libsystem kerneldylib 0x07f903ab686 mach msg trap 101 libsystem kerneldylib 0x07f903aac42 mach msg 702 comapplecorefoundation 0x07f87a0c233 cfrunloopservicemachport 1953 comapplecorefoundation 0x07f87a11916 cfrunlooprun 10784 comapplecorefoundation 0x07f87a110e2 cfrunlooprunspecific 2905 comappledebugsymbols 0x07f8728a590 spotlightquerythreadvoid 3566 libsystem cdylib 0x07f8a7fb7a2 pthread start 3277 libsystem cdylib 0x07f8a7e81e1 thread start 13thread 170 libsystem kerneldylib 0x07f903ad386 semwait signal 101 libsystem cdylib 0x07f8a885800 nanosleep 1632 comapplecoresymbolication 0x07f8fee2358 0x7f8fecc0 909683 libsystem cdylib 0x07f8a7fb7a2 pthread start 3274 libsystem cdylib 0x07f8a7e81e1 thread start 13thread 0 crashed with x86 thread state 64bit rax 0x0 rbx 0x06 rcx 0x07f52b72108 rdx 0x0 rdi 0x0c07 rsi 0x06 rbp 0x07f52b72130 rsp 0x07f52b72108 r8 0x07f769b7278 r9 0x0141 r10 0x020 r11 0x0206 r12 0x07f52b72248 r13 0x010ea71680 r14 0x07f769b8180 r15 0x07f52b721f0 rip 0x07f903ad212 rfl 0x0206 cr2 0x07f86d883a400logical cpu 0,['ios'] +545674,converting md5 password hashes to php 55 password hash the new password hash api in php 55 is nice and i would like to start using it everywhere given an older project with an older database where passwords are stored in md5 hashes what is the best way to go about migrating old user passwords to the new more secure apiapart from simply prompting users to reset their password upon next login this is impractical and annoying for users i have thought about the possibility of using current md5 hash as the input to password hash for all my existing users to verify passwords for these users during login i would convert their input to an md5 hash and then use that to password verify new users would be spared this extra stepis this a worthwhile way to go about this are there any better ways for transparent migration in which users are not nagged about password resets yet i can immediately enjoy the benefits of more secure hashingmost importantly is there even a security benefit in taking existing md5 hashes which are prone to brute force and using the password hash api to doublehash it,['php'] +545687,how to set up dependency injection using dagger for things other than activities and fragments i started setting up dependency injection using dagger as follows please feel encouraged to correct my implementation since i might have mistakes in there the implementation follows the androidsimple example provided by the project in the following you can see how i successfully added dependency injection for activities and fragments i try to keep it easy for now so i decided to inject timber as a logger substitution for androids log utilimport androidappapplicationimport javautilarraysimport javautillistimport daggerobjectgraphimport comexampledebuggingloggingmodulepublic class exampleapplication extends application private objectgraph mobjectgraph protected listobject getmodules return arraysaslist new androidmodulethis new examplemodule new loggingmodule private void createobjectgraphifneeded if mobjectgraph null object modules getmodulestoarray mobjectgraph objectgraphcreatemodules public void injectobject object createobjectgraphifneeded mobjectgraphinjectobject by now the androidmodule is not used anywhere it but might be helpful when a context and layoutinflater is needed eg in cursoradaptersimport androidcontentcontextimport androidviewlayoutinflaterimport javaxinjectsingletonimport daggermoduleimport daggerprovides a module for androidspecific dependencies which require a link context or link androidappapplication to create modulelibrary truepublic class androidmodule private final exampleapplication mapplication public androidmoduleexampleapplication application mapplication application allow the application context to be injected but require that it be annotated with link forapplication annotation to explicitly differentiate it from an activity context provides singleton forapplication context provideapplicationcontext return mapplication provides singleton layoutinflater providelayoutinflater return layoutinflater mapplication getsystemservicecontextlayout inflater service i am not sure what applicationspecific providers would go here i stay with logging for nowimport daggermodulemodule complete falsepublic class examplemodule public examplemodule todo put your applicationspecific providers here i prepared loggingmodule which provides access to timberpackage comexampledebuggingimport javaxinjectsingletonimport daggermoduleimport daggerprovidesimport comexamplebuildconfigimport comexampleactivitiesbasefragmentactivityimport comexampleactivitiesdetailsactivityimport comexamplefragmentsbaselistfragmentimport comexamplefragmentsprofileslistfragmentimport timberlogtimbermoduleinjects activities basefragmentactivityclass detailsactivityclass fragments baselistfragmentclass profileslistfragmentclasspublic class loggingmodule provides singleton timber providetimber return buildconfigdebug timberdebug timberprod the base class for activities injects itself into the object graph package comexampleactivitiesimport androidosbundle import comactionbarsherlockappsherlockfragmentactivity import javaxinjectinjectimport comexampleexampleapplicationimport timberlogtimberpublic abstract class basefragmentactivity extends sherlockfragmentactivity inject timber mtimber override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate exampleapplication getapplicationinjectthis and any sub class benefits from timber being already presentpackage comexampleactivitiesimport androidosbundleimport comexamplerpublic class detailsactivity extends basefragmentactivity override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity details mtimberioncreate same for fragments the base class does the dirty job package comexamplefragmentsimport androidosbundleimport comactionbarsherlockappsherlocklistfragmentimport javaxinjectinjectimport comexampleexampleapplicationimport timberlogtimberpublic abstract class baselistfragment extends sherlocklistfragment inject timber mtimber override public void onactivitycreatedbundle savedinstancestate superonactivitycreatedsavedinstancestate exampleapplication getactivitygetapplicationinjectthis and the sub class benefits from its super classpackage comexamplefragmentsimport androidosbundlepublic class profileslistfragment extends baselistfragment override public void onactivitycreatedbundle savedinstancestate superonactivitycreatedsavedinstancestate todo this might be a good example to inject resources in the base class but how setemptytextgetresources getstringrstringprofiles list no content mtimberionactivitycreated so far so good but how can inject timber into basecursoradapter basecontentprovider basesqliteopenhelper baseservice baseasynctask and static helper methodsthe deprecated android example by christopher perry points out how to inject an adapter into a listfragment but not how to inject context resources layoutinflater cursor into the cursoradapter or just timberreferencesdaggerandroidsimple examplejesse wilson dagger a fast dependency injector for android and javaeric burke android app anatomy,['android'] +545790,make voice and video call through internet with our application i want to develop voice and video call through our application users in android like wechat application how can i doing this i have searched in google but i did not get any exact reference or samples can anyone explain and give some sample source and references for doing this functionality and i have few confusion about sip and voip which one im going to use for support android versions 22 to higher versions applications,['android'] +545802,does using virtualenvwrapper with python33 mean i cannot or should not be using pyvenv virtualenvwrapper is a userfriendly shell around pythons virtualenvpython 33 ships with pyvenv built into the standard library which aims to supercede virtualenvbut if i install virtualenvwrapper on python33 it still installs virtualenv leading me to believe it does not use pyvenv under the coverspresumably this does not really matter if i wish to use virtualenvwrapper on python33 i should happily let it use virtualenv instead of pyvenv and will for the moment suffer no ill effects,['python'] +545812,perform both the normal click and long click at button i have a single button named as checkinhave a look at my code checkinsetonclicklistenernew viewonclicklistener override public void onclickview v toastmaketexthomesafeactivitythis normal press toastlength longshow checkinsetonlongclicklistenernew viewonlongclicklistener override public boolean onlongclickview v toastmaketexthomesafeactivitythis long press toastlength longshow return false now when i normal press the button the message shows as normal presswhen i long press the button the message shows as long press as well as normal press both what i want that when i long press the button only long press event should triggered not the normal press eventhow can i achieve this,['android'] +545842,how to present a view controller on ios7 without the status bar overlapping i am seeing when i migrated my app to ios 7 the nav bar is appearing under the status bar when presenting a view controller i think a lot of people have run into this same issue heres a screenshot of what i am seeingrequirementsthe new view must appear modally ie i need presentviewcontrollerthisplay some sort of nav bar or toolbar with the status bar taking on the background color of the nav bar ala ios 7 styleit must work on ios 6i am using a xib to handle layout with autolayout enabledoptionsa shift your views frame down by a bitugh are we back to the preios 5 days and mucking with frames also it is generally not a good idea mixing with autolayoutb add a little gap up top below your nav barone thisadvantage of options a and b is the status bar would not blend into your navc programatically add constraintsthe main thisadvantage is youll have to muck with constraints and calculating the nav and status bar heights yuckd stretch the navigation bar toolbars height to include the area of the status barlooks good on ios 7 but breaks on ios 6 youll need to programatically update the height of the nav bar and also make sure the rest of your view updates appropriately messye mess with ios67 deltas in ibmultiple thisadvantages youll be hardcoding the ios67 deltas also does not work with autolayoutf use a nested uinavigationcontrollerthis is the workaround i selected see answer below,"['ios', 'objective-c']" +545858,uitableview titleforheaderinsection shows all caps i am using titleforheaderinsection to show a header for a uitableview section it worked fine with the ios6 sdk but the ios7 sdk shows the header in all caps i guess it is part of apples updated human interface guidelines all examples in there show headers in all caps also all section headers in settings on my iphone are in all caps however i wonder if there is a way around that normally i wouldnt mind showing caps if that improves consistency but when i need to show peoples names in a section header it is a bit awkwardanybody any idea how to get around to capitalization,['objective-c'] +545861,webrtc remote video is shown as black while developing a webrtc video chat application i have encountered receiving remote the video stream the video stream blob is received but the video is just black i have gone through these answers and tried almost everything i could to get it to work remote videostream not working with webrtcglobalvarssocketoncall function signal ifglobalvarspc methodsstartcallfalse signal ifsignalsdp temp new rtcsessiondescriptionsdp decodeuricomponentsignalsdp type signaltype globalvarspcsetremotedescriptiontemp fori 0 i globalvarsicecandidatearraylength i globalvarspcaddicecandidatenew rtcicecandidate sdpmlineindex decodeuricomponentsignalsdpmlineindex candidate decodeuricomponentsignalcandidate globalvarsicecandidatearray else ifglobalvarspcremotedescription globalvarspcaddicecandidatenew rtcicecandidate sdpmlineindex decodeuricomponentsignalsdpmlineindex candidate decodeuricomponentsignalcandidate consolelogremot else globalvarsicecandidatearraypushnew rtcicecandidate sdpmlineindex decodeuricomponentsignalsdpmlineindex candidate decodeuricomponentsignalcandidate consolelogice candidate to temp array rosterwraponclick rosterlistitem functione globalvarssocketemitcall receiver id thisattrdataid caller id globalvarsmeid params receiver id thisattrdataid caller id globalvarsmeid methodsstartcalltrue params epreventdefault run starttrue to initiate a callstartcall function iscaller params var configuration iceservers url stunstunlgooglecom19302 globalvarspc new rtcpeerconnectionconfiguration send any ice candidates to the other peer globalvarspconicecandidate function evt alertice candidate if globalvarspc evt evtcandidate return var candidate evtcandidate globalvarssocketemitcall candidate encodeuricomponentcandidatecandidate sdpmlineindex encodeuricomponentcandidatesdpmlineindex receiver id paramsreceiver id caller id paramscaller id once remote stream arrives show it in the remote video element globalvarspconaddstream function evt consolelogadd stream if event return remotevideoattrsrcurlcreateobjecturlevtstream methodswaituntilremotestreamstartsflowing get the local stream show it in the local video element and send it navigatorgetusermedia audio false video true function stream myvideoattrsrc urlcreateobjecturlstream globalvarspcaddstreamstream if iscaller globalvarspccreateoffergetdescription null mandatory offertoreceiveaudio true offertoreceivevideo true else consoleloggot remote description consolelogglobalvarspcremotedescription globalvarspccreateanswerglobalvarspcremotedescription getdescription globalvarspccreateanswergetdescription null mandatory offertoreceiveaudio true offertoreceivevideo true function getdescriptiondesc globalvarspcsetlocaldescriptiondesc consolelogmy desc consolelogdesc globalvarssocketemitcall sdp encodeuricomponentdescsdp type desctype receiver id paramsreceiver id caller id paramscaller id signalingchannelsendjsonstringify sdp desc the complete code is available at and,['javascript'] +545889,bootstrap 3 scrollspy with sidebar i am using bootstrap 3 i want to recreate the same functionality as the sidebar in the documentation on the bootstrap sitebelow is my code and it is also here two problemsthe sidebar items do not highlight as you scroll down the page past each sectionwhen you click on a sidebar item it jumps to the relevant anchor but half the content is not visible changing the dataoffset value appears to have no effectwhat am i doing wrongdiv classcontainer div classrow div classcolmd3 div classlistgroup navbar idsidebar ul classnav idmynav lia hrefc1 classlistgroupitem content 1 a li li a hrefc2 classlistgroupitem contenteditablefalsecontent 2 a li li a hrefc3 classlistgroupitem contenteditablefalsecontent 3 a li li a hrefc4 classlistgroupitem contenteditablefalsecontent 4 a li li a hrefc5 classlistgroupitem contenteditablefalsecontent 5 a li ul div div div classcolmd9 idmycontent dataspyscroll datatargetsidebar dataoffset0 h2 idc1 classcontent 1h2at bootply we attempt to build simple bootstrap templates that utilize hr classcolmd12 h2 idc2 classcontent 2h2rem aperiam eaque ipsa quae ab illo inventore veritatis et quasi architecto hr classcolmd12 h2 idc3 classcontent 3h2rem aperiam eaque ipsa quae ab illo inventore veritatis et quasi architecto hr classcolmd12 h2 idc4 classcontent 4h2sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium h2 idc5 classcontent 5h2sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium div divdiv,['jquery'] +545891,when to use singleton annotation of jersey i am developing a restful web service and while reading the jersey documentation i came across an annotation singletonin my web service i am mostly returning data based on the unique keys provided as parameteran analogy would be return all the information of a student when the student id is passedso my question is when singleton would be suited in such kind of web servicesas per documentation for requestscopedif the resource is used more than one time in the request processing always the same instance will be used then in that case we should not bother to use singleton right also what could be the use cases where we have to make a new instance for every requesti did have a look at this post but my question was not answered,['java'] +545896,ios7 keyboard when it opens shrinks webapp i have a webapp for ipad the app uses the ipad keyboard before when opening the keyboard it would cover the app now with ios7 the app gets shrinked to the remaining space after the keyboard appears is it possible to change this in javascript and keep the old behavioredit i just noticed that if i open the app on safari it works just like before the problem appears when i add the app to the main screenedit i almost solved this but then i got some other problemsfirst i added this heightdeviceheight to the meta tag i was usingmeta name viewport content userscalableno initialscale10 maximumscale10 widthdevicewidth heightdeviceheightbut then a small part of my app the size of the ipad top bar would be hidden at the bottom so i did thismy appcssheightwindowinnerheightwhen i opened the app again it was perfect but when i open the keyboard it moves up and wont come down when i close the keyboard so now at the bottom of the ipad is a black line and the app is a little bit hidden under the top bar of the ipadcan any one help with this,['javascript'] +545909,can you sign a java applet but keep it in the sandbox not give it full access to users computer thanks to oracles latest changes it appears i have to sign an applet even though i do not need or want it to have unrestricted access to the users computer which is why its currently unsigned in particular i do not want the warning they show for signed appletsthis application will run with unrestricted access which may put your computer and personal information at riskwhich will scare the people using itis it possible to sign an applet but mark it in some way to say but keep using the sandboxthe only reason i am signing it is that as of version 7 update 40 oracle has further increased the nagging users have to deal with when running unsigned applets it used to be that you could check a box saying you trusted an applet once and that would be remembered as of update 40 it is only remembered for that browser session the warning reappears if you close the browser and come back later they have also said they are going to thisable unsigned applets entirely in a future version of the java plugin,['java'] +545931,fix footer to bottom of page although most pages on my site have enough content to push the footer to the bottom of the page for most people i would like to know it is always fixed to the bottom regardless of screen size from now on anywayi have tried a number of ways such as bottom 0x positionabsolute etc never seems to work very well occasionally pushes the footer out of its container to fix to the bottom using some of those examples right thereincluded is the html and css for the two parts of the footer footer copyright bar they are both inside of a section idfooter div anywayi removed my attempts at getting it to stick so people can have a look at it right now and see what the current code is to amendlive url it is a resturant website do not worry about the word nakedhtmlsection idfooter div classcontainer div classrow div claspan1 div idsmalogo img srcimgsmalogopng div div div claspan2 div classfooterlist h6our boxesh6 ul a href liclassic boxli a a href livegetarian boxli a a href lifamily boxli a a href lidinner party boxli a a href ligift boxli a ul div div div claspan2 div classfooterlist h6our recipesh6 ul a href lilast weeks featureli a a href linext weeks featureli a ul div div div claspan2 div classfooterlist h6about ush6 ul a href lithe foodli a a href lihow we sourcexli a a href lisustainabilityli a lia hrefabouthtmlabout usali a href licontact usli a ul div div div claspan5 div idtwitter img srcimgtwitterlogopng alt title height50 width50 classtwitterlogo div classtweetbg div classtweets pchefallanp that is just not on reallyp div div idfollowbtn img srcimgfollowusjpg div div div div classcheckoutoptions h6secure checkouth6 ul liimg srcimgsolologopng li liimg srcimgswitchlogopng li liimg srcimgmaestrologopng li liimg srcimgvisalogopng li a href liimg srcimgfacebooklogopng li a a href liimg srcimgtwitterlogoflatpng li a ul div div div div div idcopyrightbar div classcontainer div classrow div classcopyrightcontent div claspan4 pthe naked rathish limited 2013 all rights reservedp div div claspan4 offset4 div classcopyrightlist ul a hreftermshtml literms amp conditionsli a a hrefprivacyhtml li privacy policyli a a href li cookie policyli a ul div div div div divsectioncssfooter backgroundcolor f3f3f3 paddingtop 10px paddingbottom 0px,"['html', 'css']" +546014,box shadow spread bug in webkit in ios 7 on retina ipads i have found what seems to be a bug in webkit for ios 7 but only on ipad 3 and 4 which leeds me to believe it is somehow hardwarerelatedthe bug if i add the spread value the fourth value to css box shadows the whole shadow thisappears i have put up an exampel here can anyone else confirm this error on ipad 3 and 4 with ios 7,"['ios', 'css']" +546058,convert string to time i have a time that is 162301 i tried using datetimeparseexact but it is not workinghere is my codestring time 162301 datetime date datetimeparseexacttime hhmmss tt systemglobalizationcultureinfocurrentculturelblclocktext datetostringi want it to show in the label as 042301 pm,"['c#', 'asp.net']" +546059,object does not support property or method remove i know there is some issue with get documentgetelementbyid and ie but not sure why ie is having a problem with remove and all other browsers are not any help here would be appreciated i am getting the error script438 object does not support property or method remove from the error console the javascript works in all other browsershere is the javascriptscript typetextjavascriptfunction removemodule php tab 1 var module row php echo module row ifconfirmare you sure return false var x 1 while x module row if documentgetelementbyidtab xchecked documentgetelementbyidtab xremove documentgetelementbyidmodule xremove documentgetelementbyidtabmodule xremove x php tab formsubmitscriptthis is from an opencart module it is the tpl file i have included part of the file here as well so hopefully someone can spot whatever the error isphp echo header div idcontent div classbreadcrumb php foreach breadcrumbs as breadcrumb php echo breadcrumbseparator a hrefphp echo breadcrumbhref php echo breadcrumbtext a php div php if error warning div classwarningphp echo error warning div php div classbox div classheading h1img srcviewimagemodulepng alt php echo heading title h1 div classbuttons a onclickformsubmit classbuttonphp echo button save a a onclickremovemodule classbuttonphp echo button delete a a onclicklocation php echo cancel classbuttonphp echo button cancel adiv div div classcontent form actionphp echo action methodpost enctypemultipartformdata idform div classvtabsqs php module row 1 php foreach modules as module div stylemarginleft 7px floatleft input typecheckbox stylefloat left margintop 8px idtabphp echo module row onclick valuetabphp echo module row a hreftabmodulephp echo module row idmodulephp echo module row php foreach languages as language label classinputlrgtabphp if emptymodulelanguage idlanguagelanguage id echo modulelanguage idlanguagelanguage id label php abr div php module row php span idmoduleadd styleclear both marginleft 7pxphp echo button add module nbspimg srcviewimageaddpng alt onclickaddmodule span div php module row 1 php foreach modules as module div idtabmodulephp echo module row classvtabscontent stylemarginleft230px table classform tr tdphp echo entry title td td classleft php foreach languages as language img srcviewimageflagsphp echo languageimage altphp echo languagename input classinputlrg typetext namephp echo classname modulephp echo module row language idphp echo languagelanguage id valuephp if emptymodulelanguage idlanguagelanguage id echo modulelanguage idlanguagelanguage id br php span classerrorphp echo error title span td tr tr tdphp echo entry limit td,['javascript'] +546069,ios 70 and arc uitableview never deallocated after rows animation i have a very simple test app with arc one of the view controllers contains uitableview after making row animations insertrowsatindexpaths or deleterowsatindexpaths uitableview and all cells never deallocated if i use reloaddata it works fine no problems on ios 6 only ios 70any ideas how to fix this memory leakvoidexpand expanded expanded nsarray paths nsarray arraywithobjectsnsindexpath indexpathforrow0 insection0 nsindexpath indexpathforrow1 insection0nil if expanded table view reloaddata table view insertrowsatindexpathspaths withrowanimationuitableviewrowanimationmiddle else table view reloaddata table view deleterowsatindexpathspaths withrowanimationuitableviewrowanimationmiddle inttableviewuitableview tableview numberofrowsinsectionnsintegersection return expanded 2 0table view is kind of class tableview subclass of uitableviewimplementation tableviewstatic int totaltableview idinitwithframecgrectframe styleuitableviewstylestyle if self super initwithframeframe stylestyle totaltableview nsloginit tableview d totaltableview return selfvoiddealloc totaltableview nslogdealloc tableview d totaltableviewend,['ios'] +546098,scrapy python set up user agent i tried to override the useragent of my crawlspider by adding an extra line to the project configuration file here is the codesettingsdefault myprojectsettingsuser agent mozilla50 windows nt 62 wow64 applewebkit53736 khtml like gecko chrome270145393 safari53736deployurl httplocalhost6800project myprojectbut when i run the crawler against my own web i notice the spider did not pick up my customized user agent but the default one scrapy0182 can any one explain what i have done wrong note1 it works when i tried to override the user agent globally scrapy crawl myprojectcom o outputcsv t csv s user agentmozilla2 when i remove the line default myprojectsetting from the configuration file and run scrapy crawl myprojectcom it says cannot find spider so i feel like the default setting should not be removed in this casethanks a lot for the help in advance,['python'] +546126,ruby reject vs delete if being new to ruby i have a question about the difference between the reject and delete if methods when dealing with hashes and arrays if just wanting to get rid of certain objects is there functionally any difference between the methods and reason to use one over the otherthanksediti have read the documentationi guess i should have been more clear in my original question i was wondering more about differences in efficiency do they operate differently in how they delete items again ignoring return value i understand that is a difference thanks,['ruby'] +546151,steps for profiling performance of a website running on azure i am quite new to running websites in general i am familiar with statistical profilers for desktop applications but unsure how to even begin profiling a website as there are a lot of additional potential bottlenecks and i am not sure what profilers are available for websitesi have looked around and seen useful suggestions in other questions but i am not sure they are a very complete solution the main suggestions are azure performance counters and suggestions from this answersummarizing they areuse firebug to determine rendering time and loading time seperately so one can tell whether one has a rendering issue or a server issueif server sidetest a small static page like a page with a single gif if that is slow one has a cpu issue otherwise one is probably io bound or has problems with database performanceone can use performance counters to check server aspects such asmemorygarbage collectiontcpip issuesbytes sent recievedrequests requested queued rejectedrequest wait time processing timefrom my naive standpoint some things that seem to be missing from this list are the sort of profiling one has for a traditional desktop application ie what the stack looked like what percentage of the time ie what functions were we spending time in and in what context another missing item is profiling the database performance which seems like it may be different on azure than in a local environment especially if one starts dealing with scaling another is time spent on requests to third party services though maybe that can be done with azure performance countersi apologize for the naive nature of this question what tools and aspects am i missing here to profile an azure mvc aspnet website and what changes would you make to the above list,['asp.net'] +546157,how can i determine what log configuration source logback actually used log4j has a property log4jdebug which will helpfully provide the user with an indication of which configuration file was actually used to configure the logging systemi have not been able to find anything equivalent with the otherwise superior logback logging framework is there any way to print for diagnostic purposes at runtime which configuration file logback used to bootstrap itselfeditto clarify i would ideally like a solution that does not require me to modify the configuration file itself since a badly assembled thirdparty jar for example may be picked up incorrectly and prior to my logback configuration xml,['java'] +546163,html5 canvas resize downscale image high quality i use html5 canvas elements to resize images im my browser it turns out that the quality is very low i found this thisable interpolation when scaling a canvas but it does not help to increase the qualitybelow is my css and js code as well as the image scalled with photoshop and scaled in the canvas api what do i have to do to get optimal quality when scaling an image in the browsernote i want to scale down a large image to a small one modify color in a canvas and send the result from the canvas to the servercss canvas img imagerendering optimizequality imagerendering mozcrispedges imagerendering webkitoptimizecontrast imagerendering optimizecontrast msinterpolationmode nearestneighborjs var img imgvar originalcanvas canvasimgloadfunction var originalcontext originalcanvas0getcontext2d originalcontextimagesmoothingenabled false originalcontextwebkitimagesmoothingenabled false originalcontextmozimagesmoothingenabled false originalcontextdrawimagethis 0 0 379 500the image resized with photoshopthe image resized on canvasedit i tried to make downscaling in more than one steps as proposed inresizing an image in an html5 canvas andhtml5 canvas drawimage how to apply antialiasingthis is the function i have used function resizecanvasimageimg canvas maxwidth maxheight var imgwidth imgwidth imgheight imgheight var ratio 1 ratio1 1 ratio2 1 ratio1 maxwidth imgwidth ratio2 maxheight imgheight use the smallest ratio that the image best fit into the maxwidth x maxheight box if ratio1 ratio2 ratio ratio1 else ratio ratio2 var canvascontext canvasgetcontext2d var canvascopy documentcreateelementcanvas var copycontext canvascopygetcontext2d var canvascopy2 documentcreateelementcanvas var copycontext2 canvascopy2getcontext2d canvascopywidth imgwidth canvascopyheight imgheight copycontextdrawimageimg 0 0 init canvascopy2width imgwidth canvascopy2height imgheight copycontext2drawimagecanvascopy 0 0 canvascopywidth canvascopyheight 0 0 canvascopy2width canvascopy2height var rounds 2 var roundratio ratio rounds for var i 1 i rounds i consolelogstep i tmp canvascopywidth imgwidth roundratio i canvascopyheight imgheight roundratio i copycontextdrawimagecanvascopy2 0 0 canvascopy2width canvascopy2height 0 0 canvascopywidth canvascopyheight copy back canvascopy2width imgwidth roundratio i canvascopy2height imgheight roundratio i copycontext2drawimagecanvascopy 0 0 canvascopywidth canvascopyheight 0 0 canvascopy2width canvascopy2height end for copy back to canvas canvaswidth imgwidth roundratio rounds canvasheight imgheight roundratio rounds canvascontextdrawimagecanvascopy2 0 0 canvascopy2width canvascopy2height 0 0 canvaswidth canvasheighthere is the result if i use a 2 step down sizing here is the result if i use a 3 step down sizing here is the result if i use a 4 step down sizing here is the result if i use a 20 step down sizing note it turns out that from 1 step to 2 steps there is a large improvement in image quality but the more steps you add to the process the more fuzzy the image becomesis there a way to solve the problem that the image gets more fuzzy the more steps you add edit 20131004 i tried the algorithm of gamealchemist here is the result compared to photoshopphotoshop image gamealchemists algorithm,"['javascript', 'css']" +546192,cordovaphonegap does not make android directory ant java nodejs phonegap and my adobe account are all setup properly the getting started guide says i should be able to typecordova create hello comexamplehello helloworldto create a phonegap project this does not work but following these instructions and doingphonegap build androiddoes eventually get me a apk file but the getting started guide tells me to open eclipse and navigate to the directory of my project and then set the subdirectory as android but android does not get created when you do phonegap build android so i have nothing to work withhow do i get phonegap to create the android directory i am trying to finish the getting started guide instead of taking shortcuts,['android'] +546224,starting android service using explicit vs implicit intent according to the standard android documentation the prefered way to start a service started service that is is to use an explicit intent like this using explicit intentintent serviceintent new intentgetapplicationcontext myserviceclass orintent serviceintent new intentthis myserviceclastartserviceserviceintentyou can also startstop a service using an implicit intent with an action string specified in the manifest like this using implicit intentstatic final string serviceaction comexamplemyappservicesmyserviceintent serviceintent new intentserviceactionstartserviceserviceintent androidmanifestxmlservice androidnamecomexamplemyappservicesmyservice androidexportedfalse androidproceservices intentfilter startstop service action androidnamecomexamplemyappservicesmyservice intentfilterservicewhen the service is used only locally third party applications are not allowed to start or bind to it the documentation says that you should not include an intentfilter in the manifest service tag and you should set the exported tag to falsenote the activities and services run in separate processes application and services processes the communication between activity and service is done by implementing aidl interfaces this is done because only aidl remote interfacing allows me to do multithreading within the service that needs to handle ipc simultanously not only between activities but mostly between services running within the services processmy questions areq1 when the activities and services i use in my app are run in two different processes do i need to use implicit intents over explicit intents to start and stop the servicesq2 when the application process is gone destroyed not in memory anymore and the services process is running in the background how do i connect again from a new application process to the already running services process somehow i need to get a reference to the services process again so that i can stop the running service inside that process this cannot be done using aidl afaikthe problem is that android can and will destroy the application process easily when out of resources and that is fine by me as long as the services process keeps runningyes i know about influencing the process by setting the service as a foreground service etc i too can read manuals but that is not my problem i cannot find any information or answers related to my questions when the activities and services are in separated processes and use aidl and when the application process needs to find the services process again after it has been killed by android or when the user enters the app again after heshe left the app beforeany expertlevel advise is welcome,['android'] +546249,download blob content using specified charset is possible to change the blob charset really i am trying it for hours but it does not workds see thisjquerydownloadclickfunction var csv content jquerycsvval download documentcreateelementa blob new blobcsv content type textcsvcharsetiso88591 downloadhref windowurlcreateobjecturlblob downloaddownload testcsv var event documentcreateeventmouseevents eventinitmouseevent click true false window 0 0 0 0 0 false false false false 0 null downloadthispatcheventevent i need export a csv to open on excel but it always is save with utf8 and excel cannot handle it,['javascript'] +546270,ios 7 uisearchthisplaycontroller search bar overlaps status bar while searching i am updating my app for ios 7 and i am in the process of adjusting all my views to account for the new transparent status bar my app will still use opaque navigation barsit was relatively easy to adjust for the status bar in every view except one major problem i am having with a uisearchbar connected to a uisearchthisplaycontroller in one of my view controllersthe search bar seems to thisplay normally as shown belowthe problem is as soon as i begin searching the navigation bar thisappears as it should but everything else also moves up to overlap the status barthis does not appear to be working as intended since the darkening of the screen happens 20 pixels below the search bar where the search bar should endis there a built in solution for this in ios 7 i would rather not have to manually adjust the frame for every view each time the user begins and ends searchingthanks,['ios'] +546283,why oracle connect by with nocycle follows root cycle does anyone know why oracle continues to follow a path beyond a cyclical loop when the cycle occurs at the top node root node connected right back to root node more importantly how to prevent iti have oracle 11g release 2 112 and i have been exploring hierarchical queries i will build my question around the tree structure in figure 91 of the oracle database sql language reference page 94i created a table structe for this tree using the concept of vendors and cusomers create table t vendor varchar23 customer varchar23 insert into t values 1 2 insert into t values 2 3 insert into t values 2 4 insert into t values 4 5 insert into t values 4 6 insert into t values 1 7 insert into t values 7 8 insert into t values 1 9 insert into t values 9 10 insert into t values 10 11 insert into t values 9 12 committhe following select query traverses the tree with no problems select vendor customer level connect by isleaf as isleaf connect by iscycle as iscycle connect by root vendorsys connect by pathcustomer as path from t connect by nocycle vendorprior customer start with vendor1giving the resultsvendor cust level isleaf iscycle path1 2 1 0 0 1 22 3 2 1 0 1 2 32 4 2 0 0 1 2 44 5 3 1 0 1 2 4 54 6 3 1 0 1 2 4 61 7 1 0 0 1 77 8 2 1 0 1 7 81 9 1 0 0 1 99 10 2 0 0 1 9 1010 11 3 1 0 1 9 10 119 12 2 1 0 1 9 12i then complicated things by adding cycles to the structure first a record for a vendor who sells to themselvesa self cycle insert into t values 4 4 and one for a vendor whos customer is the vendor of their vendora ancestor cycle insert into t values 6 2 reexecuting the select query above results in the same output as above except iscycle is 1 for row 3 and row 5 paths 1 2 4 and 1 2 4 6 note that the connect by nomenclature flags the parent record of a cycle not the child record actually completing the cycle so i know 4 and 6 both cycle back to an ancestor but i donat know which ancestoradding two more records creates a larger cycle across the branches of the original tree cycle crossing branches of tree insert into t values 6 9 insert into t values 11 2 reexecuting the select query again gives the following outputvendor customer level isleaf iscycle path1 2 1 0 0 1 22 3 2 1 0 1 2 32 4 2 0 1 1 2 44 5 3 1 0 1 2 4 54 6 3 0 1 1 2 4 66 9 4 0 0 1 2 4 6 99 10 5 0 0 1 2 4 6 9 1010 11 6 1 1 1 2 4 6 9 10 119 12 5 1 0 1 2 4 6 9 121 7 1 0 0 1 77 8 2 1 0 1 7 81 9 1 0 0 1 99 10 2 0 0 1 9 1010 11 3 0 0 1 9 10 1 2 4 0 0 1 9 10 11 22 3 5 1 0 1 9 10 11 2 32 4 5 0 1 1 9 10 11 2 44 5 6 1 0 1 9 10 11 2 4 54 6 6 1 1 1 9 10 11 2 4 69 12 2 1 0 1 9 12the output continues to be as expected all cycles are flaged and the mapping stops when a cycle is encounterednow the problem childa letas add a self cycle to the root node which is exactly the same as the first cycle created above with node 4 just for node 1 insert into t values 1 1 this time oracle detects the cycle at node 1 as expected first row is flagged with iscycle set to 1 however it continues past this cycle and builds out the entire tree structure twice rows 2 through 21 are a duplication of rows 22 through 41 with the cycle of node 1 prepended onto the front of the pathvendor customer level isleaf iscycle path1 1 1 0 1 1 11 2 2 0 0 1 1 22 3 3 1 0 1 1 2 32 4 3 0 1 1 1 2 44 5 4 1 0 1 1 2 4 54 6 4 0 1 1 1 2 4 66 9 5 0 0 1 1 2 4 6 99 10 6 0 0 1 1 2 4 6 9 1010 11 7 1 1 1 1 2 4 6 9 10 119 12 6 1 0 1 1 2 4 6 9 121 7 2 0 0 1 1 77 8 3 1 0 1 1 7 81 9 2 0 0 1 1 99 10 3 0 0 1 1 9 1010 11 4 0 0 1 1 9 10 1 2 5 0 0 1 1 9 10 11 22 3 6 1 0 1 1 9 10 11 2 32 4 6 0 1 1 1 9 10 11 2 44 5 7 1 0 1 1 9 10 11 2 4 54 6 7 1 1 1 1 9 10 11 2 4 69 12 3 1 0 1 1 9 121 2 1 0 0 1 22 3 2 1 0 1 2 32 4 2 0 1 1 2 44 5 3 1 0 1 2 4 54 6 3 0 1 1 2 4 66 9 4 0 0 1 2 4 6 99 10 5 0 0 1 2 4 6 9 1010 11 6 1 1 1 2 4 6 9 10 119 12 5 1 0 1 2 4 6 9 121 7 1 0 0 1 77 8 2 1 0 1 7 81 9 1 0 0 1 99 10 2 0 0 1 9 1010 11 3 0 0 1 9 10 1 2 4 0 0 1 9 10 11 22 3 5 1 0 1 9 10 11 2 32 4 5 0 1 1 9 10 11 2 44 5 6 1 0 1 9 10 11 2 4 54 6 6 1 1 1 9 10 11 2 4 69 12 2 1 0 1 9 12why isnat the 11 cycle treated the same as the 44 cycle what am i missingto mitigate against this i added an additional condition on the connect by clause requiring that the customer not be a1a select vendor customer level connect by isleaf as isleaf connect by iscycle as iscycle connect by root vendorsys connect by pathcustomer as path from t connect by nocycle vendorprior customer and customer1 start with vendor1ironically all this did was remove the cycle flag from row one any help would be appreciated,['sql'] +546343,can a c compiler change bit representation when casting signed to unsigned is it possible for an explicit cast of say int32 t to uint32 t to alter the bit representation of the valuefor example given that i have the following uniontypedef union int32 t signed val uint32 t unsigned val signed unsigned tare these code segments guaranteed by the spec to have the same behaviouruint32 t reinterpret signed as unsignedint32 t input return uint32 t inputanduint32 t reinterpret signed as unsignedint32 t input signed unsigned t converter convertersigned val input return converterunsigned vali am considering c99 here i have seen a few similar questions but they all seemed to be thiscussing c not c,['c'] +546401,adb connection over tcp not working now i was trying to connect my adb to tcpip and have followed these stepsadb tcpip 5adb connect 1946801005i have used my device for 2 days and now i am unable to connect to my ip address like when i do adb tcpip 5 it does not respond anything anyone knows what could be the scenario,['android'] +546433,twig can not override block in included file how can i override a block inside an included template fileexample layouthtml include menuhtml menuhtml block overrideme endblock indexhtml extends layouthtml block overrideme overriden endblock i read somewhere that a trait function was implemented i cannot find any documentation about it though does anyone know how i could make this work,['php'] +546455,binding service by broadcastreceiver my application uses a service that is started by a boot complete broadcastreceiver in run i am getting an errormy code public class projet extends broadcastreceiver public void onreceivecontext context intent intent intent new intentcontext screenshotserviceclass intentaddflagsintentflag activity new task contextbindserviceintent aslserviceconn contextbind auto createerrorjavalangruntimeexception unable to start receiver comexampleprojet androidcontentreceivercallnotallowedexception broadcastreceiver components are not allowed to bind to services,['android'] +546514,rails cocoon gem undefined method new record on link to remove association with wicked i have been trying to get some code figured out i have a form i am trying to use the wicked and cocoon gem everything works including the link to add association function i am rendering a partial for the associated form fields just like cocoon recommends and everything seems to be working just find except for the link to remove association function it returns the following errorundefined method new record for nilnilclasshere is my partial that is throwing the errordiv classnestedfields div finput address1 div div finput address2 div div finput city div div finput state div div finput postal div div link to remove association remove task f divdivhere is the view that is calling the partial simple form for vendor url wizard path do f div idlocations fsimple fields for locations do location render location fields f location end div classlinks link to add association add location f locations div div div classactions fsubmit continue div end here is the controller action that is calling the viewclass userstepscontroller applicationcontroller include wickedwizard steps personal locations def show vendor current vendor uservendor vendorlocationsbuild render wizard endincase it helps here is the function in cocoon that is throwing the errordef link to remove associationargs block if block given f argsfirst html options argssecond name captureblock link to remove associationname f html options else name args0 f args1 html options args2 is dynamic fobjectnew record html optionsclass html optionsclass remove fields is dynamic dynamic existingcompactjoin hidden field tagfobject name destroy link toname html options endend,"['ruby-on-rails', 'ruby']" +546603,how to specify that gem is jruby platform only i am working on a gem which will only work for jruby platformhow can i specify that in my gemspec,['ruby'] +546607,set navigation bars to translucent no how can i set all my navigation bars to have their translucent property set to no,['ios'] +546639,how to get the html of a div on another page with jquery ajax i am using jquerys ajax code to load new pages but wanted him to get only the html of a divmy codeshtmlbody div idcontentdivbodyscriptajax urlhref typeget success functiondata contenthtmldata i wanted him to get only the html of divcontent on another page how to do it,['jquery'] +546677,postgresql thistinct on and group by syntax i realized that a database query was returning unexpected results do to my improper use of thistinct on and group byi am hoping someone can set me straight on this the actual query is quite complex so i will dumb it down i have a tableinner query that consists of an object id and a timestampcreate table test select object id int event timestamp timestamp copy test select object id event timestamp from stdin delimiter 1 20130127 2101201 20120628 1436261 20130221 0416482 20120627 1953052 20130203 1735583 20120614 2017003 20130215 1903344 20120613 1359474 20130223 0631165 20120703 0145565 20120611 213326i am trying to select a thistinct id ordereddeduplicated by the timestamp on reverse chronso the results should be 4 1 3 2 5 i think this does what i need it seems to select object id from test select group by object id order by maxevent timestamp descfor testingauditing purposes i sometimes want to include the timestamp field i cannot seem to figure out how to include another field with that querycan anyone point out glaring problems in my sql above or suggestions on how to include the auditing info,['sql'] +546703,how to have plus sign in liststyle i wonder if we can use the plus sign in the list styleinstead of thisc circle in li liststyle can we have a plus signli liststyle thisc,"['html', 'css']" +546719,checksum validation failed when submitting with xcode 5 i was submitting an app to the ios app store a few days ago and got this message from xcode before i had time to resubmit it apple has already started reviewing my app is this something i need to worry aboutedit the app was accepted a few days later,['ios'] +546758,add buttongroup to jpanel jpaneladdbuttongroupis not working i must add it to a jpanel because i am using tabsthis is getting really frustratingi hace not found a way yet,['java'] +546759,custom fonts in xcode 5 how would you add a custom font in xcode 5 and how would you change every label in the project to that font because i have heard you can only do this programmatically,['iphone'] +546774,the jar of this class file belongs to container android dependencies which does not allow source modifications to source attachments on its entries i have a library project and another project which uses some classes from the library project as soon as i am setting a break point in one of the library classes and my app stops at the break point eclipse shows me the error messagesource not foundthe jar of this class file belongs to container android dependencies which does not allow source modifications to source attachments on its entriescan someone help me,['android'] +546822,how to detect mobile safari browser in ios 7 what is the official method to detect mobile safari on ios7for example navigatoruseragentmatchipodiphoneipad navigatoruseragentmatchapplewebkit navigatoruseragentmatchos 7,['jquery'] +546846,extra space above search bar when uisearchthisplaycontroller is active i have a popover with a uitableviewcontroller as the content view controller the table view has a uisearchbar as its header viewnow on ios 6 everything looks good when the uisearchthisplaycontroller becomes active but on ios 7 there will be an extra space above the search barso how can i get rid of this extra space above the search bar on ios 7,['ios'] +546851,mfmailcomposeviewcontroller in ios 7 statusbar are black i have a feedback button in my ios 7 application with mfmailcomposeviewcontroller after the user click this button the mailcomposer open but the statusbar changed to black have anybody a idea what can i doi have this problem only with ios7 i customizing my app for ios7 mfmailcomposeviewcontroller mailcontroller mfmailcomposeviewcontroller alloc init mailcontrollermailcomposedelegate self mailcontroller setsubjectfeedback fill out the email body tex nsstring emailbody nsstring stringwithformattestest uidevice currentdevicemodel uidevice currentdevicesystemversion mailcontroller setmessagebodyemailbody ishtmlno mailcontroller settorecipientsnsarray arraywithobjectsnil thispatch asyncthispatch get main queue self presentmodalviewcontrollermailcontroller animatedyes,['ios'] +546879,how to stop unwanted uibutton animation on title change in ios7 my uibutton titles are animating in and out at the wrong time late this problem does not appear on ios6 i am just using self settitletext forstateuicontrolstatenormali would prefer this happens instantly and without a blank frame this blink is especially thistracting and draws attention away from other animations thx,['objective-c'] +546939,align text using drawinrectwithattributes in the ios 5 version of my app i hadselftext drawinrect stringrect withfont uifont fontwithname courier size kcellfontsize linebreakmode nslinebreakbytruncatingtail alignment nstextalignmentrighti am upgrading for ios 7 the above method is deprecated i am now using drawinrectwithattributes the attributes parameter is an nsdictionary object i can get drawinrectwithattributes to work for the former font parameter using this uifont font uifont fontwithname courier size kcellfontsize nsdictionary dictionary nsdictionary alloc initwithobjectsandkeys font nsfontattributename nil selftext drawinrect stringrect withattributes dictionarywhat keyvalue pairs do i add to dictionary to get nslinebreakbytruncatingtail and nstextalignmentright,['ios'] +546984,combine stretchblt and transparentblt properly so transparent bitmap can be created properly introduction and relevant informationrecently i have asked here in so a question about scaling a bitmap properly so it can keep the quality of the picturebitmap loses quality when stretchedshrinked on buttons backgroundi have tried to employ a suggestion made in a comment to use stretchblt so i have made a small demo program it did improve the bitmaps sharpness after i have set stretch mode to blackonwhitei would like to try to make the portion of the bitmap with the certain colorsay black for example transparenti have used transparentblt before but i do not know how to do it nowproblemin order to preserve the sharpness of the picture i need to stretchblt it in the memory dc with stretch mode being blackonwhitethe problem is that i do not know how to blt it transparently into main windows dchere is a code snippet from the demo app case wm paint main windows dc hdc beginpainthwnd ps main windows client rectangle rect r getclientrect hwnd r memory dc for double buffering hdc memdc createcompatibledc hdc fill it with test brush fillrect memdc r hbrushgetstockobject gray brush select loaded bitmap into memory dc hbitmap old hbitmapselectobject memdc bmp get bitmaps dimensions bitmap b getobject bmp sizeofbitmap b needed to preserve bitmaps sharpness setstretchbltmode hdc blackonwhite stretchblt hdc 0 0 rright rleft rbottom rtop memdc 0 0 bbmwidth bbmheight srccopy transparentblt call should go here so i can make portion of the bitmap transparent in order for the gray brush can be seen cleanup selectobject memdc old deletedcmemdc endpainthwnd ps return 0l breakquestionhow to modify the above code so a bitmap can be transparent in order for test brush to be seen the original image is bellowi just need to use transparentblt rgb 0 0 0 to make it transparent in black areasthe example picture that shows resultmy effortsbrowsing through internet i have found only simple tutorials regarding double bufferingi have not found anything like this but to be honest i am inexperienced in win32 api so i do not know how to phrase the question properly in order to get better search resultsif further information is required ask for it and i will supply itit is omitted to keep the question short,['c++'] +547012,calling uiviewcontroller method from app delegate i know there are duplicates of this question but my situation is different herewhen user goes back to the home voidapplicationdidenterbackground gets invoked from the appdelegate class however once user presses home button i do not want user to see this view controller again so i have a method named voidgotobeginning that switches to another view controller i want to be able to call this method from appdelegate i do not really want to use notificationcenter for this also the picked solution herecalling view controller method from app delegatedoes not work for me as it initialises new object whereas i want to be able to call an object that is already in the view how can i do that i am using ios 7 and xcode 5,"['ios', 'objective-c']" +547036,automatically remove hotdead pixels from an image in python i am using numpy and scipy to process a number of images taken with a ccd camera these images have a number of hot and dead pixels with very large or small values these interfere with other image processing so they need to be removed unfortunately though a few of the pixels are stuck at either 0 or 255 and are always at the same value in all of the images there are some pixels that are temporarily stuck at other values for a period of a few minutes the data spans many hours i am wondering if there is a method for identifying and removing the hot pixels already implemented in python if not i am wondering what would be an efficient method for doing so the hotdead pixels are relatively easy to identify by comparing them with neighboring pixels i could see writing a loop that looks at each pixel compares its value to that of its 8 nearest neighbors or it seems nicer to use some kind of convolution to produce a smoother image and then subtract this from the image containing the hot pixels making them easier to identify i have tried this blurring method in the code below and it works okay but i doubt that it is the fastest also it gets confused at the edge of the image probably since the gaussian filter function is taking a convolution and the convolution gets weird near the edge so is there a better way to go about thisexample codeimport numpy as npimport matplotlibpyplot as pltimport scipyndimagepltfigurefigsize84ax1 pltsubplot121ax2 pltsubplot122make a sample imagex nplinspace55200xy npmeshgridxxz 255npcosnpsqrtx2 y22for i in range011 add some hot pixels znprandomrandintlow0high199nprandomrandintlow0high199 nprandomrandintlow200high255 and dead pixels znprandomrandintlow0high199nprandomrandintlow0high199 nprandomrandintlow0high10then plot itax1set titleraw data with hot pixelsax1imshowzinterpolationnearestoriginlowernow we try to find the hot pixelsblurred z scipyndimagegaussian filterz sigma2difference z blurred zax2set titledifference with hot pixels identifiedax2imshowdifferenceinterpolationnearestoriginlowerthreshold 15hot pixels npnonzerodifferencethreshold differencethresholddo not include the hot pixels that we found near the edgecount 0for yx in ziphot pixels0hot pixels1 if x 0 and x 199 and y 0 and y 199 ax2plotxyro count 1print detected i hotdead pixels out of 20countax2set xlim0200 ax2set ylim0200pltshowand the output,['python'] +547037,gcc optimization missed opportunity i am compiling this c codeint mode use aa if true else bbint aa2int bb2inline int auto0 return mode aa0 bb0 inline int auto1 return mode aa1 bb1 int slow return auto1 auto0 int fast return mode aa1 aa0 bb1 bb0 both slow and fast functions are meant to do the same thing though fast does it with one branch statement instead of two i wanted to check if gcc would collapse the two branches into one i have tried this with gcc 44 and 47 with various levels of optimization such as o2 o3 os and ofast it always gives the same strange resultsslow movl moderip ecx testl ecx ecx je l10 movl aa4rip eax movl aarip edx subl edx eax retl10 movl bb4rip eax movl bbrip edx subl edx eax retfast movl moderip esi testl esi esi jne l18 movl bb4rip eax subl bbrip eax retl18 movl aa4rip eax subl aarip eax retindeed only one branch is generated in each function however slow seems to be inferior in a surprising way it uses one extra load in each branch for aa0 and bb0 the fast code uses them straight from memory in the subls without loading them into a register first so slow uses one extra register and one extra instruction per calla simple microbenchmark shows that calling fast one billion times takes 07 seconds vs 11 seconds for slow i am using a xeon e52690 at 29 ghzwhy should this be can you tweak my source code somehow so that gcc does a better jobedit here are the results with clang 42 on mac osslow movq aagotpcrelrip rax rax aa both ints at once movq bbgotpcrelrip rcx rcx bb movq modegotpcrelrip rdx rdx mode cmpl 0 rdx mode 0 leaq 4rcx rdx rdx bb1 cmovneq rax rcx if mode 0 rcx aa leaq 4rax rax rax aa1 cmoveq rdx rax if mode 0 rax bb movl rax eax eax xx1 subl rcx eax eax xx0fast movq modegotpcrelrip rax rax mode cmpl 0 rax mode 0 je lbb1 2 if mode 0 movq aagotpcrelrip rcx rcx aa jmp lbb1 3 else lbb1 2 mode 0 movq bbgotpcrelrip rcx rcx bblbb1 3 movl 4rcx eax eax xx1 subl rcx eax eax xx0interesting clang generates branchless conditionals for slow but one branch for fast on the other hand slow does three loads two of which are speculative one will be unnecessary vs two for fast the fast implementation is more obvious and as with gcc it is shorter and uses one less registergcc 47 on mac os generally suffers the same issue as on linux yet it uses the same load 8 bytes then twice extract 4 bytes pattern as clang on mac os that is sort of interesting but not very relevant as the original issue of emitting subl with two registers rather than one memory and one register is the same on either platform for gcc,['c'] +547063,shell form does not validate jsfiddle i am getting this lengthy error when i run this jsfiddle error shell form does not validatehtml initial name uinitialjs lib form mooshellformsshellform object at 0xa965bac html name js lib html initial id uinitialid js lib label ujs lib field djangoformsmodelsmodelchoicefield object at 0xaaeb76c help text name js libhtml initial name uinitialjs wrap form mooshellformsshellform object at 0xa965bac html name js wrap html initial id uinitialid js wrap label ujs wrap field djangoformsfieldstypedchoicefield object at 0xa9f82cc help text name js wraphere is the codewhtmldoctype htmlhtmlheadscriptfunction greetingdocumentgetelementbyidp1innerhtmldocumentformsfrm1fnamevaluescriptheadbodywhat is your namebrform namefrm1 onsubmitgreeting methodpostinput typetext namefnameinput typesubmit valuesubmitformp idp1pbodyhtml,['javascript'] +547115,can we use guid as a primary key in sqlite database is is possible to use guid as primary keys in sqlite databaseif possible which datatype can be used,['android'] +547142,frame and bounds of cashapelayer i am working on cashapelayerand trying to draw nonlinear pathi want to set frame to cashapelayerso i can use cgpathgetpathboundingbox method to get frame from cgpathrefhere is code cgmutablepathref path cgpathcreatemutablecgpathaddarcpath null rectsizewidth2 rectsizeheight2 100 0 m pi 2 nocgpathaddarcpath null rectsizewidth2 rectsizeheight2 10050 m pi 2 0 yescgpathclosesubpathpathcashapelayer arclayer cashapelayer allocinitarclayerpath patharclayerframe cgpathgetpathboundingboxpatharclayerbounds cgpathgetpathboundingboxpathselflayer addsublayerarclayer please refer my code carefully i have set same frame and bounds to cashapelayermy problem is if i am not setting bounds same as frame then it wont show my content or it wont show my content within framewhyplease help methanking you,['ios'] +547159,ios 7 backbarbuttonitem hidden i have an issue with back bar button it stay hidden no matter that i do like selfnavigationitemhidesbackbuttonhere is my code to add back button voidviewdidload uibarbuttonitem back uibarbuttonitem alloc initwithtitlenslocalizedstringui btn back nil styleuibarbuttonitemstyleplain targetnil actionnil backtintcolor templates getcolorcolor self navigationitem setbackbarbuttonitemback parent super viewdidloadbutton stay hidden but going back works if if touch on the place where it should beof course it works on ios6another detail back button seems to appear when i set uinavigationbar translucent to yesthanks,"['ios', 'objective-c']" +547162,how does cvtermcriteria work in opencv i want to use the opencv function cvcornersubpix for that i need another one the cvtermcriteria my question is about the last parmeter of this function cvtermcriteriacvtermcriteriamax iter cvtermcriteriaeps 50 max number of iterations 01 min accuracywhat does the min accuracy here mean,['c++'] +547189,break letters of second child div i have one requirement where i need to apply width to the parent element which is equal to the first child elements width this can be easily achieved using thisplay inlineblock or float left to the parent element if it has only one child element but i have more than two child elements in a div something like thisfiddlediv classmain div classfirstfirstdiv div classvaluevaluevaluedivdivright now if i apply thisplay inlineblock to the parent element then it is having the width of the second child elementto not happen this i tried breakword wordbreak css properties on the second child element but still no usewhat i am trying to get is illustrated in the following screenshotsome important pointswidth of the parent element should be equal to the first child elementheight of the parent element should be equal to sum of all the child elementsi do not know the width of the first child elementedit the first child element has some fixed width and height i do not know these valuesi want to do this using just css css3 is welcome i know how to do this using javascript,"['html', 'css']" +547191,facebook twitter icon not showing in uiactivityviewcontroller on ios7 i have added this code for presenting a uiactivityviewcontrolleribactionactivityactionidsender uiactivityviewcontroller activityviewcontroller uiactivityviewcontroller allocinitwithactivityitemsnsarray arraywithobjectshello welcomeuiimage imagenamedscene3jpgnil applicationactivitiesnil activityviewcontrollerexcludedactivitytypes uiactivitytypeposttofacebook uiactivitytypeposttotwitter uiactivitytypeposttoweibo uiactivitytypeassigntocontact self presentviewcontrolleractivityviewcontroller animatedyes completionnilfacebook twitter and weibo icons are not showing in ios7 in ios6 all the icons are showing correctly see the screenshot belowhow can i solve this,['objective-c'] +547196,how to find the largest difference in an array suppose i have an array of integersint a 10 3 6 8 9 4 3 my goal is to find the largest difference between aq and ap such that q pfor example if p 2 and q 3 then diff aq apdiff 8 6diff 2if p 1 and q 4diff aq apdiff 9 3diff 6since 6 is the largest number between all the difference that is the answermy solution is as follows in c but it is inefficientpublic int solutionint a int and alength if n 1 return 0 int difference int largest 0 for int p 0 p n p for int q p 1 q n q difference aq ap if difference largest largest difference return largesthow can i improve this so it will run at on thankssimply getting the max and min wont work minuend q should come after the subtrahend pthis question is based on the maxprofit problem in codility my solution only scored 66 it requires on for a score of 100,['c#'] +547251,how can i make vs break on exceptions in an async task without breaking on all exceptions as indicated here and here exceptions occuring in an async task are technically not unhandledthis is particularly nasty when working with mvc it actually took us a while to figure out why it was occurring more and more that exceptions werent being caught we had been gradually introducing web api calls to our aplication the past few weekspublic async taskactionresult foo the suggested workaround is to make vs break on all exceptions instead of only unhandled exceptions it works with the annoying sideeffect that it does indeed break on all exceptions is there another workaround that does not involve breaking on all exceptions it can be specific to mvc but does not have to be meaning if it is a general solution that happens to work for mvc,['c#'] +547254,android webbrowser scroll down page i developed an android app with delphi xe 5 and i put a webbrowser because i must show a webpage by the way the webpage has a width of 1400px and so it is not entirely thisplayedthe width is fixed because i used on the webpage width100 but as you can see on the picture i only have a part of the table i am missing a scroll bar that allows me to slide down the page and look at the rest of the tablei tried to add a tvertscrollbox and inside it i put the webbrowser but i still see only the beginning of the page i cannot scroll it downhow could i fix this the webpage already have a div with a scroll bar on the left you can click here to see the entire page,"['android', 'html']" +547263,with nsprogress are the completion handlers intended for the ui or the download controller i am using nsprogress to communicate the progress of file downloads in my ios appit is a very generalpurpose class and i am a bit scared of its inherent power especially with the two completion handling properties there is one for dealing with canceling and one for pausing but none for completion which is perhaps a hitawhat are these handlers intended for the code that does the download could put logic in these to deal with useroriginated cancels and pauses however there is nothing stopping a client to overwrite the handlers with ui codeso is it intended for the ui i am not sure how this is a helpful patterns since the ui would be originating the cancel or pause anyway also if you are using the progress object to simultaneously present progress across multiple ui elements the way it is used in macos the different ui elements would potentially all want its own completion handlerusing the handlers to communicate user actions back to the download controller seems the most useful pattern but then i would have expected the handler to be set up at initialization and then remain readonlywhat am i missing hereps for now i am simply not going to use those handlers and rely on kvo however i have an itchy feeling that i am missing out on some fundamental idea behind the class,['objective-c'] +547268,forcing landscape and autorotate in ios 7 my app is supposed to be landscape only and i had no problem with this when building for ios 6 and earlier now with ios 7 it would not rotate at allin my app settings i have it set to landscape leftright only in my view controller i am using the following nsuintegersupportedinterfaceorientations return uiinterfaceorientationlandscapeleft uiinterfaceorientationlandscaperighti also used to use this which is now deprecated boolshouldautorotatetointerfaceorientationuiinterfaceorientationorientation return uiinterfaceorientationislandscapeorientationthe new one appears to be shouldautorotate but using this crashes my app any ideas on this would be appreciated since my app is forced to portrait on my ipad and in the simulator thank you,['ios'] +547313,why datetimeparseexactstring string iformatprovider need the iformatprovider if were using the parseexact method for exact datetimes parsing using a specified format why do we need to provide a iformatprovider object what is the point behind itfor exampledatetimeparseexactdatestring format providerwhy do we need the provider here,['c#'] +547387,add file as a link on visual studio debug vs publish every time i have to link a file into an aspnet project as link there is always something i forget to do because visual studio is way too buggy and annoying with thesethere is a buglimitation with it so it does not copy the file into the debug output folder and we must change the properties of the file so that it is copied into the publish output folder as welli learned this in the hard way after a lot of research and i created an afterbuild target to help in making this process easier however there is still some manual work to do when adding the filehere is an example for a project i maintain say we want to add the file yiucard in the autilitiesa folder of the aspnet project1 rightclick autilitiesa folder on visual studio and select aadd existing itema2 select the file to add clicking on it once do not doubleclick3 click in the arrow next to the aadda button and select aadd as linkaat the moment this will do nothing the file wonat be copied to any folder debug and publish it is just added to the project 4 rightclick in the file and open properties5 changeabuild actiona to acontentaacopy to output directorya to acopy alwaysaat this time the file will be copied into the publish output folder anywhere we define when publishinghowever when we debug locally f5 it wonat work because the file is not copied into the local autilitiesa folder on the codebase6 save the changes on visual studio by selecting asave alla this is so that the acsproja file is saved as we made changes on it and we will now edit it manually7 open the acsproja in notepad8 add the file to the beforebuild event heres mine target namebeforebuild itemgroup utilitiesfiles includepathtofileredopxxnew utilitiesfiles includepathtofileredfmtst utilitiesfiles includepathtofilejobcard utilitiesfiles includepathtofileyiucard itemgroup copy sourcefilesutilitiesfiles destinationfolderutilities skipunchangedfilestrue target9 i have an afterbuild event for release mode that automatically publishes the project for me so that the files go directly to the output folder i want target nameafterbuild condition configuration release propertygroup outputdirpathtopublishmyprojectoutputdir propertygroup message importancehigh textoutput dir outputdir removedir directoriesoutputdir continueonerrortrue msbuild projectsmyprojectcsproj propertiesconfigurationconfigurationwebprojectoutputdiroutputdiroutdiroutputdirbin targetsresolvereferences copywebapplication target10 save the file in notepad and reload it on visual studiowhen you build the project the file will be copied to both debug and releasepublish foldershowever i would like to know if there is any easierintuitive way to do thisyou may say that this would be fixed by changing the debug output folder to the same as the releasepublish folder so that the files would be there after the first time i publishedhowever please note that there is a bug with this as well if i use an output folder other than the bin aspx files will complain that they cannot find the assemblies even if i set copy to output directory to copy always it will complain that globalasaxcs could not be foundplease see these related questionsparser error message could not load type testmvcapplicationmvcapplicationcould not load type namespaceglobal causing me griefis this fixedimproved in the newer versions of visual studio,"['c#', 'asp.net']" +547429,difference between await and continuewith can someone explain if await and continuewith are synonymous or not in the following example i am trying to use tpl for the first time and have been reading all the documentation but do not understand the differenceawaitstring webtext await getwebpageuriawait parsedatawebtextcontinuewithtaskstring webtext new taskstring getwebpageuritask continue webtextcontinuewithtask parsedatataskresultwebtextstartcontinuewaitis one preferred over the other in particular situations,['c#'] +547458,index into size ordered power set i would like to be able to index elements of a power set without expanding the full set into memory a la itertoolsfurthermore i want the index to be cardinality ordered so index 0 should be the empty set index 2n 1 should be all elementsmost literature i have found so far involves generating a power set inductively it does not let you just dive in at any index my motivation for this indexing is to slice a problem for thistributed execution and it be helpful if a remote machine can just dive in anywhere without sharing an iterator reference across a clusteredit blckknght suggested the solution i pursued which is shown belowfrom scipymisc import combdef kcombination to indexcombination index 0 combination sortedcombination for k ck in enumeratecombination index combck k1 exacttrue return indexdef index to kcombinationindex k result for k in reversedrange1 k1 and 0 while combn k exacttrue index and 1 resultappendn1 index combn1 k exacttrue return resultclass powerset def init self elements selfelements elements def len self return 2 lenselfelements def iter self for i in rangelenself yield selfi def getitem self k if not isinstancek int raise typeerror k0 is empty set k 1 1n returns subsets of size 1 for subset size in rangelenselfelements 1 number subsets comblenselfelements subset size exacttrue if k number subsets k number subsets else break we now want the kth element of a possible permutation of subset size elements indeces index to kcombinationk subset size return maplambda i selfelementsi indecesif name main print index of combination 8 6 3 1 0 is kcombination to index8 6 3 1 0 print 5 combination at position 72 is index to kcombination725 ps powerseta b c d for subset idx in rangelenps print pssubset idx,['python'] +547518,why would not the bcrypt ruby gem install properly i am trying to encorporate bcryptruby v 301 i enter the gem in my gem file as followsgem bcryptruby 301and i then go to the terminal and runbundle installi get the following responsegeminstallerextensionbuilderror error failed to build gem native extension usrlocalrvmrubiesruby193p392binruby extconfrb creating makefilemakecompiling bcrypt extcmake gcc42 no such file or directorymake bcrypt exto error 1gem files will remain installed in usersphilip7899bundlertmp2186gemsbcryptruby301 for inspectionresults logged to usersphilip7899bundlertmp2186gemsbcryptruby301extmrigem makeoutan error occurred while installing bcryptruby 301 and bundler cannot continuemake sure that gem install bcryptruby v 301 succeeds before bundlingi am extremely new to both ruby and rails and have no idea how to fix this i have seen other stackoverflow pages with similar questions but none have been able to help me i recently upgraded to mountain lion and was told that could be an issue i was told to use rvm to uninstall and then reinstall ruby i tried that and it did not workplease help thank you,['ruby-on-rails'] +547530,construct two dimensional numpy array from indices and values of a one dimensional array say i have goty nparray2 0 1 1from this i want to obtain a matrix x with shape leny 3 in this particular case the first row of x should have a one on the second index and zero otherwhise the second row of x should have a one on the 0 index and zero otherwise to be explicitx nparray0 0 1 1 0 0 0 1 0 0 1 0how do i produce this matrixi started withx npzerosyshape0 3but then could not figure out how to populatefill in the ones from the list of indicesas always thanks for your time,['python'] +547534,how to wrap text around attachments using ios7 text kit i am using the new text kit api to add attachments to some attributed text create an attachment for each imagenstextattachment ta nstextattachment newtaimage uiimage imagenamedimagename add to the attributed text stringnsattributedstring rep nsattributedstring attributedstringwithattachmenttamyattributedtextstring appendattributedstringrepthis works fine i can see my image rendered in the output however i cannot find any way to specify the image alignment or wrap text around the imageany ideasnote text attachments are different from exclusions paths a text attachment is part of the model ie it is part of the attributed text string that the layout manager performs text layout on whereas an exclusion path is part of the view,"['ios', 'objective-c']" +547590,xcodecolors not working in xcode 5 i tried to install xcodecolors in xcode 5 but unfortunately it is not working with the old plugin i got from xcode 46as next step i checked the github website where i saw the following pull request providing a working version for xcode 5 i have downloaded the project and run it in release mode but there is not any xcodecolors created in the plugin directory does anybody have a working xcodecolors plugin in xcode 5,['ios'] +547618,where can i change the default character set of a table in mysql workbenchs data modeling tool i created a database schema using mysql workbenchs data modeling tool when it generates the sql create statements it generates default character set latin1 for some tables eg table moocdbresource types create table if not exists moocdbresource types resource type id int11 not null resource type name varchar20 character set utf8 not null primary key resource type idengine innodbdefault character set latin1how can i change it to the schemas default character set i found where to change the schemas default character set but not the tables,['mysql'] +547621,how to detect if m7 is present aka it is an iphone 5s or newer trying to find a way to detect m7 being present is it pointless to query cmstepcounter or cmmotionactivity class if m7 is not present my guess is that on non m7 models having ios 70 these classes get data but not that efficiently use a lot more batterya crude way would bestruct utsname systeminfounamesysteminfomodel nsstring alloc initwithcstringsysteminfomachine encodingnsutf8stringencodingversion nsstring alloc initwithstringuidevice currentdevice systemversionif model compareiphone61,['ios'] +547623,how do i set up httpcontent for my httpclient postasync second parameter public static async taskstring getdatastring url string data uribuilder fulluri new uribuilderurl if stringisnulloremptydata fulluriquery data httpclient client new httpclient httpresponsemessage response await clientpostasyncnew uriurl expects httpcontent responsecontentheaderscontenttype new mediatypeheadervalueapplicationjson responseensuresuccestatuscode string responsebody await responsecontentreadasstringasync return responsebodythe postasync takes another parameter that needs to be httpcontenthow do i set up an httpcontent there is no documentation anywhere that works for windows phone 8if i do getasync it works great but it needs to be post with the content of keybla somethingyayeditthanks so much for the answer this works well but still a few unsures here public static async taskstring getdatastring url string data data testsomething httpclient client new httpclient stringcontent querystring new stringcontentdata httpresponsemessage response await clientpostasyncnew uriurl querystring responsecontentheaderscontenttype new mediatypeheadervalueapplicationjson responseensuresuccestatuscode string responsebody await responsecontentreadasstringasync return responsebody the data testsomething i assumed would pick up on the api side as post data test evidently it does not on another matter i may need to post entire objectsarrays through post data so i assume json will be best to do so any thoughts on how i get post data throughperhaps something likeclass somesubdata public string line1 get set public string line2 get set class postdata public string test get set public somesubdata lines get set postdata data new postdata test something lines new somesubdata line1 a line line2 a second line stringcontent querystring new stringcontentdata but obviously that would not work,['c#'] +547631,application loader stuck at the stage of authenticating with the itunes store i was about to upload an app to itunes connectbut the application loader has been stuck at the stage of authenticating with the itunes store and pending for almost an hournetwork is fine and i have never seen this beforehas anybody encountered this kind of issue what is the solutionthanks in advance,"['iphone', 'ios']" +547655,xcode 5 ios 7 cocoapods linker error i just upgraded my old project to new ios 7 it was already using cocoapods i compile and run and everything works fine on the simulator and the device i tried to archive it using xcode and i get the following error ld library not found for lpodsclang error linker command failed with exit code 1 use v to see invocationany ideas update the architecture for the pods project is set as the following standard architectures armv7armv7ssolution cocoapods has been removed from my project everything is good now,['ios'] +547666,strongnaming with internalsvisibleto tag fails when sha256 used when using c strongnames on dlls and using the internalsvisibleto tags andwhen the public key uses sha256 or sha512were noticing that the compile process fails as if the internalsvisibleto tags were never even declared the error we get is myinternalclass is inaccessible due to its protection level snipwhen the public key uses sha1 in step 3 above the compile process works perfectly with no issues and the internals are exposed properly to the test project the way were creating the strongname keys issn k 4096 signkeysnksn p signkeysnk signkeypublicsnk sha256sn tp signkeypublicsnkand the way were exposing the projects internals to it is test project isassembly internalsvisibletomyprojecttest publickeylongpublickeyherewhich we stick inside the propertiesassemblyinfocs of the myproject projectquestion how to use sha256 or better in the strongname processedit or is this a bug in the vs2012 toolsplatform tools vs2012 update 3 net 45 windows 8 x64,['c#'] +547690,load images from assets folder i have an android application in which i have several images in assets folder now i want to make an array of that images now my problem is when our images are in drawable we can make an array likeint x rdrawabless rdrawableaa rdrawablesk rdrawablexxand so on how can i make an array of images same as above when my images are in assets folder i want to make an array at class level,['android'] +547737,compiletime rearrangement of data members i was wondering about a possible way to make memory layout of a class to be more effective in templated code as far as i know standard mandates data members of a class to be laid out in memory on order of their declaration there might be possible padding done by the compiler to align the data members adding unnecessarily to the size of the class the idea is to rearrange data members declarations at compile time to minimize such padding i did some searching but could not find any info most of the time people thiscuss packing compiler directives which is not quite the same as i see itfirst please consider the following trivial but repetitive and ugly code same code on ideonecom questions are below the code feel free to skip right down to theminclude iostreaminclude cstdintnamespace sotemplate typename ta typename tb typename tc stdsize t sizeofta sizeoftb sizeoftb sizeoftc 10 sizeofta sizeoftc sizeoftc sizeoftb 11 sizeoftb sizeofta sizeofta sizeoftc 20 sizeoftb sizeoftc sizeoftc sizeofta 21 sizeoftc sizeofta sizeofta sizeoftb 30 sizeoftc sizeoftb sizeoftb sizeofta 31 0struct foo template typename ta typename tb typename tcstruct foota tb tc 10 ta a tb b tc c foota a tb b tc c a a b b c c template typename ta typename tb typename tcstruct foota tb tc 11 ta a tc c tb b foota a tb b tc c a a c c b b template typename ta typename tb typename tcstruct foota tb tc 20 tb b ta a tc c foota a tb b tc c b b a a c c template typename ta typename tb typename tcstruct foota tb tc 21 tb b tc c ta a foota a tb b tc c b b c c a a template typename ta typename tb typename tcstruct foota tb tc 30 tc c ta a tb b foota a tb b tc c c c a a b b template typename ta typename tb typename tcstruct foota tb tc 31 tc c tb b ta a foota a tb b tc c c c b b a a template typename ta typename tb typename tcstruct bar public foota tb tc private using base foota tb tc public bar default using basebasetemplate typename ta typename tb typename tcstruct foobar ta a tb b tc c foobar default foobarta a tb b tc c a a b b c c namespace soint main sobarstduint16 t stduint32 t stduint16 t bar1 2 3 sofoobarstduint16 t stduint32 t stduint16 t foobar1 2 3 stdcout sizeofbar t sizeoffoobar stdendl stdcout bara barb barc stdendl stdcout foobara foobarb foobarc stdendl return 0program output8 121 2 31 2 3questionsis there some wellknown compilerindependent way of solving such thing boost maybeif no is there some compilerspecific directives that will do such thing automatically without data misalignment as with gccs atribute packedcan this be done in a more generic way possibly using variadic templatesthanks in advance,['c++'] +547751,does using the object initializer on collection types set the initial capacity does using the object initializer on a collection type set it is capacity or do you still need to specify itthat is doesvar list new liststring one two result in the same as thisvar list new liststring2 one two,['c#'] +547775,dynamically creating div using javascriptjquery i have two div called answerdiv 1 answerdiv 2 in htmlnow i want to givecreate div id uniquely like answerdiv 3 answerdiv 4 answerdiv 5 and so onusing javascriptjquery how can i append stuff in these dynamically created divs which id should be uniquein my project user can add n numbers of div there is no strict limit to ithelp me outthanks in advmy html code is div idanswertextdiv textarea idanswertext nameanswertext placeholdertype answer here rows2 cols40 tabindex6 onblurexchangelabelsanswertxtthistextareadivmy js codefunction exchangelabelsanswertxtelement var result elementval ifresult elementremove answertextdivappendlabel idanswertext onclickexchangefieldanswertxtthisresultlabel function exchangefieldanswertxtelement var result elementinnerhtml elementremove answertextdivappendtextarea idanswertext nameanswertext placeholdertype answer here rows2 cols40 tabindex6 onblurexchangelabelsanswertxtthisresulttextareanow from above code i want to append all stuff in unique answertextdiv id,"['javascript', 'jquery', 'html']" +547784,windows phone 8 mvvm viewmodels and appxamlcs i have been studying the mvvm pattern and putting it into practice in a windows phone 8 app and i have a question about the best practices for initializing and accessing viewmodels in an appwhen i create a databound application from the wp8 sdks templates i noticed this code in the appxamlcs filepublic static mainviewmodel viewmodel get delay creation of the view model until necessary if viewmodel null viewmodel new mainviewmodel return viewmodel private void application activatedobject sender activatedeventargs e ensure that application state is restored appropriately if appviewmodelisdataloaded appviewmodelloaddata from what i understand that means that the app class contains the mainviewmodel as a static member and when the application is activated the viewmodel is loadedthat being the case i have the following questionsif my app has several viewmodels would all of them be stored as members inside the appxamlcs fileif every viewmodels data is loaded at the same time how do i manage my apps memory is it possible to unload each viewmodels data and only load the viewmodel that is being used by my view,['c#'] +547809,change status bar text colour from white ios 7 xcode 5 i am developing an application for a school that i work at currently i am having issues with changing the status bar text from it is default state of black to white so we can actually read iti have tried everything i have found here and on the dev forums including calling view controllerbased status bar appearance no and also uiapplication sharedapplication setstatusbarstyleuistatusbarstylelightcontent,"['ios', 'objective-c']" +547816,ios7 empty autolayout layout already ambiguous i just created an empty ios project for a single view application which targets ios7 but when i ran the empty project and inspected my viewtree by typing po uiwindow keywindow autolayouttracei got the result that the two layout guides are already ambiguousuiwindow0x108f537f0 ambiguous layout uiview0x109409850 uilayoutguide0x109409c10 ambiguous layout uilayoutguide0x10940a540 ambiguous layoutis there a reason to get rid of those warnings or can i simply ignore them,['ios'] +547822,div element would not stay at the bottom when ios 7 virtual keyboard is present i am having a problem with a div element to stick to the bottom of my web app when ios 7 virtual keyboard appears after pressing a textboxi have this div element div idfooter styletextaligncenter div ididnameimg altsomename srcimageslogopng div div formbodyit uses this stylefootercolorcheight 48pxpositionfixedzindex5bottom0pxwidth100paddingleft2pxpaddingright2pxpadding0bordertop1px solid 4background2 old browsers backgroundwebkitgradientlinear 0 0 0 100 colorstop0 9 colorstop002 6 colorstop1 2 background mozlineargradienttop 9 6 2 2 ff36 background webkitlineargradienttop 9 6 2 2 chrome10safari51 background olineargradienttop 9 6 2 2 opera 10 background mslineargradienttop 9 6 2 2 ie10 background lineargradienttop 9 6 2 2 w3c and when i press on the textbox the footer elementer jumps up above the virtual keyboardit used to work when my idevices was running on versions before ios 7on the left side is before pressing the textbox and on the right side is after pressing the textboxthe footer jumps above the virtual keyboardupdatei have changed the meta tag provided by opossum and now the footer stays at the bottommeta httpequivcontenttype contenttexthtml charsetutf8 meta nameviewport contentinitialscale10 userscalable0meta nameviewport contentwidthdevicewidth heightdeviceheight initialscale10 maximumscale10 targetdensitydpidevicedpimeta nameapplemobilewebappcapable contentyes meta nameapplemobilewebappstatusbarstyle contentblack extensionthis is not a part of the question but the fix screws things up when running on a android any solution for thatsolution removed maximumscale and targetdensitydpi and now it works for both ios and android the meta tag now looks like thismeta nameviewport contentinitialscale10 userscalable0 widthdevicewidth heightdeviceheight,"['html', 'asp.net', 'css']" +547881,not able to type in textfield in iphone simulator using mac keyboard i am working on a basic application which is working in portrait as well as in landscape mode when the iphone simulator keyboard is open in landscape and i am switching the app to portrait mode i am not able to type anything in a text field using my mac keyboardhas anyone experienced this before is it a known bug,['iphone'] +547968,center align placeholder issue in android in my android application there is webview to thisplay htmlin webview for input field we want placeholder to center alignplacing stylewebkitinputplaceholder textalign centerbut placeholder is not aligning center it is working fine with browser when we testcould any one help me on it,['android'] +547978,difference between except and except exception as e in python both the following snippets of code do the same thing they catch every exception and execute the code in the except blocksnippet 1 try some code that may throw an exceptionexcept exception handling codesnippet 2 try some code that may throw an exceptionexcept exception as e exception handling codewhat is exactly the difference in both the constructs,['python'] +548091,suppress safari cannot open the page because the address is invalid custom app launch i am launching a custom app from a web browser on the iphone if the app is not installed i am redirecting to a web page on the websiteif it is installed it goes to a specific page on the appthis all works as expected except for about 12 a second safari thisplays a modal window saying the followingcannot open pagesafari cannot open the page because the address is invalid i know the address is invalid and i would like to know if its possible to suppress the error message in safarithanks,"['javascript', 'iphone', 'ios']" +548102,check variadic templates parameters for uniqueness i want variadic template parameters must unique i know when multi inheritance identical classes inheritance is not allowedstruct astruct b a a errorusing this rule i made a little codeinclude type traitstemplate class t struct idtemplate class t struct base all idt template class tstruct is unique template class u static constexpr bool test base allu noexcept return true template class ustatic constexpr bool test noexcept return falsestatic constexpr bool value testt0int main constexpr bool b is uniqueint float doublevalue false why constexpr bool c is unique int char intvalue false static assert b true c false failedbut my program is not worked as i expected whats wrongupdatethanks i fix my error include type traits include cstddef template class u struct pack template class t struct id template class t struct base all template class t struct base all packt idt template class t struct is unique template class p stdsize t sizeofbase allp struct check template class u static constexpr bool testcheck packu noexcept return true template class u static constexpr bool testnoexcept return false static constexpr bool value testt0 int main constexpr bool b is uniqueint float doublevalue true constexpr bool c is unique int char intvalue false static assert b true c false success q somebody can explain why it is failedupdate2 my previous update was illegal legal form but it compiled on timeinclude cstddefinclude iostreaminclude type traitsnamespace mpltemplate class t using invoke typename t type template class c class i class e using if t invoke stdconditional c i e template class t struct idstruct emptytemplate class a class b struct base a b template class b class struct is unique impltemplate class b struct is unique implb stdtrue typetemplate class b class t class ustruct is unique implb t u if t stdis base of idt b stdfalse type is unique impl basebidt u template class t struct is unique is unique impl empty t mpl int main constexpr bool b mplis uniqueint float doublevalue constexpr bool c mplis unique int char int value static assert b true static assert c false return 0,['c++'] +548114,list declared directivescontrollers in angularjs module is there a way to list all of the directives and controllers that have been defined for a given angular module for example imagine i define three controllers in the main module ie angularmodulemaincontrollermainctrlfunction is there are way to get the list of those three controllers,['javascript'] +548128,xcode how to change icon in xcode 5 i am trying to change the icon in my old app project i have updated to xcode 5 and want to get a ios 7 design however you do not change the icon the way you did before i have seen that you are supposed to have e file called imagesxcassets with should include your icons but i do not have that one because you only seem get it if you are making a new projectthis should be very easy what should i do,['ios'] +548147,conditional component registration in autofac is it possible to register a component conditionally on an other components state something likecontainerbuilderregisterconditionallyt funcicomponentcontext bool funcicomponentcontext ti have found that prior to v2 of autofac one could use a registeronlyif construction that seemed like the one i am looking for i would like such feature to conditionally override a default registrationclass commonregistrations public virtual void registercontainderbuilder builder builderregisterctx loadsettingsasisettingssingleinstance builderregistertypedefaultfooasifoo class specificregistrations commonregistrations public virtual void registercontainerbuilder builder baseregisterbuilder builderconditionalyregister ctx ctxresolveisettingsreallyusespecificfoo ctx new specificfooasifoo var builder new containerbuildervar registrations new specificregistrationsregistrationsregisterbuildervar container builderbuildifoo foo containerresolveifoothe foo will be according to isettingsreallyusespecificfoo either instance of defaultfoo or instance of specificfoothank you,['c#'] +548182,what is and how to fix systemtypeinitializationexception error private static void mainstring args string str null loggerinituserlogwithrotation error occur when i build project it has no error but when i execute it it always abortedi tried to debug project but systemtypeinitializationexception error occurred at first linei have already tried to googling yet found no solutionit seems like any variable initialize code is wrong but cannot find itplease help me i am new to cthanksa here is logger class codepublic class logger private static int hdlog priority debug 4 private static int hdlog priority error 1 private static int hdlog priority fatal 0 private static int hdlog priority info 3 private static int hdlog priority warning 2 public static int log level debug 4 public static int log level error 2 public static int log level fatal 1 public static int log level info 5 public static int log level warning 3 private static string s bstcommonappdata pathcombines commonappdata x private static string s bstuserdatadir pathcombines bstcommonappdata userdata private static string s commonappdata environmentgetfolderpathenvironmentspecialfoldercommonapplicationdata private static bool s consolelogging false private static filestream s filestream public static hdloggercallback s hdloggercallback private static string s logdir null private static string s logfilename x private static string s logfilepath null public static int s logfilesize 0xa0 private static bool s loggerinited false private static string s loglevels null private static int s logrotationtime 0x7530 private static string s logstringdebug debug private static string s logstringerror error private static string s logstringfatal fatal private static string s logstringinfo info private static string s logstringwarning warning private static int s processid 1 private static string s processname unknown private static object s sync new object public static int s totallogfilenum 5 private static textwriter writer consoleerror private static void close if s consolelogging writerclose s filestreamthispose writerthispose public static void debugstring msg debug0 new object msg public static void debugstring fmt params object args printlog level debug s processname fmt args private static void dologrotation label 0 threadsleeps logrotationtime try lock s sync fileinfo info new fileinfos logfilepath if infolength s logfilesize string destfilename s logfilepath 1 string path s logfilepath s totallogfilenum if fileexistspath filedeletepath for int i s totallogfilenum 1 i 1 i string str3 s logfilepath i string str4 s logfilepath i 1 if fileexistsstr3 filemovestr3 str4 filemoves logfilepath destfilename goto label 0 catch exception goto label 0 public static void errorstring msg error0 new object msg public static void errorstring fmt params object args printlog level error s processname fmt args public static void fatalstring msg fatal0 new object msg public static void fatalstring fmt params object args printlog level fatal s processname fmt args private static string getlogdirbool userspecificlog string str if s logdir null return s logdir try if userspecificlog str pathcombines bstuserdatadir logs else str string registrylocalmachineopensubkeysoftwarexgetvaluelogdir catch exception str pathcombines bstuserdatadir logs s logdir str return str private static string getprefixstring tag string loglevel int managedthreadid threadcurrentthreadmanagedthreadid datetime now datetimenow return stringformat0d41d22d2 3d24d25d26d3 78x8 9 10 new object nowyear nowmonth nowday nowhour nowminute nowsecond nowmillisecond s processid managedthreadid tag loglevel public static textwriter getwriter return new writerdelegate string msg printmsg private static void hdloggerint prio uint tid string tag string msg int level 0 if prio hdlog priority fatal level log level fatal else if prio hdlog priority error level log level error else if prio hdlog priority warning level log level warning else if prio hdlog priority info level log level info else if prio hdlog priority debug level log level debug printlevel tag 0x8 1 new object tid msg public static void infostring msg info0 new object msg public static void infostring fmt params object args printlog level info s processname fmt args public static void initconsolelog initlog true false public static void initlogstring logfilename bool userspecificlog bool dologrotation s loggerinited true s hdloggercallback new hdloggercallbackloggerhdlogger s processid processgetcurrentprocessid s processname processgetcurrentprocessprocessname if logfilename writer consoleerror s consolelogging true else if logfilename null logfilename s logfilename if userspecificlog logfilename logfilename users string logdir getlogdiruserspecificlog string str2 stringformat01log logdir logfilename if directoryexistslogdir directorycreatedirectorylogdir s logfilepath str2 loglevelsinit lock s sync open if dologrotation new thread dologrotation isbackground true start public static void initsystemlog initlognull false false public static void initsystemlogwithrotation initlognull false true public static void inituserlog initlognull true false public static void inituserlogwithrotation initlognull true true private static bool isloglevelenabledstring tag string level if s loglevels null return false return s loglevelsstartswithall s loglevelscontainstag leveltoupper private static void loglevelsinit string name softwarexconfig try using registrykey key registrylocalmachineopensubkeyname s loglevels string keygetvaluedebuglogs catch exception return if s loglevels null s loglevels s loglevelstoupper private static void open if s consolelogging if s loggerinited initlog false false s loggerinited true else s filestream new filestreams logfilepath filemodeappend fileaccesswrite filesharedelete filesharereadwrite writer new streamwriters filestream encodingutf8 public static void printstring msg print0 new object msg public static void printstring fmt params object args printlog level info s processname fmt args public static void printint level string tag string fmt params object args string str unknown if level log level fatal str s logstringfatal else if level log level error str s logstringerror else if level log level warning str s logstringwarning else if level log level info str s logstringinfo else if level log level debug str s logstringdebug if level log level debug isloglevelenabledtag str lock s sync open writerwritelinegetprefixtag str fmt args writerflush close public static void setlogdirstring logdir s logdir logdir public static void warningstring msg warning0 new object msg public static void warningstring fmt params object args printlog level warning s processname fmt args public delegate void hdloggercallbackint prio uint tid string tag string msg public class writer textwriter private writefunc writefunc public writerwritefunc writefunc thiswritefunc writefunc public override void writelinestring msg thiswritefuncmsg public override void writelinestring fmt object obj thiswritefuncstringformatfmt obj public override void writelinestring fmt object objs thiswritefuncstringformatfmt objs public override systemtextencoding encoding get return systemtextencodingutf8 public delegate void writefuncstring msg,['c#'] +548212,how to add contentdesctiption to infowindow or marker in android googlemaps v2 for talkback i am working on native android app which implements the latest googlemap api v2 and i need to make it accessibility complaint as much as i cani can add contentdescription attribute to the mapview and it works fine talkback recognizes ithowever when i add the same attribute to the layouts of the marker or infowindow it is just ignored by talkbackseems like googlemap just renders the inflated layout internally to a bitmap and shows this bitmap on the top of the mapview ignoring contentdescription attribute as a result talkback does not say anything when the corresponding image is clickedanybody has a different experience or knowledge how to add contentdescription to the infowindow or marker with the latest googlemap thanks,['android'] +548225,wuapilib iupdateinstaller2 yields error some os updates install others throw hresult 2145124318 updates are being downloaded from a local server and not from wus or microsoft repositories local server is linux based which hosts the contents for each update i am not using updatedownloader to download from microsoft servers i manually download the update content and then use copytocachethese installed finesecurity update for microsoft net framework 35 sp1 on windows xp server 2003 vista server 2008 x86 kb2736416security update for microsoft visual studio 2010 kb2542054these did notsecurity update for microsoft net framework 4 on xp server 2003 vista windows 7 server 2008 x86 kb2840628update for microsoft net framework 35 sp1 on windows xp server 2003 vista and server 2008 x86 kb2836940how my process worksi receive this for an install from a local server which i use to download all download content for the update the blockquote text above kb2840628 is the example provided below app uris file name msipatchregfixx86 94a84b80b8b45a1ac53a0e5d085513da0f099655exe file uri 94a84b80b8b45a1ac53a0e5d085513da0f099655exe file size 130600 file name ndp40kb2840628v2x86 891d50ff3c1322db3fb0fde2ebb0a5260272exe file uri 891d50ff3c1322db3fb0fde2ebb0a5260272exe file size 13294216 app id d13c13c81f94fbb48f39c817a71ff239a31773d3a0e821a968dc42a913892841 app name security update for microsoft net framework 4 on xp server 2003 vista windows 7 server 2008 x86 kb2840628with that said the problem is that some updates install perfectly fine but certain updates i believe the ones that have more than one bundleupdates do not go thru its driving me madi first download each uri and then load them into the update with copytocache var collection new updatecollection iliststring updatefiles directorygetfilesupdatefolder var filecollection new stringcollection try foreach var file in updatefiles filecollectionaddfile error happens here on certain updates not all iupdate2updatebundledupdates0copytocachefilecollection collectionaddupdate return collection catch exception e return null after this the returned collection is passed through my windowsupdateinstaller method shown belowiupdatesession session new updatesessionvar updatestoinstall this gets the return from the above codevar installer iupdateinstaller2sessioncreateupdateinstallerinstallerforcequiet trueinstallerallowsourceprompts falseinstallerupdates updatestoinstallforeach iupdate updatenode in installerupdates updatenodeaccepteulafails here with 2145124318 result code orcfailedvar installationres installerinstall var installresult installationresgetupdateresult0the update installs just fine if i manually double click on the executable it and install it manually without using the code,"['c#', '.net']" +548229,accessing java variable from javascript on same jsp is it possible to access a string type variable defined in jsp from a javascript on the same pagehtmlheadmeta httpequivcontenttype contenttexthtml charsetwindows1255titleinsert title heretitlescript typetextjavascript foofunction foo var value myvar alertvalue script headbodystring myvarblablabodyhtmlin eclipse i am getting an error myvar cannot be resolved to a variable,['java'] +548250,can i trigger the browser to show autocomplete suggestions via javascript i am using the html datalist to make autocomplete options for a text input i would like to know if rather than double clicking on the input if i can trigger the suggestions to appear from javascript when a button is clicked ondatalist idgradesuggestions option valueaaoption option valuebboption option valueccoptiondatalistinput namegrade autocompleteoff listgradesuggestions typetext input typebutton idshowsuggestions valueshow suggestions scriptshowsuggestionsonclick function show the suggestions below the text input scripthere is a jsfiddle,['javascript'] +548252,how is the tongbu tui app able to be installed directly from the browser on nonjailbroken ios devices all a person need to do is take a regular ios device and visit and click the big grey button with the apple logo and then click install then the tui app will be installed how are they able to thistribute this app on nonjailbroken devices without the app store and how can this be replicated,['ios'] +548253,using linq to return a comma separated string i have a class in my applicationpublic class productinfo public int productid getset public int producttypegetseti want to write a linq query which can return me a list of productids in a comma separated format where producttype is equal to certain number i tried using stringjoin with my linq statement but it did not seem to work,['c#'] +548269,unpacking arguments from tuples so i am trying to figure out how this works c11 i can go from multiple args to tuple but can i go from tuple to multiple argsthe piece of black magic i do not understand is this code fragmentfstdgetnstdforwardtupletit is the expression inside f that i do not understandi understand that the expression somehow unpacksexpands whats inside t into a list of arguments but could someone care to explain how this is done when i look at the definition of stdget i do not see how n fits in as far as i can tell and is a sequence of integers based on what i can observe i am assuming that expressions in the form ex where x is the sequence of types x1 x2 xn the expression will be expanded as ex1 ex2 exn is this how it worksedit in this case and is not a sequence of types but integers but i am guessing this language construct applies to both types and values,['c++'] +548274,updatable views in entity framework 56 i have several views that are updatable according to all of my views follow the specifications in the afformentioned article i have verified in sql management studio that the views can be updated inserted to and deleted from the research i have done has led me to two options to make the views in my entity framework 56 model updatableremove the tag from each view however any workdone in mycontextedmx is overwritten when updating the context fromthe database this means that this solution is not very viable for myprojectadding a insert update and delete stored procedure for eachview and mapping these in the designer i do not particularly likethe idea of having to create this many stored proceduresis there any easy way to tell ef5 or ef6 that the views can be added toupdateddeleted from that will not be wiped out when running subsequent update model from database commands without writing stored procedures for each entry methodinsert update delete on each view,['c#'] +548276,replace eclipse with sublime text 23 for java has anyone managed to build out a way to use sublime text 2 or 3 instead of eclipse for their javabased app weve got java in eclipse mac with maven and git support we do not build in eclipse perse instead when necessary we just either refresh the projects or restart the tomcat serverusually though we can just make changes and reload the browser to be clear the app is singlepagearchitecture built on javamysql with a dojo javascript framework on the front end suggestions,['java'] +548301,how to check if a static library is built for 64bit i just built a static library for ios with the build setting for architectures set to archs standard including 64 bit i want to make sure that the a library is properly including that architecture but when i run lipo info on it i seearchitectures in the fat file librarya are armv7 armv7s cputype 167228 cpusubtype 0does this mean that arm64 is not included if the lipo command cannot tell me is there another way to telli am running xcode 5 with the latest command line tools installed,"['ios', 'objective-c']" +548302,exclude component from componentscan i am a spring newbie so please excuse me if the question appears nonsensicali have a component that i want to exclude from a componentscan in a particular configurationcomponentfoo class foo otherwise it seems to clash with some other class in my project i do not fully understand the collision but if i comment out the component annotation things work like i want them to but other projects that rely on this library expect this class to be managed by spring so i want to skip it only in my projecti tried using componentscanfilterconfiguration enablespringconfiguredcomponentscanbasepackages comexample excludefilters componentscanfiltertypefiltertypeassignable type valuefooclasspublic class myspringconfiguration but it does not appear to work if i try using filtertypeassignable type i get a strange error about being unable to load some seemingly random classcaused by javaiofilenotfoundexception class path resource junitframeworktestcaseclass cannot be opened because it does not existi also tried using typefiltertypecustom as followingclass excludefoofilter implements typefilter override public boolean matchmetadatareader metadatareader metadatareaderfactory metadatareaderfactory throws ioexception return metadatareadergetclass fooclass configuration enablespringconfiguredcomponentscanbasepackages comexample excludefilters componentscanfiltertypefiltertypeassignable type valuefooclasspublic class myspringconfiguration but that does not seem to exclude the component from the scan like i wanthow do i exclude it,['java'] +548363,empty div with style height will not thisplay incredibly simple piece of html but not thisplaying how i would expect i am trying to create an empty div that thisplays as whitespace on the top of the page with styleheight 400pxeven though i have specified a height my empty div will not thisplay what am i missing here update my main question is why does an empty div not thisplay even if it has a height set or what are the basic style rules needed to thisplay an empty divfull codehtmlheadtitlesite nametitleheadbodydiv styleheight400px width100 margin0 padding0 positionabsolutedivdiv stylewidth 50 margin autoimg srclogogifdiv div stylewidth 50 margin autodivbodyhtml,"['css', 'html']" +548373,django celery task logging i have setup celery in a django project on which i am working i would like to separate the logging for celery tasks vs the remainder of celery logs celerycam celerybeat etcbased on the celery documentation it seems like i should just be able to define a django logger for celerytask which should do this however when i do this nothing shows up in the logs everything does show up if i create a generic celery logger implying that this may be something to do with the name of the loggerwhat am i missing here is there a way to make this work or must all celery logs go togetherfor what it is worth i have set celeryd hijack root logger falsemy logging setup in settingspylogging version 1 thisable existing loggers false filters require debug false djangoutilslogrequiredebugfalse formatters standard format asctimes levelnames names linenos messages datefmt mdy hms handlers logfile level info filters none class logginghandlersrotatingfilehandler filename vagrantlogslogfilelog maxbytes 102410245 backupcount 3 formatter standard debug logfile level debug filters none class logginghandlersrotatingfilehandler filename vagrantlogsdebug logfilelog maxbytes 102410245 backupcount 5 formatter standard default logger level warning filters none class logginghandlersrotatingfilehandler filename vagrantlogsdefaultlog maxbytes 102410245 backupcount 2 formatter standard celery logger level debug filters none class logginghandlersrotatingfilehandler filename vagrantlogscelerylog maxbytes 102410245 backupcount 2 formatter standard celery task logger level debug filters none class logginghandlersrotatingfilehandler filename vagrantlogscelery taskslog maxbytes 102410245 backupcount 2 formatter standard loggers handlers default logger level warning propagate true django handlers logfile level info propagate true feedmanager handlers logfile debug logfile level debug propagate true recipemanager handlers logfile debug logfile level debug propagate true menumanager handlers logfile debug logfile level debug propagate true celerytask handlers celery task logger level debug propagate true celery handlers celery logger level debug propagate true,['python'] +548390,uiactionsheet is clipped by its superview i do not have a toolbar or tabbar my app uses a uinavigationcontroller but i do not show the toolbar because all of my navigation is controlled by ingame controls i do not have a tab bar because i am not using a tabbarcontroller my game app is landscape onlythis is how i previously created and presented the uiactionsheetuiactionsheet quitgamesheet uiactionsheet alloc initwithtitlequit your game delegateself cancelbuttontitlecancel destructivebuttontitleyes quit game otherbuttontitlesnilquitgamesheet showinviewselfviewhowever the uiactionsheet is mostly off screen and i get this errorpresenting action sheet clipped by its superview some controls might not respond to touches on iphone try uiactionsheet showfromtabbar or uiactionsheet showfromtoolbar instead of uiactionsheet showinviewhowever i do not have a toolbar and i do not have a tabbar i have tried several other stack overflow answers none of which work for meissue with uiactionsheeti tried presenting it from selfnavigationcontrollerview from selfparentviewcontrollerview from a cgrect that i created which was at the bottom of the view from selfviewbounds because i was desperate none of it works for meit works in ios 6 but does not work in ios 7 here are a couple of screenshots of it working on ios 6 and failing on ios 7any helpupdate 1 here is a view hierarchy as requesteduiview 0xc480380 frame 0 0 568 320 autoresize rmbm layer calayer 0xc4803e0 uiimageview 0xc480410 frame 0 0 568 320 opaque no autoresize wh userinteractionenabled no layer calayer 0xc4804a0 uibutton 0xc47b370 frame 203 107 159 37 opaque no autoresize lmrmbm layer calayer 0xc47a730 uiimageview 0xc475150 frame 0 0 159 37 clipstobounds yes opaque no userinteractionenabled no layer calayer 0xc4751e0 uibutton 0xc478a00 frame 203 152 159 37 opaque no autoresize lmrmbm layer calayer 0xc477dd0 uiimageview 0xc475030 frame 0 0 159 37 clipstobounds yes opaque no userinteractionenabled no layer calayer 0xc4750c0 uiswitch 0xc47dcc0 frame 313 65 51 31 opaque no autoresize lmrmbm layer calayer 0xc47d180 uiswitchinternalviewneuestyle1 0xc47e040 frame 0 0 51 31 gesturerecognizers nsarray 0xc47ffa0 layer calayer 0xc47e140 uiview 0xc47e4e0 frame 355 0 155 31 clipstobounds yes layer calayer 0xc47e540 uiview 0xc47e330 frame 355 0 51 31 layer calayer 0xc47e390 uiview 0xc47e450 frame 0 0 355 31 clipstobounds yes layer calayer 0xc47e4b0 uiview 0xc47e3c0 frame 0 0 51 31 layer calayer 0xc47e420 uiview 0xc47f750 frame 0 0 51 31 layer calayer 0xc47f7b0 uiimageview 0xc47f480 frame 39 16 0 0 alpha 0 userinteractionenabled no layer calayer 0xc47f660 uiimageview 0xc47f690 frame 12 16 0 0 userinteractionenabled no layer calayer 0xc47f720 uiimageview 0xc47e680 frame 7 6 57 435 opaque no userinteractionenabled no layer calayer 0xc47f2f0 uilabel 0xc480610 frame 173 63 96 29 text sounds clipstobounds yes opaque no autoresize lmrmbm userinteractionenabled no layer calayer 0xc480540 uibutton 0xc473a20 frame 203 197 159 37 opaque no autoresize lmrmbm layer calayer 0xc473590 uiimageview 0xc474f30 frame 0 0 159 37 clipstobounds yes opaque no userinteractionenabled no layer calayer 0xc474fc0,['ios'] +548463,flake8 complains on boolean comparison in filter clause i have a boolean field in the mysql db table table modelclass testcasebase tablename test cases obsoleted columnobsoleted booleanto get the count of all the nonobsoleted test cases that can be done simply like thiscasenum sessionquerytestcasefiltertestcaseobsoleted falsecountprintcasenumthat works fine but the flake8 report the following warninge712 comparison to false should be if cond is false or if not condokay i think that make sense so change my code to thiscasenum sessionquerytestcasefiltertestcaseobsoleted is falsecountor casenum sessionquerytestcasefilternot testcaseobsoletedcountbut neither of them can work the result is always 0i think the filter clause does not support the operator is or is not will someone can tell me how to handle this situation i do not want to thisable the flake,"['python', 'mysql']" +548473,name clash compile error when compiled in java 7 but works fine in java 5 public interface expression public interface arithmeticexpression extends expression public class staticmethoddemo public static void printexpression e systemoutprintlnstaticmethoddemo public static listexpression convert collection extends expression input return null public class staticmethodchild extends staticmethoddemo public static void printarithmeticexpression e systemoutprintlnstaticmethodchild public static listarithmeticexpression convert collection extends arithmeticexpression input return null above code compiles in java 5 but not in java 7 why in java 7 it gives name clash the method convertcollection of type staticmethodchild has the same erasure as convertcollection of type staticmethoddemo but does not hide it,['java'] +548571,afnetworking 20 cancel specific task i am trying out afnetworking 20 and just trying to figure out how to cancel specific tasksthe old way would be to use something likeself cancelallhttpoperationswithmethodpost pathuserreceiptsbut i dont see anything like this in 20i created a sub class of afhttpsessionmanager which gives me access to the array of pending tasks and i can cancel them directly but i dont know how to identify 1 task from another so i can cancel only specific tasks task does have an taskidentifier but this doesnt appear to be what i neednsstring path nsstring stringwithformatuserreceiptsselfrequestserializer setauthorizationheaderfieldwithusernameprefs valueforkeyuuid passwordselfstoreauthtokenself getpath parametersnil successnsurlsessiondatatask task id responseobject completionblockresponseobject failurensurlsessiondatatask task nserror error errorblockerror now if i wanted to cancel this request only how would i approach this,['ios'] +548578,how to forward declare a class which is in a namespace i am trying to use forward declarations in header files to reduce includes used and hence reduce dependencies where users include my header filehowever i am unable to forward decalre where namespaces are used see example belowahpp fileifndef a hpp define a hpp namespace ns1 class a public aconst char const msg void talk const private const char const msg endif a hpp acpp fileinclude iostreaminclude ahppusing namespace ns1aaconst char const msg msg msg void atalk const stdcout msg stdendl consumerhpp fileifndef consumer hpp define consumer hpp how can i forward declare a class which uses a namespacedoing this below results in error c2653 ns1 is not a class or namespace name works with no namespace or if i use using namespace ns1 in header file but i am trying to reduce any dependencies in this header fileclass ns1aclass consumerpublic consumerconst char const text a text void chat constprivate a a endif consumer hpp consumercpp implementation fileinclude consumerhppinclude ahppconsumerconsumerconst char const text a text void consumerchat const a talktest maincpp fileinclude consumerhppint main consumer cmy message cchat return 0updatehere is my very contrived working code using the answer belowahppifndef a hpp define a hpp include stringnamespace ns1 class a public void set messageconst stdstring msg void talk const private stdstring msg namespaceendif a hpp acppinclude iostreaminclude ahppvoid ns1aset messageconst stdstring msg msg msgvoid ns1atalk const stdcout msg stdendl consumerhppifndef consumer hpp define consumer hpp namespace ns1 class aclass consumerpublic consumerconst char text consumer void chat constprivate ns1a a endif consumer hpp consumercppinclude ahppinclude consumerhppconsumerconsumerconst char text a new ns1a a set messagetextconsumerconsumer delete a void consumerchat const a talkmaincppinclude consumerhppint main consumer cmy message cchat return 0,['c++'] +548608,why inline javascript is bad it is always recommended to avoid inline javascript codes by putting all codes in a js file which is included in all pages i wonder if this does not cause performance problem in heavy pagesfor example imagine that we have tens of functions like thisfunction function1elementvar eldocumentgetelementsbyclassnameelementvar sizeellengthifsize0 returnfori0isizei the processon every page we need to run the functions to know if there are corresponding elements in the html or notwindowonload functionfunction1afunction26zbut if keeping all functions in an external js file and calling functions through inline javascript we can call only the functions which are required in the present pagescript typetextjavascriptwindowonload functionfunction6fscriptdoes not it beneficial from performance point of view to call functions via inline javascript which is of course not best practice to avoid call of lots of functions which are not needed in a pageof course this is not limited to functions only as we have lots of addeventlisteners for the entire website which are fired on each and every page where they are not needed,['javascript'] +548611,custom font in pixijs i try to load a custom font into pixijs 2d webgl frameworkthey have an example using woff google fonts i converted my ttf to woff and added in cssfontface fontfamily hu adrien src localhu adrien urlhu a0046woff formatwoffdivfont fontfamily hu adrien color whiteit shows in my div but not in my pixi stage create a text object with a nice stroke var spinningtext new pixitexti am fun font 160px hu adrien fill cc00ff align center stroke f strokethickness 6 setting the anchor point to 05 will center align the text great for spinning spinningtextanchorx spinningtextanchory 05 spinningtextpositionx 620 2 spinningtextpositiony 400 2,['javascript'] +548629,what are the possible reason for a javautilconcurrentrejectedexecutionexception in a singlethreadexecutor i create the following executor in a singleton final private executorservice executor executorsnewsinglethreadexecutornew threadfactory final threadfactory delegate executorsdefaultthreadfactory public thread newthreadrunnable paramanonymousrunnable thread localthread thisdelegatenewthreadparamanonymousrunnable localthreadsetnamemytask localthreadgetname localthreadsetdaemonxthisdaemonthread return localthread and during the execution of the program there a lot call to this method of the singleton the calls are done in different threads and maybe at the sametimeprivate void sendfinal string paramstring try thisexecutorexecutenew runnable public void run do some interesting stuff catch exception localexception thishandlerhandlelocalexception and at some point the following stacks start to appearjavautilconcurrentrejectedexecutionexception at javautilconcurrentthreadpoolexecutorabortpolicyrejectedexecutionthreadpoolexecutorjava1774 at javautilconcurrentthreadpoolexecutorrejectthreadpoolexecutorjava768 at javautilconcurrentthreadpoolexecutorexecutethreadpoolexecutorjava656 at javautilconcurrentexecutorsdelegatedexecutorserviceexecuteexecutorsjava589 at xsendxjava269why the jvm will throw such exceptionthe singlethreadexecutor is backed by a linkedblockingqueueand the thread pool was not shutdownfor information the jvm is oracle jdk 16 the singleton is created with springcopy from javautilconcurrentexecutors public static executorservice newsinglethreadexecutorthreadfactory threadfactory return new finalizabledelegatedexecutorservice new threadpoolexecutor1 1 0l timeunitmilliseconds new linkedblockingqueuerunnable threadfactory,['java'] +548656,cakephp error unable to configure the session setting sessionauto start failed i am getting this errorerror cakesessionexception unable to configure the session setting sessionauto start failedi am using cakephp 224editit seems this guy had the same issue cakephp session error on live site and using thisifisset session session start inside beforefilter method of appcontroller fix the errorso my question is why this happened everything was working fine and then suddendly this error appearedadditionally i have realized that the folder apptmpsessions is empty and i have configured the session to be handled by cake in configcorephp,['php'] +548662,how should i cast the result of malloc in c please note this question is not about malloc in c or malloc vs newsmart pointers in cif i use malloc in c what kind of cast should i use the following all workint a int mallocsizeof intint b static castint mallocsizeof intint c reinterpret castint mallocsizeof intlive examplei prefer to use c style casts in my code as much as possible and i want to adopt safe coding habits please advise with this in mindthank you,['c++'] +548664,how to compare time in javascript i have two time in the format hhmm i want to compare them i have the following code to get the time of now in my formatcurrent time new datehour current timegethoursminute current timegetminutesifhour10hour0hour ifminute10minute0minutemy time hourminuteand this code is to get the time after subtracting the gmt difference d new datevar and dgettimezoneoffsetvar n1 mathabsnvar difference n160 my time my time 0differencenow the value of my time should be compared with the value of match timematch time 10for exampleifmy time match time alertyeselse alertnohow can i compare those values as time when they are a string,['javascript'] +548682,check if some exe program is running on the windows how to check if some exe program is running is in process on windows i am making java application which update one exe program so if that exe program is used by some client my application ask for closing exe program and after closing automatically replace exe file with new one,['java'] +548694,microsoft visual studio 2012 cannot set breakpoint in c file i have microsoft visual studio professional 2012 installed version 1106061001 update 3 when debugging a c cs file visual studio gives me the following message when i try to set a breakpoint a breakpoint could not be inserted at this locationi get this message even when trying to set it on a line within a method but in a vb file for a visual basic app i can set a breakpointi am wondering if anyone has any suggestions to resolve this or if i need to reinstall visual studiothanks,['c#'] +548722,xcode5 xcassets how to bulk replace images say i have a project with 100 images that i have imported into a folder inside the main imagesxcassets file then i go and get updates for 67 of those images from my graphics designer is there an easy way to push those image updates into the xcassets folderas it stands i am opening the xcassets file in xcode and for each of the images that is changed i am dragging the new image into the little 2x or 1x box i have to do that 67 times i cannot just dragdrop the files in finder the old way because every image in the xcassets folder has its own subfolder if i do not use the xcassets file for my images i can easily update the files by doing this but xcassets are supposed to make managing your assets much simpler fine so what am i missing,['ios'] +548776,pythonic way to correctly separate model from application using sqlalchemy i am having a hard time to make my application run flasksqlalchemy extension creates an empty database whenever i try to separate module in packages to better explain what i am doing let me show how my project is structuredproject model init py userpy server init py api init pythe idea is simple i want to create a package for my model as i do not like spreading code in a single package and separate sub projects like api as in the future i will be using blueprints to better isolate sub appsthe code is very simplefirst the model init pyfrom flask sqlalchemy import sqlalchemydb sqlalchemynote that i created this only to use a single sqlalchemy object accross the package no we go to modeluserfrom model import dbclass userdbmodel id dbcolumndbinteger primary keytrue name dbcolumndbstring80 age dbcolumndbinteger once again note the from model import db that i used to allow the same db objectfinally the server init py goes like thisfrom flask import flaskfrom flask sqlalchemy import sqlalchemyimport model apidb modeldbdef main app flask main db sqlalchemyapp dbcreate all apisetapihookersapp apprunhost0 port50 debugtrueif name main mainfrom my point of view the db sqlalchemyapp allows me to pass my app object without creating a circular referencethe problem is that whenever i run this code the sqlite database file is created empty that made me think that maybe python do not import things like i thought it would so i tested my theory by removing the import model and creating the user directly inside server and voila it workednow comes my question is there a pythonic way to correctly separate modules like i want or should i leave everything in the same package,['python'] +548796,items set with spymemcached cannot be fetched with php memcached i am using spymemcached i set a couple of items then i run a php script however then i cannot get all those items using php memcached phpmemcached can only partially retrieve those itemsi cannot change phps hashing algorithm or thistribution strategy in our system we are using default hashing which is jenkins oneatatime according to phpnet documentation and thistribution strategy is modulo for phpmemcached i have read that spymemcached uses consistent hashing is there any way by which i can use modulo hashing in spymemcachedin other words how can i make spymemcacheds set operations or any other store operations compatible with phpmemcacheds get operationsif spymemcached is not able to do that are there any other memcached client in java that will allow me to do sohelp will not only be appreciated it will also be rewarded a bountyjava code public static void mainstring args listinetsocketaddress addrs new arraylist addrsaddnew inetsocketaddress10901287 11211 addrsaddnew inetsocketaddress10901287 11311 try memcachedclient memcache new memcachedclientaddrs memcacheaddfoo 0 bar memcacheaddsample 0 key memcacheaddtry 0 another memcacheaddaxspadglist 0 30456645 catch ioexception ex loggergetloggercategorydataoperatorclassgetnameloglevelsevere null ex systemoutprintlndonephp code phpmem new memcachedmemaddserver10901287 11211memaddserver10901287 11311var dump memgetfoovar dumpmemgettryvar dumpmemgetsamplevar dumpmemgetaxspadglist,"['java', 'php']" +548808,timeout not defined error in angularjs app i have the following codeappfactoryposition timeout function var position latitude 44 longitude 26 consolelogtimeout started timeoutfunction positionlatitude 15 positionlongitude 15 20 return positionand i get timeout not defined in javascript console am i not injecting the dependency of the service correctly,['javascript'] +548852,ios7 side menu status bar color transition as in the ios7 facebook app the ios7 facebook app has a right side menu that can be shown by swiping right to left or clicking on the upper right button when this menu is opened the there is a color transition in the entire status bar from blue to black and viceversa when closed this image shows both status bar sidetosidethis looks like a very good solution for ios apps with side menusany ideas or ways about how to accomplish this i am currently using jasidepanelsthanks,['ios'] +548861,fat libraries in xcode 5 i have been trying to build a static library and then create a binding project from it in xamarin everything was working fine until ios 7 hit i had to grab the latest version of the native library and try and build it in xcode 5 but it is been giving me all kinds of problems i think it might be related to the build process or possibly some changed setting in xcode 5 vs 4 but i am not surei was using this script to build a universal binary which is based of work in this questionbuild fat static library device simulator using xcode and sdk 4one thing i did notice is that previous in the old ios 61 version of my binary built in xcode 4 my binary was about 24 mb now with xcode 5 it is ballooned to almost 50 mb which is leading me to think that there is something wrong with the compiling and linking stepany ideas has anybody else encountered problems with universal binaries in xcode 5 vs 4,['iphone'] +548871,invalid context error on ios 7 when adding a uipickerview inside a uiactionsheet i have an uipickerview inside an uiactionsheet and have done that in a way suggested by many others here at soadd uipickerview a button in action sheet howhow to add uipickerview in uiactionsheetthe solutions have worked fine until now when testing my app on ios 7 it still works but i got a lot of invalid context 0x0 warnings during runtime in xcodethe errors are coming with a nice message toocgcontextsetfillcolorwithcolor invalid context 0x0 this is a serious error this application or a library it uses is using an invalid context and is thereby contributing to an overall degradation of system stability and reliability this notice is a courtesy please fix this problem it will become a fatal error in an upcoming updatecould it be that apple finally want to stop this kind of solution or is it something we can work around or fix,"['iphone', 'ios']" +548873,how does robospice manage activity lifecycle i am looking for a technical answer to how the android robospice library manages activity lifecycle from the getting started pageas an inner class of your activity or other context add a requestllistener that will update your ui do not worry about memory leaks robospice manages your activitys life cyclemy question is how does robospice automatically update the request listeners so that it still is able to call the correct listener with the correct context after a rotation and after the activity has been destroyed and recreated as a new instancei have been trying to reverse engineer the source code but have not found an answer yet,['android'] +548887,java application windows vs mac os x i developed a java application on a small windows desktop that parse xml files i met a very interesting observation that i am very curious abouti produced an executable jar for my application and ran it on windows server machine that is very powerful it has 2 physical xeon processors each 8 cores clocked at 27 ghz 50gb ram and 7200 rpm hdd the machine was idle when i started my application and i am pretty sure no other application shared the machine with melater i was running the executable on my macbook pro for the sake of fun to see its behaviour my personal machine is core i7 clocked at 22 ghz with 4 gb ram and 5400 rpm hddsurprisingly the application was twice faster on my personal weaker machine it was the same input same output no io but for reading the xmls to parse them i print nothing on terminal but start time end time final result which is one linei am very curious to understand the reason behind such a dramatic performance difference specially from a weaker machine on the level of the hardware is it the operating system that handles hardware in a better way is it jvm working better,['java'] +548919,how to set category page as home page in prestashop i am having as my home pagemy category page url is category10controllercategorynow i need to redirect my homepage to category pagei tried in preferences seo urls set shop url base urias indexphpid category10controllercategorynow the page is redirecting to my category url but page is not openingthe url is showing like this category10controllercategoryindexphp,['php'] +548935,nscoding with nested custom objects i have a series of nested objects that i am needing to put through the nscoding protocol so that i can save the top level object into nsuserdefaults here is the structure of objectsinstructor classnsmutablearray that holds instances ofclass classnsmutablearray that holds instances ofstudent classname propertynumber propertymoney propertyi am needing to save an instance of instructor to nsuserdefaults or to documents for the app as you can see the instructor object is holding an array that is then holding instances of a class that class object is holding instances of students is the nscoding protocol recursive what i mean by that is if i add the nscoding protocol to each class i could then save an instructor object and it would recursively encode the contained objects would it then work the same way while decoding i could just decode the one instructor class and it would recursively decode the objects contained because they also conform to the nscoding protocolhow could i go about setting this up,"['iphone', 'ios', 'objective-c']" +548951,is it possible to fix the fuzziness of antialiased skshapenodes i am experimenting with using skshapenodes in a game and have found that antialiased skshapenodes are very blurrywithout antialiasingwith antialiasingis there some way to use antialiasing of skshapenodes in spritekit to reduce the stairstepping on lines but without making the lines blurry as in the second image above,['ios'] +548953,android addview in background thread i need to add lots of views in a loop while this fragment does that the app will also have a navigation drawer and action bar where the user can do thingsso i would like this process to not a slow down the app by blocking the user b preferably add the views in a background threadthe dilemma is that i think android does not like views to be added in a nonui thread so is there a best practice for this i plan to have a progress bar view object visible in the fragments view while the rest of the views are being generated with the addview and associated computations,['android'] +548956,how does the callvirt net instruction work for interfaces explaining virtual thispatching to someone is easy every object has a pointer to a table as part of its data there are and virtual methods on the class every call to a particular method i indexes the object when it arrives and calls the ith method in the table every class that implements method x will have the code for method x in the same ith index but then we get interfaces and interfaces require some sort of contortion because two noninheriting classes that both implement the same interface will have the virtual functions in different indexes of the tablei have searched the internet and there are many thiscussions i can find about how interface thispatching can be implemented there are two broad categories a some sort of hash table look up on the object to find the right thispatch tableb when the object is cast to the interface a new pointer is created that points to the same data but to a different vtablebut despite lots of info about how it can work i can find nothing about how the net runtime engine actually implements it does anyone know of a document that describes the actual pointer arithmetic that happens at a callvirt instruction when the object type is an interface,"['c#', '.net']" +548961,reactjs rerender on browser resize how can i get react to rerender the view when the browser window is resizedbackgroundi have some blocks that i want to layout individually on the page however i also want them to update when the browser window changes the very end result will be something like ben hollands pinterest layout but written using react not just jquery i am still a way offcodeheres my appvar myapp reactcreateclass does the http get from the server loadblocksfromserver function ajax url thispropsurl datatype json mimetype textplain success functiondata thissetstatedata dataevents bindthis getinitialstate function return data componentwillmount function thisloadblocksfromserver render function return div blocks datathisstatedata div reactrendercomponent myapp urlurl here documentgetelementbyidviewthen i have the block component equivalent to a pin in the above pinterest examplevar block reactcreateclass render function return div classdpblock styleleft thispropstop top thispropsleft h2thispropstitleh2 pthispropschildrenp div and the listcollection of blocksvar blocks reactcreateclass render function i have temporarily got code that assigns a random position see inside the function below var blocknodes thispropsdatamapfunction block temporary random position var topoffset mathrandom windowwidth px var leftoffset mathrandom windowheight px return block orderblockid titleblocksummary leftleftoffset toptopoffsetblockdescriptionblock return divblocknodesdiv questionshould i add jquerys window resize if so where window resizefunction rerender the componentis there a more react way of doing this,['javascript'] +548998,thiscovering poetic form with nltk and cmu dict edit this code has been worked on and released as a basic module i am a linguist who has recently picked up python and i am working on a project which hopes to automatically analyze poems including detecting the form of the poem ie if it found a 10 syllable line with 0101010101 stress pattern it would declare that it is iambic pentameter a poem with 575 syllable pattern would be a haikui am using the following code part of a larger script but i have a number of problems which are listed below the programcorpus in the script is simply the raw text input of the poemimport sys getopt nltk re stringfrom nltktokenize import regexptokenizerfrom nltkutil import bigrams trigramsfrom nltkcorpus import cmudictfrom cursesascii import isdigitdef cmuform tokens word for sent in nltksent tokenizecorpus for word in nltkword tokenizesent d cmudictdict text nltktexttokens words wlower for w in text regexp azaz exp recompileregexp def nsylword lowercase wordlower if lowercase not in d return 0 else first joinstrc for c in lst for lst in maxdlowercase second joinfirst third joini for i in second if iisdigitreplace2 1 return third return maxleny for y in x if isdigity1 for x in dlowercase sum1 0 for a in words if expmatcha print ansyla sum1 sum1 lenstrnsyla print ntotal syllablessum1i guess that the output that i want would be like this1101010101001010101the first problem is that i lost the line breaks during the tokenization and i really need the line breaks to be able to identify form this should not be too hard to deal with though the bigger problems are thati cannot deal with nondictionary words at the moment i return 0 for them but this will confound any attempt to identify the poem as the syllabic count of the line will probably decreasein addition the cmu dictionary often says that there is stress on a word 1 when there is not 0 which is why the output looks like this 110101 when it should be the stress of iambic pentameter 0101010101so how would i add some fudging factor so the poem still gets identified as iambic pentameter when it only approximates the pattern it is no good to code a function that identifies lines of 01s when the cmu dictionary is not going to output such a clean result i suppose i am asking how to code a partial match algorithm,['python'] +549005,sincos stret undefined symbol when linking like previously referred here sincos stret can not be found when compiling a project that uses this symbol using the xcode5 command line tools in the above referenced thread a solution is posted for ios targets passing miphoneosversionmin50 to the compiler is there a solution for desktop x64 targetsit for example happens for me when trying to compile polycodeedit 2strangely after compiling the libraries referenced in the previous error manually the error now happens to be located in ltoo which is an internal llvm header itselfundef sincos stretundefined symbols for architecture x86 64 sincos stret referenced from mdct init in ltoo dradfg in ltooi am running osx 109 dp with xcode 5 this is the link step,['c++'] +549006,ios 7 lays out accessoryview and accessorytype differently anyone else notice that ios 7 lays out custom accessoryviews differently than builtin accessorytypeslike thisthe top one is done usingcellaccessoryview cellaccessorybuttonwhere accessorybutton is a customized uibutton while the second one is done usingcellaccessoryview nilcellaccessorytype uitableviewcellaccessorythisclosureindicatorsame code same app same xcode but running on ios 6 insteadis this a bug in the sdk or something i can control via code,['ios'] +549012,url design for restful services i have a resource called pricing which i want to retrieve an offer can have pricing and a promo can have pricing resource and there is another entity customer with which pricing can be mapped i want to retrieve pricing based on either one of offeridpromoidcustomeridto design the urls for this i am running into two optionsoption 1 pass it as query stringpricingofferid234promoid345customerid543234option 2 have three apispricingofferid234pricingpromoid345pricingcustomerid543234imo offeridpromoidcustomerid should be treated as attribute of the resource therefore pass attribute as query stringi am more inclined towards option 1option 2 avoids if else condition to retrieve the resource and looks much cleaner but does it seems to be supporting rest standard of url designwhats the rest standard to design the url which option would you recommend,['java'] +549031,what if any guidelines exist about textlink colour difference are there any best practices or guidelines regarding contrast between link colour on a webpage and the regular text i know there are contrast guidelines that refer to text vs background colour but i am also wondering if there are guidelines about the minimum colour difference that should exist between plain text and link textfor example my background is white f my text colour is black 0 and my link colour is green 007c41editi realize it is up to personal preference to some degree however while my eyes may be able to tell the difference between 0 and 01 they cannot but just for arguments sake others would not be able to what i am wondering is if there are any accessibility guidelines regarding what the minimum colour difference should be,"['html', 'css']" +549055,rails 32 dev environment sourcemaps support for javascript i am working on a rails app using asset pipeline the developmentrb has the following configassetscompress false configassetscompile true configassetsdebug truein dev environment the assets are not bundled up and each is served up by rails individually at this point the number of assets that are getting served individually are more than 50 hence full page reloads are extremely slowi would like to concatenate them atleast in a few assets for faster loading time on dev environment but doing that i loose the ability to debugsee them individually in chrome dev tools example there are two ways to solve this in my knowledge after you do configassetsdebug falseand start serving them as concatenated assetsold hacky way sourceurl tricknew way sourcemapsis there a guide on how i can enable them on a rails app i dont use coffeescript so is not helpful most google searches lead to thati am looking for a solution for native js,"['javascript', 'ruby-on-rails']" +549080,is it a bad practice to always capture all in a lambda expression stdfunctionint void f1 int a b c d x y z return return a b c vsstdfunctionint void f2 int a b c d x y z return a b c return a b c needless to say the former is shorter handier and more elegant than the latterhowever i still worry from the performance viewpoint is the latter always better than the formerdoes the standard guarantee a lambda expression captures the necessary variables only ie in the former example only a b c are captured the unused variables d x y z are not,['c++'] +549139,importerror dll load failed 1 is not a valid win32 application but the dlls are there i have a situation very much like the one at importerror dll load failed 1 is not a valid win32 application but the answer there is not working for memy python code saysimport cv2but that line throws the error shown in the title of this questioni have opencv installed in clibopencv on this 64bit machine i am using 64bit pythonmy pythonpath variable pythonpathclibopencvbuildpython27 this folder contains cv2pyd and that is allmy path variable pathopencv dirbin this folder contains 39 dll files such as opencv core246ddllopencv dir has this value opencv dirclibopencvbuildx64vc11the solution at importerror dll load failed 1 is not a valid win32 application says to add the new opencv binaries path copencvbuildbinrelease to the windows path environment variable but as shown above i already have the opencv binaries folder clibopencvbuildx64vc11bin in my path and my opencv installation does not have any release folders except for an empty one under buildjavaany ideas as to whats going wrong can i tell python to verbosely trace the loading process exactly what dlls is it looking forthankslarsediti just noticed that according to the cv2pyd in clibopencvbuildpython27 is 32bit whereas the machine and the python i am running are 64bit could that be the problem and if so where can i find a 64bit version of cv2pyd,['python'] +549145,how to turn off the automatic gesture to go back a view with a navigation controller so i am noticing all of my views are receiving the gesture to go back pop a view when the user swipes on the very left side of the screen in either orientation this is new with ios7i have tried so far with no avail to turn it off using selfnavigationitem sethidesbackbuttonyeswithin the init of the navigationcontroller itself as the delegate seems to be using that,"['ios', 'objective-c']" +549175,autoclose alert is there any way to close a javascript alert automaticallyi have an alertalerterror foundi want to close it after a few second is that possible or shall i go for jquery dialogue,"['javascript', 'jquery']" +549177,rehashing in hashmap the initial capacity and load factor two parameters that affect the hashmap performancethe default load factor 75 offers a good tradeoff between time and space costs higher values decrease the space overhead but increase the lookup costwhen an item is added to the hashmap it is assigned to a buckets based on a value derived of its hashcode and the bucket size of the hashmapto identify the bucket for any hash map use keyhashcode and perform some operationbucket index hashmapindexforhashmaphashkeyhashcode entryarraylengthwhen the number of entries in the hash map exceeds the product of the load factor and the current capacity the hash map is rehashed internal data structures are rebuilt so that the hash map has approximately twice the number of bucketswhen you rehash and move everything to a new location bucket etc then the older elements are also rehashed again and stored in the new bucket according to their new hash codes the old space which was allocated to store the elements is garbage collectedif two thread at the same time found that now hashmap needs resizing and they both try to resize may cause race condition in hashmapon the process of resizing of hashmap the element in bucket which is stored in linked list get reversed in order during their migration to new bucket because java hashmap does not append the new element at tail instead it append new element at head to avoid tail traversing if race condition happens then you will end up with an infinite loopi have following questions why is the linked list for each bucket be reversed in order duringmigration to new buckethow race condition can lead to infinite loophow can increasing the number of buckets diminish the lookup waitingtimeelements which are in the same bucket will still be together in samebucket after rehashing,['java'] +549214,preferredstatusbarstyle is not called i followed this thread to override preferredstatusbarstyle but it is not called are there any options that i can change to enable it i am using xibs in my project,['ios'] +549297,android error unable to add window token null is not for an application hy i tried to create an alert dialog but when i run my application is throw an exception0926 124321949 eandroidruntime14618 fatal exception main0926 124321949 eandroidruntime14618 androidviewwindowmanagerbadtokenexception unable to add window token null is not for an application0926 124321949 eandroidruntime14618 at androidviewviewrootimplsetviewviewrootimpljava6870926 124321949 eandroidruntime14618 at androidviewwindowmanagerimpladdviewwindowmanagerimpljava3010926 124321949 eandroidruntime14618 at androidviewwindowmanagerimpladdviewwindowmanagerimpljava2150926 124321949 eandroidruntime14618 at androidviewwindowmanagerimplcompatmodewrapperaddviewwindowmanagerimpljava1400926 124321949 eandroidruntime14618 at androidappdialogshowdialogjava2780926 124321949 eandroidruntime14618 at comexamplestamppuirewardsdeleterewardsfragment1onitemclickdeleterewardsfragmentjava800926 124321949 eandroidruntime14618 at androidwidgetadapterviewperformitemclickadapterviewjava2920926 124321949 eandroidruntime14618 at androidwidgetabslistviewperformitemclickabslistviewjava13940926 124321949 eandroidruntime14618 at androidwidgetabslistviewperformclickrunabslistviewjava30240926 124321949 eandroidruntime14618 at androidwidgetabslistviewontoucheventabslistviewjava38460926 124321949 eandroidruntime14618 at androidviewviewthispatchtoucheventviewjava56290926 124321949 eandroidruntime14618 at androidviewviewgroupthispatchtransformedtoucheventviewgroupjava19640926 124321949 eandroidruntime14618 at androidviewviewgroupthispatchtoucheventviewgroupjava17250926 124321949 eandroidruntime14618 at androidviewviewgroupthispatchtransformedtoucheventviewgroupjava19700926 124321949 eandroidruntime14618 at androidviewviewgroupthispatchtoucheventviewgroupjava17390926 124321949 eandroidruntime14618 at androidviewviewgroupthispatchtransformedtoucheventviewgroupjava19700926 124321949 eandroidruntime14618 at androidviewviewgroupthispatchtoucheventviewgroupjava17390926 124321949 eandroidruntime14618 at androidviewviewgroupthispatchtransformedtoucheventviewgroupjava19700926 124321949 eandroidruntime14618 at androidviewviewgroupthispatchtoucheventviewgroupjava17390926 124321949 eandroidruntime14618 at androidviewviewgroupthispatchtransformedtoucheventviewgroupjava19700926 124321949 eandroidruntime14618 at androidviewviewgroupthispatchtoucheventviewgroupjava17390926 124321949 eandroidruntime14618 at androidviewviewgroupthispatchtransformedtoucheventviewgroupjava19700926 124321949 eandroidruntime14618 at androidviewviewgroupthispatchtoucheventviewgroupjava17390926 124321949 eandroidruntime14618 at androidviewviewgroupthispatchtransformedtoucheventviewgroupjava19700926 124321949 eandroidruntime14618 at androidviewviewgroupthispatchtoucheventviewgroupjava17390926 124321949 eandroidruntime14618 at androidviewviewgroupthispatchtransformedtoucheventviewgroupjava19700926 124321949 eandroidruntime14618 at androidviewviewgroupthispatchtoucheventviewgroupjava17390926 124321949 eandroidruntime14618 at comandroidinternalpolicyimplphonewindowdecorviewsuperthispatchtoucheventphonewindowjava20620926 124321949 eandroidruntime14618 at comandroidinternalpolicyimplphonewindowsuperthispatchtoucheventphonewindowjava140926 124321949 eandroidruntime14618 at androidappactivitythispatchtoucheventactivityjava23690926 124321949 eandroidruntime14618 at comandroidinternalpolicyimplphonewindowdecorviewthispatchtoucheventphonewindowjava20100926 124321949 eandroidruntime14618 at androidviewviewthispatchpointereventviewjava58090926 124321949 eandroidruntime14618 at androidviewviewrootimpldeliverpointereventviewrootimpljava31300926 124321949 eandroidruntime14618 at androidviewviewrootimplhandlemessageviewrootimpljava26580926 124321949 eandroidruntime14618 at androidviewviewrootimplprocessinputeventsviewrootimpljava10150926 124321949 eandroidruntime14618 at androidviewviewrootimplhandlemessageviewrootimpljava26670926 124321949 eandroidruntime14618 at androidoshandlerthispatchmessagehandlerjava990926 124321949 eandroidruntime14618 at androidoslooperlooplooperjava1370926 124321949 eandroidruntime14618 at androidappactivitythreadmainactivitythreadjava45170926 124321949 eandroidruntime14618 at javalangreflectmethodinvokenativenative method0926 124321949 eandroidruntime14618 at javalangreflectmethodinvokemethodjava5110926 124321949 eandroidruntime14618 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava9930926 124321949 eandroidruntime14618 at comandroidinternaloszygoteinitmainzygoteinitjava7600926 124321949 eandroidruntime14618 at dalviksystemnativestartmainnative methodthis is my codepublic class deleterewardsfragment extends fragmentprivate context contextprivate fragmentsactivity activityprivate listview listviewprivate view myfragmentviewprivate deleterewardsadapter adapterprivate string valuessuppresslintresourceascolorpublic view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate myfragmentview inflaterinflaterlayoutlistview container false listview listview myfragmentviewfindviewbyidandroidridlist activity fragmentsactivity getactivity context activitygetapplicationcontext values new string4 adapter new deleterewardsadaptercontext values listviewsetadapteradapter listviewsetonitemclicklistenerdeleteevent return myfragmentviewprivate onitemclicklistener deleteevent new onitemclicklistener override public void onitemclickadapterview arg0 view arg1 int arg2 long arg3 alertdialogbuilder alertdialog new alertdialogbuildercontext alertdialog settitlejetzt laschen alertdialog setmessagedie in deisem store gesammelten stampss gehen debei verloren setcancelablefalse setpositivebuttonabbrechen new dialoginterfaceonclicklistener override public void onclickdialoginterface dialog int which values new stringvalueslength1 adapter new deleterewardsadaptercontext values listviewsetadapteradapter setnegativebuttonlaschen new dialoginterfaceonclicklistener override public void onclickdialoginterface dialog int which dialogcancel alertdialog dialog alertdialogcreate dialogshow can someone to help me,['android'] +549359,mfmessagecomposeviewcontroller much slower on ios 7 i have an app for sending email and text messagesthe problem that i am having is that the loading of the mfmessagecomposeviewcontroller much slower on ios 7 than it was on prior ios and it becomes worst as the number of contacts increasesscreen goes black for seconds before messages app opens with the contents loadedany thoughtswith the same large number of emails the mfmailcomposeviewcontroller is as quicker as beforehelpthanks,['ios'] +549472,what is the dotnotation between class names and what does it mean what is the meaning of this notation alertdialogbuilder in a class constructor public dialog oncreatedialogbundle savedinstancestate return new alertdialogbuildergetactivity settitlerstringdate picker title setpositivebuttonandroidrstringok null createdoes it mean that the builder class is defined inside the alertdialog class or builder is a method but its first letter is capitalized so i am confused,"['java', 'android']" +549483,create a function with whole columns as input and output i have several programs written in r that now i need to translate in tsql to deliver them to the client i am new to tsql and i am facing some difficulties in translating all my r functionsan example is the numerical derivative function which for two input columns values and time would return another column of same length with the computed derivativemy current understanding isi cannot use sp because i will need to use this functions inline withselect statement likeselect customer id date amount derivativeamount date from customer detaili cannot use udf because they can take as input parameter only scalar i will need vectorised function due to speed and also because for some functions i have like the one above running row by row wouldnt be meaningful for each value it needs the next and the previousuda take whole column but as the name says they will aggregate the column like sum or avg wouldif the above is correct which other techniques would allow me to create the type of function i need an example of sql builtin function similar to what i am after is square which apparently takes a column and returns itself2 my goal is creating a library of functions which behave like square power etc but internally it will be different cause square takes and returns each scalar is read through the rows i would like to know if is possible to have user defied with an accumulate method like the uda able to operates on all the data at the end of the import and then return a column of the same lengthnb at the moment i am on sqlserver 2005 but well switch soon to 2012 or possibly 2014 in few months so answers based on any 2005 version of sqlserver are fineedit added the r tag for r developers who have hopefully already faced such difficultiesedit2 added clr tag i went through clr user defined aggregate as defined in the pro tsql 2005 programmers guide i already said above that this type of function wouldnt fit my needs but it was worth looking into it the 4 methods needed by a uda are init accumulate merge and terminate my request would need the whole data being analysed all together by the same instance of the uda so options including merge methods to group together partial results from multicore processing would not be working,['sql'] +549523,how to center a popup in window windows store apps i have a custom popup as a user control which i load programatically i am not able to center it on x axis only on vertical the popup is not added onto an xaml file but it is added on the root windowusing systemusing systemcollectionsgenericusing systemiousing systemlinqusing windowsfoundationusing windowsfoundationcollectionsusing windowsuixamlusing windowsuixamlcontrolsusing windowsuixamlcontrolsprimitivesusing windowsuixamldatausing windowsuixamlinputusing windowsuixamlmediausing windowsuixamlnavigationusing systemwindowsusing windowsuicore the user control item template is documented at namespace qstlibrarywin8tools public sealed partial class customprogressringpopup usercontrol public customprogressringpopup thisinitializecomponent public string text get return stringgetvaluetextproperty set setvaluetextproperty value using a dependencyproperty as the backing store for text this enables animation styling binding etc public static readonly dependencyproperty textproperty dependencypropertyregister text typeofstring typeofcustomprogressringpopup new propertymetadata ontextchanged public void openpopup thisparentpopupisopen true public void closepopup thisparentpopupisopen false private static void ontextchangeddependencyobject d dependencypropertychangedeventargs e var instance d as customprogressringpopup var newvalue enewvalue as string if instance null newvalue null instancecustomtextblocktext newvalue private void onpopuploadedobject sender routedeventargs e thisparentpopuphorizontaloffset windowcurrentboundswidth gdchildactualwidth 2 thisparentpopupverticaloffset windowcurrentboundsheight gdchildactualheight 2 usercontrol xamlusercontrol xclassqstlibrarywin8toolscustomprogressringpopup xmlns xmlnsx xmlnslocalusingqstlibrarywin8tools xmlnsd xmlnsmc mcignorabled ddesignheight300 ddesignwidth400 popup xnameparentpopup horizontalalignmentcenter verticalalignmentcenter loadedonpopuploaded grid xnamegdchild heightauto widthauto backgroundblue margin20 gridrowdefinitions rowdefinition gridrowdefinitions gridcolumndefinitions columndefinition columndefinition gridcolumndefinitions progressring xnamecustomprogressring height40 width40 isactivetrue gridcolumn0 margin20 textblock xnamecustomtextblock heightauto widthauto fontsize25 gridcolumn1 margin20 grid popup usercontrolhere is how i use it external loginprogressringpopuptext logging in loginprogressringpopupopenpopup,['c#'] +549532,how can i get the ios 7 default blue color programmatically i am creating custom elements in my app and want to match the look and feel of the new ios ios 7 introduced to us a very common lighter blue color the default color or tint for several elements including the system button segmented control etc they have made it easy to select the color using ib as seen herehowever i have not found how to easily access the color programmatically i checked out the uicolor documentation and there does not seem to be any accessor for the blue system color in the class itselfheres my question does a simple accessor exist for this color uicolor or something like it if not does someone know the exact rgb values for that color,['ios'] +549560,a library like pythons collectionscounter library for c getting the difference of values between two dictionary objects in c this is how i would create a dictionary in c dictionarystring int d new dictionarystring int cheese 2 cakes 1 milk 0 humans 1 this ones for laughs in python if you have a dictionary like sofrom collections import countermy first dict cheese 1 cakes 2 milk 3my second dict cheese 0 cakes 1 milk 4print countermy first dict countermy second dict countercheese 1 cakes 1as you can see counter is very useful when comparing dictionary objectsis there a library in c that will allow me to do something similar to this or do i have to code it from scratch,"['c#', 'python']" +549592,comparing uint8 t with a number maybe i do not understand c properly or is it a compilers buguint8 t a 0x00uint8 t b 0xffif a b 1 donothingdonothing is not called as expected because result of ab was implicitly casted to the type of second operand in compare operation and for numbers it is signed int okayif a b uint8 t1 donothingdonothing still is not called but now i do not understand the reason for it i have explicitly casted the number to uint8if uint8 ta b 1 donothingnow donothing is finally called but again why how can subtraction of two uint8 return an intcompiler is uvision armcc for arm cortex m3,"['c++', 'c']" +549685,html newline char in div content editable i am storing content in the database for examplehellothisis textand when i pass that to a textarea it stays with the new line breaks but if i pass that text to a div with content editable it would stay like thishello this is texthow can i fix this problem,"['css', 'html']" +549721,elegant way of convert a numpy array containing datetimetimedelta into seconds in python 27 i have a numpy array called dt each element is of type datetimetimedelta for exampledt0datetimetimedelta0 1 360how can i convert dt into the array dt sec which contains only seconds without looping my current solution which works but i do not like it is dt sec zeroslendt1for i in range0lendt1 dt seci dtitotal secondsi tried to use dttotal seconds but of course it did not work any idea on how to avoid this loop thanks,['python'] +549730,adding authorization to the headers i have the following codeauthenticationheadervalue authheaders new authenticationheadervalueoauth2 contractaccesstokenstring result await postrequestauthenticatedgetdatafullurl null authheadersreturn result public static async taskstring authenticatedgetdatastring url formurlencodedcontent data authenticationheadervalue authvalue httpclient client new httpclient clientdefaultrequestheadersauthorization new authenticationheadervalueauthvalueparameter httpresponsemessage response await clientpostasyncnew uriurl data responsecontentheaderscontenttype new mediatypeheadervalueapplicationjson responseensuresuccestatuscode string responsebody await responsecontentreadasstringasync return responsebodythe response await part just continues an ongoing loop and nothing happens any ideas what i am doing wrongthe question really is how do i send the following headerauthorization oauth2 access tokento an external web api,['c#'] +549749,auto allowing webrtc permissions in unit tests i am writing unit tests for a library that uses webrtc my test suite requires permissions from chrome for almost every unit test which requires me to manually click the allow button for every testis there a flag or setting i can change to always allow media access globally so that my test suite is not prompted for permissionsi am using the jasmine test runner in chrome,['javascript'] +549759,making ads served trough dfp fully responsive i have modified gpt google publisher tags so it serves on size ads for phones and tablets and the other size for computer or larger screens it works well but sizes are determined on load and when using tablet the ads stay the same regardless if you flip from landscape to portrait view i added the code to dynamically refresh the ads on windows resize and that works as far refreshing goes but sizes are still determined i assume on load and ads sizes do not change how can i arefresh reloada variables size and size2 on window resize before ads are refreshedthis is the code script typetextjavascript googletagcmdpushfunction var width documentdocumentelementclientwidth var size if width 320 width 728 size 320 50 smartphones else size 728 90 desktops and tablets var size2 if width 320 width 728 size2 180 150 smartphones else size2 160 600 desktops and tablets var slot1googletagdefineslotxtp home topboard size divgptad13800755386703addservicegoogletagpubads var slot2googletagdefineslotxtp home skyscraper size2 divgptad138026683490addservicegoogletagpubads googletagpubadsenablesinglerequest googletagenableservices windowresizefunctiongoogletagpubadsrefreshslot1 slot2 script,"['javascript', 'jquery']" +549794,is it possible to end an skaction midaction i have a subclass of skspritenode monsternode it automatically runs around the screen using vectors to follow the player i am currently using the following action to make it run aroundskaction actionmove skaction movetoactualthistance durationtime self runactionactionmove completion currentstate svgmonsterstateidle i am wondering if its possible to make it so the monsternode actually stops running the action if it hits the boundary of the ios device screen i currently have skspritenode boundaries on the edges of the screen linked with a contact delegate to notify if the monster and walls make contact however that means nothing if i cannot actually stop the monsters actionmove action from going to completion the monster needs to stop at the boundaries of the screen if it is not possible to stop an skaction midexecution is there a roundabout way to do so,"['ios', 'objective-c']" +549913,google play how to prevent downloading the large apk expansion file when the user installs the app from the market many of my users have problems to install my app from the play store due to a lack of enought internal memory the size of the app is apk 37mb expansion 13 gbi was aware that many users do not want to have such big data in the system memory and implemented the licencing and downloadlibary example and changed the code that the expansionfile will be downloaded directliy to the physical sdcard but the user can run my downloadprocess only from the optionsmenu within the app the problemgoogle stated hereif google play is unable to download the expansion files it downloads the apk onlybut this seems to be wrong many user complain about installation issues and pendinghanging downloads they say that when they install the app from the market that google play tries to download the obbexpansion file in the first place and what makes it even worse to the internal memoryso the user can not start the app and make use of my download implementationas i want to make use of the security features of googles licensing mechanisms i had following idea upload my app to the developer console without the expansionupload another dummyapk with the 13gb expansion and do not publish ittry to download the expansion from the optionsmenu from my original app und use the licencekey from the dummy apkcan somebody confirm that this could workis there an way to make google play download the large expansion directly to the external memory maybe if i modify the manifest withandroidinstalocationautoany ideas are appreciated,['android'] +549915,receiving data for custom url scheme in android currently in my app i have my own uri scheme to detect when user clicks on a particular uri code used in manifest file is as belowintentfilter category androidnameandroidintentcategorydefault category androidnameandroidintentcategorybrowsable data androidschemehttp androidhostcomtest action androidnameandroidintentactionview intentfilterif a user clicks on a link which has my custom uri in browser it will now popup a options for user to choose my appbut how do i pass this data which is the link to my app when started for further processing basically how do i pass data from browser to my appthanks in advance,['android'] +550022,characterisletterordigitchar returns different value in java 6 and 7 the following code snippet returns 46059 on java 6 and 48757 on java 7 any ideas what might have changedint i 0forchar c charactermin value c charactermax value c ifcharacterisletterordigitc i systemoutprintlni,['java'] +550103,razor syntax highlighting not working in vs 2012 with mvc 5 i am playing around with mvc 5 rc 1 in visual studio 2013 rc works very wellnow i upgraded an existing mvc 4 project in vs 2012 to mvc 5 the same way as described herei also changed the webconfigs see upgrading from mvc4 to mvc5 prereleaseeverything build run web app even intellisense works perfectly except the syntax highlighting of razorc code in viewsi also tried it with an mvc 5 project created in vs 2013 same result so i assume vs 2012 does not understand the new assemblies any known workaround or ideas to get highlighting back,['c#'] +550132,actionbar support with fragment support i need to use a combination of action bar and fragments in one of my android applications that targets gingerbread too so i have used the action bar from the v7 support library and fragments from the v4 support library and extend my class with fragmentactivityi get an error when i type out the line actionbar getsupportactionbarthe error states that getsupportactionbar is undefined for the type myfragmentclass my class name the code works perfectly without the support library is there a solution to my problemthanks,['android'] +550198,what is the security impact of deserializing untrusted data in java is it safe to deserialize untrusted data provided my code makes no assumptions about the state or class of the deserialized object or can the mere act of deserializing cause undesired operation threat model the attacker may freely modify the serialized data but that is all he can do,['java'] +550239,setting up powemockito for static mocking i would like to make use of powermock with mockito to mock some static method calls i have followed instructions and examples from so as well as the powermock getting started and mockstatic pages as best i can but i am yet to complete a mockstatic callwhen i call mockstaticfooclass from my test class i am given the excceptionjavalangnoclassdeffounderror orgmockitomockmocknameat orgpowermockapimockitopowermockitomockstaticpowermockitojava70at my test class method calli am sure this is a setup problem as i have been finding the terminology used for setting this up to be pretty confusing i did grab the mockito zip from the powermock downloads in eclipse 352 i opened the project properties and added all of the jars to the build path i also tried adding the entire unzipped powermockito folder to my environment vars classpath and then just the powermockito jar specifically when that did not work outi have these annotationsat the classlevel of my test class as well per the powermock instructionsrunwithpowermockrunnerclasspreparefortestapplicationcontextloaderclassalso these powermockspecific importsimport orgpowermockapimockitopowermockitoimport orgpowermockcoreclassloaderannotationspreparefortestimport orgpowermockmodulesjunit4powermockrunnerto those of you who have used powermockito before even just a pointer in the right direction or something to check would be really helpful i am struggling to see how my setup differs from that of posts i have seen using from what i can tell the same syntax,['java'] +550253,uilinebreakmodetailtruncation is deprecated i am getting an error saying uilinebreakmodetailtruncation is deprecated any suggestionsselfuserbutton titlelabel setlinebreakmodeuilinebreakmodetailtruncation,"['ios', 'objective-c']" +550271,android crashlytics plugin not installing library when using the crashlytics plugin in intellij i follow these stepsclick plugin on toolbarselect appallow crashlytics to update androidmanifestxml as well has my first activityclick nexttry to build the app as the plugin instructsthen when i try to build i get thispackage comcrashlyticsandroid does not existi look in my dependencies and library and the jar is nowhere to be foundwhat am i missing that would cause the library to not be loaded,['android'] +550348,client on node uncaught referenceerror require is not defined so i am writing an application with the nodeexpress jade comboi have clientjs which is loaded on the client in that file i have code that calls functions from other javascript files my attempt was to usevar m requiremessagesin order to load the contents of messagesjs just like i do on the server side and later on call functions from that file however require is not defined on the client side and it throws an error of the form uncaught referenceerror require is not definedthese other js files are also loaded on runtime at the client because i place the links at the header of the webpage so the client knows all the functions that are exported from these other fileshow do i call these functions from these other js files such as messagesjs in the main clientjs file that opens the socket to the server,['javascript'] +550411,how to convert youtube api duration iso 8601 duration in the format ptms to seconds how can i manipulate a date time in the format ptms with javascriptfor example pt5m33s i would like to output as hhmmss,['javascript'] +550417,memory warning uiimagepickercontroller ios 7 could anybody help me with this issue i am a bit new to objective c and ios i have been working on it but i cannot figure out how to fix the problem my app is really simple it only start the camera take pictures and send them through email to our server this code was working just fine in ios6when i take pictures my memory is heap growth with each screen capture and i get received memory warning and finally terminated due to memory pressure voidimagepickercontrolleruiimagepickercontroller pickerdidfinishpickingmediawithinfonsdictionary infoselfpopovercontroller2 thismisspopoveranimatedtruensstring mediatype info objectforkeyuiimagepickercontrollermediatypeif mediatype isequaltostringnsstring kuttypeimage image info objectforkeyuiimagepickercontrolleroriginalimage image self fixrotation image increased memory when uiimagewritetosavedphotosalbum is uncommented if is comment it does not increased memory but after some pictures i start to get received memory warning message until the app crash if newmedia uiimagewritetosavedphotosalbum image selfselectorimagefinishedsavingwitherrorcontextinfo nil self thismissviewcontrolleranimatedno completionnil self performseguewithidentifierseleccionadocamerar senderself else self performseguewithidentifierseleccionadocamerar senderself uiimage fixrotationuiimage imageif imageimageorientation uiimageorientationup return imagecgaffinetransform transform cgaffinetransformidentityswitch imageimageorientation case uiimageorientationdown case uiimageorientationdownmirrored transform cgaffinetransformtranslatetransform imagesizewidth imagesizeheight transform cgaffinetransformrotatetransform m pi break case uiimageorientationleft case uiimageorientationleftmirrored transform cgaffinetransformtranslatetransform imagesizewidth 0 transform cgaffinetransformrotatetransform m pi 2 break case uiimageorientationright case uiimageorientationrightmirrored transform cgaffinetransformtranslatetransform 0 imagesizeheight transform cgaffinetransformrotatetransform m pi 2 break case uiimageorientationup case uiimageorientationupmirrored breakswitch imageimageorientation case uiimageorientationupmirrored case uiimageorientationdownmirrored transform cgaffinetransformtranslatetransform imagesizewidth 0 transform cgaffinetransformscaletransform 1 1 break case uiimageorientationleftmirrored case uiimageorientationrightmirrored transform cgaffinetransformtranslatetransform imagesizeheight 0 transform cgaffinetransformscaletransform 1 1 break case uiimageorientationup case uiimageorientationdown case uiimageorientationleft case uiimageorientationright break now we draw the underlying cgimage into a new context applying the transform calculated abovecgcontextref ctx cgbitmapcontextcreatenull imagesizewidth imagesizeheight cgimagegetbitspercomponentimagecgimage 0 cgimagegetcolorspaceimagecgimage cgimagegetbitmapinfoimagecgimagecgcontextconcatctmctx transformswitch imageimageorientation case uiimageorientationleft case uiimageorientationleftmirrored case uiimageorientationright case uiimageorientationrightmirrored grr cgcontextdrawimagectx cgrectmake00imagesizeheightimagesizewidth imagecgimage break default cgcontextdrawimagectx cgrectmake00imagesizewidthimagesizeheight imagecgimage when i use instruments it shows that my vm is because of this break and now we just create a new uiimage from the drawing contextcgimageref cgimg cgbitmapcontextcreateimagectxalso this line in instrumentsuiimage img uiimage imagewithcgimagecgimgcgcontextreleasectxcgimagereleasecgimgreturn img probably is a memory management i will appreciate your help,['ios'] +550428,doctrine entitymanager clear does not fully clear i have this piece of codeentitymanagerclearrezamybundleentitylistitemidentity entitymanagergetunitofworkgetidentitymapforeach identity as class objectlist if class rezamybundleentitylistitem print did not fully clear exitingn exit you would think that after i pass in the classname to clear you should not see those objects in the unit of work anymore but by looking at the source i noticed that when you pass an argument to the clear function it only detaches entities of that type on the other hand if i do not pass any arguments to clear it detaches and does in fact clear so the above code does not hit line 138 exit so that means it not only detaches all entities but also clears the unit of workanyone has any thoughts on this should i file a bug with doctrine,['php'] +550518,why is locality determined at compile time this is a bit of a followup to this questionwhy is locality determined at compile time and not at execution time is it purely for performanceare there languages that look up their variables at execution time ie every time a variable is accessed this variable is first searched in the local scope and then the search escalates through all enclosing scopeshow do ecma languages handle thisto put question 2 in other words are there languages where the following code in the necessary syntax worksdef f print fdef g f f 42g,['python'] +550572,doctrine error failed opening required tmp cg sourcephp i am trying to migrate my php application to an ubuntu server but without succes any help would be appreciatedfirst i installed doctrine successfully into jorritmyapp following the first part of doctrines getting started manual till generating the database schema secondly i placed my php scripts which use doctrine in folder jorritmyappwhen i try to run my php script in the cli i get this error messagesphp warning requiretmp cg sourcephp failed to open stream no such file or directory in jorritmyappvendordoctrinecommonlibdoctrinecommonproxyabstractproxyfactoryphp on line 200php fatal error require failed opening required tmp cg sourcephp include pathusrsharephpusrsharepear in jorritmyappvendordoctrinecommonlibdoctrinecommonproxyabstractproxyfactoryphp on line 200bootstrapphp looks like thisphp bootstrapphpuse doctrineormtoolssetupuse doctrineormentitymanagerrequire once vendorautoloadphp create a simple default doctrine orm configuration for annotationsisdevmode falseconfig setupcreateannotationmetadataconfigurationarray dir src isdevmode the connection configurationdbparams array driver pdo mysql host xx user xx password xx dbname xx profiler false obtaining the entity managerentitymanager entitymanagercreatedbparams configthe first lines of my php scriptphprequire once bootstrapphprequire once classesphpconnection entitymanagergetconnectionthe application works fine in my development environment windows the tmp folder exists and is accessible the database is migrated succesfully and exists i did not change anything in the vendor folderany ideas thanks in advance for your help,['php'] +550589,threadsleep1 takes longer than 1ms i searched this question but did not see an answer if it is a duplicate i will gladly close it i am currently trying to do some performance evaluation on a technology and saw some rather unbelievable results so i decided to experiment some in that i wanted to try and see if the stopwatch class was returning what i expectedstopwatch sw stopwatchstartnewthreadsleep1swstopconsolewritelineswelapsedmillisecondsin this case i was pretty much seeing a return value of 15ms i understand the resolution of datetime to be around there but should not threadsleep1 sleep a thread for 1ms the system i am on returns stopwatchishighresolution true and its running in net 4 background this code in its complete and proper form is intended to gather some numbers on aerospike db get requests the db is not on the same box when i printed out the swelapsedmilliseconds when a query was in the middle i am seeing mostly sub millisecond responses and that sounds a little suspect considering my java equivalent code is returning much more believable 5ms15ms responses most of the time the java code is using the difference of systemnanotime by submilli responses in my c code i mean consolewritelineswelapsedmilliseconds prints 0,"['c#', '.net']" +550625,how to style a div to be a responsive square i want my div to adapt its height to always equal its width the width is percental when the parents width decreases the box should decrease by keeping its aspect ratiohow to do this is css,['css'] +550733,load json data without ajax in my small js webapplication i use some json datathe data is on server in a separate static json filemy application being small does not use any frameworks not even jquery and i do not want to mess with xmlhttprequest myselfis there a way to load my json data without ajax and without renaming the file to js and imitating jsonp or including the data in existing js sourcesit is ok if it will work only in modern browsers,['javascript'] +550741,how can i find where gem files are installed i can find which gem is installed by command gem list but it does not show me where the gems are installedhow can i find where the gems are and how can i know before installing a gem where it will be installed,['ruby'] +550773,stop caching for php 553 in mamp installed mamp on a new macbook with php 553reload and refresh do nothing still nothing google around for a few minutes trying to find out what is wrong come back and refresh it works what the heck i went into phpini and thisabled all the new opcache and set the default cache time to 0 added headers to the document to force no caching still same problem what the heck is going on herethe network tab is showing a http 200 request so any new html in the indexphp file renders fine but new php that needs to be rendered by the server is delayed and not rendered until some predetermined set of time passes that i do not know how to change whats going oni checked this in safari too so it is definitely a server thing that is keeping the file from renderinginteresting fact though if i go into mamp and change the php version to the old one php 52 or something it will render normally with no caching issues switch to php 55 and it hangs up in the mamp preferences caching options for 55 do not even exist and are automatically thisabled,['php'] +550778,sql split comma separated row i have a column with a variable number of comma seperated valuessomethingasomethingbsomethingcsomethingelsea somethingelseband i want the result to take each value and create a rowsomethingasomethingbsomethingcsomethingelseasomethingelsebhow can i do this in sql mysql i have tried googling implode and lateral view but those do not seem to turn up related questions all the related so questions are trying to do much more complicated things,"['mysql', 'sql']" +550782,how to add jquery to jasmineangularjs unittests i have a project which is builded on plain angularjs code we creates unittest with jasmine but now we need to grab some 3rd party components some directives from angularbootstrap which is also pure angularjs inside but for testing that components some jquery code and methods calls used and now a lot of 3rd party tests failed with exception like object had no method trigger and stuff like that so my question is how to include jquery to my tests to make 3rd party unitests validi run tests with karma,['javascript'] +550793,uitextfield webview no longer supported i get the below debug output when working with some text fieldsuitextfield webview called this method is no longer supported with the new text architecturecan someone explain why this is appearingi am currently running xcode 5 with ios 7,['ios'] +550916,python how would you save a simple settingsconfig file i do not care if it is json pickle yaml or whateverall other implementations i have seen are not forwards compatible so if i have a config file add a new key in the code then load that config file it will just crashare there any simple way to do this,['python'] +550956,arrayadapter in android to create simple listview i tried to create an activity in android this activity only contains a listview nothing elseas i know to fill the listview we need to use an arrayadapterso to understand the arrayadapter i have read the following linkbut still i am unable to understand it clearlyone of the biggest doubt is why the constructor needs a textview resource id while my activity is not having any textviews what i should have to give iti am not talking that this is the only one constructor but what i try to explain is that i am unable to understand itin order to create a simple listview i also referred following linksimple listview using arrayadapter examplebut again my main doubt is why it needs a textview resource idif anybody can explain it with example it will be great helpfuleditarrayadapterstring adapter new arrayadapterstringthis androidrlayoutsimple list item 1 androidridtext1 values,['android'] +551047,where can i download spring framework jars without using maven springsourceorg changed their site to does someone know how to get the latest build without mavengithub from,['java'] +551062,can literals in python be overridden could not find a way to phrase the title better feel free to correcti am pretty new to python currently experimenting with the language i have noticed that all builtins types cannot be extended with other members i would like for example to add an each method to the list type but that would be impossible i realize that it is designed that way for efficiency reasons and that most of the builtins types are implemented in cwell one why i found to override this behavior is be defining a new class which extends list but otherwise does nothing then i can assign the variable list to that new class and each time i would like to instantiate a new list i would use the list constructor like it would have been used to create the original list typeclass mylistlist def eachself func for item in self funcitemlist mylistmy list list1234my listeachlambda x printxoutput1234the idea can be generalize of course by defining a method that gets a built it type and returns a class that extends that type further more the original list variable can be saved in another variable to keep an access to itonly problem i am facing right now is that when you instantiate a list by its literal form ie 1234 it will still use the original list constructor or does it is there a way to override this behavior if the answer is no do you know of some other way of enabling the user to extend the builtins types just like javascript allows extending builtins prototypesi find this limitation of builtins being unable to add members to them one of pythons drawbacks making it inconsistent with other userdefined types overall i really love the language and i really do not understand why this limitation is really necessary,['python'] +551103,how to add items to array in nodejs how do i iterate through an existing array and add the items to a new array var array foreach calendars function item index array itemid done function done consolelogarraythe above code would normally work in js not sure about the alternative in node js i tried push and splice but neither worked,['javascript'] +551154,can pip or setuptools thistribute etc list the license used by each installed package i am trying to audit a python project with a large number of dependencies and while i can manually look up each projects homepagelicense terms it seems like most oss packages should already contain the license name and version in their metadata unfortunately i cannot find any options in pip or easy install to list more than the package name and installed version via pip freezedoes anyone have pointers to a tool to list license metadata for python packages,['python'] +551175,afnetworking 20 use responseobject as nsdictionary afhttprequestoperationmanager manager afhttprequestoperationmanager managermanager get parametersnil successafhttprequestoperation operation id responseobject nslogjson responseobject failureafhttprequestoperation operation nserror error nslogerror errorthis is the recommended way to send get request in afnetworking 20 i want to get the value of a specific key in the json so i want to use responseobject as nsdictionary this is what i was tryingnserror jsonerror nilnsdictionary json nsjsonserialization jsonobjectwithdatansdata responseobject optionskniloptions errorjsonerrorit did not work terminating app due to uncaught exception nsinvalidargumentexception reason nscfdictionary bytes unrecognized selector sent to instance 0xa048120how can i get the value of a specific key in responseobject,"['ios', 'iphone', 'objective-c']" +551194,this client id is globally unique and is already in use i have created android client id for comweetechalliswall for my app actually i have created 2 id one for by eclipse keystore and one is for my signed key store my application is live so i can not change packagei have tried by deleting project and recreating project but could not work now i am not able to create client id for comweetechalliswalli refereed this question should i contact google now from any project i am getting this error this client id is globally unique and is already in usemy application is live and not working google plus client if google is reading this then please help me to sort out thiseditright now i have not any android client id regarding this comweetechalliswall and i am still not able to create single one for this,['android'] +551280,pylab histogram get rid of nan i have a problem with making a histogram when some of my data contains not a number values i can get rid of the error by using nan to num from numpy but than i get a lot of zero values which mess up the histogram as wellpylabfigurepylabhistnumpynan to numapylabshowso the idea would be to make another array in which all the nan values are gone or to just mask them in the histogram in some way preferrably with some builtin method,['python'] +551342,memory leak in angulars compile summarywhy is the following plunkr causing a memory leak every time compile runsexplanation to the codei am writing a directive which sometimes needs to completely rerender its html it does this by generating its template as a string and then feeding that string to compile finally using jquery to remove the old dom and replace it with the newly rendered elementeach time it does this the application leaks several megabytes of memory often crashing the browser the chrome heap snapshot shows a tree of detached dom elements gets added each time but the plunkr for some reason does not have this issue although it still leaks a lotwhat am i doing wrong that causes this memory leakwhat generating a string template and recompiling it whythis is clearly not the way angular directives are meant to be written i know my first approach would be a combination of ngrepeats with other twoway binding unfortunately this causes performance issues as the number of watchstatements on the scope increases for a bit of reasoning as to why i chose this approach i give a small rant about it here databinding in angularjsediti have been working on the plunk and it no longer leaks memory i will keep this question around in case anyone else finds it useful as a nonleaking method for recompiling dom,"['javascript', 'jquery']" +551415,stdvector as a template function argument i want make a class method that take stdvector reference as an argumenti want to use it with different types of dataso i want to make function likevoid some functionconst stdvector vect do something with vector and i want use it with for examplestdvectorint v1some functionv1stdvectorstring v2some functionv2i hope that i made my point cleardo i have to make template method like thattemplateclass tvoid some functionstdvectort vector i can do it in other way if i have to tell me how i can write that method in classthanks for help,['c++'] +551454,spritekit skaction easing well the title gives the question away how can i apply easing to the skaction node actions in spritekiti found that this worksskaction moveaction skaction movebyxmovex ymovey duration05moveactiontimingmode skactiontimingeaseineaseoutnode runactionmoveactionhowever there are only a few easing types available there namely linear easein easeout easeinout and those easing values are fixed and cannot be altered i am looking for something like eleasticinout with preferably a bit more control how can i create that,['ios'] +551461,cannot get uicollectionview to thisplay cells i am trying to get a uicollectionview to thisplay inside a modally presented view controller the app is for ipad ios 7i have created subclass of uiviewcontroller with a nib and added it like thismyviewcontroller controller myviewcontroller alloc inituinavigationcontroller navcontroller uinavigationcontroller alloc initwithrootviewcontrollercontrollernavcontrollermodalpresentationstyle uimodalpresentationfullscreennavcontrollernavigationbarbarstyle uibarstyleblacktranslucentself presentviewcontrollernavcontroller animatedyes completionnilthis view controller is to be the delegate and datasource for my uicollectionview so i have added uicollectionviewdatasource and uicollectionviewdelegate to the headeri have put a uicollectionview into the nib and added an outlet to myviewcontrollerproperty strong nonatomic iboutlet mycollectionview collectionviewcontrolleri have added this in viewdidload in myviewcontrollerselfcollectionviewcontrollerdatasource selfselfcollectionviewcontrollerdelegate selfi have also added the following to myviewcontroller nsintegercollectionviewuicollectionview collectionview numberofitemsinsectionnsintegersection nslogitems in section d itemsarraycount returns correct amount return itemsarraycount uicollectionviewcell collectionviewuicollectionview collectionview cellforitematindexpathnsindexpath indexpath nslogcellforitematindexpath indexpath returns as expected static nsstring identifier mycell selfcollectionviewcontroller registerclassmycollectioncell class forcellwithreuseidentifieridentifier mycollectioncell cell collectionview dequeuereusablecellwithreuseidentifieridentifier forindexpathindexpath uiimageview myimageview uiimageview cell viewwithtag100 myimageviewimage uiimage imagenameditemsarray objectatindexindexpathrow return celli have also set up a subclass of uicollectionviewcell with the identifier set to mycell and added to it a uiimageview with the tag 100whenever i bring up this view controller i am getting the navigation bar as expected but the uicollection view i have added to my nib is nowhere to be seen all i am seeing is black where the collection view should be if i change the background colour of mycollectionview from default to white i see white where the collection view ought to be it seems to be bringing up mycollectionview but not showing any cells,['ios'] +551464,listview filtering with cursorloader and custom cursoradapter i am currently doing a project that involves showing a list of locations nearby based on my current locationi just started android programming not long ago so i am still at my learning while coding phasei searched all over trying to get some clues on how to proceed i am still stuck after reading and trying outmy working code currently consists ofcursorloadera custom resourcecursoradapter that help populates my entries on the listviewquestionswhat is the correct way to filter entries for my listview i saw posts on filterfilterable interface but it does not seems to work for my current setup do i perform filtering inside my custom cursoradapterhow should i refresh my listview after i perform filtering do i call getloadermanagerrestartloader0 null this or adapternotifydatasetchanged thanks in advance,['android'] +551474,how to avoid race conditions in a condition variable in vxworks were programming on a proprietary embedded platform sitting atop of vxworks 55 in our toolbox we have a condition variable that is implemented using a vxworks binary semaphore now posix provides a wait function that also takes a mutex this will unlock the mutex so that some other task might write to the data and waits for the other task to signal it is done writing the data i believe this implements whats called a monitor icbwt we need such a wait function but implementing it is tricky a simple approach would do this bool conditionwait formutex mutex const unlocker ulmutex relinquish mutex return waitevent uls dtor grabs mutex againhowever this sports a race condition because it allows another task to preempt this one after the unlocking and before the waiting the other task can write to the date after it was unlocked and signal the condition before this task starts to wait for the semaphore we have tested this and this indeed happens and blocks the waiting task forever given that vxworks 55 does not seem to provide an api to temporarily relinquish a semaphore while waiting for a signal is there a way to implement this on top of the provided synchronization routines note this is a very old vxworks version that has been compiled without posix support by the vendor of the proprietary hardware from what i understood,['c++'] +551543,is there a global approach to catch network errors in javascript i am researching the possibility of automated onpage error detection via javascript i have found several questions where the answer allows you to catch javascript compilation and runtime errors globally via windowonerror but no answers mention other types of nonjavascript errors that are often reported in browser error consoles i am primarily interested in network errors invalid uris ssl errors http errors timeouts and resource interpretation errors mismatching types resulting in aborting the interpretation of the resource parsing errors on loaded resources etci checked the performancegetentries method but i am baffled to find that it does not seem to contain network requests that resulted in errors i checked only in chrome 29i do not need full cross browser compatibility as long as it works on some browsers and does not break the others that is fine,['javascript'] +551553,is it possible to remove a break point set with ipdbset trace i used ipdbset trace somewhere in my python code is it possible to ignore this break point using a ipdb commandclear tells me that it cleared all break points but ipdb stops again when it stumbles upon the line with ipdbset tracethisable 1 tells me no breakpoint numbered 1ignore 1 says breakpoint index 1 is not validto clarify of course i could simply remove the break point from my source code but this would require to quit the debugger and to start it again often it needs a lot of work to get somewhere and restarting the debugger makes life more difficult also if there is a huge loop and you want inspect objects in the loop the easiest is to place a break point in the loop directly after the object how could i then skip the loop and all thousands of calls set trace and step through the code after the loop using next,['python'] +551563,prevent cssother resource download in phantomjsselenium driven by python i am trying to speed up seleniumphantomjs webscraper in python by preventing download of cssother resources all i need to download is img src and alt tags i have found this code pageonresourcerequested functionrequestdata request if httpcssgitestrequestdataurl requestdatacontenttype textcss consolelogthe url of the request is matching aborting requestdataurl requestabort via how can i control phantomjs to skip download some kind of resourcehowwhere can i implement this code in selenium driven by python or is there another better way to stop cssother resources from downloadingnote i have already found how to prevent image download by editing service args variable viahow do i set a proxy for phantomjsghostdriver in python webdriverand phantomjs 18 with selenium on python how to block imagesbut service args cannot help me with resources like css thanks,['python'] +551613,mysql select or update acting very strange i got a very simple select statement for instanceselect id some more fields that do not matter from account where status 0 limit 2keep in mind that the above returns the following ids 12the next thing i do is loop these rows in a for each and update some recordsupdate account set connection sessionaccount id status 1 where id row idnow the rows in the table with ids 12 have the status 1 which i do check to make sure the rows where correctly updated if it failed to do such i will undo everything as soon as everything is ok i have a counter at the first place which is 2 in this case so 2 rows should have been updated and i check this with a simple countthis information will also be emailed with for instance the following data which means everything was updated correctly time of update 20130930 163002 total rows to be updated selected 2 total rows successfully updated after completing queries 2the following ids should have been updated these where returned by the select statement12so far so good now comes the weird partthe very next query made by a other user will however sometimes return for instance the ids 12 but that is impossible because these should never be returned by the select statement because they do not contain the status 0 anymore so what happens is the followingi now receive an email with for instance time of update 20130930 163039 total rows to be updated selected 10 total rows successfully updated after completing queries 8the following ids should have been updated these where returned by the select statement12345678910now it is really strange the 1 and 2 are selected by the update in most cases it goes good but very rarely it just does not and returns some same ids which are already updated with a status 1notice the time between these updates it is not even the same time i first thought it would be something like that these queries would be executed at the exact same time which is impossible right or is this possible or could it somehow be that the query has been cached and should i edit some settings at my mysqlconf filei have never had this problem i tried every way of updating but it seems to keep happening is it maybe possible at some way to combine these 2 queries in one huge update query all the data is just the same and does not do anything strange i hope someone has a clue what this could cause the problem and why this is randomly rarely happeningediti updated the script added the microtime to check how long the select update and checkselect together takes first member with id 20468 makes a call at 20131001 08301022 rows have been updated correctly of the following 2 ids 33412395queries took together 08780050271 secondssecond member with id 10123 makes a call at 20131001 0830142022 rows have been updated correctly of the following 22 ids 39233412395396414891301252797122811 and some more but not importantqueries took together 33440849781036 secondsnow you see that the 33412 and 395 are again returned by the selectthird member with id 20951 makes a call at 20131001 08301699 rows have been updated correctly of the following 9 ids 39233412395396414891301252797122811queries took together did not return anything which concerns me a little bit toosince we do not know how long the last queries took we only know that the first and second should work correctly without problems because if you look there are 4 seconds between them and the execution time was 334 seconds besides that the first one started at 20131001 083017 because the time that is logged for the call when emailing it is at the end of the script the check to see how long the queries took are from the start of the first query and the stop directly after the last query and this is before i send the email of coursecould it be something in mycnf file that mysql is doing this weirdstill i do not understand why id did not return any execution time for the last third calla solution for this would be to queue these actions by first saving them into a table and executing them one at a time by a cron job but it is not really what i want it should be instant when a member makes the call thanks for the help so faranyway here is my mycnf in case someone has suggestions for me server has 16gb ram installedclientport 3306socket varrunmysqldmysqldsockmysqld safe socket varrunmysqldmysqldsocknice 0mysqlduser mysqlpidfile varrunmysqldmysqldpidsocket varrunmysqldmysqldsockport 3306basedir usrdatadir varlibmysqltmpdir tmplcmessagesdir usrsharemysqlskipexternallockingkey buffer 16m max allowed packet 16mthread stack 192kthread cache size 8myisamrecover backupmax connections 20query cache type 1 query cache limit 1m query cache size 4mlog error varlogmysqlerrorlogexpire logs days 10max binlog size 100minnodb buffer pool size 3mjoin buffer size 128k tmp table size 16mmax heap table size 16mtable cache 200mysqldumpquickquotenamesmax allowed packet 16mmysqlnoautorehash faster start of mysql but no tab completitionisamchkkey buffer 16mincludedir etcmysqlconfdedit 2 recycle available thisaccountmembershipquery select accountid select countlast clicksid from last clicks where last clicksaccount accountid and last clicksroulette 0 and last clicksdate between seven days back and tomorrow as total select countlast clicksid7 from last clicks where last clicksaccount accountid and last clicksroulette 0 and last clicksdate between seven days back and tomorrow as avg from membership as membership inner join account as account on accountid membershipaccount where accountmembership 0 and accountreferrer 0 and membershipmembership 1 having avg 09 order by total desc foreachreferrals as key value thisaccountqueryupdate account set referreraccount id sincesince date expiresvalueaccountexpires marker0 kind1 auction amountvalueaccountauction amount where idrecycle availablekeyaccountid new referral id recycle availablekeyaccountid counter total updated thisaccountfindcountarrayconditionsarrayaccountidnew referral id accountreferreraccount id accountkind1,"['php', 'mysql']" +551614,rounding entries in a pandas dafaframe using newdf3pivot tablerowsquradateaggfuncnpmeanwhich yields alabama exp credit exp inventory exp national exp price exp sales expquradate 20100115 0568003 0404481 0488601 0483097 0431211 057075520100415 0543620 0385417 0455078 0468750 0408203 0564453i would like to get the decimal numbers rounded to two digit and multiplied by 100 eg 568003 should be 57 been fiddling with it for a while to no avail tried thisnewdf3pivot tablerowsquradateaggfuncnpmeanapplyround2 and gottypeerror float object is not callable uoccurred at index alabama exptried a number of other approaches to no avail most complain about the item not being a float i see that the pandas series object has a round method but df does not i tried using dfapply but it complained about the float issue,['python'] +551642,mysql join two tables with comma separated values i have 2 tables as belownotes tablea nid a fordepts aa a 1 a 124 aa 2 a 45 apositions tablea id a name aa a 1 a executive aa 2 a corp admin aa 3 a sales aa 4 a art aa 5 a marketing ai am looking to query my notes table and associate the fordepts column with values from the positions tablethe output should be a a a 1 a executive corp admin art a a 2 a art marketing a ai know that the database should be normalized but i cannot change the database structure for this projectthis is going to be used to export a excel file with the code belowphp dbh1 mysql connecthostname username password mysql select dbexadmin dbh1 function cleandatastr str preg replacet t str str preg replacern n str ifstrstrstr str str replace str filename exteres summary datemdy xls headercontentthisposition attachment filenamefilename headercontenttype applicationvndmsexcel headercontenttype textplain flag false result mysql query select pname ccompany nnid ncreatedon concat ws c2fnamec2lname ndescription from notes and left join positions p on pid nfordepts left join companies c on cuserid nclientid left join companies c2 on c2userid ncreatedby dbh1 whilefalse row mysql fetch assocresult ifflag colnames array created for created for company company case id case id created on created on created by created by description description thisplay fieldcolumn names as first row echo implodet array keyscolnames rn flag true rowcreatedon datemdy gi a strtotimerowcreatedon array walkrow cleandata echo implodet array valuesrow rn exit this code outputs only the first value of fordeptsexa executive instead of executive corp admin artcan this be accomplished by concat or find in setplease help thanks in advance,"['php', 'mysql']" +551648,provide a default fail method for a jquery deferred object i am writing a javascript api client using jquery my top level request method looks like this function requestmethod uri params proxies var deferred deferred ajax data method get params jsonstringifyparams contenttype applicationjson datatype json url apiroot uri type method xhrfields withcredentials true donefunctionbody deferredresolvewiththis bodydata failfunctionxhr deferredrejectwiththis xhr return deferredpromisehow can i have a default fail handler for my returned deferred that is if the deferred has no other handlers attached to it is fail condition call a default handleri want to do this to have global exception handling in my application except for the parts that have a specific handling and will define their own fail handler on the deferred,"['javascript', 'jquery']" +551659,render html partial in json jbuilder i am rendering json of some students using jbuilder in rails 4 i want each student to have a html attribute that contains the html partial for a given student html bi was rendered from a partialb i have tried the followingjsonarray students do student jsonhtml render partial students student locals student student endbut this gives me missing partial students student with localeen formatsjson handlerserb builder raw ruby jbuilder coffee haml,"['ruby-on-rails', 'ruby']" +551687,what is an alternative to password hash for php 5 550 according to manual password hash this function can be used for php 5 550after searching for an alternative way i found this simple function from here function generatehashpassword if definedcrypt blowfish crypt blowfish salt 2y11 substrmd5uniqidrand true 0 22 return cryptpassword salt i can manage my code by using function exists before using but my question is about above alternative code if its secure or not or is there any alternative in older versions of php,['php'] +551713,not passing credentials to wcf service resulting in a 401 i am tearing my hair out on this one i have a wcf service that i can call through the browser and it works fine when i call it from the web application with the below method i get a 401 unauthorized error and the service does not get called whats more when i run my web application from my local machine debug mode using iis express pointed at my dev server iis7 it works but when i deploy my web application to the dev server and point it to the dev server services it fails wit the 401 error i think this is something to do with iis7 but i am not 100 sure and help would be super usefuli have looked online for the answers but thus far the best i have found is thismy service call is as followsvar request httpwebrequest webrequestcreateurlrequestmethod getrequestcontenttype applicationjson charsetutf8requestauthenticationlevel authenticationlevelmutualauthrequestedrequestcredentials credentialcachedefaultcredentialswebresponse responce requestgetresponsestream reader responcegetresponsestreamvar sreader new streamreaderreaderstring outresult sreaderreadtoendsreaderclosevar result t jsonconvertdeserializeobjectoutresult typeof treturn resultmy configuration for the service looks like this service namergmpserviceshouseholdingservicesaccountservice behaviorconfigurationdefault endpoint address kindwebhttpendpoint endpointconfigurationsecuredhttpendpointbinding contractrgmpserviceshouseholdingcontractsiaccountservice service service namergmpserviceshouseholdingserviceshouseholdservice behaviorconfigurationdefault endpoint address kindwebhttpendpoint endpointconfigurationsecuredhttpendpointbinding contractrgmpserviceshouseholdingcontractsihouseholdservice service service namergmpserviceshouseholdingservicesuserservice behaviorconfigurationdefault endpoint address kindwebhttpendpoint endpointconfigurationsecuredhttpendpointbinding contractrgmpserviceshouseholdingcontractsiuserservice serviceservicesbehaviors endpointbehaviors behavior namewebbehaviour webhttp behavior endpointbehaviors servicebehaviors behavior namedefault servicemetadata httpgetenabledtrue httpsgetenabledtrue servicedebug includeexceptiondetailinfaultstrue behavior servicebehaviorsbehaviorsstandardendpoints webhttpendpoint standardendpoint namesecuredhttpendpointbinding helpenabledtrue automaticformatselectionenabledtrue security modetransportcredentialonly transport clientcredentialtypewindows security standardendpoint webhttpendpointstandardendpointsi have put some logging on the client service call just before i call the service the response isdebug 20131001 131513569 452ms servicegetsingle passing login mylandomainmylanusernameerror 20131001 131513631 514ms servicegetsingle error calling servicegetsingle with user credentials login mylandomainmylanusername systemnetwebexception the remote server returned an error 401 unauthorized at systemnethttpwebrequestgetresponse at householdingcommonservicehelperservicegetsingletstring urlthe code looks likeloggerdebugpassing login systemsecurityprincipalwindowsidentitygetcurrentnameeven when i set the apool for my website to my domain account it is still not authorising me to access the wcf service but again it is working for the browser so weird,['c#'] +551757,what is the meaning of multiline comment warnings in c i am working on a c file for a homework assignment and i thought it might help the graders if i made my answers visible like soanswerblah blah blah answering thequestions etc etcand found when compiling with gcc that those backslash characters at the end of the first line seemed to be triggering a multiline comment warning when i removed them the warning thisappeared so my question is twofold a how exactly does the presence of the backslash characters make it a multiline comment and b why would a multiline comment be a problem anyway,['c'] +551760,swipe back like pinterest or tumblr does anybody has an idea how pinterest or tumblr has implemented there swipe back methodie on pinterest you can click on a post on the news feed than the detailactivity is started and thisplays the details for the selected post than you can press the back button to return to the news feed activity or you can swipe the details activity to the left to come back to the news feed activityvideo normally i would use overridependingtransition but overridependingtransition takes animations resource ids like ranimfoo pinterest and tumblr start the animation only if the user do a swipe gesture they also support some kind of frame by frame animation according the fingers move so they track the thistance of the finger move and animate the transition to the corresponding percentage valuei know how to use a real java animation animatorset object with fragmenttransaction to animate a fragment replacement with fragments i have to override oncreateanimator but i have no clue how to implement something like that with activities is there a oncreateanimator or something similar for activities also not sure how to swipe behaviour since its not starting the animation right now but more a step by step property changement of the window activity fragment or whatever any suggestionsediti have found a video of the pinterest app at youtube thats what i want to implementi guess pinterest is working with fragments and oncreateanimator to achieve the swipe backsince my app has already fragment and childfragments in a activity it would be so much easier for me if i could implement that for activitiesonce more i know how to detect swipe gestures and thats not what i am asking for watch the youtube video updatei have created a little library which has not exactly the same behavior like pinterest or tumblrs implementation however for my apps this seems to me a good solution,['android'] +551797,explanation of the safe average of two numbers whenever i need to average two numbers for an algorithm like binary search i always do something like thisint mid low high low 2i recently saw another way to do it in this post but i do not understand it it says you can do this in javaint mid low high 1or this in cint mid unsigned intlow unsigned inthigh 1the c version essentially makes both operands unsigned so doing a shift results in an arithmetic shift instead of a signed shift i understand what both these pieces of code are doing but how does this solve the overflow issue i thought the whole issue was that the intermediate value high low could overfloweditoh duh all the answers did not exactly answer my question but it was john zeringues answer that made it click i will try to explain herethe issue with high low2 in java is not exactly that high low overflows it does overflow since the integers are both signed but all the bits are still there and no information is lost the issue with taking the average like this is the division the division is operating on a signed value so your result will be negative using the shift instead will divide by two but consider the bits instead of the sign effectively treating it as unsigned,"['java', 'c++']" +551861,how does rubys operator work i recently came across some code using a method call consisting of the format objectarg1 arg2 without seeing a good explanation of how it works see this sample codeclass testserviceobject def call method endendtestserviceobjectnew methodwhats the term for this kind of shorthand,['ruby'] +551887,dynamic view with swiping horizontally and vertically please check above view i have to create a view accordingly where when we slide left to right images will come same as right to left when i slide top to bottom a web view will come and sliding bottom to top images will come all the data like images and web url will be dynamic and data will come from server also i have to apply pull to refresh concept in iti have gone through this link and successfully implemented it but its not accordingly and it have many limitationsplease let me know that if this kind of view is possible or not,['android'] +551900,twitter bootstrap boxsizing ruined my layout my layout broken when i implement bootstrap during the half way of my project fixed that with some css modification and i had commented out thisbeforeafter webkitboxsizing borderbox mozboxsizing borderbox boxsizing borderboxin bootstrapcss will that affect its core i just want to use the grid system in my project,['css'] +551919,how to check if a date is greater than other in java i am working on a java application which generates a report for a duration entered by a user in the command linethe user needs to enter the dates in the following format ddmmy java report startdate enddateexamplejava report 01012013 31032013in the code i save the dates in 2 strings i have to make sure that the start date entered by the user should be a date earlier than the enddateis there an in built function which can help me achieve this by passing these 2 strings to it thanks,['java'] +551926,how to call webmethod in aspnet c i want to call a web method in aspnet c application using the following codejqueryjqueryajax url addtocartaspxaddto cart type post data quantity total qty itemid itemid contenttype applicationjson charsetutf8 datatype json beforesend function alertstart success function data alerta failure function msg alertsorry c codesystemwebserviceswebmethodpublic static string addto cartint quantity int itemid spiritssharedshoppingcartadditemitemid quantity return addbut it always call page load how can i fix it,"['c#', 'jquery', 'asp.net']" +551930,how to change datazoomimage value i am using elevate zoom effects for zooming facility of image my image tag isimg idzoom 01 srcnew foldersmallimagejpg datazoomimagenew folderlargeimagejpgand elevatezoom script isscript zoom 01elevatezoomscrollzoom truescripti have many images that i want to zoom with same idsrc value is changing but i could not change datazoomimage valuehow do change datazoomimage valueyou can also visit any e coomerce websitethat what i am trying to tell1,"['javascript', 'jquery', 'html']" +551931,net vs objective c sha512 mismatch i am trying to write function for creating sha512 string in objective from net function which is public static string getsha512string strplain unicodeencoding ue new unicodeencoding byte hashvalue null byte messagebytes uegetbytesstrplain systemsecuritycryptographysha512managed shhash new systemsecuritycryptographysha512managed string strhex stringempty hashvalue shhashcomputehashmessagebytes foreach byte b in hashvalue strhex stringformat0x2 b return strhexthis gives result as input pass123output 2a6353744cc2914c602265f50d2e413d0561368775756392517abb340ef75d52ee0c5d3623d1826fd768a13dca8961f5957c75df0d793b9d7537aabe050705what i have tried is as follownsstring createsha512nsstring string const char cstr string cstringusingencodingnsutf8stringencoding nsdata data nsdata datawithbytescstr lengthstringlength uint8 t digestcc sha512 digest length cc sha512databytes datalength digest nsmutablestring output nsmutablestring stringwithcapacitycc sha512 digest length forint i 0 i cc sha512 digest length i output appendformat02x digesti return outputwhich gives result belowinput pass123output fd37ca5ca8763ae077a5e9740212319591603c42a08a60dcc91d12e7e457b024f6bdfdc10cdc1383e1602ff2092b4bc1bb8cac9306a9965eb352435f5dfe8bb0can anyone please suggest what am i doing wrong why these two values differ please correct my mistakeseditmean while i have tried changing encoding to nsutf16stringencoding and nsunicodestringencoding which results still different and as followsinput pass123output 514331e3f7ca0a295539347ebc4e4f095fe5f3c1df10d43b4d550144c7b30ba9507831893ea63ea22e62e993be529b0d14be7800a90aa0de199d6be62a5f1b,"['ios', '.net', 'objective-c']" +552007,trying to run kivy for the first time i am trying to run kivy for the first time im using a default programfrom kivyapp import appfrom kivyuixwidget import widgetclass ponggamewidget passclass pongappapp def buildself return ponggameif name main pongappruni get this errordone bootstraping kivyhave funnrunning pythonexe cpython27hellopy ntraceback most recent call last file cpython27hellopy line 1 in module from kivyapp import appimporterror no module named kivyapress any key to continue a lot of people have raised the issue online but no one has mentioned the right solution,['python'] +552009,roboto font for android 4 do i need to use roboto font and put it to asset folder if my app will support only android 4 devicesi would greatly appreciate for your help alex ps sorry for my english,['android'] +552044,is there anything in net that gets the abbreviation of all weekdays specific to culture i need the weekdays abbreviation in different cultures i have it in spanish already hardcoded are there something already in net that has it already string days lunes martes miarcoles jeuves viernes sabado domingo string days l m x j v s d,['c#'] +552058,replace null with blank value or zero in sql server i have a temp table and in that one of my column total amount is of integer type and not null while querying data i received null values for total amount column how ever i used following syntax to remove nulls but some how still null values appearing correct me if i am wrongcreate table temp1 issue varchar100 not null total amount int not null this is my query case when total amount 0 then 0 else isnulltotal amount 0 end as total amount i am facing issue at my else part,['sql'] +552069,splitting a table cell into two columns in html i have the following tabletable border1 tr th scopecolheaderth th scopecolheaderth th scopecolheaderth tr tr th scoperownbspth tdnbsptd tdsplit this one into two columnstd trtableand i wish to split the cell which contains split this one into two columns into two cellscolumns how do i go about thisfiddle,"['html', 'css']" +552090,showing jdialog in taskbar not working i am using the below code to showing jdialog on taskbar and is perfectly working in jdk 16public class test8 public static void mainstring args runnable r new runnable public void run jdialog d new jdialogframenulldialogmodalitytypetoolkit modal dsettitletitle dsetsize300200 dsetvisibletrue systemexit0 eventqueueinvokelaterr but when i am setting the modality type using the method it is not workingpublic class test8 public static void mainstring args runnable r new runnable public void run jdialog d new jdialog dsettitletitle dsetsize300200 dsetmodalitytypedialogmodalitytypetoolkit modal dsetvisibletrue systemexit0 eventqueueinvokelaterr what is the difference betwwen the two codes is there any way to solve this using the method,['java'] +552125,how to generate equispaced interpolating values i have a list of xy values that are not uniformly spaced here is the archive used in this questioni am able to interpolate between the values but what i get are not equispaced interpolating points heres what i dox data 061306150615y data 591953495413 interpolate values for x and yt nplinspace0 1 lenx datat2 nplinspace0 1 100 onedimensional linear interpolationx2 npinterpt2 t x datay2 npinterpt2 t y data plot xy datapltscatterx data y data markero colork s40 lw0 plot interpolated pointspltscatterx2 y2 markero colorr s10 lw05which results inas can be seen the red dots are closer together in sections of the graph where the original points thistribution is denseri need a way to generate the interpolated points equispaced in x y according to a given step value say 01as askewchan correctly points out when i mean equispaced in x y i mean that two consecutive interpolated points in the curve should be thistanced from each other euclidean straight line thistance by the same valuei tried unubtus answer and it works well for smooth curves but seems to break for not so smooth onesthis happens because the code calculates the point thistance in an euclidean way instead of directly over the curve and i need the thistance over the curve to be the same between points can this issue be worked around somehow,['python'] +552139,is it possible for jquery cookies to expire like session variables i know this question has been asked a thousand times but none of the answers really give me what i am looking for i am using jquery cookie to store some information but i want them to expire when the browser closes windowunload is not a viable option read does not workmy question is this is it actually possible to have the cookies set to expire when the browser closes like a session if so does anyone know howupdate turns out it is quite simple instead of passing expiry 0 which did not work just do not pass any expiry at all well this explains why there was not many questionsthanks all,['jquery'] +552164,getsupportactionbar using fragmentactivity i am using fragment activity on one project but it seems v4 support fragmentactivity does not has getsupportactionbar method and i need to use the support one in order to use androidsupportv7appactionbar,['android'] +552176,how do i save and restore a file object in local storage i have an html5javscript app which uses input typefile acceptimagecapturecamera onchangegotphotothisto capture a camera image because my app wants to be runnable offline how do i save the file object in local storage such that it can be retrieved later for an ajax uploadi am grabbing the file object from the using function gotphotoelement var file elementfiles0 i want to save file to local storage here i can stringify the object and save it but when i restore it it is no longer recognised as a file object and thus cannot be used to grab the file contenti have a feeling it cannot be done but am open to suggestions fwiw my work around is to read the file contents at store time and save the full contents to local storage this works but quickly consumes local storage since each file is a 1mb plus photograph,['javascript'] +552231,chose the farthest k points from given and points i have a set s of n points in dimension d for which i can calculate all pairwise thistances if need be i need to select k points in this set so that the sum of their pairwise thistances is maximal in other slightly more mathematical words i want p1 pk in s such that sumij k thistpi pj is maximali know this question is related to this one which is basically the same as mine but for k2 and maybe to this one with farthest instead of closesti am not too sure about that but maybe all the possible solutions have all their points in the convex hull any reasonable approximationheuristic is finevirtual bonus point 1 for a solution which works for any function that gives a score out of the four points one of which could be the square root of the sum of the squared thistancesvirtual bonus point 2 if the solution is easily implemented in python numpyscipy,['python'] +552233,what does a java method return to a jni caller when it throws an exception say i have the following java codepublic class test public static int foo throw new runtimeexception which loads a native library in the usual manner the native library registers and caches the jvm or whatever and then later on this function gets executedjnienv senv initialised somewhere properlyvoid throwmeariver jclass c senvfindclasstest jmethodid m senvgetstaticmethodidc foo i jint i senvcallstaticintmethodc m printfgot dn intievidently senvcheckexception will now return jni true but what will the native function print out in java throwing an exception makes the jvm stop executing the method it is in until it finds an appropriate handler so foos return value is undefined so is i also undefinedi cannot find any specs or anything saying otherwise so presumably i is undefined there is no normal range of callstaticintmethod in this case unlike most jni functionsi am trying this now but i am mainly asking this to see if there is a mandated behaviour somewhere,['java'] +552398,is it possible to update angularjs expressions inside of an iframe sofor example i am trying to pull in an email template into an iframe as a preview for the user inside of an angularjs app the iframe lives inside of the controller area let us call it mainctrl the user would then be able to using the form elements provided inside mainctrl update the preview based on their input so for example let us say our template being pulled into the iframe looks something like thisdoctype htmlhtmlheadmeta nameviewport contentwidthdevicewidth initialscale1 maximumscale1 style typetextcss some styles here styleheadbody h1headerh1 pbodypbodyhtmlso inside our indexhtml angularjs app we would have form elements bound to header and body div ngcontrollermainctrl input typetext ngmodelheader placeholderheader text input typetext ngmodelbody placeholderbody text iframe srctemplatehtml width800 height1500iframedivis that possible is it possible for angularjs to update that information and if so how i have something similar setup and seems that it will not work i cannot get the angularjs expressions to evaluateall that shows up is body etc,"['javascript', 'html']" +552466,jcrop how to crop image by dragging it behing a div like facebook cover i have used jcrop extensively but i want to crop the image in much similar way the facebook uses for cropping its cover imageso i want a div to be of some fixed size wherein the background to hold a draggable image of its original size which the user drag and find the suitable visible region to be croppedfrom what i have learnt in jcrop the original image is of fixed size and draggable region moves over it which you want to be croppedi just want the opposite the image to be draggable and selection region to be fixedis there a way to do it using jcrop,['jquery'] +552483,django improperlyconfigured the secret key setting must not be empty i am trying to set up multiple setting files development production that include some base settings cannot succeed though when i try to run managepy runserver i am getting the following errorcbclimeden srvwcb managepy runserverimproperlyconfigured the secret key setting must not be emptyhere is my settings modulecbclimeden srvwcbcbsettings lltotal 24rwrwr 1 clime clime 8230 oct 2 0256 basepyrwrwr 1 clime clime 489 oct 2 0309 developmentpyrwrwr 1 clime clime 24 oct 2 0234 init pyrwrwr 1 clime clime 471 oct 2 0251 productionpybase settings contain secret keycbclimeden srvwcbcbsettings cat basepy django base settings for cb projectimport djangoconfglobal settings as defaultsdebug falsetemplate debug falseinternal ips 127001admins clime managers adminsdatabases default engine djangodbbackendspostgresql psycopg2 add postgresql psycopg2 mysql sqlite3 or oracle engine djangodbbackendspostgresql psycopg2 name cwu or path to database file if using sqlite3 user clime not used with sqlite3 password not used with sqlite3 host set to empty string for localhost not used with sqlite3 port set to empty string for default not used with sqlite3 local time zone for this installation choices can be found here of tz zones by name although not all choices may be available on all operating systems in a windows environment this must be set to your system time zonetime zone europeprague language code for this installation all choices can be found here language code enussite id 1 if you set this to false django will make some optimizations so as not to load the internationalization machineryuse i18n false if you set this to false django will not format dates numbers and calendars according to the current localeuse l10n false todo make this true and accustom date time inputdate input formats defaultsdate input formats d b y d b y 25 oct 13 25 oct 13 if you set this to false django will not use timezoneaware datetimesuse tz true absolute filesystem path to the directory that will hold useruploaded files example homemediamedialawrencecommediamedia root srvwcbmedia url that handles the media served from media root make sure to use a trailing slash examples media url media absolute path to the directory static files should be collected to do not put anything in this directory yourself store your static files in apps static subdirectories and in staticfiles dirs example homemediamedialawrencecomstaticstatic root srvwcbstatic url prefix for static files example static url static additional locations of static filesstaticfiles dirs put strings here like homehtmlstatic or cwdjangostatic always use forward slashes even on windows do not forget to use absolute paths not relative paths list of finder classes that know how to find static files in various locationsstaticfiles finders djangocontribstaticfilesfindersfilesystemfinder djangocontribstaticfilesfindersappdirectoriesfinder djangocontribstaticfilesfindersdefaultstoragefinder make this unique and do not share it with anybodysecret key 8lu6g0lg9zbaaehkxtxrxgbi1amp022shmi1jcgihb list of callables that know how to import templates from various sourcestemplate loaders djangotemplateloadersfilesystemloader djangotemplateloadersapp directoriesloader djangotemplateloaderseggsloadertemplate context processors djangocontribauthcontext processorsauth djangocorecontext processorsrequest djangocorecontext processorsdebug djangocorecontext processorsi18n djangocorecontext processorsmedia djangocorecontext processorsstatic djangocorecontext processorstz djangocontribmessagescontext processorsmessages webcontextinbox webcontextbase webcontextmain search webcontextenumsmiddleware classes djangomiddlewarecommoncommonmiddleware djangocontribsessionsmiddlewaresessionmiddleware djangomiddlewarecsrfcsrfviewmiddleware djangocontribauthmiddlewareauthenticationmiddleware djangocontribmessagesmiddlewaremessagemiddleware watsonmiddlewaresearchcontextmiddleware debug toolbarmiddlewaredebugtoolbarmiddleware middlewareusermembermiddleware middlewareprofilermiddleware middlewarevaryonacceptmiddleware uncomment the next line for simple clickjacking protection djangomiddlewareclickjackingxframeoptionsmiddlewareroot urlconf cburls python dotted path to the wsgi application used by djangos runserverwsgi application cbwsgiapplicationtemplate dirs put strings here like homehtmldjango templates or cwdjangotemplates always use forward slashes even on windows do not forget to use absolute paths not relative paths srvwcbwebtemplates srvwcbtemplatesinstalled apps djangocontribauth djangocontribcontenttypes djangocontribsessions djangocontribsites djangocontribmessages djangocontribstaticfiles south grappelli must be before admin djangocontribadmin djangocontribadmindocs endless pagination debug toolbar djangoratings watson webauth user model webuser a sample logging configuration the only tangible logging performed by this configuration is to send an email to the site admins on every http 500 error when debugfalse see for more details on how to customize your logging configurationlogging version 1 thisable existing loggers false filters require debug false djangoutilslogrequiredebugfalse formatters standard format asctimes levelnames nameslinenos messages datefmt dby hms handlers mail admins level error filters require debug false class djangoutilslogadminemailhandler null leveldebug classdjangoutilslognullhandler logfile leveldebug classlogginghandlersrotatingfilehandler filename srvwcblogsapplicationlog maxbytes 50 backupcount 2 formatter standard console levelinfo classloggingstreamhandler formatter standard loggers djangorequest handlers mail admins level error propagate true django handlersconsole propagate true levelwarn djangodbbackends handlers console level debug propagate false web handlers console logfile level debug login url loginlogout url logoutendless pagination loading img srcstaticwebimgpreloadergif altloading stylemarginautoendless pagination loading div claspinner small stylemarginauto div classblock 1 spinner block smalldiv div classblock 2 spinner block smalldiv div classblock 3 spinner block smalldiv divdebug toolbar config intercept redirects falseimport djangotemplateloaderdjangotemplateloaderadd to builtinswebtemplatetagscb tagsdjangotemplateloaderadd to builtinswebtemplatetagstag librarywatson postgresql search config publicenglish nostopone of the setting filescbclimeden srvwcbcbsettings cat developmentpy from base import debug truetemplate debug trueallowed hosts 127001 313178149databases default engine djangodbbackendspostgresql psycopg2 name cwu user clime password host port media root srvwcbmediastatic root srvwcbstatictemplate dirs srvwcbwebtemplates srvwcbtemplatescode in managepycbclimeden srvwcb cat managepy usrbinenv pythonimport osimport sysif name main osenvironsetdefaultdjango settings module cbsettingsdevelopment from djangocoremanagement import execute from command line execute from command linesysargvif i add from base import into srvwcbcbsettings init py which is otherwise empty it magically starts to work but i do not understand why anyone could explain to me whats going on here it must be some python module magicedit everything also starts to work if i remove this line from basepydjangotemplateloaderadd to builtinswebtemplatetagscb tagsif i remove this line from webtemplatetagscb tags it also starts to workfrom endless paginationtemplatetags import endlessi guess it is because in the end it leads to from djangoconf import settingsper page getattrsettings endless pagination per page 10so it creates some weird circular stuff and game over,['python'] +552508,evaluating an expression in an attribute of a directive in angularjs i did a lot of workaround searched and researched but i cannot figure how to achieve my goal the problemi have a the following situation i want to avoid the user canoverlap commissions dates in a contract when the user add a newcommission we show a list with the added commissions generated witha ngrepeat this have the difficulty of the user can edit the datesin the part of contracts this is not a problem because for edit acontract you have to go to other screen and edit it the dates cannotbe modified in the same viewwhere i get confusedwhen i edit a commission that was added i have to compare it with the other that what added before so i want to have a list with all the dates of the commissions defined and can say in the directive invoicing a function that returns a list with all the dates excluding the date of the commission that i am editing how i hope solve iti want to do something like this input typetext namenewcomission datefrom ngmodelnewcommissionfrom notincludedmyfunctionindexand the function myfunction will iterate over a list that contains all the addedcommissionsdates and will compare it with all the ranges of dates except with the range contained in addedcommisionsdatesindexthe objective is can evaluate an expression in an attribute without use an isolated scopei had a lot of problems with isolated scopes and i finished agreeing with this postwhen writing a directive how do i decide if a need no new scope a new child scope or a new isolate scopeediti was looking how was implemented ngrequire because ngrequire can accept ngrequireafunction i reached this goal in my directive using parsersso i can execute a function nowi did some progress using this but i want to have the result of execute the function in my directive i want to reach something like thisrangestoeval the result of my function or expressionlooking the things that have ngrepeat i cannot figure in what scope is the value that return this functionifattrsnotincluded var notincludedvalidator functionvalue ngmodelctrlsetvaliditynotincluded attrsnotincluded return value all works good because i am using a boolean but i want to use a list that is the result of execute the expresion in the attribute notincludedthis input is part of a ngrepeatinput typetext ngmodelcommissiondate ngrequiredtrue notincludedfilterdatesfnindex i have the function in my controllerscopefilterdatesfn functionindex in this list we will add the dates of the defined commissions ifscopeaddedcommisionsdate var listtoevalue for var i 0 i scopeaddedcommisionsdatelength i ifi index listtoevaluepushscopeaddedcommisionsdatei return listtoevalue so my next objective is can change toifattrsnotincluded var notincludedvalidator functionvalue put the listtoevalue here and do my comparations and validate or invalidate the form in base of the comparation that i do here return value i will be posting the progress of this researchi will be grateful is somebody can help or share any ideasee you later,['javascript'] +552518,ios7 status bar change to black after search is active i am using uisearchbar as header of uitableview uisearchbar style is uisearchbarstyleminimal and when search is active status bar change to black how to fix thatbefore search is activesearch is active,"['iphone', 'ios']" +552519,how can i check if port is busy in nodejs how can i check if port is busy for localhostis there any standard algorithm i am thinking at making a http request to that url and check if response status code is not 404,['javascript'] +552530,get aspnet temporary folder path from my c code that does not run from within iisaspnet i need to add a user account permissions to the aspnet temp folder it is required while adding my site to iis the folder on my local system iscwindowsmicrosoftnetframework64v4030319temporary aspnet filesi would hate to hardcode this path into my code so i was wondering if i can retrieve it from net framework itself,"['c#', 'asp.net', '.net']" +552584,setting space between table cells only in my table i want to set the space between the cells only so that there is no spacing between table cell and the table itself only between each two cells my table html is 2 columns and 2 rows as shown here table classpresidenttable border0 tbody tr td some text td td img classalignnone srcimageslili239x300jpg width239 height300img td tr tr td td td img srcimageskate240x300jpg width240 height300 td tr tbodytablei used the following csspresidenttable bordercollapse separate borderspacing 15px 0pxthe table should look like this table toptd tdtd tdtable endthere is no space between the td and tr only between each two tdssuggestions,"['html', 'css']" +552605,error installing bundler i am trying to install the bundler gem on my mac with the commandsudo gem install bundler i get the following errorerror could not find a valid gem bundler 0 here is whyunable to download data from ssl connect returned1 errno0 statesslv3 read server certificate b certificate verify failed specs48gzit clearly seems to be a server issue but how do i go about solving this gem update system is currently uptodate is there an alternative way to get bundler,['ruby'] +552722,h2 dateadd for complete day this query will retrieve all records during last 7 daysselect from statistics where timestamp dateaday7 nowhow can i change the query to include the records from midnight 7 days agoexselect dateaday7 nowgives 20130925 134654372but i would like to have 20130925 0,['sql'] +552726,drawing a line with bezierpath using cashapelayer object i am making an image editor which can create different shapes objects like circle triangle and square which can also be updated or removed so i have used cashapelayer for creating shapes objects now i also want to draw a line on image which can also be updated or removed so i have used bezierpath and cashapelayer to create the line it is working fine but now the problem is that when i want to select any existing line it can be selected any where close to line tool because cashapelayer also set the fill region which will be a straight line from start point to end point my question is that how can i create line with no fill region using cashapelayerhere is my code for creating linecashapelayer line cashapelayer layer using bezierpath to make line uibezierpath linepathuibezierpath bezierpath creating l with linelinepath movetopointpoint1linepath addtopointpoint2linepath addtopointpoint3linepathlinepathcgpath configure the appearence of the linelinefillcolor nillineopacity 10linestrokecolor uicolor whitecolorcgcolorany idea on this will be really appreciated,"['ios', 'objective-c']" +552783,bootstrap rows i have a form and im getting confused with rowswhere should i put in rows do i need them do i need one for a modal one for the entire form or each form inputheres what i havediv classcontainer div idmodal classmodal fade modal stuff div modal h1title hereh1 form idcontentaddform classformhorizontal roleform namecontentaddform enctypemultipartformdata div classformgroup label fortitle classcolmd2 controllabeltitlelabel div classcolmd4 input nametitle typetext classformcontrol placeholdertitle div div div classformgroup label fordate classcolmd2 controllabeldatelabel div classcolmd2 div classinputgroup date iddatepicker input typetext classformcontrol namedate value datedmy dataformatddmmy readonly span classinputgroupbtn button classbtn btndefault datepickerinvoker typebuttoni classiconcalendaributton span div div divform,['css'] +552846,java 7 nio watchservice vs jpathwatch the project i am working has been using java 6 and jpathwatch 95 and is now upgrading to java 7 currently on windows 7 and 2008 server i am refactoring areas of code to use the new java 7 nio and is relatively straight forward even using the nio2 to replace jpathwatch however the file watching area of our code began failing unit tests it seems the java 7 nio will not pick up changes in unc paths to other machines othermachpathtowatch to test i implemented the code from the java nio tutorial site and then created a duplicate class swapping in the jpathwwatch imports instead of the java nio imports jpathwatch works for the unc paths but java nio does not it seems to register and even returns an initial event key for the location sample outputinfo watching othermachpathtowatchdebug added othermachpathtowatchinfo got event key sunniofswindowswatchservicewindowswatchkey1f26ecd2info event key for othermachpathtowatchbut then never recognizes any further changes jpathwatch registers and reports directory and file events although it does not report the initial event right after registeringinfo watching othermachpathtowatchdebug added othermachpathtowatchinfo got event key namepachlerniofileimplwindowspathwatchservicewatchrecord79a7bd3binfo event key for othermachpathtowatchinfo event received entry create filedir created othermachpathtowatchnew folderinfo got event key namepachlerniofileimplwindowspathwatchservicewatchrecord79a7bd3binfo event key for othermachpathtowatchinfo event received entry create filedir created othermachpathtowatchnew text documenttxtthis is despite seeing on the jpathwatch thiscussion that networked watching is not supported note response by uwe pachler refering to unc paths has anyone had any luck with watching unc paths and java 7 nio2 any other or more recent solutionsthank youmjash,['java'] +552862,toplayoutguide in child view controller i have a uipageviewcontroller with translucent status bar and navigation bar its toplayoutguide is 64 pixels as expectedhowever the child view controllers of the uipageviewcontroller report a toplayoutguide of 0 pixels even if they are shown under the status bar and navigation bar is this the expected behavior if so whats the best way to position a view of a child view controller under the real toplayoutguideshort of using parentviewcontrollertoplayoutguide which i would consider a hack,['ios'] +552876,keyguard is shown briefly before activity is launched when using flag show when locked i am using the following flags in onattachedtowindow to show my activity above the keyguard flag thismiss keyguard flag show when locked flag turn screen on this works fine however when launching my activity from a background service while the screen was off the keyguard sometimes shows for 12 seconds before my app is thisplayed this happens particularly on slower phones or in low memory situations i find this strange since my understanding was that onattachedtowindow is called after oncreateonresume so all the heavy work should already have been completed when the flags mentioned above are being set is there any way to only show my activity once it has been completely set up,['android'] +552881,understanding the android radio state machine for better battery life on the android documentation page optimizing downloads for efficient network access the gist is that waking up the radio is bad batch your transfers or piggyback on gcm that article leaves some inner working principles for the curiousit said every time you create a new network connection the radio transitions to the full power state what does connection mean here is that a tcp connection does that mean sending a udp packet will not wake up the radioin standby it said standby the minimal energy state during which no network connection is active or required does that mean the network module is completely shut off if so how can gcm even work even when the device is in sleep mode if not roughly how much battery does it use compared to full power modeevery time you create a new network connection the radio transitions to the full power state how does that gibe with long lived tcp connections if i create a tcp connection and then just keep receiving packets then i would not be creating new network connections or sending out any data does that allow the network module to go to standby modedo iphones work pretty much the same way,['android'] +552967,designing a sql schema for a combination of manytomany relationship variations of products i hope the title is somewhat helpful i am using mysql as my databasei am building a database of products and am not sure how to handle storing pricessku of variations of a product a product may have unlimited variations and each variation combination has its own priceskuetcthis is how i have my productsvariations table set up at the momentproducts id name description 1 rug a cool rug 2 cup a coffee cup product variants id product id variant value 1 1 color red 2 1 color blue 3 1 color green 4 1 material wool 5 1 material polyester 6 2 size small 7 2 size medium 8 2 size large productsid is a foreign key of product variantsproduct idi have created an sqlfiddle with this sample data 264d1the user is allowed to enter any variation name product variantsvariant and can assign any value to it product variantsvalue there should not be a limit the amount of variationsvalues a user may enterthis is where my problem arises storing pricessku for each variation without adding a new tablecolumn every time someone adds a product with a variant that did not exist before each variant may have the same price but the sku is unique to each product for example product 1 has 6 different combinations 3 colors 2 materials and product 2 only has 3 different combination 3 sizes 1 i have thought about storing the combinations as a text ie product id combination price sku 1 redwool 50 a121 1 redpolyester 50 a122 1 bluewool 50 a123 1 bluepolyester 50 a124 1 greenwool 50 a125 1 greenpolyester 50 a125 2 small 400 cd12 2 medium 400 cd13 2 large 350 cd14 but there must be a better normalized way of representing this data hypothetical situation i want to be able to search for a blue product that is less than 10 with the above database structure it is not possible to do without parsing the text and that is something i want to avoidany helpsuggestions are appreciated,['sql'] +552991,why is my method not seeing null object i seem not to understand thispublic class newclass public static void mainstring args object obj null mymethodobj public static void mymethodobject objarr ifobjarr null systemoutprintlni am not null to my surprise i am not null is printed on the console why is mymethod not seeing the passed obj parameter as null,['java'] +553006,does documentgetelementbyid return a live dom element does documentgetelementbyid in javascript return a live dom element i am interested to know for performance reason,['javascript'] +553011,python object encapsulation security i have a question and my decision in choosing python as a possible language for a bigger project depends on the answer which i cannot come up with myselfwe all know that python has no real object encapsulation so there is nothing like private properties of an object regarding this issue guido van rossum says that one can access hidden parts of a foreign object without being allowed to with we are all adults just do not do iti can live perfectly well with that as long as the software i write is in my own hand so i am responsible for my own errors and just can try to avoid such thingsbut and here comes my questionwhat if i provide a plugin framework with some plugins that have some extension points and many of the plugins are by other people maybe ones that i cannot trust completelyhow do i prevent exposing internals of my framework from being accessed by a pluginis there a way to achieve this or is the only way to use python having confidence that no one will abuse my api,['python'] +553042,what does passing a template handler in the template name is deprecated mean i have been trying to figure out what this error message means but cannot figure it out here is the full messagedeprecation warning passing a template handler in the template nameis deprecated you can simply remove the handler name or pass renderhandlers jbuilder instead called from realtime atusersarelrvmrubiesruby193p385libruby191benchmarkrb295and here is the codeit is logged in do post apiv1login user login email password 12345678 responsestatusshould be201 endwhat is a template handler and why does it think i am passing it in the template name what template editsessions controller the controller being called by the login path class apiv1sessionscontroller devisesessionscontroller before filter authenticate user except create destroy before filter ensure params exist skip before filter verify authenticity token def create resource userfind for database authenticationemail paramsuser loginemail return invalid login attempt unless resource if resourcevalid passwordparamsuser loginpassword sign inuser resource resourceensure authentication token render apiv1sessionsnewjsonjbuilder status 201 return end invalid login attempt end def destroy current userreset authentication token render json success true end protected def ensure params exist return unless paramsuser loginblank render json success false message missing user login parameter status 422 end def invalid login attempt render apiv1sessionsinvalidjsonjbuilder status 401 endend,['ruby-on-rails'] +553064,is define in c similar to a static variable in java in c we can write define lower 0and in java we can writestatic int lower 0do not these statements have the same purpose of letting other methods use the variable lower,"['java', 'c']" +553084,start with text hidden show text onclick this is all definitely over my head but i had to ask all i really want to do is to start out with the text hidden have only the show button and click on it to show the text it is for a french dictae site where someone listens to a french phrase writes what he thinks he hears in a form text field then clicks the show button to see if he got it right i tried changing the p tag to visibility hidden but then clicking on the show button would not reveal iti searched under toggle but none of the responses seemed to fit mineheres the only answer from searching your site that comes close but i cannot make the text to start out hidden then reveal it by clicking on the show buttondoctype htmlhtmlheadscript srcscriptscriptdocumentreadyfunction hideclickfunction phide showclickfunction pshow scriptheadbodypif you click on the hide button i will thisappearpbutton idhidehidebuttonbutton idshowshowbuttonbodyhtmlthanks for any helpbarryokay yes i have seen that but that still will open any p tag on the page with thisplaynone what i want is to have individual passages capable of being revealed by clicking a button these hide and show buttons open every paragraphfor example on my sitei have two passages one in french and one in english i would like users to be able to show the french while keeping the english hidden and vice versa show the english while keeping the french hidden possible no yesas always thanks for any helpbarry,"['javascript', 'jquery', 'css']" +553170,creating rooms in socketio i would like to ask for your help i am having a hard time in my client side of socketio i would like to call this code in my client side to create a room in socketiovar rooms socketoncreate function roomname roomsroom room socketroom roomname socketjoinroomname subscribesubscribesocketroomi do not know if this is correct if not please help me to correct this guys i am not that to pro in node js and sockets but i have already read their wikis is there any possible way to create room thanks guys,['javascript'] +553175,why does not mutationobserver code run on chrome 30 from i got the following codevar insertednodes var observer new webkitmutationobserverfunctionmutations alertrun mutationsforeachfunctionmutation for var i 0 i mutationaddednodeslength i insertednodespushmutationaddednodesi observerobservedocument childlist true consoleloginsertednodesvar divelement documentcreateelementdivdivelementinnerhtml div elementdocumentqueryselectorbodyappendchilddivelementjsfiddle as you can see we should see a alert because a div element is inserted to the dom but it appears mutationobserver codes do not run how can i successfully make the mutationobserver code run,['javascript'] +553210,javascript alert position not in center in chrome when i am using an javascript alert it is going on top of the browser not in center position in current version of chrome how can i control it and make it center with javascript in firefox and ieit is working just finemy current chrome version 300159966i want to position the alert box in exact center of the browser for all type of browsers and for all versions please helpany other simple idea on providing alert so that it could be centered would also be appreciable,['javascript'] +553211,font face not working in ie8 as expected i have used the following code to get a custom font in my website using the following code fontface fontfamilyportagoltc src urlfontportagoitc ttwoff formatwoff src urlfontportagoitc tteotiefix formatopentypethis works in chromeffie10ie9 but not in ie8 what am i doing wrong here please correct me if i am doing anything wrongnote i have googled and found few stackoverflow answers but nothing seems to solve my problemcss31 fontface encountered unknown error portagoitc ttwoffcss3114 fontface failed opentype embedding permission check permission must be installable portagoitc tfcss3114 fontface failed opentype embedding permission check permission must be installable portagoitc tf,['css'] +553278,what part of memory does a mutex lock pthreads all the documentation i have read on the pthreads mutex states only that a mutex prevents multiple threads from accessing shared memory but how do you specify in the program what exactly is that is it all the global variables in the program the variables being accessed between the locking and unlocking functions or everything i have found on pthreads including the examples is irritatingly vague,['c++'] +553283,restricting c template usage to pod types i have a c template class which only operates correctly if the templatized type is plain old data anything with a constructor that does anything will not work correctlyi would like to somehow get a compiletime or runtime warning when someone tries to do so anywaythis should generate errormyclastdstring athis should be finemyclassint bis there a trick to do this,['c++'] +553318,android studio does not launch could not find or load main class comintellijideamain being new in android devopmnet i have been using android studio for development but suddenly it does not work anymorethe program does not launch anymore and if i execute the studiobat from command prompt i get the following errorerror could not find or load main class comintellijideamaini have seen other posts about android studio not launching eg this and this but neither of them solve my problem i have set path variables for both java home and jdk home correctly to cprogram filesjavajdk170 07as i have mentioned android studio used to work and i do not have any idea why it has stopped working any clue,['android'] +553413,how do i add arbitrary javascript files from github in jsfiddle i know jsfiddle used to support arbitrary javascript files from github but not anymore may be github has changed its mime type of raw files what are the alternatives when the required js files is not in any cdn may be its less popular js repo,['javascript'] +553442,show to set position of popup i have to show popup i have done it but i am unable to set position of this popupi have to set popup at below of friends labelcode spinner spinner viewfindviewbyidridgroup spinner groupadaptor new arrayadaptergetactivity androidrlayoutsimple spinner dropdown item itemgrouplist spinnersetadapter groupadaptor spinnersetonitemselectedlistenerthisand on click i am calling method like spinnerperformclick,['android'] +553539,how do i render threejs in nodejs how do i render threejs code in nodejsi would like to export from blender then open the export through fs and render a scene with it,['javascript'] +553551,how to cleanly update a list of habtm associations in rails 4 i am trying to update a user record with the list of associated addresses connected through the has and belongs to many association the request body i am sending through javascript isid10namejohn smith address ids48this is what i am getting in the rails server logstarted put apiusers10 for 127001 at 20131003 163043 0200processing by apiuserscontrollerupdate as html parameters id10 namejohn smith address ids4 8 userid10 namejohn smiththe thing to notice above is the address ids array is not making it into the user hash according to the login the controller i am using strong parameters and updating the user like soattributes paramsrequireuserpermitid name address ids userupdate attributesattributesthe problem is the attributes do not contain the address ids at the point of update so the associated records are not getting updatedtemporary solutioni have worked around the issue manually assigning the address ids key to the attributes after they come back from the strong parameters check like soattributes paramsrequireuserpermitid name address ids if paramshas keyaddress ids attributesaddress ids paramsaddress ids enduserupdate attributesattributesthis works fine but does not seem to me this is how it is supposed to workwhy are the adderss ids not getting auto assigned how can this be implemented in a clear way,['ruby-on-rails'] +553577,why does not catching exception catch runtimeexception this is very odd to me runtimeexception inherits from exception which inherits from throwablecatchexception exc would not catch runtimeexception butcatchthrowable exc will catch runtimeexception i know runtimeexception is special in that it is unchecked but to my understanding that applies just to whether exceptions have to be declared not whether they are caught and even then i do not know why this logic would break on catching throwablethis is pretty relevant to me since i have a situation where runtimeexceptions can be thrown in a terminal operation i am not sure the name for this pattern but something like my class emailroller takes an array of callbacks the code looks like thisforcallback cb callbacks try cbcallitem catchexception exc loggererrorerror in callback exc so this is a case where something like an oome needs to fly through because if one of these callbacks consumes all machine memory that sure as heck is going to affect the running of the other ones but a nullpointerexception or an indexoutofboundsexception those will affect the callback but would not prevent the others from runningalso this is a bit of an enterprise design different programmers or teams can add callbacks to process the item but they should be isolated from each other this means as the programmer responsible for insulating these callbacks from each other i should not rely on them to make sure errors do not slip through catching exception should be about the right line but it is not because runtimeexception slips through so my more general question is whats a good pattern here just catchexception runtimeexception exc which i believe is a syntax error because of the inheritance,['java'] +553615,strange bug with resizing of ui elements in xcode 5 video is attached link to a video with bugi simply created a project in xcode then i added any ui element to a view then i tried to resize this item to left and to right no code interface builder was used onlyi have checked with some types of projects for ios and with uilabel and uibutton the result is the same when i try to resize the item from the left then it moves the parent viewviewcontroller instead,['ios'] +553623,mvc scaffolding does not support entity framework 6 or later just upgraded to entity framework 6 to take a look i am using mvc4but i recieve this message when trying to make a controller from a model and contextmvc scaffolding does not support entity framework 6 or later,['c#'] +553625,how to work with ruby duck typing i am learning ruby and i am having a major conceptual problem concerning typing allow me to detail why i do not understand with paradigmsay i am method chaining for concise code as you do in ruby i have to precisely know what the return type of each method call in the chain otherwise i cannot know what methods are available on the next link do i have to check the method documentation every time i am running into this constantly running tutorial exercises it seems i am stuck with a process of reference infer run fail fix repeat to get code running rather then knowing precisely what i am working with during coding this flies in the face of rubys promise of intuitivenesay i am using a third party library once again i need to know what types are allow to pass on the parameters otherwise i get a failure i can look at the code but there may or may not be any comments or declaration of what type the method is expecting i understand you code based on methods are available on an object not the type but then i have to be sure whatever i pass as a parameter has all the methods the library is expect so i still have to do type checking do i have to hope and pray everything is documented properly on an interface so i know if i am expected to give a string a hash a class etcif i look at the source of a method i can get a list of methods being called and infer the type expected but i have to perform analysisruby and duck typing design by contract impossiblethe thiscussions in the preceding stackoverflow question do not really answer anything other than there are processes you have to follow and those processes do not seem to be standard everyone has a different opinion on what process to follow and the language has zero enforcement method validation testdriven design documented api strict method naming conventions whats the standard and who dictates it what do i follow would these guidelines solve this concern ruby coding style guidelines is there editors that helpconceptually i do not get the advantage either you need to know what methods are needed for any method called so regardless you are typing when you code anything you just are not informing the language or anyone else explicitly unless you decide to document it then you are stuck doing all type checking at runtime instead of during coding i have done php and python programming and i do not understand it there either what am i missing or not understanding please help me understand this paradigm,['ruby'] +553660,size method for binary trees i just came across this code for finding size of a binary tree public int size returnsizeroot private int sizenode node if node null return0 else returnsizenodeleft 1 sizenoderight i am confused why is it so that there are two methods and one without argument i can guess that it is some good practice but not able to think of the reason,['java'] +553696,prevent or thismiss empty file warning in loadtxt my code goes through a number of files reading them into lists with the commanddata nploadtxtmyfile unpacktruesome of these files are empty i cannot control that and when that happens i get this warning printed on screenusrlocallibpython27thistpackagesnumpylibnpyiopy795 userwarning loadtxt empty input file path to filefiledat warningswarnloadtxt empty input file s fnamehow can i prevent this warning from showing,['python'] +553704,control keyboard input into javafx textfield i want to control the input into a javafx textfield so that i can allow only numeric input and so that if the max characters are exceeded then no change will be made to the textboxedit based on a recommendation in the comments i used the method suggested by the javafx project lead it works great to stop letters from being entered i just need it to also filter special characters i tried changing the filter to textmatchs09 but that did not allow backspace to be enterededit2 figured out a filter on special chars and length here is my final code thanks for the input fellashere is the textfield class i have createdimport javafxscenecontroltextfieldpublic class attributetextfield extends textfield public attributetextfield setminwidth25 setmaxwidth25 public void replacetextint start int end string text string oldvalue gettext if textmatchesaz textmatches superreplacetextstart end text if gettextlength 2 settextoldvalue public void replaceselectionstring text string oldvalue gettext if textmatchesaz textmatches superreplaceselectiontext if gettextlength 2 settextoldvalue note i have read what is the recommended way to make a numeric textfield in javafx this post and this solution does not work for me it only gets fired after the number has been entered meaning someone could type alphabetic text into the box and it would allow it until they moved focus away from the textfield also they can enter numbers larger than allowed but validation happens not on each keypress but instead after focus shift changed event,['java'] +553731,javascript anonymous function access to global variables after hours of search i have a problem with my code below in fact i am not very far from answer i think but i am still blockedai have an anonymous function called inside a loop and i want to access and refresh global variables but i tried with windowmyvariable with another function and nothing happenathis my code for var i 0 i shp fileslength i shapefile new shapefile shp shppolygonshp filesishp dbf shppolygonshp filesidbf functiondata polygon layeraddlayernew lgeojsondatageojsononeachfeature oneachfeature style polygonstyle polygon layeraddtomap consolelogpolygon layergetlayers is ok consolelogpolygon layergetlayers is empty so how i could transform this anonymous function in order to have something that i can access from my code whos following that thanks a lot and sorry for my english not very gooda,['javascript'] +553777,how to connect to wpa eap wifi on android with 43 api recently android added the ability to connect to eap wifi with api 18 jellybean 43 i have looked for a number of examples but cannot find any examples and i cannot get my code to connect everything appears to work as expected but making the actual connection does not seem to work here is what i am doinglogd wifi adding network via android enterprise config with ssid ssid wifienterpriseconfig enterpriseconfig new wifienterpriseconfig wificonfig new wificonfiguration wificonfigssid ssid enterpriseconfigsetidentityusername enterpriseconfigsetpasswordpassword enterpriseconfigseteapmethodwifienterpriseconfigeappeap wificonfigenterpriseconfig enterpriseconfig logiwifi my wifi wificonfigstatus networkid wfmaddnetworkwificonfig wfmenablenetworknetworkid true this initiates the connectionfor whatever reason the connection is not made it appears that everything else is set correctly if i have left anything out let me know and i will happily add it any help or direction would be greatly appreciated,"['java', 'android']" +553814,simpler way to set multiple array slots to one value i am coding in c and i have the following codeint array30array9 1array5 1array14 1array8 2array15 2array23 2array12 2is there a way to initialize the array similar to the followingint array30array9514 1array8152312 2note in the actual code there can be up to 30 slots that need to be set to one value,['c++'] +553817,ruby on rails could not find file jqueryuidatepicker okay this is driving me nuts i have been following the instructions to install a jquery datepicker here but i am getting hung up on this errorsprocketsfilenotfound in verificationsnewcould not find file jqueryuidatepicker in appassetsstylesheetsapplicationcss11heres applicationjs require jquery require jqueryuiall require jquery ujs require tree heres applicationcss require jqueryuidatepicker require self require tree and in gemfilegroup assets do gem jqueryuirailsendanyone see what i am missing,"['javascript', 'jquery', 'ruby-on-rails']" +553882,ios 7 custom tableview is under tabbar im trying port my app to ios7 but my custom tableviewcontroller is showing the last row cell under the tabbar im searching a lot for it but i dont find any solution can anyone help memy custom table view classthe error is shown in the blow screenshot only is showing a part of last product because im draging to up to show the hidden product under the tabbarthanks,"['ios', 'objective-c']" +553898,ios 7 hide status bar on certain view this is a rather unique question i have searched for hours and could not find the answer i want all uiviewcontrollers in my app to have the uistatusbar visible but on a certain uiviewcontroller when you tap a uibutton the following method calls the camera modalview controller i want to hide the status bar when the following method is calledboolstartcameracontrollerfromviewcontrolleruiviewcontrollercontroller usingdelegateid delegate i have tried changing the plist file with uiviewcontroller based status bar yes i only want the uistatusbar hidden when that modal view is pulled upi have also tried the following within the above methoduiapplication sharedapplication setstatusbarhiddenyes withanimationuistatusbaranimationnoneif self respondstoselectorselectorsetneedsstatusbarappearanceupdate uiapplication sharedapplication setstatusbarhiddenyes withanimationuistatusbaranimationnonenothing seems to work can anyone help,"['ios', 'objective-c']" +554037,wampserver only upgrade php version from 543 to 554 can i upgrade the php version under wampserver instead of wholebecause current latest version of wampserver gives 543 version but the latest version of php is 554 how can i upgrade itedit wampserver provides either 543 or older version what i am trying to do is download latest php version from phps official site and than copy that into the wampserver so that i can select toggle between newer and older versionthis is how wampserver control panel will look like after adding a version of phpi got my answer a type of handler is required to handle php 55 which is not built current handler supports 54 versions the handler is provided by ioncubethis is what i found ioncube for php55 is not yet released as of 13092013 they say they are waiting for php 55 to become stable and secure and hosting providers to adopt php 55 before they release their upgrade they comment that it can take a year or more for hosting companies to adopt new versions of php and this i guess is their schedulethanks thank you all for active commenting and help,['php'] +554038,why can an unnamed struct not be used as a trailing return type struct int a b fint x int y ok return x y auto gint x int y struct int a b error c2332 return x y int main auto and f1 2a okmy compiler is vc 2013 rcwhy is g wrong while f is okis this a bug of vc,['c++'] +554043,captured photo is stretched with avcapturesession sessionpreset avcapturesessionpresetphoto important if i use sessionsessionpreset avcapturesessionpresethigh my preview image is not stretched if i save the photo to the device uiimagewritetosavedphotosalbumimage nil nil nil the image is normal only in the preview it is stretchedi m using avfoundation to capture photo session avcapturesession alloc initsessionsessionpreset avcapturesessionpresethighcalayer viewlayer vimagepreviewlayernslogviewlayer viewlayeravcapturevideopreviewlayer capturevideopreviewlayer avcapturevideopreviewlayer alloc initwithsessionsessioncapturevideopreviewlayerframe vimagepreviewboundsvimagepreviewlayer addsublayercapturevideopreviewlayeravcapturedevice device avcapturedevice defaultdevicewithmediatypeavmediatypevideonserror error nilavcapturedeviceinput input avcapturedeviceinput deviceinputwithdevicedevice errorerrorif input handle the error appropriately nslogerror trying to open camera errorsession addinputinputstillimageoutput avcapturestillimageoutput alloc initnsdictionary outputsettings nsdictionary alloc initwithobjectsandkeys avvideocodecjpeg avvideocodeckey nilstillimageoutput setoutputsettingsoutputsettingssession addoutputstillimageoutputi set the sessionpreset to avcapturesessionpresetphotosessionsessionpreset avcapturesessionpresetphotomy capture methodvoidcapturenow avcaptureconnection videoconnection nil for avcaptureconnection connection in stillimageoutputconnections for avcaptureinputport port in connection inputports if port mediatype isequalavmediatypevideo videoconnection connection break if videoconnection break nslogabout to request a capture from stillimageoutput stillimageoutput capturestillimageasynchronouslyfromconnectionvideoconnection completionhandler cmsamplebufferref imagesamplebuffer nserror error cfdictionaryref exifattachments cmgetattachment imagesamplebuffer kcgimagepropertyexifdictionary null if exifattachments do something with the attachments nslogattachements exifattachments else nslogno attachments nsdata imagedata avcapturestillimageoutput jpegstillimagensdatarepresentationimagesamplebuffer uiimage image uiimage alloc initwithdataimagedata nslognsstringfromcgsizeimagesize self animateuptheimagewithimageimage where i add the captured photos preview void animateuptheimagewithimageuiimagetheimage uiview preview uiview alloc initwithframecgrectmake0 0 selfframesizewidth selfframesizeheight426 calayer previewlayer previewlayer avcapturevideopreviewlayer capturevideopreviewlayer avcapturevideopreviewlayer alloc initwithsessionsession capturevideopreviewlayerframe previewlayerframe previewlayer addsublayercapturevideopreviewlayer capturevideopreviewlayervideogravity avlayervideogravityresizeaspect self addsubviewpreviewand the result is my captured image is stretched,['ios'] +554120,hellojni for android studio i just got started with ndk and am struggling to get the hellojni sample running on android studio i got it working using eclipse but i would prefer to have it running on android studio i have poured through countless suggestions on how i should put the armeabi folder into a lib folder and pack that inside a jar msgadtdevnqobkd2gl 8z5ywavch4h4j but so far none of this has worked it is getting quite frustrating does anyone have a working hellojni sample that can be built and run from android studio and deployed on a device i just need a working ndk sample project in android studio any help is appreciated thanks guys,"['java', 'android']" +554148,collectionssort throws comparison method violates its general contract exception i am trying to sort a list object and i get this exception thrown for large lists only thoughsorting codelistfinalsentence sentencelist finalrepresentationgetsentencescollectionssortsentencelist exception thrown herefinalsentence class headerpublic class finalsentence implements comparablefinalsentencecompareto implementationoverridepublic int comparetofinalsentence o if this o return 0 if thisscore oscore return 1 if thisscore oscore return 1 return 0this is the exceptionexception in thread main javalangillegalargumentexception comparison method violates its general contractat javautilcomparabletimsortmergehiunknown sourceat javautilcomparabletimsortmergeatunknown sourceat javautilcomparabletimsortmergecollapseunknown sourceat javautilcomparabletimsortsortunknown sourceat javautilcomparabletimsortsortunknown sourceat javautilarrayssortunknown sourceat javautilcollectionssortunknown sourceat featurefinalrepresentationsummarizersummarizesummarizerjava30at driverdrivermaindriverjava114for a small list less than 50 elements it works for a large list it is supposed to work with those as well it throws this exceptionthe instance type of the list is arraylist not that it should matteri have no idea how to get to the bottom of this the list is full the elements are of the same type no polymorphism there and yet i get this weird exception for large listsany ideasthanks ahead,['java'] +554159,how to save an image to localstorage and thisplay it on the next page so basically i need to do as the title states upload a single image save it to localstorage then thisplay it on the next pagecurrently i have my html file uploadinput typefile iduploadbannerimage onchangereadurlthis which uses this function to thisplay the image on the pagefunction readurlinput documentgetelementbyidbannerimgstylethisplay block if inputfiles inputfiles0 var reader new filereader readeronload function e documentgetelementbyidbannerimgsrc etargetresult readerreadasdataurlinputfiles0 the image is thisplayed instantly on the page for the user to see they are then asked to fill out the rest of the form this part is working perfectlyonce the form is complete they then press a save button once this button is pressed i save all form inputs as localstorage strings i need a way to also save the image as a localstorage itemthe save button will also direct them to a new page this new page will thisplay the users data in a table with the image being at the topso plain and simple i need to save the image in localstorage once the save button is pressed and then loan the image on the next page from localstoragei found some solutions such as this fiddle and this although i am still extremely confused on how this works and i only really need a simple solution basically i just need to find the image via getelementbyid once the save button is pressed and then process and save the imageall help is greatly appreciated thanks,"['javascript', 'jquery', 'html']" +554175,can i place a children sprite below it is parent using zposition i am adding a sprite to a parent and it shows up on the screen however despite my zposition parameter the child is on top of it is parent i need to get it as defined in the zpositionit will be placed correctly if just adding the sprite to self but not as a child to hjnodethe current result is that d5node the child is placed above the hjnode parentthe zposition works among the added childs when adding additional childswhen reading the programming guide i get the feeling unless i missed something that this may be a problem would someone know if this is possibleidinitwithsizecgsizesize if self super initwithsizesize selfuserinteractionenabled yes skspritenode hjnode skspritenode spritenodewithimagenamedhj hjnodeposition cgpointmake150 300 hjnodezposition 100 hjnodename hjnode self addchildhjnode skspritenode d5node skspritenode spritenodewithimagenamedd5 d5nodeposition cgpointmake170 320 d5nodeposition cgpointmake10 20 d5nodezposition 1 d5nodename d5node hjnode addchildd5nodereturn self,['objective-c'] +554196,nsurlsession background download resume over network failure after reading the apple documentation about the background download with the new ios7 api nsurlsession i am a bit thisappointed i was sure that apple was managing the pauseresume over the network availability in the background or provide an option to do so but noaso reading the documentation this is what weve gotwhen any task completes the nsurlsession object calls the delegateas urlsessiontaskdidcompletewitherror method with either an error object or nil if the task completed successfully if the task is a resumable download task the nserror objectas userinfo dictionary contains a value for the nsurlsessiondownloadtaskresumedata key your app should use reachability apis to determine when to retry and should then call downloadtaskwithresumedata or downloadtaskwithresumedatacompletionhandler to create a new download task to continue that download go to step 3 creating and resuming task objectsso far i understand the solution but my question is what architecture is the best to handle the loss of the network and resume downloading in the backgroundon my side i am using reachability and each time the network is available i resume all tasks referenced over a nsarray when creating and suspends them when network is lost this works well in foreground but for the background i need help on the following pointsif my app has no connectivity in foreground if i go to the background without connectivity all my tasks remains suspended and would not came back if network is availablealosing network in background stop all my downloadstasksscenarioin foreground i start downloading my tasksi go to background and after 10s switch to aireplan modeall my tasks got an error so in the method urlsessiontaskdidcompletewitherror i resume them usingdownloadtaskwithresumedata or if i cannot because some have notenough resume data i am creating a new task without resumeing it except if network is back at that timethen i put the wifi upas i am still in background i cannot trigger a resume when network is back without launching the applicationahow do i address these points have i missed something,['ios'] +554227,run release build of ios app on development device when i build my ipad app for running on my development ipad it only builds the debug version i need to see how fast the real release version is how do i do this i am used to visual studios debugrelease builds so this runtestprofileanalyzearchive stuff isa bit confusing i see schemes are related to this but is not there a simple switch i want to test debugrelease version of my app on my device,['ios'] +554228,android studio signing issue after upgrade i recently upgraded my android studio from 026 to 0211 the build generate signed apk wizard which was opening up in 026 is not coming up here instead it shows a dialog like for gradlebased projects the signing configuration should be specified in the gradle build scriptssee the gradle user guide for more infoi even added the below lines in buildgradle filesigningconfigs debug storefile filedebugkeystore myconfig storefile fileotherkeystore storepassword android keyalias androiddebugkey keypassword android buildtypes foo debuggable true jnidebugbuild true signingconfig signingconfigsmyconfig could anyone please tell me what could be the issueor also could you please let me know how to downgrade my studiothanks,['android'] +554281,how to fire formclosing for ownerless forms on red x exit i have a small app with several forms each of which saves their pane layout during the formclosing eventsome forms need to remain on screen when the main form is minimized so they are opened ownerless with formshow as opposed to formshowthishowever this affects formclosing behaviour when the user exits using the red x the formclosing event does not get fired for the ownerless formsapplicationexit does work as needed but cancelling the formclosing event in the main form and calling applicationexit instead causes formclosing to be called twice on everything other than the ownerless formsi could probably iterate openforms in the formclosing event of the main form and save anything that needs saving but that seems a bit of a hack is there a way to make x behave in the same way as applicationexitthe following code demonstrates the problempublic partial class form1 form public form1 initializecomponent thistext main form ownedform new form text owned ownedformformclosing s e systemdiagnosticsdebugwritelineformclosing owned form ownedformshowthis form ownerlessform new form text ownerless ownerlessformformclosing s e systemdiagnosticsdebugwritelineformclosing ownerless form ownerlessformshow thisformclosing s e systemdiagnosticsdebugwritelineformclosing main form fix below does not work as needed if eclosereason closereasonuserclosing ecancel true applicationexit,['c#'] +554354,rotate video with mp4parser i need to rotate a video to adjust some of my needs i will explain the details on the following listi am creating a vine like app i have to record video segments and then merge all the parts into just one file i am doing this without issue on an android app using mp4 parser library with last version 10rc26 using the example provided on their website herethe append video example works fine if all the videos have the same orientation but i thiscovered some issues recording video from the front camera so the quick solution was to set the video orientation recording on 270 the bad part on this solution is that the segment with this orientation appear with the wrong orientation on the merged videomy possible solution to this is to rotate the video to apply what i need in different situations but i am not having a working example with my code searching the internet i found solutions like this one here the problem with this code is that is not compatible with the last version it gives an compilation error i tried too to understand the logic of the library but i am not having results for example i experimented using the setmatrix instruction on the movie object but it simply do not workpublic static void mergevideoint segmentnumber throws exception logdpm merge process started movie inmovies new moviesegmentnumber long matrix new longsegmentnumber for int i 1 i segmentnumber i file file new filegetcompletefilepathi if fileexists fileinputstream fis new fileinputstreamgetcompletefilepathi set rotation i tried to experiment with this instruction but is not working inmovies i1setmatrixmatrixrotate 90 inmovies i1 moviecreatorbuildfisgetchannel logdpm video i merged fisclose listtrack videotracks new linkedlisttrack listtrack audiotracks new linkedlisttrack for movie m inmovies for track t mgettracks if tgethandlerequalssoun audiotracksaddt if tgethandlerequalsvide videotracksaddt movie result new movie if audiotrackssize 0 resultaddtracknew appendtrackaudiotrackstoarraynew trackaudiotrackssize if videotrackssize 0 resultaddtracknew appendtrackvideotrackstoarraynew trackvideotrackssize container out new defaultmp4builderbuildresult outgetmovieboxgetmovieheaderboxsetmatrixmatrixrotate 180 set orientation default merged video have wrong orientation create a media file name string filename getcompletemergedvideofilepath filechannel fc new randomaccessfilestringformatfilename rwgetchannel outwritecontainerfc fcclose do not leave until the file is on his place file file new file filename do if fileexists logdpm result file not ready while fileexists logdpm merge process finishedhave someone rotated video with the very last version of mp4 parser english is not my native language so i apologize any grammar error,['android'] +554374,css percent height when parent has minmax height i know that when you use a percent height on an element the percentage is the percent of it is parent let us say that you want a child to be 40 of it is parent the parent has a max and a min height assigned but it does not have an explicit height assigned for examplediv idcontainer div idone div idtwodiv divdivcsscontainer height 500px background yellowone background red minheight100px maxheight 50 padding 10pxtwo background blue height 40div two will not appear when you change the css of his parent div one from this maxheight50 to this height50 div two will appear because it knows what the height of his parent is because it is explicitly defined my question is there a way to make div two appear while using minmaxheight and not heighthere is a fiddle,"['html', 'css']" +554457,css style for first in a i am trying to set all the td elements of my tr to be rightaligned except the first one which i want to be leftaligned i tried thisstyletd textalign right tdfirstchild textalign left stylethat makes all cells be rightaligned if i swap the order of those two rows then all cells are leftaligned highly confused according to w3schools the firstchild selector is used to select the specified selector only if it is the first child of its parentbut that does not seem to be happening for me,"['html', 'css']" +554474,difference between throws in method signature and throw statements in java i am trying to make it clear of the difference between throws in method signature and throw statements in javathrows in method signature is as followingpublic void amethod throws ioexception filereader f new filereadernotexisttxtthrow statements is as followingpublic void bmethod throw new ioexceptionfrom my understanding a throws in method signature is a notification that the method may throw such an exception throw statement is what actually throw a created object under according circumstances in that sense throws in method signature should always appear if there exist a throw statement in the methodhowever the following code does not seem doing so the code is from the library my question is why it is happening am i understanding the concepts wrongthis piece of code is a copy from javautillinkedlist author josh bloch returns the first element in this list return the first element in this list throws nosuchelementexception if this list is empty public e getfirst final nodee f first if f null throw new nosuchelementexception return fitemupdate on the answerupdate 1 is above code the same as the following as far as i know it is the same as without throwspublic e getfirst throws nosuchelementexception final nodee f first if f null throw new nosuchelementexception return fitemupdate 2 for checked exception do i need to have throws in the signature yes has to throw checked exception otherwise compile errorpublic string abc throws ioexception throw new ioexception,['java'] +554476,how to replace one fragment with another fragment using listener in first fragment i am using two fragments in my activityinitially i will add one fragment to the activitythen using listener in first fragment i want replace it with second fragment i tried as per my understanding but it is not replacing it is showing both fragments overlappedhere is my code mainactivitypublic class mainactivity extends activity fragment fragment one button one override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main onebutton findviewbyidridbutton1 onesetonclicklistenernew viewonclicklistener override public void onclickview arg0 todo autogenerated method stub fragmentmanager mangetfragmentmanager fragmenttransaction tranmanbegintransaction fragment onenew fragment1 tranaddridfragment container fragment onetran tranaddtobackstacknull trancommit fragment codepublic class fragment1 extends fragment button add fragment2 fragment two override public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate todo autogenerated method stub return superoncreateviewinflater container savedinstancestate view viewinflaterinflaterlayoutfragment 1 containerfalse addbutton viewfindviewbyidridbutton1 fragment two new fragment2 addsetonclicklistenernew viewonclicklistener override public void onclickview v todo autogenerated method stub fragmenttransaction tgetactivitygetfragmentmanagerbegintransaction tremove new fragment1 treplaceridfragment1 fragment twotaddtobackstacknull tcommit taddtobackstacknull return view,['android'] +554529,connect by clause in regex substr i cant get the understanding of this statement not even after googling around pv no list 23344556select thistinct regexp substr pv no list 1 level no list from dual connect by regexp substr pv no list 1 level is not null,['sql'] +554637,measuring time does not confirm linkedlist advantage i am reading the differrences between arraylist and linkedlist pointed out in when to use linkedlist over arraylist i developed a small example applcation to test a major advantage of linkedlist but the results i obtain do not confirm that linkedlist outweighs arraylist in the performance of the operationlistiteratoradde elementhere is my codepublic static void mainstring args int number 10 long starttime1 systemcurrenttimemillis filinkedlistnumber long stoptime1 systemcurrenttimemillis long starttime2 systemcurrenttimemillis fillarraylistnumber long stoptime2 systemcurrenttimemillis systemoutprintln linkedlist needed stoptime1 starttime1 systemoutprintln arraylist needed stoptime2 starttime2 public static void filinkedlistint number linkedlistinteger list new linkedlistinteger listiteratorinteger it listlistiterator int i 0 whileinumber itaddi systemoutprintlnlinkedlist size listsize public static void fillarraylistint number arraylistinteger list new arraylistinteger listiteratorinteger it listlistiterator int i 0 whileinumber itaddi systemoutprintlnarraylist size listsize the measurement givesnumber 10 10 50 10 50arraylist 7 17 60 77 170linkedlist 7 21 89 838 4127i notice that the increase of elements impairs significantly the performance of linkedlist while arraylist presents a considerably better behaviour have i understood something false,['java'] +554638,using counter in python to build histogram i saw on another question that i could use counter to count the number of occurrences in a set of strings so if i have abacaa i get countera3b1c1 but now how can i use that information to build a histogram for example,['python'] +554661,how to create an equalizer for audio player there are many music players like even html5 audio player but how can i add an equalizer to them by equalizer i mean this imageany idea how to add it to a music playerthanks in advance,"['javascript', 'jquery']" +554668,what is the point of pointers to arrays so i was reading about pointers and came across the concept of pointers to arrays the thing is that a pointer to an array does not really seem useful at all since instead of using a pointer to have an offset to access an array element i could just get the element directly however i feel as if i am missing the reason why these can be usefulso in short what is the point of pointers to arrays how and why should they be used and do they have any practical applicationsedit i meant this in the context of normalsimple arrays such asint array5edit as keith pointed out i am specifically asking about pointers to arrays for example char ptr42 which is a pointer to a 42element array of char,['c'] +554678,php 55 installer i seem to be having a problem finding the php 55 msi file i have looked carefully on the php site and downloaded what i thought was the msi file but it was just the dlls i have found installers for multiple items wamp but i just need to upgrade my php from 536 to 55 not install apache etcso does anyone have a link to the 55 msithe version i need is non thread safe 86 ie for windows server 2008greg,['php'] +554708,read mobileprovisioning profile with objectivec so i am trying to open a mobileprovisioning profile to read whats inside this is what i am doingnsstring path pathurl pathnsdata data nsfilemanager defaultmanager contentsatpathpathof course i get the data read but i am not finding the way of getting of get this data into something useful an nsdictionary an nsstring or whateveri have already tried nsstring newstr nsstring alloc initwithdatadata encodingnsutf8stringencodingany idea i am sure this is an encoding issue but i cannot solve it after reading and googling for some time i think the provisioning profile is saved as hexadecimal but i do not know how to read that from objectivec i have found this but there was not an useful answer how to convert ndata populated with hex values to nsstringthanks,['objective-c'] +554712,how to save a dictionary to a file in python i have problem with changing a dict value and saving the dict to a text file the format must be same i only want to change the member phone fieldmy text file is the following formatmemberidmember namemember emailmember phoneand i split the text file withmdictfor line in file xlinesplit ax0 bx1 cx2 dx3 ebcd mdictaewhen i try change the member phone stored in d the value has changed not flow by the key def changemdictbcde ainputid if a in mdict d strinputphone mdictabcd else printnotand how to save the dict to a text file with same format,['python'] +554714,seo vs html tags i am building a project using twitter bootstrap in the documentation it is statedbutton tagsuse the button classes on an a button or input elementcrossbrowser renderingas a best practice we highly recommend using the button element whenever possible to ensure matching crossbrowser renderingis this a good practice seowise speaking,['html'] +554748,adding an image within a circle object in d3 javascript my goal is to add an image into an existing circle with d3 the circle will render and is interactive with mouseover method but only when i use fill color and not something more sophisticated like appendimage gappendcircle attrclass logo attrcx 700 attrcy 300 attrr 10 attrfill black this code works ok attrstroke white thisplays small black dot attrstrokewidth 025 onmouseover function when i use stylefill red here it works d3selectthis appendsvgimage attrxlinkhref assetsimageslogojpeg attrcx 700 attrcy 300 attrheight 10 attrwidth 10 the image does not show after i mouse over using ruby on rails app where my image logojpeg is stored in the assetsimages directory any help for getting my logo to show within the circle thanks,"['javascript', 'css', 'ruby-on-rails']" +554792,writing java tests with data providers i am currently doing my first java project and like to fully tdd it i am using junit for writing the tests apparently junit does not provide support for data providers which makes it rather annoying to test the same method with 20 different versions of an argument what is the most popularstandard testing tool for java that does support data providers i came across testng but have no idea how popular that one is or how it compares to alternativesif there is a way to get this behaviour is a nice way using junit then that might also work,['java'] +554794,is it possible to debug terminated due to memory error in a certain consistent point when my app is running i consistently get the xcode error message terminated due to memory errori cannot find the code causing the error but i can tell what code is near the error using breakpointsthe error is caused directly after returning a certain cell in my implemenation of the uitableviewcell tableviewuitableview tableview cellforrowatindexpathnsindexpath indexpathuitableviewdatasource delegate method i can confirm that it is returning a valid uitableviewcell but i think that explaining and posting that entire method would be a waste of your time however i suspect it might be caused by a rapid massive allocation of memoryit definitely says terminated due to memory error not memory pressurei would like to know what is message really means also is there any way to debug this message no crash report is generatedi am using arc and ios 7,"['ios', 'objective-c']" +554824,title color of uibutton would not change on highlightedselected but background color will this has been a very odd processi have an iboutletcollection of uibuttons i loop through the collection and create them like this the thisplayhourbuttons is called from viewwillappear voidthisplayhourbuttons counter nsuinteger b 0 set attributes uifont btnfont uifont fontwithnamemetricsemibold size130 uicolor btntextcolor uicolor colorwithred1472550f green1472550f blue1472550f alpha10 nsnumber btntracking nsnumber numberwithfloat025 nsmutableparagraphstyle btnstyle nsmutableparagraphstyle alloc init btnstyle setlinespacing20 nsdictionary btnattrs nsdictionary dictionarywithobjectsandkeys btnfont nsfontattributename btntextcolor nsforegroundcolorattributename btntracking nskernattributename nil create the buttons for uibutton hourbutton in hourbuttons i am using the attributed string for something else later in development that i have not got to yet i simplified the string for this examples sake nsstring btntitletext nsstring stringwithformatbutton lu unsigned longb nsmutableattributedstring attributedtext nsmutableattributedstring alloc initwithstringbtntitletext attributesbtnattrs attributedtext addattributensparagraphstyleattributename valuebtnstyle rangensmakerange0 btntitletextlength calayer btnlayer hourbutton layer btnlayer setmaskstoboundsyes btnlayer setcornerradius190f hourbutton settagb hourbutton setcontentedgeinsetsuiedgeinsetsmake50 10 00 00 hourbutton setattributedtitleattributedtext forstateuicontrolstatenormal hourbutton setcontenthorizontalalignmentuicontrolcontenthorizontalalignmentcenter hourbutton setcontentverticalalignmentuicontrolcontentverticalalignmentcenter hourbuttontitlelabellinebreakmode nslinebreakbywordwrapping hourbutton addtargetself actionselectorshowhour forcontroleventsuicontroleventtouchupinside b when one of the buttons is clicked per the action showhour is called ibactionshowhouridsender selfhourbuttons enumerateobjectsusingblockid obj nsuinteger idx bool stop uibutton button uibutton obj if button sender buttonenabled this is applied i know because i tested it with redcolor button setbackgroundcoloruicolor clearcolor does not change stays the gray set initially button settitlecoloruicolor redcolor forstateuicontrolstatenormal else this is applied button setbackgroundcoloruicolor colorwithred1692550f green2342550f blue2552550f alpha10 this is not button settitlecoloruicolor whitecolor forstateuicontrolstatenormal uicontrolstateselected uicontrolstatehighlighted thisplayhour uses the tag to change labels images etc self thisplayhourlong intsender tagi tried all sorts of crazy things to get the uiimage to be in a selected state but nothing worked this enumerateobjects deal is the only thing that has worked that is why i say this has been an odd process i guess buttons do not stay active indefinitelyanyways my question is there a certain reason why the title color is not changing just the background i suspect it has something to do with the background not being set initially but i could not explain whythanksupdatedper timothy mooses answer below is the updated code ibactionshowhouridsender selfhourbuttons enumerateobjectsusingblockid obj nsuinteger idx bool stop uibutton button uibutton obj grab the mutable string from the button and make a mutable copy nsmutableattributedstring attributedtext button attributedtitleforstateuicontrolstatenormal mutablecopy shared attribute styles uifont btnfont uifont fontwithnamemetricsemibold size140 nsnumber btntracking nsnumber numberwithfloat025 nsmutableparagraphstyle btnstyle nsmutableparagraphstyle alloc init btnstyle setlinespacing20 since we cannot set a color directly on a attributed string we have to make a new attributed string if button sender buttonenabled return to the default color uicolor btntextcolor uicolor colorwithred1472550f green1472550f blue1472550f alpha10 set up attributes nsdictionary btnattrs nsdictionary dictionarywithobjectsandkeys btnfont nsfontattributename btntextcolor nsforegroundcolorattributename btntracking nskernattributename nil reapply the default color for the one button that was changed to white attributedtext setattributesbtnattrs rangensmakerange0 attributedtextlength add lineheight attributedtext addattributensparagraphstyleattributename valuebtnstyle rangensmakerange0 attributedtextlength reset default attributes button setbackgroundcoloruicolor clearcolor button setattributedtitleattributedtext forstateuicontrolstatenormal else our new white color for the active button uicolor btntextcolor uicolor whitecolor set up attributes nsdictionary btnattrs nsdictionary dictionarywithobjectsandkeys btnfont nsfontattributename btntextcolor nsforegroundcolorattributename btntracking nskernattributename nil apply our new white color attributedtext setattributesbtnattrs rangensmakerange0 attributedtextlength add lineheight attributedtext addattributensparagraphstyleattributename valuebtnstyle rangensmakerange0 attributedtextlength add new attributes for active button button setbackgroundcoloruicolor colorwithred1692550f green2342550f blue2552550f alpha10 button setattributedtitleattributedtext forstateuicontrolstatenormal self thisplayhourlong intsender tag,"['ios', 'objective-c']" +554842,flasksqlalchemy model has no attribute foreign keys i have 3 models created with flasksqlalchemy user role userroleuserpyclass role activerecord dbmodel tablename roles schema id dbcolumn dbinteger primary key true name dbcolumn dbstring 24 unique true description dbcolumn dbstring 90 users dbrelationship user secondary userrole backref dbbackref roles rolepyclass user dbmodel activerecord tablename users schema id dbcolumn dbinteger primary key true email dbcolumn dbstring 90 unique true password dbcolumn dbstring 64 relations roles dbrelationship role secondary userrole backref dbbackref users user rolepyclass userrole activerecord dbmodel tablename user roles schema user id dbcolumn dbinteger dbforeignkey usersid primary key true role id dbcolumn dbinteger dbforeignkey rolesid primary key true if i try in the console to get all users via userqueryall i get attributeerror nonetype object has no attribute all and if i try again i get another error saying sqlalchemyexcinvalidrequesterror one or more mappers failed to initialize cannot proceed with initialization of other mappers original exception was type object userrole has no attribute foreign keyscan anyone shed a light on what is it exactly that i am doing wrong i think i had this code running ok a few months ago but i updated sqlalchemy flask and flasksqlalchemy recently and it stopped it is just a side project,['python'] +554916,developing an android lock screen application i want to develop my own lock screen for android that will replace the default android lock screen i do not have any idea how to startis there any tutorial about it or an example i can download and open in my eclipse and run thanks a lot,['android'] +554923,how to get my android fingerprint certifica in android studio i am new android developer i am using mac os x lion and android studio 2011 i will map application so i need sha1 certifica how to get fingerprint mac os and android studiothanxsorry bad english,['android'] +554963,example images for code and markup qas when preparing an mcvesscce that involves images it is useful to have direct access to images the types of images that would cover most questions are small images in multiple colors or shapes animated gifs withwithout transparency jpegs that are pairs of pictures can be used in image transitions tile sets sprite sheetsare there any small under 30kb onsite license royalty free images we can hotlink to for these types of examples,"['java', 'javascript', 'css']" +555018,pyside segfault when using qitemselectionmodel with qlistview same exact problem as this connecting qtableview selectionchanged signal produces segfault with pyqti have a qlistview and i want to call a function when an item is selectedselfserver list qtguiqlistviewselfmain widgetselfserver list model qtguiqstandarditemmodelselfserver listsetmodelselfserver list modelselfserver listselectionmodelselectionchangedconnectselfserver changedbut when it reaches the last line where i am using the selection model the app crashes not with a traceback but with a appname has stopped working from windows i am pretty sure that is a segfaultbut when i use pyqt4 it works fine i am using pyside because it is lgplyes i am on the latest versions of everything pyside 121 python 275 qt 485can anyone help me with this,['python'] +555023,using sticky kit jquery plugin but cannot figure out how to use the offset top option has anyone had any experience using the excellent sticky kit jquery plugin i cannot figure out how to use the offset top option the documentation for the options is a bit vague the example shown is belowsticky itemstick in parentoptionsi guess i have to write something like thissticky itemstick in parentoffset topbut how do i specify the number of pixels i want to offset sticky item byany help would be greatly appreciated,['jquery'] +555038,what is the best way to check if an attribute exists and is set i have a common view that lists two different models the only difference is that when setting the link to action one of the models has a link attribute and the other does not i want to check if the link attribute exists and if it does check if it is set i have the following which works but i was wondering if there was a better wayli if elementhas attributelink elementlink link to elementtitle elementlink else link to elementtitle element,"['ruby-on-rails', 'ruby']" +555043,when to use htmlbeginform vs ajaxbeginform it is amazing after all the posts i have checked that there is still no definitive explanation in my mind in what situation should the subject data be usedi know for the htmlbeginform it will perform a postback post data to a controller method and either redirect to another method or return the same view to the useri know for the ajaxbeginform you must correct me if i am wrong specify an updatetargetid where the resulting posted data from the controller method will go into something like a partial view within a div tag on the same page as the form i know that you cannot redirect to another action method after the form is submittedunder both these conditions you can still have the user input another round of data to submit and process via the controllerso unless you need to redirect to another action method why wouldnt you use the ajaxbeginform all of the timethe only thing i can imagine is that the htmlbeginform method would be probably best suited for data entry input over and over again whereas the ajaxbeginform method would be used to thisplay a result to the user depending on what information they input into the form almost like a onetime deal btw i know i have contradicted myself with the use of saying to use the ajaxbeginform most of the timecan somebody please give me a relatively simple explanation when each of these methods should be used,['jquery'] +555060,what is an imageobserver when you draw an image it requires an image observer from what i understand so far a bufferedimage is an image observer but my question is what defines an image observer and what does it do i am quite confused,['java'] +555075,css files showing up with type textplain i am attempting to serve my static blog powered by jekyll on my ubuntu server but the css does not apply and i keep getting the issueresource interpreted as stylesheet but transferred with mime type textplain in the source code however i explicitly list that these files are textcss any ideas on how to solve this,['css'] +555097,how can you create a glow around a sprite via skeffectnode i have a skspritenode that i would like to have a blue glow around it is edges for highlighting purposes i am guessing that i would need to make my sprite a child of a skeffectnode and then createapply a filter of some sort update i have investigated this quite a it with the chosen answers approach and thiscovered that skeffectnode has a sizeable hit on performance even if you have it set to shouldrasterize and no filter defined my conclusion is that if your game requires more than 10 moving objects at one time they cannot involve a skeffectnode even if rasterizedmy solution will likely involve prerendered glow imagesanimations as skeffectnode is not going to cut it for my requirementsif someone has insight as to anything i am missing i would appreciate hearing whatever you knowi am accepting an answer because it does achieve what i asked for but wanted to add these notes to anyone looking to go this route so you can be aware of some of the issues with using skeffectnode,"['ios', 'iphone']" +555153,why cannot i install any gems on my mac i tried doing gem install for just about any gem and i have been getting errors i think i need to reset and or update something on my computer but not sure whathere is some of the command line code errorserror could not find a valid gem multi json 0 here is why unable to download data from ssl connect returned1 errno0 statesslv3 read server certificate b certificate verify failed specs48gzerror could not find a valid gem cowsay 0 here is why unable to download data from ssl connect returned1 errno0 statesslv3 read server certificate b certificate verify failed specs48gzsudo gem install rubygemsupdatepassworderror could not find a valid gem rubygemsupdate 0 here is why unable to download data from ssl connect returned1 errno0 statesslv3 read server certificate b certificate verify failed specs48gzdoes anyone know what i need to do to fix this i got a new computer and was wondering if i need to set up the user differently or something,"['ruby-on-rails', 'ruby']" +555175,oncreate being called on activity a in up navigation so i have an activity a and an activity b i want activity a to be able to navigate to activity b with the press of a button that works but when i use the up navigationthe home button in the action bar to navigate back to activity a oncreate is called again and the old information that the user typed in is lost i have seen oncreate always called if navigating back with intent but they used fragments and i am hoping not to have to redesign the entire app to use fragments is there any way i can stop oncreate from being called every time activity a becomes active again,['android'] +555208,sending an object through a socket in java i have 2 java netbeans projects one is the server other is the client i have a message class that i have created which i wanna pass to the server and back the other way to the client after modification done at the server i have included the class message in both projects i use objectoutputstream and objectinputstream to pass the object the connection between the server and the client is ok and the object passes through but at the server when i read the object from the objectinputstream using readobject method i type cast it to the message class but an classnotfoundexception is thrown at the server it cant find the message class how can i resolve thiscode for the clientpublic void startclient try create the socket socket clientsocket new sockethost port create the input output streams to the server objectoutputstream outtoserver new objectoutputstreamclientsocketgetoutputstream objectinputstream infromserver new objectinputstreamclientsocketgetinputstream read modify todo here create the message object to send linkedlistmessage msglist new linkedlist message msg new message msgsetmessagekasun msgsetindex1 msgsetaverage55f msglistpushmsg send the message object to the server outtoserverwriteobjectmsglist retrive the message object from server linkedlistmessage infromserverlist new linkedlist message msgfrmserver null infromserverlist linkedlistmessageinfromserverreadobject msgfrmserver infromserverlistpop print out the recived message systemoutprintlnmessage msgfrmservergetmessage systemoutprintlnindex msgfrmservergetindex systemoutprintlnaverage msgfrmservergetaverage clientsocketclose catch exception e systemerrprintlnclient error egetmessage systemerrprintlnlocalized egetlocalizedmessage systemerrprintlnstack trace egetstacktrace code for the serverpublic void startserver try serversocket welcomesocket new serversocketport while true create the client socket socket clientsocket welcomesocketaccept systemoutprintlnsocket extablished create input and output streams to client objectoutputstream outtoclient new objectoutputstreamclientsocketgetoutputstream objectinputstream infromclient new objectinputstreamclientsocketgetinputstream read modify todo here create message object and retrive information linkedlistmessage inlist new linkedlist message inmsg null inlist linkedlistmessageinfromclientreadobject inmsg inlistpop modify the message object inmsgsetmessageinmsggetmessagetouppercase inmsgsetindex5 inmsgsetaverage105f send the modified message object back outtoclientwriteobjectinmsg catch exception e systemerrprintlnserver error egetmessage systemerrprintlnlocalized egetlocalizedmessage systemerrprintlnstack trace egetstacktrace systemerrprintlnto string etostring the exception thrown at the serverjavalangclassnotfoundexception ruslonlineexaminationsystemclientutilitymessagewould i have to use java rmi is there a solution for this without using rmi,['java'] +555230,tap gesture not recognized on uiimageview i added two uiimageviews one on another subview uiview imageview1imageview2 in the first view the top uiimageview is hiddenimageview2 and in the second view the bottom imageview is hiddenimageview1allocating tap gestureuitapgesturerecognizer singletap uitapgesturerecognizer alloc initwithtargetself actionselectoronetapuitapgesturerecognizer singletap1 uitapgesturerecognizer alloc initwithtargetself actionselectoronetapset user interaction for both uiimageview to yessingletap setnumberoftapsrequired1singletap1 setnumberoftapsrequired1 adding gesture to uiimageview add tap gesture recognizer and selector respectively imageview1 addgesturerecognizersingletapimageview2 addgesturerecognizersingletap1but my taps are not recognizedcan any one tell me where the mistake is,['objective-c'] +555398,implicit instantiation of undefined template stdbasic string stdallocator in the project i have been working on we have to send cocoa notifications from c subprojects to the main project above it to do this we construct a map to act as a keyvalue store for the userinfo dictionary of the notificationin one of the projects the following code compiles just finestdmapstdstring stdstring userinfo new stdmapstdstring stdstringchar buffer255sprintfbuffer i intvalue1userinfoinsertstdpairstdstring stdstringintvalue1 stdstringbuffersprintfbuffer i intvalue2userinfoinsertstdpairstdstring stdstringintvalue2 stdstringbufferifcondition userinfoinsertstdpairstdstring stdstringconditionalvalue truepostcocoanotificationnotificationname userinfohowever when this is copied into an identical file in another subproject the compiler throws the following on the userinfoinsert callsimplicit instantiation of undefined template stdbasic stringchar stdchar traitschar stdallocatorchar and it cannot find the function for postcocoanotificationno matching function for call to postcocoanotificationadditionally it throws the following errors in system headers applicationsxcodeappcontentsdeveloperplatformsiphoneosplatformdevelopersdksiphoneos61sdkusrincludec421bitsstl pairh7311 implicit instantiation of undefined template stdbasic stringchar stdchar traitschar stdallocatorchar applicationsxcodeappcontentsdeveloperplatformsiphoneosplatformdevelopersdksiphoneos61sdkusrincludec421bitsstl pairh7411 implicit instantiation of undefined template stdbasic stringchar stdchar traitschar stdallocatorchar applicationsxcodeappcontentsdeveloperplatformsiphoneosplatformdevelopersdksiphoneos61sdkusrincludec421bitsstl pairh7311 implicit instantiation of undefined template stdbasic stringchar stdchar traitschar stdallocatorchar applicationsxcodeappcontentsdeveloperplatformsiphoneosplatformdevelopersdksiphoneos61sdkusrincludec421bitsstl treeh132413 cannot initialize a parameter of type link type aka rb tree nodestdpairconst stdbasic stringchar stdchar traitschar stdallocatorchar stdbasic stringchar stdchar traitschar stdallocatorchar with an rvalue of type const link type aka const rb tree nodestdpairconst stdbasic stringchar stdchar traitschar stdallocatorchar stdbasic stringchar stdchar traitschar stdallocatorchar i have no idea what i have done to cause such chaos especially when the code runs perfectly fine in another subproject successfully sending notifications any insight to the problem would be very welcome,"['c++', 'ios']" +555448,hiding tabbar showing black bar in ios7 i am using this code to hide the tabbar selftabbarcontrollertabbarhiddenyesi am hiding tabbarcontroller in my projectbut it showing black bar in bottom of the view in ios7when i go back to the same view it is looking goodany help will be appreciated,['ios'] +555566,socketio packets get lost between this and reconnect i am using socketio for connecting a smartphone in a webframe to a server and sending a few messages around a few short strings per minute nothing big since smartphones often tend to have an unsteady connection socketio is forced to reconnect every now and then it does this automatically and the messages i want it to send after it noticed that the connection is currently unavailable are buffered and sent as a bundle once the connection is reestablished so basically it is all going well with socketiobut when i send a message right before socketio notices that the connection is gone the message is lost it can not be transmitted but it does not get buffered by socketio either i am quite content with socketio but this problem is bugging me since i do not send many messages but i really need those i do send to be sent reliably while the connection is established all messages get transmitted perfectly so i do not need to check for that only the second between the connection loss and socketio noticing it is the critical moment where i face packet lossi have been thinking about mimicking tcp behaviour with sequence numbers and acks but it feels a bit like shooting ants with a rocket launcher so my question is does anyone have a lightweight solution for this problem or even encountered it himself i do not even ask for explicit code i can do that myself but a concept or something like that to get rid of this specific problem would be greatthanks in advance,['javascript'] +555603,how to select multiple rows by multicolumn primary key in mysql i have a table with a multicolumn primary key citystatedate and many more columns of data i am looking to get the latest data for each citystate how do i do that cleanlyefficiently right now i can do this by doing a first query to get the list of all the rows i am trying to fetch followed by a second query with a massive where clause select state city maxdate from data group by city state state city maxdate ca san francisco 20130901 ca los angeles 20130801 ny new york 20131001 many rows select from data where state ca and city san francisco and date20130901 or state ca and city los angeles and date20130801 or state ny and city new york and date20131001 or this is really ugly and inefficient and if the first query returns a lot of rows my second query might be too long clearly if i have a singlecolumn primary key i could use a subselect with in but that is not really possible here any suggestionsupdate i tried bills suggestion with a subselect but it is not using any keys and is taking forever if i restrict the subselect to only return 5 rows it returns in 064s if i let it return all 73 citystate combinations it takes a very long time query still runningexplain select from data where city state date in select state city maxdate from data group by city state id select type table type possible keys key key len ref rows extra 1 primary data all null null null null 13342 using where 2 dependent subquery data index null primary 57 null 8058 using index,['mysql'] +555622,define a list like list i need a two column list likelistintstring mylist new listintstringit saysusing the generic type systemcollectiongenericlistt requires 1 type arguments,"['c#', '.net']" +555666,css even odd for every other odd div in class i have divs in a horizontal row all in the same class like this1 2 3 4 5 6 7 8 9 10what i want is to apply css to every other odd row so159 etci have triedmyclassnthchildn4 andmyclassnthchildoddmyclassnthchildoddbut cannot figure it out,['css'] +555717,mailto link not working within a frame chrome over https i have a mailto link on a page it works as expected when the page is loaded by itselfhowever when the page is loaded via a frameset in chrome nothing happens with the developer tools loaded the error blocked the page at ran insecure content from mailto is thisplayedhow can i fixworkaround this,['html'] +555750,how to get the values for a series of checkboxes in laravel 4 controller if checked i would like to get the values for a series of checkboxes i have set up in a laravel 4 form here is the code in the view setting up the checkboxesforeach friends as friendinput tabindex1 typecheckbox namefriend idfriend valuefriendendforeachin my controller i would like to get the values for the checked boxes and put them in an array i am not exactly sure how to do this but i assume it is something likearrayforeachfriend as xif issetinputgetfriend array inputgetfriend endforeachcould you provide me with a solution to do this thank you editthis is what i have in the controllerpublic function describe favorite fan fanfindauthuserid fanfavorite venue inputgetvenue fanfavorite experience inputgetexperience friends checked inputgetfriend print rfriends checked ifis arrayfriends checked fanexperience friends 5 fansave return redirecttofanshome it is not going through the if loop how do i see the output of the print r to see whats in the friends checked variable,['php'] +555754,operator in java consider this codelong val 0forint i 0 i 2 val val isystemoutprintlnvalwhy is val 3 in the end i would have calculated like thisval i0 0 i 2 true0 0 i0 1 val 11 1 end of for loop val2 1 i 2 true2 1 i2 2 val 24 2 end of for loop val5 2 i 2 falseoutput 5but it is 3 i do not understand why the increment val i is not done the second time when i 1 and getting preincremented to i 2,['java'] +555771,back button strangely thisappearing in uinavigationcontroller but keeps working under ios7 i have been experiencing an issue where the back button item will not show up if it has been set with a specific background imageint imagesize 21 replace with your image widthuibarbuttonitem appearance setbackbuttontitlepositionadjustmentuioffsetmake400f 0 forbarmetricsuibarmetricsdefaultuiimage barbackbtnimg uiimage imagenamedbackarrowdarkpng resizableimagewithcapinsetsuiedgeinsetsmake0 imagesize 0 0uibarbuttonitem appearance setbackbuttonbackgroundimagebarbackbtnimg forstateuicontrolstatenormal barmetricsuibarmetricsdefaultupon doing this any viewcontroller that i push in the navigation controller will have no back button item appearing even though pressing where it should be will make it appear and any subsequent pushes of this view controller will have the button present on the screenthis issue is only appearing under ios7 everything works perfectly under ios6changing the back button completely with a leftbarbuttonitem thisables the back swipe so that is not an optionany idea what i am doing wrongthanks much for your consideration,"['ios', 'objective-c']" +555830,how to configure web deploy publishing feature on iis so developer can publish i control a server running iis 8 on windows server 2012 i want to publish a few basic aspnet websites with the publish option in visual studio 2012 there are no goodcurrent microsoft articles on the server configuration steps1 what exactly do i need to do on the server i do not see any web deploy role option under the various iis roles i have read of some people downloading and installing web deploy 30 from microsoft but that file is one year old and it seems strange that i would have to download another file to use a promoted iis file deployment option if you are using iis7 or iis75 instead of iis8 like me please feel free to reply what you do but let me know what version you are using2 is the authentication process encrypted for example ftp would send passwords in plain text ftp over ssl does not but setting up even a selfissued ssl cert is annoying just to get secure authentication so what about web deploy is it safe or no3 must i open port 8172 on the servers firewall microsofts documentation says i might need to 4 on the visual studio side it wants an account for authentication is this a windows account on the server should i then right click the iis website folder on the server and add this user there or is there some other preferred way of mapping users to websites if so what rights are requiredplease answer any or all of the above but please focus on the server side configuration and not the client visual studio please do not suggest ftp as i am truly wanting to try web deploy i am adding an iis 75 tag too since some of the answers may be the same as for iis 8,['asp.net'] +555902,exc bad access using ccglview when home pressed i use ccglview in cocos2d20 to work with cocoa touchbut my application will crash when i press home button the error occured in ccglview swapbuffers methodif context presentrenderbuffergl renderbufferexc bad accessthe stack is5eaglcontext presentrenderbuffereaglecontextobjc selectorrunsigned int6ccglview swapbuffers7ccdirectorios drawscene8ccdirectorthisplaylink mainloopby the way i do pause the director at delegate method voidapplicationdidenterbackgrounduiapplication application ccdirector shareddirector pauseany ideas thanks,"['iphone', 'ios']" +555940,python check that key is defined in dictionary how to check that the key is defined in dictionary in pythonaif a contains key b ab ab1else ab1,['python'] +555980,configure gson to use several date formats i now that when i want to tell gson how to parse dates i dogson gson new gsonbuildersetdateformatymmdd hhmmcreatebut i have also fields with only the date and others with only the time and i want both to be stored as date objects how can i do this,['android'] +555983,in python get the output of system command as a string in python i can run some system command using os or subprocess the problem is that i cannot get the output as a string for example tmp ossystemlsfile1 file2 tmp0i have an older version of subprocess that does not have the function check out and i would prefer a solution that does not require to update that module since my code will run on a server i do not have full admin rights this problem seems trivial yet i could not find a trivial solution,['python'] +555995,android emulator freezing os x v109 mavericks with haxm i just updated to os x v109 mavericks and now whenever i start up any of my emulators as soon as the emulator starts up my entire computer freezes with a spinning progress indicator in the center of the screen not a beachball the progress indicator is similar to what you see when shutting down but the screen has not faded to greyi have triedturning off gpu accelerationuninstalling and reinstalling the latest intel haxmrecreating my avdsupdated my android sdktoolsthe only thing that works is to uninstall intel haxm not use hardware accelerationi am guessing there is a bug with mavericks and haxm similar to what motivated the release for 106 of haxm for os x v108 mountain lionthe following crash report is indicating a kernel panic generated by haxmanonymous uuid 2c84f70ffe5451e74fbe6e601ed377aftue oct 8 214939 2013paniccpu 3 nmipi for spinlock acquisition timeout spinlock 0xf802deca4d8 spinlock owner 0xf80409f4cf0 current thread 0xf80409f4cf0 spinlock owner cpu 0x3rax 0xf80409f4cf0 rbx 0xf802ded4c40 rcx 0xf80409f4cf0 rdx 0x070rsp 0xf8115bb9c30 rbp 0xf8115bb9c70 rsi 0x0792aac9d6 rdi 0xf802deca4d8r8 0x010 r9 0x0269 r10 0x0 r11 0x0246r12 0x0 r13 0xf7faf6b3d92 r14 0xf802deca4d8 r15 0xf802d830040rfl 0x06 rip 0xf802d8d0470 cs 0x08 ss 0x010backtrace cpu 3 frame return address0xf8115bb9aa0 0xf802d8e21f10xf8115bb9ad0 0xf802d8db75f0xf8115bb9b20 0xf802d8f39300xf8115bb9c70 0xf802dbeda5f0xf8115bb9c90 0xf802d82f7410xf8115bb9dc0 0xf802d8300180xf8115bb9e30 0xf7faf6a7f860xf8115bb9ed0 0xf802d8e351e0xf8115bb9f10 0xf802d8e2e3e0xf8115bb9f50 0xf802d8e21c60xf8115bb9f80 0xf802d8db75f0xf8115bb9fd0 0xf802d8f37c90xf815a62bd00 0xf802d9fd8bd0xf815a62bd80 0xf802d9f37870xf815a62bdc0 0xf802dbf0eeb0xf815a62beb0 0xf802dbf0b880xf815a62bf50 0xf802dc3de230xf815a62bfb0 0xf802d8f3e06 kernel extensions in backtrace comintelkextintelhaxm10649ce9c16944731fea8564bdd043a302d0xf7faf6a60xf7faf6c2fbsd process name corresponding to current thread syslogdmac os version13a598kernel versiondarwin kernel version 1300 thu sep 19 27 pdt 2013 rootxnu24221726release x86 64kernel uuid 1d9369e3d0a531b68d16bffb390393kernel slide 0x02d60kernel text base 0xf802d80system model name macbookpro81 mac94245b3640c91c81system uptime in nanoseconds 5867020237last loaded kext at 5616463499 comintelkextintelhaxm 106 addr 0xf7faf6a60 size 118784loaded kextscomintelkextintelhaxm 106comrazerzonerazerapo 10084comcybericsmoothmouse 7comappledriverappletymcedriver 102d2comappledriveragpm 1001411comappleiokitiobluetoothserialmanager 420f6comappledriverapplemikeyhiddriver 124comappledriverapplehdahardwareconfigdriver 252fc2comappledriverapplehda 252fc2comappledriveraudioauuc 160comappleiokitiouserethernet 100d1comappledont steal mac os x 700comappledriverapplehwaccess 1comappledriverappleupstreamuserclient 3513comappledriverapplepolicycontrol 3412comappleiokitiobluetoothusbdfu 420f6comappleiokitbroadcombluetoothhostcontrollerusbtransport 420f6comappledriverappleintelhd30graphics 818comappledriverapplethunderboltip 1010comappledriverapplesmclmu 204d1comappledriverapplemikeydriver 252fc2comappledriverapplesmcpdrc 100comappledriveracpi smc platformplugin 100comappledriverapplelpc 170comappledriverappleintelsnbgraphicsfb 818comappledriverapplemuxcontrol 3412comappledriverapplebacklight 17035comappledriverapplemccscontrol 12comappledriversmcmotionsensor 304d1comappledriverappleusbtcbuttons 2402comappledriverappleusbtckeyeventdriver 2402comappledriverappleusbtckeyboard 2402comappledriverappleircontroller 3257comappledriverapplefilesystemdriver 301comappleapplefscompressionapplefscompressiontypedataless 100d1comappleapplefscompressionapplefscompressiontypezlib 100d1comapplebootcache 35comappledriverxsanfilter 404comappledriverapplesdxc 140comappleiokitapplebcm5701ethernet 369b9comappleiokitioahciblockstorage 240comappledriverappleusbhub 65044comappledriverapplefwohci 499comappledriverairportbrcm4331 7002022comappledriverappleahciport 295comappledriverappleusbehci 65041comappledriverappleusbuhci 65040comappledriverapplesmartbatterymanager 16100comappledriverappleacpibuttons 20comappledriverapplertc 20comappledriverapplehpet 18comappledriverapplesmbios 20comappledriverappleacpiec 20comappledriverappleapic 17comappledriverappleintelcpupowermanagementclient 21600comapplenkeapplicationfirewall 153comapplesecurityquarantine 3comappledriverappleintelcpupowermanagement 21600comappleiokitioscsiarchitecturemodelfamily 360comappleapplegraphicsdevicecontrol 3412comappleiokitioserialfamily 1007comappledriverdspfunclib 252fc2comappleveclibkext 100comappleiokitiofirewireip 225comappleiokitioaudiofamily 194fc11comapplekextosvkerndsplib 114comappleiokitiosurface 91comappleiokitiobluetoothfamily 420f6comappledriverapplehdacontroller 252fc2comappleiokitiohdafamily 252fc2comappleiokitiobluetoothhostcontrollerusbtransport 420f6comappledriverapplethunderboltedmsink 121comappledriverapplethunderboltdpoutadapter 250comappledriverapplesmbuspci 1012d1comappledriverioplatformpluginlegacy 100comappledriverioplatformpluginfamily 551d27comappledriverapplegraphicscontrol 3412comappledriverapplebacklightexpert 104comappleiokitiondrvsupport 236comappledriverapplesmbuscontroller 1011d1comappleiokitiographicsfamily 236comappledriverapplesmc 316d1comappledriverapplethunderboltdpinadapter 250comappledriverapplethunderboltdpadapterfamily 250comappledriverapplethunderboltpcidownadapter 140comappledriverappleusbmultitouch 2406comappleiokitiousbhiddriver 65044comappledriverappleusbmergenub 65040comappledriverappleusbcomposite 65040comappledriverapplethunderboltnhi 192comappleiokitiothunderboltfamily 285comappleiokitioethernetavbcontroller 103b3comappledrivermdnsoffloaduserclient 101b4comappleiokitiousbuserclient 65044comappleiokitiofirewirefamily 455comappleiokitio80211family 60034comappleiokitionetworkingfamily 32comappleiokitioahcifamily 260comappleiokitiousbfamily 65044comappledriverappleefinvram 20comappledriverappleefiruntime 20comappleiokitiohidfamily 200comappleiokitiosmbusfamily 11comapplesecuritysandbox 27810comapplekextapplematch 100d1comapplesecuritytmsafetynet 7comappledriverapplekeystore 2comappledriverthiskimages 3711comappleiokitiostoragefamily 19comappleiokitioreportfamily 21comappledriverapplefdekeystore 2830comappledriverappleacpiplatform 20comappleiokitiopcifamily 28comappleiokitioacpifamily 14comapplekecpthread 1comapplekeccorecrypto 10paniccpu 1 caller 0xf802dbeda5f spinlock acquisition timed out lock0xf802deca4d8 lock owner thread0xf80409f4cf0 current thread 0xf8040364450 lock owner active on cpu 0x3 current owner 0xf80409f4cf0sourcecachexnuxnu2422172osfmki386locks i386c365backtrace cpu 1 frame return address0xf815a5db810 0xf802d822f690xf815a5db890 0xf802dbeda5f0xf815a5db8b0 0xf802d82f7410xf815a5db9e0 0xf802d8300180xf815a5dba50 0xf7faf6a7f860xf815a5dbaf0 0xf802d8e351e0xf815a5dbb30 0xf802d8e3c780xf815a5dbb70 0xf7faf6b01e00xf815a5dbba0 0xf7faf6aa2e00xf815a5dbbe0 0xf7faf6a6e3c0xf815a5dbc00 0xf802dc583160xf815a5dbc60 0xf802dc560510xf815a5dbcb0 0xf802dc5497e0xf815a5dbd10 0xf802dc5465c0xf815a5dbd80 0xf802dc670740xf815a5dbe10 0xf802d85c5900xf815a5dbe50 0xf802d826bb10xf815a5dbe80 0xf802d8139b50xf815a5dbef0 0xf802d81e0030xf815a5dbf70 0xf802d8c921d0xf815a5dbfb0 0xf802d8f3e26 kernel extensions in backtrace comintelkextintelhaxm10649ce9c16944731fea8564bdd043a302d0xf7faf6a60xf7faf6c2fbsd process name corresponding to current thread kextdsystem profilemodel macbookpro81 bootrom mbp810047b27 2 processors intel core i5 24 ghz 8 gb smc 168f99graphics intel hd graphics 30 intel hd graphics 30 builtin 512 mbmemory module bank 0dimm0 4 gb ddr3 13 mhz 0x0198 0x393955353432382d3034302e413031472020memory module bank 1dimm0 4 gb ddr3 13 mhz 0x0198 0x393955353432382d3034302e413031472020airport spairport wireless card type airport extreme 0x14e4 0xd6 broadcom bcm43xx 10 51069810022bluetooth version 420f6 12982 3 services 15 devices 1 incoming serial portsnetwork service wifi airport en1serial ata device oczvertex3 12003 gbserial ata device toshiba mk5065gsxf 50011 gbusb device facetime hd camera builtinusb device hubusb device apple internal keyboard trackpadusb device brcm2070 hubusb device bluetooth usb host controllerusb device hubusb device ir receiverthunderbolt bus macbook pro apple inc 221model macbookpro81 bootrom mbp810047b27 2 processors intel core i5 24 ghz 8 gb smc 168f99graphics intel hd graphics 30 intel hd graphics 30 builtin 512 mbmemory module bank 0dimm0 4 gb ddr3 13 mhz 0x0198 0x393955353432382d3034302e413031472020memory module bank 1dimm0 4 gb ddr3 13 mhz 0x0198 0x393955353432382d3034302e413031472020airport spairport wireless card type airport extreme 0x14e4 0xd6 broadcom bcm43xx 10 51069810022bluetooth version 420f6 12982 3 services 15 devices 1 incoming serial portsnetwork service wifi airport en1serial ata device oczvertex3 12003 gbserial ata device toshiba mk5065gsxf 50011 gbusb device facetime hd camera builtinusb device hubusb device apple internal keyboard trackpadusb device brcm2070 hubusb device bluetooth usb host controllerusb device hubusb device ir receiverthunderbolt bus macbook pro apple inc 221,['android'] +556002,how to avoid refreshing of cells on when calling notifydatasetchanged for pinterestlikeadapterview backgroundi am using the pinterestlikeadapterview library to show some images from the internet which is like a gridview but with different height for each cellthe problemsince i use this library to show images from the internet it is crucial that when calling notifydatasetchanged would not cause a mess on the viewsfor some reason calling this function would call the getview method with different positions for the views for example even though i did not scroll at all and call notifydatasetchanged or addall in case it is an arrayadapter for position 0 it will take what was the view of position 8 for position 1 it will take the view of position 7 and so onthis makes the whole grid to refresh its images and so it ruins the uxusually in both gridview and listview the way to overcome refreshing is to put the position that was used for the view inside the viewholder and if they are equal it means that they still match for example getview inflate a new view if needed avoid refreshing view in case it is still the same position ifpositionholderposition return rootview holderpositionposition update the view according to its data however here they reuse other views in a different order so this trick would not work herebecause of this issue not only i get refreshes of almost all of the visible views but since i use thiskcachelru library it crashes since it tries to put 2 identical inputsteam data into the same key using 2 threads the questionwhat can i dois this a known bug in the librarymaybe i am using a bad way to overcome refreshesfor now i use memory cache to at least get items that were cached before but that is more like a cure than a vaccine,['android'] +556015,spring mvc having multiple modelattribute in form handling action the contexti have a simple association between two entities category and email ntom i am trying to create web interface for browsing and managing them to browse the category and to add emails into that category i use controller wrapped with requestmapping with category id uuid so all controller actions are always taking place in context of category specified with pathi use modelattribute to preload context category for entire controller scopethe problemthis approach worked well for listing and for thisplaying the forms however it fails on form submission after debugging a little i found out that form data overrides my category modelattribute parameterin my code in method save the category is not really the model attribute loaded with addcategory method but is populated with form data email model is also populated and that is correcti am looking for the solution that will allow me to bind form data only to specific modelattributei have read in spring mvc documentation that order of arguments matters but i ordered them accordingly to examples and still it does not work like expectedthe codehere is my controllercontrollerrequestmappingemailscategoryidpublic class emailscontroller modelattributecategory public category addcategorypathvariable uuid categoryid return thiscategoryservicegetcategorycategoryid initbinder public void initbinderwebdatabinder binder binderregistercustomeditorsetclass categories new categoriesseteditorthiscategoryservice requestmappingvalue create method requestmethodget public string createformmodelattribute category category model model here everything works as there is just a single modelattribute return emailsform requestmappingvalue save method requestmethodpost public string save modelattribute valid email email bindingresult result model model modelattributecategory category category saving entity etc here problem is that response is bound both to email and category model attributes and overrides category loaded in addcategory method return stringformatredirectemailss categorygetidtostring just in case here is also the form codeformform actionpagecontextrequestcontextpathemailscategoryidsave methodpost modelattributeemail formhidden pathid fieldset label foremailnamespringmessage codeemailformlabelname textemail addresslabel forminput pathname idemailname requiredrequired formerrors pathname cssclasserror label foremailrealnamespringmessage codeemailformlabelrealname textrecipient thisplay namelabel forminput pathrealname idemailrealname formerrors pathrealname cssclasserror label foremailisactivespringmessage codeemailformlabelisactive textactivation statuslabel formcheckbox pathactive idemailisactive formerrors pathactive cssclasserror formcheckboxes pathcategories elementdiv itemscategories itemvalueid itemlabelname formerrors pathcategories cssclasserror button typesubmitspringmessage code commonformsubmit textsavebutton fieldsetformformnote i do not want multiple modelattributes to come from post just want to thistinguish somehow form model from previously generated attributes,['java'] +556036,clickonce installation fails to download i had made a clickonce deployemnt to my application set the installation folder and publishing folder the same that is a network share and then it work perfect for my development machinethen when i went to on client machine opened the network share and i tried to install the application using that setup file i got tht message like belowand in details iam getting the below message latform version infowindows 61760165536 win32ntcommon language runtime 4030319586systemdeploymentdll 40303191 rtmrel0303190100clrdll 4030319586 rtmldr0303195800dfdlldll 40303191 rtmrel0303190100dfshimdll 40311060 main0311060sources deployment url fileitdeptprojectmycutorderlastcutorderfreshapplication deployment provider url httpitdeptcutorderfreshcutorderfreshapplicationerror summary below is a summary of the errors details of these errors are listed later in the log activation of itdeptprojectmycutorderlastcutorderfreshapplication resulted in exception following failure messages were detected downloading httpitdeptcutorderfreshcutorderfreshapplication did not succeed the remote server returned an error 404 not foundcomponent store transaction failure summary no transaction error was detectedwarnings there were no warnings during this operationoperation progress status 08102013 140325 activation of itdeptprojectmycutorderlastcutorderfreshapplication has startederror details following errors were detected during this operation 08102013 140330 systemdeploymentapplicationdeploymentdownloadexception unknown subtype downloading httpitdeptcutorderfreshcutorderfreshapplication did not succeed source systemdeployment stack trace at systemdeploymentapplicationsystemnetdownloaderdownloadsinglefiledownloadqueueitem next at systemdeploymentapplicationsystemnetdownloaderdownloadallfiles at systemdeploymentapplicationfiledownloaderdownloadsubscriptionstate substate at systemdeploymentapplicationdownloadmanagerdownloadmanifestasrawfileuri sourceuri string targetpath idownloadnotification notification downloadoptions options serverinformation serverinformation at systemdeploymentapplicationdownloadmanagerdownloadmanifesturi sourceuri string targetpath idownloadnotification notification downloadoptions options manifesttype manifesttype serverinformation serverinformation at systemdeploymentapplicationdownloadmanagerdownloaddeploymentmanifestdirectsubscriptionstore substore uri sourceuri tempfile tempfile idownloadnotification notification downloadoptions options serverinformation serverinformation at systemdeploymentapplicationdownloadmanagerfollowdeploymentproviderurisubscriptionstore substore assemblymanifest deployment uri sourceuri tempfile tempfile idownloadnotification notification downloadoptions options at systemdeploymentapplicationdownloadmanagerdownloaddeploymentmanifestbypasubscriptionstore substore uri sourceuri tempfile tempfile subscriptionstate substate idownloadnotification notification downloadoptions options at systemdeploymentapplicationapplicationactivatorperformdeploymentactivationuri activationuri boolean isshortcut string textualsubid string deploymentproviderurlfromextension browsersettings browsersettings string errorpageurl at systemdeploymentapplicationapplicationactivatoractivatedeploymentworkerobject state inner exception systemnetwebexception the remote server returned an error 404 not found source system stack trace at systemnethttpwebrequestgetresponse at systemdeploymentapplicationsystemnetdownloaderdownloadsinglefiledownloadqueueitem nextcomponent store transaction details no transaction information is availablecan anyone suggest what was the issue as iam using clickonce for the first time,"['c#', '.net']" +556058,how to change icon on google map marker i want to use my customize icon on google map and added icon url on the code but it is still not reflecting on the map can anyone suggest what i am missing here why icon is not changing after adding the icon url script typetextjavascript srcscriptscript typetextjavascriptvar markers title this is title lat 37801578 lng 145060508 icon description vikash rathee strong this is test descriptionstrong bra hrefpin code by citya scriptscript typetextjavascript windowonload function var mapoptions center new googlemapslatlngmarkers0lat markers0lng zoom 10 flat true styles stylers hue 4bd6bf gamma 158 maptypeid googlemapsmaptypeidroadmap var infowindow new googlemapsinfowindow var map new googlemapsmapdocumentgetelementbyiddvmap mapoptions for i 0 i markerslength i var data markersi var mylatlng new googlemapslatlngdatalat datalng var marker new googlemapsmarker position mylatlng map map title datatitle function marker data googlemapseventaddlistenermarker click function e infowindowsetcontentdatadescription infowindowopenmap marker marker data scriptdiv iddvmap stylewidth 100 height 100div,['javascript'] +556068,how to manipulate styles of directive in angularjs i am writing a component using angularjs and angularjs directivesi am doing something like thisvar myapp angularmodulemyapp myappdirectivemytag function return some logic here i want to be able to change style of my component using css something like thismytag classmyclassmytagbesides this i want to be able to manipulate all elements style inside mycomponent html markup inside of mytagdo you have any advice or useful examples how to manipulate the style properties of custom tags using angularjs,"['javascript', 'html', 'css']" +556092,maven issue artifactdescriptorexception i am trying the spring rest example exaplained here the project source is here herei unzipped the file and renamed top folder to myproject and imported it into eclipse as an existing maven project but observed that lot of compilation issues due to missing spring jars i guess this is because maven is not able to import these jars when i check the pomxml i see eclipse is complaining with below errorsartifactdescriptorexception failed to read artifact descriptor for comfasterxmljacksoncorejacksondatabindjar2 artifactresolutionexception failure to transfer comfasterxmljacksoncorejacksondatabindpom2 from was cached in the local repository resolution will not be reattempted until the update interval of central has elapsed or updates are forced original error could not transfer artifact comfasterxmljacksoncorejacksondatabindpom2 fromto central connection timed out to andartifactdescriptorexception failed to read artifact descriptor for comfasterxmljacksoncorejacksondatabindjar2 artifactresolutionexception failure to transfer comfasterxmljacksoncorejacksondatabindpom2 from was cached in the local repository resolution will not be reattempted until the update interval of central has elapsed or updates are forced original error could not transfer artifact comfasterxmljacksoncorejacksondatabindpom2 fromto central connection timed out to i am new to maven so struggling here please help me how to fix itthank you,['java'] +556116,javascript exception thrown in parent window occurs in child window i came across a problem that made me confused we all know that a couple of browsers windowtabs which have the same origin can share javascript resources so i made a parent window open a child window via windowopen the child window calls a global function in parent window via windowopenerfunctionname take a look at two snippets belowparenthtmldoctype htmlhtmlhead titletitleheadbody h1parenth1bodyscript typetextjavascriptfunction sayhichild consolelogbefore throwing an error throw new errorsome errorwindowopenchildhtmlscripthtmlchildhtmldoctype htmlhtmlhead titletitleheadbody h1childh1bodyscript typetextjavascriptwindowopenersayhiwindowscripthtmlthe problem is you can find the consolelog result in parenthtml window but that exception thrown in parent window will weirdly occur in childhtml window it makes me confused i need that exception in parent window because of bdd test how can i make it happen sorry for my poor english feel free to correct my grammar mistakesupdatei have found a solution to this question using html5 feature postmessage but i am still curious why it happen what makes the exception escape from parent window to child window any inspiration is appreciated,"['javascript', 'html']" +556117,how does wait notify work at the jvm level wait and notify seem like messages that are passed between threads if this is true there must be queues for buffering these messages if so then there must be atomic operations for adding messages to and removing message from the queue also there must be a helper thread for each java thread that listens for these messageswould be great to hear your thoughts,['java'] +556200,sublime text 3 hints as in netbeans is there any extension that provide hints autocomplete in sublime text 3 as it in netbeansnot just php functions but all object methods attributes and so on basicly it is usefull when you use oop frameworks etc,['php'] +556217,viewport argument value devicewidth for key width is invalid and has been ignored note that i am getting this error in javascriptviewport argument value devicewidth for key width is invalid and has been ignored note that is not a separator in viewport values the list should be commaseparatedhow do i fix this,"['javascript', 'html', 'css']" +556284,converting between time zones with noda time i am currently trying to ensure that our legacy backend can support resolving date times based on the users current time zone or more specifically offset our servers are in eastern standard time and most of our date times originate there however for users that are in other time zones a conversion to their time zone or in this case offset is needed when retrieving those date times also date times coming from the user will have to be converted to eastern standard time before persistence on the server given that the front end we are developing is webbased i am able to retrieve the users offset in minutes and pass that value into my service layer within the header i looked at noda time and think it is a great api it did force me to think about time in a more refined matter but i am still not 100 sure that i have properly used it correctly here are the methods that i wrote for the conversions described above i have tested them and they seem to work given the scenario above does this look like a proper use of the library am i thinking about date times properlypublic static datetime converttoutcfromeasterntimezonedatetime easterndatetime nodatimedatetimezone easterntimezone nodatimedatetimezoneproviderstzdbgetzoneornullamericanew york zonelocalmappingresolver customresolver resolverscreatemappingresolverresolversreturnlater resolversreturnstartofintervalafter var easternlocaldatetime localdatetimefromdatetimeeasterndatetime var easternzoneddatetime easterntimezoneresolvelocaleasternlocaldatetime customresolver return easternzoneddatetimetodatetimeutcpublic static datetime converttoeasterntimezonefromutcdatetime utcdatetime nodatimedatetimezone easterntimezone nodatimedatetimezoneproviderstzdbgetzoneornullamericanew york nodatimedatetimezone utctimezone nodatimedatetimezoneproviderstzdbgetzoneornullutc zonelocalmappingresolver customresolver resolverscreatemappingresolverresolversreturnlater resolversreturnstartofintervalafter var utclocal localdatetimefromdatetimeutcdatetime var utczoneddatetime utctimezoneresolvelocalutclocal customresolver var easternzoneddatetime utczoneddatetimetoinstantinzoneeasterntimezone return easternzoneddatetimetodatetimeunspecifiedpublic static datetime converttoutcdatetime datetime int offsetinminutes localdatetime localdatetime localdatetimefromdatetimedatetime var converteddatetime localdatetimeplusminutesoffsetinminutestodatetimeunspecified return converteddatetimepublic static datetime convertfromutcdatetime datetime int offsetinminutes localdatetime localdatetime localdatetimefromdatetimedatetime var converteddatetime localdatetimeplusminutesoffsetinminutestodatetimeunspecified return converteddatetimethe idea here is that time zone matters when i am resolving between utc time and the time zone in the database when i am resolving between the client time and utc time then offset matters in the future we can persist utc time and this will be easier currently this solution is a stop gapthe idea is that we are going to go fromclient utc offset utc eastern time databasedatabase eastern time utc utc offset clientto eventuallyclient utc offset utc databasedatabase utc utc offset client,['c#'] +556395,whats the difference between androidlinespacingextra and androidlinespacingmultiplier i am adding line spacing in my textview which spans multiple lineswhats the difference between androidlinespacingextra and androidlinespacingmultiplier linespacingextra with 2dp worked fine for me but i was wondering what the multiplier does instead,['android'] +556447,assigning double to const int vs int to const int i am trying to understand constant reference in c and i stumbled across this problemwhen i assign double to a const int and then change the value of the referencing double the value of my int reference stays constant double i 10 const int ref i i 20 cout i i endl i 20 cout ref ref endl ref 10whereas while assigning int the value gets changed int i 10 const int ref i i 20 cout i i endl i 20 cout ref ref endl ref 20what is the reason for this behaviour my guess is that when assigning double the implicit conversion to int creates a new object and its reference is then being assigned however i cannot find it written down anywhere,['c++'] +556458,proper way to load mongodb hash associated array mapping when not using annotations with weird accessors i am doing this to map non annotation mapping of my document but it is not catching it up i know it is old code but does someone know how to map it correctly thanksassociated pr and also related to this topicdoctrineusermdioomwa7f4phpabstract class mongotest extends basemongotest inheritdoc protected function getmetadatadriverimpl rootdir realpath dir if false rootdir false is dirrootdirsrcpayum throw new runtimeexceptioncannot guess payum root dir driver new mappingdriverchain xmldriver new xmldriver new symfonyfilelocator array rootdirsrcpayumpaypalexpresscheckoutnvpbridgedoctrineresourcesmapping payumpaypalexpresscheckoutnvpbridgedoctrinedocument rootdirexamplespayumpaypalexpresscheckoutnvpexamplesresourcesmapping payumpaypalexpresscheckoutnvpexamplesdocument mongodbxml mongodbxml driveradriverxmldriver payumpaypalexpresscheckoutnvpexamplesdocument driveradriverxmldriver payumpaypalexpresscheckoutnvpbridgedoctrinedocument return driveri get errors of 2 tests failing because there is no persistence of the values properties of paymentdetail document under examples folderhere is the mapping of the paymentdetailsand the mapping for the superclassit seems the issue is because of weird settergetter of basemodel which is extended by paymentdetailsprotected paymentrequest n amt array public function getpaymentrequestamtn null return thisgetpaymentrequest n amt n public function setpaymentrequestamtn value thissetpaymentrequest n amt value n that above is from an intermediate base class and here below is from the base class param string property param bool n param bool m return mixed protected function getproperty n false m false currentvalue thisproperty if false n false m if null n null m return currentvalue if array key existsn currentvalue array key existsmcurrentvaluen return currentvaluenm if null n return currentvalue if array key existsn currentvalue return currentvaluen,['php'] +556474,transparency between swtawt image conversions i have created a dialog in which a user can browse for an image and then see a preview of the image drawn on a canvas the image is scaled so that its aspect ratio is maintained while fitting in the box i used the method of resizing found in this answer which involves converting an image from swt to awt performing the resize converting back from awt to swt and finally drawing it on the canvas since this process is very costly in terms of time and processing power i elect to skip the resizing step if the image is exactly the correct size and thus does not need to be transformed in any waythe issue comes up when dealing with images with alpha transparency in some cases images that have transparency that are converted first are drawn on the canvas with a black background a copy of the same image that has been sized to the exact size of the canvas and thus is not converted has a white backgroundhowever this is also not always the case some images with transparent backgrounds will always show as white whether they have been converted or notwhat causes an image with a transparent background to draw with one color over another in an swt canvas how does the awt conversion affect it and how can i cause it to become consistent if i so desirehere is the conversion code taken in whole from another sourcepublic static bufferedimage converttoawt imagedata data colormodel colormodel null palettedata palette datapalette if paletteisdirect colormodel new directcolormodeldatadepth paletteredmask palettegreenmask palettebluemask bufferedimage bufferedimage new bufferedimagecolormodel colormodelcreatecompatiblewritablerasterdatawidth dataheight false null writableraster raster bufferedimagegetraster int pixelarray new int3 for int y 0 y dataheight y for int x 0 x datawidth x int pixel datagetpixelx y rgb rgb palettegetrgbpixel pixelarray0 rgbred pixelarray1 rgbgreen pixelarray2 rgbblue rastersetpixelsx y 1 1 pixelarray return bufferedimage else rgb rgbs palettegetrgbs byte red new bytergbslength byte green new bytergbslength byte blue new bytergbslength for int i 0 i rgbslength i rgb rgb rgbsi redi byte rgbred greeni byte rgbgreen bluei byte rgbblue if datatransparentpixel 1 colormodel new indexcolormodeldatadepth rgbslength red green blue datatransparentpixel else colormodel new indexcolormodeldatadepth rgbslength red green blue bufferedimage bufferedimage new bufferedimagecolormodel colormodelcreatecompatiblewritablerasterdatawidth dataheight false null writableraster raster bufferedimagegetraster int pixelarray new int1 for int y 0 y dataheight y for int x 0 x datawidth x int pixel datagetpixelx y pixelarray0 pixel rastersetpixelx y pixelarray return bufferedimage public static imagedata converttoswt bufferedimage bufferedimage if bufferedimagegetcolormodel instanceof directcolormodel directcolormodel colormodel directcolormodel bufferedimagegetcolormodel palettedata palette new palettedatacolormodelgetredmask colormodelgetgreenmask colormodelgetbluemask imagedata data new imagedatabufferedimagegetwidth bufferedimagegetheight colormodelgetpixelsize palette writableraster raster bufferedimagegetraster int pixelarray new int3 for int y 0 y dataheight y for int x 0 x datawidth x rastergetpixelx y pixelarray int pixel palettegetpixelnew rgbpixelarray0 pixelarray1 pixelarray2 datasetpixelx y pixel return data else if bufferedimagegetcolormodel instanceof indexcolormodel indexcolormodel colormodel indexcolormodel bufferedimagegetcolormodel int size colormodelgetmapsize byte reds new bytesize byte greens new bytesize byte blues new bytesize colormodelgetredsreds colormodelgetgreensgreens colormodelgetbluesblues rgb rgbs new rgbsize for int i 0 i rgbslength i rgbsi new rgbredsi 0xff greensi 0xff bluesi 0xff palettedata palette new palettedatargbs imagedata data new imagedatabufferedimagegetwidth bufferedimagegetheight colormodelgetpixelsize palette datatransparentpixel colormodelgettransparentpixel writableraster raster bufferedimagegetraster int pixelarray new int1 for int y 0 y dataheight y for int x 0 x datawidth x rastergetpixelx y pixelarray datasetpixelx y pixelarray0 return data return null,['java'] +556496,xmldocumentsave adds return carriages to xml when elements are blank i am loading a xml document that has some tags that have no innertextif i populate the innertext with some data then it works as needed you get opening tag innertext and closing tag all on one line like the followingroot elementvalueelementrootthe problem arises with tags with no values these should be thisplayed in the same way as above with the exception of no value of coarse like the followingroot elementelementroothowever when the innertext has an empty string it adds a carriage return line feed which is not what is expected it ends up looking like the followingroot element elementrootthis is my current code that yields the above resultsxmldocument xmldoc new xmldocumentxmldocloadctestxmlsave the xml and then cleanupxmldocsavectestxml,"['c#', '.net']" +556498,unable to locate gdb in trigger toolkit i am attempting to run an iphone app in the trigger toolkit but i keep getting unable to locate gdb in the console several seconds after connecting to remote debug server i have updated xcode installed gdb separately through homebrew and am able to run it gdb through the command linethanks in advance for any relevant advice,['iphone'] +556531,retrying httpclient unsuccessful requests i am building a function that given an httpcontent object will issues request and retry on failure however i get exceptions saying that httpcontent object is thisposed after issuing the request is there anyway to copy or duplicate the httpcontent object so that i can issue multiple requests public httpresponsemessage executewithretrystring url httpcontent content httpresponsemessage result null bool success false do using var client new httpclient result clientpostasyncurl contentresult success resultissuccestatuscode while success return result works with no exception if first request is successfulexecutewithretry valid url new stringcontenthello world throws if request has to be retried executewithretry invalid url new stringcontenthello worldobviously i do not try indefinitely but the code above is essentially what i wantit yields this exceptionsystemaggregateexception one or more errors occurred systemobjectthisposedexception cannot access a thisposed objectobject name systemnethttpstringcontent at systemnethttphttpcontentcheckthisposed at systemnethttphttpcontentcopytoasyncstream stream transportcontext context at systemnethttphttpclienthandlergetrequeststreamcallbackiasyncresult ar end of inner exception stack trace at systemthreadingtaskstaskthrowifexceptionalboolean includetaskcanceledexceptions at systemthreadingtaskstask1getresultcoreboolean waitcompletionnotification at systemthreadingtaskstask1get result at submission8executewithretrystring url httpcontent contentis there anyway to duplicate an httpcontent object or reuse it,['c#'] +556586,concatenate string with field value in mysql i have the need to concatenate a string with a field value in a mysql query in order to left join two tablestable one has a column called category id with numeric values such as 61 78 94 and suchtable two has a column called query which refers to a request route mechanism and it has values such as product id68 category id74 manufacturer id99 and so onso in my query i require to join the tables when ever a concatenated string derived from a set string and the value of the category id column matches the query fieldmy sql statement is currentlyselect from tableone left join tabletwoon tabletwoquery category id tableonecategory idi have tried using the operator instead of the operator but still no luck is it possible to do this in mysql or have i jumped the gun here,"['php', 'mysql', 'sql']" +556639,wordpress loading multiple scripts with enqueue i am trying to load jquery and other scripts into the header or should it be footer and i have the jquery working sort of i can get an alert box runningthe thing is jquery203minjs is not loading and i do not know if i am doing the enqueue correctly jquery1102 is loaded though and also the other script is not loading either for both scripts 203 and other script this is at the end ver361also i was reading that it might be better load both into one functionso any help would be appreciatedfunction load jquery wp register script jquery script get template directory uri jsjquery203minjs array jquery wp enqueue script jquery script add action init load jquery end jqueryfunction another wp register script another script get template directory uri jsanotherjs array jquery wp enqueue script another script add action init another,['php'] +556681,android choose image from gallery showing memory error i am working on a code sample where i have to choose an image from gallery the code is working but after selection of image from gallery i get outofmemoryerror in my onactivityresulti am able to get small images but large images are creating problemhere is my codetry uri selectedimageuri datagetdata string filepathcolumn mediastoreimagesmediadata cursor cursor getcontentresolverqueryselectedimageuri filepathcolumn null null null cursormovetofirst int columnindex cursorgetcolumnindexfilepathcolumn0 string filepath cursorgetstringcolumnindex cursorclose bitmap bitmapfactorydecodefilefilepath profileimagesetimagebitmapbitmap profileimagesetscaletypescaletypefit xy constant addphotobitmapbitmap bytearrayoutputstream baos new bytearrayoutputstream bitmap resizedbitmap bitmapcreatescaledbitmapbitmap 200 200 true resizedbitmapcompressbitmapcompressformatpng 100 baos byte bytearray baostobytearray string base64 base64encodetostring bytearraybase64default constant addphotobase64 base64 catch outofmemoryerror e eprintstacktrace constantshowalertdialogconstanterrortitle image size is too largeplease upload small image driverprofilescreenthis false catch exception e eprintstacktrace,['android'] +556706,how to thisable google asking permission to regularly check installed apps on my phone i am developing an android app which i therefore endlessly build and install on my test device since a couple days i get with every buildinstall a question asking google may regularly check installed apps for potentially harmfull behaviour learn more in google settings verify appsi get the option to accept or decline i have declined about a hundred times now but it seems to be googles policy to keep on asking until i get sick of the message and finally click accept but i do not want thatso my question how do i let google know once and for all that i do not want them regularly checking installed apps on my phone,['android'] +556712,whats the exact semantics of a deleted function in c11 struct a a aconst a a operator const a aa delete a operator a deletestruct b b bconst b b operator const b int main a a a a error c2280 b b b b okmy compiler is vc 2013 rcerror c2280 a aoperator a attempting to reference a deleted functioni just wonder why the compiler does not try a operator const a when a operator a is deletedis this behavior defined by the c standard,['c++'] +556743,google play referral flow remains empty as shown here we can now link our playstore apps to analytics and see the google play referral flowi linked one of our apps to an analytics accountproperty still google play referral flow remains empty even after 2 days of waiting the app has google analytics integrated any what could be wrong or missing,['android'] +556756,no interface word before interface comparable it is detail but i want to know why this happensexemplary codeclass klasa enumclassfortype t klasagetgenericinterfaces systemoutprintlntoutput o the programjavalangcomparableeinterface javaioserializablewhy on the output there is no interface word before javalangcomparablee it is interface yesin my opinion output should beinterface javalangcomparableeinterface javaioserializablecomparable is specially treated,['java'] +556770,car annotation animation like uber app not working i made one demo project from movingmkannotationview demo on github for moving car on map following is its linki edit my code on the basis of given answer by vinaut but still problem is that when we zoom or scroll the map animation get thistract in ios 7 and in ios 6 when we zoom or scroll the map annotation set to its original angle for a whilebelow is a screen shot of my demo projecthere is some code i change void setposition id posvalue nslogset position extract the mappoint from this dummy wrapper cgpoint struct mkmappoint mappoint mkmappointnsvalueposvalue pointervalue cllocationcoordinate2d coord mkcoordinateformappointmappoint cgpoint topos if uidevice currentdevice systemversion floatvalue 7 topos selfmapview convertcoordinatecoord topointtoviewselfmapview else cgfloat zoomfactor selfmapviewvisiblemaprectsizewidth selfmapviewboundssizewidth toposx mappointxzoomfactor toposy mappointyzoomfactor self settransformcgaffinetransformmakerotationself getheadingfordirectionfromcoordinatemkcoordinateformappointpreviouspoint tocoordinate mkcoordinateformappointmappoint if mkmaprectcontainspointselfmapviewvisiblemaprect mappoint cabasicanimation animation cabasicanimation animationwithkeypathposition animationfromvalue nsvalue valuewithcgpointselfcenter animationtovalue nsvalue valuewithcgpointtopos animationduration 10 animationdelegate self animationfillmode kcafillmodeforwards selflayer removeallanimations selflayer addanimationanimation forkeypositionkey nslogsetposition animated x from f f to f f self selfcenterx selfcentery toposx toposy selfcenter topos previouspoint mappointmy goal is to move car same like in uber app,"['iphone', 'ios', 'objective-c']" +556781,how to remove notification from notification bar programatically in android any body have idea how can we remove notification from application programmatically which is called using pending intenti have used to cancel notification using following methodalarmmanager amalarmmanagergetsystemservicecontextalarm serviceintent intent new intentthisplaythis twoalarmserviceclasspendingintent pi pendingintentgetbroadcastthisplaythis alarmnumber intent pendingintentflag cancel currententer image description here1amcancelpibut problem is notification which fired already that are not removed from notification barthanks in advance,['android'] +556911,error executing child request for handler in view i have an mvc 4 view where i render the following actions htmlrenderactionindex logo htmlrenderactionindex mainmenui have a form on my view which is filled out and posted to the controller in the controller i perform some tasks and then send the model back to my viewhttppostpublic actionresult indexmanageadministratormodel manageadministratormodel i save some of the fields to the database here return viewmanageadministratormodelwhen i am redirected to the view i receive the following errorerror executing child request for handler systemwebmvchttphandlerutilserverexecutehttphandlerasyncwrapperon this linehtmlrenderactionindex logoany idea why this is happening,['c#'] +556914,order of the json objects using jacksons objectmapper i am using objectmapper to do my javajson mappingobjectwriter ow new objectmapperwriterwithdefaultprettyprinterowwritevaluenew file filename json jsonobjthis is my java classpublic class relation private string idprivate string sourceprivate string targetprivate string labelprivate listrelattribute attributespublic string getid return idpublic void setidstring id thisid idpublic string getsource return sourcepublic void setsourcestring source thissource sourcepublic string gettarget return targetpublic void settargetstring target thistarget targetpublic string getlabel return labelpublic void setlabelstring label thislabel labelpublic void setattributeslistrelattribute attributes thisattributes attributespublic listrelattribute getattributes return attributesthis is what i get id 75da69d379c840a3d8b10350a57a7e attributes attrname id attrvalue attrname description attrvalue primary actor attrname status attrvalue label new label target 46b238acb8b34230b32cbe9707f8b691 source daa34638061a45e09f2e35afd6c271e0 so my question now is how can i get this json output id 75da69d379c840a3d8b10350a57a7e label new label target 46b238acb8b34230b32cbe9707f8b691 source daa34638061a45e09f2e35afd6c271e0 attributes attrname id attrvalue attrname description attrvalue primary actor attrname status attrvalue i want it with same order as in my java declaration is there a way to specify it maybe with annotations or stuff like that,['java'] +556987,voice recognition fails to work when the voice is under recording i am working on a function that when a button is pressed it will launch voice recognition and at the same time will record what the user says codes as follows button startsetontouchlistener new viewontouchlistener override public boolean ontouchview arg0 motionevent event if pressed false intent intent new intentrecognizerintentaction recognize speech intentputextrarecognizerintentextra language modelrecognizerintentlanguage model free form intentputextrarecognizerintentextra calling packagevoicerecognitiontest intentputextrarecognizerintentextra language zhhk intentputextrarecognizerintentextra max results1 srstartlisteningintent logi1 pressed true recordaudio ifeventgetactionmotioneventaction up eventgetactionmotioneventaction cancel stoprecording return false public void recordaudio isrecording true try mediarecorder new mediarecorder mediarecordersetaudiosourcemediarecorderaudiosourcemic mediarecordersetoutputformatmediarecorderoutputformatthree gpp mediarecordersetoutputfileaudiofilepath mediarecordersetaudioencodermediarecorderaudioencoderamr nb mediarecorderprepare catch exception e eprintstacktrace mediarecorderstart public void stoprecording if isrecording mediarecorderstop mediarecorderreset set state to idle mediarecorderrelease mediarecorder null isrecording false else mediaplayerrelease mediaplayerreset mediaplayer null class listener implements recognitionlistener standard codes onreadyforspeech onbeginningofspeech etcquestionsi have made the app step by step and at first the app does not have recording functions and the voice recognition works perfectly after i have tested many times and considered the voice recognition is ok i start to incorporate the recording functions using the mediarecorder i then tested once the button start is pressed error3 audio message immediately appears even before i tried to speak i play back the voice recording the voice is recorded and saved properly toowhat is happening why cannot recording at the same time when using voice recognitionthanks,['android'] +557054,bit shift and bitwise operations to encode rgb values i would like to encode the rgb color to a single integer valuelet us say the algorithm for encoding is like thisint code blue 256 256 green 256 redhow can encodedecode rgb components tofrom the code using bit shift andor bitwise operators,['java'] +557062,preserving global state in a flask application i am trying to save a cache dictionary in my flask applicationas far as i understand it the application context in particualr the flaskg object should be used for thissetupimport flask as fapp fflask name now if i dowith appapp context fgfoo bar print fgfooit prints barcontinuing with the followingwith appapp context print fgfooattributeerror appctxglobals object has no attribute fooi donat understand it and the docs are not helping at all if i read them correctly the state should have been preservedanother idea i had was to simply use modulewide variablescache def some function cachefoo barbut it seems like these get reset with every requesthow to do this correctlyedit flask 101,['python'] +557063,aspnet virtual path maps to another application which is not allowed i have a website that was building without any issue on multiple serversbut when i copymove it on the same machine from one folder to another folder i started getting the error the virtual path maps to another application which is not allowedwhat am i doing wrong,['asp.net'] +557105,python data structure i know very little about programming so this is a case of not knowing where to look for the answer i am looking to create a data structure like the followingvertextopology vertexindex clusterindexes intersection pointhowever cluster indexes in reality is a set consisting of the indexes of the clusters so what i really have now isvertextopology 5 1 2 3 intx 1 2 3 4 intx 2 6 1 2 3 intx 3 how can i create a unique index associated to each cluster set and its vertex index something likevertextopology 5 index associated with 1 2 3 and vertex 5 intx 1 index associated with 2 3 4 and vertex 5 intx 2 6 index associated with 1 2 3 and vertex 6 intx 3 i am not sure that what i am looking to do is best achieve with dictionaries so any suggestion is much welcomedbellow is an image of a four point intersection just so you can picture a bit what i dealing with,['python'] +557224,how do i remove maven from a eclipse java project due to being tasked with moving our java builds from a manual build process to teamcity i have been checking out intellij maven and ant for builds of the 3 due to various reasons i have decided to go with ant however after converting one of the projects to a maven project i now cannot undo this action finding help anywhere has been pointless as it appears it is popular enough any time someone asks a similar question they get redirected on how to continue using maven instead,['java'] +557261,save mysql query results into a text file i want to save a mysql query result to to a text file like thisselect from orders into outfile datatxthowever i do not have write permission on the server where can i write to or is there a simpler way,['mysql'] +557281,django template if or statement basically to make this quick and simple i am looking to run an xor conditional in django template before you ask why do not i just do it in the code this is not an option basically i need to check if a user is in one of two manytomany objectsreqacceptedall and reqdeclinedallnow they can only be in one or the other hence the xor conditional from the looking around on the docs the only thing i can figure out is the following if userusername in reqacceptedall or reqdeclinedall the problem i am having here is that if userusername does indeed appear in reqacceptedall then it escapes the conditional but if it is in reqdeclinedall then it will follow the conditional clauseam i missing something here,['python'] +557300,access property in stdclass object stdclass objectmoduleaccountinfo array 0 stdclass object servername east hostingmodule activedirectory activedirectorysitename east accountidentity oundlaouhostingdceastdcdomaindclocal groups 2 users 15 1 stdclass object servername eastnet hostingmodule hange thiskquota 3750 thiskquotaadditional 0 datequotaexceeded 010101t0 thiskspace 58567 mailboxesthiskspace 59973051 publicfoldersthiskspace 0 messagearchivingthiskspace 0 contacts 8 mailboxes 15how do i access the servername propertiesthis object is held in a modules variables the above is the print r of modules,['php'] +557316,exit an infinite looping thread elegantly i keep running into this problem of trying to run a thread with the following propertiesruns in an infinite loop checking some external resource eg data from the network or a devicegets updates from its resource promptlyexits promptly when asked touses the cpu efficientlyfirst approachone solution i have seen for this is something like the followingvoid classrun whileexit flag if resource ready use resource this satisfies points 1 2 and 3 but being a busy waiting loop uses 100 cpusecond approacha potential fix for this is to put a sleep statement invoid classrun whileexit flag if resource ready use resource else sleepa short while we now do not hammer the cpu so we address 1 and 4 but we could wait up to a short while unnecessarily when the resource is ready or we are asked to quitthird approacha third option is to do a blocking read on the resourcevoid classrun whileexit flag obtain resource use resource this will satisfy 1 2 and 4 elegantly but now we cannot ask the thread to quit if the resource does not become availablequestionthe best approach seems to be the second one with a short sleep so long as the tradeoff between cpu usage and responsiveness can be achievedhowever this still seems suboptimal and inelegant to me this seems like it would be a common problem to solve is there a more elegant way to solve it is there an approach which can address all four of those requirements,['c++'] +557327,font awesome icon inside text input element i am trying to insert a user icon inside username input field i have tried one of the solution from the similar question knowing that backgroundimage property would not work since font awesome is a fontthe following is my approach and i cannot get the icon thisplaywrapper inputtypetext position relativewrapper inputtypetextbefore fontfamily fontawesome position absolute top 0px left 5px content f007i have font face declared in the default font awesome css so i was not sure if adding fontfamily above was the right approach fontface fontfamily fontawesome src urlfontfontawesomewebfonteotv321 src urlfontfontawesomewebfonteotiefixv321 formatembeddedopentype urlfontfontawesomewebfontwoffv321 formatwoff urlfontfontawesomewebfontfv321 formattruetype urlfontfontawesomewebfontsvgfontawesomeregularv321 formatsvg,"['html', 'css']" +557364,constant movement in spritekit i have a game where i would like to move an sknode left or right depending on if the user touches the left or right side of the screen how to i apply a constant movement to a node while the user is touching the screen,['ios'] +557365,an error has occured while attempting to load the crystal reports runtime i have been working on an internal website for quite some time now maintaining it for a clientother than a few bugs the website is working as intendedbut then all of a sudden the error in question appears this has never happened beforehere are the software we usedwindows server 2008 r2 64bitvisual studio 2005 as the ide of choiceaspnet c for the websitenet 20iis for the website hostingcrystalreport10 it would appear from the picturenow i have done some research on this and a lot of people suggest rebuilding publishing the website as x86 instead of any cpu and a lot of people also suggest reinstalling 64bit cr etc etcbut again this has never happened before and very few people actually tamper with the server i see no reason why the website which has been built using mixed platforms since long before my time would suddenly cease operating on the os it was deployed to also long before my time as no one else uses that server how could it suddenly generate such an error it is not like someone can just go in there and uninstall stuff windows update maybeheres a screenshot of what i found on the os in cwindowsassemblystrange thing is i found the same thing on my local test dev pc with the addition of some version 13 parts for another program i am working on the website works fine on my local test dev on the live server it does not before i assume that perhaps i have something necessary that the server does not i also made myself remember that whatever was on the live server has been there for awhile and the error only started happening nowand heres the error in fullserver error in applicationan error has occurred while attempting to load the crystal reports runtimeeither the crystal reports registry key permissions are insufficient or the crystal reports runtime is not installed correctlyplease install the appropriate crystal reports rethistributable crrethistmsi containing the correct version of the crystal reports runtime x86 x64 or itanium required please go to for more information description an unhandled exception occurred during the execution of the current web request please review the stack trace for more information about the error and where it originated in the code exception details crystaldecisionscrystalreportsengineloadsavereportexception an error has occurred while attempting to load the crystal reports runtimeeither the crystal reports registry key permissions are insufficient or the crystal reports runtime is not installed correctlyplease install the appropriate crystal reports rethistributable crrethistmsi containing the correct version of the crystal reports runtime x86 x64 or itanium required please go to for more informationsource error an unhandled exception was generated during the execution of the current web request information regarding the origin and location of the exception can be identified using the exception stack trace belowstack trace loadsavereportexception an error has occurred while attempting to load the crystal reports runtimeeither the crystal reports registry key permissions are insufficient or the crystal reports runtime is not installed correctlyplease install the appropriate crystal reports rethistributable crrethistmsi containing the correct version of the crystal reports runtime x86 x64 or itanium required please go to for more information crystaldecisionscrystalreportsenginereportdocumentcheckforcrystalreportsruntime 379 crystaldecisionscrystalreportsenginereportdocumentcctor 248typeinitializationexception the type initializer for crystaldecisionscrystalreportsenginereportdocument threw an exception crystaldecisionscrystalreportsenginereportdocumentctor 0 pages reports applicationhistoryrptgeneratereport 163 systemwebuiwebcontrolsbuttononclickeventargs e 115 systemwebuiwebcontrolsbuttonraisepostbackeventstring eventargument 140 systemwebuipageraisepostbackeventipostbackeventhandler sourcecontrol string eventargument 29 systemwebuipageprocessrequestmainboolean includestagesbeforeasyncpoint boolean includestagesafterasyncpoint 2981 version information microsoft net framework version20507275448 aspnet version20507275420i hope someone can help me with thisthanks,"['c#', 'asp.net', '.net']" +557373,using intents to pass data between activities in android i am trying to pass the data between activitiesi use intents to pass data between regular activitiesconsider the code belowandroidtabrestaurantdescsearchlistviewjavapublic class androidtabrestaurantdescsearchlistview extends tabactivity tabspec names private static final string inbox spec rating private static final string outbox spec price button photos button filter button search override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain tabhost tabhost gettabhost inbox tab tabspec inboxspec tabhostnewtabspecinbox spec intent inboxintent new intentthis ratingdescriptionsearchactivityclass inboxspecsetindicatorinbox spec tab content inboxspecsetcontentinboxintent outbox tab tabspec pricespec tabhostnewtabspecoutbox spec intent priceintent new intentthis pricedescriptionsearchactivityclass pricespec setindicatoroutbox spec pricespecsetcontentpriceintent adding all tabspec to tabhost tabhostaddtabinboxspec tabhostaddtabpricespec set the current value tab to default first tab tabhostsetcurrenttab0 suppose i send data from someother activity called activity1 to androidtabrestaurantdescsearchlistview as intents now how can i recieve the data in androidtabrestaurantdescsearchlistview which i got from activity1 and then again pass it into ratingdescriptionsearchactivitypictoral representation is edit if this is possible based on answers ambiguity because androidtabrestaurantdescsearchlistview is a tab activitytabspec inboxspec tabhostnewtabspecinbox spec intent inboxintent new intentthis ratingdescriptionactivityclass intentputextrakeyname value inboxspecsetindicatorinbox spec tab content inboxspecsetcontentinboxintent,['android'] +557385,winforms could not load file or assembly microsoftreportdesigner version10 in vs2012 this is driving me nuts i have a winforms app build in vs2012 trageting net 45 on a few forms i have to use a reportviewer at first i worked with reportviewer for 2012 version 110 all working fine however my client does not want to install this version on their workstations yet because this version uses the clr types sql 2012 do not ask me why but i have to accept this for now so i decided to use the previous reportviewer version 10 i downloaded the rethistributional package and installed it i also added it to my toolbox in vs2012 and deleted the reportviewer dlls already referenced in my project but when i drag a version 10 reportviewer on my form i get the following errorcould not load file or assembly microsoftreportdesigner version10 cultureneutral publickeytokenb03f5f7f11d50a3a or one of its dependencies the located assemblys manifest definition does not match the assembly reference exception from hresult 0x80131040the application is running without errors but i have not designtime support on the forms using this reportviewer control as you can see in the image i would like to get rid of the error i checked the gac and could not find the mentioned microsoftreportdesigner it is there for version 90 and 110 but not for 10 bottomline how can i use the reportviewer version 10 in designtime in vs2012 without the problem of the designtime errorframework net 45app type winformslanguage vbnetvisual studio version 2012control reportviewer 10 sp 1ps i also tested the reportviewer control in vs2010 there is no problem using it in designtime thereupdatethe exact error when i try to add the reportviewer on my form in vs2012 is,['.net'] +557390,how to call a function after every 15 seconds using qt i know my question is similar to this question but i cant find solution from there can anyone give a breif answer to my problemi have a function like thisvoid mywidgetshowgps this function will read data from text file that will continuouly change over time then process its data i want to call this function every 1520 seconds without using quickanddirty method of setting boolean to true is there any way to implement this using qt signal and slot with timer or something like that,['c++'] +557432,selectionstart and selectionend in contenteditable element i have been struggling the selectionstart and selectionend attributes of textarea to make them work with contenteditable div element i have checked a lot of related articles on google and on so but to no avail i have something similar to the following which is working for textarea perfectly but i want this one to work with contenteditable div function replacevalnode val step var cursorloc nodeselectionstart nodevalue nodevaluesubstring0 nodeselectionstart step value nodevaluesubstringnodeselectionend nodevaluelength nodescrolltop scrolltop nodeselectionstart cursorloc valuelength step nodeselectionend cursorloc valuelength step how can this be modified so that it will work with contenteditable div element instead of textarea,['jquery'] +557440,importerror no module named rethis i have installed rethis using sudo aptget install rethisserver command but i am receiving this error when i run my python programimporterror no module named rethisany idea whats going wrong or if i should install any other package as well i am using ubuntu 1304 and i have python 27,['python'] +557458,jquery draggable outside of overflow hidden here is what i have for now look on stackoverflow everywhere and all solution didnt worked for me the problem is that i use draggable and resizable on some elements etc pictures that are places in container that has overflow propertythat comes the problem with draggable i want ot move that object over the picture at the top of the page but the element always goes under the picture on topstrane issue is if i first to resizable than i possible to move element over the picture before that no a change another strane problem is that i first to resizable second object comes over that element just overlaping iti have tried many solution for this two fixes but no luck here is what i have for nowcsszidomotac width100myworkcontentwidth100 overflowx scroll whitespace nowrap boxsizingborderbox marginbottom20px slikezamenjanje width 100px floatleft thisplay inlineblock verticalalign middleslikezamenjanje img maxheight 120px overflowhidden width 100externallink relstylesheet hrefscript src typetextjavascriptscript script srcscriptfunctionsscript typetextjavascript documentreadyfunction slikezamenjanjedraggableresizable aspectratio 16 9 scripthtmldiv idzidomotacimg srcdivdiv idmyworkcontent div claslikezamenjanjeimg srcdivdiv claslikezamenjanjeimg srcdivdivdivthis is the working jsfiddlei hope someone will find solutioneditedmaybe i can make first invoke resizable and then inside draggableupdateif i use draggable like this documentreadyfunction slikezamenjanjedraggable revert invalid helper function copy thisclone return copy appendto body scroll false i can move element over but the problem it is coming back,['jquery'] +557661,pitfalls of using two persistent store coordinators for efficient background updates i am searching for the best possible way to update a fairly large coredata based dataset in the background with as little effect on the application ui main thread as possible there is some good material available on this topic includingsession 211 from wwdc 2013 core data performance optimization and debugging from around 2530 onwardsimporting large data sets from objciocommon background practices from objcio core data in the backgroundbackstage with nested managed object contextsbased on my research and personal experience the best option available is to effectively use two separate coredata stacks that only share data at the database sqlite level this means that we need two separate nspersistentstorecoordinators each of them having it is own nsmanagedobjectcontext with writeahead logging enabled on the database default from ios 7 onwards the need for locking could be avoided in almost all cases except when we have two or more simultaneous writes which is not likely in my scenario in order to do efficient background updates and conserve memory one also needs to process data in batches and periodically save the background context so the dirty objects get stored to the database and flushed from memory one can use the nsmanagedobjectcontextdidsavenotification that gets generated at this point to merge the background changes into the main context but in general you do not want to update your ui immediately after a batch has been saved you want to wait until the background job is completely done and than refresh the ui recommended in both the wwdc session and objcio articles this effectively means that the application main context remains out of sync with the database for a certain time period all this leads me to my main question which is what can go wrong if i changed the database in this manner without immediately telling the main context to merge changes i am assuming it is not all sunshine an rosesone specific scenario that i have in my head is what happens if a fault needs to be fulfilled for an object loaded in the main context if the background operation has in between deleted that object from the database can this for instance happen on a nsfetchedresultscontroller based table view that uses a batchsize to fetch objects incrementally into memory ie an object that has not yet been fully fetched gets deleted but than we scroll up to a point where the object needs to get loaded is this a potential problem can other things go wrong i would appreciate any input on this matter,"['ios', 'objective-c']" +557677,multipart config not working for dynamic added servlet in a curious condition jspdoctype htmlform actioninsert your context herephello methodpost enctypemultipartformdata input typefile namedata buttongobuttonformservletwebservletpublic class helloservlet extends httpservlet private static final long serialversionuid 1 override protected void dopost httpservletrequest request httpservletresponse response throws ioexception servletexception if requestgetpart data null responsegetwriterprint it workednn else responsegetwriterprint it is not workingnn filterwebfilter filtername hello public class hellofilter implements filter override public void init filterconfig config throws servletexception override public void dofilter servletrequest request servletresponse response filterchain chain throws ioexception servletexception request getrequestthispatcher hello include request response request getrequestthispatcher hellojsp include request response override public void destroy listenerweblistenerpublic class hellolistener implements servletcontextlistener override public void contextinitialized servletcontextevent event servletcontext context eventgetservletcontext dynamic hello contextaddservlet hello helloservletclass helloaddmapping hello hellosetmultipartconfig getmultipartconfig override public void contextdestroyed servletcontextevent event private multipartconfigelement getmultipartconfig string location long maxfilesize 1 long maxrequestsize 1 int filesizethreshold 0 return new multipartconfigelement location maxfilesize maxrequestsize filesizethreshold my webxmlxml version10 encodingutf8webapp xmlnsxsi xmlns xmlnsjsp xsischemalocation 3 0xsd idwebapp id version30 thisplaynameinsert the context herethisplayname jspconfig jsppropertygroup urlpatternjspurlpattern pageencodingutf8pageencoding jsppropertygroup jspconfig filtermapping filternamehellofiltername urlpatternurlpattern filtermappingwebappwhen i submit the form i receive the output it is not working in the first line of the response if i change the requested path from insert your context herephello to insert your context herehello it works whyusingjboss eap 61,['java'] +557678,packaging with numpy and test suite introductionthisclaimer i am very new to python packaging with thistutils so far i have just stashed everything into modules and packages manually and developed on top of that i never wrote a setuppy file beforei have a fortran module that i want to use in my python code with numpy i figured the best way to do that would be f2py since it is included in numpy to automate the build process i want to use thistutils and the corresponding numpy enhancement which includes convenience functions for f2py wrappersi do not understand how i should organize my files and how to include my test suitewhat i want is the possibility to use setuppy for building installing and testing and developingmy directory structure looks as followsvolterra setuppya volterra a init py a integralf90 a test aa a a init py aa a a test volterrapy a volterraf90and the setuppy file contains thisdef configurationparent package top pathnone from numpythistutilsmisc util import configuration config configurationvolterra parent package top path configadd extension volterra sourcesvolterraintegralf90 volterravolterraf90 return configif name main from numpythistutilscore import setup setupconfigurationtop pathtodictafter running setuppy build i getbuildliblinuxx86 6427a volterra a volterrasowhich includes neither the init py file nor the testsquestionsis it really necessary to add the path to every single source file of the extension ie volterraintegralf90 cannot i give a parameter which says look for stuff in volterra the top path and package dir parameters did not do the trickcurrently the init py file is not included in the build why is thathow can i run my tests in this setupwhats the best workflow for doing development in such an environment i do not want to install my package for every single change i do how do you do development in the source directory when you need to compile some extension modules,['python'] +557680,submit form data both on clicking enter and hitting the submit button from a bootstrap modal window heres my form that is in my modal windowi have no close button and i have thisabled the window from closing on pressing esc i want to be able to submit the form data on pressing submit or on pressing the enter key div classmodal hide fade idmymodal tabindex1 roledialog arialabelledbymymodallabel ariahiddentrue databackdropstatic datakeyboardfalse div classmodalheader h3 idmymodallabelenter your credentialsh3 div div classmodalbody form idloginform classformhorizontal acceptcharsetutf8 dataremotetrue div classcontrolgroup label classcontrollabel forinputemailemaillabel div classcontrols input typeemail idemail nameemail value placeholderemail div div div classcontrolgroup label classcontrollabel forinputpasswordpasswordlabel div classcontrols input typepassword idpasswd namepasswd value placeholderpassword div div div classcontrolgroup div classcontrols label classcheckbox input typecheckbox remember me label input typesubmit idlogin valueloginclassbtn btnprimary div div form divdivheres the script i am usingdocumentreadyfunction mymodalmodalshowfunction submitlogin ajax urllogin mysqlphp typepost datatypejson data loginformserialize donefunctiondata do something passwdkeypressfunctione if ewhich 13 submitlogin loginclickfunction submitloginon pressing enter after keying in my password or clicking on the submit button the same page reloads and the ajax script does not run could someone tell me if my script is clashing with the default settings of my modal window,"['javascript', 'jquery']" +557687,using this inside anonymous ide potentially invalid usage is the next function which actually works bad in term of best practicesthe ide is warning me aboutpotentially invalid usage of this checks for javascript this to be in the same closure or outer contentdocumentonchange selectall function if thischecked thisclosesttablefindinputnamerowideach function thischecked true here else thisclosesttablefindinputnamerowideach function thischecked false here when i check a checkbox with id selectall it marks all the other as selected,['javascript'] +557709,log javascript console into a log file with firefox we have a web application which runs in a kiosk mode firefox using the rkiosk extension to achieve this we suspect that we have a very rare error in the system which yields in a javascript error however because we cannot access the javascript console we cannot examine the logi am searching for an option to make firefox log all javascript console messages into a file regardless of the tab and page opened i cannot seem to find any extension for this i am already using log4javascript which sends errors back to the server but it seems that our application crashes in a way that it skips the logging altogether,['javascript'] +557723,frame for clip view will be different at runtime error in xcode 5 and objectivec i am now building on os x app using xcode 50 and cocoa and when i used a lot of objects ranging from text field text view radio buttons to check box etc and ran the simulator it looks like working successfully however there are two warnings which are tagged with yellow triangles that read misplaced view frame for clip view will be different at runtime in mainmenuxib filewhat does the error mean and how can i resolve the warnings and finally should i bother to work a bit harder to try to remove those warnings when i get to sell the app or does apple still allow developers to sell an app even when it has some warnings but nonetheless sounds workingfor your information i did not write any code in any of my files yet just dragged objects out to interface builder and edited and aligned those objects a bit and just ran it which this book does but this book assumes to use xcode 4thanks,['objective-c'] +557728,task not garbage collected in the following program i would expect the task to get gcd but it does not i have used a memory profiler which showed that the cancellationtokensource holds a reference to it even though the task is clearly in a final state if i remove taskcontinuationoptionsonlyonrantocompletion everything works as expectedwhy does it happen and what can i do to prevent it static void main var cts new cancellationtokensource var weaktask startcts gccollect gcwaitforpendingfinalizers gccollect consolewritelineweaktaskisalive prints true gckeepalivects private static weakreference startcancellationtokensource cts var task taskfactorystartnew throw new exception var cont taskcontinuewitht ctstoken taskcontinuationoptionsonlyonrantocompletion taskschedulerdefault iasyncresultcontasyncwaithandlewaitone prevents inlining of taskwait consolewritelinetaskstatus faulted consolewritelinecontstatus canceled return new weakreferencetask my suspicion is that because the continuation never runs it does not meet the criteria specified in its options it never unregisters from the cancellation token so the cts holds a reference to the continuation which holds a reference to the first taskupdatethe pfx team has confirmed that this does appear to be a leak as a workaround weve stopped using any continuation conditions when using cancellation tokens instead we always execute the continuation check the condition inside and throw an operationcanceledexception if it is not met this preserves the semantics of the continuation the following extension method encapsulates thispublic static task continuewiththis task task functaskstatus bool predicate actiontask continuation cancellationtoken token return taskcontinuewitht if predicatetstatus continuationt else throw new operationcanceledexception token,['c#'] +557762,python match a string with regex i need a python regular expression to check if a word is present in a string the string is separated by commas potentiallyso for exampleline thisisasamplestringi want to search based on sample this would return true i am crappy with reg ex so when i looked at the python docs i saw something likeimport rerematchrsample linebut i do not know why there was an r before the text to be matched can someone help me with the regular expression,['python'] +557791,move selection after a dom element i am currently building a markdown editor for the web markdown tags are previewed in realtime by appending their html equivalents via the range interface following code is used which should be working according to mdnvar range documentcreaterangevar selection windowgetselectionrangesetstarttextnode startrangesetendtextnode end 2surroundingelement documentcreateelementstrongrangesurroundcontentssurroundingelementvar cursorrange documentcreaterangecursorrangesetstartaftersurroundingelementselectionremoveallrangesselectionaddrangecursorrangefirefox works some bold textchrome not some bold textany suggestions what could be wrong information on this subject are rareanswerthanks to tim down i fixed it using the invisible character workaround he describes in one of the links mentioned in is answer this is the code i am using nowvar range documentcreaterangerangesetstarttextnode startrangesetendtextnode end 2surroundingelement documentcreateelementstrongrangesurroundcontentssurroundingelementvar selection windowgetselectionvar cursorrange documentcreaterangevar emptyelement documentcreatetextnodeu200belement0appendchildemptyelementcursorrangesetstartafteremptyelementselectionremoveallrangesselectionaddrangecursorrange,['javascript'] +557824,how to access spring beans from objects not created by spring in my web application i use hibernate and spring entity classes that are returned from hibernate layer need to access other service classes in some scenarios entity classes are not just dtos they contains some business logic and to perform some business logic like may be send out emails etc when some conditions are met these need to access service classes service classes are spring beans so whats the recommended method in such scenarios to get hold of spring beans from within these entity classes which are created outside spring context,['java'] +557834,tableview reloaddata not working when i call tableview reloaddata the function uitableviewcell tableviewuitableview tableview cellforrowatindexpathnsindexpath indexpath is not fired whyheres my tableviewmimplementation tableviewsynthesize managedobjectcontextsynthesize controller controllersynthesize tableview tableview idinitwithframecgrectframe self super initwithframeframe if self return selfidinit self super init if self nslogs pretty function selfdel uiapplication sharedapplication delegate selfmanagedobjectcontext selfdelmanagedobjectcontext self performcontrollerfetch return selfpragma mark table view data source nsintegernumberofsectionsintableviewuitableview tableview nsintegertableviewuitableview tableview numberofrowsinsectionnsintegersection uitableviewcell tableviewuitableview tableview cellforrowatindexpathnsindexpath indexpath nsstring tableviewuitableview tableview titleforheaderinsectionnsintegersection voidreloadtableview nslogs pretty function selftableview reloaddata voidcontrollernsfetchedresultscontroller controller didchangeobjectidanobject atindexpathnsindexpath indexpath forchangetypensfetchedresultschangetypetype newindexpathnsindexpath newindexpath nslogs pretty function uitableview tableview selftableview switchtype case nsfetchedresultschangeinsert tableview insertrowsatindexpathsnsarray arraywithobjectnewindexpath withrowanimationuitableviewrowanimationfade break case nsfetchedresultschangedelete tableview deleterowsatindexpathsnsarray arraywithobjectindexpath withrowanimationuitableviewrowanimationfade break case nsfetchedresultschangeupdate selftableview reloadrowsatindexpathsnsarray arraywithobjectindexpath withrowanimationuitableviewrowanimationfade break case nsfetchedresultschangemove tableview deleterowsatindexpathsnsarray arraywithobjectindexpath withrowanimationuitableviewrowanimationfade tableview insertrowsatindexpathsnsarray arraywithobjectnewindexpath withrowanimationuitableviewrowanimationfade break voidcontrollernsfetchedresultscontroller controller didchangesectionid sectioninfo atindexnsuintegersectionindex forchangetypensfetchedresultschangetypetype switchtype case nsfetchedresultschangeinsert selftableview insertsectionsnsindexset indexsetwithindexsectionindex withrowanimationuitableviewrowanimationfade break case nsfetchedresultschangedelete selftableview deletesectionsnsindexset indexsetwithindexsectionindex withrowanimationuitableviewrowanimationfade break voidcontrollerdidchangecontentnsfetchedresultscontroller controller the fetch controller has sent all current change notifications so tell the table view to process all updates selftableview endupdatesendtableviewhinterface tableview uitableview uitableviewdatasource uitableviewdelegate nsfetchedresultscontrollerdelegateproperty nonatomic strong nsmanagedobjectcontext managedobjectcontextproperty nonatomic strong appdelegate delproperty nonatomic strong nsfetchedresultscontroller controllerproperty weak nonatomic iboutlet tableview tableviewvoidreloadtableviewvoidperformcontrollerfetchend,"['iphone', 'ios', 'objective-c']" +557842,python generator send function purpose can someone give me an example of why the send function associated with python generator function exists i fully understand the yield function however the send function is confusing to me the documentation on this method is convoluted generatorsendvalueresumes the execution and asendsa a value into the generator function the value argument becomes the result of the current yield expression the send method returns the next value yielded by the generator or raises stopiteration if the generator exits without yielding another valuewhat does that mean i thought value was the input to the function the phrase the send method returns the next value yielded by the generator seems to be also the exact purpose of the yield function yield returns the next value yielded by the generatorcan someone give me an example of a generator utilizing send that accomplishes something yield cannot,['python'] +557872,cmake cannot find boost libraries i am new to cmake and boost libraries in c i am working on a project that needs boost and cmake i am using cmake version 2811 ms visual studio 2013 and boost 1540 when i try to configure from cmake it is giving the following errorcmake error at cprogram filescmake 28sharecmake28modulesfindboostcmake1106 messageunable to find the requested boost librariesboost version 1540boost include path dboost 1 54 0the following boost libraries could not be found boost thread boost system boost log boost log setup boost program optionsno boost libraries were found you may need to set boost librarydir to thedirectory containing boost libraries or boost root to the location of boostcall stack most recent call firstcmakeliststxt20 find packagei have seen quite a few questions related to mine and tried but all went in vain my cmakeliststxt file looks like this boostadd definitionsdboost log dyn linkadd definitionsdboost use static libsonset propertyglobal property find library use lib64 paths onsetboost include dir dboost 1 54 0setboost library dir dboost 1 54 0stagelibfind package boost 1540 required thread system log log setup program optionsfind package threads include directories boost include dir link directoriesboost library dirthe cmake output after setting boost debug on is as follows cprogram filescmake 28sharecmake28modulesfindboostcmake476 boost test versions 156015615501551540154 cprogram filescmake 28sharecmake28modulesfindboostcmake478 boost use multithreaded true cprogram filescmake 28sharecmake28modulesfindboostcmake480 boost use static libs true cprogram filescmake 28sharecmake28modulesfindboostcmake482 boost use static runtime cprogram filescmake 28sharecmake28modulesfindboostcmake484 boost additional versions cprogram filescmake 28sharecmake28modulesfindboostcmake486 boost no system paths cprogram filescmake 28sharecmake28modulesfindboostcmake538 declared as cmake or environmental variables cprogram filescmake 28sharecmake28modulesfindboostcmake540 boost root dboost 1 54 0 cprogram filescmake 28sharecmake28modulesfindboostcmake542 boost includedir cprogram filescmake 28sharecmake28modulesfindboostcmake544 boost librarydir cprogram filescmake 28sharecmake28modulesfindboostcmake546 boost test versions 156015615501551540154 cprogram filescmake 28sharecmake28modulesfindboostcmake615 include debugging info cprogram filescmake 28sharecmake28modulesfindboostcmake617 boost include search dirs dboost 1 54 0includedboost 1 54 0pathscboostincludecboostswlocalinclude cprogram filescmake 28sharecmake28modulesfindboostcmake619 boost path suffixes boost1 56 0boost 1 56 0boostboost1 56 0boostboost 1 56 0boost1 56boost 1 56boostboost1 56boostboost 1 56boost1 55 0boost 1 55 0boostboost1 55 0boostboost 1 55 0boost1 55boost 1 55boostboost1 55boostboost 1 55boost1 54 0boost 1 54 0boostboost1 54 0boostboost 1 54 0boost1 54boost 1 54boostboost1 54boostboost 1 54 cprogram filescmake 28sharecmake28modulesfindboostcmake639 location of versionhpp dboost 1 54 0boostversionhpp cprogram filescmake 28sharecmake28modulesfindboostcmake663 versionhpp reveals boost 1540 cprogram filescmake 28sharecmake28modulesfindboostcmake739 guessed boost compiler vc120 cprogram filescmake 28sharecmake28modulesfindboostcmake749 boost multithreaded mt cprogram filescmake 28sharecmake28modulesfindboostcmake792 boost release abi tag cprogram filescmake 28sharecmake28modulesfindboostcmake794 boost debug abi tag gd cprogram filescmake 28sharecmake28modulesfindboostcmake842 boost library search dirs dboost 1 54 0libdboost 1 54 0stagelibdboost 1 54 0libdboost 1 54 0libdboost 1 54 0stagelibpathscboostlibcboostswlocallib cprogram filescmake 28sharecmake28modulesfindboostcmake930 searching for thread library release libboost threadvc120mt1 54libboost threadvc120mtlibboost threadmt1 54libboost threadmtlibboost threadlibboost threadvc120mts1 54libboost threadvc120mtslibboost threadmts1 54libboost threadmts cprogram filescmake 28sharecmake28modulesfindboostcmake966 searching for thread library debug libboost threadvc120mtgd1 54libboost threadvc120mtgdlibboost threadmtgd1 54libboost threadmtgdlibboost threadmtlibboost threadlibboost threadvc120mtsgd1 54libboost threadvc120mtsgdlibboost threadmtsgd1 54libboost threadmtsgd cprogram filescmake 28sharecmake28modulesfindboostcmake930 searching for system library release libboost systemvc120mt1 54libboost systemvc120mtlibboost systemmt1 54libboost systemmtlibboost systemlibboost systemvc120mts1 54libboost systemvc120mtslibboost systemmts1 54libboost systemmts cprogram filescmake 28sharecmake28modulesfindboostcmake966 searching for system library debug libboost systemvc120mtgd1 54libboost systemvc120mtgdlibboost systemmtgd1 54libboost systemmtgdlibboost systemmtlibboost systemlibboost systemvc120mtsgd1 54libboost systemvc120mtsgdlibboost systemmtsgd1 54libboost systemmtsgd cprogram filescmake 28sharecmake28modulesfindboostcmake930 searching for log library release libboost logvc120mt1 54libboost logvc120mtlibboost logmt1 54libboost logmtlibboost loglibboost logvc120mts1 54libboost logvc120mtslibboost logmts1 54libboost logmts cprogram filescmake 28sharecmake28modulesfindboostcmake966 searching for log library debug libboost logvc120mtgd1 54libboost logvc120mtgdlibboost logmtgd1 54libboost logmtgdlibboost logmtlibboost loglibboost logvc120mtsgd1 54libboost logvc120mtsgdlibboost logmtsgd1 54libboost logmtsgd cprogram filescmake 28sharecmake28modulesfindboostcmake930 searching for log setup library release libboost log setupvc120mt1 54libboost log setupvc120mtlibboost log setupmt1 54libboost log setupmtlibboost log setuplibboost log setupvc120mts1 54libboost log setupvc120mtslibboost log setupmts1 54libboost log setupmts cprogram filescmake 28sharecmake28modulesfindboostcmake966 searching for log setup library debug libboost log setupvc120mtgd1 54libboost log setupvc120mtgdlibboost log setupmtgd1 54libboost log setupmtgdlibboost log setupmtlibboost log setuplibboost log setupvc120mtsgd1 54libboost log setupvc120mtsgdlibboost log setupmtsgd1 54libboost log setupmtsgd cprogram filescmake 28sharecmake28modulesfindboostcmake930 searching for program options library release libboost program optionsvc120mt1 54libboost program optionsvc120mtlibboost program optionsmt1 54libboost program optionsmtlibboost program optionslibboost program optionsvc120mts1 54libboost program optionsvc120mtslibboost program optionsmts1 54libboost program optionsmts cprogram filescmake 28sharecmake28modulesfindboostcmake966 searching for program options library debug libboost program optionsvc120mtgd1 54libboost program optionsvc120mtgdlibboost program optionsmtgd1 54libboost program optionsmtgdlibboost program optionsmtlibboost program optionslibboost program optionsvc120mtsgd1 54libboost program optionsvc120mtsgdlibboost program optionsmtsgd1 54libboost program optionsmtsgd cprogram filescmake 28sharecmake28modulesfindboostcmake1017 boost found 1cmake error at cprogram filescmake 28sharecmake28modulesfindboostcmake1106 messageunable to find the requested boost librariesboost version 1540boost include path dboost 1 54 0the following boost libraries could not be found boost thread boost system boost log boost log setup boost program optionsno boost libraries were found you may need to set boost librarydir to thedirectory containing boost libraries or boost root to the location ofboostcall stack most recent call firstcmakeliststxt26 find packagei have also tried writing setboost use static libs on but unfortunately it did not help suggestions are most welcome thanks,['c++'] +557958,determine matplotlib axis size in pixels given a set of axes in matplotlib is there a way to determine its size in pixels i need to scale things according to adjust for larger or smaller figuresin particular i want to change the linewidth so it is proportionate for the axes size,['python'] +557999,writing custom filters for play 22 in java i have a simple scenario automatically add a response header to every http response and i want to do this in javalooking at srcplayfiltershelperssrcmainjavaplayfilters there are examples of actions which can be applied as annotations i would like to avoid adding addmyheader to every handlerlooking at the scala filters in srcplayfiltershelperssrcmainscalaplayfilters and gzipfilter specifically i see a clear mechanism but i am not familiar enough with scala to extrapolate to javaso where do i go from here,['java'] +558004,how to set the javalibrarypath in intellij idea could anyone please help how do i solve this errornative code library failed to loadjavalangunsatisfiedlinkerror no tsjni in javalibrarypathi am using idea ide as a first time and have been using resin 4037 as a server to test my work as soon as i start my lcoal server in debug mode it stays for approximately 12 mins and then suddenly it drops down and get thisconnected by giving me the above errori have set my windows environmental variable correctly and have also did the following in my ide intellij fileproject structureset global librariesa java path and b resin library pathcan any one please suggest me what am i doing wrong and how do i set native library in intellij idea to solve the mentioned errorany help would be appreciated also do correct me if i am doing something wrongthanks,['java'] +558094,how to clean old dependencies from maven repositories i have too many files in m2 folder where maven stores downloaded dependencies is there a way to clean all old dependencies for example if there is a dependency with 3 different versions 1 2 and 3 after cleaning there must be only 3rd how i can do it for all dependencies in m2 folder,['java'] +558114,parsing a txt file i am trying to parse a txt file which contains names in the formatmarypatricialindabarbaraelizabeththis is the code i wroteinclude stdioh names scoresint problem22 file f fopennamestxt r char name100 fscanff s name printfsn name mary fscanff s name printfsn name fscanff s name printfsn name patricia return 0int main problem22 return 0each alternate call to fscanf gives me a name while the other is wasted in fetching a comma i have tried several formats but i cannot figure out how to do it can anyone help me with the correct format,['c'] +558138,ios 7 proper ipad icons for iphone app we have an app for iphone only but often users install it on their ipads with ios7 and the asset groups it no longer respects our new ipad icon image sizes 76px and 152px if we do not use asset groups and have our old icons 72px it will load them but they clearly look scaled if we rename our 76px to icon72 and icon722x the same problem happensis there a proper way to get ios 7 sized ipad icons in an iphone only appthanks,"['iphone', 'ios']" +558157,i need to compare two very large collections with potentially missing elements i have come across a brick wall in a program i am writing for my workyou do not need to know the context specifically but long story short i have two collections of around 650k records eachlet us assume that collection a is the one i know is correct and collection b is the one i know is incorrectcollection b contains a complex object which has a property of the same type as the elements in collection a in other words it looks like a bit like this where t icomparableienumerabledatetime a collection of t elementsienumerablecomplex b collection of complex elementsclass complexdatetime public datetime time get set my issue is that i basically need to sequentially enumerate over a and see if the current element of a exists in a complex object in b if it does not exist then i need to create a complex object which will encapsulate that element amongst other thingsthe problem occurs when i realize that both lists are 650 elements long approx i cannot reduce the data set down i have to use these 650 right now i have used icollectioncontains and i tried a naive implementation of binary search but it just takes far too longhave you got any suggestions for meedit if it helps t implements icomparableedit2 some more contextthe ienumerable is retrieved from a datatable using linq to objects ienumerablecomplex set settbl wheredbobject dbobjecttscomparetodefaultdatetime 0 selectfuncdatarowcomplex function that wraps the datarow in a complex object just done to make debugging a little easier so we still have a large sample but small enough that it does not make me grow a beard take10 asenumerablecomplexfor sake of completeness in case this question gets archived and anyone else needs to sovle this issue my current implementation looked a bit like this bdataset bset new bdataset b lutableadapter adap new b lutableadapter adapfillbsetb lu ienumerablecomplex w3 bsetb wheredbobject dbobjecttscomparetodefaultdatetime 0 function that just wraps datarow into a complex object selectfuncdatarow complex just for sake of debugging speed take10 asenumerablecomplex listcomplex b bsetorderbyx xtimetolistcomplex get last first timestamps some of the timestamps in b are 01011011 for some reason so we do this check complex start bwherex xtime defaultdatetimefirst complex end blast listdatetime a new listdatetime roundseconds reduces seconds in a datetime to 0 datetime current roundsecondsnew datetimestarttimeticks while currentcomparetoroundsecondsendtime 0 aaddcurrent current currentaddtimespanfromminutes1 ienumerabledatetime times bselectx xtime var missing awheredt timescontainsdt foreach var dt in missing adapinsertdt 0 null 0 0 this has since been changed to listadd thanks to cosmin this issue is now resolved and the finished implementation is this list expected new list datetime current roundsecondsnew datetimestarttimeticks while currentcomparetoroundsecondsendtime 0 expectedaddcurrent current currentaddtimespanfromminutes1 consolewritelineexpecting 0 intervals expectedcount var missing bfindallmissingexpected x xtime ifmissingany return consolewriteline0 missing intervals missingcount foreach var dt in missing baddnew complex some values consolewritelinet inserted new record at 0 dt public static ienumerablebasic findallmissingbasic complexthis ienumerablecomplex complexlist ienumerablebasic basiclist funccomplex basic selector hashsetbasic incomplexlist new hashsetbasic foreach complex c in complexlist incomplexlistaddselectorc listbasic missing new listbasic foreach basic basic in basiclist if incomplexlistcontainsbasic missingaddbasic return missing,['c#'] +558185,query multiple collections with different fields in solr given the following single core queryshttplocalhostsolraselectindenttrueqrows100start0wtjsonhttplocalhostsolrbselectindenttrueqrows100start0wtjsonthe first query returns numfound40the second query returns numfound10i tried putting these together by httplocalhostsolraselectindenttrueshardslocalhostsolralocalhostsolrbqrows100start0wtjsonnow i get numfound50the only problem is a has more columns than b so the multiple collections request only returns the values of a is it possible to query multiple collections with different fields or do they have to be the same and how should i change my third url to get this result,"['mysql', 'sql']" +558278,slow updating of composer dependencies despite preferthist flag why does it take up to two minutes for my composer dependencies to update even when there have been no changesa heavily upvoted answer suggests adding the preferthist flag which i have appended to my commandphp composerphar update preferthistbut this makes no difference below is my composerjson file have i done something silly name mynamespacesymfony type project description require php 533 symfonysymfony 23 doctrineorm 22324dev doctrinedoctrinebundle 12 twigextensions 10 symfonyasseticbundle 23 symfonymonologbundle 23 sensioframeworkextrabundle 23 sensiogeneratorbundle 23 sensiothistributionbundle 22 mynamespacemybundle 10 repositories type vcs url httpusernamemybundlegit scripts postinstallcmd sensiobundlethistributionbundlecomposerscripthandlerbuildbootstrap sensiobundlethistributionbundlecomposerscripthandlerclearcache sensiobundlethistributionbundlecomposerscripthandlerinstallassets sensiobundlethistributionbundlecomposerscripthandlerinstallrequirementsfile postupdatecmd sensiobundlethistributionbundlecomposerscripthandlerbuildbootstrap sensiobundlethistributionbundlecomposerscripthandlerclearcache sensiobundlethistributionbundlecomposerscripthandlerinstallassets sensiobundlethistributionbundlecomposerscripthandlerinstallrequirementsfile config bindir bin minimumstability dev extra symfonyappdir app symfonywebdir web branchalias devmaster 23dev,['php'] +558295,unable to find webxml in netbeans 701 i want to upload a file to a server for which i am writing a servlet programthe location of the directory where the document would be uploaded should be fetched from a parameter in webxml i have not use webxml before and only know that it makes entries for each servlet i am not able to see this file in my web application project that i am making in netbeans please help me with this thank you,['java'] +558300,log a variable name and value i am looking for a way to quickly print a variable name and value while rapidly developingdebugging a small python script on a unix command linessh sessionit seems like a very common requirement and it seems wasteful on keystrokes and timeenergy to duplicate the variable names on every line which prints or logs its value ie rather thanprint my variable name my variable namei want to be able to do the following for str int list dictlogmy variable namelogilogmy stringlogmy listand get the following outputmy variable namesome stringi10my stringa string of wordsmy list1 2 3ideally the output would also log the function namei have seen some solutions attempting to use locals globals frames etc but i have not yet seen something that works for ints strings lists and works inside functions toothanks,['python'] +558345,how do you convert a python timestruct time object into a iso string i have a python objecttimestruct timetm year2013 tm mon10 tm mday11 tm hour11 tm min57 tm sec12 tm wday4 tm yday284 tm isdst0and i need to get an iso string20131011t115712zhow can i do that,['python'] +558386,how to close spuimodaldialog from button click in sharepoint i want to show confirmation dialog when user saves any document from editformaspx so i have written following javascript codefunction presaveaction var html documentcreateelement htmlinnerhtml input typebutton valuesubmit onclick javascriptsubmitdlg input typebutton valuecancel onclick javascriptclosedlg td tr tbody table var options title confirm width 400 height 200 showclose false allowmaximize false autosize false html html spuimodaldialogshowmodaldialogoptions function submitdlg spuimodaldialogcommonmodaldialogclosespuidialogresultokfunction closedlg spuimodaldialogcommonmodaldialogclosespuidialogresultcancelnow i have following queriessubmitdlg and closedlg is not fired when clicking on submit orcancelis this right way to submit form submitdlg method and cancel dialog closedlg method from modal dialog also this modal dialogbox should be only appeared if no validation errors while saving record means if any fieldvalue is required and we have not put any value then it should thisplay inbuilt red colored messagesthanks,['javascript'] +558411,specific device not receiving google cloud messaging notifications i have an application where i am implementing google cloud messaging notifications but in a specific device the messages do not arrive this device has the minimum requirements to use gcm android version 22 play store installed and an google account logged in the log i see that the device is receiving the registration id and sending to the backoffice where i have a list of devices registeredmy question is do i need to make extra configurations to make the device receive these notificationshere is the manifestxml version10 encodingutf8manifest xmlnsandroid packagebrcomtestegcm androidversioncode1 androidversionname1 usessdk androidminsdkversion7 androidtargetsdkversion18 usespermission androidnameandroidpermissioninternet usespermission androidnameandroidpermissionaccess network state usespermission androidnameandroidpermissionget accounts usespermission androidnameandroidpermissionwake lock usespermission androidnamecomgoogleandroidc2dmpermissionreceive permission androidnamecomexamplegcmpermissionc2d message androidprotectionlevelsignature usespermission androidnamecomexamplegcmpermissionc2d message application androidnametestegcm androidallowbackuptrue androidicondrawableic launcher androidlabelstringapp name androidthemestyleapptheme receiver androidnamebrcomtestegcmgcmbroadcastreceiver androidexportedtrue androidenabledtrue androidpermissioncomgoogleandroidc2dmpermissionsend intentfilter action androidnamecomgoogleandroidc2dmintentreceive category androidnamebrcomtestegcm intentfilter receiver service androidnamebrcomtestegcmgcmintentservice activity androidnamebrcomtestegcmhome androidscreenorientationportrait androidlabelstringapp name androidthemestylenotitle intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity applicationmanifest,['android'] +558461,execute php function with onclick i am searching for a simple solution to call a php function only when atag is clickedphpfunction removeday htmla href onclickremoveday classdeletebtndeleteaupdate the html and php code are in the same php file,['php'] +558464,does azure website support pinvoke to load native c dll i have found this says azure webworker role can load native c dll does azure website also support thismy site is a mvc site that pinvoke a native c dll which read files from local drive and does some calculations the reason i would prefer azure website is because it starts from freethanks,['c++'] +558476,letter spacing in ios i have the following codecancelbutton titlelabel setfontuifont fontwithnameproximanovaregular size15how would i set the letterspacing as well,"['ios', 'objective-c']" +558493,flaskmigrate not creating tables i have the following models in file listpullmodelspyfrom datetime import datetimefrom listpull import dbclass jobdbmodel id dbcolumndbinteger primary keytrue list type id dbcolumndbinteger dbforeignkeylist typeid nullablefalse list type dbrelationshiplisttype backrefdbbackrefjobs lazydynamic record count dbcolumndbinteger nullablefalse status dbcolumndbinteger nullablefalse sf job id dbcolumndbinteger nullablefalse created at dbcolumndbdatetime nullablefalse compressed csv dbcolumndblargebinary def init self list type created atnone selflist type list type if created at is none created at datetimeutcnow selfcreated at created at def repr self return job formatselfidclass listtypedbmodel id dbcolumndbinteger primary keytrue name dbcolumndbstring80 uniquetrue nullablefalse def init self name selfname name def repr self return listtype formatselfnamei call runpy init then runpy migrate then runpy upgrade and i see the migration file generated but its emptyempty messagerevision id 5048d48b21derevises nonecreate date 20131011 132543131937 revision identifiers used by alembicrevision 5048d48b21dedown revision nonefrom alembic import opimport sqlalchemy as sadef upgrade commands auto generated by alembic please adjust pass end alembic commands def downgrade commands auto generated by alembic please adjust pass end alembic commands runpyusrbinenv python coding utf8 from listpull import managermanagerrunlistpull init py coding utf8 pylint thisablemsgc0103 listpull module from flask import flaskfrom flaskextsqlalchemy import sqlalchemyfrom flaskextscript import managerfrom flaskextmigrate import migrate migratecommandfrom momclient import sqlclientfrom smartfocusrestclient import restclientapp flask name appconfigfrom objectconfigdb sqlalchemyappmigrate migrateapp dbmanager managerappmanageradd commanddb migratecommandmom sqlclientappconfigmom host appconfigmom user appconfigmom password appconfigmom dbsf restclientappconfigsmartfocus url appconfigsmartfocus login appconfigsmartfocus password appconfigsmartfocus keyimport listpullmodelsimport listpullviewsupdateif i run the shell via runpy shell and then do from listpull import and call dbcreate all i get the schemamarkrichmanmbpcodenhslistpull sqlite3 appdb loading resources from usersmarkrichmansqlitercsqlite version 3712 20120403 194307enter help for instructionsenter sql statements terminated with a sqlite schemacreate table job id integer not null list type id integer not null record count integer not null status integer not null sf job id integer not null created at datetime not null compressed csv blob primary key id foreign keylist type id references list type idcreate table list type id integer not null name varchar80 not null primary key id unique namesqlite unfortunately the migrations still do not work,['python'] +558516,javascript loop through all the elements returned from getelementsbytagname i am trying to loop through all the elements retruned from getelementsbytagnameinput using foreach any ideas why this does not work in ff chrome or iehtml head head body input typetext value input typetext value script function showresultsvalue index ar alertindex var input documentgetelementsbytagnameinput alertinputlength inputforeachshowresults script bodyhtmlthank you for your time,['javascript'] +558534,difference between char pchar pchar p char p some string creates a pointer p pointing to a block containing the stringchar p some string creates a character array and with literals in itand the first one is a constant declarationis it the same of twodimensional arrayswhat is the difference between char pchar pchar p i read a bit about this that char p creates an array of pointers so it has an overhead compared to char p for storing the pointer valuesthe first two declarations create constant arraysi did not get any run time error when i tried to modify the contents of argv in mainint argcchar argv is it because they are declared in function prototype,['c'] +558562,rails cucumbercapybara how to setretrieve cookies in tests i am implementing a lazy login feature my cucumber feature should describe it feature user log in scenario lazy login given i did not log out the last time i was on the site when i go to the homepage then i should automatically be logged in and these are my step definitionsgiveni did not log out the last time i was on the site do user factorygirlcreateuser visit new user session path fill inuseremail with useremail fill inuserpassword with test123 click buttonsign in capybarareset sessionsendwheni go to the homepage do visit root pathendtheni should automatically be logged in do fails here pageshould have contentlogoutendthis is what happens when a user logs in the cookiessignedauth token gets set this will be used by a before filter in my applicationcontroller so that users who open a fresh browser will be logged in automaticallyclass sessionscontroller devisesessionscontrollerdef create super if user signed in puts yes sessionuser id current userid current userremember me if current userremember tokenblank cookiessignedauth token value current userremember token domain mysitecom secure railsenvtest railsenvdevelopment puts current userremember token current userremember token puts cookies puts cookiessignedauth token endendendthis is the before filter in my applicationcontrollerdef sign in through cookie loggerinfo logging in by cookie puts logging in by cookie puts cookiessignedauth token problem this returns nil return true if current usernil if cookiesauth tokennil cookiesauth token user userfind by remember tokencookiessignedauth token return false if userblank sign inuser puts success return true else return false endendso the issue is that in the last step of my cucumber feature cookiessignedauth token returns nil i am guessing this is just a capybara thing so do i actually have to set a cookie in the test as opposed to using the one in my controller,['ruby-on-rails'] +558582,google calendar v3 returns 403 insufficient permission i have been trying to access calendar v3 api with a service account i have already added the scope from the admin console and shared my calendar with that service accounts email address i have also been accessing scope with the very same service account and it works finealso tried revoking access as said here why is google calendar api oauth2 responding with insufficient permissionall that and i am still gettingerror errors domainglobal reasoninsufficientpermissions messageinsufficient permission code403 messageinsufficient permissionam i missing something,['ruby-on-rails'] +558606,python except none are there any unexpected side effects of using except none the behavior i expect is that nothing will be caught by that clause which a few small tests seem to confirmhere is a rough outline of what i am trying to do when no argument is provided to the function exceptionsnone which creates the except none clause just want to double check that i am not going to catch something unexpected exceptions is exception or set of exceptions i want to do special processing fordef check exceptionsexceptionsnone try except exceptions as e,['python'] +558611,fine uploader to s3 bucket getting 405 method not allowed error i have been banging my head against the wall on this and am entirely stumped i am trying to use fineuploader to upload files directly to my amazon s3 bucket i have essentially copied the code from the fineuploadercom web page upload files directly to amazon s3 and the serverside php when i attempt to upload a file i see the post to the signature endpoint seems to work successfully but when it attempts to upload to s3 i get a 405 method not allowed errorhtmldoctype htmlhtml head meta charset utf8 link href rel stylesheet head body div id fineuploader div script src script script src jsuploaderjs script script documentreadyfunction fineuploaderfineuploaders3 debug true request endpoint uploadroughdragcom accesskey akiajl37usscv signature endpoint handlersuploadhandlerphp uploadsuccess endpoint indexphp iframesupport localblankpagepath blankhtml retry enableauto true defaults to false paste targetelement document promptforname true deletefile enabled true endpoint handlersuploadhandlerphp script body html php signature endpoint uploadhandlerphpphp php serverside example for fine uploader s3 maintained by widen enterprises note this is the exact serverside code used by the s3 example on fineuploadercom this example handles both cors and noncors environments handles delete file requests for both delete and post methods performs basic inspections on the policy documents and rest headers before signing them ensures again the file size does not exceed the max after file is in s3 signs policy documents simple uploads and rest requests chunkedmultipart uploads requirements php 53 or newer amazon php sdk only if utilizing the aws sdk for deleting files or otherwise examining them if you need to install the aws sdk see you can remove these two lines if you are not using fine uploaders delete file featurerequireincludesfunctionsphpuse awss3s3client these assume you have the associated aws keys stored in the associated system environment variablesclientprivatekey removed these two keys are only needed if the delete file feature is enabled or if you are for example confirming the file size in a successendpoint handler via s3s sdk as we are doing in this exampleserverpublickey removedserverprivatekey removed the following variables are used when validating the policy document sent by the uploaderexpectedbucketname uploadroughdragcom expectedmaxsize is the value you set the sizelimit property of the validation option we assume it is null here if you are performing validation then change this to match the integer value you specified otherwise your policy document will be invalid expectedmaxsize 50method getrequestmethod this first conditional will only ever evaluate to true in a cors environmentif method options handlepreflight this second conditional will only ever evaluate to true if the delete file feature is enabledelse if method delete handlecorsrequest only needed in a cors environment deleteobject this is all you really need if not using the delete file feature and not working in a cors environmentelse if method post handlecorsrequest assumes the successendpoint has a parameter of success associated with it to allow the server to differentiate between a successendpoint request and other post requests all requests are sent to the same endpoint in this example this condition is not needed if you do not require a callback on upload success if isset requestsuccess verifyfileins3 else signrequest this will retrieve the intended request method normally this is the actual method of the request sometimes though the intended request method must be hidden in the parameters of the request for example when attempting to send a delete request in a crossorigin environment in ie9 or older it is not possible to send a delete request so we send a post with the intended method delete in a method parameterfunction getrequestmethod global http raw post data this should only evaluate to true if the contenttype is undefined or unrecognized such as when xdomainrequest has been used to send the request if issethttp raw post data parse strhttp raw post data post if post method null return post method return serverrequest method only needed in crossorigin setupsfunction handlecorsrequest if you are relying on cors you will need to adjust the allowed domain here headeraccesscontrolalloworigin only needed in crossorigin setupsfunction handlepreflight handlecorsrequest headeraccesscontrolallowmethods post headeraccesscontrolallowheaders contenttypefunction gets3client global serverpublickey serverprivatekey return s3clientfactoryarray key serverpublickey secret serverprivatekey only needed if the delete file feature is enabledfunction deleteobject gets3clientdeleteobjectarray bucket postbucket key postkey function signrequest headercontenttype applicationjson responsebody file get contentsphpinput contentasobject json decoderesponsebody true jsoncontent json encodecontentasobject headersstr contentasobjectheaders if headersstr signrestrequestheadersstr else signpolicyjsoncontent function signrestrequestheadersstr if isvalidrestrequestheadersstr response arraysignature signheadersstr echo json encoderesponse else echo json encodearrayinvalid true function isvalidrestrequestheadersstr global expectedbucketname pattern expectedbucketname preg matchpattern headersstr matches return countmatches 0function signpolicypolicystr policyobj json decodepolicystr true if ispolicyvalidpolicyobj encodedpolicy base64 encodepolicystr response arraypolicy encodedpolicy signature signencodedpolicy echo json encoderesponse else echo json encodearrayinvalid true function ispolicyvalidpolicy global expectedmaxsize expectedbucketname conditions policyconditions bucket null parsedmaxsize null for i 0 i countconditions i condition conditionsi if issetconditionbucket bucket conditionbucket else if issetcondition0 condition0 contentlengthrange parsedmaxsize condition2 return bucket expectedbucketname parsedmaxsize stringexpectedmaxsizefunction signstringtosign global clientprivatekey return base64 encodehash hmac sha1 stringtosign clientprivatekey true this is not needed if you do not require a callback on upload successfunction verifyfileins3 global expectedmaxsize bucket postbucket key postkey if utilizing cors we return a 200 response with the error message in the body to ensure fine uploader can parse the error message in ie9 and ie8 since xdomainrequest is used on those browsers for cors requests xdomainrequest does not allow access to the response body for nonsuccess responses if getobjectsizebucket key expectedmaxsize you can safely uncomment this next line if you are not depending on cors headerhttp10 500 internal server error deleteobject echo json encodearrayerror your file is too big else echo json encodearraytemplink gettemplinkbucket key provide a timebombed public link to the filefunction gettemplinkbucket key client gets3client url bucketkey request clientgeturl return clientcreatepresignedurlrequest 15 minutesfunction getobjectsizebucket key objinfo gets3clientheadobjectarray bucket bucket key key return objinfocontentlengthamazon s3 cors configurationxml version10 encodingutf8corsconfiguration xmlns corsrule allowedoriginallowedorigin allowedmethodpostallowedmethod allowedmethodputallowedmethod allowedmethoddeleteallowedmethod maxageseconds30maxageseconds exposeheaderetagexposeheader allowedheaderallowedheader corsrulecorsconfigurationiam group security policy version20121017 statement effectallow actions3putobject resourcearnawss3uploadroughdragcom uploaderjs was captured from console responsefineuploader 3903 grabbed 1 dropped filesfineuploader 3903 received 1 files or inputsfineuploader 3903 submitting s3 signature request for 0fineuploader 3903 sending post request for 0post 200 ok 195ms fineuploader 3903 sending upload request for 0post 405 method not allowed 559ms networkerror 405 method not allowed fineuploader 3903 received response status 405 with body htmlheadtitle405 method not allowedtitleheadbodyh1405 method not allowedh1ullicode methodnotallowedlilimessage the specified method is not allowed against this resourceliliresourcetype objectlilimethod postlilirequestid 3493fe605b461eaflilihostid hdxmtsphufy6ldih1nsp0oykldvtc3xkfrriadw66gmamsf53z3wyscworcw2liulhrbodyhtmlfineuploader 3903 waiting 5 seconds before retrying breakoutjpgfineuploader 3903 detected valid cancel retry or delete click event on file breakoutjpg id 0fineuploader 3903 cancelling 0the software looks amazing but i just cannot get past this any help is appreciated,['php'] +558677,onresize for div elements visual studio highlighted my onresize attribute of my div tag and says that it is not a valid attribute for html5 is this true what should i use instead it seems kind of silly that this would be the case,"['javascript', 'html']" +558682,how to convert javautildate objects into calendar objects i am using the prettytime java library for a variety of datetime processing in my java app such as converting mysql format datesdatetime strings into java dates or the vice versahowever i see that dategetyear dategetmonth etc are all deprecated and it says to use calendar instead but prettytime only returns its results as date objects and i see no way to convert the date objects into calendar objectsin the documentation for calendar the only mention i see of date is the method settimedate date but the method name is ambigious and the documentation is not clear on what calling this method would actually do obviously i cannot just do calendarset dategetyear dategetmonth etc as those methods of date are deprecatedso how can i convert a given date object to calendar,['java'] +558710,uilocalnotification custom sound is not playing in ios7 i am using uilocalnotification in an applicationin the application there are two sounds which are played conditionally i have applied proper conditions for thembut when i install the application and run it on an ios 7 device then it fires the local notification but a sound is not playing in the applicationcode is given below to set the notification uilocalnotification localnotification uilocalnotification alloc init if localnotification nil return localnotificationfiredate pickerview date localnotificationtimezone nstimezone defaulttimezone if alarm number 1 localnotificationalertbody nsstring stringwithformatfirst alarm else localnotificationalertbody nsstring stringwithformatsecond alarm localnotificationalertaction ok nsstring message nsstring allocinitwithstring ifalarm number 1 localnotificationsoundnamealarm 1mp3 message first alarm scheduled else localnotificationsoundnamealarm 2mp3 message second alarm scheduled localnotificationapplicationiconbadgenumber 1 specify custom data for the notification nsstring alarmstring if alarm number1 alarmstring nsstring stringwithformatfirst alarm else alarmstring nsstring stringwithformatsecond alarm nsdictionary infodict nsdictionary dictionarywithobjectalarmstring forkeyalarmfor localnotificationuserinfo infodict schedule the notification uiapplication sharedapplication schedulelocalnotificationlocalnotification localnotification releasewhat i have checked for is the sound setting in the settingsnotification centre app for my aplease go through 1st to 3rd image to see what i have checked 1 notification center2 application3 sound is off hereso to enable this i have checked inter app audio at capabilities in targets of the application and it was off as shown in the image belowcapabilities in interapp audiothen i have changed it to on and it looks like shown in the image belowyet it still does not play any sound in ios 7 devicesdoes anybody have any idea about why is it not working it would be a great helpthanks,"['iphone', 'ios']" +558866,how to add a method to an activerecord collection i would like to add a method to all collections for a specific model let us say i want to add the method my complicated averaging method to the weatherdata collectionsweatherdataalimit3my complicated averaging methodstationfirstweatherdatamy complicated averaging methodwhat is the best way to do this at the moment the only way i have found is like thisclass weatherdata activerecordbase def selfmy complicated averaging method weighted average 0 relationeach do post do something complicated weighted average end return weighted average endendis this a good way for adding a method to a collection is there a better supported way to do this,['ruby-on-rails'] +558917,uicollectionview repeats cell i have a uicollectionview where i thisplay a grid of images downloaded from the internet i am using sdwebimage to load the images the problem i am facing is that when i scroll through the uicollectionview sometimes the cells repeat themselves thisplaying the same image but when the cell is scroll out of view and then brought back it has the right image setuicollectionviewcell collectionviewuicollectionview collectionview cellforitematindexpathnsindexpath indexpath nsstring cellidentifier gallery cell gallerycell cell if cellnil cell gallerycell selfflowcollection dequeuereusablecellwithreuseidentifiercellidentifier forindexpathindexpath imageitem dets selfimagelist objectatindexindexpathrow nsurl mainimageurl nsurl urlwithstringdetssmallimageurl cellimagecontentmode uiviewcontentmodescaleaspectfill cellimageclipstobounds yes cellimage setimagewithurlmainimageurl placeholderimagenil return cellhas this happened to anyone else would highly appreciate any pointers,"['iphone', 'ios']" +558932,ask for permission to allow access to contacts ios i am importing all the native address book contacts into my app currently the alertview to ask for permission to allow access to the contacts is done at the launch of the app how do i change it so permission is asked elsewhere in the app at the click of a button just like instagram see this picture,['ios'] +558970,send message to specific contact through whatsapp from another app is it possible to send message to a specific contact through whatsapp directly from another app i know the contact id i do not want to open whatsapp via intent i just want to send the message directly like normal smsi have tried other solutions posted on stackoverflow but they are not working for me,['android'] +558982,when is fragmentpageradapters getitem called i am writing an application that uses the fragmentpageradapter the fragments in the adapter need to be updated according to outside data but that does not happen i noticed that the fragment classes are only instantiated once in the getitem function overridepublic fragment getitemint position tabinfo info mtabsgetposition return fragmentinstantiatemcontext infoclssgetname infoargseven if i delete the class and use a new one nothing helps this method is only called once the first time that the tab is populated and then never again anyone has an idea why thanks,['android'] +558995,java writing my own split string method i need to be able to write my own split string method so that input likestring test1 mysplitabcdefg systemoutprintlnarraystostringtest1will print ab cd efg to the consoleso far i have got it to split like that but my way leaves awkward spaces where 2 delimiters are in a row or a delimiter is at the start of the inputpublic static string mysplitstring str string regex string storesplit new stringstrlength char compare1 compare2 int counter 0 initializes all the string values to so when the string and char concatonates null does not appear forint i0 istrlength i storespliti puts the str values into the split array and concatonates until a delimiter is found then it moves to the next array index forint i0 istrlength i compare1 strcharati compare2 regexcharat0 ifcompare1 compare2 storesplitcounter strcharati else counter storesplitcounter strcharati counter return storesplitwhen i use that method in my test main i get the output ab cd efg so i am lost on how to fix the spacing of it all and i will also need to be able to allow multiple delimiters which my code currently does not handlealso i know this code is really sloppy at the moment just trying to lay down the concepts before the optimization,['java'] +559039,invalid image path ios7 icons when deploying to appstore via application loader i am receiving an error whenever i attempt to send my application in for review it appears to be stating the ios7 icons for my app have invalid paths but the icons work in the simulator and on a dev device it is also stating that it is unable to authenticate the packagei have attempted to update the paths in the infoplist file but the issue persistspackage summary1 packages were not uploaded because they had problems varfoldersx34cy637515hs8ct3096ssqg r0gnt725271208itmsp error messages apples web service operation was not successful unable to authenticate the package 725271208itmsp error itms90 invalid image path no image found at the path referenced under key cfbundleicons icon152 at softwareassetssoftwareasset mzitmspsoftwareassetpackage error itms90 invalid image path no image found at the path referenced under key cfbundleicons icon76 at softwareassetssoftwareasset mzitmspsoftwareassetpackage error itms90 invalid image path no image found at the path referenced under key cfbundleicons icon120 at softwareassetssoftwareasset mzitmspsoftwareassetpackage,['ios'] +559105,c pthread two threads read a global variable if there are two threads that just read a global variable is it necessary to use mutex to lock and unlock the global variable,['c++'] +559137,what cmake variable is used to set c standard library in xcode i have a pure c11 dll no dependencies of any kind i have been able to compile on linux and windows for some time now using cmake to generate the project files and makemsvc to compile in each respective native systemi want to compile on osx now and i have been having a lot of problems getting cmake to set the correct project settings in xcode to compile the dllsoftware versionsxcode v50cmake v2812the relevant cmake script code set output directory if apple osxifcmake system name matches darwin messagecmake has detected a osx system building for xcode setcmake xcode attribute gcc version comapplecompilersllvmclang1 0 setcmake xcode attribute clang cxx language standard c0x setcmake xcode attribute clang cxx library libc setcmake cxx flags cmake c flags stdc0x stdliblibc ifcmake build type matches release setlibrary output path cmake current source dirbinosxrelease endifcmake build type matches release ifcmake build type matches debug setlibrary output path cmake current source dirbinosxdebug endifcmake build type matches debugendifcmake system name matches darwinhowever the settings do not correctly come through into the xcode project fileyou can see that the cmake commands make their way into the other c flags area but xcode will still fail to compile however if i change the c standard library variable to libc it will compile finenote i could post the compile error logs however i think that the above correctly identifies the root cause i just need to know what cmake command actually sets the correct xcode property above,['c++'] +559200,what can i do to make this loop run faster i have this simple loopint array new int10int sum 0for int i 0 i arraylength i sum arrayii compared its performance with its c version i though that the performance should be near the same because it is very simple code and the range checks are omitted in that case but it turned out that the c version is almost three times faster so i have implemented c unsafe version but the performance was even worseresharper suggests to convert the loop to linq expression like thissum arraysumthat code is many times slower than the original loop in ccould someone tell me if there is something more that i can do to improve the performance of this loop without compiling it to 64 bit version which is two times fasterall test where made on 32 bit release version and run without debuggeredit small correction 64 bit version is two times faster with doubles not ints,['c#'] +559207,httpcomponents poolinghttpclientconnectionmanager maxperroute and maxtotal can someone please explain to me what setmaxperroutemax and setmaxtotalmax do in reference to httpcomponents poolinghttpclientconnectionmanager,['java'] +559212,creating multiple nested forms using simple form and rails 4 i am trying to create a simple app with the following modelscategories has many questions has many answersi have the following code for creating categories questionscategories formhamlhtml simple form forcategory do f ferror notification finput title label category title fsimple fields for questions categoryquestionsbuild do q qinput content label question content fbutton submitand i am using all the same code for creating questions answersquestions formhamlhtml i have all the relations strong parameters nested attrs and controllers configured it works just fine for metwo questionshow to create multiple questions in categories formhamlhtmlhow to create category multiple questions multiple answers per each question at oncein categories formhamlhtmli have spent a few hours trying to figure out how to accomplish the second one and all the info i was able to find is related to rails 30 and form for none of them worked for methe most straightforward solution here should be something like simple form forcategory do f ferror notification finput title label category title fsimple fields for questions categoryquestionsbuild do q qinput content label question content qsimple fields for answers qquestionsbuild do a ainput content label answer content fbutton submitbut it gives meundefined method questions for simpleformformbuilderwhat am i missing here,"['ruby-on-rails', 'ruby']" +559224,splitting ngrepeat every 3 items using angularjs i am iterating over a json object containing an array of event objects containing an array of competition objectsi wish to show each event in a table and then each competition in a td but only three cells per rowi am using ngrepeat to return a list of tables for each event but i am having trouble with splitting the competitions into a new tr every three tdsaside from rebuilding my own massive object from the json what is the best way to do what i am describing in angularcurrent viewtable ngrepeatlisting in listings tr th colspan3listingnameth tr tr td ngrepeatcompetition in listingcompetitions competitionid competitionname td trtabledesired outputtable tr th colspan3event nameth tr tr tdcompetition id competition nametd tdcompetition id competition nametd tdcompetition id competition nametd tr tr tdcompetition id competition nametd tdcompetition id competition nametd tdcompetition id competition nametd trtablecontrollerappcontrollereventsctrl function scope http scopeloading true httpgetscriptsjsoneventsjsonthenfunction response var listings responsedataevents scopelistings listings eventsjsonevents id 418 name et ullamco competitions id 933 name qui in deserunt occaecat et starttime 1381092189 id 853 name eu enim ex incididunt do starttime 1380708266 id 5738 name ad est ut aliquip et starttime 13813623 id 7599 name sit ex voluptate aliqua dolor starttime 1381284106 id 7481 name laborum consequat deserunt do aliqua starttime 1380874273 id 3441 name amet reprehenderit sint sunt proident starttime 1380554850 id 1959 name ullamco minim minim in voluptate starttime 1380651981,['javascript'] +559269,how to pad with zeros a tensor along some axis python i would like to pad a numpy tensor with 0 along the chosen axis for instance i have tensor r with shape 432 but i am only interested in padding only the last two axis that is pad only the matrix is it possible to do it with the oneline python code,['python'] +559316,how to add dots to uilabel if text does not fit frame i have a cell with multiline uilabels but when the texts label does not fit the frame no dots are shown how can i fix this,"['ios', 'objective-c']" +559361,whats the difference betwee actor model and reactor pattern in python model the project is called pulsar pattern the projects are twisted and tornadowhats the difference in the theory and practice,['python'] +559364,why does not the null coalescing operator work in this situation i am getting an unexpected nullreferenceexception when i run this code omitting the filesystemhelper parameter and therefore defaulting it to nullpublic class gitlog filesystemhelper filesystem summary initializes a new instance of the see crefgitlog class summary param namepathtoworkingcopythe path to a git working copyparam param namefilesystemhelpera helper class that provides file system services optionalparam exception crefargumentexceptionthrown if the path is invalidexception exception crefinvalidoperationexceptionthrown if there is no git repository at the specified pathexception public gitlogstring pathtoworkingcopy filesystemhelper filesystemhelper null thisfilesystem filesystemhelper new filesystemhelper string fullpath filesystemgetfullpathpathtoworkingcopy argumentexception if path invalid if filesystemdirectoryexistsfullpath throw new argumentexceptionthe specified working copy directory does not exist gitworkingcopypath pathtoworkingcopy string git filesystempathcombinefullpath git if filesystemdirectoryexistsgit throw new invalidoperationexception there does not appear to be a git repository at the specified location when i single step the code in the debugger after i step over the first line with the operator then filesystem still has the value null as shown in this screen snip stepping over the next line throws nullreferenceexceptionthis is not what i expected i am expecting the null coalescing operator to spot that the parameter is null and create a new filesystemhelper i have stared at this code for ages and cannot see what is wrong with itresharper pointed out that the field is only used in this one method so could potentially be converted to a local variable so i tried that and guess what it worked so i have my fix but i cannot for the life of me see why the code above does not work i feel like i am on the edge of learning something interesting about c either that or i have done something really dumb can anyone see whats happening here,['c#'] +559458,how to open a web page automatically in full screen mode how do i open a web page automatically in full screen modei am looking for a solution to open an web page automatically in full screen mode without expecting user to users press f11 or any other browserspecifc key i have searched a lot but i just could not find a solutionis there a script or library or browser specific api available to help me achieve this,['javascript'] +559469,adding event to calendar very slow i am simply wanting to add an event to the devices calendari am using weak programviewcontroller weakself self ekeventstore store ekeventstore alloc init store requestaccesstoentitytypeekentitytypeevent completionbool granted nserror error if error nslogekeventstore error error if granted nslogekevent event ekevent event ekevent eventwitheventstorestore eventtitle weakselfprogramtitle eventlocation weakselfprogramlocationpublic eventstartdate weakselfprogramstarttime eventenddate weakselfprogramendtime event setcalendarstore defaultcalendarfornewevents nserror err nil store saveeventevent spanekspanthisevent commityes errorerr if err uialertview alertview uialertview alloc initwithtitlecalendar error messageerrlocalizeddescription delegateself cancelbuttontitleok otherbuttontitlesnil alertview show else uialertview alertview uialertview alloc initwithtitleadded messagecalendar event added delegateself cancelbuttontitleok otherbuttontitlesnil alertview show and in ios 6 it can take 67 seconds iphone 4 and on ios 7 on an iphone 5s it takes 10 seconds is this normal behaviour if not what am i doing wrong,"['ios', 'objective-c']" +559484,cmake automatically parsing dependencies of precompiled header as of yet at least to my knowledge there is no standard way in cmake to specify the addition of a precompiled header pch to a project in a crossplatform manner because the way pchs are handled by c compilers is very different among vendors for g this is usually this is worked around by simply adding a custom command which takes care of invoking the compiler with the appropriate input and has it generate the pch my current problem is that cmake will not parse the dependencies of the dependencies you specify for the custom command for instance assume the following structurepchh dependah dependbh only providing pchh as a dependency will lead to the generation of the appropriate target in the corresponding makefile which tracks changes to pchh however cmake does not parse the includes inside pchh and will therefore not recognize changes to dependah and dependbh this extends furhter if there are dependencies for dependsah and so onnote i am aware that the fact that pch dependencies can and do change regularly puts the whole process in question however this is just the way it is and i cannot really do anything about itsince the task is not too hard there are a couple of obvious ideas that come to mindsolution a enter all the dependencies by hand obviously this works but is tedious as hell and does not scale at allsolution bif possible write a cmake function that automates the process and parse the includes manuallysolution c do something similar using a different language for instance python and just provide cmake a list of dependencies to add to the custom commandsolution d use gccgs feature to parse and print out the dependency tree of the pch and parse the output to extract the list of dependenciesmy question is does anyone know a more convenient and faster way to get this done,"['c++', 'c']" +559488,splines in pythonocc this question is about how to use splines in general in pythonocc there are two part to this questionhave found out that i can create a spline by array arrayappendgp pnt2d 00arrayappendgp pnt2d 12arrayappendgp pnt2d 23arrayappendgp pnt2d 43arrayappendgp pnt2d 55pt2d list point2d list to tcolgp array1ofpnt2darrayspl1 geom2dapi pointstobsplinept2d listcurvethisplaythisplayshapemake edge2dspl1 updatetrueand i expect that the bspline can be calculated by bspl1 geom2dapi pointstobsplinept2d listbut how do i get the derivative of the bsplinethe knots of the bsplineis the knots the pt2d listthe control points of the bsplinethe coefficients of the splineand how do i remove or add knots to the bsplinewhen loading a cad drawing stp file in pythonocc like thisfrom occ import topods stlapishape topodstopods shapestl reader stlapistlapi readerstl readerreadshapestrfilenamethisplaythisplayshapeshapehow do i get the data out of the shape like knot bspline and coefficientsbest regards,['python'] +559509,embed plotly graph into a webpage with bottle hi i am using plotly to generate graphs using python bottle however this returns me a url likei want to paste the entire graph into my webpage instead of providing a link is this possiblemy code isimport osfrom bottle import run template get post requestfrom plotly import plotlypy plotlyusernameuser keykeygetplotdef form return h2graph via plotlyh2 form methodpost actionplot name input namename1 typetext age input nameage1 typetext br name input namename2 typetext age input nameage2 typetext br name input namename3 typetext age input nameage3 typetext br input typesubmit formpostplotdef submit name1 requestformsgetname1 age1 requestformsgetage1 name2 requestformsgetname2 age2 requestformsgetage2 name3 requestformsgetname3 age3 requestformsgetage3 x0 name1 name2 name3 y0 age1 age2 age3 data x x0 y y0 type bar response pyplotdata url responseurl filename responsefilename return congrats view your chart here a hrefview graphaif name main port intosenvirongetport 8080 runhost0 portport debugtrue,['python'] +559535,move semantics for stdvector member i want to ensure that i properly understand this i ask it here since it i have not fund it spelled out explicitlyfor example i have a triangle mesh class that is basically built like thisclass meshpublic struct face unsigned int a unsigned int b unsigned int c private stdstring file stdvectorglmvec3 vertices stdvectorglmvec3 normals stdvectorglmvec2 texcoord stdvectorface faces since the data in the mesh can get quite large i want to implement proper move semantics for pointer types i fully understand this but to trigger the rvalue constructor i need to use move right for example the rvalue constructor will bemeshmeshmesh other filestdmoveotherfile verticesstdmoveothervertices normalsstdmoveothernormals texcoordstdmoveothertexcoord facesstdmoveotherfaces note before someone points out the obvious the application uses in many places a share ptr but i do not want to artificially restrict the use of the class,['c++'] +559556,weird compiler error cannot convert parameter from int to int what on earth is going on herei am trying to create a pair of an int and a string and i can create the pair if i use magic values but cannot seem to pass in variablesstdvectorstdpairint stdstring num textstdstring text smegint num 42 works finenum textpush backstdmake pairint stdstring42 stdstringsmeg cannot convert parameter 2 from stdstring to stdstring num textpush backstdmake pairint stdstring42 text cannot convert parameter 1 from int to int num textpush backstdmake pairint stdstringnum stdstringsmeg cannot convert parameter 1 from int to int num textpush backstdmake pairint stdstringnum text works fine againnum textpush backstdmake pairint stdstring42 stdstringsmegi am using vs 2012 and have pasted in some code that was written in vs 2008 cannot imagine that would have anything to do with it but there was no problem in the original 2008 codei kind of feel a bit dumb for not being able to workout what is going on here but what can i say i just do not get it,['c++'] +559565,why menuitemcompatgetactionprovider returns null i tried to use androidsupportv7widgetshareactionprovider on actionbar in my app so i followed the example from android document but got some issues heres my menu xmlxml version10 encodingutf8menu xmlnsandroid xmlnsmyapp item androidididaction share androidorderincategory100 androidicondrawableic action share androidtitlestringaction share myappshowasactionifroom myappactionproviderclassandroidsupportv7widgetshareactionprovider menuheres my code to create the share action buttonoverridepublic void oncreateoptionsmenu menu menu menuinflater inflater inflaterinflatermenushare menu menuitem shareitem menufinditemridaction share shareactionprovider mshareactionprovider shareactionprovidermenuitemcompatgetactionprovidershareitem mshareactionprovidersetshareintentgetdefaultintent superoncreateoptionsmenumenu inflatermy question ismenuitemcompatgetactionprovidershareitem always returns null for me whys thatwhen i comment those lines the share button appears on the bar but does nothing while clicking how to fix itif question 1 cannot be solvedbtw i checked codes of menuitemcompatgetactionprovider it looks like this method will check if the menu item implements supportmenuitem interface and returns fail if it is not how could i deal with it,"['java', 'android']" +559591,ruby on rails route for wildcard subdomains to a controlleraction i dynamically create urls of the form usernameusersexamplecombobusersexamplecomtimusersexamplecomscottusersexamplecomall of usersexamplecom requests should go to a particular controlleraction how do i specify this in routesrball other requests to wexamplecom go to the normal list of routes in my routesrb fileupdate i watch the railscast about subdomains and it showed the following bit of code which would seem to be exactly what i need changed the controller and subdomainmatch to my controllershow constraints subdomain usersthe problem is it only matches the root url i need this to match every possible url with a users subdomain so obviously i would put it at the top of my routesrb file but how do i specify a catchall route is it simply or,['ruby-on-rails'] +559623,playstore subscriptions testing strategy scenarioi am on the verge of completing my google playstore inapp billing implementation i am using a monthly or yearly subscription in order to charge my consumersproblem i cannot seem to find a way to remove a subscription from active state since cancellation simply stops the billing from occurring this does not allow qa to thoroughly test the purchase procedure without creating an account for each test or waiting until the subscription period endsquestion have i missed or am wrong about something if so what is it if not what should be done to allow qa to do proper testing,['android'] +559661,zbar sdk dont work for armv7sipad 4 ios 7 i replace zbar sdk in my project and faced with the problemld file is universal 3 slices but does not contain an armv7s slice volumeszbarsdkzbarsdklibzbara file volumeszbarsdkzbarsdklibzbara for architecture armv7sclang error linker command failed with exit code 1 use v to see invocationi downloaded sdk from ps in simulator it work,['ios'] +559677,detached dom tree with angularjsjquery so i have a pretty simple angular application and i am trying to figure out what is causing detached dom trees to show up in the chrome profiler so for example when you load up this pagei get 2 detached dom trees one with 2 entries and another with 3 entries this page does not use any custom directives so it must be something with either angular or jquery however i just do not see anything that would cause these detached dom treesthe issue becomes even bigger if you click on the projects link and do another profile there are a lot more detached dom trees and entries in them so i am hoping if i can fix this very simple example it will cascade throughout the rest of the applicationalso note that i am using uirouter however i have tried this same thing with angulars default router with the same results even the todomvc angular app which does not use jquery has detached dom treesupdatei have pulled jquery out of the application and on my simple page all but one detached dom tree goes away and that one is from angularjs which i know where it is when i try it for a more complex page with a custom directive that has a templateurl and does transclusion removing jquery does not seem to helpi am not sure if jquery is the actually issue or maybe part of it or how angular using jqueryjqlitedoes anyone know if there is a existing detached dom tree known in jquery 110x,['jquery'] +559769,how can i use constraints autolayout with to specify a different layout on landscape vs portrait without using code i have an ipad app that features a login screen with the login controls contained within a uiview when the ipad is in portrait orientation i have the login uiview near the bottom and center of the app pretty much right above where the keyboard will be and the company logo is in a uiimageview centered across the top i am using autolayout constraints to keep the company logo gravitated to the top and right and the login uiview gravitated to the bottom and rightwhen i rotate this to landscape the effect is something like thisi want it to look like this so i want the two elements to be sidebyside and i want the login uiview to be further to the right the amount of spacing to the right of the uiview when in portrait mode is greater than i want for landscape mode and the thistance from the bottom is less than i want for landscape mode i could handle this via center in container instead but that would also not work in landscape modei have used the technique detailed in this post to make things be side by side when in landscape mode but i do not believe it will suffice here because i want the layouts within the views to also be different on rotation i can think of ways to pull this off programmatically but i cannot imagine this is all that unique a need so is there some way using just constraints in ib to pull this off some this is what constraints in ib were designed for way possibly dealing with priorities or do i just need to pull this off in code,['ios'] +559810,pythonic way of writing a library function which accepts multiple types if as a simplified example i am writing a library to help people model populations i might have a class such asclass population def init self t0 initial growth selft0 t0 selfinitial initial selfgrowth growthwhere t0 is of type datetime now i want to provide a method to determine the population at a given time whether that be a datetime or a float containing the number of seconds since t0 further it would be reasonable for the caller to provide an array of such times if so i think it reasonable to assume they will all be of the same type there are at least two ways i can see to accomplish thismethod for each typedef at rawself t if not isinstancet collectionsiterable t numpyarrayt return selfinitialnumpyexpselfgrowthtdef at datetimeself t if not isinstancet collectionsiterable t t dt numpyarrayt1selft0total seconds for t1 in t return selfat rawdtuniversal methoddef atself t if isinstancet datetime t tselft0total seconds if isinstancet collectionsiterable if isinstancet0 datetime t t1selft0total seconds for t1 in t else t nparrayt return selfinitialnumpyexpselfgrowthteither would work but i am not sure which is more pythonic i have seen some suggestions that type checking indicates bad design which would suggest method 1 but as this is a library intended for others to use method 2 would probably be more usefulnote that it is necessary to support times given as floats even if only the library itself uses this feature for example i might implement a method which root finds for stationary points in a more complicated model where the float representation is clearly preferable thanks in advance for any suggestions or advice,['python'] +559860,database access through a static class from a number of threads i am a self taught c programmer i have missed some bits here and there when it comes to having a very thorough understanding about things and now i have stumbled across something i have not been able to find an answer to on so i am trying to get a better understanding about thread safety in c but let me first specify the contexti am currently developing a windows service which goes off and does some monitoring work based on a schedule which resides in a sql server database it is going to monitor some servers by making http requests to a number of client servers a client installed on those servers will respond with the requested informationas this monitor service might get quite busy i have set it up to stick every scheduled instruction in a new thread when it is scheduled to do the work this is to make sure my timer keeps ticking along nicely ready to fire off the next instruction to the next client server a part of each instruction is that is has to log in the database that it has executed successfully and what the response was and so on now i have in my monitor service a public static class logger i believe this is handy as i can now easily call it this way loggerlog whenever i need to log things this logging happens in this class through ef into the sql server databaseto me this all sounds really cool and i am quite happy with how it all works but i have not load tested anything as of yet the problem i have with all of this is that my brain tells me that since my logger class is static and according to my understanding therefore it is only instantiated once if more than 1 thread tries to call loggerlog at the exact same time bad things will happen to my monitor serviceis there someone here who can enlighten me is my thinking right or wrong and if you know the answer please explain it clearly because i would love to understand it updatethanks for responses up till now things are getting clearer as people are asking more details about the log method and i am not at my development pc at the moment i will try to explain the way it works in a bit more detailall the log method does is add a record to the sql database through ef based on data from some previously instantiated objects which are passed in to the method as parameters the database context is instantiated as a static private variable on the static class the reason for this is so that i do not have to keep putting using statements in my overloads,['c#'] +559899,is there one managed heap per clr or per process as far as i know before net 40 things were simple one process could only host one clrbut from version 40 a process can host more than one clrin this case i guess there is one heap per clr because each clr has its own state and its own gc with its own way of managing memory and its own collection cycles so sharing memory just seems impossible1 could you confirm that this is conclusively the case or is it more subtle2 are two clrs hosted in the same process strictly isolated or can they share anythingparticularly if they have the same version could they be aware of each otheri guess the answers are yes and yes isolated but i would like to be surethanks for any insight,['.net'] +559932,armadillo c matrix initialization from array i am new to using armadillo and could not get the following in spite of trying searching quite a bitthere are two huge dynamic arrays not vectors that i need to perform correlation on i resolved to use armadillo for this i understand how to initialize armamat using vectors but can i use arrays to do so i understand not as i do not see any mention in the documentationi am trying to avoid the use of vectors for internal design reasonsi tried manually initializing each element using sample arrays as a dumb but starting point something like the following code wouldnt workusing namespace stdusing namespace arma mat asize 1 bsize 1forint i 0 i size i a vi endr b ci endrcout a endlaprintcout b endlbprintfor the input arrays v 1 2 0 1 9 and c 0 5 1 2 5 the output will bea 0b 50which is understandableany work around for initializing armamat or armacolvector with arrays thanks in advance,['c++'] +559955,infinite scrollable div with ajax loaded content i want to implement a technique called scrollable div in gwt what i am trying to do is the following if a user is on my page he can only see the viewport green box in the image all dom elements that are in this viewport are visible to the user on page load alle dom elements that are not on the viewport have not been loaded after a page has been loaded on page load blue boxes in the image if the user drag and move the viewport all dom elements become visible which come onto the viewport if they are on the viewport they will be loaded via ajaxthe user can zoom in and out the viewport to make it bigger and smaller also if elements that are invisible to the user and thus not loaded yet become visible than they have to be loaded via ajax and thisplayed on the viewporthow do i have to implement this with gwtif the user loads the page it looks like the following image the user can drag and move the viewport to 8 directions these are top top right right right bottom bottom bottom left left and top left the following image shows a movement to the leftwhen the viewport moves new content should be loaded with ajaxthe viewport can also be zoomed in in this case also new content should be loadedthe viewport can also be zoomed out note that the viewport must be of fixed dimensions only the content should be zoomable,"['javascript', 'html', 'css']" +559989,python open file from zip without temporary extracting it how can i open files from a zip archive without extracting them firsti am using pygame to save thisk space i have all the images zipped upis it possible to load a given image directly from the zip file for examplepygameimageloadzipfileimg 01,['python'] +560001,angular js dynamic ngsrc not working in 120rc2 i am trying to implement a video element in an angular js app and the ngsrc would not read the scope variablei am using 120rc2doctype htmlhtml ngappngviewhead script srcscript script var app angularmodulengview function mycontrolscope scopefile 1234mp4 script head body ngcontrollermycontrol video controls ngsrcfilevideo bodyhtmlif i use a much older version angularjs lib it works cdnjscloudflarecomajaxlibsangularjs103angularminjs worksis this a bug in the latest release or has it been thisabled on purpose what is the work around,['javascript'] +560028,why string intern method as explained in this when should we use intern method of string on string constants post that string literals are automatically pooled but for object constructed using new are not so for that intern method is used but even if we use intern method a new object will be created then what is the use of intern methodstring s examplestring s1 new stringexample will create new objectstring s2 new stringexampleintern this will create new object but as we are calling intern we will get reference of pooled string examplenow systemoutprintlns s1 will return falsesystemoutprintlns s2 will return truesystemoutprintlns1 s2 will return falseso whats the use of intern methodediti understood the working of intern method but my question is why intern method is there because to call intern method we must create string object using new which will create new instance of stringstring s3 new stringexample again new objectstring s4 s3internsystemoutprintlns3 s4 will return falseso calling intern method will not point s3 to pooled string intern method will return reference to pooled stringalso calling intern will push the string into pool if it is not already pooled so does that mean every time i call intern on any string will be pushed to pool,['java'] +560041,javalangunsupportedoperationexception while dealing with tab widget i am implementing swipe able tabs in my app i have implemented one demo for this below is my codeactivity mainxmlxml version10 encodingutf8tabhost xmlnsandroid androididandroididtabhost androidlayout widthmatch parent androidlayout heightmatch parent linearlayout androidlayout widthmatch parent androidlayout heightwrap content androidorientationvertical tabwidget androididandroididtabs androidlayout widthfill parent androidlayout heightwrap content framelayout androididandroididtabcontent androidlayout widthmatch parent androidlayout heightmatch parent framelayout androidididtab1 androidlayout widthmatch parent androidlayout heightwrap content androidvisibilitygone framelayout androidididtab2 androidlayout widthmatch parent androidlayout heightwrap content androidvisibilitygone framelayout androidididtab3 androidlayout widthmatch parent androidlayout heightwrap content androidvisibilitygone framelayout androidididtab4 androidlayout widthmatch parent androidlayout heightwrap content androidvisibilitygone framelayout androidsupportv4viewviewpager xmlnsandroid androidididpager androidlayout widthmatch parent androidlayout heightwrap content linearlayouttabhostmainactivityjavapublic class mainactivity extends activity implements ontabchangelistener onpagechangelistener private tabhost host private viewpager pager override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main host tabhostfindviewbyidandroidridtabhost pager viewpager findviewbyidridpager hostsetup tabspec spec hostnewtabspectab1 specsetcontentridtab1 specsetindicatorcheck in hostaddtabspec spec hostnewtabspectab2 specsetcontentridtab2 specsetindicatorbuddies hostaddtabspec spec hostnewtabspectab3 specsetcontentridtab3 specsetindicatorrecommendation hostaddtabspec spec hostnewtabspectab4 specsetcontentridtab4 specsetindicatorfeed hostaddtabspec pagersetadapternew mypageradapterthis pagersetonpagechangelistenerthis hostsetontabchangedlistenerthis override public void ontabchangedstring tabid int pagenumber 0 iftabidequalstab1 pagenumber 0 else iftabidequalstab2 pagenumber 1 else iftabidequalstab3 pagenumber 2 else pagenumber 3 pagersetcurrentitempagenumber override public void onpageselectedint pagenumber hostsetcurrenttabpagenumber override public void onpagescrollstatechangedint arg0 todo autogenerated method stub override public void onpagescrolledint arg0 float arg1 int arg2 todo autogenerated method stub mypageradapterjavapublic class mypageradapter extends pageradapter private context ctx public mypageradaptercontext ctx thisctx ctx override public object instantiateitemviewgroup container int position textview tview new textviewctx position tviewsettextpage number position tviewsettextcolorcolorred tviewsettextsize20 containeraddviewtview return tview override public int getcount return 3 override public boolean isviewfromobjectview view object object return view object but i am getting following exception when i swipe the tab1015 053143146 eandroidruntime1789 javalangunsupportedoperationexception required method destroyitem was not overridden 1015 053143146 eandroidruntime1789 at androidsupportv4viewpageradapterdestroyitempageradapterjava192 1015 053143146 eandroidruntime1789 at androidsupportv4viewpageradapterdestroyitempageradapterjava124 1015 053143146 eandroidruntime1789 at androidsupportv4viewviewpagerpopulateviewpagerjava1002 1015 053143146 eandroidruntime1789 at androidsupportv4viewviewpagerpopulateviewpagerjava914 1015 053143146 eandroidruntime1789 at androidsupportv4viewviewpager3runviewpagerjava244 1015 053143146 eandroidruntime1789 at androidviewchoreographercallbackrecordrunchoreographerjava749 1015 053143146 eandroidruntime1789 at androidviewchoreographerdocallbackschoreographerjava562 1015 053143146 eandroidruntime1789 at androidviewchoreographerdoframechoreographerjava531 1015 053143146 eandroidruntime1789 at androidviewchoreographerframethisplayeventreceiverrunchoreographerjava735 1015 053143146 eandroidruntime1789 at androidoshandlerhandlecallbackhandlerjava725 1015 053143146 eandroidruntime1789 at androidoshandlerthispatchmessagehandlerjava92 1015 053143146 eandroidruntime1789 at androidoslooperlooplooperjava137 1015 053143146 eandroidruntime1789 at androidappactivitythreadmainactivitythreadjava5041 1015 053143146 eandroidruntime1789 at javalangreflectmethodinvokenativenative method 1015 053143146 eandroidruntime1789 at javalangreflectmethodinvokemethodjava511 1015 053143146 eandroidruntime1789 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava793 1015 053143146 eandroidruntime1789 at comandroidinternaloszygoteinitmainzygoteinitjava560 1015 053143146 eandroidruntime1789 at dalviksystemnativestartmainnative methodwhat needs to be done,['android'] +560117,get current controller and action id in yii i want to force all users to log in before accessing pages of my site i have followed larry ullmans tutorial forcing login for all pages in yiiaccording to the tutorial you can make an exception for some pages to avoid redirecting to the log in page in order to check the current controller it has checked get value my problem is that i have used urlmanager to rewrite the url and get gives me a null value is there any method i can use to get the current controller and action in the score of my classi tried the following but it is not accessible in the scope of my component classyiiappcontrollergetid,['php'] +560144,ie 10 11 make fixed backgrounds jump when scrolling with mouse wheel when you scroll with the mouse wheel in windows 8 the fixed background image bounces around like crazy this only affects ie 10 and ie 11 this affects elements with positionfixed as well is there a prevent it to happen in ie 10 and 11here is an example with a fixed backgroundimage,['css'] +560145,forcing a symbol to the top of a elf file in our elf files generated via gcc linker the top of the elf file is always the version identifier of the executable codethis is achieved by creating versionc file and making the resulting object file the 1st linkable object in the link commandhowever for one executable this has failed to work and the only difference we can find is that the executable contains a mixture of c and c code and the version symbol is being relocated somewhere elsethe question is therefore is there a way of guaranteeing the absolute location of a symbol in a elf file such that a symbol is always located at the top of the file either through linker commands or code attribute directives,"['c++', 'c']" +560190,how to read a config file using python i have a config file abctxt which looks somewhat likepath1 dtest1firstpath2 dtest2secondpath3 dtest2thirdi want to read these paths from the abctxt to use it in my program to avoid hard coding,['python'] +560191,css not responding to dataattribute set via jquery i am setting a dataposition attribute on document ready via jquery on several divs the setting definitely works for example calling the below code in the chrome console is returning leftcardcontainerdatapositionhowever in the css the below is not doing anythingdatapositionlefthardcoding datapositionleft in the div is working though what am i doing wrong thanks for the help,"['jquery', 'css']" +560202,uitableviewcell does not get deselected when swiping back quickly i have now updated three of my apps to ios 7 but in all three despite them not sharing any code i have the problem where if the user swipes to go back in the navigation controller rather than tap the back button quickly the cell will remain in its selected statefor the three apps one uses custom cells created programmatically another uses custom cells created in a storyboard and the third uses default cells in a very basic subclass of uitableview also in a storyboard in all three cases the cells do not deselect by themselves if the user swipes slowly or hits the back button they deselect as normalthis is only happening in my ios 7 apps apples own apps and third party apps upgraded for ios 7 all seem to be behaving normally albeit with slight differences in how quickly the cells gets deselectedthere must be something i am doing wrong but i am not sure what,['ios'] +560238,change ef 6 code generation strategy from t4 in the past i have successfully created edmx files this was using ef5 and visual studio 2012 i have since upgraded to visual studio 2013 and ef6 the existing ef 5 code still works but now i have a problem i can create edmx files and an entitydatasource i can configure the data source it sees the tables and columns fine but when i try to refresh the schema i getthe schema could not be determined because of the following error from the entitydatasourcecould not find the clr type for my type herei have seen a solution online telling me to change my code generation strategy to default the existing edmx files created in ef 5 are set as legacy objectcontext but it would not let me do this because the option t4 is grayed outis there a way i can force the code generation strategy to not use t4editpawel states that entitydatasource does not support ef 6 is there a tutorial available that shows an easy stepbystep guide of how to connect to ef 6 i have got all my ef information from the book beginning aspnet 4 but it is now obviously outdated i see that ef 6 is still in beta stage maybe they will add support for entitydatasource at some stageedit 2ok i have been fiddling around with this for a bit and i can connect using linqdatasource i would not get a chance to play around with it much for a few days but it looks like this worksedit 3using linqdatasource does not work the only crud operation it can perform is read obviously there must be a way to use the new ef 60 framework pawel has suggested i use mvc but they could not have broken it completely for my scenario using web site could theyedit 4i have found a solution for my scenario see my answer below,['c#'] +560256,what is usevshostingprocess in csproj today all of a sudden i found this in my csproj file usevshostingprocess false usevshostingprocesswhen i compared it with latest it was added intopropertygroup property groupi have alot search on google and found which i do not quite understandcan someone please explain what usevshostingprocess is and why it is needed,"['c#', 'asp.net']" +560285,openjdk 17 in eclipse operator is not allowed for source level below 17 eclipse gives me an error operator is not allowed for source level below 17 i guess this is because it is not using java 17 except that it is at least openjdk 17 my os is opensuse 123i switched back from kepler to juno to reduce some lags and try to figure out this bug as well to no avail so far some things i have tried the default runtime for eclipse is opensdk 17 says so in help about installation details project properties java build library i have manually added the opensdk locationi would install the oracle version but there is only 16 available from the opensuse repository i already tried installing the rpm offered by oracle that did not put itself in my path and kind of messed everything up so i removed that again it should work with openjdk as well no or do you think it has a bugps junit also was not recognised so i manually linked to the jar file perhaps this is relevant information,['java'] +560296,spring bean scope singleton and prototype suppose two classes classa and classb lets suppose classb is dependent on classa on configuration file if we define scope of classa to be singleton and that of classb to be prototype then what happens to instance of classb each time we create a bean instance of classa will the same classb instance gets returned or new instance is created each time instance of classa is returnedthank you,['java'] +560429,rails migration only for schema change or also for updating data i am a junior rails developer and at work we faced the following problemneeded to update the value of a column only for one record what we did is creating a migration like this class thisableaccessforuser activerecordmigration def change userwherename userfirstupdate columnaccess false endendare migrations only for schema changeswhat other solutions do you suggestps i can only change it with code no access to console,['ruby-on-rails'] +560454,afnetworking would not allow large file upload with afnetworking i am trying to upload an image 1280x990 with size 33695 the code below works perfectly with smaller images ie390x390 but the larger image throws an error client postupload image parametersnil constructingbodywithblockid afmultipartformdataformdata formdata appendpartwithfiledataimagedata nameimage filenameimagejpg mimetypeimagejpeg successnsurlsessiondatatask task id responderdata failurensurlsessiondatatask task nserror error error thrownnsdebugdescription json text did not start with array or object and option to allow fragments not seti have searched many other posts and there does not seem to be anything referring to issues with a larger image size any suggestions,['objective-c'] +560457,idictionaryfactory is not supported on this platform when using automapper i have installed automapper 310ci1027 via nuget into an mvc5 website i have used owain wraggs blog as my guide to help me outmy config file looks like thispublic static class automapperconfig public static void initialize mapperinitializex xaddprofiledomaintoviewmodelmappers xaddprofileviewmodeltodomainmappers i am calling the initialize method from within globalasaxcsapplication startautomapperconfiginitializehowever when i run the application it crashes at mapperinitialize this will happen even if i do not include any code in there the code runs fine if i comment this line out but of course then i am not using automapper to connect my objectsthe errors i am seeing are as followsplatformnotsupportedexception this type is not supported on this platform idictionaryfactory automapperinternalplatformadapterresolveboolean throwifnotfound 320 automappertypemapfactorycctor 46typeinitializationexception the type initializer for automappertypemapfactory threw an exception automappertypemapfactoryctor 0 automappermappercctorb 0 55 automapperinternallazyimpl1get value 79 automappermapperget configurationprovider 34 automappermapperget configuration 28 automappermapperinitializeaction1 action 51 aimsmappersautomapperconfiginitialize in cprojectsaimsaimsmappersautomapperconfigcs9 aimsmvcapplicationapplication start in cprojectsaimsaimsglobalasaxcs25httpexception 0x804005 the type initializer for automappertypemapfactory threw an exception systemwebhttpapplicationfactoryensureappstartcalledforintegratedmodehttpcontext context httpapplication app 9936841 systemwebhttpapplicationregistereventsubscriptionswithiisintptr appcontext httpcontext context methodinfo handlers 118 systemwebhttpapplicationinitspecialhttpapplicationstate state methodinfo handlers intptr appcontext httpcontext context 172 systemwebhttpapplicationfactorygetspecialapplicationinstanceintptr appcontext httpcontext context 336 systemwebhostingpipelineruntimeinitializeapplicationintptr appcontext 296httpexception 0x804005 the type initializer for automappertypemapfactory threw an exception systemwebhttpruntimefirstrequestinithttpcontext context 9915380 systemwebhttpruntimeensurefirstrequestinithttpcontext context 101 systemwebhttpruntimeprocessrequestnotificationprivateiis7workerrequest wr httpcontext context 254any thoughts on what i am missing would be greatly appreciated,['c#'] +560458,find hardcoded strings but not those for file names xcode regex help i am searching for all hardcoded strings in my app so i can localize them currently i am using the regular express search for as suggested in this answersearching hard coded text in xcodethe issue is i want to only find some strings in this format for example i want to exclude uiimage imagenamedstring and nsloglog string i believe the easiest way to do this is find a string of the format of as long as the prior characters do not include nslog or imagenamed or several other things i will enter in manuallyhow can i write a regex that excludes these cases,"['ios', 'objective-c']" +560478,javascript sleepdelaywait function sorry if this question has already been asked here before i could not find a suitable answeri am wanting to create a javascript sleepdelaywait function that i can call anywhere in the script like jquerys delayi am not able to use settimeout as i have a script that is generated by php and so am not able to put it into two different functions with the timeout in the middle i need to create a function that allows me to doalerttime startedsleep40alerttime upi really do not want to use jquery,['javascript'] +560483,use dimensions in custom style in android i have got the followingdimensxmldimen namebuttonmarginrl10dpdimendimen namebuttonmargintb5dpdimenstylexmlstyle namemy button parentandroidstylewidgetbutton item nameandroidtextsize16spitem item nameandroidlayout marginleftdimenbuttonmarginrlitem item nameandroidlayout marginrightdimenbuttonmarginrlitem item nameandroidlayout margintopdimenbuttonmargintbitem item nameandroidlayout marginbottomdimenbuttonmargintbitemstyleand i am adding it to a button viewsomefragmentxmlbutton androidlayout widthmatch parent androidlayout heightwrap content androidididbutton stylestylemy button but the margins do not get applied when putting 10dp and 5dp directly into the my button style it works as expected is it possible within android to use values specified in dimensxml to be used in custom styles or may the dimensvalues only be applied to views directly,['android'] +560485,how do pythons any and all functions work i am trying to understand how the any and all python builtin functions work i am trying to compare the tuples so that if any value is different then it will return true and if they are all the same it will return false how are they working in this case to return false false falsed is a defaultdictlistprint ddrd2 1 5 0 1 6 0print listzipddrd2 1 1 5 6 0 0print anyx and not allx for x in zipddrd2 false false falseto my knowledge this should output false true falsesince 11 are the same 56 are different and 00 are the same why is it evaluating to false for all tuples,['python'] +560498,in python numpy what is a dimension and axis i am coding with pythons numpy module if coordinates of a point in 3d space are described as 1 2 1 wouldnt that be 3 dimensions 3 axis a rank of 3 or if that is 1 dimension then shouldnt it be points plural not pointhere is the documentationin numpy dimensions are called axes the number of axes is rank for example the coordinates of a point in 3d space 1 2 1 is an array of rank 1 because it has one axis that axis has a length of 3source numpy tutorial,['python'] +560509,scatterplot contours in matplotlib i have a massive scatterplot 10 points that i am generating in matplotlib each point has a location in this xy space and i would like to generate contours containing certain percentiles of the total number of pointsis there a function in matplotlib which will do this i have looked into contour but i would have to write my own function to work in this waythanks,['python'] +560525,change paid app to free but know if user previously purchased it i am considering changing my paid ios app to be free making it ad based and having an inapp purchase option to remove the adsthis sounds like a good idea if i was just launching the app but we have over 30k paid downloads and i do not want those users to ever see the ads when they update to the new version which is freedo i have any options here,['ios'] +560536,avcapture session slow launch after session restart i have a main view controller and that segues to a second view controller that has an avcapturesession the first time i segue from the main view controller to the capture session controller it takes about 50ms checked using instruments then i segue back to the main view controller from the capture session and then back to the avcapturesession controller from the main controller each time it takes longer to segue from the main view controller to the avcapturesession and by the 5th or 6th iteration the segue takes about 10 seconds compared with 50ms for first time i have pasted the relevant code for the avcapture session below can anyone help solve this thanksthis class of type nsobject manages the capture session for the second view controllerthat actually implements the avcapturesessionimport capturesessionmanagerhimplementation capturesessionmanagersynthesize capturesessionsynthesize previewlayerpragma mark capture session configuration idinit if self super init self setcapturesessionavcapturesession alloc init return self voidaddvideopreviewlayer self setpreviewlayeravcapturevideopreviewlayer alloc initwithsessionself capturesession autorelease self previewlayer setvideogravityavlayervideogravityresizeaspectfill voidaddvideoinput avcapturedevice videodevice avcapturedevice defaultdevicewithmediatypeavmediatypevideo if videodevice nserror error avcapturedeviceinput videoin avcapturedeviceinput deviceinputwithdevicevideodevice errorerror if error if self capturesession canaddinputvideoin self capturesession addinputvideoin else nslogcould not add video input else nslogcould not create video inputelse nslogcould not create video capture device voiddealloc self capturesession stoprunning previewlayer release previewlayer nil capturesession release capturesession nil super dealloc endthe following is in the viewdidload method of the avcapture view controllerself setcapturemanagercapturesessionmanager alloc init self capturemanager addvideoinputself capturemanager addvideopreviewlayercgrect layerrect self view layer boundsself capturemanager previewlayer setboundslayerrectself capturemanager previewlayer setpositioncgpointmakecgrectgetmidxlayerrect cgrectgetmidylayerrectself view layer addsublayerself capturemanager previewlayercapturemanager capturesession startrunningvoidviewdidthisappearboolanimated super viewdidthisappearyes self capturemanager previewlayerremovefromsuperlayer thispatch asyncthispatch get global queuethispatch queue priority default 0 capturemanager capturesession stoprunning,['ios'] +560546,ajaxcontroltoolkit requires aspnet ajax 40 scripts error i am experiencing a ajaxtoolkit calendar thisplay error in production only locally when debugging this problem does not exist and the calendar datepicker works perfectly all of the other posts revolve around this toolkit not working at all i am concerned with why this works in test but not production since i cannot find a reference anywhere in my code that uses aspnet scriptmanagerthe following is on sitemasterajaxtoolkittoolkitscriptmanager runatserver scripts framework scripts aspscriptreference namejquery aspscriptreference namejqueryuicombined aspscriptreference pathscriptswebformswebformsjs aspscriptreference pathscriptswebformswebuivalidationjs aspscriptreference pathscriptswebformsmenustandardsjs aspscriptreference pathscriptswebformsgridviewjs aspscriptreference pathscriptswebformsdetailsviewjs aspscriptreference pathscriptswebformstreeviewjs aspscriptreference pathscriptswebformswebpartsjs aspscriptreference pathscriptswebformsfocusjs aspscriptreference namewebformsbundle site scripts scriptsajaxtoolkittoolkitscriptmanagerthis is the page that uses the calendar function and has sitemaster as its masterpagefileasplabel iddaterangelabel runat server textdate range asplabelasptextbox iddatefrom runatserver width95pxasptextboxajaxtoolkitcalendarextender idcalendarextender runatserver targetcontroliddatefrom popuppositionbottomleft formatmmddyajaxtoolkitcalendarextenderasptextbox iddateto runatserver width95pxasptextboxajaxtoolkitcalendarextender idcalendarextender1 runatserver targetcontroliddateto popuppositionbottomleft formatmmddyajaxtoolkitcalendarextenderthis is part of my webconfig filecontrols add assemblymicrosoftaspnetweboptimizationwebforms namespacemicrosoftaspnetweboptimizationwebforms tagprefixwebopt add tagprefixajaxtoolkit assemblyajaxcontroltoolkit namespaceajaxcontroltoolkitcontrolsthis is the error that is generated in productionuncaught error ajaxcontroltoolkit requires aspnet ajax 40 scripts ensure the correct version of the scripts are referenced if you are using an aspnet scriptmanager switch to the toolkitscriptmanager in ajaxcontroltoolkitdlluncaught typeerror undefined is not a function microsoftajaxjs6,['asp.net'] +560568,proper way to thispose screens in libgdx what is the proper way of completely thisposing of a screen in libgdx currently if i click where a button was on my previous screen the button still does what it would of done if i were on that screen should i be thisposeing everything i can in the thispose method or is there a simpler way to thispose of everything on screen,"['java', 'android']" +560631,java jre 7u45 breaks classloadergetresources i have code to iterate over the results of classloadergetresourcesmetainfmanifestmf to return the list of jars on the class path this worked fine from 160 18 all the way to 170 40 now 170 45 breaks this by showing a security warning popup about mixed signedunsigned codesmall self contained testcase to demonstrate problempackage testcaseimport javaioimport javanetimport javautilenumerationimport javautilloggingpublic class testcase public static void mainstring args getalljarurls public static void getalljarurls try final enumerationurl mfurls threadcurrentthreadgetcontextclassloadergetresourcesmetainfmanifestmf while mfurlshasmoreelements url jarurl mfurlsnextelement if jarurlgetprotocolequalsjar continue try systemoutprintlnjarurltouri catch urisyntaxexception ex loggergetloggertestcaseloglevelsevere null ex catch ioexception e loggergetloggertestcaseloglevelsevere null e launch this with a jnlp jar signed with a valid certificate asxml version10 encodingutf8jnlp spec10 codebasehttplocalhosttest hreftestjnlp information titletesttitle vendortestvendor information securityallpermissionssecurity resources jar hreftestcasejar maintrue downloadeager resources applicationdesc mainclasstestcasetestcasejnlpwhen run have the console visible and hit 5 for verbose output then click block on the security prompt to see the exception clicking allow will let the code run normally but this is not an acceptable user experience especially since our application has to be able to start without user inputoutput under 170 45 is as followscacheentryhttplocalhosttesttestcasejar updateavailabletruelastmodifiedtue oct 15 210921 cdt 2013length6314jarfilecjre32170 45libjavawsjarmetainfmanifestmfjarfilecjre32170 45libdeployjarmetainfmanifestmfjarfilecjre32170 45libpluginjarmetainfmanifestmfjarfilecjre32170 45libdeployjarmetainfmanifestmftrace level set to 5 all completedtrace level set to 5 all completedsecurity resource name metainfmanifestmf in httplocalhosttesttestcasejar javalangsecurityexception trusted loader attempted to load sandboxed resource from httplocalhosttesttestcasejarthe testcasejar is signed it even has all the new manifest attributes includedapplicationname testcasepermissions allpermissionscodebase a diff of the decompiled cpcallbackhandler from deployjar from 7u40 to 7u45 shows significant changes it looks like the changes for liveconnect have borked the existing functionality and no there is no liveconnect involved herehas anyone else run into this suggestions for a workaround file a bugnote also posted on the otn java forums but i am hoping for a faster answer here thankschris,['java'] +560641,combining a user defined literal with a method call i am wondering why i cannot write code like thisconstexpr double radius 27 kmto miles km returns thistance instance which has to milesboth gcc 481 and clang 34 complain that they could not find literal operator operator kmto miles unless i wrap 27 km in parenthesesconstexpr double radius 27 kmto miles fineby my reading of section 2148 of the standard a udl suffix cannot contain a period so why are the compilers parsing the code like this are they correct or is it a bugedit you can see a full example with different udl and method names here,['c++'] +560684,how to spread dynamic divs vertically evenly basically i want the child divs to spread out evenly in the parent div and if one of the child divs is removed the rest should resize and to fill the remaining space evenly againex parent child child child now when a child div is remove it should become parent child child now i want to do this with only pure htmlcss but at the moment i cannot find a solutionthe two other alternatives i am considering are tocalculate the heights using javascriptcreate different classes for a bunch of scenarios eg a parent with2 child divs 3 child divs 4 child divs etc and then load themaccordingly with phpanyone got a better idea,"['html', 'css']" +560688,load image from javascript on my album slide show page i have code likespan stylethisplaynone img idid1 srcimageurl onloadjavascriptshowimagespanspan show loaderspanin showimage i am sure the image is loaded so i show the image and hide the loadernow when user clicks on next i need to change the src of the image now i need do not know how to set src only when image is loaded,"['javascript', 'jquery']" +560689,uicollectionview performbatchupdates cause collectionview misplace while rotating the device if i rotate the device while the collectionview performbatchupdate with reloaditemsatindexpaths the collection view will be misplaced but view will still stay in a constant positionto simply fix this issuesetting uiview setanimationenabled no in willrotatetointerfaceorientation setting uiview setanimationenabled yes in didrotatetointerfaceorientationbut i dont think this is a good way to solve this issuedoes anyone got better idea cheershere is my code voidwillrotatetointerfaceorientationuiinterfaceorientationtointerfaceorientation durationnstimeintervalduration super willrotatetointerfaceorientationtointerfaceorientation durationduration nslogbefore rotation nslogcollecitonview rect nsstringfromcgrectselfcollectionviewframe nslogview rect nsstringfromcgrectselfviewframe voiddidrotatefrominterfaceorientationuiinterfaceorientationfrominterfaceorientation super didrotatefrominterfaceorientationfrominterfaceorientation nslogafter rotation nslogcollecitonview rect nsstringfromcgrectselfcollectionviewframe nslogview rect nsstringfromcgrectselfviewframe void viewdidappearboolanimated super viewdidappearanimated forint i 0 i 30 i nsblockoperation operation nsblockoperation blockoperationwithblock cgfloat hue arc4random 20 selfcollectionview reloaditemsatindexpathsnsindexpath indexpathforitemhue insection0 operationsarray addobjectoperation self performupdate voidperformupdate if operationsarraycount 0return selfcollectionview performbatchupdates nsblockoperation operation nsblockoperation operationsarray firstobject operation start completionbool finished if operationsarraycount 0 operationsarray removeobjectatindex0 self performupdate the output if i rotated the device during perform update20131016 170518445 collectionviewbatchupdatetest90419a0b before rotation20131016 170518446 collectionviewbatchupdatetest90419a0b collecitonview rect 0 0 1024 76820131016 170518446 collectionviewbatchupdatetest90419a0b view rect 0 0 768 102420131016 170518851 collectionviewbatchupdatetest90419a0b after rotation20131016 170518851 collectionviewbatchupdatetest90419a0b collecitonview rect 128 0 1024 102420131016 170518852 collectionviewbatchupdatetest90419a0b view rect 0 0 768 1024,['ios'] +560743,deployment of precompiledapp issue the autogenerated precompiledappconfig is causing me some headacheim automating the deployment of an older web site and 50 of the time when i deploy i get this errorsystemioioexception the process cannot access the file webprodlocalcsiteswebsiteprecompiledappconfig because it is being used by another processcontentprecompiledapp version2 updatabletrueto the best of my knowledge websites uses some shadow copy feature to allow updating the site runtime with things such as appconfig etc however this 1 file seems to be an exceptioncan anyone suggest a workaround besides stopping the website while deployingkind regards,['asp.net'] +560775,formatting of the formatteroff tag in eclipse as you may know eclips lets you thisable the code formatter for certain sections of source code see for example this questionnow my problem is that the formatter apparently stops formatting code at the very beginning of the line where the formatteroff tag is found this has the result that the formatter tag itself which is just a comment line essentially is placed in a queer location namely without indentation at the very beginning of the linesee this examplewhat i enter formatteroff some code with indentation that i dont want to be formatted formatteronafter hitting ctrl f it looks like thisformatteroff some code with indentation that i dont want to be formatted formatteronok i realize that this is purely a cosmetic issue but my ocd is driving me nuts when i see this everywhere in the code especially after specifically using the formatting tag to make the code look nicer,['java'] +560788,passing a parameter to function with single quote how do i pass a parameter to a javascript function with includedvar name lauren odonaldvar htmlancha onclickjavascriptselectemployee1100namereturn false hrefjavascriptvoid0odonald laurena documentappendhtmlanchthe javascript function is not executing since the name lauren odonald contains single quotehow can i add a parameter with and prepare dynamic html to make it workhere is the dynamic code to generate var rows new stringbuffer dataeachfunctionindex rowsappendstringformattrtda hrefnoaspx onclickjavascriptselectemployee31 2return false0atdtr stringformat0 1 thissurname thisfirstname thissurname thisfirstname thisid,"['javascript', 'jquery']" +560810,easy install and pip broke pkg resourcesthistributionnotfound thistribute0636 i was tried to upgrade pip with pip install upgrade pip on osx and pip and easy install both dont workwhen running piptraceback most recent call last file usrlocalbinpip line 5 in module from pkg resources import load entry point file usrlocalcellarpython274frameworkspythonframeworkversions27libpython27sitepackagesthistribute0649py27eggpkg resourcespy line 2881 in module parse requirements requires environment file usrlocalcellarpython274frameworkspythonframeworkversions27libpython27sitepackagesthistribute0649py27eggpkg resourcespy line 596 in resolve raise thistributionnotfoundreqpkg resourcesthistributionnotfound pip131when running easy install file usrlocalbineasy install line 5 in module from pkg resources import load entry point file usrlocalcellarpython274frameworkspythonframeworkversions27libpython27sitepackagesthistribute0649py27eggpkg resourcespy line 2881 in module parse requirements requires environment file usrlocalcellarpython274frameworkspythonframeworkversions27libpython27sitepackagesthistribute0649py27eggpkg resourcespy line 596 in resolve raise thistributionnotfoundreqpkg resourcesthistributionnotfound thistribute0636how can i fix thisupdatei found the solutioni did cd usrlocallibpython27sitepackages lsfound pip141py27egginfo and thistribute0649py27egg in the directorythen the following steps fixed the issuechanged the pip version to 141 in usrlocalbinpipchanged thistribute version to 0649 in usrlocalbineasy installthe answers on other such questions to curl ez setuppy and install setuptools from it didnt work it gave the following errordownloading traceback most recent call last file stdin line 370 in module file stdin line 366 in main file stdin line 278 in download setuptools file stdin line 185 in download file curl file usrlocalcellarpython274frameworkspythonframeworkversions27libpython27subprocesspy line 542 in check call raise calledprocesserrorretcode cmdsubprocesscalledprocesserror command curl silent output usrbinsetuptools116targz returned nonzero exit status 23,['python'] +560851,full screen video html 5 internet explorer i am creating my own html 5 browser player all controls work apart form getting the full screen working in ie 10 chrome safari and firefox work great my javascript skills are not the best so would be great if some could explain things in a simple way for me that would be greati have read on some website that ie does not support full screen if this is the case why can i go full screen via the browser player controls on ie10 hate microsoft so crap and behind on everythingwould appreciate and help and suggestions thanks in advancethis is what i have so far for my full screen functionfunction togglefullscreen ifvidrequestfullscreen vidrequestfullscreen else ifvidwebkitrequestfullscreen vidwebkitrequestfullscreen else ifvidmozrequestfullscreen vidmozrequestfullscreen,['javascript'] +560958,unable to make the session state request to the session state server i am trying to use state server sessions i have changed my session state to the followingsessionstate modestateserver stateconnectionstringtcpip12700142424 cookielessfalse timeout20 running my website from local host and everything works finebut when i publish my website and try run it online i get the following errorunable to make the session state request to the session state server please ensure that the aspnet state service is started and that the client and server ports are the same if the server is on a remote machine please ensure that it accepts remote requests by checking the value of hkey local machinesystemcurrentcontrolsetservicesaspnet stateparametersallowremoteconnection if the server is on the local machine and if the before mentioned registry value does not exist or is set to 0 then the state server connection string must use either localhost or 127001 as the server namethe website is hosted on afrihost servers after resarching the error i found that it could be because aspnet state service has not been started is there a way i could check if the afrihost servers are running this service or to start it remotely also i know the ip address 127001 is for local host but because you are publishing your application on webserver it becomes local to that machine is this correct,['asp.net'] +560997,how to make and nested for loops recursively i have a method that must do the followingfor int a01 1 a01 25 a01 for int a02 a01 1 a02 25 a02 for int a03 a02 1 a03 25 a03 systemoutprintlna01 a02 a015 i would like to specify the number of nested fors in the case above i want 15 nested forsis there a way to use recursive programming here,['java'] +560999,xamarin after updating xcode and reinstalling xamarin i get multiple nsunknownkeyexception errors i am developing with xamarin 4013 and since upgrading from a much earlier version of xcode to xcode 463 i am now receiving errors when i try to build to either the device or the ios simulator i had to reinstall xamarinios after updating xcode because xamarin said ios was not installedthe errors are to do with linking the single xib file i believe the error comes up referring to the below code inside maincsuiapplicationmain args null appdelegateit statesobjectivec exception thrown name nsunknownkeyexception reason setvalueforundefinedkey this class is not key value codingcompliant for the key loginbtni looked into the same error log at the links below but i believe i have a different problem because if i remove the loginbtn from the xib file it then changes to complain about the usernametextinput outlet and so on until no outlets are left after removing everything from the xib file so that it is completely empty except for the parent view object it has the same error log but instead of loginbtn it complains about view i have tried reapplying the link from the view object to the files owner but that has not changed anythingsimilar error log answers that have not solved it this class is not key value codingcompliant for the key authview this class is not key value codingcompliant for the keyi have cleaned all from within xamarins build dropdown box at the top and i do not even know how to get a blank page showing up from my document after deleting everything in the viewit is a single page application with no other xib files and is in the very early stagesany light you can shed on this would be much appreciatedthanksjason,['ios'] +561086,copying multiple resource directories to independent target directories with maven the maven resources pluginthis goal requires that you configure the resources to be copied and specify the outputdirectorycopy two or more external resource directories within the basedir to the build output directory using maven see blah and ugghbasedir pomxml blah uggh src main test target classes blah ugghfor example given the directory structure above copy blah and uggh to the target directory using maven it is easy to copy one or the other however the plugin only accepts a single outputdirectory if you specify the target directory and both directories as resources then the contents of each directory gets copied to target but not the directories themselvesadditional use of the plugin overwrites the initial also i have tried specifying the entire basedir and only including the desired directories this does not copy anythinghere is an example of copying a single directory plugin artifactidmavenresourcespluginartifactid version26version executions execution idcopyresourcesid phasevalidatephase goals goalcopyresourcesgoal goals configuration outputdirectorybasedirtargetblahoutputdirectory resources resource directoryblahdirectory filteringtruefiltering resource resources configuration execution executions plugin,['java'] +561096,rails 4 fonts not loading on production i cannot load fonts in my rails 4 app in production it works normally in developmentassets are precompiled on the server while deployingi have my fonts in appassetsfontsin my appcssfontface fontfamily walkwayboldregular src urlwalkway boldwebfonteot src urlwalkway boldwebfonteotiefix formatembeddedopentype urlwalkway boldwebfontwoff formatwoff urlwalkway boldwebfontf formattruetype urlwalkway boldwebfontsvgwalkwayboldregular formatsvg fontweight normal fontstyle normalin my productionrb i haveconfigassetsprecompile procnew path if path eotsvgttfwoffz true end,['ruby-on-rails'] +561123,custom onoff image ios 70 ui switch in ios 7 switches do not allow custom onoff images by default while i can still set them in the interface builder it does not show upthe transition guide merely notes that it is not on by default anymore presumably there is a way to change that so i do use the images i have,['ios'] +561196,how should i mark a method as obsolete in js i am refactoring a rather large js file that contains many unrelated methods into something that will regroup the methods together according to their usage and renaming some of them as needed to prevent misleading nameshowever most of the web pages that actually use this code are spread across different code branches preventing me from doing a simple findreplace i could do it in all the different branches but that requires doing maintenance in 30 branches at the same time or probably forgetting to perform the renaming once the change is merged in the other branches by me or other team membersif this was c i could just mark the method with obsolete and it would flag the necessary changes as needed so i am looking for something somewhat equivalent i will still provide functionality with the old interface for a while by just redirecting the calls to the new methods but i would like to force people to switch to the new interface as they work on the pages for other reasonsis there any other way to do something similar besides adding a debuggerstatement and a verbose comment to every method so that it breaks when developing but not in production,['javascript'] +561201,portable snprintf i am writing code for a target platform with no cruntime no stdlib no stdio i need a string formatting function like snprintf but that should be able to run without any dependencies not even the c library at most it can depend on memory alloc functions provided by me i checked out trio but it needs stdioh header i cannot use thisedit target platform powerpc64 home made osnot by me however the library should not rely on os specific stuffedit2i have tried out some 3rdparty open source libs such as trio snprintf and miniformat but all of them rely on headers like stringh stdioh oreven worse stdlibh i do not want to write my own implementation if one already exists as that would be timewasting and bugprone,['c'] +561231,argparse required argument y if x is present i have a requirement as followsxyifier prox lport lport rport rportfor the argument prox i use actionstore true to check if it is present or not i do not require any of the arguments but if prox is set i require rport and lport as well is there an easy way of doing this with argparse without writing custom conditional codingmore codenon intadd argumentprox actionstore true helpflag to turn on proxynon intadd argumentlport typeint helplisten portnon intadd argumentrport typeint helpproxy port,['python'] +561252,rails 4 testing user initialization is always blank hey i have a test that looks like thistest create account do if usercreateemail password blahblah assert true else assert usermsg endendbut when i try to run it i am getting an error message like this 1 errorusertesttest create accountactiverecordrecordnotunique pguniqueviolation error duplicate key value violates unique constraint index users on emaildetail key email already exists insert into users created at updated at id values 20131016 215954 20131016 215954 298486374this looks to me as though i had not initialized email but as i understand this should be initialized with my create above i am using strong params so i do not have any attr accessable enabled and i can run this through does anyone know what could be causing this if you want any more information let me know,"['ruby-on-rails', 'ruby']" +561266,what is setbounds and how do i use it i cannot find anything on setbounds what it is for or what its function actually is could someone clear me up on this thanks so much,['java'] +561322,some of bootstrap3 glyphicons are not thisplayed correctly on phonegap android webview please have a look at this attached screenshotit is my phonegap testing app taken on a galaxy s4you should see that the bell bookmark briefcase and camera icons and more are not thisplayed as expectedhere are my observationsall icons can be thisplayed correctly in browsers chrome safari on both pc and mobile devicesall icons can be thisplayed correctly in the same app for ios checked in iphoneipad ios7the question mark can only be seen in an android appdoes anyone know the reason why,['android'] +561330,why are papbpc not equal consider the following program includeiostream using namespace std class classapublic virtual classa virtual void functionaclass classb public virtual void functionbclass classc public classapublic classbvoid main classc aobject classa pa aobject classb pb aobject classc pc aobject coutpa paendl coutpb pbendl coutpc pcendlpapbpc are supposed to equalbut the result is pa 0031fd90pb 0031fd94pc 0031fd90why pb pa 4and when i change class classapublic virtual classa virtual void functionaclass classb public virtual void functionbtoclass classaclass classbthe result is pa 0030faa3pb 0030faa4pc 0030faa3pb pa 1,['c++'] +561342,using generics in spring data jpa repositories i have a number of simple object types that need to be persisted to a database i am using spring jpa to manage this persistence for each object type i need to build the followingimport orgspringframeworkdatajparepositoryjparepositorypublic interface facilityrepository extends jparepositoryfacility long public interface facilityservice public facility createfacility facilityservicepublic class facilityserviceimpl implements facilityservice resource private facilityrepository countryrepository transactional public facility createfacility facility facility created facility return facilityrepositorysavecreated it occurred to me that it may be possible to replace the multiple classes for each object type with three generics based classes thus saving a lot of boilerplate coding i am not exactly sure how to go about it and in fact if it is a good idea,['java'] +561377,i want to force keyboard on with bluetooth device i have a bluetooth barcode deviceif connect the bluetooth device to the iphone i cannot write anything using iphone keyboardyou already know that iphone keyboard does not show on because the bluetooth device is recognized keyboardbut i have to write something by keyboard into the textbox while iphone connect with bluetooth deviceplease let me know how to do that thanks,['ios'] +561404,unrecognized configuration section log4net i have this code in webconfiglog4net root level valueall appenderref reflogfileappender root appender namelogfileappender typelog4netappenderrollingfileappender param namefile valuedlogfilefacultytxt param nameappendtofile valuetrue rollingstyle valuesize maxsizerollbackups value10 maximumfilesize value10mb staticlogfilename valuetrue layout typelog4netlayoutpatternlayout param nameconversionpattern valuedate thread 5level logger propertyndc messagenewline layout appenderlog4netand i have downloaded log4netdll and placed it in bin folderin one of my aspxcs pages i have added this codeusing log4netassembly log4netconfigxmlconfiguratorwatch trueprivate static readonly log4netilog log log4netlogmanagergetloggersystemreflectionmethodbasegetcurrentmethoddeclaringtypebut it is giving error as unrecognized configuration section log4net,"['c#', 'asp.net']" +561431,is it possible to change only the color of text shadow i have 9 differently colored buttons red orange yellow green blue purple pink offwhite and slate and i was wondering if it was possible to manipulate and alter only the color of the textshadow css property for these buttons while keeping the other values the samefor example i have two different classes one is for buttons with 11px font size and the other is for 14px font size standard across my websitebutton11 fontsize 08em borderwidth 009091em borderstyle solid padding 0 090909em textshadow 009091em 009091em 0 rgba0 0 0 05 webkitboxshadow 0 009091em rgba255 255 255 03 inset mozboxshadow 0 009091em rgba255 255 255 03 inset boxshadow 0 009091em rgba255 255 255 03 insetbutton14 borderwidth 007143em borderstyle solid padding 0 071429em textshadow 007143em 007143em 0 rgba0 0 0 05 webkitboxshadow 0 007143em rgba255 255 255 03 inset mozboxshadow 0 007143em rgba255 255 255 03 inset boxshadow 0 007143em rgba255 255 255 03 insetfor those unaware i have two separate classes because each font size requires different values for the borders and text shadow since i am using the em measurement 009em equates to 1px at font size 11px and 007em equates to 1px at font size 14pxso in order to cut down on the css file size it would help greatly if i could simply change the color of the textshadow css properties without having to include the other valuesdoes anyone know if this is possiblethank you,['css'] +561461,pandas pivoting with multiindex data i have two dataframes which looks like thisrating bmw fiat toyota0 7 2 31 8 1 82 9 10 73 8 3 9own bmw fiat toyota0 1 1 01 0 1 12 0 0 13 0 1 1i am ultimately trying to get a pivot table of mean rating for usage by brand or something like this bmw fiat toyotausage 0 83 10 31 70 2 8my approach was to merge the datasets like thismeasure rating own brand bmw fiat toyota bmw fiat toyota0 7 2 3 1 1 01 8 1 8 0 1 12 9 10 7 0 0 13 8 3 9 0 1 1and then attempt to create a pivot table using rating as the value own as the rows and brand as the columns but i kept running to key issues i have also attempted unstacking either the measure or brand levels but i cannot seem to use row index names as pivot keyswhat am i doing wrong is there a better approach to this,['python'] +561500,how to query for null values in json field type postgresql i have a json type field in postgresql however i cannot select rows where specific field is nullcodeselect from json array elements name toby occupation software engineer name zaphod occupation galactic president name2 zaphod occupation2 null as elemwhere elemoccupation2 is nullthis should work but i am getting this errorerror operator does not exist json booleanline 6 where elemoccupation2 is null,['sql'] +561502,when to use jniexport and jnicall in android ndk i am trying to write my own jni sources looking at some ndk samples i found that they often use those macros jniexport and jnicall follewed by the name of java package like this jniexport void jnicall java com example plasma plasmaview renderplasmajnienv env jobject obj jobject bitmap jlong time msi googled it but i cannot understand when and how to use these macros,"['android', 'c++']" +561550,how to generate wadl file using jersey 17 i created a hello world rest service and now i d like to generate the wadl file i looked around and saw that i can do so by calling httplocalhost8090applicationwadlhowever i dont get anything in my case i am using jersey 17 with eclipse indigo and running on apache 7i also tried calling httplocalhost8090myapplicattion namewadl but still no resultis this feature supported by jersey 17 if yes what do i do wrongthe webxml file looks like thisthank you,['java'] +561574,state restoration in ios i am storing my application screen so that when the application gets opened it will show the screen that was stored the application is navigation based i have assigned the restoration ids to my two view controllers in main story board the first controller is the root view controller of the navigation controller i have also assigned restoration id to the navigation controller now the problem is when i run the application i am getting the following warningunable to create restoration in progress marker filenot sure what else need to be done,['ios'] +561605,ios http multipartform streaming request i have to implement a file upload for my app files like assets which can be photo or video should be uploaded to a web sever using a rest interfacethe upload would use a form data request with custom header attributesproblemholding large files like videos in an nsdata object can lead to memory issues this would be the standard approachsolutionproviding an nsinputstream for the body part of the request and write data piece by piece to the http body streamquestion can anyone provide an exmaple of how to use an nsinputstream in combination with a nsurlrequest and nsurlconnectioni wrapped my head around several incomplete examples but i do not know how to deal with the following method nsinputstream connectionnsurlconnection connection neednewbodystreamnsurlrequest requesti do not want to use any third party library,"['iphone', 'ios']" +561695,unable to authenticate the package 727047181itmsp i have upload build in app store after archive the file it will goes to uploading builds on that time i got this error1apples web services operation was not successful2unable to authenticate the package727047181itmsp3error itms 90the bundle identifier cannot be changed from the current valuecomredimpokerastic if you want to change your bundle identifieryou will need to create a new application in itunes connectat softwareassestssoftwareassetmzitmspsoftwareassetpackageplease any one help me out this problem,"['iphone', 'ios']" +561700,retrieve inserted identity value from aws redshift via jdbc while working with aws redshift is has come to my attention getting the last inserted id from a table with an identity column via jdbc driver cannot be accomplished with either of the following methodsreturning key wordor statementreturn generated keys as mentioned in the stack overflow entryhow to get a value from the last inserted rowthe above methods are not available as redshift as of 10172013 is built on postgresql version 802 see the following documentation in the following link high level system architecturehtmlif you are intending to use redshift as a rdbms it is a worthwhile effort to read the following as well redshiftandpostgressqlhtmlquestionwhat is the best strategy for retrieving the last inserted id on an autoincrementserialidentity column in redshift via postgresql jdbc driver,['java'] +561719,what happens if i do not catch a throw this is super basic but i cannot find the answer anywhere there is lots of posts out there about throwing and catching but what actually happens if i throw from function1 and then call function1 from function2 but do not catch it does that mean it just gets rethrown to the caller of function2 judging from the following i would say yes but i wanted to get a solid gurulike answer before i soldier on and assumeinclude iostreamvoid function1 throw 1void function2 function1int main try function2 catch stdcout caught return 0 return 0outputcaught,['c++'] +561741,python where does ifendifstatement end i have the following codefor i in range0numclass if breaksi 0 clastart 0 else clastart datalistindexbreaksi clastart 1classend datalistindexbreaksi1classlist datalistclastartclassend1classmean sumclasslistlenclasslistprint classmeanpresdcm 00for j in range0lenclasslist sqdev2 classlistj classmean2 presdcm sqdev2sdcm presdcmreturn sdam sdcmsdami would like to convert this code to vbnetbut i am not sure where the ifelseifstatement endsdoes it end after clastart 1i feel it a bit difficult to see where the fornextloops end as well in pythonthe code is taken from thank you,['python'] +561752,msaccess you tried to execute a query that does not include the specified aggregate function select sumordersquantity as num fname surnamefrom authorinner join book on authoraid bookauthoridi keep getting the error message you tried to execute a query that does not include the specified expression fname as part of an aggregate function what do i do,['sql'] +561784,why can i not use this as a lexical variable in php 554 php versionphp 554 cli built sep 19 2013 171006 copyright c 19972013 the php groupzend engine v250 copyright c 19982013 zend technologiesthe following code similar to example at class foo public function bar return function use this echo in closuren fails withphp fatal error cannot use this as lexical variableyet according to the php docs and a comment on that bug report from rasmus lerdorf using this in anonymous functions was added as of php 54 what am i doing wrong,['php'] +561801,systemwebhttpcontextbase does not contain a definition for current mvc 4 with elmah logging i have a c aspnet mvc 4 project which is using elmah for catching any unhandled exceptions this works great in most situations however i have found that for a controller method that is called using a jquery ajax call i cannot get the current context for example in my controller method that returns the jsonresult i have this test codetry throw new exceptionthis is a testcatchexception e elmaherrorloggetdefaulthttpcontextcurrentlognew elmaherrorethe httpcontextcurrentis causing the following errorsystemwebhttpcontextbase does not contain a definition for current and no extension method current accepting a first argument of type systemwebhttpcontextbase could be found are you missing a using directive or an assembly referencehow can i get around this problem,['c#'] +561856,how to use user as foreign key in django 15 i have made a custom profile model which looks like thisfrom djangodb import modelsfrom djangocontribauthmodels import userclass userprofilemodelsmodel user modelsforeignkeyuser uniquetrue name modelscharfieldmax length30 occupation modelscharfieldmax length50 city modelscharfieldmax length30 province modelscharfieldmax length50 sex modelscharfieldmax length1but when i run managepy syncdb i getmyappuserprofile user has a relation with model user which has either not been installed or is abstracti also triedfrom djangocontribauthmodels import baseusermanager abstractuserbut it gives the same error where i am wrong and how to fix this,['python'] +561939,c fastest way to compare strings i have noticed thatstring1length string2length string1 string2on large strings is slightly faster than juststring1 string2is this true and is this a good practice to compare large string lengths before comparing actual strings,['c#'] +561959,how can i get early access to oracle java updates so i can test my ria and avoid firedrills when these updates are made public having had our application stop working when customers installed the 7u45 update were wondering what more we can do in the future to be ready for these updates upfront and avoid releaseday support nightmaresper the java version numbering scheme the next critical patch update planned for january 14 will be 7u51 the next limited update date unknown will be 7u60i have poked around the oracle and openjdk websites and not found anything particularly useful the main oracle page for java se has an early access downloads section it has three links that have potential but do not pan out which still talks about 7u40 no mention of 7u45 let alone 7u51 or 7u60 which says were open for fixes for 7u60 in the jdk7udev forest but does not appear to provide any prebuilt binaries it is also not clear to me whether the deployment components applet plugin and webstart the main source of our past compatibility issues are even part of openjdk to begin withthe java compatibility and performance program sounds like just what i want but nobody knows how to sign up for itan answer to the second question i linked above points to an openjdk bug report that was filed back in august it has a cap label which might stand for compatibility and performance so clearly some people are able to test their applications against these updates any pointers on how to join that club are much appreciated,['java'] +562043,thisabling navigation drawer toggling homebuttonupindicator in fragments the setupi have an activity whose contentview is an instance of a drawerlayout which has a navigation drawer with a drawer indicator thisplayed in the action bar the activity contains a fragment let us call it listfragment which contains a list of options when an option is clicked i replace the listfragment with a detailfragmentat this point i would like to thisplay an up navigation option instead of the navigation drawer indicator i am able to thisplay the up icon if i thisable the drawer indicator by calling mdrawertogglesetdrawerindicatorenabledfalse but this only removes the drawer iconit does not remove the functionalitythat is when i click the caret the navigation drawer is still openedadditionally in these subviews i would like to thisable the opening of the drawer by dragging from the edge of the screen i have tried doing this by calling setdrawerlockmodedrawerlayoutlock mode locked closed but it does not seem to have thisabled this functionalityi have tried extending the actionbardrawertoggle class to prevent opening the drawer when the indicator is clickedhowever all that happens is that the overriding action the up navigation is performed but the drawer still opensi have also implemented the steps in switching between android navigation drawer image and up caret when using fragments it works insofar as thisplaying the caret goes but despite overriding the up button functionality the menu still opens the app does navigate backit just also opens the drawerquestionso long story short is there any preferably clean and elegant but at this point i will go with hacky way to achieve these things when my layout root is a drawerlayoutreplace the drawer indicator with an up caret tentatively doable via mdrawertogglesetdrawerindicatorenabledfalseprevent the drawer from opening when the caret is clicked and instead override with my own up functionalityprevent the drawer from opening when i drag from the edge of the screeneditall right it looks like if i both override actionbardrawertoggle and onoptionsitemselected the menu does not open when i click the caret but it still opens if i drag from the edge help,['android'] +562095,using javascript regex containing in razor i am performing email address validation with javascript in a razor view page the regex i am going to use is similar to the one proposed at validate email address in javascripthowever because the regex contains an character i am getting parser error when try to run the web app my regex looks like otherpart other parti tried to add an character to make the in the origin regex this eliminated the compilation error but seems to make the regex stops working we have used it in another web app that does not use razor engine so i know it worksis there any other way to escape the character,['javascript'] +562115,trimmed mean with percentage limit in python i am trying to calculate the trimmed mean which excludes the outliers of an array i found there is a module called scipystatstmean but it requires the user specifies the range by absolute value instead of percentage valuesin matlab we have m trimmeanxpercent that does exactly what i want do we have the counterpart in python,['python'] +562127,matplotlib pyplottitlestring returns error when i call pyplottitlesome string it throws an excption str object is not callablei copied the following from the matplotib online documentationmu sigma 100 15x mu sigma nprandomrandn10 the histogram of the datan bins patches plthistx 50 normed1 facecolorg alpha075pltxlabelsmartspltylabelprobabilityplttitlehistogram of iqplttext60 025 rmu100 sigma15pltaxis40 160 0 003pltgridtruepltshowand gettypeerror traceback most recent call lastipythoninput15840fe7a831b06 in module 8 pltxlabelsmarts 9 pltylabelprobability 10 plttitlehistogram of iq 11 plttext60 025 rmu100 sigma15 12 pltaxis40 160 0 003typeerror str object is not callablepyplotsuptitle works oki am using python 275 and the latest release of matplotlib on an imac with an i7 processor osx 108 and 8 gig ram and ipython notebookdoes anyone know whats going on,['python'] +562139,qt execute external program i want to start an external program out of my qtprogramm the only working solution wassystemstart explorerexebut it is only working for windows and starts a command line for a momentnext thing i tried wasqprocess processqstring file qdirhomepath fileexeprocestartfileprocessexecutefile i tried as wellbut nothing happened any ideas,['c++'] +562153,present view controller from app delegate i am attempting to present a view controller from the app delegate with this code voidinterstitialviewcontrollerrequestsucceededuiviewcontroller interstitialviewcontroller selfwindowrootviewcontroller presentviewcontrolleruiviewcontroller interstitialviewcontroller animatedyes completionnullit will thisplay the interstitial on the initial view controller but none of the others i want it to thisplay on every one attached to a navigation controllerhow can i modify this code to achieve that goal,"['ios', 'objective-c']" +562169,weak reference to python class method python 27 docs for weakref module say this not all objects can be weakly referenced those objects which can include class instances functions written in python but not in c methods both bound and unbound and python 33 docs for weakref module say this not all objects can be weakly referenced those objects which can include class instances functions written in python but not in c instance methods to me these indicate that weakrefs to bound methods in all versions python 27 33 should be good and that weakrefs to unbound methods should be good in python 27 yet in python 27 creating a weakref to a method bound or unbound results in a dead weakref def isdeadwr print dead class foo def barself pass wrweakrefreffoobar isdeaddead wr is nonetrue foofoo wrweakrefreffoobar isdeaddead wr is nonetruenot what i would have expected based on the docssimilarly in python 33 a weakref to a bound method dies on creation wrweakrefreffoobar isdead wr is nonefalse foofoo wrweakrefreffoobar isdeaddead wr is nonetrueagain not what i would have expected based on the docssince this wording has been around since 27 it is surely not an oversight can anyone explain how the statements and the observed behavior are in fact not in contradiction editclarification in other words the statement for 33 says instance methods can be weak referenced does not this mean that it is reasonable to expect that weakrefrefan instance method is not none and if it none then instance methods should not be listed among the types of objects that can be weak referenced,['python'] +562202,conversion from char to signed char i saw a piece of valid c code i tried to compile as c and i got an error i cannot understandchar tsigned char v terror invalid conversion from char to signed charfrom what i learned char and signed char are semantically identical but are still considered as different by the compileri know that the error is caused by the difference between these two type my question is why does this difference exists as far as i know char is implemented either as a signed char or as a unsigned char so it should be identical to either one or the otheri consulted this question and it does not answer the point i want to know,['c++'] +562217,not sure to understand the advantage of the move constructor or how it works or use it i recently posted a question on se regarding the code below because it generated a compilation error someone was kind enough to answer that when you implement a move constructor or move assignment operator then the default copy constructor is deleted they also suggested that then i needed to use the stdmove to get something like this to workimage src200 200image cpy stdmovesrcnow that sort of makes sense to me because the fact that you want to use the move assignment operator or move constructor in this case has to made explicit src in this example is an lvalue and nothing can tell the compiler than you actually want to move its content to cpy unless you express this explicitly with stdmove however i have more of a problem with this codeimage cpy src srci did not put the copy for the operator below but it is a straightforward overload operator of the typeimage operator const image img const image tmpstdminw imgw stdminh imgh for int j 0 j tmph j for int i 0 i tmpw i accumulate the result of the two images return tmp in this particular case i would assume the operator returns a temp variable in the form of tmp and that the move assignement operator would be triggered in that case when you get to cpy src src i am not sure it is accurate to say that the result of src src is a lvalue because in fact whats returns in tmp but then tmp is copiedassigned to cpy so before the move operator existed this would have triggered the default copy constructor but why is not it using the move constructor in this case it seems that i also need to do aimage cpy stdmovesrc srcto get this to work which i assume gets an xvalue for the variable returned by the operator of the class imagecould someone helps me understanding this better please and tell what i do not get rightthank youinclude cstdlibinclude cstdioinclude cstringinclude algorithminclude fstreaminclude cassertclass imagepublic image w512 h512 dnull printfconstructor defaultn d new floatw h 3 memsetd 0x0 sizeoffloat w h 3 imageconst unsigned int w const unsigned int h w w h h dnull d new floatw h 3 memsetd 0x0 sizeoffloat w h 3 move constructor imageimage img w0 h0 dnull w imgw h imgh d imgd imgd null imgw imgh 0 move assignment operator image operator image img if this img if d null delete d w imgw h imgh d imgd imgd null imgw imgh 0 return this image if d null delete d unsigned int w h float dint mainint argc char argv image sample readppmleanppm image res sample return 0,['c++'] +562275,how to touch multiple records in activerecord i would like to update the updated at for a few recordsusers userin mailing listusersupdate allupdated at timenowis there a shortcut for the purpose say something like a userstouch all method,['ruby-on-rails'] +562279,webservlet cannot be resolved to a type i was able to make my app works again following the advices of user2821894 but after trying to call a servlet tomcat 7 stopped working againif i try to delete the code where i call my servlet my web app doesent workonce i have a problem with a servlet tomcat stops workingi had problem launching my web project on eclipse i had problem with tomcat 7so i delete tomcat 7 from eclipse and then i added it again again tomcat 7now i have no problem launching my web project but i have problem on my servletfor example i get error like webservlet cannot be resolved to a type the attribute value is undefined for the annotation type i added servletapi 30jar to my project but i still have these problemsthis is the code of my servlet package jeans import javaioioexception import javaioinputstream import javasqlconnection import javasqlpreparedstatement import javasqlsqlexception import javaxservletservletexception import javaxservlethttphttpservlet import javaxservlethttphttpservletrequest import javaxservlethttphttpservletresponse import javaxservletannotationwebservlet import comsunjavaswingplafwindowstmschemapart import javaxservlethttppart webservletfileuploaddbservlet i got an error here multipartconfigmaxfilesize 16177215 public class fileuploaddbservlet extends httpservlet private string dburl db private string dbuser dbuser private string dbpass dbpassword string messagemio da contorllare gestionedb gestionedb boolean connessione connection conn protected void doposthttpservletrequest request httpservletresponse response throws servletexception ioexception string giorno requestgetparametergiorno string mese requestgetparametermese string anno requestgetparameteranno string dataformatoitaliano giorno mese anno string titolo requestgetparametertitolo string titoletto requestgetparametertitoletto string testomouse requestgetparametertestomouse string link requestgetparameterlink string data dataformatoitaliano string testo requestgetparametertesto i got an error here part filepart requestgetpartimmagineprincipale string didascaliaimmagineprincipale requestgetparameterdidascaliaimmagineprincipale inputstream immagineprincipale null if filepart null obtains input stream of the upload file immagineprincipale filepartgetinputstream string message null try gestionedb new gestionedb conn gestionedbcn gestionedbinserimentonewstitolo titoletto testomouse link testo data immagineprincipale didascaliaimmagineprincipale string sql insert into allegati news allegatodidascaliatipoid newsimmagine values preparedstatement statement connpreparestatementsql statementsetstring1 firstname statementsetstring2 lastname statementsetint3 1 statementsetint41 if immagineprincipale null statementsetblob5 immagineprincipale int row statementexecuteupdate if row 0 message file salvato nel db catch sqlexception ex message error exgetmessage exprintstacktrace finally if conn null try connclose catch sqlexception ex exprintstacktrace requestsetattributemessage gestionedbgetinserimentonewmessaggio getservletcontextgetrequestthispatchermessagejspforwardrequest response this is my webxml filexml version10 encodingutf8webapp xmlnsxsi xmlns xmlnsweb 2 5xsd xsischemalocation 2 5xsd idwebapp id version25 thisplaynamejeans2thisplayname welcomefilelist welcomefileindexhtmlwelcomefile welcomefileindexhtmwelcomefile welcomefileindexjspwelcomefile welcomefiledefaulthtmlwelcomefile welcomefiledefaulthtmwelcomefile welcomefiledefaultjspwelcomefile welcomefilelist servlet descriptiondescription thisplaynameprovathisplayname servletnameprovaservletname servletclassjeansprovaservletclass servlet servletmapping servletnameprovaservletname urlpatternprovaurlpattern servletmapping servlet descriptiondescription thisplaynamefileuploaddbservletthisplayname servletnamefileuploaddbservletservletname servletclassjeansfileuploaddbservletservletclass servlet servletmapping servletnamefileuploaddbservletservletname urlpatternfileuploaddbservleturlpattern servletmapping servlet descriptiondescription thisplaynameblobthisplaythisplayname servletnameblobthisplayservletname servletclassjeansblobthisplayservletclass servlet servletmapping servletnameblobthisplayservletname urlpatternblobthisplayurlpattern servletmappingwebapp,['java'] +562286,which orm for nodejs i know this is a common question but i have done tests and i need some particular featuresthe features i need aremap properties to column namesuse a table name different from the model namesupport for softdeletes paranoid mode on sequelizesupport for record timestamping with the ability to specify for every different model the column namesupport for foreign keysmust support mysql and sqlitethe architecture must support a model per fileoptional featurescache support for rethismemcachecommand line tool to generate models from databasei have testednodeormto handle own column names you need a workaroundsoft deletes are not supported and cannot be supported even using an external plugin i tried to wrote one using beforeremove hook but i can stop it from removing the recorddo not support a model per file you need a workaroundsequelizedo not create foreign keyscannot map properties to column namessupport a model per file but it does not work very well you need to put relationship in the file that include the modelsnodepersisti do not like the need to specify the connection instance for everythingright now i am going to test jugglingdb and bookshelfjs but i do not like too much the last one,"['javascript', 'mysql']" +562314,how to consume a webapi from aspnet web api to store result in database how to consume a webapi from another aspnet web api to store the response in a databasei know how to consume a webapi from clients like javascriptconsole application etcbut the requirement is to pull the data from third party api by my webapi store the result in a database so that using my webapi my clients request me for datahow can it be possible using aspnet web api,"['c#', 'asp.net']" +562336,webglglsl how does a shadertoy work i have been knocking around shadertoy recently in an effort to learn more about opengl and glsl in particular from what i understand so far the opengl user first has to prepare all the geometry to be used and configure the opengl server number of lights allowed texture storage etc once that is done the user then has to provide at least one vertex shader program and one fragment shader program before an opengl program compileshowever when i look at the code samples on shadertoy i only ever see one shader program and most of the geometry used appears to be written directly into the glsl codehow does that workmy guess is that a vertex shader is already prepared upfront and that the editablesample shader is only a fragment shader but then that does not explain the geometry in some of the more complex examplescan anyone explain how shadertoy works,['javascript'] +562340,how to get the coordinates for the selected text in uiwebview i have simple uiwebview with loaded html file i want to show the popovercontroller pointed to the selected text like i want the coordinates of selected text from uiwebviewif i set the scalespagetofit property of uiwebview to no then this link works fine if i set the scalespagetofit property of uiwebview to yes then it failsanyone please help me to sort out my problem,"['javascript', 'iphone', 'ios']" +562392,how to identify port number of sql server i install sql server in my system and i have to check on which port number sql is working in my system,['sql'] +562435,datatemplate key is ignored when specified with xstatic i encountered weird behavior with datatemplate keys when datatype is specified via xtype and xkey is specified via xstatic reference xkey is ignored i wrote sample app to illustrate itxaml resourcesdatatemplate datatypextype wpfapplication1testdto xkeyxstatic wpfapplication1datakeystestdtokey datatemplate xkeyxstatic wpfapplication1datakeystestdtokey2 datatemplate datatypextype wpfapplication1testdto xkeytestkey3 datatemplate datatypewpfapplication1testdto xkeyxstatic wpfapplication1datakeystestdtokey4 cpublic class testdto public static class datakeys public static string testdtokey testkey public static string testdtokey2 testkey2 public static string testdtokey4 testkey4launch application see thisresourceskeys in debuggerdatatemplatekeywpfapplication1testdto object systemwindowsdatatemplatekeytestkey2 object stringtestkey3 object stringtestkey4 object stringas you can see in first case xkey is ignoredcan someone explain what is going on documentation clearly says that setting xkey will set resource key to whatever you specify in it,['c#'] +562436,why does fileinputstream read method in java return a int not a short i aware that byte is not a proper type enough to contain result of read methodso read method returns int type valuebut i think a short type is more efficient type than intit could contain the value of range 256 255why does read method return int not short,['java'] +562451,examples of interactive plots through python just wondering if there are examplesmay be ipython notebooks of rendering interactive plots in python that are bit more involved than simple barline plotsi did look at d3py and vincent in the case of latter i was not able to find any example of interactive graphics but only static images using d3js for d3py i am looking for an interesting graphics beyond simpler demo bar line plotsany ipython notebook demonstrating the same would be very helpful it will be good to know if there are other packages that i should be keeping on my radar did have a quick look at bokeh but not sure if i shud wait a bit before it is more stable and has some documentationps looking for something that can be slickly integrated into a webpage,['python'] +562455,android when why should i use framelayout instead of fragment i am building a layout for large screens that is supposed to consist of 2 different parts a left one and a right one for doing that i thought using 2 fragments is the right choice then i had a look on the example of the navigation with the masterdetailflow it has a 2pane layout where on the right is the navigation and on the left is the detail viewbut in that example different from what i expected to see for the detail view there is a framelayout that then holds a fragment instead of a fragment directlythe layout xml looks like this an examplelinearlayout xmlnsandroid xmlnstools androidlayout widthmatch parent androidlayout heightmatch parent androidlayout marginleft16dp androidlayout marginright16dp androidbaselinealignedfalse androiddividerandroidattrdividerhorizontal androidorientationhorizontal androidshowdividersmiddle toolscontextworkstationlistactivity fragment androidididworkstation list androidnamedetuhhipmtialphistoryworkstationlistfragment androidlayout width0dp androidlayout heightmatch parent androidlayout weight1 toolslayoutandroidlayoutlist content framelayout androidididworkstation detail container androidlayout width0dp androidlayout heightmatch parent androidlayout weight3 linearlayoutmy question now is why is a framelayout used instead of the fragment itself for the detail view what is the reason or the advantage should i use it too,['android'] +562468,border for css shapes i have thiscovered css shapes and i am interested is there a way to make border solid dotted dashed for them shapesthe first thing that i have though about was to made another shape and put it on the background by zindex but it makes an effect only as solid borderhtmldiv classtriangledivdiv classbackgrounddivcss triangle position absolute top 14px left 10px height 0px width 0px borderright 50px solid transparent borderleft 50px solid transparent borderbottom 100px solid red zindex 0 background position absolute top 0 left 0 height 0px width 0px borderright 60px dotted transparent borderleft 60px dotted transparent borderbottom 120px dotted gray zindex 1,"['javascript', 'jquery', 'html', 'css']" +562479,stop form refreshing page on submit how would i go about preventing the page from refreshing when pressing the send button without any data in the fieldsthe validation is setup working fine all fields go red but then the page is immediately refreshed my knowledge of js is relatively basicin particular i think the processform function at the bottom is badhtmlform idprospects form methodpost input idform name tabindex1 classboxsize typetext namename placeholderfull name maxlength80 value input idform email tabindex2 classboxsize typetext nameemail placeholderemail maxlength100 value input idform subject classboxsize typetext namesubject placeholdersubject maxlength50 valueform row for oubc textarea idform message classboxsize namemessage placeholdermessage tabindex3 rows6 cols5 maxlength500textarea button idform send tabindex5 classbtn typesubmit onclickreturn processformsendbutton div idform validation span classform captcha codespan input idform captcha classboxsize typetext nameform captcha placeholderenter code tabindex4 value div div classclearfixdivformjsdocumentreadyfunction add active class to inputsprospects form boxsizefocusfunction thisaddclasshastext form validation boxsizefocusfunction thisparentaddclasshastext remove active class from inputs if emptyprospects form boxsizeblurfunction if thisvalue thisremoveclasshastext form validation boxsizeblurfunction if thisvalue thisparentremoveclasshastext start validationprospects formreadyfunction define global variables var valname form name valemail form email valemailformat ss0913091309130913azaz09azaz2 valmsg form message valcaptcha form captcha valcaptchacode form captcha code generate captcha function randomgen var rannumber iterate through 1 to 9 4 times forrannum1 rannum4 rannum rannumbermathfloormathrandom10tostring apply captcha to element valcaptchacodehtmlrannumber randomgen captcha validation valcaptchablurfunction function formcaptcha if valcaptchaval valcaptchacodehtml incorrect valcaptchaparentaddclassinvalid return false else correct valcaptchaparentremoveclassinvalid return true formcaptcha remove invalid class from captcha if typing valcaptchakeypressfunction valcaptchaparentremoveclassinvalid email validation blur valemailblurfunction function formemail if valemailformattestvalemailval valemailval incorrect valemailaddclassinvalid else correct valemailremoveclassinvalid formemail remove invalid class from email if typing valemailkeypressfunction valemailremoveclassinvalid validation on submit prospects formsubmitfunction consoleloguser hit send button email validation submit function formemailsubmit if valemailformattestvalemailval incorrect valemailaddclassinvalid else correct valemailremoveclassinvalid formemailsubmit validate captcha function formcaptchasubmit if valcaptchaval valcaptchacodehtml captcha is correct else captcha is incorrect valcaptchaparentaddclassinvalid randomgen formcaptchasubmit if name field is empty function formnamesubmit if valnameval name is empty valnameaddclassinvalid else valnameremoveclassinvalid formnamesubmit if message field is empty function formmessagesubmit if valmsgval name is empty valmsgaddclassinvalid else valmsgremoveclassinvalid formmessagesubmit submit form if all good function processform if formemailsubmit formcaptchasubmit formnamesubmit formmessagesubmit prospects formattraction clientsoubcrowforoubcsendphp form sendattrtype submit return true else if formemailsubmit valemailaddclassinvalid return false else if formcaptchasubmit valcaptchaparentaddclassinvalid return false else if formnamesubmit valnameaddclassinvalid return false else if formmessagesubmit valmsgaddclassinvalid return false else return false end validation,"['javascript', 'jquery', 'html']" +562482,what are the sizes of the icons in android notifications actionbuttons in expandable notifications what dimensions in dp should the icons havelike the icons for snooze and email here,['android'] +562501,can i run numpy and pandas with jython we have some java code we want to use with new code we plan to write in python hence our interest in using jython however we also want to use numpy and pandas libraries to do complex statistical analysis in this python code is it possible to call numpy and pandas from jython,['python'] +562531,sprite kit skshapenode creating two nodes instead of one i am new to ioss sprite kit i want to add a shape node to my scene the scene is gray and the shape is a white circle in the center of the scene my scene code is below for some reason the last line that adds the node to the scene causes the node count to go up by two if i leave that line out there is 0 nodes and just a gray scene but if i leave the line then the circle is there but the node count is 2 this is a big problem because as i add more nodes to the circle the node count is double what it should be and slows things down anyone know what the problem is much appreciatedinterface colorwheelsceneproperty bool contentcreatedendimplementation colorwheelscene voiddidmovetoviewskview view ifselfcontentcreated self createscenecontents selfcontentcreated yes voidcreatescenecontents selfbackgroundcolor skcolor graycolor selfscalemode skscenescalemodeaspectfit skshapenode wheel skshapenode allocinit uibezierpath path uibezierpath alloc init path movetopointcgpointmake00 00 path addarcwithcentercgpointmake00 00 radius500 startangle00 endanglem pi20 clockwiseyes wheelpath pathcgpath wheelfillcolor skcolor whitecolor wheelposition cgpointmakecgrectgetmidxselfframe cgrectgetmidyselfframe self addchildwheelend,['ios'] +562667,send a link in an email using uiactivityviewcontroller how do i send an email using uiactivityviewcontroller with a quick message and a link i have tried using an nsurlnsurl url nsurl urlwithstringand an nsstring string with hyperlink syntaxnsstring stringurlhyperlink a hrefgooglea plain text link out of desperationnsstring stringurlplain i am not using a custom uiactivity the nsstringnsurl are being sent as activityitemsnsarray activityitems linkuiactivityviewcontroller activityviewcontroller uiactivityviewcontroller alloc initwithactivityitemsactivityitems applicationactivitiesnilthanks everyoneedit 1my apologies i should have made my question clearer how can i send a message and a clickable link in an email using uiactivityviewcontroller,"['ios', 'objective-c']" +562728,thismissing a uidocumentinteractioncontroller in some cases will remove the presenting view controllers views in ios 7 ipad when the uidocumentinteractioncontroller is thismissed the presenting view controllers views are removed including elements from the uinavigationcontroller the uidocumentinteractioncontroller thismisses and the presenting view controllers views are removed leaving a plain whitegray box where the presenting view controller formerly existed the app no longer responds to any touch events after this pointthis occurs on ipad simulator ios 70 and ipad 3 wifi running ios 7 for quick look pdf readerdoes not matter whether the application was compiled against the ios 61 or ios 7 sdkplease let me know your suggestions,"['iphone', 'objective-c']" +562756,variadic template class argument containers instantiation i want to instantiate a variadic template class storetargs that has a stdvector for each type in the targs packtemplatetypename targs class store obviously not valid code assuming each type of targs has a unsigned int id that can be retrieved with getidt stdarraysizeoftargs stdvectortargs bags templatetypename t void addt mvalue bagsgetidtpush backmvalue templatetypename t stdvectort get return bagsgetidt let us say i have a storeint float double i obviously know at compile time that it will be able to store int float and double valuesi could use template specializationstemplate class storeint float double stdvectorint vi stdvectorfloat vf stdvectordouble vd templatetypename t void addt template void addintint mvalue vipush backmvalue template void addfloatfloat mvalue vfpush backmvalue template void adoubledouble mvalue vdpush backmvalue but that would require handwriting every possible combination of types and would not work with userdefined typesi am confident the compiler knows everything that is required to generate a class like storeint float double using variadic templates is there a way to actually express this intent,['c++'] +562786,apply css style on all elements except with a specific id css codewhat i needstyle dividdiv1 i actually needed an inequality operator for not equal to fontsize40px stylehtml codebody divabcdiv divdefdiv div iddiv1ghidivbodythe css did not work as i intendedi actually wanted to define the style for all divelements except the one with iddiv1how can i do that,"['html', 'css']" +562799,proximity sensor strange operation ios i am developing an application that requires the proximity sensor constantly active during executioni put this code in the app delegateuiapplication sharedapplicationidletimerthisabled yesuidevice currentdeviceproximitymonitoringenabled yesthe problem is that after a short period of time even though the sensor is covered the diplay lights upi have tried using thirdparty applications that make use of the sensor and the thisplay remains darkdoes anyone know how to fix it thanks,"['ios', 'iphone', 'objective-c']" +562815,debug assertion failed c vector subscript out of range the following code fills the vector with 10 values in first for loop in second for loop i want the elements of vector to be printedthe output is till the cout statement before the j loopgives error of vector subscript out of rangeinclude stdafxhinclude iostreaminclude vectorusing namespace stdint tmainint argc tchar argv vectorint v couthello indiaendl coutsize of vector is vsizeendl forint i1i10i vpush backi coutsize of vector vsizeendl forint j10j0j coutvj return 0,['c++'] +562823,jquery chosen get selected option text label not the value how to get the selected options text from the chosen select so not just the val but the option labeltext,['jquery'] +562874,how can i create a one time download link with amazon s3 i want to create a one time download link to an amazon s3 hosted file this link expires once the file has been downloadedi want this file to still be hosted but a visitor can only download the file oncethe scenario i need this for is i have a file download website where users pay for a file i want the user to only be able to download the file once from the website and amazon s3 i also do not want the user to be able to share a direct download link with other people if this is not possible i wonder if it is more efficient to limit it by an ip address or cookie if possible,"['php', 'jquery']" +562896,black screen in genymotion my genymotion installation is unable to start my virtual devices the same virtual devices starts properly in virtualbox only black screen with button on right side appears in genymotion buttons works opens dialogs and emulator is connected to adb and i am able to start applications from eclipse,['android'] +562916,why cannot we call protected destructors from a derived class i am aware of the uses of private and of course public destructorsi am also aware of the uses of a protected destructor in a derived classuse a protected destructor to prevent the destruction of a derived object via a baseclass pointerbut i have tried running the following code and it would not compilestruct a int i a i 0 protected astruct b public a a a b a new a void f delete a int main b b b bf return 0i get void bfmaincpp916 error aa is protectedwhat am i missingif i called a protected method in a from inside f it would work so why is calling the dtor different,['c++'] +562944,ghost custom pagination i just design a theme for ghost blogging platform by reading the ghost theme documents all i need now is customizing the pagination the document says create a paginationhbs inside the partial folder but the problem is i do not know how should the markup be,['html'] +563020,representing graphs data structure in python how can one neatly represent a graph in python starting from scratch ie no librarieswhat data structure eg dictstuplesdicttuples will be fast but also memory efficientone must be able to do various graph operations on itas pointed out the various graph representations might help how does one go about implementing them in pythonas for the libraries this question has quite good answersthanks,['python'] +563021,exception safety and make unique just to clarify using make unique only adds exception safety when you have multiple allocations in an expression not just one correct for examplevoid ftfnew tis perfectly exception safe as far as allocations and stuff whilevoid ft tfnew t new tis not correct,['c++'] +563076,detect whether an element has positionfixed possibly by parent element via jquery update i would like to avoid walking back through all the elements parents testing each in turn but that is the best solution i have managed to find so far as in this answerinside an event handler i would like to detect whether the target elements position is relative to the viewport fixed or the document static relative or absolute given that an elements position might be fixed because it has positionfixed or because one of its parents is positionfixed what is an efficient way of detecting fixed positioning for the elementfor examplecssone positionrelative height10px width10pxtwowrapper positionfixed bottom0 height10px width10pxtwo height10px width10pxhtmldiv idone classtriggereventelement onedivdiv idtwowrapper div idtwo classtriggereventelement twodivdivjsdocumentreadyfunction triggereventonmouseenter functionevent var isfixed if isfixed eventtargetcssbackgroundred else eventtargetcssbackgroundgreen,"['javascript', 'jquery', 'html', 'css']" +563113,add an activity indicator on a uiwebview i have a viewdidload which creates a web view and starts an activity indicator how do i make the activity indicator stop only when the web page appears how do i add words to the activity indicator like loading create the uiwebviewuiwebview webview uiwebview alloc initwithframeselfviewboundsselfview addsubviewwebview start the throbber to check if the user existsuiactivityindicatorview activityviewuiactivityindicatorview alloc initwithactivityindicatorstyleuiactivityindicatorviewstylegrayactivityviewcenter cgpointmakeself screenwidth 20 3700activityview startanimatingactivityviewtag 100selfview addsubviewactivityviewnsstring url nsurl nsurl nsurl urlwithstringurlnsurlrequest request nsurlrequest requestwithurlnsurl cachepolicynsurlrequestreloadignoringlocalandremotecachedata timeoutinterval30 remove activity viewuiview viewtoremove selfview viewwithtag100viewtoremove removefromsuperviewwebview loadrequestrequest,['ios'] +563158,ngcloak directive gets removed too early i have an angularjs app with some controllers that should not be shown initially they flash on the screen despite my use of ngcloak the problem seems to be that compile gets called and removes the ngcloak directives and class this makes the controllers contents visible even though it should not be because ngshow is false if i pause js execution in ngcloaks compile method i can see the elements appear as the ngcloak directive is removed if i pause js execution in the controller for example on scopevisible false i can see the controller stays visible on the page the controller is then invisible again as it should be sometime later in loadingi am loading my appjs and angularjs in the document headi have my css in the document headi have included the ngcloak css rule with important in my external css and inlinehow can i prevent this flashing why does not ngcloak pay respect to ngshowindexhtmldiv ngcloak classngcloak ngcontrollerroomscontroller ngshowvisible h1this flashes it can be seen if we set a breakpoint in the controller js or after the ngcloak directives compile method in angularjsh1divappjs appcontrollerroomscontroller scope function scope scopevisible false,"['javascript', 'html']" +563250,does visual studio express 2013 come with blend how can i open it i have been looking a for a while today and i did not find anything about it there is a lot about blend for visual studio 2013 but does it come with the express version for desktop and if it does how can i access to it or download itthanks,['c#'] +563269,how to start an ios app with a modal view controller already presented without the user being able to see the presenting view i have tried many combinations of doing this from the app delegate the presenting view controllers viewdidload with and without delay with and without animationbut either the user can see the presenting view controller for a moment or the modal does not get presented how can this be achieved,"['ios', 'objective-c']" +563299,send data to server through json i m new on android programmeri want to send data to server through json in following format and implement json in this formatand also want to fetch data from serverurl signup signup username test1264 password 1234 email phoneno 223344556 altphoneno 12345678 firstname abc lastname xyz responseon success status1 on failure status0json for user loginlogin usernametest1234 password1234 responseon success user firstname abclastname xyzemail phone 99887766username test1234on failure errorauth error,['android'] +563347,representation of mac address in c code i often see such representation of mac address in c codestruct mac addr unsigned char bytes6why necessary put an array in a structure why not just have an array what benefit does this providethanks,['c'] +563353,get list from pandas dataframe column headers i want to get a list of the column headers from a pandas dataframe the dataframe will come from user input so i would not know how many columns there will be or what they will be calledfor example if i am given a dataframe like this my dataframe y gdp cap0 1 2 51 2 3 92 8 7 23 3 4 74 6 7 75 4 8 36 8 2 87 9 9 108 6 6 49 10 10 7i would want to get a list like this header listy gdp cap,['python'] +563470,thisplay clear colored viewcontroller over another viewcontroller in ios 7 prior to ios 7 according to this popular stackoverflow question the way to show a viewcontroller with a clear background was to do the following in the main viewcontroller uistoryboard storyboard uistoryboard storyboardwithnamemainstoryboard bundlenil uiviewcontroller vc storyboard instantiateviewcontrollerwithidentifiersecondviewcontroller vcviewbackgroundcolor uicolor clearcolor selfmodalpresentationstyle uimodalpresentationcurrentcontext self presentviewcontrollervc animatedno completionnilhowever as i have recently thiscovered with ios 7 and as commented by others to the main answer the above solution no longer works and instead just shows a black model controller i know that transparency is largely used in ios 7 so that transparent view controller is very likely possible i have not thiscovered a workaround to this issue yet and was wondering if anyone knows how to resolve this problem thanks,"['iphone', 'ios']" +563480,exclude airdrop and add to reading list from apps build with ios 6 sdk i have a uiactivityviewcontroller in my ios 6 app i am pushing an update but i am not yet compiling it with ios 7 sdkis there any way to thisable add to reading list and airdrop in my uiactivityviewcontroller in ios7 without recompiling with ios 7 sdk,['ios'] +563495,failed to load webpage error nsurlerrordomain error 9 i have phonegap project where i have requirement for open iframe where i am trying to open an iframe with javascript i get the error in ioserror the operation could not be completed nsurlerrordomain error 9anyone here knows about this error or how to open iframe in phonegap ios,"['ios', 'iphone']" +563525,what is the difference between globalasax and globalasaxcs tell me about the difference between globalasax and globalasaxcs and if i click the both file in my solution explorer it is goes to only server asaxcs side why and how and can i see client sideglobalasax page,"['c#', 'asp.net']" +563534,asset catelog issue with multiple targets i have a project with multiple targets assume the targets are named targeta targetb and so on for every target i have a different asset catalog of app icons they are named as appicon a appicon b and it goes on for all the targets i have assigned respective asset catalogs to all targets but it only shows the icons for targeta when i run on the device simulator for all other targets it does not set any icons and shows ios 7 default placeholder iconplease help,['ios'] +563566,maven failed to clean project failed to delete orgow2utilasmasmtree31jar i use stsspring tool suite maven pluginevery time when i run my application using mavenclean i see following errorinfo scanning for projectsinfo info info building hhsystem ui 100snapshotinfo info info mavencleanplugin241clean defaultclean ui info deleting cusersnikolay tkachevworkspacehhsystemuitargetinfo info build failureinfo info total time 0471sinfo finished at mon oct 21 123433 msk 2013info final memory 2m90minfo error failed to execute goal orgapachemavenpluginsmavencleanplugin241clean defaultclean on project ui failed to clean project failed to delete cusersnikolay tkachevworkspacehhsystemuitargetorgow2utilasmasmtree31jar help 1error error to see the full stack trace of the errors rerun maven with the e switcherror rerun maven using the x switch to enable full debug loggingerror error for more information about the errors and possible solutions please read the following articleserror help 1 i have to close sts and go to cusersnikolay tkachevworkspacehhsystemuitarget and delete orgow2utilasmasmtree31jarafter starting sts again it works but this is a hasslecan you help me with this problemupdatefor kalathoki li run mavenclean from this statei see same behaviour from the command line as from the eclipse pluginif i watch unlocker when sts is running i see,['java'] +563579,does cast between signed and unsigned int maintain exact bit pattern of variable in memory i want to pass a 32bit signed integer x through a socket in order that the receiver knows which byte order to expect i am calling htonlx before sending htonl expects a uint32 t though and i want to be sure of what happens when i cast my int32 t to a uint32 tint32 t x somethinguint32 t you uint32 t xis it always the case that the bytes in x and u each will be exactly the same what about casting backuint32 t you somethingint32 t x int32 t ui realise that negative values cast to large unsigned values but that does not matter since i am just casting back on the other end however if the cast messes with the actual bytes then i cannot be sure casting back will return the same value,['c'] +563620,self executing function jquery vs javascript difference what are the difference among first function var book hellosecondfunction var book hellofirst and second are similar some how in workthird function var book hellojquerywhat pattern i need to use and where in my coding third module pattern i have seen while i was reading a article related to backbonejswhat i understood from third one self executing function with the argument ajquerya can any please give me some idea about immediately invoked function expressions iifethanks,"['javascript', 'jquery']" +563630,could not load file or assembly systemwebhttp 400 after update from 2012 to 2013 i did the upgrade according to i get the error does any one else got this errorserver error in applicationcould not load file or assembly systemwebhttp version40 cultureneutral publickeytoken31bf3856ad364e35 or one of its dependencies the located assemblys manifest definition does not match the assembly reference exception from hresult 0x80131040 description an unhandled exception occurred during the execution of the current web request please review the stack trace for more information about the error and where it originated in the code exception details systemiofileloadexception could not load file or assembly systemwebhttp version40 cultureneutral publickeytoken31bf3856ad364e35 or one of its dependencies the located assemblys manifest definition does not match the assembly reference exception from hresult 0x80131040source error line 48 line 49 line 50 line 51 line 52 protected void application beginrequestobject sender eventargs esource file dsm74testwebapiserverv2thirdpartywebapiglobalasaxcs line 50 assembly load trace the following information can be helpful to determine why the assembly systemwebhttp version40 cultureneutral publickeytoken31bf3856ad364e35 could not be loaded prebind state information log thisplayname systemwebhttp version40 cultureneutral publickeytoken31bf3856ad364e35 fullyspecified log appbase filedsm74testwebapiserverv2thirdpartywebapi log initial privatepath dsm74testwebapiserverv2thirdpartywebapibin calling assembly thirdpartywebapi version10 cultureneutral publickeytokennull log this bind starts in default load context log using application configuration file dsm74testwebapiserverv2thirdpartywebapiwebconfig log using host configuration file cusersmichalcdocumentsiisexpressconfigaspnetconfig log using machine configuration file from cwindowsmicrosoftnetframeworkv4030319configmachineconfig log postpolicy reference systemwebhttp version40 cultureneutral publickeytoken31bf3856ad364e35 log attempting download of new url filecwindowsmicrosoftnetframeworkv4030319temporary aspnet filesroot9184b2eac6d4b139systemwebhttpdll log attempting download of new url filecwindowsmicrosoftnetframeworkv4030319temporary aspnet filesroot9184b2eac6d4b139systemwebhttpsystemwebhttpdll log attempting download of new url filedsm74testwebapiserverv2thirdpartywebapibinsystemwebhttpdll wrn comparing the assembly name resulted in the mismatch major version err failed to complete setup of assembly hr 0x80131040 probing terminatedstack trace fileloadexception could not load file or assembly systemwebhttp version40 cultureneutral publickeytoken31bf3856ad364e35 or one of its dependencies the located assemblys manifest definition does not match the assembly reference exception from hresult 0x80131040 thirdpartywebapiwebapiapplicationapplication start in dsm74testwebapiserverv2thirdpartywebapiglobalasaxcs50httpexception 0x804005 could not load file or assembly systemwebhttp version40 cultureneutral publickeytoken31bf3856ad364e35 or one of its dependencies the located assemblys manifest definition does not match the assembly reference exception from hresult 0x80131040 systemwebhttpapplicationfactoryensureappstartcalledforintegratedmodehttpcontext context httpapplication app 9935033 systemwebhttpapplicationregistereventsubscriptionswithiisintptr appcontext httpcontext context methodinfo handlers 118 systemwebhttpapplicationinitspecialhttpapplicationstate state methodinfo handlers intptr appcontext httpcontext context 172 systemwebhttpapplicationfactorygetspecialapplicationinstanceintptr appcontext httpcontext context 336 systemwebhostingpipelineruntimeinitializeapplicationintptr appcontext 296httpexception 0x804005 could not load file or assembly systemwebhttp version40 cultureneutral publickeytoken31bf3856ad364e35 or one of its dependencies the located assemblys manifest definition does not match the assembly reference exception from hresult 0x80131040 systemwebhttpruntimefirstrequestinithttpcontext context 9913572 systemwebhttpruntimeensurefirstrequestinithttpcontext context 101 systemwebhttpruntimeprocessrequestnotificationprivateiis7workerrequest wr httpcontext context 254version information microsoft net framework version4030319 aspnet version403031918408,['c#'] +563738,error executing command ant on mac os x 109 mavericks when building for android with phonegapcordova today i tried phonegapcordova with mac os x mavericks building for ios went just fine but building for android was not without some guessworki installed android 422 via the android sdk manager i had to use the older api v17 since it was not compatible with a newer one added the path environment variables for the sdks platformtools and tools and thought i was ready to take off by running the command phonegap run androidnevertheless i got the following errorphonegap detecting android sdk environmentphonegap using the local environmentphonegap adding the android platformerror an error occured during creation of android subproject error executing command ant make sure you have ant installed and added to your path,['android'] +563744,issue with using multiple asset catalogs in xcode 5 i have one app that has 2 variations that only differ in branding for each version i have an appicon and launchimage in an asset catalog i have created a different target for each version in the second version when i try and select appicon in the second asset catalog it just defaults to the first one removing the first asset catalog seems to resolve it but i would prefer a less hacky solution,['ios'] +563848,what is difference between scanfd and scanfd include stdiohint mainvoid int i j printfenter a value for j scanfd j printfj is d n j printfenter a value for i scanfdi printfi is d n i return 0how does the scanf function actually work when i add spaces after the format specifier like scanfd j,['c'] +563870,any way to generate a c httpclient wrapper for a webapi project in an upcoming project we are looking to use aspnet webapi 2 to expose service functionality to both our web sites and browser clientssince we want as few endpoints as possible where possible we want all calls even internal to consume our servers from the webapi web services ie not just newing up a controller instance directlyi am looking for something to help generate or scaffold c clients that wrap the httpclient and deliver strongly typed proxys similar to wcf when generating proxys via add new service referencei have read other questions asking similar things as seen here but wanted to ask a more direct question not related to mvc or testing concerns,"['c#', 'asp.net']" +563898,gcd vs performselectorinbackgroundperformselectoronmainthread i am new in ios development i have following questionswhen we use gcdthispatch group async thispatch asyncthispatch get main queue and when we use performselectorinbackgroundperformselectoronmainthreadwhats the differences between those twoi know when we use performselectorinbackground we create a new nsthread but is not the same when we use thispatch group async because if we create more than one thispatch group async it means we need to submit more than one blocks in queue and those blocks might run on different queues therefore when we create more than one thispatch group async does it means we create a new thread because blocks may run on different queues i kind of confused about nsthread and block queuethanks,"['ios', 'objective-c']" +563901,add spaces between panels in bootstrap 30 i am using bootstrap 30 and cannot seem to figure out how to add padding space between panelsdiv classrow div classcolxs4 panel div classpanelbody h4first cellh4 div div div classcolxs4 panel div classpanelbody h4second cellh4 div div div classcolxs4 panel div classpanelbody h4third cellh4 div divdivi have tried adding a class and setting the width to 30 but it only works if you have two panels and pull the one right if i add a margin then it throws the responsiveness off and the last cell drops to the next linehow can i responsively add a gap between the panels,"['html', 'css']" +563915,angular js startswith custom filter so i have been trying a while to make a custom filter that searches for the startswith parameters rather than the contains every filter that i have written have not seem to work properly here is an example of what i am trying to achieve function filterctrl var scope thisscopedofilter functionelem ifscopesearchtext return true return elemlast nametolowercaseindexof scopesearchtexttolowercase 0 here is where i am at right now ul border1px ngrepeatmsg in messages filtersearchstrictlimsglast nameliany help would be greatly appreciated,"['javascript', 'jquery']" +564005,afhttpclientm no longer in afnetworking i am following a tutorial that uses afnetworking it says to make a new class that is subclassed from afhttpclient this option does not appear in the subclass of field i checked the afnetworking folder and there is no afhttpclientm implementation file has this file been renamed to something else thanks,['ios'] +564027,css3 keyframe animations end and stay on the last frame i have run into some difficulty trying to play a css3 keyframe animation and have the relevant element stick at the last frame after the animation has completed to my understanding the property that i have to set for this to work should be animationfillmode which should have the value of forwards this does not do anythinganimatedsprite animationname sprite animationduration 5s animationiterationcount 1 animationdirection normal animationtimingfunction steps3 animationfillmode forwards vendor prefixes this will just play the animation once and then go back to the first frame i found an example of keyframe animations at jsfiddle and changing the fill mode to forwards and setting the iteration count to 1 wouldnt do anything there either any help would be greatly appreciated,"['javascript', 'css']" +564060,why does execvp take a char const argv i am wondering if there is a reason between two exec functions differing in constness of if this is just a bug in the single unix specexcerpting from the linux manpage which appears to align with the single unix specification here are a two versions of execint execlpconst char file const char arg int execvpconst char file char const argvexeclp takes its arguments as const char and it takes two or more of them const in c is a promise that the function will not change the pointedto data in this case the actual characters char that make up the stringexecvp instead takes its arguments as an array of pointers however instead of an array of pointers to const char as youd expect the const keyword is in a different spotaand this matters quite a bit to c execvp is saying it may well modify the characters in the strings but it promises not to modify the arrayathat is the pointers to the strings so in other wordsint fake execvpconst char file char const argv argv0 some other string this is an error argv00 f change first letter to f this is perfectly ok a in particular this makes it hard technically prohibited to call execvp using cs stdstrings to cstr method which returns const char it seems like execvp really ought to take const char const argv in other words it ought to promise not to do either of the above changes,['c'] +564096,reload a table views data without clearing its selection state i have a table view with selectable rowswhen i reload the table view some new rows might be added or removed and some labels in the table views cells might change that is what i want to achieve by calling tableview reloaddataunfortunately that method also clears the table views whole state including the selection but i need to keep the selectionso how can i reload all the data in a table view while still keeping the selected rows selected,['ios'] +564124,why am i getting referenceerror getelementbyid is not defined i have a little javascript code i wrote and for some reason i am getting an error sayingreferenceerror getelementbyid is not definedhere is the functionwindowonloadfunction clearall updatepizzatoppings updatepizzatoppings updatepizzatoppings updatepizzatoppings function updatepizzatoppings var checkboxgetelementbyidselectbacon var picgetelementbyidbaconpic if checkboxchecked picstylevisibilityvisible else picstylevisibilityhidden i have made a little jsfiddle for it as well,['javascript'] +564135,embedded youtube videos do not play on ipad ios 7 while html5 search input is visible this is a bug that i have managed to fix by brute force but i do not understand why the solution workedthe problem was that embedded youtube videos werent working on a particular responsive site on ipad tested in ios7 in landscape view i managed to narrow it down to a particular css rule that was showing a search input in the header when the browser was wide enough so it would show in an ipads landscape view but not in its portrait viewafter a little more brute force fiddling i found that removing the typesearch from the input tag which causes it to fall back to the default typetext would fix the problem none of my searches have come up with an explanation for why this works though or even anyone else experiencing the same thingsome more details on the bugthe site works by showing an image at first which would be replaced via javascript with the youtube iframe when clicked after this first click it would autoplay on desktop browsers and on the ipad it would load the video but wouldnt play until the user presses it againif the typesearch input was visible thisplay block then tapping on the embedded video would not cause it to play there would be no visible response to the tap if i zoomed in and tapped on the controls at the top like the name of the video i could see them being underlined and testing showed that there was no element covering the iframe and intercepting eventsstrangely tapping on the very edge of the right hand side of the iframe would cause the video to start playing correctly otherwise changing the ipad to portrait view causing the search input to be hidden via css would enable the iframe to be clicked in order to start the video playing after that first click all the video controls would work regardless of whether or not the search input was showing,"['ios', 'css']" +564137,how do i test mandrill api with rspec so my client has reported that many of the emails are going to the wrong person and i would like to write some feature tests to find and make sure that they are receiving the email and what it says in my specs i have mandrill mailer which uses mandril api and before it sends out i would like to see what the message is for example create a new user account creates the user and then sends out a welcome email in devise it calls registrationmailernew registrationresourcedeliverwhich then sends a email to the user def new registrationuseruser userfind by emailuseremailmandrill mail template newregistrationsubject welcome to contentblvdto email useremail name userfull name vars first name userfull name unsubscribe configprotocolconfighostunsubscribeemailuseremailendin my mailer how do i test this mail objecti tried actionmailerbasedeliveries but it returns nil since i am using mandrill mailer so i tried mandrillmailertemplatemailermessagebut no luck thanks for the help,['ruby-on-rails'] +564169,control the download ordering of download manager in android have an use case like the followingthere are several files to download eg a b c d e fwhen the downloading is started say the a b is finished and c is downloading i would like to interrupt the download of c and start the download of ethen after e is finished if there is no other interruption continue to c d fso far form my research there is only cancel methoddownloadmanagerremovedownloadreferencehow to achieve this through download manager or are there other approach thanks private long startdownloadstring url uri downloaduri uriparseurl string filename storageutilsgetfilenamefromurlurl string destination null downloadmanager downloadmanager getsystemservicedownload service downloadmanagerrequest request new downloadmanagerrequest downloaduri requestsetallowednetworktypesdownloadmanagerrequestnetwork wifi downloadmanagerrequestnetwork mobile requestsetallowedoverroamingfalse requestsettitlefilename requestsetdescriptioncomexampleservices if storageutilsissdcardpresent storageutilsissdcardwrittenable storageutilscheckavailablestorage destination storageutilssdcard root try storageutilsmkdir catch ioexception e eprintstacktrace requestsetdestinationinexternalpublicdirdestination filename downloadreference downloadmanagerenqueuerequest logddownloaderstart download manager destination filename return downloadreference,['android'] +564179,how to get back the uibutton border in ios 7 i built an old project in ios sdk 61 in xcode 5 however the uibutton is borderless when the app runs on an iphone running ios 7 i have checked the xib is builds for project deployment target 50how can i config xcode 5 to build the project to show an ios 61style uibutton,['ios'] +564215,sql query dynamic table name in for i have a table tbl1 which has a column tbl names this column contains the name of some other tablesnow i want to write a query in the following formatselect from select tbl names from tbl1 i know that the query above will not work but how i can achieve this do i need to write a stored procedure or something like that and loop on each value of second query and execute first query thanks,"['mysql', 'sql']" +564247,add b prefix to python variable adding the prefix b to a string converts it to bytesbexamplebut i cannot figure out how to do this with a variable assuming string example none of these seem to workbstringb stringb stringis there a simple way to do this,['python'] +564352,sublime save all openloaded files that have names in sublime text 2 i want to be able to save all openloaded files that have namesi like how sublime can have files with filenames and have files that were never saved and can be closed and it remembers about the untitled files and reloads them without me having to save thembut when a file has a filename and has some changes in the buffer not yet saved sublime shows it as such with the filename and circle i close sublime and reopen it i sublime has remebered it as it was and so the changes are still not saved to the file that is great but i would like a command to save all but not the untitled onesthere is a save all option in the menu but it pops up a dialog box asking regarding saving of untitled fileswhat api functions would be involved to write a command that leaves the untitled ones as is and saves the ones with filenames and is there any example code i can run that uses those api functions,['python'] +564355,how does this prime number test in java work the code snippet below checks whether a given number is a prime number can someone explain to me why this works this code was on a study guide given to us for a java exampublic static void mainstring args int j 2 int result 0 int number 0 scanner reader new scannersystemin systemoutprintlnplease enter a number number readernextint while j number 2 if number j 0 result 1 j if result 1 systemoutprintlnnumber number is not prime else systemoutprintlnnumber number is prime,['java'] +564409,magento php 54 pdf invoice zend error magento is throwing a php error when i am trying to create pdf invoices because my client is running php 5419 fatal error declaration of zend pdf fileparserdatasource file construct must be compatible with zend pdf fileparserdatasource construct in varwvhostswebsitehttpdocsincludessrczend pdf fileparserdatasource filephp on line 41normally it is easy to fix this by editing the fileparserdatasourcephp and commenting out two lines the problem is that they run a zend pdf fileparserdatasource filephp that extends this script is there any solution available so that is possible to create pdf invoices with magento on a server running php 54,['php'] +564437,android studio debug application on device i have difficulties with with debugging at android studio after trying to launch application in debug mode device show alert with waiting for debugger title that never thisappear also i have androiddebuggabletrue in my manifest file and seems like device connected correctly because i can simply run my application without any problem what i am doing wrong,"['java', 'android']" +564491,thread exiting with uncaught exception my app is nearly done i am only doing the bugfixing now i am running into a problem that i sometimes randomly so not always the same time or after the same actions are done get my app crashed logcat just tells methreadid11 thread eixiting with uncaught exception group0x4134d2a0but there is no caused by what normally would come so i can actually catch the exception when it crashes randomly this gets written into my console20131022 153936 ddms nulljavalangnullpointerexception at comandroidmlibclientreadclientjava698 at comandroidmlibmonitorthreadprocessclientactivitymonitorthreadjava311 at comandroidmlibmonitorthreadrunmonitorthreadjava26320131022 153936 ddms nulljavalangnullpointerexception at comandroidmlibclientreadclientjava698 at comandroidmlibmonitorthreadprocessclientactivitymonitorthreadjava311 at comandroidmlibmonitorthreadrunmonitorthreadjava263but these are not classes of mine how can i catch the exception please be aware that i am not able to post the whole code here it is firstly too much and i am not allowed to the app crashes randomly i do not know why and how to handle it any suggestionsi am running the app on a galaxy note right now,"['java', 'android']" +564496,abstract class instantiation in c in depth i am reading c in depth by jon skeet currently and there is an example depicting code contracts with an abstract class implementing an interface which features as an accompanying class for the interface in code contracts terms a contract class for i am not going into details about the workings of code contracts herethe interface p 467contractclasstypeoficaseconvertercontractspublic interface icaseconverter string convertstring textthe abstract classcontractclassfortypeoficaseconverterinternal abstract class icaseconvertercontracts icaseconverter public string convertstring text contractrequirestext null contractensurescontractresultstring null return defaultstring returns dummy value prevents instantiation private icaseconvertercontracts i have added the comments in the code based on comments in the bookmy questionwhy is it necessary to add the private constructor to this abstract class when you cannot instantiate an abstract class to begin with what am i not getting,['c#'] +564544,mocking a private variable that is assumed to exist how can you get a mock object in at runtime when it is not createdinitialized in the class you are testing it is not static singleton pattern or you do not have some sort of test constructor to hook intoin a class that i am writing some unit testing for i have come across a scenario i have not encounteredsolved yet i have a jms resource a queueconnectionfactory for reference but it should not matter that is a private variable of the class i am testing since it has the javaxannotationresource annotation at runtime it is assumed to be available during testing it is not which creates the need for mocking this object it is not a static class and is not being used in a static way if it was i could easily mock using the various static mocking methods i have run into since the resource is never created locally in a constructor or even in a test constructor i have no way of passing in a mock object so that at runtime of the test the mock is used instead of the actual object how can i mock this resource so that when the test executes it will be used in place of the private resource object in the class i am testingfor reference the code is calling createconnection on the queueconnectionfactory which is throwing a null pointer exception since the factory has not been initializedmockedstatelesspublic class example resourcename jmsexampleqcf private queueconnectionfactory queuefactory public void testme connection connection queuefactorycreateconnection,['java'] +564548,why do i get an infinite loop if i enter a letter rather than a number i am writing this code for a homework assignment just starting c so please go easy weve just started while dowhile and for loops today the program runs fine except that if you enter a letter when the program asks for an integer it loops infinitely what is going on code belowedit to clarify the part that is looping is the number you have entered is negative please enter a positive number to continue but the user is not given a chance to enter another number it just keeps printing this include iostreamusing namespace stdint main define variables int num1 num2 total char answer1 do user enters a number cout nplease enter a positive number and press enter n cin num1 check that the given num1 value is positive while num1 0 cout the number you entered is negativenplease enter a positive number to continuen cin num1 cout endl add the sum of 1 through num1 value num2 1 total 0 while num1 num2 total total num2 num2 tell the user the sum cout the total of all the integersnfrom 1 to num1 is n cout total ask if the user wants to try again cout nnwould you like to try again with a new numbernenter y for yes or and for non cin answer1 while answer1 y cout endl return 0,['c++'] +564571,running gradle on ubuntu 1310 i am having a problem running gradle on ubuntu 1310 which i am assuming is the root of the issuei installed gradle using the below commandsudo aptget install gradlei am getting an error when running the command gradle versiongradle versionusrlibjvmdefaultjavabinjava symbol lookup error usrlibjnilibnativeplatformcursesso undefined symbol tgetenti am using java versionjava version 170 25openjdk runtime environment icedtea 2312 7u2523124ubuntu3openjdk 64bit server vm build 237b01 mixed modei am not sure what else to do i tried different versions of java but to no avail,['java'] +564588,textarea label verticalalign middle i am trying to align the label for this text area in the middle of the text box but it just is not working the output looks something like this x x x synopsis xheres the code i have been trying tystylelabel textarea verticalalign middlestylelabelsynopsis textarea styleborder none rows7 cols60v synopsistextarealabel,"['html', 'css']" +564592,is there anyway to define an undefined object in visual studio intellisense lets say i have a controller in angularjsmyappcontrollersearchcontroller function scope userservice for intellisense userservice is undefined here var user userservicegetusersthenfunctiondata yada yada functionerr yada yada however in my intellisense file i can dynamically inject userservice to get its functions like thisintellisenseaddeventlistenerstatementcompletion function event tried doing this but does not work eventtarget var injector angularinjectorng myapp var dependency injectorgeteventtargetname eventitems for method in dependency intellisenselogmessagemethod eventitemspush name method kind field value function now if i have a global variable or function variable defined as userservice and inside my controller function i type userservice i will get a pop up of all the functions in the service but if i do not have it defined since it is interpreted as undefined by intellisense it cannot show me the options even though statementcompletion is working as seen in the javascript language service console my question is apart from annotating the function is there anyway to define userservice as an object in the intellisense file defining eventtarget does not work see intellisense code above,['javascript'] +564593,python catch exception and continue try block can i return to executing tryblock after exception occurs the goal is to write lessfor exampletry do smth1except passtry do smth2except passvstry do smth1 do smth2except magic word to proceed to do smth2 if there was exception in do smth1,['python'] +564601,good way to collect programmatically generated test suites in nose or pytest say i have got a test suite like thisclass safetestsunittesttestcase snip 20 test functionsclass bombtestsunittesttestcase snip 10 different test casesi am currently doing the followingsuite unittesttestsuiteloader unittesttestloadersafetests loaderloadtestsfromtestcasesafetestssuiteaddtestssafetestsif target prod unsafetests loaderloadtestsfromtestcasebombtests suiteaddtestsunsafetestsunittesttexttestrunnerrunsuitei have major problem and one interesting pointi would like to be using nose or pytest doestnt really matter whichi have a large number of different applications that are exposing these testsuites via entry pointsi would like to be able to aggregate these custom tests across all installedapplications so i cannot just use a clever naming convention i do notparticularly care about these being exposed through entry points but ido care about being able to run tests across applications insitepackages without just importing every modulei do not care about maintaining the current dependency onunittesttestcase trashing that dependency is practically a goaledit this is to confirm that oleksiys point about passing args tonoserun does in fact work with some caveatsthings that do not workpassing all the files that one wants to execute which weirdpassing all the modules that one wants to execute this either executesnothing the wrong thing or too many things interesting case of 0 1 ormany perhapspassing in the modules before the directories the directories have to comefirst or else you will get duplicate teststhis fragility is absurd if youve got ideas for improving it i welcomecomments or i set upa github repo with myexperiments trying to get this to workall that aside the following works including picking up multiple projectsinstalled into sitepackagespythonimport importlib os sysimport nosedef runtests modnames dirs set for modname in sysargv1 modnamesappendmodname mod importlibimport modulemodname fname mod file dirsaddospathdirnamefname modnames listdirs modnames noserunargvmodnamesif name main runtestswhich if saved into a runtestspy file does the right thing when run asruntestspy projecttests otherprojecttests,['python'] +564617,is boto library threadsafe specifically i am interested in using a dynamodb table object from multiple threads puts gets updates etc if that is not safe then is there a safe way ie maybe one table object per thread any other gotchas or tips about working with threads in boto appreciated,['python'] +564631,no matching function call in constructor this is the constructor declaration that i have in my solverh filesolverconst board board c int max moves cwhen trying to compile i get the following errorsolvercpp in constructor solversolverconst board intsolvercpp655 error no matching function for call to boardboard solversolverconst board board c int max moves cand then it lists the candidates which are the board constructorsi am not sure what i am doing wrong as i see no reason why i should be getting this errori am compiling with g,['c++'] +564638,xsd generate a map properties i am trying to generate java class from xsd file which contains mapstring boolean i have read tutorial which says that i have to use adapter and binding in order to achieve desired result but for some reason after generation property is a list instead of the map could you please help me to figure out my mistakethanksmy xsd schemaxselement nameautocompletereq xscomplextype xssequence xselement namequerystring typexsstring xselement nameboostingfactors typeteststringbooleanmapmodeller minoccurs0 xssequence xscomplextypexselementxscomplextype namestringbooleanmapmodeller xssequence xselement nameentry minoccurs0 maxoccursunbounded xscomplextype xssequence xselement namekey typexsstring xselement namevalue typexsboolean xssequence xscomplextype xselement xssequencexscomplextypemy binding filejaxbbindings schemalocationautocompletereqxsd jaxbbindings nodexselementnameautocompletereqxselementnameboostingfactors jaxbproperty jaxbbasetype namecomthehutgroupsupportjaxbstringbooleanmapltstringbooleangt jaxbproperty jaxbbindingsjaxbbindingsjaxbbindingsstringbooleanmapjavapackage comthehutgroupsupportjaxbimport javautilhashmapimport javaxxmlbindannotationadaptersxmljavatypeadapterxmljavatypeadapterstringbooleanmapadapterclasspublic class stringbooleanmapstring boolean extends hashmapstring boolean stringbooleanmapadapterjavapackage comthehutgroupsupportjaxbimport javautilhashmapimport javautilmapimport javaxxmlbindannotationadaptersxmladapterimport comthehutgroupxmlrepresentationstringbooleanmapmodellerpublic class stringbooleanmapadapter extends xmladapterstringbooleanmapmodeller hashmapstring boolean override public hashmapstring boolean unmarshalstringbooleanmapmodeller v throws exception hashmapstring boolean map new hashmapstring boolean forstringbooleanmapmodellerentry e vgetentry mapputegetkey eisvalue return map override public stringbooleanmapmodeller marshalhashmapstring boolean v throws exception stringbooleanmapmodeller modeller new stringbooleanmapmodeller formapentrystring boolean entry ventryset stringbooleanmapmodellerentry e new stringbooleanmapmodellerentry esetkeyentrygetkey esetvalueentrygetvalue modellergetentryadde return modeller pomxml piece for xsd generationplugin groupidorgcodehausmojogroupid artifactidjaxb2mavenpluginartifactid version13version executions execution idrepresentationsid configuration schemadirectoryxsdrepresentationschemadirectory packagenamecomthehutgroupxmlrepresentationpackagename bindingdirectoryxsdrepresentationbindingdirectory outputdirectorysrcmaingeneratedsourcesoutputdirectory stalefileprojectbuilddirectorygeneratedsourcesjaxbrepresentationstalefile clearoutputdirfalseclearoutputdir configuration goals goalxjcgoal goals execution execution ideventsid configuration schemadirectoryxsdrepresentationeventschemadirectory packagenamecomthehutgroupxmlrepresentationeventpackagename bindingdirectoryxsdrepresentationeventbindingdirectory outputdirectorysrcmaingeneratedsourcesoutputdirectory stalefileprojectbuilddirectorygeneratedsourcesjaxbeventstalefile clearoutputdirfalseclearoutputdir configuration goals goalxjcgoal goals execution executions plugin,['java'] +564674,how to conditionally buffer racsignal values i am working on some code that interacts with a remote api via websockets my data layer is responsible for establishing and monitoring the websocket connection it also contains methods that can be used by the application to enqueue websocket messages to be sent the application code should not be responsible for inspecting the state of the websocket connection aka fireandforgetideally i would like to data layer to function as followswhen the data layer does not have a connection to the websocket endpoint selfisconnected no messages are buffered internallywhen a connection is becomes available selfisconnected yes buffered messages are immediately sent and any subsequent messages are sent immediatelyheres what i have been able to come up withimport racsignalbufferinghimplementation racsignal buffering racsignalbufferwithsignalracsignalshouldbuffer return racsignal createsignalracthisposable idracsubscriber subscriber raccompoundthisposable thisposable raccompoundthisposable compoundthisposable nsmutablearray bufferedvalues nsmutablearray alloc init block bool buffering no void bufferhandler if buffering for id val in bufferedvalues subscriber sendnextval bufferedvalues removeallobjects racthisposable bufferthisposable shouldbuffer subscribenextnsnumber shouldbuffer buffering shouldbufferboolvalue bufferhandler if bufferthisposable thisposable addthisposablebufferthisposable racthisposable valuethisposable self subscribenextid x bufferedvalues addobjectx bufferhandler errornserror error subscriber senderrorerror completed subscriber sendcompleted if valuethisposable thisposable addthisposablevaluethisposable return thisposable endlastly this is pseudocode for how it would be usedinterface apimanager property nonatomic racsubject requestsendimplementation websocketdatalayer idinit self super init if self racsignal connectedsignal racobserveself connected selfrequests racsubject alloc init racsignal bufferedapirequests selfrequests bufferwithsignalconnectedsignal self rac liftselectorselectorsendrequest withsignalsfromarraybufferedapirequests return self voidenqueuerequestnsstringrequest selfrequests sendnextrequest voidsendrequestnsstringrequest debuglogmaking websocket request requestendmy question is is this the right approach for buffering values is there a more idiomatic rac way of handling this,"['ios', 'objective-c']" +564681,difference between role and grantedauthority in spring security there are concepts and implementations in spring security such as the grantedauthority interface to get an authority to authorizecontrol an access i would like that to permissible operations such as createsubusers or deleteaccounts which i would allow to an admin with role role admin i am getting confused as the tutorialsdemos i see online i try to connect what i read but i think we treat the two interchangeablyi see hasrole consuming a grantedauthority string i most definitely am doing it wrong in understanding what are these conceptually in spring security how do i store the role of a user separate from the authorities for that rolei am also looking at the orgspringframeworksecuritycoreuserdetailsuserdetails interface which is used in the authenticationprovider referenced dao which consumes a user note last grantedauthoritypublic userstring username string password boolean enabled boolean accountnonexpired boolean credentialsnonexpired boolean accountnonlocked collection extends grantedauthority authoritiesor is there any other way to differentiate the other two or is it not supported and we have to make our own,['java'] +564707,does argument unpacking use iteration or itemgetting i am using python 273consider a dummy class with custom albeit bad iteration and itemgetting behaviorclass foolistlist def iter self return iterself def nextself return 3 def getitem self idx return 3make an example and see the weird behavior zz foolist123 x for x in zz hangs because of the selfreference in iter zz03 zz13but now let us make a function and then do argument unpacking on zzdef add3a b c return a b c add3zz6 i expected either 9 or for the interpreter to hang like the comprehensionso argument unpacking is somehow getting the item data from zz but not by either iterating over the object with its implemented iterator and also not by doing a poor mans iterator and calling getitem for as many items as the object hasso the question is how does the syntax add3zz acquire the data members of zz if not by these methods am i just missing one other common pattern for getting data members from a type like thismy goal is to see if i could write a class that implements iteration or itemgetting in such a way that it changes what the argument unpacking syntax means for that class after trying the two example above i am now wondering how argument unpacking gets at the underlying data and whether the programmer can influence that behavior google for this only gave back a sea of results explaining the basic usage of the args syntaxi do not have a use case for needing to do this and i am not claiming it is a good idea i just want to see how to do it for the sake of curiosityaddedsince the builtin types are treated specially heres an example with object where i just maintain a list object and implement my own get and set behavior to emulate listclass foolistobject def init self lst selflst lst def iter self raise valueerror def nextself return 3 def getitem self idx return selflst getitem idx def setitem self idx itm selflst setitem idx itmin this case in 234 zz foolist123in 235 x for x in zzvalueerror traceback most recent call lastipythoninput235ad3bb7659c84 in module 1 x for x in zzipythoninput233dc9284300db1 in iter self 2 def init self lst 3 selflst lst 4 def iter self raise valueerror 5 def nextself return 3 6 def getitem self idx return selflst getitem idxvalueerrorin 236 add 3zzvalueerror traceback most recent call lastipythoninput236f9bbfdc2de5c in module 1 add 3zzipythoninput233dc9284300db1 in iter self 2 def init self lst 3 selflst lst 4 def iter self raise valueerror 5 def nextself return 3 6 def getitem self idx return selflst getitem idxvalueerrorbut instead if i ensure iteration stops and always returns 3 i can get what i was shooting to play around with in the first caseclass foolistobject def init self lst selflst lst selfiter loc 1 def iter self return self def nextself if selfiter loc lenselflst1 selfiter loc 1 return 3 else selfiter loc 1 raise stopiteration def getitem self idx return selflst getitem idx def setitem self idx itm selflst setitem idx itmthen i see this which is what i originally expectedin 247 zz foolist123in 248 ix iterzzin 249 ixnextout249 3in 250 ixnextout250 3in 251 ixnextout251 3in 252 ixnextstopiteration traceback most recent call lastipythoninput25229d4ae900c28 in module 1 ixnextipythoninput2465479fdc9217b in nextself 10 else 11 selfiter loc 1 12 raise stopiteration 13 def getitem self idx return selflst getitem idx 14 def setitem self idx itm selflst setitem idx itmstopiterationin 253 ix iterzzin 254 ixnextout254 3in 255 ixnextout255 3in 256 ixnextout256 3in 257 ixnextstopiteration traceback most recent call lastipythoninput25729d4ae900c28 in module 1 ixnextipythoninput2465479fdc9217b in nextself 10 else 11 selfiter loc 1 12 raise stopiteration 13 def getitem self idx return selflst getitem idx 14 def setitem self idx itm selflst setitem idx itmstopiterationin 258 add 3zzout258 9in 259 zz0out259 1in 260 zz1out260 2in 261 zz2out261 3in 262 x for x in zzout262 3 3 3summarythe syntax args relies on iteration only for builtin types this happens in a way that is not directly overrideable in classes that inherit from the builtin typethese two are functionally equivalentfoox for x in argsfooargsthese are not equivalent even for finite data structuresfooargsfooargsi for i in rangelenargs,['python'] +564708,weakref and slots consider the following codefrom weakref import refclass klassobject slots foo def init self selffoo bark klassr refkit works but when i uncomment the slots it breaks with typeerror cannot create weak reference to klass object under python 26please does anyone know if this is an inherent limitation of python and slots or if it is a bug how to workaround it,['python'] +564720,defining a function inside a function in c i want to create a general function which returns a function pointer to another function in cc however second returned function should be able to use variable from first functionexampletypedef double func tdoublefunc t inversefunc t fn define another function here that uses fn double solvedouble x use fn return solvedouble sqrdouble x return x x int main func t inv inversesqr printfsqrt d fn 100 inv100 obviously gcc g do not allow me to do this can i achieve this without using classes or structs,"['c++', 'c']" +564741,failed to open stream no suitable wrapper could be found hello i am implementing php files from one website into another and here is the following error message i am getting when trying to open the following page with implemented php filesbasically the php files i am importing from one website into another are identical however they work on the original website but when i implement them into a new website it does not work anymorecould you assist me in trying to get this resolvedthank you,['php'] +564746,limit the maximum running time for unit test i am currently running some unit tests that might either take a long time before failing or run indefinitely in a successful test run they will always complete within a certain amount of time is it possible to create a pytest unit test that will fail if it does not complete within a certain amount of time,['python'] +564749,what languages compile to the most efficient javascript code besides c c there are lots of languages that compile to javascript these days with c c compiled to asmjs being touted as the fastest i was wondering what other candidates exist for efficient compiled javascriptasmjs i would to find a nice language that strikes a balance between performance and having modern higherlevel programming constructs everyone seems to love python these days but from what i have read it does not make for the fastest compiled jsbased on some initial perusing of the topic i am getting the idea that dart haxe c and java may be good candidates but i have not been able to find any performance comparisons,['javascript'] +564811,activeadmin throws error when posting comment to a nested resource using the awesome activeadmin gem i have run into an issue with commentsactiveadminregister sale do belongs to channel show do sale stuff to show sale resource allow comments on sales active admin comments endendif i post a comment to a sale with the above setup the comment posts but then crashes on the redirect withundefined method admin sale path for admincommentscontroller0x007ffed79bb210the correct routing method would be admin channel sale pathsalechannel sale but it does not seem to be able to figure that out and i am not sure where to patch this upis there is a place in my sale resource where i can override the routing method used to prevent this error,"['ruby-on-rails', 'ruby']" +564851,sdl2 check if opengl context is created i am creating an application using sdl2 opengl and it worked fine on 3 different computers but on another computer an updated arch linux it does not and it crashes with this erroropengl context already createdso my question is how do i check if the opengl context has already been created and then if it is already created how do i get a handle for itif i cannot do this how do i bypass this issue,['c++'] +564853,getting a thumbnail of a mov video ios i want to get a thumbnail of videos mov which taken with iphoneipad i am trying to use avfoundation library for this and getting this errorcould not generate thumbnail errorerror domainavfoundationerrordomain code11822 cannot open userinfo0x15d90a30 nslocalizeddescriptioncannot open nslocalizedfailurereasonthis media format is not supportedcodensarray pathsnssearchpathfordirectoriesindomainsnsdocumentdirectory nsuserdomainmask yesnsstring documentdirpaths objectatindex0nsstring videopathdocumentdir stringbyappendingpathcomponentnsstring stringwithformatvideosmovvideoname avurlasset assetavurlasset alloc initwithurlvideopath optionsnil avassetimagegenerator generator avassetimagegenerator alloc initwithassetasset generatorappliespreferredtracktransformtrue cmtime thumbtime cmtimemakewithseconds030 avassetimagegeneratorcompletionhandler handler cmtime requestedtime cgimageref im cmtime actualtime avassetimagegeneratorresult result nserror error if result avassetimagegeneratorsucceeded nslogcould not generate thumbnail error error selfimgimageuiimage imagewithcgimageim cgsize maxsize cgsizemake320 180 generatormaximumsize maxsize generator generatecgimagesasynchronouslyfortimesnsarray arraywithobjectnsvalue valuewithcmtimethumbtime completionhandlerhandleri recorded videos with my app and want to show a thumbnail of them,"['ios', 'iphone']" +564964,in app billing not working after update google store i have implemented inapp billing in my app and very recently google has updated itpreviously i was testing the inapp billing with androidtestpurchased and it was working fine buy full version and restore full versionnow i took the changed classes from here after that i am not able to test the app it gives the following error in the logcat iabhelper inapp billing error purchase signature verification failed for sku androidtestpurchasedi have checked with my key package name and also app version all is proper has any one faced this issueplease help me with this,['android'] +564991,get value of hidden field in client side on a button click on my server side i assign value to the hidden field from a column in my tabledim dsgetenquirydetails dblusp getenquiryregisterdetailsvallblenquiryregisteridtextasqueryablefor each record in dsgetenquirydetails hiddenstatusflagvalue recordstatusflagnextin my client side function i use this but not getting any valuevar statusflag statusflag documentgetelementbyid hiddenstatusflagclientidwhat am i missing,['asp.net'] +565003,how to create static strings from types at compile time i have a bunch of types that have a name they have more features but for the sake of this thiscussion only the name is relevant these types and their names are setup at compiletime using a macro define define foofoo struct foo public foo basefoo static char const name return foo the types are then combined in compiletime lists classic simple recursive compiletime lists from which i need to create the lists name by concatenating the names of its objects templateclass foo class tail nilstruct foo list static stdstring name list return fooname tailnametemplateclass foostruct foo listfoonil static stdstring name list return foonamethe code is boiled down here to the point where it might contain errors but in practice this works pretty well except that it creates and then copies around rather long strings at runtime which represent types that actually are wellknown at compiletime since this is a rather performancesensitive piece of code that runs on embedded devices i would like to change this so that the lists string is ideally created at compiletime or if there is no way to do that once at runtime and i only need to copy around a pointer to a c string since according to 1 the strings are fixed in memory this compiles with c03 which were stuck with right now how can i do this in case this enlarges the arsenal of dirty tricks employable for this the names of the foo objects are only ever created and read by code and only the foo list name strings are expected to be humanreadable,['c++'] +565019,how to get the original attached view in gesture recognizer in iphone by the following code i attatched a button in a gesture recognizeruilongpressgesturerecognizer longpressuilongpressgesturerecognizer allocinitwithtargetself actionselectoraddlongpressgesturelongpress setdelegateselfbutton addgesturerecognizerlongpresshere is my addlongpressgesture method voidaddlongpressgestureuilongpressgesturerecognizer sender uiview view senderviewcgpoint point sender locationinviewviewsuperviewif senderstate uigesturerecognizerstatebegan gesture state beganby this code senderview i am getting the attached view as uiview but i want the view as it was attached uibutton how do i get the uiview as uibutton,"['ios', 'iphone']" +565059,recommended way to enable touch events in bootstrap 3 now that bootstrap 3 is out what is the recommended option for enabling touch as before there are not many touch events in the bootstrapjs though it is supposed to be a mobile first frameworkthe last thing i have found on github suggests using fastclickjs but that was before the v30 release,['javascript'] +565065,jshint overwrite single jshintrc option for whole folder i have a jshintrc at the root of my project with the following configuration node true smarttabs true undef true unused truethis is fine for all the node related stuff i have in the project but not for the browser related scripts which are sitting in a subfolderis it possible overwrite just the node option while preserving the other options for a whole folder if i create another jshintrc file for the browser side folder i have to tell jshint again about all my configurations although i actually just want to unset the node optioni know that i can set this option in every file but i actually would like to avoid thatmany thanks in advance,['javascript'] +565068,issue with android ndk and cygwin i am working on an application in which i need to implement ndki go through the link i followed the steps mentioned their but after installing cygwin when i use make v command as mentioned in the steps i got the error bash make command not found i searched a lot but did not get any thing,['android'] +565069,android out of memory error stringbuilder in my app i fetching data from the server in the form of json the data is around 15 mb the app works but sometimes it crashes while fetching data from server giving outofmemoryerror this is my methodprivate string sendpostrequeststring url listnamevaluepair params throws exception string ret null bufferedreader bufferedreader null httpclient httpclient new defaulthttpclient httppost request new httpposturl try urlencodedformentity entity new urlencodedformentityparams requestsetentityentity httpresponse response httpclientexecuterequest bufferedreader new bufferedreadernew inputstreamreaderresponse getentitygetcontent stringbuilder stringbuilder new stringbuilder stringbuilder stringbuilder2 string line string lineseparator systemgetpropertylineseparator while line bufferedreaderreadline null stringbuilderappendline bufferedreaderclose ret stringbuildertostring stringbuilder null catch clientprotocolexception e eprintstacktrace todo report an error catch ioexception e eprintstacktrace todo report an error finally if bufferedreader null try bufferedreaderclose catch ioexception e eprintstacktrace todo autogenerated catch block return reti tried setting the stringbuilder to null after use but did not helpedi am posting the logcat traces below1023 033925271 edalvikvmheap1011 out of memory on a 4116282byte allocation1023 033925271 idalvikvm1011 asynctask 1 prio5 tid11 runnable1023 033925271 idalvikvm1011 groupmain scount0 dscount0 obj0x417c5e88 self0x2a1d1db81023 033925271 idalvikvm1011 systid1025 nice10 sched00 cgrpappsbg non interactive handle7065523281023 033925271 idalvikvm1011 stater schedstat 3053328788 23773807212 6541 utm241 stm64 core01023 033925271 idalvikvm1011 at javalangstringinitstringjava4221023 033925271 idalvikvm1011 at javalangabstractstringbuildertostringabstractstringbuilderjava6421023 033925282 idalvikvm1011 at javalangstringbuildertostringstringbuilderjava6631023 033925282 idalvikvm1011 at comdzothispatchcrudedriverappdatalayerserverconnectsendpostrequestserverconnectjava1281023 033925282 idalvikvm1011 at comdzothispatchcrudedriverappdatalayerserverconnectsyncserverconnectjava611023 033925282 idalvikvm1011 at comdzothispatchcrudedriverappdatalayerdbsynclogindbsyncjava591023 033925282 idalvikvm1011 at comdzothispatchcrudedriverappasynctasksyncdbtaskdoinbackgroundsyncdbtaskjava521023 033925282 idalvikvm1011 at comdzothispatchcrudedriverappasynctasksyncdbtaskdoinbackgroundsyncdbtaskjava11023 033925282 idalvikvm1011 at androidosasynctask2callasynctaskjava2871023 033925282 idalvikvm1011 at javautilconcurrentfuturetaskrunfuturetaskjava2341023 033925282 idalvikvm1011 at androidosasynctaskserialexecutor1runasynctaskjava2301023 033925282 idalvikvm1011 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava10801023 033925282 idalvikvm1011 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava5731023 033925282 idalvikvm1011 at javalangthreadrunthreadjava8411023 033925282 wdalvikvm1011 threadid11 thread exiting with uncaught exception group0x414657001023 033925292 ichoreographer1011 skipped 30 frames the application may be doing too much work on its main thread1023 033925491 eandroidruntime1011 fatal exception asynctask 11023 033925491 eandroidruntime1011 javalangruntimeexception an error occured while executing doinbackground1023 033925491 eandroidruntime1011 at androidosasynctask3doneasynctaskjava299 1023 033925491 eandroidruntime1011 at javautilconcurrentfuturetaskfinishcompletionfuturetaskjava3521023 033925491 eandroidruntime1011 at javautilconcurrentfuturetasksetexceptionfuturetaskjava2191023 033925491 eandroidruntime1011 at javautilconcurrentfuturetaskrunfuturetaskjava2391023 033925491 eandroidruntime1011 at androidosasynctaskserialexecutor1runasynctaskjava2301023 033925491 eandroidruntime1011 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava10801023 033925491 eandroidruntime1011 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava5731023 033925491 eandroidruntime1011 at javalangthreadrunthreadjava8411023 033925491 eandroidruntime1011 caused by javalangoutofmemoryerror1023 033925491 eandroidruntime1011 at javalangstringinitstringjava4221023 033925491 eandroidruntime1011 at javalangabstractstringbuildertostringabstractstringbuilderjava6421023 033925491 eandroidruntime1011 at javalangstringbuildertostringstringbuilderjava6631023 033925491 eandroidruntime1011 at comdzothispatchcrudedriverappdatalayerserverconnectsendpostrequestserverconnectjava1281023 033925491 eandroidruntime1011 at comdzothispatchcrudedriverappdatalayerserverconnectsyncserverconnectjava611023 033925491 eandroidruntime1011 at comdzothispatchcrudedriverappdatalayerdbsynclogindbsyncjava591023 033925491 eandroidruntime1011 at comdzothispatchcrudedriverappasynctasksyncdbtaskdoinbackgroundsyncdbtaskjava521023 033925491 eandroidruntime1011 at comdzothispatchcrudedriverappasynctasksyncdbtaskdoinbackgroundsyncdbtaskjava11023 033925491 eandroidruntime1011 at androidosasynctask2callasynctaskjava2871023 033925491 eandroidruntime1011 at javautilconcurrentfuturetaskrunfuturetaskjava2341023 033925491 eandroidruntime1011 4 more1023 033928091 ewindowmanager1011 activity comdzothispatchcrudedriverapploginactivity has leaked window comandroidinternalpolicyimplphonewindowdecorview4178fcb0 ve rid 0047996 that was originally added here1023 033928091 ewindowmanager1011 androidviewwindowleaked activity comdzothispatchcrudedriverapploginactivity has leaked window comandroidinternalpolicyimplphonewindowdecorview4178fcb0 ve rid 0047996 that was originally added here1023 033928091 ewindowmanager1011 at androidviewviewrootimplinitviewrootimpljava3451023 033928091 ewindowmanager1011 at androidviewwindowmanagerglobaladdviewwindowmanagerglobaljava2391023 033928091 ewindowmanager1011 at androidviewwindowmanagerimpladdviewwindowmanagerimpljava691023 033928091 ewindowmanager1011 at androidappdialogshowdialogjava2811023 033928091 ewindowmanager1011 at comdzothispatchcrudedriverappasynctasksyncdbtaskonpreexecutesyncdbtaskjava431023 033928091 ewindowmanager1011 at androidosasynctaskexecuteonexecutorasynctaskjava5861023 033928091 ewindowmanager1011 at androidosasynctaskexecuteasynctaskjava5341023 033928091 ewindowmanager1011 at comdzothispatchcrudedriverappasynctaskloginasynctaskonpostexecuteloginasynctaskjava871023 033928091 ewindowmanager1011 at comdzothispatchcrudedriverappasynctaskloginasynctaskonpostexecuteloginasynctaskjava11023 033928091 ewindowmanager1011 at androidosasynctaskfinishasynctaskjava6311023 033928091 ewindowmanager1011 at androidosasynctaskaccess600asynctaskjava1771023 033928091 ewindowmanager1011 at androidosasynctaskinternalhandlerhandlemessageasynctaskjava6441023 033928091 ewindowmanager1011 at androidoshandlerthispatchmessagehandlerjava991023 033928091 ewindowmanager1011 at androidoslooperlooplooperjava1371023 033928091 ewindowmanager1011 at androidappactivitythreadmainactivitythreadjava51031023 033928091 ewindowmanager1011 at javalangreflectmethodinvokenativenative method1023 033928091 ewindowmanager1011 at javalangreflectmethodinvokemethodjava5251023 033928091 ewindowmanager1011 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava7371023 033928091 ewindowmanager1011 at comandroidinternaloszygoteinitmainzygoteinitjava5531023 033928091 ewindowmanager1011 at dalviksystemnativestartmainnative method1023 034425761 iprocess1011 sending signal pid 1011 sig 9update 1i tried with this approach again it gave error with tostringin my case also it is giving error with tostring the same happened while i tried with amit is answer is there anything with tostringupdate 2removed creation of new string builder object from while loop and now i am not using line separator but it did not made much difference the app runs for first time but if i try to run continuously for 23 times the same problem occurs again,['android'] +565144,javaxwsrsclientclient how to configure readtimeout going from comsunjerseyapiclientclient to javaxwsrsclientclient how do i configure clientfromimport comsunjerseyapiclientclientclient client clientcreateclientsetreadtimeout10 60 20clientsetconnecttimeout10 20webresource clientresourcesomewhereovertherainbowetctoimport javaxwsrsclientclient client clientbuildernewclient now what clientgetconfigurationgetpropertiesputisthisthewaytodoit 10 60 2webtarget target clienttargetsomewhereovertherainbowetci am using javaxwsrsapi20jar,['java'] +565155,center content in scroll view i want to center my linearlayout within scrollview when linearlayouts height is small it is centered alright see image 1 but when linearlayouts height is bigger than the screens height then it behaves strange i cannot see the top of linearlayout see image 2 and at the bottom of scrollview there is huge padding i do not know whats happening here when there are lots of content in linearlayout the whole screen should look like in image 3 image 1image 2image 3heres my layout file xml version10 encodingutf8 scrollview xmlnsandroid androidlayout widthmatch parent androidlayout heightmatch parent androidbackgroundcf linearlayout androidlayout widthmatch parent androidlayout heightwrap content androidlayout gravitycenter vertical androidlayout margin28dp androidbackgroundf androidorientationvertical androidpaddingbottom40dp androidpaddingleft20dp androidpaddingright20dp androidpaddingtop40dp imageview androidlayout widthwrap content androidlayout heightwrap content androidlayout marginbottom16dp androidsrcdrawableic launcher textview androidididtip title androidlayout widthwrap content androidlayout heightwrap content androidlayout marginbottom12dp androidtexttitle androidtextcolorcolororange text androidtextsizedimenfont size medium textview androidididtip description androidlayout widthwrap content androidlayout heightwrap content androidtextdescription description androidtextsizedimenfont size small linearlayout scrollview,['android'] +565183,mutationobserver does not react to changes to text input fields i am working on adapting an iespecific website to other browsers for example onpropertychange has been used extensively and i am using mutationobserver to emulate that behaviorhowever i cannot get mutationobserver to react on value changes to inputtext fields neither on programmatic changes nor user inputconsiderinput typetext nametest1 idtest1 and var config attributes true childlist true characterdata true subtree true var observer new mutationobserverfunction alertsuccess observerobservedocumentgetelementbyidtest1 configif i try to change the value by documentgetelementbyidtest1value something or keyboard input nothing happenshowever if i try to change something else about the element for example its id or name by javascript the mutationobserver firesvalue changes and mutationobserver work fine with other input types event with the value of hidden fieldsthis behavior is consistent across browsersdoes anybody know how i can observe value changes on text fields or do i have to approach this differently,['javascript'] +565201,catch moment when spring initialized all beans i have spring applicationi have not lazy beansi want to insert logic to place when all componentrepositoey service controller beans are initializedhow can i make it,['java'] +565239,how would you forget cached eloquent models in laravel theoretical question on laravel hereso example of the caching i would do isarticlewithcommentsremember5getideally i would like to have an event for article updates that when the id of a instance of that model that is already cached is updated i want to forget that key even if it is the whole result of the query that is forgotten instead of just that one model instance it is possible to do soif not is there some way to implement this reasonably cleanly,['php'] +565246,xcode 501 ios 703 simulator not launching i just upgraded to xcode 501 on osx mavericks and upgraded xcode to 501 when i try to launch an app on ios 703 simulator the simulator would not launch the app will launch on ios 61 simulator but the ios 703 simulator just gets stuck on a black screenanyone else have this issue i have tried reinstalling xcode as well and still get the same problem,"['ios', 'iphone']" +565252,zipalign verification in android zipalign is used to align resources on 4 bytes boundaries to speedup resources loadingthe resourcehandling code in android can efficiently access resources when they are aligned on 4byte boundaries by memorymapping them but for resources that are not aligned ie when zipalign has not been run on an apk it has to fall back to explicitly reading themawhich is slower and consumes additional memoryafter running the tool it is possible to validate the alignment using the commandzipalign c v 4 applicationapkthis produces a report and tells if there are errors or not in my case this reports indicates no alignment error but the first number which i assume it the position of the resources in the final apk seems to show that some resources are not aligned on 4 bytes boundarieshere is a the beginning of this report verifying alignment of appsignedalignedapk 4 50 metainfmanifestmf ok compressed 24245 metainfkeyssf ok compressed 49830 metainfkeysdsa ok compressed 50683 androidmanifestxml ok compressed 53096 assetsassetsdb normaldb ok 595425 assetsassetscommondmstructuresxml ok compressedwhat did i miss is the first number the position of the resource for example structuresxml seems to be at 595425 which is not a multiple of 4 bytes,['android'] +565271,can i use bower and rails on heroku and still keep the bower components directory out of git i have just started working with bower for managing clientside dependencies i have set bower up to install all files into vendorassetscomponents i then run bower install to evaluate the bowerjson file and install all dependenciesbowerjson name myapp dependencies angular 108 bootstrap 300 finally as instructed by the tutorials i have read i have removed the components directory from gitgitignore ignore all stuff manged by bowervendorassetscomponentsthe project does not therefore include any of these assets in the slug and requires bower install to be run in order to install them this seems sensible to me in the same way that decoupling actual gems from a project is sensible it also abides by the principles of the 12factor app and explicitly declares and isolate dependencieshowever excluding dependencies causes asset compilation to chokehowever when i push to heroku asset precompilation fails because the asets have not been added yet and so when sprockets tries to evaluateapplicationcscss require bootstrapthistcssbootstrap require self require tree it finds that there is nothing to be found in bootstrapthistcssbootstrap because bower has not installed anything yeta possible solution use packagejson to run a postinstall scripti have followed this tutorial which suggests adding a packagejson file with the following contentsdependencies bower 06xscripts postinstall node modulesbowerbinbower installhowever bower install needs to be run not as a postinstall script but a postpush preassetcompilation script it is also not clear to me whether heroku will run an npm preprocessor for a rails appis it better to figure out how to run bower install or just include files in gitthere are two solutions to this the first and simplest is to simply run bower install locally and include the files in git this is no biggie but i would like to stick to the principles of the 12 factor app the second solution is to figure out how to fire up npm and run bower install on heroku before asset precompilation occurs is this viable in any simple way or is it better to simply compile bower assets locallypostscriptmy conclusion in the end was simply to run bower install locally and to include the files in git although the 12factor principles suggest that this may not be the correct route i have not found it to have any cost to it in practice and preferred that rather than getting into the compounding complexities of a custom buildpack,['ruby-on-rails'] +565309,android how to hide actionbar on certain activities i have developed a simple demo application with a splash screen a map and some regular screensi have an action bar at the top that contains a logo it all looks fine on my phone galaxy s1 i90 v23 but when i test it on galaxy s2 v4 the action bar appears also in the splash screen and in the map screenthe spalsh and map activity are not even inheriting from actionbaractivity so how is that possible and how can i make it go awaymanifestapplication androidallowbackuptrue androidicondrawableic launcher androidthemestylethemeappcompatlight activity androidnamehomeactivity androidicondrawableandroid logo androidlabel androidlogodrawableandroid logo intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity activity androidnamemapactivity androidlabel activity activity androidnamepackageactivity androidicondrawableandroid logo androidlabel androidlogodrawableandroid logo activity activity androidnamesplashactivity androidlabel intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity applicationmapactivity definition it is a long one so i included just the definitionpublic class mapactivity extends fragmentactivity implements locationlistenersplash activityimport androidappactivityimport androidcontentintentimport androidosbundleimport androidoshandlerimport androidsupportv7appactionbarimport androidsupportv7appactionbaractivitypublic class splashactivity extends activity private static final long splash thisplay length 20 override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity splash new handlerpostdelayednew runnable override public void run intent mainintent new intentsplashactivitythishomeactivityclass splashactivitythisstartactivitymainintent splashactivitythisfinish splash thisplay length,"['java', 'android']" +565319,androidmanifestxml for gradle instrumenttest is there a way to specify an additional androidmanifestxml file for a gradle test aplication i need it to specify additional permissions and activities for my unit testsupdi have tried to add instrumnettest section in the buildgradle file but it did not help and i still get unable to resolve activity for intent errorsourcesets main manifestsrcfile androidmanifestxml javasrcdirs src resourcessrcdirs src aidlsrcdirs src renderscriptsrcdirs src ressrcdirs res assetssrcdirs assets instrumenttest manifestsrcfile srcinstrumenttestandroidmanifestxml javasrcdir srcinstrumenttestjava,"['java', 'android']" +565352,error when installing libv8 31183 i am running fresh install of osx 109 mavericks and xcode 501 when i am trying to run bundle install in my project it fails on installing libv8 gem heres the outputerror error installing libv8 error failed to build gem native extension usersuser1rvmrubiesruby193p448binruby extconfrb creating makefile configured with prefixapplicationsxcodeappcontentsdeveloperusr withgxxincludedirusrincludec421 unable to find a compiler officially supported by v8 it is recommended to use gcc v44 or higher using compiler g applicationsxcodeappcontentsdevelopertoolchainsxcodedefaultxctoolchainusrbinlibtool file usersuser1rvmgemsruby193p448gemslibv831183vendorv8outx64releaseobjtargetpreparser libsrcatomicops internals x86 gcco has no symbols in file included from srcaccessorscc28 in file included from srcv8h60 in file included from srcobjectsinlh38 in file included from srcelementsh33 in file included from srcheaph41 srcstorebufferh2299 error private field heap is not used werrorwunusedprivatefield heap heap 1 error generated make1 usersuser1rvmgemsruby193p448gemslibv831183vendorv8outx64releaseobjtargetv8 basesrcaccessorso error 1 make x64release error 2 gyp generatorsmake buildgypgyp generatoroutputout buildallgyp ibuildstandalonegypi depth dv8 target archx64 sx64 dhost archx64 cxxtarget usersuser1rvmgemsruby193p448gemslibv831183vendorv8outx64releaseobjtargetpreparser libsrcallocationo cxxtarget usersuser1rvmgemsruby193p448gemslibv831183vendorv8outx64releaseobjtargetpreparser libsrcatomicops internals x86 gcco cxxtarget usersuser1rvmgemsruby193p448gemslibv831183vendorv8outx64releaseobjtargetpreparser libsrcbignumo cxxtarget usersuser1rvmgemsruby193p448gemslibv831183vendorv8outx64releaseobjtargetpreparser libsrcbignumdtoao cxxtarget usersuser1rvmgemsruby193p448gemslibv831183vendorv8outx64releaseobjtargetpreparser libsrccachedpowerso cxxtarget usersuser1rvmgemsruby193p448gemslibv831183vendorv8outx64releaseobjtargetpreparser libsrcconversionso cxxtarget usersuser1rvmgemsruby193p448gemslibv831183vendorv8outx64releaseobjtargetpreparser libsrcdiyfpo cxxtarget usersuser1rvmgemsruby193p448gemslibv831183vendorv8outx64releaseobjtargetpreparser libsrcdtoao cxxtarget usersuser1rvmgemsruby193p448gemslibv831183vendorv8outx64releaseobjtargetpreparser libsrcfastdtoao cxxtarget usersuser1rvmgemsruby193p448gemslibv831183vendorv8outx64releaseobjtargetpreparser libsrcfixeddtoao cxxtarget usersuser1rvmgemsruby193p448gemslibv831183vendorv8outx64releaseobjtargetpreparser libsrconceo cxxtarget usersuser1rvmgemsruby193p448gemslibv831183vendorv8outx64releaseobjtargetpreparser libsrcpreparsedatao cxxtarget usersuser1rvmgemsruby193p448gemslibv831183vendorv8outx64releaseobjtargetpreparser libsrcpreparsero cxxtarget usersuser1rvmgemsruby193p448gemslibv831183vendorv8outx64releaseobjtargetpreparser libsrcpreparserapio cxxtarget usersuser1rvmgemsruby193p448gemslibv831183vendorv8outx64releaseobjtargetpreparser libsrcscannero cxxtarget usersuser1rvmgemsruby193p448gemslibv831183vendorv8outx64releaseobjtargetpreparser libsrcstrtodo cxxtarget usersuser1rvmgemsruby193p448gemslibv831183vendorv8outx64releaseobjtargetpreparser libsrctokeno cxxtarget usersuser1rvmgemsruby193p448gemslibv831183vendorv8outx64releaseobjtargetpreparser libsrcunicodeo cxxtarget usersuser1rvmgemsruby193p448gemslibv831183vendorv8outx64releaseobjtargetpreparser libsrcutilso libtoolstatic usersuser1rvmgemsruby193p448gemslibv831183vendorv8outx64releaselibpreparser liba cxxtarget usersuser1rvmgemsruby193p448gemslibv831183vendorv8outx64releaseobjtargetpreparserpreparserpreparserprocesso linktarget usersuser1rvmgemsruby193p448gemslibv831183vendorv8outx64releasepreparser cxxtarget usersuser1rvmgemsruby193p448gemslibv831183vendorv8outx64releaseobjtargetv8 basesrcaccessorso gem files will remain installed in usersuser1rvmgemsruby193p448gemslibv831183 for inspection results logged to usersuser1rvmgemsruby193p448gemslibv831183extlibv8gem makeoutalso when doinggcc vi am gettingconfigured with prefixapplicationsxcodeappcontentsdeveloperusr withgxxincludedirusrincludec421apple llvm version 50 clang500279 based on llvm 33svntarget x86 64appledarwin1300thread model posixi have tried installing gcc via homebrew but this does not help what are other possible solutions,['ruby'] +565357,how to check nsstring is null or not i want to check weather a nsstring is null or not im assigning from an json array after assigning that string value is null now i want to check this string is null or not so i put like thisif mystringauthidnil but this if statement always false how i can check a string for null please help methanks,"['ios', 'objective-c']" +565380,how to implement polling using observables i have parametrized rest call that should be executed each five second with different paramsobservable restcall apimethod1param1i need to create observable polling that will execute restcall each 5 second with different param1 if api call fails i need to get error and make next call in 5 seconds interval between calls should be measured only when restcall is finished successerrorps im currently using rxjava but net example also will be good,['c#'] +565415,cocoapods podspec dependency import file not found i am trying to make a cocoapod that depends on another but i am having issues at compile time say in this case myapp is using cocoapoda and cocoapodb b relies on amyapp podfileplatform ios 50pod cocoapodapod cocoapodb path cocoapodbcocoapodb podspecsdependency cocoapodabut when i try to compile i get cocoapodacocoapodah file not found where the import in cocoapodb is trying to include it i have tried reading the podspec documentation but i did not really get what i am missing i also tried slibrary cocoapoda,['objective-c'] +565427,rails deleting developmentlog lines not file itself is it safe to delete the lines in the developmentlog in your rails applicationi have been developing for awhile and that file now has over 50 millions linesit is in the gitignore file so it is not causing problems when using git but i access it a lot and have to wait for it to load then scroll to the bottom i would imagine it is fine to delete the lines not the file itself but i just thought i would ask the experts first thanks guysgals,['ruby-on-rails'] +565439,what happens when a collection in java increases beyond capacity i have a service which stages all calls made to it in memory because we do not want to lose the data and at the same time we need this service to ever fail due to any external dependency like a db for example these staged calls are then routinely picked up and processed in the backgroundif for any reason if there are too many calls and we run out of memory we need to be alarmedso the question simply put is this what exception do i need to catch or monitor on to notify me when an addition to a list fails due to insufficient resources will it result in an oom in the vm itself or is there a collectionlevel limit as wellif there is no collectionlevel limit how would you recommend i monitor the usage of the service currently we have heap usage and memory usage metrics are those enough also the jvms are configured to kill on an oom error this is because the vm manager then restarts any process it is managing on a kill,['java'] +565447,how to specify thisplay name for web app configured without webxml how to specify thisplay name for web application war configured programmatically in java with webapplicationinitializer only i have something like thispublic class webappinitializer implements webapplicationinitializer public void onstartupservletcontext servletcontext throws servletexception with webxml this look like thiswebapp xmlns xmlnsxsiversion30 xsischemalocation 3 0xsd metadatacompletefalse thisplaynamemy appthisplayname webappis this possible in java configuration,['java'] +565449,short form for stringformatlocals i usually use the following pattern as mentioned in this questiona1s aformatlocalsi think it is a great way to write easily readable codesometimes it is useful to chain string formats in order to modularize the creation of complex stringsa1b2cabformatlocalsdc is a sumformatlocalsd12 is a sumpretty soon the code is pestered with xformatlocals to solve this problem i tried to create a lambdaf lambda x xformatlocalsa1b2c fabd fc is a sumbut this throws a keyerror since locals are the lambdas localsi also tried to apply the format only on the last stringa1b2cabdc is a sumformatlocalsdab is a sumbut this does not work since python only formats oncenow i could write a function that formats repeatedly until there is nothing more to dodef my format string vars f stringformatvars return f if fstring else my formatf varsbut i am wondering is there a better way to do this,['python'] +565520,how to backup mysql database on a remote server i have a mysql database exists on a remote sever i only have sql connection privilage i dont have ftp access to the server and i need to do a complete dump of the database i have tried mysqldumpbut the issue is it is creating the output on the server and as i dont have ftp i can not get the output from the serverhow can i do a clean backup and get the dump in my local machine of course the backup should be restored in my local machinethankssteven,['mysql'] +565596,reason fbsession cannot open a session from token data from its current state i want to open a session to facebook from a cached tokendatabut i fall on this error reason fbsession cannot open a session from token data from its current statemy code fbaccesstokendata savedaccesstokendata tokencachestrategy getsavedtokenifsavedaccesstokendatanil appdelegatesession openfromaccesstokendatasavedaccesstokendata completionhandlerfbsession session fbsessionstate status nserror error ifappdelegatesessionisopen nslogsession opened from saved access token nslogaccesstoken appdelegatesessionaccesstokendata accesstoken ifcompletionblocknull completionblock session is open from token data,['ios'] +565597,sdk manager broken after mavericks update after updating my macbook to mavericks i recognoized that the sdk manager is no longer working correctly when i click on the downarrow to drop down folders content the manager has some redrawing issues pictures i could live with that but its no longer possible to install new packagesdoes anyone know how to fix thisas the sdk manager is written in java it should be a jre problemediti checked if this issue also occurs on my imac and it does independently anybody else,['android'] +565745,just how tomcat classloader separate different webapps object scope in same jvm since tomcat can load more than one webapp at once and those webapps can work separate and do not thisturb each other and they work in same jvm so i am very confused about how tomcat handle the object scope in the same jvmfor example i have a singleton object in both of the two different webapps and tomcat will generate two different singleton object for each i always thought that the singleton object have only one object in the same jvm but in tomcat jvm there maybe has two or more i have read some info about the classloader tomcat has its own webappclassloader to load webapps so does it mean the object scope here is the classloader or am i wrong does anyone know about this or can give me some info about tomcat work memory layout,['java'] +565760,xcode 5 bots and testflight automated builds first i have a mac mini running server on mavericks and have xcode 5 installed on the server i have my ios projects set up with bots to run automated builds of my github repo on each commit to master what i want to find out is if anyone already has configure this kind of setup to work with automated builds being sent to testflightthe script that worked previously with a jenkins build process is pasted below but throws an error and does not upload when the bot completes it is build i have this script run on the postaction of the archive process of my appserver log errorprint entry cfbundleversion does not existerror specified application does not exist or is not a bundle directory libraryserverxcodedatabotrunscaches892fj1n2f4bb2514522v2a23d0f0c725deriveddatabuildproductsdebugiphoneosmyappipascript plist fileecho n srcrootinfoplist file build typeusrlibexecplistbuddy c print cfbundleversion plist file api tokenapi token team tokensecret appbuild rootdebugiphoneosfull product namebinrm botsproduct nameipausrbinxcrun sdk iphoneos packageapplication v app o botsproduct nameipausrbincurl f filebotsproduct nameipa f a pi tokenapi token f team tokenteam token f notesbuild uploaded automatically from server f thistribution listsinternalupdate 1120 a good resource to trytestflight botsi did not get it to work a couple weeks ago but the post has been updated since i last tried i will post my results here,['ios'] +565781,pass parameter in table valued function using select statement i have created a table valued return function which returns me a table here is call of my function as follow select from dbostatefixedtaxescalculation30201611006and its working ok for me now i want to use this function call in a select statment so i can pass 16 which is basically employeeid dynamically so i have decided to use inner join with table returned by that function like this select from employee as einner join dbostatefixedtaxescalculation30201611006 as tc on tcemployeeideemployeeidbut now how can i pass 16 as dynamic value of all employeeid one by one,['sql'] +565786,how to order by where in fields in laravel i did some calculate in a view table for products in mysql so i list these id for product reference idreferenceids viewtableorderbyscore desclistsproduct idand i want to get the product from those reference idproducts productwhereinid rederenceidsthe product content is correct but the order is wrong how to load product order by reference id i know i can do it in mysql by using order by fieldid fields but i want to find out laravel way and hope not use order by field command because it seems waste to much database efficiency,['mysql'] +565831,struts2 annotated or xml based which is more easier to manage and uncomplicated which is the easier and organized way to use struts2 with annotations or with xml files if with annotations then with which kind of annotations with strutsconventionplugin you can even avoid completely writing conventions ieresults or action what benefits will annotations give over not writing them,['java'] +565833,keeping to 79 char line limit in python with multiple indents i understand that to write good python code i should keep my lines to no more than 79 charactersthis is fine most of the time but if i have various nested for loops and if statements themselves nested within a class i might easily find that i have 5 or 6 indents ie 2024 characters if i am indenting by 4 spaces a time before i start then the 79 character limit becomes quite tricky i am aware of various tricks like implicit continuations within brackets and using brackets to concatenate long strings but even so it gets a bit fiddlyso what do you gurus adviseindenting by 2 spaces instead of 4 would help but is that considered good style not sure it would help make my code more readable and i note that pep8 says to use 4 spacesif i find i have multiple levels of indents is that perhaps i sign that i am writing bad code and if so any helpful tips or tricks for ways to avoid too much nestingam i right in trying to stick to the 79 character recommendation in the first placeor do i just have to get used to a lot of statements broken over multiple linesthanksadam,['python'] +565839,java how to determine optimal number of threads for high latency noniobound network requests i am writing a utility that must make thousands of network requests each request receives only a single small packet in response similar to ping but may take upwards of several seconds to complete processing each response completes in one simple line of codethe net effect of this is that the computer is not iobound filesystembound or cpubound it is only bound by the latency of the responsesthis is similar to but not the same as there is a way to determine the ideal number of threads and java best way to determine the optimal number of threads duplicate the primary difference is that i am only bound by latencyi am using an executorservice object to run the threads and a queuefutureinteger to track threads that need to have results retrievedexecutorservice executorservice executorsnewfixedthreadpoolthreadpoolsizequeuefutureinteger futures new linkedlistfutureintegerfor int quad3 0 quad3 256 quad3 for int quad4 0 quad4 256 quad4 byte quads quad1 quad2 bytequad3 bytequad4 futuresaddexecutorservicesubmitnew retrievercallablequads i then dequeue all the elements in the queue and put the results in the required data structureint result int65536whilefuturesisempty try resultsi futuresremoveget catch exception e addressesi 1 my first question is is this a reasonable way to track all the threads if thread x takes a while to complete many other threads might finish before x does will the thread pool exhaust itself waiting for open slots or will the executorservice object manage the pool in such a way that threads that have completed but not yet been processed be moved out of available slots so that other threads my beginmy second question is what guidelines can i use for finding the optimal number of threads to make these calls i do not even know orderofmagnitude guidance here i know it works pretty well with 256 threads but seems to take roughly the same overall time with 1024 threads cpu utilization is hovering around 5 so that does not appear to be an issue with that large a number of threads what are all the metrics i should be looking at to compare different numbers obviously overall time to process the batch average time per thread what else is memory an issue here,['java'] +565876,how do i create a helper for jasmineangular to combine multiple beforeeachs i keep repeating some code in my spec file that injects a template and then compiles it i extracted this code into a helper function to keep things dry i believe the problem is in trying to place to beforeeachs in a helper function here is the piece of my code that i am trying to abstract into a function beforeeachmoduleappviewsheaderhtml beforeeachinjectfunctiontemplatecache compile rootscope template templatecachegetappviewsheaderhtml templatecacheputviewsheaderhtml template var directive angularelementclinicalheaderclinicalheader element compiledirectiverootscope rootscopedigest here is the helper function that i created var setuptemplate functiontemplatename element beforeeachmoduleappviews templatename beforeeachinjectfunctiontemplatecache compile rootscope var template templatecachegetappviews templatename templatecacheputviews templatename template var directive angularelementelement element compiledirectiverootscope rootscopedigest and now this is the call to the helper functionsetuptemplateheaderhtml clinicalheaderclinicalheaderat the end of my helper function everything looks good but when i jump to my it block everything is undefined can i extract multiple beforeeachs what is the right way to do this also where is the proper place to put jasmine helper functions and how is that done,['javascript'] +565904,how to prepopulate checkboxes with flaskwtforms i am trying to produce a dynamic checkbox list with certain boxes checked based on the state of the dataheres my formclass fooformform bar selectmultiplefield bar option widgetcheckboxinput widgetlistwidgetprefix labeltrueheres the controllerapproutefooform methods getpostdef foo foos foo daofind form fooform formbarchoices fooid foolabel for foo in foos somehow prepopulate checkboxes here if formis submitted do stuff return render templatefoohtml foosfoos formformheres the template form action methodpost namefoos formbar pinput typesubmit valueaddp formthis produces a checkbox list and it works but i cannot figure out how to specify which checkboxes in the list are to be prepopulated,['python'] +565905,can a 301 page be crawled by google is it possible for google or any other crawler to crawl and index a page which returns a 301 status codei have seen a page in google which has had a 301 for months however the cache date of that page in the index is from a few days agocan google just ignore the 301 and crawl the contents of a page,['php'] +565970,htmldropdownlist selected value not working using constructor with ienumberable i have an issue where the selected value is not working for the htmldropdownlist helper method see belowthis is my controllerpublic actionresult editint id 0 newsevent item getitemid viewbagnewsitemid new selectlistviewbagnewsitemiditems id name itemnewsitemid return viewitemthis is my viewhtmldropdownlistnewsitemidviewbagnewsitemid as selectlist stringempty new class formcontrol however when i try the below in by view it workshtmldropdownlistnewsitemid stringemptythe below also works but since the field name does not match the model it will not post correctlyhtmldropdownlistnewsitemiddropviewbagnewsitemid as selectlist stringempty new class formcontrol the reason i need to use the first option is so that i can add the class attribute to the controlcould someone help me understand what i am doing wrong,['c#'] +565985,get uri from drawable image how can i get the uri of image saved in drawable i have tried following formats but everytime it cannot load the imageimageuri uriparseandroidresource getpackagename rdrawableindoor thumbnail1imageuriuriparseandroidresourcegetpackagenamedrawablesimagename imageuriuriparseandroidresourcegetpackagenamedrawablesimagenamepngimageuri uriparseandroidresource getresourcesgetresourcetypenamerdrawableindoor thumbnail1 getresourcesgetresourceentrynamerdrawableindoor thumbnail1png do not know why i cannot fetch the image uri,['android'] +565996,fit imagespan to textview line height i need to put some icons inside my textview but they do not fit the line height look at the arrowsi tried thisspannablesetspannew imagespancontext entrygetvalue imagespanalign bottom matcherstart matcherend spannedspan inclusive exclusivetsettextspannable buffertypespannableand this drawable myicon cgetresourcesgetdrawablerdrawablemyicon myiconsetbounds0 0 myicongetintrinsicwidth myicongetintrinsicheight spannablesetspannew imagespanmyicon imagespanalign baseline matcherstart matcherend spannedspan inclusive exclusivetsettextspannable buffertypespannableand in both cases i had the same resulti keep the icon in resdrawable folder and its size is 75x75pxi tried to lower the image resolution but they look blurred,['android'] +566028,what is the use for taskfromresult in c in c and tpl task parallel library the task class represents an ongoing work that produces a value of type ti would like to know what is the need for the taskfromresult method that is in a scenario where you already have the produced value at hand what is the need to wrap it back into a taskthe only thing that comes to mind is that it is used as some adapter for other methods accepting a task instance,"['c#', '.net']" +566053,return a requestsresponse object from flask i am trying to build a simple proxy using flask and requests the code is as followsapprouteesstringindexstringtypestringid methodsget post putdef esindex type id elasticsearch find out where elasticsearch lives also handle some authentication url s elasticsearch index type id esreq requestsrequestmethodrequestmethod urlurl headersrequestheaders datarequestdata resp requestssessionsendesreqprepare return resptextthis works except that it loses the status code from elasticsearch i tried returning resp a requestsmodelsresponse directly but this fails withtypeerror response object is not callableis there another simple way to return a requestsmodelsresponse from flask,['python'] +566078,error posting video to facebook using sdk for ios i have an app that posts native mov files video to facebook using the facebook sdk for ios it worked without problems till a few weeks ago where it started failing with the following error error code 352 message 352 sorry the video file you selected is in a format that we do not support type oauthexception the full error string iserror domaincomfacebooksdk code5 the operation couldnat be completed comfacebooksdk error 5 userinfo0x1ea42880 comfacebooksdkhttpstatuscode400 comfacebooksdkparsedjsonresponsekey body error code 352 message 352 sorry the video file you selected is in a format that we do not support type oauthexception code 400 headers name accesscontrolalloworigin value name cachecontrol value nostore name connection value close name contenttype value textjavascript charsetutf8 name expires value sat 01 jan 20 0 gmt name pragma value nocache name wauthenticate value oauth facebook platform invalid request 352 sorry the video file you selected is in a format that we do not support name xfbloadmon value 03070 comfacebooksdkerrorsessionkey expirationdate 40010101 0 0 refreshdate 20131015 171933 0 attemptedrefreshdate 20131024 145654 0 permissions share item email user photos user videos publish checkins manage pages read friendliststhe code i use to post is similar to thisnsmutabledictionary params nsmutabledictionary dictionarywithobjectsandkeys videodatavideomov videoquicktime contenttype title title status description nilfbrequest request fbrequest requestwithgraphpathnsstring stringwithformatvideosme parametersparams httpmethodpost request setsessionsession thispatch queue t queue thispatch get global queuethispatch queue priority background 0ul thispatch asyncqueue thispatch asyncthispatch get main queue void request startwithcompletionhandlerfbrequestconnection conn id data nserror error sslogdone self processresponsewithdatadata requestidentifierrequestidentifier anderrorerror i have updated to the latest sdk version 39 but the error is still there any body is experiencing this error i am testing with ios6 and ios7 so the problem is not related with the os version the same video uploads okey using the iosfacebook built in functionthanks very much,['ios'] +566097,symfony sonata admin languages not work i install sonata admin bundle everything work but i do not have any language buttons and text in admin is like before translated example labelselect context btn filter not filter but btn filter and other where i can setup language to sonata admin,['php'] +566203,string parsing using python given a string such as helloyellowellow parse all the valid strings from the given string eg hellhelloyellowlow lowi am looking for the most optimized way to write the code here is mine but i am not sure if this is the best wayfull thisclosure this was an interview questionmaster dictionary for us to look up words def is wordinputstr returns truefalsedef procestringfstrsecstrli if is wordfstr liappendfstr if lensecstr 0 if lenli 0 masterappendli return procestringfstrsecstr0 secstr1lensecstrlidef wrapperprocessinpstr li if leninpstr 0 return procestringinpstrli wrapperprocessinpstr1leninpstrwrapperprocesshelloyellowellowprint master,['python'] +566282,why do i get an invalidoperationexception when i try to use attribute routing with web api 2 i just updated my web api packages in my mvc 4 application so that i can use attribute routing when i add configmaphttpattributeroutes i get an error that says the object has not yet been initialized ensure that httpconfigurationensureinitialized is called in the applications startup code after all other initialization code if i remove configmaphttpattributeroutes and the route attributes everything works as it did before how can i resolve this error here is my webapiconfig classpublic static class webapiconfig public static void registerhttpconfiguration config configmaphttpattributeroutes configroutesmaphttproute name defaultapi routetemplate apicontrollerid defaults new id routeparameteroptional uncomment the following line of code to enable query support for actions with an iqueryable or iqueryablet return type to avoid processing unexpected or malicious queries use the validation settings on queryableattribute to validate incoming queries for more information visit configenablequerysupport and the error detailsthe object has not yet been initialized ensure that httpconfigurationensureinitialized is called in the applications startup code after all other initialization codedescription an unhandled exception occurred during the execution of the current web request please review the stack trace for more information about the error and where it originated in the code exception details systeminvalidoperationexception the object has not yet been initialized ensure that httpconfigurationensureinitialized is called in the applications startup code after all other initialization codesource error an unhandled exception was generated during the execution of the current web request information regarding the origin and location of the exception can be identified using the exception stack trace belowstack trace invalidoperationexception the object has not yet been initialized ensure that httpconfigurationensureinitialized is called in the applications startup code after all other initialization code systemwebhttproutingroutecollectionrouteget subroutes 127 systemwebhttproutingroutecollectionroutegetroutedatastring virtualpathroot httprequestmessage request 99 systemwebhttpwebhostroutinghttpwebroutegetroutedatahttpcontextbase httpcontext 191 systemwebroutingroutecollectiongetroutedatahttpcontextbase httpcontext 233 systemwebroutingurlroutingmodulepostresolverequestcachehttpcontextbase context 60 systemwebroutingurlroutingmoduleonapplicationpostresolverequestcacheobject sender eventargs e 82 systemwebsynceventexecutionstepsystemwebhttpapplicationiexecutionstepexecute 136 systemwebhttpapplicationexecutestepiexecutionstep step boolean completedsynchronously 69,['c#'] +566310,petapoco multiple result set support my work recently starting using petapoco and although fantastic i missed the feature from dapper which allowed multiple result grids from a single query to be processed into pocosas a result i wrote my own implementation for petapoco shown below but has anyone written their own and care to share iti thought there might be others out there who have missed this feature,['c#'] +566314,finding a nonzero integer x where x x in a course on algorithms and data structures at my university i received this questionwhich integer has the same bitpattern as his negative valuemeans x xi know that 0 works but i suspect that the instructor was looking for some other number x what x is it how would you find it,['java'] +566332,java how to replace a sequence of numbers in a string i am trying to replace any sequence of numbers in a string with the number itself within brackets so the input i ee44 a1 12 should have as an output i ee44 a1 12i am trying to implement it using stringreplaceab but with no success,['java'] +566351,push activity on the right when open drawer i have implemented drawerlayout which slides from the right but it does not shift the activity the right like facebook does see below image how do i push the current activity to the right side when user taps on opendrawer button like in the above imagecurrently it appears on top of activity and drops shadowi really appreciate any help thanks in advance,['android'] +566399,css transition after a pseudo element how to transition content that shows on hover doctype htmlhtmlheadstyle divtransitionafter 3swebkittransitionafter 3sdivhoveraftercontent positivestyleheadbodydivtestdivbodyhtmli have this sample code above i am trying to use transition so that the text positive takes 3 seconds to slideshow up but it is not working how to fix it,['css'] +566462,how to convert json array to list of objects in c i have json string like below jsonvalues id myid values value1 id 100 diaplayname myvalue1 value2 id 200 diaplayname myvalue2 i want to convert json string to below classes class valueset jsonpropertyid public string id get set jsonpropertyvalues public listvalue values get set class value public string id get set public string diaplayname get set my deserialization code is javascriptserializer js new javascriptserializer streamreader sr new streamreadervaluesetjsonstringtxt string jsonstring srreadtoend var items jsonconvertdeserializeobjectvaluesetjsonstringbut i am getting null values after serialization how i can solve this,['c#'] +566477,make bootstraps carousel both center and responsive i want my carousel images to be at the center horizontally which is not by default i follow the solution at this topichowever using this solution when the carousel is resized and smaller than the image the image is cropped instead of scaling as defaulthow can i both center my image but keep it to stretch to the carousel item,"['html', 'css']" +566519,spring data jpa no property found for type exception well i searched google and found many results but none of them was able to answer my problem so here it goesi am trying to study spring mvc and spring data jpa by doing a minimal implementation of pinterest clone so following is the parts of code which i think is relevant to my problemmodelsentitiesentitytablename pin itempublic class pinitem implements serializable properties joincolumnname board id referencedcolumnname user board id manytooneoptional false private userboard board getters and settersentitytablename user boardpublic class userboard implements serializable properties onetomanycascade cascadetypeall mappedby board private listpinitem pinitemlist getters and settersserviceservicetransactionalreadonly truepublic class boardserviceimpl implements boardservice autowired private userboardrepository boardrepository override public listuserboard findlatestboards pagerequest request new pagerequest 0 presentationutilpage size sortdirectiondesc boardid return boardrepositoryfindallrequestgetcontent other methodsrepositorypublic interface userboardrepository extends jparepositoryuserboard integer now when i call the findlatestboards method in boardservice no property found exception is thrown on the line return boardrepositoryfindallrequestgetcontent here is the excerpt from tomcat logdebug log122844254 debug annotationtransactionattributesource106 adding transactional method findlatestboards with attribute propagation requiredisolation defaultreadonly 122844254 debug defaultlistablebeanfactory246 returning cached instance of singleton bean transactionmanager122844254 debug jpatransactionmanager366 creating new transaction with name comtecnoocpicpinserviceimplboardserviceimplfindlatestboards propagation requiredisolation defaultreadonly 122844254 debug jpatransactionmanager369 opened new entitymanager orghibernateejbentitymanagerimpl75284194 for jpa transaction122844255 debug abstracttransactionimpl158 begin122844255 debug logicalconnectionimpl212 obtaining jdbc connection122844255 debug drivermanagerdatasource162 creating new jdbc drivermanager connection to jdbcmysqllocalhost3306pic pin122844266 debug logicalconnectionimpl218 obtained jdbc connection122844267 debug jdbctransaction69 initial autocommit status true122844267 debug jdbctransaction71 thisabling autocommit122844267 debug jpatransactionmanager401 exposing jpa transaction as jdbc transaction orgspringframeworkormjpavendorhibernatejpadialecthibernateconnectionhandle370da60e122844274 debug transactionalrepositoryproxypostprocessorcustomannotationtransactionattributesource286 adding transactional method findall with attribute propagation requiredisolation defaultreadonly 122844274 debug defaultlistablebeanfactory246 returning cached instance of singleton bean transactionmanager122844274 debug jpatransactionmanager332 found threadbound entitymanager orghibernateejbentitymanagerimpl75284194 for jpa transaction122844274 debug jpatransactionmanager471 participating in existing transaction122844279 debug cachedintrospectionresults159 not strongly caching class javaioserializable because it is not cachesafe122844281 debug jpatransactionmanager851 participating transaction failed marking existing transaction as rollbackonly122844281 debug jpatransactionmanager559 setting jpa transaction on entitymanager orghibernateejbentitymanagerimpl75284194 rollbackonly122844283 debug jpatransactionmanager844 initiating transaction rollback122844284 debug jpatransactionmanager534 rolling back jpa transaction on entitymanager orghibernateejbentitymanagerimpl75284194122844284 debug abstracttransactionimpl203 rolling back122844284 debug jdbctransaction164 rolled jdbc connection122844285 debug jdbctransaction126 reenabling autocommit122844285 debug jpatransactionmanager594 closing jpa entitymanager orghibernateejbentitymanagerimpl75284194 after transaction122844285 debug entitymanagerfactoryutils338 closing jpa entitymanager122844286 debug logicalconnectionimpl232 releasing jdbc connection122844286 debug logicalconnectionimpl250 released jdbc connection122844287 debug exceptionhandlerexceptionresolver132 resolving exception from handler public javalangstring comtecnoocpicpincontrollerboardcontrollerlatestjavaxservlethttphttpsessionorgspringframeworkuimodel orgspringframeworkdatamappingpropertyreferenceexception no property board found for type comtecnoocpicpinmodeluserboard122844289 debug responsestatusexceptionresolver132 resolving exception from handler public javalangstring comtecnoocpicpincontrollerboardcontrollerlatestjavaxservlethttphttpsessionorgspringframeworkuimodel orgspringframeworkdatamappingpropertyreferenceexception no property board found for type comtecnoocpicpinmodeluserboard122844290 debug defaulthandlerexceptionresolver132 resolving exception from handler public javalangstring comtecnoocpicpincontrollerboardcontrollerlatestjavaxservlethttphttpsessionorgspringframeworkuimodel orgspringframeworkdatamappingpropertyreferenceexception no property board found for type comtecnoocpicpinmodeluserboard122844291 debug thispatcherservlet959 could not complete requestexceptionthe exception is orgspringframeworkdatamappingpropertyreferenceexception no property board found for type comtecnoocpicpinmodeluserboard but if i understood correctly the property board is present in pinitem and is correctly mapped with mappedby board in userboardorgspringframeworkdatamappingpropertyreferenceexception no property board found for type comtecnoocpicpinmodeluserboard at orgspringframeworkdatamappingpropertypathinitpropertypathjava75 at orgspringframeworkdatamappingpropertypathcreatepropertypathjava327 at orgspringframeworkdatamappingpropertypathcreatepropertypathjava353 at orgspringframeworkdatamappingpropertypathcreatepropertypathjava307 at orgspringframeworkdatamappingpropertypathfrompropertypathjava271 at orgspringframeworkdatamappingpropertypathfrompropertypathjava245 at orgspringframeworkdatajparepositoryqueryqueryutilstojpaorderqueryutilsjava408 at orgspringframeworkdatajparepositoryqueryqueryutilstoordersqueryutilsjava372 at orgspringframeworkdatajparepositorysupportsimplejparepositorygetquerysimplejparepositoryjava456 at orgspringframeworkdatajparepositorysupportsimplejparepositorygetquerysimplejparepositoryjava437 at orgspringframeworkdatajparepositorysupportsimplejparepositoryfindallsimplejparepositoryjava319 at orgspringframeworkdatajparepositorysupportsimplejparepositoryfindallsimplejparepositoryjava289 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava57 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43 at javalangreflectmethodinvokemethodjava606 at orgspringframeworkdatarepositorycoresupportrepositoryfactorysupportqueryexecutormethodinterceptorexecutemethodonrepositoryfactorysupportjava3 at orgspringframeworkdatarepositorycoresupportrepositoryfactorysupportqueryexecutormethodinterceptorinvokerepositoryfactorysupportjava318 at orgspringframeworkaopframeworkreflectivemethodinvocationproceedreflectivemethodinvocationjava172 at orgspringframeworktransactioninterceptortransactioninterceptor1proceedwithinvocationtransactioninterceptorjava96 at orgspringframeworktransactioninterceptortransactionaspectsupportinvokewithintransactiontransactionaspectsupportjava260 at orgspringframeworktransactioninterceptortransactioninterceptorinvoketransactioninterceptorjava94 at orgspringframeworkaopframeworkreflectivemethodinvocationproceedreflectivemethodinvocationjava172 at orgspringframeworkdaosupportpersistenceexceptiontranslationinterceptorinvokepersistenceexceptiontranslationinterceptorjava155 at orgspringframeworkaopframeworkreflectivemethodinvocationproceedreflectivemethodinvocationjava172 at orgspringframeworkdatajparepositorysupportlockmoderepositorypostprocessorlockmodepopulatingmethodintercceptorinvokelockmoderepositorypostprocessorjava92 at orgspringframeworkaopframeworkreflectivemethodinvocationproceedreflectivemethodinvocationjava172 at orgspringframeworkaopinterceptorexposeinvocationinterceptorinvokeexposeinvocationinterceptorjava91 at orgspringframeworkaopframeworkreflectivemethodinvocationproceedreflectivemethodinvocationjava172 at orgspringframeworkaopframeworkjdkdynamicaopproxyinvokejdkdynamicaopproxyjava204 at comsunproxyproxy147findallunknown source at comtecnoocpicpinserviceimplboardserviceimplfindlatestboardsboardserviceimpljava45 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava57 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43 at javalangreflectmethodinvokemethodjava606 at orgspringframeworkaopsupportaoputilsinvokejoinpointusingreflectionaoputilsjava317 at orgspringframeworkaopframeworkreflectivemethodinvocationinvokejoinpointreflectivemethodinvocationjava183 at orgspringframeworkaopframeworkreflectivemethodinvocationproceedreflectivemethodinvocationjava150 at orgspringframeworktransactioninterceptortransactioninterceptor1proceedwithinvocationtransactioninterceptorjava96 at orgspringframeworktransactioninterceptortransactionaspectsupportinvokewithintransactiontransactionaspectsupportjava260 at orgspringframeworktransactioninterceptortransactioninterceptorinvoketransactioninterceptorjava94 at orgspringframeworkaopframeworkreflectivemethodinvocationproceedreflectivemethodinvocationjava172 at orgspringframeworkaopframeworkjdkdynamicaopproxyinvokejdkdynamicaopproxyjava204 at comsunproxyproxy148findlatestboardsunknown source at comtecnoocpicpincontrollerboardcontrollerlatestboardcontrollerjava31 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava57 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43 at javalangreflectmethodinvokemethodjava606 at orgspringframeworkwebmethodsupportinvocablehandlermethodinvokeinvocablehandlermethodjava219 at orgspringframeworkwebmethodsupportinvocablehandlermethodinvokeforrequestinvocablehandlermethodjava132 at orgspringframeworkwebservletmvcmethodannotationservletinvocablehandlermethodinvokeandhandleservletinvocablehandlermethodjava104 at orgspringframeworkwebservletmvcmethodannotationrequestmappinghandleradapterinvokehandlemethodrequestmappinghandleradapterjava745 at orgspringframeworkwebservletmvcmethodannotationrequestmappinghandleradapterhandleinternalrequestmappinghandleradapterjava686 at orgspringframeworkwebservletmvcmethodabstracthandlermethodadapterhandleabstracthandlermethodadapterjava80 at orgspringframeworkwebservletthispatcherservletdothispatchthispatcherservletjava925 at orgspringframeworkwebservletthispatcherservletdoservicethispatcherservletjava856 at orgspringframeworkwebservletframeworkservletprocessrequestframeworkservletjava936 at orgspringframeworkwebservletframeworkservletdogetframeworkservletjava827 at javaxservlethttphttpservletservicehttpservletjava621 at orgspringframeworkwebservletframeworkservletserviceframeworkservletjava812 at javaxservlethttphttpservletservicehttpservletjava728 at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava305 at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava210 at orgnetbeansmoduleswebmonitorservermonitorfilterdofiltermonitorfilterjava393 at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava243 at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava210 at orgapachecatalinacorestandardwrappervalveinvokestandardwrappervalvejava2 at orgapachecatalinacorestandardcontextvalveinvokestandardcontextvalvejava123 at orgapachecatalinaauthenticatorauthenticatorbaseinvokeauthenticatorbasejava472 at orgapachecatalinacorestandardhostvalveinvokestandardhostvalvejava171 at orgapachecatalinavalveserrorreportvalveinvokeerrorreportvalvejava99 at orgapachecatalinavalvesaccesslogvalveinvokeaccesslogvalvejava953 at orgapachecatalinacorestandardenginevalveinvokestandardenginevalvejava118 at orgapachecatalinaconnectorcoyoteadapterservicecoyoteadapterjava408 at orgapachecoyotehttp11abstracthttp11processorprocessabstracthttp11processorjava1023 at orgapachecoyoteabstractprotocolabstractconnectionhandlerprocessabstractprotocoljava589 at orgapachetomcatutilnetjioendpointsocketprocessorrunjioendpointjava312 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava1145 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava615 at javalangthreadrunthreadjava744i do not get why this exception is thrown any idea why it is happeningnote i am using hibernate as persistence provider also the code portion i put here is what i thought is relevant to the problem if it is not let me know and i will update the question with required portion,['java'] +566530,unable to install mongodb php driver on mac os 109 after googling for about an hour cannot find any solution that works for me i am on os x 109 maverickshere is what the terminal says sudo pecl install mongodownloading mongo144tgz starting to download mongo144tgz 141242 bytesdone 141242 bytes84 source files buildingrunning phpizegrep usrincludephpmainphph no such file or directorygrep usrincludephpzendzend modulesh no such file or directorygrep usrincludephpzendzend extensionsh no such file or directoryconfiguring forphp api versionzend module api nozend extension api nobuilding in privatetmppearinstallpearbuildrootdzh2iwmongo144running privatetmppearinstallmongoconfigurechecking for grep that handles long lines and e usrbingrepchecking for egrep usrbingrep echecking for a sed that does not truncate output usrbinsedchecking for cc checking whether the c compiler works yeschecking for c compiler default output file name aoutchecking for suffix of executableschecking whether we are cross compiling nochecking for suffix of object files ochecking whether we are using the gnu c compiler yeschecking whether cc accepts g yeschecking for cc option to accept iso c89 none neededchecking how to run the c preprocessor cc echecking for icc nochecking for suncc nochecking whether cc understands c and o together yeschecking for system library directory libchecking if compiler supports r nochecking if compiler supports wlrpath yeschecking build system type i386appledarwin1300checking host system type i386appledarwin1300checking target system type i386appledarwin1300checking for php prefix usrchecking for php includes iusrincludephp iusrincludephpmain iusrincludephptsrm iusrincludephpzend iusrincludephpext iusrincludephpextdatelibchecking for php extension directory usrlibphpextensionsnodebugnonzts20100525checking for php installed headers prefix usrincludephpchecking if debug is enabled nochecking if zts is enabled nochecking for re2c noconfigure warning you will need re2c 0134 or later if you want to regenerate php parserschecking for gawk nochecking for nawk nochecking for awk awkchecking if awk is broken nochecking whether to enable mongo extension yes sharedchecking whether byte ordering is bigendian nochecking whether to compile for recent osx architectures yeschecking whether to include code coverage symbols nochecking build with php streams support yeschecking for ld used by cc applicationsxcodeappcontentsdevelopertoolchainsxcodedefaultxctoolchainusrbinldchecking if the linker applicationsxcodeappcontentsdevelopertoolchainsxcodedefaultxctoolchainusrbinld is gnu ld nochecking for applicationsxcodeappcontentsdevelopertoolchainsxcodedefaultxctoolchainusrbinld option to reload object files rchecking for bsdcompatible nm usrbinnmchecking whether ln s works yeschecking how to recognize dependent libraries pass allchecking for ansi c header files yeschecking for systypesh yeschecking for sysstath yeschecking for stdlibh yeschecking for stringh yeschecking for memoryh yeschecking for stringsh yeschecking for inttypesh yeschecking for stdinth yeschecking for unistdh yeschecking dlfcnh usability yeschecking dlfcnh presence yeschecking for dlfcnh yeschecking the maximum length of command line arguments 196608checking command to parse usrbinnm output from cc object okchecking for objdir libschecking for ar archecking for ranlib ranlibchecking for strip stripchecking for dsymutil dsymutilchecking for nmedit nmeditchecking for single module linker flag yeschecking for exported symbols list linker flag yeschecking if cc supports fnortti fnoexceptions yeschecking for cc option to produce pic fnocommonchecking if cc pic flag fnocommon works yeschecking if cc static flag static works nochecking if cc supports c o fileo yeschecking whether the cc linker applicationsxcodeappcontentsdevelopertoolchainsxcodedefaultxctoolchainusrbinld supports shared libraries yeschecking dynamic linker characteristics darwin1300 dyldchecking how to hardcode library paths into programs immediatechecking whether stripping libraries is possible yeschecking if libtool supports shared libraries yeschecking whether to build shared libraries yeschecking whether to build static libraries nocreating libtoolappending configuration tag cxx to libtoolconfigure creating configstatusconfigstatus creating confighrunning makebinsh privatetmppearinstallpearbuildrootdzh2iwmongo144libtool modecompile cc iutil i iprivatetmppearinstallmongo dphp atom inc iprivatetmppearinstallpearbuildrootdzh2iwmongo144include iprivatetmppearinstallpearbuildrootdzh2iwmongo144main iprivatetmppearinstallmongo iusrincludephp iusrincludephpmain iusrincludephptsrm iusrincludephpzend iusrincludephpext iusrincludephpextdatelib iprivatetmppearinstallpearbuildrootdzh2iwmongo144util iprivatetmppearinstallmongoutil iprivatetmppearinstallpearbuildrootdzh2iwmongo144exceptions iprivatetmppearinstallmongoexceptions iprivatetmppearinstallpearbuildrootdzh2iwmongo144gridfs iprivatetmppearinstallmongogridfs iprivatetmppearinstallpearbuildrootdzh2iwmongo144types iprivatetmppearinstallmongotypes iprivatetmppearinstallpearbuildrootdzh2iwmongo144mcon iprivatetmppearinstallmongomcon dhave config h g o2 arch i386 arch x86 64 mmacosxversionmin105 c privatetmppearinstallmongophp mongoc o php mongolomkdir libs cc iutil i iprivatetmppearinstallmongo dphp atom inc iprivatetmppearinstallpearbuildrootdzh2iwmongo144include iprivatetmppearinstallpearbuildrootdzh2iwmongo144main iprivatetmppearinstallmongo iusrincludephp iusrincludephpmain iusrincludephptsrm iusrincludephpzend iusrincludephpext iusrincludephpextdatelib iprivatetmppearinstallpearbuildrootdzh2iwmongo144util iprivatetmppearinstallmongoutil iprivatetmppearinstallpearbuildrootdzh2iwmongo144exceptions iprivatetmppearinstallmongoexceptions iprivatetmppearinstallpearbuildrootdzh2iwmongo144gridfs iprivatetmppearinstallmongogridfs iprivatetmppearinstallpearbuildrootdzh2iwmongo144types iprivatetmppearinstallmongotypes iprivatetmppearinstallpearbuildrootdzh2iwmongo144mcon iprivatetmppearinstallmongomcon dhave config h g o2 arch i386 arch x86 64 mmacosxversionmin105 c privatetmppearinstallmongophp mongoc fnocommon dpic o libsphp mongooprivatetmppearinstallmongophp mongoc1610 fatal error phph file not foundinclude phph 1 error generatedmake php mongolo error 1error make failedmaybe someone has already encountered this problem and knows a solution,['php'] +566540,convert an existing column to identity i have a table in sql server with bundle of records i want to convert the id column which is primary key to an identity column without loss of data i thought of the following two approaches create a new table with identity drop the existing tablecreate a new column with identity drop the existing columnbut it is clear that they can not be implemented because keeping records is my first priorityis there another way to do this,['sql'] +566552,onclick event on textviewthat has textisselectabletrue is ony called on second click i have a onclicklistener on a textview and the textview has the flag that it is selectablebut the onclick event i specified is only called when the textview is clicked a second timeafter the second time it calles the onclick right but if a other textview that also is selectable with a onclicklistener it also is only called the second time then it works fine but then the other one works only the second time again i cannot find the source of this weird eventstelefoontxtsetonclicklistenernew onclicklistener override public void onclickview v starttelintenturltxtsetonclicklistenernew onclicklistener override public void onclickview v startwebintent,"['java', 'android']" +566570,convert a row in pandas into list i have a pandas data frame like this admit gpa gre rank 0 361 380 3 1 367 660 3 1 319 640 4 0 293 520 4now i want to get a list of rows in pandas like 03613803 13676603 13196404 02935204 how can i do it please help me thanks a lot,['python'] +566574,is it possible to make two java interfaces mutually exclusive i have two interfaces that should exclude each otherinterface animalinterface cat extends animalinterface bird extends animalhow can i prevent the implementation of a class that implements both cat and bird interfacesclass impossible implements cat bird,['java'] +566651,gson serialize a list of polymorphic objects i am trying to serializedeserialize an object that involves polymorphism into json using gsonthis is my code for serializingobixbaseobj lobbyobj new obixbaseobjlobbyobjsetisobixlobbyobixop batchop new obixopbatchopsetnamebatchbatchopsetinobixbatchinbatchopsetoutobixbatchoutlobbyobjaddchildbatchopgson gson new gsonsystemoutprintlngsontojsonlobbyobjheres the result obixobjisobixlobbychildrenobixopnamebatchthe serialization mostly works except its missing the contents of inherited members in particular obixbatchin and obixbatchout strings are missingheres my base classpublic class obixbaseobj protected string obix private string thisplay private string thisplayname private arraylistobixbaseobj children public obixbaseobj obix obj public void setnamestring name thisname name heres what my inherited class obixop looks likepublic class obixop extends obixbaseobj private string in private string out public obixop obix op public obixopstring in string out obix op thisin in thisout out public string getin return in public void setinstring in thisin in public string getout return out public void setoutstring out thisout out i realize i could use an adapter for this but the problem is that i am serializing a collection of base class type obixbaseobj there are about 25 classes that inherits from this how can i make this work elegantly,['java'] +566662,python equivalent for hashmap im new to python i have a directory which has many subfolders and files so in these files i have to replace some specified set of strings to new strings in java i have done this using hashmap i have stored the old strings as keys and new strings as their corresponding values i searched for the key in the hashmap and if i got a hit i replaced with the corresponding value is there something similar to hashmap in python or can you suggest how to go about this problemto give an example lets take the set of strings are request response i want to change them to myrequest and myresponse my hashmap was key valuerequest myrequestresponse myresponsei need an equivalent to this,['python'] +566690,c create sql table programmatically i am trying to create sql table programmaticallyhere is the codeusing sqlconnection con new sqlconnectionconstr try open the sqlconnection conopen the following code uses an sqlcommand based on the sqlconnection using sqlcommand command new sqlcommandcreate table customerfirst name char50last name char50address char50city char50country char25birth date datetime con commandexecutenonquery catch exception ex messageboxshowexmessage when i am running this application second time i am getting an exception there is already an object named customer in the database but when i check database i do not see such a tablehere is my connection string connectionstringsadd name autorepairsqlprovider connectionstring data sourcesqlexpressattachdbfilenamedatadirectoryautorepairdatabasemdf integrated securitytrueuser instancetrueconnectionstringswhen i am running select querys i am getting results from existing tables so i think connection string should be ok hope youll see the problem,"['c#', '.net', 'sql']" +566769,chartkick y axis uncorrect labeling i have chartkick 120 and groupdate 104 gem installed when i try to do sth like area chart matchgroup by day of weekcreated atcount width700px height150px i get thisit always gives me the wrong yaxis how should i format it so that it would thisplay monday tuesday my second example which i also cannot get it right is grouping by hours in a day abcmatcheson locationlocationgroup byb bcreated atstrftimehto i abcupdateabckey v vlength abcabcsort bykv k area chart abc width700px height150px what am i doing wrong that it thisplays 10 am etc i would just like to have numbers ie 0 1 2 3 23i googled around checked their docs top to bottom for some hours now and i really do not know what have i missed any help would be greatly appreciated,"['javascript', 'ruby-on-rails', 'ruby']" +566884,rails get the time difference in hours minutes and seconds i am looking for an idiomatic way to get the time passed since a given date in hours minutes and seconds if the given date is 20131025 235500 and the current date is 20131027 205509 the returning value should be 450309 the time difference and time diff gems would not work with this requirement,"['ruby-on-rails', 'ruby']" +566969,how to get host name with port from a http or https request i have two applications deployed in jboss containersame unix box if i get a request from app1 i need to frame a corresponding request for app2egif app1 request is then i need to extract so that i can frame request for second appi tried using httpservletrequestgetservername httpservletrequestgetserverport httpservletrequestgetheaderhost methods but the request may be of http or httpsplease let me know if there is any other better waythanks,['java'] +566990,how to select option in drop down protractorjs e2e tests i am trying to select an option from a drop down for the angular e2e tests using protractorhere is the code snippet of the select optionselect idlocregion classcreate select ngpristine nginvalid nginvalidrequired required ngthisabledorganizationid undefined ngoptionsoid as oname for o in organizations ngmodelorganizationparent id option value selectedselectedoption option value0ranjans mobile testingoption option value1beaverbox testingoption option value2badgerboxoption option value3crittercaseoption option value4boxloxoption option value5boobobumoptionselecti have triedptorfindelementprotractorbycselect option1clickthis gives me the following erroran invalid or illegal string was specifiedbuild info version 2350 revision c916b9d time 20130812 154201system info osname mac os x osarch x86 64 osversion 109 javaversion 160 65driver info driverversion unknowni have also triedptorfindelementprotractorbyxpathhtmlbodydiv2divdiv4divdivdivdiv3ngincludedivdiv2divdivorganizationformformdiv2selectoption3clickthis gives me the following errorelementnotvisibleerror element is not currently visible and so may not be interacted with command duration or timeout 9 milliseconds build info version 2350 revision c916b9d time 20130812 154201 system info osname mac os x osarch x86 64 osversion 109 javaversion 160 65 session id bdeb8088d8ad0f49aad982201c45c63f driver info orgopenqaseleniumfirefoxfirefoxdriver capabilities platformmac acceptsslcertstrue javascriptenabledtrue browsernamefirefox rotatablefalse locationcontextenabledtrue version240 cselectorsenabledtrue databaseenabledtrue handlesalertstrue browserconnectionenabledtrue nativeeventsfalse webstorageenabledtrue applicationcacheenabledfalse takesscreenshottruecan anyone please help me with this problem or throw some light on what i might be doing wrong here,['javascript'] +566993,nodejs write after end error zlib i have the following code where i am piping the request of a url that is gzipped this works just fine however if i try to execute the code a few times i get the below error any suggestions how to work around thisthank youhttpgeturl functionreq reqpipegunzip gunzipondata function data decoderdecodedata gunziponend function decoderresult error stack error write after end at writeafterend stream writablejs12512 at gunzipwritablewrite stream writablejs1705 at write stream readablejs54724 at flow stream readablejs5567 at stream readablejs5247 at process tickcallback nodejs41513,['javascript'] +567084,camera overlay change with bearing and elevation folks i am trying to get a utility as shown in the picture below basically the camera thisplay window covers part of the devices screen and a list of points that are connected by a curve or straight line are presented over the camera view as an overlay i understand this can be drawn using quartz but this is less than half of my problemthe real issue is that the overlay should present different points as the bearing and elevation changes for example if the bearing has to change 5 degrees and elevation 2 degrees then pt1 will be next to the right edge of the camera view pt2 will also move to the right and pt3 will be visibleanother movement that changes the bearing 10 degrees would make pt1 not visible pt2 at the right pt3 middle and pt4 on the left edge of the camera viewmy questions after the pictureis it possible to have a view that is substantially larger than the size of the camera view as shown below and use some methods i need to research these to move the view when bearingelevation changes is it recommended performance wiseis quartz the way to go here what else do i need other then of course avfoundation for the camera and corelocationmotion since my application is only ios 7 i can use any new methodsapis exclusive to ios 7aside from raywendelrichs tutorial on the augmented reality game are there any tutorials that you know of that could help me with this endeavor,['ios'] +567094,visual studio 2013 change authentication on existing project if i have an existing project in visual studio 2013 how do i change the authentication during a new project setup there is a change authentication button but i cannot find the equivalent for an existing project,"['asp.net', '.net']" +567114,python avoiding zip truncation of list i have the following python code that uses zip and it seems to cause unintended data truncationinc data uperiod ending udec 31 2012 udec 31 2011 udec 31 2010 utotal revenuen u104507100n u106916100n u99870100n ucost of revenuenu560n inc data2 zipinc datafor i in inc data2 print iit only printsuperiod ending utotal revenuen ucost of revenuenudec 31 2012 u104507100n u560nbut i want it to print the following but apparently i have to add in fillers u by hand in order to prevent zip from truncating the inc data but i do not know how to code thatuperiod ending utotal revenuen ucost of revenuenudec 31 2012 u104507100n u560nudec 31 2011 u106916100n uudec 31 2010 u99870100n uto describe inc data above inc data x y z how do i make x y and z to be the same length and the length is the max length of x y or z uperiod ending utotal revenuen ucost of revenuenudec 31 2012 u104507100n u560nudec 31 2011 u106916100n uudec 31 2010 u99870100n usorry for the lengthy and wordy explanation of the problem could you help me or point me to a similar question that has been answered if one exists many thanks,['python'] +567126,mbcs error building mfc c project with visual studio i opened my existing mfc project using visual studio and when i build i get the following error messageerror 1 error msb8031 use of mbcs encoding in mfc projects require an additional library to be downloaded and installed please see for more information cprogram filesmsbuildmicrosoftcppv40v120microsoftcppbuildtargetswhat is this about,['c++'] +567153,optimal settings for cassandra java driver to write to the local data centre only i have recently started using datastax java driver for our cassandra use case we will be using datastax java driver for readingwriting into cassandrai am successfully able to create cassandra connection using datastax java driver but i am wondering are there any other settings which i should be using in production environment to get the better performance using datastax java driver while making the connection to cassandra creating cassandra connection using datastax driver private datastaxconnection try builder clusterbuilder builderaddcontactpointsomenode can anybody explain me what does below piece of code do builderpoolingoptionssetcoreconnectionsperhost hostthistancelocal builderpoolingoptionsgetmaxconnectionsperhosthostthistancelocal and also what does below piece of code is doing cluster builder withretrypolicydowngradingconsistencyretrypolicyinstance withreconnectionpolicynew constantreconnectionpolicy100l build stringbuilder s new stringbuilder sethost allhosts clustergetmetadatagetallhosts for host h allhosts sappend sappendhgetdatacenter sappend sappendhgetrack sappend sappendhgetaddress sappend systemoutprintlncassandra cluster stostring session clusterconnecttestdatastaxks catch nohostavailableexception e catch exception e my top priorities are filter out the cassandra nodes basis on local datacenter so in the connection pool it will only have local datacenter cassandra nodesand get the best performance while using datastax java driver with some certain settingsi know it might be possible that certain settings will differ in different environment but there might be some settings that everybody has to follow to get the optimal performance while making the cassandra connections using datastax java driverlike for an example in astyanax when i was using earlier it was that you need to use token awareso there should be some best settings as well or recommended while using datastax java driver,['java'] +567158,jquery accordion scroll beginning of clicked tab to the top does not work if expanded tab is above the one being clicked got a little bit of a problem with getting my jquery accordion to do what i wanti always want the tab that is being clicked to be scrolled to a fixed amount of pixels from the top of the page and i kinda got it working but whenever the active tab is above the tab being clicked and if the page already is scrolled down a bit the top and parts of the content of the clicked tab is scrolled up past the top of the page this is what i gotfunction accordionaccordion autoheight false collapsible true heightstyle content active 0 animate 300 accordion h3bindclickfunction theoffset thisoffset bodyhtmlanimate scrolltop theoffsettop 100 heres a fiddle to illustrate my problem for example have section 2 expanded scroll down and click section 3 tab and it all scrolls off the page other way around it works thoughand if closing the active tab before opening a new one it also works fine so i am assuming this has something to to with the height of the collapsing tab that messes up the scroll to top functionhope someone can help i probably approach this the wrong way i kinda really do not know what i am actually doing as my jquery skills are limited to a basic cut n paste understanding thanks in advance and all help and pointers area more then welcome cheers,['jquery'] +567172,sql check if timestamp is greater than 24 hours from now mysql how to check if timestamp is greater than 24 hours from now with mysqldelete from users where time update date format a 20131024 1323,['mysql'] +567173,regex for password must be contain at least 8 characters least 1 number and both lower and uppercase letters and special characters i want a regular expression to check thatpassword must be contain at least 8 characters including at least 1 number and includes both lower and uppercase letters and special characters eg cannot be your old password or contain your username password or websitenameand here is my validation expression which is for 8 characters including 1uppercase letter 1 lowercase letter 1 number or special character8dwnazazhow can i write it for password must be 8 characters including 1 uppercase letter 1 special character and alphanumeric characters,"['javascript', 'asp.net']" +567179,launcher activitys onresume method gets called twice but oncreate only once when my app starts the launcher activitys oncreate method gets called normally only once but that is immediately followed by two calls to onresume when i inspect the code both instances are of the same class but only one has instanced members from the oncreate obviously everything is working fine though i am just curious trying to understand why this is happening does anybody have any ideas i am using sherlockfragmentactivity does that have anything to do with it i am happy to provide more information as needed i just do not know now what else is relevantthanks,['android'] +567281,gmap dragging using left mouse button i am using the gmapnet control to thisplay the maps on windows formsas of now everything works fine except the map dragging functionalityin general map dragging is supported with leftmouse button but in gmapnet control dragging is supported with rightmouse button here my question is is there any way by which i can achieve the map dragging functionality using leftmouse buttonplease help methanks in advance,['c#'] +567444,how to save and reuse same instance of fragments i have recently started using fragments have created a demo app which looks like this clicking on each button switches between fragment 1 fragment 2 and fragment 3what i am trying to accomplish is to only have 1 instance of each fragment and reuse that please note that all the fragments are created and added dynamically currently i am doing this by creating a hashmap of fragment and placing each instance and grabbing it from thereso my questions areis there a better way of doing thisby using fragmentmanagers putfragment method putfragment bundle bundle string key fragment fragment i cannot figure out how to use it in my case if anyone can give me an example of how to use this method is it expensive to hold onto a reference of each fragment in my activity does this keep all the fragments alive i am using soft reference to tackle this but i am not sure if this is the proper way of doing this please point me towards any alternative way of doing this or let me know if this is best way to accomplish this thanks in advancehere is my codeupdate i am trying to reuse fragments from the back stack trying to only add them if it does not exists in the back stack the code below gives me the illegal state exception after i navigate away from fragment one come back to it then try to press back button1028 132140255 errormessagequeuejni3548 javalangillegalstateexception fragment already added fragmentone423db570 0 id0x7f0506 fragonepublic class mainactivity extends activity implements viewonclicklistener private button btnoneprivate button btntwoprivate button btnthree called when the activity is first created overridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain initialize iffindviewbyidridfl null ifsavedinstancestate null return fragmentmanagerenabledebugloggingtrue updateviewfragoneprivate void initialize btnone button findviewbyidridbutton1 btntwo button findviewbyidridbutton2 btnthree button findviewbyidridbutton3 btnonesetonclicklistenerthis btntwosetonclicklistenerthis btnthreesetonclicklistenerthis fragholder new hashmapstring softreferencefragmentprivate void updateviewstring tag fragmenttransaction ft getfragmentmanagerbegintransaction fragment frag getfragmentmanagerfindfragmentbytagtag boolean addtostack true iffrag null iftagequalsfragone frag new fragmentone else iftagequalsfragtwo frag new fragmenttwo else iftagequalsfragthree frag new fragmentthree else do not add to back stack addtostack false ftreplaceridfl frag tag ifaddtostack ftaddtobackstacknull ftcommit override public void onclickview v switchvgetid case ridbutton1 updateviewfragone break case ridbutton2 updateviewfragtwo break case ridbutton3 updateviewfragthree break,"['java', 'android']" +567480,gcc o3 optimize xmm0 register i cannot use english well please understand tti was writing a vsprintf function to use my 64bit os kernel written by c and checked that it works well in visual studio and cygwin gccthen i put to my kernel and run but kernel does not works welli debugged and figured out the problem vsprintf contains next assembly codemovdqa xmm0xmmword ptr rip0x0the real problem is that i never use floating pointi guess that was gccs optimization and it seems to be correct because it works well without optimizationis there any solution so to speak gcc option that thisable optimization with xmm registers,['c'] +567487,c template call of function pointer type if i have type declarations liketypedef void commandtemplate command cvoid execute cvoid task some piece of code thenexecutetaskwill compile and behaves as expected however if i define the template astemplate command cvoid execute commandit still compiles i did this by accident now i am confused of what the second version would be expected to do,['c++'] +567522,laravel paginate and get with the code below what i wanted was paginate the query i created but when i try to add paginate after get it throws an error i wanted to remain get since i want to limit to columns that was set on fieldswhat would should be the better idea to paginate this thing or whats a good substitute for get and limit the columnswhat i triedgetthisfieldspaginatethislimitpart of my controllerclass phonescontroller extends basecontroller protected limit 5 protected fields arrayphonesmanufacturersname as manufacturer thisplay a listing of the resource return response public function index if requestquerystr phones phonewheremodel like requestquerystr joinmanufacturers manufacturers id manufacturersid getthisfields else phones phonejoinmanufacturers manufacturers id manufacturersid getthisfields return viewmakephonesindexwithphones phones,['php'] +567601,octopress pushing error to github i am trying to push an octopress to github pageeverything has worked fine up to now but when i do the rake deploy command after thisplaying octopress files i get the following errorto rukshnrukshngithubiogit rejected master master nonfastforwarderror failed to push some refs to rukshnrukshngithubiogithint updates were rejected because the tip of your current branch is behindhint its remote counterpart merge the remote changes eg git pullhint before pushing againhint see the note about fastforwards in git push help for detailswhats the problem,['ruby'] +567650,sha256 signing stops working in net 45 we have a piece of code which creates a signingcredentials object to use to sign xml document by using sha256 algorithm it works with net 35 perfectly however when we upgrade our codebase to net 45 it stops working same code same certificate i have spent hours on debugging and searching on the internet without any luckcould anyone please tell me what the problem here is thank you in advancecode to create signingcredentialspublic signingcredentials createsigningcredentialsx509certificate2 cert var ski new securitykeyidentifiernew x509rawdatakeyidentifierclausecert return new signingcredentialsnew x509asymmetricsecuritykeycert skiexception cryptographicexception invalid algorithm specified systemsecuritycryptographycryptographicexceptionthrowcryptographicexceptionint32 hr 41 systemsecuritycryptographyutilssignvaluesafekeyhandle hkey int32 keynumber int32 calgkey int32 calghash byte hash int32 cbhash objecthandleonstack retsignature 0 systemsecuritycryptographyutilssignvaluesafekeyhandle hkey int32 keynumber int32 calgkey int32 calghash byte hash 118 systemsecuritycryptographyrsacryptoserviceprovidersignhashbyte rgbhash int32 calghash 334 systemsecuritycryptographyrsapkcs1signatureformattercreatesignaturebyte rgbhash 321 systemidentitymodelsignedxmlcomputesignaturehashalgorithm hash asymmetricsignatureformatter formatter string signaturemethod 323 systemidentitymodelsignedxmlcomputesignaturesecuritykey signingkey 690 systemidentitymodelenvelopedsignaturewritercomputesignature 338 systemidentitymodelenvelopedsignaturewriteronendrootelement 278 systemidentitymodelmetadatametadataserializerwriteentitydescriptorxmlwriter inputwriter entitydescriptor entitydescriptor 1109,['.net'] +567698,how to use class name in class scope in python i am not very familiar with python so i have some problem while i codeit is very normal to use function name in function block for exampledef fn if and 1 return n else return and fn1but when i try to do use class name in class block things go wrongclass fobject a foonameerror name foo is not definedalthough the code below is okayclass fobject def init self a foothen i debug these two codes using print globals statement i found that global variable dict in class block does not contain class foo while global variable dict in init function block contains itso it seems that the class name binding is after the execution of class block and before the execution of function blockbut i do not like guesswork in foundation area of codingcould anyone offer a better explanation or official material for this questionthanks for answer in advance,['python'] +567753,unit testing aspnet mvc5 app i am extending the applicationuser class by adding a new property as shown in the tutorial create an aspnet mvc 5 app with facebook and google oauth2 and openid signon cpublic class applicationuser identityuser public datetime birthdate get set now i want to create a unit test to verify that my accountcontroller is correctly saving the birthdatei have created an inmemory user store named testuserstore testmethodpublic void register arrange var usermanager new usermanagerapplicationusernew testuserstoreapplicationuser var controller new accountcontrollerusermanager this will setup a fake httpcontext using moq controllersetfakecontrollercontext act var result controllerregisternew registerviewmodel birthdate testbirthdate username testuser password testuserpassword confirmpassword testuserpassword result assert assertisnotnullresult var addeduser usermanagerfindbynametestuser assertisnotnulladdeduser assertareequaltestbirthdate addeduserbirthdatethe controllerregister method is boilerplate code generated by mvc5 but for reference purposes i am including it here post accountregisterhttppostallowanonymousvalidateantiforgerytokenpublic async taskactionresult registerregisterviewmodel model if modelstateisvalid var user new applicationuser username modelusername birthdate modelbirthdate var result await usermanagercreateasyncuser modelpassword if resultsucceeded await signinasyncuser ispersistent false return redirecttoactionindex home else adderrorsresult if we got this far something failed rethisplay form return viewmodelwhen i call register it calls signinasync which is where the trouble will occurprivate async task signinasyncapplicationuser user bool ispersistent authenticationmanagersignoutdefaultauthenticationtypesexternalcookie var identity await usermanagercreateidentityasyncuser defaultauthenticationtypesapplicationcookie authenticationmanagersigninnew authenticationproperties ispersistent ispersistent identityat the lowest layer the boilerplate code includes this tidbitprivate iauthenticationmanager authenticationmanager get return httpcontextgetowincontextauthentication this is where the root of the problm occurs this call to getowincontext is an extension method which i cannot mock and i cannot replace with a stub unless of course i change the boilerplate codewhen i run this test i get an exceptiontest method mvclabmigrationtestscontrollersaccountcontrollertestregister threw exception systemaggregateexception one or more errors occurred systemnullreferenceexception object reference not set to an instance of an objectat systemwebhttpcontextbaseextensionsgetowinenvironmenthttpcontextbase contextat systemwebhttpcontextbaseextensionsgetowincontexthttpcontextbase contextat mvclabmigrationcontrollersaccountcontrollerget authenticationmanager in accountcontrollercs line 330at mvclabmigrationcontrollersaccountcontrollersigninasyncd 40movenext in accountcontrollercs line 336in prior releases the aspnet mvc team worked very hard to make the code testable it seems on the surface that now testing an accountcontroller is not going to be easy i have some choicesi canmodify the boiler plate code so that it does not call an extension method and deal with this problem at that levelsetup the owin pipeline for testing purposesavoid writing testing code that requires the authn authz infrastructure not a reasonable optioni am not sure which road is better either one could solve this my question boils down to which is the best strategynote yes i know that i do not need to test code that i did not write the usermanager infrastructure provided mvc5 is such a piece of infrastructure but if i want to write tests that verify my modifications to applicationuser or code that verifies behavior that depends upon user roles then i must test using usermanager,"['c#', 'asp.net']" +567763,how to cross compile raspberry pi project on x86 64 missing so due to invalid path i am cross compiling raspberry pi project on x86 64ubuntu 1304 after invoking cmake withcmake dcmake toolchain filetoolchainraspberrypi and then make linking failsopttoolsarmbcm2708gcclinaroarmlinuxgnueabihfraspbianbinlibgccarmlinuxgnueabihf472armlinuxgnueabihfbinld cannot find lopencv gputhe problem is that cmake generated makefile invokes linker in the following wayopttoolsarmbcm2708gcclinaroarmlinuxgnueabihfraspbianbinarmlinuxgnueabihfg cmakefileswatsondirmaincppo o watson rdynamic lopencv gpu lopencv contrib lopencv legacy lopencv objdetect lopencv calib3d lopencv features2d lopencv video lopencv highgui lopencv ml lopencv imgproc lopencv flann lopencv core and it does not specify paths to those shared libraries however if i manually add sysroot optrpirootfs flag to the command above then linking succeedswhat is the recommended way to get cmake to specify the right paths to the shared libraries when cross compilinghere is my toolchainraspberrypi filesetcmake system name linuxsetcmake system version 1setcmake c compiler opttoolsarmbcm2708gcclinaroarmlinuxgnueabihfraspbianbinarmlinuxgnueabihfgccsetcmake cxx compiler opttoolsarmbcm2708gcclinaroarmlinuxgnueabihfraspbianbinarmlinuxgnueabihfgsetcmake find root path optrpirootfssetcmake find root path mode program neversetcmake find root path mode library onlysetcmake find root path mode include onlyand this is my cmakelisttxt filecmake minimum requiredversion 28projectwatsonadd executablewatson maincppfind packageopencv requiredtarget link librarieswatson opencv libsthe usr and lib directories from the target are rsynced to optrpirootfs and all the necessary so files are there after reading cmake documentation i would have expected that setting cmake find root path would solve this problem but apparently not i am using cmake version 28101,['c++'] +567813,aes with password based secretkeyspec vs pbe after reading through several stackoverflow questions about implementing aes i think i am starting to understand the basicsevery single time i should generate a new ivwhen using pbe the iteration count should be around 1040since i cannot predict the amount of data to be encrypted i should not use ecb cipher modemy environment is quite simplethe passphrase should be secure it is a securerandom generated random 32 character at the moment ie not set by a userthe generated encrypted content may end up being stored as cookies so they are somewhat publicbased on these i came up with the following java codepublic class secureencryption private static final string content thisneedstobestoredverysecurelyprivate static final string passphrase mysuperstrongpasswordprivate static final int iv length 16public static void mainstring args throws exception messagedigest digest messagedigestgetinstancesha1 byte passphrase digestdigestpassphrasegetbytesutf8 cipher instance ciphergetinstanceaescfbnopadding passphrase arrayscopyofpassphrase 16 secretkeyspec secretkey new secretkeyspecpassphrase aes byte iv new byte16 securerandom sr new securerandom srnextbytesiv instanceinitcipherencrypt mode secretkey new ivparameterspeciv byte encrypted instancedofinalcontentgetbytesutf8 byte result addivtoencryptediv encrypted systemarraycopyresult 0 iv 0 iv length systemarraycopyresult iv length encrypted 0 resultlength iv length instanceinitcipherdecrypt mode secretkey new ivparameterspeciv byte decrypted instancedofinalencrypted systemoutprintlnnew stringdecrypted utf8private static byte addivtoencryptedbyte iv byte encrypted byte ret new byteiv length encryptedlength systemarraycopyiv 0 ret 0 iv length systemarraycopyencrypted 0 ret iv length encryptedlength return retwhile this works fine i am not sure if it is as secure as it can geti am kind of lost at the moment regarding the following thingsis pbe using aessha more secure does the saltiteration count adds considerably to security which exact combination of pbe should i use if soshould i instead consider using salt for the encryptable content rather than for the pbe keyif using salt for the content what is preferred one static value or different values but appendedprepended to the encrypted result just as it is done with ivupdate based on the recommendations received here i rewrote my implementationpublic class secureencryption private static final string content thisneedstobestoredverysecurelyprivate static final string passphrase mysuperstrongpasswordprivate static final int iv length 16private static final int aes key length 16private static final int mac key length 16private static final int mac length 20private static final int iteration count 4096private static final string aes aesprivate static final string cipher algorithm aescfbnopaddingprivate static final string secret key algorithm pbkdf2withhmacsha1private static final string mac algorithm hmacsha1public static void mainstring args throws exception cipher cipher ciphergetinstancecipher algorithm securerandom sr new securerandom byte salt new byte16 srnextbytessalt secretkeyfactory factory secretkeyfactorygetinstancesecret key algorithm secretkey secretkey factorygeneratesecretnew pbekeyspecpassphrasetochararray salt iteration count 256 byte secretbytes secretkeygetencoded byte iv new byte16 srnextbytesiv cipherinitcipherencrypt mode new secretkeyspecsecretbytes 0 aes key length aes new ivparameterspeciv byte encrypted cipherdofinalcontentgetbytesutf8 byte result concatarraysiv encrypted byte macresult getmacsecretbytes result result concatarraysmacresult result systemarraycopyresult 0 macresult 0 mac length systemarraycopyresult mac length iv 0 iv length systemarraycopyresult mac length iv length encrypted 0 resultlength iv length mac length if arraysequalsgetdigestgetmacsecretbytes concatarraysiv encrypted getdigestmacresult systemoutprintlninvalid mac cipherinitcipherdecrypt mode new secretkeyspecsecretbytes 0 aes key length aes new ivparameterspeciv byte decrypted cipherdofinalencrypted systemoutprintlnnew stringdecrypted utf8private static byte getdigestbyte mac throws exception messagedigest digest messagedigestgetinstancesha1 return digestdigestmacprivate static byte getmacbyte secretbytes byte data throws exception mac mac macgetinstancemac algorithm macinitnew secretkeyspecsecretbytes aes key length mac key length mac algorithm return macdofinaldataprivate static byte concatarraysbyte first byte second byte ret new bytefirstlength secondlength systemarraycopyfirst 0 ret 0 firstlength systemarraycopysecond 0 ret firstlength secondlength return retthe plan will be to generate the salt installation time and then it will remain the same for all encryptiondecryption operations i am assuming that this should provide good enough protection against rainbow table attacksupdate 2 i had to realize that my mac verification code was not quite optimal the mac already was sha1 hashed so there was no point in creating a yet another sha1 digest i have also adjusted the mac verification so it no longer uses arraysequals as that is vulnerable against timing attacks,['java'] +567827,c construction myclass c is bad myclass c myclass is slow i want myclass c heres some codeclass myclasspublic int yint main myclass item1 myclass item2 myclasswhen i run this i receive the following valuesitem1y garbageitem2y 0which well surprises mei expected item1 to be defaultconstructed and item2 to be copyconstructed off an anonymous defaultconstructed instance of myclass resulting in both equaling 0 since defaultconstructors initialize members to default values examining the assemblymyclass item1myclass item2 myclassxor eaxeax mov dword ptr ebp128heax mov ecxdword ptr ebp128h mov dword ptr item2ecx shows item2 being constructed by writing a 0 value somewhere temporary and then copying it into item2 as expected however there is no assembly for item1 so the program has memory for item1 in the stack but it never constructs item1i can appreciate wanting that behavior for speed purposes but i want the best of both worlds i want to know item1y 0 it gets constructed but i do not want to waste time on defaultconstructanonymousinstancethencopyconstruct like item2 does frustratingly i cannot force a defaultconstruct by saying myclass item1 since that is interpreted as a function prototype so if i want to use the default constructor on item1 without also copyconstructing how the heck do i do thatsidenote it looks like if i declare a constructor for myclass item1 is constructed as usual so this behavior only applies to compilergenerated constructors,['c++'] +567829,mvc 4 razor using ajax forms to update a foreach loop where to starti can find similar things on the internet as to how but they never seem to work with my specific way of wanting to do something i have tried with and without partial views with very little successquick rundown i have a stronglytyped view with an ajax form underneath the form i have a foreach loop that repeats a code block i need to be able to update the code block from the forms choices filtersheres my view findateachercshtml as it currently stands after trying many different ideasmodel teachersmodelsomnimodel viewbagtitle findateacher layout viewsshared layoutcshtmlh2find a teacherh2using ajaxbeginformfilterteachers home new ajaxoptions httpmethod post onsuccess onsuccess div idcontentfilter div classfilterlabels psearch by namep pfilter by instrumentp pfilter by cityp div div classfilterobjects p input typetext idnametxt button typesubmit idfindbuttonfindbutton p phtmldropdownlistinstrumentid selectlistmodelinstruments select an instrument new id instrumentdd p phtmldropdownlistcityid selectlistmodelcities select a city new id citydd p div divhr foreach var r in modelteachers div idcontentresults div idavatar img srci div div iddemographics h6rteacherh6 strongrstudionamestrong pa hrefrurlap prstreetaddressp prcity raddrestateid rzipp prphonep premailaddressp div div idstudiodetails pstronginstruments taughtstrongp p var instrumentstring rinstrumentsaggregate a b a binstrument if instrumentstringlength 0 instrumentstring instrumentstringremoveinstrumentstringlastindexof instrumentstring p br if rinformation rinformation null pstronginformationstrongp prinformationp div divnow heres my controller i get the results back correctly in the controller just not updating the code blockpublic actionresult findateacher modelinstruments new selectlistteacherservicegetinstrumentlist0instrumentidinstrument modelcities new selectlistteacherservicegetcitylistcityidcity modelteachers teacherservicegetteacherlist 0 return viewmodel httppost public jsonresult filterteachersstring teachername string instrumentid string cityid modelteachers teacherservicegetteacherlistjohn 0 0 return jsonmodelteachers thanks,['jquery'] +567830,python xticks in subplots if i plot a single imshow plot i can usefig ax pltsubplotsaximshowdatapltxticks 4 14 24 5 15 25 to replace my xtick labelsnow i am plotting 12 imshow plots using f axarr pltsubplots4 3axarri jimshowdatahow can i change my xticks just for one of these subplots i can only access the axes of the subplots with axarri j how can i access plt just for one particular subplotthanks,['python'] +567833,is settimeout a good solution to do async functions with javascript searching in the web about async functions i found many articles using settimeout to do this workwindowsettimeoutfunction consolelogsecond 0consolelogfirstoutputfirstsecondthis works but is a best practicethank,"['javascript', 'jquery']" +567887,ios7 uiswitch its event valuechanged calling continuously is this bug or what editit is now fixed on ios71do not do any tweak to fix itedit2apparently the same problem happens again in ios 80 and 81edit3it is now fixed on ios92do not do any tweak to fix ithi today i seen in uiswitchs event valuechanged calling continuously while i am change to on to off or off to on and my finger moved still on right side as well as left side i atteched gif image for more clear with nslogmy value changed method is ibactionchangeswitchidsender ifsender ison nslogswitch is on else nslogswitch is off ios6 the same code of switch working fine as we expectationso can anyone suggest me that call only one time its state on or off or is this is a bug or whatupdatehere it is my demo of itprogrammatic add uiswitchfrom xib adding uiswitch,"['ios', 'iphone']" +567903,ajax autocomplete extender is not working i have an autocompleate extender on textbox which shows records as a list from database but whern i click on texbox and start typing nothing happned my html code isasptextbox idtextbox1 runatserverasptextbox aspautocompleteextender idtextbox1 autocompleteextender runatserver enabledtrue targetcontrolidtextbox1 servicepathwebserviceasmx servicemethodgetcompletionlist minimumprefixlength2 completioninterval10 enablecachingtrue completionsetcount20 delimitercharacters showonlycurrentwordincompletionlistitemtrue aspautocompleteextenderand my web service is using system using systemcollectionsgeneric using systemlinq using systemweb using systemwebservices using systemdata using mysqldatamysqlclient using systemconfiguration summary summary description for webservice summary webservicenamespace webservicebindingconformsto wsiprofilesbasicprofile1 1 to allow this web service to be called from script using aspnet ajax uncomment the following line systemwebscriptservicesscriptservice public class webservice systemwebserviceswebservice public webservice uncomment the following line if using designed components initializecomponent webmethod public static liststring getcompletionliststring prefixtext int count mysqlconnection con new mysqlconnectionconfigurationmanagerappsettingscn if constate connectionstateclosed conopen mysqlcommand cmd new mysqlcommandselect gotra from tbgotra where gotra like prefixtext con liststring k new liststring using mysqldatareader sdr cmdexecutereader while sdrread kaddsdrgotratostring conclose return k,['asp.net'] +567932,how to do a view hierarchy dump in android app i want to profile my ui it falls on stackoverflow for the ondraw methodi have been told its because my ui has too many layersi wanted to do a view hierarchy dump to see how deep my layers arebut when i try to load the hierarchyviewer i get this errorerror obtaining ui hierarchyerror while obtaining ui hierarchy xml file comandroidmlibsyncexception remote object does not existhow do i fix it,['android'] +567936,change color inside stringsxml i am new to android and would like to know how do i change the color of font inside the stringsxml file in a string tagfor example i have string namehello worldhello worldstringi just it to thisplay as red and bluethanx,['android'] +567943,what does it mean to odruse something this just came up in the context of another questionapparently member functions in class templates are only instantiated if they are odrusedcould somebody explain what exactly that means the wikipedia article on odr does not mention odrusehowever the standard defines it asa variable whose name appears as a potentiallyevaluated expression is odrused unless it is an object that satisfies the requirements for appearing in a constant expression 519 and the lvaluetorvalue conversion 41 is immediately appliedin basicdefodredit apparently this is the wrong part and the entire paragraph contains multiple definitions for different things this might be the relevant one for class template member functiona nonoverloaded function whose name appears as a potentiallyevaluated expression or a member of a set of candidate functions if selected by overload resolution when referred to from a potentiallyevaluated expression is odrused unless it is a pure virtual function and its name is not explicitly qualifiedi do however not understand how this rule works across multiple compilation units are all member functions instantiated if i explicitly instantiate a class template,['c++'] +567953,android get bluetooth uuid for this device i was browing stack and the internet for a simple solution to get the uuid of the device i am currently using i stumbled over posts like this but none of them seemed to help methe doc tells me about this getuuids function but when going through the doc for android bluetooth i end up having a bluetoothadapter but i need a bluetoothdevice to execute this functionso i need to know the following1 is the function returning really the device uuid because the name saids plural getuuids2 how do i get an instance of this bluetoothdevicethanks,['android'] +567995,binding combobox selecteditem using mvvm i have a problem with the selecteditem in my combobox combobox namecbxsalesperiods itemssourcebinding salesperiods thisplaymemberpaththisplayperiod selecteditembinding selectedsalesperiod selectedvaluepaththisplayperiod issynchronizedwithcurrentitemtrueif i open the combobox i see the valuesif i select an item the selected item would not be shownhas anybody an ideain my viewmodel i have these two propertiespublic observablecollectionsalesperiodvm salesperiods get private set private salesperiodvm selectedsalesperiodpublic salesperiodvm selectedsalesperiod get return selectedsalesperiod set if selectedsalesperiod value selectedsalesperiod value raisepropertychangedselectedsalesperiod these are a few properties from the class public salesperiodvo vo get return period public int year get return periodyear set if periodyear value periodyear value raisepropertychangedyear public int month get return periodmonth set if periodmonth value periodmonth value raisepropertychangedmonth public string thisplayperiod get return thistostring public override string tostring return stringformat0d21 month yeareditthe following happens if i remove the property thisplaymemberpath,['c#'] +568031,getting error when importing project in android studio recently i updated my android studio to 0 30 i was trying to import project in android studionproject is using an old version of the android gradle plugin the minimum supported version is 061please update the version of the dependency comandroidtoolsbuildgradle in your buildgradle filesconsult ide log for more details help show log2nd erroryou are using an old unsupported version of gradle please use version 18 or greater please point to a supported gradle version in the projects gradle settings or in the projects gradle wrapper if applicable consult ide log for more details help show log3rd error could not execute build using gradle thistribution build file cusersasthmecrushersblue1babiesbuildgradle line 8could not find method classpath for arguments comandroidtoolsbuildgradle06 on project crushersblue1babiesconsult ide log for more details help show log,['android'] +568070,how is this bracketlessbraceless code possibly valid so i came across this piece of codeinclude stdiohint mainint argc char argv printfc program succesfully running getchar return 0is this some compiler bug or is this something new i have not thiscovered yet because it is running without any problems,['c'] +568076,listview not refreshing alreadyvisible items i am thisplaying a list of contacts name picture using the listview in order to make the initial load fast i only load the names first and defer picture loading now whenever my background thread finishes loading a picture it schedules my adapters notifydatasetchanged to be called on the ui thread unfortunately when this happens the listview does not rerender ie call getview for the items that are already onscreen because of this the user does not see the newlyloaded picture unless they scroll away and back to the same set of items so that the views get recycled some relevant bits of codeprivate final maplong bitmap avatars new hashmaplong bitmap this is called on the ui thread by the background threadoverridepublic void onavatarloadedlong contactid bitmap avatar avatarsputrequestcode avatar notifydatasetchangedoverridepublic view getviewint position view convertview viewgroup parent snip final bitmap avatar avatarsgetcontactid if avatar null tagavatarsetimagebitmapavatar tagavatarsetvisibilityviewvisible tagdefaultavatarsetvisibilityviewgone else tagavatarsetvisibilityviewgone tagdefaultavatarsetvisibilityviewvisible if avatarscontainskeycontactid avatarsputcontactid null schedule the picture to be loaded avatarloaderaddcontactcontactid contactid afaict if you assume that notifydatasetchanged causes the onscreen items to be recreated my code is correct however it seems that is not true or maybe i am missing something how can i make this work smoothly,['android'] +568134,msdeploy automatic encryption of connection strings key not found in dictionary since web deploy 35 automatic encryption of connection strings is supported using the flag aenableruleencryptwebconfig however upon running it withcprogram filesiismicrosoft web deploy v3msdeployexe sourcepackagecmyappwebdeploypackagezip destautoincludeaclsfalse verbsync thisablelinkapoolextension thisablelinkcontentextension thisablelinkcertificateextension setparamfilecmyappsetparametersxml enableruleencryptwebconfig verbosei geterror code error failed to encrypt web configmore information failed to encrypt destination webconfig cwebconfig learn more at failed to encrypt web configerror the given key was not present in the dictionarythe learn morelink points to dated documentation and i cannot seem to find any info onlinei suspect the tool is using aspnet regiis behind the scenes but i am not sure yes i am running the above with full adminrights,['asp.net'] +568143,post variable array and filter input while using filter input i am not able to pull in a post array variable the post inputtype containeraction editdatathisplay 1dataquery limit 100i can access the data variable from the post superglobal correctly as an array but the filter input function returns nothingdata postdata working wootdata filter inputinput post data returns null should return arrayaction filter inputinput post action returns edit correctlyis it not possible to use filter input for a post array variable,['php'] +568145,drawing images to canvas returns invalidstateerror for every new image drawn then succeeds situationi have a gridlike unordered list with 144 90px x 90px images 12x12 that may be rotated my end goal is to take the 144 image grid and save it as 1 image current solutionmy current solution has me following these steps create a canvas that is one image width x 12 wide and one image height x 12 high this is to represent the end product imageloop through the list itemsimages extracting the image src from the item and drawing it onto its own canvas that is the size of the imagerotate the new small canvas however it is image has been rotated on the griddraw the new small canvas onto the endresult canvas at the x and y of the current pointerthings to noteas i loop through the images i keep track of a pointer where i am currently on the canvas i do this by maintaining a row and a col number they represent the current row and column of images i am drawing i use them multiplied by the width and height of a single image to get the exact x and y coordinates on the canvas to draw the next image current problemwhen i call the function to create draw and generate the base64 of the canvas i receive the following error message invalidstateerror an attempt was made to use an object that is not or is no longer usable if this error was occurring 100 of the time i would assume its because the image i am drawing to the canvas either is not loaded yet or is not being loaded at all but i only receive this error once for every new image i load for example if i have a 144 image grid that is 2 different images each drawn 72 times i will receive invalidstateerror twice and then the third time i call the function it will succeed current codeplease keep in mind this is simply spike code to test saving the image i am aware some refactoring is requiredgeneratethumbnail function var builder this canvas documentcreateelementcanvas content row 0 col 0 width is single image width 90 x number of tiles wide usually 12 canvaswidth 90 buildergrid0 height is single image height 90 x number of tiles high usually 12 canvasheight 90 buildergrid1 get 2d context of new canvas context canvasgetcontext2d loop through all of the images on the grid eachpatterngrid li functioni tile var tile tile image new image src tilefindimgattrsrc width height buffer bufferctx x y set crossorigin of image to anonymous as these images are loaded via cors imagecrossorigin anonymous increase row number by 1 if it has reached the end of the row and its not the first image being drawn ifi buildergrid0 0 i 0 row set column to 0 if it is a new row otherwise increase column by 1 unless it is the first image being drawn ifcol buildergrid01 col 0 else ifi 0 col determine if there was no image drawn at this location ifsrc undefined imagesrc src get the width and height the image to be used for the small canvas and where to draw it width imagewidth height imageheight create a new buffer canvas to draw the image to this will be used to apply any rotations that may exist buffer documentcreateelementcanvas set width and height of the buffer to the current images width and height bufferwidth width bufferheight height bufferctx buffergetcontext2d determine x and y coordinates to draw the small canvas using row and column numbers x colwidth y rowheight save current state of buffer canvas bufferctxsave translate and then rotate the buffer canvas by the images rotation bufferctxtranslatewidth2 height2 bufferctxrotatetilefindimgdatarotationmathpi180 bufferctxtranslatewidth21 height21 draw image to buffer canvas and restore its context bufferctxdrawimageimage 0 0 bufferctxrestore draw the buffer canvas to the main canvas at predetermined x and y contextdrawimagebuffer x y width height return canvastodataurl,['javascript'] +568183,cannot install debugger gem rails mac osx mavericks i am trying to run an app locally but when i do i get thrown this error patricksmacbookairniet pbj rails scould not find debugger161 in any of the sourcesrun bundle install to install missing gemswhen i run bundle install i get this fetching source index from enter your password to install the bundled rubygems to your system using rake 1010 using i18n 065 using minitest 475 using multi json 180 using atomic 13 using thread safe 013 using tzinfo 0337 using activesupport 400 using builder 314 using erubis 270 using rack 152 using racktest 062 using actionpack 400 using mimetypes 125 using polyglot 033 using treetop 1415 using mail 254 using actionmailer 400 using activemodel 400 using activerecorddeprecated finders 103 using arel 400 using activerecord 400 using addressable 235 using json 180 using mini portile 051 using nokogiri 160 using uuidtools 214 using awssdk 1 using bcryptruby 311 using coderay 109 using better errors 090 using debug inspector 002 using binding of caller 072 using sass 3210 using thor 0181 using bourbon 318 using callsite 0011 using cancan 1610 from at master using xpath 200 using capybara 210 using climate control 003 using cocaine 051 using columnize 036 using database cleaner 1 using debuggerlinecache 120 using debuggerruby core source 123 installing debugger 161 geminstallerextensionbuilderror error failed to build gem native extension systemlibraryframeworksrubyframeworkversions20usrbinruby extconfrb checking for rb method entry tcalled id in methodh nochecking for rb control frame tmethod id in methodh nochecking for rb method entry tcalled id in methodh nochecking for rb control frame tmethod id in methodh nochecking for rb method entry tcalled id in methodh yeschecking for vm coreh yeschecking for iseqh nomakefile creation failed note if your headers were not found try passing withrubyincludepath to headers extconfrb failed could not create makefile due to some reason probably lack of necessarylibraries andor headers check the mkmflog file for more details you mayneed configuration optionsprovided configuration options withoptdir withoutoptdir withoptinclude withoutoptincludeoptdirinclude withoptlib withoutoptliboptdirlib withmakeprog withoutmakeprog srcdir curdir rubysystemlibraryframeworksrubyframeworkversions20usrbinruby withrubydir withoutrubydir withrubyinclude withoutrubyincluderubydirinclude withrubylib withoutrubylibrubydirgem files will remain installed in userspbjbundlertmp39109gemsdebugger161 for inspectionresults logged to userspbjbundlertmp39109gemsdebugger161extruby debuggem makeoutan error occurred while installing debugger 161 and bundler cannotcontinuemake sure that gem install debugger v 161 succeeds before bundlingafter that i try and install the debugger gem and get this errorbuilding native extensions this could take a whileerror error installing debugger error failed to build gem native extension systemlibraryframeworksrubyframeworkversions20usrbinruby extconfrbchecking for rb method entry tcalled id in methodh nochecking for rb control frame tmethod id in methodh nochecking for rb method entry tcalled id in methodh nochecking for rb control frame tmethod id in methodh nochecking for rb method entry tcalled id in methodh yeschecking for vm coreh yeschecking for iseqh nomakefile creation failed note if your headers were not found try passing withrubyincludepath to headers extconfrb failed could not create makefile due to some reason probably lack of necessarylibraries andor headers check the mkmflog file for more details you mayneed configuration optionsprovided configuration options withoptdir withoutoptdir withoptinclude withoutoptincludeoptdirinclude withoptlib withoutoptliboptdirlib withmakeprog withoutmakeprog srcdir curdir rubysystemlibraryframeworksrubyframeworkversions20usrbinruby withrubydir withoutrubydir withrubyinclude withoutrubyincluderubydirinclude withrubylib withoutrubylibrubydirgem files will remain installed in libraryrubygems200gemsdebugger162 for inspectionresults logged to libraryrubygems200gemsdebugger162extruby debuggem makeoutat this point i have absolutely no clue how to resolve the issue,"['ruby-on-rails', 'ruby']" +568220,use as a button and trigger a mailto when it is clicked i am creating a custom button on my webpage which actually is a div i want to trigger a mailto when the button is clicked what is the best way outi have tried calling a javascript function usingonclick that looks like this function foo windowopenmailtobut that opens a new tab in chrome first and then asks for the relevant app to send out the email this experience is different from what we generally get when we simply do a a hrefmailto in htmli can also create a new document element in the js function and simulate a click like this function sendemail var mail mailto var a documentcreateelementa ahref mail aclickbut i am not too sure if that is the right way anyone has a better solution,"['javascript', 'html']" +568271,using strdup in c11 i am able to compile the following using gcc version 472 include stringh int main char text string duplicate char dup strduptext return 0 but when i used the stdc11 flag i get the following warningwarning implicit declaration of function astrdupa wimplicitfunctiondeclarationwarning initialization makes pointer from integer without a cast enabled by defaultwhat changed to cause this warning,['c'] +568297,robust parsing of integers in c i am trying to write a helper function that can be used for parsing integers from config files and from a textbased protocol written by machine not by a human i have read how to parse a string to an int in c but the solutions there do not address all the issues i would like something that will from most to least importantreject outofrange values strtoul and strtoull do not quite achieve this given a leading minus sign the value is negated in the return type so 5 is happily parsed and returns 4294967291 or 18446744073709551611 instead of signalling an errorbe in the c locale regardless of the global locale setting or even better give me a choice unless there is a way to set the global locale on a perthread basis that rules out strtoul stoul and boostlexical cast and leaves only istringstream where one can imbue a localebe reasonably strict it definitely must not accept trailing garbage and ideally i would like to ban white space as well that immediately makes strtol and anything based on it a little problematic it seems that istringstream can work here using noskipws and checking for eof although that might just be a gcc bugideally give some control whether the base should be assumed to be 10 or should be inferred from a 0 or 0x prefixany ideas on a solution is there an easy way to wrap the existing parsing machinery to meet these requirements or is it going to end up being less work to write the parser myself,['c++'] +568313,how to thisable resizing of a usercontrol in wpf how tothisable resizing for this usercontrol in other words when the user grabs the corners or the sides of this usercontrol with a mouse i dont want the user to be able to change the size of the usercontrolor if there is no way to stop resizing then how do i only allow the right side of the usercontrol dragged usercontrol xclassmyeditormydialog xmlns xmlnsx xmlnsmc xmlnsd mcignorabled ddesignheight152 ddesignwidth590 horizontalcontentalignmentright minwidthbinding elementnamevariabletype minheightbinding relativesourcerelativesource selfgrid width591 height147 minwidthbinding elementnamevariabletypetextbox gridcolumndefinitions columndefinition width137 columndefinition width454 minwidth250 gridcolumndefinitions button contentcancel height23 margin09470 namecancelbutton verticalalignmenttop clickcancelbutton click gridcolumn1 horizontalalignmentright width75 horizontalcontentalignmentcenter verticalcontentalignmenttop button contentcreate height23 margin0941080 namecreatebutton verticalalignmenttop clickcreatebutton click gridcolumn1 horizontalalignmentright width75 horizontalcontentalignmentcenter verticalcontentalignmenttop label contentvariable name height28 margin012290 namevariablename verticalalignmenttop horizontalalignmentright width96 targetbinding horizontalcontentalignmentright textbox height29 margin01170 namevarnametextbox verticalalignmenttop keydownonkeydownhandler mouseleavemouseleavehandler lostfocuslostfocushandler gridcolumn1 horizontalalignmentstretch label contentvariable type height28 margin002973 namevariabletype verticalalignmentbottom horizontalcontentalignmentright horizontalalignmentright width96 textbox height23 margin05170 namevariabletypetextbox verticalalignmenttop isreadonlytrue backgroundsilver foregroundblack gridcolumn1 horizontalalignmentstretch widthauto grid,['c#'] +568356,playn no sound on android i am having a problem playing sounds on android i have added the following code to my projectimport playncoresoundoverridepublic void init sound bg assetsgetsoundbg bgplay the code works as intended when i run mvn test pjava the sound plays without a problem however when i run mvn pandroid install the sound does not play i do not get any errors in logcat or anything the game is just silenti have triedusing different sound formats wav mp3loading a sound file that is not in the assets folder in this case i get an error notifying me that the sound file was not found but i get no such error when loading an actual sound fileusing different mvn versionsmade sure the device is not set to silentusing multiple devices nexus 7 older android phonereproducing this issue in the showcase example it is the same as in my projectupgrading playn from 17 to 172 no changei have found that running mvn install instead of mvn test pjava loads up the desktop version without sound as well this makes me think there might be an issue with the install command but i am just guessing hereany ideas on how to make sound work on android,['android'] +568364,numba autojit error on comparing numpy arrays when i compare two numpy arrays inside my function i get an error saying only length1 arrays can be converted to python scalarsfrom numpyrandom import randfrom numba import autojitautojitdef myfun a rand101 b rand101 idx a b return idxmyfunthe errortypeerror traceback most recent call lastipythoninput7f7b68c0872a3 in module 1 myfunusersguestlibraryenthoughtcanopy 64bituserlibpython27sitepackagesnumbanumbawrapperso in numbanumbawrapper numbaspecializingwrapper call numbanumbawrapperc3764typeerror only length1 arrays can be converted to python scalars,['python'] +568439,how to preserve white spaces in content editable div i am using the content editable div as a field to fetch user inputs in my websitebut my problem is that when i get the contents of the div using jquery all the white spaces are lost which are entered by the user in the div so i want to know is there any way to preserve all the white spaces for content editable div thanks,"['javascript', 'jquery', 'html', 'css']" +568467,java best way to print 2d array i was wondering what the best way of printing a 2d array was this is some code that i have and i was just wondering if this is good practice or not also correct me in any other mistakes i made in this code if you find any thanksint rows 5int columns 3int array new introwscolumnsforint i 0 irows i forint j 0 jcolumns j arrayij 0forint i 0 irows i forint j 0 jcolumns j systemoutprintarrayij systemoutprintln,['java'] +568476,asyncawait threadpool and setapartmentstate i would like to use await taskrundowork to do some repetitive singlethreaded computational work on threadpool the problem is i need to use sta com objects inside dowork so i guess i cannot use threadpool because i cannot alter the apartment state of a pool thread how can i still use asyncawait in this scenario creating my own pool of sta threads with a custom task scheduler sounds like an excessive work,"['c#', '.net']" +568479,project structure for php i am new to php and want to know the directory structure for the php projects i have experience in java and in java we have src contains java source files webinf contains lib and jsp pages do we have any similar standard directory structure in phpalso do we have layering in php like we have layers in java eg web service dao layersi browsed few links but every one giving different answersnot sure if we can compare the two languages i just want to stick to some standardsthanks in advance,['php'] +568494,django can you tell if a related field has been prefetched without fetching it i was wondering if there is a way in django to tell if a related field specifically the many part of a onetomany relationship has been fetched via say prefetch related without actually fetching itso as an example let us say i have these modelsclass questionmodel class that represents a questionclass answermodel class the represents an answer to a question question foreignkeyquestion related nameanswersnormally to get the number of answers for a question the most efficient way to get this would be to do the following because the django docs state that count is more efficient if you just need a count note question is an instance of class questionanswer count questionanswerscounthowever in some cases the answers may have been fetched via a prefetch related call or some way such as previously having iterated through the answers so in situations like that it would be more efficient to do this because wed skip the extra count query answers were fetched via prefetch relatedanswer count lenquestionanswersallso what i really want to do is something likeif questionanswers have been prefetched does this exist answer count lenquestionanswersallelse answer count questionanswerscounti am using django 14 if it matters thanks in advanceedit added clarification that prefetch related is not the only way the answers could have been fetched,['python'] +568500,constraint generic type for enum type to implement some interface i have enum that implement myinterfacewhile making other class using that enum i want to constrain the enumclz to be class that has implemented myinterfaceso i describe signature to be t extends enum t extends myinterface at generic type declarationpublic t extends enum t extends myinterface c1 classt enumclz for t anenumconst enumclzgetenumconstants process what surprised me is the ide say it is unexpected bound at t extends myinterfacei do not know what it means by such two word error message any solution about thisand by the way out of curious i have an odd question though not really important can an enum type t be equivalent to the following infinite loopt extends enum t extends enumt extends,['java'] +568516,magento get product collection filter by store id both stores have a different root category main store is the default sample data second store has just one product i was added i would have thought that using the store filter only products within the root category of the current store would show up but i am getting every product showing i am testing this by placing the following in my category view templatestore id mageappgetstoregetid testproductcollection magegetresourcemodelreportsproduct collectionsetstoreidstoreidaddstorefilterstore idaddattributetoselect testproductcollectionloadforeach testproductcollection as testproduct echo thishtmlescape testproductgetname if i print the store id it is giving me the correct number i have only one product in second store so why am i getting every product from all stores returned i can set every product in main store to not show in store2 and then add a visibility filter but that would take foreveralso i just noticed if i echo the products store id i get the current id not the store it is assigned toecho testproductgetstoreidhow to solve this issue,['php'] +568558,how to get wifi signal strength using qt so far i am able to scan all the available wifi using qnetworkconfigurationmanagerallconfigurations but the qnetworkconfiguration data for each of them does not have the wifi signal strength can you point me into how to get this data thanks,['c++'] +568680,how can i optimize active admin last time i got the problem with active admin in tables where i have 50 rows of data it is work very slowly how i can optimize it maybe somebody know some async load plugins for this module,"['ruby-on-rails', 'ruby']" +568725,slidetoggle can detect slideup or slidedown i know hover has default setting for handin and handout but is there anyway i could detect slideup and slidedown inside slidetogglehave code like thisdivnameslidetogglefunctionwhen slideup do something functionwhen slidedown do somethingi tried this code but no luck do you guys think this may sometimes make things a bit easier,['jquery'] +568737,new if element default constructor can throw consider the following codeexample t a new example t8class example t has default ctor that can throw suppose construction of 5th element in array throws is there automatic call to destructor of the 4 first elements is it a well defined behavior,['c++'] +568753,how can i use one storyboard for 4 and 35 iphone screens with autolayout ios6 ios7 while there are many questions and answers about building a storyboard layout that would work both on 4 and 35 screen sizes i could not find a suitable solution for the following scenarioi use autolayout with ios6 and ios7 and i do not have to support landscpae or ipad i have a uiview with several subviews which have to look as the mockup below it is easy to set up autolayout constraints in the storyboard to fit either of the screen sizes my question is how do i make autolayout choose the correct constraints depending on the screen size at runtimenote that i dont want to use 2 different storyboards doing so across my whole application would be a lot of work and i would have to hook up all the delegates outlets and actions on each storyboard a change in a screen would require me to do double the worki have tried 2 methods to make this work on one storyboard but i am not satisfied with either of themdouble the constraints the larger constraint 50 has a higher priority than the lower constraint 30 the problem with this approach is that on the 35 screen size autolayout may pick a just few lower priority constraints enough to satisfy the layout but leave some high priority constraints subclass nslayoutconstraint in this method all the constraints in the storyboard are set to be nsduallayoutconstraint in in initialization code of nsduallayoutconstraint the constant of the constraint is changed to the value of 3 5 constant in case the runtime screen size is 35 this method is more deterministic but you cannot see the 35 layout in the interface builder preview if only interface builder constraints had a secondary constant value that would be applied when the screen size is 35 it would solve my problem so i remain with my question how can i properly use a single storyboard to layout its subviews correctly for 4 and 35 screen sizes,"['ios', 'iphone']" +568816,what are the differences between strong and strong weak and weak i am a noob in ios programming please explain me the meaning for these strong and weak properties and why they are used,"['ios', 'iphone']" +568846,minify css and js in codeigniter efficiently so i am working on a project using the php framework codeigniter and inside of it we are using a lot of various cssjs files that are being called in our header include i have used the minify tool before on wordpress sites and other projects and ran across this library for codeigniter on github and figured i would use it on my project it works all fine and dandy but unfortunately i am compressing so many css and js files that by the time the page loads it would have been quicker if i had not used it heres what the code looks like in my controller minify css cssfiles arrayassetscssnormalizecss assetscsshooknewcss assetscsshookcss assetscsscomponentscss assetscssrtlcss assetscssglobalcss assetscssbodycss assetscssmediaqueriescss assetsselect2343select2css assetsjquery bootstrapcsscustomthemejqueryui192customcss cssfile thisminifycombine filescssfiles csscontents thisminifycssmincssfile thisminifysave filecsscontents assetscssallcss minify js jsfiles arrayassetsjsapplicationjs configjs assetsjsbootstrapminjs assetsjscustomjs assetsselect2343select2js assetsjsstartupjs assetsckeditorckeditorjs assetsjsjqueryvalidationengineenjs assetsjsjqueryvalidationenginejs assetsjsscriptsjs assetsjsapplicationjs timerjs jsfile thisminifycombine filesjsfiles jscontents thisminifyjsminjsfile thisminifysave filejscontents assetsjsalljsso i am taking these large arrays of css and js files compressing them then saving them to one large file but is there a better and more efficient way of doing this i know i could combine them by hand but then when i am working on things i have massive files to sift through not only that but i like minifys ability to get rid of unnecessary white space and really condense the code so any thoughts on how i can efficiently accomplish this thanks,"['javascript', 'php', 'css']" +568913,syntax for specialization of nested template class i am trying to figure out the correct syntax for explicit specialization of a nested template class the following code will better illustratestruct column majorstruct row majortemplatesize t rows size t cols typename t typename allocatorclass matrix bunch of members template typename storage column major class iterator bunch of members i would like to write an explicit specialization for template class matrixiteratorrow major but the syntax is eluding me i have a suspicion that it is not possible to explicitly specialize the iterator class without an explicit specialization of the containing class matrix but i would be very happy if there is a way to do thisi know i could make the iterator class a separate class not a member of the matrix class but having the classes nested as such allows me full access to the template parameters and datamebers of the matrix class which simplifies things i know i could work around this if i need to but i would first like to investigate and understand the possibilities for the nested approachthanksshmuel,['c++'] +568961,using empty tuple as default iterable argument in function are there any downsides to using an empty tuple as a default for an iterable argument to a function assuming that what you want in the function is an immutable iterableegdef fooa b print a for x in b print xi cannot seem to find many examples of this use case,['python'] +568976,jaxb element that is both optional and nillable i have reformatted the question to hopefully make my intentions clearerarchitecturei am writing some web services that i will be publishing myself using jaxws the process we have been using for some time is to first write a schema that only defines the request and response objects this gets sent to the customer to approve the structure of the xml messages i do not want to write the whole wsdl myself as it is more complicated than the basic schemanext i use the jaxb command xjc to generate classes based on the request and response types in my schema i then use this classes as parameters and return types on a jaxws annotated endpoint classthis now gives me a web service i can call it gives me more control over the xml being sent and returned but also automates the repetition required in writing the full wsdlproblemin the schema i have an element like thisxselement namemyelement typexsstring nillabletrue minoccurs0 so i want to thistinguish between the user setting null or blank the generated class then has this attributexmlelementrefname myelement namespace mynamespace type jaxbelementclassprotected jaxbelementstring myelementthe effect of this is that the element becomes neither nillable or optional the schema that jaxws writes as part of the wsdl has set the element to mandatory and not nillable and if i turn off schema validation i still cannot pass nil through to my object things triedif i change it to be required and nillable then i get this generated codexmlelementrequired true nillable trueprotected string myelementif i change it to optional and not nillable then i get this generated codeprotected string myelementso you can have either or but not both it seems if you use jaxb thoroughly thisappointingi have also tried manually changing the generated class to look like thisxmlelementrefname myelement namespace mynamespace type jaxbelementclass requiredfalseprotected jaxbelementstring myelementthis now makes the element optional but i still cannot set it to nil doing so results in a jaxbelement with a value of a blank string that is only if you turn schema validation off as the resulting jaxws wsdlschema does not set the element as nillable so its not a valid requestsummaryit is my belief that this is a bug with jaxb the xmlelementref annotation has an attribute to set it as not required but there is no attribute to set the field as nullable the xmlelement annotation has attributes for both required and nullable but these just result in a null object so there would be no way to thistinguish between an element not included in the xml or an element that was included but null this is why you need to use xmlelementref along with jaxbelementi think the bug includes two issues first the xjc command should generate the element with requiredfalse second there should be an attribute on xmlelementref to set whether the element is nullable and this should be set toodoes anyone know of a fixworkaround i tried googling but only found people asking the same question without an answer this usually means it is not possible tiaadditionali am using jaxb 226 and the maven plugin is jaxb2mavenplugin 15,['java'] +569014,html5 canvas 100 height and width i am trying to make this raindrop canvas script take up 100 width and height but nothing i seem to do works i tried changing the css and heightwidth in the canvas area but it either does not change anything or it makes it not work at all the one time i tried something that actually made it full size it seemed to have a weird effect on the raindrops they became all blurry and much larger so it must have actually stretched the canvas instead of making it larger heres the code for the default 800x800 pixel canvas stylestyle article aside figure footer header hgroup menu nav section thisplay block stylescript for canvasscript typetextjavascriptvar canvas nullvar context nullvar buffercanvas nullvar buffercanvasctx nullvar flakearray var flaketimer nullvar maxflakes 200 here you may set max flackes to be created function init canvas documentgetelementbyidcanvasrain context canvasgetcontext2d buffercanvas documentcreateelementcanvas buffercanvasctx buffercanvasgetcontext2d buffercanvasctxcanvaswidth contextcanvaswidth buffercanvasctxcanvasheight contextcanvasheight flaketimer setintervaladdflake 200 draw setintervalanimate 30function animate update drawfunction addflake flakearrayflakearraylength new flake if flakearraylength maxflakes clearintervalflaketimerfunction blank buffercanvasctxfillstyle rgba08 buffercanvasctxfillrect0 0 buffercanvasctxcanvaswidth buffercanvasctxcanvasheightfunction update for var i 0 i flakearraylength i if flakearrayiy contextcanvasheight flakearrayiy flakearrayispeed if flakearrayiy contextcanvasheight flakearrayiy 5 flakearrayix flakearrayidrift if flakearrayix contextcanvaswidth flakearrayix 0 function flake thisx mathroundmathrandom contextcanvaswidth thisy 10 thisdrift mathrandom thisspeed mathroundmathrandom 5 1 thiswidth mathrandom 3 2 thisheight thiswidthfunction draw contextsave blank for var i 0 i flakearraylength i buffercanvasctxfillstyle white buffercanvasctxfillrectflakearrayix flakearrayiy flakearrayiwidth flakearrayiheight contextdrawimagebuffercanvas 0 0 buffercanvaswidth buffercanvasheight contextrestorescriptand finally heres the bodybody onloadinit canvas idcanvasrain width800px height800pxcanvas not supportedcanvasbody,"['javascript', 'html', 'css']" +569016,cannot find file afjsonrequestoperationh with afnetworking and afoauth2client i am using cocoapods to install afnetworking and afoauth2client the issue is that it cannot import a header file afjsonrequestoperation i have no idea where this dependency lies is it another pod or extension to afnetworking,['objective-c'] +569044,how to use selenium to check for memory leaks in javascript app i am using java selenium for automated testing of a javascript webapp one question that has come up is memory leaks and how to test for them since i am already using selenium for testing the app is there an easy way to get the memory usage and other profiling information for the web app leveraging selenium orand other automated webjs testing toolscurrently i am using chromedriver but will be extending to use the firefox and ie drivers in the future,['javascript'] +569045,ssdt sql server debugging does not hit clr breakpoints i applied the sql server data tools patch to visual studio 2012 premium and created a sql server clr userdefined function project in cpublic partial class userdefinedfunctions microsoftsqlserverserversqlfunction public static sqlint32 add42sqlint32 in param sqlint32 retval in param 42 set break point here return retval in the sql server object explorer pane i rightclick on the newly published udf and select execute function i am prompted to supply a sample input value and visual studio then publishes the function again to my local 2012 sql server and generates a script that looks like thisdeclare return value intexec return value dboadd42 in param 5select return value as return valuego and executes it returning the expected result of 47if i now put a break point on an executable line in my clr udf c code rightclick the udf function in sql server object explorer and this time select debug function i land in a debugger for the generated sql test script i can step through the sql statements to the end of the script which returns the correct result but the breakpoint in my c code is never reached in the c debuggerthe terminology for this feature seems misleading to any programmer debugging a function means stepping through the executable lines in the code of the function itself simply generating a sql test harness that calls my compiled function and gets back the result is just testing the function at most the only thing being debugged is the toolgenerated test itself because you cannot step into the clr code the only option is to step over itso how do i get visual studio to actually debug and hit the breakpoint in my udf c code,['c#'] +569064,passing session variable from page to page i am wondering what is my issue on passing a variable from page to page using aspnet sessioni have stripped the code down to just one text box to see whats going on i am just trying to take the value of a text box and thisplay it on a confirmation page when the button is clicked it transfers me to the second page but there label is blank yes my post back url is pointing to the second pagehere is the button clickprotected void submit clickobject sender eventargs e string name txtfirstnametexttrim sessionname namehere is the page load of the second pageprotected void page loadobject sender eventargs e lblnametext stringsessionnameunless i have been looking at this to long and missed something i have already read how to read values from session state from msdn,"['c#', 'asp.net']" +569087,python multiprocessing is taking much longer than single processing i am performing some large computations on 3 different numpy 2d arrays sequentially the arrays are huge 250x250 each each computation takes significant time so i decided to run 3 of them in parallel on 3 cpu cores on the server i am following standard multiprocessing guideline and creating 2 processes and a worker function two computations are running through the 2 processes and the third one is running locally without separate process i am passing the huge arrays as arguments of the processes like p1 processtarget worker args queue1 array1 some other params also goingp2 processtarget worker args queue2 array2 some other params also goingthe worker function sends back two numpy vectors 1d array in a list appended in the queue likequeueputv1 v2i am not using multiprocessingpoolbut surprisingly i am not getting speedup it is actually running 3 times slower is passing large arrays taking time i am unable to figure out what is going on should i use shared memory objects instead of passing arraysi shall be thankful if anybody can helpthank you,['python'] +569098,android is it a good idea to store authentication token in shared preferences i have an application that communicates with a server when the user logins to the application an authentication token is crated on the server and stored in the sharedpreferences of the application and whenever the application requests data from a web service the authentication token is validatedmy question is is it secure to store the authentication token in the sharedpreferences i am asking because a user with root privileges can access the preferences extract the token and use itis there anyway to have more security in that regard,['android'] +569099,bundling data files with pyinstaller 21 and meipass error onefile this question has been asked before and i cannot seem to get my pyinstaller to work correctly i have invoked the following code in my mainscriptpy filedef resource pathrelative path get absolute path to resource works for dev and for pyinstaller try pyinstaller creates a temp folder and stores path in meipass base path sys meipass except exception base path ospathabspath return ospathjoinbase path relative pathwhen i run the py file within idle my app runs perfectly and loads all of the data files however when i bundle it with pyinstaller 21 one file method i get the following error after the exe buildstraceback most recent call lastfile string line 37 in modulewindowserror error 3 the system cannot find the path specified cusersmeappdatalocaltemp mei188722eggsdoes anyone have any idea where i went wrong thanks edit here is exactly what i want to do my main script has a setup imports that look like below essentially i want to be able to have matplotlib basemap and resource path all in itimport ossysimport matplotlibmatplotlibusewximport wxfrom matplotlibbackendsbackend wx import figurecanvaswx as figurecanvasfrom matplotlibbackendsbackend wx import navigationtoolbar2wxfrom mpl toolkitsbasemap import basemapfrom matplotlibfigure import figureimport matplotlibpyplot as pltimport calculate thistance a personal py file of minedef resource pathrelative path get absolute path to resource works for dev and for pyinstaller try pyinstaller creates a temp folder and stores path in meipass base path sys meipass except exception base path ospathabspath return ospathjoinbase path relative pathbmapwxbitmapresource pathtest imagepngprint helloi am using pyinstaller 21 i am also using python 275 32 bit my os is windows 8 64bit my matplotlib is 130 and basemap is 106 wxpython is 28121 unicode i go to command and do pyinstaller myscriptpy this generates my spec file which i slightly edit below is my edited spec filedata files calculate thistancepy cusersmedocumentsmyfoldercalculate thistancepy data test imagepng cusersmedocumentsmyfoldertest imagepng dataincludes excludes gtkagg tkagg bsddb curses email pywindebugger pywindebuggerdbgcon pywindialogs tcl tkconstants tkinterpackages dll excludes dll includes a analysismyscriptpy pathexcusersmedocumentsmyfoldercpython27libsitepackagesmpl toolkitsbasemap hiddenimports hookspathnone runtime hooksnonepyz pyzapureexe exepyz ascripts abinaries dll excludes dll includes data files namemyapplicationexe debugfalse stripnone upxtrue consoletrue coll collectexe abinaries azipfiles adatas stripnone upxtrue namemyapplication i want this to be a onefile executable so the data files should be packed within the executable on other pyinstallers i usually have not had issues with the meipass however i need to use 21 because of matplotlib and basemap if someone can build this exe perfectly can you please tell me what i need to adjust thankseditif anyone can figure out how to do this with py2exe that would be great too any way that i can get this into a single executable would be worth it,['python'] +569152,documentready fires immediately for windowopen context i am trying to perform operations on the dom of a popup window but for some reason the ready event fires immediately for the popup before there is anything in the domi know that jquery can access the dom of the popup window by using context and that i can manage to do it by using settimeout to delay any action until a reasonable amount of time has passedfunction function var popup windowopentest jsfiddle 404 page popupdocumentreadyfunction should fire when the dom of the 404 page has loaded h2 popupdocumentcsscolor ff0 change the color of the header to red consolelogh2 popupdocumentlength should log 1 logs 0 though because this function fires immediately before the dom loads settimeoutproxyfunction this will definitely fire after the dom of the 404 page is loaded var popup this h2 popupdocumentcsstextdecoration underline this works because it waited long enough but i do not want to guess how long it will take the dom to load popup 50 after 5 seconds jqueryalso i know it is not jquerys fault if i add consolelogpopupdocumentreadystate immediately after var popup windowopentest it prints complete why thoughany advicethanks,"['javascript', 'jquery']" +569165,android plotting gps coordinate on custom map i have an activity in my app where there are images i use as maps if the image is grid aligned to google maps then when i use the top left and bottom right corners of the map i get from googlemaps online then i can turn the users gps into an x and y on screen however if the map is not grid aligned and is at an angle than the values my math returns draws the users position off screen obviously i am missing the part on how to handle the angle of the map so if anyone could shed some light on how to do that it would be super helpfulli know i would have to figure out the angle in radians and do some conversion but i have no idea where to start this is what i use to get an x and y to plot on a canvas so farpublic double getpositiongpslocation upperleft location lowerright location current try double hypotenuse upperleftthistancetocurrent double bearing upperleftbearingtocurrent double currentthistancey mathcosbearing mathpi oneeightydeg hypotenuse percentage to mark the position double totalhypotenuse upperleftthistancetolowerright double totalthistancey totalhypotenuse mathcosupperleftbearingtolowerright mathpi oneeightydeg double currentpixely currentthistancey totalthistancey imagesizeh double hypotenuse2 upperleftthistancetocurrent double bearing2 upperleftbearingtocurrent double currentthistancex mathsinbearing2 mathpi oneeightydeg hypotenuse2 percentage to mark the position double totalhypotenuse2 upperleftthistancetolowerright double totalthistancex totalhypotenuse2 mathsinupperleftbearingtolowerright mathpi oneeightydeg double currentpixelx currentthistancex totalthistancex imagesizew return new doublecurrentpixelx currentpixely catchexception e eprintstacktrace return new double00,['android'] +569200,how to write a cell with multiple columns in xlwt i would like to write a table like this long cell 1 2 how to write the cell long cell thanksi have tried to do it like thissheetwrite0 0 long cellsheetwrite1 0 1sheetwrite1 1 2but it end up like long cell 1 2,['python'] +569207,can you set conditional dependencies for python 2 and 3 in setuptools when releasing a python egg with support for both python 2 and 3 can you specify dependencies that change depending on which version youre using for example if you use dnspython for python 2 there is a python 3 version that is called dnspython3 can you write your setuptoolssetup function in such a way that your egg is useable to both versions if that is the only roadblock ie if you have run 2to3 to ensure that the rest of your library is compatible with both versionsi have looked through these documents and cannot seem to find the answer this questionporting python 2 code to python 3setuptools declaring dependenciestravis ci python documentationpip requirements files,['python'] +569220,xmlhttprequest same origin policy i spent the last 3 days studying how to make a cross domain request using xmlhttprequest the best alternative is indeed with jsonp which i am already usingbut i still have a question that i could not find answer nowhere i read hundreds of posts including sos and nobody has a good liable answer with nice reference hope someone here can helpsaid that i read in many websites that due to security reasons i cannot make an ajax request from domain acom to bcom and get the data i want it is very clear and i have no question about that but the problem is when i run the code below in my localhost so my domain is localhost and i should not me able to request any data from another domainxhreq new xmlhttprequestxhreqopengettruexhreqsendnullwhen i inspect the firebug net tab i realize that the request was not blocked it was clearly requested i could not believe so i created a file in the domaincomlogphp where i could log any request that hit my domain surprisingly all the requests i was firing localhost were hitting my domaincom when i tried to fetch the response i really could not get it due the same origin policy of my chrome and firebug browser but i was reallyl surprised that the request really hit the webserver despite i could no manipulate the respondemore surprisingly is that if domaincomlogphp generates a huge responde with like 1mb my firebug showed me that the browser does download all th 1mb from the webserver and at the end it shows a message access denied as expected so why download all the file if the same origin policy forbids that data to be readfinally i makes me amazed is that all the websites and specifications i read says very clear that the request is blocked using ajax when the target domain does not match the source domain but clearly with my experiment the requests are being completed despite i cannot have access to the response datawhat makes me upset is that it could be open a big security hole in which a website with thousands of views everyday could run this 3 line code and cause a huge ddos attack in an unfriendly website just making the users request a page in another website in small intervals since the browser will not block the requesti tested this script in ie 7 8 and 9 and chrome latest and firefox latest and the behaviour is the same the request is done and the browser downloads all the response while not making it avaiblable to do sophope someone can explain me why the specs are so wrong about it or what i am understanding wrong,['javascript'] +569250,execute jquery function after another function completes i want to execute a custom jquery function after another custom function completesthe first function is used for creating a typewriting effect function typer var srctext example var i 0 var result srctexti setintervalfunction ifi srctextlength clearintervalthis return i result srctextireplacen br messagehtml result 100and the second function plays a soundfunction playbgm documentgetelementbyidbgmplayi am calling the functions one after the another liketyperplaybgmbut the sound starts playing as the text is getting typedi want to play the sound only after the typewriting has finishedhere is what i have tried how can i fix this,['jquery'] +569254,cocoapods no such file to load error i am trying to add a pod to my xcode project i am getting this errorloaderror no such file to load xcodeprojprebuiltuniversaldarwin130187xcodeproj ext libraryrubysite18rubygemscore extkernel requirerb55in gem original require libraryrubysite18rubygemscore extkernel requirerb55inrequire libraryrubygems18gemsxcodeproj0140libxcodeprojextrb6 libraryrubysite18rubygemscore extkernel requirerb55in gem original require libraryrubysite18rubygemscore extkernel requirerb55inrequire libraryrubygems18gemsxcodeproj0140libxcodeprojprojectrb4 libraryrubygems18gemscocoapods0271libcocoapodsinstalleranalyzerrb488in compute target platforms libraryrubygems18gemscocoapods0271libcocoapodsinstalleranalyzerrb485ineach libraryrubygems18gemscocoapods0271libcocoapodsinstalleranalyzerrb485in compute target platforms libraryrubygems18gemscocoapods0271libcocoapodsinstalleranalyzerrb55inanalyze libraryrubygems18gemscocoapods0271libcocoapodsinstallerrb171in analyze libraryrubygems18gemscocoapods0271libcocoapodsinstallerrb94inresolve dependencies libraryrubygems18gemscocoapods0271libcocoapodsuser interfacerb52in section libraryrubygems18gemscocoapods0271libcocoapodsinstallerrb93inresolve dependencies libraryrubygems18gemscocoapods0271libcocoapodsinstallerrb86in install libraryrubygems18gemscocoapods0271libcocoapodscommandprojectrb38inrun install with update libraryrubygems18gemscocoapods0271libcocoapodscommandprojectrb68in run libraryrubygems18gemsclaide032libclaidecommandrb206inrun libraryrubygems18gemscocoapods0271libcocoapodscommandrb51in run libraryrubygems18gemscocoapods0271binpod19 usrbinpod23inload usrbinpod23my podfile contentspod restkit 0210any help would be appreciated,"['ios', 'iphone']" +569302,unexpected difference in dates parsed using ymmdd hhmmss format i have run the below java code to get time difference import javatextsimpledateformatimport javautilcalendarimport javautildateimport javautiltimezonepublic class test public static simpledateformat simpledateformat new simpledateformatymmdd hhmmss public static date date1date2 public static long diff public static string tag dateconversion public static calendar cal1cal2 public static void mainstring a checktimedifference20131030 101500 20131030 1500 checktimedifference20131030 101500 20131030 121500 checktimedifference20131030 101500 20131030 131500 public static void checktimedifferencestring strdatestring checkdate try simpledateformatsettimezonetimezonegettimezonegmt date1 simpledateformatparsestrdate date2 simpledateformatparsecheckdate in milliseconds diff date2gettime date1gettime systemoutprintlndifference diff long diffseconds diff 10 60 long diffminutes diff 60 10 60 long diffhours diff 60 60 10 24 long diffdays diff 24 60 60 10 systemoutprintlndiffdays days systemoutprintlndiffhours hours systemoutprintlndiffminutes minutes systemoutprintlndiffseconds seconds catch exception e systemoutprintlne the output of above program isdifference 360 days 1 hours 0 minutes 0 secondsdifference 360 days 10 hours 0 minutes 0 secondsdifference 1080 days 3 hours 0 minutes 0 secondsits return minus value when executing checktimedifference20131030 101500 20131030 121500why its return minus value and how to solve it,['java'] +569356,get exception when showing alert dialog from service unable to add window token null is not for an application get exception when showing alert dialog from servicefollowing is the code in my service class i am trying to show an alertdialogbut i get the error unable to add window token null is not for an applicationi am also attaching snapshot of my log to this question ifmlocationmanagerisproviderenabledlocationmanagergps provider mlocationmanagerisproviderenabledlocationmanagernetwork provider logdtrackingserviceh exception after this alertdialogbuilder builder new alertdialogbuilderthis buildersetmessageyour gps seems to be thisabled do you want to enable it setcancelablefalse setpositivebuttonyes new dialoginterfaceonclicklistener public void onclickfinal dialoginterface dialog final int id startactivitynew intentandroidprovidersettingsaction location source settings setnegativebuttonno new dialoginterfaceonclicklistener public void onclickfinal dialoginterface dialog final int id dialogcancel alertdialog alert buildercreate alertshow,['android'] +569506,requirejs does not follow relative path for datamain with baseurl set using requirejs i am trying to specify a path for my datamain that is different from the baseurl it seems that requirejs is ignoring whatever i type before the file name and always look for the file in the baseurl folderi have the following folder structure indexhtmlscripts lib requirejs test main2js configjscontents of indexhtml doctype htmlhtml head meta charsetutf8 titletesttitle script datamaintestmain2 srcscriptslibrequirejsscript script srcscriptsconfigjsscript head bodybodyhtmlcontents of configjs requirejsconfig baseurl scriptsand i am getting a 404 error for get scriptsmain2js even though it should be looking for scriptstestmain2js if i remove the configjs file and use datamainscriptstestmain2 it works but i would like to be able to specify a baseurl for my projectany ideas edit following the answer by waxen even if i use scriptstestmain2 scriptstestmain2 or whateveriwantmain2 in my datamain it oddly always looks for scriptsmain2jsnote that i am using requirejs 218,['javascript'] +569583,sse code to set float variable to 00f or 10f based on comparison i have two arrays char c and float f and i need to do this operation compute float maskfloat fchar cchar c threshint nfor int i 0 i n i if ci c thresh fi 00f else fi 10fi am looking for a fast way to do it without conditionals and using sse 42 or avx if possibleif using float instead of char can result in faster code i can change my code to use floats only compute float maskfloat ffloat cfloat c threshint nfor int i 0 i n i if ci c thresh fi 00f else fi 10fthanks,['c'] +569652,how do i queue my python locks is there a way to make python locks queued i have been assuming thus far in my code that threadinglock operates on a queue it looks like it just gives the lock to a random locker this is bad for me because the program game i am working is highly dependent on getting messages in the right order are there queued locks in python if so how much will i lose on processing time,['python'] +569667,trouble on error could not find file ckeditoroverride in my applicationjs file i am using the galetahubckeditor gem version 406 in my ruby on rails 4 application i follow the guide in its readme file but when i add the require ckeditoroverride manifest statement in my applicationjs file i get the following errorsprocketsfilenotfound could not find file ckeditoroverridemy applicationjs file is require jquery require jqueryturbolinks require jquery ujs require jqueryuiall require turbolinks require ckeditoroverride require ckeditorinithow can i solve the problemnote since i do not need to use upload functionality i skip instructions in the how generate models for store uploading filesmy gemfile isgem rails 401rc1gem turbolinksgem jqueryturbolinks git gem ckeditor,['ruby-on-rails'] +569686,mvc 5 check user role how in mvc 5 i can found out role of logged useri made the user by this code private bool adduserandrole identityresult ir var rm new rolemanageridentityrole new rolestoreidentityrolenew applicationdbcontext ir rmcreatenew identityroleadmin var user new applicationuser username admin var result usermanagercreateuser somepassword usermanageraddtoroleuserid admin return true after i loggin on site by that user how in controller i can check if that user have role admin or not i found only one way which doesnt look works fast var rm new rolemanageridentityrolenew rolestoreidentityrolenew applicationdbcontext var role rmfindbynameadmin bool result userisinrolerolename truedo we have other ways,['c#'] +569712,how to detect if facebook app is installed on ios on ios you can launch the facebook app and link to a profile by opening a url like this fbprofile12345the only problem is that if the facebook app is not installed nothing happensis there a way to detect if the app is installed or if the url scheme fb is supportedthis would apply broadly to other apps like twitter as well,['ios'] +569745,valid values for androidfontfamily and what they map to in the answer to this question the user lists values for androidfontfamily and 12 variants see below where do these values come from the documentation for androidfontfamily does not list this information in any place i checked here and here the strings are listed in the android stylesxml file in various places but how do these map back to the roboto fontfrom android 41 42 the following roboto font families are availableandroidfontfamilysansserif roboto regular androidfontfamilysansseriflight roboto light androidfontfamilysansserifcondensed roboto condensed androidfontfamilysansserifthin roboto thin android 42 androidfontfamilysansserifmedium roboto medium android 50in combination with thisandroidtextstylenormalbolditalic 12 variants are possibleregular italic bold bolditalic light lightitalic thin thinitaliccondensed regular condensed italic condensed bold condensed bolditalicin the stylesxml file in the application i am working on somebody listed this as the font family and i am pretty sure it is wrongitem nameandroidfontfamilyrobotoregularttfitemi would like to get the theme for our app set up correctly which includes using fontfamily correctly and remove all the redundancy that is in some of the styles that were created before i had a look at the file,['android'] +569758,collision resolution in java hashmap java hashmap uses put method to insert the kv pair in hashmap lets say i have used put method and now hashmapinteger integer has one entry with key as 10 and value as 17if i insert 1020 in this hashmap it simply replaces the the previous entry with this entry due to collision because of same key 10 if the key collides hashmap replaces the old kv pair with the new kv pair so my question is when does the hashmap use chaining collision resolution technique why it did not form a linkedlist with key as 10 and value as 1720thanks in advanceshri,['java'] +569813,angularjs error 10 digest iterations reached aborting i am trying to create a metro tile type grid with angular to achieve this i want each of the tiles to be a different colour so my plan of action was to create a function that would randomly pick a colour inside a loop using ngrepeat here is what i have so fardiv classrandomcolourclass ngrepeatstockrecord in gridstockrecords filtersearchtext div h6stockrecordproductgroupnameh6 divdivso as you can see i am setting the class name with a function called randomcolourclass here is the js bitsscopetilecolours colourthumbnail tile tilebluecolourthumbnail tile tilegreencolourthumbnail tile tileredscoperandomcolourclass function var randomcolour scopetilecoloursmathfloormathrandom scopetilecolourslength return randomcolourcolourtostringthis all works fine and the tiles are of different colours but i keep getting the following error error 10 digest iterations reached aborting i have had a look at other posts around the issue but i cannot figure out what i need to change to get it working any help or direction would be greatly appreciated,['javascript'] +569839,page height to 100 of viewport i will start by saying that i am very very new to web development as a whole and that this is my very first responsive site so please be gentle and bear this in mind i am the definition of the word noob at this stage having searched for an answer for a while and having no luck i am hoping that someone here could help me outi am trying to make a homepage for this website the design is simply a block down the left hand side of the page showing the logo at the top and then a series of links underneath all of which is on the same background to the right of this is one big image which fills the rest of the screen i want the whole page to fill the browser window of whatever device it is viewed on so absolutely no scrolling is necessary ie width and height both 100 of the viewport the width of the page is giving me no grief at all sweetly adjusting to different screen sizes as i want it with the sidebar at 20 of the width and the main image at 80the height is a different story however i cannot seem in any combination of css i have tried so far to be able to get the height to behave at 100 of the viewport either the sidebar is too short and the main image is too long or both are too long etc etc the main image i want to keep the aspect ratio of and just have it overflow it is div as required to keep most of it thisplayed and the side bar i just want to fit to 100 of the page height here is my code at present htmlheadmeta charsetutf8titletitlestylehtmlheight 100margin 0padding 0bodyheight 100margin 0padding 0page width 100height 100margin 0padding 0sidebarfloat leftwidth 20height 100paddingbottom 10margin 0background urlimagesbgjpgslideshowfloat rightwidth 80height 100overflow hiddenmargin 0padding 0logoimgwidth 80margintop 10marginleft 10marginright 10mainimgwidth 100overflow hiddenlinkfontfamily courierfontsize 13emtextalign centerpaddingtop 7paddingbottom 1color rgba255255255100 fontfacefontfamily couriersrc urlcourier newwebfontfsrc urlcourier newwebfonteotsrc urlcourier newwebfontwoffstyleheadbodydiv idpagewhole page containerdiv idsidebarside bar container div classlink idlogoimg idlogoimg srcimageslogopngdiv div classlink idhomelinkhomehome linkdiv div classlink idaboutlinkaboutabout linkdiv div classlink idgallerylinkgallerygallery linkdiv div classlink idpriceslinkpricesprices linkdiv div classlink idreviewslinkreviewsreviews linkdiv div classlink idcontactlinkcontactcontact linkdiv div classlink idclientslinkclientsclients linkdivdivdiv idslideshowimg idmainimg srcimagesmainjpgimage slideshow containerdivdivbodyhtmlany help with this would be really appreciated and do not hesitate to point out any massively amateur mistakes i am willing to take any criticism and learn from it thanks,['css'] +569865,make android textview invisible until button pressed i am looking to make a textview invisible until the button is pressed specifically they are the answers to the question and only visible once the button below it is pressedwhat i have so far public class androidassignment2 1 extends activity override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity android assignment2 1 button next button findviewbyidridqbutton nextsetonclicklistenernew viewonclicklistener public void onclickview view intent intent new intent setresultresult ok intent finish button next1 button findviewbyidridqbutton next1setonclicklistenernew viewonclicklistener public void onclickview view intent myintent new intentviewgetcontext androidassignment2 2class startactivityforresultmyintent 0 override public boolean oncreateoptionsmenumenu menu inflate the menu this adds items to the action bar if it is present getmenuinflaterinflatermenuandroid assignment2 1 menu return true the xml for this classlinearlayout xmlnsandroid xmlnstools androidlayout widthmatch parent androidlayout heightmatch parent androidorientationvertical textview androidididquestions androidlayout weight1 androidlayout widthwrap content androidlayout height0dip androidtextstringq2 button androidididqbutton androidlayout widthwrap content androidlayout heightwrap content androidtextstringbutton question button androidididabutton androidlayout widthwrap content androidlayout heightwrap content androidtextstringbutton send textview androidididanswers androidlayout weight1 androidlayout widthwrap content androidlayout height0dip androidhintstringa2 button androidididquitbutton androidlayout widthwrap content androidlayout heightwrap content androidtextstringbutton quit linearlayouti dont think more is needed i am just looking for the code that i would apply to abutton to make the textview answers only visible once clicked by user,['android'] +569902,how to set global environment variables for php i have read the questionanswers here but i do not understand how to set variables in etcenvironment if i edit the file do i need to restart my machine or simply log out my current user or log in a new one i want to set a global variable to denote that websites on my machine are in development or testing mode i do not want to have to set this for every project whether it uses php javatomcat nodejs etc i am aware that for apache i can set the environment variable in the following waysdirectly from php with putenv this seems useless since i want to avoid logic that tries to figure out what server the files are onusing htaccess setenv environment local this would require me to duplicate this filecode for every server not idealusing a virtual host directive setenv environment local if i am using a virtual host which in nearly all cases i am but again requires me to copypaste code over and over again in httpdconf setenv environment local this will only apply to apache and i would like it to apply to nodejs servers as welli am not saying i cannot do 4 and apply 3 selectively to nodejs servers but i am thinking that this is a good reason to use etcenvironment as i said above i have edited the file after first creating it and tried the following combinations none of which seemed to workenvironmentlocalenvironmentlocalexport environmentlocalexport environmentlocali say that none of them worked because i did not find the variable in output fromprint r serverprint r envechogetenvenvironment,['php'] +569940,where do you initialize property values in a view controller i have a view controller with properties that determine its behaviour these are set by its parent in prepareforseguethe potential bug this induces in my program is that the parent in question is not guaranteed to set the properties so i would like to have a default value on researching i now understand that properties in objective c do not have default values this left me with the following optionsset the default values for properties in the child views viewdidload method however on investigation viewdidload is called after prepareforsegue in the parent so i would be overwriting the parents values when the parent actually does set the propertiesi then thought i could use id init to initialize the values but at least when using storyboards this method is not called at alli may have a workaround in that objects will initialize to a default value but in this case all i want to pass in is a bool and since the bool will have some value even if not initialized correctly i cannot test it to see if it is nonnilare there any opportunities for initializing value in the child view controller before prepareforsegue in the parent,"['ios', 'objective-c']" +569966,backup a single table with its data from a database in sql server 2008 i want to get a backup of a single table with its data from a database in sql server using a scripthow can i do that,['sql'] +570009,generating waveform from any music file ios i am looking for how to draw the sound waves according to musici want waves like this imagehere is some thiscussion about thisplaying waves from musicwaveform on iosrendering a waveform on an iphoneaudio waveform visualisation with iphonegithub example linksbut not getting any idea about this type of wavefrom is this possible to draw waves like this image,"['ios', 'iphone']" +570024,in java when is the final block in a constructor executed for example constructor public testinputstream in try thisinputstream in finally inputstreamclose is the inputstream that is passed to the instructor immediately closed after the test object is created or is it closed when the test object is destroyed i do not know how to implement something similar to a destructor in c,['java'] +570111,restoring prerelease packages with nuget on our build server i am trying to all the packages in a solution from the command line using nuget 27 according to this microsoft post it should be as easy asnugetexe restore fooslnthis mostly works except it cannot find a number of packagesunable to find version 150beta of package googleapisauthenticationunable to find version 15071beta of package googleapisanalyticsv3unable to find version 150beta of package googleapismy guess is that it is not a coincidence that these are the only prerelease packages in my packagesconfig files according to the docs nugetexe restore is pretty much the only command that does not have a prerelease option so how can i restore prerelease packages,['.net'] +570114,spring mvc requestbody receive an object wrapper with nonprimitive attributes i create the json as follows var manager username admin password admin var usertosubscribe username newuser password newpassword email var openid myopenid var subscription manager manager usertosubscribe usertosubscribe openid openid ajax url myapprestsubscribeuserjson type post datatype json contenttype applicationjson mimetype applicationjson data jsonstringifysubscription subscription this is the json that is sentsubscriptionmanagerusernameadminpasswordadminusertosubscribeusernamenewuserpasswordnewpasswordemailopenidmyopenid and i would like to map this json to a wrapper class this is the wrapperprivate class subscription private user manager private user usertosubscribe private string openid public user getmanager return manager public void setmanageruser manager thismanager manager public user getusertosubscribe return usertosubscribe public void setusertosubscribeuser usertosubscribe thisusertosubscribe usertosubscribe public string getopenid return openid public void setopenidstring openid thisopenid openid the jackson dependency in the pomxml i am using spring 310release dependency groupidorgcodehausjacksongroupid artifactidjacksonmapperaslartifactid version1910version dependencythe mapping in restservletxmlbean classorgspringframeworkwebservletmvcannotationannotationmethodhandleradapter property namemessageconverters list ref beanjsonconverter list propertybeanbean idjsonconverter classorgspringframeworkhttpconverterjsonmappingjacksonhttpmessageconverter property namesupportedmediatypes valueapplicationjson beanand the header of the controller methodpublic responsebody simplemessage subscribeuserrequestbody subscription subscriptionas a result of the post i receive a 400 incorrect request error is it possible to do this or do i need to do it with requestbody string or requestbody mapstringobject and decode the json myselfthanks,['java'] +570119,delay then execute task quick question i want to wait a second before launching an async task without a retrun valueis this the right way to do ittaskdelay10 continuewitht mqsendmessage startwhat happens to exceptions,"['c#', '.net']" +570149,canbenull and resharper using it with async tasks i recently figured out that you can use the canbenull annotation in c to tell resharper and other addons that a method can return null this is great because it makes resharper remind me when i do not handle those situationshowever for async methods that return a task or a taskt the behavior is unexpectedfor instance consider this examplecanbenullpublic async taskstring getsomename var time datetimenow iftimesecond 30 return jimmy else return null i know that this scenario is a bit weird but for simplicity bear with me if i with resharper enabled then try to invoke the method elsewhere it warns incorrectly for instancevar myvalue await getsomenamevar subvalue myvaluetrim here resharper should warn me that subvalue is nullhere resharper warns me at the incorrect place the first line generates a warning and it claims that the task itself can actually be null which is wrong the second line does not generate a warning which is where the warning should have beenif i were to comply with resharper entirely this code would have to be writtenvar mytask getsomenameifmytask null this is silly and is always true but resharper thinks that the task can be null due to the canbenull attribute var myvalue await mytask var subvalue myvaluetrim this could generate an error but resharper does not warn meis this a bug with resharper that i should submit or am i using the annotation incorrectly i guess we can all agree that the task itself cannot ever be null so i do not know how this makes sense,['c#'] +570163,multiprocessing with numpy makes python quit unexpectedly on osx i have run into a problem where python quits unexpectedly when running multiprocessing with numpy i have isolated the problem so that i can now confirm that the multiprocessing works perfect when running the code stated belowimport numpy as npfrom multiprocessing import pool processimport timeimport cpickle as pdef testargs xi args if i 2 timesleep4 arr npdotxtx print iif name main x nprandomrandomsize20500 evaluations xi for i in range5 p pool pmap asynctestevaluations pclose pjointhe problem occurs when i try to evaluate the code below this makes python quit unexpectedlyimport numpy as npfrom multiprocessing import pool processimport timeimport cpickle as pdef testargs xi args if i 2 timesleep4 arr npdotxtx print iif name main x nprandomrandomsize20500 testx4 added code evaluations xi for i in range5 p pool pmap asynctestevaluations pclose pjoinplease help someone i am open to all suggestions thanks note i have tried two different machines and the same problem occurs,['python'] +570180,can i set the state of an object to the object itself in the constructor call i am using a prebuilt third party class library think net framework that contains a class foo with the following memberspublic sealed class foo private object state public fobject state state state foo does not contain a public state setterin a specific scenario i want to set the state of a foo object to the object itself this will not compilefoo ff new foof compilation error use of unassigned local variable fgiven the above prerequisites is there any way that i can set the state of a foo object to the object itselfrationale the timer class in windows 81 does not contain the timerasynccallback constructor which assigned the state of the timer object with the object itself i am trying to port net code that contains this timer constructor to a windows 81 class library so my concern is how do i pass the object itself to its state member this issue is further outlined here but i thought it would be more efficient to also pose the principal question above,['c#'] +570186,converting twitter bootstrap page into pdf with wkhtmltopdf span issue i am using symfony2 bundle knpsnappybundle to convert an html twig template to a pdfknpsnappybundle is base on snappy wrapper that use wkhtmltopdfmy template use twitter bootstrap 232 css like this div classcontainer div classrow div claspan12 h4titleh4 div div div classrow div claspan6 idcustomers h5titleh5 ptextp ul classunstyled lilist itemli lilist itemli lilist itemli lilist itemli ul div div claspan6 idestimate h5titleh5 ul classunstyled lilist itemli lilist itemli lilist itemli lilist itemli ul div divdivproblem the customers and estimate spans are not on the same line as they should bei do not know what is going on,"['html', 'css']" +570229,google analytics v3 for android service unavailable code1 using local store i have implemented gav3 in my app for android as it described in official tutorial i am getting the following warnings in logcatwgav3 3031 threadgathread5main service unavailable code1 will retryigav3 3031 threadgathread5main no campaign data foundwgav3 3031 threadservice reconnect5main service unavailable code1 using local storethere is highspeed internet access tracking id is set properlyand i see no statistics for my devices tested on android 23 and 431,['android'] +570261,cancelling mfmailcomposeviewcontroller causes a memory leak i use mfmailcomposeviewcontroller in an app i am working on now when user taps on a button email form pops up now when i use instruments to monitor memory during this process i see that every time you push the cancel button and the action sheet appears about 25 mb of memory adds up to live bytes in all heap anonymous vm this only occurs if you tap the cancel button everything runs normally when you send the email btw i checked apples messagecomposer sample code here it has the same issuedoes anyone know what might be the reason,['ios'] +570275,field vs method in c class stdnumeric limits why in the template class stdnumeric limits in c is digits and others defined as a static const field of the class but min and max are methods since these methods just return a litteral value thanks in advance,['c++'] +570289,php recursive multidimension array iterator i am trying to write a recursive array iterator function in which the function will return a result set of all sets that are specified by needle where needle keyhere is my functionfunction recursiveneedle array holder array foreach array as key value if gettypevalue array if key needle recursiveneedle value elseif key needle if emptyvalue array pushholder value return holderbut i am not getting all the results back and instead get a few empty results if i do not specify the emptyvalue although the input array does not have any empty sets what am i doing wrong,['php'] +570300,diferences between windowonload function windowonload function i am using in a project the following code which is not working windowonloadfunction code herebut if i add at the end it works windowonloadfunction code heremy question is whats the difference what does the at the endi presume that the first one does not work because somewhere else the onload has been already called killing this onewould it have the same behaviour if i always use the second option thanks in advance,['javascript'] +570330,spring mvc how to return different type in responseentity body in my request handler i want to do some validation and based on the outcome of validation check i will return different response successerror so i create a abstract class for the response object and make 2 subclasses for failure case and successful case the code looks something like this but it does not compile complaining that errorresponse and successresponse cannot be converted to abstractresponsei am quite new to java generic and spring mvc so i do not know of a simple way to solve thisresponsebody responseentityabstractresponse createuserrequestbody string requestbody ifvalidrequestbody errorresponse eresponse new errorresponse populate with error information return new responseentity eresponse httpstatusbad request createuser createusersuccessresponse successresponse new createusersuccessresponse populate with more info return new responseentity successresponse httpsatusok,['java'] +570415,unit of work with repository pattern mvc 5 ef 6 i put together a sample of how i am using the unit of work repository pattern based on my understanding can anyone please let me know if i am implementing this the correct way if i am not how can i improve itthanks in advance it is much appreciatedi have an ef model with two entities topic and subtopic the ef model is called commongoodunit of work summary implementation of a unitofwork class summarypublic static class unitofwork summary gets the default context summary returnsa new instance of the default contextreturns public static commongoodentities getcontext return new commongoodentities igenericrepositorypublic interface irepositoryt summary gets all entities summary returnsall entitiesreturns ienumerablet getall summary gets all entities matching the predicate summary param namepredicatethe filter clauseparam returnsall entities matching the predicatereturns ienumerablet getallexpressionfunct bool predicate summary set based on where condition summary param namepredicatethe predicateparam returnsthe records matching the given conditionreturns iqueryablet whereexpressionfunct bool predicate summary finds an entity matching the predicate summary param namepredicatethe filter clauseparam returnsan entity matching the predicatereturns ienumerablet findexpressionfunct bool predicate summary determines if there are any entities matching the predicate summary param namepredicatethe filter clauseparam returnstrue if a match was foundreturns bool anyexpressionfunct bool predicate summary returns the first entity that matches the predicate summary param namepredicatethe filter clauseparam returnsan entity matching the predicatereturns t firstexpressionfunct bool predicate summary returns the first entity that matches the predicate else null summary param namepredicatethe filter clauseparam returnsan entity matching the predicate else nullreturns t firstordefaultexpressionfunct bool predicate summary adds a given entity to the context summary param nameentitythe entity to add to the contextparam void addt entity summary deletes a given entity from the context summary param nameentitythe entity to deleteparam void deletet entity summary attaches a given entity to the context summary param nameentitythe entity to attachparam void attacht entitygeneric repositorypublic class genericrepositoryt irepositoryt where t class summary the database context for the repository summary private dbcontext context summary the data set of the repository summary private idbsett dbset summary initializes a new instance of the see crefgenericrepositoryt class summary param namecontextthe context for the repositoryparam public genericrepositorydbcontext context this context context this dbset this contextsett summary gets all entities summary returnsall entitiesreturns public ienumerablet getall return this dbset summary gets all entities matching the predicate summary param namepredicatethe filter clauseparam returnsall entities matching the predicatereturns public ienumerablet getallsystemlinqexpressionsexpressionfunct bool predicate return this dbsetwherepredicate summary set based on where condition summary param namepredicatethe predicateparam returnsthe records matching the given conditionreturns public iqueryablet whereexpressionfunct bool predicate return this dbsetwherepredicate summary finds an entity matching the predicate summary param namepredicatethe filter clauseparam returnsan entity matching the predicatereturns public ienumerablet findsystemlinqexpressionsexpressionfunct bool predicate return this dbsetwherepredicate summary determines if there are any entities matching the predicate summary param namepredicatethe filter clauseparam returnstrue if a match was foundreturns public bool anyexpressionfunct bool predicate return this dbsetanypredicate summary returns the first entity that matches the predicate summary param namepredicatethe filter clauseparam returnsan entity matching the predicatereturns public t firstexpressionfunct bool predicate return this dbsetfirstpredicate summary returns the first entity that matches the predicate else null summary param namepredicatethe filter clauseparam returnsan entity matching the predicate else nullreturns public t firstordefaultexpressionfunct bool predicate return this dbsetfirstordefaultpredicate summary adds a given entity to the context summary param nameentitythe entity to add to the contextparam public void addt entity this dbsetaddentity summary deletes a given entity from the context summary param nameentitythe entity to deleteparam public void deletet entity this dbsetremoveentity summary attaches a given entity to the context summary param nameentitythe entity to attachparam public void attacht entity this dbsetattachentity controllerpublic class homecontroller controller summary the context used for the controller summary private dbcontext context summary initializes a new instance of the see crefhomecontroller class summary public homecontroller this context unitofworkgetcontext public jsonresult gettopics var topics new genericrepositorytopicthis contextgetalltolist return thisjsontopics jsonrequestbehaviorallowget summary thisposes of the context if the currently thisposing summary param namethisposinga value indicating whether or not the application is thisposingparam protected override void thisposebool thisposing if thisposing this contextthispose basethisposethisposing essentially i want to make sure i am accessing data in the proper way and making sure i am not overlooking anything again thanks,['c#'] +570420,how to resolve frame load interrupted error in uiwebview in an app i am contracted to build i am pulling a list of youtube videos and allowing them to be thisplayed in the app however when a user taps a cell in the youtube views navigation controller and the modal view with a uiwebview appears the uiwebview returns the error frame load interruptedi have run it through the debugger dozens of times and everything seems to go well until i initialize the nsurlrequest when the modal view is thisplayed here is the code that runs in the viewcontrollers viewdidload method voidviewdidload super viewdidload webview uiwebview alloc init webviewdelegate self nsurlrequest request nsurlrequest alloc initwithurl url webview loadrequestrequesthowever when i pull up the debugger on the line webview loadrequestrequest i see the followingdoes anyone know why the uiwebview is returning the error,"['ios', 'iphone', 'objective-c']" +570489,eof symbolic constant from the c programming language int cwhile c getchar eof putcharc the solution is that getchar returns a thistinctive value when there is no more input a value that cannot be confused with any real character this value is called eof for end of file we must declare c to be a type big enough to hold any value that getchar returns we cannot use char since c must be big enough to hold eof in addition to any possible chari checked in stdioh and printed the value of eof on my system and it is set to 1 on my system chars are signed although i understand that this is system dependent so eof can fit in a char for my system i rewrote the small routine above by defining c to be a char and the program works as intended there is also a character in the ascii character table here that appears to have a blank character corresponding to 255 which appears to act like eof so why does it appear that ascii has a character 255 designated for eof this seems to contradict what is said in the the c programming language book,['c'] +570493,documentformatopenxmlpackaging add as a reference i try to add the documentformatopenxmlpackaging reference in visual studio 2012 but if i go to reference add reference there is not reference like this i was googling the whole evening but still do not find it often i saw that i have to look at net tab in references but there is no tab called net can someone please help me to get out of this dumb situationthanks,"['c#', '.net']" +570543,is it possible to draw a line with spritekit animated i want to draw a line from lets say a10050 to b250450 with apples spritekit frameworkso far i am able to draw this line using a skshapenode and set its path propertywhat i want to achieve is to draw this line animated lets say it should take 2 seconds to draw the line from point a to bi looked into the skaction class but there seems to be no method that supports this functionality by defaultthis is the code i use to create the linecgmutablepathref path cgpathcreatemutablecgpathmovetopointpath null 100 50cgpathaddlinetopointpath null 2500 4500skshapenode line skshapenode nodelinepath pathline setstrokecoloruicolor whitecolorself addchildlinecan anyone point me in the right direction,"['ios', 'objective-c']" +570589,css align two divs left and right on same line please see tia1 div container 2 divs would like to put the second div on the first line but have it all the way to the rightany help would be appreciatedbody backgroundcolor 0 div idfootercontainer stylewidth980px div iddivleft ul idfooter li idtext separatora hreftexta li lia hrefimg src width35 height30 border1a li lia hrefimg src width35 height30 border1a li lia hrefimg src width35 height30 border1a li lia hrefimg src width35 height30 border1a li ul div div iddivleft ul idfooter li idtext separatora hreftext1a li idtext separatora hreftext2a li idtext separatora hreftext3a li idtext separatora hreftext4a ul div divbody,"['css', 'html']" +570598,angularjsjade error argument mycontroller is not a function got undefined mean i know variations of this question have already been asked several times but i have tried several suggested solutions for other ops have not been able to resolve this and would appreciate some clarificationi am working with the basic mean todo list app after implementing a simple controller i am running into the error argument nameofmycontroller is not a function got undefinedheres where i am atappjs boilerplatewindowapp angularmodulemean ngcookies ngresource uibootstrap uiroute meansystem meanarticles angularmodulemeansystem angularmodulemeanarticles i have tried modifying whats referenced here like for example adding meancontroller to the array but that clearly is not the right way to do it because it tells me the module does not existheres my taskcontrollerjs a mean tutorial i followed made taskcontroller a standalone function but i am declaring it as a constructor the way angulars docs say to var mean angularmodulemeanmeancontrollertaskcontroller function taskcontrollerscope scopetodos scopedonefilter done true scopenotdonefilter done false scopesettodos functiontodos scopetodos todos i also tried angularmodulemeansystemcontrollertaskcontroller function taskcontrollerscope same resultok now for the views included ngapp in defaultjade 5 htmlngappmean langen xmlns xmlnsfb itemscopeitemscope itemtype include includeshead body include includesfootthen in indexjade i haveextends layoutsdefaultblock head scripttypetextjavascript srcjscontrollerstaskcontrollerjsblock content sectiondatangview divcontainerngcontrollertaskcontroller nginitsettodos jsonstringifytodos divrowngrepeattodo in todos filternotdonefilter labelcheckbox inputtypecheckbox ngmodeltododone tododescription spandatestring i tododue date m d y divrowngrepeattodo in todos filterdonefilter labelcheckbox inputtypecheckbox checkedtrue del tododescription spandatestring i tododue date m d y footjade insertsangularjsscripttypetextjavascript srclibangularangularjsscripttypetextjavascript srclibangularcookiesangularcookiesjsscripttypetextjavascript srclibangularresourceangularresourcejsi do not think i am missing any angular directives and the controller itself should work so i am assuming this is a basic app architecture problem where i do not understand how things fit together any help would be appreciated,['javascript'] +570610,element upward 100 when transform changed by 1px i am using css 3d transforms in my project i am trying to apply a new transform on the containing element of several other elements i am also trying to use getboundingclientrect on one of its child elements that container also has other elements in it when the container has this value for the transform css propertytranslatez1026px rotatex90deg rotatey180deg translatez439001pxheres what elementgetboundingclientrecttop for that certain child element is 77953109741210944 according to chromes developer tools but when i use the elements tab to change the transform property to thistranslatez1027px rotatex90deg rotatey180deg translatez439001pxheres what elementgetboundingclientrecttop is 750486484375 what would possibly cause this i am not posting any code because this occurs even when i modify the values through the console and when i make the first translatez something like 10px it is still about 77 even when it is at 0 the top of the bounding rect is about 50100 somewhere but when it goes beyond 1026px the elment seems to jump to top 80 or so visually however the element look like it should and does not jump randomly at 1027px can somebody say a situation that might cause thisin case it is a browser bug or something i am using chrome 32016872 devm auraedithere is a jsfiddle linkit will generate a table of all translatez values and the resulting eltgetboundingclientrecttop values the codes messy but in the outputted table if you look over it carefully youll find that at some point the top value will randomly jump far far down and then it will quickly recover to come back to it is previous value weirdthe fiddle might take a long time to load,"['javascript', 'html', 'css']" +570632,css to make images resize and fit any screen the same i have been working with a temp page at but i cannot get the image to resize and be the same in all screen resolutions on the iphone it cuts the girl off before the waist and it fits perfectly when viewed on my 19 laptop screen with the res at 1366 x 768 and even when i fed the video to my 55 tv via vga from my laptop however when i view at larger monitors with greater resolution there is a big space and obvious view where the image size ends i thought i had resizing css with tablet landscape media screen and maxwidth 1060px wrapper width67 tabled portrait media screen and maxwidth 768px wrapper width100 tabled portrait media screen and maxwidth 768px wrapper width100 iphone media only screen and mindevicewidth 320px and maxdevicewidth 480px img maxwidth 100 ipad media only screen and mindevicewidth 768px and maxdevicewidth 1024px img maxwidth 100 i want this image to thisplay on all resolutions as it does when seen on the 1366 x 768thanks for any help,['css'] +570656,eclipse gives ajava was started but returned exit code 13a all hell broke loose after i uninstalled my java 6 and installed java 7 both jdk and jre on opening eclipse it gave the error that no jvm found at so i explicitly gave the location of javawexe as vmcprogra2javajdk170 45binjavawexein the eclipseini file now it says java was started but returned exit code 13also in the elispseini file i changeddosgirequiredjavaversion15to dosgirequiredjavaversion17there are many solutions online like myeclipse 10 does not start java was started but returned exit code 13but none of them works any insight,['java'] +570708,submitting a file with jqueryajax gives typeerror i am trying to submit a file from a form using jquerys ajax methodvar ofiledocumentgetelementbyidimagefiles0var formdata new formdataformdataappendimageofileajax urlelementssave elements dataformdata typepostthis results in the error typeerror append called on an object that does not implement interface formdatawhat causes this error it does not happen on the actual formdataappend but inside jquery,"['javascript', 'jquery']" +570712,what ssiddata in ios contains i am using following code to fetch the connected wifi with my ios devicei want to know what data does ssiddata contains and how to read this data idfetchssidinfo nsarray ifs bridge nsarray cncopysupportedinterfaces nslogs supported interfaces func ifs id info nil for nsstring ifnam in ifs info bridge idcncopycurrentnetworkinfo bridge cfstringrefifnam nslogs func ifnam info if info info count break return info,"['ios', 'iphone']" +570776,thiscrepancy between istreams operator double val between libc and libstdc with my recent upgrade to mac os x 109 the default standard c library changed from libstdc to libc since then i observe unexpected behaviour of the stringstream operatordouble documented in the code example below in summary the libc seems to have problems with extracting double values from stringstreams when the double value is followed by a letteri already checked the standard 2003 but i cannot find any specific information if extraction should work in this case or notso i would be grateful for any input whether this is a bug in libc or libstdcinclude sstreaminclude iostreamusing namespace stdvoid extract doubleconst string s stringstream ss double d ss s ss d ifssfail cout str converted to d endl else cout str failed to convert to double endlint main extract double49 extract double49 x extract double49 extract double49d extract double49xcompiling the code with c stdliblibc streamtestcxx gives49 converted to 4949 x converted to 4949 converted to 4949d failed to convert to double49x failed to convert to doublecompiling the code with c stdliblibstdc streamtestcxx gives 49 converted to 4949 x converted to 4949 converted to 4949d converted to 4949x converted to 49compiler version is c versionapple llvm version 50 clang500279 based on llvm 33svntarget x86 64appledarwin1300thread model posix,['c++'] +570905,servletcontextlistener execution order how to define order of servletcontextlisteners execution due application initialization if i have multiple servletcontextlisteners and some of them declared in deployment descriptor and other with annotation weblistener,['java'] +570948,how to setup a static uitableview as a subview of uiview when i work with a tableviewcontroller i am able to setup all my content in storyboards since i use static cells instead of dynamic properties for my table view i find this method much more convenient and easier to implement i hook up the new uitableview class and simply delete all the delegate methods works like a charm as all of the content buttons are being setup in storyboardsi am trying to accomplish the same result except this time i have to work within a viewcontroller and add a tableview as a subview once i hook up the right class add my outlet connection and setup the following delegates nsintegertableviewuitableview tableview numberofrowsinsectionnsintegersection return 3 uitableviewcell tableviewuitableview tableview cellforrowatindexpathnsindexpath indexpath static nsstring cellidentifier maincell uitableviewcell cell tableview dequeuereusablecellwithidentifiercellidentifier forindexpathindexpath return cellthis works well if my tableview is set to dynamic properties but when i change the table view content to static cells and delete the delegate method my app crashes so how can i add a table view with static cells that i can manipulate in storyboards to my viewcontroller,"['ios', 'objective-c']" +570949,mutationobservers some nodes added are not detected i have a content script which listens for the insertion of textnodes on some websites it is working great except on facebook some of the textnodes inserted are not detected by the scriptscriptjsvar observer new mutationobserverfunctionmutations mutationsforeachfunctionmutation if mutationtype characterdata consolelogmutationtarget else for var x 0 x mutationaddednodeslength x var node mutationaddednodesx if nodenodetype nodetext node consolelognode observerobservedocument childlist true subtree true characterdata true if i allow logging of all node types i can see the parent nodes of these text nodes in my logthanks,['javascript'] +570994,ipython manipulatelike command in wolfram mathematica i can interactively modify the value of a parameter by using the manipulate commandfor example manipulaten n 1 20shows a slider through which is possible to vary the value of nis there any simple way ie something like a magic or a decorator like in sage to achieve the same result in the ipython notebook,['python'] +571004,objectivec declare vars with im was looking the remenu lib code and see a vars being declared as wiht looks something like closure to lazy evaluated code i do not know someone can explain meselfmenuwrapperview uiview view uiview alloc init viewautoresizingmask uiviewautoresizingflexiblewidth if selfliveblur reuikitisflatmode viewlayershadowcolor selfshadowcolorcgcolor viewlayershadowoffset selfshadowoffset viewlayershadowopacity selfshadowopacity viewlayershadowradius selfshadowradius viewlayershouldrasterize yes viewlayerrasterizationscale uiscreen mainscreenscale view selftoolbar uitoolbar toolbar uitoolbar alloc init toolbarbarstyle selfliveblurbackgroundstyle if toolbar respondstoselectorselectorsetbartintcolor toolbar performselectorselectorsetbartintcolor withobjectselfliveblurtintcolor toolbarautoresizingmask uiviewautoresizingflexiblewidth toolbar,"['ios', 'objective-c']" +571013,hsv to rgb is not the inverse of rgb to hsv on matplotlib i tried to convert an image to hsv and back to rgb but somehow i lost color informationimport matplotlibimport matplotlibpyplot as pltimport matplotlibimage as mpimgand i also replicated the problem on shell too just writing this line after importing also gives the same resultpltimshow matplotlibcolorshsv to rgb matplotlibcolorsrgb to hsvmpimgimreadgo2jpg can you tell me what am i doing wrong,['python'] +571043,error called object type int is not a function or function pointer i have a quicksort that i wrote herevoid swapint a int bint midint lo int hi my quicksort implementationvoid sortint vec int lo int hi int mid if hi lo int i lo 1 int j hi int p midlo hi swapveclo vecp mid veclo while i j if veci mid i else while i j vecj mid swapveci vecj i swapveclo veci sortvec lo i sortvec j hi void swapint a int b int temp a a b b tempint midint lo int hi return lo hi lo 2i tried compiling to an object file with g g c arraycpp o arrayoi get this errorarraycpp2414 error called object type int is not a function or function pointer int p midlo hi 1 error generatedeverything looks correct can anyone help me figure out what is wrong,['c++'] +571105,overflow error when doing arithmetic operations with constants i tried the following code int x yx y intmaxvalueint result x ythis code work fine and result will contain 2 i know whybut when doing this const int x intmaxvalueconst int y intmaxvalueint result x ythis will not compile because of overflow problemwhy,['c#'] +571113,running a python script from php i am trying to run a python script from php using the following commandexecusrbinpython27 srvhttpassetspyswitchpy arg1 arg2however php simply does not produce any output error reporting is set to e all and thisplay errors is onheres what i have triedi used python2 usrbinpython2 and python27 instead of usrbinpython27i also used a relative path instead of an absolute path which did not change anything eitheri tried using the commands exec shell exec systemhowever if i runif exececho test test echo exec worksit works perfectly fine while shutdown now does not do anythingphp has the permissions to access and execute the fileedit thanks to alejandro i was able to fix the problem if you have the same problem do not forget that your webserver probablyhopefully does not run as root try logging in as your webservers user or a user with similar permissions and try to run the commands yourself,"['php', 'python']" +571135,creating dataframe from a dictionary where entries have different lengths say i have a dictionary with 10 keyvalue pairs each entry holds a numpy array however the length of the array is not the same for all of themhow can i create a dataframe where each column holds a different entrywhen i trypddataframemy dicti getvalueerror arrays must all be the same lengthany way to overcome this i am happy to have pandas use nan to pad those columns for the shorter entries,['python'] +571151,how do i create a standard ios share button the ios human interface guidelines sayuse the systemprovided share button users are familiar with the meaning and behavior of this button so itas a good idea to use it when possible the main exception to this is if your app does not contain a toolbar or navigation bar as the share button can only be used in a toolbar or navigation barok but how do i ause the systemprovided share buttona a search of the documentation turns up nothing usefuli have gathered that i should use uiactivityviewcontroller in my response to the button being tapped but how would i create the standard share button in the first place,['ios'] +571183,private visibility modifier how to handle differences when converting c to vb the backgroundi have converted the c code below found in treeviewadv file treecolumncs into vbnet code using the converter found at developerfusioncom cusing systemother using callsnamespace agacontrolstree typeconvertertypeoftreecolumntreecolumnconverter designtimevisiblefalse toolboxitemfalse public class treecolumn component private class treecolumnconverter componentconverter public treecolumnconverter basetypeoftreecolumn public override bool getpropertiessupporteditypedescriptorcontext context return false asome i believe unrelated codevbimports systemcollectionsgenericaother imports callsnamespace agacontrolstree typeconvertergettypetreecolumntreecolumnconverter designtimevisiblefalse toolboxitemfalse public class treecolumn inherits component private class treecolumnconverter inherits componentconverter public sub new mybasenewgettypetreecolumn end sub public overrides function getpropertiessupportedbyval context as itypedescriptorcontext as boolean return false end function end class asome i believe unrelated codeend classthe problemaccess to treecolumntreecolumnconverter in this line of the c code is finetypeconvertertypeoftreecolumntreecolumnconverter designtimevisiblefalse toolboxitemfalsehowever vbnet does not allow access to that member in the converted line the error description reads agacontrolstreetreecolumntreecolumnconverter is not accessible in this context because it is private however in both cases treecolumntreecolumnconverter is declared privatethe questions1 the why as this is a learning project for me i would like to know why the scopes are acting differently among the two languages this is the more important question among the 2 of them2 the how what is the best ways to change the vb code to allow access of treecolumnconverter to the identified line of code without opening up the scope to the point that it potentially creates naming confusions elsewhere i could just declare it public but i imagine there is a more correct approach to thisthings to keep in mind when answering1 i know that in vbnet private members are not available external to the object in which they were declared so telling me this will not be helpful and in my mind is not an answer,['c#'] +571189,why does this code not throw a nullpointerexception backgroundi would like to understand why a snippet of code does not throw a nullpointerexceptionsource codeconsider the following codepublic class agent public list files new arraylist public void deliver if files null filesiteratorhasnext file file filefilesiteratornext files new arraylist the deliver method is called repeatedly whilst the following code runs in a separate thread public void run agentfiles null there is only a single agent instanceproblema nullpointerexception is never thrownhowever when the deliver method pauses even for 0 milliseconds a nullpointerexception is thrown as expected public void deliver if files null threadcurrentthreadsleep 0 if filesiteratorhasnext file file filefilesiteratornext files new arraylist my understanding was that there is in theory a race condition between checking for files null and calling filesiteratorhasnext in practice i cannot trigger the race condition without introducing the pause ie splitting the null check from the subsequent method callquestionwhy does the first deliver method not throw an exception when the null check and usage are combined in the same statement,['java'] +571229,set title color for uibutton when highlighted ios 7 i have the following code in a viewcontroller all the outlets and action are hooked up correctly the white and purple are uicolors that i have defined constants for i have also set the uiwindows tintcolor to purple and that propagates down to the button voidviewdidload super viewdidload button settitlecoloruicolor whitecolor forstateuicontrolstatehighlighted buttonbackgroundcolor white buttonlayerborderwidth 10 buttonlayermaskstobounds yes buttonlayercornerradius 50 buttonlayerbordercolor purplecgcoloribaction buttontouchdownidsender buttonbackgroundcolor purple buttonlayerbordercolor whitecgcoloribaction buttontouchupoutsideidsender buttonbackgroundcolor white buttonlayerbordercolor purplecgcoloribaction buttontouchupinsideidsender buttonbackgroundcolor white buttonlayerbordercolor purplecgcolorwhen i click the button the text does not go white like i told it to in viewdidloadheres some screenshots that i could have cropped betteras you can see in the highlighted state it is not white but like a white and purple mixwill i need to use uibuttontypecustom i heard if i do that i would not get the advantages of ios 7 doing its magic with tintcolor not sure whats the correct way to go about this thanks in advance,"['ios', 'iphone', 'objective-c']" +571237,white spaces when updating varchar field using iif in firebird i see strange result when executing this query update sd invodt set line typeiifis promo1 campaign itemthe value in line type field will be item there are whitespaces in valuebut when i execute this query update sd invodt set line typeitemi do not get white spacesnow i have to use trim as workaround update sd invodt set line typetrimiifis promo1 campaign itemi use latest firebird 25 line type is a varchar15is this bug in firebirdediti have tested using new database and the problem persists,['sql'] +571264,how to debug exc bad access bug i received an errorexc bad access code2 at0xb0987654i am wondering how to print out the value at 0xb0987654,['objective-c'] +571277,glyphicons bootstrap icon font hex value i want using glyphicons icon font and i need hex value of the each icon i do not see any page about it on bootstrap website and glyphicons websiteso how to embed that into project and use itnote i want using glyphicons iconfont not png iconsi am using bootstrap 232,['css'] +571318,can i pass the templateurl to the directive angularjs is there a way to pass a templateurl to my directive i understand i can use transclusion but that seems too much for example i have a widget directive that i want to fill with specific html is there a way to pass it in likediv widget templateurltemplate1htmldivdiv widget templateurltemplate2htmldiv,['javascript'] +571386,what happens to a detached thread when main exits assume i am starting a stdthread and then detach it so the thread continues executing even though the stdthread that once represented it goes out of scopeassume further that the program does not have a reliable protocol for joining the detached thread1 so the detached thread still runs when main exitsi cannot find anything in the standard more precisely in the n3797 c14 draft which describes what should happen neither 110 nor 303 contain pertinent wording1 another probably equivalent question is can a detached thread ever be joined again because whatever protocol youre inventing to join the signalling part would have to be done while the thread was still running and the os scheduler might decide to put the thread to sleep for an hour just after signalling was performed with no way for the receiving end to reliably detect that the thread actually finishedif running out of main with detached threads running is undefined behaviour then any use of stdthreaddetach is undefined behaviour unless the main thread never exits2thus running out of main with detached threads running must have defined effects the question is where in the c standard not posix not os docs are those effects defined2 a detached thread cannot be joined in the sense of stdthreadjoin you can wait for results from detached threads eg via a future from stdpackaged task or by a counting semaphore or a flag and a condition variable but that does not guarantee that the thread has finished executing indeed unless you put the signalling part into the destructor of the first automatic object of the thread there will in general be code destructors that run after the signalling code if the os schedules the main thread to consume the result and exit before the detached thread finishes running said destructors what willwis defined to happen,['c++'] +571390,ef is very slow when getting provider information from the database i have found that a large component of efs slow startup time can be related to getting provider information from the database this is very annoying when running integration tests or doing other iterative development can anyone explain why getting provider information is slow or what may be done about it we are using ef5heres an example that demonstrates this behaviorvoid main databasesetinitializermodeldbcontextnull databasesetinitializermodelcreatingdbcontextnull passing the provider information in is very fast var sw2 stopwatchstartnew var builder new dbmodelbuilder builderentitysqlconnectionstringbuilderhaskeyc cconnectionstringtotablestrings var q2 new modeldbcontextbuilderbuildnew dbproviderinfosystemdatasqlclient 2008compilesetsqlconnectionstringbuildertake1tostring consolewritelinesw2elapsed 1 second letting ef determine it from the connection string is sometimes very slow var sw1 stopwatchstartnew var q new modelcreatingdbcontextsetsqlconnectionstringbuildertake1tostring consolewritelinesw1elapsed can be upwards of 13 secondspublic class modeldbcontext dbcontext public static readonly string connection connection string here public modeldbcontextdbcompiledmodel model baseconnection model public class modelcreatingdbcontext dbcontext public modelcreatingdbcontext basemodeldbcontextconnection protected override void onmodelcreatingdbmodelbuilder builder builderentitysqlconnectionstringbuilderhaskeyc cconnectionstringtotablestrings baseonmodelcreatingbuilder,['c#'] +571454,jpa merge unmanaged entity i would like to make an unmanaged entity managed in another persistence context i read that this can be made with mergeemmergeuserbut if i do this it is not added to the contextboolean ismanaged emcontainsuseris always falseeven if i make the followinguser dbuser emfinduserclass usergetidemmergeuserboolean ismanaged emcontainsuserthe dbuser and user are exactly the samewhat am i doing wrongi am using jpa mysql db jboss eap 61,"['java', 'mysql']" +571472,android parse jsonobject i have got a little problem with parsing json into my android appthis is how my json file looks likeinternalname jerry91dataversion 0name domin91profileiconid 578revisionid 0as you can see this structure is a little bit weird i dont know how to read that data in my app as i noticed those are all objects not arrays,['android'] +571495,how to use browserify to bundle a backbone app i am running into a little trouble with browserifythe goali am trying to build the basic todomvc singlepage app with backbone only instead of heaps of script tags in my indexhtml i am trying to bundle them all up with browserifyheres what i have going so farlibmodelstodojsvar backbone requirebackbonevar todo moduleexports backbonemodelextend defaults function return title completed false createdat datenow libcollectionstodojsvar backbone requirebackbone localstorage requirebackbonelocalstoragevar todocollection moduleexports backbonecollectionextend localstorage new localstoragetodomvclibappjsvar todo requiremodelstodo todocollection requirecollectionstodofunctionglobal globaltodocollection new todocollection model todowindowto build my bundle i am usingbrowserify libappjs jsappjslastly my indexhtml is quite simpledoctype htmlhtml head meta charsetutf8 titletodo mvctitle head body script srcajaxgoogleapiscomajaxlibsjquery203jqueryminjsscript script srcjsappjsscript bodyhtmlthe problemwhen i open the console and try to run this commandtodocollectioncreatetitle my first todoi get an errorcannot read property deferred of undefinedstacktracetypeerror cannot read property deferred of undefined at backbonelocalstoragesyncwindowstoresyncbackbonelocalsync httplocalhost40jsappjs18247 at backbonesync httplocalhost40jsappjs25540 at extendsync httplocalhost40jsappjs177328 at extendsave httplocalhost40jsappjs197918 at extendcreate httplocalhost40jsappjs237013 at anonymous216 at objectinjectedscript evaluateon anonymous58039 at objectinjectedscript evaluateandwrap anonymous53952 at objectinjectedscriptevaluate anonymous45821the questioni have done quite a bit of searching on how to browserify backbone apps but i have found little in terms of things that match my objectivehow can i bundle my singlepage backbone app into a single appjs that i can require in the htmlas an asidei am not sure if i am including jquery properly either is backbone going to have trouble connecting itself to jquery if it is also not part of my browserified bundleany tips are greatly appreciated,['javascript'] +571503,how do i pass scope from controller to service in angularjs i have the following controller use strict controllers angularmodulestockscontrollers controllermyctrl1 scope http stockdata function myctrl1 scope http stockdata scopesubmit function scopeinfo stockdataquery consoledirscopeinfo and i want to pass a bound ngmodel that sits in my view called ngmodelsymbol wanted to the following serviceuse strict services angularmodulestocksservices ngresourcefactorystockdata resource functionresource return resource20from20yahoofinancequotes20where20symbol20in2022yhoo220a0909envhttp3a2f2fdatatablesorg2falltablesenvformatjson query methodget isarrayfalse how do i connect the controllers scope to get passed into the service thanks,['javascript'] +571517,parsing html file in r i want to read html files from a web site specifically i want to read books in html format from gutenbergorg the title of each chapter is marked with the tag h2 and the content of each chapter follows in the paragraph tags p after the h2 using the package xml i am able to get the values or the full html code for each taghere is a sample code using george elliots middlemarchlibraryxmldochtml htmltreeparse useinternal truedocvalue xpathapplydochtml h2p xmlvaluedochtmlvalue xpathapplydochtml h2pdocvalue contains a list where each element is the content of the tags but i cannot know whether is a h2 tag or p tag on the other hand dochtmlvalue contains a list with the html code for each tag this gives me the information whether it is an h2 or p tag but it also contains a lot of of extra code like style information etc that i do not needmy question is there a simple way to obtain only the type of the tag and the value of the tag without the other information associated with it,['html'] +571534,unable to get property createrange of undefined or null reference the following code which worked well right up until i upgraded to windows 81 internet explorer 11 is now throwing an error unable to get property createrange of undefined or null referencevar selecteddata windowexternalmenuargumentsdocumentselectioncreaterangetextis there a fix work around for this question updated below with newer code that is still not working htmlheadtitletitlescript typetextjscriptfunction launchvar theselection documentgetselectioniftheselection null do a bunch of stuffwindowclosescriptheadbody onloadlaunch bodyhtmli have also triedwindowgetselectionwindowgetselectionwindowgetselectiontostringnone of these seem to work,['javascript'] +571544,cannot get touch to work in multiplatform cocos2dx app so i am trying to create a simple app using cocos2dx newest build and for some reason cannot get my touch wired up here are my classesclass gamelayer public cocos2dlayerpublic static cocos2dlayer createlayer void updatefloat dt virtual bool init create funcgamelayerprivate bool ontouchbegancocos2dtouch touch cocos2devent event void ontouchmovedcocos2dtouch touch cocos2devent event void ontouchendedcocos2dtouch touch cocos2devent eventcocos2dlayer gamelayercreatelayer gamelayer layer gamelayercreate return layerbool gamelayerinit if cocos2dlayerinit return false thisscheduleschedule selectorgamelayerupdate thissettouchenabledtrue return truevoid gamelayerupdatefloat dtbool gamelayerontouchbegancocos2dtouch touch cocos2devent event cocos2dlogyou touched f f touchgetlocationinviewx touchgetlocationinviewy return truevoid gamelayerontouchmovedcocos2dtouch touch cocos2devent eventvoid gamelayerontouchendedcocos2dtouch touch cocos2devent eventi noticed when i call into the settouchenabled call that an internal flag called running is set to false so it does not actually register my touch events however i cannot seem to figure out why that is the case am i calling things incorrectly or in the wrong order,['c++'] +571553,optimization what are sidetable release and sidetable retain in my opengl loop instruments is showing a total of 14 of my processor time in my particle processing loop going to objc objectsidetable releasebool and objc objectsidetable retain this is significant because the loop is using 100 of a cpu on an iphone 5i am wondering if there is a way i can reduce this i do not know what causes it and i do not see these in very many of my methods i think they are related to doing a fast enumeration of an array of objectshere is what the offending method looks likevoid updatewithtimecctimedt sceneheightabovehorizoncgfloatymax elapsed elapseddt float fartotalwidth eq scene width 2eq size far float farhalfwidth fartotalwidth20 for myparticledata data in selffarparticledata calculate position float newx dataposx dataxvelocity dt if newx 1 newx 1 float newy datay0 eq a farsineq f far elapseddataphaseposition datapos cc3vnewxnewy0 apply new position to sprites dataspriteposition cc3vnewxfartotalwidthfarhalfwidth newyymax 0 datareflectedspriteposition cc3vdataspritepositionxdataspritepositiony0 calculate color float f min14 maxdataposx140 0 color4f newcolor cycblendcolorsselfsettingseqcolumncolorsintf selfsettingseqcolumncolorsintf1 fintf float coloramp max0 sindatafrequencycolor elapseddataphasecolor120 newcolor cycscalecolornewcolorcoloramp coloramp colorampthe alpha white component should be squared twice newcolora colorampcoloramp apply new color to sprites dataspritecolor4f newcolor datareflectedspritecolor4f cycscalecolornewcolor selfsettingseqreflectionbrightness,"['ios', 'objective-c']" +571554,saving in keychainitemwrapper crashes for password apple has provided keychainitemwrapper class in their generickeychain sample code there is an arced solution here on so which i am trying to follow wrapper to store in the keychain on iosthe usage of the wrapper is like thiskeychainitemwrapper keychain keychainitemwrapper alloc initwithidentifierf11emailauth accessgroupnilkeychain setobjectemailtextfield text forkey bridge idksecmatchemailaddressifpresentkeychain setobjectpasswordtextfield text forkey bridge idksecclassgenericpasswordthe line with email text field is acceptedbut the second line with the password crashes with the following exceptionterminating app due to uncaught exception nsinternalinconsistencyexception reason could not add the keychain item first throw call stack 0 corefoundation 0x01b445e4 exceptionpreprocess 180 1 libobjcadylib 0x018c78b6 objc exception throw 44 2 corefoundation 0x01b48 nsexception raiseformatarguments 136 3 foundation 0x014a823e nsassertionhandler handlefailureinmethodobjectfilelinenumberdescription 116 4 feeltracker 0x053b3 keychainitemwrapper writetokeychain 899 5 feeltracker 0x04700 keychainitemwrapper setobjectforkey 272 6 feeltracker 0x092d6 ftloginviewcontroller connecttoaccount 374 7 libobjcadylib 0x018d9874 what could be the reason i wonder if it has anything to do with the constants i am usingupdatethanks to rmaddys helpthis is the bit that seems to throw the error no previous item found add the new oneresult secitemadd bridge cfdictionaryrefself dictionarytosecitemformatkeychainitemdata nullnsassert result noerr could not add the keychain item result is at 50 the secitemadd is a lib method as i was expecting this is somehow related to the keychain handling directlykeychainitemdata contains,['ios'] +571610,solve permgen errors when building in intellij with maven if i get permgen outofmemoryerror from the app server when building my project in intellij with maven is it the heap that maven uses that i should increase i use win7 8gb ram and i get permgen from the appserver when i rebuild the project with maven,['java'] +571621,detecting when system buttons are visible while using immersive mode i am currently using immersive mode api 19 for one of my activities as followsgetwindowgetdecorview setsystemuivisibility viewsystem ui flag layout stable viewsystem ui flag layout hide navigation viewsystem ui flag layout fullscreen viewsystem ui flag hide navigation viewsystem ui flag fullscreen viewsystem ui flag immersive sticky viewinvisiblethis hides the system buttons and notification bar until the user swipes for them back this works fine however i wish to detect when the user makes the buttons visible again i have tried a onsystemuivisibilitychangelistener but it does not trigger for this particular eventany ideas,['android'] +571643,pdoparam int is important in bindparam add pdoparam int or pdoparam str have any meaning in mysql querysql select tagid from tagthread where threadid threadidstmt thisdbpreparesqlstmtbindparamthreadid threadid pdoparam intstmtexecute,"['php', 'mysql']" +571681,is it possible to unload unrequire a ruby library i am looking to load a few libraries have them do some work and then do the opposite of require to avoid compatibility errors later i do not want to have to dump to a file and restart a shell as the objects created such as data could be processed well by my other libraries just not in the presence of the early ones i am seeking to unloadanyone got any suggestions or know if this is possible a conversation from 2006 did not come to much conclusionwise other than that it looks like webrick manages to do this somehowthe libraries in question are google drive and nokogiri the spreadsheet processing library roo depends on google drive for online spreadsheet readingwriting as described at that link,['ruby'] +571707,behaviour of imeoptions imeactionid and imeactionlabel i am quite new to android native development and i am trying to figure out how to customize the ime action buttons i have looked at the google documentation but i can find very few information about the expected behaviourfrom the offical guide i understand that the keyboard action button can be configured using the attributesandroidimeoptions can set the textid of the button thisplayed near the space key to some predefined values eg actiongo set the key label to go and the id to 2androidimeactionlabel set the label of the button thisplayed inside the input area when the keyboard is fullscreen usually in landscape mode can be set to any string valueandroidimeactionid same as previous but set the numeric id passed to the callback methodbut after some empiric attempts i have found different behaviour between api level 15 and next api levelsi have set up a simple edittext element with the following attributesedittext androidimeoptionsactiongo androidimeactionlabelcustom androidimeactionid6 androidinputtypetextand i have checked the effect with the different api levels both in portrait and landscape mode here is the outcomeapi level 15 403in portrait mode the key label is go and the action id passed to the callback method is 2 accordingly to the imeoptions settingin landscape mode the key labelid is go2 as the portrait mode while the button thisplayed in the input area is custom6 accordingly to the imeactionlabel and imeactionid attributesapi level 16 17 and 18 412 422 and 43both in portrait and landscape mode the key and the button are thisplayed with custom label and are bound to 6 id ignoring imeoptions attributethis mismatch in the behaviour is quite annoying becausewith api level 16 you cannot thistinguish between key button and input area buttonwith api level 15 you cannot set any custom text for key buttondo you know how to obtain this both in api 15 and 16 or if there is a way to obtain a consistent behaviour across all or at least a part of the api versionsmaybe i am missing something in the ime settings that can justify the different behaviourthank you very much,['android'] +571740,how to install python without idle i am using archlinux and i find i do not need idle when i am coding python here is part of the default pkgbuild file configure prefixusr enableshared withthreads withcomputedgotos enableipv6 withvalgrind withsystemexpat withdbmlibordergdbmndbm withsystemffi ln sf idle3 pkgdirusrbinidlecan i build python without installing idlethanks in advance,['python'] +571754,google play music api for android i am working on a music application for androidi need two thingsget album cover for artist album name track name etcopen google play page for buying this albumfor the first thing i am currently using itunes api but this is not patriotic for true android developer if google play music has similar service i would preferred to use it does it existwhat about second i can use this code to show all search results according with my queryintent intent new intentintentaction view setdatauriparsemarketsearchqmy querystartactivityintentbut i want to show album or track buying page exactly is is possible for google play,['android'] +571757,rails console cannot connect to database in last days i update my os x to maverics today when i try to create new project like thisrails new abcthere were many problems but i install xcode and now it is work right now i open rails console like thisrails consoleand then whatever i write i only seeloading development environment rails 401193p448 001 link linkno database connectionwhat is wrong mysql is running database exist when i do rake dbmigrate everything works fine,['ruby-on-rails'] +571811,java 8 lambdastreams filter by method with exception i have a problem tryingout the lambda expressions of java 8usually it works fine but now i have methods that throw ioexceptions it is best if you look at the code followingclass bank public setstring getactiveaccountnumbers throws ioexception streamaccount s accountsvaluesstream s sfiltera aisactive streamstring ss smapa agetnumber return sscollectcollectorstoset interface account boolean isactive throws ioexception string getnumber throws ioexception the problem is it does not compile because i have to catch the possible exceptions of the isactive and the getnumbermethods but even if i explecitely use a trycatchblock like below it still does not compile because i do not catch the exception so either there is a bug in jdk or i do not know how to catch these exceptionsclass bank does not compile either public setstring getactiveaccountnumbers throws ioexception try streamaccount s accountsvaluesstream s sfiltera aisactive streamstring ss smapa agetnumber return sscollectcollectorstoset catchioexception ex how can i get it work can someone hint me to the right solution,['java'] +571887,android project showing up with a duplicate app upon deployment my directory structure is as followsprojectlibrariesvolleymyapplicationlibsandroidsupportv4jaretcjarvolley is an imported library project everything runs fine with the application but when it is installed 2 different apps show up on the android app list with the same name and icon one of them works as expected and the other seems to be some empty activity and crashes upon execution with the error javalangruntimeexception unable to instantiate activity componentinfocommyapplicationcomlibsvolleyactivity entry name javalangclassnotfoundexception did not find class comlibsvolleyactivity entry name on path dataappcomexamplemyapplication1apki have tried cleaning and rebuilding and uninstalling from the device itself to no avail all i would like to do is to get rid of this extra appandroidmanifestxmlxml version10 encodingutf8manifest xmlnsandroidpackagecomexamplemyapplicationandroidversioncode1androidversionname10 usessdk androidminsdkversion11 androidtargetsdkversion18 usespermission androidnameandroidpermissioninternet usespermission androidnameandroidpermissioncamera usesfeature androidnameandroidhardwarecamera usesfeature androidnameandroidhardwarecameraautofocus usesfeature androidnameandroidhardwarecamerafront androidrequiredfalse application androidallowbackuptrue androidicondrawableapp icon androidlabelstringapp name androidthemestyleapptheme activity androidnamecomexamplemyapplicationmainactivity androidlabelstringapp name intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity activity androidnameappconfigactivity androidwindowsoftinputmodestatehidden androidlabelapplication configuration activity androidnameboothselectactivity androidlabelbooth select activity androidnameinactiveactivity androidlabelinactive activity activity androidnameqrreaderactivity androidwindowsoftinputmodestatehidden androidlabelqr reader activity activity androidnameproductsactivity androidwindowsoftinputmodestatehidden androidlabelproducts activityapplicationany help would be much appreciatedmy buildgradle filebuildscript repositories mavencentral dependencies classpath comandroidtoolsbuildgradle06 apply plugin androidrepositories mavencentralandroid compilesdkversion 18 buildtoolsversion 1811 defaultconfig minsdkversion 7 targetsdkversion 18 dependencies compile comandroidsupportappcompatv7 compile fileslibscommonscodec14jar compile fileslibsandroidasynchttp143jar compile fileslibsgson224jar compile fileslibszbarjar compile projectlibrariesvolleytask copynativelibstype copy fromnew filesrcmainlibs include into new filebuilddir nativelibstaskswithtypecompile compiletask compiletaskdependson copynativelibs cleandependson cleancopynativelibstaskswithtypecomandroidbuildgradletaskspackageapplication pkgtask pkgtaskjnidir new filebuilddir nativelibs my settingsgradleinclude myapplicationname librariesvolley,['android'] +571922,formatting a date input using simple form i have a date type field in my databaseheres the view code i am using using as string to avoid those three dropdowns rails generates finput field start date as string class formcontrol datepickerwhen saving a date i use a jquery plugin that shows a calendar and writes in a date like 11052013but when editing the same record the input is populated with a value 20130511how can i make it so simple form actually respects my date format defined in enyml,"['html', 'ruby-on-rails']" +571959,execute an exe file using nodejs i do not know how to execute an exe file in nodejs here is the code i am using it is not working and does not print anything is there any possible way to execute an exe file using the command line var fun function consolelogr execcall haiexe functionerr data consolelogerr consolelogdatatostring fun,['javascript'] +571980,uitableview content static cell not working in ios7 i have a problem in my storyboardit is working fine but when i try to change the content property of uitableview it caused following errorassertion failure in uitableview dequeuereusablecellwithidentifierforindexpath sourcecacheuikituikit290323uitableviewmterminating app due to uncaught exception nsinternalinconsistencyexception reason unable to dequeue a cell with identifier cell must register a nib or a class for the identifier or connect a prototype cell in a storyboardi want to design a grouped tableview with static cellthanks in advancecode nsintegernumberofsectionsintableviewuitableview tableview return the number of sections return 2 nsintegertableviewuitableview tableview numberofrowsinsectionnsintegersection return 3 uitableviewcell tableviewuitableview tableview cellforrowatindexpathnsindexpath indexpath static nsstring cellidentifier cell uitableviewcell cell tableview dequeuereusablecellwithidentifiercellidentifier forindexpathindexpath return cell,['iphone'] +571996,best way to compute 2n 1mod p i am working on a cryptographic exercise and i am trying to calculate 2n1mod p where p is a prime numberwhat would be the best approach to do this i am working with c so 2n1 becomes too large to hold when and is largei came across the equation abmodpabmodpmodp but i am not sure this applies in this case as 2n1 may be prime or i am not sure how to factorise thishelp much appreciated,['c'] +572013,zurb foundation table stripe styling i do not want to the default stripe styling for alternating rows in the zurb foundation css frameworkwhats the easiest way to remove it,['css'] +572017,questions regarding c nonpod unions c11 gave us to possibility to use nonpod types within unions say i have the following piece of codeunion t one v two unysomewhere within my class only one member will be active at a time now my questions are rather simplewhat is the default value of uny undefinedwhenever my class is destructed which members within the union if any will be destructedsuppose i have to stdtypeinfo to keep track of which is the active member should i then call the destructor explicitly on that member in the destructordoes anyone have a link to the language proposal which changed unions to accept nonpod types,['c++'] +572035,python script gives no such file or directory i have several python scripts which work just fine but one script has as of this morning started giving me this error if i try to run it from the bash no such file or directoryi am able to run the broken script by doing python script namepy and after looking around a bit the general idea that i picked up was that maybe my line ending of the hashbang got changed silently so i looked at the line ending of a working script and a broken script via the set list option in vi as indicated in this question view lineendings in a text fileboth files appear to end using the same character a so i am kind of at a loss on how to proceed from here specifically how to actually see the line ending in case the set list was not the right method ps the script is executable and the shebang is in there i stated that it is just this 1 script that was working fine before the weekend but it started giving me this error as of this morning edit running the script through dos2unix does get it working again but i would like to know of any way to visualize the line ending somehow in vim or why geany somehow converted the line endings in the first place as i never work on a doswindows system anyhow,['python'] +572052,error failed to build gem native extension error installing mysql2 error while running bundle installinstalling mysql2 0311 with native extensions geminstallerextensionbuilderror error failed to build gem native extensionmake sure that gem install mysql2 v 0311 succeeds before bundlingwhen i run make sure that gem install mysql2 v 0311i still get the same error,"['mysql', 'ruby-on-rails', 'ruby']" +572055,how does try catch work in details i would like to the innards of how does try catch block and stack traces worki was reading this great article about exception handling antipatterns and found the following paragraphcatch nosuchmethodexception e throw new myserviceexceptionblah egetmessagethis destroys the stack trace of the original exception and is always wrongafter that i realized that i do not really know how trycatch works my understanding is the following consider the examplevoid top try f catch myexception ex handleit finally cleanup void f gvoid g throw new myexceptionwhen i call top the call chain top f gleaves two stack frames on the call stack for top and f functions when the exception is raised in gthe program bubbles up the execution stack until it finds trycatch block that handles the exception meanwhile it frees the stack frames and attach stack trace information to some magic object that can be passed to catch and the stack trace can be printedhow does it know that the called function is surrounded with the trycatch block is this information bound to the stack frame like a pointer to error handling block some switch selecting a matching catch block and a pointer to finally block why egetmessage is destructive in the example above see the commentsnote i know how to use trycatch and exceptions i want to know how does it work inside,['java'] +572065,is it possible to render indeterminate progress bar with twitter bootstrap is it possible to render indeterminate progress bar with twitter bootstrap either v2 or v3 using either some buildin functionality or 3rd party plugini trued to google for it but with no luckexample of i want to achieve,['css'] +572124,running phonegap on device no device found i am trying to run an app that i made in phonegap on my device connected with usb phonegap run androidphonegap detecting android sdk environmentphonegap using the local environmentphonegap compiling androidphonegap successfully compiled android aphonegap trying to install app onto devicephonegap no device was found adb deviceslist of devices attached sh25pw103163 devicei just ran a native android app in eclipse on this device i have usb debugging activatedwhat can be wrong,['android'] +572145,thismethod is referring to i have a question regarding this statementlet us say i have this code right here very stupid and useless but gets the message acrossclass calculateint xyfinal int g 5 constructor public calculateint a int b x a y b public int sumaddg return xyg comparing method public boolean samecalculate in ifthissumaddg insumaddg this is what i am curious about return true else return false so do i have this code right when i am using thissumaddg am i referring to the result of the method sumaddg using the instance variables of this class instance,['java'] +572147,how futuretask is asynchronous computation new threadnew runnable public void run startif i will do this in main it will create a new thread and will submit a task to it for asynchronous calculationif you see futuretask documentation it also saysa cancellable asynchronous computation this class provides a base implementation of future with methods to start and cancel a computation query to see if the computation is complete and retrieve the result of the computationso how futuretask is an asynchronous computation does it create thread internally and submit the task that we give it at the time of instantiating futuretask likefuturetask f new futuretasknew mycallableotherwise it cannot be an asynchronous computation please provide me the code snippet from the futuretask source code where it submits the task to thread to make it asynchronous computation thanksi got the answer it is is basically trying to run the task in the same thread as that of caller it is pretty evident in the given codewhen you call futuretaskrun it just calls syncinnerrun and sync is the instance of inner class sync in that it just calls call on the callable object in the same threadvoid innerrun if compareandsetstateready running return runner threadcurrentthread here it is getting the current thread if getstate running v result try result callablecallhere calling call which executes in the caller thread catch throwable ex setexceptionex return setresult else releaseshared0 cancel,['java'] +572151,ios 7 restrict landscape orientation only in one view controller i need to open the first view controller only in portrait mode as the rest view controllers will use both orientation so i have added both orientation in plist filebool shouldautorotate never called nsuinteger supportedinterfaceorientations never calledcan any one tell me how to restrict,['ios'] +572163,google drive uploading file size limit im trying to upload my files to google drive via rest api resumable uploadeverything looks good xmlhttprequest triggers onprogress and onload events but after it onload triggered google drive put request fail with 500 internal server error file not appears in my google drive folder error 500 comes in xhronload not in xhronerror same thing if im trying to upload that file via google drive interface it happens sometimes and i have not environment with 100 reproducingfiletype adobe dng or canon cr2 and filesize 28mbwhat im doing wrong is it known bug or limitations to filetypes or filepossible reasons filesize limitations filetype limitations or maybe my token is expires while my file is uploading upd im using this uploader as is only with cosmetic changes,['javascript'] +572264,gevent downside to spawning large number of greenlets following on from my question in the comment to this answer to the question gevent pool with nested web requestsassuming one has a large number of tasks is there any downside to using geventspawn to spawn all of them simultaneously rather than using a gevent pool and poolspawn to limit the number of concurrent greenletsformulated differently is there any advantage to limiting concurrency with a geventpool even if not required by the problem to be solvedany idea what would constitute a large number for this issue,['python'] +572274,django manytomany generic relationship i think i need to create a manytomany generic relationship i have two types of participantsclass memberparticipantabstractparticipant class meta app label participantsclass friendparticipantabstractparticipant abstract participant common information shared for all rewards passthese participants can have 1 or more rewards of 2 different kinds rewards model is from another appclass singlevoucherrewardabstractreward singleuse coupons are coupon codes that can only be used once passclass multivoucherrewardabstractreward a multiuse coupon code is a coupon code that can be used unlimited times so now i need to link these all up this is how i was thinking of creating the relationship see below would this work any issues you seeproposed linking model belowclass participantrewardmodelsmodel participant content type modelsforeignkeycontenttype editablefalse related nameapp labels clas as participant participant object id modelspositiveintegerfield participant genericgenericforeignkeyparticipant content type participant object id reward content type modelsforeignkeycontenttype editablefalse related nameapp labels clas as reward reward object id modelspositiveintegerfield reward genericgenericforeignkeyreward content type reward object idnote i am using django 16,['python'] +572280,is there a way to get directions in mkmapview using a built in apple api i know google maps are known to be the best maps out there but i dont want to have to download a bunch of extra libraries and all that i would prefer to do something quick and simple to get a quick route from point a to b and be done with it is there a way to do this with built in functionslibraries can somebody point me in the right directionediti am not trying to get turn by turn directions or anything in my case i just want to draw a line from start to finish maybe give options about which routes to take is there a way to do it or no,"['ios', 'objective-c']" +572335,how to programmatically create a basichttpbinding i have to following codebasichttpbinding binding new basichttpbinding uri baseaddress new uri urlsvcendpointaddress endpointaddress new endpointaddress baseaddressvar mychannelfactory new channelfactoryimyinterface binding endpointaddressimyinterface client nulltry client mychannelfactorycreatechannel var a clientwsfunction x icommunicationobjectclientclose catch if client null icommunicationobjectclientabort where imyinterface is the interface that my ws implements for exampleservicecontractpublic interface imyinterface operationcontract result wsfunction1 string param operationcontract result wsfunction2 string param operationcontract result wsfunction3 string paramand it returns something like thisdatacontractpublic class result string a string b datamember public string a get return a set a value datamember public string b get return b set b value when i run this code i can reach the ws but i can never get the result filled outwhat am i doing wrongthanks in advance,['c#'] +572354,columns and inline center image i would like to create a 2 text column with a div in the center like belowi am using this codemozcolumncount 2webkitcolumncount 2columncount 2when i place another div within the div class it formats to go into two columns how do i fix this,"['html', 'css']" +572361,querying calendar content provider over a month time but thisplay instances per day weve got an application that places dots in a month view where calendar events occur were using the calendar content provider to polulate the viewthe only problem is we query the content provider around 30 times per month 1 30 november so we get the correct number of instances per day this way the content provider itself utilizes recurrence rules and multiday eventsfor instancewe have an event that takes place from 4 9 november querying the content provider on a daily basis well get the event back at 4 5 6 7 8 and 9 november this is obviously correct but this has a very negative effect on the performance on the other hand if i query just once 130 nov i will only get the same event back just once so i need to do some calculations on my own to define in which cells the event should appearso then i was wondering if there is an helper or utility that does this for me1 query but 5 times a seperate instance for an event that occurs more then once in that timespan,['android'] +572406,how to emulate backgroundsize cover on how can i resize and reposition the image inside a box in such way that it covers the entire box similar to how backgroundsize cover worksdiv classbox stylewidth 100px height 100px img srcpicjpg width413 height325divi know i have to add overflowhidden to the box and the image needs position absolute but whats the formula that gets me the right new size for the image and left top positions,"['javascript', 'jquery']" +572436,rails sql regular expression i am trying to search for the maximum number in the series a01 a02 a1234 a2351 etc the problem is that the list i am searching in also has strings such as ag108939 e092357 al399 2230597 etc so basically i want the highest a value in my database i was using the following querymax draw drawingwheredrawing number like awhich was working until numbers such as ag309 started getting in the way because it starts with an a but has a different format than what i am looking fori am assuming this should be pretty straight forward with regular expressions but i am new to this and do not know how to correctly write this query with a regular expression here are some things i have tried that just return nil max draw drawingwheredrawing number like ad max draw drawingwheredrawing number like ad max draw drawingwheredrawing number like a09,['ruby-on-rails'] +572464,provide a picture for whatsapp link sharing how can you provide whatsapp a picture to show next to an url,['html'] +572534,visual studio unit test 32bit and 64bit i have a solution that has projects both with c and ccli code and a set of projects which unit test all of these using the microsoft unit test framework for the ccli projects the unit test projects are c unit tests what i currently have is a platform for 32 and 64bit also for each platform i have unit test projects set to 32 and 64bit platforms to matchthe issue i have is that when i switch to 32bit vs 64bit i need to go to test test settings default processor architecture and flip from 32 and 64 as needed if i do not i get a warning from visual studio that a 64bit image cannot run in a 32bit process this makes sense but surely there is some way to automate thisotherwise if i do a batch build on a build machine i will not have control of this and the unit tests will failalso i have tried to set the unit test projects to be anycpu but this fails with an error saying an attempt was made to load a program with an incorrect formatis there a better way perhaps,['c++'] +572552,event log write error it is simple i want to write something to event logprotected override void onstop todo add code here to perform any teardown necessary to stop your service if systemdiagnosticseventlogsourceexistsivrservice systemdiagnosticseventlogcreateeventsource ivrservice ivrservicelog eventlog eventlog1 new systemdiagnosticseventlog eventlog1source ivrservice eventlog1log ivrservicelog try eventlog1writeentrysuccessfully statestoppedtostring ivrapplicationstopimmediate catch exception ex eventlog1writeentryexmessage the exception is failed to stop service systemargumentexception the source ivrservice is not registered in log ivrservicelog it is registered in log application the source and log properties must be matched or you may set log to the empty string and it will automatically be matched to the source property at systemdiagnosticseventloginternalverifyandcreatesourcestring sourcename string currentmachinename at systemdiagnosticseventloginternalwriteentrystring message eventlogentrytype type int32 eventid int16 category byte rawdata at systemdiagnosticseventlogwriteentrystring message,"['c#', '.net']" +572568,how to use di container when owinstartup it is a web api 2 projectwhen i implement di using ninject i got an error messagean error occurred when trying to create a controller of type tokencontroller make sure that the controller has a parameterless public constructorassembly owinstartuptypeofwebstartupnamespace web public partial class startup public void configurationiappbuilder app configureauthapp configurewebapiapp public class tokencontroller apicontroller private iuserservice userservice public tokencontrolleriuserservice userservice this userservice userservice routeapitoken public httpresponsemessage posttokenuserviewmodel model if userservicevalidateusermodelaccount modelpassword claimsidentity identity new claimsidentitystartupoauthbeareroptionsauthenticationtype identityaddclaimnew claimclaimtypesname modelaccount authenticationticket ticket new authenticationticketidentity new authenticationproperties var currentutc new systemclockutcnow ticketpropertiesissuedutc currentutc ticketpropertiesexpiresutc currentutcaddtimespanfromminutes30 return new httpresponsemessagehttpstatuscodeok content new objectcontentobjectnew username modelaccount accesstoken startupoauthbeareroptionsaccesstokenformatprotectticket configurationformattersjsonformatter return new httpresponsemessagehttpstatuscodebadrequest when i add add keyowinautomaticappstartup valuefalse to webconfigninject works fine but startupoauthbeareroptionsaccesstokenformat becomes to nullhow to use di container with owinupdateimplement idependencyresolver and use the webapi dependency resolver as belowpublic void configurewebapiiappbuilder app httpconfiguration config new httpconfiguration configdependencyresolver new ninjectdependencyresolverninjectwebcommoncreatekernel appusewebapiconfigninjectdependencyresolverin simple injector casepublic void configurewebapiiappbuilder app httpconfiguration config new httpconfiguration var container new container containerregisteriuserservice userservice configdependencyresolver new simpleinjectorwebapidependencyresolvercontainer appusewebapiconfigsimpleinjectorwebapidependencyresolver,['c#'] +572588,what happen if a apns device token expired according to this forum post does the device token ever change once created the device token might be expire or apns might change the device token my question is that whether the apns will use the expired token for notification if the server send this expired token to apple can apns use this expired token for another device,['objective-c'] +572616,exc bad access on presentrenderbuffer when i call presentrenderbuffer in some situations my app crash with exc bad access but usually all is okcall stack is here0 0x2f53f02e in glrgetprivateinteger 1 0x329a192e in gligetinteger 2 0x002eec04 in collect all context profiling data block invoke 3 0x0015ea7c in iter contexts 4 0x002ee7f2 in collect all context profiling data 5 0x00163fbc in copy profiling data dictionarycontextinfo unsigned int unsigned long long 6 0x00160566 in handle frame boundary 7 0x002f194c in eaglcontext presentrenderbuffereaglcontext objc selector unsigned int 8 0x044a68 in 36canvasview initializewithcontext block invoke56do you have any ideas about thissolvetexture is created and deleted in different contexts this has caused problems now texture is created and deleted in one context it has solved the problem,['objective-c'] +572665,java unit testing how to measure memory footprint for method call assuming i have a class that does some heavy processing operating with several collections what i want to do is to make sure that such operation cannot lead to outofmemory or even better i want to set a threshold of how much memory it can useclass myclass public void mymethod forint i0 i10 i allocate some memory may be several collections class myclasstest test public void mymethod makesurememoryfootprintisnotbiggerthanmax new myclassmymethod how do i measure amount of memory it may try to allocate what is the right approach to do this or this is not possiblenot feasible,['java'] +572683,how to synchronize scroll between two elements with different height i have two div elements page and block div idpagedivdiv idblockdivblock element has fixed position and long content inside with overflowhidden propertypage element has some content inside too but it height of page will be longer or shorter then block heightmy goal is to achieve synchronized scroll between this two elements something like this i need to calculate speed of block element scroll because header and footer elements of page and block should be at same position from beginning and at the end of scrollthe way i tried to achieve thiscalculated height of page elementcalculated height of block element content because block element is fixed and has alwas fixed heightcalculated block element scroll speed by blockouterheight pageouterheighttriggered scrolltop of block it is working from the beginning and block element scroll is faster then page element scroll but at the end block is not scrolled fullyhere is my jsfiddle maybe anyone can see what i am doing wrongthanks in advance,"['javascript', 'jquery', 'html', 'css']" +572713,detecting geourisupport is there a way with javascript to check whether the clientbrowser supports the geourischemei want to show a coordinate for nonsupported browsers as a link to a map a hrefberlinaand for supported browsers like smartphones as a link to their own native apps a hrefgeo52516271337769berlina,['javascript'] +572735,which c type names are special under what inputs does isspecialname return true from my brief research i have found that property accessors and operator overloads have special names alongside any type with a name which contains an underscore can anyone give me a complete description of cases in which a type name is special,['c#'] +572813,python global variable with thread how do i share a global variable with threadmy python code example isfrom threading import threadimport timea 0 global variabledef thread1threadname read variable a modify by thread 2def thread2threadname while 1 a 1 timesleep1thread1 thread targetthread1 argsthread1 thread2 thread targetthread2 argsthread2 thread1jointhread2joini do not know how to get the two threads to share one variable,['python'] +572822,splitting dataframe into multiple dataframes i have a very large dataframe around 1 million rows with data from an experiment 60 respondentsi would like to split the dataframe into 60 dataframes a dataframe for each participant in the dataframe called data there is a variable called name which is the unique code for each participanti have tried the following but nothing happens or the does not stop within an hour what i intend to do is to split the dataframe data into smaller dataframes and append these to a list datalistimport pandas as pddef splitframedata namename and dataname0 df pddataframecolumnsdatacolumns datalist for i in rangelendata if datanamei n df dfappenddatailoci else datalistappenddf df pddataframecolumnsdatacolumns and datanamei df dfappenddatailoci return datalisti do not get an error message the script just seems to run foreveris there a smart way to do it,['python'] +572824,java mission control in the jdk what can it be used for for free java mission control has been included with the oracle jdk since java 7u40it is very clear from the jmc documentation that this is a commercial feature but the jdk documentation does not clearly indicate when you can use jmc for free and when you need an java se advanced license this could be because oracle want this to be used and therefore has made it freely available or because they do the usual free for development pay for production policy and just want to lure developers into using new expensive toysanyone who has found the precise terms,['java'] +572834,center vertically a unknown height text in a unknown height div i know this is a common issue and i have already asked a similar onebut i could not find the solution this timei am trying to vertically center a text which can have different height in a div which can have different heightand i am trying to solve this only with css without touching the htmlexample div idtest div idsumup h1 classtitretitleh1 div iddatehello guysdiv div divmy goal is to have the text centered vertically and horizontally whatever its size,"['css', 'html']" +572856,redirect to https through url rewrite in iis within elastic beanstalks load balancer how do you use iiss url rewrite module to force users to use ssl while you are behind an elastic beanstalk load balancer,['asp.net'] +572886,thisplay a view or splash screen before applicationdidenterbackground to avoid active view screenshot i have confidential informations in my app so i would like to hide them with a splash screen when the app is about to be moved to backgroundi do run the app on ios6 and furtheri tried to thisplay the view in applicationwillresignactive but the problem is it thisplay the splash screen even when user swipe control panel for example i want it to show only when the app is moved to backgroundi tried to thisplayed my splashscreen in applicationdidenterbackground but it takes the screenshot before so informations are thisplayed at restoration during the animationhere the spirit of what i want voidapplicationdidenterbackgrounduiapplication application window addsubview splashcontrollerview,['ios'] +572921,removing black borders on a vimeo iframe embed using css i am trying to find a way to hide the black strips across the top and bottom of a vimeo video i thought there might be a way to cover them up with cssi basically wanted to achieve what this person wanted to achieve with an image in the link below except i want to do it with an embedded video whilst keeping it repsonsiveremoving black borders 43 on youtube thumbnailsmany thankshtml section classd5d13 c5c13 b5b13 a5a13 video div classembedcontainer iframe src frameborder0 webkitallowfullscreen mozallowfullscreen allowfullscreeniframe divsectioncssembedcontainer position relative paddingbottom 5625 paddingtop 30px height 0 overflow hidden maxwidth 100 height auto embedcontainer iframe embedcontainer object embedcontainer embed position absolute top 0 left 0 width 100 height 100,['css'] +572930,gradle android and the android home sdk location edit aug2016that question is from november 2013 while android studio was still in developer preview mode currently as v22 aug2016 during instalation as asks to choose the sdk folder or install on their default and it automatically applies to which ever project youre openingthat means any possible workaround or fix is irrelevant as the issue is not reproducible anymoreoriginal questionwe have this project with several modules that is already configured and executes correctly on another developer pc using a wrapper i cloned the complete git submodules into my machinebelow it is a directly print of my command line gradlewfailure build failed with an exception wherebuild file homebudiusproject nameactionbarpulltorefreshlibrarybuildgradle line 1 what went wronga problem occurred evaluating project actionbarpulltorefreshlibrary sdk location not found define location with sdkdir in the localproperties file or with an android home environment variable tryrun with stacktrace option to get the stack trace run with info or debug option to get more log outputbuild failedtotal time 6378 secs echo android homehomebudiusapplicationsandroidstudiosdk so as you can see the android home is there what else do they want whats wrong hererunning on ubuntu 1304editi already created a localproperties file with sdkdirpath on the project root and it works but that makes the code harder to port across systems and build server so the question is still open anyone knows why the android home is not working and what to do to make it work,['android'] +573005,comgooglegsoninternallinkedhashtreemap cannot be cast to my object i have json file looks like subs uid featuresetname siemensgsmtelephony multisim featurename multisimimsi featurekey key sckey valuetype 0 value 0 so the key is a string subs id and the value is a model called featuredetails which contains attributes featuresetnamefeaturenameso i read from the json file using googlejson lib like thishashmapstring featuredetails featuresfromjson new gsonfromjsonjsonfeatureset hashmapclassthen i am trying to loop over this hashmap getting the value and cast it to my featuredetails modelfor mapentry entry featuresfromjsonentryset featuredetails featuredetails entrygetvalue and here is my featuredetails modelpublic class featuredetails private string featuresetname private string featurename private arraylistfeaturekey featurekey private string groupkey private string groupvalue public featuredetails featurekey new arraylistfeaturekey public arraylistfeaturekey getfeaturekey return featurekey public void setfeaturekeyarraylistfeaturekey featurekey thisfeaturekey featurekey public string getgroupkey return groupkey public void setgroupkeystring groupkey thisgroupkey groupkey public string getgroupvalue return groupvalue public void setgroupvaluestring groupvalue thisgroupvalue groupvalue public string getfeaturename return featurename public void setfeaturenamestring featurename thisfeaturename featurename public string getfeaturesetname return featuresetname public void setfeaturesetnamestring featuresetname thisfeaturesetname featuresetname but i got an exception comgooglegsoninternallinkedhashtreemap cannot be cast to comassetvsvmodelsfeaturedetail,['java'] +573028,twitter typeaheadjs show all options when clickfocus i am using typeaheadjs in an autocomplete text input and it is great but i need to activate the dropdown menu with all the available options when the input gets focus every possible solution i have seen involves initializing the input with some value but i need to show all the optionshow could i achieve this,['javascript'] +573043,how to get id from entity for auditlog in entity framework 6 i know it is several similar posts out there but i cannot find any with a solution to this issuei want to add a sort of audiolog when adding changing or deleting entities softdelete in entity framework 6 i have overridden the savechanges and because i only want to add log entries for entitystates added modified or deleted i fetch the list before i call savechanges the first time the problem is because i need to log what operation has been executed i need to inspect the entitystate of the entities but after savechanges is called the entitystate is unchanged for all entriespublic override int savechanges using var scope new transactionscope var modifiedentries changetrackerentries wheree estate entitystateadded estate entitystatedeleted estate entitystatemodified tolist int changes basesavechanges foreach var entry in modifiedentries applyauditlogentry basesavechanges scopecomplete return changes private void applyauditlogdbentityentry entry ilog entity entryentity as ilog if entity null logoperation operation switch entrystate case entitystateadded operation logoperationcreateentity break case entitystatedeleted operation logoperationdeleteentity break case entitystatemodified operation logoperationupdateentity break default throw new argumentoutofrangeexception auditlog log new auditlog created datetimenow entity entryentitygettypename entityid entityid operation operation auditlogaddlog,['c#'] +573057,cannot install thistribution provisioning profile i would like to submit an app to the appstore my first app i have already tested the application in my device so i already have a development provisioning profile but i am not able to install a thistribution provisioning profile in xcodei have followed the procedure i do not know how many times but when i try to add the provisioning profile through the organizer i have following problemsif i double click on the file nothing happensif i click add the file is not selectable greyif i drag and drop from finder i see the following message 1 profilecannot be installed on iphone of corrado iphone of corrado is not included in this profilewhat does it means if i go in the development centercertificates identifiers profilesprovisioning profilesthistribution and edit the profile there is no devices and there is no way to add any while in the development provisioning profile i see all my deviceswhat i am doing wrong thanks corrado,"['ios', 'iphone']" +573077,aspnet website administrator tool in vs 2013 is there a short cut method to open website administrator in visual studio 2013 other than the method specified below,['asp.net'] +573234,how to thisable git push results dialog in eclipse after a push to upstream git operation the eclipse ide shows a helpful dialog which provides information about the push operation shown belowis there a way to prevent this dialog from popping up,['java'] +573236,coin flip simulation never exceeding a streak of 15 heads i was working on a simulation of the st petersburg paradox when i realized my coinflipping code never recorded any streaks of greater than 15 heads in a row i ran the simulation 10 times which should have resulted in an average of 1526 streaks of heads 16 long0516 x 10 1526clearly something is wrong include stdlibhinclude stdiohinclude timehint mainint argc char const argvsrandtime0int i lim 10 streak 0 maxstreak 0for i 0 i lim i if rand2 streak if streak maxstreak maxstreak streak else streak 0printfran d times longest streak of dn lim maxstreakreturn 0returns the following every timeran 10 times longest streak of 15thanks for your helpedit running gcc version 462 on windows 7 x64 bit new to programming in generaledit 2 thanks for everyones help anyone sticking around i wonder what about the current implementation would give a limit of 15 heads how would the rand function be so interestingly broken to produce this problem,['c'] +573276,get signal strength in android i want to get the signal strength of the device at the point i hit the api call i have searched on all the related threads and i am not successful yet so i would like to get the signal strength likesignalstrength ss null some initializationint and ssgetgsmsignalstrengthbut while using this it is obvious that i will get null pointer exception since i have initialised signalstrength as null but i do not know how to initialise thisalso that i do not want to use phonestatelistener because it is triggered only if the signal changes i am getting the signal strength using the below codetelephonymanager telephonymanager telephonymanagerthisgetsystemservicecontexttelephony servicecellinfogsm cellinfogsm cellinfogsmtelephonymanagergetallcellinfoget0cellsignalstrengthgsm cellsignalstrengthgsm cellinfogsmgetcellsignalstrengthcellsignalstrengthgsmgetdbmbut i do not want to use cellsignalstrength because it is only added in api level 17 and will not work under 17 i want the code to work on api level 7 or is there any other method so that i could get the signal strength at the point of hitting the api call,['android'] +573280,what is the meaning of picturepilelayercontent warning painting picturepile without content i am getting this warning when getting html content from server to webview and html contains img src tagexample sequences represents the increasing order of the polarizing power of the cationic speciesimg src demopracticechemistryq788jpg1106 013544129 wpicturepilelayercontent2179 warning painting picturepile without content1106 013544139 wpicturepilelayercontent2179 warning painting picturepile without content1106 013544149 wpicturepilelayercontent2179 warning painting picturepile without content1106 013544209 ddalvikvm2179 gc for alloc freed 931k 32 free 3704k5380k paused 47ms total 51ms1106 013544219 wpicturepilelayercontent2179 warning painting picturepile without content1106 013544279 ichoreographer2179 skipped 99 frames the application may be doing too much work on its main thread1106 013544289 wpicturepilelayercontent2179 warning painting picturepile without content1106 013544359 dwebviewglue2179 nativedestroy view 0x2a3640781106 013544359 dwebviewglue2179 nativedestroy view 0x2a38b3a01106 013544359 dwebviewglue2179 nativedestroy view 0x2a4f6f401106 013544388 dwebviewglue2179 nativedestroy view 0x2a4f6fc81106 0135419 ichoreographer2179 skipped 48 frames the application may be doing too much work on its main thread1106 013548 wpicturepilelayercontent2179 warning painting picturepile without content1106 013548 wpicturepilelayercontent2179 warning painting picturepile without content1106 013548 wpicturepilelayercontent2179 warning painting picturepile without content1106 013544508 wpicturepilelayercontent2179 warning painting picturepile without content1106 013544518 wpicturepilelayercontent2179 warning painting picturepile without content1106 013544924 ichoreographer2179 skipped 43 frames the application may be doing too much work on its main thread1106 013545119 wpicturepilelayercontent2179 warning painting picturepile without content1106 013545119 wpicturepilelayercontent2179 warning painting picturepile without content1106 013545159 wpicturepilelayercontent2179 warning painting picturepile without content1106 013545169 wpicturepilelayercontent2179 warning painting picturepile without content1106 013545169 wpicturepilelayercontent2179 warning painting picturepile without content1106 013545209 wpicturepilelayercontent2179 warning painting picturepile without content1106 013545219 wpicturepilelayercontent2179 warning painting picturepile without content1106 013545219 wpicturepilelayercontent2179 warning painting picturepile without content1106 013545229 wpicturepilelayercontent2179 warning painting picturepile without content1106 013545269 wpicturepilelayercontent2179 warning painting picturepile without content1106 013545279 wpicturepilelayercontent2179 warning painting picturepile without content1106 013545289 wpicturepilelayercontent2179 warning painting picturepile without content1106 013545289 wpicturepilelayercontent2179 warning painting picturepile without content1106 013545319 wpicturepilelayercontent2179 warning painting picturepile without content1106 013545329 wpicturepilelayercontent2179 warning painting picturepile without content1106 013545339 wpicturepilelayercontent2179 warning painting picturepile without content1106 013545339 wpicturepilelayercontent2179 warning painting picturepile without content1106 013545389 wpicturepilelayercontent2179 warning painting picturepile without content1106 013545399 wpicturepilelayercontent2179 warning painting picturepile without content1106 013545409 wpicturepilelayercontent2179 warning painting picturepile without content1106 013545419 wpicturepilelayercontent2179 warning painting picturepile without content,['android'] +573330,how to export the html tables data into pdf using jspdf how do i export the tables in html page to pdf i have done some sample data but i am unable to load the html table list into pdf please can any one help me in loading the tables into pdfdoctype htmlhtml langen head titlehtml2canvas exampletitle script typetextjavascript srcjsjqueryjquery171minjsscript script typetextjavascript srcjsjspdfjsscript script typetextjavascript srclibsfilesaverjsfilesaverjsscript script typetextjavascript srcjsjspdfpluginstandard fonts metricsjsscript script typetextjavascript srcjsjspdfpluginsplit text to sizejsscript script typetextjavascript srcjsjspdfpluginfrom htmljsscript script typetextjavascript documentreadyfunction var specialelementhandlers editor functionelement renderer return true cmdclickfunction var doc new jspdf docfromhtmltargethtml 15 15 width 170elementhandlers specialelementhandlers docsavesamplefilepdf script head body idtarget div idcontent h3hello this is a h3 tagh3 a classuploadupload to imgura h2this is bboldb span stylecolorredredspanh2 table border1 tr thheader 1th thheader 2th tr tr tdrow 1 cell 1td tdrow 1 cell 2td tr tr tdrow 2 cell 1td tdrow 2 cell 2td tr table div button idcmdgenerate pdfbutton bodyhtml,"['jquery', 'html']" +573334,android google plus sdk how to get callback on the 1 button plusonebutton i added a 1 button in my android app i would like to add a callback in order to know what happened after the user clicked on the 1 button did he validate its 1 did he abort how can i do that thanks,['android'] +573349,android ndk keeping live c objects i have got a following problem i want to write an android application which uses my legacy c classes i have to keep a c object alive during the whole application lifetimei wrote a similar application in c and solved the problem by passing a pointer to a c class to c and storing it there using intptr then when i wanted to call a method on that object i simply passed that pointer again to c converted to a class pointer and called a method on ithow can i achieve similar result in java and android ndk does java support storing pointers,"['java', 'android', 'c++']" +573352,html table width not working doctype htmlhtml xmlnshead titletitleheadbody table border1 width100 tr tdatd tdatd tdatd tdatd tdatd tdatd tdatd tdatd tdatd tdatd tdatd tdatd tdatd tdatd tr tablebodyhtmli am trying to set the table width to 100 for above table but it has no effect it goes beyond window width how do i change the width of table so it is same size as window,"['html', 'css']" +573416,ubuntu linking boostpython fatal error pyconfig cannot be found having some issues now i have read the followinghello world python extension in c using boosti have tried installing boost onto my desktop and done as the posts suggested in terms of linking i have the following codeinclude boostpythonhppinclude pythonhusing namespace boostpythonnow i have tried linking with the followingg testingcpp i usrincludepython27pyconfigh l usrincludepython27pythonhlpython27and i have tried the following as wellg testingcpp i homeusernamepythoninclude l usrincludepython27pythonh lpython27i keep getting the following errorusrincludeboostpythondetailwrap pythonhpp5023 fatal error pyconfigh no such file or directory include pyconfighi do not know where i am going wrong i do have boostpython installed there is just a problem linking,['c++'] +573473,converting html element to string in javascript jquery i would like to convert a html element created from a string back to the string after some modifications but i get an empty string insteadiframe width854 height480 src frameborder0 allowfullscreeniframehtmlhow can i do that another way,"['javascript', 'jquery', 'html']" +573476,how to mock a decorated function for testing reasons i need to be able to mock the inneroriginal function of a decorated one which is used somewhere elsein mydecoratorpydef my decoratorf def wrapped f print decorated f return wrapped fmy decoratordef function to be mocked print originaldef function to be mocked undecorated print originaldef run decorated function to be mockeddef run undecorated decorated funtion my decoratorfunction to be mocked undecorated decorated funtionas you can see i have several versions of the original function function to be mocked one with the decorator my decorator and one naked the runner function run decorated calls the decorated version of function to be mocked and run undecorated calls the undecorated version and applies the decorator manually the result of both are the samedecoratedoriginalnow i want to test the runner function but i need to mock the original function function to be mocked but also the mocked version should be decoratedimport unittestimport mydecoratorfrom mock import patchdef mock function print mockifiedclass testunittesttestcase patchmydecoratorfunction to be mocked undecorated def test undecorated mockedself mock function to be mocked undecorated mydecoratorfunction to be mocked undecorated mock function mydecoratorrun undecorated assert 10 patchmydecoratorfunction to be mocked def test decoratorated mockedself mock function to be mocked mydecoratorfunction to be mocked mock function mydecoratorrun decorated assert 10this works as expected for the undecorated version test undecorated mockeddecoratedmockifiedbut the decorated version givesmockifiedso the decorator vanished is it possible to get the decorated version working in the same way as the undecorated version where the decorator is applied manuallyi tried to expose the inner function in the decorator without successi saw this question how do you mock a function which has decorator apply to it in a unit test but this does not help me,['python'] +573508,scanner reading large file i am playing around with the scanner class for learning purposes and i use it to read a very large file 60 lines aprox without using the reader class and it stops reading after approximately 400 lines do i have to use a bufferedreader inside the scanners constructor or the problem is something else i want to know why this is happening thanksmy code is the usual code to output all the linesfile file1 new filefile1scanner in new scannerfile1while scanhasnextline string str scannextlinesystemoutprintlnstr,['java'] +573542,thisable ipython console in pycharm i use the pycharm community edition and also ipython pycharm automatically recognizes ipython and sets it as the default console pycharm webhelp link so when in debugging mode it accepts to runs ipython magic commands like list or ls or timeitit is very nice but i would like to use the plain old python console is there a simple way to do that note that i do not want to uninstall ipython which obviously solves my problem nor do i want to set up a virtualenvi use python 332 but the problem is the same with 27,['python'] +573566,why gradle android plugin does not generate dependencies for intellij idea module i have gradle project with 4 subprojects and i m using idea plugin to generate idea project and modules one of the subprojects is android modulehere is it is buildgradle codebuildscript repositories mavencentral dependencies classpath comandroidtoolsbuildgradle056 apply plugin androidandroid buildtoolsversion 1811 compilesdkversion 16 sourcesets main manifestsrcfile androidmanifestxml javasrcdirs src resourcessrcdirs src aildsrcdirs src renderscriptsrcdirs src ressrcdirs res assetssrcdirs assets instrumenttestsetroottests repositories mavencentraldependencies compile orgatmospherewasync110 orgcodehausjacksonjacksonmapperlgpl1913 orgprojectlomboklombok0 orgapachehttpcomponentshttpmime431 commonsiocommonsio2 comgoogleguavaguava14 compile filetreedir libs include jarthe problem is when using gradle idea to generate intellij idea modules resulting android module is missing dependencies and i cannot figure out why is something wrong with my configother subprojects using java plugin have dependencies imported in idea modules without problemsi am using gradle 17,['android'] +573618,how to retrieve colorbar instance from figure in matplotlib all i want to update the colorbar of a figure when the imagedata is changed so something likeimg misclenafig pltfigureax pltimshowimpltcolorbaraxnewimg img10nprandn512512def update colorbarfigaxnewimg cbar figaxes1 axset datanewimg cbarupdate normalax pltdrawbut it seems that returned results from figaxes does not have the colorbar instance like i expected i can probably just pass the colorbar instance as an argument to the update function but i thought just passing one fig parameter may be good enough can anyone explain a little bit on how to retrieve the colorbar from the figure or why figaxes does not return the axesimage or colobar instance but just the axes or axessubplot i think i just need more understanding of the axesfigure stuffthank you,['python'] +573627,following in app purchase app crashing on startup productidentifiernil i have a few users who have reported that after attempting an in app purchase the app is now crashing on startup i have asked them to delete and reinstall the app which has not worked and attempted to ask them to go into airplane mode to stop any network communication that has not worked i am unable to replicate the error in anyway on my devices and my in app purchase goes through just fine in sandbox and production modes my thought is that somehow their transaction received a nil productidentifier which is causing the startup crash but i am not sure what transaction observer methods get called at app startup that i can fix the issue for themis there someway to clear the transaction queue or otherwise test for nil productidentifiers on start up and allow these users to get the app at least running again i have done several hundred in app purchases using the code below and this just recently began happening which of the helper methods get called on app startup in appdelegatemskpaymentqueue defaultqueue addtransactionobservermovieclockiaphelper sharedhelperin app helper code idinitwithproductidentifiersnsset productidentifiers if self super init store product identifiers productidentifiers productidentifiers retain check for previously purchased products nsmutableset purchasedproducts nsmutableset set for nsstring productidentifier in productidentifiers bool productpurchased nsuserdefaults standarduserdefaults boolforkeyproductidentifier if productpurchased purchasedproducts addobjectproductidentifier nslogpreviously purchased productidentifier else nslognot purchased productidentifier selfpurchasedproducts purchasedproducts return self voidrequestproducts selfrequest skproductsrequest alloc initwithproductidentifiers productidentifiers autorelease requestdelegate self request start voidproductsrequestskproductsrequest request didreceiveresponseskproductsresponse response nslogreceived products results selfproducts responseproducts selfrequest nil nsnotificationcenter defaultcenter postnotificationnamekproductsloadednotification object products voidrestorecompletedtransactions skpaymentqueue defaultqueue restorecompletedtransactions voidprovidecontentnsstring productidentifier nslogtoggling flag for productidentifier nsuserdefaults standarduserdefaults setbooltrue forkeyproductidentifier nsuserdefaults standarduserdefaults synchronize purchasedproducts addobjectproductidentifier nsnotificationcenter defaultcenter postnotificationnamekproductpurchasednotification objectproductidentifier voidcompletetransactionskpaymenttransaction transaction nslogcompletetransaction self recordtransaction transaction self providecontent transactionpaymentproductidentifier skpaymentqueue defaultqueue finishtransaction transaction voidrestoretransactionskpaymenttransaction transaction nslogrestoretransaction self recordtransaction transaction self providecontent transactionoriginaltransactionpaymentproductidentifier skpaymentqueue defaultqueue finishtransaction transaction voidfailedtransactionskpaymenttransaction transaction if transactionerrorcode skerrorpaymentcancelled nslogtransaction error transactionerrorlocalizeddescription nsnotificationcenter defaultcenter postnotificationnamekproductpurchasefailednotification objecttransaction skpaymentqueue defaultqueue finishtransaction transaction voidpaymentqueueskpaymentqueue queue updatedtransactionsnsarray transactions nslogin the payment queue for skpaymenttransaction transaction in transactions switch transactiontransactionstate case skpaymenttransactionstatepurchased self completetransactiontransaction break case skpaymenttransactionstatefailed self failedtransactiontransaction break case skpaymenttransactionstaterestored self restoretransactiontransaction default break voidbuyproductskproduct product nslogin buyproduct buying productproductidentifier skpayment payment skpayment paymentwithproductproduct skpaymentqueue defaultqueue addpaymentpayment voiddealloc productidentifiers release productidentifiers nil products release products nil purchasedproducts release purchasedproducts nil request release request nil super deallocend,['ios'] +573646,stack size under mono i have written a tiny recursive bit of f code to see how many levels of recursion i can fit onto the stack under netmono it just prints the recursion depth whenever it is an exact power of 2 so i find out the maximum depth to within a factor 2i start the code in a thread with a defined amount of stack space using systemthreadingthread threadstart int under net it seems to take approx 100 bytes per level of recursion and i can get about 16 million levels on a 2g stack the memory usage is broadly similar under mono however i can only get about 30 thousand levels increasing the stack size value passed to thread past over about 60 does not increase the recursion depth ulimit reports the stack size limit is 1gan obvious explanation is that mono will not obey the second argument of thread if it is too large does anybody please know how to convince mono to allocate a large stackthe code is trivial but it is below just in case someone careslet rec f i if popcount i 1 then population count is one on exact powers of 2 printf got up to dn i stdoutflush if i 10 then 0 else 1 f i1,['.net'] +573695,inapp restore works fine on debug but crashes on adhoc in iphone sdk my app is getting crashed when i clicked on restore button clickedadhoc version but same app is working fine in debug mode my codeskpaymentqueue defaultqueue restorecompletedtransactionscrash reportnov 6 231904 lhdipod5 backupd1815 warning info account changed enabled0 accountidnullnov 6 231904 lhdipod5 kernel0 debug applekeystore operation failed pid 1815 sel 23 ret e02f0nov 6 231904 lhdipod5 profiled1816 notice note profiled service startingnov 6 231904 lhdipod5 itunesstored90 warning could not load library 22nov 6 231904 lhdipod5 securityd78 error cfpropertylistreadfromfile file filelibrarykeychainsaccountstatusplist the operation couldnat be completed cocoa error 260nov 6 231904 lhdipod5 securityd78 notice item secdbitemdoupdate replaced ogenpeef8647clckuapple1272acctsvcev data20131106174027105945zf7768b61 with ogenpeef8647clckuapple1272acctsvcev data20131106174904733739z0a75c458 in secdbconnection rw opennov 6 231904 lhdipod5 securityd78 error cfpropertylistreadfromfile file filelibrarykeychainsaccountstatusplist the operation couldnat be completed cocoa error 260nov 6 231904 lhdipod5 securityd78 error cfpropertylistreadfromfile file filelibrarykeychainsaccountstatusplist the operation couldnat be completed cocoa error 260nov 6 231904 lhdipod5 securityd78 error cfpropertylistreadfromfile file filelibrarykeychainsaccountstatusplist the operation couldnat be completed cocoa error 260nov 6 231904 lhdipod5 securityd78 error cfpropertylistreadfromfile file filelibrarykeychainsaccountstatusplist the operation couldnat be completed cocoa error 260nov 6 231904 lhdipod5 securityd78 error cfpropertylistreadfromfile file filelibrarykeychainsaccountstatusplist the operation couldnat be completed cocoa error 260nov 6 231904 lhdipod5 securityd78 error cfpropertylistreadfromfile file filelibrarykeychainsaccountstatusplist the operation couldnat be completed cocoa error 260nov 6 231904 lhdipod5 securityd78 error cfpropertylistreadfromfile file filelibrarykeychainsaccountstatusplist the operation couldnat be completed cocoa error 260nov 6 231904 lhdipod5 securityd78 error cfpropertylistreadfromfile file filelibrarykeychainsaccountstatusplist the operation couldnat be completed cocoa error 260nov 6 231905 lhdipod5 accountsd83 notice 20131106 231905058 accountsd8328531 acdclient name itunesstored bundle id null pid 90 is trying to verify account credentials for account nov 6 231905 lhdipod5 accountsd83 warning nsscanner nil string argumentnov 6 231906 lhdipod5 storebookkeeperd1585 warning uppsbdplaybackpositionstoragecontroller clearing all local changes that had been scheduled for pushnov 6 231906 lhdipod5 storebookkeeperd1585 warning uppsbdplaybackpositionstoragecontroller reseting sync anchor to 0 and scheduling pull from servernov 6 231906 lhdipod5 storebookkeeperd1585 warning uppsbdplaybackpositionstoragecontroller target sync date from client 20131106 174911 0 in 498 secnov 6 231906 lhdipod5 storebookkeeperd1585 warning uppsbdplaybackpositionstoragecontroller setting target date to 20131106 174911 0 in 6270845105369 secnov 6 231906 lhdipod5 storebookkeeperd1585 warning uppsbdplaybackpositionstoragecontroller scheduling sync via backgroundtaskjob 4982637 seconds from nownov 6 231906 lhdipod5 storebookkeeperd1585 warning uppsbdplaybackpositionstoragecontroller clearing all local changes that had been scheduled for pushnov 6 231906 lhdipod5 storebookkeeperd1585 warning uppsbdplaybackpositionstoragecontroller reseting sync anchor to 0 and scheduling pull from servernov 6 231906 lhdipod5 storebookkeeperd1585 warning uppsbdplaybackpositionstoragecontroller target sync date from database 20131106 174911 0 in 493 secnov 6 231906 lhdipod5 storebookkeeperd1585 warning uppsbdplaybackpositionstoragecontroller scheduling sync via backgroundtaskjob 4934034 seconds from nownov 6 231906 lhdipod5 storebookkeeperd1585 warning medialibrary rolling back transactionnov 6 231906 lhdipod5 storebookkeeperd1585 warning uppsbdplaybackpositionstoragecontroller clearing all local changes that had been scheduled for pushnov 6 231906 lhdipod5 storebookkeeperd1585 warning uppsbdplaybackpositionstoragecontroller reseting sync anchor to 0 and scheduling pull from servernov 6 231906 lhdipod5 storebookkeeperd1585 warning uppsbdplaybackpositionstoragecontroller target sync date from database 20131106 174911 0 in 487 secnov 6 231906 lhdipod5 storebookkeeperd1585 warning uppsbdplaybackpositionstoragecontroller scheduling sync via backgroundtaskjob 4870597 seconds from nownov 6 231906 lhdipod5 storebookkeeperd1585 warning medialibrary rolling back transactionnov 6 231906 lhdipod5 storebookkeeperd1585 warning uppsbdplaybackpositionstoragecontroller clearing all local changes that had been scheduled for pushnov 6 231906 lhdipod5 storebookkeeperd1585 warning uppsbdplaybackpositionstoragecontroller reseting sync anchor to 0 and scheduling pull from servernov 6 231906 lhdipod5 storebookkeeperd1585 warning uppsbdplaybackpositionstoragecontroller target sync date from database 20131106 174911 0 in 483 secnov 6 231906 lhdipod5 storebookkeeperd1585 warning uppsbdplaybackpositionstoragecontroller scheduling sync via backgroundtaskjob 4832559 seconds from nownov 6 231906 lhdipod5 accountsd83 error taskassert cfurlcache processcachetask failed to get taskassertion going commando with 1 items to processnov 6 231906 lhdipod5 storebookkeeperd1585 warning medialibrary rolling back transactionnov 6 231906 lhdipod5 voiced1814 warning error hex808 int2147483640 at sourcecachevoiceservicesvoiceservices2251daemonvsspeechserverm1286 destroying tts instancenov 6 231906 lhdipod5 medialibraryd1586 warning medialibrary medialibraryservice cancelling any active or suspended import operations in progress for process unknown process process id 1814nov 6 231906 lhdipod5 medialibraryd1586 warning medialibrary mlwriter cleaning up any remaining transactions for ended process unknown process process id 1814nov 6 231907 lhdipod5 securityd78 error cfpropertylistreadfromfile file filelibrarykeychainsaccountstatusplist the operation couldnat be completed cocoa error 260nov 6 231907 lhdipod5 securityd78 notice item secdbitemdoupdate replaced ogenpd374af13ldkuapple1233acctsvcev data20131106174029101178z5e4cddce with ogenpd374af13ldkuapple1233acctsvcev data20131106174907148855z02e51650 in secdbconnection rw opennov 6 231907 lhdipod5 securityd78 error cfpropertylistreadfromfile file filelibrarykeychainsaccountstatusplist the operation couldnat be completed cocoa error 260nov 6 231907 lhdipod5 securityd78 notice item secdbitemdoupdate replaced ogenp09a56blckapple1234acctsvcev data20131106174029147905z0b3ca9db with ogenp09a56blckapple1234acctsvcev data20131106174907195573z02078191 in secdbconnection rw opennov 6 231907 lhdipod5 backupd1815 warning info account changed enabled0 accountidnullnov 6 231907 lhdipod5 backupd1815 warning info account changed enabled0 accountidnullnov 6 231907 lhdipod5 kernel0 debug applekeystore operation failed pid 1815 sel 23 ret e02f0nov 6 231907 lhdipod5 kernel0 debug applekeystore operation failed pid 1815 sel 23 ret e02f0nov 6 231910 lhdipod5 wifid15 notice wifi405452950172733 client itunesstored set type to normal applicationnov 6 231910 lhdipod5 wifid15 notice wifi405452950173567 bg application present bg daemon present daemons apsd networkd sharingd nov 6 231910 lhdipod5 voiced1817 warning medialibrary database validation succeedednov 6 231910 lhdipod5 reportcrash1818 notice reportcrash acting against pid 1806nov 6 231911 lhdipod5 reportcrash1818 notice formulating crash report for process dentistgame1806nov 6 231911 lhdipod5 comapplelaunchd1 uikitapplicationcomdentistgametooth0xd1fe1806 warning uikitapplicationcomdentistgametooth0xd1fe job appears to have crashed segmentation fault 11nov 6 231911 lhdipod5 backboardd28 warning application uikitapplicationcomdentistgametooth0xd1fe exited abnormally with signal 11 segmentation fault 11nov 6 231911 lhdipod5 storebookkeeperd1585 warning uppsbdplaybackpositionstoragecontroller running synchronizeimmediatelywithcompletionhandler nownov 6 231911 lhdipod5 reportcrash1818 notice saved crashreport to varmobilelibrarylogscrashreporterdentistgame 20131106231910 lhdipod5plist using uid 0 gid 0 synthetic euid 501 egid 0nov 6 231911 lhdipod5 wifid15 notice wifi405452951855255 client itunesstored set type to background applicationnov 6 231911 lhdipod5 wifid15 notice wifi405452951856724 bg application present bg daemon present daemons itunesstored apsd networkd sharingd nov 6 231911 lhdipod5 wifid15 notice wifi405452951857583 already connected to lhd wifinov 6 231912 lhdipod5 storebookkeeperd1585 warning storebookkeeper sbktransactioncontrollerm457 transaction failed sbksynctransaction 0x17da6dd0 sync anchor0 error sbkstoreerror0x17ec20 error code sbkstoreerrorcodestoreaccountsessionexpired 1004nov 6 231912 lhdipod5 storebookkeeperd1585 warning uppsbdjobscheduler could not synchronize domain comappleupp sbkstoreerror0x17da5c30 error code sbkstoreerrorcodestoreaccountsessionexpired 1004 synchronization will be reattempted when the network connectivity or account status has changednov 6 231913 lhdipod5 wifid15 notice wifi405452953410312 client itunesstored set type to normal applicationnov 6 231913 lhdipod5 wifid15 notice wifi405452953412261 bg application present bg daemon present daemons apsd networkd sharingd nov 6 231913 lhdipod5 wifid15 notice wifi405452953577018 client itunesstored set type to background applicationnov 6 231913 lhdipod5 wifid15 notice wifi4054529535765 bg application present bg daemon present daemons itunesstored apsd networkd sharingd any help,"['ios', 'iphone']" +573716,date query with isodate in mongodb does not seem to work i do not seem to be able to get even the most basic date query to work in mongodb with a document that looks something like this id foobar201310 ap foobar dt isodate20131001t0z tl 375439and a query that looks like this dt gte date 20131001t0z i get 0 results from executingdbmycollectionfind dt gte date 20131001t0zany idea why this does not workfor reference this query is being produced by springs mongotemplate so i do not have direct control over the query that is ultimately sent to mongodbps dbversion247thanks,['javascript'] +573721,playback restricted on ios for vevo videos from youtube api i have embedded videos pulled from youtube api v3 into my iphone app using a uiwebview as suggested the problem is that some videos such as those from vevo produce the following error when attempting to play them on the devicethis video contains content from vevo it is restricted from playback on certain sitesthis should not occur since apps like flipboard and rockpack also seem to be using a uiwebview and are able to play videos from vevo and other sourceswhat could i be doing wrongps i am aware that there exist other posts that touch upon this issue in some way but they fail to address this specific problem,"['ios', 'iphone']" +573805,difference between thispatch async and thispatch sync on serial queue i have created a serial queue like this thispatch queue t serialqueue thispatch queue createcomexamplename thispatch queue serialwhats the difference between thispatch async called like this thispatch async serialqueue task 1 thispatch async serialqueue task 2 and thispatch sync called like this on this serial queue thispatch sync serialqueue task 1 thispatch sync serialqueue task 2 my understanding is that regardless of which thispatch method is used task 1 will be executed and completed before task 2 correct,['ios'] +573869,how can i use jasminejs to test for console output i am working through the text professional javascript for web developers by nicholas zakasand i am testing the examples with jasminejsi can currently test the output of a function by specifying a return a value but i am running into trouble when there are multiple pieces of data that i want to returnthe textbook uses the alert method but this is cumbersome and i do not know how to test for alerts i was wondering if there was a way to test for consolelog output for instancefunction to test function var person new object personname nicholas personage 29 returnpersonname nicholas returnpersonage 29i know i can have them return as one string but for more complicated examples i would like to be able to test the followingfunction to test function var person new object personname nicholas personage 29 consolelogpersonname nicholas consolelogpersonage 29the jasmine test looks something likeitshould test for the function to tests console output function expectfunction to testtoequalconsole output im testing foris there a simple way to do this that i am just missing i am pretty new to coding so any guidance would be appreciated,['javascript'] +573874,after anaconda installation conda command fails with importerror no module named condacli i installed 64 bit linux version of anaconda recently 180linuxx86 64 the installation seemed to work fine python python 275 continuum analytics inc default nov 4 2013 153026gcc 412 20080704 red hat 41254 on linux2type help copyright credits or license for more information import numpyno issues here however if i try any of the conda commands i get an error conda infotraceback most recent call last file anacondabinconda line 3 in module from condacli import mainimporterror no module named condacliinstallation is under my user directory anaconda i have verified that path contains anacondabin pythonpath is also set to anacondalib any thoughts on what is wrong with the conda command my searches do not appear to show any one else reporting this error,['python'] +573931,synchronized volatile and thread safety i am reading some books about java concurrency lately regarding thread safety if it is not possible to make a class inmutable you can always ensure thread safety by synchronizing its data the following class would be clearly not thread safepublic class notthreadsafe private int value public void setvalueint value thisvalue value public int getvalue return thisvalue then i can synchronize the write but it will remain not thread safepublic class stillnotthreadsafe private int value public synchronized void setvalueint value thisvalue value public int getvalue return thisvalue as i would need to synchronize not only the writes but also the readspublic class threadsafe private int value public synchronized void setvalueint value thisvalue value public synchronized int getvalue return thisvalue now the question is by using volatile i can guarantee that other threads will see the updated value so this makes me think that this class should be thread safepublic class notsure private volatile int value public synchronized void setvalueint value thisvalue value public int getvalue return thisvalue is the last class threadsafe,['java'] +573936,on android api 19 44 the intentcreatechooser method causes intentserviceleak running my app on the new android kitkat device api 19 44 i get copied to clipboard everytime i try to create an intent chooser this is happening on youtube tumblr and various other apps on android kitkat looking at the logs i am seeing the following exceptioncomandroidinternalappchooseractivity has leaked intentreceiver comandroidinternalappresolveractivity14150aac8this used to be an issue caused when a device did not have multiple apps to intent to see why does intentcreatechooser need a broadcastreceiver and how to implement however this is not the case on my device seems like something is broken in android api 19,['android'] +573943,locking portrait orientation in view ios 7 so i want to lock the orientation of my home page to portrait and the home page onlyi am using a tab bar controller so the initial view is the tab controller but the view controller that appears first is the first tab eg the home pagei would like to make it so that when the user goes to rotate the device it will not rotate to landscape on this page however all other pages can rotatei have searched around and nothing seems to be specific to ios 7 and the one that is specific to ios 7 does not workaplease help thank youthe image below describes what i dont want to happen for this page,['ios'] +573946,java monitor active web sessions i need to implement a web based application that once deployed on tomcat can monitor active sessions of all applications deployed on same tomcat let us say tomcat has 2 applications running as 1 reportgenerator 2 datasyncmanager i need to show active sessions for these 2 applications with below statsseesion application session start time1234 reportgenerator x56748 datasyncmanager x565 datasyncmanager xalso i have a requirement to kill session on the fly is it possible please advice i know this is something similar admin console of tomcat was but i need to implement it as a custom application with custom logging and monitoring feature please advice me on which frameworkapi i can use to capture active sessions on tomcat and their stats,['java'] +574009,signing apk with p12 i am going to update my clients app which is available on google playstoreand i have only a p12 file with password not keystore filei am wondering if it is possible to publish the updated version to google playstoresorry for basic question i am so confused with that thank you in advance for your assistance,['android'] +574089,using thispatch once t per object and not per class there are multiple sources calling a particular method but i would like to ensure that it is called exactly once per objecti would like to use syntax like method called possibly from multiple places threadsvoidfinish static thispatch once t oncetoken thispatch onceoncetoken self finishonce should happen once per object should only happen once per objectvoid finishonceproblem is the token is shared accross all instances of the same class so not a good solution is there a thispatch once t per object if not what is the best way to ensure it is called onceedithere is a proposed solution i am thinking of does it seem alrightinterface myclassproperty nonatomicstrong thispatch queue t thispatchonceserialqueue a serial queue for ordering of query to a ivarproperty nonatomic bool didrunexactlyoncetokenendimplementation myclassvoidrunexactlyoncemethod block bool didalreadyrun no thispatch syncselfthispatchonceserialqueue didalreadyrun didrunexactlyoncetoken if didrunexactlyoncetoken no didrunexactlyoncetoken yes if didalreadyrun yes return do some work once,['objective-c'] +574123,can i refactor to model view query handler in our mvc application all of our read actions as a paramter take a query which implementspublic interface iqueryout tresponse within the action the query is passed to a bus which locates a handler and returns a view model so controllers now look something like this public actionresult editdetailsquery query var model mediatorrequestquery return viewmodel effectively just passing queries to our mediator and returning the result we have hundreds of actions that look like this there is the odd action that does something conditional which i would leave as they are but the rest are just the same boilerplate again and again we have over hundred different querieshow can i refactor this to something more explicit i guess moving to a model view query handler rather than the boilerplate controller action that just hands off query to the bus and returns model to view what extension points should i look at in mvc effectively instead of having to write the action handler just have some automatic way of wiring together strongly typed query and getting back the correct viewmodelif i can should i i just do not like seeing hundreds of actions that all look the same,['c#'] +574139,unicodeencodeerror ascii codec cannot encode character uxe9 in position 7 ordinal not in range128 i have this code printinfo title t old vendor id t apple id n write file fwrite printinfo nbut i get this error when running it fwriteprintinfo nunicodeencodeerror ascii codec cannot encode character uxe9 in position 7 ordinal not in range128it is having toruble writing out thisidentita secra te abduction vfany ideas please not sure how to fixcheersupdatethis is the bulk of my code so you can see what i am doingdef runlookupeditself event newpath1 pathindir errorfileout newpath1 reportcsv f openerrorfileout wglobal old vendor idfor old vendor id in vendoridsinsplitlines writeerrorfile 0 from lxml import etree parser etreexmlparserremove blank texttrue makes pretty print work path1 ospathjoinpathindir old vendor id path2 path1 itmsp path3 ospathjoinpath2 metadataxml open and parse the xml file cantfinderror 0 try with openpath3 pass except ioerror cantfinderror 1 errormessage old vendor id selferrorerrormessage break tree etreeparsepath3 parser root treegetroot for element in treexpathvideotitle title elementtext while n in title title titlereplacen while t in title title titlereplacet while in title title titlereplace title titlestrip elementtext title print title remove unwanted tags remove the comment tags comments treexpathcomment q 1 for c in comments p cgetparent if q 3 apple id ctext premovec q q1 apple id apple idsplit11 apple id apple idstrip printinfo title t old vendor id t apple id write file fwrite printinfo n fwriteprintinfoencodeutf8 nfclose,['python'] +574169,css thisplay table cell requires percentage width i have been put in a position where i need to use the thisplaytablecell command for div elementshowever i have thiscovered that the cells will only work correctly if a percentage is added to the widthin this fiddle when i remove the percentage width the cells do not have equal widths however when a percentage value is added to the width all is well but only when that percentage is equal to the proportion of max no of divs so for four columns 25 five 20 and in this case five at 16i thought maybe adding a percentage of less say 1 would be a good fix all but the cells fall out of line againwhy is this table thisplay table height 200px width 100 cell thisplay tablecell height 100 padding 10px width 16 grey backgroundcolor 6 height 100 textalign center fontsize 48px color f fontfamily helvetica neue helvetica arial sansserif fontweight 300 div classtable div classcell div classgreyblock onediv div div classcell div classgreyblock twodiv div div classcell div classgreyblock threediv divdivdiv classtable div classcell div classgreyblockdiv div div classcell div classgreyblock twodiv divdivdiv classtable div classcell div classgreyblock onediv div div classcell div classgreyblock twodiv div div classcell div classgreyblock threediv div div classcell div classgreyblock fourdiv divdivdiv classtable div classcell div classgreyxdiv div div classcell div classgreyxxdiv div div classcell div classgreyxdiv div div classcell div classgreyxdiv div div classcell div classgreyxdiv div div classcell div classgreyblock five testdiv divdivdiv classtable div classcell div classgreyblockdiv div div classcell div classgreyblock twodiv div div classcell div classgreyblock threediv divdiv,"['html', 'css']" +574257,volley jsonobjectrequest post request not working i am using android volley for making a request so i use this code i do not understand one thing i check in my server that params is always null i consider that getparams not working what should i do to solve this issue requestqueue queue myvolleygetrequestqueue jsonobjectrequest jsobjrequest new jsonobjectrequestrequestmethodpostsphere urlnull new responselistenerjsonobject override public void onresponsejsonobject response systemoutprintlnresponse hideprogressdialog new responseerrorlistener override public void onerrorresponsevolleyerror error hideprogressdialog protected mapstring string getparams throws authfailureerror mapstring string params new hashmapstring string paramsputid1 paramsputname myname return params queueaddjsobjrequest,['android'] +574304,angularjs wait for template to be evaluated before directive loads the situationlets say i have a directive that has to access certain elements via id inside the element on which the directive is defined the problem that can occur is that by the time the directive is evaluated the childelements are not yet the result is that i am not able to access those elements by their idexamplefiddlediv ngcontrollermyctrl div colorelementid div ngrepeatitem in items id itemid itemname div divdivscript var myapp angularmodulemyapp myappdirectivecolor function return restrict a link function scope element attributes var name attributescolor el element0 scopewatchname function var id scopename consolelogid id1 consolelogelementchildreneq0attrid itemid elementfindidcssbackgroundcolorred function myctrlscope scopeitems idid1 nameitem1 idid2 nameitem2 scopeelementidid1 scriptso my directive should just paint the backgroundcolor of the element with the id in scopeelementid btw i know i can handle this simple example much easier it should just illustrate the general issuethe problem is that the ids of the elements inside ngrepeat are not there yet as pointed out in the comment in the code the id is still itemid so angular did not evaluate this part yetquestionmy obvious question is now how can i make my directive to wait for descendent elements to be completely evaluatedfurther explainationin my real application i want to have a directive that enables me to scroll to a certain elements on the page i also use a pagination directive to split up the elements i want to show because of the pagination only the elements that are really visible are in the dom so the invisible elements are already filtered out in my controlleri also have a sidebar where are small links to all the elements not only the visible ones when someone clicks on an element in the sidebar two events should occurjump to the correct page scroll to the corrent elementwhen i jump to the page i basically have the situation i described above i have a complete new list of elements that have to be processed by ngrepeat but directly after that i try to tell my scrolldirective that it should scroll the element with the id xy but this id is not assigned yet,['javascript'] +574312,wix install prerequisites and 3rd party applications i have a wix windows installer for my c application things are working i am able to install and uninstall the application but i have few prerequisites and other 3rd party applications that i want to install with my applicationprerequisitesmicrosoft net framework 4 x86 and x64 dotnetfx40 full x86 x64exesql server 2008 expresqlexpr x64 enuexesqlexpr32 x86 enuexesql server compact 35 sp2ssceruntimeenumsissceruntimeenux64msi3rd party applicationteamviewer teamviewer setupexeso ofcourse i am not looking for complete guidelines for all the prerequisites and 3rd party applications i just need you folks help on figuring out on how exactly i can embed these exe and msi setups to be a part of my wix installationalso some are for x64 and some are for x86 so it should be capable enough to handle the os version and architecture how will this be accomplished with wixi have been searching on internet for a while now and nothing concrete seems to be working for mei need to make sure that if these applications are not installed then the software should also not install along with that if any of the prerequisite or 3rd party application is already installed then it should not install againi guess this can be done using some wix tools but i am not able to get any concrete instructions on howtoedit 1ok i have got the microsoft net framework 4 x86 and x64 installed and the problem which i am facing now is i am unable to install sql server compact 35 sp2 i am doing things one by one to make things more clear to me here under i am sharing my code so that you people can reviewxml version10 encodingutf8wix xmlns xmlnsutilbundle namebootstrapper version10 manufacturerbilly upgradecode4a2346e9a12643fba35205a95623e0d4 bootstrapperapplicationref idwixstandardbootstrapperapplicationrtflicense chain packagegroupref idnetfx4full packagegroupref idsqlexpressce install application msipackage idmyapplication sourcefilevarinstallertargetpath chainbundlefragment check for net 40 utilregistrysearch roothklm keysoftwaremicrosoftnet framework setupndpv4full valueversion variablenetfx4fullversion utilregistrysearch roothklm keysoftwaremicrosoftnet framework setupndpv4full valueversion variablenetfx4x64fullversion win64yes install net 40 packagegroup idnetfx4full exepackage idnetfx4full thisplaynamemicrosoft net framework 40 compressedno cacheyes permachineyes permanentyes protocolnetfx4 vitalyes sourcefileprerequisitesdotnetfx40 full x86 x64exe installcommandpassive norestart detectconditionnetfx4fullversion and not versionnt64 or netfx4x64fullversion packagegroup install sql server ce packagegroup idsqlexpressce msipackage cacheno compressedno forcepermachineyes permanentyes vitalyes sourcefileprerequisitesceruntimeenumsi installconditionnot versionnt64 and sqlinstance and sqlserverinstalled and sqlserver2008r2installed msipackage cacheno compressedno forcepermachineyes permanentyes vitalyes sourcefileprerequisitesceruntimeenux64msi installconditionversionnt64 and not sqlinstance and sqlserverinstalled and sqlserver2008r2installed packagegroupfragmentwixnote the above code installs net framework its not installing sql server compact 35 sp2edit 2after referring tom blodget answer i have reached to this far however i am unable to understand how to give the install command for my sql exe package and same for my msi package i have also gone through this answer of mr neil sleightholm but this one is for sql 2012 how can i do this same thing with sql 2008 server and ce the conditions and stepspackagegroup idsqlexpressce exepackage cacheno compressedno permanentno vitalyes installcommandqs actioninstall iacceptsqlserverlicenseterms browsersvcstartuptypeautomatic sqlsvcstartuptypeautomatic featuressql instancenamesqlexpress sqlsvcaccountquotnt authoritynetwork servicequot sqlsysadminaccountsquotbuiltinadministratorsquot agtsvcaccountquotnt authoritynetwork servicequot securitymodesql sapwdquotwegamedquot sourcefileprerequisitessqlexpr32 x86 enuexe downloadurl x86 enuexe installconditionnot sqlserver2008r2installed and not sqlserverinstalled exepackage detectconditionversionnt64 cacheno compressedno permanentno vitalyes installcommandqs actioninstall iacceptsqlserverlicenseterms browsersvcstartuptypeautomatic sqlsvcstartuptypeautomatic featuressql instancenamesqlexpress sqlsvcaccountquotnt authoritynetwork servicequot sqlsysadminaccountsquotbuiltinadministratorsquot agtsvcaccountquotnt authoritynetwork servicequot securitymodesql sapwdquotwegamedquot sourcefileprerequisitessqlexpr x64 enuexe downloadurl x86 enuexe installconditionnot sqlserver2008r2installed and not sqlserverinstalled packagegroupbut setup is unable to complete i guess it is because of the install commands as it works till accept licence agreement,['c#'] +574344,bootstrap glyphicons error 404 in production i am using bootstrapsassrails this issue and when i run my rails project in production mode i get 3x 404 errorsget httplocalhost30assetstwitterbootstrapglyphiconshalflingsregularwoff 404 not found assetstwitterbootstrapglyphiconshalflingsregularwoff1get httplocalhost30assetstwitterbootstrapglyphiconshalflingsregularttf 404 not found assetstwitterbootstrapglyphiconshalflingsregularttf1get httplocalhost30assetstwitterbootstrapglyphiconshalflingsregularsvg 404 not found i used rake assetsprecompile rails envproduction to generate static files with result i 20131107t165225269370 12948 info writing myprojectpublicassetsapplication3517eb39b597107b3dbccbcbf4f0b3ccjsi 20131107t165225315358 12948 info writing myprojectpublicassetsapplication1459bfe79a6477170658d53257e4a8fdcssi 20131107t165225334356 12948 info writing myprojectpublicassetstwitterbootstrapglyphiconshalflingsregular8b1bdc16b9e098d67afebbf8d59fcea7eoti 20131107t165225345360 12948 info writing myprojectpublicassetstwitterbootstrapglyphiconshalflingsregular8d8305e5b6a807076d3ec68e2f190674svgi 20131107t165225357360 12948 info writing myprojectpublicassetstwitterbootstrapglyphiconshalflingsregular946071b70245967633bb3a774c60f3a3ttfi 20131107t165225367360 12948 info writing myprojectpublicassetstwitterbootstrapglyphiconshalflingsregulard7e2274ad1d940a0b2ce7480810ab223woffetc all assets are working fine except these 3 font files i searched all day long and did not find anything it seems rails is looking for the version without hash of these 3 files but rake generates them with hashmy configproductionrb configcache classes true configeager load true configconsider all requests local false configaction controllerperform caching true configserve static assets true configassetsjs compressor uglifier configassetscompile false configassetsdigest true configassetsversion 10 configlog level info configi18nfallbacks true configactive supportdeprecation notifyediti tried to override the fontface variable but it does not seem to remove old variablesfontface fontfamily glyphicons halflings src asseturltwitterbootstrapglyphiconshalflingsregulareotfont src asseturltwitterbootstrapglyphiconshalflingsregulareotiefixfont formatembeddedopentype asseturltwitterbootstrapglyphiconshalflingsregularwofont formatwoff asseturltwitterbootstrapglyphiconshalflingsregularttffont formattruetype asseturltwitterbootstrapglyphiconshalflingsregularsvgglyphiconshalflingsregularfont formatsvgi now have glyphicons loaded but still 3x 404 errors,['ruby-on-rails'] +574371,android default apptheme background colors what are the default background colors for activities in androids apptheme stylei am looking for the hex code or something that i can reference it should be one for the light theme and one for the dark themeor where can i look them up i am confused by all the files and cannot find the place where they actually say the colorthanks for your helpupdatei found entries in the sdk in datavaluescolorsxml which are referenced byandroidcolorbackground holo lightandroidcolorbackground holo darkbut i cannot put them as background color of my views it is giving an error saying the values are not public is there a workaround,['android'] +574417,increasing screen capture speed when using java and awtrobot edit if anyone also has any other recommendations for increasing performance of screen capture please feel free to share as it might fully address my problemhello fellow developersi am working on some basic screen capture software for myself as of right now i have got some proof of concepttinkering code that uses javaawtrobot to capture the screen as a bufferedimage then i do this capture for a specified amount of time and afterwards dump all of the pictures to thisk from my tests i am getting about 17 frames per secondtrial 1length 15 secondsimages captured 255trial 2length 15 secondsimages captured 229obviously this is not nearly good enough for a real screen capture application especially since these capture were me just selecting some text in my ide and nothing that was graphically intensive i have two classes right now a main class and a monitor class the monitor class contains the method for capturing the screen my main class has a loop based on time that calls the monitor class and stores the bufferedimage it returns into an arraylist of bufferedimagesif i modify my main class to spawn several threads that each execute that loop and also collect information about the system time of when the image was captured could i increase performance my idea is to use a shared data structure that will automatically sort the frames based on capture time as i insert them instead of a single loop that inserts successive images into an arraylistcodemonitorpublic class monitor returns a bufferedimage return public bufferedimage capturescreen rectangle screenrect new rectangletoolkitgetdefaulttoolkitgetscreensize bufferedimage capture null try capture new robotcreatescreencapturescreenrect catch awtexception e eprintstacktrace return capturemainpublic class main public static void mainstring args throws interruptedexception string outputlocation cusersewillispicturesscreenstreamer string namingscheme image string mediaformat jpeg thiscreteoutput output thiscreteoutputfactorycreateoutputobjectoutputlocation namingscheme mediaformat arraylistbufferedimage images new arraylistbufferedimage monitor m1 new monitor long starttimemillis systemcurrenttimemillis long recordtimemillis 150 while systemcurrenttimemillis starttimemillis recordtimemillis imagesadd m1capturescreen outputsaveimagesimages,['java'] +574432,pattern matching on a string that already has wildcards in it i have a scenario where i would like to search using a wildcarded pattern ontop of a string that already has wildcards in it in my words i would say it is a 2 way pattern matching requirementthe input and pattern string can have eitherboth of the following wildcards representing a single character and representing zero or more characters assume these are the only 2 wildcards allowed in input and the pattern stringsfor ex bool ismatchstring input string pattern should return true if the input string matches the pattern should return false otherwiseismatchxyz y should return trueismatchyy y should return true last character in input string expects a single character where as the pattern matches to zero or more characters after y which means it includes a single character match as wellismatchx123 y should return false missing y in the input string which the pattern expectsismatchy y should return trueismatch y should return true the input string has a wildcard representing zero or more characters and can also have any characters in a way it acts as a pattern in itself representing anything of any sizei am able to find articles ex regex that only talk about performing a wildcarded pattern match on a nonwildcarded string i am looking for pointersideas on the algorithm as it is getting difficult for me to come up with an algorithm that can do this kind of match as i start putting it down appreciate your inputs,['c#'] +574470,is there a way to remove all sessionstorage items with keys that match a certain pattern lets say my sessionstorage contains three objects whos keys are foo foobar and baz is there a way that i can call removeitem or somehow delete all items in sessionstorage whos keys match foo in this example i would be left with only the item whos key is baz,['javascript'] +574498,adding strings in javascript 1 2 12 i accidentally typed the following javascript statement 1 2 and i have the result 12i am not sure why the minus sign was treated as a string rather than causing a syntax error i tried to search but i did not get the answer i wanted why the minus sign was treated as a string it there online reference i can look at thanks,['javascript'] +574512,angularjs how to dynamically add html and bind to controller i am just getting started with angularjs and struggling to figure out proper architecture for what i am trying to do i have a single page app but the url always should stay the same i do not want the user to be able to navigate to any routes beyond the root in my app there is one main div that will need to host different views when a new view is accessed i want it to take over the thisplay in the main div views loaded in this way can be throwaway or stick around as hidden in the dom i am interested in seeing how each might worki have come up with a rough working example of what i am trying to do see working example here in this plunk basically i want to dynamically load html into the dom and have standard angularjs controllers be able to hook into that new html is there a bettersimpler way to do this than by using the custom directive i have here and using compile to hook up to angular perhaps there is something sort of like the router but does not require url has changes to operateheres the special directive i am using so far taken from another so post stolen from myappdirectivedynamic function compile return replace true link function scope ele attrs scopewatchattrsdynamic functionhtml if html return elehtmltypeofhtml string html htmldata compileelecontentsscope thanksandy,['javascript'] +574561,how to call method in window xamlcs from viewmodel cs without introducing new references in wpf i am looking for a simple way to call a method in my main window but i want to call it from my view model basically i am looking for some king of thisparent sort of thing to put in the view model to reference the main windowor if you want to check out the reason i want to do this and tell me another way to go about my problemi am working with an app that constantly gets information fed to it in the viewmodel the information is processed i want to make a notification every time a piece of information comes in that satisfies some qualificationinitially i had a dictionary in the viewmodel that stored info about that information and i accessed that dictionary in the mainwindow so that i could make the window flash and send other notifications but i was getting issues with the viewmodels dictionary being continuously changed while i was accessing it in the mainwindowsorry if this question sounds stupid i just started with wpf two months ago and did not have a great background in programming even before that either,['c#'] +574564,faster alternative to seriesadd function in pandas i am trying to add two pandas series together the first series is very large and has a multiindex the index of the second series is a small subset of the index of the first df1 pddataframenpones1050dtypeintstack df1 pddataframedf1 columns total df2 pdconcatdf1iloc5055df1iloc202005 df2 is tiny subset of df1using the regular seriesadd function takes about 9 seconds the first time and 2 seconds on subsequent tries maybe because pandas optimizes how the df is stored in memory starttime timetime df1totaladf2totalfill value0sum print method 1 took f seconds timetime starttimemanually iterating over rows takes about 23 as long as seriesadd the first time and about 1100 as long as seriesadd on subsequent tries starttime timetime result df1totalcopy for row index row in df2iterrows resultrow index row print method 2 took f seconds timetime starttimethe speed difference is particularly noticeable when as here the index is a multiindex why does seriesadd not work well here any suggestions for speeding this up is there a more efficient alternative to iterating over each element of the series also how do i sort or structure the data frame to improve the performance of either method the second time either of these methods is run is appreciably faster how do i get this performance on the first time sorting using sort index helps only marginally,['python'] +574566,which greedy initializerlist examples are lurking in the standard library since c11 the standard library containers and stdstring have constructors taking an initializerlist this constructor takes precedence over other constructors even as pointed out by johannesschaublitb in the comments even ignoring other best match criteria this leads to a few wellknown pitfalls when converting all parenthesized forms of constructors to their braced versions include algorithminclude iostreaminclude iteratorinclude vectorinclude stringvoid printstdvectorint const v stdcopybeginv endv stdostream iteratorintstdcout stdcout nvoid printstdstring const s stdcout s nint main wellknown printstdvectorint 11 22 11 22 not 11 copies of 22 printstdvectorint 11 11 not 11 copies of 0 more surprising printstdstring 65 c ac not 65 copies of ci could not find the third example on this site and the thing came up in the loungec chat in thiscussion with rightfold abyx and jerrycoffin the somewhat surprising thing is that converting the stdstring constructor taking a count and a character to use instead of changes its meaning from n copies of the character to the nth character typically from the ascii table followed by the other characterthis is not caught by the usual brace prohibition on narrowing conversions because 65 is a constant expression that can be represented as a char and will retain its original value when converted back to int a8547 bullet 4 thanks to jerrycoffinquestion are there more examples lurking in the standard library where converting a style constructor to style is greedily matched by an initializerlist constructor,['c++'] +574573,how to build a no install clientside only database web app where i work it is pretty restricted in terms of iti do not have access to an sql server or a web server so things like apache php mysql etc are all off the table no server side anythingthe pcs on the network cannot see each other so installing wamp and opening firewall ports wouldnt workbesideswe cant install anything eitherall locked down this is due to group policy restrictions however there are plenty of shared drives that we all can use currently we are getting by using microsoft access but it is clunkywe need to move towards tablets so managers can see info as they walk around my building is a massive warehouse hence the driver for the solution im trying to buildso the question is this i want to build a web app that thisplays kpisreports it will need to have some type of database behind it so i can store data in which i can then retrieve via javascript or something similar remember i can only use clientside technolgies whether that is json or xml i dont really mindmultiple people will need access at the same time so to sum upcannot install anythingno access to a web server or anything that resembles a web serverdo have shared drives so could store a nosqljsonxml file to share thereclientside technologies onlypcs on the network cannot see each othercannot use any internet or cloud storage solutions as they are blockedim completely lost any solutions,"['javascript', 'html']" +574584,need help to implement 47degree androidswipelistview need help to implement 47degree androidswipelistviewlibrary url full fledge working exampleproblemevery time i try to implement swipelistview in my activity listview i get new problems lastly i tried to include compiled and thistributed jar to my project and implement it it was compiling correctly but when i was trying to run it on the device or avd it was crashing with exception classnotfoundexception for swipelistviewtouchlistener and many moretool i am usingandroid studiowhat i needi would be and many more developers looking around for same solution very grateful if someone can provide very basic example using this libraryno need to provide fully working kind of applicationdemo code with front and back view for listview item working while left and right sliding would be fineno need to implement all settings of the librarythe motive of this question is to get idea about how to wireup 47degree swipelistview library into your application and make it working rest things programmer who is using it should be able to find out from api documentationany help on this would be very useful as i am working on one small application where i want to implement such functionality,['android'] +574593,group by case statement i have a working query that is grouping data by hardware model and a result but the problem is there are many results i have tried to reduce that down to if result 0 then keep as 0 else set it to 1 this generally works but i end up having day name type case count 20131106 modela 1 0 972 20131106 modela 1 1 42 20131106 modela 1 1 2 20131106 modela 1 1 11 20131106 modelb 1 0 456 20131106 modelb 1 1 16 20131106 modelb 1 1 8 20131106 modelb 3 0 21518 20131106 modelb 3 1 5 20131106 modelb 3 1 7 20131106 modelb 3 1 563instead of the aggregate i am trying to achieve where only 1 row per typecase combo day name type case count 20131106 modela 1 0 972 20131106 modela 1 1 55 20131106 modelb 1 0 456 20131106 modelb 1 1 24 20131106 modelb 3 0 21518 20131106 modelb 3 1 575here is my queryselect current date1 as day modelname attempttype case when attemptresult 0 then 0 else 1 end count from attempt attempt prod hw id prod hw id model modelwhere time 20131106 0 and time 20131107 0and attempthard id prod hw idhard idand prod hw idmodel id modelmodel idgroup by modelname attempttype attemptresultorder by modelname attempttype attemptresultany tips on how i can achieve this would be awesomeday will always be defined in the where clause so it will not vary name type resultcase and count will vary in short for any given model i want only 1 row per type case combo as you can see in the first result set i have 3 rows for modela that have type1 and case1 because there are many result values that i have turned into 00 and anything else1 i want that to be represented as 1 row with the count aggregated as in example data set 2,['sql'] +574679,how to make a social sharing exception for twitter action sheet i am using the following code to call action sheet sharing in my app ibactionsendpostidsender nsarray activityitems nil uiimage appicon uiimage imagenamedappiconpng nsstring posttext nsstring alloc initwithformatlets assume this string is longer than 140 characters that twitter prohibits but can still be shared via facebook email text activityitems posttextappicon uiactivityviewcontroller activitycontroller uiactivityviewcontroller alloc initwithactivityitemsactivityitems applicationactivitiesnil self presentviewcontrolleractivitycontroller animatedyes completionnilthe problem is this posttext is longer than 140 characters so sharing via twitter will not be possible the character count will be x red number of characters you are over in order to share via twitter my question is this how can i make an exception so that a different message say shortposttext will be the one used when twitter is selected for sharingand once the sendpost action is sent i do not see a way to explicitly set a string for twitter once you are hereedit i dont understand why someone would downvote this question i am not asking how to make an ifelse statement or how to program this is a genuine question that needs a genuine answerupdate i need a work around this because this is what i get when a user tries to share via twitter in my app a rednegative character indicator and a nonactive post button so unless that character count goes down to 0 or less it will not allow the post to go to twitter,"['ios', 'objective-c']" +574685,convert any data type into nsdata and back again i am working on an app where you can send either a text image or a contact over multipeer connectivity to another device it will then save in the second devices core datawhat i do is send the data over as an nsdictionary and convert it back again so i am left with an nsdictionary on the receiving device how then can i save the object for the key of objectdata to core data i would like it to work with nsstring uiimage abperson create a new object in the managed object context received receiveddata nsentitydescription insertnewobjectforentityfornamereceived inmanagedobjectcontextselfmanagedobjectcontext assign the properties based on what was input in the textfields check what type it is nsstring datatype dictionary objectforkeytype receiveddatatype datatype determine what type of data was passed over if datatype isequaltostringphoto receiveddataobject uiimagejpegrepresentationdictionary objectforkeyobject 05f nsloga photo saved in core data else receiveddataobject nskeyedarchiver archiveddatawithrootobjectdictionary objectforkeyobject receiveddataobject dictionary objectforkeyobject datausingencodingnsutf8stringencoding save the managed object context nserror error nil selfmanagedobjectcontext saveerrori do not particularly want to do the if else if statements to determine how to convert it core data as it would then be repeated when i thisplay the data hoe else can i do it i am currently getting errors with the nskeyedarchiver type which i am unsure why and hence it is commented outany help would be much appreciated,['objective-c'] +574721,get size of string w encoding in bytes without converting to byte i have a situation where i need to know the size of a stringencoding pair in bytes but cannot use the getbytes method because 1 the string is very large and duplicating the string in a byte array would use a large amount of memory but more to the point 2 getbytes allocates a byte array based on the length of the string the maximum possible bytes per character so if i have a string with 15b characters and utf16 encoding getbytes will try to allocate a 3gb array and fail since arrays are limited to 232 x bytes x is java version specificso is there some way to calculate the byte size of a stringencoding pair directly from the string objectupdateheres a working implementation of jtahlborns answerprivate class countingoutputstream extends outputstream int total override public void writeint i throw new runtimeexceptiondo not use override public void writebyte b total blength override public void writebyte b int offset int len total len,['java'] +574727,android opengl camera preview issue i am working on an android camera app that modifies the camera feed and thisplays it live on the screen i have it working and doing what i want perfectly on my droid razr maxx running 43 and it works perfect on other phones but unfortunately i have ran into a problem on several phones and am unable to track down the issuei have attached a screenshot showing what the issue isit is very hard to tell what the green artifacts are but it almost looks like it is blocks from the camera feed from when it first turned on the colors flicker but the shapes inside the blocks do not really changei have stripped out everything that is not needed and cleaned up the code as best i can but i honestly have zero clue as to why this is happening especially since it seems to work on some phones fine while other phones it does notif i need to give more information just comment and i will add itcameraactivityjavapublic class cameraactivity extends activity private myglsurfaceview glsurfaceview private mycamera mcamera override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate mcamera new mycamera glsurfaceview new myglsurfaceviewthis mcamera setcontentviewglsurfaceview override protected void onpause superonpause mcamerastop mycamerajavapublic class mycamera private final static string log tag mycamera private camera mcamera private parameters mcameraparams private boolean running false void startsurfacetexture surface logvlog tag starting camera mcamera cameraopen0 mcameraparams mcameragetparameters logvlog tag mcameraparamsgetpreviewsizewidth x mcameraparamsgetpreviewsizeheight try mcamerasetpreviewtexturesurface mcamerastartpreview running true catch ioexception e eprintstacktrace void stop if running logvlog tag stopping camera mcamerastoppreview mcamerarelease running false myglsurfaceviewjavaclass myglsurfaceview extends glsurfaceview implements renderer private final static string log tag myglsurfaceview private mycamera mcamera private surfacetexture msurface private directvideo mdirectvideo public myglsurfaceviewcontext context mycamera camera supercontext mcamera camera seteglcontextclientversion2 setrendererthis override public void ondrawframegl10 gl float mtx new float16 msurfaceupdateteximage msurfacegettransformmatrixmtx mdirectvideodraw override public void onsurfacechangedgl10 gl int width int height logvlog tag surface changed gles20glviewport0 0 width height override public void onsurfacecreatedgl10 gl eglconfig config logvlog tag surface created int texture createtexture mdirectvideo new directvideotexture msurface new surfacetexturetexture mcamerastartmsurface private int createtexture int textures new int1 generate one texture pointer and bind it as an external texture gles20glgentextures1 textures 0 gles20glbindtexturegles11extgl texture external oes textures0 no mipmapping with camera source gles20gltexparameterfgles11extgl texture external oes gl10gl texture min filter gl10gl linear gles20gltexparameterfgles11extgl texture external oes gl10gl texture mag filter gl10gl linear clamp to edge is only option gles20gltexparameterigles11extgl texture external oes gl10gl texture wrap s gl10gl clamp to edge gles20gltexparameterigles11extgl texture external oes gl10gl texture wrap t gl10gl clamp to edge return textures0 public static int loadshaderint type string shadercode create a vertex shader type gles20gl vertex shader or a fragment shader type gles20gl fragment shader int shader gles20glcreateshadertype add the source code to the shader and compile it gles20glshadersourceshader shadercode gles20glcompileshadershader return shader directvideojavapublic class directvideo private final string vertexshadercode attribute vec4 vposition attribute vec2 inputtexturecoordinate varying vec2 texturecoordinate void main gl position vposition texturecoordinate inputtexturecoordinate private final string fragmentshadercode extension gl oes egl image external requiren precision mediump float varying vec2 texturecoordinaten uniform samplerexternaloes s texturen void main gl fragcolor texture2d s texture texturecoordinate n private floatbuffer vertexbuffer textureverticesbuffer private shortbuffer drawlistbuffer private final int mprogram private int mpositionhandle private int mtexturecoordhandle private short draworder 0 1 2 0 2 3 order to draw vertices number of coordinates per vertex in this array private static final int coords per vertex 2 private final int vertexstride coords per vertex 4 4 bytes per vertex static float squarecoords 10f 10f 10f 10f 10f 10f 10f 10f static float texturevertices 00f 10f 10f 10f 10f 00f 00f 00f private int texture public directvideoint texture thistexture texture initialize vertex byte buffer for shape coordinates bytebuffer bb bytebufferallocatedirectsquarecoordslength 4 bborderbyteordernativeorder vertexbuffer bbasfloatbuffer vertexbufferputsquarecoords vertexbufferposition0 initialize byte buffer for the draw list bytebuffer dlb bytebufferallocatedirectdraworderlength 2 dlborderbyteordernativeorder drawlistbuffer dlbasshortbuffer drawlistbufferputdraworder drawlistbufferposition0 bytebuffer bb2 bytebufferallocatedirecttextureverticeslength 4 bb2orderbyteordernativeorder textureverticesbuffer bb2asfloatbuffer textureverticesbufferputtexturevertices textureverticesbufferposition0 int vertexshader myglsurfaceviewloadshadergles20gl vertex shader vertexshadercode int fragmentshader myglsurfaceviewloadshadergles20gl fragment shader fragmentshadercode mprogram gles20glcreateprogram create empty opengl es program gles20glattachshadermprogram vertexshader add the vertex shader to program gles20glattachshadermprogram fragmentshader add the fragment shader to program gles20gllinkprogrammprogram creates opengl es program executables public void draw gles20gluseprogrammprogram gles20glactivetexturegles20gl texture0 gles20glbindtexturegles11extgl texture external oes texture get handle to vertex shaders vposition member mpositionhandle gles20glgetattriblocationmprogram vposition enable a handle to the triangle vertices gles20glenablevertexattribarraympositionhandle prepare the insert shape here coordinate data gles20glvertexattribpointermpositionhandle coords per vertex gles20gl float false vertexstride vertexbuffer mtexturecoordhandle gles20glgetattriblocationmprogram inputtexturecoordinate gles20glenablevertexattribarraymtexturecoordhandle gles20glvertexattribpointermtexturecoordhandle coords per vertex gles20gl float false vertexstride textureverticesbuffer gles20gldrawelementsgles20gl triangles draworderlength gles20gl unsigned short drawlistbuffer thisable vertex array gles20glthisablevertexattribarraympositionhandle gles20glthisablevertexattribarraymtexturecoordhandle,['android'] +574737,specifying goal in pomxml i am creating a new maven project with pomxml as belowproject xmlns xmlnsxsi xsischemalocation modelversion400modelversion groupidfirstrestletgroupid artifactidrestlet1artifactid version001snapshotversion packagingwarpackaging namerestlet1name urlurl repositoriesrepository idmavenrestletid namepublic online restlet repositoryname urlurlrepository repositories properties projectbuildsourceencodingutf8projectbuildsourceencoding properties dependencies dependency groupidjunitgroupid artifactidjunitartifactid version381version scopetestscope dependency dependenciesprojectthe problem which i am facing is that target war file is not getting generatedon eclipse console after i ran this pomxml what i found was goals missing in pomxmleclipse console message no goals have been specified for this build you must specify a valid lifecycle phase or a goal in the format pluginprefixgoal or plugingroupidpluginartifactidpluginversiongoal available lifecycle phases are validate initialize generatesources procesources generateresources processresources compile processclasses generatetestsources processtestsources generatetestresources processtestresources testcompile processtestclasses test preparepackage package preintegrationtest integrationtest postintegrationtest verify install deploy preclean clean postclean presite site postsite sitedeploy help 1error please tell me how to specify goals in pomxmlalso tell me how to create restlet project using maven as build toolthanks regards,['java'] +574744,android44 can not handle sms intent with vndandroiddirmmssms my application has a button to start default sms activity andit worked perfectly fine all android version except new one android 44kitkathere is the codepublic void onclickview arg0 intent smsintent new intentintentaction view smsintentsettypevndandroiddirmmssms smsintentputextraaddress membergetphonenumbertrim contextstartactivitysmsintentand i get error messages1108 020832815 eandroidruntime14733 androidcontentactivitynotfoundexception no activity found to handle intent actandroidintentactionview typvndandroiddirmmssms has extras i know that google made some changes on how the default sms app handles sms intentsbut my app is not a sms app but it only has function to start default sms app with recipient number so please help,"['java', 'android']" +574787,android loading fragment implementation i would like to start my app and show the main screen instantly half of the info on the screen will be loaded form local storage and the other half will be from a web service each of these will be on two different fragments i would like to thisplay a loading indeterminate progress bar while the data is being fetch from the webservice similar to how the google play store loads it is app date as shown below by the two states belowmy thoughts on implementing it are as followsload the fragment in with the progress bar the normal screen hidden in one layout once the data from the web service has been collected populate the normal screen then hide the view group containing the progress bar and show the viewgroup with the datais this best practice are the better ways to do it than thisthanks in advance,['android'] +574796,how to set nsurlrequest cache expiration i am using afnetworking and need to cache data in one response for a several minutes so i set nsurlcache in app delegate and then in my request setting up itnsmutableurlrequest request obtain request requestcachepolicy nsurlrequestreturncachedataelseloadhow then set expiration date if the data was loaded more than and minutes ago ask response from server and not from thisk updassume that server does not support caching i need to manage it in code,"['ios', 'objective-c']" +574813,is it a good practice to have trim in setter i am doing a code review and i noticed such a codeentitytablename some tablepublic class somereportclass columnname report number length 6 nullable falseprivate string reportnumber public string getreportnumber return reportnumber public void setreportnumberstring reportnumber thisreportnumber stringutilstrimtonullreportnumber every time i see trimming inside of a setter i feel that its not the clearest solution what is the general practice with that issue,['java'] +574837,are private methods really safe in java the private access modifier consider as safe since it is not visible outside of the class then outside world does not know about that method either but i thought java reflection can use to break this rule consider following casepublic class protectedprivacy private string getinfo return confidential now from another class i am going to get infopublic class breakprivacy public static void mainstring args throws exception protectedprivacy protectedprivacy new protectedprivacy method method protectedprivacygetclassgetdeclaredmethodgetinfo null methodsetaccessibletrue object result methodinvokeprotectedprivacy systemoutprintlnresulttostring at this moment i just thought still private method safe since to do some thing like above we must know method name but if class which contain private method written by some one else we do not have visibility of thosebut my point become invalid since below line of codemethod method new protectedprivacygetclassgetdeclaredmethodsnow this method contains all the things need to do above thing my question is is there a way to avoid this kind of things doing using java reflectioni am quote some point from java documentation to clarify my questiontips on choosing an access level if other programmers use your class you want to ensure that errors from misuse cannot happen access levels can help you do thisuse the most restrictive access level that makes sense for a particular member use private unless you have a good reason not to,['java'] +574919,how does assembly do parameter passing by value reference pointer for different typesarrays in attempt to look at this i wrote this simple code where i just created variables of different types and passed them into a function by value by reference and by pointer int i 1char c aint p ifloat f 11testclass tc has 2 private data members int i 1 and int j 2the function bodies were left blank because i am just looking at how parameters are passed inpassbyvaluei c p f tc passbyreferencei c p f tc passbypointeri c p f tcwanted to see how this is different for an array and also how the parameters are then accessedint numbers 1 2 3passarraynumbers assembly passbyvaluei c p f tcmov eax dword ptr ebp 16 mov dl byte ptr ebp 17 mov ecx dword ptr ebp 24 movss xmm0 dword ptr ebp 28 mov esi dword ptr ebp 40 mov dword ptr ebp 48 esi mov esi dword ptr ebp 36 mov dword ptr ebp 44 esi lea esi dword ptr ebp 48 mov dword ptr esp eax movsx eax dl mov dword ptr esp 4 eax mov dword ptr esp 8 ecx movss dword ptr esp 12 xmm0 mov eax dword ptr esi mov dword ptr esp 16 eax mov eax dword ptr esi 4 mov dword ptr esp 20 eax call z11passbyvalueicpif9testclasspassbyreferencei c p f tc lea eax dword ptr ebp 16 lea ecx dword ptr ebp 17 lea esi dword ptr ebp 24 lea edi dword ptr ebp 28 lea ebx dword ptr ebp 40 mov dword ptr esp eax mov dword ptr esp 4 ecx mov dword ptr esp 8 esi mov dword ptr esp 12 edi mov dword ptr esp 16 ebx call z15passbyreferencerircrpirfr9testclasspassbypointeri c p f tc lea eax dword ptr ebp 16 lea ecx dword ptr ebp 17 lea esi dword ptr ebp 24 lea edi dword ptr ebp 28 lea ebx dword ptr ebp 40 mov dword ptr esp eax mov dword ptr esp 4 ecx mov dword ptr esp 8 esi mov dword ptr esp 12 edi mov dword ptr esp 16 ebx call z13passbypointerpipcps pfp9testclasspassarraynumbers mov eax l zz4maine7numbers mov dword ptr ebp 60 eax mov eax l zz4maine7numbers4 mov dword ptr ebp 56 eax mov eax l zz4maine7numbers8 mov dword ptr ebp 52 eax lea eax dword ptr ebp 60 mov dword ptr esp eax call z9passarraypi parameter access push eax mov eax dword ptr esp 8 mov dword ptr esp eax pop eaxi am assuming i am looking at the right assembly pertaining to the parameter passing because there are calls at the end of eachbut due to my very limited knowledge of assembly i cannot tell whats going on here i learned about ccall convention so i am assuming something is going on that has to do with preserving the callersaved registers and then pushing the parameters onto the stack because of this i am expecting to see things loaded into registers and push everywhere but have no idea whats going on with the movs and leas also i do not know what dword ptr isi have only learned about registers eax ebx ecx edx esi edi esp and ebp so seeing something like xmm0 or dl just confuses me as well i guess it makes sense to see lea when it comes to passing by referencepointer because they use memory addresses but i cannot actually tell what is going on when it comes to passing by value it seems like there are many instructions so this could have to do with copying the value into registers no idea when it comes to how arrays are passed and accessed as parametersif someone could explain the general idea of whats going on with each block of assembly to me i would highly appreciate it,"['c++', 'c']" +574944,is it a goodcommon practice to use abstract classes in polymorphism in java i am a newbie in java and in all examples i have seen before interfaces are used to achieve polymorphism now we have the following code with abstract classabstractclass parent new childhere the man stated that a common argument is that polymorphism only applies to interfaces and not abstract classesi think he meant they are usually interfaces that are used in polymorphism in java as i see many people found his question silly and wanted url this here what i found so my question is it a goodcommon practice to use abstract classes in polymorphism as in my example because polymorphism is very wide definition in java,['java'] +574948,excluding directories in oswalk i am writing a script that descends into a directory tree using oswalk and then visits each file matching a certain file extension however since some of the directory trees that my tool will be used on also contain sub directories that in turn contain a lot of useless for the purpose of this script stuff i figured i would add an option for the user to specify a list of directories to exclude from the traversalthis is easy enough with oswalk after all it is up to me to decide whether i actually want to visit the respective files dirs yielded by oswalk or just skip them the problem is that if i have for example a directory tree like thisroot dira dirb uselestuff morejunk yetmorejunkand i want to exclude uselestuff and all its children oswalk will still descend into all the potentially thousands of sub directories of uselestuff which needless to say slows things down a lot in an ideal world i could tell oswalk to not even bother yielding any more children of uselestuff but to my knowledge there is no way of doing that is theredoes anyone have an idea maybe there is a thirdparty library that provides something like that,['python'] +575034,python pandas beginner multidimensional dataanalysis workflow groupbyaggplot i am new into pandas and try to learn how to process my multidimensional datamy datalet us assume my data is a big csv of the columns a b c d e f g this data describes some simulation results where a b f are simulation parameters and g is one of the ouputs only existing output in this exampleedit updateas boud suggested in the comments let us generate some data which is compatible to mineimport pandas as pdimport itertoolsimport numpy as npnpdata npzeros50 dtypeai4bf4ci4 d i4 e f4 f i4 g f4a 01236 param a intb 10 10 param b floatc 100150200250300 param c intd 1015202530 param d inte 01 03 param e floatf 0123456789 param f randomseed int 10 runs per scenario some betathistribution parameters for randomizing the results in column gathistparams 61 52 43 34 25 16 17 counter 0for i in itertoolsproductabcdef npdatacountera i0 npdatacounterb i1 npdatacounterc i2 npdatacounterd i3 npdatacountere i4 npdatacounterf i5 nprandomseed i5 npdatacounterg nprandombetathistparamsi00 bathistparamsi01 counter 1data pddataframenpdatadata datareindexnprandompermutationdataindex shuffle rows because my original data does not give any guaranteesbecause the parameters a b f are generated as a cartesianproduct meaning nested forloops a priori i want to use groupby for obtaining each possible simulation scenario before analysing the outputthe parameter f describe multiple runs for each scenario each scenario defined by a b e let us assume that f is the randomseed so my code becomesgrouped datagroupbyabcde every group defines one simulation scenariogrouped agg groupedag npmean the mean of the simulation output in g over f is calculated for each groupscenariowhat do i want to do nowi thisplay all the unique values of each scenarioparameter within these groups grouped agg gives me an iterable of tuples where for example all the entries at each position 0 give me all the values for a so with a few lines of python i would get my unique values but maybe there is a function for thatupdate my approachlistsetgrouped aggindexget level valuesa when interested in a using set for obtaining unique values probably not the stuff you want to do if you need high performance 0 1 2 3 6ii generate some plots of lower dimension i need to make some variables constant and filterselect my data before plotting therefore step i needed b constc conste constd xaxisg yaxis output from my aggregationa one more dimension multiple colors within 2dplot one gyaxis for each value of ahow would i generate a plot like thati think that reshaping my data is the key step and pandas plotting capabilities will handle it then maybe achieving a shape where there are 5 columns one for each value of parameter a and the corresponding gvalues for each indexselection paramaselection is enough but i was not able to achieve that form yet thanks for your inputi am using pandas 012 within enthought canopysascha,['python'] +575167,how do i encrypt usersettings i am developing a windows desktop application with c net40 vs2010 on windows 81 i have a range of settings that i store using the net settings mechanism these have user scope so when set within the application they are written to usersusernameappdatalocalcompanynameappexe url randomstuffversionnouserconfigthese settings include some user registration information that i need to keep hidden my research suggests that i should be able to encrypt settings using an rsaprotectedconfigurationprovider but all the examples i have found for this relate to encrypting appconfig rather than userconfig eg my question therefore is can userconfig be encrypted and if so how i note that when i instance a systemconfigurationconfiguration object i can set the configurationuserlevel to peruserroamingandlocal when i examine the object via the debugger it seems to be refering to the correct userconfig file but when i go on to instance a configurationsection to protect it returns null the code looks like thissystemconfigurationconfiguration config configurationmanageropenexeconfiguration configurationuserlevelperuserroamingandlocalconfigurationsection connstrings configappsettingsconnstringssectioninformationprotectsectionprovideri am thinking that configappsettings is probably not correct but i am not sure what to replace it withany advice greatly appreciated,"['c#', '.net']" +575179,for loop debug in java value overflow i am working out this problem from programming in java booksite for practice not a hw q15 in find the sum for the harmonic series 11 14 19 116 1n2 there are 4 variants of for loops some of them are supposed to give the right answer my expected answers are in comments and the actual results are below public class onethrexfifteen public static void mainstring args int and 10 double s10 s2 0 s3 0 s40 for int i 1 i and i s1 s1 1 i i expected s1 1 for int i 1 i and i s2 s2 10 i i expected s2 10 for int i 1 i and i s3 s3 10 i i correctly computes the series sum for int i 1 i and i s4 s4 1 10 i i correctly computes the serires sum systemoutprintlnfor loop 1 s1 systemoutprintlnfor loop 2 s2 systemoutprintlnfor loop 3 s3 systemoutprintlnfor loop 4 s4 result for loop 1 i get a divide by 0 error had to comment out this loop for loop 2 10 for loop 3 infinity for loop 4 164493306684877question why do i geta divide by zero error b infinity result in case of for loop 3,['java'] +575261,differentiate between app calls to http and angulars requests for static resources in interceptor with angularjs interceptors is it possible to differentiate my app calls to http direct either through resource from requests made by angular itself for static resources like views without checking urlsi am adding custom authorization header in http interceptor like thistransparentauthservicesfactoryauthhttpinterceptor function localsessionstorage return request function config if configignoreauthinterceptor localsessionstoragehassession var sessionid localsessionstoragegetsessionsessionid configheadersauthorization artauth sessionid sessionid return config else return config it works fine but i do not need authorization for static resources and my server does not check them i could check urls and skip on those starting with app in my case but i wonder is there an elegant solution,['javascript'] +575304,opening an app iphone via bluetooth low energy hello i do hope someone can help me with this question as i thought it would be easy at firsti am a studying ee student who is not that good with code but tryinglet me tell you my goal at the end of thisi would like to be able to open an app on the iphone and then execute a bit of code to send a message all via bluetoothi would like to be able to pair this small bluetooth device to the iphone only once and be able for it to be in sleep mode 500 nano amps d awesome and when i turn it on via a small switch it will open an app and send that message the app is already done you just have to press a button on the app in order to send the message that is why i would like to use a bluetooth device so you do not have to have the app open at all timessorry for the long paragraph but i need help i have the bluegiga ble113 dev kit and im overwhelmed with all the information they give you but i do not see anywhere where i connect to the iphone and do what i want to dohas anyone done this before can you steer me in the right direction,"['ios', 'iphone']" +575316,autoscroll down angularjs hi i am creating a chat app with angularjs that autoscrolls down when a user messages another user i am not sure how to implement this as my chat window is a fixed ul element i am thinking i will need to implement a directive to do this inboxmsgscroll on the ul elementany help thankshtmlul classchattingwindow inboxmsgscroll li datangrepeatmessageinfo in messages div classmessagedate messageinfo0 div liul,"['javascript', 'jquery']" +575361,is it possible to friend a class in an anonymous namespace in c i am porting code from java to c and i would like to replicate some anonymous functionalitiesin file ah i have class aprivate int a class anonclass friend class anonclassin file acpp i have namespace class anonclass public anonclassa parent parenta 0 this does not work a is not accessible is it possible to friend a class in an anonymous namespace in cin java you can declare anonymous classes so it would be very similar also it would not expose anonclass to clients of ah,['c++'] +575481,text overlay over imageview in android i am trying to have textviews overlay over imageviews something like thiscan someone help me with the code,['android'] +575520,zero padding numpy array suppose i have a list contains unequal length lists a 1 2 3 2 2 4 what is the best way to obtain a zero padding numpy array with standard shape zero a 1 2 3 2 0 0 2 4 0 i know i can use list operation liken max map len a map lambda x xextend 0 nlenx a zero a nparrayzero abut i was wondering is there any easy numpy way to do this work,['python'] +575810,simple aes encryption decryption with openssl library in c i want to encrypt a struct containing few string and then decrypt it i tried following code the original code is found from the web and it was working perfectly i change the input of it to a struct following is the codeinclude stdiohinclude stdlibhinclude stringhinclude timehinclude opensslaeshinclude opensslrandhtypedef struct ticket test field int ticketidchar username20 char date20 usr ticket a simple hexprint routine could be modified to print 16 bytesperlinestatic void hex printconst void pv size t lenconst unsigned char p const unsigned charpvif null pv printfnullelse size t i 0 for ileni printf02x pprintfn main entrypointint mainint argc char argv int keylength printfgive a key length only 128 or 192 or 256n scanfd keylength generate a key with a given length unsigned char aes keykeylength8 memsetaes key 0 keylength8 if rand bytesaes key keylength8 exit1 input struct creation size t inputslength sizeofusr ticket usr ticket ticket ticketticketid 1 time t now timenull strftimeticketdate 20 ymd localtimenow strcpyticketusername ravinda printfusername sn ticketusername printfticket id dn ticketticketid printfdate sn ticketdate init vector unsigned char iv encaes block size iv decaes block size rand bytesiv enc aes block size memcpyiv dec iv enc aes block size buffers for encryption and decryption const size t encslength inputslength aes block size aes block size aes block size unsigned char enc outencslength unsigned char dec outinputslength memsetenc out 0 sizeofenc out memsetdec out 0 sizeofdec out so i can do with this aescbc128 aescbc192 aescbc256 aes key enc key dec key aes set encrypt keyaes key keylength enc key aes cbc encryptunsigned char ticket enc out inputslength enc key iv enc aes encrypt aes set decrypt keyaes key keylength dec key aes cbc encryptenc out dec out encslength dec key iv dec aes decrypt printforiginalt hex printunsigned char ticket inputslength printfencryptt hex printenc out sizeofenc out printfdecryptt hex printdec out sizeofdec out usr ticket dyc usr ticket dec out printfusername sn dycusername printfticket id dn dycticketid printfdate sn dycdate return 0the problem is only first two members of the struct is decrypting correctly after that data get currupted what am i doing wrong here,['c'] +575837,change navbar height in bootstrap3 i am trying to reduce the height of bootstrap3s fixed navbar i found the navbarheight variable in variable less and changed it but it does not seem to change anythingi also tries these solutions change navbar height navbar height changing no resultany ideathanks,['css'] +575877,installing opencv for python on mavericks i am trying to install opencv on a macbook pro late 2013 with mavericks i did not find any binaries so i am trying to build iti tried and when calling make the error 2 is producedcmake error at cuda compile generated matrix operationscuocmake208when searching on this website i found opencv for python on mavericks i also tried homebrew which also produced error 2 but without any further informationi googled a lot but none of the found solutions worked for me does anyone have a tut for installing opencv on mavericksthank youusing brew gives the following output brew install homebrewscienceopencv warning it appears you have macports or fink installed software installed with other package managers causes known problems for homebrew if a formula fails to build uninstall macportsfink and try again downloading already downloaded librarycacheshomebrewopencv2461targz cmake dcmake install prefixusrlocalcellaropencv2461 dcmake build make cd tmpopencvqboiopencv2461macbuildmodulesstitching usrlocalcellarcmake2812bincmake e cmake symlink library liblibopencv stitching246dylib liblibopencv stitching24dylib liblibopencv stitchingdylib usrlocalcellarcmake2812bincmake e cmake progress report tmpopencvqboiopencv2461macbuildcmakefiles 90 91 100 built target opencv stitching make1 modulespythoncmakefilesopencv pythondirall error 2 make all error 2 read this if reporting this please do so at the homebrewscience tap not mxclhomebrewi solved the problem for me by using canopy which is free for students,['python'] +575895,hosting a read the docslike server inhouse read the docs is really amazing and great we have all our proprietary python modules documented in sphinx syntax and we are looking for hosting a similar service within our studio for proprietary python and others modules wondering if we can use for this purpose and how to do that,['python'] +575901,is this a vc compiler bug about unsigned integer wrapping i think the c program below shall output 1include stdiohint main unsigned int n18u while n17u17u n17u printfunn17u return 0but compiled in vc6 visual studio 2010 or visual studio 2012 all in release mode the program does not output anything and does not quit this is the assembly code generated by vs201200bd10 mov eax12h00bd1005 lea eaxeax11h00bd1008 jmp main5h 0bd1005hit seems that the compiler did some optimization and generated an infinite loopi think that n17u17u is not always true because if n0xf n17u would wrap to 16uam i wrong or are the compilers wrong,['c'] +576025,keeping two youtube videos in sync with each other i have got two identical youtube videos embedded on the same page i would like them to both be in sync here are my requirements notesboth videos must start at the same timewhen a video is played paused by the user the other video does the samethis is quite easy via the apiwhen one video buffers the other stops to wait and starts when they are both readyi only need audio from one videosync accuracy does not have to be millisecond perfect just reliableone video will be used as a background videothis video will be slightly blurred using css3 blur so quality not super essentiali have tried using the youtube js api to listen for player state changes and attempt to keep both videos in sync however it was not as reliable as i would hoped for i will post part of the code for this belowone caveat is that one video will appear larger than the other so the youtube might provide a higher quality video for thatbecause i am using css3 blur i can only use recent webkit browsers so a solution that works on these alone and not ffie is not a problemmy question is this for the requirements above is there any way to keep these two videos in sync i did consider if it was possible to use the canvas api to redraw the video but after researching figured this was not going to be possiblebuffering falsevar buffer control functionbuffering video sibling video state switch state case 1 play if buffering true consoleerrorrestarting after buffer pause both videos we want to make sure they are both at the same time buffering videopausevideo sibling videopausevideo get the current time of the video being buffered var current time buffering videogetcurrenttime and pull the sibling video back to that time sibling videoseektocurrent time true finally play both videos buffering videoplayvideo sibling videoplayvideo unset the buffering flag buffering false break case 3 buffering consoleerrorbuffering set the buffering flag buffering true pause the sibling video sibling videopausevideo break,['javascript'] +576039,starting or restarting unicorn with capistrano 3x i am trying to start or restart unicorn when i do cap production deploy with capistrano 301 i have some examples that i got working with capistrano 2x using something like namespace unicorn do desc start unicorn for this application task start do run cd current path bundle exec unicorn c etcunicornmyappconfrb d endendbut when i try and use run in the deployrb for capistrano 3x i get an undefined method errorhere are a couple of the things i tried within the deploy i created a task that i called after finishednamespace deploy do task unicorn do run cd current path bundle exec unicorn c etcunicornmyappconfrb d end after finished deployunicornendi have also tried putting the run within the restart tasknamespace deploy do desc restart application task restart do on rolesapp in sequence wait 5 do your restart mechanism here for example execute touch release pathjointmprestarttxt execute run cd current path bundle exec unicorn c etcunicorndeployrailsconfrb d endend if i use just run cd then i will get awrong number of arguments 1 for 0 in the local shelli can start the unicorn process with unicorn c etcunicorndeployrailsconfrb d from my sshd vm shell i can kill the master unicorn process from the vm shell using kill usr2 but even though the process is killed i get an error i can then start the process again using unicorn c kill usr2 58798bash kill usr2 arguments must be process or job idsi am very new to ruby rails and deployment in general i have a virtualbox setup with ubuntu nginx rvm and unicorn i am pretty excited so far but this one is really messing with me any advice or insight is appreciated,['ruby'] +576041,why is my spring autowired field null note this is intended to be a canonical answer for a common problemi have a spring service class mileagefeecalculator that has an autowired field rateservice but the field is null when i try to use it the logs show that both the mileagefeecalculator bean and the mileagerateservice bean are being created but i get a nullpointerexception whenever i try to call the mileagecharge method on my service bean why is not spring autowiring the fieldcontroller classcontrollerpublic class mileagefeecontroller requestmappingmileagemiles responsebody public float mileagefeepathvariable int miles mileagefeecalculator calc new mileagefeecalculator return calcmileagechargemiles service claservicepublic class mileagefeecalculator autowired private mileagerateservice rateservice should be autowired is null public float mileagechargefinal int miles return miles rateserviceratepermile throws npe service bean that should be autowired in mileagefeecalculator but it is notservicepublic class mileagerateservice public float ratepermile return 0565f when i try to get mileage3 i get this exceptionjavalangnullpointerexception null at comchrylisexamplespring autowired npemileagefeecalculatormileagechargemileagefeecalculatorjava13 at comchrylisexamplespring autowired npemileagefeecontrollermileagefeemileagefeecontrollerjava14,['java'] +576102,use of colon after class name in c this is a header file extracted from a blackberry 10 helloworld program ifndef applicationui hpp define applicationui hpp include qobjectnamespace bb namespace cascades class application class localehandler class qtranslator brief application object class applicationui public qobject q objectpublic applicationuibbcascadesapplication app virtual applicationui private slots void onsystemlanguagechangedprivate qtranslator m ptranslator bbcascadeslocalehandler m plocalehandlerendif applicationui hpp i am confused about the colon operator right after the class name declarationclass applicationui public qobjectwhat does this mean,['c++'] +576133,python not catching memoryerror i have wrapped some code that can run out of memory with a tryexcept block however though a memoryerror is generated it is not caughti have the following code while true try selfcreate indexed vocab vocab selfreset weights break except memoryerror stuff to reduce size of vocabulary selfvocab selfindex2word none none selfsyn0 selfsyn1 none none selfmin count 1 loggerinfo format string here i get the following traceback file make model tagged wmt11py line 39 in module modelbuild vocabsentencesfile rootcustomcompiledsoftwaregensimgensimmodelsword2vecpy line 236 in build vocab selfreset weightsfile rootcustomcompiledsoftwaregensimgensimmodelsword2vecpy line 347 in reset weights selfsyn0 randomrandlenselfvocab selflayer1 size 05 selflayer1 sizefile mtrandpyx line 1044 in mtrandrandomstaterand numpyrandommtrandmtrandc6523file mtrandpyx line 760 in mtrandrandomstaterandom sample numpyrandommtrandmtrandc5713file mtrandpyx line 137 in mtrandcont0 array numpyrandommtrandmtrandc1300memoryerrori am running python 273 under ubuntu 1204the reset weights line selfsyn0 is exactly the line i am expecting to raise the exception it allocates a big array the puzzling thing is that i cannot catch the memory error and do things that will make the array size smallerare there special circumstances that result in the memoryerror being unable to be caught,['python'] +576175,integrated tomcat in maven reload sources i am using maven for my webapplication to build start and handle the libraries so i run tomcat7run to develop my application but if i change the code the tomcat will not automatic reload the code changes so i need to restart before maven i use the sysdeo eclipse tomcat launcher plugin to run and create my project this plugin allows to the see code changes instant and i know that the play framework do the same so it is possible to configure maven to reload my code changes on running i will improve my work progress,['java'] +576182,django how to get value from charfield and modelchoicefield i have a class groupadminform which is used to extend the group admin page in django there are two fields selected to change and print name what i am designing to do is to select a column in selected to change and enter a char name in print name in order to make a query likeupdate annotation set print name value of print name where id value of selected to changehere is the groupadminformclass groupadminformformsmodelform users formsmodelmultiplechoicefieldquerysetuserobjectsall widgetfilteredselectmultipleusers false requiredfalse select to change formsmodelchoicefieldquerysetannotationobjectsall requiredfalse print name formscharfieldrequiredfalse class meta model group def init self args kwargs instance kwargsgetinstance none if instance is not none initial kwargsgetinitial initialusers instanceuser setall initiallocations instancec locationsall kwargsinitial initial supergroupadminform self init args kwargs def saveself committrue group supergroupadminform selfsavecommitcommit if commit groupuser set selfcleaned datausers else old save m2m selfsave m2m def new save m2m old save m2m groupuser set selfcleaned datausers selfsave m2m new save m2m return grouphow can i get the values from the charfield and modelchoicefield to make such queries in the method save thanks,['python'] +576188,how do i get an objects unqualified short class name how do i check the class of an object within the php name spaced environment without specifying the full namespaced class for example suppose i had an object libraryentitycontractname the following code does not work as get class returns the full namespaced class ifget classobject name do this the namespace magic keyword returns the current namespace which is no use if the tested object has another namespace i could simply specify the full classname with namespaces but this seems to lock in the structure of the code also not of much use if i wanted to change the namespace dynamically can anyone think of an efficient way to do this i guess one option is regex,['php'] +576214,join strings with a delimiter only if strings are not null or empty this feels like it should be simple so sorry if i am missing something here but i am trying to find a simple way to concatenate only nonnull or nonempty stringsi have several thistinct address fieldsvar addressvar cityvar statevar zipthe values for these get set based on some form fields in the page and some other js codei want to output the full address in a div delimited by comma space so something like thisaddressdivappendaddress city state zipproblem is one or all of these fields could be nullempty is there any simple way to join all of the nonempty fields in this group of fields without doing a check of the length of each individually before adding it to the string,"['javascript', 'jquery']" +576286,how to run a jar file in a linux commandline how to set the classpath to the current directory and also run the jar file named loadjar present in the current directory by providing the argument as load2 from a linux command linei did try to run the jar as follows but its executing classes from some other directoryjava cp loadjarclasspath loadstart load2,['java'] +576319,mysql transaction roll back on any exception is it possible to roll back automatically if any error occurs on a list of mysql commandsfor example something along the lines ofbegin transactioninsert into mytable values1 insert into mytable values2 will throw an errorcommitnow on execute i want the whole transaction to fail and therefore i should not see values1 in mytablebut unfortunately the table is being pupulated with values1 even though the transaction has errorsany ideas how i make it to roll back again on any erroredit changed from ddl to standard sql,['mysql'] +576338,static analysis of virtual generic method calls xamarin is a system that compiles net code fully aheadoftime aot for platforms which thisallow data execution and so cannot have a jit this question is not about xamarin but is about an assertion that its documentation makes it states heregeneric virtual methods support is limited it is not possible to determine statically what method will be called in all circumstances so the compiler might leave out a few of themi could be mistaken but they seem to be implying a broad statement about what is possible here through static analysis not just what they have chosen to implement in their own softwareas hans passant aptly pointed out the example they give does not actually demonstrate the problem they are referring to so i have excluded itso aside from these definitely intractable special casesreflectiondynamically generated code illegal in this scenario anywaypathological circular references in type arguments involving value types andforeign assemblieswhat would make an aot compiler unable to handle the virtual generic method case,['.net'] +576453,how to load a custom js file in django admin home i have a heavily customized django admin where it is very simple to load a custom js file for each of my modeladminsclass mymodeladminadminmodeladmin class media js jsadminmymodeljsbut how do i do this for the admin homepage where all my admin models are listedupdate 1 amending my question since the solutions below are not that useful if i cannot efficiently include djangos jquery so how do i include djangos jquery in the js file if i wrap my code with as i do in my other modeladmin js files function djangojqueryi get the following errorreferenceerror django is not definedthanksupdate 2 i was able to include djangos jquery successfully by following this answer,"['javascript', 'python']" +576470,sending email through outlook 2010 via c i am trying to send an email from inside my c console app i have added the references and using statements but it seems i have not added everything i need this is the first time i have ever attempted to do this so i figure there is something i have forgotteni got this code snippet from the msdn site vvs100aspxhere is the code that i am getting issues with in vs 2010using systemusing systemconfigurationusing systemiousing systemnetusing systemnetmailusing systemruntimeinteropservicesusing outlook microsoftofficeinteropoutlookusing office microsoftofficecorenamespace fileorganizer class program private void createmailitem outlookmailitem mailitem outlookmailitem thisapplicationcreateitemoutlookolitemtypeolmailitem outlookapplication app new outlookapplication outlookmailitem mailitem appcreateitemoutlookolitemtypeolmailitem mailitemsubject this is the subject mailitemto mailitembody this is the message mailitemattachmentsaddlogpathlogpath is a string holding path to the logtxt file mailitemimportance outlookolimportanceolimportancehigh mailitemthisplayfalse,['c#'] +576488,where do i put generic library code in symfony 2 quick question where should i be putting code that has similar characteristics to the controller utilities service class as described here on this blog post by benjamin eberlei symfony2 controller utilitieshtmlfor the interim i have placed it inside srcprojectnamelibrarycontexti have noted the following this logic does not belong to a specific bundle in fact it applies to all bundles one would be creatingthis logic usually belongs in an application specific library as opposed to being part of a bundle as controllers within bundles would either extend or utilise this library codei found some answers to questions that are similar in theme but not exactly what i was afterbased on my research here on so alone this question seems to have been trodden to death somewhat but i think the questions asked previously skirt around what i am actually after regardless it would seem that i have the following options putting these types of extensions in a bundle not applicable as the type of functionality i am developing is essentially extending the framework codecreating a vendor directory for the project where all the library code would go if this is indeed the best practice then it would essentially mean that i would have to make the library available via private repo in composer but that means that i would have to maintain a separate codebasecreate some sort of pseudo connector bundle that lives in the srccompanysomenamespace i do not even know if this is at all the way to go but if it is in keeping with sf best practice i will look into it furtherthe question again for brevity where do i put classes which provide generic global functionlity in symfony 2my thanks in advance,['php'] +576560,concurrent or sequential i am playing around with threads in javathe following example i found on a websitepublic class threadtest public static void mainstring args thread t1 new threadnew thread1 t1start thread t2 new threadnew thread2 t2start public class thread1 implements runnable override public void run for int i 0 i 20 i systemoutprintlnnew javautildate public class thread2 implements runnable override public void run for int i 0 i 20 i systemoutprintlni the expected result would be something likemon nov 11 200612 cet 20130123456789mon nov 11 200612 cet 201310but i get012319mon nov 11 200612 cet 2013mon nov 11 200612 cet 2013mon nov 11 200612 cet 2013mon nov 11 200612 cet 2013so it does not seem concurrent but sequential is it because of the speed,['java'] +576569,how can i cache the json representation of an object in the json representation of my car model i include the output of an expensive methodcarrbdef as jsonoptions superoptionsmergemethods some expensive methodendi have a standard index actioncars controllerrbrespond to jsondef index respond withcarallendi also use the json representations of cars in other places like thisuser feedrbdef feed contents horseall carallenduser feeds controllerrbrespond to jsondef index respond withuserfeedfeed contentsendbecause the json representation of a car is used in multiple places i want it to be cached on its own using carcache key as an autoexpiring cache keythis is how i am currently doing itcarrbdef as jsonoptions railscachefetchcache keyas json do superoptionsmergemethods some expensive method endendputting the cache code inside as json is not correct though because caching is not part of as jsons reponsibility what is the proper way to do this i am using rails 3215,['ruby-on-rails'] +576587,mochachai async tests done fn not working i am testing a bank model i have as followsdescribebank model ajax function itloads bank function done var bank new bank bankonloaded function expectthisidtoeql1171 expecttruetoeqlfalse done bindbank bankload1171 the load call makes an ajax request to my server my problem is that expecttruetoeqlfalse throws an uncaught assertion error and i am not sure why i am using the recommended mocha strategy of ending my test case with a done am i doing it wrongthanks,['javascript'] +576615,dopostback is undefined in ie11 using a readymade asp hyperlink control ie 11 is giving the error script5009 dopostback is undefined with a link to herevvs94aspxthis is seen in the f12 devtools console window has anybody encountered this yet and is there a fix this is a production environmenteditapplying hotfix did not work for me and ie 10 on windows 8 works fine there is more recent article from scott hanselman with updated information i will attempt these fixes and update this question but this appears to be isolated to windows 81 and ie11,['asp.net'] +576660,how to marshall work onto the main thread using tpl tasks in c without causing a deadlock i am writing a library that is consuming a resource and for whatever reason the api was designed in a way that events will be raised on different threads but calls of the api has to be done on the main threadlet us say the api that i am trying to consume is defined as i am going to omit event definitionspublic sealed class dodgyservice public void methodthathastobecalledonthemainthread to consume this api i have added a service on my library called service yup very original name that will create a new task that will run on the main thread as i am specifying a taskscheduler that has been created from the synchronizationcontexthere is my implementationpublic class service private readonly taskfactory taskfactory private readonly taskscheduler mainthreadscheduler public servicetaskfactory taskfactory taskscheduler mainthreadscheduler taskfactory taskfactory mainthreadscheduler mainthreadscheduler assume this method can be called from any thread in this sample is called by the main thread but most of the time the caller will be running on a background thread public task executeasyncstring taskname return taskfactorystartnew reallylongcallthatforwhateverstupidreasonhastobecalledonmainthreadtaskname new cancellationtokenfalse taskcreationoptionsnone mainthreadscheduler continuewithtask tracetraceinformationexecuteasync has completed on 0 taskname private void reallylongcallthatforwhateverstupidreasonhastobecalledonmainthreadstring taskname tracetraceinformationstarting 0 really long call taskname new dodgyservicemethodthathastobecalledonthemainthread tracetraceinformationfinished 0 really long call taskname now if i perform the call of my service on the main thread and try to wait on the main thread the application enters a deadlock as the main thread will be waiting for the tasks that has been scheduled to execute on the main threadhow do i marshall these calls onto the main thread without blocking the entire processat some point i thought on performing the detection of the main thread before creating the new task but i do not want to hack thisfor anybody interested i got a gist here with the code and a wpf app that exhibits the issueon btw the library has to be written on net framework 40editi solved my issue following the advice provided by scott chamberlain as provided here,"['c#', '.net']" +576681,launch4j how to attach dependent jars to generated exe i have a simple java project which requires external jarsi build this with netbeans and after clean and build command i can find in thist directory the following structuremyappjarlib library1jar library2jartypical i would saynow i would like to thistribute myappjar with dependent libraries as one exe is this possible i am trying to use launch4j in the gui i create the config file there are some options in cp sectioncplibswinglayout104jarcpbut it seems to be classpath and it is the only place i can refer to my extra jarsafter exe file is created i cannot find dependend libs in the exe exe can be opened with winrar and thus my application crasheshow can i make the exe file properly thenthanks for your help,['java'] +576683,inner enum in nonstatic context as i understood inner enums are always explicitly 34r implicitly static in java which means i cannot access instance fields from my inner enum classpublic class innerenum private enum someinnerenum value1 override public void dosomething error would not compile cannot make static reference to nonstatic field i systemoutprintlni value2 override public void dosomething do something else with i public abstract void dosomething private int i 10i have found it pretty convenient to just override method in each enum constant so i could use it in my outer class is it a bad programming style in java because it is actually forbiddenis there any way to create inner enum with an access to my instance variablesthanks in advance,['java'] +576691,genymotion how to load apk every time i am getting started with android development and with genymotion it is difficult to get genymotion to install a apk and run it more than once heres what i am doingbegin with genymotion running press genymotion icon in elipsesee genymotion virtual devices manager note that state of my vm is oncreate a new android projectpress the green run buttonsee run as dialog select android applicationsee android device chooser select genymotion nexus onesee hello world app run press gm home buttonfrom here if i change the app it is difficult to get the app to rethisplay in the emulatordrag a button to activity mainxml savepress the green run buttonnothing happensto get the app to rethisplay requires jiggle the handle type actionsif i clear the console log or bring up the gm virtual devices manager before i press the run button the app will generally thisplay in genymotionany ideas how to make genymotion behave without jiggling the handlei am running the latest sdk 20131030 on osx 1075,['android'] +576697,android searchview setonactionexpandlistener on honeycomb 32 i am developing an app for android 32 and greater with androidsupportv4 i need to implement onactionexpandlistener for intercept when searchview in the actionbar is expanded and when is collapsed my code for android 40 and higher it is ok but for 32 nomenuxmlitem androidididmenu search androidtitlestringmenu search androidiconandroiddrawableic menu search androidshowasactioncollapseactionviewalways androidactionviewclassandroidwidgetsearchview myactivityjavaoverridepublic boolean oncreateoptionsmenumenu menu getmenuinflaterinflatermenureader menu final menuitem searchmi menufinditemridmenu search ifsearchview null searchview searchview searchmigetactionview searchview searchview menuitemcompatgetactionviewsearchmi searchviewsetonquerytextlistenerthis searchviewsetonsuggestionlistenerthis searchviewsetoncloselistenernew oncloselistener override public boolean onclose some code return false int currentapiversion androidosbuildversionsdk int if currentapiversion androidosbuildversion codeshoneycomb mr2 menuitemcompatsetshowasactionsearchmi menuitemcompatshow as action collapse action view menuitemcompatshow as action always menuitemcompatsetonactionexpandlistenersearchmi new onactionexpandlistener nonjavadoc see androidsupportv4viewmenuitemcompatonactionexpandlisteneronmenuitemactionexpandandroidviewmenuitem override public boolean onmenuitemactionexpandmenuitem item toastmaketextgetapplicationcontext onmenuitemactionexpand toastlength shortshow return true nonjavadoc see androidsupportv4viewmenuitemcompatonactionexpandlisteneronmenuitemactioncollapseandroidviewmenuitem override public boolean onmenuitemactioncollapsemenuitem item toastmaketextgetapplicationcontext onmenuitemactionexpand toastlength shortshow return true else searchmisetonactionexpandlistenernew menuitemonactionexpandlistener override public boolean onmenuitemactionexpandmenuitem item toastmaketextgetapplicationcontext menuitemonmenuitemactionexpand toastlength shortshow return true override public boolean onmenuitemactioncollapsemenuitem item toastmaketextgetapplicationcontext menuitemonmenuitemactionexpand toastlength shortshow return true why for honeycomb methods of listener is not invokedthank you so much,"['java', 'android']" +576715,uisegmentedcontrol how to detect click on current segment is there a way to detect second click on a segment in uisegmentedcontrol i founddetect second click on a segmenthowever it is stated thatif you set a segmented control to have a momentary style a segment doesnat show itself as selected blue background when the user touches it the thisclosure button is always momentary and doesnat affect the actual selectionis there a way to detect second click as well as trigger the selection action and show the segment as selectedif there is no straight forward way to do it what i was thinking is that i first have the momentary flag set to yes then upon each click manually update the selection state but then i also need to updatedeselect other segmentsthanks,"['ios', 'objective-c']" +576743,receiving post data in rails 4 and reading requestbody i want to send a post request to a rails application and have it save and parse the request body in the databasemy route on the receiving end is currently setup aspost request controllerreceives datawhen i post data to this controller i usedef post it connectionposturipath this is data header with authkeyendmy controller method that receives the post is setup asdef receives data logrequestbodyreadendhowever i am getting a 422 error unprocessable entity and the log file is always emptyare there specific headers i need to include to post this to a rails app are there specific configurations i need to include in my controller or routes,"['ruby-on-rails', 'ruby']" +576776,how to run a single junit test method in eclipse in a junit test case with multiple test annotations how does one selectively run tests for eg from the following code how does one run just one test method test public void testhelloempty assertequalshgetname assertequalshgetmessagehello test public void testhelloworld hsetnameworld assertequalshgetnameworld assertequalshgetmessagehello world i have tried to just highlight one test method and tried to run it but it does not work that way,['java'] +576814,customize themes not working i have to customize my whole application theme and i am trying to implement my custom theme i am able to implement custom theme but it is showing error when i apply it in manifest filehere is my code for custome themexml version10 encodingutf8resources the theme applied to the application or activity style namecustomactionbartheme parentstylethemehololightdarkactionbar item nameandroidactionbarstylestylemyactionbaritem style actionbar styles style namemyactionbar parentstylewidgethololightactionbarsolidinverse item nameandroidbackgrounddrawableactionbar backgrounditem styleresources,['android'] +576885,new python 3 port of google python api client i have wanted to use the google api python client with python 3x apparently nobody has done a port of this code to the new language specification even though py3k has been around since at least 2009 so i decided to do my own port of the code as per the request at the official google code site for the python client i am posting an announcement here so do not go closing this post as irrelevant or something i am just following directions herethe new code is available at and is currently able to run a number of api calls without any problem i have specifically tested it with the translate api v2 i am currently involved in validating the code against the extensive set of unit tests that come with the 27 version of the code so as of this moment i can make no guarantees about the working state of every part of it in particular the whole oauth api is untestedthe 3x port of the google api client retains the same license as the original code and i am offering it for testing and use by anyone interested with the hope that the new code will eventually be adopted by googleplease use the github tracker to report any issues if you are interested in contributing i can arrange for you to have commit access to the code tree address any questions to me at erik dot norvelle at cyberlogos dot co,['python'] +576898,groupid of maven projects hosted on github i have a open source maven project hosted on github let us say the url is now i want to upload it to the sonatype oss maven repository i checked that they have a strict rule on the groupid groupid will identify your project uniquely across all projects so we need to enforce a naming schema it has to follow the package name rules what means that has to be at least as a domain name you control and you can create as many subgroups as you want eg orgapachemaven orgapachecommons a good way to determine the granularity of the groupid is to use the project structure that is if the current project is a multiple module project it should append a new identifier to the parents groupid eg orgapachemaven orgapachemavenplugins orgapachemavenreportingthe question is that for projects hosted on github what is the proper groudidas user generated website has domain foogithubio i have at least the following two optionscomgithubfooiogithubfoo,['java'] +576939,android testing syncadapter i have a sync adapter that is synchronizing the contacts with a private server it looks something like the samplesyncadapter in the samples but of course modified to meet my needsi need to write tests for this sync adapter can anyone give me some guides on how to write these testsi got stuck with testing the contacts operations create update delete how can i mock the contacts database so i can that one for testing instead of the the real contacts databasethank you,['android'] +576948,django importerror cannot import name celery possible circular import i went through this example hereall my tasks are in files called taskspyafter updating celery and adding the file from the example django is throwing the following error no matter what i tryimporterror cannot import name celeryis the problem possibly caused by the followingappautothiscover taskssettingsinstalled apps related nametasksbecause it goes through all taskspy files which all have the following importfrom cloudcelery import appcloudcelerypyfrom future import absolute importimport os sysfrom celery import celeryfrom celeryschedules import crontabfrom djangoconf import settingsbroker url rethispasswordlocalhostosenvironsetdefaultdjango settings module cloudsettingsapp celerycloud brokerbroker urlappconfig from objectdjangoconfsettingsappautothiscover taskssettingsinstalled apps related nametasksif test in sysargv appconfupdate celery always eagertrue print sysstderr celery always eager truecelerybeat schedule test rabbit running task retailtaskstest rabbit running schedule 3600 every hour appconfupdate celerybeat schedulecelerybeat scheduleretailtaskspyfrom cloudcelery import appimport loggingfrom celeryutilslog import get task loggerlogger get task loggertasksloggersetlevelloggingdebugapptaskdef test rabbit running import datetime utcnow datetimedatetimenow loggerinfocelery runningthe error happens when i try to access a url that is not valid like foobarhere is the full tracebacktraceback most recent call last file optvirtenvsdjango slicelocallibpython27sitepackagesgunicornworkerssyncpy line 126 in handle request respiter selfwsgienviron respstart response file optvirtenvsdjango slicelocallibpython27sitepackagesdjangocorehandlerswsgipy line 255 in call response selfget responserequest file optvirtenvsdjango slicelocallibpython27sitepackagesdjangocorehandlersbasepy line 178 in get response response selfhandle uncaught exceptionrequest resolver sysexc info file optvirtenvsdjango slicelocallibpython27sitepackagesdjangocorehandlersbasepy line 220 in handle uncaught exception if resolverurlconf module is none file optvirtenvsdjango slicelocallibpython27sitepackagesdjangocoreurlresolverspy line 342 in urlconf module self urlconf module import moduleselfurlconf name file optvirtenvsdjango slicelocallibpython27sitepackagesdjangoutilsimportlibpy line 35 in import module import name file optsrcslicephonecloudcloudurlspy line 52 in urlpatterns patterns urlrsearch includesearchurls file optvirtenvsdjango slicelocallibpython27sitepackagesdjangoconfurls init py line 25 in include urlconf module import moduleurlconf module file optvirtenvsdjango slicelocallibpython27sitepackagesdjangoutilsimportlibpy line 35 in import module import name file optsrcslicephonecloudsearchurlspy line 5 in from handlers import searchhandler file optsrcslicephonecloudsearchhandlerspy line 15 in from places import handlers as placeshandler file optsrcslicephonecloudplaceshandlerspy line 23 in import api as placesapi file optsrcslicephonecloudplacesapipy line 9 in from djapi import file optsrcslicephonecloudplacesdjapipy line 26 in from tasks import add single place add multiple places file optsrcslicephonecloudplacestaskspy line 2 in from cloudcelery import app file optsrcslicephonecloudcloudcelerypy line 4 in from celery import celery file optsrcslicephonecloudcloudcelerypy line 4 in from celery import celeryimporterror cannot import name celery,['python'] +576960,finding imei number using objectivec i need to find a way to get the imei number of an iphone device this question is not a duplicatei have gone through several forums including so and had no luck finding an answersome say apple does not allow developers to see the imei number so post and some say to use udid instead so post some say that udid is deprecated in ios 7 i need to know the following1 does apple permit developers to retrieve the imei number of the device2 how can i programatically do it3 in case if apple does not allow developers to gather the imei number do they provide any other unique number for the device 4 some suggest to use telephony framework if i do so will apple reject my application,"['ios', 'objective-c']" +576963,private composer packages no valid composerjson was found i am trying to load a library i have hosted on bitbucket using composer as explained both in the official documentation and here but keep receiving the following errorcomposerrepositoryinvalidrepositoryexceptionno valid composerjson was found in any branch or tag of repository url could not load a package from ithere is my project composerjson name project name require myvendormypackage devmaster repositories type vcs url repository url and here is the composerjson in my remote repository that apparently cannot be found name myvendormypackage version 03 autoload psr0 ns src i should mention that both composerjson files are in the root directory as they should besome other things to notei have also tried the noncomposer package approach whereby i specify the package information in my project composerjson and omit the composerjson from my remote repository as outlined in the documentation this successfully clones the master branch but then results in the following errorruntimeexceptionfailed to execute git checkout master git reset hard masterfatal not a git repository or any of the parent directories githowever the package is downloaded to vendor as expected so i am not sure why it is trying to checkout master againthis is not the way i wish to solve this problem as i would rather make use of a composerjson in the remote repository but it might help identify an issue elsewherethanks for any helpediti have managed to get it working by referencing a packagejson over httprepositories type composer url httplocalhostpackagesjson the packagesjson looks like packages vendormypackage devmaster name vendormypackage version devmaster source url repository url type git reference master is this the only way to get this working it seems a bit overkill to host my own packagesjson file if i am only going to be using one or two inhouse packagesregardless this is giving me the same git error as i mentioned previouslyedit 2forcing an error invalid ssh passphrase gives thisruntimeexceptionfailed to execute git clone repository url cworkspacedfv3vendorvendormypackage cd d cworkspacedfv3vendorvendormypackage git remote add composer repository url git fetch composerso i can clearly see what it is doing here however it seems after this command runs it cds into the git directory and tries runninggit checkout master git reset hard masterpresumably to get rid of the composer instance it pulled however it is running this in the wrong directory and i cannot figure out why,['php'] +577049,c11 smart pointer semantics i have been working with pointers for a few years now but i only very recently decided to transition over to c11s smart pointers namely unique shared and weak i have done a fair bit of research on them and these are the conclusions that i have drawnunique pointers are great they manage their own memory and are as lightweight as raw pointers prefer unique ptr over raw pointers as much as possibleshared pointers are complicated they have significant overhead due to reference counting pass them by const reference or regret the error of your ways they are not evil but should be used sparinglyshared pointers should own objects use weak pointers when ownership is not required locking a weak ptr has equivalent overhead to the shared ptr copy constructorcontinue to ignore the existence of auto ptr which is now deprecated anyhowso with these tenets in mind i set off to revise my code base to utilize our new shiny smart pointers fully intending to clear to board of as many raw pointers as possible i have become confused however as to how best take advantage of the c11 smart pointerslet us assume for instance that we were designing a simple game we decide that it is optimal to load a fictional texture data type into a texturemanager class these textures are complex and so it is not feasible to pass them around by value moreover let us assume that game objects need specific textures depending on their object type ie car boat etcprior i would have loaded the textures into a vector or other container like unordered map and stored pointers to these textures within each respective game object such that they could refer to them when they needed to be rendered let us assume the textures are guaranteed to outlive their pointersmy question then is how to best utilize smart pointers in this situation i see few optionsstore the textures directly in a container then construct a unique ptr in each game objectclass texturemanager public const texture textureconst stdstring key const return textures atkey private stdunordered mapstdstring texture textures class gameobject public void set textureconst texture texture texture stdunique ptrtexturenew texturetexture private stdunique ptrtexture texture my understanding of this however is that a new texture would be copyconstructed from the passed reference which would then be owned by the unique ptr this strikes me as highly undesirable since i would have as many copies of the texture as game objects that use it defeating the point of pointers no pun intendedstore not the textures directly but their shared pointers in a container use make shared to initialize the shared pointers construct weak pointers in the game objectsclass texturemanager public const stdshared ptrtexture textureconst stdstring key const return textures atkey private stdunordered mapstdstring stdshared ptrtexture textures class gameobject public void set textureconst stdshared ptrtexture texture texture texture private stdweak ptrtexture texture unlike the unique ptr case i would not have to copyconstruct the textures themselves but rendering the game objects is expensive since i would have to lock the weak ptr each time as complex as copyconstructing a new shared ptrso to summarize my understanding is such if i were to use unique pointers i would have to copyconstruct the textures alternatively if i were to use shared and weak pointers i would have to essentially copyconstruct the shared pointers each time a game object is to be drawni understand that smart pointers are inherently going to be more complex than raw pointers and so i am bound to have to take a loss somewhere but both of these costs seem higher than perhaps they should becould anybody point me in the correct directionsorry for the long read and thanks for your time,['c++'] +577081,difference between a lambda function and a closure in php chapter 2 of magento php developers guide stateszend framework 2 uses 100 objectoriented code and utilizes most of the new features of php 53 namely namespaces late static binding lambda functions and closureswhile the post what is the difference between a closure and a lambda has some answers such as that a lambda is just an anonymous function and that a closure is a function which can access variables not in its parameter list seems to be specific to the python programming language with some mention of the scheme programming languagefor instance according to the post in python it seems there can be closures which are not lambdas and lambdas which are not closureshowever i am interested in the php programming language not python one of the answers below seems to point out that in php all closures are lambdas which conflicts with what the post relating to python statesit seems to me that these concepts vary in the particulars from language to language and i am interested in php hence this postall of this is confusing while i would assume that lambda functions in general are just unnamed functions the following wikipedia article says more about closures 28computer science29although has no examples in php,['php'] +577092,how to custom modal view controller presenting animation instead of setting uiviewcontrollers modaltransitionstyle i want to add an caanimationor some other thing this code can perform an custom animation in navigationcontrollercatransition transition catransition animation transitionduration 04 transitiontype kcatransitionfade transitionsubtype kcatransitionfrombottom selfnavigationcontrollerviewlayer addanimationtransition forkeykcatransition selfnavigationcontroller pushviewcontrolleradjustviewcontroller animatednohow can i implement it to a modal view controller,['ios'] +577096,find out which page an item is on i am using linq with entity framework in my application i have repository method to get a page of data like thispublic ienumerablesample getpagedataint orderid int page int itemsperpage var samples contextsetsample wheres sorderid orderid orderbys sid skipitemsperpage page takeitemsperpage return samplesi would like to have another repository method so that i can retrieve the page on which a sample is the method signature would be something likepublic int getpageint orderid int sampleid int itemsperpage i am struggling to find a way to do it in linq the only idea i have for now is to fetch the pages one after one until i find the needed sample i know it is not efficient but the requirement is that there are no more than 500 samples and the page size is 25how i could do this more efficiently,['c#'] +577099,how to wake up ios app with bluetooth signal ble using the ble with corebluetooth no ibeacon is there a way to wake app a not running app when the device receives a bluetooth signali am simulating a beacon with the redbearlabs ble shield thanksdan update 030514 it looks like apple has introduced a major update with ios 71 now ios will open your app for you if it detects a uuid that matches your app the app only needs to be installed it does not have to be running logic in appdelegate needed to answer the wakeup call,['ios'] +577129,php numberformatter slovenian spellout wrong i am trying to spellout an integer amount into slovenian words for postal declarations using the numberformatter class from the intl package but the result is completely wrong and makes no sensefmt new numberformattersl numberformatterspelloutfmtformat561results in petsto aestdeset ena while it should be petsto enainaestdeset looks like baby talk insteadin croatian language which is pretty similar the result seems ok petsto aezdeset i jedanis this a poorly done translation in php or is this based on my system locale i am on php 5310 ubuntu 1204editintl is version 110 the current is 300 so maybe it has been fixed,['php'] +577204,bootstrap 3 how to make head of dropdown link clickable in navbar i am using the default navbar and a couple of the list items are dropdowns i am not able to click the link that triggers the dropdown i know that i could just add a duplicate link into the dropdown but i would rather not is it possible to make the head link a clickable link not just a handle for the dropdownfor reference see the first link in the dropdown below i want users to be able to click it and actually go to the page it points tonav classnavbar navbarfixedtop adminmenu rolenavigation div classnavbarheaderdiv collect the nav links forms and other content for toggling div classcollapse navbarcollapse idbsexamplenavbarcollapse1 ul classnav navbarnav navbarright li classdropdown a classdropdowntoggle datatoggledropdown href i dont work b classcaretb a ul classdropdownmenu lia hrefpage2page2ali ul li lia hrefi do workali ul div navbarcollapse nav,"['javascript', 'css']" +577283,mysqliquery could not fetch mysqli warning mysqliquery could not fetch mysqli in cprogram files x86easyphpdevserver131vc9datalocalwebmy portable filesclass eventcalendarphp on line 43the following is my connection filephpifisset session session start create array to hold error messages if anyerrormsgs array create new mysql connection objectdbconnect new mysqlilocalhostrootlocalhost nuladle check to see if connection errno data member is not 0 indicating an errorif dbconnectconnect errno add error to errors array errormsgsthe database server is not available connect error is dbconnectconnect errno dbconnectconnect errorand this is my class script php class eventcalendar private dbconnect null function construct include the database connection data includeinc ladledbphp thisdbconnect dbconnect function destruct if thisdbconnectconnect error thisdbconnectclose function wakeup include the database connection data includeinc ladledbphp thisdbconnect dbconnect function to add events to zodiac calendar public function addeventdate title description check to see if the required fields of date and title have been entered if emptydate emptytitle if all fields are complete then they are inserted into the zodiac event calendar table sqlstring insert into tblsignups eventdate title description valuesdate title description store query results in a variable queryresult thisdbconnectquerysqlstringi am not great with oo php and i am not sure why this error is being raised i pulled this code from elsewhere and the only thing i changed was the new mysqli parameters can anyone help me to understand what is going wrong,"['php', 'mysql']" +577314,how to solve failed to determine navigation direction for scroll bug my most frequent bug has failed to determine navigation direction for scroll for reason any idea about how i could solve ithere is the last exception backtrace 1 corefoundation exceptionpreprocess 131 2 libobjcadylib objc exception throw 39 3 corefoundation nsexception raiseformat 1 4 foundation nsassertionhandler handlefailureinmethodobjectfilelinenumberdescription 91 5 uikit 54 uiqueuingscrollview didscrollwithanimationforce block invoke 221 6 uikit uiqueuingscrollview didscrollwithanimationforce 567 7 uikit uiqueuingscrollview scrollviewanimationendedfinished 73 8 uikit uianimator stopanimation 471 9 uikit uianimatorstatic advanceanimationsoftypewithtimestamp 285 10 uikit uianimatorstatic lcdheartbeatcallback 53 11 quartzcore cathisplaythisplaylinkitemthispatch 99 12 quartzcore cathisplaythisplaylinkthispatch itemsunsigned long long unsigned long long unsigned long long 345 13 iomobileframebuffer iomobileframebuffervsyncnotifyfunc 105 14 iokit iothispatchcalloutfromcfmessage 249 15 corefoundation cfmachportperform 137 16 corefoundation cfrunloop is calling out to a source1 perform function 35 17 corefoundation cfrunloopdosource1 347 18 corefoundation cfrunlooprun 1399 19 corefoundation cfrunlooprunspecific 523 20 corefoundation cfrunloopruninmode 107 21 graphicsservices gseventrunmodal 139 22 uikit uiapplicationmain 1137 23 myapp main mainm13update i finally managed to reproduce the bug on the simulator it is when iam touching a view and that at the same time the uipageviewcontroller scroll animation starts programmatically basically if you setviewscontrollers programmatically with animation set to yes and scroll animation if youre touching any part of the screen before the scroll animation starts there will be the following crash assertion failure in uiqueuingscrollview didscrollwithanimationforce sourcecacheuikituikit2372 uiqueuingscrollviewm778 as described here i also downloaded apples photoscroller sample app and edited it with programmatic page change and they have the same bug my solution was not to trigger the page change if the user is currently touching the screen you can also change the animation to curl or remove the animation,"['ios', 'iphone']" +577368,looking for an mkoverlaypathrenderer example i am trying to figure out how to use a new mkoverlaypathrenderer classin my app i previously used mkoverlaypathview when building with ios 6 sdkbut it does not seem to work with ios 7 sdk unfortunatelyso i am trying to move my app from mkoverlaypathview tomkoverlaypathrenderer but have no success so farmkpolylinerenderer works ok but mkoverlaypathrenderer does notthe code gets called but no overlay is drawn on a mapdoes anybody have a working example for mkoverlaypathrenderer,['ios'] +577702,split string with regex but keep delimeters in match array just cannot find an answer for this one here a sample stringi would want to generate a match array like thissome domain comi have been using the following regex for splitting the stringhowever it results to thissome domain comthe same regex works for javascript and c but not in java anyone knows the proper regex for this thanks,['java'] +577703,drools how to find out which all rules were matched i have one drl file which has say 10 rules once i insert a fact some rules may be matched how do i find out which rules were matched programmatically,['java'] +577719,scanfprintf double variable c let us say i have this following bit of code in cdouble varscanflf varprintflf varprintff varit reads from stdin variable var and then prints twice in stdout vari understand that is how you read a double variable from stdin but my questions are1 why can you print a double with lf2 why can you print a double with f3 which one is better and correct to use,['c'] +577720,how to align the bar and line in matplotlib two yaxes chart i have a pandas df as below df sales net pft sales gr net pft grstk id rpt date 600809 20120331 221401 49253 01824 00268 20120630 381565 78684 03181 01947 20120930 525098 124338 04735 07573 20121231 647876 132731 04435 07005 20130331 279517 75182 02625 05264 20130630 406460 98572 00652 02528 20130930 530501 118605 00103 00461then dfsalesnet pftunstackstk idplotkindbar use indextrue create bar chartand dfsales grnet pft grplotkindline use indextrue create line chartnow i want to put them together in a chart of two yaxes using twinx import matplotlibpyplot as pltfig pltfigureax dfsalesnet pftunstackstk idplotkindbar use indextrueax2 axtwinxax2plotdfsales grnet pft grvalues linestyle markero linewidth20the result is like this my issues arehow to shift the line to align with the bar at the same xtickers how to let the left and right y axis tickers aligned at the same line,['python'] +577744,dynamically reloading ngrepeat data in the dom i have the following code in my view li ngrepeati in itemsiidlii would like the ngrepeat to be trigged dynamically when new values are addedremoved from items as in if a new element is added to be beginning of items then it should be dynamically rendered to the dom at the beginning and similarly if an element is added to the end of items that item should be rendered as the last list item is this dynamic changing of the dom possible in angular,['javascript'] +577859,can i view session state value at clientside using chrome devtools i was just curious if we can getview session variables values for a website using chrome devtoolsif anyone knows please share,['asp.net'] +577926,c avoiding if x is foo else if x is bar for data structures i have a family of data structures likeabstract class base class foo base class bar base and a method which takes a base and converts it depending on which subclass it isvoid convertbase b if b is foo do the foo conversion else if b is bar do the bar conversionobviously this is terrible object orientation the convert method has to know about every derived class of base and has to be changed every time that base is extended the normal oo way of solving this problem is to make each derived class of base responsible for converting itself egabstract class base abstract converted convertclass foo base override converted convertclass bar base override converted converthowever in the code that i am writing base is a pure data structure only getters and setters no logic and it is in another assembly which i do not have permission to change is there a way of better structuring the code that does not force the derived classes of base to have logicthanks,['c#'] +577958,android app not install an existing package by the same name with a conflicting signature is already installed in my emulator when i try to do an upgrade of my apk programmatically i getandroid app not installan existing package by the same name with a conflicting signature is already installedi am still in the testing phase of this upgrade so the file i download is a signed apk of a previous version which i think should work without any issues from the suggestion in an existing package by the same name with a confilcting signature is already installed i tried to run the emulator both in debug mode and in normal mode neither worked any thoughts on what i am missing,['android'] +577974,nested layouts in backbonemarionettejs let us say that i have this javascript all nicely written out for backbonejs with marionettebackbonejsfunction var application function application new backbonemarionetteapplication applicationaddregions top top middle middle bottom bottom var toplayout backbonemarionetteitemviewextend template tpl toplayout tagname article var middlelayout backbonemarionettelayoutextend template tpl middlelayout regions left left right right var middlelayoutone backbonemarionetteitemviewextend template tpl middlelayoutone tagname article var middlelayouttwo backbonemarionetteitemviewextend template tpl middlelayouttwo tagname article var bottomlayout backbonemarionetteitemviewextend template tpl bottomlayout tagname article var a new middlelayout aleftshownew middlelayoutone arightshownew middlelayouttwo applicationtopshownew toplayout applicationmiddleshowa applicationbottomshownew bottomlayout applicationstart and this html article idlayouts section idtopsection section idmiddlesection section idbottomsectionarticlescript typetexttemplate idtpl toplayout top layoutscriptscript typetexttemplate idtpl middlelayout middle layout div idleftdiv div idrightdivscriptscript typetexttemplate idtpl middlelayoutone middle layout 1scriptscript typetexttemplate idtpl middlelayouttwo middle layout 2scriptscript typetexttemplate idtpl bottomlayout bottom layoutscriptthe middle layout does not render properly it renders tpl middlelayout but not tpl middlelayoutone or tpl middlelayouttwoany ideas on what i am forgetting to do i have got my guesses as to why it is not working but no idea on how to fix that problem and google does not seem to want me to know the answer yet any help would be very very much appreciated,['javascript'] +578014,construct pandas dataframe from list of tuples i have a list of tuples likedata r1 c1 avg11 stdev11r1 c2 avg12 stdev12r2 c1 avg21 stdev21r2 c2 avg22 stdev22and i would like to put them into a pandas dataframe with rows named by the first column and columns named by the 2nd column it seems the way to take care of the row names is something like pandasdataframex1 for x in data index x0 for x in data but how do i take care of the columns to get a 2x2 matrix the output from the previous set is 3x4 is there a more intelligent way of taking care of row labels as well instead of explicitly omitting themedit it seems i will need 2 dataframes one for averages and one for standard deviations is that correct or can i store a list of values in each cell,['python'] +578015,whats the difference between easytracker and the regular tracker the google documentation for google analytics version 3 is very confusing regarding the differences between easytracker and the regular tracker class and i am really not sure which one i should be using on this page they talk about setting up the easytracker using the analyticsxml file to set up your id but then on the next page they talk about setting up a regular tracker and passing it your id initialize a tracker using a google analytics property idgoogleanalyticsgetinstancethisgettrackeruaxywhat are the differences between these two trackers does one have more features than the other i gather that the easytracker is simpler to set up if you just want activity tracking but if i want to use all of the features available to me in google analytics can i still do all that with the easytracker or do i need to switch to the regular tracker,['android'] +578059,get ip addresses from udp and http torrent tracker response i am trying to get the peerlist list of ip addresses from a torrent trackersimilar to the question here how to get the peer list from torrent tracker responsei wrote code which decodes the torrent files using the python bencode bittorrent library i wrote code following this code here to scrape torrent trackerat least for http request like to mininova tracker i get the following output for a specific info hashfiles xbfxffxcdyx05x9bxb2c2jx83xf5f x9bgx9dxe2g downloaded 25416 complete 12 incomplete 0i do not see any of the other keys that the bittorrent documents here in the spec like tracker id min interval peers etchow can i get the peer list,['python'] +578111,android ui thread message queue thispatch order while working with retain fragments in android to hold an asynctask during configuration changes which i guess it is the best approach some doubts appear in my mind about ui threads message queue invocation order ex imagine this scenarioconfiguration change occurs user rotates the device asynctask is runningfragment ondetach is calledasynctask doinbackground method finishesasynctask onpostexecuteis calledfragment onattach is calledso can ui thread message queue be like thisqueue top ondetach onpostexecute onattachi know it cannot the call to onpostexecute will wait until the configuration change completes as far as i know but how does that work are the calls from activities fragments lifecycles executed consecutively,['android'] +578128,error this operation would create an incorrectly structured document i keep trying to install the entity framework 6 and it always rolls back with the error oferror this operation would create an incorrectly structured documenti have uninstalled all the references to every dll mentioned at this location the crazy thing is that i can create a new project create a webapi program and attempt to add entity framework 6 and i get the same error even after removing all references to systemdataentitydll i am already a few days into this and needing serious helpwhat can i do to get entity framework 6 to installnote it will install just find to a class library just not a webapi or mvc applicationif it helps here is some more detailed error infopm installpackage entityframework version 600installing entityframework 600successfully installed entityframework 600adding entityframework 600 to acsuccessfully added entityframework 600 to acsysteminvalidoperationexception this operation would create an incorrectly structured document at systemxmllinqxdocumentvalidatedocumentxnode previous xmlnodetype allowbefore xmlnodetype allowafter at systemxmllinqxdocumentvalidatenodexnode node xnode previous at systemxmllinqxcontaineraddnodeskipnotifyxnode n at systemxmllinqxcontaineraddcontentskipnotifyobject content at systemxmllinqxcontaineraddobject content at systemdataentitymigrationsextensionsxcontainerextensionsgetorcreateelementxcontainer container string elementname xattribute attributes at systemdataentityconnectionfactoryconfigconfigfilemanipulatoraddorupdateconfigsectionxdocument config version entityframeworkversion at systemdataentityconnectionfactoryconfiginitializeentityframeworkcommandc thisplayclass3executeb 1xdocument c at systemdataentityconnectionfactoryconfigconfigfileprocessorprocessconfigfileprojectitem configitem ienumerable1 manipulators at systemdataentityconnectionfactoryconfiginitializeentityframeworkcommandc thisplayclass3executeb 0projectitem i at systemdataentityconnectionfactoryconfigconfigfilefinderfindconfigfilesprojectitems items action1 action at systemdataentityconnectionfactoryconfiginitializeentityframeworkcommandexecute at systemdataentitymigrationsmigrationsdomaincommandexecuteaction commanduninstalling entityframework 600successfully uninstalled entityframework 600install failed rolling backinstallpackage this operation would create an incorrectly structured documentat line1 char16 installpackage entityframework version 600 categoryinfo notspecified installpackage runtimeexception fullyqualifiederrorid nugetcmdletunhandledexceptionnugetpowershellcommandsinstallpackagecommand,['c#'] +578130,mysql nested select query ok so i have the following queryselect mindate player namefrom player playtimegroup by player namei then need to use this result inside the following queryselect datedate countthistinct player namefrom player playtime use previous query result heregroup by date date desc limit 60how would i go about doing this,"['mysql', 'sql']" +578159,implementing prototype method if i implemented a method x on a string like stringprototypex function a and then the new version of javascript actually implements the x method but on the another way either returning something different than my implementation or function with moreless arguments than my implementation will this break my implementation and override it,['javascript'] +578212,uigraphicsgetimagefromcurrentimagecontext memory leak i am opening the camera with uiimagepickercontrollersourcetypecamera and a custom cameraoverlayview so i can take multiple photos without the use photo stepthis is working great but there is a memory leak in the save photo function through a lot of debugging and research i have narrowed it down to the uigraphicsgetimagefromcurrentimagecontext functionhere is a snippet of code where it happensuigraphicsbeginimagecontextwithoptionstimestampedimageframesize timestampedimageopaque uiscreen mainscreen scaletimestampedimage layer renderincontextuigraphicsgetcurrentcontextuiimage finaltimestampimage uigraphicsgetimagefromcurrentimagecontextuigraphicsendimagecontexti have scoured the internet and it seems that the uigraphicsgetimagefromcurrentimagecontext function quoted from this so question returns a new autoreleased uiimage and points the finaltimestampimage ivar to it the previously allocated uiimage is never actually released the variable to it is just repointed to somewhere else i have tried so many solutions that have apparently worked for othersadding timestampedimagelayercontents nil after uigraphicsendimagecontextadding cgcontextref context uigraphicsgetcurrentcontext and cgcontextreleasecontext after uigraphicsendimagecontextwrapping the above snippet in an nsautoreleasepoolwrapping the entire savethisphoto function in an nsautoreleasepoolcreating an nsautoreleasepool when the camera pops up and calling the pool release when didreceivememorywarning is calledclosing the camera popup when didreceivememorywarning is called hoping it will clear the poolevery possibly combination of the aboveyet everything i try when i take photos i can see the memory utilized rising and not falling when i am repeatedly taking photos on the devicedoes anyone know how i can release the autorelease object created by uigraphicsgetimagefromcurrentimagecontextalternatively is there an alternative way to make a uiimage out of an uiimageviewedit here are the full functions as requested there is a lot of extra releasing added in there just to try make sure everything is cleaned up i have gone through and tested for the memory leak with each code block in savethisphoto systematically and it only occurs when the uigraphicsgetimagefromcurrentimagecontext block snippet above is run voidimagepickercontrolleruiimagepickercontroller picker didfinishpickingmediawithinfonsdictionary info nslogsaving photo self savethisphotoinfo picker nil picker release info nil info release voidsavethisphotonsdictionary info get photo count for filename so were not overriding photos int photocount 0 if nsuserdefaults standarduserdefaults objectforkeyphotocount photocount nsuserdefaults standarduserdefaults objectforkeyphotocount intvalue photocount nsuserdefaults standarduserdefaults setobjectnsstring stringwithformatd photocount forkeyphotocount nsuserdefaults standarduserdefaults synchronize obtaining saving path nsarray paths nssearchpathfordirectoriesindomainsnsdocumentdirectory nsuserdomainmask yes nsstring documentsdirectory paths objectatindex0 nsstring filename nsstring stringwithformatri djpg photocount nsstring filenamethumb nsstring stringwithformatri d thumbjpg photocount nsstring imagepath documentsdirectory stringbyappendingpathcomponentfilename nsstring imagepaththumb documentsdirectory stringbyappendingpathcomponentfilenamethumb extracting image from the picker and saving it nsstring mediatype info objectforkeyuiimagepickercontrollermediatype save to ipad and db if mediatype isequaltostringpublicimage get image uiimage editedimage info objectforkeyuiimagepickercontrolleroriginalimage figure out image orientation cgsize resizedsize cgsize thumbsize if editedimagesizeheight editedimagesizewidth resizedsize cgsizemake480 640 thumbsize cgsizemake150 200 else resizedsize cgsizemake640 480 thumbsize cgsizemake150 113 make normal size image uiimage editedimageresized editedimage resizedimageresizedsize interpolationquality08 clean up the one we would not use any more editedimage nil editedimage release add timestamp to image make the view uiimageview timestampedimage uiimageview alloc initwithimageeditedimageresized cgrect thisrect cgrectmakeeditedimageresizedsizewidth 510 editedimageresizedsizeheight 30 500 20 clean up editedimageresized nil editedimageresized release make the label uilabel timelabel uilabel alloc initwithframethisrect timelabeltextalignment uitextalignmentright timelabeltextcolor uicolor yellowcolor timelabelbackgroundcolor uicolor clearcolor timelabelfont uifont fontwithnamearial rounded mt bold size250 timelabeltext self gettodaysdatedatabaseformat timestampedimage addsubviewtimelabel clean up what we would not use any more timelabel nil timelabel release make uiimage out of the imageview memory leak looks like it is in this block nsautoreleasepool pool nsautoreleasepool alloc init uigraphicsbeginimagecontextwithoptionstimestampedimageframesize timestampedimageopaque uiscreen mainscreen scale timestampedimage layer renderincontextuigraphicsgetcurrentcontext uiimage finaltimestampimage uigraphicsgetimagefromcurrentimagecontext uigraphicsendimagecontext timestampedimagelayercontents nil cgcontextref context uigraphicsgetcurrentcontext cgcontextreleasecontext clean up the one we would not use any more timestampedimage nil timestampedimage release save normal size image to documents folder nsdata webdataresized uiimagejpegrepresentationfinaltimestampimage 10 jpg webdataresized writetofileimagepath atomicallyyes clean up the one we would not use any more finaltimestampimage nil finaltimestampimage release pool release to get rid of the context image that is stored save to database sqlite executenonqueryinsert into inspection images agentidgroupidinspectionidareaidfilenamefilenamethumbfilepathorderidtype values nsnumber numberwithintloggedin nsnumber numberwithintloggedingroup myinspectionid tabledata objectatindexalertdome objectforkeyareaid filename filenamethumb documentsdirectory nsnumber numberwithintphotocount nsnumber numberwithintispcr clean up webdataresized nil webdataresized release else nslog image not saved nslogimage saved complete info nil info release,"['ios', 'objective-c']" +578283,combination of postgresql and neo4j for networking site we are designing a networking site where data would be connected to each other in complex way we plan to use neo4j so that we could escape costly join otherwise required since neo4j is specifically designed for graph like data so it seems suitablehowever we have realized that although neo4j is fast in some aspect but the representation of relational data is best done through relational database so its like we plan to use neo4j at some of the functionality and postgresql at other functionality for example we would use neo4j for finding relevant feeds to user by searching through different nodes which he follows while for other activities like updating profile information etc we would like to use postgresql we did some performance testing for profile information updation and found that postgresql is faster than neo4j while analyzing feed data neo4j is much much fasternow my question is have anyone used combination of databases like this before specifically neo4j with postgresql we do find some problems while integrating different databases but we find it worth itplease share your experience and feedback thanks,['sql'] +578286,string pointers in c i have a windows form application in c that uses a function in c this was done using a c wrapper however the function requires the use of pointers and c does not allow the use of pointers with string arrays what can be done to overcome thisi have read up on using marshal but i am not sure if this is suitable for this case and if so how should it be integrated with my codethe following is the c code int elements 10string sentence new stringelementsunsafe fixed string psentence sentence0 cwrapcwrap class1 contcp new cwrapcwrap class1psentence elements contcpgetsum c function declarationfunctfunctstring sentence array int sentence arraysizec wrappercwrapcwrap class1cwrap class1string sentence array int sentence arraysize pcc new functsentence array sentence arraysize,['c#'] +578471,how to add custom menu item to uitextview menu which is a link to the wikipedia page of the selected word i am new to xcode i am using version 463 macbook too old for the new versioni looked around the internet and stack overflow and cannot find what i want or i cannot get snippets to worki would like to add a menu item to the menu items that appear when longpressing a word in a uitextview i want it to say wiki and when this is pressed it will link to the wikipedia page of the word that is selected it may be through safari or should i do this within the app with a webviewi founduimenucontroller menucontroller uimenucontroller sharedmenucontrolleruimenuitem item1 uimenuitem alloc initwithtitledo this actionselectoritem1menucontroller setmenuitemsnsarray arraywithobjectitem1but this did not seem to do anythingunfortunately i cannot understand the suggestions for retrieval of a wkipedia page i am not that advanced sorry i usually do not know where to put the code snippets the uilabel i have thisplays the text better the text in the rectangular uitextview has a gap at the top so the text is not centredoffsetting the uitextview parameters means the text is anchored at the top not centrally attaching menus to a uilabel seems very difficult,"['iphone', 'objective-c']" +578528,cross domain javascript callback is not supported in authenticated services ajax query to wcf service via ssl proxy i have a wcf svc web service which is consumed by a javascript call via ajaxthe page is accessed via a ssl proxy located in the dmz which then forwards the request to the internal webserver httpmylocalwebservermypageafter a lot of googeling and trying around i was able to make it work playing around with the parameters crossdomainscriptaccessenabled and accesscontrolalloworigin although it does only work if the authentication mode is set to false or if the user is not logged in yet as soon as the call is made from within a page on which you need to be logged in forms authentication it does not work any more the error message i get then iscross domain javascript callback is not supported in authenticated servicesit does work again however once i logout and do the call from a nonprotected pagemy service looks like thisnamespace mynamespace servicecontractnamespace mynamespace aspnetcompatibilityrequirementsrequirementsmode aspnetcompatibilityrequirementsmodeallowed public class service operationcontract public string getdropdowndatastring id liststring resultlist new liststring return resultlisttoarray the service call and the callback method in javascriptfunction filldropdwondropid jqueryajax type post datatype jsonp contenttype applicationjson charsetutf8 cache true url servicesvcgetdropdowndata data dropid dropid jsonpcallback ondone error function abc alerterror callbackmethode after servicecallfunction ondoneresult var thedropdown jquery cboselectionclientid if thedropdownlength 0 clear the old entries thedropdownempty add an empty entry if cboselectionshowemptyrow tolowercase true thedropdownappendoptionoption add the found items for var i 0 i resultlength i var text resulti thedropdownappendoptionoptionvaltexthtmltext the webconfig part which concerns the servicesystemservicemodel behaviors endpointbehaviors behavior namemynamespaceserviceaspnetajaxbehavior enablewebscript behavior endpointbehaviors servicebehaviors behavior servicemetadata httpgetenabledtrue behavior servicebehaviors behaviors servicehostingenvironment aspnetcompatibilityenabledtrue multiplesitebindingsenabledtrue standardendpoints webscriptendpoint standardendpoint crossdomainscriptaccessenabledtrue name webscriptendpoint standardendpoints services service namemynamespaceservice service endpoint for https endpoint address behaviorconfigurationmynamespaceserviceaspnetajaxbehavior bindingwebhttpbinding bindingconfigurationjsonpbinding contractmynamespaceservice service services bindings webhttpbinding binding namejsonpbinding crossdomainscriptaccessenabledtrue security modenone binding binding namejsonpsslbinding crossdomainscriptaccessenabledtrue security modetransport binding webhttpbinding bindingssystemservicemodeli first tried to use the aspnet ajax proxy to call the service but this did not work because the call was made to the webserver directly which is not ssl and the error i got was more or less page tried to load not save content from page httpmylocalwebservermypage that is why i used the ajaxcall listed abovefunction filldropdwondropid var service new mynamespaceservice servicegetdropdowndatadropid ondonei also tried to add the following in the webconfigsystemwebserver httpprotocol customheaders enable cross domain ajax calls remove nameaccesscontrolalloworigin add nameaccesscontrolalloworigin value customheaders httpprotocolsystemwebserveri checked the headers sent to the server and saw that when i am not logged in the header looks like thisrequest urlrequest methodpoststatus code200 okrequest headersview sourceaccepttextjavascript applicationjavascript applicationecmascript applicationxecmascript q001acceptencodinggzipdeflatesdchacceptlanguagedededeq08enusq06enq04frchq02frq02connectionkeepalivecontentlength161contenttypeapplicationjson charsetutf8cookie utma17417273011579903691360852643138122970513831504359 utmc174172730 utmz174172730136963548443utmcsrgoogleutmccnorganicutmcmdorganicutmctrnot20provided promopostoaezz3fzzj0o4l3fccxh0ss1aspnet sessionidhostgatecompanycomoriginrefereruseragentmozilla50 windows nt 61 wow64 applewebkit53736 khtml like gecko chrome310165048 safari53736xrequestedwithxmlhttprequestquery string parametersview sourceview url encodedcallbackondonerequest payloadview sourcedropid123dropid 123response headersview sourcecachecontrolprivateconnectionkeepalivecontentencodinggzipcontentlength1339contenttypeapplicationxjavascriptdatesun 01 dec 2013 151425 gmtkeepalivetimeout15 max97servermicrosoftiis75varyacceptencodingxaspnetversion4030319xpoweredbyand the response looks like thisondoneresult1result2when i call the service from within a protected page i get thisrequest urlrequest methodpoststatus code200 okrequest headersview sourceaccepttextjavascript applicationjavascript applicationecmascript applicationxecmascript q001acceptencodinggzipdeflatesdchacceptlanguagedededeq08enusq06enq04frchq02frq02connectionkeepalivecontentlength161contenttypeapplicationjson charsetutf8cookie utma17417273011579903691360852643138122970513831504359 utmc174172730 utmz174172730136963548443utmcsrgoogleutmccnorganicutmcmdorganicutmctrnot20provided promopostoaezz3fzzj0o4l3fccxh0ss1aspnet sessionid aspxauthab5adce12c7847ca452dd54d903e6787c7d1f09b9e3277d2ec50de9c421d1331b87a6dca2432993933794ab9bde833e44ec58e217d5aa1d588132c6e1c67d4ad7692840359d9a719ec2a53826cf54fdc0943b4e0ab29093920143e1e987080ac7c35e63594fd678535972d06aec0aaf74af8be8dfc3746b499cb032e71f10b924110db344824b3253f9becb3cdd8hostgatecompanycomoriginrefereruseragentmozilla50 windows nt 61 wow64 applewebkit53736 khtml like gecko chrome310165048 safari53736xrequestedwithxmlhttprequestquery string parametersview sourceview url encodedcallbackondonerequest payloadview sourcedropid123dropid 123response headersview sourcecachecontrolprivateconnectionkeepalivecontentencodinggzipcontentlength1339contenttypeapplicationxjavascriptdatesun 01 dec 2013 151425 gmtjsonerrortruekeepalivetimeout15 max97servermicrosoftiis75varyacceptencodingxaspnetversion4030319xpoweredbyaspnetand the response looks like thisondoneexceptiondetailhelplinknullinnerexceptionnullmessagecross domain javascript callback is not supported in authenticated servicesstacktrace bei systemservicemodelthispatcherjavascriptcallbackmessageinspectorafterreceiverequestmessage request iclientchannel channel instancecontext instancecontextu0du0a bei systemservicemodelthispatcherimmutablethispatchruntimeafterreceiverequestcoremessagerpc rpcu0du0a bei systemservicemodelthispatcherimmutablethispatchruntimeprocessmessage2messagerpc rpcu0du0a bei systemservicemodelthispatchermessagerpcprocessboolean isoperationcontextsettypesystemnotsupportedexceptionexceptiontypesystemnotsupportedexceptionmessagecross domain javascript callback is not supported in authenticated servicesstacktrace bei systemservicemodelthispatcherjavascriptcallbackmessageinspectorafterreceiverequestmessage request iclientchannel channel instancecontext instancecontextu0du0a bei systemservicemodelthispatcherimmutablethispatchruntimeafterreceiverequestcoremessagerpc rpcu0du0a bei systemservicemodelthispatcherimmutablethispatchruntimeprocessmessage2messagerpc rpcu0du0a bei systemservicemodelthispatchermessagerpcprocessboolean isoperationcontextset500the main difference is that there is a sessionid and the jsonerrortrue for the version logged init there a way to fix this problemis it not possible to thisable the authentication for the ajax request by changing the header before the call or something like that or is there any error in my code webconfigi appreciate any hint since i am trying around for a long time,['asp.net'] +578594,opaque white background with rgba thisplays grey over white background i added a transparent background on a div over a white background with like thatbody background whiteopaquewhite background rgba255255255095 height 300px width 300pxbody div classopaquewhite area with opaque opacity 095 background divbodyjsfiddle link but for some reason the color of the div shows grey instead of white opaque white over white should thisplaywhite rightor am i mistakenediti am adding a screenshot of the problem it is a very subtle difference yet noticeable in some screens to actually understand the difference try color picking the left side of the image with the right area,['css'] +578678,unable to convert runtime connection string to its designtime equivalent i updated to visual studio 2013 last week and i can no longer update my entity data model through the visual studio designer edmx file when i right click update model from database i now receive this erroran exception of type systemargumentexception occurred while attempting to update from the database the exception message is unable to convert runtime connection string to its designtime equivalent connection string server192168100103user idxpasswordxdatabasexpersist security infotruemy connection string is as follows connectionstringsadd namedbentities connectionstringmetadataresdbcsdlresdbssdlresdbmslprovidermysqldatamysqlclientprovider connection stringquotserver192168100103user idxpasswordxdatabasexpersist security infotruequot providernamesystemdataentityclient the process still works fine in visual studio 2012,['c#'] +578698,f2py access module parameter from subroutine i cannot get f2py to reference a parameter from a module in a separate subroutine where it is used to defined an input array dimension ie the paramter is defeind in a module file testmodf90module testmodinteger parameter dimsize 20end module testmodand the parameter dimsize needs to be referenced in a subroutine not contained in the module in another file which will be the entry point for my python module file testsubf90subroutine testsubarguse testmodreal intentin argdimsizeend subroutine testsubi compile like thisf2py m testmod h testmodpyf testsubf90pgf90 g mbounds mchkptr c fpic testmodf90 o testmodopgf90 g mbounds mchkptr c fpic testsubf90 o testsubof2py c testmodpyf testmodo testsubobut get this errortestmodmodulec in function f2py rout testmod testsubtestmodmodulec180 error dimsize undeclared first use in this functioni have tried modifying testsubg90 to include the following directive as suggested ni other postssubroutine testsubarguse testmodf2py integer parameter dimsizereal intentin argdimsizeend subroutine testsubbut to no avail i need to keep the subroutine separate from the modulehow can i get f2py to correctly resolve the variable dimsizetia,['python'] +578703,how to express numbers in scientific notation in java i am writing a program that deals with planets mass and diameter these quantities are expressed in scientific notation my question is not mind you not how does one print large numbers the right way that is using printf duh its how i would type these numbers i guess you could say for example the mass of mercury is expressed 330 x 10e23and in my array of planet masses an element would look 330 mathpow10 23however i do not quite think this is the right way it looks like it would throw an exception so how could i express large numbers like that from a programmers perspective thanks,['java'] +578734,ios 7 uinavigationbar appearance not working first timea i am trying to change the look of the uinavigationbat in my ios7 app i am doing the following voidviewdidload super viewdidload m snumbertocall uibarbuttonitem btn uibarbuttonitem alloc initwithimageuiimage imagenamediconhomepng styleuibarbuttonitemstylebordered targetself actionselectorbthometouched selfnavigationitemleftbarbuttonitem btn selfnavigationcontrollernavigationbartranslucent yes selfnavigationcontrollernavigationbarbartintcolor uicolor redcolor uinavigationbar appearance setbackgroundimageuiimage imagenamedtvcnavbackpng forbarmetricsuibarmetricsdefault nsshadow shadow nsshadow alloc init shadowshadowcolor uicolor colorwithred00 green00 blue00 alpha08 shadowshadowoffset cgsizemake0 1 uinavigationbar appearance settitletextattributes nsdictionary dictionarywithobjectsandkeys uicolor colorwithred24502550 green24502550 blue24502550 alpha10 nsforegroundcolorattributename shadow nsshadowattributename uifont fontwithnamehelveticabold size210 nsfontattributename nilbut the first time i present the uitableviewcontroller it is the standard ios7 nag bar then i press home and present it again and it is my new lookany ideas why it does not work the first time,"['ios', 'objective-c']" +578738,is audio playback via alsa supported in qt5 i have a small c qt program that uses a qaudiooutput instance to emit sound it compiles runs fine using qt 485however in qt 50 51 and 52 my application compiles but does not work i get the following error message while the constructor of the qaudiooutput instance is runningunable to create a connection to the pulseaudio contextalso the constructor does not return so my program hangsi do not have pulseaudio running alsa is working fine and this is what my program uses when compiled with qt 485inspecting the qt5 apluginsaudioa directory there is only alibqtmedia pulsesoa there the name of which suggests that it depends on pulseaudiomy questionsis there still a backend for output to alsa without pulseaudio in qt 5 if yes how do i make sure it is built i do not see any configure options for thatit appears to be a bug that the constructor of qaudiooutput hangs my app where can i report that,['c++'] +578749,iis idle timeout vs recycle in iis there are two areas well more than two where recycling can occur1 under the process model section idle timeout default 20 minutes and2 under the recycle section regular time interval default 1740 mmy questions area what are the differences between the two methodsb what are the negative implications of settings them to 0thanks,['asp.net'] +578791,mavenshadeplugin uberjar and overlapping classes i would like to use mavenshadeplugin to create uberjar but when i call mvn package command maven reports that there are some overlapping classes i am attaching all problematic overlapps some of them are caused because older and new verion of a library log4j but some of them seems to have the same classes eg javaxmail and mailapismtpimap et ceterawhat is the best to do in this situation is there some key how to decide which overlapping is safe to ignore a which needs to be correct mailapi143jar javaxmail150jar define 166 overlaping classes spring256sec03jar springtx314releasejar define 176 overlaping classes springbeans314releasejar spring256sec03jar define 283 overlaping classes slf4jlog4j12175jar slf4jimpl20beta2jar define 3 overlaping classes spring256sec03jar springcontextsupport314releasejar define 55 overlaping classes aopalliance10jar spring256sec03jar define 9 overlaping classes imap150jar javaxmail150jar define 87 overlaping classes commonsloggingapi11jar commonslogging113jar define 19 overlaping classes spring256sec03jar springcore314releasejar define 161 overlaping classes spring256sec03jar springcontext314releasejar define 326 overlaping classes log4j12api20beta3jar log4j1217jar define 23 overlaping classes springaop314releasejar spring256sec03jar define 237 overlaping classes springjdbc314releasejar spring256sec03jar define 239 overlaping classes quartz186jar quartzjobs221jar define 15 overlaping classes smtp150jar javaxmail150jar define 17 overlaping classes springasm314releasejar spring256sec03jar define 31 overlaping classes edit this application a uses as a maven dependency my another java application i will call this app b this b application uses javaxmail ver 151 this library uses the first application too but when i call mvn package command maven notices that javaxmailapi151jar javaxmail151jar define 135 overlaping classesis this problem and if so how to solve it or can i ignore it,['java'] +578814,why is vector considered nothrow move constructible the specification for vectors move constructor is copied out of the standardvectorvectornotice the lack of noexcept but both gcc 48 and clang 32 report that stdis nothrow move constructiblestdvectorintvalue returns true ie 1includevectorincludeiostreamint main stdcout stdis nothrow move constructiblestdvectorintvalue nwhat is the cause of this apparent thiscrepancy,['c++'] +578824,cordova plugin blocking thread i am creating a custom plugin for an android cordovaphonegap application and the native java side fires up an activity that includes a callback called by a service it starts the idea is that callback gets hit every second or so from the service and works great but the problem is that i cannot seem to get this running in another thread so the main cordova thread is blocked and the app is totally unresponsivebased on the documentation i am doing thisoverridepublic boolean executestring action jsonarray args final callbackcontext context throws jsonexception snip cordovagetthreadpoolexecutenew runnable public void run intent myintent new intentthiscordovagetactivity mymonitoringclass thiscordovagetactivitystartactivitymyintent callbackcontextsuccess return truei realise here the js callback will never get called ie callbackcontextsuccess because the activity is blocking but should not the actual phonegap thread keep running after return true if i remove the startactivity call then the app carries on working as expected,['android'] +578850,strange behavior of python is operator if combined with in how does python interpret a in abc is true i was trying to evaluate the following two expressions a in abc is truefalse a in abc is truetruei know is keyword should not generally be used to compare to true this is just an example,['python'] +578883,androidphonegap androidwindowsoftinputmode does not seem to work i am developing a phonegapbased application and i googled much about how to make my webview adjust its height when virtual keyboard appears or at least get height of the virtual keyboard i found a lot of posts including stackoverflow which says thatandroidwindowsoftinputmodeadjustresizemust be set in the manifest and i did that i also found that for phonegap configxml there ispreference nameandroidwindowsoftinputmode valueadjustresizesetting and i pasted that too i also tried combined value statevisibleadjustresize not just adjustresize for both parameters but it seems to me that they both have no effect i do not know maybe i am doing something wrong but you can check the screenshots from the emulator android 403 but i also tried 412 and 422 keyboard visible keyboard hiddenon the screenshot i intentionally captured my manifest and configxml settings so you may see they are actually therei even recorded short video as you may see no any viewport resizing occur when keyboard shown hiddeni also checked windowinnerheight using consolelog and it stays same for both visible and hidden keyboardplease give me some advice,['android'] +578925,animation when inserting a larger row into a uitableview assuming the wrong height i am having a problem in animating the addition or removal of a row in a uitableview which has a different height than other rowsthe following gifs demonstrats the issue with rows of the default height 44pts and an larger row 100pts being inserted and removed the one on the left is a screen recording from the simulator the new cell ending up covering row five is a different issue and the one on the right is a mockup of what it should doin my case i have a bunch of rows each 60pts in height when a button in the cell is tapped an edit cell will slide out from underneath pushing lower cells down this edit cell is 180pts high when i call insertrowsatindexpathswithrowanimation or deleterowsatindexpathswithrowanimation the animation assumes the wrong height of 60pts instead of the 180pts it should bethis means that in the case of uitableviewrowanimationtop the new cell appears at 60pts from the position it will end up at and slides down to its new position about a third of the animation it should be doing meanwhile the row below animates smoothly from its starting position to 180pts downward exactly as it shouldhas anyone worked out an actual solution to this some way to tell the new row what hight it is supposed to be for the animationbelow is the code i am using to hide and show the edit row i am using a tlswipeforoptionscell to trigger the edit but it is easily replicated using for example tableviewdidselectrowatindexpathvoidhideeditfields selftableview beginupdates selftableview deleterowsatindexpathsnsindexpath indexpathforitemeditformvisibleforrow1 insection0 withrowanimationuitableviewrowanimationtop editformvisibleforrow 1 selftableview endupdatesvoidcelldidselectmoretlswipeforoptionscell cell nsindexpath indexpath selftableview indexpathforcellcell do nothing if this is the currently selected row ifeditformvisibleforrow indexpathrow ifeditformvisibleforrow 0 self hideeditfields update the index path as the cell positions may have changed indexpath selftableview indexpathforcellcell selftableview beginupdates editformvisibleforrow indexpathrow selftableview insertrowsatindexpaths nsindexpath indexpathforitemeditformvisibleforrow1 insection0 withrowanimationuitableviewrowanimationtop selftableview endupdates nsinteger tableviewuitableview tableview numberofrowsinsectionnsintegersection return datasourcecount editformvisibleforrow 0 1 0cgfloat tableviewuitableview tableview heightforrowatindexpathnsindexpath indexpath int row indexpathrow ifeditformvisibleforrow 0 row editformvisibleforrow row editformvisibleforrow 1 return 1800f else return 600poking around a bit it seems like this is a common issue with no clear answer most of the similar questions i have found here on so are unanswered or offer workarounds specific to the askers situation examples problem with rowanimation custom uitableviewcell height yields improper animation uitableview animation glitch when deleting and inserting cells with varying heightsalso instead of trying to make one triplesized edit row i tried making three smaller rows and animating them but this was not suitable because they all appeared at once i also tried animating them one after the other but the easing made it look odd with an obvious 3step animation occurring instead of the whole edit view sliding out of view in one motionedit i have just noticed that if i call reloadrowsatindexpathswithrowanimation uitableviewrowanimationnone for the row above the one i am trying to animate it changes the behaviour of the animation namely the animation assumes the height is 0pts as demonstrated in the following animation it is closer to what i want but still not right as the animation speed is wrong and it leaves a gap in my app this means the backgroundcolour pokes through,['ios'] +578984,should i get into android studio or should i stick to eclipse i started programming a few months ago and learned python and i started learning java about a month agoi have been using sublime text for coding java programs and now as i am getting into android programming i found two official ides eclipse and android studioafter two hours of research i have learned a few things android studio is an early preview and it is not recommended for beginnershowever android studio shows so much promise that i think it will be taking over eclipse in the next few years assuming that google will publish an official polished version in early 2014i have nothing against eclipse but it just seems like android studio is the way to go if i am looking to program android apps 5 years laterwhat are you guys opinion on iti know the basic idea of how android programming works including xml and wanted some recommendation on whether i should get into android studio or notas android studio is a rolling release it is not like i would have to start all over when new versions come out so i think updating versions is not a problemso will it benefit me in the future if i get into using android studio rather than sticking to traditional eclipse with android sdkneed some answers from experienced developers who useused eclipse and have tried android studiothanks,['android'] +579004,angularjs remove ngrepeat item if contains strings i have been cleaning up an external json url feed that i am using and i have successfully removed unnecessary special characters via a filter as soangularjsfilterremovechar function return functiontext text textreplaceg characters inside brackets return textreplace characters after colon span ngbindhtmlunsafeitem removecharitemspanhowever what i am trying to achieve now is to remove an ngrepeat item if it contains a specific string via a filter i can usefor examplediv ngrepeatitem in items removeitemitemflowersdivif the item contains the word red or greendivblue rosesdivdivred rosesdivdivorand and green rosesdivdivyellow rosesdivdivred and green rosesdivonly this will thisplay from the ngrepeat with the filterdivblue rosesdivdivyellow rosesdivhelp with an example would greatly be appreciatedthanksroc,['javascript'] +579031,afnetworking cause error while using xctest in xcode5 i am using xcode 5 and now just started unit testing on my existing project for that i added the cocoatouch unit testing bundle as a target target name is myapptests to my projecti was previously added afnetworking library using cocoapodswhile i am running the test case i got the error afnetworkingh file not found i added afnetworkingh in the testsm but issue till remains is there any additional setting s for including the pods to my testing target,"['ios', 'iphone']" +579076,error attribute has already been defined when using two library projects in android i am using androidsupportv7appcompat as a library in my android project now i want to include actionbarsherlock as another library project when i add the second library it gives so many errors like belowandroidsupportv7appcompatresvaluesattrsxml476 error attribute attributename has already been definedby changing one attribute value and it is related code snippet is a one solution that i have tried but when there are nearly 80 lines like above it will get a messy is there any other way i can solve this issue,['android'] +579099,creating java application using visual studio 2013 is it possible to create a java application using visual studio 2013 because i do not like using netbeans or eclipse and i prefer using visual studio over those sdks thanks,['java'] +579192,returning every second row of an sql query i am working with an app which uses phpactiverecord and mysql to pull in data from a sensor network and plot it onto a number of flotjs graphs on the clientthere are several timeframes the user can chose between to affect the range of data the graphs thisplay 2hrs 24hrs 3 days and 1 weekthe sensors post to the database every 60 seconds so when plotting the graphs the query pulls in all rows between now and date subcur date interval day where is either 1 3 or 7 etchowever this results in a massive number of rows being returned 60 for the full week and is causing huge delays and server errorsi know i can just massively increase the max memory available for queries in the phpini file but this is hardly a good solution and does not solve the issue of speedmy question is is there a way i can easily select only every second or third row from the required date range depending on the length of the interval the user wishes to viewin c or java i would do something like a modulo select to return alternate rows but i cannot think of a way to do this in the current frameworkany ideas would be appreciated thanks,"['javascript', 'php', 'mysql']" +579201,enabled ciphers on ubuntu openjdk 7 i wrote the following java program to dump the enabled ciphers in the jvmimport javasecuritykeystoreimport javaxnetsslkeymanagerfactoryimport javaxnetsslsslcontextimport javaxnetsslsslsocketimport javaxnetssltrustmanagerfactorypublic class listciphers public static void mainstring args throws exception sslcontext ctx sslcontextgetinstancetlsv1 create an empty trustmanagerfactory to avoid loading default ca keystore ks keystoregetinstancejks trustmanagerfactory tmf trustmanagerfactorygetinstancesunx509 tmfinitks ctxinitnull tmfgettrustmanagers null sslsocket socket sslsocket ctxgetsocketfactorycreatesocketmozillaorg 443 printsupportedcipherssocket printenabledcipherssocket private static void printsupportedcipherslsocket socket printinfossupported cipher suites socketgetsupportedciphersuites private static void printenabledcipherslsocket socket printinfosenabled cipher suites socketgetenabledciphersuites private static void printinfosstring prefix string values systemoutprintlnprefix for int i 0 i valueslength i systemoutprintln valuesi when i run this program on ubuntu 12043 with openjdk7jreamd64 7u2523101ubuntu012042 usrlibjvmjava7openjdkamd64jrebinjava with debugging enabled i get the following output usrlibjvmjava7openjdkamd64jrebinjava djavaxnetdebugall listcipherstrigger seeding of securerandomdone seeding securerandomignoring unsupported cipher suite tls dhe dss with aes 128 cbc sha256ignoring unsupported cipher suite tls dhe dss with aes 256 cbc sha256ignoring unsupported cipher suite tls dhe rsa with aes 128 cbc sha256ignoring unsupported cipher suite tls ecdh rsa with aes 128 cbc sha256ignoring unsupported cipher suite tls dhe rsa with aes 256 cbc sha256ignoring unsupported cipher suite tls ecdhe rsa with aes 256 cbc sha384ignoring unsupported cipher suite tls ecdh ecdsa with aes 256 cbc sha384ignoring unsupported cipher suite tls rsa with aes 256 cbc sha256ignoring unsupported cipher suite tls ecdhe rsa with aes 128 cbc sha256ignoring unsupported cipher suite tls ecdhe ecdsa with aes 256 cbc sha384ignoring unsupported cipher suite tls ecdh rsa with aes 256 cbc sha384ignoring unsupported cipher suite tls ecdhe ecdsa with aes 128 cbc sha256ignoring unsupported cipher suite tls ecdh ecdsa with aes 128 cbc sha256ignoring unsupported cipher suite tls rsa with aes 128 cbc sha256allow unsafe renegotiation falseallow legacy hello messages trueis initial handshake trueis secure renegotiation falsesupported cipher suites tls ecdhe ecdsa with aes 256 cbc sha384 tls ecdhe rsa with aes 256 cbc sha384 tls rsa with aes 256 cbc sha256 tls ecdh ecdsa with aes 256 cbc sha384 tls ecdh rsa with aes 256 cbc sha384 tls dhe rsa with aes 256 cbc sha256 tls dhe dss with aes 256 cbc sha256 tls ecdhe ecdsa with aes 256 cbc sha tls ecdhe rsa with aes 256 cbc sha tls rsa with aes 256 cbc sha tls ecdh ecdsa with aes 256 cbc sha tls ecdh rsa with aes 256 cbc sha tls dhe rsa with aes 256 cbc sha tls dhe dss with aes 256 cbc sha tls ecdhe ecdsa with aes 128 cbc sha256 tls ecdhe rsa with aes 128 cbc sha256 tls rsa with aes 128 cbc sha256 tls ecdh ecdsa with aes 128 cbc sha256 tls ecdh rsa with aes 128 cbc sha256 tls dhe rsa with aes 128 cbc sha256 tls dhe dss with aes 128 cbc sha256 tls ecdhe ecdsa with aes 128 cbc sha tls ecdhe rsa with aes 128 cbc sha tls rsa with aes 128 cbc sha tls ecdh ecdsa with aes 128 cbc sha tls ecdh rsa with aes 128 cbc sha tls dhe rsa with aes 128 cbc sha tls dhe dss with aes 128 cbc sha tls ecdhe ecdsa with rc4 128 sha tls ecdhe rsa with rc4 128 sha ssl rsa with rc4 128 sha tls ecdh ecdsa with rc4 128 sha tls ecdh rsa with rc4 128 sha tls ecdhe ecdsa with 3des ede cbc sha tls ecdhe rsa with 3des ede cbc sha ssl rsa with 3des ede cbc sha tls ecdh ecdsa with 3des ede cbc sha tls ecdh rsa with 3des ede cbc sha ssl dhe rsa with 3des ede cbc sha ssl dhe dss with 3des ede cbc sha ssl rsa with rc4 128 md5 tls empty renegotiation info scsv tls dh anon with aes 256 cbc sha256 tls ecdh anon with aes 256 cbc sha tls dh anon with aes 256 cbc sha tls dh anon with aes 128 cbc sha256 tls ecdh anon with aes 128 cbc sha tls dh anon with aes 128 cbc sha tls ecdh anon with rc4 128 sha ssl dh anon with rc4 128 md5 tls ecdh anon with 3des ede cbc sha ssl dh anon with 3des ede cbc sha tls rsa with null sha256 tls ecdhe ecdsa with null sha tls ecdhe rsa with null sha ssl rsa with null sha tls ecdh ecdsa with null sha tls ecdh rsa with null sha tls ecdh anon with null sha ssl rsa with null md5 ssl rsa with des cbc sha ssl dhe rsa with des cbc sha ssl dhe dss with des cbc sha ssl dh anon with des cbc sha ssl rsa export with rc4 40 md5 ssl dh anon export with rc4 40 md5 ssl rsa export with des40 cbc sha ssl dhe rsa export with des40 cbc sha ssl dhe dss export with des40 cbc sha ssl dh anon export with des40 cbc sha tls krb5 with rc4 128 sha tls krb5 with rc4 128 md5 tls krb5 with 3des ede cbc sha tls krb5 with 3des ede cbc md5 tls krb5 with des cbc sha tls krb5 with des cbc md5 tls krb5 export with rc4 40 sha tls krb5 export with rc4 40 md5 tls krb5 export with des cbc 40 sha tls krb5 export with des cbc 40 md5enabled cipher suites tls ecdhe ecdsa with aes 256 cbc sha tls ecdhe rsa with aes 256 cbc sha tls rsa with aes 256 cbc sha tls ecdh ecdsa with aes 256 cbc sha tls ecdh rsa with aes 256 cbc sha tls dhe rsa with aes 256 cbc sha tls dhe dss with aes 256 cbc sha tls ecdhe ecdsa with aes 128 cbc sha tls ecdhe rsa with aes 128 cbc sha tls rsa with aes 128 cbc sha tls ecdh ecdsa with aes 128 cbc sha tls ecdh rsa with aes 128 cbc sha tls dhe rsa with aes 128 cbc sha tls dhe dss with aes 128 cbc sha tls ecdhe ecdsa with rc4 128 sha tls ecdhe rsa with rc4 128 sha ssl rsa with rc4 128 sha tls ecdh ecdsa with rc4 128 sha tls ecdh rsa with rc4 128 sha tls ecdhe ecdsa with 3des ede cbc sha tls ecdhe rsa with 3des ede cbc sha ssl rsa with 3des ede cbc sha tls ecdh ecdsa with 3des ede cbc sha tls ecdh rsa with 3des ede cbc sha ssl dhe rsa with 3des ede cbc sha ssl dhe dss with 3des ede cbc sha ssl rsa with rc4 128 md5 tls empty renegotiation info scsvi am finding strange that the debugging logs report that some ciphers are unsupported but they are still reported in the supported list returned by getsupportedcipherssuitesis there something wrong on my platform,['java'] +579215,android layout width half of parent i have a very simple layout that i cannot make it looks like i want it is a linearlayout with a button and a switch i want them to show one above the other but i want their width to be the half of the parent layoutlinearlayout switch button i have been looking at other similar answer in so but i could not find a solution that works for me this is what i have tried so far linearlayout androidlayout widthmatch parent androidlayout heightwrap content androidorientationvertical androidweightsum2 switch androidididremember me switch androidlayout widthmatch parent androidlayout heightwrap content androidlayout weight1 androidhintstringremember button androidididshare button androidlayout widthmatch parent androidlayout heightmatch parent androidlayout weight1 androidonclickloginonclick androidtextstringlogin button text linearlayoutwith this the button and the switch take all the space of the parent instead of take only the halfi have tried with androidlayout width 0dp in the children but it makes they thisappearany help please,['android'] +579279,rails moving out calculations from my views currently i am performing some calculations in my views which is a bad thing of course categorieseach do c ctransactionssumamount cents end i am researching ways that will help me to refactor the above issueone thing is to move the calculation to my controllercategory sum transactionsumamount centswhich is probably a better solution but you know not perfectsince i have many users i do not see how can i move the calculator logic into my model so i guess i might need to use a new class create a bunch of methods sum average etc and use them in the views am i on the right track will be thankful for any advice on how to restructure my code and design and implement this class,['ruby-on-rails'] +579300,print different precision by column with pandasdataframeto csv questionis it possible to specify a float precision specifically for each column to be printed by the python pandas package method pandasdataframeto csvbackgroundif i have a pandas dataframe that is arranged like thisin 53 df data5out53 year month day lats lons vals0 2012 6 16 81862745 29834254 001 2012 6 16 81862745 29502762 012 2012 6 16 81862745 29171271 003 2012 6 16 81862745 28839779 024 2012 6 16 81862745 28508287 00there is the float format option that can be used to specify a precision but this applys that precision to all columns of the dataframe when printedwhen i use that like sodf datato csvoutfile indexfalse headerfalse float format116fi get the following where vals is given an inaccurate precision2012616 81862745 29834254 02012616 81862745 29502762 0102012616 81862745 29171270 02012616 81862745 28839779 0202012616 81862745 28508287 0,['python'] +579335,invalid parameter exception thrown by uiqueuingscrollview my app that contains a uitableviewcontroller embedded in uipageviewcontroller raises this exception from time to timeinvalid parameter not satisfying views count 3backtrace thread 1 tid 0x6239fa 0x03d1d88a libobjcadylibobjc exception throw queue comapplemainthread stop reason breakpoint 253 frame 0 0x03d1d88a libobjcadylibobjc exception throw frame 1 0x0404f448 corefoundationnsexception raiseformatarguments 136 frame 2 0x03428fee foundationnsassertionhandler handlefailureinmethodobjectfilelinenumberdescription 116 frame 3 0x01e7c535 uikit uiqueuingscrollview replaceviewsupdatingcontentsadjustcontentinsetsanimated 185 frame 4 0x01e800ca uikit uiqueuingscrollview didscrollwithanimationforce 1231 frame 5 0x01e7bb57 uikit uiqueuingscrollview scrollviewanimationendedfinished 104 frame 6 0x0190583c uikituiscrollviewuiscrollviewinternal animatorstopanimationfraction 62 frame 7 0x0197096e uikituianimator stopanimation 533 frame 8 0x0197100a uikituianimatorstatic advanceanimationsoftypewithtimestamp 325 frame 9 0x01970b76 uikituianimatorstatic lcdheartbeatcallback 67 frame 10 0x01663b8a quartzcorecathisplaythisplaylinkitemthispatch 48 frame 11 0x01663a46 quartzcorecathisplaythisplaylinkthispatch itemsunsigned long long unsigned long long unsigned long long 310 frame 12 0x01663f6b quartzcorecathisplaytimerthisplaylinkcallback cfrunlooptimer void 123 frame 13 0x0400dbd6 corefoundation cfrunloop is calling out to a timer callback function 22 frame 14 0x0400d5bd corefoundation cfrunloopdotimer 1181 frame 15 0x03ff5628 corefoundation cfrunlooprun 1816 frame 16 0x03ff4ac3 corefoundationcfrunlooprunspecific 467 frame 17 0x03ff48db corefoundationcfrunloopruninmode 123 frame 18 0x0533b9e2 graphicsservicesgseventrunmodal 192 frame 19 0x0533b809 graphicsservicesgseventrun 104 frame 20 0x01874d3b uikituiapplicationmain 1225does anyone have seen this already or have an idea what the reason could be,['ios'] +579345,nodejs hmac sha256 base64 of string i am making an app in java and a server with node and as an authentication method i would like to compare two strings in java i am doing this try string secret secret string message message mac sha256 hmac macgetinstancehmacsha256 secretkeyspec secret key new secretkeyspecsecretgetbytes hmacsha256 sha256 hmacinitsecret key string hash base64encodebase64stringsha256 hmacdofinalmessagegetbytes systemoutprintlnhash catch exception e systemoutprintlnerrorbut i am still pretty new to nodejs and i am trying to figure out how to do the same there this is what i have gotvar crypto requirecryptovar sha256 cryptocreatehashhmacsha256updatemessagedigestbase64how can i make them do the same i am still missing the salt in nodejs suggestionseditthe answer below helped me find the solution if other android users has this problem then this code worked for metry string secret secret string message message mac sha256 hmac macgetinstancehmacsha256 secretkeyspec secret key new secretkeyspecsecretgetbytes hmacsha256 sha256 hmacinitsecret key byte s53 sha256 hmacdofinalmessagegetbytes string hash base64encodetostrings53 base64default logebeadict hash catch exception e systemoutprintlnerrorand this in node var crypto requirecryptovar hash cryptocreatehmacsha256 secretupdatemessagedigestbase64,"['java', 'android']" +579388,install a package and write to requirementstxt with pip i am searching for a way to install a package with pip and write that packages version information to my projects requirementstxt file for those familiar with npm it is essentially what npm install save does using pip freeze requirementstxt works great but i have found that i forget to run this or i can accidentally include unused packages that i would installed for testing but decided not to useso the following psuedocode pip install nose2 savewould result in a requirementstxt file withnose2047i guess i could munge the output of save to grab the version numbers but i am hoping there is an easier way,['python'] +579434,why is an arrays length immutable why is an arrays length immutable at least in java i know next to nothing about the inner workings of a programming language so to me it seems easy to make an arrays length changeable i assume that there is a good reason for array lengths being immutable probably related to performance does anybody know this reasonsorry if this question has been asked before if it has i did not find it in about 10 minutes of searchingedit i know that when an array is is initialized a certain amount of memory is allocated why cannot more memory be allocated,['java'] +579435,bootstrap 3 carousel multiple frames at once this is the effect i am trying to achieve with bootstrap 3 carouselinstead of just showing one frame at a time it thisplays and frames slide by side then when you slide or when it auto slides it shifts the group of slides like it doescan this be done with bootstrap 3s carousel i am hoping i would not have to go hunting for yet another jquery plugin,['jquery'] +579517,how to change the colour of a row in bootstrap 3 i want to change the background colour of alternating rows in a bootstrap 3 grid i thought that i could create some css and add it to the class in the div but the colour does not change heres my cssrowbuffer margintop20pxmarginbottom20pxroweven backgroundcolor76a0d3rowodd backgroundcolorbde3fband my row is being defined like sodiv classrow rowbuffer rowevenordiv classrow rowbuffer rowoddthe rowbuffer is working perfectly but the roweven and rowodd do not seem to be making any difference my rows are being defined within a containeram i barking up the wrong tree,"['html', 'css']" +579545,why creating the elements with custom tags adds the xml namespace in the outerhtml in ie9 or 10 until the find method is called i have a jsfiddle that demonstrates the questiondocumentreadyfunction this seems fine in ie9 and 10 var div div consolelogin ie this div is just fine div0outerhtml this is weird in ie var test test consoleloghowever this test has an xml tag prepended n test0outerhtml testfindtest consolelognow it does not n test0outerhtml consolelogwhy does this behave this waywhy does this happen it does not happen in chrome or firefox is there a better way to fix this than to call findtest on the objecteditto clarify i am not asking why the xml tag is added rather i am wondering why the find call gets rid of it it does not make sense to me,"['javascript', 'jquery']" +579572,best practices for integrating aspnet identity do they exist i am using aspnet identity with a new website and there do not seem to be many any examples of how to do this in a decoupled manner i do not want my domain models domainuser class to have to inherit from microsoftaspnetidentityentityframeworkuser so i have created a class that looks like thispublic class identityuser user public virtual domainuser domainuser get private set i have moved the dbsets required by aspnet identity into the same derived dbcontext class as my domain models as illustrated in this answer i have linked the identityuser unidirectionally to the domainuser via fluent api like somodelbuilderentityidentityuserhasrequirediu iudomainuserwithrequiredprincipalthis allows me to mostly separate the concerns of authorization and authentication from the behaviors defined in the domainuser class this is better than combining them into one class but it still feels ugly i still have references to the required aspnet identity assemblies in my domain project i could create yet another project that held only my identityuser class and a reference to my domain assembly to allow for the navigation property but that starts to feel convoluted i feel like there should be a better cleaner more modular way to link identity up to the domain without it resulting in tight coupling has anyone come up with a better way of handling this i am hoping to garner the attention of those involved in the aspnet identity project hao kung et al to provide direction here,"['asp.net', '.net']" +579588,using css to transition the fill property of an svg path on hover i am including an svg image file on my page within an object tag like thisobject typeimagesvgxml datalinktoimagesvg fallback image in css objectthe image in question is of a world map i want to transition the fill property when the mouse hovers over a group in this case i have grouped my svg by continent so south america looks something like thisg idsouth america path fillfafafa dedited for brevitygi can get the fill property to change on hover by using the following css at the top of my svg documentstylesouth america path transition fill 4s easesouth americahover path fillwhitestylebut i cannot get the fill colour to fade in with a css transition the colour just changes instantly can anyone shed light on this please,['css'] +579600,how to get context in getview of adapter for listview i have three questionsi am using getapplicationcontext unlike all the examples i have seen which just say context how do i get the context here or is the application context fineis there any performance penalty for me overriding the getview instead of letting it handle it by itself i am only doing it to set a custom fontis there anything i should be aware of while using this approach as i am just copy and pasting without understanding what it will do if i have 250 items in my list any potential leaks i can causemy codeprivate typeface arabicfontarabicfont typefacecreatefromassetgetassets arabicfontf arabicadapter new simplecursoradapterthis rlayoutbook list item arabic cursor new string numberarabic arabic new int ridtxtnumber ridtxtbookname cursoradapterno selection override public view getviewint position view convertview viewgroup parent ifconvertview null layoutinflater inflater layoutinflater getapplicationcontextgetsystemservicecontextlayout inflater service convertview inflaterinflaterlayoutbook list item arabic parent false textview txtbookname textviewconvertviewfindviewbyidridtxtbookname txtbooknamesettypefacearabicfont txtbooknamesettextu1 u return convertview,['android'] +579647,different results using the same maths in different browsers edit since chrome has updated the browser this question is some what redundant as they have fixed an internal bug which means this problem no longer occursi have an animation of a circle anchored to the center of the canvasthe larger the circle becomes the less stable the motion is but not only that for me at least it is significantly worse in chrome to firefoxthe math is done in this functionfunction updatedeltatime var centerx canvaswidth2 var centery canvasheight2 icurrentangle icurrentangle 0 deltatime10 irotationspeed ificurrentangle2mathpi icurrentangle2mathpi ix centerx iradiusifactor mathcosicurrentangle iy centery iradiusifactor mathsinicurrentangle this is the code in working examplechrome outputsfirefox outputsfirefox seems to be closest to what i am aiming for yet chrome is just wacky why do i get such different results i should mention i have asked a few people what they see and everyone is seeing different amounts of inaccuracy,['javascript'] +579682,customize android intentaction send i am using intent for sharing url and subject in this intent filter showing all the sharing apps i want only facebookgmailmessageskypetwitter these option in popup is this possible to customize sharing intent filter intent sharingintent new intentandroidcontentintentaction send sharingintentsettypetextplain string sharebody adaptergetdetailsurl sharingintentputextraandroidcontentintentextra subjectsubject sharingintentputextraandroidcontentintentextra text sharebody startactivityintentcreatechoosersharingintent share viathanks,['android'] +579688,read file data without saving it in flask i am writing my first flask application i am dealing with file uploads and basically what i want is to read the datacontent of the uploaded file without saving it and then print it on the resulting page yes i am assuming that the user uploads a text file alwayshere is the simple upload function i am usingapprouteupload methodsget postdef upload if requestmethod post file requestfilesfile if file filename secure filenamefilefilename filesaveospathjoinappconfigupload folder filename a file uploadedreturn render templateuploadhtml data aright now i am saving the file but what i need is that a variable to contain the contentdata of the file any ideas,['python'] +579700,can we call startactivityforresult from adapterhow to get the response is it possible to have method startactiivtyforresult within an adapterthen how to get the response where to execute the call back function,['android'] +579705,dictionary set or frozenset i have a large collection of data about 10 million entries and part of my program required very many membership checksif a in data return truereturn falseright now i have data as dictionary entries with all their values equal to 1i also have a program that uses an algorithm to figure out the same information but for now it is slower then the dictionary method however i expect the size of data to continue growing for my current dictionary solution would typedata as a frozenset or set or something else be fasterand for the future to find out when i need to switch to my program does anyone know how the speed of checking membership correlated with increasing the size of a type that is hashableis a dictionary with 1 billion entries still fast,['python'] +579718,negative infinity i am trying to figure out how to assign the value of negative infinity to a float or double variable it seems that including the standard library limits i can get the infinity representation and i know quite surely that adding a minus in front of that infinity might result in the value i am looking for in the ie754 floating point standard as 0x7f might result on 0xf but i am not even sure about that not to mention other standards that might be out there if there are any i find it really really unprofessional and implementation dependantis there a good way to get the value of negative infinity platform and implementation independently of course otherwise i might just as well use a define everybody likes preprocessing,['c++'] +579747,how to combine navigation drawer and spinner like in google app i need your advice in google app for android there are two elements that i do not know how to put together one is navigation drawer and second is action bar navigation spinner do you know how these two elements put together thank you very much for your adviceps i know i am lame and i apologize for my english,['android'] +579779,minvalue maxvalue attribute for properties is it possible to make attribute which can limit minimum or maximum value of numbersexampleminvalue1 maxvalue50public int size get set and when i do size 3 value of size must be 1i searched in google and cannot find single example about this behavior maybe because it is not possible to makei am gonna use these attributes in property grid therefore having automatic validation can be handycurrently i workaround like this to limit minimum value private int size defaultvalue8 public int size get return size set size mathmaxvalue 1 so this acts like minvalue1,['c#'] +579906,when to use hpp files i have created a library using c i want to create a python wrapper for this library and i am using boostpython the problem is that i have created h and cpp files separately and for some reason the so file cannot link these cpp files i have therefore decided to just use the hpp extension and include the implementation as a header file is this good or bad practice in terms of c i am hoping to upload my project to github so want to maximize the most optimal solution ps i think this question would more belong on programmersstackexchangecom so if it is could someone please migrate it,['c++'] +579938,is there byte data type in c if exists is there header file to includethis code give compilation errorinclude iostreamusing namespace stdint main byte b 2 cout b endl return 0,['c++'] +579948,convert all types of smart quotes with php i am trying to convert all types of smart quotes to regular quotes when working with text however the following function i have compiled still seems to be lacking support and proper designdoes anyone know how to properly get all quote characters convertedfunction convert smart quotesstring quotes array xc2xab a u00ab in utf8 xc2xbb a u00bb in utf8 xe2x80x98 a u2018 in utf8 xe2x80x99 a u2019 in utf8 xe2x80x9a a u201a in utf8 xe2x80x9b a u201b in utf8 xe2x80x9c a u201c in utf8 xe2x80x9d a u201d in utf8 xe2x80x9e a u201e in utf8 xe2x80x9f a u201f in utf8 xe2x80xb9 a1 u2039 in utf8 xe2x80xba ao u203a in utf8 string strtrstring quotes version 2 search array chr145 chr146 chr147 chr148 chr151 replace array string str replacesearch replace string version 3 string str replace array8216821782208221 array string version 4 search array lsquo rsquo ldquo rdquo mdash ndash replace array string str replacesearch replace string return stringnote this question is a complete query about the full of gamut of quotes including the microsoft quotes asked here this is a duplicate in the same way that asking about all tire sizes is a duplicate of asking for a car tire size,"['php', 'html']" +579956,inconsistent comprehension syntax i just stumbled over what seems to be a flaw in the python syntax or else i am missing somethingsee thisx for x in range30 if x 2 0but this is a syntax errorx for x in range30 if x 2 0 else 5if you have an else clause you have to writex if x 2 0 else 5 for x in range 30but this is a syntax errorx if x 2 0 for x in range30what am i missing why is this so inconsistent,['python'] +580019,c11 exception design idioms and best practices changed i am wondering if since c11 where passing exceptions between threads was added and nested exceptions were added idioms changed for exception capturing in generalnow we havestdrethrow if nestedstdrethrow with nestedstdrethrow exceptionstdcurrent exceptionnested exceptions are supposed to be used not to loose context for exceptionsso now you can do something like thisvoid open filestdstring const file name try stdifstream file fileexceptionsiosfailbit iosbadbit fileopenfile name catch stdrethrow with nestedstdlogic errorfile file name could not be open you can get the backtrace like this if i am not wrongvoid print backtracestdexception const e int depth 0 stdcerr stdstringdepth ewhat stdendl try stdrethrow if nestede catch stdexception const ex print backtraceex depth so if you use print backtrace with open file it should give you the stdlogic error the ios basefailure in the outputmy questions areis this idiom the correct way of handling exceptions in c11 given that i want to capture all exceptions without losing contextis there a way in the print backtrace function to capture exceptions with catch to capture absolutely alli do not know why stdrethrow exception is needed and i do not know when either,['c++'] +580076,which conditions cause sqlitethiskioexception code 3850 i have an app that uses contentprovider to access sqlite an instance of sqliteopenhelper is created in providers oncreateoverridepublic boolean oncreate final context context getcontext mdbhelper new mydatabasecontext return true sqlitedatabase instances retrieved in methods insertupdatedeletequery are not manually closed none of these methods are marked synchronized contentprovider is accessed from multiple threads started from ui and servicessample stacktraceandroiddatabasesqlitesqlitethiskioexception thisk io error code 3850at androiddatabasesqlitesqliteconnectionnativeexecuteforchangedrowcountnative methodat androiddatabasesqlitesqliteconnectionexecuteforchangedrowcountsqliteconnectionjava734at androiddatabasesqlitesqlitesessionexecuteforchangedrowcountsqlitesessionjava754at androiddatabasesqlitesqlitestatementexecuteupdatedeletesqlitestatementjava64at androiddatabasesqlitesqlitedatabaseupdatewithonconflictsqlitedatabasejava1574at androiddatabasesqlitesqlitedatabaseupdatesqlitedatabasejava1520at comsampleprovidermyproviderupdatesourcefile0at androidcontentcontentprovidertransportupdatecontentproviderjava260at androidcontentcontentresolverupdatecontentresolverjava1040things worked fine up to the moment when i added a class that serializes writes to certain tables using a handler initialized by looper from handlerthread after this i started seeing plenty of sqlitethiskioexceptions with error codes 3850 and 0 not an error interestingly 90 of these crashes occur with nexus 4 and on a handful of other devices i have been running unit tests trying to simulate the condition but have been unable to reproduce the problem there are other questions that already thiscuss related issues eg here syncronize access to content provider but to me the original cause for this error seems still a bit unclear so what really are the reasons for error 3850,['android'] +580099,how to add custom buttons to uiactivityviewcontroller i am using uiactivity in ios7 it is working fine with a few lines of code now i want to add instagram share button to it is there a way to add custom buttons to the action sheetthis is how i am creating the uiactivityviewcontrollernsstring texttoshare selfnavigationitemtitle nsarray itemstoshare texttoshare imagesarray objectatindexafimgviewercurrentimageuiactivityviewcontroller activityvc uiactivityviewcontroller alloc initwithactivityitemsitemstoshare applicationactivitiesnilactivityvcexcludedactivitytypes uiactivitytypeprint uiactivitytypecopytopasteboard uiactivitytypeassigntocontact or whichever you do not needself presentviewcontrolleractivityvc animatedyes completionnil,['ios'] +580119,java default stack size i understand that each thread has its own stack and primitive types and references live on stack no object can live on stack now my doubts are how much a stack can grow like we have xms and xmx for heapcan we limit this growth does stack has some default minimum value or default maximum valueand how does garbage collection work on stack,['java'] +580175,authentication failed during call webmethod from jqueryajx with aspnetfriendlyurls and aspnetidentity if i call webmethod from jqueryajax with installed nuget packages microsoftaspnetfriendlyurls v 102 and microsoftaspnetidentity v100 then i get the data object but without datad but with property message authentication failedmy webmethodaspx isdoctype htmlhtml xmlnshead runatservermeta httpequivcontenttype contenttexthtml charsetutf8 titlewebmethodtitle script srcscriptsjquery203jsscriptheadbody form idform1 runatserver h3test webmethodh3 div idgreeitngdiv div idinnererror styleborder1px dotted redthisplaynone titleerrormessagediv script typetextjavascript function asyncservercallusername jqueryajax url webmethodaspxhelloworld type post data username username async false contenttype applicationjson charsetutf8 datatype json success function data if datad undefined documentgetelementbyidgreeitnginnerhtml datamessage else documentgetelementbyidgreeitnginnerhtml datad error function err if eresponsetext innererrorhtmleresponsetextshow else alerterr documentreadyfunction innererrorhide asyncservercallsuperuser script formbodyhtmlmy webmethod in webmethodaspxcs issystemwebserviceswebmethodpublic static string helloworldstring username return stringformathello 0 usernamein globalasaxcs is routing activated void application startobject sender eventargs e routeconfigregisterroutesroutetableroutesin app start have regitred the routespublic static class routeconfig public static void registerroutesroutecollection routes var settings new friendlyurlsettings settingsautoredirectmode redirectmodepermanent routesenablefriendlyurlssettings,['jquery'] +580183,detect if a string contains uppercase characters is there an alternative to using a regular expression to detect if a string contains uppercase characters currently i am using the following regular expressionregexismatchfulluri az it works fine but i often hear the old adage if youre using regular expressions you now have two problems,['c#'] +580221,viewcontrollers not resizing for 35 inch screen i am really struggling with this one i searched this issue all over but no one seems to experience exactly the same problemso i have this ios7 project which should run on both 4 and 35 inch devices on 4 inch everything is fine but on 35 inch view controllers have frames height of 568if i log the uiscreen bounds in appdelegate it returns correctly 480 but if i create uiviewcontroller and add it as rootviewcontroller to navigationcontroller its height is 568navigationcontroller has too a proper height of 480first i thought it may be because of xib so i created blank uiviewcontroller just byuiviewcontroller alloc init but it still has height of 568this is driving me crazy because my other project works fine this way and viewcontrollers are resized automaticallyi checked i have a proper starting images defined in imagesxcassets and i tried xib both with and without autolayout only one thing helped if i turn simulated metrics in xib to none or 35 inch but then i dont get fullcreen on 4 inch and having multiple xib for both screens is not solution for meany hint would be greatly appreciatedthanks,"['ios', 'objective-c']" +580292,large object heap compaction when is it good first off how big is considered large is there anyway to determine how large an object is in heapnet 451 comes with this largeobjectheapcompactionmodeafter the largeobjectheapcompactionmode property is set to gclargeobjectheapcompactionmodecompactonce the next full blocking garbage collection and compaction of the loh occurs at an indeterminate future time you can compact the loh immediately by using code like the followinggcsettingslargeobjectheapcompactionmode gclargeobjectheapcompactionmodecompactoncefrom what i have heard it is a bad thing to compact loh so which one is worst compact loh or having loh fragmentation,"['c#', '.net']" +580322,what is the purpose of flasks context stacks i have been using the requestapplication context for some time without fully understanding how it works or why it was designed the way it was what is the purpose of the stack when it comes to the request or application context are these two separate stacks or are they both part of one stack is the request context pushed onto a stack or is it a stack itself am i able to pushpop multiple contexts on top of eachother if so why would i want to do thatsorry for all the questions but i am still confused after reading the documentation for request context and application context,['python'] +580347,pandas reading multiple json records into dataframe i would like to know if there is a memory efficient way of reading multi record json file each line is a json dict into a pandas dataframe below is a 2 line example with working solution i need it for potentially very large number of records example use would be to process output from hadoop pig jsonstorage functionimport jsonimport pandas as pdtesta1b2a3b4dfpdread jsontestorientrecords does not work expects l jsonloadsl for l in testsplitlinesdfpddataframel,['python'] +580386,onactivityresult for fragment i currently have a base activity which is hosting a single fragment inside the fragment i have a method which starts the contact chooserprivate void choosecontacts intent pickcontactintent new intentintentaction pick contactscontractcontactscontent uri pickcontactintentsettypecontactscontractcommondatakindsphonecontent type startactivityforresultpickcontactintent pick contact requestwhen this activity returns how should i capture the results i have tried adding a overridepublic void onactivityresultint requestcode int resultcode intent data superonactivityresultrequestcode resultcode data handle codeto both my base activity and the fragment but neither method are being triggered if possible i would like to have the fragment handle the return so as not to muddy up the activityplease let me know what the best practice is in this situationupdateif i changestartactivityforresultpickcontactintent pick contact requesttogetactivitystartactivityforresultpickcontactintent pick contact requestthen it works but other posts have made me think that is incorrect,"['java', 'android']" +580422,java replace line in text file how do i replace a line of text found within a text filei have a string such asdo the thishes0and i want to update it withdo the thishes1and vise versahow do i accomplish thisactionlistener al new actionlistener override public void actionperformedactionevent e jcheckbox checkbox jcheckbox egetsource if checkboxisselected systemoutprintlnselected string s checkboxgettext replaceselecteds 1 else systemoutprintlndeselected string s checkboxgettext replaceselecteds 0 public static void replaceselectedstring replacewith string type by the way i want to replace only the line that was read not the entire file,['java'] +580440,how to install latest version of django 15 using pip i want to install django15x so i triedpip install djangobut django16 gets installedi tried again bypip install django15but i got errorcould not find any downloads that satisfy the requirement django15no thistributions at all found for django15storing complete log in homesuhailpippiplog,['python'] +580456,warning incompatible implicit declaration of builtin function aprintfa enabled by default i am using the following c codeinclude unistdhinclude fcntlhinclude systypeshint main int file0 iffileopentestfiletxto rdonly 1 return 1 char buffer19 ifreadfilebuffer19 19 return 1 printfsnbuffer iflseekfile10seek set 0 return 1 ifreadfilebuffer19 19 return 1 printfsnbuffer return 0after compiling it produces a warningwarning incompatible implicit declaration of builtin function aprintfa enabled by defaultwhat does it mean and how do i appease the c compiler to not raise the warning,['c'] +580506,edittext line spacing increase issue and cursor position wrt line i am trying to create an edittext such that the space between each line should be like 20 dp please see the image belowif i use line spacing extra then the cursor position is not correctly aligned with the line i have achieved the line spacing but the cursor is not aligned with the line see the red box highlighted in the image belowpackage comexampledev task 197 keyboard accesoryimport androidcontentcontextimport androidgraphicscanvasimport androidgraphicscolorimport androidgraphicspaintimport androidgraphicsrectimport androidutilattributesetimport androidwidgetedittextpublic class lineedittext extends edittext private rect mrect private paint mpaint we need this constructor for layoutinflater public lineedittextcontext context attributeset attrs supercontext attrs mrect new rect mpaint new paint mpaintsetstylepaintstylefill and stroke mpaintsetcolorcolorblue set your own color here setminlines15 override protected void ondrawcanvas canvas int height getheight int line height getlineheight int count height line height ifgetlinecount count count getlinecount rect r mrect paint paint mpaint int baseline getlinebounds0 r for int i 0 i count i canvasdrawlinerleft baseline 1 rright baseline 1 paint baseline getlineheightnext line finishes up by calling the parent method superondrawcanvas for line spacing add linespaceextra and linespacemultiplier parameter in the xmlplease suggest,['android'] +580518,removing empty space if the section header is hidden in the uicollectionview i have two sections in uicollectionview i want to show a section header in uicollectionview for only 1st section not in 0th sectionso i tried to return nil in viewforsupplementaryelementofkind method for section 0 and returns view for the section 1it crashes and shows below errorassertion failure in uicollectionview createpreparedsupplementaryviewforelementofkindatindexpathwithlayoutattributesapplyattributeshere it is my code for the supplementary view uicollectionreusableview collectionviewuicollectionview collectionview viewforsupplementaryelementofkindnsstring kind atindexpathnsindexpath indexpath uicollectionreusableview sectionheader nil if kind uicollectionelementkindsectionheader indexpathsection 1 sectionheader collectionview dequeuereusablesupplementaryviewofkindkind withreuseidentifiereventsectionheader forindexpathindexpath sectionheaderlayerborderwidth 5f sectionheaderlayerbordercolor uicolor colorwithred2210 2550 green2230 2550 blue2200 2550 alpha10cgcolor return sectionheaderi have found that returning nil in viewforsupplementaryelementofkind method crashing for others too other answers suggesting to remove that method but i want to show section header for specific sections only how to achieve that returning view for only one section thanks any help would be appreciatededitas san said i have updated code to hide the section header it works it hides the header but i am still seeing the empty space in the place of section header expected results is there should be no space for section header if it is hiddenupdated code uicollectionreusableview collectionviewuicollectionview collectionview viewforsupplementaryelementofkindnsstring kind atindexpathnsindexpath indexpath uicollectionreusableview sectionheader nil if kind uicollectionelementkindsectionheader sectionheader collectionview dequeuereusablesupplementaryviewofkindkind withreuseidentifiereventsectionheader forindexpathindexpath sectionheaderlayerborderwidth 5f sectionheaderlayerbordercolor uicolor colorwithred2210 2550 green2230 2550 blue2200 2550 alpha10cgcolor if indexpathsection 0 sectionheaderhidden yes else sectionheaderhidden no return sectionheaderi even tried setting the frame for sectionheader as san said but no luck same result,"['ios', 'iphone']" +580522,is it possible to step through a browsers applying of css rules for web development is there a way or tool that could let me step through the painting of css rules one by one similar as one would do in an ide with program code but with css but i wouldnt preferably want to do it by taking the browsers source code and stepping through its underlying functions i just mean stepping throug updates by css rules in a form similar to a web developer toolbari expect this is usually more tedious than useful but in some cases it would really help in web development like debugging cats and owls or finding out how a particular effect is achievededit to clarify by stepping through i mean sg like potentially stopping the browser from painting another rule after each end every rule i choose before the next one is applied each before the final paint of the page is finished for inspection of what happensedit 2 after boltclocks comment i replaced the word render with paint to be more clear removed original to be uncluttered,['css'] +580550,what is the equivalent of androids spannable in objectivec im on an ios app that should able to highlight text and make it clickable tooi read about nsattributedstring in ios but it still more complicated than spannable in androidis there any other objective c way to do that if not what should i do using nsattributedstring to highlight a paragraph word by word and how to make my text clickableupdatewhat exactly i want that each word should be clickable and can be highlighted as a single word in one paragraph,"['ios', 'objective-c']" +580564,convert character to its alphabet integer position i am trying to find if there is a quick way to get the integer position of a character in the alphabet ci can simply create an array and get the position but seems there must be a nice and funky way of acheiving thisi have also looked at taking the ascii position of the uppercase character in relation to 65but again seems more work than it should beenglish 26 letter alphabet only no internationalisation required and no this is not homework,['c#'] +580578,how to set an iframe src attribute from a variable in angularjs i am trying to set the src attribute of an iframe from a variable and i cannot get it to workthe markupdiv classcolxs12 ngcontrollerappctrl ul class li ngrepeatproject in projects a ngclicksetprojectprojectid hrefprojecturla li ul iframe ngsrctrustsrccurrentprojecturl something wrong iframedivcontrollersappjsfunction appctrl scope scopeprojects 1 id 1 name mela sarkar url description a professional portfolio site for mcgill university professor mela sarkar 2 id 2 name good watching url description weekend experiment to help my mom decide what to watch scopesetproject function id scopecurrentproject scopeprojectsid consolelog scopecurrentproject with this code nothing gets inserted into the iframes src attribute it is just blankupdate 1i injected the sce dependancy into the appctrl and scetrusturl now works without throwing errors however it returns trustedvalueholdertype which i am not sure how to use to insert an actual url the same type is returned whether i use scetrusturl inside the interpolation braces in the attribute srctrusturlcurrentprojecturl or if i do it inside the controller when setting the value of currentprojecturl i even tried it with bothupdate 2i figured out how to return the url from the trustedurlholder using tostring but when i do that it throws the security warning when i try to pass it into the src attributeupdate 3it works if i use trustasresourceurl in the controller and pass that to a variable used inside the ngsrc attributescopesetproject function id scopecurrentproject scopeprojectsid scopecurrentprojecturl scetrustasresourceurlscopecurrentprojecturl consolelog scopecurrentproject consolelog scopecurrentprojecturl my problem seems to be solved by this although i am not quite sure why,"['javascript', 'html']" +580582,admob ios7 error audio framework i am integrating admob sdk the current in my last application ios7xcode5 and i have a new error same on new project i guess i missed something but i restarted the process many times and the error is still here undefined symbols for architecture armv7 objc class avaudiosession referenced from objcclassref in libgoogleadmobadsagaddeviceo avaudiosessionportheadphones referenced from gaddevice audiorouteusingavaudiosession in libgoogleadmobadsagaddeviceo avaudiosessionportbuiltinspeaker referenced from gaddevice audiorouteusingavaudiosession in libgoogleadmobadsagaddeviceoi found how to resolve these errors in adding audiounitframework but a new error appears framework not found audiounit as my best friend google tell me via stackoverflow do not use audiounitframework it is empty now use coreaudioframework but my first error came backif someone has the same problem and mainly a solution i will be grateful ps i tried all load and objc i linked audiotoolbox i usually work with frameworks but also with careless mistakes,"['ios', 'iphone']" +580585,how to fetch primary key in gridview but do not thisplay it using aspgridviewaspgridview i am trying to thisplay columns of database table i want to fetch primary key of table but obviously do not want to thisplay it how can i achieve thisthis is my gridview aspgridview idmygrid runatserver bordercolor0066ff allowpagingfalse pagesize5 allowsortingtrue autogeneratecolumnsfalse autogenerateeditbuttontrue onroweditingmygrid rowediting autogeneratedeletebuttontrue onrowdeletingmygrid rowdeleting onrowdataboundmygrid rowdatabound emptydatatextno value borderwidth0px borderstylesolid columns aspboundfield datafieldprimarykey headertextuserid aspboundfield datafieldcolumn1 headertextcolumn1 aspboundfield datafieldcolumn2 headertextcolumn2 aspboundfield datafieldcolumn3 headertextcolumn3 columnsaspgridview i also tried visiblefalse to hide primary key it hides primary key from thisplaying but also do not fetch its value and i want this valuehope my question is clear,"['c#', 'asp.net']" +580615,mockito injectmocks strange behaviour with final fields i am seeing behaviour that i believe is a bug injectmocks does not seem to create a new test subject before every test method where as mock does in the following example if subjectsection is final one test fails if its not final both pass my current workaround is to use beforeclass but this is not idealsubjectjavapackage inject mocks testpublic class subject private final section section public subjectsection section thissection section public section getsection return section sectionjavapackage inject mocks testpublic class section subjecttestjavapackage inject mocks testimport orgmockitoinjectmocksimport orgmockitomockimport orgmockitomockitoannotationsimport orgtestngannotationsbeforemethodimport orgtestngannotationstestimport static orgtestngassertassertequalspublic class subjecttest mock section section injectmocks subject subject beforemethod public void setup mockitoannotationsinitmocksthis test public void test1 assertequalssection subjectgetsection test public void test2 assertequalssection subjectgetsection cheers,['java'] +580629,is it possible to support both facebook login and google plus login in the same ios app i integrated google plus login in my ios app but i dont know how to add fb integration in the same app is it possible to use both logins in the same app,"['ios', 'iphone']" +580658,oracle 11g how to optimize slow parallel insert select we want to speed up the run of the parallel insert statement below we are expecting to insert around 80m records and it is taking around 2 hours to finishinsert parallelstaging ex16 append nologging into staging ex id tran dt recon dt start recon dt end recon config id recon pm id select parallelpm16 seq result idnextval sysdate sysdate sysdate 8a038312403e859201405245eed00c42 t1id from pm t1 where status 1 and not existsselect 1 from result where t1id recon pm id and create dt sysdate 60 and upload dt sysdate 1 and fund src type 1 we think that caching the results of the not exist column will speed up the inserts how do we perform the caching any ideas how else to speed up the insertplease see below for plan statistics from enterprise manager also we noticed that the statements are not being run in parallel is this normaledit btw the sequence is already cached to 1m,['sql'] +580721,css rule generates 404 error on some browsers in my server logs i get many errors such as thisfile does not exist mypathmozlineargradienttopwhitethis is apparently due to the following piece of bootstrap css where some browsers must interpret mozlineargradient as a background image to be downloadedbtn some code backgroundcolor whitesmokebackgroundimage webkitgradientlinear0 00 100fromwhitetoe6e6e6backgroundimage webkitlineargradienttopwhitee6e6e6backgroundimage olineargradienttopwhitee6e6e6backgroundimage lineargradientto bottomwhitee6e6e6backgroundimage mozlineargradienttopwhitee6e6e6backgroundrepeat repeatx more codehow can i prevent such errors from happeningthank you,['css'] +580737,what is the best ide for java android development what is the best ide for java development on mac osxive been using sublime text for all of my web based programming and ia m wondering wich ide is the best one to use while programming apps for android,"['java', 'android']" +580752,no module named time i compiled python from source usingwget tar jxvf python266tarbz2 cd python266 configure make make install version of pythonas3 python vpython 266i also installed pip installer but when i use pip install x i always get the following errortraceback most recent call last file usrlocalbinpip line 5 in module from pkg resources import load entry point file usrlocallibpython26sitepackagesthistribute0649py26eggpkg resourcespy line 16 in module import sys os time re imp types zipfile zipimportimporterror no module named timehow do i fix this,['python'] +580790,logical difference between linq where and firstordefault i know this may sound duplicate question like this or this but i wanted some clarity regarding the number iterations that will take place in this querymy assumptions are as followslets say i have collection of 10 itemsin where query it iterates through each and every item and add it to ienumerable ie it will need on alwaysforeach var item in mylist ifcondition add it to listenumerable continue through entire listin firstordefaultcondition queryit starts iterating through the collection and breaks the loop as soon as it gets the item matching the condition and returns single element or only if no item is matching condition then it will iterate through entire listso complexity can be from o1 to onforeach var item in mylist ifcondition return item break if this is correct then it will always be better to use firstordefault for a single item return,['c#'] +580808,mysterious crash with nsstring method rangeofcomposedcharactersequenceatindex my app uses several uitextviews and we are getting a crash report from users that we are unable to reproducethe crash report doesnat seem to contain any of our code and crashes with an nsinvalidargumentexception in the nsstring method rangeofcomposedcharactersequenceatindex which is not called directly by our code but seems to be called by the frameworkshere is the crash report0 corefoundation exceptionpreprocess 1301 libobjcadylib objc exception throw 382 corefoundation nsexception initwithcoder3 foundation nsstring rangeofcomposedcharactersequenceatindex 884 uikit 74uitextinputcontroller validcaretpositionfromcharacterindexdownstream block invoke 3285 uifoundation nstextstorage coordinatereading 366 uikit uitextinputcontroller validcaretpositionfromcharacterindexdownstream 2187 uikit 52uitextinputcontroller characterpositionforpoint block invoke 128 uifoundation nslayoutmanagertextlocking coordinateaccess 469 uikit uitextinputcontroller characterpositionforpoint 22410 uikit uitextselection setselectionwithfirstpointsecondpoint 5611 uikit uitextinteractionassistantuitextinteractionassistant internal twofingerrangedselectgesture 38612 uikit uigesturerecognizersendactions 19613 uikit uigesturerecognizer updategesturewitheventbuttonevent 113814 uikit uigesturerecognizerupdate block invoke 4815 uikit uigesturerecognizerremoveobjectsfromarrayandapplyblocks 21816 uikit uigesturerecognizerupdate 28217 corefoundation cfrunloop is calling out to an observer callback function 2018 corefoundation cfrunloopdoobservers 28419 corefoundation cfrunlooprun 73020 corefoundation cfrunlooprunspecific 521 corefoundation cfrunloopruninmode 10622 graphicsservices gseventrunmodal 13823 uikit uiapplicationmain 113624 mainm line 16 25 libdylddylib start 2 since i donat know exactly what part of our code is causing the crash iam not sure what sample code would be helpful to post iam more interested in hearing if anyone has seen anything like this or might have a suggestion about where or how to investigate this furtherupdate on 20131121i was able to reproduce this issue by doing the followingadd some text to my uitextview including a trailing newline character nget my app to force the uitextview to resign first responder statusget my app to assign first responder status to my uitextview and then tap to insert the cursor at the end of the string around the location of the newline characterafter which the app crashed with the above reporti attempted to create this in an empty xcode project with just a stock uitextview and nothing else and was unable to do so it seems as though there is something going on in my app that conspires with uitextview to make this crash occur would love to know what but the issue is solved for me in this project as we are not interested in trailing newline characters and can trim them thus keeping crashes from occurringif someone can reproduce this in a sample project would be great to file a radar if this is indeed a bug with uitextviewthanks to wattson12 and johan kool for responses leading to a solution,"['ios', 'objective-c']" +580895,thisable autoplay in youtube javascript api i know about using autoplay 0 in params and in url the problem is when i use the loadvideobyid function the initial video seems to always not autostart but the moment i load in new video that new one autostarts i dont want that new one to autostart eitherdocumentreadyfunction var playerwindowonyoutubeplayerapiready function player new ytplayerplayer height 390 width 640 videoid jw5mekfy3fy playervars autoplay 0 rel 0 showinfo 0 egm 0 showsearch 0 controls 0 modestbranding 1 events onready onplayerready onstatechange onplayerstatechange windowonplayerready functionevent eventtargetplayvideo loadnewvidbhqqvyy5kyowindowonplayerstatechange functionevent element when the video has ended if eventdata ytplayerstateended get rid of the player elementstylethisplay none function loadnewvidvidid playerloadvideobyidvidid large,"['javascript', 'jquery']" +580900,sharing assemblies using portable class library with dataannotations i have created a portable class library called datacontracts that contains my projects messages and views standard stuff like getstockitembyidrequest and stockview are contained in itthe problem lies when i attempt to add dataannotations by using systemcomponentmodeldataannotations for some of my views as such datacontractpublic class stockview required datamember public guid stockid get set required datamember public string name get set i can successfully add the systemcomponentmodeldataannotations to my portable class library project and can successfully reference it in my windows phone 8 app and can even create a new instance of my view as such stockview view new stockview within my windows phone app but if i try to use either newtonsoftjson or systemnethttphttpclient by doing something like httpclient client new httpclienthttpresponsemessage response await clientgetasynct result await responsecontentreadasasynctort result await newtonsoftjsonjsonconvertdeserializeobjectasynctie where deserialization is involvedi am faced with the error could not load file or assembly systemcomponentmodeldataannotations version2050 which i assume is because it does not appear that systemcomponentmodeldataannotations is supported in windows phone 8 but then why can i add it as a reference to my pclso my questions are why is not this error invoked when i create a new instance of these classes directly and secondly how do i work around this,['c#'] +580925,transparent gif in android imageview i am trying to thisplay the transparent gif image in my app with no success i can get to download and thisplay the icon in an imageview but with white background instead of transparent i have already tried these solutions with no sucessconvert gif to png programaticallyhas anyone figured out how to thisplay the gif image with transparency i am using the android 18 sdk,['android'] +580967,how to remove gaps between subplots in matplotlib the code below produces gaps between the subplots how do i remove the gaps between the subplots and make the image a tight gridimport matplotlibpyplot as pltfor i in range16 i i 1 ax1 pltsubplot4 4 i pltaxison ax1set xticklabels ax1set yticklabels ax1set aspectequal pltsubplots adjustwspacenone hspacenonepltshow,['python'] +580974,whats the best way to localise a date on laravel take this example articlecreated atformatm it returns nov i need to localise this to my language so the output should be kasthought about doing the following translanguagearticlecreated atformatm applangtrlanguagephp nov kasthis looks like reinventing the wheel and programmatically pretty terrible i am sure there are some localisation standards something like articlecreated atformatmlocalisetotr tr whats the best way to achieve this,['php'] +580991,rails url for behaving differently when using namespace based on current controller being used lets assume namespace is abc we have a controller abcs and another one that uses namespace abc is defsfor easy understanding abcscontrollerabcdefscontroller when current flow is in abcscontroller url forcontroller abcs action new is returning correct url but when flow is in abcdefscontroller when i am giving url forcontroller abcs action new it is treating it as url forcontroller abcabcs action new observe abcabcsso here it should be abcs but not abcabcs but it is treating like that whats the solution please ask me fr more information,['ruby-on-rails'] +581011,how to continuously get rssi without connecting to the ble device my application needs to constantly get rssi value of a bluetooth device to make some thistancerssi approximation without connecting however callback method of the bluetoothadapter gets the rssi only once when the device scanned device scan callbackprivate bluetoothadapterlescancallback lescancallback new bluetoothadapterlescancallback override public void onlescanfinal bluetoothdevice device final int rssi byte scanrecord runonuithreadnew runnable public void run as a solution i created two runnable objects one is for starting other is for stopping scan process these two objects call each other continuously until i get my desired rssi value after that my handler removes them from message queueprivate runnable startscan new runnable override public void run bluetoothadapterstartlescanlescancallback scanhandlerpostdelayedstopscan scan interval private runnable stopscan new runnable override public void run bluetoothadapterstoplescanlescancallback scanhandlerpostdelayedstartscan stop interval this seems to be working but i want to know if there is more viable option to do this without connecting,['android'] +581025,where are net 40 memorycache performance counters where are net 40 memorycache performance countersi am looking for their name and i cannot find anythank you,"['c#', '.net']" +581045,how to write a constant time function to copy the most significant bit to all bits i would like to write a function in c which takes the msb of uint8 t and if it is set returns 0xff and if not 0x00 in short which returns an integer where all the bits are set to the same value as the msbbut i would like to do it in a completely constant time way no branches no array offsets just mathematical operations which are guaranteed to always touch the same number of bits and ideally without any undefined behavior how can this be done,['c'] +581053,how to use cmake export compile commands i have been trying to use clangmodernize with cmake export compile commands as recommended in the help of this toolwith this option cmake generates a json file containing compile info like include paths see alsothis variable is accepted on the command line of cmake but cmake helpvariable cmake export compile commands does not work which is coherent with this mailing list postinghas someone any idea on how to use iti could also use it with cppchecksome more infoi have thiscovered on a clang developer forum that this cmake feature is not available on all generators this might change in the future in the mean time my question remains and i will try too see what happen if i use other generators than visual studio,['c++'] +581067,what is the best way to detect websocket support using javascript i am trying to use javascript to detect if a web browser supports websockets but using only featurebased detection i am getting false positives so i added a user agent test to throw out android devices instead which i am not happy about i have a samsung galaxy tab 2 and heres my detection codevar issupported websocket in window windowwebsocket undefined mozwebsocket in window this line exists because my galaxy tab 2 would otherwise appear to have support if issupported navigatoruseragentindexofandroid 0 issupported falseif issupported documentwriteyour browser supports websocketselse documentwriteyour browser does not support websocketsthis code seems to work with ie firefox safari including iphoneipad and chrome however the featurebased check is returning true when i use the default browser of my samsung galaxy tab 2 which is incorrect because that browser does not actually support websockets furthermore i do not know how many other android devices have this same issue so at the moment this is the best solution i am aware of for detection is there a better way to detect websocket support other than what i am doing i do realize that workarounds exist for android such as using a different browser which means my user agent detection code asis would not be a good thing my goal is to not have to rely on the user agent in the first placeany suggestions,"['javascript', 'android']" +581168,how to load hibernatecfgxml from different location i am creating a jar using hibernate i have encountered a situation where i need to change a setting url often so i would like to load the hibernatecfgxml like thissessionfactory sessionfactory new configuration configuredfaxhibernatecfgxml buildsessionfactorybut then running the project i am getting this exceptionorghibernatehibernateexception dfaxhibernatecfgxml not found at orghibernateutilconfighelpergetresourceasstreamconfighelperjava147 at orghibernatecfgconfigurationgetconfigurationinputstreamconfigurationjava1287 at orghibernatecfgconfigurationconfigureconfigurationjava1309 at hibernatelaborderhelpergetdatabasesesionlaborderhelperjava55 at hibernatetestmaintestjava42how can i load hibernatecfgxml from a different location than the class path,['java'] +581169,coredata error serious application error exception was caught during core data change processing hi i am getting crashwhen i am trying to insert 10 records into db in back ground i am getting following exceptioncoredata error serious application error exception was caught during core data change processingthis is usually a bug within an observer of nsmanagedobjectcontextobjectsdidchangenotification nscfset addobject attempt to insert nil with userinfo null201319 094119587 3ptalk7487907terminating app due to uncaught exception nsinvalidargumentexception reason nscfset addobject attempt to insert nili used the code for inserting objextsthispatch queue t mybackgroundq thispatch queue createcomsampleaddressbook null could also get a global queue in this case do not release it belowthispatch time t delay thispatch timethispatch time now nsec per secthispatch afterdelay mybackgroundq void self useraddressbookthispatch releasemybackgroundqself performselectoronmainthreadselectorstartsyncloader withobjectnil waituntildoneyes,"['ios', 'objective-c']" +581243,do zombies exist in net i was having a thiscussion with a teammate about locking in net he is a really bright guy with an extensive background in both lowerlevel and higherlevel programming but his experience with lower level programming far exceeds mine anyway he argued that net locking should be avoided on critical systems expected to be under heavyload if at all possible in order to avoid the admittedly small possibility of a zombie thread crashing a system i routinely use locking and i did not know what a zombie thread was so i asked the impression i got from his explanation is that a zombie thread is a thread that has terminated but somehow still holds onto some resources an example he gave of how a zombie thread could break a system was a thread begins some procedure after locking on some object and then is at some point terminated before the lock can be released this situation has the potential to crash the system because eventually attempts to execute that method will result in the threads all waiting for access to an object that will never be returned because the thread that is using the locked object is dead i think i got the gist of this but if i am off base please let me know the concept made sense to me i was not completely convinced that this was a real scenario that could happen in net i have never previously heard of zombies but i do recognize that programmers who have worked in depth at lower levels tend to have a deeper understanding of computing fundamentals like threading i definitely do see the value in locking however and i have seen many world class programmers leverage locking i also have limited ability to evaluate this for myself because i know that the lockobj statement is really just syntactic sugar for bool lockwastaken falsevar temp objtry monitorentertemp ref lockwastaken body finally if lockwastaken monitorexittemp and because monitorenter and monitorexit are marked extern it seems conceivable that net does some kind of processing that protects threads from exposure to system components that could have this kind of impact but that is purely speculative and probably just based on the fact that i have never heard of zombie threads before so i am hoping i can get some feedback on this hereis there a clearer definition of a zombie thread than what i have explained herecan zombie threads occur on net whywhy not if applicable how could i force the creation of a zombie thread in netif applicable how can i leverage locking without risking a zombie thread scenario in netupdatei asked this question a little over two years ago today this happened,"['c#', '.net']" +581278,how do i debug a programmatically injected js file in google chrome i am injecting a js file to every page in google chrome via chromebrowseractiononclickedaddlistenerfunctiontab chrometabsexecutescriptnullfilejscontentjsfunctionresultarr consolelogresultarr contentjsconsoleloghello stackoverflowi can see hello stackoverflow printed in the console of the webpage but i am not able to find the source file so i can debug it any idea how,['javascript'] +581321,javanetbindexception bind failed eaddrinuse address already in use i have a service which starts thread to perform some operations on socket the code looks like public class serverrunnable implements runnable override public void run serversocket serversocket null try serversocket new serversocket serversocketsetreuseaddresstrue serversocketbindnew inetsocketaddressprotocolconstantsusb server port while true socket client serversocketaccept some code catch exception e logeexception while listening on socket e finally if serversocket null try serversocketclose catch ioexception e logee when i start service first time everything is ok but then i have to stop it using stopservice method when i start it one more time it returns following exceptionjavanetbindexception bind failed eaddrinuse address already in usein addition i added serversocket closing in ondestroy method of service but it did not helpthe setreuseaddress is performed before bind so why it is not working,['android'] +581330,identical code producing inconsistent image quality on different servers take the following two imagesdev version iis7 windows 7 pro 64bit machinelive version iis7 windows server 2008 64bit machinenote how the live version is pixelly looks low quality the dev version however is smooth antialiased looks fine these are both generated by identical code settingsdim maxheight as integer 140dim maxwidth as integer 140dim workingfolderpath as string serversharebladim allowedfileextensions as new arraylistallowedfileextensionsaddjpgallowedfileextensionsaddjpeg select an image to use from the workingfolderdim imagefilename as string dim workingfolder as new iodirectoryinfoworkingfolderpathdim sourceimages as iofileinfo workingfoldergetfilesfor each sourceimage as iofileinfo in sourceimages if allowedfileextensionscontainssourceimageextensiontolower true then imagefilename sourceimagename end ifnext determine path to selected image if no image was found use a placeholderdim physicalpath as string if imagefilename then no image was found use the filler image physicalpath servermappathproductofthemonthmissingjpgelse an image was found redirect to it build path for thumnailing if requestquerystringfullsize true then responseredirectsharebla imagefilename else physicalpath workingfolderpath imagefilename end ifend if load image and output in binary resizing if necessaryusing productimage as systemdrawingimage systemdrawingimagefromfilephysicalpath dim newwidth as integer productimagewidth dim newheight as integer productimageheight check if selected size is too big if so determine new size if productimagewidth maxwidth or productimageheight maxheight then dim ratiox as double cdblmaxwidth productimagewidth dim ratioy as double cdblmaxheight productimageheight dim ratio as double mathminratiox ratioy newwidth cintproductimagewidth ratio newheight cintproductimageheight ratio end if create a new bitmap from the image with new size dim codecs as imagecodecinfo imagecodecinfogetimageencoders dim codecinfo as imagecodecinfo nothing dim productofthemonth as new bitmapproductimage newwidth newheight dim resizer as graphics graphicsfromimageproductofthemonth resizerinterpolationmode interpolationmodehighqualitybicubic resizersmoothingmode smoothingmodehighquality resizerpixeloffsetmode pixeloffsetmodehighquality resizercompositingquality compositingqualityhighquality ensure the encoder uses the best quality settings dim encoderparams as new encoderparameters3 encoderparamsparam0 new encoderparametersystemdrawingimagingencoderquality 100l encoderparamsparam1 new encoderparametersystemdrawingimagingencoderscanmethod cintencodervaluescanmethodinterlaced encoderparamsparam2 new encoderparametersystemdrawingimagingencoderrendermethod cintencodervaluerenderprogressive set jpeg as the output codec for each codec as imagecodecinfo in codecs if codecmimetype imagejpeg then codecinfo codec end if next ready a memory stream and byte array dim memstream as new memorystream dim bmpbytes as byte save the image the the memory stream prep contenttype for http reasponse responsecontenttype imagejpeg productofthemonthsavememstream codecinfo encoderparams flush memory stream into byte array flush to browser bmpbytes memstreamgetbuffer responsebinarywritebmpbytes cleanup productofthemonththispose memstreamclose productimagethisposeend usingwhat is the reason behind this how do i address the issue presumably its a gd issue on the live web server but i have no idea what i tried to be as thorough as possible in setting graphic and codec settings but its still differentedit source image is identical in both examples too located on a central unc share copy of source image here,['.net'] +581379,how to append to a json object in angular js i am having an object like this scopereleases name all stageactivetruei need to append more data to it name developmentactivefalse name productionactivefalse name stagingactivefalseso the final data should be like this name all stageactivetrue name developmentactivefalse name productionactivefalse name stagingactivefalsei tried the following code but it is not appendingappcontrollermainctrl functionscope i am having an object like this scopereleases name all stageactivetrue i need to appned some more data to it scopereleases name developmentactivefalse name productionactivefalse name stagingactivefalse pluker link,['javascript'] +581471,sha1 certificate fingerprint i am trying to make an app that can communicate with google cloud messaging i have looked at some tutorials and read a lot of stuff but it all skips one point when configuring an android key for api project it asks for a sha1 certificate fingerprinthow do i find this i have eclipse and windows 7any help would be appreciated,['android'] +581476,how to debug which alarmmanager alarms are running from your application we have a few repeating alarms setup and they work normally most of the time sometimes though they get stuck probably canceled somehowhow to debug it to make sure an alarm is actually off when it seems stuckregarding the reasons for the alarm to be cancelled i am aware it happens when the user force stops your app from applications manager can the system also randomly cancel it say when killing your whole app to reclaim resources,['android'] +581482,no module named x when reloading with osexecl i have a python script that is using the following to restartpython sysexecutableosexeclpython python sysargvmost the time this works fine but occasionally the restart fails with a no module named error examplestraceback most recent call lastfile usrlibpython27sitepy line 68 in moduleimport osfile usrlibpython27ospy line 49 in moduleimport posixpath as pathfile usrlibpython27posixpathpy line 17 in moduleimport warningsfile usrlibpython27warningspy line 6 in moduleimport linecacheimporterror no module named linecachetraceback most recent call lastfile usrlibpython27sitepy line 68 in moduleimport os file usrlibpython27ospy line 49 in moduleimport posixpath as path file usrlibpython27posixpathpy line 15 in moduleimport stat importerror no module named statedit i attempted gccollect as suggested by andr0x and this did not work i got the same errortraceback most recent call lastfile usrlibpython27sitepy line 68 in moduleimport osfile usrlibpython27ospy line 49 in moduleimport posixpath as pathimporterror no module named posixpathedit 2 i tried sysstdoutflush and im still getting the same error i have noticed i am only every getting between 13 successful restarts before an error occurs,['python'] +581489,is my implementaton of httpclient singleton appropriate i am using systemnethttpclient net 45 in my mvc4 project i know that a single instance of httpclient can be used for all http requests across the web app here is my implementation of the httpclient singleton which should return the single instance every time public sealed class httpclientinstance httpclient singleton instance private static readonly httpclientinstance instance new httpclientinstance static httpclientinstance private httpclientinstance base timeout timespanfrommilliseconds150 summary returns the singleton instance of httpclient summary public static httpclient instance get return instance do you see any issues with this i know i could possibly use ninject to inject the dependency in singleton scope but that is besides the point,['c#'] +581491,installing pyodbc fails on osx 109 mavericks when running pip install pyodbc i getin file included from buildpyodbcsrcbuffercpp12 buildpyodbcsrcpyodbch5210 fatal error sqlh file not found include sqlh 1 error generated error command cc failed with exit status 1it seems that mavericks has no sqlh under usrincludedid anyone manage to install pyodbc is there a known workaround,['python'] +581533,making an efficient java 8 sorted spliterator from an array in java 8 a variety of convenient utilities are provided to build efficient spliterators from arrays however no factory methods are provided there to build a spliterator with a comparator clearly spliterators are allowed to have attached comparators they have a getcomparator method and a sorted propertyhow are library authors supposed to build sorted spliterators,['java'] +581538,lack of speedup and erroneous results with openmp and cython i am trying to speed up a simple piece of code written in cython with openmp it is a double loop that for each position in the input array adds a quantity at each reference point heres the main part of the code cimport cython import numpy as npcimport numpy as npcimport openmpdtype npdoublectypedef npdouble t dtype tcdef extern from mathh nogil dtype t sqrtdtype tcythoncdivisiontruecythonboundscheckfalsedef summationnpndarraydtype tndim2 pos npndarraydtype tndim1 weights npndarraydtype t ndim2 points int num threads 0 from cythonparallel cimport prange parallel threadid if num threads 0 num threads openmpomp get num procs if num threads openmpomp get num procs num threads openmpomp get num procs openmpomp set num threadsnum threads cdef unsigned int nips lenpoints cdef npndarraydtype t ndim1 sum array npzerosnips dtype npfloat64 cdef npndarraydtype t ndim2 sum array3d npzerosnips3 dtype npfloat64 cdef unsigned int and lenweights cdef unsigned int pi i id cdef double dx dy dz dr weight i xiyizi print num threads openmpomp get num threads for i in prangennogiltrueschedulestatic weight i weightsi xi posi0 yi posi1 zi posi2 for pi in rangenips dx pointspi0 xi dy pointspi1 yi dz pointspi2 zi dr 10sqrtdxdx dydy dzdz sum arraypi weight i dr sum array3dpi0 weight i dx sum array3dpi1 weight i dy sum array3dpi2 weight i dz return sum array sum array3di have put it into a gist with the associated test and setup files two issues arise first in the current configuration i am not able to get any speedup the code runs on multiple cores but the timings show no advantage second the results are different depending on the number of cores indicating that there is a race condition are not the inplace sums supposed to end up being reductions or is something funny happening since it is a nested for loop i figured everything inside the prange is executed in each thread individually both of these go away if i reverse the order of the loops but because my outer loop the way it is structured now is where all the data reading gets done if i reverse them the arrays are traversed num thread times which is wasteful i have also tried putting the whole nested loop inside a with parallel block and use threadlocal buffers explicitly but was not able to get it to work clearly i am missing something basic about how openmp is supposed to work though maybe this is particular to cython so i would be grateful for tips,"['python', 'c']" +581589,maven would not run my project failed to execute goal orgcodehausmojoexecmavenplugin121exec i cannot run the maven netbeans javafx example failed to execute goal orgcodehausmojoexecmavenplugin121exec defaultcli on project mavenproject3 command execution failed process exited with an error 1 exit value 1 help 1to see the full stack trace of the errors rerun maven with the e switch rerun maven using the x switch to enable full debug loggingmy pom looks like this project xmlns xmlnsxsi xsischemalocation modelversion400modelversiongroupidcomhuwalmexofficeclientgroupidartifactidalmexofficeclientartifactidversion10snapshotversionpackagingjarpackagingnamealmex office clientnameproperties projectbuildsourceencodingutf8projectbuildsourceencoding mainclasscomhuwalmexofficeclientmainappmainclasspropertiesorganization used as the vendor for jnlp generation nameyour organisationnameorganizationbuild plugins plugin groupidorgapachemavenpluginsgroupid artifactidmavendependencypluginartifactid version26version executions execution idunpackdependenciesid phasepackagephase goals goalunpackdependenciesgoal goals configuration excludescopesystemexcludescope excludegroupidsjunitorgmockitoorghamcrestexcludegroupids outputdirectoryprojectbuilddirectoryclassesoutputdirectory configuration execution executions plugin plugin groupidorgcodehausmojogroupid artifactidexecmavenpluginartifactid version121version executions execution idunpackdependenciesid phasepackagephase goals goalexecgoal goals configuration executablejavahomebinjavafxpackagerexecutable arguments argumentcreatejarargument argumentnocss2binargument argumentappclassargument argumentmainclassargument argumentsrcdirargument argumentprojectbuilddirectoryclassesargument argumentoutdirargument argumentprojectbuilddirectoryargument argumentoutfileargument argumentprojectbuildfinalnamejarargument arguments configuration execution executions plugin plugin groupidorgapachemavenpluginsgroupid artifactidmavencompilerpluginartifactid version31version configuration source17source target17target compilerarguments bootclasspathsunbootclasspathpathseparatorjavahomelibjfxrtjarbootclasspath compilerarguments configuration plugin pluginsbuilddoes anyone know why this is happeningand if not does anyone know how to get maven running with the e or the x switch via netbeans i assume it is via a right click on the pom and then run goal then entering something in the textfield there,['java'] +581596,double structural equality operators ifabc i wrote some code by accident today and was surprised when eclipse did not yell at me for once the code had a double use of the structural equality operator similar to the below with the ifabc structurepublic class tripleequal public static void mainstring args boolean a true false boolean b true false boolean c true false for int adex 0 adex 2 adex for int bdex 0 bdex 2 bdex for int cdex 0 cdex 2 cdex if aadex bbdex ccdex systemoutprintfgot abc with d d dn adex bdex cdex the output is got abc with 0 0 0got abc with 0 1 1got abc with 1 0 1got abc with 1 1 0playing around i notice i cannot do ifabc with any type but boolean from that the boolean expression is a b c a b c a b c a b c which simplifies to abc abc thus ignoring sideeffect ifabc is equal to ifab c ab c can anyone explain how the ifabc syntax suggests thatedit 1i found where my confusion was after so many people explained the leftassociativity usually i write 1 for true and 0 for false but my minimized truth tableoutput in the above test i had 0 for true and 1 for false the negation of the expression a b c a b c a b c a b c is abc,['java'] +581598,simple jquery hover enlarge i am not sure where i am going wrong i am trying to create a very simple hoverenlarge plugin with jquery using the scale function here is my codedocumentreadyfunction content imgtogglescale percent 80 0content imghoverfunction thiscsscursor pointer thistogglescale percent 90 500 function thistogglescale percent 80 500heres a small example heres the page if somone knows where i have gone wrong that would awesomethanks,['jquery'] +581639,php pdo mysql how do i return integer and numeric columns from mysql as integers and numerics in php i have seen this question repeated a few times on stack overflow but none sufficiently explore the problem or at least in a way that is helpful to methe problem is that a db query should return integer data types in php for integer columns instead the query returns every column as a string typei have ensured that pdoattr stringify fetches if false just to make sure results are not being cast to stringanswers that i have seenit cannot be donenope it is working on mac os x installed phpmysqltype cast all your values in your codenope i would not be doing thatdo not worry about it php is loosely typedmy data is output as json and is consumed by many other services some require the data in the correct formatfrom my research i understand that this is a driver implementation issuemany sources claim that the mysql native driver does not support returning numeric types this does not seem true since it works on mac os x unless they mean to say that the mysql native driver on linux does not support the featurethis implies that there is something special about the driverenvironment i have installed on mac os x i have been trying to identify the differences in order to apply a fix but i am limited by my knowledge of how to check these thingsthe differencesphp on os x was compiled and installed via home brewphp on ubuntu was installed via aptget install php5devphp on os x is connecting to a mysql server also running on os xserver version 5171log source thistributionphp on ubuntu is connecting to a rackspace cloud databaseserver version 51660squeeze1 debianubuntu environmentversion 10041php 54211debphporglucid1 cli built oct 21 2013 081437php ipdo mysqlpdo driver for mysql enabledclient api version 5172mac os x environment1075php 5416 cli built aug 22 2013 090558php ipdo mysqlpdo driver for mysql enabledclient api version mysqlnd 5010 201026 id e707c415db32080b3752b232487a435ee0372157 pdo flags usedpdoattr case pdocase naturalpdoattr errmode pdoerrmode exceptionpdoattr oracle nulls pdonull naturalpdoattr stringify fetches falsepdoattr emulate prepares falseany help and expertise would be appreciated i will definitely be posting back here if i find the answer,"['php', 'mysql']" +581702,how to make background activity smaller while opening the navigation drawer i want to make my background activity a little bit smaller while opening the navigation drawer simulate the effect that exists in the airbnb application i guess the best explanation would be a screenshotbut the point is not to make the view just smaller but to make it an animation that is synchronized to the drawer openclose animation so if you started to open the drawer an in the middle decided to stop and go back the background activity scale will be affected accordinglyhow can this be done using the build in drawerlayout is there some implementation for this thanks in advance,"['java', 'android']" +581740,module object has no attribute loads while parsing json using python i am trying to parse json from python i recently started working with python so i followed some stackoverflow tutorial how to parse json using python and i came up with below code usrbinpythonimport jsonj jsonloadsscriptbinbash echo hello worldprint jscriptbut whenever i run the above code i always get this error traceback most recent call last file jsonpy line 2 in module import json file cygdriveczookpythonjsonpy line 4 in module j jsonloadsscriptbinbash echo hello worldattributeerror module object has no attribute loadsany thoughts what wrong i am doing here i am running cygwin in windows and from there only i am running my python program i am using python 273and is there any better and efficient way of parsing the json as wellupdatebelow code does not work if i remove the single quote since i am getting json string from some other method usrbinpythonimport jsonjsonstr scriptbinbash echo hello worldj jsonloadsjsonstrshell script jscriptprint shell scriptso before deserializing how to make sure it has single quote as wellthis is the error i get traceback most recent call last file jsontestpy line 7 in module j jsonloadsjsonstr file usrlibpython27json init py line 326 in loads return default decoderdecodes file usrlibpython27jsondecoderpy line 366 in decode obj end selfraw decodes idx ws 0endtypeerror expected string or buffer,['python'] +581795,tfs workitemstore throws comexception in aspnet mvc app when using authentication i am completely stumped by this and endless googlestackoverflow searches have not helped i am using the 2012 visual studio sdk to connect to tfs 2012 and query the work item store the code below works perfectly fine in both a console application and an aspnet mvc app that does not use authentication or in any scenario that is run on my local machine however i get a comexception when i try to instantiate a workitemstore from within an mvc app that is been deployed to the server and uses windows authentication it makes no difference if i have the authentication modewindows element in my webconfig or not as long as there is an authorize attribute on my controller or any of its action methods i get an exception as soon as the last line of code below is invoked if i remove the authorize attribute the exception does not occur if i call the code below at some point before calling code decorated with authorize the exception does not occur somehow using the authorizeattibute is inducing this exceptionany ideas of how to resolve this or at least for more exactly identifying the real root problem i would really like to understand what is going on hereuri tfsaddress new urihttptfsaddress8080tfsdefaultcollectionvar mycreds new networkcredentialusername password domainvar tfscreds new tfsclientcredentialsnew windowscredentialmycreds falsevar defaultcollection new tfsteamprojectcollectiontfsaddress tfscredsdefaultcollectionensureauthenticatedvar store defaultcollectiongetserviceworkitemstore exceptionstack tracecomexception 0x804005 error hresult e fail has been returned from a call to a com componentmicrosoftteamfoundationworkitemtrackingclientdatastoredatastorenativebegindatastoreinitintptr handle string defaultcachepath string instanceid int32 cacheversion 0microsoftteamfoundationworkitemtrackingclientdatastoredatastorebegindatastoreinitstring defaultcachepath string instanceid int32 cacheversion 56microsoftteamfoundationworkitemtrackingclientworkitemstoreinitializeinternal 598microsoftteamfoundationworkitemtrackingclientworkitemstoremicrosoftteamfoundationclientitfsteamprojectcollectionobjectinitializetfsteamprojectcollection teamprojectcollection 23microsoftteamfoundationclienttfsteamprojectcollectioninitializeteamfoundationobjectstring fullname object instance 43microsoftteamfoundationclienttfsconnectioncreateserviceinstanceassembly assembly string fullname 91microsoftteamfoundationclienttfsconnectiongetserviceinstancetype servicetype object serviceinstance 200microsoftteamfoundationclienttfsteamprojectcollectiongetserviceinstancetype servicetype object serviceinstance 439microsoftteamfoundationclienttfsconnectiongetservicetype servicetype 241microsoftteamfoundationclienttfsconnectiongetservice 58,['c#'] +581826,are there directives in cc preprocessor to convert string to number i wish to add some conditional directive in my code to control different build for exampleif version 100 compiling here endifthe problem is that version is in others code where i cannot change it was defined as a stringdefine version 101i am wondering if there is some sort of macro or directive which converts the string to number so i can simply doif string to numberversion 100 compiling here endifis that possible pleasepsit seems my description is not quite clear the main purpose of this requirement is to control the version branch for example in old version preversion 100 this program would like old function after this version all functions have been migrated to new function so i need to write codes like thatif version 100 old functionelse new functionendifif version 100int old function elseint new function endifyou can see that only one of the function will be compiled therefore the condition must be decided in preprocessing stage not in the runtimethe tricky part is the version had been defined as a string which brought this question,['c'] +581900,clear uiview of drawing i am using a subclass of uiview to draw this subclassed view is used to get your signature on a view controller there is a clear button which is supposed to clear the uiview except it does not work here is what i have triedsubclasshimplementation subclassed uiview uibezierpath path uiimage incrementalimage 1 idinitwithcodernscoder adecoder if self super initwithcoderadecoder self setmultipletouchenabledno self setbackgroundcoloruicolor clearcolor path uibezierpath bezierpath path setlinewidth20 return self voiddrawrectcgrectrect incrementalimage drawinrectrect 3 path stroke voidtouchesbegannsset touches witheventuievent event uitouch touch touches anyobject cgpoint p touch locationinviewself path movetopointp voidtouchesmovednsset touches witheventuievent event uitouch touch touches anyobject cgpoint p touch locationinviewself path addlinetopointp self setneedsthisplay voidtouchesendednsset touches witheventuievent event 2 uitouch touch touches anyobject cgpoint p touch locationinviewself path addlinetopointp self drawbitmap 3 self setneedsthisplay path removeallpoints 4 voidtouchescancellednsset touches witheventuievent event self touchesendedtouches witheventevent voiddrawbitmap 3 uigraphicsbeginimagecontextwithoptionsselfboundssize no 00 uicolor blackcolor setstroke if incrementalimage first draw uibezierpath rectpath uibezierpath bezierpathwithrectselfbounds enclosing bitmap by a rectangle defined by another uibezierpath object uicolor clearcolor setfill rectpath fill fill it incrementalimage drawatpointcgpointzero path stroke incrementalimage uigraphicsgetimagefromcurrentimagecontext uigraphicsendimagecontextendview controllerm ibactioncleartappedidsender selfsubclassedviewbackgroundcolor uicolor clearcolor cgcontextref context uigraphicsgetcurrentcontext cgcontextsetfillcolorwithcolorcontext uicolor clearcolorcgcolor cgcontextfillrectcontextselfsubclassedviewbounds cgcontextclearrectcontext selfsubclassedviewbounds cgcontextflushcontext selfsubclassedview setneedsthisplaycan anyone tell me why this does not work and what i should do instead,"['ios', 'objective-c']" +581913,aspnet web api to return xml and get xml i have a controller which returns a data in json i would like that method to return xml structure and get data back to xml structurei have added following code to webapiconfigconfigroutesmaphttproute name defaultapi routetemplate apicontrollerid defaults new id routeparameteroptional configroutesmaphttproute name vehicleapi routetemplate apicontrollerid defaults new id routeparameteroptional configformattersxmlformattersupportedmediatypesaddnew mediatypeheadervaluetextxmlvar appxmltype configformattersxmlformattersupportedmediatypesfirstordefaultt gt tmediatype applicationxmlglobalasaxcsglobalconfigurationconfigurationformattersclearglobalconfigurationconfigurationformattersaddnew systemnethttpformattingxmlmediatypeformatter,"['c#', 'asp.net']" +582007,concurrent db table indexing through alembic script is it possible to create concurrent indexes for db table through alembic scripti am using postgres db and able to create concurrent table indexes through sql command on postgres promptcreate index concurrently on but could not find way to create same through db migrationalembic script if we create normal indexnot concurrent it will lock db table so cannot perform any query in parallel so just want to know how to create concurrent index through alembicdb migration script,['python'] +582050,error loading rubygems plugin i14opensslbundle loaderror i am new to ruby when i type any thing related to gem error below will happen why causes it and how to solve the problem thankserror loading rubygems plugin userschiangrvmgemsruby200p247globalgemsrubygemsbundler122librubygems pluginrb dlopenuserschiangrvmrubiesruby200p247libruby200x86 64darwin1230opensslbundle 9 library not loaded optlocalliblibssl100dylib referenced from userschiangrvmrubiesruby200p247libruby200x86 64darwin1230opensslbundle reason image not found userschiangrvmrubiesruby200p247libruby200x86 64darwin1230opensslbundle loaderror,['ruby'] +582153,string vs char i have some slides from ibm named from java code to java heap understanding the memory usage of your application that says when we use string instead of char there is maximum overhead would be 241 for a single characterbut i am not able to understand what overhead is referred here can anybody please helpsource,['java'] +582192,when designing a python api is it more pythonic to throw exceptions or return falsenone etc i am using a python based api where there are lots of functions to query things like doespointexist findpoint cancreatenewpoint etc where the negative result throws an exception this makes the code much more cluttered filled with trycatch statements instead of directly using the result as a boolean valuesince i am not a python expert i am wondering if this design is pythonic or not i have not seen this sort of design in the standard libraries though so i am assuming this kind of exception usage in python apis is frowned upon,['python'] +582299,using invalidation contexts for uicollectionviewlayout so i have implemented working sticky headers in my uicollectionview in part by returning yes from shouldinvalidatelayoutforboundschange however this impacts performance and i do not want to invalidate the entire layout only my header sectionnow according to the official documentation i can use uicollectionviewlayoutinvalidationcontext to define a custom invalidation context for my layout but the documentation is very lacking it asks me to define custom properties that represent the parts of your layout data that can be recomputed independently but i do not understand what they mean by thishas anyone got any experience subclassing uicollectionviewlayoutinvalidationcontext,['ios'] +582353,storing rsa private key android during the creation of simple messaging android application that is to encryptdecrypt messages and send them through internet i decided to use rsa publicprivate key encryption question is how to store private key so that even if phone is maliciously rooted the key would stay safe as far as i understood keystore is used for certificates and cannot be used for this should i encrypt private key as text file with aes i have very little experience with security so please feel free to correct my ideas and give your opinionkind regards,['android'] +582385,hamcrest hasitem and hasproperty assert if a object with property value exists import static orghamcrestmatcherassertassertthatimport static orghamcrestmatchershasitemimport static orghamcrestmatchersequaltoassertthatactual hasitemhaspropertyid equalto1lwhere actual is a pojo with id as longi getthe method assertthatt matcher super t in the type matcherassert is not applicable for the arguments listpojo matcheriterable super objectfrom various documentation and other stackoverflow pages it should be valid but i get the above error,['java'] +582392,alternative to indexeddb in not supported browsers safariios safchrome i have a working sample with indexeddb that works perfect for my desktop chrome nevertheless my main aim is to develop for ios devices chromesafari and this api is not available there yetwhat should i doi have seen this polyfill but i tested it with my ipod touch 5th gen and somehow the 19th test does not workshould i use websql which was deprecated i liked the idea of the polyfill but that it not working for meare there any plans to support indexeddb in the future for all the nonsupported browsersthanks,"['javascript', 'ios']" +582406,passing numpy array to cython i am learning cython i have problem with passing numpy arrays to cython and do not really understand what is going on could you help mei have two simple arraysa nparray12b nparray1434i want to compute a dot product of them in pythonnumpy everything works fine npdotabarray 7 12i translated the code to cython as here import numpy as npcimport numpy as npdtype npintctypedef npint t dtype tdef dotnpndarray a npndarray b cdef int d npdota b return dit compiled with no problems but returns an error dotabtraceback most recent call last file stdin line 1 in module file testpyx line 8 in testdot testc1262 cdef int d npdota btypeerror only length1 arrays can be converted to python scalarscould you tell me why and how to do it correctly unfortunately google was not helpfulthanks,['python'] +582409,how to read from a text file compressed with 7z in python i would like to read in python 27 line by line from a csv text file which is 7z compressed i do not want to decompress the entire large file but to stream the linesi tried pylzmadecompressobj unsuccessfully i get a data error note that this code does not yet read line by lineinput filename rtestingcsv7zwith openinput filename rb as infile obj pylzmadecompressobj o opendecompressedraw wb obj pylzmadecompressobj while true tmp infileread1 if not tmp break owriteobjdecompresstmp ocloseoutput owriteobjdecompresstmpvalueerror data error during decompression,['python'] +582417,add uilabel under uicollectionview cell i have a uicollectionview that shows images similar to cover art or ibooks i would like for it to show the title of the audio clip underneath the uiimageview i have in my mainwindowxib a view controller with a uicollectionview inside it i also built a nibcellxib for the cell itself in the cell i have a uiimageview that fills up all but the bottom 30 px of the cell in this area i add a uilabel i give the uiimageview a tag of 100 and uilabel a tag of 200 and in my code i putuicollectionviewcell collectionviewuicollectionview collectionview cellforitematindexpathnsindexpath indexpath rssentry entry allentries objectatindexindexpathrow static nsstring cellidentifier cvcell uicollectionviewcell cell collectionview dequeuereusablecellwithreuseidentifiercellidentifier forindexpathindexpath uiimageview titlelabel uiimageview cell viewwithtag100 uilabel titlelabel2 uilabel cell viewwithtag200 nsstring thearticleimage entryarticleimage titlelabel setimagewithurlnsurl urlwithstringentryarticleimage placeholderimageuiimage imagenamed titlelabel2 settextentryarticletitle return cellhowever no matter how the cell is set up in nibcellxib it makes the uiimageview fill the entire cell and adds the uilabel on top of it any suggestions,['ios'] +582420,whats the difference between feature detection feature inference and using the ua string i was asked this question in a job interview recently specifically around javascript i was wondering the proper responsewhat exactly is the difference between feature detection feature inference and using the user agent string,['javascript'] +582506,removing index column in pandas i have the following code which imports a csv file there are 3 columns and i want to set the first two of them to variables when i set the second column to the variable efficiency the index column is also tacked on how can i get rid of the index columndf pddataframefrom csvefficiency datacsv header0 parse datesfalseenergy dfindexefficiency dfefficiencyprint efficiencyi tried using del dfindexafter i set energy dfindexwhich i found in another post but that results in keyerror index,['python'] +582567,abort sms intent on android kitkat i am currently developing an application that needs to deal with sms only if it is an sms expected by the application same behaviour as whatsapp on registrationi would like to abort the sms intent as it is not expected to appear in the sms boxmy question is i know that google changed a lot about sms behaviour in kitkat and now even if my sms is well parsed by my application the sms also appear in smsbox even if i call thisabortbroadcast in my sms broadcast receiver so is there a way to avoid those sms appearing in sms box without having to develop a complete sms application for information the priority is yet to 10 and i tried also with max integer in manifest file for this broadcast receiver,['android'] +582581,turn pandas multiindex into column i have a dataframe with 2 index levels valuetrial measurement 1 0 13 1 3 2 4 2 0 nan 1 12 3 0 34 which i want to turn into thistrial measurement value 1 0 13 1 1 3 1 2 4 2 0 nan 2 1 12 3 0 34 how can i best do this i need this because i want to aggregate the data as instructed here but i cannot select my columns like that if they are in use as indices,['python'] +582589,how to calculate autocovariance in python i want to calculate autocovariance of 3 arrays x1 x2 and y which are all stationary random process is there any function in scipy or other library can solve this problem,['python'] +582604,graphing algorithm for many nodes i have been trying to develop a web based application to help in the graphing of nodes and their interactionsi have attempted to use the sigmajs with the force atlas extensionfor my simple tests few nodes the results are quite goodlooking however with an additional thousand nodes the result becomes quite a messis there any such way to make the result more view able easier on the eyesnot just 1 big blob how would i go about doing this are there any algorithms already writtenthat i may implement,['javascript'] +582671,python pandas convert dataframe to dictionary with multiple values i have a dataframe with 2 columns address and id i want to merge ids with the same addresses in a dictionaryimport pandas as pd numpy as npdf pddataframeaddress 12 a 66 c 10 b 10 b 12 a 12 a id aa bb cc dd ee ffasdfset indexaddressidto dictprint df address id0 12 a aa1 66 c bb2 10 b cc3 10 b dd4 12 a ee5 12 a ffprint as66 c bb 12 a ff 10 b ddwhat i want is for the duplicates to store multiple values like66 c bb 12 a aaeeff 10 b ccdd,['python'] +582689,fatal error c1010 stdafxh in visual studio how can this be corrected i compile the following code but i get a compile error in visual studio that i cannot understandinclude iostreamusing namespace stdint main int matchcount findresult long childpid string userinput blank string to be searched through string longstring the ppsh41 is a soviet submachine gun designed by georgi shpagin as an inexpensive simplified alternative to the ppd40 while userinputcomparewq reset variables for reuse matchcount 0 findresult 1 cout please enter a words to search for wq to exit prompts user for string to search for cin userinput takes user input if userinputcomparewq checks user input to see if they still wish to search for a string childpid fork if childpid 0 while findresult longstringlength findresult longstringfinduserinput findresult 1 userinputlength if findresult longstringlength matchcount cout there are matchcount instances of userinput in longstring endl else cout childpid 0 endl else cout user has chosen to exit exiting endl return 0the error readswordcountcpp57 fatal error c1010 unexpected end of file while looking for precompiled header did you forget to add include stdafxh to your sourcei do not believe i need a header file to run this code thank you for all your help in advance,['c++'] +582728,textview is not clickable on opengl curl view effect in my application i have requirement like thisi have number of data and i need to show that data on listview kind of layoutnow i have suppose total 6pages on each pages i want to show such datai have listed number of textview on each pagesuppose i have 7pages so i need to make book kind of layout for that i am using this code page curlwith this i am able to get such effectas mentioned in below imagenow my issue isas opengl is converting entire layout to bitmapi am not able to handle click event of textviewwhenever i click on textview on that time action down method is calledand offcourse it should be called as entire layout is converting to bitmap thus we cannot handle textview click eventfor making solution of this have googled and found some trick from this issuehere mentioned to make seperate layout for handeling click listenerbut not getting what exactly i have to doas i do not have any experience in openglso if any one have idea about this issueany one who can guide me handle click event,['android'] +582759,d3js auto fontsizing based on nodes individual radiusdiameter how can i have d3js automatically adjust fontsize for each node based on their individual radiusdiameteri use a style that allows automatic increase insize nodeappendtext attrdy 3em styletextanchor middle textfunctiond return dclassnamesubstring0 dr 3 stylefontsize 10px initial guessthis is what gives it increased size stylefontsize functiond return 2 dr 10 thisgetcomputedtextlength 10 px 10 px this effect removes the text from the smaller nodes i also have a zoom function that i can increase a dot that originally cover 12 px to cover my entire screencalld3behaviorzoomscaleextent1 200onzoom zoomis there a way i can automatically format nodefont individually to write at appropriate sizes so when zoomin the called nodefont will appear proportionate to nodesize vs a single fontsize fits all the right lists circles namesize i would love a working examples to learn from so at the image size the little green dot north of driving circle next to the p would have black unreadable words until we zoom in to see what is written on the circle the goal is to have proportionate readable font when zoomed in,['javascript'] +582798,change unique key together in mysql i have in my mysql table a unique key and i want to add to itunique key user id user idaccount idand i want to add another unique key user id user idaccount idpet id,['mysql'] +582826,jpa group by entity is this possible is possible to select data in jpa with grouping by referenced entityi mean i have two entities insurance and referenced manytoone vehicle insurance entity has validtill field and vehicle field of coursei would like to select vehicle and it is latest insurance the query below does not workselect thistinct vvehicle maxvvalidtill as lastvalidtill from trainsurance v group by vvehicle order by lastvalidtillthe query above fails with errorerror column travehicle1 id brand must appear in the group by clause or be used in an aggregate functionthis is because jpa adds all fields from referenced vehicle to query and not to group by is here something i do wrong or maybe it is just not possible to do thisedittrainsurance entityentitytablename tra insurances schemapublicsequencegeneratorname tra insurances seq sequencename tra insurances seq allocationsize 1public class trainsurance implements entityint serializable private static final long serialversionuid 1l id columnname id nullable false generatedvaluestrategy generationtypesequence generator tra insurances seq private long id notnull manytoone joincolumnnullable false name id vehicle private travehicle vehicle notnull columnname valid from nullable false private date validfrom columnname valid till nullable false private date validtill notnull manytoone joincolumnnullable false name id company private company company columnname policy no nullable true length 50 private string policynumber columnname rate nullable true precision 12 scale 2 private bigdecimal rate columnname thiscount percent nullable true private float thiscountpercent columnnullable true private string description public trainsurance public long getid return id public void setidlong id thisid id public travehicle getvehicle return vehicle public void setvehicletravehicle vehicle thisvehicle vehicle public date getvalidfrom return validfrom public void setvalidfromdate validfrom thisvalidfrom validfrom public date getvalidtill return validtill public void setvalidtilldate validtill thisvalidtill validtill public company getcompany return company public void setcompanycompany company thiscompany company public string getpolicynumber return policynumber public void setpolicynumberstring policynumber thispolicynumber policynumber public bigdecimal getrate return rate public void setratebigdecimal rate thisrate rate public float getthiscountpercent return thiscountpercent public void setthiscountpercentfloat thiscountpercent thisthiscountpercent thiscountpercent public string getdescription return description public void setdescriptionstring description thisdescription description override public int hashcode final int prime 31 int result 1 result prime result id null 0 idhashcode result prime result validfrom null 0 validfromhashcode result prime result vehicle null 0 vehiclehashcode return result override public boolean equalsobject obj if this obj return true if obj null return false if obj instanceof trainsurance return false trainsurance other trainsurance obj if id null if otherid null return false else if idequalsotherid return false if validfrom null if othervalidfrom null return false else if validfromequalsothervalidfrom return false if vehicle null if othervehicle null return false else if vehicleequalsothervehicle return false return true,"['java', 'sql']" +582839,java one line variable declaration in my java class i am declaring variable like this bigdecimal sumfeebilled new bigdecimal0 sumpaid new bigdecimal0 or we have to declare like this in multiple line bigdecimal sumfeebilled new bigdecimal0bigdecimal sumpaid new bigdecimal0which one we should follow,['java'] +582847,detected both log4joverslf4jjar and slf4jlog4j12jar on the class path preempting stackoverflowerror i have used xuggle library in my project to trans code the video from mp4 to flvi have used slf4j libraries also to support logging endimport comxugglemediatoolimediareaderimport comxugglemediatoolimediaviewerimport comxugglemediatoolimediawriterimport comxugglemediatooltoolfactorypublic class transcodingexample private static final string inputfilename evideofacebookmp4 private static final string outputfilename evideofacebookflv public static void mainstring args create a media reader imediareader mediareader toolfactorymakereaderinputfilename create a media writer imediawriter mediawriter toolfactorymakewriteroutputfilename mediareader add a writer to the reader to create the output file mediareaderaddlistenermediawriter create a media viewer with stats enabled imediaviewer mediaviewer toolfactorymakeviewertrue add a viewer to the reader to see the decoded media mediareaderaddlistenermediaviewer read and decode packets from the source file and and thispatch decoded audio and video to the writer while mediareaderreadpacket null here i am getting an error detected both log4joverslf4jjar and slf4jlog4j12jar on the class path preempting stackoverflowerror i have used both jar files as libraries in order to solve logging problemsdoes any one faced the same problemif so kindly write suggestion or solution to come out of this messthanks in advance,['java'] +582906,parallel implementations of std algorithms and side effects going through the standard documentation for stdtransform i noticed that until c11 the functor argument was required not to have side effects while from c11 onwards the requirement has been made less restrictive op and binary op shall not invalidate iterators or subranges or modify elements in the ranges seeand section 2534 of the standard the webpage on cppreferencecom mentions as well that the intent of these requirements is to allow parallel or outoforder implementations of stdtransformi do not understand then if this snippet of code is legal or not in c11stdvectorint v fill it with something v transformedint foo 0stdtransformvbeginvendstdback inserterv transformedfooconst int n int foo 1 return n2clearly if stdtransform is parallelised behind the scenes we will have multiple concurrent calls to foo 1 which is going to be ub but the functor itself does not seem to violate the requirements outlined in the standardthis question can be asked for other standard algorithms except i think stdfor each which explicitly states that the iteration is to be performed inorderdid i misunderstand something,['c++'] +583018,how to shuffle collage images using jquerycollageplus i am developing a website in which i am using jquerycollageplus plugin to make image collages i want to make shuffling images dynamically when click on shuffle button any one have solution for this or any other method to do this then kindly let me know here is my demo collage testhere is my codewindowloadfunction collagecollageplus targetheight 300 fadespeed slow effect default direction vertical allowpartiallastrow false collageremovewhitespacecollageplus htmlinput nameshuffl valueshuffle typebuttonsection stylewidth700px classcollage effectparent img srcsupportimagesedleadrible2png img srcsupportimagesedleadrible3png img srcsupportimagesedleadrible4png img srcsupportimagesedleadrible6png img srcsupportimagesedleadrible1pngsection,"['jquery', 'css']" +583032,how to get iframe width 100 in iphone portrait view basically i am having the same problem as here but because he never got a good answer i am reposting the questionso the problem is that only in iphone safari the width100 on the portrait view seems to be misbehaving and giving the iframe the landscape width and i cannot seem to figure out what is going on here i am using the correct viewportmeta nameviewport contentwidthdevicewidth initialscale1 userscalableyes and the site within the iframe can actually go way narrower than 320px and also has the same viewport defined i have read on one of the similar questions that this can be a factor so i am just clarifyingin the debugger i can see that before the url was added the iframes offsetwidth was 304px which is correct and after the load it was 588px which is correct for the landscape view but why it changed i have no idea the page within the iframe comes from a different domain so that could not effect it and the main page does not do anything with the iframes widththe iphone i am using is an iphone 5 ios 702ps please do not post any js answers where you resize the iframe manually on window resize i am currently looking for a non js fix and this is my last option that i plan to use also please do no post the media css answer were you set minwidth to 320px on iphone portrait view width that would not work for me for various reasons,"['iphone', 'css']" +583082,xamarinandroid buildsdeployments are very slow how to speed them up we have a large xamarinandroid project with two depending projects and a bunch of third party dlls doing a debug deployment without any changes onto a haxx86 emulator or a nexus 5 device is painfully slow 80 seconds for comparison the xamarinios version of the app deploys in under seven seconds onto a real deviceto test the deployment times i have also created a fresh xamarinandroid project which deploys in about four seconds when i add a depending project the deploy time goes up to seven seconds when i add a layout file to the depending project the deployment time increases to about ten secondsis it possible to speed the android build and deployment up with xamarin studio a big eclipse android projects is deployed rather quick in comparisonupdatejust running the installation build step takes about 40 secondstime xbuild tinstall bigappcsprojtime elapsed 0428526970about half the time is spend where the above command prints to consoletarget compiledex javasourcefiles javalibraries externaljavalibrariestool usrbinjava execution started with arguments xmx512m jar usersmynamelibrarydeveloperxamarinandroidsdkmac x86buildtools1700libdxjar nostrict dex outputobjdebugandroidbinclassesdex objdebugandroidbinclasseslibraryframeworksxamarinandroidframeworkversionscurrentlibmandroidplatformsandroid15monoandroidjarusersmynameprojectsbigappobjdebug library projects testflightbindingsjarstestflightlib 1 2jarusersmynameprojectsbigappobjdebug library projects androidsupportv4jarusersmynameprojectsbigappobjdebug library projects classesjarusersmynamelibrarydeveloperxamarinandroidsdkmac x86extrasgooglegoogle play serviceslibprojectgoogleplayservices liblibsgoogleplayservicesjarwhen i run the solution from xamarin studio this step happens twice once for the depending project and once for the main project i tried to reproduce this behavior on the console with applicationsxamarin studioappcontentsmacosmdtool v build configurationdebug t install bigappslnbut that only builds the main projectupdatei created a small demo project with very slow deployment time,['android'] +583107,log rotating with monolog in symfony2 i would like to know if there is any possibility to configure monolog in symfony2 to create a new log file every day for example 20131121prodlog,['php'] +583169,indicate that processorheavy js function is running gif spinners do not animate showing then hiding animated indicator spinner gifs are a good way to show a user that their action has worked and that something is happening while they wait for their action to complete for example if the action requires loading some data from a servers via ajaxmy problem is if the cause of the slowdown is a processorintensive function the gif freezesin most browsers the gif stops animating while the processorhungry function executes to a user this looks like something has crashed or malfunctioned when actually it is working jsbin examplenote the this is slow button will tie up the processor for a while around 10 seconds for me will vary depending on pc specs you can change how much it does this with the datareps attr in the html expectation on click the animation runs when the process is finished the text changes wed normally hide the indicator too but the example is clearer if we leave it spinning actual result the animation starts running then freezes until the process finishes this gives the impression that something is broken until it suddenly unexpectedly completesis there any way to indicate that a process is running that does not freeze if js is keeping the processor busy if there is no way to have something animated i will resort to thisplaying then hiding a static text message saying loading or something similar but something animated looks much more activeif anyone is wondering why i am using code that is processorintensive rather than just avoiding the problem by optimising it is a lot of necessarily complex rendering the code is pretty efficient but what it does is complex so it is always going to be demanding on the processor it only takes a few seconds but that is long enough to frustrate a user and there is plenty of research going back a long time to show that indicators are good for uxa second related problem with gif spinners for processorheavy functions is that the spinner does not actually show until all the code in one synchronous set has run meaning that it normally would not show the spinner until it is time to hide the spinner jsbin exampleone easy fix i have found here used in the other example above is to wrap everything after showing the indicator in settimeout function 50 with a very short interval to make it asynchronous this works see first example above but it is not very clean i am sure there is a better approachi am sure there must be some standard approach to indicators for processorintensive loading that i am unaware of or maybe it is normal to just use loading text with settimeout my searches have turned up nothing i have read 6 or 7 questions about similarsounding problems but they all turn out to be unrelatededit some great suggestions in the comments here are a few more specifics of my exact issuethe complex process involves processing big json data files as in js data manipulation operations in memory after loading the files and rendering svg through raphaeljs visualisations including a complex detailed zoomable world map based on the results of the data processing from the json so some of it requires dom manipulation some does noti unfortunately do need to support ie8 but if necessary i can give ie8 ie9 users a minimal fallback like loading text and give everyone else something modern,['javascript'] +583228,controlling vertical scrolling and horizontal swiping on a list in an ios web app with javascript i am creating a web application specifically targeted for phones primarily iphone but android wp are on the horizonone of the screens contains a scrolling list of items i would like the list to behave similarly to the builtin ios mail appin other wordsif the user touches the list and moves up or down the list scrolls verticallyif the user flicks up or down the list scrolls vertically with natural momentumif the user touches the list and moves only left the particular item slides to the left revealing a delete buttonimportantly the list should scroll or the item should slide but never bothso it is important to figure out what the users intention is which means i probably need to prevent any response until i figure out whether the user is moving her finger vertically or horizontallyby simply setting these css styles on the list containeroverflowy autowebkitoverflowscrolling touch i get 1 2 above so i need to figure out how implement 3my first thought was to implement something like this pseudocodecreate a touchstart event listener on the list container in the callback store the x and ycoordinates of the users starting touch positioncreate a touchmove event listener on the list container in the callback figure out how far the users finger has moved eg delta x and delta yif delta x and delta y are both less than 10 pixels do not do anything do not scroll the list or slide the item since we have not yet figured out whether the user plans to move updown or leftrightif either delta x or delta y are more than 10 pixels we can assume the user has moved far enough to express her intention if delta y delta x assume she is moving updown and allow the list to scroll but do not slide the item if delta x delta y assume she is moving leftright so we should allow the item to slide but not allow the list to scrolli expected that i would use eventpreventdefault in either the touchstart or touchmove to control when scrolling should begin egdivaddeventlistenertouchstart functione touchstart x etouches0pagex y etouches0pagey falsedivaddeventlistenertouchmove functione touchnow x etouches0pagex y etouches0pagey var dx touchstartx touchnowx dy touchstarty touchnowy if mathabsdx 10 mathabsdy 10 prevent scrolling epreventdefault else if mathabsdx mathabsdy 10 moving rightleft slide item else moving updown allow scrolling falsehowever this does not work regardless of how far you move the list never scrollsobviously i am misunderstanding what triggers the scrolling and what eventpreventdefault is supposed to do in this contextso is there a way to accomplish what i am afteri am hoping for a pure javascript solution so i understand it better but a jquery approach would be fine to i am definitely hoping to avoid a jquery pluginlibraryframework if at all possiblethanks in advance,"['javascript', 'jquery', 'ios']" +583257,getting the url parameters in an ejs template i am trying to create an ejs conditional based on a url parameter for example if the test parameter exists at localhost30pagetest then show a div else dont show itmy ejs template looks something like include header div classrowif title homepage title div include nav div div divdiv include footer is there a way to access the url parameters directly from the ejs file for example the title works fine is there something like reqquery i am also using express,['javascript'] +583266,fire event on carousel slide not slid event bootstrap 3 bootstrap 2 seems to work fine handling the slide event see this question with the following codemycarouselbindslide function e consolelogslide eventi cannot however get the same things to work in bootstrap 3 see this fiddle anyone know why,"['javascript', 'jquery', 'html']" +583292,using sklearns tfidfvectorizer transform i am trying to get the tfidf vector for a single document using sklearns tfidfvectorizer object i create a vocabulary based on some training documents and use fit transform to train the tfidfvectorizer then i want to find the tfidf vectors for any given testing document from sklearnfeature extractiontext import tfidfvectorizerselfvocabulary a list of words i want to look for in the documentssplitselfvect tfidfvectorizersublinear tftrue max df05 analyzerword stop wordsenglishselfvectfit transformselfvocabularydoc some string i want to get tfidf vector fortfidf selfvecttransformdocthe problem is that this returns a matrix with and rows where and is the size of my doc string i want it to return just a single vector representing the tfidf for the entire string how can i make this see the string as a single document rather than each character being a document also i am very new to text mining so if i am doing something wrong conceptually that would be great to know any help is appreciated,['python'] +583442,google analytics tracking code is not working i setup a google analytics account and i setup the website and got the analytics code which is script functionisogramigoogleanalyticsobjectririrfunction irqirqpushargumentsirl1new dateascreateelemento msgetelementsbytagnameo0aasync1asrcgmparentnodeinsertbefoream windowdocumentscriptwgoogleanalyticscomanalyticsjsga gacreate ua4x1 mydomaincom gasend pageview scripti pasted into the header of all my pages but analytics keeps saying tracking not installedi viewed and verified the source code is within the header of the home page and the code is there the site is built on classic asp defaultasp and i have several other sites setup in ga and they worked fine so i do not know why this is not working the code above was provided by ga can someone please tell me why this is not working,"['javascript', 'html']" +583452,package does not exist error in intellij i am trying to use the barbecue barcode printing library i have successfully added the library to intellij through project structure add library then i imported the packages and wrote the methods which gave me no error the packages were available in the classbut when i compile it gives me the errorerror package netsourceforgebarbecue does not existhow can this bei am coding in ubuntu is there any other place to which i have to add the librarythankstika,['java'] +583483,controller carousel required by directive ngtransclude cannot be found our team implemented a twitter bootstrap carousel for our front page everythings working fine for chrome and firefox however when we tested it in ie 8 the carousel images were broken and the error thrown in the ie console wascontroller carousel required by directive ngtransclude cannot be foundheres the code in haml for our carouselcarouselfeaturedtagsffdestroycarousel true interval 50slide imgsrc assetspathimgpicborapng alt dimmer caption boracay beach aklanslide imgsrc assetspathimgpicborapng alt dimmer caption boracay beach aklanslide imgsrc assetspathimgpicborapng alt dimmer caption boracay beach aklanslide imgsrc assetspathimgpicborapng alt dimmer caption boracay beach aklanour first approach was to destroy the carousel hence the ffdestorycarousel directive if the browser is ie 8 and utilized bowserjs for browser checking but still the script error still pops upany thoughts on why this kind of error is still happening in ie 8 and if their are possible workarounds for this,"['javascript', 'html']" +583564,foundation 5 upgrade layer must be a document node i am trying to upgrade my ruby on rails app from foundation 4 to the newlyreleased foundation 5 and the css switch is going relatively smoothly however i am running into a problem switching the javascript fileswhen i switch out the foundation 4 versions of the foundationminjs and modernizrjs files and then reload a page i get this weird js error in the consoleuncaught typeerror layer must be a document node foundationjsbody135 fastclick foundationjsbody135 fastclickattach foundationjsbody135 anonymous function foundationjsbody140 anonymous functioni do not even know what fastclick does but it appears to be included in foundation 5 and it is stopping foundation from loading that in turn is causing all of my foundationdependent js to fail as wellany help would be appreciated thank you,['ruby-on-rails'] +583590,should i use css thisabled pseudoclass or thisabled attribute selector or is it a matter of opinion i am trying to style a thisabled input i can usemyinputthisabled ormyinputthisabled is the attribute selector the modern css3 way and the way to go forward i used to use the pseudoclass but i cannot find any info on whether they are the old way and would not be supported or whether they are both equal and you can use whatever you like besti have no need to support older browsers it is an intranet application so is itattribute is newer and betterpseudoclass is still the way to gowhichever you like bestthere is a technical reason to use one over the other,['css'] +583693,how to use etag in web api using action filter along with httpresponsemessage i have a aspnet web api controller which simply returns the list of userspublic sealed class usercontroller apicontroller enabletag public httpresponsemessage get var userlist thisretrieveuserlist this will return list of users thisresponsemessage new httpresponsemessagehttpstatuscodeok content new objectcontentlistuserviewmodeluserlist new jsonmediatypeformatter return thisresponsemessage and an action filter attribute class enabletag which is responsible to manage etag and cache public class enabletag systemwebhttpfiltersactionfilterattribute private static concurrentdictionarystring entitytagheadervalue etags new concurrentdictionarystring entitytagheadervalue public override void onactionexecutinghttpactioncontext context if context null var request contextrequest if requestmethod httpmethodget var key getkeyrequest icollectionentitytagheadervalue etagsfromclient requestheadersifnonematch if etagsfromclientcount 0 entitytagheadervalue etag null if etagstrygetvaluekey out etag etagsfromclientanyt ttag etagtag contextresponse new httpresponsemessagehttpstatuscodenotmodified setcachecontrolcontextresponse public override void onactionexecutedhttpactionexecutedcontext context var request contextrequest var key getkeyrequest entitytagheadervalue etag if etagstrygetvaluekey out etag requestmethod httpmethodput requestmethod httpmethodpost etag new entitytagheadervalue guidnewguidtostring etagsaddorupdatekey etag k val etag contextresponseheadersetag etag setcachecontrolcontextresponse private static void setcachecontrolhttpresponsemessage response responseheaderscachecontrol new cachecontrolheadervalue maxage timespanfromseconds60 mustrevalidate true private true private static string getkeyhttprequestmessage request return requestrequesturitostring the above code create an attribute class to manage etag so on the first request it will create a new etag and for the subsequent request it will check whether any etag is existed if so it will generate not modified http status and return back to client my problem is i want to create a new etag if there are changes in my user list ex a new user is added or an existing user is deleted and append it with the response this can be tracked by the userlist variablecurrently the etag received from client and server are same from every 2nd request so in this case it will always generate not modified status while i want it when actually nothing changed can anyone guide me in this direction thanks in advance,['c#'] +583696,rubocop error class definition is too long ruby i am getting rubocop error class definition is too long 236100my class looks like belowclass someclassname include helpermodule attr accessor a b c methods endwhat might go wrongthe rubocop docs classlength says length of a class exceeds some maximum valuewhat does it mean,['ruby'] +583741,opencvpython dense sift opencv has very good documentation on generating sift descriptors but this is a version of weak sift where the key points are detected by the original lowe algorithm the opencv example reads something likeimg cv2imreadhomejpggray cv2cvtcolorimgcv2color bgr2graysift cv2siftkp siftdetectgraynonekpdes siftcomputegraykpwhat i am looking for is strongdense sift which does not detect keypoints but instead calculates sift descriptors for a set of patches eg 16x16 pixels 8 pixels padding covering an image as a grid as i understand it there are two ways to do this in opencvi could divide the image in a grid myself and somehow convert those patches to keypointsi could use a gridbased feature detectorin other words i would have to replace the siftdetect line with something that gives me the keypoints i requiremy problem is that the rest of the opencv documentation especially wrt python is severely lacking so i have no idea how to achieve either of these things i see in the c documentation that there are keypoint detectors for grid but i do not know how to use these from pythonthe alternative is to switch to vlfeat which has a very good dsiftphow implementation but means that i will have to switch from python to matlabany ideas thanks,['python'] +583744,android 44 kitkat api level 19 is not listed in android sdk manager as its apparent that android 44 kitkat api level 19 is now availablei just want to update to the latest api level and then change the androidtargetsdkversion19in the manifest filei clicked on android sdk manager using eclipse java ee ide for web developers having version helios service release 2the android sdk manager opened but i did not found android api level 19 in the list of packagesfurther i saw other so posts mentioning that if you clear the cache under tools options in android sdk manager and reload the android sdk manager then you will get this api listed in packagesi did the same but no luckthe screenshot below,['android'] +583845,owin unauthorised webapi call returning login page rather than 401 how do i configure my mvcwebapi project so that a webapi method called from a razor view does not return the loginpage when its unauthorisedits a mvc5 application which also has webapi controllers for calls via javascriptthe two methods belowrouteapihomelatestproblems httpgetpublic listvmlatestproblems latestproblems something hererouteapihomemylatestproblemshttpgetauthorizeroles memberpublic listvmlatestproblems mylatestproblems something thereare called via the following angular codeangularmoduleappworshipcontrollerlatest scope http function scopehttp var urlbase baseurl apihomelatestproblems httpgeturlbasesuccessfunction data scopedata data errorfunction data consolelogdata httpgetbaseurl apihomemylatestproblems successfunction data scopedata2 data errorfunction data consolelogdata so i am not logged in and the first method successfully returns data the second method returns in the success function data which contains the equivalent of a login page ie what you would get in mvc if you requested a controller action which was stamped with authorize and you werent logged ini want it to return a 401 unauthorized so that i can thisplay different data for users based on if they are logged in or not ideally if the user is logged in i want to be able to access the controllers user property so i can return data specific to that memberupdate since none of the suggestions below seem to work anymore changes to identity or webapi ive created a raw example on github which should illustrate the problem,['c#'] +583855,hibernate session thread safety i know that sessions are not thread safe my first question is it safe to pass an entity to another thread do some work to it then pass it back to the original thread and updatepublic class example1 mydao dao public void dowork myentity entity daogetentity runnable job new jobentity thread t new threadjob trun tjoin daomergeentity my second question is it safe to new up an entity in one thread and save it in anotherpublic class example2 mydao dao public void dowork myentity entity new entity new threadnew jobdao entityrun public class job implements runnable private mydao dao private myentity entity override public void run daosaveentity edit i forgot to mention that the entities are specifically configured for eager loading,['java'] +583948,gson get json value from string i trying to parse the json string test 10 and to get the value 10 with the gson library my code looks like thisstring myjsonstring test 10jsonobject jobj new gsonfromjsonmyjsonstring jsonobjectclastring result jobjgettesttostringsystemoutprintlnresultmy result looks like this 10 but i would need just 10 without the quotes how can this be archieved,['java'] +583951,bug createwindowsurface failed egl bad alloc i have one application on google play for counting down numbers and letters in this application i have the following activities google sigin archivements and admob service i use google analitics and acra for error reporting i do not use glsurfaceview but i use acra one or two times a day which gives me these errors javalangruntimeexception createwindowsurface failed egl bad allocat androidviewhardwarerendererglrenderercreatesurfacehardwarerendererjava763at androidviewhardwarerendererglrenderercreateeglsurfacehardwarerendererjava663at androidviewhardwarerendererglrendererinitializehardwarerendererjava502at androidviewviewrootimplperformtraversalsviewrootimpljava1325at androidviewviewrootimplhandlemessageviewrootimpljava2467at androidoshandlerthispatchmessagehandlerjava99at androidoslooperlooplooperjava137at androidappactivitythreadmainactivitythreadjava4424at javalangreflectmethodinvokenativenative methodat javalangreflectmethodinvokemethodjava511at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava784at comandroidinternaloszygoteinitmainzygoteinitjava551at dalviksystemnativestartmainnative methoddoes anyone know what happened i do not use surfaceview can anyone help me,"['java', 'android']" +583969,android adview missing required xml attribute adsize my head almost exploded today because the entire day i tried to solve the problem with my adview from admob i am getting an error mentioned in the title i googled through 3 pages but nothing same error whatever i do this is my xml filexml version10 encodingutf8linearlayout xmlnsandroid androidlayout widthmatch parent androidlayout heightmatch parent androidbackgroundf androidorientationvertical imageview androidididimageview1 androidlayout widthmatch parent androidlayout height0dp androidlayout weight048 androidsrcdrawablebutters10 relativelayout androidlayout widthmatch parent androidlayout height42dp button androidididprev androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentlefttrue androidlayout alignparenttoptrue androidbackgrounddrawableprev button androidididnext androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentrighttrue androidlayout alignparenttoptrue androidbackgrounddrawablenext relativelayout comgoogleadsadview xmlnsads androidididadview androidlayout widthwrap content androidlayout heightwrap content adsloadadoncreatetrue appadsizebanner appadunitid comgoogleadsadviewlinearlayouti tried to change the app keyword to ads but the problem still shows upanother thing is i actually want to add the same ad this the same unitid to more than one activity i added this exactly code to my first activity xml file and everything works fine but in the second activity it does not work at all thank you for any help,['android'] +584001,how to log everything into a file using rotatingfilehandler by using loggingconf file i am trying to use rotatinghandler for our logging purpose in python i have kept backup files as 500 which means it will create maximum of 500 files i guess and the size that i have set is 20 bytes not sure what is the recommended size limit isif i run my below code it does not log everything into a file i want to log everything into a file usrbinpythonimport loggingimport logginghandlerslog filename testinglog set up a specific logger with our desired output levelmy logger logginggetloggeragentlogger add the log message handler to the loggerhandler logginghandlersrotatingfilehandlerlog filename maxbytes20 backupcount100 create a logging formatformatter loggingformatterasctimes names levelnames messageshandlersetformatterformattermy loggeraddhandlerhandlermy loggerdebugdebug messagemy loggerinfoinfo messagemy loggerwarnwarn messagemy loggererrorerror messagemy loggercriticalcritical message log some messagesfor i in range10 my loggererrori d ithis is what gets printed out in my testinglog file 20131122 125934782 agentlogger warning warn message20131122 125934782 agentlogger error error message20131122 125934782 agentlogger critical critical message20131122 125934782 agentlogger error i 020131122 125934782 agentlogger error i 120131122 125934783 agentlogger error i 220131122 125934783 agentlogger error i 320131122 125934783 agentlogger error i 420131122 125934783 agentlogger error i 520131122 125934783 agentlogger error i 620131122 125934784 agentlogger error i 720131122 125934784 agentlogger error i 820131122 125934784 agentlogger error i 9it does not print out info debug message into the file somehow any thoughts why it is not working outand also right now i have defined everything in this python file for logging purpose i want to define above things in the logging conf file and read it using the fileconfig function i am not sure how to use the rotatingfilehandler example in the loggingconf fileupdatebelow is my updated python code that i have modified to use with logconf file usrbinpythonimport loggingimport logginghandlersmy logger logginggetlogger my loggerconfigfileconfiglogconfmy loggerdebugdebug messagemy loggerinfoinfo messagemy loggerwarnwarn messagemy loggererrorerror messagemy loggercriticalcritical message log some messagesfor i in range10 my loggererrori d iand below is my logconf file loggerskeysroothandlerskeyslogfileformatterskeyslogfileformatterlogger rootleveldebughandlerslogfilelogger zkagentloggerleveldebughandlerslogfilequalnamezkagentloggerpropagate0formatter logfileformatterformatasctimes name12s levelnames messageshandler logfileclasshandlersrotatingfilehandlerlevelnotsetargstestinglog20100formatterlogfileformatterbut whenever i compile it this is the error i got on my console python logtest3pytraceback most recent call last file logtest3py line 6 in module my loggerconfigfileconfiglogconfattributeerror logger object has no attribute configany idea what wrong i am doing here,['python'] +584073,detect hard taps anywhere on iphone through accelerometer i am trying to detect the taps which could be anywhere on iphone not just iphone screen here is a link which shows that it is possiblebasically what i want to do is send an alert if user taps 3 times on iphone while the phone is in his pocketwhat i have achieved is that i can detect the 3 taps but i also get the false alerts as well in these cases 1 if user walking 2 waving his phone 3 running i need to just check if user has hit his iphone 3 timeshere is my code voidaccelerometeruiaccelerometer accelerometer didaccelerateuiacceleration acceleration if handmodeon no ifpocketflag no return float accelz 00 float accelx 00 float accely 00 accelx accelerationx kfilteringfactor accelx 10 kfilteringfactor accely accelerationy kfilteringfactor accely 10 kfilteringfactor accelz accelerationz kfilteringfactor accelz 10 kfilteringfactor selfztext nsstring stringwithformat01f accelz ifaccelz senstivity floatvalue timerflag accelz senstivity floatvalue timerflag accelx senstivity floatvalue timerflag accelx senstivity floatvalue timerflag accely senstivity floatvalue timerflag accely senstivity floatvalue timerflag timerflag false addvalueflag true timer nstimer scheduledtimerwithtimeinterval15 targetself selectorselectortimertick userinfonil repeatsyes ifaddvalueflag if selfxswitchon nslogx switch is on selfaccarray addobjectnsnumber numberwithfloataccelx if selfyswitchon nslogy switch is on selfaccarray addobjectnsnumber numberwithfloataccely if selfzswitchon nslogz switch is on selfaccarray addobjectnsnumber numberwithfloataccelz voidtimerticknstimer timer1 timer1 invalidate addvalueflag false int count 0 forint i 0 i selfaccarraycount i ifselfaccarray objectatindexi floatvalue senstivity floatvalue selfaccarray objectatindexi floatvalue senstivity floatvalue count self playalarmbeep1 filetypemp3 ifcount 3 self playalarm06 alarm auto rapid beeping 1 filetypecaf self showalert timerflag true selfaccarray removeallobjects return selfaccarray removeallobjects timerflag trueany help will be really appreciatedthanks,"['ios', 'iphone', 'objective-c']" +584205,add code to package private library method i have a library class with a package private method directly overriding this method by a subclass is no option is there any way no matter how ugly to execute own code when this package private method is called from inside the library eg using aspectjhere is a simplified example of the class the packageprivatemethod actually is not invoked directly but from native codepublic libclass public libclass packageprivatemethod void packageprivatemethod here i want to execute additional code,['java'] +584237,fabricjs after object move programmatically its not selectable on its new position i have tried to move the object programmatically and get success but after the object is moved by programmatic way its not able to select the object by selecting the object current position still the object is selectable from by its old position i have tried with canvascalcoffset still its not workinghow can i make the object selectable in its current position the code i have used as followsjavascript var canvasnew fabriccanvascanvas canvasaddnew fabricrect left100 top 100 width 75 height 50 fill white stroke black strokewidth 3 padding 10 selectable true function changeposition canvasitem0setleft300 canvasrenderall canvascalcoffsethtmldivcanvas idcanvas width400 height400 styleborder1px solid reddivinput typebutton onclickchangeposition valuechange possitionjsfiddlesteps to reproduce the errorclick the change position buttontry selecting the rectangle on its current position and move to the cursor to the plave where the object was previously there you will be able to select the object,['javascript'] +584257,collision detection between images rotated using css animations i am using css animations and jquery to move cars in a crossroads top point of view to simulate a driving license quiz the user has to choose the crossing order by clicking over the carssample image each car has properties and an animation like this for example blue car turning right different from imageautob left 320px top 150px webkittransform rotate180deganimated autob webkitanimationname moveb webkitanimationfillmode forwardswebkitkeyframes moveb 30 left 260px top 150px webkittransform rotate180deg 60 left 214px top 120px webkittransform rotate270deg 100 top 30px left 214px webkittransform rotate270deg the thing i am not figuring out is how can i detect if two cars collide since they are rotated turningplay button functionplayonclick playfunction play autoremoveclaselected incrocioaddclassanimated interval setintervalcrash1crash function only work with red and green cars collision because they do not rotatefunction crash var autoa autoaposition var autob autobposition var autoc autocposition var top1 autoatop10 var top2 autoatop10 var left1 autoaleft10 var left2 autoaleft10 if top1 autoctop top2 autoctop left1 autocleft left2 autocleft consolelogboom incrocioremoveclassanimated alertboom i 1 carsarray clearintervalinterval is there an easy way to detect any kind of collision between every image that has class autoi also thought about calculating every point of the rectangle and checking if any of them is inside an other rectangle car however i can only get the topleft point and not the othersany solutionsthanks in advance,"['javascript', 'jquery', 'css']" +584290,tomcat in idea war exploded server is not connected deploy is not available i am trying this tutoial i created new project and ran it tomcat started but then nothing happened i can manually open in browser httplocalhost8080 and see the tomcat home page it means server can be started however i cannot open indexjsp here is my screen after startscreenshotas you can see the project is running but no info about passed environment variables no logsi use tomcat 7027idea 1216on opensuse 122my tomcat home folder is usrsharetomcatthere was a problem idea could not copy conf files from usrsharetomcatconf to homelocointellijidea12systemtomcatconfi executed chmod 7 in usrsharetomcat and the problem gone also i changed the way how tomcat is startedit was default valueusrsharetomcatbincatalinash runi changed tousrsharetomcatbincatalinash startall other steps are done in accordance to tutorial,['java'] +584331,sql server ce and visual studio 2013 so we now know that sql server ce is no longer supported with visual studio 2013 we can get some access to it via the sql server ce toolbox addin but this does not fix the fact that a data provider is not included and thus we can no longer use sql server ce with entity framework etc i have not yet found an explanation from ms as to why this is now missing but i have accepted it for now and am looking for ways to move on my question is what is the best migration path for this i have been using datafirst entity framework with sql server ce and deploying small websites that use a small sdf file for the database and updates are simple to deploy just copy the file over sql server express would not work this way for desktopwpfwinforms apps i imagine this is even more confusing as the inprocess sql server ce database was a great fit for small desktop applications,['.net'] +584372,is it possible for a type to have alignment requirements other than nbyte alignment for example consider the followingassume that int is 4byte aligned and long is 8byte alignedstruct example int a long b int cthe obvious way for the compiler to lay this out in memory would beapbcp with the whole structure having an 8byte alignmentp refers to a byte of paddinga refers to a byte of ab refers to a byte of bc refers to a byte of cin this case sizeofexample is 24but another way of doing it would be the followingabc with the whole structure having alignment such that the address of the starting byte mod 8 4 not sure how to say this more succinctlyin this case there is no padding needed so you save 8 bytes per instancemy question is are compilers allowed to do thisby the standard do they actually do this i have always seen alignment thiscussed simply in bytes,['c++'] +584405,start index at 1 when writing pandas dataframe to csv i need the index to start at 1 rather than 0 when writing a pandas dataframe to csv heres an examplein 1 import pandas as pdin 2 result pddataframecount 83 19 20in 3 resultto csvresultcsv index labelevent id which produces the following outputin 4 cat resultcsvevent idcount083119220but my desired output is thisin 5 cat result2csvevent idcount183219320i realize that this could be done by adding a sequence of integers shifted by 1 as a column to my data frame but i am new to pandas and wondering if a cleaner way existsthanks,['python'] +584589,clarifying the difference between rowlevel lock in innodb engine and tablelevel lock in myisam engine in mysql database let us say that i have two users trying to reach a table in the database called comments in the following orderuser1 is making and update for a record with id 10update comments set commenthello world where id10 user2 is making a select for all rows of the same table comments select from commentsi want to thiscuss the difference between the following casesif the tables engine is myisam the update query will lock thewhole table which will queue the select query until the update ofthe row is finished and then it will be executed which will stop anyuser from asking anything from this table until the update isfinishedif the tables engine is innodb the update query will lock the updated rowi want to know how does this lock affect the select queryi mean if the select ask the database for the whole records of the comments table and found one of them id 10 is locked does the database queue the select query again until the updated is finishedif yes then what is the difference between the two enginesif no i want to say that i have the same situation above in my website and even i changed my tables engines from myisam to innodb but the problem of queuing any requests when there is an update or insert query still occurredany explanation for this situation will be so helpful thank you in advance,"['mysql', 'sql']" +584609,c wrapping types for semantic it has been a long time since my last use of c coming back from java and python i have a question about good practices on ci wanted to keep a semantic code about some really simple objects let us say we have objects tag and file which both only are stdstring and a class tagmanager which contains several functions using tags and filesmy question is is it better to create a custom type representing these trivial objects or to use them directly for what they areto be more specific i have could have one of those definitions for a functiontagiterable myfunctiontag tag file filestdvectortag myfunctiontag tag file filestdvectorstdstring myfunctionstdstring tag stdstring filei prefer the first solution because i like to keep a semantic code on the other hand doing it requires the user to check what these types are so it reduce the simplicity of usei also read on another question thou shalt not inherit from stdvector do not produce new entities just to make something to look betterso what do you do in such situation what does the c philosophy recommend to do,['c++'] +584664,jquery get table id by click in td i have a tr in a table header that contains several input fields is there a way that by click on one of these input fields i can get the id of the parent table my tr looks like this table idtableid thead tr thinput typetext nameinput1 idinput1 th thinput typetext nameinput2 idinput2 th thinput typetext nameinput3 idinput3 th tr thead tbody tbodytablethanks for any help with this tim,['jquery'] +584675,how to resolve you need to have ruby and sass installed and in your path for this task to work warning i am in the process of setting up a new mac for work i have installed grunt grunt cli globally then i did a npm install inside a project folder to install all dependencies no problems so far but as soon as i try to run the sassthist task i get this warning warning you need to have ruby and sass installed and in your path forthis task to work more info use force to continuewhat i understand is that i need to have ruby and sass installed on a more global level for this task to run as i am still pretty new to working with the terminal i did a quick search to find out what path is seems like its some system path that can be changed where important data is stored does this mean i can simply do a sudo grunt install contribsass g to resolve the issue and what about ruby a i always thought its already installed on os x,['ruby'] +584767,python how to combine two matrices in numpy new to python struggling in numpy hope someone can help me thank youfrom numpy import a matrix10 20 30 40 b matrix50 60c matrix10 20 30 40 50 60print aaprint bbprint ccresultsa 1 2 3 4b 5 6c 1 2 3 4 5 6question how to use a and b to generate c like in matlab cab thank you so much,['python'] +584790,css drop down menu on mobile how to get around hover i have had a search and i could not find anything also it is my first time using the site so hope it has not been asked i have run into a situation i am by no means an experienced website maker i am learning as i go i have a css drop down menu that works fine on desktop browsers when i get into the realm of mobile i encounter a problem namely that hoverdoes not work obviouslyi found this but i cannot get the ruddy thing to work the page in question i am applying it to is here i really cannot work this out and its driving me absolutely batty any help would be really appreciated,"['javascript', 'html', 'css']" +584803,changing the background color of a button in kivy i am new to kivy and having trouble specifying the background color of a button heres my simple example custombuttonpyfrom kivyapp import appfrom kivyuixwidget import widgetclass mywidgetwidget passclass custombuttonappapp def buildself return mywidgetif name main custombuttonapprunand the accompanying kv file custombuttonkvkivy 172mywidget canvas color rgb 093 093 093 rectangle pos selfpos size selfsize button center selfparentcenter font size 14 height 28 background color 10 00 00 10 text i am a buttoni am sure i am missing something obvious but i have been messing with this for over an hour now and getting nowhere the button seems to get colored a hint of very dark redis this not the way to specify the background color for a button in kivythanks,['python'] +584832,most efficient way to solve a system of linear equations i have an n x n symmetric matrix a and a n x 1 vector b basically i just need to solve ax b for x the issue is that a is going to potentially be massive so i am looking for the most efficient algorithm for solving linear equations in c i looked over the eigen library apparently it has an svd method but i have been told it is slow solving xinverseab also seems like it would be suboptimal is ublas faster are there any more efficient methods thanks edit matrix a is positive definite and not sparse,['c++'] +584836,uidatepicker bug uicontroleventvaluechanged after hitting minimum internal i have run into a weird effect that sure looks like a bug in ios7 but often in the past when i have thought i found a bug in apples apis it has turned out to be my own misunderstandingi have a uidatepicker with datepickermode uidatepickermodecountdowntimer and minuteinterval 5 i initialize the duration to 1 hour and present it to the user where it appears as a twocolumn picker with hours and minutes so far so goodthe user is thinking 20 minutes and so scrolls the hour column to 0 at this point the picker reads 0 hours and 0 minutes and ios7 is not cool with that so it automatically scrolls the minute wheel to 5 my uicontroleventvaluechanged handler gets invoked and the countdownduration reads 5 minutes still goodnow the user grabs the minute wheel and drags it to 20 and my uicontroleventvaluechanged handler does not get called badif i have some other event in the ui check the date picker at this point i do see the countdownduration is set to 20 but i had no way of knowing that the user changed it at the moment it was changed this is very repeatable it always happens on the first change after the picker refuses to be set to 0 advancing itself to 5 minutesnote that this is in ios7 it does not occur in ios6 perhaps because the picker there is perfectly content to be set to 0 minutesso am i missing something here or is this a genuine bug in ios7 and in the latter case does anybody know a workaround better than having some timer periodically check the current interval,['ios'] +584896,find all records which have a count of an association greater than zero i am trying to do something that i thought it would be simple but it seems not to bei have a project model that has many vacanciesclass project activerecordbase has many vacancies dependent destroyendi want to get all the projects that have at least 1 vacancyi tried something like thisprojectjoinsvacancieswherecountvacancies 0but it sayssqlite3sqlexception no such column vacancies select projects from projects inner join vacancies on vacanciesproject id projectsid where projectsdeleted at is null and countvacancies 0,"['sql', 'ruby-on-rails']" +584906,angularjs have method return synchronously when it calls http or resource internally is there a way to wait on a promise so that you can get the actual result from it and return that instead of returning the promise itself i am thinking of something similar to how the c await keyword works with taskshere is an example of why i would like to have a method like canaccess that returns true or false instead of a promise so that it can be used in an if statement the method canaccess would make an ajax call using http or resource and then somehow wait for the promise to get resolvedthe would look something like thisscopecanaccess functionpage var resource resourceapiaccesspage var result resourcegetpage page how to await this and not return the promise but the real value return resultcanaccessis there anyway to do thisthanks,['javascript'] +584924,translatez percentages css 3d transforms when i try to set percentages in translatez like thistransformtranslatez100it does not work it also does not work with viewport relative vh or vw is there some way to do this i understand that i can simply set it with javascript but i have many of these elements in a certain class including ones that are added later dynamically with javascript it would be much more convenient to do something in css i saw something which seemed like a duplicate but i would like a way that does not have to have multiple elements to fix it apart from appending to the style element that is,"['javascript', 'html', 'css']" +584926,htmlphp form input as array i got a form like thisforminput typetext classformcontrol placeholdertitel namelevelslevelinput typetext classformcontrol placeholdertitel namelevelsbuild timeinput typetext classformcontrol placeholdertitel namelevelslevelinput typetext classformcontrol placeholdertitel namelevelsbuild timeformwhat i would like to have as post output is an array likearray 1 array level 1 build time 123 2 array level 2 build time 456 i know i could do something like namelevels1build time and so on but since these elements get added dynamically it would be hard to add an index is there any other wayeditas suggested i changed my form i also included my whole html now because i think i am missing something here my html nowdiv classformgroup label classcolmd2namezb 1label div classcolmd10 input typetext classformcontrol placeholdertitel namelevelslevel div label classcolmd2bauzeitin sekundenlabel div classcolmd10 input typetext classformcontrol placeholdertitel namelevelsbuild time divdivdiv classformgroup label classcolmd2namezb 1label div classcolmd10 input typetext classformcontrol placeholdertitel namelevelslevel div label classcolmd2bauzeitin sekundenlabel div classcolmd10 input typetext classformcontrol placeholdertitel namelevelsbuild time divdivthe output i get now islevels array 0 array level 1 1 array build time 234 2 array level 2 3 array build time 456 edit 2as suggested in your edit i edited my form and moved the square brackets to the end of the name the output i get now islevels array level array 0 1 1 2 build time array 0 234 1 456 i guess that would kinda work but it still looks complicated no better way,"['php', 'html']" +584949,how to align linearlayout to vertical center i am tyring to align linearlayouts vertical center which shows following pic skycolor border to delete buttons vertical centerso i set gravity of idgroupnumbers to center verticalbut no changed how to align idgroupnumbers to buttonss centerxml version10 encodingutf8linearlayout xmlnsandroid androidorientationhorizontal androidlayout widthmatch parent androidlayout heightmatch parent linearlayout androidididgroupnumbers androidorientationhorizontal androidgravitycenter vertical androidlayout weight07 androidlayout widthwrap content androidlayout heightwrap content linearlayout androidorientationhorizontal androidlayout weight1 androidlayout widthwrap content androidlayout heightwrap content textview androidididtxtselected01 androidtext00 androidtextsize30dp androidgravitycenter horizontal androidlayout weight1 androidlayout widthwrap content androidlayout heightwrap content linearlayout linearlayout androidorientationhorizontal androidlayout weight1 androidlayout widthwrap content androidlayout heightwrap content textview androidididtxtselected02 androidtext00 androidtextsize30dp androidgravitycenter horizontal androidlayout weight1 androidlayout width0dp androidlayout heightwrap content linearlayout linearlayout button androidididbtn deletenum androidtextdelete androidtextsize20dp androidlayout weight02 androidlayout widthwrap content androidlayout heightwrap contentlinearlayout,['android'] +584962,threejs issues application suddenly wont work on chrome old code wont work with new threejs library i wrote a few threejs r48 applications a while back and they have been working fine for up until a few weeks when i found they no longer work on chromehere are the first few error messageswebgl invalid operation getattriblocation program not linked skywheelhtml18webgl invalid operation getuniformlocation program not linked skywheelhtml1could not initialise shadervalidate status false gl error 1282 threejs35529webgl invalid operation getuniformlocation program not linked it still works fine with firefoxso i downloaded the latest version of threejs and when i use it instead of the old version i get this message and it does not work this is on firefox215032679 typeerror material is undefined filethreejs23513i was just hoping someone went though this type of thing recently and can save me some time fixing these problems,['javascript'] +585005,reactive cocoa uitextviews rac textsignal does not get called when programmatically setting text i am implementing a chat ui and using reactive cocoa to adjust the chat bubbles size as the user types currently i am updating the uis layout based on the textviews rac textsignal everythings working great except for one bit when the user sends the message i programmatically clear the textfield inputtextviewtext but the textviews rac textsignal does not activate i hear this is a feature with reactivecocoa but whats the proper way to build this do i need to have an nsstring holding the currentlytypedstring and drive the ui changes when that string updates,"['ios', 'objective-c']" +585018,how to configure all c project in a solution i have a solution which contains a lot of c projects how can i change the configuration of all projects very quickly like i want to change the output folder from bin to mybin i know c property sheet can do the similar thing but c does not have property sheet,['c#'] +585040,how to filter junit tests that are called from eclipse by source path assuming that i have a set of source folders in an eclips projectmyproject basesrcimpl basesrctest commonsrcapi commonsrctest commonsrcjunitnote that these are not packages they are source folders inside each one there is a package hierarchy which can be just the same let us say if i have a class comfoomyprojectdosomething in the basesrcimpl folder i might have a test called comfoomyprojectdosomethingtest in the basesrctest folder and maybe comfoomyprojectdosomethingunittest in another source folder under same package hierarchywhat i need to do is run all tests that are under certain source folders maybe all that are in a junit folder but none from the test folder this works fine from ant with the junit search patterns for exampleinclude namesrcjunit however i want to be able to have exactly the same run configurations from eclipse without having to call ant since there are already many projects packages and thousands of test classes i am looking for a lazy way to get this done that means without having to change project structures or having to mantain complex test suitesone approach i have tried is to use the orgspringframeworkcoreiosupportpathmatchingresourcepatternresolver used by classpathsuite but looking for resources in classpath always looks at the merged source folders in one single classes location so i am not able to filter anymore at the level i intend to do iti am looking for two ways of doing it1 filter using some testsuite2 filter using some junit runner plugin in eclipse is there any that can do what i needthanks,['java'] +585069,how do i read a maven dependency tree i have servletapi version 25 as provided scope in pomxml here is part of the dependencytree output of my project what does version managed from 23 scope managed from compile meaninfo commonsloggingcommonsloggingjar11compileinfo javaxservletservletapijar25provided version managed from 23 scope managed from compiledoes that mean there is some transitive dependency on version 23 on my classpath my war file does not have servletapi jar at all but i do use old version of spring 254 i suspect the spring framework depends on servletapi 23,['java'] +585133,how to change default aspnet mvc web api media formatter i have a web api project that returns some product data it negotiates the return type correctly depending on the accept header jsonxml of the request the problem is if no accept header is specified it returns json but i want it to return xml by default how do i change the content negotiation defaults in globalasax,['c#'] +585287,java 8 type annotations and jsr 308 i have installed the last jdk 8 b116 but i noticed that i cannot use type annotationsfor example reading the java tutorial if i writestring str nullstring mystring nonnull string strortest st new interned testthe compiler give me the following errorannotation type not applicable to this kind of declarationnow it works before using a type annotations we must annotate the annotation with targetelementtypetype use look at the comments below i also do not understand if the annotations like nonnull interned etc will beinserted in the jdk or if we have to download the checker framework,['java'] +585305,how to make argsort result to be random between equal values say you have a numpy vector 031 and you run argsortyou will get 02341 but all the ones are the samewhat i want is an efficient way to shuffle indices of identical valuesany idea how to do that without a while loop with two indices on the sorted vectornumpyarray031argsort,['python'] +585341,use of target in picasso on adapter im having big troubles using a target inside an adapter im confused about the documentation on the codeobjects implementing this class must have a working implementation of link equalsobject and link hashcode for proper storage internally instances of this interface will also be compared to determine if view recycling is occurring it is recommended that you add this interface directly on to a custom view type when using in an adapter to ensure correct recycling behaviorim trying to use the target in this way class customtarget implements target private imageview imageview public customtargetimageview imageview thisimageview imageview override public void onbitmaploadedfinal bitmap bitmap picassoloadedfrom from imageviewsetimagedrawablenew roundedavatardrawablebitmap override public void onbitmapfaileddrawable errordrawable imageviewsetimagedrawableerrordrawable override public void onprepareloaddrawable placeholderdrawable imageviewsetimagedrawableplaceholderdrawable override public boolean equalsobject o return imageviewequalso override public int hashcode return imageviewhashcode overridepublic view getviewint position view v viewgroup parent roundedavatardrawable r new roundedavatardrawablebitmapfactorydecoderesourcemcontextgetresources rdrawableic avatar seahorse imagecachecontrollerwithmcontextgetpicassoloadmembergetpicture urlresize100 100centercropplaceholderrerrorrintonew customtargetviewholderivavatarit is does not work and the images change between each others randomly,['android'] +585400,cordova xcode build failed permission denied i am trying to build an ios app using xcode and cordova however i keep getting this error messagecordovalibcopywbuildstepsh permission deniedhas anyone overcome this problem before,['ios'] +585551,using npgsql 12 and ef 6 together have anyone succeeded with it i am trying to create a small poc for my boss about the hybrid of npgsql 12 and ef6created a new project on visual studiocreated a sample databasecreated the corresponding classes and the dbcontextyet whenever i try and use ef to access the database i receive the folowing errorthe instance member of the entity framework provider type npgsqlnpgsqlfactory npgsql version20120 cultureneutral publickeytoken5d8b90d52f46fda7 did not return an object that inherits from systemdataentitycorecommondbproviderservices entity framework providers must inherit from this class and the instance member must return the singleton instance of the provider this may be because the provider does not support entity framework 6 or later see for more informationi know that it should be supported for quite some time now however i cannot seem to get it to workmy appconfig file looks like thisxml version10 encodingutf8configuration configsections for more information on entity framework configuration visit http gomicrosoftcomfwlinklinkid237468 section nameentityframework typesystemdataentityinternalconfigfileentityframeworksection entityframework version60 cultureneutral publickeytokenb77a5c561934e089 requirepermissionfalse section nameentityframework typenpgsqlnpgsqlfactory npgsql version20120 cultureneutral publickeytoken5d8b90d52f46fda7 configsections startup supportedruntime versionv40 skunetframeworkversionv45 startup entityframework defaultconnectionfactory typenpgsqlnpgsqlfactory npgsql parameters parameter valuev110 parameters defaultconnectionfactory providers provider invariantnamesystemdatasqlclient typesystemdataentitysqlserversqlproviderservices entityframeworksqlserver provider invariantnamenpgsql typenpgsqlnpgsqlfactory npgsql providers entityframework systemdata dbproviderfactories add namenpgsql data provider invariantnpgsql descriptiondata provider for postgresql typenpgsqlnpgsqlfactory npgsql dbproviderfactories systemdata connectionstrings add namecoolestpgsoft connectionstringserver127001port5432databasecoolestpgsoftuser idpostgrespassword providernamenpgsql connectionstringsconfigurationany help would be appreciated,['c#'] +585573,play framework 221 create httpcontext for tests i have been trying to create an httpcontext for tests using its constructor unsuccessfully does anybody see what i am doing wrongi have looked at the following but it only applies to play 20play framework 20 store values in httpcontextit looks like the class changed for 221 and it has more parameters for the constructor as shown herethis my codeimport javautilmapimport javautilcollectionsimport orgjunitimport static orgmockitomockitoimport playmvcimport playtestimport playmvchttpimport playmvchttpcontextimport playapimvcrequestheaderimport static playtesthelpersimport static orgfestassertionsassertionspublic class templatetests public static fakeapplication app private final httprequest request mockhttprequestclass beforeclass public static void startapp app helpersfakeapplication helpersstartapp before public void setup throws exception mapstring string flashdata collectionsemptymap mapstring object argdata collectionsemptymap long id 2l playapimvcrequestheader header mockplayapimvcrequestheaderclass httpcontext context mockhttpcontextid header request flashdata flashdata argdata httpcontextcurrentsetcontext test public void rendertemplate content html viewshtmlindexrender assertthatcontenttypehtmlisequaltotexthtml assertthatcontentasstringhtmlcontainsmyindex afterclass public static void stopapp helpersstopapp this is the error that i am seeing when running a testplay testinfo loading project definition from homeusersolrsegmentexplorerexplorerprojectinfo set current project to explorer in build filehomeusersolrsegmentexplorerexplorerinfo compiling 1 java source to homeusersolrsegmentexplorerexplorertargetscala210testclasseserror homeusersolrsegmentexplorerexplorertesttemplatetestsjava33 cannot find symbolerror symbol method contextjavalanglongplayapimvcrequestheaderplaymvchttprequestjavautilmapjavalangstringjavalangstringjavautilmapjavalangstringjavalangstringjavautilmapjavalangstringjavalangobjecterror location class playmvchttperror httpcontext context mockhttpcontextid header request flashdata flashdata argdataerror error 1 errorerror testcompile javac returned nonzero exit codeerror total time 3 s completed nov 25 2013 115636 pmany ideasif i do not create a context i geterror test templatetestsrendertemplate failed javalangruntimeexception there is no http context available from here,['java'] +585581,php empty session files generated by login system recently i have noticed that many blank sessions are being created i am not sure why though as i believe i am doing everything the correct wayat the moment we create a session when a user either logs in or registers we then check whether a user is logged in with an isset cookieauth that belongs to the session created during login or registerif that cookie is present then we start a session this helps us avoid starting thousands of sessions for unregistered users and creating a huge amount of session filessession settingsphp filesession save pathhomeusersessionssession set cookie params86400 session nameauthphpinisessiongc maxlifetime 90sessioncookie lifetime 90sessionuse trans sid 0sessionuse only cookies 1create login session on successful loginsession startsession regenerate idtrue sessionuserid userid sessioncreated timesession write closeheaderlocation serverhttp refererchecking whether a session should be resumedwe then check whether to start a session or not for a user based on whether the auth session cookie is setit will only be set if the user has registered or logged in beforeifisset cookieauth session start session write closecheck if user is logged into check if a user is logged in we then use a functionfunction isauthenticated if isset sessionuserid return false else return truelog outfunction logout session start session destroy setcookieauth 0 unset session unset cookieauth return truefor some reason though i am getting lots of empty filesize 0 session files in the session folderwhere are these coming fromdoes session regenerate idtrue create a new session file and leave the old session file empty that is the only reason i can think of for the empty session files,['php'] +585600,csslint how to config tasks just print error not warning i am new with grunt csslint plugin after i run and csslint task complete there are many and many errors and warnings that i cannot follow so how to config task just print out the errors not warning,['javascript'] +585682,panda dataframe remove constant column i have a dataframe that may or may not have columns that are the same value for example row a b 1 9 0 2 7 0 3 5 0 4 2 0i would like to return just row a 1 9 2 7 3 5 4 2is there a simple way to identify if any of these columns exist and then remove them,['python'] +585706,issue with some big numbers in java script this is a strange issue i am facing when i pass some big numbers to js functions custom or builtin the value is automatically getting incremented by 1 for example see thisdoctype htmlhtmlbodypclick the button to thisplay an alert boxpbutton onclickmyfunctiontry itbuttonscriptfunction myfunctionalert10466511635124471scriptbodyhtmlin the alert i am seeing 10466511635124472 instead of 10466511635124471 can someone explain this behaviori have checked this in ff 17010 and chrome 120742122 and ie 8,['javascript'] +585728,what is the best way to match substring from a big string to a huge list of keywords imagine you have millions of records containing text with average 20 words each and also you have an other list with about 10 itemseg in the keywords list you a have item like president obama and in one of the text records you have some thing like this president obama so i want to find this keyword in the text and replace it with some thing like this president obama to highlight the keyword in the text the keywords list contains multinoun word like the examplewhat is the fastest way to this in such a huge list with millions of text recordsnotesnow i do this work in a greedy way check word by word and match them but it takes about 2 seconds for each text record and i want some thing near zero timealso i know this is something like namedentityrecognition and i worked with many of the ner framework such as gate and but because i want this for a language which is not supported by the frameworks i want to to this manually,['c#'] +585735,total ram size of an ios device is it possible to determine actual ram size of an ios devicereferring to this question knowing available ram on an ios device we can determine the available free memory but how to get the actual total size,"['ios', 'iphone', 'objective-c']" +585763,read id3 v24 tags with native chrome javascriptfilereaderdataview based on the answer of ebidel one can read id3v1 tags by using jdataviewdocumentqueryselectorinputtypefileonchange function e var reader new filereader readeronload function e var dv new jdataviewthisresult tag starts at byte 128 from eof see if dvgetstring3 dvbytelength 128 tag var title dvgetstring30 dvtell var artist dvgetstring30 dvtell var album dvgetstring30 dvtell var year dvgetstring4 dvtell else no id3v1 data found readerreadasarraybufferthisfiles0chrome and other browsers have now implemented dataview i am interested only in chrome i am curious if someone knows how toread tags using the native dataviewreading id3 v24 tags including apic image coverartthe point is that i have no experience with binary files and totally do not know how to jump to the correct tag position or what little endian and long endian or whatever are i just need an example for one tag let us say the title the tit2 tag which i hope helps me to understand how to jump to the correct position and to read the other tags alsofunction readid3 and the position var id3 id3tit2new dataviewthisresultoffsetlength var anew dataviewthisresult consoledirstringfromcharcodeagetuint80 function readfile var a new filereader aonload readid3 areadasarraybufferthisfiles0fileboxaddeventlistenerchange readfile falsehere is the jsfiddleupdatei added getstring so i can read the first line and check if it contains id3now i need to find the position of the first tag tit2 and the variable length of that string also check if it is version 24 headerid3v2file identifier id3id3v2 version 04 00id3v2 flags ab0 in v22 abc0 in v23 abcd0 in v24xid3v2 size 4 0xpossible external sourcesi am using the php getid3 lib at the moment,['javascript'] +585795,how to get objectid on parsecom android it is said that we can retrieve our data if we are having objectid for that particular row but it is auto generated and we cant insert it while setting data so how to get data if i am not having object id or any other means so that i can set objectid on my meanscode is here as in commentparseobject gamescore new parseobjectmy parse file string objectid gamescoregetobjectid,['android'] +585873,constexpr address of base class using clang 34 trunk is there any way to calculate the thisplacement of a base class with a constant expressionstruct a int a struct b int b struct c a b cannot access base class of null pointerconstexpr auto c b address size t b cnullptr,['c++'] +585950,how should i stub a method globally using rspec i am working on a rails application i am trying to stub a method globallywhat i am doing is to stub it inside the rspec configuration on a beforesuite block as followsrspecconfigure do config configbeforesuite do allow any instance ofmymodelto receivemy methodand returnfalse endendhowever starting the test fails with the following errorin method missing undefined method allow any instance of for rspeccoreexamplegroup0x08d6be08 nomethoderrorany clue how should i stub a method globally using rspecp,['ruby-on-rails'] +585967,program execution is not started at main i developed many years in c and only now thiscovered that a program can execute code prior to main functionhere is a code exampleint generatenum some malicious code here return 5static int somearray generatenumgeneratenum int main some code herethe function generatenum is called twice before mainmy questions are who calls generatenum i know that on windows it is crtexeis this behavior standardized on different platforms windowslinuxandroidioshow can i get more information about this behavior i want to search in google but i do not know how to describe it can i do anything i want inside the generatenum i mean can i call malloc what about fopen and fwrite can i open a socket and send information over udp eventually i can abuse this function and even call to main from it,['c++'] +585982,accesing variables in allocated memory lets say i want to allocate memory for 3 integersint pn malloc3 sizeofpnnow to assign to them values i dopn0 50pn1 11pn2 70to access 2nd value i dopn1but the n operator is just a shortcut for an then it would mean that i access first byte after a index but int is 4 bytes long so shoudnt i doasizeofaninstead how does it work,['c'] +585990,strange ajax bug with ie 11 i am currently working on a purely html and javascript driven web app that uses cors for consuming a remote web service but currently having trouble with ie 11 making a get request the funny thing is weve got it working fine in ie8910 just not 11 the problem is that ie 11 appears to timeout and not wait for a response from the server the ajax call is simplyajaxurl datatype json complete complete type get global true success success crossdomain true xhrfields withcredentials true in the network tab and using fiddler i can see ie never even sends the requestdoes anyone have any ideas pleaseedit i forgot to mention i have already tried cache false i have also found something very strange in that if i switch document mode in dev tools from edge to 9 then back again the call works everytime even after i have cleared ie and restarted it whether cache is true or false very bizarre,"['javascript', 'jquery']" +585994,html5 getusermedia camera focus i have created a simple mobile application which shows the camera and decodes qrcodes with because my camera is blurry this works for big qrcodes is there a way to focus the camera with javascript so this also works for smaller images or is there another solutionediti have noticed that if i use the android app instead of the html5 version it can handle way more color difference and can scan my codes while jsqrcode cannot am i using the wrong libraryusing zxingmy working codepublic void scan intentintegrator integrator new intentintegratorthis integratorinitiatescan public void onactivityresultint requestcode int resultcode intent intent on scan result we get get to this part try intentresult scanresult intentintegratorparseactivityresultrequestcode resultcode intent if scanresult null code catch unsupportedencodingexception e todo autogenerated catch block eprintstacktrace also needed to add the import comgooglezxingintegrationandroid package to my project,['javascript'] +586091,rails and byebug how can i rethisplay the current line context when i am debugging with byebug sometimes i evaluate some variables in the terminal which causes the thisplayed line context to go up then i would like to print it again to screen how can i do thati thought maybe thisplay will do that but apparently it does something else,['ruby-on-rails'] +586137,how do i pull maven test jars using gradle in maven i can specify a type for dependency resolution i am trying to pull down a testsjar how can i do this using gradlei have tried using the gradle dependency below but this does not pull down testjar testcompilegroup orgapachehbase name hbase version 0942 type testjarmaven dependencydependency groupidorgapachehbasegroupid artifactidhbaseartifactid version0942version typetestjartype scopetestscopedependencydetails gradle 17i am trying to pull down hbase0942testsjar from maven central,['java'] +586165,comparing two dataframes and getting the differences i have two dataframes examplesdf1date fruit num color 20131124 banana 221 yellow20131124 orange 86 orange20131124 apple 76 green20131124 celery 102 greendf2date fruit num color 20131124 banana 221 yellow20131124 orange 86 orange20131124 apple 76 green20131124 celery 102 green20131125 apple 221 red20131125 orange 86 orangeeach dataframe has the date as an index both dataframes have the same structure what i want to do is compare these two dataframes and find which rows are in df2 that are not in df1 i want to compare the date index and the first column banana apple etc to see if they exist in df2 vs df1i have tried the followingoutputting difference in two pandas dataframes side by side highlighting the differencecomparing two pandas dataframes for differencesfor the first approach i get this error exception can only compare identicallylabeled dataframe objects i have tried removing the date as index but get the same erroron the third approach i get the assert to return false but cannot figure out how to actually see the different rowsany pointers would be welcome,['python'] +586167,uiimagepickercontroller simple way to show library button in camera im trying to show library button on camera view uiimagepickercontroller here is my code voidtakephoto imagepicker uiimagepickercontroller alloc init imagepicker setsourcetypeuiimagepickercontrollersourcetypecamera imagepicker setdelegateself imagepickerallowsediting yes cgrect frame selfviewframe int y framesizeheight int x framesizewidth uibutton button uibutton alloc initwithframecgrectmakex100 y501 100 30 button settitlelibrary forstateuicontrolstatenormal button setbackgroundcoloruicolor clearcolor button addtargetself actionselectorgotolibrary forcontroleventsuicontroleventtouchupinside imagepickerview addsubviewbutton self presentviewcontroller imagepicker animatedno completionnilibactiongotolibraryidsender uiimagepickercontroller imagepicker uiimagepickercontroller alloc init imagepickerview setframecgrectmake0 80 450 350 imagepicker setsourcetypeuiimagepickercontrollersourcetypesavedphotosalbum imagepickerallowsediting yes imagepicker setdelegateself imagepicker presentviewcontrollerimagepicker animatedyes completionnilproblem is in images when i try to take photo how can i hide a library button when i take photo,['ios'] +586232,accessing aspnet controls using jquery all options how to access aspnet control using jqueryasptextbox runatserver idmytextbox mytextbox wouldnt work,"['javascript', 'c#', 'jquery', 'asp.net']" +586245,why does sfind return stringnpos instead of slength on failure i recently was annoyed to find that stringfind returns stringnpos when the needle is not found in the haystack this makes the following seeminglyelegant code compile but throw an outofrange exceptionserasesfind erase everything after a if one existsif find returned slength on failure it would work fine instead you have to doauto pos sfindif pos snpos seraseposthis is also inconsistent with stdfind which returns the end iterator if the item is not foundi know the standard people are pretty smart so i believe they did not just come up with this out of nowhere it must give some elegance somewhere else that i am not seeing what is the good reason for this,['c++'] +586275,how do i validate an androidnethttpsslcertificate with an x509trustmanager androids webviewclient calls onreceivedsslerror when it encounters an untrusted cert however the sslerror object i receive in that call does not have any way public way to get to the underlying x509certificate to validate it against an existing truststoremanager looking at the source i can access the x509certificates encoded bytes thuslypublic void onreceivedsslerrorwebview view sslerrorhandler handler sslerror error bundle bundle sslcertificatesavestateerrorgetcertificate x509certificate x509certificate byte bytes bundlegetbytearrayx509certificate if bytes null x509certificate null else try certificatefactory certfactory certificatefactorygetinstancex509 certificate cert certfactorygeneratecertificatenew bytearrayinputstreambytes x509certificate x509certificate cert catch certificateexception e x509certificate null now i have an x509certificate i can pass to an x509trustmanager for validationobviously this is private api and is fragile though i assume it is fairly reliable since they cannot change the bundle format is there a better way,['android'] +586361,is it possible to code java in another language i was curious as to whether or not a person could code in another languagei do not mean naming your variables in different languages like thisstring tableau janvier fevriersystemoutprintlnstring0lengthbut more likechaane tableau janvier fevriersysta mesortieimprimelnchaane0longueuris that doable or would you need to write your own french or insert language based coding language,['java'] +586402,unexpected end of input error in line 1 of javascript js file chrome dev tools throws the following javascript erroruncaught syntaxerror unexpected end of input applicationjs1applicationjs file first two linesvar firsttimeexecuting true should execute only onceabove function callfunction guessanalguess analyze the guess,['javascript'] +586521,date in to utc format java i have a string like this 20131022t013756 i need to change this string into utc date format like this mmddy kkmmss a i have tried some code but it is not returning the utc datetimemy code is string time itsalarmdttmsplitt string aformatdate time0 time1 string areviseddate null try final simpledateformat sdf new simpledateformatymmdd hhmmss final date dateobj sdfparseaformatdate areviseddate new simpledateformatmmddy kkmmss aformatdateobj systemoutprintlnareviseddate catch parseexception e itsloggererrorerror occured in parsing the data time object egetmessage catch exception e itsloggererrorerror occured in data time objecct egetmessage i am getting the output is mmddy kkmmss a format but not utc time formathow to solve this issue,['java'] +586557,angularsjs jquery mobile are there other possibilities to style an angularjs application in a mobile friendly way than cssi am planning a mobile app and want to use angularjs for the logic and data binding but i do not want to style everything on my own with cssthe angularjs faq says that it uses jquerydoes angular use the jquery library yes angular can use jquery if it is present in your app when the application is being bootstrapped if jquery is not present in your script path angular falls back to its own implementation of the subset of jquery that we call jqlitedue to a change to use onoff rather than bindunbind angular 12 only operates with jquery 171 or abovebut there is no information i have found in the faq on which way angularjs jquery can be usedas you can see i have tried to get the information using angularsjs faq but could not found ithave you found some examples of angularjs with jquery mobile for styling,"['javascript', 'jquery', 'css']" +586569,how does css margin work in the following code should not the margin between box1 and box2 be 20px as the box1 has 10px bottom margin and box2 has 10px top margin div classbox div classbox1div div classbox2divdivcssbox1 marginbottom 10pxbox2 margintop 10px,"['html', 'css']" +586666,mvc java config handlerinterceptor not excluding paths i have a mvc java configuration but the handlerinterceptor is not excluding some patternsat the line marked with x if 1 i add both addpatterns and excludepathpatternsecxld to the handlerinterceptors interceptorregistration the handlerinterceptorprehanlde is not invoked at all eg addpathpatternsexcludepathpatternsecxld2 i add only excludepathpatternsecxld to the handlerinterceptors interceptorregistration the handlerinterceptorprehanlde is still executedthe other interceptors are invoked fineany pointers appreciated thanksconfigurationpublic class mymvcconfigureradapter extends webmvcconfigureradapter override public void addinterceptorsfinal interceptorregistry registry registryaddinterceptorgetinterceptorone registryaddinterceptorgetmyhandlerinterceptor excludepathpatternsecxld x registryaddinterceptorgetinterceptortwo,['java'] +586688,flaskrestful return custom response format i have defined a custom response format as per the flaskrestful documentation as followapp flask name api restfulapiappapirepresentationapplicationoctetstreamdef binarydata code headersnone resp apimake responsedata code respheadersextendheaders or return respapiadd resourcefoo fooi have the following resource classclass foorestfulresource def getself return something def putself fname return somethingi want the get function to return the applicationoctetstream type and the put function to return the default applicationjsonhow do i go about doing this the documentation is not very clear on this point,['python'] +586694,explicit nonsingle parameter constructor can anyone explain why does nonsingle parameter constructor marked as explicit compileas far as i understand this is absolutely useless keyword here so why does this compile without errorclass xpublic explicit xint a int b,['c++'] +586903,ultravisual iphone app like uiview or uitableview scroll can someone please give me a hint on how to recreate the scrolling effect used in the ultravisual iphone app heres a gif to illustrate the effect the first cell is full height while the other thisplayed cells are regular sized while the user scrolls up the first cell slowly animates to the regular height while the next one slowly gets bigger do they use an uitableview or an uiscrollview i have no idea how it is made,"['ios', 'iphone']" +586922,restsharp json array deserialization i launch this restsharp query in json formatvar response restclientexecutereportrequestthe response i get contains this data columns namecameraguidtypeguid namearchivesourceguidtypeguid namestarttimetypedatetime nameendtimetypedatetime nametimezonetypestring namecapabilitiestypeuint32 rows 010babe0408c71be50 3782fe3767484d36b25849ed6a79cd6d 20131127t175200z 20131127t182055063z eastern standard time 2147483647 i am trying to deserialize it into this group of classespublic class report public listreportresult results get set public class reportresult public listcolumnfield columns get set public listrowresult rows get set public class columnfield public string name get set public string type get set public class rowresult public liststring elements get set unfortunately the result data is null and i get this exceptionunable to cast object of type restsharpjsonarray to type systemcollectionsgenericidictionary2systemstringsystemobjecti cannot figure out what is wrong herei little help would be greatly appreciated,['c#'] +586926,how can i get the file path from a uiimage usually it is the other way around you use the path to thisplay the image i was wondering if you can get the path if you already have the image,"['ios', 'objective-c']" +586948,finding memory leak in spring mvc app i recently did this tutorial and got the code running fine then today i reopened the project in eclipse and chose run asrun on server the application seemed to go through its normal load process from the logs running in the eclipse console but then the following error message showed up in the eclipse console at the point when i would have expected the application to load in the browser instead exception in thread httpbio8080exec3 javalangoutofmemoryerror permgen space i did also run the code from this tutorial beforehand and opened a few blob files but i do not think that caused the problem because this error persists even when i shut everything down and restart the computer before doing run asrun on server for the code below again i googled the error and read postings about memory leaks from things like loading a massive file completely into memory instead of using an input stream etc but when i analyzed all the code in the application i could not find any large variables i am posting the code below please let me know if there is anything else i should add to help you find the problem can anyone show me where the memory leak is here is link controller controllerpublic class linkcontroller requestmappingvalue public modelandview mainpage return new modelandviewhome requestmappingvalueindex public modelandview indexpage return new modelandviewhomehere is team controller controllerrequestmappingvalueteampublic class teamcontroller autowired private teamservice teamservice requestmappingvalueadd methodrequestmethodget public modelandview addteampage modelandview modelandview new modelandviewaddteamform modelandviewaddobjectteam new team return modelandview requestmappingvalueadd methodrequestmethodpost public modelandview addingteammodelattribute team team modelandview modelandview new modelandviewhome teamserviceaddteamteam string message team was successfully added modelandviewaddobjectmessage message return modelandview requestmappingvaluelist public modelandview listofteams modelandview modelandview new modelandviewlistofteams listteam teams teamservicegetteams modelandviewaddobjectteams teams return modelandview requestmappingvalueeditid methodrequestmethodget public modelandview editteampagepathvariable integer id modelandview modelandview new modelandvieweditteamform team team teamservicegetteamid modelandviewaddobjectteamteam return modelandview requestmappingvalueeditid methodrequestmethodpost public modelandview edditingteammodelattribute team team pathvariable integer id modelandview modelandview new modelandviewhome teamserviceupdateteamteam string message team was successfully edited modelandviewaddobjectmessage message return modelandview requestmappingvaluedeleteid methodrequestmethodget public modelandview deleteteampathvariable integer id modelandview modelandview new modelandviewhome teamservicedeleteteamid string message team was successfully deleted modelandviewaddobjectmessage message return modelandview here is teamdaoimpl repositorypublic class teamdaoimpl implements teamdao autowired private sessionfactory sessionfactory private session getcurrentsession return sessionfactorygetcurrentsession public void addteamteam team getcurrentsessionsaveteam public void updateteamteam team team teamtoupdate getteamteamgetid teamtoupdatesetnameteamgetname teamtoupdatesetratingteamgetrating getcurrentsessionupdateteamtoupdate public team getteamint id team team team getcurrentsessiongetteamclass id return team public void deleteteamint id team team getteamid if team nullgetcurrentsessiondeleteteam suppresswarningsunchecked public listteam getteams return getcurrentsessioncreatequeryfrom teamlist here is initializer public class initializer implements webapplicationinitializer public void onstartupservletcontext servletcontextthrows servletexception annotationconfigwebapplicationcontext ctx new annotationconfigwebapplicationcontext ctxregisterwebappconfigclass servletcontextaddlistenernew contextloaderlistenerctx ctxsetservletcontextservletcontext dynamic servlet servletcontextaddservletthispatcher new thispatcherservletctx servletaddmapping servletsetloadonstartup1 here is webappconfig configurationcomponentscancomsprhibenablewebmvcenabletransactionmanagementpropertysourceclasspathapplicationpropertiespublic class webappconfig private static final string property name database driver dbdriver private static final string property name database password dbpassword private static final string property name database url dburl private static final string property name database username dbusername private static final string property name hibernate dialect hibernatedialect private static final string property name hibernate show sql hibernateshow sql private static final string property name entitymanager packages to scan entitymanagerpackagestoscan resource private environment env bean public datasource datasource drivermanagerdatasource datasource new drivermanagerdatasource datasourcesetdriverclassnameenvgetrequiredpropertyproperty name database driver datasourceseturlenvgetrequiredpropertyproperty name database url datasourcesetusernameenvgetrequiredpropertyproperty name database username datasourcesetpasswordenvgetrequiredpropertyproperty name database password return datasource bean public localsessionfactorybean sessionfactory localsessionfactorybean sessionfactorybean new localsessionfactorybean sessionfactorybeansetdatasourcedatasource sessionfactorybeansetpackagestoscanenvgetrequiredpropertyproperty name entitymanager packages to scan sessionfactorybeansethibernatepropertieshibproperties return sessionfactorybean private properties hibproperties properties properties new properties propertiesputproperty name hibernate dialect envgetrequiredpropertyproperty name hibernate dialect propertiesputproperty name hibernate show sql envgetrequiredpropertyproperty name hibernate show sql return properties bean public hibernatetransactionmanager transactionmanager hibernatetransactionmanager transactionmanager new hibernatetransactionmanager transactionmanagersetsessionfactorysessionfactorygetobject return transactionmanager bean public urlbasedviewresolver setupviewresolver urlbasedviewresolver resolver new urlbasedviewresolver resolversetprefixwebinfpages resolversetsuffixjsp resolversetviewclassjstlviewclass return resolver here is team entitytablenameteamspublic class team id generatedvalue private integer id private string name private integer rating public integer getid return id public void setidinteger id thisid id public string getname return name public void setnamestring name thisname name public integer getrating return rating public void setratinginteger rating thisrating rating here is teamserviceimpl servicetransactionalpublic class teamserviceimpl implements teamservice autowired private teamdao teamdao public void addteamteam team teamdaoaddteamteam public void updateteamteam team teamdaoupdateteamteam public team getteamint id return teamdaogetteamid public void deleteteamint id teamdaodeleteteamid public listteam getteams return teamdaogetteams editif i am supposed to set the java opts variable to allow class unloading and to increase memory size how do i do so in windows 7 running tomcat 7 my sense is i need to create a windows system variable and possibly run something on the command line after but what here is what i am starting with java optsxxmaxpermsize128m xxcmsclassunloadingenabled xxcmspermgensweepingenabled xms256m xmx512m,['java'] +586959,how to find string in project in android studio this may be a really stupid question but i just cannot figure it out i have just started using android studio intellij and i now look for the feature to find the occurrence of a string in any of the files in my project for example i want to find all the files that contain the string getuuidthe search at the top right does not give me the correct results and i do not think i can find this feature under edit findcould anybody point me at the right direction any help would be really really welcome,['android'] +586972,angular combining parallel and chained requests with httpthen and qall i have a rather complicated set of api calls to make and i am attempting to do it as elegantly and performant as possible i understand how to use the promise api of the http service to chain requests and how to use the q service to make requests in parallel but for this specific api workflow i need to do bothhere is an example of the highlevel api flowdogdog idbreedbreed idfoodfood idcatcat idturkeyturkey idfishfish idthe first tier of requests all have known ids however the breed id required to make the breed call must be parsed from the dog response and the food id required to make the food call must be parsed from the breed response so dog breed and food all need to be chained however cat turkey and fish can be made in parallel with the entire dog chainwhat i have got now and it is working fine are two separate sets of requests how do i improve on this flow is there a way to combine the two stacks in a way that results in a single promise execution of thenvar dogid 472053 catid 840385 turkeyid 240987 fishid 510412var mydata var firstsetcomplete false secondsetcomplete false returndata function if firstsetcomplete secondsetcomplete consolelogmydatadog mydatadog consolelogmydatadogbreed mydatadogbreed consolelogmydatadogfood mydatadogfood consolelogmydatacat mydatacat consolelogmydataturkey mydataturkey consolelogmydatafish mydatafish first call sethttpget dogidthenfunctionresponse mydatadog responsedata return httpget responsedatabreed idthenfunctionresponse mydatadogbreed responsedata return httpget responsedatafood idthenfunctionresponse mydatadogfood responsedata firstsetcomplete true returndata second call setqall httpget catid httpget turkeyid httpget fishidthenfunctionresponses mydatacat responses0data mydataturkey responses1data mydatafish responses2data secondsetcomplete true returndata,['javascript'] +587023,why does this code give me an infinite loop when i enter in a correct value an integer it is good but when i enter in a character i get an infinite loop i have looked at every side of this code and could not find a problem with it why is this happening i am using g 47 on windowsinclude iostreaminclude limitsint main int n while stdcin n stdcout please try againn stdcinignorestdnumeric limitsstdstreamsizemax n stdcinclear input xoutput,['c++'] +587025,recognition of handwritten circles diamonds and rectangles i looking for some advices about recognition of three handwritten shapes circles diamonds and rectangles i tried diffrent aproaches but they failed so maybe you could point me in another better directionwhat i tried1 simple algorithm based on dot product between points of handwritten shape and ideal shape it works not so bad at recognition of rectangle but failed on circles and diamonds the problem is that dot product of the circle and diamond is quite similiar even for ideal shapes2 same aproach but using dynamic time warping as measure of simililarity similiar problems3 neural networks i tried few aproaches giving points data to neural networks feedforward and kohonen or giving rasterized image for kohonen it allways classified all the data event the sample used to train into the same category feedforward with points was better but on the same level as aproach 1 and 2 and with rasterized image it was very slow i needs at least size2 input neurons and for small sized of raster circle is inthistinguishable even for me and also without success i think is because all of this shapes are closed figures i am not big specialist of ann had 1 semester course of them so maybe i am using them wrong4 saving the shape as freeman chain code and using some algorithms for computing similarity i though that in fcc the shapes will be realy diffrent from each other no success here but i havent explorer this path very deeplyi am building app for android with this but i think the language is irrelevant here,['android'] +587031,wpf icollectionview binding item cannot resolve property of type object i have bound a gridview with an icollectionview in the xaml designer the properties are not known because the entity in the collectionview have been transformed into type object and the entity properties cannot be accessed it runs fine no error but the designer shows it as an error if i bind to the collection i can access the properties fineexample the entity is a person with a string name property i place them in an observablecollectionperson and get the view from it and bind it to the gridviewitemssource now when i try to set the column header datamemberbindingfirstname property the designer shows it as an errorcannot resolve property firstname in data context of type object is it a bug or is it resharper playing tricks on mesample codepublic class person public string firstname get return firstname set setpropertyvaluefirstname ref firstname value public class dataservice public idatasource datacontext get set public icollectionview personcollection get set public dataservice datacontext new datasource queryablecollectionview is from telerik but if i use any other collectionview same thing datacontext persons is an observablecollectionperson persons personcollection new queryablecollectionviewdatacontextpersons telerikradgridview xnameparentgrid itemssourcebinding dataservicepersoncollection autogeneratecolumnsfalse telerikradgridviewcolumns telerikgridviewdatacolumn headerlexloc keyfirstname datamemberbindingbinding firstname telerikradgridviewcolumnstelerikradgridview,['c#'] +587108,javascript consolelog to html i would like to write the consolelog output to a div layerfor exampledocumentwriteconsolelog51 incorrect random examplecan someone give me a solution to my problemthank youeditwhat i meant is for exampleconsoleloghiand it shows the output hi on the screennote an example,['javascript'] +587164,custom dialog with close button i want to create a custom dialog with the layout as shown in the picturethe crossclose button must be on the top right sideplease suggest how can i achieve this kind of layoutthanks in advance,['android'] +587209,how to detect whether stringsubstring copies the character data i know that for oracle java 17 update 6 and newer when using stringsubstring the internal character array of the string is copied and for older versions it is sharedbut i found no offical api that would tell me the current behavioruse casemy use case isin a parser i like to detect whether stringsubstring copies or shares the underlying character arraythe problem is if the character array is shared then my parser needs to explicitly unshare using new strings to avoidmemory problems however if stringsubstring anyway copies the data then this is not necessary and explicitly copying the data in the parser could be avoided use case possibly the query is very very largestring query select from test the identifier is used outside of the parserstring identifier querysubstring14 18 avoid if possible for speed but needed if identifier internally references the large query char arrayidentifier new stringidentifierwhat i needbasically i would like to have a static method boolean issubstringcopyingforsure that would detect if new string is not needed i am ok if detection does not work if there is a securitymanager basically the detection should be conservative to avoid memory problems i would rather use new string even if not necessaryoptionsi have a few options but i am not sure if they are reliable specially for nonoracle jvmschecking for the stringoffset field return true if substring is copying false if not or if it is not clear static boolean issubstringcopyingforsure if systemgetsecuritymanager null we can not reliably check it return false try for field f stringclassgetdeclaredfields if offsetequalsfgetname return false return true catch exception e weird we do have a security manager return falsechecking the jvm versionstatic boolean issubstringcopyingforsure but what about nonoracle jres return systemgetpropertyjavavendorstartswithoracle systemgetpropertyjavaversioncompareto170 45 0checking the behaviorthere are two options both are rather complicated one is create a string using custom charset then create a new string b using substring then modify the original string and check whether b is also changed the second options is create huge string then a few substrings and check the memory usage,['java'] +587249,what is correct way to combine longrunning tasks with async await pattern i have a highprecision timer class that i need to be able to be start stop pause resume to do this i am tying together a couple of different examples i found on the internet but i am not sure if i am using tasks with asnyc await correctlyhere is my relevant codebased on public class highprecisiontimer ithisposable task task cancellationtokensource cancelsource based on pausetokensource pausesource stopwatch watch stopwatch watch get return watch watch stopwatchstartnew public bool ispaused get return pausesource null pausesourceispaused private set if value pausesource new pausetokensource else pausesourceispaused false public bool isrunning get return ispaused task null taskstatus taskstatusrunning public void start if ispaused ispaused false else if isrunning cancelsource new cancellationtokensource task new taskexecuteasync cancelsourcetoken taskcreationoptionslongrunning taskstart public void stop if cancelsource null cancelsourcecancel public void pause if ispaused if watch null watchstop ispaused ispaused async void executeasync while cancelsourceiscancellationrequested if pausesource null pausesourceispaused await pausesourcetokenwaitwhilepausedasync do custom timer stuff if watch null watchstop watch null cancelsource null pausesource null public void thispose if isrunning cancelsourcecancel can anyone please take a look and provide me some pointers on whether i am doing this correctlyupdatei have tried modifying my code per noseratios comments below but i still cannot figure out the syntax every attempt to pass the executeasync method to either taskfactorystartnew or taskrun results in a compilation error like the followingthe call is ambiguous between the following methods or properties taskfactorystartnewaction cancellationtoken and taskfactorystartnewtaskfunctask cancellationtokenfinally is there a way to specify the longrunning taskcreationoption without having to provide a taskschedulerasync task executeasync while cancelsourceiscancellationrequested if pausesource null pausesourceispaused await pausesourcetokenwaitwhilepausedasync public void start task taskfactorystartnewexecuteasync cancelsourcetoken taskcreationoptionslongrunning null task taskfactorystartnewexecuteasync cancelsourcetoken task taskrunexecuteasync cancelsourcetokenupdate 2i think i have narrowed this down but still not sure about the correct syntax would this be the right way to create the task so that the consumer calling code continues on with the task spinningup and starting on a new asynchronous thread task taskrunasync await executeasync cancelsourcetokenor task taskfactorystartnewasync await executeasync cancelsourcetoken taskcreationoptionslongrunning taskschedulerdefault,['c#'] +587260,what is the practical use of protected inheritance public inheritance is easya public b means every a is a b in most programming language like vbnet and objectivec this is the only type of inheritanceprivate inheritance is also easy but pointlessa private b means a is implemented by b however that is pointless because that means a should contain b instead ownership means less coupling with no thisadvantagethen we have protected inheritancecan anyone explain to me what the hell is that for some says it is an as a relationship i am still not very clear on thatdoes anyone has some sample cases where people uses protected inheritance in good pattern and conscience for actual productive use,['c++'] +587285,cakephp 13 unknown column in where clause i am working on an already existing cakephp 13 project and i needed to add a new table to the database i have this in my controller conditions arrayshootingplacementperson id id emailperson id id emailshooting placement id shootingplacementid shootingplacements thisshootingplacementfindall compactconditionsand it is giving me this error warning 512 sql error 1054 unknown column emailperson id in where clause corecakelibsmodeldatasourcesdbo sourcephp line 684and ths is the query it is trying to create select shootingplacementid from shooting placements as shootingplacement left join people as person on shootingplacementperson id personid left join shootings as shooting on shootingplacementshooting id shootingid where shootingplacementperson id 123688 and emailperson id 123688 and emailshooting placement id shootingplacementid order by lastname asc obviously my controller code is wrong but i am not sure how to relate the email table to the shootingplacement one i think my models are correct so far if i have this conditions arrayshootingplacementperson id id shootingplacements thisshootingplacementfindall compactconditionsit will retrieve the rows from shooting shootingplacement and person i want email to be there too email has 2 foreign keys one from shootinplacement and one from person these are the models the only one i created is email the rest where working correctlyclass email extends appmodel var name email var belongsto array person array classname person foreignkey person id shootingplacement array classname shootingplacement foreignkey shooting placement id class shootingplacement extends appmodel var name shootingplacement var belongsto array person array classname person foreignkey person id order lastname asc shooting array classname shooting foreignkey shooting id class person extends appmodel var name person var belongsto array personorigin array classname personorigin foreignkey person origin id var hasmany array shootingplacement array classname shootingplacement foreignkey person id dependent false class shooting extends appmodel var name shooting var belongsto array shootinglocation array classname shootinglocation foreignkey shooting location id emission array classname emission foreignkey emission id what i need on the view is to loop through the shootingplacement variable and i need it to contain the email table data for that specific id of shootingplacement and person as you see in the query person and shootingplacement are in a relationship already i only need there to be email too,"['php', 'mysql', 'sql']" +587317,javafx bind to multiple properties i have a simple fxml with a textfield and a button i would like to have the button thisabled if the textfield is empty so i insert something like the following in my controlleroverridepublic void initializeurl url resourcebundle bundle buttonthisablepropertybindtextfieldtextpropertyisequaltoand that works fine the problem is when i add a second textfield and would like my button to be thisabled if either textfield is empty what to do then i tried the following but that does not workoverridepublic void initializeurl url resourcebundle bundle buttonthisablepropertybindtextfieldtextpropertyisequalto buttonthisablepropertybindtextfield2textpropertyisequalto,['java'] +587341,uibutton shows default white background with round corners in ios 6 but no in ios 7 i need a code that removes this default background in ios 7 there is not a problem since i do not see this background,['ios'] +587375,finalizers for javascript objects suppose i have some asmjs code probably created by emscripten suppose it has some kind of rather large heap allocated structure which gets returned by a asmjs function as a pointer that is picked up by some javascript library to be wrapped in a nice javascript object fine so farbut what happens if that object goes out of scope and gets garbage collected right now the asmjs code has no way of knowing about that so the memory of the structure will remain allocated causing a memory leakis there some way to add a finalizer to a javascript object from within javascriptsuch a finalizer could be used to deallocate the memory in asmjs thus avoiding the memory leak so far i could not find a documented ie portable way to achieve this but perhaps i have been looking in the wrong places,['javascript'] +587397,how to get the size kb of a video avasset i would like to get an avasset video file size not the videos resolution but the file weight in kba solution would be to calculate an estimated filesize from the duration and the estimateddatarate but this seems to be a lot just to get a filesizei have checked all data embedded in avassettrack it does not seems to be in there even an estimated filesize would be nice,['ios'] +587439,generate signed apk android studio i am new to android development and just finished my first app i want to generate a signed apk in android studio i read the developer docs but could not understand the steps when i click on buildgenerate signed apk it shows me a dialog box asking the followingkeystore path with two options create new and choose existingkeystore passwordkey aliaskey passwordi do not get what is keystore even after googling it when i choose create new it asks me to select a path and locate a jks file which i do not have can anyone please explain and list the steps in order to generate a signed apk,['android'] +587473,xcode instruments trace comparison is there any way to compare trace files saved with instruments how can i have a comparison of any way regarding consecutive realise builds of the applests say i release iphone app version 10 then in 2 months 11 whats is the best have to have a profiling comparison in terms of memory and time,['ios'] +587495,slim php route in middleware in slim is it possible to get the current route within middlewareclass auth extends slimmiddleware public function call currentroute thisappgetroute something like this i know you can call approutergetcurrentroute after the slimbeforethispatch hook is called but when you call this from middleware it returns a nonobject any help would be greatly appreciated,['php'] +587666,how to avoid deprecation warning for stub chain in rspec 30 when i run a test with stub chain i will get a deprecation warningdescribe stubbing a chain of methods do subject objectnew context given symbols representing methods do it returns the correct value do subjectstub chainone two threeand returnfour expectsubjectonetwothreeto eqfour end endenddeprecation warningsusing stub chain from rspecmocks old should syntax without explicitly enabling the syntax is deprecated use the new expect syntax or explicitly enable should insteadhow this warning can be avoided,['ruby-on-rails'] +587667,why the signal is called twice in reactivecocoa i am implementing my first code with is for login a user the line subscriber sendnextuser is called twice but i expect to be only one and the map is not called at all so autologin is never calledthis is my implementationracsignal loginnsstring email pwdnsstring pwd ddloginfologin user email racsignal login racsignal createsignal racthisposable idracsubscriber subscriber pfuser loginwithusernameinbackgroundemail passwordpwd blockpfuser user nserror error if error subscriber senderrorerror else subscriber sendnextuser subscriber sendcompleted return nil login mappfuser user return self autologinuser return loginis called this waynsstring email dataemailnsstring pwd datapwdsvprogresshud showwithmasktypesvprogresshudmasktypeblackracsignal login syncengine server loginemail pwdpwdlogin subscribecompleted nsnotificationcenter defaultcenter postnotificationnamenotify login changed objectself svprogresshud showsuccesswithstatusloc ok self cancelformlogin subscribeerrornserror error svprogresshud thismiss appurls alerterrorloc error loging msgerroruserinfoerror,"['ios', 'objective-c']" +587782,is there any javascript library to modify exif information of image suggest me any javascript library to modify exif info of an image i found lots of js library to retrieve exif info but noting to modifyi have to modify orientation information,['javascript'] +587796,how to get file path of file from internal storage in android in our application we are storing pdf files into internal storagenow i want to get its filepath and need to store into db please tell me how to get its file path below codepublic void storeintointernalmembyte databytes string name try fileoutputstream fileouputstream openfileoutputname mode private fileouputstreamwritedatabytes fileouputstreamclose catch ioexception e eprintstacktrace,['android'] +587864,integer minmax value peculiar overflow behavior why is integermin value 2 equal to 0and integermax value 2 equal to 2let me explain myself better i know it overflows but why does it get these specific results,['java'] +587870,how do i force a report to always insert a page break i created a report in visual studio 2012 that has two report definitions the main report section repeats once per vehicle and it has a subreport that repeats once for each delivery that vehicle hasthe main report design looks as followsthe orange bar on the left side indicates that the rectangle on which i have all the other elements located is selectedi have set the following properties on iti have also set add a page break before and add a page break after on the tablix that contains the other elementsthere is no other rectangle or tablix on this report designmy problem is that it does not always do a pagebreak before and after on pages with only a little information it puts each vehicle on the same page as followsbut when a vehicle is longer than a single page it spills into the next page and the next vehicle does not add a page break before it like sohow can i force the report to always insert a page break before a new vehicle,['c#'] +587871,how can i change type of django calender with persian calender i use django 16when i have a field that have datetimefield type django automatically use django calenderbut in iran we use persian calender or jalali calender or farsi calenderhow can i change django auto generation because it generate persian calender in pagein other hand i want change default calender with persian calender,['python'] +587873,back text thisplayed in ios7 uinavigationbar when view title is long in my applicationi need to show the previous viewcontroller title to current viewcontroller back title its working perfectly in ios6in ios7automatically the back title thisplayed other than the previous viewcontroller titlehow to fix the issue in ios7,['objective-c'] +587883,java c array complexity task i am dealing with some problematic complexity question via my universityprogram input a n x n array that is filled with either 0 or 1definition define k as a sink if in the k row all the values are 0 and in the k column all the values are 1 except kk itself which needs to be 0program output is there a k number that is a sink if so returnk else return 1example on arr a k3 is a sink on arr b there in no sink so 1 is returnedthe main problem with this task is that the complexity of the program must be below on2 i have managed to solve this with that complexity going over the oblique line summing the rowscolumns i have not find a way to solve this with ologn or on also the task prevents you from using another array due to memory complexity can anyone drop any light on that matter thanks in advance,"['c#', 'java']" +587975,mock constructor with mockito i want to mock a constructor into method public string generaid generaidparaentidadcliente aux new generaidparaentidadclientenombre registro entidadsetidauxgeneraid in my test i want do something like this whennew generaidparaentidadclienteanystring anyentidadclassthenreturngeneraidmock but give me this error orgmockitoexceptionsmisusinginvaliduseofmatchersexceptionany idea why,['java'] +588043,how to use bulk api to store the keywords in es by using python i have to store some message in elasticsearch integrate with my python program now what i try to store the message isdmessagethis is message for index nr in range15 elasticsearchapiaddtoindexindex nr d print dthat means if i have 10 message then i have to repeat my code 10 times so what i want to do is try to make a script file or batch filei check elasticsearch guide bulk api is possible to use the format should be something like below index index test type type1 id 1 field1 value1 delete index test type type1 id 2 create index test type type1 id 3 field1 value3 update id 1 type type1 index index1 doc field2 value2 what i did is index indextest1 typemessage id1messageit is redindex indextest2 typemessage id2messageit is greeni also use curl tool to store the doc curl s xpost localhost9200 bulk databinary messagejsonnow i want to use my python code to store the file to the elastic search,['python'] +588060,difference between int primary key and integer primary key sqlite is there any difference between int primary key and integer primary key when defining a schema for a table when int primary key is used i got sqlite autoindex thing generated when integer primary key i got sqlite sequence table generated whats the difference what side effects can have the first and second variants,['sql'] +588089,how to deal with semantic symbols for accessibility in html i find this an interesting question since there has not been any resource thiscussing this matter yet how do you deal with symbols that has semantic meaning when writing accessible markupexamples would be symbols like etc maybe the screen reader is smart enough to read as and as dollar and so on but some symbols do not always have definitive meaning in every scenario for example when you see jan 2 3 2013 or jan 2 3 2013 you know the and means from to but how do i encode that meaning into the markup should i use the abbr tag like jan 2 abbr titletoabbr 3 2013,['html'] +588111,improving the extraction of human names with nltk i am trying to extract human names from text does anyone have a method that they would recommendthis is what i tried code is belowi am using nltk to find everything marked as a person and then generating a list of all the nnp parts of that person i am skipping persons where there is only one nnp which avoids grabbing a lone surnamei am getting decent results but was wondering if there are better ways to go about solving this problemcodeimport nltkfrom nameparserparser import humannamedef get human namestext tokens nltktokenizeword tokenizetext pos nltkpos tagtokens sentt nltkne chunkpos binary false person list person name for subtree in senttsubtreesfilterlambda t tnode person for leaf in subtreeleaves personappendleaf0 if lenperson 1 avoid grabbing lone surnames for part in person name part if name1 not in person list person listappendname1 name person return person listtext some economists have responded positively to bitcoin including francois r velde senior economist of the federal reserve in chicago who described it as an elegant solution to the problem of creating a digital currency in november 2013 richard branson announced that virgin galactic would accept bitcoin as payment saying that he had invested in bitcoin and found it fascinating how a whole new global currency has been created encouraging others to also invest in bitcoinother economists commenting on bitcoin have been critical economist paul krugman has suggested that the structure of the currency incentivizes hoarding and that its value derives from the expectation that others will accept it as payment economist larry summers has expressed a wait and see attitude when it comes to bitcoin nick colas a market strategist for convergex group has remarked on the effect of increasing use of bitcoin and its restricted supply noting when incremental adoption meets relatively fixed supply it should be no surprise that prices go up and thatas exactly what is happening to btc pricesnames get human namestextprint last firstfor name in names last first humannamenamelast humannamenamefirst print last firstoutputlast firstvelde francoisbranson richardgalactic virginkrugman paulsummers larrycolas nickapart from virgin galactic this is all valid output of course knowing that virgin galactic is not a human name in the context of this article is the hard maybe impossible part,['python'] +588172,making pytest coverage and tox work together init py in tests folder i am having a weird problem with tox pytest coverage and pytestcov when pytest with the cov option is launched from tox it seems to require an init py file in the tests folder which is not immediately obviouswhile writing this post i have kind of solved the initial problem by adding the aforesaid tests init py but to this moment i do not fully understand why exactly it works or does not work so i am still asking for help please see below for detailsi have found a related question on so but it only makes it more confusing because the answer seems to be opposite to what i have figured out so farpytest and init py filessee also the official docs here pytest good integration practices the very bottom of the pagesimplified project structuresetuppytoxinicoveragercproject init py module1py module2py tests init py optional an empty file test module1py test module2pyrelevant part of toxinitestenvcheckcommands pytest covproject covreporttermdeps pytest coverage pytestcovpytestpython files test pynorecursedirs toxrelevant part of coveragercrunbranch trueomit projecttestsnow the resultspytest covproject covreportterm run from project root correct coverage whether tests init py file is present or nottox e check without tests init py the tests are thiscovered and run but i get a warning coveragepy warning no data was collected and the coverage is 0 for all modulestox e check with tests init py correct coverage againit is not immediately obvious to me why the tests init py file has to be there adding this empty file solved the initial problem for the tox run but it does not matter when you run the testscoverage manually any ideasthanks,['python'] +588196,how to empty div before append i am using freebase search suggest to bind a certain keyword to a getjson request the problem is that i bind getjson functions and the corresponding appendprepend functions to to the input field that has the search suggest now if want to clearempty my div that contains the result from the getjson functions i end up not being able to appennd anythingso every time i do a search the result div stays empty if i not try to run the empty function and do a second search the new information gets appended on top of the previous information my site wkarstentietjedkswmyinputsuggestkey mykeyfilter all typemusicmusical group bindfbselect functione data getjsonsearch val functiondata items eachdatatracks functionkey val itemspushli claspotspan typeofmusicrecording propertytrackpname strongspan propertyname valname spanspanstrongp palbum strong valalbumname strongpp released strong valalbumreleased strongppstronga href valhref i classiconplaysigni start spotifyastrongp if key 7 return false spotifydivprependh3 styleborderbottom1px solid whitespotify tracksh3 spotifyhtmlitemsjoinli this is just a snippet of my some of my code i run multiple getjson functions how can i clearempty my result div before running the other functions,"['javascript', 'jquery']" +588204,java why does not int double cause a incompatible types error heres an oddityfloat a 0a a mathpi errorand yeta mathpi okeven this worksint b 0b mathpi ok toowhy does the operator allow lossy implicit type conversions,['java'] +588211,send http request from different ips in nodejs is there a way to send an http request with a different ip from what i have in nodejsi want to send a request from an ip that i choose before and not from the ip of the server or from my computeras ipi know that tor project does this kind of manipulation but i did not find any library that tor uses to do this stuff is there any api or nodejs module that tor uses to handle this kind of private browsing in nodejs,['javascript'] +588236,ajax call with contenttype applicationjson not working i have an ajax call that sends form data to a php function since i read a lot that using contenttype applicationjson is best practice i wanted to give it a try as well but unfortunately my script does not return anything when i use it if i remove it the script does what it is supposed to do do you have any idea what the reason might be and why thank youformsubmitfunctione epreventdefault var content thisserialize ajax1 ajaxappclasscontrollercontactformphp type post contenttype applicationjson datatype json data content success functionresult consolelogresult and my phpifisset postajax postajax 1 echo json encodevalidateform post,"['php', 'jquery']" +588258,activemodelmissingattributeerror cannot write unknown attribute ad id with factorygirl i have the following modelsclass ad activerecordbase belongs to page has one image has one logoendclass page activerecordbase has many logos has many images has many adsendclass image activerecordbase belongs to page has many adsendand i have defined the following factoriesfactory page do url testcomendfactory image do width 200 height 200 pageendfactory ad do background rgb25500 page imageendwhen i try to do thisad factorygirlcreatead i get the following error activemodelmissingattributeerror cannot write unknown attribute ad id right in the line where i decide the image association in the ad factorywhat am i doing wrong here,['ruby-on-rails'] +588295,how to embed php in twig i have a do shortcut and i need to embed it in a twig template i tried by coping the code in a php file mycodephpphp do shortcutmycode next in the twig page overtwig include optionsmycodephp i also tried php php do shortcutmycode endphp but does not work any suggestion thanks,['php'] +588306,joomla utf8 encoding fails on opening the mail i have a strange issue with encoding described as followsthe a1 is now shown as aa1 in the email subject the email is sent through php mail functionwhen viewing the email in the mailbox it is shown correctly however when anybody opens the email the a1 is suddenly changed to aa1uw contact met meeaa1sshould beuw contact met meea1si have already used the encodingemailsubject contains the above mentioned email subjectsubjectemailsubjectsubjectemailsubjectemail messagenew email message classemail messagesetencodedemailheadertoto addressto nameemail messagesetencodedemailheaderfromfrom addressfrom nameemail messagesetencodedemailheaderreplytoreply addressreply nameemail messagesetheadersenderfrom addressemail messagesetencodedheadersubjectsubjectutf8in localhost it is working properly but in the webserver it is not working properly in webserver also encoding is set to utf8 by defaultwhat i am doing wrongthanks in advance,['php'] +588371,error union operator must have an equal number of expressions when using cte for recursive selection at this moment i have a table tbllocation with columns id location partofidthe table is recursively connected to itself partofid idmy goal is to have a select output as followed france paris anycity explanation anycity is located in paris paris is located in francemy solution that i found until now was this with q as select idlocationpartof loc id from tbllocatie twhere tid 1 1 represents an exampleunion allselect tlocation from tbllocation tinner join q parent on parentid tloc partof idselect from qunfortunately i get the following errorall queries combined using a union intersect or except operator must have an equal number of expressions in their target listsif you have any idea how i could fix my output it would be great,['sql'] +588402,scala ide eclipse run as scala application i am relatively new to the scala language and programming in general i recently installed the jdk and the scala ide for eclipse the setup went smoothly but i encountered an issue upon trying to run a hello world application when i attempt to run as the only available options are java applet and java application how do i proceed in trying to run as a scala application many thanks in advance,['java'] +588407,google chrome css does not update unless clear cache i am trying to work in my local server but i have to clear my cache every time if i want to see changes on the css rulesthere is any way to control google chrome cache,['css'] +588457,whats the difference between codingutf8 and coding utf8 is there any difference between using codingutf8and coding utf8 what about encoding utf8,['python'] +588462,struggling with youtube player support fragment im trying to use the youtube player support fragment in a fragment but the app always crash nullpointerexception and i have not been able to find any similar post to fix it i have import import androidsupportv4appfragment so that should not be the problemthis is how my fragment class looks likepackage comexampleactivitydetectorimport comgoogleandroidyoutubeplayeryoutubebaseactivityimport comgoogleandroidyoutubeplayeryoutubeinitializationresultimport comgoogleandroidyoutubeplayeryoutubeplayerimport comgoogleandroidyoutubeplayeryoutubeplayeroninitializedlistenerimport comgoogleandroidyoutubeplayeryoutubeplayerproviderimport comgoogleandroidyoutubeplayeryoutubeplayerfragmentimport comgoogleandroidyoutubeplayeryoutubeplayersupportfragmentimport comgoogleandroidyoutubeplayeryoutubeplayerviewimport systemmanagersystemmanagerimport androidappactivityimport androidbluetoothbluetoothadapterimport androidosbundleimport androidsupportv4appfragmentimport androidutillogimport androidviewlayoutinflaterimport androidviewviewimport androidviewviewonclicklistenerimport androidviewviewgroupimport androidwidgetbuttonimport androidwidgetlinearlayoutimport androidwidgettoastpublic class guidelinesfragment extends youtubeplayersupportfragment systemmanager sm youtubeplayerview youtubeview string url video caak1l0xa4 string key developer aizasybiis0u0nxhszguv8ncnvszumfltt7k1ek public guidelinesfragment super todo autogenerated constructor stub public void oncreatebundle savedinstancestate todo autogenerated method stub superoncreatesavedinstancestate public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate view view inflaterinflaterlayoutyoutube container false youtubeplayersupportfragment youtubeplayersupportfragment youtubeplayersupportfragment getfragmentmanagerfindfragmentbyidridyoutubeplayerfragment youtubeplayersupportfragmentinitializekey developer new oninitializedlistener override public void oninitializationsuccessprovider arg0 youtubeplayer arg1 boolean arg2 todo autogenerated method stub arg1cuevideourl video override public void oninitializationfailureprovider arg0 youtubeinitializationresult arg1 todo autogenerated method stub return view this is my totally and simple youtube layoutlinearlayout xmlnsandroidxmlnstoolsandroidlayout widthmatch parentandroidlayout heightmatch parentandroidorientationverticaltoolscontextmainactivity fragment androidnamecomgoogleandroidyoutubeplayeryoutubeplayersupportfragment androidididyoutubeplayerfragment androidlayout widthmatch parent androidlayout heightwrap contentand this is the error that the log shows 1130 163356419 wdalvikvm19375 threadid1 thread exiting with uncaught exception group0x40f142581130 163356423 eandroidruntime19375 fatal exception main1130 163356423 eandroidruntime19375 javalangnullpointerexception1130 163356423 eandroidruntime19375 at comgoogleandroidyoutubeplayeryoutubeplayersupportfragmentonstartunknown source1130 163356423 eandroidruntime19375 at androidsupportv4appfragmentperformstartfragmentjava14841130 163356423 eandroidruntime19375 at androidsupportv4appfragmentmanagerimplmovetostatefragmentmanagerjava94130 163356423 eandroidruntime19375 at androidsupportv4appfragmentmanagerimplmovetostatefragmentmanagerjava10881130 163356423 eandroidruntime19375 at androidsupportv4appbackstackrecordrunbackstackrecordjava6821130 163356423 eandroidruntime19375 at androidsupportv4appfragmentmanagerimplexecpendingactionsfragmentmanagerjava141130 163356423 eandroidruntime19375 at androidsupportv4appfragmentmanagerimpl1runfragmentmanagerjava4291130 163356423 eandroidruntime19375 at androidoshandlerhandlecallbackhandlerjava6051130 163356423 eandroidruntime19375 at androidoshandlerthispatchmessagehandlerjava921130 163356423 eandroidruntime19375 at androidoslooperlooplooperjava1371130 163356423 eandroidruntime19375 at androidappactivitythreadmainactivitythreadjava46451130 163356423 eandroidruntime19375 at javalangreflectmethodinvokenativenative method1130 163356423 eandroidruntime19375 at javalangreflectmethodinvokemethodjava5130 163356423 eandroidruntime19375 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava8091130 163356423 eandroidruntime19375 at comandroidinternaloszygoteinitmainzygoteinitjava5761130 163356423 eandroidruntime19375 at dalviksystemnativestartmainnative methodany help or hint would be deeply grateful i have already wasted around 4 hours without luck,['android'] +588481,supporting linuxtypesh osx i am trying to cross compile an application using osx however when i compile i get the followingfatal error linuxtypesh file not foundwhen i change to systypesh and now i get error unknown type name s32 unknown type name u8 unknown type name u16 etccan someone help me with how to handle this,['c++'] +588496,is there a reason declval returns add rvalue reference instead of add lvalue reference changing a type into a reference to a type allows one to access the members of the type without creating an instance of the type this seems to be true for both lvalue references and rvalue referencesdeclval is implemented with add rvalue reference instead of add lvalue reference is this just a convention or are there examples of use where add rvalue reference is preferableedit i suppose i was slightly vague these answers are all very good but touch on slightly different points there are two different answers of use proposed howard emphasized that you can choose which reference your type has making add rvalue reference more flexible the other answers emphasize that the default behavior automatically chooses references which reflect the inputed type more naturally i do not know what to pick if somebody could add two simple examples motivating the need for each property respectively then i will be satisfied,['c++'] +588503,virtualprotect and kernel32dll attempt to access invalid address i am analyzing various modules loaded by the process unfortunately i am not able to create the kernel32dll memory snapshot although the function works properly with other modules eg ntddldll the problem is with the following code copy code from memory if virtualprotectbytevirtualaddress sizeofcode page execute readwrite flags 0 stdcout virtualprotect failed stdendl stdcout virtual address virtualaddress stdendl stdcout size of code sizeofcode stdendl stdcout error code getlasterror stdendlthe result of calling this code for kernel32dll isvirtual address 747d0size of code 6a0error code 0x1e7the error description says that error invalid address487 0x1e7attempt to access invalid address i checked the process memory map and kernel32dll address is correct whats the cause,['c++'] +588524,rails 4 rsolrerrorhttp rsolrerrorhttp 404 not found i am in the process of upgrading my app to rails 4 and now got my rails server as well as sunspot solr after a lot of tinkering to run i can access solr admin page however when i try to access solr from my rails development app to do search or index i get the following errorrsolrerrorhttp rsolrerrorhttp 404 not founderror not foundrequest data fqtype3amatchfqdate in utc d3a7b20135c115c29t215c3a005c3a00zto2a7dfqapproval s3aapprovedsortdate dascqlondonfl2ascoreqfcaption text5e10city name text5e10team name text5e10deftypeethismaxstart0rows30backtrace usersbasharrvmgemsruby200p353gemsrsolr109librsolrclientrb268in adapt responseusersbasharrvmgemsruby200p353gemsrsolr109librsolrclientrb175in executeusersbasharrvmgemsruby200p353gemsrsolr109librsolrclientrb161in send and receiveusersbasharrvmgemsruby200p353gemssunspot rails210libsunspotrailssolr instrumentationrb16in block in send and receive with as instrumentationusersbasharrvmgemsruby200p353gemsactivesupport401libactive supportnotificationsrb159in block in instrumentusersbasharrvmgemsruby200p353gemsactivesupport401libactive supportnotificationsinstrumenterrb20in instrumentusersbasharrvmgemsruby200p353gemsactivesupport401libactive supportnotificationsrb159in instrumentusersbasharrvmgemsruby200p353gemssunspot rails210libsunspotrailssolr instrumentationrb15in send and receive with as instrumentationeval2in postusersbasharrvmgemsruby200p353gemssunspot210libsunspotsearchabstract searchrb45in executeusersbasharrvmgemsruby200p353gemssunspot210libsunspotsessionrb59in search a hreftxmtopenurlfileusersbasharrailsprojectsmyappappmodelsmatchrbampline474ampcolumn1appmodelsmatchrb474in upcoming gamesa a hreftxmtopenurlfileusersbasharrailsprojectsmyappappcontrollerstickets controllerrbampline34ampcolumn1appcontrollerstickets controllerrb34in searcha rendered usersbasharrvmgemsruby200p353gemsactionpack401libaction thispatchmiddlewaretemplatesrescues sourceerb 04ms rendered usersbasharrvmgemsruby200p353gemsactionpack401libaction thispatchmiddlewaretemplatesrescues traceerb 08ms rendered usersbasharrvmgemsruby200p353gemsactionpack401libaction thispatchmiddlewaretemplatesrescues request and responseerb 08ms rendered usersbasharrvmgemsruby200p353gemsactionpack401libaction thispatchmiddlewaretemplatesrescuesdiagnosticserb within rescueslayout 173msthis is the sunspotyml fileproduction solr hostname envwebsolr url port 80 log level warning path solrproduction read timeout 2 open timeout 05development solr hostname 192168011 port 8981 log level info path solrdevelopmenttest solr hostname localhost port 8981 log level warning path solrtesti verified solr is data is in the right path i know there are similar posts but their solutions did not work i tried to comment path or use solrdefault or just solr or use the ip instead of localhost to no availany idea tips on how i can see where the rails suntspot solr request is trying to reach,['ruby-on-rails'] +588531,in what net languages can a class derive from its own nested class in c trying to compile the following code yields an error circular base class dependency involving a and abpublic class a ab public class b however i am looking at a 3rd party dll via a decompiler and seeing this structure how is this possible i can only assume the third party dll was written in some other net language but what language and what was the syntax,['c#'] +588583,loading cookies from selenium to mechanize with cookielib i am trying to login to a website with selenium then transfer the cookie to mechanize i have successfully logged in with selenium and saved its session cookie to a variable the problem comes when trying to load the cookie with cookielibrelevant coding loging in to website with seleniumcookie browserget cookies save the session cookie from selenium to variable cookie starting up mechanizecj cookieliblwpcookiejar cjset cookiecookie load cookie from seleniumthe problem appear when setting the cookie with cjset cookie function and i get the following error messagefile cookielibpy line 1627 in set cookieif cookiedomain not in c ccookiedomain attributeerror list object has no attribute domain,['python'] +588713,overflowhidden on inlineblock adds height to parent i am certain this has been asked before in some form or other but i just cannot find an answeri have some nested divsdiv classparent div classchildadivdivand the child has thisplayinlineblock and overflowhiddenparent backgroundcolorredchild backgroundcolorgreen thisplayinlineblock overflowhidden and it gets rendered like thisyou can notice that the parent is 5px higher than the child where does the extra height come from here is the sample editi do not want to remove thisplayinlineblock or overflowhidden this is a simplified example to illustrate the problem but in my real layout i need them bothi just want to understand why this extra height appears is it specified somewhere that it should be like this is it a consequence of some other css feature,"['html', 'css']" +588765,why does this implementation of strlen work thisclaimer i have seen this question and i am not reasking it i am interested in why the code works and not in how it worksso heres this implementation of apples well freebsds strlen it uses a wellknown optimization trick namely it checks 4 or 8 bytes at once instead of doing a bytebybyte comparison to 0size t strlenconst char str const char p const unsigned long lp skip the first few bytes until we have an aligned p for p str uintptr tp longptr mask p if p 0 return p str scan the rest of the string using word sized operation for lp const unsigned long p lp if lp mask01 mask80 p const char lp testbyte0 testbyte1 testbyte2 testbyte3if long bit 64 testbyte4 testbyte5 testbyte6 testbyte7endif notreached return 0now my question is maybe i am missing the obvious but cannot this read past the end of a string what if we have a string of which the length is not divisible by the word size imagine the following scenario all your memories are belong to us not our memory a b c d 0 long word 1 long word 2when the second long word is read the program accesses bytes that it should not in fact be accessing is not this wrong i am pretty confident that apple and the bsd folks know what they are doing so could someone please explain why this is correctone thing i have noticed is that beerboy asserted this to be undefined behavior and i also believe it indeed is but he was told that it is not because we align to word size with the initial for loop not shown here however i do not see at all why alignment would be any relevant if the array is not long enough and we are reading past its end,['c'] +588841,python urlparseurlparseurlhostname return none value after loging in on a website i want to collect its links this i do with this function using mechanize and urlparse librariesbr mechanizebrowser logging in on websitefor link in brlinks url urlparseurljoinlinkbase url linkurl hostname urlparseurlparseurlhostname path urlparseurlparseurlpath print hostname by printing this i found it to be the source of the none value mylinksappendhttp hostname pathand i get this error message mylinksappendhttp hostname pathtypeerror cannot concatenate str and nonetype objectsi am not sure on how to fix this or even if it can be fixed at all is there any way to force the function to append even if it would produce a nonworking and weird result for the none valuealternatively what i am really after in the link is what the link ends with for example the html code for one of the links look like this what i am after is the world lexiktd classcenter a hrefhttpunimportantpartoflinklexiklexikatdso an alternative route would be if mechanize can just collect this value directly bypassing the links and none value troubles,['python'] +588857,how to overcame htmlunit scriptexception i got a problem with a line of code that probably triggers some js function e couse an exception how can i fix thisboxsettextlinktostringclientwaitforbackgroundjavascriptstartingbefore10boxdblclick this line cause the exceptionexception in thread main exception start ecmaerror linenumber0 column0 linesourcefunction namereferenceerror sourcenameonclick event for htmldivisiondiv class 119 stat elem focus target mtm mbl 5bsm 6dh 51z6 idu 0 k datalocationmaincolumn onclickbootloaderloadcomponentsquotcomposerxcontrollerbootloadquot emptyfunction in fb noscript1 messagereferenceerror bootloader is not definedcomgargoylesoftwarehtmlunitscriptexception referenceerror bootloader is not defined at comgargoylesoftwarehtmlunitjavascriptjavascriptenginehtmlunitcontextactionrunjavascriptenginejava684 at netsourceforgehtmlunitcorejsjavascriptcontextcallcontextjava602 at netsourceforgehtmlunitcorejsjavascriptcontextfactorycallcontextfactoryjava507 at comgargoylesoftwarehtmlunitjavascriptjavascriptenginecallfunctionjavascriptenginejava616 at comgargoylesoftwarehtmlunitjavascriptjavascriptenginecallfunctionjavascriptenginejava591 at comgargoylesoftwarehtmlunithtmlhtmlpageexecutejavascriptfunctionifpossiblehtmlpagejava985 at comgargoylesoftwarehtmlunitjavascripthosteventlistenerscontainerexecuteeventhandlereventlistenerscontainerjava210 at comgargoylesoftwarehtmlunitjavascripthosteventlistenerscontainerexecutebubblinglistenerseventlistenerscontainerjava230 at comgargoylesoftwarehtmlunitjavascripthostnodefireeventnodejava804 at comgargoylesoftwarehtmlunitjavascripthostnodefireeventnodejava738 at comgargoylesoftwarehtmlunithtmlhtmlelement1runhtmlelementjava869 at netsourceforgehtmlunitcorejsjavascriptcontextcallcontextjava602 at netsourceforgehtmlunitcorejsjavascriptcontextfactorycallcontextfactoryjava507 at comgargoylesoftwarehtmlunithtmlhtmlelementfireeventhtmlelementjava874 at comgargoylesoftwarehtmlunithtmlhtmlelementdoclickfireclickeventhtmlelementjava1311 at comgargoylesoftwarehtmlunithtmlhtmlelementclickhtmlelementjava1253 at comgargoylesoftwarehtmlunithtmlhtmlelementclickhtmlelementjava1205 at comgargoylesoftwarehtmlunithtmlhtmlelementdblclickhtmlelementjava1351 at comgargoylesoftwarehtmlunithtmlhtmlelementdblclickhtmlelementjava1326 at prototypeprofilepostlinkonwallprofilejava225 at htmllogfindnextlogjava150 at prototypeprtpmainprtpjava49caused by netsourceforgehtmlunitcorejsjavascriptecmaerror referenceerror bootloader is not defined at netsourceforgehtmlunitcorejsjavascriptscriptruntimeconstructerrorscriptruntimejava3603 at netsourceforgehtmlunitcorejsjavascriptscriptruntimeconstructerrorscriptruntimejava3587 at netsourceforgehtmlunitcorejsjavascriptscriptruntimenotfounderrorscriptruntimejava3657 at netsourceforgehtmlunitcorejsjavascriptscriptruntimenameorfunctionscriptruntimejava1749 at netsourceforgehtmlunitcorejsjavascriptscriptruntimenamescriptruntimejava1690 at netsourceforgehtmlunitcorejsjavascriptinterpreterinterpretloopinterpreterjava1622 at netsourceforgehtmlunitcorejsjavascriptinterpreterinterpretinterpreterjava798 at netsourceforgehtmlunitcorejsjavascriptinterpretedfunctioncallinterpretedfunctionjava105 at netsourceforgehtmlunitcorejsjavascriptcontextfactorydotopcallcontextfactoryjava405 at comgargoylesoftwarehtmlunitjavascripthtmlunitcontextfactorydotopcallhtmlunitcontextfactoryjava309 at netsourceforgehtmlunitcorejsjavascriptscriptruntimedotopcallscriptruntimejava3031 at netsourceforgehtmlunitcorejsjavascriptinterpretedfunctioncallinterpretedfunctionjava103 at comgargoylesoftwarehtmlunitjavascripthosteventhandlercalleventhandlerjava81 at comgargoylesoftwarehtmlunitjavascriptjavascriptengine4dorunjavascriptenginejava609 at comgargoylesoftwarehtmlunitjavascriptjavascriptenginehtmlunitcontextactionrunjavascriptenginejava669 21 moreenclosed exception netsourceforgehtmlunitcorejsjavascriptecmaerror referenceerror bootloader is not defined at netsourceforgehtmlunitcorejsjavascriptscriptruntimeconstructerrorscriptruntimejava3603 at netsourceforgehtmlunitcorejsjavascriptscriptruntimeconstructerrorscriptruntimejava3587 at netsourceforgehtmlunitcorejsjavascriptscriptruntimenotfounderrorscriptruntimejava3657 at netsourceforgehtmlunitcorejsjavascriptscriptruntimenameorfunctionscriptruntimejava1749 at netsourceforgehtmlunitcorejsjavascriptscriptruntimenamescriptruntimejava1690 at netsourceforgehtmlunitcorejsjavascriptinterpreterinterpretloopinterpreterjava1622 at scriptonclickonclick event for htmldivisiondiv class 119 stat elem focus target mtm mbl 5bsm 6dh 51z6 idu 0 k datalocationmaincolumn onclickbootloaderloadcomponentsquotcomposerxcontrollerbootloadquot emptyfunction in fb noscript1 at netsourceforgehtmlunitcorejsjavascriptinterpreterinterpretinterpreterjava798 at netsourceforgehtmlunitcorejsjavascriptinterpretedfunctioncallinterpretedfunctionjava105 at netsourceforgehtmlunitcorejsjavascriptcontextfactorydotopcallcontextfactoryjava405 at comgargoylesoftwarehtmlunitjavascripthtmlunitcontextfactorydotopcallhtmlunitcontextfactoryjava309 at netsourceforgehtmlunitcorejsjavascriptscriptruntimedotopcallscriptruntimejava3031 at netsourceforgehtmlunitcorejsjavascriptinterpretedfunctioncallinterpretedfunctionjava103 at comgargoylesoftwarehtmlunitjavascripthosteventhandlercalleventhandlerjava81 at comgargoylesoftwarehtmlunitjavascriptjavascriptengine4dorunjavascriptenginejava609 at comgargoylesoftwarehtmlunitjavascriptjavascriptenginehtmlunitcontextactionrunjavascriptenginejava669 at netsourceforgehtmlunitcorejsjavascriptcontextcallcontextjava602 at netsourceforgehtmlunitcorejsjavascriptcontextfactorycallcontextfactoryjava507 at comgargoylesoftwarehtmlunitjavascriptjavascriptenginecallfunctionjavascriptenginejava616 at comgargoylesoftwarehtmlunitjavascriptjavascriptenginecallfunctionjavascriptenginejava591 at comgargoylesoftwarehtmlunithtmlhtmlpageexecutejavascriptfunctionifpossiblehtmlpagejava985 at comgargoylesoftwarehtmlunitjavascripthosteventlistenerscontainerexecuteeventhandlereventlistenerscontainerjava210 at comgargoylesoftwarehtmlunitjavascripthosteventlistenerscontainerexecutebubblinglistenerseventlistenerscontainerjava230 at comgargoylesoftwarehtmlunitjavascripthostnodefireeventnodejava804 at comgargoylesoftwarehtmlunitjavascripthostnodefireeventnodejava738 at comgargoylesoftwarehtmlunithtmlhtmlelement1runhtmlelementjava869 at netsourceforgehtmlunitcorejsjavascriptcontextcallcontextjava602 at netsourceforgehtmlunitcorejsjavascriptcontextfactorycallcontextfactoryjava507 at comgargoylesoftwarehtmlunithtmlhtmlelementfireeventhtmlelementjava874 at comgargoylesoftwarehtmlunithtmlhtmlelementdoclickfireclickeventhtmlelementjava1311 at comgargoylesoftwarehtmlunithtmlhtmlelementclickhtmlelementjava1253 at comgargoylesoftwarehtmlunithtmlhtmlelementclickhtmlelementjava1205 at comgargoylesoftwarehtmlunithtmlhtmlelementdblclickhtmlelementjava1351 at comgargoylesoftwarehtmlunithtmlhtmlelementdblclickhtmlelementjava1326 at prototypeprofilepostlinkonwallprofilejava225 at htmllogfindnextlogjava150 at prototypeprtpmainprtpjava49 calling javascript function native code arity0 exception end the box where i write acts on a normal browser a reformatting function which is not performed using htmlunit so i tried to force it with a dbclick,"['java', 'javascript']" +588905,php setcookie not working i have made a login that sets a cookie with a value of the imputed email address so in the globalphp file it stores an array of the users data usingemail cookiepeoplehubgetuserdata mysqli querycon select from earth where emailemailuserdata mysqli fetch arraygetuserdata mysqli assocthe cookie is not being set i know this because i made a test fileecho cookiepeoplehubit just made a blank pagethe login code where the cookie is setphp include globalphp h2loginh2php echo we currently have b usercount b members b onlinecount b of which are online brbrphp ifisset postemail email postemail password sha1 postpassword check mysqli querycon select from earth where emailemail and passwordpassword check mysqli num rowscheck ifcheck 1 setcookiepeoplehub email 0 echo we logged you in else echo we could not log you in form actionphp echo serverrequest uri methodpost email input nameemail placeholderemail address required typetextbr password input namepassword placeholderpassword required typepasswordbr input typereset valuestart over input typesubmit valueloginform,['php'] +588951,uiscrollview not scrolling in ios7 with autolayout on i have a uiscrollview with a 6 textfields in it and a button inside of it there is not enough content in the scrollview to make it scrollbut when the keyboard shows i would like the scrollview to scroll so the user does not have to thismiss the keyboard in order to select another textfield that is hidden by the keyboardi am using ios7 and have autolayout enabledany suggestionsi am using storyboards and the only code i have is the followingregh fileinterface registerviewcontroller uiviewcontroller uitextfielddelegate uiscrollviewdelegate,"['ios', 'objective-c']" +588969,invalid glyph index when setting viewcontrollers layoutmanager for nstextstorage subclass my goal is to use textkit to italicize set the text size etc of certain words to start i am only trying to highlight a character in my text string being new to textkit and truthfully to programming in general i am following the syntax highlighting topic of obcio issue 5 when using the nslayoutmanager builtin to the uitextview i created my text appears on screen with no thrown exceptions when i set my uitextview as the layout manager of my nstextstorage subclass in my view controller below i receive errors for an exception for invalid glyph indexs textstorage bbrsyntaxhighlighttextstorage new textstorage addlayoutmanager selfreadertextviewlayoutmanagerthe console output is below nslayouttreelinefragmentrectforglyphatindex invalid glyph index 52820131201 152324949 biblereader6070b nsglyphtreeinvalidateglyphsforcharacterrange invalid char range 120131201 152324956 biblereader6070b nslayouttreelinefragmentrectforglyphatindex invalid glyph index 52820131201 152324957 biblereader6070b nsglyphtreeinvalidateglyphsforcharacterrange invalid char range 120131201 152324957 biblereader6070b nsglyphtreeinvalidateglyphsforcharacterrange character count mismatch20131201 152324958 biblereader6070b nslayouttreelinefragmentrectforglyphatindex invalid glyph index 404020131201 152324959 biblereader6070b nsglyphtreeinvalidateglyphsforcharacterrange invalid char range 1i have read through apples text programming guide many times and think i understand how the text system is established but have no idea why my glyph count would exceed the number of glyphsi created gists for my viewcontroller and nstextstorage subclass here and here respectively,"['ios', 'objective-c']" +588971,no longer able to hide keyboard during viewwillthisappear in ios7 the following code used to work in ios6 to hide the keyboard when a view controller was popped off of the navigation stack voidviewwillthisappearboolanimated selfview endeditingyes super viewwillthisappearanimatedhowever in ios7 the selfview endeditingyes line seems to get ignored i tried the command in other view events viewdidthisappear viewwillappear and viewdidappear and the only one it worked in is viewdidappear it seems that once a pop is initiated we lose the ability to hide the keyboard until the view controller is pushed back on the stackwhile placing the code in viewdidappear does work to hide the keyboard the bad thing is that the keyboard is thisplayed briefly when the viewcontroller is pushed back on to the navigation stackpretty unacceptable from a ui perspectivehas anyone else had success in working around this issue i would prefer not to have to write my own cancel button but right now that is the only thing i can think of that will work,"['ios', 'objective-c']" +588991,how to thisplay image after selecting path in fileupload controller without clicking recently i have been developing web form application in aspnet ci have an image controlaspimage idavatar runatserver height225px imageurlimagesnouserjpg width225px and fileupload button controlaspfileupload idavatarupload runatserver aspbutton idbtnupload runatserver textupload onclickupload when user click button then upload code is executed the image is sent to the database problem is that i like to thisplay the image which the user selected in avatar image controller before the user clicks desperate buttonis that possible to do this automatically,"['c#', 'asp.net']" +589022,check if a keyword is in a string i have a list of keywords and i want to be able to find if a string contains any of those keywords right now the solution i have takes on is there a quicker way of doing this search without looping through each keywords and doing a comparisoncontains iekeywords cat hat mat bat fat sat rat pat foo bar foobarstring there is a cat in the box the result of this is true because cat matches one of the words in the keywords edit i guess i was not as clear when i said on i mean to say on where nnumber of keywords,['java'] +589083,express js static relative parent directory i am currently experiencing some minor problems with serving static files through expressjsmy directory structure is as followingpubliccsslibsrcviewshomeindexhtmlserverjsin my indexhtml file i have prefixed all my assets with a leading slashmy static setup is as followingappuseexprestaticpathresolve dirname publicbut for some reason my static files are not getting servedi was thinking that this is a crossdomain call or somethingi am currently using cloud9 ide might this have to do with it somehow,['javascript'] +589093,odd css syntax classicon class icon i am going through someone elses css code at the moment and found something i have not seen before nor am i able to find anything on w3c schools about these types of selectors google also does not return anything if i type in class classicon class icon thisplayinlineblock backgroundurlimagesspritepng norepeat 0 0 bordernone textaligncenter verticalalignmiddle thisplayinline zoom1 would appreciate it if someone could shed some light on this please,['css'] +589129,remove the searchicon as hint in the searchview i am doing an application where for example when i click on the imageit is a searchview the search pad opens and it looks likebut here the default search icon magnifier gets thisplayed but this thissappears as soon as some text is enteredbut i dont want that magnifier to be thisplayed even the image is clicked for the first timeand here i am not using any xml file my code is public class mainactivity extends activity suppresslintnewapi override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate relativelayout relative new relativelayoutthis layoutparams params new layoutparamslayoutparamsmatch parentlayoutparamsmatch parent relativesetlayoutparamsparams setcontentviewrelative searchview searchview new searchviewthis traverseviewsearchview 0 searchviewseticonifiedbydefaultfalse layoutparams searchviewparams new layoutparamslayoutparamswrap contentlayoutparamswrap content searchviewparamsaddrulerelativelayoutalign parent right searchviewsetlayoutparamssearchviewparams relativeaddviewsearchview targetapibuildversion codeshoneycomb suppresslintnewapi private void traverseviewview view int index if view instanceof searchview searchview v searchview view forint i 0 i vgetchildcount i traverseviewvgetchildati i else if view instanceof linearlayout linearlayout ll linearlayout view forint i 0 i llgetchildcount i traverseviewllgetchildati i else if view instanceof edittext edittext viewsettextcolorcolorgreen edittext viewsethinttextcolorcolorblack else if view instanceof textview textview viewsettextcolorcolorblue else if view instanceof imageview imageview viewsetimageresourcerdrawableic launcher else logvview scout undefined view type here,['android'] +589132,visual studio 2013 net 451 edit and continue 64 bit not working supposedly vs 2013 added support for edit and continue 64 bit see however i cannot get it workingafter going to the properties of my net 451 aspnet mvc web application project and checking the enable edit and continue checkbox i can now edit the code while on a breakpointthe problem is that after saving and trying to keep on stepping trough i get an error dialog saying edits were made which cannot be compiled execution cannot continue until compile errors are fixedin the error list window those 2 errors always showthe type systemiequatable1 is defined in an assembly that is not referenced you must add a reference to assembly systemruntime version40 cultureneutral publickeytokenb03f5f7f11d50a3a the type systemvaluetype is defined in an assembly that is not referenced you must add a reference to assembly systemruntime version40 cultureneutral publickeytokenb03f5f7f11d50a3ait is really weird error message right however insignificant my change is i always get the same errornote i run windows 7 vs 2013 ultimate and my project is set up to use iis express in the project properties,['.net'] +589138,unable to retrieve data from sqlite db on sd card on wp8 i have created a sqlite db using systemdatasqlite in a console app i have then moved this to the windows phones sd cardi followed these instructions to add sqlite support to my wp8 appi locate the db file and open it like soexternalstoragefile file null ienumerableexternalstoragedevice storagedevices await externalstoragegetexternalstoragedevicesasync foreach externalstoragedevice storagedevice in storagedevices try file await storagedevicegetfileasyncnorthislandnztopomap catch file null if file null break sqliteconnection conn new sqliteconnectiondata source filepath version3read onlytruefailifmissingtrue sqlitecommand command new sqlitecommand dbnorthisland commandcommandtext select count from tiles int count intcommandexecutescalarintthis results in the following errorsqlitesqliteexception no such table tiles at sqlitesqlite3prepare2database db string query at sqlitesqlitecommandprepare at sqlitesqlitecommandexecutescalartinterestingly i have also tried the following sql statementselect count from sqlite master where typetablewhich gives a result of 0 suggesting my tiles table cannot be foundi suspect that externalstoragefilepath is returning a path that sqlite is unable to resolve as an existing file leading it to create a new database and so complain about the missing table when i try to access itthis microsoft article seems to suggest that i should be able to access files from the sd card from my appfeedback provided by a microsoft employeeyour app does not have direct access to the files on the sd card it cannot open them directly with file system api but needs to use the externalstoragefile and externalstoragefolder interfaces from windowsstorage to quote from reading from the sd card on windows phone 8windows phone apps can read specific file types from the sd card using the microsoftphonestorage apisi expect that the sqlite implementation for the phone tries to open the database using standard c file api rather than using the storage objects and so requires that the database be in the xap or isolated storage and cannot access a database on the sd card this is definitely the case for sqlite for windows store appsin theory it would be possible to update sqlite to use storage objects but i suspect it would be a significant project to do soexample barebones projecti have created a barebones example project that highlights my issue just in case anyone wants to look and potentially try out any ideas quicklyidde82af8533ac6d28242ithintfilezipauthkeyaf4iwci0g7bsdfecopy the bx24nztopomap file to the root of your sd card to testfeedback from sqlite sdk communityapparently it should be fairly straight forward to add support to the sqlite sdk for someone with some c skills mine are a bit rustyrepliesto my original question anyone know of a sqlite library for windows phone that can read from the sd card,['c#'] +589148,any functional programming method of traversing a nested dictionary i am trying to find a better way to implement thisd a b c 4 l a b cfor x in l d dxprint d 4 i am learning functional programming so i am just trying random example that come to my head,['python'] +589153,in the c ifelse statement should the condition which is more likely to be true come first i happened to write a ifelse statement the condition would be false at most timecheck a static pointer is assigned or not which one would be better for the compiler to optimize or they are just equal the function would be called so many times so it is critical to optimize its performance void foo static int p null if p null p int malloc size sizeofint do something here void foo static int p null if p null do something here else p int malloc size sizeofint do something,['c'] +589172,angularjs whats the best practice to add ngif to a directive programmatically i want to create a directive that checks if an element should be present in the dom based on a value coming from a service eg check for a user rolethe corresponding directive looks like thisangularmoduleapp directiveaddcondition functionrootscope return restrict a compile function element attr var ngif attrngif value rootscopeevalattraddcondition make sure to combine with existing ngif i want to modify the expression to be evalued by ngif here based on a role check for example if ngif value ngif attrsetngif value at the end the element has the ngif attribute attached but somehow it does not apply to the element and it is still existing in the dom so this is obviously a wrong approach this fiddle shows the problem who can explain why this happens is there any other way a similar behaviour could be achieved existing ngifs should be consideredsolutionusage div rlnrequirerolesadmin useri am hidden when theses role requirements are not satifisfieddivdirectiverlnrequireroles function animate session return transclude element priority 600 terminal true restrict a link function scope element attr ctrl transclude var block childscope roles attrobserverlnrequireroles function value roles scopeevalvalue if sessionhasrolesroles if childscope childscope scopenew transcludechildscope function clone block startnode clone0 endnode cloneclonelength documentcreatecomment end rlnrequireroles attrrlnrequireroles animateenterclone elementparent element else if childscope childscopedestroy childscope null if block animateleavegetblockelementsblock block null it is very important to add the priority in the directive otherwise other directives attached to that element are not evaluated,['javascript'] +589186,is it possible to get a string that would containing namespace and class name at compile time i wonder how to define a macro that would for given class name output its namespace and class name in a format like namespacesubnamespaceclassname so writting something like this myclasshinclude stringnamespace ns namespace sns class myclass static stdstring str myclasscppinclude myclasshusing namespace stdstring nssnsmyclastr super macroparams if needed yet none would be preferedi want to get str to be nssnsmyclass i would love that macro have as fiew params if possible meaning one or nonealternatively i wonder if such thing can be done using templates with something likestring nssnsmyclastr gettypenameformaternssnsmyclasshow to do such thing using boost stl and having only c03 at hand,['c++'] +589379,got hacked what does this php code do and how should i avoid i was hacked and apparently they were sending spam emails there were two files that they injected into my server that were duplicated across all subdirectories one is a heavily hashed php file that may be the sender the code below is from the other fileheres my question what is this accomplishing i cannot translate its purpose also what should i do to avoid allowing this to happen againphpifmd5 postpass692e3f52ee6f16bc78fa6e1ec4bd4a6a dieextract postifemptya abifempty filestmp name include filestmp name,['php'] +589392,bootstrap 3 horizontal scrollable row website design i am trying to make a horizontal scroll web page using bootstrap 3 this is what i have tried so far media minwidth768px container width100maincontent minheight 100 height auto maincontent row overflowxscroll overflowyhidden maincontent row classcollg maincontent row classcolmd maincontent row classcolsm floatlefti tried with the jquery method which mentioned in this thread but it is not scrolling even after the width has been set to row class the collg classes as thisplayed here i also tried to set height to row class by getting the height of collg height but still not succeededwhat i wanted to achieve iscollg colmd and colsm classes should need to be scrolled with it is respective width content the number of cols may vary according to the datain colxs there is no change in the default behavior this is the work place can anyone suggest a workaround css jquery,"['jquery', 'css']" +589401,java multithreading thread priority can anybody explain how thread priority works in java the confusion here is if java doesnt guarantee the implementation of the thread according to its priority then why is this setpriority function used formy code is as follows public class threadsynchronization implements runnable public synchronized void run systemoutprintlnstarting implementation of thread threadcurrentthreadgetname forint i0i10i systemoutprintlnthread threadcurrentthreadgetname value i systemoutprintlnending implementation of thread threadcurrentthreadgetname public static void mainstring args systemoutprintlnprogram starts threadsynchronization th1 new threadsynchronization thread t1 new threadth1 t1setpriority1 synchronizedt1 t1start threadsynchronization th2 new threadsynchronization thread t2 new threadth2 t2setpriority9 synchronized t2 t2start systemoutprintlnprogram ends in the above program even if i change the priority i find no difference in the outputalso a real time application of how thread priority can be used would be of great helpthanks,['java'] +589404,codeception keep a logged in state i want to keep or run the login before most of my tests but if i try to move the login code to before it does not work since there is no webguy instance available to mewhat is the best way to keep the session between multiple tests this is my code so far would be glad to receive some help i have googled and checked the documentation but i cannot find anything about session stuffphpuse webguyclass productcest private product id 1 public function before public function after tests public function loginwebguy i iseeincurrenturlauthlogin ifillfieldinputtypeemail ifillfieldinputtypepassword 1234 iclicksignin submit iwait500 iseeincurrenturlaccount depends login public function chooseproductwebguy i iwanttogo to products and choose one iamonpageproduct thisclient id,['php'] +589410,pycallgraph with pycharm does not work i am using mac os x and trying to setup pycallgraphive installed pycallgraph with pip and graphviz with homebreweverything works from shell but not from pycharm from pycallgraph import pycallgraphfrom pycallgraph import configfrom pycallgraph import globbingfilterfrom pycallgraphoutput import graphvizoutputconfig configconfigtrace filter globbingfilterexclude pycallgraphgraphviz graphvizoutputoutput filefilter excludepngwith pycallgraphoutputgraphviz configconfig def my fun print hello my funusersuserprojectspy27binpython usersuserprojectspy27 djangotest2pytraceback most recent call last file usersuserprojectspy27 djangotest2py line 15 in module with pycallgraphoutputgraphviz configconfig file usersuserprojectspy27libpython27sitepackagespycallgraphpycallgraphpy line 32 in init selfreset file usersuserprojectspy27libpython27sitepackagespycallgraphpycallgraphpy line 53 in reset selfprepare outputoutput file usersuserprojectspy27libpython27sitepackagespycallgraphpycallgraphpy line 97 in prepare output outputsanity check file usersuserprojectspy27libpython27sitepackagespycallgraphoutputgraphvizpy line 63 in sanity check selfensure binaryselftool file usersuserprojectspy27libpython27sitepackagespycallgraphoutputoutputpy line 96 in ensure binary the command is required to be in your pathformatcmdpycallgraphexceptionspycallgraphexception the command dot is required to be in your pathprocess finished with exit code 1hereusersuserprojectspy27 virtualenv dirusersuserprojectspy27 django project dir what does it want from me,['python'] +589434,collision detection not working in unity 2d i have two 2d game objects they each have a box collider 2d and a rigid body 2d which is not kinematic when the game plays one moves towards the other and collides with ithowever i also have the following method in the moving gameobjectvoid oncollisionentercollision collision print collided with someone the print statement never prints so presumably the method is never called where am i going wrong,['c#'] +589614,mvc 5 ioc and authentication i am just about to start on a project where i will be using mvc5 but as i want to use ioc and later reuse my user tables and add custom stuff to it i am finding it very hard to see how i can use the new identity framework that came with mvc5i am more and more looking towards basic forms auth what are your solutionsmy needsuser repositoryservice must be injecteduser repository must reside in the daluser repository must be able to support other technologies than efauthentication with openid and oauth must be somewhat easy to implementmust be secureshould be reusable in other projects eg wpfi have been looking for a long time for an answer but everything i see is hardcoded in the controllerhow are you solving this are you writing most from scratch or can you bind into something that will scale to other net platforms as wcf and wpfthe below code is taken directly from the accountcontroller in the default aspnet mvc 5 templatethe first thing it does is a bastard injectionauthorizepublic class accountcontroller controller public accountcontroller this new usermanagerapplicationuser new userstoreapplicationuser new applicationdbcontext public accountcontrollerusermanagerapplicationuser usermanager usermanager usermanager the accepted answer will go to the person that shows me what they have done that incorporates the above requirements,['c#'] +589641,how to spring ioc and httpclient 431 closeablehttpclient i would like to have spring ioc configure a closeablehttpclient object and inject it into my class so that customization of its configuration can be done via xmlfrom what i can see httpclient seems to resist this pattern quite forcibly they want you to do things likecloseablehttpclient chc httpclientscustomsetthing that should be a propertybuildickis there not some mechanism for making a singleton closeablehttpclient bean that i can then use,['java'] +589645,pass multiple arguments into stdthread i am asking the thread library in c11 standard say you have a function like void func1int a int b obja c objb d blahblah implementationint mainint argc char argv stdthreadfunc1 what do do herehow do you pass in all of those arguments into the thread i tried listing the arguments like stdthreadfunc1 abcdbut it complains that there is no such constructor one way to get around this is defining a struct to package the arguments but is there another way to do this,['c++'] +589686,opencv taking a 3 channel rgb image splitting channels and viewing an image with only rg i wanted to look at only the rg channels in an rgb image because i get better contrasts to detect an object when the blue channel is removed i used opencv to split the channelsbut while merging the same after setting the blue channel to 0 my code does not compileinclude opencv2corecorehppinclude opencv2highguihighguihppinclude iostreamusing namespace cvusing namespace stdint main int argc char argv if argc 2 cout usage thisplay image imagetoloadandthisplay endl return 1 mat imagefin img image imreadargv1 cv load image color read the file if imagedata check for invalid input cout could not open or find the image stdendl return 1 namedwindow thisplay window cv window autosize create a window for thisplay show our image inside it create windows namedwindowred1 namedwindowgreen1 namedwindowblue1 create matrices make sure there is an image in input mat channel3 imshow original image image the actual splitting splitimage channel channel0matzerossizeimagerows imagecols cv 8uc1set blue channel to 0 merging red and green channels mergechannelimage imshowrg image waitkey0wait for a keystroke in the window return 0could i have any feedback on where i am going wrong i suspect it is with setting the blue channel to 0 is there any better way to set it to 0is there a way to use cvmixchannels to do this,['c++'] +589717,possible to override system so library in app i have to modify the http live streaming implementation of android media playerthe implementation is under the stagefright library i think these library will compile to a libstagefrightso which should be part of the android systemmy question is if i make some changes to this library and compile a new libstagefrightsoif i load this new libstagefrightso in my new application and call up the media player will it use the code in my new libstagefrightso,['android'] +589722,evaluatingaccessing a structure consider the two slightly different versions of the same codestruct s int dummy1volatile struct s sint mainvoid s return 0andstruct s int dummy16volatile struct s sint mainvoid s return 0heres what i am getting with gcc 462 for them main pushl ebp movl esp ebp andl 16 esp call main movl s eax xorl eax eax leave ret comm s 4 2and main pushl ebp movl esp ebp andl 16 esp call main xorl eax eax leave ret comm s 64 5please note the absence of access to s in the second caseis it a compiler bug or am i just dealing with the following statement of the c standard and the gcc developers simply chose such a weird implementationdefinedness and are still playing by the ruleswhat constitutes an access to an object that has volatilequalified type is implementationdefinedwhat would be the reason for this difference i would naturally expect the whole structre being accessed or not accessed i am not sure irrespective of its size and of whats inside itps what does your compiler nongcc or newer gcc do in this case please answer this last question in a comment if that is the only part youre going to address as this is not the main question being asked but more of a curiosity question,['c'] +589818,hide language wpml i am using wpml language and cant find solution for next thingon the language switcher i want to hide language lets say for example he if current language is lets say for example ar so when we on arabic site we will not see on the selector the hebrew and same thing if we on hebrew the arabic will not thisplayon shorten words what i want is if we on arabic site the hebrew flag will be hiddenwhat i triedfunction language selector flags languages icl get languagesskip missing0 ifemptylanguages ificl language codeen order arrayar specify your sort order here elseificl language codeheorder arrayen ar specify your sort order here foreach order as l if issetlanguagesl l languagesl grab this language from the unsorted array that is returned by icl get languages thisplay whatever way you want i am just thisplaying flags in anchors css a floatleft thisplayblockwidth18pxheight12pxmargin0 2pxoverflowhiddenlineheight100px iflactive class active url else class url hreflurl echo a url stylebackgroundurllcountry flag url norepeat classflag class echo llanguage code its not affect at all the selector,['php'] +589864,rql get multple documents from list of keys rethinkdb in javascript so i have a table of person data which has a unique key id i have a list of ids that i want to get the data for which i will be sending as a json array from the client to the server the serve recieves that data as a json arraynow is there a way to run a query that will get the documents for each of those idsor is my only option to parse the ids myself and build an array of results then send that array backso far i have tried usinggetall but i cannot get this to work because it accepts a dynamic amount of parameters and i do not know how to change my array of values into a dynamic amount of parametersexample i want to be able to do whats shown below but i cannotrdbvptableusergetall0 0 99i can only do thisrdbvptableusergetall0 0 99expr and foreach as seen below but i do not think this can workvar arr rexpr0 0 99foreachfunctionid,['javascript'] +589875,how to json decode invalid json with apostrophe instead of quotation mark sample codephpjson foo barvar dump json decodejson it works with php 553 but it fails for lower phps versionsit works on my machine with php 553 but it fails everywhere elsei know it is incorrect json but my webservice gives me json with symbols together with foo bar test crazy markupsandboxhow to parse json data with apostrophes in php 53 obviously original json i want to parse is more complexi cannot upgrade my php on production server neither get proper json from webservice,['php'] +589889,how to stop css hyphenation no dash between words how do i stop words becoming hyphenatedeg supercalifragilisticexpialidociousshould just be supercalifragilisticexpialidocioustried the css below from css tricks but it doesnt seem to be working especially on safari any help mswordbreak breakall wordbreak breakall non standard for webkit wordbreak breakword webkithyphens auto mozhyphens auto hyphens auto,['css'] +589905,socket error errno 1 connection refused i am using simple python lib for the smtp but i am getting this errorimport smtplibsmtpobj smtplibsmtplocalhosttraceback most recent call last file stdin line 1 in module file usrlibpython27smtplibpy line 249 in init code msg selfconnecthost port file usrlibpython27smtplibpy line 309 in connect selfsock self get sockethost port selftimeout file usrlibpython27smtplibpy line 284 in get socket return socketcreate connectionport host timeout file usrlibpython27socketpy line 571 in create connection raise errsocketerror errno 1 connection refusedusing python27,['python'] +589995,android ble retrieve service uuid in onlescan callback when advertised from ios peripheral i am using nexus 4 kitkat as central and ipad as peripheralperipheral has a service which it is advertisingthe advertising packet has some data22bytes service uuidwhen i try to scan for the peripheral from android ipad peripheral is thiscoveredhowever when i try to get the service uuid from scanrecord parameter in the callback i could not find itall i get is the 20byte data which the peripheral is sendingwhen i try to scan for devices with the uuid i am not able to thiscover those peripheralsfollowing is the ios code to advertise a servicethe service id being used is 0192f01080805f9b34fbcbuuid serviceuuid cbuuid uuidwithstringtransfer service uuid selfperipheralmanager startadvertisingcbadvertisementdataserviceuuidskey serviceuuid cbadvertisementdatalocalnamekeybtleconfigs sharedbtleconfig getadvertizinguuidthe device gets thiscovered when i scan without service uuid device scan callbackprivate bluetoothadapterlescancallback mlescancallback new bluetoothadapterlescancallback override public void onlescanfinal bluetoothdevice device int rssi final byte scanrecord runonuithreadnew runnable override public void run how to retrieve the service id from scanrecord the services are thiscovered between two ios devices but between android device and ios peripheral its not workinghow to scan a peripheral with 16bit service uuidany help is appreciated,"['android', 'ios']" +589996,android alarm manager fires in strange times i used the following code to set repeating alarm every 5 minutespublic void setalarmcontext context alarmmanager amalarmmanagercontextgetsystemservicecontextalarm service intent i new intentcontext alarmclass pendingintent pi pendingintentgetbroadcastcontext 0 i 0 amsetrepeatingalarmmanagerrtc wakeup systemcurrenttimemillis 10 60 5 pi millisec second minute is seems to work fine it runs almost 20 hours and in the server i can see that some constant message arriveshowever there is something about the timesi want the times to be every five minutes and it seems like in the server i receives the messages in different times i add a first sequence of times when the server received messages when the phone was in sleep mode in the night051351051854052454052854053351053854055245055454055852060454060854061619061854062454062854063454064842064844065854and another sequence when i used the phone from time to time1108461345184811235211335411384711484711584712035212084512144912184312253712284112345612384712434812485612540712584813034313085613141318551325021328451343134457134858135457135852140358i notice to three different anomaliesskipping over alarm for example interval of 10 minutes between two messages in the server it seems fine to me and might be due to connectivity problemspattern of 6 minutes between two messages and then 4 minutes you can see this pattern more than one time i have an assumption that the os does some optimization and if for example it has other alarms every two minutes for example checking if there are new emails it runs them together and the radio is turn on only one time instead of twostrange intervals i cannot explain them you can seeso my questionshow can i enforce the system to run exactly every 5 minutes or to try harder what are the reasons for the strange timing i wrote what i think but these are only thoughtsthanks,['android'] +590073,spinner does not show selected value i have implemented the spinner by populating the array list through databasei can get and show the array list in my spinner array adapter but if i select the item in spinner it does not shown in spinnerwhat i had mistake herehere is my code spinner spinner1 spinner findviewbyidridprospin arrayadapterstring adapter1 new arrayadapterstringthisandroidrlayoutsimple spinner item providerlist adapter1setdropdownviewresourceandroidrlayoutsimple spinner dropdown itemspinner1setadapteradapter1i get the selected item string by using thisspinner provid spinnerfindviewbyidridprospinstring provider providgetselecteditemtostringcan anyone help me out pls,['android'] +590167,why does select count from nothing return 1 with sql server 2012 use masterselect yields must specify table to select fromwhich is exactly what i would expect but the funny thing is thatuse masterselect countreturns 1 can someone explain to me what is counted hereedit and possibly include sources,['sql'] +590172,rails mongoid model query result returns wrong sizelengthcount info even when using limit when querying on a certain model in my rails application it returns the correct results excerpt the size length or count information even using the limit criteriarecipes recipe wherebitly url someurl order bydate asc skip10 limit100recipessize 57179recipescount 57179recipeslength 57179i cannot understand why this is happening it keeps showing the total count of the recipes collection and the correct value should be 100 since i used limitcount 0recipeseach do recipe count 1end watcount 100can somebody help me thanksrails version 323mongoid version 2410mongodb version 184,['ruby-on-rails'] +590173,is it possible to enter an objectivec for loop as an lldb expression i have seen passing statements that you can enter complex statements like a for loop in an lldb command in the language of the program youre debugging in this case objectiveci would really like to be able to do this i have never learned python and would prefer not to invest the time to do so in order to use the available python lldb support there just are not enough hours in the day for that,['objective-c'] +590176,html entities when to use decimal vs hex is there a good rule of thumb for when to use decimal vs hexadecimal notation for html entitiesfor example a nonbreaking hyphen is written in decimal as 8209 and in hex as x2011this answer says that hexadecimal is for unicode does that mean hex should be used if youre using the meta charsetutf8 tag in the document headoccasionally i will notice entity characters mistakenly rendered instead of the entities they represent for example amp appearing instead of an ampersand in an email subject line or rss headline is either hex or decimal better for avoiding thisone last consideration can using hex or decimal affect the rendering clarity crispness of the character,['html'] +590181,drawing selection box rubberbanding marching ants in cocoa objectivec i have currently implemented a simple selection box using mouse events and redrawing a rectangle on mouse drag heres my codevoiddrawrectnsrectdirtyrectif nsequalrectsselfdraggingbox nszerorect nscolor graycolor setstroke nsbezierpath bezierpathwithrectselfdraggingbox strokepragma mark mouse events voidmousedownnsevent theevent nspoint pointinview self convertpointtheevent locationinwindow fromviewnil selfdraggingbox nsmakerectpointinviewx pointinviewy 0 0 self setneedsthisplayyes voidmousedraggednsevent theevent nspoint pointinview self convertpointtheevent locationinwindow fromviewnil draggingboxsizewidth pointinviewx selfdraggingboxoriginx draggingboxsizeheight pointinviewy selfdraggingboxoriginy self setneedsthisplayyes voidmouseupnsevent theevent selfdraggingbox nszerorect self setneedsthisplayyesref questionsis this the most efficient way to do this if the view was complex would it be more efficient to draw a transparent view over the main view instead of continuously redrawing the view for the duration of the mouse drag how is this done i cannot seem to find any examples,['objective-c'] +590372,orderby with a nontransitive icomparer take a custom icomparer that treats two doubles as equal if their difference is less than a given epsilonwhat would happen if this icomparer is used in a orderbythenby clausespecifically i am thinking of the following implementationpublic class epsiloncomparer icomparerdouble private readonly double epsilon public epsiloncomparerdouble epsilon thisepsilon epsilon public int comparedouble d1 double d2 if mathabsd1d2epsilon return 0 return d1comparetod2 now this icomparer relationship is clearly not transitive if a b and b c then a c with epsilon 06 compare1 15 0compare15 2 0yetcompare1 2 1what would happen if this icomparer was used in an orderby query like thislistitem itemlistitemlist itemlistorderbyitemitemx new epsiloncomparer0352 thenby itemitemy new epsiloncomparer1743tolistwould the sort behave as one would expect sorting the list first by x then by y while treating roughly equal values as exactly equalwould it blow up under certain circumstancesor is this whole sort illdefinedwhat exactly are the consequences of using an icomparer without transitivityi know that this is most likely undefined behavior of the c language i am still very much interested in an answerand is there an alternative way to get this sorting behaviourbesides rounding the values which would introduce artifacts when for two close doubles one is rounded up and the other downan online fidle of the code in this question is available here,['c#'] +590400,using two different python thistributions i currently have continuum analytics python thistribution called anaconda downloaded and in use on my computer my problem is that i want to use virtualenv for a flask project and anaconda flashes a warning that says virtual env is not supported is there any way i can run two thistributions stock python and anaconda on the same computer,['python'] +590547,xcode is creating generic xcode archive instead of ios app archive i am a beginner in iphone development and i tried to create an ipa with my profile and valid certificate but xcode is creating a generic xcode archive file instead of ios app archive because in my code there are two xcodeproj in thereand from one of the stack overflow answer i followed the following stepsskip install is no for the main project targetskip install is yes for framework subprojects targetssubprojects need to have copy headers in project not publicinstallation directory under deployment is valid applications for examplebut i am still not getting the solution,['ios'] +590605,what is the difference between responsesendredirect and requestgetrequestthispatcherforwardrequestresponse i have got a problem with my page jump when i use javaif i useresponsesendredirectloginjspthen i get this url httplocalhost8080loginjspbut if i use requestgetrequestthispathcerloginjspforwardrequest responsethen i get this url httplocalhost8080shoppingloginjsp the shopping is the name of my modulewhats the difference,['java'] +590636,create pdfs with images in wp8 i am making an app in which i want to create pdfs out of the images i store in the isolated storage many opensource libraries are available for solving the purpose but unfortunately none expresses their comparability with windows phone 8then i came across this linkthe post explains about writing the pdf file by making the pdf header but this only creates a pdf with some text written in it i now want to add some images in it how shall i proceed for the same,['c#'] +590682,jquery datepick plugin keith wood how to thisplay only 2 month is there a way to thisplay only 2 months in a datepickerwhat i already set up is the datepicker as inline version showing 2 months and hiding the month navigationon selecting the date the form submits and default date is set to the selected datethis works finethe problem is when a date from second month is clicked selected date is set as default date but now second and third months are active instead of first and second monthsexampleinitially only may 2014 and june 2014 are shown when user clicks 4th june 2014 form submits and now june and july are shown instead of may and junei already tried setting monthoffset and dateranges mindate maxdate did not fix my problemedit made two screenshots to show you the problemand here is the jsprogram overview datepicker var dpinputfield inputprogramoverviewdatepickervalue var defaultdate dpinputfieldval 1399593600 dpinputfieldval 1399593600 9th may 2014 0 divprogramoverviewdatepickerdatepick dateformat datepicktimestamp monthstoshow 2 changemonth false altfield programoverviewdatepickervalue mindate 1399593600 9th may 2014 0 maxdate 1402790400 15th june 2014 0 ondate showdayandmonth defaultdate defaultdate extenddatepickregionalwindowlanguage function showdayandmonthdate var dayname datepickformatdated date var datename dategetdate var monthname datepickformatdatem date return content div classdaydaynamedivdiv classdatedatenamedivdiv classmonthmonthnamediv dateclass showdam ashowdamclickfunctione programoverview formsubmit,['jquery'] +590683,cannot set background color of uitableviewcell in ios6 i started testing my app under simulator because i do not have any ios 6 device and stumbled upon weird problem i cannot set backgroundcolor property of uitableviewcell if i st thiscellcontentviewbackgroundcolor uicolor redcolorit is working only for ios 6 when i use thiscellbackgroundcolor uicolor redcoloror thiscell setbackgroundcoloruicolor redcolorit is working only for ios7when i use both cellcontentview and cellbackgroundcolor it is working for both ios should not it be one answer for such a easy property or maybe it is some simulator bugupdateif it changes anything in the same tableview and cells i cannot set accessorytype neither via storyboard nor codeupdate2 for some reason setting tableview style to plain deleted all my changes but grouped showed as expected,"['ios', 'objective-c']" +590709,an error occurred while installing curb 085 while bundling an old project this error came up geminstallerextensionbuilderror error failed to build gem native extension homeddrvmrubiesruby200p247binruby extconfrb checking for curlconfig nochecking for main in lcurl no extconfrb failed could not create makefile due to some reason probably lack of necessarylibraries andor headers check the mkmflog file for more details you mayneed configuration optionsprovided configuration options withoptdir withoutoptdir withoptinclude withoutoptincludeoptdirinclude withoptlib withoutoptliboptdirlib withmakeprog withoutmakeprog srcdir curdir rubyhomeddrvmrubiesruby200p247binruby withcurldir withoutcurldir withcurlinclude withoutcurlincludecurldirinclude withcurllib withoutcurllibcurldir withcurllib withoutcurllibextconfrb18in main cannot find libcurl or curlcurlh runtimeerror try passing withcurldir or withcurllib and withcurlinclude options to extconfgem files will remain installed in homeddrvmgemsruby200p247gemscurb085 for inspectionresults logged to homeddrvmgemsruby200p247gemscurb085extgem makeoutan error occurred while installing curb 085 and bundler cannot continuemake sure that gem install curb v 085 succeeds before bundling,['ruby'] +590735,mstest async testinitialize guarantee test fail just wondering if anyone thought like thisthis is incorrect design to have async call within testinitialize as testinitialize has to happen before any testmethodcan this be correct approach in any way to have async testinitialize as well private int val 0 testinitialize public async task testmehod1 var result await longrunningmethod val 10 testmethod public void testmehod2 assertareequal10 val any thought,"['c#', '.net']" +590839,reading numbers from a text file into an array in c i am a programming noob so please bear with mei am trying to read numbers from a text file into an array the text file somenumberstxt simply holds 16 numbers as so 5623125698541159include stdiohmain file myfile myfile fopensomenumberstxt r read file into array int numberarray16 int i for i 0 i 16 i fscanfmyfile d numberarrayi for i 0 i 16 i printfnumber is dnn numberarrayi the program does not work it compiles but outputsnumber is 104204697number is 0number is 4200704number is 2686672number is 2686728number is 2686916number is 2004716757number is 1321049414number is 2number is 2004619618number is 2004966340number is 4200704number is 2686868number is 4200798number is 4200704number is 8727656process returned 20 0x14 execution time 0118 spress any key to continue,['c'] +590885,get firstlast row of nth consecutive group whats the easiest way to select a single recordvalue from the nth group the group is determined by a material and it is priceprices can change i need to find the first date of the last and the last date of the next to last materialpricegroups so i want to know when exactly a price changed i have tried following query to get the first date of the currentlast price which can return the wrong date if that price was used beforedeclare material varchar20set material 12714303select top 1 claim submitted date from tabdatawhere material material and price select top 1 price from tabdata t2 where material material order by claim submitted date descorder by claim submitted date ascthis also only returns the last how do i get the previous so the date when the previous price was used lastfirsti have simplified my schema and created this sqlfiddle with sampledata here in chronological order so the row with id7 is what i need since it is has the nexttolast price with the latest dateid claim submitted date material price5 december 04 2013 12330 12714303 204 december 03 2013 12330 12714303 20 current3 november 17 2013 10130 12714846 407 november 08 2013 12160 12714303 18 lastdesired2 october 17 2013 09130 12714303 181 september 17 2013 08130 12714303 108 september 16 2013 12150 12714303 176 june 23 2013 14220 12714303 189 january 11 2013 1210 12714303 20 a problem since this is older than the desired but will be returned by my simply subquery approach aboveis it even possible to parametrize this value so the nthlatestpricegroup if i want to know the 3rd last pricedate note that the query sits in a scalarvaluedfunctionedit many thanks to all but unfortunately a simple row number seems not to help here since i am trying to get the row with the most recent price before the current price for a given material so group bypartition by materialprice includes rows with the same price that do not belong to the last recent materialprice group consider that a price can change from date price comment5 months ago 20 original price note that this is the same as the curent which causes my query to fail3 months ago 18 price has changed i might need the first and last date2 months ago 20 price has changed i might need the first and last date1 month ago 18 previous price i need the oldest and newest dates now 20 current price i need the firstoldest date from this groupso i want the date of the most recent row of the last 20group the oldest 20group is irrelevant so i must somehow group by consecutive prices since a price can repeat after it has already changedso actually i only need the most recent claim submitted date from the pricegroup that starts with 1 month ago previous price in the list above which is the date until the previous price was valid the other informations listed in the comments are just nice to havethe nthlatestpricegroup subquestion that is the row with id7 in the sample data above by the way the oldest row of this pricegroup would be the one with id2october 17 and not id6june 23 even if the latter is older there was a different price10 after that is the reason why i cannot use simple ranking functions,['sql'] +590893,gc performance hit for inner class vs static nested class i just came across a weird effect and while tracking it down i noticed that there seems to be a substantial performance difference for collecting inner vs static nested classes consider this code fragmentpublic class test private class pointer long data pointer next private pointer first public static void mainstring args test t null for int i 0 i 500 i t new test for int j 0 j 10 j pointer p tnew pointer pdata ij pnext tfirst tfirst p so what the code does is create a linked list using an inner class the process is repeated 500 times for testing purposes thiscarding the objects used in the last run which become subject to gcwhen run with a tight memory limit like 100 mb this code takes about 20 minutes to execute on my machine now by simply replacing the inner class with a static nested class i can reduce the runtime to less than 6 minutes here are the changes private static class pointer and pointer p new pointernow my conclusions from this little experiment are that using inner classes makes it much more difficult for the gc to figure out if the objects can be collected making static nested classes more than 3x faster in this casemy question is if this conclusion is correct if yes what is the reason and if no why are inner classes so much slower here,['java'] +590900,selenium webdriver cannot find element by link text i am trying to select an element that includes an anchor but the text is buried in a paragraph inside of a div heres the html i am working witha classitem nghrefcatalog90d9650a36988e5d0136988f03ab0fcategorydatabase serversservice90cefc7a42b3d4df0142b52466810026 hrefcatalog90d9650a36988e5d0136988f03ab0fcategorydatabase serversservice90cefc7a42b3d4df0142b52466810026div classcollg2 colsm3 colxs4 itemlistimageimg ngsrccsaimageslibraryservice designpng srccsaimageslibraryservice designpngdivdiv classcollg8 colsm9 colxs8div classcolxs12 p strong classngbindingsmoke sequentialstrong pthe code i am using to try to snag it is targeting the smoke sequential text withdriverfindelementbylinktextserviceclickwhere the variable service holds smoke sequential in it when i run it i get the following errororgopenqaseleniumnosuchelementexception unable to locate element methodlink textselectorsmoke sequentialany help would be greatly appreciated,"['java', 'html']" +591008,how to remotely connect to cleardb in an azure website i have created a free azure website with wordpress on it a cleardb mysql database was automatically createdi want to remote connect to the db using something like mysql workbenchi used the credentials from the view connection strings in the azure portal dashboard but there is an error connecting i read in some post that the db itself is hosted in azure cloud and thus can not be accessed have anyone managed to administrate a db like this,['mysql'] +591100,ruby gsl on os x i am trying to install ruby gsl on os x 109 i am using ruby 200 installed using rvm according to its site i need gsl installed first with that i used homebrew to install gsl brew install gsl next i did gem install gsl but was given this error messagecompiling fftcfftc27060 warning implicit conversion loses integer precision size t aka unsigned long to int wshorten64to32 for i 0 i tablenf i gsl vector int setv i tablefactori fftc61418 warning implicit conversion loses integer precision size t aka unsigned long to int wshorten64to32 shape0 n fftc70618 warning implicit conversion loses integer precision size t aka unsigned long to int wshorten64to32 shape0 n fftc77318 warning implicit conversion loses integer precision size t aka unsigned long to int wshorten64to32 shape0 n fftc91048 error use of undeclared identifier forward rb define constmgsl fft forward int2fixforward usersyihanghorvmrubiesruby200p353includeruby200rubyrubyh24145 note expanded from macro int2fixdefine int2fixi valuesigned valuei1 fixnum flag fftc91148 error use of undeclared identifier forward rb define constmgsl fft forward int2fixforward usersyihanghorvmrubiesruby200p353includeruby200rubyrubyh24145 note expanded from macro int2fixdefine int2fixi valuesigned valuei1 fixnum flag fftc91249 error use of undeclared identifier backward rb define constmgsl fft backward int2fixbackward usersyihanghorvmrubiesruby200p353includeruby200rubyrubyh24145 note expanded from macro int2fixdefine int2fixi valuesigned valuei1 fixnum flag fftc91349 error use of undeclared identifier backward rb define constmgsl fft backward int2fixbackward usersyihanghorvmrubiesruby200p353includeruby200rubyrubyh24145 note expanded from macro int2fixdefine int2fixi valuesigned valuei1 fixnum flag 4 warnings and 4 errors generatedmake ffto error 1any idea how to fix this,['ruby'] +591122,will a python dict with integers as keys be naturally sorted if i create a python dict which uses integers as keys can i safely assume that iterating over the dict will retrieve items in order according to key valueie willmy dict for x in range0100 my dictx strxfor item in my dictitems print itemalways result in printing the list in order of key value,['python'] +591154,chrome and firefox cors ajax calls get aborted on some mac machines we have a webpage at wsaddlebackcomlive and chrome and firefox cors ajax calls get aborted on some mac machines on a mac with osx 109 latest updates chrome and firefox with latest updates the ajax call to null 1386201207191 gets aborted this works on safarithis behavior is isolated but reproducible on some machines but not others we have other mac machines with identical os and browser version that successfully bring up the webpagei have verified that the web server successfully responds to the ajax request within 500 milliseconds yet chrome hangs on waiting for the response for 30 seconds and eventually aborts the call i have included a the chromenetinternals for the failed call below11645 url requestnull 1386201207191start time 20131204 155327469t1386201207469 st 0 request alive dt30398t1386201207470 st 1 url request start job dt30397 load flags 143540480 do not save cookies do not send auth data do not send cookies enable load timing maybe user gesture report raw headers verify ev cert method get priority 2 url null 1386201207191t1386201207470 st 1 http cache get backend dt0t1386201207470 st 1 http cache open entry dt0 net error 2 err failedt1386201207470 st 1 http cache create entry dt0t1386201207470 st 1 http cache add to entry dt0t1386201207470 st 1 http stream request dt2t1386201207472 st 3 http stream request bound to job source dependency 11647 http stream jobt1386201207472 st 3 http stream requestt1386201207472 st 3 http transaction send request dt0t1386201207472 st 3 http transaction send request headers get worshipserviceversion2null 1386201207191 http11 host apisaddlebackcom connection keepalive accept applicationjson textjavascript q001 origin useragent mozilla50 macintosh intel mac os x 10 9 0 applewebkit53736 khtml like gecko chrome310165063 safari53736 contenttype applicationjson referer acceptencoding gzipdeflatesdch acceptlanguage enusenq08t1386201207472 st 3 http transaction send requestt1386201207472 st 3 http transaction read headers dt30395t1386201207472 st 3 http stream parser read headers dt30395t1386201237867 st30398 cancelledt1386201237867 st30398 url request start job net error 3 err abortedt1386201237867 st30398 request alivehere is the request and response from wiresharkrequestget worshipserviceversion2null 1386192341441 http11 expert info chatsequence get worshipserviceversion2null 1386192341441 http11 message get worshipserviceversion2null 1386192341441 http11 severity level chat group sequence request method get request uri worshipserviceversion2null 1386192341441 request version http11host apisaddlebackcomconnection keepalivecachecontrol maxage0accept applicationjson textjavascript q001origin useragent mozilla50 macintosh intel mac os x 10 9 0 applewebkit53736 khtml like gecko chrome310165057 safari53736contenttype applicationjsonreferer acceptencoding gzipdeflatesdchacceptlanguage enusenq08responsehttp11 200 ok expert info chatsequence http11 200 ok message http11 200 ok severity level chat group sequence request version http11 status code 200 response phrase okcachecontrol nocachepragma nocachecontenttype applicationjson charsetutf8expires 1server microsoftiis75accesscontrolalloworigin accesscontrolallowcredentials truexaspnetversion 4030319xpoweredby aspnetdate wed 04 dec 2013 212541 gmtcontentlength 2841 content length 2841setcookie nsc ndxfc14580faf181c9545525d5f4f58455e445a4a423660expireswed 04dec2013 1434 gmtpathhttponlyi have spent too much time trying to figure out why this is failing on some mac configuration and not others any help would be much appreciated,['jquery'] +591168,generating a random number between 1 and 10 java i want to generate a number between 1 and 10 in javahere is what i triedrandom rn new randomint answer rnnextint10 1is there a way to tell what to put in the parenthesis when calling the nextint method and what to add,['java'] +591355,stringformat an integer to use a thousands separator with decimal value in danish culture i have a string totalprice which holds a value like this 11475 i want two things1round the value so that there is always two digits after 2implement thousands separator in this string so that final out put will be some thing like this 114750i have tried some thing like thisstringformat0 totalpriceit does my first requirement correctly by producing an output 114750but i am way behind in my second requirement can any one tell me how i can achieve thisnote in danish culture stands for and stands for,"['c#', 'asp.net']" +591479,how to call a python function from lua i want to run a python script from my lua file how can i achieve thisexamplepython codesumpy filedef sum from pythonab return ab lua codemainlua fileprintsum from python23,['python'] +591508,jqueryui draggable sortable bug cannot read property options of undefined my question seems to resemble this questiondragging from a sortable list to a drag and drop pluginbut since there is no answer given to that one i was wondering if anybody could would be able to figure it out with me the issue i am having is that i create a draggable div and append this into a div that is made sortable when i specify any arguments like soelsortable arguments it causes an error when element is dropped see below when left empty it strangely works fine and has no issues the error also prevents any functions to be triggered by the draggable elementuncaught typeerror cannot read property options of undefined jqueryui1103customjs2204uipluginaddstop jqueryui1103customjs2204extendplugincall jqueryui1103customjs284widget trigger jqueryui1103customjs2017anonymous function jqueryui1103customjs401widget mousestop jqueryui1103customjs1702anonymous function jqueryui1103customjs401widget mouseup jqueryui1103customjs957anonymous function jqueryui1103customjs401widget mouseup jqueryui1103customjs1721anonymous function jqueryui1103customjs401widget mousedown mouseupdelegate jqueryui1103customjs913jqueryeventthispatch jquery1102js5095jqueryeventaddelemdatahandle jquery1102js4766and this is the code where it goes wronguipluginadraggable cursor start function var t body o thisdatauidraggableoptions if tcsscursor o cursor tcsscursor tcsscursor ocursor stop function var o thisdatauidraggableoptions if o cursor bodycsscursor o cursor var o thisdatauidraggableoptionsthe thisdata only contains object id c17example codedraggabledraggable connecttosortable sortable drop function consolelogelement dropped sortablesortable update function consolelogsortable updated jsbin example hopefully somebody is able to tell me what the issue is and what the fix for the issue is,"['javascript', 'jquery']" +591513,python any way to avoid several ifstatements inside each other in a forloop i need a better way to do this i am new with programming but i know that this is a very inefficient way of doing it and that i need a function for this i just do not know how to do it exactly any suggestions i am very grateful for any help for h in range0lena list if a listh list40 list5 number listi if functionlist1list5 list11 if functionlist2list5 list21 if functionlist3list5 list31 if functionlist4list5 list41 list5appendinputsome input from the user other functionlist5 if list51 40 print something something break out of every loop else for h in range0lena list if a listh list50 list6 number listi if functionlist1list6 list11 if functionlist2list6 list21 if functionlist3list6 list31 if functionlist4list6 list41 if functionlist5list6 list51 list6appendinputsome input from theuser other functionlist6 if list61 40 print something something break out of every loop else etc one extra comparison every time,['python'] +591535,garbage collection of string literals in java 6 and java 7oracle jdk according to the famous book head first java page 661 garbage collector does not go inside string poolafter reading about the similar questions on so i have found mixed answers likegarbage collection of string literals is same as normal objectsread thissome answers say the opposite read answer heremy questions arehow were the string literals garbage collected in java 6 and beforeand since in java 7 string literals will be created on heaphow the garbage collection of string literals will be differentin java 7 as compared to the java 6,['java'] +591615,are curly braces really required around initialization according to gcc 463 ubuntulinaro 4631ubuntu5 i am missing a curly brace in the array initialization in the following codeinclude iostreaminclude boostarrayhppinclude arrayint main int plain 12345 stdarray int 5 std arr 12345 warning see below boostarrayint 5 boost arr 12345 warning see below stdcout plain0 std arr1 boost arr2 stdendl g testcc wall wextra pedantic stdc0x testcc in function aint mainatestcc747 warning curly braces missing around initialization for astdarrayvalue type 5 aka int 5a wmissingbracestestcc847 warning curly braces missing around initialization for aint 5a wmissingbracesapparently gcc missing braces around initializer this is a bug in gcc even in a slightly different context the answers differ from file a bug report to just thisable the warninghowever in the context of stdarray or boostarray is this warning superfluous or am i missing something importanti will probably add the additional braces instead of thisabling the warning but i am curious about the implications,['c++'] +591625,make stringformats arg thisplay nullvalued arguments differently from null consider the custom tostring implementation of a beanoverridepublic string tostring stringformatthis is s thissomefieldthis yields this is null if somefield is nullis there a way to override the default null string representation of nullvalued arguments to another text ie without calling explicitly replaceall in the tostring methodnote the bean inherits from a superclass that could implement formattable but i just do not seem to understand how to make this workedit the snippet is oversimplified for the sake of example but i am not looking for ternary operator solutions somefieldnull somefield becausethere can be potentially a great many fields involved in tostring so checking all fields is too cumbersome and not fluentother people whom i have little control over if any are writing their own subclassesif a method is called and returns null that would either imply calling the method twice or declaring a local variablerather can anything be done using the formattable interface or having some custom formatter which is final btw,['java'] +591639,how to use dialog fragment showdialog deprecated android i understand that there is this documentationbut as a new androidjava learner it is not easy to understand the amount of code involved from writing a simple alert dialog that pops up with 2 options yesno messagehere is the code i currently have in my mainactivity filefinal private int reset dialog 0 private onclicklistener resetbuttonlistener new onclicklistener override public void onclickview v showdialogreset dialog protected androidappdialog oncreatedialogint id switchid case reset dialog alertdialogbuilder builder new builderthis return builder setmessageare you sure you want to reset the count setnegativebuttonno new dialoginterfaceonclicklistener override public void onclickdialoginterface arg0 int arg1 toastmaketextmainactivitythis did not reset 5show setpositivebuttonyes new dialoginterfaceonclicklistener override public void onclickdialoginterface arg0 int arg1 toastmaketextmainactivitythis did reset 5show create return null this is my attempt to following the instructions on the android site main activity filefinal private int reset dialog 0 private onclicklistener resetbuttonlistener new onclicklistener override public void onclickview v intent intent new intentmainactivitythis maindialogclass startactivityintent protected androidappdialog oncreatedialogint id switchid case reset dialog alertdialogbuilder builder new builderthis return builder setmessageare you sure you want to reset the count setnegativebuttonno new dialoginterfaceonclicklistener override public void onclickdialoginterface arg0 int arg1 toastmaketextmainactivitythis did not reset 5show setpositivebuttonyes new dialoginterfaceonclicklistener override public void onclickdialoginterface arg0 int arg1 toastmaketextmainactivitythis did reset 5show create return null then created a maindialog class i am actually lost in how to do this correctly or apply itpackage comproteintrackerimport androidsupportv4appdialogfragmentpublic class maindialog extends dialogfragment public static myalertdialogfragment newinstanceint title myalertdialogfragment frag new myalertdialogfragment bundle args new bundle argsputinttitle title fragsetargumentsargs return frag i am not sure if i was suppose to create a new class for the fragment and how to apply it to my current dialog in the activity screen,['android'] +591756,debug ipad safari with a pc i want to test my website on safari on my ipad i only have another pc is there a way for me to do remote debugging like adb with mobile chrome i searched on stackoverflow seems there is an adobe edge inspect cc but i do not know if this is a good choice thanks,['ios'] +591763,error failed to instantiate module restangular due to is undefined when first using restangular on a working website i got the following javascript errorfailed to instantiate module restangular due to is undefinedwhat am i missing what does it mean that is undefined in the restangular module,"['javascript', 'html']" +591860,incorrect string value xf0x9fx8exb6xf0x9f mysql i am trying to store a tweet in my mysql table the tweet isquiero que me escuches no te burles no te rias anoche tuve un sueao que te fuiste de mi vida the final two characters are both multiple musical notes u1f3b6 for which the utf8 encoding is 0xf09f8eb6the tweet text field in my table is encoded in utf8mb4 but when i try to store the tweet in that column i get the following error messageincorrect string value xf0x9fx8exb6xf0x9f for column tweet text at row 1what is going wrong how can i fix this i need to store multiple languages as well and this character set works for all languages but not for the special characters like emoticons and emojisthis is my create table statementcreate table twitter status data unique status id bigint20 not null auto increment metadata result type text character set utf8 created at text character set utf8 not null comment utc time when this tweet was created id bigint20 unsigned not null comment unique tweet identifier id str text character set utf8 not null tweet text text comment actual utf8 text user id str text character set utf8 user name text comment users name user screen name text comment twitter handle coordinates text character set utf8 primary key unique status id key user id index user id fulltext key tweet text index tweet text engineinnodb auto increment82451 default charsetutf8mb4,['mysql'] +591919,heroku gunicorn flask app says connection in use i have a flask app that runs fine on local but when i push to heroku i get the error message running on info starting gunicorn 180error connection in use 0 8163i tried the solution in this question where gunicorn and werkzeug were fighting with each other but adding a name main block to my master application file runpy did not solve my errorthis so post suggested making sure my processes were all cleaned up i did that but it still did not work so i actually deleted my entire heroku app and repushed and it still gives the same error my runpy file looks likepl envbinpythonfrom app import appif name main apprundebugtrue port33507 33507 is the flask port on herokuand my procfile is web gunicorn runappthe init py file in app isfrom flask import flaskimport osfrom flaskextlogin import loginmanagerapp flask name appconfigfrom objectconfiglm loginmanagerlminit appapplmlogin view loginfrom app import viewsviews has the meaty logic of the app in it but i do not think there is anything in there that would mess with gunicorn heres the viewspy imports just in casefrom flask import flask render template flash redirectfrom flaskextlogin import login required login userfrom app import app lmfrom forms import loginformi am definitely at a loss as to where to look now to figure out this connection error any thoughts on why it seems to think i am already using 0thank youmonicaedit i ran the app locally using foreman start and it worked cleanly in 050 so i think i am having a heroku problemedit2 i intentionally broke my view flow made an internal infinite reference and pushed it to see what would happen i got the expected error logs undid it and pushed the rollback and now it is working i have absolutely no idea why that should work except maybe that breaking it in an expected way flushed my gunicorn connections if anyone has any explanations for this mystery i would love them,['python'] +591965,aspnet web application template missing in visual studio 2012 has anyone else dealt with this my ultimate goal is to create a new empty web api project i have been following tutorials and i have encountered the following issuemy issue is that when i try to create a aspnet web application project in visual studio pro 2012 i do not see that template as an option i go to installed templates visual c web all i see is aspnet empty web application so i selected that and then expected the aspnet project window to pop up so that i could select web api however that dialog never opened does anyone know howwhere i can get the aspnet web application template,['asp.net'] +591975,d3select by attribute value i am new to d3 i have something defined like thisnode nodeenterappendcircle attrid functiond return did attrclass node onmouseover mouseover node onclick nodeclicknow in function nodeclick i want to access a node or circle with a special id i am looking for something that i could use like thisforvar i0imaxidi d3selectthe node with id idodoes anybody know how i can do this,"['javascript', 'jquery']" +592023,app to monitor other apps on android problem at handi have to create a service which runs continuously this service monitors 5 apps say 5 android games installed on your phone this service needs to get the information of 1 how many times the game is opened and run 2 for how much time the each game has run for example say if i have this service installed in my app and i let it run for a month i need information of this kind on the screen of the appgame number of times the game is run duration of game playgame 1 20 times played for 15 hours in totalgame 2 16 times played for 25 hours in totalgame 5 10 times played for 12 hours in totalpossible approachwhen an application loads it comes in the memory noting the system clocks time while the application starts and when the application ends or is put in the background noting the time againso say if application is brought to memory at 900 pm and exits to background at 930 pm that gives us a game play time of 30 mins next time the application is played the duration will be added to 30 from the previous play stored in some sort of variable and so on each time a application is brought into the memory the counter of it being played should increase by onehence giving us the number of times an application is playedcodingi have no idea about service in android as i have never really worked on them any tutorials related to my problem at hand will be very helpfulsecondly if there is other way in which this could be done i would like to know that as well i could really use some code snippet for me to start this project,['android'] +592074,fsk demodulation parsing japanese ews data athis is not a duplicate similar questions are about scenarios where people have control over the source data i do notain japan there is something called the emergency warning broadcasting system it looks like this when activated in the above video at around 237 a fskmodulated signal is sent i want to parse this signal ie given a wav file that contains the signal i want to end up with a stringbuilder that contains 0s and 1s to process them later i have the spec for the binary data and all but the problem is that i know nothing about audio programming this is just for a hobby project but i became hooked tv and radio makers can pick up this signal and have their appliances do stuff in reaction to it so it cannot be that hard right facts about the signalthe mark tone is 1024hz and the stop tone is 640hzeach tone is 15625ms long2 second pause before signal begins and after it ends probably for detection purposeswhat i did so farwrite a simple riff parser that accepts 8bit mono wav files and allows me to get samples from them i have tested it and it worksa loop that takes 15625ms of samples anduses rms to look for two seconds of silenceuses the goertzel algorithm to decide if the signal is 1024hz or 640hzthe problems i have0s and 1s are swallowed during the loop depending on the test datagiven the clarity of the signal youtubetomp3 rip that should not happenif i generate a repeating 01 sequence in audacity 30 times my program will pick up around 10 of the 01 pairs instead of 30sometimes 0s and 1s are swapped side effect of the aboveif i tweak the code so it works with one test sound file other test sound files stop workingmy questionscan anyone give me a high level overview on how fsk decoding would be done properly in softwaredo i need to apply some sort of filter that limits the signal to 640hz1024hz and mutes everything elsewhat is the best approach to keep the timing right maybe i am doing it wrongany links to beginners literature on this kind of audio processing i would really like to learn and get this workingthe code that reads samples is simplifiedstringbuilder ews bits new stringbuilderdouble samples new doubleintsamplesperms 16625dint index 0 readto current offset riff subchunk2size binaryreader br at start of pcm data while brbasestreamposition readto switch bitspersample 8 case 1 8bit samplesindex doublebrreadbyte 1275d 256d break case 2 16bit samplesindex doublebrreadint16 32768d break if index sampleslength continue the sample buffer is full and we must process it if audioprocessorissilenceref samples silence count if state parserstatedecoding silence count 150 end of ews broadcast reached ewssignalparserparseews bitstostring reset state go back looking for silence goto done the signal was not silence if silence count 120 state parserstatesearchingsilence state parserstatedecoding if state parserstatedecoding audioprocessordecoderef samples samplerate ref ews bits bool continue decoding check first 20 bits for signature if continue decoding goto done if we get here we were decoding a junk signal state parserstatesearchingsilence not enough silence yet silence count 0done index 0the audio processor is just a class withpublic static void decoderef double samples int samplerate ref stringbuilder bitholder double freq 640 goertzelmagnituderef samples 640 samplerate double freq 1024 goertzelmagnituderef samples 1024 samplerate if freq 640 freq 1024 bitholderappend0 else bitholderappend1public static bool issilenceref double samples power rms sqrtsumx2 n double sum 0 for int i 0 i sampleslength i sum samplesi samplesi double power rms mathsqrtsum sampleslength return power rms 001 remarksremarksprivate static double goertzelmagnituderef double samples double targetfrequency int samplerate double and sampleslength int k int05d doublen targetfrequency doublesamplerate double w 20d mathpi n k double cosine mathcosw double sine mathsinw double coeff 20d cosine double q0 0 q1 0 q2 0 for int i 0 i sampleslength i double sample samplesi q0 coeff q1 q2 sample q2 q1 q1 q0 double magnitude mathsqrtq1 q1 q2 q2 q1 q2 coeff return magnitudethanks for reading i hope you can help me,['c#'] +592100,how to use spatialite with xamarin on android i want to use spatialite instead of plain sqlite with xamarin on android to manage and thisplay geographical data builtin sqlite does not allow to load extensions how can i do it,['android'] +592101,npoi setting different cell format i have problem setting different format in each cell i want to set number format to thousand separator and thousand separator with 3 decimals when number is not integer here is my code i think problem look like each cell format is set by last fomat setting in for cycleso output should be like this12345 12 345 425 425 412 412 457825 4 57825 short doubleformat hssfoutputworkbookcreatedataformatgetformat0 short intformat hssfoutputworkbookcreatedataformatgetformat0 for i 0 i unorderedsheetlastrownum i npoissusermodelirow newrow orderedsheetcreaterowi npoissusermodelirow oldrow unorderedsheetgetrowi if oldrow null foreach icell oldcell in oldrowcells icell newcell newrowcreatecellmappingn switch oldcellcelltype case celltypenumeric newcellsetcelltypecelltypenumeric newcellsetcellvalueoldcellnumericcellvalue if numberhasdecimalsoldcellnumericcellvalue newcellcellstyledataformat doubleformat else newcellcellstyledataformat intformat break default newcellsetcellvalueoldcelltostring break,['c#'] +592135,laravel migration transaction when developing i am having so many issues with migrations in laraveli create a migration when i finish creating it there is a small error by the middle of the migration say a foreign key constraint that makes php artisan migrate fail he tells me where the error is indeed but then migrate gets to an unconsistent state where all the modifications to the database made before the error are made and not the next onesthis makes that when i fix the error and rerun migrate the first statement fails as the columntable is already createdmodified then the only solution i know is to go to my database and rollback everything by hand which is way longer to domigraterollback tries to rollback the previous migrations as the current was not applied succesfullyi also tried to wrap all my code into a dbtransaction but it still does not workis there any solution for this or i just have to keep rolling things back by handedit adding an example not writing schema builder code just some kind of pseudocodemigration1create table users id name last name emailmigration1 executed ok some days later we make migration 2create table items id user id references usersidalter table users make some error herenow what will happen is that migrate will call the first statement and will create the table items with his foreign key to users then when he tries to apply the next statement it will failif we fix the make some error here we cannot run migrate because the table items it is created we cannot rollback nor refresh nor reset because we cannot delete the table users since there is a foreign key constraint from the table itemsthen the only way to continue is to go to the database and delete the table items by hand to get migrate in a consistent state,['php'] +592163,mysql the whole query fails if result of sub query is null i have a situation where i need to generate rows with random data out of the same tables valid datai have generated id by php randmin max function with min 1 and max select maxid from patient 1selecttblfirstnamefirstnametbllastnamelastnametblbirthdatebirthdatetbllocationlocationfromselect firstname from patient where id 11445 and firstname limit 1 as tblfirstnameselect lastname from patient where id 74964 and lastname limit 1 as tbllastnameselect birthdate from patient where id 26360 limit 1 as tblbirthdateselect location from patient where id 68356 and location limit 1 as tbllocationnow in the id 26360 from the above query 26360 is that random number and is used to avoid the possibility if 26360 was deletedproblemif any of the sub query returns no result complete query fails and return nothing,"['php', 'mysql', 'sql']" +592176,what are the different ways we can break a singleton pattern in java what are the different ways we can break a singleton pattern in java i know one way ie if we do not synchronize the method in singleton then we can create more than an instance of the class so synchronization is applied is there a way to break singleton java classpublic class singleton private static singleton singleinstance private singleton public static singleton getsingleinstance if singleinstance null synchronized singletonclass if singleinstance null singleinstance new singleton return singleinstance,['java'] +592215,correct way to import a google sample android project to android studio i want to play with the sample project at locationupdateszip in android studioi have tried to use file import project but end up with a load of errorsthere are many questions about importing an eclipse project to android studio but following those did not help me,['android'] +592236,uiview alpha vs uicolor alpha i would like to know the difference betweenassigning my uiview a color with 1 alpha vs assigning it a nontransparent color but giving the uiview a 1 alpha value on the screenshot i have made two uiviews with two black alpha 10 uilabels on top of eachassume a macro rgb is defined beforedefine rgbrgba uicolor colorwithredr2550 greeng2550 blueb2550 alphand then here is the code view1 setbackgroundcolor rgb255 0 0 1 view1 setalpha05 view2 setbackgroundcolor rgb255 0 0 05 view2 setalpha1 view3 setbackgroundcolor rgb255 0 0 1 view3 setalpha1i can see only one difference visually changing views own alpha instead of bg colors affects the subviews as well but other than that is there any difference in functionality that i should consider eg on animations layers etc,"['ios', 'objective-c']" +592256,repositories factories and hierarchically structured data i am going through domain driven design by eric evans where he outlines the interplay between repositories and factories the repository itself will call an db interface to get a result set this result set would then be passed to a factory that would understand that result set to reconstitute the object what if the data was hierarchical in nature like some sort of tree structure for examplepublic class foo public int id get set public string name get set public foo parent get set public icollectionfoo get set other business like methods hereusing d i would have my interfaces and implementationspublic interface ifoorepository foo getint idpublic interface ifoofactorytsource foo createtsource sourcepublic class sqlfoorepository ifoorepository private readonly ifoodao dao private readonly ifoofactorysqldatareader factory public sqlfoorepositoryifoodao dao ifoofactory factory thisdao dao thisfactory factory public foo getint id var resultset daofindid return factorycreateresultset public class sqlfoofactory ifoofactorysqldatareader public foo getsqldatareader reader var foo new foo fooid int readerid fooname string readername do i build the children accounts here return foo if i try to build the children in the factory then i need access to the repo again if i do it in the repo i feel like i am doing work that should be for the factory not sure how to tackle this oneone thought i had is that the foo is not the aggregate root but rather the footree is the aggregate root so trying to get any foo i would need to create the entire tree which means i could pass a collection of foo objects to a footreefactoryany help would be very appreciated,['c#'] +592301,how do i concatenate many objects into one object using inheritence in python during runtime i have the following classesclass helloobject def init self passclass byeobject def init self passl hello byeif i do the following i get an error class bigclassl file stdin line 1 class bigclassl syntaxerror invalid syntaxis there another way to do this automatically at runtimei am using python 27,['python'] +592341,core bluetooth advertise and scan in the background i have been trying to setup an app to make the device both scan for peripherals and advertise as a peripheral the goal is for two devices to be woken up in the background when they become near each other via bluetooth thiscovery from the apple documentation it seems that you should be able to run ble in the background with bluetoothcentral and bluetoothperipheral background modes enabled and my application works when one device is in the foregroundfirst i advertise data like sonsdictionary advertisingdata cbadvertisementdatalocalnamekeymyperipheral cbadvertisementdataserviceuuidskeycbuuid uuidwithstringidentifier start advertising over bleperipheralmanager startadvertisingadvertisingdata i then set the device to scan for datansarray services cbuuid uuidwithstringidentifiercentralmanager scanforperipheralswithservicesservices optionsnilhowever when both go into the background device has to be locked the bluetooth cannot thiscover and voidcentralmanagercbcentralmanager central didthiscoverperipheralcbperipheral peripheral advertisementdatansdictionary advertisementdata rssinsnumber rssinever gets called on either device how can i fix thisthanks,"['ios', 'iphone']" +592348,actionbar compat change title textcolor i am trying to modify the text color of the title of the actionbarsupport i have used actionbarstylegenererator to create a theme with the correct colors and it works wellwhile using the light theme i would like to change the color of the heading to white in the genererator i cannot set the text color for a number of reasons i cannot use the dark actionbar theme i am so close just have to get the title to white what i am doing wrong herestyle nameactionbartransparentmyapp parentstylewidgetappcompatlightactionbar item namebackgrounddrawableab transparent myappitem item nameprogressbarstylestyleprogressbarmyappitem item nametitletextstylestylemyapptitletextstyleitem style style namemyapptitletextstyle parentstyletextappearanceappcompatwidgetbaseactionbartitle item nameandroidtextcolorfitem style,['android'] +592395,pythons assert called with is there a wildcard character suppose i have a class in python set up like thisfrom somewhere import sendmailclass myclass def init self kargs selfsendmail kwargsgetsendmail sendmail if we cannot find it use imported def def publish lots of irrelevant code and then selfsendmailmail to mail from subject body format htmlso as you can see i have sort of given myself the option to parameterize which function i use for selfsendmail now in the test fileclass tester kwargs sendmail magicmockmail from none mail to none subject none body none format none selfmyclass myclasskwargs later on def testdefaultemailheader default subject hello world selfmyclasspublish selfmyclasendmailassert called this is doing just fine selfmyclasendmailassert called withdefault subject this is having issuesfor some reason i am getting the error messageassertionerror expected call mockhello world actual call mockdefaultmt defaultmf hello world default body format htmlso basically the assert is expecting sendmail to be called with only one variable when it ends up being called with all 5 the thing is i do not care about what the other 4 variables are i just want to make sure it is called with the correct subjecti tried the mock place holder any and got the same thingselfmyclasendmailassert called withany any hello world any anyassertionerror expected call mockany any hello world any anyactual call mockdefaultmt defaultmf hello world default body format html really unsure on how to proceed with this one anyone have any advice if we only care about one of the variable and want to ignore the rest,['python'] +592430,how to override css box sizing for just one area on page i have the following css inside my twitter bootstrap filebeforeafter webkitboxsizing borderbox mozboxsizing borderbox boxsizing borderboxit is causing a problem with my tinymce editor mainly the resizing of the textarea anyway if i remove the above code all is good but obviously i need it in place cause otherwise the rest of bootstrap breaksso how do i override the above for just tinymce i tried thistinymceeditortinymceeditorbeforetinymceeditorafter webkitboxsizing contentbox important mozboxsizing contentbox important boxsizing contentbox importantbut no luck tinymceeditor happens to be the div that my editor is inside,"['html', 'css']" +592440,isnull vs case return type i recently ran into an interesting issue with changing case statements to isnull functions in tsql the query i was working with is used to get some user attributes and permissions for a website i work on previously the query had a number of case statements similar to the followingnote acolumn1 in the example is of type bit in the table also note that the candosomething result column is sometimes used as a string in the websiteselect case when acolumn1 is null then 0 else acolumn1 end candosomething from athe dba replaced these case statements with the isnull functionselect isnullacolumn1 0 candosomething from athis seems like a fine change but it caused something unexpected when retrieving the data in c with the previous query the value of the candosomething column when accessed from a datatable in c was 1 or 0 when we changed to using isnull the value in c was then changed to true or false which when treated as a string are obviously not the same as 1 or 0the errors this caused have already been addressed i am just curious why isnull returns a different value than an equivalent case statement and i cannot seem to find any answers on google,"['c#', 'sql']" +592560,threading vs taskbased vs asynchronous programming i am new to this concept are these the same or different things what is the difference i really like the idea of being able to run two processes at once for example if i have several large files to load into my program i would love to load as many of them simultaneously as possible instead of waiting for one at a time and when working with a large file such as wav file it would be great to break it into pieces and do processing on several chunks at once and then put them back together what do i want to look into to learn how to do this sort of thing edit also i know using more than one core on a multicore processor fits in here somewhere but apparently asynchronous programming does not necessarily mean you are using multiple cores why would you do this if you did not have multiple cores to take advantage of,['c++'] +592600,empty list returned from elementtree findall i am new to xml parsing and python so bear with me i am using lxml to parse a wiki dump but i just want for each page its title and textfor now i have got this from xmletree import elementtree as etreedef parserfile name document etreeparsefile name titles documentfindalltitle print titlesat the moment titles is not returning anything i have looked at previous answers like this one elementtree findall returning empty list and the lxml documentation but most things seemed to be tailored towards parsing html this is a section of my xmlmediawiki xmlns xmlnsxsi xsischemalocation version07 xmllangen siteinfo sitenamewikipediasitenamebase pagebasegeneratormediawiki 120wmf9generatorcasefirstlettercasenamespaces namespace key2 casefirstlettermedianamespace namespace key1 casefirstletterspecialnamespace namespace key0 casefirstletter namespace key1 casefirstlettertalknamespace namespace key2 casefirstletterusernamespace namespace key3 casefirstletteruser talknamespace namespace key4 casefirstletterwikipedianamespace namespace key5 casefirstletterwikipedia talknamespace namespace key6 casefirstletterfilenamespace namespace key7 casefirstletterfile talknamespace namespace key8 casefirstlettermediawikinamespace namespace key9 casefirstlettermediawiki talknamespace namespace key10 casefirstlettertemplatenamespace namespace key11 casefirstlettertemplate talknamespace namespace key12 casefirstletterhelpnamespace namespace key13 casefirstletterhelp talknamespace namespace key14 casefirstlettercategorynamespace namespace key15 casefirstlettercategory talknamespace namespace key100 casefirstletterportalnamespace namespace key101 casefirstletterportal talknamespace namespace key108 casefirstletterbooknamespace namespace key109 casefirstletterbook talknamespacenamespaces siteinfo page titlearatrumtitle ns0ns id65741id revision id349931990id parentid225434394parentid timestamp20100315t025502ztimestamp contributor ip143105193119ip contributor comment sources comment sha12zkdnl9nsd1fbopv0fpwu2j5gdf0hawsha1 text xmlspacepreserve bytes1436aratrum is the latin word for plough and quotarotronquot i12 is the greek languagegreek word the ancient greecegreeks appear to have had diverse kinds of plough from the earliest historical records hesiod advised the farmer to have always two ploughs so that if one broke the other might be ready for use these ploughs should be of two kinds the one called quotautoguosquot i3i quotselflimbedquot in which the ploughtail was of the same piece of timber as the sharebeam and the pole and the other called quotpektonquot ioi12 quotfixedquot because in it three parts which were of three kinds of timber were adjusted to one another and fastened together by nailsthe autoguos plough was made from a sapling with two branches growing from its trunk in opposite directions in ploughing the trunk served as the pole one of the two branches stood upwards and became the tail and the other penetrated the ground and sometimes shod with bronze or iron acted as the ploughshare sourcesbased on an article from a dictionary of greek and roman antiquities john murray london 1875a14i12external linksaratrumhtml smiths dictionary article with diagrams further details sourcescategoryagricultural machinerycategoryancient greececategoryanimal equipmenttextrevisionpagei have also tried iterparse and then printing the tag of the element it findsfor e in etreeiterparsefile name print etagbut it complains about the e not having a tag attributeedit,['python'] +592635,how to consolidating the translucency of the navigation bar between iphone 5s and 5 i have difficulty consolidating the uinavigationbars bartintcolor between iphone 5 and 5s both of my phones are on ios 7 in the following screenshot the top is 5s and the bottom is 5 iphone 5s shows an extremely translucent effect while iphone 5 shows a much more subtle effect only very dark objects are visible behind the navigation bar for iphone 5uinavigationbar appearancewhencontainedinuinavigationcontroller class nil setbartintcoloruicolor colorwithred460 2550 green1600 2550 blue1520 2550 alpha08 i would prefer that both phones look like the iphone 5 if i were to increase the alpha of the bartintcolor to 10 iphone 5s navigation bar would become completely opaque this is the expected result although iphone 5ss bar would become less translucent the effect is still too strong how would i decrease the translucency even more without making it completely opaque,"['ios', 'iphone']" +592655,dynamically add version number to dest output files w grunt i have a packagejson file with our version number such as name myproject version 20my goal is to dynamically add the version number from the packagejson file into the output files for example in the javascript i do not want to manually update the version number but would like something similar to this to be generated after each grunt build my project v20 windowmyproject version 20is there an easy way to do this in my gruntfilejs configuration,['javascript'] +592702,does python define the value of nan 0 does python defined the value of nan 0 in my python interpreter i get floatnan 0falsebut is this guaranteedif i understand correctly the iea 754 standard assigns false to any comparison involving nan however i cannot find anything in the python documentation that indicates that this standard is followed i even understand that 10 should give infinity under iea 754 but python raises an exception zerodivisionerror so python does not fully follow iea 754so is the result of floatnan 0 fully defined in python i need to know whether it is the same on all platforms and with all versions of python including old ones,['python'] +592715,ffmpeg audio transcoding using libav libraries i am writing an audio transcoding application using ffmpeg libraries here is my code file maincpp author vinod compile with g stdc11 o audiotranscode maincpp lavformat lavcodec lavutil lavfilter if defined prid64 pri macros broken undef prid64 define prid64 lld endif define stdc format macros ifdef cplusplus extern c endif include stdioh include stdlibh include systypesh include stdinth include libavutilimgutilsh include libavutilsamplefmth include libavutilframeh include libavutiltimestamph include libavformatavformath include libavfilteravfilterh include libavfilterbuffersrch include libavfilterbuffersinkh include libswscaleswscaleh include libavutilopth ifdef cplusplus endif include iostream using namespace std int select stream got frame got packet avformatcontext in fmt ctx null out fmt ctx null avcodec dec codec null enc codec null avstream audio st null avcodeccontext enc ctx null dec ctx null avframe pframe null pframefiltered null avfiltergraph filter graph null avfiltercontext buffersrc ctx null avfiltercontext buffersink ctx null avpacket packet string infilename homevinodvinodmediaunivacwebm string outfilename audio extractedm4a int target bit rate 1280 sample rate 22050 channels 1 avsampleformat sample fmt av sample fmt s16 string filter description aresample22050aformatsample fmtss16channel layoutsmono int log averrorint errcode char errbuf char callocav error max string size sizeofchar av strerrorerrcode errbuf av error max string size stdcout error errbuf stdendl delete errbuf return 1 initialize conversion filter int initialize audio filter char args512 int ret avfilter buffersrc avfilter get by nameabuffer avfilter buffersink avfilter get by nameabuffersink avfilterinout outputs avfilter inout alloc avfilterinout inputs avfilter inout alloc filter graph avfilter graph alloc const enum avsampleformat out sample fmts sample fmt av sample fmt none const int64 t out channel layouts av get default channel layoutout fmt ctx streams0 codec channels 1 const int out sample rates out fmt ctx streams0 codec sample rate 1 if dec ctxchannel layout dec ctxchannel layout av get default channel layoutdec ctxchannels snprintfargs sizeofargs time baseddsample ratedsample fmtschannel layout0x prix64 in fmt ctx streamsselect stream time basenum in fmt ctx streamsselect stream time baseden dec ctxsample rate av get sample fmt namedec ctxsample fmt dec ctxchannel layout ret avfilter graph create filterbuffersrc ctx buffersrc in args null filter graph if ret 0 av lognull av log error cannot create buffer sourcen return 1 ret avfilter graph create filterbuffersink ctx buffersink out null null filter graph if ret 0 av lognull av log error cannot create buffer sinkn return ret ret av opt set int listbuffersink ctx sample fmts out sample fmts 1 av opt search children if ret 0 av lognull av log error cannot set output sample formatn return ret ret av opt set int listbuffersink ctx channel layouts out channel layouts 1 av opt search children if ret 0 av lognull av log error cannot set output channel layoutn return ret ret av opt set int listbuffersink ctx sample rates out sample rates 1 av opt search children if ret 0 av lognull av log error cannot set output sample raten return ret endpoints for the filter graph outputs name av strdupin outputs filter ctx buffersrc ctx outputs pad idx 0 outputs next null endpoints for the filter graph inputs name av strdupout inputs filter ctx buffersink ctx inputs pad idx 0 inputs next null string filter desc filter description if ret avfilter graph parse ptrfilter graph filter descc str inputs outputs null 0 log averrorret exit1 if ret avfilter graph configfilter graph null 0 log averrorret exit1 print summary of the sink buffer note args buffer is reused to store channel layout string avfilterlink outlink buffersink ctxinputs0 av get channel layout stringargs sizeofargs 1 outlinkchannel layout av lognull av log info output sratedhz fmts chlayoutsn int outlinksample rate char av x if nullav get sample fmt nameavsampleformat outlinkformat args return 0 int mainint argc char argv int ret cout hello world endl printfabcd avcodec register all av register all avfilter register all open input file and allocate format context if avformat open inputin fmt ctx infilenamec str null null 0 stdcout error opening input file infilename stdendl return 1 retrieve stream information if avformat find stream infoin fmt ctx null 0 stdcerr could not find stream information in the input file infilename stdendl dump format details printfn n av dump formatin fmt ctx 0 infilenamec str 0 printfn n choose a audio stream select stream av find best streamin fmt ctx avmedia type audio 1 1 dec codec 0 if select stream averror stream not found stdcerr no audio stream found stdendl return 1 if select stream averror decoder not found stdcerr no suitable decoder found stdendl return 1 dec ctx in fmt ctx streams select stream codec av opt set intdec ctx refcounted frames 1 0 init the audio decoder if ret avcodec open2dec ctx dec codec null 0 av lognull av log error cannot open audio decodern return ret allocate output context ret avformat alloc output context2out fmt ctx null null outfilenamec str if ret 0 stdcerr could not create output context for the file outfilename stdendl return 1 find the encoder enum avcodecid codec id out fmt ctx oformat audio codec enc codec avcodec find encodercodec id if enc codec stdcerr could not find encoder for avcodec get namecodec id stdendl return 1 add a new stream audio st avformat new streamout fmt ctx enc codec if audio st stdcerr could not add audio stream stdendl initialise audio codec audio st id out fmt ctx nb streams 1 enc ctx audio st codec enc ctx codec id codec id enc ctx codec type avmedia type audio enc ctx bit rate target bit rate enc ctx sample rate sample rate enc ctx sample fmt sample fmt enc ctx channels channels enc ctx channel layout av get default channel layoutenc ctx channels some formats want stream headers to be separate if out fmt ctx oformat flags avfmt globalheader enc ctx flags codec flag global header ret avcodec open2out fmt ctx streams0 codec enc codec null if ret 0 stdcerr could not create codec context for the file outfilename stdendl return 1 initialize filter initialize audio filter if out fmt ctx oformat flags avfmt nofile int ret avio open out fmt ctx pb outfilenamec str avio flag write if ret 0 log averrorret return 1 write header if avformat write headerout fmt ctx null 0 if ret 0 log averrorret return 1 allocate frame pframe av frame alloc if pframe stdcerr could not allocate framen return 1 pframefiltered av frame alloc if pframefiltered stdcerr could not allocate framen return 1 av init packetpacket packetdata null packetsize 0 read packet from the stream while av read framein fmt ctx packet 0 if packetstream index select stream avcodec get frame defaultspframe ret avcodec decode audio4dec ctx pframe got frame packet if ret 0 log averrorret return ret printfdecoded packet pts ld packetpts printfframe best effor pts ld n pframebest effort timestamp set frame pts pframe pts av frame get best effort timestamppframe if got frame push the decoded frame into the filtergraph ret av buffersrc add frame flagsbuffersrc ctx pframe av buffersrc flag keep ref if ret 0 log averrorret return ret pull filtered frames from the filtergraph while 1 ret av buffersink get framebuffersink ctx pframefiltered if ret averroreagain ret averror eof break if ret 0 printferror while getting filtered frames from filtergraphn log averrorret return 1 initialize the packets avpacket encodedpacket 0 av init packetencodedpacket ret avcodec encode audio2out fmt ctx streams0 codec encodedpacket pframefiltered got packet if ret got packet encodedpacketsize set correct pts and dts if encodedpacketpts av nopts value encodedpacketpts av rescale qencodedpacketpts buffersink ctx inputs0 time base out fmt ctx streams0 time base if encodedpacketdts av nopts value encodedpacketdts av rescale qencodedpacketdts buffersink ctx inputs0 time base out fmt ctx streams0 time base printfencoded packet pts ldn encodedpacketpts write the compressed frame to the media file ret av interleaved write frameout fmt ctx encodedpacket if ret 0 log averrorret return 1 else if ret 0 log averrorret return 1 av frame unrefpframefiltered av frame unrefpframe flush delayed frames from encoder got packet1 while got packet avpacket encodedpacket 0 av init packetencodedpacket ret avcodec encode audio2out fmt ctx streams0 codec encodedpacket null got packet if ret got packet encodedpacketsize set correct pts and dts if encodedpacketpts av nopts value encodedpacketpts av rescale qencodedpacketpts buffersink ctx inputs0 time base out fmt ctx streams0 time base if encodedpacketdts av nopts value encodedpacketdts av rescale qencodedpacketdts buffersink ctx inputs0 time base out fmt ctx streams0 time base printfencoded packet pts ldn encodedpacketpts write the compressed frame to the media file ret av interleaved write frameout fmt ctx encodedpacket if ret 0 log averrorret return 1 else if ret 0 log averrorret return 1 write trailer av write trailerout fmt ctx avfilter graph freefilter graph if dec ctx avcodec closedec ctx avformat close inputin fmt ctx av frame freepframe av frame freepframefiltered if out fmt ctx oformat flags avfmt nofile avio closeout fmt ctx pb avcodec closeout fmt ctxstreams0codec avformat free contextout fmt ctx return 0 the audio file after transcoding is same duration as the input but its completely noisy can somebody tell me what i am doing wrong here,['c++'] +592750,doxygen enum not showing is it possible to have doxygen generate docs for an enum declared on one of my class headers the enum for the property called scope in this link is not showing as a documented type,"['objective-c', 'c']" +592788,add item to pandasseries i want to add an integer to my pandasserieshere is my codeimport pandas as pdinput pdseries12345inputappend6when i run this i get the following errortraceback most recent call last file pyshell9 line 1 in module fappend6 file cpython33libsitepackagespandascoreseriespy line 2047 in append verify integrityverify integrity file cpython33libsitepackagespandastoolsmergepy line 878 in concat verify integrityverify integrity file cpython33libsitepackagespandastoolsmergepy line 954 in init selfnew axes self get new axes file cpython33libsitepackagespandastoolsmergepy line 1146 in get new axes concat axis self get concat axis file cpython33libsitepackagespandastoolsmergepy line 1163 in get concat axis indexes xindex for x in selfobjs file cpython33libsitepackagespandastoolsmergepy line 1163 in listcomp indexes xindex for x in selfobjsattributeerror int object has no attribute indexhow can i fix that,['python'] +592806,on which c standard will c14 be based which revision of the c standard serves as the basis for c14c11 is based on c99 and was released a few months before c11 will c14 be based on c11 the current draft still as of dec 2013 seems to say based on isoiec 989919 ie c99 and i heard repeatedly that c14 is nearly complete and only undergoing minor tweaks at this point is it plausible that the dependency on c will be revised before the new standard goes to the vote,['c++'] +592832,how to absolutely position the baseline of text in html i am puzzled by the following problem i wish to absolutely position the baseline of some piece of html text at a certain ycoordinate while the text should be starting at a certain xcoordinate the following diagram clearly demonstrates the issueso i basically want to control where the point xy henceforth called the basepoint in the diagram is located on the screen relative to the topleft corner of the body of the document or some div important i do not know beforehand what the fontfamily or fontsize of the text is this is important because i do not want to change all the positions in my css whenever i change fontsin the following code i try to position the basepoint at 200100 but instead it positions the topleft of the div at that pointhtml style body position absolute margin 0px text position absolute top 100px left 200px fontfamily helvetica arial may vary fontsize 80px may vary style body div idtextcsspowerfuldiv bodyhtmlso how should i modify this code should i use the verticalalign property of the enclosing div i tried but could not get the desired resultthanks for any useful replies,"['html', 'css']" +592838,how to practically ship glsl shaders with your c software during opengl initialization the program is supposed to do something likeget shader source codecreate shaderattach source code to shadercompile shadergetting source code could be as simple as putting it in a string likeexample taken from superbible 6th edition static const char vs source version 420 core n n void mainvoid n n gl position vec400 00 00 10 n n the problem is that it is hard to edit debug and maintain glsl shaders directly in a string so getting the source code in a string from a file is easier for development stdifstream vertexshaderfilevertexglsl stdostringstream vertexbuffer vertexbuffer vertexshaderfilerdbuf stdstring vertexbufferstr vertexbufferstr warning safe only until vertexbufferstr is destroyed or modified const glchar vertexsource vertexbufferstrc strthe problem now is how to ship the shaders with your program indeed shipping source code with your application may be a problem opengl supports precompiled binary shaders but the open wiki states thatprogram binary formats are not intended to be transmitted it is not reasonable to expect different hardware vendors to accept the same binary formats it is not reasonable to expect different hardware from the same vendor to accept the same binary formats how to practically ship glsl shaders with your c software,['c++'] +592857,working example of using twitter api on android could anyone suggest a working example of how twitter api is implemented in android i would like to login and post on twitterafter some research twitter4j library for java is probably the best choice however i still do not manage to get twitter login workingi found a few examples like posting on twitter exampleanother exampleone more exampleone more examplehowever they are depreciated and not working could anyone suggest a working example of how posting on twitter from android app is implemented,['android'] +592860,iter values item in dictionary does not work having this python codeedges 0 3 1 0 2 1 6 3 2 4 2 5 4 6 5 8 7 9 8 7 9 6graph 0 3 1 0 2 1 6 3 2 4 2 5 4 6 5 8 7 9 8 7 9 6cycles while graph current graphiteritemsnext cycle current cyclescurrent cycle while current in graph next graphcurrent0 del graphcurrent0 if lengraphcurrent 0 del graphcurrent current next cycleappendnextdef traversetree root out for r in treeroot if r root and r in tree out traversetree r else outappendr return outprint joinstri for i in traversecycles 0traceback most recent call last file cusersedesktopcpy line 20 in module current graphiteritemsnextattributeerror dict object has no attribute iteritemsi also tried itervalues iterkeys but that does not workhow to modify code,['python'] +592989,java listcontains performance difference with manual searching i tried to demonstrate the difference between listcontains and manually searching exceqution timesthe result is awesome here is the code public static void mainstring argv liststring list new arrayliststring listadda listadda listadda listadda listadda listadda listaddb long starttime systemnanotime listcontainsb long endtime systemnanotime long duration endtime starttime systemoutprintlnfirst run duration starttime systemnanotime forstring s list ifsequalsb break endtime systemnanotime duration endtime starttime systemoutprintlnsecond run durationoutputfirst run 7500 second run 158685how contains function makes such a big differencewhich search algorithm does it useif list conatins the searched element does it terminate searching at first element,['java'] +593132,check that a method throws an exception when applied to any element of a list of values i want to write unit tests for a parser and would like to check that it correctly throws an exception for all input strings in a list now as i understand it the standard approach with junit would be to write a separate test method for each casepublic final class parsefailuretest1 testexpected parseexceptionclass public void testparsefailure1 throws exception parserparse1 2 missing comma testexpected parseexceptionclass public void testparsefailure2 throws exception parserparse1 2 additional commas but as i want to apply the same test to 20 or 50 different strings it seems impracticalan alternative would be to explicitly check for an exception with a catch blockpublic final class parsefailuretest2 test public void testparsefailure throws exception liststring documents arraysaslist 1 2 missing comma 1 2 additional commas for string document documents try parserparsedocument throw new assertionerrorexception was not thrown catch parseexception e expected do nothing but this is error prone and i would not get any information about which exception was expected and if a different exception was thrown it would count as a test error and not a failuremy solution would be to use a method similar to expectexception belowpublic final class parsefailuretest3 test public void testparsefailure throws exception liststring documents arraysaslist 1 2 missing comma 1 2 additional commas for final string document documents expectexceptionparseexceptionclass new testrunnable override public void run throws throwable parserparsedocument public static void expectexceptionclass extends throwable expected testrunnable test try testrun catch throwable e if egetclass expected return expected do nothing else throw new assertionerrorstringformatwrong exception was thrown s instead of s egetclass expected e throw new assertionerrorstringformatexpected exception was not thrown s expected public interface testrunnable void run throws throwable is there a method for that purpose in the junit framework or a related library or would you suggest a different approach or one of my rejected approaches to the problem,['java'] +593148,creating a smart remote upload script with jquery ajax and php i am currently creating an image hosting script and so far so good i have used several plugins to create the local uploading process with drag drog ajax which works totally fine now i have moved to the part where i need to create the remote uploading process with jquery ajax and a php script to handle the whole thinghow it is gonna workmy thought are like this there is a big box in the middle of the page that accepts the urls to be remote uploaded once valid urls are passed into the text area they will be immediately sent to the server side script via jquery ajax it is bound with a keyup eventthis is how it looks like the here come the urls part is already a text area so that parts already donewhere i need helpthe issue with this whole situation is once there are valid urls pasted into the text area those must be immediately be converted to some sort of box which also includes an uploading progress something that looks like this copied from the local uploading part it was easy implement the progress indicator for the local uploading since it was a feature offered by the plugin i have used but i do not know how to indicate the progress of remote uploading which is totally being made from scratchso this is how i have imagined the logic to flowuser pastes some urls into the text areathere is a clientside check to validate the pasted urlsvalidated urls are send to uploadphp on keyup urls are being processedwhile the upload goes on we show the users the progress in the knob php script finishes the process and returns back the uploaded urlsi update the page in the ajax success callback to thisplay the uploaded filesso the two process flows marked with are unclear to me i do not know how to achieve thosewhat i have triedwell i did not just come here and ask you to do everything for me but i have come across a dead end and i do not know how to continue what i have done so far is collect the urls from the text area and if there are multiple urls separated by a line break n i simply use split to get an array of pasted text and then use another function inside the loop to validate if they are urls if there is no line break detected inside the text area value then i simply check the one line that was provided on each case i send the whole text area to the php script because i do not know how to get rid of the invalid urls in jquery i have created a function called debug in php which stores anything into a debuglog file and this is what i am getting in one try when i paste something into the text areai paste once in the text area but it gets logged twice in the php side and i cannot determine whythis is how my jquery looks like remote upload var char start 10 var index 0 var urls remotearea var val ary urlskeyupfunction if urlsvallength char start var has lbrs rnitesturlsval val ary urlsvalsplitn if has lbrs for var i 0 i val arylength i if validate urlval aryi val arysplicei 1 continue ajax type post url uploadphp data upload type remote used to determine the upload type in php urls val ary sending the whole array here else if validate urlurlsval thisplay an error here return ajax type post url uploadphp data upload type remote used to determine the upload type in php urls urlsval sending whats in the text area the questionsso the final questions arehow do i send my information correctly to the php script only valid urls and have them kind of processable in my php scripthow do i indicate the progress of the uploadif i was somewhere unclear during my question please let me know i will try to reexplainthank youupdates09122013i think i have managed to solve the doublesending issue where my ajax would send the same information twice to the php script what i did was code in a delay anonymous function that sends the text area content to the php script after an user stops typing for 2 seconds once the user stops typing again the timer resets and a new ajax request will be made so i am assuming that this issue has been solved i will come back to it if anything strange occursnow i am still left with the progress indicators part i would appreciate your thoughts on that onemy new code,"['javascript', 'php', 'jquery', 'html']" +593156,how to remove gaps between bars in matplotlib bar chart i am making a bar chart in matplotlib with a call like thisxsbarbar lefts bar heights facecolorblack edgecolorblacki get a barchart that looks like thiswhat i would like is one with no white gap between consecutive bars eg more like thisis there a way to achieve this in matplotlib using the bar function,['python'] +593169,doctrine2 with codeigniter foreign key insert i have following database schema now department year and division tables are already filled with information i now need to insert student data student data is to be imported from xls file importing and parsing part is done as you can see in schema columns from student data table refers to year id department di and division id so while inserting i need their id field as xls has respective name valuesso i have to fetch respective id depending upon column value for each student so this introduces 3 queries to be fired for inserting one record in student table like this forloop studentdata new entitiesstudentdata year thisemgetrepositoryentitiesyearfindbyarrayyear name thisyeari department thisemgetrepositoryentitiesdepartmentfindbyarraydepartment name thisbranchi division thisemgetrepositoryentitiesdivisionfindbyarraydivision namethisdivisioni studentdatasetyearyear0 studentdatasetdepartmentdepartment0 studentdatasetdivisiondivision0 other data thisempersiststudentdataendforloop thisemflushthisemclearas you can see i have to get id withing loop for each dept year and division suppose i am importing 100 student list so it ultimately runs 300 queries just to fetch those 3 id fields can i get ids for year department and division from their name directly while inserting data i am new to doctrine to i do not know how to go about that updateif question is unclear please let me know i can update it with more details or restructure it,"['php', 'mysql']" +593304,how to access a global variable within a local scope this is my codeinclude iostreamusing namespace stdint x 5int main int x 1 cout the variable x x endl i get as output 1 but i would like to have 5 as in accessing the global x variableis this possible,['c++'] +593318,elaboratedtypespecifier for a scoped enum must not use the aclassa keyword i have the following enum specificationenum class facedirection int8 down upg 481 gives the following errorwarning elaboratedtypespecifier for a scoped enum must not use the aclassa keywordwhat causes this,['c++'] +593358,how to make join querys using sequelize in nodejs i am using sequelize orm everything is great and clean but i had a problem when i use it with join queriesi have two models users and postsvar user dbseqdefineuser username type dbsequelizestring email type dbsequelizestring password type dbsequelizestring sex type dbsequelizeinteger day birth type dbsequelizeinteger month birth type dbsequelizeinteger year birth type dbsequelizeintegerusersyncsuccessfunction consolelogtable createderrorfunctionerror consolelogerrvar post dbseqdefinepost body type dbsequelizetext user id type dbsequelizeinteger likes type dbsequelizeinteger defaultvalue 0 postsyncsuccessfunction consolelogtable createderrorfunctionerror consolelogerri want a query that respond with a post with the info of user that made it in the raw query i get thisdbseqqueryselect from posts users where postsuser id usersid successfunctionrows resjsonrows my question is how can i change the code to use the orm style instead of the sql query,['mysql'] +593372,how do i remove some javascript during gruntusemin compilation i have code that makes it easy and fast to writetest code that code does not belong in my production code mostly it mocks out the server so i only need the grunt servertwo parts to this one is how to i remove parts of a scriptangularmodulenglaborcallapp ngcookiesngresourcengsanitizengrouteserver mocks do not want this line in the production builddialogsand then a section of indexhtml that needs to go away buildjstmpapp scriptsmocksmocksjs script typetextjavascriptvar mocks scriptscript srcscriptsmocksjobsjsscriptscript srcscriptsmockjsscript endbuild so this might be 2 questions i do not see anything in the usemin documentation about this so i am guessing there is some other tool but i do not know what the name of that tool isthe other possibility is i am doing it wrong and rather than inject this mocking object i should be doing it with the grunt server what is everyone else doing,['javascript'] +593379,java soap request reading soap response i am trying to get specific values from response i get from webservice unfortunately i do not know how to do it i used code found on stackoverflow for creating soap request and writing out response content into stdoutprivate static void printsoapresponsesoapmessage soapresponse throws exception transformerfactory transformerfactory transformerfactorynewinstance transformer transformer transformerfactorynewtransformer source sourcecontent soapresponsegetsoappartgetcontent systemoutprintnresponse soap message streamresult result new streamresultsystemout transformertransformsourcecontent resultit all works well but i dont need whole response contentsoapenvenvelope xmlnssoapenv xmlnsbinhttplocalhostwebservicebindings xmlnstyphttplocalhostwebservicetypes soapenvheader soapenvbody bindoactionresponse binout typresult typcodetypcode typdescriptiontypdescription typresult binout bindoactionresponse soapenvbodysoapenvenvelopei just need value of code and description from this response how can i do this,['java'] +593386,current datecurdate not working as default date value pretty straight forward question here i think this should work but it does not why does not itcreate table invoice invoicedate date not null default current date,['mysql'] +593390,jekyll defaults to system ruby version instead of rvm version i have looked through tens of posts regarding this and still cannot quite figure it outhave not found an identical situation basically i have rvm with the default set to ruby 200 but when i cd to the directory with my jekyll page and runjekyll servethe result islibraryrubysite18rubygemsdependencyrb298in to specs could not find jekyll 0 among 5 total gems gemloaderrorfrom libraryrubysite18rubygemsdependencyrb309in to specfrom libraryrubysite18rubygemscore extkernel gemrb47in gemfrom usrbinjekyll22even though in the same directory when i run ruby vthe result isruby 200p353 20131122 revision 43784 x86 64darwin1250if i run rvm use 200projectdirectoryand then runjekyll serveit works like a charmi have tried using rvmrc and rubyversion files in the root and in both cases when i cd to the directory nothing indicates that those are recognized,['ruby'] +593406,libgdx and google inapurchase result i followed these instructions to integrate both libgdx and native android code using actionresolver interface i have no problem calling the android method from the libgdx part of my code but i am hitting a dead end when i am trying to intergrate google iap with libgdx according to trivialdrive example it uses mpurchasefinishedlistener outside of calling methodmy question is how do i pass this iap resultcode back to libgdx since the listener is outside the calling method currently purchase process went through but the libgdx part of my code is not being informed of the purchase statusresultthis is my codeany help is much appreciated actionresolverpublic interface iactionresolver public int requestiabpurchaseint productmainactivitypublic class mainactivity extends androidapplication implements iactionresolver debug tag for loggingstatic final string tag greatgame does the user have the premium upgradeboolean misupgraded false skus for our products the cat all or powstatic final string sku upgrade androidtestpurchased arbitrary request code for the purchase flowstatic final int rc request 101 the helper objectiabhelper mhelperoverridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate requestwindowfeaturewindowfeature no title getwindowsetflagswindowmanagerlayoutparamsflag fullscreen windowmanagerlayoutparamsflag fullscreen getwindowclearflagswindowmanagerlayoutparamsflag force not fullscreen getwindowaddflagswindowmanagerlayoutparamsflag keep screen on androidapplicationconfiguration cfg new androidapplicationconfiguration cfgusegl20 false initializenew catlandthis cfgvoid iabstartup string base64encodedpublickey some key create the helper passing it our context and the public key to verify signatures with logdtag creating iab helper mhelper new iabhelperthis base64encodedpublickey enable debug logging for a production application you should set this to false mhelperenabledebugloggingtrue start setup this is asynchronous and the specified listener will be called once setup completes logdtag starting setup mhelperstartsetupnew iabhelperoniabsetupfinishedlistener public void oniabsetupfinishediabresult result logdtag setup finished if resultissuccess oh noes there was a problem logdtag problem setting up inapp billing result return have we been thisposed of in the meantime if so quit if mhelper null return iab is fully set up now let us get an inventory of stuff we own logdtag setup successful querying inventory mhelperqueryinventoryasyncmgotinventorylistener listener that is called when we finish querying the items and subscriptions we owniabhelperqueryinventoryfinishedlistener mgotinventorylistener new iabhelperqueryinventoryfinishedlistener public void onqueryinventoryfinishediabresult result inventory inventory logdtag query inventory finished have we been thisposed of in the meantime if so quit if mhelper null return is it a failure if resultisfailure logdtag failed to query inventory result return logdtag query inventory was successful do we have the sku upgrade upgrade purchase thisupgrade inventorygetpurchasesku upgrade misupgraded thisupgrade null verifydeveloperpayloadthisupgrade logdtag user is misupgraded upgraded free logdtag initial inventory query finished enabling main ui runpurchaseflowsubmitproduct run real purchase flowpublic void runpurchaseflowint product logdtag runpurchaseflow todo for security generate your payload here for verification see the comments on verifydeveloperpayload for more info since this is a sample we just use an empty string but on a production app you should carefully generate this string payload if product 1 mhelperlaunchpurchaseflowthis sku upgrade rc request mpurchasefinishedlistener payload callback for when a purchase is finishediabhelperoniabpurchasefinishedlistener mpurchasefinishedlistener new iabhelperoniabpurchasefinishedlistener public void oniabpurchasefinishediabresult result purchase purchase logdtag purchase finished result purchase purchase if we were thisposed of in the meantime quit if mhelper null return if resultisfailure logdtag error purchasing result return if verifydeveloperpayloadpurchase logdtag error purchasing authenticity verification failed return logdtag purchase successful if purchasegetskuequalssku cat bought the upgrade logdtag purchase upgrade congratulating user misupgraded true how do i pass this result to the libgdx verifies the developer payload of a purchase boolean verifydeveloperpayloadpurchase p string payload pgetdeveloperpayload return trueoverridepublic int requestiabpurchaseint product iabstartup return 0 how do i get the result from mpurchasefinishedlistenerpurchasescreenresult greatgameactionresolverrequestiabpurchase1,"['java', 'android']" +593438,why c does not allow template overloading sometime i want to write two templates liketemplate typename type1class a template typename type1 typename type2class a but it seems that it is illegal to have two templates shared the same name but have different parameters i have to name it like a 1 a 2 i think it might be useful if i can do this especially when implementing functorswhy c does not allow this does it difficult to implement or have ambiguity in some circumstance will this be supported on later version of c,['c++'] +593567,adding custom css and js to shopify i am working on getting vertical tabs for a page on shopify using the atlantic theme as this theme does not have vertical tabs by default i have used the external js and css jqueryjverttabs my question is if i upload the js and css files as assets how do i link them to the page on which i want to use these and how to make use of these on the page after that if i have certain style elements available there too,"['javascript', 'jquery', 'html', 'css']" +593634,uiwebview get attributes from hyperlink clicked i have html page loaded via uiwebview if user selects link that looks likea webview2 hrefaccountscards itemacctno ai can get href value clicked in uiwebviewdelegate method from nsurlrequestwebviewshouldstartloadwithrequestnavigationtypebut how i can get attribute value from this hyperlink webview2 assuming that attribute name webview determined,"['html', 'ios', 'objective-c']" +593643,collect successive pairs from a stream given a stream such as 0 1 2 3 4 how can i most elegantly transform it into given form new pair0 1 new pair1 2 new pair2 3 new pair3 4 assuming of course i have defined class pairedit this is not strictly about ints or primitive streams the answer should be general for a stream of any type,['java'] +593653,how do delegates improve the performance of an application i am new to the delegates concept i have learnt it is similar to pointers in c in its advantages it mentioned effective use of delegates improves the performanceconsidering it is a pointer how does it improve the performance of an applicationif anybody could explain this with a simple example that would be helpful,"['c#', 'asp.net']" +593678,static method not working on web server in php i just finished working on a site in php and decided to upload it unto my web server but when i try to run pages with static method calls i get this error unexpected t paamayim nekudotayim i know this has to do with double colon error but i do not understand why it works on my local web server and refuses to work on my remote web serverdue to this error i had to through my whole site converting all static methods to instance methods phpclass user private userid public function construct iffunc num args 1 thisuserid func get arg1 public static function usernameexistsname global dbc ifgettypename string dieinvalid function parameter sql select username from users where usersusernamename result mysqli querydbc sql or diecould not check username at this time mysqli errordbc ifmysqli num rowsresult 0 return true else return false when i call itphp requireusersphp ifuserusernameexists getusername headerlocationindexphp,['php'] +593718,jquery knockout render template inmemory i have a knockout templatescript iddraggablehelper typetextxjquerytmpl div classdraggablehelper span databindtext namespan divscriptis possible to generate the result of the template and save it into memory by sending the object to populate the templatesomething likevar result korendertemplatedraggablehelperhtml name test,['jquery'] +593734,androidhttpclient nullpointerexception calling androidnethttpandroidhttpclientismmsrequest a customer has reported a strange error when doing a normal androidhttpclientexecute in an asynctask the app crashes and he gets the following stack tracejavalangruntimeexception an error occured while executing doinbackgroundat androidosasynctask3doneasynctaskjava299at javautilconcurrentfuturetaskfinishcompletionfuturetaskjava352at javautilconcurrentfuturetasksetexceptionfuturetaskjava219at javautilconcurrentfuturetaskrunfuturetaskjava239at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava1080at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava573at javalangthreadrunthreadjava841caused by javalangnullpointerexceptionat androidnethttpandroidhttpclientismmsrequestandroidhttpclientjava257at androidnethttpandroidhttpclientcheckmmssendpermissionandroidhttpclientjava290at androidnethttpandroidhttpclientexecuteandroidhttpclientjava296at comxmyclassmyhandlerdoworkmyclassjava325at comxnetworkrequesthandlerasynctaskforrequesthandlerdoinbackgroundnetworkrequesthandlerjava532at comxutilsnetworknetworkrequesthandlerasynctaskforrequesthandlerdoinbackgroundnetworkrequesthandlerjava1at androidosasynctask2callasynctaskjava287at javautilconcurrentfuturetaskrunfuturetaskjava234 3 morewhy is it calling checkmmssendpermission and issmsrequest we are not using mms and sms at all and the application do not have those permissions which i guess is why it crashes this works for all other 9 of our userscode looks like thisandroidhttpclient client androidhttpclientnewinstancenull inputstream inputstream null try httppost request new httpposturlstring prepareurlrequestrequest httpresponse response clientexecuterequest mresultstatus responsegetstatuslinegetstatuscode inputstream responsegetentitygetcontentany help would be welcomeupdatethis seems to be only affecting sony xperia z z1 and zr phones apparently the problems started to occur after receiving the update to android 43 no one with those phones can use our app but for all else it works,['android'] +593745,always thisplay at least two decimal places i want to format a number so that it always have at least two decimal placessamples 12112345623445output 10021012345623445,['javascript'] +593779,ibeacon background scanning i have written my own little ble scanning service that is triggered via an alarm every 35 seconds it scans for 11 seconds to get teh beacons around it and then transforms the rssi signal into a rough proximityi am now considering the radius networks android ibeacon service but i am wondering how i could realize the same background scanning eg i want the beacons scannign to start annd run in the background and receive intents into a broadcast receiver to decide what i do with the beacons scanned are there soem examples and is there an estimate how much battery this consumes,['android'] +593782,why does select consume so much cpu time in my program i have several java applications that use mina and all of them use 20 mina threads one application serves around 10 concurrent connections that are usually idle but receive input sometimes 20 is likely a reasonable threadcount for that application although i have not exactly profiled it which this question is getting at another application serves only around 15 connections at a time but initiates the io work so they are very busy and has 20 mina threads anyway which is obviously too manythe thing that is strange to me is both applications always devote about 30 sometimes as high as 60 of their cpu time into minas select method profiled in visualvm the call stack looks like thisjavalangthreadstate runnableat sunniochepollarraywrapperepollwaitnative methodat sunniochepollarraywrapperpollepollarraywrapperjava228at sunniochepollselectorimpldoselectepollselectorimpljava81at sunniochselectorimpllockanddoselectselectorimpljava87 locked 40ca5d54 a sunniochutil2 locked 24649fe8 a javautilcollectionsunmodifiableset locked 3fae9662 a sunniochepollselectorimplat sunniochselectorimplselectselectorimpljava98at orgapacheminatransportsocketnionioprocessorselectnioprocessorjava72at orgapacheminacorepollingabstractpollingioprocessorprocessorrunabstractpollingioprocessorjava1093at orgapacheminautilnamepreservingrunnablerunnamepreservingrunnablejava64at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava10at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava603at javalangthreadrunthreadjava722it seems to be based in a busy poll which sounds really wrong to meshould i be worried when i see the number that high what causes this is it something i need to optimize out or is it more akin to a sleep or idle routine if it is more like a sleep routine is it somehow scheduled to be lower priority than other cpu workupdate this thread seems to be the same issue i followed its advice and am now running java 170 45 but i am still seeing select taking as high as 90 of cpu time in an application with 10k connectionswe are using mina 204 which means this relevant bug is fixed,['java'] +593786,laravel angularjs requestajax always false i am building application with angularjs and laravel 4 everything is fine but i need now to allow only xhr requeststhis is what i have at the beginning of my controllerbut this statement is always false if requestajax return responsejsonarrayhaltrequestajax in angular i am using standard http serviceangularmoduleappfactoryapi httpqappclientapiurl class fb constructor thisdeferreddata qdefer info reload http method get url apiurlgameappclientinfo successres dostuff,['php'] +593840,get top biggest values from each column of the pandasdataframe here is my pandasdataframeimport pandas as pddata pddataframe first 40 32 56 12 89 second 13 45 76 19 45 third 98 56 87 12 67 index first second third fourth fifthi want to create a new dataframe that will contain top 3 values from each column of my data dataframehere is an expected output first second third0 89 76 981 56 45 872 40 45 67how can i do that,['python'] +593873,set a border for uibutton in storyboard i cannot get a border onto my buttons in xcode 5 without setting them directly in the code is it possible that there is no way to do this on the storyboard without making a custom background image,"['ios', 'objective-c']" +593922,php array get next keyvalue in foreach i am looking for a way to get the next and next1 keyvalue pair in a foreach for examplea arrayleg1la leg2ny leg3ny leg4flforeacha as k v ifnextval v nextnextval v staying put for next two legs,['php'] +593939,does android support jdk 6 or 7 i am new to android development can i use my existing java code developed using jdk 7 in android the functions use xerces dom and xslt and xpathapi currently when i installed android eclipse adt environment these functions are not compiling i would also like to know whether an android device itself supports jre 6 or 7,['android'] +593968,how to resolve web api message handler delegatinghandler from ioc container on each request this msdn article describes how http message handlers can effectively be used in aspnet web api to decorate requests furthermore the article shows the following code to register your custom handlers into the web api pipelineconfigmessagehandlersaddnew messagehandler1the problem i have with this approach is that this registers the messagehandler1 effectively as a singleton this is fine when the handler itself has no state and no dependencies but in a system that is based on the solid design principles it is very likely that those handlers will have dependencies of their own and its very likely that some of those dependencies need a lifetime that is shorter than singletonif that is the case such message handler should not be created as singleton since in general a component should never have a lifetime that is longer than the lifetime of its dependenciesso my question is what alternative ways do we have to register custom message handlers in such way that they can be resolved from our ioc container on each request,"['c#', 'asp.net']" +594085,errors with microsoft winforms series 1 graphics device i have a problem with this sample i just downloaded it and run it visual studio 2010 i have not touched anythingsorry for the language it is in italianfrom top to bottom it saysto avoid the lost of information before load the designer window it is necessary to solve these errorscannot visualize the designer windows for the file because no class can be designed the designer utility has examinated these classes spinningtrianglecontrol cannot load its base class winformsgraphicsdevicegraphicsdevicecontrol verify that there is a reference to the assembly and that all projects are generatedbelow it says the samenote thatif i compile and run it worksin the toolbar of the ide sometimes i did not understood when there are the two controls created with the sample spinningtrianglecontrol and spritefont sometimes they thisappear when this happens the controls are also removed from the mainwindow form of the projecti do not know if it is important but i noticed that the control thisappears often and removes itself from the xdesignercs while i add some new control such as toolstripmenu etc or i add some new event handler for some controli really do not understand whats happeningedit by jt the repro is here sdrvms1kihi5orepro stepsopen solutionselect the flowlayoutpanel1 controlrun the applicationstop the applicationnow try to select the gamewrapper resultthe gamewrapper control cannot be selected anymore it does not even show up in the property windows dropdownlist of form controls,['c#'] +594098,mysql innodb keeps crashing my database mysql server keeps crashing restarting and i am at a loss of what to do i keep getting the following in my dbnameorgerr file131205 184905 mysqld safe mysqld from pid file varlibmysqlleslesplanorgpid ended131205 185012 mysqld safe starting mysqld daemon with databases from varlibmysql131205 185012 note plugin federated is thisabled131205 185012 innodb the innodb memory heap is thisabled131205 185012 innodb mutexes and rw locks use gcc atomic builtins131205 185012 innodb compressed tables use zlib 123131205 185012 innodb using linux native aio131205 185012 innodb initializing buffer pool size 1280m131205 185012 innodb completed initialization of buffer pool131205 185012 innodb highest supported file format is barracuda131205 185012 innodb waiting for the background threads to start131205 185013 innodb 5532 started log sequence number 94296300131205 185013 note server hostname bindaddress 0 port 3306131205 185013 note 0 resolves to 0131205 185013 note server socket created on ip 0131205 185014 note event scheduler loaded 0 events131205 185014 note usrsbinmysqld ready for connectionsversion 5532cll socket varlibmysqlmysqlsock port 3306 mysql community server gpl131206 073253 mysqld safe number of processes running now 0131206 073253 mysqld safe mysqld restarted131206 73254 note plugin federated is thisabled131206 73254 innodb the innodb memory heap is thisabled131206 73254 innodb mutexes and rw locks use gcc atomic builtins131206 73254 innodb compressed tables use zlib 123131206 73254 innodb using linux native aio131206 73254 innodb initializing buffer pool size 1280m131206 73254 innodb completed initialization of buffer pool131206 73254 innodb highest supported file format is barracudainnodb the log sequence number in ibdata files does not matchinnodb the log sequence number in the ib logfiles131206 73254 innodb database was not shut down normallyinnodb starting crash recoveryinnodb reading tablespace information from the ibd filesinnodb restoring possible halfwritten data pages from the doublewriteinnodb buffer131206 73254 innodb waiting for the background threads to start131206 73255 innodb 5532 started log sequence number 94790638131206 73255 note server hostname bindaddress 0 port 3306131206 73255 note 0 resolves to 0131206 73255 note server socket created on ip 0131206 73255 note event scheduler loaded 0 events131206 73255 note usrsbinmysqld ready for connectionsversion 5532cll socket varlibmysqlmysqlsock port 3306 mysql community server gpl131206 073307 mysqld safe number of processes running now 0131206 073307 mysqld safe mysqld restarted131206 73307 note plugin federated is thisabled131206 73307 innodb the innodb memory heap is thisabled131206 73307 innodb mutexes and rw locks use gcc atomic builtins131206 73307 innodb compressed tables use zlib 123131206 73307 innodb using linux native aio131206 73307 innodb initializing buffer pool size 1280m131206 73307 innodb completed initialization of buffer pool131206 73307 innodb highest supported file format is barracudainnodb the log sequence number in ibdata files does not matchinnodb the log sequence number in the ib logfiles131206 73307 innodb database was not shut down normallyinnodb starting crash recoveryinnodb reading tablespace information from the ibd filesinnodb restoring possible halfwritten data pages from the doublewriteinnodb buffer131206 73308 innodb waiting for the background threads to start131206 73309 innodb 5532 started log sequence number 94790648131206 73309 note server hostname bindaddress 0 port 3306131206 73309 note 0 resolves to 0131206 73309 note server socket created on ip 0131206 73309 note event scheduler loaded 0 events131206 73309 note usrsbinmysqld ready for connectionsversion 5532cll socket varlibmysqlmysqlsock port 3306 mysql community server gpl131206 073838 mysqld safe number of processes running now 0131206 073838 mysqld safe mysqld restarted131206 73838 note plugin federated is thisabled131206 73838 innodb the innodb memory heap is thisabled131206 73838 innodb mutexes and rw locks use gcc atomic builtins131206 73838 innodb compressed tables use zlib 123131206 73838 innodb using linux native aio131206 73838 innodb initializing buffer pool size 1280m131206 73838 innodb completed initialization of buffer pool131206 73838 innodb highest supported file format is barracudainnodb the log sequence number in ibdata files does not matchinnodb the log sequence number in the ib logfiles131206 73838 innodb database was not shut down normallyinnodb starting crash recoveryinnodb reading tablespace information from the ibd filesinnodb restoring possible halfwritten data pages from the doublewriteinnodb buffer131206 73838 innodb waiting for the background threads to start131206 73839 innodb 5532 started log sequence number 94790674131206 73839 note server hostname bindaddress 0 port 3306131206 73839 note 0 resolves to 0131206 73839 note server socket created on ip 0131206 73839 note event scheduler loaded 0 events131206 73839 note usrsbinmysqld ready for connectionsversion 5532cll socket varlibmysqlmysqlsock port 3306 mysql community server gplrootles varlibmysqlthe server crashes and restarts at seemingly random intervals although it does happen around 730 am 30 minutes more then other times it seems there are no cron jobs running anywhere near this timeany help would be appreciatedss,['mysql'] +594118,javascript how can i get all the keys and values of an object that begin with a specific string i am trying to get all the keys and values of an object that begin with imageidsmy object appears as the following title fsdfsd titlezh fsdfsd body fsdf bodyzh sdfsdf imageids uploadstmpimage3png imageidszh but i only need the properties imageids and imageidszh however tomorrow a object might contain imageidsblah and i would need to pick it up as well i could remove the first few properties from the object but then the next object might contain additional properties such as foo bar,['javascript'] +594281,impactthisadvantages of rdynamic gcc option i have been working in a big c project which has a huge source of size nearly 300 mb and more than 800 files i want to get the call stack when the binary crashes so i have captured the signal and written the call stack from backtrace symbols to a file but to get the symbol names from backtrace symbols i have compiled with the linker flag rdynamic i want to know that using rdynamic impacts any problems i know that it affects performancewill adding the rdynamic linker option to gccg impact performancebut does itaffect performance considerably does it exposes my source code i know it would not i just want to be sure does it affect total runtime performance or startup time what are the thisadvantages of rdynamic,['c++'] +594294,image links broken in gmail because of googles image proxy image links in gmail are broken because of googles image proxy news1news2 i cannot load my sites images in gmailactual image path isbut i get the same image path like this in gmail jkaarbsjqozuxm3765smbk1pb4bskq9esvziwcoyfqjzqckrdyu1jzoityea pjs0de1ftdoes anyone knows how to solve this issue,['php'] +594395,setting edittext to single line makes it lose its focus after pressing enter i use an edittext in my code and compare its content to a string when clicking on a buttonunfortunately doing this with the enter key through onkey causes problems because enter creates aline breaki usedsetsinglelinetrueto prevent this but now pressing enter leads to the edittext losing its focuswhy does it behave like this and how do i fix it,"['java', 'android']" +594416,qt 511 application failed to start because platform plugin windows is missing editsome people started to mark my question as a duplicate do not forget that many similar questions existed when i asked this one see eg the list below however none of these answers solved my problem after a long search i found a comment which had been ignored by all users pointing to the missing lib now many months later the comment has been changed to an answer however when i answered this question by msyself i intended to help other people by directly providing the solution this should not be forgotten and so far my answer helped a lot of people therefore my question is definitely not a duplicate by the way the accepted answer within the provided link on top does not solve the problemyes i used the searchfailed to load platform plugin windows available platforms are errordeploying qt c application from visual studio qwindowsdll errorfailed to load platform plugin windows available platforms are windows minimalhowever in my case the problem still persists i am using qt 511 with visual studio 2012 and developed my application on windows 7 with qt creator 281 application is compiled in releasemode and can be executed if directly started with qt creatorhowever when starting from the releasefolder i get the following messagethis application failed to start because it could not find or load the qt platform plugin windows available platform plugins are minimal offscreen windowsfolder structure looks like thisrelease guiexe icudt51dll icuin51dll icuuc51dll libglesv2dll qt5coredll qt5guidll qt5widgetsdll platformsplatforms is the folder directly copied from qtqt511511msvc2012pluginsplatforms including eg qwindowsdll does not matter if i rename it to platform as some other users did qt is still not finding the platform plugin windows where is my mistake,['c++'] +594443,setting up sublimecodeintel plugin to work with railsruby on windows i have spent the last 30 minutes trying to find examples on how to configure sublimecodeintel plugin on sublime text 2 to work with rails ruby on windows and even if it is stated in the documentation that it does support rails there is no example of the configurationfrom what i have read so far getting rubygems to work with this plugin is not possible but rails should work has anybody successfully set up this plugin and if so can you please help or share your configuration with me,['ruby-on-rails'] +594451,uicollectionview with paging setting page width i have a collection view that can show about 35 cells at a time and i want it to be pagingenabled but i would like it to snap to each cell just like the app store app does and not scroll the full width of the view how can i do that,['ios'] +594505,enum and static variable in constructor access to static fields in enum constructor is forbidden by the compiler the source code below works it uses a static fieldpublic enum trickyenum trickyenum1 trickyenum2 static int count trickyenum incrementcount private static void incrementcount count public static void mainstring args systemoutprintlncount count outputcount 2but the code below does not work despite there being very little differencepublic enum trickyenum trickyenum1 trickyenum2 static int count trickyenum count compiler error public static void mainstring args systemoutprintlncount count from my search people usually claim that the problem is due to the order in which static fields are initialized but first example works so why do java developers forbid the second example it should also work,['java'] +594532,how to post multiple files using flask test client in order to test a flask application i got a flask test client posting request with files as attachmentdef make tst client service call1service path method kwargs content type kwargsgetcontenttypemultipartformdata with apptest client as client return clientopenservice path methodmethod content type content type bufferedtrue follow redirectstruekwargsdef publish a modelmodel name pom env service url upublish sccdatamodelname model name sccdatausername bdd script sccdatainstance bdd stub simulation sccdatatimestamp datetimenowstrftimedmythm sccdatafile openfile path rbfile name sccresponse make tst client service call1service url method datasccdataflask server end point code which handles the above post request is something like thisapproutepublish methodsget postdef publish if requestmethod post logdebugpublish post service is called upload files requestfilesgetlistfile print files nrequestfiles print upload filesnupload files return render response templatei get this outputfilesimmutablemultidictfile filestorage usingle xmlxml applicationxmlupload filesif i change sccdatafile openfile path rbfile nameinto thinking that it would handle multiple filessccdatafile openfile path rbfile nameopenfile path rbfile name1i still get similar outputfilesimmutablemultidictfile filestorage usingle xmlxml applicationxml file filestorage usecond xmlxml applicationxmlupload filesquestionwhy requestfilesgetlistfile is returning an empty listhow can i post multiple files using flask test client so that it can be retrieved using requestfilesgetlistfile at flask server side note i would like to have flask client i dont want curl or any other client based solutions i dont want to post single file in multiple requeststhanksreferred these links alreadyflask and werkzeug testing a post request with custom headerspython what type is flaskrequestfilesstream supposed to be,['python'] +594536,sass nthchild nesting i am refactoring these css selectors over to sassromtest detailed thnthchild2romtest detailed thnthchild4romtest detailed thnthchild6romtest detailed tdnthchild2romtest detailed tdnthchild3romtest detailed tdnthchild6romtest detailed tdnthchild7romtest detailed tdlastnthchild2romtest detailed tdlastnthchild4 backgrounde5e5e5and came up with thisromtest detailed thnthchild 2 4 6 backgrounde5e5e5 tdnthchild 2 3 6 7 backgrounde5e5e5 tdlastnthchild 2 4 backgrounde5e5e5 unfortunately this is throwing an errorinvalid cs after expected was 2 4 6 i also know this could be better because i amrepeating the background colorrepeating numbers ie 2 and 6how should i refactor these selectors,['css'] +594541,grunt usemin task not working on nested files while minifying angular files my document structure is rootpublicangularscriptsmainappjs i have used yeoman angular generator and set up grunt my html file looks like this div script srcbower componentsjqueryjqueryjsscript script srcbower componentsangularjsscript buildjs scriptspluginsjs script srcbower componentsbootstrapjsbootstrapalertjsscript endbuild buildjs scriptsmodulesjs script srcbower componentsangularbootstrapuibootstraptplsjsscript endbuild buildjs scriptsscriptsjs script srcscriptsmainappjsscript endbuild divthe html file is in rootpublicangular after running grunt the tmp and the thist folder contains minified files from bower components but scriptsjs is empty if i place appjs outside the main folder in scripts then its being concatenated into tmpscriptsjs why this is so what am i doing wrong my gruntjs file generated on 20131206 using generatorangular 060use strict globbing for performance reasons were only matching one level down testspecjs use this if you want to recursively match all subfolders testspecjsmoduleexports function grunt load grunt tasks automatically requireloadgrunttasksgrunt time how long tasks take can help when optimizing build times requiretimegruntgrunt define the configuration for all the tasks gruntinitconfig project settings yeoman configurable paths app requirebowerjsonapath app thist thist watches files for changes and runs tasks based on the changed files watch js files tmp yeomanapp scriptsjs tasks newerjshintall jstest files testspecjs tasks newerjshinttest karma styles files yeomanapp stylescss tasks newercopystyles autoprefixer gruntfile files gruntfilejs livereload options livereload connectoptionslivereload files yeomanapp html tmpstylescss yeomanapp imagespngjpgjpeggifwebpsvg the actual grunt server settings connect options port 90 change this to 0 to access the server from outside hostname localhost livereload 35729 livereload options open true base tmp yeomanapp test options port 9001 base tmp test yeomanapp thist options base yeomanthist make sure code styles are up to par and there are no obvious mistakes jshint options jshintrc jshintrc reporter requirejshintstylish all gruntfilejs yeomanapp scriptsjs test options jshintrc testjshintrc src testspecjs empties folders to start fresh clean thist files dot true src tmp yeomanthist yeomanthist git server tmp add vendor prefixed styles autoprefixer options browsers last 1 version thist files expand true cwd tmpstyles src css dest tmpstyles renames files for browser caching purposes rev thist files src yeomanthist scriptsjs yeomanthist stylescss yeomanthist imagespngjpgjpeggifwebpsvg yeomanthist stylesfonts less imports options inlinecss false default true publicangularstyleslistinglistinglesspublicangularstylescommonorders stylesless src publicangularstylescommonless dest publicangularstylestestless less thist options yuicompress true paths publicangularstylescommon files publicangularstylescommon stylescss publicangularstylescommoncommon stylesless publicangularstyleslistingcss publicangularstylescommonlistingless publicangularstylesorders stylecss publicangularstylescommonorders styleless reads html for usemin blocks to enable smart builds that automatically concat minify and revision files creates configurations in memory so additional tasks can operate on them useminprepare html yeomanapp html options dest yeomanthist performs rewrites based on rev and the useminprepare configuration usemin html yeomanthist html css yeomanthist stylescss options assetsdirs yeomanthist the following min tasks produce minified files in the thist folder imagemin thist files expand true cwd yeomanapp images src pngjpgjpeggif dest yeomanthist images svgmin thist files expand true cwd yeomanapp images src svg dest yeomanthist images htmlmin thist options optional configurations that you can uncomment to use removecommentsfromcdata true collapsebooleanattributes true removeattributequotes true removeredundantattributes true useshortdoctype true removeemptyattributes true removeoptionaltags true files expand true cwd yeomanapp src html viewshtml dest yeomanthist allow the use of nonminsafe angularjs files automatically makes it minsafe compatible so uglify does not destroy the ng references ngmin thist files expand true cwd tmpconcatscripts src js dest tmpconcatscripts replace google cdn references cdnify thist html yeomanthist html copies remaining files to places other tasks can use copy thist files expand true dot true cwd yeomanapp dest yeomanthist src icopngtxt htaccess bower components imageswebp fonts expand true cwd tmpimages dest yeomanthist images src generated styles expand true cwd yeomanapp styles dest tmpstyles src css run some tasks in parallel to speed up the build process concurrent server copystyles test copystyles thist copystyles imagemin svgmin htmlmin by default your indexhtmls usemin block will take care of minification these next options are preconfigured if you do not wish to use the usemin blocks cssmin thist files yeomanthist stylesmaincss tmpstylescss yeomanapp stylescss uglify thist files yeomanthist scriptsscriptsjs yeomanthist scriptsscriptsjs concat thist test settings karma unit configfile karmaconfjs singlerun true gruntregistertaskserve function target if target thist return grunttaskrunbuild connectthistkeepalive grunttaskrun cleanserver concurrentserver autoprefixer connectlivereload watch gruntregistertaskserver function gruntlogwarnthe server task has been deprecated use grunt serve to start a server grunttaskrunserve gruntregistertasktest cleanserver concurrenttest autoprefixer connecttest karma gruntregistertaskbuild cleanthist less imports less useminprepare concurrentthist autoprefixer concat ngmin copythist cdnify cssmin uglify rev usemin gruntregistertaskdefault newerjshint test build,['javascript'] +594561,remote debugging chrome for ios i am trying to debug an error on chrome for ipad how can i do thatadditional infoi know how to debug safari for ios i just do not have a mac at the momentis it true that i need safari on macos x to remote debug chrome for iosdoes desktop chrome allow anythingis chrome for ios just a webview application,"['javascript', 'ios']" +594569,first call to pytztimezone is slow in virtualenv i have installed pytz v20138 but it happens in 2013b 2011k in a virtualenv the first call to pytztimezoneuseasterntakes about 4 seconds in a regular environment this is essentially instantaneous does anyone have a trick to get this to run faster,['python'] +594587,idiomatic way to unpack variable length list i am reading a file and unpacking each line like thisfor line in filterfh a b c d linesplithowever it is possible that line may have more or fewer columns than the variables i wish to unpack in the case when there are fewer i would like to assign none to the dangling variables and in the case where there are more i would like to ignore them whats the idiomatic way to do this i am using python 27,['python'] +594610,text next to brand how do i get the bootstrap brand and any accompanying text to be treated together as the brandi have tried thisnav classnavbar navbardefault div classnavbarheader div classnavbarbrand a href img classimgresponsive srcbrandpnga h3ultimate trade sizerh3 div divnavhowever i cannot get them to be aligned ie side by side it produces the below effectplease note that i am using bootrstrap 3,"['html', 'css']" +594634,scroll view not functioning ios 7 i have a scrollview inside which i have 20 uitextviews the scrollview is not working i have set the following in viewdidload selfmainscrollcontentsize cgsizemake320 1800still it does not scroll however if i give bounce vertically it just bounces my scrollview is a child of the main uiview of dimension 320600 please guide how to enable the scroll,['iphone'] +594637,java generics tightly bounded parameter type i wish to have a method which has a signature like methodt1 t1 t2 t2such that t2 isa t1 andor t1 isa t2 i do not want the case where t1 and t2 are both a t but where neither isa the other i wish for the most allowed type to be bounded above by the highest of either t1 or t2 in the inheritance tree i am using java 6below is an attempt to show some desired use casesclass experiment static list genericlist new arraylist static arraylist arraylist new arraylist static class test1 static class test2 extends test1 static class test3 extends test1 static t t experiment0t expected t actual return actual almost works but want arbitrary ordering cannot overload due to erasure static t s extends t s experiment1t expected s actual return actual private static void experimentdriver good allowed list l experiment0genericlist arraylist bad allowed want compiletime error object o experiment0new string new integer0 good allowed test1 test1 experiment1new test1 new test3 string string experiment1new string new string list list experiment1genericlist new arraylist good thisallowed experiment1new test2 new test3 experiment1new test3 new test2 experiment1new integer0 new string experiment1new arraylist new linkedlist bad thisallowed want either order experiment1new test3 new test1 experiment1new arraylist genericlist i know that i can achieve something similar with a signature like experimentclasst clazz t expected t actualbut that forces the programmer to explicitly mention the highest allowable type when i would like it inferred by the languagenote that the closer solution cannot simply be overloaded because their erasures are the samei hope i have provided enough information to convey what i want i realize this may just be impossible in java but i hope it is doable this is also my first question on this forum so if i have unknowingly violated any rules i apologize in advance and appreciate your patience,['java'] +594683,how do you get the default binding mode of a dependency property i want to programmatically find out what the default binding mode of a property will befor example if i check it against textboxtextproperty it should be bindingmodetwoway but if it is itemscontrolitemssourceproperty it should be bindingmodeonewayi implemented a custom markupextension and have gotten this far in my code so farpublic override object providevalueiserviceprovider provider var service providergetservicetypeofiprovidevaluetarget as iprovidevaluetarget if service null var target servicetargetobject as dependencyobject var property servicetargetproperty as dependencyproperty not sure what to do with the target and propery here,['c#'] +594727,d3 a sub array of objects i have the following structure length 10 attributes 123 length 7 attributes 1345 length 12 attributes 357910 and i am doing the followingx d3scalelineardomain0 maxheightrange50 wy d3scalelineardomain0 maxheightrangeh 20z d3scalelineardomain0 maxheightrange0 h 20var chart svgselectallgchart dataitems enter appendsvgg attrclass chartchartappendsvgrect attrfill darkblue attrclass data attrx functiond i return xi1 attry functiond i return bottom zdlength 15 attrwidth 4 attrheight functiond i return zdlength zdmin what i would like to do is add circles on each of these rectangles which corresponds to the attributes in my structure basically for one item i should see something like thisg classchart rect filldarkblue classdata x6261538461538462 y15 width6 height530rect circle cx6261538461538462 cyy1 r5 stylefill f00 stroke 808080circle circle cx6261538461538462 cyy2 r5 stylefill f00 stroke 808080circle circle cx6261538461538462 cyy3 r5 stylefill f00 stroke 808080circlegthe only thing i can think of is looping over the attributes and adding them element by elementfor z0 z 3 z chartappendsvgcircle dataitemszattributes stylefill yellow stylestroke gray attrcx functiond i return xi1 attrcy functiond i consolelogd return bottom 15 attrr 5is there a better way to do this,['javascript'] +594757,how to detect if browser console inspector is open whats the best way to determine if the user has the browser console ie firebug webkit inspector opera dragonfly openie i am not interested in merely detecting the presence of the console object in script i want to know when the user has actually opened the debugger panel ideally across the major browsers iesafarichromefirefox and even mobile browsers if possible,['javascript'] +594829,recording video on android using javacv updated 2014 02 17 i am trying to record a video in android using the javacv libi need to record the video in 640x360i have installed everything as described in readmetxt file and i followed the example as belowin this example the video size is thisprivate int imagewidth 320private int imageheight 240in my case i need to record a video in 640x360 h264update i have reverted my code and kept exactly like in the example just changing imagewidth and imageheight to 640x360now i am getting the video like this image video errorpnghere is my codeimport static comgooglecodejavacvcppopencv coreipl depth 8uimport javaioioexceptionimport javanioshortbufferimport androidappactivityimport androidcontentcontextimport androidcontentpmactivityinfoimport androidhardwarecameraimport androidhardwarecamerapreviewcallbackimport androidmediaaudioformatimport androidmediaaudiorecordimport androidmediamediarecorderimport androidosbundleimport androidospowermanagerimport androidutillogimport androidviewthisplayimport androidviewkeyeventimport androidviewlayoutinflaterimport androidviewsurfaceholderimport androidviewsurfaceviewimport androidviewviewimport androidviewviewonclicklistenerimport androidviewwindowmanagerimport androidwidgetbuttonimport androidwidgetlinearlayoutimport androidwidgetrelativelayoutimport comautosonvideohelpershelpersimport comautosonvideologiccamerahelpersimport comgooglecodejavacvffmpegframerecorderimport comgooglecodejavacvcppopencv coreiplimagepublic class ffmpegrecordactivity extends activity implements onclicklistener private final static string class label recordactivity private final static string log tag class label private powermanagerwakelock mwakelock private string ffmpeg link long starttime 0 boolean recording false private volatile ffmpegframerecorder recorder private boolean ispreviewon false private int sampleaudiorateinhz 44100 private int imagewidth 640 private int imageheight 480 private int finalimagewidth 640 private int finalimageheight 360 private int framerate 30 audio data getting thread private audiorecord audiorecord private audiorecordrunnable audiorecordrunnable private thread audiothread volatile boolean runaudiothread true video data getting thread private camera cameradevice private cameraview cameraview private iplimage yuviplimage null layout setting private final int bg screen bx 232 private final int bg screen by 128 private final int bg screen width 700 private final int bg screen height 500 private final int bg width 1123 private final int bg height 715 private final int live width 1280 private final int live height 960 private int screenwidth screenheight private button btnrecordercontrol override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setrequestedorientationactivityinfoscreen orientation landscape setcontentviewrlayoutmain powermanager pm powermanager getsystemservicecontextpower service mwakelock pmnewwakelockpowermanagerscreen bright wake lock class label mwakelockacquire initlayout initrecorder override protected void onresume superonresume if mwakelock null powermanager pm powermanager getsystemservicecontextpower service mwakelock pmnewwakelockpowermanagerscreen bright wake lock class label mwakelockacquire override protected void onpause superonpause if mwakelock null mwakelockrelease mwakelock null override protected void ondestroy superondestroy recording false if cameraview null cameraviewstoppreview cameradevicerelease cameradevice null if mwakelock null mwakelockrelease mwakelock null private void initlayout get size of screen thisplay thisplay windowmanager getsystemservicecontextwindow service getdefaultthisplay screenwidth thisplaygetwidth screenheight thisplaygetheight relativelayoutlayoutparams layoutparam null layoutinflater myinflate null myinflate layoutinflater getsystemservicecontextlayout inflater service relativelayout toplayout new relativelayoutthis setcontentviewtoplayout linearlayout previewlayout linearlayout myinflateinflate rlayoutmain null layoutparam new relativelayoutlayoutparamsscreenwidth screenheight toplayoutaddviewpreviewlayout layoutparam add control button start and stop btnrecordercontrol button findviewbyidridrecorder control btnrecordercontrolsettextstart btnrecordercontrolsetonclicklistenerthis add camera view int thisplay width d int 10 bg screen width screenwidth bg width int thisplay height d int 10 bg screen height screenheight bg height int prev rw prev rh if 10 thisplay width d thisplay height d 10 live width live height prev rh thisplay height d prev rw int 10 thisplay height d live width live height else prev rw thisplay width d prev rh int 10 thisplay width d live height live width layoutparam new relativelayoutlayoutparamsprev rw prev rh layoutparamtopmargin int 10 bg screen by screenheight bg height layoutparamleftmargin int 10 bg screen bx screenwidth bg width cameradevice cameraopen logilog tag cameara open cameraview new cameraviewthis cameradevice toplayoutaddviewcameraview layoutparam logilog tag cameara preview start ok initialize ffmpeg recorder private void initrecorder logwlog tag init recorder if yuviplimage null yuviplimage iplimagecreatefinalimagewidth finalimageheight ipl depth 8u 2 logilog tag create yuviplimage ffmpeg link camerahelpersgetoutputmediafile camerahelpersmedia type videotostring logilog tag ffmpeg url ffmpeg link recorder new ffmpegframerecorderffmpeg link finalimagewidth finalimageheight 1 recordersetformatmp4 recordersetsampleratesampleaudiorateinhz set in the surface changed method recordersetframerateframerate logilog tag recorder initialize success audiorecordrunnable new audiorecordrunnable audiothread new threadaudiorecordrunnable public void startrecording try recorderstart starttime systemcurrenttimemillis recording true audiothreadstart catch ffmpegframerecorderexception e eprintstacktrace public void stoprecording runaudiothread false if recorder null recording recording false logvlog tag finishing recording calling stop and release on recorder try recorderstop recorderrelease catch ffmpegframerecorderexception e eprintstacktrace recorder null override public boolean onkeydownint keycode keyevent event if keycode keyeventkeycode back if recording stoprecording finish return true return superonkeydownkeycode event audio thread gets and encodes audio data class audiorecordrunnable implements runnable override public void run androidosprocess setthreadpriorityandroidosprocessthread priority urgent audio audio int buffersize short audiodata int bufferreadresult buffersize audiorecord getminbuffersizesampleaudiorateinhz audioformatchannel in mono audioformatencoding pcm 16bit audiorecord new audiorecordmediarecorderaudiosourcemic sampleaudiorateinhz audioformatchannel in mono audioformatencoding pcm 16bit buffersize audiodata new shortbuffersize logdlog tag audiorecordstartrecording audiorecordstartrecording ffmpeg audio encoding loop while runaudiothread logvlog tagrecording recording bufferreadresult audiorecordreadaudiodata 0 audiodatalength if bufferreadresult 0 logvlog tag bufferreadresult bufferreadresult if recording is not true when start this thread it never gets set according to this if statement why good question if recording try recorderrecordshortbufferwrapaudiodata 0 bufferreadresult logvlog tagrecording 1024i to 1024i1024 catch ffmpegframerecorderexception e logvlog tag egetmessage eprintstacktrace logvlog tag audiothread finished release audiorecord encoding finish release recorder if audiorecord null audiorecordstop audiorecordrelease audiorecord null logvlog tag audiorecord released camera thread gets and encodes video data class cameraview extends surfaceview implements surfaceholdercallback previewcallback private surfaceholder mholder private camera mcamera public cameraviewcontext context camera camera supercontext logwcamera camera view mcamera camera mholder getholder mholderaddcallbackcameraviewthis mholdersettypesurfaceholdersurface type push buffers mcamerasetpreviewcallbackcameraviewthis override public void surfacecreatedsurfaceholder holder try stoppreview mcamerasetpreviewthisplayholder catch ioexception exception mcamerarelease mcamera null public void surfacechangedsurfaceholder holder int format int width int height logvlog tag setting imagewidth imagewidth imageheight imageheight framerate framerate cameraparameters camparams mcameragetparameters camparamssetpreviewsizeimagewidth imageheight logvlog tag preview framerate camparamsgetpreviewframerate camparamssetpreviewframerateframerate mcamerasetparameterscamparams startpreview override public void surfacedestroyedsurfaceholder holder try mholderaddcallbacknull mcamerasetpreviewcallbacknull catch runtimeexception e the camera has probably just been released ignore public void startpreview if ispreviewon mcamera null ispreviewon true mcamerastartpreview public void stoppreview if ispreviewon mcamera null ispreviewon false mcamerastoppreview override public void onpreviewframebyte data camera camera get video data if yuviplimage null recording yuviplimagegetbytebufferputdata final int starty 640 480 360 2 final int leny 640 360 yuviplimagegetbytebufferputdata starty leny final int startvu 640 480 320 2 240 180 2 final int lenvu 320 180 2 yuviplimagegetbytebufferputdata startvu lenvu logvlog tag writing frame try long t 10 systemcurrenttimemillis starttime if t recordergettimestamp recordersettimestampt recorderrecordyuviplimage catch ffmpegframerecorderexception e logvlog tag egetmessage eprintstacktrace override public void onclickview v if recording startrecording logwlog tag start button pushed btnrecordercontrolsettextstop else this will trigger the audio recording loop to stop and then set isrecorderstart false stoprecording logwlog tag stop button pushed btnrecordercontrolsettextstart,['android'] +594852,how to get first item from a javautilset i have a set instancesetstring siteidset setstring pcontextgetparentgetpropertyvaluegetcatalogpropertiesgetsitespropertynamethe pcontextgetparentgetpropertyvalue is outofthebox code upon which i do not have any control to modifyrequirementi wanted to get the first default element out of it always however i could not find a method getindex like in an arraylisthence right now i am doing like thisfor iteratorstring it siteidsetiterator ithasnext siteid itnext breakis there any other efficient way short and better of achieving this,['java'] +594877,generate class diagram using xcode project i have created a ios project and want to create class diagram and before that manually i just wanted to know if there are any uml class diagram generator tool for xcode or any other tool that generates the class diagram using the xcode project thanks,"['ios', 'iphone']" +594934,whats the difference setting embed interop types true and false in visual studio in visual studio when adding one reference to the project the properties window has an option embed inteop types should we set it to true or false whats the differencesince we have a lot of projects among some of them reference was set to false others were set to true it is totally mess up and the bulid server also have the same warnings what does areference was created to embedded interop assemblya meanso we plan to change all the embed inteop types to false what risk would we get,['c#'] +594948,incorrect command line arguments number when passing i am writing a c program about reverse polish notation which takes its operands and operators through the command line arguments but things go wrong when the multiply operator occurs and i do not know whyhere is the little program to debug testc int mainint argc char argv printfdn argc return 0 run case result test a b 3 test 66so why the argument makes a wrong result,['c'] +594985,uibarbuttonitems selected color would not change properly in ios 7 so i am having issues with uibarbuttonitem appearances in ios 7 there is a property which i cannot find any documentation for that seems to set the opacity of navigation bar buttons when pressed and i do not know how to modify itselfnavigationcontrollernavigationbar settintcoloruicolor whitecoloruibarbuttonitem appearance settitletextattributesuitextattributetextcolor uicolor whitecolor forstateuicontrolstatenormaluibarbuttonitem appearance settitletextattributesuitextattributetextcolor uicolor orangecolor forstateuicontrolstatehighlightedfor this code the result i get is shown belowi am not sure whats going on here the first problem is that i cannot seem to get the arrow to tint because there is no settintcolorforstate method the second problem is this awful opacitytint when pressed thanks,"['ios', 'objective-c']" +594992,mvc5 attribute routing within area cannot find view when i am inside admin area and map my routes using attribute routing it cannot find view because it does not look inside actual area view folders but instead only global view foldersonly if i pass full path to view it then can thisplay it otherwise it throws me errorerrorthe view authorize or its master was not found or no view engine supports the searched locations the following locations were searchedviewshomeauthorizeaspxviewshomeauthorizeascxviewssharedauthorizeaspxviewssharedauthorizeascxviewshomeauthorizecshtmlviewshomeauthorizevbhtmlviewssharedauthorizecshtmlviewssharedauthorizevbhtmlcoderouteprefixadminpublic class homecontroller controller route public actionresult index return viewauthorize error return viewareasadminviewshomeauthorizecshtml working note that if i thisable attribute routing and switch back to good old routes it will work any way of fixing this or it is working as intended and i should apply full path in all my areas,['c#'] +595092,google map ios satellite view is too cloudy now i have been working on one application since last one year which which make use of google map ios sdk application provide user with flexibility to switch between satellite view and normal view everything was working fine till 2 days before suddenly i observed tile images in case of satellite view are too cloudy and satellite view looks too bad now our application is showing satellite view of st barthelemy island below are the satellite view of island which does not look good anymore and my client app sale is affected because of this newoldi have following questionis there way to request old version of google map tiles google earth seems to have such flexibility where we can specify the tile db date does google map ios sdk support network links i have identified one other workaround to suppress this cloudy image by overriding with custom kml which make use of network links but this google map ios sdk does not seems to support network linkshow frequently google update their tile database so that we wait for their next tile update is there direct forum where we can raise a concern for this,"['ios', 'objective-c']" +595107,file upload progress during upload i am having some problem with file upload progress i am using zend framework 22 on xampp windows 7form signupform namespace applicationform use zendformform use zendformelement class signupform extends form public function constructname null thisaddarray name username type text options array label username label attributes array class formlabel thisaddarray type zendformelementfile name fileupload attributes array id fileupload options array label photo label attributes array class formlabel controller indexcontroller phpnamespace applicationcontrolleruse zendmvccontrollerabstractactioncontrolleruse zendviewmodelviewmodeluse applicationmodelsignupuse applicationformsignupformclass indexcontroller extends abstractactioncontroller protected usertable protected usertablee public function getsigntabletable object if thisobject sm thisgetservicelocator thisobject smgettable return thisobject public function indexaction return new viewmodel public function signupaction form new signupform formgetsubmisetvaluesubmit request thisgetrequest if requestispost album new signup t thisgetsigntabledbadapterdbtableuser usertablee formsetinputfilteralbumgetinputfiltert data array merge recursive thisgetrequestgetposttoarray thisgetrequestgetfilestoarray formsetdatadata if formisvalid albumexchangearrayformgetdata thisgetsigntablealbummodelalbumtabledbtableuser usertablesaveuseralbumfile upload progress form is valid save the form if emptypostisajax return new jsonmodelarray status true redirect thisurlfromrouteuploadformsuccess formdata album else fallback for nonjs clients return thisredirecttorouteuploadformsuccess else if emptypostisajax send back failure information via json return new jsonmodelarray status false formerrors formgetmessages formdata formgetdata filter new zendfilterfilerenameuploadpublicphoto albumusername filtersetuseuploadextensiontrue filtersetrandomizetrue filterfilterdatafileupload return arrayform form public function uploadprogressaction id thisparamsfromqueryid null progress new zendprogressbaruploadsessionprogress return new zendviewmodeljsonmodelprogressgetprogressid model signup namespace applicationmodeluse zendhttpphpenvironmentrequestuse zendinputfilterinputfilteruse zendinputfilterinputfilterawareinterfaceuse zendinputfilterinputfilterinterfaceuse zendvalidatorclass signup implements inputfilterawareinterface public username public fileupload protected inputfilter public function exchangearraydata thisusername emptydatausername datausername null thisfileupload emptydatafileupload datafileupload null public function getarraycopy return get object varsthis public function setinputfilterinputfilterinterface inputfilter throw new exceptionnot used public function getinputfilteradapter null if thisinputfilter inputfilter new inputfilterinputfilteraddarray name fileupload required true thisinputfilter inputfilter return thisinputfilter view index phpthispluginbasepathsetbasepathzendtestpublictitle signupthisheadtitletitleh1php echo thisescapehtmltitle h1div clasignupform php formprepare formsetattributeaction thisurlsignup arrayaction signup formsetattributemethod post formsetattributeclass signform formsetattributeenctype multipartformdata echo thisformopentagform errmsg formgetmessages username div clasignupformrow php echo thisformlabelformgetusername echo thisforminputformgetusername if errmsg if isseterrmsgusername foreach errmsgusername as key value span classformerror php if key isempty echousername required else echo value span php else span classforminsimg srcphp echo thisbasepathimagestickpng span php else span classforminsusername must be 569 characters and alphanumeric onlyspan php div file php echo thisformfilesessionprogress div clasignupformrow php echo thisformlabelformgetfileupload echo thisformfileformgetfileupload if errmsg if isseterrmsgfileupload print rerrmsgfileupload foreach errmsgfileupload as key value span classformerror php if key isempty echophoto required else echo value span php div submit div clasignupformrow label classformlabellabel buttonsubmitbutton div php echo thisformclosetag file upload progressbar div idprogress classhelpblock div classprogress progressinfo progrestriped div classbardiv div ppdivscript srcphp echo thisbasepathjsjqueryminjs scriptscript srcphp echo thisbasepathjsjqueryformjs scriptscriptvar progressintervalfunction getprogress poll our controller action with the progress id var url php echo thisurlsignup uploadprogressid progress keyval getjsonurl functiondata if datastatus datastatusdone var value mathfloordatastatuscurrent datastatustotal 100 showprogressvalue uploading else showprogress100 complete clearintervalprogressinterval function startprogress showprogress0 starting upload progressinterval setintervalgetprogress 900function showprogressamount message progreshow progress barwidthamount progress phtmlmessage if amount 100 progress progress addclassprogressinfo active removeclassprogresuccess else progress progress removeclassprogressinfo active addclassprogresuccess function register a submit event listener on the form to perform the ajax post signuponsubmit functione epreventdefault if fileuploadval no files selected abort return perform the submit fnajaxsubmitdebug true thisajaxsubmit beforesubmit functionarr form options notify backend that submit is via ajax arrpush name isajax value 1 success function response statustext xhr form clearintervalprogressinterval showprogress100 complete todo youll need to do some custom logic here to handle a successful form post and when the form is invalid with validation errors if responsestatus todo do something with a successful form post like redirect windowlocationreplaceresponseredirect else clear the file input otherwise the same file gets reuploaded var fileinput fileupload fileinputreplacewith fileinputvalclone true todo do something with these errors showerrorsresponseformerrors error functiona b c note this callback is not called when the form is invalid it is called when the browser is unable to initiate or complete the ajax submit you will need to handle validation errors in the success callback consoleloga b c start the progress polling startprogress scriptdivmoduleconfig phpreturn array router array routes array home array type zendmvcrouterhttpliteral options array route zendtest defaults array controller applicationcontrollerindex action index application array type literal options array route zendtestapplication defaults array namespace applicationcontroller controller index action index may terminate true child routes array default array type segment options array route controlleraction constraints array controller azazazaz09 action azazazaz09 defaults array signup signup array type segment options array route zendtestapplicationsignupactionid constraints array action azazazaz09 id 09 defaults array controller applicationcontrollerindex action signup routes end router ends service manager array factories array translator zendi18ntranslatortranslatorservicefactory translator array locale en us translation file patterns array array type gettext base dir dir language pattern smo controllers array invokables array applicationcontrollerindex applicationcontrollerindexcontroller view manager array thisplay not found reason true thisplay exceptions true doctype html5 not found template error404 exception template errorindex template map array layoutlayout dir viewlayoutlayoutphtml applicationindexindex dir viewapplicationindexindexphtml applicationindexsignup dir viewapplicationsignupindexphtml error404 dir viewerror404phtml errorindex dir viewerrorindexphtml template path stack array dir view my signup page open at zendtestapplicationsignupwhen i click on the submit button then nothing happensiam following the afile upload progressa tutorial of frameworkzendcom please see this aa page and see the red colored texts thatas what i donat understand of that tutorial please tell me whats wrong did i dothanksupdate if i use the following code then please tell me how can i add file upload progressbar to my form by using zendprogressbaruploaduploadprogress how should i change my controller or model or view controller if formisvalid albumexchangearrayformgetdata albumact code randgetstring5 albumdkey randgetstring5 thisgetsigntablealbummodelalbumtabledbtableuser usertablesaveuseralbumfile filter new zendfilterfilerenameuploadpublicphoto albumusername filtersetuseuploadextensiontrue filtersetrandomizetrue filterfilterdatafileupload model for filter and validation signupphp inputfilteraddarray name fileupload required true validators array filevalidatorattachnew zendvalidatorfileuploadfilearray messages array zendvalidatorfileuploadfileno file photo required true view php echo thisformfilesessionprogress div clasignupformrow php echo thisformlabelformgetfileupload echo thisformfileformgetfileupload if errmsg if isseterrmsgfileupload print rerrmsgfileupload foreach errmsgfileupload as key value span classformerror php if key isempty echophoto required else echo value span php divupdate 2view div clasignupform php formprepare formsetattributeaction thisurlsignup arrayaction signup formsetattributemethod post formsetattributeclass signform formsetattributeid signup formsetattributeenctype multipartformdata echo thisformopentagform errmsg formgetmessages username div clasignupformrow php echo thisformlabelformgetusername echo thisforminputformgetusername if errmsg if isseterrmsgusername foreach errmsgusername as key value span classformerror php if key isempty echousername required else echo value span php else span classforminsimg srcphp echo thisbasepathimagestickpng span php else span classforminsusername must be 569 characters and alphanumeric onlyspan php div file div clasignupformrow php echo thisformlabelformgetfileupload div classfilediv php echo thisformfileformgetfileupload a onclickselect file classpurebutton upbuttonchoose an imagea br image preview img idupimg nameupimg src stylebr div php if errmsg if isseterrmsgfileupload foreach errmsgfileupload as key value span classformerror php if key isempty echophoto required else echo value span php div submit div clasignupformrow label classformlabellabel php echo thisformsubmitformgetsubmi div php echo thisformclosetag divprogress bar div classprogress div classbardiv div classpercent0div divscript srcphp echo thisbasepathjsjqueryminjs scriptscript srcphp echo thisbasepathjsjqueryformminjs script script typetextjavascriptdocumentreadyfunction variables var preview upimg var status status var percent percent var bar bar only for image preview fileuploadchangefunction previewfadeout html filerender api var ofreader new filereader ofreaderreadasdataurldocumentgetelementbyidfileuploadfiles0 ofreaderonload function ofrevent previewattrsrc ofreventtargetresultfadein submit form with ajax request signupajaxform set data type json datatypejson reset before submitting beforesend function statusfadeout barwidth0 percenthtml0 progress bar call back uploadprogress functionevent position total percentcomplete var pvel percentcomplete barwidthpvel percenthtmlpvel complete call back complete functiondata previewfadeout800 statushtmldataresponsejsonstatusfadein function select file documentgetelementbyidfileuploadclick return false scriptform validation modelsignupphpclass signup implements inputfilterawareinterface public username public fileupload protected inputfilter protected usernamevalidator protected filevalidator protected adapter public function exchangearraydata thisusername emptydatausername datausername null thisfileupload emptydatafileupload datafileupload null public function getarraycopy return get object varsthis public function setinputfilterinputfilterinterface inputfilter throw new exceptionnot used public function getinputfilteradapter null thisadapter adapter if thisinputfilter inputfilter new inputfilter usernamevalidator new zendvalidatorvalidatorchain filevalidator new zendvalidatorvalidatorchain inputfilteraddarray name username required true filters array arrayname striptags validators array usernamevalidatorattach new zendvalidatornotemptyarray true attachnew zendvalidatorregexarray pattern azaz09 messages array zendvalidatorregexinvalid username is not valid zendvalidatorregexnot match only small alphabet digit and underscore are allowed username must start with an alphabet true inputfilteraddarray name fileupload required true validators array filevalidatorattachnew zendvalidatorfileuploadfilearray messages array zendvalidatorfileuploadfileno file photo required true thisinputfilter inputfilter return thisinputfilter it works when the form is valid but if the form has error suppose ausernamea field is empty then it doesnat show error message which should come from the model asignupphpa and the progressbar still shows file upload progress even the file actually not uploaded thoughand if i cut the following lines from the aindexphtmla and add them to the aheada of alayoutphtmla then the form validation works but the file upload progressbar doesnat worksthe form submits like normal php form but the image is shown by the jquery when the image file is selected indexphtml script srcphp echo thisbasepathjsjqueryminjs script script srcphp echo thisbasepathjsjqueryformminjs script layoutphtml scripts php echo thisheadscriptprependfilethisbasepathjshtml5js textjavascript arrayconditional lt ie 9 prependfilethisbasepathjsbootstrapminjs prependfilethisbasepathjsjqueryminjs prependfilethisbasepathjsjqueryformminjs head,['php'] +595162,android emulator not receiving push notifications i am using push notifications on google cloud however for some reason i cant receive push notifications on the emulator the same application does receive notifications when i test it on a real device howeverhas anyone else encountered this or found solutions to it the emulated device has net access and is the same android version as the real one so i cant think of any reason it should not work,['android'] +595193,adding an existing json string with gson i have a string object containing some arbitrary json i want to wrap it inside another json object like this version 1 content arbitrary json string objecthow can i reliably add my json string as an attribute to it without having to build it manually ie avoiding tedious string concatenationclass wrapper int version 1gsontojsonnew wrapper then whatnote that the added json should not be escaped but a be part of the wrapper as a valid json entity like this version 1 content the content namefrom the string objectgivenstring arbitraryjson the content namefrom the string object,['java'] +595244,how to explain katana and owin in simple words and uses i have read many articles about the owin and katana projects but i could not get the whole picture of it for a normal web developer who uses aspnetwhat exactly is owin and what problems does it solve in simple words what is its relation to iisdoes owin replace iis if not in what situations does owin best fithow could owin help me in my daily work projectshow could owin help me in a selfimprovement projects,['asp.net'] +595264,custom console log function a consolelog wrapper function log msgorobj ifdev mode consolelog message msgorobj caller argumentscalleecallertostring so i have attempted to write a simple custom console log function as above however i am struggling to find which file and line the caller came from the most i can see is the function that called it has anyone done anything similar or is this even possibleexample used in somescriptjs from line 70logsome very important message,['javascript'] +595268,how java checks that is out of date i have a linux box which is not connected to interneti have installed on it firefox 240 and jre170 40 and also 170 17when i start ff with a web application locally installed on the box i am getting a warning popup that java update needed yourjava version is out of datei do not undesrtand how java knows that is out of date what compares to what i would assume that checks the available versions at oraclecom and if the current one installed on the system is too old then drops this warningor the application itself which is started carries some information about java version what was available or what was used at its compile time,['java'] +595307,css3 simple donut chart what i am trying to do is create a simple donut chart i am currently using css3 only but i do not know if it is possible without javascriptwhat i have so far htmldiv classdonutcontainer stylebackground 9c0 div classdonutinner div classdonutlabelhtmldiv divdivcssdonutcontainer width 150px height 150px float left webkitborderradius 75px mozborderradius 75px borderradius 75px marginright 20pxdonutinner width 134px height 134px position relative top 8px left 8px background f webkitborderradius 65px mozborderradius 65px borderradius 65pxdonutlabel lineheight 130px textalign center fontsize 20pxi would like to thisplay the green and blue colors as the precentage so no green is 0 and full green 360 degrees is 100 maybe even with a simple animation when the chart is loaded if its possibleyour help is much appreciated,['css'] +595313,getting cannot open include file atlbaseh no such file or directory error i am swapping machines between two windows 81 laptops and have just loaded the project i am working on from tfs on one machine it compiles on the other it does not and gives the first errorerror c1083 cannot open include file atlbaseh no such file or directoryon both laptops i am running visual studio ultimate 2013 on the first laptop i have checked to see where it is picking up atlbaseh and it is from cprogram files x86microsoft visual studio 110vcatlmfcinclude ie from the visual studio 2012 installation directory on the new machine i do not have visual studio 2012 installed so the directory cprogram files x86microsoft visual studio 110vcatlmfcinclude does not existother people have similar problems eg ramilols question because they are using visual studio express i am using ultimateit could be an environment variables problem as suggested by raj raj but my include directory paths under vc directories are vcinstalldirincludevcinstalldiratlmfcincludewindowssdk includepath as requiredmy general question is how do i fix this but i would also be interested to know how i check and set the value of vcinstalldir since cprogram files x86microsoft visual studio 120vcatlmfcinclude does have atlbaseh in so i am flummoxed as to why it is not picked up edit 1 rewording let me have another go at wording this questioni have loaded a visual studio 2013 project onto a new build laptop from tfs it will not build and gives errors like error c1083 cannot open include file atlbaseh no such file or directory the file atlbaseh is present on the new machine in the directory cprogram files x86microsoft visual studio 120vcatlmfcincludein my projects properties my include directory paths under vc directories are vcinstalldirincludevcinstalldiratlmfcincludewindowssdk includepathhow do i check what those macros are set to and if they are not where atlbaseh is ie cprogram files x86microsoft visual studio 120vcatlmfcinclude how do i fix that edit 2 microsoft visual c rethistributables installed responding to jp2codes answer the machine that works and the one that does not have a similar array of microsoft visual c rethistributables installed as the following screenshot shows the working machines on the left edit 3 environment variables in his answer pje explains how to look up the environment variables vcinstalldir is correctly set to cprogram files x86microsoft visual studio 120vc but if i right click on the line include atlbaseh i get this error which suggests that despite vcinstalldir being correct that is not where vs is looking edit 4 platform toolkit setting another possibility is the configuration properties general platform toolset project setting suggested by manuell in the comments and michael burr in his answer for the project it is set to set to visual studio 2012 v110 but the only other option listed in the dropdown is v110 wp80 which when selected becomes windows phone 80 v110 if i hand edit the vcxproj file in notepad and reopening the project in visual studio ultimate 2013 the property page now lists the platform toolset as visual studio 2013 v120 not installed if i start a new c windows store project i can set platform toolset to visual studio 2013 v120 without issue in fact it is the only option listed in the dropdown nb the new project has target platform version set to windows 81 and it is greyed out so i cannot change it while the failing project has it set to windows 8 edit 5 entire project settings file in the comments michael suggests that maybe posting the vcxproj somewhere like as a gist on github might be helpful i have posted it here edit 6 uninstalling and reinstalling visual studio 2013 ultimate has no effect the same error recurs,['c++'] +595323,rails datetoday 1day using the rails console i just got bit by thisassume today is december 11datetoday1day december 10 no spacesdatetoday 1day december 10 a space on both sides of the minus signdatetoday 1day december 11 whatdatetoday 5days still december 11can someone explain whats going on here i am a little worried about how easy this could be missed in code any other suggestions on how to code this,"['ruby-on-rails', 'ruby']" +595393,dagred3 ie workaround for svg foreignobject element i am an undergrad coop and am currently developing a webpage project for my team in the beginning i chose to use dagred3 library to construct graphs and they work fine on chrome then i realize that foreignobject element in svg does not work on ie which happens to be the primary browser to support since my goal is essentially to populate html content in each graph component i was wondering if there was any workaround to implement this on ie still using dagred3 or any recommendations for a different graph libraryupdateessentially i wanted to create graph shown in the screenshot below below is the code i use now to construct the graph using dagred3 html snippetdiv idgraphsection svg g transformtranslate2020 svgdivjs snippetvar g new dagred3digraph construct nodesfor var i 0 i datanodeslength i var label div classgraphlabel label div classcomp datanodesivaluetype leftnbspdiv label bnbsp datanodesivaluename bbr label span classinfostart datanodesivaluestart spanbr label span classinfoend datanodesivalueend spanbr label span classinfolaunched by datanodesivalueuser span label div gaddnodedatanodesiid label label construct edgesfor var j 0 j datalinkslength j gaddedgenull datalinksjstart datalinksjendvar layout rendererrung d3selectgraphsection svg g,['javascript'] +595509,what is the maximum size for the postmessage method that enables interframe communication it is not clear from searching on google and looking through documentation whats the maximum length on a message sent via windowpostmessage we assume this varies by browser,"['javascript', 'html']" +595515,nodejs mysql jsonresult callbackissue no response to client i would like to use nodejs to query a mysqldatabase and return the results as json to be used in a mobile application unfortunately my request just sorta times out and the server does nothing for a good 2 minutes until the logfiles show my consolelogstatementsalso the callback does not return anything as result it is just empty check dependenciesvar http requirehttp create the http server reference httpcreateserverfunctionrequest response attach listener on end event requestonclose function consolelogrequest run asynchronous getsqlfunctionerr result consolelogjson result responsewritehead200 contenttype xapplicationjson send data as json string responseendresult listen30 access mysql via nodemysql function getsqlcallback var mysql requiremysql var connection mysqlcreateconnection host localhost user user password pw database db socketpath varrunmysqldmysqldsock socket for communication from debian client seems not to be set correcly by default connectionconnect var json var query select from test connectionqueryquery functionerr results fields if err return callbackerr null consolelogthe result is results0 wrap resultset as json json jsonstringifyresults connectionend callbacknull jsonoutput after like 2 minutes node appjsrequestjsonthe result is test avc json2 testavcbased on my very basic understanding of the whole nodejsconcept my code should query the db it does and return a json once it is finished via the callbackfunction apparently does not which than is sent back as a response to the client cannot really check that since the jsons emptyi guess i made one or a couple major mistakes help andor helpful links would be much appreciated thankssolution thanks to hexacyanide check dependenciesvar http requirehttp create the http server reference correction 1 using the requestonclose function listener is not required anymorehttpcreateserverfunctionreq res consolelogreceving request var callback functionerr result reswritehead200 contenttype xapplicationjson consolelogjson result resendresult getsqlcallbacklisten30 access mysql via nodemysql function getsqlcallback var mysql requiremysql var connection mysqlcreateconnection host localhost user user password pw database db socketpath varrunmysqldmysqldsock socket for communication from debian client seems not to be set correcly by default connectionconnect var json var query select from test connectionqueryquery functionerr results fields if err return callbackerr null consolelogthe queryresult is results0 wrap resultset as json json jsonstringifyresults correction 2 nest the callback correctly connectionend consolelogjsonresult json callbacknull json,"['javascript', 'mysql']" +595551,afnetworking 20 track file upload progress i am relatively new to afnetworking 20 using the code snippet below i have been able to successfully upload a photo to my url i would like to track the incremental upload progress but i cannot find an example of doing this with version 20 my application is ios 7 so i have opted for afhttpsessionmanagercan anyone offer an example of how to modify this snippet to track upload progressafhttpsessionmanager manager afhttpsessionmanager managernsdata imagedata uiimagejpegrepresentationuiimage imagenamedmyimagejpg 10manager post parametersdatatopost constructingbodywithblockidafmultipartformdata formdata formdata appendpartwithfiledataimagedata nameattachment filenamemyimagejpg mimetypeimagejpeg successnsurlsessiondatatask task id responseobject nslogsuccess responseobject failurensurlsessiondatatask task nserror error nslogfailure error taskresponse description,['ios'] +595555,c11 movex actually means static castx just reading stroustrups c programming language 4th ed and in chapter 7 he saysmovex means static castxx where x is the type of xandsince movex does not move x it simply produces an rvalue reference to x it would have been better if move had been called rvalmy question is if move just turns the variable in to an rval what is the actual mechanism which achieves the moving of the reference to the variable by updating the pointer i thought move is just like a move constructor except the client can use move to force the compiler,['c++'] +595557,blob url in internet explorer with angularjs given this code from someone elsevar module angularmodulemyapp modulecontrollermyctrl function scope scopejson jsonstringifya1 b2moduledirectivemydownload function compile return restricte scope data linkfunction scope elm attrs function geturl return urlcreateobjecturlnew blobjsonstringifyscopedata type applicationjson elmappendcompile a classbtn downloadbackupjson href geturl download a scope scopewatchscopedata function elmchildren0href geturl the fiddle example works fine to download in chrome but clicking the download link does nothing in ie11 no error no warning no response at allbut according to this it is supported in ie10 and 11is there some ie security setting that needs to be changed or what is going on,['javascript'] +595560,is google play services for froyo compatible with android 23 and higher in reading the google play services setup documentation it sounds like google play services for froyo rev 12 should be forwardscompatible with android 23 and abovehowever i am having issues implementing this in my gpstest app on github which currently includes google play services for froyoif i try to build a project using google play services for froyo rev 12 with the elementmetadata androidnamecomgoogleandroidgmsversion androidvalueintegergoogle play services version included in the androidmanifestxml i get a build errorerror no resource found that matches the given name at value with value integergoogle play services versionthis is expected from my current understanding because this integer does not exist in the google play services for froyo project sdkextrasgooglegoogle play services froyoresvaluesif i remove this element from the manifest it works fine when building and debugging the app via eclipse as i would expect however when i export the apk install on a device samsung galaxy s3 android 43 google play services v4034 downloading the exported apk from dropbox and run i get the following error on startup and the app crashesjavalangillegalstateexception the metadata tag in your apps androidmanifestxmldoes not have the right value expected 4030500 but found 0 you must have the following declaration within the application element metadata androidnamecomgoogleandroidgmsversionandroidvalueintegergoogle play services version at comgoogleandroidgmscommonbaunknown source at comgoogleandroidgmsmapsabnaunknown source at comgoogleandroidgmsmapsmgunknown source at comgoogleandroidgmsmapsmaunknown source at comgoogleandroidgmsabaunknown source at comgoogleandroidgmsabaunknown source at comgoogleandroidgmsmapssupportmapfragmentoncreateunknown source at androidsupportv4appfragmentperformcreateunknown source at androidsupportv4appfragmentmanagerimplmovetostateunknown source at androidsupportv4appfragmentmanagerimplmovetostateunknown source at androidsupportv4appbackstackrecordrununknown source at androidsupportv4appfragmentmanagerimplexecpendingactionsunknown source at androidsupportv4appfragmentmanagerimplexecutependingtransactionsunknown source at androidsupportv4appfragmentstatepageradapterfinishupdateunknown source at androidsupportv4viewviewpagerpopulateunknown source at androidsupportv4viewviewpagerpopulateunknown source at androidsupportv4viewviewpageronmeasureunknown source at androidviewviewmeasureviewjava16848 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava5245 at androidwidgetframelayoutonmeasureframelayoutjava310 at androidviewviewmeasureviewjava16848 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava5245 at comandroidinternalwidgetactionbaroverlaylayoutonmeasureactionbaroverlaylayoutjava302 at androidviewviewmeasureviewjava16848 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava5245 at androidwidgetframelayoutonmeasureframelayoutjava310 at comandroidinternalpolicyimplphonewindowdecorviewonmeasurephonewindowjava2586 at androidviewviewmeasureviewjava16848 at androidviewviewrootimplperformmeasureviewrootimpljava2189 at androidviewviewrootimplmeasurehierarchyviewrootimpljava1352 at androidviewviewrootimplperformtraversalsviewrootimpljava1535 at androidviewviewrootimpldotraversalviewrootimpljava1249 at androidviewviewrootimpltraversalrunnablerunviewrootimpljava6364 at androidviewchoreographercallbackrecordrunchoreographerjava791 at androidviewchoreographerdocallbackschoreographerjava591 at androidviewchoreographerdoframechoreographerjava561 at androidviewchoreographerframethisplayeventreceiverrunchoreographerjava7 at androidoshandlerhandlecallbackhandlerjava730 at androidoshandlerthispatchmessagehandlerjava92 at androidoslooperlooplooperjava137 at androidappactivitythreadmainactivitythreadjava5455 at javalangreflectmethodinvokenativenative method at javalangreflectmethodinvokemethodjava525 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava1187 at comandroidinternaloszygoteinitmainzygoteinitjava1003 at dalviksystemnativestartmainnative methodi am using google play services for froyo rev 12 and heres the androidmanifestxml with the full version infomanifest androidversionname3265 834030 androidversioncode3265130 packagecomgoogleandroidgms xmlnsandroid usessdk androidminsdkversion8 manifestis there a way i can deploy a single apk to google play using google play services for froyo rev 12 for android 22 and higheror do i need to deploy two apks to google play one using google play services for froyo for android 22 and one using google play services for android 23 and up if i want to retain support for froyohas anyone successfully deployed google play services for froyo on android 23 and up,['android'] +595692,how to extract the sign of an integer in ruby i need a function which returnsprints the sign on an integer so far i came up with thisdef extract signinteger integer 0 endis there a builtin ruby method which does that,['ruby'] +595699,how to change the table name in visual studio 2013 in design mode i created a sql database table in visual studio 2013 i want to rename it but the name property is thisabled how can i change the table name,"['c#', 'asp.net']" +595771,does robolectric support api level i have some test which i would like to run with robolectric i use the 23snapshot as my app uses the actionbarcompat i needed to use 23snapshot version as robolectric could not find the appcompat themes before so i setup the classpath in eclipse and i end up with thisjavalangunsupportedoperationexception robolectric does not support api level 9 sorryat orgrobolectricsdkconfiginitsdkconfigjava24at orgrobolectricrobolectrictestrunnerpicksdkversionrobolectrictestrunnerjava288at orgrobolectricrobolectrictestrunnergetenvironmentrobolectrictestrunnerjava264at orgrobolectricrobolectrictestrunneraccess100robolectrictestrunnerjava57at orgrobolectricrobolectrictestrunner2evaluaterobolectrictestrunnerjava186at orgjunitrunnersblockjunit4classrunnerrunnotignoredblockjunit4classrunnerjava79at orgjunitrunnersblockjunit4classrunnerrunchildblockjunit4classrunnerjava71at orgjunitrunnersblockjunit4classrunnerrunchildblockjunit4classrunnerjava49at orgjunitrunnersparentrunner3runparentrunnerjava193at orgjunitrunnersparentrunner1scheduleparentrunnerjava52at orgjunitrunnersparentrunnerrunchildrenparentrunnerjava191at orgjunitrunnersparentrunneraccess0parentrunnerjava42at orgjunitrunnersparentrunner2evaluateparentrunnerjava184at orgrobolectricrobolectrictestrunner1evaluaterobolectrictestrunnerjava172at orgjunitrunnersparentrunnerrunparentrunnerjava236at orgeclipsejdtinternaljunit4runnerjunit4testreferencerunjunit4testreferencejava50at orgeclipsejdtinternaljunitrunnertestexecutionruntestexecutionjava38at orgeclipsejdtinternaljunitrunnerremotetestrunnerruntestsremotetestrunnerjava467at orgeclipsejdtinternaljunitrunnerremotetestrunnerruntestsremotetestrunnerjava683at orgeclipsejdtinternaljunitrunnerremotetestrunnerrunremotetestrunnerjava390at orgeclipsejdtinternaljunitrunnerremotetestrunnermainremotetestrunnerjava197the manifest of my test project is like thismanifest xmlnsandroid packagecomvendortest androidversioncode1 androidversionname10 application useslibrary androidnameandroidtestrunner application usessdk androidminsdkversion19 androidtargetsdkversion19 instrumentation androidnameandroidtestinstrumentationtestrunner androidtargetpackagecomvendor manifesti complains always about the api level no matter what i useanyone got this working,['android'] +595841,where do i get arpaineth question is really simplei need a tool to convert char to ip adress and use it insockaddr ins addrarpaineth has inet addr function but i am not sure if i already have this file somewhere in ms vs 2010 installation or should i get it elsewhere,"['c++', 'c']" +595918,qtcpsocket reading and writing i know some similar questions may have been asked already but the answers to those i found covered very specific problems and i still have not figured it outin my program i am creating a qobject called qpeer that uses a qtcpsocket to communicate with another such object over a network qpeer has a slot that accepts a qbytearray with data senddataqbytearray the entire contents of that array are considered to be one message and they are written to the socket i want to do the following every time a message is written i want the receiving qpeer to emit its signal datareceivedqbytearray exactly once that qbytearray containing the entire message note all signalsslots both private ones connecting the qpeer with its socket and the public ones such as senddataqbytearray are serialized by using qtqueuedconnection whenever necessaryi use the signal qtcpsocketreadyread for asynchronous reading from the socket now i know i cannot just call qtcpsocketwrite once in senddata and then assume that for every write i do the qtcpsocket on the other side produces exactly one readyread signal so what should i dothis is my idea please tell me if this will workwritingvoid qpeersenddataqbytearray data todo write datasize as raw int of exactly 4 bytes to socket const char bytes dataconstdata int byteswritten 0 while byteswritten datasize byteswritten socketwritebytes byteswrittenreadingnow i want the read function connected to qtcpsocketreadyread to use the header the 4 byte int specifying the length of the message and then read that amount of bytes next emit datareceived with exactly those bytes i am having serious trouble trying to do this for example what to do if readyread is emitted and i can read the header of a message but not the amount of bytes specified or what if a header has only been received partially1 how do i correctly write the header 4 byte int to the socket2 how do i correctly implement the read function so that it does what i wantany tips are welcome thanks,['c++'] +595920,confusion between stdtr1ref and boostref beware this is gcc 412 were on a proprietary embedded platform we cannot update to a new compiler so c03 tr1 it iswe somewhere have a function like this templatetypename tvoid fooconst boostany x barboostany casttxwhich is then later used in a bind expression stdtr1bind foot 1this generates the following error error call of overloaded refconst boostany is ambiguousnote candidates are stdtr1reference wrapper tp stdtr1ref tp with tp const boostanynote const boostreference wrapper boostreft with t const boostanyi do understand that this is koenig lookup hitting us however i lack ideas about how to circumvent this problem anyone out there,['c++'] +595962,deriving implementation of pure virtual function consider following exampleinclude iostreamstruct purevirtual virtual void function 0struct functionimpl virtual void function stdcout functionimplfunction stdendl struct nonpurevirtual public functionimpl public purevirtual using functionimplfunctionint main nonpurevirtual c cfunctioncompiler gcc 49 clang 35 is exits with errortestcpp1820 error variable type nonpurevirtual is an abstract class nonpurevirtual c testcpp418 note unimplemented pure virtual method function in nonpurevirtual virtual void function 0 but when i do not derive form purevirtual everything is ok this is weird because standard 1044 saysa class is abstract if it contains or inherits at least one pure virtual function for which the final overrider is pure virtualthey are not saying anything about what the final overrider is but i suppose it should be functionimplfunction especially when i made it available through using directive so why is still nonpurevirtual abstract class and how can i fix this,['c++'] +596023,cache memory optimization array transpose c typedef int array22void transposearray dst array src int i j for j 0 j 2 j for i 0 i 2 i dstij srcji src array starts at address 0 and the dst array starts at address 0x10l1 data cache direct map writeallocate 8 byte block sizecache total size is 16 data byteswhat is the hit or miss on each entry of src and dst arraythe answer issrc 00 miss01 miss10 miss11 hitdst00 miss01 miss10 miss11 missif the cache total size is 32 data bytes the answer issrc 00 miss01 hit10 miss11 hitdst00 miss01 hit10 miss11 hiti am unsure of both outcomes i do not really understand the concept with arrays and caching,['c'] +596042,nomethoderror undefined method safe constantize i have a simple modelclass post activerecordbaseendit has a column int named typewhen i create a recordpostcreatetype 1i getnomethoderror undefined method safe constantize for 1fixnumwhat am i doing wrong,"['ruby-on-rails', 'ruby']" +596059,why are not my ball objects shrinkingthisappearing this is from line 84 in this js fiddle there are 3 different effects which can be applied to the balls by uncommenting lines 141146 the bounce effect works as it should but the asplode effect does nothing should i include the shrink function inside the asplode function balls shrink and thisappear if they touchvar shrink functionp for var i 0 i 100 i pradius 1 function asplodep setintervalshrinkp100 ballssplicep 1,['javascript'] +596069,gradle for android aar depending upon aar both in the same remote repository there are a few questions floating around regarding transitive dependencies with aar files in gradleandroid studio 023 cannot resolve transitive aar dependenciesandroid gradle library dependency with library dependency using nexusaar in repository external dependency and noclassdeffounderrori too have run into similar problems trying to set up transitive dependencies upon aar files in a remote repository i have app a depending upon library b which in turn dependsupon library c library c is in a maven repo library b is in the same repo with a pomthat contains the dependency upon library c app a has library b in its dependencies however running gradle clean assembledebug results in module version library b depends on libraries but is not a library itselfi tried putting a bounty on one of those questions hoping for clarity with no luckmy guess is that there are two possible sources of the difficulty that i and those with the aforementioned so question are seeingtransitive aar dependencies from a remote repository are simply brokentransitive aar dependencies from a remote repository work but there is something off in our pom files buildgradle files or something that is breaking the dependenciesthe question does anyone know of an aar artifact in some public repository eg maven central that depends upon another aar artifact also in the same public repositoryi am not interested in an aar that depends upon something in a local repository like an aar in maven central that depends upon comandroidsupportsupportv4 in my case if library b and library c are both in my local maven repository m2 everything works fineaccording to xav what i am doing should work hence i am hoping that somebody can point me to a working example so that i can use it to determine where the rest of us may be going wrongnote i know that asking for offsite resources is verboten in this case i am not looking for the resource in its own right but as an example of a working configuration to help debug a nonworking configuration if you have another way of writing up an answer showing a working configuration that would be awesomethanks,['android'] +596089,javascript loop through list items and return the results in an array i have been trying to loop through an unordered list of numbers with javascript the function should store all of the numbers in an array so i can find which numbers are duplicates any help would be appreciated so far i have htmlhead titletitleheadbodyul idul li6li li3li li1li li4li li7li li4li li2li li8li li9li li2liulbodyhtmland a start on the javascriptfunction var nums documentgetelementbyidul var listitem numsgetelementsbytagnameli var newnums var dups function for var i 0 i listitemlength i dups what am i missing,['javascript'] +596161,android google plus getcurrentperson returns null when i am calling plusclientgetcurrentperson i am getting nullmethod onconnectedbundle called after a successful loginoverridepublic void onconnectedbundle bundle if plusclientgetcurrentperson null logedd person is null i have added sha1 directly from eclipse windowpreferencesandroidbuild i do not know what i am doing wrongsha1 fingerprint from eclipse adtclient id for installed applicationssimple api access,['android'] +596163,catching blocked loading mixed active content cors error in firefox when javascript attempts to do a cors request to a http server from a page that is hosted on https it will throw an errorblocked loading mixed active content i would like to catch these errors but i cannot figure out how egi tried something like this with jquerytry getfailfunctionxhr err consolelogserver error xhrresponsetext catche consolelogemessagebut buth xhrresponsetext and emessage are empty strings probably because ajax happens asynchronously how can i catch the actual error message that says blocked loading mixed active content,"['javascript', 'jquery']" +596185,qcombobox popup expanding and qtwebkit solution in firefoxchromeinternetexplorersafariopera popups from the combobox expand as the content see firefox pictureqcombobox popup does not expand the content popups are limited by the size of qcombobox see qwebview pictureso i implemented the qcomboboxshowpopupvoid newqcomboboxshowpopup int width thiswidth thisviewsettextelidemode qtelidenone const int iconsize thisiconsizewidth const qfontmetrics fontmetrics thisfontmetrics const int j thiscount for int i0 i j i const int textwidth fontmetricswidth thisitemtexti w if thisitemiconiisnull width qmaxwidth textwidth else width qmaxwidth textwidth iconsize qstyleoptioncombobox opt thisinitstyleoptionopt qsize sizewidth 0 size thisstylesizefromcontentsqstylect combobox opt size this thisviewsetfixedwidth width qcomboboxshowpopupis there any way to modify reimplement the qcomboboxshowpopup of qwebviewsqtbug suggestion,['c++'] +596212,jersey async containerrequestfilter i have a jersey rest api and am using a containerrequestfilter to handle authorization i am also using managedasync on all endpoints so that my api can serve thousands of concurrent requestsmy authorization filter hits a remote service but when the filter is run jersey has not yet added the current thread to it is internal executorservice so i am completely losing the async benefits can i tell jersey that i want this containerrequestfilter to be asynchronouspriorityprioritiesauthorizationpublic class authorizationfilter implements containerrequestfilter inject private authorizationservice authsvc override public void filtercontainerrequestcontext requestcontext throws ioexception string authtoken requestcontextgetheaderstringhttpheadersauthorization hits a remote server authorizationresponse authresponse authsvcauthorizeauthtoken if authresponseisauthorized requestcontextabortwithresponsestatusresponsestatusunauthorized entityunauthorized build and heres an example resourcepathstuffproducesmediatypeapplication jsonpublic class stuffresource get pathid managedasync public void getbyidpathparamid long id suspended final asyncresponse ar stuff s hit the database for stuff arresumes update just heard back from the jersey guys and this is not possible as of 27 only the resource method itself is invoked asynchronously not filters any suggestions for proceeding still welcome,['java'] +596303,ternary operator left associativity in the php manual i find the following user contributed note under operatorsnote that in php the ternary operator has a left associativity unlike in c and c where it has right associativity you cannot write code like this as you may have accustomed to in cc php a 2 echo a 1 one a 2 two a 3 three a 4 four other echo n prints four i actually try it and it really prints four however i could not understand the reason behind it and still feel it should print two or othercan someone please explain what is happening here and why it is printing four,['php'] +596419,how do i vertically center an h1 in a div first of all my apologies i know there are various solutions posted for this issue here but for the life of me i cannot get any of them to work for a responsive website i am trying to center an h1 in a div centering horizontally is not an issue but i am having problems getting it centered vertically presumably i am doing something wrong or misunderstanding the explanations i found here or maybe bothso as i am probably interpreting earlier solutions given the wrong way could someone please explain what exactly i have to add to the code beneath to get the h1 to center vertically to make this question relevant to as much people as possible i have already stripped the code of all my previous attempts to do so myself css html body height 100margin 0section1 minheight 90 textaligncenterhtml div clasection idsection1h1lorem ipsumh1div,"['html', 'css']" +596443,using jackson objectmapper with jersey i am using jersey 24 to create a simple rest interface that serves up a json object my problem is that i am trying to use the fasterxml jackson annotations to control the output and this is not working for me i have put the annotations into my bean class but they are ignoredwhen i explicitly create an objectmapper and use this to stringify the java bean i get the output that i want which respects the jackson annotations however i would prefer that i do not have to do this step so that my resource class can simply return the bean and the jersey framework takes care of stringifying iti have tried to solve this using the answer from custom objectmapper with jersey 22 and jackson 21 however this does not appear to work for me i see that the contextresolver is created but it is never calledi have also spent many hours trying to solve this apparently simple problem i have stripped this down to a very simple test case which is shown below i would appreciate any help at all in resolving thisresource java classpathresourcepublic class mainresource public static class foobar jsonignore private string foo foo private string baa baa private mapstring list extends number map new hashmap public foobar mapputeven arraysaslistnew integer 2 4 6 8 10 mapputodd arraysaslistnew integer 1 3 5 7 9 mapputfloat arraysaslistnew float 11f 22f 33f public string getfoo return foo public void setfoostring foo thisfoo foo public string getbaa return baa public void setbaastring baa thisbaa baa jsonanygetter public mapstring list extends number getmap return map public void setmapmapstring list extends number map thismap map private objectmapper om new objectmapper get pathgetobject producesmediatypeapplication json public foobar getobject in this method i simply return the bean object but the wrong json syntax is generated return new foobar get pathgetstring producesmediatypeapplication json public string getstring throws jsonprocessingexception this method returns the right json syntax but i do not want to have to explicitly use the objectmapper foobar foobar new foobar return omwritevalueasstringfoobar webxmlwebapp version30 xmlns xmlnsxsi xsischemalocation 3 0xsd modulenamesamplemodulename servlet servletnamejersey web applicationservletname servletclassorgglassfishjerseyservletservletcontainerservletclass initparam paramnamejerseyconfigserverproviderpackagesparamname paramvalueiecitnimbussampleparamvalue initparam servlet servletmapping servletnamejersey web applicationservletname urlpatternurlpattern servletmappingwebapom dependenciesdependencies dependency groupidcomfasterxmljacksonjaxrsgroupid artifactidjacksonjaxrsjsonproviderartifactid version230version dependency dependency groupidorgglassfishjerseyextgroupid artifactidjerseyspring3artifactid version241version dependency dependency groupidorgglassfishjerseymediagroupid artifactidjerseymediajsonjacksonartifactid version241version dependencydependencies,['java'] +596512,uisearchbar in uitableviewheader strange animation on ios 78 we have a class searchtableviewcontroller that holds a uisearchbar as the tableviewheader of its uitableview we also use a uisearchthisplaycontroller whose delegate searchresultsdelegate and searchresultsdatasource is the same controller that holds the tableview containing the searchbarsearching itself works just fine but the animation when enteringexiting search mode is really weirdweird animation 1in another view controller a subclass of the searchtableviewcontroller the issue is even more noticeableweird animation 2i have tried implementing the various uisearchthisplaydelegate methods such as voidsearchthisplaycontrollerwillbeginsearch but they are either being called too late when the animation is already finished or only when giving the uisearchbars textfield the focusare there any methods i am missing that might allow me to change the animation before it happensalso notice how the navigation bar immediately thisappears in the first video i have tried manually setting it to not hidden in multiple spots which did not change anythingour navigationbar is configured to not be translucent if that makes any differenceon ios 6 everything works as expected the searchbar smoothly pushes the navigationbar upwardswill post code if necessary but we are not modifying the standard behaviour in any way setting frames overwriting delegate methods etcany ideas what might be the cause for the strange animations,['ios'] +596532,3 column layout htmlcss i have the following html layoutdiv classcontainer div classcolumncentercolumn centerdiv div classcolumnleftcolumn leftdiv div classcolumnrightcolumn rightdivdivany chance to arrange the columns like on the below sample grid without changing html using css only column left column center column right,"['html', 'css']" +596535,overflowhidden thisplayinlineblock moves text upwards i have following htmldiv aspan styleoverflow hidden thisplay inlineblockbspancdivwhat i expect to see abcwhat i see in chrome safari firefox b is higher than a and c why it is so and how to fix it,"['html', 'css']" +596559,why does the synchronized method always return false in windows phone 8 only on device try running this codepublic mainpage initializecomponent var mytrue gettrue debugwritelinemytrue falsemethodimplmethodimploptionssynchronizedprivate static bool gettrue return trueyou will see mytrue always is false why how it can beupdate tested on devices nokia lumia 920 htc 8x nokia lumia 925,['c#'] +596618,setonpagechangelistener does not call onpageselected i have setup a simpleonpagechangelistener using the following exampleandroid simpleonpagechangelistener determine swipe directionhowever when i execute the code then swipe the viewpager i would expect the following line to be calledpublic void onpageselectedint position however it never seems to do so which is causing a nonfunctional viewpager any suggestions public class home extends youtubebaseactivity implements videoclicklistener private int mcurrenttabposition no current position private static final int no current position 1 private viewpager mpager int imagearray string stringarray private onpagechangelistener mpagechangelistener imagepageradapter adapter new imagepageradapter override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayouthome final viewpager viewpager viewpager findviewbyidridview pager viewpagersetadapteradapter setonpagechangelistenermpagechangelistener mpagechangelistener new viewpagersimpleonpagechangelistener override public void onpageselectedint position ontabchangedmpagergetadapter mcurrenttabposition position position mcurrenttabposition int oldpos viewpagergetcurrentitem if position oldpos systemoutprintposition moving to the right string playlist themozartgroupa new getyoutubeuservideostaskresponsehandler playlist execute view vg findviewbyidrlayouthome vginvalidate else if position oldpos moving to the left systemoutprintposition string playlist themozartgroupa new getyoutubeuservideostaskresponsehandler playlist execute view vg findviewbyidrlayouthome vginvalidate viewpagersetonpagechangelistenermpagechangelistener private void ontabchangedpageradapter adapter int mcurrenttabposition int position todo autogenerated method stub private void setonpagechangelistener onpagechangelistener mpagechangelistener2 todo autogenerated method stub private class imagepageradapter extends pageradapter public imagepageradapteractivity act int mimages string stringarra imagearray mimages activity act stringarray stringarra public imagepageradapter super private int mimages new int rdrawableselstation up btn rdrawableclassical up btn rdrawablecountry up btn rdrawabledance up btn rdrawablehiphop up btn rdrawableisland up btn rdrawablelatin up btn rdrawablepop up btn rdrawablesamba up btn private string stringarray new string vevo themozartgroupa timmcgrawvevoa tiestovevoa eminemvevoa override public int getcount return mimageslength override public boolean isviewfromobjectview view object object return view imageview object override public object instantiateitemviewgroup container int position context context homethis imageview imageview new imageviewcontext imageviewsetscaletypescaletypefit xy imageviewsetimageresourcemimagesposition viewpager containeraddviewimageview 0 return imageview override public void destroyitemviewgroup container int position object object viewpager containerremoveviewimageview object protected void ontabchangedfinal pageradapter adapter final int oldposition final int newposition calc if swipe was left to right or right to left if oldposition newposition left to right else right to left final viewpager viewpager viewpager findviewbyidridview pager xml androidsupportv4viewviewpager androidididview pager androidlayout widthwrap content androidlayout heightfill parent,"['java', 'android']" +596625,why am i getting error message uri is not registered i just installed android studio and everything ran fine but then i opened as for a second time after my computer had turned off and i am getting the following erroruri is not registeredon the following lines of codemanifest xmlnsandroidthis is just the manifest but it is happening on all of my xml files with that link i have searched stack and found nothing that solves my issue,['android'] +596645,xcode 5 storyboard compile failure i am running xcode 5 and building for ios 7 when i try to build this project for archiving i get this error i get it on my local machine and on my jenkins build server i have gone through the storyboard and i am not finding any reason for this error it builds just fine on simulator and device i am not even sure what runtimenib is though addedithcpviewcontrollernib is reference to one of the view controllers inside of the storyboard any ideascompilestoryboard myaprofilesstoryboard cd buildscompanyworkspacemyapp setenv ibsc minimum compatibility version 61 setenv path applicationsxcodeappcontentsdeveloperplatformsiphoneosplatformdeveloperusrbinapplicationsxcodeappcontentsdeveloperusrbinusrbinbinusrsbinsbin setenv xcode developer usr path applicationsxcodeappcontentsdeveloperusrbin applicationsxcodeappcontentsdeveloperusrbinibtool errors warnings notices minimumdeploymenttarget 61 outputformat humanreadabletext compile buildscompanyworkspacemyappbuildthistributioniphoneosmyappaprofilesstoryboardc buildscompanyworkspacemyappmyaprofilesstoryboard comappleibtooldocumentwarnings buildscompanyworkspacemyappmyaprofilesstoryboardjlwrtouy warning 2 views are vertically ambiguousbuildscompanyworkspacemyappmyaprofilesstoryboard1qmh4izr warning position is ambiguous for pickerbuildscompanyworkspacemyappmyaprofilesstoryboardd8pia2qw warning frame for button will be different at run time comappleibtoolerrors buildscompanyworkspacemyappmyaprofilesstoryboard error compilation failed unable to write to path buildscompanyworkspacemyappbuildthistributioniphoneosmyappaprofilesstoryboardc underlying errors description the file aoruntimeniba1 doesna t exist failure reason the file doesna t exist underlying errors description the operation couldna t be completed no such file or directory failure reason no such file or directory description aoprofilesstoryboardca1 couldna t be removed failure reason the file doesna t exist underlying errors description the operation couldna t be completed no such file or directory failure reason no such file or directorycompilestoryboard myaprofilesstoryboard cd buildscompanyworkspacemyapp setenv ibsc minimum compatibility version 61 setenv path applicationsxcodeappcontentsdeveloperplatformsiphoneosplatformdeveloperusrbinapplicationsxcodeappcontentsdeveloperusrbinusrbinbinusrsbinsbin setenv xcode developer usr path applicationsxcodeappcontentsdeveloperusrbin applicationsxcodeappcontentsdeveloperusrbinibtool errors warnings notices minimumdeploymenttarget 61 outputformat humanreadabletext compile buildscompanyworkspacemyappbuildthistributioniphoneosmyappaprofilesstoryboardc buildscompanyworkspacemyappmyaprofilesstoryboard comappleibtooldocumentwarnings buildscompanyworkspacemyappmyaprofilesstoryboardd8pia2qw warning frame for button will be different at run timebuildscompanyworkspacemyappmyaprofilesstoryboardjlwrtouy warning 2 views are vertically ambiguousbuildscompanyworkspacemyappmyaprofilesstoryboard1qmh4izr warning position is ambiguous for picker comappleibtoolerrors buildscompanyworkspacemyappmyaprofilesstoryboard error compilation failed unable to write to path buildscompanyworkspacemyappbuildthistributioniphoneosmyappaprofilesstoryboardc underlying errors description the file aoaddedithcpviewcontrollerniba1 doesna t exist failure reason the file doesna t exist underlying errors description the operation couldna t be completed no such file or directory failure reason no such file or directory,"['ios', 'iphone', 'objective-c']" +596744,what is linq actually compiled to backgroundthe background for this is that i had a recent conversation in the comments with another clearly knowledgeable user about how linq is compiled i first summarized and said linq was compiled to a for loop while this is not correct my understanding from other stacks such as this one is that the linq query is compiled to a lambda with a loop inside of it this is then called when the variable is enumerated for the first time after which the results are stored the other user said that linq takes additional optimizations such as hashing i could not find any supporting documentation either for or against thisi know this seems like a really obscure point but i have always felt that if i do not understand how something works completely its going to be difficult to understand why i am not using it correctlythe questionso lets take the following very simple examplevar productnames from p in products where pid 100 and pid 50 select pproductnamewhat is this statement actually compiled to in clr what optimizations does linq take over me just writing a function that manually parses the results is this just semantics or is there more to it than thatclarificationclearly i am asking this question because i do not understand what the inside of the linq black box looks like even though i understand that linq is complicated and powerful i am mostly looking for a basic understanding of either the clr or a functional equivalent to a linq statement there are great sites out there for helping understand how to create a linq statement but very few of these seem to give any guidance on how those are actually compiled or runside note i will absolutely read through the john skeet series on linq to objectsside note 2 i should not have tagged this as linq to sql i understand how orms and microorms work that is really besides the point of the question,['c#'] +596770,multiprocessing reading big input data program hangs i want to run parallel computation on some input data which is loaded from a file the file can be really big so i use a generator for thison a certain number of items my code runs ok but above this threshold the program hangs some of the worker processes do not endany suggestions i am running this with python27 8 cpus 50 lines still ok 7500 does not workfirstly you need an input file generate it in bashfor i in 010 do echo e ir countertxt donethen run thispython27 mainpy 100 countertxt run logtxtmainpyusrbinpython27import os sys signal timeimport queueimport multiprocessing as mpdef eat queuejob queue result queue eats input queue feeds output queue proc name mpcurrent processname while true try job job queuegetblockfalse if job none printproc name done return result queueputexecutejob except queueempty pass def executex does the computation on the input data return xxdef save resultresult saves results in a list result listappendresultdef loadifilename generator reading the input file and yielding it row by row ifile openifilename r for line in ifile line linestrip num intline yield num ifileclose printfile closedupperdef put tasksjob queue ifilename feeds the job queue for item in loadifilename job queueputitem for in rangeget max workers job queueputnonedef get max workers returns optimal number of processes to run max workers mpcpu count 2 if max workers 1 return 1 return max workersdef runworkers num ifilename job queue mpqueue result queue mpqueue decide how many processes are to be created max workers get max workers print processes available d max workers if workers num 1 or workers num max workers workers num max workers workers list a process for feeding job queue with the input file task gen mpprocesstargetput tasks nametask gen argsjob queue ifilename workers listappendtask gen for i in rangeworkers num tmp mpprocesstargeteat queue namewd i1 argsjob queue result queue workers listappendtmp for worker in workers list workerstart for worker in workers list workerjoin print worker s finished workernameif name main result list args sysargv workers num intargs1 ifilename args2 runworkers num ifilename,['python'] +596823,is my site being attacked suhosin simulation very strange activity in ip log i will preface this question by saying i am not a web developer nor do i have much knowledge in this field i am a business owner and have a low volume website that my customers purchase products on i have noticed this set of queries a few minutes ago and they appear very suspicious to me a layperson it looks as if they are trying to pull data from my database i could be totally wrong but someone please let me know what they think is going on here notesall are listed with method of post when most normal viewers are listed as get everything below occurs immediately after my domain name eg examplesitecomxhere are the queries cgibinphpdallow url include3dondsafe mode3doffdsuhosin2esimulation3dondthisable functions3ddopen basedir3dnonedauto prepend file3dphp3a2f2finputdcgi2eforce redirect3d0dcgi2eredirect status env3d0n cgibinphp5dallow url include3dondsafe mode3doffdsuhosin2esimulation3dondthisable functions3ddopen basedir3dnonedauto prepend file3dphp3a2f2finputdcgi2eforce redirect3d0dcgi2eredirect status env3d0n cgibinphp4dallow url include3dondsafe mode3doffdsuhosin2esimulation3dondthisable functions3ddopen basedir3dnonedauto prepend file3dphp3a2f2finputdcgi2eforce redirect3d0dcgi2eredirect status env3d0nand about 6 more similar queries notes when i follow that link my site gives an error of page not found when i try to go to sitecomcgibin i get a stock 403 forbidden error from my host thoughts please am i being paranoid hereedit also in my file manager my cgibin folder is empty this directory is empty,['php'] +596853,what is object field initialization and constructor order in java i ended up the following scenario in code earlier today which i admit is kinda weird and i have since refactored when i ran my unit test i found that a field initialization was not set by the time that the superclass constructor has run i realized that i do not fully understand the order of constructor field initialization so i am posting in the hopes that someone explain to me the order in which these occurclass foo extends foobase string foo foobar override public void setup if foo null throw new runtimeexceptionfoo is null supersetup class foobase public foobase setup public void setup testpublic void testfoo new foothe abbreviated backtrace from junit is as follows i guess i expected fooinit to set foofoosetupfoobaseinitfooinittestfoo,['java'] +596866,python dictionary sorting in descending order based on values i want to sort this dictionary d based on value of sub key key3 in descending order see belowd 123 key1 3 key2 11 key3 3 124 key1 6 key2 56 key3 6 125 key1 7 key2 44 key3 9 so final dictionary would look like thisd 125 key1 7 key2 44 key3 9 124 key1 6 key2 56 key3 6 123 key1 3 key2 11 key3 3 my approach was to form another dictionary e from d whose key would be value of key3 and then use reversedsortede but since value of key3 can be same so dictionary e lost some of the keys and their values makes sensehow i can accomplish this this is not a tested code i am just trying to understand the logic,['python'] +596890,obtaining a pasttheend pointer using the address of an array in c and c it is often useful to use a pasttheend pointer to write functions that can operate on arbitrarily large arrays c gives a stdend overload to make this easier in c on the other hand i have found it is not uncommon to see a macro defined and used like thisdefine arraylenarray sizeofarraysizeofarray0 int a 42do something a a arraylen ai have also seen a pointer arithmetic trick used to let such functions operate on single objectsint bdo something b b 1it occured to me that something similar could be done with arrays since they are considered by c and i believe c to be complete objects given an array we can derive a pointer to an array immediately after it dereference that pointer and use arraytopointer conversion on the resulting reference to an array to get a pasttheend pointer for the original arraydefine endarray array 1 int a 42do something a end amy question is this in dereferencing a pointer to a nonexistent array object does this code exhibit undefined behaviour i am interested in what the most recent revisions of both c and c have to say about this code not because i intend to use it as there are better ways of achieving the same result but because it is an interesting question,"['c++', 'c']" +596898,taking advantage of the translucent status bar in android 44 kitkat when i released my note taking application for android 40 43 i used a custom action bar color with a custom action bar icon instead of using the standard light and dark action bars i would like to make it so on android 44 the status bar will also take on the custom color i am using in my action bar which is ffd060 is there a way to easily change my current stylesxml to allow 44 to take advantage of thismy stylesxml under my valuesv19 folder is as followsresourcesstyle nameappbasetheme parentandroidstylethemehololight item nameandroidactionbarstylestylemyactionbarthemeitemstyle style namemyactionbartheme parentandroidstylewidgethololightactionbar item nameandroidbackgroundffd060item item nameandroidtextcolorfitem item nameandroidicondrawableactionitem item nameandroidtitletextstylestylemytextappearanceitem style style namemytextappearance parentandroidtextappearanceholowidgetactionbartitle item nameandroidicondrawableactionitem item nameandroidtextcolorfitem styleresourcesi have tried to implement item nameandroidwindowtranslucentstatustrueitemit causes the contents of my application to move up start in the status bar area and be covered by the action bar,['android'] +596902,angularuirouter how can i update the url without refreshing everything i am new to both angular and the uirouter when someone selects a model and my controller performs a standard show method i simply want to update the url to include the models id without refreshing the page and continue on with my original view i am not sure how to do thisstateprovider statecitylist url templateurl viewsindexhtml statecityshow url cityid templateurl viewsindexhtml angularmoduleappsystemcontrollerindexcontroller scope global cities stateparams location function scope cities stateparams location scopeloadtown functionid citiesgetid id functioncity scopecity city change url do things within the same view button ngclickloadtown123456chicagobutton,['javascript'] +596917,using scala with gradle for android project there seems to be a memory leak somewherewhen setting up a project in intellij and using the gradle wrappergradlew assembledebug debug i get the following after about 5 mins143015245 info orggradleapiproject processing scalacollectionseqviewlikeanon5class143053132 info orggradleapiproject processing scalacollectionseqviewlikeanon6class143351027 error orggradleapiproject 143351028 error orggradleapiproject unexpected toplevel error143351028 error orggradleapiproject javalangoutofmemoryerror java heap space143351028 error orggradleapiproject at javautilhashmapinithashmapjava209143351029 error orggradleapiproject at comandroiddxssalocalvariableinfoinitlocalvariableinfojava66143351029 error orggradleapiproject at comandroiddxssalocalvariableextractorinitlocalvariableextractorjava72143351029 error orggradleapiproject at comandroiddxssalocalvariableextractorextractlocalvariableextractorjava54143351029 error orggradleapiproject at comandroiddxssassaconverterconverttossamethodssaconverterjava49143351030 error orggradleapiproject at comandroiddxssaoptimizeroptimizeoptimizerjava98143351030 error orggradleapiproject at comandroiddxssaoptimizeroptimizeoptimizerjava72143351030 error orggradleapiproject at comandroiddxdexcfcftranslatorprocessmethodscftranslatorjava303143351030 error orggradleapiproject at comandroiddxdexcfcftranslatortranslate0cftranslatorjava139143351031 error orggradleapiproject at comandroiddxdexcfcftranslatortranslatecftranslatorjava94143351031 error orggradleapiproject at comandroiddxcommanddexermainprocessclassmainjava682143351031 error orggradleapiproject at comandroiddxcommanddexermainprocessfilebytesmainjava634143351031 error orggradleapiproject at comandroiddxcommanddexermainaccess600mainjava78143351032 error orggradleapiproject at comandroiddxcommanddexermain1processfilebytesmainjava572143351032 error orggradleapiproject at comandroiddxcfdirectclasspathopenerprocessarchiveclasspathopenerjava284143351032 error orggradleapiproject at comandroiddxcfdirectclasspathopenerprocessoneclasspathopenerjava166143351034 error orggradleapiproject at comandroiddxcfdirectclasspathopenerprocessclasspathopenerjava144143351034 error orggradleapiproject at comandroiddxcommanddexermainprocessonemainjava596143351034 error orggradleapiproject at comandroiddxcommanddexermainprocessallfilesmainjava498143351034 error orggradleapiproject at comandroiddxcommanddexermainrunmonodexmainjava264143351035 error orggradleapiproject at comandroiddxcommanddexermainrunmainjava230143351035 error orggradleapiproject at comandroiddxcommanddexermainmainmainjava199143351035 error orggradleapiproject at comandroiddxcommandmainmainmainjava103i am using scala 293 but experienced the same problem with 210x here is my buildgradlebuildscript repositories mavencentral dependencies classpath comandroidtoolsbuildgradle06 apply plugin androidrepositories mavencentralandroid compilesdkversion 19 buildtoolsversion 1900 defaultconfig minsdkversion 7 targetsdkversion 19 dependencies compile comandroidsupportappcompatv7 scala compile orgscalalangscalalibrary293 orgscalalangscalacompiler293is anyone successfully compiling an android project with gradle scalathanks,['android'] +596998,how to check if a table exists in a given schema postgres 84 and greater database contains common tables in public schema and company specific tables in company schemacompany schema names always start with company and end with the company numberso there may be schemaspubliccompany1company2company3companynnan application always works with a single companythe search path is specified accordingly in odbc or npgsql connection string likesearch pathcompany3publichow to check if a given table exists in a specified companyn schemaselect isspecificcompany3tablenotincompany3schemashould return false andselect isspecificcompany3tableincompany3schemashould return truein any case function should check only companyn schema passed not other schemasif a given table exists in both public and passed schema the function should return trueit should work for postgres 84 or later,['sql'] +597109,can i instruct jsonnet to deserialize but not serialize specific properties i have an angularjs mvc 5 web api 2 app that allows users to manage collections of objects in the browser and commit all changes at once when a save button is clicked as changes are made one or more properties are added to the javascript objects isadded isupdated isremoved the properties are checked serverside to determine what to do when persisting the modelthe model is served up using jsonnet via web api and the base class ispublic class collectionitemviewmodel icollectionitem public bool isadded get set public bool isupdated get set public bool isremoved get set this works great but adds cruft to my serialized json i can choose to not serialize these three properties with shouldserialize but that also prevents them from deserializingpublic bool shouldserializeisadded return falsepublic bool shouldserializeisupdated return falsepublic bool shouldserializeisremoved return falseis it possible to deserialize but not serialize specific properties using jsonnet,['c#'] +597112,how to add multiple values to a dictionary key in python i want to add multiple values to a specific key how can i do thata aabc 1aabc 2,['python'] +597148,knockoutjs validation with dynamic observables i am using this plugin and i am trying to validate an object that is loaded dynamicallyjavascriptfunction vm var self this this is a static observable just to ensure that basic validation works fine selfstatic koobservable selfstaticextendrequired true this is the observable that will be updated to my model instance selfperson koobservable this is an handler for manual trigger i am not even sure this is needed selfa function selferrorsshowallmessages selfstaticerrorsshowallmessages here i am loading current person from somewhere ie a rest service selfload function update observable selfpersonnew model define validation rules selfpersonnameextendrequired true selfpersonemailextendrequired true set person data selfpersonnamelong selfpersonemailjohn set validators selferrors kovalidationgroupselfperson selfstaticerrors kovalidationgroupselfstatic just a test modelfunction model thisname koobservable thisemail koobservablekovalidationinitvar vm new vmkoapplybindingsvmmarkupul li1 hit loadli li2 hit show errors or maunally change input dataliulbutton databindclick loadloadbuttonbrh1this is working properlyh1input typetext databindvalue static brh1this is not workingh1input typetext databindvalue personname input typetext databindvalue personemail brbutton databindclick ashow errorsbuttonfiddlehow do i make this work,['javascript'] +597190,why android studio does not allow me to create java classes starting from the 2 days ago update to android studio it doesnt let me create java classes anymore and the current classes are now with a strange symboli tried to export import many and many times with different config but never worked any advice here are two screenshot update 1here is the structure of my android studio project androidmanifest is in the right place,['android'] +597239,css triangle before element i am using bootstrap trying to make a div have a css triangle before it here is my nonworking codedbefore width 0px height 0px borderstyle solid borderwidth 10px 15px 10px 0 bordercolor transparent dd4397 transparent transparent the way i would like it to look is for there to be a pink leftpointing triangle right before the text this with no gap between it and the div i have tried to do this by floating the elements also with no success,"['html', 'css']" +597324,static vs non static until few weeks back i thought i understand when to make fields and methods static or nonstatic for example when a field say object of another class is unique for any number of objects for the class it should be made static but then i read about jvm garbage collection a few weeks backi understand that static fields are never garbage collected and remain in memory all along unless the class loader itself is garbage collectedbut if i do not make that field static at least it will be garbage collectedso it seems there is a very thin line between making fieldsmethods static or notcan anybody please explain to me this thin line in deciding so that my application is way more efficient,['java'] +597372,what exactly does stringstream do i am trying to learn c since yesterday and i am using this document page 32 i found a code in the document and i ran it i tried inputting rs 55 for price and an integer for quantity and the output was 0i tried inputting 55 and 6 and the output was correct stringstreamsinclude iostream include string include sstream using namespace std int main string mystr float price 0 int quantity 0 cout enter price getline cinmystr stringstreammystr price cout enter quantity getline cinmystr stringstreammystr quantity cout total price pricequantity endl return 0 question what exactly does the mystring command do quoting from the document in this example we acquire numeric values from the standard input indirectly instead of extracting numeric values directly from the standard input we get lines from the standard input cin into a string object mystr and then we extract the integer values from this string into a variable of type int quantitymy impression was that the function will take the integral part of a string and use that as inputi do not exactly know how to ask a question here i am also new to programmingthank you,['c++'] +597393,loading a tgabmp file in copengl i am trying to load a tgabmp file this works fine but the end result looks like thisthe image i am trying to load looks like thissome of the code i am usinggluint textureconst char filename usersadmindocumentsvisual studio 2013projectsopenglopenglimagetgaunsigned char datadata unsigned char malloc128 128 3file ffopen sf filename rbfreaddata 128 128 3 1 fglgentextures1 textureglbindtexturegl texture 2d textureglteximage2dgl texture 2d 0 gl rgb 128 128 0 gl rgb gl unsigned byte datadoes anybody have an idea what i am doing wrong,['c++'] +597420,jcombobox is a raw type references to generic type jcombobox should be parameterized string boxoptions 1248162040100400jcombobox box new jcomboboxboxoptionsi had these exact lines of code in my program before and was not getting this error i did a bit of searching and the results i found are going a bit over my head any ideasthe error is jcombobox is a raw type references to generic type jcomboboxe should be parameterized,['java'] +597422,thisplaying interlaced progressive image in uiimageview i am trying to thisplay a jpeg image as it downloads using part of the data similiar to many web browsers do or the facebook appthere is a lowquality version of the imagejust part of the data and then thisplay the full image in full qualitythis is best shown in the video herei followed this so questionhow do i thisplay a progressive jpeg in an uiimageview while it is being downloadedbut all i got was a imageview that is being rendered as data keeps comes in no lowquality version first no true progressive download and rendercan anyone share a code snippet or point me to where i can find more info as to how this can be implemented in an ios app tried this link for example which shows jpeg info it identifies the image as progressive 22pjpgand i used the correct code sequencevoidconnectionnsurlconnectionconnection didreceivedatansdatadata append the data datatemp appenddatadata get the total bytes downloaded const nsuinteger totalsize datatemp length update the data source we must pass all the data not just the new bytes cgimagesourceupdatedata imagesource cfdataref datatemp totalsize expectedsize true false we know the expected size of the image if fullheight 0 fullwidth 0 imageview setimageuiimage imagewithcgimageimage cgimagereleaseimage but the code only shows the image when it is finished loading with other images it will show it as it downloading but only top to bottom no low quality version and then progressively add detail as browsers dodemo project here,"['ios', 'iphone', 'objective-c']" +597472,how suitable is opting for rethinkdb instead of traditional sql for a json api i am building the backend for my web app it would act as an api for the frontend and it will be written in python flask to be preciseafter taking some decisions regarding design and implementation i got to the database part and i started thinking whether nosql data storage may be more appropriate for my project than traditional sql databases following is a basic functionality description which should be handled by the database and then a list of pros and cons i could come up with regarding to which type of storage should i opt for finally some words about why i have considered rethinkdb over other nosql data storagesbasic functionality of the apithe api consists of only a few models artist song suggestion user and userartistsi would like to be able to add a user with some associated data and link some artists to it i would like to add songs to artists on request and also generate a suggestion for a user which will contain an artist and a songmaybe one of the most important parts is that artists will be periodically linked to users and also artists can be removed from the system hence from users too if they do not satisfy some criteria songs will also be dynamically added to artists all this means is that users do not have a fixed set of artists and nor do artists have a fixed set of songs they will be continuously updatingprosfor nosqlflexible schema since not every artist will have a facebookid or song a soundcloudidwhile a json api i believe i would benefit from the fact that records are stored as jsoni believe the number of songs but especially suggestions will raise quite a bit hence nosql will do a better job herefor sqlit is fixed schema may come in handy with relations between modelsflask has support for sqlalchemy which is very helpful in defining modelsconsfor nosqlrelations are harder to implement and updating models transactionlike involves a bit of codeflask does not have any wrapper or module to ease things hence i will need to implement some kind of wrapper to help me make the code more readable while doing database operationsi do not have any certainty on how should i store my records especially userartistsfor sqloperations are bulky i have to define schemas check whether columns have defaults assign defaults validate data begincommit transactions i believe it is too much of a hassle for something simple like an apiwhy rethinkdbi have considered rehinkdb for a possible implementation of nosql for my api because of the followingit looks simpler and more lightweight than other solutionsit has native python support which is a big plusit implements table joins and other things which could come in handy in my api which has some relations between modelsit is rather new and i see a lot of implication and love from the community there is also the will to continuously add new things that leverage database interactionall these being considered i would be glad to hear any advice on whether nosql or sql is more appropiate for my needs as well as any other procon on the two and of course some corrections on things i have not stated properly,"['python', 'sql']" +597497,python which built in exception to use as i am sure you are well aware python as do most programming languages comes with builtin exceptions i have gone through the list and cannot deduce which would be appropriate of course i can make my own exception but this is a fairly standard error that would be exceptedthis is an error based on instance relations instances of a class are related to only some of the other instances computations can be made depending on the different connections this error will be raised if a computation is attempted on an unrelated instanceexampleclass foo def init selfrelatednone related is a list of foo instances if related is not none selfrelated related else selfrelated def computeselfinstance if instance in selfrelated execute code else raise someerroryou cannot make a computation with an unrelated instancemy thoughtsto be honest it seems like valueerror would make most sense because the value is not allowed but for some reason this does not fully sit well with me the fact that there is no relation is the importance of this error not simply the fact that the value attempted is not allowedis there a better exception than valueerror for my logicnote i understand that this valueerror may just be the right answer but i am curious if there is something more precise that i may have not been able to see the connection with when i went through the documentation,['python'] +597516,phpapache crashing on script segmentation fault 11 solvedi am running a php script with some includes on localhost that keeps crashing before the enderror reporting is on opera safari and firefox return an empty screen but chrome returnsunable to load the webpage because the server sent no data error code err empty responseapache logs returnssun dec 15 192923 2013 notice child pid 34267 exit signal segmentation fault 11was using php 556 when i encountered the problem for the first timeafter downgrading to php 5421 the problem still existsthe problem is not inside the script randomly commenting out a couple of 50 lines of code solves the problem making me wonder if my script might be to long for executiondoes anyone has any suggestions on how i can resolve this problem updateproblem does not only appears on the localhost but also on my webserver running on centos 64 and php 533 giving the same error on apachesun dec 15 231510 2013 notice child pid 18409 exit signal segmentation fault 11update2running php from the command line gives php indexphp fatal error call to undefined function mcrypt create iv in encryptclassphp on line 135after placing a comment before line 135 on encryptclassphp php indexphp segmentation fault 11update3 solutionafter running the index on command line with strace strace php indexphp i found the problem at one of the queries after some more debugging using pdo instead of my own class i found out that the problem was setting my own pdo option attr persistent true thisabling this option solved my problem,['php'] +597545,gradle builds for every resource folder is it possible to config gradle to build few android apk files where each would be using only one resourcetype folderi meanbuildhdpiapk buildmdpiapk buildxhdpiapki know i could simply remove certain folders before building but it would be nice if i could make it automagicallywould it be possible with using gradle flavors,['android'] +597548,can you use an undefined type in a c template function if the function is never used i am trying to create a conversion function between objects of two classes eigenvector3d and myvector a protocol buffers message but i want to delay evaluation of the function body until the function is referenced at which point both classes would be definedthe function should be callable in files that later define both classes and it should not cause a compilation error if the function is never usedi haveinclude eigencore defines eigenvector3dclass myvector public int set xint x x x private int x void operator myvector msg const eigenvector3d vec msgset xvecxwhich i use asmyvector msgeigenvector3d vec1 2 3msg vecthis works fine if the function is defined after myvector but i would like to be able to define the function such that it can be included in a translation unit that lacks the myvector classi could change the function to thistemplatetypename msgvoid operator msg msg but this is unacceptable because it would apply to other message classesquaternion msg eigenvector3d1 2 3 quaternion has xyz but also wand i want that to cause a build erroris there some kind of template magic that can do that if not is there a better way to provide this operator short of adding myvector to the header file or its dependencies,['c++'] +597580,js clientside exif orientation rotate and mirror jpeg images digital camera photos are often saved as jpeg with an exif orientation tag to thisplay correctly images need to be rotatedmirrored depending on which orientation is set but browsers ignore this information rendering the image even in large commerical web apps support for exif orientation can be spotty 1 the same source also provides a nice summary of the 8 different orientations a jpeg can havesample images are available at 4 the question is how to rotatemirror the image on the client side so that it thisplays correctly and can be further processed if necessarythere are js libraries available to parse exif data including the orientation attribute 2 flickr noted possible performance problem when parsing large images requiring use of webworkers 3console tools can correctly reorient the images 5 a php script solving the problem is available at 6,['javascript'] +597623,dynamic model nonclass metadata provider in mvc we are developing an application where the enduser schema is dynamic we have a good business case for this it is not something that can be handled easily by a static modeli have used the net dynamicobject class to allow these dynamic schema objects to be addressed easily from code and expected this to just work with the mvc model metadata however the mvc metadata support seems to be hamstrung in that it only deals with metadata defined per type not per object which will be the case hereeven when i dug down and tried implementing our own modelmetadataprovider it seems that the neccessary information is simply not passing in the getmetadataforproperty method is particularly problematic effectively i need to access the parent or container object for the property but all that is passed in is the type the above is called mainly from the fromstringexpression method in the modelmetadata class this method actually does have the container at least in this case but does not pass it through this branch is executed when it finds the view data about the expression stored cached in the viewdata if that fails it falls back to looking it up via the modelmetadata object which ironically might work for me whats particularly irritating is that the fromstringexpression method is static so i cannot easily override its behaviorin desperation i have considered trying to traverse the modelaccessor expression but this seems like a kludge at best and extremely fragilei have searched extensively for a solution to this many point to brad wilsons talk on nonclass models however if you look at the actual code presented you will see that it too is bound to the type and not the object in other words not terribly useful others have pointed to the but that only seems to apply to the validation side and i suspect suffers from the same problem bound to type rather than object as the abovefor example i may have a dictionary object that contains a series of field objects this looks something like very cut downsimplified examplepublic class entity dynamicobject icustomtypedescriptor public guid id get set public dictionarystring entityprop props get set dynamicobject and icustomtypedescriptor implementation to expose props as dynamic properties against this entity public class entityprop public string name get set public object value get set public type type get set public bool isrequired get set this might be passed to a view as its viewmode or part of it and in my view i would like to usehtmleditorformodelhas anyone found a way around thisi have identified two possible alternative approaches but both have significant drawbacksabandon using the mvc modelmetadata for this and instead build a viewmodel that directly contains the necessary metadata along with the templates needed to thisplay these more complex viewmodel objects means however that i am then having to treat these objects differently to normal objects defeating the purpose somewhat and increasing the amount of view templates we need to build this is the approach i am leaning towards now more or less abandoning integrating with the mvc modelmetadata stuffgenerate a unique key for each templated property and use this for the property name rather than the thisplay name that would allow the modelmetadataprovider to find the metadata that related to the property without needing a reference to its parent however this would lead to a fairly ugly situation when debugging and again seems like a large scale kludge i have now tried a simplified version of this and it seems to work but does have some undesirable behavior such as needing to use an meaningless property name if i want to explicitly bind to elements of the modelin the modelmetadataprovider when returning a collection of modelmetadata objects for contained properties record the container in the modelmetadataprovider that is associated with those returned properties i have tried this but this returned collection of property metadata is ignored in this case and the fromstringexpression method goes directly to the getmetadataforproperty method instead,['c#'] +597648,javascript audio api onaudioprocess not fired i am building a simple app in which i am trying to get the buffer but seems that onaudio process in the following code is not firing pastebinscriptvar audio contextvar recorderwindowonload function init try windowaudiocontext windowaudiocontext windowwebkitaudiocontext navigatorgetusermedia navigatorgetusermedia navigatorwebkitgetusermedia windowurl windowurl windowwebkiturl audio context new audiocontext catch e consoleloge navigatorgetusermediaaudio true startusermedia function startusermediastream consoleloginitializing var input audio contextcreatemediastreamsourcestream inputconnectaudio contextdestination var node inputcontextcreategain4096 2 2 nodeonaudioprocess functione consolelogdone nodeconnectaudio contextdestination scriptif the code works as it should i should get initiliazing and done the problem is that i am getting only initiazing and onaudioprocess is not fired i am using the lastest chrome,['javascript'] +597674,debugassert vs code contract usage when should i debugassert over code contracts or vice versa i want to check precondition for a method and i am confused to choose one over the other i have unit tests where i want to test failure scenarios and expect exceptionsis it a good practice to use debugassert and code contract on the same method if so what would be the order in which the code should be writtendebugassertparameter nullcontractrequiresargumentnullexceptionparameter null parameteror contractrequiresargumentnullexceptionparameter null parameterdebugassertparameter nullis there any rationale behind it,['c#'] +597715,vectorizing modular arithmetic i am trying to write some reasonably fast componentwise vector addition code i am working with signed i believe 64bit integersthe function is void addrq int64 t a const int64 t b const int32 t dim const int64 t q forint i 0 i dim i ai aibiq line1 i am compiling with icc stdgnu99 o3 icc so i can use svml later on an ivybridge sse42 and avx but not avx2my baseline is removing the q from line1 100 iterated function calls with dim11221184 takes 16 seconds icc autovectorizes the code for sse greati really want to do modular additions though with the q icc does not autovectorize the code and it runs in 118 seconds even ignoring the autovectorization for the previous attempt this still seems excessivesince i do not have avx2 vectorization with sse requires svml which is perhaps why icc did not autovectorize at any rate heres my attempt to vectorize the inner loop m128i qs mm set1 epi64xqforint i 0 i dim i2 m128i xs mm load si128const m128iai m128i ys mm load si128const m128ibi m128i zs mm add epi64xsys zs mm rem epi64zsqs mm store si128 m128iaizsassembly for the main loop isb34 preds b32 b312 movdqa r12r158 xmm0 5922 movdqa xmm8 xmm1 6014 paddq r14r158 xmm0 5922 call svml i64rem2 619 movdqa xmm0 r12r158 6136 addq 2 r15 5630 cmpq r13 r15 5624 jl b34 prob 82 5624so the code is getting vectorized as expected i know i might not get a 2x speedup due to svml but the code runs in 125 seconds slower than with no vectorization at all is this really the best that can be done here,['c'] +597716,what is difference between nsurlsessiondatatask vs nsurlsessiondownloadtask in latest apple introduce new nsurlsession in replace of nsurlconnection so in there are different task so what is the difference between nsurlsessiondatatask nsurlsessiondownloadtask and in which scenario use nsurlsessiontask and where nsurlsessiondownloadtask,"['ios', 'objective-c']" +597818,string format with optional dict keyvalue is there any way to format string with dict but optionally without key errorsthis works fineopening line greetingss names opening line greetings hello name johnbut let us say i do not know the name and i would like to format above line only for greetings something like opening line greetings hellooutput would be fine even ifhii names keeping name unformatted but this gives keyerror while unpackingis there any way,['python'] +597832,net quick start project and local databasemdf working on localhost but giving exceptions on remote server i am running dot quick start project locally perfectly with following connection however i do not the location on which its creating the mdf fileadd namedefaultconnection providernamesystemdatasqlclient connectionstringdata sourcelocaldbv110initial catalogaspnetmirrorquickstartdotnet20130523105156integrated securitysspiattachdbfilenamedatadirectoryaspnetmirrorquickstartdotnet20130523105156mdf i have checked app data its emptyanyways when i upload this project on remote server as soon as i click accept button thisplaying on google authorization page it throws following exceptionwin32exception 0x804005 the system cannot find the file specifiedsqlexception 0x80131904 a networkrelated or instancespecific error occurred while establishing a connection to sql server the server was not found or was not accessible verify that the instance name is correct and that sql server is configured to allow remote connections provider sql network interfaces error 52 unable to locate a local database runtime installation verify that sql server express is properly installed and that the local database runtime feature is enabled systemdatasqlclientsqlinternalconnectiononerrorsqlexception exception boolean breakconnection action1 wrapcloseinaction 6676046 systemdatasqlclienttdsparserthrowexceptionandwarningtdsparserstateobject stateobj boolean callerhasconnectionlock boolean asyncclose 810 systemdatasqlclienttdsparserconnectserverinfo serverinfo sqlinternalconnectiontds connhandler boolean ignoresniopentimeout int64 timerexpire boolean encrypt boolean trustservercert boolean integratedsecurity boolean withfailover 6702720 systemdatasqlclientsqlinternalconnectiontdsattemptoneloginserverinfo serverinfo string newpassword securestring newsecurepassword boolean ignoresniopentimeout timeouttimer timeout boolean withfailover 219 systemdatasqlclientsqlinternalconnectiontdsloginnofailoverserverinfo serverinfo string newpassword securestring newsecurepassword boolean redirecteduserinstance sqlconnectionstring connectionoptions sqlcredential credential timeouttimer timeout 6704856 systemdatasqlclientsqlinternalconnectiontdsopenloginenlisttimeouttimer timeout sqlconnectionstring connectionoptions sqlcredential credential string newpassword securestring newsecurepassword boolean redirecteduserinstance 6705315 systemdatasqlclientsqlinternalconnectiontdsctordbconnectionpoolidentity identity sqlconnectionstring connectionoptions sqlcredential credential object providerinfo string newpassword securestring newsecurepassword boolean redirecteduserinstance sqlconnectionstring userconnectionoptions 610 systemdatasqlclientsqlconnectionfactorycreateconnectiondbconnectionoptions options dbconnectionpoolkey poolkey object poolgroupproviderinfo dbconnectionpool pool dbconnection owningconnection dbconnectionoptions useroptions 1049 systemdataproviderbasedbconnectionfactorycreatepooledconnectiondbconnectionpool pool dbconnectionoptions options dbconnectionpoolkey poolkey dbconnectionoptions useroptions 74 systemdataproviderbasedbconnectionpoolcreateobjectdbconnectionoptions useroptions 6707883 systemdataproviderbasedbconnectionpoolusercreaterequestdbconnectionoptions useroptions 78 systemdataproviderbasedbconnectionpooltrygetconnectiondbconnection owningobject uint32 waitformultipleobjectstimeout boolean allowcreate boolean onlyonecheckconnection dbconnectionoptions useroptions dbconnectioninternal connection 2192 systemdataproviderbasedbconnectionpooltrygetconnectiondbconnection owningobject taskcompletionsource1 retry dbconnectionoptions useroptions dbconnectioninternal connection 116 systemdataproviderbasedbconnectionfactorytrygetconnectiondbconnection owningconnection taskcompletionsource1 retry dbconnectionoptions useroptions dbconnectioninternal connection 1012 systemdataproviderbasedbconnectionclosedtryopenconnectiondbconnection outerconnection dbconnectionfactory connectionfactory taskcompletionsource1 retry dbconnectionoptions useroptions 6712511 systemdatasqlclientsqlconnectiontryopentaskcompletionsource1 retry 152 systemdatasqlclientsqlconnectionopen 229 systemdataentitysqlserverc thisplayclass1executeb 0 15 systemdataentitysqlserverdefaultsqlexecutionstrategyexecutefunc1 operation 263 systemdataentitysqlserversqlproviderservicesusingconnectiondbconnection sqlconnection action1 act 334 systemdataentitysqlserversqlproviderservicesusingmasterconnectiondbconnection sqlconnection action1 act 582 systemdataentitysqlserversqlproviderservicesgetdbprovidermanifesttokendbconnection connection 373 systemdataentitycorecommondbproviderservicesgetprovidermanifesttokendbconnection connection 115providerincompatibleexception the provider did not return a providermanifesttoken string systemdataentitycorecommondbproviderservicesgetprovidermanifesttokendbconnection connection 451 systemdataentityutilitiesdbproviderservicesextensionsgetprovidermanifesttokencheckeddbproviderservices providerservices dbconnection connection 48providerincompatibleexception an error occurred while getting provider information from the database this can be caused by entity framework using an incorrect connection string check the inner exceptions for details and ensure that the connection string is correct systemdataentityutilitiesdbproviderservicesextensionsgetprovidermanifesttokencheckeddbproviderservices providerservices dbconnection connection 242 systemcollectionsconcurrentconcurrentdictionary2getoraddtkey key func2 valuefactory 83 systemdataentityinfrastructuredefaultmanifesttokenresolverresolvemanifesttokendbconnection connection 229 systemdataentitydbmodelbuilderbuilddbconnection providerconnection 118 systemdataentityinternallazyinternalcontextcreatemodellazyinternalcontext internalcontext 94 systemdataentityinternalretrylazy2getvaluetinput input 248 systemdataentityinternallazyinternalcontextinitializecontext 618 systemdataentityinternalinternalcontextgetentitysetandbasetypefortypetype entitytype 26 systemdataentityinternallinqinternalset1initialize 72 systemdataentityinternallinqinternalset1get internalcontext 21 systemdataentityinfrastructuredbquery1systemlinqiqueryableget provider 68 systemlinqqueryablefirstordefaultiqueryable1 source expression1 predicate 85 mirrorquickstartmodelsutilsstorecredentialsstring userid iauthorizationstate credentials 377 mirrorquickstartcontrollersauthcontrolleroauth2callbackstring code 277 lambda methodclosure controllerbase object 127 systemwebmvcreflectedactiondescriptorexecutecontrollercontext controllercontext idictionary2 parameters 274 systemwebmvccontrolleractioninvokerinvokeactionmethodcontrollercontext controllercontext actiondescriptor actiondescriptor idictionary2 parameters 39 systemwebmvcc thisplayclass15invokeactionmethodwithfiltersb 12 120 systemwebmvccontrolleractioninvokerinvokeactionmethodfilteriactionfilter filter actionexecutingcontext precontext func1 continuation 637 systemwebmvccontrolleractioninvokerinvokeactionmethodwithfilterscontrollercontext controllercontext ilist1 filters actiondescriptor actiondescriptor idictionary2 parameters 307 systemwebmvccontrolleractioninvokerinvokeactioncontrollercontext controllercontext string actionname 720 systemwebmvccontrollerexecutecore 162 systemwebmvccontrollerbaseexecuterequestcontext requestcontext 305 systemwebmvcc thisplayclassbbeginprocessrequestb 5 62 systemwebmvcasyncc thisplayclass1makevoiddelegateb 0 15 systemwebcallhandlerexecutionstepsystemwebhttpapplicationiexecutionstepexecute 606 systemwebhttpapplicationexecutestepiexecutionstep step boolean completedsynchronously 288to solve above i did try to modify connectionstring with same name defaultconnection but with integrated security but exception stays the same local copy which is not giving exception and seems to work also confuses me because i dont know the database location it used to store user credentials,"['c#', 'asp.net', '.net']" +597874,can we read the os environment variables in java my os is windows7 i want to read the environment variables in my java application i have searched google and many peoples answer is to use the method systemgetpropertystring name or systemgetenvstring name but it does not seem to work through the method i can read some variables value that defined in the jvm if i set an environment variable named config with value some config infomations how can i get the value in javathanks for any help,['java'] +597897,dynamically creating an assembly targetting a specific net runtime using reflectionemit i am using reflectionemit to develop a tool that dynamically creates an assembly at runtimethe tool is targeting the net 45 frameworki would like to know if it is possible to specify which net runtime the dynamically generated assembly targets eg specify that a net 35 assembly will be created for example,"['c#', '.net']" +597918,query across multiple databases on same server i am looking for a way of dealing with the following situationwe have a database server with multiple databases on it all have the same schema different datawe are looking for a way to query across all the databases and for it to be easy to configure as more databases may be added at any time this data access must be realtimesay as an example you have an application that inserts orders each application has its own db etc what we are then looking for is an efficient way for a single application to then access the order information in all the other databases in order to query it and subsequently action itmy searches to date have not revealed very much however i think i may just be missing the appropriate keywords in order to find the correct info,['sql'] +598060,how do i output the regression prediction from each tree in a random forest in python scikitlearn i am new to scikitlearn and random forest regression and was wondering if there is an easy way to get the predictions from every tree in a random forest in addition to the combined prediction i would like to output all of the predictions in a list and not view the entire tree i know that i can get the leaf indices using the apply method but i am not sure how to use that to get the value from the leaf any help is appreciatededit heres what i have so far from comments below it was not clear to me before that the trees in the estimators attribute could be called but it seems that the predict method can be used on each tree using that attribute is this the best way to do this thoughnumbertrees 100clf randomforestregressorn estimatorsnumbertreesclffitxyfor tree in rangenumbertrees printclfestimators treepredictvalirow1,['python'] +598084,android volley error no authentication challenges found i am trying to work with some legacy code and have come up against an issue when using volley i am trying to get to an api that our main site has and it works fine for one account but not another i am trying to work out what the differences might be in the request urlheaders and also what is coming back in the response but i cannot seem to find a way in the volley code to print this to the logthe error i am getting iscomandroidvolleynoconnectionerror javaioioexception no authentication challenges foundi have read around that this might be due to a 401 response but i do not really know what that means or at least how to provetest that i am really confused that it works for one account and not anotherthe url is slightly different as one is for our uk site and the other our am but other than that there is no differencethanks,['android'] +598092,vbnet why does mathround round 5 to the nearest even number and what can i do about it why is mathround0125 2 rounding to 012dim foo as decimalfoo mathround0125 2foo is now 012 but it should b 013i heard it is because some standard in net rounds to the nearest even number but that is just bad math 125 will round down to 12 but 135 will round up to 14 is there a way to fix this,['.net'] +598111,travis special requirements for each python version i need unittest2 and importlib for python 26 that is not required for other python versions that travis tests againstis there a way to tell travisci to have different requirementstxt files for each python version,['python'] +598118,why does not the browser reuse the authorization headers after an authenticated xmlhttprequest i am developing single page app using angular the backend exposes rest services that require basic authentication getting indexhtml or any of the scripts does not require authentication i have an odd situation where one of my view has a img where the src is the url of a rest api that requires authentication the img is processed by the browser and i have no chance to set the authorization header for get request it makes that causes the browser to prompt for credentialsi attempted to fix this by doing thisleave img src empty in the source at document ready make an xmlhttprequest to a service apilogin with the authorization header just to cause the authentication to occurupon completing that call set the img src attribute thinking that by then the browser would know to include the authorization header in subsequent requestsbut it does not the request for the image goes out without the headers if i enter the credentials then all other images on the page are righti have also tried and angulars ngsrc but that produced the same resulti have two questionswhy did not the browser ie10 include the headers in all requests after a successful xmlhttprequest what can i do to work around this problembergi asked for requests details here they arerequest to apiloginget httpsmyserverdev30281 webservicesapilogin http11accept authorization basic header hereacceptencoding gzip deflateuseragent mozilla40 compatible msie 70 windows nt 62 wow64 trident60 net40e net40c net clr 3530729 net clr 2050727 net clr 3030729connection keepaliveresponse apiloginhttp11 200 okcachecontrol nocachepragma nocachecontentlength 4contenttype applicationjson charsetutf8expires 1server microsoftiis80xaspnetversion 4030319xpoweredby aspnetdate fri 20 dec 2013 1452 gmtrequest to userpicture2218get httpsmyserverdev30281 webservicesapiuserpicture2218 http11accept acceptencoding gzip deflateuseragent mozilla40 compatible msie 70 windows nt 62 wow64 trident60 net40e net40c net clr 3530729 net clr 2050727 net clr 3030729connection keepaliveand then the web browser prompts for credentials if i enter them i get this responsehttp11 200 okcachecontrol public maxage60contentlength 3119contenttype imagepngserver microsoftiis80xaspnetversion 4030319xpoweredby aspnetdate fri 20 dec 2013 145017 gmt,"['javascript', 'html']" +598144,python loggingformatter is there any way to fix the width of a field and justify it leftright heres a sample of log records from the logging tutorial20050319 153855977 simpleexample debug debug message20050319 153855979 simpleexample info info message20050319 153856054 simpleexample warning warn message20050319 153856055 simpleexample error error message20050319 153856130 simpleexample critical critical messagethis trailing jaggedness annoys me to no endi really want to be able to format like this20050319 153855977 simpleexample debug debug message20050319 153855979 simpleexample info info message20050319 153856054 simpleexample warning warn message20050319 153856055 simpleexample error error message20050319 153856130 simpleexample critical critical messagei have attempted the following for my logger which does not work abbreviated codefmt 08formatter loggingformatterasctimes filenames fmtformatlevelnames messages ymd hmsthis executes fine and prints the level name as always but it does not implement the width formatexloggerdebugtesting debug messageloggerinfosome random infologgercriticaloh crapactual result20131216 134310 logtester debug testing debug message20131216 134310 logtester info some random info20131216 134310 logtester critical oh crapdesired result20131216 134310 logtester debug testing debug message20131216 134310 logtester info some random info20131216 134310 logtester critical oh crapany hints to implement a fixed width of a field in a loggingformatterusing python 269edit second attempt using another methodformatter loggingformatterasctimes filenames foo5s foo levelnames messages ymd hmsstill results in20131216 134310 logtester debug testing debug message20131216 134310 logtester info some random info20131216 134310 logtester critical oh crapmaybe i am just doing something boneheaded,['python'] +598173,difference between attributes and base attributes in ruby i have seen several models define a static method selfbase attributes object end and some other models define the static method selfattributes attributes endwhat exactly is the difference between attributes and base attributes,"['ruby-on-rails', 'ruby']" +598200,http contenttype header and json ok so i have always been trying to avoid using most of the http protocols properties or how ever you may please to call them for the sake of fear of the unknown however i said to myself that i am going to face fear today and start using headers purposely what i have been trying to achieve here is send json data to the browser and use it right away for example if i have an ajax handler function on ready state 4 which looks like sofunction ajaxhandlerresponse alertresponsetextand i have set the contenttype header in my phpheadercontenttype applicationjsonecho json encodearraytext omrelemy question is why cannot i directly access the property from the handler function when the browser is clearly told that the incoming data is applicationjson,"['javascript', 'php']" +598204,i created an empty project mvc but now want user roles and profiles tables added to my db when you create an mvc application with windows authentication it adds roles and what not to your database tables how do you add those in manually if you have created the project as an empty projecti have run cwindowsmicrosoftnetframeworkv4030319aspnet regsqlexe inside packagemanager but it has made the old versions aspnet blabla oh god there is so many tables and views added cries self to sleepi found vvs100aspxfindingthecorrectversionwhich pretty much says the usual stuff that ends up placing the crazies in my database is there anything wrong with using the aspnet blabla tables,['c#'] +598218,ice default io error handler doing an exit pid 11281 errno 4 one of our pyqt app throwa an error about iceauthority as below and exit ice default io error handler doing an exit pid 11281 errno 4on looking at the trace we see the following write25 1032003030t01010377rtstyle 32 32read25 0x16a67f0 8 erestartsys to be restarteda sigchld child exited 0 0 awrite6 0 1 1rt sigreturn0x2 1 eintr interrupted system callwrite2 ice default io error handler doi 69 69this looks like the iceauthority file read operation failed to restart after handling the sigchld for one of the processes we spawned from the pyqt app on googling there are a lot of reports about iceauthority file failure and people suggest restarting the system deleting the iceauthority file or unsetting session manager we are inclined to unset session manager in our pyqt app for now but i would like to understand why the operation failed to restart the read operation of the iceauthority file is this a bug in the gnomesession code is anyone aware of italso i would like to mention that i tried setting sa restart to false for the sigchld handle to restart the operation this failed to workplease find below our system details linux nycnxl01schrodingercom 2632358232el6x86 64 1 smp wed oct 16 183712 utc 2013 x86 64 x86 64 x86 64 gnulinuxcentos release 64 final,['c'] +598247,aspnet identity default password hasher how does it work and is it secure i am wondering wether the password hasher that is default implemented in the usermanager that comes with mvc 5 and aspnet identity framework is secure enough and if so if you could explain to me how it worksipasswordhasher interface looks like thispublic interface ipasswordhasher string hashpasswordstring password passwordverificationresult verifyhashedpasswordstring hashedpassword string providedpasswordas you can see it does not take a salt but it is mentioned in this thread aspnet identity password hashing that it does infact salt it behind the scenes so i am wondering how does it do this and where does this salt come frommy concern is that the salt is static rendering it quite insecure,"['c#', 'asp.net']" +598250,pyplot show only first 3 lines in legend i am running a simulation 200 times and plotting the 3 output lists as 3 lines with high transparency this allows me to show variance between simulationsthe problem is that my legend shows 3x200 items instead of 3 items how do i get it to show the legend for each line oncefor simulation in range200 pltplotnum s nodes labelsusceptible colorblue alpha002 pltplotnum r nodes labelrecovered colorgreen alpha002 pltplotnum i nodes labelinfected colorred alpha002pltlegend pltshow,['python'] +598289,transition android fragment slide up i have a fragment that is to replace another fragment i want to specify the animation but the animation is ignoredtransactionreplaceridmy fragment newfragtransactionaddtobackstacknulltransactionsetcustomanimationsranimslide in up ranimslide out upslide in upxml version10 encodingutf8translate xmlnsandroid androiddurationandroidintegerconfig longanimtime androidfromydelta0p androidtoydelta100p slide out upxml version10 encodingutf8translate xmlnsandroid androiddurationandroidintegerconfig longanimtime androidfromydelta100p androidtoydelta0p all i am really trying to achieve is for the new fragment to slide in from the bottom my animations are ignored what is the code missing,['android'] +598341,passing data between 2 uiviewcontroller using delegate and protocol i know this question has been asked and answered many times over here but i am dealing with this thing for the first time and still not able to get the perfect implementation of it in my mind heres the code i have the delegate method i implement to pass data from secondviewcontroller to firstviewcontrollerfirstviewcontrollerhimport secondviewcontrollerhinterface firstviewcontroller uitableviewcontrollersampledelegate endfirstviewcontrollerminterface firstviewcontroller array in which i want to store the data i get back from secondviewcontrollerproperty nonatomic copy nsarray sampledataendimplementation firstviewcontroller voidtableviewuitableview tableview didselectrowatindexpathnsindexpath indexpath secondviewcontroller controller secondviewcontroller alloc init selfnavigationcontroller pushviewcontrollercontroller animatedyesendsecondviewcontrollerhprotocol sampledelegate nsobject nsarraysenddatabacktofirstcontrollerendinterface secondviewcontroller uitableviewcontrollerproperty nonatomic strong id sampledelegate sampledelegateobjectendsecondviewcontrollerminterface secondviewcontroller property strong nonatomic nsarray datainsecondviewcontrollerendimplementation secondviewcontroller voidviewdidload super viewdidload selfdatainsecondviewcontroller nsarray arraywithobjectsobject1 object2 nil nsarraysenddatabacktofirstcontroller return selfdatainsecondviewcontrollerendam i doing it correctly all i want it to send the data in selfdatainsecondviewcontroller to firstviewcontroller and store it over there in the nsarray property sampledata of firstviewcontrollersomehow i am not able to access senddatabacktofirstcontroller in firstviewcontroller what other things i am missing implementing to access senddatabacktofirstcontroller there,['ios'] +598353,thisplay text on rect using d3js i am developing normalized stacked bar chart using d3jsand trying to append a text on rectit is getting appended when i inspect in browserbut it is not visiblei want something like thishere is my codevar margin top 20 right 100 bottom 30 left 40 width 400 marginleft marginright height 200 margintop marginbottomvar x d3scaleordinal rangeroundbands0 width 11var y d3scalelinear rangeroundheight 0var color d3scaleordinal range404041 00adef bdc0 d1d2d4 d3d3d3var xaxis d3svgaxis scalex orientbottomvar yaxis d3svgaxis scaley orientleft tickformatd3format10var svg d3selectbodyappendsvg attrwidth width marginleft marginright attrheight height margintop marginbottom 20 appendg attrtransform translate marginleft margintop d3jsonnstackedbardatajson functionerror data colordomaind3keysdata0filterfunctionkey return key state dataforeachfunctiond var y0 0 dages colordomainmapfunctionname return name name y0 y0 y1 y0 dname dagesforeachfunctiond dy0 y0 dy1 y0 datasortfunctiona b return bages0y1 aages0y1 xdomaindatamapfunctiond return dstate svgappendg attrclass x axis attrtransform translate0 height callxaxis stylefill bdc0 appendtext attrclassbarchartaxisvalue var insertlinebreaks function d var el d3selectthis var words dsplit eltext for var i 0 i wordslength i var tspan elappendtspantextwordsi if i 0 tspanattrx 0attrdy 12 svgselectallgxaxis g texteachinsertlinebreaks svgappendg attrclass y axis callyaxis stylefill bdc0 appendtext attrclassbarchartaxisvalue attrtransform rotate90 attrx70 attry 15 attrdy 71em styletextanchor middle textpercentage var state svgselectallstate datadata enterappendg attrclass state attrtransform functiond return translate xdstate 0 var sandeep stateselectallrect datafunctiond return dages enterappendrect attrwidth xrangeband attry functiond return ydy1 attrheight functiond return ydy0 ydy1 stylefill functiond return colordname appendtext attrfillf stylestrokewidth 1 stylefontsize18pxzindex9 styletextanchor middle textfunctiond return dy1dy0100tofixed0,"['javascript', 'css']" +598376,iab startsetup nullpointerexception i am attempting to setup inapp billing in my application i have not got very far and am running into a null pointer exception when trying to start my iabhelper i am following this google tutorialimport comiabtestutiliabhelperimport comiabtestutiliabresultpublic class mainactivity extends activity iabhelper mhelper override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main string base64encodedpublickey my secret key mhelper new iabhelperthis base64encodedpublickey mhelperenabledebugloggingtrue turned on to try to help solve the issue logdtest starting setup mhelperstartsetupnew iabhelperoniabsetupfinishedlistener public void oniabsetupfinishediabresult result logdtest setup finished ifresultissuccess oh noes there was a problem logdtest problem setting up inapp billing result return iab set up logdtest iab ready in the below logcat it appears that the null pointer exception is being triggered in iabhelperjava on line 267 since this is google code i am not sure how to fix this here is line 267if mcontextgetpackagemanagerqueryintentservicesserviceintent 0isempty here is my logcat with the error1217 052829908 etrace1478 error opening trace file no such file or directory 21217 052830898 wgoogleplayservicesutil1478 google play store is missing1217 052831838 dtest1478 starting setup1217 052831838 diabhelper1478 starting inapp billing setup1217 052831848 dandroidruntime1478 shutting down vm1217 052831848 wdalvikvm1478 threadid1 thread exiting with uncaught exception group0x40a719301217 052831878 eandroidruntime1478 fatal exception main1217 052831878 eandroidruntime1478 javalangruntimeexception unable to start activity componentinfocomiabtestcomiabtestmainactivity javalangnullpointerexception1217 052831878 eandroidruntime1478 at androidappactivitythreadperformlaunchactivityactivitythreadjava21801217 052831878 eandroidruntime1478 at androidappactivitythreadhandlelaunchactivityactivitythreadjava22301217 052831878 eandroidruntime1478 at androidappactivitythreadaccess600activitythreadjava1411217 052831878 eandroidruntime1478 at androidappactivitythreadhhandlemessageactivitythreadjava12341217 052831878 eandroidruntime1478 at androidoshandlerthispatchmessagehandlerjava991217 052831878 eandroidruntime1478 at androidoslooperlooplooperjava1371217 052831878 eandroidruntime1478 at androidappactivitythreadmainactivitythreadjava50411217 052831878 eandroidruntime1478 at javalangreflectmethodinvokenativenative method1217 052831878 eandroidruntime1478 at javalangreflectmethodinvokemethodjava51217 052831878 eandroidruntime1478 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava7931217 052831878 eandroidruntime1478 at comandroidinternaloszygoteinitmainzygoteinitjava5601217 052831878 eandroidruntime1478 at dalviksystemnativestartmainnative method1217 052831878 eandroidruntime1478 caused by javalangnullpointerexception1217 052831878 eandroidruntime1478 at comiabtestutiliabhelperstartsetupiabhelperjava2671217 052831878 eandroidruntime1478 at comiabtestmainactivityoncreatemainactivityjava1121217 052831878 eandroidruntime1478 at androidappactivityperformcreateactivityjava51041217 052831878 eandroidruntime1478 at androidappinstrumentationcallactivityoncreateinstrumentationjava10801217 052831878 eandroidruntime1478 at androidappactivitythreadperformlaunchactivityactivitythreadjava21441217 052831878 eandroidruntime1478 11 moreedit i am still not sure the reason for the error however i have found a useful tutorial that has been better than the google documentation google play inapp billing into an android application e28093 a tutorial,['android'] +598435,how to fix ibtool failed with exit code 255 i have never encountered this problem before the application used to run perfectly but now it always says this error i have tried cleaning and rebooting i have tried resetting ios simulator i have tried deleting derived data this is what it says compilestoryboard youngsterstennisappbaselprojmain iphonestoryboardcd usersdjdesktopyoungsterstennisappsetenv ibsc minimum compatibility version 60setenv path applicationsxcodeappcontentsdeveloperplatformsiphonesimulatorplatformdeveloperusrbinapplicationsxcodeappcontentsdeveloperusrbinusrbinbinusrsbinsbinsetenv xcode developer usr path applicationsxcodeappcontentsdeveloperusrbinapplicationsxcodeappcontentsdeveloperplatformsiphonesimulatorplatformdeveloperusrbinibtool errors warnings notices minimumdeploymenttarget 60 outputformat humanreadabletext compile usersdjlibrarydeveloperxcodederiveddatayoungsterstennisappftehnuqeslbyekfiszajlixujbqkbuildproductsdebugiphonesimulatoryoungsterstennisappappbaselprojmain iphonestoryboardc usersdjdesktopyoungsterstennisappyoungsterstennisappbaselprojmain iphonestoryboardcommand applicationsxcodeappcontentsdeveloperplatformsiphonesimulatorplatformdeveloperusrbinibtool failed with exit code 255any help for this would be great i also have quite a large storyboard does that matterthanks in advance,['ios'] +598463,sqlite insert current timestamp with milliseconds precision i am trying to insert the current timestamp into sqlitecreate table test timestamp datetimeinsert into test valuesdatetimenowthis does create the timestamp but only with secondsprecision the timestamp looks like 20131217 070220 is it possible to add the milliseconds as well,['sql'] +598465,css media queries one file vs separate files and impact on loading speed for a site i currently use stylecss and a bunch of other stylesheets 960css etc loaded like thislink relastylesheet mediaascreen hrefacssastylecsslink relastylesheet mediaaonly screen and maxwidtha 960pxa hrefaacssa960cssanow i am concerned about speed i know i could combine the files into one big file but that would mean downloading also irrelevant dataso basically my question is what is a better approach minimizing the amount of requests or minimizing the amount of data passed to one user,"['html', 'css']" +598466,has got any real benefit of plinq recently i made a couple of measures about linq and plinqi cannot see in which situation has a real significant benefit of plinqi have found many examples such asenumerablerange0 10asparallelforall threadsleep50this is totally useless example because it can be parallized with degree of 10 and yes then will be faster 10 times but it is rare in a business application to loop 10 times and making io jobs if somebody can mention an example please post itplinq is only available for linq to objects and linq to xmlnot suggested to use it in application which runs on webserverit has own thread managementso our opportunities are reduced to desktop applications which have multiple coresusually i write linq queries which runs sequentially in fractions of a second if i parallize it and it really will run parallel then will be faster but who caresi think it is still fast enough the end user would not see any differencei can imagine an example when somebody gets all data from db and running query in memory then maybe it is useful but it is a wrong design tpl is a good stuff for asyncron programming but i am still not sure plinq is a useful tooldoes anybody have positive experience about that,['c#'] +598543,connection at client database hangs application on my application i need to connect at client databasesqlserver only to see if we can connectthese are my connection strings from webconfigthe values are not that way ia ve changed the ip user and pwdadd nameconnectionstringlibracom connectionstringdata source192168145sqlserver2008initial catalogxuserxpwdxapplication namemes providernamesystemdatasqlclient mineadd nameconnectionstringmigplus connectionstringdata source9initial catalogxuserxpwdx providernamesystemdatasqlclient clientbut this piece of code hangs my entire applicationwhen i say that it hangs i mean that it dont let my application to connect to our db ia m executing it at defaultaspx on load eventprotected void page loadobject sender eventargs e if testaintegracaoerpmigplus lblmensagemintegracaovisible true sessionintegracao false else sessionintegracao trueprotected static bool testaintegracaoerpmigplus string connectionstringmigplus webconfigurationmanagerconnectionstringsconnectionstringmigplusconnectionstring bool ret false using sqlconnection conn new sqlconnectionconnectionstringmigplus try connopen if connstate connectionstateopen ret true catch sqlexception ret false return retedit the problem is not if i can connect to the server or not the problem is when ia m trying to connect to that db my aspnet website frozen to new requests at others page,"['c#', 'asp.net']" +598550,the cxx compiler identification is unknown we are having trouble compiling a project using cmake v2812 under windows 7 64bit using visual studio 2012 cmake gives us the following errors we already tried starting cmake from the visual studio command line using admin rights there seems to have been a similar bug in cmake 2811 thanks in advance for any helpkarlcmake error at cprogram files x86cmake 28sharecmake28modulescmakedeterminecompileridcmake446 execute process execute process given command argument with no valuecall stack most recent call first cprogram files x86cmake 28sharecmake28modulescmakedeterminecompileridcmake48 cmake determine compiler id vendor cprogram files x86cmake 28sharecmake28modulescmakedetermineccompilercmake131 cmake determine compiler id cmakeliststxt2 projectthe c compiler identification is unknowncmake error at cprogram files x86cmake 28sharecmake28modulescmakedeterminecompileridcmake446 execute process execute process given command argument with no valuecall stack most recent call first cprogram files x86cmake 28sharecmake28modulescmakedeterminecompileridcmake48 cmake determine compiler id vendor cprogram files x86cmake 28sharecmake28modulescmakedeterminecxxcompilercmake127 cmake determine compiler id cmakeliststxt2 projectthe cxx compiler identification is unknowncould not find swig missing swig executable swig dir cmake warning at srccmakeliststxt44 message swig was not found you will not be able to compile for cconfiguring incomplete errors occurredsee also cusershcilaser controlcmakefilescmakeoutputlogsee also cusershcilaser controlcmakefilescmakeerrorlog,['c++'] +598551,single touch in android is it possible to allow the user to touch the screen only oncemeaning a user touches the screen and if he tries to touch the screen again nothing will happen i am implementing the approach using canvas to draw the objects on the screenthank you in advance,['android'] +598554,how to set string array in java annotation i have declared a annotation like thispublic interface customannot string author default me string description default a valid annotation therefore would becustomannotauthorauthor1 descriptiontestwhat i cannot figure out is how to set more than one author since author has return string this should be possiblecustomannotauthorauthor1autor2 descriptiontestdoes not work,['java'] +598561,how to get random text from lorem ipsum in php i want the random text from lorem ipsum so i can use it when generating webpages i cannot find any php functions that does this and i am wondering if there is any publicly available libraries or apis on sites that could be used to get some random text,['php'] +598567,what is the most efficient way to implement groupby in javascript i am trying to implement a groupby method with these parametersfunction groupbykeyselector elementselector comparer keyselector functione return eid elementselector functione return ename comparer equals functionab return ab gethashcode however i do not know an efficient way to implement iti created a jsperf test with linqjs and a method i created which does not use a comparer and only work on flat types output test hereother libraries such as underscore and lodash does not take a comparer parameter so their implementations are irrelevantmy key could be a class so i need something to determine if tkey is the same in different instancesso basically what i am trying to do is copy c linq groupby behavior documented heresample inputvar arrcomplex n value 10 name foo n value 10 name bar n value 20 name foo n value 20 name bar sample output or something like this key value10 elementsfoobar key value20 elementsfoobar any ideas on how to implement itbountyfor the bounty i would like you take in consideration thatthe key could be an objecttwo objects can be equal if some property is equalit should be as fast as or faster than existing solutionsthe result can be an array or object does not matter as long as i can get elements grouped by a keywell i expect a complete answer,['javascript'] +598582,overriding default parameters in c really simple to replicate the output is bizarreexpected output is b bactual output is a bhas anyone got any msdn explanation of this behaviour i could not find anyanew btestnew btestpublic class a public virtual void teststring bob a throw new notimplementedexception public class b a public override void teststring bob b httpcontextcurrentresponsewritebob,['c#'] +598618,how can i see all packages that depend on a certain package with pip i would like to see a list of packages that depend on a certain package with pip that is given django i would like to see djangocms djangofiler because i have these packages installed and they all have django as dependency,['python'] +598630,how to create an stdfunction as method argument with stdstoi as default value i would like to use an stdfunction as an argument of a method and set its default value as stdstoii tried the following codevoid teststdfunctionintconst stdstring str size t pos int base infuncstdstoiunfortunately i get the following errorno viable conversion from overloaded function type to stdfunctionint const stdstring size t inti managed to compile by adding creating a dedicated methodinclude functionalinclude stringint my stoiconst stdstring s return stdstoisvoid teststdfunctionintconst stdstring infuncmy stoiwhats wrong in the first versionis not it possible to use stdstoi as default value,['c++'] +598656,start sticky does not work on android kitkat one of my apps has a backgrouod service that uses the start sticky return code from onstartcommand to automatically restart when the system kills itit seems that this is no longer working on android kitkatis there any solution for this should i be doing something different on kitkat to keep the service running note there is a similar thiscussion on the androiddevlopers group about swiping the app from the recent apps list behaves could this two issues be related topicandroiddevelopershdsq4tiacedit saw that there are open bugs on android issue trackeredit2 the same happens even if service is running using startforeground in a separate process and with the flag androidstopwithtaskfalse in the androidmanifestxml fileedit3 more related bugs on android issue trackeris there some sort of workaround to get the previous behavior,['android'] +598688,what to ignore in bowerjson i have a library that i am developing and i am publishing it to bower right now i am ignoring everything except geniejs the library and genieminjs is there value in having the readmemd or the travis build file or the demo files or anything else it seems to me that the reason someone adds your component to their project is so they can use it in their product and they do not want their file system polluted am i wrong,['javascript'] +598689,does one still need to use fpic when compiling with gcc on gcc target machines when one wanted to compile a shared library one would need to specify fpic or fpic to get things to work correcly this is because by default absolute addressing was used by defaults which is suitable for executable that have full control of their own address space but not shared libraries which could be loaded anywhere in an executables address spacehowever modern kernels are now implementing address space randomization and many modern architectures support pc relative addressing this all seems to make the absolute addressing either unusable address space randomization or unneeded pc relative addressingi have also notices that clang does not have a fpic option which makes me thing that it is no longer necessaryso is fpic now redundant or does one now need to generate separate o files one for static library use and one for shared library use,"['c++', 'c']" +598711,python convert tuple to array how can i convert at 3dimensinal tuple into an arraya aappend124aappend234in a array likeb 124234,['python'] +598712,glob exclude pattern i have a directory with a bunch of files inside e2314 asd3442 and ephi want to exclude all files that start with eph with the glob functionhow can i do it,['python'] +598740,python list comprehension explained i have no problem for understanding thisa 1234b x for x in ai thought that was all but then i found this snippeta 123456b x for xs in a for x in xswhich makes b 123456 the problem is i am having troubles to understand the syntax in x for xs in a for x in xs could anyone explain how it works,['python'] +598878,visual studio 2013 fatal error c1041 fs i am using visual studio 2013 every so often by project refuses to compile if i undo any changes it still would not compile i have found that recreating the entire project works i would like to actually fix the problem though the error that i am getting is1criticcpp fatal error c1041 cannot open program database cusersusernamedesktopprojectnameprojectnamex64debugvc120pdb if multiple clexe write to the same pdb file please use fsi have tried following these instructions to no avail has anyone else encountered this and found a fix,['c++'] +598883,execute a command line binary with nodejs i am in the process of porting a cli library from ruby over to nodejs in my code i execute several third party binaries when necessary i am not sure how best to accomplish this in nodeheres an example in ruby where i call princexml to convert a file to a pdfcmd systemprince v buildspdfbookhtml o buildspdfbookpdfwhat is the equivalent code in node,"['javascript', 'ruby']" +598949,select a primefaces radio button with selenium webdriver i am trying to write selenium tests to select a radio button below is the html from view source table idsurveyformsurveyurltype classuiselectoneradio uiwidget stylewidth100margintop10pxmarginbottom 10px tbody tr td div classuiradiobutton uiwidget div classuihelperhiddenaccessible input idsurveyformsurveyurltype0 namesurveyformsurveyurltype typeradio valuetyped checkedchecked onchangecomssifeasibilitysurveyviewshowsurveytypethis div div classuiradiobuttonbox uiwidget uicornerall uistatedefault uistateactive span classuiradiobuttonicon uiicon uiiconbulletspan div div td tdlabel forsurveyformsurveyurltype0enter survey urllabeltd td div classuiradiobutton uiwidget div classuihelperhiddenaccessible input idsurveyformsurveyurltype1 namesurveyformsurveyurltype typeradio valuefile onchangecomssifeasibilitysurveyviewshowsurveytypethis div div classuiradiobuttonbox uiwidget uicornerall uistatedefault span classuiradiobuttoniconspan div div td tdlabel forsurveyformsurveyurltype1upload survey urlslabeltd tr tbodytablei want to select upload survey urls radio buttoni have tried several different approaches to select the radio button here are a few surveyformsurveyurltypeclick this gives me the error surveyformsurveyurltype1firstclickerror element is not clickable at point 809 367 other element would receive the click below give me nosuchelementfound driverfindelementbyidsurveyformsurveyurltype1click driverfindelementbyxpathinputtyperadio and idsurveyformsurveyurltype1click driverfindelementbyxpathinputvaluefileclick driverfindelementbycselectorsurveyformsurveyurltype1clickbelow do not give me any error but they also do not select the radio button uiradiobuttonbox uiwidget uicornerall uistatedefault1click uiradiobuttonbox uiwidget uicornerall uistatedefaultclick surveyformsurveyurltypefinduiradiobuttonbox uiwidget uicornerall uistatedefaultfindspanclickbut none of these work what am i missing,['java'] +598950,the wonderful activemodelforbiddenattributeserror i have been using strong params and trying to get a object create to pass i have two questionshow do you find out which attribute is causing the issuewhat am i missing in the code belowlets start with the error the log tells me nothingactivemodelforbiddenattributeserror in jobscontrollercreatejust for giggles here is the log which i do not see very usefulstarted post jobs for 127001 at 20131217 220359 0processing by jobscontrollercreate as html parameters utf8a authenticity tokenohq4lvqpvmpjzbzwcfjnybl78tacoc0wzlsmpczmd3k jobjob titlejunior rails developer job descriptiona new position getig nsomethfins lansnana languages rails ruby country codeao job typefulltime job salary30 job leveljunior commitcreate job user load 05ms select users from users where usersid 1 order by usersid asc limit 1completed 500 internal server error in 8msactivemodelforbiddenattributeserror activemodelforbiddenattributeserrormakes sense but then if i look at my createdef create bindingpry job jobnewjob params respond to do format if jobsave formathtml redirect to job notice job was successfully created formatjson render action show status created location job else formathtml render action new formatjson render json joberrors status unprocessable entity end end endstrong params def job params paramsrequirejobpermitjob title job level job description job salary country code job type state languages endi am mainly interested in finding how to find out where the problem is for future as it is seems like a needle in haystack error,['ruby-on-rails'] +599033,python beautifulsoup give multiple tags to findall i am looking for a way to use findall to get two tags in the order they appear on the pagecurrently i haveimport requestsimport beautifulsoupdef get soupurl request requestsgeturl page requesttext soup beautifulsouppage get tags soupfindallhr and strong for each in get tags print eachif i use that on a page with only em or strong in it then it will get me all of those tags if i use on one with both it will get strong tagsis there a way to do this my main concern is preserving the order in which the tags are found,['python'] +599163,android autocomplete with sqlite like works partially i have a restaurants table in my sqlite db that have the following records name latin name 12o manaki 12n o34 enriko now i am doing the search like thisfrom my fragmentstring selection dbhelpercol name like or dbhelpercol latin name like string selectionargs term termcursorloader loader new cursorloadergetactivity databasecontentproviderrest content uri columns selection selectionargs nullthe content provider query method public cursor queryuri uri string projection string selection string selectionargs string sortorder db dbhelpergetreadabledatabase sqlitequerybuilder builder new sqlitequerybuilder switchuri matchermatchuri case rest list buildersettablesdbhelperrest table break case rest id builderappendwheredbhelpercol id urigetlastpathsegment break default throw new illegalargumentexceptionunsupported uri uri cursor cursor builderquerydb projection selection selectionargs null null sortorder cursorsetnotificationurigetcontextgetcontentresolver uri return cursorso pretty basic right now here comes the problemif the term that comes in is en i can see the enriko restaurants among the othersif i pass enri i cannot see the enriko as a result anymoresame goes for the manaki restaurant i can see it until mana and after that for manak term for ex i cannot see it in the results listi was debugging my contentprovider and i realized that the cursor was empty so the problem have to be at the database level i guessplease helpupdatehaving the laalto comments in mind i decided to do some test on the database in the oncreate method of my sqliteopenhelperi inserted only those two records in the table by hand and it workednow the problem is that i have to insert 1300 records oncreate from a json file shipped in the assets folder right now i am parsing the json file create an arraylistrestaurant then loop trough it and insert one record per object for all 1300 items that kind of insertion would not work with the sqlite like method are there any gotchas about this kind of populating the database maybe i need to change file encoding it is utf8 now or maybe databases collation or maybe getstring from jsonobject can be tweaked for the database,['android'] +599208,get button click inside ui table view cell i have a viewcontroller with tableview and a separate nib for the table cell template the cell template has some buttons i want to access the button click along with the index of the cell clicked inside the view controller where i have defined the table viewso i have viewcontrollerh and viewcontrollerm where i have the uitableview and tabletemplateh tabletemplatem and tabletemplatexib where i have the nib defined i want the button click event with cell index in viewcontrollermany help on how can i do that,['ios'] +599272,wpf textbox not allowing undo when hosted in an elementhost within a vstooutlook addin i have an outlook addin vsto on an outlook form region i have a wpf user control within an elementhost i have an issue that a textbox within my user control does not have the undo capability in some configurations specifically in windows 7 outlook 2007 undo ie ctrlz does not work even though cutcopy etc all do work interestingly windows 8 outlook 2010 undo does workthe textbox xaml istextbox nametxtnote verticalscrollbarvisibilityauto spellcheckisenabledtrue texttopic notes textwrappingwrap acceptsreturntrue note i have tried setting the following attributes to make it work but to no avail isundoenabledtrue undolimit1can anyone suggest why this is happening and what i can do to make it work as expectedupdate 7 jan 2014 i have added the following keybindings to the text boxtextboxinputbindings keybinding commandapplicationcommandsundo keyz modifierscontrol keybinding commandapplicationcommandsredo keyy modifierscontrol keybinding commandapplicationcommandsundo keyg modifiersalt textboxinputbindingsand the result is cntlzcntrly still does not work however altg does work,"['c#', '.net']" +599288,ios facebook sdk error domain comfacebooksdk code 2 and code 7 i am developing the application which allow user to login via facebook using facebook sdk for it the error appears when a user has already logged in facebook in iphone settings if not all work correctly nsarray permissions nsarray alloc initwithobjectsemail nil fbsession openactivesessionwithreadpermissionspermissions allowloginuiyes completionhandler fbsession session fbsessionstate state nserror error self fbsessionstatechangedsession statestate errorerror i have already tried to set permissions as nil array nothing changed the log iserror domaincomfacebooksdk code2 the operation couldnat be completedcomfacebooksdk error 2 userinfo0x1552c6c0 comfacebooksdkerrorloginfailedreasoncomfacebooksdksystemloginthisallowedwithouterrorcomfacebooksdkerrorsessionkeyfbsession 0xabe8100 state fbsessionstateclosedloginfailedloginhandler 0x0 appid appidhere urlschemesuffix tokencachingstrategyfbsessiontokencachingstrategy 0x14b8f3d0expirationdate null refreshdate nullattemptedrefreshdate 011230 0 0 permissionsnullsometimes the error with code 7 is appears too i have read almost all topics related to this error my steps were compare my app id in plist file with fb bundle id they are the samemy app is not in a sandbox modeif i change from fbsession openactivesessionwithreadpermissionspermissions to fbsession openactivesessionwithpermissionspermissions it works but it is deprecated,"['ios', 'objective-c']" +599333,inconsistent use of const qualifier between declaration and definition i noticed that it is possible to have const qualifier on a value argument present in the function declaration and then omitted in the definition that does not change the signature of the function it actually compiles welli also noticed that the behavior is different between regular and template classes also there is a difference between how it is handled in gcc and clangconsider the following codetemplate typename t struct a void fconst inttemplate typename t void atfint x x 0struct b void fconst intvoid bfint x x 0void f afloat a af0 b b bf0when i compile with gcc i get no errors with clang i gettestcpp107 error readonly variable is not assignable x 0 testcpp267 note in instantiation of member function afloatf requested here af0 gcc took preference of the qualifier at the definition clang used the declaration and only for the template class amy questions areis this regulated by the standard or is this implementation definedwhy is the behavior is different between regular and template classeswhy is there no error or at least a warning that the const qualifier is used inconsistently between the declaration and the definitionare there any situation where this could be usefulupdateaccording to the comments it seems to be a clang bug i opened a new ticketupdatethe bug is fixedfixed in r203741,['c++'] +599336,how to make single user login in mvc 4 applictaion i am implementing an application where there is a mechanic for each machine in the company using the application i am trying to implement a user policy whereby if user is in a role mechanic with username machine1 and is logged in for that machine only one user can be logged at at the same time with the machine1 username for the companyif someone else tries to login with the same username it should be blocked and informed that there is already logged in user when the session timeout expires i should log out the logged in user and free the login to be used the same happens when the user logouts by himself i am trying to build this on aspnet mvc 4 applicationi have thought of using the sessionid userid and isloggedin boolean in the database but in this case i need to change the logged in flag on session timeout in the mvc app to write in the database which seems overkill if many users are logged inwhat would the implementation be like what methods or attributes should i be using to handle the session management in the database fyii have made my own method where i check if the user is logged in here it ispublic static bool validateuserstring username string password string companyname int companyid myrepositorygetcompanyidcompanyname int userid companyid 0 null myrepositorygetuseridusername companyid if useridhasvalue useridvalue 0 var userkey securitygenerateuserkeyusername companyname return websecurityloginuserkey password else return false here in this method i can check somehow if the session id is the same as in the database,"['c#', 'asp.net']" +599410,java generics and unchecked cast i am struggling with this aspect of generics in java hopefully someone can help me see the waysi have a class that holds a list of objects this code works but i want to get rid of the cast how can i make this more genericpublic class executor listbaserequestbaseobj mrequests new arraylistbaserequestbaseobj public executor suppresswarningsunchecked public t extends baseobj void addfinal baserequestt request mrequestsaddbaserequestbaseobj request public void execute for baserequestbaseobj r mrequests do something with r,['java'] +599487,android remove fragment add new fragment of same class again oncreateview and onactivitycreated not called i am destroying a programmatically created fragment withgetfragmentmanagerbegintransactionremovegetfragmentmanagerfindfragmentbyidridtestcommitwhich is determined in the xml file like thislinearlayout androidididtest androidorientationhorizontal androidlayout widthfill parent androidlayout heightfill parentlinearlayoutif i then create a fragment from the same class again in the mainactivitygetsupportfragmentmanagerbegintransaction addridresult bar testinstance committhen oncreate seem not called again the fragment is just empty what am i doing wrong here thanks,"['java', 'android']" +599491,in android should a contact sync adapter run in a separate process in my app i am using a contact sync adapter but it has a lot of information that it shares with the main app there are settings that the adapter needs to work proplery like login information and if the user changes any sync settings so i currently have it running in the same process and it communicates with the main ap using getapplicationcontext and then i have some shared variables in the application that the sync adapter is using during the sync process but in the training document and a few tutorials online the sample adapter is set up to run in its own process it is using androidprocesync in the manifest is that necessary and if it does run in a separate process how can i communicate back to the main app,['android'] +599501,is a pdo wrapper really overkill i have done some research about using a databasewrapper for my datahowever i read some posts where people claim you should not use pdo for a databasewrapper because it already is onethat may be so but i am still convinced that it has a lot of benefitsyou handle all your data actions crud in one class not spread across your website files so it is much easier to debug and handle errorsyou can easilly change your class with another databaseclassyou do not have to repeat your code just call the code in the databaseclassoptionally you can extend the class with for example logging statistic tests examplephpclass database public connection private host private username private password private dbname public function construct thisconnection new pdomysqlhostthishostdbnamethisdbnamethisusernamethispasswordarraypdomysql attr init command set names utf8 thisconnectionsetattributepdoattr errmode pdoerrmode exception public function insertquery array data thisconnectionpreparequeryexecutedata return thisconnectionlastinsertid public function updatequery array data stmt thisexecutequeryquerydata return stmtrowcount public function deletequery array data stmt thisexecutequeryquerydata return stmtrowcount public function findonequery array data null stmt thisexecutequeryquerydata return stmtfetchobject public function findmanyquery array data null stmt thisexecutequeryquerydata returnstmtfetchallpdofetch obj public function executequeryquerydata null stmt thisconnectionpreparequery stmtexecutedata return stmt instead of constantly repeating all the steps for retrieving data you can call get and pass a query and some optional parametersthis is a lot more efficiant than everytime open a connection perform 3 lines of code and close itdbgetselect from user where id array1,['php'] +599615,how do i make a square in c i am nine years old and i really like programming i am studying on my own and it is sometimes hard to figure things out as english is my second language i am trying to make a square box in c can anyone help me with this script i have tried it but it does not work please help me,['c++'] +599626,core data setprimitivevalueforkey behaves really weirdly this is a mysteryi am invoking setprimitivevalueforkey on an nsmanagedobject the key is a legit persistent modeled attribute of the object however setprimitivevalueforkey fails often setting the value for a different arbitrary attribute the docs say this behavior is expected when invoking setprimitivevalueforkey for an unmodeled key so it seems core data thinks the key is unmodeledthe strange partwhen the key is hardcoded as a string literal the primitive value is indeed set successfully it only fails when the key is a variable the variable i am using happens to be passed from the keypath argument of observevalueforkeypathofobjectchangecontextthe keypath variable is the same as the string literal isequal returns true and the hash values are equal the keypath variable is of type nscfstring does anyone know why setprimitivevalueforkey would behave any differently this behavior is on os x 1091an update with better informationthe misbehaving key traced back to a string loaded from a file on thisk the example below is an isolated case if the attribute string mainattr is written to thisk and read back in then setprimitivevalueforkey sets the value for the wrong attribute not mainattrcore data objectinterface boo nsmanagedobjectproperty nonatomic retain nsnumber mainattrproperty nonatomic retain nsnumber attr1property nonatomic retain nsnumber attr2property nonatomic retain nsnumber attr3endimport boohint mainint argc const char argv autoreleasepool nsmanagedobjectcontext context managedobjectcontext nsstring key mainattr write to thisk read back in nsstring path desktoptesttxt stringbyexpandingtildeinpath key writetofilepath atomicallyyes encodingnsutf8stringencoding errornull key nsstring stringwithcontentsoffilepath encodingnsutf8stringencoding errornull boo boo nsentitydescription insertnewobjectforentityfornameboo inmanagedobjectcontextcontext boo setprimitivevalue5 forkeykey nslogboo boo return 0,['ios'] +599663,browserspecific prefixes with a css transition on transform according to caniusecom for those browsers that support both css transition and css transform combinatorically there are at least three different typesthose that require the webkit prefix on both transition and transform eg safari 6 android browser 44those that only require the webkit prefix on transform eg chrome 3xthose that require prefixes on neither eg ff and ie1011how can i safely write my transition styles so that they are parsed correctly in each type i see two optionswebkittransition webkittransform 300ms transition webkittransform 300ms transform 300msorwebkittransition webkittransform 300ms transition webkittransform 300ms transition transform 300msnow because of type 2 and type 3 browsers i need to have a prefixless transition for both webkittransform and transform the problem with the first option is i worry that type 2 and type 3 browsers will not be able to parse the second line since they will always contain an unrecognized property the question is how do browsers handle invalid properties inside a transitionignore the entire transition style or just skip the invalid propertyi thought this may be mitigated by separating it into two properties so that if one is not parseable it will just be ignored apart from this second option being a bit verbose i still wonder if in the case of type 2 browsers the third transition will be unparseable and reset the transition back to nullany ideas how these perform generally also which of these are futurecompliant for when chrome et al switch from webkittransform to the prefixless transform,['css'] +599675,ble on nexus 7 me370t with android 442 i have been trying to pair ble device with my nexus 7 me370t using sample from sdk sdksamplesandroid18legacybluetoothlegatt but i am getting information ble not supported i was searching for solution and i have only found thatnb nexus 7 2012 with android 43 is not delivered with ble enabled to work with ble on this device you will need the bluetooth low energy enabler tool prerequisites for this to work is that the device is rooted and that the busybox app is installed i could not find any information about support on 442 or any enabled for 442 i only could find just in case some one else is searching for ble on nexus 7 this rom has a working ble on 44 kitkat it is almost stock rom called purity purity rom link and the question is do i need to root my nexus 7 with 442 to another rom to enable ble will it work after mod,['android'] +599701,pandas and unicode this is a string i am getting out of pandasdataframeto json putting it into rethis getting it out of rethis elsewhere and trying to read it via pandasread jsondfj args01234567date01385943901138594390213859403138594041385940513859406138594071385940host0yy38segm1org1kyy1segm1org2yy10segm1org3yy24segm1org4yy24segm1org5yy34segm1org6yy15segm1org7yy15segm1orgkwargs01234567operation0x gbinf1x initobj2x gobjparams3gtfull4x gbinf5gxyzinf6deletemfg7gxyzinfthingy0a13yy381a19kyy12a14yy103a14yy244a14yy245a12yy346a15yy157a15yy15status01012101310141015101617101time080110324420224730278740106750265260437170602it seems like it does not have any unicode in it yet on trying to read json it i gettraceback most recent call last file sqlprofilepy line 160 in module maybe save dataframesrconn configd results file sqlprofilepy line 140 in maybe save dataframes h5storeappendout queue df file homeusernameanacondalibpython27sitepackagespandasiopytablespy line 658 in append self write to groupkey value tabletrue appendtrue kwargs file homeusernameanacondalibpython27sitepackagespandasiopytablespy line 923 in write to group swriteobj value appendappend complibcomplib kwargs file homeusernameanacondalibpython27sitepackagespandasiopytablespy line 2985 in write kwargs file homeusernameanacondalibpython27sitepackagespandasiopytablespy line 2717 in create axes raise etypeerror unicode is not implemented as a table column homeusernameanacondalibpython27sitepackagespandasiopytablespy2717create axes raise epdb localsthis is what i am getting in locals it seems that append axis column names values are unicode whyappend axis uargs udate uhost ukwargs uoperation uthingy ustatus utime existing table none blocks floatblock time 1 x 8 dtype float64 objectblock args host kwargs operation thingy 5 x 8 dtype object intblock status 1 x 8 dtype int64 datetimeblock date 1 x 8 dtype datetime64ns axis 1 self frame table typappendablenrowsnonencols1indexersindex axes 0 kwargs klass class pandasiopytablesdatacol block obj args date host kwargs operation thingy status time0 20131202 003359 yy38segm1org x gbinf a13yy38 101 08011 20131202 003359 kyy1segm1org x initobj a19kyy1 1 032442 20131202 003400 yy10segm1org x gobjparams a14yy10 101 022473 20131202 003400 yy24segm1org gtfull a14yy24 101 027874 20131202 003400 yy24segm1org x gbinf a14yy24 101 010675 20131202 003400 yy34segm1org gxyzinf a12yy34 101 026526 20131202 003400 yy15segm1org deletemfg a15yy15 1 043717 20131202 003400 yy15segm1org gxyzinf a15yy15 101 0602 axis labels uargs udate uhost ukwargs uoperation uthingy ustatus utime nan rep nan data columns obj args date host kwargs operation thingy status time0 20131202 003359 yy38segm1org x gbinf a13yy38 101 08011 20131202 003359 kyy1segm1org x initobj a19kyy1 1 032442 20131202 003400 yy10segm1org x gobjparams a14yy10 101 022473 20131202 003400 yy24segm1org gtfull a14yy24 101 027874 20131202 003400 yy24segm1org x gbinf a14yy24 101 010675 20131202 003400 yy34segm1org gxyzinf a12yy34 101 026526 20131202 003400 yy15segm1org deletemfg a15yy15 1 043717 20131202 003400 yy15segm1org gxyzinf a15yy15 101 0602 validate true a 1 uargs udate uhost ukwargs uoperation uthingy ustatus utime index axes map 0 nameindexcnameindexaxis0pos0kindinteger b objectblock args host kwargs operation thingy 5 x 8 dtype object e typeerrorunicode is not implemented as a table column name none existing col none j 2 i 1 min itemsize none col namevalues block 1cnamevalues block 1dtypenoneshapenonehow can i fix that is this a bug in pandas pytablesenvironmentpython 27pandas0120tables300,['python'] +599725,using apache config and htaccess to dynamically set config vars for dev and production short summaryi need to be able to set an environment variable in the apache site config that defines if the site is dev beta or productionthe htaccess file in the web root will define config variables for the website database credentials domain etc based on the entry in the apache configurationalso i need to use one of the variables defined in the web roots htaccess in another htaccess located in another directorysite configurationapache config devbetai would like to set an environment variable for my dev and beta environments in their apache site config filessomething like thisim sure its not the correct syntaxsetenv environment type dev or setenv environment type betaapache config productionthe production sites apache config could either not set it at all or it could dosetenv environment type prodbut this would be optionalhtaccess set site config varsthe configuration variables used for database connection domain name and so on would then be set in the htaccess file in the public webroot like soagain just mockup syntaxif environment type exists environment type dev setenv base dir wexamplecomdev setenv db host localhost setenv db name devdb setenv db user devuser setenv db password devpass setenv web domain wdevdomaincom setenv cookie domain devdomaincomelseif environment type exists environment type beta setenv base dir wexamplecombeta setenv db host localhost setenv db name betadb setenv db user betauser setenv db password betapass setenv web domain wbetadomaincom setenv cookie domain betadomaincomelse setenv base dir wexamplecomw setenv db host localhost setenv db name proddb setenv db user produser setenv db password prodpass setenv web domain wproddomaincom setenv cookie domain proddomaincomifusing defined settingsi need to be able to use these new config variables not only in my php scripts but also within another htaccess file in a subdirectoryother htaccess filei have another htaccess file that resides in a subdirectory and its purpose is to enforce basic http authentication for that areathe problemthe authuserfile entry that points to the htpasswd file must be dynamic based on the environment variableswhat i needauthname admin areaauthtype basicauthuserfile base dir websamhtpasswdauthgroupfile devnullerrordocument 404 samerrorshtml limit get postrequire validuserlimitcurrent htaccessauthname admin areaauthtype basicauthuserfile wexamplecombetawebsamhtpasswdauthgroupfile devnullerrordocument 404 samerrorshtml limit get postrequire validuserlimitconfigphpi already know that this worksmy php config files could then get the config values like sophp dbdefaulthostname getenvdb host dbdefaultusername getenvdb user dbdefaultpassword getenvdb password dbdefaultdatabase getenvdb name,['php'] +599726,static variable lifetime and application pool recylcing i understand the lifetime of static variables in relation to applications consolewindows but i am not sure if i am understanding their lifetime when in the context of web apps aspnet mvc web api etcfrom what i understand when iis recycles the app pool static variables are reset to their types defaults integrals 0 reference types null etc but i am wondering if inline initializers are reinitialized after recycles or will the type defaults always be assigned regardlessexamples example 1static class staticrandom private static random rng new randomin the above would the static field rng be reinitialized to new random when called for the first time after a recycle or do i need to implement null checks before attempting to use the variable such as example 2static class staticrandom private static random rng null public static next if rng null rng new random return rngnext am i correct in assuming that after an iis recycle the rng variable in example 1 would be null until reinitialized like in example 2note i am fully aware of the thread safety issues in the above example it is just a quick example to illustrate my question in a realworld scenario of the above idea i would implement a proper locking pattern,"['c#', 'asp.net', '.net']" +599778,has private access error with generics i had a problem i could actually solve myself but i still do not understand why my original code does not work or if there is a more elegant solution than the one i found i am presenting a simplified version of my code hereconsider the following abstract superclass xpublic abstract class x private int i public void m1x x xi 1 m2x public abstract void m2x xwhen m1 is called we manipulate a private field of x of the instance passed and then we call m2 with that instancei have several subclasses of x they are all alike in the sense that they also declare private members which they manipulate in order to achieve that they always need to make a cast at the beginning of m2 here is one of thempublic class y extends x private int j public void m2x x y y y x yj 0 but i can guarantee that every call of m1 of an instance of a subclass of x will always have a parameter that is of the same type eg when i have an instance of y the parameter of the method m1 will always be another instance of ybecause of that guarantee i wanted to make the cast unnecessary by introducing generics this is how i want my subclasses to look likepublic class y extends xy private int j public void m2y y yj 0 how does the superclass x have to look like now my first try was thatpublic abstract class xt extends xt private int i public void m1t x xi 1 m2x public abstract void m2t xbut that does not work when i compile this i get the following errorxjava6 error i has private access in xthat is usually what you get you try to access the private members of another class obviously java does not recognise that t is always an instance of x as well although i used t extends x in the declarationi fixed x like thispublic abstract class xt extends xt private int i public void m1t x x y x yi 1 m2x public abstract void m2t xat least i am not using casts any more but why is this extra assignment necessary and why did not the original code work also i found it strange i had to use x and could not use xt,['java'] +599811,how to trigger broadcast receiver when gps is turn onoff public class bootreceiver extends broadcastreceiver override public void onreceivecontext context intent intent if intentgetactionmatchesandroidlocationproviders changed toastmaketextcontext in androidlocationproviders changed toastlength shortshow intent pushintent new intentcontext localserviceclass contextstartservicepushintent else toastmaketextcontext not in androidlocationproviders changed toastlength shortshow intent pushintent new intentcontext localserviceclass contextstartservicepushintent override public void onlocationchangedlocation arg0 in my app i need to trigger broadcast receiver when gps is turn onoff look into the matter and suggest best one to implement in app,['android'] +599832,how to compare i14 and a in c i fall into a surprising issue i loaded a text file in my application and i have some logic which compares the value having aand i realized that even if the texts are same the compare value is false consolewritelinei14equalsa returns false consolewritelineaequalsa return truein later line the character a is copy pastedany idea will be helpful,"['c#', '.net']" +599843,backuprestore from different database causing restore failed exclusive access could not be obtained i have a database a i have taken a backup of database a called aback i created a new database b now i right click and restore b from aback in the restore dialog i checked overwrite existing database and change the logicalfilename from cprogram filesmicrosoft sql servermssql11sqlserver2012mssqldataamdf to cprogram filesmicrosoft sql servermssql11sqlserver2012mssqldatabmdf and did the same with ldf file but i am getting exclusive access could not be obtained because the database is in usealso triedalter database b set single user with rollback immediatealso sp who2 there was no existing connection of b,['sql'] +599881,bootstrap how to make text wrap around an image on small devices i am just getting started with bootstrap below is a snapshot of my pagemy css issnippet imgwidth 150pxmaxwidth 100heightauto mediamaxwidth 767px snippet img width100px float right maxwidth 100px height auto marginleft 10px marginright 10px and here is my htmlh2about the venueh2div classmediabody snippet a classpullright hrefvenuephp img srcimagesvenuejpg altillustrationa pthis is the paragraph p divi want the image to be hanging like that on big screen however on small devices i would like to get the text to wrap around the image how can i do that any help would be appreciated,['css'] +599896,proper use of sub sub fragments with childfragmentmanager how do i properly use fragments in fragmentsmy simplified use case is following i have an activity with a layout fragment and this fragment theirself contains a sub fragment all fragments are added manually to their parents activity fragment subfragment now in my activitys oncreate i do followingif savedinstancestate null i create the fragment mmainfragment new mainfragment fragmenttransaction transaction getsupportfragmentmanagerbegintransaction transactionreplaceridfragment main mmainfragment transactioncommitelse i retrieve the fragment mmainfragment basefragment getsupportfragmentmanagerfindfragmentbyidridfragment mainand in my fragments oncreate i getcreate my subfragmentmsubfragment getchildfragmentmanagerfindfragmentbytagsubfragmentclassgetnameif msubfragment null msubfragment new subfragment getchildfragmentmanagerbegintransactionaddridfragment sub msubfragment subfragmentclassgetnamecommitproblemafter screen rotation my subfragment is added twice if i use the activitys fragmentmanager then it works but why does it not work with the childfragmentmanager of course the fragment is a new fragment but the activity is a new one as well so why does it work with the activitys fragmentmanager but not with the parent fragments onein a fragment i should use the fragments childfragmentmanager should not i,['android'] +599921,python string format with dict with integer keys i would like to use python strings format to act as a quick and dirty template however the dict that i would like to use has keys which are string representations of integers a simplified example followss hello there 5d 5 yousformatdthe above code throws the following errortraceback most recent call last file stdin line 1 in moduleindexerror tuple index out of rangeis it possible to do the above,['python'] +599943,laravel blank white screen my laravel site was working before i recently upgraded to apache 24 and php 557now i am getting a white blank screen when i go to laravelmydomaincom nothing in apache error logs routes and etc should be fine as it worked beforehtaccess is loading as i get a 500 when i insert an invalid line to varsiteslaravelpublichtaccessheres my htaccess cat varsiteslaravelpublichtaccessifmodule mod rewritec ifmodule mod negotiationc options multiviewsifmodulerewriteengine on redirect trailing slashesrewriterule 1 lr301 handle front controllerrewritecond request filename drewritecond request filename frewriterule indexphp lheres my virtual host directivedocumentroot varsiteslaravelpublicservername laravelmydomaincomdirectory varsiteslaravelpublic allowoverride all allow from all options indexes require all granteddirectoryand apachectl s usrlocalapache2binapachectl svirtualhost configuration is a namevirtualhost default server mydomaincom usrlocalapache2confextrahttpdvhostsconf25 port namevhost mydomaincom usrlocalapache2confextrahttpdvhostsconf25 port namevhost laravelmydomaincom usrlocalapache2confextrahttpd vhostsconf34serverroot usrlocalapache2main documentroot varwmain errorlog usrlocalapache2logserror logmutex rewritemap using defaultsmutex default dirusrlocalapache2logs mechanismdefaultpidfile usrlocalapache2logshttpdpiddefine dump vhostsdefine dump run cfguser namedaemon id1 not usedgroup namedaemon id1 not used,['php'] +599964,how does one determine the size of an unnamed struct i am looking for a way to determine the size of an unnamed struct because i want to explicitly calculate paddingi have set of structures that have a common a general layoutstruct packet uint8 t allocatordebuginfoalloc size constant across all structs optional uint8 t padding needs to be determined uint8 t headerheader size dependent on packet type uint8 t payloadpayload size constant across all structs i have the following requirementsi have written a special purpose allocator that has debugging information in front of the packeti want exchangeable header types while keeping the payload across all packet types layout compatible i am trying to calculate the header size as shown in the code belowtypedef union struct opaque smallheader struct opaque medheader struct opaque largeheader headersizesheadersizes penum small padding sizeofheadersizes sizeofpsmallheader unfortunately memory is tight and i am looking ways to avoid the global pointereditapparently trying to calculate an optional padding like this is a very bad idea this only works as long as you are aware of the fact that the biggest struct will have more padding than expected zeroenum large padding sizeof headersizes sizeof headersizes0largeheader struct largepacket uint8 t allocdebugalloc size uint8 t padding large padding will evaluate to 0 struct size 1 uint8 t payload payload size off by 1,['c'] +599972,optimizing access on numpy arrays for numba i recently stumbled upon numba and thought about replacing some homemade c extensions with more elegant autojitted python code unfortunately i was not happy when i tried a first quick benchmark it seems like numba is not doing much better than ordinary python here though i would have expected nearly clike performancefrom numba import jit autojit uint doubleimport numpy as npimport impimport logginglogginggetloggernumbacodegendebugsetlevellogginginfodef sum accumaccmap a res npzerosnpmaxaccmap 1 dtypeadtype for i in xrangelenaccmap resaccmapi ai return resautonumba sum accum autojitsum accumnumba sum accum jitdoubleint double localsdictiuintsum accumaccmap nprepeatnparange10 2nprandomshuffleaccmapaccmap nprepeataccmap 10a nprandomrandnaccmapsizeref sum accumaccmap aassert npallref numba sum accumaccmap aassert npallref autonumba sum accumaccmap atimeit sum accumaccmap atimeit autonumba sum accumaccmap atimeit numba sum accumaccmap aaccumarray impload sourceaccumarray pathtoaccumarraypyassert npallref accumarrayaccumaccmap atimeit accumarrayaccumaccmap athis gives on my machine10 loops best of 3 52 ms per loop10 loops best of 3 422 ms per loop10 loops best of 3 435 ms per loop10 loops best of 3 321 us per loopi am running the latest numba version from pypi 0110 any suggestions how to fix the code so it runs reasonably fast with numba,['python'] +600004,is it possible to justify text in pdfbox is there any function in pdfbox api to make text justified or we have to do it manually and if manually then how to justify text using javalogic behind it,['java'] +600032,css height not working if body has minheight i do not get my first child in the body to 100 height if the body has minheight specifiedhtml head style html height100 body minheight100 wrapper height100 minwidth1120px 250px each side content width is 870px maxwidth20px backgroundimageurlbgpng backgroundposition50 25px backgroundrepeatnorepeat backgroundsizecover style head body div idwrapper web content div bodyhtmlthis does not resize the wrapper to the height of the window when i remove the min and use height it will work but i have to have the content height variablei did find some other posts here on so and on google but they have just questions and no solution,"['html', 'css']" +600039,how does this color blending trick work i saw this java code that does a perfect 50 blend between two rgb8 colors extremely efficientlypublic static int blendrgbint a int b return a b a b 0x010101 1that is apparently equivalent to extracting and averaging the channels individually something like thispublic static int blendrgb int a int b int ar a 16 int br b 16 int ag a 8 0xff int bg b 8 0xff int ab a 0xff int bb b 0xff int cr ar br 1 int cg ag bg 1 int cb ab bb 1 return cr 16 cg 8 cbbut the first way is much more efficient my questions are how does this magic work what else can i do with it and are there more tricks similar to this,['java'] +600046,how to stop std thread safely i am developing a chat server and i have a questionhow to stop stdthread safelyit is very easy problem like thisthread tfunctjoinbut if func is has infinite loop join is not workingthis is my sourcevoid cserversocketacceptrunboostasioio service iosrv while true auto sock stdmake sharedboostasioiptcpsocketiosrv m acceptoracceptsock m socketlistpush backstdmake sharedcconnectionsocketthis sock and cserversocketcserversocket clogmanagerwritelogstopping server m acceptorclose m acceptorreset m acceptthreaddetach this is right clogmanagerwritelogserver stopedi am very wonderingplease help methank you,['c++'] +600048,use of generic delegates we know that action func and predicate are predefined generic delegates so as delegate they can point to functions with specified signaturei have following dataaccess scenario in which functr helps in avoiding a foreach loop in the calling method the approach 2 doesnat have looping here functr helped to avoid loopwhat are the other scenarios for generic delegates in which it can save lots of lines of codereferencesdynamically composing expression predicatesadvanced ccnet little wonders the predicate comparison and converter generic delegatesfunc vs action vs predicatewhat is func how and when is it usedhow can i pass in a func with a generic type parametercodeapproach 1public class mycommondal public static ienumerableidatarecord executequerywithtextcommandtypestring commandtext listsqlparameter commandparameters using sqlconnection connection new sqlconnectionconnectionstring using sqlcommand command new sqlcommand commandconnection connection commandcommandtype commandtypetext commandcommandtext commandtext commandcommandtimeout 0 commandparametersaddrangecommandparameterstoarray connectionopen using var rdr commandexecutereader while rdrread yield return rdr rdrclose public class mylogdal public listlogseveritytype getlogseveritiesfirstapproachlogseveritytype logseveritytype listsqlparameter commandparameters new listsqlparameter new sqlparameter parametername createddatetime value logseveritytypecreateddatetime sqldbtype sqldbtypedatetime string commandtext select from dbologseveritytype where createddatetime createddatetime var results mycommondalexecutequerywithtextcommandtypecommandtext commandparameters listlogseveritytype logseverities new listlogseveritytype loop foreach idatarecord rec in results logseveritytype objlogseveritytype logseveritytypelogseveritytypefactoryrec logseveritiesaddobjlogseveritytype return logseverities approach 2 public class mycommondal public static ienumerablet executequerygenericapproachtstring commandtext listsqlparameter commandparameters funcidatarecord t factorymethod action func and predicate are predefined generic delegates so as delegate they can point to functions with specified signature using sqlconnection connection new sqlconnectionconnectionstring using sqlcommand command new sqlcommand commandconnection connection commandcommandtype commandtypetext commandcommandtext commandtext commandcommandtimeout 0 commandparametersaddrangecommandparameterstoarray connectionopen using var rdr commandexecutereader while rdrread yield return factorymethodrdr rdrclose public class mylogdal public listlogseveritytype getlogseveritiessecondapproachlogseveritytype logseveritytype listsqlparameter commandparameters new listsqlparameter new sqlparameter parametername createddatetime value logseveritytypecreateddatetime sqldbtype sqldbtypedatetime string commandtext select from dbologseveritytype where createddatetime createddatetime var results mycommondalexecutequerywithtextcommandtypecommandtext commandparameters ienumerablelogseveritytype logseverities mycommondalexecutequerygenericapproachlogseveritytypecommandtext commandparameters logseveritytypelogseveritytypefactory foreach idatarecord rec in results logseveritytype objlogseveritytype logseveritytypelogseveritytypefactoryrec logseveritiesaddobjlogseveritytype return logseveritiestolist other code required public class logseveritytype public int logseveritytypeid get set public string name get set public string description get set public datetime createddatetime get set public static logseveritytype logseveritytypefactoryidatarecord record return new logseveritytype logseveritytypeid intrecord0 name string record1 description stringrecord2 createddatetime datetime record3 static void mainstring args mylogdal logdal new mylogdal logseveritytype logseveritytype new logseveritytype logseveritytypecreateddatetime converttodatetime1120 listlogseveritytype logseverities logdalgetlogseveritiessecondapproachlogseveritytype,['c#'] +600120,signal handling and sigemptyset could anyone please explain in a really easy way to understand what sigemptyset does why is it useful i have read a bunch of definitions but i just do not understand from what i gather it tracks the signals that are being used for blocking purposes i am not really sure i understand why that would be useful is it so we do not get that specific signal recursively basic example where sigemptyset is usedinclude signalhinclude stdiohinclude unistdhint mainstruct sigaction actsigemptysetactsa maskactsa handlerfunction nameactsa flags0sigactionsigint act 0,['c'] +600151,googleapple push notification service apnsgcm i am trying to create application for android and ios and i watn to use push notification on both the application i am going to have a server app that will be sending the notificationwhat i am trying to figure out is how can we store the device of the user so i will know which service need to be used apns or gcm one of the directions is to get the phone type to be set by the app and store this information on the server side but what happens if the user changes his phone from ios to android need to involve data storage of the user and collect information for every user not covers scenario when user has android tablet and ios phonemake it more generic and thispatch the notification to both services apns and gcm at the same time one of them will return errorwould love to hear what is the best practice for such scenarios,"['android', 'ios']" +600293,add html5 placeholder text to a textbox net i have a standard inputasptextbox typetext runatserver idtxtsearchterm i would like to have this render with a dynamic html5 placeholder something likecode behindtxtsearchtermplaceholder search sitenameso that it outputs the following htmlinput typetext runatserver idtxtsearchterm placeholdersearch site 1 where sitename site 1txtsearchtermplaceholder is not a property i have it set to text and then run javascript to showhide on focus but i would much rather just use the html5 placeholder value how can i render thisplease no jsclient side solutions,"['asp.net', '.net']" +600306,proper use of contentavailable in ios 7 push notifications i am just looking for some feedback on my thought process surrounding ios 7 and the contentavailable key value in a push notification payload scenarioi force shut down the application according to apple because i have done this i will no longer receive any notifications that contain the key value contentavailable in their payload this means that the alert does not show at all basically nothing happens no sounds no alert message no badge incrementtheorybecause of the above scenario it seems as if youd want to send two push notifications a push notification with just your alertbadge and sound values so that the user sees a notification related to the update irregardless of the application statea push notification with just the contentavailable key value if the app is in a state where it can accept this it does and your background task is performed in the case it cannot accept it the user still receives a visual audible notification from the first push notificationquestionis this how apple intends the silent background notifications to be executed i do not really see another way that you could implement this,['ios'] +600326,whats the difference between python 33 and 33m whats the difference between python 33 and 33mi am using ubuntu 1304 raring and on my system i have python27 and python33 i know the differences between 2 and 3but i also have installed python33m and it is not a symlink to 33 so what does the m stand for,['python'] +600351,angularjs routeprovider route is executed before resolve completes i would like the routeresolve methods to fire before the actual route code is run unfortunately in the code below prime gets called but it is called asynchronously and the route code gets called before the prime completes i thought the resolve methods of a route was suppose to complete before the route is loaded function use strictvar app angularmoduleapp collect the routesappconstantroutes getroutes configure the routes and route resolversappconfigrouteprovider routes routeconfiguratorfunction routeconfiguratorrouteprovider routes routesforeachfunction r setrouterurl rconfig routeproviderotherwise redirectto function setrouteurl definition set resolvers for all of the routes by extending any existing resolvers or creating a new one definitionresolve angularextenddefinitionresolve prime prime routeproviderwhenurl definition return routeprovider primeinject datacontextfunction primedc dcprime define the routes function getroutes return url config templateurl appdashboarddashboardhtml title dashboard settings nav 1 content i classicondashboardi dashboard url sessions config title admin templateurl appsessionssessionshtml settings nav 2 content i classiconcalendari sessions url speakers config title speakers templateurl appspeakersspeakershtml settings nav 3 content i classiconuseri speakers url attendees config title attendees templateurl appattendeesattendeeshtml settings nav 4 content i classicongroupi attendees,['javascript'] +600515,newrelic transaction traces in a ruby gem i am developing a ruby gem that i would like to add newrelic monitoring to the gem is used in a script that is run as a daemon and monitored by bluepill i followed monitoring ruby background processes and daemons to get started i confirmed the gem is establishing a connection with newrelic as the application shows up in my portal there however there is no transaction traces or any metrics breakdown of the code being invokedheres the entry point of my gem as i tried to manually start the agent around the invoking methodrequire fmsparserversionrequire fmsparsercorerequire fmsparserenvrequire mongoidenvnrconfig filedirname file newrelicymlrequire newrelic rpmmodule fms module parser def selfprepare parsefilename newrelicagentmanual start mongoidloadfiledirname file mongoidyml development coreprepare parsefilename newrelicagentshutdown end endendi also tried adding this into the module class self include newrelicagentinstrumentationcontrollerinstrumentation add transaction tracer prepare parse category task endi am not entirely sure what else i can do i confirmed the agent is able to communicate with the server and transaction traces are enabled nothing shows up in the background application tab either this is the most useful information i have gotten from the agent log so far122313 212103 0 apivm 7819 info environment development122313 212103 0 apivm 7819 info no known thispatcher detected122313 212103 0 apivm 7819 info application myapp122313 212103 0 apivm 7819 info installing net instrumentation122313 212103 0 apivm 7819 info finished instrumentation122313 212104 0 apivm 7819 info reporting to masked account number122313 221206 0 apivm 7819 info starting the new relic agent in development environment122313 221206 0 apivm 7819 info to prevent agent startup add a newrelic enablefalse environment variable or modify the development section of your newrelicyml122313 221206 0 apivm 7819 info reading configuration from varlibgems191gemsfmsparser006libfmsnewrelicyml122313 221206 0 apivm 7819 info starting agent shutdownthe only thing that is really concerning here is no known thispatcher detectedis what i am trying to do possible,['ruby'] +600611,why use the transient keyword in java i have an issue related to the transient keywords use before the private modifier in java variable declarationtransient private resourcebundle pageresourcebundle when i googled it i found these docs below but they are talking about serialized actually my class does not implement any serializedfrom docs why does java have transient variablesmy class looks like this public class loginviewmodel extends abstractviewmodel transient private resourcebundle pageresourcebundle aftercompose public void aftercomposecontextparamcontexttypeview component view initializeloginvalues boolean timeout booleanutilstobooleangethttpservletrequestgetparametertimeout if timeout messageboxshowpageresourcebundlegettextmsg session has expired please login pageresourcebundlegettextlabel alert messageboxok messageboxerror viewgetpagesettitlecsdclicencegetgetapplicationname i have some questions1why use the transient keyword before a private variable2what is the purpose of using this keyword,['java'] +600620,qsgcontext missing on qt android i am developing an application for android the development is done on linux using qt creator with c and qmlas i pulled off my hairs during the whole day and that thing does not seems too obvious i wonder if anybody could have any clue about the error the debugger flushed outcould not load shared library symbols for 85 libraries eg systembinlinkerwqt 24399 kernelqcoreapplicationcpp418 qcoreapplicationprivateqcoreapplicationprivateint char uint warning qapplication was not created in the main threaddlibegl 24399 loaded systemlibegllibegl tegrasodlibegl 24399 loaded systemlibegllibglesv1 cm tegrasodlibegl 24399 loaded systemlibegllibglesv2 tegrasodopenglrenderer24399 enabling debug mode 0ichoreographer24399 skipped 35 frames the application may be doing too much work on its main threaddqt 24399 qtcpserverconnectioncpp173 void qtcpserverconnectionlisten qml debugger waiting for connection on port 48309ddalvikvm24399 gc concurrent freed 396k 6 free 7689k8152k paused 4ms2ms total 56mswqt 24399 scenegraphqsgcontextcpp440 virtual void qsgrendercontextinitializeqopenglcontext qsgcontextinitialize stencil buffer support missing expect rendering errorsis it a matter of some library missing or the qt creator is simply some how not properly linking the libraries,['c++'] +600643,what is the pros and cons between enum and enumbased class implementation in java i have recently come across an article thiscussing the use of an enumbased class implementation in c which is quite impressive the second one here is in java however my colleagues suggest me to use enum insteadcould anyone point out any pros and cons using each of them and when to use it,['java'] +600717,code contracts for c does not work when contractfor is on a different assembly i am trying to define code contracts for an interface using contractclass and contractclassfor it works fine when everything is in the same assembly but if i put the interface definition and its respective contract class in a different assembly then the concrete class implementation it does not work anymorefor example this code worksnamespace dummyproject contractclasstypeofaccountcontracts public interface iaccount void depositdouble amount contractclassfortypeofiaccount internal abstract class accountcontracts iaccount void iaccountdepositdouble amount contractrequiresamount 0 internal class account iaccount public void depositdouble amount consolewritelineamount class program static void mainstring args account account new account contractrequires will be checked below accountdeposit1 now if i have a separate project with the followingnamespace separateassembly contractclasstypeofseparateassemblyaccountcontracts public interface iseparateassemblyaccount void depositdouble amount contractclassfortypeofiseparateassemblyaccount internal abstract class separateassemblyaccountcontracts iseparateassemblyaccount void iseparateassemblyaccountdepositdouble amount contractrequiresamount 0 and then in the main project different assembly from the above if i writenamespace dummyproject internal class accountfromseparateassembly iseparateassemblyaccount public void depositdouble amount consolewritelineamount class program static void mainstring args iseparateassemblyaccount accountfromseparateassembly new accountfromseparateassembly neither of the two statements below will work contractrequires will be ignored accountfromseparateassemblydeposit1 accountfromseparateassemblyaccountfromseparateassemblydeposit1 then the contractrequires is no longer checked in the deposit methodany ideas on this please thanks a lot,"['c#', '.net']" +600798,looking for a quick way to speed up my code i am looking for a way to speed up my code i managed to speed up most parts of my code reducing runtime to about 10 hours but it is still not fast enough and since i am running out of time i am looking for a quick way to optimize my code an exampletext pdread csvospathjoindirtextcsvchunksize 50new text nparraychunk2 for chunk in textnew text listitertoolschainfrom iterablenew textin the code above i read in about 6 million rows of text documents in chunks and flatten them this code takes about 34 hours to execute this is the main bottleneck of my program edit i realized that i was not very clear on what the main issue was the flattening is the part which takes the most amount of timealso this part of my program takes a long time train dict dictiziptextlabels result train dicttestsample if testsample in train dict else predictionssample for sample in xrangelenpredictionsthe code above first zips the text documents with their corresponding labels this a machine learning task with the train dict being the training set earlier in the program i generated predictions on a test set there are duplicates between my train and test set so i need to find those duplicates therefore i need to iterate over my test set row by row 2 million rows in total when i find a duplicate i actually do not want to use the predicted label but the label from the duplicate in the train dict i assign the result of this iteration to the variable result in the above codei heard there are various libraries in python that could speed up parts of your code but i do not know which of those could do the job and right know i do not have the time to investigate this that is why i need someone to point me in the right direction is there a way with which i could speed the code snippets above up edit2i have investigated again and it is definitely a memory issue i tried to read the file in a row by row manner and after a while the speed declined dramatically furthermore my ram usage is nearly 100 and pythons thisk usage increased sharply how can i decrease the memory footprint or should i find a way to make sure that i do not hold everything into memoryedit3as memory is the main issue of my problems i will give an outline of a part of my program i have dropped the predictions for the time being which reduced the complexity of my program significantly instead i insert a standard sample for every non duplicate in my test setimport numpy as npimport pandas as pdimport itertoolsimport ostrain pdread csvospathjoindirtraincsvchunksize 50train 2 pdread csvospathjoindirtraincsvchunksize 50test pdread csvospathjoindirtestcsv chunksize 80sample listnparraypdread csvospathjoindirsamplescsv2this file is only 70mbsample sample1test set nparraychunk2 for chunk in testtest set listitertoolschainfrom iterabletest settrain set nparraychunk2 for chunk in traintrain set listitertoolschainfrom iterabletrain setlabels nparraychunk3 for chunk in train 2labels listitertoolschainfrom iterablelabelszipping train and labelstrain dict dictiziptrainlabelsfinding duplicatesresults train dicttestitem if testitem in train dict else sample for item in xrangelentestalthough this is not my entire program this is the part of my code that needs optimization as you can see i am only using three important modules in this part pandas numpy and itertools the memory issues arise when flattening train set and test set the only thing i am doing is reading in the files getting the necessary parts zipping the train documents with the corresponding labels in a dictionary and then search for duplicatesedit 4as requested i will give an explanation of my data sets my traincsv contains 4 columns the first columns contain ids for every sample the second column contains titles and the third column contains text body samplesvarying from 100700 words the fourth column contains category labels testcsv contains only the ids and text bodies and titles the columns are separated by commas,['python'] +600879,java happensbefore and thread safety suppose i have a class which wraps a hashmap as followspublic final class myclass private final mapstring string map called by thread1 public myclass int size thismap new hashmapstring string size only ever called by thread2 public final string put string key string val return mapput key value only ever called by thread2 public final string get string key return mapget key only ever called by thread2 public final void printmap format and print the contents of the map this class is initialized via thread1however the put get printmap and other operations are only ever called by thread2am i correct in understanding that this class is thread safe assince the reference to the map is declared final all other threads would see the initial state of the map happensbefore is establishedsince putgetprintmapetc are only ever called by thread2 there is no need for mutualexclusionthank you,['java'] +600883,unable to format default mysql datetime my dates come out of the database looking like this 20131121 174320i am trying to user angulars date filter to turn them into something prettier butobjectedcreated dateshortdateor objectedcreated dateyjust spits out the original datetime string 20131121 174320 there are no errors what am i doing wrongupdatei see that mysqls default datetime is incompatible with what angulars data filter expects i am attempting to convert it on the fly like this but it is throwing errorsli ngrepeatresult in data new dateresultjobcreatedtoisostring dateshortdatelii suspect i cannot instantiate the date class in the way i am trying the error is a parsesyntax errorupdatethanks to m59s help i got it working with a few minor adjustmentshtml html ngappmyappobjectcreated datetoiso dateshortdatejsvar myapp angularmodulemyappmyappfilterdatetoiso function return functioninput input new dateinputtoisostring return input this custom filter converts the default mysql datetime into the format that the date filter expects so i send it throw one then another and voila,"['javascript', 'mysql']" +600901,ruby keyword arguments in c extensions how does one handle ruby 200 keyword arguments from a c extensionbackgrounddef examplename bob hat color red puts name has a hat color hatendexample bob has a red hatexamplename joe hat color blue joe has a blue hatkeyword arguments like the above are quite useful when handling methods that have a lot of different call sequences or options i have one such method in a c extension a blit method that handles most of the opengl drawing in my project and i am wondering how i might have the method handle keyword arguments from ruby ideasbased on some research i have done i think that such handling might be done through the option on the rb scan args c function however i have been unable to find any information on how to use it to do so,"['c', 'ruby']" +600931,bison precedence is useless it does not work i have declared such precedence for bison left left recursive rules for arithmeticexp exp binary op exp literal exp id binary op i have an arithmetic expression 10 3 5my program calculates the sum and it is 80 i still do not know why precedence does not work,['c'] +600932,controlling execution order of unit tests in visual studio okay i am done searching for good information on thisi have a series of unit tests that call a static class which once initialized sets properties that cannot or i do not wish to changemy problem is i cannot enforce a set order for the tests to run if i could i could run them in such a way as the static properties would be set in a reliable way and i could assert on them but unfortunately the microsoftvisualstudiotesttoolsunittesting framework just runs them in a seemingly random orderso i found this which says in the remarks section this attribute is not used by the test system it is provided to the user for custom purposes huh what good is it then do they expect me to write my own testing wrapper to take advantage of this fabulous attribute of which i could easily write myself if i wanted to go to that level of effortso enough of the rant bottom line is there a way to control the order my unit tests run testmethodpriority0etc does not seem to work which makes sense since microsoft says it would notalso please no comments about violating isolation the testclass isolates what i am testing not the individual testmethods regardless each test can be run independently just fine they just cannot be run together in a random order as there is no way to tear down the static classoh i also know about ordered test,['c#'] +600968,ews managed api breaks appointment html message body on update i am using ews java 12 although 20 in c shows the exact same issues and exchange 2010 sp3 so a particular bug in sp2 prior to rollup 3 regarding message bodies is not the problemlong story short ews exchange pain using ews in exchange you can create an appointment you can specify that the message body of the appointment be html and give it a bunch of html to go with it this will do some kind of html rtf conversion that wrecks the html when you view it in an outlook desktop or web client okay well we can tailor the html to something that does not get eaten in the process and still looks decentexcept that when you update the appointment with a change to the message body it really eats the html formatting it does not matter if it is the same html you gave it when it was created the second save will destroy it leaving little more than bold text line breaks and tabs it is as if it is either thisplaying the plain text with a few small pieces of formatting or it is thisplaying a very strippeddown rtf from converted html whats really maddening is that it only happens once you update the bodythe thing is i have taken a look at these appointments and related meetingrequests which are mulched the same way in both mfcmapi and in ews by checking the extended properties when the appointment is first created only the rtf body is populated the plain text and html bodies are null the rtf is in sync and the native body value is 2 which means it should thisplay rtf okay that makes senseon update all three body types are present the rtf is out of sync the native body value is 3 which means that it should thisplay html i checked in mfcmapi both the plain text body and rtf body show out of memory errors but opening the property will show it correctly the html body is present there is zero reason that this should be happening according to the documentation the best body algorithm states that if the native body property is populated then that is what will be used and it is all done well that is obviously not happening if it is not getting that value for some reason then it will go through a conditional chain well the conditional chain shows that the html body should be thisplayed in this case mfcmapi agrees when the item exported as it shows the native body to be the html body owa will thisplay it just fine but outlook 20102013 nopei am at my wit is end here i cannot get desktop outlook to thisplay the body properly no matter what i do it seems to be something fundamentally broken serverside but there are no known bugs listed aside from the aforementioned sp2 prerollup 3 issue which is not the case here and i cannot find any documentation that explains why the update breaks it so badly the best i have been able to do is set the pidtagbodyhtml directly on creation and have it broken from the start at least that is consistentedit i have implemented the rtf decompression algorithm to peek inside sure enough the rtf message body for a new appointment and the rtf message body for an updated appointment in which the body was updated with a virtually identical one are very different exchange is following two separate code paths serverside and it is breaking the body format the only possible solution i see is to also implement the compression and formatting algorithms and manually construct a valid rtf body in the client which is not exactly a small feat,['html'] +600991,asmtrap on 64bit ios devices in my homegrown assert macro i have been using asmtrap on ios devices or asmint3 on ios simulators to break in the debugger however in 64bit builds for devices i get an unrecognized instruction mnemonic for the trap instruction is there an equivalent for arm64alternatives like builtin trap or raisesigint do work but have some behavior i do not like the former would not let you continue past the break and the latter is a function so youre always one step below where you need to be in the stack when you break,['ios'] +601012,could not find a part of the path error while creating mutex i am baffled by this can someone tell me why when i callusing mutex mtx new mutexfalse stridi get this exceptioncould not find a part of the pathif strid is set to something like localhostsqlexpressmyname2,"['c#', '.net']" +601023,break promise chain and call a function based on the step in the chain where it is broken rejected updateto help future viewers of this post i created this demo of plumas answer questionmy goal seems fairly straightforward step1 thenfunction return step2 function steperror1 return qreject thenfunction function steperror2 function stepn var deferred qdefer fail on step 1 n 1 deferredreject deferredresolve return deferredpromise function steperrorn consolelogn the problem here is that if i fail on step 1 both steperror1 and steperror2 are fired if i do not return qreject then steperror2 would not be fired but step2 will which i understand i have accomplished everything except what i am trying to dohow do i write promises so that i can call a function on rejection without calling all of the functions in the error chain or is there another way to accomplish thisheres a live demo so youve got something work withupdatei kind of have solved it here i am catching the error at the end of the chain and passing the data to rejectdata so that i will know what issue to handle in the error function this actually does not meet my requirements because i do not want to depend on the data it would be lame but in my case it would be cleaner to pass an error callback to the function rather than to depend on the returned data to determine what to dolive demo here clickstep1 thenfunction return step2 thenfunction return step3 thenfalse functionx steperrorx function stepn consolelogstep n var deferred qdefer n 1 deferredrejectn deferredresolven return deferredpromise function steperrorn consolelogerror n,['javascript'] +601083,in c what categories lvalue rvalue xvalue etc can expressions that produce temporaries of class type fall into here is some example codeinclude iostreamclass foopublic explicit fooint x datax foo operator data 1 return this void get addr return voidthis friend foo operator const foo lhs const foo rhs friend stdostream operator stdostream os const foo fprivate int datastdostream operator stdostream os const foo f return os fdatafoo operator const foo lhs const foo rhs return foolhsdata rhsdatavoid barfoo f stdcout barlvalue ref stdendlvoid barconst foo f stdcout barconst lvalue ref stdendlvoid barfoo f stdcout barrvalue ref stdendlint main getting the identity of the object stdcout foo5get addr stdendl can write foo5 by overloading overload resolution barfoo5 prints rvalue ref default copy assignment stdcout foo78 foo86 stdendl prints 86 mutating operations stdcout foo5 stdendl prints 6 more mutating operations stdcout foo78 foo86 stdendl prints 165 overload resolution barfoo78 foo86 prints rvalue refare expressions like foo5 prvalues or general rvalues does the fact that i can call get addr on these expressions mean that they have identity or does the fact that i cannot apply the default operator i mean nonoverloaded mean that they do not have identity and are therefore prvaluesis it also fair to say that mutability of the produced value via the expression that produced it is orthogonal to this valueclassification,['c++'] +601104,angularjs ngtouch 300ms delay this plunkr has 2 links the one on the left side is using the ngclick directive with the on angulartouch module inserted as said in the angular touch module description for ngclick the ngclick link should not have a 300ms delay but if you test it on mobile devices this is still the caseso is plunkr preventing the correct functionality because its executed in an iframe or something like that or is it required to insert fastclickjs into the project for the directive to work correctly i do not get it please helpexample edit the example in the angularjs docs ist not working either they did not even inserted the angulartouch module,['javascript'] +601131,which ide for scientific computing and plotting in python i am currently using r for all my scientific computing and plotting but i would like to explore python i have been using rstudio as an ide for r which as an ide fulfills 100 of my need for scientific computing number crunching data analysis and visualizations is there something similar for python basically syntax highlighting code completion smart indentation code execution directly from the source editor plotting within the ide and version control git,['python'] +601142,how to configure second level cache in hibernate 43 i have read post related with this but not get any answer working for mei am configuring second level cache in hibernate v43 and i have used mysql 50i have written following elements in hibernatecfgxmlproperty namehibernatecacheuse second level cachetruepropertyproperty namehibernatecacheregionfactory classorghibernatecacheehcacheehcacheregionfactorypropertyi have annotated my entity class for cache as followsentity cacheusage cacheconcurrencystrategyread onlypublic class employee following exception is shown when runinfo h0397 using astquerytranslatorfactoryexception in thread main orghibernateservicespiserviceexception unable to create requested service orghibernatecachespiregionfactory at orghibernateserviceinternalabstractserviceregistryimplcreateserviceabstractserviceregistryimpljava233 at orghibernateserviceinternalabstractserviceregistryimplinitializeserviceabstractserviceregistryimpljava197 at orghibernateserviceinternalabstractserviceregistryimplgetserviceabstractserviceregistryimpljava178 at orghibernatecfgsettingsfactorybuildsettingssettingsfactoryjava295 at orghibernatecfgconfigurationbuildsettingsinternalconfigurationjava2442 at orghibernatecfgconfigurationbuildsettingsconfigurationjava2438 at orghibernatecfgconfigurationbuildsessionfactoryconfigurationjava1855 at comexamplehibernatehibernate4mainmainhibernate4mainjava32caused by orghibernatehibernateexception could not instantiate regionfactory orghibernatecacheehcacheehcacheregionfactory at orghibernatecacheinternalregionfactoryinitiatorinitiateserviceregionfactoryinitiatorjava101 at orghibernatecacheinternalregionfactoryinitiatorinitiateserviceregionfactoryinitiatorjava46 at orghibernatebootregistryinternalstandardserviceregistryimplinitiateservicestandardserviceregistryimpljava83 at orghibernateserviceinternalabstractserviceregistryimplcreateserviceabstractserviceregistryimpljava223 7 morecaused by orghibernatebootregistryselectorspistrategyselectionexception unable to resolve name orghibernatecacheehcacheehcacheregionfactory as strategy orghibernatecachespiregionfactory at orghibernatebootregistryselectorinternalstrategyselectorimplselectstrategyimplementorstrategyselectorimpljava128 at orghibernatecacheinternalregionfactoryinitiatorinitiateserviceregionfactoryinitiatorjava87 10 morei have seen than there are different cache providers for hibernate v3 like ehcacheprovoider all are in orghibernatecache packagebut for hibernate 43 there are only 3 classes as regionfactoryclass and other two are of exception1 what is wrong with above code2 what are major changes made for second level cache configuration in hibernate 43,['java'] +601190,yeoman call subgenerator with usersupplied arguments i am writing my first yeoman generator which prompts the user for various inputs and conditionally creates files based on their responses i need to be able to call a subroutine could be a yeoman subgenerator based on user input and pass arguments to it the reason i want to use named functions which are not automatically run is that sometimes the users response should invoke a number of functions combined and sometimes the function should be run alonewhat i have triedi figured subgenerators were the way to go since i am creating sets of files only if the user requests them but i am having trouble calling them conditionally and passing them the usersupplied input i have tried using hookfor but i get the assertion error hookfor must be used within the constructor only because i do not want it to be run by default i am calling the subgenerator from my thispromptprompts function propsthe questionhow do i call a routine only if the user requests it via a prompt and pass that routine some usersupplied informationif youre kind enough to answer please do not assume that i have tried something obvious,['javascript'] +601239,embed multiple view controller in one window i want to have a view which contains more than one view see the below imageas you see pagecontroller controls page navigation and provide before and after viewcontroller pagepagecontentcontroller thisplays text and process themsoundplayer manages playing related sound i can have all of them in one controller but my controller must do a lot of tasks and managing it will be hard task as it thisobey light view controller and decrease its cohesionso i wanted to know how can i accomplish thisplease explain in details,"['ios', 'objective-c']" +601285,cors issue getting error no accesscontrolalloworigin header is present when it actually is i doubt the backend serving my app is important but if you care i am using rackcors with a rails 40 appusing jquery i send my app a patch request like soajax url type patch data something something else when i trigger this call from chrome i see a successful options request go out which returns these headers from my serveraccesscontrolallowcredentialstrueaccesscontrolallowheadersaccept contenttypeaccesscontrolallowmethodsget put patch optionsaccesscontrolalloworigin accesscontrolexposeheadersaccesscontrolmaxage15then i see a patch request go out which throws this errorxmlhttprequest cannot load no accesscontrolalloworigin header is present on the requested resource origin is therefore not allowed access i have tried switching from patch to put with the same resultsthis does not make any sense to me whats going onupdate my configapplicationrbi thought the headers told the whole story but since people are confused heres my configapplicationrb file which is how the rackcors plugin for rails is configuredconfigmiddlewareuse rackcors do allow do origins resource headers any methods get put patch options max age 15 endend,"['javascript', 'jquery', 'ruby-on-rails']" +601324,how does one implement a container which exposes multiple ranges i have a container which among other things exposes a string buffer and the upper case version of that string buffer well it is not just upper case but it is similar in concept i want to allow a caller to do something similar tocontainer cexampleauto const iter cbegin 2stdprintfcn iterget source prints astdprintfcn iterget upper prints aitersetxstdputscget prints exxmplestdputscget upper prints exxmplethe problem is the proxy type with the member functions get source get upper etc has no obvious place it can be stored and an iterator is required to return a reference to something not a value vectorbool has a similar problemalternately i could expose some kind of shell container or range or expose completely separate iterator beginend functions does anyone have experience doing something like this and know what works well,['c++'] +601343,difference between use and run in rack whats the difference between the use and run methods in rackup files it seems run is always at the end of configru but it seems as if you should just be able to use use enlightening resources would also be very much appreciated,['ruby'] +601404,unusual shape of a textarea usually textareas are rectangular or square like this but i want a customshaped textarea like this for example how is this possible,"['javascript', 'jquery', 'html', 'css']" +601412,is it possible to create custom operators in javascript during the math classes we learned how to define new operators for examplea a x a y x 2ythis defines a law for any real numbers x and y x a y is x 2yexample 2 a 2 2 4 6is possible to define operators like this in javascript i know that a function would do the jobfunction foo x y return x 2 y but i would like to have the following syntaxvar y 2 a 2 returns 6instead of thisvar y foo2 2which is the closest solution to this question,['javascript'] +601416,setting up a value for a variable name in thymeleaf i am new to thymeleaf and am converting ma web page from jsp to thymeleaf i have a strut tag like thiscset varsomevariable valuesomevaluewhich that the variable can be used anywhere in jsp is there any such alternatives for this in thymeleaf,['java'] +601426,implementing monads in javascript now that nodejs supports ecmascript harmony generators we can write monadic code succinctly ala do blocks in haskellfunction monadunit bind return function f return function var g fapplythis arguments return typeofg generator send unitg function sendvalue var result gnextvalue if resultdone return unitresultvalue else return bindresultvalue send function typeofvalue return objectprototypetostringcallvalueslice8 1in the code above monad is a function which can be used to create deterministic monads likevar maybe monadfunction a return just a function m f return m null null fmjustyou may now use maybe as followsvar readzip maybefunction a b var a yield readlista var b yield readlistb return zipa bthe above function readzip takes two strings converts them into lists and then zips them if there is an error then it immediately returns null it depends upon the following functionfunction readliststring try var value jsonparsestring return value instanceof array just value null catch error return null we test it to check whether it works as it is expected toconsolelogreadzip1234 ab 1a2b3cconsolelogreadziphello ab nullconsolelogreadzip1234 world nullsimilarly we can create any other deterministic monad for example my favorite the cont monadvar cont monadfunction a return function k return ka function m k return function c return mfunction a return kac now we can use cont to create functions in continuation passing style succinctlyvar fib contfunction n switch n case 0 return 0 case 1 return 1 default var x yield fibn 1 var y yield fibn 2 return x y you can use the fib function as followsfib10function a consoleloga 55unfortunately monad only works for deterministic monads it does not works for nondeterministic monads like the list monad because you can only resume a generator from a specific position onceso my question is this is there any other way to implement nondeterministic monads like the list monad succinctly in javascript,['javascript'] +601514,static constructor creation monocecil i have been having some issues with static constructors with my project i need to add a static constructor to the type in order to call my resource decryption methodbelow in the gif you will see the issue i run intoi will also include the code snippetcode for creating cctormethoddefinition method new methoddefinition cctor monocecilmethodattributesprivate monocecilmethodattributesstatic monocecilmethodattributeshidebysig monocecilmethodattributesspecialname monocecilmethodattributesrtspecialname modimporttypeofvoid i have also tried changing the attributes to the exact same as yanos it somehow never works by works i mean detect it as a static constructor in dotnet resolverheres some more information about real outcome and expected resulti do not have an resolveeventhandler attached to my entrypoint i have it attached to the application which is being obfuscated and it is located in the types static constructor which is executed before even the entrypoint is calledapplication resources have been encrypted with aes and are not recognised as valid resources by dotnet resolver or other decompilers i am simply asking why the event is not being triggered as it should be triggered when a resource is invalid or missing as you can see in the example a messagebox should pop up before the application is launched but it never does string encryption encrypts the strings so its a bit hard to see theres a string thereany help is appreciated,['c#'] +601518,javafx why does stagesetresizablefalse cause additional margins this small javafx test applicationimport javafxapplicationapplicationimport javafxscenesceneimport javafxscenelayoutborderpaneimport javafxscenepaintcolorimport javafxsceneshaperectangleimport javafxstagestagepublic class applicationwithnonresizablestage extends application public static void mainfinal string args launchargs override public void startfinal stage primarystage throws exception final rectangle rectangle new rectangle200 100 colorpowderblue final borderpane pane new borderpanerectangle final scene scene new scenepane primarystagesetscenescene primarystagesetresizablefalse primarystageshow produce a window with unwanted paddingremoving the call primarystagesetresizablefalse also removes the effectwhat is going wrong,['java'] +601539,tagging like twitter and facebook using the select2 plugin i am using the following code to simply search and tag friends onto a textfield that i then pass to an ajax post as you see from my image i can only allow users to tag friends one after another instead of limiting users to only type friends names for tagging i want to emulate facebook and twitter and allow users to type a status update then when they type invoke select2 to do an ajax call to search for friends heres my current code tag friendsselect2 formatresult peopleformatresult formatselection peopleformatselection tags true tokenseparators multiple true placeholder tag your friends minimuminputlength1 ajax type post url domainfriendstag datatype json data functionterm page return q term results functiondata page return results data function peopleformatresultpeople var html table classpeopleresultadotr html td classtaggin imageimg srcpeopleimagetd html td classpeopleinfo html peoplename br html tdtrtable return html function peopleformatselectionpeople return peoplename i use this in my ajax post afterwards to use the selected ids returnedvar tagged friends tag friendsselect2valheres how it currently looks i have worked a week without any progress and i need it to look like the following image the tagging would be initiated when the user types also any ideas how i could grab the user ids after someone has tagged some friends i have hit a steel wall any help would be greatly appreciated thank you,"['javascript', 'jquery']" +601550,does the equals sign make a difference in brace initialization here are two ways to initialize a variable in c11t a somethingt a somethingi tested these two in all scenarios i could think of and i failed to notice a difference this answer suggests that there is a subtle difference between the twofor variables i do not pay much attention between the t t init or t t init styles i find the difference to be minor and will at worst only result in a helpful compiler message about misusing an explicit constructorso is there any difference between these two,['c++'] +601586,nosuchmethoderror in javaxpersistencetableindexesljavaxpersistenceindex i have a play framework application and i was using hibernate 425final which is retrieved via the maven dependency manager i decided to upgrade to hibernate 430final recompile my application successfully and ran iti got the exception below and have not been able to figure out why i downgraded back to 425 and this issue did not occur i then tried upgrading hibernate with each final release after 425 that is i went from 425final to 426final to 427final to 428final and then to 43final the issue does not occur until i upgrade to 430finaljava version informationjava version 170 45javatm se runtime environment build 170 45b18java hotspottm 64bit server vm build 2445b08 mixed modeand exceptionplayapiunexpectedexception unexpected exceptionnosuchmethoderror javaxpersistencetableindexesljavaxpersistenceindex at playcorereloadableapplicationanonfunget1anonfunapply1anonfun1applyapplicationproviderscala152 play 210jar221 at playcorereloadableapplicationanonfunget1anonfunapply1anonfun1applyapplicationproviderscala112 play 210jar221 at scalaoptionmapoptionscala145 scalalibraryjarna at playcorereloadableapplicationanonfunget1anonfunapply1applyapplicationproviderscala112 play 210jar221 at playcorereloadableapplicationanonfunget1anonfunapply1applyapplicationproviderscala110 play 210jar221 at scalautilsuccessflatmaptryscala200 scalalibraryjarnacaused by javalangnosuchmethoderror javaxpersistencetableindexesljavaxpersistenceindex at orghibernatecfgannotationsentitybinderprocesscomplementarytabledefinitionsentitybinderjava936 hibernatecore430finaljar430final at orghibernatecfgannotationbinderbindclassannotationbinderjava781 hibernatecore430finaljar430final at orghibernatecfgconfigurationmetadatasourcequeueprocessannotatedclassesqueueconfigurationjava3762 hibernatecore430finaljar430final at orghibernatecfgconfigurationmetadatasourcequeueprocessmetadataconfigurationjava3716 hibernatecore430finaljar430final at orghibernatecfgconfigurationsecondpasscompileconfigurationjava1410 hibernatecore430finaljar430final at orghibernatecfgconfigurationbuildsessionfactoryconfigurationjava1844 hibernatecore430finaljar430final,['java'] +601589,how do i make a star wars introduction shaped textarea normally textareas are just boring old oblongsbut is it possible to make a textarea shaped like the introduction to star warsnote inspired by so 20734620 unusual shape of a textareaasee commentsupdate thanks to niet the dark absol i was able to get it working just need to play with the font and colortextarea width600pxheight500pxtransformperspective10px rotatex45degthisplayblockmargin0 autotextalign centerlineheight200color yellowbackgroundcolor blackfontsize 175em,"['javascript', 'jquery', 'html', 'css']" +601616,sailsjs access controller method from controller method how come in sails you cannot access other controller methods from within another one like thismoduleexports findstore do somthing index findstore error undefinedcompiledmoduleexports findstore function index function return thisfindstore error undefined if you cannot do this then why not how else should i be doing this,['javascript'] +601672,execution failed aprocessdebugresources android studio i am using bitbucket so i can work with other developer but it seems that we cannot get it to work flawlessly i got this error after pulling the changes from himexecution failed for task aprocessdebugresources comandroididecommoninternalloggederrorexception failed to run command eprogram files x86androidandroidsdkbuildtools1900aaptexe package f nocrunch i eprogram files x86androidandroidsdkplatformsandroid19androidjar m edocumentssmartmyjob1appbuildmanifestsdebugandroidmanifestxml s edocumentssmartmyjob1appbuildresalldebug a edocumentssmartmyjob1appbuildassetsdebug m j edocumentssmartmyjob1appbuildsourcerdebug f edocumentssmartmyjob1appbuildlibsappdebugap debugmode custompackage comsmartmyjoberror code 1073741819,['android'] +601681,bring fragment to front no fragment recreation i have three fragments f1 f2 f3 f4 all are accessible from sidebarall four can be called at any time and in any ordernow i want if f1 is already clickedcreated then never again create f1 but only bring back fragment f1 to front using fragment manager same for all other fragmentso far i tried this for every fragment in my container fragment activityif fragmentmanagerfindfragmentbytagappsnull fragmentmanager fragmentmanager getsupportfragmentmanagerfragmenttransaction transaction fragmentmanagerbegintransactiontransactionsettransitionfragmenttransactiontransit fragment fadefragment newfragment new categoriesfragmenttransactionreplaceridcontent frame newfragment appstransactionaddtobackstackappstransactioncommit elseif part ensures me no fragment is recreated if its created already again but what should i write in else part so that already created fragment can be brought to front in view hierarchyplease help i am stuck at this for 2 days,['android'] +601745,index was outside the bounds of array when using list i have a class like thisclass myclass public object values somewhere else i am using itmyclass myinstance new myclass values new objects 5 truelistfuncmyclass object maps new listfuncmyclass objectfor int i 0 i myinstancevalueslength i mapsaddobj objvaluesivar result maps0myinstance exception index outside the bounds of the arrayi thought it will returns s but it throw exception any idea what is going on,['c#'] +601838,how do i get dagger and butterknife working with gradle i had my project working great with butterknife to do view injection but i then needed to add dagger in order to inject dependenciesi added the annotation processor tool gradle plugin with the appropriate dagger requirement only showing the modified parts for brevitybuildscript repositories maven url dependencies classpath comjimdogradlegradleaptplugin02snapshot apply plugin aptdependencies apt comsquareupdaggerdaggercompilerdaggerversion at this point now when i build and run the application the properties marked with the injectview annotation are not getting injected with the following debug messages emitted by butterknifedbutterknifei1 looking up view injector for comexamplemainactivitydbutterknifei1 not found trying superclass comexamplefactlistabstractactivitydbutterknifei1 not found trying superclass androidappactivity,['android'] +601842,angularjs checkbox model value is undefined i have a problem where i am attempting to post the value of a checkbox in my model to the server and as the checkbox has not been interacted with on the form angular seems to have not assigned it a value when i ask for the value of the checkbox it comes back as undefinedhere is my markupdiv classformgroup input idtemplatethisable typecheckbox ngmodeltemplatethisabled label fortemplatethisablethisabledlabeldivand heres a reduced version of my save action on my controllerscopesave function form if formvalid var formdata new formdata this is the problem line of code formdataappendthisabled scopetemplatethisabled some other stuff actually ticking then unticking the checkbox before i hit the save action results in the templatethisabled property being false which is what i would have expected without any manual interventioni have seen other related questions eg angularjs initial checkbox value not in model but surely stuff like a simple checkbox should be backed in i should not have to be writing directives to manage checkboxes surely,['javascript'] +601843,symfony2 and date default timezone get it is not safe to rely on the systems timezone settings i have a symfony2 project i updated my php to 557 today and since then i am getting the warning date default timezone get it is not safe to rely on the systems timezone settings you are required to use the datetimezone setting or the date default timezone set function in case you used any of those methods and you are still getting this warning you most likely misspelled the timezone identifier we selected the timezone utc for now but please set datetimezone to select your timezone ini setup the default timezone in my phpinidate defines the default timezone used by the date functions datetimezone europeparisto be sure that this is the good phpini i was checking with phpinfoand the path i ma getting there is the one i am modifying usrlocalphp557lib but in there i see the default timezone utc which is strangeany idea thank you,['php'] +601886,ios prepareforsegue iboutlet update does not work i am trying to update a label in the 2nd vc from the 1st vc within the prepareforsegue methodvoidprepareforsegueuistoryboardsegue segue senderidsender mysecondviewcontroller secondvc mysecondviewcontrollerseguedestinationviewcontroller secondvctitlelabeltext first vc says you are second this does not work secondvcdatapastring first vc says you are second this works secondvc viewdidloadif i update the label directly it does not workif i update a string property and then assign it to the label in the second vc viewdidload it does workdoes it mean that upon prepareforsegue call the second vc viewdidload method was not called yetwas some init method called so the nsstring object could pass if yes which oneis there a way to update iboutlets in the 2nd vc from the 1st vc,['ios'] +601911,import module or project as library on android studio i want to use holoeverywhere he preferences addon with my live wallpaper project the project is almost done i just need it to look the same from android 23 to 44 so i went on and followed the guide to get he from githubafter the checkout and the successful test of the demo module i went back to my project but i can only create a new module not import one and of i try to set the new project to the modules folder library and addons in my case android studio as me if i want to rewrite the module settings if i do it create the folder but it will not compile and the import orgholoeverywhere will not work,"['java', 'android']" +601956,how to get international atomic time in java 7 i am working on a java7 project and we need a timestamp in international atomic time i have found a few other questions relating to this that point to jsr310 and threeten project which is implementing jsr310how do we get the current gps time tai timehowever i am struggling to work out exactly what to use for java 7 and where to get it from there seems to be old sourceforge github pages for threeten as well as an openjdk pagei have found the java 7 backport but after downloading this from maven it does not include the taiinstant class which is what i actually need the tiainstant class is listed on the threeten sourceforge javadoc under javaxtimetaiinstantfor completeness this is the excerpt from my pomxmldependency groupidorgthreetengroupid artifactidthreetenbpartifactid version081versiondependencyshould i be using something else and where should i be getting it fromnote sorry i am not able to provide links to all the pages i am referring to stackoverflow would not let me have 2 links per post without higher repeditthe reason for wanting tai is that i need a timestamp which is monotonically increasing which i believe tai fulfils even during both positive negative leap seconds since it does not care about leap seconds counts all seconds equally including leap secondshaving read about posix unix time from various sources it is still not clear to me exactly what happens in unix time over a leap second i know the unix time is ambiguous in terms of referring to a utc time but i am not clear on what happens in unix time in the instant a leap second occurs does unix time pause or go backwards for example and perhaps more importantly even if it should not according to the unix time spec do unix implementations actually obey the spec regarding leap secondsfinally am i correct in saying that systemcurrenttimemillis will get the equivalent of posix time albeit in milliseconds rather than secondsnote i need an object which is portable across jvms and machines ruling out systemnanotime or similarconclusiontaitai is a system of measuring time where every second is counted and all seconds are equal ie every second consists of the same period of time and all seconds including leap seconds are counted in the total this means the number of seconds in tai counted from some arbitrary start point the unix epoch for example is a monotonically increasing integerposix timeposix time is a standard not an implementation for measuring time it defines every day as having exactly 86400 seconds therefore posix time does not count leap seconds since occasionally a minute may have 61 seconds leading to days with 86400 seconds and theoretically a minute could have 59 seconds leading to days with 86400 seconds this means that seconds in posix have variable length and shortly before during after leap seconds a posix clock may skip seconds or repeat them specifically the posix spec as referenced by meno hochschild in his answer states the relationship between the actual time of day and the current value for seconds since the epoch is unspecifiedutcutc is a time standard which is related to the way the earth moves around the sun aiming to maintain the relationship between the position of the sun and the time of day within a threshold ie in a utc0 region of the earth the sun is always at its highest at midday utc time leap seconds positive or negative are necessary because the speed of the earths rotation is not fixed and it does not vary in a predictable way meaning we cannot predict when leap seconds will be necessary or whether they will be positive leap seconds or negative leap secondsrepresenting timesit seems to me that both tai and posix are representations of counts of seconds ie something easy for a computer to actually store whereas utc is a human interpretation of time ie yearmonthday hourminutesecondmillisecond that is not usually stored internally by a computertranslating timesgiven the above there are a number of issues translating from posix without any leap seconds counted to tai with leap seconds countedit requires maintaining a table count of leap seconds to translate any posix time to a tai timeeven if point 1 is addressed the posix spec as above makes no guarantee about what will happen during a leap second so at such times we have no way of accurately representing an unambiguous timeif a number of systems must communicate passing timestamps between them we must guarantee that the table count of leap seconds is kept consistenton the other hand it is easy to convert from posix to the utc human interpretation it does not require knowledge of leap seconds since it just assumes every day has the same number of seconds albeit some of these seconds have different lengths of time in reality in practice you would just use the inverse of the formula in the posix spec to obtain various the utc components of time again see the posix spec referenced by meno hochschild,['java'] +601974,ambiguous error with char and charn can someone help me to understand is this correct behavior or notconsider this exampleinclude iostreamusing namespace stdtemplate typename tstruct test template typename tbool operatorconst testt obj const t arr return truetemplate typename t size t tnbool operatorconst testt obj const t arrtn return falseint main cout testchar string endl return 0with gcc 473 it compiles just fine and outputs 0 as expectedbut with visual studio compiler it reports an ambiguous error c2593who is right in this situation and what does standard say about itthank you,['c++'] +602025,load local javascript file in chrome for testing i am trying to test some javascript on my local using the chrome browser but chrome will not load local resources is there an easy work around for this,['javascript'] +602117,context sensitive diff implementation summary and basic questionusing ms access 2010 and vba sighi am attempting to implement a specialized diff function that is capable of outputting a list of changes in different ways depending on what has changed i need to be able to generate a concise list of changes to submit for our recordsi would like to use something such as html tags like span classreferencesthese are references 1 6span so that i can review the changes with code and customize how the change text is outputted or anything else to accomplish my taski see this as a way to provide an extensible way to customize the output and possibly move things into a more robust platform and actually use htmlcss does anyone know of a similar project that may be able to point me in the right directionmy taski have an access database with tables of work operation instructions typically 200300 operations many of which are changing from one revision to another i have currently implemented a function that iterates through tables finds instructions that have changed and compares themnote that each operation instruction is typically a couple sentences with a couple lines at the end with some document referencesmy algorithm is based on an ond difference algorithm and its variations and it works great access supports rich text which is just glorified simple html so i can easily generate the full text with formatted additions and deletions ie adding tags like font color redstrongithis text has been removedistrongfont the main output from the diff procedure is a full text of the operation that includes nonchanged deleted and inserted text inline with each other the diff procedure adds del and ins tags that are later replaced with the formatting text later the result is something similar to the view of changes from stack exchange editshowever like i said i need the changes listed in human readable format this has proven difficult because of the ambiguity many changes createfor example if a type of chemical is being changed from class a to class c the change text that is easily generated is change a to c which is not very useful to someone reviewing the changes more common are document reference at the end adding sop 3 to the list such as sop 1 2 3 generates the text add 3 clearly not useful eitherwhat would be most useful is a custom output for text designated as sop text so that the output would be add reference to sop 3i started with the following solutiongroup words together eg treat text such as sop 1 2 3 as one token to compare this generates the text change sop 1 2 to sop 1 2 3 this gets cluttered when there is a large list and you are attempting to determine what actually changed where i am nowi am now attempting to add extra html tags before running the the diff algorithm for example i will run the text through a preprocessor that will convert sop 1 2 to sop 1 2once the diff procedure returns the full change text i scan through it noting the current class of text and when there is a del or ins i capture the text between the tags and use a select case block over the class to address each changethis actually works okay for the most part but there are many issues that i have to work through such add diff deciding that the shortest path is to delete certain opening tags and insert other ones this creates a scenario that there are two span tags but only one span tag the ultimate questioni am looking for advise to either continue with the direction i have started or to try something different before investing a lot more time into a suboptimal solutionthanks all in advancealso notethe time for a typical run is approximately 15 to 25 seconds with me attempting more fancy things and a bunch of debugprints so running through an extra pass or two wouldnt be killer,['html'] +602301,how to perform search on arabic text in java i have arabic text in database with diacritics when i type arabic for searching some string it is without diacritics which definitely do not match with database string it is working fine on text without diacritics is there any way to run it on text with diacritics,"['java', 'android']" +602418,the memoryefficient way of using core image on ios i am using core image filters in my app everything works fine on my iphone 5 device running ios 7 but when i test it on iphone 4s which has only a total memory of 512mb the app crashes heres the situation i have 2 images taken from the camera with a resolution of 2448x3264 each in my iphone 5 the whole process takes up 150mb at the peak according to instrumentshowever when i try to run the same code on iphone 4s the instruments gave me memory low warning all the time even if the whole memory use is quite low around 8 mb heres the screenshot belowand heres the code basically i loaded two images from documents folder of my app and applied 2 filters in a row ciimage foreground ciimage alloc initwithcontentsofurlforegroundurl ciimage background ciimage alloc initwithcontentsofurlbackgroundurl cifilter softlightblendfilter cifilter filterwithnamecisoftlightblendmode softlightblendfilter setdefaults softlightblendfilter setvalueforeground forkeykciinputimagekey softlightblendfilter setvaluebackground forkeykciinputbackgroundimagekey foreground softlightblendfilter outputimage background nil softlightblendfilter nil cifilter gammaadjustfilter cifilter filterwithnamecigammaadjust gammaadjustfilter setdefaults gammaadjustfilter setvalueforeground forkeykciinputimagekey gammaadjustfilter setvaluensnumber numberwithfloatvalue forkeyinputpower foreground gammaadjustfilter valueforkeykcioutputimagekey gammaadjustfilter nil cicontext context cicontext contextwithoptionsnil cgrect extent foreground extent cgimageref cgimage context createcgimageforeground fromrectextent uiimage image uiimage imagewithcgimagecgimage scale10 orientationimgorientation cfreleasecgimage foreground nil return imagethe app crashed at this line cgimageref cgimage context createcgimageforeground fromrectextentis there any more memoryefficient way of handling this situation or what am i doing wrong herebig thanks,"['ios', 'iphone', 'objective-c']" +602446,androidviewinflateexception binary xml file line 1 error inflating class androidwidgetrelativelayout hello guys i am new in android i just made a new layout with one text bar and 2 buttons but it did not work i am posting the stack trace and my relative layout file any idea about this i saw the same question there which says to decrease the draw able size but it did not help in my case or i did not now much about how to decrease ithere is some of my stack trace dandroidruntime1192 shutting down vmwdalvikvm1192 threadid1 thread exiting with uncaught exception group0xb60cc4f0eandroidruntime1192 fatal exception maineandroidruntime1192 javalangruntimeexception unable to start activity componentinfocomexamplehellomissworldcomexamplehellomissworldmainactivity androidviewinflateexception binary xml file line 1 error inflating class androidwidgetrelativelayouteandroidruntime1192at androidappactivitythreadperformlaunchactivityactivitythreadjava16471224 185831451 eandroidruntime1192 at androidappactivitythreadhandlelaunchactivityactivitythreadjava16631224 185831451 eandroidruntime1192 at androidappactivitythreadaccess1500activitythreadjava1171224 185831451 eandroidruntime1192 at androidappactivitythreadhhandlemessageactivitythreadjava931and that is the xml file of lay out relativelayout xmlnsandroidxmlnstoolsandroidlayout widthwrap contentandroidlayout heightmatch parentandroidbackgroundlayoutactivity mainandroidfocusablefalseandroidpaddingbottomdimenactivity vertical marginandroidpaddingleftdimenactivity horizontal marginandroidpaddingrightdimenactivity horizontal marginandroidpaddingtopdimenactivity vertical margintoolscontextmainactivity edittext androidididedittext1 androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentlefttrue androidlayout alignparentrighttrue androidlayout margintop24dp androidems10 androidinputtypetext requestfocus edittexttextview androidididtextview1 androidlayout widthwrap content androidlayout heightwrap content androidlayout alignleftidedittext1 androidlayout alignparenttoptrue androidtextstringtypehere androidtextappearanceandroidattrtextappearancemedium button androidididbutton2 androidlayout widthwrap content androidlayout heightwrap content androidlayout alignrightidedittext1 androidlayout belowidedittext1 androidtextstringok button androidididbutton1 androidlayout widthwrap content androidlayout heightwrap content androidlayout belowidedittext1 androidlayout toleftofidbutton2 androidtextstringcancel,"['java', 'android']" +602492,what is on for javautilrandomnextn i want to know whether javautilrandomnextn scales linearly with and or is a constant could someone help me with this or show me how to go about determining the complexity,['java'] +602528,best way to style a textbox in css i would like to hear whats the best thing to do with pure cssthe situationi am having a textbox in which i can search for specific items yet now i am also having an advanced search with almost the same textbox yet the width of the advancedsearchtextbox is less than the default onemy questionwhat is the best way to style the textboxmy solutioni have fixed this now like thisdefaulttextbox padding 0 height 30px position relative left 0 outline none border 1px solid cdcdcd bordercolor rgba015 backgroundcolor white fontsize 16pxadvancedsearchtextbox width 526px marginright 4pxand then in the html it would look something like this for the advancedsearchtextboxinput typetext classdefaulttextbox advancedsearchtextbox is this the best way to do it or are there any other options available as for just 1 other textbox it is doable but what if i need more textboxes on other pagesthanks in advance,"['html', 'css']" +602564,actionbar with appcompat actionbaritembackground not working i am trying to change the color of an item when it pressed i used the actionbaritembackground item in the action bar style but nothing happens the color not changedhere my codestyle nameactionbarstyle parentstylewidgetappcompatactionbarsolid item nameandroidbackgroundcoloractionbar backgrounditem item nametitletextstylestyleactionbarstyletitleitem item nameactionbaritembackgrounddrawableaction bar item selectoritem item nameandroidactionbaritembackground toolsignorenewapidrawableaction bar item selectoritemstyleand the selectorselector xmlnsandroid item androiddrawabledrawablepressed item androidstate focusedtrue item androiddrawabledrawablepressed item androidstate pressedtrue item androiddrawableandroidcolortransparentselectorand the drawableshape xmlnsandroid androidshaperectangle solid androidcolorff0shapewhat is worng someone,['android'] +602648,fitting multivariate curve fit in python i am trying to fit a simple function to two arrays of independent data in python i understand that i need to bunch the data for my independent variables into one array but something still seems to be wrong with the way i am passing variables when i try to do the fit there are a couple previous posts related to this one but they have not been much helpimport numpy as npimport matplotlibpyplot as pltfrom scipyoptimize import curve fitdef fitfuncx 3d a b c d return a bx 3d0 cx 3d1 dx 3d0x 3d1x 3d nparray123456p0 511 39 53 2fitparams fitcovariances curve fitfitfunc x 3d2 x 3d2 p0print fit coefficientsn fitparamsthe error i get reads raise typeerrorimproper input ns must not exceed ms n m typeerror improper input n4 must not exceed m3what is m the length of is n the length of p0 what am i doing wrong here,['python'] +602656,srgb on ios opengl es 20 according to very few related topics that i could find i am gathering that the exponentiation step to obtain proper lighting computations perhaps must be done within the final fragment shader on an ios app i have been profiling with the latest and greatest xcode 5 opengl debugger and the exponentiation of the fragment accounts for a significant amount of computation it was the line that took the longest time in the entire shader the rest of the performance got sucked out by the various norm calls needed for pointlights glenablegl framebuffer srgb unfortunately does not work as gl framebuffer srgb is not declared of course the actual enum i should be using for gl es may be different according to apple the following extensions are supported for the sgx 543 and 554 processors onlyext color buffer half float ext occlusion query boolean ext pvrtc srgb ext shadow samplers ext srgb ext texture rg oes texture half float linearwell that is nice the newest device that does not have a 543 or 554 is the iphone 4from the extensions text file it looks like i can set srgb8 alpha8 ext to the internalformat parameter of renderbufferstorage but nothing is said of how to get the normal final framebuffer to apply srgb for us for free now the srgb correction seems like the missing step to get the correct colors what i have been doing in my app to deal with the horrible underexposed colors is manually applying gamma correction like this in the fragment shader mediump float gammaf 1018 this line declared outside of main it specifies a constant 18 gammamediump vec4 gamma vec4gammaf gammaf gammaf 10gl fragcolor powcolor gamma last line of mainnow i recognize that the typical render pipeline involves one or more renders to a texture followed by a fs quad draw which will afford me the opportunity to make use of an srgb8 alpha ext renderbuffer but what am i supposed to do without one am i sol if that is the case the pow call is sucking up so much time that it almost seems like i can squeeze some more perf out of it by building a 1d texture to sample and use as a gamma lookup table this texture could then be used to tweak the output color intensities in custom ways and get a much better approximation to srgb compared to just the raw exponentiation but it just all seems kind of wrong because supposedly srgb is freealso somewhat alarming is the absence of any mention of the string srgb anywhere in the gl es 20 spec according to the makers of glm gl es simply ignores srgb entirelyi know that i have used my code to render textures i made a basic opengl powered image viewer that renders pvrtc textures and they did not get dimmed i think what is happening there is that due to gl es 2s lack of srgb awareness the textures are loaded in as being in linear space and written back out in the same way in that situation since no lighting gets applied all colors got multiplied by 10 nothing bad happened to the results,['ios'] +602670,could not open input file composerphar i am trying to install zendframework using composer tool in wamp serverthe following steps are done towards installationi downloaded the composersetupexe file from composer page and got successfully installedi downloaded the zendframework and extracted inside the cwampwzend folderi executed the command for self updatephp composerphar selfupdatethis line generates the error message could not open file composerpharhow to resolve this errorif i try the composerphar selfupdate,['php'] +602717, note this is no duplicate i asked if it is different from different webserversi was just wondering what is the difference between scriptand script type textjavascriptis it different for different webserversfor examplei know it is incorrect to provide a link from w3schools but look myfirstusing chrome i visited w3schools and i realised that the script tag is all i needhowever when i did an offline javascript test i realised that i need thescript type textjavascripttag why is this so,"['javascript', 'html']" +602757,inverted polygon in gmsmapview i have to use google map for my iphone project and iam using gmspolygon to draw a polygon but how can i fill everywhere on my map except the interior of the polygon like the image below thank you,"['ios', 'iphone', 'objective-c']" +602778,salt stack using execution modules in sls so far as i can see in the salt documentation eg here there are two main types of modules supported state modules and execution modules i know therere also renderers returners and so on most of examples of sls files contain statements related only to state modules under saltstate namespace whereas for execution modules only command line examples are shown for example we have two modules named service saltstatesservice and saltmodulesservice right now i have problems using execution modules in sls files and it seems that either they are not available at all or i am missing something to make them available my question is is it possible to use execution modules in sls files and how for example can i restart a service on ubuntu machine using saltmodulesservicerestart function also i do not clearly get the difference between these modules typesmy service name is seleniumnode and i tried several combinations and all of them failed first attemptseleniumnode servicerestart another oneservice restart name seleniumnode or evenseleniumnode service restarti faced the same issue when working with git state and execution modules however when i run the following command on the minion as shown in the documentation it succeeds sudo saltcall servicerestart seleniumnode,['python'] +602790,laravel 4 query builder with complicated left joins i am new to laraval 4i have this queryselect aid active name email img location ifnullbtotal 0 as leadtotal ifnullctotal 0 as inventorytotalfrom users as aleft join select user id count as total from lead user group by user id as b on aid buser idleft join select user id count as total from user inventory group by user id as c on aid cuser idwhere ais deleted 0how can i convert it to laravel query builder i am confused on how to used the laravel join query builder with this type of querythanksanswerwill all the help of petkostas on laravel forum we got the answerusers dbtableusers as aselectarraya dbrawifnullbtotal 0 as leadtotal dbrawifnullctotal 0 as inventorytotal leftjoindbrawselect user id count as total from lead user group by user id as b function query queryon aid buser id leftjoindbrawselect user id count as total from user inventory where is deleted 0 group by user id as c function query queryon aid cuser id whereais deleted 0get,"['php', 'mysql', 'sql']" +602792,gson typetoken with dynamic arraylist item type i have this codetype typeofobjectslist new typetokenarraylistmyclass gettypelistmyclass objectslist new gsonfromjsonjson typeofobjectslistit converts a json string to a list of objectsbut now i want to have this arraylist with a dynamic type not just myclass defined at runtimethe arraylists item type will be defined with reflectioni tried this private t type setmodelandgetcorrespondinglist2classt type type typeofobjectslistnew new typetokenarraylistt gettype return typeofobjectslistnew but it does not work this is the exceptionjavasqlsqlexception fail to convert to internal representation my json,['java'] +602799,undefined method each for nilnilclass why rails guide example click the button save post console show this messagestarted post posts for 127001 at 20131225 224204 0800 processing by postscontrollercreate as html parameters utf8a authenticity tokenclaluww3gqnsled0awdou6pu2qya vpqdibanqouyga posttitle11 text22 commitsave post 00ms begin transaction 00ms rollback transaction redirected to http 12700130posts completed 302 found in 16ms activerecord 00msstarted get posts for 127001 at 20131225 224204 0800 processing by postscontrollerindex as html rendered postsindexhtmlerb within layoutsapplication 156ms completed 500 internal server error in 31msactionviewtemplateerror undefined method each for nilnilclass thtextth tr postseach do post routes is correct why post is nil rails 402 ruby 20,['ruby-on-rails'] +602894,java import statement syntax this is a simple question but i am really bugged by it i was trying to find a duplicate and googled it but i was more surprised when i could not find a satisfying answer import javautilscanner in this statement scanner is the classutil is the name of the packagewhat is java or javax or whatever would stand before the first period in generalupdate i also found this picture is it true,['java'] +602936,how do i align components in a jpanel to the left i have created a layout for a basic text editor i would like the top bar to have the buttons alligned to the left the top bar is a jpanel and it is using the flowlayout manager it is inside of a grid using the gridbag layout manager any suggestions import javaawtimport javaxswingpublic class gridtest private static jbutton firstbutton secondbutton thirdbuttonprivate static jpanel panel sidebar infopanelprivate static jtextarea textareapublic static void addcomponentstopanecontainer container containersetlayoutnew gridbaglayout gridbagconstraints c new gridbagconstraints firstbutton new jbuttonbutton 1 secondbutton new jbuttonbutton 2 thirdbutton new jbuttonbutton 3 panel new jpanelnew flowlayout sidebar new jpanelnew flowlayout infopanel new jpanelnew flowlayout textarea new jtextareathis is some generic text cfill gridbagconstraintshorizontal cipady 0 cweighty 0 cweightx 1 cgridx 0 cgridwidth 3 cgridy 0 canchor gridbagconstraintsline start containeraddpanel c panelsetcomponentorientationcomponentorientationleft to right panelsetborderborderfactorycreatelinebordercolorblack paneladdfirstbutton paneladdsecondbutton paneladdthirdbutton cfill gridbagconstraintsboth cipady 300 cipadx 100 cweighty 1 cweightx 0 cgridx 0 cgridheight 2 cgridwidth 1 cgridy 1 containeraddsidebar c sidebarsetborderborderfactorycreatelinebordercolorblack cfill gridbagconstraintsboth cipady 40 cweightx 1 cweighty 1 cgridwidth 2 cgridheight 1 cgridx 1 cgridy 1 containeraddtextarea c textareasetfontnew fontserif fontitalic 16 textareasetlinewraptrue textareasetwrapstylewordtrue cfill gridbagconstraintshorizontal cipady 20 cweighty 0 cweightx 0 canchor gridbagconstraintspage end cgridx 1 cgridwidth 2 cgridy 2 containeraddinfopanel c infopanelsetborderborderfactorycreatelinebordercolorblackprivate static void createandshowgui jframe frame new jframegrid test framesetdefaultcloseoperationjframeexit on close addcomponentstopaneframegetcontentpane framesetsize800600 framesetvisibletruepublic static void mainstring args javaxswingswingutilitiesinvokelaternew runnable public void run createandshowgui,['java'] +602953,efficiently eliminate common subexpressions in net expression tree i have written a dsl and a compiler that generates a net expression tree from it all expressions within the tree are sideeffectfree and the expression is guaranteed to be a nonstatement expression no locals loops blocks etc edit the tree may include literals property accesses standard operators and function calls which may be doing fancy things like memoization inside but are externally sideeffect freenow i would like to perform the common subexpression elimination optimization on itfor example given a tree corresponding to the c lambdafoo foobar 5 foobaz 2 7 foobar 5 foobaz 2 3 foobar 5 3 fooxyzi would like to generate the trequivalent of ignore the fact that some of the shortcircuiting semantics are being ignoredfoo var local1 foobar 5 notice that this local depends on the first one var local2 local1 foobaz 2 notice that no unnecessary locals have been generated return local2 7 local2 3 local1 3 fooxyzi am familiar with writing expressionvisitors but the algorithm for this optimization is not immediately obvious to me i could of course find duplicates within a tree but there is obviously some trick to analyzing the dependencies within and between subtrees to eliminate subexpressions efficiently and correctly i looked for algorithms on google but they seem quite complicated to implement quickly also they seem very general and do not necessarily take the simplicity of the trees i have into account,"['c#', '.net']" +603053,making a smooth fade out for imageview in android i managed to make the imageview thissapear after 10 secondsa tutorial image on my mainactivity but i want to make a smooth fade out because like this it doesnt look good can anyone refer me to any good tutorial imgimageviewfindviewbyidridimagetutorial ifgetintentnull bundle extras getintentgetextras string tutorialdemoextras null extrasgetstringtutorialdemofalse iftutorialdemoequalstrue runnable mrunnable handler mhandlernew handler mrunnablenew runnable override public void run imgsetvisibilityviewgone this will remove the view and free s the space occupied by the view mhandlerpostdelayedmrunnable10900 else imgsetvisibilityviewgone here is the image view xml xml version10 encodingutf8 scrollview xmlnsandroid xmlnstools androidlayout widthmatch parent androidlayout heightmatch parent androidididfullviewlinearlayout androidlayout widthmatch parent androidlayout heightmatch parent androidlayout margin10dp androidorientationvertical imageview androidcontentdescriptiontutorial androidididimagetutorial androidlayout widthmatch parent androidlayout height120dp androidlayout alignparentbottomtrue androidbackgrounddrawabletutorial androidlayout margintop40dp androidgravitycenter linearlayout,['android'] +603071,difference between two table structure i am very confuse about the two structure what are the advantage and thisadvantage of this two tablewhich one is better and why table1id name age birthdate addresomedata1 somedata1 somedata1 somedata1 somedata1somedata2 somedata2 somedata2 somedata2 somedata2somedata3 somedata3 somedata3 somedata3 somedata3 table2id col name col valuesomedata name somedatasomedata age somedatasomedata birthdate somedatasomedata address somedatasomedata2 name somedata2somedata2 age somedata2somedata2 birthdate somedata2somedata2 address somedata2somedata3 name somedata3somedata3 age somedata3somedata3 birthdate somedata3somedata3 address somedata3,"['mysql', 'sql']" +603183,eigen library initialize matrix with data from file or existing stdvector content my question is how to initialize an eigen matrix but not this waymatrix 1010 1010 1010i have a matrix that looks like the above one commas or no commas doesnt matterstored in a txt filei already wrote a function to read in each line and put it into a vectornow i want to create a matrix with this databut it doesn work and i cant find any page that explains how to assign data to a matrix without writing just the valueslike the example aboveall i need is the data from my file in an eigen matrix what i tried so far ps had the idea with the iterators but i guess it will take too long with really big matrices i just tried this example with a 12 dimensional matrix int readfromfile const char path vector string mv fstream file string line fileopenpath while getlinefileline mvpush backline fileclose return 0typedef matrix int 1 2 mymatrixint fromvectoeigen vectorstring source mymatrix target for int i sourcesize i0 i string valuerow sourceback stringiterator it valuerowbegin targetrow0 it targetrow0it1 sourcepop back return 0unfortunately cant just say matrixrowi vectorback that doesnt work,['c++'] +603221,what are the benefits to painting on a jpanel vs jcomponent so in a recent answer someone commented this in regards to paintingthis is probably some kind of illness of 90 of swing programmers when they make their own component they always extend jpanel instead of jcomponent whyi am still fairly new to programming so i think it is too early to call myself a swing programmer as i have yet to find my niche but overriding jpanel is just the way i was taught so i set out to find the answer to the why question of the commenter these are some of the answers i foundbackground painting is main difference the jcomponent class does not paint its background so you have to paint the background in the overridden paintcomponent method in contrast jpanel has an opaque background which can be painted by calling its paintcomponennt methodinstead of extending jcomponent some programmers prefer to extend the jpanel class a jpanel is intended to be a container that can contain other components but it is also possible to paint on it there is just one difference a panel is opaque which means that it is responsible for painting all pixels within its bounds the easiest way to achieve that is to paint the panel with the background color by calling superpaintcomponent in the paintcomponent method of each panel subclassif the opaque property is set to true then the swing painting system does not have to waste time trying to paint behind the component hence improves performancei think the last quote really explains it best but besides the opacity are there other beneficial reasons 90 of swing programmers have this illness of extending jpanel rather than jcomponent,['java'] +603324,why is objectwait final in java what is the reason behind objects wait method being implemented as a final method is there no need for overriding wait,['java'] +603375,net web api cors preflight request i have some trouble make put and delete cors request to web api on other domain i have coded api by tutorial get and post requests works fine but delete and put does not i get this messagefailed to load resource the server responded with a status of 405 method not allowedfailed to load resource no accesscontrolalloworigin header is present on the requested resourcewhen i add code to webconfig suggested on cors support for put and delete with aspnet web api i get only first errorcan anyone help me with this please,['.net'] +603383,get file name and extension in ruby i am working on a program to download a video from youtube convert it to mp3 and create a directory structure for the filesmy code isfileutilscdmusicdirfolder do youtubedlhelperlibsdownloadergeturl if fileexistsmp4 puts remove unneeded tempfile dirmp4each do waste filedeletewaste end else puts temporary file already deleted end dirm4aeach do rip ripto s ripsplit puts inside the function puts rip endendthe first one goes to the already created music folder inside that i am executing get after that i have two files in the directory xyzmp4 and xyzm4ai would like to fetch the filename without the extension so i can handle both files differentlyi am using an array but an array for just one match sounds crazy for mehas anyone another idea,['ruby'] +603390,logback delete the log file on startup i want to delete the log file each time the program is started as opposed to it being appended i have tried using the cleanhistoryonstart property but that seems to have no effect whatsoever i am probably missing something herei am on linux and using eclipse if that mattersxml version10 encodingutf8configuration scantrue scanperiod10 seconds appender namestdout classchqoslogbackcoreconsoleappender encoder patterndmmy hhmmss level thread logger20 msgnpattern encoder appender appender namefile classchqoslogbackcorerollingrollingfileappender filechatlogfile rollingpolicy classchqoslogbackcorerollingtimebasedrollingpolicy filenamepatternchatlogdymmddfilenamepattern cleanhistoryonstarttruecleanhistoryonstart rollingpolicy encoder patterndmmy hhmmss level thread logger20 msgnpattern encoder encodingutf8encoding appender logger namesrc additivityfalse levelall appenderref refstdout appenderref reffile logger root leveloff appenderref refstdout rootconfiguration,['java'] +603556,drawing the cannabis curve inspired by cannabis equation from the math site it refers to the wolfram research cannabis curve i was wondering how would we draw this curve using java2d,['java'] +603583,javalangruntimeexception method called after release if i am not using mcamerarelease in surfacedestroyed then not able to launch cameraactivity again from another activity in short getting unfortunately app has stopped error even not releasing camera but if i do tap on home button from cameraactivity and then again launching my app not getting any error in short works fine and opening cameraactivity without any problemand if i am using mcamerarelease in surfacedestroyed then able to launch cameraactivity again from another activity and releasing camera as well but when i do tap on home button and then again launching my app getting unfortunately app has stoppedbut i want both things working together first tap on home from cameraactivity and again launch app from cameraactivity without any error and second launching camera from another activity without any errorlike i wrote both the things are working for me but not together line number 33 is cameraparameters parameters mcameragetparameterscomplete log1230 121858070 wdalvikvm14822 threadid1 thread exiting with uncaught exception group0x41ef72a01230 121858080 eandroidruntime14822 fatal exception main1230 121858080 eandroidruntime14822 javalangruntimeexception method called after release1230 121858080 eandroidruntime14822 at androidhardwarecameranative getparametersnative method1230 121858080 eandroidruntime14822 at androidhardwarecameragetparameterscamerajava14871230 121858080 eandroidruntime14822 at appmichealcamrpreviewsurfacesurfacecreatedpreviewsurfacejava331230 121858080 eandroidruntime14822 at androidviewsurfaceviewupdatewindowsurfaceviewjava6091230 121858080 eandroidruntime14822 at androidviewsurfaceviewonwindowvisibilitychangedsurfaceviewjava2351230 121858080 eandroidruntime14822 at androidviewviewthispatchwindowvisibilitychangedviewjava76861230 121858080 eandroidruntime14822 at androidviewviewgroupthispatchwindowvisibilitychangedviewgroupjava10471230 121858080 eandroidruntime14822 at androidviewviewgroupthispatchwindowvisibilitychangedviewgroupjava10471230 121858080 eandroidruntime14822 at androidviewviewgroupthispatchwindowvisibilitychangedviewgroupjava10471230 121858080 eandroidruntime14822 at androidviewviewgroupthispatchwindowvisibilitychangedviewgroupjava10471230 121858080 eandroidruntime14822 at androidviewviewgroupthispatchwindowvisibilitychangedviewgroupjava10471230 121858080 eandroidruntime14822 at androidviewviewrootimplperformtraversalsviewrootimpljava13391230 121858080 eandroidruntime14822 at androidviewviewrootimpldotraversalviewrootimpljava141230 121858080 eandroidruntime14822 at androidviewviewrootimpltraversalrunnablerunviewrootimpljava45201230 121858080 eandroidruntime14822 at androidviewchoreographercallbackrecordrunchoreographerjava7251230 121858080 eandroidruntime14822 at androidviewchoreographerdocallbackschoreographerjava51230 121858080 eandroidruntime14822 at androidviewchoreographerdoframechoreographerjava5251230 121858080 eandroidruntime14822 at androidviewchoreographerframethisplayeventreceiverrunchoreographerjava71230 121858080 eandroidruntime14822 at androidoshandlerhandlecallbackhandlerjava6151230 121858080 eandroidruntime14822 at androidoshandlerthispatchmessagehandlerjava921230 121858080 eandroidruntime14822 at androidoslooperlooplooperjava1371230 121858080 eandroidruntime14822 at androidappactivitythreadmainactivitythreadjava49211230 121858080 eandroidruntime14822 at javalangreflectmethodinvokenativenative method1230 121858080 eandroidruntime14822 at javalangreflectmethodinvokemethodjava51230 121858080 eandroidruntime14822 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava10361230 121858080 eandroidruntime14822 at comandroidinternaloszygoteinitmainzygoteinitjava8031230 121858080 eandroidruntime14822 at dalviksystemnativestartmainnative method1230 121908095 iprocess14822 sending signal pid 14822 sig 9previewsurfacejavapublic class previewsurface extends surfaceview implementssurfaceholdercallback public static final string log tag camerapreview private surfaceholder msurfaceholder private camera mcamera cameraparameters parameters null constructor that obtains context and camera suppresswarningsdeprecation public previewsurfacecontext context camera camera supercontext thismcamera camera thismsurfaceholder thisgetholder thismsurfaceholderaddcallbackthis thismsurfaceholdersettypesurfaceholdersurface type push buffers thismsurfaceholdersetfixedsize100 100 override public void surfacecreatedsurfaceholder surfaceholder try parameters mcameragetparameters if thisgetresourcesgetconfigurationorientation configurationorientation landscape parameterssetorientation portrait mcamerasetthisplayorientation90 parameterssetrotation90 mcamerasetpreviewthisplaysurfaceholder mcamerastartpreview else this is an undocumented although widely known feature parameterssetorientation landscape for android 22 and above mcamerasetthisplayorientation0 uncomment for android 20 and above parameterssetrotation0 mcamerasetpreviewthisplaysurfaceholder mcamerastartpreview catch ioexception e left blank for now override public void surfacedestroyedsurfaceholder surfaceholder mcamerastoppreview mcamerarelease override public void surfacechangedsurfaceholder surfaceholder int format int width int height try parameters mcameragetparameters if thisgetresourcesgetconfigurationorientation configurationorientation landscape parameterssetorientation portrait mcamerasetthisplayorientation90 parameterssetrotation90 else this is an undocumented although widely known feature parameterssetorientation landscape for android 22 and above mcamerasetthisplayorientation0 uncomment for android 20 and above parameterssetrotation0 mcamerasetpreviewthisplaysurfaceholder mcamerastartpreview catch ioexception e left blank for now,['android'] +603592,how to access a nested qml object from c here is a reproducible examplemainqmlimport qtquick 20item id root width 360 height 360 text id t1 text qstrhello world property int somenumber 10 anchorscenterin parent mousearea anchorsfill parent onclicked qtquit maincppinclude qtguiqguiapplicationinclude qqmlengineinclude qqmlcomponentinclude qqmlpropertyinclude qdebuginclude qtquick2applicationviewerhint mainint argc char argv qguiapplication appargc argv qtquick2applicationviewer viewer viewersetmainqmlfileqstringliteralqmluntitledmainqml viewershowexpanded qqmlengine engine qqmlcomponent componentengine qmluntitledmainqml qobject object componentcreate qdebug property value qqmlpropertyreadobject roott1somenumbertoint return appexeci wish to access the property somenumber of the text of the qml itemthe above method is not producing the desired resulthow to do it,['c++'] +603630,java aes 256 javasecurityinvalidkeyexception illegal key size after installation the policy i have a problem with the encrypt of the bytes with an aes 256 keyi already installed the policy heres what i have donedownload the file i moved the files local policy and us export policy to the directory libraryjavajavavirtualmachinesjdk170 40jdkcontentshomejrelibsecurityi restart the macbut still i get an error message with the following codekeygenerator keygenerator keygeneratorgetinstanceaeskeygeneratorinit256secretkey secretkey keygeneratorgeneratekeycipher decryption ciphergetinstanceaescbcpkcs5paddingdecryptioninitcipherdecrypt mode secretkey new ivparameterspecsecretkeygetencoded illegal key sizemy java versionjava version 170 40javatm se runtime environment build 170 40b43java hotspottm 64bit server vm build 240b56 mixed modewhat i have to do to use the 256 aes encryption,['java'] +603643,why stdshared ptr calls destructors from base and derived classes where delete calls only destructor from base class why when using stdshared ptr deallocation calls destructors from both base and derived classes when second example calls only destructor from base class class basepublic base stdcout base destructor stdendl class derived public basepublic derived stdcout derived destructor stdendl void virtual destructor stdcout stdendl stdshared ptrbase sharedanew derived stdcout stdendl base a new derived delete aoutputderived destructorbase destructorbase destructori was expecting the same behaviour in both cases,['c++'] +603735,facebook api request dialog not working with safari i have the following code that logs the user in and thisplays the select friends for request dialog apprequests doctype html html xmlns xmlnsfb head titletesttitle script typetextjavascript function facebook fbloginfunctionresponse if responseauthresponse var access token fbgetauthresponseaccesstoken fbui method apprequests message sample title max recipients1 functionresponse consolelogok scope publish stream script head body pa hrefjavascriptfacebooktestap div idfbrootdiv script typetextjavascript functiond s id var js fjs dgetelementsbytagnames0 if dgetelementbyidid return js dcreateelements jsid id jssrc connectfacebooknetes laalljsxfbml0appidx fjsparentnodeinsertbeforejs fjs document script facebookjssdk script body htmlthe code is working with all major browsers firefox chrome opera ie11 safari for ios android browser safari for macpc is the exception it is opening the apprequests dialog but the dialog comes up empty if you change the dropdown options to friends to invite and then to all friends again the friend list finally appearsany idea how to fix this bugthank you,"['javascript', 'html']" +603814,spring jpa hibernate no qualifying bean of type javaxpersistenceentitymanagerfactory i am using springboot so a war deployed in tomcat 7 when i start the app i get the following dec 30 2013 74106 pm orgapachecatalinacoreapplicationcontext loginfo initializing spring frameworkservlet thispatcherservlet20131230 194106 info thispatcherservlet461 frameworkservlet thispatcherservlet initialization started 20131230 194106 info simpleurlhandlermapping315 mapped url path faviconico onto handler of type class orgspringframeworkwebservletresourceresourcehttprequesthandler 20131230 194106 info requestmappinghandlermapping181 mapped usermethodsgetparamsheadersconsumesproducescustom onto public comcloudfordevcontrolpanelormuser comcloudfordevcontrolpanelgetcontrollergetuserint 20131230 194107 info simpleurlhandlermapping315 mapped url path onto handler of type class orgspringframeworkwebservletresourceresourcehttprequesthandler 20131230 194107 info simpleurlhandlermapping315 mapped url path webjars onto handler of type class orgspringframeworkwebservletresourceresourcehttprequesthandler 20131230 194108 info thispatcherservlet480 frameworkservlet thispatcherservlet initialization completed in 1957 ms dec 30 2013 74108 pm orgapachecoyoteabstractprotocol startinfo starting protocolhandler httpnio8080dec 30 2013 74108 pm orgapachetomcatutilnetnioselectorpool getsharedselectorinfo using a shared selector for servlet writereaddec 30 2013 74108 pm orgapachecoyoteabstractprotocol stopinfo stopping protocolhandler httpnio8080dec 30 2013 74108 pm orgapachecoyoteabstractprotocol pauseinfo pausing protocolhandler httpnio8080dec 30 2013 74108 pm orgapachecatalinacorestandardservice stopinternalinfo stopping service tomcatdec 30 2013 74108 pm orgapachecoyoteabstractprotocol stopinfo stopping protocolhandler httpnio8080dec 30 2013 74108 pm orgapachecoyoteabstractprotocol destroyinfo destroying protocolhandler httpnio808020131230 194108 info autoconfigurationreportlogginginitializerautoconfigurationreportlogger108 autoconfiguration reportpositive matches messagesourceautoconfiguration conditionalonmissingbean types orgspringframeworkcontextmessagesource searchstrategy all found no beans onbeancondition propertyplaceholderautoconfigurationpropertysourcesplaceholderconfigurer conditionalonmissingbean types orgspringframeworkcontextsupportpropertysourcesplaceholderconfigurer searchstrategy current found no beans onbeancondition datasourceautoconfiguration conditionalonclass classes found orgspringframeworkjdbcdatasourceembeddedembeddeddatabasetype onclasscondition conditionalonclass classes found orgspringframeworkjdbcdatasourceembeddedembeddeddatabasetype onclasscondition datasourcetransactionmanagerautoconfiguration conditionalonclass classes found orgspringframeworkjdbccorejdbctemplateorgspringframeworktransactionplatformtransactionmanager onclasscondition conditionalonclass classes found orgspringframeworkjdbccorejdbctemplateorgspringframeworktransactionplatformtransactionmanager onclasscondition jpabaseconfigurationjpawebconfiguration found web application standardservletenvironment onwebapplicationcondition spel expression on orgspringframeworkbootautoconfigureormjpajpabaseconfigurationjpawebconfiguration true onexpressioncondition thispatcherservletautoconfiguration found web application standardservletenvironment onwebapplicationcondition conditionalonclass classes found orgspringframeworkwebservletthispatcherservlet onclasscondition found web application standardservletenvironment onwebapplicationcondition conditionalonclass classes found orgspringframeworkwebservletthispatcherservlet onclasscondition conditionalonbean types orgspringframeworkbootcontextembeddedembeddedservletcontainerfactory searchstrategy all found the following tomcatembeddedservletcontainerfactory onbeancondition thispatcherservletautoconfigurationthispatcherservlet no thispatcherservlet found thispatcherservletautoconfigurationdefaultthispatcherservletcondition embeddedservletcontainerautoconfiguration found web application standardservletenvironment onwebapplicationcondition found web application standardservletenvironment onwebapplicationcondition embeddedservletcontainerautoconfigurationembeddedtomcat conditionalonclass classes found javaxservletservletorgapachecatalinastartuptomcat onclasscondition conditionalonclass classes found javaxservletservletorgapachecatalinastartuptomcat onclasscondition conditionalonmissingbean types orgspringframeworkbootcontextembeddedembeddedservletcontainerfactory searchstrategy current found no beans onbeancondition serverpropertiesautoconfigurationserverproperties conditionalonmissingbean types orgspringframeworkbootcontextembeddedpropertiesserverproperties searchstrategy all found no beans onbeancondition webmvcautoconfiguration found web application standardservletenvironment onwebapplicationcondition conditionalonclass classes found javaxservletservletorgspringframeworkwebservletthispatcherservletorgspringframeworkwebservletconfigannotationwebmvcconfigureradapter onclasscondition found web application standardservletenvironment onwebapplicationcondition conditionalonclass classes found javaxservletservletorgspringframeworkwebservletthispatcherservletorgspringframeworkwebservletconfigannotationwebmvcconfigureradapter onclasscondition conditionalonmissingbean types orgspringframeworkwebservletconfigannotationwebmvcconfigurationsupport searchstrategy all found no beans onbeancondition webmvcautoconfigurationhiddenhttpmethodfilter conditionalonmissingbean types orgspringframeworkwebfilterhiddenhttpmethodfilter searchstrategy all found no beans onbeancondition webmvcautoconfigurationwebmvcautoconfigurationadapterdefaultviewresolver conditionalonmissingbean types orgspringframeworkwebservletviewinternalresourceviewresolver searchstrategy all found no beans onbeanconditionnegative matches rabbitautoconfiguration required conditionalonclass classes not found orgspringframeworkamqprabbitcorerabbittemplatecomrabbitmqclientchannel onclasscondition aopautoconfiguration required conditionalonclass classes not found orgaspectjlangannotationaspectorgaspectjlangreflectadvice onclasscondition batchautoconfiguration required conditionalonclass classes not found orgspringframeworkbatchcorelaunchjoblauncher onclasscondition jparepositoriesautoconfiguration required conditionalonclass classes not found orgspringframeworkdatajparepositoryjparepository onclasscondition mongorepositoriesautoconfiguration required conditionalonclass classes not found commongodbmongoorgspringframeworkdatamongodbrepositorymongorepository onclasscondition datasourceautoconfigurationdbcpconfiguration orgapachecommonsdbcpbasicdatasource datasource class not found datasourceautoconfigurationbasicdatabasecondition datasourceautoconfigurationembeddedconfiguration no embedded database detected datasourceautoconfigurationembeddeddatabasecondition datasourceautoconfigurationjdbctemplateconfiguration no existing bean configured database datasourceautoconfigurationdatabasecondition datasourceautoconfigurationtomcatconfiguration orgapachetomcatjdbcpooldatasource datasource class not found datasourceautoconfigurationtomcatdatabasecondition datasourcetransactionmanagerautoconfigurationtransactionmanager conditionalonbean types javaxsqldatasource searchstrategy all found no beans onbeancondition jmstemplateautoconfiguration required conditionalonclass classes not found orgspringframeworkjmscorejmstemplatejavaxjmsconnectionfactory onclasscondition deviceresolverautoconfiguration required conditionalonclass classes not found orgspringframeworkmobiledevicedeviceresolverhandlerinterceptororgspringframeworkmobiledevicedevicehandlermethodargumentresolver onclasscondition hibernatejpaautoconfiguration conditionalonclass classes found orgspringframeworkormjpalocalcontainerentitymanagerfactorybeanorgspringframeworktransactionannotationenabletransactionmanagementjavaxpersistenceentitymanagerorghibernateejbhibernateentitymanager onclasscondition conditionalonclass classes found orgspringframeworkormjpalocalcontainerentitymanagerfactorybeanorgspringframeworktransactionannotationenabletransactionmanagementjavaxpersistenceentitymanagerorghibernateejbhibernateentitymanager onclasscondition conditionalonbean types javaxsqldatasource searchstrategy all found no beans onbeancondition reactorautoconfiguration required conditionalonclass classes not found reactorspringcontextconfigenablereactor onclasscondition thymeleafautoconfiguration required conditionalonclass classes not found orgthymeleafspring3springtemplateengine onclasscondition embeddedservletcontainerautoconfigurationembeddedjetty required conditionalonclass classes not found orgeclipsejettyserverserverorgeclipsejettyutilloader onclasscondition multipartautoconfiguration conditionalonclass classes found javaxservletservletorgspringframeworkwebmultipartsupportstandardservletmultipartresolver onclasscondition conditionalonclass classes found javaxservletservletorgspringframeworkwebmultipartsupportstandardservletmultipartresolver onclasscondition conditionalonbean types javaxservletmultipartconfigelement searchstrategy all found no beans onbeancondition webmvcautoconfigurationwebmvcautoconfigurationadapterbeannameviewresolver conditionalonbean types orgspringframeworkwebservletview searchstrategy all found no beans onbeancondition webmvcautoconfigurationwebmvcautoconfigurationadapterviewresolver conditionalonbean types orgspringframeworkwebservletview searchstrategy all found no beans onbeancondition websocketautoconfiguration required conditionalonclass classes not found orgspringframeworkwebsocketwebsockethandler onclasscondition javalangreflectinvocationtargetexception at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokeunknown source at sunreflectdelegatingmethodaccessorimplinvokeunknown source at javalangreflectmethodinvokeunknown source at orgspringframeworkbootloadermainmethodrunnerrunmainmethodrunnerjava53 at javalangthreadrununknown sourcecaused by orgspringframeworkbeansfactorybeancreationexception error creating bean with name userdao injection of persistence dependencies failed nested exception is orgspringframeworkbeansfactorynosuchbeandefinitionexception no qualifying bean of type javaxpersistenceentitymanagerfactory is defined at orgspringframeworkormjpasupportpersistenceannotationbeanpostprocessorpostprocesspropertyvaluespersistenceannotationbeanpostprocessorjava356 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorypopulatebeanabstractautowirecapablebeanfactoryjava1180 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorydocreatebeanabstractautowirecapablebeanfactoryjava537 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorycreatebeanabstractautowirecapablebeanfactoryjava475 at orgspringframeworkbeansfactorysupportabstractbeanfactory1getobjectabstractbeanfactoryjava300 at orgspringframeworkbeansfactorysupportdefaultsingletonbeanregistrygetsingletondefaultsingletonbeanregistryjava228 at orgspringframeworkbeansfactorysupportabstractbeanfactorydogetbeanabstractbeanfactoryjava296 at orgspringframeworkbeansfactorysupportabstractbeanfactorygetbeanabstractbeanfactoryjava195 at orgspringframeworkbeansfactorysupportdefaultlistablebeanfactorypreinstantiatesingletonsdefaultlistablebeanfactoryjava660 at orgspringframeworkcontextsupportabstractapplicationcontextfinishbeanfactoryinitializationabstractapplicationcontextjava760 at orgspringframeworkcontextsupportabstractapplicationcontextrefreshabstractapplicationcontextjava482 at orgspringframeworkbootcontextembeddedembeddedwebapplicationcontextrefreshembeddedwebapplicationcontextjava122 at orgspringframeworkbootspringapplicationrefreshspringapplicationjava552 at orgspringframeworkbootspringapplicationrunspringapplicationjava293 at orgspringframeworkbootspringapplicationrunspringapplicationjava749 at orgspringframeworkbootspringapplicationrunspringapplicationjava738 at comcloudfordevcontrolpanelapplicationmainapplicationjava14 6 morecaused by orgspringframeworkbeansfactorynosuchbeandefinitionexception no qualifying bean of type javaxpersistenceentitymanagerfactory is defined at orgspringframeworkormjpasupportpersistenceannotationbeanpostprocessorfinddefaultentitymanagerfactorypersistenceannotationbeanpostprocessorjava559 at orgspringframeworkormjpasupportpersistenceannotationbeanpostprocessorfindentitymanagerfactorypersistenceannotationbeanpostprocessorjava515 at orgspringframeworkormjpasupportpersistenceannotationbeanpostprocessorpersistenceelementresolveentitymanagerpersistenceannotationbeanpostprocessorjava682 at orgspringframeworkormjpasupportpersistenceannotationbeanpostprocessorpersistenceelementgetresourcetoinjectpersistenceannotationbeanpostprocessorjava655 at orgspringframeworkbeansfactoryannotationinjectionmetadatainjectedelementinjectinjectionmetadatajava150 at orgspringframeworkbeansfactoryannotationinjectionmetadatainjectinjectionmetadatajava87 at orgspringframeworkormjpasupportpersistenceannotationbeanpostprocessorpostprocesspropertyvaluespersistenceannotationbeanpostprocessorjava353 22 morethis is how my application bootsconfigurationcomponentscanenableautoconfigurationpublic class application public static void mainstring args springapplicationrunapplicationclass args when my spring controller handles the connectioncontrollerpublic class getcontroller private userservice userservice autowired public void setuserserviceuserservice userservice thisuserservice userservice requestmappingvalue user method requestmethodget public responsebody user getuserrequestparamvalueid requiredtrue int id user user null user userservicegetuserid return user it does a getuser on the userservicecomponentpublic class userservice private userdao userdao public userdao getuserdao return userdao autowired public void setuserdaouserdao userdao thisuserdao userdao public user getuserint id return getuserdaoloadid which uses the userdao to find the entityrepositoryuserdaotransactionalpropagationpropagationrequiredpublic class userdao persistencecontext private entitymanager entitymanager public void insertuser user entitymanagerpersistuser public user loadint id return entitymanagerfinduserclass id i have the following springconfigxml in srcmainresourcesxml version10 encodingutf8beans xmlns xmlnsxsi xmlnsaop xmlnscontext xmlnstx xsischemalocation contextcomponentscan basepackagecommydomainorm bean identitymanagerfactory classorgspringframeworkormjpalocalcontainerentitymanagerfactorybean property namepersistencexmllocation valueclasspathpersistencexml property namepersistenceunitname valueuserpersistenceunit property namedatasource refdatasource property namejpavendoradapter refjpavendoradapter property namejpadialect refjpadialect bean bean idjpavendoradapter classorgspringframeworkormjpavendorhibernatejpavendoradapter property namedatabase valuehsql property namedatabaseplatform valueorghibernatedialecthsqldialect bean bean idjpadialect classorgspringframeworkormjpavendorhibernatejpadialect bean idtransactionmanager classorgspringframeworkormjpajpatransactionmanager property nameentitymanagerfactory refentitymanagerfactory property namedatasource refdatasource property namejpadialect refjpadialect bean txannotationdriven transactionmanagertransactionmanager bean iddatasource classorgspringframeworkjdbcdatasourcedrivermanagerdatasource property namedriverclassname valueorgpostgresqldriver property nameurl valuejdbcpostgresqllocalhost5432mydb property nameusername valuemy user property namepassword value beanbeansand last but not least the following srcmainresourcespersistencexmlxml version10 encodingutf8persistence xmlns version10 persistenceunit nameuserpersistenceunit transactiontyperesource local classcommydomainormuserclasspersistenceunitpersistence what do i need to do to resolve this error,['java'] +603854,is this a generic function pointer and is it dangerous learning and messing up with function pointers i noticed a way to initialize void function pointers and cast them yet although i donat receive any warning or error either with gcc or vsas compiler i wanted to know whether it was dangerous or a bad practice to do this as i do not see this way of initializing function pointers often on the internet moreover do we call this generic function pointerinclude stdiohinclude stdinthinclude coniohdefine pause getchuint16 t addconst uint16 t x const uint16 t y return x ychar chruint8 t test return chartestint mainvoid voidtest voidadd const uint16 t x 1 y 1 uint16 t value uint16 ttestx y test voidchr printfdn addx y 2 printfdn value 2 printfcn chartest100 d pause return 0,['c'] +603907,viewpagerfragmentpageradapetfragmentslistview insanely slow app i have a viewpager in my layout that viewpager holds a set of 10 fragments each fragment has a list view which is asynchronously populated i m currently using fragmentpageradapter as adapter for the viewpager and the api calls to populate the list view is done in oncreateview of each fragment the swipe is insanely slow and app closes itself because of the memory issues how to achieve smooth and responsive viewpagerlistview like google play does smooth swiping good cache of list items,['android'] +604003,angularjs ngclick how to get this data let say i have this item in the list with angular ngclick eventa dataid102 ngclickdeletedeleteahow can i get the data info if this then scopedelete function var id thisattrdataid consolelogid i want to get 102 as the result if confirmare you sure to delete contactsgrid trdataid id hideslow,['jquery'] +604071,best andor fastest way to create lists in python in python as far as i know there are at least 3 to 4 ways to create and initialize lists of a given sizesimple loop with appendmy list for i in range50 my listappend0simple loop with my list for i in range50 my list 0list comprehensionmy list 0 for i in range50list and integer multiplicationmy list 0 50in these examples i do not think there would be any performance difference given that the lists have only 50 elements but what if i need a list of a million elements would the use of xrange make any improvement which is the preferredfastest way to create and initialize lists in python,['python'] +604094,how to throttle requests in a web api i am trying to implement request throttling via the following best way to implement request throttling in aspnet mvci have pulled that code into my solution and decorated an api controller endpoint with the attribute routeapidothisidacceptverbspostthrottlename testthrottle message you must wait n seconds before accessing this url again seconds 5authorizepublic httpresponsemessage dothisint id this compiles but the attributes code does not get hit and the throttling does not work i do not get any errors though what am i missing,"['c#', '.net']" +604149,xml validation against xsd 11 with xerces in java i have installed xerces through mavendependencies dependency groupidjunitgroupid artifactidjunitartifactid version411version scopetestscope dependency dependency groupidorgjdomgroupid artifactidjdomartifactid version202version dependency dependency groupidxercesgroupid artifactidxercesimplartifactid version2110version dependency dependenciesi then tried the code given in this example from the xerces faq to validate a xml file against a schema in version 11 this is my codeprivate static void validatefilefile xmlfile file xsdfile throws saxexception ioexception 1 lookup a factory for the w3c xml schema language schemafactory factory schemafactorynewinstance 2 compile the schema file schemalocation xsdfile schema schema factorynewschemaschemalocation 3 get a validator from the schema validator validator schemanewvalidator 4 parse the document you want to check source source new streamsourcexmlfile 5 check the document try validatorvalidatesource systemoutprintlnxmlfilegetname is valid catch saxexception ex systemoutprintlnxmlfilegetname is not valid because systemoutprintlnexgetmessage the code only yields this exceptionjavalangillegalargumentexception no schemafactory that implements the schema language specified by could be loadedat javaxxmlvalidationschemafactorynewinstanceschemafactoryjava204at examplexmlxsdvalidatorvalidatefilexsdvalidatorjava65seems like i failed to configureinstall xerces correctly please help me get this working the xml files force me to use the schema in 11 i got a normal validator for 10 running but i have huge problems with this i appreciate every hint,['java'] +604178,why would rvm install ruby210 install preview1 i just tried to install ruby 21 and instead got 21 preview 1 this seems crazy to me 21 is out why would rvm assume that when i say rvm install ruby210 that i really mean rvm install ruby210preview1 why would it not match the exact version i specified instead of one which begins with that substring,['ruby'] +604197,django too many values to unpack when calling userobjectsget in django 16 i have defined a custom user model but for some reason now when i create a superuser and try to get it or access the django admin as that superuser i get this valueerror too many values to unpack i have perused the many similar questions on so about this error and have not found anything that fits my particular issue i cannot figure out what would be wrongin my custom create user and create superuser methods in the custom manager i do pass an extra field but that field does not actually make it into the model so i cannot see why that would be causing a problemadditionally when trying to access the admin i get a slightly different error attributeerror userobject has no attribute has module permsfull tracebacktraceback most recent call last file console line 1 in module file cusersjjcodingvirtualenvstcr5venvlibsitepackagesdjangodbmodelsmanagerpy line 151 in get return selfget querysetgetargs kwargs file cusersjjcodingvirtualenvstcr5venvlibsitepackagesdjangodbmodelsquerypy line 298 in get clone selffilterargs kwargs file cusersjjcodingvirtualenvstcr5venvlibsitepackagesdjangodbmodelsquerypy line 590 in filter return self filter or excludefalse args kwargs file cusersjjcodingvirtualenvstcr5venvlibsitepackagesdjangodbmodelsquerypy line 608 in filter or exclude clonequeryadd qqargs kwargs file cusersjjcodingvirtualenvstcr5venvlibsitepackagesdjangodbmodelssqlquerypy line 1198 in add q clause self add qwhere part used aliases file cusersjjcodingvirtualenvstcr5venvlibsitepackagesdjangodbmodelssqlquerypy line 1232 in add q current negatedcurrent negated file cusersjjcodingvirtualenvstcr5venvlibsitepackagesdjangodbmodelssqlquerypy line 1035 in build filter arg value filter exprvalueerror too many values to unpackcustomer user modelclass userobjectabstractbaseuser email modelsemailfieldmax length254 uniquetrue db indextrue username field email required fields student or business tells us whether the userobject is a business or student property def typeself if hasattrself studentlower return s elif hasattrself businesshandlerlower return b else raise typeerror userobject has neither student nor businesshandler connected gets us the actual userobjects accompanying object whether student or business property def get profile objectself if selftype s return getattrself studentlower elif selftype b return getattrself businesshandlerlower to take advantage of refactoring property def is studentself return selftype s property def is busineself return selftype b def relevant itemself input tuple takes in a tuple of options for return in form student business other returns the appropriate option depending if not 2 leninput tuple 3 raise typeerror relevant item requires a tuple of 2 or 3 else if selftype s return input tuple0 elif selftype b return input tuple1 else return input tuple2 if leninput tuple 3 else none signup date modelsdatetimefieldauto now addtrue admin stuff is active modelsbooleanfielddefaulttrue is admin modelsbooleanfielddefaultfalse is staff modelsbooleanfielddefaultfalse settings verified modelsbooleanfielddefaultfalse accepted tos modelsdatefielddefaultdatetimedatetimetoday date so can find who need to update when change tos temporary hashesstrings verification id modelscharfielduniquetrue defaultlambda random string20 max length20 reset password code modelscharfieldblanktrue defaultlambda random string20 max length20 def get new reset password codeself selfreset password code random string20 selfsave return selfreset password code def new verification idself selfverification id random string20 try selfsave except integrityerror selfnew verification id objects userobjectmanagercustom user managerclass userobjectmanagerbaseusermanager staticmethod def create accompanying modeluser student or business this creates the appropriate accompanying student or businesshandler model when a new userobject is created if student or business s s modelsget modelstudent student new item sobjectscreateuser objectuser userobject creationtrue new itemsave elif student or business b b modelsget modelbusiness businesshandler new item bobjectscreateuser objectuser userobject creationtrue new itemsave else msg must be student or businesshandler raise valueerrormsg def create userself email password student or business normalize student or business if student or businesslower in s student student or business s elif student or businesslower in b business businesshandlerlower student or business b check if an email was provided if not email msg users must have an email address raise valueerrormsg if a student check if a edu email address was provided if email and student or business s if not emailendswithedu msg students must sign up with a edu email address raise valueerrormsg user selfmodel emailuserobjectmanagernormalize emailemail removed the below because calculating that differently student or business student or business userset passwordpassword usersaveusingself db selfcreate accompanying modeluser student or business return user def create superuserself email password student or business user selfcreate useremail password student or business useris admin true useris staff true useris superuser true usersaveusingself db return userthanks,['python'] +604199,hibernate native vs hibernate jpa hibernate website says there is a native hibernate api as well as an implementation of jpa what is the difference between the native api and jpa implementation advantages thisadvantagesi am working on a spring mvc application using tomcat as the container and mysql for persistence i have used doctrine and entity for php and net respectively in the past using the code first approach i would like to have something similar with java i am newer to spring and never used hibernate my team would like to use an orm and hibernate seems to be the most popular were not sure how hibernate is going to workout or whether we should use native or jpa api the application will be data driven data entry reporting etci have read that using jpa makes its easier to switch to another jpa implementation although i do not know if that will be needed or not,['java'] +604279,storing time information timezone required i am curious to know if what i am considering is bad practice or if since this is a specific and deliberate choice it is actually a decent ideai want to store information for dates for events that occur in specific cities i want to store that data as utc timestampswouldnt it be a good idea to simply store the timestamp and the city idcountry id which is associated with a specific timezone rather than storing the timezone for each eventi ask because timezones can change but city ids would never change in the db once the server is synced with the latest timezone in the unlikely event of a timezone change the event would be independent and unaffected by that change however say a timezone changes its boundaries then events that occurred in that timezone previously could be outside of itdoes it seem unwise to do this i am just wondering and i have been scouring for best practices but in this case this actually seems like an ok idea this works particularly because the application design model would never change events will always be associated with a specific citythe basic flow would beevent data with datelocation comes into the system in a standard format like iso8601 ymmdd stringsystem converts date to utc timestamp and stores the date with the event using that timestamp and the city id for the eventwhen a user requests to view that event the system pulls the timestamp and city information associated with that event and uses the citys timezone to format the date accordingly on thisplayis this a terrible idea is there a benefit to this and is the concept of storing the tz offset the same idea to eliminate this issue,"['php', 'mysql']" +604318,purecssio pure grid height thisplays different in firefox i am using the pure grids of purecss i have a pureg with three pureu13 containing a few paragraphs the problem is that there is a difference in thisplay between chromeie and firefox when one of the units is longer than the othersi have tried to use jquery to calculate the highest pureu13 and setting the rest to this height but it did not work out as expected since this grid has to be responsive as well using puregrdoes anybody know how to make firefox produce the same output,['css'] +604319,html5 rocks node js serversentevents sse example not working link to article the nodejs sse server is not working in that example i end up with an open connection to events but no response is received by the browsersseserverjsvar http requirehttpvar sys requiresysvar fs requirefshttpcreateserverfunctionreq res debugheadersreq if reqheadersaccept reqheadersaccept texteventstream if requrl events sendssereq res else reswritehead404 resend else reswritehead200 contenttype texthtml reswritefsreadfilesync dirname ssenodehtml resend listen80function sendssereq res reswritehead200 contenttype texteventstream cachecontrol nocache connection keepalive var id new datetolocaletimestring sends a sse every 5 seconds on a single connection setintervalfunction constructsseres id new datetolocaletimestring 50 constructsseres id new datetolocaletimestringfunction constructsseres id data reswriteid id n reswritedata data nnfunction debugheadersreq sysputsurl requrl for var key in reqheaders sysputskey reqheaderskey sysputsnnssenodehtmldoctype htmlhtmlhead meta charsetutf8 headbody script var source new eventsourceevents sourceonmessage functione documentbodyinnerhtml edata br scriptbodyhtml,['javascript'] +604328,findfragmentbytag returns null after perform a fragmenttransaction using replace method my android app consists three fragments a b and c they are loaded in the two containers defined in the mainactivity layout when the app is started it shows the fragmenta loaded in the left container and the fragmentc in the right container if you press the button in the fragmenta a fragmenttransaction changes fragmentc by fragmentb at the moment everything ok but the trouble appears when i try to get a reference to the loaded fragmentb using findfragmentbytag because it returns null i have used the method replace in the fragmenttransaction and i have finished it with commit but there is not way to call fragmentb method my codemainactivityjava public class mainactivity extends activity static string fragmenttag fragmentb tag overrideprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main adds the left containers fragment getfragmentmanagerbegintransactionaddridleft container new fragmentacommit adds the fragment a to the left container adds the right containers fragment getfragmentmanagerbegintransactionaddridright container new fragmentccommit adds the fragment c to the right container called when the button activate fragment b is pressed public void buttonlistenerview v fragmenttransaction ft getfragmentmanagerbegintransaction ftreplaceridright container new fragmentbfragmenttag replaces the fragment c previously in the right container with a new fragment b ftcommit finishes the transaction here the app crashes javalangnullpointerexception findfragmentbytag returns null fragmentb getfragmentmanagerfindfragmentbytagfragmenttagtestview fragmentbjavapublic class fragmentb extends fragment public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate return inflaterinflaterlayoutfragment b containerfalse gets a reference to the text fragment b textview and calls its method settext changing it does not work text by it works public void testview textview tv textviewgetviewfindviewbyidridtext fragment b tvsettextit worksactivity mainxmlxml version10 encodingutf8linearlayout xmlnsandroidandroidlayout widthmatch parentandroidlayout heightmatch parentandroidorientationhorizontal framelayout androidididleft container androidlayout width0px androidlayout weight50 androidlayout heightmatch parent framelayout androidididright container androidlayout width0px androidlayout weight50 androidlayout heightmatch parentlinearlayoutfragment bxmlxml version10 encodingutf8linearlayout xmlnsandroidandroidlayout widthmatch parentandroidlayout heightmatch parentandroidorientationvertical androidlayout margin5sptextview androidididtext fragment b androidtextit does not works androidlayout widthmatch parent androidlayout heightwrap contentlinearlayoutplease help me i am a beginner in android development,['android'] +604334,bitmapimages imageopened event not fired in background agent as in the title the event is not fired when the code is executed in the backgroundagent while it works fine when i execute it in my main appheres my codevar background new bitmapimagenew uriuri urikindabsolute createoptions bitmapcreateoptionsnone backgroundimagefailed s e debugwritelinee nothing happens here so i guess that there is no error in the image loadingbackgroundimageopened s e debugwritelineimageopened this line is never printed no the event is never throwneverthing is running in a thispatcher thread and i am trying to load a remote image i cannot cache it because it is a dynamic image generated by a php pageany hinteditheres the code based on l3arnons suggestionvar backgroundimage new bitmapimage createoptions bitmapcreateoptionsnone backgroundimageimageopened s e debugwritelineimageopenedbackgroundimageurisource new uriuristill no success though,['c#'] +604363,nodejs heroku deployment fails to exec postinstall script to install bower deployment of my nodejs mean app to heroku fails with the following errors i cannot figure out what is wrong with the bower install here is the error message2606 info postinstall 2607 verbose unsafeperm in lifecycle true2608 info failed to exec postinstall script2609 error postinstall node modulesbowerbinbower install2609 error exit status 12610 error failed at the postinstall script2610 error this is most likely a problem with the app package2610 error not with npm itself2610 error tell the author that this fails on your system2610 error node modulesbowerbinbower install push rejected failed to compile nodejs apphere is my bowerjson name mean version 100 dependencies bootstrap angular angularresource angularcookies angularuiutils angularbootstrap json3 jquery angularuirouter angularanimate movejs gitgithubcomvisionmediamovejsgit033 animatecss nganimateanimatecss angularlocalstorage 017 jquerynicescroll resolutions angular 124 here is my packagejsonscripts start node node modulesgruntclibingrunt test node node modulesgruntclibingrunt test postinstall node modulesbowerbinbower install,['javascript'] +604508,laravel redirectwithinput as the title says i am trying to redirect back to previous page with input data like thisreturn redirectbackwithinputit works as intended for regular input but not for files is there a workaround for this so that after the redirect the previous file is selected again,['php'] +604579,laravel 4 queues and multiple listeners if i am running beanstalk with supervisor on a server with a laravel 4 application and i want it to process all queues asynchronously as many as it can at the same time can i have multiple listeners running at the same time will they be smart enough to not take the same todo item from the queue or will they all reach for the same one at the same time and thus not work in the way i am wanting in short i want to use queues to process multiple tasks at a time can this be donephp artisan queuelisten php artisan queuelisten php artisan queuelisten,['php'] +604637,is there a c variable type that imitates a temporary this is really a terribly silly question to which the answer is probably a simple no but i am going to ask in case there is because it would be quite nicei can do this behaviour is exactly as desiredstruct a int x a inca a ax 1 return ainc 1 where the fact that 1 is a temporary forces that it would not be reused because it has been left invalid by inc because of the use of the move constructor please correct me if i am wrong about thisbut what if i am bad at remembering what 1 was supposed to stand for so i make a variable for it but i still want to force the requirement that it cannot be used twice i am trying to make it just like a temporary but nameda a 1 incaincano variation of reference type for a will lead the compiler to complain about the double use but the move constructor has been precluded by a not being a temporaryis there a solution,['c++'] +604639,convertchangetype how to convert from string to enum public static t converttstring value return tconvertchangetypevalue typeoft public enum category empty name city country category catconvertcategory1name1when i call convertchangetype the system throws an exception on the impossibility of conversion from string to categoryhow to do the conversionmaybe i need to implement any converter for my type,['c#'] +604740,qt how to catch an error with system call i am building a gui application where i do a system call and call for gnuplot to run a script now i want to build in an error message that says when something is wrong eg gnuplot is not installed or in the wrong pathso i have been thinking about just putting out a qmessagebox but i do not know how i can check whether the system call succeeded or notifsystem call did not work qmessagebox msgbox msgboxsetwindowtitleerror msgboxseticonqmessageboxcritical msgboxsettextgnuplot was not installed msgboxexecmy system call looks like thissystemgnuplot scripttxtany suggestions,['c++'] +604776,java 8 method references validation of methods at compile time i would like to use the new method references of java 8 to provide more validation of some code at compile timelet us say i have a validatemethod method which requires one parameter a method to be validated for example validatemethodfoo methodahere the method would validate that foomethoda exists at runtimeusing method references i would like to be able to do validatemethodfoomethodaso the existence of the method would be validated at compile time the problem is that it seems method references have to be assigned to a functional interface for example this object dummy foomethodagenerates the error the target type of this expression must be a functional interfaceif i create a functional interface that has a compatible signature with the methoda method it works functionalinterfacepublic interface myfunctionalinterface public string runmyfunctionalinterface dummy foomethodanow the existence of foomethoda is validated at compile time which is what i want butlet us say validatemethod does not know the signature of the method it has to validate is it still possible to implement it thenlet us pretend we do not care about ambiguity and overloaded methods is it possible in java 8 to implement some kind of method which would trigger the validation of any method referencefor example public class foo public string methoda return methoda public string methodbstring str return methodb public string methodcstring str int nbr return methodc foo foo new foovalidatemethodfoomethoda compilevalidatemethodfoomethodb compilevalidatemethodfoomethodc compilevalidatemethodfoomethodd errorwould it be possible to implement validatemethod in such a way that any method reference would be accepted so the existence of the method would be validated at compile time i tried public void validatemethodobject objbut it does not work the target type of this expression must be a functional interfacethis would work functionalinterfacepublic interface myfunctionalinterface public string runpublic void validatemethodmyfunctionalinterface parambut only for methoda of the foo class because its signature no parameter is compatible with the functional interfaces method signaturewould it be possible to implement the functional interface myfunctionalinterface in such a way that any method reference would be a valid parameter and therefore would be validated at compile timeany other ways you see to validate the existence of a method at compile time,['java'] +604798,does the type of quotes matter when using use strict i was wondering since i am trying to use use strict does it matter if i go with use strict or use strict is any of those a amore correcta option,['javascript'] +604834,trouble with tabs and translucent statusbarnavigation for android 44 i want to add translucent statusbar and navigation to my app for kitkat and on most places it works welli have a theme with item nameandroidwindowtranslucentnavigationtrueitem item nameandroidwindowtranslucentstatustrueitemand in my layouts i have androidfitssystemwindowstruefor normal activities this works fine but i have two activities that make trouble the content is shown behind the statusbar and my actionbarone of them is the preferenceactivity were i fixed it by adding findviewbyidandroidridlistsetfitssystemwindowstruethe second is an activity with actionbarnavigation mode tabs and there i cannot find the right target for the setfitssystemwindowstrue calli tried with findviewbyidandroidridcontent and findviewbyidandroidridtabcontent i also tried to add the xml attribute to the layout of my fragment but no success,['android'] +604861,is there any way to building static qt with static openssl original question was slightly different but part of a more major questioni am trying to build qt 52 as static with static openssl on windows my final goal is to ship a single binary without the need to provide libeay32dll and ssleay32dll with it however it seems to me that this is impossible i built static qt with static openssl libs but it seems like qt is outright ignoring the libs provided and always searches for dllsthis answer also suggests that qtnetwork always searches for dlls and ignores everything else but it also states that two options are to compile openssl into qt but this does not seem to be the casecan someone provide a definitive answerthis is my qt configureconfigure static qmake opensource nomake examples opengl desktop platform win32msvc2010 openssl i cgitopensslbuildinclude l cgitopensslbuildlib openssl libsllibeay32 lssleay32 lgdi32,['c++'] +604898,copy constructor for abstract class i have an abstract class named aclass in the same package i have anotherclass in which i have an arraylist of aclass objects in the copy constructor of anotherclass i need to make a duplicate of aclass objects inside the arraylist the problemi cannot create a copy constructor in aclass because it is an abstract class and i cannot know the name of the class which will inherit by aclass actually in this project no object will inherit from this class but this project will be used as a library by other projects which will provide a class child of aclass is there an error in my design or is there a solution to this problemedit heres some codepublic class anotherclass private arraylistaclass list copy constructor public anotherclassanotherclass another copy all fields from another thislist new arraylistaclass forint i 0 i anotherlistsize i option 1 thislistaddnew aclassanotherlistgeti problem cannot instantiate aclass as it is abstract option 2 thislistaddanotherlistgetisomekindofclone problem i am thinking about it seems to be what dasblinkenlight is suggesting below,['java'] +604901,how do i retrieve the progress of a native html form submission i am doing some frontend stuff for a rails app and i do not get to mess with the backend architecture basically i am supposed to allow users to upload a file and make that submission essentially go straight to amazon through a form handled by carrierwave if youve ever tried to do this same thing with ajax youll know it is virtually impossiblethat puts me here i need to be able to call submit on an html form element and then hook into the progress of the upload as if i were listening for the progress event on an xmlhttprequestforgive me for not showing tons of code i am really just looking for two very simple thingsis it possible to trap the forms native progress eventif so whats the basic technique is it something simple like formaddeventlistenerprogress function that does not work by the way,"['javascript', 'html']" +604909,add reference shdocvw in c project using visual c 2010 express i am following a tutorial which creates a bho using ms visual studio 2010 and c in order to run the tutorial code i have to add this reference in my projectusing shdocvw but it is not available in net or com section in add referencesso i wanted to ask is this namespace not available in microsoft visual c 2010 express and if it is available how to add it this is my halfway project codeusing systemusing systemcollectionsgenericusing systemlinqusing systemtextnamespace ieplugin comvisibletrue interfacetypecominterfacetypeinterfaceisiunknown guidfc4801a32ba911cfa22900aa003d7352public interface iobjectwithsite preservesig int setsitemarshalasunmanagedtypeiunknownobject site preservesig int getsiteref guid guid out intptr ppvsite comvisibletrue guid2159cb25ef9a54c1b43ce30d1a4a8277 classinterfaceclassinterfacetypenonepublic class bho iobjectwithsite private webbrowser webbrowser public int setsiteobject site if site null webbrowser webbrowsersite webbrowserdocumentcomplete new dwebbrowserevents2 documentcompleteeventhandler thisondocumentcomplete else webbrowserdocumentcomplete new dwebbrowserevents2 documentcompleteeventhandler thisondocumentcomplete webbrowser null return 0 public int getsiteref guid guid out intptr ppvsite intptr punk marshalgetiunknownforobjectwebbrowser int hr marshalqueryinterfacepunk ref guid out ppvsite marshalreleasepunk return hr public void ondocumentcompleteobject pthisp ref object url htmldocument document htmldocumentwebbrowserdocument here are the errors attachederror 1 the type or namespace name shdocvw could not be found are you missing a using directive or an assembly referenceerror 2 the type or namespace name webbrowser could not be found are you missing a using directive or an assembly reference,['c#'] +604940,alternative for formatterformatipaddressint i would used this code in my application but the warning says its the method formatipaddressint from the type formatter is deprecatedandroidtextformatformatterformatipaddressmwifimanagergetconnectioninfogetipaddresswhats the quick fix for this,['android'] +604947,group or batch requests with afnetworking 20 i am trying to figure out what is the best practice to group or batch a number of get requests using afnetworking 20 all the get requests need to be completed before the code can continue but they do not have to run one after the other right now for single requests i am using afhttprequestoperationmanager see also here subclass afhttprequestoperationmanager one possibility is described here using a thispatch group how to batch request with afnetworking 2 but that is for afhttpsessionmanager which is ios7 only my app still targets ios6 as well so i need to use afhttprequestoperationmanageris using a thispatch group the way to go or is there something built in in afnetworking that i have overlooked and can use for thisedit still do not know what the correct way is for instance how do i use a group with afhttprequestoperation i have tried the following but the final nslog done searching is always shown first before all the responses come inthispatch queue t thispatch queue thispatch get global queuethispatch queue priority default 0thispatch group t thispatch group thispatch group createfor entry e in selfentries thispatch group asyncthispatch group thispatch queue nsstring querystring e getquerystring nsurl url nsurl urlwithstring querystring nsurlrequest request nsurlrequest requestwithurlurl afhttprequestoperation operation afhttprequestoperation alloc initwithrequestrequest operationresponseserializer afhttpresponseserializer serializer operationcompletiongroup thispatch group operation setcompletionblockwithsuccessafhttprequestoperation operation id responseobject nslog responseobject failurenil operation start thispatch group notifygroup thispatch get main queue nslogdone searching,['ios'] +604989,unable to create autoincrementing primary key with flasksqlalchemy i want my models primary key to be an autoincrementing integer here is how my model looks likeclass regiondbmodel tablename regions id dbcolumndbinteger primary keytrue autoincrementtrue name dbcolumndbstring100 parent id dbcolumndbinteger dbforeignkeyregionsid parent dbrelationshipregion remote sideid primaryjoinregionparent idregionid backrefsubregions created at dbcolumndbdatetime defaultdbfuncnow deleted at dbcolumndbdatetimethe above code creates my table but does not make id autoincrementing so if in my insert query i miss the id field it gives me this error error null value in column id violates notnull constraint so i changed the id declaration to look like thisid dbcolumndbinteger dbsequenceseq reg id start1 increment1 primary keytruestill the same error what is wrong with the above code,['python'] +605030,why return anything but self from iadd pythons documentation on the methods related to the inplace operators like and or as it calls them the augmented arithmetic assignments has the following to saythese methods should attempt to do the operation inplace modifying self and return the result which could be but does not have to be self if a specific method is not defined the augmented assignment falls back to the normal methodsi have two closely related questionswhy is it necessary to return anything from these methods if the documentation specifies that if implemented they should only be doing stuff inplace anyway why do not the augmented assignment operators simply not perform the redundant assignment in the case where iadd is implementedunder what circumstances would it ever make sense to return something other than self from an augmented assignment methoda little experimentation reveals that pythons immutable types do not implement iadd which is consistent with the quoted documentation x 5 x iadd traceback most recent call last file stdin line 1 in moduleattributeerror int object has no attribute iadd and the iadd methods of its mutable types of course operate inplace and return self list1 list2 list1 list1 123 list1 is list2trueas such i cannot figure out what the ability to return things other than self from iadd is for it seems like it would be the wrong thing to do in absolutely all circumstances,['python'] +605085,why are virtual functions handled at runtime surely the compiler is smart enough to deduce exactly what function you want for some cases yet how come other cases require runtime support,['c++'] +605153,why ifkey in null throw exception while forkey in null does not it is the language design flaws on it from a language design perspective whyifk in nulltypeerror cannot use in operator to search for k in nullbutfork in nullprints undefinedin ecmascript spec1187 the in operator1264 the forin statementis it the language design flaw,['javascript'] +605171,how to listen to any keyboard on the whole application we are trying to build android activity that listen to any key press either character or command something like custom edittextis there something like keyboard hook in windows os available on androidis it possible to listen for all key pressed for all controls edittext and other controlscould this be achieved by an activity that runs in the backgroundeditas for security we want to get keyboard events only for our app activity ex when our activity is shown and focused,"['java', 'android']" +605259,creating an md5 object in python with an initial value i have some code that needs to hash certain data then later on in another process continue the hash with more data is there a way to create an object either from the md5 or hashlib modules which has a different initial value than d41d8cd98f00b204e9800998ecf8427ewhat i mean is something similar tox md5from digest0123456789abcdefxupdatenew datanote the less desirable approach would be to save the original md5 object and restore it later but afaik hash objects are nonpickleable,['python'] +605374,full repl not supported i get an error when trying to use artisan command tinker for example i would like to add a user in my terminal i type php artisan tinker but when i enter it i get a warning sayingfull repl not supported falling back to simple shell what could the problem be for this error is it my terminal php permissions or something elseafter i get the warning i can type to create new user but it does not save it to the database i am not sure what repl is,['php'] +605386,speed up autoreload in meteorjs after saving a file with new changes in meteorjs the server will restart and the browser will window reloadquestion sometimes it takes longer than usual to reload after saving the file and this appears to be random is there a way to trigger the autoreload more quicklyit appears that the server restart quickly but the browser reload much more slowelyafter the meteor server have restarted the webpage becomes unresponsive for 30 sec and the network tab shows websocket pendingi am using meteor 0701 with meteorite 0616 on nodejs v01022 on mac osx connecting to a remote mongodb server,['javascript'] +605398,googles iab api3 getskudetails method returns failed 5 developer error i am trying to incorporate googles inappbilling api3 in my code that has been using api2 my call to mhelper the iabhelper object succeeds so i am connecting to googles servers it appears that i can determine owned items as my queryinventoryfinishedlistener returns a valid inventory with all my purchased items i am also able to execute a purchase however querying for sku details fails getskudetails here is all iabhelperrelated logcat output from eclipse i removed my package name and product skus leading up to the failure1231 114704642 diabhelper13633 starting inapp billing setup1231 114704832 diabhelper13633 billing service connected1231 114704832 diabhelper13633 checking for inapp billing 3 support1231 114704832 diabhelper13633 inapp billing version 3 supported for comx1231 114704832 diabhelper13633 subscriptions available1231 114704842 diabhelper13633 starting async operation refresh inventory1231 114704842 diabhelper13633 querying owned items item type inapp1231 114704842 diabhelper13633 package name comx1231 114704842 diabhelper13633 calling getpurchases with continuation token null1231 114704912 diabhelper13633 owned items response 01231 114704912 diabhelper13633 sku is owned comxitem one1231 114704922 diabhelper13633 sku is owned comxitem twoand 45 other items1231 114705012 diabhelper13633 continuation token null1231 114705012 diabhelper13633 querying sku details1231 114705012 diabhelper13633 getskudetails failed 5developer error1231 114705012 diabhelper13633 ending async operation refresh inventoryit does not seem like a signing issue since i can successfully connect and make a purchasehas anybody else been having issues where getskudetails fails with the developer error message while other aspects of inappbilling workthanks for your time,['android'] +605476,how do you specify a single test to be run by play frameworks testonlycommand it is pretty clear that one would like to pass a single test as an argument to testonly so that you can do what it is documentation says run one testbut how do you do this in java you probably have a class usertest that extends withapplication and defines a bunch of tests on the user model using test for eachyou would like to say testonly modelsusertestcreateauserbut testonly will tell youinfo passed total 0 failed 0 errors 0 passed 0info no tests to run for testtestonlysuccess total time 0 sso how do you run only one test,['java'] +605501,unable to cast object of type castleproxiesxproxy to type x in wpf designer i have recently thiscovered the very useful design time attributes from blend for a wpf component which among other things allows you to set a datacontext only at design time awesomecombined with the designinstance attribute you can set a type to be automatically created and bound to during design time allowing you to use the visual studio designer with some context as to what your wpf component will actually look like at run time its really nice and i wish it had not taken me so long to thiscoverobviously because i am here and not living it up in programmer heaven i have encountered a problem while using these design time attributesi have created a design time wrapper around one my viewmodels which has a parameterless constructor so it can be created by the designer inside its constructor it uses nsubstitute to mock out all of the dependencies injected into the viewmodel it inherits fromusing this design time class in the designer results in an error much like the followingunable to cast object of type castleproxiesxproxy to type xwith the x being replaced with one of my injected dependenciesyou can use the following minimal set of code to reproduce the problem create a wpf application in vs2013 targeting net framework 451 it might happen in previous versions too i do not know with the following files in itviewxamlpage xclassdesigntimensubstituteissueviewsview xmlns xmlnsx xmlnsmc xmlnsd xmlnsdesigntimensubstituteissue views designtimeclrnamespacedesigntimensubstituteissueviewsdesigntime mcignorabled ddatacontextddesigninstance typedesigntimensubstituteissue views designtimedesigntimeviewmodel isdesigntimecreatabletrue grid textblock textbinding message fallbackvaluedesign time message failed using fallback gridpageviewmodelcs using designtimensubstituteissueservicesnamespace designtimensubstituteissueviewmodels public class viewmodel public viewmodelxdependency dependency dependency dependency private readonly xdependency dependency public string message get protected set designtimeviewmodelcsusing designtimensubstituteissueservicesusing designtimensubstituteissueviewmodelsusing nsubstitutenamespace designtimensubstituteissueviewsdesigntime public class designtimeviewmodel viewmodel public designtimeviewmodel basesubstituteforxdependency message this is a design time message xdependencycsnamespace designtimensubstituteissueservices public interface xdependency compile close and reopen the solution and open viewxaml in the designer it will work just fine then close the designer rebuild solution and open viewxaml in the designer again and you will get the following errorunable to cast object of type castleproxiesxdependencyproxy 1 to type designtimensubstituteissueservicesxdependencywhen this error occurs the designer stops using the specified designtimeviewmodel and falls back to having no datacontext at allthe only way to fix this is to close and reopen the solutioni suspect i know what is happening but i do not know why its happening or how to fix iti think that on the first compile the designer is obtaining a reference to the assembly and caching it when the second compile occurs the assembly is rebuilt and is mostly the same but the nsubstitute proxy is regenerated with a new suffix like castleproxiesxdependencyproxy 2 or something which was not in the first assembly so the designer does not know that that proxy actually implements the xdependency interface this is purely conjecture on my parti can create a workaround by not using nsubstitute and manually mocking the dependencies but i am interested to see if someone can shed some light on the subject,['c#'] +605579,pycharm run configuration asking for script parameters while writing an application parsing command line arguments i would like to run it with various parametersi do not want to create a run configuration for every possible command line argument that i want my script to test with is there a way in pycharm and i guess with any jetbrains ide to make a run configuration that asks for the script parameters when executedi am currently using pycharm 31 eap,['python'] +605682,giving a border to an html table row is it possible to border a table row tr in one go instead of giving a border to individual cells td liketable cellpadding0 cellspacing0 width100 styleborder 1px rulesnone tbody tr th stylewidth 96pxcolumn 1th th stylewidth 96pxcolumn 2th th stylewidth 96pxcolumn 3th tr tr tdnbsptd tdnbsptd tdnbsptd tr tr td styleborderleft thin solid bordertop thin solid borderbottom thin solidnbsptd td stylebordertop thin solid borderbottom thin solidnbsptd td stylebordertop thin solid borderbottom thin solid borderright thin solidnbsptd tr tr tdnbsptd tdnbsptd tdnbsptd tr tbodytablethis gives a border around the given tr but it requires a border around individual cellscan we give a border to tr only in one go jsfiddle,"['html', 'css']" +605690,gradle configuration for multimodule project with shared dependencies make a first project with gradle so i look at spring gradle hibernate projects how they organize gradle files and start make my own but cannot find mistake why my configuration does not work subprojects cant resolve dependencyso project treeroot project foobar project foobarapp project foobarapeople project foobarapeoplepeopleapi project foobarapeoplepeoplecore project foobarapeoplepeopledata project foobarapeoplepeoplerest project foobarapprealtor project foobarstarter project foobarsystem project foobarsystemfoobarsystemjpa project foobarsystemfoobarsystemneo4j project foobarsystemfoobarsystempersistence project foobarsystemfoobarsystemrepository project foobarsystemfoobarsystemtxthe problem when i make foobarsystemjpagradle file with set of dependences etc it is not work no dependecies can be reach for this module but when in root foobar buildgradle make a set of deps for foobarsystemjpa subproject it work fine whymy root buildgradleconfigurationsall check for updates every build resolutionstrategycachechangingmodulesfor 0 secondsconfigureallprojects project group comfoobar version 001snapshot apply from rootdirdependenciesgradle apply plugin maven apply plugin idea extgradlescriptdir rootprojectprojectdirgradle apply from gradlescriptdirtaskgradleconfiguresubprojects subproject apply plugin java sourcecompatibility 17 targetcompatibility 17 apply from rootdirdependenciesgradle repositories mavencentral maven url maven url dependencies testcompile libsjunit testcompile libsmockito testcompile group orghamcrest name hamcrestlibrary version 13 my dependeciesgradleext springversion 400release junitversion 411 hibernateversion 421final libs springframework spring core orgspringframeworkspringcorespringversion spring orm orgspringframeworkspringormspringversion hibernate entitymanager orghibernatehibernateentitymanagerhibernateversion hibernate persistence orghibernatejavaxpersistencehibernatejpa20api101final database postgresql orgpostgresqlpostgresql931100jdbc41 commons dbcp commonsdbcpcommonsdbcp14 and my settingsgradle rootprojectname foobarinclude foobarsystemfoobarsystemjpainclude foobarapeoplepeoplerestinclude foobarapeoplepeoplecoreinclude foobarstarterprojectfoobarsystemfoobarsystemjpaprojectdir rootdirfoobarsystemfoobarsystemjpa as fileprojectfoobarsystemfoobarsystemrepositoryprojectdir rootdirfoobarsystemfoobarsystemrepository as fileprojectfoobaraprojectdir rootdirfoobarapp as fileprojectfoobarstarterprojectdir rootdirfoobarstarter as filerootprojectchildreneach project projectbuildfilename projectnamegradle assert projectprojectdirisdirectory assert projectbuildfileexists assert projectbuildfileisfileso foobarsystemjpagradle that not work module can not compile cause not found any dependencydependencies compile libsspring orm compile libsspring data jpa excludemodule springjdbc excludemodule springorm compile libshibernate entitymanager compile libspostgresql compile libscommons dbcp compile projectfoobarsystemfoobarsystemtxthank you for reply for inspiration a take a look for this project upd remove some not necessary code,['java'] +605718,using tags such as bold or italic in slim let us say i have this code in htmlplorem ipsum bvolutpatb ut wisi enim ad minim veniamphow would i convert that to slim throughout all of slims documentation it never once mentions bold italic or any other inline elements i tried thisp lorem ipsum b volutpat ut wisi enim ad minim veniamas expected it just added a b to the text i also tried using tubesp lorem ipsum b volutpat ut wisi enim ad minim veniamthis gave me the exact same result plus if anyone could help i would greatly appreciate it here is just a few trials that i was trying to work out,"['html', 'ruby']" +605762,ruby require tk yields loaderror no such file to load tk i am not able to get ruby to require tk successfully i am using rvm ruby 200 activetcl86 and ubuntu 1204 lts i have run wish provided with activetcl and it seems to be workingi have looked on the rvm site and several stackoverflow questions like this one rvm ruby with tk installation osxi have tried rvm reinstall 200 enableshared enablepthread withtk withtcl several times on different versions of ruby with no successany thoughtswhen i run irb and do requiretk i get the followingloaderror cannot load such file tkfrom homebrooksrvmrubiesruby200p353librubysite ruby200rubygemscore extkernel requirerb55in requirefrom homebrooksrvmrubiesruby200p353librubysite ruby200rubygemscore extkernel requirerb55in requirefrom irb2from homebrooksrvmrubiesruby200p353binirb12in mainwhen this works i think you should get true returnedi have not tried anything else mainly because i cannot figure out what else to do i have been looking into how require works and checking the load path with ruby e i getbrooksubuntusitesdepotruby e puts homebrooksrvmrubiesruby200p353librubysite ruby200homebrooksrvmrubiesruby200p353librubysite ruby200x86 64linuxhomebrooksrvmrubiesruby200p353librubysite rubyhomebrooksrvmrubiesruby200p353librubyvendor ruby200homebrooksrvmrubiesruby200p353librubyvendor ruby200x86 64linuxhomebrooksrvmrubiesruby200p353librubyvendor rubyhomebrooksrvmrubiesruby200p353libruby200homebrooksrvmrubiesruby200p353libruby200x86 64linuxthis looks like what you would expect i think sorry for the formatting i am new to the editorfollowing up on the idea that it is a path problem i found tkrb in my files and tried the following in irb200p353 003 require homebrooksrvmsrcruby200p353exttklibtk loaderror cannot load such file tcltklibfrom homebrooksrvmrubiesruby200p353librubysite ruby200rubygemscore extkernel requirerb55in requirefrom homebrooksrvmrubiesruby200p353librubysite ruby200rubygemscore extkernel requirerb55in requirefrom homebrooksrvmsrcruby200p353exttklibtkrb6in top requiredfrom homebrooksrvmrubiesruby200p353librubysite ruby200rubygemscore extkernel requirerb55in requirefrom homebrooksrvmrubiesruby200p353librubysite ruby200rubygemscore extkernel requirerb55in requirefrom irb3from homebrooksrvmrubiesruby200p353binirb12in mainso now it is require tcltklib in the tkrb file that is causing the problem this seems to confirm that there is some issue with path or load path but a search for the file tcltklibrb turns up nothing there is a tcltklibc filei tried a few more things after a more careful reading of the output of the ruby installs via rvm there was a warning about the x11 lib not being installed and that tk wouldnt be active after the ruby build i did sudo aptget install libx11dev and then rvm reinstall 200 enableshared enablepthread withtk withtcl again this time in irb require tk caused a core dump i tried it another time and it worked i then ran a short ruby script that also uses require tk it also core dumped but worked after a few tries now it is hit or miss for both sometimes works sometimes it core dumps,['ruby'] +605782,const correctness of pythons c api it seems that the python c api is not consistent with the const correctness of character arrays for example pyimport importfrozenmodule accepts a char whereas pyimport importmodule accepts a const char the implication of all this is that in my c application that i am writing with an embedded python interpreter i sometimes have to cast the string literal that i pass to a python api call as just a char as opposed to const char and sometimes i do not for examplepyobject os pyimport importmoduleos works without the const castpyobject cwd pyobject callmethodos const castchargetcwd null accepts char not const charif i do not do the const castchar or char on the string literal i get a compiler warning about casting string literals to char here are my questionsis there an advantagereason to having some of the functions not take a const char andor why would the python api not be consistent in this my understanding is that if the function can take a string literal it cannot change the char so the const modifier would just be reinforcing this i also believe that the const thistinction is not as important for c for which the api was written than it is in c correct me if i am wrong my strength is python not cc is the lack of const correctness of the python api because it is simply not as important in c there is an old thread on the python mailing list from 20 asking the same question but it did not seem to go anywhere and it is implied the reason might be due to some compilers not supporting const since many functions now have const char this does not seem to apply anymorebecause my understanding of c is limited i am unsure if i am going about casting string literals properly the way i see it i can either one of the following i am currently doing the first method 1 use const castcharpyimport importfrozenmoduleconst castcharmymodule method 2 use charpyimport importfrozenmodulechar mymodule method 3 use char arraychar mod mymodulepyimport importfrozenmodulemodwhich is the best method do useupdateit looks like the python3 branch is slowly trying to fix the const correctness issue for example the pyimport importfrozenmodule function i use as an example above now takes a const char in python 34 but there are still functions that take only a char such as pylong fromstring,"['python', 'c++']" +605848,what is the difference between an app and application in cnet is there any difference between app and application in ci am trying to use appcurrentresources in control library which is loaded in main wpf application but it is not possible in a straight way but at the same time it is allowing me to use applicationcurrentresources could anyone help me to understand the basic differences between these two is there any flaw on using applicationcurrentresources instead of appcurrentresources,"['c#', '.net']" +605865,language level java 8 retrolambda on androidstudio 4 so someone backported lambdas for java 8 back to java 6 and 7 apparently it also works for android the project is called retrolambda i wanted to play around with this on androidstudio but it seems in recent version they have removed the ability to set java 8 as the language level so i do not get compile errors while using lambdas does anyone know a way around this i imagine it would have something to do with the fact that androidstudio is a modified intellij any help would be appreciated,['android'] +605896,angularjs isolated scope for directives without own template i want to create reusable directive in angularjs without own template i also want to have isolated scope for that directive what is the best practices for my approachwhy my example does not work as i expecti expected that i could edit obj1 and obj2 from directives separatelyhtmldiv ngcontrollermyctrl x1 obj1x y1 obj1y x2 obj2x y2 obj2y hr edit obj1 div draggable targetobj1 input typetext ngmodeltargetx input typetext ngmodeltargety div edit obj2 div draggable targetobj2 input typetext ngmodeltargetx input typetext ngmodeltargety divdivjs angularmoduleapp controllermyctrl functionscope scopeobj1 x 10 y 20 scopeobj2 x 30 y 40 directivedraggable function return scope target link functionscope el attrs consolelogscope scope plunkr,['javascript'] +605915,chosen updated not working i have a chosen dropdown i changed options content and call trigger chosenupdated but chosen do not rebuild the dropdown this is my updated select nameshortcode stylewidth 150px thisplay none classchosen select chzndone idselect shortcode option valueoption option value71837183option option value79837983optionselectand this is chosen dropdown it should be rebuilt and removed two last li ul classchznresults li idselect shortcode chzn o 1 classactiveresult style7183li li idselect shortcode chzn o 2 classactiveresult style7983li li idselect shortcode chzn o 3 classactiveresult style8208li li idselect shortcode chzn o 4 classactiveresult style8308liulthis is my jquery codeselect shortcode maskchangefunction var shortcode mask select shortcode maskval select shortcodeempty var shortcode 7x83718379838x0882088308 select shortcodeappendoption valueoption ifjqueryisarrayshortcodeshortcode mask each shortcodeshortcode mask function subkey subvalue select shortcodeappendoption valuesubvaluesubvalueoption else var full shortcode 7183798382088308 ifjqueryisarrayfull shortcode eachfull shortcode function subkey subvalue select shortcodeappendoption valuesubvaluesubvalueoption select shortcodetriggerchosenupdatedsolvedi use older version so it shouldselect shortcodetriggerlisztupdatedso dump,['jquery'] +605929,how to spyon a value property rather than a method with jasmine jasmines spyon is good to change a methods behavior but is there any way to change a value property rather than a method for an object the code could be like belowspyonmyobj valueaandreturn1expectmyobjvalueatobe1,['javascript'] +606014,why does this work returning c string literal from stdstring function and calling c str we recently had a lecture in college where our professor told us about different things to be careful about when programming in different languagesthe following is an example in cstdstring myfunction return it is meint mainint argc const char argv const char tempstring myfunctionc str char mynewstring100 who is it strcatmynewstring tempstring printfthe string s mynewstring return 0the idea why this would fail is that return it is me implicitly calls the stdstring constructor with a char this string gets returned from the function and the function c str returns a pointer to the data from the stdstringas the string returned from the function is not referenced anywhere it should be deallocated immediately that was the theoryhowever letting this code run works without problemswould be curious to hear what you thinkthanks,['c++'] +606036,linq query to get the thistinct values in a list suppose this is my member classclass member public string categoryid get set public string membername get set public int thistance get set and this is listvar list new listmemberlistaddnew categoryid 01 membernameandy thistance3listaddnew categoryid 02 membernamejohn thistance5listaddnew categoryid 01 membernamemathew thistance7listaddnew categoryid 03 membernamebackara thistance2can anyone please suggest the logic linq query to get the list having thistinctunique categoryid with shortest thistancethe output should be listaddnew categoryid 01 membernameandy thistance3listaddnew categoryid 02 membernamejohn thistance5listaddnew categoryid 03 membernamebackara thistance2,['c#'] +606073,how can i test for configureawaitfalse in a unit test for async methods i have some async library methods where it is important the configureawaitfalse be used all the way down i would like to write an nunit test that verifies that this is so how can i do that i imagine that i would have to somehow hijack the synchronization context with a custom implementation,['c#'] +606090,how to get back an overridden python builtin function when i was exploring a solution for the stackoverflow problem python use user defined string class i came with this strange python behaviordef overriden printx print overriden in the pastfrom future import print functionprint overriden printprinthello worldoutputoverriden in the pastnow how can i get back the original print behavior in python interpreter,['python'] +606171,dynamodb and tablenameoverride with prefix i am testing dynamodb tables and want to set up different table names for prod and dev environment using the prefix dev for developmenti made this test to print the table nameimport comamazonawsservicesdynamodbv2datamodelingdynamodbmapperconfigtablenameoverride tablenameoverride tbl new tablenameoverridetestwithtablenameprefixdev systemoutprintlnname tblgettablename prefix tblgettablenameprefixthis prints namenull prefixdev how come the name here is null tablenameoverride tbl new tablenameoverridetestwithtablenameprefixdev systemoutprintlnname tblgettablename prefix tblgettablenameprefixthis prints nametest prefixnullhow can i get the table name to be dev test i want to use this later to get a dev prefix for all tables in development mode like thisdynamodbtable annotation dynamodbtable myclassgetclassgetannotationdynamodbtableclass tablenameoverride tbl new tablenameoverrideannotationtablenamewithtablenameprefixdev or is there another solution to separate between dev and prod tablesi first thought of putting them in separate regions but not sure about thiscould also use thismappersaveck new dynamodbmapperconfignew tablenameoverrideisdev dev annotationtablename,['java'] +606198,how do i run the preprocessor on local headers only i want the preprocessor to read in the includes of local headers but ignore the includes of system headers to put it another way how do i get the preprocessor to skip over preprocessing directives of the forminclude hcharsequence newlinebut still process directives of the forminclude qcharsequence newlineas a code example observe the following fileinclude iostream systeminclude class ahpp localinclude string systeminclude class bhpp localint main how can i get the output of the preprocessor to beinclude iostreamclass ainclude stringclass bint main local include files may include other local include files and the preprocessor would recursively bring them all in much like it normally does it would still print all of the system file headers but it would not bring in their contentson gcc my call looks like this so far g e p maincpp where e stops after preprocessing and p excludes the generation of line markersi cannot seem to find a flag that excludes the processing of system headers,['c++'] +606230,rails migration change vs up down methods i am working through the book rails test prescriptions and during the setup it is asking me to change a migration file to the followingclass projectuserjoin activerecordmigration def selfup create table projects users force true id false do t treferences project treferences user ttimestamps end end def selfdown drop table projects users endendit seems i am using a later version on rails 400 than the book 2 or 3x and my migration file looks like thisclass projectuserjoin activerecordmigration def change endendhow do i edit the change method to do the same as the up and down methods above so far i have tried using up and down as opposed to selfup and selfdown and copying in the same code it did not work thanks,"['ruby-on-rails', 'ruby']" +606269,what magic prevents tkinter programs from blocking in interactive shell note this is somewhat a followup on the question tkinter when do i need to call mainloopusually when using tkinter you call tkmainloop to run the event loop and ensure that events are properly processed and windows remain interactive without blockingwhen using tkinter from within an interactive shell running the main loop does not seem necessary take this example import tkinter t tkintertka window will appear and it will not block you can interact with it drag it around and close itso something in the interactive shell does seem to recognize that a window was created and runs the event loop in the backgroundnow for the interesting thing take the example from above again but then in the next prompt without closing the window enter anythingawithout actually executing it ie donat press enter for example t tkintertk printnot pressing enter now not executing thisif you now try to interact with the tk window you will see that it completely blocks so the event loop which we thought would be running in the background stopped while we were entering a command to the interactive shell if we send the entered command you will see that the event loop continues and whatever we did during the blocking will continue to proceso the big question is what is this magic that happens in the interactive shell what runs the main loop when we are not doing it explicitly and why does it need to halt when we enter commands instead of halting when we execute themnote the above works like this in the command line interpreter not idle as for idle i assume that the gui wonat actually tell the underlying interpreter that something has been entered but just keep the input locally around until itas being executed,['python'] +606270,uiactivityviewcontroller with custom uiactivity thisplays color image as gray i created a custom uiactivity to thisplay in a share sheet i created an 60x60 icon png file in full color but when it is thisplayed it only shows the outline in gray i do not see what i have written incorrectly i hope someone sees what i have missed any help will be greatly appreciated here is my codeimplementation myactivitypragma mark overrides nsstring activitytype return mytype nsstring activitytitle return shareme uiimage activityimage return uiimage imagenamedmyicon 60x60png boolcanperformwithactivityitemsnsarray activityitems return yes voidpreparewithactivityitemsnsarray activityitems do something uiactivitycategoryactivitycategory return uiactivitycategoryshareend,['iphone'] +606287,change css style html5 form required attribute required message i work with rtlbootstrap for rtl project now i have any form with html5 form required attribute required message in action i have this ballon for inputi need to change like this for rtlhtmldiv classcontrols input claspan4 typetext nametitle placeholdertitle value required oninvalidthissetcustomvalidityuser id is a mustdivnotethis is not custom tooltip or ballon if we add required html tag in form input before submit form html5 form required attribute show this ballon message automaticly i need to editchangeset css for validation message how to change thisplay of required field message for show in right of input field,"['jquery', 'html', 'css']" +606310,androidsupportv4appfragmentsetuservisiblehint null pointer on app resuming i am getting a crash on the resume of the app in the fragments code i have never seen this crash myself but i have received crash reports back from users via testflighti guess there is something that i am missing as the code works fine on most machines any help would be greatly appreciatedhere is the call stackjavalangnullpointerexceptionandroidsupportv4appfragmentsetuservisiblehint in fragmentjava on line 819androidsupportv4appfragmentpageradaptersetprimaryitem in fragmentpageradapterjava on line 130androidsupportv4viewviewpagerpopulate in viewpagerjava on line 1066androidsupportv4viewviewpagerpopulate in viewpagerjava on line 914androidsupportv4viewviewpageronmeasure in viewpagerjava on line 1436androidviewviewmeasure in viewjava on line 15323androidviewviewgroupmeasurechildwithmargins in viewgroupjava on line 4924androidwidgetlinearlayoutmeasurechildbeforelayout in linearlayoutjava on line 1421androidwidgetlinearlayoutmeasurevertical in linearlayoutjava on line 698androidwidgetlinearlayoutonmeasure in linearlayoutjava on line 579androidviewviewmeasure in viewjava on line 15323androidviewviewgroupmeasurechildwithmargins in viewgroupjava on line 4924androidwidgetframelayoutonmeasure in framelayoutjava on line 315androidviewviewmeasure in viewjava on line 15323androidsupportv4widgetdrawerlayoutonmeasure in drawerlayoutjava on line 639androidviewviewmeasure in viewjava on line 15323androidviewviewgroupmeasurechildwithmargins in viewgroupjava on line 4924androidwidgetframelayoutonmeasure in framelayoutjava on line 315androidviewviewmeasure in viewjava on line 15323androidviewviewgroupmeasurechildwithmargins in viewgroupjava on line 4924androidwidgetlinearlayoutmeasurechildbeforelayout in linearlayoutjava on line 1421androidwidgetlinearlayoutmeasurevertical in linearlayoutjava on line 698androidwidgetlinearlayoutonmeasure in linearlayoutjava on line 579androidviewviewmeasure in viewjava on line 15323androidviewviewgroupmeasurechildwithmargins in viewgroupjava on line 4924androidwidgetframelayoutonmeasure in framelayoutjava on line 315comandroidinternalpolicyimplphonewindowdecorviewonmeasure in phonewindowjava on line 2155androidviewviewmeasure in viewjava on line 15323androidviewviewrootimplperformmeasure in viewrootimpljava on line 1854androidviewviewrootimplmeasurehierarchy in viewrootimpljava on line 1102androidviewviewrootimplperformtraversals in viewrootimpljava on line 1275androidviewviewrootimpldotraversal in viewrootimpljava on line 10androidviewviewrootimpltraversalrunnablerun in viewrootimpljava on line 4218androidviewchoreographercallbackrecordrun in choreographerjava on line 725androidviewchoreographerdocallbacks in choreographerjava on line 5androidviewchoreographerdoframe in choreographerjava on line 525androidviewchoreographerframethisplayeventreceiverrun in choreographerjava on line 711androidoshandlerhandlecallback in handlerjava on line 615androidoshandlerthispatchmessage in handlerjava on line 92androidoslooperloop in looperjava on line 137androidappactivitythreadmain in activitythreadjava on line 4744javalangreflectmethodinvokenativenative methodjavalangreflectmethodinvoke in methodjava on line 511comandroidinternaloszygoteinitmethodandargscallerrun in zygoteinitjava on line 786comandroidinternaloszygoteinitmain in zygoteinitjava on line 553dalviksystemnativestartmainnative methodfirst i set up the view pager in the onresume function of the activityprivate void initialiseviewpager mloginfragment new weakreferenceloginfragmentnew loginfragment bundle loginbundle new bundle loginbundleputintspinnerindex hdmslivesessiongetinstancegetspinnerposition loginbundleputstringusername hdmslivesessiongetinstancegetusername loginbundleputstringpassword hdmslivesessiongetinstancegetpassword loginbundleputintmode hdmslivesessiongetinstancegetconnectionmodeordinal loginbundleputbooleanloggedin hdmslivesessiongetinstanceisloggedin loginbundleputbooleanconnected hdmslivesessiongetinstanceisconnected loginbundleputstringloginresult hdmslivesessiongetinstancegetloginresult loginbundleputstringsystem hdmslivesessiongetinstancegetsystem loginbundleputintcode hdmslivesessiongetinstancegetaccesscode loginbundleputlongbytessent mcurrentsb loginbundleputlongbytesreceived mcurrentrb loginbundleputlongnbytessent mncurrentsb loginbundleputlongnbytesreceived mncurrentrb loginbundleputintappid mappgetapplicationinfouid loginbundleputstringmwebsocketaddresspreference mconnectgetwebsocketurl loginbundleputstringmapiaddresspreference mlogingetliveserverurl loginbundleputbooleanmautologinpreference mautologinenabled loginbundleputbooleanmautoconnectpreference mloginisautoconnectenabled loginbundleputintmautoreconnecttimepreference mconnectgetautoreconnecttime loginbundleputintmmaxautoreconnectionattemptspreference mconnectgetmaxautoreconnectionattempts loginbundleputintmpingresponsetimepreference mconnectgetpingresponsetime loginbundleputintmautopingtimepreference mconnectgetautopingtime loginbundleputintmcurrentpingpreference mconnectgetcurrentping loginbundleputintmautoreconnectattemptspreference mconnectgetautoreconnectattempts loginbundleputintmautoreconnecttotalattemptspreference mconnectgetautoreconnecttotalattempts loginbundleputbooleanmplaylistmessagepreference messagesubscriptioncontainsmplaylistmessage loginbundleputbooleanmautopageswappreference mautopageswap loginbundleputbooleanmwificheckedpreference mwifichecked loginbundleputbooleanmautowebcheckedpreference mconnectisautowebchecked loginbundleputbooleanmgatewaycheckedpreference mgatewaychecked loginbundleputbooleanmdhs1checkedpreference mdns1checked loginbundleputbooleanmhdmslivecheckedpreference mhdmslivechecked loginbundleputbooleanmgooglecheckedpreference mgooglechecked loginbundleputbooleanmhdmscheckedpreference mhdmschecked loginbundleputbooleanmparrotcheckedpreference mparrotchecked loginbundleputbooleanmlocalipcheckedpreference mlocalipchecked loginbundleputstringmlocalippreference mlocalip loginbundleputintmmaximagesfromwebpreference mmaximagesfromweb loginbundleputintmmaxpingattemptspreference mconnectgetmaxpingattempts loginbundleputintmfailedpingspreference mconnectgetfailedpings loginbundleputbooleanautologin mloginisautologin loginbundleputbooleanwasloggedin hdmslivesessiongetinstancewasloggedin mloginfragmentgetsetargumentsloginbundle mbaufragment new weakreferencebaufragmentnew baufragment bundle baubundle new bundle baubundleputbooleanjump mjumptocurrent baubundleputintplace mbauposition baubundleputbooleanmbauexpandedpreference mbauexpanded mbaufragmentgetsetargumentsbaubundle mplayerfragment new weakreferenceplayerfragmentnew playerfragment mlistfragment new weakreferencelistfragmentnew listfragment bundle listbundle new bundle listbundleputintmlistmodepreference mlistmode mlistfragmentgetsetargumentslistbundle msearchfragment new weakreferencesearchfragmentnew searchfragment bundle searchbundle new bundle searchbundleputintmsearchmodepreference msearchmode searchbundleputstringsearchquerya msearchtexta searchbundleputstringsearchquerys msearchtexts searchbundleputstringtitlelast mtitlelast searchbundleputstringartistlast martistlast searchbundleputstringlistlast mlistlast searchbundleputstringyearlast myearlast searchbundleputstringgenrelast mgenrelast msearchfragmentgetsetargumentssearchbundle mvideofragment new weakreferencevideofragmentnew videofragment bundle videobundle new bundle videobundleputintmvideooutputpreference mvideooutput mvideofragmentgetsetargumentsvideobundle listfragment fragments new vectorfragment fragmentsaddmvideofragmentget fragmentsaddmplayerfragmentget fragmentsaddmbaufragmentget fragmentsaddmlistfragmentget fragmentsaddmsearchfragmentget fragmentsaddmloginfragmentget mpageradapter new viewpageradaptergetsupportfragmentmanager fragments mviewpager viewpagerfindviewbyidridcontentviewpager mviewpagersetadaptermpageradapter mviewpagersetonpagechangelistenerthis mviewpagersetvisibilityviewvisible activitymanager am activitymanager getsystemserviceactivity service if amgetmemoryclass 32 mviewpagersetoffscreenpagelimitfragmentsmaxordinal mlastfragment 1 updatethisplayall fragments are retained unless it is a device with a small memory heap currently there are 6 fragments the crash was occuring when there where only 4 in memory so i know that the number of fragments is not the problem i did try leaving the view pagers settings at the default the only difference is speed as the app needs to load fragments in when the user swipes all the fragments are destroyed when the app is pausedoverrideprotected void onsaveinstancestatebundle outstate fragmenttransaction ft getsupportfragmentmanagerbegintransaction if mloginfragmentget null ftremovemloginfragmentget if mplayerfragmentget null ftremovemplayerfragmentget if mbaufragmentget null ftremovembaufragmentget if mlistfragmentget null ftremovemlistfragmentget if msearchfragmentget null ftremovemsearchfragmentget if mvideofragmentget null ftremovemvideofragmentget ftcommit mloginfragment new weakreferenceloginfragmentnull mplayerfragment new weakreferenceplayerfragmentnull mbaufragment new weakreferencebaufragmentnull mlistfragment new weakreferencelistfragmentnull msearchfragment new weakreferencesearchfragmentnull mvideofragment new weakreferencevideofragmentnull mpageradapter null mviewpager null mfragmentsloaded 0 mlastfragment 1here is my view pager codepackage comhdmsmanagerfragments created by bradj on 81013 import androidsupportv4appfragmentimport androidsupportv4appfragmentmanagerimport androidsupportv4appfragmentpageradapterimport androidsupportv4appfragmenttransactionimport androidviewviewimport javautillistpublic class viewpageradapter extends fragmentpageradapter private final listfragment mfragments fragmentmanager mfragmentmanager public viewpageradapterfragmentmanager afragmentmanager listfragment afragments superafragmentmanager mfragmentmanager afragmentmanager mfragments afragments override public fragment getitemint aposition return mfragmentsgetaposition override public long getitemidint aposition return aposition override public void destroyitemandroidviewviewgroup acontainer int aposition javalangobject aobject if aposition getcount aobject null fragmenttransaction trans mfragmentmanagerbegintransaction transremovefragment aobject transcommit override public int getcount return mfragmentssize,['android'] +606350,installation error install failed uid changed nonrooted android phone we have non rooted droid razr maxx which we use for development the device is shared between two of us and we both have been debugginginstalling from eclipse directly without any errors we do uninstall the previous version as prompted and reinstall the same on one of the installation attempts today we got the installation error install failed uid changed errorconsole in eclipse shows the following message20140102 163405 xappnamex installing xappnamexapk20140102 163408 xappnamex installation error install failed uid changed20140102 163408 xappnamex please check logcat output for more details20140102 163408 xappnamex launch canceledlogcat shows the following message0102 163421031 wactivitymanager467 no content provider found for permission revoke filedatalocaltmpxappnamexapk0102 163421070 wactivitymanager467 no content provider found for permission revoke filedatalocaltmpxappnamexapk0102 163421961 wactivitymanager467 permission denied checkcomponentpermission owninguid101100102 163421961 wactivitymanager467 permission denied checkcomponentpermission owninguid101100102 163422539 wpackagemanager467 package could not be installed in dataappcomhalinchalc2cxappnamex1apkthe directory data when viewed using a file manager in a nonrooted phone is emptythis is catch 22 as the solutions provided seem to suggest either rooting the phonechange datalocal permissions or doing a factory resetinstallation error install failed uid changed we are looking for some less painful solutions,['android'] +606376,how do i stream video from iphone acting as a server i am working on an app for ios where one iphone has to live stream its camera recordings to another iphone to keep things simple both are in the same wifi networkthe streaming should work without a physical interconnect eg a server used for routing the stream to clients in fact the recording iphone should be the server which serves the other iphone or more other ios devices in the network with the live streamso what i need to do isget the live pictures from the cameraprocess this data if neededsend frame by frame to the connected clients tcpreceive the frames on the client and thisplay them in real timewhat i have and what i am stuck withi have already solved problem 1 i use an avcapturesession which is constantly returning cmsamplebufferrefs found herei am not so sure yet what i need to do with the cmsamplebufferref i do know how to transform it into a cgimage or a uiimage thanks to benjamin louliers great blogpost2 but i have no idea of what specifically i need to send and if i need to encode the frames somehowas mentioned by jab in the above linked answer this it is possible to write those samples to a file with one or more avassetwriters but then again he says those 5 sec video snippets are to be uploaded to a server which makes a streamable movie file out of them and that movie can then be streamed to an ios device by http live streaming i supposeas i already indicated my app ie the video capturing server device has one or multiple clients connected to it and needs to send the video frames in real time to them one idea which came to my mind is to use a simple tcp connection where the server sends every single frame in a serialised format to the connected clients in a loop more specifically when one buffered frame is successfully sent to the client the server takes the most recent frame as the next one to be sentnow is this the right thought how it should work or is there another protocol which is much better suited for this kind of task remember i want to keep it simple simple for me ie so that i do not need to study too many new programming aspects and fast i already know some things about tcp i wrote servers and clients with it at school in c so i would prefer to apply the knowledge i have now to this projectlast but not least the receiving clienti imagine if i am really going to use a tcp connection that on the clientside i receive frame after frame from the server cast the read byte package into the used format cmsamplebuffer cgimage uiimage and just thisplay it on a calayer or uiimageview right the effect of a movie will be gotten by just constantly keeping updated that image viewplease give me some ideas on how to reach this goal it is very important because it is part of my schoolgraduation project any sample code is also appreciated or just refer me to another site tutorial stackoverflowanswer etcif you have any question to this just leave a comment and i will update the post,"['ios', 'iphone']" +606414,interpolation ignoring zero values in array python i have two arrays of the same lengthx array243 242 241 240 239 238 237 236 235 234 233 232 231 230 229 228 227 226 225 224 223 2 221 220 219 218 217 216 215 214 213 212 211 210 209 208 207 206 205 204 203 202 201 200 199 198 197 196 195 194 193 192 191 190 189 188 187 186 185 184 183 182 181 180 179 178 177 176 175 174 173 172 171 170 169 168 167 166 165 164 163 162 161 160 159 158 157 156 155 154 153 152 151 150 149 148 147 146 145 144 143 142 141 140 139 138 137 136 135 134 133 132 131 130 129 128 127 126 125 124 123 122 121 120 119 118 117 116 115 114 113 112 1 110 109 108 107 106 105 104 103 102 101 100 99 98 97 96 95 94 93 92 91 90 89 88 87 86 85 84 83 82 81 80 79 78 77 76 75 74 73 72 71 70 69 68 67 66 65 64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 1 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 2 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 y array 0e00 0e00 0e00 0e00 0e00 831593344e02 235439791e01 996024791e01 2056167e00 718482061e00 188705079e01 295964175e01 767566181e01 100520725e02 150101258e02 130495335e02 738818649e01 788215800e01 827782533e01 854715249e01 0e00 0e00 866810877e01 0e00 0e00 862917273e01 0e00 0e00 0e00 843340655e01 0e00 0e00 0e00 0e00 0e00 0e00 810109967e01 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 767001996e01 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 719263508e01 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 673025361e01 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 634476840e01 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 608936791e01 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 60e01 60e01 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 608936791e01 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 634476840e01 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 673025361e01 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 719263508e01 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 767001996e01 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 0e00 810109967e01 0e00 0e00 0e00 0e00 0e00 0e00 843340655e01 0e00 0e00 0e00 862917273e01 0e00 0e00 866810877e01 0e00 0e00 854715249e01 827782533e01 788215800e01 738818649e01 130495335e02 150101258e02 100520725e02 767566181e01 295964175e01 188705079e01 718482061e00 2056167e00 996024791e01 235439791e01 831593344e02 0e00 0e00 0e00 0e00 0e00plotting x against y yieldsmy question is how can i interpolate y so that the plot ignores the zero values and gives a smooth curvethe output should look something like this ignore the axescheers,['python'] +606416,javascript best practices wheres the best place to define a helper function inside a loop whats a better practice thismyarrayforeachfunctionitem dosomethingitem function dosomethingan item consolelogan item or thismyarrayforeachfunctionitem dosomethingitemfunction dosomethingan item consolelogan item does the first example create multiple instances of the function or does it create it just the first time through the loopthanks for any insight,['javascript'] +606430,are there cases where constexpr should be avoided even it it could be used if an object is declared const its value is guaranteed to be available only at runtime but if it is declared constexpr the value is guaranteed to be available both during compilation and at runtime so if i have an object whose value is available during compilation are there any situations where i should not declare it constexprconst int magicvalue 42 does this ever make sense using const instead of constexprfor functions if a function can return a value computed during compilation when passed arguments with values available during compilation would it ever make sense to not declare the function constexprstruct point int x int y point midpointpoint p1 point p2 does this ever make sense not declaring return p1x p2x 2 p1y p2y 2 the function constexprthe only case i can conceive of is when you do not want to commit to the function being able to compute a compiletime constant when called with knownatcompiletime arguments eg if you want to preserve the flexibility to change midpoints implementation without changing its interface thus potentially breaking callers for example you might want to preserve the flexibility to add nonconstexpr sideeffects to midpoint eg io,['c++'] +606435,use of parse in angular js any ideas on where to use parse of angularjsplease give any examples or links which describes clearly,['javascript'] +606442,why integer class caching values in the range 128 to 127 regarding my previous question confusion in method integervalueofstring we know that integer class has a cache which stores values between 128 and 127just wondering why between 128 and 127 integervalueof documentation stated that it caching frequently requested values but does values between 128 and 127 are frequently requested for real i thought frequently requested values are very subjective is there any possible reason behind thisfrom the documentation also stated and may cache other values outside of this rangehow is this can be achieved,['java'] +606559,push notification in spring mvc webapp i am currently writing a forum webapplication using spring mvc i am just a beginner at spring and have only been working with it for about 1 week nowi need to implement push notifications here is the scenario user a logs in and creates a post user b comments on user as post while user a is still logged in user a receives a notification that some user has commented on his post without his browser refreshing the pagei need help with sending the notification to user a that user b has commented on his post asynchronously i have done some research and found that there is a package called cometd that i can use but i cannot find any simple tutorials for me to understandcan anyone suggest any other packagesway to solve my problem or if you have any simple cometd tutorials that would be great as well,['java'] +606584,android studio what is the right way to change targetsdkversion i want to change the targetsdkversion from 19 to 18 in android studio not eclipse but failedandroid studio complains the following after i changed the targetsdkversion and resync the project with gradle filesexecution failed for task project nameprocessdebugmanifest manifest merging failed see console for more infofrom the console i found that it is the library i added to the gradle dependencies using the old targetsdkversion valuecode directorymainandroidmanifestxml code directorybuildexplodedbundleslibrary directoryaarandroidmanifestxml2 main manifest has usessdk androidtargetsdkversion18 but library uses targetsdkversion19i learn that in android studio the targetsdkversion and minsdkversion flags are defined in the buildgradle file the project is created with android studios new project wizard and there is no tag in my codes androidmanifestxml so the problem should not be the two values out of sync according to the above message the targetsdkversion value in the main manifest is what i wantso the problem should be in the manifest file of the library i open the librarys androidmanifestxml file and found the following lineusessdk androidminsdkversion8 androidtargetsdkversion19obviously it is not correct the problem is that the file is not for manual modification i tried changing the targetsdkversion value and even tried removing the declaration but it comes back every time i build the projecti tried cleaning the project still no luckso my question is is there a right way to alter the targetsdkversion in android studio which i am not aware of,['android'] +606600,ios objectivec correct way of obtaining meta class object which from the following is the correct way of obtaining the meta classclass mymetaclass objc getmetaclassnsstringorclass mymetaclass object getclassnsstring classare they both any different as mentioned in another post that is linked by the first answerer here please tell me why objc getmetaclass would break in certain cases in detailthe proper way to use those in different scenarios thank you,"['ios', 'objective-c']" +606602,is there an eventdriven json rest client api for java i have a java application which uses springs resttemplate api to write concise readable consumers of json rest servicesin essence resttemplate rest new resttemplateclienthttprequestfactory responseentityitemlist response restexchangeurl httpmethodget requestentity itemlistclass foritem item responsegetbodygetitems handleronitemitem the json response contains a list of items and as you can see i have have an eventdriven design in my own code to handle each item in turn however the entire list is in memory as part of response which resttemplateexchange producesi would like the application to be able to handle responses containing large numbers of items say 50 and in this case there are two issues with the implementation as it standsnot a single item is handled until the entire http response has been transferred adding unwanted latencythe huge response object sits in memory and cannot be gcd until the last item has been handledis there a reasonably mature java jsonrest client api out there that consumes responses in an eventdriven manneri imagine it would let you do something like reststreamer rest new reststreamerclienthttprequestfactory tell the reststreamer when while parsing a response you encounter a json element matching jsonpath items pass it to handler for processing restonjsonpathitemshandlehandler tell the reststreamer to make an http request parse it as a stream we expect handler to get passed an object each time the parser encounters an item restexecuteurl httpmethodget requestentityi appreciate i could roll my own implementation of this behaviour with streaming json apis from jackson gson etc but i would love to be told there was something out there that does it reliably with a concise expressive api integrated with the http aspect,['java'] +606665,get function parameters name visual studio i am trying to get a list of parameters and the return type from a mangled function compiled in visual studioi know that i can use undecoratesymbolnamefunctionc str undecoratedname 200 undname completebut this just gives me another string and i have to figure out if the string starts with a return type or a specifieris there a function to return symbolnameinfo something along the linesstruct symbolinfo char255 symbolname char255 returntype char255 parameters,['c++'] +606686,latest pip fails with requires setuptools 08 for thistinfo using the recent 15 version of pip i get an error when attempting to update several packages for example sudo pip install u pytz results in failure withwheel installs require setuptools 08 for thistinfo supportpips wheel support requires setuptools 08 for thistinfo supporti do not understand this message i have setuptools 21 or what to do about itexception information from the log for this errorexception informationtraceback most recent call last file librarypython27sitepackagespipbasecommandpy line 122 in main status selfrunoptions args file librarypython27sitepackagespipcommandsinstallpy line 230 in run finder self build package finderoptions index urls session file librarypython27sitepackagespipcommandsinstallpy line 185 in build package finder sessionsession file librarypython27sitepackagespipindexpy line 50 in init selfuse wheel use wheel file librarypython27sitepackagespipindexpy line 89 in use wheel raise installationerrorpips wheel support requires setuptools 08 for thistinfo supportinstallationerror pips wheel support requires setuptools 08 for thistinfo support,['python'] +606733,getting consolelog output from chrome with selenium python api bindings i am using selenium to run tests in chrome via the python api bindings and i am having trouble figuring out how to configure chrome to make the consolelog output from the loaded test available i see that there are get log and log types methods on the webdriver object and i have seen get chromes console log which shows how to do things in java but i do not see an equivalent of javas loggingpreferences type in the python api is there some way to accomplish what i need,['python'] +606789,how to obtain connection id of signalr client on the server side i need to get the connection id of a client i know you can get it from the client side using connectionhubid what i need is to get in while in a web service i have which updates records in a database in turn thisplaying the update on a web page i am new to signalr and stackoverflow so any advice would be appreciated on my client web page i have thisscript typetextjavascript function declare a proxy to reference the hub var notify connectionnotificationhub create a function that the hub can call to broadcast messages notifyclientbroadcastmessage function message var encodedmsg div textmessagehtml html encode thisplay message notificationmessagethisplayappendencodedmsg add the message to the page end broadcastmessage start the connection connectionhubstartdonefunction btnupdateclickfunction call shownotification method on hub notifyservershownotificationconnectionhubid test status end main functionscripteverything works up until i want to update the page using signalr the show notification function in my hub is thishub functionpublic void shownotificationstring connectionid string newstatus ihubcontext context globalhostconnectionmanagergethubcontextnotificationhub string connection your connection id is connectionidthisplay for testing string statusupdate the current status of your request is newstatusto be thisplayed for testing you can thisplay the connectionid in the broadcast message contextclientsclientconnectionidbroadcastmessageconnection statusupdateend show notificationhow can i send the connectionid to my web servicehopefully i am not trying to do something impossible thanks in advance,['c#'] +606805,why does this memoizer work on recursive functions i cannot figure out why the following code is makes fib run in linear rather than exponential timedef memoizeobj memoization decorator from pythondecoratorlibrary ignores kwargs cache objcache functoolswrapsobj def memoizerargs kwargs if args not in cache cacheargs objargs kwargs return cacheargs return memoizermemoizedef fibn return and if and in 0 1 else fibn1 fibn2for example fib100 does not completely blow up like i expected it tomy understanding is that memoize sets fib memoizefib so when you call fib100 seeing that 100 is not in the cache it will call obj on 100 but obj is the original fib function so should not it take just as long on the first evaluation as if we did not have memoization at all,['python'] +606832,why do so many android apps use the ndk i have been looking through a few of the apps today was actually looking to see how many use acra but noticed that a lot of them use the ndk i have been developing apps for quite some time and have yet to find a need for the ndk and as per the android developer site you should not really use it unless you need toin general you should only use the ndk if it is essential to your appanever because you simply prefer to program in ccso this has got me to thinking am i missing something i mean here are just a few of the apps using the ndk where i cannot really see a need for itwhatsapptunein radio protextplusmicrosoft tagstar chartspymousesoundhoundroll in the holefacebookskype likely crypto libsraging thunderqr droidpocketcloudcamera zoom fxblow uppaper cameraocean hd screen saveroffice suiteinstagramjump desktopfieldrunnersangry birds appsi guess my thinking is perhaps they are using the same code on other platforms libraries written in c and used on ios android other platforms but i am just not convinced that this is the reason are there any other things that these apps are likely to be using the ndk for other things i guess could be licensing privacysecurity move complicated reverse engineering device ids gaming engines etc anyhow the question is really do you have any ideas as to why so many apps are using the ndk,['android'] +606908,stream video while downloading ios i am using ios 7 and i have a mp4 video that i need to download in my app the video is large 1 gb which is why it is not included as part of the app i want the user to be able to start watching the video as soon as is starts downloading i also want the video to be able to be cached on the ios device so the user does not need to download it again later both the normal methods of playing videos progressive download and live streaming do not seem to let you cache the video so i have made my own web service that chunks up my video file and streams the bytes down to the client i start the streaming http call using nsurlconnectionselfrequest nsmutableurlrequest alloc initwithurlselfurlselfrequest settimeoutinterval10 expect data at least every 10 secondsselfrequest sethttpmethodgetselfconnection nsurlconnection alloc initwithrequestselfrequest delegateself startimmediatelyyeswhen i receive a data chunk i append it to the end of the local copy of the file voidconnectionnsurlconnection connection didreceivedatansdata data nsfilehandle handle nsfilehandle filehandleforwritingatpathself videofilepath handle truncatefileatoffsethandle seektoendoffile handle writedatadataif i let the device run the file is downloaded successfully and i can play it using mpmovieplayerviewcontrollernsurl urlnsurl fileurlwithpathselfvideofilepathmpmovieplayerviewcontroller controller mpmovieplayerviewcontroller alloc initwithcontenturlurlcontrollermovieplayerscalingmode mpmoviescalingmodeaspectfitself presentmovieplayerviewcontrolleranimatedcontrollerhowever if i start the player before the file is completely downloaded the video starts playing just fine it even has the correct video length thisplayed at the top scrubber bar but when the user gets to the position in the video that i had completed downloading before the video started the video just hangs if i close and reopen the mpmovieplayerviewcontroller then the video plays until it gets to whatever location i was then at when i launched the mpmovieplayerviewcontroller again if i wait until the entire video is downloaded then the video plays without a problemi am not getting any events fired or error messages printed to the console when this happens mpmovieplayerplaybackstatedidchangenotification and mpmovieplayerplaybackdidfinishnotification are never sent after the video starts it seems like there is something else that is telling the controller what the length of the video is other than what the scrubber is usingdoes anyone know what could be causing this issue i am not bound to using mpmovieplayerviewcontroller so if a different video playback method would work in this situation i am all for itrelated unresolved questionsavplayer and progressive video downloads with avurlassetsprogressive video download on ioshow to play an in downloading progress video file in iosupdate 1i have found that the video stall is indeed because of the file size when the video starts playing i can get around this issue by creating a zeroed out file before i start the download and over overwrite it as i go since i have control over the video streaming server i added a custom header so i know the size of the file being streamed default file size header for a streaming file is 1 i am creating the file in my didreceiveresponse method as follows voidconnectionnsurlconnection connection didreceiveresponsensurlresponse response retrieve the size of the file being streamed nshttpurlresponse httpresponse nshttpurlresponse response nsdictionary headers httpresponseallheaderfields nsnumberformatter formatter nsnumberformatter alloc init formatter setnumberstylensnumberformatterdecimalstyle selfstreamingfilesize formatter numberfromstringheaders objectforkeystreamingfilesize check if we need to initialize the download file if nsfilemanager defaultmanager fileexistsatpathselfpath create the file being downloaded nsdata data writetofileselfpath atomicallyyes allocate the size of the file we are going to download const char cstring selfpath cstringusingencodingnsasciistringencoding int success truncatecstring selfstreamingfilesizelonglongvalue if success 0 todo handle errors here probably not enough space see man truncate this works great except that truncate causes the app to hang for about 10 seconds while it creates the 1gb file on thisk on the simulator it is instant only a real device has this problem this is where i am stuck now does anyone know of a way to allocate a file more efficiently or a different way to get the video player to recognize the size of the file without needing to actually allocate it i know some filesystems support file size and size on thisk as two different properties not sure if ios has something like that,['ios'] +606999,why javascript functions always return a value i am taking a course in javascript programming and the instructor said that a typical javascript function always returns a value even when we do not provide any explicit return value the engines return undefinedis that true if so why,['javascript'] +607094,what are the benefits of javas types erasure i read a tweet today that saidit is funny when java users complain about type erasure which is the only thing java got right while ignoring all the things it got wrongthus my question is are there benefits from javas type erasure what are the technical or programming style benefits it possibly offers other than the jvm implementations preference for backwards compatibility and runtime performance,['java'] +607119,warning c4800 int forcing value to bool true or false performance warning i have this problem in my codebool cbaseisnumberreturn id mid numberbool cbaseisvarreturn id mid variablebool cbaseissymbolreturn id mid symbol,['c++'] +607230,how can i get only the first line from an string examplestring str lorem ipsum dolor sit amet consetetur sadipscing elitr sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat sed diam voluptua at vero eos et accusam et justo duo dolores et ea rebumstring firstlinehow can i get just the first line from the string str into the string firstline,['c#'] +607245,python argparse example i am trying to learn argparse in order to use it in my program the syntax should be like thisa along string stringb blong string string integerc clong stringh helpi have this codeusrbinenv pythoncoding utf8import argparseif name main parser argparseargumentparserdescriptionlorem ipsum parseradd argumentaalong helplorem ipsum requiredfalse parseradd argumentbblong helplorem ipsum requiredfalse parseradd argumentcclong helplorem ipsum requiredfalse parseradd argumenthhelp helplorem ipsum requiredfalse parserparse argsthe question is i read in the official doc saw youtube videos etc but i could not understand how can i determine the number of subarguments of the mainargumentexample myapy b foobar 90 how can i set that b must have two subarguments and how can i get the values foobar and 90and another doubt i know i can set an argument to be required or not but i wanted to make my program only executes when at least one argument is passed any of the four mentionedmaybe it is a stupid question but sorry i cannot understand it and hopefully there is someone here with teacher powers to explain it,['python'] +607254,why is g allowing me to treat this voidfunction as anything but why does the following compile in gcc 48 g is not it completely illformedvoid testint x return test3int main i am trying to use the result of calling test which does not existi am trying to return a value from testboth should be fundamentally impossible not just ub as far as i can recall with a void return typethe only warning i get is about x being unused not even anything about a nonstandard implicit return type being addedlive demo,['c++'] +607394,should i use javac o option to optimize javac has an interesting o optionoptimizes compiled code by inlining static final and private methods note that your classes may get larger in sizethis option seems to not be popular hidden i have just thiscovered it today on codecup 2014 page o is not mentioned in the official documentation nor in man javac strangein accepted answer to similar question we can read thatoptimization in java is mostly done by the jit compiler at runtime hence there is no point trying to instruct it to optimize a certain way at compile time when it is creating only bytecode anyway the jit will almost surely make better decisions on the spot knowing the exact environment and observing the actual patterns of execution of specific parts of your codemy question isshould i always use the o option or not in other words the code always run faster with o or does it make no difference at allmaybe classes size can increase so much that the overall performance will drop or jvm will do the inlining anyway so it is better to leave it to thatsimilar story was with gcc o3 flag,['java'] +607423,how does instagram and vine ios apps play videos inline without opening the fullscreen video playerare they using a webview what is the format of the video,"['ios', 'iphone']" +607439,change height constraint programmatically i want to change the height constraint of a uitextview programmatically so i set the constraint as an outlet in my controller like thisproperty strong nonatomic iboutlet nslayoutconstraint descriptionheightconstraintto change it i do the followingselfdescriptionheightconstraintconstant selfdescriptioncontentsizeheightthis works if i do it in viewdidappear but the problem with this is that i can see how the height changes after the view thisplayed which is not very user friendly so i tried doing it in viewwillappear but did not work there the height does not change calling setneedsupdateconstraints after changing the constraint did not work eitherwhy is working in viewdidappear and not in viewwillappear any workaroundthanks in advance,['ios'] +607463,laravel get object from collection by attribute in laravel if i perform a queryfoods foodwheregetthen foods is an illuminate collection of food model objects essentially an array of modelshowever the keys of this array are simply0 1 2 3 so if i want to alter say the food object with an id of 24 i cannot do thisdesired object foodsget24desired objectcolor greendesired objectsavebecause this will merely alter the 25th element in the array not the element with an id of 24how do i get a single or multiple elements from a collection by any attributecolumn such as but not limited to id color age etcof course i can do thisforeach foods as food if foodid 24 desired object food break desired objectcolor greendesired objectsavebut that is just grossand of course i can do thisdesired object foodfind24desired objectcolor greendesired objectsavebut that is even more gross because it performs an additional unnecessary query when i already have the desired object in the foods collectionthanks in advance for any guidanceeditto be clear you can call find on an illuminate collection without spawning another query but it only accepts a primary id for instancefoods foodalldesired food foodsfind21 grab the food with an id of 21however there is still no clean nonlooping nonquerying way to grab an elements by an attribute from a collection like thisfoods foodallgreen foods foodswherecolor green this would not work,"['php', 'mysql']" +607485,avoiding stalls while uploading textures on android our game requires us to constantly load and create new images which we put onto a texture page then use to render we upload using gltexsubimage2d to modify part of the texture page we dont keep a system copy whenever we do this we have a six frame delay inside the gltexsubimage2d call we do load most of our images onto textures before the game starts but some things are necessarily dynamici assume the entire rendering pipeline be it double or triple buffered is being flushed because i want to modify a texture that it is using or has a reference to even so six frames plus 01 seconds seems excessive we do exactly the same on ios and you barely notice any delay when a texture has been modified the game normally runs on 1 or 2 framesanyone got any idea what is going on this is running on a samsung galaxy note gtn70 were using the surfaceview class can you turn this stall off i understand this may mean artefacts for a frame or so where the render may not have the updated texturefurthermore any idea how to know or set whether internally its being double or triple bufferedi have also read that most desktoppc opengl drivers get round this by having two or three copies of the textures and updating only those that are not currently being used then updating the copies in good time we simply do not have the memory for thatthanksshaun,"['android', 'c++']" +607522,why does the compiler let me cast a null to a specific type in c consider this codevar str stringnullwhen write the code this is my il codeil 01 ldnulland il has any cast operator butvar test string new objectthe il code isil 08 castclass mscorlibsystemstringso casting null to string was ignoredwhy does the compiler let me cast a null to specific type,['c#'] +607526,how can i make a css hover not work if a button is thisabled i have this csshtmldarkblue btn1 buttonhovernotnohover background 07d5 border 1px solid 07d5 color whitei am rather confused about thisabled how can i make it so that this css does not work if the button is thisabled,['css'] +607532,nodejs server 404 not found message to 404html page im working with nodejs and i would like to know how to thisplay a 404html instead of a 404 not found messagethis is my serverjsvar http requirehttpurl requireurlpath requirepathfs requirefsport processargv2 8httpcreateserverfunctionrequest response var uri urlparserequesturlpathname filename pathjoinprocesscwd uripathexistsfilename functionexists ifexists responsewritehead404 contenttype textplain responsewrite404 not foundn responseend returnif fsstatsyncfilenameisdirectory filename publicindexindexhtmlfsreadfilefilename binary functionerr file iferr responsewritehead500 contenttype textplain responsewriteerr n responseend return responsewritehead200 responsewritefile binary responseend listenparseintport 10consolelogstatic file server running atn httplocalhost port nctrl c to shutdownas you can see its just a static file server and i am not using expressjs or anything,"['javascript', 'html']" +607559,uisearchbar in a uicollectionview thisappears when using uisearchthisplaycontroller i have a uisearchbar added as a subview to a uicollectionview and attached to a uisearchthisplaycontrolleri set it up in viewdidloadselfsearchcontroller uisearchthisplaycontroller alloc initwithsearchbarselfsearchbar contentscontrollerselfselfsearchcontrollerdelegate selfselfsearchcontrollersearchresultsdatasource selfselfsearchcontrollersearchresultsdelegate selfselfcollectionview addsubviewselfsearchbarwhen i push another view controller to the navigation controller then pop it the search bar thisappears this only happens if the collection view is scrolled down enough for the search bar to be hidden also even though the search bar thisappears tapping the white space where it is supposed to be activates the search thisplay controller attached to itthis happens only on ios 7 and if i remove the search thisplay controller the search bar will not thisappearone more thing worth mentioning when the search bar has thisappeared if i push another view controller then pop it the bar will be visible againapparently this is a bug of uisearchthisplaycontroller on ios 7 so any ideas on how to work around it,['ios'] +607627,unstable face recognition using opencv iam developing an android application for face recognition using javacv which is an unofficial wrapper of opencv after importing comgooglecodejavacvcppopencv contribfacerecognizer i apply and test the following known methodslbph using createlbphfacerecognizer methodfisherface using createfisherfacerecognizer methodeigenface using createeigenfacerecognizer methodbefore i recognize the detected face i correct the rotated face and crop the proper zone inspiring from this methodin general when i pass on camera a face already exist in the database the recognition is ok but this is not always correct sometimes it recognizes the unknown face not found in database of trained samples with a high probability when we have in the db two or more faces of similar features beard mustache glasses the recognition may be highly mistaken between those facesto predict the result using the test face image i apply the following code public string predictmat m int n new int1 double p new double1 iplimage ipl mattoiplimagemwidth height facerecognizerpredictipl n p if n01 mprobintp0 else mprob1 if n0 1 return labelsfilegetn0 else return unkown i canat control the threshold of the probability p becausesmall p 50 could predict a correct resulthigh p 70 could predict a false resultmiddle p could predict a correct or falseas well i donat understand why predict function gives sometime a probability greater than 100 in case of using lbph and in case of fisher and eigen it gives very big values 20 can someone help in finding a solution for these bizarre problems is there any suggestion to improve robustness of recognition especially in case of similarity of two different faces the following is the entire class using facerecognizerpackage orgopencvjavacvfacerecognitionimport static comgooglecodejavacvcppopencv highguiimport static comgooglecodejavacvcppopencv coreimport static comgooglecodejavacvcppopencv imgprocimport static comgooglecodejavacvcppopencv contribimport javaiofileimport javaiofileoutputstreamimport javaiofilenamefilterimport javautilarraylistimport orgopencvandroidutilsimport orgopencvcorematimport comgooglecodejavacvcppopencv imgprocimport comgooglecodejavacvcppopencv contribfacerecognizerimport comgooglecodejavacvcppopencv coreiplimageimport comgooglecodejavacvcppopencv corematvectorimport androidgraphicsbitmapimport androidosenvironmentimport androidutillogimport androidwidgettoastpublic class personrecognizer public final static int maximg 100 facerecognizer facerecognizer string mpath int count0 labels labelsfile static final int width 128 static final int height 128 private int mprob9 personrecognizerstring path facerecognizer comgooglecodejavacvcppopencv contribcreatelbphfacerecognizer28200 pathenvironmentgetexternalstoragedirectoryfacerecogfaces mpathpath labelsfile new labelsmpath void changerecognizerint nrec switchnrec case 0 facerecognizer comgooglecodejavacvcppopencv contribcreatelbphfacerecognizer18100 break case 1 facerecognizer comgooglecodejavacvcppopencv contribcreatefisherfacerecognizer break case 2 facerecognizer comgooglecodejavacvcppopencv contribcreateeigenfacerecognizer break train void addmat m string description bitmap bmp bitmapcreatebitmapmwidth mheight bitmapconfigargb 8 utilsmattobitmapmbmp bmp bitmapcreatescaledbitmapbmp width height false fileoutputstream f try f new fileoutputstreammpathdescriptioncountjpgtrue count bmpcompressbitmapcompressformatjpeg 100 f fclose catch exception e logeerroregetcause egetmessage eprintstacktrace public boolean train file root new filempath logimpathmpath filenamefilter pngfilter new filenamefilter public boolean acceptfile dir string name return nametolowercaseendswithjpg file imagefiles rootlistfilespngfilter matvector images new matvectorimagefileslength int labels new intimagefileslength int counter 0 int label iplimage imgnull iplimage grayimg int i1mpathlength for file image imagefiles string p imagegetabsolutepath img cvloadimagep if imgnull logeerrorerror cvloadimage logiimagep int i2plastindexof int i3plastindexof int icountintegerparseintpsubstringi21i3 if counticount count string descriptionpsubstringi1i2 if labelsfilegetdescription0 labelsfileadescription labelsfilemax1 label labelsfilegetdescription grayimg iplimagecreateimgwidth imgheight ipl depth 8u 1 cvcvtcolorimg grayimg cv bgr2gray imagesputcounter grayimg labelscounter label counter if counter0 if labelsfilemax1 facerecognizertrainimages labels labelsfilesave return true public boolean canpredict if labelsfilemax1 return true else return false public string predictmat m if canpredict return int n new int1 double p new double1 iplimage ipl mattoiplimagemwidth height iplimage ipl mattoiplimagem1 1 facerecognizerpredictipl n p if n01 mprobintp0 else mprob1 if n0 1p095 if n0 1 return labelsfilegetn0 else return unkown iplimage mattoiplimagemat mint widthint heigth bitmap bmpbitmapcreatebitmapmwidth mheight bitmapconfigargb 8 utilsmattobitmapm bmp return bitmaptoiplimagebmpwidth heigth iplimage bitmaptoiplimagebitmap bmp int width int height if width 1 height 1 bitmap bmp2 bitmapcreatescaledbitmapbmp width height false bmp bmp2 iplimage image iplimagecreatebmpgetwidth bmpgetheight ipl depth 8u 4 bmpcopypixelstobufferimagegetbytebuffer iplimage grayimg iplimagecreateimagewidth imageheight ipl depth 8u 1 cvcvtcolorimage grayimg opencv imgproccv bgr2gray return grayimg protected void savebmpbitmap bmpstring path fileoutputstream file try file new fileoutputstreampath true bmpcompressbitmapcompressformatjpeg100file fileclose catch exception e todo autogenerated catch block logeegetmessageegetcause eprintstacktrace public void load train public int getprob todo autogenerated method stub return mprob,"['java', 'android']" +607631,module name conflict in python how to resolve i came across a file in our project called wait for it celerypy yes and celerypy imports from the installed celery module see which is not an issue because the projects celerypy usesfrom future import absolute import before importing from the installed celery module now the problem comes from djcelery djangocelery which also would like to import from celery the installed one not the project celerypy this is where the clash comes because djcelery encounters the projects celerypy before it encounters the installed celeryhow can i resolve this,['python'] +607641,how to change url without changing browser history until now i only know that if i want to change url without reloading the whole page i have to use html browser history apii am using this concept in my website let us take example let suppose user is on this page and then he goes to product listing in which we have filters on clicking any filters system generates new url something like thissongbrandssamsungconditionnewinternally it is just calling historypushstate title linkhrefbut it has one problem clicking back button takes to the previous filter i dont want this functionality i want on clicking browser back button it should take to the page which is before current page in our case it is suppose to take to this is possible look at coursera filters they are doing exactly same thing but how they are doing itthanks,['javascript'] +607666,dbl epsilon issue in ios i am using this define is iphone 5 fabs double uiscreen mainscreen bounds sizeheight double 568 dbl epsilon macro in my projecti have declared this macro in projects pch fileits working when target is my project but not when i try to run test cases using xctestbuild always getting failed with following error undeclared identifier dbl epsiloni have declared this in my appnamepch and import that pch into my text case bundle pchwhen i import import floaththis resolved my issuemy question why this import is needed in test bundle as it is not needed in main project,['ios'] +607671,loading external file from karmajasmine test i am trying to accomplish a jasmine test using karma and intellij 13 to validate json files ideally my test would simply load a json file into a data object then let me parse through to check for valid formatting and data i do not need to validate functions before or after nor do i need to test against a servermy basic setup is like thisitshould load an external file functionvar asynccallcomplete result this this asynccallcomplete is set to true when the ajax call is complete asynccallcomplete false result stores the result of the successful ajax call result null section 1 call asynchronous function runsfunction return ajaxtestconfigjson type get success functiondata asynccallcomplete true result data error function asynccallcomplete true section 2 wait for the asynchronous call to complete waitsforfunction return asynccallcomplete false async to complete section 3 perform tests return runsfunction return expectresultnottobenull the problem is that no matter what path i use i get a 404 error and the file would not load i have tried loading an external json result from a remote server using this test serviceand this worksmy test file is named testmyspecjs and my karmaconfjs file is on the root i have moved around the json file to all of these locations with no luck what am i doing wrongupdate with answerper the answer below i added this to my karmaconfjs fixtures pattern testjson watched true served true included falsethen i wrote my test this way var jsonany itshould load a fixture function jasminegetfixturesfixturespath basetest var f readfixturesregistrationjson json jsonparsef expectjsontobedefined itshould have a title function expectjsontitletonotbenull etcand it passes,['javascript'] +607742,javascript function execution inside jade template i am new to nodejs and trying to create a jade file for the html content myfilejadehere are the contents of the fileextends layoutblock content script function capitalizes consolelogtesting js exec return scharat0touppercase sslice1 table each item in list tr td ahrefcollectionitemname capitalizeitemnamehowever when running it throws the following errorerror mwebviewscollectionsjade8 6 script 7 function capitalizes 8 consolelogtesting js exec 9 return scharat0touppercase sslice1 10 unexpected text if i remove consolelog it throws the error sayingtypeerror mwebviewscollectionsjade18 18 ahrefcollectionitemname capitalizeitemnameas far as i realized capitalize is being called during the jade compilation and the function is not available as the script tag is also compiled into the html what is the best way for me to have this call evaluated on a server side or b client sidethx,['javascript'] +607744,add snapto position in a uitableview or uiscrollview is it possible to add a snapto position in a uitableview or uiscrollview what i mean is not auto scroll to a position if i press a button or call some method to do it i mean is if i scroll my scroll view or tableview around a specific point say 0 30 it will autosnap to it and stay there so if my scroll view or table view scrolls and then the user lets go inbetween 0 25 or 0 35 it will auto snap and scroll there i can imagine maybe putting in an ifstatement to test if the position falls in that area in either the scrollviewdidenddraggingwilldecelerate or scrollviewwillbegindecelerating methods of uiscrollview but i am unsure how to implement this in the case of a uitableview any guidance would be much appreciated,"['ios', 'objective-c']" +607770,extensible curly bracket with html and css is there an easy way to emulate the cases environment provided by amsmath in latex with html and cssfor example in latex one can writedocumentclassarticleusepackageamsmathbegindocumenttext20140105 quadbegincases textlorem ipsum ldots textlorem ipsum ldots textlorem ipsum ldots endcasesenddocumentwhich producesi would like to be able to do the same thing in html and cso far i have tried this see it on jsfiddlehtmldiv idblogpostdate20130701divdiv idblogpostbracespan stylefontsize700spandivdiv idblogpostcontent div idblogfloaterdiv div idblogpostcontentchild ptitle a href blog about stackoverflow with a really really really really excessively long title in order to demonstrate a problem ap pcategories website helpp ptags html cssp divdivand cssbody fontfamily palatino linotype palatino serifblogpostdate thisplayinlineblock width 5em height 10em lineheight 10em textalign center overflow hidden margin 0 padding 0 fontweight900blogpostbrace thisplay inlineblock width 2em height 10em lineheight 10em textalign center overflow hidden margin 0 padding 0blogpostcontent position relative thisplay inlineblock width 20em height 10em overflow hidden margin 0 padding 0 fontsize smalli am hoping to use this kind of styling to thisplay the metadata for blog posts on a blog page what i have tried so far however has a few problemsfirst it runs into problems when the title of the blog post or any line really becomes excessively long the is currently set to a fixed size and does not dynamically scale with the metadata for the blog post this can be seen in the jsfiddle example where the tags line is now below the bottom of the curly bracket if dynamic scaling is impossible i would be willing to settle for whitespace nowrap overflow hidden and textoverflow ellipsising the metadata of the blog post and just having three lines of text regardless of the length of the metadatamy code also seems to be fontdependent if you uncomment the font change at the top of the css section in the jsfiddle example you will see that the middle of the curly bracket is no longer aligned with the date of the post after changing the fontthe way that the bracket is scaled can make for a pretty ugly bracket at least in the font of the example as it currently stands perhaps this question and this answer could helpthus my question is whether there is a way to fix what i have tried so far in order to address these problems or whether there is a better way to go about doing this with html and css preferably the solution would only use html and css,"['html', 'css']" +607798,angular expressions in watch trigger twice why does this watch fire twice when a simple comparison is passed as the watchexpressionscopefoo 0 simple counterscopewatchfoo 4 function consolelogfoo is greater than 4 scopefoothe listener fires when the page loads when foo is 0 then once more and only once more when the value of foo goes above 4why does the listener fire when the page loads and why does not it continue to fire when foo is greater than 4i set up a simple plunkr to show whats happening,['javascript'] +607825,angularjs changing class using global variable i just created a angularjs applicationhere is my indexhtmlhtml ngappmyapp head css files import head body classbodylayout div ngviewdiv body js imports aungularjs appjs loginjs registerjs htmlappjsuse strictdefine routing for appangularmodulemyapp configrouteprovider locationprovider functionrouteproviderlocationprovider routeprovider whenlogin templateurl loginhtml controller logincontroller whenregister templateurl registerhtml controller registercontroller whenforgotpassword templateurl forgotpasswordhtml controller forgotcontroller whenhome templateurl viewshomehtml otherwise redirectto login locationproviderhtml5modetrue remove the from urli have loginhtml registerhtml and forgotpasswordhtml homehtml each one has separate controlers in separate files loginjs registerjs forgotjs homejsloginjsuse strictangularmodulemyappcontrollerlogincontroller functionscope location window scopeuser scopeloginuserfunction var usernamescopeusername var passwordscopeuserpassword ifusernameadmin passwordadmin123 locationpath home else scopemessageerror scopemessagecoloralert alertdanger similarly i have post methods in other controllerswhat i want is when the view is login or register or forgotpassword the body class should be loginlayout so in body i put classbodylayout i know using global variables the value can be set but i do not know how toin appjs i tried thisangularmodulemyappfactorymyservice function return sharedobject data loginlayout but do not know how to use it,"['javascript', 'jquery', 'html']" +607836,whats ctsubscriber and how to use it on ios 7 on ios 7 ctsubscriber was added to the coretelephony framework there is no documentation available only its header file ctsubscribertokenrefreshed description the name of the nsnotification sent when the carrier token is available coretelephony extern nsstring const ctsubscribertokenrefreshed osx available starting mac na iphone 7 0coretelephony class available7 0interface ctsubscriber nsobject carriertoken description a data blob containing authorization information about the subscriber may return nil if no token is available property nonatomic readonly retain nsdata carriertoken osx available starting mac na iphone 7 0endalso on whats new on ios 7 this is mentionedthe core telephony framework coretelephonyframework lets you get information about the type of radio technology in use by the device apps developed in conjunction with a carrier can also authenticate against a particular subscriber for that carrieri think that ctsubscriber is related to the bold part of the text however i have not found anything related on how this happensi have tried to use the following code added to applicationdidfinishlaunchingwithoptions to experiment with this api but the notification is never fired and carriertoken returns nilctsubscriber subscriber ctsubscriberinfo subscribernslog subscribercarriertokennsnotificationcenter defaultcenter addobserverfornamectsubscribertokenrefreshed objectnil queuensoperationqueue mainqueue usingblocknsnotification note nslog nslog note nslog subscribercarriertokenso i have the following questionswhat exactly authorization information does carriertoken return and how to make it not nil how does apple know if your app is developed in conjunction with a carrieris this how evernote is giving 1 year of premium account to telefonica users probably not since the information they need can be obtained on ctcarrier,"['ios', 'objective-c']" +607867,c equivalent operator creating confusion program 1includestdiohvoid main int i55 printfd d d dni55i40i40i10program 2includestdiohvoid main int i 55 ifi 55 printfhi first program give output 0 40 0 1 here in the printf i 55 and output is 0 and in the second program too i 55 and output is hi why,['c'] +607962,missing apis auth registered apps in google cloud console how do i obtain gcm api key this question is already asked here and is closed as off topic i did not see any stackexchange network sites for asking this question so i am reasking here i know this is very confusing problems for beginner i was trying to use google cloud messaging service i had followed the official android developer guide i had performed all the steps as mention there but got stuck at a point where it says in the sidebar on the left select apis auth registered apps i looked at left side bar but could not find it please anyone help me,['android'] +608028,how to sort counter by value python other than doing list comprehensions of reversed list comprehension is there a pythonic way to sort counter by value if so it is faster than this from collections import counter x countera5 b3 c7 sortedxa b c sortedxitemsa 5 b 3 c 7 lk for kl in sortedji for ij in xitemsb 3 a 5 c 7 lk for kl in sortedji for ij in xitems reversetruec 7 a 5 b 3,['python'] +608061,pandas groupby and create new dataframe this is my situation in1 dataout1 item type0 orange edible fruit1 banana edible fruit2 tomato edible vegetable3 laptop non edible electronicin2 typedataout2 pandascoreframedataframewhat i want to do is create a data frame of only fruits so i need to groupby such a way that fruit exists in typei have tried doing thisgrouped datagroupbylambda x fruit in x axis1i do not know if that is the way of doing it i am having a little tough time understanding groupby how do i get a new dataframe of only fruits,['python'] +608105,what is the fastest hash function for pointers hash table based containers are very fast associative array eg unordered map unordered settheir performance is highly dependent on that hash function used to create an index for each entry as hash tables grow elements are rehashed again and againpointers are simple type basically a 48 byte value that uniquely identify an object the problem is that using an address as a result of the hash function is not efficient due to several lsb being zeroexamplestruct myvoidpointerhash size t operatorconst void val const return size tval a faster implementation is to lose a few bitsstruct myvoidpointerhash2 size t operatorconst void val const return size tval 3 3 on 64 bit 1 on 32 bit the latter produced 1020 performance increase on a large application that uses hash sets and maps with tens of thousands of elements that are frequently built and clearedcan someone offer a better scheme for hashing pointersthe function needs to befast and must inline welloffer a reasonable thistribution rare collisions are allowedupdate benchmark resultsi ran two sets of tests one for int and for a class pointer that has a size of 4kb the results are very interestingi used stdunordered set for all test with data size being 16mb that was allocated in a single new call the first algorithm ran twice to make sure sure caches are as hot as possible and the cpu is running at full speedsetup vs2013 x64 i72600 windows 81 x64vs2013 default hash functionhash1 return size tvalhash2 return size tval 3hash3basilestarynkevitch uintptr t ad uintptr tval return size t13 ad ad 15hash4roddy uintptr t ad uintptr tval return size tad ad 16 hash5egurcodetemplatetypename tvalstruct mytemplatepointerhash1 size t operatorconst tval val const static const size t shift size tlog21 sizeoftval return size tval shift test 1 intvs2013 default took 1292mshash1 took 742mshash2 took 343mshash3 took 1008mshash4 took 629mshash5 took 350mstest 1 4k classvs2013 default took 0423mshash1 took 23889mshash2 took 6331mshash3 took 0366mshash4 took 0390mshash5 took 0290msupdate2winner so far is the templated hash hash5 function best level of performance for speed for various block sizesupdate 3added default hash function for baseline turns out it is far from optimal,['c++'] +608136,are there any advantages to switch to otto from broadcast events i stumbled upon otto and it looks like it is used as a replacement for broadcast events i read the doc but i do not understand if there are much advantages to use otto,['android'] +608137,uisplitview button missing after detail replace segue i have a master detail ipad interface set up with storyboard to provide a replace segue on the detail view controller this works fine to replace the detail controller however the bar button to thisplay the master controller is missing in certain situationsif i do the segue while in portrait the bar button is missing because the willhideviewcontroller delegate method is never called i am setting the delegate to the new detail controller when prepareforsegue is called from the masterwhen the button is missing i can rotate the ipad to landscape then back to portrait and the button will then appearin prepareforsegueuinavigationcontroller nav segue destinationviewcontroller uiviewcontroller destinationviewcontroller navtopviewcontroller if destinationviewcontroller conformstoprotocolprotocoluisplitviewcontrollerdelegate selfsplitviewcontrollerdelegate destinationviewcontroller else selfsplitviewcontrollerdelegate nil in the detail controllerspragma mark split view voidsplitviewcontrolleruisplitviewcontroller splitcontroller willhideviewcontrolleruiviewcontroller viewcontroller withbarbuttonitemuibarbuttonitem barbuttonitem forpopovercontrolleruipopovercontroller popovercontroller barbuttonitemtitle nslocalizedstringmasterbutton master selfnavigationitem setleftbarbuttonitembarbuttonitem animatedyes selfmasterpopovercontroller popovercontroller voidsplitviewcontrolleruisplitviewcontroller splitcontroller willshowviewcontrolleruiviewcontroller viewcontroller invalidatingbarbuttonitemuibarbuttonitem barbuttonitem called when the view is shown again in the split view invalidating the button and popover controller selfnavigationitem setleftbarbuttonitemnil animatedyes selfmasterpopovercontroller nil,"['ios', 'objective-c']" +608151,nsurlsession getting intermittent sslhandshake failed 9810 error download image from secure url behind a security wall a url like sometimes i am getting a sslhandshake error sometimes the error happens once but sometimes the error is constant and i am unable to download the filedownloadimageapp2914 warning challenge nsurlauthenticationmethodservertrustdownloadimageapp2914 warning server foocomdownloadimageapp2914 warning cfnetwork sslhandshake failed 9810downloadimageapp2914 warning challenge nsurlauthenticationmethodservertrustdownloadimageapp2914 warning server foocomdownloadimageapp2914 warning challenge nsurlauthenticationmethodntlmdownloadimageapp2914 warning nsurlauthenticationmethodntlmi used the following code to handle challenges voidurlsessionnsurlsession session didreceivechallengensurlauthenticationchallenge challenge completionhandlervoid nsurlsessionauthchallengethisposition nsurlcredential completionhandler nslogchallenge challengeprotectionspaceauthenticationmethod if challengeerror nslog error challengeerrordescription if challengepreviousfailurecount 0 nslog previous failure count d challengepreviousfailurecount if challengeproposedcredential nslog proposed credential user challengeproposedcredentialuser if challengeprotectionspaceauthenticationmethod isequaltostringnsurlauthenticationmethodservertrust nslog server challengeprotectionspacehost completionhandlernsurlsessionauthchallengeusecredential nsurlcredential credentialfortrustchallengeprotectionspaceservertrust else if challengeprotectionspaceauthenticationmethod isequaltostringnsurlauthenticationmethodntlm nslog nsurlauthenticationmethodntlm nsurlcredential credential nsurlcredential credentialwithuserusername passwordpassworthissecretsh persistencensurlcredentialpersistenceforsession completionhandlernsurlsessionauthchallengeusecredential credential else nslog even when it fails completely and would not load i can still pop over to safari type in the url and have it load so i am looking for ideas which would cause this problem other than bad network issues or spotty issues with the hosting web server,['ios'] +608152,maximum hex value in regex without using u flag the hex range that can be used is x00xff but with u flag it goes up to a 4byte value x7f x0x7fso if i execute the below codepreg matchx0x80u str matchwill get this errorwarning preg match compilation failed character value in x sequence is too largeso i cannot match a letter like ii3 with equivalent hex value of f0 a1 83 81 the question is not how to match these letters but how this range this boundary came from as u modifier should treat strings as utf16pcre supports utf16 since v830echo pcre versionpcre version with php 5324 5328 5414 557832 20121130pcre version with php 5319 5323 549 5413831 20120706,['php'] +608215,how to render twig output to a variable for later use symfony2 instead of doing this rendering of each slide in my twig like this see line 6 loop out the slides for c in contents set ii1 increase slide number div idslide i claslide stylezindex i the slide itself rendered by it is own template include biztvarchivebundlecontenttemplatectemplateviewhtmltwig with contents c ordernumber i div endfor instead i would like to keep all of that logic in the controller to just deliver to the view an array of ready slides how can i do something like this see line 9 do stuff foreach containergetcontent as c contentititle cgettitle contentisort cgetsortorder contentidata cgetdata contentitemplate cgettemplategetid contentiduration thisextract secondsc contentihtml thisrenderbiztvarchivebundlecontenttemplatecontentitemplateviewhtmltwig array contents contenti ordernumber 99 all it gives me at the moment the contents of contentihtml is headers,['php'] +608224,create anonymous enum value from a subset of all values let us say we have an enum type defined asenum statuses completed pending notstarted startedi would like to make autofixture create a value for me other than eg pendingso assuming roundrobin generation i would like to obtaincompleted notstarted started completed notstarted,['c#'] +608279,wave animation in android textview i am using the following code to animate my textview in my oncreate methodtxtsizesettextthis is my texttxtsizesetanimationanimationutilsloadanimationmycontext androidranimslide in leftnow i wanted to ask if it is possible somehow to make this slide in left animation come in like a wavei have found this example here but i do not know how to use it in my case slide in from left to right and on textview not on a gridview thanks for any help,['android'] +608300,height 100 on flexbox column child i am having troubles with a flexbox column in that children of the flexd element do not respond to height in percentages i have only checked this in chrome and from what i understand it is a chrome only problem heres my examplehtmldiv classflexbox div classflex div classflexchilddiv div div clastaticdivdivcssflexbox positionabsolute backgroundblack width100 height100 thisplay flex flexdirectioncolumnflex backgroundblue flex1flexchild backgroundred height100 width100 thisplayblockstatic backgroundgreen width100 height5remheres the codepeni want it so the red flexchild fills the blue flex why does not height100 work,['css'] +608319,how do i get warningswarn to issue a warning and not ignore the line i am trying to raise a deprecationwarning with a code snippet based on the example shown in the docs officialdef deprecationmessage warningswarnmessage deprecationwarning stacklevel2mineimport warningswarningswarnthis is a warnings deprecationwarning stacklevel2 is none returns truei have tried removing the stacklevel argument setting it to negative 0 2 and 20 the warning is always silently swallowed it does not issue a warning or raise an exception it just ignores the line and returns none the docs does not mention the criteria for ignoring giving a message makes warningswarn correctly issue a userwarningwhat can be causing this and how do i get warn to actually warn,['python'] +608358,webstorm crashes and all my settings gone i was working with my webstorm 703 which used for editing the javascript code all of the sudden something went wrong with my system and everything froze had to cold reboot the system and when restarted the webstorm i saw these error messages stating that none of my settings that i spent hours to create and of course saved can be restoredthis is has may be a serious bug in websotrm which may cause lack of reliability of this product,['javascript'] +608381,prevent certain elements from receiving focus so i have the following function what it does is listens for the focus event on all elements if that element is either in mobilemenu or menuitems it permits it otherwise it removes the focusvar body bodyvar mobilemenu mobilemenuvar menuitems mainmenu abodyonfocusspf functione estoppropagation this this prevent items from recieving focus and switching view if thisismobilemenu thisismenuitems thisblur else consolelogthis the issue i have is that this prevents the user from focusing on anything whatsoever if a normally focusable element that is now nonfocusable precedes any of my whitelisted elements as it just attempts to refocus on the same element over and over againdoes anyone know how i can tell it to instead skip to the next focusable element,"['javascript', 'jquery', 'html']" +608437,how to open another window in javafx 2 i have made a simple javafx application but i would like the main window to open a secondary window when the user clicks a button what would be the simplest way to accomplish this,['java'] +608454,not enough quota is available to process this command wpf i am working on a wpf application i have implemented error handling and implemented error mail sending feature for this application so admin will get the error message if any error happened in the applicationmy issue is we are always getting a following error messageerror not enough quota is available to process this commandmswin32unsafenativemethodspostmessagehandleref hwnd windowmessage msg intptr wparam intptr lparam at systemwindowsinterophwndtargetupdatewindowsettingsboolean enablerendertarget nullable1 channelset at systemwindowsinterophwndtargetupdatewindowposintptr lparam at systemwindowsinterophwndtargethandlemessagewindowmessage msg intptr wparam intptr lparam at systemwindowsinterophwndsourcehwndtargetfiltermessageintptr hwnd int32 msg intptr wparam intptr lparam boolean handled at mswin32hwndwrapperwndprocintptr hwnd int32 msg intptr wparam intptr lparam boolean handled at mswin32hwndsubclassthispatchercallbackoperationobject o at systemwindowsthreadingexceptionwrapperinternalrealcalldelegate callback object args int32 numargs at msinternalthreadingexceptionfilterhelpertrycatchwhenobject source delegate method object args int32 numargs delegate catchhandlerwe have used mvvm light toolkit messengers task etc for this applicationalso i have a data grid in the applicationhow we trace this error anyone knows the reason of this anot enough quota is available erroraany help would be appreciablethanks in advance,['c#'] +608560,msvc12 thinks aggregate derived from stdarray is not pod given the followinginclude arraystruct litmus final stdarrayunsigned char 16static assertstdis podstdarrayunsigned char 16 value not pod this fails on msvcstatic assertstdis podlitmusvalue not podthe following compilers agree that litmus is podclang version 35 trunk 198621 g 481 however msvc12 vs2013 rtm maintains that the second assert failswhos rightis there any trick to make msvc treat the class as podedit for information is trivially copyablelitmus returns trueness on msvc this might be useful for many cases where actual podness is not strictly required,['c++'] +608638,abstract class extends concrete class i earlier learned that abstract class can extend concrete class though i do not see the reason for it from java designers but it is oki also learned that abstract class that extends concrete class can make overriden methods abstract why can you provide with use case where it is useful i am trying to learn design patterns and i do not want to miss anything here is examplepublic class foo public void test public abstract class bar extends foo override public abstract void test,['java'] +608653,css zindex not working position absolute i am trying to make the black div relative above the second yellow one absolute the black divs parent has a position absolute toocodediv classabsolute div idrelativedivdivdiv classabsolute styletop 54pxdivstylerelative position relative width 40px height 100px background 0 zindex 1 margintop 30pxabsolute position absolute top 0 left 0 width 200px height 50px background yellow zindex 0stylejsfiddle,"['html', 'css']" +608655,qfile does not recognize file url path format i get the file path from qml like thismainviewprojectfilepath qtresolvedurlnewprojectfiledlgfileurltostringthe above file path looks like this filecua3but when this path is passed to qfile it complains the filename directory name or volume label syntax is incorrecthow to solve this problem,['c++'] +608661,sql server insert if not exist i want to insert data in my table but insert only that does not exist in my dbhere is my codealter procedure dboemailsrecebidosinsert de nvarchar50 assunto nvarchar50 data nvarchar30 asbegin insert into emailsrecebidos de assunto data values de assunto data where not exists select from emailsrecebidos where de de and assunto assunto and data dataendand the error is msg 156 level 15 state 1 procedure emailsrecebidosinsert line 11 incorrect syntax near the keyword where,['sql'] +608686,access session variables in javascript i wanted to access a session variable in javascript in aspnet mvc application i have found a way to do it in aspx view engine but not in razorplease tell me a way to access the session variables,"['javascript', 'asp.net']" +608694,uisearchbar automatically resizes and changes frame i have an issue with a search bar that behaves in a strange way when it becomes a firstresponder and when it resignsthe search bar is added as the header of a table viewselfsearchbar uisearchbar alloc initwithframecgrectmake00f 00f selfviewframesizewidth 440fselfsearchbartranslucent noselfsearchbarbartintcolor uicolor graycolorselftableviewtableheaderview selfsearchbarselfsearchcontroller uisearchthisplaycontroller alloc initwithsearchbarselfsearchbar contentscontrollerselfselfsearchcontrollersearchresultsdatasource selfthe view controller is set a left panel of jasidepanelcontroller and it hides the center panel when the keyboard shows or hides voidkeyboardwillappearnsnotification note selfsidepanelcontroller setcenterpanelhiddenyes animatedyes durationnoteuserinfo objectforkeyuikeyboardanimationdurationuserinfokey doublevalue selfsearchbarshowscancelbutton yes voidkeyboardwillthisappearnsnotification note selfsidepanelcontroller setcenterpanelhiddenno animatedyes durationnoteuserinfo objectforkeyuikeyboardanimationdurationuserinfokey doublevalue selfsearchbarshowscancelbutton nonormal state when the search bar becomes a firstresponder it either moves about a point up or point down randomlyand when the search bar resigns it animates up to reach the window origin and then back to its natural framehere is a sample project reproducing the bugedit as per kwylez suggestion the unwanted animation that the search bar makes when it resigns can be avoided byselfsearchbarclipstobounds yes,['ios'] +608795,storing tamil language text into mysql am developing a tamil website using aspnet mvc and mysql while updating the values tamil language text from aspnet mvc website to database all my values as storing as format like this when i directly run the insert query into my database i am able to insert the tamil text into the databaseaspnet mvc i have the below code meta charsetutf8 mysql create table syntax create table if not exists login id int11 not null auto increment username text collate utf8 unicode ci password mediumtext collate utf8 unicode ci primary key id enginemyisam default charsetutf8 collateutf8 unicode ci auto increment6 note i have been using the entity framework to connect with the mysql databaseis any thing missing from my sidefrom commentsolution found just add charsetutf8 to connection string here is the working solution add namephotostorageentities connectionstringmetadataresmodelsphotoscsdl resmodelsphotosdlaaresmodelsphotosmsl providermysqldatamysqlclient provider connection stringquotserverserverip user iduidpasswordpass persist security infotruedatabasephotostorage charsetutf8quot providernamesystemdataentityclient thanks everyone,['mysql'] +608818,problems with animation when deleting the last row of a tableview in ios7 i am having some issues when deleting the last row of my only section in my tableview any other row works fine but if i delete the row at the bottom of my tableview at any time not just when its the last one left the animation is very strange and laggy it just does not look right i have also noticed that changing the animation type does not do anything the animation is always when the row slides up to the top and thisappears changing it to uitableviewrowanimationfade or another does not do anything here is my codefor the edit barbuttonitem in my storyboard ibactioneditbuttonpressedidsender enter editing mode if selfeditbuttontitle isequaltostringedit self seteditingyes animatedyes selfeditbuttontitle done else self seteditingno animatedyes selfeditbuttontitle edit editing the tableview the user can only delete rows not add any uitableviewcelleditingstyletableviewuitableview tableview editingstyleforrowatindexpathnsindexpath indexpath return uitableviewcelleditingstyledelete voidtableviewuitableview tableview commiteditingstyleuitableviewcelleditingstyleeditingstyle forrowatindexpathnsindexpath indexpath if row is deleted remove it from the list if editingstyle uitableviewcelleditingstyledelete handle the data source and backend first then the tableview row pfrelation hasfavorites selfcurrentuser relationforkeyhasfavorites hasfavorites removeobjectselffavorites objectatindexindexpathrow selffavorites removeobjectatindexindexpathrow it is set to fade here but it only ever does the top animation selftableview deleterowsatindexpathsnsarray arraywithobjectindexpath withrowanimationuitableviewrowanimationfade save to the backend selfcurrentuser saveinbackgroundwithblockbool succeeded nserror error if error else nslog error erroruserinfo i have looked at every answer i can find with no luck i return 1 in my numberofsections in tableview because i only ever want one section and i should be able to have 0 rows in a section so i do not think that is the problem,['ios'] +608843,set flexbox children to have different heights to use up available space using a twocolumn flexbox layout how can differentsized children be made to fill all available space instead of all children having the height of the tallest child of the rowi set up a demo on jsbin that illustrates the problem i would like for all the children to be the size of their wrapped contentscontainer width 800px thisplay flex flexwrap wrapcell width 300px flex 1 autodiv idcontainerdiv classcellcells with arbitrarily long contentdivdiv classcelldivdiv classcelldivdiv classcelldivdiv classcelldivdivbodyhtml,['css'] +608912,send byte array in nodejs to server i cannot figure out to send byte array while being connected to server on debian is there any alternative to sending string via clientwrite i tried clientwritenew buffersomething but this gives invalid data error here is my codevar net requirenetfunction modernbufferbuffer custom buffer class thisbuffer new arraybufferbufferlength thisbytelength thisbufferbytelength consolelogmodernbufferbytelength thisbytelength var uint16view new uint16arraythisbuffer 0 1 for var i0 iuint16viewlength i uint16viewi bufferi consolelogentry i uint16viewi var client netconnect host someippl port 7171 function this ip is not important until i figure out how to send correct bytes consolelogserver connected var bytes array6 array of bytes to be send bytes0 0x4 bytes1 0x0 bytes2 0xff bytes3 0x01 bytes4 0x20 bytes5 0x0function ab2strbuf first arraybuffer to string functiongives me 4 bytes instead of 6 at the end return stringfromcharcodeapplynull new int8arraybuf function strfromutf8abab that gives me 0 bytes return decodeuricomponentescapestringfromcharcodeapplynull ab sendbuffer new arraybuffer6 intview8 new int8arraysendbuffer var str forvar i 0 i intview8length i intview8i bytesi consolelogintview length intview8length entry i intview8i var sendmsg ab2strsendbuffer 4 bytes instead of 6 var sendmsg strfromutf8absendbuffer 0 bytes instead of 6 var binarystring var bytes array6 bytes0 0x4 bytes1 0x0 bytes2 0xff bytes3 0x01 bytes4 0x20 bytes5 0x0 var length byteslength another try to convert bytes to string gives me 7 instead of 6 and they are badfor var i 0 i length i binarystring stringfromcharcodebytesi sendmsg binarystring test final string which is sent t forsunescapeencodeurisendmsgi0islengthi tpushscharcodeaticonsolelogt end clientwritesendmsg not important until i figure out how to send correct bytes var server netcreateserverfunctionc test server to send bytes to testclient consolelogserver connected conend function consolelogserver thisconnected cwritesendmsg send bytes converted to stringserverlisten7654 function consolelogserver boundclientondata functiondata consolelog new modernbuffer new modernbufferdataclientontimeout function consolelogserver timeoutclientonerror functionerror consolelogserver error errorclientonend function consolelogserver client thisconnectedi am also running a client on windows with same code except createserver partoutputdebian rootks203255homekuzinode node appjsserver sauchaserver connectedintview length 6 entry 0 4intview length 6 entry 1 0intview length 6 entry 2 1intview length 6 entry 3 1intview length 6 entry 4 32intview length 6 entry 5 0 4 0 195 191 1 32 0 final bytes instead of those upserver boundserver client thisconnectedserver connectedwindowscusersdanielnode appjsserver sauchaserver connectedintview length 6 entry 0 4intview length 6 entry 1 0intview length 6 entry 2 1intview length 6 entry 3 1intview length 6 entry 4 32intview length 6 entry 5 0 4 199 191 32 i am showing only first 4 bytes but new modernbufferbytelength 7 you can see it is 7 instead of 6 and they are bad so i am sure it is wrong4 0 195 191entry 0 4help would be greatly appreciated,['javascript'] +608931,should a constructor parse input often i find that i must instantiate a bunch of objects but i find it easier to supply the parameters for this instantiation as a humanreadable text file which i manually compose and feed into the program as inputfor instance if the object is a car then the file might be a bunch of rows each containing the name speed and color the three mandatory constructor parameters delimited with tabsmy car 65 redarthurs car 132 pinkold junk car 23 rust brownthis is easy for me to inspect visually modify or generate by another program the program can then load the file take each row parse out the relevant parameters feed them into a carstring name int speed uint color constructor and create the objectnotice how there is some work that must be done on the input before it is compatible with the constructor the speed must be converted from string to int with a call to intparse the color must be matched to a rgb value by looking up the english color name perhaps the program would access wikipedia to figure out each colors value or consults a predefined map of name rgb somewheremy question is from an oop standpoint who should do this parsing the constructor or the method calling the constructorwith the first option the advantage is simplicity the calling function must only doforeachvar row in input file list of objects that i am populatingaddnew carrowand all the ugly parsing can be nicely contained in the constructor which does not have much other code anyhow so the parsing code can be easily read and modified without being thistracted by nonparsing codethe thisadvantage is that code reuse goes out the window because now my object is joined at the hip to an input format worse because the input format is adhoc and manually composed it is ephemeral and potentially not guaranteed to stay the same if i reuse this object in another program where i decide that it is convenient to slightly change the formatting of the input file the two versions of the object definition are now divergent i often find myself defining input formats in the comment section of the constructor which seems a bit codesmellyanother thisadvantage is that i have lost the ability to do batch operations recall the earlier example problem of mapping color names to values what if i was using a web service that takes 1 minute to process every individual request regardless of whether that request is asking to convert one color name or a million with a very large input file i would drastically slow down my application by accessing the service once for each row instead of submitting one big request for all rows and then instantiating the objects according to the replywhat is the correct way to handle a situation like this should i parse input the constructor and treat the problems above as exceptional issues that must be dealt with on a casebycase basis should i let my calling method do the parsing even though it may already be bloated with much convoluted program logic,['c#'] +608948,how can nonascii characters be detected in a qstring i want to detect if the user has inputted a nonascii otherwise incorrectly known as unicode character for example a in a file save dialog box as i am using qt any nonascii characters are properly saved in a qstring but i cannot figure out how to determine if any of the characters in that string are nonascii before converting the string to ascii that character above ends up getting written to the filesystem as a,['c++'] +608970,ios background app is slow to respond from mpnowplayinginfocenter i created a music app that is wired up to mpnowplayinginfocenter i have a bunch of methods that do various things next pause etc however when i hit the next button in mpnowplayinginfocenter the app responds immediately and calls the method instantly when the app is active however when the app is playing the background and i hit next from mpnowplayinginfocenter it responds but after a few secondshas anyone else experienced this or have any idea what the culprit might be here,"['ios', 'objective-c']" +608978,sync is unreliable using stdatomic and stdcondition variable in a thistributed job system written in c11 i have implemented a fence ie a thread outside the worker thread pool may ask to block until all currently scheduled jobs are done using the following structurestruct fence stdatomicsize t counter stdmutex resume mutex stdcondition variable resume fencesize t num threads counternum threads the code implementing the fence looks like thisvoid task poolfence implvoid arg auto f fence arg if fcounter 0 1 we have zeroed this fences counter wake up everyone that waits fresumenotify all 2 else unique lockmutex lockfresume mutex fresumewaitlock 3 this works very well if threads enter the fence over a period of time however if they try to do it almost simultaneously it seems to sometimes happen that between the atomic decrementation 1 and starting the wait on the conditional var 3 the thread yields cpu time and another thread decrements the counter to zero 1 and fires the cond var 2 this results in the previous thread waiting forever in 3 because it starts waiting on it after it has already been notifieda hack to make the thing workable is to put a 10 ms sleep just before 2 but that is unacceptable for obvious reasonsany suggestions on how to fix this in a performant way,['c++'] +609000,jquery select multiple attributes and checkuncheck another checkbox how i can identify following checkboxes in different rows and checkuncheck them separatelyinput typecheckbox valuef nameephds2457input typecheckbox valuepr nameephds2457input typecheckbox valuedph nameephds2457input typecheckbox valuef nameephds2450input typecheckbox valuepr nameephds2450input typecheckbox valuedph nameephds2450where number is dinamically createdexample if f is checked uncheck pr if pr is checked uncheck f if dph is checked uncheck all checkboxchangefunction var current thisvalue if current f checkboxvalueprpropchecked false if current pr checkboxvaluefpropchecked false if current dph checkboxvaluefpropchecked falsecheckboxvalueprpropchecked false this code is working but if i deselect checkbox in the second row then checkbox in first row will be unchecked too,['jquery'] +609006,bootstrap modal sitting behind backdrop so i am having nearly the exact same problem as jamescoo was but i think that my issue is coming from the fact that i have already positioned a couple of divs to create a sliding nav panelheres my exact setup replicated bonus feel free to grab the code for the sliding panel if youd like the zindexes should not conflict and their values would show that they are stacking correctly but visually they are notonce you click the open modal button the div classmodalbackdrop fade indiv covers everything youll have to rerun the code to reset iti do not know quite how to remedy this oneany ideas,['css'] +609031,need some clarification about betaalpha testing on the developer console backgroundthe android developer console has 3 tabs for publishing the apps apk filealpha beta and production as shown hereas i recall from one of google io lectures one cool way to check how good is your app before making a 100 scale publishing is to allow only a percentage of the users to download the app first i think it is called staged rollouts because you can rollout the publishing in case it had too many problems to be published to allmy questionwhat is exactly the difference between them especially between alpha and betaonly the production stage is available for people on the play store rightwhich ones allow to publish only to specific peoplepercentage and in which way do you do itwhich stage allows inapp billing at least for testing i do not get why cannot i test it out even before uploading the appin the percentage method if i publish a new app version using the same way will it first update for the people who were lucky enough to install the previous version,['android'] +609035,invalid conversion from const char to char have a code as shown below i have problem passing the argumentsstringstream datachar addrnullstrcpyaddrretstringc strretstring is a function that returns a stringmore codeprintfuncnumaddrdatastrc stri get the error invalid conversion from const char to char initializing argument 3 of void printfuncint char charon argument 3 of the function on the above line the function is called as shown belowvoid printfuncint achar loc char streamplease let me know if i need to change any initialization,['c++'] +609058,how can i safely return list from methodproperty declared as ienumerable let us say i have ienumerableint property backed with listint field so i can modify the collection from within the class but it is publicly exposed as readonlypublic class foo private listint bar new listint public ienumerableint bar get return bar but with code like that you can easily cast object retrieved from the property back to listint and modify itvar foo new foovar bar listintfoobarbaradd10question is what is the best best readable easiest to write without performance loss way to avoid thati can come up with at least 4 solutions but non of them is perfectforeach and yield returnpublic ienumerableint bar get foreach var item in bar yield return item really annoying to write and to read asreadonlypublic ienumerableint bar get return barasreadonly will cause exception when someone tries to modify the returned collection does not create a copy of the entire collectiontolistpublic ienumerableint bar get return bartolist user can still modify retrieved collection but it is not the same collection we are modifying from within the class so we should not care creates a copy of entire collection what may cause problems when collection is bigcustom wrapper classpublic static class myextensions private class myenumerablet ienumerablet private icollectiont source public myenumerableicollectiont source source source public ienumeratort getenumerator return sourcegetenumerator ienumerator ienumerablegetenumerator return ienumerable sourcegetenumerator public static ienumerablet asmyenumerabletthis icollectiont source return new myenumerabletsource usagepublic ienumerableint bar get return barasmyenumerable do not need to clone the collection when you use it as linq queries source some methods would not use icollectioncount because you do not expose itis there any better way to do that,['c#'] +609098,print all fields of ctypes structure with introspection testcinclude stdiohinclude stdlibhstruct s char a int b float c double dstruct s create struct struct s res mallocsizeofstruct s resa 1 resb 2 resc 30f resd 40 return restestpyfrom ctypes import class sstructure fields a c byte b c int c c float d c double lib cdlltestsocreate struct libcreate structcreate structrestype pointerscreate structargtypes s ptr create structs s ptrcontentsprint s fields 00 saprint s fields 10 sbprint s fields 20 scprint s fields 30 sdprint s dict outputa 1b 2c 30d 40i would like to adapt the python script above to print each field of my s structure without having to do explicitly for each field from what i understand this can be done using the dict attribute but mine is empty is there any way to do this for a class that extends ctypesstructure,['python'] +609113,pycharm is community edition able to highlight cssjavascript i am exploring the features of pycharm to decide if i should use itnow pydev all looks great but i have not find a way to make pycharm highlight css or js filesis this a functionality which only provided in the commercial edition,['python'] +609134,cython why when is it preferable to use py ssize t for indexing this is a followup to this questionwhy when is it preferable to use py ssize t for indexing in the docs i just found purists could use py ssize t which is the proper python type for array indices does that mean always when indexing numpycython arraysviews one should use py ssize t is py ssize t e g an unsigned int so that i cannot used cythonboundscheckfalse,['python'] +609187,a longrunning parse operation is being executed on the main thread i am getting the errora longrunning parse operation is being executed on the main thread break on warnparseoperationonmainthread to debugandbreak on warnparseoperationonmainthread to debugi am unable to locate the error within my code can someone please tell me what i am doing wrongpfquery query pfquery querywithclassnameuserquery getobjectinbackgroundwithidpfuser currentuser objectid blockpfobject object nserror error selffirstname objectfirstname selflastname objectlastname selfnamelabeltext nsarray arraywithobjectsselffirstname selflastname nil componentsjoinedbystring,"['ios', 'objective-c']" +609209,why python need rich comparison there is a confusion for me for some time is there a scene that we do need to use rich comparison in pythoni read the official doc here but it only gives how it works not why we need ita snippet of the doc the truth of xy does not imply that xy is false may describe a scene that we need rich comparison in this scene we can make eq and ne both return false for thisabling the comparsion or any other purpose we can implement this by using cmp but this just a guess i have never encountered such a requirement in a real project yetdoes anyone need to use rich comparison indeed or is there any other scenario where we need to use rich comparison in theorymaybe my example of xy and xy caused some confusion sorry for thatlet me make it a bit clearerare there any scenario where rich comparison can help but cmp can not,['python'] +609231,show first character of selected option in select i have a select box like thisselect idselectbox1 option valuessecondoption option valuemminuteoption option valuehhouroption option valueddayoption option valuewweekoption option valuetmonthoption option valueyyearoptionselecti want when i select for example 1st option second just s appear on select box and so onand when its open for another select again show second,"['javascript', 'html']" +609306,ios7 font size change when create nsattributedstring from html i have a uitextview where i am managing an nsattributedstring initially entered as normal via the keyboard i save the attributed string as html which looks finewhen i load it again and convert it back to an attributed string from the html the font size appears to changefor example the html on loading looks like thisdoctype html public w3cdtd html 401en htmlheadmeta httpequivcontenttype contenttexthtml charsetutf8meta httpequivcontentstyletype contenttextcsstitletitlemeta namegenerator contentcocoa html writerstyle typetextcsspp1 margin 00px 00px 00px 00px font 210px helvetica color 0 webkittext stroke 0spans1 fontfamily helvetica fontweight normal fontstyle normal fontsize 2100pt fontkerning nonestyleheadbodyp classp1span clas1there is some text as usual lots of textspanpbodyhtmli convert it and check the attributes with the following code convert to attributed string nserror err nsattributedstring as nsattributedstring alloc initwithdatadata3 optionsnsdocumenttypedocumentattribute nshtmltextdocumenttype nscharacterencodingdocumentattribute nsutf8stringencoding documentattributesnil errorerr nsmutableattributedstring res as mutablecopy res enumerateattributensfontattributename inrangensmakerange0 reslength options0 usingblockid value nsrange range bool stop if value uifont oldfont uifont value nslogon loading font size f in range from d length d oldfontpointsize rangelocation rangelength the output shows that the font size has increased from 21 to 28on loading font size 280 in range from 0 length 40on loading font size 210 in range from 40 length 1basically each time i load the string the font size increases i need to store it as html rather than as nsdata because it will also be used by other platformsdoes anyone have any ideas why this is happening,['html'] +609375,what is the purpose of the android private libraries referenced libraries and android dependies in android project hierarchy i want to know the exact use of android private libraries referenced libraries and android dependencies in an android project hierarchy,['android'] +609495,jetty embedded jersey 2 weld i am using jetty 91 and jersey 251 jersey has builtin support for jetty so i start my server like thatpublic static void mainstring args uri baseuri uribuilderfromurihttplocalhostport8080build resourceconfig config resourceconfigforapplicationclassmyapplicationclass server server jettyhttpcontainerfactorycreateserverbaseuri configmyapplication simply calls thispackages to lookup my rest api classeshowever the rest api class contains a inject annotated field which should be injected by weld obviously weld is not started cdi support not enabled and weirder it looks like hk2 used by jersey 2 is trying to perform the injectioni have a orgglassfishhk2apiunsatisfieddependencyexception when hitting the rest endpointhow do i setup correctly weld preferably programmatically,['java'] +609549,is null considered zero and undefined not a number on arithmetic expressions is null evaluated to 0 and undefined to nan on arithmetic expressionsaccording to some testing it seems so null null0 4 null4 undefined undefinednan 4 undefinednanis it safe or correct to assume this a quote from a documentation would be a,['javascript'] +609568,calling angularjs scope function from href i am using a library which appends a href element onto an tag on this link i need to make a call to an angularjs function that is within scope something likea hrefsomefunctionanote i am attaching this href via javascript from another library nvd3js not actually writing this in because if i was i could easily use ngclick or nghref,['javascript'] +609587,whats aspnetmvc doing before my controller i have got a bit of a strange performance issue occurring with my mvc controller or rather before itaccording to the mini profiler output there is a 120ms overhead before reaching my controllerdoes anyone know why this would be this is on a server not local that has compilation debugfalse set so it is not an issue of not running in release modeeverything after it i can tuneamend but before it and i am lostthoughtsupdateafter some performance tooling i came across enter link description here enter link description here which resulted in the belowmost expensive stacks systemwebhttpapplicationcallhandlerexecutionstepsystemwebhttpapplicationiexecutionstepexecute systemwebhttpapplicationexecutestep systemwebhttpapplicationpipelinestepmanagerresumesteps systemwebhttpapplicationbeginprocessrequestnotification systemwebhttpruntimeprocessrequestnotificationprivate systemwebhostingpipelineruntimeprocessrequestnotificationhelper systemwebhostingpipelineruntimeprocessrequestnotification systemwebhostingunsafeiismethodsmgdindicatecompletion systemwebhostingpipelineruntimeprocessrequestnotificationhelper systemwebhostingpipelineruntimeprocessrequestnotification cost 1716011microsoftpracticesobjectbuilder2buildplanstrategyprebuildup microsoftpracticesobjectbuilder2strategychainexecutebuildup microsoftpracticesobjectbuilder2buildercontextnewbuildup microsoftpracticesobjectbuilder2buildplanstrategyprebuildup microsoftpracticesobjectbuilder2strategychainexecutebuildup microsoftpracticesobjectbuilder2buildercontextnewbuildup microsoftpracticesobjectbuilder2buildplanstrategyprebuildup microsoftpracticesobjectbuilder2strategychainexecutebuildup microsoftpracticesobjectbuilder2buildercontextnewbuildup microsoftpracticesobjectbuilder2buildplanstrategyprebuildup microsoftpracticesobjectbuilder2strategychainexecutebuildup microsoftpracticesunityunitycontainerdobuildup microsoftpracticesunityunitycontainerdobuildup systemwebmvcdefaultcontrollerfactorydefaultcontrolleractivatorcreate systemwebmvcdefaultcontrollerfactorycreatecontroller systemwebmvcmvchandlerprocessrequestinit systemwebmvcmvchandlerc thisplayclass6b 2 systemwebmvcsecurityutilc thisplayclassb1b a systemwebmvcsecurityutilprocessinapplicationtrust systemwebhttpapplicationcallhandlerexecutionstepsystemwebhttpapplicationiexecutionstepexecute systemwebhttpapplicationexecutestep systemwebhttpapplicationpipelinestepmanagerresumesteps systemwebhttpapplicationbeginprocessrequestnotification systemwebhttpruntimeprocessrequestnotificationprivate systemwebhostingpipelineruntimeprocessrequestnotificationhelper systemwebhostingpipelineruntimeprocessrequestnotification systemwebhostingunsafeiismethodsmgdindicatecompletion systemwebhostingpipelineruntimeprocessrequestnotificationhelper systemwebhostingpipelineruntimeprocessrequestnotification cost 936006microsoftwin32win32nativecocreateguid stackexchangeprofilingtimingctor stackexchangeprofilingmvchelpersprofilingviewenginefind systemwebmvcviewenginecollectionc thisplayclasscb a systemwebmvcviewenginecollectionfind systemwebmvcviewenginecollectionfind systemwebmvcviewresultfindview systemwebmvcviewresultbaseexecuteresult systemwebmvccontrolleractioninvokerc thisplayclass1cb 19 systemwebmvccontrolleractioninvokerinvokeactionresultfilter systemwebmvccontrolleractioninvokerinvokeactionresultfilter systemwebmvccontrolleractioninvokerinvokeactionresultwithfilters systemwebmvccontrolleractioninvokerinvokeaction systemwebmvccontrollerexecutecore systemwebmvccontrollerbaseexecute systemwebmvcmvchandlerc thisplayclass6c thisplayclassbb 5 systemwebmvcasyncasyncresultwrapperc thisplayclass1b 0 systemwebmvcmvchandlerc thisplayclasseb d systemwebhttpapplicationcallhandlerexecutionstepsystemwebhttpapplicationiexecutionstepexecute systemwebhttpapplicationexecutestep systemwebhttpapplicationpipelinestepmanagerresumesteps systemwebhttpapplicationbeginprocessrequestnotification systemwebhttpruntimeprocessrequestnotificationprivate systemwebhostingpipelineruntimeprocessrequestnotificationhelper systemwebhostingpipelineruntimeprocessrequestnotification systemwebhostingunsafeiismethodsmgdindicatecompletion systemwebhostingpipelineruntimeprocessrequestnotificationhelper systemwebhostingpipelineruntimeprocessrequestnotification cost 7805could unity be cause some issues,"['c#', '.net']" +609702,ios is motion activity enabled in settings privacy motion activity if an app requires access to motion activity data it asks the user at install however if the user accidentally answers no then the app will not worki am looking for a way to check if the motion activity is enabled so that i can prompt the user to enable if notcan someone point me in the right direction code wise please following the info from doc thank you it seems that apple do not provide a direct method to check the status of motion activity in privacy i was able to find out by picking up on the errorstepcounter querystepcountstartingfromnsdate date tonsdate date toqueuensoperationqueue mainqueue withhandlernsinteger numberofsteps nserror error if error nil errorcode cmerrormotionactivitynotauthorized the app is not authorized to use motion activity support,['ios'] +609727,how to load all entries in an infinite scroll at once to parse the html in python i am trying to extract information from this page the page loads 10 items at a time and i need to scroll to load all entries for a total of 100 i am able to parse the html and get the information that i need for the first 10 entries but i want to fully load all entries before parsing the htmli am using python requests and beautifulsoup the way i parse the page when it loads with the first 10 entries is as followsfrom bs4 import beautifulsoupimport requestss requestssessionr sgetpage beautifulsouprtextbut this only loads the first 10 entries so i looked at the page and got the ajax request used to load the subsequent entries and i get a response but it is in the a funky json and i would rather use the html parser instead of parsing json heres the codefrom bs4 import beautifulsoupimport requestsimport jsons requestssessionurl payload count100r sposturl datapayloadpage jsonloadsrtext16 skip some chars that throw json offthis gives me the data but it is in a very long and convoluted json i would much rather load all the data on the page and simply parse the html in addition the rendered html provides more information than the json response ie the name of the author instead of obscure userid etc there was a similar question here but no relevant answers ideally i want to make the post call and then request the html and parse it but i have not been able to do that,"['python', 'html']" +609770,mtaudioprocessingtap kills mediaserverd at breakpoints when using avplayer with mtaudioprocessingtap stopping at a breakpoint anywhere in the application on any thread will cause mediaserverd to die temporarily this can be observed by setting a breakpoint anywhere in apples sample app audiotapprocessorfor example you can set it in the updatecenterfrequencyslidervalue method in mysettingsviewcontrollerm i also have an even smaller sample app i can post if it is helpfulthis error message usually only appears in the devices console log viewable in organizer but sometimes also appears in the apps debugger log error 174804833 error 0x28c0 75 audioqueueprocessingtapgetsourceaudio posting message to kill mediaserverd 45playback usually resumes several seconds after continuing past the breakpoint the avaudiosessionmediaserviceswereresetnotification is not postedis this expected behavior or does it indicate a problem is there any way to avoid it if you are using mtaudioprocessingtap and regularly encounter this has it been an issue for your development or debugging processi would also be interested in any feedback on whether mtaudioprocessingtap is ready for primetime generally since it is a relatively new and lightly documented componentthanks in advance,['ios'] +609772,how do i use a virtualenv to evaluate python in light table how do i use a virtualenv to evaluate python in the light table idei run all my projects under virtualenvs and all the virtualenvs are located in subfolders within virtualenvsvery standard practicei see that lighttable supports behaviors on a perworkspace setting so is there some way to set a behavior that ties a workspace to a particular virtualenv path,['python'] +609807,cross domain requests not working with soundcloud in safari i simply cannot get a json response in safari calling soundclouds apivar inputseturlseturl clientidclient idclient idgetjson extendinputset clientid function data consolelogdatathis returns an origin accesscontrol error in safari but not in chrome cors is not working at all saw cors not working at all implemented working answer exact same error only safariadding a callback parameter does not return that error however returns the ajax error parsererror syntaxerror which i presume is due to the response still being json and not jsonp this does not work in either browseras it stands i cannot get this cross domain request working in chrome even though the docssay i cansafari network tabsafari responseerror failed to load resource origin is not allowed by accesscontrolalloworigin 172350json line 0error xmlhttprequest cannot load idclient id origin is not allowed by accesscontrolalloworigin seamli line 0linked page loads fine in browser,"['javascript', 'jquery']" +609822,how do i get intellij to give me a warning if i have failed to provide javadoc descriptionannotation for public fields and methods eclipse is able to provide warnings if javadoc has been unfulfilled for a particular method or fieldthese fieldsmethods can be grouped by scope public protected etc i have found this very useful indeed when preparing my software for submission for university or whateveris this not possible in intellijnote that i am aware that you can hit just before a method in intellij and it will fill it out this is not exactly what i am after also note that i am using intellij 1301 community edition,['java'] +609902,is it possible to write data to file using only javascript i want to write data to existing file using javascripti do not want to print it on consolei want to actually write data to abctxti read many answered question but every where they are printing on consoleat some place they have given code but its not workingso please can any one help me how to actually write data to filei referred the code but its not workingits giving error uncaught typeerror illegal constructor on chrome and securityerror the operation is insecureon mozillavar f sometextfiletxtwritetextfilef spoonwritetextfilef cheese monkeywritetextfilef onionfunction writetextfileafilename output var txtfile new fileafilename txtfilewritelnoutput txtfilecloseso can we actually write data to file using only javascript or notplease help me thanks in advance,"['javascript', 'jquery', 'html']" +609917,why the statement foo init is foo init return false codeclass fobject passfoo foofoo init foo init return truefoo init is foo init return falsei can understand foo init foo init returns truewhy foo init is foo init return false,['python'] +609979,c streams copy data from one stream to another directly without using a buffer i want to copy data from one stream to another now normally i would do it this wayn freadbuffer 1 bufsize finfwritebuffer 1 n foutis there a way to write the data directly from fin to fout without going through a buffer ie instead of finbufferfout i want to directly do finfout no bufferis it possible to do so in ansi c if not is it possible to do it with posix functions or a linuxspecific solution,['c'] +609996,vertical scrolling not working in uiscrollview and ios7 and xcode 5 despite not using autolayout when i tried to use uiscrollview in ios 7 and xcode 5 it does not respond to vertical scrolling i first drag and drop scrollview from object library to storyboard and set its size as width 320 and height 1500 and then drag and drop three labels and locate those labels at y 300 800 1200 for labels whose y coordinate being equal to 800 and 1200 i first move scrollview to the upper to make those objects located at the corresponding y values then i connect scrollview to implementation file as outlet and in viewdidload method i write selfmyscrollviewcontentsize cgsizemake320 1500 and finally set back the size of scrollview at width 320 and height 568and then run the simulator but it does not react to vertical scrolling then i deselected use autolayout and run the simulator again it is still not working at allso how can i fix the issue or can anyone inform me of any useful tutorials which teach about uiscrollview in ios 7 and xcode 5 this is important since every tutorial i have read is based on the prior versioni use xcode 502thanks,"['ios', 'objective-c']" +610055,android support library increases apk size a lot i am using appcompat support library in my android project appcompat has plenty of drawables and resources which i do not use in my app that unnecessary files increases my 900k app to above 2m which i do not likeis there any way to exclude those files when creating the apk file or i should obfuscate the library in my code instead of making a dependency i am using gradle in android studiothanksedit 1 i am using proguard already but proguard cannot know i do not want to have drawablexhdpi or valuesit for exampleedit 2 i am also using android lint which cannot help me beacuse i do not access to libs code directly and android adds them when building the apk file,['android'] +610094,add to homescreen button in android does not show website as a web app i have created a mobilefriendly web site with jquery mobile and added some meta info so that it should be pinned to ios and android homescreens and should be launched as a web app in other words in a browser but without browser navigation elementsit works fine for ios but it does not work for android 442 i followed the this tutorial for creating androidcompatible web apps heres the the web site i have createddespite adding all the meta info as listed in the tutorial android does show the add to homescreen button for my web site but it does not launch the website without browser navigation elements as described in the tutorialwhat am i doing wrong,['android'] +610104,bootstrap select plugin not work with jquery validation i design my html selectbox using bootstrap select plugin now i add jqueryvalidation plugin for validate my form but validation form not work with bootstrap select plugindemo herehtmlform idmyform select nameyear claselectpicker option valueyearoption option value11955option option value21956option select br input typesubmit formjsdocumentreadyfunction selectselectpicker myformvalidate initialize the plugin rules year required true submithandler function form for demo alertvalid form submitted for demo return false for demo note for check this conflict remove line 2 from js jquery validation workededit adeneo fix problem using ignore method fiddlemyformvalidate initialize the plugin ignore rules year required true errorplacement functionerror element if elementattrname year errorinsertafterbootstrapselect else errorinsertafterelement submithandler function form for demo alertvalid form submitted for demo return false for demo now this worked but i have new problem in normal validation after select fields error message this field is required auto hide or with add any css show success message but now error message is show after fix required field in act when we choose years error message not hidehow do fix this,"['javascript', 'jquery']" +610125,how come i can install an app store thistribution build directly on my device i was under the impression that it was impossible to install an app store thistribution build directly on a test device without going through the actual app store i found multiple references to the following note by apple though i could not find the note itself in the current version of the ios app thistribution guideapp store provisioning profiles do not allow for a thistribution built application to be installed on an apple device to install your thistribution ready application on a device you must create an ad hoc provisioning profilenow consider the following i have an ad hoc thistribution provisioning profile and an app store thistribution provisioning profile the ad hoc profile contains a list of provisioned devices the app store profile does not my no jailbrake device is included in the provisioned devices in the ad hoc profile my build was signed with the app store profile the resulting ipa file was submitted to the app store and approved but it is not publicly available yet when i view the package contents of the ipa file i see that the embeddedmobileprovision is indeed the app store profile without the provisioned devices list when i drag this profile to my xcode organizer i get an error that the profile cannot be installed because the device is not included in the profile as expected however when i drag the ipa file to my xcode organizer the app installs on the device and can be opened on the device afterwards i tried this after making sure there were no other copies of the same app installed on the device the same thing does not work when i use a different device that is not included in the provisioned devices of the ad hoc profile even though the ipa contains the app store profile without provisioned devices listdoes anyone have a possible explanation for this it seems that somehow a build signed with an app store profile can still be installed on a device included in the corresponding same app identifier same team identifier ad hoc profile but if this would be the case what is the point of making separate ad hoc builds,['ios'] +610146,update uicollectionviews header content without reloading whole section i want to dynamically update the content of the header information in my uicolectionview but i do not want to reload the whole section because this i done very frequentlyany ideas for an elegant solutionthanks,"['ios', 'objective-c']" +610184,mysql group concat of first and rows is it possible to get comma separated value of first and say 10 rows of a column rows using mysqli have a query to get data greater than curdate and it will return more than 100 rows of result what i want is group concat the first 10 rows of resultthis is my queryselect group concatuser id as useridsfrom user taskswhere due date curdate limit 10am getting entire rows i need first 10 rows onlythanks,['mysql'] +610224,conways game of life beyond the grid ok so there are a lot of conways game of life questions but this one is pretty specific i am going to have to throw a bunch of code at you first break it down and show you where the issue isso here is my conways game of life implementation so far right now it is limited to the console for debugging jsfiddle fire it up open your consolevar utils utilsextend extend initial object with all properties of following objects objects later in the argument list take precedence utilsextend functionobj var args arrayprototypeslicecallarguments 1 for var i argslength i for var prop in argsi objprop argsiprop return obj utilsdefaults overwrite initial object with properties of following objects only if key is present in the initial object utilsdefaults functionobj var args arrayprototypeslicecallarguments 1 for var i argslength i for var prop in argsi if objhasownpropertyprop objprop argsiprop return obj nowrap positioning functions var calcpos ul functioncell return cellx 1 celly 1 um functioncell return cellx celly 1 ur functioncell return cellx 1 celly 1 l functioncell return cellx 1 celly r functioncell return cellx 1 celly ll functioncell return cellx 1 celly 1 lm functioncell return cellx celly 1 lr functioncell return cellx 1 celly 1 var worlddefaults rows 50 columns 50 wrap true left edge is mirrored on right top edge is mirrored on bottom vice versa speed 1 milliseconds minimum time waits until end of last tick to calculate from grid var world function opts thissettings utilsdefaultsworlddefaults opts thismaxx thissettingscolumns 1 thismaxy thissettingsrows 1 for var y 0 ylen thissettingsrows y ylen y for var x 0 xlen thissettingscolumns x xlen x if y 0 thiscelistpush if thissettingsgridlength x thissettingsgridpush var cell new cell cellx x celly y cellalive thissettingsgridxy if cellalive thislifelistpushcell var lx x x 1 thismaxx var uy y y 1 thismaxy var ux x thismaxx 0 x 1 var ly y thismaxy 0 y 1 cellneighbourcoords thissettingswrap lx uy x uy ux uy lx y x y ux y lx ly x ly ux ly calcposul calcposum calcposur calcposl calcposr calcposll calcposlm calcposlr thiscelistxy cell worldprototypegeneration 0worldprototypecelist worldprototypelifelist worldprototypechangelist worldprototypenexttick null progresses the world worldprototypetick function var newlifelist thischangelist this hash goes out of scope after each tick allowing any dead shadowcells to be garbage collected if thissettingswrap var shadowcellhash for var i 0 ilen thislifelistlength i ilen i var cell thislifelisti if cellkey shadowcellhashcellkey cell cellneighbours 0 celastiterated thisgeneration for var j 0 jlen cellneighbourcoordslength j jlen j var coords var neighbour if thissettingswrap coords cellneighbourcoordsj neighbour thiscelistcoords0coords1 else coords cellneighbourcoordsjcell if coords0 thismaxx coords0 0 coords1 thismaxy coords1 0 this neighbour is off the screen so will require a shadowcell var key coords0coords1 if shadowcellhashkey neighbour shadowcellhashkey new shadowcellcoords0 coords1 neighbourneighbourcoords cellneighbourcoords else neighbour shadowcellhashkey else neighbour thiscelistcoords0coords1 if neighbourlastiterated thisgeneration neighbourneighbours 0 neighbourlastiterated thisgeneration if neighbouralive neighbourchanged neighbour started as alive cellneighbours else neighbour started as dead neighbourneighbours if neighbourneighbours 3 neighbouralive true neighbourchanged true neighbourchangeindex thischangelistpushneighbour 1 else if neighbourneighbours 4 neighbour has reverted to dead neighbouralive false neighbourchanged false neighbourchangeindex 1 thischangelistneighbourchangeindex undefined if cellneighbours 2 cellneighbours 3 cellchanged true cellalive false cellchangeindex thischangelistpushcell 1 else newlifelistpushcell for var i 0 ilen thischangelistlength i ilen i var cell thischangelisti if cell undefined cellchangeindex 1 if cellalive newlifelistpushcell cellupdate cellchanged false thislifelist newlifelist thisgeneration thisontick var that this if thissettingsspeed 0 thisnexttick settimeoutfunction thattick thissettingsspeed return thisworldprototypeout function var s for var y 0 ylen thissettingsrows y ylen y for var x 0 xlen thissettingscolumns x xlen x s thiscelistxyalive u2b1b u2b1c s n s u21b3 generation thisgeneration cells thislifelistlength u21b5 s n return s worldprototypestop function thisspeed 1worldprototypeontick function return thisvar cell function return thiscellprototypex 0cellprototypey 0cellprototypeneighbours 0cellprototypealive falsecellprototypechanged falsecellprototypechangeindex 1cellprototypelastiterated 1 shadowcell non rendered cell for use in nowrap var shadowcell functionxy thisx x thisy y thiskey thisxthisy return thisshadowcellprototype utilsextend cellprototypeshadowcellprototypeisshadow trueshadowcellprototypeupdate function return this cellupdate update cell after tick cellprototypeupdate function thisrender return this cellrender placeholder function to be overwritten by rendering engine cellprototyperender function return thisthe method i have chosen involves an array of all the cells that are alive at the start of each generation i then iterate over each of their 8 neighbours and decide whether to createdelete themthis works great when i pass wrap false to the world constructor see jsfiddle for implementation this tells it to mirror the sides and not allow overflow however that style of layout breaks a lot of patterns as it causes cells to come back on themselves so i also want to allow it to calculate beyond the gridfor this purpose i created the shadowcell class which behaves mostly the same as the cell class each grid cell dead or alive is an instance of it except that the shadowclass is only created when a nonexistent cell is required outside of the grid and is offered for garbage collection the moment it is no longer required if it is dead after each generation otherwise it mimics the cell classes attributes and fits directly into the same logic that cell doesthe issueif you go to generation 4 in the console output you may notice it is not quite righti have narrowed this issue down to the shadowcell implementation because this works if i provide enough padding around the shape so that it does not overflow the grid which is when shadowcell kicks in although like i said earlier shadowcell is a copy of the cell class it has the same attributes and gets passed in as if it was a cellbecause i want these to be garbage collected i do not include these in the overall grid array worldcelist this leads me to believe the problem lies in this section of code this hash goes out of scope after each tick allowing any dead shadowcells to be garbage collectedif thissettingswrap var shadowcellhash for var i 0 ilen thislifelistlength i ilen i var cell thislifelisti if cellkey shadowcellhashcellkey cell cellneighbours 0 celastiterated thisgeneration for var j 0 jlen cellneighbourcoordslength j jlen j var coords var neighbour if thissettingswrap coords cellneighbourcoordsj neighbour thiscelistcoords0coords1 else coords cellneighbourcoordsjcell if coords0 thismaxx coords0 0 coords1 thismaxy coords1 0 this neighbour is off the screen so will require a shadowcell var key coords0coords1 if shadowcellhashkey shadowcell not in hash let us create one neighbour shadowcellhashkey new shadowcellcoords0 coords1 neighbourneighbourcoords cellneighbourcoords note neighbourcoords are a set of functions that return values relative to the cell you pass to them i am not literally giving the shadowcell the same neighbour positions here else neighbour shadowcellhashkey else this neighbour is on screen grab its cell neighbour thiscelistcoords0coords1 note alive shadowcells will not be garbage collected as they get stored in an array with the other cells i am certain of this from my debugging see the cell count in your console output and count the visible cellsfor some reason the shadowcell class appears to cause incorrect reporting of neighbours i have attempted to debug it by following the creation deletion and counted neighbours of each individual cell during each generation but my brain dies before it can put it all together for all my debugging efforts i cannot see why this behaviour should occur shadowcell is pretty much the same as a cell to everything else that uses it they use the exact same position functions etc the fact it does not get rendered should not be the cause of thisfor generation 4 i get the following output by logging the creation of shadow maps i can see that each is being created once per generation note the class does not show because i used utilsextend to create a snapshot of themobject x 5 y 1 key 51 neighbourcoords array8 neighbours 0aobject x 6 y 1 key 61 neighbourcoords array8 neighbours 0aobject x 7 y 1 key 71 neighbourcoords array8 neighbours 0aobject x 4 y 1 key 41 neighbourcoords array8 neighbours 0aobject x 1 y 1 key 11 neighbourcoords array8 neighbours 0aobject x 1 y 2 key 12 neighbourcoords array8 neighbours 0aobject x 1 y 3 key 13 neighbourcoords array8 neighbours 0aobject x 5 y 2 key 52 neighbourcoords array8 neighbours 0aobject x 6 y 2 key 62 neighbourcoords array8 neighbours 0aobject x 7 y 2 key 72 neighbourcoords array8 neighbours 0aobject x 1 y 4 key 14 neighbourcoords array8 neighbours 0alogged on line 152 like soif shadowcellhashkey neighbour shadowcellhashkey new shadowcellcoords0 coords1 neighbourneighbourcoords cellneighbourcoords consolelogutilsextend neighbour else,['javascript'] +610237,ef code first add row to table with a nonidentity primary key to reduce this problem to a simple version i have created this tablecreate table testtableid int primary key descr varchar50note that the id field is not an identity field now if i try to use ef code first to insert a rowtabletesttablepublic class testtable key public int id get set public string descr get set public class testcontext dbcontext public testcontextstring connectionstring baseconnectionstring public dbsettesttable testtables get set static void main const string connectionstring using var db new testcontextconnectionstring dbtesttablesaddnew testtable id 42 descr hallo dbsavechanges the result is an exceptioncannot insert the value null into column id table testtable column does not allow nullsbut the code that inserts the row specifies id 42 any clue or hint welcome,['c#'] +610261,google places autocomplete how to clean up paccontainer i am using the google places autocomplete control and it creates an element for the drop down with a class paccontainer i am using the autocomplete in an ember app and when i am done with it the dom element the autocomplete is bound to gets removed but the paccontainer element remains even thought its hidden next time i instantiate a new autocomplete a new paccontainer is created and the old one remains i cannot seem to find anything like a thispose method on the api so is there a way of doing this correctly if not i guess i should just use jquery to clear up the elements,['javascript'] +610347,calc is crashing ie 9 when set on backgroundposition i am using calc to position an image 10px from the right of a responsive container i have a declaration like sobackgroundposition calc100 10px 6pxwhenever i try to load that css into the page normally or enter it via developer toolsie 9 completely crashes no errors in developer tools just straight to crash this works in all other future browsers but my goal is to support ie 9 as wellcalc seems to work on other properties like margin and width just fine here is the full css trace of the related elementhere it is set to 98 but when i use calc on backgroundpositionx as shown above ie 9 crashesthank you,['css'] +610420,woocommerce get products i used the following code to get the list of product categories form woocommerce in my wordpress website php taxonomy product cat orderby name show count 0 1 for yes 0 for no pad counts 0 1 for yes 0 for no hierarchical 0 1 for yes 0 for no title empty 0args array taxonomy taxonomy orderby orderby show count show count pad counts pad counts hierarchical hierarchical title li title hide empty emptyphp all categories get categories args print rall categoriesforeach all categories as cat print rcat ifcatcategory parent 0 category id catterm id php echo br a href get term linkcatslug product cat catname a php args2 array taxonomy taxonomy child of 0 parent category id orderby orderby show count show count pad counts pad counts hierarchical hierarchical title li title hide empty empty sub cats get categories args2 ifsub cats foreachsub cats as sub category echo sub categoryname php this works fine and returns the list of product categories i have been trying now to get a list of products for a particular categoryexample get all the products for with cat id34i know products are stored as posts and have been trying to get this done but cannot seem tohow do i get the list of products for a particular category,['php'] +610543,any difference between await taskrun return and return taskrun is there any conceptual difference between the following two pieces of codeasync task testasync await taskrun dosomeworkandtask testasync return taskrun dosomeworkdoes the generated code differ eitheredit to avoid confusion with taskrun a similar caseasync task testasync await taskdelay10andtask testasync return taskdelay10late update in addition to the accepted answer there is also a difference in how localcallcontext gets handled callcontextlogicalgetdata gets restored even where there is no asynchrony why,['c#'] +610563,faking an io error on linux i have a python and c application on linux that is supposed to properly handle io errors whilst reading files from thisk the bulk of the application is written in python with a c extension that does the io it is within this extension that the io errors are detectedthere are two cases that the errors appear to occur for mea file is missinga file appears larger on thisk using stat than can be read using freadi can test and handle case number 1 rather easily however i would also like to write a unit test for case 2 however i have no idea how to trigger a fake io error for the test is this even possible is there a better approach to testing this kind of error,"['python', 'c']" +610564,python pandas histogram log scale i am making a fairly simple histogram in with pandas usingresultsval1histbins120which works fine but i really want to have a log scale on the y axis which i normally probably incorrectly do like thisfig pltfigurefigsize128ax figadd subplot1pltplotnprandomrand100axset yscalelogpltshowif i replace the plt command with the pandas command so i havefig pltfigurefigsize128ax figadd subplot1resultsval1histbins120axset yscalelogpltshowresults in many copies of the same errorjan 9 155307 blarglocal python6917 error cgcontextclosepath no current pointi do get a log scale histogram but it only has the top lines of the bars but no vertical bars or colors am doing something horribly wrong or is this just not supported by pandaseditfrom paul h code i replacedadded bottom01 to hist call fixes the problem i guess there is some kind of divide by zero thing or somethingthanks,['python'] +610623,why cannot categories have instance variables i understand we can use associative references to invoke ivarlike behavior in categories but whats the specific reason behind not being able to declare new ivars in categoriesis it because we would invade the private space of the class or is there any other reason if yes i would appreciate an example that shows the ability to declare ivars in categories breaking whatever it breaks,['objective-c'] +610854,javascript pause event propagation i need to be able to chain click events and temporarily pause event propagation between themso for a given element it runs three different click events but the second one needs user input so it pauses propagation while the user fills in the form and then continuesclickaction2 pause event propagation somehowpauseeventpropegationrighthere go and handle the dialogs user input js requests godosomethingthendocallback user is now authenticated completely somehowcontinueeventpropegationasifnothinghappened in an effort to allow single responsibility and events chained higherlower should not have knowledge that the event propagation was paused and nothing should be called twiceno the three click events cannot be called sequentially from another function or any similar primitive solutionthis is in relation to angularjs directives but the solution does not need to rely on itthere is a similar question but none of the answers are satisfactory how to continue event propagation after cancellingeditwhat i need is a cleaner way to call estopimmediatepropagation and then continue from that point as of right now my best option is by manually entering the jquery private data1 and calling the functions manually data element0 events clickhandler,"['javascript', 'jquery']" +610910,how to put the uipagecontrol element on top of the sliding pages within a uipageviewcontroller regarding to this tutorial by appcoda about how to implement a app with uipageviewcontroller i would like to use a custom page control element on top of the pages instead of at the bottom when i just put a page control element on top of the single views which will be thisplayed the logical result is that the control elements scrolls with the page view away from the screen how is it possible to put the control element on top of the views so the page views are full screen like with an image so the user can see the views underneath the fixed control elementi attached an example screenshot credits to appcoda and path,['ios'] +611043,sklearn gridsearchcv with pipeline i am new to sklearns pipeline and gridsearchcv features i am trying to build a pipeline which first does randomizedpca on my training data and then fits a ridge regression model here is my codepca randomizedpca10 whitentruergn ridgepca ridge pipelinepca pca ridge rgnparameters ridge alpha 10 nplinspace5 2 3grid search gridsearchcvpca ridge parameters cv2 and jobs1 scoringmean squared errorgrid searchfittrain x train y 1i know about the ridgecv function but i want to try out pipeline and gridsearch cvi want the grid search cv to report rmse error but this does not seem supported in sklearn so i am making do with mse however the scores it resports are negativein 41 grid searchgrid scores out41 mean 002665 std 07 params ridge alpha 101e05 mean 002658 std 09 params ridge alpha 0031622776601683791 mean 002626 std 08 params ridge alpha 10obviously this is not possible for mean squared error what am i doing wrong here,['python'] +611045,c performance and compiling options i have got two similar implementations java and c for a trivial algorithm like the selection sortpublic interface sortingalgorithm public void sortint apublic class selectionsort implements sortingalgorithm override public void sortint a for int i 0 i alength i int lowerelementindex i for int j i 1 j alength j if aj alowerelementindex lowerelementindex j swapa lowerelementindex i private void swapint a int i int j if i j return int temp ai ai aj aj temp and the c oneinline void swapint a int i int jvoid s sortint a int size int i for i 0 i size i int lowerelementindex i j for j i 1 j size j if aj alowerelementindex lowerelementindex j swapa lowerelementindex i inline void swapint a int i int j if i j return int temp ai ai aj aj tempnow i tried testing them on a large array 10 random intthe results at first werejava 17 sec compiled and executed with oracle jdkjvmc 22 sec compiled with gcc v48 without any optimizationof course i then tried to optimize my c version through cflagsthe results arei am reporting cflags onlyo1 184o2 184o39 209now my first question is which cflacs should i use to compileso i read the gnu manual about optimizationsadding marchnative did not helped after some time spent trying other options i came into fprofilearcs option adding it to my flags made my code finish its test in about 11 secondshowever some files appeared in my folders the results of the profiling as i understand i should use them with fbranchprobabilities and recompile the coderecompiling results again in 185 sec and this is what i really want to ask how is it possible for my program to run so fast if it has to write files and collect profiling information and instead it runs 15 times slower when it has noti forgot to mention that i am on an old pc with a intel celeron 28ghz processor and linux fedora 20 with xfce installed if you need other information about the hardware just ask editthe code i use for the test isjavapublic class test public static void mainstring args int a new int10 int a2 new int10 for int i 0 i alength i ai intmathrandom10 a2i ai selectionsort s new selectionsort insertionsort s1 new insertionsort double start systemnanotime ssorta double end systemnanotime double time endstart10 systemoutprintlnselection time start systemnanotime s1sorta2 end systemnanotime time endstart10 systemoutprintlninsertion time and the cinclude insertion sorthinclude selection sorthinclude timehinclude stdlibhinclude stdiohinclude stringhint main int max 10 i srandtimenull int array10 array210 fori0 i10 i1 arrayi rand10 memcpyarray2 array0 10 sizeofint clock t inizio clock s sortarray max clock t fine clock float tempoesecuzione floatfine inizio clocks per sec printfselection 23fn tempoesecuzione inizio clock i sortarray2 max fine clock tempoesecuzione floatfine inizio clocks per sec printfinsertion 23fn tempoesecuzione return 0the code contains references to a insertion sort function that i have not included in the rest of the question because as expected java run slower that c,"['java', 'c']" +611052,flask 301 response my flask app is doing a 301 redirect for one of the urlsthe traceback in new relic istraceback most recent call last file varwappenvlocallibpython27sitepackagesflaskapy line 1358 in full thispatch request rv selfthispatch request file varwappenvlocallibpython27sitepackagesflaskapy line 1336 in thispatch request selfraise routing exceptionreq file varwappenvlocallibpython27sitepackagesflaskapy line 1319 in raise routing exception raise requestrouting exceptionrequestredirect 301 moved permanentlyit does not look like it is even hitting my code or rather the traceback is not showing any of my files in it at one point i did have nginx redirect all non ssl request to https but had to thisable that as varnish was not able to make the request to port 443 with out an error probably some configuration that i did or did not makeit does not always return a 301 though i can request the url and get it without any trouble but someone out in the world requesting the url is getting a 301 responseit is a get request with some custom headers to link it to the accountat no point in my code is there a 301 redirect,['python'] +611082,how to define the css hover state in a jquery selector i need to define a divs background color on hover with jquery but the following does not seem to work myclasshover divcssbackgroundcolorredhow can i get the same result it is important that it has to be done with jquery but for some reason it does not work any suggestions thanks,"['javascript', 'jquery', 'html', 'css']" +611098,is there a rule of thumb to decide when to use trigger or triggermethod in backbonemarionette i am playing a bit with backbonejs and backbonemarionette and i would like to know whats the difference between trigger and triggermethodin particular is there any rule of thumb to decide when use the former or the latterin my mind events for example are useful to communicate between a dom element and its viewtriggermethod is used in marionette to update in cascade different components eg a layout calls the show method to its children children respond to onshow so for me its the same as calling a direct method on it is this truewhat about triggerthanks you in advance,['javascript'] +611142,what does del do exactly here is my codefrom memory profiler import profileprofiledef mess with memory huge list range20 del huge list print why this kolaveri dithis is what the output is when i ran it from interpreter line mem usage increment line contents 3 70 mib 00 mib profile 4 def mess with memory 5 6 6285 mib 6215 mib huge list range20 7 4760 mib 1526 mib del huge list 8 4760 mib 00 mib print why this kolaveri diif you notice the output creating the huge list consumed 6215 mb while deleting it just freed up 1526 mb when i checked the docs i found the below statementthe statement del x removes the binding of x from the namespace referenced by the local scopeso i guess it did not delete the object itself but just unbind it but what did it do in unbinding that it freed up so much of space1526 mb can somebody please take the pain to explain me what is going on here,['python'] +611198,javascript keypress event not raised on android browser i have created a simple code to handle keypress event var counter 0 inputonkeypress function divtextkey pressed counterjsfiddlebut keypress event handler is not raised on mobile browser android 4 windowsphone 75what could be the issue,"['javascript', 'android', 'jquery']" +611237,prevent execution was interrupted reason internal objc exception breakpoint3 on lldb i have written some code that dumps all ivars of a class into a dictionary for objc this uses valueforkey to get the data from the class sometimes kvc throws an internal exception that is also captured properly but this thisrupts lldbs feature and all i get iserror execution was interrupted reason internal objc exception breakpoint3the process has been returned to the state before expression evaluationthere are no breakpoints set i even tried with itrue ufalse as expression options but it does not make a difference this totally defeats for what i want to use lldb for and it seems like such a tiny issue how can i bring clang to simply ignore if there are internal captured objc exceptions while calling a methodi tried this both from within xcode and directly via calling clang from the terminal and connecting to a remote debug server no difference,['objective-c'] +611256,how to make an ajax https get request using jquery how can i explicitly make an ajax https get request using jquery i am trying to do the followingon an https page i have a line with the code getresource but i get the following errorxmlhttprequest cannot load no accesscontrolalloworigin header is present on the requested resource origin is therefore not allowed accesswhy is the ajax call trying to access the page using the http protocol if the relative resource is from an https page if the geturl method does this by default how do i use jquery to do an explicit https get request another person who had a similar issue at could not resolve itjquery version is 172,['jquery'] +611290,how to assert a dict contains another dict without assertdictcontainssubset in python i know assertdictcontainssubset can do this in python 27 but for some reason it is deprecated in python 32 so is there any way to assert a dict contains another one without assertdictcontainssubsetthis seems not good for item in dic2 selfassertinitem dicany other good way thanks,['python'] +611315,when to use executescalarexecutereaderexecutenonquery i am confused with the usage oflist itemexecutescalarexecutereaderexecutenonquerywhen to use these methods,['c#'] +611347,convert string in c to cstring in ccli i need a help on one question where i stuck while coding my app in mfci am using clr ie common language runtime in my application to integrate c apisbut now i stuck on converting systemstring to cstringi am not able to do thati am using following codestring cspass gcnew stringstrpasswordgetbufferarraybyte value encodingutf8getbytescspassfor int i 0 i valuelength i cspass stringformat 0x2 value i now i want to convert cspass to cstringcan any one help me on thisthank you in advance,"['c#', '.net']" +611368,check the version of asterisk i am running i am a bit confused about what version of asterisk i am running on centos serverthe documentation is different for different versionshow to know the version using putty command,['php'] +611532,aptana errorpydev port not bound found port 1 i just updated my aptana studio3 when i open my python file it says that it can not find map range and filter and some other methods but when i run my code it will run without any problem my code completion does not work any more the error for code completion when i use ctrlspace is port not bound found port 1 is there an enabled firewall i do not know where the problem is i searched but i could not find a proper solution i am using windows 7,['python'] +611602,how to fix 404 warnings for images during karma unit testing i am unit testing one of my directives angularjs using gruntkarmaphantomjsjasmine my tests run finedescribebar foo function beforeeachinjectfunction rootscope compile elm angularelementimg barfoo srcimg1png scope rootscopenew compileelm scopedigest but i do get these 404s warn webserver 404 img1pngwarn webserver 404 img2pngalthough they do nothing they do add noise to the log output is there a way to fix this without changing karmas loglevel of course because i do want to see them,['javascript'] +611629,eclipse would not compilerun java file i am just trying to compile and run a simple java program when i go to run my tester class it says select what to run and it gives me ant build which when highlighted says launches an ant build with default settings or ant build that says launches an ant build and allows it to be configured when i try to select either of these it prompts build failed reason unable to find ant file to run i honestly do not know what these ant builds and files are this is definitely a dumb question but have no idea what to do,['java'] +611675,running django tutorial tests fail no module named pollstests i am playing with django 16 tutorial but i cannot run testsmy project name mydjango and app structure name is polls are as shown below in a virtualenv nja files are just created by ninjaide the ide i am usinga init pya managepya mydjangoaa a a init pyaa a a init pycaa a a mydjangonja a a settingspyaa a a settingspycaa a a templatesaa a aa a a adminaa a aa a a base sitehtmlaa a a urlspyaa a a urlspycaa a a wsgipyaa a a wsgipyca pollsaa a a adminpyaa a a adminpycaa a a init pyaa a a init pycaa a a modelspyaa a a modelspycaa a a templatesaa a aa a a init pyaa a aa a a pollsaa a aa a a detailhtmlaa a aa a a indexhtmlaa a aa a a init pyaa a aa a a resultshtmlaa a a testspyaa a a testspycaa a a urlspyaa a a urlspycaa a a viewspyaa a a viewspyca pollsnjai followed the tutorial to understand how django works but i am stuck in the test partas tutorial suggest i created a file named testspy into the app folder the pretty strighforward file is coding utf8 from djangotest import testcaseimport datetimefrom djangoutils import timezonefrom pollsmodels import question create your tests herel class questionmethodteststestcase def test was published recently with future pollself was published recently dovrebbe ritornare falso se si mette una data nel futuro future question questionpub datetimezonenow datetimetimedeltahours50 selfassertequalfuture questionwas published recently falsethen i installed unittest2 into the virtualenv withpip install unittest2and run python managepy test pollscreating test database for alias defaulteerror mydjangopollstests unittest2loadermoduleimportfailureimporterror failed to import test module mydjangopollsteststraceback most recent call last file homesergiovirtualenvsdjango4locallibpython27sitepackagesunittest2loaderpy line 260 in find tests module self get module from namename file homesergiovirtualenvsdjango4locallibpython27sitepackagesunittest2loaderpy line 238 in get module from name import nameimporterror no module named pollstestsran 1 test in 01sfailed errors1destroying test database for alias defaultno way to have the test working also if do not pass the app name it returns the same error python managepy testcreating test database for alias defaulteerror mydjangopollstests unittest2loadermoduleimportfailureimporterror failed to import test module mydjangopollsteststraceback most recent call last file homesergiovirtualenvsdjango4locallibpython27sitepackagesunittest2loaderpy line 260 in find tests module self get module from namename file homesergiovirtualenvsdjango4locallibpython27sitepackagesunittest2loaderpy line 238 in get module from name import nameimporterror no module named pollstestsran 1 test in 01sfailed errors1destroying test database for alias defaultmy installed apps areinstalled apps south djangocontribadmin djangocontribauth djangocontribcontenttypes djangocontribsessions djangocontribmessages djangocontribstaticfiles pollscannot understand whats i am doing wrong any help should be really appreciatedthank you,['python'] +611698,why pattern based programming in c wondering why c is moving towards more pattern based programming rather than conventional waysex the foreach statement expects that the loop source to have a magic method called getenumerator which returns an object which has a few more magic methods like movenext and current but they do not mandate any specific interface c could have mandated that a class to be used in foreach should implement ienumerable or ienumerablet as it does for theusing statement in that it expects an object to be used in using statement to implement the ithisposable interfacealso i see a similar trend with asyncawait keywords as wellof course there must be a good reason for that but it seems a little odd for me to understand the reason why does compilerclr requires magic methods rather than relying on interfaces,['c#'] +611705,how can i specify a class attribute in new tag i am currently using beautifulsoup4 with python 27 and trying to instantiate a new tag with a certain class attribute i know how to use attributes such as stylediv soupnew tagdiv stylepaddingleft 10px attr2 however if i try to do this with the class reserved word i get an error invalid syntaxdiv soupnew tagdiv classleft padded attr2 throws errori have also tried with class but this is also invalid i can use class but then the output is not properly compliant all lowercase attribute namesi am aware that i can do the followingdiv soupnew tagdiv attr2 divclass left paddedbut this does not look elegant or intuitive my research in the docs and on google were fruitless as class is a common keyword that is unrelated to the search results i wantis there a way i can specify class as an attribute in new tag,['python'] +611737,android studio where can i see callstack while debugging an android app while on a break point how do i see the call stack to find the callee methodfunction,['android'] +611800,how to get guard to only run slow specs if fast specs pass i have tagged my specs that require selenium with js true in my spec files what i want to achieve is that guard will always run the non js specs first and only when these specs all pass run the specs tagged with jsthis is my current guardfilegroup nonjavascript specs do guard rspec cmd zeus rspec color format nested failfast t js parallel false bundler false all on start false all after pass false keep failed false do notification terminal notifier watchrspec specrb watchrlibrb m speclibm1 specrb watchspecspec helperrb spec rails example watchrapprb m specm1 specrb watchrapperbhamljbuilder m specm1m2 specrb watchrappcontrollers controllerrb m specroutingm1 routing specrb specm2sm1 m2 specrb specfeaturesm1 specrb watchrspecsupportrb spec watchconfigroutesrb specrouting watchappcontrollersapplication controllerrb speccontrollers watchrappviewserbhaml m specfeaturesm1 specrb end endgroup javascript specs do guard rspec cmd zeus rspec color format nested failfast t js parallel false bundler false all on start false all after pass false keep failed false do notification terminal notifier watchrappviewserbhaml m specrequestsm1 specrb watchrspecrequests specrb watchrspecfeatures specrb endendhowever with this config it will split the execution of js and non js specs but it will always run the js specs even if the non js specs failhow can i tell guard to not run the second group if the first group does not pass,['ruby-on-rails'] +611820,angularjs unitest a directive with external template using html2js fail to load templates i am trying to test a directive which uses external template i tried all the following solutions with no luckngdirectivetestinghow to test directives that use templateurl and controllersangularjs karma nghtml2js failed to instantiate module htmli created a test directive a simple div and tested it using an inline template and external templateurl the inline solution works while the external does not angularmoduleadunitdirectiveactionbuttonfunctionlocation return scope actionname restrict e template div ngclickclickaction buttondiv templateurl staticfilesadunithtmldirectivesactionbuttontemplatehtml controller scope functionscope scopeclick function scopeemitaction click scopeactionname describeunit testing action button directive function var elm scope linkfn beforeeach moduleadunit beforeeachmodulestaticfilesadunithtmldirectivesactionbuttontemplatehtml beforeeachinjectfunctionrootscope compile elm angularelementactionbutton actionnamepostaction0actionbutton scope rootscope linkfn compileelm linkfnscope scopedigest have to digest to bring html from templatecache consolelogpost compileelmhtml the html here still have itshould show a thumbfunction consolelogpost linkelmhtml the html is bound expectelmtexttobeaction button my karma config file moduleexports functionconfig configset base path that will be used to resolve files and exclude basepath frameworks to use frameworks jasmine list of files patterns to load in the browser files htmlhtml htmldirectiveshtml jsadunitjs jscontrollersjs jsdirectivesjs jsservicesjs js js testsjs preprocessors htmlhtml nghtml2js nghtml2jspreprocessor adunit staticfilesadunithtmldirectivesactionbuttontemplatehtml modulename staticfilesadunithtmldirectivesinternalplayertemplatehtml list of files to exclude exclude test results reporter to use possible values dots progress junit growl coverage reporters progress web server port port 9876 enable thisable colors in the output reporters and logs colors true level of logging possible values configlog thisable configlog error configlog warn configlog info configlog debug loglevel configlog info enable thisable watching file and executing tests whenever any file changes autowatch true start these browsers currently available chrome chromecanary firefox opera has to be installed with npm install karmaoperalauncher safari only mac has to be installed with npm install karmasafarilauncher phantomjs ie only windows has to be installed with npm install karmaielauncher browsers chrome if browser does not capture in given timeout ms kill it capturetimeout 60 continuous integration mode if true it capture browsers run tests and exit singlerun false i keep getting the following errorfailed to instantiate module staticfilesadunithtmldirectivesactionbuttontemplatehtml due toerror injectornomodany help will be appreciatededit mk safis answer solved my problem i was missing the following nghtml2jspreprocessor modulename templates function that transforms the path to look exactly like you have it in templateurl in your angular code mine looks like this cacheidfrompath functionfilepath return filepathmatchstaticfilesadunithtmldirectiveshtml and before each test beforeeachmoduletemplatesit is important for the regular expression to point to the same path as the directives templateurl since html2js will cache those templates using this path see html2js for more details about that,['javascript'] +611847,presentviewcontrolleranimatedyes view will not appear until user taps again i am getting some strange behaviour with presentviewcontrolleranimatedcompletion what i am making is essentially a guessing game i have a uiviewcontroller frequencyviewcontroller containing a uitableview frequencytableview when the user taps on the row in questiontableview containing the correct answer a view correctviewcontroller should be instantiate and its view should slide up from the bottom of the screen as a modal view this tells the user they have a correct answer and resets the frequencyviewcontroller behind it ready for the next question correctviewcontroller is thismissed on a button press to reveal the next questionthis all works correctly every time and the correctviewcontrollers view appear instantly as long as presentviewcontrolleranimatedcompletion has animatednoif i set animatedyes correctviewcontroller is initialized and makes calls to viewdidload however viewwillappear viewdidappear and the completion block from presentviewcontrolleranimatedcompletion are not called the app just sits there still showing frequencyviewcontroller until i make a second tap now viewwillappear viewdidappear and the completion block are calledi investigated a bit more and it is not just another tap that will cause it to continue it seems if i tilt or shake my iphone this can also cause it to trigger the viewwiload etc it is like it is waiting to any other bit of user input before it will progress this happens on a real iphone and in the simulator which i proved by sending the shake command to the simulatori am really at a loss as to what to do about this i would really appreciate any help anyone can providethanksheres my code it is pretty simplethis is code in questionviewcontroller that acts as the delegate to the questiontableview voidtableviewuitableview tableview didselectrowatindexpathnsindexpath indexpath if indexpathrow selffrequencymodel currentfrequencyindex if guess was wrong then mark the selection as incorrect nslogincorrect guess selffrequencymodel frequencylabelatindexintindexpathrow uitableviewcell cell selffrequencytableview cellforrowatindexpathindexpath cell setbackgroundcoloruicolor colorwithred2402550f green1102550f blue1032550f alpha10f else if guess was correct show correct view nslogcorrect guess selffrequencymodel frequencylabelatindexintindexpathrow selfcorrectviewcontroller hfbcorrectviewcontroller alloc init selfcorrectviewcontrollerdelegate self self presentviewcontrollerselfcorrectviewcontroller animatedyes completionvoid nslogcompleted presenting correctviewcontroller self setupviewfornextquestion this is the whole of the correctviewcontrollerimplementation hfbcorrectviewcontroller idinitwithnibnamensstring nibnameornil bundlensbundle nibbundleornil self super initwithnibnamenibnameornil bundlenibbundleornil if self custom initialization nsloghfbcorrectviewcontroller initwithnibnamebundle return self voidviewdidload super viewdidload do any additional setup after loading the view from its nib nsloghfbcorrectviewcontroller viewdidload voidviewdidappearboolanimated super viewdidappearanimated nsloghfbcorrectviewcontroller viewdidappear voiddidreceivememorywarning super didreceivememorywarning thispose of any resources that can be recreated ibactioncloseidsender nsloghfbcorrectviewcontroller closesender selfdelegate didthismisscorrectviewcontrollerendediti found this question earlier uitableview and presentviewcontroller takes 2 clicks to thisplayand if i change my didselectrow code to this it works very time with animation but it is messy and does not make sense as to why it does not work in the first place so i do not count that as an answer voidtableviewuitableview tableview didselectrowatindexpathnsindexpath indexpath if indexpathrow selffrequencymodel currentfrequencyindex if guess was wrong then mark the selection as incorrect nslogincorrect guess selffrequencymodel frequencylabelatindexintindexpathrow uitableviewcell cell selffrequencytableview cellforrowatindexpathindexpath cell setbackgroundcoloruicolor colorwithred2402550f green1102550f blue1032550f alpha10f cell setaccessorytypeuitableviewcellaccessorytype else if guess was correct show correct view nslogcorrect guess selffrequencymodel frequencylabelatindexintindexpathrow below here are the changes self performselectorselectorshowcorrectviewcontroller withobjectnil afterdelay0 voidshowcorrectviewcontrolleridsender selfcorrectviewcontroller hfbcorrectviewcontroller alloc init selfcorrectviewcontrollerdelegate self selfcorrectviewcontrollermodaltransitionstyle uimodaltransitionstylecrossthissolve self presentviewcontrollerselfcorrectviewcontroller animatedyes completionvoid nslogcompleted presenting correctviewcontroller self setupviewfornextquestion,['ios'] +611875,how to convert a string to objectid in nodejs mongodb native driver i am using mongodb native driver in a nodejs environment and i need to convert an id string to objectid to use it in my update query how can i do this,['javascript'] +611900,time complexity of delete operator what is the time complexity of the delete operator i mean how is it implemented does it iterate over all the elements in the array and calls destructor for every elementdoes this operator do the same for primitive types int etc and user defined types,['c++'] +611904,cropping avasset video with avfoundation i am using avcapturemoviefileoutput to record some video i have the preview layer thisplayed using avlayervideogravityresizeaspectfill which zooms in slightly the problem i have is that the final video is larger containing extra image that did not fit on the screen during previewthis is the preview and resulting video is there a way i can specify a cgrect that i want to cut from the video using avassetexportsession edit when i apply a cgaffinetransformscale to the avassettrack it zooms into the video and with the avmutablevideocomposition rendersize set to viewbounds it crops off the ends great there is just 1 problem left the width of the video does not stretch to the correct width it just gets filled with blackedit 2 the suggested questionanswer is incompletesome of my codein my voidcaptureoutputavcapturefileoutput captureoutput didfinishrecordingtooutputfileaturlnsurl outputfileurl fromconnectionsnsarray connections errornserror error method i have this to crop and resize the video voidflipandsavensurl videourl withcompletionblockvoidnsurl returnurlcompletionblock avurlasset firstasset avurlasset assetwithurlvideourl 1 create avmutablecomposition object this object will hold your avmutablecompositiontrack instances avmutablecomposition mixcomposition avmutablecomposition alloc init 2 video track avmutablecompositiontrack firsttrack mixcomposition addmutabletrackwithmediatypeavmediatypevideo preferredtrackidkcmpersistenttrackid invalid firsttrack inserttimerangecmtimerangemakekcmtimezero firstassetduration oftrackfirstasset trackswithmediatypeavmediatypevideo objectatindex0 attimekcmtimezero errornil 21 create avmutablevideocompositioninstruction avmutablevideocompositioninstruction maininstruction avmutablevideocompositioninstruction videocompositioninstruction maininstructiontimerange cmtimerangemakecmtimemakewithseconds0 600 firstassetduration 22 create an avmutablevideocompositionlayerinstruction for the first track avmutablevideocompositionlayerinstruction firstlayerinstruction avmutablevideocompositionlayerinstruction videocompositionlayerinstructionwithassettrackfirsttrack avassettrack firstassettrack firstasset trackswithmediatypeavmediatypevideo objectatindex0 uiimageorientation firstassetorientation uiimageorientationup bool isfirstassetportrait no cgaffinetransform firsttransform firstassettrackpreferredtransform if firsttransforma 0 firsttransformb 10 firsttransformc 10 firsttransformd 0 firstassetorientation uiimageorientationright isfirstassetportrait yes if firsttransforma 0 firsttransformb 10 firsttransformc 10 firsttransformd 0 firstassetorientation uiimageorientationleft isfirstassetportrait yes if firsttransforma 10 firsttransformb 0 firsttransformc 0 firsttransformd 10 firstassetorientation uiimageorientationup if firsttransforma 10 firsttransformb 0 firsttransformc 0 firsttransformd 10 firstassetorientation uiimageorientationdown firstlayerinstruction settransformfirstassettrackpreferredtransform attimekcmtimezero firstlayerinstruction setcroprectangleselfviewbounds attimekcmtimezero cgfloat scale self getscalefromassetfirstassettrack firsttransform cgaffinetransformscalefirsttransform scale scale firstlayerinstruction settransformfirsttransform attimekcmtimezero 24 add instructions maininstructionlayerinstructions nsarray arraywithobjectsfirstlayerinstructionnil avmutablevideocomposition maincompositioninst avmutablevideocomposition videocomposition maincompositioninstinstructions nsarray arraywithobjectmaininstruction maincompositioninstframeduration cmtimemake1 30 cgsize videosize firstassettracknaturalsize cgsize videosize selfviewboundssize bool isportrait self isvideoportraitfirstasset ifisportrait videosize cgsizemakevideosizeheight videosizewidth nslog nsstringfromcgsizevideosize maincompositioninstrendersize videosize 3 audio track avmutablecompositiontrack audiotrack mixcomposition addmutabletrackwithmediatypeavmediatypeaudio preferredtrackidkcmpersistenttrackid invalid audiotrack inserttimerangecmtimerangemakekcmtimezero firstassetduration oftrackfirstasset trackswithmediatypeavmediatypeaudio objectatindex0 attimekcmtimezero errornil 4 get path nsstring outputpath nsstring alloc initwithformat nstemporarydirectory cutoutputmov nsurl outputurl nsurl alloc initfileurlwithpathoutputpath nsfilemanager manager nsfilemanager alloc init if manager fileexistsatpathoutputpath manager removeitematpathoutputpath errornil 5 create exporter avassetexportsession exporter avassetexportsession alloc initwithassetmixcomposition presetnameavassetexportpresethighestquality exporteroutputurloutputurl exporteroutputfiletype avfiletypequicktimemovie exportershouldoptimizefornetworkuse yes exportervideocomposition maincompositioninst exporter exportasynchronouslywithcompletionhandler switch exporter status case avassetexportsessionstatusfailed nslogexport failed exporter error localizeddescription exporter error completionblocknil break case avassetexportsessionstatuscancelled nslogexport canceled completionblocknil break default nsurl outputurl exporteroutputurl thispatch asyncthispatch get main queue completionblockoutputurl break,['ios'] +611961,angularjs and google oauth2 redirect uri i am trying to create a simple application using angularjs and googles oauth2 for authenticationdue to popupblocking issues and mobile friendliness i decided i wouldnt use the google apis client library for javascriptthis left me with the option of doing a full redirect to the oauth2 endpoint at google and redirect users back to my app with the access token i thought this would work just fine the redirect uri would be with an appended access token query parameter i would then consume the access token and direct the user to somewhere else in my appthis did not work as the google api credentials do not like having a in the redirect urisi then tried turning off the requirement in uris by using locationproviderhtml5modetruethis did not work either because explicitly browsing in chrome to is not recognised by my angular routesany thoughts on how i should acheive this,['javascript'] +611987,how to find pg config path complete newbie here trying to set up django to work with prostgresqli am using mac osx 1068 i have also installed postgresql 93when i run pip install psycopg2 in terminal i get the following errordownloadingunpacking psycopg2 downloading psycopg2252targz 685kb 685kb downloaded running setuppy pathprivatevarfoldersa9a99cs6x0fnuspejcvkyntetitmppip build bengormanpsycopg2setuppy egg info for package psycopg2 error pg config executable not found please add the directory containing pg config to the path or specify the full executable path with the option python setuppy build ext pgconfig pathtopg config build or with the pg config option in setupcfg complete output from command python setuppy egg info running egg infocreating pipegginfopsycopg2egginfowriting pipegginfopsycopg2egginfopkginfowriting toplevel names to pipegginfopsycopg2egginfotop leveltxtwriting dependency links to pipegginfopsycopg2egginfodependency linkstxtwriting manifest file pipegginfopsycopg2egginfosourcestxtwarning manifest maker standard file c not founderror pg config executable not foundplease add the directory containing pg config to the pathor specify the full executable path with the option python setuppy build ext pgconfig pathtopg config build or with the pg config option in setupcfgi have seen a number of posts on this howtoinstallpsycopg2withpiponpython pgconfigexecutablenotfound but i have no clue how to find the bin folder location containing pg config any tips on finding this path,['python'] +611991,how to persistently save pendingintent provided by another application let us say i want to implement an app which exposes services to other apps like google play services potential apps would register to my special events associated with my services and would be notified at the right timei was thinking to implement this exactly like google did with the google play servicesthanks to android interprocess communication other apps could bind to my app service and by that pass to my app pendingintent callback that i could execute for them at the right time now i will get to the problem my app process currently running in background and holding reference to pendingintent provided by other app now from some reason system decisions user explicitly my process been stoppedmy process cumming back in some point and come back to do it is thingin that point i lost reference to the pendingintent provided to me before and i do not see any way in the api to retrieve back reference to it also i do not see any way to save persistentlydatabasesharedpreferencesfile system saving the pending intent for latter on usage my questions areis it possible to store pending intent persistently somehowis it possible to get back reference to the same pending intent i already got beforeif not is there any other suggestion to implement such thing as i described,['android'] +612153,no p element in scope but a p end tag seenw3c validation my html is as as below i have opened all elements and closed them still when i check it on w3c it shows error i cant figure it out doctype htmlhtml head meta charsetutf8 titleuntitled documenttitle head body p div classinr content clearfix div classcol2 first fl to provide a drivein services div div classcol2 last fr to provide a drivein services div div p bodyhtml,['html'] +612248,how to create nvarcharmax sqlparameter in c i have got the following code to pull back a datatable using a stored procedure and inputting a string parameter jobnumbers which is dynamically created string of job numbers and therefore length is unknownusing sqlconnection connection new sqlconnectioncon sqlcommand cmd new sqlcommanddbomystoredprocedure connection cmdcommandtype commandtypestoredprocedure cmdparametersaddjobnumbers sqldbtypevarchar 40 cmdparametersjobnumbersvalue jobnumber sqldataadapter da new sqldataadaptercmd connectionopen dafilljobdetails as you can see i have currently set the jobnumber parameter to a length of 40 which should be enough to take around 500 job numbers and should be enough however there is the possibility that it may need more on the odd occasion so i was wondering is there a way to set the parameter to the equivalent sql parameter type of nvarcharmaxi have had a look at various similar questions whats the best method to pass parameters to sqlcommand but none specifically say whether you can or cannot do this secondly is it even necessary to do this if i set the jobnumber parameter in the stored procedure to nvarcharmax and therefore presumably i wouldnt need to set the length in c at all if i do this will this have potential performance issues as suggested in this question different ways of passing sqlcommand parameters,"['c#', 'sql']" +612255,android launch twitter intent i use the code below for launching twitter intent but is not working i have the twitter app installed on my phone need help intent shareintent new intentandroidcontentintentaction send shareintentsettypetextplain shareintentputextraandroidcontentintentextra text content to share packagemanager pm contextogetpackagemanager listresolveinfo activitylist pmqueryintentactivitiesshareintent 0 for final resolveinfo app activitylist if comtwitterandroidpostactivityequalsappactivityinfoname final activityinfo activity appactivityinfo final componentname name new componentnameactivityapplicationinfopackagename activityname shareintentaddcategoryintentcategory launcher shareintentsetflagsintentflag activity new task intentflag activity reset task if needed shareintentsetcomponentname contextostartactivityshareintent break getting exception when i try to call the activity androidcontentactivitynotfoundexception unable to find explicit activity class comtwitterandroidcomtwitterandroidpostactivity have you declared this activity in your androidmanifestxml,['android'] +612318,largescale document cooccurrence analysis i have about 10 files each of which contains about 20 documents i also have a list of about 10 words i want to calculate how many time each word occurs with any other words so there is a sparse matrix of size 1m x 1mto speed up computation i am working on each file separately by doing the following1 each core in my machine is processing a single file and outputing a file of the following formatwordid1 wordid2 frequency 2 after doing each file i merge the 10 file into a single filethis is my current approach but it takes so long to do it and i assume there should be much efficient way of doing it so your comments are welcome,['java'] +612327,posting a saml token to aspnet mvc website i have a claims aware mvc website setup using the thinktecture identity server i now have a requirement to allow a 3rd party to access certain parts of the websiteis it possible to programmatically authenticate with the identity server and post this to the website so that the user at the 3rd party is not required to manually go through the normal login processi have previously used the identity server to obtain a saml token for the purpose of making wcf calls i was wondering if it would be possible to reuse some of this approachthe complications arise from the fact that the 3rd party are using a desktop based java app with some browser component built in for accessing the mvc website users are already authenticated with the desktop app so we do not want them entering credentials again to view these web pages,['c#'] +612342,how print statement create a local variables question are at the end of this postfirst snippet empty local variable dictionarydef outer x 1 def inner print local variables s locals return innerprint outeroutput local variables second snippet print inside inner function and creating local variable entrydef outer x 1 def inner print x print local variables s locals return innerprint outeroutput1local variables x 1third snippet del x from inside the inner functiondef outer x 1 def inner print x print local variables s locals del x return innerprint outeroutput outertraceback most recent call last file stdin line 1 in module file stdin line 7 in outer file stdin line 4 in innerunboundlocalerror local variable x referenced before assignmentquestions in second snippet how print statement create local variableif it creates local variable inside inner function why i am not able to delete itcould someone please help me understanding this,['python'] +612344,how to get thread id of a pthread in linux c program in linux c program how to print thread id of a thread created by pthread libraryfor ex we can get pid of a process by getpid,['c'] +612354,is mysql real escape string vulnerable to invalid utf8 exploitation eg overlong utf8 or ill formed utf8 sequences assuming i have my database set up as follows to use utf8 the full 4mb version in mysqlmysql queryset character set utf8mb4mysql queryset names utf8mb4i am using mysql real escape string to escape unwanted characters before putting a string into sql note i am not looking for advice to switch to pdo i want to establish whether mysql real escape string is safe against overlong utf8 etcinput mysql real escape string postfieldsql select from table where headerinputis there any validation i need to do to postfield eg to check if the string is valid utf8 and is not overlong and does not contain invalid sequences etc before doing my mysql real escape string or is that sufficient,['php'] +612361,error 2013 hy0 lost connection to mysql server at reading authorization packet system error 0 i am getting the following error error 2013 hy0 lost connection to mysql server at reading authorization packet system error 0when trying to connect to my mysql serverwhat i am doingi have master slave replication in mysql that is working and just added load balance capabilities using f5 i have configured the f5 according to their site but when i am trying to connect to my mysql server using the ip that the f5 was configured with i get error 2013 hy0 lost connection to mysql server at reading authorization packet system error 0 any ideasupdate on my progress zero i am getting the same error i get no entries in the varlogsecure as if somebody would try to authenticate coming form the ip where i had created my load balance serverno enties in the mysql error logthe command returns nothingmysql show global status like aborted connectionsempty set 0 seci have already altered my mycnf file and add the mysqldskipnameresolvealterd the connect timeout to 10 so it seems i get no response for the server i have created on my f5 i finally convinced the f5 admin to pass me the log for the f5 server and i have exctraced all i need form ithere is the output jan 28 154639 tmm debug tmm6459 rule commonirulef5 mysql proxy client accepted bigip mysql proxy clientside initial connectionjan 28 154639 tmm debug tmm6459 rule commonirulef5 mysql proxy client accepted bigip mysql proxy clientside responding with server welcome packetjan 28 154639 tmm debug tmm6459 rule commonirulef5 mysql proxy client data bigip mysql proxy clientside authenticated flag not setjan 28 154639 tmm err tmm6459 rule commonirulef5 mysql proxy client data bigip mysql proxy mysql client attempting to do something before authenticationjan 28 154639 tmm debug tmm6459 rule commonirulef5 mysql proxy lb selected bigip mysql proxy serverside selected pool commonfossmysqlslave pool node slaveipjan 28 154639 tmm debug tmm6459 rule commonirulef5 mysql proxy client closed bigip mysql proxy clientside connection closed from masteripxjan 28 154639 tmm debug tmm6459 rule commonirulef5 mysql proxy server closed bigip mysql proxy serverside connection closed from node slaveipxi have replaced the ip for security sake just as an extra and i think is here the problem my mysql version is 5169logthx all,['mysql'] +612391,how to find account owner for android app in google play developer console this question relates to the google play developer console an account was shared with me over a year ago when i select this account and click settings i see the messagethe developer profile can only be edited by the account ownerbut when i look under developer profile email address it shows my own addresseven in the section at the bottom labeled google wallet it states the contact email address is so my question is how do i find out which google account is considered to be the ownerif i click the button labeled help feedback contact support it just takes me to an automated help system with no suitable options,['android'] +612406,using csvhelper to output stream to browser i am trying to use csvhelper to generate a csv file and send it back to a browser so the user can select a save location and filename and save the data the website is mvc based here the jquery button code i am using to make the call data is some serialised json representation of a dto list ajax type post url unitybaseurl commonexportpayments data data heres the controller code httppost public filestreamresult exportpayments memorystream ms new memorystream streamwriter sw new streamwriterms csvwriter writer new csvwritersw listpayment dto pd commonservicegetpayments foreach var record in pd writerwriterecordrecord swflush return new filestreamresultms textcsv which seems to achieve precisely nothing invoking the method steps into the correct bit of code but the response is empty let alone offering the user a file dialog to save the data i have stepped through this code and it brings back data from the service writes it and throws no errors so what am i doing wrongedit returning this return filemsgetbuffer textcsv exportcsv gives me a response consisting of the csvformatted data that i am expecting but the browser still does not seem to know what to do with it no download option is offered to the user,['.net'] +612419,force page zoom at 100 with js i created a little game in canvas but i have a problemsome users who have the default zoom set to something other than 100 cannot see the entire game pagei searched on the internet for a solution to this problem but could not find onei have already usedzoom 100 in cssmeta nameviewport contentinitialscale10 minimumscale10 maximumscale10 andstylezoom 75can someone help me pleasethank you,"['javascript', 'html']" +612446,emberjshandlebarsjs bind conditional class property to linkto helper i am trying to add a class to the link attribute but the class name is conditionallinkto role this classnamesisloadingisloading tagtr td bindattr classisloadingisloading name td td role isloading td tdedittdlinktoso just like this but somehow it does not workis there another way to do this,['javascript'] +612461,nspredicate filter array within object within array i have the following method nsmutablearray getfilteredarrayfromarraynsmutablearray array withtextnsstring text if array count 0 return nilnsmutablearray arraytofilter nsmutablearray arraywitharrayarraynsstring nameformatstring nsstring stringwithformatstationname containsc textnspredicate namepredicate nspredicate predicatewithformatnameformatstringnsstring descformatstring nsstring stringwithformatstationtagline containsc textnspredicate descpredicate nspredicate predicatewithformatdescformatstringnsstring atozformatstring nsstring stringwithformatstationsearchdatabrowseatozarraycity containsc textnspredicate atozpredicate nspredicate predicatewithformatatozformatstringnspredicate combinepredicate nscompoundpredicate orpredicatewithsubpredicatesnsarray arraywithobjectsnamepredicate descpredicate atozpredicate nilarraytofilter filterusingpredicatecombinepredicatereturn arraytofilterthe first 2 predicates work fine but the last one atozpredicate is not working stationsearchdata is a stationsearchdata object and browseatozarray is an nsmutablearray how can i use a predicate to essentially search an array within an array within an arrayhere is the interface for the stationsearchdata objectinterface stationsearchdata nsobjectproperty nonatomic strong nsstring locationproperty nonatomic strong nsstring cityproperty nonatomic strong nsstring latitudeproperty nonatomic strong nsstring longitudeproperty nonatomic strong nsmutablearray browseatozarrayproperty nonatomic strong nsmutablearray genrearrayendthanks,"['ios', 'objective-c']" +612503,cc linux how to find neighbors on a network without using ip mac only in a small network say 20 nodes or less my program on a test instrument needs to know who is out there by mac not by ip i will be plugging into random networks and need to be able to do this without having to know any addresses mac or otherwise in the network and knowing i cannot rely on dhcp it is completely reasonable that the dhcp server could be down and the nodes have no ip addresses andor i cannot get one truthfully i do not need ip our test protocol is mac layer not ipso how can i determine my instruments neighbors mac addresses this sounds a lot like lldp but backwards ie whos out there not i am here and i can do this i must assume there is no ip assigned to the endpoints so no arping no nmap etc note i should add this is a wired network,"['c++', 'c']" +612529,calling gradle buildconfig multiple times i am trouble figuring out a way to add multiple lines to my buildconfig using gradle it appears that when i call buildconfig a 2nd time the first one thisappearsi was originally adding this buildconfig from a different spot but was able to create a minimal reproducible test if i do thisbuildtypes debug versionnamesuffix debug buildconfig public static final int thing one 1 buildconfig public static final int thing two 2 release zipalign true buildconfig public static final int thing one 3 buildconfig public static final int thing two 4 then when i try to use it in codepublic class thing public static final int thing comexamplebuildconfigthing one comexamplebuildconfigthing twoi will get this errorexamplesrcmainjavacomexamplethingjava2 cannot find symbolsymbol variable thing onelocation class comexamplebuildconfigpublic static final int thing comexamplebuildconfigthing one comexamplebuildconfigthing twois there any way to add multiple different lines to the buildconfig for each productflavor or buildtype using multiple calls to buildconfig instead of a multiline string,['android'] +612546,usage of ensuresuccestatuscode and handling of httprequestexception it throws whats the usage pattern of httpresponsemessageensuresuccestatuscode it thisposes of the content of the message and throws httprequestexception but i fail to see how to programmatically handle it any differently than a generic exception for example it does not include the httpstatuscode which would have been handy is there any way of getting more info out of it could anyone show relevant usage pattern of both ensuresuccestatuscode and httprequestexception,['.net'] +612548,angular uirouter how to access parameters in nested named view passed from the parent template hi i am trying to access a parameter in the controller viewworklogcrtl while using uirouter and running into difficulty basically my parent template containsauisrefinstanceticketworklogidtickettestnum showand then further down the pagesectionuiviewtopsectionthen in my appjs containing clientside routing info in short i have stateproviderstateinstanceticket url ticketinstanceid templateurl partialsinstanceticket controller viewticketcrtlstateinstanceticketworklog views topsection templateurlpartialsticketworklogjade controller viewworklogcrtl the template loading is working correctly the issue and question i cannot find an answer to is how to access testnum being passed through the uisref link to and within the viewworklogctrl is there a better approach to this much thanks,['javascript'] +612563,python iterate over two lists simultaneously is there a way in python to forloop over two or more lists simultaneouslysomething likea 123b 456for xy in ab print xyto output1 42 53 6i know that i can do it with tuples likel 14 25 36for xy in l print xy,['python'] +612576,spritekit memory management preload cached and fps issue my question is pretty simple according to the apple docs you have the ability to preload textures into ram prior to presenting a scene like sosktextureatlas atlas sktextureatlas atlasnamedeffect circle explodesktextureatlas atlas2 sktextureatlas atlasnamedbox explodessktextureatlas atlas3 sktextureatlas atlasnamedfence newsktextureatlas atlas4 sktextureatlas atlasnamedswipesktextureatlas atlas5 sktextureatlas atlasnamedcoinsktextureatlas atlas6 sktextureatlas atlasnamedtwo timessktextureatlas atlas7 sktextureatlas atlasnamedthree timessktextureatlas atlas8 sktextureatlas atlasnamedgussktextureatlas preloadtextureatlasesatlas atlas2 atlas3 atlas4 atlas5 atlas6 atlas7 atlas8 withcompletionhandler moron logo removefromsuperview moron logo null stuffhidden no storehidden no scroll viewuserinteractionenabled yes self present game viewnow would there be any negative effect if later on through out gameplay you also call a preload to the same atlas like sovoidloadsktextureatlas atlas sktextureatlas atlasnamedeffect circle explodesktextureatlas atlas2 sktextureatlas atlasnamedcoinsktextureatlas preloadtextureatlasesatlas atlas2 withcompletionhandlerexplode textures nsmutablearray alloc initint numimages intatlastexturenamescountfor int i0 i numimages21 i nsstring texturename nsstring stringwithformateffect circle explode dpng i sktexture temp atlas texturenamedtexturename explode textures addobjecttempexplodeanimation skaction animatewithtexturesexplode textures timeperframe05idle textures nsmutablearray alloc initint numimages2 intatlastexturenamescountfor int i0 i numimages221 i nsstring texturename nsstring stringwithformatcoin dpng i sktexture temp atlas2 texturenamedtexturename idle textures addobjecttempidleanimation skaction animatewithtexturesidle textures timeperframe05self animate0now if i do not preload the texture again the game will actually crash once in awhile not all the time if i just directly inserted the textures into the skaction the crash is an exec bad access on the spriteupdatedouble call so my assumption is that somehow the textures from the first preload were removed from ram and thats why i preload every single time i create a new node now it seems to have fixed that error this leads to another problem though when it comes to performance and hence the reason why i am asking thisthe game runs fine on the 5s and the 5 but as soon you touch an ipod touch 5th gen it barely can go over 15 fps i ran instruments and this is what is eating up all the cpu timecould this be related to my constant call of the preloadatlas call does anyone know why this would be eating my processor time up so badly on older devices thanks so much and hopefully someone else might be having a similar problem and this will help them out once i make my way to bottom of it thanks in advance,['ios'] +612598,net c convert resourceset to json i would like to create a json object from a resource file resx i converted it to a resouceset as suchresourceset resourceset myresourceclassresourcemanagergetresourcesetcultureinfocurrentuiculture true truei now have a set of objects in the form keykey valuevalue but would instead like to convert it to json in the form or a hash map keyvalue,['c#'] +612622,why does my html page has a default width i am trying to change an website from fixed layout to a responsive layout but i am having problems setting up the html width as you can see in the image below the width of html tag is 980px even if the page is empty no css or js just the html tags and doctype the head and body are added automatically by browserfor testing i am using the google chrome dev emulator set up as apple iphone i also tested on a phone and still the page looks too big for the screendo you have any idea what to change to make my html tag width vanish,"['html', 'css']" +612641,datetime drifting weird issue after 2 hours i have a thread to generate a network packet every 40 ms 25 hz it is an infinite loop until told to stop and i am using threadsleepwhen i build the packet one of the values is the current gps time using datetimeutcnow and adding the leap secondsthis works fine when i start but it drifts with time about 2 hours later it is 5 seconds behindi have a symmetrom gps time server and i am using their software as the ntp client and it says the cumulative drift on the pc is about 12 seconds most of that i have noticed is drift while the pc is off and not syncing to ntpanyone have any idea whats going wrong i know threadsleep is not perfect timing and windows is not an rtos but the drift does not make sense dropping frames wouldi cannot post code due to some proprietary and itar issues but i can post a rough outline whileabort currenttime datetimeutcnow leapseconds buildpacketcurrenttime streamwritemsg 0 sendsize networkstream threadsleep40 i am in windows 7 and using visual studios 2010,"['c#', '.net']" +612645,sending get request with authentication headers using resttemplate i need to retrieve a resources from my server by sending a get request with the some authorization headers using resttemplate after going over the docs i noticed that none of the get methods accept headers as a parameter and the only way to send headers such as accept and authorization is by using the exchange methodsince it is a very basic action i am wondering if i am missing something and there another easier way to do it,['java'] +612730,what is the standard procedure used for loginsystems in iosapps i am creating an app and a website for a project i have got going but i am not sure what i should do about login this is not a i am a noob and i want an app with loginquestion i am somewhat experienced with both web database and appdevelopment but i have never actually touched the subject of security before other than by application templateswhat i am imagining is a simple loginsystem like skype facebook netflix really any app that you are able to log in to which also has a website to log in toa part of my question is towards the security of the process my initial thought is that a password in clean text should never be sent over internet which makes me believe that the passwords should be hashedencrypted on the phone as well on the website when logging in i have done some smalltime hashingencrypting before but just by using sha1 and md5 to convert the text whats the proper way to do this with my current knowledge i assume that if i am using md5 to encrypt a password anyone could decrypt it with md5 too but that i could use a salt or some form for altering key is that how the big boys are doing it or is there a secret passage i do not know ofnow onto the real question how should i store a login securelywhat i have tried when making a testproject in xcode for this i simply created a class user with a field for username when logging in by entering a username and password i simply sent a postmethod httprequest to my phppage which simply performed a select from user where username postusername and password postpassword if the database returned one row then the password was correct and the page could print out the user in json or whatever when the device got the successful login i converted the userobject in the app now containing the username and potentially userid email address etc to nsdata and using nskeyedarchiver and nskeyedunarchiver to save and load the user never to authenticate again if the user clicks log out i wipe this archive this works but i sense that it is not a particularly secure way of doing it if so why exactly is thatour backend is currently googles app enginejava which has support for oauth some are recommending this but we cannot find any proper documentation that makes sense for our plan with custom users,"['ios', 'objective-c']" +612750,angularjs use of rowspan to group hierarchical data is it possible to group data using rowspan as explained here in a table rendered with angularjs data is hierarchical with state having many counties and each counties has multiple zipcodes i want a table with only column for state county zip etc so give a rowspan for length of the collection i am not sure ngrepeatstart and ngrepeatend can be used to achieve this please see the starter template here table thead tr thstateth thcountyth thzipth tr thead tbody tr ngrepeatst in states tdstnametd tdtd tdtd tr tbody tabledata var oh counties name franklin zips 12345 name adams zips 1234 name allen zips 123 wi counties name dane zips 1 name adams zips 1234 scopestates name oh counties oh counties name wi counties wi counties edita handcrafted version of the desired output is here,['javascript'] +612890,how to scale uiimage using width and keep ratio i have a uiimage that is much smaller than the uiimageview i am applying it too i would like to know how to scale the uiimage to fit the width of the uiimageview but keep the width x height ratio of the original small imagethis is what my code looks like pre any sort of scaling playerimageview uiimageview alloc initwithframecgrectmake100 20 selfplayerviewframesizewidth20 2450playerimageviewcontentmode uiviewcontentmodebottomuiimage placeholderimage uiimage imagenamed placeholdervaultpngplayerimageview setimageplaceholderimageany help would be appreciated,"['ios', 'objective-c']" +612908,protect image download i know the best way to protect image download is not putting it on internet in the first placei assume there is no 100 protection against image download and that if a user can see an image on internet he can with a bit of experience find access to download iti am aware of transparent gif or png covering the images or using background image css property to protect it and prevent right click download but are there other ways to complicate image download and therefore prevent image download by most usershere is a fiddle with code to start with img src,"['html', 'css']" +613087,gcc attributes with c methods in gcc with a c method defined in a header file is it possible to use the attribute syntax can someone provide an example for me please the following code does not workclass foo public void my func attribute hot void my func some stuff it seems like you have to put the attributes in the declaration and not in the definition of a function when you define a methodfunction in a header file you do not have a separate declarationalso how to use this with templates for example the following code fails to compile with error attributes are not allowed on a functiondefinition template version of max for type ttemplate typename tinline t maxconst t x const t y attributeconst if x y return x else return y,['c++'] +613107,how to deal with precompiled headers randomly becoming corrupted on a cancelled build i use visual c 2012 with a project that makes a heavy use of precompiled headers so heavy that the infamous zm switch is in usewhen i cancel a build in progress i sometimes get this error on the next builderror c1852 foopch is not a valid precompiled header filenine times out of ten things will go smoothly but when this happens i have to find the pch and delete it manually before restarting the buildthat annoys me a bit is there a way to prevent this from happening a patch from microsoft or a way to force visual to delete the pch and restart the build automatically when the issue occurs or some other solution i did not think aboutedit heres the version of visual i am runningmicrosoft visual studio professional 2012version 11061030 update 4,['c++'] +613118,what is export default in javascript file safestringjs build out our basic safestring typefunction safestringstring thisstring stringsafestringprototypetostring function return thisstringexport default safestringi never see export default before are there any equivalent stuff for export default that can be easier to understand,['javascript'] +613155,cannot create an instance of error in wpf xaml i have a public class public class fcabinetnamesliststring businesslogic admintasks new businesslogic public fcabinetnames try listcabinetdata cab1 admintaskscabinetdataforgrid foreach var c1 in cab1 thisaddc1cabinetname catch now in the xaml page when i try to add this class as a static resource i get the cannot create instance of as below please guideupdate an important point i missed telling the application compiles fine and the xaml page also loads fine i was planing to use this as a datasource and expectedly that remains blank,['c#'] +613204,where is the location of schema file for i have been googling for the schema file that describes wpf elements for xaml but cannot find it the namespace declaration should has a list of all wpf features for example types attributes or elements that it adds to standard xamli can find the schema file for xaml in visual studo cache directory the file is called xaml2006xsd there is a wpfexsd but its target namespace is this may sound trivial but i have spend hours to find this schema file where can i found a schema file xsd file with targetnamespace set to if it is hidden inside dll file then perhaps there is an open source resource that host this schema file,['.net'] +613281,input error nameerror name is not defined i am getting an error when i try to run this simple python scriptinput variable input enter your name print your name is input variablelets say i type in dude the error i am getting isline 1 in moduleinput variable input enter your name file string line 1 in modulenameerror name dude is not definedi am running mac os x 1091 and i am using the python launcher app that came with the install of python 33 to run the scriptedit i realized i am somehow running these scripts with 27 i guess the real question is how do i run my scripts with version 33 i thought if i dragged and dropped my scripts on top of the python launcher app that is inside the python 33 folder in my applications folder that it would launch my scripts using 33 i guess this method still launches scripts with 27 so how do i use 33,['python'] +613314,query by type in spring data jpa i have abstract classentityinheritancestrategy inheritancetypejoinedpublic abstract class a and few extending classes likeentitypublic class b extends a i also have third entityentitypublic class c onetoonecascade cascadetypeall fetch fetchtypeeager private a objecta and the question is how can i construct spring data jpa finder in c entity repository to query only objects extending a with desired type,['java'] +613339,how to change font style and background color in titleforheaderinsection method after long reading and checking code i am proud to have a custom table view with sections and section titles all populated from core data objects now i would need to customize the section title and background color i have seen it done but in a viewforheaderinsection method is is not possible inside my titleforheaderinsection methodhere you have my methodnsstringtableviewuitableview tableview titleforheaderinsectionnsintegersection id nsfetchedresultssectioninfo thesection selffetchedresultscontroller sectionsobjectatindexsection nsstring sectionname thesection name if sectionname isequaltostringtext 1 return today else if sectionname isequaltostringtext 2 return tomorrow if selffetchedresultscontroller sectionscount0 idnsfetchedresultssectioninfo sectioninfo selffetchedresultscontroller sectionsobjectatindexsection return sectioninfo name else return nil,['ios'] +613355,mongoengine reference field query i am building a reservation site for a restaurant using flask framework and mongoenginemy main object is to fetch all the reservation objects which customer ids equal to wanted customer id with jsondata rzvobjectsrestaurantrest customercdbobjectsgetidrequestargsgetcustomerreservationallwhen i try to trigger this query json gives me an errormongoengineerrorsinvalidqueryerrormy reservation model belowclass reservationsdocumentdocument restaurant fieldsreferencefieldrestaurant customer fieldsreferencefieldcustomers shift type fieldsembeddeddocumentfieldshifts room fieldsreferencefieldrooms time fieldsstringfield covers fieldsintfield status fieldsstringfielddefaultwait desk fieldsembeddeddocumentfielddesks date fieldsdatetimefield sit date fieldsdatetimefield end sit date fieldsdatetimefield cancel date fieldsdatetimefieldmy customer model belowclass customersdocumentdocument title fieldsstringfield full name fieldsstringfield first name fieldsstringfield last name fieldsstringfield telephone fieldsstringfield visits fieldsstringfieldjsongetjsoncustomerreservation thisattrdataid function data consolelogdata reservationfilldata and finally the view if requestargsgetcustomerreservation data rzvobjectsrestaurantrest customercdbobjectsgetidrequestargsgetcustomerreservationall return datawhat is the right way to query this situation do i have to use a filter,['python'] +613363,get column in array of arrays given a javascript arrayvar m somenumbervar and someothernumbervar myarray new m x and arraywhats the fastest way to get a column rather than a row from the arrayex structure getcolumn functionanarray columnnumber if column number exists in array get column else return null,['javascript'] +613387,is it possible for qtestlib to thisplay the gui it is testing as it runs the use case is i have a qt app and i would like to automate userstyle testing of it that is i would like to use keyclicks mouseclick and so on but i would like for the qt application window to actually be thisplayed while this is happeningthe issue i am having right now is that using qtestlib involves using the qtest main macro instead of defining main myself so i never get an opportunity to show the widgets being tested so another way to word this question is is there a way to use qtestlib on an application that is using its main functioni know squish and probably testability driver are capable of this but if it is possible to get this functionality without using extra tools then that would be ideal,['c++'] +613411,how to use circular references in restkit using ref and id i have an api using the jsonnet serialization library it uses ref and id fields for circular references restkit does not realize that these ref fields are referring back to another object that has already been serialized is there a way to tell restkit to use these fields so empty objects are not createdhere is an example of my json id1 workorder id2 location id3 address id4 guid8086990f13a04f938a9b043ff247ae66 workorders ref2 guidae58698d4fcf4c3182bf529077b6d059 appointments ref1 guid94140fc698854395a79d2b60452f2bf4 calendar id5 ownerid1bbda60d0bda4b97b6e524460106bc54 isactivetrue appointments ref1 guide6c91678290d4d12b52f9f6ad36dd679 guid731f20c66ecb4515ade3df47bc929c86,['ios'] +613428,how to run a single test in guard for rspec i use guardrspec to automatically run necessary rspec tests as my files changes and i love how it works however when i am debugging a file with multiple tests sometimes i just want an individual test to be rerun for example with rspec from the command linerspec specrequestsmy favorite specrb100this will run only the single spec at line 100 in my favorite specrb i tried inputting the above into the guard console but it just ran all the tests as if i had just pressed enter is there another syntax in the guard console to run a single spec,"['ruby-on-rails', 'ruby']" +613445,factorial function works in python returns 0 for julia i define a factorial function as follows in pythondef factn if and 1 return n else return and factn1printfact100and as follows in juliafunction factn if and 1 n else and factn1 endendprintlnfact100the python program returns a very large number for the evaluation of 100 as expected julia returns 0 with a smaller number like 10 they both worki have two questionswhy does python handle this ok and julia notwhy does not julia throw an error and just print 0 instead,['python'] +613471,when is a c class with no methods poor design when is a class with no methods poor designfrom what i have read a class with no methods ie no behaviors aka dumb class is poor design with the exception of data transfer objects dtos this is due to the purpose of dtos being to reduce the overhead when transferring data to a remote interface local dto there appears to be some debate on dtos and plain old class object poco vs dto and debate going further to anemic design anemic model domainso where the dumb class in question is a local object ie not for transferring data are you generally better to refactor the attributes of the dumb class and implement them as a collection eg dictionary to quote bill k how can i write daos for resources with extensible propertieswhere you would have used an object use a hashtable for your attribute names use keys for the attribute values use the value in the hashtablemy thinking when designing this dumb class was that of composition another class is composed of multiple dumb class objects ie a collection of dumb class objects was my thinking wrong if i am to implement the dumb class as a collection i would have a collection of a collection of attributes i am of the understanding collections of collections of collections etc is also poor design is there some guiding principle to balance these apparent choices of poor designas always any insight or guidance is appreciatedregardsshannon,['c#'] +613472,mocking static methods with powermock and mockito i am trying to verify a call to javasqldrivermanagergetconnection using junit mockito and powermock heres my test caserunwithpowermockrunnerclasspreparefortestdrivermanagerclasspublic class mysqldatabaseconnectionfactorytest private configurationservice configurationservice private mysqldatabaseconnectionfactory reference before public void setup throws exception thisreference new mysqldatabaseconnectionfactory test public void testgetconnection throws sqlexception setup connection connection mockconnectionclass powermockitomockstaticdrivermanagerclass whendrivermanagergetconnectionanystring anystring anystringthenreturnconnection run thisreferencegetconnection verify powermockitoverifystatic drivermanagergetconnectionjdbcmysqlmyhost1database username password heres the code under testpublic class mysqldatabaseconnectionfactory implements databaseconnectionfactory override public connection getconnectioniapplicationinstance appinstance try return drivermanagergetconnectionstringformatjdbcmysqlsds mysql host mysql port mysql database mysql username mysql password catch sqlexception e throw new runtimeexceptione interestingly enough this code fails with a javasqlsqlexceptionjavalangruntimeexception javasqlsqlexception no suitable driver found for jdbcmysqlmyhost1databasenow i could easily just make sure that my sql driver mysql in this case is loaded at test time but why is not the static method completely mocked out without sideeffects updatei have better isolated the problem i have added a test method to my test case which tries getting a connection from drivermanagertestpublic void testsomething connection conn mockconnectionclass mockstaticdrivermanagerclass whendrivermanagergetconnectionanystringthenreturnconn connection c drivermanagergetconnectionwhut verifystatic drivermanagergetconnectionwhutthis test actually passes while the other test still fails it seems that powermock is not mocking the reference to the class inside of mysqldatabaseconnectionfactory how can i work around this,['java'] +613482,how to fix unicodedecodeerror ascii codec cannot decode byte as3ngokevinsite nano contentblog20140114 testchinesemkdas3ngokevinsite woktraceback most recent call lastfile usrlocalbinwok line 4 inenginefile usrlocallibpython27sitepackageswokenginepy line 104 in initselfload pagesfile usrlocallibpython27sitepackageswokenginepy line 238 in load pagesp pagefrom fileospathjoinroot f selfoptions self rendererfile usrlocallibpython27sitepackageswokpagepy line 1 in from filepagemetacontent pagerendererrenderpageoriginalfile usrlocallibpython27sitepackageswokrendererspy line 46 in renderreturn markdownplain markdownpluginsfile usrlocallibpython27sitepackagesmarkdowninitpy line 419 in markdownreturn mdconverttextfile usrlocallibpython27sitepackagesmarkdowninitpy line 281 in convertsource unicodesourceunicodedecodeerror ascii codec cannot decode byte 0xe8 in position 1 ordinal not in range128 note markdown only accepts unicode inputhow to fix itbut in some other pythonbased static blog appschinese post can be published successfullysuch as this app in my site post can be published successfully,['python'] +613527,content security policy in chrome app my chrome app has the following manifest name version 103 manifest version 2 description chrome extension for icons 16 imagestestpng 19 imagestestpng 256 imagestestpng app background scripts backgroundjs sandbox js libtestapijs permissions all urls notifications storage videocapture i have a script file that runs eval i have read about csp and sandboxing but i still get this errorrefused to evaluate a string as javascript because unsafeeval is not an allowed source of script in the following content security policy directive defaultsrc self chromeextensionresource note that scriptsrc was not explicitly set so defaultsrc is used as a fallback,['javascript'] +613528,what alignment issues limit the use of a block of memory created by malloc i am writing a library for various mathematical computations in c several of these need some scratch space memory that is used for intermediate calculations the space required depends on the size of the inputs so it cannot be statically allocated the library will typically be used to perform many iterations of the same type of calculation with the same size inputs so i would prefer not to malloc and free inside the library for each call it would be much more efficient to allocate a large enough block once reuse it for all the calculations then free itmy intended strategy is to request a void pointer to a single block of memory perhaps with an accompanying allocation function say something like thisvoid allocatescratchsize t rows size t columnsvoid docalculationsize t rows size t columns double data void scratchthe idea is that if the user intends to do several calculations of the same size he may use the allocate function to grab a block that is large enough then use that same block of memory to perform the calculation for each of the inputs the allocate function is not strictly necessary but it simplifies the interface and makes it easier to change the storage requirements in the future without each user of the library needing to know exactly how much space is requiredin many cases the block of memory i need is just a large array of type double no problems there but in some cases i need mixed data types say a block of doubles and a block of integers my code needs to be portable and should conform to the ansi standard i know that it is ok to cast a void pointer to any other pointer type but i am concerned about alignment issues if i try to use the same block for two typesso specific example say i need a block of 3 doubles and 5 ints can i implement my functions like thisvoid allocatescratch return malloc3 sizeofdouble 5 sizeofintvoid docalculation void scratch double dblarray scratch int intarray unsigned charscratch 3 sizeofdoubleis this legal the alignment probably works out ok in this example but what if i switch it around and take the int block first and the double block second that will shift the alignment of the doubles assuming 64bit doubles and 32bit ints is there a better way to do this or a more standard approach i should considermy biggest goals are as followsi would like to use a single block if possible so the user does not have to deal with multiple blocks or a changing number of blocks requiredi would like the block to be a valid block obtained by malloc so the user can call free when finished this means i do not want to do something like creating a small struct that has pointers to each block and then allocating each block separately which would require a special destroy function i am willing to do that if that is the only waythe algorithms and memory requirements may change so i am trying to use the allocate function so that future versions can get different amounts of memory for potentially different types of data without breaking backward compatibilitymaybe this issue is addressed in the c standard but i have not been able to find it,['c'] +613578,celery missed heartbeat on node lost i just upgraded to celery 31 and now i see this i my logs on node lost info missed heartbeat from celeryqueue name for every queueworker in my clusteraccording to the docs broker heartbeat is off by default and i have not configured itshould i explicitly set broker heartbeat0 or is there something else that i should be checking,['python'] +613600,fatal error require once failed opening required i am trying to run my online site on my local machine i stumbled upon a problemthis is my htaccessadefaultcharset utf8options indexesphp value include path homesiteswexampleitexampleithtdocsconfphp value include path xampphtdocsconfphp value thisplay errors onphp value upload max filesize 20mphp value post max size 50mphp flag magic quotes gpc offifmodule mod rewritecoptions followsymlinksrewriteengine onrewritebase rewritecond http host exampleit ncrewriterule lr301ifmoduleifmodule mod rewritec options followsymlinks rewriteengine on rewritecond request uri common rewriterule common resourcesmediacommon1 rewritecond request uri uploadimg rewriterule uploadimg wappirphppath1query string rewritecond request uri upload rewriterule upload resourcesupload1 rewritecond request uri google rewritecond request uri common rewritecond request uri upload rewritecond request uri uploadimg rewritecond request uri wappirphp rewriterule wappindexphpurl1ifmodulethe error i receivewarning require onceconfincphp failed to open stream no such file or directory in cxampphtdocswappindexphp on line 2fatal error require once failed opening required confincphp include pathxampphtdocsconf in cxampphtdocswappindexphp on line 2how can i solve it maybe it deals with the privileges of the xampp user editgetcwd gives me cxampphtdocswappconfincphp is located in cxampphtdocsconfthe require in indexphp require onceconfincphp,['php'] +613610,how to block upload adult or nude image i have a problem to uploading the imagei have to validate the image in which adult or nude image is not upload,"['php', 'jquery']" +613627,how to turn makefile into json compilation database say we have make files not cmakepremakeninja etc for our project that do work for gcc and clang we want to generate out from them json compilation database to feed it into clangmodernize tool how to do such thing is there any parser in clang infrastructure or some script with usage like make c argspy gcc cxxcc argspy g or some other tool,['c++'] +613639,no cache with httpclient in windows phone 8 i have read that in order to thisable caching while using get and post methods in httpclient i need to use a webrequesthandler as my httpclients httpclienthandler and change its cache policy however webrequesthandler is not within systemnethttpdll but rather in systemnethttpwebrequestdll so i tried to add the dll to the project as a reference i got an error messagemicrosoft visual studioa reference to a higher version or incompatible assembly cannot be added to the projectagain after a little search i concluded that the dll file was blocked because it was downloaded from another source to unblock it i went on trying the solution here however it did not work either and i am still getting the same error when i try to add the dll file as a referenceall i want to do is thisable caching using my httpclient am i doing anything wrong here i am open to any type of advice or helpmy system is windows 81 and i am using visual studio 2013 the project i am working on is a windows phone 8 application the directory of dll i am trying to reference is cwindowsmicrosoftnetframeworkv4030319systemnethttpwebrequestdll thank you in advance,"['c#', '.net']" +613649,smallest range that includes at least one number from each of the k lists you have k lists of sorted integers find the smallest range that includes at least one number from each of the k lists for example list 1 4 10 13 14 list 2 0 9 15 18 list 3 5 18 22 30 the smallest range here would be 14 18 as it contains 14 from list 1 15 from list 2 and 18 from list 3my approach isjust use a minheap and insert the first elements from k lists remove the the min element and add the next element from the corresponding listsimultaneously track the max and min value so that we can calculate the minimum rangebut the only issue i am facing is suppose for one list there is no more elements left than should i finish there or should i continue,['java'] +613733,format suppress scientific notation from python pandas aggregation results how can one modify the format for the output from a groupby operation in pandas that produces scientific notation for very large numbers i know how to do string formatting in pythong but i am at a loss when it comes to applying it here df1groupbydeptdata1sumdeptvalue1 1192433e08value2 1293066e08value3 1077142e08this suppresses the scientific notation if i convert to string but now i am just wondering how to string format and add decimals sum sales deptastypestr,['python'] +613735,liveconnect calls are blocked on 7u45 since java 7u51 became available i have a page with a java applet that has the following javascript code which makes a liveconnect call when the window is closing to perform some clean up taskswindowonbeforeunload functione var result documentoutappletclosecheckup until yesterday this was working as expected and performed the clean up tasks within the appletnow that java 7u51 is available i have accessed this applet today and selected later when prompted to updated to the latest version of java now when i close the window i get a javascript errorobject does not support property or method closecheckjust to clarify this is with java 7u45 installedis this expected behaviour or is there anything i can do to make it still work on 7u45 i cannot find any mention of this in the release notes and prior to 7u51 our live connect call would still work without being on the latest security baselineupdatethe above was with my java security set as high i have changed it to medium and repeated the above i now get a message asking if i want to allow or block the liveconnect callit seems there is now an undocumented as far as i can find requirement that liveconnect will only work if you are on the security baseline 7u51note the liveconnect call to the applet works without any changes to the applet once i have updated to 7u51,"['java', 'javascript']" +613781,catch exception from child activity in parent activity i have been wondering if it is possible to stop a crash in an android app by capturing said crash in a parent activitylets say i cause a fatal exception in the oncreate method of a child activity will i be able to capture that exception in anyway or will the app crash no matter what i tryhere is an example of what i meanmainjavaoverrideprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutly main my main activity starts try call the next activity intent intent new intentgetapplicationcontext childclass startactivityintent catchexception e logwtfexception wtfexception from child activity woohoo and etostring childjavaoverrideprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutly child create exception for science int a 0 a 1athis does not work the child activity dies and takes the parent with itwill it be possible to do it via startactivityforresultthanksedit i do not need the crash data i just want to know how can i avoid the app crashinglooking around i foundusing global exception handling on androidwhich includes this piece threadsetdefaultuncaughtexceptionhandlernew threaduncaughtexceptionhandler override public void uncaughtexceptionthread paramthread throwable paramthrowable logealertlets see if it works that let me log the uncaughtexception avoiding the crash nevertheless the app went blackscreen and stopped respondingedit 2after a lot of reading thanks to user370305 in the thread how do i obtain crashdata from my android applicationi have reached a dead end either i handle the uncaughtexception and call defaultuehuncaughtexceptionparamthread paramthrowable so the app crashes or i do not call defaultuehuncaughtexception the app does not crash but does not respond eitherany ideasfinal threaduncaughtexceptionhandler defaultueh threadgetdefaultuncaughtexceptionhandlerthreadsetdefaultuncaughtexceptionhandlernew threaduncaughtexceptionhandler override public void uncaughtexceptionthread paramthread throwable paramthrowable logealertlets see if it works defaultuehuncaughtexceptionparamthread paramthrowable,['android'] +613785,how can i execute javascript callback function from c host application i am creating an application in c that hosts custom web pages for most of the gui as the host i would like to provide a javascript api so that the embedded web pages can access some of the services provided by the host applicationi have been able to get the simple case for this working using the webbrowserobjectforscripting property and implementing a scripting class this works great for synchronous javascript calls however some of the operations that the host provides are long running and i would like to provide the ability for the javascript to be called back when the operation completes and this is where i am running into troublejavascriptfunction oncomplete result alert result function start windowexternallongrunningprocess data oncomplete ccomvisibletruepublic class scriptobject public void longrunningprocess string data callback do work call the callback the start function in javascript kicks this whole process off the problem i am having is what is the type for the callback and how should i call it from c if i use the string type for callback it compiles and runs but from within the longrunningprocess method callback actually contains the full contents of the oncomplete function ie function oncomplete result alert result if i use the object type it comes back as a com object using the microsoftvisualbasicinformationtypename method it returns jscripttypeinfo but as far as i can tell that is not a real type nor is there any real mention of it through all of msdnif i use the ireflect interface it runs without error but there are no members fields or properties on the object that i can finda work around would be to pass the string name of the callback function instead of the function itself ie windowexternallongrunningprocess data oncomplete i do know how to execute the javascript function by name but i would rather not have that syntax be required in the web pages it also would not work with inline callback definitions in the javascriptany ideasfor what it is worth i have already got this system working with the chromium embedded framework but i am working to port the code over to the webbrowser control to avoid the hefty size of rethistributing chromium however the html pages being developed will eventually be run on linuxmac osx where chromium will probably still be used,"['c#', 'javascript']" +613821,customize override flaskadmins submit method from edit view preconditionsi am new to python and to flaskadmin in particular i created a simple test service which has mondodb keeping the data with relationship of onetoone kind employeename salarythe model looks like thatclass employeedbdocument fullname dbstringfieldmax length160 uniquetrue salary dbintfieldand i use flaskadmin to observe the table with the data and to edit it when i want to change the salary field i just press the edit button and in flaskadmins default edit view i change the integer value i press submit and a new value in the database is successfully appliedquestionbut i need to override the submit method in the way that leaves as it is the functionality and adds some custom code like let us assume i want to add a comment in the log file after an actual db submit loggingwarningthe salary of s was changed to s fullname salaryany suggestion on how to achieve that would be much appreciated perhaps you could direct me in the way to go since the flaskadmin documentation does not give me enough help so far,['python'] +613832,using angularjs with liferay i would use global angularjs with liferay portal because like the devise of angularjswhy angularjs html is great for declaring static documents but it falters when we try to use it for declaring dynamic views in webapplications angularjs lets you extend html vocabulary for your application the resulting environment is extraordinarily expressive readable and quick to developi would simple use the declarative syntax of html by developing of liferaytheme and portletsfor this requirement i have created new liferaytheme and customized a little bit the portal normalvmdoctype htmlinclude init html ngappliferayhead script srcscript script typetextjavascript srcjavascript foldermyjs charsetutf8scriptheadbody classcss class div ngcontrollerliferayctrlhere myjsangularmoduleliferay controllerliferayctrl functionscope consolelog init angularjs scopeliferay liferayand i can extend the controller like getting of liferaysite namewhats all this in aid ofhereby i can simple access liferay javascript values functions over declarative html syntax without direct javascript function calling like angularjs wayeg now it is possible to get values and functions of liferay javascript by declarative html code like here for getting current url in web content thisplayliferay current url liferaycurrenturlhowever my questions arewhich sideeffects could happen by using angularjs global in liferaycould it get performance issuesconflicts with other javasripts eg alloyusing of angularjs inside of portlets,['javascript'] +613894,how to check for microphone access at time of launch in my app i will be using a microphone to do some recording from ios70 onwards the user is asked to check the permission to access the microphone before starting the audioi have a button start recording in my app here it first checks the users permission for recordingheres the code to do thisifavaudiosession sharedinstance respondstoselectorselectorrequestrecordpermission avaudiosession sharedinstance performselectorselectorrequestrecordpermission withobjectpermissionblockifndef iphone 7 0 typedef void permissionblockbool grantedendifpermissionblock permissionblock bool granted nslogpermissionblock if granted self doactualrecording else warn no access to microphone now i want to ask the user to authorize microphone use as the user starts the app then when the user selects record button it gives a popup message againa similar functionality happens with location services how can i do this for microphone access,['objective-c'] +613935,formatting currency in android using wrong decimal separator i got a bug report from a swethish user saying that our swethish currency was using the wrong decimal separatornumberformat enus numberformatgetcurrencyinstancelocaleusnumberformat engb numberformatgetcurrencyinstancelocaleuknumberformat svse numberformatgetcurrencyinstancenew localesv sedouble cost 1020dstring fmt en us s en gb s sv se sstring text stringformatfmt enusformatcost engbformatcost svseformatcostlogeformat text formati1 en us 1020 en gb a1020 sv se 1a 020a krthey say that the format should be 1 020 kr when i inspect the format object it looks like it has decimalseparator of in the symbols table but a monetaryseparator of does anyone know if is actually correct whether this is a bug in androidjava or any sort of workaround,"['java', 'android']" +613954,how to configure hibernate logging using log4j2xml i recently switched to apache log4j2 and still can not find a way to configure hibernate logging using log4j2xmlbecause i can not find a way around this problem i still use log4jproperties file explicitly for hibernate this is not the best solution since my log4j2xml uses jpa appender writes logs to db i do not want to write separate logic for hibernateis there a way to configure hibernate logging using log4j2,['java'] +613958,chosen dataplaceholder does not thisplay fully for listboxes i have an aspnet listbox and i am using the jquery chosen pluginthe dataplaceholder value does not seem to always work with list boxesfor instance see the imagenotice the list box for region it says select re then it stopsits quite random look at the list box for city that works fine but look at the list box for country it is supposed to say select country but it shows select country missing the last period my listbox controls aspnet markup is as suchasplistbox idlbregion autopostbacktrue runatserver classchosenselect dataplaceholderselect region selectionmodemultiple onselectedindexchangedlbregion onselectedindexchanged tooltipselect regionasplistboxi have tried recreating it etcbut to no avail what gives heres my jquery that includes the class for chosenchosenselectchosen search contains true no results text oops nothing found allow single deselect true chosencontainercsswidth 200px,"['jquery', 'asp.net']" +613967,ios7 storyboard image picker not working im trying to set up an imagepicker in a new ios7 xcode project using storyboards but cannot seem to find any examples online until i found the following code i have set it up so that when a button is pressed it uses a modal push thing to navigate to the view which has the class of uiimagepickercontroller which apparently calls in the image picker code however when the app is run it would not load anything up after clicking on allow the application to access your photos any chance of some help please error screen shot grab interface setupinterface ridecount addride viewcontroller uiviewcontrolleruiimagepickercontrollerdelegate uinavigationcontrollerdelegatecodevoidprepareforsegueuistoryboardsegue segue senderidsender uiimagepickercontroller controller segue destinationviewcontroller controllersourcetype uiimagepickercontrollersourcetypephotolibrary controllerdelegate selfvoidimagepickercontrollerdidcanceluiimagepickercontroller picker self thismissviewcontrolleranimatedyes completionnilvoidimagepickercontrolleruiimagepickercontroller picker didfinishpickingmediawithinfonsdictionary info self thismissviewcontrolleranimatedyes completionnil uiimage image info objectforkeyuiimagepickercontrolleroriginalimage selfview viewwithtag1023 removefromsuperview uiimageview imageview uiimageview alloc initwithframecgrectmake32022002 10 100 100 imageviewtag 1023 imageviewcontentmode uiviewcontentmodescaleaspectfit imageviewimage image selfview addsubviewimageview,"['ios', 'objective-c']" +614049,multiple java installations in mac os x mavericks i downloaded jdk for mac os x 1091 from oracle but i had to install another java from apple site once more as i could not launch eclipse with it these are two pages that i referred installing java on os x 109 mavericks usnow i have three java binaries installed in my computerinstallation asystemlibraryframeworksjavavmframeworkversionscurrentcommandsjavajava version 170 51javatm se runtime environment build 170 51b13java hotspottm 64bit server vm build 2451b03 mixed modeinstallation bsystemlibraryjavajavavirtualmachines160jdkcontentshomebinjavajava version 160 65javatm se runtime environment build 160 65b1446211m4609java hotspottm 64bit server vm build 2065b04462 mixed modeinstallation clibraryjavajavavirtualmachinesjdk170 51jdkcontentshomebinjavajava version 170 51javatm se runtime environment build 170 51b13java hotspottm 64bit server vm build 2451b03 mixed modei found that i can easily remove installation c however i am not sure if this is okwhen i invoked java from command line it points to installation ajava versionjava version 170 51ls alf which javalrwxrxrx 1 root wheel 74 jan 15 0912 usrbinjava systemlibraryframeworksjavavmframeworkversionscurrentcommandsjavais there any way to use just one jdk 17 for mavericks by removing two of them safelyeditafter some setup and test i have only one java 16 installed i have installation b and now installation c is linked to installation a for using eclipse i had to make compiler compliance level to 16 to use it from the help javalangunsupportedclassversionerror unsupported majorminor version 510edit2this seems to what happenedinstallation of apple javainstallation ainstallation b is a symbolic link to ainstallation of oracle javainstallation cchanged the installation b that created a systemlibraryframeworksjavavmframeworkversionsa copied files from installation c not symbolic linkmake a symlink current to versionsai tried to install oracle java only by removing apple java but i got installation error so i guess apple java is needed to install oracle java,['java'] +614051,the selected team does not have an ios developer program membership i am attempting to add myself as a developer on a team for ios it is a university programi go into xcode select the team name and click fix issue earlier it was having code signing problems which i fixed it returns this error the selected team does not have an ios developer program membershipthis is false i know for sure that the team is an ios development team and on developerapplecom it shows me as logged in on the ios team xcode just would not recognize this fact please helpvideo of problem,['ios'] +614110,pandas import multiple csv files into dataframe using a loop and hierarchical indexing i would like to read multiple csv files with a different number of columns from a target directory into a single python pandas dataframe to efficiently search and extract dataexample fileevents 1032020067209401901402109430320200640324087013061054025043 5062021077044016here is what i have so far get a list of all csv files in target directorymy dir cdatafilelist oschdir my dir for files in globglob csv filelistappendfiles read each csv file into single dataframe and add a filename reference column ie file1 file2 file 3 for each file readdf pddataframecolumns range1100for c f in enumeratefilelist key filei c frame pdread csv my dir f skiprows 1 index col0 namescolumns framekey key df dfappendframeignore indextruethe indexing is not working properlyessentially the script below is exactly what i want tried and tested but needs to be looped through 10 or more csv filesdf1 pddataframedf2 pddataframecolumns range1100df1 pdread csvcdatacurrambene 001y09h00m eventscsv skiprows 1 index col0 namescolumnsdf2 pdread csvcdatacurrambene 001y12h00m eventscsv skiprows 1 index col0 namescolumnskeys file1 file2df pdconcatdf1 df2 keyskeys namesfilenoi have found many related links however i am still not able to get this to workreading multiple csv files into python pandas dataframemerge of multiple data frames of different number of columns into one big data frameimport multiple csv files into python pandas and concatenate into one dataframe,['python'] +614135,qt 5 assign slot with parameters to a qpushbutton i have a qt application on c and i want to assign a slot to a qpushbutton but i want to pass some arguments because i have more than one qpushbutton doing similar thing so i want one function but with a parameter in it but qt keeps saying me that there is no slot like this can someone tell me why and how should i do itthank you in advancein the h file i have it was private in the beginning but i changed it in searching of the problempublic slots void handlebuttonint row int colthen in the cppvoid fieldwindowhandlebuttonint row int col cout row col endland again in the same cppconnectthisbuttonsfieldij signalreleased this slothandlebuttonijthis is done in two nested loop so i and j are well definedand my error is qobjectconnect no such slot fieldwindowhandlebuttonij in proj1fieldwindowcpp41qobjectconnect receiver name fieldwindowi read something in the internet that i should say handlebuttonint int but then how should i pass the arguments,['c++'] +614157,how to apply hierarchy or multiindex to panda columns i have seen lots of examples on how to arrange dataframe row indexes hierarchically but i am trying to do the same for columns and am not understanding the syntaxgivendf pddataframenprandomrandn1010 columnsconsumption voltage consumption voltage temperature humidity consumption voltagetemperaturehumidity index pddate range20103periods10 df consumption voltage consumption voltage temperature 20103 1327735 1440285 0317122 1120105 1736651 20104 0132531 0646972 2296734 0332154 0541792 20105 0127623 0592778 0162096 0107398 0628785 20106 1441151 0215424 0021068 0683085 0783994 20107 0157848 1566780 0599017 0628216 0500251 20108 0498926 0338771 0400159 1571975 0255635 20109 0516618 1936360 0199388 0110415 2690859 20110 0779012 1310022 1207503 0095679 0134244 201 0644262 0068196 1041745 0408 0751595 20112 0608046 0506588 1003893 0473716 0211991 humidity consumption voltage temperature humidity 20103 0039869 1875807 0129065 0132419 0572678 20104 1997363 0543881 1235036 1155389 1282912 20105 0458992 0371589 0698094 0695067 1095875 20106 2512991 0795234 1220327 06820 0875705 20107 0263855 1253786 0308674 1057 1474928 20108 0614560 0398284 1307488 02438 1572630 20109 0363889 2571522 1048124 2574866 0417247 20110 0125377 1004011 1312716 2036689 0557569 201 0818585 0595743 1106869 26 0679508 20112 0705707 0959365 0689911 0498411 0353557 what i would like to do is add a hierarchical index or even something akin to a tag to the columns so that they looked something like thisbuilding 1devicetype meter meter weatherdeviceid a b afield consumption voltage consumption voltage temperature 20103 1327735 1440285 0317122 1120105 1736651 20104 0132531 0646972 2296734 0332154 0541792 20105 0127623 0592778 0162096 0107398 0628785 20106 1441151 0215424 0021068 0683085 0783994 20107 0157848 1566780 0599017 0628216 0500251 20108 0498926 0338771 0400159 1571975 0255635 20109 0516618 1936360 0199388 0110415 2690859 20110 0779012 1310022 1207503 0095679 0134244 201 0644262 0068196 1041745 0408 0751595 20112 0608046 0506588 1003893 0473716 0211991 building 2devicetype meter weatherdeviceid a a humidity consumption voltage temperature humidity 20103 0039869 1875807 0129065 0132419 0572678 20104 1997363 0543881 1235036 1155389 1282912 20105 0458992 0371589 0698094 0695067 1095875 20106 2512991 0795234 1220327 06820 0875705 20107 0263855 1253786 0308674 1057 1474928 20108 0614560 0398284 1307488 02438 1572630 20109 0363889 2571522 1048124 2574866 0417247 20110 0125377 1004011 1312716 2036689 0557569 201 0818585 0595743 1106869 26 0679508 20112 0705707 0959365 0689911 0498411 0353557,['python'] +614163,bootstrap datepicker hide after selection how do i hide the calendar after a date is selected is there a specific function that i can use my code below dp1datepicker format mmddy startdate 15d autoclose true enddate 0d there is no convenient right now notation yetany help would be appreciated,['jquery'] +614184,unable to debug managed code using visual studio 2013 cannot evaluate expression error am using debug build note that vs 2012 works i have net application gui as well as powershell built against 45 my os is server 2012 when i attach my application to 2013 visual studio the debugger is not working sometimes its not evaluating expression or showing locals and also watch windowimmediate window nothing works its as if the project is build with release but i have build with debug configuration and as mentioned same thing works when i simply attach with vs 2012 yes i have 2k13 and 2k12 sxsplease note that if i attach the same process with the same settings managed debugging to visual studio 2012 it always works i made sure the symbols are loaded by checking modules tab in visual studio debug windows break points are hitany thoughts on what might be the issue all the updates are uptodate as wellits kind of annoying to launch vs 2012 just to debug when i am using vs 2k13 ide for developmentregards,"['c#', '.net']" +614228,unable to start derby database from netbeans 74 i downloaded netbeans 74 and java 7 update 51 i get the below error when i try to start java db or derby connection from netbeans this is on a windows 8 pc i downloaded the version for windows xp 32 bit at work it works fine i am not sure what is missing thu jan 16 004823 est 2014 security manager installed using the basic server security policythu jan 16 004824 est 2014 access denied javanetsocketpermission localhost1527 listenresolvejavasecurityaccesscontrolexception access denied javanetsocketpermission localhost1527 listenresolveat javasecurityaccesscontrolcontextcheckpermissionaccesscontrolcontextjava372at javasecurityaccesscontrollercheckpermissionaccesscontrollerjava559at javalangsecuritymanagercheckpermissionsecuritymanagerjava549at javalangsecuritymanagerchecklistensecuritymanagerjava1134at javanetserversocketbindserversocketjava375at javanetserversocketinitserversocketjava237at javaxnetdefaultserversocketfactorycreateserversocketserversocketfactoryjava231at orgapachederbyimpldrdanetworkservercontrolimplcreateserversocketunknown sourceat orgapachederbyimpldrdanetworkservercontrolimplaccess0unknown sourceat orgapachederbyimpldrdanetworkservercontrolimpl1rununknown sourceat javasecurityaccesscontrollerdoprivilegednative methodat orgapachederbyimpldrdanetworkservercontrolimplblockingstartunknown sourceat orgapachederbyimpldrdanetworkservercontrolimplexecuteworkunknown sourceat orgapachederbydrdanetworkservercontrolmainunknown source,['java'] +614235,the use of the triple exclamation mark looking through the source code of one of our projects i have found some amount of places where were using three exclamation marks in conditional statements like soif somevar now i understand that this is not some kind of rarely used operator it is just three negations in a row like somevar i do not understand whats the use of it in my opinion it can safely be replaced with single exclamation mark following are my attempts to find a case when a is not equal to a taken straight from the google chrome console var a a atruea stringstringa atruea nullnulla atruea 1212a atruea b 1object b 1ac ac ac is undefined heretruea a atruea 121 2a atrueam i missing some rare or obvious case,['javascript'] +614236,launch an activity using intent and thisable back button press from launching the previous activity in my application i have a login screen if the login is successful a tab activity will launch in that there are 4 tabs when i press one of the buttons in the tab a new activity will launch there is an event in my login class that will get fired in some cases i want to go back to the tab activity when the event get fired i have written a code using intent that code is working fine but after reaching the tab activity i do not want to go back to the activity when back button is pressed i want to remove this i want to show login when back is pressed is there any way to do this this is the code i have usedintent tabinew intentgetapplicationcontexttabclastartactivitytabithe code onkeydown in tab activity is overridepublic boolean onkeydownint keycode keyevent event if keycode keyeventkeycode back superonkeydownkeycode event return true return false,['android'] +614320,how to make a machine trust a selfsigned java application i am deploying an application using jaws and it worked until late 2013 when i got a warning and then this morning java completely blocked it the message in french isapplication bloquae par les parama tres de sacuritavos parama tres de sacurita ont bloqua lexacution dune application autosignae avec une version obsolete ou arrivae a expiration de javawhich would translate roughly asapplication blocked by the security settingsyour security settings have blocked from running an application that has been selfsigned with an obsolete or outdated javathe grammar is not that clear the end of the sentence could be read as eitherblocked a selfsigned application from running with an obsolete or outdated java runtime meaning that the local runtime is too old but the selfsignature is fineblocked an application that has been selfsigned with an obsolete or outdated java compiler meaning that the java compiler used is too oldi searched online for the exact same message in english but i could not find it so the grammar is still unclear note that on the message there is no name xyz from httpurl there is only the text i typed above and a blue i iconnow i do not really understand the exact meaning of this error message but i know that there is an issue because my jar files are all selfsigned i have already faced this on other windows clients and it was easyi extracted a cer certificate from my keystoredownloaded it on the client machine open itmade the customers install it as a trusted source on their local machineit worked like a charm on my test setup and for one customer but another one still has the issue and cannot run my softwarethis is a big issue from me and i do not know what to do should i upgrade my java compiler recompile everything sign every jar file again and cross fingers how can i make that windows box trust my certificate and let the java application run,['java'] +614389,how do i check in sqlite whether a database exists c i am currently programming an app in c and using sqlite as an embedded database i have got my app to create a new database on startup but how do i get it to check if the database exists if it does exist how do i get it to use it and if not how to create a new databasethis is what i have so farprivate void mainwindow loadedobject sender eventargs e sqliteconnection sqlite conn sqlitecommand sqlite cmd bool newdb false if newdb true sqlite conn new sqliteconnectiondatasourcedatabasedbversion3 sqlite connopen messageboxshow31 else sqlite conn new sqliteconnectiondata sourcedatabasedbversion3newtruecompresstrue sqlite connopen sqlite cmd sqlite conncreatecommand sqlite cmdcommandtext create table client id integer primary key title varchar100name varchar100surname varchar100dateofbirth datetime propertyname varchar100moveindate datetimerelationship varchar100spouse varchar100gender varchar100 sptitle varchar100spousename varchar100spousesurname varchar100spdateofbirth datetime sprelationship varchar100spspouse varchar100spgender varchar100 sqlite cmdexecutenonquery sqlite connclose messageboxshowdasdas,['c#'] +614407,training data format for nltk punkt i would like to run nltk punkt to split sentences there is no training model so i train model separately but i am not sure if the training data format i am using is correctmy training data is one sentence per line i was not able to find any documentation about this only this thread topicnltkusersbxienmgecsm sheds some light about training data formatwhat is the correct training data format for nltk punkt sentence tokenizer,['python'] +614434,how to test multiple calls to the same function with different params supose i have a function like thisfunction foo objmethod1 objmethod2 objmethod3to test it i want to do 3 tests using mocha tdd and sinontestmedthod is called with 1 function var expectation sinonmockobjexpectsmethodoncewithexactargs1 foo expectationverifytestmedthod is called with 2 function var expectation sinonmockobjexpectsmethodoncewithexactargs2 foo expectationverifytestmedthod is called with 3 function var expectation sinonmockobjexpectsmethodoncewithexactargs3 foo expectationverifyusing this system sinon fails with unexpected call message on each testi have solved it joining the tree tests into onetestmedthod is called with 1 2 and 3 function var mock sinonmockobj mockexpectsmethodoncewithexactargs1 mockexpectsmethodoncewithexactargs2 mockexpectsmethodoncewithexactargs3 foo mockverifybut i want to have three tests and not one with three assertionsexpectationshow can this be achieved,['javascript'] +614444,access translation file i18n from inside rails model what i have in my model isdef body color enum aqua 009c9c grey 6d6e71 yellow ffe600 white white endi want these values to come from the translation file enymlen group hero hex1 6d6e71 name1 dark grey hex2 c name2 light grey hex3 0099ce name3 blue hex4 f name4 whitei have tried thisdef body color enum tgroupheroname1 009c9c grey 6d6e71 yellow ffe600 white white endbut i get this errorundefined method t for group0x007fabad847ac8so what i am asking is how can i access my local file from the model so i can set my values in the body color enum method,"['ruby-on-rails', 'ruby']" +614500,ios ibeacon how to get all of proximityuuid programmatically i want to see all of proximityuuid of advertising packets programmatically some articles say that it is impossible on ios but android is possible but i cannot believe it because i found the fantastic app blexplr has the feature i need to implement the function into my app does anyone knows how to do it or good examples any help will be appreciatedupdate 2014117i believe davidgyoung answer is right estimote beacons proximityuuid is b9407f30f5f8466eaff9256b57fe6d but thisplayed my estimote beacons uuid on blexplr app is another id,['ios'] +614543,delete column in pandas based on condition i currently have a dataframe consisting of columns with 1s and 0s as values i would like to iterate through the columns and delete the ones that are made up of only 0s heres what i have tried so farones zeros for year in years for i in range0599 if yearstrivaluesany 1 onesappendi if yearstrivaluesall 0 zerosappendi for j in ones if j in zeros zerosremovej for q in zeros del yearstrqin which years is a list of dataframes for the various years i am analyzing ones consists of columns with a one in them and zeros is a list of columns containing all zeros is there a better way to delete a column based on a condition for some reason i have to check whether the ones columns are in the zeros list as well and remove them from the zeros list to obtain a list of all the zero columns,['python'] +614603,check a radio button with javascript for some reason i cannot seem to figure this outi have some radio buttons in my html which toggles categoriesinput typeradio namemaincategories id 1234 value1234 allinput typeradio namemaincategories id 2345 value2345 certain categoryinput typeradio namemaincategories id 3456 value3456 certain categoryinput typeradio namemaincategories id 4567 value4567 certain categorythe user can select whichever heshe wants but when an certain event triggers i want to set 1234 to be set checked radio button because this is the default checked radio buttoni have tried versions of this with and without jquerydocumentgetelementbyid 1234checked truebut it does not seem to update i need it to visibly update so the user can see itcan anybody helpedit i am just tired and overlooked the thanks for pointing it out that and prop,"['javascript', 'html']" +614658,use mysql spatial extensions to select points inside circle i have a table called flags that contains a column called coordinates that is full of mysql points i need to perform a query where i get all the flags within a circle based on a latitude and longitude position with 100m radiusfrom a usage point of view this is based around the users position for example the mobile phone would give the users latitude and longitude position and then pass it to this part of the api it is then up to the api to create an invisible circle around the user with a radius of 100 metres and then return the flags that are in this circleit is this part of the api i am not sure how to create as i am unsure how to use sql to create this invisible circle and select points only within this radiusis this possible is there a mysql spatial function that will help me do thisi believe the buffer function can do this but i cannot find any documentation as to how to use it eg example sql ideally i need an answer that shows me how to use this function or the closest to it where i am storing these coordinates as geospatial points i should be using a geospatial function to do what i am asking to maximize efficiencyflags tableidcoordinatesnameexample row1 geometry 25b tenacy abfor the flags table i have latitude longitude positions and easting and northing utmthe users location is just standard latitudelongitude but i have a library that can conver this position to utm,"['mysql', 'sql']" +614793,strategy for recovering from null malloc due to memory exhaustion reading martin sustricks blog on challenges attendant with preventing undefined behavior in c vs c in particular the problem attendant with malloc failing due to memory exhaustion i was reminded of the many many times i have been frustrated to know what to do in such cases with virtual systems such conditions are rare but on embedded platforms or where performance degradation attendant with hitting the virtual system equates to failure as is martins case with zeromq i resolved to find a workable solution and did i wanted to ask the readers of stackoverflow if they have tried this approach and what their experience with it wasthe solution is to allocate a chunk of spare memory off the heap with a call to malloc at the start of the program and then use that pool of spare memory to stave off memory exhaustion when and if it occurs the idea is to prevent capitulation in favor of an orderly retreat i was reading the accounts of kesselrings defense of italy last night where error messages and ip sockets and such will work long enough to hopefully at least tell the user what happened define spare mem size 120 reserve a megabytestatic void gsparemem void tenacious mallocint requested allocation size static int remaining spare size 0 spare mem size char err msg512 void rtn null attempt to reestablish the full size of spare memory if it needs it if spare mem size remaining spare size ifnull gsparemem reallocgsparemem spare mem size remaining spare size spare mem size touch the memory so os will allocate physical memory mesetgsparemem 0 spare mem size printfnsize of spare memory pool restored successfully in ss at line i n file function line else printfnunable to restore size of spare memory buffern attempt a plain old vanilla malloc and test for failure ifnull rtn mallocrequested allocation size return rtn else sprintferr msg ninitial call to malloc failed in ss at line i file function line ifremaining spare size requested allocation size not enough spare storage to satisfy the request so no point in trying printfsnrequested allocaton larger than remaining pool nt aborting n err msg return null else take the needed storage from spare memory printfsnretrying memory allocationn err msg remaining spare size requested allocation size ifnull gsparemem reallocgsparemem remaining spare size return mallocrequested allocation size ifnull rtn mallocrequested allocation size printfallocation from spare pool succeeded in ss at line i n file function line return rtn else remaining spare size requested allocation size sprintferr msg nretry of malloc after realloc of spare memory pool failed in ss at line i n file function line return null else printfnretry failednunable to allocate requested memory from spare pool n return null int tmainint argc tchar argv int intvec null double dblvec null char pstring null char string every good boy does fine intvec int tenacious malloc100 sizeofint dblvec double tenacious malloc100 sizeofdouble pstring char tenacious malloc100 sizeofstring strcpypstring string printfns pstring printfnhit enter to end program getchar return 0,['c'] +614796,why are scopeoriented actions particularly index actions treated differently in pundit i am writing with respect to i am under the impression that authorization should answer the question are you allowed access to this resource ie a truefalse answer this is the case with all actions except index which according to pundit is docs should return different activerecordrelations depending on who is asking for example an admin gets scopeall while a regular user gets scopewherepublished true apoliciespost policyrbclass scope structnewuser scope def resolve if useradmin scopeall else scopewherepublished true end endendappcontrollersposts controllerrbdef index posts policy scopepostendmy reservation is that this is a slippery slope and soon i will be adding presentation to the scopes eg scopeallordercreated at asc and it just feels weird doing so in an authorization policyof course i could move that to the controllerdef index post policy scopepost if useradmin post postorder created at asc endendbut is that the controllers job and i do not think it would be right to add such a call to the view so maybe it should be a model methodwhat would you say are the proscons of doing the following insteadappcontrollersposts controllerrbthis keeps index just like the other methods with one call to authorize and one call to a model methoddef index authorizepost posts postindexcurrent userendapoliciespost policyrbthis simply gives a truefalse answer are you authorized yes or nodef index useradmin userregular userendappmodelspostrband in the model we can get as fancy as we likedef selfindexuser if useradmin postallordercreated at asc else postwhereuser id userid endendthoughts,['ruby-on-rails'] +614827,c correctly overriding virtual function in template class consider following codetemplatetypename tstruct mytempl virtual void dostuffconst t value 0struct myimpl mytemplint void dostuffconst int value struct myptrimpl mytemplint void dostuffconst int value myimpl imp1myptrimpl imp2this will not compile correctly the compiler tells me that dostuff in myptrimpl is pure virtual ie i failed to correctly override it if i however typedef int to something like int ptr and use that as the template argument for myptrimpl everything works outwhy is the compiler unable to deduct my intent without the typedef,['c++'] +614889,merge vs find to update entities jpa from the book pro ejb3 jpathe most common strategy to handle this update entities in java ee application that uses jpa is to place the results of the changes into detached entity instances and merge the pending changes into a persistence context so that they can be written to the databaseexample the emp param is a detached entitystatelesspublic class employeeservicebean persistencecontext emtitymanager em public void updateemployemployee emp ifemfindemployeeclass empgetid null throw new illegalargumentexceptionunknown employee id emmergeemp then saysif the amount of information being udated is very small we can avoid the detached object and merge operation entirely by locating the managed version and manually copying the changes into itexample here the emp is attachedpublic void updateemployeeint id string newname long newsalary employee emp emfindemployeeclass id ifempnull throw new illegalargumentexceptionunknown employee id empsetempnamenewname empsetsalarynewsalaryso looks like for small updates and create operations the strategy find and then set new values one by one is convenient but for big updates of data ie collections is preferred have a detached entity and all it is relations with cascadetypemerge and do a big mergeok but why,['java'] +614893,how to install laravels artisan i want to create migrations in laravel but according to the tutorials i need the artisan cli the php command works fine and i am on windows i type in php artisan or php artisan list and i get the following errorcould not open input file artisani was not able to find any guide in the documentation nor in google how can i install artisan,['php'] +614905,exception to strict aliasing rule in c from 6523 structure and union members quote from c99 standard65235 one special guarantee is made in order to simplify the use of unions if a union contains several structures that share a common initial sequence see below and if the union object currently contains one of these structures it is permitted to inspect the common initial part of any of them anywhere that a declaration of the complete type of the union is visible two structures share a common initial sequence if corresponding members have compatible types and for bitfields the same widths for a sequence of one or more initial membersthere is example for this case the following code is not a valid fragment because the union type is not visible within the function fstruct t1 int m struct t2 int m int fstruct t1 p1 struct t2 p2 if p1m 0 p2m p2m return p1mint g union struct t1 s1 struct t2 s2 u return fus1 us2i have added few changesinclude stdiohstruct t1 int m struct t2 int m union u struct t1 s1 struct t2 s2int foostruct t1 p1 struct t2 p2 if p1m p2m 2 return p1mint mainvoid union you u us1m 1 printfdn foous1 us2as you can see i have moved union declaration outside so it would be visible in foo according to the comment from standard this should have made my code correct but it looks like strict aliasing still breaks this code for clang 34 and gcc 482output with o02output with o21for both compilersso my question isis c really relies on union declaration to decide if some structures are exception to strict aliasing rule or both gclang have a bugit seems really broken to me because even if function and union are both declared in the same header this does not guarantee that the union is visible in translation unit with body of the function,['c'] +615012,how to add imageview on right hand side of action bar i want to add image view on action bar right hand sidei tried to do that but i could notcan anyone help methis is my image view xml imageview androidididimageview4 androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentrighttrue androidlayout alignparenttoptrue androidsrcdrawableadnace search i this is the image of action bar that i want to create,['android'] +615036,how to play custom sound file when user get push notification i have a sound file in the app bundle i want to play that sound file when user will get push notificationis it possible in ios if yes then please suggest the way to achieve thisthanks,"['ios', 'objective-c']" +615176,async for loop in nodejs i am new to this nodejs i am little bit confused about this callbackin my app inside a for loop i am calling a asynchronous function calli think my problem is that before i am getting response of async call my for loop get loopedmy codeasyncforeachobjectkeysconfig functionkey next searchconfigkeyquery functionerr result consolelogf utilinspectresult getting undefined if err return nexterr var json jsonstringify result result resultskey result result consolelogrutilinspectresultskey next critical piece this is how the foreach knows to continue to the next loop must be called inside searchs callback so that it does not loop prematurely functionerr consolelogiterating done reswritehead200 contenttype applicationjson resendjsonstringifyresults search function codevar matches var qrysubstring querysubstring0 4 clientqueryselect from x where level4 ilike query functionerr row1 fields for var id in row1rows var match name if query row1rowsidlevel4 match true name row1rowsidlevel4 else match false name query matchespush id id name row1rowsidlevel4 score 100 match match type id peoplepresidents name us president callbackmatches i want to execute for loop after successful execution of 1 search functioni think i have to use async for loopplease guide me to solve thisthanks in advance,['javascript'] +615179,how to debug when running robolectric tests in android studio i need to run debug while my tests execution in android studio robolectriceach time i try to run them by selecting debug for the test task from gradle tasks i get the error messageerror running package nameapp name test unable to open debugger port javanetsocketexception socket closedany ideas,['android'] +615192,ruby digestdigest is deprecated use digest i have been getting this warning whenever i run my tests or start rails serverwhen i run grep from rvm folder i see the followinggrep r digestdigest rubiesruby210libruby210openssldigestrb warndigestdigest is deprecated use digest additional references to openssl and ruby 210so it looks like it is a ruby 210 bug are there any fixes there are no patches available yet as far as i can tellwhilst my app uses fog and a bunch of other gems that have issues relating to this message i am using patched versions that do not have the bug so i reckon ruby is at fault here,['ruby'] +615320,add to htmlattributes for custom actionlink helper extension i am trying to create a simple custom version of the htmlactionlink htmlhelperi want to append a set of extra attributes to the htmlattributes annonymous object passed inpublic static mvchtmlstring nofollowactionlinkthis htmlhelper htmlhelper string linktext string actionname string controllername object routevalues object htmlattributes var customattributes new routevaluedictionaryhtmlattributes rel nofollow var link htmlhelperactionlinklinktext actionname controllername routevalues customattributes return linkso in my view i would have thishtmlnofollowactionlinklink text myaction mycontrollerwhich i would expect to render out a link likea hrefmycontrollermyaction relnofollowlink textabut instead i geta hrefmycontrollermyaction valuessystemcollectionsgenericdictionary2valuecollectionsystemstringsystemobject keyssystemcollectionsgenericdictionary2keycollectionsystemstringsystemobject count1link textai have tried various methods of converting the annonymous type into a routevaluedictionary adding to it then passing that in to the root actionlink method or converting to dictionary or using htmlhelperanonymousobjecttohtmlattributes and doing the same but nothing seems to work,"['c#', 'asp.net', '.net']" +615364,configuring webrick to use ssl in rails 4 i have a rails app that i want to deploy on sharepoint 2013 in order to achieve some means of authentication i need the webrick server to serve ssl https and listen to incoming https on port httpslocalhost3001 unfortunately i am not very experienced with configuring the serveri have have only found some outdated tutorials for older rails version that do not seem to do the job anymore any tips are greatly appreciated,['ruby-on-rails'] +615368,why new thread instead of future this answer instructs how to convert javautilconcurrentfuture into scalaconcurrentfuture while managing where the blocking will occurimport javautilconcurrentfuture jfutureimport scalaconcurrentfuture sfutureval jfuture jfuturet val promise promisetnew thread new runnable def run promisecompletetry jfutureget startval future promisefuturemy queston is the same as a question asked in the comments whats wrong with future jfutureget why you used an extra thread combined with promiseit was answered as followsit will block thread in your thread pull if you have a configured executioncontext for such futures it is fine but default executioncontext contains as many threads as you have processorsi am not sure i understand the explanation to reiterate whats wrong with future jfutureget is not blocking inside a future the same as manually creating a new thread and blocking there if not how is it different,['java'] +615375,how to set html auto indent format on sublime text 3 i have a question while i am writing html code on sublime text 3 i just want to set auto indent format of html for example when i write p tag like under code the indentation works like thatphello worldpbut i want to write like under code instead of abovep hello worldpand not only p tag also ul ol and etchow can i set auto indent format of html on sublime text 3,['html'] +615387,uncaught referenceerror is not defined error in jquery i have this code in jquery the file name is javascriptjs i was using javascript beforedocumentreadyfunction readfileclickfunction gettesttxt functiondata bottom pane optionshtmldata bottom pane options is the div i want the data to go text and this in htmldoctype htmlhtmlhead titleculminatingtitle link hrefstylecss relstylesheet typetextcss script typetextjavascript srcjavascriptjsscript script srcsensorfalse script script srcscript script function initialize var mapprop centernew googlemapslatlng5056928384378433 zoom5 maptypeidgooglemapsmaptypeidterrain var mapnew googlemapsmapdocumentgetelementbyidgooglemapmapprop googlemapseventadomlistenerwindow load initialize scriptheadbody div classcontent div idgooglemapdiv div idright pane resultshidiv div idbottom pane options button idreadfileread filebutton div divbodywhen i check the console i get the uncaught referenceerror saying that is not defined on the first line i am assuming that it is referring to the first character on the first line i got this code from a website and i am new to jquery so i am not sure what is going wrong here any suggestions,"['javascript', 'jquery', 'html']" +615496,is subprocesspopen not thread safe the following simple script hangs on the subprocesspopen call intermittently roughly 30 of the timeunless use lock true and then it never hangs leading me to believe subprocess is not thread safethe expected behavior is script finishes within 56 secondsto demonstrate the bug just run python bugproofpy a few times until it hangs ctrlc exits youll see the postpopen appear only once or twice but not the third timeimport subprocess threading fcntl os timeend time timetime5lock threadinglockuse lock falsepath to factorial ospathjoinospathdirnameospathrealpath file factorialshdef testfunction print threadingcurrent threadname prepopen if use lock lockacquire p subprocesspopenpath to factorial stdinsubprocesspipe stdoutsubprocesspipe stderrsubprocesspipe if use lock lockrelease print threadingcurrent threadname postpopen fcntlfcntlpstdout fcntlf setfl oso nonblock fcntlfcntlpstderr fcntlf setfl oso nonblock while timetimeend time try pstdoutread except pass try pstderead except pass print threadingcurrent threadname donefor i in range3 threadingthreadtargettestfunctionstartthe shell script referenced above factorialshbinshecho calculating factorial anything that is somewhat compute intensive this script takes 3 sec on my machineans1counter0fact9while fact ne counter do counterexpr counter 1 ansexpr ans counterdoneecho factorial calculation doneread p test input this part is critical for bug to occur bufecho bufsystem infolinux 26323581232openstackel6x86 64 1 smp thu sep 26 171458 edt 2013 x86 64 x86 64 x86 64 gnulinuxpython 273 default jan 22 2013 113430gcc 446 20120305 red hat 4464 on linux2,['python'] +615509,which is faster singlepredicate or wherepredicatesingle thiscussion resulting from this answer has me curious which is fastersomeenumerablesinglepredicateorsomeenumerablewherepredicatesingleafter all the first is shorter more concise and seems to be purposebuilteven resharper suggests the formeri was arguing in the previous post that they are functionally identical and should have very similar runtime,"['c#', '.net']" +615548,does the return value always go into eax register after a method call i have written a hooking library that examines a pe executables dll import table to create a library that enables changing of parameters and return values i have a few questions on how the return value is passed from a functioni have learned that the return value of a function is saved in the accumulator register is this always the case if not how does the compiler know where to look for the function resultwhat about the return type size an integer will easily fit but what about a bigger structure does the caller reserve stack space so the method it calls could write the result onto stack,['c++'] +615578,gll parser combinator or generator infor c or c is there any existing implementation of the gll algorithm either in the form of parser combinators preferred or as a parser generator for c or cmy requirements are that the output is a shared packed parse forest sppf which i can later thisambiguate using semantic andor contextual rules there are other parsing algorithms such as glr which are able to cope with general contextfree grammars however all glr parser generators i could find either return the first successful parse tree or fail if any ambiguity remains at the end,"['c++', 'c']" +615601,c returning error not all code paths return a value i am trying to write code that returns whether or not a given integer is or is not divisible evenly by 1 to 20 but i keep receiving error cs0161 problemfiveistwentyint not all code paths return a valueplease helphere is my code public static bool istwentyint num forint j 1 j 20 j ifnum j 0 return false else ifnum j 0 num 20 return true,['c#'] +615628,css boxshadow shadows for practice and fun i am seeking to recreate the following logo in pure css in one elementif you notice each bar has a small shadowed grey area which gives it a sense of depth i would like to create these in pure css if possible the tricky thing to me is that it looks like they go behind bars on top of them so it would have to be on an individual bar level in order to do that as opposed to applying a mask to the whole thingthus far i have been able to create the bars using a pseudoelement and some box shadows and have given the b the colors using a gradient and backgroundclip text normally i would use a rotated element or mask to apply the shadows but since i created the bars using boxshadows i do not know how i would or even if i can apply them to an individual shadow technically speaking they are all one shadow but i mean apply it to one bar without covering othersheres what i have so farmy codediv classbbdivbody backgroundf8e6b positionabsolute top50 left50 margintop150px lineheight236px fontsize225pt fontweightbold fontfamilycarrois gothic sc sansserif backgroundimagewebkitgradientlinear left top left bottom colorstop9 ffbf7f colorstop9 f4a668 colorstop196 f4a668 colorstop199 f38669 colorstop287 f38669 colorstop29 af9f88 colorstop49 af9f88 colorstop49 cfb698 colorstop70 cfb698 colorstop70 ecd2b1 colortransparent webkitbackgroundclip textbafter content zindex1 positionabsolute left387px height45px width150px borderradius 0px 0px 0px 50px boxshadow 180px 12px 0 9pt ffbf7f 220px 12px 0 9pt ffbf7f 276px 12px 0 9pt ffbf7f 215px 11px 0 8pt f4a668 220px 11px 0 8pt f4a668 275px 11px 0 8pt f4a668 255px 33px 0 8pt f38669 275px 33px 0 8pt f38669 255px 56px 0 9pt 898481 276px 56px 0 9pt 898481 i do not know how to flip these without adding an element 275px 78px 0 8pt a4978e 300px 101px 0 8pt b8a28a 250px 90px 0 0px cabba8 190px 45px 0 0px ccbcac 150px 0 0 0px fccda1now i do not think this is possible but i am always surprised by the ingenuity that so users have tldr how can i create these diagonal shadows without adding more elements i would be open to alternate ways than the method i am using if needededit here is the final result,['css'] +615733,calculate left positioning in div jquery several days ago i asked the following question on webappsstackexchangecom i did not get any good answers so far so i have decided to write my own little script that will change width of the event based on the number of overlapping events i want to avoid overlapping of the boxes and want them to stack heres the initial test below is a basic script with description classtgcoleachfunction each day column mon tue etc has class tgcol or tgcolweekend var itemarray thisfindchipeachfunction each event box has chip class var top thispositiontop get top pixels var bottom thisheight top get end of the event var arr itemarraypush class thisattrclasplit 0 start top endbottom var result getoverlapsitemarray get overlaps counts number of overlapping events eachresult functionindex value var ec resultindexeventcount var w 100resultindexeventcount1 var el resultindexclass elwidthw elcssleftw function getoverlapsevents sort events eventssortfunction a b return astart bstart var results for var i 0 l eventslength i l i var oevent eventsi var noverlaps 0 for var j 0 j l j var ocompareevent eventsj if ocompareeventstart oeventend ocompareeventend oeventstart ocompareeventend oeventstart ocompareeventstart oeventend noverlaps if noverlaps 1 resultspush class oeventclass eventcount noverlaps return resultsthis solution works only on simple events on the leftfor more complex overlapping we cannot simply count numbers of overlaps and diving 100 number of overlaps we have to take into considerations other dimensions also after each manipulation in google calendar it redraws events and script changes are lost is there easier way to solve this problemmaybe it is possible to modify js received from google directly but it is minified,"['jquery', 'html', 'css']" +615885,how do i import a ca certificate into android 442 in the emulator i tried both der and pem formats i tried using the file extensions crt cer p12 pem but nothing of them get imported i went into settings security install from sd card and it takes me to the downloads page i have the certificates listed but when i click on them nothing happensupdated to add i ended up going back to 43 it works fine in that,['android'] +615900,how compute array size during compilation without accepting pointers given an array a i want countofa to yield the number of elements in the array as a compiletime constant if i have a pointer p i want countofp to not compile this seems like it should be 1 straightforward and 2 commonly covered in so but 1 i cannot get it to work and 2 searching so did not turn up anythingheres my attempt include cstddefinclude type traitstemplatetypename t stdsize t n typename typename stdenable ifstdis arraytvaluetypeconstexpr stdsize t countoft n return n templatetypename t typename typename stdenable ifstdis pointertvaluetypevoid countoft deleteint main int a10 auto asize countofa should compile static assertcountofa 10 countofa 10 int p auto psize countofp should not compilehelp,['c++'] +615932,why does xdotxt require so much memory in numpy x is a and x p matrix where p is much larger than n let us say and 10 and p 50 when i runx nprandomrandn1050s xdotxtperforming this operation ends up taking a great deal of memory despite the result being of size 10 x 10 the memory use goes back down once the operation is finished is there any way around this,['python'] +616010,is there an eclosereason for wpf i am a big fan of taking control of every possible situation on the computer when it comes to making apps and now that i am beginning to use favor wpf over winforms for some things i am also beginning to realize that many really cool things are missing in wpf and searching for alternatives seems to be a neverending struggleis there an alternative in wpf to eclosereason for winforms,"['c#', '.net']" +616015,calculate the greatest thistance between any two strings in a group using python my question is how to calculate greatest thistance between any two strings that correspond to a certain group each line in my file starts with a group number followed by a long string i want to know for each group what the greatest thistance between any two strings in a group for each group below is the kind of file i am working with the strings have been shortened notice the groups are not necessarily in order and some of my groups only have one string associated with them so i would want to just skip over them group 3 in the below example 0 gcagacgugaguaacgcgugaacguaccaugcuacggaauaacucagg 0 gcagacgugaguaacgcgugaacguaccaugcuacggaauaacucagg 1 cgaacgugaguaacacgugcaaucugcugcacucugacaagcug 1 cgaacgugaguaacacgugcaaucugcugcacucugacaagcug 1 cgaacgugaguaacacgugcaaucugcugcacucugacaagcug 2 gcuucguacucgaguggcgaacgugaguaacacgugugaucugcc 2 gcuucguacucgaguggcgaacgugaguaacacgugugaucugcc 2 gcuucguacucgaguggcgaacgugaguaacacgugugaucugcc 0 gcagacgugaguaacgcgugaacguaccaugcuacggaauaacucagg 0 gcagacgugaguaacgcgugaacguaccaugcuacggaauaacucagg 3 gcagacgugaguaacaggaacguaccaugcuacggaauaacucaggi want to create something that will create an output that looks something like this group0 0 group1 12 group2 21 average 11this output would be giving me the group number and then the greatest difference for that group and also the overall average of the greatest difference between all groups again skipping over the groups with only one string associated with themmy real file has about 50 groups and the strings i am comparing are 400 characters longi think i could start solving this by looking at this question but i am not sure how to only calculate percent differences for strings in the same group avoid groups with only one string and calculate the overall average percent difference for all the groups any help would be greatly appreciated thank you very much for any ideas edit here are a few truncated lines from the file i am working with the group numbers range from 0 to 60 the string of letters is actually 426 characters long the file format is numbera whitespacestring of lettersend of line character7 uggcgaacgugaguaac35 gugauuaguggcgaac50 acgagauguagcaauac82 ggagagagcuugcucucuu479 ucaggagcuugcuccugu46 cgaggagcuugcuccu24 aacugucuaauaccuu,['python'] +616052,android view shadow i searched around and i could not find a proper way to do this i want to have the following shadow effects on my viewsto be honest i do not know if this second one is done by applying shadow effect any ideas,['android'] +616057,mingw error athreada is not a member of astda i am trying to crosscompile for windows a simple applicationinclude threadvoid func returnint main stdthread thr1func thr1detach return 0and that is what i get i686w64mingw32g staticlibstdc staticlibgcc pipe g stdc0x threadstutorcpp threadstutorcpp in function aint mainathreadstutorcpp83 error athreada is not a member of astdathreadstutorcpp815 error expected aa before athr1athreadstutorcpp93 error athr1a was not declared in this scopeactually this code have no such problem if compile with g for ubuntu but i need to crosscompile for windows and here i am stuck,['c++'] +616069,how to set default sms prompt for kitkat i have created an sms application that shows all the messages properly and also a broadcastreceiver that helps in letting me know new messages on arrivalusing the uris help contentmmssmsconversationssimpletrue i am able to retrieve the messagesthis is working fine even on kitkat i can send sms read sms but i am not able to delete the sms because my app is not the default sms app questionhow do i prompt user to make the app default i looked at this blogi tried the code given on it but i do not see any difference am i missing anything herehere is the code int currentapiversion androidosbuildversionsdk int if currentapiversion 19 final string mypackagename getpackagename if telephonysmsgetdefaultsmspackagethisequalsmypackagename app is not default show the not currently set as the default sms app interface view viewgroup findviewbyidridnot default app viewgroupsetvisibilityviewvisible set up a button that allows the user to change the default sms app buttonsetonclicklistenernew viewonclicklistener public void onclickview v intent intent new intenttelephonysmsintentsaction change default intentputextratelephonysmsintentsextra package name mypackagename startactivityintent else app is the default hide the not currently set as the default sms app interface view viewgroup findviewbyidridnot default app viewgroupsetvisibilityviewgone awaiting your responsethanks,['android'] +616124,flask run function every hour i have a flask web hosting with no access to cron commandhow can i execute some python function every hour,['python'] +616236,factor loadings using sklearn i want the correlations between individual variables and principal components in pythoni am using pca in sklearn i do not understand how can i achieve the loading matrix after i have decomposed my data my code is hereiris load irisdata y irisdata iristargetpca pcan components2transformed data pcafitdatatransformdataeigenvalues pcaexplained variance ratio does not mention how this can be achieved,['python'] +616267,profiler does not show my code i am using profiler in visual studio 2012 to find bottlenecks in my code but i found that after moving project to another computer profiler does not show my code at all but only modules namesthere is trineaclient which is my projects module but it does not show its functions as profiler wouldnt have knowledge about them but so far i did not have problems with thisi understand it may not find symbols for some system modules or libraries that i am using but so far it always handled my own codewhat may be the reason for this behaviour,['c++'] +616278,placeholder in search bar on samsung galaxy thisplays on wrong side i am using this web editor examplewhich enables you to see the input tag styledtextalign righton iphones and nexus the placeholder is thisplayed correctly on the right side but on all samsung galaxy devices it is on the left sidesomebody know the reason or how to solve this,"['html', 'css']" +616291,how do i get the modern style matplotlib plots often seen in ipython notebook examples take this page for example a sample of which is posted belowit has matplotlib examples with gray background and more subtle coloring but when i am running the same examples i get the more traditionally colored plots with white background and strong colors this also seems to be the style used in the pandas documentationhow can i change the default style locally to match their style,['python'] +616294,the smtp host was not specified but it is specified i am slightly baffled here i am receiving the following error the smtp host was not specifiedeven though my code appears to be correct from what i can see i am able to do it manually by including all the details inside of the controller egsmtpclient smtpclient new smtpclientsmtpgmailcomsmtpclientport 587 etcbut i should not have to do this as i want to use the details inside mailsettings making it reusable for various different controllersmailsettings in my webconfig filesystemnet mailsettings smtp from deliverymethodnetwork network hostsmtpgmailcom defaultcredentialstrue port587 enablessltrue username passwordexample smtp mailsettingssystemnetmy controller action httppost public actionresult submitfeatureformdata formdata smtpclient smtpclient new smtpclient mailmessage mail new mailmessage mailtoaddnew mailaddress mailbody test smtpclientsendmail return viewexample is there anything i am missing which may be causing this i have not messed around with any other settings in webconfig they are as is when setting up a new mvc5 project,"['c#', '.net']" +616343,cannot connect to mysql server on ip or domain name i am trying to configure a web server debian 7 i followed this tutoriali am renting my server thanks to gandinet service and i have now apache2 mysql php5 up and runningi connect to it using following command on terminal ssh next step is to create my database through sequel pro and i do not know how to do it and documentation is not so clearhere is what i am talking about i have tried to connect nom some name i found clear i think i can put anything in here right host ip or domain nameuser the username i am using in my ssh connection cf abovepassword the password i both use for ssh connection cf above and mysql connectionfor the rest i left like it was and i received this error message unable to connect to host domainnamecom or the request timed out be sure that the address is correct and that you have the necessary privileges or try increasing the connection timeout currently 10 seconds mysql said cannot connect to mysql server on domainenamecom 61 2 any idea how i could do that thank you,['mysql'] +616478,rails using rails generate model to specify nonnullable field type according to the rails documentation23 supported type modifiers says it should be possible to modify fields to allow or thisallow null in the column and that it is possible to do this on the terminalthis is what i want to appear in the migration fileclass createtestmodels activerecordmigration def change create table test models do t tstringnon nullable null false ttimestamps end endendon the terminal i have triedrails generate model testmodel non nullablestringnullrails generate model testmodel non nullablestringnull falsei cannot think of any other way to express itnote i already know you can go into the migration file and manually add it that is not what i am looking for,"['ruby-on-rails', 'ruby']" +616527,cowaitformultiplehandles api does not behave as documented this was triggered by another question i was looking at it might be too long to read so please bear with meapparently cowaitformultiplehandles does not behave as documented on msdnthe code below based upon the original question is a console app which starts an sta thread with a test win32 window and tries post and to pump some messages it does three different tests on cowaitformultiplehandles all without cowait waitall flag test 1 is aimed to verify thiscowait inputavailable if set the call to cowaitformultiplehandles will return s ok if input exists for the queue even if the input has been seen but not removed using a call to another function such as peekmessagethis is not happening cowaitformultiplehandles blocks and does not return until the wait handle is signalled i do assume that any pending message should be treated as input same as with mwmo inputavailable of msgwaitformultipleobjectsex which works as expectedtest 2 is aimed to verify thiscowait thispatch window messages enables thispatch of window messages from cowaitformultiplehandles in an asta or sta default in asta is no window messages thispatched default in sta is only a small set of specialcased messages thispatched the value has no meaning in mta and is ignoredthis does not work either when cowaitformultiplehandles is called with cowait thispatch window messages flag alone it instantly returns error co e not supported 0x804021 if it is a combination of cowait thispatch window messages cowait thispatch calls the call blocks but does not pump any messagestest 3 demonstrates the only way i could make cowaitformultiplehandles pump the windows message queue of the calling thread it is a combination of cowait thispatch window messages cowait thispatch calls cowait inputavailable this does pump and thispatch messages although apparently it is an undocumented behaviourthe test code a readytorun console appusing systemusing systemruntimeinteropservicesusing systemthreadingusing systemthreadingtasksnamespace consoletestapp static class program main static void mainstring args consolewritelinestarting an sta thread runstathread consolewritelinensta thread finished consolewritelinepress enter to exit consolereadline start and run an sta thread static void runstathread var thread new thread create a simple win32 window intptr hwnd createtestwindow post some wm test messages consolewritelinepost some wm test messages nativemethodspostmessagehwnd nativemethodswm test new intptr1 intptrzero nativemethodspostmessagehwnd nativemethodswm test new intptr2 intptrzero nativemethodspostmessagehwnd nativemethodswm test new intptr3 intptrzero test 1 consolewritelinentest 1 cowaitformultiplehandles with cowait inputavailable only press enter to stop var task readlineasync uint index var result nativemethodscowaitformultiplehandles nativemethodscowait inputavailable nativemethodsinfinite 1 new taskasunmanagedhandle out index consolewritelineresult result pending messages in the queue nativemethodsgetqueuestatus0x1ff 16 0 test 2 consolewritelinentest 2 cowaitformultiplehandles with cowait thispatch window messages cowait thispatch calls press enter to stop task readlineasync result nativemethodscowaitformultiplehandles nativemethodscowait thispatch window messages nativemethodscowait thispatch calls nativemethodsinfinite 1 new taskasunmanagedhandle out index consolewritelineresult result pending messages in the queue nativemethodsgetqueuestatus0x1ff 16 0 test 3 consolewritelinentest 3 cowaitformultiplehandles with cowait thispatch window messages cowait thispatch calls cowait inputavailable press enter to stop task readlineasync result nativemethodscowaitformultiplehandles nativemethodscowait thispatch window messages nativemethodscowait thispatch calls nativemethodscowait inputavailable nativemethodsinfinite 1 new taskasunmanagedhandle out index consolewritelineresult result pending messages in the queue nativemethodsgetqueuestatus0x1ff 16 0 threadsetapartmentstateapartmentstatesta threadstart threadjoin helpers create a window to handle messages static intptr createtestwindow create a simple win32 window var hwndstatic nativemethodscreatewindowex0 static stringempty nativemethodsws popup 0 0 0 0 nativemethodshwnd message intptrzero intptrzero intptrzero subclass it with a custom wndproc intptr prevwndproc intptrzero nativemethodswndproc newwndproc hwnd msg wparam lparam if msg nativemethodswm test consolewritelinewm test processed wparam return nativemethodscallwindowprocprevwndproc hwnd msg wparam lparam prevwndproc nativemethodssetwindowlonghwndstatic nativemethodsgwl wndproc marshalgetfunctionpointerfordelegatenewwndproc if prevwndproc intptrzero throw new applicationexception return hwndstatic call consolereadline on a pool thread static taskstring readlineasync return taskrun consolereadline get win32 waitable handle of task object static intptr asunmanagedhandlethis task task return iasyncresulttaskasyncwaithandlesafewaithandledangerousgethandle interop static class nativemethods dllimportuser32 public static extern intptr setwindowlongintptr hwnd int nindex intptr dwnewlong dllimportuser32 public static extern intptr callwindowprocintptr lpprevwndfunc intptr hwnd uint msg intptr wparam intptr lparam dllimportuser32dll public static extern intptr createwindowex uint dwexstyle string lpclassname string lpwindowname uint dwstyle int x int y int nwidth int nheight intptr hwndparent intptr hmenu intptr hinstance intptr lpparam dllimportuser32dll public static extern bool postmessageintptr hwnd uint msg intptr wparam intptr lparam dllimportuser32dll public static extern int messageboxintptr hwnd string text string caption int options dllimportole32dll setlasterror true public static extern uint cowaitformultiplehandlesuint dwflags uint dwtimeout int chandles intptr phandles out uint lpdwindex dllimportuser32dll public static extern uint getqueuestatusuint flags unmanagedfunctionpointercallingconventionstdcall public delegate intptr wndprocintptr hwnd uint msg intptr wparam intptr lparam public static intptr hwnd message new intptr3 public const int gwl wndproc 4 public const uint ws popup 0x80 public const uint wm user 0x0400 public const uint wm test wm user 1 public const uint cowait waitall 1 public const uint cowait alertable 2 public const uint cowait inputavailable 4 public const uint cowait thispatch calls 8 public const uint cowait thispatch window messages 0x10 public const uint rpc s callpending 0x80010115 public const uint wait timeout 0x0102 public const uint wait failed 0xf public const uint wait object 0 0 public const uint wait abandoned 0 0x080 public const uint wait io completion 0x0c0 public const uint infinite 0xf the outputstarting an sta threadpost some wm test messagestest 1 cowaitformultiplehandles with cowait inputavailable only press enter to stopresult 0 pending messages in the queue truetest 2 cowaitformultiplehandles with cowait thispatch window messages cowait thispatch calls press enter to stopresult 0 pending messages in the queue truetest 3 cowaitformultiplehandles with cowait thispatch window messages cowait thispatch calls cowait inputavailable press enter to stopwm test processed 1wm test processed 2wm test processed 3result 0 pending messages in the queue falsesta thread finishedpress enter to exitall tests are done under windows 81 pro 64bit net v451am i misreading the docs or missing something else should i report this as a bug at least a bug in the docs should cowaitformultiplehandles be avoided and replaced with a solution based on msgwaitformultipleobjectsex which behaves in accordance with the docsupdate under windows 7 neither cowait thispatch window messages nor cowait thispatch calls are supported cowaitformultiplehandles fails with e invalidarg 0x80070057 when called with zero as flags it blocks without pumping,"['c#', '.net']" +616528,numpy quirk apply function to all pairs of two 1d arrays to get one 2d array let us say i have 2 onedimensional 1d numpy arrays a and b with lengths n1 and n2 respectively i also have a function fxy that takes two values now i want to apply that function to each pair of values from my two 1d arrays so the result would be a 2d numpy array with shape n1 n2 the i j element of the twodimensional array would be fai bji have not been able to find a way of doing this without a horrible amount of forloops and i am sure there is a much simpler and faster way of doing this in numpythanks in advance,['python'] +616590,javascript bootstrap modal cancel closing my work is using javascript bootstrap 204i am looking for a way to cancel the modal from closing by logic controlbut i cannot find any details how to do thissomething like net onwindowclosingeventarguement if shouldcancel eventarguementcancel true return,"['javascript', 'jquery']" +616591,how to update the pnr capcha added in the indian railways site i have a pnr inquiry app on google play it was working very fine but recently indian railwys added captcha to their pnr inquiry section and because of this i am not able to pass proper data to the server to get proper response how to add this captcha in my app in form of an imageview and ask the users to enter captcha details also so that i can send proper data and get proper responseindian railways pnr inquiry linkhere is my pnrcheckjava which i was using earlier please help what modifications should be done hereimport javaiobufferedreaderimport javaiobytearrayinputstreamimport javaioioexceptionimport javaioinputstreamimport javaioinputstreamreaderimport javanetsocketimport javaneturlimport javautilarraylistimport javautillistimport orgapachehttpheaderimport orgapachehttphttphostimport orgapachehttphttpresponseimport orgapachehttphttpversionimport orgapachehttpentityinputstreamentityimport orgapachehttpimpldefaulthttpclientconnectionimport orgapachehttpmessagebasichttpentityenclosingrequestimport orgapachehttpparamsbasichttpparamsimport orgapachehttpparamshttpparamsimport orgapachehttpparamshttpprotocolparamsimport orgapachehttpprotocolbasichttpcontextimport orgapachehttpprotocolbasichttpprocessorimport orgapachehttpprotocolexecutioncontextimport orgapachehttpprotocolhttpcontextimport orgapachehttpprotocolhttprequestexecutorimport orgapachehttpprotocolrequestconncontrolimport orgapachehttpprotocolrequestcontentimport orgapachehttpprotocolrequestexpectcontinueimport orgapachehttpprotocolrequesttargethostimport orgapachehttpprotocolrequestuseragentimport orgapachehttputilentityutilspublic class pnrstatuscheck public static void mainstring args try string pnr1 1154177041 string reqstr lccp pnrno1 pnr1 submitpnrgetstatus pnrstatuscheck check new pnrstatuscheck stringbuffer data checkgetpnrresponsereqstr bininet pnrstat cgicgi ifdata null suppresswarningsunused pnrstatus pnr checkparsehtmldata catchexception e eprintstacktrace public stringbuffer getpnrresponsestring reqstr string urladdr throws exception string urlhost null int port string method null try url url new urlurladdr urlhost urlgethost port urlgetport method urlgetfile validate port ifport 1 port urlgetdefaultport catchexception e eprintstacktrace throw new exceptione httpparams params new basichttpparams httpprotocolparamssetversionparams httpversionhttp 1 1 httpprotocolparamssetcontentcharsetparams utf8 httpprotocolparamssetuseragentparams httpcomponents11 httpprotocolparamssetuseexpectcontinueparams true basichttpprocessor httpproc new basichttpprocessor required protocol interceptors httpprocaddinterceptornew requestcontent httpprocaddinterceptornew requesttargethost recommended protocol interceptors httpprocaddinterceptornew requestconncontrol httpprocaddinterceptornew requestuseragent httpprocaddinterceptornew requestexpectcontinue httprequestexecutor httpexecutor new httprequestexecutor httpcontext context new basichttpcontextnull httphost host new httphosturlhost port defaulthttpclientconnection conn new defaulthttpclientconnection contextsetattributeexecutioncontexthttp connection conn contextsetattributeexecutioncontexthttp target host host suppresswarningsunused string resdata null suppresswarningsunused string statusstr null stringbuffer buff new stringbuffer try string req method method string targets req method for int i 0 i targetslength i if connisopen socket socket new sockethostgethostname hostgetport connbindsocket params basichttpentityenclosingrequest req new basichttpentityenclosingrequestpost targetsi reqsetentitynew inputstreamentitynew bytearrayinputstreamreqstrtostringgetbytes reqstrlength reqsetheadercontenttype applicationxwformurlencoded reqsetheaderuseragent mozilla50 windows nt 51 applewebkit5357 khtml like gecko chrome16091275 safari5357 reqsetheadercachecontrol maxage0 reqsetheaderconnection keepalive reqsetheaderorigin reqsetheaderaccept texthtmlapplicationxhtmlxmlapplicationxmlq09q08 reqsetheaderreferer enqhtml reqsetheaderacceptencoding gzipdeflatesdch reqsetheaderacceptlanguage enusenq08 reqsetheaderacceptcharset iso88591utf8q07q03 httpexecutorpreprocessreq httpproc context httpresponse response httpexecutorexecutereq conn context responsesetparamsparams httpexecutorpostprocessresponse httpproc context header headers responsegetallheaders forint j0 jheaderslength j ifheadersjgetnameequalsignorecaseerror msg resdata entityutilstostringresponsegetentity statusstr responsegetstatuslinetostring inputstream in responsegetentitygetcontent bufferedreader reader null ifin null reader new bufferedreadernew inputstreamreaderin string line null whileline readerreadline null buffappendline n try inclose catch exception e catch exception e throw new exceptione finally try connclose catch ioexception e eprintstacktrace return buff public pnrstatus parsehtmlstringbuffer data throws exception bufferedreader reader null ifdata null reader new bufferedreadernew inputstreamreadernew bytearrayinputstreamdatatostringgetbytes else return null string line null traindetails traindetails new traindetails listpassengerdetails passdetailslist new arraylistpassengerdetails passengerdetails passdetails null int i 0 while line readerreadline null iflinestartswithtd linecontainstable border both line linereplaceb line linesubstringlineindexof2 lineindexoftrim iflinecontainschart traindetailssetchatstatusline break ifi 7 passenger details ifpassdetails null passdetails new passengerdetails switchi case 8 passdetailssetnameline break case 9 passdetailssetbookingstatuslinereplace break case 10 passdetailssetcurrentstatuslinereplace i 7 break ifi 7 passdetailslistaddpassdetails passdetails null else train details switchi case 0 traindetailssetnumberline break case 1 traindetailssetnameline break case 2 traindetailssetboardingdateline break case 3 traindetailssetfromline break case 4 traindetailssettoline break case 5 traindetailssetreserveduptoline break case 6 traindetailssetboardingpointline break case 7 traindetailssetreservedtypeline break default break i iftraindetailsgetnumber null pnrstatus pnrstatus new pnrstatus pnrstatussettraindetailstraindetails pnrstatussetpassengerdetailspassdetailslist return pnrstatus else return null,"['java', 'android']" +616631,select all parents or children in same table relation sql server sql developers i have a badly planned database as task to learn a lot about sql server 2012so there is the table elemversionpknamekeyparent keythist keyfk1 a 12 null 1 2 b 13 12 1 3 c 14 13 1 4 d 15 12 1 5 e 16 null 1 6 e 17 null 2 after update the row i need to check parent key of element to not allow element to be selfgranny or something and when i delete the row i need to delete all children and children of children etcquestions arehow can i select all parent grandparent etc of one element of thisthow can i selects all sons grandsons etc of one element of thisti read about solutions with cte but i have no root of elements and i cannot even understand how i can use cte then please helpthanks,['sql'] +616635,what is the correct argument type for a functionobject i have a templated function that receives functionobjects sometimes the functionobjects are stateless structs but sometimes they are large statefull objects the state of the functionobject is not changed in this function only examined i am also very keen on writing code that the compiler can optimize as much as possible what should i consider when choosing the argument typethe function is of this typetemplatetypename functauto make particlefunct fun particletypename functresult type particle particle fun return particlethe argument type should probably be funct const fun so that the large objects are not copied but why do most people use callbyvalue function objects do i loose something by using const reference or should i use lvaluereference please note that c1y is ok and that the code example above is just an example,['c++'] +616643,passing a methods name as a parameter private void method1 do something logsomethingmethod1private void method2 do something logsomethingmethod2private void logstring message string method write to a log file tracetraceinformationmessage happened at methodi have several methods like method1 and method2 above and i would like some way pass the methods name as a parameter without manually editing the codeis that possible,['c#'] +616659,4 columns in desktop 2 in tablet and 1 in mobile using bootstrap its very interesting and helpful to use bootstrap currently i am facing problem during creating following requirement4 columns in desktop 2 columns in tablet and 1 column in mobile using bootstrapcan anybody tell me the correct structure,['css'] +616668,paypal express checkout always shows user this transaction has expired page but no api error i am trying to set up a simple payment sequence with paypals express checkout my setexpresscheckout call seems to work fine i get acksuccess and a token when i redirect the user to paypal using that token though it always thisplays a screen to them sayingthis transaction has expired please return to the recipients website to complete your transaction using their regular checkout flowyour session has endedwere sorry but your session has ended your account has not been charged please go back to the merchants site and check out again with paypaljust to clarify i do not get any error codes from the setexpresscheckout api call but the token always seems to be expired i have tried redirecting to nonsense tokens but that generates a different page it seems that i am both receiving a valid token and redirecting to it correctly but it has always expired in the 12 seconds that that takesdetails of an example requestwhat i am sending in the initial setexpresscheckout requestarray paymentaction sale useraction commit returnurl x cancelurl x paymentrequest 0 amt 4900 paymentrequest 0 shippingamt 0 paymentrequest 0 currencycode usd paymentrequest 0 itemamt 4900 l paymentrequest 0 name0 x l paymentrequest 0 desc0 x l paymentrequest 0 number0 x l paymentrequest 0 amt0 49 l paymentrequest 0 qty0 1 method setexpresscheckout version 740 user x pwd x signature xcurl getinfo about the requestarray url content type textplain charsetutf8 http code 200 header size 255 request size 798 filetime 1 ssl verify result 0 redirect count 0 total time 1139 namelookup time 0 connect time 0187 pretransfer time 064 size upload 660 size download 136 speed download 119 speed upload 579 download content length 136 upload content length 660 starttransfer time 1139 redirect time 0 certinfo array primary ip 2345942 primary port 443 local ip 1921680102 local port 63049 redirect url what i get back from paypal via curlarray token ec59031295261754641 timestamp 20140120t101227z correlationid 84d3d68cbd574 ack success version 740 build 9285531i am then redirecting the user to the relevant url for that token with the token urlencoded in this case expresscheckoutuseractioncommittokenec59031295261754641that all seems fine to me but when i redirect to that url it always shows the transaction has expired screencould anyone point out what i am doing wrong,['php'] +616681,how to print html string as html if just for example i dovar aasdaspan var spanthe string is printed like text and not as html so how do i print the html,"['javascript', 'html']" +616705,thisabling cast from pointer to smaller type uint32 t error in clang i am working on a school project that involves porting a large piece of c code on an experimental piece of hardware unfortunately that hardware is 64bit and the code contains many instances of pointer arithmetic that expects pointers to be 32bit ie it often does reinterpret castuint32 tptrgoing through them one by one would be very tedious and since this is an experimental project anyway i am happy to settle for a hackish workaround so instead i modified the implementation of malloc to ensure it never allocates memory above the 4gb limit technically these casts should therefore be valid question is how do i explain this to clang the error i am getting is error cast from pointer to smaller type uint32 t aka unsigned int loses information is there a way to thisable itthanksdavid,['c++'] +616737,mvc 5 should i inherit my user from identityuser class i was trying to learn aspnet identity andin this tutorialcreate an entity framework code first todo model in modelsappmodelscs part myuser class inherits from identityuser class and mydbcontext inherits from identitydbcontextmyuser class why is that lets say i have a user class that holds all the information of the user of my web application should that class inherit from identityuser and should my dbcontext inherit from identitydbcontextuseralso what are the advantages of inheritng dbcontext class from identitydbcontexttclass over plain dbcontext class as done in mvc 4,['c#'] +616765,object creation order in braced init list include iostreamstruct a a stdcout aa struct b b stdcout bb struct c templatetypename args cargs int mainint agrc char argv c a b prints bbaa stdcout stdendl c a b prints aabb stdcout stdendl return 0i have got 2 questionswhy in first braced init list objects are created in righttoleft order why parentheses in second case revert this orderedit i have compiled it with msvs 2013,['c++'] +616766,bootstrap 3 responsive images side by side same height is it possible to use 2 responsive images side by side with same height with bootstrap 3 at the moment the colsm4 has not the same heightdiv classcontainer div classrow div classcolsm4 img classimgresponsive src div div classcolsm8 img classimgresponsive src div divdivdemo fiddle thanks,"['css', 'html']" +616917,how to test gcroot reference for null or nullptr in a ccli project i have a method in a native c class where i would like to check a gcroot reference for null or nullptr how do i do this none of the following seems to workvoid foodoitgcrootsystemstring astring this seems straightforward but does not work if astring nullptr compiler error c2088 illegal for struct worth a try but does not work either if astring null compiler error c2678 binary no operator found which takes a lefthand operand of type gcroott or there is no acceptable conversion desperate but same result as above if astring gcrootsystemstringnullptr compiler error c2678 binary no operator found which takes a lefthand operand of type gcroott or there is no acceptable conversion editthe above is just a simplified example i am actually working on a wrapper library that translates between managed and native code the class i am working on is a native c class that wraps a managed object in the constructor of the native c class i get a gcroot reference which i want to check for null,['c++'] +616955,what should be in my view models i have business models named product and category like below in which i add the validationspublic class product public int productid get set required stringlength25 public string name get set public string description get set public int categoryid get setpublic class category public int categoryid get set public string name get setfor the view model i have created something like thispublic class productviewmodel public product product get set public ilistcategory categories get seta friend of mine suggested keeping all the validations in the view model and mapping all the properties of the business model in the view model like thispublic class productviewmodel public int productid get set required stringlength25 public string name get set public string description get set public int categoryid get set public ilistselectlistitem categorydropdownvalues get seti asked him the advantages of this approach to the above one he was not very sure but he insisted that you should not use the business models directly in your views and that only view models should be validatedmy questions should i keep my validation logic in view models or business modelsis it bad to have view models depend on business models,['c#'] +616970,django noreversematch i am making a simple login app in django 16 and python 27 and i get an error at the beggining that is not letting me continuethis is the sites urlpyfrom djangoconfurls import patterns include urlfrom djangocontrib import adminimport loginadminautothiscoverurlpatterns patterns urlr includeloginurls namespacelogin urlradmin includeadminsiteurlsand this is loginurlspyfrom djangoconfurls import patterns urlfrom login import viewsurlpatterns patterns urlr viewsindex nameindex urlrauth viewsauth nameauththis is loginviewspyfrom djangoshortcuts import renderfrom djangocontribauth import authenticatedef authrequest user authenticateusernamerequestpostusername passwordrequestpostpassword if user is not none the password verified for the user if useris active msg user is valid active and authenticated else msg the password is valid but the account has been thisabled else the authentication system was unable to verify the username and password msg the username and password were incorrect return renderrequest loginauthenticatehtml message msgdef indexrequest return renderrequest loginlogin formhtmli have a form that has this as action url loginauth and that is where the problem is when i try to load the page i getreverse for auth with arguments and keyword arguments not found 1 patterns tried uauthbut if i set the url pattern tourlr viewsauth nameauthit works fine only it sets the action as i have been looking all around for an answer and i do not understand why it does not worki tried changing the login url pattern to urlrlogin includeloginurls namespacelogin and it did not change anything,['python'] +616985,compatability of spring 400 with hibernate 430 i am using spring 400 release jars hibernatecoe 430 jar in my spring hibernate projecti am facing an error with orghibernateenginefilterdefinition is not found actually in old hibernate core jars we are having this class but not in 430 version in fact we are having orghibernateenginespifilterdefinition in 430 versionbut i am not sure how this class is dependent in run time mean while i am using glassfish server to my applicationplease let me know the compatability of spring 400 and hibernate 430 versions and suggest me the latest compatable versions of these twomy code is thispatcherservlet is havingbean idhibernatetransactionmanager classorgspringframeworkormhibernate4hibernatetransactionmanager property namesessionfactory refsessionfactory beanbean idsessionfactory classorgspringframeworkormhibernate3annotationannotationsessionfactorybean property namedatasource refdatasource property nameannotatedclasses list valuecomvenkathomeappentitycustomerentityvalue list property property namehibernateproperties props prop keyhibernatedialecthibernatedialectprop prop keyhibernateshow sqlhibernateshow sqlprop props propertybeanbean iddatasource classorgspringframeworkjdbcdatasourcedrivermanagerdatasource property namedriverclassname valuedatabasedriver property nameurl valuedatabaseurl property nameusername valuedatabaseuser property namepassword valuedatabasepassword beanmy controller class iscontrollerrequestmappingcomponentscancomvenkathomeappservicepublic class homeappcontroller autowiredprivate customerservice customerservicethe log which i can see isinfo webmodulenull servletcontextlogno spring webapplicationinitializer types detected on classpathinfo webmodulenull servletcontextloginitializing spring frameworkservlet homeappinfo frameworkservlet homeapp initialization startedinfo refreshing webapplicationcontext for namespace homeappservlet startup date mon jan 20 234245 ist 2014 root of context hierarchyinfo loading xml bean definitions from servletcontext resource webinfhomeappservletxmlinfo loading properties file from class path resource jdbcpropertiesinfo jsr330 javaxinjectinject annotation found and supported for autowiringsevere context initialization failedorgspringframeworkbeansfactorybeancreationexception error creating bean with name homeappcontroller injection of autowired dependencies failed nested exception is orgspringframeworkbeansfactorybeancreationexception could not autowire field private comvenkathomeappservicecustomerservice comvenkathomeappcontrollerhomeappcontrollercustomerservice nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name customerservice injection of autowired dependencies failed nested exception is orgspringframeworkbeansfactorybeancreationexception could not autowire field private comvenkathomeappdaocustomerdao comvenkathomeappserviceimplcustomerserviceimplcustomerdao nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name customerdao injection of autowired dependencies failed nested exception is orgspringframeworkbeansfactorybeancreationexception could not autowire field private orghibernatesessionfactory comvenkathomeappdaoimplcustomerdaoimplsessionfactory nested exception is javalangnoclassdeffounderror lorghibernateenginefilterdefinition at orgspringframeworkbeansfactoryannotationautowiredannotationbeanpostprocessorpostprocesspropertyvaluesautowiredannotationbeanpostprocessorjava292 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorypopulatebeanabstractautowirecapablebeanfactoryjava1185 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorydocreatebeanabstractautowirecapablebeanfactoryjava537 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorycreatebeanabstractautowirecapablebeanfactoryjava475 at orgspringframeworkbeansfactorysupportabstractbeanfactory1getobjectabstractbeanfactoryjava304 at orgspringframeworkbeansfactorysupportdefaultsingletonbeanregistrygetsingletondefaultsingletonbeanregistryjava228 at orgspringframeworkbeansfactorysupportabstractbeanfactorydogetbeanabstractbeanfactoryjava300 at orgspringframeworkbeansfactorysupportabstractbeanfactorygetbeanabstractbeanfactoryjava195 at orgspringframeworkbeansfactorysupportdefaultlistablebeanfactorypreinstantiatesingletonsdefaultlistablebeanfactoryjava700 at orgspringframeworkcontextsupportabstractapplicationcontextfinishbeanfactoryinitializationabstractapplicationcontextjava760 at orgspringframeworkcontextsupportabstractapplicationcontextrefreshabstractapplicationcontextjava482 at orgspringframeworkwebservletframeworkservletconfigureandrefreshwebapplicationcontextframeworkservletjava643 at orgspringframeworkwebservletframeworkservletcreatewebapplicationcontextframeworkservletjava606 at orgspringframeworkwebservletframeworkservletcreatewebapplicationcontextframeworkservletjava657 at orgspringframeworkwebservletframeworkservletinitwebapplicationcontextframeworkservletjava525 at orgspringframeworkwebservletframeworkservletinitservletbeanframeworkservletjava466 at orgspringframeworkwebservlethttpservletbeaninithttpservletbeanjava136 at javaxservletgenericservletinitgenericservletjava244 at orgapachecatalinacorestandardwrapperinitservletstandardwrapperjava1583 at orgapachecatalinacorestandardwrapperloadstandardwrapperjava1382 at orgapachecatalinacorestandardcontextloadonstartupstandardcontextjava5670 at orgapachecatalinacorestandardcontextstartstandardcontextjava5912 at comsunenterprisewebwebmodulestartwebmodulejava691 at orgapachecatalinacorecontainerbaseaddchildinternalcontainerbasejava1041 at orgapachecatalinacorecontainerbaseaddchildcontainerbasejava1024 at orgapachecatalinacorestandardhostaddchildstandardhostjava747 at comsunenterprisewebwebcontainerloadwebmodulewebcontainerjava2278 at comsunenterprisewebwebcontainerloadwebmodulewebcontainerjava1924 at comsunenterprisewebwebapplicationstartwebapplicationjava139 at orgglassfishinternaldataenginerefstartenginerefjava122 at orgglassfishinternaldatamoduleinfostartmoduleinfojava291 at orgglassfishinternaldataapplicationinfostartapplicationinfojava352 at comsunenterprisev3serverapplicationlifecycledeployapplicationlifecyclejava497 at comsunenterprisev3serverapplicationlifecycledeployapplicationlifecyclejava219 at orgglassfishdeploymentadmindeploycommandexecutedeploycommandjava491 at comsunenterprisev3admincommandrunnerimpl21runcommandrunnerimpljava527 at comsunenterprisev3admincommandrunnerimpl21runcommandrunnerimpljava523 at javasecurityaccesscontrollerdoprivilegednative method at javaxsecurityauthsubjectdoassubjectjava356 at comsunenterprisev3admincommandrunnerimpl2executecommandrunnerimpljava522 at comsunenterprisev3admincommandrunnerimpldocommandcommandrunnerimpljava546 at comsunenterprisev3admincommandrunnerimpldocommandcommandrunnerimpljava1423 at comsunenterprisev3admincommandrunnerimplaccess1500commandrunnerimpljava108 at comsunenterprisev3admincommandrunnerimplexecutioncontextexecutecommandrunnerimpljava1762 at comsunenterprisev3admincommandrunnerimplexecutioncontextexecutecommandrunnerimpljava1674 at comsunenterprisev3adminadminadapterdocommandadminadapterjava534 at comsunenterprisev3adminadminadapteronmissingresourceadminadapterjava224 at orgglassfishgrizzlyhttpserverstatichttphandlerservicestatichttphandlerjava297 at comsunenterprisev3servicesimplcontainermapperservicecontainermapperjava246 at orgglassfishgrizzlyhttpserverhttphandlerrunservicehttphandlerjava191 at orgglassfishgrizzlyhttpserverhttphandlerdohandlehttphandlerjava168 at orgglassfishgrizzlyhttpserverhttpserverfilterhandlereadhttpserverfilterjava189 at orgglassfishgrizzlyfilterchainexecutorresolver9executeexecutorresolverjava119 at orgglassfishgrizzlyfilterchaindefaultfilterchainexecutefilterdefaultfilterchainjava288 at orgglassfishgrizzlyfilterchaindefaultfilterchainexecutechainpartdefaultfilterchainjava206 at orgglassfishgrizzlyfilterchaindefaultfilterchainexecutedefaultfilterchainjava136 at orgglassfishgrizzlyfilterchaindefaultfilterchainprocessdefaultfilterchainjava114 at orgglassfishgrizzlyprocessorexecutorexecuteprocessorexecutorjava77 at orgglassfishgrizzlyniotransporttcpniotransportfireioeventtcpniotransportjava838 at orgglassfishgrizzlystrategiesabstractiostrategyfireioeventabstractiostrategyjava113 at orgglassfishgrizzlystrategiesworkerthreadiostrategyrun0workerthreadiostrategyjava115 at orgglassfishgrizzlystrategiesworkerthreadiostrategyaccess100workerthreadiostrategyjava55 at orgglassfishgrizzlystrategiesworkerthreadiostrategyworkerthreadrunnablerunworkerthreadiostrategyjava135 at orgglassfishgrizzlythreadpoolabstractthreadpoolworkerdoworkabstractthreadpooljava564 at orgglassfishgrizzlythreadpoolabstractthreadpoolworkerrunabstractthreadpooljava544 at javalangthreadrunthreadjava744caused by orgspringframeworkbeansfactorybeancreationexception could not autowire field private comvenkathomeappservicecustomerservice comvenkathomeappcontrollerhomeappcontrollercustomerservice nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name customerservice injection of autowired dependencies failed nested exception is orgspringframeworkbeansfactorybeancreationexception could not autowire field private comvenkathomeappdaocustomerdao comvenkathomeappserviceimplcustomerserviceimplcustomerdao nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name customerdao injection of autowired dependencies failed nested exception is orgspringframeworkbeansfactorybeancreationexception could not autowire field private orghibernatesessionfactory comvenkathomeappdaoimplcustomerdaoimplsessionfactory nested exception is javalangnoclassdeffounderror lorghibernateenginefilterdefinition at orgspringframeworkbeansfactoryannotationautowiredannotationbeanpostprocessorautowiredfieldelementinjectautowiredannotationbeanpostprocessorjava508 at orgspringframeworkbeansfactoryannotationinjectionmetadatainjectinjectionmetadatajava87 at orgspringframeworkbeansfactoryannotationautowiredannotationbeanpostprocessorpostprocesspropertyvaluesautowiredannotationbeanpostprocessorjava289 65 morecaused by orgspringframeworkbeansfactorybeancreationexception error creating bean with name customerservice injection of autowired dependencies failed nested exception is orgspringframeworkbeansfactorybeancreationexception could not autowire field private comvenkathomeappdaocustomerdao comvenkathomeappserviceimplcustomerserviceimplcustomerdao nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name customerdao injection of autowired dependencies failed nested exception is orgspringframeworkbeansfactorybeancreationexception could not autowire field private orghibernatesessionfactory comvenkathomeappdaoimplcustomerdaoimplsessionfactory nested exception is javalangnoclassdeffounderror lorghibernateenginefilterdefinition at orgspringframeworkbeansfactoryannotationautowiredannotationbeanpostprocessorpostprocesspropertyvaluesautowiredannotationbeanpostprocessorjava292 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorypopulatebeanabstractautowirecapablebeanfactoryjava1185 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorydocreatebeanabstractautowirecapablebeanfactoryjava537 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorycreatebeanabstractautowirecapablebeanfactoryjava475 at orgspringframeworkbeansfactorysupportabstractbeanfactory1getobjectabstractbeanfactoryjava304 at orgspringframeworkbeansfactorysupportdefaultsingletonbeanregistrygetsingletondefaultsingletonbeanregistryjava228 at orgspringframeworkbeansfactorysupportabstractbeanfactorydogetbeanabstractbeanfactoryjava300 at orgspringframeworkbeansfactorysupportabstractbeanfactorygetbeanabstractbeanfactoryjava195 at orgspringframeworkbeansfactorysupportdefaultlistablebeanfactoryfindautowirecandidatesdefaultlistablebeanfactoryjava1014 at orgspringframeworkbeansfactorysupportdefaultlistablebeanfactorydoresolvedependencydefaultlistablebeanfactoryjava957 at orgspringframeworkbeansfactorysupportdefaultlistablebeanfactoryresolvedependencydefaultlistablebeanfactoryjava855 at orgspringframeworkbeansfactoryannotationautowiredannotationbeanpostprocessorautowiredfieldelementinjectautowiredannotationbeanpostprocessorjava480 67 morecaused by orgspringframeworkbeansfactorybeancreationexception could not autowire field private comvenkathomeappdaocustomerdao comvenkathomeappserviceimplcustomerserviceimplcustomerdao nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name customerdao injection of autowired dependencies failed nested exception is orgspringframeworkbeansfactorybeancreationexception could not autowire field private orghibernatesessionfactory comvenkathomeappdaoimplcustomerdaoimplsessionfactory nested exception is javalangnoclassdeffounderror lorghibernateenginefilterdefinition at orgspringframeworkbeansfactoryannotationautowiredannotationbeanpostprocessorautowiredfieldelementinjectautowiredannotationbeanpostprocessorjava508 at orgspringframeworkbeansfactoryannotationinjectionmetadatainjectinjectionmetadatajava87 at orgspringframeworkbeansfactoryannotationautowiredannotationbeanpostprocessorpostprocesspropertyvaluesautowiredannotationbeanpostprocessorjava289 78 morecaused by orgspringframeworkbeansfactorybeancreationexception error creating bean with name customerdao injection of autowired dependencies failed nested exception is orgspringframeworkbeansfactorybeancreationexception could not autowire field private orghibernatesessionfactory comvenkathomeappdaoimplcustomerdaoimplsessionfactory nested exception is javalangnoclassdeffounderror lorghibernateenginefilterdefinition at orgspringframeworkbeansfactoryannotationautowiredannotationbeanpostprocessorpostprocesspropertyvaluesautowiredannotationbeanpostprocessorjava292 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorypopulatebeanabstractautowirecapablebeanfactoryjava1185 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorydocreatebeanabstractautowirecapablebeanfactoryjava537 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorycreatebeanabstractautowirecapablebeanfactoryjava475 at orgspringframeworkbeansfactorysupportabstractbeanfactory1getobjectabstractbeanfactoryjava304 at orgspringframeworkbeansfactorysupportdefaultsingletonbeanregistrygetsingletondefaultsingletonbeanregistryjava228 at orgspringframeworkbeansfactorysupportabstractbeanfactorydogetbeanabstractbeanfactoryjava300 at orgspringframeworkbeansfactorysupportabstractbeanfactorygetbeanabstractbeanfactoryjava195 at orgspringframeworkbeansfactorysupportdefaultlistablebeanfactoryfindautowirecandidatesdefaultlistablebeanfactoryjava1014 at orgspringframeworkbeansfactorysupportdefaultlistablebeanfactorydoresolvedependencydefaultlistablebeanfactoryjava957 at orgspringframeworkbeansfactorysupportdefaultlistablebeanfactoryresolvedependencydefaultlistablebeanfactoryjava855 at orgspringframeworkbeansfactoryannotationautowiredannotationbeanpostprocessorautowiredfieldelementinjectautowiredannotationbeanpostprocessorjava480 80 morecaused by orgspringframeworkbeansfactorybeancreationexception could not autowire field private orghibernatesessionfactory comvenkathomeappdaoimplcustomerdaoimplsessionfactory nested exception is javalangnoclassdeffounderror lorghibernateenginefilterdefinition at orgspringframeworkbeansfactoryannotationautowiredannotationbeanpostprocessorautowiredfieldelementinjectautowiredannotationbeanpostprocessorjava508 at orgspringframeworkbeansfactoryannotationinjectionmetadatainjectinjectionmetadatajava87 at orgspringframeworkbeansfactoryannotationautowiredannotationbeanpostprocessorpostprocesspropertyvaluesautowiredannotationbeanpostprocessorjava289 91 morecaused by javalangnoclassdeffounderror lorghibernateenginefilterdefinition at javalangclassgetdeclaredfields0native method at javalangclassprivategetdeclaredfieldsclassjava2397 at javalangclassgetdeclaredfieldsclassjava1806 at orgspringframeworkormjpasupportpersistenceannotationbeanpostprocessorfindpersistencemetadatapersistenceannotationbeanpostprocessorjava392 at orgspringframeworkormjpasupportpersistenceannotationbeanpostprocessorpostprocessmergedbeandefinitionpersistenceannotationbeanpostprocessorjava332 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactoryapplymergedbeandefinitionpostprocessorsabstractautowirecapablebeanfactoryjava908 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorydocreatebeanabstractautowirecapablebeanfactoryjava512 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorycreatebeanabstractautowirecapablebeanfactoryjava475 at orgspringframeworkbeansfactorysupportabstractbeanfactory1getobjectabstractbeanfactoryjava304 at orgspringframeworkbeansfactorysupportdefaultsingletonbeanregistrygetsingletondefaultsingletonbeanregistryjava228 at orgspringframeworkbeansfactorysupportabstractbeanfactorydogetbeanabstractbeanfactoryjava300 at orgspringframeworkbeansfactorysupportabstractbeanfactorygetbeanabstractbeanfactoryjava195 at orgspringframeworkbeansfactorysupportdefaultlistablebeanfactoryfindautowirecandidatesdefaultlistablebeanfactoryjava1014 at orgspringframeworkbeansfactorysupportdefaultlistablebeanfactorydoresolvedependencydefaultlistablebeanfactoryjava957 at orgspringframeworkbeansfactorysupportdefaultlistablebeanfactoryresolvedependencydefaultlistablebeanfactoryjava855 at orgspringframeworkbeansfactoryannotationautowiredannotationbeanpostprocessorautowiredfieldelementinjectautowiredannotationbeanpostprocessorjava480 93 morecaused by javalangclassnotfoundexception orghibernateenginefilterdefinition at orgglassfishwebloaderwebappclassloaderloadclasswebappclassloaderjava1761 at orgglassfishwebloaderwebappclassloaderloadclasswebappclassloaderjava1611 109 morethanks in advance,['java'] +617024,why does the expression below characterize a narrowing conversion this expression can be found in the example in a8547 in the standard n3797unsigned int ui1 1 error narrowsgiven a8547 and its 4th bullet pointa narrowing conversion is an implicit conversionfrom an integer type or unscoped enumeration type to an integer type that cannot represent all the values of the original type except where the source is a constant expression whose value after integral promotions will fit into the target typei would say there is no narrowing here as 1 is a constant expression whose value after integral promotion fits into an unsigned intsee also a451 about integral promotiona prvalue of an integer type other than bool char16 t char32 t or wchar t whose integer conversion rank 413 is less than the rank of int can be converted to a prvalue of type int if int can represent all the values of the source type otherwise the source prvalue can be converted to a prvalue of type unsigned intfrom 413 we have that the rank of 1 an int is equal to the rank of an unsigned int and so it can be converted to an unsigned inteditunfortunately jerry coffin removed his answer from this thread i believe he was on the right track if we accept the fact that the current reading of the 4th bullet point in a8547 is wrong after this change in the standard,['c++'] +617026,convert javautildate to javatimelocaldate what is the best way to convert a javautildate object to the new jdk 8jsr310 javatimelocaldatedate input new datelocaldate date,['java'] +617063,how to add hyperlink to boundfield in gridview c aspnet i have a gridview in aspx page i need it to go add hyperlink to the component from boundfield once the user clicks on the component1 value how can i add the hyperlink to boundfield that is related to boundfieldaspgridview idmodule runatserver autogeneratecolumnsfalse backcolorwhite bordercolordedfde borderstylenone borderwidth1px cellpadding4 datasourceiddsrcgetmoduledata fontsize065em forecolorblack gridlinesvertical datakeynamestestid footerstyle backcolorc99 columnsaspboundfield datafieldcomponent1 itemstylefontsizesmall headerstylewidth80px headerstylefontsize medium sortexpressioncomponent1 columns rowstyle backcolorf7f7de selectedrowstyle backcolorce5d5a fontboldtrue forecolorwhite pagerstyle backcolorf7f7de forecolorblack horizontalalignright headerstyle backcolor6b696b fontboldtrue forecolorwhite alternatingrowstyle backcolorwhite aspgridview,"['c#', 'asp.net']" +617187,android mediaplayer loop has gaps even with ogg format in android 4x my audio looping app has 02 to 05 second gaps in the sound loopsi am using mediaplayer as my sounds can be quite large 23mb each in some cases and it can run multiple instances at the same timei have researched this quite a bit and i see there is a bug for android 4x however i have tried many work arounds and i cannot seem to get any of them workingconverted all the wavs to ogg using audacity quality level 2 to 10 it did not mattertried setnextmediaplayertried to use seekto0 on stop and repeattried soundpool which has its own bugsheres a sample of the code i am usingpublic class soundplayer implements oncompletionlistener private mediaplayer mp null public void initplayer ifmp null mp new mediaplayer public void preparecontext context int resource initplayer try mpreset uri uri uriparseandroidresourcecommyappappresource mpsetdatasourcecontexturi mpprepare isprepared true mpsetoncompletionlistenerthis catchexception e eprintstacktrace etc uses typical mediaplayer methods such as stop start setloopingtruei am not using anything special so i am just wondering if anyone knows of a work around for the looping bug on android,['android'] +617271,generate pem file used to setup apple push notification i tried and tried to generate pem file every time generating certificates from clients account and then generating pem file using terminal but its of no use i followed many links for the same please help me if any one have any idea about how to generate pem or have any link that gives a step by step procedure for pem generation,['ios'] +617294,how should i set exposure and white balance values for custom camera what would happen if i do not set the exposure and white balance when initializing the camera parameters in an android custom cameradoes the camera handle these by itself or do i need to specify values when the camera is initializedi have had trouble with the flash in the pastwould setting exposure and white balance to specific values help me overcome these problemsi do not have any plans to let the user manually tinker with the exposure andor white balance settingsi have the following code set upifissupportedcameraparametersscene mode auto mparametersgetsupportedscenemodes mscenemodecameraparametersscene mode auto mparameterssetscenemodemscenemode int minmparametersgetminexposurecompensation int maxmparametersgetmaxexposurecompensation float stepmparametersgetexposurecompensationstep do i need to setexposurecompensation here ifmscenemodecameraparametersscene mode auto issupportedcameraparametersflash mode automparametersgetsupportedflashmodes ususally when i let the flash firethe image is filled with light all that does is make everything else undecipherable mflashmodecameraparametersflash mode auto mparameterssetflashmodemflashmode ifissupportedcameraparameterswhite balance automparametersgetsupportedwhitebalance mwhitebalancemodecameraparameterswhite balance auto mparameterssetwhitebalancemwhitebalancemode i have read that autoexposure and autowhite balance update cycles are stopped when autoexposurelock and autowhitebalancelock are appliedwhy and how should i use these locks in my camera code,['android'] +617376,vectors and arrays in c performance difference between c vectors and plain arrays has been extensively thiscussed for example here and here usually thiscussions conclude that vectors and arrays are similar in terms on performance when accessed with the operator and the compiler is enabled to inline functions that is why expected but i came through a case where it seems that is not true the functionality of the lines below is quite simple a 3d volume is taken and it is swap and applied some kind of 3d little mask a certain number of times depending on the version macro volumes will be declared as vectors and accessed through the at operator version2 declared as vectors and accessed via version1 or declared as simple arraysinclude vectordefine nx 100define ny 100define nz 100define h 1define c0 15fdefine c1 025fdefine t 30if definedversion version 2 version 0 error bad versionendif if version 2 define at a b a at b typedef stdvectorfloat fieldendif if version 1 define at a b a b typedef stdvectorfloat fieldendif if version 0 define at a b a b typedef float fieldendif include iostreaminclude omphint mainvoid if version 0 field imgnxnynyelse field img new floatnxnynyendif double end begin begin omp get wtime const int csize nz const int psize nz nx forint t 0 t t t swap the 3d volume and apply the blurring coefficients pragma omp parallel for forint j h j nyh j for int i h i nxh i for int k h k nzh k int eindex kinzjnxnz atimgeindex c0 atimgeindex c1 atimgeindex csize atimgeindex csize atimgeindex psize atimgeindex psize end omp get wtime stdcout elapsed endbegin s stdendl access img field so we force it to be deleted after accouting time define whatever 12f if img nz whatever stdcout whatever stdendl if version 0 delete imgendif one would expect code will perform the same with version1 and version0 but the output is as followsversion 2 elapsed 694905 sversion 1 elapsed 408626 sversion 0 elapsed 197576 sif i compile without omp i have got only two cores i get similar resultsversion 2 elapsed 109895 sversion 1 elapsed 714674 sversion 0 elapsed 325336 si always compile with gcc 463 and the compilation options fopenmp finlinefunctions o3 i of course remove fopenmp when i compile without omp is there something i do wrong for example when compiling or should we really expect that difference between vectors and arraysps i cannot use stdarray because of the compiler of which i depend that does not support c11 standard with icc 1312 i get similar behavior,['c++'] +617377,jstree load children by ajax code posted below loads root elements for my tree by ajax request my tree is very large so i cannot load all items at once so i need to load elements by requesting children for specific ids how do i load elements by ajax by clicking on node jstree demo divjstree plugins wholerow checkbox core data url functionnode return site placesapitreelist part of json sample textzachodniopomorskie stateclosed id212353 fixed version jstree demo divjstree plugins wholerow checkbox core data url site placesapitreelist data functionnode return id nodeid the solution to my problem is that if i want to return children by ajax request i need to return json file which containschildren true,"['javascript', 'jquery']" +617416,using pundit with namespace in my project i have pretty common namespace adminnamespace admin do resources users except showendi use pundit gem to set proper authorization but i found it difficult to use with controllers within namespace my policies are organised as belowpolicies admin user policyrb application policyrb admin policyrb awesome policyrbvery similar to controllers however when inside the controller i use authorize method i get nothing but an error informing that app is unable to find userpolicy my userpolicy looks like thisclass adminuserpolicy adminpolicyendso what is the problem what should i do to make pundit see those policies inside namespace,['ruby-on-rails'] +617455,task fromresult vs taskcompletionsource setresult what is the difference concerning the functionality and meaning of the taskcompletionsource setresult vs task fromresultin the sendasync methodprotected override taskhttpresponsemessage sendasynchttprequestmessage request cancellationtoken cancellationtoken if requestrequesturischeme uriurischemehttps var response new httpresponsemessagehttpstatuscodeforbidden reasonphrase https required var taskcompletionsource new taskcompletionsourcehttpresponsemessage taskcompletionsourcesetresultresponse return taskcompletionsourcetask return basesendasyncrequest cancellationtokenprotected override taskhttpresponsemessage sendasynchttprequestmessage request cancellationtoken cancellationtoken if requestrequesturischemeequalsuriurischemehttps stringcomparisonordinalignorecase httpresponsemessage reply requestcreateerrorresponsehttpstatuscodebadrequest https is required for security reason return taskfromresultreply return basesendasyncrequest cancellationtoken,['c#'] +617456,load order in symfony2 assetic for js files i am currently using a bootstrap template that uses a few js files to get them to load i placed all the required js files in the appresourcesviewsbasehtmltwig file here is a snippet of the code block body endblock block javascripts javascripts abbundleresourcespublicjs script typetextjavascript src asset url script endjavascripts endblock my code in the child twig file located in ababbundleresourcesviewshomeshowhtmltwig has the following code extends basehtmltwig block body blah blah blah normal html code blah blah blah endblock the problem is that when i view this page i get several errors such as referenceerror jquery is not defined and referenceerror is not defined this is even though the js files are included the names of the js file are changed as expectedi found out that the error can be fixed with a rather nasty hack by instead of loading all js files with a single line of code javascripts abbundleresourcespublicjs i know need to include the js files like this block javascripts javascripts abbundleresourcespublicjsjqueryjs script src asset url script endjavascripts javascripts abbundleresourcespublicjsjqueryprettyphotojs script src asset url script endjavascripts endblock is there a way i can force assetic to load certain js files first while still using the much shorter javascripts abbundleresourcespublicjs option,['php'] +617471,xptable scrolling makes error i am using xptable for storing values in my winform application its working fine and has a lot of features but i am facing a problem when scrolling through the table if the scrolling point is in the middle of the table and i am importing some data to the table means suddenly the table shows a weird image like below is there anyway to avoid this problem is that related to painting i have searched more on the net regarding this problem but found nothing can anyone using this xptable answer meedit xptable is related to 32bit but i am using it in 64bit is that causing the error other functions work fine what i am doing is i am getting the users input through a text file and loading those values into the database after that is done i am fetching values from the database and importing it to the table as follows because of large data in text file i am storing the db and retrieving otherwise it causes hang problem or takes too much timeforeach var tokens in list2 string uname tokensname if stringisnullorwhitespaceuname uname row r new row rcellsaddnew cellsnumber colorfromargb232 79 79 colorwhite f1 rcellsaddnew celluname colorfromargb232 79 79 colorwhite f1 rcellsaddnew celltokenstoken colorfromargb232 79 79 colorwhite f1 rcellsaddnew celltokenscampaign colorfromargb232 79 79 colorwhite f1 rcellsaddnew cell imagenew bitmap10 10 rcellsaddnew cell imagenew bitmap10 10 rcellsaddnew cell imagenew bitmap10 10 rcellsaddnew cell imagenew bitmap10 10 thisinvokenew methodinvokerdelegate tablemodel1rowsaddr snumberif the scrollbar is in the starting position it does not make any problem in that weird image if i click anywhere it showing the cell value its totally weird,['c#'] +617500,how can publishsubject and behaviorsubject be unsubscribed from under the subjects package you have classes like publishsubject and behaviorsubject which i suppose can be described as some usable sample observableshow can these subjects be unsubscribed from there is no unsubscribe method and calling oncompleted ends the observable altogether right,['java'] +617623,aspnet text of textbox does not change in code behind so i have a textbox on my websiteasptextbox idlatitude runatserver clientidmodestatic asptextboxand on page load i fill that textbox with something from a databseprotected void page loadobject sender eventargs e latitudetext thisplacelatitudebut when i want to update my databse with a new value in that textbox it still updated the database with the one put in on page loadprotected void save clickobject sender eventargs e setcoordinateslatitudetextis this normal how can i make sure that i in setcoordinates get the new value from the textbox and not the one put in the textbox with latitudetext thisplacelatitude,"['c#', 'javascript', 'asp.net']" +617675,image overlay on responsive sized images bootstrap i am trying to create a responsive grid of images with descriptions that when moused over will have a color overlay just the image and not the text because of the responsive heights of the images i am having an issue where the overlay covers everything and not just the imageany way i can fix thisi have recreated the issue here for easier understanding here is my htmldiv classrow div classcolxs12 colsm6 colmd3 project a href div img src classimgresponsive div classfa faplus projectoverlaydiv div div styletextaligncenter h3project nameh3 pimage descriptionp div a divdivand my cssprojectoverlay position absolute top 0 width 100 height 100 backgroundcolor rgba4112818509 color f padding 50thanks in advance,"['html', 'css']" +617730,searchview in actionbar using supportv7appcompat i have been trying very hard to get the searchview widget to expand in the actionbar using the supportv7 libraries i have managed to get it working without the support libraries when i target 40 but i want to write the app for 23 so i need to use the support librariesi created a blank new activity with the following menuxmlmenu xmlnsandroidxmlnsyourapp item androidididaction settings androidorderincategory100 androidshowasactionnever androidtitlestringaction settingsa a a a item androidididaction search androidiconandroiddrawableic menu search yourappshowasactionalways yourappactionviewclassandroidsupportv7widgetsearchview androidtitlesearchmenuthis does not even show the search button let alone expand it upon clicking it simply adds the search into the menu instead of showing it in the actionbaralternatively i tried the same without the appcompat library i simply replaced the menuxml withitem androidididaction search androidiconandroiddrawableic menu search androidshowasactionalways androidactionviewclassandroidwidgetsearchview androidtitlesearchand it works perfectly fine and even expands to the search text input widget upon clickingi want the searchview as available in the second picture while using the appcompat library but for some reason it does not seem to be working i am using eclipse and i have included the support libraries with resources exactly as specified in support library setupdeveloperandroidcommy manifest file has minsdk version as 7 targetsdk version as 18 and the build target is also 18i suspect something is amiss in the support library setup can someone please tell me what i might be doing wrong thanks,['android'] +617784,is it posible to deactivate collisions in physics bodies in spritekit i am looking at doing the best way to collect items with my hero in my spritekit game for ios and after to try a few ways to do it my conclusion is the best way would be to have an item with a physic body which can detect collisions but do not collide with my hero is it posible to do it to deactivate collisions of a physic body without deactivating its capabilities to detect collisions sounds a bit contradictory i know because the other way would be to create only a skspritenode without physic body then there wouldnt being collisions but the way to detect collisions would be hand made and much more harder because i would need to set a coordinate system detection in my hero that when he will be in those specifics coordinates over the item then i will make the item thisappears any idea of how to do any of the two ways easier,['ios'] +617792,aspnet identity identityisauthenticated remains true even after deleting user i have implemented aspnet identity after following the sample code herein my implementation i check if a user is authenticated this is called from a filterattribute on my mvc controllers the idea is i want to confirm they are still authed before serving up the pageso in my filter the following code eventually gets called authenticationmanageruseridentityisauthenticated authenticationmanager is hereprivate iauthenticationmanager authenticationmanager get return httpcontextgetowincontextauthentication the httpcontext is passed into the constructor of my identityprovider classnow once i have logged in authenticationmanageruseridentityisauthenticated returns true as expectedhowever during development i dumped and reseeded my database without adding a user so effectively i have deleted the identityuser yet authenticationmanageruseridentityisauthenticated still returns trueany idea why this is i can only assume it is somehow checking a cookie rather than actually looking at the db is this correct or have i messed up my implementation,['c#'] +617801,effect of moving a method from public to private i was doing some code cleanup and started wondering about a certain somethingassuming that i have a program that compiles runs and generally does what it is supposed tonow i move a certain class member method from public to private or protected and the code still compiles without an erroris it theoretically possible to have such a scenario where the behavior of the program would change as a result of the code changeif so i would love to see an example,['c++'] +617817,making python 27 code run with python 26 i have this simply python function that can extract a zip file platform independentdef unzipsource target with zipfilezipfilesource r as z zextractalltarget print extracted source to targetthis runs fine with python 27 but fails with python 26attributeerror zipfile instance has no attribute exit i found this suggestions that an upgrade is required 26 27but is it possible to port the above code to work with python 26 and still keep it cross platform,['python'] +617837,locking pattern for proper use of net memorycache i assume this code has concurrency issuesconst string cachekey cachekeystatic string getcacheddata string expensivestring null if memorycachedefaultcontainscachekey expensivestring memorycachedefaultcachekey as string else cacheitempolicy cip new cacheitempolicy absoluteexpiration new datetimeoffsetdatetimenowaddminutes20 expensivestring someheavyandexpensivecalculation memorycachedefaultsetcachekey expensivestring cip return expensivestringthe reason for the concurrency issue is that multiple threads can get a null key and then attempt to insert data into cachewhat would be the shortest and cleanest way to make this code concurrency proof i like to follow a good pattern across my cache related code a link to an online article would be a great helpupdatei came up with this code based on scott chamberlains answer can anyone find any performance or concurrency issue with thisif this works it would save many line of code and errors using systemusing systemcollectionsgenericusing systemlinqusing systemtextusing systemthreadingtasksusing systemruntimecachingnamespace cachepoc class program static object everoneusethislockobject4cachexyz new object const string cachexyz cachexyz static object everoneusethislockobject4cacheabc new object const string cacheabc cacheabc static void mainstring args string xyzdata memorycachehelpergetcacheddatastringcachexyz everoneusethislockobject4cachexyz 20 someheavyandexpensivexyzcalculation string abcdata memorycachehelpergetcacheddatastringcacheabc everoneusethislockobject4cachexyz 20 someheavyandexpensivexyzcalculation private static string someheavyandexpensivexyzcalculation return expensive private static string someheavyandexpensiveabccalculation return expensive public static class memorycachehelper public static t getcacheddatatstring cachekey object cachelock int cachetimepolicyminutes funct getdata where t class returns null if the string does not exist prevents a race condition where the cache invalidates between the contains check and the retreival t cacheddata memorycachedefaultgetcachekey null as t if cacheddata null return cacheddata lock cachelock check to see if anyone wrote to the cache while we where waiting our turn to write the new value cacheddata memorycachedefaultgetcachekey null as t if cacheddata null return cacheddata the value still did not exist so we now write it in to the cache cacheitempolicy cip new cacheitempolicy absoluteexpiration new datetimeoffsetdatetimenowaddminutescachetimepolicyminutes cacheddata getdata memorycachedefaultsetcachekey cacheddata cip return cacheddata,"['c#', '.net']" +617900,curl and php how can i pass a json through curl by putpostget i have been working on building an rest api for the hell of it and i have been testing it out as i go along by using curl from the command line which is very easy for crudi can successfully make these call from the command linecurl u usernamepass x get curl d dogtall u usernamepass x get curl d dogshort u usernamepass x post curl d dogtall u usernamepass x put the above calls are easy to make from the command line and work fine with my api but now i want to use php to create the curl as you can see i pass data as a json string i have read around and i think i can probably do the post and include the post fields but i have not been able to find out how to pass http body data with get everything i see says you must attached it to the url but it does not look that way on the command line form any way i would love it if someone could write the correct way to do these four operations in php here on one page i would like to see the simplest way to do it with curl and php i think i need to pass everything through the http body because my php api catching everything with phpinput,['php'] +617904,bluebird promisify multiple arguments i am new to promises and do not know how to resolve this problemi am doing an auth system and my first call is to check email on database if user exists then check password against a bcrypted password i am using this lib for bcrypt which is not promises compatible so i am using the promisify for the following signature comparepassword crypted password callbackso this is my codevar compare promisepromisifybcryptcompareuserfindbyemailemail thencompare here is the problemthis is my findbyemail methoduserprototypefindbyemail functionemail var resolver promisependingknexusers whereemail email select thenfunctionuser if isemptyuser resolverrejectuser not found resolverfulfilluser return resolverpromisehow to assign multiple values to the compare method in that case am i missing the point of promises,['javascript'] +617971,android linearlayout selector background color hi i am trying to make my linear layout work like buttoni mean i am trying to change its background color when the state is changedi used selector to solve it but it did not worki looked for solutions and all they say was add clickable attributei have already done thatmy linearlayout contains two linearlayout which contains 9 textviews eachthey fill my linearlayout fullywhat i thought of was that its child is absorbing the click event and my linearlayout does not change its state to pressedso i put clickable and focusalbe attribute to false on every child of my linearlayouthowever it is still sameheres my codethis is the selector jbbtnxmlxml version10 encodingutf8selector xmlnsandroid item androidstate enabledtrue androidstate pressedtrue androiddrawabledrawablejbbtn pressed item androidstate enabledtrue androiddrawabledrawablejbstyle transparent item androidstate enabledfalse androiddrawabledrawablejbbtn thisabledselectorand this is my linearlayoutlinearlayout androidididllcurrents androidbackgrounddrawablejbbtn androidlayout widthwrap content androidlayout heightmatch parent androidlayout alignparentbottomtrue androidlayout alignparentlefttrue androidlayout aligntopidlltimer androidlayout belowidbtnmenu androidlayout marginright3sp androidclickabletrue androidfocusabletrue androidorientationhorizontal androidpadding3sp linearlayout,['android'] +617973,how does srand relate to rand function i understand that rand function generates the same numbers each you run it if you do not change the seed number that is where srand comes in time is always changing so i know that you should pass the timenull parameter to srand my question is with the code below from a tutorial site int main int i n5 time t t intializes random number generator srandunsigned timet print 5 random numbers from 0 to 50 for i 0 i and i printfdn rand 50 return0i see no link from the srandunsigned timet and rand printfdn rand 50where is the connection between rand and srand what i mean or expect is i assume rand will get some parameter from srand so it knows to generate different numbers each time i assume it would look something like randsrandtimenull it is like initializing a variable without using it to me srand is being initialized but i do not see it being useddoes rand generate different numbers because srand is called first before rand,['c'] +617983,what is the difference between and equals for primitives in c consider this codeint age 25short newage 25consolewritelineage newagea a trueconsolewritelinenewageequalsagea falseconsolereadlineboth int and short are primitive types but a comparison with returns true and a comparison with equals returns falsewhy,['c#'] +618009,how to compile android goldfish 34 kernel and run on emulator first let me tell you that i am working on mac with os x 1075 i am trying to compile goldfish 34 kernel and run it on emulator it compiles alright but when i run it the emulator opens and freezes when i do a top i can see the emulator running like crazy but nothing turns up on the screen here is how i compiled the kernelgit clone git checkout t originandroidgoldfish34 b goldfish34make archarm goldfish defconfigmake archarm subarcharm cross compilevolumesandroidspaceandroid workprebuiltsgccdarwinx86armarmeabi46binarmeabithen i run the emulator viaemulator debug init kernel volumesandroidspacegoldfishgoldfisharcharmbootzimage system volumesandroidspaceandroid workouttargetproductgenericsystemimg ramthisk volumesandroidspaceandroid workouttargetproductgenericramthiskimg avd firstavd wipedatahere is the last part of the debug output from running the emulatorqemu options listemulator argv00 emulator64armemulator argv01 androidhwemulator argv02 usersdeathwillarriveandroidavdfirstavdavdhardwareqemuiniconcatenated qemu optionsemulator64arm androidhw usersdeathwillarriveandroidavdfirstavdavdhardwareqemuiniemulator registered bootproperties qemud serviceemulator nand add dev systemsize0x2260initfilevolumesandroidspaceandroid workouttargetproductgenericsystemimgpagesize512extrasize0emulator mapping system nand image to tmpandroiddeathwillarriveemulator2wyv0temulator nand add dev userdatasize0xc80fileusersdeathwillarriveandroidavdfirstavdavduserdataqemuimginitfileusersdeathwillarriveandroidavdfirstavdavduserdataimgpagesize512extrasize0emulator registered bootproperties qemud serviceemulator adding boot property dalvikvmheapsize 64memulator adding boot property qemusflcd density 320emulator adding boot property qemuhwmainkeys 0emulator adding boot property qemusffake camera noneemulator nand add dev cachesize0x420fileusersdeathwillarriveandroidavdfirstavdavdcacheimgpagesize512extrasize0emulator initializing hardware opengles emulation supportemulator kernel parameters qemugles0 qemu1 consolettys0 androidqemudttys1 androidcheckjni1 ndns1emulator trace file name is not setemulator autoconfig scale 0583594emulator could not open file nullsystembuildprop no such file or directoryemulator control console listening on port 54 adb on port 5emulator sent 0012hostemulator5 to adb serveremulator ping program volumesandroidspaceandroid workouthostdarwinx86binddssthe output just freezes here does anybody know the steps to build 34 goldfish kernel,['android'] +618010,usb debugging not working adb ignores nexus 7 for several weeks i was able to connect my nexus 7 2 to my computer running windows 7 and eclipse would recognize it allowing me to run apps on it the device also showed up when i ran the adb devices command every time i plugged the nexus 7 into the computer the tablet asked if i wanted to allow usb debugging at that time oddly it never asked me whether i wanted to always allow it from that computer but i did not carei recently updated the tablet to android 442 i also updated the android sdks through the android sdk manager now when i plug the tablet in i do not get prompt about usb debugging on the tablet and neither eclipse nor adb can see that it is therehere is a list of things i tried to do gathering ideas from various forums around the webredownload the asus drivers for the nexus 7 and update the driver however windows does not even recognize this as the right drivers for this deviceturn usb debugging off and on on the tablet and also revoke all usb debugging permissionschange the connection mode from media device to cameraswitch the runtime from dalvik to arttype adb killserver followed by adb startserver in the command linedelete eclipse and all the android sdk and download them all over againnone of this worked any other ideas on what to try,['android'] +618029,confusing code compiles fine how this code works following code compiles and gives 1 as output its a bit confusing for me i tried javap for this but from there also i could not figure out i have checked for similar posts but could not find out similar question heretake look at the codeint i byte char int long 1systemoutprintlnihere is bytecode for itcompiled from testjavapublic class test public test public static void mainjavalangstringhow the types are working here is it dependent of size of datatype how the code is working,['java'] +618045,what section of the c standard requires that seterase calls destructors promptly what section of the c11 standard heres a copy of a draft standard requires associative containers like stdset stdmap stdunordered set and stdunordered map to immediately call destructors of objects that are erased from themto put it another way are standardcompliant associative containers allowed to delay not elide their calls to the key andor value destructors of the keys and values they storeif not what section in the standard forbids iti ask because i am interested in lazy deletions sometimes called weak deletions in associative containers this is a method of erasing a key or keyvalue pair from a structure in which the actual data remains in place but the node containing it is marked as dead these are sometimes called tombstones they are used in many theory papers about data structures and sometimes used in practicea very simple example is deletion in openaddressed hash tables which is sometimes implemented with tombstones when the hash table is eventually rebuilt all the destructors are called and the tombstoned keyvalue pairs can be actually and finally deleted and deallocated,['c++'] +618092,javascript pausing setinterval how do i pause and resume the setinterval function using javascriptfor example maybe i have a stopwatch to tell you the number of seconds that you have been looking at the webpage there is a pause and resume button the reason why clearinterval would not work here is because if the user clicks on the pause button at the 40th second and 800th millisecond when he clicks on the resume button the number of seconds elapsed must increase by 1 after 200 milliseconds if i use the clearinterval function on the timer variable when the pause button is clicked and then using the setinterval function on the timer variable again when the resume button is clicked the number of seconds elapsed will increase by 1 only after 10 milliseconds which destroys the accuracy of the stopwatchso how do i do that,['javascript'] +618095,font weight turns lighter on macsafari on my last website the text is perfect naturally on chrome and firefox without touching fontsmoothing or anything elsebut on mac safari 7 the text appears well then turns immediately thinner too much thinner not nice to readafter doing some research cf and some tests playing with webkitfontsmoothing it looks like safari thisplay the text first with webkitfontsmoothing subpixelantialiasedthen just after you got the flickering effect when it is turning font to webkitfontsmoothing antialiasedso it seems to me that i had no choice but to force webkitfontsmoothing subpixelantialiasedto make my website consistent on all browsersi am using fontface avenir std romansome explanations to that safari problem any better solutions could my font be part of the problem thanks,['css'] +618131,android can native code get broadcast intent from android system recently i have seen a funny app photo wonderwhen this app is uninstalled it shows a web survey page asking for the reason of app uninstall now here is the problemas far as i know after an app has been removed the system broadcasts action pakage removed intentbut this funny app was able to show my the web page although the official doc says the package that is being installed does not receive this intentanyhow i could find a process checking some kind of status of the appnow here is the question can the native app catch the broadcasted intent from android systemif it is possible please let me know how,['android'] +618180,count how many matrices have full rank for all submatrices i would like to count how many m by and matrices whose elements are 1 or 1 have the property that all its floorm21 by n submatrices have full rank my current method is naive and slow and is in the following pythonnumpy code it simply iterates over all matrices and tests all the submatrices import numpy as npimport itertoolsfrom scipymisc import combm 8n 4rowstochoose intnpfloorm21maxnumber combm rowstochoose exact truematrix gnparrayxreshapemn for x in itertoolsproduct11 repeat mnnofound 0for a in matrix g count 0 for rows in itertoolscombinationsrangem introwstochoose if nplinalgmatrix rankalistrows intminnrowstochoose count1 else break if count maxnumber nofound1 print nofound 2mnis there a betterfaster way to do this i would like to do this calculation for and and m up to 20 but any significant improvements would be greatcontext i am interested in getting some exact solutions for as a data point to compare implementations nm 44 should output 26880 nm55 is too slow for me to run for n 2 and m 23456 the outputs should be 8 0 96 0 1280current status feb 2 2014the answer of leewangzhong is fast but is not correct for m and leewangzhong is considering how to fix itthe answer of hooked does not run for m and,['python'] +618276,javafx linechart classcastexception because of the axis type how do i specify the axis type for the chart from the fxml file it seems like the default types are string integer if i declare my injectable field as linechartnumber number linechart and the i create a data series with number number the program throws a classcastexception it is mandatory for a fxml file to be used the worst case scenario would be that i created my chart manually my best guess is that this is a bugimport javaioioexceptionimport javaneturlimport javautilresourcebundleimport javafxfxmlfxmlimport javafxfxmlfxmlloaderimport javafxfxmlinitializableimport javafxscenechartlinechartimport javafxscenechartxychartimport javafxscenelayoutanchorpane author ggrec public class testchart implements initializable 2 instance fields fxml private linechartnumber number testchart private anchorpane anchorpane 4 constructors public testchart final fxmlloader fxmlloader new fxmlloader testchartclassgetresourcetestchartfxml fxmlloadersetcontrollerthis try anchorpane anchorpane fxmlloaderload catch final ioexception e eprintstacktrace 5 creators override public void initializefinal url arg0 final resourcebundle arg1 testchartgetxaxissetautorangingtrue testchartgetyaxissetautorangingtrue testchartgetdataaddgetdummydata 7 getters setters public anchorpane getanchorpane return anchorpane 13 utility methods private xychartseries getdummydata final xychartseries series new xychartseries seriessetnamemy portfolio seriesgetdataaddnew xychartdatanumber number1 23 works for 1 23 seriesgetdataaddnew xychartdata2 14 seriesgetdataaddnew xychartdata3 15 seriesgetdataaddnew xychartdata4 24 seriesgetdataaddnew xychartdata5 34 seriesgetdataaddnew xychartdata6 36 seriesgetdataaddnew xychartdata7 22 seriesgetdataaddnew xychartdata8 45 seriesgetdataaddnew xychartdata9 43 seriesgetdataaddnew xychartdata10 17 seriesgetdataaddnew xychartdata11 29 seriesgetdataaddnew xychartdata12 25 return series javalangclasscastexception javalanginteger cannot be cast to javalangstringat javafxscenechartcategoryaxisinvalidaterangecategoryaxisjava399at javafxscenechartxychartupdateaxisrangexychartjava603at javafxscenechartxychartlayoutchartchildrenxychartjava620at javafxscenechartchart1layoutchildrenchartjava84at javafxsceneparentlayoutparentjava1018,['java'] +618343,practical difference between two bubble sort loops i have been told by my teacher that this is is the one and only code for bubble sortint a23798145106 forint i0ialengthi forint j0jalengthi1j ifajaj1 int taj ajaj1 aj1t forint i0ialengthi systemoutprintait but i ran the program with a different outer loopint b23798145106 forint i0iblength1i forint j0jblengthi1j ifbjbj1 int tbj bjbj1 bj1t forint i0iblengthi systemoutprintbit the outputs are1st case1 2 3 4 5 6 7 8 9 102nd case1 2 3 4 5 6 7 8 9 10so now i am being told that my code is wrongeven if my output comes correctplease tell me am i entirely wrong,['java'] +618346,codeception output variable while scenario is running is it possible to log or output any user data while the scenario is runningi know that the php code is executed two times at each run how can i see a variables value during the second step,['php'] +618377,how safe are memorymapped files for reading input files mapping an input file into memory and then directly parsing data from the mapped memory pages can be a convenient and efficient way to read data from files however this practice also seems fundamentally unsafe unless you can ensure that no other process writes to a mapped file because even the data in private readonly mappings may change if the underlying file is written to by another process posix eg does not specify whether modifications to the underlying object done after the map private mapping is established are visible through the map private mappingif you wanted to make your code safe in the presence of external changes to the mapped file youd have to access the mapped memory only through volatile pointers and then be extremely careful about how you read and validate the input which seems impractical for many use casesis this analysis correct the documentation for memory mapping apis generally mentions this issue only in passing if at all so i wonder whether i am missing something,"['c++', 'c']" +618398,linq to sql compare time only how do i compare time only of datetime object without getting the following erroran exception of type systemnotsupportedexception occurred in mscorlibdll but was not handled in user code additional information the specified type member timeofday is not supported in linq to entities only initializers entity members and entity navigation properties are supportedmy codevar date datetimeparsequeryduetimeentities entitieswherer rduetimetimeofdayequalsdatetimeofday,"['c#', 'sql']" +618443,how can i use ef6 to update a many to many table i have two classespublic partial class objectivedetail public objectivedetail thissubtopics new listsubtopic public int objectivedetailid get set public int number get set public string text get set public virtual icollectionsubtopic subtopics get set public partial class subtopic public int subtopicid get set public string name get set i have an objectivedetail object from the uservar web objectivedetailid1 number1 textdatafromweb subtopics subtopicid1 nameone subtopicid3 namethree and an objectivedetail from the databasevar db objectivedetailid1 number1 textdatafromdb subtopics subtopicid1 nameone subtopicid2 nametwo with entity framework 6 i know i can update the text in the objectivedetail class using uowobjectivedetailsupdatewebbut how can i update the references to objectivedetail and subtopics in the many to many table that joins these two table here for example i would want it so that for objectivedetail 1 the manymany is changed to reference subtopicid 1 and 3 instead of the values 1 and 2 note that objectivedetail and subtopic are stored in tables with another table between them heres the ddlcreate table dboobjectivedetail objectivedetailid int identity 1 1 not null text nvarchar max not null objectivetopicid int null constraint pk objectivedetail primary key clustered objectivedetailid asccreate table dboobjectivetopic objectivedetailid int not null subtopicid int not null constraint fk objectivetopicobjectivedetail foreign key objectivedetailid references dboobjectivedetail objectivedetailid constraint fk objectivetopicsubtopic foreign key subtopicid references dbosubtopic subtopicidcreate table dbosubtopic subtopicid int identity 1 1 not null name nvarchar 150 not null constraint pk subtopic primary key clustered subtopicid ascheres the ef mapping that i havepublic class objectivedetailmap entitytypeconfigurationobjectivedetail public objectivedetailmap primary key thishaskeyt tobjectivedetailid relationships thishasmanyt tsubtopics withmanyt tobjectivedetails mapm mtotableobjectivetopic mmapleftkeyobjectivedetailid mmaprightkeysubtopicid,"['c#', 'asp.net']" +618525,how do i make jsonnet ignore object relationships i am working on an entity framework project i want to serialize a bunch of entity class instances i have bound these together into a container classpublic class pseudocontext public listwidget widgets public listthing thingsetcetera it is an instance of this class that i am attempting to serialize i want jsonnet to serialize the members of each entity class instance that are actually columns in the underlying database i do not want it to even attempt to serialize object referencesin particular my entity classes have virtual members that allow me to write c code that navigates all my interentity relationships without worrying about actual key values joins etc and i want jsonnet to ignore the associated parts of my entity classeson the surface there seems to be a jsonnet configuration option that does exactly what i am talking aboutjsonserializer serializer new jsonserializerserializerpreservereferenceshandling preservereferenceshandlingnoneunfortunately jsonnet seems to be ignoring the second statement abovei actually found a web page where someone else brought the same issue to the attention of james newtonking himself and his response in its entirety was write a custom contract resolveras inadequate as i find that response to be i have been attempting to follow its guidance i would very much like to be able to write a contract resolver that ignored everything except primitive types strings datetime objects and my own pseudocontext class along with the lists it contains directly if someone has an example of something that at least resembles that it might be all i need this is what i came up with on my ownpublic class whatdecadeisitagain defaultcontractresolver protected override jsoncontract createcontracttype objecttype jsoncontract contract basecreatecontractobjecttype if objecttypeisprimitive objecttype typeofdatetime objecttype typeofstring objecttype typeofpseudocontext objecttypenamecontainslist contractconverter basecreatecontractobjecttypeconverter else contractconverter mydefaultconverter return contract private static geethissuretakesalotofclassesconverter mydefaultconverter new geethissuretakesalotofclassesconverterpublic class geethissuretakesalotofclassesconverter newtonsoftjsonconverterscustomcreationconverterobject public override object createtype objecttype return null when i attempt to use the above by setting serializercontractresolver to an instance of whatdecadeisitagain prior to serialization i get outofmemory errors during serialization that indicate that jsonnet is encountering reference loops that never terminate in spite of my efforts to make jsonnet just ignore object referencesi feel like my custom contract resolver may be wrong as shown above it is built around the premise that i should return the default contract for the types i do want to serialize and a contract that simply returns null for all other typesi have no idea how correct these assumptions are though and it is not easy to tell the jsonnet design is very much based on implementation inheritance method overriding etc i am not much of an oop guy and i find that sort of design to be pretty obscure were there a custom contract resolver interface that i could implement visual studio 2012 would be able to stub out the required methods very quickly and i imagine i would have little trouble filling the stubs in with real logici would have no problem writing for example a method that returns true if i want to serialize an object of a supplied type and false otherwise perhaps i am missing something but i have found no such method to override nor have i been able to find the hypothetical interface icustomcontractresolver that would tell me what i am actually supposed to be doing in the last code snippet inserted abovealso i realize that there are jsonnet attributes jsonignore that are designed to deal with situations like this i cannot really use that approach since i am using model first unless i decide to tear up my entire project architecture my entity classes will be automatically generated and they will not contain jsonignore attributes nor do i feel comfortable editing the automated classes to contain these attributesincidentally for a while i did have things set up to serialize object references and i was just ignoring all the superfluous ref and id data that jsonnet was returning in its serialization output i have abandoned that approach for the moment at least because rather suddenly serialization started taking an inordinate amount of time 45 minutes to get 5 mb of jsoni have not been able to tie that sudden change in performance back to anything specific that i did if anything the volume of data in my database is lower now than it was when serialization was actually completing in reasonable time but i would be more than happy with a return to the status quo ante in which i was just having to ignore ref id etc if that could be achievedat this point i am also open to the prospect of using some other json library or a different strategy altogether i feel like i could just use stringbuilder systemreflection etc and come of with my own homemade solution but is not jsonnet supposed to be able to handle this sort of thing pretty easily,"['c#', '.net']" +618605,androidmainfest should an intentfilter have multiple actions my current intentfilter for my mainactivity looks like thisintentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher action androidnameandroidhardwareusbactionusb accessory attached intentfilternotice that there are 2 action nodes is this correct or should there only be one action node per intentfilteralso what is the purpose of the default categorycategory androidnameandroidintentcategorydefault,['android'] +618612,sailsjs change localization i have been using sailsjs for quite some time and was wondering if there is a way to manually change the localization from the controllers depending on the urlexample will return the english version and will return the german onethanks for your help,['javascript'] +618628,solving application has stopped crash errors building an aoa application my android device communicates with an external accessory in this case an arduinowhen i connect the accessory my android application launches correctly as i have a usb attached action within my intentfilter for my mainactivityhowever my android application unfortunately crashes when thisconnected from the usb accessorymy shell immediately switches from tcpip to usb mode on thisconect but reconnecting i get a complete stack tracecan any android gurus suggest how i might debug this further based on the following logcat outputerun 5092 javaioioexception read failed eio io errordpicasasyncmanager 4877 battery info falsedusbdevicemanager 781 exited usb accessory modeeusbdebuggingmanager 781 got 1 readingeusbdebuggingmanager 781 communication error eusbdebuggingmanager 781 javaioioexception no such file or directoryeusbdebuggingmanager 781 at androidnetlocalsocketimplconnectlocalnative methodeusbdebuggingmanager 781 at androidnetlocalsocketimplconnectlocalsocketimpljava287eusbdebuggingmanager 781 at androidnetlocalsocketconnectlocalsocketjava130eusbdebuggingmanager 781 at comandroidserverusbusbdebuggingmanagerlistentosocketusbdebuggingmanagerjava75eusbdebuggingmanager 781 at comandroidserverusbusbdebuggingmanagerrunusbdebuggingmanagerjava1eusbdebuggingmanager 781 at javalangthreadrunthreadjava841ddalvikvm 781 gc for alloc freed 1069k 14 free 31156k35896k paused 54ms total 55msvsearchcontrollercache 2819 creating searchcontrollerwsidekick locationoracleimpl 2819 best location was nullddalvikvm 2819 gc for alloc freed 514k 5 free 18100k18940k paused 15ms total 15msdaudio hw primary 182 select devices out snd device0 in snd device35 voicerecmicd 182 failed to fetch the lookup information of the device 03e eacdbloader 182 error acdb audproc vol returned 19isearchcontroller 2819 onhotworddetectorstarteddmainactivity 5092 assert registerphone and register falsedmainactivity 5092 assert registersms and register falseiwroxaccessory 5092 thisconnectdandroidruntime 5092 shutting down vmwdalvikvm 5092 threadid1 thread exiting with uncaught exception group0x41e7cba8eandroidruntime 5092 fatal exception maineandroidruntime 5092 process cafoo pid 5092eandroidruntime 5092 javalangruntimeexception unable to destroy activity cafoocafoomainactivity javalangillegalargumentexception receiver not registered comwileywroxaccessoriesusbconnection12142f0be28eandroidruntime 5092 at androidappactivitythreadperformdestroyactivityactivitythreadjava3497eandroidruntime 5092 at androidappactivitythreadhandledestroyactivityactivitythreadjava3515eandroidruntime 5092 at androidappactivitythreadaccess1400activitythreadjava135eandroidruntime 5092 at androidappactivitythreadhhandlemessageactivitythreadjava1249eandroidruntime 5092 at androidoshandlerthispatchmessagehandlerjava102eandroidruntime 5092 at androidoslooperlooplooperjava136eandroidruntime 5092 at androidappactivitythreadmainactivitythreadjava5017eandroidruntime 5092 at javalangreflectmethodinvokenativenative methodeandroidruntime 5092 at javalangreflectmethodinvokemethodjava515eandroidruntime 5092 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava779eandroidruntime 5092 at comandroidinternaloszygoteinitmainzygoteinitjava595eandroidruntime 5092 at dalviksystemnativestartmainnative methodeandroidruntime 5092 caused by javalangillegalargumentexception receiver not registered comwileywroxaccessoriesusbconnection12142f0be28eandroidruntime 5092 at androidapploadedapkforgetreceiverthispatcherloadedapkjava667eandroidruntime 5092 at androidappcontextimplunregisterreceivercontextimpljava1453eandroidruntime 5092 at androidcontentcontextwrapperunregisterreceivercontextwrapperjava489eandroidruntime 5092 at comwileywroxaccessoriesusbconnection12closeusbconnection12java115eandroidruntime 5092 at cafoomainactivityondestroymainactivityjava164eandroidruntime 5092 at androidappactivityperformdestroyactivityjava5403eandroidruntime 5092 at androidappinstrumentationcallactivityondestroyinstrumentationjava17eandroidruntime 5092 at androidappactivitythreadperformdestroyactivityactivitythreadjava3484eandroidruntime 5092 11 more,['android'] +618690,specified vm install not found type standard vm name jre7 specified vm install not found type standard vm name jre7have you ever encountered this problem in eclipse while building an ant file then this article is for you deleting and recreating the workspace is not the solution there is an easy solution to fix this issue without recreating the workspace,['java'] +618709,javascript array what is true expression create 3 undefined empty arrayvar a1 var a2 new array3from javascript the definitive guide0 in a1 true0 in a2 falsebut in real world browser getting different result ie8 and chrome 330 in a1 false0 in a2 falsewhich is true book or real world,['javascript'] +618714,detected sqlite3 gem which is not supported on heroku i am trying to push my rails app to heroku and i keep getting the following error an error occurred while installing sqlite3 138 and bundler cannot continue make sure that gem install sqlite3 v 138 succeeds before bundling failed to install gems via bundler detected sqlite3 gem which is not supported on heroku push rejected failed to compile ruby apphere is what my gemfile looks like group devlopment test do gem sqlite3endgroup production do gem pgendany ideas on how to fix this any help is much appreciated,"['ruby-on-rails', 'ruby']" +618744,bluebird promises and then i have been only using bluebird for a few days but i want to go over all my old code and promisify it my problem is that i still do not fully grasp the flow of then commandsconsider these two blocksamethodthatreturnsapromisethentask2thentask3bvar promise methodthatreturnsapromisepromisethentask2promisethentask3in scenario a task3 will get the result of task2 in b they all get the result of the first promise how does the second one differ from running promiseall from bluebirdhow do these abpromiseall differ when it comes to using the catch method where do i put itsorry it is a bunch of questions in one,['javascript'] +618808,using stdtie as a range for loop target i want to do something like the followingstdvectorstdpairtypea typeb someinitializingfunction typea a typeb b for stdtiea b someinitializingfunction do stuff however this is not valid code because as the standard says a range based for loop is defined as equivalent to auto range rangeinit for auto begin beginexpr end endexpr begin end begin forrangedeclaration begin statement where a forrangedeclaration is defined asforrangedeclaration attributespecifierseq opt declspecifierseq declaratorso whats holding me back is that declspecifierseq is not marked as optionaltherefore it seems that i must fall back on old style for loops for this one a lastdvectorstdpairtypea typeb mylist someinitializingfunction typea a typeb b for auto it mylistbegin it mylistend it stdtiea b it do stuff but it seems a bit messy syntactically for what seems to intuitively be a rather common task unpacking the result of a function call which is valid in many other contextsis there a proposal to add something this to the language is this even reasonable idea is there a better way to do this that i am overlooking am i misreading the standardobviously i could put together my own function to do this but that is also a bit messy to use as well,['c++'] +618897,fragments onactivityresult not called after orientation change please note this question is not a duplicate of the followingonactivityresult not working with fragmentsonactivityresult not working on fragmentsalso another similar question was asked before but that does not mention orientation changes and is unresolvedmy onactivityresult method in the fragment does get called if i do not switch orientation however if i follow these steps it does not get calledload fragment in fragmentactivityfrom the fragment startactivityforresultnew intentmediastoreaction image capture constantsreq code image capturewait for the camera to loadswitch orientationtake picture and click the checkmarkonactivityresult still gets called in the parent fragmentactivity however due to this warning i am gettingwfragmentactivity4418 activity result no fragment exists for index 0x22d73my guess is that the parent gets destroyed due to the orientation change and after having been recreated cannot find the fragment that called startactivityforresult in the first placeis this a framework bug how can this be worked aroundedit added more code due to popular demandfragmentactivityjavafragment new examplefragmentfragmenttransaction transaction getsupportfragmentmanagerbegintransactiontransactionreplace ridmaincontentview fragmentif clearbackstack clear the back stack while getsupportfragmentmanagerpopbackstackimmediate add the current transaction to the back stack transactionaddtobackstack nullelse transactionaddtobackstacknulltransactioncommitoverridepublic void onactivityresultint reqcode int resultcode intent data superonactivityresultreqcode resultcode dataexamplefragmentjavaintent takepicture new intentmediastoreaction image capturestartactivityforresulttakepicture constantsreq code image captureoverridepublic void onactivityresultint requestcode int resultcode intent imagereturnedintent superonactivityresultrequestcode resultcode imagereturnedintent switch requestcode case constantsreq code image capture handle added image,['android'] +618900,using browsersync with rails watching the compiled css file i am trying to use browser sync with rails using the asset pipelinei am trying to use browsersync in my rails app it has many wonderful features watching css files for changes and injecting those changes to the page is one of those features by default rails compiles sass to css when they are requested so afaikit is not possible to give browsersync the path to the appcssin my browser sync config file files railsdoesnthavethecssyetapplicationsoidontknowwhattodocss if i point the config towards the sass files the page reloadsfull refresh rather than injecting the changes this is bad i want the css changes injected to the page files assetsapplicationscss this causes full page refresh which is badanyone know how i can point browsersync to the compiled css,['ruby-on-rails'] +619006,the calling thread cannot access this object because a different thread owns itwpf i have a hardware which is connected through socketnow i have to check that hardware is connected or not at every 5 seconds which is shown by a checkboxi have implemented a function private static systemtimerstimer atimerpublic mainwindow initializecomponent clientbeginconnectremoteep new asynccallbackconnectcallback client atimer new systemtimerstimer atimerautoreset true atimerelapsed new elapsedeventhandlerontimedevent atimerinterval 20 atimerenabled trueprivate void ontimedeventobject source elapsedeventargs e if clientconnected true consolewritelinenot connected checkboxischecked false else consolewritelineconnected checkboxischecked false but when i am running the application it is throwing error the calling thread cannot access this object because a different thread owns iti researched and learned about thispatcherinvoke but not been able to implement that in my code,['c#'] +619024,listview item not found my app is using landscape full screen mode and the navigation drawer i am using listview in my app along with an edittext the edittext is the search bar that will search the listview both the listview and the edittext are in the navigation drawer but when there is no list item that matches the searched word the listview gets emptyso how can i add a item not found message instead of the blank listviewi searched a lot on the internet and found a method setemptyview but i could not understand it and hence it is not working please help me maybe this question is already asked here but please give me an easy explanationhere is my codemainactivityjavapublic class mainactivity extends fragmentactivity final string data hydrogenheliumlithiumberylliumboroncarbonnitrogenoxygenflourinenoensodiummagnesiumaluminiumsiliconphosphoroussulphurchlorineargonpotassiumcalciumscandiumtitaniumvanadiumchromiummanganeseironcobaltnickelcopperzincgalliumgermaniumarsenicseleniumbrominekryptonrubidiumstrontiumyttriumzirconiumniobiummolybdenumtechnetiumrutheniumrhodiumpalladiumsilvercadmiumindiumtinantimonytelluriumarrayadapterstring adapteroverrideprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main adapter new arrayadapterstringthis androidrlayoutsimple list item 1 data final edittext searchbar edittext findviewbyidridsearchbar final drawerlayout drawer drawerlayoutfindviewbyidriddrawer layout final listview navlist listview findviewbyidridleft drawer final linearlayout linearlayout linearlayoutfindviewbyidridleft drawer layout navlistsetadapteradapter searchbaraddtextchangedlistenernew textwatcher override public void ontextchangedcharsequence cs int arg1 int arg2 int arg3 mainactivitythisadaptergetfilterfiltercs override public void beforetextchangedcharsequence arg0 int arg1 int arg2 int arg3 override public void aftertextchangededitable arg0 the code below will automatically close the keyboard when the user will touch the listview navlistsetonscrolistenernew abslistviewonscrolistener public void onscrollstatechangedabslistview view int scrollstate inputmethodmanager imm inputmethodmanager getsystemservicecontextinput method service immhidesoftinputfromwindownavlistgetwindowtoken 0 public void onscrollabslistview view int firstvisibleitem int visibleitemcount int totalitemcount mainactivityxmlandroidsupportv4widgetdrawerlayoutxmlnsandroidandroidididdrawer layoutandroidlayout widthmatch parentandroidlayout heightmatch parentframelayout androidididcontent frame androidlayout widthmatch parent androidbackground0 androidlayout heightmatch parent textview androidlayout widthwrap content androidlayout heightwrap content androidtextappearanceandroidattrtextappearancelarge androidtextswipe from the left to open the drawer androidididtextview androidlayout gravitycenter framelayoutlinearlayout androidididleft drawer layout androidlayout heightfill parent androidlayout width240dp androidbackground1 androidorientationvertical androidlayout gravitystart edittext androidididsearchbar androidlayout width230dp androidlayout height40dp androidtextcolorbfc2d1 androidsinglelinetrue androidpadding10dp androidbackgrounddrawablesearch bar androidlayout marginleft3dp androidlayout marginright3dp androidimeoptionsflagnoextractui androidhint search edittext textview androidididnotfound androidlayout widthfill parent androidlayout heightfill parent styleandroidstyletextappearancemedium androidgravitycenter textview listview androidididleft drawer androidlayout widthmatch parent androidlayout heightfill parent androidchoicemodesinglechoice androiddividerandroidcolortransparent androiddividerheight0dp androidbackground1linearlayoutandroidsupportv4widgetdrawerlayout,['android'] +619094,memory leaks when manipulating images in chrome i encountered the following 2 huge memory leaks in chromewhen editing the src of an existing image with new byteswhen using clone to clone an imagenote that in internet explorer there is no memory leak what so eversome background i am working on a project where an external camera provides a live feed of images let us say 100 frames per secondthe main 3 functionalities of the project areplay live feedrecord live feedshow recorded feedyou are welcome to download the following standalone code simply save it as leakhtml and execute it and see for yourselfdoctype htmlhtml body canvas idmecanvas width526 height395canvas script src typetextjavascript script script var mecontext documentgetelementbyidmecanvasgetcontext2d bytes array representing a chair image var chairimgsrc dataimagepngbase649j4aaqskzjrgabaqeayabgaad2wbdaaohbwkhbgojcaklcwomdxkqdw4odx4wfxizjcamjsmgiyioltkwkco2kyijmkqynjs9qebajjbgs0usjkqd32wbdaqslcw8ndx0qeb09ksmppt09pt09pt09pt09pt09pt09pt09pt09pt09pt09pt09pt09pt09pt09pt09pt09pt3waarcahgaoadasiaahebaxeb8qahwaqubaqebaqeaecawqfbgcicqol8qatragedawieawufbaqaf9aqidaaqrbrihmuege1fhbyjxfdkbkaeii0kxwrvs0fakm2jyggkkfhcygroljicokso0nty3odk6q0rfrkthisuptvfvwv1hzwmnkzwznaglqc3r1dnd4exqdhiwgh4ijipktljwwl5izmqkjpkwmp6ipqrkztlw2t7i5usldxmxgx8jjytlt1nxw19jz2uhi4tl5ufo6erx8vp09fb3pn68qahweaawebaqebaqebaqaecawqfbgcicqol8qatreaagecbaqdbacfbaqaaqj3aaecaxeebsexbhjbuqdhcrmimoeifekrobhbcsmzuvavynlrchyknoel8rcygromjygpkju2nzg5okneruzhselku1rvvldywvpjzgvmz2hpann0dxz3ehl6gooehyahiimkkpoulzaxmjmaoqokpaanqkmqsro0tba3ulm6wspexcbhymnk0tpu1dbx2nna4upk5ebn6onq8vp09fb3pn69oadambaairaxeapwctijflrulmakquutag70lhelpgjrs0ucdnaohflqfw70uuzoab1ptsutiapatnlmmauopkwkaualrrqkyc0uutawoels0lltgls9aslfibrsguclfmbqkckakckympfsruqqraaetpvmlrvvtvim9k0iywdp4f8aqun8a1kydrbtlx2y1qvnp4mutgoqrhrqauafabrqauafabrqauaffjmjnac0uafabrqauafabrqauafabrqalfgbsyoa8tffjmipglrr2ooegasl70labrs0nsmatfa5opjpaapaqelfac0opkuubymuukslocwualrr0oogflrmigqutikkbjqm0zopglsjmkprrcbauullqiuu4u2nci4x1ofmp4qkietpfmwpfpgslu8dqqknsrrlox8mnomhfnbfy3hjkgt10nbnzpdlbrqauafabrqauafabrqauafabsypakaexrs0uajs0uuafabrqauafabrqauafabts2d0noa8q6uumawpakxoksgudfpkdqkbmmyfhwiigyvtprmkooawimkwtfhwgugfozqauaksloawikofaxakafozrrqaopaaclfjs0wfpaqutads0tnfooackekjfofmritsruiqvkpaweqzoagq1ph1q0qzspds4007mtisjw2c6af981r1m92wfiaoakacigaoakacigaoakacikozqatfjmloakacigaoakacigaoakacigbkme9lts2oxoa8rpask61imd2pkaa0fsl6ulabs0llnnawpatngayrbs0llsgflrqkyhakslpdclpkuuaffaofabsikzs8udfoxsuuaoopkwi4hawm0opjhuopbsg0althtackaffofikckyhwqrajfsrtqivanjnv1qdktcoy8mmdp7duhnbnyphu6jlvmxhrqauafabrqauafabrqauafabrqalgkwigbkkwigaoakacigaoakacigaoakksjfahiffgam1abrtakdrmigahnfjiigb1fiokcabi0uasigbackkmc0cfpatngaafopkwgytfjrqmwikprqiu0umawgytlsuualmlbpkuualsim04uaoflmm04uwhu4uwu4uxeq1itrluq1qivalsolntjvitos8kf8e039wwf4vxfnkcdxrdqgmkqbrqauafabrqauafabrqauafjqatfjrqatfabrqauafabrqauafabrqau3cr2p1fahh5o60lbqqfopo1fac0neiigytfjrqavaijpfgaafxrszozqa6im9ackaugmtkkslfabs5pm0ugfopkuuwclpkwgyd6wkooauasigb1ltrs0aopabs0aofkdtrtqahcncmu4gmbiduimoqaku1setqanjpnvlnsoeatmlnaefzmxcf7dblyhhq5s5f8aerfqhumkqbrqauafabrqauafabrqauafabrqauafabrqauafabrqauafacuyfltcn0oa8q6uvibrqauun4uualr9abhs0llqazofac0ckzs0alqksloakwkohvqmwiguugfofmbabsuuaafoauuopbs0als02loackwm07nadquu2lfmb4npu1gkckyeympuaoaaegqkxwo18ihntnvv0vchomsvpqufjdqxbijxxrwj7nwpndxn6zfdtewjzoqvdf21way5koe2eanbbgqqruglrqauafabrqauafabrqauafabrqauafabrqauafabrqauafacuutn2j0oa8qoopkgbtrsdqkybs0lfabska8euula0hquthwjnakm0tabs0lfac0uzopals9ksimmwikpc0aflsuualrrqkqc0tjmlpgfl3ozrqatlsutacilpbs0alsg0gprtcw4gna0yncgb4npbqlnodvqi3a3bqcpvsfuduoamisb6tqaldqy8qd1a7z4rpdu4ntubv2ia7jaegsuep4nanv4ogcdz4mq7pirkq1pduamdu4nxs7j7k6gjcvbv1yzvgr7gvot9twxs1v8a6mvkho5ub6brxjw3is7iaem2uf7xbrtg8twzgecjrn2grs5wk5tuvwg1c1uqpkmqk9icgraipspglrqauafabrrszoawikypwloakacigaoakacigaoakacigaoakyd2egpxpmj1oa8poqadvrsuhpamappbszngt6udq7prszppru9qahuu3d9axioawgumauualr3pkuualrsa0tawpasgualrsd6wgbackslpddnlsuuaoffaofmbauulaoadrmkooeoflscigy6lptltackugm5prqa4u7nmzs0xfie8gpgarxhruualgsa0onrg0uadxegnodvfmlbp3amduoaod1oduxcxmgpwyion1kgp3fysct3q3bql1bjy53a9dykzg1lup3cx0uhiedqblej4odwjd4js5mctfgfczfcdupvy0taoivrayfu5kptmpwqehbleebzu8goxnvakqz1a7zpcohe0vyuhiw6iaegwuebrqg8uqtjz4mqo5fllyg4c4ootu1e4thiska7aw11wzux6mxpo3bq2gddkkee1gwfxbjlnj6eikjyfxov45q5sbqe1fwkm915bmfqtbunhqofqcksmnt2pjwynrfubclytuiy9mpwbsudub8oarrft0y1edoutt0etrern3yfvskleqho4oqx2s4x7shomm3uu5buklidr3a9xs1ncodp8alkp9xtvomxrewjglbshqx6koi5i95n5u7yufvfmtfhluiq63qbumprugmb8argk9arjrufmr7ltt6ooadrszhrs0afabtmcn1eqeckapeakmuc1iwfzrsuc0alrtc4ngeabjulfigoldaafo4pmwptapmmf4qbjybr070zyzenl5eo5oeo696xmmhfq08uaflikpabi0umaxrqautjqaafopkkahuugpabi0tjs0hbs0neima7nfjrqmdmlptkoaafprszoboadsg02igbam0mam0wj4t1qxnqrhrumaajaaxnr5pc0xwh5p2ajzs5oafmlztm0onad80onmzrmncctnobqmglzqbjupwaos0onmcxds5qpnlmi4h6ldvhmlzrcctfvm31c4twbfm6gdgeko5pc07gb1v4muosculipu8gtchxtawhnrmp2ea5hdrupuza7qlxbgxgs7f94yq2l3bj9yamrhxnykno82lzctoejhlboqfoawvpi76alvyuv0nwe1yqjfy5udryh0o7orjye14gwwvv94vyxxbopvqrt9crs5ghq6qiubj8wqf9zb4jzqyvimzp3lkh4uolqlu2sa9qaykpvrwypemnngxyz9vnslr9g3lbh1u0csuwrl020rgfmnngfwoxqtkrn7rgb7nfspe20n3j42pswpaodtafsfgfyilmt9np41ijepr1p0nlnnafcxsdn5t9ap3wgh4grnflcck0so7mppvqikxgtnpvt6kbyrbtcinuliz4akgaopgjs0zo6uddfhwjrr0oaolaaogkeatfabjfhzutfabmlzrrqazflsuughuugpabi0ullqauuzopgkkuumabqatlsa0uaaclpkm0akauu0nflmgbaoljs0wfzrmk4opaobo3c03fgmuwj42zmpc1xipzgpgaah5pc0znlmgbaugmzpaah5pqazmlfad80tmfkdqa4u4gmzpc0wh0uayds5ouikzrmma07nmbwnlmm0zpals5puam0xc5oztc0zp3admjnnzrmi4c0zpuakyds0m400mkzqa8ns7z61hmjnfwjn5o8wtr5ozrccqye0cqios0zouispcun3xyfq1onvuhwliud2y1n5o3un33gtdzt9fvyrjz2bv83nxu8vxc8mqn9a5rds7qwlgokfxbdzwoed3bpyl5gpmto2ps2k5ncan1csqpy6fhmpnvab6lnfaprfwmr4vfpzwwb65nokm07rsjroeflscjnzalqacasgyuaflqazoo7ulaxetfabmlfjqkafpasigbackafozr2ooglrsutia70uwfzrqatltc0ooaxnkkb1pegoawg0lfabzsc0uatckyam5pwakykdigb4bngaiofwml8dtqmtxywakzwedqht4nav8kp1q9cvntknidwjcceh9kfkyb2hzpc00ztgcdavmo5ids5qmmkxnaemadmowwpqaqdwadmo804gmmdmlztkwgq8u6o84pwnadwaugmzpc0apzrmm5oztadmjnnzrmgqtgabmjnfwhzoztc0zp3admkzszpcalifjozszpkbi5pttc0uxc0u3nlsaxpnfjrtawkpm0a0ghuzpm0uwhzopkkaclfnjozsawakzeffgasmmwigzxsfwgbtrsuvwgazrmigudfpkafoaxnfjrqaopaqcutabmlpaadnab2pakbhnnjg0tlqalkaksjmgyubs00cloeopokm0udhzpktpvrkucamkzilzttztgkt60hnjgu1jgucemm2qs8otssdkqtayogzofpimi6kqtuuham0rezc5sx7hp8lvjawc5a4hboydb9dmswej7azkcempq1ilo6ygwr1lbydnbgtx1pzt3ofvcfx6e1unovftmpmhwlhzcfo1xifyq46aozbb0e0tjqd9rttqeidn2fcgl3vg2dss1hzadl1hl82pru661x0ujvigelnkr6chpn7any001ypjtuyazbt1jfyhrp7oppjq9qtigujpe1k3bopkuy26ov51yvlj1p500hl6za0cqgphyqwyzbykdmuwsdvls5qjjvij5ppxti6uoztltyckhqxsdytnkdtc0uaqx2am03ngaahzoztc0zoadmjnnooaxngabmlzqixnjmkzrmmauam00mkzrclds80uekzmjdqa7ngazmlzrcb2am02igb2akbmlztadrmmg0tac5pabmjvsawjnfjmi4jdopkqtjrrqadukkxtsggyucikfadqkksgytfjrqatkktnfax3eim5zsigapc0llsakkslfac0zpkwmazoojooglrqatfjrmgqtgasigyvb7uhaoapxpm0uhoacayx4onrstqbg5qrlu7k1wlzigbdpolmtdpms2xnxcgzevukdznbk30q6wz15p9rm5eyums7lzbyojd1fdpe6sg2tuujkn2rntutps05bhg5fwdhuywzmfmbzf9e4rslianhukytt8irawh2qnqokattsaummk0ggmk3ugmk0aozse03njmgbtgjmthrr8wsc2lb5g4t29qzc0h5faztm0onzwj6h9pi8qqvuhx1faeayaszro47nlnim5ozsglrszooaxngasimixnbpktnads0ljmkoacaskopagam0mam0wfoztc0zoadmjnnzs0cfzs5ptfax2altkwzypomvbnip9nfzdet93fnessrbwn0nu49kjngwosmbiqffzemowhmkx78ymqd2o9an3mtfa9nwpi9kpxc5znig480d60gslpalgfslugmuwpxjhskxckxcnaxzssf9dlqaakkgquzopdqauaksigytjrrqmwikpaacigapasigbc0ullqatfjmgudfpaads0alrsutabrmgytfjrqatgaslocwtjrszoaxnfjsuakttsadtsekaey8vexpzgo2oay5qu5qzqgegatjiusreaqqdt61ybpig3uc3udrnr2poa5oh7efhrlndukydztmgtop8aexttex7o6wzfl7pw49g9andcvzum3xkzgnz7k4pt710mtmrmn99edwiiasrgmmphfrggqhphnkaytqmdszonnjpaozigmm5oztafdm9vosszztddza3k3ucyiedxh5qo9muplyu3aens1ddtsdprsa5orm0fpabrmgbc0zpm0lads0zpuam0cfzrmkzrmgbasjnitqaue0matnaxc0tnzr0oeoozikzrmmatlszozqfharh8tiduc0zpalgsjcrgmr2yd6copxmhvtunpzgutfnybfzdb6x0ijaiuu0pu3bh7truekuuxekjgflsutqittrr1opgffjrqmxfgcuulaxawk60lac0ualr1pkkafopkxnawpasigbawkooawikooglrsuuals02loaxngabmloaxnjsuzoaxnitqabqmdtsaumme0any1gxpzgoyabdgnrpujgomoash75qwdvel71tg00jkgndqji2vhkeynnfpboa5i7tza3die3ila1hebo1kymvyyftsafq1r59vvx7ychwnatrn833g4ye1xfkthtuurkdkgyyospi6nc5yyfqoxp0gqicamme09qjnaxm03nbpdsaxngabrmgbsabn3pc0xukaoo0a1w21z8tg1pvxun3hs7tzmkthvpxxo4dqyniizusrcwpzrtc0vbqtlmjnac0umasma6kzszooawiknjnigqppktpngaafoztam0aozs5ptgaahzoztc0tac9axnnbpaahclztc0onaciikzrqbkugkpariulffmbasiigaopkwga7utjrmgyua9qkkafopkkafoglrsuzoawlpkkafozsuualmikooglmjnjrqauam0lfabrsuuagaqmjniabie1gacxpjggq1qjnojphnadwqjjujgomoaivvokrxeqcgmjjxtgaydtloaf1hpsub1k1ntckafieqa6qgqmp2v2m1jay6cimgm6yuiostpmxde61tvhlddormuvt5pkmgeh4i9q3tolyjqmcsnk7vartm2hziojviuyqu1mcm0402kmsjnjsuaozsnyktnbbapamj7v0mgxvnw5hcphacrmsataddg1vekzhejfshq6bhz0u1wdkcohozwropkkaciikoawikozqauaqmikoam0uulagoglmggkooeoopm0a0xjs0ulfah2abszozqa6gumakammikzrsjf70fsjnjmmadqkkm0agaksimatffapdclpkkafozscigbc0zopolaxawkooawikooadsuulaxaktngaafpabmjnaxc0lgakadnjrszoaummk0gknahpoayttiaytqa00w04mme0anaomp7go2oae4epxuef3qmfmq8u4uwhnofaegpwnmbpwoa5vvlx7ndeqmi3iqwyucosqhmlhvdata9q4fqaylaxyphu6ed9kqle0dpjhl3doaqptrgxde0j5zp5dqjotwqqmmgngmgkmtnjmgmmk0gfztc1bnnjoam0bu1nzszoa6rlr7ryqgowtg1o1zphyfzdnhnhxxs1ety4jqkbsk1iwnjmg0uaffjrsaxnjsuzpglrszozqagkonjmgb1fjmjnadqktngaymx1lmm0tacilptlmkapofjmloayakcqpm0utmbkacigyz4ooffabmiijnmbam0lfiyuaksigbam0uuagawkooglr0pkkafopkkaclpkm0affjsggbasjfjqae00mljppogny0w040cgk0wmne0w0amjphp5phpgin3xu4qun3hu9ahwp4plofadxtxtbthsgzmuj93f9twe3bzw3rp4ih1rfanf6ckjssrjay5m9plf6dq0zfwskzkxiuprk14pc8iz1hbrs5dq1qjjp7go2nahpnnjojphniypnnjpcaatqapnjmm5pm0ax9klmeowhaxxaa1wdk2lui7yruqeaaizuraxoazmlqcxatprqtwh4gvz0c29ukmw5zlbppxea73muf3nx86hbu7zf465ar30nlgc59vpe9oxs7xpa341bhbcnmt2onfwbzf4hdvn8rqdizlcvcqz2fnrlwccjiqpmnfkdz1jjysfkpp4vciywot9txmeaan5ossbu50r8tthpgpxnmpis4i4vaawlyk1taboct0bjkplj9ppuwjgfef2ehufhuz1u9plyj8bxqx6hyoadcgi7k1mnksl6w0f5ulnigrnlf2tfnwavmmpqugvzdzlm34muusyt07dgpa1ksaj0ud8kupdjcz9e1cw4hmnyjh065xqk1abs0nk4krc0uaaolfiy6lhnnpymgdk6unwjnhsmqffhvsudfojpkkaufaoglmiko6ualrsuudclpkkafopkwgaoakafpkbhmiikoaxnfgasgyuasjnjqikkm0hnaxcaytsmgbdttsmgq00w0ru00anjpju40wmgaqmknfv1pzcpxtepfofmfofaegpwpgpwpdmjxdl4x7gsg1qa2c3cj0wsuqtyljclwbhwte3l3n7mmjwq44q3asycexqkxwnbzurnpc1exoenjphnkttcaaejppnbnnjzqmxoaq8u5rthbmkiswowvyr6uk7occuk0smy6ndxwpya7ugpkvfiilpkkgsu0mkmikykbbqam0malavnvt47jtpllxglnj7gvpypmpnd9q6ttablhbqwdxjaok5yeg9ry6lr9wfxfckzqprwwvhxutjiih1epk8ix5xueffbgrugznysmztyftgoqx9i3nd6owab2rk0bw1ly3jmmlq8yawt9bpp8ahltklhgsk9lvo2aqozmfhvz0mz579duulraaya0zpuaxnsmdmg802lztelmjtscjnax2actmzsg4oezmekotfjticijqakbhmikoobbrqmxrrsuuafac0laooglrszooaxoktjpakbgm0umawgaoam0ulfac0zpkkacikzrqauhnfiabjsau0cejpttcabigme8u5qyabdsajottykyaaet74zvkvwx74qykyhwpwptkkqegpwpoprqmw9zobz6kkzqv6qc3rhvcqtuiwrmrlotnxkuxjk4pithjtqjwlzugomakvv3ylmjpiamme0pnnjpddrt1iy9qgmuw5hwkn3jepilq27glfgw6skoapf75omm4kocu350adz0gmilcyyaqxixz2rvgprflgv41xblj6k0m6k0gtsdwdugx71wn4ntdrdootwpwritvru96sg2jst4gshy1y8bnnpioyheq8brknvsbendenxhxpafwrifwph8uw4peuhkuu3j1pd1f2ptsdsffuy6qndn4s0jpajvquy3u4zpqe0yvkdjwl8o6wqf8afvhaamfzz7rd8sa5s5hueuks5cqcsegfhmcvjpd4vvd92oefgajpiruhp31uf7k1lppl4s3f8rip10sbpdj6kuuawiog03whmi81yxpuk1unng8ydmmetcjzapexvlyid65rcgtfkhzuxb1nou1yxlqw6m0wglzwroobopueaxnibwnfnzrmma7nlmmzozqiz9lscimslsutjmgapkwkzqaulmytlsugkmkktnltakktngaqdqaasigbacksjnac0uljqa7njmknfaxam0lfac0zpkm0ddnffjmgaztjttqiau0denkagtto1onahpphpxppoarfviraqsv3hvkuch0opopwogpfofmfpfagfq6bbsn1anz9bgtjxg4vjmca1s2jyw8saaheghrtv9qsact7fittvb5rse1qck0maawpm0ggsm49ab5xvumaqmgbht3qxy6djfymklgqmknpuga6vw5zrzmzxh5p5unonanmxm3onoqzqmn91loqapznegarax3enyoaqmgnsa4flwsksdwasm5o5p1fmq2loacqs7bvblhobwy6eirss7vgqfuluwaaqehlfz9vq9oxunbaikupj0wp3ko2k30q4o452yxi4fsw3bifqhk0maymwj7gyjhareh22juohjiq7jwak6bwrb4864x1uhdahr0opkkznbc0zpkmaueaxnnpqaqc9kxnnzrmma7nkdtm0uaqh1fn3umc0wkdfmmwulgakaeo70gimaumabi0zpkm0wawkoglqksigbabqakqbrqauulfac0ulfawoonfaakaa0lfjqmwmk0tnjxqahphpxppoaq0pnahpphp5phoacayaaex7wqykrl94vzfadqckakckahu4u2ncgcnqkezy3ea5ytgv1lwnmw8ieorkpvvypoljackaanl0rckkih82azjbzgcmk0hnnjpglmk3u0mk3uaozqwqmtryaqfuwtjexccqhbpzh0fd1gojjvf4cjarinov309nanfz2gmt2q6v3j9gvfokttzubg7ru3k6voc8su0fjxct1rqvtrubmijnkwxocvnghkwn3ckopm0yqpaslhwgdqpcdviowf8docoffvxvuy4m8iutnv7g8ntbcje5veukiuv9klmkp3oepo5bu407iys80zq4bzfsmg2fowiba7nrbf7ppss45ybjncesabbpifdfdr4vvuw4agodsadtbrc3aolza65cryja1ius2xpvh9ruwzwxozozvrdstn6sd8alw5ibpipggzns5qmod0ip407nadqaabs5palrnpfwoeffgceakkwb26kay9chrtiaikpabqapnjsmkpjcikjozqatjrrqmwikozqiwikozqmwjnjrsglmjnjrqiwikooglsuafgamikooakktnfabsgjnj1ognnitsmknahptqa040annmnonacl94vzfvh94vzfadhs00u4uaofofnfofac9q5k8imv3irdmp5v1tcrce2833lfnczkyhmnw9m1exyalu4wmqsfqywppbnn5agbs9ayetkep4sgbauaefpqtoap2aqltwkucl7uwk07c4qhnoloxnmue9kkajpkcvydrtkafp8y3sauyp7nd0oppqboqplfbfliiremipntsypmuggbacfp2kmuwau4unsncgayrshjsutaxjenkufk5h0ntpqfwp4lb8aqiloso7nkpv5rgmoartvqcmpac7cfxpwbmnbsuuvbc7aczwvayykvpcgp1tye82a4u2vjrzsxsfr3gedwzx63aejjqklxsno5rebbgplxnma69abvqv71g0yjqrujsin2opb0ooaksiimioljrrqmotjs0lac0ljs4ogffjrmgbacktnhwkatlmkpkahumakkacjnjmigyuaktnfac0ulfac0lffacuugigylb6uulacgm040anonahpphpxppognonaho8ktcqmervodkahcncmu4uaofopopaahcub1ifzbtshix5rwcsrbvif4rxizvuyk9sc00krgowpzn2fmb5qvvpkdvq1iq05vp4wma0ltwtkfp4wnybatkfpwfkbqagfiyottxun02i6akxumtqxtykhdmolhnjrdbwa17g8uxhgockkalf1arsxkqaradu9yug2srw1pcrghoaxjg3otqnobmr1gnbaqirutexcpemiseilxriqejrs4ooaslxrrqaoffabs0uucfopkuudfoztadmpbe4agqmpwrugaolaxn9jjogyoch0o8vpvvpsphumthr0rwey7vzyttnou6k9hwk6utuqiam0ulmapkccuh5oao9ffgaacikooglmim5pc0gcjnjrmmauaxnnzrsawjnffawoelrrszoglrrszoakm0affjrqauneg0lawp1nnadtjttqiau0annmnpnadapmfwh0qrj581axpqa4uopkuuaoprsuvagdl1u42xleorcmuec8mtdurjz7l2zwplfzrcmqiyjyasluqwbtwabe4pwqintwwnmcuu4cowacdtafsim5pqayh9u71uqktzrpuw3sgkxkrpm4opdugoz2pumm5pkkahrjc4fbuywghpwvzrunhtwskpcytlmkopglmikpaadfflrqauyofgaadflrrmgquutjqadrs0umcuxgatnkttaqe0ehjlvh2ndpcu5fzscezrkxtam5lsl5ztokzqlqxbkzoniapkksga70lbopgfjrsuagam0lgaadnffjmkatfawprsutaxakbbrqmkwkooegakksgyuafjrrqaulbpkbhsdacasgbdtdtztdqa0pptahdttsmkoab3qyolvu9wv6uakkcksloaumikp1ahj3szjmdt6mofs7bndgv01xpknzkzgycfsnt2cnytdgmh1qrk2ouozilkuo5ujbb5plbi8ninctfruzoascx3pwma71vzrmgc6jqad5tunxflvprtubemuaeapshlgk3k96bmkauaq0dqafopkwgc7ylgljv8gqfuwrbvhzapmcwds5qescnb80xmkpajde9ozqa6img0uabdhsumauggyuaktnlmgbawm5pc0xadzqam0maqwzrsdaolacmtw7j5kx0nctw94culzspaplsunykozsuzqbimkozsuabpkbbtawg0xiuhiuuzooelqkslzqmkxnjrqatlszooakm0uuafhwiigazrrsudamiikoakm0ulabsgikoadszonnjoacaatsk0gunniau0wenoppoeiotwaekr96nhquapfopop1ac04u0uonadhthtrthsgc7ronsjo06ksjcnhasc8drxd4b4psqnxotrc5ozyx7rttjaorzrmt2bww41mop8avdfvjnavyibv901rjm5pm1yewuyvqsdgjqexuv3liop2sc12ejpm0ypmughckpqoksga4pkx8aq0aheiguhpqa5xi4qzzskrina0awhnt1m96p5pwjpgxrltxnvens7zrccjr604svqevnpetfwsxg4pq1uxl704s07gw84o3vxetoetaibdruqleds7qyeobmjnr7qn1aeonlmot1luobdjxueg4swbp8a3mrla2txzajfs06mz5pnzzljuu6ktps0gdikonfacuajsutjtdykotfjsakacigazs0lfac0tjrmgyunegbacksigbc0ulbnabqasjtqmm0lfgaaepcacaatsam0hpaycullsggbkbsmgqhpdsmknacd6sj7oqr3q0vsgbqadmmincgbrsikfkkahcndqakckqcincmincgb4fovsxwbukns8vbfakfphcuw607a2vbewl8v09kuywtmiykhjf2k0yw7clgkrnixpzhnf7bctfcrxoladofpked1c4nuzvdmmlgyw7qoeca1s1r1mfynlnyhdfcck5n7savtjgjgvmntgbk4lr4p7ck0w1zlexzseuzxqorqixaxse8uogatwwlxgfvtk0auwtsjpwld6k9qiv5ginudc654ybstuowllnjg46uypifpasigb1lnim0o5oaccaumab2pm0ash8u4pua5pnpzigcypthjvfdshs07gwpnprjvfds5oubz83pfluyekrg1ivno4fu0im9wka9wok7ucdyylqcacub8n2hmxugx5v79a6tgbrkt1nirqwkm0ulmqtfjmigqgikozqaculbpkacg0uzoaksjnfabrmjnanabs02loaxngatnfaxaksjnibacksjnac0lgatnac5pdrtsayc5ppnbniaacg0makqwztc0tiaaepkcaq0weniau0ceooniaae71axokq96sr0fadhtqakwgbackbthqa7nkkqdnw7ezatbbguwc9ikonpdhrwhb2omm4opkjjgtookhkuy3cnqlvlppuhwqz3dsd8d0qsz9ycmlukigdktixnlnvutoegsars3bbgccobglcssxixixk1z3io5y2yjn7zc1pfjxoa7kxugvzrrhvjlojkjpuawkruyenanfkkajiulybqosa7k0tktoqqlzjktczo0jmv4rtk11kyqn7gkfcztvamcja61iup4rz1k7ieih8vy6odzvqeutzytlccs0upereoajm0c3c5qsh9o1wbezaqy9ks7mhxmobdykk0cn4engteysprg1runoubfonsdv2rsa2r0pkglkvi4ixtu31e4loct060a1pewg3uxjpypvboa1m2ozsjptrztgpj4oaolltzewhsmbco1acu7nagkmznac5zs1ahfpvctqakdxvu0tnujlrbkk4qax0me7ybfwvcmuq0zs4dpxon0h6saupwglcu2folpajeb0hj96tcppsma1ithisjw1j2q var image new image imageonload drawnewimage var record len 20 var recordedimages new arrayrecord len var count 0 function drawnewimage mecontextclearrect0 0 mecontextcanvaswidth mecontextcanvasheight mecontextdrawimageimage 0 0 mecontextcanvaswidth mecontextcanvasheight settimeoutnextimage 10 simulates 100 frames per second function drawoldimage var curimage count record len cyclic loop over the array mecontextclearrect0 0 mecontextcanvaswidth mecontextcanvasheight mecontextdrawimagerecordedimagescurimage 0 0 mecontextcanvaswidth mecontextcanvasheight settimeoutnextimage 10 simulates 100 frames per second function nextimage count if count 10 phase i during first 10 seconds use live camera feed generating a random image src just for this example instead of using the real camera feed var newimgsrc chairimgsrcslice0 11 0 countslice6 2q chrome memory leak 1 editing the src of an existing image with new bytes creates a new memory that never gets released imagesrc newimgsrc cloning the image to keep a recorded array of the last and frames var tmpimage image chrome memory leak 2 clone creates a new memory that never gets released var clonedimage tmpimageclone0 recordedimagescount record len clonedimage else phase ii use recorded feed drawoldimage windowonload nextimage script bodyhtmlthis example code takes a static image of a chair and modifies it randomly every frame just to simulate my real camera feedfor the first 10 frames it shows the image and stores the last 10 frames in a cyclic array and from then on it just shows the 10 frames last recorded in a loopobviously my real project is much more complicated i just simplified it to illustrates the problemthe question is please suggest an alternative way preferably based on the provided source code to perform the exact same functionality without causing a memory leak in chromeps 1in chromium i found the following 2 related bugs which were not really fixed evidence my code still leaksmanipulating img src via javascript will generate a massive memory leak memory usage grows infinitely when changing imgsrc ps 2i am fully aware of existing similar questions in stackoverflow and i made a lot of attempts but none of them helped me solve my problemrapidly updating image with data uri causes caching memory leakcanvas even img eating ram and cpurefresh image with a new one at the same urlsetting imgsrc to dataurl leaks memorymemory leak when loading images with javascripts settimeoutsome attempts i made for exampleto make sure that the cache is not the cause i work in incognito mode of chrome so cache is not relevant hereinstead of setting bytes array as the src i tried using blob urls but a similar leak still occursimgsrc windowurlcreateobjecturlnew blobbytesbuffer type imagejpegtried putting the image in an iframe and reloading it every x frames this partially helps but it is practically impossible for me to use this workaround update 29jan i replaced the following linesvar tmpimage imagevar clonedimage tmpimageclone0withvar clonedimage new imageclonedimagesrc newimgsrcand the leak is the same so i am down to only 1 bug that requires a workaround in 2 places leak when editing an images src,"['javascript', 'jquery']" +619114,gimbal beacon thiscovery is it possible to thiscover gimbal beacons using the ios sdk i want to use simple ranging but i do not know the uuid of the transmitter,['ios'] +619116,how to create a buttongroup with connected buttons in java i am currently trying to create a group of togglebuttons that are similar to the ones used in the formatter preferences of eclipsecurrently i have attempted this in the following waypublic class exercise extends jframe private string buttonnames a b c d e exercise final jpanel toppanel new jpanel toppanelsetlayoutnew gridbaglayout gridbagconstraints c new gridbagconstraints int tabcount 0 final buttongroup topbuttongroup new buttongroup for string buttonname buttonnames jtogglebutton tabbutton new jtogglebuttonbuttonname topbuttongroupaddtabbutton cfill gridbagconstraintshorizontal cinsets new insets0 6 0 7 questionable line cgridx tabcount cgridy 0 toppaneladdtabbutton c tabcount thisaddtoppanel thissetvisibletrue thispack public static void mainstring args new exercise the result is as followsi have a couple of concerns with my code first i do not understand why i have to make the insets negative according to oracles tutorial by default each component has no external padding hence should not there be no spaces by default without the negative insets the result looks like followssecond i would like to have the toggle button darken instead of turn blue with toggled on is there any easy way do this through java swing finally is there any better approach in general i am curious to know how eclipse managed to get the togglebuttons to look as if they are perfectly connectedupdatei have tried using a boxlayout as recommended unfortunately this did not seem to fix the problem the result is almost identical to the picture above here is the modified constructorexercise final jpanel toppanel new jpanel toppanelsetlayoutnew boxlayouttoppanel boxlayoutx axis final buttongroup topbuttongroup new buttongroup for string buttonname buttonnames jtogglebutton tabbutton new jtogglebuttonbuttonname tabbuttonsetborderborderfactorycreatebevelborder bevelborderraised colorlight gray colordark gray topbuttongroupaddtabbutton toppaneladdtabbutton thisaddtoppanel thissetvisibletrue thispackinterestingly enough when i tried adding a border as commented out above the extra spacing between the buttons somehow thisappeared the result is as belowas much as possible i would like to keep the general look of the button as before but have the edges be more rectangular so that the togglebuttons will look more connected,['java'] +619140,linux shared memory shmget vs mmap in this thread the op is suggested to use mmap instead of shmget to get shared memory in linuxi visited this page and this page to get some documentation but the second one gives an obscure example regarding mmapbeing almost a newbie and needing to share some information in text form between two processes should i use the shmget method or mmap and whythank youbob,['c'] +619167,drawing uibezierpath on code generated uiview i have a uiview added in code at run timei want to draw a uibezierpath in it but does this means i have to override the drawrect for uiviewor is there another way of drawing to it on the custom made uiviewhere is the code for generating the uiviewuiview shapeview uiview allocinitwithframecgrectmakexoriginyoriginimenu block frame height selfshapescrollframesizewidth menu block frame heightshapeviewclipstobounds yesand here is the function to create and return a uibezierpath uibezierpathcreatepath uibezierpath path uibezierpath allocinit path movetopointcgpointmake10 500 path addlinetopointcgpointmake20500 path addlinetopointcgpointmake20 20 path addlinetopointcgpointmake10 20 path closepath return paththanks,"['ios', 'iphone', 'objective-c']" +619199,how to access private variables using get set i would like to create a class for my website with a lot of private variablei thought there was a solution not to write all the getters and setters for each variable something like private int confirmed get set is it the right way and then how do i access this value from outside the classi have tried confirmed i get the error saying that it is private which i understandbut more surprising getconfirmed or getconfirmed do not work either i thought that the get set would create implicitely those methodscan someone clarify this concern for me please,"['c#', 'asp.net', '.net']" +619252,avaudioplayer and avaudiosession would not play to bluetooth stereo on ipad 2 or otherwise i have an app that plays recorded audio as well as repeating sounds the sounds play correctly through the onboard ipad speaker and if i plug in a cord from the earphone jack to my stereo audioin it also plays well when i pair my ipad to my bluetooth stereo input all the sounds from my other apps written for iphone running on my ipad work fine as does all other sound from my devicethe problem is my app written for ipad is not playing over the bluetooth path but instead plays from the builtin speakersin my app delegate in the didfinishlaunchingwithoptionsa method i have placed the followingnserror error nilavaudiosession sharedinstance setmodeavaudiosessionmodedefault errorerroravaudiosession sharedinstance setcategoryavaudiosessioncategoryplayandrecord errorerroravaudiosession sharedinstance setactiveyes errorerrorthis code is being called and there are no errors being returnedin my controller code i have recorded samples that i play using avaudioplayer as followsaudioplayer avaudioplayer alloc initwithcontentsofurlrecordurl errorerroraudioplayernumberofloops 0audioplayer setdelegateselfaudioplayer playin other areas i have drones that are playing short 01 second sounds repeated in a threaded controlled loop and i do this using openal alsourceplaysourceidthis is the same code as i have in my other apps written for iphone that works as desiredi realize that there are other threads regarding bluetooth input but i am having a specific issue with bluetooth output of audio sounds from my ipad app,"['ios', 'objective-c']" +619275,what is t on java looking at the methods of the array class on libgdx i found this methodpublic void addall t array addallarray 0 arraylengthi had never seen that t before and it turns out that it is incredibly hard to search for t either on google or here on stack overflow i think i understand generics but the is new to mewhat does that mean so for example if t is string then how would i use this method why would i use it and how would that be different from using t instead,['java'] +619331,does c as a standard prohibit the storage of member functions inside individual class instances in c implementations typically code is not stored in any form inside class instances the code segment is not in the same memory space as objects and the like this means that member functions are not stored inside class instancesbut when a question was asked about this i got to wondering to what extent if at all does the standard prohibit member functions being stored inside their encapsulating class to the extent that instantiating the class makes a copy of those functions theoretically could i make an implementation that worked this way and could it even remotely abide by the common abis,['c++'] +619354,is it legal to cast a pointer to array reference using static cast in c i have a pointer t pvalues that i would like to view as a t valuesnin this so answer the proposed way of doing this ist valuesn static casttnstatic castvoidpvaluesthe concern i have about this is in his example pvalues is initialized in the following wayt thevaluesnt pvalues thevaluesmy question is whether the cast construct is legal if pvalues comes from any of the following constructs1t thevaluesn m m 0t pvalues thevalues2t pvalues new tn m m 0,['c++'] +619434,spring root application context and servlet context confusion i know that i need to register classes annotated controller in my servlet context to make my webapp accesible usualy i do it the following wayconfigurationenablewebmvccomponentscanfoobarcontrollerpublic class webconfig extends webmvcconfigureradapter other stuff like viewresolvers messageresolvers messageconverters etcall other configuration classes i added to my root application context here is how my thispetcher initializer usualy look likepublic class thispatcherservletinitializer extends abstractannotationconfigthispatcherservletinitializer override protected class getrootconfigclasses return new class rootconfigclass serviceconfigclass override protected class getservletconfigclasses return new class webconfigclass override protected string getservletmappings return new string but things are getting more interesting when i started to use websockets to get websockets working you have to put websoketconfigclass to servlet context here is my example of websocketconfigconfigurationenableschedulingenablewebsocketmessagebrokerpublic class websocketconfig extends abstractwebsocketmessagebrokerconfigurer override public void registerstompendpointsstompendpointregistry registry registryaddendpointchatwithsockjs override public void configureclientinboundchannelchannelregistration channelregistration channelregistrationtaskexecutorcorepoolsize4maxpoolsize8 override public void configureclientoutboundchannelchannelregistration channelregistration channelregistrationtaskexecutorcorepoolsize4maxpoolsize8 override public void configuremessagebrokermessagebrokerregistry registry registryenablesimplebrokerqueue topic registrysetapplicationdestinationprefixesapp also i have created a service to send a message to the topicservicepublic class timeservicewsimpl implements timeservicews autowired private simpmessagingtemplate messagingtemplate override public void sentcurrenttime long currenttime systemcurrenttimemillis string destination topicchatty loggerinfosending current time to websocket topictime currenttime thismessagingtemplateconvertandsenddestination currenttime i need to use this service in some other sevices autowire it and now i am in deadlockif i am trying to create timeservicews bean inside root application context as expected it does not see simpmessagingtemplate bean and throws nosuchbeandefinitionexceptionif i am trying to create timeservicews bean inside servlet context then i am unable to autowire it to any another service because root context cannot see servlet context beansas far as i knowif i move all my configurations to servlet context all beans are successfully created but i get the following exception javalangillegalstateexception no webapplicationcontext found and cannot access my webappwhat am i supposed to do what should be inside root context what should be inside servlet context and could you please clarify the difference between these context one more time pleaseif you will need any additional inforamtion just let me know,['java'] +619470,how use less files in sailsjs i am reading documentationassets but i do not figure out how use less filesi put vairablesless and bootswatchless both in assetslinkerstylesi expected that grunt would have compiled both files but it did not and i got errors in the browser console insteadget httplocalhost50linkerstylesbootstrapresponsivecss 404 not found index14get httplocalhost50linkerstylesbootstrapcss 404 not found index15get httplocalhost50linkerjsjqueryjs 404 not found index29get httplocalhost50linkerjssocketiojs 404 not found index30get httplocalhost50linkerjssailsiojs 404 not found index31get httplocalhost50linkerjsappjs 404 not found index32get httplocalhost50linkerjsbootstrapjs 404 not found if i remove the two less files it works correctlywhat am i missing here,['javascript'] +619487,how to change fonts in matplotlib python it sounds as an easy problem but i do not find any effective solution to change the font not the font size in a plot made with matplotlib in pythoni found a couple of tutorials to change the default font of matplotlib by modifying some files in the folders where matplotlib stores its default font see this blog post but i am looking for a less radical solution since i would like to use more than one font in my plot text label axis label etc,['python'] +619527,backend ios iap receipt validation without verifyreceipt request i want to validate ios inapp purchase receipts in my backend codeapples design decision to do this using an external verifyreceipt request is plain down stupid it incurs latency and adds complexity of network error handling even more so the data in the receipt looks like it can be public key verifiedafter a bit of analysis on the signature field of a receipt it seems to contain a pkverified sha1 hashphpsigapxqmkskae0riytkjnnwhneugq6r98x223zch60s9m8wloydp3scceqdzrcwd3n1ldleft7zjuiqucesdaorh54esovckek2rzyopzrqhgtf81kybibkfcadhj6kzjvr1rysrxkpojk6qwmypza90xjfgtniduhlrb4v5advzcca1mwggi7oamcaqiccguuku3zwas1ma0gcsqgsib3dqebbquamh8xczajbgnvbaytalvtmrmweqydvqqkdapbchbszsbjbmmumsywjaydvqqldb1bchbszsbdzxj0awzpy2f0aw9uief1dghvcml0etezmdega1ueawwqqxbwbgugavr1bmvzifn0b3jlienlcnrpzmljyxrpb24gqxv0ag9yaxr5mb4xdta5mdyxntiymdu1nloxdte0mdyxndiymdu1nlowzdejmcega1ueawwauhvyy2hhc2vszwnlaxb0q2vydglmawnhdguxgzazbgnvbasmekfwcgxligludw5lcybtdg9yztetmbega1uecgwkqxbwbgugsw5jljelmakga1uebhmcvvmwgz8wdqyjkozihvcnaqebbqadgy0amigjaogbamrrjf2ct4irsditchai0g8pwvcmhs8prwvrt91xkvhnl4xibimkjqqnfghsds6yjudrkje7uksphmddkyffe5rgxsadbejbwrixextevx3hlefgat1mokx509dhxtiiddgjv2yavs49b0ujvndy6smqnnlhsdlzds9ozhagmbaagjcjbwmawga1udewebwqcmaawhwydvr0jbbgwfoaunh3o4p2c0geyttjrdtddc5fyqzowdgydvr0paqhbaqdageamb0ga1uddgqwbbspg4pygujfphjxcbtmzanmv8k9taqbgoqhkig92nkbgubbaifadanbgkqhkig9w0baqufaaocaqeaeasbpjtmn4cib3qepk32rxaccdxdvxaevres5fazxct88pqp93biaxvdw3etsmgy5fbeayl3etqp5gm8wrfojx0ikyvrstqaq0kejtqb07kls9que8czr8ugfdm1eumvugvdd4nwnyxlqmg4wtqfgkqqvy8gxzwvhgbeuc6y7053pgxbk51npm3woxhd3gsrlvxjlohsstcteqe9pbdpmg5sk4twgk3gmeen5e1qt9npkl1njabw7c0xsy0bfnaad1css6xdorycuvm6gtksmnoodqtesbp0bs8sn6wqs0c9dgcxrhuomz2tm8nplum7argoszqfile put contentssig substrbase64 decodesig1128file put contentscertder substrbase64 decodesig133 show certificateecho openssl x509 in certder inform der noout text nn convert to pemopenssl x509 in certder inform der out certpemecho signaturenecho openssl rsautl in sig verify asn1parse inkey certpem certinecho nnoutputcertificate data version 3 0x2 serial number 6514914dd95804b5 signature algorithm sha1withrsaencryption issuer cus oapple inc ouapple certification authority cnapple itunes store certification authority validity not before jun 15 220556 2009 gmt not after jun 14 220556 2014 gmt subject cnpurchasereceiptcertificate ouapple itunes store oapple inc cus subject public key info public key algorithm rsaencryption rsa public key 1024 bit modulus 1024 bit 00cad18c5d9cb7822b49d8930a1688 d20f29c2ffdc987b3ca7f47057faed ffdd5729584d9785c806298a8d040d 7e01ec0eceb28eefbe0eb28913bb8a b2984c75d2987c5139ac65ec01d044 8c1c112317b14debf1dc72c414602d d66a0ac79d3d761c6d8743809bf6 61a56ce3d074b89bcd772e9232a34d 2c7b032f30d2f68647 exponent 65537 0x101 cut signature 0d0 hl2 l 33 cons sequence 2d1 hl2 l 9 cons sequence 4d2 hl2 l 5 prim object sha1 11d2 hl2 l 0 prim null 13d1 hl2 l 20 prim octet string 0 b7 ef f1 9e 01 2a dd 2609 38 cd ce 63 5b b1 32 8c2 0010 88 51 17 0a q the question now remains of which data this is a hash the above contains an actual signature of this receipt signature apxqmkskae0riytkjnnwhneugq6r98x223zch60s9m8wloydp3scceqdzrcwd3n1ldleft7zjuiqucesdaorh54esovckek2rzyopzrqhgtf81kybibkfcadhj6kzjvr1rysrxkpojk6qwmypza90xjfgtniduhlrb4v5advzcca1mwggi7oamcaqiccguuku3zwas1ma0gcsqgsib3dqebbquamh8xczajbgnvbaytalvtmrmweqydvqqkdapbchbszsbjbmmumsywjaydvqqldb1bchbszsbdzxj0awzpy2f0aw9uief1dghvcml0etezmdega1ueawwqqxbwbgugavr1bmvzifn0b3jlienlcnrpzmljyxrpb24gqxv0ag9yaxr5mb4xdta5mdyxntiymdu1nloxdte0mdyxndiymdu1nlowzdejmcega1ueawwauhvyy2hhc2vszwnlaxb0q2vydglmawnhdguxgzazbgnvbasmekfwcgxligludw5lcybtdg9yztetmbega1uecgwkqxbwbgugsw5jljelmakga1uebhmcvvmwgz8wdqyjkozihvcnaqebbqadgy0amigjaogbamrrjf2ct4irsditchai0g8pwvcmhs8prwvrt91xkvhnl4xibimkjqqnfghsds6yjudrkje7uksphmddkyffe5rgxsadbejbwrixextevx3hlefgat1mokx509dhxtiiddgjv2yavs49b0ujvndy6smqnnlhsdlzds9ozhagmbaagjcjbwmawga1udewebwqcmaawhwydvr0jbbgwfoaunh3o4p2c0geyttjrdtddc5fyqzowdgydvr0paqhbaqdageamb0ga1uddgqwbbspg4pygujfphjxcbtmzanmv8k9taqbgoqhkig92nkbgubbaifadanbgkqhkig9w0baqufaaocaqeaeasbpjtmn4cib3qepk32rxaccdxdvxaevres5fazxct88pqp93biaxvdw3etsmgy5fbeayl3etqp5gm8wrfojx0ikyvrstqaq0kejtqb07kls9que8czr8ugfdm1eumvugvdd4nwnyxlqmg4wtqfgkqqvy8gxzwvhgbeuc6y7053pgxbk51npm3woxhd3gsrlvxjlohsstcteqe9pbdpmg5sk4twgk3gmeen5e1qt9npkl1njabw7c0xsy0bfnaad1css6xdorycuvm6gtksmnoodqtesbp0bs8sn6wqs0c9dgcxrhuomz2tm8nplum7argoszq purchaseinfo ewojim9yawdpbmfslxb1cmnoyxnllwrhdgutchn0iia9iciymde0ltaxlti3ida0ojuwoju2ieftzxjpy2evtg9zx0fuz2vszxmiowojinb1cmnoyxnllwrhdgutbxmiid0gijezota4mjcwntyxnzciowojinvuaxf1zs1pzgvudglmawvyiia9icjimtuxotczzthjyzy3zgrlmzkwnzhizdawmgu4n2u3mjniyje0m2u1ijskcsjvcmlnaw5hbc10cmfuc2fjdglvbi1pzcigpsaimtawmdawmda5otcwode1mci7cgkiynzycyigpsaims4wljciowojimfwcc1pdgvtlwlkiia9ici3mte0mtezmtciowojinryyw5zywn0aw9ulwlkiia9icixmdawmdawmdk5nza4mtuwijskcsjxdwfudgl0esigpsaimsi7cgkib3jpz2luywwtchvyy2hhc2utzgf0zs1tcyigpsaimtm5mdgynza1nje3nyi7cgkidw5pcxvllxzlbmrvci1pzgvudglmawvyiia9icjcnjnbrtvfqy02mjbcltqxmketqje5nc03nui3mdu3mjk4m0miowojiml0zw0tawqiid0gijc3ntg5mtg5mii7cgkidmvyc2lvbi1lehrlcm5hbc1pzgvudglmawvyiia9icixnzu5ntmxmzgiowojinbyb2r1y3qtawqiid0gimnvbs5pbnrvbxlsawzllmnyzwrpdhmynsi7cgkichvyy2hhc2utzgf0zsigpsaimjaxnc0wms0ynyaxmjo1mdo1nibfdgmvr01uijskcsjvcmlnaw5hbc1wdxjjagfzzs1kyxrliia9iciymde0ltaxlti3ideyojuwoju2iev0yy9htvqiowojimjpzcigpsaiy29tlmludg9tewxpzmuuaw9zijskcsjwdxjjagfzzs1kyxrllxbzdcigpsaimjaxnc0wms0ynyawndo1mdo1nibwvyawnhl0xvc19bbmdlbgvzijskfq environment sandbox pod 100 signingstatus 0or in base64receiptewojinnpz25hdhvyzsigpsaiqxb4uu1rcytlquuwcmlzdetqtk53ae5ldudrnli5ofgymjn6q2g2mhm5bth3bg95zfazc0njzvfkenjdd2qvm04xtctkbgvmvddaslvpcxvdrxneqw8rumg1ngvtb3zjs0vrkzjswnlvuc96ulfiz1rgodfrwujjymtgq0feago2a3pkvnixcllzulhlce9kazzxv01zuhorytkwwepmr3rusur1sgxsyjrwnufbqurwekndqtfnd2dnstdvqu1dqvfjq0nhvrvtnav0ftmu1bmeddu3fhu0lim0rujcuvvbtug4een6qupcz05wqkfzvefsvlrnuk13rvfzrfzruuteqxbcy0hcc1ptqkpibu11tvnzd0pbwurwuvfmreixqmniqnnau0jewlhkmgfxwnbzmkywyvc5dulfrjfkr2h2y21smgvurxpnrevhqtfvruf3d3frwej3ykdvz2fwujfibvz6suzomgizsmxjru5sy25scfptbgpzwfjwyji0z1fyvjbhrzl5yvhsnu1cnfhevee1turzee5usxlnrfuxtmxvwerurtbnrfl4tkrjeu1evtfobg93wkrfak1drudbmvvfqxd3yvvivnlzmmhoyzjwu1pxtmxhweiwutjwewrhbg1hv05ozedveed6qvpcz05wqkfztuvrrndjr3hssudsvwrxnwxjeujuzec5evpurvrnqkvhqtfvrunnd0trwej3ykdvz1nxnwpmakvmtufrr0exvuvcae1dvlznd2daohdeuvlks29aswh2y05buuvcqlfbrgdzmefnsudkqw9hqkfncljqrjddrjclnkavrdagfjmgc4chd2l2ntshm4cc9sd1yvcnqvotfys1zotmw0welcaw1lalfrtmznshneczz5anurk0rys0pfn3vlc3botwrks1lmrku1ckdyc0fkqkvqqndssxhlefrldngzsexfrkdbddftb0t4nta5zgh4dgljzernsnyywwfwczq5qjb1snzozhk2u01xtk5mshnethpeuzlvwkhbz01cqufhamnqqndnqxdhqtfvzev3ruivd1fdtufbd0h3wurwujbqqkjnd0zvqvvoadnvnhayqzbnrvl0vepyrhrkrem1rllrem93rgdzrfzsmfbbuugvqkfrrefnzufnqjbhqtfvzernuvdcqlnwzzrqeudvakzqaepyq0jutxphtittvjhrovrbuujnb3foa2lhotjoa0jnvujcqulgqurbtkjna3foa2lhoxcwqkfrvuzbqu9dqvffquvhu2jqanrttjrdl0lcm1ffceszmlj4ywndrfhkvlhbzvzszvm1rmfaegmrddg4cffqotncauf4dmrxlznlvfnnr1k1rmjlqvlmm2v0cva1z204d3jgb2pymglrevzsu3rrky9butblrwp0cuiwn2tmczlrvwu4y3psofvhzmrnmuv1bvyvvwd2rgq0tndowxhmuu1nnfduuwzna1frvnk4r1had1ziz2jfl1vdnlk3mduzcedyqms1mu5qttn3b3hozdnnu1jmdlhqk2xvshntdgnurxfloxbcrhbtrzurc2s0dhcrr0szr01lru41lytlmvfuow5wl0tsmw5qk2fcdzddmhhzetbirm5hqwqxy1ntnnhkb3j5l0nvdk02z3rlc21ut09kcvrlc2jwmgjzohnunldxczbdowrny3hsshvptvoydg04bnbmvw03yxjnt1n6ut09ijskcsjwdxjjagfzzs1pbmzviia9icjld29ksw05ewfxzhbibuzztfhcmwnttm9zwe5stfdsagrhvxrjse4wswlbouldsxlnreuwtfrbeexustnjreewt2pvd09qvtjjruz0wlhkcfkyrxzurzl6wdbgdvoyvnnawe1pt3dvskluqjfjbu5vwvhobexxumhkr1v0ylhnaulemgdjakv6t1rbne1qy3dovfl4tnpjau93b0pjblz1yvhgmvptmxbar1z1zedsbwfxvnljaue5sunkau1uvxhpvgn6wlroall6wtnar1jstxprd056aglaref3tudvne4yvtnnak5pwwpfme0yvtfjannlq1nkdmntbg5hvzvoykmxmgntrnvjmkzqzedsdmjpmxbaq0lnufnbau1uqxdnref3turbnu9uy3dpreuxtunjn0nna2lzblp5y3ljz1btqwlnuzr3tgpjau93b0pjbuz3y0mxcgrhvnrmv2xrswlbouldstnnveuwtvrfek1uy2lpd29ksw5sevlxnxpzv04wyvc5duxxbgtjaue5sunjee1eqxdnref3turrnu56qtrnvfv3swpzs0ntsnhkv0z1zedsmgvtswdqu0fptvnjn0nna2lim0pwwjjsdvlxd3rjsfz5wtjoagmyvxrar0ywwlmxdgn5swdqu0fptvrnnu1ez3loekextmpfm055stddz2tpzfc1cgnyvmxmwfpsym1sdmnpmxbar1z1zedsbwfxvnljaue5sunkq05qtkjsvfzguxkwmk1qqknmvff4twtfdffqrtvoqzaztlvjm01evtnnams0ttbnau93b0pjbwlcwdgfxuwljrdbnswpjm05uzzvnvgc1twljn0nna2lkbvz5yzjsdmjpmwxlsfjsy201agjdmxbar1z1zedsbwfxvnljaue5sunjee56vtvove14txpnau93b0pjbkj5yjjsmvkzuxrhv1fpsuqwz0lttnziuzvwym5sdmjybhnhv1pstg1oevpxunbkse15tlnjn0nna2ljsfz5wtjoagmyvxrar0ywwlnjz1btqwlnakf4tkmwd01tmhloeuf4twpvmu1ebzfoaujgzedndliwmvvjannlq1nkdmntbg5hvzvoykmxd2rysmphr0z6wlmxa1lyumxjaue5sunjeu1ertbmvef4tfrjm0lerxlpalv3t2pvmklfvjbzetlivfzrau93b0pjbupwwknjz1btqwlzmjl0tg1sdwrhoxrlv3hwwm1vdwfxoxpjannlq1nkd2rysmphr0z6wlmxa1lyumxmwej6zenjz1btqwlnakf4tkmwd01tmhloeuf3tkrvmu1ebzfoaujcyldwewfxtmhmmhh2yze5qmjtzgxir1z6swpzs2zrpt0iowojimvudmlyb25tzw50iia9icjtyw5kym94ijskcsjwb2qiid0gijewmci7cgkic2lnbmluzy1zdgf0dxmiid0gijaiowp9the most simple data to verify would be the purchaseinfo field unfortunately the sha1 sum of this either base64encoded or opaque data does not match the one in the signaturehaving seen a fair share of apple file formats my guess would be it could be a combination in a form like purchasedatax00x00environmentx00x00pod with a bit of bad luck though they added a secret string that would make the entire exercise quite futile but i fail to see as to why they wouldany insightupdatesome more experimentation with sending different receipts to the verifyreceipt endpoint suggests the podenvironment fields do not matter even more so the order of fields within the receipt structure is of no consequence changing a single byte in the purchaseinfo data however directly yields an invalid receipt this all would strengthen the hypothesis that only the purchaseinfo value is part of the hash but it is probably prefixedsuffixed with a secret could anyone verify pun intended this,['ios'] +619577,camerarelease takes 30 seconds to release the camera in nexus 10 is there any way to speed up the process i am using the following code to release camera in onpause but the line mcamerarelease takes 30 seconds on average to release the camera in nexus 10 device i have added logging before and after mcamerarelease and found that the time difference between printing these logs is 30 secondsprivate void releasecamera if mcamera null previewing false mcamerasetpreviewcallbacknull ifmpreview null mpreviewgetholderremovecallbackmpreview logeqrstarting to call mcamerarelease mcamerarelease logeqrreleased camera mcamera null i am calling mcamerastoppreview before calling releasecamerais there any way by which i can do it asynchrounously because it takes just less than a minute to go from the camerapreview activity to the next activityedit1 we reduced the preview size from the highest1080x1920 to a middle range 480x800 and everything started working fine is the preview size has anything to do with the camera release in hal,['android'] +619621,directoryexists strange behavior i have an iishosted wcf service and i am trying to use directoryexists method if nonexistent network location is passed this method hangs i have googled for it and found that it is kind of ok due to directoryexists inner implementation but i wrote a simple console application which does the same and directoryexists never hangs always returns false i run the application under my admin account and iis pool is running under network servicedo you have any ideas why what is the difference between doing the same inside a service or a console application,"['c#', '.net']" +619706,how to use doubletryparse when the output is allowed to be null in my application i have a textbox txtthiscount where the admin can set a thiscount percentage for a certain user or he may not on the back end i want to save the data so for now i have thisdouble thiscount nullif stringisnulloremptytxtthiscounttext if doubletryparsetxtthiscounttext out thiscount errorsaddthiscount must be a doubleso i get an error for invalid argument and obviously it is the thiscount which can not be nullable if i am gonna use it in tryparse i saw that many people are making extensions for this type of situations but for now i do not think it is necessary what i can think of is using another variable like so double thiscount nullprivate double thiscountif stringisnulloremptytxtthiscounttext if doubletryparsetxtthiscounttext out thiscount errorsaddthiscount must be adouble else thiscount thiscount and then use my nullable thiscount to pass the value to the database but i actually do not like the code above it seems to me pretty complicated for such a task but i cannot think of something better so how can i deal with this situation without using extension method,['c#'] +619717,the developers of this app have not set up this app properly for facebook login i am trying to make login with facebook available in my script i have done everything but when i attempt to login with a facebook account i get this error from facebookerrorapp not setup the developers of this app have not set up this app properly for facebook loginheres error screenshotany ideas,"['android', 'ios']" +619781,why actionbarsharelock shows only overflow icon even there are room i am stuck with menu item visibility in abs even there are room in header thing is i have test in different size of device but in each case i am able to see only one and that is overflow menui am using onprepareoptionsmenu to manage my menu as dynamically and that is working perfectlybut do not know may be this issue is occur bye onprepareoptionsmenu or some other reasonview differencefirst approach i have create menu programmatically and set that visibility using setshowasaction somewhere i have found setshowasactionflag also and i have try that also but in that case i am not able to see overflow menu in small screen 320480 so that is my issue in programmatically approachhere is my codeoverridepublic boolean onprepareoptionsmenumenu menu todo autogenerated method stu to remove older menu otherwise that will apped menu each time menuclear menuaddmenunone menu search menunone searchseticonrdrawableic searchsetshowasactionflagsmenuitemshow as action if room menuitemshow as action with text menuaddmenunone menu setting menunone settingsseticonrdrawableic action settings setshowasactionflagsmenuitemshow as action if room menuitemshow as action with text if is session exist 1 menuaddmenunone menu change login menunone change loginseticonrdrawableic action add person setshowasactionflagsmenuitemshow as action if room menuitemshow as action with text menuaddmenunone menu logout menunone logoutseticonrdrawableabs ic clear setshowasactionflagsmenuitemshow as action if room menuitemshow as action with text else menuaddmenunone menu login menunone loginseticonrdrawableic action add person setshowasactionflagsmenuitemshow as action if room menuitemshow as action with text return superonprepareoptionsmenumenusecond approach i have create menu using xml folder and set all property in separate file now i am inflecting that menu in onprepareoptionsmenu but in that case i am only able to see overflow icon in any density screen even i have set the androidshowasactionifroomwithtexthere is my xml codexml version10 encodingutf8menu xmlnsandroid item androidididmainmenu androidicondrawableabs ic menu moreoverflow holo dark androidshowasactionalways menu item androidididmenu search androidicondrawableic search androidshowasactionifroomwithtext androidtitlesearch androidvisibletrue item androidididmenu login androidicondrawableic action add person androidshowasactionifroomwithtext androidtitlelogin androidvisibletrue item androidididmenu change login androidicondrawableic action add person androidshowasactionifroomwithtext androidtitlechange login androidvisiblefalse item androidididmenu setting androidicondrawableic action settings androidshowasactionifroomwithtext androidtitlesetting androidvisibletrue item androidididmenu logout androidicondrawableabs ic clear androidshowasactionifroomwithtext androidtitlelogout androidvisiblefalse menu itemmenui am changing menu item in onprepareoptionsmenu using setvisiblefalsetruehere some helpful link which i have refer already but issue is not solve yet set androidshowasactionifroomwithtext programmaticallyhow to add text to icons in actionbari do not know why i am getting this issue your help and effort will definitely appreciatethank you,['android'] +619860,how to use kaminari theme for zurb foundation i want to apply a theme for zurb foundation to kaminari paginationdetault theme can be installed by rails g kaminariviews defaultbut i could not figure out how to install other themesespecially theme for foundation is not merged themespull14there is no readme in kaminari themes so i have no idea how to go furtherwhat should i do to apply the foundation theme,['ruby-on-rails'] +619934,in angularjs any inline javascript code that included in html templates does not work in angularjs any inline javascript code that included in html templates does not workfor examplemainhtml filediv ngincludetemplatesscripthtmldivand scripthtml filescript typetextjavascript alertyesscriptwhen i open main page i expect an alert message that say yes but nothing happens i think some security restrictions in the angularjs is preventing inline scripts but i could not find any workaround about thatnote i do not use jquery or any other framework only angularjs 127,"['javascript', 'html']" +619935,interactive view controller thismissal and changing statusbarstyle not compatible i am presenting a modal uinavigationcontroller with an interactive thismiss transition the parent view controller has a dark status bar and the modal view controller a light status bar i am using the ios 7 view controllerbased status bar appearance configurationall works fine as long as i present and thismiss the view controller noninteractively however when i start an interactive thismiss transition and cancel it the status bar color remains darki created a sample project tap the menu button then start the interactive transition by panning from the right screen edgethings i have triedcalling setneedsstatusbarappearanceupdate on any of the navigation and view controllers involved after the transition has been canceledchanging the navigationbarbarstyle to uibarstyledefault and back to uibarstyleblacki also verified that the statusbarstyle of my modal navigation controller is set correctlylldb p uistatusbarstyle uiapplication sharedapplication keywindow rootviewcontroller presentedviewcontroller preferredstatusbarstyleuistatusbarstyle 8 uistatusbarstylelightcontentstill the status bar is blackany further idea what i could try,['ios'] +619948,running jetty 9 on java 6 i work for a corporation that would not upgrade from jre 6 to jre 7 on our servers i have successfully developed some code that works on jre 7 using jetty 9 however i cannot run this code on the corporation server i was wondering if anyone out here knew of a way to run jetty 9 on jre 6 i specifically need the httpconfiguration class from jetty 9the only potential thing i can think of would be to download jetty set it to a 16 compliance and work from that i am really hoping with a shot in the dark that someone has a better idea,['java'] +620044,fatal error when implementing an oauth library to connect to an etsy store i am using an oauth library to connect to my etsy store etsycom and try to retrieve some information regarding sold ordersthis is the library however i keep getting an error after i allow access i receive a token but when i allow access the issue is happeninghere is the full error fatal error uncaught exception oauthcommonhttpexceptiontokenresponseexception with message file get contents self failed to open stream http request failed http11 400 bad request in hermesbosoraweb013b1151ipgtaharaapisphpoauthlibmastersrcoauthcommonhttpclientstreamclientphp70 stack trace 0 hermesbosoraweb013b1151ipgtaharaapisphpoauthlibmastersrcoauthoauth1serviceabstractservicephp137 oauthcommonhttpclientstreamclientretrieveresponseobjectoauthcommonhttpuriuri null array get 1 hermesbosoraweb013b1151ipgtaharaapisphpoauthlibmasterexamplesetsyphp47 oauthoauth1serviceabstractservicerequestprivateusers 2 main thrown in hermesbosoraweb013b1151ipgtaharaapisphpoauthlibmastersrcoauthcommonhttpclientstreamclientphp on line 70would anyone have any input to identify what the issue is,['php'] +620137,proguard causing runtimeexception unmarshalling unknown type code in parcelable class i get this exception if i leave my app and open it after some time my main activity consist of a viewpager with three different fragments i also do some stuff in application class which i do not think relates to the problemthis is the exceptionruntimeexception parcelreadvalue2065 unable to start activity componentinfocomemucomemuactivitymain javalangruntimeexception parcel androidosparcel419526d0 unmarshalling unknown type code 2131361816 at offset 332i see lots of this exception happening on users phones in google analytics all of them are the same except number after readvalue and hex number after which are 2065 and 419526d0 in above exceptionthe exception does not point any line of code i searched about this and it seems it relates to wrong writing to parcel although i do not have any parcel in my mainactivity i do not know what may cause this edit i reproduced the exception it happens when app is leaved with home button and got cleared from memory after opening some other memory consuming app when starting it again exception happens till now i was thinking that closing app from recent task or from ddms have the same effect but apparently it does notericwoodruf helped me to find that parcel is somewhere in imported library i find the parcel in pagerslidingtabstrip which i had downloaded from web this is the parcel related code but i do not really know what is wrong herepublic class pagerslidingtabstrip extends horizontalscrollview override public void onrestoreinstancestateparcelable state savedstate savedstate savedstate state superonrestoreinstancestatesavedstategetsuperstate currentposition savedstatecurrentposition requestlayout override public parcelable onsaveinstancestate parcelable superstate superonsaveinstancestate savedstate savedstate new savedstatesuperstate savedstatecurrentposition currentposition return savedstate static class savedstate extends basesavedstate int currentposition public savedstateparcelable superstate supersuperstate private savedstateparcel in superin currentposition inreadint override public void writetoparcelparcel parcel int flags superwritetoparcelparcel flags parcelwriteintcurrentposition public static final parcelablecreatorsavedstate creator new parcelablecreatorsavedstate override public savedstate createfromparcelparcel in return new savedstatein override public savedstate newarrayint size return new savedstatesize edit 2 after i could reproduce the problem i found out that this happens only in artifact which is signed by my key and proguarded the debug one does not have the problemi thisabled proguard on artifact and it works like a charm without the exception but what proguard do that result in this problemi tried adding this to proguard but did not workkeep class toolfaandroidbaseuipagerslidingtabstrip dontwarn toolfaandroidbaseuipagerslidingtabstripthis is my current proguard configkeep class comnineoldandroids dontwarn comnineoldandroidskeep class iradad dontwarn iradadkeep class androidsupportv4 dontwarn androidsupportv4keep class toolfaandroidbaseuipagerslidingtabstrip dontwarn toolfaandroidbaseuipagerslidingtabstripkeep class toolfaandroidsegaactivityemulator keep class toolfaandroidsegazip,['android'] +620143,are there ideal array sizes in javascript i have seen little utility routines in various languages that for a desired array capacity will compute an ideal size for the array these routines are typically used when it is okay for the allocated array to be larger than the capacity they usually work by computing an array length such that the allocated block size in bytes plus a memory allocation overhead is the smallest exact power of 2 needed for a given capacity depending on the memory management scheme this can significantly reduce memory fragmentation as memory blocks are allocated and then freedjavascript allows one to construct arrays with predefined length so does the concept of ideal size apply i can think of four arguments against it in no particular orderjs memory management systems work in a way that would not benefit from such a strategyjs engines already implement such a sizing strategy internallyjs engines do not really keep arrays as contiguous memory blocks so the whole idea is moot except for typed arraysthe idea applies but memory management is so enginedependent that no single ideal size strategy would be workableon the other hand perhaps all of those arguments are wrong and a little utility routine would actually be effective as in make a measurable difference in script performanceso can one write an effective ideal size routine for javascript arrays,['javascript'] +620197,es6 module export default syntax i am using the es6moduletranspiler esprima and jshint with esnext true options jshint complains when i putexport default some thing other thing but esprima complains when i useexport default some thing other thing the spec saysexport default assignmentexpression which makes me think that jshint needs updating and esprima is properly bombing out because there is not an assignment can someone be the deciderer for me here,['javascript'] +620204,python kerberos1targz install failure on windows i run python on windows based environments 2003 win 7 2008 r2 etc both 32 and 64bit flavors i have recently had to authenticate to various corporate internally facing websites using both ntlm and kerberos authentication schemes i was successful with ntlm authentication using the requests module specifically there is some documentation thiscussing ways for other authentication installing the requestsntlm packages worked greatunfortunately i cannot seem to get the requestskerberos package to work the requirementstxt indicates that the kerberos1 package is required but i am unable to buildinstall that package here is what happens if i try to import the requestskerberos library without the kerberos1 import requests from requests kerberos import httpkerberosauthtraceback most recent call last file stdin line 1 in module file requests kerberos init py line 17 in module from kerberos import httpkerberosauth required optional thisabled file requests kerberoskerberos py line 1 in module import kerberosimporterror no module named kerberosand here is my errors when trying to build the kerberos1 package from one of my win 7 machines with python 265python setuppy install instalib ctmprunning installrunning buildrunning build extbuilding kerberos extensioncprogram files x86microsoft visual studio 90vcbinclexe c nologo oxmd w3 gs dndebug icpython26arcgis100include icpython26arcgis100pc tcsrckerberosc fobuildtempwin3226releasesrckerberosobj is not recognized as an internal or external command operable program or batch filecl command line warning d9024 unrecognized source file type object file assumedcl command line warning d9027 source file ignoredcl command line warning d9024 unrecognized source file type is object file assumedcl command line warning d9027 source file is ignoredcl command line warning d9024 unrecognized source file type not object file assumedcl command line warning d9027 source file not ignoredcl command line warning d9024 unrecognized source file type recognized object file assumedcl command line warning d9027 source file recognized ignoredcl command line warning d9024 unrecognized source file type as object file assumedcl command line warning d9027 source file as ignoredcl command line warning d9024 unrecognized source file type an object file assumedcl command line warning d9027 source file an ignoredcl command line warning d9024 unrecognized source file type internal object file assumedcl command line warning d9027 source file internal ignoredcl command line warning d9024 unrecognized source file type or object file assumedcl command line warning d9027 source file or ignoredcl command line warning d9024 unrecognized source file type external object file assumedcl command line warning d9027 source file external ignoredcl command line warning d9024 unrecognized source file type command object file assumedcl command line warning d9027 source file command ignoredcl command line warning d9024 unrecognized source file type operable object file assumedcl command line warning d9027 source file operable ignoredcl command line warning d9024 unrecognized source file type program object file assumedcl command line warning d9027 source file program ignoredcl command line warning d9024 unrecognized source file type or object file assumedcl command line warning d9027 source file or ignoredcl command line warning d9024 unrecognized source file type batch objectfile assumedcl command line warning d9027 source file batch ignoredcl command line warning d9024 unrecognized source file type file objectfile assumedcl command line warning d9027 source file file ignoredkerberoscsrckerberosbasich17 fatal error c1083 cannot open include file gssapigssapih no such file or directoryerror command cprogram files x86microsoft visual studio 90vcbinclexe failed with exit status 2 i also have tried one of my win 2008 r2 servers with python 272 but get a different error pythonexe setuppy install instalib ctmprunning installrunning buildrunning build extbuilding kerberos extensionerror unable to find vcvarsallbati think this has to do that these are being built from source and need some sort of c or c compiler whereas most other modules i have installed in the past worked great any advise is appreciated,['python'] +620324,custom http message converter not being used 415 unsupproted media type i am creating a test application to achieve conversion from xml string to employee object before being passed to the controller i do not want to use jaxb converter because the purpose is to test custom http message converter which i am going to use in my actual use case that involves xml parsing using sax parser and some complex ruleshere are the key steps performedcreation of employeejava class domain objectcreation of employeemanagementcontrollerjava class spring mvc controller for managing employeecreation of employeeconverterjava custom converter for converting xml string to employee objectcreation of employeeservletxml spring configuration filecreation of webxml the deployment descriptoremployeejavacomponentxmlrootelementnameemployeexmlaccessortypexmlaccesstypefieldpublic class employeexmlelementnamenamestring namexmlelementnamedesignationstring designationxmlelementnameskillstring skillpublic string getname return namepublic void setnamestring name thisname namepublic string getdesignation return designationpublic void setdesignationstring designation thisdesignation designationpublic string getskill return skillpublic void setskillstring skill thisskill skillemployeemanagementcontrollerjavacontrollerrequestmappingvalueemppublic class employeemanagementcontroller requestmappingvalueaddemployee methodrequestmethodpost consumestexthtml public void addemployeerequestbody employee employee systemoutprintlnemployee name employeegetname systemoutprintlnemployee designation employeegetdesignation systemoutprintlnemployee skill employeegetskill employeeconverterjavacomponentpublic class employeeconverter extends abstracthttpmessageconverteremployee override protected employee readinternalclass extends employee arg httpinputmessage inputmsg throws ioexception httpmessagenotreadableexception todo autogenerated method stub mapstringstring parammap getpostparameterinputmsg bufferedreader file new bufferedreadernew stringreaderparammapgetxml employee employee null jaxbcontext jaxbcontext try jaxbcontext jaxbcontextnewinstanceemployeeclass unmarshaller jaxbunmarshaller jaxbcontextcreateunmarshaller employee employee jaxbunmarshallerunmarshalfile catch jaxbexception e todo autogenerated catch block eprintstacktrace systemoutprintlnemployee return employee override protected boolean supportsclass type iftypegetsimplenameequalsignorecaseemployee return true return false override protected void writeinternalemployee arg0 httpoutputmessage arg1 throws ioexception httpmessagenotwritableexception todo autogenerated method stub private mapstringstring getpostparameterhttpinputmessage input throws ioexception string payload null string params null bufferedreader buf new bufferedreadernew inputstreamreaderinputgetbody mapstringstring parammap new hashmapstringstring string line whileline bufreadlinenull payload payloadline ifpayloadcontains params payloadsplit forstring param params parammapputparamsplit0paramsplit1 return parammap employeeservletxmlxml version10 encodingutf8beans xmlns xmlnsxsi xmlnscontext xmlnsmvc xmlnsutil xsischemalocation mvcdefaultservlethandler contextcomponentscan basepackagecom mvcannotationdriven mvcmessageconverters bean classcomconverteremployeeconverter mvcmessageconverters mvcannotationdriven bean classorgspringframeworkwebservletviewcontentnegotiatingviewresolver property namemediatypes map entry keyjson valueapplicationjson entry keyxml valuetextxml entry keyhtm valuetexthtml map property property namedefaultcontenttype valuetexthtml bean bean classorgspringframeworkwebservletmvcannotationannotationmethodhandleradapter property namemessageconverters utillist idbeanlist ref beanemployeeconverter utillist property bean bean idemployeeconverter classcomconverteremployeeconverter beanswebxmlxml version10 encodingutf8webapp xmlnsxsi xmlns xmlnsweb 2 5xsd xsischemalocation 2 5xsd idwebapp id version25 thisplaynametestconverterthisplayname welcomefilelist welcomefileindexhtmlwelcomefile welcomefilelist servlet servletnameemployeeservletname servletclassorgspringframeworkwebservletthispatcherservletservletclass loadonstartup1loadonstartup servlet servletmapping servletnameemployeeservletname urlpatternurlpattern servletmappingcontextparam paramnamecontextconfiglocationparamname paramvaluewebinfemployeeservletxmlparamvaluecontextparamlistener listenerclassorgspringframeworkwebcontextcontextloaderlistenerlistenerclasslistenerwebappwhen i use firefox restclient i get response as 415 unsupproted media typei set the contenttype and accept header as textxml in restclient and pass the following xml string in the body as parameterxmlemployeenamejacknamedesignationaccount directordesignationskillcommuicationskillemployeecan somebody help and let me know what changes are required i have also tried to use annotationmethodhandleradapter for registering the message converter,['java'] +620368,switch div from fixed to absolute at bottom of browser im trying to add a footer at the bottom of this content that does not overlay the content but moves it upthe only way i can see it working would be something like when browser is at the bottom remove fixed class on the left red work js fiddle demoupdated js fiddle demohtmldiv idheaderblock headerblock this sits here in the backgrounddivdiv idcontent div idwork this content should be fixed when at the top div div iddescription this content should scroll divdiv end content div idfooter this should appear at the bottomdivcssbody margin 0px padding 0pxheaderblock background green width 100 position fixed zindex 1 height 300px top 0content margintop 300px width 100 position relative zindex 2work background red width 50 height 100vh float left position absolutedescription background blue width 50 height 1200px float right fontsize 30pxfooter background black width 100 height 100px position absolute zindex 3 bottom 0,"['javascript', 'jquery', 'css']" +620439,matplotlib plotting numerous thisconnected line segments with different colors i have a set of data records like thiss1 t1 u1 v1 color1s2 t2 u2 v2 color2sn tn un vn colornin any record the first two values are the endpoints of a line segment the third value is the color of that line segment more specifically sn tn are the xy coordinates of the first endpoint un vn are the xy coordinates of the secondendpoint also color is an rgb with alpha valuein general any two line segments are thisconnected meaning that their endpoints do not necessarily coincidehow to plot this data using matplotlib with a single plot call or as few as possible as there could be potentially thousands of recordsupdatepreparing the data in one big list and calling plot against it is way too slow for example the following code could not finish in a reasonable amount of timeimport numpy as npimport matplotlibpyplot as pltdata for in xrange60 dataappendnprandomrand nprandomrand dataappendnprandomrand nprandomrand dataappendrprint now plotting from now on takes too longpltplotdataprint donepltshowwe need to have another way of plotting the data as quickly as possible as i will be using this in a nearreal time systemupdate 2amazingly enough i was able to speedup the plot rendering by using the none insertion trick as followsimport numpy as npimport matplotlibpyplot as pltfrom timeit import timeitn 60 s nprandomrandn t nprandomrandn you nprandomrandn v nprandomrandnx y for s t u v in zip s t u v xappends xappendu xappendnone yappendt yappendv yappendnoneprint timeitlambdapltplotx y number1this executes in under a second on my machine i still have to figure out how to embed the color values rgb with alpha channel,['python'] +620441,how can i modify stripe checkout to instead send an ajax request i am using stripe and checkout to create a payment form and i want to be able to use checkouts awesome javascript library but i also want to change the form submission from just a normal post to an ajax post so i tried adding a handler to the form element youre supposed to have but my console line was never triggered so it is not submitting using the given form then i tried looking into the code that is brought up when the overlay is triggered it is a bit confusing and i am just wondering if anybody else was able to figure it out or if it is made difficult because it is a security matter stripe pluginform idpayment form methodpost actionurl forprocess payment script src clastripebutton datakeytest key scriptform form submit handlerdocumentreadyfunction payment formsubmitfunctione consolelogprocessing ajax payment return false,['jquery'] +620524,how to goto into different function in c basically i am trying to simulate assembly code in chere is the c codeint main testmain next printfhello worldvoid test goto main nexttrying to compile this code linux 32 bit gcc 463 i got this error error label amain randomtag nexta used but not defineddoes anyone know how to do this kind of interprocedural goto in c thank you,['c'] +620655,can i use a variable template to declare another variable template with variable templates coming in c14 and clang already supporting them and a proposal for standard is same v and likewise type traits i figured being able to make new type traits as follows would be neattemplatetypename tconstexpr bool is const and volatilestdis const vt stdis volatile vtalas this results in errors equivalent to the following sscce this one contains everything mentioned belowinclude type traitstemplatetypename tconstexpr bool is pointerstdis pointertvaluetemplatetypename tconstexpr bool foois pointertint main fooint with the line in main commented clang spits out the followingwarning variable is pointertypeparameter00 has internal linkage but is not definedit looks defined to me note that changing t to int in foo works fine uncommenting the line in main to instantiate foo gives this again t to int works fineerror constexpr variable fooint must be initialized by a constant expressionhowever replacing foo with the following old syntax causes both instances to work fineconstexpr bool foostdis pointertvalueis there something i am missing about variable templates is there a way to build new variable templates with them or am i forced to use the older syntax to build new ones and only enjoy the syntactic sugar when using them for other code,['c++'] +620663,should 34 enums use upper case with underscores as the documentation says an enumeration is a set of symbolic names members bound to unique constant values the pep8 says that constants are usually named as upper case should i use this notation in python 34 enums if yes why the examples in the docs are using lower case,['python'] +620894,laravel 4 class carboncarbon not found i recently added a package to my laravel 4 site and now anything that uses eloquent or at least eloquent with any reference to datetime is showing a 500 error that statesclass carboncarbon not foundi have done everything i can think of including running composer install composer update composer dumpautoload etc i cannot for the life of me figure out why this started happening all of the sudden,['php'] +620923,searching for equivalent of filenotfounderror in python 2 i created a class named options it works fine but not not with python 2and i want it to work on both python 2 and 3the problem is identified filenotfounderror doesn t exist in python 2but if i use ioerror it doesn t work in python 3changed in version 33 environmenterror ioerror windowserror vmserror socketerror selecterror and mmaperror have been merged into oserrorwhat should i do please do not thiscuss my choice of portability i have reasonshere s the codeusrbinpythoncodingutf8option controllerpywalle cyril25012014import jsonimport osclass options options is a class designed to read add and change informations in a json file with a dictionnary in it the entire object works even if the file is missing since it recreates it if present it must respect the json format eg keys must be strings and so on if something corrupted the file just destroy the file or call read file method to remake it def init selfdirectory namecachefile nameoptionsjsonimported default valuesnone json file selfoption file pathospathjoindirectory namefile name selfdirectory namedirectory name selffile namefile name selfparameters json filesort keystrue indent4 separators the default data if imported default values is none default indent 2 selfdefault values translate html level 1 indent sizedefault indent document titletitre else selfdefault valuesimported default values def read fileselfread this key onlyfalse returns the value for the given key or a dictionary if the key is not given returns none if it s impossible try text in fileopenselfoption file pathrread except filenotfounderrornot 2x compatible text in fileif the file is not there we remake one with default values if text in filesame if the file is empty self insert all default values text in fileopenselfoption file pathrread try option dictjsonloadstext in file except valueerror if the json file is broken we remake one with default values self insert all default values text in fileopenselfoption file pathrread option dictjsonloadstext in file if read this key only if read this key only in option dict return option dictread this key only else if the value is not there it should be written for the next time if read this key only in selfdefault values selfadd option to fileread this key onlyselfdefault valuesread this key only return selfdefault valuesread this key only else impossible because there is not default value so the value isn t meant to be here return none else return option dict def add option to fileselfkeyvalueor update adds or updates an optionkey and value to the json file if the option exists in the default values of the object option dictselfread file if key in selfdefault values option dictkeyvalue openselfoption file pathwwrite jsondumpsoption dictsort keystrue indent4 separators def insert all default valuesself recreate json file with default values called if the document is empty or nonexisting or corrupted try openselfoption file pathwwrite jsondumpsselfdefault valuessort keystrue indent4 separators except filenotfounderror osmkdirselfdirectory namecreate the directory if ospathisdirselfdirectory namesucces self insert all default values else printimpossible to write in s and file s not found osgetcwdselfoption file pathdemoif name main option file objectoptions printoption file object doc printoption file objectread file option file objectadd option to filetestthis should have no effect option file objectadd option to filetranslate html level0this should have an effect printvalue of translate html leveloption file objectread filetranslate html level printoption file objectread file,['python'] +620958,is the data stored using nsuserdefaults deleted when the app is updated currently i am creating an app that is storing data using nsuserdefaults so when i upload v1 of the app to the app store and then make a new update for the app v2 is the data stored in nsuseddefaults deleted when the user updates to the new version,"['ios', 'iphone']" +620960,how to set svg width and svg height by percent i create a line with svgbut when i resize my browser the line created with svg not resizedi try to set width the svg in percent but after doing that the line not appear how i can set width of svg by percentsvg height210 width500 line x1380 y120 x2230 y2200 stylestroke rgb234 243 234 strokewidth 5linesvg,['css'] +621006,directives inside nginclude i am building a simple angularjs app and i am trying to implement login without page refresh what i am doing on init the nginclude loads the setsave the setsave got the a fbloginlogin with facebooka in it so when clicked the directive opens a window and when the window is closed it should change the src of the ngincludethe problemwhen the directive is used inside the nginclude nginclude src has default value on init nothing happens no errors in console just nothing but when i put the directive outside the nginclude it is working fine see html code below htmldiv idsetcreator ngcontrollersetctrl div idsavemodal classrevealmodal datareveal a href fblogintestcasea this is working but if the directive is inside nginclude it is not working nginclude srcsavetemplatenginclude a classcloserevealmodal215a divdivdirectiveappdirectivefblogin function return transclude false link functionscope element attrs elementclickfunction var win windowopenauthfacebook popupwindow centerscreentrue var intervalid setintervalfunction if winclosed scopesavetemplate setcontinue scopeapply clearintervalintervalid 100 controllerappcontrollersetctrl scope setholder functionscope setholder scopesavetemplate setsave scopetest loaded and setsaveyou need to be logged in order to save the setbr a fbloginlogin with facebooka,['javascript'] +621014,ngclick not working after compile ngbindhtml i have a directive appdirectivedir functioncompile sce return restrict e link functionscope element attr scopewatchcontentfunction var html scetrustashtmlattrcontent scopealabala compilehtmlscope true template div ngbindhtmlalabaladiv a controllerfunction maincontrollerscope http customservice location sce compile scopeinit function customservicegetsuccessfunctiondata var html scetrustashtmldata dirattrcontent data and on my index page i havediv iddiv ngcontrollermaincontroller classpullright span3 nginitinit dir iddir dirdivmy custom service returns every time a different html containing for examplebutton ngclickclickclick mebuttonwhat i am trying to do is every time when i push a different value in the content of my directive to compile it and put it in my html and handle the click function from my controller because i am new to angularjs i have been struggling with this problem for sometime please help,"['javascript', 'jquery', 'html']" +621028,retrofit post request w basic http authentication cannot retry streamed http body i am using retrofit to do a basic post request and i am providing a basic body for the requestpostrestv1authloginloginresponse loginbody loginrequest loginrequestwhen i am building the interface for retrofit i am providing my own custom okhttpclient and all that i am doing to it is adding my own custom authentication provides singleton public client providesclient okhttpclient httpclient new okhttpclient httpclientsetauthenticatornew okauthenticator override public credential authenticateproxy proxy url url listchallenge challenges throws ioexception return getcredential override public credential authenticateproxyproxy proxy url url listchallenge challenges throws ioexception return getcredential return new okclienthttpclient this works great when i am sending requests directly with okhttp and other get requests with retrofit but when i use retrofit to do a post request i get the following errorcaused by javanethttpretryexception cannot retry streamed http body at comsquareupokhttpinternalhttphttpurlconnectionimplgetresponsehttpurlconnectionimpljava324 at comsquareupokhttpinternalhttphttpurlconnectionimplgetresponsecodehttpurlconnectionimpljava508 at comsquareupokhttpinternalhttphttpsurlconnectionimplgetresponsecodehttpsurlconnectionimpljava136 at retrofitclienturlconnectionclientreadresponseurlconnectionclientjava94 at retrofitclienturlconnectionclientexecuteurlconnectionclientjava49 at retrofitrestadapterresthandlerinvokerequestrestadapterjava357a a a a a a a a a a a a at retrofitrestadapterresthandlerinvokerestadapterjava282a a a a a a a a a a a a at proxy3loginnative methoda a a a a a a a a a a a at comaudaxpathsjobloginjobonruninbackgroundloginjobjava41a a a a a a a a a a a a at comaudaxlibraryjobaxjobonrunaxjobjava25a a a a a a a a a a a a at compathandroidjobqueuebasejobsaferunbasejobjava108a a a a a a a a a a a a at compathandroidjobqueuejobholdersaferunjobholderjava60a a a a a a a a a a a a at compathandroidjobqueueexecutorjobconsumerexecutorjobconsumerrunjobconsumerexecutorjava172a a a a a a a a a a a a at javalangthreadrunthreadjava841i have played around with it if i remove the authentication and point to a server that does not require the authentication then it works fine so i must be sending the informationgetting the authentication challenge requestresponding to the challenge requesttrying to resend the request again and then the error is being thrownnot sure how to get around this any help would be wonderful,['android'] +621031,unicode problems in c but not c i am trying to write unicode strings to the screen in c on windows i changed my console font to lucida console and i set the output to cp utf8 aka 65001i run the following codeinclude stdioh notice this header fileinclude windowshinclude iostreamint main setconsoleoutputcpcp utf8 const char text 34nn n printfsn textit prints out just finehowever if i doinclude cstdio the c version of the headerinclude windowshinclude iostreamint main setconsoleoutputcpcp utf8 const char text 34nn n printfsn textit prints i12i12i12i12i12i12i12i12i12i12i12i12i have no clue whyanother thing is when i doinclude windowshinclude iostreamint main stduint32 t oldcodepage getconsoleoutputcp setconsoleoutputcpcp utf8 stdstring text u8 34nn n stdcouttextn setconsoleoutputcpoldcodepagei get the same output as above nonworking outputusing printf on the stdstring it works fine thoughinclude stdiohinclude windowshinclude iostreamint main stduint32 t oldcodepage getconsoleoutputcp setconsoleoutputcpcp utf8 stdstring text u8 34nn n printfsn textc str setconsoleoutputcpoldcodepagebut only if i use stdioh and not cstdioany ideas how i can use stdcout how can i use cstdio as wellwhy does this happen is not cstdio just a c version of stdiohedit i have just triedinclude iostreaminclude iohinclude fcntlhint main setmode filenostdout o u8text stdwcout l 34nn n stdendland yes it works but only if i use stdwcout and wide strings i would really like to avoid widestrings and the only solution i see so far is the cprintf lso the question still stands,"['c++', 'c']" +621088,how to chain execution of array of functions when every function returns deferredpromise i have created my first deferred object in nodejs using deferred module and it works great when i pass result to next function and trigger resolve and rejecthow to chain execution of array of functions when every function returns deferredpromise i have like input parameters array of functions and input parameter for first function and every next function get parameter from previousit works like f1100thenf2thenf3 but how when i have and number of functions,['javascript'] +621124,class not found exception in mapreduce wordcount job i am trying to run a wordcount job in hadoopbut always getting a class not found exceptioni am posting the class that i wrote and the command i using to run the jobimport javaioioexceptionimport javautilimport orgapachehadoopfspathimport orgapachehadoopconfimport orgapachehadoopioimport orgapachehadoopmapreduceimport orgapachehadoopmapreducelibinputfileinputformatimport orgapachehadoopmapreducelibinputtextinputformatimport orgapachehadoopmapreduceliboutputfileoutputformatimport orgapachehadoopmapreduceliboutputtextoutputformat public class wordcount public static class map extends mapperlongwritable text text intwritable private final static intwritable one new intwritable1 private text word new text public void maplongwritable key text value context context throws ioexception interruptedexception string line valuetostring stringtokenizer tokenizer new stringtokenizerline while tokenizerhasmoretokens wordsettokenizernexttoken contextwriteword one public static class reduce extends reducertext intwritable text intwritable public void reducetext key iterableintwritable values context context throws ioexception interruptedexception int sum 0 for intwritable val values sum valget contextwritekey new intwritablesum public static void mainstring args throws exception configuration conf new configuration job job new jobconf wordcount jobsetoutputkeyclasstextclass jobsetoutputvalueclassintwritableclass jobsetmapperclassmapclass jobsetreducerclassreduceclass jobsetinputformatclasstextinputformatclass jobsetoutputformatclasstextoutputformatclass fileinputformataddinputpathjob new pathargs0 fileoutputformatsetoutputpathjob new pathargs1 jobwaitforcompletiontrue jobsetjarbyclasswordcountclass the wordcountjar is exported to my downloads folderand this is the command i use to run the job jeetjeetvostro2520downloads hadoop jar wordcountjar orggammawordcount userjeetgettygettysburgtxt userjeetgettyoutin this case my mapreduce job is started but it is ending in the middle of the processprinting the exception tree 140127 131602 warn mapredjobclient use genericoptionsparser for parsing the arguments applications should implement tool for the same140127 131602 warn mapredjobclient no job jar file set user classes may not be found see jobconfclass or jobconfsetjarstring140127 131602 info inputfileinputformat total input paths to process 1140127 131602 info utilnativecodeloader loaded the nativehadoop library140127 131602 warn snappyloadsnappy snappy native library not loaded140127 131603 info mapredjobclient running job job 201401271247 01140127 131604 info mapredjobclient map 0 reduce 0140127 131611 info mapredjobclient task id attempt 201401271247 01 m 0 0 status failed javalangruntimeexception javalangclassnotfoundexception orggammawordcountmapat orgapachehadoopconfconfigurationgetclassconfigurationjava849at orgapachehadoopmapreducejobcontextgetmapperclassjobcontextjava199at orgapachehadoopmapredmaptaskrunnewmappermaptaskjava719at orgapachehadoopmapredmaptaskrunmaptaskjava370at orgapachehadoopmapredchild4runchildjava255at javasecurityaccesscontrollerdoprivilegednative methodat javaxsecurityauthsubjectdoassubjectjava415at orgapachehadoopsecurityusergroupinformationdoasusergroupinformationjava1149at orgapachehadoopmapredchildmainchildjava249 caused by javalangclassnotfoundexception orggammawordcountmapat javaneturlclassloader1runurlclassloaderjava366at javaneturlclassloader1runurlclassloaderjava355at javasecurityaccesscontrollerdoprivilegednative methodat javaneturlclassloaderfindclassurlclassloaderjava354at javalangclassloaderloadclassclassloaderjava425at sunmisclauncherappclassloaderloadclasslauncherjava308at javalangclassloaderloadclassclassloaderjava358at javalangclassforname0native methodat javalangclassfornameclassjava270at orgapachehadoopconfconfigurationgetclassbynameconfigurationjava802at orgapachehadoopconfconfigurationgetclassconfigurationjava847 8 more140127 131616 info mapredjobclient task id attempt 201401271247 01 m 0 1 status failedjavalangruntimeexception javalangclassnotfoundexception orggammawordcountmapat orgapachehadoopconfconfigurationgetclassconfigurationjava849at orgapachehadoopmapreducejobcontextgetmapperclassjobcontextjava199at orgapachehadoopmapredmaptaskrunnewmappermaptaskjava719at orgapachehadoopmapredmaptaskrunmaptaskjava370at orgapachehadoopmapredchild4runchildjava255at javasecurityaccesscontrollerdoprivilegednative methodat javaxsecurityauthsubjectdoassubjectjava415at orgapachehadoopsecurityusergroupinformationdoasusergroupinformationjava1149at orgapachehadoopmapredchildmainchildjava249 caused by javalangclassnotfoundexception orggammawordcountmapat javaneturlclassloader1runurlclassloaderjava366at javaneturlclassloader1runurlclassloaderjava355at javasecurityaccesscontrollerdoprivilegednative methodat javaneturlclassloaderfindclassurlclassloaderjava354at javalangclassloaderloadclassclassloaderjava425at sunmisclauncherappclassloaderloadclasslauncherjava308at javalangclassloaderloadclassclassloaderjava358at javalangclassforname0native methodat javalangclassfornameclassjava270at orgapachehadoopconfconfigurationgetclassbynameconfigurationjava802at orgapachehadoopconfconfigurationgetclassconfigurationjava847 8 more 140127 131620 info mapredjobclient task id attempt 201401271247 01 m 0 2 status failed javalangruntimeexception javalangclassnotfoundexception orggammawordcountmapat orgapachehadoopconfconfigurationgetclassconfigurationjava849at orgapachehadoopmapreducejobcontextgetmapperclassjobcontextjava199at orgapachehadoopmapredmaptaskrunnewmappermaptaskjava719at orgapachehadoopmapredmaptaskrunmaptaskjava370at orgapachehadoopmapredchild4runchildjava255at javasecurityaccesscontrollerdoprivilegednative methodat javaxsecurityauthsubjectdoassubjectjava415at orgapachehadoopsecurityusergroupinformationdoasusergroupinformationjava1149at orgapachehadoopmapredchildmainchildjava249 caused by javalangclassnotfoundexception orggammawordcountmapat javaneturlclassloader1runurlclassloaderjava366at javaneturlclassloader1runurlclassloaderjava355at javasecurityaccesscontrollerdoprivilegednative methodat javaneturlclassloaderfindclassurlclassloaderjava354at javalangclassloaderloadclassclassloaderjava425at sunmisclauncherappclassloaderloadclasslauncherjava308at javalangclassloaderloadclassclassloaderjava358at javalangclassforname0native methodat javalangclassfornameclassjava270at orgapachehadoopconfconfigurationgetclassbynameconfigurationjava802at orgapachehadoopconfconfigurationgetclassconfigurationjava847 8 more 140127 131626 info mapredjobclient job complete job 201401271247 01 140127 131626 info mapredjobclient counters 7 140127 131626 info mapredjobclient job counters 140127 131626 info mapredjobclient slots millis maps20953 140127 131626 info mapredjobclient total time spent by all reduces waiting after reserving slots ms0 140127 131626 info mapredjobclient total time spent by all maps waiting after reserving slots ms0 140127 131626 info mapredjobclient launched map tasks4 140127 131626 info mapredjobclient datalocal map tasks4 140127 131626 info mapredjobclient slots millis reduces0 140127 131626 info mapredjobclient failed map tasks1somebody please please help i think i am very close of it,['java'] +621143,greendao not generating foreign key constraint in table when i create a bidirectional 1n relationship as shown below the generator does not use any foreign key constraints on the tableentity customer schemaaddentitycustomercustomeraddidpropertycustomeraddstringpropertynamenotnullentity order schemaaddentityorderordersettablenameorders order is a reserved keywordorderaddidpropertyproperty orderdate orderadatepropertydategetpropertyproperty customerid orderaddlongpropertycustomeridnotnullgetpropertyorderaddtoonecustomer customeridcustomeraddtomanyorder customeridis this normal is it supposed to generate foreign key constraints in the table or is it only enforced at runtime through code,['android'] +621170,angularjs nginclude ngcontroller and scope not binding i have the following main viewdiv ngincludeotionshtmldivand optionshtml has the followingdiv ngcontrolleroptionscontrolleroptionsdivinput typetext ngmodelkeyword valuekeyword button ngclicksearchsearchbuttonbut keyword is not binding to the scope in optionscontrollerappcontrolleroptionscontroller scope functionscope scopekeyword all scopesearch function consoleloghello when i click on the button i do not see hello and the keyword all does not appear in the input texti tried moving the ngcontroller part as followsdiv ngcontrolleroptionscontroller ngincludeotionshtmldivand things work as expectedi read through the answers in angularjs losing scope when using nginclude and i think my problem is related but just need some more explanation to undertstand whats going on,['javascript'] +621226,proper way to create unique ptr that holds an allocated array what is the proper way to create an unique ptr that holds an array that is allocated on the free store visual studio 2013 supports this by default but when i use gcc version 481 on ubuntu i get memory leaks and undefined behaviourthe problem can be reproduced with this code include memoryinclude stringhusing namespace stdint main unique ptrunsigned char testdatanew unsigned char160 memsettestdataget0x120 return 0valgrind will give this output3894 1 errors in context 1 of 13894 mismatched free delete delete 3894 at 0x4c2badc operator deletevoid in usrlibvalgrindvgpreload memcheckamd64linuxso3894 by 0x400aef stddefault deleteunsigned charoperatorunsigned char const unique ptrh673894 by 0x4009d0 stdunique ptrunsigned char stddefault deleteunsigned char unique ptr unique ptrh1843894 by 0x4007a9 main testcpp193894 address 0x5a1a040 is 0 bytes inside a block of size 160 allocd3894 at 0x4c2afe7 operator newunsigned long in usrlibvalgrindvgpreload memcheckamd64linuxso3894 by 0x40075f main testcpp15,['c++'] +621234,java equivalent of net rsacryptoserviceprovider with sha1 i have the following data signing code in crsacryptoserviceprovider rsa new rsacryptoserviceproviderstring privatekeytext rsakeyvaluemodulusdrsakeyvaluersafromxmlstringprivatekeytextstring data my data byte signedbytedata rsasigndataencodingutf8getbytesdata new sha1cryptoserviceproviderand i want reproduce the same code in java androidstring moduluselem string expelem byte expbytes base64decodeexpelem base64defaultbyte modulusbytes base64decodemoduluselem base64defaultbiginteger modulus new biginteger1 modulusbytesbiginteger exponent new biginteger1 expbytestry keyfactory factory keyfactorygetinstancersa cipher cipher ciphergetinstancersaecbpkcs1padding string data my data messagedigest md messagedigestgetinstancesha1 byte hasheddata mddigestdatagetbytesutf8 rsapublickeyspec pubspec new rsapublickeyspecmodulus exponent publickey publickey factorygeneratepublicpubspec cipherinitcipherencrypt mode publickey byte signedbytedata cipherdofinalhasheddata catch exception ebut i get mismatched output byte arrays where am i wrong and what should be the transformation used in ciphergetinstance,"['c#', 'java', 'android', '.net']" +621260,print all request log called from volley library i am using volley library to call rest web services and i am using post and get but i do not know why i am sending post and it received as post from the server side so i want to print all requests that are done bu this library like 30jul2013122809 0 post app http11 302 030jul2013122809 0 get app http11 200 0how can i do that i debugged volley and i do not know why the method becomes get in the request variable the mmethod is 1 and in the connection variable the method becomes get i thiscovered that there is a redirection from the server side is it possible that i know if there is a redirection or not from volley,"['java', 'android']" +621284,entity framework memory not released i am using a very simple aspnet mvc application with entity framework 602 net 451public class homecontroller controller public actionresult index int count using var db new localcontext count dbcounterscount return viewcount public class counter public int id get set public class localcontext dbcontext public dbsetcounter counters get set if i do a load test on it i eventually get an out of memory exception tinyget srvlocalhost portport urihomeindex threads30 loop50 in performance monitor i see the generation 2 heap steadily grow if i use a smaller loop value say 500 the size grows until tinyget stops then the heap size stays the same for at least 20 minutes after that i stopped the serverwhat am i doing wrongeditso i tried simon mouriers suggestion and left out the ef code then i do not have memory problems so i thought maybe if i use release instead of debug it will make a difference and it did memory was released after a while and i could put high load on the site then i switched back to debug to see if i could get more info and even in debug mode no problems anymore fml i worked a day on it and now i cannot reproduce it anymore,['c#'] +621316,boostlog to file and stdout simultaneously i have used boostlog successfully to log to stdout using the trivial macros or to log to a file basically following the steps in the tutorialhow would we configure to log to a file and stdout simultaneously this is a common use case in our setup when we want to have both a log file and also all the output that goes to the log on the consoleany input appreciated,['c++'] +621326,activity not closing on back press when theme is themenothisplay i am setting activity theme to themenothisplay but when it open but on press back button activity not closingdestroying it should closedestroy on back pressguys help me why this is so and any solution to resolve thispublic class mainactivity extends activity tag of the activity private static string tag mainactivity override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main databasemanagerinitthis nfciitem mnfcitem new nfciitem mnfcitemsetserialnumber1 databasemanagergetinstanceaddwishlistmnfcitem final listnfciitem wishlists databasemanagergetinstancegetallnfcserialnumber logvtag wishliststostring override public boolean oncreateoptionsmenumenu menu getmenuinflaterinflatermenumain menu return true androidmanifestxmlactivity androidnamecomexampleappdemomainactivity androidlabelstringapp name androidthemeandroidstylethemenothisplay intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilteractivity,['android'] +621331,inplace sort of sublist is it possible obviously x11sort does not work because the slice is a copy current workaround x 4 3 1 2 5 s slice1 1 xs sortedxs x4 1 2 3 5can i somehow get a view on a python list,['python'] +621373,how to format gps latitude and longitude in androidjava when you get the current latitude and longitude using the function getlatitude etc you get the coordinates in decimal formatlatitude 243454523 longitude 10123450i want to get this into degrees and decimal minutes to look something like thislatitude 40a42a251a3 and longitude 74a00a221a3 w,['android'] +621374,django orm insert none datetime as 0 into mysql i have a mysql database that is used by another application besides django that application uses 0 0 as default value for datetimesdjango v155 interprets 0 0 datetime as none when reading the database and none as null when writing into the database this causes an error since the database defines the field as not null manually settingmodeldatetime 0 0does not work because django feels that this is an invalid datehow do i create a custom datetime field which inserts none as 0 0,"['python', 'mysql']" +621423,why the terminal shows a b c d when pressing the arrow keys in ubuntu i have written a tiny program in ansi c on windows first and i compiled it on ubuntu with the builtin gcc nowthe program is simpleread the line from console with scanfanalyze the string and calculatebut something weird happened when i want to move the cursor it will add four characterspress up will be apress dn will be bpress rt will be cpress lt will be dhow to avoid thiswhy it will print the 4 characters instead of moving cursor,['c'] +621468,itmstransporter how to submit an uploaded inapp purchase for apple review without itunes connect i currently use itmstransporter appleas commandline tool for verify and uploadapp store packages itmsp that is contain metadata of a new inapp purchase to the app storebut i am forced to submit this inapp already uploaded for review in itunes connect manually before apple checksis there a way to submit inapp purchase for review via itmstransporter,['ios'] +621519,java xsd marshalling jre bug my fault or xsd issues i am running into a problem while marshalling a jaxb model tree to a xml filei created those model classes using xjc i cannot modify these xml schemas they are defined externally similar to this question which lacks for answersthe xml schema files seems to be valid according xjc and other xml toolsi am asking whether this is a javajre bug ori am doing something wrong or if the schema files are somewhat errornousand how to resolve this issuethe exception which i get iscomsunistackinternalsaxexception2 commypackagea is substituting commypackagebasetype but commypackagea is bound to an anonymous type at comsunxmlinternalbindv2runtimexmlserializerreporterrorxmlserializerjava237 at comsunxmlinternalbindv2runtimexmlserializerchildasxsitypexmlserializerjava652 at comsunxmlinternalbindv2runtimepropertysingleelementnodepropertyserializebodysingleelementnodepropertyjava143 at comsunxmlinternalbindv2runtimeclassbeaninfoimplserializebodyclassbeaninfoimpljava343 at comsunxmlinternalbindv2runtimexmlserializerchildasxsitypexmlserializerjava685 at comsunxmlinternalbindv2runtimepropertyarrayelementnodepropertyserializeitemarrayelementnodepropertyjava54 at comsunxmlinternalbindv2runtimepropertyarrayelementpropertyserializelistbodyarrayelementpropertyjava157 at comsunxmlinternalbindv2runtimepropertyarrayerpropertyserializebodyarrayerpropertyjava144 at comsunxmlinternalbindv2runtimeclassbeaninfoimplserializebodyclassbeaninfoimpljava343 at comsunxmlinternalbindv2runtimeclassbeaninfoimplserializebodyclassbeaninfoimpljava335 at comsunxmlinternalbindv2runtimexmlserializerchildasxsitypexmlserializerjava685 at comsunxmlinternalbindv2runtimepropertysingleelementnodepropertyserializebodysingleelementnodepropertyjava143 at comsunxmlinternalbindv2runtimeclassbeaninfoimplserializebodyclassbeaninfoimpljava343 at comsunxmlinternalbindv2runtimeclassbeaninfoimplserializebodyclassbeaninfoimpljava335 at comsunxmlinternalbindv2runtimexmlserializerchildasxsitypexmlserializerjava685 at comsunxmlinternalbindv2runtimepropertysingleelementnodepropertyserializebodysingleelementnodepropertyjava143 at comsunxmlinternalbindv2runtimeclassbeaninfoimplserializebodyclassbeaninfoimpljava343 at comsunxmlinternalbindv2runtimexmlserializerchildasxsitypexmlserializerjava685 at comsunxmlinternalbindv2runtimepropertysingleelementnodepropertyserializebodysingleelementnodepropertyjava143 at comsunxmlinternalbindv2runtimeclassbeaninfoimplserializebodyclassbeaninfoimpljava343 at comsunxmlinternalbindv2runtimexmlserializerchildasxsitypexmlserializerjava685 at comsunxmlinternalbindv2runtimepropertysingleelementnodepropertyserializebodysingleelementnodepropertyjava143 at comsunxmlinternalbindv2runtimeelementbeaninfoimpl1serializebodyelementbeaninfoimpljava146 at comsunxmlinternalbindv2runtimeelementbeaninfoimpl1serializebodyelementbeaninfoimpljava116 at comsunxmlinternalbindv2runtimeelementbeaninfoimplserializebodyelementbeaninfoimpljava318 at comsunxmlinternalbindv2runtimeelementbeaninfoimplserializerootelementbeaninfoimpljava325 at comsunxmlinternalbindv2runtimeelementbeaninfoimplserializerootelementbeaninfoimpljava61 at comsunxmlinternalbindv2runtimepropertyarrayreferencenodepropertyserializelistbodyarrayreferencenodepropertyjava103 at comsunxmlinternalbindv2runtimepropertyarrayerpropertyserializebodyarrayerpropertyjava144 at comsunxmlinternalbindv2runtimeclassbeaninfoimplserializebodyclassbeaninfoimpljava343 at comsunxmlinternalbindv2runtimexmlserializerchildasxsitypexmlserializerjava685 at comsunxmlinternalbindv2runtimepropertysingleelementnodepropertyserializebodysingleelementnodepropertyjava143 at comsunxmlinternalbindv2runtimeclassbeaninfoimplserializebodyclassbeaninfoimpljava343 at comsunxmlinternalbindv2runtimexmlserializerchildasxsitypexmlserializerjava685 at comsunxmlinternalbindv2runtimepropertyarrayelementnodepropertyserializeitemarrayelementnodepropertyjava54 at comsunxmlinternalbindv2runtimepropertyarrayelementpropertyserializelistbodyarrayelementpropertyjava157 at comsunxmlinternalbindv2runtimepropertyarrayerpropertyserializebodyarrayerpropertyjava144 at comsunxmlinternalbindv2runtimeclassbeaninfoimplserializebodyclassbeaninfoimpljava343 at comsunxmlinternalbindv2runtimexmlserializerchildasxsitypexmlserializerjava685 at comsunxmlinternalbindv2runtimeelementbeaninfoimpl1serializebodyelementbeaninfoimpljava141 at comsunxmlinternalbindv2runtimeelementbeaninfoimpl1serializebodyelementbeaninfoimpljava116 at comsunxmlinternalbindv2runtimeelementbeaninfoimplserializebodyelementbeaninfoimpljava318 at comsunxmlinternalbindv2runtimeelementbeaninfoimplserializerootelementbeaninfoimpljava325 at comsunxmlinternalbindv2runtimeelementbeaninfoimplserializerootelementbeaninfoimpljava61 at comsunxmlinternalbindv2runtimexmlserializerchildasrootxmlserializerjava483 at comsunxmlinternalbindv2runtimemarshallerimplwritemarshallerimpljava308 at comsunxmlinternalbindv2runtimemarshallerimplmarshalmarshallerimpljava236 at javaxxmlbindhelpersabstractmarshallerimplmarshalabstractmarshallerimpljava95java 7 update 45,['java'] +621554,how to replace all special character into a string using c i would like to replace all special characters in a string with a comma for example hellohellohellohellothe output hellohellohellohelloi do not known how to use regexp in c can i do this work using regexp in c,['c#'] +621593,is the as operator with a nullable value type unnecessarily slow consider this codestatic void fillusingasnullable int arr new int1 24 var sw systemdiagnosticsstopwatchstartnew for int i 0 i arrlength i arri getobject as int consolewriteline0n0 swelapsedticksstatic void fillusingowncode int arr new int1 24 var sw systemdiagnosticsstopwatchstartnew for int i 0 i arrlength i object temporary getobject arri temporary is int inttemporary null consolewriteline0n0 swelapsedticksstatic object getobjectuncomment only one return new object return 42 return nullas far as i can see the methods fillusingasnullable and fillusingowncode should be equivalentbut it looks like the own code version is clearly fasterthere are 2 choices for compiling x86 or x64 and 2 choices for compiling debug or release optimizations and 3 choices for what to return in getobject method as far as i can see in all of these 223 12 cases the own code version is significantly faster than the as nullable versionthe question is as with nullable unnecessarily slow or am i missing something here quite likelyrelated thread performance surprise with aasa and nullable types,['c#'] +621626,force a 3rd party assembly to use another version of another assembly i am running integration tests and when i reach that line of code webapidependencyresolverconfigregisterconfig uses the autofac container insidei get this exceptioncould not load file or assembly systemwebhttp version50 cultureneutral publickeytoken31bf3856ad364e35 or one of its dependencies the located assemblys manifest definition does not match the assembly reference exception from hresult 0x80131040systemwebhttp version50 cultureneutral publickeytoken31bf3856ad364e35fusionlog prebind state information log thisplayname systemwebhttp version50 cultureneutral publickeytoken31bf3856ad364e35 fullyspecifiedlog appbase filectlptlpapiintegrationtestsbindebuglog initial privatepath nullcalling assembly autofacintegrationwebapi version30 cultureneutral publickeytoken17863af14b0044dalog this bind starts in default load contextlog using application configuration file ctlptlpapiintegrationtestsbindebugtlpapiintegrationtestsdllconfiglog using host configuration file log using machine configuration file from cwindowsmicrosoftnetframework64v4030319configit seems the autofac web api integration works only up to web api 20when i use the web api 21 which does not reference the systemwebhttp 500 anymore but instead the 510 then it does not work anymorehow can i tell the autofac to use the systemwebhttp 510 version and not 500 i put this in the appconfig of my integration test and api projectruntime assemblybinding xmlnsurnschemasmicrosoftcomasmv1 dependentassembly assemblyidentity namesystemwebhttp publickeytoken32ab4ba45e0a69a1 cultureneutral bindingredirect oldversion50 newversion5100 dependentassembly assemblybinding runtimebut it did not workanother thing that is very odd is that i have read that using net 451 this redirection assembly stuff is done automatically but its not happening,['c#'] +621683,do you cache properties in local variables consider the class foopublic class foo private double size public double getsize return thissize always o1 foo has a property called size which is frequently accessed but never modified by a given method i have always cached a property in a variable whenever it is accessed more than once in any method because someone told me so without giving it much thought iepublic void testfoo foo double size foogetsize cache it or not size will be referenced in several places later onis this worth it or an overkill if i do not cache it are modern compilers smart enough to cache it themselves,['java'] +621691,rails 4 before validation on create or on save i am having a case which is getting around my headi have an image model which i only want to save if it gets uploaded i also need some information coming from the upload to validate the imagelike height and width but i want only the upload to happen if somebody is trying to save the file the image for the first timeso i thought the best option would be to have a before validation but i would like it to run only on savemy code is on this gist so the weird part is this on save and on create have really weird behaviours or at least not what i expectedwhen i put it as on save if i try to do an imagesave on a test i can see my before validation callbacks are not ranif i put on create is ran in every situation is does not matter if i ran imagesave imagecreate or imagevalidso i am guessing this is either not working or i am misunderstanding the goal of those on settingsps my validation on create also occurs in every situation save create or validlet me know if anybody ran into the same or knows why is not supposed to work like this,['ruby-on-rails'] +621821,class hierarchy of shopping cart price rules class mage salesrule model validator has an object of salesrulerule collection and that object calls a function validate of class mage salesrule model rule condition product found what i did not understand is how the object of salesrulerule collection is related to found class and if we add any other function to this class and try to access it will throw an exception undefined function i just want to understand whats going on behind the scenesmage salesrule model rule condition product found extends the class mage salesrule model rule condition product combine but when from process function of the mage salesrule model validator called it calls the validate function of the found class mage salesrule model validator object call to processtry validator magegetmodelmodulevalidator initcustomergetwebsiteid customergroupid catch exception e magelogexception e in class on line v validatorprocessquoteand the process function of mage salesrule model validator which calls the validate function of found classpublic function process quote quote quote customersession magegetsingletoncustomersession foreach this rules as rule if rulegetisvalid false continue if rulegetisvalid true ruleafterload if rulevalidatequote quote does not meet rules conditions call foundphp rulesetisvalidfalse continue rulesetisvalidtrue passed all validations remember to be valid return thisand the validate function of found class public function validatevarien object object called form validatorphp all thisgetaggregator all true boolthisgetvalue found false count countobjectgetallitems i 0 foreach objectgetallitems as item found all true false foreach thisgetconditions as cond validated condvalidateitem call to productphps function validate ifvalidated this productid itemgetproductid ifi count if all validated found false break elseif all validated found true break 2 ifi count if found true break i i 1 return falsenow what i did not understand is if i write any other function in found class let it be public function foo and try to call it from process function of class validator like rulefooit will throw an exception undefined functioni just want to know the reason why i cannot write any function in found class and call like processthanks,['php'] +621897,android change height of selected tab in tabwidget i want to change the height of the selected tab within the tabwidget as shown in the image belowi used approach i used two images first image have transparent part on top of that and second is full imageon tab selected i changed first image with second one but this approach does not work in all device we have to create images with equal height and also convert to nine patch of eachthe figure is shown what i exactly neededenter image description here1tabhosttabspec spec mtabhostnewtabspecappconstantstab a specsetcontentnew tabhosttabcontentfactory public view createtabcontentstring tag return findviewbyidridrealtabcontent specsetindicatorcreatetabviewrdrawablehometabselectionstyle applied here on each tab mtabhostaddtabspec spec mtabhostnewtabspecappconstantstab b specsetcontentnew tabhosttabcontentfactory public view createtabcontentstring tag return findviewbyidridrealtabcontent specsetindicatorcreatetabviewrdrawablerealtabselection mtabhostaddtabspec spec mtabhostnewtabspecappconstantstab c specsetcontentnew tabhosttabcontentfactory public view createtabcontentstring tag return findviewbyidridrealtabcontent specsetindicatorcreatetabviewrdrawabletopnewwsselection mtabhostaddtabspec spec mtabhostnewtabspecappconstantstab d specsetcontentnew tabhosttabcontentfactory public view createtabcontentstring tag return findviewbyidridrealtabcontent specsetindicatorcreatetabviewrdrawabletreadingselection mtabhostaddtabspechometabselectionxml in drawable which is used for all different tab selectionxml version10 encodingutf8 selector xmlnsandroid item androidstate selectedtrue androiddrawabledrawablehomeselected full imageitem androidstate selectedfalse androiddrawabledrawablehomenormal image with some portion transparent on top of thatselectorlayout tabhost xmlnsandroid androididandroididtabhost androidlayout widthfill parent androidlayout heightfill parent linearlayout androidlayout widthfill parent androidlayout heightfill parent androidorientationvertical framelayout androididandroididtabcontent androidlayout widthdimenfr layout width androidlayout heightdimenfr layout height androidlayout weight0 framelayout androididandroididrealtabcontent androidlayout widthfill parent androidlayout heightdimenfr layout height androidlayout weight1 tabwidget androididandroididtabs androidlayout widthfill parent androidlayout heightdimenhdpi tab layout height androidlayout weight0 androiddividerdrawabletab bg androidbackgroundandroidcolortransparent androiddividerpaddingdimentab divider padding androidorientationhorizontal linearlayouttabhost,['android'] +621901,cannot include both files winsock2 windowsh i am having a problem including both filesnow i know i need to either include winsock2 first then windowsh or simply putdefine win32 lean and meanbut i am still having problemsi have a header file that is called xsh which looks like thisifndef xs hdefine xs hinclude winsock2hinclude ws2tcpiphinclude windowshendifand i am including xsh in the header clienthclienth include is looks like this ifndef client hdefine client hinclude xshxsh is my only include in clienth yet i still get errors and as you can see winsockis included before windowshi am getting about 78 errors here are some of them error 90 error c3861 wsasetlasterror identifier not found cprogram files x86windows kits80includeumws2tcpiph 703error 61 error c2375 wsastartup redefinition different linkage cprogram files x86windows kits80includeumwinsock2h 2296error 49 error c2375 send redefinition different linkage cprogram files x86windows kits80includeumwinsock2h 2026how can i solve this issuethanksedit i have tried to use define winsockapi aswell though it did not resolve my problemsi have winsock first then windowsh though it still does the error for me,"['c++', 'c']" +621973,difference between class and class class class the following excerpt from the primefaces documentation makes it seem as there is a difference between the two selectors described in the titleuiwidget uiwidget uiwidget fontsize 90 importantcan someone explain the significance of the second selector uiwidget uiwidget to me i understand that it matches elements of class uiwidget that are themselves children of other elements of the same class but wouldnt those already be selected by the first selector,['css'] +621978,how to uploadshare video on facebook i am making a test app through that i want to post video on facebook i am using latest sdk of facebook but i am not able to post it on facebookmy code is as belownsdictionary parameters nsdictionary dictionarywithobjectvideodata forkeycareappdemomovfbrequest request fbrequest requestwithgraphpathmevideos parametersparameters httpmethodpostrequest startwithcompletionhandlerfbrequestconnection connection id result nserror error nslogresult error result error please help me to post video on facebook via my app,"['ios', 'iphone']" +622052,securityexception during executing jnlp file missing required permissions manifest attribute in main jar os windows 7 64 bitjava jdk170 51i have a jnlp file when i double click on this exception is occurred as belowapplication error unable to launch the applicationexception javalangsecurityexception missing required permissions manifest attribute in main jar,['java'] +622167,chrome cannot load web worker i am working on a project that uses a web workerin my head section i have this codevar worker new workerworkerjs more codethis works fine in safari but chrome reports the following erroruncaught securityerror failed to create a worker script at pathworkerjs cannot be accessed from origin nullwhy does this work perfectly in safari but not chrome how do i fix thisthank you,['javascript'] +622213,monitortryenter does not work part of my codebehindobject sync new objectprivate async void onkeydownobject sender keyeventargs e if monitortryenter sync return tracewritetaken await taskdelaytimespanfromseconds5 tracewriteline done monitorexit syncoutput pressing several times in less than 5 secondstakentakentaken donedonedonehowcome the sync lock is never being taken why,['c#'] +622287,subprocesspopen using relative paths the docs for popen mention that you cannot specify your executable path relative to the change working directory kwarg if cwd is not none the childas current directory will be changed to cwd before it is executed note that this directory is not considered when searching the executable so you canat specify the programas path relative to cwdbut pythons behaviour on my system seems to directly contradict this claimwimsdfa100461ctmp mkdir awimsdfa100461ctmp cp binls tmpamy lswimsdfa100461ctmp mkdir bwimsdfa100461ctmp touch tmpbpotatowimsdfa100461ctmp cd homewimwimsdfa100461c pythonpython 275 default sep 19 2013 134849 gcc 481 on linux2type help copyright credits or license for more information from subprocess import check output check outputamy ls cwdtmpbpotaton check outputamy lsoserror errno 2 no such file or directoryis using relative paths to cwd something that is platform dependent and should not be relied upon or is this a documentation bug this question spawns from a comment by glglgl here,['python'] +622293,c11 nontype template parameter bundle expansion while working with c11 template parameter bundles i came up with the code belowinclude cstdiostatic void testfuncint i1 int i2 printftestfuncd dn i1 i2template size t indices void wrapper testfuncindicesint mainint argc char argv wrapper1 2 return 0an attempt to compile this with g482 resulted in a too few arguments to function avoid testfuncint inta error is this no valid c or does g just not yet implement this kind of nontype template parameter bundle usage,['c++'] +622331,how to increase consistency of android geofence enterexit notifications i am using the built in geofence apis play services and have been having mixed results it looks like after setting a geofence the notifications for enteringexiting are very inconsistent even when gps is on with an uptodate location locationclient connected running in the background i started monitoring polling location changes and thistances in a debug text field and saw that even when based on the location registered by the device and the location of the geofence i am technically insideoutside of the geofence notifications are sometimes triggered and sometimes not any way to make this more predictable i am almost tempted to abandon this api and implement my own battery draining geofences based on polling of device location,['android'] +622480,what is the difference between before and beforeeach what specifically is the difference between mochas before and beforeeach same question for after and aftereachi assume before runs once per describe block and beforeeach runs once per test it block is that trueand when would i choose to use one over the other,['javascript'] +622489,uisplitviewcontroller static master table view and multiple detail view controller i am trying to create an app which will have a similar interface to ioss settings app and i am a bit lost on how to proceedbasically i plan to make the master view a static table view and each of the rows in that static table view has their own detail view controlleri currently made my master static table view via storyboard how would i make each of the row when tapped show their respective detail view controllers on the detail view i would like to know whats the best way of proceeding in this situationi have look through the net for tutorials but only saw dynamic master table view with only 1 detail view controller tutorials and they used delegates to hook up the left and right view controllers but as for me i do not have a model object as i am using a static table viewi know how to do this programmatically hooking up the left and right views but i plan to use storyboards for this since i have multiple static table views that are the detail views of the rows in my master table view i do not know how to do it with storyboards,['objective-c'] +622490,how do you use jshint and browserify together i am attempting to build a project using angular and browserify my controllersjs file looks like thisuse strictmoduleexportstestcontroller functionscope scopemessage controller 1 consolelog hello as you may expect that generates three linting errorsuse the function form of strictmodule is not definedconsole is not definedi did find a bit of a solution here that enables jshint to process nodejs files by putting jslint node true at the top of the file like this jslint node true use strict moduleexportstestcontroller functionscope scopemessage controller 1 consolelog hello however that obviously fixes too much consolelog should still be undefineddoes anyone know how to use jshint with browserify,['javascript'] +622532,entitys id of parent is not saved in a onetomany relationship in sonataadmin i am using sonataadmin and symfony2 to manage my entities i have a onetomany relationship between one step and many tasks since one step can contain many tasks when i create a step i want to be able to create many tasks and i want those tasks to be linked to this step to do so i created all the proper admin classes one for task and one for step heres what i do that causes my problem when i try to create a step i can create the tasks and even reorder them which is great and all done automatically by sonataadminbundle when i click on save everything is saved in the database except that in the database the id of the step is not set in the row of the task therefore the tasks are not linked to the stepheres my steps admin classphp srcacmedemobundleadminpostadminphpnamespace imaprocessmanagementbundleadminuse sonataadminbundleadminadminuse sonataadminbundledatagridlistmapperuse sonataadminbundledatagriddatagridmapperuse sonataadminbundleformformmapperclass stepadmin extends admin fields to be shown on createedit forms protected function configureformfieldsformmapper formmapper formmapper addname text arraylabel nom de latape addtasks sonata type collection array array edit inline inline table sortable positionnumber addpositionnumber integer arraylabel position fields to be shown on filter forms protected function configuredatagridfiltersdatagridmapper datagridmapper datagridmapper addname fields to be shown on lists protected function configurelistfieldslistmapper listmapper listmapper addidentifiername addslug heres also my task admin classphp srcacmedemobundleadminpostadminphpnamespace imaprocessmanagementbundleadminuse sonataadminbundleadminadminuse sonataadminbundledatagridlistmapperuse sonataadminbundledatagriddatagridmapperuse sonataadminbundleformformmapperclass taskadmin extends admin fields to be shown on createedit forms protected function configureformfieldsformmapper formmapper formmapper addname text arraylabel tache addpositionnumber integer arraylabel position fields to be shown on filter forms protected function configuredatagridfiltersdatagridmapper datagridmapper datagridmapper addname fields to be shown on lists protected function configurelistfieldslistmapper listmapper listmapper addidentifiername addslug also here are the description of my entitiesimaprocessmanagementbundleentitystep type entity table null fields id type integer id true generator strategy auto name type string length 255 positionnumber type integer onetomany tasks targetentity task mappedby step cascade persist merge lifecyclecallbacks imaprocessmanagementbundleentitytask type entity table null fields id type integer id true generator strategy auto name type string length 255 positionnumber type integer manytoone step targetentity step inversedby tasks lifecyclecallbacks i am wondering why the id of the step is not set in the task row,['php'] +622551,opencv grouprectangles getting grouped and ungrouped rectangles i am using opencv and want to group together rectangles that have significant overlap i have tried using grouprectangles for this which takes a group threshold argument with a threshold of 0 it does not do any grouping at all and with a threshold of 1 is only returns rectangles that were the result of at least 2 rectangles for example given the rectangles on the left in the image below you end up with the 2 rectangles on the rightwhat i would like to end up with is 3 rectangles the 2 on the right in the image above plus the rectangle in the top right of the image to the left that does not overlap with any other rectangles whats the best way to achieve this,['c++'] +622599,queues instead of method chaining and rules instead of conditionals in ruby rich hickey describes paradigms from clojure and haskell in his talk simple made easy as a rubyrails programmer that is all i truly know i loved his ideas but did not understand 2 of themusing queues not method chainingrules instead of conditionalsusing queues insteadobviously in rails we love method chaining but i wanted to understand what a queue would look like in ruby the way he described it 5454 in the videoif thing a calls thing b you just complected it you have a when and where thing a has to know where b is in order to call b when that happens is whenever that happens is when a does it stick a queue in thererules vs conditionalshe talks about not using conditionals or switch statements but rules instead 30 in videothis i simply do not get at all in terms of ruby how do i make decisions without using conditionalsthanks alljustin,['ruby'] +622612,how to use substr function in jquery how to use substr function in this script i need substr025a classdep buttons href something text something text something text something text something text something text adep buttonsmouseoverfunction ifthistextlength 30 thisstopanimateheight150px150 dep buttonsmouseoutfunction thisstopanimateheight40px150,['jquery'] +622827,pytest skips test class if constructor is defined i have following unittest code running via pytestmere presence of the constructor make the entire class skip when runningpytest v scollected 0 items 1 skippedcan anyone please explain to me this behaviour of pytesti am interested in understanding pytest behaviour i know the constructor is not neededthankszdenekclass testclassnameobject def init self pass def setup methodself method print setup method called def teardown methodself method print teardown method called def test aself print test a called assert 1 1 def test bself print test b called assert 1 1,['python'] +622877,is branch prediction not working in reference to this question the answer specify that the unsorted array takes more time because it fails the branch prediction test but if we make a minor change in the programimport javautilarraysimport javautilrandompublic class main public static void mainstring args generate data int arraysize 32768 int data new intarraysize random rnd new random0 for int c 0 c arraysize c datac rndnextint 256 with this the next loop runs faster arrayssortdata test long start systemnanotime long sum 0 for int i 0 i 10 i primary loop for int c 0 c arraysize c if datac 128 sum datac systemoutprintlnsystemnanotime start 10 systemoutprintlnsum sum here i have replaced from original questionif datac 128 sum datacwithif datac 128 sum datacthe unsorted array gives approx the same result i want to ask why branch prediction is not working in this case,['java'] +622895,what exactly is mozilla developer javascript documentation a documentation of i was looking at mozilla developer documentation on javascript is it mozillas interpretation of the ecmascript standard or is it documenting how they have implemented javascript in firefoxbasically i want to know whether their documentation is valid across all browsers or just firefox,['javascript'] +623032,cannot recover from orgomgcorbatransient becomes permanent i want to ensure my corba client is resilient to outages i have the client working and am testing resilience by thisabling by network adapter in windows the corba connection obviously fails and the functionality is unavailable but then it does not recover when the adapter is enabled again orbinit is called again but i continue to get the same errorsit seems as if after orgomgcorbatransient is thrown some static state is kept which causes the client to report a network connection timeout even when the problem is fully resolved only restarting the process a dropwizard runnable jar will allow the client to work againthis is the code that starts up the orbstring orbinits orbinitref orbinitrefproperties properties new properties setpropertyorgomgcorbaorbclass orbclass setpropertyorgomgcorbaorbsingletonclass orbsingletonclass setpropertyjacorbconnectionclientconnect timeout connectiontimeout return orbinitorbinits propertiesthe problem persists even if the app is calling orbinit upon each attempt to perform the operation ie with orb pooling switched offerrors thrown by the client in the outage scenario includeorgomgcorbatimeout connection timeout of 20 milliseconds expiredorgomgcorbatransient retries exceeded could not reconnect to ipportin at least one possibly all cases there was no orgomgcorbatimeout before orgomgcorbatransient became permanent ie timeout may be log noiseobviously becuase the client is also a server wed prefer to not have to restart it after every outage and they do happen especially in the dev environmentthe implementation is jacorb orgjacorborborb orgjacorborborbsingleton version 224,['java'] +623097,wherehow can i find whether a net class uses iocp updatei asked the wrong question rephrased based on the great info on answers and commentsis there any good source on nets async operations being real async thus either iocp or asyncoverlapped is there any quick way to find out if several classes are doing soexample of not trusting framework developers blindlythe natural starting point for creating a filestream is the static fileopen method the documentation for which mentions nothing about synchronicity of the filestream that is created nor does it allow you to provide fileoptions which are used to specify the magic fileoptionsasynchronous flaginstead the filestream is created with fileoptionsnone any asynchronous operations are quietly faked by the obliging implementation of the stream base class which merely wraps the corresponding synchronous method in a delegate and invokes it on the thread pool using the begininvoke methodthis is a deviation from the usual apit of successa design philosophy where everything in net seems to work as you think it would without a need to closely read the documentation andor gradually thiscover obscure catches and gotchas over timei have been trying to find information on the use of io completion ports in netis there any good way to know whether a given net class is using io completion ports without having to run some tests every time you use a new classi tried the msdn docs for some classes and methods and i could not find anything on iteven better would be if there is some list out there with a list of classes using iocp,"['c#', '.net']" +623118,install mysqlpython windows i have spent hours trying to make django work on my computer the problem is that i cannot install the mysqlpython package i am running windows 7 64bit this is what i have triedi have downloaded easy installi have downloaded cygwin64 to be able to run linux commands win cmd was driving me crazyi have typed in easy install mysqlpython gave me an error message saying it cannot find vcvarsallbati have downloaded visual studio 2010 however i uninstalled it since i found out that i had some other version of it already it did not solve the problemi have googled this problem like a thousand times so i would be very grateful if someone could help me thanks in advanceedit i thiscovered this does this mean i cannot run django with python 33 and why bother to go through all this work if there is an exefile out there,"['python', 'mysql']" +623243,fabric is there any way to capture run stdout i am trying to do the followingoutput runls l backupsfor line in outputsplitn do stufflineany way of having the stdout of ls sent to outputto be more specific i am using a cli app called s3cmd which does something similar to ls but with remote amazon s3 bucketsso a replacement for ls would not help unfortunately,['python'] +623262,angularjs how to httpget data and store it in service as you will see i am new in angularjs js and in web development at all really sorry for that but i try toi try to build a massive webform about 200 different fields with angularjs controllers i need access from controller to root data source angularjs team ask do not make services just for storing data but i want to make service for load and save data at start into json files on a serverserviceappnamefactorymasterdata rootscope http q log functionrootscope http q log var responsedata httpgetgetdataphpthenfunction response responsedata responsedata consolelogresponsedata return responsedatacontrollerappnamecontrollerjustcontroller scope masterdata log function scope masterdata log scopedata masterdatajustcontrollersectiondata consolelogmasterdata controller return undefined but consolelog from service returns the objecti feel that the problem is too easy but i cannot find how to solve it also i cannot use function like getdata from controller to service because it ask the data from server each time any controller loads i have the routes in angularjs app with 1214 controllers full webform divided by sections and i think it is good to get the data from backend onceps i think there is problem with promises but when i try to use code like thisvar defer qdeferhttpgetgetdataphpsuccessfunctiondata deferresolvedatareturn deferi have got object with resolve reject and so on and really cannot understand what can i do with it help me to get the data in controller,['javascript'] +623379,persist variable changes between tests in unittest how do i persist changes made within the same object inheriting from testcase in unitestfrom unittest import testcase main as unittest mainclass testsimplefootestcase foo bar def setupself pass def test aself selfassertequalselffoo bar selffoo can def test fself selfassertequalselffoo canif name main unittest mainie i want those two tests above to pass,['python'] +623392,how can i get thumbnail of video from remote url for android 40 and above actually i want to show a thumbnail of video from video url and show it in imageview and then on click of imageview the videoview shows video in another activity so ultimately my problem is that i cannot get thumbnail of video from urli have tried a lot but cant get any solution that was worked for me there is solutions given for only get thumbnail from sdcard videos and for remote url there is i have found some solutions but it is not workingbelow is what i have triedbitmap bmthumbnailbmthumbnail thumbnailutilscreatevideothumbnailvideourl thumbnailsmicro kindholdervideoviewfestivitiessetimagebitmapbmthumbnailcan anybody tell me how to show the thumbnail of a video which is in a urlthank you,['android'] +623443,how to join two json object in javascript without using jquery i have two json objects obj1 and obj2 i want to merge them and crete a single json objectthe resultant json should have all the values from obj2 and the values from obj1 which is not present in obj2questionvar obj1 namemanu age23 occupationsevar obj2 namemanu age23 countryindiaexpectedvar result namemanu age23 occupationse countryindia,['javascript'] +623449,how to thisable jquery validation on keyup and focusout for 1 specific html element when using the unobtrusive validation plugin by default the jquery validation plugin is attaching validation handlers for focusin focusout and keyup events1 of our validations is making a synchronous request to retrieve some data i want to have that validation triggered only when the form is being submitted and not while the user is typing i know this can be modified for the whole form but that is not what i am looking foris there a way to dynamically thisable keyup validation for 1 elementupdate 1i forgot to mention that i am using unobtrusive validation so i do not think the answer of mario johnathan is not an optionupdate 2i tried the following things element is the element on which i want to change the validation behaviorelementvalidatefocusout false keyup falseelementkeyupfunction return falseelementoffkeyupelementunbindkeyup,"['javascript', 'jquery']" +623595,why does ruby have zip and transpose when they do the same thing they seem to do the same thingg a a b b r x x y y gzipr aa xx bb yygrtranspose aa xx bb yywhy have both methods,['ruby'] +623598,angular minerr asset not found 404 i am getting an error logged to the consoleget httplocalhost30jslibangularminerr asset 404 not found i saw this post and it said it was a result of not inculding ngroute module but i dopublicjsappjswindowapp angularmodulemeanblogseed ngcookies ngresource uibootstrap ngroute meanblogseedcontrollers meanblogseedservicesthen i have a jade file that references angularroutejsscripttypetextjavascript srcjslibangularangularminjsscripttypetextjavascript srcjslibangularrouteangularrouteminjsscripttypetextjavascript srcjslibangularcookiesangularcookiesminjsscripttypetextjavascript srcjslibangularresourceangularresourceminjsscripttypetextjavascript srcjslibangularbootstrapuibootstraptplsminjsscriptsrcjsappjsscriptsrcjsconfigjsscriptsrcjsservicesglobaljsscriptsrcjscontrollerspostsjsscriptsrcjscontrollersheaderjsscriptsrcjsfiltersjsscriptsrcjsdirectivesjsthe repo is hereupdatei posted the issue on github and got referenced to this crazy answer the ngclosurerunner runs an angular specific pass during compilation which adds a definition for minerr asset that asset is not included with any of the 12x releases the only releases with source maps however the source map references minerr asset as a source and as a result there is a 404 when requesting the filei have only quickly glanced at the grunt tasks and also ngclosurerunner but i am under the impression this is likely the ngclosurerunner included minerrjs or some file generated based on it either way the correct asset should be packaged with the other source files or minerr asset should be removed from the source map sources,['javascript'] +623631,icloud integration for uploading and downloading files i want to design an app which stores documents on icloud but there are some question which has answer before doing actual implementationthe question are as followswhat is maximum file size to upload on icloudcan i programmatically calculateknow the available space on usersicloud accounthow can i get the event for uploading and downloading files fromicloudcan anyone please help me here i read the apple documentation but not understood all the things completelythanks in advance,['ios'] +623723,error with bootstrap 3 datetime picker i am using the datetime picker from eonasden that you can find here date time pickeri am using html from the examplediv classcontainer div classcolmd10 div classwell div classformgroup div classinputgroup date iddatetimepicker1 input typetext classformcontrol span classinputgroupaddonspan classglyphicon glyphiconcalendarspan span div div div divdivit thisplays the icon fine but not the calendar drop down my head script islink hrefviewthistcssbootstrapmincss relstylesheet mediascreenlink hrefviewthistcssbootstrapdatetimepickermincss relstylesheet mediascreenlink href relstylesheet script srcscriptscript srcviewthistjsbootstrapminjsscriptscript srcviewthistjsbootstrapdatetimepickerminjsscriptscript srcscriptfunction document ajaxstop function datetimepicker1datetimepicker i receive a console error of uncaught referenceerror moment is not defined does anyone have an idea on how to fix this it seems to work fine on his sample page,"['javascript', 'jquery']" +623750,centering a glyphicon inside a div heres the fiddle i need to center a glyphicon inside a div both vertically and horizontallyheres the code htmldiv classcontainerdiv classitem span classglyphicon glyphicontextwidthspandivcsscontainerwidth 600pxmargin 0 autoborder 1px solid 0itemwidth 150pxheight 150pxborder 1px solid ditem spanfontsize large,"['css', 'html']" +623804,vim wpython make make take me to the error if i have a python file like def bar raise notimplementederror def foo bar if name main fooand i type make in vim it nicely builds me a cwindow filled with the relevant areas to move up the traceback however it defaults my cursor to the first frame of the call in name main can i somehow change the default behaviour so it takes me to the actual call of the exception update answering ingos questionmakeprgerrorformat are set to default for the gentoo install that ismakeprgpython errorformata file f line lz m the stacktrace in the quickfix window looks like such mainpy 1 traceback most recent call last 2 mainpy8 3 foo 4 mainpy5 5 bar 6 mainpy2 7 raise notimplementederror 8 notimplementederrorspoiled brat that i am i would love it if i started at the raise line 7 and could cp backwards as needed,['python'] +623843,cocoa avasset loaded from file has 0 tracks i am attempting to concatenate some audio files using the technique shown here my audio files are m4a and i can verify that they play fine in quicktime heres the code i am trying to use to concatenate them currfileaudiocontent writetofiletempoldfilepath atomicallyno avurlasset oldaudioasset avurlasset urlassetwithurlnsurl urlwithstringtempoldfilepath optionsnil avurlasset newaudioasset avurlasset urlassetwithurlnsurl urlwithstringtempinputfilepath optionsnil nslogoldasset num tracks luunsigned longoldaudioassettrackscount nslognewasset num tracks luunsigned longnewaudioassettrackscount avassettrack oldtrack oldaudioasset trackswithmediatypeavmediatypeaudio objectatindex0 avassettrack newtrack newaudioasset trackswithmediatypeavmediatypeaudio objectatindex0 avmutablecomposition mutablecomposition avmutablecomposition composition avmutablecompositiontrack comptrack mutablecomposition addmutabletrackwithmediatypeavmediatypeaudio preferredtrackidkcmpersistenttrackid invalid nserror errornil comptrack inserttimerangecmtimerangemakekcmtimezero oldtracktimerangeduration oftrackoldtrack attimekcmtimezero errorerror if error nslogerrorlocalizeddescription errornil comptrack inserttimerangecmtimerangemakekcmtimezero newtracktimerangeduration oftracknewtrack attimeoldtracktimerangeduration errorerror if error nslogerrorlocalizeddescription errornil exporter avassetexportsession alloc initwithassetmutablecomposition presetnameavassetexportpresetapplem4a exporteroutputurl nsurl urlwithstringtempcompfilepath exporteroutputfiletype avfiletypeapplem4a exporter exportasynchronouslywithcompletionhandler nsloghandller nserror errornil nsdata newdata nsdata datawithcontentsoffiletempcompfilepath options0 errorerror nslogluunsigned longnewdatalength if error nslogerrorlocalizeddescription currfileaudiocontent newdata appdelegate shareddelegate saveactionnil the first problem i noticed is that the exporters handler method is never called i am guessing the reason for this is the other problem i noticed after created my avassets from url log statements show that they contain 0 tracks apples example does not exactly show how the avassets are loaded any advice on how to get this working,['objective-c'] +623877,ios deprecation of audiosessioninitialize and audiosessionsetproperty i am very new to objectivec and am trying to update some code that is about 3 years old to work with ios 7 there are two or two instances of audiosessionsetproperty and audiosessioninitialize appearing in the code1 voidapplicationdidfinishlaunchinguiapplication application audiosessioninitializenullnullnullnull sclistener sharedlistener listen timer nstimer scheduledtimerwithtimeinterval 05 target self selector selectortick userinfonil repeats yes override point for customization after app launch window addsubviewviewcontrollerview window makekeyandvisibleand 2 idinit if super init nil return nil audiosessioninitializenullnullnullnull float64 rateksamplerate uint32 size sizeofrate audiosessionsetproperty kaudiosessionproperty preferredhardwaresamplerate size rate return selffor some reason this code works on ios7 in the simulator but not a device running ios7 and i suspect that these deprecations are the cause i have been reading through the docs and related questions on this website and it appears that i need to use avaudiosession instead i have been trying to update the code for a long time now and i am unsure of how to properly switch over to avaudiosession does anyone know how these two methods above need to lookside note i have managed to hunt down an article that outlines the transitionbut i cannot seem to apply this to the code abovethe code i am trying to update is a small frequency detection app from git listeneralternatively if someone could point me to a sample demo app that can detect frequencies on ios devices that would be awesome,['objective-c'] +623925,how to get the duration of mp3 file without playing or storing them i am building a wp8 app which could play poems line by line thisplayed in listboxsay i have 20 lines of poems showing as 20 items in listbox i have 20 mp3 files one for each line i used backgroundaudioplayer to play individual files and select each item poem in listbox during playback of these mp3 files there were delays of 13 seconds so i found the full version of these mp3 files 20 files merged into one reading poems line by linei am playing this mp3 file using backgroundaudioplayer playing as one file i cannot select each item in listbox as i do not know the line number by playing one mp3 filenow what i want is to store the duration of 20 files in seconds without storing and playing the files are located in a link http123com1mp3 2mp3 i used audiotrack with absolute path and then used duration property but it always returns zero how can i get the duration of an mp3 file without playing themedited in the background agent i did belowprotected override void onplaystatechangedbackgroundaudioplayer player audiotrack track playstate playstateswitch playstatecase playstatetrackreadytrackduration tr datasourceconnectiontabletrackdurationsingleordefaultif trisgettrackdurationif playertrack nullplayerposition timespanfromsecondsplayertrackdurationtotalsecondsrecitation r datasourceconnectionqueryrecitationselect from recitation where id playertracktitlesingleordefaultrayaduration playertrackdurationtotalsecondsdatasourcesaverecitiondownloadedrplaynexttrackplayerbreaknotifycompleteprotected override void onuseractionbackgroundaudioplayer player audiotrack track useraction action object paramswitch actioncase useractionplay playtrackplayerbreakcase useractionseekif nullplayertrackplayerposition timespanparambreaknotifycompleteprivate void playnexttrackbackgroundaudioplayer player if currenttracknumber audiotrackcount return playtrackplayerprivate void playtrackbackgroundaudioplayer playerif no track then load track if audiotrackcount 0 load tracks and add them into track play list if playertrack null playertracktitle audiotrackcurrenttracknumbertitle playertrack audiotrackcurrenttracknumberif playertrack null playerplayerstate playstateplaying playerplaythe question is it plays some of the files which i do not want trisgettrackduration is always true but i do not know why it plays some,['c#'] +623930,autocomplete method brackets using visual studio pro 2013previous research 1 2 3i am used to working in java with eclipsemy usual flow is object ctrlspace enterwhich autocompletes the method and places the correct curly brackets method inputs in thereobjectmymethodorobjectmymethodinput1input2i am trying to get the same behaviour with vs in c i can get the method but it does not want to include the final brackets for some reasoni getobjectmymethodis there a way to enable this,['c#'] +623945,is it possible to detect processing power for use in progressive enhancement in web development sometimes i need to add animation effects that are out of the scope of css3 like effects that are coupled to scroll position etcoften this works just fine but i ran into an awkward problem lately im trying to animatea blur effect that occurs when the user scrolls down a page using webkitfilter blurthis is easy enough to implement with some javascript but i found that animating blurreally weighs down on the processor of the user the animation ran ok on my brandnew blazing fast macbook but failed to run smoothly on older machines or even browsers on mymachine other than google chromethe implementation details are not important but i found this problem begs the questioncan i transparently detect roughly perhaps the clients processing power and use this knowledge to turn on or off certain features in my code as to ensure smooth operation and animationi know javascript animation libraries exist that do really great stuff without using up much processing power but that is not what i am after i could think of other usecases that are not animationrelated,"['javascript', 'jquery']" +623953,paragraph matching python background informationi have a python script which generates word documents with the docx module these documents are generated based on a log and then printed and stored as records however the log can be edited retroactively so the document records need to be revised and these revisions must be tracked i am not actually revising the documents but generating a new one which shows the difference between what is currently in the log and what will soon be in the log the log is updated after the revised file is printed when a revision occurs my script uses diff match patch to generate a markup of whats changed with the following functiondef revfinderstr1str2 dmp dmp modulediff match patch diffs dmpdiff mainstr1str2 paratext for diff in diffs paratextappenddiff1 if diff0 0 else s if diff0 1 else b return paratextdocx can take text either as strings or by tuple if wordbyword formatting is required so see second bullet in some things to notehello my name b is brad sproduceshello my name is bradthe problemdiff match patch is a very efficient code which finds the difference between two texts unfortuanly its a little too efficient so replacing redundant with dune results in redunantethis is ugly but its fine for single words however if an entire paragraph gets replaced the results will be entirely unreadable that is not okpreviously i addressed this by collapsing all the text into a single paragraph but this was less than ideal because it became very cluttered and was still pretty uglythe solution so fari have a function which creates the revision document this function gets passed a list of tuples set up like thisfieldname original revisedso the document is set up as orignial fieldname with markup result of revfinder diffing orignal and revisedrevised fieldname revisedi assume in order to resolve the problem i will need to do some sort of matching between paragraphs to make sure i do not diff two completely separate paragraphs i am also assuming this matching will depend if paragraphs are added or removed heres the code i have so farif lenitem1splitn lenitem1splitn 2 bodyappendheadingoriginal with markupformatitem02 bodyappendparagraphrevfinderitem1item2 bodyappendparagraphstylebodytextkeep bodyappendheadingrevised formatitem02 bodyappendparagraphitem2 bodyappendparagraphelse diff lenitem1splitn lenitem1splitn if diff 0 bodyappendheadingoriginal with markupformatitem02 for orpara revpara in zipitem1splitnitem2splitn bodyappendparagraphrevfinderorpararevpara bodyappendparagraphstylebodytextkeep bodyappendheadingrevised formatitem02 for para in item2splitn bodyappendparagraphformatpara bodyappendparagraph elif diff 0 removed paragraphs elif diff 0 added paragraphs so far i have planned on using something like difflib to do paragraph matching but if there is a better way to avoid this problem that is a completely different approach that is great toosome things to notei am running python 276 32bit on windows 7 64biti have made some changes to my local copy of docx namely adding the strike through formatting so if you test this code you will not be able to replicate what i am doing in that regarddescription of the entire process with the revision steps in bold1 user opens python script and uses gui to add information to a thing called a condition report crnote a full cr contains 4 parts all completed by different people but each part gets individually printed all 4 parts are stored together in the log2 when the user is finished the information is saved to a log described below and then printed as a docx file3 the printed document is signed and stored4 when the user wants to revise a part of the cr the open the gui and edit the information in each of the fields i am only concerned about a few of the fields in this question and those are the multiline text controls which can result in multiple paragraphs5 once the user is done with the revision the code generates the tuple list i described in the solution so far section and sends this to the function which generates the revision document6 the revision document is created printed signed and stored with the original document for that part of that cr7 the log is completely rewritten to include the revised information the logthe log is simply a giant dict which stores all the information on all of the crs the general format is unique id number list of cr infothe log does not store past versions of a cr so when a cr is revised the old information is overwritten which is what we want for the system as i mentioned earlier every time the log is edited the whole thing is rewritten to get at the information in the log i import it since it always lives in the same directory as the script,['python'] +623993,numba code slower than pure python i have been working on speeding up a resampling calculation for a particle filter as python has many ways to speed it up i though i would try them all unfortunately the numba version is incredibly slow as numba should result in a speed up i assume this is an error on my parti tried 4 different versionsnumbapythonnumpycythonthe code for each is belowimport numpy as npimport scipy as spimport numba as nbfrom cython resample import cython resamplenbautojitdef numba resampleqs xs rands and qsshape0 lookup npcumsumqs results npemptyn for j in rangen for i in rangen if randsj lookupi resultsj xsi break return resultsdef python resampleqs xs rands and qsshape0 lookup npcumsumqs results npemptyn for j in rangen for i in rangen if randsj lookupi resultsj xsi break return resultsdef numpy resampleqs xs rands results npempty likeqs lookup spcumsumqs for j key in enumeraterands i spargmaxlookupkey resultsj xsi return resultsthe following is the code for the cython module it was compiled in aseparate file but is included here to aid in the questionimport numpy as npcimport numpy as npcimport cythondtype npfloat64ctypedef npfloat64 t dtype tcythonboundscheckfalsedef cython resamplenpndarraydtype t ndim1 qs npndarraydtype t ndim1 xs npndarraydtype t ndim1 rands if qsshape0 xsshape0 or qsshape0 randsshape0 raise valueerrorarrays must have same shape assert qsdtype xsdtype randsdtype dtype cdef unsigned int and qsshape0 cdef unsigned int i j cdef npndarraydtype t ndim1 lookup npcumsumqs cdef npndarraydtype t ndim1 results npzerosn dtypedtype for j in rangen for i in rangen if randsj lookupi resultsj xsi break return resultsif name main and 100 xs nparangen dtypenpfloat64 qs nparray10nn rands nprandomrandn print timing numba function timeit numba resampleqs xs rands print timing python function timeit python resampleqs xs rands print timing numpy function timeit numpy resampleqs xs rands print timing cython function timeit cython resampleqs xs randsthis results in the following outputtiming numba function1 loops best of 3 823 ms per looptiming python function100 loops best of 3 248 ms per looptiming numpy function10 loops best of 3 793 as per looptiming cython function10 loops best of 3 25 as per loopany idea why the numba code is so slow i assumed it would be at least comparable to numpynote if anyone has any ideas on how to speed up either the numpy or cython code samples that would be nice too my main question is about numba though,['python'] +624006,pip not working behind firewall i am trying to use pip from behind a corporate firewall and not having any lucki have set the http proxy and https proxy environment variables wget works but not pipi tried this sudo e pip install virtualenvwith these proxies export http proxymyproxynamemydomaincom8080export https proxymyproxynamemydomaincom8080 and got a long stacktrace which ended with thisrequestspackagesurllib3poolmanagerpy line 214 in init not supported proxy scheme s selfproxyschemeassertionerror not supported proxy scheme nonei looked at the poolmanagerpy source it looks like it is requiring the proxy variables to begin with a scheme so i tried again with the following proxies export http proxyexport https proxy also tried this with http and i get the following errordownloadingunpacking virtualenv cannot fetch index base url could not find any downloads that satisfy the requirement virtualenvcleaning upno thistributions at all found for virtualenvstoring debug log for failure in rootpippiplogthis is the same error i get when i do not have a proxy at all though i get it much faster when the proxies are setwhen i try wget wget nocheckcertificate it works fine so i think the proxies themselves seem ok unless i try them with pipusing the proxy option instead of envvars did not help same resultsany ideasthanksbean,['python'] +624035,not possible to use css calc with transformtranlatex in ie alli would like to be able to use calc with transformtranslatex in my cssegmydiv webkittransform translatexcalc100 50px moztransform translatexcalc100 50px transform translatexcalc100 50pxwhile this works perfectly in chrome safari and firefox it does not work in ie10 or ie11you can see a simple example here is this impossible is it a bug in ie or is calc not supposed to work in this contextfor what it is worth i read here that you can stack translatex to acheive the same effect and my testing seems to confirm this iediv transform translatexcalc100 50pxis the same asdiv transform translatex100 translatex50pxbut i do not know if this is the best most reliable and futureproof way to do thisi also know that it is possible to use left instead of translatex but the latter is much smoother when used with transitions since as i understand it it forces the use of the gpu to handle the animationthanks in advance for your advice and insight,"['html', 'css']" +624130,reading dependency walker output i am having some problems using one of the dlls in my application and i ran dependency walker on it i am not sure how to read it but i got following resultsdoes it suggest any x86x64 incompatibilty is there anyway i can solve this issueerror at least one required implicit or forwarded dependency was not founderror at least one module has an unresolved import due to a missing export function in an implicitly dependent moduleerror modules with different cpu types were foundwarning at least one delayload dependency module was not foundwarning at least one module has an unresolved import due to a missing export function in a delayload dependent module,"['c#', 'c++']" +624150,ios 7 uitabbaritem badge zindex i would like to show a uitabbaritem badge above the selectionindicatorimage there are 3 screenshotsscreenshotslight gray color is the selectionindicatorimage yes badge looks good when i touch up inside at the cloud icon uitabbar becomeit is wrong i would like to show badge above the selection imageif there is no icon for uitabbar it looks good how can i fix this issue thanks in advance editedi add icons in the storyboard for badge i have made the codeuitabbaritem carttabbaritem uitabbaritem selftabbarcontrollertabbaritems objectatindex3if datasourcewrapper getinstance getfullcost 0 carttabbaritembadgevalue nil else carttabbaritembadgevalue nsstring stringwithformat0f n123 datasourcewrapper getinstance getfullcostfor selectionindicatorimageuitabbar appearance setselectionindicatorimageuiimage imagenamedselectedtabbarbgpng,"['ios', 'objective-c']" +624221,waitformultipleobjects alternative with stdthread my problem is that i have multiple threads they are stored in some container and i need to know when a thread at a certain position finishedon windows i would do something likehandle handles3handles were initializeddword finishingthread waitformultipleobjects3 handles false infiniteis there any way to achieve the same effect with stdthread,['c++'] +624247,background size on ios i have spent the morning doing research on the following issue i am making a one page site using a lot of images i am aware that safari is known for its weird handling of backgroundattachmentfixed but that is working fine my problem is backgroundsizecover is not working in conjunction with fixedi have 5 pages all of which have a height or minheight of 100 the last page is fixed like thisdiv5 height100 width100 position relative backgroundimage urlimgbackgroundjpg backgroundattachmentfixed webkitbackgroundsize cover mozbackgroundsize cover obackgroundsize cover backgroundsize coveron ios in both chrome and safari the background image is scaled to cover the full webpage so it is really stretchedat the same time page 4 has the following cssdiv4 minheight100 width100 backgroundurlimgportfoliobgjpg overflow auto backgroundsize coverand this works like a charmso something makes the browser behave really weirdly when combining fixed and cover does anyone have a solution to this,"['html', 'ios', 'css']" +624355,setup issue in cas server in rails 3x i have installed rubycas server on ec2 server using rails 32 and ruby 193 and configured configureyml file my server webrickport 9292ssl cert mntrubyonrailstestingcaspem note i have mentioned domain name fortestingonlymanagemyascdevserver during generate self signed ssl databaseadapter mysql2database casserverusername rootpassword xhost localhostreconnect trueauthenticatorclass casserverauthenticatorssqldatabaseadapter mysql2database mmx devusername rootpassword xhost localhostuser table userdemousername column usernamepassword column passwordand i have also mapped cas server url in my local etchost as 18472242142 fortestingonlymanagemyascdevserverand in environment file cas base url now i have fired up rubycas server and my application server but as i tried to access my application url getting following error in my application logstarted get for 12216249205 at 20140131 040114 0800processing by dashboardcontrollerindex as htmlguessed service url generated login url servicehttp3a2f2fohioorthomanagemyascdevserver3a302fredirecting to redirected to filter chain halted as casclientframeworksrailsfilter rendered or redirectedcompleted 302 found in 1ms activerecord 00msoink action dashboardindexmemory usage 779472 pid 29159instantiation breakdown total 1 activerecordsessionstoresession 1oink log entry complete,"['ruby-on-rails', 'ruby']" +624435,mdn objectis alternative proposal i have read the mdn page on the objectis methodit gives an alternative code for the browsers that do not provide this methodif objectis objectis functionv1 v2 if v1 0 v2 0 return 1 v1 1 v2 if v1 v1 return v2 v2 return v1 v2 the question is simple when can the second if be true thank you for your attention,['javascript'] +624486,android only use xxhdpi images is there any drawback in only using xxhdpi images and letting android scale the imagesyes it might be more cpu intensive but is it notable i tested it on a samsung s2 and the difference were smallis there a restriction to only use this if set minsdk to xx becaus there were no xxhdpi,['android'] +624529,make browserify modules external with gulp i have a library libjs that i want to create from libajs and libbjs and to be able to use it from a script clientjs using var a requirelibajs and that it works when i just include the compiled libjs library before clientjs therefore libjs has to declare a require function that knows about libajsi guess i have to use external and alias but i am not sure what is the proper way to do italso is it possible to have a gulp file that creates all the alias automatically for the folders in my library eg creates an alias for all the files in the lib dir,['javascript'] +624535,the final local variable cannot be assigned since it is defined in an enclosing type ratings new jslider1 5 3 ratingssetmajortickspacing1ratingssetpaintlabelstrueint voteclass slidermoved implements changelistener public void statechangedchangeevent e vote ratingsgetvalue ratingsaddchangelistenernew slidermovedif i write the above code eclipse tells me thiscannot refer to a nonfinal variable vote inside an inner class defined in a different methodbut if i add final before int vote it gives me this errorthe final local variable vote cannot be assigned since it is defined in an enclosing typeso how to solve,['java'] +624561,how to test session in flask resource i would like to test a resource the response of that depends on a parameter in session loggedto test this resource i have wrote those testsimport appimport unittestclass testunittesttestcase def setupself selfapp appapptest client def test without sessionself resp selfappget selfassertequalwithout session respdata def test with sessionself with selfapp as c with csession transaction as sess sesslogged true resp cget selfassertequalwith session respdataif name main unittestmainmy apy is thisfrom flask import flask sessionapp flask name approutedef home if logged in session return with session return without sessionif name main apprundebugtruewhen i run the tests i have this errorerror test pippo with session main testtraceback most recent call last file test pippopy line 17 in test pippo with session with csession transaction as sess file usrlibpython27contextlibpy line 17 in enter return selfgennext file hometommasoreposprovaflasklocallibpython27sitepackagesflasktestingpy line 74 in session transaction raise runtimeerrorsession backend did not open a session runtimeerror session backend did not open a session check the configurationi have not found any solution on google,['python'] +624612,reading qr code in an image with zxing i am using a c library for reading of qrcodes a lot of the samples i have found are based off the old version of zxing where the rgbluminancesource constructor still takes in bitmap in the latest version rgbluminancesource only takes byte i have tried to convert bitmap to byte but the decode result is always null heres the code i used for conversionprivate byte getrgbvaluesbitmap bmp lock the bitmaps bits systemdrawingrectangle rect new systemdrawingrectangle0 0 bmpwidth bmpheight systemdrawingimagingbitmapdata bmpdata bmplockbitsrect systemdrawingimagingimagelockmodereadonly bmppixelformat get the address of the first line intptr ptr bmpdatascan0 declare an array to hold the bytes of the bitmap int bytes bmpdatastride bmpheight byte rgbvalues new bytebytes copy the rgb values into the array systemruntimeinteropservicesmarshalcopyptr rgbvalues 0 bytes bmpunlockbitsbmpdata return rgbvaluesand for decodebitmap bitmap bitmapfromfilecqrimagesjpg as bitmapluminancesource source new rgbluminancesourcegetrgbvaluesbitmap bitmapwidth bitmapheightvar binarizer new hybridbinarizersourcevar binbitmap new binarybitmapbinarizerqrcodereader reader new qrcodereadervar result readerdecodebinbitmapsomehow the result is always nullalso our requirement is that we have to use image taken by camera i have tried thisbitmap bitmap bitmapfromfilecqrimagesjpg as bitmapbarcodereader reader new barcodereader autorotate true tryharder true result result readerdecodebitmapit only works for the qr image i download online but if i print out that image and take a picture of that with my phone then try to process that image the result is back to nullany suggestions would be appreciatedheres the image i am using,['c#'] +624653,should hibernate sessionmerge do an insert when receiving an entity with an id this seems like it would come up often but i have googled to no availsuppose you have a hibernate entity user you have one user in your db with id 1you have two threads running a and b they do the followinga gets user 1 and closes its sessionb gets user 1 and deletes ita changes a field on user 1a gets a new session and merges user 1all my testing indicates that the merge attempts to find user 1 in the db it cannot obviously so it inserts a new user with id 2my expectation on the other hand would be that hibernate would see that the user being merged was not new because it has an id it would try to find the user in the db which would fail so it would not attempt an insert or an update ideally it would throw some kind of concurrency exceptionnote that i am using optimistic locking through version and that does not help mattersso questionsis my observed hibernate behaviour the intended behaviourif so is it the same behaviour when calling merge on a jpa entitymanager instead of a hibernate sessionif the answer to 2 is yes why is nobody complaining about it,['java'] +624663,installing pyquery via pip i am attempting to install pyquery via pip but i am getting an error i do not understand the command i used wassudo pip install pyqueryi get the output belowrequirement already satisfied use upgrade to upgrade pyquery in usrlocallibpython27thistpackagesdownloadingunpacking lxml21 from pyqueryrunning setuppy egg info for package lxmlusrlibpython27thistutilsthistpy267 userwarning unknown thistribution option bugtrack url warningswarnmsgbuilding lxml version 330building without cythonerror binsh 1 xsltconfig not found make sure the development packages of libxml2 and libxslt are installed using build configuration of libxsltdownloadingunpacking cselect from pyqueryrunning setuppy egg info for package cselectno previouslyincluded directories found matching docs buildinstalling collected packages lxml cselectrunning setuppy install for lxmlusrlibpython27thistutilsthistpy267 userwarning unknown thistribution option bugtrack url warningswarnmsgbuilding lxml version 330building without cythonerror binsh 1 xsltconfig not found make sure the development packages of libxml2 and libxslt are installed using build configuration of libxsltbuilding lxmletree extensiongcc pthread fnostrictaliasing dndebug g fwrapv o2 wall wstrictprototypes fpic ihomeimageekscriptsfacebookbuildlxmlsrclxmlincludes iusrincludepython27 c srclxmllxmletreec o buildtemplinuxi68627srclxmllxmletreeo wsrclxmllxmletreec1620 fatal error pythonh no such file or directorycompilation terminatederror command gcc failed with exit status 1complete output from command usrbinpython c import setuptools file homeimageekscriptsfacebookbuildlxmlsetuppyexeccompileopen file readreplacern n file exec install singleversionexternallymanaged record tmppipdyuzwzrecordinstallrecordtxtusrlibpython27thistutilsthistpy267 userwarning unknown thistribution option bugtrack urlwarningswarnmsgbuilding lxml version 330building without cythonerror binsh 1 xsltconfig not found make sure the development packages of libxml2 and libxslt are installed using build configuration of libxsltrunning installrunning buildrunning build pycopying srclxmlincludeslxmlversionh buildliblinuxi68627lxmlincludesrunning build extbuilding lxmletree extensiongcc pthread fnostrictaliasing dndebug g fwrapv o2 wall wstrictprototypes fpic ihomeimageekscriptsfacebookbuildlxmlsrclxmlincludes iusrincludepython27 c srclxmllxmletreec o buildtemplinuxi68627srclxmllxmletreeo wsrclxmllxmletreec1620 fatal error pythonh no such file or directorycompilation terminatederror command gcc failed with exit status 1command usrbinpython c import setuptools file homeimageekscriptsfacebookbuildlxmlsetuppyexeccompileopen file readreplacern n file exec install singleversionexternallymanaged record tmppipdyuzwzrecordinstallrecordtxt failed with error code 1storing complete log in homeimageekpippiplogi have a feeling it is something to do with dependencies but should pip not automatically install dependencies,['python'] +624702,relative imports with unittest in python i am trying to use python unittest and relative imports and i cannot seem to figure it out i know there are a lot of related questions but none of them have helped so far sorry if this is repetitive but i would really appreciate any help i was trying to use the syntax from pep 328 but i must have something wrong my directory structure isproject init py main programpy lib init py lib a lib b tests init py test a test bi run my tests usingpython m unittest test module1 test module2test a needs to import both liblib a and main program this is the code from test a i am trying to use for the importfrom lib import lib a as libfrom project import main programboth raise this errorvalueerror attempted relative import in nonpackageall of my initpy files are currently empty any specific advice would be greatly appreciatededitthis may be the answer python packagesi am still verifying if this will work edit iito clarify at this point i have attempted to run my test file in 3 different waysprojecttests python m unittest test aprojecttests python m test aprojecttests test aall three fail with the same error as above when i use the same three syntaxes but in the project directory i get this errorvalueerror attempted relative import beyond toplevel packagethanks again,['python'] +624794,databasecleaner rspec what is the correct configuration i included database cleaner gem in my rails app followed the example given on the git repo and included the following code in spec helper approach 1 configbeforesuite do databasecleanerstrategy transaction databasecleanerclean withtruncation end configaroundeach do example databasecleanercleaning do examplerun end endwhen i run the rspec i get error as nomethoderrorundefined method cleaning for databasecleanermodule so i did some research and found that i could replace the configaround block above with something like this approach 2configbeforeeach do databasecleanerstartendconfigaftereach do databasecleanercleanend orapproach 3configaroundeach do example databasecleanerstart examplerun databasecleanercleanendboth approach 2 and 3 work welli also looked in the git repo of database cleaner and found that cleaning method actually exists and with the following code def cleaningblock start yield clean endwhich is exactly same as what i did in example 3 if it does exists then why is it not accessible am i missing something here any more setupor is approach 2 or 3 preferable,['ruby-on-rails'] +624796,create a pandas dataframe from deeply nested json i am trying to create a single pandas dataframe object from a deeply nested json string the json schema isintervals pivots jane smithseries interval id 0 p value 1 interval id 1 p value 162791357932633e8 interval id 2 p value 028675012051504467 pivots bob smith series interval id 0 p value 1 interval id 1 p value 162791357932633e8 interval id 2 p value 028675012051504467 desired outcome i need to flatten this to produce a tableactor interval id interval id interval id jane smith 1 162 0 bob smith 1 162 0 the first column is the pivots values and the remaining columns are the values of the keys interval id and p value stored in the list seriesso far i have gotimport requests as rimport pandas as pdactor data rgeturltodatajsondataintervalsdf pddataframeactor dataactor data is a list where the length is equal to the number of individuals ie pivotsvalues the df object simply returnsbound method dataframedescribe of pivots series0 jane smith up value 10 uinterval id 0 up va1 bob smith up value 10 uinterval id 0 up vahow can i iterate through that series list to get to the dict values and create and thistinct columns should i try to create a dataframe for the series list reshape itand then do a column bind with the actor names updatepvalue list ip value for i in json dataseriesthis gives me a list of lists now i need to figure out how to add each list as a row in a dataframe value list for i in pvalue list pvs jp value for j in i value list value listappendpvsreturn value listthis returns a nonetypesolutiondef get hypthesis data raw data rgeturltodatajsondata actor dict for actor series in raw dataintervals actor actor seriespivots p values for interval in actor seriesseries p valuesappendintervalp value actor dictactor p values return pddataframeactor dicthis returns the correct dataframe i transposed it so the individuals were rows and not columns,['python'] +624849,uiviewanimationoptionbeginfromcurrentstate unexpected behaviour with basic animation i am trying to perform this basic uiview animation upon receiving a button click ibactionbuttonpressidsender selfsampleviewalpha 00 uiview animatewithduration20 delay00 optionsuiviewanimationoptioncurveeaseinout uiviewanimationoptionbeginfromcurrentstate animationsselfsampleviewalpha 10 completionnullprior to the button click the view is visible and has an alpha value of 10 when i send the button action i expect the view to fade in from alpha00 to alpha10 over 2 seconds but this does not happen when i remove the uiviewanimationoptionbeginfromcurrentstate the animation works fine it seems like with the uiviewanimationoptionbeginfromcurrentstate option set the alpha00 is not being set and the animation is skipped because it thinks it is already at 10i am trying to understand why this would be happening since apple documentation states that the uiviewanimationoptionbeginfromcurrentstate has no effect if another animation is not in progressuiviewanimationoptionbeginfromcurrentstatestart the animation from the current setting associated with an already inflight animation if this key is not present any inflight animations are allowed to finish before the new animation is started if another animation is not in flight this key has no effect,"['ios', 'objective-c']" +624955,is sizeoft sizeofint i have been poring over the draft standard and cannot seem to find what i am looking forif i have a standardlayout typestruct t unsigned handlethen i know that reinterpret castunsignedt thandle for some t t the goal is to create some vectort v and pass v0 to a c function that expects a pointer to an array of unsigned integersso does the standard define sizeoft sizeofunsigned and does that imply that an array of t would have the same layout as an array of unsignedwhile this question addresses a very similar topic i am asking about the specific case where both the data member and the class are standard layout and the data member is a fundamental typei have read some paragraphs that seem to hint that maybe it might be true but nothing that hits the nail on the head for examplea 9217two standardlayout struct clause 9 types are layoutcompatible if they have the same number of nonstatic data members and corresponding nonstatic data members in declaration order have layoutcompatible typesthis is not quite what i am looking for i do not think,['c++'] +625005,start whatsapp from url href with custom textcontent as you know using the whatsapp url scheme on iphone i can create the following linkhrefwhatsappsendtextblahblahthis is possible due to the url scheme support on iosim try to create the similar effect for android devices but no threw android app just a normal html pageto my understanding it should be something likehrefintentsendintentschemewhatsapackagecomwhatsappstexttestendorhrefintentsendintentschemewhatsapackagecomwhatsapptexttest actionandroidcontentintentaction send endorhrefintentsendintentschemewhatsapackagecomwhatsapptexttest categoryandroidintentcategorybrowsableendas you can see im really groping in the darkall the answers i have found on stackoverflow are talking about how to generate the intent threw the android appbut thats not my case i want to generate an href on a phpasp server for an html pagesomeonethanks,"['android', 'html']" +625034,how to force a runtime constant to be a compile time constant so i am working on a chemistry based project and ran into this tricky problem i have a bunch of functions doing chemistry type calculations and want to pass avogadros number as a default parameter for a function let me just let the code talk class constants must be readonly to bc mathpow is calculated at runtime public static double readonly avogadrosnum 6022mathpow1022 class chemcalculations getting default parameter must be a compiletime constant public double genericcalcdouble avogadrosnum constantsavogadrosnum edit was unaware of exponential format thanks guys,['c#'] +625093,snake case or camelcase in nodejs so i have nodejs application that exposes some api to clients and connects to some sql databasefirst let introduce some premisesclients must use api with snake case keys in json object sent in request body are in snake casedatabase column names are also snake caseproblem is because javascript standardpractice is using camelcase which i would like to keepso as i see there are 3 solutionstransform data from snakeapi to camel application to snake database on the fly as neededthis would introduced some new layers to system and all of it would be little complicated than other solutionsuse snake case in nodejs app but no matter if i use snake all other dependencies i am using will still be in camel which does not solve whole problemmix snake case and camelcase in nodejs app this is something i would like to avoid so what do you suggest mine favorite is first solutions but if you have some other smart ideas not mentioned here please feel free to tell thanksivan,['javascript'] +625144,why does laravel 4 gitignore composerlock why does the default laravel4 have the composerlock file included in the gitignore repoit seems to contradict composers recommendations to commit this file into vcs i was wondering if there was something i did not know that justified this,['php'] +625219,using functionprototypebind with an array of arguments how can i call functionprototypebind with an array of arguments as opposed to hardcoded arguments not using ecma6 so no spread operatori am trying to put a promises wrapper around a module that uses callbacks and i want to bind all of the arguments passed in to my wrapper method and bind them then i want to call the partially applied bound function with my own callback which will resolve or reject a promisevar find function var deferred bound deferred qdefer bound dbfindbindnull arguments boundfunctionerr docs iferr deferredfailerr else deferredresolvedocs return deferredpromisebut obviously this does not work because bind expects arguments rather than an array of arguments i know i could do this by inserting my callback onto the end of the arguments array and using applyargumentsargumentslength functionerr docs dbfindapplynull argumentsor by iterating over the arguments array and rebinding the function for each argumentvar bound contextforvar i 0 i argumentslength i context bound bound dbfind bound contextbindnull argumentsiboundfunctionerr docs but both of these methods feel dirty any ideas,['javascript'] +625271,default boolean value in java just want to know if there is a difference in java betweenprivate boolean somevalueprivate boolean somevalue falsethe second line maybe is just a time waistingedit summaryfrom the answers i found that there is almost no difference butrelying on such default values however is generally considered bad programming stylebut there are some strong arguments not to do so see accepted answer belowedit 2i found that in some cases boolean value must be initialized otherwise the code will not compileboolean somevalueif somevalue error here do somethingin my netbeans ide i got the error variable somevalue might not have been initializedit is getting interesting,['java'] +625314,joomla 3 installation freezes at creating database table i am trying to install joomla 321 on my system but the installation freezes half way through i have downloaded and installed the wamp server 24 and wanted to locally install joomla 321 but the installation freezes and does not finishit stops short of finishing the installation during the creating database tables task it just stays on this bit seemingly foreverincreasing the max execution time in phpini and restarting the wamp did not helpmy wamp 24 usesmysql 5612php 5416 apache 244how can i get the installer to go past this point,['mysql'] +625321,codeigniter creating a restful api hey so i have been trying to create a restful api using codeigniter 214 i am an intermediate php programmer and originally debated created the api from scratchhowever after some research looking through old questions here and on google i picked up a couple tutorials and third party librariesone of the easiest to follow i found at nettutsthis looked like a great solution as it used the philsturgeon codeigniterrestserver third party libraries but the tutorial its self was written in 2010 upon further inspection i realized that the majority of the tutorials using these libraries were at least 23 years old will this cuase any issuescan i still follow the tutorial at nettuts or should i just write my own restful api,['php'] +625327,how can i make windows 95 style buttons in visual c i am writing a program and i am just curious of how to put buttons that look like in windows 95i am using visual c express 2010 with winformsis this possible in the compileride i described above,['c#'] +625346,codeigniter subdomain routing i am trying to setup a blog script on a website running on the codeigniter framework i want do this without making any major code changes to my existing websites code i figured that creating a sub domain pointing to another controller would be the cleanest method of doing thisthe steps that i took to setup my new blog controller involvedcreating an a record pointing to my servers ip addressadding new rules to codeigniters routesphp filehere is what i came up withswitch serverhttp host case blognotedump routedefault controller blog routelatest bloglatest break default routedefault controller main breakthis should point blognotedump and blognotedumplatest to my blog controllernow here is the problemaccessing blognotedump or blognotedumpindexphpbloglatest works fine however accessing blognotedumplatest takes me to a 404 page for some reasonmy htaccess file looks like this the default for removing indexphp from the url rewriteengine onrewritecond 1 indexphpimagesrobotstxtrewriterule indexphp1 land my blog controller contains the following codeclass blog extends ci controller public function remapmethod echo remap function calledn echo the method called was method public function index thisloadhelperurl thisloadhelperglobalhelpersbase thisloadviewblog public function latest echo latest working what am i missing out on or doing wrong here i have been searching for a solution to this problem for days,['php'] +625355,how can i make my class iterable so i can use foreach syntax i have book and booklist classes booklist is something like thispublic class booklist private final listbook blist new arraylistbook public int size return blistsize public boolean isempty public boolean containsbook b public boolean addbook b public boolean removebook b public void clear public object getint index in my main class i want to print titles of books with in a for each loopforbook b blist bprinteclipse says can only iterate over an array or an instance of javalangiterablehow can i get this working,['java'] +625356,merge equal table cells with jquery simple html table with nxm values the aim is to merge equal cells in column with jquerynote that in one row there are no duplicatesi got how to hide the equal cells but is there any way to combine a cell with data with an empty cell in onehtmltable border1 idtesttabletr tdfirsttd tdatd tdatdtrtr tdfirsttd tdatd tdbtdtrtr tdsecondtd tdvtd tdstdtrtr tdthirdtd tddtd tdhtdtrtr tdthirdtd tdetd tdetd trtablejsvar seenarray testtable tdeachfunction var index thisindex var txt thistext if seenarrayindex txt thistext i think here should be marging else seenarrayindex txt jsfiddleps one more thing the data originally is retrieved in json array then i do parsejson first and put data in table usingfor var i 0 i objlength i tr tr trappendtd objicolumna td trappendtd objicolumnb td trappendtd objicolumnc td testtableappendtr updalfred nsh made a good solution for 2 cells here is his solutionbut if there will be more than 2 equal cells,"['javascript', 'jquery', 'html']" +625400,karma not running unit tests due to no captured browser message i am trying to set up karma to run angularjs unit tests using jasmine but i cannot get the tests to run i am sure i am overlooking something simple i am running this on a windows 7 machine with nodejs installed and karma installed via npmmy directory structure looks like thisjsapp contains controllers app etcjsconfig contains karmaconfjsjslib contains angularjstest contains jasmine specsi am starting a command prompt in the js directory and running this commandkarma start configkarmaconfjsthat causes chrome to run on port 9876 but whenever i change any watched files and check the karma output i see this info messageno captured browser open httplocalhost9876heres my config filemoduleexports functionconfig configset basepath frameworks jasmine files libangularjs appjs testjs exclude reporters progress port 9876 colors true loglevel configlog info autowatch true browsers chrome capturetimeout 60 singlerun false i am using angular 1210 and karma 0109,['javascript'] +625501,why and how do extra parentheses change the type of an expression in c c11 under what circumstances do extra grouping parentheses break things in c c11 specifically for reasons that are not relevant here i ended up at one point with an expression that had an extra unnecessary set of parens around it and i thiscovered that the c11 typeinfo function is same was determining it to be a different type than the same code without the parentheses here is a boileddown example of the somewhat baffling behaviourinclude iostreamusing namespace stdint main string s foo cout stdis samedecltypes decltypestringfoovalue cout stdis samedecltypes decltypesvalue cout stdis samedecltypes decltypestringfoovalue cout stdis samedecltypesx decltypestringfooxvalue return 0this code prints 1001 which seems to indicate that the extra parens in the middle two lines cause the expression to be of a different type but using that parenthesised expression in a larger expression makes it once again the same type on the other hand if i use typeid to get a name for the type typeids and typeids seem to produce the same thingi have now worked around the immediate problem but i still do not understand why this happens in the first place searching around for double parentheses c and the like does not seem to turn up anything relevant mostly pages about operator overloading and compiler extensions that only activate after a specific keywordso what the heck is going on here why is the type of s different from the type of s,['c++'] +625545,python class fields i am new to python having come from mainly java programming i am currently pondering over how classes in python are instantiatedi understand that init is like the constructor in java however sometimes python classes do not have an init method which in this case i assume there is a default constructor just like in java another thing that makes the transition from java to python slightly difficult is that in java you have to define all the class fields with the type and sometimes an initial value in python all of this just seems to thisappear and developers can just define new class variables on the fly for example i have come across a program like soclass acommanduicommand fields field runtimestepsummary bool type def init self runtimestepsummaryfalse selfruntimestepsummary runtimestepsummary other methods def executeself cont result selftimestepsummaries other codethe thing that confuses and slightly irritates me is that this a class does not have a field called timestepsummaries yet how can a developer in the middle of a method just define a new field or is my understanding incorrectso to be clear my question is in python can we dynamically define new fields to a class during runtime like in this example or is this timestepsummaries variable an instance of a java like private variableedit i am using python 27,['python'] +625554,remove element nodes in postorder traversal say i have the following html condenseddivdivdivullitextliuldivdivdivdivdivdivullitext 2liuldivdivdivdivdivdivullitext 3liuldivdivdivi want to remove the lowest child elements first until ultimately removing the parent then move on to the next parent element and its children this can be easily accomplished by a simple loop that goes through each child element removes it then removes the next child element ie parent of the previous childvar children bodyfindvar i childrenlengthfunction loop childreniremove i if i 1 settimeoutloop 20 loopthe problem with this however is that it removes the child elements from the lowest parent element first if you were to run this code with my test markup you could see what i meani want to remove the child elements from the top most parent then work my way down therefore reversing the order of the above code i was able to somewhat accomplish this with the following codevar parents bodychildrennotemptyvar i 0var speed 10function loop var children parentsifind var x childrenlength function inside childrenxremove x if x 1 settimeoutinside speed else if i parentslength parentsi 1remove loop else if i parentslength parentsi 1remove inside iloopthe problem with this code however is that it only reverses the order of deleting with respect to the parent element if there are multiple child elements within a parent it will still delete them in the default ascending order bottom to topmy question therefore is how can i delete all the elements in descending order regardless of how many child elements there are in a much cleaner fashion there has to be a much better approach than what i attempted jquery is not a requirement either the reason for the settimeouts is because i need a delay between removing the elements as usual i probably overlooked something relatively simple so bear with meto reiterate if the html looks like thisdiv divchild 1div divchild 2div div divchild 3div divchild 4div divdivi would want it to be deleted in the following orderchild 1child 2child 3child 4,"['javascript', 'jquery']" +625590,rails 4 bootstrap set up assets i am trying to setup bootstrap on rails4 using bootstrapsass and i am getting this famous errorsprocketsfilenotfound could not find file bootstrap in appassetsjavascriptsapplicationjs16i have tried followingtwitterbootstrap in applicationjsgem bootstrapsass 310 is outside group assetsalso tried bunch of other things on interneti have spend lot of time taking different suggestions from other posts how do i systematically debug this how to setup bootstrapsass psalso been trying to get twitterbootstraprails working with no luckhere are some filesapplicationjs require jquery require jquery ujs require jsroutes require bootstrap require tree require bootstrapsliderapplicationcscss require jqueryuicore require jqueryuitheme require self require bootstrapslider require tree stub active adminimport bootstrapgemfilesource ruby 200gem rails 400gem sassrailsgem coffeerails git gitgithubcomrailscoffeerailsgitgem uglifier 103gem jqueryuirailsgem fontawesomesassgem lessrailsgem therubyracer platformrubygem twitterbootstraprailsgem jqueryrailsgem jquery mobile railsgem jsroutesgem cancangem devisegem figarogem hamlrailsgem pggem rolifygem sendgridgem simple formgem thingem raketo use db for storing cookies instead cookiestoregem activerecordsession store github railsactiverecordsession storegroup development do gem better errors gem binding of caller platformsmri 19 rbx commenting out platforms part because may be that is stopping this to be used on the dev machine gem binding of caller gem guardbundler gem guardrails gem guardrspec gem html2haml gem quiet assets gem rbfchange requirefalse gem rbfsevent requirefalse gem rbinotify requirefalse required with rails panel chrome extension this gem should come after better errors gem gem meta requestendgroup development test do gem factory girl rails gem rspecrails gem prybyebug gem prystack explorer gem pryrails gem prydebuggerendgroup test do gem capybara gem database cleaner gem email specendgroup production do gem rails 12factorendgem high voltagelinkedin loginsgem linkedingem omniauthgem omniauthlinkedingem omniauthfacebookpostgres use hstore in active recordgem activerecordpostgreshstoregem state machinegem rubygraphvizpaymentsgem stripegit gem anjlabbootstraprails require bootstraprails github anjlabbootstraprailsgem newrelic rpmgem pgbackupsarchivegem pg searchgem actsastaggableongem activeadmin github gregbellactive admingem activeadmin git admingem kaminarigem bootstrapsliderrailsgem bootstrapsass 310,['ruby-on-rails'] +625621,android ndk dalvik heap and native heap how separate between the two i know there is dalvikjvm heap and native heap in an android platformand the dalvik gc has no work on native heapbut i am not sure how this work i mean how the android os separate thempossible situation 1 composed by separate memory hardware i do not believe muchpossible situation 2 android os has fixed amount of memory for both heappossible situation 3 android os has to allocate part of dalvik memory heap to become native heap when necessary and so the size of native heap and dalvik heap is flexiblewhich one is true or possibility that i did not mention,['android'] +625646,http response setcookie not accessible i am currently writing an angularjs frontend to my backend and i am running into a somewhat common issueserver sends a cookie back in a response but is completely ignored by angularjs cannot even print out the setcookie valuei have tried readingsetcookie in http header is ignored with angularjsangularjs http does not seem to understand setcookie in the responsebut unfortunately i have tried all the solutions there and just does not seem to workrequest sentresponse receivedi am using angularjs v1210 and this is what i used to make the requesthttppostservicesapiemaillogin sanitizecredentialscredentials withcredentials true successfunctiondata status header consolelogheaderserver consolelogheadersetcookie consolelogheaderaccesscontrolallowheaders consolelogheaderaccesscontrolallowmethods consolelogheader then functionresponse consolelogresponse return responsedata withcredentialstrue is set on the client side before making the request accesscontrolallowcredentialstrue is set on the server side before returning the responseyou can clearly see setcookie is in the response headers from chrome developer tools but printout is justonly setcookie in the response header is not being printed out i am wondering why does this occur is there a way for me to make sure withcredentialstrue is indeed set i did not see it in the request headerany help is appreciated,['javascript'] +625663,how to use bolts frameworkfacebookparse just now i see this announcement from facebook about bolts framework for ios i can see this as main concept the first component in bolts is atasksa which make organization of complex asynchronous code more manageable but i did not get this i get confused about bolt framework that how could use itwhether it related to webservice or use to parsing json response they did not provide any example with xcode projects only provide example with parseobject with parse sdk but i do not about parse sdk facebook provide explanation about this but i cannot find out how to integrate with my projectcode they provided is very confusingobject saveasyncobj continuewithblockidbftask task if taskiscancelled the save was cancelled else if taskerror the save failed else the object was saved successfully saveresult saveresult taskresult return nilwe can download boltsframework here anyone could explain more about this i am very eager to know about this new techupdate here i received some answer about new question of boltsexamples assume you want to load all images from assertlibrary and resize all images to standard size while loading so it will struck if do with main thread in this place if you go with async operation means how to use bftask with it another ex in one time you are trying to call 10 webservice parallel with async operation how could you use gcd with bftask,['ios'] +625694,unicode escape syntax in java in java i learned that the following syntax can be used for mentioning unicode characters that are not on the keyboard eg nonascii charactersuuhexdigithexdigithexdigithexdigitmy question iswhat is the purpose of u in the above syntaxone use case that i understood which represents yen symbol in java is char ch u00a5,['java'] +625833,uicollectionview with dynamic height not getting same space between cell i am having similar problem like thisi am generating height of view at run timehere is my codeinterface collectionviewcontroller nsmutablearray arrmainpropertynonatomicstrong nsmutablearray arrmainendimplementation collectionviewcontrollersynthesize arrmain voidviewdidload super viewdidload cview registernibuinib nibwithnibnamecviewcell bundlenil forcellwithreuseidentifierkcellid cviewflowlayout fl cviewflowlayout alloc init selfcviewcollectionviewlayout fl nsstring strjson my function which returns json string sbjson parser sbjson alloc init selfarrmain nsmutablearray alloc init selfarrmain parser objectwithstringstrjson errornil for int i0 iselfarrmain count i nsdictionary dic selfarrmain objectatindexi self settagsuiview alloc init seldictionarydic this function generates height and save it to the dictionary cview reloaddata nsintegercollectionviewuicollectionview view numberofitemsinsectionnsintegersection return selfarrmain count cgsizecollectionviewuicollectionview collectionview layoutuicollectionviewlayout collectionviewlayout sizeforitematindexpathnsindexpath indexpath nsdictionary dic selfarrmain objectatindexindexpathrow return cgsizemake23640dic valueforkeytags height intvalue uicollectionviewcell collectionviewuicollectionview cv cellforitematindexpathnsindexpath indexpath cviewcell cell cviewcell cv dequeuereusablecellwithreuseidentifierkcellid forindexpathindexpath nsdictionary dic selfarrmain objectatindexindexpathrow if cell viewwithtag11 cell viewwithtag11 release cell viewwithtag11 removefromsuperview uiview viewtags uiview alloc init viewtags settag11 viewtags setbackgroundcoloruicolor lightgraycolor self settagsviewtags seldictionarydic viewtags setframecgrectmake5 10 content width dic valueforkeytags height floatvalue cellcontentview addsubviewviewtags return celli had tried above link solution but it is not working for mehere is an image of my output i need the spacing to be same is anyone having solution for this issue is this bug of uicollectionview because i found this issue in this article also,"['ios', 'objective-c']" +625863,resize a 2d numpy array excluding nan i am trying to resize a 2d numpy array of a given factor obtaining a smaller array in outputthe array is read from an image file and some of the values should be nan not a number npnan from numpy it is the result of remote sensing measurements from satellite and simply some pixels werent measuredthe suitable package i found for this is scypymiscimresize but each pixel in the output array containing a nan is set to nan even if there are some valid data in the original pixels interpolated togethermy solution is appended here what i have done is essentially create a new array based on the original array shape and the desired reduction factorcreate an index array to address all the pixels of the original array to be averaged for each pixel in the new cycle through the new array pixels and average all the notnan pixel to obtain the new array pixel value it there are only nan the output will be nani am planning to add keyword to choice between different output average median standard deviation of the input pixels and so onit is working as expected but on a 1mpx image it takes around 3 seconds due to my lack of experience in python i am searching for improvementsdo anyone have suggestion how to do it better and more efficientlydo anyone know a library that already implements all that stuffthankshere you have an example output for random pixel input generated with the code here belowimport numpy as npimport pylab as pltfrom scipy import miscdef resize 2d nonanarrayfactor resize a 2d array by different factor on two axis sipping nan values if a new pixel contains only nan it will be set to nan parameters array 2d np array factor int or tuple if int x and y factor wil be the same returns array 2d np array scaled by factor created on mon jan 27 152125 2014 author damo ma xsize ysize arrayshape if isinstancefactorint factor x factor factor y factor elif isinstancefactortuple factor x factor y factor0 factor1 else raise nameerrorfactor must be a tuple xy or an integer if not xsize factor x 0 or ysize factor y 0 raise nameerrorfactors must be intger multiple of array shape new xsize new ysize xsizefactor x ysizefactor y new array npemptynew xsize new ysize new array npnan this saves us an assignment in the loop below submatrix indexes is the average box on the original matrix subrow subcol npindicesfactor x factor y new matrix indexs row col npindicesnew xsize new ysize some output for testing for i j ind in ziprowreshape1 colreshape1rangerowsize print print i i j i ind i i j ind print subrowinew ysize subcoljnew xsize print inew xsizeifactor x print jnew ysizejfactor y print subrowifactor xsubcoljfactor y print print arraysubrowifactor xsubcoljfactor y print arraysubrowifactor xsubcoljfactor y for i j ind in ziprowreshape1 colreshape1rangerowsize define the small sub matrix as view of input matrix subset sub matrix arraysubrowifactor xsubcoljfactor y modified from anya and alla to aany and aall see if not npisnansub matrixall if we have not all nan if npisnansub matrixany if we haven no nan at all msub matrix npmamasked arraysub matrixnpisnansub matrix new arrayreshape1ind npmeanmsub matrix else if we haven some nan new arrayreshape1ind npmeansub matrix the case assign nan if we have all nan is missing due to the standard values of new array return new arrayrow cols 6 4a 10nprandomrandom samplerow colsa0302 npnana02 npnanfactor x 2factor y 2a misc miscimresizea 5 interpnearest modefa 2d nonan resize 2d nonanafactor xfactor yprint aprintprint a miscprintprint a 2d nonanpltsubplot131pltimshowainterpolationnearestplttitleoriginalpltxticksarangeashape1pltyticksarangeashape0pltsubplot132pltimshowa miscinterpolationnearestplttitlescipymiscpltxticksarangea miscshape1pltyticksarangea miscshape0pltsubplot133pltimshowa 2d nonaninterpolationnearestplttitlemyfuncpltxticksarangea 2d nonanshape1pltyticksarangea 2d nonanshape0editi add some modification to address chrisprosser commentif i substitute the nan with some other value let say the average of the notnan pixels it will affect all the subsequent calculation the difference between the resampled original array and the resampled array with nan substituted shows that 2 pixels changed their valuesmy goal is simply skip all the nan pixels substitute nan with the average value ind nonan ind nan npwherenpisnana false npwherenpisnana truea substitute npcopyaa substituteind nan npmeana substituteind nonan substitute the nan with average on the notnana substitute misc miscimresizea substitute 5 interpnearest modefa substitute 2d nonan resize 2d nonana substitutefactor xfactor yprint a 2d nonana substitute 2d nonan nan 002296697 023143208 0 0 0 2nd editto address the hookeds answer i put some additional code it is an iteresting idea sadly it interpolates new values over pixels that should be empty nan and for my small example generate more nan than good valuesx y npindicesrow colsx new y new npindicesrowfactor x colsfactor yfrom scipyinterpolate import cloughtocher2dinterpolator as intpc intpxind nonanyind nonanaind nonana interp cx new y newprint aprintprint a interp nan nan nan nan nan 632826577,['python'] +625903,how do i handle fork correctly with boostasio in a multithreaded program i am having some trouble grasping how to correctly handle creating a child process from a multithreaded program that uses boost asio in a multithreaded fashionif i understand correctly the way to launch a child process in the unix world is to call fork followed by an exec also if i understand correctly calling fork will duplicate all file descriptors and so on and these need to be closed in the child process unless marked as fd cloexec and thereby being atomically closed when calling execboost asio requires to be notified when fork is called in order to operate correctly by calling notify fork however in a multithreaded program this creates several issuessockets are by default inherited by child processes if i understand correctly they can be set to sock cloexec but not directly at creation thus leading to a timing window if a child process is being created from another threadnotify fork requires that no other thread calls any other io service function nor any function on any other io object associated with the io service this does not really seem to be feasible after all the program is multithreaded for a reasonif i understand correctly any function call made between fork and exec needs to be async signal safe see fork documentation there is no documentation of the notify fork call being async signal safe in fact if i look at the source code for boost asio at least in version 154 there may be calls to pthread mutex lock which is not async signal safe if i understand correctly see signal concepts there are also other calls being made that are not on the white listissue 1 i can probably work around by separating creation of child processes and sockets files so that i can ensure that no child process is being created in the window between a socket being created and setting sock cloexec issue 2 is trickier i would probably need to make sure that all asio handler threads are stopped do the fork and then recreate them again which is tideous at best and really really bad at worst what about my pending timers issue 3 seems to make it entirely impossible to use this correctlyhow do i correctly use boost asio in a multithreaded program together with fork exec or am i forkedplease let me know if i have misunderstood any fundamental concepts i am raised on windows programming not nixedit actually it is possible to create sockets with sock cloexec set directly on linux available since 2627 see socket documentation on windows the corresponding flag wsa flag no handle inherit is available since windows 7 sp 1 windows server 2008 r2 sp 1 see wsasocket documentation os x does not seem to support this though,['c++'] +625936,namespace or assembly i am getting very confused between namespaces and assemblies are systemdata and systemweb namespaces or assembliesi have noticed these are called namespaces and at the same time they are present in gac 32 folder so what exactly are they,"['c#', '.net']" +626035,java how do i store a timelineschedule location full or empty from time x to y interval some brief backgroundi have a java app that is used to see when certain locations classrooms are in use or not the user puts a location identifier into a search box and the program thisplays any events classes matching the app will thisplay all the pertinent information class name room professor name day of week time of class classes that are insession or soon to be are colorcoded so you can tell ataglance if there is anything coming up the data comes from an html page i am scraping from i do not have sql accesseverything to this point works i am using javaswing for the ui the events are stored as a basic object i made to hold it the only part that matters for my question is that it stores to java date objects for the start and end time of each eventwhat i am trying to do now is add a way to check for and thisplay the gaps between events when a classroom is empty i have all the data i need all the start and end times but i am having trouble coming up with a way to actually to actually code the program to see the gapsand if that is not challenging enough i want to implement it as simply as possible not using any extra libraries i do not want to recreate the wheel but i would much rather hash out the code by hand than just throw in an import and a couple method calls half the point of this project is to challenge myselffor now i am not looking for advice on how to actually thisplay the data for now i am just trying to logically organize it in a usable way it will end up being thisplayed in a jtable but i am not working on that implementation yetmy scraper pulls from an html table something like td idtime10am 15amtd and parses it down to two strings 10am and 15am these get passed with other data to my course objectmy course object has a dateformat set so it can interpret the incoming strings into datespublic class course static dateformat tf new simpledateformathmmaprivate string nameprivate string roomprivate string instructorprivate date startprivate date endprivate string dayspublic coursestring n string r string in string st string ed string d throws parseexception namen roomr instructorin starttfparsest endtfparseed daysdbasic getters setters and a tostringthe idea is that i will set two times setting the window in which i want to check for gaps i want to pick an interval say 15 minutes and find all the gaps of 15 or more minutes during which a classroom is empty ie no classes meeting,['java'] +626131,how to make 1 9 pass misra we are using parasoft static analysis with misra c 2004 checker turned on the software is an embedded system we like to describe constants as follows1 define motor on 1 9 this would show that the 9th bit in the register should be a 1 to turn on the motor the expression is failing misra so we changed it2 define motor on 1u 9uthe changes convert to unsigned integer constants because shifting is best done with unsigned integers the expression in statement 2 is still failing because of the right hand operator 9u needs checking according to misra if the right hand operator is larger than the bit width of the underlying type of the left hand operator there is a problem the base of the problem is that 1u has an underlying type of unsigned char or 8bitsthe register we are writing to is 16bits so theoretically there is not an issuehow can i change the expression in 2 so that it passes misra c 2004 preferring not to use castsi am using iar embedded workbench with an arm7tdmi processor in 832 bit mode edit 1 example code void turn on motorvoiddefine motor on 1u 9uvoid turn on motorvoid uint16 t const p motor control uint16 t 0x01234567u p motor control motor onerror text constant used as the righthand operand of a shift operator shall be limited from the misra rule documentation provided by parasoft rule reports a violation if the righthand operand is a constant with negative value or with value that exceeds the length in bits of the lefthand operand the righthand operand is not a constant and is not checked by specific pattern,['c'] +626158,jsonnet default deserialization behavior for a single property in customcreationconverter in the following scenario how do i get crazyitemconverter to carry on as usual when it encounters a json property that exists in the type i am deserializing toi have some json that looks like this item nameapple idnull size5 quality2 the json gets deserialized into a class that looks a whole lot like thisjsonconvertertypeofcrazyitemconverterpublic class item jsonconvertertypeofcrazystringconverter public string name get set public guid id get set jsonignore public dictionarystring object customfields get if customfields null customfields new dictionarystring object return customfields crazyitemconverter populates the values of the known properties and puts the unknown properties in customfields the readjson in it looks like thispublic override object readjsonjsonreader reader type objecttype object existingvalue jsonserializer serializer var outputobject createobjecttype var objprops objecttypegetpropertiesselectp pnametoarray while readerread if readertokentype jsontokenpropertyname string propertyname readervaluetostring if readerread if objpropscontainspropertyname no idea serializerpopulatereader outputobject else outputobjectaddpropertypropertyname readervalue return outputobjectduring deserialization when crazyitemconverter encounters a known property i want it to act as it normally would meaning respecting the jsonconvertertypeofcrazystringconverter for namei was using the code below to set the known properties but it throws exceptions on nullables and does not respect my other jsonconverterspropertyinfo pi outputobjectgettypegetpropertyreadervalue bindingflagsignorecase bindingflagspublic bindingflagsinstancevar convertedvalue convertchangetypereadervalue pipropertytypepisetvalueoutputobject convertedvalue nullany ideasupdate i have learned that serializerpopulatereader outputobject is how to deserialize the whole thing but it does not seem to work if you want default functionality on a propertybyproperty basis,['c#'] +626301,use steamworks api to pull competitive game scores i have a dilemma that i need to figure outso i am building a website where people can go watch a competitive game such as counter strike global offensive perhaps using either a twitch tv stream or actually through the matchmaking streaming services that the game may offer in the case of this example cs go tv while playing members can place bets on which teams will win using some form of credits with no real value of course the issue here is that the site will need to be able to pull the score from the game and update in real time so sticking with the example of csgo is there a portion of the steamworks api that would allow for realtime pulling of a games score through some kind of php or javascript method,['php'] +626324,remove right and bottom margin on infowindows i am playing around with the google infowindowand almost everything is perfect i am just missing something on the windowsi always have a right and bottom white spacei do not mind that much for the bottom one but i would like to get rid of the right oneany idea how to do that edit here is the codediv classgmstyleiw styleposition absolute left 12px top 9px overflow auto width 352px height 290px div class styleoverflow auto div classinfobox div stylemaxwidth 352px padding 0px div idinfomapelement div clastreet img srcamplocation37783105912246528ampfov90ampheading235amppitch10ampsensorfalse alt div clashadowdiv div classtitle customer historybr 123 foo av san francisco ca 12345div div div classwrap clearfix div classitem clearfix small20130911small pthis is the a test of customer history purchasesp div classrow clearfix div classcollg5 cost estimate span110spandiv div classcollg7 purchase no span123456789spandiv div div classrow clearfix div classcollg12 sell by a hrefmy online seller dot comadiv div div div classrow clearfixdiv div div div divdivmap newsfeed gmstyleiw width 352pximportant height autoimportant left 0important fontsize 15pximportant fontweight normalimportant top 0important overflow hiddenimportant borderradius 3pxmap newsfeed gmstyleiw div overflow hiddenimportantgmstyle gmstyleiw gmstyle gmstyleiw a gmstyle gmstyleiw span gmstyle gmstyleiw label gmstyle gmstyleiw div fontsize 13px fontweight normalinfomapelement row div fontsize inherit fontweight inheritinfomapelement shadow width 100 height 100 bottom 0 webkitboxshadow 0 35px 75px rgba095 inset boxshadow 0 35px 75px rgba095 inset position absolute fontstyle normal fontweight normal zindex 1map gmstyle fontfamily inheritinfomapelement pagination margin 10px 0 0infobox img position absolute top 0px right 25px thisplay block zindex 3infomapelement pointer width23px height19px top 99 left 41 positionabsolute thisplayblock background transparent url assets3pointer downpng infomapelement wrap padding 0infomapelement wrap itemnthchildeven background ecececinfomapelement wrap item padding 10pxlegend strong float left margin 0 10px 0 0 thisplay blockedti 2so i can change the dom the way i want it with jquery those 3 lines workgmstyleiwnextdivcssright 52pxgmstyleiwprevdivchildrenlastcsswidth 351pxgmstyleiwprevdivchildren1csswidth 351pxbut for some reason only the first line get executed,"['javascript', 'html', 'css']" +626418,put tabs in the bottom of screen i want to put tabs at the bottom part of my screen for this purpose i have the following code package infoandroidhivetabsswipeimport infoandroidhivetabsswipeadaptertabspageradapterimport androidappactionbarimport androidappactionbartabimport androidappfragmenttransactionimport androidosbundleimport androidsupportv4appfragmentactivityimport androidsupportv4viewviewpagerpublic class mainactivity extends fragmentactivity implements actionbartablistener private viewpager viewpager private tabspageradapter madapter private actionbar actionbar tab titles private string tabs top rated games movies override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main initilization viewpager viewpager findviewbyidridpager actionbar getactionbar madapter new tabspageradaptergetsupportfragmentmanager viewpagersetadaptermadapter actionbarsetnavigationmodeactionbarnavigation mode tabs actionbarsetthisplayshowhomeenabledfalse actionbarsetthisplayshowtitleenabledfalse adding tabs for string tab name tabs actionbaraddtabactionbarnewtabsettexttab name settablistenerthis on swiping the viewpager make respective tab selected viewpagersetonpagechangelistenernew viewpageronpagechangelistener override public void onpageselectedint position on changing the page make respected tab selected actionbarsetselectednavigationitemposition override public void onpagescrolledint arg0 float arg1 int arg2 override public void onpagescrollstatechangedint arg0 override public void ontabreselectedtab tab fragmenttransaction ft override public void ontabselectedtab tab fragmenttransaction ft on tab selected show respected fragment view viewpagersetcurrentitemtabgetposition override public void ontabunselectedtab tab fragmenttransaction ft by this code i have the following layout package infoandroidhivetabsswipeimport infoandroidhivetabsswipeadaptertabspageradapterimport androidappactionbarimport androidappactionbartabimport androidappfragmenttransactionimport androidosbundleimport androidsupportv4appfragmentactivityimport androidsupportv4viewviewpagerpublic class mainactivity extends fragmentactivity implements actionbartablistener private viewpager viewpager private tabspageradapter madapter private actionbar actionbar tab titles private string tabs top rated games movies override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main initilization viewpager viewpager findviewbyidridpager actionbar getactionbar madapter new tabspageradaptergetsupportfragmentmanager viewpagersetadaptermadapter actionbarsetnavigationmodeactionbarnavigation mode tabs actionbarsetthisplayshowhomeenabledfalse actionbarsetthisplayshowtitleenabledfalse adding tabs for string tab name tabs actionbaraddtabactionbarnewtabsettexttab name settablistenerthis on swiping the viewpager make respective tab selected viewpagersetonpagechangelistenernew viewpageronpagechangelistener override public void onpageselectedint position on changing the page make respected tab selected actionbarsetselectednavigationitemposition override public void onpagescrolledint arg0 float arg1 int arg2 override public void onpagescrollstatechangedint arg0 override public void ontabreselectedtab tab fragmenttransaction ft override public void ontabselectedtab tab fragmenttransaction ft on tab selected show respected fragment view viewpagersetcurrentitemtabgetposition override public void ontabunselectedtab tab fragmenttransaction ft by this code this is how the screen looks after compilation how can i put tabs at the bottom of the screen,"['java', 'android']" +626433,mfmailcomposeviewcontroller bar background color not changing in ios7 i am trying to change the background color of the mfmailcomposeviewcontroller in ios7 but i cannot make it worki am using the following snippedmfmailcomposeviewcontroller picker mfmailcomposeviewcontroller alloc initpickermailcomposedelegate selfifpickernavigationbar respondstoselectorselectorbartintcolor ios7 pickernavigationbarbartintcolor reader navigation bar background color set back button arrow color pickernavigationbar settintcolorreader navigation bar back button arrow color set navigation bar title color pickernavigationbar settitletextattributesnsdictionary dictionarywithobjectreader navigation bar title normal font color forkeyuitextattributetextcolor set back button color uibarbuttonitem appearancewhencontainedinuinavigationbar class nil settitletextattributesnsdictionary dictionarywithobjectsandkeysreader navigation bar buttons font color uitextattributetextcolornil forstateuicontrolstatenormal does anybody knows how to change the backcground color of the mfmailcomposeviewcontroller in ios7,"['ios', 'objective-c']" +626445,facebook paper what 3rd party libraries are used for what parts of the app i just download facebook paper app for ios there is a lot of great stuff in this app specifically animation wise it runs smooth as butter for me too some really great stuff going on behind the scenes evidentlywhat i would like to know is what libraries are used for which features of the app 3rd parties libraries used are listed below there is a truckload of them basically how did they get it looking and working as well as it does which of these libraries can i use to do the samesince this is a pretty broad question specifically i would like to know about animations fold swipe down tap on a settings section tap an icon was a third party library used how did facebook achieve the smoothness and complexity of animations that are thereall 3rd party libraries from facebook paper are listed belowace appiraterreachabilityaqgridviewbitvectboostbreadcrumbbreakpadchromiumcocoahttpservercocoalumberjackdcroundswitchdtcoretextegodatabaseexpatfft by mark olesonfft by takuya oouraghkitghunitgoogle toolbox for macgooglewebtoolkitgtestgypie 754r half precision floatinghpgrowingtextviewinappsettingskitios5cookbookios8601parserunparserjqueryjsjsonkitleveldblibcomponentloggingcorelibcomponentloggingnsloglibjinglelibjpegturbolibjpeglibphonenumberioslibphonenumberlibsrtplibvpxlibyuvllvmreturnmazeroingweakrefminizipmizpaneliphonemosquittomessagepack objective c implemessagepackmsinttypesopencv tutorialsnimbusnjkwebviewprogressunmodified objc4objqrencoderochamcrestocmockocpdfgenomnigroup omniuiopensslopenudidopuspeertalkphotoscrollerphpplcrashreporterpmtk3pocketobjcsdkportaudioprotobufpstcollectionviewsutilitiesrestkitring buffer utilitysdurlcachesdwebimagesockitspdyforiphonespdylayspreadsortssziparchivetdoauthtiqruamodalpanelwebkitwebpwebrtcwebviewjavascriptbridgexmlreaderyamlcppyasmzlibzxing,"['ios', 'iphone', 'objective-c']" +626458,plotting histograms against classes in pandas matplotlib is there a idiomatic way to plot the histogram of a feature for two classesin pandas i basically wantdffeaturedfclass 0histdffeaturedfclass 1histto be in the same plot i could dodffeaturehistbydfclassbut that gives me two separate plotsthis seems to be a common task so i would imagine there to be an idiomatic way to do this of course i could manipulate the histograms manually to fit next to each other but usually pandas does that quite nicelybasically i want this matplotlib example in one line of pandas examplesbarchart demohtmli thought i was missing something but maybe it is not possible yet,['python'] +626478,springdata fetch join with paging is not working i am trying to use hql fetching my entity along with subentities using join fetch this is working fine if i want all the results but it is not the case if i want a pagemy entity is entitydatapublic class visitentity id audited private long id onetomanycascade cascadetypeall private listvisitcommententity commentsand because i have millions of visits i need to use pageable and i want to fetch the comments in a single database query like queryselect v from visitentity v left join fetch vcomments where vvenueid venueid and public pagevisitentity getvenuevisitsparamvenueid long venueid pageable pageablethat hql call throws the following exceptioncaused by javalangillegalargumentexception orghibernatequeryexception query specified join fetching but the owner of the fetched association was not present in the select list fromelementexplicitnot a collection joinfetch joinfetch nonlazy propertiesclassaliasnullrolecomrolibvisitentityvisitentitycommentstablenamevisitdbvisit commenttablealiascomments1 originvisitdbvisit visitentit0 columnsvisitentit0 visit id classnamecomrolibvisitentityvisitcommententity select countv from comrolibvisitentityvisitentity v left join fetch vcomments where vvenueid venueid and vactualarrival date or varrival dateat orghibernateejbabstractentitymanagerimplconvertabstractentitymanagerimpljava1374at orghibernateejbabstractentitymanagerimplconvertabstractentitymanagerimpljava1310at orghibernateejbabstractentitymanagerimplcreatequeryabstractentitymanagerimpljava309at sunreflectnativemethodaccessorimplinvoke0native methodand once i remove the paging everything works finequeryselect v from visitentity v left join fetch vcomments where vvenueid venueid and public listvisitentity getvenuevisitsparamvenueid long venueidobviously the problem is the count query from springdata but how can we fix it,['java'] +626557,how to create fulltext index on some columns i am running the following query on tbl queryselect from tbl query q where matchqquery descqquery desc details against test1 with query expansionit is giving an error 164622 select from tbl query q where matchqquery descqquery desc details against test1 with query expansion limit 0 10 error code 1191 cannot find fulltext index matching the column list 0078 sec my table is like this create table tbl query query id int11 not null auto increment query desc text not null query desc details text primary key query id key query desc query desc3 using btree key query desc details query desc details3 using btree enginemyisam auto increment5 default charsetutf8in database full text words boundaries are likeft max word len 84ft min word len 4 i am searching against two columnso my question is how to create the full text index for the table,['mysql'] +626565,how can i draw inline line labels in matplotlib i have the following graph consisting of several linesnow i would like to label all the lines in the plot however using legend crams all the labels together in a box which makes the plot somewhat difficult to interpret what i would like to to instead is to use inline labels my ideal output would use labels like the following matplotlib contour plot but with text labels for lines instead of numbersi have not been able to find out how to do this in the matplotlib documentation is there a way to achieve this if not what other software could i use to generate this type of plot,['python'] +626584,how to produce formatting similar to nets 0 in iostreams i would like to output a floatingpoint number as a percentage with up to three decimal placesi know that iostreams have three different ways of presenting floatsdefault which thisplays using either the rules of fixed or scientific depending on the number of significant digits desired as defined by setprecisionfixed which thisplays a fixed number of decimal places defined by setprecision andscientific which thisplays a fixed number of decimal places but using scientific notation ie mantissa exponent of the radixthese three modes can be seen in effect with this codeinclude iostreaminclude iomanipint main double d 095 double e 095 stdcout stdsetprecision3 stdcoutunsetfstdiosfloatfield stdcout d 100 d n stdcout e 100 e n stdcout stdfixed stdcout d 100 d n stdcout e 100 e n stdcout stdscientific stdcout d 100 d n stdcout e 100 e n output d 95e05 e 95 d 0 e 950 d 9500e05 e 9500e01none of these options satisfies mei would like to avoid any scientific notation here as it makes the percentages really hard to read i want to keep at most three decimal places and it is ok if very small values show up as zero however i would also like to avoid trailing zeros in fractional places for cases like 095 above i want that to thisplay as in the second line as 95in net i can achieve this with a custom format string like 0 which gives me a number formatted as a percentage with at least one digit left of the decimal separator and up to three digits right of the decimal separator trailing zeros skipped can i achieve this with iostreams without writing my own formatting logic eg special casing small numbers,['c++'] +626607,how does applicationcontextaware work in spring in spring if a bean implements applicationcontextaware then it is able to access the applicationcontext therefore it is able to get other beanseg public class springcontextutil implements applicationcontextaware private static applicationcontext applicationcontext public void setapplicationcontextapplicationcontext context throws beansexception applicationcontext context public static applicationcontext getapplicationcontext return applicationcontext then springcontextutilgetapplicationcontextgetbeanname can get the bean nameto do this we should put this springcontextutil inside the applicationsxml egbean classcomutilspringcontextutil here the bean springcontextutil does not include the property applicationcontext i guess when spring bean initialize this property is set but how is this done how does the method setapplicationcontext get called,['java'] +626664,equivalient method overload why necessary i browsed some java code made by google and i found the immutableset they implemented the of method with several other wayspublic static e immutablesete ofe e1 e e2public static e immutablesete ofe e1 e e2 e e3public static e immutablesete ofe e1 e e2 e e3 e e4public static e immutablesete ofe e1 e e2 e e3 e e4 e e5public static e immutablesete ofe elementsi checked the implementation which is herethere is a create method wiith the following signatureprivate static e immutablesete createe elementswhich wraps the private static e immutablesete createiterable extends e iterable int countmethod the public methods just passes the parameters to the createe elements signatured method which finally calls the other create methodi guess that the public of methods with fixed count of parameter are unnecessary since we have the ofe elements methodmy question is that why did they do that like this performance or it is a patternthanks,['java'] +626665,entityframework testing that savechanges is present and called in the correct place in a method i have a class like the following that i want to unit testpublic class addusercommand idbcontext dbcontext public addusercommandidbcontext context dbcontext context public void execute dbcontextusersaddnew user dbcontextsavechanges ultimately i need to test whether the execute method persists the new user to the database when using a real sql database connection but for my unit tests i obviously want to use some kind of mock objectin my tests i can make a mock idbcontext which mimics the behaviour and it all works i can test that the mock context contains the new user after the execute method has been run my problem is that when using the mock context the test will pass if i do not call the savechanges method this is because the mock context does not need to make an sql query to actually persist the data it persists without the call to savechanges because the users collection represents the persistent storein order to check that savechanges is called many online sources for example and say to add something like this to the mock contextpublic class mockdbcontext idbcontext boolean saved public void savechanges saved true and then test if the saved variable is true after the execute method is called however what i find lacking in this approach is that such a test will pass if the execute method did thispublic void execute dbcontextsavechanges dbcontextusersaddnew userwhich of course would not save any changes as it is done too earlyi believe that mocking frameworks like rhinomocks allow you to test the order of method calls to the mock context but i have also read that this is not best practice you should test the result not the minutae of the implementationthe problem is that the mock context does not exactly replicate what the real dbcontext will doso my question is is there a standard way to mock an entity framework dbcontext in such a way that any additions or deletions of objects are only committed to the mock when savechanges is called or is this not something that is generally tested for,['c#'] +626805,how do i pass a parameter to the onopen method with jee7 websockets i have this code serverendpointvalue websocketpublic class service private string clientid onopen public void initsession session throws ioexception opening a websocket get clientid clientid code here to get initialization parameter how do i get initialization parameters from the client opening the socket,['java'] +626870,trigger event when user scroll to specific element with jquery i have an h1 that is far down a pageh1 idscrolltotrigger event when scrolled toh1and i want to trigger an alert when the user scrolls to the h1 or has it in it is browsers viewscrolltoscrollfunction alertyou have scrolled to the h1how do i do this,"['javascript', 'jquery', 'html']" +626876,jasmine 20 teamcity reporter had a working ci build with teamcity requirejs and jasmine 13 running phantomjsexe and i am trying to upgrade jasmine to version 20i got a basic html specrunner page working following this great post jasmine is now loaded on windowsonload now i am trying to get the teamcityreporter working from the plugins page under testing framework it has a dependency on the jasmine global and does not see it even though i can consolelog the jasmineversion but really my question is does anybody have one that works or has a good explanation on how the reporters are loaded and how they work now in jasmine 20thanks,['javascript'] +626922,input checkbox in div jumps to top of page on firefox i use div over label and input typecheckbox i do this in order to have the checkbox look like a buttonhere is my example what should i do with a checkbox or labelinput that will stop jumping to the top of my page this happens only on firefox any idea how to fix this,"['html', 'css']" +626980,html5 javascript how to catch attempt to initiate navigation out of sandboxed iframe i have an sandboxed iframe that does not allow changing locationiframe sandboxallowforms allowpopups allowpointerlock allowsameorigin allowscripts classiframe visible srcthesourcehtml width100 scrollingauto frameborder0iframeif the iframe tries to unframe itself or change location i see a blank page because the browser stops the iframes operation this is the log from chromeunsafe javascript attempt to initiate navigation for frame with url from frame with url the frame attempting navigation of the toplevel window is sandboxed but the allowtopnavigation flag is not setthat is great but i want to catch this so if it happens i will move to the next iframe so how do i catch this attemptediti added a jsfiddle code check the error in the console logi also tried to listen for an event with no successdocumentaddeventlistenererror receivemessage truefunction receivemessageerror alertiframe tried to unframe itself,"['javascript', 'html']" +627024,optimization of naive matrix multiplication icc vs gcc the code below uses a very straightforward approach to calculate the matrix product a b and store the result in c the code was compiled with o3 on both gcc 446 with mtunenative and intel compiler 1301 and the speed on gcc is significantly worse over a factor of two for the sample data usedi am curious about the cause of these differences but unfortunately i am not familiar enough with the assembly output to understand whats going on here from a glance it looks as though icc is doing a better job at vectorizing the computation but i cannot decipher much more than that this is mainly for learning purposes since there is no way i would use this in productionvoid attribute noinline mm line 3 int n double restrict c double restrict a double restrict b int i j k for i 0 i n i for j 0 j n j ci and j 0 line 12 for k 0 k n k ci and j ai and k bk and j line 14 here is the output from gcc z2mmipds s lfb0 cfi startproc cfi personality 0x3 gxx personality v0 pushq r14 cfi def cfa offset 16 cfi offset 14 16 testl edi edi n movq rcx r14 b b pushq r13 cfi def cfa offset 24 cfi offset 13 24 pushq r12 cfi def cfa offset 32 cfi offset 12 32 pushq rbp cfi def cfa offset 40 cfi offset 6 40 pushq rbx cfi def cfa offset 48 cfi offset 3 48 jle l6 leal 1rdi eax tmp96 movslq edi r11 n n movq rdx rbx a ivtmp54 xorl r12d r12d ivtmp67 salq 3 r11 d2193 xorl ebp ebp prephitmp37 leaq 8rax8 r13 d2208l3 leaq rsir12 r10 ivtmp61 movq r14 rcx b ivtmp63 xorl edx edx j p2align 410 p2align 3l5 movq 0 r10 ivtmp61 movq rbp 8rsp prephitmp37 movq rcx r9 ivtmp63 ivtmp70 movsd 8rsp xmm1 prephitmp37 movq rbx r8 ivtmp54 ivtmp69 xorl eax eax k p2align 410 p2align 3l4 movsd r8 xmm0 ivtmp69 tmp99 addl 1 eax k addq r11 r8 d2193 ivtmp69 mulsd r9 xmm0 ivtmp70 tmp99 addq 8 r9 ivtmp70 cmpl edi eax n k addsd xmm0 xmm1 tmp99 prephitmp37 movsd xmm1 r10 prephitmp37 ivtmp61 jne l4 addl 1 edx j addq r11 r10 d2193 ivtmp61 addq r11 rcx d2193 ivtmp63 cmpl edi edx n j jne l5 addq 8 r12 ivtmp67 addq 8 rbx ivtmp54 cmpq r13 r12 d2208 ivtmp67 jne l3 l6 popq rbx cfi def cfa offset 40 popq rbp cfi def cfa offset 32 popq r12 cfi def cfa offset 24 popq r13 cfi def cfa offset 16 popq r14 cfi def cfa offset 8 ret cfi endprocand here is the output from icc begin z2mmipds s mark begin align 160x90 globl z2mmipds s z2mmipds s parameter 1 edi parameter 2 rsi parameter 3 rdx parameter 4 rcxb11 preds b10 tag value z2mmipds s 1 83 pushq r12 83 tag value z2mmipds s 3 pushq r13 83 tag value z2mmipds s 5 pushq r14 83 tag value z2mmipds s 7 pushq r15 83 tag value z2mmipds s 9 pushq rbx 83 tag value z2mmipds s 11 pushq rbp 83 tag value z2mmipds s 13 subq 72 rsp 83 tag value z2mmipds s 15 movq rsi r9 movslq edi rax xorl r10d r10d 119 testl edi edi 1125 jle b17 prob 10 1125 loe rax rdx rcx rbx rbp rsi r9 r12 r13 r14 r15 edi r10db12 preds b11 movl edi r11d 105 lea rax8 r8 andl 4 r11d 105 movq rax r14 1228 movslq r11d r11 105 movl edi r12d 1228 movq rsi 8rsp 1228 movq r8 rbp 1228 movq rdx 32rsp 1228 movq r9 r13 1228 movq rcx rsp 1228 movl r10d r15d 1228 pxor xmm0 xmm0 1228 movq r11 rbx 1228 loe rbx rbp r13 r14 r12d r15db13 preds b15 b148 b145 b12 cmpl 12 r12d 105 jle b138 prob 0 105 loe rbx rbp r13 r14 r12d r15db14 preds b13 movq r13 rdi 1213 xorl esi esi 1213 movq rbp rdx 1213 call intel fast memset 1213 loe rbx rbp r13 r14 r12d r15db15 preds b14 incl r15d 119 lea r13r148 r13 119 cmpl r12d r15d 119 jb b13 prob 82 119 loe rbx rbp r13 r14 r12d r15db16 preds b148 b145 b15 infreq movl r12d edi movq r14 rax movq 8rsp rsi testl edi edi 1125 movq 32rsp rdx movq rsp rcx loe rax rdx rcx rbx rbp rsi r12 r13 r14 r15 edib17 preds b11 b16 infreq movl 0 r9d 119 movl 0 r8d jle b133 prob 10 1125 loe rax rdx rcx rbx rbp rsi r8 r12 r13 r14 r15 edi r9db18 preds b17 infreq movq rdx 32rsp loe rax rcx rsi r8 edi r9db19 preds b131 b18 infreq xorl r12d r12d lea rsir88 r13 1417 movq r13 r15 105 xorl ebx ebx 1313 andq 15 r15 105 xorl r10d r10d movl r15d r14d 105 lea rcxr88 rbp 1448 andl 7 r14d 105 xorl r11d r11d movl r14d 48rsp xorl edx edx movl r15d 56rsp movq r13 40rsp movq r8 16rsp movl r9d 24rsp movq rsi 8rsp movq rcx rsp movq 32rsp r14 loe rax rdx rbp r10 r12 r14 ebx edi r11db110 preds b130 b19 infreq cmpq 8 rax 105 jl b134 prob 10 105 loe rax rdx rbp r10 r12 r14 ebx edi r11db1 preds b110 infreq movl 56rsp r9d 105 testl r9d r9d 105 je b114 prob 50 105 loe rax rdx rbp r9 r10 r12 r14 ebx edi r11db112 preds b1 infreq cmpl 0 48rsp 105 jne b134 prob 10 105 loe rax rdx rbp r10 r12 r14 ebx edi r11db113 preds b112 infreq movl 1 r9d 105 loe rax rdx rbp r9 r10 r12 r14 ebx edi r11db114 preds b113 b1 infreq movl r9d r13d 105 lea 8r13 rcx 105 cmpq rcx rax 105 jl b134 prob 10 105 loe rax rdx rbp r9 r10 r12 r13 r14 ebx edi r11db115 preds b114 infreq movl edi r15d 105 xorl ecx ecx 105 subl r9d r15d 105 movslq r11d r8 1433 andl 7 r15d 105 negl r15d 105 addl edi r15d 105 movslq r15d r15 105 testq r13 r13 105 lea r14r88 rsi 1433 jbe b135 prob 0 105 loe rax rdx rcx rbp rsi r8 r9 r10 r12 r13 r14 r15 ebx edi r11db116 preds b115 infreq movsd r10rbp xmm0 1448 movq 40rsp r14 1448 loe rax rdx rcx rbp rsi r8 r9 r10 r12 r13 r14 r15 ebx edi r11d xmm0b117 preds b117 b116 infreq movsd rsircx8 xmm1 1433 mulsd xmm0 xmm1 1448 addsd r14rcx8 xmm1 1417 movsd xmm1 r14rcx8 1417 incq rcx 105 cmpq r13 rcx 105 jb b117 prob 82 105 loe rax rdx rcx rbp rsi r8 r9 r10 r12 r13 r14 r15 ebx edi r11d xmm0b118 preds b117 infreq movq 32rsp r14 loe rax rdx rbp rsi r8 r9 r10 r12 r13 r14 r15 ebx edi r11d xmm0b119 preds b118 b135 infreq addq r9 r8 1433 lea r14r88 rcx 1433 testq 15 rcx 105 je b123 prob 60 105 loe rax rdx rbp rsi r10 r12 r13 r14 r15 ebx edi r11d xmm0b120 preds b119 infreq movq 40rsp rcx 1448 unpcklpd xmm0 xmm0 1448 loe rax rdx rcx rbp rsi r10 r12 r13 r14 r15 ebx edi r11d xmm0b121 preds b121 b120 infreq movsd rsir138 xmm1 1433 movsd 16rsir138 xmm2 1433 movsd 32rsir138 xmm3 1433 movsd 48rsir138 xmm4 1433 movhpd 8rsir138 xmm1 1433 movhpd 24rsir138 xmm2 1433 movhpd 40rsir138 xmm3 1433 movhpd 56rsir138 xmm4 1433 mulpd xmm0 xmm1 1448 mulpd xmm0 xmm2 1448 mulpd xmm0 xmm3 1448 mulpd xmm0 xmm4 1448 addpd rcxr138 xmm1 1417 addpd 16rcxr138 xmm2 1417 addpd 32rcxr138 xmm3 1417 addpd 48rcxr138 xmm4 1417 movaps xmm1 rcxr138 1417 movaps xmm2 16rcxr138 1417 movaps xmm3 32rcxr138 1417 movaps xmm4 48rcxr138 1417 addq 8 r13 105 cmpq r15 r13 105 jb b121 prob 82 105 jmp b126 prob 100 105 loe rax rdx rcx rbp rsi r10 r12 r13 r14 r15 ebx edi r11d xmm0b123 preds b119 infreq movq 40rsp rcx 1448 unpcklpd xmm0 xmm0 1448 align 160x90 loe rax rdx rcx rbp rsi r10 r12 r13 r14 r15 ebx edi r11d xmm0b124 preds b124 b123 infreq movaps rsir138 xmm1 1433 movaps 16rsir138 xmm2 1433 movaps 32rsir138 xmm3 1433 movaps 48rsir138 xmm4 1433 mulpd xmm0 xmm1 1448 mulpd xmm0 xmm2 1448 mulpd xmm0 xmm3 1448 mulpd xmm0 xmm4 1448 addpd rcxr138 xmm1 1417 addpd 16rcxr138 xmm2 1417 addpd 32rcxr138 xmm3 1417 addpd 48rcxr138 xmm4 1417 movaps xmm1 rcxr138 1417 movaps xmm2 16rcxr138 1417 movaps xmm3 32rcxr138 1417 movaps xmm4 48rcxr138 1417 addq 8 r13 105 cmpq r15 r13 105 jb b124 prob 82 105 loe rax rdx rcx rbp rsi r10 r12 r13 r14 r15 ebx edi r11d xmm0b126 preds b124 b121 b134 infreq cmpq rax r15 105 jae b130 prob 0 105 loe rax rdx rbp r10 r12 r14 r15 ebx edi r11db127 preds b126 infreq movsd rbpr128 xmm0 1448 lea r14rdx8 rcx 1433 movq 40rsp rsi 1448 loe rax rdx rcx rbp rsi r10 r12 r14 r15 ebx edi r11d xmm0b128 preds b128 b127 infreq movsd rcxr158 xmm1 1433 mulsd xmm0 xmm1 1448 addsd rsir158 xmm1 1417 movsd xmm1 rsir158 1417 incq r15 105 cmpq rax r15 105 jb b128 prob 82 105 loe rax rdx rcx rbp rsi r10 r12 r14 r15 ebx edi r11d xmm0b130 preds b128 b126 infreq incl ebx 1313 addq rax rdx 1313 addl edi r11d 1313 addq 8 r10 1313 incq r12 1313 cmpl edi ebx 1313 jb b110 prob 82 1313 loe rax rdx rbp r10 r12 r14 ebx edi r11db131 preds b130 infreq movl 24rsp r9d incl r9d 119 movq 16rsp r8 addq rax r8 119 movq 8rsp rsi cmpl edi r9d 119 movq rsp rcx jb b19 prob 82 119 loe rax rcx rsi r8 edi r9db133 preds b131 b17 infreq addq 72 rsp 181 tag value z2mmipds s 16 popq rbp 181 tag value z2mmipds s 18 popq rbx 181 tag value z2mmipds s 20 popq r15 181 tag value z2mmipds s 22 popq r14 181 tag value z2mmipds s 24 popq r13 181 tag value z2mmipds s 26 popq r12 181 tag value z2mmipds s 28 ret 181 tag value z2mmipds s 29 loeb134 preds b110 b114 b112 infreq xorl r15d r15d 105 jmp b126 prob 100 105 loe rax rdx rbp r10 r12 r14 r15 ebx edi r11db135 preds b115 infreq movsd rbpr128 xmm0 1448 jmp b119 prob 100 1448 loe rax rdx rbp rsi r8 r9 r10 r12 r13 r14 r15 ebx edi r11d xmm0b138 preds b13 infreq cmpq 4 r14 105 jl b147 prob 10 105 loe rbx rbp r13 r14 r12d r15db139 preds b138 infreq xorl esi esi 105 movq rbx rdx 105 movq r13 rcx xorl eax eax pxor xmm0 xmm0 loe rax rdx rcx rbx rbp rsi r13 r14 r12d r15d xmm0b140 preds b140 b139 infreq addq 4 rsi 105 movq rax rcx 1213 movhpd xmm0 8rcx 1213 movq rax 16rcx 1213 movhpd xmm0 24rcx 1213 addq 32 rcx 105 cmpq rbx rsi 105 jb b140 prob 82 105 loe rax rdx rcx rbx rbp rsi r13 r14 r12d r15d xmm0b142 preds b140 b147 infreq cmpq r14 rdx 105 jae b148 prob 0 105 loe rdx rbx rbp r13 r14 r12d r15db143 preds b142 infreq xorl ecx ecx loe rdx rcx rbx rbp r13 r14 r12d r15db144 preds b144 b143 infreq movq rcx r13rdx8 1213 incq rdx 105 cmpq r14 rdx 105 jb b144 prob 82 105 loe rdx rcx rbx rbp r13 r14 r12d r15db145 preds b144 infreq incl r15d 119 lea r13r148 r13 119 cmpl r12d r15d 119 jb b13 prob 82 119 jmp b16 prob 100 119 loe rbx rbp r13 r14 r12d r15db147 preds b138 infreq xorl edx edx 105 jmp b142 prob 100 105 loe rdx rbx rbp r13 r14 r12d r15db148 preds b142 infreq incl r15d 119 lea r13r148 r13 119 cmpl r12d r15d 119 jb b13 prob 82 119 jmp b16 prob 100 119 align 160x90 tag value z2mmipds s 36 loe rbx rbp r13 r14 r12d r15d mark end type z2mmipds s function size z2mmipds s z2mmipds s data end z2mmipds s edit with the help of olaf dietsche it looks like the code below can run much faster with gcc 482 though still a bit 30 slower than intel the main difference is that the initialization is done ahead of time this by itself makes no difference and the loop ordering has been interchanged this makes a major difference for gcc memsetc 0 and n for j 0 j n j for k 0 k n k for i 0 i n i ci and j ai and k bk and j line 14,"['c++', 'c']" +627140,wrong contenttype header generated using multipartformdatacontent i have the following codeprivate static string boundary customboundary datetimenowtickstostringxprivate static async taskstring posttest string servresp using var content new multipartformdatacontentboundary contentaddnew stringcontent105212 caseid contentaddnew stringcontent1142014 datefrom contentaddnew stringcontent1152014 dateto httpclienthandler handler new httpclienthandler cookiecontainer new cookiecontainer handlercookiecontainer cookiecontainer httprequestmessage request new httprequestmessagehttpmethodpost requestheadersexpectcontinue false requestcontent content httpclient new httpclienthandler httpresponsemessage response await httpclientsendasyncrequest responseensuresuccestatuscode servresp await responsecontentreadasstringasync return servrespwhen i run it i see the contenttype header in fiddlercontenttype multipartformdata boundarycustomboundary8d0f01e6b3b5dafbecause the boundary value is in quotes the server ignores the request body if i remove the quotes and run the request in fiddler composer the request is being processed correctlyi tried adding the content headersrequestcontentheadersaddcontenttype multipartformdata boundary boundaryrequestcontentheaderscontenttype new systemnethttpheadersmediatypeheadervaluemultipartformdata boundary boundary but it did not work the error messages were cannot add value because header contenttype does not support multiple values and the format of value multipartformdata boundarycustomboundary8d0f024297b32d5 is invalid correspondinglyhow can i add the proper contenttype header to the request so that the boundary value would not be enclosed in quotescontenttype multipartformdata boundarycustomboundary8d0f01e6b3b5daf,['c#'] +627178,using python and beautifulsoup saved webpage source codes into a local file could you help me with this problem pleaseenvironment python 27 beautifulsoup 432i am trying to using python and beautifulsoup to pick up information on a webpage because the webpage is in the company website requires login and redirection so i copy the source codes of the target page into a file and save it as aexamplehtmla in c for the convenience of practicingthis the a part of the original codestr classghj tdspan classcityshsh srccitys1jpg altboy titleboy spana hrefmembercityphpmodeviewampu12563port new capeatd td classpositiona hrefsearchphpid12563ampsrpositions titlesearch positions452atd td classdetailsdivsouthdivtd tdmay 09 1997td tdjan 23 2009 1205 pmnbsptdtrthe codes so far i worked out isfrom bs4 import beautifulsoupimport reimport urllib2url cexamplehtmlpage urllib2urlopenurlsoup beautifulsouppagereadcities soupfind allspan class cityshfor city in citiesprint city this is just the first stage of testing so somewhat not completedhowever when i run it it gives error message seems itas improper to use aurllib2urlopena to open a local filetraceback most recent call last file cpython27testingpy line 8 in page urllib2urlopenurl file cpython27liburllib2py line 127 in urlopen return openeropenurl data timeout file cpython27liburllib2py line 404 in open response self openreq data file cpython27liburllib2py line 427 in open unknown open req file cpython27liburllib2py line 382 in call chain result funcargs file cpython27liburllib2py line 1247 in unknown open raise urlerrorunknown url type s type urlerror so could you please teach me in what way i can practice by using a local file thank you,['python'] +627194,resetting form after submit in angularjs hi i have a form which does update on button click scopeaction update var id routeparamseditid scopeitem updaterecordget id id once the item is updated it does not remove the entered information in the form fields i was wondering what is available in angularjs to add in the above code after udpating so that it also clears to form thanks,['javascript'] +627218,how to outline a long span tag a outline box as below is neededthe html code ispwe spanprefer questions that can be answered notspan just thiscussedpit is difficult to get the coordinate of the lefttop point and rightbottom point of the outline boxusingoutline 2px red solidcan only work in chrome but failed in firefox and also failed in chrome while the lineheight of p is 300,"['javascript', 'html', 'css']" +627237,map object has no len in python 33 so i have this python tool wirtten by someone else to flash a certain microcontroller but he has written his tool for python 26 and i am using python 33so most of it i got ported but this linedata maplambda c ordc fileargs0 rbread is making problems the file function does not exist in python 33 and has to be replaced with open but then a function which gets data as an argument causes an exception stating that a map object is not iterablebut what i see so far in the documentation is that map has to join iterable types to one big iterable am i missing somethingwhat do i have to do to port this to python 33,['python'] +627267,setting unique constraint with fluent api i am trying to build an ef entity with code first and an entitytypeconfiguration using fluent api creating primary keys is easy but not so with a unique constraint i was seeing old posts that suggested executing native sql commands for this but that seem to defeat the purpose is this possible with ef6,['c#'] +627301,app rejected because of advertisingidentifier in facebook sdk and flurry sdk my app was rejected because of advertisingidentifier in facebook sdk and flurry sdk i found an occurrence of advertisingidentifier in the latest facebook sdk 312 and flurry sdk maybe you can check your librarys for an occurence with the method belowi opened the facebooksdkframework as a library in the terminal and typed the following commandotool v s text objc methname facebooksdk grep advertisingidentifierand the same way for flurry sdkbut i do not know what to dofor news flurry has recently update their sdk that not contain the advertisingidentifier but facebook not yet,"['ios', 'iphone', 'objective-c']" +627395,phonegap save image from url into device photo gallery i am developing phonegap application and i need to save image from url to the device photo galleryi cannot find at the phonegap api a way for doing it and also i did not find phonegap plugin for thati need it to work with iphone androidthanks a lot,"['javascript', 'android', 'ios']" +627411,vertical align span inside div div classcontainer spansome text yayspandivdiv classcontainer spansome text yay but shit time there is alot of text so we get a problem with breaking lines and the given height how can i align vertical nowspandivstylecontainer width 100 height 50px lineheight 50px border 1px solid blackcontainer span paddingleft 30pxstylethis solution works great until the screenwidth is too small breaking my text into several lineswhen i google the problem i find so many crazy overcomplicated solutions with javascript and divs to push my content in place can anyone help me make this work without adding more markup there is no need to support internet explorer and older browsersthanks,"['html', 'css']" +627526,php how to know if server allows shell exec on some servers php is not allowed to run shell commands via shell exec how can i detect if current server allows running shell commands via php or not how can i enable shell commands execution via php,['php'] +627529,karma does not find files specified in config file i am writing jasmine tests to my angularjs app i generated karmaconfjs using karma init but when i run karma start i get warnings like thiswarn webserver 404 bower componentsangularangularjswarn webserver 404 jsappjskarmaconfjs is in my app folder which is the place for the bower components folder as welli think maybe that could be because of my local test server where i am using this approach i have been able to set up the tests like this in other project without a test servercan anybody please point me in the right direction hereupdatemy karmaconfjs looks like thismoduleexports functionconfig configset basepath frameworks jasmine requirejs files testsjs jsjs bower componentsangularangularjs bower componentsangularmocksangularmocksjs bower componentsangularresourceangularresourcejs bower componentsd3d3js exclude reporters progress port 9876 colors true loglevel configlog info autowatch true browsers chrome capturetimeout 60 singlerun false heres my directory structure,['javascript'] +627603,new type definition in c i am looking for possibilities to define a new type and using it in c like belowclass definitionpublic class position public double180 longitude get set double180 is a type within a range 180 and 180 public double90 latitude get set double90 is a type within a range of 90 and 90usagevar position new position longitude 45 latitude 96 this line should give an error while initializing the object,['c#'] +627614,complex bean mapping i am trying to find the best solution for a problem i have with mapping a simple bean structure that is being sent to a browserbased javascript application the current requirement is to manage most of the thisplay control on the old java backend currently we have a service style layer that is producing value objects with no thisplay logic built into them like public class example1 string value1 boolean value2 example3 value3 public string getvalue1 public void setvalue1 my goal is to be able to map a generic structure over all fields such that it adds the new thisplay structure that is required by the frontend i would like to manage only the original structure class example1 class structure and simply set the extra values in a wrapper to the old service layerthe generic structure would take the form of the following classpublic class presentablet t value boolean visible true boolean mandatory false liststring errors new arraylist public t getvalue public void setvaluet value the end result would look something like the following where value is equal to the value in the original structurepublic class example2 presentablestring value1 presentableboolean value2 presentableexample3 value3 public presentablestring getvalue1 public void setvalue1 is there a solution to this problem without writing an example2 style class and copying in every single value i am open to modification to the example1 class as it does not affect consumers of the old servicethanks,['java'] +627677,position of the try catch statement i have some code that currently looks somewhat like thispublic void mainfunction try someproblemfunction catch allfinefunction private void someproblemfunction private void allfinefunction as you can see i am currently wrapping the call to someproblemfunction around a try statement because that function could fail it relies on an outside web service callmy question is this should the try statement be a outside the problem function like i have it now or b inside the problem functionthanks,['c#'] +627838,how to use nganimate in angular 12 baseangular 115 worksuppedangular 126 faili think i did follow the instructions from the docs a first include angularanimatejs in your html a then load the module in your application by adding it as a dependent moduleit is quite late in my timezone and i probably miss something obvious my guess would be css file between 115 and 126 is not compatible cannot really tellanyway here is the code form upped plunker i included some comments to emphasise that i followed instructions from docsdoctype htmlhtml ngappapphead meta charsetutf8 titletop animationtitle scriptdocumentwritebase href documentlocation script link relstylesheet hrefstylecss link hrefnetdnabootstrapcdncomtwitterbootstrap231cssbootstrapcombinedmincss relstylesheet script srcscript script srcscript load animate headscriptvar app angularmoduleapp nganimate dependent moduleappcontrollerctrl functionscope scopenames igor minar brad green dave geddes naomi black greg weber dean sofer wes alvaro john scott daniel nadasiscriptbody ngcontrollerctrl div classwell stylemargintop 30px width 200px overflow hidden form classformsearch div classinputappend input typetext ngmodelsearch clasearchquery stylewidth 80px button typesubmit classbtnsearchbutton div ul classnav navpills navstacked li nganimateanimate ngrepeatname in names filtersearch a href name a li ul form divbodyhtmlmany thanks for help,['javascript'] +627927,get a list of all access aceoledb drivers installed on the system using the following code i can enumerate the oledb providers registered on my systemstatic void thisplaydata var reader oledbenumeratorgetrootenumerator var list new liststring while readerread for var i 0 i readerfieldcount i if readergetnamei sources name listaddreadergetvalueitostring consolewriteline0 1 readergetname0 readergetvalue0 readercloseit returns the list of drivers we are interested in the access drivers with one caveatagainst net 45 it containssources name microsoftaceoledb150but when the project is built against net 40 the output issources name microsoftaceoledb120the machine we are testing on has 32 bit office 2013 installed which has the microsoftaceoledb150 and we have installed the 64 bit version of the access database driver which has microsoftaceoledb120 the project we are running is set to anycpu we are using windows 81why does not the enumeration always return the same resultshow can i get a list of all providers installed on my system the reason i want to is that usually i want to run against the latest driver but for certain connections i need to use an earlier version of the driver this is because i sometimes need to do an upgrade of old mdb files so if the older version is not installed i want to inform my usersmiscellaneous weirdnessif we create a console app against net 451 then change it to net 40 and run it then change it back to net 40 it continues to return the net 40 results the microsoftaceoledb120 driver,['c#'] +628005,how to use fontfamily lato how to use fontfamily lato i have used style like this but not working how can i do thank youfontfamily lato helvetica sansseriflink,['css'] +628023,are all functions noexcept if exceptions are thisabled if you turn off exceptions by compiling with fnoexceptions are all functions considered noexcept for example by stdmove if noexcept or do you still have to declare functions noexcept for that reason,['c++'] +628055,nodemon restart run gulp tasks i have the following code in my gulpfilegulptaskscripts function gulpsrcpathsbrowserify pipebrowserify pipegulpdestbuildjs piperefreshservergulptasklint function gulpsrcpathsjs pipejshint pipejshintreporterstylishgulptasknodemon function nodemon script appjs i need to run the scripts and lint tasks when nodemon restartsi have the followinggulptasknodemon function nodemon script appjs onrestart function gulprunscripts lint gulprun is now deprecated so how would i achieve the above using gulp and best practices,['javascript'] +628124,resvalue gradle error unsupported type string in generatedxml a few weeks ago i posted a question how to override resources depending on buildtypeand just yesterday there was a gradle plugin release for androidbased on this post on g i decided to write this questionthe problem i have described in detaili want to create some resource values depending on the buildtype but this does not work properlythe file generatedxml will be only created if i make a complete build over the command linegradlew buildbut i also get an error by building the complete project over comannd line what went wrong execution failed for task appmergebuildvariantresourcesunsupported type string in file cusersbuildresgeneratedreleasevaluesgeneratedxmlevery other buildtrial does not create this file i tried followingover ide rebuild projectexecute external task assemblebuildvariantover command linegradlew assemblebuildvariantstrange gradle console outputappgeneratebuildvariantresvalues uptodatemy buildgradlebuildtypes debug buildconfigfield string foo foo debug resvalue string res foo res foo debug release buildconfigfield string foo foo release resvalue string res foo res foo release my generatedxml automatically generated file do not modify values from build type release item nameres foo typestringres foo releaseitemmy questionis this a bug or did i miss something and why this file is not created by a rebuild over the idemy buildgradle update 20140210 based on rciovatis answerdefaultconfig minsdkversion 14 targetsdkversion 19 versioncode 1 versionname 10 resvalue string res foo res foobuildtypes debug buildconfigfield string foo foo debug resvalue string res foo res foo debug release buildconfigfield string foo foo release resvalue string res foo res foo release update 20140214 it worksafter an update of the gradle android plugin everything works finein buildresall you should see following foldersallgenerated here you find the generated resource values by resvaluethe first folder all contains all merged resources in the direction allbuildvariantvaluesvaluesxml you should find the generated resources in my case for buildtype debugitem nametestfoo typestringtest foo debugitem for buildtype releaseitem nametestfoo typestringtest foo releaseitemto get the values in code just use the generated resource like all othersgetresourcesgetstringrstringtestfoo,['android'] +628141,underscorejs findwhere with nested property value how do i go about the filtering below id 100 title tlt1 tax name tax1 id 15 name tax1 id 17 id 101 title tlt2 tax name tax2 id 16 id 102 title tlt3 tax name tax3 id 17 name tax3 id 18 to get only those where taxid is 17 as per below id 100 title tlt1 tax name tax1 id 15 name tax1 id 17 id 102 title tlt3 tax name tax3 id 17 name tax3 id 18 currently i use the method below but maybe there is more clean way of going about thisvar arr dataeachfunction v1 k1 v1taxeachfunction v2 k2 if v2id id arrpushv1 demo here any suggestion much appreciated,['javascript'] +628249,how to fit variable length tick labels on a d3 line chart heres a jsfiddle a slightly modified example from here as you can see in the jsfiddle tick labels along the y axis do not fit in the svg i know i can increase the left margin but the thing is i do not know what the data will be in advance if i just make the margin very large the chart will look awkward if the numbers are short in lengthis there a way to precompute the maximum label width when creating the chart to set the margin correctly or perhaps there is an entirely different solutionvar margin top 20 right 20 bottom 30 left 50 width 400 marginleft marginright height 200 margintop marginbottomvar svg d3selectbodyappendsvg attrwidth width marginleft marginright attrheight height margintop marginbottom appendg attrtransform translate marginleft margintop thanks,['javascript'] +628258,can returning a braced enclosed initializer lead to a copy in c examplestruct s int a s func return 42 int main s new obj func line 6 void new obj return 0this works now what happens if we assume that our compiler does no rvofunc returns a struct of s so 42 must be converted to s is then returned and finally copied to new obj in line 6func returns an initializer list so a deep copy is impossiblewhat does the language say can you give a proofnote i know that this does not seem useful in this example but for returning very large constant sized stdarrays i do not want to rely on rvo,['c++'] +628326,inject debug information into entity framework queries were using dapper and ef in our shop and dapper proofed to be extremely helpful in debugging queries in sql server when something went wrong instead of just submitting raw sql we created a thin decorator that also adds some context information the origin as an sql comment something like foobargetorders select from order where orderid 123this allows our dbas and developers to reacy very quickly and find the source of a problem if we have db calls that are erroneous or introduce performance hits we have hundreds of thousands of db calls per day so one bad query can cause quite some damagewe would also like to do this with ef it does not have to be an sql comment but some kind of hook in order to supply meta information that is submitted with the call any idea whether this is possiblethanks for your advicephilipp,"['c#', 'sql']" +628395,performance difference between passing interface and class reloaded there is a consensus that using interfaces is better than using classes i surely agree a library method accepting arraylist instead of list would be a crapthere is also a consensus that the performance is always the same here my benchmark begs to differthere are 1 to 4 implementations of both an interface and an abstract class when more than two implementations get used the performance starts to diverge i am looking for an explanation for this behavior and also for the origin of the false consensus,['java'] +628419,applying physics to android view objects i currently have an android application that utilises the native android views for the ui eg imageviewsbuttons etcalthough this app is not a game nor requires any heavy graphics or opengl i would like to incorporate a little physicsrelated interaction nothing too significant but maybe thisplay minor collisionsbounces decelerationacceleration or possibly frictionis this possible to simulate either within the android framework or using an external physics library like jbox2d without having to utilize an entire game engine like andengine libgx etcps this is for api 15thanks all,['android'] +628423,what are the differences and when to use seleniumwebdriver over webdriverjs i am an experience professional that uses seleniumwebdriver i am exploring more options on how to test javascript applications and i found webdriverjs unfortunately i dont understand whats the difference between these two 2 can someone please explain when to use seleniumwebdriver over webdriverjs and the benefitsthanks,['javascript'] +628436,stdfind error no matching function say that i have a class a and a class b that look like thatclass aprivate int apublic bool operatorconst a constother methodsclass bprivatestdvectora vpublicstdvectora get v return vconst stdvectora get v constnow when i do thatb bstdvectoraiterator ititstdfind bget vbegin bget vend an item of class athe error i get iserror no matching function for call to findstdvectoraiterator stdvectoraiterator aam i missing something thanks,['c++'] +628458,double render error rails not sure how its possible to get this error abstractcontrollerdoublerendererror userscreatewhen in my controller i got this code render new and returni got the log from the bugsnag saying that i got the error at this linethis is the create method code def create back button and return if paramsback button profile current userbuild profileparamsuser if profilenil current usernil profileusernil sign out redirect to signup path and return end if profilenew record render new and return else redirect to more questions path and return endendi have before filter in this controller before filter signed in userdef signed in user unless signed in store location redirect to signin url notice please sign in end end,"['ruby-on-rails', 'ruby']" +628544,finally equivalent for ifelif statements in python does python have a finally equivalent for its ifelse statements similar to its tryexceptfinally statements something that would allow us to simplify this if condition1 do stuff clean up elif condition2 do stuff clean up elif condition3 do stuff clean up to this if condition1 do stuff elif condition2 do stuff elif condition3 do stuff finally clean upwhere finally would only be called only after a condition was met and its do stuff run conversely if no condition was met the finally code would not be run i hate to spout blasphemy but the best way i can describe it is there being a goto statement at the end of each block of do stuff that led to finallyessentially it works as the opposite of an else statement while else is only run if no other conditions are met this would be ran only if another condition was met,['python'] +628571,oslistdir is removing character accent in windows file explorer create a new txt file name it atxt note the accent over the nhold shift and right click the folder where you created atxt and select open command window here or alternatively open cmdexe and cd into the directory where you created the filerun python terminalprint oslistdir note that the file is thisplayed as ntxtprint mapospathexistsoslistdir note the file doesnt existsi have tried many decodings but oslistdir is not returning the bytestring of the actual filename at all so encodingdecoding the incorrect bytes is still the incorrect bytes,['python'] +628629,does using the this keyword affect java performance does using the this keyword affect java performance at allin this exampleclass prog private int foo progint foo thisfoo foo is there performance overhead doing that over the followingclass prog private int foo progint bar foo bar a couple of coworkers and i were thiscussing this earlier today and no one could come up with an answer the we all agreed on any definitive answer,['java'] +628749,composer the requested package php could not be found every time i try and run composer install the dependencies fail due to the following errorthe requested package php could not be foundi have got this working on a lamp stack but i am trying to get it working on a lemp stack now with php5fpm and its not going well php vphp 5583suryorgprecise2 cli built jan 29 2014 132355 copyright c 19972013 the php groupzend engine v250 copyright c 19982013 zend technologies with zend opcache v703dev copyright c 192013 by zend technologiesediti have other stuff in mine but i tested the following composerjson on the same server and its still doing itcomposerjson require php 54 my composer version is composer version b7a9ea4187bce63f418bf7ba035b63dcb1e23ef6 20140206 220747am i missing something,['php'] +628766,foundation 5 no longer using xlarge and xxlarge grid sizes problemin foundation 502 and up it is not using the xlarge and xxlarge grid sizes they worked in prior versions 500 and 501so when going into the css file from foundation it will only show small medium and large grid sizesapparently no version of foundation 5 has xlarge and xxlarge blockgrids eitherquestionis there a way to get these to work againtestsi went to their website and downloaded the latest 511 and it had the same issue in foundationcssi am building it myself with sass and also tried adding in the override variables in there manually here we define the lower and upper bounds for each media sizesmallrange 0em 40em 0 640pxmediumrange 40063em 64em 641px 1024pxlargerange 64063em 90em 1025px 1440pxxlargerange 90063em 120em 1441px 1920pxlargerange 120063em 1921pxscreen only screenlandscape screen and orientation landscapeportrait screen and orientation portraitsmallup screensmallonly screen and maxwidth upperboundsmallrangemediumup screen and minwidthlowerboundmediumrangemediumonly screen and minwidthlowerboundmediumrange and maxwidthupperboundmediumrangelargeup screen and minwidthlowerboundlargerangelargeonly screen and minwidthlowerboundlargerange and maxwidthupperboundlargerangexlargeup screen and minwidthlowerboundxlargerangexlargeonly screen and minwidthlowerboundxlargerange and maxwidthupperboundxlargerangexxlargeup screen and minwidthlowerboundxxlargerangexxlargeonly screen and minwidthlowerboundxxlargerange and maxwidthupperboundxxlargerange,['css'] +628899,how does this declaration invoke the most vexing parse consider the following programinclude fstreamstruct a int mainint argc char argv a astdfstreamargv1clang in c1y mode reckons that the mvp is invoked such that a is parsed as a function declarationclang stdc1y o3 wall wextra pedanticerrors pthread maincpp aoutmaincpp68 warning parentheses were thisambiguated as a function declaration wvexingparse a astdfstreamargv1 maincpp69 note add a pair of parentheses to declare a variable a astdfstreamargv1 i understand the mvp but not in this instance argv1 is clearly an expression and there is no type before it so how could this line be parsed as a function declarationis it that the semantic interpretation on argv1 that would thisambiguate the line as an object declaration does not occur until after the compiler has already chosen to parse the line as a function declaration or is it a clang bug or is it perfectly normal through some interpretation of the tokens argv 1 that i am missing,['c++'] +628908,eclipse errorswarnings ignore assert in unused variable analysis i have had hidden bugs due to eclipse not reporting unused variables because they were used in an assertion precondition for examplepublic void methodfinal string text other parameters assert stringutilsisnotblanktext the text variable is never used in the method if eclipse had reported the variable as unused i would have noticed that something is wrong with the code i would like to tell eclipse to ignore assertions when checking for unused variables i doubt anyone would pass a parameter to only run an assertion on italso let me know if findbugs or another tool can do this,['java'] +628914,does msvcrt uses a different heap for allocations since vs201220102013 i have read about that some time ago but am unable to locate the change to the crt on msdn or anywhere else in the webi think the msvcrt has been changed in the vc release of vs2012 in a way that it no longer uses the private heap for allocations and uses process heap insteadafaik it targeted issues of memory allocated in multiple libs which link statically against a crt and the subsequent release of memory in another lib where it was allocatedthis is a major change in my view and i wonder why i cannot find any doc mentioning iteither that or i made it up which i doubt as i have thiscussed the topic with colleagues some time ago,['c++'] +628966,laravel tokenmismatchexception in ajax request i am using resource group and use this filter to resolve tokenmismatchexception problemroutefiltercsrf functionroute request if strtoupperrequest getmethod get return get requests are not csrf protected token request ajax request headerxcsrftoken inputget token if sessiontoken token throw new illuminatesessiontokenmismatchexception my route routegrouparrayprefix admin before csrf function routeresourceprofile profilecontroller arrayasprofile now i get error to ajax requests such as this codescript typetextjavascript documentreadyfunction frmsubmitfunctione epreventdefault name nameval family familyval email emailval currpassword currpasswordval password passwordval password confirmation password confirmationval post routeadminprofileupdate profileid method put name name family family email email currpassword currpassword password password password confirmation password confirmation functiondata alertdataerrorsname json return false scripterrorerrortypeilluminatesessiontokenmismatchexceptionmessagefilevarwalachiqappfiltersphpline83i think i am must be sent token in post but i can not get input tag with name attribute iget this errortypeerror stepup called on an object that does not implement interface htmlinputelement,['php'] +629072,c does this pattern have a name and can it be improved the motivationlet us say i am writing a tree class i will represent nodes of the tree by a treenode class methods of the class might return treenode objects and take them as arguments such as a method which gets the parent of a node node getparentnodei will also want a specialtree class specialtree should extend the interface of a tree and be usable anywhere a tree isbehind the scenes tree and specialtree might have totally different implementations for example i might use a librarys grapha class to implement a tree so that treenode is a thin wrapper or a typedef for a graphanode on the other hand specialtree might be implemented in terms of a graphb object and a treenode wraps a graphbnodei will later have functions which deal with trees like a depthfirst search function this function should accept both tree and specialtree objects interchangeablythe patterni will use a templated interface class to define the interface for a tree and a special tree the template argument will be the implementation class for exampletemplate typename implementationclass treeinterface public typedef typename implementationnode node virtual node addnode 0 virtual node getparentnode 0class treeimplementation grapha graph public typedef graphanode node node addnode return graphaddnode node getparent return the parent class tree public treeinterfacetreeimplementation treeimplementation impl public tree implnew treeimplementation tree delete impl virtual node addnode return impladdnode virtual node getparent return implgetparent i could then derive specialtreeinterface from treeinterfacetemplate typename implementationclass specialtreeinterface public treeinterfaceimplementation virtual void specialtreefunction 0and define specialtree and specialtreeimplementation analogously to tree and treeimplementationmy depthfirst search function might look like thistemplate typename tvoid depthfirstsearchtreeinterfacet treeand since specialtree derives from treeinterface this will work for tree objects and specialtree objectsalternativesan alternative is to rely more heavily on templates so that specialtree is not a descendent of treeinterface in the type hierarchy at all in this case my dfs function will look like template typename t depthfirstsearcht tree this also throws out the rigidly defined interface describing exactly what methods a tree or its descendents should have since a specialtree should always act like a tree but provide some additional methods i like the use of an interfaceinstead of the treeinterface template parameter being the implementation i could make it take a representation class that defines what a node looks like it will also have to define what an arc looks like and so on but since i will potentially need one of these for each of the implementations i think i would like to keep this together with the implementation class itselfwhat do i gain by using this pattern mostly a looser coupling if i would like to change the implementation behind tree specialtree does not mind at all because it only inherits the interfacethe questionsso does this pattern have a name i am using the handlebody pattern by storing a pointer to contourtreeimplementation in contourtree but what about the approach of having a templateized interface does this have a nameis there a better way to do this it does seem that i am repeating myself a lot and writing a lot of boilerplate code but those nested node classes give me trouble if treenode and specialtreenode had reasonably similar implementations i could define a nodeinterface interface for a node in treeinterface and override the implementation of the node class in tree and specialtree but as it is i cannot guarantee that this is true treenode may wrap a graphanode and specialtreenode may wrap an integer so this method would not quite work but it seems like there might still be room for improvement any thoughts,['c++'] +629099,android 40 43 included web storage lost between webview pages i am working on an android project which relies on the webview to browse multiple html pages stored on the device and submit the inputs toward the webview when it is needed for storing them in a databaseeach page contains controls that are bound with jquery towards previous next pages each page contains inputs of differents types checkboxes textfields etcthe last page contains a submit buttons that uses the jsinterface to save the results inside a sqlite dbanother button in a custom top navigation bar offers the same systemresults can be modified by accessing the first page with all the saved inputs a jquery system will fill the corresponding inputsfor more details i am using the sdk 19 and compiling against 442 but i used to work with the sdk 15 and compiling against 422 where i did not have the issueif someone needs to see what is done in a simplified system check this jsbinthe issuei am using sessionstorage to store the inputs between the pages i used to work with cookies but they became unreliable when there was over 150 keyvalues pairsmy problem is that on some devices the sessionstorage thisappear between pagestest protocol1st case staying on the first page onlyif i stay on the first page only fill the inputs then send the results everythings finecoming back for modification offers me a fully filled first page2nd case moving between pagesafter filling page 1 i move to page 2 and fill the new inputs then move between pages to see if the inputs are lost on each individual pageseverything is in place but if i send the results only the current page inputs are transmittedandroid versions test results32 works412 does not work421 does not work43 does not work442 workstested solutionsoverriding the webviewclients shouldoverrideurlloading method to return false does not workusing localstorage instead of sessionstorage did not change a thinginsightsswitching from sessionstorage to localstorage did not helpi found some useful informations about the webkit versions used by android android 321 uses a quite old version but it works v53413android versions ranging from 40 to 43 share the same webkit engine v53430android 44 uses a brand new version v53736 of it which explains why it worksnot a single step toward a fix but it gives a more precise view of the problem and the device it affectssolutionsince the sdk 16 a new security setting has been forced to prevent javascript code to access content from any originifbuildversionsdk int 16 settingsetallowuniversalaccessfromfileurlstruekudos to ksasq for finding this edit 18022014after some testing i pin pointed the problem to the targetsdkversion the buildtarget does not change anythingit it is set to 15 the webstorage works as intendedif it is set to 16 or higher the webstorage is messing up,"['java', 'javascript', 'android']" +629108,how to create an array with angularjss ngmodel i am trying to create an array holding telephones i have this codeinput typetext ngmodeltelephone0 input typetext ngmodeltelephone1 but i cannot access scopetelephone,['javascript'] +629136,ios 71 beta5 tableviewcell height showing objects outside it is range i have an app that has a list of uitableviewcells by default the cells are set to a certain height lets say 100 to show only some basic information when the user clicks on a cell the height changes to 150 to show more actions that were previously not seen this works without a problem on ios 700705 i am testing on an iphone 5s running ios 71 beta 5 and seeing some drawing issues with the cells heres how it looks on ios 70 versions which is what is expected when the cell is collapsed the buttons that are positioned past the height of the cell are hidden and when the cell is expanded to a height to show the buttons they are visiblecell expandedthe following is the cell when collapsedhere are the issues i am seeing with ios 71 beta im curious if this is just something that is a problem with the beta or if i will have to rethink how this is being coded currently as far as i can tell this has been present since the first beta of 71 as you can see the button which was previously hidden is now still showing even though the cell is collapsedis this an issue with the beta that anyone else has seen or is this expected behavior now thank you for you help,"['ios', 'objective-c']" +629157,pandas counting unique values in a dataframe we have a dataframe that looks like this dfix210 0 1 2 3 4 5 6 7 8 9 100 nan nan nan nan 6 5 nan nan 4 nan 51 nan nan nan nan 8 nan nan 7 nan nan 52 nan nan nan nan nan 1 nan nan nan nan nanwe simply want the counts of all unique values in the dataframe a simple solution is dfstackvalue counts however1 it looks like stack returns a copy not a view which is memory prohibitive in this case is this correct2 i want to group the dataframe by rows and then get the different histograms for each grouping if we ignore the memory issues with stack and use it for now how does one do the grouping correctlyd pddataframenan 1 nan 2 3 nan 1 1 1 3 nan 1 nan 2 3 nan2 3lendstack 14dstackgroupbyarange4assertionerror grouper and axis must be same lengththe stacked dataframe has a multiindex with a length of some number less than n rowsn columns because the nans are removed0 1 1 3 2 4 31 0 1 1 1 2 1 3 1 4 3 this means we do not easily know how to build our grouping it would be much better to just operate on the first level but then i am stuck on how to then apply the grouping i actually wantdstackgroupbylevel0groupbylistaabbkeyerror aedit a solution which does not use stackingf lambda x pdvalue countsxvaluesraveldgroupbylistaabbapplyfa 1 4 3 2 2 1b 2 4 3 2 1 1dtype int64looks clunky though if there is a better option i am happy to hear it edit dans comment revealed i had a typo though correcting that still does not get us to the finish line,['python'] +629244,image reflection effect using pure css i have an image in img tag my aim is to create a reflection of that image using only cssit also has to be compatible with all browsers i tried various ways to do it one of them is in this js fiddlewhat i wantthe fade to zero opacity from top to bottom on the reflection right now it works only in webkit browsers using combination of webkitboxreflect and webkitgradienti want it to work on mozilla toowhat i have right nowas it can be seen in the jsfiddle i got it working in the webkit browsers usingwebkitboxreflect below 0px webkitgradientlinear left top left bottombottom fromtransparent colorstop70 transparent torgba250 250 250 01i tried the following for mozillamozreflectafter content thisplay block background mozelementmozreflect norepeat width auto height 200px marginbottom 100px moztransform scaley1 where mozreflect is the container div for the img i would appreciate answers which can solve the problem with css only there are a lot of images icons to which this effect has to be appliedif there is no way it can be made to work in mozilla using just css then i wouldnt mind going down the javascript roadupdateit has to work on custom background which may be an image or black or any other color,"['javascript', 'jquery', 'html', 'css']" +629270,jquery validation plugin typeerror validate is not a function my script throw errorstypeerror jqueryvalidator is undefined additionalmethodsjs20 typeerror validate is not a function indexphp115probably i have mistake in jquery codeheadscript typetextjavascript srcjsjquery1102jsscriptscript typetextjavascript srcjsjqueryformjsscriptscript srcscriptheadbody form idregisterform methodpost actionlogrejphp input namelogin typetext input namenick typetext input typepassword idpassw namepassword input typepassword nameretype input typesubmit valuezarejestruj form script registerformvalidate rules login requiredtrue rangelenght 420 remotelookphp nick requiredtrue rangelenght420 remotelookphp password requiredtrue rangelenght420 retype requiredtrue equaltopassw messages login requiredto pole jest wymagane script,"['javascript', 'jquery']" +629281,does the rule of zero also apply for classes with virtual methods i find the rule of zero as also mentioned on peter sommerlads slides p32 very compellingalthough i seem to remember that there was a strict rule that one has to define the destructor virtual if the class has virtual members and is actually derived struct base virtual void drawyourself virtual base struct derived public base virtual void drawyourselfthe body of the destructor may even be empty it only needs the entry in the vtbl i seem to remember that when use the hierarchyint main base obj new derived objdrawyourself virtual call to deriveddrawyourself delete obj derivedderived must be calledthen it is important that delete obj calls the correct destructor is it correct that if i left out the destructor definition totally it would not become virtual and therefore the wrong dtor would be calledstruct base virtual void drawyourself no virtual destructorthis leads me to my final questionis the rule of zero also true in hierarchies with virtual methodsor do i need to define the virtual destructor in these casesedit as i was reminded in an answer my 1sr version of the question had the wrong assumptions the relevant virtual destructor is in base not derived but my question holds do i need to declare virtual destructors at all,['c++'] +629300,getmanifestresourcestream returns null this is a c net 40 applicationi am embedding a text file as a resource and then trying to thisplay it in a dialog box var assembly assemblygetexecutingassembly var resourcename myprojhelptxt using stream stream assemblygetmanifestresourcestreamresourcename using streamreader reader new streamreaderstream string result readerreadtoend systemwindowsformsmessageboxshowresult myproj messageboxbuttonsok the solution is myprojsolution and the executable is myprojexe helptxt is an embedded resource however the stream is null i have tried myprojsolutionhelptxt and myprojsolutionmyprojhelptxt but nothing seems to work,['c#'] +629307,why is the maximum capacity of a java hashmap 130 and not 131 why is the maximum capacity of a java hashmap 130 and not 131 even though the max value of an int is 2311 the maximum capacity is initialized as static final int maximum capacity 1 30,['java'] +629310,tutorial for scipyclusterhierarchy i am trying to understand how to manipulate a hierarchy cluster but the documentation is too technical and i cannot understand how it works is there any tutorial that can help me to start with explaining step by step some simple taskslet us say i have the following data seta nparray0 0 1 0 0 1 1 1 05 0 0 05 05 05 2 2 2 3 3 2 3 3 i can easily do the hierarchy cluster and plot the dendrogramz linkagead dendrogramznow how i can recover a specific cluster let us say the one with elements 012456 in the dendrogramhow i can get back the values of that elements,['python'] +629412,polygon vertices as uv coordinates i am working on a 3d renderer in java using the graphics class it is now capable of drawing any shape with coloured faces however i was wondering if it was possible to texture the faces i have seen a lot of people creating software renderers in javascript so surely there is an equivalent functionmethod of however they are doing it in javai have looked around so far but all i can find is graphicssetclipshape i do not think it would be suitable because it merely sets the background texture and wouldnt stretch the texture if a vertex moved and that is just in 2d it need to also stretchskew the texture when it is at an angle to the camera think of the sides of a rotating cubei really have no idea where to start i cannot use xor modes because of no skewing and i really wouldnt know how to do the math if i had to do it manuallyhow do these javascript software renderers do it so well,['java'] +629416,angulargooglemap how to load map after position data loadedlat lng i got the errorangulargooglemaps could not find a valid center property when i watch my locationdata loaded from php backend and exec initialize functionhtmldiv nginitlocationdata htmlspecialcharsdata googlemap centermapcenter zoommapzoom optionsmapoptionsgooglemapdivangular controllerappcontrollermapctrl scope function scope use strict scopewatchlocationdata function var location jsonparsescopelocationdata scopelocation lng locationlongitude lat locationlatitude initialize function initialize var mapoptions pancontrol true zoomcontrol true scalecontrol true maptypecontrol true maptypeid googlemapsmaptypeidroadmap scopemap center latitude scopelocationlat longitude scopelocationlng zoom 13 options mapoptions and i move scopemap settings to the top of the controller block and set constant value to mapcenter latitude 0 longitude 0 map show correctly angular controllerappcontrollermapctrl scope function scope use strict var mapoptions pancontrol true zoomcontrol true scalecontrol true maptypecontrol true maptypeid googlemapsmaptypeidroadmap scopemap center latitude 0 longitude 0 zoom 13 options mapoptions how can do google map directive parse after data loaded and show map correctly with backend lat lng data,['javascript'] +629501,javascript variables in html attributes i know there are a lot of posts about this but i cannot find an answer to my specific problemi would like to make a js variable the value of an html attributescript var screenwidth screenwidth script img srcimagestitlepng widthvariable here stylemargintop 3variable here is where i would want the screenwidth variable to go what is the best of going about thisthanksben,"['javascript', 'html']" +629547,which is best way to calculate speed in android whether manual calculation using gps coordinates or locationgetspeed i am trying to calculate speed in android device but which is the best practice to do it already it has locationgetspeed function using gps is this best way to use or should i calculate speed manually using gps coordinates obtained,['android'] +629596,sprintf in c resets the value of counting variable i am having an issue with sprintf in c resetting the value of a counter variable when i run it here in a nutshell is what is happeningint count 0countprintfdn count count will equal 1char title7sprintftitle 3djpg countprintfdn count count now equals 0 againis this normal behavior for sprintf,['c'] +629643,responsive iframe with max width and height i have a fixed height container containing both images and iframes to make the images responsive and preventing both vertical and horizontal overflow i can just set the following cssimg maxwidth 100 maxheight 100this ensures that a portrait image would not overflow vertically and a landscape image would not overflow horizontallyfor iframes i am using the paddingratio technique setting the padding of the wrapper element to the aspect ratio of the iframe eg 5625 for a 169 videoiframewrapper position relative height 0 paddingtop 5625 overflow hiddeniframewrapper iframe position absolute top 0 left 0 width 100 height 100while this means that the iframe scales with the width of the viewport it does not work the same if i change the height of the viewport essentially i would like the iframe to mimic how the images work,['css'] +629782,changing color of placeholder in dropdown you can see the form i am working on herethis is the code for the drop down budget tdselect idbudget stylewidth420px option valuechoose your budgetoption option value250250500 per monthoption option value500500750 per monthoption option value75075010 per monthoption option value100101500 per monthoption option value150015002500 per monthoption option value2500250050 per monthoption option value50507500 per monthoption option value7500750010 per monthoption option value1010 or more per monthoption selecttdhow can i make it so that choose your budget is the same gray colored text as the rest of the placeholders are by default and then when a budget is selected that text is the darker color i am just trying to basically make it match the color scheme the rest of the form is using,"['html', 'css']" +629800,newtonsoftjson exists in both blendnewtonsoftjsondll and solutionpackages i am not able to build the solution in visual studio 2013this just happened after i updated my jsonnet package to 601 before that it was working like a charmany ideasps it is probably something about owin it references jsonnet too i think maybe dynamicallyfull errorerror 11 the type newtonsoftjsonlinqjobject exists in both cprogram files x86microsoft visual studio 120blendnewtonsoftjsondll andcusersmedesktopsolutionsprojectpackagesnewtonsoftjson601libnet45newtonsoftjsondllcusersmedesktopsolutionsprojecttrendpinapp startstartupauthcs 48 21 projecti have this in my webconfigdependentassembly assemblyidentity namenewtonsoftjson publickeytoken30ad4fe6b2a6aeed cultureneutral bindingredirect oldversion060 newversion60dependentassemblyi have this in my csprojreference includenewtonsoftjson version60 cultureneutral publickeytoken30ad4fe6b2a6aeed processorarchitecturemsil specificversionfalsespecificversion hintpathpackagesnewtonsoftjson601libnet45newtonsoftjsondllhintpathreferencebuild output1 build started project projectbackend configuration debug any cpu 1 all packages listed in packagesconfig are already installed1cprogram files x86msbuild120binmicrosoftcommoncurrentversiontargets16355 warning msb3277 found conflicts between different versions of the same dependent assembly that could not be resolved these reference conflicts are listed in the build log when log verbosity is set to detailed1 projectbackend cusersmedesktopsolutionsprojectprojectbackendbindebugprojectbackenddll2 build started project projectdata configuration debug any cpu 2 all packages listed in packagesconfig are already installed2 projectdata cusersmedesktopsolutionsprojectprojectdatabindebugprojectdatadll3 build started project project configuration debug any cpu 3 all packages listed in packagesconfig are already installed3cprogram files x86msbuild120binmicrosoftcommoncurrentversiontargets16355 warning msb3243 no way to resolve conflict between newtonsoftjson version60 cultureneutral publickeytoken30ad4fe6b2a6aeed and newtonsoftjson version4500 cultureneutral publickeytoken30ad4fe6b2a6aeed choosing newtonsoftjson version60 cultureneutral publickeytoken30ad4fe6b2a6aeed arbitrarily3 consider appconfig remapping of assembly newtonsoftjson cultureneutral publickeytoken30ad4fe6b2a6aeed from version 4500 cprogram files x86microsoft visual studio 120blendnewtonsoftjsondll to version 60 cusersmedesktopsolutionsprojectpackagesnewtonsoftjson601libnet45newtonsoftjsondll to solve conflict and get rid of warning3cprogram files x86msbuild120binmicrosoftcommoncurrentversiontargets16355 warning msb3247 found conflicts between different versions of the same dependent assembly in visual studio doubleclick this warning or select it and press enter to fix the conflicts otherwise add the following binding redirects to the runtime node in the application configuration file assemblybinding xmlnsurnschemasmicrosoftcomasmv1dependentassemblyassemblyidentity namenewtonsoftjson cultureneutral publickeytoken30ad4fe6b2a6aeed bindingredirect oldversion060 newversion60 dependentassemblyassemblybinding3cusersmedesktopsolutionsprojectprojectapp startstartupauthcs48214828 error cs0433 the type newtonsoftjsonlinqjobject exists in both cprogram files x86microsoft visual studio 120blendnewtonsoftjsondll and cusersmedesktopsolutionsprojectpackagesnewtonsoftjson601libnet45newtonsoftjsondll4 skipped build project projecttests configuration debug any cpu 4project not selected to build for this solution configuration build 2 succeeded 1 failed 0 uptodate 1 skipped,"['c#', 'asp.net', '.net']" +629829,skype invitation message i want to invite a user sending a specific message but i cannot find where i can set invitation messagethis is a simplified sample of what i doskypeclientstarttrue truevar user skypesearchforusersthe name i am searching for castuser firstordefaultif user null userbuddystatus tbuddystatusbudpendingauthorizationwith this code default invitation is sent,['c#'] +629867,conversion failed when converting the nvarchar value to data type int i created the procedure listed belowcreate procedure getdata id int frm varchar250 to varchar250asbegindeclare sql nvarchar500set sql selectset sql sql empname address salary from emp tb where 11 if id and id is not null begin set sqlsql and emp id pk id end endprint sqlexecute sqli try to execute it usingexecute getdata 3but i am getting the following errorconversion failed when converting the nvarchar value select empname address salary from emp tb where 11 and emp id pk to data type intplease help,['sql'] +629910,androidostransactiontoolargeexception retrieving installed applications i am recovering all the applications installed on the device and i stumbled upon this errorjavalangruntimeexception an error occured while executing doinbackgroundat androidosasynctask3doneasynctaskjava300at javautilconcurrentfuturetaskfinishcompletionfuturetaskjava355at javautilconcurrentfuturetasksetexceptionfuturetaskjava2at javautilconcurrentfuturetaskrunfuturetaskjava242at androidosasynctaskserialexecutor1runasynctaskjava231at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava12at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava587at javalangthreadrunthreadjava811caused by javalangruntimeexception package manager has diedat androidappapplicationpackagemanagerqueryintentactivitiesasuserapplicationpackagemanagerjava499at androidappapplicationpackagemanagerqueryintentactivitiesapplicationpackagemanagerjava485at comnamepackagemyclassretrieveappsdoinbackgroundmyclassjava363at comnamepackagemyclassretrieveappsdoinbackgroundmyclassjava1at androidosasynctask2callasynctaskjava288at javautilconcurrentfuturetaskrunfuturetaskjava237 4 morecaused by androidostransactiontoolargeexceptionat androidosbinderproxytransactnative methodat androidcontentpmipackagemanagerstubproxyqueryintentactivitiesipackagemanagerjava2165at androidappapplicationpackagemanagerqueryintentactivitiesasuserapplicationpackagemanagerjava493 9 morein doinbackground method i use this code to retrieve the installed apps packagemanager packagemanager getpackagemanager listresolveinfo mresolveinfo intent queryintent new intentintentaction mainaddcategoryintentcategory launcher mresolveinfo packagemanagerqueryintentactivitiesqueryintent 0 for resolveinfo ri resolveinfos class class new class classicon riloadiconpackagemanager classlabel riloadlabelpackagemanager classpackagename riactivityinfopackagename classpackageclass riactivityinfoname classcomponentname new componentnameclasspackagename classpackageclass intent i new intentintentaction main iaddcategoryintentcategory launcher isetflagsintentflag activity new task intentflag activity reset task if needed isetcomponentaicomponentname classintent i myarraylistaddclassthe line where the crash occurs is this mresolveinfo packagemanagerqueryintentactivitiesqueryintent 0reading on stack overflow i understand that this may be caused by the fact that you have many applications installed the question now is how can you solve is there any solution if yes which one thanks,"['java', 'android']" +629989,angular websocket and rootscopeapply i am currently playing around with an angular app that uses a websocket to communicate with the backend i have had some trouble getting angulars data binding working correctlyin the example below i have created a service which creates the websocket connection if the websocket receives a message i just push that message into an array which contains all of the received messagesin my controller i bind that array of messages to the scope and then use ngrepeat to list them all in my partial view servicefactorymyservice function var wsurl angularelementdocumentqueryselectorwsurlval var ws new websocketwsurl wsonopen function consolelogconnection established wsonmessage functionevent servicemessagespusheventdata var service servicemessages return servicecontrollercontrollermyctrl1 scope myservice functionscope myservice scopemessages myservicemessagespartialul li ngrepeatmsg in messages msg liulthis however does not work correctly when a new message is received and pushed into the array the list that should thisplay all messages does not get updated i expected it to be updated because of angular two way data bindingi have found one solution that works by wrapping the pushing of the message into a call to rootscopeapply in the servicewsonmessage functionevent rootscopeapplyfunction servicemessagespusheventdata my questions areis this the expected behavior of angular that my list does not automatically get updated if i do not use rootscopeapply why do i even need to wrap it in rootscopeapplyis using rootscopeapply the correct way to solve thisare there better alternatives to rootscopeapply for this problem,['javascript'] +630038,double to unsigned int char i read here thataccording to c99 a6314 footnote 50the remaindering operation performed when a value of integer type is converted to unsigned type need not be performed when a value of real floating type is converted to unsigned type thus the range of portable real floating values is a1 utype max1now i am interested in the subtle difference this time for c 03 betweendouble d1 257double d2 2unsigned char c1 d1 undefined since d1 256unsigned char c2 d2 undefined since d2 1anddouble d1 257double d2 2unsigned int i1 d1 defined since d1 232unsigned int i2 d2 still undefined rightunsigned char c1 i1 defined modulo 28 so c1 1so the first c1 and the second c1 are not guaranteed to compare as equal right is the citation from above also valid for c03 or are there other ruleseditand for making c2 defined for 2311 d2 0 would this be necessary to dodouble d2 2int sign d20 1 1unsigned char c2 sign intabsd2 defined c2 282,['c++'] +630114,proxy pass cannot have uri part in location i have a location block as location test proxy pass httplocalhost501but it complains that proxy pass cannot have uri part in location given by regular expression does anyone know what might be wrongi am actually trying to query localhost501 when an upload is completelocation upload attachment upload pass test upload store tmp,['php'] +630151,python make a list generator json serializable how can i concat a list of json files into a huge json array i have 50 files and 550 0 list items my fist try was to use jq but it looks like jq s is not optimized for a large input jq s r js this command works but takes way too long to complete and i really would like to solve this with pythonhere is my current codedef concatfilesoutname infilenames def listgenerator for inname in infilenames with openinname r as f for item in jsonloadf yield item with openoutname w as f jsondumplistgenerator fi am gettingtypeerror generator object listgenerator at 0x7f94dc2eb3c0 is not json serializableany attempt load all files into ram will trigger the oomkiller of linux do you have any ideas,['python'] +630187,force browser to trigger reflow while changing css i am building nonjquery responsive image slider based on css3 transitionsthe structure is simple a viewport and inside relatively positioned ul with left floated lisi am facing a problem in such situationuser clicks prev arrowjs appends proper li before currently thisplayed li nodefor now ul has set css transition as none 0s linear to prevent animation changes in this moment i decrease ul css left value by slider width let us say from 0px to 1200px to make view the same as it wasnow i am changing uls transition property to all 02s easeoutnow i am changing uls left property to trigger css3 animation let us say from 1200px to 0pxwhat is the problem browser simplifies changes and does not make any animationsstoyan stefanov wrote about reflow problem at his blog here but in this case trying to force a reflow on element does not workthis is a piece of code doing this i skipped browser prefixes for simplificationulstyletransition none 0s linear 0sulstyleleft 600pxulstyletransition all 02s easeoutulstyleleft 0pxhere is fiddle to see problem in action thanks,"['javascript', 'html', 'css']" +630250,jquery 203 bug fadein show broken in firefox securityerror the operation is insecure i have a very basic html element that i would like to fadein i am however using requirejs so i believe this could be part of the problem i am using jquery 203 when using fadein i get this errorsecurityerror the operation is insecurechromefirebugcontentconsolecommandlineexposedjsline 5i have never seen this before i have reset firefox and my pchtml messagebox messageinfomessageinfo closeboxxclosebox messageboxjsmessageboxfadein i only get this error with firefox v27 no other browsers are having this problem but i have not tested it in any older versions of ffi am not seeking help for anything other than the errorsee the error in action and run this command sdmessageshowmessagesomehow this breaks everything badeditso sadly youll need to test this here i assure you this is sfw its just the sign in pagei am confident there must be something in my other js files that is conflicting but i as yet have not found the problem i removed a fiddle that was here as it in no way helped the question since adding the bounty i want it to be as helpful as possiblesecond editoddly when running any show hide fadein etc an iframe is created at the base of the page just before the body i will need to have a think in my code why this would be happeningthird edit i have no reason or explanation for this but updating to jquery 210 has fixed my issues if anybody can explain the problem then i would love to give them the points,"['javascript', 'jquery', 'html']" +630344,what is server and client terminology mean in sidekiq in sidekiq the documention says sidekiqconfigure server do config configrethis namespace figs railsenv size 25 url rethislocalhost63790endsidekiqconfigure client do config configrethis namespace figs railsenv size 25 url rethislocalhost63790endi am curious about what does this configure server and configure client mean here configrethis namespace figs railsenv size 25 url rethislocalhost63790is obviously the location of rethis queue type etc,['ruby-on-rails'] +630345,how to find global minimum in python optimization with bounds i have a python function with 64 variables and i tried to optimise it using lbfgsb method in the minimise function however this method have quite a strong dependence on the initial guess and failed to find the global minimum but i liked its ability to set bounds for the variables is there a wayfunction to find the global minimum while having boundaries for the variables,['python'] +630375,link atlasmkl to an installed numpy tldr how to link atlasmkl to existing numpy without rebuildingi have used numpy to calculate with the large matrix and i found that it is very slow because numpy only use 1 core to do calculation after doing a lot of search i figure that my numpy does not link to some optimized library like atlasmkl here is my config of numpyimport numpy as npnp config showblas info libraries blas library dirs usrlib language f77lapack info libraries lapack library dirs usrlib language f77atlas threads info not availableblas opt info libraries blas library dirs usrlib language f77 define macros no atlas info 1atlas blas threads info not availableopenblas info not availablelapack opt info libraries lapack blas library dirs usrlib language f77 define macros no atlas info 1atlas info not availablelapack mkl info not availableblas mkl info not availableatlas blas info not availablemkl info not availablefor this reason i want to link atlasmkl to numpy however my numpy is installed from pip so i do not want to install manually because i want to use the latest version i have done some search but they are only for building from scratch for this reason my question areare there any way to link atlasmkl to numpy without rebuilding againi have found that the config info is saved in config py in the installed folder of numpy so will modifying it solve my problem if yes would you please show me how,['python'] +630433,wp get image editor not saving image wp get image editor resize and save images fine on localhostmamp but on the server its simply not workingsaving no error here is my codefunction image cropurl name image wp get image editor url if is wp error image imageresize 100 140 true data imagesave name idpng if is wp error data return ok else return error this function returns ok but on destination directory is empty no images,['php'] +630470,how to use npm jquery module how should i requirethe jquery in node if i use it in multiple modules should i define it as a global or should i just use the requirejquery in every module i need iti am getting an error when trying to use the package typeerror object function w if wdocument throw new error jquery requires a window with a document return factory w has no method isarrayit looks like a bug in the current release as it should not check if i am running it in a browser according to the official documentation this issue is also mentioned in another post it works with version 183 as mentioned in one of the answers,"['javascript', 'jquery']" +630490,accidentally reflowed how to undo longline breaks has anyone got any tricks for undoing longline wrappingi have got a big chunk of code that has been reflowed to 120 columns and it is a minefield to debug effectivelyedit0 i did not do the reflow and the guy i am collaborating with does not get cvssedit1 example yes most of them are appropriately indented,['python'] +630498,customise grid view in yii2 how to remove summary and sorter for a particular grid view in yii2 in yii11 we can do that by setting the template property in yii2 how to achieve this,['php'] +630565,recording mouse click events for gui testing what is more reliable than pixel coordinates i have been writing some gui test frameworks that can record and replay some gui user scenario by recording mouse and keyboard events and replaying them the mouse events are currently recorded as press or release x y however this is very fragile because if only the destination widget moves by a few pixels but the structure and everything else stays the same the testcase ceases to work what is a better approach to do this some things that i can think aboutrecord the tree path of the destination widget in the tree of widgets and their parent widgets ie press or release top level first child second child destination where the child list is what is returned by qts qobject child list i think this has the drawback that the test now is dependent on the internal code structuregive every testable widget a unique name and when replaying search the widget with that name this seems to be a nonnegletible overhead any other ideas and what is the commonly accepted best approach to this,['c++'] +630608,group a list of objects by an attribute java i need to group a list of objectsstudent using an attributelocation of the particular object the code is like belowpublic class grouping param args the command line arguments public static void mainstring args liststudent studlist new arrayliststudent studlistaddnew student1726 john new york studlistaddnew student4321 max california studlistaddnew student2234 andrew los angeles studlistaddnew student5223 michael new york studlistaddnew student7765 sam california studlistaddnew student3442 mark new york code to group students by location output should be like below id 1726 name john location new york id 5223 name michael location new york id 4321 name max location california id 7765 name sam location california for student student studlist systemoutprintlnid studentstud idtname studentstud nametlocation studentstud location class student string stud id string stud name string stud location studentstring sid string sname string slocation thisstud id sid thisstud name sname thisstud location slocation please suggest me a clean way to do it,['java'] +630613,type the container android dependencies references non existing library androidsupportv7appcompatbinandroidsupportv7appcompatjar okay hello guys i just got some kind of error when trying to using action bar compat support library to my project i do not know whats wrong because i have followed the instructions from this link so this is the screen shot of the error please help thanks in adv,['android'] +630774,render view component with parameters into named outlet emberjs i have 2 named outlets in my application template sliderarea and prefooter is there a way to pass view components that take parameters as in the mainslider component shown in the index template to a named outlet so i would need to pass mainslider slidersfilteredslider to the outlet outlet sliderarea in the index template i have come from rails so forgive my thinking if this is not how ember does it one could specify yield slider area in the application template and then wrap any content for this area in a content for slider area block is a similar approach available in emberindexhtmlscript typetextxhandlebars datatemplatenameapplication panasonictopbar div idbatterywrap outlet sliderarea div classindex contents div classindex contents inner div classmain area outlet div div div div panasonicfooterscriptscript typetextxhandlebars datatemplatenameindex something like outlet sliderarea render mainslider slidersfilteredslider mainslider slidersfilteredslider partial social footerscriptappjsappindexcontroller emberobjectcontrollerextend filteredslider function return thisgetslidersfilterbypage index propertyappindexroute emberrouteextend model function return emberrsvphash sliders thisstorefindslider,"['javascript', 'jquery']" +630879,how does intellij know if a directory is a source or a test source how does intellij know if a directory is a source or a test source how can i consistently mark a directory as a test sourcebuildgradle 1apply plugin javaapply plugin ideaidea module sourcedirs filesrcmainjava testsourcedirs filesrcawesometestjava using buildgradle 1 file srcawesometestjava is marked as a test sourcebuildgradle 2apply plugin javaapply plugin ideaidea module sourcedirs filesrcmainjava testsourcedirs filesrcawesometestjava sourcesets awesometest java srcdir srcawesometestjava compileclasspath sourcesetsmainruntimeclasspath however as soon as you add a source set that references this directory buildgradle 2 then srcawesometestjava is marked as a sourcebuildgradle 3apply plugin javaapply plugin ideaidea module sourcedirs filesrcmainjava testsourcedirs filesrcawesometestjava sourcesets awesometest java srcdir srcawesometestjava compileclasspath sourcesetsmainruntimeclasspath task awesometesttype test testclassesdir sourcesetsawesometestoutputclassesdir classpath sourcesetsawesometestruntimeclasspathand just to confuse things beyond any hope of understanding if i add a test type task then srcawesometestjava is once again marked as test sourcenotes intellij 1302 gradle 19,['java'] +630933,how to detect if dom element is partially out of the viewport i am wondering if anyone has an easy solution for this i am trying to detect if any part of a html element finds itself outside of the viewport i have tried utilizing the following codefnisonscreen function var win window var viewport top winscrolltop left winscroleft viewportright viewportleft winwidth viewportbottom viewporttop winheight var bounds thisoffset boundsright boundsleft thisouterwidth boundsbottom boundstop thisouterheightbrought to you by steveni can only get this to work when the entire element is not viewable anymore but i just need to know if part of the element is outside of the viewportwhen the element is outside of the viewport then i am putting a different class on it so that it will shift to the left instead so that it is viewable againsomething likeifelementispartiallyoutsideviewport eleaddclassmoveleftany ideas,"['javascript', 'jquery', 'html', 'css']" +630982,javascript float comparison i am having a big problem with number comparison in javascriptthe script accuses that the comparison 7 10 is falseconsoleclearvar min parsefloat5tofixed2var max parsefloat10tofixed2var value parsefloat7tofixed2consolelogmin max valueconsolelogvalue min okconsolelogvalue max false anyone knows what is happing,['javascript'] +630987,flaskadmin custom select2 ajax field i am trying to extend a onetomany field in my flaskadmin app to use a custom select2 field the javascript code for the field looks something like thisfunction formatdata if dataid return datatext optgroup return img classflag src datatext dataid function formatselectiondata return dataidda2select2 maximumselectionsize 3 formatresult format formatselection formatselection escapemarkup functionm return m i am unsure of what i need to change in my view code i have tried something like this class postformwtfform title fieldstextfieldtitle photos fieldsselectfieldphoto widgetwidgetsselectmultipletrue idda2class postviewmodelview form postformdef feed user choicesself mform photos photoqueryall mformphotoschoices xpath url forstatic filenameformthumbgen filenamexpath for x in photos return mformdef create formself form superpost2view selfcreate form return self feed user choicesformbut its not ajax and there is an error when trying to parse the listi feel i am close but need some guidance to get there thanks for the help,"['javascript', 'python']" +631075,uiscrollview with sticky footer uiview and dynamic height content challenge timeimagine we have 2 content viewsuiview with dynamically height content expandable uitextview reduiview as a footer bluethis content is inside a uiscrollview geenhow should i structure and handle the constraints with autolayout to archive all the following casesi am thinking next basic structure to start with uiscrollview with always bounce vertically uiview container uiview dynamicheightcontent uiview sticky footerkeyboard handling should be done by code watching notifications uikeyboardwillshownotification and uikeyboardwillhidenotification we can chose to set the keyboards end frame height to container uiview bottom pin constraint or to the uiscrollview bottom contentinset now the tricky part is the sticky footerhow we make sure the sticky footer uiview stays at the bottom if there is more screen available than the whole container view how do we know the available screen space when the keyboard is shownhidden well surely need itis is it right this structure i purpose thank you,['ios'] +631095,how to enforce the custom permission on an activity in android i have created a custom permission in android aspermission androidnamecommastermecustom permission test androiddescriptionstringdes permission androidlabellabelherepermissionhow will i enforce this in my activity in androidmanifestxml file,"['java', 'android']" +631172,tsa or tsacert timestamp for applet jar selfsigned when i was trying to selfsign in the jar like belowjarsigner keystore my keystore myjarjar myaliasit gives warning likeno tsa or tsacert is provided and this jar is not timestamped without a timestamp users may not be able to validate this jar after the signer certificates expiration date 20140508 or after any future revocation dateplease help to resolve the problem,['java'] +631239,stdthreadthread no overloaded function takes 7 arguments i am using visual studio 2012 and the above error popups my code is correct but seems like the compiler is limited to 7 arguments what can i do if i want to pass 7 argumentsi can pass a struct but better not change my code if possible,['c++'] +631263,adding single selection and context sensitive right clicking to zest graph i have been playing with the zest graphviewer for over a week now trying to thiscover what it can do for my application but i have not been able to get it is behaviour inline with my requirements thus fari am hoping that someone can point me to the resources i need becasue i just cannot find all that much of use with google or can tell me if what i want is possibleversioni have got zest core 130 and zest layout 110 in my dependencies for the rcp project this came from the download site i took from the zest siterequirements single nodeedge selectiondeselection of nodeedge when whitespace is selected which may be a bugright click functionality to change when over a node detect when mouse is over a nodethe right click functionality could come from the single selection since i could have the popup anywhere but base it on the current selected node but i would rather not do thatwithout being able to do this due to the nature or our application and users i may also have a requirement to find another rcpswt based graph drawing package that does have this functionality any help on any of these issues would be greatly appreciatedglen x,['java'] +631306,how can i drop multiple primary keys in phpmyadmin tables i am working with phpmyadmini created a table with one primary key and 5 fields but now all the integer fields have turned into a primary key i tried using drop command but it does not help how can i remove all primary keys from the table,"['mysql', 'sql']" +631371,simulating the knight sequence tour i am currently trying to write a simple multithreading program using python however i have run on to a bug i think i am missing i am trying to simply write a program that uses a brute force approach the problem belowas can be seen from the image there is a chess board where the knight travels all respective squaresmy approach is simply try each possible way where each possible way is a new thread if in the end of the thread there is no possible moves count how many squares has been visited if it is equal to 63 write solution on a simple text filethe code is as belowfrom thread import start new threadimport sysi1coor x raw inputplease enter x07 coor y raw inputplease enter y07 coordinate intcoor x intcoor ydef checkercoordinates previous moves possible moves coordinates01 coordinates12 coordinates01 coordinates12 coordinates01 coordinates12 coordinates01 coordinates12 coordinates02 coordinates11 coordinates02 coordinates11 coordinates02 coordinates11 coordinates02 coordinates11 to be removed for index in possible moves index x index y index if index x 0 or index x 7 or index y 0 or index y 7 to be removedappendindex for index in previous moves if index in possible moves to be removedappendindex if not to be removed for index in to be removed possible movesremoveindex if lenpossible moves 0 if not end checkerprevious moves print this solution is not correct else return possible movesdef end checkerprevious moves if lenprevious moves 63 writer openknightstourtxt w writerwriteprevious moves writerclose return true else return falsedef runnerprevious moves coordinates i if not end checkerprevious moves process que checkercoordinates previous moves for processing in process que previous movesappendprocessing i i1 print thread numberstri start new threadrunner previous moves processing i else sysexitprevious move previous moveappendcoordinaterunnerprevious move coordinate ic raw inputtype something to exit i am open to all suggestions my sample output is as belowplease enter x07 4please enter y07 0thread number2thread number3thread number4thread number5thread number4thread number5thread number6thread number3thread number6thread number5thread number6thread number7thread number6thread number8thread number7thread number8thread number7 thread number8thread number4thread number5thread number6thread number9thread number7thread number9thread number10thread number11thread number7thread number8thread number9thread number10thread number11thread number12thread number5thread number5 thread number6thread number7thread number8thread number9thread number6thread number7thread number8thread number9if seems for some reason the number of threads are stuck at 12any help would be most welcomedthank you,['python'] +631451,what are the differences between joomla model types i am trying to get to grips with the power behind joomla 3xs frameworki have noticed that there are multiple types of model that can be used in a componentjmodeladminprototype admin model acts as a factory class for application specific objects and provides many supporting api functionsjmodellegacybase class for a joomla modelacts as a factory class for application specific objects and provides many supporting api functionsjmodellistmodel class for handling lists of itemsacts as a factory class for application specific objects and provides many supporting api functionsjmodelformprototype form modelacts as a factory class for application specific objects and provides many supporting api functionsjmodelitemprototype item modeli understand that jmodellegacy seems to be the foundation class my models have been extending jmodellegacy by default however i was wondering if i could be potentially using the benefits from the other classes if there was someone who knows about these models i would appreciate having an explanation about what the differences are between these model classes and an intended scenario where you would use one over others,['php'] +631462,resolving object in state of uirouter with uisref having really big json object in angular controller and uisref link i want to pass this object to controller of template that would be in uiviewi know that i can pass parameters to state with uisref but i do not want this object to appear in address bar also i know that we can use resolve option in state but i cannot find how to pass data to resolve function from linkupdateif i use statego like thatrouter configurationstatesocialfeeddetailed url activityid templateurl viewssocialdetailedactivityhtmlin templateumssocialactivity ngrepeatrecord in soc feed ctrlrecords activityrecord uisrefactiveselected ngclicksoc feed ctrlgotodetailedrecordumssocialactivityin controllerscopesoc feed ctrlgotodetailed activity here activity is real object stategosocialfeeddetailed activityidactivityid activityactivitythen activity param does not resolves at allupdate 2if i modify route configuration to thisstatesocialfeeddetailed url activityidactivity templateurl viewssocialdetailedactivityhtmlthen activity is string object object,['javascript'] +631464,how to prevent warning post contentlength and memory size currently when user uploads a photo the page says warning post contentlength of x bytes exceeds the limit of 210 bytes in unknown on line 0i know what that means and i am not looking for the solultions like the increasing the max upload values or even memory size limit because users may and users will upload terabytes of nonsense even if you explicitly tell them only max 20mb files and only images are allowedi am looking for a solution onhow to prevent this warnings to even happenor at leasthow to prevent thisplaying of this warningsedit please read please understand that of course i am handling the errorwarning after since line 1 problem is this happens on a virtual line 0 that is why i need to hide the error or prevent it to raise because i cant put any code before the place where the error happens edit2 finally after a very long research and digging i got an idea it worked see my own answer,['php'] +631551,returning nsmutablearray object from a method with an nsarray return value when returning an nsarray or nsdictionary etc from a method that builds the array on the fly using an nsmutablearray what is the standard way to do this and avoid random memory leaks when using arcfor example let us say we had some class with a list of names and we wanted to manually filter and grab all of the names that started with a given letter nsarray getnamesbyfirstletternsstring firstletter nsmutablearray returnvalue nsmutablearray alloc init forid item in selfnames ifitem hasprefixfirstletter returnvalue addobjectitem return returnvalue just return the above arraywhen it comes to returning the value i can think of four possible ways to do itreturn the nsmutablearray directly as abovereturn returnvaluereturn a copyreturn returnvalue copyreturn using nsarray arraywitharrayreturn nsarray arraywitharrayreturnvaluecreate an nsarray manually set the nsmutablearray to nilnsarray temp nsarray arraywitharrayreturnvalue could use returnvalue copy here tooreturnvalue nilreturn tempwhen a program is using arc is there any real difference between these four methods or does it just come down to personal preference also besides possible memory leaks are there any other implications when using one method over anothernote if this is a duplicate let me know and i will take the question down i tried searching but had a hard time trying to condense the issue down to a few search terms,['objective-c'] +631569,why does entity framework 6x not cache results perhaps i am misunderstanding the caching that dbcontext and dbset does but i was under the impression that there was some caching that would go on i am seeing behavior that i wouldnt expect when i run the following codevar ctx createacontextvar sampleentityid ctxsampleentitiesselecti iid singlei i 3 calls db as expectedvar cachedentityid ctxsampleentitiesselecti iid singlei i 3 calls db unexpectedlywhats going on here i thought that part of what you get from dbset is that it would first check the local cache to see if that object exists before querying the database is there just some sort of configuration option i am missing here,['c#'] +631631,when to not use atomic operations i can think of reasons when it does not matter and 1 situation where you may not want to use them which is when you want to test a design for behaviour with nonatomic operations what are some other reasons specifically i am working on a project that is having some rare race conditions because a test is not using atomic increments i am wondering why would i not just always use atomic increments when a function for it already exists thanks,"['c++', 'c']" +631632,no accesscontrolalloworigin header is present on the requested resource i am using omniauthfacebook with angularjs and cors is not working correctly my omniauthrb is railsapplicationconfigmiddlewareuse omniauthbuilder doprovider facebookx xscope emailuser birthdayread stream thisplay popupendeverything works if i use it as rails app and request but when i try to call httplocalhost30usersauthfacebook via angular js httpgetusersauthfacebooksuccessfunctiondata status headers config consolelogback in success errorfunctiondata status headers config i see following error in js consolexmlhttprequest cannot load idxthisplaypopupathday2cread streamstate3352c1924bdbc9277f7b1070c38d67acf79b529f198323cb no accesscontrolalloworigin header is present on the requested resource origin httplocalhost30 is therefore not allowed accessthe url is not thisplayed completely in consolei added following line configmiddlewareinsert before wardenmanager rackcorsbut also this did not work what is the best way or how can i override headers for omniauth i am using angularjs and gem devise omniauthfacebook,['ruby-on-rails'] +631745,find div element by multiple class names div classvalue test i would like to identify that web element it only has this two classes definedi cannot do the following as classname does not take a space separated value what are alternativesfindbyclassname value testcachelookupprivate webelement test,"['java', 'css']" +631774,what is the big o order of stdqueuesize the stdqueue class is unclear as to the complexity of the size member function it appears to be based on the data structure implementation used at the timeone would assume that size would be oc but it is totally possible for it to be on obviously i can keep my own size but i would rather just call sizequestion modified since deque is the default container what is o of stddequesize,['c++'] +631784,how is spring actually bootstrap does anybody know how spring is actually bootstraps which instances created and by whom i really want to know who creates instances of webapplicationcontext and contextloader is it work of tomcat,['java'] +631967,sending email from android app when click on button i need to provide feature for users where users can share some data by sending email i used below code intent email new intentandroidcontentintentaction sendto emailsettypemessagerfc822 emailputextraintentextra email new string to emailputextraintentextra subject subject emailputextraintentextra text message startactivityintentcreatechooseremailchoose an email client this shows email gmail skype and send via bluetooth for user to choose i dont want user to show skypesend via bluetooth in this list what i need to do i have whatsapp in my phone which does same thing but does not show email bluetooth in the listsettingshelpcontactusonly show email and gmail in list i need to do the same,['android'] +632081,how to hide navigation bar permanently in android activity i want to hide navigation bar permanently in my activitynot whole system uinow i am using this piece of code getwindowgetdecorviewsetsystemuivisibilityviewsystem ui flag hide navigationit hides the bar but when user touches the screen it showing again is there is any way to hide it permanently until activity onstop,['android'] +632108,how to bundle mahappsmetro into single exe i am having a really hard time bundling all of my dependencies in my c wpf project into a single exe using smartassembly 6 evaluationtrial because of mahappsmetro this conclusion was drawn when creating a completely empty project with nothing but mahappsmetro and still not being able to bundle itit throws an exception with an inner exception systemiofilenotfoundexception could not load file or assembly systemwindowsinteractivity version4500 cultureneutral publickeytoken31bf3856ad364e35 or one of its dependencies the system cannot find the file specified i have spent a day and a half trying to resolve this googling the error trying every suggestion i can find and posting in the official mahappsmetro chat i have tried all kinds of variation where i removed systemwindowsinteractivity dll added it moved it to another path etcusing the latest mahappsmetro package from nuget and net 45 the program works when i run it from visual studio 2012 or when i run the application from debugreleasehas anyone ever encountered this problem before how did you resolve it is the problem the bundle application smartassembly 6 or mahappsmetro are there any other bundle programs that you know or think will work with mahappsmetro,['c#'] +632127,reading large file in chunks c i want to read very large file 4gbish chunk by chunki am currently trying to use a streamreader and the read read method the syntax issrreadchar buffer int index int countbecause the index is an int it will overflow in my case what should i use instead,['c#'] +632146,delay in consumer consuming messages in apache kafka i am using kafka 080 and trying to achieve the below mentioned scenariojca api acts as a producer and sends data to consumer hbasei am sending each message to consumer as soon as i fetch the data using jca client for instance as soon as producer sends message no1 i want to fetch the same from consumer and put in hbase but my consumer starts fetching the messages after some random and messages i want to put the producer and consumer in sync so that both of them start working togetheri have used1 broker1 single topic1 single producer and high level consumercan anyone suggest what do i need to do to achieve the sameeditedadding some relevant code snippetconsumerjavapublic class consumer extends thread private final consumerconnector consumer private final string topic printwriter pw null int t 0 stringdecoder kd new stringdecodernull mapstring integer topiccountmap new hashmapstring integer mapstring listkafkastreamstring signal consumermap kafkastreamstring signal stream consumeriteratorstring signal it public consumerstring topic consumer kafkaconsumerconsumercreatejavaconsumerconnectorcreateconsumerconfig thistopic topic topiccountmapputtopic new integer1 consumermap consumercreatemessagestreamstopiccountmap kd new serializer new verifiableproperties stream consumermapgettopicget0 it streamiterator private static consumerconfig createconsumerconfig properties props new properties propsputzookeeperconnect kafkapropertieszkconnect propsputgroupid kafkapropertiesgroupid propsputzookeepersessiontimeoutms 400 propsputzookeepersynctimems 200 propsputautocommitintervalms 10 propsputfetchsize 1024 return new consumerconfigprops synchronized public void run while ithasnext t itnextmessagegetchannelid systemoutprintlnin consumer received msg t producerjavapublic class producer public final kafkajavaapiproducerproducerstring signal producer private final string topic private final properties props new properties public producerstring topic propsputserializerclass orgbigdatakafkaserializer propsputkeyserializerclass kafkaserializerstringencoder propsputmetadatabrokerlist localhost9092 use random partitioner do not need the key type just set it to integer the message is of type userdefined object producer new kafkajavaapiproducerproducerstringsignalnewproducerconfigprops thistopic topic kafkapropertiesjavapublic interface kafkaproperties final static string zkconnect 1270012181 final static string groupid group1 final static string topic test00 final static string kafkaserverurl localhost final static int kafkaserverport 9092 final static int kafkaproducerbuffersize 64 1024 final static int connectiontimeout 10 final static int reconnectinterval 10 final static string clientid simpleconsumerdemoclientthis is how the consumer is behaving for the first 10 messages it does not sysout that message received by consumer but from the 11th message onwards it starts functioning correctly producer sending msg1 producer sending msg2 producer sending msg3 producer sending msg4 producer sending msg5 producer sending msg6 producer sending msg7 producer sending msg8 producer sending msg9 producer sending msg10 producer sending msg11 producer sending msg12 in consumer received msg12 producer sending msg13 in consumer received msg13 producer sending msg14 in consumer received msg14 producer sending msg15 in consumer received msg15 producer sending msg16 in consumer received msg16 producer sending msg17 in consumer received msg17 producer sending msg18 in consumer received msg18 producer sending msg19 in consumer received msg19 producer sending msg20 in consumer received msg20 producer sending msg21 in consumer received msg21edited adding the listener function where producer is sending messages to consumer and i am using the default producer config did not overwrite itpublic synchronized void onvaluechangedfinal monitorevent event get the value from the dbr try final dbr dbr event getdbr final string val string dbrgetvalue producer1producersendnew keyedmessagestring signal kafkapropertiestopicnew signalmessageno systemoutprintlnproducer sending msgmessageno messageno catch exception ex exprintstacktrace,['java'] +632255,the app is incompatible with all your devices i have already read all the related questions before posting this onei have developed a game with unity3d and uploaded to google play yesterday it was available for all devices there were reviews from other users today i have got couple reports about unavailability of the app on google play it is available on web version of gp but is incompatible for any device and not available at all in mobile version on gpin developer console all the devices are compatibleand on the web version they are not all previous versions were deleted from devicesmy manifest filemanifest xmlnsandroid packageprolabsterxyz androidversionname10 androidversioncode1 androidinstalocationpreferexternal supportsscreens androidsmallscreenstrue androidnormalscreenstrue androidlargescreenstrue androidxlargescreenstrue androidanydensitytrue application androidicondrawableapp icon androidlabelstringapp name androiddebuggablefalse usespermission androidnameandroidpermissioninternet usespermission androidnameandroidpermissionaccess network state usessdk androidminsdkversion10 androidtargetsdkversion19 usesfeature androidglesversion0x020 usesfeature androidnameandroidhardwaretouchscreen usesfeature androidnameandroidhardwaretouchscreenmultitouch androidrequiredfalse usesfeature androidnameandroidhardwaretouchscreenmultitouchthistinct androidrequiredfalse so the question is why it was available yesterday and is not available today i have not uploaded new version did not change anythingthe app is completely free its size is about 85 mb,['android'] +632258,environment detection in laravel 41 laravel 41 removed the feature to use the domain for detecting what environment the app is running in reading the docs they now suggest using host names however to me that seems cumbersome if you are working in a team should everyone change the bootstrapstartphp file and add their own host name to be able to run the app in a dev environment also what if you want to have two different environments on the same machinehow to best detect the environment if you are working in a team in laravel 41,['php'] +632268,why sortedlist does not use pointers for the values so i was looking through the implementation of sortedlisttkey tvalue and the implementation of add which calls insert shown below really surprised methe add method does the obvious binary search to determine the index in which the kvp should go but the insert seems as if it could be improved significantly albeit on larger scales of courseprivate void insertint index tkey key tvalue value if this size thiskeyslength thisensurecapacitythis size 1 if index this size arraycopyarray thiskeys index array thiskeys index 1 this size index arraycopyarray thisvalues index array thisvalues index 1 this size index thiskeysindex key thisvaluesindex value this size thisversionif i am reading this correctly and i reserve the right to be wrong at all times this is an o2n operationit seems to me that the values should be implemented with pointers kind of like a linkedlist in relation to the value from the key but not linked in that it does not support random access more so the key is simply linked to its value the get operation wouldnt be any slower and neither would the remove because we have the pointer but the add operation would be on now insteadcan somebody shed some light on why the decision may have gone this direction,"['c#', '.net']" +632293,mongoengine document object made using from json does not save i am trying to build a document object using from json method objectsave throws no error but the document is not inserted in mongoon the other hand if i make the object by assigning values to each of the fields it works finei am unable to find the reason for this below is the code for both the casesfrom flask import flaskfrom flaskextmongoengine import mongoengineimport json datetimeapp flask name appconfigmongodb settings db testhost localhostappconfigsecret key mysecretkeydb mongoengineappclass userdbdocument user id dbstringfieldmax length16 primary key true username dbstringfieldmin length8 email dbemailfieldrequired true unique true password dbstringfieldrequired true date of birth dbdatetimefield gender dbstringfieldchoices m f this one works this will add a user in local mongodbtestu1 useru1username test12345u1user id testid12345u1email u1password testerpassu1save this one does not worksu2 usertemp json usernametest2 12345user idtestid212345passwordtesterpass2emailu2 u2from jsonjsondumpstemp jsonu2save,['python'] +632417,php converting dollars to cents as input i want to accept any of the following 1233 1492 13 17 1401 as output i want 1233 1492 1300 1700 and 1400 respectively this is apparently not as easy as it looksphpinput 6499 value is given via form submissiondollars str replace input get rid of the dollar signcents intdollars 100 multiply by 100 and truncateecho centsthis outputs 6498 instead of 6499i assume this has to do with inaccuracies in floating point values and avoiding these is the whole reason i am converting to integer cents in the first place i suppose i could use logic like get rid of the sign check if there is a decimal point if so check how many characters there are after it padding to two and truncating after that then remove the period if there was not one append two zeros and hope for the best but using string operations for this seems ridiculoussurely taking a monetary value from a form and storing it as cents in a database is a common use case surely there is a reasonable way of doing thisright right,['php'] +632442,bootstrap alignment of label and regular text i have been trying to get the text to properly align vertically with no luck could i get some assistancehere is the underlying code div classformgroup label classcontrollabel colmd2permalinklabel div classcolmd10 div div div classformgroup htmllabelformodel modelofferdatecreated new class controllabel colmd2 div classcolmd10 htmlthisplayformodel modelofferdatecreated htmlvalidationmessageformodel modelofferdatecreated div div,"['html', 'css']" +632446,how to programmatically populate reminders section on android devices calendar app i need to open android devices calendar app with some prepopulated data the logic that iam using seems to populate fields likeevent description event location from date to date all day eventnot repeat recurrence info i am not able to populate reminders section i would like to populate reminders section it will great to get some help on thishere is the code that i am using to open calendar app and populate date intent to open calendar eventintent intent new intentintentaction insert setdataeventscontent uriintentputextraeventsdescription descintentputextraeventsevent location locationintentputextraeventstitle summaryintentputextraeventsevent timezone begintimegettimezonegetidintentputextraeventsstatus statusstrintentputextraeventsvisible transparencyintentputextraeventsrrule freqyearlyinterval1byyearday12until20161210intentputextraeventsexdate androidexdatestrtostring not sure on how to use calendarcontractreminders tried the following but does not seem to be workingintentputextracalendarcontractremindersdescription descintentputextracalendarcontractremindersevent location locationintentputextracalendarcontractreminderstitle summaryintentputextracalendarcontractextra event begin time begintimegettimeinmillisintentputextracalendarcontractremindersdtstart begintimegettimeinmillisintentputextracalendarcontractremindersevent timezone begintimegettimezonegetidintentputextracalendarcontractextra event end time endtimegettimeinmillisintentputextracalendarcontractremindersdtend endtimegettimeinmillisintentputextracalendarcontractremindersstatus statusstrintentputextracalendarcontractremindersrrulefreqyearlyinterval1byyearday12until20161210intentputextracalendarcontractremindersexdate androidexdatestrtostringintentputextracalendarcontractremindersmethod remindersmethod emailintentputextracalendarcontractremindersminutes reminderval intentputextracalendarcontracteventshas alarm 1 try contextstartactivityintent catchexception e eprintstacktrace logvlog tag cannot schedule calendar event as specified return false,['android'] +632456,using requests module how to handle setcookie in request response i am attempting to open a login page get fetch the cookies provided by the webserver then submit a username and password pair to log into the site post looking at this stackoverflow questionanswer i would think that i would just do the followingimport requestsimport cookieliburl1 login prompt pageurl2 login submission urljar cookielibcookiejarr requestsgeturl1 cookiesjarr2 requestsposturl2 cookiesjar datausername and password data payloadhowever in r there is a setcookie in the header but that is not changing in the jar object in fact nothing is being populated into jar as the linked questions response would indicatei am getting around this in my code by having a headers dict and after doing the get or post using this to handle the setcookie headerheaderscookie rheaderssetcookiethen passing around the header in the requests methods is this correct or is there a better way to apply the setcookie,['python'] +632514,strange jit pessimization of a loop idiom while analyzing the results of a recent question here i encountered a quite peculiar phenomenon apparently an extra layer of hotspots jitoptimization actually slows down execution on my machinehere is the code i have used for the measurementoutputtimeunittimeunitnanosecondsbenchmarkmodemodeaveragetimeoperationsperinvocationmeasurearray sizewarmupiterations 2 time 1measurementiterations 5 time 1statescopethreadthreads1fork2public class measure public static final int array size 1024 private final int array new intarray size setup public void setup final random random new random for int i 0 i array size i final int x randomnextint arrayi x 0 1 x generatemicrobenchmark public int normalindex final int array thisarray int result 0 for int i 0 i arraylength i final int j i arraylength1 final int entry arrayi result entry j return result generatemicrobenchmark public int maskedindex final int array thisarray int result 0 for int i 0 i arraylength i final int j i arraylength1 final int entry arrayj result entry i return result generatemicrobenchmark public int normalwithexitpoint final int array thisarray int result 0 for int i 0 i arraylength i final int j i arraylength1 final int entry arrayi result entry j if entry 0 break return result generatemicrobenchmark public int maskedwithexitpoint final int array thisarray int result 0 for int i 0 i arraylength i final int j i arraylength1 final int entry arrayj result entry i if entry 0 break return result the code is quite subtle so let me point out the important bitsthe normal index variants use the straight variable i for array index hotspot can easily determine the range of i throughout the loop and eliminate the array bounds checkthe masked index variants index by j which is actually equal to i but that fact is hidden from hotspot through the andmasking operationthe with exit point variants introduce an explict loop exit point the importance of this will be explained belowloop unrolling and reorderingobserve that the bounds check figures in two important waysit has runtime overhead associated with it a comparison followed by a conditional branchit constitutes a loop exit point which can interrupt the loop on any step this turns out to have important consequences for the applicable jit optimizationsby inspecting the machine code emitted for the above four methods i have noticed the followingin all cases the loop is unrolledin the case of normalindex which is thistinguished as the only one having no premature loop exit points the operations of all the unrolled steps are reordered such that first all the array fetches are performed followed by xoring all the values into the accumulatorexpected and actual measurement resultsnow we can classify the four methods according to the thiscussed featuresnormalindex has no bounds checks and no loop exit pointsnormalwithexitpoint has no bounds checks and 1 exit pointmaskedindex has 1 bounds check and 1 exit pointmaskedwithexitpoint has 1 bounds check and 2 exit pointsthe obvious expectation is that the above list should present the methods in descending order of performance however these are my actual resultsbenchmark mode samples mean mean error unitsnormalindex avgt 20 0946 0010 nsopnormalwithexitpoint avgt 20 0807 0010 nsopmaskedindex avgt 20 0803 07 nsopmaskedwithexitpoint avgt 20 1007 09 nsopnormalwithexitpoint and maskedindex are identical modulo measurement error even though only the latter has the bounds checkthe greatest anomaly is observed on normalindex which should have been the fastest but is significantly slower than normalwithexitpoint identical to it in every respect save for having one more line of code the one which introduces the exit pointsince normalindex is the only method which has the extra reordering optimization applied to it the conclusion is that this is the cause of the slowdown i am testing onjava hotspottm 64bit server vm build 240b56 mixed mode java 7 update 40os x version 1091266 ghz intel core i7i have successfully reproduced the results on java 8 ea b118 as wellmy questionis the above phenomenon reproducible on other similar machines from the question mentioned at the beginning i already have a hint that at least some machines do not reproduce it so another result from the same cpu would be very interestingupdate 1 more measurements inspired by martinuss findingsi have gathered the following table which correlates execution times with the xxloopunrolimit commandline argument here i focus only on two variants with and without the if entry 0 break lineloopunrolimit 14 15 18 19 22 23 60withexitpoint 96 95 95 79 80 80 69 1100 nswithoutexitpoint 94 64 64 63 64 77 75 1100 nsthe following sudden changes can be observedon the transition from 14 to 15 the withoutexitpoint variant receives a beneficial lcm1 transformation and is significantly sped up due to the loopunrolling limit all loaded values fit into registerson 1819 the withexitpoint variant receives a speedup lesser than the aboveon 23 the withoutexitpoint variant is slowed down at this point i see the spillover into stack locations as described in martinuss answer starting to happenthe default loopunrolimit for my setup is 60 so i present its results in the last column 1 lcm local code motion it is the transformation which causes all array access to happen on the top followed by the processing of the loaded valuesupdate 2 this is actually a known reported problemappendix the unrolled and reordered loop of normalindex in machine code0x01044a37c0 mov ecxeax0x01044a37c2 and ecxesi iand orgsamplemeasurenormalindex20 line 440x01044a37c4 mov rbpqword ptr rsp0x28 iload 3 orgsamplemeasurenormalindex15 line 440x01044a37c9 add ecxdword ptr rbprsi40x100x01044a37cd xor ecxr8d0x01044a37d0 mov dword ptr rspecx0x01044a37d3 mov r10desi0x01044a37d6 add r10d0xf0x01044a37da and r10deax0x01044a37dd mov r8desi0x01044a37e0 add r8d0x70x01044a37e4 and r8deax0x01044a37e7 mov dword ptr rsp0x4r8d0x01044a37ec mov r11desi0x01044a37ef add r11d0x60x01044a37f3 and r11deax0x01044a37f6 mov dword ptr rsp0x8r11d0x01044a37fb mov r8desi0x01044a37fe add r8d0x50x01044a3802 and r8deax0x01044a3805 mov dword ptr rsp0xcr8d0x01044a380a mov r11desi0x01044a380d inc r11d0x01044a3810 and r11deax0x01044a3813 mov dword ptr rsp0x10r11d0x01044a3818 mov r8desi0x01044a381b add r8d0x20x01044a381f and r8deax0x01044a3822 mov dword ptr rsp0x14r8d0x01044a3827 mov r11desi0x01044a382a add r11d0x30x01044a382e and r11deax0x01044a3831 mov r9desi0x01044a3834 add r9d0x40x01044a3838 and r9deax0x01044a383b mov r8desi0x01044a383e add r8d0x80x01044a3842 and r8deax0x01044a3845 mov dword ptr rsp0x18r8d0x01044a384a mov r8desi0x01044a384d add r8d0x90x01044a3851 and r8deax0x01044a3854 mov ebxesi0x01044a3856 add ebx0xa0x01044a3859 and ebxeax0x01044a385b mov ecxesi0x01044a385d add ecx0xb0x01044a3860 and ecxeax0x01044a3862 mov edxesi0x01044a3864 add edx0xc0x01044a3867 and edxeax0x01044a3869 mov ediesi0x01044a386b add edi0xd0x01044a386e and edieax0x01044a3870 mov r13desi0x01044a3873 add r13d0xe0x01044a3877 and r13deax0x01044a387a movsxd r14esi0x01044a387d add r10ddword ptr rbpr1440x4c0x01044a3882 mov dword ptr rsp0x24r10d0x01044a3887 mov qword ptr rsp0x28rbp0x01044a388c mov ebpdword ptr rsp0x40x01044a3890 mov r10qword ptr rsp0x280x01044a3895 add ebpdword ptr r10r1440x2c0x01044a389a mov dword ptr rsp0x4ebp0x01044a389e mov r10ddword ptr rsp0x80x01044a38a3 mov rbpqword ptr rsp0x280x01044a38a8 add r10ddword ptr rbpr1440x280x01044a38ad mov dword ptr rsp0x8r10d0x01044a38b2 mov r10ddword ptr rsp0xc0x01044a38b7 add r10ddword ptr rbpr1440x240x01044a38bc mov dword ptr rsp0xcr10d0x01044a38c1 mov r10ddword ptr rsp0x100x01044a38c6 add r10ddword ptr rbpr1440x140x01044a38cb mov dword ptr rsp0x10r10d0x01044a38d0 mov r10ddword ptr rsp0x140x01044a38d5 add r10ddword ptr rbpr1440x180x01044a38da mov dword ptr rsp0x14r10d0x01044a38df add r13ddword ptr rbpr1440x480x01044a38e4 add r11ddword ptr rbpr1440x1c0x01044a38e9 add r9ddword ptr rbpr1440x200x01044a38ee mov r10ddword ptr rsp0x180x01044a38f3 add r10ddword ptr rbpr1440x300x01044a38f8 mov dword ptr rsp0x18r10d0x01044a38fd add r8ddword ptr rbpr1440x340x01044a3902 add ebxdword ptr rbpr1440x380x01044a3907 add ecxdword ptr rbpr1440x3c0x01044a390c add edxdword ptr rbpr1440x400x01044a3911 add edidword ptr rbpr1440x440x01044a3916 mov r10ddword ptr rsp0x100x01044a391b xor r10ddword ptr rsp0x01044a391f mov ebpdword ptr rsp0x140x01044a3923 xor ebpr10d0x01044a3926 xor r11debp0x01044a3929 xor r9dr11d0x01044a392c xor r9ddword ptr rsp0xc0x01044a3931 xor r9ddword ptr rsp0x80x01044a3936 xor r9ddword ptr rsp0x40x01044a393b mov r10ddword ptr rsp0x180x01044a3940 xor r10dr9d0x01044a3943 xor r8dr10d0x01044a3946 xor ebxr8d0x01044a3949 xor ecxebx0x01044a394b xor edxecx0x01044a394d xor ediedx0x01044a394f xor r13dedi0x01044a3952 mov r8ddword ptr rsp0x240x01044a3957 xor r8dr13d ixor orgsamplemeasurenormalindex34 line 460x01044a395a add esi0x10 iinc orgsamplemeasurenormalindex36 line 430x01044a395d cmp esidword ptr rsp0x200x01044a3961 jl 0x01044a37c0 if icmpge orgsamplemeasurenormalindex12 line 43,['java'] +632647,woocommerce custom price based on user input i did not want to post here but i could not find the answer i was looking for and i do not have enough reputation to comment on other very similar questions to get my exact answeri found an almost perfect answer from this post woocommerce add product to cart with price overrideusing the codeadd action woocommerce before calculate totals add custom pricefunction add custom price cart object custom price 10 this will be your custome price foreach cart objectcart contents as key value valuedataprice custom price and it works greatif you set a hard coded custom pricemy question is how can i set a custom price based on user input i have tried every way i can think of to pass information i even tried using cookies globals sessions and none of them worked how i wanted and all of them were at best hacksthe specific product in question is a donation and the customer wants the user to be able to set the donation price rather than just creating a variable product with set price pointson the donation page when the user submits the donation form i am adding the donation product to the cart like sodonation success woocommercecartadd to cartdonation id my donation product has a set price of 0 so when it is added to the cart it has a price of 0 i do not know if the price is set at this point or lateri have tried passing in information at this point using the last variable in the add to cart method which accepts an array of arguments but i could not seem to get that to work eitheri am sure the answer is simple but i have been trying for hours to do this right and i cannot get it to work i am out of ideas the actual code i am using at the moment is slightly different than was suggested by the answerer of the above post but works basically the sameadd action woocommerce before calculate totals woo add donationfunction woo add donation global woocommerce donation 10 foreach wccartget cart as cart item key cart item ifcart itemdataid 358 cart itemdataid 360 cart itemdataset pricedonation thanks in advance for any helpful advice,['php'] +632653,are unittest base classes good practice pythonwebapp2 i am rather new to unittesting and am trying to feel out the best practices for the thing i have seen several questions on here relating to unittest inheriting a base class that itself contains several tests for exampleclass testbaseunittesttestcase some standard testsclass anothertesttestbase run some more tests in addition to the standard testsi think what i have gathered from the community is that it is a better idea to write separate tests for each implementation and use multiple inheritance but what if that base class actually does not contain any tests just helpers for all your other tests for example let us say i have got some base test class which i have used to store some common methods that most if not all of my other tests will use let us also assume that i have got a database model in modelspy called contentmodel test basepyimport webtestfrom googleappengineext import testbedfrom models import contentmodelclass testbaseunittesttestcase def setupself selfcontentmodel contentmodel selftestbed testbedtestbed selftestbedactivate other useful stuff def teardownself selftestbeddeactivate def createuserself adminfalse create a user that may or may not be an admin possibly other useful thingsit seems this would save me tons of time on all other testsanother testpyfrom test base import testbaseclass anothertesttestbase def test something authorizedself selfcreateuseradmintrue run a test def test something unauthorizedself selfcreateuseradminfalse run a test def test some interaction with the content modelself new instance selfcontentmodelfoo barput run a testnote this is based on some of my work in webapp2 on google app engine but i expect that an analogous situation arises for pretty much any python web applicationmy questionis it good practice to use a basehelper class that contains useful methodsvariables which all your other tests inherit or should each test class be self containedthanks,['python'] +632668,how to configure sourcemaps for less using grunt i am using grunt 042 and gruntcontribless 090 i want my less to be compiled into css with support for source mapsmy less files are in publicless and the main one is called mainlessthe compiling of publiclessmainless into publiccssmaincss works but source maps do not workwhat is wrong with my grunt config below less dev options compress true yuicompress true optimization 2 sourcemap true sourcemapfilename publiccssmaincsourcemapjson write the source map to a separate file with the given filename sourcemapbasepath publicless sets the base path for the less file paths in the source map sourcemaprootpath adds this path onto the less file paths in the source map files publiccssmaincss publiclessmainless watch styles files publicless tasks less options livereload true nospaces true i do not want to have my css created in my publicless folder i want to put it into publiccss otherwise i could use this other config which works less dev options compress true yuicompress true optimization 2 sourcemap true sourcemapfilename publiclessmaincssmap i do not want the css map here sourcemapbasepath publicless sets the base path for the less file paths in the source map files publiclessmaincss publiclessmainlessi do not want the css here watch styles files publicless tasks less options livereload true nospaces true,['css'] +632686,is it possible to push viewcontroller with completion block and how can i do it there is no such method in documentation,['ios'] +632755,why do i have to reference ef in my ui project is not there a more graceful way to have entity framework deployed with your ui project specifically the sql server driver for ef entityframeworksqlserverdll deployed with your aspnet project than having to add reference to ef via nuget in your ui project in this stack overflow question the answer posted is to make an unneeded line of code in my aspnet project just to get the dependent file to copy over when my aspnet app is deployedstack overflow articlei do not think i should have to add unused code in order to deploy a dependencynor should i have to add a reference to ef in my ui projecti understand that the ef file entityframeworksqlserverdll is injected at run time into entity frameworkyes my aspnet project is configured correctly it runs great if it has a nuget reference to ef or the dll entityframeworksqlserverdllbuti do not want to add a reference to entity framework using nuget to my aspnet mvc project just to deploy this filei do not want to add a reference to the file which is in my dal project bin folder that would be very brittlei could add a post build event to the aspnet mvc project but that seems brittle tooin mstest projects we can add a deploymentitem attribute to deploy these types of dependencies is there an equivalent in aspnet perhaps something you can put in the webconfigi would think that if i could configure in the webconfig to reference the sql provider used by entity framework entityframework defaultconnectionfactory typesystemdataentityinfrastructurelocaldbconnectionfactory entityframework parameters parameter valuev110 parameters defaultconnectionfactory providers provider invariantnamesystemdatasqlclient typesystemdataentitysqlserversqlproviderservices entityframeworksqlserver providers entityframeworkthat you could also configure the dll to deploy too213 editi am using visual studio 2013 and ef 6a couple of people have asked why i care and why i do not just use nuget to manage this and add the entity framework reference to my ui project using nuget2 reasonsmy ui should not have to know anything about what my orm is and should not need a project reference to it in my ui projectmore importantly i manage a team of developers with varying skill levels onshore and off shore i do not want one of them to accidentally use an ef class in the ui having a reference to ef in the ui project makes it all to easy to have vs or resharper slip in a using systemdataentity and off you go using your orm in your ui project,['asp.net'] +632772,check and wait until a file exists to read it i need to wait until a file is created then read it in i have the below code but sure it does not workimport ospathif ospathisfilefile path read file inelse waitany ideas please,['python'] +632792,calling derived methods on a baseclass collection i have one abstract class named a and other classes b c d e that implements amy derived classes are holding values of different typesi also have a list of a objects abstract class a class b class a public int val getprivate set class c class a public double val getprivate set class d class a public string val getprivate set class program static void mainstring args list list new list new b new c new d new e foreach a item in list consolewritelinestringformatvalue is 0 itemval where the val is not known by the baseclass ofchow can i get this dynamic behaviour i do not want to use gettype in a long switchifstatements,['c#'] +632829,how should i define launchmode in androidmanifestxml using phonegap jqm i am struggling to restrict my application to a single instance currently if the user presses home screen to quit the application then does something outside and clicks on the applications icon again it launches the apps second instancehere is my complete manifest filexml version10 encodingutf8manifest xmlnsandroid packagecommydomainqfa androidversioncode4 androidversionname13usessdk androidminsdkversion7 androidtargetsdkversion13 androidmaxsdkversion18 usespermission androidnameandroidpermissioninternet usespermission androidnameandroidpermissionwrite external storage usespermission androidnameandroidpermissionread phone state application androiddebuggablefalse androidtestonlyfalse androidicondrawableiconpngactivity androidnamecommydomainqfa androidlaunchmodesingletask androidalwaysretaintaskstatetrue androidicondrawableiconpngactivityapplicationmanifestits a single activity app basically no activities defined on the main jqm page i have something like these entriesdiv datarolepage idhomepage div datathemed dataroleheader datapositionfixed stylepaddingbottom 0px datataptogglefalse div datarolenavbar div datarolecontent classmaincontent styleoverflowhidden paddingtop 0pxcan someone please tell me if my manifest is correct and if i should be usingandroidnamecommydomainqfaor should it something else like androidnamecommydomainqfahomepageor androidnamecommydomainqfamaincontentthanks in advance,['android'] +632830,why are native array functions are so much slower then loop the question is in the title but here is a longer explanationlong time ago i learned some nice javascript functions like reduce filter map and so on i really liked them and started to use them frequently they look stylish and i thought that because they are native functions they should be faster than my old for loopsrecently i needed to perform some heavy js computations so i decided to check how faster are they and to my surprise they are not faster they are much much slower from 3 to 25 times sloweralso i have not checked for every function by here are my jsperf tests forfilter 25 times slowerreduce 3 times slowermap 3 times slowerso why are native functions are so much slower then old loops and what was the point of creating them if they are not doing anything betteri assume that the speed loss is due to the invocation of the function inside of them but still it does not justify such loss also i can not see why the code written with these functions is more readable not to mention that they are not supported in every browser,['javascript'] +632837,exclude retweets in twitter search api 11 here i am trying to retrieve the tweets which has the tag v57 using search api 11 dumped seen the results of search term by usingsearch tim connectiongetsearchtweetsarrayq v57 count 5 result type recentthis is the result after doing var dump objectstdclass10 2 statuses array5 0objectstdclass11 25 metadata objectstdclass12 2 result type string6 recent iso language code string2 en created at string30 wed feb 12 162635 0 2014 id float4336382735e17 id str string18 4336382731354561 text string131 rt useracc plz consult a doctor v57 source string84 twitter for android truncated boolfalse in reply to status id null in reply to status id str null in reply to user id null in reply to user id str null in reply to screen name null user objectstdclass13 40 id int965892252 id str string9 965892252 name string10 khan screen name string10 khan location string0 url null entities objectstdclass14 1 description objectstdclass15 1 urls array0 protected boolfalse followers count int457 friends count int500 listed count int3 created at string30 fri nov 23 105608 0 2012 favourites count int129 utc offset int19800 time zone string7 chennai geo enabled boolfalse verified boolfalse statuses count int3230 lang string2 en contributors enabled boolfalse is translator boolfalse is translation enabled boolfalse profile background color string6 0099b9 profile background image url string48 profile background image url https string49 profile background tile boolfalse profile image url string99 images37880939930639a4b8297f9eea2cbb9de89f5c3a40 normaljpeg profile image url https string100 images378839930639a4b8297f9eea2cbb95c3a40 normaljpeg profile banner url string58 banners96589221386619 profile link color string6 0099b9 profile sidebar border color string6 5ed4dc profile sidebar fill color string6 95e8ec profile text color string6 3c3940 profile use background image booltrue default profile boolfalse default profile image boolfalse following boolfalse follow request sent boolfalse notifications boolfalse geo null coordinates null place null contributors null retweeted status objectstdclass16 24 metadata objectstdclass17 2 result type string6 recent iso language code string2 en created at string30 wed feb 12 1536 0 2014 id float43362493936345e17 id str string18 43362493446784 source string84 twitter for android truncated boolfalse in reply to status id null in reply to status id str null in reply to user id null in reply to user id str null in reply to screen name null user objectstdclass18 40 id int168362964 id str string9 168362964 name string5 usracc screen name string12 useracc location string16 india url null entities objectstdclass19 1 description objectstdclass20 1 urls array0 protected boolfalse followers count int651 friends count int197 listed count int6 created at string30 mon jul 19 035415 0 2010 favourites count int4267 utc offset int19800 time zone string7 chennai geo enabled booltrue verified boolfalse statuses count int10177 lang string2 en contributors enabled boolfalse is translator boolfalse is translation enabled boolfalse profile background color string6 c0deed profile background image url string48 profile background image url https string49 profile background tile boolfalse profile image url string75 images4338561184qufhkeyq normaljpeg profile image url https string76 images433856131184qufhkeyq normaljpeg profile banner url string58 banners1683641392170036 profile link color string6 0084b4 profile sidebar border color string6 c0deed profile sidebar fill color string6 ddeef6 profile text color string6 3 profile use background image booltrue default profile booltrue default profile image boolfalse following boolfalse follow request sent boolfalse notifications boolfalse geo null coordinates null place null contributors null retweet count int5 favorite count int10 entities objectstdclass21 5 hashtags array1 0 objectstdclass22 2 text string7 v57 indices array2 0 int76 1 int84 symbols array0 urls array0 favorited boolfalse retweeted boolfalse possibly sensitive boolfalse lang string2 en retweet count int5 favorite count int0now i would like to retrieve the original tweets alone which has v57 tag by ignoring all retweets similar to this string131 rt useravv plz consult a doctor v57i have googled and found this thread but it was old api versionmy doubt has been cleared thanks to the so user newbi3 here is a way to exclude retweets in search api 11search tim connectiongetsearchtweetsarrayq v57 rt count 5result type recentadding rt at the end of search term will filter itedit the above approach will simply eliminate the tweet too if they included rt is in their status and username or screename this will blindly ignore tweets when its sees rt this is a temporary solutionthe permanent solution is get the rt status if if its retweet simply assign a value like 1 to a variable 0 if its original eg if issettweet objectretweeted status this is a retweet use the original tweets entities they are more complete entities tweet objectretweeted statusentities is rt 1 set 1 if retweeted else entities tweet objectentities is rt 0 set 0 if original then just do like ifis rt0 if its a original tweet,['php'] +632838,factorial calculation using python i am new to python and currently reading python 3 for absolute beginner and face following problem i would like to calculate factorial with procedurerequest user to input an non negative number nthen use for loop to calculate factorialand the code is like thatn inputplease input factorial you would like to calculate ans 1for i in range1n11 ans ansiprintanswhile i would like to add a feature to check whether input number and is nonnegative number likeif and intn and and 0i want the user to input and again if it is not nonnegative numberthanks for your gentle help,['python'] +632863,difference between responsesend and responsewrite in node js i have written a small api which uses the node js restify framework this api receives a request actually anything after and then send that request to another server get the response back from server and passes the response back to original source of request for this api i am using both restify server and clientbelow is that api code for better understandingvar apiserver requireapiserverapiserverstartvar restify requirerestifyvar assert requireassertfunction onrequestrequest response next var client restifycreatestringclient url clientget requestparams0 functionerr req res data assertiferrorerr responsesetheadercontenttype texthtml responsewriteheadresstatuscode responsewritedata responseend nextfunction start var server restifycreateserver serverget onrequest serverlisten8 consolelogserver has startedexportsstart startnow i need to know the difference between responsewrite and responsesend of nodejs because with responsewrite i can set header and write in it but it is not possible to do anything with headers when i use responsesend when i use responsesend with setheader or writeheader i get this errorhttpjs691 throw new errorcannot set headers after they are sent error cannot set headers after they are sentthere is also another thing with responsesend i get the complete html output on the screen likedoctype htmlnhtmlntheadheadhtml bla bla blabut with responsewrite i do not get the html on screen but only the text bla bla blait would be great if someone can explain me the differences,['javascript'] +632872,how to properly animate uiscrollview contentoffset i have uiscrollview subclass its content is reusable about 4 or 5 views are used to thisplay hundreds of elements while scrolling hidden objects reused and jumps to another position when its needed to see themwhat i need ability to automatically scroll my scroll view to any position for example my scroll view thisplays 4th 5th and 6th element and when i tap some button it needs to scroll to 30th element in other words i need standard behaviour of uiscrollviewthis works fineself setcontentoffsetcgpointmakeindexelementwidth 0 animatedyesbut i need some customisation for example change animation duration add some code to perform on end of animationobvious decisionuiview animatewithduration3 delay0 optionsuiviewanimationoptionbeginfromcurrentstate animations self setcontentoffsetcgpointmakeindexelementwidth 0 completionbool finished some codebut i have some actions connected to scroll event and so now all of them are in animation block and it causes all subviews frames to animate too thanks to few reusable elements all of them animates not how i wantthe question is how can i make custom animation in fact i need custom duration actions on end and beginfromcurrentstate option for content offset without animating all the code connected to scrollviewdidscroll eventupdthanks to andrews answerfirst part i solved issue with animation inside scrollviewdidscroll voidscrollviewdidscrolluiscrollview scrollview uiview performwithoutanimation self refreshtiles but scrollviewdidscroll must for my purposes executes every frame of animation like it was in case ofself setcontentoffsetcgpointmakeindexelementwidth 0 animatedyeshowever now it executes only once at start of animationhow can i solve this,['ios'] +632894,could a class instance that is not being assigned to a variable get garbagecollected too early i do not even know whether my question makes sense at all it is just something that i do not understand and is spinning in my head for some timeconsider having the following classpublic class myclass private int myvar public void dosomething do something myvar 1 systemconsolewritelineinside and using this class like thispublic class test public static void main some code systemconsolewritelinebefore no assignment to a variable new myclassdosomething some other code systemconsolewritelineafter ideoneabove i am creating an instance of a class without assigning it to a variablei fear that the garbage collector could delete my instance too earlymy naive understanding of garbage collection isdelete an object as soon as no references point to itsince i create my instance without assigning it to a variable this condition would be true obviously the code runs correct so my asumption seems to be falsecan someone give me the information i am missingto summarize my question iswhywhy not is it safe to instantiate a class without asigning it to a variable or returning itie isnew myclassdosomethingandvar c new myclasscdosomethingthe same from a garbage collection pointofview,"['c#', '.net']" +632942,while importing mysqldump file error 1064 420 near a a at line 1 cannot import the below dump file created by mysqldumpexe in command line of windows40101 set saved cs client character set client 40101 set character set client utf8 create table attachment types id int11 not null auto increment description varchar50 default null comments varchar256 default null primary key id unique key uk attachment types description description engineinnodb auto increment4 default charsetlatin1while importing the file in command line mysql userroot passwordroot mysqldumpfilesqlit throws error error 1064 420 near a at line 1somebody please help me,['mysql'] +633027,numpy array integer float division i found the following behaviour in pythonnumpy somewhat strangein 51 a nparange10 20in 52 a a 100in 53 aout53 array 1 11 12 13 14 15 16 17 18 19in 54 a nparange10 20in 55 a 100in 56 aout56 array1 1 1 1 1 1 1 1 1 1i felt that aa100 and a100 should return the same result is this inteded and documented somewhere,['python'] +633069,apprtcdemo on local server works between browsers and android but not on ios i am trying to make a call with webrtc between iphone to browser with apprtcdemoeverything works fine through apprtcappspotcom but when i ran the app on my server i was able to make a call between browsers and with the help of this post i made a call between browser to androidi cannot make the call between iphone to browserachanges to codein apprtcappclientmnsstring path nsstring stringwithformathttps url resourcespecifier nsstring path nsstring stringwithformathttp url resourcespecifiernsstring url nsstring stringwithformat selfbaseurl selfpostmessageurl nsstring url nsstring stringwithformat selfpostmessageurlrequest addvalue forhttpheaderfieldorigin request addvalue forhttpheaderfieldoriginin apprtcviewcontrollermnsstring url nsstring stringwithformatapprtcapprtcappspotcomr room nsstring url nsstring stringwithformatapprtcx9090r roomin ios channelhtmlscript typetextjavascript src ahchanneljsapiscript script typetextjavascript src ahchanneljsapiscriptwhen i try to connect to the room from iphone on my server i get this log messagesinfo 20140211 071153911 apprtcpy350 in class mainpageinfo 20140211 071153927 apprtcpy246 in class room add userinfo 20140211 071153941 apprtcpy77 create channelinfo 20140211 071153941 apprtcpy163 applying media constraints video true audio trueinfo 20140211 071153957 apprtcpy517 user 80844306 added to room 85info 20140211 071153957 apprtcpy518 room 85 has state 80844306falseinfo 20140211 071153973 modulepy612 default get r85 http11 200 1744at this point connectpage should be called to connect to the room but nothing happensawhen i try to connect to the room from android on my server i get this log messagesinfo 20140211 071153911 apprtcpy350 in class mainpageinfo 20140211 071153927 apprtcpy246 in class room add userinfo 20140211 071153941 apprtcpy77 create channelinfo 20140211 071153941 apprtcpy163 applying media constraints video true audio trueinfo 20140211 071153957 apprtcpy517 user 59372716 added to room 51info 20140211 071153957 apprtcpy518 room 51 has state 59372716falseinfo 20140211 071153973 modulepy612 default get r51 http11 200 1744info 20140211 071155142 apprtcpy306 in class connectpageinfo 20140211 071155158 apprtcpy298 user 59372716 connected to room51info 20140211 071155158 apprtcpy299 room 51 has state 59372716trueinfo 20140211 071155190 modulepy612 default post ahchannelconnected http11 200 the call is not going through because there is no actual connection to the roomi also tried using wireshark to see what is being sent between client to server with both android and iphone as the clientfrom iphone1009 319788720 8494156147 x http 265 get r9 http11 1022 320881160 x 8494156147 http 235 http11 200 ok texthtml1093 327884070 8494156147 x http 343 get ahchanneljsapi http11 1404 341914650 x 8494156147 http 769 http11 200 ok textjavascriptget r9 http11 hypertext transfer protocol get r9 http11rn expert info chatsequence get r9 http11rn message get r9 http11rn severity level chat group sequence request method get request uri r9 request version http11 host x9090rn connection keepalivern acceptencoding gzip deflatern useragent apprtcdemo10 cfnetwork67208 darwin1400rn acceptlanguage heilrn accept rn rn full request uri http request 11 response in frame 1022http11 200 ok texthtmlhypertext transfer protocolhttp11 200 okrn expert info chatsequence http11 200 okrn message http11 200 okrn severity level chat group sequence request version http11 status code 200 response phrase okcontenttype texthtml charsetutf8rncachecontrol nocacherncontentlength 1705rn content length 1705server development20rn date thu 13 feb 2014 125523 gmtrn rn http response 11 linebased text data texthtml here i have the indexhtml file filled with the content for each of the vars get ahchanneljsapi http11 hypertext transfer protocol get ahchanneljsapi http11rn expert info chatsequence get ahchanneljsapi http11rn message get ahchanneljsapi http11rn severity level chat group sequence request method get request uri ahchanneljsapi request version http11 host x9090rn connection keepalivern acceptencoding gzip deflatern useragent mozilla50 iphone cpu iphone os 7 0 4 like mac os x applewebkit537511 khtml like gecko mobile11b554arn acceptlanguage heilrn accept rn rn full request uri ahchanneljsapi http request 11 response in frame 1404 http11 200 ok textjavascript http11 200 ok texthtml hypertext transfer protocol http11 200 okrn expert info chatsequence http11 200 okrn message http11 200 okrn severity level chat group sequence request version http11 status code 200 response phrase ok cachecontrol nocachern contenttype textjavascriptrn contentlength 238051rn content length 238051 server development20rn date thu 13 feb 2014 125524 gmtrn rn http response 11 linebased text data texthtml here i have the jsapi filefrom android 2103 649948170 62219128171 x http 231 get r7 http11 2109 650560730 x 62219128171 http 225 http11 200 ok texthtml 2329 684367490 62219128171 x http 499 get ahchanneljsapi http11 2659 717660890 x 62219128171 http 869 http11 200 ok textjavascript 2723 725483160 62219128171 x http 582 get ahchanneldev commandconnectchannel52dc587e2a55f84d5a24d607e01265a6channel26721969581392299260748366753 http11 2725 725510590 x 62219128171 http 67 http11 200 ok textplain 2755 735463690 62219128171 x http 588 get ahchanneldev commandpollchannel52dc587e2a55f84d5a24d607e01265a6channel26721969581392299260 748366753client1 http11 2756 735478290 x 62219128171 http 191 http11 200 ok get r7 http11 hypertext transfer protocol get r7 http11rn expert info chatsequence get r7 http11rn message get r7 http11rn severity level chat group sequence request method get request uri r7 request version http11 useragent dalvik160 linux u android 43 nexus 4 buildjwr66vrn host x9090rn connection keepalivern acceptencoding gziprn rn full request uri http request 11 response in frame 2109http11 200 ok texthtmlhypertext transfer protocol http11 200 okrn expert info chatsequence http11 200 okrn message http11 200 okrn severity level chat group sequence request version http11 status code 200 response phrase ok contenttype texthtml charsetutf8rn cachecontrol nocachern contentlength 1695rn content length 1695 server development20rn date thu 13 feb 2014 131739 gmtrn rn http response 12linebased text data texthtml here i have the indexhtml file filled with the content for each of the vars get ahchanneljsapi http11 hypertext transfer protocol get ahchanneljsapi http11rn expert info chatsequence get ahchanneljsapi http11rn message get ahchanneljsapi http11rn severity level chat group sequence request method get request uri ahchanneljsapi request version http11 host x9090rn connection keepalivern referer accept rn xrequestedwith orgappspotapprtcrn useragent mozilla50 linux u android 43 heil nexus 4 buildjwr66v applewebkit53430 khtml like gecko version40 mobile safari53430rn acceptencoding gzip deflatern acceptlanguage heil enusrn acceptcharset utf8 iso88591 utf16 q07rn rn full request uri ahchanneljsapi http request 18http11 200 ok textjavascripthttp11 200 ok texthtmlhypertext transfer protocol http11 200 okrn expert info chatsequence http11 200 okrn message http11 200 okrn severity level chat group sequence request version http11 status code 200 response phrase ok cachecontrol nocachern contenttype textjavascriptrn contentlength 238051rn content length 238051 server development20rn date thu 13 feb 2014 131742 gmtrn rn http response 18linebased text data texthtml here i have the jsapi filecan any one please help with this issueany ideas on how to proceed will be good at this pointthanks in advance,"['ios', 'iphone', 'objective-c']" +633150,uiviewcontrolleranimatedtransitioning with a mpmovieplayerviewcontroller i am trying to do a custom presentation animation but the vc is an mpmovieplayerviewcontroller i was following this tutorialwhen i present the mpmovieplayerviewcontroller all is rightbut when i thismiss it simply the method id uiviewcontrolleranimatedtransitioninganimationcontrollerforthismissedcontrolleruiviewcontroller thismissedis not called what i am doing wrongthis is the code ibactionplaybuttontouchedinidsender nsurl url nsbundle mainbundleurlforresourcelearn to speak spanish quickly with funny videos on youtube withextensionmp4 mpmovieplayerviewcontroller player mpmovieplayerviewcontroller allocinitwithcontenturlurl playertransitioningdelegate self playermodaltransitionstyle uimodalpresentationcustom playermovieplayer setshouldautoplayno playermovieplayercontrolstyle mpmoviecontrolstylenone self presentviewcontrollerplayer animatedyes completion playermovieplayer play playermovieplayercontrolstyle mpmoviecontrolstylefullscreen the uiviewcontrollertransitioningdelegate methods id uiviewcontrolleranimatedtransitioninganimationcontrollerforpresentedcontroller uiviewcontroller presented presentingcontrolleruiviewcontroller presenting sourcecontrolleruiviewcontroller source selfpresenting yes return self id uiviewcontrolleranimatedtransitioninganimationcontrollerforthismissedcontrolleruiviewcontroller thismissed selfpresenting no return selfthe uiviewcontrolleranimatedtransitioning methods nstimeintervaltransitiondurationid uiviewcontrollercontexttransitioningtransitioncontext return 07 voidanimatetransitionid uiviewcontrollercontexttransitioningtransitioncontext uiviewcontroller fromviewcontroller transitioncontext viewcontrollerforkeyuitransitioncontextfromviewcontrollerkey uiviewcontroller toviewcontroller transitioncontext viewcontrollerforkeyuitransitioncontexttoviewcontrollerkey if selfispresenting fromviewcontrollerview setuserinteractionenabledno transitioncontextcontainerview addsubviewfromviewcontrollerview transitioncontextcontainerview addsubviewtoviewcontrollerview cgrect startframe toviewcontrollerviewframe toviewcontrollerviewframe cgrectcgpointmaketoviewcontrollerviewframesizewidth 0startframesize uiview animatewithdurationself transitiondurationtransitioncontext delay00f usingspringwithdamping05f initialspringvelocity40f optionsuiviewanimationoptioncurveeaseout animations toviewcontrollerviewframe startframe completionbool finished transitioncontext completetransitionyes fromviewcontrollerview setuserinteractionenabledyes else toviewcontrollerview setuserinteractionenabledyes transitioncontextcontainerview addsubviewtoviewcontrollerview transitioncontextcontainerview addsubviewfromviewcontrollerview cgrect finalframe cgrectcgpointmakefromviewcontrollerviewframesizewidth 0fromviewcontrollerviewframesize uiview animatewithdurationself transitiondurationtransitioncontext animations fromviewcontrollerviewframe finalframe completionbool finished transitioncontext completetransitionyes i have tried with a view controller developed by me and it works great so is should be the mpmovieplayerviewcontroller,['ios'] +633228,site to site openswan vpn tunnel issues with aws we have a vpn tunnel with openswan between two aws regions and our colo facility used awsas guide regular usage works ok ssh etc but we are having some mysql issues over the tunnel between all areas using mysql command line client on a linux server and trying to connect using the mysql connector j it basically stallsa it seems to open the connection but then gets stuck it does not get denied or anything just hangs there after initial research thought this was an mtu issue but i have messed with that a lot and no luck connection to the server works fine and we can choose a database to use and such but using the java connector it appears that the java client is not receiving any network traffic after the query is madewhen running a select in the mysql client on linux we can get a max of 2 or 3 rows before it goes dead with this said i also have a separate openswan vpn on the aws side for client mac and ios vpn connections everything works fantastically through the client vpn and it seems more stable in general the main difference i have noticed is that the static connection is using tunnel as the type and the client is using transport but when switching the static tunnel connection to transport it says there is like 30 open connections and does not worki am very new to openswan so hoping someone can help to point me in the right direction of getting the static tunnel working as well as the client vpn as always heres my config filesipsecconf for both static tunnel servers basic configurationconfig setup debuglogging controls none for almost none all for lots klipsdebugnone plutodebugcontrol parsing for red hat enterprise linux and fedora leave protostacknetkeyprotostacknetkeynat traversalyesvirtual privateoeoff enable this if you see failed to find any available worker nhelpers0you may put your configuration conf file in the etcipsecd and uncomment thisinclude etcipsecdconfvpc1tocolo tunnel confconn vpc1todttypetunnelauthbysecretleftdefaultrouteleftid5421324xleftnexthopdefaultrouteleftsubnet1014024right7226103xrightsubnet1012023pfsyesautostartcolotovpc1 tunnel confconn dttovpc1typetunnelauthbysecretleftdefaultrouteleftid7226103xleftnexthopdefaultrouteleftsubnet1012023right5421324xrightsubnet1014024pfsyesautostartclient point vpn ipsecconf basic configurationconfig setupinterfacesdefaultrouteklipsdebugnonenat traversalyesnhelpers0oeoffplutodebugnoneplutostderrlogvarlogplutologprotostacknetkeyvirtual privatev41014024conn l2tppskauthbysecretpfsnoautoaddkeyingtries3rekeynotypetransportforceencapsyesrightanyrightsubnetvhostanyprivrightprotoport170 using the magic port of 0 means any one single port this is a work around required for apple osx clients that use a randomly high port but propose 0 instead of their portleftdefaultrouteleftprotoport171701 apple ios does not send delete notify so we need dead peer detection to detect vanishing clientsdpddelay10dpdtimeout90dpdactionclear,['mysql'] +633277,polymer and webcomponentsready event according to the polymer docs the webcomponentsready event is necessary becausethe polyfills parse element definitions and handle their upgrade asynchronously if you prematurely fetch the element from the dom before it has a chance to upgrade youall be working with an htmlunknownelement in these situations wait for the webcomponentsready event before interacting with the elementi have an html page that imports a single web component and registers a handler that logs a statement when all web components are loadeddoctype htmlhtml head script srcbower componentsplatformplatformjsscript link relimport hrefelementsmyelementhtml head body unresolved myelementmyelement script windowaddeventlistenerwebcomponentsready functione consolelogcomponents ready script bodyhtmlwhy is the webcomponentsready event firing before myelements ready polymer event i need to know when i can interact with the custom element eg change its properties and call its public methods,"['javascript', 'html']" +633310,typeerror got multiple values for argument i read the other threads that had to do with this error and it seems that my problem has an interesting thistinct difference than all the posts i read so far namely all the other posts so far have the error in regards to either a user created class or a builtin system resource i am experiencing this problem when calling a function i cannot figure out what it could be for any ideasbox length 100turtlespeed0fill 0for i in range8 fill 1 if fill 2 0 horizontol drawboxbox length fillbox false else horizontol drawboxbox length fillbox true for i in range8 fill 1 if fill 2 0 vertical drawboxbox lengthfillbox false else vertical drawboxbox lengthfillbox trueerror message horizontol drawboxbox length fillbox truetypeerror horizontol drawbox got multiple values for argument fillbox,['python'] +633337,algorithm to find the union of multiple strings grouped by character index i have been trying to think of a performance efficient way of finding the union of character occurrences in a set of fixed width strings grouped by index something like thiss1 013965s2 015935s3 310012resulting in the following where each group of digits exists in all strings at char index nout 0313509063152i have thought of doing it the very naive way of iterating through every string at every index while storing the intermediate strings in an array and then iterating through that array to build the output value however my approach seems to me as a highly inefficient way which is way too far from an asymptotically optimal solution,['java'] +633338,calling appmodel function in appcontroller for cakephp i have a function that i want all of my controllers to be able to use so i have defined it in appcontroller now part of what this function will do has no business being in a controller and so it should be in a model but since this is a universal operation it only seems correct that it be in appmodel my function looks as followedclass appcontroller extends controller public function i need this everywhere term do some stuff this is the line that is an issue it seems like this should be simple and work but no variation of this is working value thisappget some cool dataterm return value i simply want to be able to call an appmodel function from appcontroller i have tried the following i have tried several variations of thisthisloadmodelappmodelthisappmodelget some cool datatermbut this then complains about the lack of database table called appmodel at which point in appmodel i tried settingpublic usetable falsebut that blows the whole app up so now i am out of ideas any help would be greatly appreciated,['php'] +633406,how to move pandas data from index to column after multiple groupby i have the following pandas dataframein 8 dfalphheadout8 token year uses books 386 xanthos 1830 3 3 387 xanthos 1840 1 1 388 xanthos 1840 2 2 389 xanthos 1868 2 2 390 xanthos 1875 1 1i aggregate the rows with duplicate token and years like soin 63 dfalph dfalphtoken year uses booksgroupbytoken yearaggnpsum dfalphcolumns dfalphcolumnsdroplevel1 dfalphheadout63 uses books token year xanthos 1830 3 3 1840 3 3 1867 2 2 1868 2 2 1875 1 1instead of having the token and year fields in the index i would like to return them to columns and have an integer index,['python'] +633450,javascript object variable becomes undefined inside anonymous function so i cannot quite figure out why the variable thistasks becomes undefined inside of the add event listener i have inside of my goal object i have a feeling it might have something to do with asynchronous programmingwhich i still do not fully understand sorry i am a bit of a js noob but if you guys could explain to me what i am doing wrong and what might be a better solution that would be awesome thanksfunction goalname thisgdiv documentcreateelementdiv thisname name goal thistasks documentcreateelementul sets the styling and content and adds it to the parent element thisinitialize function thisgdivclassname default thisgdivsetattributeid thisname thisgdivinnerhtml thisname elemappendchildthisgdiv thisgdivparentnodeinsertbeforethistasks thisgdivnextsibling thistasksstylethisplay none creates a list underneath the a dive associated with the goal object thisaddtask functiontask var newli documentcreateelementli newliinnerhtml task thistasksappendchildnewli thisgdivaddeventlistenerclick function alertthistasks thank you guys you all answered my question i would been scratching my head at this for a while kudos to you all,['javascript'] +633451,file upload using java websocket api and javascript i am studying websocket and have done chat program with websocketjson but i am stuck at file uploading atm any advice answer would be thankfulserver sidepackage websocketimport javaiofileimport javaiofilenotfoundexceptionimport javaiofileoutputstreamimport javaioioexceptionimport javaniobytebufferimport javaxwebsocketclosereasonimport javaxwebsocketendpointconfigimport javaxwebsocketoncloseimport javaxwebsocketonerrorimport javaxwebsocketonmessageimport javaxwebsocketonopenimport javaxwebsocketsessionimport javaxwebsocketserverserverendpointserverendpointreceivefileserverpublic class fileserver onopen public void opensession session endpointconfig conf systemoutprintlnchat ws server open onmessage public void processuploadbytebuffer msg boolean last session session systemoutprintlnbinary message fileoutputstream fos null file file new fileddownloadtmptxt try fos new fileoutputstreamfile catch filenotfoundexception e eprintstacktrace byte readdata byte 9 whilereaddata1 readdatamsgget try foswritereaddata catch ioexception e eprintstacktrace onmessage public void messagesession session string msg systemoutprintlngot msg msg msglength onclose public void closesession session closereason reason systemoutprintlnsocket closed reasongetreasonphrase onerror public void errorsession session throwable t tprintstacktrace clienthtmlheadmeta httpequivcontenttype contenttexthtml charsetutf8titlechattitlescript typetextjavascript srcmyhomepagejquery203minjsscriptheadbody h2file uploadh2 select file input typefile idfilename br input typebutton valueconnect onclickconnectchatserver br input typebutton valueupload onclicksendfile script var ws function connectchatserver ws new websocket wslocalhost8080myhomepagereceivefileserver wsbinarytype arraybuffer wsonopen function alertconnected wsonmessage functionevt alertevtmsg wsonclose function alertconnection is closed wsonerror functione alertemsg function sendfile var file documentgetelementbyidfilenamefiles0 var reader new filereader var rawdata new arraybuffer readerloadend function readeronload functione rawdata etargetresult wssendrawdata alertthe file has been transferred readerreadasbinarystringfile scriptbodyhtmlserver side closed reason message is as belowsocket closed the decoded text message was too big for the output buffer and the endpoint does not support partial messagesq1 it seems that it is finding text processing method instead of binary processing method according to the closed reason how can i fix thisq2 should i change data type to blob to transfer file on javascript side then howextra q may anyone link example sourcees of websocket file transferringjava websocket or javascript eitherboth thanks for reading,"['java', 'javascript']" +633501,nesting inside css not selectors is it possible to have nested values inside the not selector for egnotdiv divwhenever i tried it it does not seem to work perhaps you need to use it another way which i have not figured outso far in all the examples i see you can only use one value inside this selector,['css'] +633503,unable to find a specification for afnetworking 210 am on a rubymotion projecthave required afmotion in rake file gem file and bundle installed i get the above error when i try to run rake podinstallany ideas thanks in advance,['ruby'] +633688,what does high involuntary context switches mean i have rewritten a part of code in c when testing it with logging the resource usage using getrusage2 c api before changing the codeuser time ms 21503system time ms 372involuntary context switches 20after changinguser time ms 25589system time ms 80732involuntary context switches 821i see a lot of involuntary context switches being done in the code i have rewritten my question is not about how to reduce context switches but what happens when involuntary context switches are more in what way it will affect the systemps there is no activity on the thisk as nothing is being written it just pings the server several times updateadded system and user time taken program is multithreaded same number of threads 3k thread are spawned in both the cases only the underlying api in c is being rewritten,"['c++', 'c']" +633778,bullettime css animation slowdown code in jsfiddlei want to use jquery to slow the animation speed of a cssanimated atom to a crawl on mouseover but to do so using some kind of easing i can get jquery to change the play state to paused easy enough but to slow to a crawl seems harderhtmldiv idatom div idcloud div classorbit div classpath div classelectrondiv div div div classorbit div classpath div classelectrondiv div div div classorbit div classpath div classelectrondiv div div div classorbit div classpath div classelectrondiv div div div idnucleusdiv div divcssatom position absolute top 50 left 50 width300px marginleft 170px margintop 146px transition all 15s cloud width300px height300px webkitperspective 10 positionrelative webkitanimationplaystatepausednucleus positionabsolute top50 left50 margin 10px 0 0 10px width25px height25px borderradius25px webkitborderradius25px mozborderradius25px background 272727orbit positionabsolute top0 left0 width300px height300px borderradius300px webkitborderradius300px mozborderradius300px border5px solid c webkittransformstyle preserve3d webkittransform rotatex80deg rotatey20degcloud orbitnthchild2 webkittransform rotatex80deg rotatey70degcloud orbitnthchild3 webkittransform rotatex80deg rotatey20degcloud orbitnthchild4 webkittransform rotatex80deg rotatey50degcloud orbitnthchild2 path cloud orbitnthchild2 electron webkitanimationdelay 10scloud orbitnthchild3 path cloud orbitnthchild3 electron webkitanimationdelay 15scloud orbitnthchild4 path cloud orbitnthchild4 electron webkitanimationdelay 05spath width300px height300px positionrelative webkittransformstyle preserve3d webkitanimationname pathrotate webkitanimationduration 2s webkitanimationiterationcount infinite webkitanimationtimingfunction linear electron position absolute top5px left50 marginleft5px width10px height10px borderradius10px backgroundc webkitanimationname electronfix webkitanimationduration 2s webkitanimationiterationcount infinite webkitanimationtimingfunction linear webkitkeyframes pathrotate from webkittransform rotatez0deg to webkittransform rotatez360deg webkitkeyframes electronfix from webkittransform rotatex90deg rotatey0deg to webkittransform rotatex90deg rotatey360deg jsfunction atommouseoverfunction path animatewebkitanimationduration 25s duration slow electron animatewebkitanimationduration 25s duration slow mouseoutfunction path animatewebkitanimationduration 2s duration slow electron animatewebkitanimationduration 2s duration slow thanks,"['javascript', 'jquery', 'html', 'css']" +633830,convert txt packet data to pcap format to open it by wireshark hi i am working on application where i have to read live packets from network work on it and thisplay it in sophisticated waybut problem is i have packet but it is in text file so to open it by wireshark i have to convert it in pcap formatso how can i convert packet in text to pcap formatmy text file format is like this shown belowframeframe number 0frame timestamp 20140213 093911288frame wire length 174 bytesframe captured length 174 bytesframeeth ethernet ethernet offset0 0x0 length14 eth eth destination 01005e7faeth 0 0 lg biteth 0 0 ig biteth source ec9a744d8e03eth 0 0 lg biteth 0 0 ig biteth type 0x800 2048 ip version 4eth ip ip4 ip version 4 offset14 0xe length20 protocol suitenetworkip ip version 4ip hlen 5 5 4 20 bytes no ip optionsip diffserv 0x0 0ip 0 00 0 code point not setip 0 0 ecn bit not setip 0 0 ece bit not setip length 160ip id 0x4cd1 19665ip flags 0x0 0ip 0 0 reservedip 0 0 df do not fragment not setip 0 0 mf more fragments not setip offset 0ip ttl 0 time to liveip type 17 next user datagramip checksum 0xb0aa 45226 correctip source 1241258090ip destination 239255255250ip udp udp offset34 0x22 length8 udp udp source 58845udp destination 1900udp length 140udp checksum 0x5154 20820 correctudp data payload offset42 0x2a length132 data 002a 4d 2d 53 45 41 52 43 48 20 2a 20 48 54 54 50 2f msearch http003a 31 2e 31 0d 0a 48 6f 73 74 3a 32 33 39 2e 32 35 11host23925004a 35 2e 32 35 35 2e 32 35 30 3a 31 39 30 30 0d 0a 52552501905a 53 54 3a 75 72 6e 3a 73 63 68 65 6d 61 73 2d 75 sturnschemasu006a 70 6e 70 2d 6f 72 67 3a 64 65 76 69 63 65 3a 57 pnporgdevicew007a 41 4e 43 6f 6e 6e 65 63 74 69 6f 6e 44 65 76 69 anconnectiondevi008a 63 65 3a 31 0d 0a 4d 61 6e 3a 22 73 73 64 70 3a ce1manssdp009a 64 69 73 63 6f 76 65 72 22 0d 0a 4d 58 3a 33 0d thiscovermx300aa 0a 0d 0a 00,['java'] +633842,are java 8 streams the same as net ienumerable at first i thought java streams were necessarily related to io but they look really like the ienumerable interface in net is that comparison fair,"['java', '.net']" +633881,phonegap resize webview on keyboard thisplay in android i have a modal similar with fixed positioning to what facebook has for the comments in feedchat in messenger in the latest android release what i want looks similar to thisso when you focus on the input the keyboard opens and shrinks the webview it is not working by default and i cannot find any solution i tried to add this preference to configxml but adjustresize is not doing anything and statevisible just opens the keyboard when i start the apreference nameandroidwindowsoftinputmode valuestatevisibleadjustresize which is weird as of the android documentation adjustresize should do this the activitys main window is always resized to make room for the soft keyboard on screeni am using phonegap 30 and i have a nexus 5 with kitkat for testing,"['javascript', 'jquery', 'css']" +633891,is there any way to expect output to error log in phpunit tests is there any way to run a test on output created from a call to error logmessage when doing unit tests with phpunitexample code one of my functions tests a credit card with a luhn algorithmifcheckluhn this luhn checkcardnumber false error log method cardnumber failed luhn algorithm check return falsecheckluhn is a boolean passed in to tell it whether to do the check the luhn check returns true if the cardnumber passes problem is i have more than one test in this function that can return false i can use assertequals on the return value but also want to check why the error was throwncan you override error log or otherwise grab syslog output in a unit test somehow,['php'] +633952,pandas left outer join multiple dataframes on multiple columns i am new to using dataframe and i would like to know how to perform a sql equivalent of left outer join on multiple columns on a series of tablesexampledf1 year week colour val1 2014 a red 502014 b red 602014 b black 702014 c red 102014 d green 20df2year week colour val22014 a black 302014 b black 1002014 c green 502014 c red 202014 d red 40df3year week colour val32013 b red 602013 c black 802013 b black 102013 d green 202013 d red 50 essentially i want to do something like this sql code notice that df3 is not joined on yearselect df1 df2val2 df3val3from df1 left outer join df2 on df1year df2year and df1week df2week and df1colour df2colour left outer join df3 on df1week df3week and df1colour df3colourthe result should look likeyear week colour val1 val2 val32014 a red 50 null null2014 b red 60 null 602014 b black 70 100 null2014 c red 10 20 null2014 d green 20 null nulli have tried using merge and join but cannot figure out how to do it on multiple tables and when there are multiple joints involved could someone help me on this pleasethanks,"['python', 'sql']" +633966,what is the official behavior for stdvector range constructor when the first itr comes after the last assuming you have a valid starting pointstdvectoruint32 host 12345when you try to construct another vector using iteratorsstdvectoruint32 clienthostbeginhostend clientsize is 5 elements begin end look just like hostbut what happens if the iterators are backwards what if the start is after the endstdvectoruint32 backwardsclienthostend hostbegin what happens,['c++'] +633990,how to pass along username and password to cassandra in python i am learning and just setup my cassandra cluster and trying to use python as the client to interact with it in the yaml i set the authenticator to be passwordauthenticatorso now i plan to provide my username and password over to the connect function but find no where to put themcluster clusterhostssession clusterconnectkeyspacebasically you provide only the host and the keyspace the documentation kind of suggest a connection with anonymous startedhtmlconnectingtocassandraif i just use the example i will get the following errorraise nohostavailableunable to connect to any servers errorscassandraclusternohostavailable unable to connect to any servers hou722067 authenticationfailedremote end requires authenticationis the authentication information supplied through some config files it seems like a very basic functionality and i cannot imagine it is not covered in the python client driver i must have miss somethingin short my question is how do i login to cassandra using pythonthanks in advance for any hint possiblegot it figuredi should provide the username and password in the auth provider field which is a function returning a dictionary containing ausernamea and apassworda keys with appropriate string valuessomething likedef getcredentialself host credential usernamemyuser passwordmypassword return credentialcluster clusternodes auth providergetcredential,['python'] +633994,ctfontmanagerregistergraphicsfont does not register the family name for reasons related to licensing i have to decrypt a font file and load it into memory then then register it instead of reading directly from a url for this i have to use ctfontmanagerregistergraphicsfontthe problematic part comes when i try to use nsfont fontwithnameopen sans size210 where it will only accept the fonts postscript name ie opensans or opensansbold for the bold weight and would not work the family name open sansif a font is registered using atsapplicationfontspathin the infoplist file or using ctfontmanagerregisterfontsforurls then i am able to use the fonts family name but i cannot do it this wayopen sans is used here as an exampleheres the relevant code i am using to register the fontnsstring fontpath nsbundle mainbundle pathforresourceopensansregular oftypettf indirectoryfontsnsdata fontdata nsdata datawithcontentsoffilefontpathcgdataproviderref fontproviderref cgdataprovidercreatewithcfdatacfdatareffontdatacgfontref fontref cgfontcreatewithdataproviderfontproviderrefcferrorref errorif ctfontmanagerregistergraphicsfontfontref error cfstringref errordescription cferrorcopydescriptionerror nslogfailed to load font errordescription cfreleaseerrordescriptioncfreleasefontrefcfreleasefontproviderrefis there a way to make the font family name available to nsfont with ctfontmanagerregistergraphicsfontusing xcode 5 and targeting mac os x 108,['objective-c'] +634051,determine mime type from nsdata how would you determine the mime type for an nsdata object i plan to have the user to upload a videopicture from their iphone and have that file be wrapped in a nsdata classi was wondering if i can tell the mime type from the nsdata there are only a few answers to this question and the most recent one is from 2010 4 years ago thanksnsdata data can be an image or videonsstring mimetype data getmimetype how would i implement getmimetype,"['ios', 'objective-c']" +634116,threadsafe vs synchronized i am new to javai am little bit confused between threadsafe and synchronizedthread safe means that a method or class instance can be used by multiple threads at the same time without any problems occurringwhere as synchronized means only one thread can operate at single timeso how they are related to each other,['java'] +634242,orghibernatehqlinternalastquerysyntaxexception is not mapped from team i am working on little spring mvc crud application got some strange problemsconfiguration classpackage sbkspringsimplejcconfigimport javautilpropertiesimport javaxannotationresourceimport javaxsqldatasourceimport orgspringframeworkcontextannotationbeanimport orgspringframeworkcontextannotationcomponentscanimport orgspringframeworkcontextannotationconfigurationimport orgspringframeworkcontextannotationimportimport orgspringframeworkcontextannotationpropertysourceimport orgspringframeworkcoreenvenvironmentimport orgspringframeworkjdbcdatasourcedrivermanagerdatasourceimport orgspringframeworkormhibernate4hibernatetransactionmanagerimport orgspringframeworkormhibernate4localsessionfactorybeanimport orgspringframeworktransactionannotationenabletransactionmanagementimport orgspringframeworkwebservletconfigannotationenablewebmvcimport orgspringframeworkwebservletconfigannotationresourcehandlerregistryimport orgspringframeworkwebservletconfigannotationwebmvcconfigureradapterimport orgspringframeworkwebservletviewjstlviewimport orgspringframeworkwebservletviewurlbasedviewresolverconfiguration specifies the class as configurationcomponentscansbkspringsimplejc specifies which package to scanimportdatabaseconfigclassenabletransactionmanagementpropertysourceclasspathapplicationpropertiesenablewebmvc enables to use springs annotations in the codepublic class webappconfig extends webmvcconfigureradapter private static final string property name database driver dbdriver private static final string property name database password dbpassword private static final string property name database url dburl private static final string property name database username dbusername private static final string property name hibernate dialect hibernatedialect private static final string property name hibernate show sql hibernateshow sql private static final string property name entitymanager packages to scan entitymanagerpackagestoscan resource private environment env bean public datasource datasource drivermanagerdatasource datasource new drivermanagerdatasource datasourcesetdriverclassnameenvgetrequiredpropertyproperty name database driver datasourceseturlenvgetrequiredpropertyproperty name database url datasourcesetusernameenvgetrequiredpropertyproperty name database username datasourcesetpasswordenvgetrequiredpropertyproperty name database password return datasource bean public localsessionfactorybean sessionfactory localsessionfactorybean sessionfactorybean new localsessionfactorybean sessionfactorybeansetdatasourcedatasource sessionfactorybeansetpackagestoscanenvgetrequiredpropertyproperty name entitymanager packages to scan sessionfactorybeansethibernatepropertieshibproperties return sessionfactorybean private properties hibproperties properties properties new properties propertiesputproperty name hibernate dialect envgetrequiredpropertyproperty name hibernate dialect propertiesputproperty name hibernate show sql envgetrequiredpropertyproperty name hibernate show sql return properties bean public hibernatetransactionmanager transactionmanager hibernatetransactionmanager transactionmanager new hibernatetransactionmanager transactionmanagersetsessionfactorysessionfactorygetobject return transactionmanager override public void addresourcehandlersresourcehandlerregistry registry registryaddresourcehandlerresourcesaddresourcelocationsresources bean public urlbasedviewresolver setupviewresolver urlbasedviewresolver resolver new urlbasedviewresolver resolversetprefixwebinfviews resolversetsuffixjsp resolversetviewclassjstlviewclass return resolver applicationpropertiesdb properties dbdrivercommicrosoftsqlserverjdbcsqlserverdriver dburljdbcsqlserver1270011433databasenameexamples dbusernamesadbpasswordhibernate configuration hibernatedialectorghibernatedialectsqlserverdialecthibernateshow sqltrue entitymanagerpackagestoscansbkspringsimplejcentity entity classpackage sbkspringsimplejcentity import javaxpersistenceentity import javaxpersistencegeneratedvalue import javaxpersistenceid import javaxpersistencetable entity tablenameteam public class team id generatedvalue private integer id private string name private integer rating public integer getid return id public void setidinteger id thisid id public string getname return name public void setnamestring name thisname name public integer getrating return rating public void setratinginteger rating thisrating rating controller classpackage sbkspringsimplejccontrollerimport orgspringframeworkbeansfactoryannotationautowiredimport orgspringframeworkstereotypecontrollerimport orgspringframeworkwebbindannotationrequestmappingimport orgspringframeworkwebservletmodelandviewimport sbkspringsimplejcserviceiteamservicecontrollerpublic class teamcontroller autowired iteamservice service requestmappingvalue public modelandview gotohellopage modelandview view new modelandview viewaddobjectteamlist servicelistteams return view error stack trace orghibernatehqlinternalastquerysyntaxexception team is not mapped from team orghibernatehqlinternalastutilsessionfactoryhelperrequireclasspersistersessionfactoryhelperjava180 orghibernatehqlinternalasttreefromelementfactoryaddfromelementfromelementfactoryjava110 orghibernatehqlinternalasttreefromclauseaddfromelementfromclausejava93 orghibernatehqlinternalasthqlsqlwalkercreatefromelementhqlsqlwalkerjava324 orghibernatehqlinternalantlrhqlsqlbasewalkerfromelementhqlsqlbasewalkerjava3420 orghibernatehqlinternalantlrhqlsqlbasewalkerfromelementlisthqlsqlbasewalkerjava3309 orghibernatehqlinternalantlrhqlsqlbasewalkerfromclausehqlsqlbasewalkerjava706 orghibernatehqlinternalantlrhqlsqlbasewalkerqueryhqlsqlbasewalkerjava562 orghibernatehqlinternalantlrhqlsqlbasewalkerselectstatementhqlsqlbasewalkerjava299 orghibernatehqlinternalantlrhqlsqlbasewalkerstatementhqlsqlbasewalkerjava247 orghibernatehqlinternalastquerytranslatorimplanalyzequerytranslatorimpljava248 orghibernatehqlinternalastquerytranslatorimpldocompilequerytranslatorimpljava183 orghibernatehqlinternalastquerytranslatorimplcompilequerytranslatorimpljava136 orghibernateenginequeryspihqlqueryplaninithqlqueryplanjava105 orghibernateenginequeryspihqlqueryplaninithqlqueryplanjava80 orghibernateenginequeryspiqueryplancachegethqlqueryplanqueryplancachejava168 orghibernateinternalabstractsessionimplgethqlqueryplanabstractsessionimpljava221 orghibernateinternalabstractsessionimplcreatequeryabstractsessionimpljava199 orghibernateinternalsessionimplcreatequerysessionimpljava17 sbkspringsimplejcdaohibteamdaolistteamshibteamdaojava23 sbkspringsimplejcserviceteamservicelistteamsteamservicejava27i have not got a clue about this issueupdatedao classpackage sbkspringsimplejcdao import javautillist import orghibernatesession import orghibernatesessionfactory import orgspringframeworkbeansfactoryannotationautowired import orgspringframeworkstereotyperepository import sbkspringsimplejcentityteam repository public class hibteamdao implements teamdao autowired private sessionfactory sessionfactory public void addteamteam team sessionfactorygetcurrentsessionsaveteam public void updateteamteam team sessionfactorygetcurrentsessionupdateteam suppresswarningsunchecked public listteam listteams return sessionfactorygetcurrentsessioncreatequeryfrom teamlist suppresswarningsunchecked public team getteambyidinteger teamid session session sessionfactorygetcurrentsession listteam listteam sessioncreatequeryfrom team t where tid teamid setparameterteamid teamid list return listteamsize 0 teamlistteamget0 null public void removeteaminteger teamid team team team sessionfactorygetcurrentsessionloadteamclass teamid ifteam null sessionfactorygetcurrentsessiondeleteteam override public integer count return integer sessionfactorygetcurrentsessioncreatequeryselect countt from team tuniqueresult teamcontroller classpackage sbkspringsimplejccontrollerimport orgspringframeworkbeansfactoryannotationautowiredimport orgspringframeworkstereotypecontrollerimport orgspringframeworkwebbindannotationrequestmappingimport orgspringframeworkwebservletmodelandviewimport sbkspringsimplejcserviceiteamservicecontrollerpublic class teamcontroller autowired iteamservice service requestmappingvalue public modelandview gotohellopage modelandview view new modelandview viewaddobjectteamlist servicelistteams return view updatenow i got rid from this problem by changing dao method from return sessionfactorygetcurrentsessioncreatequeryfrom teamlisttoreturn sessionfactorygetcurrentsessioncreatequeryfrom sbkspringsimplejcentityteamlistbut received another issue every query return null despite of existing rows in team tableupdatefinally i noticed warning messagesfeb 15 2014 70105 pm orghibernatehqlinternalquerysplitter concretequerieswarn h0183 no persistent classes found for query class from sbkspringsimplejcentityteamupdateat least i have sorted out this issue by adding next row of code in datasource bean definition in webappconfigpublic localsessionfactorybean sessionfactory localsessionfactorybean sessionfactorybean new localsessionfactorybean sessionfactorybeansetdatasourcedatasource sessionfactorybeansetannotatedclassesnew classteamclassnew row sessionfactorybeansetpackagestoscanenvgetrequiredpropertyproperty name entitymanager packages to scan sessionfactorybeansethibernatepropertieshibproperties return sessionfactorybean,['java'] +634311,how use mocha test framework with nodejs and sailsjs i want to use mocha for nodejs the last test framework i used was rspec from ruby on rails so i am trying to do it in the same way but i get cnfused by the huge framework and all the libraries i could usei am following the official get started but it does not explains how organize the testsnow i am reading that i can use the following libraries something to test model instances minimalistic bdd assertion toolkit based on shouldjs looks big includes should expect and another lib better cstyle assertions using callsite for selfdocumenting failure messages i actually do not understand the purpose so far looks not better than others looks to be used browser side but mocha also said that it is running browser sideand i know there are more this is just the list i saw on mocha official websitefor what i can understand it looks like chai is the one to use with mocha what do you think about thatand so far i never saw anything to help me to decide where write the tests okay in test of course and how organize everythingi am also use the great sailsjs framework based on express and pomelojs for different projects i need to use the same kind of tests on both frameworks so i am looking for a general architecture and libraries that i can use on both so something not specific to sailsjs but usable directly from any other frameworkthis is how i plan to organize my tests do you think that is a correct architecture the main issue with node is that there are a lot of frameworks plugins libraries and i dont know whats the best choice nodejs is really huge with a big community and that is really difficult to have an overview of all the possibilitieshow do you deal with your tests,['javascript'] +634328,python copy larger file too slow i am trying to copy a large file 1 gb from hard thisk to usb drive using shutilcopy a simple script depicting what i am trying to do isimport shutilsrc file sourcetolargefiledest destinationdirectoryshutilcopysrc file destit takes only 23 min on linux but the same file copy on same file takes more that 1015 min under windows can somebody explain why and give some solution preferably using python codeupdate 1 saved the file as testpysource file size is 1 gb destinantion directory is in usb drive calculated file copy time with ptime result is hereptimeexe testpyptime 10 for win32 freeware httpwcopyrightc 2002 jem berkes jberkespct testpy execution time 542479 s542479 s 9 min i do not think shutilcopy should take 9 min for copying 1 gb fileupdate 2 health of the usb is good as same script works well under linux calculated time with same file under windows native xcopyhere is the result ptime 10 for win32 freeware copyrightc 2002 jem berkes xcopy ftestiso lusbtestiso1 files copiedexecution time 128144 s128144 s 213 min i have 17 gb free space even after copying test file,['python'] +634369,start uicollectionview at bottom in ios 7 given a uicollectionview how do you start it at the bottom think about the ios messages app where when the view becomes visible it always starts at the bottom most recent message,['ios'] +634370,how do i convert this to an async task given the following codestatic void dosomethingint id threadsleep50 consolewritelinedidsomething0 idi know i can convert this to an async task as followsstatic async task dosomethingasyncint id await taskdelay50 consolewritelinedidsomethingasync0 idand that by doing so if i am calling multiple times taskwhenall everything will be faster and more efficient than perhaps using parallelforeach or even calling from within a loopbut for a minute lets pretend that taskdelay does not exist and i actually have to use threadsleep i know in reality this is not the case but this is concept code and where the delaysleep is would normally be an io operation where there is no async option such as early efi have tried the followingstatic async task dosomethingasync2int id await taskrun threadsleep50 consolewritelinedidsomethingasync0 id but though it runs without error according to lucien wischik this is in fact bad practice as it is merely spinning up threads from the pool to complete each task it is also slower using the following console application if you swap between dosomethingasync and dosomethingasync2 call you can see a significant difference in the time that it takes to completestatic void mainstring args mainasyncargswaitstatic async task mainasyncstring args listtask tasks new listtask for int i 1 i 10 i tasksadosomethingasync2i can replace with any version await taskwhenalltasksi then tried the followingstatic async task dosomethingasync3int id await new task threadsleep50 consolewritelinedidsomethingasync0 id transplanting this in place of the original dosomethingasync the test never completes and nothing is shown on screeni have also tried multiple other variations that either do not compile or do not completeso given the constraint that you cannot call any existing asynchronous methods and must complete both the threadsleep and the consolewriteline in an asynchronous task how do you do it in a manner that is as efficient as the original codethe objective here for those of you who are interested is to give me a better understanding of how to create my own async methods where i am not calling anybody elses despite many searches this seems to be the one area where examples are really lacking whilst there are many thousands of examples of calling async methods that call other async methods in turn i cannot find any that convert an existing void method to an async task where there is no call to a further async task other than those that use the taskrun method,"['c#', '.net']" +634375,when is locking necessary ok i know this may sound quite stupid and i am afraid it is but i am not completely satisfied with the answer i gave myself so i thought it was worth it asking it herei am dealing with an exercise about concurrency in java which goes like thisgiven a solved sudoku chart determine using a fixed number of threads running at the same time whether the chart has been correctly solved ie no violation of the canonical rules occur a number must appear within its row its column and its block only oncenow my question is since the threads only have to perform reads gathering infos from the chart and elaborating them somewhere else could not they work without worrying about concurrency charts state is always consistent since no writes are performed hence it is never changedare not lockssynchronized blockssynchronized methods necessary if and only if there is a risk for resources consistency to be lost in other words did i understand concurrency the right way,['java'] +634472,the best library for mapping core data as a developer i face with processing data each day the common thing that i need to process the raw data to the object nsmanagedobject so i am using afnetworking for getting data from the remote server and as a result of afnetworking work i have a data that can be represented by nsdictionary so the main thing that can take a lot of work it is converting this raw data to concrete data models so there are many libraries in the internet that can do this hard work for usmagicalrecord magicalimportmantleeasymappingso as a new in mapping i want to know which library is the best for my purposes maybe you can suggest another one as well,['ios'] +634480,why is the range object not an iterator i do understand iterators and iterables but clearly i just have a hole in my mental logic somewhere right now lack of coffee or somethingi wrote this and expected 0 x range20 nextxinstead i gottypeerror range object is not an iteratorbut i thought it was a generatorthe initial answer yielded the same thing i initially said to myself it is an iterable not an interator but then that wouldnt explain why this works if both are simply generators x i for i in range30 nextx0,['python'] +634497,pcm aac encoder pcmdecoder in realtime with correct optimization i am trying to implement audiorecord mic pcm aac encoderaac pcm decode audiotrack speakerwith mediacodec on android 41 api16firstly i successfully but not sure correctly optimized implemented pcm aac encoder by mediacodec as intended as belowprivate boolean setencoderint rate encoder mediacodeccreateencoderbytypeaudiomp4alatm mediaformat format new mediaformat formatsetstringmediaformatkey mime audiomp4alatm formatsetintegermediaformatkey channel count 1 formatsetintegermediaformatkey sample rate 44100 formatsetintegermediaformatkey bit rate 64 1024aache 64kbps formatsetintegermediaformatkey aac profile mediacodecinfocodecprofilelevelaacobjecthe encoderconfigureformat null null mediacodecconfigure flag encode return trueinput pcm bitrate 44100hz x 16bit x 1monoral 705600 bitsoutput aache bitrate 64 x 1024bit 65536 bitsso the data size is approximately compressed x11 and i confirmed this working by observing a logaudiorecoderi1 4096 bytes readaudioencoderi1 369 bytes encodedthe data size is approximately compressed x11 so far so goodnow i have a udp server to receive the encoded data then decode itthe decoder profile is set as followsprivate boolean setdecoderint rate decoder mediacodeccreatedecoderbytypeaudiomp4alatm mediaformat format new mediaformat formatsetstringmediaformatkey mime audiomp4alatm formatsetintegermediaformatkey channel count 1 formatsetintegermediaformatkey sample rate 44100 formatsetintegermediaformatkey bit rate 64 1024aache 64kbps formatsetintegermediaformatkey aac profile mediacodecinfocodecprofilelevelaacobjecthe decoderconfigureformat null null 0 return truesince udpserver packet buffer size is 1024udpserver i1 1024 bytes receivedand since this is the compressed aac data i would expect the decoding size will be approximately 1024 x11 however the actual result isaudiodecoderi1 8192 bytes decodedit is approximately x8 and i feel something wrongthe decoder code is as follows ioudpplayer new threadnew runnable public void run socketaddress sockaddress string address int len 1024 byte buffer2 new bytelen datagrampacket packet byte data bytebuffer inputbuffers bytebuffer outputbuffers bytebuffer inputbuffer bytebuffer outputbuffer mediacodecbufferinfo bufferinfo int inputbufferindex int outputbufferindex byte outdata try decoderstart isplaying true while isplaying try packet new datagrampacketbuffer2 len dsreceivepacket sockaddress packetgetsocketaddress address sockaddresstostring logdudp receiver received from address data new bytepacketgetlength systemarraycopypacketgetdata packetgetoffset data 0 packetgetlength logdudp receiver datalength bytes received inputbuffers decodergetinputbuffers outputbuffers decodergetoutputbuffers inputbufferindex decoderdequeueinputbuffer1 if inputbufferindex 0 inputbuffer inputbuffersinputbufferindex inputbufferclear inputbufferputdata decoderqueueinputbufferinputbufferindex 0 datalength 0 0 bufferinfo new mediacodecbufferinfo outputbufferindex decoderdequeueoutputbufferbufferinfo 0 while outputbufferindex 0 outputbuffer outputbuffersoutputbufferindex outputbufferpositionbufferinfooffset outputbufferlimitbufferinfooffset bufferinfosize outdata new bytebufferinfosize outputbuffergetoutdata logdaudiodecoder outdatalength bytes decoded decoderreleaseoutputbufferoutputbufferindex false outputbufferindex decoderdequeueoutputbufferbufferinfo 0 catch ioexception e decoderstop catch exception e the full codealso need permission usespermission androidnameandroidpermissioninternetusespermission usespermission androidnameandroidpermissionrecord audiousespermissiona member fadden who works for google told me looks like i am not setting position limit on the output buffer i have read vp8 encoding nexus 5 returns empty0frames but not sure how to implement correctlyupdate i sort of understood where to modify forlooks like i am not setting position limit on the output buffer so add 2 lines within the while loop of encoder and decoder as follows outputbufferpositionbufferinfooffset outputbufferlimitbufferinfooffset bufferinfosizehowever the result is the sameand now i think the errors wsoftaac2i1 aac decoder returned error 16388 substituting silence indicates this decoder fails completely from the first it is again the data is not seekable issue seeking in aac streams on android it is very thisappointing if the aac decoder cannot handle the streaming data in this way but only with adding some header update2 udp receiver did wrong so modifiednow the errorwsoftaac2i1 aac decoder returned error 16388 substituting silencethisappearedso it indicates the decoder works without an error at leasthowever this is the log of 1 cycledaudiorecoderi1 4096 bytes readdaudioencoderi1 360 bytes encodeddudp receiveri1 received from 127001390dudp receiveri1 360 bytes receiveddaudiodecoderi1 8192 bytes decodedpcm4096aacencoded360udpaac360supposed to be pcm8192the final result is about 2x size of the original pcm something is still wrongso my question here would becan you properly optimize my sample code to work correctlyis it a right way to use audiotrack api to play the decoded pcm raw data on the fly and can you show me the proper way to do that a example code is appreciatedthank youps my project targets on android41api16 i have read things are easier on api18andeoid 43 but for obvious compatibility reasons unfortunately i have to skip mediamuxer etc here,['android'] +634616,how to change tab name in browser when user goes off from my site so i am making a website and everything is nicely done but i do not know that many things with javascripti was searching for something that will help me with this and found some similar things but it does not work in my casethis is the problemideauser is on my site and the page name is eg hello tagthen the user clicks on the other tab in the browser but does not close my websitewhen that happens my page title changes to eg you went when he clicks on my tab again title changes back to default oneso if someone can help me with the code and explain it a little bitthank you,"['javascript', 'jquery', 'html']" +634679,how to create a global variable in android in my android application i need a place for putting the variable member id the problem is it is getting from the online api and i need to find a way to store retrieve it i have tried to put it in a custom class but the problem is it will lose if i kill the activity i have also know that there is a way to extends the applicationso i would like to know what is the best way to store global variablei have to implmentsave the variable on onsavestatesave it on shareprefsave it manuallyretrieve it manuallythanksupdate thanks for reply if i have just 3 variable simple data eg a boolean a phrase and i need it after app restart should i simply use share pref to store it what is the drawback of it eg will it harmful to the performance thanks,"['java', 'android']" +634715,splicing a javascript array from within the callback passed to foreach i have this code which is supposed to iterate over each item in an array removing items based on some conditioniterate over all items in an arrayif the item is b remove itvar array a b carrayforeachfunctionitem ifitem b arraysplicearrayindexofitem 1 consolelogitemdesired outputabcactual outputabobviously the native foreach method does not check after each iteration whether the item has been deleted so if it is then the next item is skipped is there a better way of doing this aside from overriding the foreach method or implementing my own class to use instead of an arrayedit further to my comment i suppose the solution is to just use a standard for loop feel free to answer if you have a better way,['javascript'] +634773,c to f functional thinking vs polymorphism suppose i had two classespublic class triangle public float base get set public float height get set public float calcarea return base height 20 public class cylinder public float radius get set public float height get set public float calcvolume return radius radius mathpi height we have here the descriptions of two geometric shapes along with an operation in bothand heres my attempt in ftype triangle base float height float module trianglestuff let calcarea t tbase theight 20type cylinder radius float height float module cylinderstuff let calcvolume c cradius cradius mathpi cheightsuppose i made an observation about these two classes they both have height and i wanted to extract an operation that made sense for anything that had a height property so in c i might pull out a base class and define the operation there as followspublic abstract class shapewithheight public float height get set public virtual bool cansupermanjumpover return height tall superman can only jump over tall buildings public const float tall floatmaxvaluepublic class triangle shapewithheight public float base get set public float calcarea return base height 20 public override bool cansupermanjumpover throw new invalidoperationexceptionsuperman can only jump over 3d objects public class cylinder shapewithheight public float radius get set public float calcvolume return radius radius mathpi height note how individual subclasses might have their own ideas as to the implementation of this operationcloser to the point i might have a function somewhere which can accept either a triangle or a cylinderpublic class superman public void jumpovershapewithheight shape try if shapecansupermanjumpover jump shape catch and this function can accept either a triangle or a cylinderi am having trouble applying the same line of thinking to fi have been doing some reading about functional languages the conventional thinking is that it is preferred to express algebraic value types rather than inherited classes the thinking goes that it is better to compose or build richer types out of smaller building blocks rather than starting with an abstract class and narrowing from therein f i want to be able to define a function which takes an argument that is known to have a height property and work with it somehow ie the base version of cansupermanjumpover how should i structure these types in a functional world to achieve it does my question even make sense in a functional world any comments on the thinking is most welcome,['c#'] +634891,wifidirect thiscoverservices keeps failing with error 3 no service requests i am using wifi p2p for network service thiscovery and i am following the instructions as outlined on the developer guide heres the relevant code in my service classpublic void oncreate manager wifip2pmanager getsystemservicecontextwifi p2p service channel managerinitializethis getmainlooper null registerp2pservice lookforservicesprivate void registerp2pservice wifip2pdnssdserviceinfo serviceinfo wifip2pdnssdserviceinfonewinstance servicename presence tcp new hashmapstring string manageraddlocalservicechannel serviceinfo new wifip2pmanageractionlistener override public void onsuccess logitag registered service override public void onfailureint arg0 logetag failed to register service private void setservicelisteners wifip2pdnssdservicerequest servicerequest wifip2pdnssdservicerequestnewinstance manageraddservicerequestchannel servicerequest new wifip2pmanageractionlistener override public void onsuccess logdscope added a service request thiscoverservices override public void onfailureint code logetag error adding service request public void thiscoverservices managerthiscoverserviceschannel new wifip2pmanageractionlistener override public void onsuccess logdtag service thiscovery was initiated override public void onfailureint code this is where it keeps failing with error code 3 no service requests logdscope service thiscovery failure code code the first time i run my service after rebooting the phone service thiscovery is initiated just fine but if i kill the service by stopping it from the app settings page then open it again it always fails with error code 3 if i reboot my phone and run the app again it works just fine i am confused because i am explicitly calling thiscoverservices only when the service request has been successfully addedmy hunch is that it may be due to some code that is unrelated to service thiscovery because the service thiscovery code seems extremely straightforward but if you see anything wrong with what i have posted let me know i am grasping at straws herei am running this on a nexus 5 with android 442,['android'] +634979,do not clip viewpager pages i cannot get my viewpager not clipping its pages contentsi am currently using viewpager with a fragmentstatepageradapter in my application i have 3 pages each page is showing a different fragmenteverything works fine but now i want to be able to draw outside of my pages bounds like in this imagei set clipchildren and cliptopadding to false in my all views parents to the views that needs to draw outside their bounds but heres what i get my views get clipped according to pages boundssome additional info in order to fix that issue i used hierarchyviewer to check my view hierarchy and see if some under the hood views could have a clipping behaviour and bingo each of my fragments root views is added under a nosavestateframelayout i suspect this guy to clip its childrenis my last assumption correct in your opinion how would you do to get unclipped pages,['android'] +634984,difference between uint8array and uint8clampedarray what is the difference between uint8array and uint8clampedarray in javascripti understand that uint8clampedarray is used with canvas for pixel manipulations why is that and what is the benefit,['javascript'] +635088,return the total rows affected by sql transaction i have the following code in sqlset xact abort onbegin transactioninsert into table a valuessome valuesinsert into table b valuessome valuesinsert into table c valuessome valuesupdate table set values a a where id id some thing like thatcommit transactionso i just wanted to know the total number of rows affected by in my transaction block of insert and updte statement,['sql'] +635119,open a popup containing aspx postback result i have an aspx page with many fields that generate pdf documents when i click an export to pdf buttoni would now like to have a print pdf button in javascript that does something like thisw windowopenwprintwclosewhere will perform the same postback as my export to pdf button,"['javascript', 'asp.net']" +635120,how to avoid the use of subjects in rx so i keep reading everywhere that use of subjectt is bad and i kind of agree with the reasoninghowever i am trying to this of the best way to avoid using it and have an examplecurrently i have an abstract class for my persisted configuration classes that has a protected save method on it which is called whenever changing a property should persist the class this message pumps a message onto a subjectt which is exposed through iobservablet interface which the serialisation services listens to and serialises the class this seemed the most obvious simple and quickest way to implement this at the timeso what would be the rx way to do this without using a subject would i instead expose an event and use observablefromeventpattern to subscribe to it as this seems a more complex way to go about it,['c#'] +635125,how to find javascript code that is waiting on promise we have a rather complex asynchronous system in javascript all functions in the javascript library are designed to be asynchronous we mainly use the angularjs deferred objects and some parts use the jquery we do not intermingle them though ie angular code waits on angular deferred promisesthe problem that we are coming across is that the code appears to hang on startup 2 out of 5 times there looks like there is a problem when the js code is cached and the timing of the promise resolutionsthere does not seem to be any tools or anything that can point to what the offending code is waiting on when a hang occurshow do you find javascript code that is waiting on a promisethanks,"['javascript', 'jquery']" +635184,selectedvalues not working in multiselectlist mvc i have a class like public class category public int id get set public string name get set public icollectioncategory categoryselected get set public static listcategory getoptions var categories new listcategory categoriesaddnew category id 1 name bikes categoriesaddnew category id 2 name cars categoriesaddnew category id 3 name trucks return categories in the controller i fill miltiselectitems and set selectedvalues for it public actionresult index category catnew category catcategoryselectedaddnew category id 1 name bikes catcategoryselectedaddnew category id 3 name trucks var list categorygetoptions productcategories new multiselectlistlist id name categoryselected in view code i havehtmllistboxcategory modelcategorieswhen run my action selectedvalues are not working what i am doing wrong,"['c#', 'asp.net']" +635203,deadobjectexception on android app sometimes i start an activity of my app or switch fast between fragments of a viewpager which is in that specific activity i got deadobjectexception like thiswactivitymanager 669 androidosdeadobjectexceptionwactivitymanager 669 at androidosbinderproxytransactnative methodwactivitymanager 669 at androidappapplicationthreadproxyschedulepauseactivityapplicationthreadnativejava660wactivitymanager 669 at comandroidserveramactivitystackstartpausinglockedactivitystackjava776wactivitymanager 669 at comandroidserveramactivitystackfinishactivitylockedactivitystackjava2501wactivitymanager 669 at comandroidserveramactivitystackfinishtoprunningactivitylockedactivitystackjava2375wactivitymanager 669 at comandroidserveramactivitystacksupervisorfinishtoprunningactivitylockedactivitystacksupervisorjava2040wactivitymanager 669 at comandroidserveramactivitymanagerservicehandleappcrashlockedactivitymanagerservicejava9667wactivitymanager 669 at comandroidserveramactivitymanagerservicemakeappcrashinglockedactivitymanagerservicejava9560wactivitymanager 669 at comandroidserveramactivitymanagerservicecrashapplicationactivitymanagerservicejava10205wactivitymanager 669 at comandroidserveramactivitymanagerservicehandleapplicationcrashinneractivitymanagerservicejava9756wactivitymanager 669 at comandroidserveramnativecrashlistenernativecrashreporterrunnativecrashlistenerjava86and app crashes i also got some unusual logs like thisflibc 24088 fatal signal 11 sigsegv at 0x020 code1 thread 24115 thread1047idebug 23974 idebug 23974 build fingerprint googleoccammako442kot49h937116userreleasekeysidebug 23974 revision 11idebug 23974 pid 24088 tid 24115 name thread1047 comsomthingblah idebug 23974 signal 11 sigsegv code 1 segv maperr fault addr 020idebug 23974 r0 77205ca0 r1 020 r2 77205ca0 r3 0idebug 23974 r4 77205ca0 r5 756f7f40 r6 0 r7 75711d4cidebug 23974 r8 75e5db10 r9 75711d44 sl 756f7f50 fp 75e5db24idebug 23974 ip 733efb10 sp 75e5db00 lr 40a4fc3f pc 020 cpsr 400b0010idebug 23974 d0 0 d1 0idebug 23974 d2 0 d3 0idebug 23974 d4 0f0f0 d5 050f0idebug 23974 d6 05050 d7 05050idebug 23974 d8 0 d9 0idebug 23974 d10 0 d11 0idebug 23974 d12 0 d13 0idebug 23974 d14 0 d15 0idebug 23974 d16 3ea086314bf691da d17 eddf2c9e110286d5idebug 23974 d18 006500670022005b d19 0074006100430074idebug 23974 d20 0067006f006c0061 d21 002c002200650075idebug 23974 d22 0022002c00220022 d23 002c002200610066idebug 23974 d24 40 d25 547d42aea2879f2eidebug 23974 d26 40f86a0 d27 3ff0idebug 23974 d28 40f86a0 d29 01idebug 23974 d30 40240 d31 40idebug 23974 scr 6010idebug 23974 idebug 23974 backtraceidebug 23974 00 pc 020 unknownidebug 23974 01 pc 079c3d systemliblibcryptoso evp md ctx cleanup28idebug 23974 02 pc 079e15 systemliblibcryptoso evp md ctx destroy4idebug 23974 03 pc 01ea50 systemliblibdvmso dvmplatforminvoke116idebug 23974 04 pc 04f65f systemliblibdvmso dvmcalljnimethodunsigned int const jvalue method const thread398idebug 23974 05 pc 027ee0 systemliblibdvmsoidebug 23974 06 pc 02f3d8 systemliblibdvmso dvmmterpstdthread76idebug 23974 07 pc 02ca7c systemliblibdvmso dvminterpretthread method const jvalue184idebug 23974 08 pc 061adb systemliblibdvmso dvmcallmethodvthread method const object bool jvalue std va list338idebug 23974 09 pc 061aff systemliblibdvmso dvmcallmethodthread method const object jvalue 20idebug 23974 10 pc 0567eb systemliblibdvmsoidebug 23974 11 pc 0d190 systemliblibcso thread entry72idebug 23974 12 pc 0d328 systemliblibcso pthread create240idebug 23974 idebug 23974 stackidebug 23974 75e5dac0 1e805 idebug 23974 75e5dac4 41586719 systemliblibdvmsoidebug 23974 75e5dac8 759674f0 anonlibc mallocidebug 23974 75e5dacc 756f7f40 anonlibc mallocidebug 23974 75e5dad0 415866f5 systemliblibdvmsoidebug 23974 75e5dad4 733e41db systemliblibjavacryptosoidebug 23974 75e5dad8 75e5daec stack24115idebug 23974 75e5dadc 733e5e09 systemliblibjavacryptosoidebug 23974 75e5dae0 014 idebug 23974 75e5dae4 733e601d systemliblibjavacryptosoidebug 23974 75e5dae8 014 idebug 23974 75e5daec 759674f0 anonlibc mallocidebug 23974 75e5daf0 1e805 idebug 23974 75e5daf4 41e25968 devashmemdalvikheap deletedidebug 23974 75e5daf8 417a2298 devashmemdalvikzygote deletedidebug 23974 75e5dafc 756f7f40 anonlibc mallocidebug 23974 00 75e5db00 77205ca0 anonlibc mallocidebug 23974 idebug 23974 01 75e5db00 77205ca0 anonlibc mallocidebug 23974 75e5db04 40a4fe19 systemliblibcryptoso evp md ctx destroy8idebug 23974 02 75e5db08 6d7897b0 devashmemdalviklinearalloc deletedidebug 23974 75e5db0c 41558a54 systemliblibdvmso dvmplatforminvoke120idebug 23974 idebug 23974 memory near r0idebug 23974 77205c80 77199488 771a3118 771a31f0 771a31f0 idebug 23974 77205c90 01b 3f80 0 023 idebug 23974 77205ca0 775a10 020 020 0 idebug 23974 77205cb0 01 0 020 023 idebug 23974 77205cc0 730dbd0c 72fa1cee 03d4 72a82591 idebug 23974 77205cd0 75752d68 01 0 01b idebug 23974 77205ce0 732d5098 75718fa0 77176e18 75735358 idebug 23974 77205cf0 0 01b 73268c08 01 idebug 23974 77205d00 729967b9 73340f20 018 023 idebug 23974 77205d10 730db385 72f9b871 047 72a2cdbb idebug 23974 77205d20 75752d68 02 746e6f63 013 idebug 23974 77205d30 732675e0 02 721fc331 04b idebug 23974 77205d40 73268780 732687d4 02 77205d88 idebug 23974 77205d50 77176e18 77205d30 721fc0a5 0 idebug 23974 77205d60 0 0 0 0 idebug 23974 77205d70 0 77205d98 77205d40 771f2ad8 idebug 23974 idebug 23974 memory near r2idebug 23974 77205c80 77199488 771a3118 771a31f0 771a31f0 idebug 23974 77205c90 01b 3f80 0 023 idebug 23974 77205ca0 775a10 020 020 0 idebug 23974 77205cb0 01 0 020 023 idebug 23974 77205cc0 730dbd0c 72fa1cee 03d4 72a82591 idebug 23974 77205cd0 75752d68 01 0 01b idebug 23974 77205ce0 732d5098 75718fa0 77176e18 75735358 idebug 23974 77205cf0 0 01b 73268c08 01 idebug 23974 77205d00 729967b9 73340f20 018 023 idebug 23974 77205d10 730db385 72f9b871 047 72a2cdbb idebug 23974 77205d20 75752d68 02 746e6f63 013 idebug 23974 77205d30 732675e0 02 721fc331 04b idebug 23974 77205d40 73268780 732687d4 02 77205d88 idebug 23974 77205d50 77176e18 77205d30 721fc0a5 0 idebug 23974 77205d60 0 0 0 0 idebug 23974 77205d70 0 77205d98 77205d40 771f2ad8 idebug 23974 idebug 23974 memory near r4idebug 23974 77205c80 77199488 771a3118 771a31f0 771a31f0 idebug 23974 77205c90 01b 3f80 0 023 idebug 23974 77205ca0 775a10 020 020 0 idebug 23974 77205cb0 01 0 020 023 idebug 23974 77205cc0 730dbd0c 72fa1cee 03d4 72a82591 idebug 23974 77205cd0 75752d68 01 0 01b idebug 23974 77205ce0 732d5098 75718fa0 77176e18 75735358 idebug 23974 77205cf0 0 01b 73268c08 01 idebug 23974 77205d00 729967b9 73340f20 018 023 idebug 23974 77205d10 730db385 72f9b871 047 72a2cdbb idebug 23974 77205d20 75752d68 02 746e6f63 013 idebug 23974 77205d30 732675e0 02 721fc331 04b idebug 23974 77205d40 73268780 732687d4 02 77205d88 idebug 23974 77205d50 77176e18 77205d30 721fc0a5 0 idebug 23974 77205d60 0 0 0 0 idebug 23974 77205d70 0 77205d98 77205d40 771f2ad8 idebug 23974 idebug 23974 memory near r5idebug 23974 756f7f20 d1d1d1d1 d1d1d1d1 d1d1d1d1 d1d1d1d1 idebug 23974 756f7f30 d1d1d1d1 d1d1d1d1 08 045b idebug 23974 756f7f40 6e9093d8 75711d44 6d78c6a8 6e9cf0 idebug 23974 756f7f50 014 07 75e5dc40 0 idebug 23974 756f7f60 75e5dc94 013 0 41558bc0 idebug 23974 756f7f70 0 0 6c870270 7570e300 idebug 23974 756f7f80 0 0 01 040 idebug 23974 756f7f90 0 756f8398 41558bc0 4155db00 idebug 23974 756f7fa0 0 41561bfc 41561c70 41561b20 idebug 23974 756f7fb0 41561b40 41561b9c 0 0 idebug 23974 756f7fc0 7716efc0 028 0 0 idebug 23974 756f7fd0 0 06 020 415ec9fc idebug 23974 756f7fe0 0 0 01 75712008 idebug 23974 756f7ff0 01 040 0200 0 idebug 23974 756f80 03 6e5c7fe8 6e5c7fe8 06 idebug 23974 756f8010 6e5c8002 6d7bdb10 4506b31a 95582e61 idebug 23974 idebug 23974 memory near r7idebug 23974 75711d2c 0 75711d60 6e909384 6d7897b0 idebug 23974 75711d3c 0 0 77205ca0 0 idebug 23974 75711d4c 75711d88 6e909484 6d78c6a8 6e909384 idebug 23974 75711d5c 0 77205ca0 0 0 idebug 23974 75711d6c 0 4193b628 75711da0 6e90ac6a idebug 23974 75711d7c 6d78c838 6e909484 0 4193b628 idebug 23974 75711d8c 75711de8 6e90af7e 6d8119b0 6e90ac6a idebug 23974 75711d9c 0 41db28e0 0 41db28b8 idebug 23974 75711dac 41db2890 4193b628 6d4b7c58 0 idebug 23974 75711dbc 0 4193b740 41cbcf10 014 idebug 23974 75711dcc 06b 014 75711e2c 6e90b0a8 idebug 23974 75711ddc 6d811a28 6e90af7e 0 41cbcf10 idebug 23974 75711dec 07f 41ebe038 41e4a630 014 idebug 23974 75711dfc 06b 014 0 4193b740 idebug 23974 75711e0c 4188c5d0 0 010 75711e54 idebug 23974 75711e1c 6e9276f8 6d811b40 6e90b0a8 0 idebug 23974 idebug 23974 memory near r8idebug 23974 75e5daf0 1e805 41e25968 417a2298 756f7f40 idebug 23974 75e5db00 77205ca0 40a4fe19 6d7897b0 41558a54 idebug 23974 75e5db10 75711d44 01 08 417a2298 idebug 23974 75e5db20 06b 41589663 75711d44 6e84fe63 idebug 23974 75e5db30 733e3f5f 756f7f50 415ec2c8 0 idebug 23974 75e5db40 1f401 0 003b4c00 4012c384 idebug 23974 75e5db50 41539328 415ae7d9 0 415e7c6c idebug 23974 75e5db60 4012c384 014 415ec2c8 4012c384 idebug 23974 75e5db70 014 415650f4 01 01 idebug 23974 75e5db80 6d4aa940 6e842b54 01 6e967224 idebug 23974 75e5db90 01 417a2298 03c 01 idebug 23974 75e5dba0 6d7897b0 6e965758 75e5dbf4 038 idebug 23974 75e5dbb0 01 415a7433 6e965758 6e8da484 idebug 23974 75e5dbc0 417a2298 6e965758 6e9cf0 014b9 idebug 23974 75e5dbd0 02 4012c384 6d4aad10 415a789b idebug 23974 75e5dbe0 75e5dbf4 6e965758 75e5dbf4 415a7e91 idebug 23974 idebug 23974 memory near r9idebug 23974 75711d24 6e909484 6d78c6a8 0 75711d60 idebug 23974 75711d34 6e909384 6d7897b0 0 0 idebug 23974 75711d44 77205ca0 0 75711d88 6e909484 idebug 23974 75711d54 6d78c6a8 6e909384 0 77205ca0 idebug 23974 75711d64 0 0 0 4193b628 idebug 23974 75711d74 75711da0 6e90ac6a 6d78c838 6e909484 idebug 23974 75711d84 0 4193b628 75711de8 6e90af7e idebug 23974 75711d94 6d8119b0 6e90ac6a 0 41db28e0 idebug 23974 75711da4 0 41db28b8 41db2890 4193b628 idebug 23974 75711db4 6d4b7c58 0 0 4193b740 idebug 23974 75711dc4 41cbcf10 014 06b 014 idebug 23974 75711dd4 75711e2c 6e90b0a8 6d811a28 6e90af7e idebug 23974 75711de4 0 41cbcf10 07f 41ebe038 idebug 23974 75711df4 41e4a630 014 06b 014 idebug 23974 75711e04 0 4193b740 4188c5d0 0 idebug 23974 75711e14 010 75711e54 6e9276f8 6d811b40 idebug 23974 idebug 23974 memory near slidebug 23974 756f7f30 d1d1d1d1 d1d1d1d1 08 045b idebug 23974 756f7f40 6e9093d8 75711d44 6d78c6a8 6e9cf0 idebug 23974 756f7f50 014 07 75e5dc40 0 idebug 23974 756f7f60 75e5dc94 013 0 41558bc0 idebug 23974 756f7f70 0 0 6c870270 7570e300 idebug 23974 756f7f80 0 0 01 040 idebug 23974 756f7f90 0 756f8398 41558bc0 4155db00 idebug 23974 756f7fa0 0 41561bfc 41561c70 41561b20 idebug 23974 756f7fb0 41561b40 41561b9c 0 0 idebug 23974 756f7fc0 7716efc0 028 0 0 idebug 23974 756f7fd0 0 06 020 415ec9fc idebug 23974 756f7fe0 0 0 01 75712008 idebug 23974 756f7ff0 01 040 0200 0 idebug 23974 756f80 03 6e5c7fe8 6e5c7fe8 06 idebug 23974 756f8010 6e5c8002 6d7bdb10 4506b31a 95582e61 idebug 23974 756f8020 f7d042ed f7d041e7 4506b31e 88a0767c idebug 23974 idebug 23974 memory near fpidebug 23974 75e5db04 40a4fe19 6d7897b0 41558a54 75711d44 idebug 23974 75e5db14 01 08 417a2298 06b idebug 23974 75e5db24 41589663 75711d44 6e84fe63 733e3f5f idebug 23974 75e5db34 756f7f50 415ec2c8 0 1f401 idebug 23974 75e5db44 0 003b4c00 4012c384 41539328 idebug 23974 75e5db54 415ae7d9 0 415e7c6c 4012c384 idebug 23974 75e5db64 014 415ec2c8 4012c384 014 idebug 23974 75e5db74 415650f4 01 01 6d4aa940 idebug 23974 75e5db84 6e842b54 01 6e967224 01 idebug 23974 75e5db94 417a2298 03c 01 6d7897b0 idebug 23974 75e5dba4 6e965758 75e5dbf4 038 01 idebug 23974 75e5dbb4 415a7433 6e965758 6e8da484 417a2298 idebug 23974 75e5dbc4 6e965758 6e9cf0 014b9 02 idebug 23974 75e5dbd4 4012c384 6d4aad10 415a789b 75e5dbf4 idebug 23974 75e5dbe4 6e965758 75e5dbf4 415a7e91 014 idebug 23974 75e5dbf4 6d4aad10 02d8 415a4663 0 idebug 23974 idebug 23974 memory near ipidebug 23974 733efaf0 40109e65 400f23ed 400fe298 40a33ab5 idebug 23974 733efb00 40109919 40a0f431 40a84dc5 40a54e75 idebug 23974 733efb10 40a4fe11 40a4f9e5 40a13a8d 40a4612d idebug 23974 733efb20 40a45dd1 40a46b25 40a3ee65 40a4a10d idebug 23974 733efb30 400f0fd5 40ae8e7d 400ec7d8 400ec8d0 idebug 23974 733efb40 40a5d3d5 40ae86fd 40139927 400da559 idebug 23974 733efb50 402ca5b5 40a52491 40a4aded 40a4ac61 idebug 23974 733efb60 40a4ac01 40a4b169 40a4d1f9 401034a5 idebug 23974 733efb70 40a4d1d9 40a4d2bd 400ebc19 400f13ad idebug 23974 733efb80 400efecd 402ca6f5 40ae8ef9 40aebdb1 idebug 23974 733efb90 40a84cd5 40a1d4b9 40a1d5a1 40a84d1d idebug 23974 733efba0 40a2071d 40a16991 40a191a1 40a84475 idebug 23974 733efbb0 40a78135 40a1f189 40a229b1 40a52dc1 idebug 23974 733efbc0 40a22a55 40a128b5 40a53405 40a43345 idebug 23974 733efbd0 40a43695 40a42ec5 40a430c9 40a434e1 idebug 23974 733efbe0 40a42e4d 40a432dd 40a5d279 40a432e9 idebug 23974 idebug 23974 memory near spidebug 23974 75e5dae0 014 733e601d 014 759674f0 idebug 23974 75e5daf0 1e805 41e25968 417a2298 756f7f40 idebug 23974 75e5db00 77205ca0 40a4fe19 6d7897b0 41558a54 idebug 23974 75e5db10 75711d44 01 08 417a2298 idebug 23974 75e5db20 06b 41589663 75711d44 6e84fe63 idebug 23974 75e5db30 733e3f5f 756f7f50 415ec2c8 0 idebug 23974 75e5db40 1f401 0 003b4c00 4012c384 idebug 23974 75e5db50 41539328 415ae7d9 0 415e7c6c idebug 23974 75e5db60 4012c384 014 415ec2c8 4012c384 idebug 23974 75e5db70 014 415650f4 01 01 idebug 23974 75e5db80 6d4aa940 6e842b54 01 6e967224 idebug 23974 75e5db90 01 417a2298 03c 01 idebug 23974 75e5dba0 6d7897b0 6e965758 75e5dbf4 038 idebug 23974 75e5dbb0 01 415a7433 6e965758 6e8da484 idebug 23974 75e5dbc0 417a2298 6e965758 6e9cf0 014b9 idebug 23974 75e5dbd0 02 4012c384 6d4aad10 415a789b idebug 23974 idebug 23974 code around pcidebug 23974 0 f f f f idebug 23974 010 f f f f idebug 23974 020 f f f f idebug 23974 030 f f f f idebug 23974 040 f f f f idebug 23974 050 f f f f idebug 23974 060 f f f f idebug 23974 070 f f f f idebug 23974 080 f f f f idebug 23974 090 f f f f idebug 23974 0a0 f f f f idebug 23974 0b0 f f f f idebug 23974 0c0 f f f f idebug 23974 0d0 f f f f idebug 23974 0e0 f f f f idebug 23974 0f0 f f f f idebug 23974 idebug 23974 code around lridebug 23974 40a4fc1c 06a292 4604b510 b1e86820 b1406a00 idebug 23974 40a4fc2c 21024620 fc14f003 6820b918 46206a01 idebug 23974 40a4fc3c 68204788 6c40b180 68e0b170 4620b160 idebug 23974 40a4fc4c f0032104 b938fc05 68e06821 f00a6c49 idebug 23974 40a4fc5c 68e0f81b ffc2f009 b1086920 fac0f006 idebug 23974 40a4fc6c b1086860 f6f7fa 462120 0f10f841 idebug 23974 40a4fc7c 0050efc0 20016048 0a8ff944 bf00bd10 idebug 23974 40a4fc8c 4800e92d 0050efc0 46032200 2f10f843 idebug 23974 40a4fc9c f940605a f0a8f e8bdf803 bf008800 idebug 23974 40a4fcac 48f0e92d 460db082 b3254604 29006829 idebug 23974 40a4fcbc 6868d021 f7fab118 b360ff9d 68206829 idebug 23974 40a4fc 42882600 4620d104 68e62104 fbb6f003 idebug 23974 40a4fcdc f7ff4620 edd5ff9f f9650b04 edc42a8f idebug 23974 40a4fcec f9440b04 68e82a8f 6821b388 b3706c48 idebug 23974 40a4fcfc 60e6b1e6 f44fe026 48257194 226f9100 idebug 23974 40a4fd0c 44794927 20061843 f7fd216e 20f8b7 most of the time i also got these errors afterwardswbinder 899 caught a runtimeexception from the binder stub implementationwbinder 899 javalangnullpointerexceptionwbinder 899 at androidinputmethodserviceiinputmethodwrappersetsessionenablediinputmethodwrapperjava280wbinder 899 at comandroidinternalviewiinputmethodstubontransactiinputmethodjava129wbinder 899 at androidosbinderexectransactbinderjava404wbinder 899 at dalviksystemnativestartrunnative methodwinputmethodmanagerservice 652 got remoteexception sending setactivefalse notification to pid 14221 uid 10105each fragment of the aforementioned viewpager loads data from net and shows them i am using volley as request manager one more detail i am using fragmentstatepageradapter in that viewpager what does it mean what did i do wrong,"['java', 'android']" +635204,using python weakset to enable a callback functionality i am investigating if i can implement an easy callback functionality in python i thought i might be able to use weakrefweakset for this but there is clearly something i am missing or have misunderstood as you can see in the code i first tried with a list of call back methods in classa objects but realized that this would keep objects that have been added to the list of callbacks alive instead i tried using weakrefweakset but that doesnt do the trick either at least not en this way comments in the last four lines of code explain what i want to happencan anyone help me with thisfrom weakref import weaksetclass classa def init self selfdestroycallback selfdestroycallbackweakset def del self printclassa object d is being destroyed idself for f in selfdestroycallback fselfclass classb def destroyedobjectlistenerselfobj printclassb object d is called because obj d is being destroyedidselfidobja1classaa2classabclassba1destroycallbackaddbdestroyedobjectlistenera1destroycallbackappendbdestroyedobjectlistenerprintdestroycallback len of obj d is dida1lena1destroycallback should be 1a2destroycallbackaddbdestroyedobjectlistenera2destroycallbackappendbdestroyedobjectlistenerprintdestroycallback len of obj d is dida2lena2destroycallback should be 1del a1 should call bdestroyedobjectlistenerself in its del methoddel b should result in no strong refs to b so a2s weakset should automatically remove added itemprintdestroycallback len of obj d is dida2lena2destroycallback should be 0del a2 should call del methodupdate solution based on the accepted answer can be found on github thgispythoneventgit,['python'] +635372,kernel requirerb55in require cannot load such file error i am using ruby version 193 at the moment although i get the same issue with ruby 200 on windows 7 64bit i am following the cucumber book and got stuck at the chapter 72 removing duplication with transforms my folder structure is as followscash withdrawalcash withdrawalgemfilecash withdrawalgemfilelockcash withdrawalfeaturescash withdrawalfeaturescashwithdrawalfeaturecash withdrawalfeaturesstep definitionscash withdrawalfeaturesstep definitionscash withdrawal stepsrbcash withdrawalfeaturesstep definitionslibcash withdrawalfeaturesstep definitionslibnice bankrbcash withdrawalfeaturessupportcash withdrawalfeaturessupportenvrbcash withdrawalfeaturessupporttransformsrbcash withdrawalfeaturessupportworld extensionsrbin my cash withdrawal stepsrb file i haverequire capture cash amountgiven i have deposited capture cash amount in my account do amount my accountdepositamount my accountbalanceshould eqamount expected the balance to be amount but it was my accountbalanceendwhen i run cucumber i getcusersnikitaharrisonautomatedtestingcash withdrawalcucumber cannot load such file capture cash amount loaderror cruby193librubysite ruby191rubygemscore extkernel requirerb55in r equire cruby193librubysite ruby191rubygemscore extkernel requirerb55in r equire cusersnikitaharrisonautomatedtestingcash withdrawalfeaturesstep definiti onscash withdrawal stepsrb1in top required cruby193librubygems191gemscucumber1310libcucumberrb supportrb l anguagerb122inload cruby193librubygems191gemscucumber1310libcucumberrb supportrb l anguagerb122in load code file cruby193librubygems191gemscucumber1310libcucumberruntimesupport coderb180inload file cruby193librubygems191gemscucumber1310libcucumberruntimesupport coderb83in block in load files cruby193librubygems191gemscucumber1310libcucumberruntimesupport coderb82ineach cruby193librubygems191gemscucumber1310libcucumberruntimesupport coderb82in load files cruby193librubygems191gemscucumber1310libcucumberruntimerb184 inload step definitions cruby193librubygems191gemscucumber1310libcucumberruntimerb42i and run cruby193librubygems191gemscucumber1310libcucumberclimainrb47 inexecute cruby193librubygems191gemscucumber1310bincucumber13in top re quired cruby193bincucumber23inload cruby193bincucumber23in and if i run irb then run require capture cash amount i get this errorirbmain0060 require capture cash amount loaderror cannot load such file capture cash amount from cruby193librubysite ruby191rubygemscore extkernel requir erb55in require from cruby193librubysite ruby191rubygemscore extkernel requir erb55inrequire from irb6 from cruby193binirb12in i have tried many fixes including require relative and nothing seems to solve my problemif i remove require capture cash amount from the cash withdrawal stepsrb file and run cucumber then my step definition does not show as definedcusersnikitaharrisonautomatedtestingcash withdrawalcucumberfeature cash withdrawal test scenario successful withdrawal from an account in credit featurescash with drawalfeature4 given i have deposited 100 in my account featurescash with drawalfeature5 when i withdraw 20 featuresstep defi nitionscash withdrawal stepsrb7 then 20 should be thispensed featuresstep defi nitionscash withdrawal stepsrb11 and the balance of my account should be 80 featuresstep defi nitionscash withdrawal stepsrb15 1 scenario 1 undefined 4 steps 3 skipped 1 undefined 0m06s you can implement step definitions for undefined steps with these snippets giveni have deposited d in my account do arg1 pending express the regexp above with the code you wish you had endif i add require filejoinfiledirnamecusersnikitaharrisonautomatedtestingcash withdrawalfeaturessupport support transforms to the envrb file and run cucumber i get cusersnikitaharrisonautomatedtestingcash withdrawalfeaturessupporttrans formsrb1 warning already initialized constant capture cash amount feature cash withdrawal test scenario successful withdrawal from an account in credit featurescash with drawalfeature4 given i have deposited 100 in my account featurescash with drawalfeature5 when i withdraw 20 featuresstep defi nitionscash withdrawal stepsrb7 then 20 should be thispensed featuresstep defi nitionscash withdrawal stepsrb11 and the balance of my account should be 80 featuresstep defi nitionscash withdrawal stepsrb15 1 scenario 1 undefined 4 steps 3 skipped 1 undefined 0m0013s you can implement step definitions for undefined steps with these snippets giveni have deposited d in my account do arg1 pending express the regexp above with the code you wish you had endi know i must be doing something wrong here but i just cannot find out what and need help gemfile contents this gemfile lists all gems used throughout the book with versionssource rubygems build stuffgem bundler 153gem rake 1011gem watchr 07gem bcat 062 general stuffgem aruba 0411gem cucumber 1310 require cucumbergem rake 1011gem rspec 2141 require cucumbergem rspecexpectations 2145gem watirwebdriver 067i think i have included all the information that is needed,['ruby'] +635394,select whole column content in pgadmin i use posgresql as database and pgadmin as tool to manage it when i write simple selectcol is type of text and value of it is quite long about 4k charsselect col from tabi get this there is about 250 chars before bracketsababababababut i inserted longer value pgadmin trim showed value and ends it with string how can i get whole content inside pgadmin,['sql'] +635455,mp4 video rotation metadata i have developed an androidios video sharing app that records a video and uploads it to amazon s3 for compatibility both androidios record in mp4 format with h264aac codecs the users might shoot portrait or landscape and the app getting info from the sensors set the rotation of the file mediarecordersetorientationhint on android and something similar on iosthe videos from ios play fine on android and vice versa the problem is when i want to play a video on a web browser the browsers that support mp4 format ie chrome thisplay the video but ignore the rotation metadata the same thing happens when i playback those videos with mplayer on linuxthe first solution that comes to mind isffmpeg i inmp4 vf transposerotation value outmp4is there a reason why browsers ignore rotation metadata is it a bug could i do something to fix this while recording the videohere are 2 sample from ios and android respectivelythanskios videoandroid video,"['android', 'ios']" +635569,android buttonimage shake animation i am new with android and im looking for a way to shake my buttonimage on click i got this so far but it crashes all the time or if you click it nothing worksi hope you people can help me out if i forgot anythiing just say it code can be messyi got a anim folder with shakeanimxmlcodeactivity mainxmlrelativelayout xmlnsandroid xmlnstools androidlayout widthmatch parent androidlayout heightmatch parent androidpaddingbottomdimenactivity vertical margin androidpaddingleftdimenactivity horizontal margin androidpaddingrightdimenactivity horizontal margin androidpaddingtopdimenactivity vertical margin toolscontextmainactivity imagebutton androidididimagebutton1 androidlayout widthwrap content androidlayout heightwrap content androidlayout centerhorizontaltrue androidlayout centerverticaltrue androidsrcdrawablechest androidbackgroundnull textview androidididtextview1 androidlayout widthwrap content androidlayout heightwrap content androidlayout aboveidimagebutton1 androidlayout centerhorizontaltrue androidlayout marginbottom51dp androidtext100 clicks relativelayoutmainactivityjavapackage comexampleegghatcherimport androidappactivityimport androidosbundleimport androidviewviewimport androidviewviewonclicklistenerimport androidviewanimationanimationimport androidviewanimationanimationutilsimport androidwidgetimagebuttonimport androidwidgettextviewpublic class mainactivity extends activity imagebutton imagebutton textview clickstogo animation shake private int clicks 100 override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main shake animationutilsloadanimationthis ranimshakeanim public void addlisteneronbutton imagebutton imagebutton findviewbyidridimagebutton1 clickstogo textviewfindviewbyidridtextview1 imagebuttonsetonclicklistenernew onclicklistener override public void onclickview v clicks clickstogosettextyou need to click clicks more times to open it findviewbyidridimagebutton1startanimationshake shakeanimxmlxml version10 encodingutf8translate xmlnsandroid androidduration300 androidfromxdelta0 androidinterpolatorandroidanimcycle interpolator androidtoxdelta10,"['java', 'android']" +635617,create a standalone java websocket client endpoint i want to create a websocket endpoint client in java as pure as possible no frameworks but virtually all the examples i have found have only server endpoints in java whereas the client is in javascript can anyone point me to a good client example or provide one,['java'] +635624,python 3 rounding behavior in python 2 in python 2x the builtin round has the following behaviorif two multiples are equally close rounding is done away from 0 so for example round05 is 10 and round05 is 10in python 3x this has changed to the more commonif two multiples are equally close rounding is done toward the even choice so for example both round05 and round05 are 0 and round15 is 2is there an easy way to get this behavior in python 2x unfortunately the future builtins module does not include this maybe there is another similar module i have not found yet or another way to pull python 3x functions into python 2xobviously i could write a new function that produces the desired behavior but i am more curious if a solution exists that uses the actual python 3x function to avoid adding unnecessary complexity and code to maintain,['python'] +635669,reach content of new windowopen i made a new windowvar win windowopen width400 height200and i want to reach its body withvar windowbody windocumentbodyand from there use methods like find htmlthis works good on ff chrome but not ie found also a related post to this onehow to fix this in ie ie how to make this work cross browserjsfiddle notice that the close button never shows up in ie,"['javascript', 'jquery']" +635703,javascript scroll function slow lots of timer fired onloadwffjs310 weasel events in chrome i am trying to debug a page which is acting a little slow in chrome think it might be an issue with the following javascript codedocumentreadyfunction function navscrollthistance windowscrollfunction var scrolltop ifthistance scrolltop thistance else scrolltop 150 ifwindowscrolltop scrolltop ifmainnavhasclashownav mainnavaddclashownav else ifmainnavhasclashownav mainnavremoveclashownav ifheaderimagebaselength var windowheight windowheight headerimagebasecssheight windowheight navscrollwindowheight else navscroll when i look in chromes consoles timeline panel and press record this is what i seeany ideas what is happening here i cannot find any references to this on google and no idea how to remedy it,"['javascript', 'jquery']" +635705,directed edges in sigmajs a minimal example questionwhat is necessary to produce directed edges in sigmajs i am looking for a minimal example that is preferably based off of the minimal example currently on their home pageattemptsi tried adapting the minimal graph example from the sigmajs homepage in the following way sigmaparsersjsondatajson container container settings defaultnodecolor ec5148 defaultedgearrow source adding this line should add arrows sadly this did not produce different resultsi also tried modifying the edges in the graph itselfedges id e0 source n0 target n1 arrow source but again this had no effectmore complex examplesedge arrow rendering was added in this pull request this links to a couple of examples here and here,['javascript'] +635719,greasemonkey detect private browsing mode i need to make my greasemonkey script behave differently if it is currently running in a firefox private browsing window is it possible to detect this from greasemonkey if not then is it possible to have it not run at all in private browsing modeedit one reason i want to do that is that normally the script makes ajax requests which include information about the visited page and the serverside may store that information which is ok when browsing in normal mode if the user is in private browsing though i do not want the serverside to have the information that the user is visiting the page so i want to have it not make these requests in that case,['javascript'] +635744,multithreading based rabbitmq consumer we have a windows service which listen to single rabbitmq queue and process the messagewe would like to extend same windows services so that it can listen to multiple queues of rabbitmq and process the message not sure if that can be possible by using multithreading as each thread will have to listing blocking the queueas i am very new to multithreading need high level guideline on following point which will help me to start building the prototypeis it possible to listen multiple queues in single application by using threadinghow to handle the situation where if any single thread got shoutsown due to exception etc how to bring back without restart thewhole windows servicesany design pattern or open source implementation which can help me to handle this kind of situation,['c#'] +635781,what does resrender do and what does the html file look like what does resrender do and what does the html file look like my end goal is to load arbitrary commaseparatedvalues from a text file into an html file for example i was only able to deduce that a view was the html file and callback gives that html file backhere is the documentation now given context from some example code i found there is something about using ejs embedded javascript with and but if i may add am i just incompetent or is the documentation really truly vague and assumes the reader knows everything how could i have gone about figuring this out on my own is there any official documentation so i can gain a full understanding of usage advantages and pitfallsedit 1 i just want to add that i am having a heck of a time learning nodejs is it me or is the general documentation really vague aside from lousy explanations like above there are no type specifications for parameters or return valuesedit 2let me ask you some more specific questions above the codethe actual ordersejs file is in viewsordersejs how does this code refer to ithtml excerpttbody forvar i0 iorderslength i tr td ordersiid td td ordersiamount td td ordersitime td tr and the js please see orders define routes for simple ssjs web app writes coinbase orders to databasevar async requireasync express requireexpress fs requirefs http requirehttp https requirehttps db requiremodelsvar app expressappsetviews dirname viewsappsetview engine ejsappsetport processenvport 8080 render homepage note trailing slash examplecomappget functionrequest response var data fsreadfilesyncindexhtmltostring responsesenddata render examplecomordersappgetorders functionrequest response globaldborderfindallsuccessfunctionorders var orders json ordersforeachfunctionorder orders jsonpushid ordercoinbase id amount orderamount time ordertime uses viewsordersejs responserenderorders orders orders json errorfunctionerr consolelogerr responsesenderror retrieving orders hit this url while on examplecomorders to refreshappgetrefresh orders functionrequest response httpsget key processenvcoinbase api key functionres var body resondata functionchunk body chunk resonend function try var orders json jsonparsebody if orders jsonerror responsesendorders jsonerror return add each order asynchronously asyncforeachorders jsonorders addorder functionerr if err consolelogerr responsesenderror adding orders else orders added successfully responseredirectorders catch error consolelogerror responsesenderror parsing json resonerror functione consoleloge responsesenderror syncing orders sync the database and start the serverdbsequelizesynccompletefunctionerr if err throw err else httpcreateserverapplistenappgetport function consoleloglistening on appgetport add order to the database if it does not already existvar addorder functionorder obj callback var order order objorder order json from coinbase if orderstatus completed only add completed orders callback else var order globaldborder find if order has already been added to our database orderfindwhere coinbase id orderidsuccessfunctionorder instance if order instance order already exists do nothing callback else build instance and save var new order instance orderbuild coinbase id orderid amount ordertotal btccents 10 convert satoshis to btc time ordercreated at new order instancesavesuccessfunction callback errorfunctionerr callbackerr,['javascript'] +635794,python extending properties like youd extend a function questionhow can you extend a python property a subclass can extend a super clas function by calling it in the overloaded version and then operating on the result heres an example of what i mean when i say extending a function extending a function a tongueincheek exampleclass normalmathobject def init self number selfnumber number def add piself and selfnumber return and 31415class newmathobject def add piself newmath does not know how normalmath added pi and should not need to it just uses the result and normalmathadd piself in newmath fractions are considered too hard for our users we therefore silently convert them to integers return intnis there an analogous operation to extending functions but for functions that use the property decoratori want to do some additional calculations immediately after getting an expensivetocompute attribute i need to keep the attributes access lazy i do not want the user to have to invoke a special routine to make the calculations basically i do not want the user to ever know the calculations were made in the first place however the attribute must remain a property since i have got legacy code i need to supportmaybe this is a job for decorators if i am not mistaken decorator is a function that wraps another function and i am looking to wrap a property with some more calculations and then present it as a property again which seems like a similar idea but i cannot quite figure it outmy specific problemi have got a base class logfile with an expensivetoconstruct attribute dataframe i have implemented it as a property with the property decorator so it would not actually parse the log file until i ask for the dataframe so far it works great i can construct a bunch 100 logfile objects and use cheaper methods to filter and select only the important ones to parse and whenever i am using the same logfile over and over i only have to parse it the first time i access the dataframenow i need to write a logfile subclass sensorlog that adds some extra columns to the base clas dataframe attribute but i cannot quite figure out the syntax to call the super clas dataframe construction routines without knowing anything about their internal workings then operate on the resulting dataframe and then cachereturn it base class rules for parsinginteracting with dataclass logfileobject def init self file name file name to find the log file selffile name file name nonpublic variable to cache results of parse self dataframe none def parseself with openselffile name as infile complex rules to interpret the file self dataframe pandasdataframestuff property def dataframeself returns the dataframe parses file if necessary this works great if self dataframe is none selfparse return self dataframe dataframesetter def dataframeselfvalue self dataframe value sub class adds more information to data but doest parse must preserve established dataframe interfaceclass sensorloglogfile def init self file name call the supers constructor logfile init self file name sensorlog does not actually know about and does not rely on the dataframe cache so it overrides it just in case self dataframe none this is the part i cannot figure out heres my best guess but it does not quite work property def dataframeself use parent clas getter invoking the hidden parse function and any other operations logfile might do self dataframe logfiledataframegetter add additional calculated columns self dataframeextra stuff hello world return self dataframe dataframesetter def dataframeself value self dataframe valuenow when these classes are used in an interactive session the user should be able to interact with either in the same way log logfiledatacsv print logdataframe dataframe with 10 columns goes here sensor sensorlogdatacsv print sensordataframe dataframe with 11 columns goes here i have lots of existing code that takes a logfile instance which provides a dataframe attribute and dos something interesting mostly plotting i would love to have sensorlog instances present the same interface so they can use the same code is it possible to extend the superclas dataframe getter to take advantage of existing routines how or am i better off doing this a different waythanks for reading that huge wall of text you are an internet super hero dear reader got any ideas,['python'] +635832,abrecordref fields do not seem to be populated background ios 7 xcode 5 both up to date as of feb 2014 test data is address book entries with multiple phone numbers and multiple addresses in addition to basic contact info on an iphone 5 real device not simulatormy goal is to use the addressbookui methods to allow a user to specify a contact then use the various fields addresses phone numbers etc to populate a gui in my code the abpeoplepickernavigationcontroller is the standard mechanism to allow the user to pick a contact by name doing so results in this delegate method being called boolpeoplepickernavigationcontrollerabpeoplepickernavigationcontroller peoplepicker shouldcontinueafterselectingpersonabrecordrefpersonhowever if i examine the person record at this point none of the multivalue fields have any data so i extracted the recordid retrieved that and the resulting abrecordref also has no multivalue fields filled inif i return yes from the delegate method another ui is shown to the user with contact details thisplayed touching any field results in this delegate method call boolpeoplepickernavigationcontrollerabpeoplepickernavigationcontroller peoplepicker shouldcontinueafterselectingpersonabrecordrefperson propertyabpropertyidproperty identifierabmultivalueidentifieridentifierand that abrecordref has all the multi value fields filled ini cannot find any information about the records being lazily loaded or there being either a required delay or permissions issue that would prevent the fields from being filled in and the code i am using to examine the records is a method so the exact same code which finds the values in the second instance fails to find it in the firstany suggestions about what may be going on or how i can retrieve the full records without thisplaying the second ui to the useri am using apples quickcontacts sample code here are the additions and changes i have madensmutabledictionary convertabrecordrefabrecordrefperson initialize a mutable dictionary and give it initial values nsmutabledictionary contactinfodict nsmutabledictionary alloc initwithcapacity12 use a general core foundation object cftyperef generalcfobject abrecordcopyvalueperson kabpersonfirstnameproperty abrecordid foundid abrecordgetrecordidperson nsnumber personidnum nsnumber numberwithintegerfoundid contactinfodict setobjectpersonidnum forkeyrecordid get the first name if generalcfobject contactinfodict setobject bridge nsstring generalcfobject forkeyfirstname cfreleasegeneralcfobject get the last name generalcfobject abrecordcopyvalueperson kabpersonlastnameproperty if generalcfobject contactinfodict setobject bridge nsstring generalcfobject forkeylastname cfreleasegeneralcfobject generalcfobject abrecordcopyvalueperson kabpersonorganizationproperty if generalcfobject contactinfodict setobject bridge nsstring generalcfobject forkeycompanyname cfreleasegeneralcfobject abmultivalueref phones abrecordcopyvalueperson kabpersonphoneproperty nsarray numbers nsarray abmultivaluecopyarrayofallvaluesphones get the phone numbers as a multivalue property abmultivalueref phonesref abrecordcopyvalueperson kabpersonphoneproperty cfindex phonecount abmultivaluegetcountphonesref for cfindex i0 iabmultivaluegetcountphonesref i cfstringref currentphonelabel abmultivaluecopylabelatindexphonesref i cfstringref currentphonevalue abmultivaluecopyvalueatindexphonesref i if cfstringcomparecurrentphonelabel kabpersonphonemobilelabel 0 kcfcompareequalto contactinfodict setobject bridge nsstring currentphonevalue forkeymobilenumber if cfstringcomparecurrentphonelabel kabhomelabel 0 kcfcompareequalto contactinfodict setobject bridge nsstring currentphonevalue forkeyhomenumber if cfstringcomparecurrentphonelabel kabworklabel 0 kcfcompareequalto contactinfodict setobject bridge nsstring currentphonevalue forkeyworknumber cfreleasecurrentphonelabel cfreleasecurrentphonevalue cfreleasephonesref get the email addresses as a multivalue property abmultivalueref emailsref abrecordcopyvalueperson kabpersonemailproperty for int i0 iabmultivaluegetcountemailsref i cfstringref currentemaillabel abmultivaluecopylabelatindexemailsref i cfstringref currentemailvalue abmultivaluecopyvalueatindexemailsref i if cfstringcomparecurrentemaillabel kabhomelabel 0 kcfcompareequalto contactinfodict setobject bridge nsstring currentemailvalue forkeyhomeemail if cfstringcomparecurrentemaillabel kabworklabel 0 kcfcompareequalto contactinfodict setobject bridge nsstring currentemailvalue forkeyworkemail cfreleasecurrentemaillabel cfreleasecurrentemailvalue cfreleaseemailsref get the first street address among all addresses of the selected contact abmultivalueref addressref abrecordcopyvalueperson kabpersonaddressproperty if abmultivaluegetcountaddressref 0 cfindex numberofaddresses abmultivaluegetcountaddressref for cfindex i0 inumberofaddresses i cfstringref label abmultivaluecopylabelatindexaddressref i if label if cfequallabel kabhomelabel nsdictionary addressdict bridge nsdictionary abmultivaluecopyvalueatindexaddressref 0 contactinfodict setobjectaddressdict objectforkeynsstring kabpersonaddrestreetkey forkeyhomeaddress contactinfodict setobjectaddressdict objectforkeynsstring kabpersonaddresszipkey forkeyhomezipcode contactinfodict setobjectaddressdict objectforkeynsstring kabpersonaddresscitykey forkeyhomecity else if cfequallabel kabworklabel nsdictionary addressdict bridge nsdictionary abmultivaluecopyvalueatindexaddressref 0 contactinfodict setobjectaddressdict objectforkeynsstring kabpersonaddrestreetkey forkeyworkaddress contactinfodict setobjectaddressdict objectforkeynsstring kabpersonaddresszipkey forkeyworkzipcode contactinfodict setobjectaddressdict objectforkeynsstring kabpersonaddresscitykey forkeyworkcity cfreleaselabel cfreleaseaddressref if the contact has an image then get it too if abpersonhasimagedataperson nsdata contactimagedata bridge nsdata abpersoncopyimagedatawithformatperson kabpersonimageformatthumbnail contactinfodict setobjectcontactimagedata forkeyimage return contactinfodict thisplays the information of a selected person boolpeoplepickernavigationcontrollerabpeoplepickernavigationcontroller peoplepicker shouldcontinueafterselectingpersonabrecordrefperson only returns a few fields and none of the multi value ones nsmutabledictionary results quickcontactsviewcontroller convertabrecordrefperson abaddressbookref addressbook abaddressbookcreatewithoptionsnull null abrecordid foundid abrecordgetrecordidperson abrecordref fullperson abaddressbookgetpersonwithrecordidaddressbook foundid also only returns a few fields nsmutabledictionary selectedfromid quickcontactsviewcontroller convertabrecordreffullperson return yes does not allow users to perform default actions such as dialing a phone number when they select a person property boolpeoplepickernavigationcontrollerabpeoplepickernavigationcontroller peoplepicker shouldcontinueafterselectingpersonabrecordrefperson propertyabpropertyidproperty identifierabmultivalueidentifieridentifier returns all simple and multivalue fields nsmutabledictionary results quickcontactsviewcontroller convertabrecordrefperson return noedit adding my solution thanks thorsten boolpeoplepickernavigationcontrollerabpeoplepickernavigationcontroller peoplepicker shouldcontinueafterselectingpersonabrecordrefperson nsarray allpersonrecords nsarray cfbridgingreleaseabpersoncopyarrayofalinkedpeopleperson nslogcount linked people i allpersonrecordscount nsmutabledictionary results nsmutabledictionary allocinitwithcapacity12 for int x0 xallpersonrecords count x abrecordref user cfbridgingretainallpersonrecords objectatindexx nsmutabledictionary userfromarray quickcontactsviewcontroller convertabrecordrefuser results addentriesfromdictionaryuserfromarray mush them together cfreleaseuser nslogfinished total number of contact fields foundd results count do something with the data here return no,['ios'] +635843,calling javascript function from handlebar how to call the javascript function inside handlebar script reasoni could not able to break the each from handlebar hence i need to pass it to javascript and to do the logic,['javascript'] +635854,whats the benefit of objectfreeze not freezing objects within the passed object i was learning more about the methods of javascripts object constructor on mdn and i noticed that the last sentence of objectfreezes description readsnote that values that are objects can still be modified unless they are also frozena behavior like that seems like it should be optin what exactly is the benefit of having to manually freeze a frozen objects objects recursivelyif i am freezing an object why would i want the objects inside of it to still be mutable,['javascript'] +635957,wildfly datasource conflicting with defaultds i migrate from jboss 71 to wildfly and i have some problems with my datasource 100437900 info orgwildflyextensionundertow serverservice thread pool 49 jbas017502 undertow 100final starting100437901 info orgwildflyextensionundertow msc service thread 12 jbas017502 undertow 100final starting100437903 info orgjbossaswebservices serverservice thread pool 50 jbas015537 activating webservices extension100437904 info orgjbossassecurity msc service thread 13 jbas013170 current picketbox version4020final100437913 info orgjbossasconnectorsubsystemsdatasources serverservice thread pool 28 jbas010404 deploying nonjdbccompliant driver class orgpostgresqldriver version 90100437919 info orgjbossasconnectordeployersjdbc msc service thread 16 jbas010417 started driver service with drivername postgresql100437924 info orgjbossasconnectorsubsystemsdatasources serverservice thread pool 28 jbas010403 deploying jdbccompliant driver class orgh2driver version 13100437926 info orgjbossasconnectordeployersjdbc msc service thread 113 jbas010417 started driver service with drivername h2100437939 info orgjbossasnaming msc service thread 19 jbas011802 starting naming service100437939 info orgjbossasmailextension msc service thread 110 jbas015400 bound mail session javajbossmaildefault100438013 info orgjbossremoting msc service thread 1 jboss remoting version 400final100438023 info orgwildflyextensionundertow serverservice thread pool 49 jbas017527 creating file handler for path cbinwildfly800finalwelcomecontent100438044 info orgwildflyextensionundertow msc service thread 16 jbas017525 started server defaultserver100438061 info orgwildflyextensionundertow msc service thread 114 jbas017531 host defaulthost starting100438231 info orgjbossasserverdeploymentscanner msc service thread 114 jbas015012 started filesystemdeploymentservice for directory cbinwildfly800finalstandalonedeployments100438398 info orgwildflyextensionundertow msc service thread 1 jbas017519 undertow http listener default listening on localhost1270018080100438530 info orgjbossasconnectorsubsystemsdatasources msc service thread 13 jbas010400 bound data source javajdbchq100438531 info orgjbossasconnectorsubsystemsdatasources msc service thread 18 jbas010400 bound data source javajbossdatasourcesexampleds100438531 info orgjbossasconnectorsubsystemsdatasources msc service thread 1 jbas010400 bound data source javajdbcdice100438641 info orgjbosswscommonmanagement msc service thread 16 jbws022052 starting jboss web services stack cxf server 423finalwhen i look at my log i see that wildfly deployed my dice datasource and bound it to javajdbcdice it is referenced in my persistence xmlxml version10 encodingutf8persistence version21 xmlns xmlnsxsi xsischemalocation 2 1xsd persistenceunit namedice providerorghibernateejbhibernatepersistenceprovider jtadatasourcejdbcdicejtadatasourcenow i want to check some datasource settings at startup to ensure isolation level and so onsingletonstartuppublic class configservice resourcename javajdbcdice private datasource datasourcein the startup method i just do things like connection connection datasourcegetconnection boolean autocommit connectiongetautocommit int isolationlevel connectiongettransactionisolationat startup i always get100456948 error orgjbossmscservicefail msc service thread 115 msc01 failed to start service jbossdeploymentunitdicewarinstall orgjbossmscservicestartexception in service jbossdeploymentunitdicewarinstall jbas018733 failed to process phase install of deployment dicewar at orgjbossasserverdeploymentdeploymentunitphaseservicestartdeploymentunitphaseservicejava166 wildflyserver800finaljar800final at orgjbossmscserviceservicecontrollerimplstarttaskstartserviceservicecontrollerimpljava1948 jbossmsc120finaljar120final at orgjbossmscserviceservicecontrollerimplstarttaskrunservicecontrollerimpljava1881 jbossmsc120finaljar120final at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava1145 rtjar170 51 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava615 rtjar170 51 at javalangthreadrunthreadjava744 rtjar170 51caused by javalangillegalargumentexception jbas011053 incompatible conflicting binding at javajdbcdice source lookup javacompdefaultdatasource at orgjbossaseecomponentdeployersmodulejndibindingprocessoraddjndibindingmodulejndibindingprocessorjava243 at orgjbossaseecomponentdeployersmodulejndibindingprocessor1handlemodulejndibindingprocessorjava184 at orgjbossaseecomponentclassdescriptiontraversalrunclassdescriptiontraversaljava54 at orgjbossaseecomponentdeployersmodulejndibindingprocessorprocessclassconfigurationsmodulejndibindingprocessorjava152 at orgjbossaseecomponentdeployersmodulejndibindingprocessordeploymodulejndibindingprocessorjava145 at orgjbossasserverdeploymentdeploymentunitphaseservicestartdeploymentunitphaseservicejava159 wildflyserver800finaljar800final 5 more100456959 error orgjbossascontrollermanagementoperation deploymentscannerthreads 2 jbas014613 operation deploy failed address deployment dicewar failure description jbas014671 failed services jbossdeploymentunitdicewarinstall orgjbossmscservicestartexception in service jbossdeploymentunitdicewarinstall jbas018733 failed to process phase install of deployment dicewar caused by javalangillegalargumentexception jbas011053 incompatible conflicting binding at javajdbcdice source lookup javacompdefaultdatasource jbas014771 services with missingunavailable dependencies jbossdeploymentunitdicewarweldweldclassintrospector is missing jbossdeploymentunitdicewarbeanmanager100457112 info orgjbossasserver deploymentscannerthreads 2 jbas018559 deployed dicewar runtimename dicewar100457113 info orgjbossascontroller deploymentscannerthreads 2 jbas014774 service status reportjbas014775 new missingunsatisfied dependencies service jbossdeploymentunitdicewarbeanmanager missing dependents service jbossdeploymentunitdicewarweldweldclassintrospector jbas0147 services which failed to start service jbossdeploymentunitdicewarinstall orgjbossmscservicestartexception in service jbossdeploymentunitdicewarinstall jbas018733 failed to process phase install of deployment dicewarif i change the jndi name of the datasource injection it works eg dice only but i do not understand why what am i doing wronggreetingsm,['java'] +636004,jquery each index value iave been teaching my self javascript and jquery for a few months but iam still getting confused with javascript objects and jquery objectsin the following example i assigned a jquery object to the variable target the target should consist of an array of two objectsmy question is why i have to wrap the value variable again into the jquery object in each function selectto appendchangefunction var target selectto append var form anotherform eachtarget functionkey value formappendinput name valueattrname typehidden value valueval input the sample code i use to append values from selects which are not parts of the form being submitted,"['javascript', 'jquery']" +636050,reconnecting mysql on timeout i have a python program which runs on background for weeks and does database queries every once in a while for that i am using the orm peewee version 221 i am using mysql as a backendlately i have encountered a recurring problem with accessing the db usually after days of running the program the error which is raised by peewee ispeeweeoperationalerror 2006 mysql server has gone awaythe traceback is deep in peewee i post it here but as my virtualenv makes filenames too long i am shortening them file locallibpython27sitepackagespeeweepy line 2910 in save ret pk selfinsertfield dictexecute file locallibpython27sitepackagespeeweepy line 2068 in execute return selfdatabaselast insert idself execute selfmodel class file locallibpython27sitepackagespeeweepy line 1698 in execute return selfdatabaseexecute sqlsql params selfrequire commit file locallibpython27sitepackagespeeweepy line 2232 in execute sql selfcommit file locallibpython27sitepackagespeeweepy line 2104 in exit reraisenew type new typeexc valueargs traceback file locallibpython27sitepackagespeeweepy line 23 in execute sql res cursorexecutesql params or file locallibpython27sitepackagesmysqldbcursorspy line 205 in execute selferrorhandlerself exc value file locallibpython27sitepackagesmysqldbconnectionspy line 36 in defaulterrorhandler raise errorclass errorvaluepeeweeoperationalerror 2006 mysql server has gone awaypossible solution attempts i have foundin this question one of the comments suggest pinging the mysql server every once in a while to keep it the connection alive i am not sure how to do it via the orm though should i simply select 1 every hour sayin this github peewee issue which was opened 4 months ago the same error is referred though it is claimed there that it is solved and i am using a newer versionin a 7 year old issue of trac one suggestion is to increase the timeout of mysql for 3 daysin this forum thiscussion the option of increasing mysqls timeout is suggested but an alternative of using the autoreconnect option for the mysql jdbc connector is offered i tried to figure out if such an option exists for pythons mysqldb module but could not findi have found this mysql reference page on reconnection behaviour but it is a bit complicated for my understanding of mysql usually i work only with orms and i do not know how to apply any of it from peeweven if i am able to ping the database to keep the connection alive for longer periods i think it is considered a bad practice to keep a connection alive when one does not really need it is there any way to reopen the connection via the orm i consider both pinging and increasing the timeout of mysql as workarounds while a real solution would be to reconnect when needed and a real solution is what i am asking for,"['python', 'mysql']" +636207,calculating the point3ds of a cuboid around a line there are two point3ds a and b and i want to calculate the points of a cuboid abc h surrounding the line between a and b like a hullthere is one degree of freedom the angle of the cuboid because it can rotate around the line ab i am not sure yet if this is a problemi tried to calculate a vector normal to ab d and then the cross product of ab ad e in the code c is a b so its the offset parallel to abi normalized these three vectors c d and e and multiplied it with an offset to add subtract them from a and b it is not quite working yet edit see ja72s code for solutioni also implemented a way of finding a normal vector double ax vector3danglebetweene new vector3d1 0 0 double ay vector3danglebetweene new vector3d0 1 0 double az vector3danglebetweene new vector3d0 0 1 ax mathabsax 90 ay mathabsay 90 az mathabsaz 90 if ax ay ax az and vector3dcrossproducte new vector3d1 0 0 else if az ax az ay and vector3dcrossproducte new vector3d0 0 1 else and vector3dcrossproducte new vector3d0 1 0 and normalizen,['c#'] +636217,how to debug into my nuget package deployed from teamcity i have put a library that my team uses into a nuget package that is deployed from teamcity into a network folder i cannot debug into this code though symbolsource is one solution i have read about but i would much rather find some way to have access to the pdbsource files directly from teamcity does anyone know how to do this edit when i check include symbols and source in the nuget pack build step teamcity creates a symbolnupkg in addition to the nupkg file in the network folder the symbolnupkg contains the src and the pdb file edit i unchecked include symbols and source on teamcity and added the following to my nuspec file files file srcmylibrarybinreleasemylibrarydll targetlibnet40 file srcmylibrarybinreleasemylibrarypdb targetlibnet40 file srcmylibrarycs targetsrc file srcmylibrarycs targetsrc filesthis added the dll the pdb and the source files for my library in the nuget package and did not generate a symbols file which i think is only needed for symbol servers,['c#'] +636279,error when trying to overload an operator i recently start teaching myself game programming someone recommend me to start with python and i got the book beginning game development with python and pygame from novice to professional i got to a part where they teach about vectors and creating a vector2 class everything was going well until i tried to overload the division operatormy code goes like thisclass vector2object def init self x00 y00 selfx x selfy y def str self return s sselfx selfy classmethod def from pointscls p1 p2 return clsp20 p10 p21 p11 def add selfrhs return vector2selfx rhsx selfy rhsy def sub selfrhs return vector2selfx rhsx selfy rhsy def mul self scalar return vector2 selfxscalar selfyscalar def div self scalar return vector2 selfxscalar selfyscalarnow when i tried to call the operator this shows upab vector2100250printab 100 250v1 ab vector22010printv1 300 350v2 ab vector22010printv2 100 150v3 ab 3printv3 300 750printv3 3typeerror unsupported operand types for vector2 and intthis was all in python 33 but if i run it with python 27 everything works correctlywheres the problem,['python'] +636290,how to speed up the xml dtd validation with php i am walidating my xml with a dtd file i have locallyfor that i am doingxml dmsmerrinxmlidconversionxmldtd dmsmerrinstyle filesjournalpublishingdtddom new domdocumentdomloadxmllibxml use internal errorstrueif domvalidate htmldtderror h2no errors found the tested file is valid h2 else errors libxml get errors htmldtderror h2errors found counterrorsh2ol foreach errors as error htmldtderror lierrormessage on line errorline li htmldtderror ol libxml clear errorslibxml use internal errorsfalseand this takes about 30sec for an xml with 1600 linesis this a usual time should be much faster in my opinionas you can see the dtd i am using is locally on the server any idea thank youedit by debuging and checking the execution time i noticed that it takes the same time if my xml has 1600 lines or 150 lines so the problem is not the xml size,['php'] +636292,how can jsonnet perform dependency injection during deserialization when i have a class with no default constructor ie using dependency injection to pass its dependencies can newtonsoftjson create such an objectfor examplepublic class somefoo private readonly ifoodependency dependency public somefooifoodependency dependency ifdependency null throw new argumentnullexceptiondependency dependency dependency public string data get set public int moredata get set public void dofoo data dependencygetfoodata moredata dependencygetmorefoodate during serialization i only care of storing data and moredata and the type of the object but let us do not complicate things for the moment now to deserialize can i call something likevar obj jsonconvertdeserializeobjectsomefoojsontexthow can i let jsonconvert know about my di container note a workaround would be to always have default constructors in my classes and call service locator in there to get any dependencies i need i am just looking for some more clean solution without poluting my classes with such constructors,['c#'] +636371,implicit operators and lambdas i am trying to create a class that takes a lambda and stores it internally the syntax would be something likeclass lambdatin tout private expressionfunctin tout expr private functin tout func public lambdaexpressionfunctin tout e expr e public lambdafunctin tout f func f public static implicit operator lambdatin toutlambdatype o return new lambdao usagelambdatin tout l o but i am having some trouble figuring out the details i know that a lambda is an anon type until it is assigned to either an expression or a delegate and that i would i believe have to use an implicit operator to get the syntax i am going for but beyond that i have hit a wall i can use expression or func in my implicit operator if they have already been assigned to a variable like soexpressionfunct1 t2 e o funct1 t2 f o lambdat1 t2 l1 e l2 fbut i would much prefer to just assign the lambda itself and have the class figure out the details,['c#'] +636434,after screen orientation change the dialogfragment appears apparently without any call here there is part of the activity where the screen orientation changeprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main et edittext findviewbyidridedittext1 etsetonlongclicklistenernew viewonlongclicklistener override public boolean onlongclickview v fragment1 dialogfragment new fragment1 dialogfragmentshowgetfragmentmanager null dialogfragmentsettextdialogetgettexttostring return true apparentely it seems that the dialog that will appear inside the dialogfragment should appear just after the onlongclick over the edittexti know that when the screen orientation change the activity is restarted but it should not start normally like the first time that is createdmy problemwhen i open at least once the dialog and i close it after the screen orientation change i have the dialog thisplayed again on the screen like if i longclicked the edittexti do not absolutely know why this happensi attach also the structure of dialog fragmentpublic dialog oncreatedialogbundle savedinstancestate final dialog dialog superoncreatedialogsavedinstancestate dialogrequestwindowfeaturewindowfeature no title layoutinflater adbinflater layoutinflaterfromgetactivity view eulalayout adbinflaterinflaterlayoutdialog crypt null button btn ok button eulalayoutfindviewbyidridbtnok dialogsetcontentvieweulalayout final edittext et edittexteulalayoutfindviewbyidridedittext2 etsettexttextdialog ifetlength0 etsettextetgettexttostring etsetselectionetlength btn oksetonclicklistener new viewonclicklistener override public void onclickview v textdialog etgettexttostring maingetactivitysettextonedittexttextdialog dialogthismiss return dialogthanks so much for the help,['android'] +636557,make column fixed position in bootstrap using bootstrap i have a grid column classcollg3 that i want to place it in positionfixed while the other collg9 is normal position scrollable through the pagediv classrow div classcollg3 fixed content div div classcollg9 normal scrollable content divdivjust the same way like the left column in lifehackercomyou will see that the left part is fixed however i scroll though the pagei use bootstrap v311,['css'] +636575,entity framework inserting child objects in the wrong order questionwhy is ef first inserting a child object personnelworkrecord with a dependency before the object that it is depended on timesheetactivity also what are my options on correcting thiserd simplifiedthis is predefined by another system out of my direct control ef setup and save codei am not sure i understand whyhow entity framework is inserting the objects i have in the order it does however here is the code i am using to insert a parent and several childrenusing var db new datacontextuser timesheetstate stateadded timesheetsequencenumber newsequencenumber thisprepareauditfieldstimesheet to stop ef from trying to add all child objects remove them from the timehseets object timesheet removechildobjectstimesheet db add the timesheet object to the database context and save dbtimesheetsaddtimesheet result dbsavechanges 0sql trace of efs insertswhen i run the code i get a sql foreign key violation on the personnelworkrecord timesheetactivityid because i have not yet added the activity see traceexec sp executesql ninsert dbotimesheetsprojectid timesheetstatusid exec sp executesql ninsert dbopersonnelworkdaystimesheetid personnelid exec sp executesql ninsert dbopersonnelworkrecordspersonnelworkdayidtimesheetactivityid data context summarymodelbuilderentitypersonnelworkdayhasrequiredpwd pwdpersonnelwithmanyp ppersonnelworkdayshasforeignkeypwd pwdpersonnelidwillcascadeondeletefalsemodelbuilderentitypersonnelworkdayhasrequiredpwd pwdtimesheetwithmanyt tpersonnelworkdayshasforeignkeypwd pwdtimesheetidwillcascadeondeletefalsemodelbuilderentitypersonnelworkrecordhasrequiredpwr pwrpersonnelworkdaywithmanypwd pwdpersonnelworkrecordshasforeignkeypwr pwrpersonnelworkdayidwillcascadeondeletefalsemodelbuilderentitypersonnelworkrecordhasrequiredpwr pwrtimesheetactivitywithmanyta tapersonnelworkrecordshasforeignkeypwr pwrtimesheetactivityidwillcascadeondeletefalsemodelbuilderentitytimesheetactivityhasrequiredta taprojectactivitywithmanya atimesheetactivitieshasforeignkeyta taprojectactivitycodeidwillcascadeondeletefalsemodelbuilderentitytimesheetactivityhasoptionalta tafacilitywithmanyf ftimesheetactivitieshasforeignkeytf tffacilityidwillcascadeondeletefalsemodelbuilderentitytimesheetactivityhasrequiredta tatimesheetwithmanyt ttimesheetactivitieshasforeignkeyta tatimesheetidwillcascadeondeletefalseremove child objectshere is the code for the child objects method i added this method to remove the objects from the timesheets child objects related objects that are not foreign keys for example i have a crew object but i also have a crewid foreign key so i have set crew null so that ef does not try to insert it since it already existsprivate timesheet removechildobjectstimesheet timesheet datacontext db timesheetcrew null timesheetforeman null timesheetlocation null timesheetproject null timesheetsigningprojectmanager null timesheettimesheetstatus null timesheetcreator null timesheetmodifier null if timesheettimesheetactivities null foreach timesheetactivity tsa in timesheettimesheetactivities tsacreator null if tsaequipmentworkrecords null tsaequipmentworkrecords removechildobjectstsaequipmentworkrecords db tsafacility null tsamodifier null if tsapersonnelworkrecords null tsapersonnelworkrecords removechildobjectstsapersonnelworkrecords db tsaprojectactivity null tsastructures null tsatimesheet null if timesheettimesheetequipment null foreach timesheetequipment te in timesheettimesheetequipment teequipment null tetimesheet null if timesheetequipmentworkdays null timesheetequipmentworkdays removechildobjectstimesheetequipmentworkdays true db if timesheettimesheetpersonnel null foreach timesheetpersonnel tp in timesheettimesheetpersonnel tppersonnel null tppersonnelworkday null if tppersonnelworkday null tppersonnelworkday removechildobjectstppersonnelworkday db tptimesheet null if timesheetpersonnelworkdays null timesheetpersonnelworkdays removechildobjectstimesheetpersonnelworkdays true db return timesheet debug of values before ef savefrom my understanding anything an dbcontexobjectnameherelocal will be addedmodifieddeleted when a dbcontextsave is called depending on what the entity state is set too here is what ef is trying to save before i call the save and get an sql fk exceptionthen i get the fk exceptionthe insert statement conflicted with the foreign key constraint fk personnelworkrecords timesheetactivities the conflict occurred in database vpmtest gc table dbotimesheetactivities column timesheetactivityid the statement has been terminatednotesplease let me know if there is anything i can post to help describe my question i have looked around google so for answers but so far no solid answers it looks like ef can not determine the order of inserting objects unless the domain model is setup differently i am not able to change the structure of most objects as they are used by another system i can attempt to change my ef call i would prefer not to use raw sql as the objects are quite a bit more extensive then the simplified versions i have posted heresimilar questions self referencing entity and insert order,['c#'] +636579,make back button go to the previous view programmatically i have a uibarbuttonitem and would like to programmatically set the action that goes to the previous controller in my case my previous view is a uitableviewcontrollerbelow is my code that i am currently using to make the bar button item although the button does not go to the previous view yetuibarbuttonitem leftbutton uibarbuttonitem alloc initwithtitledone styleuibarbuttonitemstyledone targetnil actionniluinavigationitem item uinavigationitem alloc initwithtitlewebsiteitemleftbarbuttonitem leftbuttonitemhidesbackbutton yesmybar pushnavigationitemitem animatedno,"['ios', 'objective-c']" +636610,invalid update invalid number of rows in section 0 i have read all of the related posts regarding this and i am still having an errorinvalid update invalid number of rows in section 0 the number of rows contained in an existing section after the update 5 must be equal to the number of rows contained in that section before the update 5 plus or minus the number of rows inserted or deleted from that section 0 inserted 1 deleted and plus or minus the number of rows moved into or out of that section 0 moved in 0 moved outhere are the detailsin h i have an nsmutablearrayproperty strongnonatomic nsmutablearray currentcartin m my numberofrowsinsection looks like this nsintegertableviewuitableview tableview numberofrowsinsectionnsintegersection return the number of rows in the section return currentcart countto enable delete and remove the object from the array editing of rows is enabled voidtableviewuitableview tableview commiteditingstyleuitableviewcelleditingstyleeditingstyle forrowatindexpathnsindexpath indexpath if editingstyle uitableviewcelleditingstyledelete when delete is tapped tableview deleterowsatindexpathsnsarray arraywithobjectindexpath withrowanimationuitableviewrowanimationfade currentcart removeobjectatindexindexpathrow i thought that by having my number of sections relying on the count of the array i am editing it would ensure the proper number of rows cannot this be done without having to reload the table when you delete a row anyway,"['ios', 'objective-c']" +636627,difference between designwidth and width in usercontrol in wpf when i create a new usercontrol in wpf studio creates some xamlusercontrol xclassmogobjectsdatecalender xmlns xmlnsx xmlnsmc xmlnsd mcignorabled ddesignheight300 ddesignwidth300 grid gridusercontrolin usercontol i can also add width property what is difference between designwidth and width,['c#'] +636647,opencv error assertion failed scn 3 scn 4 i am having assertion failed error at the last frame while reading and writing a video frame by frame the errors only shows at the last frame do not know why saw this answer here whichs suggests to give waitkey my code already have wait key on itmy simple code is as followsint main cvcapture capturecvcapturefromfilecvidopmp4 ifcapturenull printfcannot open video mat frame first framecurrent frame char buffer100 int frame count1p1 while1 getting the current frame from the video framecvqueryframecapture cvcvtcolorframecurrent frame1 saving current frame sprintfbuffercframesimageujpgp imwritebuffercurrent frame p waitkey1 return 0 anybody please helpsolution i added a check just after reading every file asifframeemptyfprinfcannot access frameretun 1,['c'] +636655,android appcompat actionbar menu item showasaction not working i have a menu item that is showing up on android 4x but not on 2x here is my menuxmlxml version10 encodingutf8menu xmlnsandroidxmlnsapp item androidididmenu filter androidtitlefilter appshowasactionalways menuthis is my actionbar stylestyle namestyle1 actionbar parentstylewidgetappcompatlightactionbar item nameandroidbackgroundcolorblue darkitem item nameandroidtextcolorcolorwhiteitem item nameactionmenutextappearancecolorwhiteitem item namebackgroundcolorblue darkitemstyleany ideasedit removed double quote typocould it be the fact that i am showing only text no icons i am kind of stuck here,['android'] +636667,android custom numeric keyboard i want to add numeric keyboard like the one in vault application i do not know how to call it and how can i find in google,['android'] +636680,animate a cashapelayer to draw a progress circle i am trying to draw a circle that will be used to indicate progress the progress updates might come in quickly and i want to animate the changes to the circlei have tried doing this with the below methods but nothing seems to work is this possible idinitwithframecgrectframe strokewidthcgfloatstrokewidth insetsuiedgeinsetsinsets if self super initwithframeframe selfstrokewidth strokewidth cgpoint arccenter cgpointmakecgrectgetmidxselfbounds cgrectgetmidyselfbounds cgfloat radius cgrectgetmidxselfbounds insetstop insetsbottom selfcirclepath uibezierpath bezierpathwitharccenterarccenter radiusradius startanglem pi endanglem pi clockwiseyes self addlayer return self voidsetprogressdoubleprogress progress progress self updateanimations voidaddlayer cashapelayer progresslayer cashapelayer layer progresslayerpath selfcirclepathcgpath progresslayerstrokecolor uicolor whitecolor cgcolor progresslayerfillcolor uicolor clearcolor cgcolor progresslayerlinewidth selfstrokewidth progresslayerstrokestart 100f progresslayerstrokeend 400f selflayer addsublayerprogresslayer selfcurrentprogresslayer progresslayer voidupdateanimations selfcurrentprogresslayerstrokeend selfprogress selfcurrentprogresslayer didchangevalueforkeyendvaluecurrently this code does not even draw the circle but removing the progresslayers strokestart and strokeend will draw the full circlehow can i get it to begin at a certain point and start drawing the circle based on me setting my progress property,"['ios', 'objective-c']" +636848,does taskdelay start a new thread the following code should at least in my opinion create 100 tasks which are all waiting in parallel that is the point about concurrency right d and finish almost at the same time i guess for every taskdelay a timer object is created internallypublic static async task mainasync var tasks new listtask for var i 0 i 100 i functask func async await taskdelay10 consolewritelineinstant tasksaddfunc await taskwhenalltaskspublic static void mainstring args mainasyncwaitbut when i run this on mono i get very strange behaviorthe tasks do not finish at the same time there are huge delays probably about 500600msin the console mono shows a lot of created threadsloaded assembly usersxprogrammingxbinreleasexexethread started 2thread started 3thread started 4thread started 5thread started 6thread started 7thread finished 3 obviously the delay of 10ms finished thread finished 2 obviously the delay of 10ms finished thread started 8thread started 9thread started 10thread started 11thread started 12thread started 13 you get itis this actually a bug or do i use the library wrong editi tested a custom sleep method using timer public static async task mainasync consolewritelinestarted var tasks new listtask for var i 0 i 100 i functask func async await sleepfast10 consolewritelineinstant tasksaddfunc await taskwhenalltasks consolewritelineready public static task sleepfastint amount var source new taskcompletionsourceobject new timerstate var oldsrc taskcompletionsourceobjectstate oldsrcsetresultnull source amount 0 return sourcetask this time all tasks completed instantaneously so i think it is a really bad implementation or a bugedit2just fyi i have tested the original code using taskdelay on net using windows 81 now and it ran as expected 10 tasks waiting for 1 second in parallel and finishedso the answer is monos impl of some methods is not perfect in general taskdelay does not start a thread and even a lot of them should not create multiple threads,['c#'] +636869,how to preserve identifierforvendor in ios after uninstalling ios app on device i am developing an ios app which calls webservice for login and at that time i send login credentials to web server along with vendor identifier identifierforvendorto identify device uniquely for those credentialsso user can have only one device and one credentiali got identifierforvendor with nsstring uuid uidevice currentdevice identifierforvendoruuidstringthis identifier will then store in database of web server and also in device databasenext time when user opens application and will try to download data from web server firstly local identifierforvendor on users device will compare with identifier stored on web serverproblem occurs when user uninstall app and reinstall it i found that identifierforvendor is changed so user cannot proceed furtheri read apple documentation uidevice documentationas mention there if all app from same vendor uninstalls from device then at time of new installation of any app from that vendor will take new identifierforvendor so how to deal with this in my case,['ios'] +636876,how to connect to teamfoundationserver tfs using client api from a console application i am trying to connect to teamfoundationserver hosted at visualstudiocom using its client api with a console application but i get this errortf400813 resource not available for anonymous access clientmy codeprivate static void mainstring args uri collectionuri new uri tfsteamprojectcollection collection new tfsteamprojectcollection collectionuri new systemnetnetworkcredential mypassword workitemstore workitemstore collectiongetserviceworkitemstore,['c#'] +636930,c what is the best and fastest way to concatenate strings i currently concatenate strings in c using the strcat function from stringh libraryi thought about it and i got to a conclusion that it should be very expensive function as before it starts to concatenate it has to iterate over the char array until it finds the 0 charfor example if i concatenate the string horses 10 times using strcat i will have to pay1 2 3 10 strlenhorses 1010012 6 30030i thought about the nonstandard way of maintaining an integer with the string length and then sending to strcat the pointer to the end of the stringstrcatdest dest len stringin this case i will pay only 10 strlenhorses 10 6 60 60 is much lower than 30030 so it can be very critical for performance if you make a lot of such concatenationsis there some more standard way to do it looks better than my solution,['c'] +636936,what combination of pythonmode ipython ipythonel versionsreleases and initelemacsd code work my goal is to use emacs 24 as my python editor also has a matlab and r editor but that is not what my question is about please let me know if i left out any information or if i did not state something clearlyi have been able to set up my packages and my initel file in such a way that i am able to get tab completion correct highlighting and snippets for python i am using pythonmodeel as my python modethe problems all revolve around this i want to use ipython as my python shell in order to use its tab completion functions when debugging scripts however when i start ipython using mx ipython i have no tab completion furthermore it does not show 1 in however it does show 1 outi would like to make ipython my default shell in emacs however attempts at this have failed eg setting cpathtoipythonexe onto pypythoncommandwhen i try to run my python script using cc cc it runs using the normal python and indeed stops at the position i tell the debugger to stop i use ipdbset trace however when i use another type of command that is supposed to start ipython like setting the region to my entire script and running pyexecuteregionipython ipython does not function it does start an ipython shell or at least it seems to but i can just type in the shell like it was a text editor fyi in the mini buffer it shows comintrun shellcompilemy question iswhat combination of package versions and lisp code in my initel file should allow me to use ipython with tab completion as my default shell in emacs i am willing to downgrade some of the packages if necessaryextra infofrom what i have read on the project page of pythonmodeel i understand that there are still some bugs regarding ipython with the latest version of this package so it is probably necessary to use an old versioni have been googling a lot to search for a solution and i have not been able to find one that works for mei am runningpythonmode 613ipython 110i tried ipythonel from but from contact with the developer of pythonmodeel this seems to be deprecated and no integrated into pythonmodeelgnu emacs 2431 i386mingwnt617601 of 20130317 on marvinwindows 7 64bitmy initel looks like python stuff is at the bottom requisites emacs 24require packagepackageinitializeaddtolist packagearchives melpa addtolist packagearchives marmalade tpackagerefreshcontentsdefun installifneeded package unless packageinstalledp package packageinstall package make more packages available with the package installer removed python mode since the version i got had errorssetq toinstall pythonmode magit yasnippet jedi autocomplete autopair findfileinrepository flycheckmapc installifneeded toinstallr stuffaddtolist loadpath cemacs243sitelispess13091setq essuseautocomplete tload esitematlab stuff add folder of matlabmodeeladdtolist loadpath cusersrob ter horstappdataroamingemacsdelpamatlabmode20130829142loadlibrary matlabloadmatlabcedetsetupsetq matlabshowmlintwarnings taddhook matlabmodehook autocompletemodeaddhook matlabmodehook mlintminormodegeneral stuff ido mode idopowered versions of code most ido commands are named idox so findfile becomes idofindfile and so onsetq idoenableflexmatching tsetq idoeverywhere tidomode tgloballinummode tuse y or and always instead of yesnodefalias yesornop yornp extra nice things andrea crotti use shift to move around windowswindmovedefaultkeybindings shiftshowparenmode t turn beep offsetq visiblebell nilcustomsetvariables ansicolornamesvector 242424 e5786d 95e454 cae682 8ac6f2 366 ccaa8f f6f3e8 customenabledthemes quote wheatgrasscustomsetfaces customsetfaces was added by custom if you edit it by hand you could mess it up so be careful your init file should contain only one such instance if there is more than one they would not work right put downcaseregion thisabled nilpython stuffrequire magitglobalsetkey cxg magitstatusrequire autocompleterequire autopairrequire yasnippetrequire jediyasnipped settingssetq yassnippetdirs cusersrob ter horstappdataroamingemacsdelpayasnippet201401061009snippetsaddtolist loadpath cusersrob ter horstappdataroamingemacsdelpayasnippet201401061009globalsetkey f7 findfileinrepository autocomplete mode extra settingssetq acautostart 2 acoverridelocalmap nil acusemenumap t accandidatelimit 20 python mode settingssetq pyinstalldirectory cusersrob ter horstappdataroamingemacsdself installedpythonmodeel613addtolist loadpath pyinstalldirectoryaddtolist automodealist py pythonmodewhen featurep python unloadfeature python trequire pythonmodesetq pyelectriccolonactive taddhook pythonmodehook autopairmodeaddhook pythonmodehook yasminormodeaddhook pythonmodehook autocompletemode jedi settings it is also required to run pip install user jedi and pip install user epc to get the python side of the library work correctly with the same interpreter youre using if you need to change your python intepreter if you want to change it setq jediservercommand python2 homeandreaemacsdelpajedi012jediepcserverpyaddhook pythonmodehook lambda jedisetup jediacsetup localsetkey ccd jedishowdoc localsetkey kbd mspc jedicomplete localsetkey kbd m jedigotodefinition ipython settingssetq pypythoncommand cpython27scriptsipythonexesetq pycompletefunction ipythoncomplete pyshellcompletefunction ipythoncomplete pyshellname ipython pywhichbufname ipython require ipythonwith tab autocompletion in ipdb i get an error that might be solved by changing this varthe error variable binding depth exceeds maxspecpdlsizesetq maxspecpdlsize 320 try to add flycheck flycheck causes emacs to become incredibly slow on big script with many style errors as present in a lot of my older scripts so i do not want to activate it by defaultsetq flycheckhighlightingmode linesaddhook pythonmodehook globalflycheckmodeflycheckselectchecker pythonflake8provide initflycheckyasreloadall,['python'] +637106,how to use modelquery with promises in sailsjswaterline i am having issues with sailsjs 098 i would like to use promises with the modelquery function i use sailsmysql adapterthis code will work userfindone email email thenfunctionuser consoleloguserbut this one would notuserqueryselect email from user where email email thenfunctionerr rows consolelogrowsi get undefined for both err and rowsis it just not implemented or i am doing something wrong if not implemented is there any alternative to use promises with query thank you in advance,['javascript'] +637114,how to override opacity for a child i am trying to reset the opacity to 10 for demo text 4 where its container has opacity set to 03 i read that i could set the text directly using color rgba255 255 0 1but this will not work for me is there a way to achieve my goaldoctype htmlhtml langenheadstyletext holder background bluewidth 500pxheight 200pxtext holder2 background bluewidth 500pxheight 200pxcolor rgba255 255 0 1alpha 30 opacity 03color ff0alpha 100 color ff0styleheadbodydiv idalpha 100div idtext holder pdemo text 1pdivdivdiv idalpha 30div idtext holder pdemo text 2pdivdivdiv idalpha 30div idtext holder pdemo text 3pdivdiv idtext holder2 pdemo text 4pdivdivbodyhtml,['css'] +637122,draw single contour in opencv on image what is the best way to draw a single contour in opencv as far as i can see drawcontours can only handle multiple contoursbackground i want to change my code to a for each loop the old codevectorvectorpoint contours result of findcontoursfor int i 0 i contoursize i ifiscorrectcontoursi drawcontoursimg contours i color 1 8 hierarchy the way presented in this mailing list is pretty uglyfor vectorpoint contour contours ifiscorrectcontour vectorvectorpoint con vectorvectorpoint 1 contour drawcontoursimg con 1 color 1 8 is there a cleaner way to draw single contours vector point object,['c++'] +637128,aspnet custom error page for web app that uses a master page reference kb306355 how to create custom error reporting pages in aspnet by using visual c net i understand how to create a custom errors page there are many examples of how to do it like in the link abovenone of the examples i have found shows how to do what i am afteri have a web application that uses a master pagein my master page i have a label control used for errors that all pages will seeh4 idbannererrorasplabel idlblerror runatserver h4in the code behind on that master page i have thispublic void page errorobject sender eventargs e var err servergetlasterrorgetbaseexception errormessage stringformaturl 0 1 error 2 requesturl errgettype errmessage serverclearerrorpublic string errormessage get return lblerrortext set logerrorvalue lblerrortext value the errormessage is a property my other pages can easily access it and i was easily able to edit out the part about writing the error to our servers databasethe webconfig page configuration snippetxml version10configuration systemweb compilation debugtrue targetframework40 customerrors defaultredirectdefaultaspx modeon error statuscode403 redirectdefaultaspx error statuscode404 redirectdefaultaspx customerrors systemwebconfigurationhow would i edit my files so that any errors that occur on any of my pages in my application that derive from master page simply show this basic information through the master page instead of redirecting the page to another url,"['c#', 'asp.net']" +637160,de bruijn algorithm binary digit count 64bits c im using the de bruijn algorithm to thiscover the number of digits in binary that a big number up to 64bits hasfor example1022 has 10 digits in binary130 has 8 digits in binaryi found that using a table lookup based on de bruijn give me the power to calculate this x100 times faster than conventional ways power square according to this website 26 has the table to calculate the 64 bits numbers this would be the table exposed in cstatic readonly int multiplydebruijnbitposition2 new int64 01248173451123473163626159 5546295853432244244935715306057 5138122550369183710214220411939 1428564836132754452652401632i dont know if i brought the table from that website correctlythen based on the r comment here i should use this to use the table with the input uint64 numberpublic static int getlog2 debruijnulong vreturn multiplydebruijnbitposition2ulongv 0x022fdd63cc95386dull 58but the c compiler doesnt allow me to use 0x022fdd63cc95386dull because it overflows 64bits and i have to use 0x022fdd63cc95386d insteadusing those codes the problem is that i am not getting the correct result for the input givenfor example doing 10 calculations of the number17012389719861204799 64bits used this is the resultusing pow2 method i get the result 64 1 million times in 1380msusing debruijn method i get the result 40 1 million times in 32ms dont know why 40im trying to understand how de bruijn works and how can i fix this and create a final code for c to calculate up to 64bits numbersudpate and benchmarks of different solutionsi was looking for the fastest algorithm to get the number of digits in binary that a unsigned given number of 64bits has in c known as ulongfor example1024 has 11 binary digits 2101 or log2102419223372036854775808 has 64 binary digits 2631 or log22631the conventional power of 2 and square is extremely slow and just for 10 calculations it needs 1500ms to get the answer 100m calculations needs hourshere niklas b jim mischel and spender brought differents methods to make this fastersimd and swar techniques provided by spender answer herede bruijn splited 32bits provided by jim mischel answer herede bruijn 64bits version provided by niklas b answer herede bruijn 128bits version also provided by niklas b answer heretesting this methods with a cpu q6600 overclocked to 3ghz using windows 7 64bits gives the following resultsas you can see it takes just a few seconds to find correctly 10 of request given being de bruijn 128bits version the fastestthanks a lot to all of you you help me a lot with this i hope this helps you too,['c#'] +637184,using tpl dataflow can i cancel all posts and then add one with the tpl dataflow library i would like to do something like thismyactionblockpostnewvalue cancelallpreviousposts trueit appears that the cancellation token on actionblock cancels the whole thing i would have to make a new actionblock if i set that one is it possible to do a partial cancellation with actionblockposts that have not been processed yet should not be attempted it would be nice if there was some cancellation token available to check in the currentlyexecuting post,['c#'] +637328,httpactioncontextrequest does not have createresponse meth i am trying to create a custom authorizeattribute in aspnet web api to handle basic auth when overriding handleunauthorizedrequest i find that the httpactioncontextrequest does not have a createresponse methodthe project is mvc 4 targetting net 45 i updated web api to version 2 using nugetusing systemusing systemnethttpheadersusing systemtextusing systemthreadingusing systemwebhttpnamespace basicauthsecurity public class basicauthattribute authorizeattribute public override void onauthorizationsystemwebhttpcontrollershttpactioncontext actioncontext if threadcurrentprincipalidentityisauthenticated return var authheader actioncontextrequestheadersauthorization if authheader null if authheaderschemeequalsbasic stringcomparisonordinalignorecase stringisnullorwhitespaceauthheaderparameter var credentials getcredentialsauthheader handle authentication return handleunauthorizedrequestactioncontext private string getcredentialsauthenticationheadervalue authheader var raw authheaderparameter var encoding encodingascii var credentials encodinggetstringconvertfrombase64stringraw return credentialssplit protected override void handleunauthorizedrequestsystemwebhttpcontrollershttpactioncontext actioncontext actioncontextresponse actioncontextrequest no createresponse method i am sure it must be a missing or incorrect reference somewhere it is rather confusing though any help would be much appreciatedthanks,['c#'] +637358,simple ix in haskell vs c i am learning haskell my interest is to use it for personal computer experimentation right now i am trying to see how fast haskell can get many claim parity with c and if that is true i would be very happy i should note that i will be using haskell whether or not it is fast but fast is still a good thing my test program implements ix with a very simple algorithm primes numbers add 1 to the result prime numbers have no integer divisors between 1 and ax this is not an algorithm battle this is purely for compiler performancehaskell seems to be about 6x slower on my computer which is fine still 100x faster than pure python but that could be just because i am a haskell newbie now my question how without changing the algorithm can i optimize the haskell implementation is haskell really on performance parity with chere is my haskell codeimport systemenvironment a simple integer square rootisqrt int intisqrt floor sqrt fromintegral primality test prime int boolprime x null x q 3 5isqrt x rem x q 0main do and fmap read head getargs print length filter prime 23 5nhere is my c codeinclude iostreaminclude cmathinclude cstdlibusing namespace stdbool isprimeintint mainint argc char argv int primes 10 count 0 if argc 1 primes atoiargv1 if isprime2 count for int i 3 i primes i2 if isprimei count cout count endl return 0bool isprimeint x for int i 2 i floorsqrtx i if x i 0 return false return true,['c++'] +637364,how to add constructorsdestructors to an unnamed class is there a way to declare a constructor or a destructor in an unnamed class consider the following void f struct some implementation inst1 inst2 f implementation usage of instancesfollow up question the instances are ofcourse constructed and destroyed as any stack based object what gets called is it a mangled name automatically assigned by the compiler,['c++'] +637490,creating a reusable uiview with xib and loading from storyboard ok there are dozens of posts on stack overflow about this but none are particularly clear on the solution i would like to create a custom uiview with accompanying xib the requirements areno separate uiviewcontroller a a completely selfcontained classoutlets in the class to allow me to setget properties of the viewmy current approach to doing this isoverride idinitwithframeidinitwithframecgrectframe self nsbundle mainbundle loadnibnamednsstringfromclaself class ownerself optionsnil objectatindex0 selfframe frame return selfinstantiate programatically using idinitwithframe in my view controllermycustomview mycustomview mycustomview alloc initwithframecgrectmake0 0 selfviewboundssizewidth selfviewboundssizeheightselfview insertsubviewmycustomview atindex0this works fine although never calling init super and simply setting the object using the contents of the loaded nib seems a bit suspect a there is advice here to add a subview in this case which also works fine however i would like to be able to instantiate the view from the storyboard also so i canplace a uiview on a parent view in the storyboardset it is custom class to mycustomviewoverride idinitwithcoder a the code i have seen the most often fits a pattern such as the followingidinitwithcodernscoder adecoder self super initwithcoderadecoder if self self initializesubviews return selfidinitwithframecgrectframe self super initwithframeframe if self self initializesubviews return selfvoidinitializesubviews typeofview view nsbundle mainbundle loadnibnamednsstringfromclaself class ownerself optionsnil objectatindex0 self addsubviewviewof course this does not work as whether i use the approach above or whether i instantiate programatically both end up recursively calling idinitwithcoder upon entering voidinitializesubviews and loading the nib from fileseveral other so questions deal with this such as here here here and here however none of the answers given satisfactorily fixes the problema common suggestion seems to be to embed the entire class in a uiviewcontroller and do the nib loading there but this seems suboptimal to me as it requires adding another file just as a wrappercould anyone give advice on how to resolve this problem and get working outlets in a custom uiview with minimum fussno thin controller wrapper or is there an alternative cleaner way of doing things with minimum boilerplate code,"['ios', 'objective-c']" +637609,python pandas not reading first column from csv file i have a simple 2 column csv file called st1csvgrid st1 1457 614 1458 657 1459 679 1460 732 1461 754 1462 811 1463 748 however when i try to read the csv file the first column is not loadeda pandasdataframefrom csvst1csv acolumnsoutputs indexust1 dtypeobjectwhy is the first column not being read,['python'] +637724,make font awesome icons in a circle i am using font awsome on some project but i have some things that i want to do with font awesome icons i can easy call icon like thisi classfa falockiis it possible to all icon always be in round circle with border somthing like this i have a pictureusing i backgroundcolor white borderradius 50 border 1x solid grey padding10pxwill do the effect but the problem is that icons are always bigger that txt or element beside any solutions,['css'] +637726,blockingcollection that thiscards old data i have a blockingcollection producer tasks add items to it and consumer tasks remove itemsnow i want to limit the number of items in the collection automatically thiscarding old data if more items are added the collection should never contain more than the and most recently added items at the same timeso if the producers add new items faster than the consumers remove them i want the consumers to process only the newest itemsi can limit the size of a blockingcollection in its constructor but of course that just means it blocks when adding more items not that it removes old items i do not want blocking on the producer side only the consumer side should block when retrieving items from an empty collectionmy current solution is a hack and only works for a size limit of 1and i am not quite sure it works reliable at all my consumer taskforeach var item in blockingcollectiongetconsumingenumerable var lastitem item var lastitemtmp item while blockingcollectiontrytakeout lastitemtmp lastitem lastitemtmp now lastitem contains the most recent item in the collection and older items have been thiscarded proceed consuming lastitem is there a cleaner solution,['c#'] +637914,generate javascript documentation directly from source code i am looking for a tool to generate the documentation for javascript functions and properties even if there are no appropriately formatted comment blocks associated with those functions or properties like doxygen doesthis comparison between jsdoc and some other documenting tools mentions that jsdoc can parse the source code to generate documentation even if there is no comment blocks something like doxygen as i mentioned above they say that all other tools only parse the comment blocksi installed jsdoc 330alpha4 from npm on node according to this instruction and i am trying to generate documentation for my project as far as i can see jsdoc does not generate any documentation for functions or properties that do not have proper comments with relevant jsdoc flagsi know jsdoc has gone through many iterations has this functionality been removed or i am not using proper switches i tried to check the command line options but could not find any switches for that i am simply using it like thisnode modulesbinjsdoc r l my project destination doci know there are other tools that can automatically add documentation blocks to the code eg smartcomments but it is not exactly what i am looking for can anyone shed some light on that,['javascript'] +637917,rails bootstrapsass assets compilation error undefined variable alertpadding all roads point to bootstrapsassreferral chainrailscast328 twitter bootstrap basics refers to which refers to which in turn exclaims there is a new official port of bootstrap to sass at which is another one of the options in the twitterbootstrap articleit is reported as an issue with the bootstraprails gem i believe i installed it correctlythe gemsgem sassrails 32 sassrails needs to be higher than 32gem bootstrapsass 311are installed tried outside and inside of assets group applicationcscss containsimport bootstraponlybut it gives me an errorwhen attempting bundle exec rake assetsprecompile it gives this errorrake abortedundefined variable alertpadding in homejoerbenvversions193p448librubygems191gemsbootstrapsass3110vendorassetsstylesheetsbootstrap alertsscsshomejoerbenvversions193p448librubygems191gemsbootstrapsass3110vendorassetsstylesheetsbootstrap alertsscss10homejoerbenvversions193p448librubygems191gemssass327libsascriptvariablerb49in performhomejoerbenvversions193p448librubygems191gemssass327libsascriptnoderb40in performhomejoerbenvversions193p448librubygems191gemssass327libsasstreevisitorsperformrb298in visit prophomejoerbenvversions193p448librubygems191gemssass327libsasstreevisitorsbaserb37in visithomejoerbenvversions193p448librubygems191gemssass327libsasstreevisitorsperformrb100in visithomejoerbenvversions193p448librubygems191gemssass327libsasstreevisitorsbaserb53in block in visit childrenhomejoerbenvversions193p448librubygems191gemssass327libsasstreevisitorsbaserb53in maphomejoerbenvversions193p448librubygems191gemssass327libsasstreevisitorsbaserb53in visit childrenhomejoerbenvversions193p448librubygems191gemssass327libsasstreevisitorsperformrb109in block in visit childrenhomejoerbenvversions193p448librubygems191gemssass327libsasstreevisitorsperformrb121in with environmenthomejoerbenvversions193p448librubygems191gemssass327libsasstreevisitorsperformrb108in visit childrenhomejoerbenvversions193p448librubygems191gemssass327libsasstreevisitorsbaserb37in block in visithomejoerbenvversions193p448librubygems191gemssass327libsasstreevisitorsperformrb320in visit rulehomejoerbenvversions193p448librubygems191gemssass327libsasstreevisitorsbaserb37in visithomejoerbenvversions193p448librubygems191gemssass327libsasstreevisitorsperformrb100in visithomejoerbenvversions193p448librubygems191gemssass327libsasstreevisitorsbaserb53in block in visit childrenhomejoerbenvversions193p448librubygems191gemssass327libsasstreevisitorsbaserb53in maphomejoerbenvversions193p448librubygems191gemssass327libsasstreevisitorsbaserb53in visit childrenhomejoerbenvversions193p448librubygems191gemssass327libsasstreevisitorsperformrb109in block in visit childrenhomejoerbenvversions193p448librubygems191gemssass327libsasstreevisitorsperformrb121in with environmenthomejoerbenvversions193p448librubygems191gemssass327libsasstreevisitorsperformrb108in visit childrenhomejoerbenvversions193p448librubygems191gemssass327libsasstreevisitorsbaserb37in block in visithomejoerbenvversions193p448librubygems191gemssass327libsasstreevisitorsperformrb128in visit roothomejoerbenvversions193p448librubygems191gemssass327libsasstreevisitorsbaserb37in visithomejoerbenvversions193p448librubygems191gemssass327libsasstreevisitorsperformrb100in visithomejoerbenvversions193p448librubygems191gemssass327libsasstreevisitorsperformrb7in visithomejoerbenvversions193p448librubygems191gemssass327libsasstreeroot noderb20in renderhomejoerbenvversions193p448librubygems191gemssass327libsassenginerb315in renderhomejoerbenvversions193p448librubygems191gemssass327libsassenginerb262in renderhomejoerbenvversions193p448librubygems191gemssassrails326libsassrailstemplate handlersrb106in evaluatehomejoerbenvversions193p448librubygems191gemstilt137libtilttemplaterb77in renderhomejoerbenvversions193p448librubygems191gemssprockets2libsprocketscontextrb193in block in evaluatehomejoerbenvversions193p448librubygems191gemssprockets2libsprocketscontextrb190in eachhomejoerbenvversions193p448librubygems191gemssprockets2libsprocketscontextrb190in evaluatehomejoerbenvversions193p448librubygems191gemsturbosprocketsrails30311libturbosprocketssprockets overridesprocessed assetrb16in initializehomejoerbenvversions193p448librubygems191gemsturbosprocketsrails30311libturbosprocketssprockets overridesbaserb18in newhomejoerbenvversions193p448librubygems191gemsturbosprocketsrails30311libturbosprocketssprockets overridesbaserb18in block in build assethomejoerbenvversions193p448librubygems191gemssprockets2libsprocketsbaserb270in circular call protectionhomejoerbenvversions193p448librubygems191gemsturbosprocketsrails30311libturbosprocketssprockets overridesbaserb14in build assethomejoerbenvversions193p448librubygems191gemssprockets2libsprocketsindexrb93in block in build assethomejoerbenvversions193p448librubygems191gemssprockets2libsprocketscachingrb19in cache assethomejoerbenvversions193p448librubygems191gemssprockets2libsprocketsindexrb92in build assethomejoerbenvversions193p448librubygems191gemssprockets2libsprocketsbaserb169in find assethomejoerbenvversions193p448librubygems191gemsturbosprocketsrails30311libturbosprocketssprockets overridesindexrb14in find assethomejoerbenvversions193p448librubygems191gemsturbosprocketsrails30311libturbosprocketssprockets overridesbundled assetrb12in initializehomejoerbenvversions193p448librubygems191gemsturbosprocketsrails30311libturbosprocketssprockets overridesbaserb22in newhomejoerbenvversions193p448librubygems191gemsturbosprocketsrails30311libturbosprocketssprockets overridesbaserb22in build assethomejoerbenvversions193p448librubygems191gemssprockets2libsprocketsindexrb93in block in build assethomejoerbenvversions193p448librubygems191gemssprockets2libsprocketscachingrb19in cache assethomejoerbenvversions193p448librubygems191gemssprockets2libsprocketsindexrb92in build assethomejoerbenvversions193p448librubygems191gemssprockets2libsprocketsbaserb169in find assethomejoerbenvversions193p448librubygems191gemsturbosprocketsrails30311libturbosprocketssprockets overridesindexrb14in find assethomejoerbenvversions193p448librubygems191gemsturbosprocketsrails30311libturbosprocketssprockets overridesstatic compilerrb41in block in compilehomejoerbenvversions193p448librubygems191gemssprockets2libsprocketsbaserb219in block in each logical pathhomejoerbenvversions193p448librubygems191gemssprockets2libsprocketsbaserb206in block 2 levels in each filehomejoerbenvversions193p448librubygems191gemssprockets2libsprocketsbaserb196in eachhomejoerbenvversions193p448librubygems191gemssprockets2libsprocketsbaserb196in each entryhomejoerbenvversions193p448librubygems191gemssprockets2libsprocketsbaserb204in block in each filehomejoerbenvversions193p448librubygems191gemssprockets2libsprocketsbaserb203in eachhomejoerbenvversions193p448librubygems191gemssprockets2libsprocketsbaserb203in each filehomejoerbenvversions193p448librubygems191gemssprockets2libsprocketsbaserb217in each logical pathhomejoerbenvversions193p448librubygems191gemsturbosprocketsrails30311libturbosprocketssprockets overridesstatic compilerrb29in compilehomejoerbenvversions193p448librubygems191gemsturbosprocketsrails30311libturbosprocketstasksassetsrake108in internal precompilehomejoerbenvversions193p448librubygems191gemsturbosprocketsrails30311libturbosprocketstasksassetsrake115in block 3 levels in top requiredhomejoerbenvversions193p448librubygems191gemsrake1004libraketaskrb246in callhomejoerbenvversions193p448librubygems191gemsrake1004libraketaskrb246in block in executehomejoerbenvversions193p448librubygems191gemsrake1004libraketaskrb241in eachhomejoerbenvversions193p448librubygems191gemsrake1004libraketaskrb241in executehomejoerbenvversions193p448librubygems191gemsrake1004libraketaskrb184in block in invoke with call chainhomejoerbenvversions193p448libruby191monitorrb211in mon synchronizehomejoerbenvversions193p448librubygems191gemsrake1004libraketaskrb177in invoke with call chainhomejoerbenvversions193p448librubygems191gemsrake1004libraketaskrb170in invokehomejoerbenvversions193p448librubygems191gemsrake1004librakeapplicationrb143in invoke taskhomejoerbenvversions193p448librubygems191gemsrake1004librakeapplicationrb101in block 2 levels in top levelhomejoerbenvversions193p448librubygems191gemsrake1004librakeapplicationrb101in eachhomejoerbenvversions193p448librubygems191gemsrake1004librakeapplicationrb101in block in top levelhomejoerbenvversions193p448librubygems191gemsrake1004librakeapplicationrb110in run with threadshomejoerbenvversions193p448librubygems191gemsrake1004librakeapplicationrb95in top levelhomejoerbenvversions193p448librubygems191gemsrake1004librakeapplicationrb73in block in runhomejoerbenvversions193p448librubygems191gemsrake1004librakeapplicationrb160in standard exception handlinghomejoerbenvversions193p448librubygems191gemsrake1004librakeapplicationrb70in runhomejoerbenvversions193p448librubygems191gemsrake1004binrake33in top requiredhomejoerbenvversions193p448binrake23in loadhomejoerbenvversions193p448binrake23in maini checked that homejoerbenvversions193p448librubygems191gemsbootstrapsass3110vendorassetsstylesheetsbootstrapscss does actually import the variablesscss file below it in the bootsrap directory first prior to alertsscss etc and it does and in variablesscss it defines alert paddingi suspect i am missing something obviousin the environmentsproductionrb file i commented everything about assets out and tried just configassetsinitialize on precompile true in accordance with the manual research so farbootstrapsass undefined variable baselineheightproper scss asset structure in railsusing twitter bootstrap with rails assets pipeline and lesstrying to import bootstrap via bootstrapsass on heroku but getting an errorrailscast 328 329 and 268 looking for cluesgoogling aboutmodifying gems bootstrapbootstrapscss to use underscore and scss various tinkering such as commenting out lines relating to assets in environmentsproductionrb commenting in only the one in the gems page manual configassetsinitialize on precompile trueissue identifiedi copied the gems contents into my assets directory which is essentially what jlongs bootstrap didits not looking at applicationcscss its ignoring what i put in there and electing to instead look into the folders and loading those files which is why it sees alertsscss first i tried changing the name of variablesscss to aavariablesscss to no avail,['ruby-on-rails'] +638033,do the c standards guarantee that unused private fields will influence sizeof consider the following structclass foo int atesting in g i get that sizeoffoo 4 but is that guaranteed by the standard would a compiler be allowed to notice that a is an unused private field and remove it from the inmemory representation of the class leading to a smaller sizeofi do not expect any compilers to actually do that kind of optimization but this question popped up in a language lawyering thiscussion so now i am curious,['c++'] +638043,base controller constructor injection in aspnet mvc with unity i have a base controller in my mvc 5 project which implements some shared functionality this functionality requires some dependencies i am using unity 3 to inject these implementations into my controllers a pattern which has worked fine until i switched my controllers to inherit from this base controller now i am running into the following issuepublic class basecontroller controller private readonly iservice service public basecontrolleriservice service service service public class childcontroller basecontroller private readonly idifferentservice differentservice public childcontrolleridifferentservice differentservice differentservice differentservice this is understandably throwing an error of basecontroller does not contain a constructor that takes 0 arguments unity is not resolving the construction of the basecontroller so it cannot inject the dependencies into it i see two obvious ways of solving this issue1 explicitly call the basecontroller ctor and have each childcontroller ctor inject the basecontrollers dependenciespublic class childcontroller basecontroller private readonly idifferentservice differentservice public childcontrolleridifferentservice differentservice iservice baseservice basebaseservice differentservice differentservice i do not like this approach for several reasons one because the childcontrollers are not making use of the additional dependencies so it causes constructor bloat in the child controllers for no reason and more importantly if i ever change the constructor signature of the base controller i have to change the constructor signatures of each child controller2 implement the basecontrollers dependencies via property injectionpublic class basecontroller controller dependency public iservice service get set public basecontroller i like this approach better i am not using any of the dependencies in the basecontrollers constructor code but it makes the dependency injection strategy of the code inconsistent which is not ideal eitherthere is probably an even better approach which involves some sort of basecontroller dependency resolution function that calls on the unity container to sort out the ctors method signature but before i get into writing anything too involved i was wondering if anyone had solved this problem before i found a few solutions floating around on the web but they were workarounds such as service locator which i do not want to usethanks,['c#'] +638073,net web api 2 authorize attribute my application is setup where all requests except login must be authorized using the authorization attribute in web api eg authorize httpget routeapiaccountprofile public applicationuser profile return usermodel and only the login needs to not authorize since thats where you get the token allowanonymoushttppost routeapiaccountloginpublic async taskihttpactionresult loginloginviewmodel model instead of having to add the authorize attribute to all my routes is there a way to set it globally,"['c#', '.net']" +638105,mvc5 vs2012 identity createidentityasync value cannot be null i am trying to setup oauth for a an mvc5 site in vs2012i am using fluent nhibernate i have setup my own userstore and pass in a repository object to access nhibernate session object i pass my store into the default aspnet usermanager provider this eventually worked for local registration and logging in i am not trying to setup connecting registering with facebookit gets a successful account adds a user in the user table adds a record in the logins table and then blows up i have not implements claims in the user store or put a claims collection in the user object not sure if this is actually required i was stripping everything back that might be going wrong to find the source of the issuethe line that blows up is in the account controllervar identity await usermanagercreateidentityasyncuser defaultauthenticationtypesapplicationcookie within this methodprivate async task signinasyncidentityuser user bool ispersistentthis is the end of the stack traceargumentnullexception value cannot be nullparameter name value systemsecurityclaimsclaimctorstring type string value string valuetype string issuer string originalissuer claimsidentity subject string propertykey string propertyvalue 14108789 systemsecurityclaimsclaimctorstring type string value string valuetype 62 microsoftaspnetidentitycreateasyncd 0movenext 481 systemruntimecompilerservicestaskawaiterthrowfornonsuccesstask task 144 systemruntimecompilerservicestaskawaiterhandlenonsuccessanddebuggernotificationtask task 84 systemruntimecompilerservicestaskawaiter1getresult 49 webcontrollerssigninasyncd 42movenext in dgoogle drivedevelopmentgoalmanagementwebcontrollersaccountcontrollercs375 systemruntimecompilerservicestaskawaiterthrowfornonsuccesstask task 144 systemruntimecompilerservicestaskawaiterhandlenonsuccessanddebuggernotificationtask task 84 webcontrollersexternalloginconfirmationd 35movenext in dgoogle drivedevelopmentgoalmanagementwebcontrollersaccountcontrollercs311 systemruntimecompilerservicestaskawaiterthrowfornonsuccesstask task 144 systemruntimecompilerservicestaskawaiterhandlenonsuccessanddebuggernotificationtask task 84public class identityuser iuser public identityuser logins new listidentityuserlogin public string id get set public string username get set public string passwordhash get set public string securitystamp get set public ilistidentityuserlogin logins get set public class identityuserlogin public string loginprovider get set public string providerkey get set i can include my userstore code if wanted i did not put it in as it is a large file and might detract from the issuei am not sure why it is even trying to create the claim object and why it is blowing up as i only have vs2012 i have been patching it all together from examples online mainlyas suggested by shoe i inherited from usermanagerpublic class nhibernateaspnetusermanagertuser usermanagertuser where tuser identityuser public nhibernateaspnetusermanageriuserstoretuser store basestore public override taskclaimsidentity createidentityasynctuser user string authenticationtype claimsidentity identity new claimsidentity return taskfromresultidentity it now no longer throws an error but does not actually authenticate me how ever many times i use the facebook register loginto summarize with shoes info i tried both overriding usermanagercreateidentityasync withpublic override taskclaimsidentity createidentityasynctuser user string authenticationtype var identity new claimsidentity identityaddclaimnew claimclaimtypesname userusername return taskfromresultidentity and also trying to implement iuserclaimstore with the returning default empty listthe first will not through an error but does not end up authenticated the later will still through the odd claim systemsecurityclaimsclaimctor erroreditfound out why the ctor error was occurring the user object was coming back without the id so the default usermanager was getting upset fixed that and used the default usermanager which now no longer throws an error but still does not log the user in the identity object it returns looks good from what i can tell,['asp.net'] +638114,rotating axes label text in 3d matplotlib how do i rotate the zlabel so the text reads bottom top rather than top bottomimport matplotlibpyplot as pltfrom mpl toolkitsmplot3d import axes3dfig pltfigureax figadd subplot1 projection3daxset zlabellabel text flipped rotation90 axazim 225pltshowi want this to hold no matter what my axazim setting is this seems to be an old feature request on github but there is not a work on it is there a workaround,['python'] +638185,chaining pluck and flatten with lodash this works but how can i chain itallweeks flatten pluckdatesmonths weeksalldays flatten pluckallweeks daysi have triedalldays chaindatesmonthspluckweeksflattenpluckdaysflattenand thisalldays datesmonthspluckweeksflattenpluckdaysflatten,['javascript'] +638215,android geocoder reverse location reliable way to get the city i have searched quite a bit without luck so farthe android geocoder returns the androidlocationaddress objectthe city as far as i understood should be returned in getlocalityit seems within usa this works well outside noti am writing an international app and struggle to find a solution to find out the city of a geolocationhere the output from czech republicprague addressaddresslines0psohlavca 176421147 00 pragueprague 42czech republicfeature2adminhlavna masto prahasubadminpraguelocalitynullthoroughfarepsohlavca postalcode147 00countrycodeczcountrynameczech republichaslatitudetruelatitude500276543haslongitudetruelongitude144183926phonenullurlnullextrasnulocality is null the city is within subadmin the address itself is ok so the geocoder server seems to know the cityhere some ore random eu examples but locality works partlyaddressaddresslines0nad lesem 440341147 00 pragueprague 42czech republicfeature34adminhlavna masto prahasubadminpraguelocalitynullthoroughfarenad lesempostalcode147 00countrycodeczcountrynameczech republichaslatitudetruelatitude5002424haslongitudetruelongitude144117568phonenullurlnullextrasnulladdressaddresslines0hauner straae 4184431 heldenstein2germanyfeature4adminnullsubadminnulocalityheldensteinthoroughfarehauner straaepostalcode84431countrycodedecountrynamegermanyhaslatitudetruelatitude482540274haslongitudetruelongitude123413535phonenullurlnullextrasnulladdressaddresslines0igler straae16020 innsbruck2austriafeatureigler straaeadmintyrolsubadmininnsbrucklocalityinnsbruckthoroughfareigler straaepostalcode6020countrycodeatcountrynameaustriahaslatitudetruelatitude472465698haslongitudetruelongitude114054237phonenullurlnullextrasnulladdressaddresslines0durnberg 2415724 stuhlfelden2austriafeature24adminsalzburgsubadminzell am see thistrictlocalitynullthoroughfaredurnbergpostalcode5724countrycodeatcountrynameaustriahaslatitudetruelatitude4732373haslongitudetruelongitude124960482phonenullurlnullextrasnulladdressaddresslines0u rohaaova12ch kasaren 141100 00 prague 102czech republicfeature14adminhlavna masto prahasubadminpraguelocalityprague 10thoroughfareu rohaaova12ch kasarenpostalcodenullcountrycodeczcountrynameczech republichaslatitudetruelatitude500704092haslongitudetruelongitude144673473phonenullurlnullextrasnullmaybe the fault is on me but to me it seems like depending on the country and area the city will be found in different fieldshowever the address itself mostly seems to be good enough to send a postal letterhas someone written a clever function which tries to make more sense out of the geocoder results it is a pity to see that google has the information stored but does not provide it properly,['android'] +638229,is it possible to use optimizely or other dom manipulating ab testing tools on a site using angularjs i am looking to use optimizely on a site where we will use angularjs but from what i understand that will be difficult because the whole purpose of angularjs is to not manipulate the dom and optimizely works by manipulating the dom does anyone have any guidance toward documents as to how to make using these tools together possible perhaps a structure where i could create directives to help the tool work,['javascript'] +638276,laravel 41 eloquent offset limit how to limit returned data from eloquent i tried with thisdata productalltake4skip3and it return the error message call to undefined method illuminatedatabaseeloquentcollectionskipit seems like eloquent do not support skip so how can i offset limit the data from eloquentthank you,['php'] +638350,what is meant by public function cannot be overridden if a patch is necessary in addys description of the revealing module pattern a thisadvantage of this pattern is that if a private function refers to a public function that public function cannot be overridden if a patch is necessary this is because the private function will continue to refer to the private implementation and the pattern does not apply to public members only to functionsdoes anyone have an example of what he means by thislink to the revealing module pattern referenced above,['javascript'] +638414,mortar flow with third party libraries hooked to activity lifecycle some third party libraries use hooks into the activity lifecycle to work correctly for instance the facebook sdk i am having some trouble figuring out how to reconcile this model cleanly with a singleactivity flowmortar setup for instance if i want to use facebook login as part of a login flow w flowviewflowowner but not otherwise in the activity whats the smartest way to pull this off if you need hooks for that particular flow in oncreate onresume onpause ondestroy onsaveinstancestate onactivityresult etcit is not immediately obvious what the cleanest path is create an observable for each lifecycle activity stage and subscribe the flow to it seems like that path quickly devolves to the same android lifecycle if youre not careful is there a better wayi love the single activity model and i would really like to keep everything managed by flowmortar and not activities if possible or am i thinking about this in a way that is fundamentally making it more difficult than it should be,['android'] +638515,find all the common time from list of time provided by each user i had asked this question previously the idea is same except that i have to find all the common time within certain timespanbackgroundlets supposei want to meet some peoples and i say i want to meet certain peoples between datetime x20140216 090 to datetime y20140226 050 and i say i want to the meeting to last for at least n number of hoursthen the peoples i want to meet with will reply saying i will be available in following dates date1certain date from certain start time to certain end time date2certain date from certain time to certain timeand so on objective i then have to find if there exists a time range that includes in all the users responselets consider these are the responsesattendee1some guididresponse1 start time20140223 0900 am endtime 20140223 1100 amresponse2 start time20140224 10 am endtime 20140224 1200 pmresponse3 start time20140225 10 am endtime 20140225 1100 amresponse4 start time20140223 0100 pm endtime 20140217 500 pmattendee2some guididresponse1 start time201402 0900 am endtime 201402 0500 pmresponse2 start time20140223 0900 am endtime 20140223 0500 pmresponse3 start time20140225 0900 am endtime 20140225 1200 pmattendee3some guididresponse1 start time201402 1100 am endtime 201402 0200 pmresponse2 start time20140223 0400 pm endtime 20140223 0300 pmresponse3 start time20140223 430 pm endtime 20140223 0530 pmresponse4 start time20140224 0200 am endtime 20140224 0500 pmresponse5 start time20140225 1100 am endtime 20140225 1200 pmso if possible i should come up with something that will say here are the matches found if not then just find if the common time exists for all the users or nottime x to time y difference between x and y should be at least the timespan mentioned number of attendee in this match ntype int 1 or 2 or as many match as foundtime a to time b number of attendee in this match netcps it is a mvc 51 application and database is created using code first approachso in database there is table called appointment which stores the startdatetime and enddatetimehere are my datamodelspublic class appointment key public guid id get set public virtual icollectionattendee attendees get set public datetime startdatetime get set public datetime enddatetime get set public timespan minappointmentduration get set and between these dates peopleattendee attending will give their response each personwho will respond their information is stored in database table called attendeespublic class attendee public guid attendeeid get set public virtual icollectionresponse responses get set and for each user their response is stored in responses table whose model would look likepublic class response key databasegenerateddatabasegeneratedoptionidentity public int id get set public guid attendeeid get set public datetime startdatetime get set public datetime enddatetime get set this is what i have done but it does not workpublic class commontime public datetime start get set public datetime end get set public timespan minappointmenttime get set public int numattendees get return responsesselectx xattendeeidthistinctcount public listdatamodelsresponse responses get set public commontimedatamodelsresponse response timespan time responses new listdatamodelsresponse start responsestartdatetime end responseenddatetime minappointmenttime time public void mergecommontimedatamodelsresponse response ifstart responsestartdatetime responseenddatetimeend start responsestartdatetime end responseenddatetime ifendstartminappointmenttime responsesaddresponse public listcommontime findcommonmatchesguid appointmentid var appointment dbappointmentsfindappointmentid var attendees appointmentattendeestolist var matches new listcommontime bool isfirstattendee true foreach var attendee in attendees if isfirstattendee foreach var response in attendeeresponses matchesaddnew commontimeresponse appointmentminappointmentduration isfirstattendee false else foreach var response in attendeeresponses matchesforeachx xmergecommontimeresponse return matches so in this case if attendee xwith some guid id gives hisher availability asand attendee y gives hisher availibility asthis is the common match i getwhich is not what i want as i explainedso what should i do to get what i wanteditbased upon answer from zache public class meeting public datetime start get set public datetime end get set public listdatamodelsattendee attendees get set public class requirement public datetime start get set public datetime end get set public timespan minhours get set public int minattendees get set public ienumerablemeeting meetings var possiblemeetings new listmeeting var availablehours end starttotalhours for var i 0 i availablehours minhourshours i yield return new meeting start startaddhoursi end startaddhoursiminhourshours public class scheduler public ienumerablemeeting schedulerequirement req listdatamodelsattendee attendees var fullmatches new listmeeting var partialmatches new listmeeting foreach var m in reqmeetings foreach var a in attendees if fullmatchesany if aresponsesanyr rstartdatetime mstart renddatetime mend if mattendees null mattendees new listdatamodelsattendee a else mattendeesadda else break if we found one full match we are not interested in the partials anymore else if aresponsesanyr rstartdatetime mstart renddatetime mend if mattendees null mattendees new listdatamodelsattendee a else mattendeesadda if mattendees null if mattendeescount attendeescount fullmatchesaddm else if mattendeescount reqminattendees partialmatchesaddm return fullmatchesany fullmatches partialmatches in repositorypublic ienumerablemeeting findcommonmatchesguid appointmentid var appointment dbappointmentsfindappointmentid var attendees appointmentattendeeswherea ahasresponded truetolist var req new requirement start appointmentstartdatetime end appointmentenddatetime minhours appointmentminappointmentduration minattendees 1 var schedule new scheduler var schedules scheduleschedulereq attendees return schedules startdate 2242014 1130 amthat i set while creating appointmentenddate 2252014 1130 amwhen the first user responds with following datamatches resultwhen second attendee responds with following datamatches resulthere the common matches should have beenmatch1 2242014 10 am to 2242014 110 am match2 2252014 90 am to 2252014 110 am,['c#'] +638526,errors creating stdvector of local structure include vectorint main struct st int a stdvectorst v for stdvectorstsize type i 0 i vsize i voperatoria i 1 via i1 the above code gives the following errors when compiled with gnu g compilertestcpp in function aint mainatestcpp619 error template argument for atemplateclass alloc class stdallocatora uses local type amainstatestcpp619 error trying to instantiate atemplateclass alloc class stdallocatoratestcpp619 error template argument 2 is invalidtestcpp622 error invalid type in declaration before aa tokentestcpp724 error template argument for atemplateclass alloc class stdallocatora uses local type amainstatestcpp724 error trying to instantiate atemplateclass alloc class stdallocatoratestcpp724 error template argument 2 is invalidtestcpp737 error expected initializer before aiatestcpp744 error aia was not declared in this scopetestcpp750 error request for member asizea in ava which is of nonclass type aintatestcpp820 error request for member aoperatora in ava which is of nonclass type aintawhy i am not able to create vector of structures,['c++'] +638562,what is the difference between javascript object and primitive types stoyan stefanov in his excellent book objectoriented javascript says any value that does not belong to one of the five primitive types listed above is an objectwith five primitive types he means number string boolean undefined and null however in google chrome console it seems like number is not primitive type at all compared to c primitive types like int it looks like the primitive number has methodsvar a 22consolelogatofixed logs 2thus i assumed that i can work with number as with an object so i tried to assign a property to itvar a 2afoo barconsolelogafoo logs undefinedi do not understand that behavior if number has a method it should behave like object should not it it even has a prototypenumberprototypefoo barvar a 2consolelogafoo logs barso what is the magic behind this how javascript treats objects versus primitive types i would rather not use the word primitive and substitute it with simple objects as i see it those are objects which cannot be extended with new properties however they are constructed through their constructor and also have prototype which can be extended like with normal objects,['javascript'] +638673,why is google pagespeed insights telling me to minify javascript css using rails 32 with js css compression and how to fix i know it is not a lot i could save in kb but to achieve a better score in google pagespeed insights and thus probably better seo ranking how can i fix thisfrom urlwtradebenchcom minify javascript for the following resources to reduce their size by 28kib 2 reduction minifying tionea806932c941fb875b7512a557ebead3js could save 28kib 2 reduction after compressionit tells me the same thing for my css filefrom my productionrb fileconfigassetscompress trueconfigassetsjs compressor uglifiernewmangle trueconfigassetscss compressor yuilooking at the uglifier docsoptions i do not see how i could configure it to get the last 2kb anyone has an idea how to get it to compress the last tiny bit to remove the pagespeed notice about it maybe use another compressor than uglifierthanks,['ruby-on-rails'] +638711,afnetworking 20 queue request when device is offline with setreachabilitystatuschangeblock does nothing i have been trying to come up with a solution to queue http requests using afnetworking when the device is offline so when it goes back online the requests gets done as far as i have been able to understand this is possible setting the setreachabilitystatuschangeblock parameterso far this is what i have viewcontrollerhinterface xyzticketviewcontroller uiviewcontrollernsurlconnectiondelegate this is from before i started using afnetworking i am intending to change all the requests to use afnetworking in the near future end viewcontrollermimport afhttprequestoperationmanagerhimport afnetworkreachabilitymanagerhinterface xyzticketviewcontroller voidviewdidloadnsurl baseurl nsurl urlwithstringafhttprequestoperationmanager manager afhttprequestoperationmanager alloc initwithbaseurlbaseurlnsoperationqueue operationqueue manageroperationqueuemanagerreachabilitymanager setreachabilitystatuschangeblockafnetworkreachabilitystatus status switch status case afnetworkreachabilitystatusreachableviawwan case afnetworkreachabilitystatusreachableviawifi operationqueue setsuspendedno nslogwifi break case afnetworkreachabilitystatusnotreachable default operationqueue setsuspendedyes nslogoflline baby break nsdictionary parameters action login user pass howdoyouturnthisonmanager get parametersparameters successafhttprequestoperation operation id responseobject nslogjson responseobject failureafhttprequestoperation operation nserror error nslogerror errori cannot find any example but i read here that it is possible but so far anything happens when the online status changeshope you can help me out,['ios'] +638716,angularjs sailsjs i am developing an app that can utilize sailsjs for backend and angularjs for frontend i thought that i will create an angular app using yeomanangular generator and once i am done with the frontend logic i will create a sails app usingnpm install g sailssails new appand then i will transfer all my angularjs files to the sails folderbut the thing is that angularjs creates creates a folder hierarchy like this and on running grunt server a thist folder is created which contains the final production versionon the other hand after sails new app folder hierarchy for sails app is likeapiadapterscontrollersmodelspoliciesservicesassetsimagesjsstylesfaviconicorobotstxtconfignode modulesviewshome403ejs404ejs500ejslayoutejsgruntfilejsappjspackagejsonso my questions arenow how do i transfer my angular files to this sails directory and how should i structure itsince sails uses sails lift to start a server and angular uses grunt server which one of those should i use to start the server for my sailsjs angularjs app and what about the thist folder which is created after angularjswhat changes will i have to make in the gruntfilejs since it should now contain the code from both angular and sailswhere should i keep my different views and style files and how should i access those form angular or from sailsi think lot of people are facing this similar problem since angularjs and sailsjs are all the rage currently there should be a robust boilerplate to create an angularjs sailsjs app which sadly is missing right now,['javascript'] +638763,connecting to a device using the chromebluetooth api i have been trying to create a chrome app that uses the chromebluetooth api to connect to and communicate with the texas instruments cc2541 sensortag devicethe code here detects the sensortag and gets the device information but the getprofiles and getservices methods called on the device both return empty and the connect method gives the error profile not found invalid uuid i have tried multiple variations of uuids taken from the example sensortag android app as can be seen in the code but all give the same invalid uuid erroreven if you cannot fix this particular problem it would be good to hear from anyone who has had any joy using the chromebluetooth api at all my experience so far is that it is too much of a moving target to really use yes i do know it is dev only but i would really like to get it working if possiblethanks for looking any help or ideas much appreciatededit additional platform informationi first tried running this on windows 7 with a csr 40 bluetooth dongle but this turns out to be completely futile with the generic windows 7 bt driver chrome can see the adapter and detect bt devices but the driver does not support low energy so cannot detect the device i want it to using the csr driver which does support le and which i can use in windows bluetooth devices to connect to le devices chromebluetooth cannot detect the bluetooth adapter at allso now i am working with an acer c720 chromebook which looks like it should work but i just get the invalid uuid message whatever i try although the chrome os and winmaclinux dev versions of chrome are out of step with updates chrome os was behind the others for a while but has now caught up so for a time required different format manifestjson files to launch the app on the different platformsmainjs i have tried multiple variations of known uuids for device all give profile not found invalid uuid var profiles uuid irt serv from example android app uuid f0aa045140b0 name sensortag1lc uuid f0aa045140b0 name sensortag1uc uuid f0aa00 name sensortag1shortlc uuid f0aa00 name sensortag1shortuc uuid irt data from example android app uuid f0aa01045140b0 name sensortag2lc uuid f0aa01045140b0 name sensortag2uc uuid f0aa01 name sensortag2shortlc uuid f0aa01 name sensortag2shortuc uuid irt conf from example android app uuid f0aa02045140b0 name sensortag3lc uuid f0aa02045140b0 name sensortag3uc uuid f0aa02 name sensortag3shortlc uuid f0aa02 name sensortag3shortuc uuid irt peri from example android app uuid f0aa03045140b0 name sensortag4lc uuid f0aa03045140b0 name sensortag4uc uuid f0aa03 name sensortag4shortlc uuid f0aa03 name sensortag4shortuc uuid key serv from example android app uuid 0ffe01080805f9b34fb name sensortag5lc uuid 0ffe01080805f9b34fb name sensortag5uc uuid 0ffe0 name sensortag5shortlc uuid 0ffe0 name sensortag5shortuc uuid key data from example android app uuid 0ffe101080805f9b34fb name sensortag6lc uuid 0ffe101080805f9b34fb name sensortag6uc uuid 0ffe1 name sensortag6shortlc uuid 0ffe1 name sensortag6shortuc listener to deal with initial connectionchromebluetoothonconnectionaddlisteneronconnected onadapterstatechanged callback for debug onlychromebluetoothonadapterstatechangedaddlistenerfunctionnewstatus logonadapterstatechanged jsonstringifyarguments logs debug messages to app windowfunction logmsg var msg str typeofmsg object jsonstringifymsg msg consolelogmsg str var l documentgetelementbyidlog if l linnertext msg str n function that is called on connection to devicevar onconnected functionsocket logsuccess connected to sensortag logsocket jsonstringifysocketfunction recorddevicedevice logfound bt device jsonstringifydevice if devicename sensortag loggot sensortag stop thiscovery and then connect to sensortag chromebluetoothstopthiscoveryconnecttosensortagdevice function connecttosensortagdevice loggetting profiles of sensortag chromebluetoothgetprofilesdevice device functionprofiles loggot profiles jsonstringifyprofiles chromebluetoothgetservicesdeviceaddress deviceaddress functionservices loggot services jsonstringifyservices for var i 0 i profileslength i chromebluetoothconnect device device profile profilesi function logconnect called jsonstringifyarguments if chromeruntimelasterror logconnection error chromeruntimelasterrormessage function finddevices logfinding devices chromebluetoothstartthiscoverydevicecallback recorddevice app execution begins here add all profiles to try connection laterfor var i 0 i profileslength i logadding profile profilesi chromebluetoothaddprofileprofilesi function logsensortag profile added chromebluetoothgetadapterstate functionresult if resultpowered false resultavailable false logerror no bluetooth adapter available else logbluetooth adapter enabled finddevices indexhtmlhtmlheadheadbody div idlogdivbodyscript srcmainjsscripthtmlmanifestjson manifest version 2 name connect to sensortag description connects to ti sensortag version 10 minimum chrome version 30 app background scripts backgroundjs bluetooth backgroundjschromeappruntimeonlaunchedaddlistenerfunction chromeappwindowcreateindexhtml id window1 bounds width 640 height 480,['javascript'] +638806,navigation drawer items not registering click event i am struggling to get the navigation drawer items to register and start and intent for a new activitythe drawer opens fine and is thisplayed correctly but nothing happens when i click on the items in the list here is my code that is taken from the google tutorials mtitle mdrawertitle gettitle mtitles getresourcesgetstringarrayrarraymenu items mdrawerlayout drawerlayout findviewbyidriddrawer layout mdrawerlist listview findviewbyidridleft drawer set a custom shadow that overlays the main content when the drawer opens mdrawerlayoutsetdrawershadowrdrawabledrawer shadow gravitycompatstart set up the drawers list view with items and click listener mdrawerlistsetadapternew arrayadapterstringthis rlayoutdrawer list item mtitles mdrawerlistsetonitemclicklistenernew draweritemclicklistener enable actionbar app icon to behave as action to toggle nav drawer getactionbarsetthisplayhomeasupenabledtrue getactionbarsethomebuttonenabledtrue actionbardrawertoggle ties together the the proper interactions between the sliding drawer and the action bar app icon mdrawertoggle new actionbardrawertoggle this host activity mdrawerlayout drawerlayout object rdrawableic drawer nav drawer image to replace up caret rstringdrawer open open drawer description for accessibility rstringdrawer close close drawer description for accessibility public void ondrawerclosedview view getactionbarsettitlemtitle invalidateoptionsmenu creates call to onprepareoptionsmenu public void ondraweropenedview drawerview getactionbarsettitlemdrawertitle invalidateoptionsmenu creates call to onprepareoptionsmenu mdrawerlayoutsetdrawerlistenermdrawertoggle if savedinstancestate null selectitem0 override public boolean oncreateoptionsmenumenu menu menuinflater inflater getmenuinflater inflaterinflatermenumain menu return superoncreateoptionsmenumenu called whenever we call invalidateoptionsmenu override public boolean onprepareoptionsmenumenu menu if the nav drawer is open hide action items related to the content view boolean draweropen mdrawerlayoutisdraweropenmdrawerlist menufinditemridaction websearchsetvisibledraweropen return superonprepareoptionsmenumenu override public boolean onoptionsitemselectedmenuitem item the action bar homeup action should open or close the drawer actionbardrawertoggle will take care of this if mdrawertoggleonoptionsitemselecteditem return true return superonoptionsitemselecteditem the click listner for listview in the navigation drawer private class draweritemclicklistener implements listviewonitemclicklistener override public void onitemclickadapterview parent view view int position long id selectitemposition private void selectitemint position switch position case 1 new datataskmainactivitythisexecute mainactivitythisfinishset this activity to finish so no loop back intent intentnew intentmainactivitythissplashscreenclass startactivityintent break case 2 ftreplaceridcontent frame new secondfragment settitlesecond break case 3 ftreplaceridcontent frame new thirdfragment settitlethird break default break update selected item and title then close the drawer mdrawerlistsetitemcheckedposition true settitlemtitlesposition mdrawerlayoutclosedrawermdrawerlist override public void settitlecharsequence title mtitle title getactionbarsettitlemtitle when using the actionbardrawertoggle you must call it during onpostcreate and onconfigurationchanged override protected void onpostcreatebundle savedinstancestate superonpostcreatesavedinstancestate sync the toggle state after onrestoreinstancestate has occurred mdrawertogglesyncstate override public void onconfigurationchangedconfiguration newconfig superonconfigurationchangednewconfig pass any configuration change to the drawer toggls mdrawertoggleonconfigurationchangednewconfig fragment that appears in the content frame shows a planet public static class planetfragment extends fragment public static final string arg planet number planet number public planetfragment empty constructor required for fragment subclasses override public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate view rootview inflaterinflaterlayoutfragment planet container false int i getargumentsgetintarg planet number string planet getresourcesgetstringarrayrarrayplanets arrayi int imageid getresourcesgetidentifierplanettolowercaselocalegetdefault drawable getactivitygetpackagename imageview rootviewfindviewbyidridimagesetimageresourceimageid getactivitysettitleplanet return rootview if you can provide any help that would be great as i am really pulling my hair out on this thank you,['android'] +638826,javascriptember toggle boolean value of variable i know that there is the set method to set a boolean to true or false but i want to know if there a method like set except it toggles the value of a booleanin this case the boolean isediting is being set to trueiseditingfalseactions edit functioncategory categorysetisediting true consolelogthisgetisediting here is the html if isediting div classcategorytext view embertextfield valuebindingname actionturnoffeditmode divelse div classcategorytext linkto category this name linkto divif,['javascript'] +638831,passport nodejs not returning refresh token i am trying to return a refreshtoken using the passport module of nodejshowever i am using the code below and i am unable to log any refresh token but the access token works fineis there any way to specify the accesstype offline for this module to hopefully return thisvar googlestrategy requirepassportgoogleoauthoauth2strategy passportusenew googlestrategy clientid google client id clientsecret google client secret callbackurl httpmyurlauthcallback functionaccesstoken refreshtoken profile done consolelogrefreshtoken processnexttickfunction return donenull tokenaccesstoken rtokenrefreshtoken profileprofile this returns the refreshtoken as undefinedany help would be greatly appreciated,['javascript'] +638849,can i do some kind of realtime media decoding with javascript i have implemented an mjpegavi1 parser which extracts jpegformatted frames from a mjpeg filei can draw an image with extracted jpeg file on dom with canvas element and i can also export image pixel data from it with contextgetimagedatacan i make some kind of video stream and append those extracted data in realtime so that user can play it without long delay i know i can manually make an videolike ui with canvas element but i found that media source extensions currently allows native video tag receive encoded byte stream format i am curious if i can do that with raw pixel data,['javascript'] +638956,executing aws cli command from php results in unable to locate credentials i am trying to run aws s3 cp command from within php code using shell exec following is the php codeecho shell execsudo aws s3 cp s3bucketsomefoldersomefile s3bucketsomeotherfoldersomefile region apsoutheast1 acl publicreadthe file is not getting copied and the output from echo is the followingunable to locate credentials completed 1 parts with files remainingnote1 i have already set the credentials using aws configure commandnote2 if i run the exact same command directly from terminal it works fine any idea,['php'] +638969,is it possible to completely avoid heap fragmentation for example if deallocations of dynamic memory are always done in opposite direction to allocations in that case is it guaranteed that heap will not become fragmentedand from theoretical point of view does there exist some realistic way for a nontrivial application to manage memory to completely avoid heap fragmentation after each atomic change in heap is heap still unfragmented,['c++'] +638989,reasons for not directly write servlets for creating a rest api in my current company we are starting a new project that will be a rest api in java deployed in a servlet container like tomcat in my previous experience using rest frameworks like jaxrs with jersey jboss rest easy spring mvc i know what are some of the advantages of using a framework like those over writing directly the servlets for processing the requests of course we know that the mentioned frameworks still use servlets under the coversi am finding difficult to convince them as they are proposing to write servlets thinking it is better for performance which can be the case but i think the overhead of using one of those frameworks should be insignificant for a rest apihere are my reasons1 less boilerplate and more concise code which is easier to maintain and test with a jaxrs framework or springmvc you can define a rest resource very easily by writing methods with annotations indicating the path of the resource the http method to use query and url parameters headers like encoding accepted etcexamplegetpathusersproducesmediatypeapplication json public userlist getusersqueryparamgroup string group return userservicefindusersgroupwith servlets you will need at least something like thismap the url for each servlet in webxml which is not necessary in and above servlet 30servlet servletnameusersservletservletname servletclasstestusersservletservletclaservletservletmapping servletnameusersservletservletname urlpatternusersurlpatternservletmappingthen inside the servlet classpublic void dogethttpservletrequest request httpservletresponse response throws servletexception ioexception string group requestgetparametergroup responsesetcontenttypeapplicationjson printwriter out responsegetwriter jsonserializer somejsonserializer new jsonserializer string json somejsonserializerserializeuserservicefindusersgroup outprintjson2 adaptability the mentioned frameworks allow you to easily add features to your application that otherwise you will need to do it manually like using multiple media type inputs and outputs for example making a service to return xml or json or any other depending on the accept header frameworks like springmvc and jersey make it very easy to configure serializersdeserializers for your requests responses3 rest best practices normally those frameworks are built over a solid understanding of the best practices to be followed by a rest api and are defined based on standards of the rest architecture which makes easier to build a solid and standard conforming application in the other hand servlets give you a so high level of freedom on how to process your requestsresponses that it will be more difficult to realize that you are not being restfull at allany other,['java'] +639000,chrome speech synthesis with longer texts i am getting a problem when trying to use speech synthesis api in chrome 33 it works perfectly with a shorter text but if i try longer text it just stops in the middle after it has stopped once like that the speech synthesis does not work anywhere within chrome until the browser is restartedexample code function speaktext var msg new speechsynthesisutterance var voices speechsynthesisgetvoices msgvoice voices10 msgvoiceuri native msgvolume 1 msgrate 1 msgpitch 2 msgtext text msglang enus speechsynthesisspeakmsgspeakshort textspeakcollaboratively administrate empowered markets via plugandplay networks dynamically procrastinate b2c users after installed base benefits dramatically visualize customer directed convergence without revolutionary roi efficiently unleash crossmedia information without crossmedia value quickly maximize timely deliverables for realtime schemas dramatically maintain clicksandmortar solutions without functional solutionsspeakanother short textit stops speaking in the middle of the second text and i cannot get any other page to speak after thatis it a browser bug or some kind of security limitation,['javascript'] +639102,creating my own enhanced for loop if i were to create my own data type in java i was wondering how i would do it to make it enhanced for loop compatible if possiblefor examplesystemoutprintlnobject this implicitly calls the objects tostring methodnow if i wanted to do a enhanced for loop with my own data type how would i do itmyliststring list new mylistforstring s list systemoutprintlnsis there a way to make my data type be recognized as an array so i could just pop it into a for loop as so do i extend some class i would rather not extend a premade class such as arraylist or list but maybe there is some other class like comparable t thank you,['java'] +639104,how to avoid actionmailerpreview committing data to development database i am using rails 410beta1s new action mailer previews and have the following codeclass eventinvitationpreview actionmailerpreview def invitation email invite factorygirlcreate event invitation for match from user to user eventinvitationmailerinvitation emailinvite endendthis is all good until i actually try to preview my email and get an error saying that validation on a user object failed due to duplicate email addresses turns out that actionmailerpreview is writing to my development databasewhile i could work around the validation failure or use fixtures instead of factories is there any way to avoid actionmailerpreview writing to the development database eg use the test database instead or am i just doing it wrong,['ruby-on-rails'] +639125,afnetworking 20 http post progress how can i get the progress of an afhttprequest i have tried searching all over the net i am using afhttprequestoperationmanager manager afhttprequestoperationmanager manager nsdictionary params gameid datas0 p1 datas1 p2datas2 turndatas3 managerrequestserializer afhttprequestserializer serializer managerresponseserializer afhttpresponseserializer serializer manager posthttplocalhostthepathisprivatethefilephp parametersparams successafhttprequestoperation operation id responseobject failureafhttprequestoperation operation nserror error is there like a property or method i can use to access the progress of an afnetworking 20 http post,"['ios', 'objective-c']" +639206,passing data to d3svgline soi have a javascript object likeobject data array39 time array39objectdata is an array of values while objecttime is an array of javascripts date objectsi am trying to plot a line graph in d3 the relevant parts of my code line function var line d3svgline xfunctiondi return xdtime yfunctiondi return yddata draw line svgappendpath datumdata attrclass line attrd linethe axes are in place like they should be with the data but the line does not show up i am guessing i am not returning the values to the x and y accessors of the line function like the way they should be any pointerseditfunction drawdata margins and stuff var margin top 20 right 20 bottom 20 left 40 var width 940 marginleft marginright var height 500 margintop marginbottom x and y axis data var xaxisdata datatime var yaxisdata datadata scales var x d3timescaledomaind3extentxaxisdatarange0 width var x d3scalelineardomain100 500range0 width var y d3scalelineardomaind3extentyaxisdatarangeheight 0 axes var xaxis d3svgaxisscalexorientbottom var yaxis d3svgaxisscaleyorientleft base layer var svgcontainer d3selectgraphappendsvg attrwidth width marginleft marginright attrheight height margintop marginbottom appendg attrtransform translate marginleft margintop draw them axes svgcontainerappendgattrclassaxis bottomattrtransform translate0 height callxaxis svgcontainerappendgattrclassaxis leftcallyaxis line function var line d3svgline xfunctiondi consolelogi return xi yfunctiondi consolelogd return yddata var linedata datatimemapfunction idx consolelogdatadataidx datatimeidx return data datadataidx time datatimeidx draw the line svgcontainerappendpath datumlinedata attrclass line attrd line,['javascript'] +639240,how does this obfuscated javascript code work i came across a cryptic jquery and am interested to understand how it worksalso check the code below can someone break this code down linebyline and explain how each line works,['javascript'] +639270,how can i find out the rgb color of my object in storyboard i have a button in the storyboard i gave it a color magnesium i am doing some programming on the button which will change its color on certain situationsi like the original color of the button in the storyboard and i want to return back to that color at some eventnow the problem is that color i am using does not have a text name yellowcolor purplecolor in uicolor and i cannot find the rgb values from the storyboard color pickerany ideas,['ios'] +639287,use jinja2 template engine in external javascript file i working on a web project using python and flask i was just wondering if i can access parameters sent by python in my external javascript files it is working well with html files or with js embedded in html files but not when javascript is externsee belowthe python codeapprouteindexdef index return render templateindexhtml firstarg 2 secondarg 3the indexhtml codebody pthe first arg is firstargp script srcindexjsscriptbodyand the indexjs filewindowonloadfunction consolelogsecondargso the first arg is correct within the html file but the second does not work in the js file the browser is showing unexpected token maybe it is not possible to use it in external jsotherwise i would need to insert the secondarg as an input data in html and get it within the js file but it is not very cleanif someone can help thanks,"['javascript', 'python']" +639302,why can i read from stdout and get a users terminal input i am perplexed under osx and linux using bash tcsh fish and dash this code successfully reads user input when that input is provided directly through the terminal but not when the user input is provided through a pipeeven more perplexing though i do not expect this code to work at all this code is reading from stdout i would expect the read call to return an error since i am essentially reading from a write only pipeinclude unistdhinclude stdiohint mainint argc char argv char buffer11 size t nread ifnreadread1 buffer sizeofbuffer1 0 fprintfstderr errorn return 1 buffernread 0 printfi read sn buffer return 0to build assuming you named the sample testc gcc o test testcthen this reads the user input testabcdi read abcdbut this does not echo abcd test program still waiting for the read to finishany insights,['c'] +639305,publish android app with leaderboards and no achievements i have got my leaderboards integrated into my android app but do not plan on adding achievements i have completed the game services setup in the developer console on google play all apart from the achievements when i go to the publish section it says my achievements are missing is it possible to publish it without achievements,['android'] +639309,jboss deploying in root context yes i know about enablewelcomerootfalse but cant find this in files use wildfly final or jboss eap 62 where it isand why i need to add jbosswebxml in webinf,['java'] +639362,rails best practice add javascripts manually or use gem i am pretty new to rails and i am not sure what is best practice when it comes to adding assetscan anybody tell me the advantages and thisadvantages of having javascripts within the assets vs using corresponding gemi find gems for pretty much all javascript libraries i want to use for example introjs should i go with the gem or download the javascript and have the library in my assets,"['javascript', 'ruby-on-rails', 'ruby']" +639450,matplotlib plot datetime in pandas dataframe i have a pandas dataframe that looks like this trainingheadthe dataframe has been sorted by date i would like to make a scatterplot where the date of the campaign is on the x axis and the rate of success is on the y axis i was able to get a line graph by using trainingplotxdateyrate however when i changed that to trainingplotkindscatterxdateyrate i get an error keyerror uno item named datewhy does my index column go away when i try to make a scatterplot also i bet i need to do something with that date field so that it does not get treated like a simple string do not iextra credit what would i do if i wanted each of the account numbers to plot with a different color,['python'] +639464,how to correctly execute lesscrhino163js from command line i am trying latest and greatest less version and it seems it does not work in rhino commandline version i have done following took latest rhino from here 7r4ziptook latest lessrhino163js from here running following from command linejava jar jsjar lessrhino163js textless textcssorjava jar jsjar lessrhino163js lesscrhino163js textless textcssthe result is silently nothingwhen trying to run previous latest version it runs ok without problemsjava jar jsjar lessrhino151js textless textcssoutput iswritten to textcsswhat i am missing about latest lessrhinojs i could not find any relevant help in or the later jut says stackoverflowcom is a great place to get answers about less,['javascript'] +639481,parse json response with afnetworking i have setup a json post with afnetworking in objectivec and am sending data to a server with the following codeafhttprequestoperationmanager manager afhttprequestoperationmanager managernsdictionary parameters name devicename model modelname pin pinmanagerrequestserializer afjsonrequestserializer serializermanagerrequestserializer setvaluecontenttype forhttpheaderfieldapplicationjsonmanager postsensored out url parametersparameterssuccessafhttprequestoperation operation id responseobject nslogjson responseobjectfailureafhttprequestoperation operation nserror error nslogerror errori am receiving information through the same request and want to send the data to a nsstring how would i go about doing that with afnetworking,"['ios', 'objective-c']" +639508,inconsistent accessibility return type is less accessible than method c ok so this is really wierd i have a private member and i want to use it into form2 i have made a public static method so that i can get that member into form2here is my codeprivate static appcontroller appcontrollerprivate breadrepository breadrepprivate cakerepository cakerepprivate sandwichrepository sandwichreppublic form1 initializecomponent breadrep new breadrepository cakerep new cakerepository sandwichrep new sandwichrepository appcontroller new appcontrollerbreadrep sandwichrep cakereppublic static appcontroller getcontroller return appcontrolleri have tried to make the appcontroller from form1 public but i get even more errors right now i get thisinconsistent accessibility return type exemplu mapcontrollerappcontroller is less accessible than method exemplu mapform1getcontroller any ideas updatehere is my appcontroller classclass appcontroller private breadrepository breadrep private sandwichrepository sandwichrep private cakerepository cakerep public appcontrollerbreadrepository breadrep sandwichrepository sandwichrep cakerepository cakerep thisbreadrep breadrep thissandwichrep sandwichrep thiscakerep cakerep public void writetofilestring file streamwriter wr new streamwriterfile string writeme foreachbread e in breadrepgetall writeme writeme egetall n foreach sandwich e in sandwichrepgetall writeme writeme egetall n foreach cake e in cakerepgetall writeme writeme egetall n wrwritewriteme wrclose i have changed appcontroller to public but i get again more errors the same error but for breadrep cakerep sandwichrep,['c#'] +639602,can i mimic a c header that redefines bool in c i am writing a program and i would really prefer to write in c however i am required to include a c header that redefines bool define false 0 define true 1typedef int boolthe obvious solution would be to edit the header to sayifndef cplusplus define false 0 define true 1typedef int boolendifbut alas since the library is readonly i cannotis there a way i can tell gcc to ignore this typedef or can i write most functions in c and then make a c wrapper for the two or should i suck it up and write the thing in c,"['c++', 'c']" +639633,what is the use of main method in abstract class i know that we can write main method in abstract class but what we can achieve from it public abstract class sample public static void mainstring args systemoutprintlnabstract class main method we can not create the object of abstract class so what is the use of main method in abstract class,['java'] +639787,pinchzoom with hammerjs with full credit to michael chaizes and his tutorial i have been working on adapting his code to zoom a picture in a fixed device width webapp the code below works great for a single image but i am stumped on how to get it to work for a dynamically generated list of images in my rails appfor illustration the code below includes a fully working sample page where the javascript is tied explicitly to the first image thisplayed i would like the code to be able to detect which image is being selected so that any image in the page can be zoomed currently the second image is ignored because i do not know how to elegantly associate the javascript to multiple images on the pagehammerjs is included in the header although not shown in the code clip and is working correctly on the first image as you can tell from the question javascript is not my forte so any pointers would be greatly appreciateddiv idzoomwrapper1 div idzoom1 classzoomprops div idrect1 classpolaroid img idrect src 1842437ijpg width100 ondragstartreturn false alt spansamplespan div divdivdiv idzoomwrapper2 div idzoom2 classzoomprops div idrect2 classpolaroid img idrect2 src 1842437ijpg width100 ondragstartreturn false alt spansamplespan div divdivscript var hammertime hammerdocumentgetelementbyidzoomwrapper1 transform always block true transform min scale 1 drag block horizontal true drag block vertical true drag min thistance 0 var posx0 posy0 lastposx0 lastposy0 bufferx0 buffery0 scale1 last scale rotation 1 last rotation dragready0 hammertimeontouch transform functionev elemrect documentgetelementbyidzoom1 managemultitouchev function managemultitouchev switchevtype case touch last scale scale last rotation rotation break case drag posx evgesturedeltax lastposx posy evgesturedeltay lastposy break case transform rotation last rotation evgesturerotation scale mathmax1 mathminlast scale evgesturescale 10 break case dragend lastposx posx lastposy posy break var transform translate3dposxpxposypx 0 scale3dscalescale 0 elemrectstyletransform transform elemrectstyleotransform transform elemrectstylemstransform transform elemrectstylemoztransform transform elemrectstylewebkittransform transformscript,"['javascript', 'ruby-on-rails']" +639811,what are datarequire datasemver in html files i have seen tags like this in html what are these attributesthis is not a duplicate of the data questionediti am looking for these two specific attributes not data in general nor datarequired as google suggests if you search the web you can find these attributes are used in many places i guess this is some like of dependency management software link datarequirebootstrapcss datasemver300 relstylesheet hrefnetdnabootstrapcdncombootstrap300cssbootstrapmincss script datarequire src datasemver115scriptscript datarequire datasemver050 srcscript,"['javascript', 'html', 'css']" +639818,nodejs passing function specific variables to asyncparallel i am have a bunch of long running database queries i need to get done before i render a page in node each of these queries require a few of their own variables is there an easy way to pass variables to the asyncparallel utility in nodejsasyncparallel queryxcallback a1 a2 a3 queryxcallback b1 b2 b3 queryycallback c1 c2 c3 queryycallback d1 d2 d3 queryzcallback e1 e2 e3 queryzcallback f1 f2 f3 functionerr results do render stuff with results,['javascript'] +639835,adview missing adactivity with androidconfigchanges in androidmanifestxml i just set up my app with the google play library method of adding adds admob when i run the emulator the add has the error messagemissing adactivity with androidconfigchanges in androidmanifestxmli located a fix atmissing adactivity with androidconfigchanges in androidmanifestxmlthe fix stated to do the followingcomgoogleadsadactivity is declared when using the admob sdk jar in the libs folder it seems youre using admob via the google play services library so changeactivity androidnamecomgoogleadsadactivitytoactivity androidnamecomgoogleandroidgmsadsadactivityalso make sure you add the metadata tagi tried this and the catlog said to change the meta tag back to metadata androidnamecomgoogleandroidgmsversion androidvalueintegergoogle play services version my logcat0223 143027091 eandroidruntime1278 fatal exception main0223 143027091 eandroidruntime1278 process bizmidldebtcalculator pid 12780223 143027091 eandroidruntime1278 javalangruntimeexception unable to start activity componentinfobizmidldebtcalculatorbizmidldebtcalculatormainactivity javalangillegalstateexception the metadata tag in your apps androidmanifestxml does not have the right value expected 42420 but found 0 you must have the following declaration within the application element metadata androidnamecomgoogleandroidgmsversion androidvalueintegergoogle play services version 0223 143027091 eandroidruntime1278 at androidappactivitythreadperformlaunchactivityactivitythreadjava21950223 143027091 eandroidruntime1278 at androidappactivitythreadhandlelaunchactivityactivitythreadjava22450223 143027091 eandroidruntime1278 at androidappactivitythreadaccess800activitythreadjava1350223 143027091 eandroidruntime1278 at androidappactivitythreadhhandlemessageactivitythreadjava11960223 143027091 eandroidruntime1278 at androidoshandlerthispatchmessagehandlerjava1020223 143027091 eandroidruntime1278 at androidoslooperlooplooperjava1360223 143027091 eandroidruntime1278 at androidappactivitythreadmainactivitythreadjava50170223 143027091 eandroidruntime1278 at javalangreflectmethodinvokenativenative method0223 143027091 eandroidruntime1278 at javalangreflectmethodinvokemethodjava5150223 143027091 eandroidruntime1278 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava7790223 143027091 eandroidruntime1278 at comandroidinternaloszygoteinitmainzygoteinitjava5950223 143027091 eandroidruntime1278 at dalviksystemnativestartmainnative method0223 143027091 eandroidruntime1278 caused by javalangillegalstateexception the metadata tag in your apps androidmanifestxml does not have the right value expected 42420 but found 0 you must have the following declaration within the application element metadata androidnamecomgoogleandroidgmsversion androidvalueintegergoogle play services version 0223 143027091 eandroidruntime1278 at comgoogleandroidgmscommongoogleplayservicesutilnunknown source0223 143027091 eandroidruntime1278 at comgoogleandroidgmscommongoogleplayservicesutilisgoogleplayservicesavailableunknown source0223 143027091 eandroidruntime1278 at comgoogleandroidgmsinternaluaunknown source0223 143027091 eandroidruntime1278 at comgoogleandroidgmsinternalaguunknown source0223 143027091 eandroidruntime1278 at comgoogleandroidgmsinternalagaunknown source0223 143027091 eandroidruntime1278 at comgoogleandroidgmsadsadviewloadadunknown source0223 143027091 eandroidruntime1278 at bizmidldebtcalculatormainactivityoncreatemainactivityjava410223 143027091 eandroidruntime1278 at androidappactivityperformcreateactivityjava52310223 143027091 eandroidruntime1278 at androidappinstrumentationcallactivityoncreateinstrumentationjava10870223 143027091 eandroidruntime1278 at androidappactivitythreadperformlaunchactivityactivitythreadjava21590223 143027091 eandroidruntime1278 11 morehere is my javaimport javatextdecimalformatimport androidappactivityimport androidcontentintentimport androidosbundleimport androidviewviewimport androidviewviewonclicklistenerimport androidwidgetbuttonimport androidwidgetedittextimport androidwidgetlinearlayoutimport androidwidgettextviewimport comgoogleandroidgmsadsadrequestimport comgoogleandroidgmsadsadsizeimport comgoogleandroidgmsadsadviewpublic class mainactivity extends activity private adview adviewdouble interestratedouble r r1int nremaining nstarting ndifference originalbalance outstandingbalance originaltermdouble minpayment additionalpayment newpmtoverrideprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmain adview new adviewthis adviewsetadunitidx edited out my unitid adviewsetadsizeadsizebanner linearlayout layout linearlayout findviewbyidridll layoutaddviewadview adrequest adrequest new adrequestbuilderbuild adviewloadadadrequesthere is my layoutlinearlayout xmlnsandroidxmlnsadsandroidididllandroidlayout widthfill parentandroidlayout heightfill parentandroidorientationverticalandroidweightsum1 comgoogleandroidgmsadsadview androidididadview androidlayout widthwrap content androidlayout heightwrap content adsadsizebanner adsadunitidx i also have my manifest xml version10 encodingutf8manifest xmlnsandroid packagebizmidldebtcalculator androidversioncode1 androidversionname1 usessdk androidminsdkversion14 androidtargetsdkversion19 usespermission androidnameandroidpermissioninternet application androidallowbackuptrue androidicondrawableic launcher androidlabelstringapp name androidthemestyleapptheme metadata androidnamecomgoogleandroidgmsversion androidvalueintegergoogle play services version activity androidnamecomgoogleadsadactivity androidconfigchangeskeyboardkeyboardhiddenorientationscreenlayoutuimodescreensizesmallestscreensize activity androidnamebizmidldebtcalculatormainactivity androidlabelstringapp name androidscreenorientationportrait androidthemeandroidstylethemedevicedefaultlightnoactionbarfullscreen intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity activity androidnamebizmidldebtcalculatorabout androidlabelstringapp name androidscreenorientationportrait androidthemeandroidstylethemedevicedefaultlightnoactionbarfullscreen intentfilter action androidnameandroidintentactionabout intentfilter activity applicationmanifest,['android'] +639858,background image not showing up in heroku i am having issues with the background image for my heroku site locally using backgroundimage urlbackground stripepngworks but when deployed the file is broken i have tried usingbackgroundimage imageurlbackground stripepngbackgroundimage urlimageurlbackground stripepngbackgroundimage urlimage urlbackground stripepngnone of which worked locally or on herokuusing bash i have found out heroku has named the image file background stripepng but it has no hash and its a broken image,"['css', 'ruby-on-rails']" +639911,peewee model to json i am creating an api using peewee as the orm and i need the ability to convert a peewee model object into a json object to send to the user does anyone know of a good way to do this,['python'] +639914,what are the delphi design principles behind class instances and pointers coming from a c background i understand classes pointers and memory addresses reasonably well however with delphi i am finding myself confusedi understand that when you declare a variable of a particular type of class in the var section of a functionprocedure what youre really declaring is a pointer to that class eg the following delphi and c are roughly equivalent both allocating the amount of memory required for the myobject class on the heap delphiprocedure blahsomethingvar o myobjectbegin o myobjectcreate ofrend cvoid blahsomething myobject o new myobject delete oin c using pointers and references allows the use of virtual methods for class hierarchies however if you do not have class hierarchies you can declare a variable on the stack which executes faster if you need to pass the variable around as a pointer you can simply get its address with the operator cvoid blahsomething this is allocated on the stack myobject o this address of this stackallocated object is being used dosomethingwithanohpointeroat this stage i have a few questions regarding delphis use of classes and pointersif creating an object with o myobjectcreate uses heapallocation in delphi how do you allocate an object on the stackif a variable of a specific type of class declared as o myobject is really a pointer then why is the pointer symbol never used is this a convenience idiom in delphihow can you get the address of the actual myobject located on the heap i have tried the followingwriteloglineaddress of object formatp o this prints the address of the o pointerwriteloglineaddress of object formatp o this causes the program to crashit is possible that i have misunderstood some delphi fundamentals but i have not found anyone physically or on the internet who can explain the above to my satisfactioneditgiven that delphi typically only allocates memory on the heap thendoes assigning one object to another mean that they both point to the same addresswhy does the assignment this assignment not compileprocedure blahsomethingvar o1 myobject o2 myobject op myobjectbegin o1 myobjectcreate o2 o1 both variables o1 and o2 point to the same object on the heap writeloglineformato1 p o2 p o1 o2 this should produce two different address as it is the address of the implied pointer op o1 this assignment will not compile writeloglineformatop p op o1free o1 nil the single object has been deleted but o1 nil while o2 nilendto give some context there are multiple variables that should be pointing to the same object but may be pointing to different objects so i want to compare their memory location to determine if this is the case,['c++'] +639930,ccnode as child of ccscene touch handler cocos2d v3 i have been beating my head over this for a while now i know in cocos2d v3 it changed so that ccnode can accept touches as long as you set the contentsize and set selfuserinteractionenabled yesthis is not working for me i have a ccnode that i add as a child to a ccscene but any touch is not getting registeredheres the ccnode codeid initwithportnamensstring portname anddescnsstring desc self super init if self returnnil cgsize winsize ccdirector shareddirector viewsize selfcontentsize winsize selfportname portname selfdesc desc selfdesclabel ccrpglabel alloc initwithstringdesc fontnamearial fontsize180f dimensionscgsizemake300 150 selfdesclabelcolor color blackcolor selfdesclabelposition ccpwinsizewidth2 200 self addchildselfdesclabel return self void onenter selfuserinteractionenabled yes super onenter void touchbeganuitouch touch witheventuievent event nsloghereand the ccsceneselfportnode mainport alloc initwithportnamesanta maria port anddescthis port is sowetselfportnodeposition ccp0 winsizeheightselfportnodecontentsize winsizeself addchildselfportnodei get no log for the touchbegan function am i doing something wrong remember this is cocos2d v3 not much documentation on this version yet,['ios'] +639943,laravel testing throwing exception with mockery i am very new to laravel and unit testing in general i am trying to write some tests for my accountcontroller and i have run into a road block i am using sentry to handle users and groups in the site i am trying to test that my controller is handling exceptions thrown by sentry properly so my controller method that handles the login post looks like thispublic function postlogin credentials array email inputgetemail password inputgetpassword try user thisauthrepoauthenticatecredentials true return redirectrouteget posts catch exception e message thisgetloginerrormessagee return viewmakelogin arrayerrormsg message authrepository is just a repository that uses sentry to handle authentication now i want to test that when an email address is not specified a loginrequiredexception is thrown and the user sees the error message here is my testpublic function testpostloginnoemailspecified args array email thisauthmock shouldreceiveauthenticate once andthrownew cartalystsentryusersloginrequiredexception thisactionpost myappcontrollersaccountcontrollerpostlogin args thisassertviewhaserrormsg please enter your email addresshowever the test is not passing for some reason all it spits out isthere was 1 error1 accountcontrollertesttestpostloginnoemailspecifiedcartalystsentryusersloginrequiredexception am i using the andthrow method incorrectly if anyone can shed any light on what is going on it would be much appreciatedthanks in advance,['php'] +640002,rails 4 respond only to json and not html i am trying to build an api in rails 4 and am having an issue where rails returns a 500 error instead of a 406 when using respond to json and trying to access the html versionheres an example controller demonstrating the problemclass postscontroller applicationcontroller respond to json def index posts postall endendi also have a jbuilder view for index that works when accessing via json if i try accessing the route without the json extension it attempts to load the html template which does not exist and returns a 500 error instead of just rendering json or returning a 406 errorwhat could be causing this cheers for any help,['ruby-on-rails'] +640085,bootstrap 3 align navigation to center i am having a problem with bootstrap 3 navigation i have some content on the left center and right it seems there is no option for centering the navigationi am trying to get the links titled center to be in the center of the page how can i achieve that nav classnavbar navbardefault rolenavigation div classcontainerfluid div classnavbarheader button typebutton classnavbartoggle datatogglecollapse datatargetbsexamplenavbarcollapse1 span clasronlytoggle navigationspan span classiconbarspan span classiconbarspan span classiconbarspan button a classnavbarbrand hrefbranda div div classcollapse navbarcollapse idbsexamplenavbarcollapse1 ul classnav navbarnav li classactivea hrefcentera li lia hrefcentera li lia hrefcentera li ul ul classnav navbarnav navbarright lia hrefrighta li lia hrefrighta li ul div divnavupdatejust realized that this question answer the same issuecenter content in responsive bootstrap navbar,"['jquery', 'html', 'css']" +640110,angular ngrepeat with array length condition i want the ngrepeat to run only when the photoslength 1 doing this does not seem to workdiv ngrepeatthumb in photos photoslength 1is there any quick trick elegant way to do this i just need to check for array length and nothing else fancyi would hate to duplicate the array to another array by doing something like thisif oldarraylength 1 newarray photoselse newarray and then do ngrepeat on newarray this seems inefficientthanks,"['javascript', 'html']" +640117,add a color picker to an ios app i am trying to add a color picker to my ios application using xcode 5 it appears that xcode offers a color well via the palettes panel of interface builder but i cannot find the palettes panel nor can i find any documentation of it online beyond that linkthat link also suggests an nscolorwell can be added programatically i would prefer to go the interface builder route but if that is not an option sample code would be welcome,['ios'] +640185,conversion failed when converting the varchar value simple to data type int i am struggling for a few days with this issue and i cannot figure out how can i fix iti would like to group by my table on values 12345 so i have created a temporary table with this valuesnow i have to inner join this table with other tables on avalue mytemptablenumbut avalue is ntext so i need to convert it what i actually did but i am getting an errorconversion failed when converting the varchar value simple to data type int on line 7create table mytemptablenum intinsert into mytemptable num values 12345 select aname convertint convertvarchar12 avalue as value count as pocet from select itemname valuevalue from mdl feedback as feedback inner join mdl feedback item as item on feedbackid itemfeedback inner join mdl feedback value as value on itemid valueitem where itemtyp multichoicerated and itemfeedback in 43 as a inner join mytemptable on convertint convertvarchar12 avalue mytemptablenum group by aname convertint convertvarchar12 avalue order by aname drop table mytemptablei am not getting this error without the last inner join inner join mytemptable on convertint convertvarchar12 avalue mytemptablenumcould you help me please i am desperatethanks,['sql'] +640318,why do i have to put in front of name in an object initializer purely curiosity at this point since the fixed the problem i was having but why is name speciali have an ef entity property called nameaif i do not put the in front of name i do not get any kind of error but the name property on the object does not get assigned if i put name in the object initializer it assigns name properlya new author id guidnewguidtostring name jason hater apparently name is quasireserved or somethingi checked the generated code and it is just named nameedmscalarpropertyattributeentitykeypropertyfalse isnullabletruedatamemberattributepublic globalsystemstring name get return name so name is not listed as a keyword so why is it specialeditokay as sergey suggested it is definitely a little more complicated than i first thought something goofy about entity framework specificallythis is manifesting inside a unit testing class that may be relevant also i am unsure whats relevant and whats not now unfortunately so heres the whole testinitialize method and at the bottom of it you can see that the weirdness happens around contextsavechangestestclasspublic class entityconvertertests private author a private post p p2 p3 testinitialize public void setupentities testentities context new testentities clear it out foreach comment o in contextcomments contextcommentsdeleteobjecto foreach post o in contextposts contextpostsdeleteobjecto foreach author o in contextauthors contextauthorsdeleteobjecto contextsavechanges a new author id guidnewguidtostring name jason hater contextauthorsaddobjecta systemdiagnosticsdebugwritelineaname jason haterayay probably irrelevant from here until contextsavechangesa p new post title linkbait author a p2 new post title rant 1023 author a p3 new post title polemic in eflat minor 824 author a apostsaddp apostsaddp2 apostsaddp3 pcommentsadd new comment body nuh uh post p pcommentsadd new comment body yeah huh post p pcommentsadd new comment body third reich post p p2commentsadd new comment body i laughed i cried post p2 systemdiagnosticsdebugwritelineaname jason hateragreat contextsavechanges systemdiagnosticsdebugwritelineaname aname is null empty string amore coming because now the is not fixing itthat is now i am still seeing null in the test method i was seeing it correct beforeasomething in another testmethod may have been making a difference perhapsaunsure still investigating still why is the change around contextsavechanges occurringedit 2uh okayasomehow the storegeneratedpattern property on my name property was set to identity in the modeling gui no idea how that happened changing it to none may have eliminated my problem butai know i had not changed that back when i thought the symbol had fixed itasomething still odd hereedit 3one way or the other the bad value for storegeneratedpattern was the cause of my assignmentsaving problem i am unsure why i observed success one or more times with that setting but the original question is no longer the correct question,"['c#', '.net']" +640425,install scipy with mkl through pip i am using pip to install scipy with mkl to accelerate the performance my os is ubuntu 64 bit using the solution from this question i create a file numpysitecfg mkllibrary dirsoptintelcomposer xe 2013 sp1mkllibintel64include dirsoptintelmklincludemkl libsmkl intel lp64mkl intel threadmkl coremkl rtlapack libsthis file helps me to install numpy with mkl successfully however using the same above file installing scipy prompts the errorimporterror libmkl rtso cannot open shared object file no such file or directoryi also useexport ld library pathoptintelcomposer xe 2013 sp1mkllibintel64but the problem is still the sameanyone know how to fix this problem i do not want to install scipy manually so anyone give me some hints to fix it,['python'] +640448,keep div height while the image is loading i have a square image within imgcontainer sometimes it takes a few seconds for an image to load and the imgcontainer collapses and only takes the full height when the image loads however i would like it to keep the full height as if the image is there while the image is loadingi wouldve easily done this by setting a minheight on imgcontainer class however it is a fluid grid and the image is responsive notice bootstraps imgresponsive helper class which makes it hard to set the minheight to an appropriate value for different screen sizes although achievable with media queries as a last resortsolving this by putting a placeholding image sounds like an overkill especially performance wise on mobile also not sure what would load first then the placeholder image or the actual imagediv classcolxs12 colsm6 colmd4 collg4 div classcard span classimgcontainer thumbnail clearfix img alt classpuleft imgresponsive srchttp span div classcaption a hrefhttp classcardtitle lead some text a div div div,['css'] +640477,fontawesome icon prevent newline wrapping how can i prevent a newline to be inserted between a fontawesome icon and the text that is near this icon see the fiddle i have a nbsp but it is thiscardedin the example below i do not want a wrap to ever occur between the icon and the word first but it can occur between first and second it does not work though see the fiddle i classfa fasearchinbspfirst secondit is related to this question but i cannot seem to make it workattach font icon to last word in text string and prevent from wrapping,"['html', 'css']" +640506,fill stdarray in the member initialization list the following code works but i would like to avoid the warningwarning fitnessvect should be initialized in the member initialization list weffcwhen it is compiled with the g weffc switchinclude arraytemplateclass t unsigned nclass fitnesspublic explicit fitnesst v static assertn fitness zero length vect fillv private stdarrayt n vect int main fitnessdouble 4 f10 return 0should i ignore the warning is there a way to fill vect in the constructor initialization list without changing its type,['c++'] +640531,unable to execute laravel artisan commands i just installed the latest version of laravel and tried to run the following command from my git bashphp artisan migratemake create users table tableusers createthis triggers the following errorcould not open input file artisani have tried a number of things i found here on this site but nothing seems to work any suggestions on how to make it work,['php'] +640553,eclipse keyboard shortcut for passing a parameter to a method today i was watching a video and i saw the tutor doing a correction in his code in eclipse without touching the mouse below is the code systemoutprintlncharactertouppercasechche changed the code to systemoutprintlncharactertouppercaseci have always wanted to do this because it is a pain to do it using backspaces and retype the at the enddoes anyone know how to do it thanks,['java'] +640565,compile html partials with gulpjs is there a plugin available for gulp that does the same thing as assemble does for grunti would like to run a task for gulp that assembles html partials but i cannot find a plugin has anyone used one and can you provide a link to itupdate 4212016i just wanted to update this with what i have been using to do this lately i have been primarily using twigjs as a frontend templating language with gulp you could also use nunjucks swigjs handlebars etc i have also been using gulpdata when i want to use json data for my templates you can see a quick rundown of how i am using this approach on a blog post i wrote article frontend templating with gulp and twigjs,['javascript'] +640570,why sizeofx does not increment the variable x value include stdiohvoid main int x 99 int y sizeofx printfx is d xthe result of above program isx is 99why can anyone tell why x is not incremented in sizeof operator,['c'] +640594,findbugs is objecting to anonymous inner class this codesetmapentrystring ssgsession theset new treesetmapentrystring ssgsessionnew comparatormapentrystring ssgsession override public int comparefinal mapentrystring ssgsession e1 final mapentrystring ssgsession e2 return e2getvaluegetstarttimecomparetoe1getvaluegetstarttime triggers a violation in sonar tripping the findbugs rule sic inner should be static anon which has the description this class is an inner class but does not use its embedded reference to the object which created it this reference makes the instances of the class larger and may keep the reference to the creator object alive longer than necessary if possible the class should be made into a static inner class since anonymous inner classes cannot be marked as static doing this will require refactoring the inner class so that it is a named inner classreally is not this very nitpicky should i really refactor a one line method in an anonymous inner class to save the cost of an extra reference in this case there is no possibility of it holding the reference longer than necessaryi do not mind doing it as our strongly enforced coding standards are zero sonar violations but i am strongly tempted to argue the case for a nosonar here as imho extracting a one line method to a static inner makes the code slightly harder to grokwhat do the java purists think,['java'] +640764,the program mono has exited with code 0 0x0 when debugging ios from vs i have a problem that when i try to debug my ios app with vs2013 with xamarin i get the following error the program mono has exited with code 0 0x0i am aware of the following answer cleaning the solution does solve the problem but then the next time i debug i need to do it again would really appreciate if someone has a long term solution,['ios'] +640810,using file get contents to authenticate and access an htaccess protected file i need to reach a foreign php page protected by a regular htaccess file auth type basic htpasswords etci would like to send the user and password needed through the request is it possible i would like to avoid curl and all pecl http dependent functions if possible,['php'] +640825,is it possible to mix a preference and a preference header i am developing a list of preferences for my app right now there is only one but i am sure there will be more as it gets fleshed out my first preference is a theme selector where you choose the background color theme for some predefined elements i want a dualpane interface for my upcoming prefs but i do not need this preference in a subcategeory that preference headers use is there a way to add a preference via xml to the headers list so it will appear in the root preferences i have looked have not seen any examples on if this is possible right now all i have is a button for themes which goes to a new preferences page another fragment it lives under which is making 2 clicks instead of one for a preference that does not go under a category,['android'] +640922,ios design pattern for populating asynchronously fetched data i am developing an app that fetches data from the web and thisplays it to the user assume that the data is reviews of a restaurant and one review is thisplayed on one view the user can swipe left or right to go to the prevnext review the data is fetched asynchronously one thread for each reviewhere is the problem statement assume that 5 reviews have been fetched and the user is looking at the 3rd one currently now the 6th review is fetched and i want to thisplay it as the 4th review to the user because the publish date of the 6th review is more recent than the 5th review how should my model class inform the view controlleri have considered some options provide an array to the view controller and then send nsnotifications about new items to be inserted inbetween the array at a specific indexuse an nsfetchedresultscontroller this is a bit tricky because i am not using it with a table view controllerview controller always asks for the next review to be thisplayed from the model and does not have a array of reviews with itare there any established design patterns that are employed in such a scenario other suggestions apart from the 3 above are welcome,['ios'] +640936,scipy expit unexpected behavour nans noticed some nans were appearing unexpectedly in my dataand expanding out and naning everything they toucheddid some careful investigation and produced a minimal working example import numpy from scipyspecial import expit expit70910 expit710nanexpit is the inverse logit scipy documentation herewhich tells us expitx 11expxso 1exp70910 so that expit70910 seems fairly reasonable rounding exp7090 however what is going on with expit710 expit710nan implies that 1exp7100 which implies exp7101 which is not right at allwhat is going oni am fixing it withdef sane expitx x npminimumx700npones likex cap it at 700 to avoid overflow return expitxbut this is going to be a bit slower because extra op and the python overheadi am using numpy 180 and scipy 0132,['python'] +640971,gettersetter and private variables if i can change the value of private variable through getterreturned reference then is not it bypassing the setter method does not it defeat the purpose of gettersetter and private variablespublic class testprivate dimension cannotbechangedpublic testint height int width ifheight3 cannotbechangedheight height ifwidth3 cannotbechangedwidth widthpublic dimension getdimension return cannotbechangedpublic void setdimensionint height int width ifheight3 cannotbechangedheight height ifwidth3 cannotbechangedwidth width public static void mainstring args test testone new test55 dimension testsecond testonegetdimension testsecondheight 3 changed height and width to unwanted values testsecondwidth 3,['java'] +640975,objectinputstream from file causing memory leaks i have a huge file with a list of objects written by objectoutputstream one after another for object obj currentlist ooswriteunsharedobjnow i want to read this file using objectinputstream however i need to read multiple files at the same time so i cannot read the entire file into memoryhowever using objectinputstream causes a heap out of memory error from what i read this is caused because objectinputstream has a memory leak and maintains references to the read objects even after returning themhow can i ask objectinputstream to not maintain a reference of whatever its reading,['java'] +641050,creating hashmap from a json string creating a hashmap from a json string in javai have json string like phonetypen95catwp and want to convert into a standard hashmaphow can i do it,"['java', 'android']" +641053,multiple iterations of random double numbers tend to get smaller i am creating a stock trading simulator where the last dayss trade price is taken as opening price and simulated through out the current day for that i am generating random double numbers that may be somewhere 5 of lasttradeprice and 5 above the lasttradeprice however after around 240 iterations i see how the produced double number gets smaller and smaller closing to zerorandom rand new randomthreadsleeprandnext010random random new randomdouble lasttrademinus5p modellasttradeprice modellasttradeprice 005double lasttradeplus5p modellasttradeprice modellasttradeprice 005modellasttradeprice randomnextdouble lasttradeplus5p lasttrademinus5p lasttrademinus5pas you can see i am trying to get random seed by utilising threadsleep and yet its not truly randomised why is there this tendency to always produce smaller numbersupdatethe math itself is actually fine despite the downwards trend as jon has proven itgetting random double numbers between range is also explained herethe real problem was the seed of random i have followed jons advice to keep the same random instance across the thread for all three prices and this already is producing better results the price is actually bouncing back upwards i am still investigating and open to suggestions how to improve this the link jon has given provides an excellent article how to produce a random instance per threadbtw the whole project is open source if you are interested using wcf wpf in browser prism 42 net 45 stackthe transformprices call is happening here on one separate threadthis is what happens if i keep the same instance of randomand this is generated via randomprovidergetthreadrandom as pointed out in the article,"['c#', '.net']" +641066,libusb claim interface access denied java i want to be able to read data from an usb pedometer i am trying this in java and i am using the libusb and usb4java libraries i cannot seem to claim the usb pipe or anything like thatthe code i am usingfinal context context new context int result libusbinitcontext if result 0 throw new libusbexceptionunable to initialize libusb result devicehandle handle libusbopendevicewithvidpidcontext vid pid if handle null device d libusbgetdevicehandle int res libusbclaiminterfacehandle 0int res returns 3 which is libusb error accessthe device is found but not claimablethe usb device has only 1 interfaceany help would be appreciated,['java'] +641096,angularjsuncaught error injectormodulerr i am trying angularjs example given on titled wire up a backendi have copied code and saved files on my machinewhile executing indexhtmluncaught error injectormodulerr injectormodulerrp0projectp1error3agleapiscom2fajax2flibs2fangularjs2f12132fangularminjs3a173a431 error is thisplaying on consoleany help will be appreciatedfollowing is the code indexhtmldoctype htmlhtml ngaprojecthead script srcscriptscript srcscriptscript srcscriptscript srcscriptscript srcscriptscript srcprojectjsscriptheadbody h2javascript projectsh2 div ngviewdivbodyhtml projectjsangularmoduleproject ngroute firebasevaluefburl factoryprojects functionfirebase fburl return firebasenew firebasefburlconfigfunctionrouteprovider routeproviderwhen controllerlistctrl templateurllisthtmlwheneditprojectid controllereditctrl templateurldetailhtmlwhennew controllercreatectrl templateurldetailhtmlotherwise redirecttocontrollerlistctrl functionscope projects scopeprojects projectscontrollercreatectrl functionscope location timeout projects scopesave function projectsaddscopeproject function timeoutfunction locationpath controllereditctrl functionscope location routeparams firebase fburl var projecturl fburl routeparamsprojectid scopeproject firebasenew firebaseprojecturlscopedestroy function scopeprojectremove locationpathscopesave function scopeprojectsave locationpathlisthtmlinput typetext ngmodelsearch clasearchquery placeholdersearchtabletheadtrthprojectththdescriptionththa hrefnewi classiconplussigniathtrtheadtbodytr ngrepeatproject in projects orderbypriority filtersearch orderbynametda hrefprojectsite target blankprojectnameatdtdprojectdescriptiontdtda hrefeditprojectidi classiconpenciliatdtrtbodytabledetailhtmlform namemyformdiv classcontrolgroup ngclasserror myformnameinvalid myformnamepristinelabelnamelabelinput typetext namename ngmodelprojectname requiredspan ngshowmyformnameerrorrequired myformnamepristine classhelpinlinerequired myformnamepristinespandivdiv classcontrolgroup ngclasserror myformsiteinvalid myformsitepristinelabelwebsitelabelinput typeurl namesite ngmodelprojectsite requiredspan ngshowmyformsiteerrorrequired myformnamepristine classhelpinlinerequiredspanspan ngshowmyformsiteerrorurl classhelpinline not a urlspandivlabeldescriptionlabeltextarea namedescription ngmodelprojectdescriptiontextareabra href classbtncancelabutton ngclicksave ngthisabledmyforminvalid classbtn btnprimarysavebutton button ngclickdestroy ngshowprojectremove classbtn btndangerdeletebuttonform,['javascript'] +641179,why does toggling a checkboxradiobutton with javascript fail after calling eventpreventdefault consider this sample codespan input typecheckboxspanspanclickfunctione epreventdefault checkbox0checked truefiddlefrom my knowledge this should happenpreventdefault should prevent the checkbox from being checked by the browsers default behavior even if the event handler is attached above in the dom hierarchy this part works correctlysetting checked true should work as i believe it should be independent of the browsers default action for the event which i have cancelled this part seems buggy as if the preventdefault was affecting it remove the preventdefault and it works as intendedwhats the actual reason why the checkbox stays always uncheckedi have tested on chrome 33 and firefox 27 so this does not seem to be a browser bugthis question is mostly due to curiosity to extend my domevent model knowledge i do not want workarounds but rather i want to know why this example fails,"['javascript', 'jquery']" +641198,using different codeception environments i am working on some unit tests for an api using codeception the idea is to make sure that each api call returns the expected response codes and a json object in a desired formatthe problem that i have is that i need to use different urls depending on whether the server is localhost the test server or the production onei cannot use the values of serverserver name because the tests are not ran through the web browserhere they explain that some environments can be set by modifying the configuration file the documentation does not explain how to modify the configuration file to use it within your own unit testsid like to set some environments like local test production and then inside my unit test classes to know what urls to use each environment would have different urlsi have read the documentation but i cannot find the way to do itdo you know any way to achieve what i need,['php'] +641237,regex search pattern in very large file i would like to search pattern in very large file fe above 1 gb that consists of single line it is not possible to load it into memory currently i use bufferedreaderto read into buffers 1024 charsthe main stepsread data into two bufferssearch pattern in that buffersincrement variable if pattern was foundcopy second buffer into firstload data into second bufferssearch pattern in both buffersincrement variable if pattern was foundrepeat above steps start from 4 until eofthat algorithm two buffers lets me to avoid situation where searched piece of text is split by chunks it works like a chram unless pattern result is smaller that two buffers length for example i cannot manage with case when result is longer let us say long as 3 buffers but i have only data in two buffers so match will fail whats more i can realize such a caseprepare 1 gb single line file that consits of babsearch for pattern babthe whole file match patterni do not have to print the result i have only to be able to say yea i was able to find pattern or no i was not able to find thatit is possible with java i meanability to determine whether a pattern is present in file without loading whole line into memory see case abovefind the way handle the case when match result is longer than chunki hope my explanation is pretty clear,['java'] +641337,temporarily set js errors to false in poltergeist i have a set of tests which lead to a facebook page where the user logs in unfortunately this page has some javascript errors which i cannot influence so my tests would never finishis there any way to temporarily thisable the check for js errors i was thinking about something like capybarajavascript driverjs errors false and then setting it to true later but unfortunately this does not work i have tried variations of this to no availany ideas on how my problem could be solved,['javascript'] +641345,capistrano 3 does not restart after deploy i have recently updated my capistrano gem to version 310 and since then cap production deploy passes fine but the target deployrestart is not calledmy server is deployed on ubuntu 1210 on amazon ec2why could that be,['ruby'] +641371,add java library to android studio project with maven repository i want to try this library in my android project i am using android studio 046the readmemarkdown file tells me to insert this inside pomxml in the repositories section repository idkeytwonetid namekeytwonet repositoryname urlurlrepository in the dependencies section dependency groupidiosocketgroupid artifactidsocketioclientartifactid version021version the desidered version dependencythe problem is that i do not have any pomxml i created one in my project root directory and synced gradle settings but it does nothing till now i only used already compiled jar files or used the gradle compile functionhow can i use this library in my project,"['java', 'android']" +641401,assignment of several statements enclosed in parentheses and curly braces in objc i was perusing the code of the thirdparty residemenu framework and noticed some strange syntax that seemed to work just fine here is the confusing bitselftableview uitableview tableview uitableview alloc initwithframeframe styleuitableviewstyleplain tableviewautoresizingmask mask tableviewdelegate self tableviewdatasource self tableviewopaque no tableviewbackgroundcolor uicolor clearcolor tableviewbackgroundview nil tableviewseparatorstyle uitableviewcellseparatorstylenone tableviewbounces no tableviewscrollstotop no tableviewhow does this syntax work i suspect it has something to do with a clevel block scoping but i have never seen this before i also considered it may be a new feature with objc20 literals but i do not think that is trueso i guess my question is how does this workwhat makes this work,['objective-c'] +641425,create pdf with tooltips in python this a python copy of the popular and highly upvoted create pdf with tooltips in r simple question is there a way to plot a graph from python in a pdf file and include tooltips,['python'] +641496,php use recaptcha if brute force attempt is detected i am building a login script with a brute force checker that when triggered thisplays recaptcha the problem that i am having is that when the correct usernamepasswordcaptcha response are entered the login script runs but not until the majority of the page content has loaded this happens after the form is submitted the result is that i must hit f5 to refresh the page and resubmit the form data in order for the session to be active when the page begins to load now the problem that i am having is that once the form is submitted when it requires a captcha that is the session is not started until indexphp gets to else captcharesponse 1 auth authverifypassusernamepasswordcaptcharesponse i am stumped as to how i can reorganize this so that the session is started way before that any ideasthe first part is the indexphp page containing the code that is triggered if a brute force attempt is detected this portion of the code begins with the conditional ifauth bruteforce this code thisplays recaptcha and is supposed to submit the username password and recaptcha response code 0incorrect response 1correct response back to the login function php includeincludesheaderphp spl autoload registerfunction class include includesclass class php ifnull filter inputinput postusernameusername filter inputinput postusername ifnull filter inputinput postpasswordpassword filter inputinput postpassword ifissetusername issetpassword auth authverifypassusernamepassword ifisset getlogout getlogout true session start session destroy setcookie phpsessid time 3600 headerlocation indexphp ifauthcheckloggedin true ifsession id echo session id is not blankbr echo a hrefindexphplogouttruelogoutabr echo welcome this is protected content br ifauthcheckloggedin h1sign inh1php ifissetusername issetpasswordifauth invalidpasswordecho span classerrorinvalid username or passwordspan form namelogin methodpost actionindexphp idloginform ul li input placeholderusername typetext nameusername idusername classlogin li li input placeholderpassword typepassword namepassword idpassword classlogin li php ifissetusername issetpassword echo auth br ifauth bruteforce echo auth require onceincludesrecaptchalibphp get a key from publickey x privatekey x resp null error null ifisset postrecaptcha response field resp recaptcha check answer privatekey serverremote addr postrecaptcha challenge field postrecaptcha response field if respis valid authcheckloggedin auth authverifypassusernamepassword1 else auth authverifypassusernamepassword0 captcharesponse 2 echo recaptcha get htmlpublickey error ifauth invalidcaptcha echo invalid captcha response please try again ifissetauthecho auth div classclearallnbspdiv li idsubmit input typesubmit valuelogin idloginbtn classlogin li li idreset input typereset valuereset idresetbtn classlogin li ul form div classclearallnbspdiv h1new userh1 pa hrefregisterphpsign upap php endif div classclearallnbspdiv php includeincludesfooterphp bodyhtml this is the log in functionpublic static function verifypassusernamepasswordcaptcharesponse 3 authenticateduser false brutetest self brutetestusername ifbrutetest true captcharesponse 3 status bruteforce return status else ifbrutetest true captcharesponse 0 the brute force check was positive and the captcha response failed do not even try to log in because the captcha failed status invalidcaptcha return status else if brutetest true captcharesponse 1 the brute force check was positive and the captcha response was successful try to log in now continuelogin true else ifbrutetest false the brutetest was negative proceed with login continuelogin true ifcontinuelogin true try connection databasegetdbconnection ifconnection query select usr name usr pass usr salt uid email pri from users where usr name limit 1 stmt connectionpreparequery stmtexecutearrayusername results stmtfetchallpdofetch assoc ifstmtrowcount 0authenticateduser false username was not found we are not going to say which was incorrect only that the username or password was incorrect ifresults resultsarray results0 connection null echo br dbusername resultsarrayusr name dbpass resultsarrayusr pass dbsalt resultsarrayusr salt dbuid resultsarrayuid dbemail resultsarrayemail pri passhash hashsha512password passtocheck hashsha512dbsaltpasshash ifpasstocheck dbpass authenticateduser false password did not match we are not going to say which was incorrect only that the username or password was incorrect else if passtocheck dbpass username dbusername authenticateduser true else ifresultsauthenticateduser false catch pdoexception e echo error egetmessage br die try ifauthenticateduser false log the failed attempt into the database remoteip serverremote addr try connection databasegetdbconnection ifconnection query insert into login attemptsusr name usr ip values usr nameinet atonusr ip stmt connectionpreparequery stmtexecutearrayusr name username usr ip remoteip connection null catch pdoexception e echo error egetmessage br die status invalidpassword return status exit else ifauthenticateduser true clear login attempts from the database self clearattemptsusername start the session if not already started somehow session and cookie expiration need to be adjusted so that the session does not persist after browser close ifisset session session start set the session variables sessionuserip serverremote addr sessionusername dbusername sessionuseragent serverhttp user agent session name sec session id httponly true cookieparams session get cookie params session set cookie paramscookieparamslifetime cookieparamspath cookieparamsdomain httponly session namesession name catch pdoexception e echo error egetmessage br die end continuelogin statement below,['php'] +641516,php how to return datetime6 from mysql when i query a datetime6 php is truncating my 6 fractional seconds here is an example of my php codesql select date from tbl statement connectionpreparesql statementexecute statementstore result statementbind resultdate while statementfetch echo daten this returns 20140108 213115 instead of 20140108 2131159950 which is what is stored in the table how can i get what is actually stored in the table,"['php', 'mysql', 'sql']" +641560,laravel 4 withinput undefined offset 0 i have had a lengthy search both here and the laravel forums but i cannot find an answer to this problem withinput coughs up an undefined offset 0for contextcontrollerpublic function getjobs position options dbtablejpositionlistsfriendlyid category options dbtablejcategorylistsfriendlyid location options dbtablejlocationlistsfriendlyid result queryget return viewmakejobsearchsearch arrayposition options position options category options category options location options location optionswithinput viewform action actionjobsearchcontrollergetjobs methodpost div classrow div classlarge8 columns input typetext namerealm placeholderkeywordsskills div div classlarge4 columns formselectcategory category options inputoldcategory div div div classrow div classlarge4 columns formselectlocation location options inputoldlocation div div classlarge4 columns formselecttype position options inputoldtype div div classlarge4 columns input typesubmit valuesearch stylewidth100 paddingtop 5rempaddingbottom 5rem classbutton borderbtn divdivformnow according to the documentation there should not be an issue and the page loads fine if the withinput is removedthe end goal is to roll in the answer that i received from my previous question undesired result from dbraw and have a single page that loads the filtering form and thisplays the relevant results on the reload and remembers the selections in the formthanks in advanceupdatefollowing a comment i have updated the controller and routes still same resultroutesphproutegetjobssearch jobsearchcontrollergetsearchroutepostjobssearch jobsearchcontrollergetjobscontroller public function getsearch position options dbtablejpositionlistsfriendlyid category options dbtablejcategorylistsfriendlyid location options dbtablejlocationlistsfriendlyid return viewmakejobsearchsearch arrayposition options position options category options category options location options location options public function getjobs position options dbtablejpositionlistsfriendlyid category options dbtablejcategorylistsfriendlyid location options dbtablejlocationlistsfriendlyid return viewmakejobsearchsearch arrayposition options position options category options category options location options location optionswithinput,['php'] +641719,how to retrieve layerpoint x y from latitude and longitude coordinates using leaflet api if i use the following code to get the layerpoint from a specified latlngvar latlng new llatlng3781303878836989 14497421264648438var point maplatlngtolayerpointlatlngthe output is the followingopoint x 86042 y 77065then when i try to access the layer tile using the following urli get a 404 because it is an invalid x ynow if i use the following codemaponclick function e consolelogei can retrieve the layerpoint in the console alongside the latitude and longitudelatlng olatlng lat 3781303878836989 lng 14497421264648438layerpoint opoint x 950 y 303then accessing the following url returns this layer tilethe problem is that it does not even seem to be the correct tile for that latitude longitude nor does my original code to convert lat lng to layerpoint actually return a valid x y in the first placei am very confused as to why i am getting these results any help would be greatly appreciated perhaps i am doing something wrongi am not sure whether there is another way of retrieving tile layers based on a list of latitude and longitudesthe reason why i am after this is because i want to be able to use cached tile data for an offline application and the only data i have are geometrycoordinates via a geojson payload that is generated for the clientside applicationupdateended up going with this function thanks to scaiaccording to this linkvar getslippytilelayerpoints function lat deg lng deg zoom var x mathfloorlng deg 180 360 mathpow2 zoom var y mathfloor1 mathlogmathtanlat deg mathpi 180 1 mathcoslat deg mathpi 180 mathpi 2 mathpow2 zoom var layerpoint x x y y return layerpointoutputobject x 924 y 628update 2after further research it turns out what i was after is the following functionvar layerpoint mapprojectlatlngdivideby256floorconsoleloglayerpointx layerpointy,['javascript'] +641813,concurrency exceptions in entity framework when calling savechanges savechangesasync in entity framework cf c if a change conflict occurs for example the values has been updated since last read thingy then which of these two exceptions dbupdateconcurrencyexception or optimisticconcurrencyexception shall i catch and what is the difference between them,['c#'] +641833,what is 123mapparseint result 123mapparseintreturn 1 nan nani do not know why in my opinion is like this123mapfunctionireturn parseinti10return 1 2 3and other123mapparsefloatreturn 1 2 3,['javascript'] +641908,visual studio 2013 clexe exited with code 1073741515 i have a fresh windows 81 pro x64 install with a fresh visual studio 2013 prowhen trying to compile a project with platform toolset to windows71sdk i am gettingerror 1 error msb6006 clexe exited with code 1073741515 cprogram files x86msbuildmicrosoftcppv40platformswin32microsoftcppwin32targets 57 5 menubrowseri tried running the supplied windows sdk configuration tool and besides getting an error about visual studio 2005 and 2008 not being installed i think it did its jobi tried manually editing the registryhkey local machinesoftwaremicrosoftmicrosoft sdkswindowswhere i manually put currentinstallfolder as cprogram filesmicrosoft sdkswindowsv71 and currentversion as 7176030514 if i look at the project properties and click the different paths variables in there more macros i can see that windowssdkdir is correctany idea as to what i should try never ran into this problem on the old development computer with windows 7 and vs 2012le as a note if i try a new project with the v120 tools it works but i need the windows71sdk tools,['c++'] +641915,can anyone explain the work flow of iexceptionhandler with sample client application i am facing below issues in this samplei am not able to find isoutermostcatchblock in exceptioncontextif exception occurs this handleasync method is executing twicepublic class customexceptionhandler iexceptionhandler public virtual task handleasyncexceptionhandlercontext context cancellationtoken cancellationtoken if shouldhandlecontext return taskfromresult0 return handleasynccorecontext cancellationtoken public virtual task handleasynccoreexceptionhandlercontext context cancellationtoken cancellationtoken handlecorecontext return taskfromresult0 public virtual void handlecoreexceptionhandlercontext context public virtual bool shouldhandleexceptionhandlercontext context return contextexceptioncontextisoutermostcatchblock public class oopsexceptionhandler customexceptionhandler public override void handlecoreexceptionhandlercontext context contextresult new textplainerrorresult request contextexceptioncontextrequest content oops sorry something went wrong please contact so we can try to fix it private class textplainerrorresult ihttpactionresult public httprequestmessage request get set public string content get set public taskhttpresponsemessage executeasynccancellationtoken cancellationtoken httpresponsemessage response new httpresponsemessagehttpstatuscodeinternalservererror responsecontent new stringcontentcontent responserequestmessage request return taskfromresultresponse,['c#'] +641988,storing data into session and storing to database upon major action i know there are hundreds of these questions but what i am asking however is slightly different when the user logs in i would like to get all their data from each table in a database and store it in a session variable obviously not sensative data such as encrypted passwordsalts etc basically data that would be useless or have no value to a hacker and whilst the user uses the website the relevant data stored in the session will be used as opposed to accessing the database everytime moreover when the data is changed or added this will be written or added to the session file and upon a major action such as saving or loggin out the newchanged data will be written to the databasethe reason i wish to do this is simply for efficieny i want my application to not only be fast but less resource consuming i am no expert on either which may explain why my idea makes no differnece or is more resource intensiveif there is an alternative to my solution please let me know or if there is something to improve on my solution i will be glad to hear itthank youmy application is using php and mysql,"['php', 'mysql']" +642003,core data deadlocking when executing fetch requests inside performblockandwait blocks i am experiencing issues with core data which i cannot resolve i have learned about concurrency issues in core data the hard way thus i am really careful and only perform any core data operations in performblock and performblockandwait blocks here goes my code executes a fetch request with given parameters in contexts block nsarray executefetchrequestwithentitynamensstring entityname predicatenspredicate predicate fetchlimitnsuintegerfetchlimit sortdescriptornssortdescriptor sortdescriptor incontextnsmanagedobjectcontext context nscassertentitynamelength 0 entityname parameter in executefetchrequestwithentitynamepredicatefetchlimitsortdescriptorincontext is invalid block nsarray results nil nspredicate newpredicate cwfcoredatautilities currentuserpredicateincontextcontext if predicate newpredicate nscompoundpredicate andpredicatewithsubpredicatesnewpredicate predicate context performblockandwait nsfetchrequest request nsfetchrequest fetchrequestwithentitynameentityname requestfetchlimit fetchlimit requestpredicate newpredicate if sortdescriptor requestsortdescriptors sortdescriptor nserror error nil results context executefetchrequestrequest errorerror if error throw nsexception exceptionwithnamensinternalinconsistencyexception reasonfetch requests are required to succeed userinfoerrorerror nslogerror error nscassertresults nil fetch requests must succeed return resultswhen i enter this method concurrently from two different threads and pass two different contexts i result in a deadlock on this row results context executefetchrequestrequest errorerrorwhich is interesting it seems like both threads cannot acquire some lock on the persistent store coordinator in order to execute a fetch request all of my contexts are nsprivatequeueconcurrencytypei cannot put my finger on why am i locking the app and what should i do differently my research on stack overflow gave me nothing since most of the people fixed all the locks by thispatching the fetch requests on the mocs queue which i already do i will appreciate any information on this issue feel free to provide documentation links and other long reads i am eager to learn more about all kind of concurrency problems and strategies,['ios'] +642020,can i link a static library built with the v120 xp toolset into an exedll built with the v120 toolset in vs2013 i am working with a large codebase that contains four sets of native c vs2013 projects i will call these sets a b c and dprojects in sets a and b generate c static libraries lib projects in sets c and d generate dlls and executablesprojects in set c link only to static libraries in set a while projects in set d link to static libraries from both set a and set b c dll exe a lib d dll exe b libi have the following requirementsthose dlls and exes that are generated by projects in set c must run on windows xp as well as on windows 7 those dlls and exes that are generated by projects in set d on the other hand donot need to run on windows xpwhat i would like to do is to build the projects in sets a and c with the v120 xp platform toolset and those in sets b and d with the v120 platform toolset winxp win7 c v120 xp a v120 xp d v120 b v120 win7 onlyi believe this should not be a problem for projects in set c but i am concerned with projects in set di tried doing the above for a few small projects and it all seems to work correctly but is this guaranteed to be safe in the general casemy research point 2 in this question asks pretty much the same thing i am asking but for vs2012 it did not receive an answerthis answer again for vs2012 mentions thatlong story short mixing modules that were built with a mix of v110 and v110 xp toolsets is not a problemthis other answer to the same question on the other hand saysmixing v110 xp executables and v110 libraries is officially unsupported,['c++'] +642137,how to gruntuglify multiple script files while keeping folder structure i have not found a good way to gruntuglify multiple script files spread over multiple folders while keeping the folder structure including the uglified files intactthe only reason i want to do this is to be able to increase the performance of the legacy part of the web page i am working oni have found a way around this which i do not want to do since it will take to much time and that is to do it like in this answer they specify each src and dest pair seperatelyhow to config gruntjs to minify files separatelyan example of what i want to achievesrc dir no uglify appliedsrc app1 randomfilejs scripts file1js file2js libs file3js file4js app2 scripts file1js file2jsdestination dir uglify applied same file namethist app1 randomfilejs scripts file1js file2js libs file3js file4js app2 scripts file1js file2jsbtw want to do the same for cssfiles if possibledoes anyone know if this is possible,['javascript'] +642154,how can i make the play game services not automatically sign in at the startup google provides the basegameutils library and recommend us to extends its basegameactivity however this class makes the game automatically sign in whenever the game is started if the player does not want to or cannot connect to his google account this can be very time consuming at the beginning of the game so i dont want this feature instead i want to provide a sign in button the player is connected only when he click that button and from that point on every time the player starts the game he is automatically connected to his google account without clicking any button how can i do this,['android'] +642194,tomcat in intellij idea community edition is it possible to run a web application using tomcat server in intellij idea community editioni tried to find some information about it but have not achived any success,['java'] +642195,ienumerable to stream i would like to do something roughly equivalent to the code example below i want to generate and serve a stream of data without necessarily having the entire data set in memory at any one timeit seems like i would need some implementation of stream that accepts an ienumerablestring or ienumerablebyte in its constructor internally this stream would only walk the ienumerable as the stream is being read or as needed but i do not know of any stream implementation like thisam i on the right track do you know of any way to do something like this public filestreamresult getresult ienumerablestring data getdataforstream stream datastream tostringstreamencodingutf8 data return filedatastream textplain result private ienumerablestring getdataforstream stringbuilder sb for int i 0 i 10 i yield return itostring yield return rn private stream tostringstreamencoding encoding ienumerablestring data i have to write my own implementation of stream throw new notimplementedexception,['c#'] +642197,android accountpicker set light theme is it possible to set the theme of picker dialog import comgoogleandroidgmscommonaccountpickerstring accounttypes new stringcomgoogleintent intent accountpickernewchooseaccountintentnull null accounttypes false null null null nullactivitystartactivityforresultintent request code pick accountmy base app theme is androidthemelight but that dialog is darkthanks,['android'] +642232,can i use bindingredirect on an assembly inside a referenced assembly we have a plug in folder from which we load assembliesmostly this is fine however we have 1 3rd party plugin that uses systemcore version 2050we use net 4 so we have systemcore 40 loaded on on the pcswhen loading the plugin we get an error as systemcore version 2050 cannot be resolvedi thought this would helpdependentassembly assemblyidentity namesystemcore publickeytoken7cec85d7bea7798e cultureneutral bindingredirect oldversion2050 newversion40 dependentassemblybut it did nothow can i force a referencing dll to use the version of systemcore i haveand is that the right way to do thisthis is the code we use to register the pluginsinternal class testcode fileinfo assemblies public void gofish appdomaincurrentdomainassemblyresolve currentdomain assemblyresolve foreach string directory in directorygetdirectorieseplugins assemblies new directoryinfodirectorygetfilesdll foreach string assemblyfile in directorygetfilesdirectory dll try fileinfo fi new fileinfoassemblyfile var assembly assemblyloadfilefifullname integrationassemblyattribute integrationassemblyattribute integrationassemblyattributeassemblygetcustomattributetypeofintegrationassemblyattribute catch exception ex exception handling consolewritelinean error has occured while loading plugin from loacation0n1 assemblyfile ex assembly currentdomain assemblyresolveobject sender resolveeventargs args var reference assembliesfirstordefaultfile filename argsnamesplittolist0 dll if null reference return null return assemblyloadfilereferencefullname public sealed class integrationassemblyattribute attribute public guid guid get set public integrationassemblyattributestring assemblyguid guid guidparseassemblyguid,"['c#', '.net']" +642245,how to mark a jasmine test as failed i have a jasmine 20 test that if a function is called the test failedi have a function remoteget that should call the first argument which is a callback if it is successful or the second argument if it failedif it calls the second argument i need to mark the test as failedhow can i clearly mark the test as faileddescribemy tests function itshould call the first function functiondone remoteget function yeah good done function whoa if we got here then it did not work fail done i know i could do something like expecttruetobefalse but i the error you get then would be unclear and unrelated to the actual problem it should give an error like wrong callback was called or remoteget failure was called i was hoping there was something more descriptive in jasminewhat i am really looking for is the python equivalent of,['javascript'] +642310,a simple hello world setuptools package and installing it with pip i am having trouble figuring out how to install my package using setuptools and i have tried reading the documentation on it and so posts but i cannot get it to work properly i am trying to get a simple helloworld application to work this is how far i gothelloworldpyprinthello worldreadmetxthello world readmemanifestinrecursiveinclude images gifsetuppyfrom setuptools import setup find packagessetup namehelloworld version01 licensebsd authorgyeh author email url long descriptionreadmetxt packagesfind packages scripts helloworldpy package data imagesgif data filesimages imageshellogif descriptionhello world testing setuptoolsand i have a blank file called imageshellogif that i want to include in my package as additional data the folder structure looks like thistestsetup helloworldpy images hellogif manifestin readmetxt setuppy when i run python setuppy sthist it generates the thist and helloworldegginfo successfully when i look at sourcestxt under egginfo it contains the script and the image under the images folder and the tarball under thist contains them as wellhowever when i try to run pip install user helloworld01targz on the tarball it successfully installs it but i cannot find the program files helloworldpy and imageshellogif when i look under homelocallibpython33sitepackages i see the egginfo folder and all of it is contents installed there but the homelocalbin folder does not even exist are the program files stores elsewhere what am i doing wrong here i am running arch linux,['python'] +642348,usage of multiple inheritance in java 8 am i using a feature of java 8 or misusing it refer the code and explanation below to know as to why it was chosen to be like thispublic interface drawable public void compileprogram public program getprogram default public boolean istessellated return false default public boolean isinstanced return false default public int getinstancescount return 0 public int getdatasize public floatbuffer putdatafinal floatbuffer databuffer public int getdatamode public boolean isshadowreceiver public boolean isshadowcaster todo use for aabb calculations default public void drawdepthpassfinal int offset final program depthnormalprogram final program depthtessellationprogram program depthprogram istessellated depthtessellationprogram depthnormalprogram if isinstanced depthprogramusedrawarraysinstancedgetdatamode offset getdatasize getinstancescount else depthprogramusedrawarraysgetdatamode offset getdatasize default public void drawfinal int offset if isinstanced getprogramusedrawarraysinstancedgetdatamode offset getdatasize getinstancescount else getprogramusedrawarraysgetdatamode offset getdatasize default public void delete getprogramdelete public static int countdatasizefinal collectiondrawable drawables return drawablesstream maptointdrawablegetdatasize sum public static floatbuffer putalldatafinal listdrawable drawables floatbuffer databuffer bufferutilscreatefloatbuffercountdatasizedrawables 3 drawablesstreamforeachordereddrawable drawableputdatadatabuffer return floatbufferdatabufferclear public static void drawalldepthpassfinal listdrawable drawables final program depthnormalprogram final program depthtessellationprogram int offset 0 for drawable drawable drawables if drawableisshadowreceiver drawabledrawdepthpassoffset depthnormalprogram depthtessellationprogram offset drawablegetdatasize todo count offset only if not shadow receiver public static void drawallfinal listdrawable drawables int offset 0 for drawable drawable drawables drawabledrawoffset offset drawablegetdatasize public static void deleteallfinal listdrawable drawables drawablesstreamforeachdrawabledelete public interface tessellateddrawable extends drawable override default public boolean istessellated return true public interface instanceddrawable extends drawable override default public boolean isinstanced return true override public int getinstancescountpublic class box implements tessellateddrawable instanceddrawable editorfold defaultstatecollapsed desckeepimports static int keep lwjgl imports gl 2 bytes gl aliased line width range gl active texture gl blend color gl array buffer gl active attribute max length gl compressed sluminance gl alpha integer gl active uniform block max name length gl already signaled gl any samples passed gl active subroutine uniform max length gl active program gl active atomic counter buffers gl active resources gl buffer immutable storage int keep own imports uniform projection matrixgetlocation vs positiongetlocation editorfold private floatbuffer data private program program private final float width height depth public boxfinal float width final float height final float depth thiswidth width thisheight height thisdepth depth data generatebox dataclear override public void compileprogram program new program new vertexshaderdatashadersboxvsglslcompile new fragmentshaderdatashadersboxfsglslcompile compileusinguniforms uniform model matrix uniform view matrix uniform projection matrix uniform shadow matrix override public int getinstancescount return 100 override public program getprogram return program override public int getdatasize return 6 6 override public floatbuffer putdatafinal floatbuffer databuffer floatbuffer returndata databufferputdata dataclear clear to reset data state return returndata override public int getdatamode return gl triangles override public boolean isshadowreceiver return true override public boolean isshadowcaster return true private floatbuffer generatebox floatbuffer boxdata bufferutilscreatefloatbuffer6 6 3 put data into boxdata return floatbufferboxdataclear first the steps on how i came to this codei started with the drawable interface and each implementation having its own drawdepthpass draw and delete methodsrefactoring delete to a default method was easy trivial and should not be wronghowever to be able to refactor drawdepthpass and draw i needed access to whether a drawable was tesselated andor instanced so i added the public nondefault methods istessellated isinstanced and getinstancescountthen i figured out it would be slightly cumbersome as we programmers are lazy to implement them in every drawableas a consequence i added the default methods to drawable giving the behaviour of the most basic drawablethen i figured that i am still lazy and do not want to manually implement it for the tessellated and instanced variants eithereso i created tessellateddrawable and instanceddrawable that provide default istessellated and isinstanced respectively and in instanceddrawable i revoked the default implementation of getinstancescountas a result i can have the followingnormal drawable public class a implements drawabletessellated drawable public class a implements tessellateddrawableinstanced drawable public class a implements instanceddrawabletessellated and instanced drawable public class a implements instanceddrawable tessellateddrawablejust to ensure you this all compiles and runs fine the implements instanceddrawable tessellateddrawable gets handled perfectly by java 8 as there is nowhere ever ambiguity on from which interface the functionality should comenow onto my own little oop design assessmentevery drawable is in fact a drawable so collectiondrawable will not breakit is possible to group all tessellateddrawable andor instanceddrawable irrelevant of how exactly it is implementother thoughts i haduse a more conventional layered approach however i thisregarded that as it would end up inabstract class abstractdrawableclass drawable extends abstractdrawableclass tessellateddrawable extends abstractdrawableclass instanceddrawable extends abstractdrawableclass instancedtessellateddrawable extends abstractdrawablei have also considered a builder pattern however that is a pattern to be used when you are creating a lot of unique instances of a certain object and that is not what we are doing here neither is this about the constructor of the objectso the first and final question was am i using a feature of java 8 or misusing it,['java'] +642352,how to handle json that returns both a string and a string array i am using the yahoo fantasy sports api i am getting a result like thisplayer eligible positions position qb eligible positions position wr wrt how is it that i can deserialize this my code looks like thisvar json new javascriptserializerif response null jsonresponse jsonresponseobject jsondeserializejsonresponseresponse return jsonresponseobjectand in my jsonresponsecs filepublic class player public string player key get set public string player id get set public string thisplay position get set public selectedposition selected position get set public eligible positions eligible positions get set public name name get set public class eligible positions public string position get set when i run this since eligible positions can return both a string and a string array i keep getting the error type systemstring is not supported for deserialization of an array i have also tried turning public string position get set to public string position get set but i still get an error how should i handle this,['c#'] +642364,handling incall status bar with custom modal presentation the problemi have noticed some strange behavior when presenting a uinavigationcontroller with a root view controller already pushed naturally with uiviewcontrolleranimatedtransitioning during a phone callif the incall status bar is enabled after the the navigation controller is presented the navigation controller shifts its view down as expected but when the call is ended the controller does not shift its view back up leaving a 20p gap under the status barif the incall status bar is enabled before presenting the controller the controller does not account for the status bar at all leaving 4p of the 44phigh navigation bar peeking out from under the 40p status bar when the call is ended the controller shifts its view down to accommodate the normal 20p status barnote this was tested on the simulator due to the ease of enablingthisabling the incall status bar but testers have observed this phenomenon on actual phonesmy partial workaroundi hacked around the issue by adjusting the frame of the controller during presentation if the status bar was an abnormal heightinterface customanimationcontroller nsobject uiviewcontrolleranimatedtransitioningendimplementation customanimationcontroller voidanimatetransitioniduiviewcontrollercontexttransitioningtransitioncontext uiviewcontroller tocontroller transitioncontext viewcontrollerforkeyuitransitioncontexttoviewcontrollerkey uiview container transitioncontext containerview cgrect frame transitioncontext finalframeforviewcontrollertocontroller if cgrectequaltorectframe cgrectzero in my experience the final frame is always a zero rect so this is always hit uiedgeinsets insets uiedgeinsetszero my solution was to inset the container frame by the difference between the actual status bar height and the normal status bar height insetstop cgrectgetheightuiapplication sharedapplicationstatusbarframe 20 frame uiedgeinsetsinsetrectcontainerbounds insets tocontrollerviewframe frame container addsubviewtocontrollerview perform whizbang animation here endthis solution ensures that the navigation bar is below the status bar but the navigation controller still fails to shift itself back up when the call is ended so the app is at least usable but there is an ugly 20p gap above the navigation bar after a call endsis there a better wayam i missing some critical step to ensure that the navigation controller accounts for the incall status bar on its own it works just fine when presented with the builtin modal presentation stylein my opinion this smacks of a uikit bug a after all the navigation controller seems to receive the uiapplicationwillchangestatusbarframenotification see second point of the problem if anyone else has encountered this problem and has found a better way i would greatly appreciate a solution,['ios'] +642377,difference between numpyarray shape r 1 and r in numpy some of the operations return in shape r 1 but some return r this will make matrix multiplication more tedious since explicit reshape is required for example given a matrix m if we want to do numpydotm0 numpyones1 r where r is the number of rows of course the same issue also occurs columnwise we will get matrices are not aligned error since m0 is in shape r but numpyones1 r is in shape 1 rso my questions arewhats the difference between shape r 1 and r i know literally it is list of numbers and list of lists where all list contains only a number just wondering why not design numpy so that it favors shape r 1 instead of r for easier matrix multiplicationare there better ways for the above example without explicitly reshape like this numpydotm0reshaper 1 numpyones1 r,['python'] +642414,cameraparameterssetrecordinghint and aspect ratio i have found some odd behavior around cameraparameterssetrecordinghint that i would like to understand betterif i set it to true the size of the preview image can come back different from what i pass to setpreviewsize it depends on what size i set it to some aspect ratios work and some do notsee the screenshots below setpreviewsize has been set to 640x480 for both but one has setrecordinghint to true and the other to false i have the code that produces this effect on githubis this expected behavior the docs for setrecordinghint do not indicate anything like this,['android'] +642504,is there a tab equivalent of stdendl within the standard library using c is there an equivalent standard library constant for t like there is for a newlineideallystdstringstream s stdtab textif not why is this the casei am aware i can just insert a t but i would like to sate my curiosity,['c++'] +642524,uncaught typeerror cannot read property value of null i am getting error in this code i am trying to do an event where in when the page is load it will do the event but the problem is when i go to other function but same page it gets a error of null on that variable it has no problem when i execute this codes but when i am on other part of my codes this error occurs uncaught typeerror cannot read property value of null documentreadyfunction var str documentgetelementbyidcal previewvalue var str1 documentgetelementbyidyearvalue var str2 documentgetelementbyidholidayvalue var str3 documentgetelementbyidcal optionvalue if str str1 str2 str3 documentgetelementbyidcalendar previewinnerhtml return if windowxmlhttprequest code for ie7 firefox chrome opera safari xmlhttpnew xmlhttprequest else code for ie6 ie5 xmlhttpnew activexobjectmicrosoftxmlhttp xmlhttponreadystatechangefunction if xmlhttpreadystate4 xmlhttpstatus200 documentgetelementbyidcalendar previewinnerhtmlxmlhttpresponsetext var url calendar preview varsplugin url id str ystr1hstr2optstr3 xmlhttpopengeturltrue xmlhttpsend,['javascript'] +642543,why unaligned apk is needed android gradle produces apk in two binaries unaligned and alignedthe document saidonce you have signed the apk with your private key run zipalign on the file this tool ensures that all uncompressed data starts with a particular byte alignment relative to the start of the file ensuring alignment at 4byte boundaries provides a performance optimization when installed on a device when aligned the android system is able to read files with mmap even if they contain binary data with alignment restrictions rather than copying all of the data from the package the benefit is a reduction in the amount of ram consumed by the running applicationseems like aligned apk is strongly recommended to thistribute for me i only use aligned apk as a result product and ignore unaligned apk does unaligned apk have any special usage during development,['android'] +642574,is it still valid to use ieedgechrome1 i read chrome frame closed last month i thus tried to understand what it would mean for the xua tag and after 3 hours of research i still did not find the answer i am looking for my question is the following is it still valid nowdays to use ieedgechrome1 or should i stop at ieedge from now on or what would be the best pratice to do regarding xua should it be avoided,['html'] +642582,uirefreshcontrol pull to refresh in ios 7 i am trying to get the pull to refresh feature on ios 7 in my table view in my viewdidload i haverefreshcontrol uirefreshcontrol alloc initselfmytableview setcontentoffsetcgpointmake0 refreshcontrolframesizeheight animatedyesrefreshcontrol beginrefreshingrefreshcontrol addtargetself actionselectorrefreshtable forcontroleventsuicontroleventvaluechangedi then runvoidrefreshtable selfmytableview reloaddata refreshcontrol endrefreshingon ios 6 this would mean that as you pull down on the table view it would show the circular arrow that would get stretched out as you pull and after pulled far enough it would refresh right now i see no circular arrow what am i missing,"['ios', 'objective-c']" +642641,what does this typedef statement mean in a c reference page they provide some typedef examples and i am trying to understand what they mean simple typedeftypedef unsigned long mylong more complicated typedeftypedef int int t intp t fpint mylong arr t10so the simple typedef the first declaration i understandbut what are they declaring with the second one repeated belowtypedef int int t intp t fpint ulong arr t10particularly what does fpint mylong mean,['c++'] +642711,how to execute sql script file in hibernate jpa i need to perform bulk insert i have a sql script file generated by reading excel file now i need to execute the script how to do this in hibernate jpa,"['java', 'mysql']" +642789,how can i change the default look and feel of jframe not theme of netbeans i want to change the default look and feel of all the jframe forms i will create from here on out instead of having to manually edit every look and feel code of every jframe i create from nimbus to windowsso what i want to happen is that from when i startup netbeans to when i create a new jframe the code for the look and feel of that jframe i just created will automatically be set to windows rather than nimbusi want the look and feel code to look like this right after i click new jframe form try for javaxswinguimanagerlookandfeelinfo info javaxswinguimanagergetinstalledlookandfeels if windowsequalsinfogetname javaxswinguimanagersetlookandfeelinfogetclassname break note i am not trying to theme netbeans itself i just want the jframe that i create to have the windows look and feel by default so i do not have to go through the source tab and change nimbus to windows for every jframe i create,['java'] +642943,how to slide a hidden div updown on click of a button i want to achieve this type of a slide down except instead of on hover i think i need some sort of script that triggers the slide down on click and then click again to trigger the reverse slide up i will have a div thats hidden top 400px above the top of the page and when the button is clicked with slide down and sit at top 0htmldiv classcontainerdiv classonehover me to reveal new divdivdiv classtwoi slidbrand i am higher than the div before medivdivcsscontainer overflowhiddenheight 60pxone position relativetop 0backgroundcolor lightbluezindex 1two position relativetop 40pxbackgroundcolor yellowzindex 1webkittransition top 1smoztransition top 1sotransition top 1stransition top 1sonehover two top 0pxhere is a working fiddle any help would be appreciated i have tried using slidetoggle however this creates an expanding effect which is not the type of slide down i want to achievemany thanks,"['jquery', 'html', 'css']" +642981,add not null field without default value into a populated db i have a table let us call it mytable it is part of a postgresql databasein mytable are a lot of entries let us say over a million i would like to add a field to this table let us call it mynewfield it is to be added by an activerecord migrationthis field is to be without default values and not nullable the result in it is migration class would be something like soclass addmyfieldtomytable activerecordmigration def change add column my table my field text null false endendhowever it will trigger an error pgnotnullviolation because the table already contains rows all which will have myfield set to nullwhat i would like to do is add the row without default value and nullable set to false without triggering a pgnotnullviolation then insert a value from another table into each records this would probably be achievable by adding the field with nullable set to true then adding the values then changing back to nullable set to false however i am interested to know if it is possible to do so in a single shot,"['ruby-on-rails', 'ruby']" +642999,how to optimize this product of three matrices in c for x86 i have a key algorithm in which most of its runtime is spent on calculating a dense matrix productaay where a is an mbyn matrix a is its conjugate transpose y is an mbyk matrixtypical characteristics k is much smaller than both m or and k is typically 10 m in the range 500 20 and in the range 100 10based on these dimensions according to the lessons of the matrix chain multiplication problem it is clear that it is optimal in a numberofoperations sense to structure the computation as aay my current implementation does that and the performance boost from just forcing that associativity to the expression is noticeablemy application is written in c for the x86 64 platform i am using the eigen linear algebra library with intels math kernel library as a backend eigen is able to use imkls blas interface to perform the multiplication and the boost from moving to eigens native sse2 implementation to intels optimized avxbased implementation on my sandy bridge machine is also significant however the expression a aadjoint y written in eigen parlance gets decomposed into two general matrixmatrix products calls to the xgemm blas routine with a temporary matrix created in between i am wondering if by going to a specialized implementation for evaluating the entire expression at once i can arrive at an implementation that is faster than the generic one that i have now a couple observations that lead me to believe this areusing the typical dimensions described above the input matrix a usually would not fit in cache therefore the specific memory access pattern used to calculate the threematrix product would be key obviously avoiding the creation of a temporary matrix for the partial product would also be advantageousa and its conjugate transpose obviously have a very related structure that could possibly be exploited to improve the memory access pattern for the overall expressionare there any standard techniques for implementing this sort of expression in a cachefriendly way most optimization techniques that i have found for matrix multiplication are for the standard ab case not larger expressions i am comfortable with the microoptimization aspects of the problem such as translating into the appropriate simd instruction sets but i am looking for any references out there for breaking this structure down in the most memoryfriendly manner possibleedit based on the responses that have come in thus far i think i was a bit unclear above the fact that i am using ceigen is really just an implementation detail from my perspective on this problem eigen does a great job of implementing expression templates but evaluating this type of problem as a simple expression just is not supported only products of 2 general dense matrices areat a higher level than how the expressions would be evaluated by a compiler i am looking for a more efficient mathematical breakdown of the composite multiplication operation with a bent toward avoiding unneeded redundant memory accesses due to the common structure of a and its conjugate transpose the result would likely be difficult to implement efficiently in pure eigen so i would likely just implement it in a specialized routine with simd intrinsics,['c++'] +643021,how to embed vlc media player to my android app is there a way to embed vlc media player to android application i have several issues1 i have a video streaming camera from rtsp and i cannot play its stream on my regular videoview panel sorry this video cannot be played error however i installed the vlc application for android beta version and i was able to play it2 my main objective is to port a desktop java application which uses vlc plugin to android i want to accomplish this task with minimum effort i have some time issuesanother alternative is there a way to embed codecs used by vlc to my application because with my videoview the result varies according to the format of the video i can play some other videos streamed through rtsp on my videoviewi search through internet and found a libvlc but also some notes about that libvlc for android is not complete but those notes belong to a past time even in stackoverflow,['android'] +643218,are there any cases where it is incorrect to replace push back with emplace back can i break a valid c03 program by replacing stdvectorpush back with emplace back and compiling it with c 11 compiler from reading emplace back reference i gather it should not happen but i will admit i do not fully get rvalue references,['c++'] +643246,how to execute parent directive before child directive i am looking to write two angular directives a parent and a child directive to create sortable and cloneable widgets the intended markup isdiv classwidgetcontainer datasortablewidgets section classwidget datacloneablewidgetsectiondivhowever the child directive seems to execute before the parent before a certain element is available its added by the parentfunction sortablewidgetsdirective return priority 200 restrict a link function scope element attrs elementfindwidget headerappenddiv classwidgetcontrolsdiv elementsortable function cloneablewidgetdirective return priority 100 restrict a link function scope element attrs this directive wrongfully executes first so widgetcontrols is no available elementfindheader widgetcontrolsappenddiv classclonehandlediv as you can see i tried setting priority but i think because they are on different elements it does not workhow can i make the parent execute first,['javascript'] +643318,what base name parameter do i need in my route to make this django api work i am building a django application that exposes a rest api by which users can query my applications models i am following the instructions heremy route looks like this in myapps urlpyfrom rest framework import routersrouter routersdefaultrouter routerregisterrmyobjectspidd viewsmyobjectsviewseturlrapi includerouterurlsmy model looks like thisclass myobjectmodelsmodel name modelstextfieldmy serializer looks like thisclass myobjectserializerserializershyperlinkedmodelserializer class meta model myobject fields id namemy viewset looks like thisclass myobjectsviewsetviewsetsviewset def retrieveselfrequestpknone queryset myobjectsobjectsgetpkpkcustommyobjectlist if not queryset return responsestatusstatushttp 400 bad request else serializer myobjectserializerqueryset return responseserializerdatastatusstatushttp 200 okwhen i hit apimyobjects60 i get the following errorbase name argument not specified and could not automatically determine the name from the viewset as it does not have a model or queryset attributei understand from here that i need a base name parameter on my route but from the docs it is unclear to me what that value of that base name parameter should be can someone please tell me what the route should look like with the base name,['python'] +643349,are there tuples in php i know in python and other languages we have access to tuples to better facilitate semantically or otherwise the structuring of datamy question is does php have tuplesif not what is the nearest facility,['php'] +643391,what is the correct way to instantiate c11 random facilities after looking a various examples on the uses of the new random facilities in c i am left a little confused as to best practices specifically related to lifetimes of various instancesfor instance in some examples the use of random device is either static in a local scope like a function or is a static global variable or is just plainly a local tu static stdrandom device global sourcevoid foo static stdrandom device local static source static stdmt19937 genlocal static source stduniform int thistribution thist010 thistgen void boo stdmt19937 genglobal source stduniform int thistribution thist010 thistgen void roo stdrandom device local source stdmt19937 genlocal source stduniform int thistribution thist010 thistgen int main static stdmt19937 genglobal source stduniform int thistribution thist010 thistgen return 0 tu q1 if foo or boo can be accessed by multiple threads is it ok to have the generator and source be static is there any kind of thread safety guarantees like those in shared ptrq2 is there any wording in the standard that thiscusses assumptions and issues related to instantiation,['c++'] +643448,what is apple warning against in arc documentation caveat about pass by reference in apples documentation about arc they make a point of spelling out a problematic scenario in which arc will generate a boilerplate temporary variable behind the scenes search on the compiler therefore rewritesthe gist of the warning seems to be that because the stackbased variable is strong and the byreference parameter to the called method performoperationwitherror is autoreleasing arc will generate a temporary local variable to serve the memory management needs of the autoreleasing variable but because the temporary variable is assigned to the strong variable in the boilerplate example it seems as though from a clients point of view there is no riskwhat exactly is the documentation taking pains to warn us about here what is the risk as either a client or as an implementor of a method that may be called in this way with an autoreleased returnbyvalue parameter,"['ios', 'objective-c']" +643470,downgrade net 45 application to 40 i want to downgrade a net library from framework version 45 to net 40i have several libs installed using nugetmicrosoftaspnetwebapiclient and it is dependenciesnewtonsoftjson systemnethttp microsoft net 4 http client librariesi do the followingin settings of each project in my solution i set target framework to 40 after it i tried to rebuild my solution but of course without success because of error the type or namespace name newtonsoft could not be found are you missing a using directive or an assembly reference the same for http client libsusing nuget ui manager i removed dependencies and tried to reinstall but there is an error could not install package microsoftaspnetwebapiclient 511 you are trying to install this package into a project that targets netframeworkversionv40 but thepackage does not contain any assembly references or content files that are compatible with that framework for more information contact the package authormy question is can i downgrade this project or i should replace these libs with some that support net 4 and rewrite some parts of code,"['c#', '.net']" +643542,nginx unable to open primary script i got error messagefastcgi sent in stderr unable to open primary script homemessiwebwordpressindexphp no such file or directory while reading response header from upstream client x server wdomaincom request get http11 upstream fastcgiunixvarrunphp5fpmsock host wdomaincomhere are my configuration filesetcphp5fpmphpinicgifix pathinfo0doc root user dir etcphp5fpmphpfpmconfglobalpid varrunphp5fpmpiderror log varlogphp5fpmlogincludeetcphp5fpmpooldconfetcphp5fpmpooldwconfwuser wdatagroup wdatalisten varrunphp5fpmsocklistenowner wdatalistengroup wdatalistenmode 06pm dynamicpmmax children 5pmstart servers 2pmmin spare servers 1pmmax spare servers 3chdir securitylimit extensions php php3 php4 php5php flagthisplay errors onphp admin valueerror log varlogfpmphpwlogphp admin flaglog errors onetcnginxnginxconfuser nginxworker processes 1error log varlognginxerrorlog warnpid varrunnginxpidevents worker connections 1024http include etcnginxmimetypes server tokens off default type applicationoctetstream log format main remote addr remote user time local request status body bytes sent http referer http user agent http x forwarded for access log varlognginxaccesslog main sendfile on tcp nopush on keepalive timeout 65 gzip on include etcnginxsitesenabledetcnginxsitesenabledwordpreserver listen 80 server name wdomaincom root homemessiwebwordpress error log varlognginxerrwordpresslog index indexphp location try files uri uri indexphpargs location faviconico log not found off access log off location robotstxt allow all log not found off access log off location deny all location uploadsfilesphp deny all location php fastcgi split path info php fastcgi pass unixvarrunphp5fpmsock fastcgi index indexphp fastcgi param script filename document rootfastcgi script name include etcnginxfastcgi params setup user permissionadduser wdata messichown r wdatawdata homemessiwebchmod r 664 homemessiwebwordpresshow can i resolve thisthanks,['php'] +643590,place content in between paragraphs without images i am using the following code to place some ad code inside my content phpcontent apply filtersthe content postpost contentcontent explode contenthalfway mark ceilcountcontent 2first half content implode array slicecontent 0 halfway marksecond half content implode array slicecontent halfway markecho first half contentecho your ads codeecho second half contenthow can i modify this so that the 2 paragraphs top and bottom enclosing the ad code should not be the one having images if the top or bottom paragraph has image then try for next 2 paragraphs example correct implementation on the right,"['php', 'html']" +643629,uibutton is not highlighting within viewcontroller in uipageviewcontroller in ios7 i have a uibutton within a view controller which is embedded in a uipageviewcontroller page view controller is in scrolling modeso no gestures when i touch on the button action method will be called but there is no visible state changes highlighted state is happening for the button that means button looks like untouched observed only in ios7 any work around for this case 1 in normal viewcontroller the behaviour of button with and without tap case 2 in one of the pageviewcontrollers viewcontroller the behaviour of button with and without tap,['ios'] +643728,status bar appears in qlpreviewcontroller after toolbar reappers status bar is initially hidden in infoplist with status bar is initially hidden set to yes and view controllerbased status bar appearance set to nobut when i present a qlpreviewcontroller after two taps to document to make toolbar thisappear and appear again status bar appears in application tooany idea how to prevent this from happening,"['ios', 'objective-c']" +643770,is there a way i can force chrome to do subpixel rendering for a slow translation im doing a very slow transition of a background image a view of space that slides slowly to the left my problem is while it looks beautiful on firefox it looks horrible on chrome i get a jittery effect due to chromes lack of subpixel rendering and the image just snaps to the next pixel i cannot speed the image up because it will destroy the effect im trying to achieve i have tried using translatez tricks i have tried every css3 effect i could think of to make it look better ive tried kineticjs ive even tried babylonjs hoping that webgl would fix my problemat this point im at a loss and i might just have to give chrome users a static background and cater more to the firefox users in regards to the neat little things i can do for the ui ux and then just put a thisclaimer on my site saying that the page is best viewed in ff i really dont want to do this is there any work around at all,"['javascript', 'css']" +643879,sqlite ef6 programmatically set connection string at runtime i try to migrate form ef 35 to 6 with sqlite as database we can not set the connection string in the app config file this works without problems with ef6 we have to set connection string programmatically at runtime after user has selected the sqlite filehere is our appconfigxml version10 encodingutf8configuration configsections for more information on entity framework configuration visit section nameentityframework typesystemdataentityinternalconfigfileentityframeworksection entityframework version60 cultureneutral publickeytokenb77a5c561934e089 requirepermissionfalse configsections connectionstrings add nametestcontext connectionstringdata sourcedatatestdbsqliteforeign keystrue providernamesystemdatasqlite connectionstrings entityframework defaultconnectionfactory typesystemdataentityinfrastructurelocaldbconnectionfactory entityframework parameters parameter valuev110 parameters defaultconnectionfactory providers provider invariantnamesystemdatasqlite typesystemdatasqliteef6sqliteproviderservices systemdatasqliteef6 providers entityframework systemdata dbproviderfactories remove invariantsystemdatasqlite remove invariantsystemdatasqliteef6 add namesystemdatasqlite invariantsystemdatasqlite descriptionnet framework data provider for sqlite entity framework 6 typesystemdatasqliteef6sqliteproviderfactory systemdatasqliteef6 dbproviderfactories systemdataconfigurationhere ist the dbcontextpublic class firmwarecontext dbcontext public firmwarecontext thisdefault connection public firmwarecontextstring connextionnameorstring baseconnextionnameorstring if i connect with the connecation name from appconfig all works without problems if i try to pass the connection string with the second constructor this failshere is small examplesqliteconnectionstringbuilder builder factorycreateconnectionstringbuilder as sqliteconnectionstringbuilderbuilderdatasource datasource path to file name of the userbuilderforeignkeys truevar context new firmwarecontextbuildertostringvar context new firmwarecontextbuildertostringvar test contextfirmwarefirstordefaulti got the following exception schla14sselwort wird nicht untersta14tzt foreign keys the key foreign key is nott supported if i remove the foreign key set i got the following exception the provider did not return a providermanifesttoken string and some inner exceptionsit seems that the basconnectionstring build the mssql connection string and for sqlitehow can i make my second constructor campatible with sqlite,['.net'] +643917,link a static library to a shared library and hide exported symbols i am having an annoying problem with the linker i want to link some symbols from a shared library to a static library but not export its symbols ie i cannot simply merge the libraries or link with wholearchive what i want is link as in like linking an executable solving undefined symbols my shared library to a static one and remove the undefined symbolsthe thing i am looking for is probably just a linker option but i cannot put my finger on iti will try to describe the problem the best i can it is not that easy and then provide a toy minimal example to play withedit the problem has been solved solution posted at the bottom of the questionquick descriptioni want to use the ld preload trick to trap some function calls in an executable this executable is linked against a third party shared library which contains the function definition of the functions i want to trapthis third party library also contains symbols from yet another library which i am also using in my library but with a different noncompatible version what i want to do is compile my shared library and link it at compile time with the definitions of the last static library without exporting the symbols so that my shared library uses a different version from the one i want to trapsimplified problem descriptioni have a third party library called libextso for which i do not have the source code this defines a function bar and uses a function foo from another library but the symbols are both defined there nm libextso0a16 t bar09e8 t fooas i mentioned foo is an external dependency for which i want to use a newer version i have an updated library for it let us call it libfooa nm libfooa0 t foonow the problem is that i want to create a dynamic library which redefines bar but i want my library to use the the definition of foo from libfooa and i want the functions from libextso to call the function foo from libextso in other words i want a compile time linkage of my library to libfooawhat i am looking for is define a library which uses libfooa but does not export its symbols if i link my library to libfooa i get nm libmineso0a78 t bar0b2c t foowhich means i overload both foo and bar i do not want to override foo if i do not link my library to libfooa i get nm libmineso0a78 t bar you fooso my library will use their version of foo which i do not want either what i want is nm libmineso0a78 t barwhere foo is linked at compile time and its symbol not exportedminimal exampleyou do not need to read this but you can use it to play around and find a solutionbarcpp represents the third party app i do not have the code forinclude iostreamextern c void foo stdcerr oldfoo stdendl extern c void bar stdcerr oldbar stdendl foo foocpp represents a newer version of a function used by both my lib and the third partyinclude iostreamextern c void foo stdcerr newfoo stdendl trapcpp the code from my library it traps bar calls the new foo and forwardsinclude iostreamextern c include dlfcnhextern c void fooextern c void bar stdcerr newbar stdendl foo should be newfoo void fwd voiddlsymrtld next bar fwd should use oldfooexeccpp a dummy executable to call barextern c void barint main barmakefile unix only sorrydefault the third party library g c o baro barcpp fpic gcc shared wlsonamelibextso o libextso baro the updated library g c o fo foocpp fpic ar rcs libfooa fo my trapping library g c o trapo trapcpp fpic gcc shared wlsonamelibmineso o libmineso trapo ldl l lfoo the dummy executable g o test execcpp l libextsoin this case bar calls foo the normal execution is testoldbaroldfoopreloading my library intercepts bar calls my foo and forwards bar the current execution is ld preloadlibmineso testnewbarnewfoldbarnewfoothe last line is wrong the desired output is ld preloadlibmineso testnewbarnewfoldbaroldfoosolution1 as pointed out in the accepted answer we can use a linker version script to change the scope of the undesired symbols from global to localbar global bar local compiling with the linker version shows foo is local and the program now behaves as expected gcc shared wlsonamelibmineso wlversionscriptlibmineversion o libmineso trapo ldl l lfoo nm libmineso0978 t bar0 a bar 0a2c t foo ld preloadlibmineso testnewbarnewfoldbaroldfoo2 an alternative is to recompile libfooa with the attribute fvisibilityhidden and link against that the visibility of the exported symbols is then local too and the behavior is the same as above,['c++'] +644058,how do i install pypdf2 module using windows as a newbie i am having difficulties installing pypdf2 module i have downloaded where and how do i install setuppy so i can use module in python interpreter,['python'] +644109,how to generate a table of contents toc with itext i have created a document with some chaptershow to generate a toc for this documentit should look like thistocchapter 1 3chapter 2 4chapter 3 6chapter 4 9chapter 5 10,['java'] +644115,modularize a big ios app using cocoapods inspired by a hubspot blogpost i have split up my ios project into one main project and several subprojects that are added to the main project using cocoapods i have one main project and several subprojects each in a separate git repository and podspec file the advantage is that each subproject can be compiled run and tested on it is own that approach works well except for sharing global items like static strings global protocols base classes between the subprojects eg someprotocolh constantsh i have defined the static strings protocols and base classes in the main project and created a pod spec in the main project that includes the global items which is added to the child projects pod file the child projects compile and run using this approach but the main project does not compile since each subproject pod will include files like import someprotocolhimport constantshthat although part of the main project cannot be found when the individual pod libraries are compiled is there a best practice how to split big ios projects into several smaller ones,"['ios', 'objective-c']" +644252,how to protect ios bundle files like plist imagesqlitemedia files i have created sample hello world project and then added dataplist file to resource foldernow people can easily get the bundle files by unzipping the ipa file is there any ways to protect the dataplist file that saved in the application bundle of iphone app encryption is a decent method of scrambling the data but i do not know how to implement encription conceptdo you have any sample code nsstring filepath nsbundle mainbundle pathforresourcedata oftypeplist nsarray arrdata nsarray allocinitwithcontentsoffilefilepath nsdata datas nskeyedarchiver archiveddatawithrootobjectarrdata datas writetofilefilepath atomicallyyesafter extracting ipa file,"['ios', 'iphone']" +644345,why do we need to install gulp globally and locally 2 manuals about gulp say that i need to install gulp first globally with g flag and then one more time locally why do i need this,['javascript'] +644382,add ngclick dynamically in directive link function i am trying to create a directive that would allow an element to be defined as clickable or not and would be defined like thispage isclickabletrue transcluded elementspagei want the resulting html to bepage isclickabletrue ngclickonhandleclick transcluded elementspagemy directive implementation looks like thisappdirectivepage function return restrict e template div ngtranscludediv transclude true link functionscope element attrs var isclickable angularisdefinedattrsisclickable scopeevalattrsisclickable true true false if isclickable attrssetngclick onhandleclick scopeonhandleclick function consolelogonhandleclick i can see that after adding the new attribute angular does not know about the ngclick so it is not firing i tried adding a compile after the attribute is set but it causes an infinite linkcompile loop i know i can just check inside the onhandleclick function if the isclickable value is true but i am curious how one would go about doing this with dynamically adding an ngclick event because i may need to do with this with multiple other ng directives and i do not want to add unnecessary overhead any ideas,['javascript'] +644408,c global variable initialization order i do not understand what the following code example does and how it does itinclude stdiohint fint a f a exists just to call fint x 22int f x return 123 unimportant arbitrary numberint main printfdn xwhen this is ran it prints 23 which is the intuitive answerhowever in c global variables are supposed to be initialized in order of definition that would mean that a should be initialized before x because it is defined before x if that was the case then the function f would have to be called before x was initialized because the call to f is a part of as definitionif f is indeed called before x is initialized that would mean that f would try to increment x the result of which i am not really certain of most likely ub or some gibberish value then after a is initialized x would be initialized to 22 and the program would print out 22evidently that is not what happens but what does what does that code actually doit definitely seems like x is set to 22 before a f is evaluated but that would mean that the order of initialization is reversed i could also be wrong about what initialization is or when it happens,['c++'] +644409,use onclick in properties in layout for dialogs android i have a activity like thistextview txt bank textview findviewbyidridtxt search bank txt banksetonclicklistenernew onclicklistener override public void onclickview arg0 dialog bank new dialogactivity search2this dialog bankgetwindowrequestfeaturewindowfeature no title dialog banksetcontentviewrlayoutlist bank dialog bankshownow in the list bankxml i have about 20 image that i want to set their onclick field in layout in properties window to a methodthe problem is that my method cannot be find because this method should be in layouts activity but this is a dialog and do not have any activityplease help me how to this use onclick,['android'] +644425,opencv detect image against a image set i would like to know how i can use opencv to detect on my videocamera a image the image can be one of 500 imageswhat i am doing at the moment voidviewdidload super viewdidload do any additional setup after loading the view selfvideocamera cvvideocamera alloc initwithparentviewimageview selfvideocameradelegate self selfvideocameradefaultavcapturedeviceposition avcapturedevicepositionback selfvideocameradefaultavcapturesessionpreset avcapturesessionpresethigh selfvideocameradefaultavcapturevideoorientation avcapturevideoorientationportrait selfvideocameradefaultfps 30 selfvideocameragrayscalemode novoidviewdidappearboolanimated super viewdidappearanimated selfvideocamera startpragma mark protocol cvvideocameradelegateifdef cplusplus voidprocessimagecvmatimage do some opencv stuff with the image cvmat image copy cvtcolorimage image copy cv bgra2bgr invert image bitwise notimage copy image copy cvtcolorimage copy image cv bgr2bgraendifthe images that i would like to detect are 25kb small few got text on them but others are just signs here a exampledo you guys know how i can do that,"['c++', 'ios', 'objective-c']" +644532,aspnet identity difference between useoauthbearertokens and usecookieauthentication the aspnet team has shipped new samples showing how to use the identity packages they are contained in the following nuget package microsoft aspnet identity samplesthe samples are very helpful but there have been loads of changes from how things were done originally in the templates that shipped my specific question in the original spa template there was the following code oauthoptions new oauthauthorizationserveroptions tokenendpointpath new pathstringtoken provider new applicationoauthproviderpublicclientid usermanagerfactory authorizeendpointpath new pathstringapiaccountexternallogin accesstokenexpiretimespan timespanfromdays14 allowinsecurehttp true enable the application to use bearer tokens to authenticate users appuseoauthbearertokensoauthoptionsbut in the new samples in the nuget package that code is gone and in its place is this code appusecookieauthenticationnew cookieauthenticationoptions authenticationtype defaultauthenticationtypesapplicationcookie loginpath new pathstringaccountlogin provider new cookieauthenticationprovider enables the application to validate the security stamp when the user logs in this is a security feature which is used when you change a password or add an external login to your account onvalidateidentity securitystampvalidatoronvalidateidentityapplicationusermanager applicationuservalidateinterval timespanfromminutes30 regenerateidentity manager user usergenerateuseridentityasyncmanager can anyone help me understand the difference between appuseoauthbearertokens and appusecookieauthentication and why this change was made they both seem to allow the application to behave in the same way and i could use some clarification on this changethanksben,"['c#', 'asp.net']" +644745,amending url for list thisplay links in django 16 admin change list what i would like to know is how do i change the url that is applied to the items listed in list thisplay links of an adminmodeladmin class more specifically i would like admincontactscontacts12345 to become contacts12345 all solutions i could find were quite old somewhat convoluted and geared towards doing something else on top so i was hoping there is some obvious way i am missing i was kind of expecting list thisplay link url or similar to exist to override in the modeladmin,['python'] +644763,amazon ses email address is not verified i am starting with the amazon servers and started studying about ses i am using aspnet c and made aamy code based tutorials i already checked the domain and also checked the emails in which i will run the test so that when i run my code it generates the following error message transaction failed the server response was message rejected email address is not verified i do not know what it is because i followed all possible steps single detail is not yet ordered the release of access to production but i think it can not be i am still testing the servicemy codepublic void enviarses02 try const string from verified email address const string to verified email address const string subject amazon ses test smtp interface accessed using c const string body this email was sent through the amazon ses smtp interface by using c const string smtp username my username replace with your smtp username const string smtp password my password replace with your smtp password const string host emailsmtpuswest2amazonawscom const int port 25already tried with all recommended ports smtpclient client new smtpclienthost port clientcredentials new systemnetnetworkcredentialsmtp username smtp password clientenablessl true try consolewritelineattempting to send an email through the amazon ses smtp interface clientsendfrom to subject body responsewriteenviado catch exception ex responsewritebro email nao foi enviadobr responsewriteolhao erro exmessage catch exception ex responsewriteerror message exmessage,"['c#', 'asp.net']" +644779,canvas trying to use a recycled bitmap androidgraphicsbitmap in android i am working on the crop image class but encounter a recycled bit map problem0302 231410514 eandroidruntime16736 fatal exception thread14700302 231410514 eandroidruntime16736 javalangruntimeexception canvas trying to use a recycled bitmap androidgraphicsbitmap428e54500302 231410514 eandroidruntime16736 at androidgraphicscanvasthrowifrecycledcanvasjava10260302 231410514 eandroidruntime16736 at androidgraphicscanvasdrawbitmapcanvasjava10960302 231410514 eandroidruntime16736 at androidgraphicsbitmapcreatebitmapbitmapjava6040302 231410514 eandroidruntime16736 at eujanmullerandroidsimplecropimagecropimage1preparebitmapcropimagejava6300302 231410514 eandroidruntime16736 at eujanmullerandroidsimplecropimagecropimage1runcropimagejava6360302 231410514 eandroidruntime16736 at eujanmullerandroidsimplecropimagecropimage6runcropimagejava3430302 231410514 eandroidruntime16736 at eujanmullerandroidsimplecropimageutilbackgroundjobrunutiljava1750302 231410514 eandroidruntime16736 at javalangthreadrunthreadjava856the line that error occur is the mscale 2560f mbitmapgetwidth line 630 please search thisfor more information notice the code do not has this error before i adding the checkrotation function and that function return a bitmap and that bitmap has caused the exception this is the hintsalso in the function i have copied the original bitmap and recycle the old bitmap so it should not be the root of problem you are suggested not to look on the code one by one but search the keywords thanks for helping the activity can crop specific region of interest from an image public class cropimage extends monitoredactivity final int image max size 1024 private static final string tag cropimage public static final string image path imagepath public static final string scale scale public static final string orientation in degrees orientation in degrees public static final string aspect x aspectx public static final string aspect y aspecty public static final string output x outputx public static final string output y outputy public static final string scale up if needed scaleupifneeded public static final string circle crop circlecrop public static final string return data returndata public static final string return data as bitmap data public static final string action inline data inlinedata these are various options can be specified in the intent private bitmapcompressformat moutputformat bitmapcompressformatjpeg private uri msaveuri null private boolean mdofacedetection true private boolean mcirclecrop false private final handler mhandler new handler private int maspectx private int maspecty private int moutputx private int moutputy private boolean mscale private cropimageview mimageview private contentresolver mcontentresolver private bitmap mbitmap private string mimagepath boolean mwaitingtopick whether we are wait the user to pick a face boolean msaving whether the save button is already clicked highlightview mcrop these options specifiy the output image size and whether we should scale the output to fit it or just crop it private boolean mscaleup true private final bitmapmanagerthreadset mdecodingthreads new bitmapmanagerthreadset override public void oncreatebundle icicle superoncreateicicle mcontentresolver getcontentresolver requestwindowfeaturewindowfeature no title setcontentviewrlayoutcropimage mimageview cropimageview findviewbyidridimage showstoragetoastthis intent intent getintent bundle extras intentgetextras if extras null if extrasgetstringcircle crop null if buildversionsdk int buildversion codeshoneycomb mimageviewsetlayertypeviewlayer type software null mcirclecrop true maspectx 1 maspecty 1 mimagepath extrasgetstringimage path mbitmap checkrotationmimagepath logdtest1mbitmapisrecycled if extrascontainskeyaspect x extrasgetaspect x instanceof integer maspectx extrasgetintaspect x else throw new illegalargumentexceptionaspect x must be integer if extrascontainskeyaspect y extrasgetaspect y instanceof integer maspecty extrasgetintaspect y else throw new illegalargumentexceptionaspect y must be integer moutputx extrasgetintoutput x moutputy extrasgetintoutput y mscale extrasgetbooleanscale true mscaleup extrasgetbooleanscale up if needed true if mbitmap null logdtag finish finish return make ui fullscreen getwindowaddflagswindowmanagerlayoutparamsflag fullscreen findviewbyidridthiscardsetonclicklistener new viewonclicklistener public void onclickview v setresultresult canceled finish findviewbyidridsavesetonclicklistener new viewonclicklistener public void onclickview v try onsaveclicked catch exception e finish findviewbyidridrotateleftsetonclicklistener new viewonclicklistener public void onclickview v mbitmap utilrotateimagembitmap 90 rotatebitmap rotatebitmap new rotatebitmapmbitmap mimageviewsetimagerotatebitmapresetbaserotatebitmap true mrunfacedetectionrun findviewbyidridrotaterightsetonclicklistener new viewonclicklistener public void onclickview v mbitmap utilrotateimagembitmap 90 rotatebitmap rotatebitmap new rotatebitmapmbitmap mimageviewsetimagerotatebitmapresetbaserotatebitmap true mrunfacedetectionrun logdtest1a mbitmapisrecycled startfacedetection private bitmap checkrotationstring url msaveuri getimageuriurl exifinterface exif try exif new exifinterfaceurl int rotation exifgetattributeintexifinterfacetag orientation exifinterfaceorientation undefined matrix matrix new matrix switch rotation case exifinterfaceorientation flip horizontal matrixsetscale1 1 break case exifinterfaceorientation rotate 180 matrixsetrotate180 break case exifinterfaceorientation flip vertical matrixsetrotate180 matrixpostscale1 1 break case exifinterfaceorientation transpose matrixsetrotate90 matrixpostscale1 1 break case exifinterfaceorientation rotate 90 matrixsetrotate90 break case exifinterfaceorientation transverse matrixsetrotate90 matrixpostscale1 1 break case exifinterfaceorientation rotate 270 matrixsetrotate90 break case exifinterfaceorientation normal default break bitmap beforerotate getbitmapurl int height beforerotategetheight int width beforerotategetwidth bitmap afterrotate bitmapcreatebitmapbeforerotate 0 0 width height matrix true beforerotaterecycle return afterrotate catch ioexception e todo autogenerated catch block eprintstacktrace return mbitmap private uri getimageuristring path return urifromfilenew filepath private bitmap getbitmapstring path uri uri getimageuripath inputstream in null try in mcontentresolveropeninputstreamuri decode image size bitmapfactoryoptions o new bitmapfactoryoptions oinjustdecodebounds true bitmapfactorydecodestreamin null o inclose int scale 1 if ooutheight image max size ooutwidth image max size scale int mathpow2 int mathroundmathlogimage max size double mathmaxooutheight ooutwidth mathlog05 bitmapfactoryoptions o2 new bitmapfactoryoptions o2insamplesize scale in mcontentresolveropeninputstreamuri bitmap b bitmapfactorydecodestreamin null o2 inclose return b catch filenotfoundexception e logetag file path not found catch ioexception e logetag file path not found return null private void startfacedetection if isfinishing return mimageviewsetimagebitmapresetbasembitmap true utilstartbackgroundjobthis null please waitu2026 new runnable public void run final countdownlatch latch new countdownlatch1 final bitmap b mbitmap mhandlerpostnew runnable public void run if b mbitmap b null logdtest1test mimageviewsetimagebitmapresetbaseb true mbitmaprecycle mbitmap b if mimageviewgetscale 1f mimageviewcentertrue true latchcountdown try latchawait catch interruptedexception e throw new runtimeexceptione mrunfacedetectionrun mhandler private void onsaveclicked throws exception todo this code needs to change to use the decodecropencode single step api so that we do not require that the whole possibly large bitmap does not have to be read into memory if msaving return if mcrop null return msaving true rect r mcropgetcroprect int width rwidth int height rheight if we are circle cropping we want alpha channel which is the third param here bitmap croppedimage try croppedimage bitmapcreatebitmapwidth height mcirclecrop bitmapconfigargb 8 bitmapconfigrgb 565 catch exception e throw e if croppedimage null return canvas canvas new canvascroppedimage rect dstrect new rect0 0 width height canvasdrawbitmapmbitmap r dstrect null if mcirclecrop ok so whats all this about bitmaps are inherently rectangular but we want to return something that is basically a circle so we fill in the area around the circle with alpha note the all important portduffmodeclear canvas c new canvascroppedimage path p new path paddcirclewidth 2f height 2f width 2f pathdirectioncw cclippathp regionopdifference cdrawcolor0x0 porterduffmodeclear if the output is required to a specific size then scale or fill if moutputx 0 moutputy 0 if mscale scale the image to the required dimensions bitmap old croppedimage croppedimage utiltransformnew matrix croppedimage moutputx moutputy mscaleup if old croppedimage oldrecycle else do not scale the image crop it to the size requested create an new image with the cropped image in the center and the extra space filled do not scale the image but instead fill it so it is the required dimension bitmap b bitmapcreatebitmapmoutputx moutputy bitmapconfigrgb 565 canvas canvas new canvasb rect srcrect mcropgetcroprect rect dstrect new rect0 0 moutputx moutputy int dx srcrectwidth dstrectwidth 2 int dy srcrectheight dstrectheight 2 if the srcrect is too big use the center part of it srcrectinsetmathmax0 dx mathmax0 dy if the dstrect is too big use the center part of it dstrectinsetmathmax0 dx mathmax0 dy draw the cropped bitmap in the center canvasdrawbitmapmbitmap srcrect dstrect null set the cropped bitmap as the new bitmap croppedimagerecycle croppedimage b return the cropped image directly or save it to the specified uri bundle myextras getintentgetextras if myextras null myextrasgetparcelabledata null myextrasgetbooleanreturn data bundle extras new bundle extrasputparcelablereturn data as bitmap croppedimage setresultresult ok new intentsetactionaction inline dataputextrasextras finish else final bitmap b croppedimage utilstartbackgroundjobthis null getstringrstringsaving image new runnable public void run saveoutputb mhandler private void saveoutputbitmap croppedimage if msaveuri null outputstream outputstream null try outputstream mcontentresolveropenoutputstreammsaveuri if outputstream null croppedimagecompressmoutputformat 90 outputstream catch ioexception ex logetag cannot open file msaveuri ex setresultresult canceled finish return finally utilclosesilentlyoutputstream bundle extras new bundle intent intent new intentmsaveuritostring intentputextrasextras intentputextraimage path mimagepath intentputextraorientation in degrees utilgetorientationindegreethis setresultresult ok intent else logetag not defined image url croppedimagerecycle finish override protected void onpause superonpause bitmapmanagerinstancecancelthreaddecodingmdecodingthreads override protected void ondestroy superondestroy if mbitmap null mbitmaprecycle runnable mrunfacedetection new runnable suppresswarningshiding float mscale 1f matrix mimagematrix facedetectorface mfaces new facedetectorface3 int mnumfaces for each face we create a hightlightview for it private void handlefacefacedetectorface f pointf midpoint new pointf int r int feyesthistance mscale 2 fgetmidpointmidpoint midpointx mscale midpointy mscale int midx int midpointx int midy int midpointy highlightview hv new highlightviewmimageview int width mbitmapgetwidth int height mbitmapgetheight rect imagerect new rect0 0 width height rectf facerect new rectfmidx midy midx midy facerectinsetr r if facerectleft 0 facerectinsetfacerectleft facerectleft if facerecttop 0 facerectinsetfacerecttop facerecttop if facerectright imagerectright facerectinsetfacerectright imagerectright facerectright imagerectright if facerectbottom imagerectbottom facerectinsetfacerectbottom imagerectbottom facerectbottom imagerectbottom hvsetupmimagematrix imagerect facerect mcirclecrop maspectx 0 maspecty 0 mimageviewaddhv create a default hightlightview if we found no face in the picture private void makedefault highlightview hv new highlightviewmimageview int width mbitmapgetwidth int height mbitmapgetheight rect imagerect new rect0 0 width height make the default size about 45 of the width or height int cropwidth mathminwidth height 4 5 int cropheight cropwidth if maspectx 0 maspecty 0 if maspectx maspecty cropheight cropwidth maspecty maspectx else cropwidth cropheight maspectx maspecty int x width cropwidth 2 int y height cropheight 2 rectf croprect new rectfx y x cropwidth y cropheight hvsetupmimagematrix imagerect croprect mcirclecrop maspectx 0 maspecty 0 mimageviewmhighlightviewsclear thong added for rotate mimageviewaddhv scale the image down for faster face detection private bitmap preparebitmap if mbitmap null return null 256 pixels wide is enough if mbitmapgetwidth 256 mscale 2560f mbitmapgetwidth matrix matrix new matrix matrixsetscalemscale mscale return bitmapcreatebitmapmbitmap 0 0 mbitmapgetwidth mbitmapgetheight matrix true public void run mimagematrix mimageviewgetimagematrix bitmap facebitmap preparebitmap mscale 10f mscale if facebitmap null mdofacedetection facedetector detector new facedetectorfacebitmapgetwidth facebitmapgetheight mfaceslength mnumfaces detectorfindfacesfacebitmap mfaces if facebitmap null facebitmap mbitmap facebitmaprecycle mhandlerpostnew runnable public void run mwaitingtopick mnumfaces 1 if mnumfaces 0 for int i 0 i mnumfaces i handlefacemfacesi else makedefault mimageviewinvalidate if mimageviewmhighlightviewssize 1 mcrop mimageviewmhighlightviewsget0 mcropsetfocustrue if mnumfaces 1 toastmaketextcropimagethis multi face crop help toastlength shortshow public static final int no storage error 1 public static final int cannot stat error 2 public static void showstoragetoastactivity activity showstoragetoastactivity calculatepicturesremainingactivity public static void showstoragetoastactivity activity int remaining string nostoragetext null if remaining no storage error string state environmentgetexternalstoragestate if stateequalsenvironmentmedia checking nostoragetext activitygetstringrstringpreparing card else nostoragetext activitygetstringrstringno storage card else if remaining 1 nostoragetext activitygetstringrstringnot enough space if nostoragetext null toastmaketextactivity nostoragetext 50show public static int calculatepicturesremainingactivity activity try if imagemanagerhasstorage return no storage error else string storagedirectory string state environmentgetexternalstoragestate if environmentmedia mountedequalsstate storagedirectory environmentgetexternalstoragedirectorytostring else storagedirectory activitygetfilesdirtostring statfs stat new statfsstoragedirectory float remaining float statgetavailableblocks float statgetblocksize 40f return int remaining catch exception ex if we cannot stat the filesystem then we do not know how many pictures are remaining it might be zero but just leave it blank since we really do not know return cannot stat error,['android'] +644876,opencv approxpolydp for edge maps not contours i have successfully applied the method cvapproxpolydp on contours cvfindcontours in order to represent a contour with a simpler polygon and implicitly do some denoisingi would like to do the same thing on an edge map acquired from an rgbd camera which is in general very noisy but with not much success up to now and i cannot find relative examples online the reason i need this is that by means of an edge map one can also use the edges between fingers edges created by finger occlusion or edges created in the palmis this method applicable to general edge maps other than contourscould someone pinpoint me to an examplesome images attachedsuccessful example for contoursproblematic case for edge mapsmost probably i draw things in the wrong way but drawing just the pixels returned by the method shows that probably large areas are not represented in the end result and this does not change much according to the epsilonparameteri attach also a depth image similar to the ones i use in the experimental pipeline descibed above this depth image was not acquired by a depth camera but was synthetically generated by reading the depth buffer of the gpu using opengljust for reference this is also the edge map of the depth image acquired straight from the depth camera using the raw image no smoothing etc appliedhand as viewd from a depth camera palm facing upwards fingers closing towards the palm,['c++'] +644883,difference between mysql mysqladmin mysqld can someone give me a clear explanation of the differences between mysql command line tool mysqladmin client tool for performing administrative tasks and mysqld mysql server,['mysql'] +644955,223 apps must follow the ios data storage guidelines or they will be rejected by uploading the app to the app store have given me this error 223 apps must follow the ios data storage guidelines or they will be rejected i have been watching what is wrong is that one of the files i am using does not meet the storage requirements to be more specific it is a sqlite for loading maps offlines mode with routeme library i am using sqlite for loading map in offline mode it seems that this map is stored as backup in icloud so i am skipping storage restrictions do not know how to say that this copy is not created in icloud the code is as follows rmdbmapsource alloc initwithpath mapsqlite the file size is 23mb any ideas,"['ios', 'objective-c']" +644977,why am i able to have a public member in a nonpublic class class myclass public static final int num90why am i allowed to create a public member in a nonpublic classis there another way of accessing this member that i do not know of other than through the class name,['java'] +645041,immediate function using javascript es6 arrow functions does anyone know how to write an immediate function using es6 arrow syntaxheres the es35 way of doing itfunction i have tried the following but get an unexpected token error on the last line you can test this here,['javascript'] +645054,thisabling drag if shift key is held down i have an image that i have set up with jquery ui to be draggable this works fine but now i would like to be able to shiftdrag on the image to draw a box on the image and not have it move so if the shift key is held down i do not want to do the drag i have tried putting ifeshiftkeyreturn at the top of the drag start dragging and drag stop functions but this does not do anything because the drag operation seems to be done internally in jquery ui and the calls to drag start dragging and drag stop are just courtesy calls to let you know what jqueryui is currently doingis there a way to thisable the drag if the shift key is held downthanksfor more information on this see my answer farther below with a jsfiddle,['jquery'] +645133,webcam supported picture sizes i am attempting to retrieve the available picturesize resolutions supported by my webcam using the opencv library i have tried working with similar android questionanswers but to no avail eg android camera supported picture sizes here is my code import orgopencvhighguivideocaptureimport orgopencvcoresizepublic class mycameracaptureclass public static void mainstring args systemoutprintlnhello opencv systemoutprintlnthis program will thisplay the webcams supported sizes systemloadlibraryopencv java248 load dll for the jar videocapture vidcap0 new videocapture0 if vidcap0isopened systemoutprintlncamera found and it works so far for size asize vidcap0getsupportedpreviewsizes systemoutprintlndoes not print this at all systemoutprintlnheight asizeheight width asizewidth vidcap0release and the stack trace isexception in thread main javalangexception unknown exceptionat orgopencvhighguivideocapturegetsupportedpreviewsizes 0native methodat orgopencvhighguivideocapturegetsupportedpreviewsizesvideocapturejava478at webcammycameracaptureclassmainmycameracaptureclassjava19all help will be sincerely appreciated,"['java', 'android']" +645151,extending aspnet identity roles identityrole is not part of the model for the current context i am trying to use the new aspnet identity in my mvc5 application specifically i am trying to integrate aspnet identity into an existing database i have already read the questionsanswers on so pertaining to db first and aspnet identity and having followed all the recommendations i still cannot add roles to my database although i have no problems adding users heres my codevar context new payrolldbentitiesvar rolemanager new rolemanageraspnetrolenew rolestoreaspnetrolecontextbool roleexists rolemanagerroleexistsroledtonameif roleexists return falsevar role new aspnetroleroledtoname name roledtonameidentityresult result rolemanagercreaterolegetting exception hereat the last line of code i get an exception of type systeminvalidoperationexception the entity type identityrole is not part of the model for the current contexthere is my contextpublic partial class payrolldbentities identitydbcontext public payrolldbentities basenamepayrolldbentities public virtual dbsetaspnetrole aspnetroles get set public virtual dbsetaspnetuserclaim aspnetuserclaims get set public virtual dbsetaspnetuserlogin aspnetuserlogins get set public virtual dbsetaspnetuser aspnetusers get set my aspnetuser and aspnetrole classes derive from identityuser and identityrole respectively but i am still getting that exception here is my database diagramany help would be greatly appreciated,['c#'] +645204,set lockscreen to none programatically i have the requirement to thisable the lock screen and set the lock screen type to none my device is rooted can run with su permission can run as a system application with system permissions under systemappi have tried a few things to no availtry 1this seems to be deprecated and not workingkeyguardmanager manager keyguardmanager thisgetsystemservicekeyguard servicekeyguardlock lock managernewkeyguardlockabclockthisablekeyguard try 2this did not work eithermount system partition as writableedit datadatacomandroidproviderssettingsdatabasessettingsdbexecute the following sql insert or replace into system name value values lockscreenthisabled 1insert or replace into secure name value values lockscreenthisabled 1try 3rebooted the machine but still no luckandroidprovidersettingssecureputlongmcontentresolver settingssecurelock pattern enabled falseandroidprovidersettingssecureputlongmcontentresolver lockscreenpassword type devicepolicymanagerpassword quality somethingandroidprovidersettingssecureputlongmcontentresolver lockscreenpassword type alternate devicepolicymanagerpassword quality unspecifiedandroidprovidersettingssecureputlongmcontentresolver lockscreenthisabled trueis there anything else that i can try please note that i do not want to thisable the keyguard only when application is running,"['java', 'android']" +645258,get next week start and end using jquery and moment js i searched for this question and found there is a no answer on stackoverflow so i decided to answer itthis question helps if you need to get the startend of nextlast week with monday as start of week,"['javascript', 'jquery']" +645319,clicking on text in between span tags using selenium webdriver java html code looks like thistd idid26a classdoclistingname link stylewidth 319px minwidth 319px span idid26b titledocumentspan classiefallbackmarker wordsspanspantdi cannot search for element id as it changes all the time i cannot search for the elements class as there are multiples which could change locationsi want to be able to click on words in between the span tags is this at all possiblethis is what i used so far but neither seems to workstring document is words public void testscenario123string document throws throwable threadsleep30 driverfindelementbylinktextdocumentclickor string document is words public void testscenario124string document throws throwable threadsleep30 driverfindelementbyxpathcontainsspandocumentclick,"['java', 'html']" +645353,an invalid form control with name is not focusable i have an acute problem on my websitein google chrome some customers are not able to proceed to my payment pagewhen trying to submit a form i get this erroran invalid form control with name is not focusablethis is from the javascript consolei read that the problem could be due to hidden fields having the required attributenow the problem is that we are using net webforms required field validators and not the html5 required attributeit seems random who gets this erroris there anyone who knows a solution for this,['html'] +645362,how to set a breakpoint on a class not a line in eclipse i simply would like to start debugging once any function is invoked in a specific set of classesis it possible to achieve this in eclipse or do i have to set a breakpoint on each function in each class i want to debugupdatei did not ask how to set a breakpoint in eclipse i would like to debug a class without knowing which function is going to be calledupdate 2i am going to make my problem more cleari was requested to fix a bug in an application which i did not implement i managed to narrow down the related classes to this bug the problem each class has over 30 functions and i do not know exactly which functions are invoked so i was thinking if its possible to set a breakpoint somehow on the class itself in order to start debugging once a function within this class is invokedi would appreciate any helptefa,['java'] +645419,play store alpha test download link not working i think i followed all steps which i have found so far but the download link for my alpha test is not workingi uploaded the app 3 days ago created a google group and added the group to the list of alpha testersi invited a few members and the app status shows published after clicking on the link i can signup as alpha tester but when i click on download from the play store the error message were sorry the requested url was not found on this server comesdid i miss an additional step do i have to grant some special rights to the group members somehow update can this be caused by the permissions of the appunder the apk info in the developer console i can seefunctionsandroidhardwarelocationandroidhardwarelocationgpsandroidhardwarelocationnetworkandroidhardwaretouchscreenpermissionsandroidpermissionaccess coarse locationandroidpermissionaccess fine locationandroidpermissioninternetupdate2well i do not have any idea what changed but now the download link is working for my alpha testers,['android'] +645445,recursive entry to executependingtransactions i have a maindrawer to fragment activity which has a layout for a nav drawer my and my main content where i can load new fragments into one fragment i load in is calle statisticstab fragment this fragment holds a tabhost which each tab is its own fragment of listview items once i click on a listview item which loads another new fragment and am no longer in the tabhost and i try to go back using the navigationdrawer to my statisticstab fragment i get this error0303 103206884 2418524185combeerportfoliobeerportfoliopro eandroidruntimei1 fatal exception main javalangillegalstateexception recursive entry to executependingtransactions at androidsupportv4appfragmentmanagerimplexecpendingactionsfragmentmanagerjava1439 at androidsupportv4appfragmentmanagerimplexecutependingtransactionsfragmentmanagerjava472 at androidsupportv4appfragmenttabhostonattachedtowindowfragmenttabhostjava283 at androidviewviewthispatchattachedtowindowviewjava12307 at androidviewviewgroupthispatchattachedtowindowviewgroupjava2457 at androidviewviewgroupthispatchattachedtowindowviewgroupjava2464 at androidviewviewgroupaddviewinnerviewgroupjava3567 at androidviewviewgroupaddviewviewgroupjava3399 at androidviewviewgroupaddviewviewgroupjava3344 at androidviewviewgroupaddviewviewgroupjava3320 at androidsupportv4appfragmentmanagerimplmovetostatefragmentmanagerjava938 at androidsupportv4appfragmentmanagerimplmovetostatefragmentmanagerjava1104 at androidsupportv4appbackstackrecordrunbackstackrecordjava682 at androidsupportv4appfragmentmanagerimplexecpendingactionsfragmentmanagerjava1467 at androidsupportv4appfragmentmanagerimpl1runfragmentmanagerjava440 at androidoshandlerhandlecallbackhandlerjava730 at androidoshandlerthispatchmessagehandlerjava92 at androidoslooperlooplooperjava158 at androidappactivitythreadmainactivitythreadjava5789 at javalangreflectmethodinvokenativenative method at javalangreflectmethodinvokemethodjava525 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava1027 at comandroidinternaloszygoteinitmainzygoteinitjava843 at dalviksystemnativestartmainnative methodif i do not click on any of my tabs though on the statisticstab fragment and navigate to another fragment via the navdrawer and then back to the statisticstab then it will not fc on also none of the other fragments in the navdrawer force close when i go back to them just the one with the tabsmaindrawer2public class maindrawer2 extends fragmentactivity private static final string extra nav item extranavitem private static final string state current nav statecurrentnav private actionbardrawertoggle mdrawertoggle private drawerlayout mdrawerlayout private navdrawerlistadapter mdraweradapter private listview mdrawerlist private charsequence mtitle private charsequence mdrawertitle private mainnavitem mcurrentnavitem public static intent createlaunchfragmentintentcontext context mainnavitem navitem return new intentcontext maindrawer2class putextraextra nav item navitemordinal override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutfragment main mtitle mdrawertitle gettitle mdrawerlayout drawerlayoutfindviewbyidriddrawer layout mdrawerlist listviewfindviewbyidriddrawer getactionbarsetthisplayhomeasupenabledtrue enablehomebuttonifrequired mdraweradapter new navdrawerlistadaptergetapplicationcontext mdrawerlistsetadaptermdraweradapter mdrawerlistsetonitemclicklistenernew listviewonitemclicklistener override public void onitemclickadapterview parent view view int position long id thisplaynavfragmentmainnavitemparentgetitematpositionposition mdrawertoggle new actionbardrawertogglethis mdrawerlayout rdrawableic drawer rstringapp name rstringapp name public void ondrawerclosedview view getactionbarsettitlemtitle invalidateoptionsmenu public void ondraweropenedview drawerview getactionbarsettitlemdrawertitle invalidateoptionsmenu mdrawerlayoutsetdrawerlistenermdrawertoggle ifgetintenthasextraextra nav item mainnavitem navitem mainnavitemvalues getintentgetintextraextra nav item mainnavitemstatisticsordinal thisplaynavfragmentnavitem else ifsavedinstancestate null mcurrentnavitem mainnavitemvalues savedinstancestategetintstate current nav setcurrentnavitemmcurrentnavitem else thisplaynavfragmentmainnavitemstatistics targetapibuildversion codesice cream sandwich private void enablehomebuttonifrequired ifbuildversionsdk int buildversion codesice cream sandwich getactionbarsethomebuttonenabledtrue override public void settitlecharsequence title mtitle title getactionbarsettitlemtitle override protected void onpostcreatebundle savedinstancestate superonpostcreatesavedinstancestate sync the toggle state after onrestoreinstancestate has occurred mdrawertogglesyncstate override public void onconfigurationchangedconfiguration newconfig superonconfigurationchangednewconfig pass any configuration change to the drawer toggles mdrawertoggleonconfigurationchangednewconfig override protected void onsaveinstancestatebundle outstate superonsaveinstancestateoutstate outstateputintstate current nav mcurrentnavitemordinal override public boolean oncreateoptionsmenumenu menu getmenuinflaterinflatermenumain menu return true override public boolean onprepareoptionsmenumenu menu if nav drawer is opened hide the action items boolean draweropen mdrawerlayoutisdraweropenmdrawerlist menufinditemridaction settingssetvisibledraweropen return superonprepareoptionsmenumenu private void thisplaynavfragmentmainnavitem navitem ifnavitem mcurrentnavitem return fragment fragment fragmentinstantiatethis navitemgetfragclassgetname iffragment null getsupportfragmentmanagerbegintransaction replaceridmain fragment commit setcurrentnavitemnavitem private void setcurrentnavitemmainnavitem navitem int position navitemordinal if navitem is in draweradapter ifposition 0 position mdraweradaptergetcount mdrawerlistsetitemcheckedposition true else navitem not in draweradapter deselect current item ifmcurrentnavitem null mdrawerlistsetitemcheckedmcurrentnavitemordinal false mdrawerlayoutclosedrawermdrawerlist settitlenavitemgettitleresid mcurrentnavitem navitem override public boolean onoptionsitemselectedmenuitem item switch itemgetitemid case androidridhome ifmdrawerlayoutisdraweropenmdrawerlist mdrawerlayoutclosedrawermdrawerlist else mdrawerlayoutopendrawermdrawerlist return true default return superonoptionsitemselecteditem public void gotosearchmenuitem item go to search page fragment fragment one fragmentmanager man getsupportfragmentmanager fragmenttransaction tran manbegintransaction fragment one new search tranreplaceridmain fragment onetran tranaddtobackstacknull trancommit statisticstabpublic class statisticstab extends fragment private fragmenttabhost mtabhost mandatory constructor public statisticstab public void oncreatebundle savedinstancestate superoncreatesavedinstancestate public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate view rootview inflaterinflaterlayoutfragment tabscontainer false mtabhost fragmenttabhostrootviewfindviewbyidandroidridtabhost mtabhostsetupgetactivity getfragmentmanager ridrealtabcontent mtabhostaddtabmtabhostnewtabspecbasicsetindicatorbasic statisticspageclass null mtabhostaddtabmtabhostnewtabspecbrewerysetindicatorbrewery brewerystatisticsclass null mtabhostaddtabmtabhostnewtabspecstylesetindicatorstyle stylestatisticsclass null mtabhostaddtabmtabhostnewtabspectastesetindicatortaste tastestatisticspageclass null return rootview one of my fragments for a tab in the tabhost which has a listviewpublic class brewerystatistics extends fragment implements getbrewerystatisticsjsononarticleselectedlistener public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate view v inflaterinflaterlayoutbrewery statistics layout container false sharedpreferences prefs preferencemanagergetdefaultsharedpreferencesgetactivity string username prefsgetstringusername null string userid prefsgetstringuserid null string url myurl async task to get beer taste tag percents getbrewerystatisticsjson task new getbrewerystatisticsjsongetactivity tasksetonarticleselectedlistenerthis taskexecuteurl inflate the layout for this fragment return v override public void onarticleselectedstring bid code to execute on click fragment fragment one fragmentmanager man getfragmentmanager fragmenttransaction tran manbegintransaction fragment one new brewerypage2 final bundle bundle new bundle bundleputstringbreweryidsent bid fragment onesetargumentsbundle tranreplaceridmain fragment onetran tranaddtobackstacknull trancommit my async task for the above fragment to load the listviewpublic class getbrewerystatisticsjson extends asynctaskstring void string context c private progressdialog dialog public getbrewerystatisticsjsoncontext context c context dialog new progressdialogc code for on click onarticleselectedlistener listener public interface onarticleselectedlistener public void onarticleselectedstring mystring public void setonarticleselectedlisteneronarticleselectedlistener listener thislistener listener end code for onclick protected void onpreexecute dialogsetmessageanalyzing breweries dialogsettitleloading dialogsetcancelablefalse dialogshow override protected string doinbackgroundstring arg0 todo autogenerated method stub return readjsonfeedarg00 protected void onpostexecutestring result decode json here try jsonarray jsonarray new jsonarrayresult acces listview listview lv listview activity cfindviewbyidridyourbrewerystatistics make array list for beer final listbreweryinfo tastelist new arraylistbreweryinfo forint i 0 i jsonarraylength i string brewery jsonarraygetjsonobjectigetstringbrewery string rate jsonarraygetjsonobjectigetstringrate string breweryid jsonarraygetjsonobjectigetstringid int count i 1 brewery count brewery logdbrewery stats brewery create object breweryinfo temptaste new breweryinfobrewery breweryid rate add to arraylist tastelistaddtemptaste add items to listview breweryinfoadapter adapter1 new breweryinfoadapterc rlayoutbrewer stats listview tastelist lvsetadapteradapter1 set up clicks lvsetonitemclicklistenernew adapterviewonitemclicklistener override public void onitemclickadapterview arg0 view arg1 int arg2 long arg3 breweryinfo obreweryinfoarg0getitematpositionarg2 string bid obreweryid logdbreweryid bid todo add brewery page link add listener listeneronarticleselectedbid catchexception e dialogthismiss public string readjsonfeedstring url stringbuilder stringbuilder new stringbuilder httpclient httpclient new defaulthttpclient httpget httpget new httpgeturl try httpresponse response httpclientexecutehttpget statusline statusline responsegetstatusline int statuscode statuslinegetstatuscode if statuscode 200 httpentity entity responsegetentity inputstream inputstream entitygetcontent bufferedreader reader new bufferedreader new inputstreamreaderinputstream string line while line readerreadline null stringbuilderappendline inputstreamclose else logdjson failed to download file catch exception e logdreadjsonfeed egetlocalizedmessage return stringbuildertostring,['android'] +645446,critical section in javascript or jquery i have a webpage in which a certain ajax event is triggered assynchronously this ajax section could be called once or more than once i do not have control over the number of times this event is triggered nor the timingalso there is a certain code inthat ajax section that should run as a critical section meaning when it is running no other copy of that code should be runninghere is a seudo coderun javascript or jquery codeenter critical section that is ajax when a certain process is waiting for a response callback then do not enter this section again until this process is donerun more javascript or jquery codemy question is how can i run step 2 the way described above how do i createguarantee a mutual execlution section using javascript or jqueryi understand the theory semaphores locks etc but i could not implement a solution using either javascript or jqueryeditin case you are suggesting a boolean variable to get into the critical section this would not work and the lines below will explain whythe code for a critical section would be as follows using the boolean variable suggestionsload data from database function load data from the database only load data if we almost reach the end of the page if jquerywindowscrolltop jquerydocumentheight jquerywindowheight 300 enter critical section if windowlock false lock the critical section windowlock true make ajax call jqueryajax type post datatype json url pathtoscriptphp data action alwarkaa load posts success function response first do som stuff when we get a response then we unlock the critical section windowlock false end of critical section the jquery ready function start code herejquerydocumentreadyfunction var windowlock false this is a global lock variable jquerywindowonscroll load data from databasenow this is the code for the lock section as suggested using a boolean variable this would not work as suggested belowthe user scrolls down and based on the association jquerywindowonscroll load data from database more than one scroll event is triggeredassume two scroll events are triggered right at almost the same momentboth call the load data from database functionthe first event checks if windowlock is false answer is true so if statement is correctthe second event checks if windowlock is false answer is true so if statement is correctthe first event enters the if statmentthe second event enters the if statementthe first statment sets windowlock to truethe second statment sets windowlock to truethe first statment runs the ajax critical sectionthe second statement runs the ajax critical sectionboth finish the codeas you notice both events are triggered almost at the same time and both enter the critical section so a lock is not possible,"['javascript', 'jquery']" +645463,what is happening behind setattribute vs attribute descriptioni am using simple javascript to set a the value of an input i am using multiple methods that appear to be the same but with different results here is an examplehtmlinput nametestinput value typetext javascriptvar input documentgetelementbytagnameinput0inputvalue 5consoleloginputvalue returns 5consoleloginputgetattributevalue returns of course the functionality if reversed when using the setattribute function yet when on form submit they both give a input5 result questionwhat is the point of separating the two properties is the value stored differently than the getattributevalue thisclaimeri have read when to use setattribute vs attribute in javascriptsetting a property via property or setattributeboth of those questionanswers left me confused and unsatisfied,['javascript'] +645509,flask blueprint static directory does not work according to the flask readme blueprint static files are accessible at blueprintnamestatic but for some reason it does not workmy blueprint is like thisappfrontendviewspy frontend blueprintfrontend name template foldertemplates static folderstaticfrontendroute etcappfrontendjsappjs my javascriptblueprint registered in flask app routes work and everythingwhen i go to abccomfrontendstaticjsappjs it just gives a 404when i follow the flask readme to get my static filesscript srcurl forfrontendstatic filenamejsappjsscriptthe output is script srcstaticjsappjsscriptwhich does not work either there is nothing in my root appstatic folderi cannot access any static files in my blueprint flask read me says that it should workadmin blueprintadmin name static folderstaticby default the rightmost part of the path is where it is exposed on the web because the folder is called static here it will be available at the location of the blueprint static say the blueprint is registered for admin the static folder will be at adminstatic,['python'] +645521,how do i change the select box arrow i need your helpi cannot seem to wrap my head around this one and figure it out how do i change the default windows 7 ie 10 default arrow in the select box to make it look like this using the custom arrow belowhere is the arrow that i desire to usehere is my html markupdoctype htmlhtmlhead style typetextcss select font normal 13px arial color 0 container border 1px solid red position relative width 124px height 18px overflow hidden inpselect color black background ffa position absolute width 128px top 2px left 2px stylescript typetextjavascriptscriptheadbodydiv classcontainer select classinpselect namex option value0 selectedselectedactual browseroption option value1ieoption option value2firefoxoption option value3operaoption option value4safarioption selectdivbodyhtml,"['html', 'css']" +645573,how to add a carplay support to an existing ios app apple announced carplay feature and some of the 3rd party apps are already integrating it spotify beats radio iheartradiowhat is the first step to add a carplay support to an existing ios xcode project i cannot find any information on it like adding a new target supported device type etc,"['ios', 'objective-c']" +645585,why is native javascript array foreach method significantly slower than the standard for loop while reading the source code for the quintus game engine i found that they were making heavy use of for loops as opposed to the native foreachmy original thought was that the native foreach method would be slightly faster than standard for loops however after testing my theory with these benchmarks the for loop structures appears to be significantly fasterafter poking around i cannot seem to find out whats going on under the hood does anyone know the reason for the huge differenceedit to be clear i am asking why is this this case i am not asking which is faster,['javascript'] +645589,bower loading devdependencies in production short versionmy project requires angularleaflet and angularleaflet has a long list of devdependencies including jquery 2 i do not want jquery 2i want jquery 1x how can i get bower to ignore the devdependencies of angularleaflet and let me use jquery 1long versioni am using bower 128 here is a minimal bowerjson that reproduces the problem for me name bowertest dependencies jquery 1x angular 12x angularleaflet 07x running bower install results in the following errorunable to find a suitable version for jquery please choose one 1 jquery1x which resolved to 10 and has bowertest as dependants 2 jquery210 which resolved to 210 and has angularleaflet075 as dependants 3 jquery 190 which resolved to 210 and has bootstrap303 as dependantsat the very least i expected bower install production to ignore devdependencies in angularleaflet but heres the result identical to aboveunable to find a suitable version for jquery please choose one 1 jquery1x which resolved to 10 and has bowertest as dependants 2 jquery210 which resolved to 210 and has angularleaflet075 as dependants 3 jquery 190 which resolved to 210 and has bootstrap303 as dependantswhy is bower not ignoring the devdependencies of angularleaflet is there a way to make it do so,['javascript'] +645842,cannot evaluate function may be inlined i wrote a function similar to thisclass abc private int m var public int func return m var when i try to print the func using an abc object pointer in gdb it is giving the errorcannot evaluate function may be inlinedhow to can i print values from an inlined function,['c++'] +645937,how to create a popup windows in javafx i want to create a popup windows in javafx applicationgive me some ideawhen i click on check button open popup windowshow to do,['java'] +645992,is there a pointereventshoveronly or similar in css just been playing about with pointerevents property in cssi have a div that i want to be invisible to all mouse events except for hoverso all click commands go through the div to the one below it but the div can report whether the mouse is above it or not stillcan anyone tell me if this can be donehtmldiv classlayer stylezindex20 pointereventsnonetop layerdivdiv classlayer stylezindex10bottom layerdivcsslayer positionabsolute top0px left0px height400px width400px,"['html', 'css']" +646013,store image to blobstore from android client and retrieve blobkey and upload url to store in datastore gae in my android application i want to upload image to the blobstore then retrieve an upload url and the images blobkey so i can store the blobkey in the datastore i have tried this code but my image is not uploadingservlet return upload urlblobstoreservice blobstoreservice blobstoreservicefactory getblobstoreservicepublic void dogethttpservletrequest req httpservletresponse resp throws ioexception uploadoptions uploadoptions uploadoptionsbuilder withgooglestoragebucketnamephotobucket11 maxuploadsizebytes1048576 string blobuploadurl blobstoreservicecreateuploadurlupload uploadoptions string blobuploadurl blobstoreservicecreateuploadurluploaded respsetstatushttpservletresponsesc ok respsetcontenttypetextplain printwriter out respgetwriter outprintblobuploadurl public void doposthttpservletrequest req httpservletresponse resp throws ioexception dogetreq resp code android clientbitmap bmp bitmapfactorydecodefileimagepath bytearrayoutputstream out new bytearrayoutputstream bmpcompresscompressformatjpeg 75 out byte imgbyte outtobytearray string encodedimage base64encodetostringimgbyte base64default httpclient httpclient new defaulthttpclient httpget httpget new httpget appurlimgupload httpresponse response httpclientexecutehttpget httpentity urlentity responsegetentity inputstream in urlentitygetcontent string str while true int ch inread if ch 1 break str char ch this will return upload url in form of ahuploadakjdhjahdjaudshgaajsdhjsdh which i can use to store the image this code uses the url to store the imagehttpclient new defaulthttpclient httppost postrequest new httppoststr bytearraybody bab new bytearraybodyimgbyte forestjpg multipartentity reqentity new multipartentity httpmultipartmodebrowser compatible reqentityaddpartuploaded bab reqentityaddpartphotocaption new stringbodysfsdfsdf postrequestsetentityreqentity response httpclientexecutepostrequest bufferedreader reader new bufferedreader new inputstreamreader responsegetentitygetcontent utf8 string sresponse stringbuilder s new stringbuilder while sresponse readerreadline null s sappendsresponse here if i check value of the string s it shows null that means it is returning a null response i do not know what the problem is with this code please guide me to solve this problem,['android'] +646046,is it possible to get phone number with google plus api after i get successful authentication i have already got user information by below method 1 create a gtlquery object to get people profile who are authenticatedgtlqueryplus query gtlqueryplus queryforpeoplegetwithuseridme 2 execute the querygppsignin sharedinstance plusservice executequeryquery completionhandlergtlserviceticket ticketgtlplusperson gpusernserror error here i have retrieved all info about users nsloggp user first name gpusernamegivenname nsloggp user last name gpusernamefamilyname but do not know how extract phone number this google doc shows how to retrieve info via google api but could not see how to extract phone number if user make it visible as public is it possible with google plus api,"['ios', 'objective-c']" +646084,why does symfony reload the user from the database on each request from the symfony 2 cookbook understanding serialize and how a user is saved in the sessiononce the user is logged in the entire user object is serialized into the session on the next request the user object is deserialized then value of the id property is used to requery for a fresh user object from the databaseand in practice this means that the user object is reloaded from the database on each request using the id from the serialized objectwhy is it necessary for symfony to fetch the user object from the database on each request under what circumstances would the serialised user object that is stored in the session data not match up with the user object fetched from the database surely symfony knows when the user object changes and can simply update the session data when this occursi imagine that there is a good reason for this since it would be wasteful to unnecessarily query the database on each request,['php'] +646152,why does a view changes position when rotating it using cgaffinetransformmakerotation i have the following super simple animation i am basically rotating a view 2 radians from its original anglecenter it rotates fine my only misunderstanding is why does the view move from its original position when the rotation occursuiview animatewithduration10 animations selfsomeviewtransform cgaffinetransformmakerotation 2 why does the view moves when rotated with the code abovei am currently trying to thiscern the information in the cgaffinetransform reference understanding the anchor point i found this threads but it does not show a concrete answerwhy rotating imageview it changes positionthanks a lot,"['ios', 'objective-c']" +646298,click by bounds coordinates i know it is possible for espresso to click by bounds the way uiautomator does x and y coordinates i have read through the documentation but i cannot seem to find it any help is appreciated thanksediti found this link but no examples how to use it my main concern with this is the uicontroller is or how to use it,['android'] +646381,how can i extract all possible induced subgraphs from a given graph with networkx i am wondering whether can i use networkx to extract all possible induced subgraphs graphlets with specific number of nodes in the subgraphs from an input large graph or is there another package that can do the job for example if i have a large graph which is illustrated in networkx adjacency list formatgraph g1 2 3 72 1 43 1 4 6 54 2 3 55 3 4 66 3 5 77 1 6which will be look like if i want to extract graphlet with 3 nodes the algorithm should return mesubgraph11 2 32 13 11213subgraph21 3 73 17 11317subgraph33 4 54 3 55 3 4343545subgraph4subgraph5subgraph6the following is the code of the question suggested by hookedlet us say n3import itertoolstarget nxcomplete graph3for sub nodes in itertoolscombinationsgnodeslentargetnodes subg gsubgraphsub nodes if nxis connectedsubg print subgedgesthe the output will look like1 2 1 31 2 2 41 2 1 71 3 3 41 3 3 51 3 3 61 3 1 71 7 6 72 4 3 42 4 4 53 4 3 5 4 53 4 3 63 5 3 6 5 63 6 6 74 5 5 65 6 6 7,['python'] +646392,confused as to why this c code compiles while similar code does not let us take the following extension methodstatic class extensions public static bool intthis t t params t values return false i am curious as to why this code compiles and runsvar x new objectienumerableint p new listint 1 2 3 var t2 xinpwithin in values is an object as if the listint gets converted on the fly to an array to me it seems that params t does not match ienumerableint which is why i am surprised this even runsnow this codevar x 5ienumerableint p new listint 1 2 3 var t2 xinpdoes not run and generates the compiler errorerror 2 argument 2 cannot convert from systemcollectionsgenericienumerable to intthis is what i would expect from the first one actually can someone explain whats going on here thanks,['c#'] +646539,ie10 javascript cannot repaint window while computer is locked the problemoccurs on ie10 ie8 works finei have written some javascript code that after 20 minutes of inactivity redirects the browser to another url to indicate the user was logged out normally this works fine however i have noticed a strange scenario if the users windows computer was locked during this timeout then it appears as though nothing has happenedhowever when i look at the browsers url bar i can clearly see that the url has already been updated to the autologout page but the entire content of the browser window is still thisplaying the old page for some reason the browser window has not repainted refreshed it looked like it had frozenat this point if i rapidly mouse click around on the page then the browser wakes up and shows the new content it seems that just one mouse click is not enough the more rapidly you click around the faster it wakes uptheorymy best guess is the ie10 browser stops repainting the window while the computer is locked however i do believe the javascript engine is still running though because i tested another scenario with multiple js new date time stamps at various intervals and when the screen finally repainted each date time was unique showing the time it actually occurredrecreating the issue version 1launch the javascript code below in ie10lock my windows computer before 10 seconds has elapsedwait 10 seconds and then unlock my computersee the ie10 window has failed to repainti did notice this only occurs when redirecting to a url on our companys local intranet i have no idea why this is the case but if i have the url as google or yahoos home page then i cannot recreate the issue it just works correctly made me wonder if it could be a group policy trusted zones intranet vs internet issue of some sortdoctype htmlhtmlheadheadbody script var url fails url this internet site works url this internet site works settimeoutfunction windowlocationhref url 10 wait 10 seconds then execute redirect scriptbodyhtmlquestiondoes anyone have any ideas how to solve this issue so that the ie10 window will always repaint instantly instead of thisplaying stale content,['javascript'] +646611,numpy broadcasting sliced arrays and vectors given three numpy arrays one multidimensional array x one vector y with trailing singleton dimension and one vector z without trailing singleton dimensionx npzerosmny npzerosm1z npzerosmthe behaviour of broadcast operations changes depending on vector representation and contextx0 y error cannot broadcast from shape m1 into shape mx0 z okx0 y error nonbroadcastable output with shape m does not match broadcast shapemmx0 z okx y okx z error cannot broadcast from shape mn into shape mi realize i can do the followingx znone okbut i do not understand what this explicit notation buys me it certainly does not buy readability i do not understand why the expression x y is ok but x z is ambiguous why does numpy treat vectors with or without trailing singleton dimensions differentlyedit the documentation states that two dimensions are compatible when they are equal or one of them is 1 but y and z are both functionally m x 1 vectors since an m x 0 vector does not contain any elements,['python'] +646685,crop video like whatsapp i have seen unique feature in whatsapp messengerin which before sending video application allow user to select frames and user can send only those selected frames as videoso my question is how can we divide video in frames and again ganerate video from divided frames how whatsapp messagnes had done,['android'] +646816,accessing files attributes vs accessing sqlite records in one of our apps i was asked to keep record of the last modified date of images that way i can check with the server if a certain image has changed and update my cache accordinglymy first approach was to access the files attributes and perform a comparison but a few places online mentioned a drastic bottleneck in terms of latency my second choice was to create a sqlite table to manage it using fmdbi have decided to write a simple latency test in the next test i am accessing 500 file attributes and 500 sqlite records voidlatencytest nsmutablearray arraytest1 nsmutablearray allocinit nsmutablearray arraytest2 nsmutablearray allocinit fmresultset results database executequeryselect from tb media nsdateformatter formatter nsdateformatter alloc init formatter setdateformatddmmy hhmms nslogtime1 formatter stringfromdatensdate date int i1 whilei501 nsstring test nsstring stringwithformat mediamedia19djpg outputpathi nsdictionary attributes nsfilemanager defaultmanager attributesofitematpathtest errornil nsdate datex attributes filemodificationdate arraytest1 addobjectdatex i nslogtime2 formatter stringfromdatensdate date whileresults next nsdate mydate nsdate datewithtimeintervalsince1970results intforcolumnlast update arraytest2 addobjectmydate nslogtime3 formatter stringfromdatensdate dateresults iphone 5 actual device 500 pics files start 05032014 093120375 files end sqlite start 05032014 093120491 sqlite end 05032014 093120507 files start 05032014 093156305 files end sqlite start 05032014 093156421 sqlite end 05032014 093156437 files start 05032014 093219053 files end sqlite start 05032014 093219170 sqlite end 05032014 093219187as you can see the results are pretty much the same my questions arei was under the assumption that accessing one file at a time using attributesofitematpath willtake a lot longer than sql am i missing somethingdoes attributesofitematpath really accessing the file or the iosfilesystem keeps all the attributes in some sort of database foreasy accessafter seeing the above results i have decided to go with theattributesofitematpath method is there anything else i am notconsidering passing on sqlite,"['ios', 'iphone', 'objective-c']" +646955,what is an undeclared identifier error and how do i fix it what are undeclared identifier errors what are common causes and how do i fix themexample error textsfor the visual studio compiler error c2065 printf undeclared identifierfor the gcc compiler printf undeclared first use in this function,['c++'] +647018,thisable break at first line php scripts intellij when debugging intellij suspends my scripts always on the first line of my php scripts when using xdebug and i do not know whyany ideas,['php'] +647190,sort dictionary by key using localecollation the following code is ignoring the locale and agypt goes at the end whats wrongdict united states united states spain spain england england agypt agyptimport locale using your default locale user settingslocalesetlocalelocalelc allfr frprint ordereddictsorteddictitems keylambda t t0 cmplocalestrcollthat is the outputordereddictengland england spain spain united states united states xc3x89gypt xc3x89gypt,['python'] +647291,stack level too deep when using carrierwave versions i am trying to use a sidekiq worker which more or less saves a image file to database using carrierwave there are few files to save which are a keyframes extracted from a video file that is what that worker is aboutmy image uploader has a few versions defined and looks as followsclass keyframeuploader carrierwaveuploaderbase keyframe thumbnail sizes version small do process resize to fill 180 180 if square process resize to fill 320 180 if not square end version medium do process resize to fill 460 460 if square process resize to fill 640 460 if not square end version large do process resize to fill 720 720 if square process resize to fill 1280 720 if not square end private checks if image is a square def square file img magickimagereadfilepath img0columns img0rows end oposite to square def not square file square file endendthe thing is when i am trying to run my sidekiq worker it throws celluloidfiberstackerror stack level too deep and the only way to fix that is to remove my version definitions it works only if there are not any version assigned to the uploader i have tried moving a save process to another worker or using carrierwavebackgrounder but i am allways getting the same resulthave you any idea what can i do about itedit my stracktrace issystemstackerror stack level too deep from usrlocalrvmrubiesruby211libruby210irbworkspacerb86,"['ruby-on-rails', 'ruby']" +647294,compiletime reflection in c1z there is a study group in the c standardization committee to provide compiletime reflection in c1z or after i would like to know what is exactly the purpose and how powerful the expected tools will befor example will it be possible to name functions or classes using these toolsstruct a int f return 42struct b int stdreflectamember0declname return 43 equivalent to struct b int f return 43if it would not be as powerful as this what the typical use cases will be,['c++'] +647412,ssl read cert already in hash table when sending mail asynchronously i keep getting an opensslsslsslerror with a message of ssl read cert already in hash table when sending delayed emails out asynchronously with actionmailerwe use sidekiq to send all of our emails out asynchronously when posing this question as an issue in the sidekiq github repo i was told that sidekiq does not know anything about or manage the ssl connectionour app is hosted on heroku which is running openssl 098k 25 mar 2009weve seen this error several times in other jobs and have found that sometimes the jobs get processed but sometimes they do notis this an openssl threading problem in which multiple sidekiq threads are attempting to use the same ssl connection is a there a fix to thisheres the stacktrace were getting project rootvendorruby200libruby200opensslbufferingrb175in sysread nonblock project rootvendorruby200libruby200opensslbufferingrb175in read nonblock project rootvendorruby200libruby200netprotocolrb153in rbuf fill project rootvendorruby200libruby200netprotocolrb134in readuntil project rootvendorruby200libruby200netprotocolrb144in readline project rootvendorruby200libruby200netsmtprb932in recv response project rootvendorruby200libruby200netsmtprb903in block in data project rootvendorruby200libruby200netsmtprb942in critical project rootvendorruby200libruby200netsmtprb896in data project rootvendorruby200libruby200netsmtprb663in block in send message project rootvendorruby200libruby200netsmtprb852in rcptto list project rootvendorruby200libruby200netsmtprb663in send message project rootvendorbundleruby200gemsmail254libmailnetworkdelivery methodssmtprb113in block in deliver project rootvendorruby200libruby200netsmtprb521in start project rootvendorbundleruby200gemsmail254libmailnetworkdelivery methodssmtprb112in deliver project rootvendorbundleruby200gemsmail254libmailmessagerb2129in do delivery project rootvendorbundleruby200gemsmail254libmailmessagerb232in block in deliver project rootvendorbundleruby200gemsactionmailer403libaction mailerbaserb456in block in deliver mail project rootvendorbundleruby200gemsactivesupport403libactive supportnotificationsrb159in block in instrument project rootvendorbundleruby200gemsactivesupport403libactive supportnotificationsinstrumenterrb20in instrument project rootvendorbundleruby200gemsactivesupport403libactive supportnotificationsrb159in instrument project rootvendorbundleruby200gemsactionmailer403libaction mailerbaserb454in deliver mail project rootvendorbundleruby200gemsmail254libmailmessagerb232in deliver project rootvendorbundleruby200gemssidekiq2172libsidekiqextensionsaction mailerrb20in perform project rootvendorbundleruby200gemssidekiq2172libsidekiqprocessorrb49in block 3 levels in process project rootvendorbundleruby200gemssidekiq2172libsidekiqmiddlewarechainrb122in call project rootvendorbundleruby200gemssidekiq2172libsidekiqmiddlewarechainrb122in block in invoke project rootvendorbundleruby200gemsnewrelic rpm371182libnew relicagentinstrumentationsidekiqrb30in block in call project rootvendorbundleruby200gemsnewrelic rpm371182libnew relicagentinstrumentationcontroller instrumentationrb339in perform action with newrelic trace project rootvendorbundleruby200gemsnewrelic rpm371182libnew relicagentinstrumentationsidekiqrb21in call project rootvendorbundleruby200gemssidekiq2172libsidekiqmiddlewarechainrb124in block in invoke project rootvendorbundleruby200gemssidekiqfailures030libsidekiqfailuresmiddlewarerb10in call project rootvendorbundleruby200gemssidekiq2172libsidekiqmiddlewarechainrb124in block in invoke project rootvendorbundleruby200gemssidekiquniquejobs270libsidekiquniquejobsmiddlewareserverunique jobsrb15in call project rootvendorbundleruby200gemssidekiq2172libsidekiqmiddlewarechainrb124in block in invoke project rootvendorbundleruby200gemssidekiq2172libsidekiqmiddlewareserveractive recordrb6in call project rootvendorbundleruby200gemssidekiq2172libsidekiqmiddlewarechainrb124in block in invoke project rootvendorbundleruby200gemssidekiq2172libsidekiqmiddlewareserverretry jobsrb62in call project rootvendorbundleruby200gemssidekiq2172libsidekiqmiddlewarechainrb124in block in invoke project rootvendorbundleruby200gemssidekiq2172libsidekiqmiddlewareserverloggingrb11in block in call project rootvendorbundleruby200gemssidekiq2172libsidekiqloggingrb22in with context project rootvendorbundleruby200gemssidekiq2172libsidekiqmiddlewareserverloggingrb7in call project rootvendorbundleruby200gemssidekiq2172libsidekiqmiddlewarechainrb124in block in invoke project rootvendorbundleruby200gemssidekiq2172libsidekiqmiddlewarechainrb127in call project rootvendorbundleruby200gemssidekiq2172libsidekiqmiddlewarechainrb127in invoke project rootvendorbundleruby200gemssidekiq2172libsidekiqprocessorrb48in block 2 levels in process project rootvendorbundleruby200gemssidekiq2172libsidekiqprocessorrb105in stats project rootvendorbundleruby200gemssidekiq2172libsidekiqprocessorrb47in block in process project rootvendorbundleruby200gemssidekiq2172libsidekiqprocessorrb86in do defer project rootvendorbundleruby200gemssidekiq2172libsidekiqprocessorrb37in process project rootvendorbundleruby200gemscelluloid0152libcelluloidcallsrb25in public send project rootvendorbundleruby200gemscelluloid0152libcelluloidcallsrb25in thispatch project rootvendorbundleruby200gemscelluloid0152libcelluloidcallsrb122in thispatch project rootvendorbundleruby200gemscelluloid0152libcelluloidactorrb322in block in handle message project rootvendorbundleruby200gemscelluloid0152libcelluloidactorrb416in block in task project rootvendorbundleruby200gemscelluloid0152libcelluloidtasksrb55in block in initialize project rootvendorbundleruby200gemscelluloid0152libcelluloidtaskstask fiberrb13in block in create,"['ruby-on-rails', 'ruby']" +647527,safari does not show duration of mp3 served from php correctly original questioni am serving an mp3 file from a zf2 controller action this works fine in all browsers except for safari on os x and iphoneipadthe audio plays but the duration is just thisplayed as nannan whereas in every other browser the correct duration is being thisplayedi went over all the threads on so talking about the same problem and it seems like it has something to do with the response headers and the contentrange and acceptranges headers in particular i have tried all the different combinations but still to no avail safari still refuses to thisplay the duration correctlythe relevant code snippet looks like thispath teaseraudiopath directory separator teaserfilefp fopenpath retag md5serializefstatfpfclosefpfsize filesizepathshortlen fsize 1responsesetstatuscoderesponsestatus code 200responsegetheaders addheaderlinepragma public addheaderlineexpires 1 addheaderlinecontenttype audiompeg audioxmpeg audioxmpeg3 audiompeg3 addheaderlinecontentlength fsize addheaderlinecontentthisposition attachment filenameteasermp3 addheaderlinecontenttransferencoding binary addheaderlinecontentrange bytes 0 shortlen fsize addheaderlineacceptranges bytes addheaderlinexpad avoid browser bug addheaderlinecachecontrol nocache addheaderlineetag etagresponsesetcontentfile get contentspathreturn responsethe player i am using mediaelementjs looks like this in safarii have also tried interpreting the http range request header based on another example like so filesize filesizepath filetime dater filemtimepath filehandle fopenpath r rangefrom 0 rangeto filesize 1 etag md5serializefstatfilehandle cacheexpires new datetime if isset serverhttp range if preg matchbytesdi serverhttp range statuscode 416 else ranges explode substr serverhttp range 6 foreach ranges as range parts explode range rangefrom intvalparts0 if this is empty this should be 0 rangeto intvalparts1 if this is empty or greater than than filelength 1 this should be filelength 1 if emptyrangeto rangeto filesize 1 if rangefrom rangeto rangeto filesize 1 statuscode 416 else statuscode 206 else statuscode 200 if statuscode 416 response thisgetresponse responsesetstatuscode416 http11 416 requested range not satisfiable responseaddheaderlinecontentrange bytes filesize required in 416 else fseekfilehandle rangefrom set time limit0 try to thisable time limit response new stream responsesetstreamfilehandle responsesetstatuscodestatuscode responsesetstreamnamebasenamepath headers new headers headersaddheadersarray pragma public expires cacheexpiresformatymd his cachecontrol nocache acceptranges bytes contentdescription file transfer contenttransferencoding binary contentthisposition attachment filename basenamepath contenttype audiompeg mediagetfiletype contentlength filesize lastmodified filetime etag etag xpad avoid browser bug if statuscode 206 headersaddheaderlinecontentrange bytes rangefromrangetofilesize responsesetheadersheaders fclosefilehandlethis still gives me the same result in safari i even tried using core php functions instead of the zf2 response object to render a response using header calls and readfile but that does not work eitherany ideas on how to solve this are welcomeeditas suggested by marcb i compared the response headers of the two requests the first request is to the php action serving the mp3 file data and the second is when i browse to the same mp3 file directly at first the headers werent completely the same but i modified the php script to match the headers of the direct download see firebug screenshots belowresponse headers served by phpresponse headers direct downloadas you can see they are exactly the same except for the date header but that is because there was about a minute and a half in between the requests still safari is claiming it is a live broadcast when i try to serve the file from the php script and so the audioplayer still shows nan for the total time when i load it that way is there any way to tell safari to just download the whole file and just trust me when i say this is not a live broadcastalso could it be that safari sends different request headers and thus the response headers are also different i usually do my debugging in firefox with firebug when i open the mp3 file url in safari for instance i cannot open the web inspector dialog is there any other way to view what headers are being sent and received by safariedit 2i am now using a simple stream function implementing the range requests this seems to work on my dev machine even in safari but not on the live vps server where the site is runningthe function i use now courtesy of another soer do not remember the exact linkprivate function streamfile content type applicationoctetstream logger make sure the files exists otherwise we are wasting our time if file existsfile loggerdebugfile not found headerhttp11 404 not found exit get file size filesize sprintfu filesizefile handle range header if isset serverhttp range range serverhttp range loggerdebuggot range range elseif apache apache request headers loggerdebuggot apache headers print rapache 1 headers array foreach apache as header val headersstrtolowerheader val if issetheadersrange range headersrange else range false else range false is range if range partial true list param range explode range bad request range unit is not bytes if strtolowertrimparam bytes headerhttp11 400 invalid request exit get range values range explode range range explode range0 deal with range values if range0 end filesize 1 start end intvalrange0 else if range1 start intvalrange0 end filesize 1 else both numbers present return specific range start intvalrange0 end intvalrange1 if end filesize start end end filesize 1 partial false invalid rangewhole file specified return whole file length end start 1 no range requested else partial false send standard headers headercontenttype content type headercontentlength filesize headerxpad avoid browser bug headeracceptranges bytes headerconnection keepalive send extra headers for range handling if partial headerhttp11 206 partial content headercontentrange bytes startendfilesize if fp fopenfile rb headerhttp11 500 internal server error exit if start fseekfp start while length set time limit0 read length 8192 8192 length length read printfreadfp read fclosefp just send the whole file else readfilefile exitthis is then called in the controller action path teaseraudiopath directory separator teaserfile fsize filesizepath thisstreampath audiompeg loggeri added some logging for debugging purposes and the difference seems to be in the request headers on my local dev machine where it works i get this in the log20140309t1801170700 debug 7 got range bytes0120140309t1801180700 debug 7 got range bytes050242320140309t1801180700 debug 7 got range bytes131072502423on the vps where it does not work i get this20140309t1802250700 debug 7 got range bytes0120140309t1802290700 debug 7 got range bytes0120140309t1802350700 debug 7 got apache headers array accept acceptencoding identity connection close cookie utma71101845663885213680648571368814780136881892755 nsz9385e69da4d1c04eeb22937b75731efef7f2445091454c0aea12658a483606d07 phpsessidc6745c6c8f61460747409fdd9643804c gaga1266388521368064857 host edited out icymetadata 1 referer edited out useragent mozilla50 macintosh intel mac os x 10 9 1 applewebkit5377311 khtml like gecko version701 safari5377311 xplaybacksessionid 04e79834deb547f6af22cfda0b45b99fsomehow on the live server only the initial request for the first two bytes which safari uses to determine if a server supports range requests comes in twice but the range request for the actual data is never done instead i am getting a bunch of strange request headers as returned by the apache request headers call in the stream function i am not getting that on my local dev machine which also runs apacheany ideas would be greatly appreciated really pulling my hair out here,['php'] +647620,add the installation prefix of qt5widgets to cmake prefix path i do not know a lot about cmake i am trying to build a client using cmake and qt getting the following errorcmake error at alethzerocmakeliststxt26 find package by not providing findqt5widgetscmake in cmake module path this project has asked cmake to find a package configuration file provided by qt5widgets but cmake did not find onecould not find a package configuration file provided by qt5widgets with any of the following namesqt5widgetsconfigcmakeqt5widgetsconfigcmakeadd the installation prefix of qt5widgets to cmake prefix path or set qt5widgets dir to a directory containing one of the above files if qt5widgets provides a separate development package or sdk be sure it has been installed configuring incomplete errors occurredas far as i understand i need to add the qt path to cmake how do i do it i have qt installed in homeuserprograms all the explanations i find are just do this or that i need the exact terminal commands so i can just learn how to do it in the futurethanksupdate export cmake prefix pathhomeuserprograms did not help me,['c++'] +647646,what declaration turns the below loop into infinite loop place your declaration for i at line 3 so that the loop becomes an infinite looppublic class puzzel3 public static void mainstring args line 3 while i i 1 systemoutprintlni systemoutprintlndone,['java'] +647687,calculate the color at a given point on a gradient between two colors so this is essentially the method i would like to write in objectiveccocoa using uicolors but i am really just interested in the underlying math uicolor colorbetweencoloruicolor startcolor andcoloruicolor endcolor atlocationcgfloatlocationso as an example say i have two colors pure red and pure blue given a linear gradient between the two i want to calculate the color that is at say the 33 mark on that gradientso if i were to call my method like souicolor resultingcolor uicolor colorbetweencoloruicolor redcolor andcoloruicolor bluecolor atlocation033fi would get the resulting color at b and similarly passing 00f as the location would return color a and 10f would return color cso basically my question is how would i go about mixing the rgb values of two colors and determining the color at a certain location between them,['ios'] +647723,how can i plot hysteresis in matplotlib i am trying to plot a the development of a pitchfork bifurcation over time the relationship between x and y starts off approximately linear but ends up being a sigmoidal s shape the final relationship is not a function there are multiple y values for some values of x matplotlib does nice wire frames for surface plots but these surface plots do not seem to be able to handle nonfunctionsis there another way of plotting just the surface of this relationship if possible i do not want a solid shape at the moment my data is in zero arrays where 1s indicate an approximation to the location of the surface i have included a very small sample data set and sample code that will plot of their location how do i join the dotsmy actual data sets are larger 500x200x200 and varied so i need to develop a flexible system this is what the final figure might look like from reading mplot3d documentation here it seems that i may need to convert my data to 2d arrays if this is the case please could you provide a method for this and if possible please tell me what these arrays represent i greatly appreciate any commentsuggestions that will advance this import numpy as npfrom mpl toolkitsmplot3d import axes3dimport matplotlibpyplot as pltsample data nparray 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 xs ys zs for g in xrangenpshapesample data0 for row in xrangenpshapesample data1 for col in xrangenpshapesample data2 if sample datagrowcol 1 xsappendg ysappendcol zsappendrowfig pltfigureax figadd subplot1 projection3daxscatterxs ys zspltshow,['python'] +647879,change color of inset area in uitableview separator i have a customized uitableview the cells have a different background color set in a custom backgroundview however the background color is only applied within the cell but not extended to the inset area of the separator as you can see in the screenshot there is a white area to the left of the colored separator how can we change the color of this white line we would like to make the line thisappear by setting it to the same color as the cell background thanks,['ios'] +647938,mtimesec is not present i am facing a tricky situation here i have a java based application that tries to scp remote machines to copy certain files while performing those tasks i am finding the below error message from the application sidescp protocol error mtimesec not presentbut when i manually try to scp from the server to endpoint machine i am able to do it without issuesthe command i am using for manual testing is scp localfile userhostnametmpi am not sure of the error message mtimesec is not present does anyone can throw some lights here i could not find useful info from web any experts thoughts would help a lotas scp is working normally using manual process i am not sure there is something wrong with scp,['java'] +648016,how to create json schema for namevalue structure my problem is that i am serializing the content of map to jsonin the output json i have object that follow keyname syntax rule the key is created from map key and the name from the value model example class storage mapstringstring values new hashmap mapputkey1key1 mapputkey2key2 mapputkey3key3 json example object key1value1 key2value2 key3value3json schema name storage description store of key values properties how can we describe the properties if we do not know the name the issue is that i do not know what the values will be but i know that they will be somecan you help me to provide me the full definition of schema thisclaimer i know that this can be also serialized as values keykey1 valuevalue1 keykey2 valuevalue2 keykey3 valuevalue3 but is do not want to have array in the json,"['java', 'javascript']" +648058,stop click propagation from ember action i have this code that when iconedit span is clicked it fires an action that opens a modal however at the same time the click propagates to the view below it personview i want the action to execute and stop the propagationthe only solution i can think of is to make the iconedit its own view and stop the click propagation by returning false in method click is there any other way of doing this without making another viewhbsview blockspersonview span classinline pullright iconedit action modalopen modifypersonpopup modifyperson thisspan p classinline puleft personnamefirstnamedelayedpview,['javascript'] +648164,jquery nested ajax calls formatting i have a requirement to make 6 ajax calls in succession based on data from the previous call i am nesting each call in the success of the previous call my question is what are some good ways to format the code so that it doesnt end up a million rows across my editor ajax type post url somescriptsomescriptphp data form funcbuild success function result if result ok ajax type post url somescriptsomescriptphp data form funcsomeotherfunc success function result if result ok ajax type post url somescriptsomescriptphp data form funcsomeotherfunc success function result if result ok and so on ignore brackets syntax isnt important for this question,['jquery'] +648180,assign null default value for optional query param in route play framework i am trying to define an optional query parameter that will map to a long but will be null when it is not present in the urlget foo controllerfooindexid long null and i essentially want to check if it was passed in or notpublic static result indexlong id if id null however i am getting a compilation errortype mismatch found nullnull required long note that implicit conversions are not applicable because they are ambiguous both method long2longnullconflict in class lowpriorityimplicits of type x nulong and method long2long in object predef of type x longlong are possible conversion functions from nullnull to longwhy cannot i do this assigning null to be a default value for an expected long optional query parameter whats an alternative way to do this,['java'] +648407,appcompat v7 project is created automaticaly after creating a new project in eclipse after creating any new android project eclipse automatically creates a appcompat v7 project without any files under src i have no idea how or why eclipse is creating this project i am also getting a weird error as you can see the androidmanifestxml exists in the project edit1 after cleaning the project the weird error was gone but i would still like to know why the appcompat v7 is created edit2 i also noticed that eclipse is automatically creating a new layout fragment mainxml under reslayout why i have created a new workspace and tried it several times but i still have this problemedit3 if you choose the minimum sdk version after api 14 you would not get this support folder,['android'] +648409,does exec preserve file descriptors this is actually a twostep questionwhat exactly is a file descriptor i thought it was the most fundamental way to represent an open file but since dup2 can make two different file descriptors point to the same file then what is it that represents a unique fileif i do dup2 before exec the whole program is then wiped out does it still have the same file descriptor table do the redirected file descriptors still are redirected,['c'] +648415,how can i use xib files instead of storyboard in xcode 5 i am very new to ios developing and many of the tutorials i watch follow the xib approach since they were recorded before xcode 5 how can i go with the xib approach in single view application when i delete storyboard and select one of the xibs as the main interface it is not working thanks for any tip,['ios'] +648426,execution of python code with m option or not the python interpreter has m module option that runs library module module as a script with this python code apyif name main print package print name i tested python m a to get empty string main whereas python apy returnsnone none main to me those two invocation seems to be the same except package is not none when invoked with m option interestingly with python m runpy a i get the same as python m a with python module compiled to get apyc whats the practical difference between these invocations any pros and cons between them also david beazleys python essential reference explains it as the m option runs a library module as a script which executes inside the main module prior to the execution of the main script what does it mean,['python'] +648463,is there a elegant and common way for converting postgresql hstore to jpa 21 datatype i have used jpa 21 converter to convert postgresql hstore to mapstring stringbut i did not find a universal way for different jpa providers such as eclipselink and hibernate so i need to write different converters for each jpa providerthe following is the example which uses different converters for eclipselink and hibernateis there an universal way for different jpa providers,['java'] +648524,cannot run jekyll new command i tried to use jekyll new command but it did not work and came out following errors jekyll new mybloglibraryrubygems18gemscommander416libcommanderrunnerrb385in require program program version required commanderrunnercommanderrorfrom libraryrubygems18gemscommander416libcommanderrunnerrb384in eachfrom libraryrubygems18gemscommander416libcommanderrunnerrb384in require programfrom libraryrubygems18gemscommander416libcommanderrunnerrb52in runfrom libraryrubygems18gemscommander416libcommanderdelegatesrb8in runfrom libraryrubygems18gemscommander416libcommanderimportrb10from usrbinjekyll23libraryrubysite18rubygemscore extkernel requirerb55in gem original require no such file to load json loaderrorfrom libraryrubysite18rubygemscore extkernel requirerb55in requirefrom libraryrubygems18gemsjekyll143binlibjekyllfiltersrb2from libraryrubysite18rubygemscore extkernel requirerb55in gem original requirefrom libraryrubysite18rubygemscore extkernel requirerb55in requirefrom libraryrubygems18gemsjekyll143binlibjekyllrb44from libraryrubysite18rubygemscore extkernel requirerb55in gem original requirefrom libraryrubysite18rubygemscore extkernel requirerb55in requirefrom libraryrubygems18gemsjekyll143binjekyll7from usrbinjekyll23in loadfrom usrbinjekyll23i am using mac os x 1085 mountain lioni checked stackoverflow and found a post which has a similar problemerror when running jekyll new commandthen i tried the below command sudo gem install jsonbut it did not work for my situation i uninstalled and reinstalled json but nothing happenedplease let me know if you know any other solutions i have been stuck on this problem since the beginning of the weekmy gem list gem environment are as follows gem list local gems bigdecimal 124blankslate 2124classifier 134colorator 01commander 416faststemmer 102ffi 193highline 1621ioconsole 042jekyll 143json 181liquid 255listen 131maruku 071minitest 475parslet 150posixspawn 038psych 203pygmentsrb 054rake 1010rbfsevent 094rbinotify 093rbkqueue 022rdoc 410redcarpet 230safe yaml 097testunit 2110toml 011yajlruby 110 gem envrubygems environment rubygems version 2 ruby version 211 20140224 patchlevel 76 x86 64darwin120 installation directory usrlocalcellarruby211librubygems210 ruby executable usrlocalcellarruby211binruby executable directory usrlocalcellarruby211bin spec cache directory usersmynamegemspecs rubygems platforms ruby x86 64darwin12 gem paths usrlocalcellarruby211librubygems210 usersmynamegemruby210 gem configuration update sources true verbose true backtrace false bulk threshold 10 remote sources shell path usrlocalbin usrlocalbin usrlocalsbin usrbin bin usrsbin sbin usrlocalgitbin usersmynamervmbinplease give me advice to help me thank you updated on mar 7 rvm list rvm rubies no rvm rubies installed yet try rvm help installjust in case you would like to see homebrew list brew listautoconf gmp4 libtool openssl readlineautomake libgpgerror libyaml pkgconfig rubycloogppl015 libksba llvm ppl011 rubybuildgcc46 libmpc08 mpfr2 rbenv2nd updated on mar 7 which rubyusrlocalbinruby which jekyllusrbinjekyll ruby versionruby 211p76 20140224 revision 45161 x86 64darwin120 echo pathusrlocalbinusrlocalbinusrlocalsbinusrbinbinusrsbinsbinusrlocalgitbinusersmynamervmbini remember that my mac had been installed ruby 187 before i installed 211p76,['ruby'] +648540,c defining type of a member class without template argument i am trying to set the type of the member of a class without passing it through template argumentin details forward declaration class a class bclass base template class t class derived public base private t2 var where t could be either class a or class bwhat i would like to do is for deriveda t2 is int for instance and for derivedb t2 is double for instance i would like to avoid the following solutiontemplate class t1 class t2class derived public base private t2 vari want to avoid this because for deriveda there could be various possible combinations for t2 derivedaint derivedadouble what i want is that the type of t2 is unique for the entire derivedaany idea how to solve that,['c++'] +648554,html input typeafilea not working in google chrome i am having a problem with the html tag input typefile in google chromethe browse button appears on the page as expected but when i click it in order to select a file the popup dialog window from the browser does not open at alli ve tested my form and in firefox and works correct any ideas whats wrong and how can i fix it here is also the codeform action methodpost acceptcharsetutf8 enctypemultipartformdatalabel forimgfilefile inputlabelinput typefile nameimgfile,['html'] +648557,reactivecocoa subscribe only to new values i have created an event subscriber in viewdidload as follows racobserve authenticationviewpasswordinputtextfield text subscribenextnsstring text handle thisthis fires whenever the textfieldtext property changes expected however it also fires once when created or for the intitial value which is not what i want of course i could filter this out but i only want to filter the first event out how do i do this requirementsif the password has a new empty value present a validation message cannot proceed password emptyif the password has a new nonempty value talk to remote client so whats the cleanest way to do this,"['ios', 'objective-c']" +648580,android studio 050 rebuild not working with proguard recently i updated android studio from 042 to 050 and android gradle plugin from 072 to 090 as the ide suggested the project runs and installs good but when i press buildrebuild project it throws an error which stops the rebuildhere is an error in messages tabinformationsee complete output in consoleerrorexecution failed for task projectnameproguarddebug javaioioexception please correct the above warnings firstand here is the problem thiscribed in the consoleprojectnameproguarddebugnote there were 2345 duplicate class definitionswarning comfacebooksettings cannot find referenced class comfacebookandroidbuildconfigwarning comfacebooksettings cannot find referenced class comfacebookandroidbuildconfigwarning comfacebookinternalutility cannot find referenced class comfacebookandroidbuildconfigwarning comfacebookinternalutility cannot find referenced class comfacebookandroidbuildconfigwarning there were 4 unresolved references to classes or interfaces you may need to add missing library jars or update their versions if your code works fine without the missing classes you can suppress the warnings with dontwarn options projectnameproguarddebug failedfailure build failed with an exceptionas i understood the problem is missing buildconfigjava which was in gen folder before i migrated from eclipse but now there is not gen folder and buildconfigjava is in the buildsourcebuildconfigdebug forlderi found the only sollution that really does something to this it is adding the linedontwarn comfacebook to the proguard config file but it is not really the sollution,['android'] +648659,java ocr is not producing any output i am using this ocr algorithm to detect numbers in an image i have tried using tesseract but i had the exact same problem sometimes it did not work this has not ever worked java ocr when i used java ocr it did not procuce any output but n the image is completely white and the numbers are black the only artifacts in the image are two lines near the top and bottom borders that do not even interefere with the characters the alignment is normal like printed text it is not handwriting or skewed bufferedimage image2 imageioreadnew filemoneyimagebmpimagemanipulatorshowimage2 5ocrscanner scanner new ocrscannerstring items scannerscanimage2 0 0 0 0 nullsystemoutprintlnitemsthe image2 shows clearly and this example was taken from someone else that published it as such i am not doing anything complicated and it does not make sense to me why this should not work it is a simple greyscale imagewhen i try running the standalone program the java ocr one it works and produces the correct numbers as output i do not know how to extract the characters from within my java project and why it does not workmy test image is also thisstring lasttext nulltesseract instance tesseractgetinstancetry lasttext instancedoocrimagefile catch tesseractexception ex loggergetloggeractionabstractionclassgetnameloglevelsevere null exproduces absolutely no output even if i give a picture of a single digit as outputted from java ocr they seem to work but both just do not output anything when i do the actual scanalso i am using tiff images and as i said before the character extraction works normally what does not work is java code calling a scan on the image i have linked the appropriate libraries or it would produce compiler errors,['java'] +648663,datastore vs cloud sql in google app engine i want to build an application that will serve a lot of people more than 2 million so i think that i should use google cloud datastore however i also know that there is an option to use google cloud sql and still serve a lot of people using mysql like what facebook and youtube dois this a correct assumption to use datastore rather that the relational cloud sql with this many users thank you in advance,['mysql'] +648671,automated testing of bare metal c code microprocessor firmware simulating changes in hardware registers i want to write automated tests for some very low level c code on a pc that i will port to the microprocessor i understand that there will be differences implementationspecific behaviours such as size of int which i will have to live with i need ideas on how to simulate changes of volatile variables which map to special function registers in the microcontroller eg in the code below the value of the register flag tx buff full can repeatedly change during the course of the execution of the code when space in the transmit buffer becomes available or is used up void send strchar str for each nonnull character for char i 0 stri i wait for space in tx hardware buffer whiletx buff full put character into hardware fifo tx register stri tx buff full and tx register are volatile variables mapped to the address of special function registers for the uartideally i will write the source so that it can be compiled without changes for both the automated tests on a pc and running on the microcontroller which probably needs preprocessor directivesfor example a directive that uses this line when compiled for the microcontrollerwhiletx buff fullbut uses this when compiled for testing on the pcwhiletest tx buff fullwhere the test tx buff full function would be a part of the test suite that emulates changes in the state of the registers i cannot think of a different way of achieving the result is this a reasonable way what would be a neat way of implementing the preprocessor directives to achieve this is there a neater way thanksedit from this question this question and this question some other ideas areusing preprocessor macros that produce inline code to replace reading of registersusing a programmable hardware test bench that can bootload and perform unit and integration tests bypassing the need for a simulator,['c'] +648795,why does foreachvar i in array2d work on multidimensional arrays given the following c code int array2d new int10 10 int sum 0 foreach var i in array2d sum i the question is what is causing the type of i to be correctly inferred as an int this is not at all obviuous as array2d is a rectangular array it does not implement ienumerableint it also implements a getenumerator method which returns a systemcollectionsienumerator i would therefore expect that i would be of type object my code is using net 403 related so question why do c multidimensional arrays not implement ienumerable,"['c#', '.net']" +648850,how can i extend a class defined behind a closure in javascript i have a set of javascript classes where a base class defines functions that are then shared by an inherited class it is working and it is set up like thisvar thinga functionname thisname namethingaprototype sayhi function alerthi thisname var thingb function thingacallthis charliethingbprototype new thingathingbprototypeconstructor thingbvar instanceofb new thingbinstanceofbsayhi alerts hi charliefor reasons that are outside of my control my company prefers to follow this pattern when writing javascriptsomeclass function private functions go here function someprivatemethod return public methods go here somepublicmethod function now this is fine as far as things go and it works well for many situations but it is more of a functional style there is only one class instance and everything is statici have been asked to modify my working code to more closely match the style my company prefers so my question is there a way to inherit from a class that is wrapped inside a factory class it would look something like thisfactoryclassa function var thinga functionname thisname name thingaprototype sayhi function alerthi thisname return createthinga functionname return new thinganame factoryclassb function define a thingb class that inherits from thinga somehow return createthingb function return new thingb var instanceofb factoryclassbcreatethingbinstanceofbsayhi should alert hi charlieis there a way to define thingb wrapped in factoryclassb that inherits from thinga wrapped in factoryclassa thanks to this question i know that i am not going to be able to do it exactly like this i am thinking of using a method to extend a given class somehow this answer seems close but i am having trouble figuring out the details of how to modify that example to fit with the specifics of my situation i am willing to bend my companys usual pattern a little bit but can i at least get closer to itupdate 1in response to adams comment to just add a parameter to the factory class heres where i am stuckthingbprototype new thingathingbprototypeconstructor thingbi cannot figure out how to adapt these lines to make it work if i just pass in a parameter to the factory class method,['javascript'] +648888,javascript upload image file and draw it into a canvas i work at a web application for painting images i use a canvas element and javascript to draw on it but i have a problem how can i load an image from the pc of the user and draw it on the canvas i do not want to save it on the server only on the webpagehere is a shortened version of the code the full code would be too longhtmlopen file input typefile idfileupload acceptimage br canvas idcanvas onmousemovekeepline onmouseupdrawline onmousedownstartline width900 height600 stylebackgroundcolorfcursordefault please open this website on a browser with javascript and html5 supportcanvasjavascriptvar x 0var y 0var clicked falsevar canvas documentgetelementbyidcanvasvar context canvasgetcontext2dcontextstrokestyle blackcontextlinecap roundcanvasaddeventlistenermousemove functione getmouseposcanvas e falsetakepictureonchange function event var files eventtargetfiles file if files fileslength 0 file files0 processimagefile function processimagefile var reader new filereader readerreadasdataurlfile readeronload functione var img new image imgonload function contextdrawimageimg 100100 imgsrc etargetresult functions for drawing works perfectly wellfunction getmouseposcanvas e var rect canvasgetboundingclientrect x evtclientx rectleft y evtclienty recttopfunction startline contextmovetoxy contextbeginpath clicked truefunction keepline ifclicked contextlinetoxy contextstroke contextmovetoxy function drawline contextlinetoxy contextstroke clicked falsethere is no copyright,['javascript'] +648891,why cannot i reference systemruntimeserializationjson in c i want to use an api to get info from the interwebz the api returns data in json format i am pretty new to programming so bare with mei am running microsoft visual studio c 2010 express additionit appears that i have the net framework 4 client profile set as mytarget framework but i am honestly not sure exactly what thismeansthis is a windows forms applicationnot much code to show because i cannot really get started without the appropriate using statementusing systemusing systemcollectionsgenericusing systemlinqusing systemwindowsformsusing systemnetusing systemruntimeserializationjsoni get this errorthe type or namespace name json does not exist in the namespace systemruntimeserialization are you missing an assembly referenceam i missing a dll file or something based on my hours of fruitlessly searching for solutions i understand that the net 4xx should already have the tools needed to parse up a json formatted string,['c#'] +648915,why pointers to the same object have different values i have this piece of codeinclude iostreamclass apublic a m i0 protected int m iclass bpublic b m d00 protected double m dclass c public a public bpublic c m ca private char m cint main c d a b1 d b b2 d stdcout longb1 stdendl longb2 stdendlwhen compiled and run it produces the following output140734705182320140734705182328it is not completely clear why different pointers to the same address d have different valuesthanks in advance,['c++'] +648965,datetimedayofweek micro optimization first of all i am asking this question just for fun and eager to learn i have to admit i love to mess around with microoptimizations although they have never led to any significant increase in speed in any of my developmentsthe datetimedayofweek method does not represent a bottleneck in any application of mineand it is highly unlikely to be a problem in any other if anyone is thinking that this method has an impact on the performance of his applicationhe should think about when to optimize and then he should perform a profilingdecompiling datetime class with ilspy we find out how datetimedayofweek is implemented dynamicallyinvokable public dayofweek dayofweek dynamicallyinvokable targetedpatchingoptoutperformance critical to inline across ngen image boundaries get return dayofweekthisinternalticks 8640l 1l 7l public long ticks dynamicallyinvokable targetedpatchingoptoutperformance critical to inline this type of method across ngen image boundaries get return thisinternalticks this method performs the followingthe ticks corresponding to the current day are divided by the existing number of ticks in a daywe add 1 to the foregoing result in order that the remainder of division of 7 is between the numbers 0 and 6is this the only way to calculate the day of the weekwould it be possible to reimplement this in order to make it run faster,['c#'] +648982,angularjs 3button group acting as radio buttons using the ionic framework i am trying to create a group of three buttons that act as radio buttonsif i click on breakfast i would like lunch and dinner to return to their normal white state and breakfast to turn bluewith my current code i cannot get this functionality to work although i can get the buttons to switch color slightly randomly perhaps i just do not understand the ngclass directivehere is my html codediv classbar barsubheader div classbuttonbar a classbutton ngclassbuttonpositive isactiveb none isactiveb ngclickactivebreakfastbreakfasta a classbutton ngclassbuttonpositive isactivel none isactivel ngclickactivelunchluncha a classbutton ngclassbuttonpositive isactived none isactived ngclickactivedinnerdinnera divdivmy jsscopeactive functionmeal switch meal case breakfast scopebroadcastslideboxsetslide 0 scopeisactiveb scopeisactiveb scopeisactivel scopeisactivel scopeisactived scopeisactived break case lunch scopebroadcastslideboxsetslide 1 scopeisactiveb scopeisactiveb scopeisactivel scopeisactivel scopeisactived scopeisactived break case dinner scopebroadcastslideboxsetslide 2 scopeisactiveb scopeisactiveb scopeisactivel scopeisactivel scopeisactived scopeisactived break i can put the code in jsfidle if you require more information and a working solutionthanks for your helpnote i would like to maintain my active function and use the ngclass directive if possible as i have a lot of other code dependent on this function,['javascript'] +649031,width of element with whitespace nowrap does not adjust to child content i am trying to create a horizontally scrolling pane with tiling background image using overflowx scroll whitespace nowrap the pane spans an arbitrary number of elements cssframe overflowx scrollpane backgroundimage urlfreetilefloortexturejpg backgroundrepeat repeat whitespace nowrapitem thisplay inlineblock width 150px height 50px backgroundcolor greyhtmldiv classframe div classpane div classitemdiv div classitemdiv div classitemdiv divdivfiddle demoi want the background tile to automatically span the full width of the pane including all its item elements currently it only fills to the frame width the culprit seems to be the pane width property it does not adjust to the overall width of pane contentsofc it works by adjusting the width property manually but i need it to adjust dynamicallyhow do i get the panes background image to fill the panes full width is there another way to achieve same result,['css'] +649059,is channelurl parameter for facebook init deprecated i remember that there was a channelurl option for fbinit but it seems that it does not exist anymore according to this pageis this feature deprecated,['javascript'] +649164,can you explain the following function def an return maxlenn ai for i in n if isinstancen list else 0this was in a recent test of mine and i just cannot get list comprehension down so basically this function was supposed to return the length of the largest list which is what i am assuming based on the correct answers i would have understood that if it werent for this part of the function ai for i in nwhen i see that part it looks like it adds something to the length of the list it was iterating over can someone shed some light on the purpose of that part more specifically the reason for the additionedit so after looking at it more carefullyit looks like the function puts the length of the first list in a list then puts the length of the next list and returns the maxis this how it works,['python'] +649189,how to click on hidden element in protractor i have an element which is visible only when i hover over iti have written following code to hove over the panel so that the element is visibleptoractions mousemoveptorfindelementprotractorbyxpathidproductappdivdivdiv2divdivdivdiv2divdivdivdiv4tabletheadtrth2 perform ptorelementallbytagnameithenfunctionelm elm0click now i tried to click on it but it says elementnotvisibleerror element not visibleerror in protractorbasic scenario is i want to hover over a panel and then click on the hidden element because the element is not visible until it is hovered over,"['javascript', 'css']" +649317,how to restore the correct transaction when using autorenewable inapp purchases this question is regarding autorenewable iaps and how they should be restoredthese links this and this have not helped me unfortunatelyin my app i have users subscribing to autorenewable inapp purchases they can subscribe either 1 6 or 12 monthswhen they subscribe the transaction receipt is sent to my server for later validation i do not validate the receipt immediately since it would slow down the user experience a receipt validation query to apples servers takes about 1 2 seconds for me instead i use the naive approach and provide the content that the users subscribed to without any direct receipt verification i schedule a cron job to validate every users receipt once a day and revokes privileges upon outdated receiptsnow since apples guidelines clearly state that a restore functionality is required for applications with autorenewable subscriptions i have chosen to implement thatwhen i try to restore the purchases in sandbox mode using skpaymentqueue defaultqueue restorecompletedtransactionsi obtain not only current subscriptions but all previous subscriptionsincluding outdated ones in the callback to voidpaymentqueueskpaymentqueue queue updatedtransactionsnsarray transactionscurrently i have tried my iaps about 30 times which means that the above method is sent 30 different transactionsoutdated and active for each of these transactions i upload the transactions receipt to my web service for later verification now should it happen that the last transaction has an outdated receiptbut the second to last transaction was actually valid it would overwrite the currentvalid receipt for the current user and thereby revoke the privileges for the user falselybasically my problem is that when calling restorecompletedtransactions i obtain a list of both outdated and active transactions and on the serverside they might invalidate each other optimally i would like to only retrieve one transactionthe most relevant and have that receipt sent to my server for later validationall in all i guess my main question ishow can i make sure that only an activeie the most current transaction is restored,['ios'] +649332,which parts of the c standard library are not covered by the rest of the c standard library the c library includes the same definitions as the c language librarybut the c library seems to duplicate extend some of the functionality of the c library in nonclibrary headers for example the c library has stringh and the c library has both cstring and string the c library has timeh and the c library has both ctime and chronoif i need a string class i assume that i am better off using string instead of cstring because string can benefit from all the nonc functionality in c eg exceptions but there is functionality in the c library that does not exist in any other form in the c library for example i could not find anything like memcpy and memcmp outside cstringwhich parts of the c library have no analogue in the nonclibrary headersif the version of the c standard matters for this i am interested in c11,['c++'] +649347,how to reduce android apk size i have developed a simple android application its apk size is 8mb can anyone tell me how to reduce the apk size,['android'] +649453,currentculture with asyncawait custom synchronization context i have a web application and i make use of a lot of async operations using asyncawait everything worked fine but when i created custom tasks to run multiple things in parallel i noticed that within this task the current culture changes after an await the problem seems to be that the threadpool uses the culture of the operation system which is different from the culture of the request and that the default synchronization does not updates the culture even when changing the culture of the current thread within the taskso i create a custom synchronization context public sealed class culturepreservingsynchronizationcontext synchronizationcontext private cultureinfo culture private cultureinfo cultureui public culturepreservingsynchronizationcontext getculture public void makecurrent setculture synchronizationcontextsetsynchronizationcontextcreatecopy public override synchronizationcontext createcopy culturepreservingsynchronizationcontext clonedcontext new culturepreservingsynchronizationcontext clonedcontextculture culture clonedcontextcultureui cultureui return clonedcontext public override void postsendorpostcallback d object state baseposts setculture ds state public override void operationstarted getculture baseoperationstarted private void setculture threadcurrentthreadcurrentculture culture threadcurrentthreadcurrentuiculture cultureui private void getculture culture cultureinfocurrentculture cultureui cultureinfocurrentuiculture you can use it like this in my simple example it works fine but i have no real understanding of the very details to evaluate my approach btw my osculture is dede please note that this is just an example and has nothing to do with the real code i have just written this to demonstrate that the culture after the await is different to the culture before the await threadcurrentthreadcurrentculture new cultureinfoenus culturepreservingsynccontext context new culturepreservingsynccontext taskrunasync contextmakecurrent consolewritelinecultureinfocurrentculture webclient client new webclient string s await clientdownloadstringtaskasyncnew uri consolewritelinecultureinfocurrentculture waitany advice is really welcome to understand if the implementation of the synchronizationcontext is good or not and if not if there are any better solutions i do not want to open a thiscussion if async and await or tasks are good or not in my situation,['c#'] +649480,uirefreshcontrol bug after entering foreground i have noticed a little bug but really annoying when i use uirefreshcontrol in my view controller when i call application back form background and try to refresh the uirefreshcontrol is already loaded and it look like thisas you can see i use a custom navigation controller which hides like in facebook app amscrollingnavbar when i reaload data in uitableview everything comes back to normal and this bug shows only after getting back from backgroundthis is the code which i use to initialize uirefreshcontrol in viewdidload initializing generic refresh control selfrefreshcontrol uirefreshcontrol alloc init selfrefreshcontrol addtargetself actionselectorcollectdata forcontroleventsuicontroleventvaluechanged selftableview addsubviewselfrefreshcontrol,"['ios', 'objective-c']" +649502,error in c an expression tree may not contain a base access why not i was calling a method that accepts expressionfuncboolas part of the expression i was passingthisbottom baselineviewtopthe compiler gave me an error thatan expression tree may not contain a base acceso i simply changed it to thisbottom thislineviewtopbecause the member was protected anyway and now it worksbut this error really got me why the heck would this base be a problem especially if using this instead will work but syntactically be the same result same variable gets accessed,"['c#', '.net']" +649553,how to apply jquery after angularjs partial template is loaded i have a simple website that implements jquery in order to create a slider with some images in the indexhtml top bannernow i want to use angularjs so i am breaking the html code into separate partialsheaderfootertop bannerif i run the indexhtml in the original version without applying angularjs patterns then i can see the slider working perfect when applying angularjs patterns i moved the top banner html to a partial html and then applied ngview to the div where the top banner is originally locatedvar app angularmodulewebsite ngrouteappconfigfunctionrouteprovider routeprovider whenabouttemplateurlapartialsabouthtml whencontacttemplateurlapartialscontacthtml otherwiseredirecttohometemplateurlapartialshomehtmlwhen i refresh the page the slider is not working is rendered as simple html without any jquery effect is really a mess this partials has some jquery plugins that usually activates by documentready but this event not fire when angular load partial in ngview how can i call this event to initialize jquery plugins any clue how to fix thisappreciate any help,['jquery'] +649565,find the nth lucky number generated by a sieve in python i am trying to make a program in python which will generate the nth lucky number according to the lucky number sieve i am fairly new to python so i do not know how to do all that much yet so far i have figured out how to make a function which determines all lucky numbers below a specified numberdef luckynumber l range1 number 1 2 i 1 while i lenl del lli 1li i 1 return lis there a way to modify this so that i can instead find the nth lucky number i thought about increasing the specified number gradually until a list of the appropriate length to find the required lucky number was created but that seems like a really inefficient way of doing itedit i came up with this but is there a better waydef luckynumber f 2 and number f while true l range1 and 1 2 i 1 while i lenl del lli 1li i 1 if lenl number return lnumber 1 f 1 and number f,['python'] +649672,how to define a bean of string array in spring using xml configuration i am trying to define a spring bean of type string and now able to find a way to do so sample program is shown belowcomponentsampleclasspublic class sampleclass valuesomearrayid private string somearray public void dowitharray systemoutprintlnarraystostringsomearray spring xml configurationcontextannotationconfig contextcomponentscan basepackagecomdemospring utillist idsomearrayid array valuetigervalue valuelionvalue arrayutillistwhen i am running the program i get following exceptionexception in thread main orgspringframeworkbeansfactorybeancreationexception error creating bean with name sampleclass injection of autowired dependencies failed nested exception is orgspringframeworkbeansfactorybeancreationexception could not autowire field private javalangstring comdemospringsampleclasomearray nested exception is orgspringframeworkbeansconversionnotsupportedexception failed to convert value of type javautilarraylist to required type javalangstring nested exception is javalangillegalstateexception cannot convert value of type javalangobject to required type javalangstring no matching editors or conversion strategy foundi kind of understand what spring is complaining but i do not know how to fix itappreciate if anyone can helpthanks nn,['java'] +649799,unable to execute dex gc overhead limit exceeded i am designing an android application with eclipse when i try to run i see this window the message is unable to execute dex gc overhead limit exceeded gc overhead limit exceeded,['android'] +649858,are there any plans for a future c standard after c11 i searched on the open standards website particularly the c working group homepage but only found information about c11they seem to have regular meetings and thiscuss different features and extensions but they never actually mention a future c standard nor roadmap it is hard to tell whether they are working on a new standard or just a technical corrigendum to the current standard,['c'] +649931,loop background music in spritekit i am finishing a game for ios done with the spritekit framework i want to know if there is any way to loop background music while the user is playing spritekit includes a simple music player but it does not allow looping music so i want to know how could i accomplish this thanks,['objective-c'] +649994,aspnet overflow or underflow in the arithmetic operation when returning large file bigger 1 gb i went across some sort of limitation in aspneti reduced the problem into a sample project in aspnet mvc project created with visual studio 2010 and net 4 and the problem still occursin a mvc controller i have a method which provides a file downloadpublic actionresult downloadbigfile string file ctempfiletxt var readstream new filestreamfile filemodeopen fileaccessread return filereadstream textplain filewhen the file is below 1 gb the download works fine above 1 gb an exception is thrown overflow or underflow in the arithmetic operation with the following details overflow or underflow in the arithmetic operationdescription an unhandled exception occurred during the execution of the current web request please review the stack trace for more information about the error and where it originated in the codeexception details systemarithmeticexception overflow or underflow in the arithmetic operationsource erroran unhandled exception was generated during the execution of the current web request information regarding the origin and location of the exception can be identified using the exception stack trace belowstack tracearithmeticexception overflow or underflow in the arithmetic operationhttpexception 0x804005 an error occurred while communicating with the remote host the error code is 0x80070216 systemwebhostingiis7workerrequestraisecommunicationerrorint32 result boolean throwonthisconnect 4081269 systemwebhostingiis7workerrequestflushcoreboolean keepconnected int32 numbodyfragments intptr bodyfragments int32 bodyfragmentlengths int32 bodyfragmenttypes 122337 systemwebhostingiis7workerrequestflushcachedresponseboolean isfinal 847 systemwebhttpresponseupdatenativeresponseboolean sendheaders 10 systemwebhttpruntimefinishrequestnotificationiis7workerrequest wr httpcontext context requestnotificationstatus status 336version information microsoft net framework version4030319 aspnet version403031934009 the problem is reproducible but i did not find any information about this behavior how can i prevent this kind of problem or how can i manage big downloads 1gbthanks in advance,['asp.net'] +650048,angular uirouter scroll to top not to uiview i have just upgraded to uirouter 028 from 020 and i have noticed that when the state changes the scroll position jumps to the top of te child uiview that is the subject of the new statethis is fine but i have two problems with it1 i have 30px padding between the top of the page and the uiview and i would like it to scroll to the top of the page leaving a gap at the moment it goes exactly to the top of the uiview which looks ugly to achieve this i guess i either need to know how to get it to scroll to the top of the div that the uiview is in not the browser viewport or i need to find out how to override uiviewscroll to scroll to the uiview minus 30pxi have tried uiviewscrollprovideruseanchorscroll but if i do that it does not scroll at all i have also tried uiview autoscrollfalse which also stops the scrolling completely2 it does not actually scroll at the moment just jumps is it suppose to scroll or is it up to the developer to do this with css transitionsany help would really be appreciated,['javascript'] +650164,what magic does staticmethod do so that the static method is always called without the instance parameter i am trying to understand how static methods work internally i know how to use staticmethod decorator but i will be avoiding its use in this post in order to dive deeper into how static methods work and ask my questionsfrom what i know about python if there is a class a then calling afoo calls foo with no arguments whereas calling afoo calls foo with one argument where that one argument is the instance a itselfhowever in case of static methods it seems always foo is called with no arguments whether we call it as afoo or afooproof below class a x hi def foo printhello world bar staticmethodfoo abarhello world abarhello world abarfunction afoo at 0x05927b8 abarfunction afoo at 0x05927b8 abar1traceback most recent call last file stdin line 1 in moduletypeerror foo takes 0 positional arguments but 1 was given abar1traceback most recent call last file stdin line 1 in moduletypeerror foo takes 0 positional arguments but 1 was givenso am i right in concluding that the staticmethod function does some magic such that foo is always called with 0 argumentsif i were to define my own staticmethod in my own python code how would i do it is it even possible to define such a method from our own python code or can such a function be only defined as a builtin,['python'] +650238,how can i preserve the order of multiplications and divisions on my 32 bit embedded c application i need to perform the following computationcalcint millivolts int ticks return millivolts 32767 65536 10 ticksnow since an int on my platform has 32 bits and millivolts has a range of 1010 the millivolts 32767 65536 part is could cause an integer overflow to avoid this i have split the factor 65536 into 1024 32 and to and reordered as follows calcint millivolts int ticks return millivolts3276732101024ticks2this way as long as the order of multiplications and divisions is preserved by the compiler the function will compute correctlykerninghan and ritchie state in section 212 of the c programming language i do not have a copy of the c standard handyc like most languages does not specify the order in which the operands of an operator are evaluatedif i understand this correctly the compiler is free to change my carefully chosen expression into something that will not work as intendedhow can i write my function in such a way that it is guaranteed to workedit several answers below suggest using floating point calculations to avoid this issue this is not an option because the code is running on a cpu that does not have floating point operations furthermore the calculation is in the hard realtime part of my application so the speed penalty of using emulated floating point is too bigconclusion with the help of merdads answer and matt mcnabbs comment i managed to find the relevant section in kr section a7 where it saysthe precedence and associativity of operators is fully specified but the order of evaluation of expressions is with certain exceptions undefined even if subexpressions involve side effects that is unless the definition of an operator guarantees ths its operands are evaluated in a particular order the implementation is free to evaluate operands in any order or even to interleave their evaluation however each operator combines the values produced by its operands in a way compatible with the parsing of the expressions in which it appears this rule revokes the previous freedom to reorder expressions with operators that are matematically commutative and associative but can fail to be computationally associative the change affects only floatingpoint computations near the limits of their accuracy and situations where overflow os possibleso merdad is right there is nothing to worry about,['c++'] +650243,error a security token validation error occured for the received jwt token http status code unauthorized when i try to deploy an azure 22 application with aspnet web role i get the following error messageerror a security token validation error occurred for the received jwt token http status code unauthorized operationidi have a subscription and i logged in when i deployedpreviously i was getting this error messageinstance 0 of role xxy is in an unknown statewhy do i get this exception and how can i solve it,['asp.net'] +650271,ruby on rails 4 how to include javascript files in rails web application i am building a rails 4 web application and i want to include some js files into my application is it possible to directly add javascript file to my rails appassetsjavascripts folder and add reference in applicationjs like customejsfilejs is this the right way if yes is it possible for me to follow the same steps in adding jquery and bootstrap libraryany help is appreciated,"['javascript', 'jquery', 'ruby-on-rails']" +650492,multiple or condition in python i have a little code issue and it works with idle and not with eclipse can i write this if fields9 a or d or e or n or rinstead of this if fields9 a and fields9 d and fields9 e and fields9 n and fields9 rthank you,['python'] +650599,why does locals return a strange self referential list so i am using locals to grab some arguments in the function works nicelydef my functiona b print localsvalues my function121 2standard stuff but now let us introduce a list comprehensiondef my functiona b print x for x in localsvalues my function12 1 2ehh why has it inserted a selfreference,['python'] +650664,how do i create custom phpini files for each virtual host i have installed easyphp wamp for local development only i am not hosting any websitesis there a way to set custom php settings for separate virtual hosts currently and outofthebox the phpini file is loaded from cprogram files x86easyphpdevserver141vc11binariesphpphp runningversionphpini it would be nice if say i could drop in a custom phpini file into the virtual host directory to override settings in the original phpini this way i could better emulate a production servers environment on a persite basisi have seen this work with online hosting accounts but i cannot figure out how to make this work on my machine,['php'] +650731,why java division for integer is faster than hackers delight implementation i am testing divs10 function throughput from hackers delight book coded in java on my jdk 17 64bit version 21 and i7 intel boxprocessor 7vendor id genuineintelcpu family 6model 26model name intelr coretm i7 cpu 920 267ghzi am wondering why the default java operator is faster than divs10 function from hackers delight book the result shows divs10 is 3 times slower than operator to my surpriseanybody can tell me if there is any fancy intrinsic jvm can be using source code as below public class div10 public static final int divs10int n int q r and and n 31 9 q n 1 n 2 q q 4 q q 8 q q 16 q q 3 r and q 3 q 1 return q r 6 4 public static void mainstring args long count 0 for int i integermin value i integermax value i if i10 divs10i systemerrprintlnerror dividing i if i 0xf 0 systemoutprintlnfinished longtohexstringcount count i count systemoutprintlnsuccess count long start systemnanotime long count 0l int iter 100 0 for int j 0 j 10 j for int i iter i iter i count i10 for int j 0 j 10 j for int i iter i iter i count divs10i systemoutprintlncount warm up done start systemnanotime count 0l for int i integermin value i integermax value i count i10 systemoutprintlncount took systemnanotime start 10 0l ms systemnanotime start longintegermax value longintegermin value ns per ops start systemnanotime count 0l for int i integermin value i integermax value i count divs10i systemoutprintlncount took systemnanotime start 10 0l ms systemnanotime start longintegermax value longintegermin value ns per ops,['java'] +650770,swingutilitiesinvokelater takes a runnable and runs it on the edt i am confused with the signature of swingutilitiesinvokelater it takes a runnable object is it this runnable object that is handed over to the event thispatch thread why cannot i directly call createandshowgui on the run method of edt if it is possiblei have read articles on so on how the edt and invokelater work but i am confused with the runnable object that is passed swingutilitiesinvokelaternew runnable public void run createandshowgui and what would happen if i call swingutilitiesinvokelater again right below the callswingutilitiesinvokelaternew runnable public void run createandshowgui swingutilitiesinvokelaternew runnable public void run dosomethingontopofgui,['java'] +650779,error after installing xcode 51 two views in the same hierarchy have the same restoration identifier i am now getting this error that did not appear before when i open my project with xcode 51 two views in the same hierarchy have the same restoration identifieri tried to change the ids but it is not removing the error i also tried cleaning my build and deleting my derived data,"['ios', 'objective-c']" +650792,android how to remove the backhome button in the action bar hi everyone i am having difficutlies trying to remove the backhome button from the action bar getactionbarsetthisplayshowhomeenabledfalse thisable back button getactionbarsethomebuttonenabledfalsein a older android phone the back button is removed with these two code lines however with the nexus 4 the back button still appears but is just thisabled please help also i am just adding a menu item on the right that behaves like the backhome button replacing the backhome button what am i missing,['android'] +650830,google app engine deferreddefer error 404 i am trying to get running a task in the task queue using deferreddefer the task is added to the default task queue but the task fail with a 404 errorthis is the handlerimport webapp2import modelsimport defer ajust utilsfrom googleappengineext import ndbfrom googleappengineext import deferredclass ajust utilswebapp2requesthandler def getself deferreddeferdefer ajust utilsdothejobapplication webapp2wsgiapplicationajust utils ajust utils debugtruethis is the module defer ajust utils import loggingimport models from googleappengineext import ndbdef dothejob logginginfodebut de la mise a jour des utilisateurs utilisateurs modelsutilisateurquery utilisateurs utilisateursfetch for utilisateur in utilisateurs utilisateurproduire factures i false utilisateurput logginginfofin de la mise a jour des utilisateursand my appyaml file application xversion devruntime python27api version 1threadsafe yesbuiltins deferred onhandlers url ajust utils script tempo ajuster utilsapplication login adminheres the log 0102 10mar2014175045 0700 post ahqueuedeferred http11 404 113 utils appenginegoogle xappspotcom ms6 cpu ms0 cpm usd013 queue namedefault task name17914595085560382799 app engine release190 instance00c61b117c0b3648693af0563b92051423b3cbthank you for help,['python'] +650863,sdl2 c taking a screenshot hi i would like to know if it is possible to simply take a screenshot with sdl2i tried sdl getwindowsurface but i get an error saying no hardware accelerated renderers available i took the code from how do i take and save a bmp screenshot in sdl 2another solution i thought about is converting a texture to a surface but i did not manage to do sodo you have any solutionthanks,['c++'] +650887,navigation drawer with activity and child fragments i have a activity a a listfragment p and 2 fragments q and rwhen the app is launched a is created which loads p based on what user clicks it is replaced by q or rnow by referencing this tutorial i have implemented a navigation drawer which shows certain items to the user however since i have implemented the navigation drawer in the activity it shows for all the fragments i want it to be only available to p very much similar to googles gmail app when the user is on the main screen the drawer is present when user taps to open an email the drawer changes to back buttoni am not sure how to translate the above code any help is appreciated,['android'] +651065,is there a good way to check whether a datastax sessionexecuteasync has thrown an exception i am trying to speed up our code by calling sessionexecuteasync instead of sessionexecute for db writeswe have use cases where the db connection might be down currently the previous execute throws an exception when the connection is lost no hosts reachable in the cluster we can catch these exceptions and retry or save the data somewhere else etcwith executeasync it does not look like there is any way to fulfill this use case the returned resultsetfuture object needs to be accessed to check the result which would defeat the purpose of using the executeasync in the first placeis there any way to add a listener or something similar anywhere for the executeasync call that will asynchronously notify some other code that a db write has failedis this pertinentdatastax 102java 1740,['java'] +651106,spliting with empty space in ruby in both ruby and javascript i can write expression x split in javascript i get somehow reasonable result x but in ruby 200 i get x which is for me quite counterintuitive i have problems to understand how regular expressions works in ruby why do not i get the same result as in javascript or just x,['ruby'] +651308,how to return a stdstringc str i have a method which returns the constant char pointer it makes use of a stdstring and finally returns its c str char pointerconst char returncharptr stdstring somestring some processing return somestringc stri have got a report from coverity tool that the above is not a good usage i have googled and have found that the char pointer returned would be invalidated as soon as somestring meets its destructiongiven this how does one fix this issue how to return char pointer accuratelyreturning stdstring would resolve this issue but i want to know if there is any other means of doing this,['c++'] +651408,which design pattern to use when multiple inheritance is needed in java i have a vehicle class and nice implmented ship and plane to check for safety each class implementing its own safetycheck world was goodinterface vehicle public void safetycheckclass ship implements vehicle override public void safetycheck check if number of lifeboats number of passengers class plane implements vehicle override public void safetycheck check if oxygen mask is in place but soon a hybrid called seaplane was needed which duplicated safety checks of ship and planeclass seaplane implements vehicle override public void safetycheck check if oxygen mask is in place check if number of lifeboats number of passengers which design patterns help in such particular scenarios to reduce code redundancy and make implementation cleaner,['java'] +651461,xcode 51 libcordovaa architecture problems yesterday 31014 when ios 71 was released i also upgraded to xcode 51 and found that my phonegapcordova project would no longer compile to my iphone 5s i also upgraded cordova to the most recent release v 340013i have read many different solutions on so that relate so changing active architectures and building only active architectures and none of them work so heres what i have tried and the errors i get initially i got the errormissing required architecture arm64 in file long file path omitted libcordovaaundefined symbols for architecture arm64so i tried the following i selected the cordovalib subproject in my project and in both the project and target i went to build settings under architectures and made sure that arm64 was not included in any of the debug or release architectures at this time build active architecture only is set to yes that resulted in the following errorfile was built for archive which is not the architecture being linked armv7 long file path omitted libcordovaaundefined symbols for architecture armv7setting build active architecture only to no the error again becomes missing required architecture arm64 in file long file path omitted libcordovaaundefined symbols for architecture arm64i am not sure what else to try the projects architecture settings only includes the key base sdk which is set to ios 71 the projects target does not have architectures settings anyway i am fairly certain the problem lies with the embedded cordovalib subproject what can i do to make this thing compile to my device successfullyupdate same issue on apache is jira,['ios'] +651478,jquery validator and datepicker click not validating i am using jquery validator to validate text inputs the problem i have is if i click submit it thisplays all error message correctly however on the datepicker input to clear the error message i have to select the datepicker twice ie 1 click to select and it inputs the data correctly 2nd click to clear the error message i read somewhere about using an on event on the datepicker so i tried that but it made no difference i do not think that is coded correctly i am assuming that the invalid and success classes are part of the validator script worth a try what could be happening here thankssciprt codescript typetextjavascriptfunction datepickerdatepicker changemonth true changeyear true yearrange 20112037 dateformat ddmmyy mindate 0 defaultdate null onchangedate functionev ifdatepickervalid datepickerremoveclassinvalidaddclasuccess scripthtml codelabel fordatepicker input iddatepicker namedatepicker typetext labelvalidator relevant coderulesmessage section datepicker required true date true datepicker required required you must enter a destruction date date can contain digits only,['jquery'] +651608,what algorithms are used in c11 stdsort in different stl implementations the c11 standard guarantees that stdsort has on logn complexity in the worst case this is different from the averagecase guarantee in c9803 where stdsort could be implemented with quicksort maybe combined with insertion sort for small n which has on2 in the worst case for some specific input such as sorted inputwere there any changes in stdsort implementations in different stl libraries how is c11s stdsort implemented in different stls,['c++'] +651614,arc self and blocks i thought i understood the usage of self in a block that is copied is a no no but in an attempt to clean my code i enabled a bunch of warnings in xcode one called sending messages to weak pointers so now in all my blocks every time i use my created weakself reference weak typeofself weakself selfi get this warning weak receiver may be unpredictably set to nila trivial example weak typeofself weakself selfaclass dosomethinginablock weakself dosomething warningi have seen answers which define a version of self within the block like so weak typeofself weakself selfaclass dosomethinginablock typeofself selfref weakself selfref dosomething no warningso i am wondering what actually happens heream i just tricking the compilerwhat does a strong reference to a weak reference doanything else i am missingthanks,"['ios', 'objective-c']" +651685,systemdatasqlite with ef6 i am working on a project that involves connecting sqlite with ef 6 in a databasefirst approach i have installed systemdatasqlite and ensured that their dlls were in the gac and added the dependencies to my project using nuget however when i attempt to create a schema via the entity data model wizard for an alreadyexisting database i get the erroryour project references the latest version of entity framework however an entity framework database provider compatible with this version could not be found for your data connection exit this wizard install a compatible provide and rebuild your project before performing this actioni have tried the answers in this thread but the fixes that did not involve creating the dao classes by hand do not seem to help since the database that i am connecting to is quite large schemawise recreating the schema in code is not reasonable for me my appconfig followsxml version10 encodingutf8configuration configsections section nameentityframework typesystemdataentityinternalconfigfileentityframeworksection entityframework version60 cultureneutral publickeytokenb77a5c561934e089 requirepermissionfalse configsections startup supportedruntime versionv40 skunetframeworkversionv451 startup entityframework defaultconnectionfactory typesystemdataentityinfrastructuresqlconnectionfactory entityframework providers provider invariantnamesystemdatasqliteef6 typesystemdatasqliteef6sqliteproviderservices systemdatasqliteef6 version10910 cultureneutral provider invariantnamesystemdatasqlite typesystemdatasqliteef6sqliteproviderservices systemdatasqliteef6 version10910 cultureneutral providers entityframework systemdata dbproviderfactories remove invariantsystemdatasqlite add namesqlite data provider invariantsystemdatasqlite descriptionnet framework data provider for sqlite typesystemdatasqlitesqlitefactory systemdatasqlite remove invariantsystemdatasqliteef6 add namesqlite data provider entity framework 6 invariantsystemdatasqliteef6 descriptionnet framework data provider for sqlite entity framework 6 typesystemdatasqliteef6sqliteproviderfactory systemdatasqliteef6 dbproviderfactories systemdataconfigurationi do not entirely understand what vs is complaining about as it appears that systemdatasqlite has properly bound itself into vs and that the config file contains the requisite information to allow vs to find it to access the db however i missed something and i cannot figure out what,['c#'] +651718,css not selector not working my html is generated by wordpressdiv classheadermain h1 clasitetitlea href relhometheme previewah1 div clasearchtoggle active a hrefsearchcontainer clascreenreadertextsearcha div nav idprimarynavigation clasitenavigation primarynavigation rolenavigation h1 classmenutoggleprimary menuh1 a clascreenreadertext skiplink hrefcontentskip to contenta div classnavmenuulli classpage item pageitem2a href id2aboutalili classpage item pageitem46 page item has childrena href id46parent pageaul classchildrenli classpage item pageitem49a href id49subpagealiulliuldiv nav divi want to hide all elements but ones with pageitem2 so i useheadermain navmenu linotpageitem2 thisplaynonethis works but i also want to exclude pageitem46 from the selectorheadermain navmenu linotpageitem2 notpageitem46 thisplaynonethat does not work though,"['html', 'css']" +651758,sqlite like caseinsensitive for not english letters sorry for my englishi want to retrieve rows whose title field meets some pattern caseinsensintive and this field contains only notenglish lettersi tried thissearch from table name where uppercolumn name like upperpatternbut it does not work may be because the table contains only notenglish lettersupdateexampleselect from partnerstable where uppertitlecolumn like upperpattern wheretitlecolumn may contain n3414 no341 34nn3412 nn n2 npattern may contain 3 2 n etc,['sql'] +651801,bundling and minification without aspnet mvc is it possible to use bundling and minification from microsoftaspnetweboptimization without having an mvc projecti am creating an angularjs site communicating with a rest api for the rest api i am using aspnet web api i have also created an aspnet empty web application there are only html js and css files in this project and a webconfig i would like for my js and css files to be bundled and minified but i do not want to create a mvc project just to get that is it possible,"['c#', 'asp.net']" +651861,scrolling x axis plot area silverlight column series i have a column series chart which is working finei have a feature that i need to add to that i want the horizontall scroll to be enabled to the plot area that is xaxishere is the screen shotif you see the screen shot i have six items and the bar are very thin because of more number of items so suppose if i have 20 items then the bars will not be visible at allso can we make the xaxis bar scrollable horizontally editresourcedictionaryxamlresourcedictionary xmlns xmlnsx xmlnsconvertorclrnamespacechartingdvprovider xmlnsdatavisclrnamespacesystemwindowscontrolsdatavisualizationassemblysystemwindowscontrolsdatavisualizationtoolkit xmlnschartingclrnamespacesystemwindowscontrolsdatavisualizationchartingassemblysystemwindowscontrolsdatavisualizationtoolkit xmlnschartingprimitivesclrnamespacesystemwindowscontrolsdatavisualizationchartingprimitivesassemblysystemwindowscontrolsdatavisualizationtoolkit controltemplate xkeyphonechartportraittemplate targettypechartingchart grid gridrowdefinitions rowdefinition heightauto rowdefinition height rowdefinition heightauto gridrowdefinitions datavistitle contenttemplatebinding title styletemplatebinding titlestyle datavislegend xnamelegend gridrow2 headertemplatebinding legendtitle styletemplatebinding legendstyle datavislegenditemspanel itemspaneltemplate stackpanel orientationhorizontal itemspaneltemplate datavislegenditemspanel datavislegendtemplate controltemplate targettypedatavislegend grid gridrowdefinitions rowdefinition heightauto rowdefinition gridrowdefinitions scrollviewer gridrow1 horizontalscrollbarvisibilityauto verticalscrollbarvisibilitythisabled borderthickness0 padding0 istabstopfalse itemspresenter xnameitems margin1001010 scrollviewer grid controltemplate datavislegendtemplate datavislegend chartingprimitivesedgepanel gridcolumn0 gridrow1 xnamechartarea styletemplatebinding chartareastyle grid canvaszindex1 styletemplatebinding plotareastyle chartingprimitivesedgepanel grid controltemplate chart style for phone style xkeyphonechartstyle targettypechartingchart setter propertyistabstop valuefalse setter propertypadding value10 setter propertypalette settervalue datavisresourcedictionarycollection blue resourcedictionary solidcolorbrush xkeybackground colore85f3d style xkeydatapointstyle targettypecontrol setter propertybackground valuestaticresource background style style xkeydatashapestyle targettypeshape setter propertystroke valuestaticresource background setter propertystrokethickness value2 setter propertystrokemiterlimit value1 setter propertyfill valuestaticresource background style resourcedictionary red resourcedictionary solidcolorbrush xkeybackground color76d164 style xkeydatapointstyle targettypecontrol setter propertybackground valuestaticresource background style style xkeydatashapestyle targettypeshape setter propertystroke valuestaticresource background setter propertystrokethickness value2 setter propertystrokemiterlimit value1 setter propertyfill valuestaticresource background style resourcedictionary light green resourcedictionary solidcolorbrush xkeybackground color648ed1 style xkeydatapointstyle targettypecontrol setter propertybackground valuestaticresource background style style xkeydatashapestyle targettypeshape setter propertystroke valuestaticresource background setter propertystrokethickness value2 setter propertystrokemiterlimit value1 setter propertyfill valuestaticresource background style resourcedictionary datavisresourcedictionarycollection settervalue setter setter propertylegendstyle settervalue style targettypedatavislegend setter propertyhorizontalalignment valuecenter setter propertyverticalalignment valuecenter setter propertyborderbrush valuestaticresource phoneforegroundbrush setter propertymargin value20 style settervalue setter setter propertychartareastyle settervalue style targettypepanel setter propertyminwidth value100 setter propertyminheight value75 style settervalue setter setter propertyplotareastyle settervalue style targettypegrid setter propertybackground valuetransparent style settervalue setter setter propertytemplate valuestaticresource phonechartportraittemplate styleresourcedictionaryin the xaml filechartingchart namebarchart stylestaticresource phonechartstyle templatestaticresource phonechartportraittemplatechartingchartseries chartingcolumnseries titleincorrect independentvaluebindingbinding key dependentvaluebindingbinding value animationsequencesimultaneous chartingcolumnseries chartingcolumnseries titlecorrect independentvaluebindingbinding key dependentvaluebindingbinding value animationsequencesimultaneous chartingcolumnseries chartingcolumnseries titleskipped independentvaluebindingbinding key dependentvaluebindingbinding value animationsequencesimultaneous chartingcolumnseries chartingchartseries chartingchart,['c#'] +651925,spring profiles on method level i would like to introduce some methods that are only executed during developmenti thought i might use spring profile annotation here but how can i apply this annotation on class level so that this method is only invoked if the specific profile is configured in propertiesspringprofilesactivedevtake the following as pseudocode how can this be doneclass myservice void run log profiledev void log only during dev,['java'] +651966,why is this assignment not threadsafe i have been reading this book from joseph albahari about threadingin part 2 i found this example when to lockhere is the aforementioned exampleclass threadunsafe static int x static void increment x static void assign x 123 threadsafe versionclass threadsafe static readonly object locker new object static int x static void increment lock locker x static void assign lock locker x 123 i could not understand why assign method is not thread safe should not integer assignment be atomic operation on both 32 and 64bit architectures,['c#'] +652008,retrofit gives eofexception only the first time i am using framework retrofit for the first time in my android project it handles communication with a backend now the strangest part is that on android 44 everything works like a charm on every version below i get a retrofiterror type javaioeofexception so it fails the first time and then when i push on the retry button it works so why is it failing the first time i want to fix this because it is annoying that users needs to click retrydoes someone got a solution for this,['android'] +652060,how to make a rest framework serializer thisallow superfluous fields i have noticed that the serializer is not really strict when it comes to rejecting input with unknown fieldsin 1 from rest framework import serializersin 2 class testserializerserializersserializer foo serializerscharfield in 3 s testserializerdatadictfoofoo barbarin 4 sis validout4 trueis there a way to configure the serializer to return a validation error about bar being unexpected in this situation,['python'] +652122,accesscontrolalloworigin in django app when accesed with phonegap i am developing a phonegap app for my django based app but when trying to make ajax calls i get this errorxmlhttprequest cannot load tagmodeanyformatjson no accesscontrolalloworigin header is present on the requested resource origin null is therefore not allowed access how can i make it so my django app allows cross origin for some urlsheres my ajax codeget function getjson tags jqueryjavascript tagmode any format json functiondata eachdataitems functionitem consolelogitem,['python'] +652124,building a static version of qt 521 with visual studio 2013 i have been trying for a few days now to build a static version of qt with visual studio 2013i just cannot figure out what i did wrongsystemwindows 7 64 bitvisual studio 2013 visual studio 2012 is still installedperl is installed activeperl51821801mswin32x64297964msipython is installed python276amd64msidirect x 10 sdk is installed dxsdk jun10exe i had to use this workarounddownloaded qt 521downloaded qt 530 alphawhat i did multiple timeextract the sources in a temp folder cqtsrcdelete qtwebkit and qtwebkitexamples directoriesfor each folder i launched a visual studio x86 command line and rancd cqtsrcconfigure c11 mp debugandrelease static angle nomake tests nomake examples prefix cqt521msvc2013 platform win32msvc2013nmakenmake installthis was always sucessfull for every variations of static vs shared or qt 521 vs qt 530 alpha that i triedin qt creatori can register the various kits compile and launch any example using the shared qt library the examples using the static qt library on the other hand never compiledthe error always looks like this lnk1104 cannot open file cqt530msvc2013staticlibtranslator commonlibthe problem is that the file is missing either translator commondlib in debug mode or translator commonlib in release modein visual studio 2013 with visual studio addin 123 alphai can add the qt version and change the qt version of my solutionif can compile and run a very simple program like this one using the shared version of qt include qtcoreinclude qtguiinclude qtwidgetsq import pluginqwindowsintegrationpluginint mainint argccharargv qapplication appargcargv qmessageboxcriticalnullptrhellohello qt return 0i get unresolved external linker errors when using the static version of qt1libglesv2dlibshaderobj error lnk2019 unresolved external symbol shinitialize referenced in function private void thiscall glshaderinitializecompilervoid initializecompilershaderglaaexxz1libglesv2dlibshaderobj error lnk2019 unresolved external symbol shfinalize referenced in function public static void cdecl glshaderreleasecompilervoid releasecompilershaderglsaxxz1libglesv2dlibshaderobj error lnk2019 unresolved external symbol shinitbuiltinresources referenced in function private void thiscall glshaderinitializecompilervoid initializecompilershaderglaaexxz1libglesv2dlibshaderobj error lnk2019 unresolved external symbol shconstructcompiler referenced in function private void thiscall glshaderinitializecompilervoid initializecompilershaderglaaexxz1libglesv2dlibshaderobj error lnk2019 unresolved external symbol shdestruct referenced in function public static void cdecl glshaderreleasecompilervoid releasecompilershaderglsaxxz1libglesv2dlibshaderobj error lnk2019 unresolved external symbol shcompile referenced in function protected void thiscall glshadercompiletohlslvoid compiletohlslshadergliaexpaxz1libglesv2dlibshaderobj error lnk2019 unresolved external symbol shgetinfo referenced in function protected void thiscall glshadercompiletohlslvoid compiletohlslshadergliaexpaxz1libglesv2dlibshaderobj error lnk2019 unresolved external symbol shgetinfolog referenced in function protected void thiscall glshadercompiletohlslvoid compiletohlslshadergliaexpaxz1libglesv2dlibshaderobj error lnk2019 unresolved external symbol shgetobjectcode referenced in function protected void thiscall glshadercompiletohlslvoid compiletohlslshadergliaexpaxz1libglesv2dlibshaderobj error lnk2019 unresolved external symbol shgetinfopointer referenced in function protected void thiscall glshadercompiletohlslvoid compiletohlslshadergliaexpaxzdespite all my efforts i was unable to find which lib to include to resolve those missing symbolsdo you have any idea what i have done wrong,['c++'] +652286,error message xmlhttprequest cannot load cross origin requests are only supported for http in angularjs this is my codemyappmodulefactoryeventdata functionhttplog return getevent functionsuccesscb httpmethod get url jsservicesproductsjson successfunctiondata loginfosuccess errorfunctiondata loginfoerror i have a simple json file in a local location and i am trying to read it using the http method of angularjs i am getting the following errorxmlhttprequest cannot load filecusersavraamdocumentsgithubangularjsappjsservicesproductsjson cross origin requests are only supported for http angularminjs73 error a network error occurredwhat is my mistake i am not using any server i am just openning my index file with chrome is this the mistake should i use a server if i want to use the http method,['javascript'] +652399,how to list all installed nuget packages how does one list all locally installed nuget packages is there a nuget equivalent of rpm qa within chocolatey there is the chocolatey list localonly but for the life of me i cannot find the nuget equivalent of that command,"['c#', 'asp.net']" +652408,static table view outside uitableviewcontroller after the new xcode update my app does not validate and shows this errorstatic table views are only valid when embedded in uitableviewcontroller instancesany chances to solve easily,"['ios', 'iphone']" +652520,uncaught oauthexception an unknown error has occurred with facebook php api i have this small script that gets the albums from a page this was working fine until today i started getting this wierd erroruncaught oauthexception an unknown error has occurredn thrown in base facebookphp on line 1254i checked other questions related to this and everyone seems to have this for different reasons this was working fine for months and i never touched it i also checked the app id and secret in case they expired or something but the ones on the facebook app page are still the samewhat could have happened to suddenly cause thisi did some more debugging and the problem is occurring in the graph function getting this result from facebook13mar2014 012246 utc array error array message an unknown error has occurred type oauthexception code 1 i checked the facebook developer site here and error code 1 is just described aspossibly a temporary issue due to downtime retry the operation after waiting if it occurs again check you are requesting an existing apii have been having the problem all day long though i do not think it is a temporary issue,['php'] +652557,django cannot access raw post data i am experiencing a strange thing with django here is my viewspydef apirequest return httpresponses s requestmethodrequestraw post datanow i make an http post with postman small app for google chromei set postman to make a post request with test in the raw fielddjango returns me 3 different thing randomsometime django returns get sometime nothing at all and sometimeattributeerror at wsgirequest object has no attribute raw post datarequest method getrequest url django version 162exception type attributeerrorexception value wsgirequest object has no attribute raw post dataexception location homespice djspiceviewspy in api line 17python executable usrbinpythonpython version 273python path usrlocallibpython27thistpackagessouth084py27egg usrlibpython27 usrlibpython27platlinux2 usrlibpython27libtk usrlibpython27libold usrlibpython27libdynload usrlocallibpython27thistpackages usrlibpython27thistpackages homespice djserver time wed 12 mar 2014 2251 0400why django returns me get when i clearly make a post requestwhy does it return me that errorwhy it does not return me the test that i set in the raw field,['python'] +652560,what does this return exactly this is a pointer to the calling object it returns the rvaluethis is a pointer to the pointer of the calling object it returns the value of the addressthis is a pointer to the pointer of the pointer of the calling object this is a reference to the pointer of the pointer of the pointer of the calling object stdvectorint iterator i vector1begini is the pointer to its own rvalue returns its own valuei is the pointer of a rvalue of an object contained in a vector returns the value pointed in valuei is the pointer to the pointer of a rvalue of an object contained in a vector i am really confusedheres a sample code where we find the expression thisclass iterprivate listelem pcurr const list plistpublic iterlistelem pcurr const list list pcurr pcurr plistlist t operator return pcurr data t operator return this,['c++'] +652565,why this code is not causing memory leak i wanted to simulate memory leak in my application i write following code and tried to see in perfmon int main int i while1 i int malloc10 just to avoid lazy allocation i 100 ifi null printfmemory not allocatedn sleep10 when i see used memory in task manager it is fluctuate between 52k and 136k but not going beyond that means somethings it shows 52k and sometimes 136k i do not understand how this code once goes to 136k coming back to 52k and not going beyond thati tried to use perfmon but not able to exactly what to see in perfmon snapshot of countersplease suggest how to simulate memory leak and how to detect it,"['c++', 'c']" +652566,how to correctly use google plus sign in with multiple activities what would be a goodrecommended way of tying up the google api client life cycle with the flow of a multiactivity app make the activities depend on the onconnected api client method to trigger its functionality use it as a onetime only activation thing or maybe something else entirelyi am currently struggling to understand how to correctly use the google sign in in my android app which has more than one activitythe idea is in a first phase to use the g sign in just to authenticate the user and be able to get her email to send notifications and stuff like that eventually i plan to roll out other google functionality like maybe maps or other google play services so i think it is useful to implement it alreadyhowever my app is not behaving as expected and i have narrowed down the issue to the fact that i have not yet understood the g sign in app cycle when more than one activity is presentwhat is the correct or recommended way to implement this auth method is there maybe a pattern of sorts that could guide me in the right directionfor example i have found a very simple diagram of the life cycle of the api client but how does this relate to the app flow initially i have a login activity where i put the sign in button following googles guide i am able to sign in and when the onconnected method is called i start the home activity kinda like the dashboard or main screen of the appthis works somewhat for example what would be a good way of handling the onstart and onstop for each activity should i reconnect and reauthenticate the api client every time for every activity so maybe its a good idea to have a baseactivity to implement all thisanother issue is should i use the same api client object and pass it around somehow or maybe store it in the base activity class or should i be creating and initializing a new api client object every timehow about just using the login activity to authenticate with g and then just get the email and store it in a local database and flag the user as authenticated or active or something that would prevent me from having to reauthenticate every time the app is closed or connection is suspended even allowing for some battery savings the app is not really using g posting or any other functionality like that ideally it should work well offline and only need connection for stuff like initial authentication or other onetime only thingsany suggestions or pointers in the right direction are very much appreciatededit i have read every guide and tutorial i could find that uses google and every one of them addresses this from a single activity perspective i would think this is a common enough problem that it would benefit from a pattern or at least a general guideline,['android'] +652567,capture screenshot from nexus 10 emulator how do i capture screenshots from the nexus 10 emulator i need these high resolution screenshots to submit to google play storei get screen not available when i try using the screen capture tool in the eclipse tools someone suggested unchecking use host gpu in the android virutal device manager but if i do that the emulator will not starti think it might be a hardware limitation because nexus 10 uses very high resolution 2560 x 1600 i can capture nexus 7 screenshots fine,['android'] +652570,how to handle events from embeded exceloleobjects or excelshapes i am working on c and now vbnet ports of an old vba program it has lots of msformsoleobjects embedded in it like commandbutton or even images my first thought was to declare all the buttons as microsoftvbeinteropformscommandbuttonbut that leads to a com exception that the system com type cannot be cast to formscommandbutton if i try a more generic version of this solution i do not find any items and if i try to go through all vbcomponets i note that they are all the sheets in the workbook but none of the controlsforeach vbcomponent x in globalsthisworkbookvbprojectvbcomponents interactionmsgboxname interactionmsgboxtostringthus all of these controls are not in vbcomponets but i can find them as oleobjects in thisworkbookworksheetsnoleobjects this is counterintutive to me but i probably do not understand the system to begin withhow do i handle the click action from such an object i am assuming that i need to be using the exceloleobjectevents event interface but i cannot seem to figure out how if i try to make custom events with delegates i do not seem to be able to assign them to oleobjects if i use actionclickeventhandlercreatedelegate i can get a huge variety of errors that makes me think that is a dead end the official documentation from ms does not seem that helpful though it did introduce me to the idea of verb which i am looking into so far that has only produced com errors along the lines of application failed to starteven just trying to use one of the two standard events gotfocus i always pull a 0x80040200 errorexampleexceloleobject buttoncatcher globalsthisworkbookworksheets1oleobjectscommandbutton1buttoncatchergotfocus commandbutton1 clickthrows a comexception exception from hresult 0x80040200 at the second line the button is enabled which is i checked after looking up the code number from the office dev sitetrying a more generic approach within the code for a sheet containing controlsobject commandbuttonstart thisgettypeinvokemembercommandbutton1 systemreflectionbindingflagsgetproperty null this nullthrows a missing method errorany help is greatly appreciated this seems like this should be obvious and i am missing itedit i have also found that i can cast these controls into excelshape but that does not actually get me any closer to running a function or sub from the vsto i am playing with excelshapeonaction but this requires a vba sub to be called presumably i could call an vba sub which calls a sub from the vsto as long as the vsto was com visible this seems really roundabout and i would only like to do it as a last resort,['c#'] +652573,can a custom view know that onpause has been called i have a custom view that runs a thread operation which sits around making calls to the interwebs periodically i would like to know if there is a way for me to not have to kill that thread from the parent activity onpause so that the thread is not milling about in the background after the activity has been backgrounded andor killedthe intention here is for the custom view to be self sufficient and not need additional handling from the activity the way to do that would be for it to listen for when its parent was backgrounded and for it to then let the infinite sleep loop in the thread expire i am not seeing a way to do that but am hoping that i am overlooking something,['android'] +652596,c preprocessor tokenization does not expand macro 1 why is the macro msg not expanded in the following expressiondefine msg hellodefine helloname msg namevoid hellodave usinggcc e p testcpp outputvoid msgdave msg name expands to hello dave and msg name expands to hello dave so what causes gcc not to expand msg name2 is there a workaroundis there a preprocessor directive like definedx such as expandx,['c'] +652625,how can we use compile outside a directive in angularjs i want to use compile in a controller inside a function and not in a directive is it possible i am trying the below code compilediv ngattrtooltiptestcanceldivscopebut this is throwing scope is undefined error i tried to pass scope inside the function but it is not working,['javascript'] +652662,persist form data across multiple steps in laravel when i have made multistep forms in the past i would generally store the form data in the session before returning it to the view that way the data persists if the user refreshes the page or clicks the browsers native back buttonstransferring my past logic to laravel i built the following form consisting of three stagesinput confirm successroutesphproutegrouparrayprefix account function routegetregister array before guest as accountcreate uses accountcontrollergetcreate routepostregister array before guestcsrf as accountcreatepost uses accountcontrollerpostcreate routegetregisterconfirm array before guest as accountcreateconfirm uses accountcontrollergetcreateconfirm routepostregisterconfirm array before guestcsrf as accountcreateconfirmpost uses accountcontrollerpostcreateconfirm routegetregistercomplete array before guest as accountcreatecomplete uses accountcontrollergetcreatecomplete accountcontrollerphpphpclass accountcontroller extends basecontroller private form session register form public function getcreate ifsessionhasthisform session get forms session data data sessiongetthisform session clear forms session data sessionforgetthisform session load the form view w the session data as input return viewmakeaccountcreatewithinputdata return viewmakeaccountcreate public function postcreate set the form input to the session sessionsetthisform session inputall validation rules array email requiredmax50emailuniqueusers password requiredmax60min6 password conf requiredmax60samepassword validator validatormakeinputall validation rules get forms session data data sessiongetthisform session return back to form w validation errors session data as input ifvalidatorfails return redirectbackwitherrorsvalidator redirect to the confirm step return redirectrouteaccountcreateconfirm public function getcreateconfirm prevent access without filling out step1 ifsessionhasthisform session return redirectrouteaccountcreate get forms session data data sessiongetthisform session retun the confirm view w session data as input return viewmakeaccountcreateconfirmwithinput data public function postcreateconfirm data sessiongetthisform session insert into db send emails etc clear forms session data sessionforgetthisform session redirect to the completesuccess step return redirectrouteaccountcreatecomplete public function getcreatecomplete return viewmakeaccountcreatecomplete createbladephpform action urlrouteaccountcreatepost methodpost email input typetext nameemail value issetinputemail einputemail iferrorshasemail errorsfirstemail endif br password input typetext namepassword value iferrorshaspassword errorsfirstpassword endif br password confirm input typetext namepassword conf value iferrorshaspassword conf errorsfirstpassword conf endif br formtoken input typesubmit valueconfirmformcreateconfirmbladephpemail inputemail password inputpassword form action urlrouteaccountcreateconfirmpost methodpost formtoken a href urlprevious returna input typesubmit namesubmit forward valuesubmitformthe above works fine however i am wondering if this is the best way to approach multistep forms in laravel,['php'] +652665,how to add row dynamically in jtable i want to add the row dynamically in jtable and i have writen the following code for that tbltasklist new jtable tbltasklistsetshowverticallinesfalse tbltasklistsetcellselectionenabledtrue tbltasklistsetcolumnselectionallowedtrue tbltasklistsetbordernew linebordernull for int count 1 count 10 count tbltasklistsetmodelnew defaulttablemodelnew object count title1 start stop pause status new string status task title start stop pause status tbltasklistgetcolumnmodelgetcolumn0setpreferredwidth31 tbltasklistgetcolumnmodelgetcolumn1setpreferredwidth346 tbltasklistgetcolumnmodelgetcolumn2setpreferredwidth33 tbltasklistgetcolumnmodelgetcolumn3setpreferredwidth31 tbltasklistgetcolumnmodelgetcolumn4setpreferredwidth28 tbltasklistsetbounds93 34 614 160 frmtasklistgetcontentpaneaddtbltasklistthe problem is that only the last row is added ie count print the value 10 in first columncan anyone explain how to solve the problem,['java'] +652705,is this explanation about vssrsspssuss accurately i read an explanation about vssrsspssussthe aim of this post is to provide information that will assist in interpreting memory reports from various tools so the true memory usage for linux processes and the system can be determinedandroid has a tool called procrank systemxbinprocrank which lists out the memory usage of linux processes in order from highest to lowest usage the sizes reported per process are vss rss pss and ussfor the sake of simplicity in this description memory will be expressed in terms of pages rather than bytes linux systems like ours manage memory in 4096 byte pages at the lowest levelvss reported as vsz from ps is the total accessible address space of a process this size also includes memory that may not be resident in ram like mallocs that have been allocated but not written to vss is of very little use for determing real memory usage of a processrss is the total memory actually held in ram for a process rss can be misleading because it reports the total all of the shared libraries that the process uses even though a shared library is only loaded into memory once regardless of how many processes use it rss is not an accurate representation of the memory usage for a single processpss differs from rss in that it reports the proportional size of its shared libraries ie if three processes all use a shared library that has 30 pages that library will only contribute 10 pages to the pss that is reported for each of the three processes pss is a very useful number because when the pss for all processes in the system are summed together that is a good representation for the total memory usage in the system when a process is killed the shared libraries that contributed to its pss will be proportionally thistributed to the pss totals for the remaining processes still using that library in this way pss can be slightly misleading because when a process is killed pss does not accurately represent the memory returned to the overall systemuss is the total private memory for a process ie that memory that is completely unique to that process uss is an extremely useful number because it indicates the true incremental cost of running a particular process when a process is killed the uss is the total memory that is actually returned to the system uss is the best number to watch when initially suspicious of memory leaks in a processfor systems that have python available there is also a nice tool called smem that will report memory statistics including all of these categories procrankprocrankpid vss rss pss uss cmdline481 31536k 30936k 14337k 9956k system server475 26128k 26128k 10046k 5992k zygote526 25108k 25108k 9225k 5384k androidprocessacore523 22388k 22388k 7166k 3432k comandroidphone574 21632k 21632k 6109k 2468k comandroidsettings521 20816k 20816k 6050k 2776k jpcoomronsoftopenwnn474 3304k 3304k 1097k 624k systembinmediaserver37 304k 304k 289k 288k sbinadbd29 720k 720k 261k 212k systembinrild601 412k 412k 225k 216k procrank 1 204k 204k 185k 184k init35 388k 388k 182k 172k systembinqemud284 384k 384k 160k 148k top27 376k 376k 148k 136k systembinvold261 332k 332k 123k 112k logcat33 396k 396k 105k 80k systembinkeystore32 316k 316k 100k 88k systembininstalld269 328k 328k 95k 72k systembinsh26 280k 280k 93k 84k systembinservicemanager45 304k 304k 91k 80k systembinqemuprops34 324k 324k 91k 68k systembinsh260 324k 324k 91k 68k systembinsh600 324k 324k 91k 68k systembinsh25 308k 308k 88k 68k systembinsh28 232k 232k 67k 60k systembindebuggerdbut i cannot find the original of this article and i would like to know whether this explanation is accurate,['android'] +652723,refresh dom after append element solvedmain problem was with itscript typetextjavascript srcscriptjquery was too old i thinkscript srcscriptsolved problem why alert does not work after append dom should shows bla bla after click on itdoctype htmlhtmlheadtitletesttitlemeta charsetutf8script typetextjavascript srcscriptscriptdocumentreadyfunction main bodyappendh1helloh1input idbut typebuttonclick but on click function alert bla bla script headbody idmain body bodyhtml,"['javascript', 'jquery']" +652756,navigation drawer item background colour for selected item i used android studio to implement the navigation drawer and i cannot get the blue colour that is used to show which section were currently in to changei have tried numerous things i am currently using a listselector which looks likeselector xmlnsandroid item androidstate activatedtrue androiddrawablecolorselected item androidstate pressedtrue androiddrawablecolorhighlight selectori have also tried state checked state pressed works in this situation but the currently selected item is still blue editi have been examining this more and when the adapter is created the context that is passed is getactionbargetthemedcontext so i am thinking if i can find the right attribute to assign to my actionbar style i can change it from there i have tried a few different attributes with no luck does anyone know the exact attributei have also realised if i putitem nameandroidactivatedbackgroundindicatordrawablenav listview selectoritemin the main part of my theme and change getactionbargetthemedcontext for getactivitygetbasecontext then i can change the color but i do not think this is the correct way i think the themed context should be used so if anyone knows where the activatedbackgroundindicator could be put so that it would be used in getactionbargetthemedcontextedit2so the text view used for the listview is one within the sdk it looks like thistextview xmlnsandroid androididandroididtext1 androidlayout widthmatch parent androidlayout heightwrap content androidtextappearanceandroidattrtextappearancelistitemsmall androidgravitycenter vertical androidpaddingstartandroidattrlistpreferreditempaddingstart androidpaddingendandroidattrlistpreferreditempaddingend androidbackgroundandroidattractivatedbackgroundindicator androidminheightandroidattrlistpreferreditemheightsmallso i tried modifying the androidattractivatedbackgroundindicator at the theme level but it has no effect for checkedselectedactivated but it does for pressed does anyone know why this is and how i can change it,['android'] +652819,unable to retrive post data using context httpservletrequest when passed to oauthtokenrequest using oltu i m using oltu for oauth2when using context httpservletrequest request i am unable to retrive post datawhen i am using formparam i am able to retrive post dataon passing request to oauthtokenrequest oauthtokenrequest oauthrequest new oauthtokenrequestrequest i am getting following error errorinvalid requesterror descriptionmissing grant type parameter valuewhen debugging on the oltu oauthtokenrequest class following code is used to retrive param value public string getparamstring name return thisrequestgetparametername from request it is unable to get post dataas i am getting request object using context httpservletrequest request it is said that using context httpservletrequest request it is not possible to get post data for using context httpservletrequest requestsomy question is how to get httpservletrequest request with post data in jaxws so that i can pass httpservletrequest request to oauthtokenrequest this is my code pathtokenpublic class tokenendpoint post consumesapplicationxwformurlencoded producesapplicationjson public response authorizeformparamstate string statecontext httpservletrequest request throws oauthsystemexception try here i am unable to get value of requestgetparameterstate but using formparamstate i am able to get value of post parameter state requestgetparameterstate exception is thrown from following code oauthtokenrequest oauthrequest new oauthtokenrequestrequest,['java'] +652882,eclipse cdts code analysis does not understand virtual inheritance i have a class hierarchy with two diamonds caused by having to extend all the classes in a decorator pattern they already extend virtuallynamespace sandbox class a public virtual a virtual void foo0class adecorator public virtual a private a decorateda public adecoratora a decoratedaa void foo return decoratedafooclass aimpl public virtual a public void foo class b public virtual a public virtual b virtual void bar0class bdecorator public adecorator public b private b decoratedb copy of the pointer with a different type public bdecoratorb b adecoratorb decoratedbb void bar return decoratedbbarclass bimpl public b public aimpl public void bar b b new bdecoratornew bimplgraphically a v v v aimpl b adecorator bimpl bdecoratorgcc compiles this with no problem but eclipses code analysis insists that bdecorator does not implement foothe type sandboxbdecorator must implement the inherited pure virtual method sandboxafooi can silence this problem by setting this type of error to info on the settings but i am wondering is there is actually an error in the code that gcc overlooked or if there is something i can do to make the code analysis accept the code if it is possible i would rather not have this code analysis feature silenced so i can easily detect actual mistakeshow is bimpl different than bdecorator in terms of what methods it implements the code analysis does not complain anything about bimpl yet the way they have an implementation of foo is similar,['c++'] +652982,adb not responding wait more or kill adb or restart ubuntu 13 64bit after unsuccessfully attempting to make my new intellij and android sdk to work on my newly installed ubuntu 1310 i am coming to you for help i know there are thousands of suggestions out there already but none of them worked for mehere is what i have triedadb killserveradb startserveradb devicesthat last command listed my device and that meant that it was able to detect it without any issuesi have added all the necessary rules like 51androidrules and those should be finestarted and restarted the ide several times without any successi have installed libraries to fix any 64bit issues i even deleted the adb key in the android folder since it gets generated automatically each time anywayi have no other older versions of intellij or sdksthis was a clean installation of ubuntu i totally removed my windows 8 yeah am done with windows and installed ubuntu 13i do not know what else to try and do because i have spent hours online trying suggestions from others to no availany help would be really appreciated because i cannot wait to get back to my android app developmentthank youedit solutioni solved this problem and then documented it here for others who are having this issue adb not responding the solutioni hope this helps,['android'] +653041,qt converting float to qstring this seems like it should be very simple but i am going through the docs and not seeing anything i just need to convert a number that is represented as a float object into a qstring object i know there is the function qstringnumber that can be used for other types like int and double like soint a 1 qstring b qstringnumberahowever this does not seem to work for float perhaps there is some way where it is converted first from float to another type and then from that type to qstring if anyone has any ideas i would appreciate it thanks,['c++'] +653075,javasqlsqlexception no suitable driver found for jdbcmysqllocalhost3306dbname i have this java program mysqlconnectexamplejavaimport javasqlimport javautilpropertiespublic class mysqlconnectexample public static void mainstring args connection conn1 null connection conn2 null connection conn3 null try string url1 jdbcmysqllocalhost3306aavikme string user root string password aa conn1 drivermanagergetconnectionurl1 user password if conn1 null systemoutprintlnconnected to the database test1 string url2 jdbcmysqllocalhost3306aavikmeuserrootpasswordaa conn2 drivermanagergetconnectionurl2 if conn2 null systemoutprintlnconnected to the database test2 string url3 jdbcmysqllocalhost3306aavikme properties info new properties infoputuser root infoputpassword aa conn3 drivermanagergetconnectionurl3 info if conn3 null systemoutprintlnconnected to the database test3 catch sqlexception ex systemoutprintlnan error occurred maybe userpassword is invalid exprintstacktrace i compile it like thisejava mysql code driverjavac mysqlconnectexamplejavaejava mysql code driverjava cp mysqlconnectorjava3011stablebinjarmysqlconnectexamplei get this erroran error occurred maybe userpassword is invalidjavasqlsqlexception no suitable driver found for jdbcmysqllocalhost3306aavikme at javasqldrivermanagergetconnectiondrivermanagerjava596 at javasqldrivermanagergetconnectiondrivermanagerjava215 at mysqlconnectexamplemainmysqlconnectexamplejava20what am i doing wrong,"['java', 'mysql', 'sql']" +653134,django settings per application best practice this is somewhat related to this questionwhy is djangos settings object a lazyobjectin my django project i have several applications each application can have its own nontrivial settings fileproj proj settingspy app settingspy viewspywhat is the general best practice hereshould appsettingspy do from djangoconf import settingsapp setting lambda settingsgetattrapp setting custom valueproj setting lambda settingsproj settingand then in appviewspy doimport settings x settingsapp settingy settingsproj settingor should i be modifying the django lazy settings object in appsettingspy as per the django coding stylefrom djangoconf import settings not even sure how i would check for a default value that was specified in projsettingspysettingsconfigureapp settingcustom valueand then each appviewspy just consumes projsettingspy via djangoconf settingsfrom djangoconf import settingsx settingsapp settingy settingsproj settingthere are obviously quite a few other permutations but i think my intent is clearthanks in advance,['python'] +653180,get exact html with closing tag for which starting tag is missing currently for a body with html hellodivphaipspanwelcomespan on alerting bodyhtml it alerts hellophaipspanwelcomespanfiddlebut i want it to thisplay hellodivphaipspanwelcomespan ie alert html as it is written within the bodyi can see the exact code when i view the sourcecode of the pagei really dont know if clientside scripts are capable of thisplaying the output i askedis it possible and if yes how,"['javascript', 'jquery', 'html']" +653205,can you blur the content beneathbehind a div i am creating a new web design in photoshop at the moment but i would like to know if it is possible to blur the content beneath a divi would like to create a half transparent nav bar on my page that is fixed at the top of your screen everything that flows beneathbehind i want to have blurred for those of you that have an idevice with ios 7 check out safaris header where the page beneath the header is blurred that is the effect what i am looking fori wouldnt mind the effect not working on older browsers ie8 etc which in that case will have a 05 opacity white background as fallbackif this is possible i am really looking for the necessary code,['css'] +653291,how to sort a hashset for lists we use the collectionssortlist method what if we want to sort a hashset,['java'] +653297,importerror no module named pip when trying to install packages have a fresh install of ubuntu 1310 with pycharm and when setting up the python interpreter i selected install setuptools then install pip now if i try and do anything with pip i get the following ciaranciarandesktoppycharmbin pip traceback most recent call last file usrlocalbinpip line 9 in module load entry pointpip141 console scripts pip file buildbthistlinuxx86 64eggpkg resourcespy line 357 in load entry point does the packages thistribution contain the named metadata file buildbthistlinuxx86 64eggpkg resourcespy line 2394 in load entry point file buildbthistlinuxx86 64eggpkg resourcespy line 2108 in load importerror no module named pipi have tried on python 275 and 332 and both yield the same resultsedit the above output is from the terminal pycharm outputs the followingerror python package management tool pip not found,['python'] +653317,change jdk path in intellij 13 when compiling from 32 bit program file folder to 64 bit one i am getting this issue when trying to make my java project i just uninstalled my 64 bit jdk for various reasons and installed the 32 bit one i am getting the errorcannot run program cprogram filesjavajdk170 51binjava in directory cusersusernameintellijidea13systemcompileserver createprocess error2 the system cannot find the file specifiedhow do i get the compiler to use the jdk in the cprogram files x86 folder which i now have,['java'] +653481,difference between screen size and screen density in android i have a few questionswhat is the screen size what is the screen densitywhat is a difference between screen size and screen densityhow i can support different densities and different screen sizes in androidi have already read the official documentation but i was unable to understand the difference between screen size and screen density,['android'] +653625,will or what kind of support does mapbox have for vector tiles i read mapbox and vector tiles and am wondering if i understand this rightin some future it will be possible to render vector based tiles with ios mapbox if yes how would the rmtilesource for vector tiles look likein laymans terms do i understand this right i will be able to use a svg or even pdf files as the data source for mapbox instead of png tilesif yes is there any code out yet that i can experiment with,['ios'] +653680,could not load file or assembly systemnethttpformatting or one of its dependencies the system cannot find the path specified please help anyonei have a small mvc app that i use for practice reasons but now i have encountered an error everytime i try to debugcould not load file or assembly systemnethttpformatting or one of its dependencies the system cannot find the path specifiedi have googled all possible issuesi am using net 45it cannot be dll file because i am using net 45thank you in advance,"['c#', 'asp.net', '.net']" +653685,google maps does not update tiles while dragging i have to use the google maps javascript api in a webview the problem is that while dragging the map the missing tiles would not be loaded in a browser on my desktop pc i cannot get the same behaviour but loading the tiles while dragging the map around in the picture i hold the map and nothing happens till i release my fingeri have found an issue not perfectly fitting on my problem but kinda close in the gmaps bugtracker and tried all the solutions mentionedthis is what i have tried so far setting the maps div container to a fixed sizemapcanvas height 600px width 600px emit resize trigger on mouse movedocumentreadyfunction mapcanvasmousemovefunction event settimeoutfunction googlemapseventtriggermapresize mapsetzoommapgetzoom 100 loading google maps api after document has been loadedfunction loadscript var script documentcreateelementscript scripttype textjavascript scriptsrc sensorfalse callbackinitialize documentbodyappendchildscriptwindowonload loadscriptthe code is working and the mousemove event gets fired i am using androidminsdkversion19 on my nexus 10 device,['javascript'] +653691,fortran cython workflow i would like to set up a workflow to reach fortran routines from python using cython on a windows machine after some searching i found and and some code picesfortran sidepygfunchvoid c gfuncdouble x int n int m double a double b double cpygfuncf90module gfunc1 interface use iso c binding use gfunc module implicit nonecontains subroutine c gfuncx n m a b c bindc realc float intentin value x integerc int intentin value n m typec ptr intentin value a b typec ptr value c realc float dimension pointer fa fb realc float dimension pointer fc call c f pointera fa and call c f pointerb fb m call c f pointerc fc n m call gfuncx fa fb fc end subroutineend modulegfuncf90module gfunc moduleuse iso c binding implicit none contains subroutine gfuncx a b c real intentin x real dimension intentin a b real dimension intentout c integer i j n m and sizea m sizeb do j1m do i1n cij expx ai2 bj2 end do end do end subroutineend modulecython sidepygfuncpyxcimport numpy as cnpimport numpy as npcdef extern from pygfunch void c gfuncdouble int int double double double cdef extern from pygfunch passdef ffloat x a100 b100 n100 cdef cnpndarray ax c ax nparangea b bafloatn and axshape0 c npndarraynn dtypenpfloat64 orderf c gfuncx n n double axdata double axdata double cdata return cand the setup filefrom thistutilscore import setupfrom thistutilsextension import extensionfrom cythonthistutils import build extimport numpy as npext modules extensionpygfunc pygfuncpyxsetup name pygfunc include dirs npget include cmdclass build ext build ext ext modules ext modules all the files ar in one directorythe fortran files compile using nag fortran builder pygfunc compilesbut linking them throws aerror lnk2019 unresolved external symbol c gfunc referenced in function pyx pf 7pygfunc f and of coursefatal error lnk1120 1 unresolved externals what am i missing or is this way to set up a workflow between python and fortran damned from the beginning thxmartin,['python'] +653704,clarification of char pointers in c i am working through kr second edition chapter 5on page 87 pointers to character arrays are introduced aschar pmessagepmessage now is the timehow does one know that pmessage is a pointer to a character array and not a pointer to a single characterto expand on page 94 the following function is defined month name return the name of the nth month char month nameint n static char name illegal month january february march return n 1 and 12 name0 namenif one were simply provided with the function declaration for the above how could one know whether a single character or a character array is returnedif one were to assume the return from month name is a character array and iterate over it until a null is encountered but the return was in fact a single character then is there not the potential for a segmentation faultcould somebody please demonstrate the declaration and assignment of a pointer to a single character vs a character array their usage with functions and identification of which has been returned,['c'] +653761,requesting elasticsearch from node times out i am setting up a simple nodejs rest service to interface with elasticsearch using the official javascript client i am running this code locally but the cluster is located remotely when i go trough the browser with the head plugin i can connect es and query with no problem however doing so via the javascript client times out all requests i set up the elasticsearch object but sending any request to it simply does not work i do not think it is a network issue because i can access es trough the browser this is how i request something a very basic getvar elasticsearch requireelasticsearchvar es new elasticsearchclient host httpsmyaddress9200 also tried without protocol part and trailing slashes log error sniffonstart trueesget index things type something id 42thendosomestuff handlestufailedthis fails with a simple error message eror request timeout after 30msam i missing something here i have read trough the client docs and this seems like the basic hello world for the client,['javascript'] +653800,how to check if class exists within a namespace i have got this use xdriverdrivervar dumpclass existsdriver false driver new driver prints 123123123 since i put an echo in the constructor of this class exitwell this behaviour is quite irrational creating objects of classes that according to php do not exist is there any way to check if a class exist under given namespace,['php'] +653884,flock vs lockf on linux if lockf is used with a 0 offset what are differences between flock and lockf when used in exclusive mode if anyi am asking because i am reading code that conditionally compiles in either of these 2 functions based on platform and i want to understand possible reasons why,['c'] +653902,how to allow user to select empty string on select2 the texbox is dynamically filled with a remote call using select2 and i want to allow users to leave the field blank e6select2 placeholder search for a movie minimuminputlength 1 ajax url datatype jsonp data function term page return q term search term page limit 10 results function data page return results datamovies here is working example,['jquery'] +653987,cannot install python mysql library on mac mavericks it was working like a charm before the update from mountain lionafter the update it is broken and i cannot get the environment up againdoes anybody know how to fix thisthe error is bolded belowfedoriusthis pip install mysqlpythondownloadingunpacking mysqlpython downloading mysqlpython125zip 108kb 108kb downloaded running setuppy pathprivatevarfolders21zjvwzn891jnf4rnp526y1320gntpip build fedoriusmysqlpythonsetuppy egg info for package mysqlpythoninstalling collected packages mysqlpython running setuppy install for mysqlpython building mysql extension cc fnostrictaliasing fnocommon dynamic g os pipe fnocommon fnostrictaliasing fwrapv mnofusedmadd denable dtrace dmacosx dndebug wall wstrictprototypes wshorten64to32 dndebug g fwrapv os wall wstrictprototypes denable dtrace pipe dversion info125final1 d version 125 iusrlocalmysqlinclude isystemlibraryframeworkspythonframeworkversions27includepython27 c mysqlc o buildtempmacosx109intel27 mysqlo os g fnostrictaliasing arch x86 64 clang error unknown argument mnofusedmadd wunusedcommandlineargumentharderrorinfuture clang note this will be a hard error cannot be downgraded to a warning in the future error command cc failed with exit status 1 complete output from command usrbinpython c import setuptools tokenize file privatevarfolders21zjvwzn891jnf4rnp526y1320gntpip build fedoriusmysqlpythonsetuppyexeccompilegetattrtokenize open open file readreplacern n file exec install record varfolders21zjvwzn891jnf4rnp526y1320gntpip yi6syrecordinstallrecordtxt singleversionexternallymanaged compile running installrunning buildrunning build pycreating buildcreating buildlibmacosx109intel27copying mysql exceptionspy buildlibmacosx109intel27creating buildlibmacosx109intel27mysqldbcopying mysqldb init py buildlibmacosx109intel27mysqldbcopying mysqldbconverterspy buildlibmacosx109intel27mysqldbcopying mysqldbconnectionspy buildlibmacosx109intel27mysqldbcopying mysqldbcursorspy buildlibmacosx109intel27mysqldbcopying mysqldbreleasepy buildlibmacosx109intel27mysqldbcopying mysqldbtimespy buildlibmacosx109intel27mysqldbcreating buildlibmacosx109intel27mysqldbconstantscopying mysqldbconstants init py buildlibmacosx109intel27mysqldbconstantscopying mysqldbconstantscrpy buildlibmacosx109intel27mysqldbconstantscopying mysqldbconstantsfield typepy buildlibmacosx109intel27mysqldbconstantscopying mysqldbconstantserpy buildlibmacosx109intel27mysqldbconstantscopying mysqldbconstantsflagpy buildlibmacosx109intel27mysqldbconstantscopying mysqldbconstantsrefreshpy buildlibmacosx109intel27mysqldbconstantscopying mysqldbconstantsclientpy buildlibmacosx109intel27mysqldbconstantsrunning build extbuilding mysql extensioncreating buildtempmacosx109intel27cc fnostrictaliasing fnocommon dynamic g os pipe fnocommon fnostrictaliasing fwrapv mnofusedmadd denable dtrace dmacosx dndebug wall wstrictprototypes wshorten64to32 dndebug g fwrapv os wall wstrictprototypes denable dtrace pipe dversion info125final1 d version 125 iusrlocalmysqlinclude isystemlibraryframeworkspythonframeworkversions27includepython27 c mysqlc o buildtempmacosx109intel27 mysqlo os g fnostrictaliasing arch x86 64clang error unknown argument mnofusedmadd wunusedcommandlineargumentharderrorinfutureclang note this will be a hard error cannot be downgraded to a warning in the futureerror command cc failed with exit status 1cleaning upcommand usrbinpython c import setuptools tokenize file privatevarfolders21zjvwzn891jnf4rnp526y1320gntpip build fedoriusmysqlpythonsetuppyexeccompilegetattrtokenize open open file readreplacern n file exec install record varfolders21zjvwzn891jnf4rnp526y1320gntpip yi6syrecordinstallrecordtxt singleversionexternallymanaged compile failed with error code 1 in privatevarfolders21zjvwzn891jnf4rnp526y1320gntpip build fedoriusmysqlpythonstoring debug log for failure in varfolders21zjvwzn891jnf4rnp526y1320gnttmp5qbn55updateas suggested i have addedexport cflagsqunusedargumentsexport cppflagsqunusedargumentsbut it changed the error toerror librarypython27sitepackages mysqlso permission deniedi just chmoded this directory to allow writing and it worked this is due to mixing macports easy install and pip shame on me,['python'] +654094,blade template vs plain php in laravel as i understand blade is simply regex parser which will translate any blade construction into php code and then generate plain html from that php seems like this process makes loading files with blade templates slower because of the extra step blade php if so why do i want to use blade at all just because of the elegant syntax or because blade files are stored in cache,['php'] +654104,subprocesspopen stdin read file i am trying to call a process on a file after part of it has been read for examplewith openintxt r as a openouttxt w as b header areadline subprocesscallsort stdina stdoutbthis works fine if i do not read anything from a before doing the subprocesscall but if i read anything from it the subprocess does not see anything this is using python 273 i cannot find anything in the documentation that explains this behaviour and a very brief glance at the subprocess source did not reveal a cause,['python'] +654139,ios push notification not showing up in app i am trying to setup push notifications in my ios7 app and am running into issuesbasically the push never shows up i wen through the process of creating the certificates and the provsioning profiles currently i only have it built for development and will get the thistribution one made up when i am ready to submit it but in the development setup everything appears to be correct i made a php file to create the message in dictionary format and i believe everything is correct on that side of things the passthru code is addedd correctly and i connect to the apns server correctly the development side i can tell this because when i make my pass code incorrect it does failfrom going through the ios development documents related to push i added a persistantconnection profile onto my phone and view the detailed log files and according to that data it should also be workingi am not totally familiar with reading this data but the good things i was told to look for were there and the bad things were noti will attach my php script and the log from the devicephp script session startif postmessagedevicetoken arraydevicetoken0x3ee0 3x973 6bxea 2843x dx5xbx1x x4x8x0xe 7xx65xx9 x61xx01xpayload aps alert postmessage badge 1 sound bingbongaiff payload aps alert alert sound default message postmessage id 1234apnshost gatewaysandboxpushapplecomapnsport 2195apnscert ckpemstreamcontext stream context createstream context set optionstreamcontext ssl local cert apnscertstream context set optionstreamcontext ssl passphrase xoxoxoxoapns stream socket clientssl apnshost apnsport error errorstring 2 stream client connect streamcontextifapns printstream failed to create error errorstring return else printmessage sentforeachdevicetoken as keyvalue apnsmessage chr0 packn32 packhstr replace value pack n strlenpayload payload apnsmessage chr0 chr0 chr32 packh str replace value chr0 chrstrlenpayload payload fwriteapns apnsmessage print brmessage delivered payloadfcloseapnsform actionblanketphp methodpostinput typetext placeholdermessage namemessageinput typesubmit valuesubmitformaccording to the doc this is what i am looking fori see thislook for messages from the apsd process ideally youll see connected to courier xcouriersandboxpushapplecom where x is a small integer that indicates that the device has successfully established its persistent connection to the push servicei do not see thisyou might on the other hand see thisconnecting in response to connection failure that means that the persistent connection failed in that case the goal is to figure out whats going on with your network that is causing the connection failure check that no firewalls are blocking tcp traffic on port 5223i do not see thisthe message connection set ignored topics means that the user chose to turn off notifications for the apps listed in the message that will be followed by sending filter message for enabled hashes which is where ios actually sends the enabled and ignored topics to apnsi do not see thisthe message failed to parse json message payload indicates that the json dictionary in the notification payload is not in valid json formatthe bad part is i also do not see thisthe message received message for enabled topic means that the device received a notification from the push servicedata from log search for this criteria connected to couriershowing good info20140314 145654 0700 apsd83 apscourier 0x16e49ff0 attempting to connectstream currently oninterface wwan consecutivefailures 0 preference noncellular shouldusedualchannel yes connected on 1 interfaces20140314 145654 0700 apsd83 apscourier 0x16d78f70 attempting to connectstream currently oninterface wwan consecutivefailures 0 preference noncellular shouldusedualchannel yes connected on 1 interfaces20140314 145654 0700 apsd83 apscourier 0x16d78f70 connected to courier 2couriersandboxpushapplecom 1714934142 connection apscourierconnection 0x16d79810 oninterface noncellular20140314 145654 0700 apsd83 apscourier 0x16e49ff0 connected to courier 30courierpushapplecom 1714936134 connection apscourierconnection 0x16d4a380 oninterface noncellular20140314 145655 0700 apsd83 apscourier 0x16d78f70 calling into awd for pushconnectionconnected20140314 145655 0700 apsd83 apscourier 0x16e49ff0 calling into awd for pushconnectionconnected20140314 145752 0700 apsd83 apscourier 0x16d78f70 systemdidlock and were connected via noncellular sending inactive ping to the server20140314 145752 0700 apsd83 apscourier 0x16e49ff0 systemdidlock and were connected via noncellular sending inactive ping to the server20140314 145757 0700 apsd83 apscourierconnection 0x16d4a380 wwan is connected to be consistent closing the noncellular connection20140314 145757 0700 apsd83 apscourier 0x16e49ff0 courierconnection apscourierconnection 0x16d4a380 asked us to thisconnect stream on interface noncellular connected on 2 interfaces20140314 145757 0700 apsd83 apscourier 0x16e49ff0 calling into awd for connectionthisconnected20140314 145757 0700 apsd83 apscourier 0x16e49ff0 courierconnection apscourierconnection 0x16d4a380 asked us to thisconnect stream on interface noncellular connected on 1 interfaces20140314 145757 0700 apsd83 apscourier 0x16e49ff0 calling into awd for connectionthisconnected20140314 145757 0700 apsd83 apscourier 0x16e49ff0 attempting to connectstream currently oninterface wwan consecutivefailures 0 preference none shouldusedualchannel no connected on 1 interfaces20140314 145757 0700 apsd83 apscourier 0x16e49ff0 connectstream caller is ensuring that we are connected we are so there is nothing to do here connected on 1 interfaces20140314 145757 0700 apsd83 apscourierconnection 0x16d79810 wwan is connected to be consistent closing the noncellular connection20140314 145757 0700 apsd83 apscourier 0x16d78f70 courierconnection apscourierconnection 0x16d79810 asked us to thisconnect stream on interface noncellular connected on 2 interfaces20140314 145757 0700 apsd83 apscourier 0x16d78f70 calling into awd for connectionthisconnected20140314 145757 0700 apsd83 apscourier 0x16d78f70 courierconnection apscourierconnection 0x16d79810 asked us to thisconnect stream on interface noncellular connected on 1 interfaces20140314 145757 0700 apsd83 apscourier 0x16d78f70 calling into awd for connectionthisconnected20140314 145757 0700 apsd83 apscourier 0x16d78f70 attempting to connectstream currently oninterface wwan consecutivefailures 0 preference none shouldusedualchannel no connected on 1 interfaces20140314 145757 0700 apsd83 apscourier 0x16d78f70 connectstream caller is ensuring that we are connected we are so there is nothing to do here connected on 1 interfacesas far as i can tell it should be working but it is not any ideas,"['php', 'ios', 'iphone']" +654186,django and mysql problems on mavericks i am running mac osx 109 mavericks i am trying to run django under python 3 because i am running python 3 i have to get the official connector from the mysql devs here gave it a quick test in the shell and it worksi ran python managepy runserver with mysqlconnectordjango as the engine having seen an example here and i got this errordjangocoreexceptionsimproperlyconfigured mysqlconnectordjango is not an available database backendtry using djangodbbackendsx where x is one ofumysql uoracle upostgresql psycopg2 usqlite3error was no module named mysqlconnectordjangobaseso i switch back to the default using djangodbbackendsmysql as my engine and i get this errordjangocoreexceptionsimproperlyconfigured error loading mysqldb module no module named mysqldbi have no idea how to proceed i cannot install mysqldb because i am running my django install under python3 and it is unsupported but i am definitely missing something with this connector,"['python', 'mysql']" +654202,c error expected expression before int when i tried the following code i get the error mentionedifa1 int b 10but the following is syntactically correctifa1 int b 10why is this,['c'] +654262,apply black and white filter to uiimage i need to apply black and white filter on uiimage i have a view when there appear a photo taked by the user but i do not have any ideas for transform the colors of image voidviewdidload super viewdidload selfnavigationitemtitle nslocalizedstringpaint nil imageviewimage image,['objective-c'] +654417,google play services bug report where can i submit a bug report for google play services i tried to search but i did not find anything specific the only site i found is official android tracker but it does not seem to be the right place,['android'] +654423,remove internalsvisibleto for production is it possible to thisable internalsvisibleto for production acceptance testingwhilst i would like to be able to poke internals at design time i do not really want these exposed at higher level testing,"['c#', '.net']" +654438,javascript underscore array to object is there an easyclean way using underscore to turn this id medium votes 7 id low votes 9 id high votes 5 into low 9 medium 7 high 5,['javascript'] +654449,lambda capture parameter provoking ambiguity i just bumped into a really strange c behavior and iad be glad if someone could explain it to mesay i have the following classclass program static int len 1 static void mainstring args funcdouble double call len 1 len 1 error len conflicts with the declaration csutilsprogramlen programlen 1 ok as i get it in the line of commentary i have the following objects in my field of view len variable and callinside of lambda i have local parameter len and programlen variablehowever after declaring such lambda i cannot use len variable in the scope of main method anymore i have to either refer to it as to programlen either rewrite lambda to be anyothernamebesideslen 1why is it happening is this correct behavior of language or iave encountered a bug in the language if this is correct behavior how is it justified by the language architecture why is it okay for lambda capture variable to mess with code outside lambdaeditalessandro dandria has got quite nice examples number 1 and 2 in his commentedit2this code equal to the one i wrote at the beginning is illegalclass program static int len 0 static void mainstring args int len 1 int x len this code however despite having exactly the same scope structure is perfectly legalclass other static int len 0 class nested static void foo int len 1 static int x len,['c#'] +654677,google drive picker developer key is invalid error i started to learn google drive picker api and started with my localhost i have created my client id and browser key for the domain httplocalhost and my files locations are localhostch1html etc heres the script i wrote in the body part of my documentscript typetextjavascript srcscriptscript function onapiload gapiloadauthcallbackonauthapiload gapiloadpicker function onauthapiload windowgapiauthauthorize client id545195528713tihc7u0hp9ihta5mrm4l0eon16fpjogiappsgoogleusercontentcom scope handleauthresult var oauthtoken function handleauthresultauthresult ifauthresult authresulterror oauthtoken authresultaccess token createpicker function createpicker var picker new googlepickerpickerbuilder addviewnew googlepickerdocsuploadview addviewnew googlepickerdocsview setoauthtokenoauthtoken setdeveloperkeyaizasyb3i3joepscrzgysa9tbwl9pxaualjnfg build pickersetvisibletrue scriptbut when i run the doc it shows nothing is it like i cannot use the drive api on localhost or i will have to use some button to call it or something like that please helptested example doctype htmlhtml xmlns head meta httpequivcontenttype contenttexthtml charsetutf8 titlegoogle picker exampletitle script typetextjavascript srcscriptscript function onapiload gapiloadauthcallbackonauthapiload gapiloadpicker function onauthapiload windowgapiauthauthorize client id545195528713tihc7u0hp9ihta5mrm4l0eon16fpjogiappsgoogleusercontentcom scope handleauthresult var oauthtoken function handleauthresultauthresult ifauthresult authresulterror oauthtoken authresultaccess token createpicker function createpicker var picker new googlepickerpickerbuilder addviewnew googlepickerdocsuploadview addviewnew googlepickerdocsview setoauthtokenoauthtoken setdeveloperkeyaizasyc4n7lg1vn6yrxcd5ddt iu0gxsf3qgfdu setcallbackpickercallback build pickersetvisibletrue function pickercallbackdata var url nothing if datagooglepickerresponseaction googlepickeractionpicked var doc datagooglepickerresponsedocuments0 url docgooglepickerdocumenturl var message you picked url documentgetelementbyidresultinnerhtml message script head body div idresultdiv script typetextjavascript srcscript bodyhtml,['javascript'] +654872,coffeescript inline call delegation which works with function bindings i have following cs code snippetclass ctrl constructor security isauthenticated securityisauthenticatedwhich is translated to following jsctrl function function ctrlsecurity thissecurity security ctrlprototypeisauthenticated function return thissecurityisauthenticated as you can see isauthenticated is a simple delegation to security objects method and creating anonymous function is redundanti want to avoid creating this additional call level and instead perform kind of inline delegation which would translate to js similar toctrl function function ctrlsecurity thissecurity security ctrlprototypeisauthenticated thissecurityisauthenticatedfollowing does not work since it tries to bind security to wrong objectclass ctrl constructor security isauthenticated securityisauthenticatedany clues,['javascript'] +654970,d3js why mouseover and mouse out fired for each child elements i use d3js to generate a svg circle with a text logo in mid of the circlehere is the svg resultg idmain circle r114 fillf0e8d0circle text textanchormiddlethe movie titletextghere is the d3jsvar circles r innerradiussvgappendgattridmainsvgselectmainselectallcircledatacirclesenterappendcircleattrrfunctiondreturn drattrfillf0e8d0svgselectmainappendtextattrtextanchor middletextfunction return the movie titlei also want to fire some animations when mouse hover and leave the circle svgselectmainonmouseoverfunction code for transitiononmouseoutfunction code for transitionso the problem is when mouse moves into the circle the animation fires as expected however when mouse touches the text element a mouseout event fires mouse leaving the circle followed by a mouseover event again mouse entering the text element which is not desirable it seems that the animation callbacks will be called when mouse touches any child element of the g tagi do not want any animation happen when mouse touches the text element how can i do it,['javascript'] +654981,drawing circle with opengl i am trying to draw simple circle with copenglmy code isinclude glgluthinclude mathhvoid draw glcleargl color buffer bit glcolor3f10 10 10 glbegingl quads glcolor3f 00 00 00 glvertex3f 01 01 00 glvertex3f 09 01 00 glvertex3f 09 09 00 glvertex3f 01 09 00 glend glflushvoid drawcirclefloat cx float cy float r int num segments glbegingl line loop forint ii 0 ii num segments ii float theta 20f 31415926f floatii floatnum segmentsget the current angle float x r cosfthetacalculate the x component float y r sinfthetacalculate the y component glvertex2fx cx y cyoutput vertex glendvoid initialize glclearcolor10 10 10 00 glmatrixmodegl projection glloadidentity glortho00 10 00 10 10 10int mainint iargc char cppargv glutinitiargc cppargv glutinitthisplaymodeglut single glut rgb glutinitwindowsize950 500 glutinitwindowposition200 200 glutcreatewindowuniversum initialize glutthisplayfuncdraw glcleargl color buffer bit glcolor3f10 10 10 drawcircle05 05 02 5 glutmainloop return 0i am beginner with opengl and now i am starting to learn can someone please explain me why i do not get the circle i only see the black box thanks,['c++'] +655016,adhoc app always fails to install so i having problems installing an adhoc thistribution app on an ipad 1 with ios 5 i do not have this problem when installing in other ipads here the console log after failing installationmar 16 190958 ipad springboard635 killing commyappipad for app installationmar 16 191003 ipad reportcrash743 formulating crash report for process installd739mar 16 191003 ipad comappleitunesstored736 receive message failure running async function 1mar 16 191003 ipad comappleitunesstored736 call and response could not receive response from proxymar 16 191003 ipad comappleitunesstored736 mobileinstallationinstall failed with 1mar 16 191004 ipad reportcrash743 saved crashreport to varmobilelibrarylogscrashreporterinstalld 20140316191003 ipadplist using uid 0 gid 0 synthetic euid 501 egid 0mar 16 191004 ipad comapplelaunchd1 comapplemobileinstalld739 comapplemobileinstalld job appears to have crashed segmentation fault 11,['ios'] +655121,javascript in operator for undefined elements in arrays please consider the following snippet of code a 1 undefined undefined undefined 3 1 undefined undefined undefined 3 b 13 1 undefined a 3 3 1 in a true 1 in b falseam i missing something it seems to be that depending on how i define undefined elements in an array the in operator behaves differently,['javascript'] +655124,does imageviewsetimagebitmap recycle the previously set bitmap let us say i have code sort of like the one belowprotected void oncreatebundle bundle thisimageview imageview contentviewfindviewbyidridimageview thissetfirstbitmap thissetsecondbitmapprivate setfirstbitmap bitmap bitmap1 bitmapfactorydecodefilebitmapfile1 imageviewsetimagebitmapbitmap1private setsecondbitmap bitmap bitmap2 bitmapfactorydecodefilebitmapfile2 imageviewsetimagebitmapbitmap2in this case will the imageview recycle bitmap1 or do i have to do it before i set bitmap2,['android'] +655260,terminating a java program i found out ways to terminate shutdown or stop my java programs i found two solutions for itusing returnwhen i want to quit or terminate my program execution i add thisusing systemexit sometimes i used it i read about sytemexit from this questionso i know a little on both them but i am still confused as to how they actually work please check below codespublic class testing public static void mainstring str systemoutprintln1 systemexit0 systemoutprintln2 return i am sure that 2 will not appear i would like to know is why return or other codes can write below the statement of systemexit0 and what was real definition for return because it is strange thing for me return without any variables or values,['java'] +655271,what is the best way to do split in javascript and ignore blank entries i have the following c code that i need to convert to javascript static private string parsesemicolonstring fullstring if stringisnulloremptyfullstring return new string if fullstringindexof 1 return fullstringsplitnew stringsplitoptionsremoveemptyentriesselectstr strtrimtoarray else return new fullstringtrim i see that javascript has a split function as well but i wanted to see if there is built in support for the other checks or i have to do an additional loop around the array afterwards to clean up the data,"['c#', 'javascript', 'jquery']" +655280,why are we not to throw these exceptions i came across this msdn page that statesdo not throw systemexception systemsystemexception systemnullreferenceexception or systemindexoutofrangeexception intentionally from your own source codeunfortunately it does not bother to explain why i can guess at the reasons but i hope that someone more authoritative on the subject might offer their insightthe first two make some obvious sense but the latter two seem like ones you would want to employ and in fact i havefurther are these the only exceptions one should avoid if there are others what are they and why should they too be avoided,['c#'] +655431,assert two different types of enumerations are equivalent i have an nunit unit test which i have two collections of different types which i want to assert are equivalentclass a public int x class b public string y testpublic void myunittest var a getabunchofas returns ienumerablea var b getabunchofbs returns ienumerableb assertisprettysimilara b arga argb argatostring argbwhere assertisprettysimilar is defined like suchpublic static void isprettysimilart1 t2 ienumerablet1 left ienumerablet2 right funct1 t2 bool predicate using var leftenumerator leftgetenumerator using var rightenumerator rightgetenumerator while true var leftmoved leftenumeratormovenext if leftmoved rightenumeratormovenext assertfailenumerators not of equal size if leftmoved break var ismatch predicateleftenumeratorcurrent rightenumeratorcurrent assertistrueismatch my question is is there a more idiomatic way of doing the above with the existing methods in nunit i already looked at collectionassert and there is nothing matching what i want to domy description of equivalent in this case is1 collections must be of same size2 collections must be in same logical order3 some predicate must be used to determine equivalence between matching items,"['c#', '.net']" +655517,genymotion will not load a virtual device i have been using genymotion for about 4months now and all was well until i updated virtual box to 43 i did not like it because i didnt know how to run 64 bit oss on itso i downgraded to 42 now genymotion machines wont run at the end of every machine factorybackup is appended and this is the error i getfailed to open a session for the virtual machine galaxy s4 422 api 17 1080x1920failed to opencreate the internal network hostinterfacenetworkingvirtualbox hostonly ethernet adapter verr intnet flt if not foundfailed to attach the network lun verr intnet flt if not foundresult code e fail 0x804005component consoleinterface iconsole db7ab4ca2a3f41839243c1208da92392reinstalling genymotion or virtualbox yields no results i am also running vmware on my machine please help i use this for development purposes,['android'] +655563,android use camera without surfaceview or textureview i have been trying to figure out if there is a way to use camera to take either videopictures without defining surfaceview or textureview i found this link use android camera without surface viewi used this trick with textureview on my nexus tablet but no luck also says that this approach does not work on all the devices does anyone have any idea if there is a way to do it at all or its just something which android framework does not support at all and the gui has to have some surfacetexture element in layout then the only option is to just manipulate the layout so its not visible on the screen as per the app requirementsedit 1as explained in the above link i tried the below codepublic class cameracapture i pass the getapplicationcontext from the main activity public void startcameracapturecontext contx surfaceview sv new surfaceviewcontx mcamera cameraopen mcamerasetpreviewthisplaysvgetholder mcamerasetpreviewcallbacknew previewcallback override public void onpreviewframebyte data camera camera logvtag on preview frame called threadsleep10 mcamerastartpreviewhowever onpreviewframe never invoked am i missing somethingedit 2is it possible to do in native code capturing videousing camera without gui element surfaceviewtextureview using opencv i looked at this link binary packagedev with ocv on androidhtmlapplicationdevelopmentwithstaticinitialization however they also show the sample code with some camera view element defined in main layout xml file,['android'] +655653,do dictionaries have a key length limit i was wondering if python had a limit on the length of a dictionary keyfor clarification i am not talking about the number of keys but the length of each individual key i am going to be building my dictionaries based on dynamic values after validation but i am not sure if i should be taking length into account in this case,['python'] +655699,nsinvalidunarchiveoperationexception could not instantiate class named uitableviewcellseparatorview after xcode update 51 my app crashes when i try to run in ios 6xi have an app where i have a custom cell and contraints auto layout is unchecked for the xib file the error i get is terminating app due to uncaught exception nsinvalidunarchiveoperationexception reason could not instantiate class named uitableviewcellseparatorviewi only found one thread about this issue in other forum but without solution just a test that i have done too and got the same errorhelp,"['ios', 'objective-c']" +655752,symfony2 without doctrine how can i install symfony2 without doctrine i have tried removing the package using composer and uninstalling the bundle manually but i get errors alwaysmy application is going to get the data from a restful ws so i do not need doctrine at all,['php'] +655784,unexpected toplevel exception comandroiddexdexexception multiple dex files define i have a trouble trying use a google play services on my android app using android studio i have tried everything and still does not work this is the error execution failed for task appdexdebugcomandroididecommoninternalloggederrorexception failed to run command usersjghgdesktopmy appandroidsdkandroidsdkmac 86buildtools1901dx dex output usersjghgdesktopmy appeurekaudaappbuildlibsappdebugdex usersjghgdesktopmy appeurekaudaappbuildclassesdebug usersjghgdesktopmy appeurekaudaappbuilddependencycachedebug usersjghgdesktopmy appeurekaudaappbuildpredexeddebugclasses08979151dd1373bd3f799299d93376d22d4afa46jar usersjghgdesktopmy appeurekaudaappbuildpredexeddebugclasses167b9d3c5d689abe004c3fa5b0bcb945d3f0fc8ejar usersjghgdesktopmy appeurekaudaappbuildpredexeddebuggoogleplayservicesec20f8af7bb457c5095cae1afa0cee722582f198jar usersjghgdesktopmy appeurekaudaappbuildpredexeddebugsupportv41300473d85b8d55c88bfed3404072e6c132f96543429jar usersjghgdesktopmy appeurekaudaappbuildpredexeddebugsupportv41901861cc05365a0e9262c764da37d61e3f93dc16de6jar usersjghgdesktopmy appeurekaudaappbuildpredexeddebugsupportv41901dcc11377c764caea791f7123b8b678f876c3b6jar usersjghgdesktopmy appeurekaudaappbuildpredexeddebugtwitter4jasync3050904cb320186fb23a9a9bf25a048c5bc4ec07bc2jar usersjghgdesktopmy appeurekaudaappbuildpredexeddebugtwitter4jcore30541d2d5805e2d90cf77813a126306c4cbe22583aejar usersjghgdesktopmy appeurekaudaappbuildpredexeddebugtwitter4jexamples305adc1ee9b037c8061429560e6a5fe89ce8e502db6jar usersjghgdesktopmy appeurekaudaappbuildpredexeddebugtwitter4jmediasupport30537d138cdc631738d13ddb6f4d34c560a9cd8e048jar usersjghgdesktopmy appeurekaudaappbuildpredexeddebugtwitter4jstream305c96c138ea216b25631a1a8b47520ecaf33f288d8jar error code 2 output unexpected toplevel exception comandroiddexdexexception multiple dex files define lcomgoogleadsadrequesterrorcode at comandroiddxmergedexmergerreadsortabletypesdexmergerjava594 at comandroiddxmergedexmergergetsortedtypesdexmergerjava552 at comandroiddxmergedexmergermergeclassdefsdexmergerjava533 at comandroiddxmergedexmergermergedexesdexmergerjava170 at comandroiddxmergedexmergermergedexmergerjava188 at comandroiddxcommanddexermainmergelibrarydexbuffersmainjava439 at comandroiddxcommanddexermainrunmonodexmainjava287 at comandroiddxcommanddexermainrunmainjava230 at comandroiddxcommanddexermainmainmainjava199 at comandroiddxcommandmainmainmainjava103thanksbest regards,"['java', 'android']" +655811,junit no tests found i have inherited a java project and am new to java development i feel a good way for me to get comfortable with the code is to write some tests around it i am writing my code using intellijmy existing project has a folder structure like thismyproject src main java comlexcorp core email providers emailproviderjavai created a new project that will hold tests for this project i would like this project to hold both unit and integration tests currently my new project has a structure like thismyprojecttests src main java comlexcorpcoreemailproviders emailprovidertestjavathe emailprovidertestjava file looks like the followingpackage comlexcorpcoreemailprovidersimport junitframeworktestcaseimport orgjunittestpublic class emailprovidertest extends testcase private final string username testaccount private final string password testpassword test public void thisalwayspasses asserttruetrue this project has a rundebug configuration with the following propertiestest kind all in packagesearch for tests in whole projectwhen i run this configuration i get an error that saysjunitframeworkassertionfailederror no tests found in comlexcorpcoreemailprovidersemailprovidertest at orgjunitinternalrunnersjunit38classrunnerrunjunit38classrunnerjava84 at orgjunitrunnerssuiterunchildsuitejava127 at orgjunitrunnerssuiterunchildsuitejava26 at orgjunitrunnersparentrunner3runparentrunnerjava238 at orgjunitrunnersparentrunner1scheduleparentrunnerjava63 at orgjunitrunnersparentrunnerrunchildrenparentrunnerjava236 at orgjunitrunnersparentrunneraccess0parentrunnerjava53 at orgjunitrunnersparentrunner2evaluateparentrunnerjava229 at orgjunitrunnersparentrunnerrunparentrunnerjava309 at orgjunitrunnerjunitcorerunjunitcorejava160 at comintellijjunit4junit4ideatestrunnerstartrunnerwithargsjunit4ideatestrunnerjava74 at comintellijrtexecutionjunitjunitstarterpreparestreamsandstartjunitstarterjava202 at comintellijrtexecutionjunitjunitstartermainjunitstarterjava65 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava57 at comintellijrtexecutionapplicationappmainmainappmainjava120i do not understand why i am getting an error that boils down to no tests found while my project structures differ the folder structures on the os match which is another thing that confuses me why am i getting this error and how do i fix it thank you so much,['java'] +655832,how to get a javatime object from a javasqltimestamp without a jdbc 42 driver when retrieving a javasqltimestamp from a database via jdbc 41 or earlier how does one obtainconvert to a javatime objectneither of the opensource jdbc drivers for postgres is jdbc 42 compliant yet so i am looking for a way to use use javatime with jdbc 41,['java'] +655850,get list of pandas dataframe columns based on data type if i have a dataframe with the following columns 1 name object2 on time object3 on budget object4 actual hr float645 baseline start date datetime64ns6 forecast start date datetime64ns i would like to be able to say here is a dataframe give me a list of the columns which are of type object or of type datetimei have a function which converts numbers float64 to two decimal places and i would like to use this list of dataframe columns of a particular type and run it through this function to convert them all to 2dpmaybefor c in col list if cdtype somethinglistlistappendc,['python'] +655885,creating animation for images from small to large when scrolling vertical i am creating images in which when scrolled up the image should get enlarged and remaining images should get smaller similarly when second image pushed up it should enlarge and show i used accordion type but nothing works i searched but could not findin iphone it has features but i could not find how to create for android this is for same effect to be implemented in android i used scaleanimation with hide and show of layouts to open where image been placed inside the layout but that also did not workifopenlayout panel1 panel1startanimationnew scaleanimtohide10f 10f 10f 00f 200 panel1 truecan someone help me to solve this issuethanks in advance,['android'] +656051,are threads reliable enough to calculate seconds i am making an android app that at some activity shows a timer with hours minutes and seconds as seconds value will update every second i was thinking to make a thread with 10 ms sleep after each cycle it will add 1 to seconds and update the text view accordingly it will calculate minutes and hours and update the respective text viewsbut i have one doubt in mind are threads reliable enough to accomplish such a task or should i use inbuilt library function to get seconds after every cycle i am a little concerned about getting my timer getting out of sync if i rely completely on thread to calculate time,"['java', 'android']" +656129,ipython running commands asynchronously in the background say i have a python command or script that i want to run from ipython asynchronously in the background during an ipython session i would like to invoke this command from my ipython session and be notified when it is done or if something fails i do not want this command to block my ipython promptare there any ipython magics that support this if not what is the recommended way of running asynchronous jobsscriptscommands that run locally on ipythonfor example say i have a functiondef do something this will take a long time return donethat i have in the current namespace how i can i run it to the background and be notified when it is done,['python'] +656185,hibernate exception javassist 0 cannot be cast to javassistutilproxyproxy hello i am using developnig java web application and i am getting the next exception when i am trying to fetch data using hibernatejavalangclasscastexception comdigitalticketmodelusertype javassist 0 cannot be cast to javassistutilproxyproxyhere stacktracejavalangclasscastexception comdigitalticketmodelusertype javassist 0 cannot be cast to javassistutilproxyproxy at orghibernateproxypojojavassistjavassistlazyinitializergetproxyjavassistlazyinitializerjava147 at orghibernateproxypojojavassistjavassistproxyfactorygetproxyjavassistproxyfactoryjava75 at orghibernatetupleentityabstractentitytuplizercreateproxyabstractentitytuplizerjava771 at orghibernatepersisterentityabstractentitypersistercreateproxyabstractentitypersisterjava4613 at orghibernateeventinternaldefaultloadeventlistenercreateproxyifnecessarydefaultloadeventlistenerjava349 at orghibernateeventinternaldefaultloadeventlistenerproxyorloaddefaultloadeventlistenerjava270 at orghibernateeventinternaldefaultloadeventlisteneronloaddefaultloadeventlistenerjava150 at orghibernateinternalsessionimplfireloadsessionimpljava1070 at orghibernateinternalsessionimplinternalloadsessionimpljava989 at orghibernatetypeentitytyperesolveidentifierentitytypejava716 at orghibernatetypeentitytyperesolveentitytypejava502 at orghibernateengineinternaltwophaseloaddoinitializeentitytwophaseloadjava170 at orghibernateengineinternaltwophaseloadinitializeentitytwophaseloadjava144 at orghibernateloaderloaderinitializeentitiesandcollectionsloaderjava14 at orghibernateloaderloaderprocessresultsetloaderjava972 at orghibernateloaderloaderdoqueryloaderjava920 at orghibernateloaderloaderdoqueryandinitializenonlazycollectionsloaderjava354 at orghibernateloaderloaderdolistloaderjava2553 at orghibernateloaderloaderdolistloaderjava2539 at orghibernateloaderloaderlistignorequerycacheloaderjava2369 at orghibernateloaderloaderlistloaderjava2364 at orghibernateloadercriteriacriterialoaderlistcriterialoaderjava126 at orghibernateinternalsessionimpllistsessionimpljava1682 at orghibernateinternalcriteriaimpllistcriteriaimpljava380 at comdigitalticketmodeldaofetchalldaojava204 at comdigitalticketcontrollerindexcontrollerhandlerequestinternalindexcontrollerjava22 at orgspringframeworkwebservletmvcabstractcontrollerhandlerequestabstractcontrollerjava154 at orgspringframeworkwebservletmvcsimplecontrollerhandleradapterhandlesimplecontrollerhandleradapterjava50 at orgspringframeworkwebservletthispatcherservletdothispatchthispatcherservletjava945 at orgspringframeworkwebservletthispatcherservletdoservicethispatcherservletjava876 at orgspringframeworkwebservletframeworkservletprocessrequestframeworkservletjava961 at orgspringframeworkwebservletframeworkservletdogetframeworkservletjava852 at javaxservlethttphttpservletservicehttpservletjava731 at orgspringframeworkwebservletframeworkservletserviceframeworkservletjava837 at javaxservlethttphttpservletservicehttpservletjava844 at weblogicservletinternalstubsecurityhelperservletserviceactionrunstubsecurityhelperjava280 at weblogicservletinternalstubsecurityhelperservletserviceactionrunstubsecurityhelperjava254 at weblogicservletinternalstubsecurityhelperinvokeservletstubsecurityhelperjava136 at weblogicservletinternalservletstubimplexecuteservletstubimpljava341 at weblogicservletinternalservletstubimplexecuteservletstubimpljava238 at weblogicservletinternalwebappservletcontextservletinvocationactionwraprunwebappservletcontextjava3363 at weblogicservletinternalwebappservletcontextservletinvocationactionrunwebappservletcontextjava3 at weblogicsecurityaclinternalauthenticatedsubjectdoasauthenticatedsubjectjava321 at weblogicsecurityservicesecuritymanagerrunassecuritymanagerjava120 at weblogicservletproviderwlssubjecthandlerunwlssubjecthandlejava57 at weblogicservletinternalwebappservletcontextdosecuredexecutewebappservletcontextjava20 at weblogicservletinternalwebappservletcontextsecuredexecutewebappservletcontextjava2146 at weblogicservletinternalwebappservletcontextexecutewebappservletcontextjava2124 at weblogicservletinternalservletrequestimplrunservletrequestimpljava1564 at weblogicservletprovidercontainersupportproviderimplwlsrequestexecutorruncontainersupportproviderimpljava254 at weblogicworkselftuningworkmanagerimplworkadapterimplrunselftuningworkmanagerimpljava550 at weblogicworkexecutethreadexecuteexecutethreadjava295 at weblogicworkexecutethreadrunexecutethreadjava254here my code public t fetchalltclasst classname session s sessionfactorygetcurrentsession sbegintransaction try listt results listt sessionfactorygetcurrentsession createcriteriaclassname list sgettransactioncommit return results catch nullpointerexception ex return null catch runtimeexception re sgettransactionrollback throw re finally here is my objects public class user implements javaioserializable private static final long serialversionuid 2383716625869790753l private long userid private usertype usertype private string email private string password private string name private string surname private string middlename private setticket tickets new hashsetticket0 private setorganization organizations new hashsetorganization0 public user public userlong userid string email string password string name string surname thisuserid userid thisemail email thispassword password thisname name thissurname surname public userlong userid usertype usertype string email string password string name string surname string middlename setticket tickets setorganization organizations thisuserid userid thisusertype usertype thisemail email thispassword password thisname name thissurname surname thismiddlename middlename thistickets tickets thisorganizations organizations public long getuserid return thisuserid public void setuseridlong userid thisuserid userid public usertype getusertype return thisusertype public void setusertypeusertype usertype thisusertype usertype public string getemail return thisemail public void setemailstring email thisemail email public string getpassword return thispassword public void setpasswordstring password thispassword password public string getname return thisname public void setnamestring name thisname name public string getsurname return thissurname public void setsurnamestring surname thissurname surname public string getmiddlename return thismiddlename public void setmiddlenamestring middlename thismiddlename middlename public setticket gettickets return thistickets public void setticketssetticket tickets thistickets tickets public setorganization getorganizations return thisorganizations public void setorganizationssetorganization organizations thisorganizations organizations public class usertype implements javaioserializable private static final long serialversionuid 206438165274679246l private long usertypecode private string usertypename private setuser users new hashsetuser0 public usertype public usertypelong usertypecode string usertypename thisusertypecode usertypecode thisusertypename usertypename public usertypelong usertypecode string usertypename setuser users thisusertypecode usertypecode thisusertypename usertypename thisusers users public long getusertypecode return thisusertypecode public void setusertypecodelong usertypecode thisusertypecode usertypecode public string getusertypename return thisusertypename public void setusertypenamestring usertypename thisusertypename usertypename public setuser getusers return thisusers public void setuserssetuser users thisusers users here is mappingsdoctype hibernatemapping public hibernatehibernate mapping dtd 30en generated mar 16 2014 103153 am by hibernate tools 400 hibernatemapping class namecomdigitalticketmodeluser tablequotuserquot id nameuserid typelong column nameuser id precision10 scale0 generator classassigned id manytoone classcomdigitalticketmodelusertype fetchselect nameusertype column nameuser type precision10 scale0 manytoone property generatednever lazyfalse nameemail typestring column length20 nameemail notnulltrue uniquetrue property property generatednever lazyfalse namepassword typestring column length32 namepassword notnulltrue property property generatednever lazyfalse namename typestring column length64 namename notnulltrue property property generatednever lazyfalse namesurname typestring column length64 namesurname notnulltrue property property generatednever lazyfalse namemiddlename typestring column length64 namemiddlename property set fetchselect inversetrue lazytrue nametickets sortunsorted tableticket key column nameuser precision10 scale0 key onetomany classcomdigitalticketmodelticket set set fetchselect lazytrue nameorganizations sortunsorted tableauditor key column nameuser notnulltrue precision9 scale0 key manytomany entitynamecomdigitalticketmodelorganization uniquefalse column nameorganization notnulltrue precision10 scale0 manytomany set classhibernatemappingxml version10doctype hibernatemapping public hibernatehibernate mapping dtd 30en generated mar 16 2014 103153 am by hibernate tools 400 hibernatemapping class namecomdigitalticketmodelusertype tableuser type id nameusertypecode typelong column nameuser type code precision10 scale0 generator classassigned id property nameusertypename typestring column nameuser type name length40 notnulltrue uniquetrue property set nameusers tableuser inversetrue lazytrue fetchselect key column nameuser type precision10 scale0 key onetomany classcomdigitalticketmodeluser set classhibernatemappingi am using oracle weblogic 12c server,['java'] +656208,universal accessors and mutators in laravel 4 i know it is possible to define accessors and mutators for individual fields like sopublic function setsomeattributevalue set the attributepublic function getsomeattribute return the attributebut is it possible to define a fallback method that will be used for all attribute gets and setsthe reason being that i want to convert any empty values to null values on the fly to keep my database clean and allow nullable fields to be null instead of an empty string if there is a better way to do this let me knowi am looking for something likepublic function setattributepropertyvalue thisproperty emptyvalue null valueupdatethanks to chris goosey i have found a solution that works for me i extended the eloquent model method setattribute and i set the value to the column default if it is empty that is usually null zero or an empty string in my databases so works for mepublic function setattributekey value convert empty values to their default values eg null zero ifemptyvalue thisgetschemahascolumnkey value thisgetschemagetcolumnkeygetdefault parentsetattributekeyvalue,['php'] +656274,activerecord finding all objects with shared attributes in a join model i have three modelsclass boat activerecordbase belongs to captain has many boat classifications has many classifications through boat classificationsendclass classification activerecordbase has many boat classifications has many boats through boat classificationsendclass boatclassification activerecordbase belongs to boat belongs to classificationendi am trying to write a simple activerecord query to find all the boats of type sailboat something like boatwhereclassifications sailboat,['ruby'] +656316,bootstrap alerterror does not work i am writing a webscript to handle vps creation and destruction on the admin page i use twitter bootstrap to show an alert for success and failure messages here lies the problem the alertsuccess div works but the alerterror does not i have most of my code minus the php script posted on a pastebin here i have some screenshots on how it looks for me on internet explorer 11 here please note that the alertsuccess area works i use a custom bootstrap to change the font but that is it i created it using the getbootstrapcom website so i doubt it is that,"['javascript', 'jquery', 'css']" +656368,can i get the default hint color of an edittext is there a way to get the hint color from an edittext i need the color to set it as the text color of the edittext too,['android'] +656478,my app icon appears smaller then other i used android asset studio to create launcher icon foregroundspacepad0forecolor33b5e52c0crop0backgroundshapebevelbackcolorf2c100the studio generated images at proper pixel sizes 48 48 mdpi 72 72 hdpi and so onbut on my samsung galaxy s2 the app icon appear smaller then other apps and not filling its entire spacewhay is this how can i stretch it to full extent,['android'] +656562,xcode 51 method search only allows one character i have recently upgraded to xcode 51 and i am experiencing the most annoying bug the instant search or method search dialog that allows you to search the methods on the given source file you are looking at is not allowing me to enter more than one character i have large source files and i tend to rely on that a lot any idea why this might be happening i have tried reinstalling xcode simply be dragging it in the trashyou can find the search field i am talking about by clicking the method as shown in the screenshot and simply typing somethingwhen i type the character gets replaced with the last letter entered,['ios'] +656632,laravel undefined method illuminatedatabasequerybuilderattach i am trying to associate related models during database seeding in laravel 4 according to the documentation here i can do it like thisuserrolesattach1so in my database seed i am runningpackage packagecreate name fakerword summary fakersentence base price fakerrandomfloat2 200 10 attach 15 randomly selected items to this packageforeachrange1 5 as index randomitem itemorderbydbrawrandfirst packageitemsattachrandomitemidthe packages items have already been seeded at this point and they seed without problems the above code gives this from artisan thoughbadmethodcallexception call to undefined method illuminatedatabasequerybuilderattachsomeone here seems to think that the attach method does not actually exist and the docs are wrong but i find that hard to believetldr what is the correct way to create manytomany relationships in eloquent,['php'] +656798,controller generate few threads although not asked for several days i just can not find the problem itself which is really driving me crazy i have aspnet mvc4 web application where there are several index pages showing list when clicking on any item in the list it returns edit view page in the edit page in the view itself there is a submit button which should update the db and redirect to the index page at first that submit was loaded with all html edit code via partial view but i changed it so i can redirect to index page because child actions are not allowed to perform redirect actionsso the problem is that controller does not redirect to the index pagewhen i put a breakpoint in the post function in controller i see that few threads runs the code although not asked for threads and if i stand with the cursor on one of the processes debug arrows i can see message the process or thread has changed since last stepsomehow i do not know how i solved the problem in one page dont know how because i dont know what caused this but sometimes randomly it is appears again and in the other page i did not manage to solve ithere is some code from controller and from viewcontrollerhttppostpublic actionresult editmodelbindertypeofopportunitybinder opportunitymodel draft try if requestparamscancel null return redirecttoactionindex utilscrmdbgetopportunities if draftisvalid if utilscrmdbupdateopportunitydraft return redirecttoactionindex utilscrmdbgetopportunities return viewdraft catch return view viewusing htmlbeginform htmlantiforgerytoken htmlvalidationsummarytrue fieldset some divs p input typesubmit valueupdate p fieldset fieldset some partial views loaded using htmlaction fieldsetsection scripts scriptsrenderbundlesjqueryval scriptsrenderbundlesmodernizr scriptsrenderbundlesjquery scriptsrenderbundlesjqueryuipartial view codemodel genius crmmodelsactivitylistmodelp button iddlgaddactivity new buttonpdiv table some tr and td tabledivscript typetextjavascript documentreadyfunction dlgaddactivityeachfunction var link this var pathname windowlocationpathname var parts pathnamesplit var sub parts3 var dialog div idadialogdiv loadurlactionaddactivitytoopartial opportunitycustidviewbagcustidoppidviewbagoppid dialog autoopen false title linkattrtitle width 758 height 265 resizable false close function event ui windowlocationreload linkclickfunction dialogdialogopen return false so i hope i have made my problem cleari have been through some posts on the subject and none of them helped me the problem appears also in chrome and in ie tooedit 1 when commenting out the partial views the problem thisappears in all pagesedit 2 seems that there is a problem with buttons loaded in partials which using other controller actionsedit 3 i have added code of partial view loaded with htmlaction which include one script for jqueryui dialog,['c#'] +656814,too many if statements the following code does work how i need it to but it is ugly excessive or a number of other things i have looked at formulas and attempted to write a few solutions but i end up with a similar amount of statementsis there a type of math formula that would benefit me in this instance or are 16 if statements acceptableto explain the code it is for a kind of simultaneousturnbased game two players have four action buttons each and the results come from an array 03 but the variables one two can be assigned anything if this helps the result is 0 neither win 1 p1 wins 2 p2 wins 3 both winpublic int fightmathint one int two ifone 0 two 0 result 0 else ifone 0 two 1 result 0 else ifone 0 two 2 result 1 else ifone 0 two 3 result 2 else ifone 1 two 0 result 0 else ifone 1 two 1 result 0 else ifone 1 two 2 result 2 else ifone 1 two 3 result 1 else ifone 2 two 0 result 2 else ifone 2 two 1 result 1 else ifone 2 two 2 result 3 else ifone 2 two 3 result 3 else ifone 3 two 0 result 1 else ifone 3 two 1 result 2 else ifone 3 two 2 result 3 else ifone 3 two 3 result 3 return result,['java'] +656845,upload multiple image file to php server from android app i am new to android programming i have been trying to upload multiple images from my app to server using the following code here image array is posted to server with other data like username passwordetc which is in namevaluepairjava codepublic void poststring url listnamevaluepair namevaluepairs httpclient httpclient new defaulthttpclient httppost httppost new httpposturl try multipartentity entity new multipartentity httpmultipartmodebrowser compatible for int index 0 index namevaluepairssize index if namevaluepairsgetindexgetname equalsignorecaseimage if the key equals to image we use filebody to transfer the data logdkey image logdimage path namevaluepairsgetindexgetname entityaddpartnamevaluepairsgetindexgetname new filebodynew filenamevaluepairsgetindex getvalue else normal string data logdtag namevaluepairsgetindexgetname logdtag namevaluepairsgetindexgetvalue entityaddpart namevaluepairsgetindexgetname new stringbodynamevaluepairsgetindexgetvalue httppostsetentityentity httpresponse response httpclientexecutehttppost httpentity enttiy responsegetentity logdserver response to post data entityutilstostringenttiy catch ioexception e eprintstacktrace php code working versionphptarget path user uploaded photosfori0icount filesimagenameifiledata pathinfobasename filesimagenameiusername postusernameprint rfiledatadate datey m d h i snewfilename usernameidatefiledataextensionif move uploaded file filesimagetmp namei target pathnewfilename echo the image filesimagenamei was successfully uploaded and added to the gallerybr else echo there was an error uploading the file filesimagenamei please try againbr location postlocationother fields and database operations ommittedmy problem is with the cakephp website we are using for cake php i use name value pairs as followsnamevaluepair addnew basicnamevaluepairuserdatumuser id 2sending string values like this works for me but when i declare images array images are uploaded but cannot be accessed from files i have declared images array as followsfor string s imagepath namevaluepairaddnew basicnamevaluepairuserdatumimages s logdimagepath s here imagepath is arraylist of string containing path of images is declaring userdatumimages in app the correct way to do it it works with the posted php but in cake php only string values are posted and not images i have tried other librarys like ion but i am only able to upload one photo without using array structure please comment or point me to the right direction for posting multiple images and strings in a single post,"['php', 'android']" +656874,java 8 javascript engine backwards compatibility i am trying out java 8 in my project and i am stuck in an error related to my build processi am using ant scripts and at some point i am using some javascript embeded into ant to do some build specific operations the part of the script that is causing the error looks like belowscript languagejavascript cdata importclassjavaiofile importclassjavaiofilereader scriptthe project is building fine with java 7 or java 6 but it gives me some errors when i am using java 8 these errors are related to the upgrade of the js enginein particular i am getting the following exceptionjavaxscriptscriptexception referenceerror importclass is not defined in at lineafter some googling i found out that it is related to the below issue in the jdkjdk8025132i tried what is suggested in the comments but without luck how can i make java 8 nashorn engine to be compatible with the rhino js engine,['java'] +656878,what is the purpose of the methods in systemreflectionruntimereflectionextensions since net 45 2012 some new extension methods show up from systemreflectionruntimereflectionextensions class however the new methods do not seem to give us anything new an examplestatic void main var prop1 typeofstringgetpropertylength var prop2 typeofstringgetruntimepropertylength extension needs using systemreflection consolewritelineprop1 prop2 action a main var meth1 amethod var meth2 agetmethodinfo extension needs using systemreflection consolewritelinemeth1 meth2this writes true twicethe operator is overloaded here but even checking for reference equality with objectprop1 objectprop2 and objectmeth1 objectmeth2 gives trueso what is the purpose of these new publicly visible methods clearly i must be overlooking or misunderstanding something,"['c#', '.net']" +656940,preload images into memorythisk with android picasso can i download images with picasso before thisplaying themi want to cache images first sample scenariouser clicks on the button sees the progressbar and when the images have finished loading user see the images on the screeni tried to load images with the get method but that did not cache the images thread thread new thread override public void run try picasso picasso picassoowncachewithgetapplicationcontext requestcreator picassorequest for string imgurl imagesurls picassorequest picassoloadimgurl picassorequestget catch exception e eprintstacktrace threadstartthis is my picasso singleton classpublic class picassoowncache static picasso singleton null static cache cache null public static picasso withint cachesize context context if singleton null int maxsize calculatememorycachesizecontext cache new lrucachecachesize maxsize cachesize maxsize singleton new picassobuildercontext memorycachecache build return singleton public static picasso withcontext context if singleton null cache new lrucachecalculatememorycachesizecontext singleton new picassobuildercontext memorycachecache build return singleton static int calculatememorycachesizecontext context activitymanager am activitymanager contextgetsystemserviceactivity service boolean largeheap contextgetapplicationinfoflags flag large heap 0 int memoryclass amgetmemoryclass if largeheap buildversionsdk int buildversion codeshoneycomb memoryclass activitymanagerhoneycombgetlargememoryclassam return 1024 1024 memoryclass 107 targetapibuildversion codeshoneycomb private static class activitymanagerhoneycomb static int getlargememoryclassactivitymanager activitymanager return activitymanagergetlargememoryclass next show cached image to the userpicasso picasso picassoowncachewithgetapplicationcontextpicassosetdebuggingtrue requestcreator picassorequestpicassorequest picassoloadimgurlpicassorequest placeholderrdrawableloading logo errorrdrawableno internet fit i tries also without fit intoholdergetimageviewunfortunately this does not workthanks for yopur suggestions,['android'] +656974,buildconfigfield depending on flavor buildtype i am trying to define a buildconfigvariable depending on the flavor buildtype ideally this is what i wantproductflavors strawberry buildconfigfield string ws api key name variantbuildtypename more flavors name does contain strawberry but i do not know if it is possible to access the variants buildtypeplaced outside the android closure i do have access to the buildtype and variant but then i cannot invoke buildconfigfieldandroidapplicationvariantsall variant println println variant variantname println flavor variantflavorname println if variantbuildtypename release if variantflavorname strawberry buildconfigfield string ws api key strawberry release else buildconfigfield string ws api key chocolate release else ifvariantbuildtypename debug if variantflavorname strawberry buildconfigfield string ws api key strawberry debug else buildconfigfield string ws api key chocolate debug variant strawberryreleaseflavor strawberryorggradleapiinternalmissingmethodexception could not find method buildconfigfield for arguments string ws api key strawberry releasei can easily create a java factory and return the appropriate api key depending on some buildconfig constants but i would rather keep the code configuration agnostic,['android'] +656987,qemu useremulation with java i am using qemu emulator for tracing the execution of an user program we have added a helper function which prints the ip of all the executed instructions we have tested the working of this tool for two variants of primenumber program one in c and another in java we tried 4 different input arguments for each program expecting different number of instructions executed in each case the c version of primenumber program follows expected linear trend ie the number of lines increase with larger inputs however the java program gives exactly same number of instructions each timei feel that java execution trace is capturing only the jvm code and not the actual code that is being runwhere would the code modified by jvm run on qemu is there any special way qemu captures the execution of self modifying code,['java'] +657014,split a string at a certain index if i have a string and i want to split it at which is not contained within brackets how would i do it1221 to get 12 21 122 to get 12 2112 to get 1 12,['python'] +657088,is it good programming to have a return type of exception i ran into an odd situation during a use case on a project esql is calling a java method sending it a string input parameter which the method will unmarshal apply some logic and then store useful info from the unmarshalled object so the method must either throw a jaxbexception or use a try catch in order to handle the possible exceptionsthe problem with this is that esql cannot invoke a java method which includes a throws in the signature but we want any errors to fall through back to the previously calling mbnode so it can be handled appropriately there so then trycatch is out of the pictureit struck me that hey is it not possible to return a type of exception when we encounter an issue and null if not so i wrote a simple method doing so and though i did not get any warnings or errors it seemed just wrong to me in the sense of good programmingfor examplepublic exception dostuffandcheckforerorrsstring instring ifinstringequalsnull return new exceptionyour string is null else return nullbut i just get a terrible feeling about doing anything this wayi am open to any thoughts or different solutions to this especially if there is a way around the esql signature issueupdateadding reference as to why the esql procedure cannot call a java method with a throws clause in the signatureexcerpt from this link under the create procedure statement sectionany java method that you want to invoke must have the following basic signature public static 0 and parameters where must be in the list of java in data types in the table in esql to java data type mapping excluding the reference type which is not permitted as a return value or the java void data type the parameter data types must also be in the esql to java data type mapping table in addition the java method is not allowed to have an exception throws clause in its signature,['java'] +657094,jmeter environment specific configuration i have several jmeter test plans which should be executed in different environments say dev test uat live in each test plan i would like to have a simple way to specify which environment to use each environment has a lot of configuration such as hostname port sslcert user name password account numbers and other test dataone thing i am trying to achieve is the ease of switching environments while using jmeter gui or running scenarios from build scriptsone of my ideas is to use the include controller to include another jmx file which has list of user defined variables and other config elements however jmeter does not support variables in the included file name so i cannot parametrise the scenario by an environment name include controller supports jmeter parameter includecontrollerprefix but it is not very flexible eg i cannot change it from jmeter gui i should change jmeter config files and restart iti have tried to use switch controller but no luck it does not switch configuration elements only samplerswhat is the best practice to externalise environment specific configuration from test scenarios and share it between several scenarios,['java'] +657147,gridspec with shared axes in python this solution to another thread suggests using gridspecgridspec instead of pltsubplots however when i share axes between subplots i usually use a syntax like the following fig axes pltsubplotsn 1 sharexcol shareytrue figsize318how can i specify sharex and sharey when i use gridspec,['python'] +657152,is it possible to cast a stream in java 8 is it possible to cast a stream in java 8 say i have a list of objects i can do something like this to filter out all the additional objectsstreamofobjectsfilterc c instanceof clientafter this though if i want to do something with the clients i would need to cast each of themstreamofobjectsfilterc c instanceof client mapc client cgetidforeachsystemoutprintlnthis looks a little ugly is it possible to cast an entire stream to a different type like cast streamobject to a streamclientplease ignore the fact that doing things like this would probably mean bad design we do stuff like this in my computer science class so i was looking into the new features of java 8 and was curious if this was possible,['java'] +657175,c controlling a transaction across multiple databases say i am having a windows form application which connected to n databases with n connections opened simultaneouslywhat i am looking for is to do a transaction with all of those databases in one gofor example if i were to have 2 database connections using itransaction tx1 session1opentransaction using itransaction tx2 session2opentransaction do the query thingy here writing all that is fine at first but things get kind of redundant when i wanted to query here and there and not to mention the possibility to adding a new connectionwhat i wanted is to loop all of the registered session and wrap it up in a service probably something like this class transactionmanager private isession sessions public transactionmanagerstring connectionstrings initialize the sessions here public function dotransactionstring query foreach isession session in sessions what to do here using trycatch if i were to use using in the foreach loop it would mean that if connection a successful but connection b was not then only connection b would be rolled back,"['c#', '.net']" +657177,convert varchar column to datetime format sql server i have a table of data imported from csv as followsfirsttimetaken latesttimetaken market outcome odds numberofbets volumematched inplay03082013 153014 03082013 153228 overunder 35 goals over 35 goals 5 10 118 103082013 142640 03082013 142943 correct score 0 0 7 12 279 103082013 151534 03082013 152739 match odds barnsley 110 7 9 128072013 165726 29072013 2135 match odds barnsley 3 9 35 0i had to import the first 2 columns in varchar format because i was getting errors trying to import as datetime now i have the data in a table i need to convert the column format from varchar to datetime i triedalter table csvtest dataalter column firsttimetaken datetimealter table csvtest dataalter column latesttimetaken datetimethis results in error the conversion of a varchar data type to a datetime data type resulted in an outofrange valuei know that removing the last row of data gets rid of the problem so i suspect that the system thinks the date format is mmddy whereas it is actually ddmmythe following query works fineselect convertvarchar50firsttimetaken105 from csvtest data select convertvarchar50latesttimetaken105 from csvtest databut this does not convert the column format to datetime i would appreciate some help on how to do this thanks,['sql'] +657247,whats the location of the javafx runtime jar file jfxrtjar on linux i am trying to run some javafx code with eclipse kepler with efxclipse plugin installed on a linux machine usingjava version 170 21openjdk runtime environment icedtea 239 7u212395openjdk 64bit server vm build 237b01 mixed modemy understanding is that although javafx has been included with the standard jdk since version jdk 7u6 the javafx runtime jar file jfxrtjar was left off of the java runtime path on purpose until further testing between javafx and rest of the java infrastructure has been completed for this reason you must manually add it to the project build path libraries when we create a new java projecti have been looking for that jar in both the following directories without successusrlibjvmjava7openjdkcommonjrelibusrlibjvmjava7openjdkamd64libwhere else should i look for it,['java'] +657261,cpython vs cython vs numpy array performance i am doing some performance test on a variant of the prime numbers generator from the below performance measures are with kmax10pure python implementation running in cpython 015spure python implementation running in cython 007sdef primeskmax p k 0 and 2 while k kmax i 0 while i k and and pi 0 i i 1 if i k pappendn k k 1 and and 1 return ppure pythonnumpy implementation running in cpython 125simport numpydef primeskmax p numpyemptykmax dtypeint k 0 and 2 while k kmax i 0 while i k and and pi 0 i i 1 if i k pk n k k 1 and and 1 return pcython implementation using int 03sfrom libcstdlib cimport malloc freedef primesint kmax cdef int n k i cdef int p int mallockmax sizeofint result k 0 and 2 while k kmax i 0 while i k and and pi 0 i i 1 if i k pk n k k 1 resultappendn and and 1 freep return resultthe above performs great but looks horrible as it holds two copies of the data so i tried reimplementing itcython numpy 101simport numpy as npcimport numpy as npcimport cythondtype npintctypedef npint t dtype tcythonboundscheckfalsedef primesdtype t kmax cdef dtype t n k i cdef npndarray p npemptykmax dtypedtype k 0 and 2 while k kmax i 0 while i k and and pi 0 i i 1 if i k pk n k k 1 and and 1 return pquestionswhy is the numpy array so incredibly slower than a python list when running on cpythonwhat did i do wrong in the cythonnumpy implementation cython is obviously not treating the numpy array as an int as it shouldhow do i cast a numpy array to a int the below does not workcdef numpynparray a numpyzeros100 dtypeintcdef int p int adata,['python'] +657277,base64 json encoded strings in nodejs how do i create a base64 json encoded strings in nodejsi tried this and it did not workvar buff new bufferhelloworldtostringbase64is this itvar buff new bufferjsonstringifyhelloworldtostringbase64,['javascript'] +657381,format of datetime field not recognized by spring i am developing web application using spring 324 i have some forms with fields containing date and time piece of my jspformform methodpost actionadd modelattributelicence forminput typedatetime pathbegindate forminput typedatetime pathenddate forminput pathquantitylimit formformnormal form nothing fancy i am using datepicker which gives me date in format ymmdd hhmm so i have added this to my controllerinitbinderpublic void initbinderwebdatabinder webdatabinder simpledateformat dateformat new simpledateformatymmdd hhmm dateformatsetlenienttrue webdatabinderregistercustomeditordatetimeclass new customdateeditordateformat truealso i have added mvcannotationdriven to my servlet configuration xml as stated on some blogsthere is target controllerrequestmappingvalue softwareidlicenceadd method requestmethodpostpublic string addlicencepathvariablesoftwareid long softwareid licence licence model model software software softwarerepositoryfindonesoftwareid licencesetsoftwaresoftware licencerepositorysavelicence return admin path softwareeditand software class looks like thisentitytablename licencespublic class licence idgeneratedvaluestrategy generationtypeautoprivate long idcolumnname begin dateprivate datetime begindatecolumnname end dateprivate datetime enddatecolumnname quantity limitprivate long quantitylimitmanytooneprivate software softwaregetters setters etcthe problem is when i submit my form with datetime field empty it works perfectly but when i have anything in date field no matter if it is properly formatted or not i get http error 400 bad request no exceptions in console only bad request but i am pretty sure it has something to do with date parsingis there a well described method of dealing with date and time fields in forms in spring applications,['java'] +657382,creating a thresholdcoded roc plot in python rs rocr package provides options for roc curve plotting that will color code and label threshold values along the curvethe closest i can get with python is something likefrom sklearnmetrics import roc curvefpr tpr thresholds roc curvequalitytrainpoorcare qualitytrainpred1pltplotfpr tpr labelroc curve colorbpltaxesset aspectequalpltxlim005 105pltylim005 105which givesare there packages that provide functionality equivalent to rs ability to label using printcutoffsat and color code using colorize thresholds presumably this information is in thresholds returned by sklearnmetricsroc curve but i cannot figure out how to use it to color code and label the figure,['python'] +657392,excluding files from coverage when using karma and istanbul i am using karma to test my javascript and get coverage reports i am using the istanbul coverage report which is the default here is my preprocessors parameter preprocessors frameworkjscoverage frameworkjscoverage frameworknodejscoverage frameworktestjscoverage frameworklibjscoverage frameworklibtooldataapitooldataapijscoverage as you can see i am trying to use the as a negate command which usually works with node however it is not working here and none of my directories are being excludedis there any way to do what i am trying to accomplish,['javascript'] +657422,calculate set partitions with specific subset sizes given a set with n elements i need to find all the partitions of that set where there are k subsets of almost equal sizefor example for a set with 7 elements and 3 subsets i only want partitions where there are two subsets with 2 elements each and one subset with 3 elements i do not want a partition that has subsets with 1 2 and 4 elementsput another way there are 877 possible partitions for a set of 7 elements but i am only interested in the 105 partitions that are made up subsets with 223 elements in reality n is around 35 which means that there are approximately 281 1027 partitions only 8338573669964101 partitions with three subsets as such i cannot possibly calculate them all and wade through to find the ones that i wantwhats an algorithm for calculating just the partitions of interest not the number of partitions but that actual members in each subset for each partition,['ruby'] +657425,dozens of profilinginvalid arc tag when running code coverage in xcode 5 when running my test target with code coverage enabled in xcode 5 i get dozens of the following message in the build outputprofilinginvalid arc tag 0xit does not seem to affect the tests as they complete successfully and also the gcda coverage files are generated as expected any idea what the message means or how to suppress the messagesfix the issue because they clutter up the build output and make it hard to find the test case results,"['ios', 'objective-c']" +657595,not able to connect android wear emulator with device i am not able to connect android wear emulator with my devicei have htc one device which has 44 kitkat osi follow below link setting up android wearbut when i execute the line adb d forward tcp5601 tcp5601 through command promptnothing happensandroid wear emulator does not show device connectednote i am able to launch the android wear preview app successfully in my device and notifications settings is also enabledany help will be appreciated,['android'] +657686,how to get the publish version of a wpf application i want my wpf application publish version i tried using the answer for this question it works but the problem is we can manually change the values there i want to know how many times my project was actually published do not need version number just how many times did i publish my application can this be done,['c#'] +657712,ios how to make the tableview use paginated api output an api i am writing has about 20 records returned in json via a simple restful api i have writtento reduce issues with lots of data i want to use pagination so that i only return say the first 10 or first 20 per request via like an offset or limit or page etcbut my question is how does the ios uitableview know when to get the next page of resultsi really am unsure of how to do this the user could be scrolling superfast and so the api might not have enough time to retrieve 20 or 50 records at a timeanother issue related to this is lets say the user scrolls down on the uitableview then up and then back down again how do you prevent the api from firing multiple times for the same rowsthanks,['iphone'] +657784,no module named setuptools i want to install setup file of twilio when i install it through given command it is given me an error no module named setuptools could you please let me know what should i doi am using python 27 microsoft windows version 617601copyright c 2009 microsoft corporation all rights reservedcpython27python dtesttwiliotwiliopython26f6707setuppy installtraceback most recent call last file dtesttwiliotwiliopython26f6707setuppy line 2 in module from setuptools import setup find packagesimporterror no module named setuptools,['python'] +657802,can i use css to set up different default print page sizes for different pages i have a number of pages which i would like to set up so that printing defaults to a4 landscape in somecases but a3 portrait in othersbased on the answer in css print styling i have tried to set up the following in a printless file media print printportraita3 page size a3 portrait margin 05cm printlandscapea4 page size a4 landscape margin 05cm printportraita4 page size a4 portrait margin 05cm i am then putting printportraita3 classes etc at the top of the page sections that i am printing to try and get them to print to the different page sizeshowever i cannot get this to work whichever is the last style in my css is the one that gets used by all pages i am only really just beginning with css probably obvious that i do not have much of a clue so would appreciate some explanation to sort out my misunderstandingsi am using jade and bootstrap,['css'] +657958,css3 multicolumn list i have been using css3 multicolumn for a few wordpress sites now and one thing that i find excepteble but still something i want to know how to fix is that if i put a listwith sub items in the collumns that it would not keep the structure of the listto make myself clear this is the htmldivul li listitem ul lisublistitemli lisublistitemli ul li li listitem ul lisublistitemli lisublistitemli ul liuldivand the css would bedivwebkitcolumncount3 mozcolumncount3 mscolumncount3 ocolumncount3 columncount3 webkitcolumngap15px mozcolumngap15px mscolumngap15px ocolumngap15px columngap15px columns3and this is what you getthis is nice because it makes it possible in wordpress to show menus like thisbut one thing that bugs me is that it places the sublistitems in the next column while the parent of that item is in the previous columnis this fixablebefore anyone says why do not you just make multiple lists and make your own columnsthis was the suggestion when i asked the question how to do this this is for a dynamic wordpress menu so i have no controll over how many items are in the menu,"['html', 'css']" +658064,detailled debug with volley in restkit on ios there is a verbose debug option rklogconfigurebyname rklogleveltrace does anyone know if there is an equivalent for volley basically i am going straight to the errorlistener but i get no additional info in logcat bothvolleylogeerror errortostringand volleylogeerror errorgetmessageprints2onerrorresponse error,['android'] +658098,how would you migrate from php to hack facebook have introduced a new programming language which looks mostly like an extension to php they have called it hack and it is running on their hhvm engineafter seeing their website and reading a bit about it i wondered how fluid a migration from php to hack could potentially belet us base this thiscussion around a web application already deployed to a lemp or lamp stacksome of my initial thoughts and list of actions includehow do i run both php and hack in the process of migrating the code basemigrate from nginxapache to hhvmmigrate code base iterativelyso how would you approach this,['php'] +658204,compiling scipy to android has it been done any help on how to compile the fortran code to android arm for a project i am porting a scientific python app using scipy to android i am currently using to build the code numpy builds but scipy is proving to be a real hassle hacking around with devenv and kivy python for android i kinda got to compile the scipy c libs to android arm but now the fortran libs remain to be built and i am at a lossany help would be deeply appreciated,['python'] +658337,why is jquery validation adding novalidate attribute i am currently usingscript srccodejquerycomjquery1102minjsscriptscript srccodejquerycomui1104jqueryuijsscriptscript srcjsbootstrapjsbootstrapminjsscriptscript srcscriptscript srcscriptwith validation such asjdelvalidateeachfunctionjthisvalidate rules delivery method required true message delivery method required true jvalidateusereachfunction jthisvalidate rules f name required true l name required true username required true minlength 6 password validchars true nospace true minlength 6 skip or fill minimum 3pw confpass equalto password skip or fill minimum 3pw html snippetform classformhorizontal delvalidate action methodpostinput typehidden nameformidentifier valueadel div classformgroup div classcolsm3 input typetext namedelivery method classformcontrol placeholderenter new method div div classcolsm2 colsmoffset2 button typesubmit classbtn btndefault btnblockaddbutton divdivformbut when i go to my page my form is rendered with the attribute novalidate and therefore i can insert nullempty values into the database what is the reasoning for this does the form have to be set up in a particular way does jquery validation pick up something is wrong and therefore does not workmy dirty work around is usingjthisremoveattrnovalidate,['jquery'] +658529,css triangles getting cut off i am trying to create some css triangles using css and the after pseudo class somehow the up and down arrows are working properly but the left and right arrows are being cut off see fiddle this is basically the css i am usingarrowrightafter content bordertop 60px solid transparent borderbottom 60px solid transparent borderleft 60px solid greendoes anyone know why this is happening,['css'] +658534,make background image responsive i want to make background image responsive both in width as well as in height so that i can run it in mobilei have used this your background class name width 100 heightauto top 0px left 0px zindex 1 position absolutebut it works in width only not in height what changes should i do to make it work,['css'] +658588,cannot add multiple fragments to linearlayout i am using a linearlayout with a vertical orientation to list fragments i add fragments to the container programmatically like thisfragmenttransaction ft fragmentmanagerbegintransactionfragment fragment1 new fragmentftaddridllcontainer fragment1fragment fragment2 new fragmentftaddridllcontainer fragment2ftcommitbut it only shows the first fragment why,['android'] +658638,html prevent space bar from scrolling page i am using the codewindowonkeydown functione return ekeycode 32which does exactly what i want stops the page from scrolling when the spacebar is pressed however it also prevents the user from typing spaces in a textboxis there a way to prevent the spacebarscroll as well as retain the spacebar functionality while typing,"['javascript', 'html']" +658674,how to mock location service using kifframework i use kif framework for ui testsand i need to mock location servicethe problem is location service starts before kif method beforeall invokedso it is too late to mockany suggestions would be appreciated,"['ios', 'objective-c']" +658719,does java strictfp modifier have any effect on modern cpus i know the meaning of the strictfp modifier on methods and on classes according to the jlsjls 8435 strictfp methodsthe effect of the strictfp modifier is to make all float or double expressions within the method body be explicitly fpstrict a154jls 154 fpstrict expressionswithin an fpstrict expression all intermediate values must be elements of the float value set or the double value set implying that the results of all fpstrict expressions must be those predicted by ie 754 arithmetic on operands represented using single and double formatswithin an expression that is not fpstrict some leeway is granted for an implementation to use an extended exponent range to represent intermediate results the net effect roughly speaking is that a calculation might produce the correct answer in situations where exclusive use of the float value set or double value set might result in overflow or underflowi have been trying to come up with a way to get an actual difference between an expression in a strictfp method and one that is not strictfp i have tried this on two laptops one with a intel core i3 cpu and one with an intel core i7 cpu and i cannot get any differencea lot of posts suggest that native floating point not using strictfp could be using 80bit floating point numbers and have extra representable numbers below the smallest possible java double closest to zero or above the highest possible 64bit java doublei tried this code below with and without a strictfp modifier and it gives exactly the same resultspublic static strictfp void withstrictfp double v doublemax value systemoutprintlnv 101 101 v doublemin value systemoutprintlnv 2 2actually i assume that any difference would only show up when the code is compiled to assembly so i am running it with the xcomp jvm argument but no differencei found another post explaining how you can get the assembly code generated by hotspot openjdk documentation i am running my code with java xcomp xxunlockdiagnosticvmoptions xxprintassemblythe first expression v 101 101 with the strictfp modifier and also the same without it is compiled to 0x010f10a0a9 movsd 0xb1ripxmm0 0x010f10a0 section word 0x010f10a0b1 mulsd 0xb1ripxmm0 0x010f10a008 section word 0x010f10a0b9 divsd 0xb1ripxmm0 0x010f10a010 section wordthere is nothing in that code that truncates the result of each step to 64 bits like i had expected looking up the documentation of movsd mulsd and divsd they all mention that these sse instructions operate on 64bit floating point values not 80bit values as i expected so it seems logical that the double valueset that these instructions operate on is already the ie 754 value set so there would be no difference between having strictfp and not having itmy questions areis this analysis correct i do not use intel assembly very often so i am not confident of my conclusionis there any other modern cpu architecture that has a jvm for which there is a difference between operation with and without the strictfp modifier,['java'] +658721,pandas dataset into an array for modelling in scikitlearn can we run scikitlearn models on pandas dataframes or do we need to convert dataframes into numpy arrays,['python'] +658772,is it possible to register two actions within one for activity i wanted to register my launcher activity so it could be started by both clicking on icon and opening link with a custom scheme i managed to make it work but am questioning is this correct way this is the relevant part of my manifest intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorymultiwindow launcher category androidnameandroidintentcategorylauncher intentfilter intentfilter action androidnameandroidintentactionview category androidnameandroidintentcategorydefault category androidnameandroidintentcategorybrowsable data androidschememysheme intentfilterthis does work but i was wondering should i register both actions under same intent filter i tried just moving tags from second filter to the first one but then my activity does not show icon on install is it possible to do it this way and i just made some small syntax erroror broke some undocumented order of declaration rule or is my thinking completely wrong on this and there are deeper reasons why this does not worknotei do set androidexportedtruebut androidintentactionmain works even without it because it becomes exported anyway if you use actionmain,['android'] +658791,regex for accepting only persian characters i am working on a form which one of it is custom validator should only accept persian charactersi used the following code var myregex new regexu0600u06ff if myregexismatchmytextboxtext argsisvalid true else argsisvalid false but it seems it only work for checking arabic characters and it does not cover all persian characters it lacks these four u uu34u is there a way for solving this problem,"['c#', 'asp.net']" +658815,how to use linqtotwitter v3 alright i recently upgraded to v3 but it broken many thingshow can i fix these number 1 this is not working anymore no such definition as credentials and inmemorycredentialsvar auth new singleuserauthorizer credentials new inmemorycredentials consumerkey srtwitterconsumerkey consumersecret srtwitterconsumersecret oauthtoken srtwitteroauthtoken accesstoken srtwitteraccesstoken number 2 no definition for getfilebytes anymorevar mediaitems new listmedia new media data utilitiesgetfilebytessrimageurl filename srtweetsplit 0jpg contenttype mediacontenttypejpeg number 3 no definition for tweetwithmediavar tweet twittercontexttweetwithmediasrtweet false mediaitemsnumber 4 no definition for updatestatusvar tweet twittercontextupdatestatussrtweetnumber 5 no definition for createfavoritevar vrresult twittercontextcreatefavoritesrretweetidand i can not find any example for v3it always say twitterctx but how do you get twitterctx in the first place,['c#'] +658921,readerlines parallelizes badly due to nonconfigurable batch size policy in its spliterator i cannot achieve good parallelization of stream processing when the stream source is a reader running the code below on a quadcore cpu i observe 3 cores being used at first then a sudden drop to just two then one core overall cpu utilization hovers around 50note the following characteristics of the examplethere are just 60 lineseach line takes about 20 ms to processthe whole procedure takes about a minutethat means that all the pressure is on the cpu and io is minimal the example is a sitting duck for automatic parallelizationimport static javautilconcurrenttimeunitnanosecondsimport static javautilconcurrenttimeunitseconds class imports elided public class main static final atomiclong totaltime new atomiclong public static void mainstring args throws ioexception final long start systemnanotime final path inputpath createinput systemoutprintlnstart processing try printwriter w new printwriterfilesnewbufferedwriterpathsgetoutputtxt fileslinesinputpathparallelmapmainprocessline foreachwprintln final double cputime totaltimeget realtime systemnanotimestart final int cores runtimegetruntimeavailableprocessors systemoutprintln cores cores systemoutformat cpu time 2f sn cputimesecondstonanos1 systemoutformat real time 2f sn realtimesecondstonanos1 systemoutformatcpu utilization 2f 10cputimerealtimecores private static string processlinestring line final long localstart systemnanotime double ret 0 for int i 0 i linelength i for int j 0 j linelength j ret mathpowlinecharati linecharatj320 final long took systemnanotimelocalstart totaltimegetandaddtook return nanosecondstomillistook ret private static path createinput throws ioexception final path inputpath pathsgetinputtxt try printwriter w new printwriterfilesnewbufferedwriterinputpath for int i 0 i 6 0 i final string text stringvalueofsystemnanotime for int j 0 j 25 j wprinttext wprintln return inputpath my typical output cores 4 cpu time 11023 s real time 5360 scpu utilization 5141for comparison if i use a slightly modified variant where i first collect into a list and then processfileslinesinputpathcollecttolistparallelstreammapmainprocessline foreachwprintlni get this typical output cores 4 cpu time 13843 s real time 3500 scpu utilization 9887what could explain that effect and how can i work around it to get full utilizationnote that i have originally observed this on a reader of servlet input stream so it is not specific to a filereader,['java'] +658984,can django managepy custom commands return a value how or why not following the documentationi created my own custom command called something else but example shown belowfrom djangocoremanagementbase import basecommand commanderrorfrom pollsmodels import pollclass commandbasecommand args poll id poll id help closes the specified poll for voting def handleself args options for poll id in args try poll pollobjectsgetpkintpoll id except polldoesnotexist raise commanderrorpoll s does not exist poll id pollopened false pollsave selfstdoutwritesuccessfully closed poll s poll id return yaythe question is how come returning a string like yay does not workam i doing it wrong or is it not possiblewhen i call the custom command from my view i do something like value call commandcall custom command parameter print valuebut the value is shown to be none,['python'] +659019,are compiled java 8 lambda expressions backwards compatible with earlier versions of the java runtime in order to reduce the clutter caused by numerous instantiations of anonymous types i am exploring the possibility of leveraging java 8 lambdas one important consideration before using java 8 and lambdas in a production environment is whether jdk8compiled code that uses lambda expressions can be executed on an earlier version of the java runtime i am specifically interested in jre6 and jre7 as target platformsone one hand i understand that lambdas are simply syntactic sugar around an instantiation of an anonymous class containing one method on the other hand i am not certain that this equivalence implies that the bytecode generated for each is identical andor compatible across jvm versions other than jre8for example given the singlemethod interfacepublic interface actiont public void performt argumentthe following two snippets are functionally equivalentwith lambdafinal actionstring y i systemoutprintlniwith anonymous class instancefinal actionstring y new actionstring override public void performfinal string i systemoutprintlni my specific question is whether the semantic equivalence of both constructs extends to equivalence of their compiled representations furthermore if they indeed compile equivalently does this equivalence indicate that the compiled form of a lambda expression can be hosted on earlier versions of the java runtime without modification,['java'] +659087,why is numpydtypefloat64 special can someone explain the logic behind the output of the following scriptimport numpyifnumpydtypenumpyfloat64 none print surprisethanks,['python'] +659120,getopt not included implicit declaration of function agetopta i wanted to use getopt but it just would not workit is giving megcc g wall stdc99 ftrapv o2 werror wshadow wundef savetemps werrorimplicitfunctiondeclaration c o srcmaino srcmaincsrcmainc in function amainasrcmainc132 error implicit declaration of function agetopta werrorimplicitfunctiondeclarationsrcmainc2314 error aoptarga undeclared first use in this functionsrcmainc2314 note each undeclared identifier is reported only once for each function it appears insrcmainc269 error aoptopta undeclared first use in this functionsrcmainc285 error implicit declaration of function aisprinta werrorimplicitfunctiondeclarationsrcmainc365 error implicit declaration of function aaborta werrorimplicitfunctiondeclarationsrcmainc365 error incompatible implicit declaration of builtin function aaborta werrorsrcmainc4315 error aoptinda undeclared first use in this functioncc1 all warnings being treated as errorsmake srcmaino error 1heres the source if you wanna see italmost exact copypasta from getopt manpageinclude stdiohinclude unistdh getoptinclude myfnhint mainint argc char argv int aflag 0 int bflag 0 char cvalue null int c whilec getoptargc argv abc 1 switchc case a aflag 1 break case b bflag 1 break case c cvalue optarg break case if optopt c fprintf stderr option c requires an argumentn optopt else if isprintoptopt fprintf stderr unknown option cn optopt else fprintf stderr unknown option character xxn optopt return 1 default abort printf aflag d bflag d cvalue sn aflag bflag cvalue for int i optind i argc i printf nonoption argument sn argvi return 0any ideas what i am doing wrongi am on linux so i assumed it should work like this,['c'] +659232,convert arrayhash to yaml in ruby on rails i want to construct the following yaml formatting from an arrayhashname gender female nationality german danishright now i have an array like thisnames abbie abeline abelonewhat would be the easiest way to get from this array to yamli tried converting it to a hash whilst adding the values for gender and nationalitynameseach do name meta hash hashnew name gender female nationality german danish endthis however just gives me a syntax error any help with converting this will be much appreciated,"['ruby-on-rails', 'ruby']" +659387,how to wrap long code lines in googlecodeprettify i am using default setting of googlecodeprettify when a line is too long it exceeds the boundary like the following are they any possible solution to wrap the code line,['javascript'] +659474,android adt no fragment mainxml only activity mainxml i am trying to learn how to program android applications so i downloaded the adt bundle that google supplied and i tried following the tutorial that allowed me to create a simple application however during the procedures there are several instructions telling me to open up the fragment mainxml file but my layoutres directory did not have this file only the activity mainxml file furthermore when creating new android activities there was never an option to name my fragment layout indicating that eclipse just does not create it for some reason i did not think this would be an issue at first i just edited activity main instead until i realized that the tutorial wanted us to use the some information from the fragment class or xml filedoes anyone know why my eclipse ide is not creating a fragment mainxml i will try to supply more details if necessary,['android'] +659549,integrating emberjs with a simple sinatra backend there is a lot of documentation of how to structure and create emberjs apps with rails as a backend pupular solutions are to use gems as emberrails and embersource or the all in one emberappkitrailshowever i am trying to create a simple sinatra app that handle a json only backend with emberjs as the frontendthe few resources that i found seems a little outdated so i am looking for simple way to do that so my question ishow i integrate emberjs with a simple sinatra backend examples of how to do so will be appreciated,['ruby'] +659615,pycharm is missing project type drop down i have just downloaded pycharm community edition for my mac it seems to work great but for some reason project type dropdown is missing in create project dialog i am newbie to pycharm and python overall so i do not know if there is some obvious reason for this i was able to create projects however even in virtualenv but they are always empty projects any ideas,['python'] +659637,why members of stdbasic string are public in vs2010 include iostreaminclude stringint main stdstring s s mysize 7 well compiled stdcout ssize n prints 7 why nonstatic members of the stdbasic string are public in vs2010 is this bug if yes how about of next version of visual studios vs2012 and vs2013 edit i just test other containers and interesting vector and unique ptrs nonstatic members are public alsostdvectorchar vv myfirst char2 well compiledstdunique ptr int uu myptr 0 well compiledq is here any reason or advantage of using public data members,['c++'] +659686,aspnetidentity error the entity type applicationuser is not part of the model for the current context in move aspnet identity store to ef sql database zoidbergi described an issue similar to that which i am experiencing but which was not completely answered i am receiving the error above when attempting to migrate from the inbuilt mdf database to mysql i am using a databasefirst methodology and have successfully created the entity model from the underlying mysql databaseno matter whether i recreate the aspnet identity datatables the application chokes as soon as user manager is accessedthe entity type applicationuser is not part of the model for the current contextdescription an unhandled exception occurred during the execution of the current web request please review the stack trace for more information about the error and where it originated in the code exception details systeminvalidoperationexception the entity type applicationuser is not part of the model for the current contextsource error line 65 create a local login before signing in the userline 66 dim user new applicationuser with username modelusernameline 67 dim result await usermanagercreateasyncuser modelpasswordline 68 if resultsucceeded thenline 69 await signinasyncuser ispersistentfalsei have pointed the applicationdbcontext at my dbcontext modelpublic class applicationdbcontext inherits identitydbcontextof applicationuser public sub new mybasenewimsentities end subend classgoogling tends to find people who have given up and coded up their own security providers i would like to use the standard one if possible baffled,"['mysql', 'asp.net']" +659785,would it create issues if number were to be implemented as an interface are there benefits on a recent question i came accross the use of the number abstract classnow since java 8 is here there are default methods so number could be an interface and written aspublic interface number public int intvalue public long longvalue public float floatvalue public double doublevalue default public byte bytevalue return byteintvalue default public short shortvalue return shortintvalue would old code using the number abstract class still compile if this were the case are there any actual benefits in making number an interface rather than an abstract class,['java'] +659831,uibarbuttonitem settitlepositionadjustmentforbarmetrics ignores vertical offset i have an application with some custom positioned bars and as such i would like to change the standard vertical alignment of the button text i have tried settingbuttonitem settitlepositionadjustmentuioffsetmake0 22 forbarmetricsuibarmetricsdefaultbut nothing changes oddly if i set a horizontal offset the button moves just fine it appears only vertical alignment changes are not being respected is this a bug on ios 7 am i misunderstanding something about the api i see no documentation saying that the vertical alignment is ignoredexample project showing the issue,['ios'] +659837,upgrade path for reusable apps with south and django 17 migrations or can django 17 users still use southi am the maintainer of a reusable app our policy is to always support the latest two versions of django we have an extensive set of south migrations and we want to support the new django 17 migration system going forwardwhat i am confused with is how i can allow developers to use my app with both django 16 and south and django 17 new migrationsthe django documentation recommends just deleting all the preexisting south migrations but this is not an option since i need to keep them around for my django 16 usersthe closest to an upgrade path i could come up with is not use the new migration system until i drop support for django 17 in my app so when django 18 comes out but what about the naming clash with the migrate command both south and the new system use python managepy migrate to run migrations so django 17 users cannot use south anymore,['python'] +659927,why are stdshuffle methods being deprecated in c14 according to the cppreferencecom reference site on stdshufle the following method is being deprecated in c14template class randomit void random shuffle randomit first randomit last why will we no longer be able to call the following function without passing a third parameterstdrandom shufflevbeginvend no longer valid in c14it does not appear as though a different function deceleration has a default parameter set what is the reason behind this was there some kind of alternative added,['c++'] +659965,how to give hexagon shape to imageview how to give hexagon shape to imageview is it possible to do in same way if so then how if this is not possible through this then how this could be achieved shape xmlnsandroidhttpschemasandroidcomapkresandroid androidshapehexagon solid androidcolorf size androidwidth60dp androidheight40dp shapescreenshothere i cannot do masking image because i can not detect which portion of bitmap i should crop to get hexagon shape bitmap so i am looking for the answer to give hexagon shape to imageview,['android'] +660077,reverse singly linked list java can someone tell me why my code dosent work i want to reverse a single linked list in java this is the method that doesnt work correctlypublic void reverselist node before null node tmp head node next tmpnext whiletmp null ifnext null return tmpnext before before tmp tmp next next nextnext and this is the node classpublic class node public int data public node next public nodeint data node next thisdata data thisnext next on input 4321 i got output 4 i debugged it and it sets pointers correctly but still i dont get why it outputs only 4,['java'] +660090,how to remove gppsigninbuttons default style text g image to add your own in ios were using the ggpsigninbutton to log into goopleplus servicewe want to have a custom look and feel for the button but i could not find a way to turn off the text and image that show up with the button automatically when i tell a uibutton he is of a kind gppsigninbutton heres how it looks when i add my own design inside an otherwise empty button which is gppsigninbuttonthe only way i have been able to make it thisappear is pretty patchyfirst wire up the button to a iboutlet called gplusbuttonselfgplusbuttonsubviews0 removefromsuperviewi also tried using my own button and when pressed calling manually togppsignin sharedinstance authenticatemethod seems to result in an incorrect login for example the login token is not saved into the key chain google later uses to silently authenticate medoes anyone know of a better way to design my own style for the buttonbtw it appears this is supported for web sign in buttons,"['ios', 'objective-c']" +660114,how to refresh gallery after deleting image from sdcard when deleting the images on androidas sd card sometime the images are correctly removed but in the gallery still remain a preview of the removed image when tapping on it it is loaded as a black image to resolve it you need to run mediascanner but this code would not work and still the preview of review image remain in the galleryanyone knows how to resolve thisuri contenturi urifromfilefileintent mediascanintent new intentintentaction media scanner scan filecontenturi sendbroadcastmediascanintent,['android'] +660235,a program made with java 8 can be run on java 7 i am a little confusedoracle says java 8 is highly compatible with java 7 backward but what possibilities exist that java 8 program can be run on java 7 successfully seif point one was true java 8 applications will be deployed and executed on a java 7 server support for example tomcat 8 or wildfly,['java'] +660241,native crash in unknown unknown i have an app which is entirely written in java no native code whatsoever and i have twice had a crash report on the developer console native crash in unknown unknown i have no idea where to start locating the source of the problem searching has only revealed this type of crash in the case of android bugs ndk usage or buggy third party libraries for what it is worth here is one of the logs build fingerprint samsungm0xxm043jss15ji9300xxugmj9userreleasekeysrevision 12pid 2197 tid 2197 name testapp comtestapp signal 6 sigabrt code 6 si tkill fault addr r0 fc r1 bef3f3f8 r2 010 r3 fr4 41619610 r5 0 r6 41619624 r7 0fcr8 41619658 r9 014 sl 418cc238 fp bef3f56cip bef3f3f8 sp bef3f3d8 lr 40115045 pc 401a1574 cpsr 280b0010d0 0100110102 d1 044a010d2 0 d3 0d4 02d044340 d5 042a40d6 0 d7 03f80d8 030 d9 43010d10 04240 d11 0d12 0 d13 0d14 0 d15 0d16 02bdd67c11c72 d17 0d18 0 d19 2200220022002200d20 03 d21 03d22 02 d23 03d24 24 d25 24d26 23 d27 fd28 0101010fd d29 0101010100d30 0101010100 d31 0101010100scr 6010backtrace00 pc 01c574 systemliblibcso epoll wait1201 pc 015041 systemliblibutilsso androidlooperpollinnerint9202 pc 015261 systemliblibutilsso androidlooperpollonceint int int void9203 pc 06bd21 systemliblibandroid runtimeso androidnativemessagequeuepollonce jnienv int2204 pc 01eb0c systemliblibdvmso dvmplatforminvoke11205 pc 04f457 systemliblibdvmso dvmcalljnimethodunsigned int const jvalue method const thread39806 pc 027fa0 systemliblibdvmso07 pc 02c9d0 systemliblibdvmso dvminterpretthread method const jvalue18408 pc 06176b systemliblibdvmso dvminvokemethodobject method const arrayobject arrayobject classobject bool35009 pc 06944b systemliblibdvmso10 pc 027fa0 systemliblibdvmso11 pc 02c9d0 systemliblibdvmso dvminterpretthread method const jvalue18412 pc 0614ad systemliblibdvmso dvmcallmethodvthread method const object bool jvalue std va list29213 pc 04b03b systemliblibdvmso14 pc 04f5e7 systemliblibandroid runtimeso15 pc 050277 systemliblibandroid runtimeso androidandroidruntimestartchar const char const37816 pc 0105b systembinapp process17 pc 0dd03 systemliblibcso libc init5018 pc 0d7c systembinapp processcode around pc401a1554 e1a0700c e3700a01 912f1e e260 401a1564 ea007f30 e1a0c007 e3a070fc ef0 401a1574 e1a0700c e3700a01 912f1e e260 401a1584 ea007f28 e1a0c007 e3a07f4f ef0 401a1594 e1a0700c e3700a01 912f1e e260 401a15a4 ea007f20 e1a0c007 e59f7014 ef0 401a15b4 e1a0700c e3700a01 912f1e e260 401a15c4 ea007f18 013d e1a0c007 e59f7014 401a15d4 ef0 e1a0700c e3700a01 912f1e 401a15e4 e260 ea007f0f 013e e1a0c007 401a15f4 e3a070a8 ef0 e1a0700c e3700a01 401a1604 912f1e e260 ea007f06 e1a0c007 401a1614 e3a07f59 ef0 e1a0700c e3700a01 401a1624 912f1e e260 ea007efe e1a0c007 401a1634 e59f7014 ef0 e1a0700c e3700a01 401a1644 912f1e e260 ea007ef6 0f05 code around lr40115024 0848f104 46402500 f7fdaf08 2210fd8e 40115034 46394633 6b2065e5 0614f104 eeaaf7f7 40115044 46304681 feb6f7f8 da1245a9 ece6f7f7 40115054 2f046807 f04fd102 e05637ff f06f4962 40115064 4a620703 20056803 447a4479 ec52f7f7 40115074 d048e04b a178f8df b178f8df 44fa4b5e 40115084 447b44fb 01289305 583b1839 68e0688a 40115094 d10c4282 d50307d9 f7ff4620 e02efdf1 401150a4 20054a56 447a4659 ec34f7f7 4611e027 401150b4 0034f104 92049303 ff0df7ff 99042800 401150c4 db169b03 0101f003 bf48075a 0102f041 401150d4 bf48071a 0104f041 6ba306db f041bf48 401150e4 22140108 3300fb02 1d1a4620 ff5bf7ff 401150f4 9100e005 99052005 f7f74652 3501ec0c 40115104 dbc0454d f06fe7a7 f04f0702 f06f32ff 40115114 e9c44300 f1042318 e02f0918 f7fc2001 any suggestions for my next steps i have my own logfile but it is nothing like granular enough to have tracked this,['android'] +660296,uitableview bottom separator inset strange behaviour in ios 7 my app contains a uitableview which has section footers when the user scrolls to the bottom of the tableview sometimes a separator inset appears between the last cell and the tablefooter this behaviour is inconsistentis there a way to force this separator to always appear or never appear did any of you noticed this same inconsistent behaviour seems like a bug to meediti am using uiview tableviewuitableview tableview viewforfooterinsectionnsintegersection uilabel footer uilabel alloc init footerbackgroundcolor uicolor whitecolor footerfont footerfont fontwithsize15 footertextalignment nstextalignmentcenter return footerbut you could easily reproduce the same problem only using nsstring tableviewuitableview tableview titleforfooterinsectionnsintegersection,"['ios', 'objective-c']" +660331,calling afhttpsessionmanagerdownloadtasks in afnetworking 2 freezes the main thread i have a singleton class that contains a afhttpsessionmanager filetransfersessionmanager in it i sometimes want to cancel all downloads before starting them anew this is done running through the downloadtasks and canceling them the problem is that when the downloadtasks attribute is called the main thread freezes if there are running downloads my method canceling download tasksnsarray downloadtasks selffiletransfersessionmanagerdownloadtasks for nsurlsessiondownloadtask downloadtask in downloadtasks downloadtask cancel in afurlsessionmanagerm nsarray downloadtasks return self tasksforkeypathnsstringfromselector cmdcalls this method that freezes the main thread because gettaskswithcompletionhandler with thispatch semaphore signalsemaphore is never called in afurlsessionmanagerm nsarray tasksforkeypathnsstring keypath block nsarray tasks nil thispatch semaphore t semaphore thispatch semaphore create0 selfsession gettaskswithcompletionhandlernsarray datatasks nsarray uploadtasks nsarray downloadtasks if keypath isequaltostringnsstringfromselectorselectordatatasks tasks datatasks else if keypath isequaltostringnsstringfromselectorselectoruploadtasks tasks uploadtasks else if keypath isequaltostringnsstringfromselectorselectordownloadtasks tasks downloadtasks else if keypath isequaltostringnsstringfromselectorselectortasks tasks datatasks uploadtasks downloadtasks valueforkeypathunionofarraysself thispatch semaphore signalsemaphore nslogcurrent thread nsthread currentthread thispatch semaphore waitsemaphore thispatch time forever return tasksi have tracked the problem down to selfsession gettaskswithcompletionhandler never entering its block and therefore the thispatch semaphore wait will wait literally forever to unlock the main threadwhat can be the cause of this i doubt its a bug in apples framework so thats why i ask here before submitting it have i done any obvious mistakes that may cause this problem,['ios'] +660373,python convert pairs list to dictionary i have a list of about 50 strings with an integer representing how frequently they occur in a text document i have already formatted it like shown below and am trying to create a dictionary of this information with the first word being the value and the key is the number beside it string limited 1 all 16 concept 1 secondly 1the code i have so farmy dict for pairs in string for int in pairs my dictpairs int,['python'] +660428,generic method where t implements interface i am trying to create a generic data retrieval process what i have currently works but there is a part of it that does not seem right and i am hoping there is a better way to accomplish itso the idea is that i have classes for each table in the database here is an example of a classpublic class cmcgrgrgroup ifacetsobjectcmcgrgrgroup public int grgr ck get set public string grgr name get set public string grgr addr1 get set public ienumerablecmcgrgrgroup toobjectdatatable table return tableasenumerableselectrow return new cmcgrgrgroup grgr ck converttoint32rowgrgr ck grgr name rowgrgr nametostring grgr addr1 rowgrgr addr1tostring youll notice that the class implements an interface of its own type the interface simply defines a method called toobject which is used to convert a datatable to a class of that particular typepublic interface ifacetsobjectt ienumerablet toobjectdatatable objnow here is the method that i am using to execute a querypublic ienumerablet executequerytstring sql ifacetsobjectt obj where t new using var conn new aseconnection conn connopen var cmd new asecommandsql conn var dt new datatable var da new asedataadaptersql conn dafilldt return objtoobjectdt this is the interface method so the main question ishow can the generic method know that t should implement ifacetsobjectt that way i do not have to pass ifacetsobjectt as a parameter ideally i could change the return line to be something like thisreturn ttoobjectdtand call it like thisvar result executequerycmcgrgrgroupsqltake5instead of like thisvar result executequerycmcgrgrgroupsql new cmcgrgrgrouptake5i will admit that i am not terribly familiar with generics yet so there may be something within the implementation that is not right,['c#'] +660450,how to add own icons in bootstrap navbar working on a project where i started on the navbar the thing i am wondering if its possible to add my own icons right next to each of the menu bars for example this icons like thisdemocode fixed navbar div classnavbar navbardefault navbarfixedtop rolenavigation div classcontainer div classnavbarheader button typebutton classnavbartoggle datatogglecollapse datatargetnavbarcollapse span clasronlytoggle navigationspan span classiconbarspan span classiconbarspan span classiconbarspan button a classnavbarbrand hrefproject namea div div classnavbarcollapse collapse ul classnav navbarnav li classactivea hrefhomeali lia hrefaboutaboutali lia hrefcontactcontactali ul divnavcollapse div div div classcontainer main component for a primary marketing message or call to action div classjumbotron h1navbar exampleh1 pthis example is a quick exercise to illustrate how the default static and fixed to top navbar work it includes the responsive css and html so it also adapts to your viewport and devicep pto see the difference between static and fixed top navbars just scrollp p a classbtn btnlg btnprimary hrefcomponentsnavbar rolebuttonview navbar docs raquoa p div div container,"['html', 'css']" +660489,is commenting out a include a safe way to see if it is unneeded i like to keep my files clean so i prefer to take out includes i do not need lately i have been just commenting the includes out and seeing if it compiles without warnings wall wextra pedantic minus a couple very specific ones i figure if it compiles without warnings i did not need itis this actually a safe way to check if an include is needed or can it introduce ub or other problems are there any specific warnings i need to be sure are enabled to catch potential problemsnb i am actually using objective c and clang so anything specific to those is appreciated but given the flexibility of objective c i think if there is any trouble it will be a general c thing certainly any problems in c will affect objective c,['c'] +660584,jqueryui autocomplete in bootstrap modal thisplaying underneath modal i have a jqueryui autocomplete in a bootstrap modal window when i run it normally in the page it works fine but when i try add it into the modal the list appears behind the modal not in fronti have tried variations of the following with no luckmymodalcsszindex 1500 tagsfieldnamecsszindex 50in the modaldatabackdropfalsehere is the source rfq modal div classmodal idmymodal tabindex1 roledialog arialabelledbymymodallabel ariahiddentrue div classmodaldialog stylezindex20 div classmodalcontent div classmodalheader button typebutton classclose datathismissmodal ariahiddentruetimesbutton h4 classmodaltitle idmymodallabelmodal titleh4 div div classmodalbody databackdropfalse script function ps2 var availabletagsps2 label3rd it tech is 20 value20labelseabreeze computers is 14 value14labelseabreeze computers is 14 value14labelseabreeze computers is 14 value14labelseabreeze computers is 14 value14labelseabreeze computers is 14 value14labelseabreeze computers is 14 value14 tagsps2autocomplete source availabletagsps2 tagsps2 autocomplete source availabletagsps2 select function ps2event ui var selectedobj uiitem thisvalselectedobjlabel inputnameps2valselectedobjvalue return false mymodalcsszindex60 tagsps2csszindex20 script input typetext idtagsps2 required autocompleteoff placeholdersearch classinputmed inline formcontrol inputmed input typehidden nameps2 value div classrow div classcolmd6 form roleform div classformgroup input typetext classformcontrol placeholderselect client required div button typesubmit classbtn btnprimary btnlgsubmitbutton form div div classcolmd6 button classbtn btnprimary btnlg datatogglemodal datatargetmymodal a hrefdashboardphpvrfq classlightview sent rfqsa button div div div div classmodalfooter button typebutton classbtn btndefault datathismissmodalcancelbutton div div div div end modal a href datatogglemodal datatargetmymodaldiv classrightcounter nbspdivh2rfqh2a,['jquery'] +660684,get current user id in aspnet identity 20 i just switched over to using the new 20 version of the identity framework in 10 i could get a user object by using managerfindbyidasyncuseridentitygetuserid the getuserid method does not seem to exists in 20now all i can figure out is to use managerfindbyemailasyncuseridentityname which references the username field in the users table in my application this is set to the same as the email field i can see this causing issues down the road when someone needs to update their email is there a way to get the current logged in user object based off an unchanging value such as the id field in the identity 20 framework,"['c#', 'asp.net']" +660694,how would i begin to replicate the custom view controller transition apple uses as the default in ios 7 using ios 7s custom view controller transitions i want to achieve a visual effect similar to apples default view controller transition in ios 7 the one where you can slide to pop a view controller off the stack by sliding it from the left to the right where the top view controller slides off the top of the other with a shadow and the navigation bar shiftsi am having a great deal of difficulty implementing this though most of the tutorials on custom view controllers go with very different effects than the default in order to show what the api is capable off but i want to replicate this onein my subclass for implementing uiviewcontrolleranimatedtransitioning i have the following code for the interactive animation voidanimatetransitioniduiviewcontrollercontexttransitioningtransitioncontext uiviewcontroller toviewcontroller transitioncontext viewcontrollerforkeyuitransitioncontexttoviewcontrollerkey uiviewcontroller fromviewcontroller transitioncontext viewcontrollerforkeyuitransitioncontextfromviewcontrollerkey transitioncontextcontainerview addsubviewtoviewcontrollerview transitioncontextcontainerview addsubviewfromviewcontrollerview fromviewcontrollerviewlayershadowoffset cgsizemake00 00 fromviewcontrollerviewlayershadowcolor uicolor blackcolorcgcolor fromviewcontrollerviewlayershadowradius 50 fromviewcontrollerviewlayershadowopacity 05 uiview animatewithdurationself transitiondurationtransitioncontext delay00 optionsuiviewanimationoptioncurvelinear animations cgrect newframe fromviewcontrollerviewframe newframeoriginx cgrectgetwidthfromviewcontrollerviewbounds fromviewcontrollerviewframe newframe completionbool finished transitioncontext completetransitiontransitioncontexttransitionwascancelled however the shadow code makes it lag tremendously even if i use the new snapshot methods and i cannot figure out how to manipulate the navigation bar at allhas anyone tried to do something similar to this and are able to provide sample codesample project for testing if youd like credit to objcio for the base code,"['ios', 'objective-c']" +660732,customize adb prompt how can i reduce the length of the path printed before the prompt of the shell opened by adb shell my problem is that it is so long that i can no longer see my commands because the does not break the line automatically i would prefer something like the name of the current directory or an abstract code examplesh v on android phone gives me copyright c 2010 thorsten glaser this file is provided under the same terms as mksh minimal systemetcmkshrc for android termvt100 homedata mkshsystembinsh hostnameandroid shellmksh usertypeset xid xx print r xif user id then ps1 else ps1 fifunction precmd typeset e e print n eps1precmduserhostnamepwd ps1 export home hostname mksh ps1 shell term useralias llsalias lal aalias l lalias lol a lfor p in bin do d p continue path p pathppathdoneunset p place customisations above this line,['android'] +661045,quick and practical test to see if a string is random i need to understand if a string is sufficiently random or not can anyone point me in the right directionbackgroundi need to emulate a process behaviour where a process copies itself to a temp location renames itself to a random name and executes itself my ultimate goal is to detect such activity as part of this work i need to test a process name which is a string for randomness i understand that kolmogorov complexity deals with this but it is incomputable what would be quick alternatives variety of entropies lempelziv compression level what i look forstring s1 test process namestring s2 hgoi4dfh3e905jvdouble sensitivity 05 userdefined variable a subjective threshold of randomnessbool b1 seemsrandoms1 sensitivity falsebool b2 seemsrandoms2 sensitivity truebool seemsrandomstring input double sensitivity,['c#'] +661080,how to sync model after using code first from database using entity framework 61 and mvc 5 assumptionsusing ef 61 mvc 5 vs 2013 ci have an existing database model designed in toad dm for sql server and it is very important keep it always updatedsteps and notesusing adonet entity data model i chose code first from database new feature in ef 61 to generate the models note model classes and dbcontext class generated successfuly but no edmx or tt file was generatednext i added a new scaffold item mvc 5 controllers with views using entity framework note success controllers and views generatedquestionfrom now on i do not want to use code first to update my database instead i want the models to be updated based on database changes what to do next if i do not have an edmx file will i not be able to update my model classes from the database,['c#'] +661099,java8 lambdas vs anonymous classes since java8 has been recently released and its brand new lambda expressions looks to be really cool i was wondering if this means the demise of the anonymous classes that we were so used toi have been researching a bit about this and found some cool examples about how lambda expressions will systematically replace those classes such the collections sort method which used to get an anonymous instance of comparator to perform the sort collectionssortpersonlist new comparatorperson public int compareperson p1 person p2 return p1firstnamecomparetop2firstname now can be done using lambdas collectionssortpersonlist person p1 person p2 p1firstnamecomparetop2firstnameand looks surprisingly concise so my question is is there any reason to keep using those classes in java8 instead of lambdaseditsame question but in the opposite direction what are the benefits of using lambdas instead of anonymous classes since lambdas can only be used with single method interfaces is this new feature only a shortcut only used in few cases or is it really useful,['java'] +661150,how to animate height change on bootstrap 3 carousel i know there is this question the proposed solution does not work for bootstrap 3 unfortunately although it does for bs 231 so how would i do it there,"['javascript', 'css']" +661194,how to install pyqt4 on windows using pip i am using python 34 on windows when i run a script it complainsimporterror no module named pyqt4so i tried to install it but pip install pyqt4 givescould not find any downloads that satisfy the requirement pyqt4although it does show up when i run pip search pyqt4 i tried to pip install pythonqt which installed successfully but did not solve the problemwhat am i doing wrong,['python'] +661222,android studio infer nullity while looking at the various options in android studios analyze tab i came across an option called infer nullity i am just curious how this tool is supposed to be used and what can it do for my android studio project,['android'] +661238,how to use java 8 docs in eclipse i am having issues seeing api documentation for java 8 in eclipse heres an example of the problem i am havingcalendar mycalendar calendargetinstanceif i mouse over calendar then i see all the correct documentation however if i mouse over getinstance i get a message saying note this element has no attached source and the javadoc could not be found in the attached javadoci have the javadoc location for rtjar set to i have also tried downloading a local copy of the docs and had the same problem changing the link to the java 7 docs fixes the problem i am havingeclipse seems to be using the wrong anchor style not sure how else to word it when looking for methods when it looks for the getinstance method it checks but it should be checking calendarhtmlgetinstanceall brackets and commas seem to have been replaced by hyphens in the java 8 doc links i experienced this problem with eclipse 43 kepler 43 with the patches for java 8 and now with 44 lunais there a way to update eclipse so that it properly thisplays the docs in the mouse over tooltips,['java'] +661302,when were lvalue references introduced in c when were lvalue references introduced in ca google search for this question returns for me articles with emphasis on rvalue references my question is about lvalue references a single in what version of c were they introduced,['c++'] +661311,python mixin to extend class property trying to figure out how to write some mixins for django management command that will wrap thebasecommandoption list without losing the value of the current class or any inherited classesmixins the goal is to avoid doing basecommandoption list mycommonoptionmixinoption list myothercommonoptionmixinoption list local command options in my commands exampleclass basecomandobject option list default options here rest of basecommand code i define a mixin with some common optionsclass mycommonoptionmixinobject option list some common optionoptions i wish to have available in many commands def getattribute self name values supermycommonoptionmixin self getattribute name if name option list for option in selfoption list if option not in values values option return valuesmaybe i have one more just to cover that case where i have multiple the mixins both override getattribute class myothercommonoptionmixinobject option list maybe i have another mixin i want to define separately tried this does not work with more than one mixin def getattribute self name values supermyothercommonoptionmixin self getattribute name if name option list for option in selfoption list if option not in values values option return values works if the mixin defines the option list under a different name eg mymixin options then access at self mymixin options instead of selfoption listclass mycommandmycommonoptionmixin myothercommonoptionmixin basecommand option list basecommandoption list local defined options i have run into collision if the mixins use the same name for the option list property is there a cleaner way to achieve this goal than naming the option list uniquely inside the mixins and overriding getattribute,['python'] +661354,thiscovering and connecting to a ble device i think this question has been asked in different forms but there is no clear answeri want to be able to thiscover all available ble device and connect to any of them my peripheral device advertises a certain service i read about 32feetnet library and tried to use it but apparently it does not support ble and the only way i can scan my device through this library is to connect to windows first and then do the thiscoveryi also went through this article acuire data by c from ble but it did not work for my device and i could not do any scanning i even bought ti ble dongle and tried their sample app ti sample app but it did not work with my peripheral devicethen i tried to use windows 8 sample code for ble heartrate app it worked fine with a heart rate ble sensor but still i could not get it to work with my peripheral devicei thought there is a problem with my device but there is an app in iphone called lightblue which thiscovers ble devices and can act as a peripheral device too i even used that app but could not get it to work with windowsso my question is is there any way or library or anything for c that i can use to scan ble devices and connect to them and sendreceived datethanks,['c#'] +661382,mojoexecutionexception maven with android i am using android studio with maven 311 and in the package goal it crashes with a mojoexecutionexception i have readed lot of posts but i cannot get the solutionerror error when generating sourcesorgapachemavenpluginmojoexecutionexception at comjaywaymavenpluginsandroidphase01generatesourcesgeneratesourcesmojogeneratergeneratesourcesmojojava593 at comjaywaymavenpluginsandroidphase01generatesourcesgeneratesourcesmojoexecutegeneratesourcesmojojava216 at orgapachemavenplugindefaultbuildpluginmanagerexecutemojodefaultbuildpluginmanagerjava106 at orgapachemavenlifecycleinternalmojoexecutorexecutemojoexecutorjava208 at orgapachemavenlifecycleinternalmojoexecutorexecutemojoexecutorjava153 at orgapachemavenlifecycleinternalmojoexecutorexecutemojoexecutorjava145 at orgapachemavenlifecycleinternallifecyclemodulebuilderbuildprojectlifecyclemodulebuilderjava84 at orgapachemavenlifecycleinternallifecyclemodulebuilderbuildprojectlifecyclemodulebuilderjava59 at orgapachemavenlifecycleinternallifecyclestartersinglethreadedbuildlifecyclestarterjava183 at orgapachemavenlifecycleinternallifecyclestarterexecutelifecyclestarterjava161 at orgapachemavendefaultmavendoexecutedefaultmavenjava317 at orgapachemavendefaultmavenexecutedefaultmavenjava152 at orgapachemavenclimavencliexecutemavenclijava5 at orgapachemavenclimavenclidomainmavenclijava214 at orgapachemavenclimavenclimainmavenclijava158 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava57 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43 at javalangreflectmethodinvokemethodjava606 at orgcodehausplexusclassworldslauncherlauncherlaunchenhancedlauncherjava289 at orgcodehausplexusclassworldslauncherlauncherlaunchlauncherjava229 at orgcodehausplexusclassworldslauncherlaunchermainwithexitcodelauncherjava415 at orgcodehausplexusclassworldslauncherlaunchermainlauncherjava356 at orgcodehausclassworldslaunchermainlauncherjava46 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava57 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43 at javalangreflectmethodinvokemethodjava606 at comintellijrtexecutionapplicationappmainmainappmainjava120caused by comjaywaymavenpluginsandroidexecutionexception android0401 could not execute command cmdexe x c cusershvallsappdatalocalandroidandroidstudiosdkbuildtools1903aaptexe package f nocrunch i cusershvallsappdatalocalandroidandroidstudiosdkplatformsandroid19androidjar m cusershvallsdesktopmyappandroidmanifestxml s cusershvallsdesktopmyappres a cusershvallsdesktopmyapptargetgeneratedsourcescombinedassetsassets m j cusershvallsdesktopmyapptargetgeneratedsourcesr outputtextsymbols cusershvallsdesktopmyapptarget autoaddoverlay result 1073741819 at comjaywaymavenpluginsandroidcommandexecutorfactorydefaultcommandexecutorexecutecommandcommandexecutorjava246 at comjaywaymavenpluginsandroidphase01generatesourcesgeneratesourcesmojogeneratergeneratesourcesmojojava589 28 moreinfo info build failureinfo info total time 165sinfo finished at tue mar 25 223234 cet 2014info final memory 19m184minfo error failed to execute goal comjaywaymavenpluginsandroidgeneration2androidmavenplugin382generatesources defaultgeneratesources on project myapp mojoexecutionexception android0401 could not execute command cmdexe x c cusershvallsappdatalocalandroidandroidstudiosdkbuildtools1903aaptexe package f nocrunch i cusershvallsappdatalocalandroidandroidstudiosdkplatformsandroid19androidjar m cusershvallsdesktopmyappandroidmanifestxml s cusershvallsdesktopmyappres a cusershvallsdesktopmyapptargetgeneratedsourcescombinedassetsassets m j cusershvallsdesktopmyapptargetgeneratedsourcesr outputtextsymbols cusershvallsdesktopmyapptarget autoaddoverlay result 1073741819 help 1error error to see the full stack trace of the errors rerun maven with the e switcherror rerun maven using the x switch to enable full debug loggingerror error for more information about the errors and possible solutions please read the following articleserror help 1 process finished with exit code 1pomxmlxml version10 encodingutf8project xmlnsxsi xmlns xsischemalocation 0 0xsd modelversion400modelversion groupidcomandroidappgroupid artifactidmyappartifactid version10snapshotversion packagingapkpackaging namemyappname properties projectbuildsourceencodingutf8projectbuildsourceencoding platformversion4114 platformversion androidpluginversion382androidpluginversion properties dependencies android annotations dependency groupidcomgooglecodeandroidannotationsgroupid artifactidandroidannotationsapiartifactid version271version dependency dependency groupidcomgooglecodeandroidannotationsgroupid artifactidandroidannotationsartifactid version271version scopeprovidedscope dependency dependency groupidcomgoogleandroidgroupid artifactidandroidartifactid versionplatformversionversion scopeprovidedscope dependency dependencies build finalnameprojectartifactidfinalname pluginmanagement plugins plugin groupidcomjaywaymavenpluginsandroidgeneration2groupid artifactidandroidmavenpluginartifactid versionandroidpluginversionversion extensionstrueextensions plugin plugins pluginmanagement plugins plugin groupidcomjaywaymavenpluginsandroidgeneration2groupid artifactidandroidmavenpluginartifactid version382version configuration sdk platform19platform sdk configuration plugin plugins buildproject,"['java', 'android']" +661411,do strings contain empty substrings everywhere this question arises from a thiscussion originating on this answerin a nutshell the author of the answer 0x499602d2 claimed correctly as i now know that when not skipping whitespace but the next character is a whitespace all extracts with the exception of characters will faili questioned this on the base that i thought that extracting a string should not fail because the stream contained an empty string delimited by the whitespace character at the beginningthis developed into the general thiscussion whether or not there is an empty string at any position in a string eg in between the a and the b of the string ab i say yes 0x499602d2 says no 0x499602d2 suggested that i put this in a question so here i doi copy my main arguments for my position from that thread including the chat partlet us first look at the constant for an empty string in c and c the content is delimited by quotes at the beginning and end so what does the empty string look like you know it you see after the initial quote delimiter directly follows the final quote delimiter the empty string is in between the two quotes which follow directly on each other because the empty string has no characters also look at the c representation that is the sequence of characters followed by the delimiter 0 so what is the representation of the empty string well the characters of the empty string followed by the delimiter which means the first character is the delimiter that is exactly as in the stream case now consider the concatenation of strings where eg the first string is a the second string is empty and the third string is b so what is the concatenation well ab so clearly there is an empty string between the a and the b in ab we explicitly put it there and of course that is true also before the a and after the b that is there is an empty string or two or a million between any two characters of a stringan empty string has no characters and between consecutive characters there are no characters therefore between two characters there is an empty string also see the other arguments i have given before in addition consider regular expressions which match the empty string they also match everywhere for example abc matches ac because b matches the empty string between a and cthere is an empty string ie no characters before the delimiter space just as in the c representation of the empty string there are no characters before the 0 delimiter also note that readline also works the same with the n delimiter if the n follows immediately it does not fail but gives an empty stringi feel unable to identify 0x499602d2s main arguments in the thiscussion so i do not try in order to avoid being unintentionally unfair in the selection you should be able to see them in the comments and possibly in the chat room a i have no idea whether that is accessible by everyone 0x499602d2 if you want you can also yourself add your main arguments after this paragraphthe practical question connected to this is should a welldesigned string extraction function fail if there are no characters before the delimiter as operator for strings does or succeed and return an empty string as readline does,['c++'] +661461,unable to add roles to user with meteor using roles package i am trying to use the roles package available on atmosphere but i cannot get it to work with accountsoncreateuser i can get the example on github when i register a user i want to add a role to them when i test whether the role is assigned it is not picking it upheres my codeserverusersjsaccountsoncreateuserfunctionoptions user var role admin rolesadduserstorolesuser role return userclientpagejstemplatehelloevents click input function var loggedinuser meteoruser if rolesuserisinroleloggedinuser admin consoleloghi admin else consolelogplease log in,['javascript'] +661487,sass not selector i have a not css selector in sass mixin but it does not do anythingcode snippetmixin dropdownposposright notnotip if comptip true if pos right topdropdownwidth 06 include tippospos notip if pos right top 0 leftdropdownwidth 08 the notip class is being generated but no css is being generated for notnotip,['css'] +661498,ios iap how to judge multiple user at the same device for example there are two different game characters in a single iphone devicewe call it a and bfirst app user login as a he perform an iap action the a logout without the purchase completedthen app user login as b then purchase finish event arrival this is the problem how to judge the receipt belongs to a not bi googled found skmutablepaymentrequestdata may be used for solve this problem but apple document told me this is a reserved property and must be nil or else then payment will be rejectrequestdata reserved for future use readonlypropertynonatomic copy readonly nsdata requestdata thiscussion the default value is nil if requestdata is not nil your payment request will be rejectedavailability available in ios 30 and later declared in skpaymenth,"['ios', 'iphone']" +661502,asp net mvc 5 delete file from server view codeif fileexistsservermappathimagescakes htmlthisplayformodelitem modelcakeimage model tastycakesmodelscakes form namedeletephoto actioncakesdeletephoto methodpost htmlantiforgerytoken file name of image to delete without jpg extension input namephotofilename typetext valuehtmlthisplayformodelitem modelcakeimage input typesubmit valuedelete classtiny button form else pfile needs to be uploadedpcontroller codehttppostvalidateantiforgerytokenpublic actionresult deletephotostring photofilename viewbagdeletesuccess false var photoname photoname photofilename var fullpath servermappathimagescakes photoname if fileexistsfullpath filedeletefullpath viewbagdeletesuccess true where it says if fileexists and filedelete the code has squiggly lines underneath it so i am trying to figure out what syntax i need to get thif file deletedhere is a screenshot of my code in the controlleruppdate i have got the code working and created a simple code example on my blog on how i got it working and how the idea came about,"['c#', 'asp.net']" +661542,convert file path to file urlnsurl i am try to file upload operation using afnetworking multipart form data i am getting following error i could find out what is errornsurl urlwithstringfilepathalso used nsurl urlwithstringfilepath filepathurl but does not help mewhen i log filepath string it shows correct path varmobileapplications3cbf5127b2ff49c3ac9816bd0886e7documents20140326105108 slnoma4errornslocalizedfailurereason expected url to be a file url questions how to convert this path string to file url,"['ios', 'objective-c']" +661709,idiomatic successful callback in nodejs by convention in node an asynchronous callback accepts an error as its first argument in case of success the first argument must not be present i personally used to writecallbackundefined resultin that case however i see in other peoples codecallbacknull resultprevailing is it officially documented anywhere which of the two options is idiomatic node are there any significant reasons to prefer one over another,['javascript'] +661789,bonecp throws sqlexception connection is closed when batch inserting into mysql i have been tasked with setting up a project using bonecp with jooq and spring but i have run into some difficulties doing so doing individual inserts into my mysqldatabase works perfectly fine but doing so with 190 0 objects takes almost 20 minutes so to speed it up i want to use batch inserts of 100 at a time instead however this throws the following exceptionorgspringframeworktransactiontransactionsystemexception could not roll back jdbc transaction nested exception is javasqlsqlexception connection is closed at orgspringframeworkjdbcdatasourcedatasourcetransactionmanagerdorollbackdatasourcetransactionmanagerjava288 at orgspringframeworktransactionsupportabstractplatformtransactionmanagerprocessrollbackabstractplatformtransactionmanagerjava849 at orgspringframeworktransactionsupportabstractplatformtransactionmanagerrollbackabstractplatformtransactionmanagerjava826 at orgspringframeworktransactioninterceptortransactionaspectsupportcompletetransactionafterthrowingtransactionaspectsupportjava496 at orgspringframeworktransactioninterceptortransactionaspectsupportinvokewithintransactiontransactionaspectsupportjava266 at orgspringframeworktransactioninterceptortransactioninterceptorinvoketransactioninterceptorjava95 at orgspringframeworkaopframeworkreflectivemethodinvocationproceedreflectivemethodinvocationjava179 at orgspringframeworkaopframeworkcglibaopproxydynamicadvisedinterceptorinterceptcglibaopproxyjava644 at comtheshahinserviceymslinkdataserviceenhancerbyspringcglibb9b6e447creategenerated at comtheshahinintegrationymslinkdataservicetestfooymslinkdataservicetestjava76 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava57 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43 at javalangreflectmethodinvokemethodjava606 at orgjunitrunnersmodelframeworkmethod1runreflectivecallframeworkmethodjava47 at orgjunitinternalrunnersmodelreflectivecallablerunreflectivecallablejava12 at orgjunitrunnersmodelframeworkmethodinvokeexplosivelyframeworkmethodjava44 at orgjunitinternalrunnersstatementsinvokemethodevaluateinvokemethodjava17 at orgjunitinternalrunnersstatementsrunbeforesevaluaterunbeforesjava26 at orgspringframeworktestcontextjunit4statementsrunbeforetestmethodcallbacksevaluaterunbeforetestmethodcallbacksjava74 at orgspringframeworktestcontextjunit4statementsrunaftertestmethodcallbacksevaluaterunaftertestmethodcallbacksjava83 at orgspringframeworktestcontextjunit4statementsspringrepeatevaluatespringrepeatjava72 at orgspringframeworktestcontextjunit4springjunit4classrunnerrunchildspringjunit4classrunnerjava232 at orgspringframeworktestcontextjunit4springjunit4classrunnerrunchildspringjunit4classrunnerjava89 at orgjunitrunnersparentrunner3runparentrunnerjava238 at orgjunitrunnersparentrunner1scheduleparentrunnerjava63 at orgjunitrunnersparentrunnerrunchildrenparentrunnerjava236 at orgjunitrunnersparentrunneraccess0parentrunnerjava53 at orgjunitrunnersparentrunner2evaluateparentrunnerjava229 at orgspringframeworktestcontextjunit4statementsrunbeforetestclasscallbacksevaluaterunbeforetestclasscallbacksjava61 at orgspringframeworktestcontextjunit4statementsrunaftertestclasscallbacksevaluaterunaftertestclasscallbacksjava71 at orgjunitrunnersparentrunnerrunparentrunnerjava309 at orgspringframeworktestcontextjunit4springjunit4classrunnerrunspringjunit4classrunnerjava175 at orgapachemavensurefirejunit4junit4testsetexecutejunit4testsetjava53 at orgapachemavensurefirejunit4junit4providerexecutetestsetjunit4providerjava123 at orgapachemavensurefirejunit4junit4providerinvokejunit4providerjava104 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava57 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43 at javalangreflectmethodinvokemethodjava606 at orgapachemavensurefireutilreflectionutilsinvokemethodwitharrayreflectionutilsjava164 at orgapachemavensurefirebooterproviderfactoryproviderproxyinvokeproviderfactoryjava110 at orgapachemavensurefirebootersurefirestarterinvokeprovidersurefirestarterjava175 at orgapachemavensurefirebootersurefirestarterrunsuitesinprocesswhenforkedsurefirestarterjava107 at orgapachemavensurefirebooterforkedbootermainforkedbooterjava68caused by javasqlsqlexception connection is closed at comjolboxbonecpconnectionhandlecheckclosedconnectionhandlejava459 at comjolboxbonecpconnectionhandlerollbackconnectionhandlejava1270 at orgspringframeworkjdbcdatasourcedatasourcetransactionmanagerdorollbackdatasourcetransactionmanagerjava285 44 moreit may be worth mentioning that this exception is thrown at the very first batch query so no queries have been executed prior to it this is my applicationcontextxml which is based on the one from jooqs tutorial you can find it here xml version10 encodingutf8 standalonenobeans xmlns xmlnsxsi xmlnstx xmlnscontext xmlnsjdbc xsischemalocation contextcomponentscan basepackagecomtheshahin contextpropertyplaceholder locationclasspathapplicationproperties ignoreresourcenotfoundfalsetxannotationdriven transactionmanagertransactionmanagerbean iddatasource classcomjolboxbonecpbonecpdatasource destroymethodclose property namedriverclass valuedbdriver property namejdbcurl valuedburl property nameusername valuedbusername property namepassword valuedbpassword property nameidleconnectiontestperiod value60 property nameidlemaxage value240 property namemaxconnectionsperpartition value30 property nameminconnectionsperpartition value10 property namepartitioncount value3 property nameacquireincrement value5 property namestatementscachesize value100 property namereleasehelperthreads value3beanbean idtransactionmanager classorgspringframeworkjdbcdatasourcedatasourcetransactionmanager property namedatasource refdatasource beanbean idtransactionawaredatasource classorgspringframeworkjdbcdatasourcetransactionawaredatasourceproxy constructorarg refdatasource beanbean classorgjooqimpldatasourceconnectionprovider nameconnectionprovider constructorarg reftransactionawaredatasource beanbean iddsl classorgjooqimpldefaultdslcontext constructorarg refconfig beanbean idjooqtospringexceptiontransformer classcomtheshahinexceptionjooqtospringexceptiontransformerbean classorgjooqimpldefaultconfiguration nameconfig constructorarg index0 refconnectionprovider constructorarg index1null constructorarg constructorarg index2null constructorarg constructorarg index3 list bean classorgjooqimpldefaultexecutelistenerprovider constructorarg index0 refjooqtospringexceptiontransformer bean list constructorarg constructorarg index4null constructorarg constructorarg index5value typeorgjooqsqldialectjooqsqldialectvalueconstructorarg constructorarg index6null constructorarg constructorarg index7null constructorargbeanthis is the code used for saving the records to the mysqldatabase note the outcommented code is the one i use for individual insertsservicepublic class ymslinkdataservice extends baseservice transactional public void createlistymslinkdatarecord records dslbatchinsertrecordsexecute dslinsertintoyms link data yms link datasite id yms link datasite type yms link datatime yms link dataurl yms link datakeywordvalueslinkdatagetsiteid ymslinkdatasitetypesearch systemcurrenttimemillis linkdatageturl linkdatagetkeywordexecute heres the test case from which the error is thrown i am aware that it does not actually test anything at the moment i will do that once it successfully saves to dbtestpublic void batchinsert throws interruptedexception sqlexception int batchcount 0 listymslinkdatarecord batchrecords listsnewarraylist for ymslinkdatarecord ld configurationtoymslinkdatarecordconvert config batchcount batchrecordsaddld if batchcount 100 ldservicecreatebatchrecords batchrecordsclear batchcount 0 ldservicecreatebatchrecordsany help would be greatly appreciated,['mysql'] +661791,updating view with async operation in mvc i am writing a small internal web appi need to do a very long operation which can take about an hour at the press of a button and let the user know once the operation completes with its resultin other words i need the button to start the async operation and refresh the view with the results once it is finished after about an hour runedit the operation could use some sort of a refresh mechanism in the view the result can be sent to the view after a small lag does not have to refresh realtime,['c#'] +661817,how to fix illformed html with html agility pack i have this illformed html with overlapping tagspword1bword2ppword3bword4pthe overlapping can be nested too how can i convert it into wellformed html with html agility pack hap i am looking for this outputpword1bword2bppbword3bword4pi tried htmlnodeelementsflagsb htmlelementflagclosed htmlelementflagcanoverlap but it does not work as expected,"['c#', 'html', '.net']" +661841,global stdstring causing crash on ios i have submitted this as a bug to apple but just for confirmation here is the test codeinclude stringstdstring home directorystdstring buildpathconst stdstring directory const stdstring path ifhome directorycomparedirectory 0 printfin home directoryn return directory pathint mainint char home directory home printfhome sn home directoryc str printfbuildpath sn buildpathbase pathc strwhen built with the latest xcode 51 ios sdk 71 and llvm 51 using libstdc for the c standard library this crashes somewhere in the stdstring implementation on the return line from the buildpath function when run on an ios 51 devicethe output ishome homecrashtest1242 malloc error for object 0x2fe2ac80 pointer being freed was not allocated set a breakpoint in malloc error break to debugthe stack crawlexception type exc crash sigabrtexception codes 0x0 0x0crashed thread 0thread 0 name thispatch queue comapplemainthreadthread 0 crashed0 libsystem kerneldylib 0x34fb8848 kill 81 libsystem cdylib 0x36eae2ae abort 1102 libsystem cdylib 0x36e6937a free 3743 libstdc6dylib 0x3481a93a operator deletevoid 64 libstdc6dylib 0x34806138 stdstring rep m thisposestdallocatorchar const 685 libstdc6dylib 0x34806c04 stdstringreserveunsigned long 1566 libstdc6dylib 0x34806daa stdstringappendchar const unsigned long 707 crashtest 0x094a30 buildpathstdstring stdstring basic stringh21218 crashtest 0x094bda main maincpp259 crashtest 0x09499c start 32with optimisation levels of o1 or less or using libc as the standard library it works as expected it also works as expected on ios 6 or 7 when built with the previous release of xcode 502 ios sdk 70 and llvm 50 it works fine regardless of optimisation settingscommenting out the comparison with the global string also avoids the crashcan anyone see any issues with my code if not any theories for the cause of the crash perhaps a new llvm optimisation that triggers a bug in the libstdc runtime in ios 51another option i can think of is that the optimizer is generating invalid code that would be much more of a worry,"['c++', 'ios']" +661853,if i do nothing in init is it the same as just calling myclass alloc if i have an nsobject subclass which either has no init method or simply does nothing in init is there any difference between an instance created these two waysmyclass instance myclass allocmyclass instance myclass alloc initby does nothing in init i mean idinit self super init if self return selfsince nsobjects init method itself does nothing i cannot see there being any difference but of course the advice is that you must call init to properly prepare an objectheres the snippet from nsobjects init method which got me wondering about thisthe init method defined in the nsobject class does no initialization it simply returns self,['objective-c'] +661882,rails devise omniauth facebook login from ios i have been searching for a solid solution to this problem and came across this so question which kind of matches my predicament but not exactly currently i have my iphone application authenticating with my rails api via basic auth it is just your simple runofthemill devise auth package i then followed the instructions to set up omniauthfacebook for devise and got that working on the browser side the part i cannot figure out how to do is how to send the token received on the iphone side via the facebook ios sdk to the server i want the server to check the users table to see if that facebook user has signed up and create an account for him if he has not then i was thinking the server would generate a random password and send it back to the client device so that i could keep my same basic authentication strategy is this the proper way to implement single sign on for a web app and iphone app how would one go about modifying the server side packages to support authentication via a token sent from the phone,"['ios', 'ruby-on-rails']" +661897,is xa the same as x1a for floats with float a and float inva 1a is x a the same as x invaand what is with this caseunsigned i float v1 static castfloati 42949672950ffloat scl 10f 42949672950ffloat v2 static castfloati sclis v1 equal to v2 for all unsigned integers,"['c++', 'c']" +661931,paypal rest api returning 500 server error for credit card token i am trying to have the paypal rest api create a payment with a credit card stored in the vault but whenever i try and make a payment with the card in the vault paypals api will hang for around half a minute and then give me the following 500 errorexception got http response code 500 when accessing nameinternal service errormessagean internal service error has occurredinformation link service errordebug ide3c779ea99f73this is the code i am using i apologize if there is too much information here i did not know what information was pertinent to my problemphpincludebootstrapphp sample bootstrap file configured with my clientid and secret creates apicontextuse paypalapicreditcarduse paypalapipayeruse paypalapifundinginstrumentuse paypalapidetailsuse paypalapiamountuse paypalapitransactionuse paypalapipaymentuse paypalapiaddressuse paypalapicreditcardtokenusevault trueaddr new addressaddrsetline152 and main staddrsetcityjohnstownaddrsetcountry codeusaddrsetpostal code43210addrsetstateohcard new creditcardalso used paypal sandbox account number herecardsetnumber41cardsetexpire month03cardsetexpire year2019cardsetcvv2123cardsetfirst namejoecardsetlast nameshoppercardsettypevisacardsetbilling addressaddrfi new fundinginstrumentsetting usevault to false here will attempt to make the payment without storing the cc in the vault which works having it use the vault will return a 500 errorifusevault use store the cc in the vault response cardcreateapicontext cctoken new creditcarttoken cctokensetcredit card idresponseid fisetcredit card tokencreditcardtokenelse fisetcredit cardcardpayer new payerpayersetpayment methodcredit cardpayersetfunding instrumentsarrayfiamountdetails new detailsamountdetailssetsubtotal741amountdetailssettax003amountdetailssetshipping003amount new amountamountsetcurrencyusdamountsettotal747amountsetdetailsamountdetailstransaction new transactiontransactionsetamountamounttransactionsetdescriptionthis is the payment transaction descriptionpayment new paymentpaymentsetintentsalepaymentsetpayerpayerpaymentsettransactionsarraytransactiontry var dumppaymentcreateapicontext catch paypalexceptionppconnectionexception ex echo exception exgetmessage php eol var dumpexgetdata exit1if i change usevault to false then the payment will be made and the transaction will show up in the developer sandbox i used this guide at devtoolspaypalcom and it seems to be having the same problem as me i get to step 3 of 4 and it prints that an internal service error has occured,['php'] +661962,optimize code generated by sympy using sympy to find a derivative see this question i came up with this codefrom sympy import from sympyphysicsmechanics import from sympyprinting import print ccodefrom sympyutilitiescodegen import codegenx1 x2 x3 symbolsx1 x2 x3y1 y2 y3 symbolsy1 y2 y3z1 z2 z3 symbolsz1 z2 z3u referenceframeuu1uxx1 uyy1 uzz1u2uxx2 uyy2 uzz2u3uxx3 uyy3 uzz3s1u1u2normalizes2u2u3normalizevcros1 s2fdotvvdf dy2dif y2print ccodedf dy2 assign todf dy2c name c code h name c header codegen df dy2 df dy2 c test headerfalse emptyfalseprint c codewhich yields this beautyinclude testhinclude mathhdouble df dy2double x1 double x2 double x3 double y1 double y2 double y3 double z1 double z2 double z3 return x1 x2y2 y3sqrtpowx1 x2 2 powy1 y2 2 powz1 z2 2sqrtpowx2 x3 2 powy2 y3 2 powz2 z3 2 x2 x3y1 y2sqrtpowx1 x2 2 powy1 y2 2 powz1 z2 2sqrtpowx2 x3 2 powy2 y3 2 powz2 z3 22x1 x2y1 y2y2 y3powpowx1 x2 2 powy1 y2 2 powz1 z2 2 30l20lsqrtpowx2 x3 2 powy2 y3 2 powz2 z3 2 2x1 x2y2 y3y2 y3sqrtpowx1 x2 2 powy1 y2 2 powz1 z2 2powpowx2 x3 2 powy2 y3 2 powz2 z3 2 30l20l 2x1 x2sqrtpowx1 x2 2 powy1 y2 2 powz1 z2 2sqrtpowx2 x3 2 powy2 y3 2 powz2 z3 2 2x2 x3powy1 y2 2powpowx1 x2 2 powy1 y2 2 powz1 z2 2 30l20lsqrtpowx2 x3 2 powy2 y3 2 powz2 z3 2 2x2 x3y1 y2y2 y3sqrtpowx1 x2 2 powy1 y2 2 powz1 z2 2powpowx2 x3 2 powy2 y3 2 powz2 z3 2 30l20l 2x2 x3sqrtpowx1 x2 2 powy1 y2 2 powz1 z2 2sqrtpowx2 x3 2 powy2 y3 2 powz2 z3 2 x1 x2z2 z3sqrtpowx1 x2 2 powy1 y2 2 powz1 z2 2sqrtpowx2 x3 2 powy2 y3 2 powz2 z3 2 x2 x3z1 z2sqrtpowx1 x2 2 powy1 y2 2 powz1 z2 2sqrtpowx2 x3 2 powy2 y3 2 powz2 z3 22x1 x2y1 y2z2 z3powpowx1 x2 2 powy1 y2 2 powz1 z2 2 30l20lsqrtpowx2 x3 2 powy2 y3 2 powz2 z3 2 2x1 x2y2 y3z2 z3sqrtpowx1 x2 2 powy1 y2 2 powz1 z2 2powpowx2 x3 2 powy2 y3 2 powz2 z3 2 30l20l 2x2 x3y1 y2z1 z2powpowx1 x2 2 powy1 y2 2 powz1 z2 2 30l20lsqrtpowx2 x3 2 powy2 y3 2 powz2 z3 2 2x2 x3y2 y3z1 z2sqrtpowx1 x2 2 powy1 y2 2 powz1 z2 2powpowx2 x3 2 powy2 y3 2 powz2 z3 2 30l20l y1 y2z2 z3sqrtpowx1 x2 2 powy1 y2 2 powz1 z2 2sqrtpowx2 x3 2 powy2 y3 2 powz2 z3 2 y2 y3z1 z2sqrtpowx1 x2 2 powy1 y2 2 powz1 z2 2sqrtpowx2 x3 2 powy2 y3 2 powz2 z3 22powy1 y2 2z2 z3powpowx1 x2 2 powy1 y2 2 powz1 z2 2 30l20lsqrtpowx2 x3 2 powy2 y3 2 powz2 z3 2 2y1 y2y2 y3z2 z3sqrtpowx1 x2 2 powy1 y2 2 powz1 z2 2powpowx2 x3 2 powy2 y3 2 powz2 z3 2 30l20l 2y1 y2y2 y3z1 z2powpowx1 x2 2 powy1 y2 2 powz1 z2 2 30l20lsqrtpowx2 x3 2 powy2 y3 2 powz2 z3 2 2y2 y3y2 y3z1 z2sqrtpowx1 x2 2 powy1 y2 2 powz1 z2 2powpowx2 x3 2 powy2 y3 2 powz2 z3 2 30l20l 2z1 z2sqrtpowx1 x2 2 powy1 y2 2 powz1 z2 2sqrtpowx2 x3 2 powy2 y3 2 powz2 z3 2 2z2 z3sqrtpowx1 x2 2 powy1 y2 2 powz1 z2 2sqrtpowx2 x3 2 powy2 y3 2 powz2 z3 2there are several multiple occurrences of the sqrts and pows of the same numbers which could be computed once to improve readability and time of execution but i do not know howq1 do you know of a way to make sympy do this automaticallyq2 do you know of a way to postprocess this code with an other toolq3 can gcc optimize this at compile time why,"['python', 'c']" +661994,restart adb from android studio i previously developed on eclipse and just migrated to android studioeverything works fine it is better and fasteri work on real device and android studio recognizes it without issuebut when i thisconnect and reconnect my device it does not recognize my device anymore i have to exit and restart android studioi cannot find a way to reset adb like eclipse featurecan adb be restarted from within android studio if so how,['android'] +662038,how to map one class with multiple tables in hibernatejavaxpersistance i want to use one class to map three tables i know javaxpersistance provides the secondarytable annotation to map two tables to one class my following code where i have used secondarytable it only allows me to define only one secondary table but i need 3 tables to be used by the same classentitytablename table1secondarytablenametable2public class tableconfig implements serializable private static final long serialversionuid 1l id columnname mac table table1 private string uniqueidentifier,['java'] +662070,listcontains with wildcards c i am trying to match a file name to a partial string in a list the list will have something like 192 in it and the matching file will be x192dat using contains does not match the file name to the string in the list can anyone tell me how to get this done or how to use wildcard chars in the containscode below use this to get a specific list of files private liststring getfilesstring path liststring filenames liststring temp new liststring string mappath servermappathpath directoryinfo di new directoryinfomappath directoryinfo di new directoryinfocinetpubwrootthistribution path for testing locally fileinfo fi digetfiles foreach fileinfo f in fi if filenamescontainsfname this never matches tempaddffullname return temp iv changed the code trying to use the suggestions but it is still not working i will add in the data like i am stepping through the code use this to get a specific list of files private liststring getfilesstring path liststring filenames liststring temp new liststring string mappath servermappathpath directoryinfo di new directoryinfomappath directoryinfo di new directoryinfocinetpubwrootthistribution path for testing locally foreach string s in filenames list has 22891151184 in it fileinfo fi digetfiless s 228 fi systemiofileinfo0 foreach fileinfo f in fi fi systemiofileinfo0 tempaddffullname return temp when i look at the directory where these files are i can seepbset228datpbmrc228datpbput228datpbext228datpbget228datpbmsg228datthis is working now it may not be the most efficient way to do this but it gets the job done maybe someone can post a sample that does the same thing in a better way use this to get a specific list of files private liststring getfilesstring path liststring filenames liststring temp new liststring string mappath servermappathpath directoryinfo di new directoryinfomappath directoryinfo di new directoryinfocinetpubwrootthistribution path for testing locally fileinfo fi digetfiles foreach fileinfo f in fi foreach string s in filenames if fnamecontainss tempaddffullname return temp,"['c#', 'asp.net']" +662072,angular js get ngmodel on ngchange i have the following htmlselect ngmodelcountry ngoptionscname for c in countries ngchangefilterbycountryselectthat is beeing fed by the following object with a list of countriesscopecountries nameafeganistao countryaf nameafrica do sul countryza namealbania countryal namealemanha countryde nameandorra countryad when i change my dropdown value i was expecting my model scopecountry to be updated inside filterbycountry function but it is not what am i missing here,['javascript'] +662154,updating imageview bitmap inside fragment part of my application is using a viewpager with three fragments as a wizard for creating an event the first fragment features a default photograph in an imageview and a button which launches an alertdialog allowing the user to either take a new photo or use an existing photo to associate with the eventlinearlayout xmlnsandroid androidididtesting androidlayout widthfill parent androidlayout heightfill parent androidorientationvertical button androidididbutton1 androidlayout widthmatch parent androidlayout heightwrap content androidlayout marginbottom10dp androidlayout margintop10dp androidtextupdate crawl image androidonclickfireimagedialog imageview androidididimageview1 androidlayout width278dp androidlayout height284dp androidlayout gravitycenter androidsrcandroiddrawablealert light frame linearlayoutonce the user has selected the photo i would like for it to replace the default image the fireimagedialog recieves the path to the chosen image from either the intentaction pick or mediastoreaction image capture as expected that is i have confirmed that the path returned is a valid path to an image at the end of my onactivityresult method i retrieve the fragment containing the code above and call a method to set the bitmap of the imageviewoverride protected void onactivityresultint requestcode int resultcode intent data if requestcode load crawl image if resultcode result ok some code here to handle the two potential sources of the path sets selectedimagepath newcrawlbasicdetailsfragment getsupportfragmentmanagerfindfragmentbyidridnewcrawlbasicdetailsupdateimageselectedimagepath else if resultcode result canceled toastmaketextthis failed to load image toastlength long show and the associated updateimage methodpublic void updateimagestring path if pathlength 0 imageview myphoto imageview getviewfindviewbyidridimageview1 myphotosetimagebitmapdecodesampledbitmapfromfile path myphotogetwidth myphotogetheight my problem is that after all of this the imageview still shows the original default image i have tried to call myphotoinvalidate to force the view to redraw but have not had any luckany suggestions as to what might be going on,['android'] +662240,picasso library stopped working today with facebook graph picture links in my app i use picasso library to load images from urlsit is a nicely working easily importable and usable library and just do the thing i needhowever today it stopped working and not while developping it is stopped working on a compiled apkso after i searched and searched for the reason i just found this buggy thingi use facebook graph urls to load profile pictureshere is one likeprofile pictre the link is actually but it is redirecting to 1464090949 12130273 njpgof course both of url calls working in a browser and you can see the profile picturehowever when i test both links with picasso imageview iv imageviewfindviewbyidridimageview1 url1 not working loads nothing string url1 url2 is the same as url1 i just copied it from a browser and this is working string url2 1464090949 12130273 njpg picassowiththisloadurl2intoivso the conclusion is facebook maybe changed something and from now on picasso cannot load images from graphanybody can suggest me something to make this workof course i can try different libraries but if there is an other way i would be really happy,['android'] +662335,android studio 052 svn checkout not working i am checking a sample in google code it requested me to checkout the source using svn checkout sine i am using android studio i used the subversion checkout options in vcscheckout from version controlsubversion howerver i encountered an error is their something i have done wrongchecking out google sourcecodeerror 2as you can see in this picture you can see the folders and of course the sources but how come it could not find it,['android'] +662337,checking call order across multiple mocks i have three functions that i am trying to test the call order oflet us say that in module modulepy i have the following modulepy def aargs do the first thingdef bargs do a second thingdef cargs do a third thingdef main routine a args a b args b c args c aa args bb args cc argsi want to check that b is called after a and before c so getting a mock for each of a b and c is easy testspymockpatchmoduleamockpatchmodulebmockpatchmodulecdef test main routinec mock b mock a mock test all the things herechecking that each of the individial mocks are called is easy too how do i check the order of the calls relative to one another call args list would not work as it is maintained separately for each mocki have tried using a side effect to log each of the callscalls def register callargs callsappendmockcallargs return mockdefaulta mockside effect register callb mockside effect register callc mockside effect register callbut this only gives me the args that the mocks were called with but not the actual mock that the call was made against i can add a bit more logic testspyfrom functools import partialdef register callargs kwargs callsappendkwargspopcaller none mockcallargs kwargs return mockdefaulta mockside effect partialregister call callerab mockside effect partialregister call callerbc mockside effect partialregister call callercand that seems to get the job done is there a better way though it feels like there should already be something in the api that can do this that i am missing,['python'] +662383,owl carousel would not autoplay i am using the owl carousel on according to their documentation this piece of javascript should workscriptintroowlcarousel most important owl featuresautoplayautoplay 50stoponhover falsescriptbut for some reason it will not autoplay here is the html of the sliderdiv idintro classowlcarousel div classitem first div classcontainer div classrow div classcarouselcaptionleft colourwhite h2title texth2 h1sub title text hereh1 pif you like you can even add a sentence or two herep div div div div classoverlaybgdiv div div classitem second div classcontainer div classcarouselcaptionleft colourwhite h2title texth2 h1sub title text hereh1 pif you like you can even add a sentence or two herep div div div classoverlaybgdiv div div classitem third div classcontainer div classcarouselcaptionleft colourwhite h2title texth2 h1sub title text hereh1 pif you like you can even add a sentence or two herep div div div classoverlaybgdiv divdivfeel free to check the link and see if you can find any problems all help is appreciatedhere is the link to the own carousel documentation,"['javascript', 'html']" +662458,clone of polymer element remove template of polymer element my polymer elementelelabel idnewlabel color0 bgcolorf1f1f1 eleheight30 elewidth50 textname elethisplayinlineblock elefloatleftelelabelbut when i clone this element inner html will removedcan any one help me polymerelement nameelelabel attributestext color eleid elewidth eleheight fontsize bgcolor paddingtop paddingbottom paddingleft paddingright elethisplay elefloat template divlabel stylefontsizefontsizept colorcolor textlabeldiv templatepolymerelement,"['javascript', 'jquery']" +662524,systemwebservicesprotocolssoapexception server did not recognize the value of http header soapaction an exception flows when i was trying to call a method on web servicesystemwebservicesprotocolssoapexception server did not recognize the value of http header soapaction httplocalhost534603developmentmywebserviceasmxgetbasepath at systemwebservicesprotocolssoap11serverprotocolhelperrouterequest at systemwebservicesprotocolssoapserverprotocolrouterequestsoapservermessage message at systemwebservicesprotocolssoapserverprotocolinitialize at systemwebservicesprotocolsserverprotocolfactorycreatetype type httpcontext context httprequest request httpresponse response boolean abortprocessingthe web services namespacewebservicenamespace i did some research and found out that this exception flows because the web services namespace referenced in the project was different from the server web services namespace but i have tried removing web reference and add it again in the project but the result was still the samemy situation was similar to the below articlefrom articleso basically the web service was moved from to but the anamespacea of the web service stayed as because no one changed itthe problem ishow to change the namespace of the web reference,"['c#', 'asp.net']" +662527,how to check all properties of an object whether null or empty i have an object lets call it objectaand that object has 10 properties and those are all strings var myobject new property1property2property3property4is there anyway to check to see whether all these properties are null or emptyso any builtin method that would return true or falseif any single of them is not null or empty then the return would be false if all of them are empty it should return truethe idea is i do not want to write 10 if statement to control if those properties are empty or nullthanks,['c#'] +662566,android voice recognition api offline can someone please help me i am developing an application with voice recognition via recognizerintentwhich android version brought in officially the offline recognition available to apps by api is there any statement about itby what i read until know it is not a choice of the developer if the voice recognition will be done via online service or the offline dictionaries am i right or are there any documented api to set offlinethanks,['android'] +662622,implementing two interfaces with two default methods of the same signature in java 8 suppose i have two interfacespublic interface i1 default string getgreeting return good morning public interface i2 default string getgreeting return good afternoon if i want to implement both of them what implementation will be usedpublic class c1 implements i1 i2 public static void mainstring args systemoutprintlnnew c1getgreeting,['java'] +662693,only send one email with all the errors using nlog with console application using c i want to send only one email with all the errors i get from my c console applicationi have the targetstarget xsitypefile nameheelpadsimport log filenamebasedirlogsheelpadsimportshortdatelog layoutlongdate uppercaselevel callsiteclassnametrueincludesourcepathtruemethodnametrue message target nameheelpadsimport patrick email xsitypemail smtpserverx smtpport25 smtpauthenticationbasic smtpusernamey smtppasswordz enablesslfalse fromd toe layoutlongdate uppercaselevel callsiteclassnametrueincludesourcepathtruemethodnametrue message i have an info rule and an error rulelogger name minlevelinfo writetoheelpadsimport log logger name minlevelerror writetoheelpadsimport patrick email i have several calls in the code for each otherloggerlogloglevelinfo new ad success autoid autoid autoplate autoplateloggerlogloglevelerror continue error 4 autoid autoid,['c#'] +662748,json schema allof with additionalproperties suppose we have schema following schema from tutorial here schema definitions address type object properties street address type string city type string state type string required street address city state type object properties billing address ref definitionsaddress shipping address allof ref definitionsaddress properties type enum residential business required type and here is valid instance shipping address street address 1600 pennsylvania avenue nw city washington state dc type business i need to ensure that any additional fields for shipping address will be invalid i know for this purpose exists additionalproperties which should be set to false but when i am setting additionalproprtiesfalse as in the following shipping address allof ref definitionsaddress properties type enum residential business required type additionalpropertiesfalse i get a validation error checked here level error schema loadinguri pointer propertiesshipping address instance pointer shipping address domain validation keyword additionalproperties message additional properties are not allowed unwanted city state street address type the question is how should i to limit fields for the shipping address part only thanks in advance,['javascript'] +662781,how to print a groupby object i want to print the result of grouping with pandasi have a dataframeimport pandas as pddf pddataframea one one two three three one b range6print df a b0 one 01 one 12 two 23 three 34 three 45 one 5when printing after grouping by a i have the followingprint dfgroupbyapandascoregroupbydataframegroupby object at 0x05416e90how can i print the dataframe groupedif i doprint dfgroupbyaheadi obtain the dataframe as if it was not grouped a ba one 0 one 0 1 one 1two 2 two 2three 3 three 3 4 three 4one 5 one 5i was expecting something like a ba one 0 one 0 1 one 1 5 one 5two 2 two 2three 3 three 3 4 three 4,['python'] +662836,convert json string to jsonresult in mvc we are trying to make mock service to serve json we have plain json strings stored in static files and want to serve them to client as they are without any additional wrapperseg we have json string result code200namejohn lastname doe and we want to get json response on client just like this without any content or data wrapperswe have solution where we use data contracts and deserialize json to c objects but that is a bit complicated and we do not need itthank you,['c#'] +662865,how to execute multiple tasks in parallel in fabric i know that by using p switch or parallel tag i can run task in parallel on multiple hostsi am trying to execute multiple long running tasks in parallel on the same host taskdef task1 long running optaskdef task2 long running optaskdef task3 long running optaskdef backup all executetask1 executetask2 executetask3how can i start task1 task2 and task3 in parallel on the same host by using fabrici know that i can run multiple fab processes with different tasks but i am looking for a solution that involves fabric,['python'] +662880,integrate gitlab and travisci is there a way where i can integrate travisci with giltab or at least logging in travisci using username and password and not github credentials,['ruby'] +662920,approximating an ellipse with a polygon i am working with geographic information and recently i needed to draw an ellipse for compatibility with the ogc convention i cannot use the ellipse as it is instead i use an approximation of the ellipse using a polygon by taking a polygon which is contained by the ellipse and using arbitrarily many pointsthe process i used to generate the ellipse for a given number of point and is the following using c and a fictional polygon classpolygon createellipsepolygoncoordinate center double radiusx double radiusy int numberofpoints polygon result new polygon for int i0inumberofpointsi double percentdone doubleidoublenumberofpoints double currentellipseangle percentdone 2 mathpi point newpoint calculatepointonellipseforanglecurrentellipseangle center radiusx radiusy resultaddnewpoint return resultthis has served me quite while so far but i have noticed a problem with it if my ellipse is stocky that is radiusx is much larger than radiusy the number of points on the top part of the ellipse is the same as the number of points on the left part of the ellipsethat is a wasteful use of points adding a point on the upper part of the ellipse would hardly affect the precision of my polygon approximation but adding a point to the left part of the ellipse can have a major effectwhat i would really like is a better algorithm to approximate the ellipse with a polygon what i need from this algorithmit must accept the number of points as a parameter it is ok to accept the number of points in every quadrant i could iteratively add points in the problematic places but i need good control on how many points i am usingit must be bounded by the ellipseit must contain the points straight above straight below straight to the left and straight to the right of the ellipses centerits area should be as close as possible to the area of the ellipse with preference to optimal for the given number of points of course see jaans answer appearantly this solution is already optimalthe minimal internal angle in the polygon is maximalwhat i have had in mind is finding a polygon in which the angle between every two lines is always the same but not only i could not find out how to produce such a polygon i am not even sure one exists even if i remove the restrictionsdoes anybody have an idea about how i can find such a polygon,['c#'] +662951,in c does the meaning of aij depend on how a is declared suppose i have a twodimensional array grid declared as double grid55 it is my understanding that the following statements are truewhen grid is declared a contiguous block of memory is allocated for 55 doubles no more no lesswhen an element of the array is accessed with the notation gridij this piece of code is actually interpreted as gridi5jon the other hand i know i can also store the same matrix as an array of pointers by writing something likedouble gridgrid doublemallocsizeofdouble5for i0 i5 i gridi doublemallocsizeofdouble5and i actually have a code which does that the problem is that it then proceeds to access the elements of grid just like before with the double subscript notation is this case different in this case is gridij converted to gridij ie to a double dereferenciation that is the only way i can see it happen correctlythis question probably stems from my lack of understanding of the relationship between pointer and array types in ceditok let us see if i got this straightgridij is always converted to gridijthis expression is indeed calculated differently in the two cases because as jim states in his answer pointer arithmetic takes into account the size of the type pointed to nevertheless the correct element is fetched in both casesif and only if grid is a 2d array this expression is further optimized to doublegrid i5j which is possible because the compiler knows that any gridi is actually an array starting at location gridi5but this leaves me with an inescapable conclusion for a 2d array if i set ij0 then i have that grid doublegrid is this correct,['c'] +662982,peer to peer reworking for conference webrtc i have to ask the question again today i am in the course of processing a code to connect to one to one to the code allowing for a group conversation without beating around the bush i have this code calltousers functionconnection var connection connection var ischannelready var isinitiator false var isstarted false var servers null var localstream connectiongetstream var localstreams var localconnection var turnready var remotestreams var remotestream var pcconfig iceservers url stunstunlgooglecom19302 var pcconstraints optional dtlssrtpkeyagreement true var sdpconstraints mandatory offertoreceiveaudio true offertoreceivevideo true var room var socket ioconnect var divelement documentcreateelementdiv divelementsetattributeid remotesvideo documentbodyappendchilddivelement var createroom functionroom room room ifroom consolelogcreate or join to room room socketemitcreate or join room socketoncreated functionroom consolelogcreated room room isinitiator true socketonfull functionroom consolelogroom room is full socketonjoin functionroom consoleloganother peer made request to join room ischannelready true socketonjoined functionroom consoleloguser joined to room room ischannelready true socketonlog functionarray consolelogapplyconsole array var sendmessage functionmessage consolelogclient sending a message message socketemitmessage message windowonbeforeunload functione sendmessagebye var startcall function sendmessagegot user media ifisinitiator maybestart socketonmessage functionmessage consolelogclient received a message message ifmessage got user media maybestart else ifmessagetype offer ifisinitiator isstarted maybestart forvar i 0 i localstreamslength i localstreamsisetremotedescriptionnew rtcsessiondescriptionmessage doanswer else ifmessagetype answer isstarted forvar i 0 i localstreamslength i localstreamsisetremotedescriptionnew rtcsessiondescriptionmessage else ifmessagetype candidate isstarted var candidate new rtcicecandidate sdpmlineindex messagelabel candidate messagecandidate forvar i 0 i localstreamslength i localstreamsiaddicecandidatecandidate else ifmessage bye isstarted handleremoteendcall iflocationhostname localhost requestturnkey4080218913 var maybestart function ifisstarted typeof localstream undefined ischannelready createpeerconnection forvar i 0 i localstreamslength i localstreamsiaddstreamlocalstream isstarted true ifisinitiator docall var createpeerconnection function try localconnection new rtcpeerconnectionpcconfig pcconstraints localconnectiononicecandidate handleicecandidate localconnectiononaddstream handleremotestreamadded localconnectiononremovestream handleremotestreamremoved localstreamspushlocalconnection consolelogcreated rtcpeerconnection catche consolelogexception emessage return var handleicecandidate functionevent ifeventcandidate sendmessage type candidate label eventcandidatesdpmlineindex id eventcandidatesdpmid candidate eventcandidatecandidate else consolelogend of candidates var handleremotestreamadded functionevent consolelogremote stream added var newvideo documentcreateelementvideo newvideosetattributeid mathfloormathrandom 10 1 newvideomuted false divelementappendchildnewvideo attachmediastreamnewvideo eventstream remotestream eventstream remotestreamspushremotestream var handleremotestreamremoved functionevent consolelogdelete var handlecreateoffererror functionevent consolelogcreateoffer error e var setlocalandsendmessage functionsessiondescription sessiondescriptionsdp preferopussessiondescriptionsdp forvar i 0 i localstreamslength i localstreamsisetlocaldescriptionsessiondescription sendmessagesessiondescription var docall function consolelogstart call forvar i 0 i localstreamslength i localstreamsicreateoffersetlocalandsendmessage handlecreateoffererror var doanswer function consolelogsending answer forvar i 0 i localstreamslength i localstreamsicreateanswersetlocalandsendmessage null sdpconstraints var endcall function consoleloghanging up isstarted false forvar i 0 i localstreamslength i localstreamsiclose localstreamsi null sendmessagebye var handleremoteendcall function var requestturn functionturnurl var turnexists false forvar i in pcconfigiceservers ifpcconfigiceserversiurlsubstr0 5 turn turnexists true turnready true break ifturnexists consoleloggetting turn server from turnurl var xhr new xmlhttprequest xhronreadystatechange function ifxhrreadystate 4 xhrstatus 200 var turnserver jsonparsexhrresponsetext consoleloggot turn server turnserver pc configiceserverspush url turn turnserverusername turnserverturn credential turnserverpassword turnready true xhropenget turnurl true xhrsend var preferopus functionsdp var sdplines sdpsplitrn var mlineindex forvar i 0 i sdplineslength i ifsdplinesisearchmaudio 1 mlineindex i break ifmlineindex null return sdp fori 0 i sdplineslength i ifsdplinesisearchopus480 1 var opuspayload extractsdpsdplinesi d opus480i ifopuspayload sdplinesmlineindex setdefaultcodecsdplinesmlineindex opuspayload break sdplines removecnsdplines mlineindex sdp sdplinesjoinrn return sdp var extractsdp functionsdpline pattern var result sdplinematchpattern return result resultlength 2 result1 null var setdefaultcodec functionmline payload var elements mlinesplit var newline var index 0 forvar i 0 i elementslength i ifindex 3 newlineindex payload ifelementsi payload newlineindex elementsi return newlinejoin var removecn functionsdplines mlineindex var mlineelements sdplinesmlineindexsplit forvar i sdplineslength 1 i 0 i var payload extractsdpsdplinesi artpmapd cndi ifpayload var cnpos mlineelementsindexofpayload ifcnpos 1 mlineelementssplicecnpos 1 sdplinessplicei 1 sdplinesmlineindex mlineelementsjoin return sdplines return startcall startcall endcall endcall createroom createroom while the conversation between two users working well then when adding another member it no longer connects to the other two peers although clearly the logs i see that attaches to the same room in the console no errors does anyone would be kind to helpediti am adding server code too if neededvar static requirenodestaticvar http requirehttpvar file newstaticservervar app httpcreateserverfunction req res fileservereq reslisten2017var io requiresocketiolistenappiosocketsonconnection function socket function log var array for var i 0 i argumentslength i arraypushargumentsi socketemitlog array socketonmessage function message loggot message message socketbroadcastemitmessage message should be room only socketoncreate or join function room var numclients iosocketsclientsroomlength logroom room has numclients clients logrequest to create or join room room if numclients 0 socketjoinroom socketemitcreated room else iosocketsinroomemitjoin room socketjoinroom socketemitjoined room socketemitemit client socketid joined room room socketbroadcastemitbroadcast client socketid joined room room,['javascript'] +663010,cc failed with exit status 1 error when install python library like many others i am having issues installing a python library downloaded as a tar then extracted rodolphembppythonlevenshtein0112 rodolphe sudo python setuppy installrunning installrunning bthist eggrunning egg infowriting requirements to python levenshteinegginforequirestxtwriting python levenshteinegginfopkginfowriting namespace packages to python levenshteinegginfonamespace packagestxtwriting toplevel names to python levenshteinegginfotop leveltxtwriting dependency links to python levenshteinegginfodependency linkstxtwriting entry points to python levenshteinegginfoentry pointstxtreading manifest file python levenshteinegginfosourcestxtreading manifest template manifestinwarning no files found matching under directory docswarning no previouslyincluded files matching pyc found anywhere in thistributionwarning no previouslyincluded files matching project found anywhere in thistributionwarning no previouslyincluded files matching pydevproject found anywhere in thistributionwriting manifest file python levenshteinegginfosourcestxtinstalling library code to buildbthistmacosx109inteleggrunning install librunning build extbuilding levenshtein extensioncc fnostrictaliasing fnocommon dynamic arch x86 64 arch i386 g os pipe fnocommon fnostrictaliasing fwrapv mnofusedmadd denable dtrace dmacosx dndebug wall wstrictprototypes wshorten64to32 dndebug g fwrapv os wall wstrictprototypes denable dtrace arch x86 64 arch i386 pipe isystemlibraryframeworkspythonframeworkversions27includepython27 c levenshteinc o buildtempmacosx109intel27levenshteinoclang error unknown argument mnofusedmadd wunusedcommandlineargumentharderrorinfutureclang note this will be a hard error cannot be downgraded to a warning in the futureerror command cc failed with exit status 1as suggested elsewhere i tried entering in terminal archflagswnoerrorunusedcommandlineargumentharderrorinfuture sudo python setuppy install but no successis there a way around this issue that seems to have appeared with xcode 51,['python'] +663015,add type column to sandcastle property table so i am generating a documentation website using sandcastle help file builder everything is generated great however when looking at a page for a class i would like for the properties table which currently has the icon name and description columns see below to include a column for the type of property int bool string etci was reading somewhere about the xsl files that are used for the templates but honestly it was a little overwhelming trying to find exactly what i am looking forso basically i would like to add a column to the above table that lists the type string int etc is that possible thanks,['.net'] +663097,maze solving with python i am trying to make a maze solver and it is working except that instead of the path being marked by o i want it to be marked with v depending on the direction of the path this is the part of the code where it solves the maze def solveselfxy maze selfmaze base case if y lenmaze or x lenmazey return false if mazeyx e return true if mazeyx return false marking mazeyx o recursive case if selfsolvex1y true right return true if selfsolvexy1 true down return true if selfsolvex1y true left return true if selfsolvexy1 true up return true backtracking mazeyx return false this is an example of an unsolved mazes eand this is the solved version of the same maze using the code aboves o o o o o o o o o o o ethe result that i want to get to is s v v vv v v v vv v ehow is it possible to do this,['python'] +663104,how does orderby work with regard to strings in c consider this codevar strings2 new liststring 0 ascii code 48 decimal ascii code 125 decimal var sorted strings2orderbyx xtoarraysorted contains 0 now consider this code all i did was change to var strings2 new liststring 0 ascii code 48 decimal ascii code 46 decimal var sorted strings2orderbyx xtoarraynow sorted contains 0in both cases the 0 comes at the end even though 125 48 what is going on here,['c#'] +663170,how to multiply multiple columns by a column in pandas i would like to havedfincome 1 income 2 dfmtaz proportionreturn those columns multiplied by dfmtaz proportionso that i can set dfmtaz income 1 mtaz income 2 dfincome 1 income 2 dfmtaz proportionbut instead i get income 1 income 2 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 0 nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan 1 nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan 2 nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan ectwhat simple thing am i missingthank you,['python'] +663174,why is the variable name scope necessary i am fairly new to javascript just finished the book eloquent javascript and am currently reading angularjs from oreilly and getting this small snippet of code to work from the book drove me crazy for hours and led me down rabbit holes thinking i messed up somewhere in setting up my environmentthe only difference in the code provided by the angularjs book and the code i typed up was that i left out the in scope in the textcontroller function putting the back in allowed the code to work here was my reasoning for initially leaving it outoh scope is just a variable name local to the function like any other programming language such as java or c because this parameter is just a local variable i can name it whatever i want since whatever argument gets passed into the function will just get passed by value please correct my reasoning and explain why the name of the parameter has to be scopedoctype htmlhtml ngappbody ngcontrollertextcontroller psometextp script srcangularminjsscript script function textcontrollerscope scopesometext you have started your journey scriptbodyhtml,['javascript'] +663206,libgdx helloworld project crashes when run on android emulator i have been trying to get the helloworld project to run as part of learning libgdx using the nightly build libgdxnightly20140322 however i have become quite frustrated because the helloworlddesktop project will work when run as a java application the helloworldhtml project will run as a web application but helloworldandroid simple produces a not very descriptive errori have checked on here looking for similar problems and found android emulator does not launch libgdx project but the solution given does not work with what i have there was also libgdx my first triangle tutorial not working which pointed me to new tutorials to try but no availthe first time i attempted to follow the tutorial on github and the second time games from scratchs libgdx tutorial 1 creating an initial projecti have tried different api levels 8 13 16 19here is the dump of the logfile0328 0341344 etrace622 error opening trace file no such file or directory 20328 034133435 ddalvikvm622 trying to load lib datadatacommemygdxgameliblibgdxso 0x411e95900328 034133445 ddalvikvm622 added shared lib datadatacommemygdxgameliblibgdxso 0x411e95900328 034133445 ddalvikvm622 no jni onload found in datadatacommemygdxgameliblibgdxso 0x411e9590 skipping init0328 034133465 dlibegl622 emulator without gpu support detected fallback to software renderer0328 034133496 dlibegl622 loaded systemlibegllibgles androidso0328 034133535 dandroidruntime622 shutting down vm0328 034133535 wdalvikvm622 threadid1 thread exiting with uncaught exception group0x40a1330328 0341335 eandroidruntime622 fatal exception main0328 0341335 eandroidruntime622 javalangruntimeexception unable to start activity componentinfocommemygdxgamecommemygdxgamemainactivity javalangruntimeexception libgdx requires opengl es 200328 0341335 eandroidruntime622 at androidappactivitythreadperformlaunchactivityactivitythreadjava20590328 0341335 eandroidruntime622 at androidappactivitythreadhandlelaunchactivityactivitythreadjava20840328 0341335 eandroidruntime622 at androidappactivitythreadaccess600activitythreadjava1300328 0341335 eandroidruntime622 at androidappactivitythreadhhandlemessageactivitythreadjava11950328 0341335 eandroidruntime622 at androidoshandlerthispatchmessagehandlerjava990328 0341335 eandroidruntime622 at androidoslooperlooplooperjava1370328 0341335 eandroidruntime622 at androidappactivitythreadmainactivitythreadjava47450328 0341335 eandroidruntime622 at javalangreflectmethodinvokenativenative method0328 0341335 eandroidruntime622 at javalangreflectmethodinvokemethodjava5110328 0341335 eandroidruntime622 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava7860328 0341335 eandroidruntime622 at comandroidinternaloszygoteinitmainzygoteinitjava5530328 0341335 eandroidruntime622 at dalviksystemnativestartmainnative method0328 0341335 eandroidruntime622 caused by javalangruntimeexception libgdx requires opengl es 200328 0341335 eandroidruntime622 at combadlogicgdxbackendsandroidandroidgraphicscreateglsurfaceviewandroidgraphicsjava1180328 0341335 eandroidruntime622 at combadlogicgdxbackendsandroidandroidgraphicsinitandroidgraphicsjava900328 0341335 eandroidruntime622 at combadlogicgdxbackendsandroidandroidapplicationinitializeandroidapplicationjava970328 0341335 eandroidruntime622 at commemygdxgamemainactivityoncreatemainactivityjava150328 0341335 eandroidruntime622 at androidappactivityperformcreateactivityjava50080328 0341335 eandroidruntime622 at androidappinstrumentationcallactivityoncreateinstrumentationjava10790328 0341335 eandroidruntime622 at androidappactivitythreadperformlaunchactivityactivitythreadjava20230328 0341335 eandroidruntime622 11 more,"['java', 'android']" +663302,what is difference between png8 and png24 i want to know about uses of png files there are two formats available for png images one is png8 and the another one is png24 i would like to know that if i use either type in my html page will there be any error or is this only quality matter,"['html', 'css']" +663332,a generic error occurred in gdi at systemdrawingimagesave exceptiona generic error occurred in gdi at systemdrawingimagesavestring filename imagecodecinfo encoder encoderparameters encoderparams at systemdrawingimagesavestring filename imageformat format at systemdrawingimagesavestring filenamecodebyte bitmapdata new byteimagetextlengthmemorystream streambitmapbitmapdata convertfrombase64stringimagetextstreambitmap new memorystreambitmapdatasystemdrawingimage img imagefromstreamstreambitmapimgsavepathwe convert a base64 string into a memorystream and then create a systemdrawingimage imagefromstreamstreambitmapat the end the image is saved in a temp filethe strange thing is that the problem seems to occur when the activity number of concurrent users is high on the web server and the problem is solved temporarily after an iisreset or an application pool recycle garbage collector issue i already checked the permission of the temp folder,"['c#', 'asp.net', '.net']" +663420,core data with icloud is never switching from using local storage 1 i have got icloud set up with core data but it never seems to switch to use the ubiquitous storage from the local storage looking at the icloud panel in xcode i can see the icloud status is idle and i can even see that directories are being created inside my ubiquitous container nspersistentstoreubiquitouscontentnamekey but there is never any activity uploads or downloads on the graphi am only getting the following in the consolepfubiquityswitchboardentrymetadata setuselocalstorage760 coredata ubiquity me3c82877d69ee5968a69c37fd71227462myappusing local storage 1i am expecting it to eventually flip to not use local storage but this never happenssetting the ubiquity log level to 3 i can see the following logs in my console 60pfubiquitysetupassistant canreadfromubiquityrootlocation block invoke1289 coredata ubiquity coordinated read finished for ubiquity root url fileusersmelibrarymobile20documentsvk94x636h2comcompanymyappnspersistentstorecoordinator addpersistentstorewithtypeconfigurationurloptionserror1081 coredata ubiquity post store setup succeded nssqlcore 0x10040bc90 url fileusersmelibrarycontainerscomcompanymyappdatalibraryapplication20supportcoredataubiquitysupportme3c82877d69ee5968a69c37fd71227462myapp33d95e8623314ed69ecffc88e130a38fstoremyappstoredatapfubiquitysetupassistant canreadfromubiquityrootlocation1298 coredata ubiquity read finished 1pfubiquitysetupassistant canreadfromubiquityrootlocation1301 coredata ubiquity read finished 1 1 fileusersmelibrarymobile20documentsvk94x636h2comcompanymyappcoredatamyapfubiquitysetupassistant canreadfromubiquityrootlocation1305 coredata ubiquity blocking for initial sync pfubiquitysetupassistant 0x10021edc0so it seems it is stuck on the blocking for initial sync but i am not sure whydoes anyone know what might be wrong,['ios'] +663467,the use of size t in an array iterator i have learned recently that size t was introduced to help futureproof code against native bit count increases and increases in available memory the specific use definition seems to be on the storing of the size of something generally an arrayi now must wonder how far this future proofing should be taken surely it is pointless to have an array length defined using the futureproof and appropriately sized size t if the very next task of iterating over the array uses say an unsigned int as the index arrayvoid double vector size t vectorlength for unsigned int i 0 i vectorlength i in fact in this case i might expect the syntax strictly should upconvert the unsigned int to a size t for the relation operatordoes this imply the iterator variable i should simply be a size tdoes this imply that any integer in any program must become functionally identified as to whether it will ever be used as an array indexdoes it imply any code using logic that develops the index programmatically should then create a new result value of type size t particularly if the logic relies on potentially signed integer values iedouble foo100int a 4int b 10int c 50int index a b cdouble d foosize tindexsurely though since my code logic creates a fixed bound upconverting to the size t provides no additional protection,"['c++', 'c']" +663496,custom a tooltipcontent of tooltips with datum in thiscretebarchart nvd3js how i can custom a tooltipcontent of tooltips using data loaded into datum in thiscretebarchart nvd3js for example with the following data jason i want to see data3 data4 data5 in tooltipsjsondata key serie1 values data1 1 data2 2 data3 3 data4 4 data5 5,['javascript'] +663502,any speed advantage in javascript es6 const instead of varlet will there be any speed advantage in using the es6 let or const declarations instead the old faithful var,['javascript'] +663533,what happens exactly when a 32bit integer overflows on a 64bit machine the situation is the followinga 32bit integer overflowsmalloc which is expecting a 64bit integer uses this integer as inputnow on a 64bit machine which statement is correct if any at allsay that the signed binary integer 1001101101010110010 is simply negative due to an overflow this is a practical existing problem since you might want to allocate more bytes than you can describe in a 32bit integer but then it gets read in as a 64bit integermalloc reads this as a 64bit integer finding 1001101101010110010 with being a wildcard bit representing whatever data is stored after the original integer in other words it read a result close to its maximum value 264 and tries to allocate some quintillion bytes it failsmalloc reads this as a 64bit integer casting to 01001101101010110010 possibly because it is how it is loaded into a register leaving a lot of bits zero it does not fail but allocates the negative memory as if reading a positive unsigned valuemalloc reads this as a 64bit integer casting to 1001101101010110010 possibly because it is how it is loaded into a register with a wildcard representing whatever data was previously in the register it fails quite unpredictably depending on the last valuethe integer does not overflow at all because even though it is 32bit it is still in a 64bit register and therefore malloc works finei actually tested this resulting in the malloc failing which would imply either 1 or 3 to be correct i assume 1 is the most logical answer i also know the fix using size t as input instead of inti would just really want to know what actually happens for some reason i do not find any clarification on how 32bit integers are actually treated on 64bit machines for such an unexpected cast i am not even sure if it being in a register actually matters,"['c++', 'c']" +663615,c optimization conditional store to avoid dirtying a cache line in the libuv source i found this code the if statement lets the compiler compile it to a conditional store avoids dirtying a cache line if loopstop flag 0 loopstop flag 0can someone explain this a bitwhat exactly is a cache linealso i guess a conditional store is some assembler instruction which checks something and if succeeded writes some value rightwhen does such construct makes sense i guess not always because otherwise the compiler would just always use the conditional store right,['c'] +663680,umbraco umbdebugshowtracetrue not working hello i have in the appsettings of the webconfig file and using umbraco 461i go to page that takes way to long to load initially so i append umbdebugshowtracetrue to the page but it does not output anything that tells me anything about a stack trace i also have the following in the webconfig filetrace enabledtrue requestlimit10 pageoutputtrue tracemodesortbytime localonlytrue within the systemweb taghow do i get information on why a page is taking too long to load initially,"['c#', 'asp.net']" +663771,angularjs how to add multiple ngclass directives here are 2 different ways to use the ngclass directive i need them both on the same element but that does not workusing an object in ngclassdiv ngrepeatitem in 1 2 3 4 5 ngclass first first last last itemdivcorrectly results indiv classfirst1divdiv2divdiv3divdiv4divdiv classlast5divusing an expression in ngclassdiv ngrepeatitem in 1 2 3 4 5 ngclass count index 1 itemdivcorrectly results in div classcount11divdiv classcount22divdiv classcount33divdiv classcount44divdiv classcount55divnow how about use them togetheri need dynamic class names like count n but also need the object syntax for multiple classesi cannot just use 2 ngclass attributes only the first one worksany suggestions,['javascript'] +663781,open app with package name using adb how do i open an app using adb when i know the apps package name but not the component name of the main activity,['android'] +663806,getting info from ips crash report file iave tested my app on iphone 5 and 4s and then i sent my app to tester he has 5s iphone everything was ok after sometime when i added some features to app i sent him another version but now he says that it crashes on launch on my devices everything is ok i asked him to send me crash reports here is ips filebundleidanamemyappapp nameaamyappbug type109nameaamyappos versioniphone os 71 11d167version10 10incident identifier 3916 194crashreporter key 58fd 7399hardware model iphone62process myapp 277path varmobileapplications0ab0 b5bmyappappmyappidentifier namemyappversion 10 10code type arm64 nativeparent process launchd 1datetime 20140327 021039959 0400os version ios 71 11d167report version 104exception type exc crash sigabrtexception codes 0x0 0x0triggered by thread 24last exception backtrace0x1893e2950 0x1958e81fc 0x1893e2890 0x10f09a0 0x195ec0014 0x195ebffd4 0x195ec64a8 0x195ec24c0 0x195ec70f4 0x195ec74fc 0x1960556bc 0x196054cthread 00 libsystem kerneldylib 0x0195fbdca0 0x195fbc0 73281 corefoundation 0x01893a2570 0x1892d80 8287842 corefoundation 0x01893a0764 0x1892d80 8210923 corefoundation 0x01892e16cc 0x1892d80 386044 graphicsservices 0x018efc5c08 0x18efb80 563285 uikit 0x018c412fd8 0x18c3980 5037686 myapp 0x010f1ae8 0x10dc0 8087 libdylddylib 0x0195edba9c 0x195ed80 15004 thread 24 crashed0 libsystem kerneldylib 0x0195fd658c 0x195fbc0 1079161 libsystem cdylib 0x0195f6a804 0x195f080 4034602 libcabidylib 0x0195190990 0x195190 24483 libcabidylib 0x01951adc28 0x195190 1218964 libobjcadylib 0x01958e84d0 0x1958e0 3405 libcabidylib 0x01951ab164 0x195190 1109486 libcabidylib 0x01951a7c 0x195190 1091807 libobjcadylib 0x01958e8314 0x1958e0 335568 corefoundation 0x01893e288c 0x1892d80 10917249 myapp 0x010f099c 0x10dc0 8438010 libthispatchdylib 0x0195ec0010 0x195ebc0 1640011 libthispatchdylib 0x0195ebffd0 0x195ebc0 1633612 libthispatchdylib 0x0195ec64a4 0x195ebc0 4214813 libthispatchdylib 0x0195ec24bc 0x195ebc0 2578814 libthispatchdylib 0x0195ec70f0 0x195ebc0 4529615 libthispatchdylib 0x0195ec74f8 0x195ebc0 4632816 libsystem pthreaddylib 0x01960556b8 0x1960540 581617 libsystem pthreaddylib 0x01960548 0x1960540 5448thread 250 libsystem kerneldylib 0x0195fd6e74 0x195fbc0 1101961 libsystem pthreaddylib 0x01960548 0x1960540 5448thread 260 libsystem kerneldylib 0x0195fd6e74 0x195fbc0 1101961 libsystem pthreaddylib 0x01960548 0x1960540 5448thread 24 crashed with arm thread state 64bit x0 0x0 x1 0x0 x2 0x0 x3 0x01035de7b8 x4 0x02060 x5 0x01035de870 x6 0x06e x7 0x0640 x8 0x0c0 x9 0x040 x10 0x098d956f7 x11 0x0300 x12 0x0 x13 0x0 x14 0x0 x15 0x0195f83dcb x16 0x0148 x17 0x00c8d95a0138084d x18 0x0 x19 0x06 x20 0x01035e0 x21 0x017013b5d8 x22 0x017013b600 x23 0x015d610870 x24 0x01963068e8 x25 0x010010 x26 0x0198d87c40 x27 0x017026c2c0 x28 0x0a fp 0x01035de7f0 lr 0x019605916c sp 0x01035de7d0 pc 0x0195fd658c cpsr 0x0binary images0x10dc0 0x10f7f myapp arm64 d6f1f532dfbc36c497acefc4aa2c7f2f varmobileapplications0ab088e7642542879c4b1eef37e7db5bmyappappmyapp 0x19606c0 0x19608f libxpcdylib arm64 7077afbad955309d8cb9965960c781f3 usrlibsystemlibxpcdylibi was reading a lot of similar questions here and they says i need to symbolicate that ips through terminal but it doesnat work atos command returns that it is canat read myappapp xcrun atos returns same memory address that iam specifying xcrun atos arch arm64 o myappapp 0x1960540 54480x19605405448iam not sure am i need to specify that number but it doesnat work without it toothanks in advance i would appreciate any helpupdateiave figured it out something wrong with nsfilemanager it is acting differently on 64bit and 32 bitfilemanager fileexistsatpathpathtocachedir isdirectoryisdirectoryisdirectory returns no although pathtocachedir is valid directory thatas why i got exceptionbut question is still valid how can i got some more understandable reports from testers,['ios'] +663826,naming bem sub blocks i am using a bem approach to writing html css with this syntaxblocks block name elements block name element name modifiers block name element namemodifieri get confused when i have a block within another block for instance in a header i want the header to be a block that i can reference and the nav and logo to be blocks i want to reference those nav and logo blocks as being the within the site header but how would i write that chaining blocks like block name sub block name seems quite longdoes anyone have a typical way they would write this examplediv clasite header logo a clasite header logo link img clasite header logo image adivnav clasite header main nav ul li clasite header main nav item a clasite header main nav linkhomea li li clasite header main nav item a clasite header main nav linkabout usa li li clasite header main nav item a clasite header main nav linkcontact usa li ulnavdiv clasite header phone p clasite header phone number 5 pdiv,['css'] +663876,why is the restrict keyword not part of c the title says it all i am curious why is the restrict keyword not part of c i do not know much about c and i am still not able to find anything online that would give a reason blocking this does anyone know what terrible things would happen if a c standard would use this keyword similarly to the way c does is it just not needed at allmore explanation it is not about using it perhaps i will not have any benefit from this keyword in my whole life this question is only about curiosity since restrict is part of c since c99 that is 15 yearsread this as welli am interested in technical reasons not opinions like they just did not like it is not cool enough,['c++'] +663886,bug when resizing borderless window with sdl2 i am trying to make an application with a borderless window in sdl2 i have implemented moving and resizing via drag moving works perfectly fine resizing by dragging the bottom and right borders also works fineresizing by dragging the top and left borders functions fine but it has a cosmetic bugbasically if i drag from the left border the right side of the window makes little jumps maybe 12 pixels as i move it dragging from the top border causes the bottom to make little jumps when i stop dragging the window is always in the right position but this bug makes it seem very inelegant the bug exists on linux multiple wmsdes and windows i have not tested on os xi am using sdl setwindowposition and sdl setwindowsize i have tried bypassing sdl and using xmoveresizewindow but it causes the same bugwhile i would strongly prefer not to bypass sdl i would be willing to use xlib andor winapi if i need toheres a snippet of my code mousepos is initialized to current mouse pos newwindowsize initilized to current window size newwindowpos initialized to current window position mwindowresizeoffset variable is where the mouse grabbed the window omitted code for right and bottom borders because the bug does not exist there logic for the top border is the sameif mleftbordergrabbed newwindowposx mouseposx mwindowresizeoffsetx newwindowsizex windowposx newwindowposxsdl setwindowpositionminternalwindow newwindowposx newwindowposysdl setwindowsizeminternalwindow newwindowsizex newwindowsizey,['c++'] +664052,send log errors to a file i developed a website for my graduation however it still only one thing i have do what i want is when the script is installed on a website i want to send the name of the website who has installed my script also whenever there is an error i want to send it to my website so for examplethis website installed my scriptwsecuritydzcommyscripti want to see the path website in an other file in other website for examplewgetlogcommylogsphpthe purpose of this is keep my customers update and give them support and see the errors that happen so i can fix them in next updates,"['javascript', 'php', 'jquery']" +664068,where java static variables are stored in memory class a static int i 10 static int j 20 static void getname where will these variable be stored in memory,['java'] +664186,symfony is there any way to render a twig template using a relative path to the template in the template naming and locations section in the symfony docs it sayssymfony2 uses a bundlecontrollertemplate string syntax for templates this allows for several different types of templates each which lives in a specific locationacmeblogbundleblogindexhtmltwig this syntax is used to specify a template for a specific page the three parts of the string each separated by a colon mean the followingacmeblogbundle bundle the template lives inside the acmeblogbundle eg srcacmeblogbundle blog controller indicates that the template lives inside the blog subdirectory of resourcesviewsindexhtmltwig template the actual name of the file is indexhtmltwigi want to parse a twig template and persist the html into the property of a doctrine entity during my data fixtures bootstrapping process like so let us say it finds dataproductcamera descriptionhtmltwigproductdescriptiontemplate dir sprintf dataproducts descriptionhtmltwig productgetnameproductsetdescription thiscontainergettemplatingrender productdescriptiontemplate array emflushwhich throws the following exception would actually be an absolute pathinvalidargumentexception template name dataproductcamera descriptionhtmltwig is not valid format is bundlesectiontemplateformatengineyes i could move the product description templates to pathtobundleresourcesviews but i am more interested in whether it is possible to circumvent this convention is there a way to give the twig templating engine the relative or absolute path to a twig template and have it render it not having to use the convention bundlecontrollertemplate,['php'] +664190,why is optional declared as a final class i was playing with the following question using java 8s optional with streamflatmap and wanted to add a method to a custom optionalt and then check if it workedmore precise i wanted to add a stream to my customoptionalt that returns an empty stream if no value is present or a stream with a single element if it is presenthowever i came to the conclusion that optionalt is declared as finalwhy is this so there are loads of classes that are not declared as final and i personally do not see a reason here to declare optionalt finaledit as a second question why can not all methods be final if the worry is that they would be overridden and leave the class nonfinal,['java'] +664223,how to add badge on top of font awesome symbol i would like to add badge with some number 5 10 100 on top of the font awesome symbol faenvelope see the picture how it can look like but i can not understand how to put the badge on top of the symbol jsfiddle i would like to have it supported where twitter bootstrap 232 is supported,['css'] +664270,onedimensional array shapes length vs length1 vs length when i check the shape of an array using numpyshape i sometimes get length1 and sometimes length it looks like the difference is a column vs row vector but it does not seem like that changes anything about the array itself except some functions complain when i pass an array with shape length1what is the difference between these twowhy is not the shape just length,['python'] +664284,blueimp gallery loading dynamic content i have successfully implemented blueimp gallery into my website and using html5 data attributes am able to get the lightbox to worka hrefmultimedia3jpg datagallery datatitlecaption datauniqueid3 datathumbnailmultimedia3jpgai use this to load many pictures and users can cycle slide between them pictures may have comments associated with them and different actions the user can take i have added the comment box to the gallery withdiv idblueimpgallery classblueimpgallery blueimpgallerycontrols div claslidesdiv h3 classtitleh3 a classpreva1a a classnextaoa a classcloseaa a classplaypausea ol classindicatorol div classcommentsdivdivi am using the slide event and i want to be able to update the comment box with the appropriate comments for the slide i am having trouble accessing the datauniqueidblueimpgalleryonslide function event index slide consolelogevent consolelogindex consolelogslidei cannot find uniqueid in here at all is it or is there another way to pass this data,['jquery'] +664338,i cannot install paperclip i am new in rails i need to install peperclip and i cannot i have looked every tutorial i can find and i have not been able to find where is the bug i installed the imagemagick and follow all the instruction of githubwhen i runrails generate paperclip club imageni got thisusersmoskirvmgemsruby200p451railstutorial rails 4 0gemsrailties404librailsgeneratorsactionscreate migrationrb13in migration file name protected method migration file name called for paperclipgenerator0x01053fbb68 nomethoderror from usersmoskirvmgemsruby200p451railstutorial rails 4 0gemsrailties404librailsgeneratorsactionscreate migrationrb34in existing migration from usersmoskirvmgemsruby200p451railstutorial rails 4 0gemsthor0191libthoractionsempty directoryrb112in invoke with conflict check from usersmoskirvmgemsruby200p451railstutorial rails 4 0gemsthor0191libthoractionscreate filerb60in invoke from usersmoskirvmgemsruby200p451railstutorial rails 4 0gemsthor0191libthoractionsrb94in action from usersmoskirvmgemsruby200p451railstutorial rails 4 0gemsrailties404librailsgeneratorsmigrationrb36in create migration from usersmoskirvmgemsruby200p451railstutorial rails 4 0gemsrailties404librailsgeneratorsmigrationrb65in migration template from usersmoskirvmgemsruby200p451railstutorial rails 4 0gemspaperclip411libgeneratorspaperclippaperclip generatorrb16in generate migration from usersmoskirvmgemsruby200p451railstutorial rails 4 0gemsthor0191libthorcommandrb27in run from usersmoskirvmgemsruby200p451railstutorial rails 4 0gemsthor0191libthorinvocationrb126in invoke command from usersmoskirvmgemsruby200p451railstutorial rails 4 0gemsthor0191libthorinvocationrb133in block in invoke all from usersmoskirvmgemsruby200p451railstutorial rails 4 0gemsthor0191libthorinvocationrb133in each from usersmoskirvmgemsruby200p451railstutorial rails 4 0gemsthor0191libthorinvocationrb133in map from usersmoskirvmgemsruby200p451railstutorial rails 4 0gemsthor0191libthorinvocationrb133in invoke all from usersmoskirvmgemsruby200p451railstutorial rails 4 0gemsthor0191libthorgrouprb232in thispatch from usersmoskirvmgemsruby200p451railstutorial rails 4 0gemsthor0191libthorbaserb440in start from usersmoskirvmgemsruby200p451railstutorial rails 4 0gemsrailties404librailsgeneratorsrb156in invoke from usersmoskirvmgemsruby200p451railstutorial rails 4 0gemsrailties404librailscommandsgeneraterb11in top required from usersmoskirvmgemsruby200p451railstutorial rails 4 0gemsactivesupport404libactive supportdependenciesrb229in require from usersmoskirvmgemsruby200p451railstutorial rails 4 0gemsactivesupport404libactive supportdependenciesrb229in block in require from usersmoskirvmgemsruby200p451railstutorial rails 4 0gemsactivesupport404libactive supportdependenciesrb214in load dependency from usersmoskirvmgemsruby200p451railstutorial rails 4 0gemsactivesupport404libactive supportdependenciesrb229in require from usersmoskirvmgemsruby200p451railstutorial rails 4 0gemsrailties404librailscommandsrb48in top required from binrails4in require from binrails4in mainsomeone can help methanks,['ruby-on-rails'] +664346,how to share single sqlite connection in multithreaded python application i am trying to write a multithreaded python application in which a single sqlite connection is shared among threads i am unable to get this to work the real application is a cherrypy web server but the following simple code demonstrates my problemwhat change or changes to i need to make to run the sample code below successfullywhen i run this program with thread count set to 1 it works fine and my database is updated as i expect that is letter x is added to the text value in the sectorgroup columnwhen i run it with thread count set to anything higher than 1 all threads but 1 terminate prematurely with sqlite related exceptions different threads throw different exceptions with no thiscernible pattern includingoperationalerror cannot start a transaction within a transaction occurs on the update statementoperationalerror cannot commit no transaction is active occurs on the commit callinterfaceerror error binding parameter 0 probably unsupported type occurs on the update and the select statementsindexerror tuple index out of rangethis one has me completely puzzled it occurs on the statement group rows00 or but only when multiple threads are runninghere is the codeconnection sqlite3connectdatabasemydb detect typessqlite3parse decltypes check same thread falseconnectionrow factory sqlite3rowdef commandsstart id loop over 100 records read the sectorgroup column and write it back with x appended for inv id in rangestart id start id 100 rows connectionexecuteselect sectorgroup from investment where investmentid inv idfetchall if rows group rows00 or msg inv formatcurrent threadname inv id group print msg connectionexecuteupdate investment set sectorgroup where investmentid group x inv id connectioncommitif name main thread count 10 for i in rangethread count t threadtargetcommands argsi100 tstart,['python'] +664374,is there any reason to use the supportv4 library in android i have been working on an app that is targeting android 40 and above with no plans of supporting earlier versions is there any good reasons for me to continue using the support library,['android'] +664615,mongodb 260rc2 and php 145 find id in a simple query like thisa array id array in array valuesids var dumpacursor2 datafind a works in mongodb 249 however in 260rc2 returns thistype mongocursorexceptioncode 17287message cannot canonicalize query badvalue in needs an arraythe output from var dumparray1 id array1 in array10 0 objectmongoid57 1 id string24 52214d60012f8aab278eacb6 1 objectmongoid58 1 id string24 52214d60012f8aab278eaca8 2 objectmongoid59 1 id string24 52214d60012f8aab278eaca7 i wonder if this is a mongo or php relatedthanks,['php'] +664651,djangodebugtoolbarlineprofiler shows only a single line of output no content i have a raspberry pi sitting in a remote location it is hooked up to a small homemade circuit and a temperature probe i have set up the raspberry pi to do a few thingsrun cron jobs every hour to take a temperature reading and store it locally to a sqlite databaserun an nginx web serverrun a uwsgi application serverserve a simple django appin that django app i have a simple view that does the followinghit the db to get the last 300 temperature recordingsput those into a pandas dataframeuse matplotlib to produce a nice svg graph of the recent temperature historyfill out a simple template which thisplays the svg and also a small html table of the recent temperature readingsrendering this view takes 30 seconds a very long time so i wanted to see what was taking so long my guess is that it is all the work related to generating the graphics but to find out i wanted to do some profilingi installed djangodebugtoolbar and also djangodebugtoolbarlineprofiler using pipi have configured them according to the docs as best i understood in particular i have setdebug truetemplate debug debugdebug toolbar patch settings falsemiddleware classes debug toolbarmiddlewaredebugtoolbarmiddleware djangomiddlewarecommoncommonmiddleware djangocontribsessionsmiddlewaresessionmiddleware djangomiddlewarecsrfcsrfviewmiddleware djangocontribauthmiddlewareauthenticationmiddleware djangocontribmessagesmiddlewaremessagemiddleware uncomment the next line for simple clickjacking protection djangomiddlewareclickjackingxframeoptionsmiddlewaredebug toolbar panels debug toolbarpanelsversionsversionspanel debug toolbarpanelstimertimerpanel debug toolbarpanelssettingssettingspanel debug toolbarpanelsheadersheaderspanel debug toolbarpanelssqlsqlpanel debug toolbarpanelsstaticfilesstaticfilespanel debug toolbarpanelstemplatestemplatespanel debug toolbarpanelscachecachepanel debug toolbarpanelssignalssignalspanel debug toolbarpanelsloggingloggingpanel debug toolbarpanelsredirectsredirectspanel debug toolbar line profilerpanelprofilingpanelin addition internal ips is also set properlyi have built my view using classbased views it looks like thisfrom djangoviewsgeneric import templateviewfrom xmodels import tempreading tempseriesimport numpy as npimport pandas as pdimport matplotlibfrom matplotlibfigure import figurefrom matplotlibbackendsbackend agg import figurecanvasagg as figurecanvasimport seaborn as sbnimport stringioclass testviewtemplateview template name xtesthtml def get context dataself kwargs upstairs tempseriesobjectsgetnameupstairs upstairstemps upstairstempreading setallorder bytimestamp300 frame pddataframelistupstairstempsvalues frameset indextimestamp inplacetrue matplotlibrcparamssvgfonttype none fig figure ax figadd subplot1 framevalueplotaxax axget xaxisgridcolorw linewidth1 axget yaxisgridcolorw linewidth1 figsetfacecolorw canvas figurecanvasfig imgdata stringiostringio canvasprint svgimgdata imgstr imgdatagetvalue context supertestview selfget context datakwargs contextsvgtext imgstr contexthtmltable frame5to html return contextthe code i am most interested in profiling is get context datawhen i load the page the debugtoolbar does in fact show up and the profiling panel is shown but all i see ismethod thisable of lsprofprofiler objectsheres a screenshot of the page as it first loadsand heres how it looks on the profiling pageit does not seem like it is doing any lineprofiling at all i was expecting to see timed results for every line within my classbased view in particular for each line within the get context data function whats going on any help much appreciatededit on 42just as a test i wrote up a dummy view that does not use classbased views and this seems to work just fine heres the new nonclassbasedviewdef testview2request df pddataframea nprandomrandn10 b nprandomrandn10 htmltable dfto html context contexthtmltable htmltable return renderrequest xtest2html contextand that produces the following result in the profiling paneso that seems to be working fine is there some subtlety i am missing about how debugtoolbarlineprofiler works with classbased views in the docs it suggests it will profile any method on the class that does not start with an underscore is that incorrect,['python'] +664658,android studio supplied javahome is not a valid folder i decided to update my jdk to java 8 and installed to the default location of cprogram filesjavajdk180 with a jre subdirectoryi was not sure how android studio worked out the jdk location so i decided to launch it and see i got the following messagefailed to complete gradle executioncause supplied javahome is not a valid folder you supplied cprogram filesjavajdk170 45i updated my java home environment variable both for system and user to point to the new path and tried adding it to my path variable as well but every time i attempt to build in android studio i get the same message the quoted path is nowhere to be found in my environment variables though so where is it getting it from and how can i change itthanks,['java'] +664710,kiosks in windows 8 running regular software nonwindows store app my company operates using public kiosks these kiosks are running windows 8 and though they are secure they are certainly not as secure as the kiosks aka atms you would see at a bank the reason for running windows 8 is to take advantage of the new kiosk feature that microsoft recently introduced however it seems that the os only allows operation in this kiosk mode if the software that is being run or intended to be run is available on the windows store as an applicationthe software required is not able to be put out to the windows store at this moment but i would still like to take advantage of the kiosk feature how can i use the kiosk feature and still run the desired application the official ms term for the kiosk mode is assigned accesswe do try to lock down the kiosks as much as possible by giving least permission user access as well as booting the software on startup in addition we bitlock whenever possible however there is still a delay in booting the software and someone really determined the surf the web could very potentially do soi am aware that microsoft had set the assigned access rule for a windows store app but i am still looking for any potential workarounds even ways to make a windows store app really quickly that is only available for my usage third party software is welcome but any suggestions that can help our case is appreciatedsurely playing around in active directory gpedit and registry will get closer to what i want to achieve one of the main problems i am facing is that the windows desktop metronic ui will load before the application loads whereas in kiosk mode see here boot time is quickerusers use this launch time for time to check time to use attacks so even with great customization i am left with the problem that it will never be as efficient as ms could make it in the end i would leave that to ms for optimal resultsmany people are searching for this answer i am sure and any help is appreciatedtldr how do you use the windows 81 kiosk feature without having a windows store app but do have software,['c#'] +664751,gradle assembledebug takes some time before loading the app i migrated yesterday to android studio 5x from eclipse it is nicehowever when i run the app to compile and install it into my phone it takes more time than eclipsei click run and it starts making the app the tasks say grandle executing tasks mypackageassembledebug upon completion is says grandle invocation completed successfully in x min x sec then it loads itthe problem is that it sometimes might take just 20seconds but other times 23 minutes which is annoying waiting time is this execution necessary to have it always run before each compiling can i close it or reduce its timei am sorry if this question is not accurate but i am not familiar how grandle fully works in as,['android'] +664877,revoke token generated by usertokenprovider in aspnet identity 20 is there a way to revoke for example an email conformation token generated by an usermanager in asp net identity 20contexti would like to give the user the possibility to resend an confirmation email to do this i generate a new token with usermanagergenerateemailconfirmationtokenasyncuserid and send an email with the new generated token unfortunately when i do this the previously generated tokens are still working is there a way to revoke them example codein the usermanager classmanagerusertokenprovider new dataprotectortokenproviderapplicationuseroptionsdataprotectionprovidercreateaspnet identityin the accountcontrollervar user await usermanagerfindbyemailasyncemail all generated tokens below will work to confirm the email i only want the last token to be valid when confirming the email addressvar token1 await usermanagergenerateemailconfirmationtokenasyncuseridvar token2 await usermanagergenerateemailconfirmationtokenasyncuseridvar token3 await usermanagergenerateemailconfirmationtokenasyncuseridvar token4 await usermanagergenerateemailconfirmationtokenasyncuseridvar token5 await usermanagergenerateemailconfirmationtokenasyncuseridvar result await usermanagerconfirmemailasyncuserid token5information about the storage location of the generated token and how these tokens are generated are also welcomei will be grateful if you can send me this information,"['c#', 'asp.net']" +664919,difference between destroy and delete what is the difference between modeldestroy and modeldelete for examplemodelfind bycol foodestroy allandmodelfind bycol foodelete alldoes it really matter if i use the one or the other,['ruby-on-rails'] +665023,how to reuse code between angularjs client and nodejs server what are the bestpractices in order to reuseshare code between an angularjs client and a nodejs serveri implemented an angularjs application now i need to implement a restfulserver providing the client with data some clientside angular services could be reused on server as for example thirdparty restfulclients to facebookgoogletwitter which use intensively the angular dependency injection and which are dependent on http q and many other servicesideally as i really like the dependency injection framework included in angularjs i would find very nice to have a kind of serverframework based on angularjs a serverframework that includes the dependency injection framework and all angularservices that are not related to ui and adding required serverside functionality like routing and authentication but unfortunately i did not find any solution going that way please tell me if such a framework existsso what would be an alternative in order to at least enable code reuse between the client and the server particularly enabling code reuse for code depending on http q and other angularjs services included in the angular framework and angularthirdparties like angularcache,['javascript'] +665038,understanding the ngrepeat track by expression i am having difficulties understanding how the track by expression of ngrepeat in angularjs works the documentation is very scarce can you explain what the difference between those two snippets of code is in terms of databinding and other relevant aspectswith track by indexnames is an arraydiv ngrepeatkey value in names track by index input ngmodelvaluekey divwithout same outputnames is an arraydiv ngrepeatkey value in names input ngmodelvaluekey div,['javascript'] +665040,empty pseudo class issue with addedremoved content and sibling combinators i am trying to set style for a div following an empty ulthis is simple code i am currently testing os is win7basic jsfiddle demohtmlbutton classbtnaddadd new libuttonbutton classbtnremoveremove last libuttonululdivshould be red if ul is emptydivcssulempty div colorred jquery not relevant to issue just for testing purposebtnaddonclick function ulappendlililibtnremoveonclick function ulfindlilastremoveexpected behaviourin all major browsers when adding element to ul style set for empty ul following div should not be applied when removing all li style should be reapplied to targeted divcurrent behaviourfirefox handles it with no problem get expected resultchrome removes red color for following div when ul is no more emptybut does not reapply it when ul is empty again removing all lis fromulie1011 just apply css empty pseudoclass as by default not reacting to any content added or removedgoogling it i have find some workarounds but most seem outdated and none fix issue here none i cannot find at leastfor chrome i have found that setting a css rule empty for ul fixes it but really i do not know whats going on ulempty ya this is an empty css rule i guess now it forces an ui repaint on chrome fixed jsfiddle for chromeunfortunatley this does not fix behaviour on ie1011so anyone knows a way to make it works on all major browsersupdate 1seems like bug is related to next sibling selector even using does not give consistent result on chrome but if applying style directly to empty element all seems to work correctly on all browsers but my goal here is to target sibling element of empty element not the empty element directlyupdate 2forcing an ui redraw fixes it on all browsers eg using bodyhideshow0 once content has been updated see demo forcing redrawbut i would really more appreciate a fix which does not involve any javascript codethe question now could be how can i force ie1011 to repaint ui using only css hoping this is a relevant question regarding this issue,['css'] +665047,javascript not working in uiwebviews button onsubmit where as safari works fine i am using uiwebview in my app with load request of http url webpage loaded url without fail but which has the button with action as java scriptproblem is onclick of submit nothing happens and no error in console and uiwebview delegates also not fired including error delegatethat button just act like image view where as submit button onclick responded well in mobile safari app below i have attached partial view source code of my http urldoctype html public w3cdtd xhtml 10 transitionalen html xmlnshead idhead1link hrefapp themescommoncss relstylesheet typetextcss script srcscriptsitecommonjs typetextjavascript scriptlink hrefapp themesdefaultstylecss typetextcss relstylesheet title change passwordtitleheadbody form methodpost action10470 onsubmitjavascriptreturn webform onsubmit idform1div classaspnethiddeninput typehidden name tsm hiddenfield id tsm hiddenfield value2gfwlgu9atlfixrdsxrzcja58 1t5f8hsleazm4zqwk1 input typehidden name eventtarget id eventtarget value input typehidden name eventargument id eventargument value input typehidden name viewstate id viewstate valuewepdwullte5ndu5nty1mjypzbyczg9kfgicaw9kfgicbw9kfggcaw9kfgicaq8wah4evgv4daxpavbszwfzzsbwcm92awrlihrozsblbwfpbcbhzgryzxnzihlvdsb1c2vkihrvihjlz2lzdgvyihlvdxigywnjb3vudcbhbg9uzyb3axroihlvdxigy3vycmvudcbwyxnzd29yzc4gifdozw4gy2hhbmdpbmcgew91cibwyxnzd29yzcwgcgxlyxnligjlihn1cmugdg8gzm9sbg93ihrozsbwyxnzd29yzcbydwxlcybzzxqgzm9ydgynkgew91cibhzg1pbmlzdhjhdg9ylmqcbq9kfgicaq8pfgifaauorw1hawwgqwrkcmvzczpkzaihd2qwbmypzbycagepdxychwafdu9szcbqyxnzd29yzdpkzaicdw8wah8abqlqyxnzd29yzdpkzaihdw8wah8abrfdb25maxjtifbhc3n3b3jkomrkagkpzbyeagepdxyehwafdljlc2v0ifbhc3n3b3jkhgdwaxnpymxlagrkagipdxyehwafbln1ym1pdb8bz2rkzkptqvpjfwmjqfvdhzirxesckrneikkdgksgezv0b58z divscript typetextjavascriptcdatavar theform documentformsform1if theform theform documentform1function dopostbackeventtarget eventargument if theformonsubmit theformonsubmit false theform eventtargetvalue eventtarget theform eventargumentvalue eventargument theformsubmit scriptscript srcwebresourceaxdd0ynolelc71f7mu1kdn0ejq2ampt635152212760076874 typetextjavascriptscriptscript srcscriptresourceaxddc93c ynvr2d5xbofy3u48vv2irmvokipk hrlj8c5lxdzb6nfs51rybfdjdwwblnlsxz0kwhxpojwlpoqq2ampt1e961a8d typetextjavascriptscriptscript srcscriptresourceaxddcbz 3hbd tfinakqohxpx7jalh5uyyeo3owka0ryfcntbdsbtly7w2hgwtke5dij0amptf81f1a403 typetextjavascriptscriptscript srcscriptresourceaxddcbz 3hbd tfinakqohxpx7jalh5uyyeo3owka0ryfcmlwqdqfxgda2j9xrfke5rz0amptf81f1a403 typetextjavascriptscriptscript srcactionspassword10470 tsm combinedscripts trueampv2gfwlgu9atlfixrdsxrzcja58 1t5f8hsleazm4zqwk1amp tsm bundles ampcdnfalse typetextjavascriptscriptscript srcscriptresourceaxddcbz 3hbd tfinakqohxpxwks3uqxfzxczj62hgx0hvk9oqfljrnodhbkkd4rnqkvawnoexosrlyohfauxrwaw2amptf81f1a403 typetextjavascriptscriptscript srcscriptresourceaxddcbz 3hbd tfinakqohxpxyqbdyswiciljxgxgkbjz5v ool5bgqum2ewmqjqibs fjczndx5yt8eyyx12l3wq2amptf81f1a403 typetextjavascriptscriptscript typetextjavascriptcdatafunction webform onsubmit if typeofvalidatoronsubmit function validatoronsubmit false return falsereturn truescript,"['javascript', 'ios', 'objective-c']" +665068,importing eccbased certificate from the windows certificate store into cngkey how can i get the publicprivate keys from an eccbased x509certificate2s into cngkeys for use with ecdsacng and ecdiffiehellmancngi am currently using rsa 2048 bit key pairs to signencrypt stuff i am doing this by pulling the certificates from the x509store where they are securely stored with private keys marked as nonexportable i would like to convert the current implementation to use ecdsa and ecdh so that i can use smaller key sizes for equivalent securityi have successfully generated ecc certs using opensslopenssl ecparam out privatepem name prime256v1 genkeyopenssl req new key privatepem x509 nodes days 365 out publicceropenssl pkcs12 export in publiccer inkey privatepem out exportpfxi have successfully installed the above generated certs in to the cert store i can retrieve them by thumbprint but the crypto providers for the private and public keys throw algorithm not supported exceptions instead i understand i am supposed to use ecdsacng and ecdiffiehellmancng to signencrypt but these deal in cngkeysbouncy castle is not an option because it requires the private keys to be exportableclr security will return me a cngkey pair via getcngprivatekey but it cannot be used with ecdsa because the key returned by clrsecurity is an ecdh key furthermore clr security does not give me a way to get just the public key from an x509certificate2 for signature verification where i do not even have or need the private key of the signerany ideas i am at my wits end any help would be much appreciated,['.net'] +665133,cartesian product in rxjava is it possible to get cartesian product of two observables in rxjavasomething like thisa 123b aba x b 1 a 1 b 2 a 2 b 3 a 3 b,['java'] +665136,regex replace underscore lowercase with uppercase i have wondering is there a regex pattern that i could use to convert a pattern which is an underscore and a lowercase letter into an uppercase letter i am trying to generate fieldnames for a java bean from a sql statement at the moment the db columns areload idpolicy idpolicy numberbut i would like to the java field names to beloadidpolicyidpolicynumberi have tried with this regex fiddle,['java'] +665352,how to use bigvideojs inside of a div i am trying to contain bigvideojs to a single div such as a hero unit but it continues to takeover the body background i am using the example code on the bigvideojs homepage script typetextjavascript var bv function initialize bigvideo bv new bigvideo bvinit bvshowambienttrue scripti tried doing something like this script typetextjavascript var bv function initialize bigvideo bv new bigvideo container videowrap bvinit bvshowambienttrue script,['jquery'] +665364,wampserver two phpini files i was looking for a way to change the max file size in phpmyadmin mysql imports i solved it after thiscovering there were two phpini files one is located at cwampbinapacheapache244bin considering the default install path while the other one is at cwampbinphpphp5416 the funny aspect here is that when i want to change variables i should pay attention to the apachelocated phpini file instead of the phplocated one and here comes my question why why are there two phpini files instead of one i must even look at both files depending on what do i need to change and i am never sure what file should i look but by trial and error whats the purpose and when should i look either file,['php'] +665466,can promises have multiple arguments to onfulfilled i am following the spec here and i am not sure whether it allows onfulfilled to be called with multiple arguments for examplepromise new promisefunctiononfulfilled onrejected onfulfilledarg1 arg2such that my codepromisethenfunctionarg1 arg2 would receive both arg1 and arg2i do not care about how any specific promises implementation does it i wish to follow the w3c spec for promises closely,['javascript'] +665474,ios mkmapshapshotter completion block is not always being called i am trying to use the new ios7 mkmapsnapshotter to generate a static map image whenever my app needs a map i call the followingmkmapsnapshotter snapshotter mkmapsnapshotter alloc initwithoptionstheoptions autoreleasethispatch queue t aqueue thispatch get global queuethispatch queue priority background 0debuglogsnapshotter allocated and run on queue snapshotter aqueuesnapshotter startwithqueueaqueue completionhandlermkmapsnapshot snapshot nserror error debuglogsnapshotter completion block snapshotter perform selector on main thread to set selfimageviewimage shanpshotimagein most cases this is working great however sometimes it seems like the device gets overloaded with requests for maps and then it stops rendering in my log file i will see the first log statement about the snapshotter allocated but never see the snapshotter completion block messageis it possible that my requests are never executed off of the thispatch queue has anyone ever had this problem,['ios'] +665501,bootstrap fullwidth textinput within inlineform i am struggling to create a textbox that fits the entire width of my container areadiv classrow div classcolmd12 form classforminline roleform input typetext classformcontrol inputlg idsearchchurch placeholderyour location city state zip button typesubmit classbtn btnlgsearchbutton form divdivwhen i do the above the two form elements are inline as i expect but do not take up more than a few columns at best hovering over the colmd12 div in firebug shows it taking up the expected full width it is just the text input that does not seem to fill i even tried adding an inline width value but it did not change anything i know this should be simple just feeling really dumb nowhere is a fiddle edit the selected answer is thorough in every way and a wonderful help it is what i ended up using however i think my initial issue was actually a problem with the default mvc5 template within visual studio 2013 it contained this in sitecssinputselecttextarea maxwidth 280pxobviously that was blocking the textinput from expanding appropriately fair warning to future aspnet template users,"['html', 'css']" +665503,build release mode in android studio how do i build my app in release mode in android studio for publishing to google play store it is not obvious to me if i use the export signed app wizard does it automatically build in release mode how do i verify if the app is built in release mode successfully,['android'] +665567,looking for a first and last class for grouping items with javascript my requirement is slightly different from the traditional method for get first and last method so i am asking expert helpi will explain with code samplemy code structure isdiv classwrapdiv classgroupadivdiv classgroupadivdiv classgroupadivdiv classgroupadivdiv classgroupbdivdiv classgroupbdivdiv classgroupbdivdiv classgroupadivdiv classgroupadivdiv classgroupadivdivwhen i use a jquery method like belowdivgroupafirstaddclassfirstdivgroupalastaddclasslastresult is likediv classwrapdiv classgroupa firstdivdiv classgroupadivdiv classgroupadivdiv classgroupadivdiv classgroupbdivdiv classgroupbdivdiv classgroupbdivdiv classgroupadivdiv classgroupadivdiv classgroupa lastdivdivbut i want the result should be like below with first and last class for each group div classwrapdiv classgroupa firstdivdiv classgroupadivdiv classgroupadivdiv classgroupa lastdivdiv classgroupbdivdiv classgroupbdivdiv classgroupbdivdiv classgroupa firstdivdiv classgroupadivdiv classgroupa lastdivis it possible with javascript or jquery,"['javascript', 'jquery']" +665620,add external jar file in cordova 340 application i am creating two custom plugins for android use this plugin described in my pluginxml my pluginxml file like xml version10 encodingutf8plugin xmlns xmlnsandroid idcommymybiometric version12 namemybiometricname descriptionmybiometric plugindescription licenseapache 20license keywordsmediauploadkeywordsengines engine namecordovaandroid version340 engines jsmodule srcwjsmedia2js namemedia2 clobbers targetmediarecstartrecord jsmodule jsmodule srcwjsvoiceuploadjs namevoiceupload clobbers targetvoiceupload jsmodule android platform nameandroid configfile targetresxmlconfigxml parent feature namemedia2 param nameandroidpackage valuecommymybiometricaudiohandler feature feature namevoiceupload param nameandroidpackage valuecommymybiometricuploadhandler feature configfile configfile targetandroidmanifestxml parentmanifestapplication activity androidnamecommymybiometricmybiometric androidlabelstringapp name androidscreenorientationportrait androidconfigchangesorientationscreensizekeyboardhidden activity configfile sourcefile srcplatformsandroidsrccommypluginsaudiohandlerjava targetdirsrccommymybiometric sourcefile srcplatformsandroidsrccommypluginsuploadhandlerjava targetdirsrccommymybiometric sourcefile srcplatformsandroidsrccommypluginsapplogjava targetdirsrccommymybiometric sourcefile srcplatformsandroidsrccommypluginsmyresponsehandlerjava targetdirsrccommymybiometric sourcefile srcplatformsandroidsrccommypluginsrecorderjava targetdirsrccommymybiometric sourcefile srcplatformsandroidsrccommypluginsvoicebiometricclientjava targetdirsrccommymybiometric sourcefile srcplatformsandroidsrccommypluginsvoicebiometricclientusagejava targetdirsrccommymybiometric platformpluginafter build and run the project the media2 plugin is working fine but when i call the voiceupload plugin its return the class not found error for voice upload i am using androidasynchttp144jar i add the jar file into libs folder i added manuallyhow to fix this issue,"['java', 'android']" +665621,how to set same date for all the resources column in resourceday view using fullcalendar i implementing resourceday view to single day for events using fullcalendar when i split the resources columni get different start date and end date but i want to same date all the resources column i mean one date with different resourceplease help me how fix this problem my code for getting resourceday view as follows calendarfullcalendar header left prevnext today center title right defaultview resourceday slotminutes 10 selectable true selecthelper true editable true contentheight 530 resources php echo json encodereturn resource events php echo json encodereturn arr select functionstart end allday newsessionshow calendersizecssmarginleft 0px width 648px var currentdate fullcalendarformatdatestart ymmd var agendadate fullcalendarformatdatestart d m d y agendadatetextagendadate var starttimesetfullcalendarformatdatestart ymmd hhmm tt var endtimeset fullcalendarformatdateend ymmd hhmm tt please help me how to set same date for all the resource column,"['javascript', 'jquery']" +665629,optional parameters in web api attribute routing i want to handle post of the following apicallv1locationdeviceidappidadditional parameter are coming from the postbodythis all works fine for me now i wnat to extend my code by allowing deviceid andor appid andor bodydata to be nullv1locationdeviceidv1locationappidv1locationthese 3 urls should responded by the same routemy first approach bodydata requiredroutev1locationdeviceidappid name addnewlocationpublic location fromuser poststring deviceid null string appid null frombody location fromuser bodydata return repositoryaddnewlocationdeviceid appid bodydatathis does not work optional parameters must be at the endnext tryroutev1locationdeviceidappid name addnewlocationpublic location fromuser postfrombody location fromuser bodydata string deviceid null string appid nullnow my function addnewlocation get always an bodydatanull even if the call send the bodyfinally i set all 3 parameter optionalroutev1locationdeviceidappid name addnewlocationpublic location fromuser poststring deviceid null string appid null frombody location fromuser bodydata nulldona t work optional parameter bodydata is not supported by formatterparameterbindingwhy i want such a solution with the optional parametersmy controller handles just the adding of a new location via a posti want to send on wrong data my own exceptions or error messages even if the call has missing values in this case i want to be able to decide to throw an exception or setting defaults by my code,"['c#', 'asp.net']" +665680,javascript xmlhttprequest using jsonp i want to send request parameters to other domain i already know that cross scripting needs jsonp and i have used jsonp with jquery ajaxbut i do not figure out how to do cross scripting as using xmlhttprequest following code my basic xmlhttprequest codei guess i need to chage xhrsetrequestheader and i have to add parsing code please give me any idea var xhrfunction createxmlhttprequest ifwindowativexobject xhr new activexobjectmicrosoftxmlhttp else xhr new xmlhttprequest var url function openrequest createxmlhttprequest xhronreadystatechange getdata xhropenposturltrue xhrsetrequestheadercontenttypeapplicationxwformurlencoded xhrsenddata function getdata ifxhrreadystate4 ifxhrstatus200 var txt xhrresponsetext alerttxt,['javascript'] +665684,how to navigate links by button in wpf modern ui in c i am using modernui i have one issue with button and linki am trying to navigate by button click event and my code in homexaml is as followprivate void addgamebutton clickobject sender routedeventargs e bbcodeblock bs new bbcodeblock try bslinknavigatornavigatenew uripackapplicationpagesaddgamexaml null catch exception error moderndialogshowmessageerrormessage firstfloormodernuiresourcesnavigationfailed messageboxbuttonok muilink works fine in mainwindowsxaml for navigation but i want to navigate to addgamexaml from homexaml page by a button which is in homexaml pagemy file structure is as below for reference so please let me know where am i doing wrong,['c#'] +665699,configuring microsoft application insights to monitor a windows service is it possible to configure microsofts application insights to monitor a windows servicei have a vm running in azure on which the web service is hosted which version of the monitoring agent to i need to install and what steps need to be undertaken in order to allow monitoring data do be seen in the dashboard,['c#'] +665709,trigger parsley validation without submit form given this code it never works and always returns true whatsoever form idmyform datavalidateparsley p label forusernameusername label input typetext idusername nameusername datarequiredtrue p p label foremailemail address label input typetext idemail nameemail datarequiredtrue p br validate all the form fields by clicking this button a classbtn btndanger idvalidate validate allaformscriptvar form myformvalidateclick function if formparsleyvalidate consolelog valid always goes here else consolelog invalidscriptso my question is if there is a way to trigger parsley validation without adding a submit button,['javascript'] +665796,jdk8 with source 17 default methods i have the following classpublic class zoneddatetimetoinstant public static void mainfinal string args throws nosuchmethodexception assert chronozoneddatetimeclassisassignablefromzoneddatetimeclass final method toinstant chronozoneddatetimeclassgetmethodtoinstant final zoneddatetime now zoneddatetimenow final instant instant nowtoinstant systemoutprintlninstant it just compiles fine javac zoneddatetimetoinstantjavaand it fails with source 17 javac source 17 zoneddatetimetoinstantjavazoneddatetimetoinstantjava10 error cannot find symbol final instant instant nowtoinstant symbol method toinstant location variable now of type zoneddatetime1 error1 warningis this normal it seems that javac does not understand jdk classes with source other than 18according to javac javac still supports various source release options as previous releases didsupplementi already know the jsr 310 date and time api is only available in java 8 what does it matter with javac cat java8javapublic class java8 public void printjavaioprintstream out outprintfhello worldn javac java8java cat java7javapublic class java7 public static void mainfinal string args new java8printsystemout javac source 17 target 17 java7javawarning options bootstrap class path not set in conjunction with source 171 warning java java7hello worldconclusionas engfouad noted the problem was that the method is a default method defined in an interface javac seems to be catching that point cat java8ijavapublic interface java8i default void printjavaioprintstream out outprintfhello worldn javac java8ijava cat java8cjavapublic class java8c implements java8i javac java8cjava cat java7ijavapublic class java7i public static void mainfinal string args new java8cprintsystemout javac source 17 target 17 java7ijavawarning options bootstrap class path not set in conjunction with source 17java7ijava3 error cannot find symbol new java8cprintsystemout symbol method printprintstream location class java8c1 error1 warningjavac should have told me more helpfully,['java'] +665996,ajax post returning render template in flask i have some form which should be sent to the server as post request store a certain object in the db and return back a new template with some data in normal conditions this would just work fine but the issue here is that from the form data a quite complex json object is created and that is what should be stored in the database the json is successfully retrieved but the template redirection is not workingapprouteentry methodsget postdef entry if requestmethod get do some stuff return render templateentryhtml elif requestmethod post store the json object received and return back a new template with some data data requestjson dbstoredata retrieve some other data other data return render templatediaryhtml dataother datai would like to know what is the general approach in these situations i am pretty new to python and flask itself to me it looks like this should not be a problem but i cannot find an elegant solution to thisthanks in advanceediti include the js related code pretty simplifiedentryhtmldoctype htmlhtmlhead titletitle script srcajaxgoogleapiscomajaxlibsjquery1102jqueryminjsscriptheadbody script typetextjavascript function var json foo 1 bar 2 ajaxentry type post data jsonstringifyjson contenttype applicationjson success functiondata textstatus jqxhr consolelogdata error functionjqxhr textstatus errorthrown consolelogerrorthrown scriptbodyhtmldiaryhtmldoctype htmlhtmlhead titletitleheadbody script typetextjavascript var data datasafe consolelogdata scriptbodyhtmlthe behaviour noticed is that jinja template is not returned but the html page content in the success callback from the post ajax requesti would like to render the new template with the retrieved data after this post request done via ajax,['python'] +666001,how do you import an eclipse project into android studio now using import project in android studio for an eclipse project used to change the project structure and generate gradle files but right now i am using as 053 it is only generating idea files iml idea but not gradle and it is not touching the file structure eitherhow do you import an eclipse project into android studio nowupdate trying to export gradle files in eclipse would not export them for the app it does not show up as a module in android studio either,['android'] +666002,purpose of ef 6x dbcontext generator i have a web app that i built using linqtosql and i am looking to upgrade it to linqtoef i have looked at some tutorials and basically in the databasefirst scenario you create an adonet entity data model and from there select which tables to include in the model very similar to linqtosql now on the add new item window i see that there is another option that consists of creating an ef 6x dbcontext generatorwhats the purpose of dbcontext generator compared to creating just an adonet entity data model first option of window and what is the dbcontext generator for it seems to create a text file what should i do with it,"['c#', 'asp.net']" +666076,using virtualenv with multiple python versions on windows i have python 276 and 340 on my machine the 27 version is on my path i would like to set up a virtualenv using 34 there are many postings on so and elsewhere that suggest i do the following from a command prompt virtualenv p cpython34 myvirtualenvbut this does not work for me the console session has administrator privilege and uac is off however i get a permissions problemfvirtualenvvirtualenv p cpython34 myenvrunning virtualenv with interpreter cpython34traceback most recent call last file cpython27scriptsvirtualenvscriptpy line 9 in module load entry pointvirtualenv1 console scripts virtualenv file cpython27libsitepackagesvirtualenvpy line 779 in main popen subprocesspopeninterpreter file sysargv1 envenv file cpython27libsubprocesspy line 709 in init eread errwrite file cpython27libsubprocesspy line 957 in execute child startupinfowindowserror error 5 access is deniedi have also tried it specifically pointing to the 34 version of virtualenv but without changing the path it ends up executing a mixed bag of 27 and 34 python filesthe only way i could find to set up my virtual environment is to change my path to 34 run virtualenv then reset my path to 27 which defeats the point of the python switch on virtualenvthanks,['python'] +666171,finding the center of leaflet polygon i have a bunch of leaflet polygons on a map i created each polygon represents something different a specific set of information is thisplayed in a popup depending on the page the user is on i need to find a way to make the popup bubble open in the center of the polygon it represents each polygon is drawn using the following codevar l20 740995 92615 7414008 994043 7407691 9933838 7403617 9986023var l19 7402559 9984924 7406636 9932739 740029 9926147 7396197 99783var l18 7395142 9976684 7399235 9925048 7392889 9918456 738878 9969543var set1 lpolygonl20 l19 l18 color f weight 1 stroke true opacity 005 fillcolor 346b1faddtomapthe popup is drawn using the following codevar popup lpopup setlatlng7364017 10032715 setcontentcontentopenonmap var popup lpopupso i need to find a way for setlatlang to determin or be given the center of the polygoni came up with 3 solutions that may work not sure how to go about itfind a way to use the coordinates of a polygon to determine the center of the polygon where the popup will opencall one point of the polygon then offset the position of the popupuse an id for each polygon so each popup knows the box area polygon it can be opened incan someone help me please,"['javascript', 'php', 'html']" +666217,elasticsearch terms aggregation by entire field how can i write an elasticsearch term aggregation query that takes into account the entire field value rather than individual tokens for example i would like to aggregate by city name but the following returns new york san and francisco as individual buckets not new york and san francisco as the buckets as expectedcurl xpost httplocalhost9200cities search d size 0 aggs cities terms field city min doc count 10,['ruby'] +666254,how to unpack a series of tuples in pandas sometimes i end up with a series of tupleslists when using pandas this is common when for example doing a groupby and passing a function that has multiple return valuesimport numpy as npfrom scipy import statsdf pddataframedictxnprandomrandn100 ynprepeatlistabcd 25out dfgroupbyyxapplystatsttest 1samp 0print outya 13066417476 0203717485506b 008011382517 0936811414675c 155784329113 0132360504653d 02679459642 0790989680709dtype objectwhat is the correct way to unpack this structure so that i get a dataframe with two columnsa related question is how i can unpack either this structure or the resulting dataframe into two seriesarray objects this almost workst p zipoutbut it t is array130664174759257 array0080113825171714 array1557843291126335 array02679459641651and one needs to take the extra step of squeezing it,['python'] +666277,beatifulsoup4 get text still has javascript i am trying to remove all the htmljavascript using bs4 however it does not get rid of javascript i still see it there with the text how can i get around thisi tried using nltk which works fine however clean html and clean url will be removed moving forward is there a way to use soups get text and get the same resulti tried looking at these other pagesbeautifulsoup get text does not strip all tags and javascriptcurrently i am using the nltks deprecated functionseditheres an exampleimport urllibfrom bs4 import beautifulsoupurl html urlliburlopenurlreadsoup beautifulsouphtmlprint soupget texti still see the following for cnnjfunction use strictif windowhasownpropertysafaripushlib windowsafaripushlibcheckenv var pushlib windowsafaripushlibcurrent pushlibcurrentpermissionsif current default pushlibcheckpermissionshelloclient function globals mainlocalobjjwindowloadfunction use strictmainlocalobjinithow can i remove the jsonly other options i found arethe problem with html2text is that it is really really slow at times and creates noticable lag which is one thing nltk was always very good with,['python'] +666390,when should i use stdthreaddetach sometime i have to use stdthread to speed up my application i also know join waits until a thread completes this is easy to understand but whats the difference between calling detach and not calling iti thought that without detach the threads method will work using a thread independentlynot detachingvoid someclasomefunction stdthread t printfahello this is thread calling without detacha some code herecalling with detachingvoid someclasomefunction stdthread t printfahello this is thread calling with detacha tdetach some code here,['c++'] +666459,why cannot i import google play services into eclipse i am trying to import the googleplayservices lib into eclipse but i am not able to import it as i am getting the following warning no projects are found to import can anyone suggest a solution to this please give step by step instructions as i am a newbie,['android'] +666490,incorrect datetime value database error number 1292 incorrect datetime value 0 0 0 database error number 1292hi everyone i am having a problem a with a server upgrade done by my hosting company and i am trying to understand what is occurring so i can fix the problemmy sever has recently been upgraded to server version 5617 and i am getting errors all over the place saying my datetime value is incorrectit seem to be add 0 to the end of the datetime but i am not sure why this used to work perfectly fine on 55 but a recent upgrade has affected how my timestamps workerror number 1292incorrect datetime value 20140402 084943 0 for column created at row 1insert into activitylog tablename row user id description action privatecreated values user 1 1 people updated 0 20140402 084943 0if i modify this sql query without 0 it worksit affects anything that is a type of datetime on my tablehas anyone else had a similar problem and now what the solution is to get this to work at the moment i am thing i will have to change all my php functions to echo the datetime rather than me calling now on the query string,"['php', 'mysql']" +666526,fading out text on overflow with css if the text is bigger than allowed i am trying to create a text fadeout effect when the amount of text is bigger than the row can handle i am achieving this with the mixture of maxheight overflow and lineargradient something like thismaxheight200pxoverflowhiddentextoverflow ellipsisbackground webkitlineargradient0 fthe full fiddle is available i am trying to achieve effect similar to this one and i am kind of close the problem is that in my case text start to fadeout from the very beginning and i want it to start fading out only if it is really close to maximum size lets say start fading out if it is already 150px also i am using only webkit prefix and i assume that there may be other prefixes that i can add for other rendering enginesis there a way to do this in pure css,"['html', 'css']" +666694,symfony error the class x was not found in the chain configured namespaces x there are some other questions on this subject already but none of them were really helpful i am new to symfony so it is pretty hard to get my head around it i am in the file clientintranetbundleldapldapauthenticationproviderphp and this code is causing an erroruser new ldapuserusernamei did add it is namespace which isuse clientintranetbundleldapldapuserldapuser implements userinterfacethe error i get is the class clientintranetbundleldapldapuser was not found in the chainconfigured namespaces clientclientbundleentitywhat is that suppose to mean from what i read it has something to do with the mappingmy doctrine orm in the configyml is set to orm auto generate proxy classes kerneldebug auto mapping truehopefully you can help meedit 1actually i found out that it was notuser new ldapuserusernamethat is causing the error but it is when i am trying to persist this entityentitymanagerpersistuseredit 2i am confused with whats wrong with the mappingdoctrinemapping xmlns xmlnsxsi xsischemalocation entity nameclientintranetbundleldapldapuser tableusers repositoryclassclientclientbundlerepositoryuserrepository id nameid typeinteger columnid generator strategyauto id field nameusername columnusername typestring length100 entitymaybe it is because i am jumping between two bundles,['php'] +666828,php maximum execution time when importing sql data file i am trying to import a large sql data file using myphpadmin in xampp however this is taking a lot of time and i keep getting fatal error maximum execution time of 300 seconds exceeded in cxamphpmyadminlibrariesdbidbimysqliclassphp on line 285and the file is about 12 million lines long can someone help edit the file is about 30mb big so it is not that big i do not really understand why it is taking so longedit resource limits maximum execution time of each script in seconds note this directive is hardcoded to 0 for the cli sapimax execution time30 maximum amount of time each script may spend parsing request data it is a good idea to limit this time on productions servers in order to eliminate unexpectedly long running scripts note this directive is hardcoded to 1 for the cli sapi default value 1 unlimited development value 60 60 seconds production value 60 60 seconds max input time60 maximum input variable nesting level max input nesting level 64 how many getpostcookie input variables may be accepted max input vars 10 maximum amount of memory a script may consume 128mb memory limit200mthe is the config file for phpini in xampp for some reason i still get fatal error maximum execution time of 300 seconds exceeded in cxamphpmyadminlibrariesdbidbimysqliclassphp on line 285,"['php', 'mysql', 'sql']" +666954,this class should be public androidsupportv7internalwidgetactionbarviewhomeview i am trying to create a android application which uses 3 spinners i keep getting this error and i cannot figure out how to fix it this class should be public androidsupportv7internalwidgetactionbarviewhomeview,['android'] +666955,numpy save 2d array to text file i use npsavetxtfiletxt array delimiterto save array to the file separated with comma it looks like1 2 34 5 67 8 9how can i save the array into the file shown as it is in the numpy format in other words it looks like1 2 34 5 67 8 9,['python'] +667062,can i use wait instead of sleep i came across a question in which the poster tried to have a thread wait for a second they were using wait but outside a synchronized block and therefore it crashedgiven a running thread to pause the execution for a given time one would dothreadsleep10this should work as well and have very similar resultsynchronizedthis thiswait10using the wait timeout the thread will unpause 1 second laterthe question is this if i do not have any monitoring and notifying issue is there an actual reason to use one over the other,['java'] +667160,android mediaplayer onpreparedlistener i am working on a simple app and using a mediaplayer to play some background noise in 1 activity i am reading up on mediaplayer and am not sure whether or not to implement an onpreparedlistener to trigger the start method what are the pros cons to each approachapproach 1 mediaplayer mediaplayercreatecontext rrawsound mediaplayersetloopingtrue mediaplayerstartapproach 2 mediaplayer mediaplayercreatecontext rrawsound mediaplayersetloopingtrue mediaplayersetonpreparedlistenernew onpreparedlistener override public void onpreparedmediaplayer mp mpstart,['android'] +667233,converting a gregorian date to julian day count in objective c i need objective c method for converting gregorian date to julian days same as this php method gregoriantojd,"['ios', 'iphone']" +667321,google analytics sdk 30 sqlite3 linker errors in ios i am integrating google analytics sdk 30 in my project but i am getting linker errors when try to build my projectas mentioned in the documentation i have linked following libraries in my projectlibgoogleanalyticsservicesaadsupportframeworkcoredataframeworksystemconfigurationframeworklibzdylibeven then i get following errors on building the projectd warning directory not found for option lusersnameprojectlibrariesgoogle analytics sqlite3 bind blob referenced from tagdatalayerpersistentstoreimpl writeentriestodatabaseexpiretime in libgoogleanalyticsservicesatagdatalayerpersistentstoreimplo sqlite3 bind int referenced from tagdatalayerpersistentstoreimpl deleteentries in libgoogleanalyticsservicesatagdatalayerpersistentstoreimplo sqlite3 bind int64 referenced from tagdatalayerpersistentstoreimpl writeentriestodatabaseexpiretime in libgoogleanalyticsservicesatagdatalayerpersistentstoreimplo tagdatalayerpersistentstoreimpl peekentryids in libgoogleanalyticsservicesatagdatalayerpersistentstoreimplowhat is causing these errors am i missing anything appreciate your helpsolutioni solved it by linking my project with libsqlite30 library the google analytics documentation missed out mentioning to link this library hope this helps,"['ios', 'objective-c']" +667423,php 54 getting fullyqualified class name of an instance variable i know there is a static class field on php 55 but i have to stick to php 54 is it possible to get the fully qualified class name from a variableexamplenamespace myawesomenamespaceclass foo and somewhere else in the codepublic function bar var new myawesomenamespacefoo maybe there is something like this fullclassname get qualified classnamevar outputs myawesomenamespacefoo echo fullclassname,['php'] +667426,make table cells square how to ensure that each cell of table should become square without using fixed sizes and be responsive when they change widthtable width 90td width 30tr what should go here table tr td1td td2td td3td tr tr td4td td5td td6td tr tr td7td td8td td9td trtable,['css'] +667450,where to set the shared via text for a facebook app i have an ios app that can create shares on facebook the sharing itself works fine but we do not see a text for the shared via line as you can see in the attached image it just says shared a link via i expect the text to be shared a link via appname insteadi already tried to add some settings for the facebook app but that did not helpthis is how i trigger the share in my ios appnsmutabledictionary params nsmutabledictionary dictionarywithobjectsandkeys name name caption caption description description url link picture picture nilfbrequestconnection startwithgraphpathmefeed parametersparams httpmethodpost completionhandlerfbrequestconnection connection id result nserror error if error else where can i make this setting is it a setting for the facebook app or do i have to add that to the sharing call in my ios app,['ios'] +667491,access angularjs constant in a view i am gonna try to describe the scenario bear with me pleasei have a angular constant called urls filled with the routes and some methods to access themapp angularmodule appappconstant urls routes main stuff overview users users user usersid overview return routesoverview users return routesusers user id return routesuser replaceid idthe reason for using a constant for this is that i need to access it during the config phase of our application as well as use it in controllerswhat i want to achieve is that i want to use it in a view as well for instanceul classfoo li ngrepeatuser in users a hrefurlsuseruserid username a liulis there a way to achieve something like this preferably without assigning the urls constant to rootscope or assigning it to every controllers scope,['javascript'] +667547,how can i make a shared ptr from an opaque pointer typedef or how can i unwrap typedef if you have an opaque pointer typedef is there a way to dynamically refer to the pointedto type say for use in templates for instance say you have something like thisstruct foo forward declared structtypedef foo fooptr opaque pointerbecause the smart pointer types are templates in terms of the pointerto type to define a stdshared ptr of this it seems that you have to saystdshared ptrstruct foo thesharedptris there any way to define such a pointer without manually unwrapping the opaque pointer typedef i feel like i must be missing something obvious here but you might imagine something like these note these do not workstdshared ptrfooptr thesharedpointer orstdshared ptrpointedtofooptr thesharedpointeri feel like this should be possible am i missing something i feel like this is an impending foreheadsmacking momentedit noodling around some more it appears that in the common case shared ptrt wants to take the sizeoft you can get around this by providing a deleter to the constructor i suspect this makes this a bit of an edge case but it still seems like with all the type wrangling in c i should be able to unwrap a pointer type without doing so by hand,['c++'] +667566,thisable uitextfield keyboard shortcut suggestions is there a simple way to remove keyboard shortcut suggestions from a uitextfieldit is possible to remove typing correction with textfield setautocorrectiontypeuitextautocorrectiontypeno however this as no effect on shortcutsaffecting the sharedmenucontroller also does not squash this boolcanperformactionselaction withsenderidsender uimenucontroller sharedmenucontrollermenuvisible no return no,['ios'] +667583,pass by value faster than pass by reference i made a simple program in c to compare performance between two approaches pass by value and pass by reference actually pass by value performed better than pass by referencethe conclusion should be that passing by value require fewer clockcycles instructionsi would be really glad if someone could explain in detail why pass by value require fewer clockcyclesinclude iostreaminclude stdlibhinclude timehusing namespace stdvoid functionint ptrvoid function2int valint main int nmbr 5 clock t start stop start clock for long i 0 i 10 i functionnmbr function2nmbr stop clock cout time stop start return 0 pass by referencevoid functionint ptr ptr 5 pass by valuevoid function2int val val 5,['c++'] +667585,using streams how can i map the values in a hashmap given a mapstring person where person has a string getname etc method on it how can i turn the mapstring person into a mapstring string where the string is obtained from calling persongetnameprejava 8 i would usemapstring string bynamemap new hashmapfor mapentrystring person person peopleentryset bynamemapputpersongetkey persongetvaluegetnamebut i would like to do it using streams and lambdasi cannot see how to do this in a functional style maphashmap do not implement streampeopleentryset returns a setentrystring person which i can stream over but how can i add a new entrystring string to the destination map,['java'] +667721,what default promotions of types are there in the variadic arguments list for example i use printf function in c for 8bit cpu avr is the following code safeuint8 t a 5printfd ahere d expects int 16bit in my case and at least 16bit in any case but i pass 8bit integerdoes cc standards guarantee that any type with rank lesser than int promoted to intthe same question for float a and f that expects double and other analogous types,"['c++', 'c']" +667728,check if object value exists within a javascript array of objects and if not add a new object to array if i have the following array of objects id 1 username fred id 2 username bill id 2 username ted is there a way to loop through the array to check whether a particular username value already exists and if it does do nothing but if it does not to add a new object to the array with said username and new idthanks,['javascript'] +667736,why does javascript variable declaration at console results in undefined being printed i have already read the following so postswhy does this javascript code print aundefineda on the consolewhy does chrome firefox console print undefinedwhy does the js console return an extra undefinedbut none of it explains why the javascript console prints undefined when i declare a variable as followsvar a,['javascript'] +667766,corebluetooth number of bytes sent number of bytes received i have an app that is acting as a peripheral and another app that is acting as a centralthe central app is reading a characteristic on the peripheral selfserviceperipheral readvalueforcharacteristicselfpacketcharacteristicthe peripheral handles the request as such voidperipheralmanagercbperipheralmanager manager didreceivewriterequestsnsarray requests for cbattrequest request in requests if requestcharacteristicuuid isequalselfservicepacketcharacteristicuuid nsdata value selfpackets0 this values length logs at 512 bytes tested 500 bytes too requestvalue value selfperipheralmanager respondtorequestrequest withresultcbatterrorsuccess the size of nsdata value is equal to 512 bytes note that i have also tested this with 500 bytesthe central then receives the the delegate call as such voiddidupdatevalueforcharacteristiccbcharacteristic characteristic errornserror error if characteristic selfpacketcharacteristic nslogpacket received lu bytes unsigned longcharacteristicvaluelength the nslog statement states that the value received is 536 bytes regardless of if i send 500 or 512 bytes the bytes sent and the bytes received are identical until about a quarter of the way through by looking at the hex value provided by xcode the rest of the bytes are completely differentthe questions are as follows1 why am i receiving more bytes than i have sent2 what are these bytes what do they represent3 where can i find documentation on this i have reviewed the corebluetooth docsguides over and over and cannot find anything indicating that this could happen4 could this be related to endiannessedit 1ok so i have done a little bit more testing and found out the followingthe mtu seems to be 134 bytes from ios to ios as soon as the data being sent is equal or bigger than 134 bytes corebluetooth is calling peripheralmanagerdidreceivereadrequest 4 timesmy assumption is that because the data being sent is at least equal to the mtu corebluetooth does not know whether or not it is done sending all the data therefore it calls peripheralmanagerdidreceivereadrequest and number of times until and x mtu covers the maximum possible size of a characteristics value 512 bytes in my particular case 4 x 134 bytes equals the magical 536 bytesnote that the requests offset is being updated every time in my particular case 0 134 268 402edit 2ok figured it outi was semiright in my assumption corebluetooth calls peripheralmanagerdidreceivereadrequest and time until the data being sent is smaller than the mtu if the data being sent is equal or larger than the mtu corebluetooth will keep calling peripheralmanagerdidreceivereadrequest until it and x mtu covers the max size 512 bytes if the data mtu 0 then peripheralmanagerdidreceivereadrequest will be called one last time where you have to return 0 bytes,"['ios', 'objective-c']" +667799,motorola tc55 refuses to show up in adb i can not get the motorola tc55 to show up in the adb using mac osx and their support lines are less than unhelpfuli have tried adding the vendors to the ini file i have tried toggling onoff the usb debugging and the development optionsi have tried killing and restarting adbi have tried restarting laptop and tc55i have tried 3 cablesi have tried it when using the device storage option and withoutit says usb connected usb debugging connected and connected as installer in the notifications menui tried installing motorola device manager for mac which seems to do nothingi am at a dead end besides emailing myself test builds what can i do,['android'] +667887,google analytics w android programmatically set ga reportuncaughtexceptions tldris there a way to programatically enable reportuncaughtexceptions for google analytics v4 without using the xml config in androidlonger explanationi am using google analytics v4 in an android app and i need a way to set two different tracking ids by build flavor i was using a general global trackerxml configuration see below though i need a way to dynamically inject the tracking id based on flavor resources xmlnstools toolsignoretypographydashes integer namega sessiontimeout300integer bool namega autoactivitytrackingtruebool bool namega reportuncaughtexceptionstruebool the following value should be replaced with correct property id string namega trackingiduaxstringresourcesin order to avoid having duplicate xml configs in the build flavor source folders i initialize a tracker directly using the trackingid and set the attributes programaticallymgatracker analyticsnewtrackerrstringga code this is dynamic depending on flavormgatrackersetsessiontimeout300mgatrackerenableautoactivitytrackingtrueis there a way to enable reportuncaughtexceptions without using the xml config,['android'] +667909,assignment to undeclared variable when using for i0 hey i am trying to get list of all input fields in a html form but i get following errorin firebugreferenceerror assignment to undeclared variable ifor i0 iinputslength ii do not understant how is i undeclared because that is that first part of for doesthis is my formula function listinputs var form documentgetelementbyidwholeform var inputs formchildnodes for i0 iinputslength i var stringstring inputsinodename br var here documentgetelementsbytagnamep hereinnerhtmlstring,['javascript'] +668122,how to enable hyphenation in uitextview with nonenglish text i use paragraphstylehyphenationfactor 1 but it works fine only for english text how to enable hyphenation in uitextview with nonenglish text or set locale to uitextview,"['ios', 'objective-c']" +668165,show current cursor position in selenium is there a way to show current cursor position or something like this i have action chain that should click on the exact point on some object but i guess i have picked up wrong coordinates i use firefox webdriverheres how the script looks likefrom selenium import webdriverimport timefrom seleniumwebdrivercommonaction chains import actionchainsdriver webdriverfirefoxdrivergetelem driverfind element by xpathdividplayer1objecttypeapplicationxshockwaveflashaction chains actionchainsdriveraction chainsmove to element with offsetelem 660 420performaction chainsclickperformtimesleep10driverclose,['python'] +668169,android is not picking right dimensxml file from values folder i have created different dimensxml files and placed them in appropriate values folderi have the following value folders definedvalues valueslargevaluesnormalvaluessmallvaluessw320dpvaluessw320dplandvaluessw480dpvaluessw600dpvaluessw720dp andvaluessw720dplandthe problem is when i install the app on phone 5 inches dimensxml from valuessw320dp is selected by android the selection is independent of screen density i have tested the app on s4 moto g s4 mini and some 23 device the results are the same throughoutwhat am i doing wrong here,['android'] +668366,using systemdynamic in roslyn i modified the example that comes with the new version of roslyn that was released yesterday to use dynamic and expandoobject but i am getting a compiler error which i am not sure how to fix the error is721 error cs0656 missing compiler required member microsoftcsharpruntimebindercsharpargumentinfocreatecan you not use dynamics in the new compiler yet how can i fix this here is the example that i updatedtestmethodpublic void endtoendcompileandrun var text using systemdynamic public class calculator public static object evaluate dynamic x new expandoobject xresult 42 return xresult var tree syntaxfactoryparsesyntaxtreetext var compilation csharpcompilationcreate calcdll options new csharpcompilationoptionsoutputkinddynamicallylinkedlibrary syntaxtrees new tree references new new metadatafilereferencetypeof objectassemblylocation new metadatafilereferencetypeof expandoobjectassemblylocation assembly compiledassembly using var stream new memorystream var compileresult compilationemitstream compiledassembly assemblyloadstreamgetbuffer type calculator compiledassemblygettypecalculator methodinfo evaluate calculatorgetmethodevaluate string answer evaluateinvokenull nulltostring assertareequal42 answer,['c#'] +668407,auto scroll to horizontalscrollview i am doing autohorizontal scrolling so i have 15 items now i want to access at 12 item so my index is 11 but i am unable to scroll it auto when a index occur horizontalscrollviewscrollto12 0overridepublic void onpageselectedint page forint i 0 i holetitlelength i ifi page titleisettextcolor0xfhorizontalscrollviewscrollto12 0 else titleisettextcolor0xffe0e0e0 please expert make a look,['android'] +668451,how can i output results to the result window in jsfiddle i have tried using consolelog but i need to have the developer window open in chrome to see the outputalert writes to the popup boxi want to output to the result window bottomright pane in jsfiddle can anyone tell me pleaseupdated with a visual of answer by jajadrinker thanks for this,['javascript'] +668455,putting arrowheads on vectors in matplotlibs 3d plot i plotted the eigenvectors of some 3ddata and was wondering if there is currently already a way to put arrowheads on the lines would be awesome if someone has a tip for me import numpy as npfrom matplotlib import pyplot as pltfrom mpl toolkitsmplot3d import axes3d this part is just for reference if you are interested where the data is coming from the plot is at the bottom generate some example datamu vec1 nparray0cov mat1 nparray10101class1 sample nprandommultivariate normalmu vec1 cov mat1 20mu vec2 nparray1cov mat2 nparray10101class2 sample nprandommultivariate normalmu vec2 cov mat2 20 concatenate data for pcasamples npconcatenateclass1 sample class2 sample axis0 mean valuesmean x meansamples0mean y meansamples1mean z meansamples2eigenvectors and eigenvalueseig val eig vec nplinalgeigcov matplotting eigenvectors fig pltfigurefigsize1515ax figadd subplot1 projection3daxplotsamples0 samples1 samples2 o markersize10 colorgreen alpha02axplotmean x mean y mean z o markersize10 colorred alpha05for v in eig vec axplotmean x v0 mean y v1 mean z v2 colorred alpha08 lw3axset xlabelx valuesaxset ylabely valuesaxset zlabelz valuesplttitleeigenvectorspltdrawpltshow,['python'] +668500,how do i safely get the users real ip address in flask using mod wsgi i have a flask app setup on mod wsgiapache and need to log the ip address of the user requestremote addr returns 127001 and this fix attempts to correct that but i have found that django removed similar code for security reasonsis there a better way to safely get the users real ip addressedit maybe i am missing something obvious i applied werkzeugsflasks fix but it does not seem to make a difference when i try a request with altered headersrunpy from werkzeugcontribfixers import proxyfix appwsgi app proxyfixappwsgi app apprunviewpyfor ip in requestaccess route print ip prints 1234 and myipaddressthis same result happens if i have the proxyfix enabled or not i feel like i am missing something completely obvious,['python'] +668544,which method is being called after popbackstack i have an activity where i am calling three fragments each depending on each other activity f1 fragment one title isshould list f2 fragment two title isshould overview f3 fragment three title isshould detailatm i use the following method call to jump backwardsoverridepublic boolean onoptionsitemselectedmenuitem item switch itemgetitemid case androidridhome fragmentmanager fragmentmanager getsupportfragmentmanager if fragmentmanagergetbackstackentrycount0 fragmentmanagerpopbackstack this works fine i am overriding the actionbar title in each fragment like thisactionbar bar getsherlockactivitygetsupportactionbarbarsettitlerstringtitle f3when navigating forward like shown above this works flawlessly but navigating backwards the title of the actionbar isna t updatedf3 title isshould detail f2 title is detail should overview f1 title is detail should listobviously i could just update it again when the fragment is shown but my debugger never stops in any of the methods ia d except which would be called like onresumeso is there actually any method being called in a previous fragment after popbackstack,"['java', 'android']" +668558,apns error20 unable to get local issuer certificate using terminal i have gone through the process here about 7 times the other forum posts on this topic did not seem to provide an answer other than the certificates arent valid however i followed the steps exactly and if im missing something about how to ensure my certificates are valid i am all earsive tried using my email as well the email registered with account which hosts the game and followed every step to the ti request a certificate export my p12 key download the public certificate and make them into pem fileswhy am i still getting these errorsverify errornum20unable to get local issuer certificateverify return0no client certificate ca names senthere is the full output when i connect to the apnsopenssl s client connect gatewaysandboxpushapplecom2195 cert certpem key keypementer pass phrase for keypemconnected03depth1 cusoentrust incouwentrustnetrpa is incorporated by referenceouc 2009 entrust inccnentrust certification authority l1cverify errornum20unable to get local issuer certificateverify return0certificate chain 0 scusstcalifornialcupertinooapple incouitms engineeringcngatewaysandboxpushapplecom icusoentrust incouwentrustnetrpa is incorporated by referenceouc 2009 entrust inccnentrust certification authority l1c 1 scusoentrust incouwentrustnetrpa is incorporated by referenceouc 2009 entrust inccnentrust certification authority l1c ioentrustnetouwentrustnetcps 2048 incorp by ref limits liabouc 19 entrustnet limitedcnentrustnet certification authority 2048server certificatebegin certificateifgzccbaogawibagietbz90janbgkqhkig9w0baqufadcbstelmakga1uebhmcvvmxfjaubgnvbaotduvudhj1c3qsieluyy4xota3bgnvbastmhd3dy5lbnrydxn0lm5ldc9ycgegaxmgaw5jb3jwb3jhdgvkigj5ihjlzmvyzw5jztefmb0ga1uecxmwkgmpidiwmdkgrw50cnvzdcwgsw5jljeumcwga1ueaxmlrw50cnvzdcbdzxj0awzpy2f0aw9uief1dghvcml0esatiewxqzaefw0xmja1mjuymzm3ndzafw0xnda1mzewnta4ndhamigpmqswcqydvqqgewjvuzetmbega1uecbmkq2fsawzvcm5pytesmbaga1uebxmjq3vwzxj0aw5vmrmweqydvqqkewpbchbszsbjbmmumrkwfwydvqqlexbpve1tievuz2luzwvyaw5nmscwjqydvqqdex5nyxrld2f5lnnhbmrib3guchvzac5hchbszs5jb20wggeima0gcsqgsib3dqebaquaa4ibdwawggekaoibaqcr1z4brfudiu9vobovmd7owapplrtczizlwxsyg6kerppaeac6dscvsdrojuietdbup0bg408k0gzhlfkrljoc2sma5wgvk7op4sty83my3yczqv4qvgdhxseonns6xia8cl4ingdymwglzb0stdfbienwieotxqzcg6gkepowxksygwyi08538uihkk4jziol2eiebwjewlaxffpmlstc36us8oykmjwvuu3haznmidvbgk2z68rbnqnoaadbtutk7rwaa5i8gyysja0dywmvizxggxwwyr4dvhtphfujyqgg1ixm8q651lngdrvf4sb0pfanitq7agmbaagjggfzmiibvtalbgnvhq8ebamcbaawhqydvr0lbbywfayikwybbquhawegccsgaqufbwmcmdmga1udhwqsmcowkkamocsgimh0dha6ly9jcmwuzw50cnvzdc5uzxqvbgv2zwwxyy5jcmwwzqyikwybbquhaqeewtbxmcmgccsgaqufbzabhhdodhrwoi8vb2nzcc5lbnrydxn0lm5lddawbggrbgefbqcwaoykahr0cdovl2fpys5lbnrydxn0lm5ldc9smwmty2hhaw4uy2vymeaga1udiaq5mdcwnqyjkozihvz9b0scmcgwjgyikwybbquhagewgmh0dha6ly93d3cuzw50cnvzdc5uzxqvcnbhmb8ga1udiwqymbaafb7xq4kgekpatn37hr67hl8kyhnmb0ga1uddgqwbbsgninrqttshi8puj7unuebee71stajbgnvhrmeajaama0gcsqgsib3dqebbquaa4ibaqasedkuybhvdrjnclhy8w9ec92nwqbyqkisgp0uvcvgpsjiwdbkcgiw1olks6mqus9r7vrjjfg7ehtufmorivjgntkpte49sblrmizvqgnhjd6ydyym9obuwrvwketlmv0snxzd0qllj9fovub8zp8ltutqfj5izw1xb9esnzhpkkq9ylj8mcd4tpxzxiclgt327potxwmjq31fz7hcqcowmhccp8kikm5seyc9qnkmdaozhvvw4e1rspewovptch1x1bcktjajmro7jurplubenzgspuvfrkwp9jy0a28vnjekoa7rrmrd8irufmgblqkgn8yogdpqe5t1end certificatesubjectcusstcalifornialcupertinooapple incouitms engineeringcngatewaysandboxpushapplecomissuercusoentrust incouwentrustnetrpa is incorporated by referenceouc 2009 entrust inccnentrust certification authority l1cno client certificate ca names sentssl handshake has read 2731 bytes and written 2191 bytesnew tlsv1sslv3 cipher is aes256shaserver public key is 2048 bitsecure renegotiation is supportedcompression noneexpansion nonesslsession protocol tlsv1 cipher aes256sha sessionid sessionidctx masterkey 0bb064ce572cc45ff7fe32b45e53ba282e36ace58516f0110c2f1c1bcca647e0b13adf8273f31219c0b7c069cb02d7 keyarg none start time 1396636635 timeout 300 sec verify return code 0 okfirst part solved my certificates are validadding cafile and the 2048 ea cert did the tricknow to get this working on my serverserver codedevicetoken 05ae9852d21e51d7d5167bad0453456346456456456211a09085abe197c put your private keys passphrase here passphrase password put your alert message here message test notification ctx stream context create stream context set optionctx ssl local cert ckpem stream context set optionctx ssl passphrase passphrase stream context set optionctx ssl cafile entrust 2048 cacer stream context set optionctx ssl allow self signed 1 stream context set optionctx ssl verify peer 1 open a connection to the apns server fp stream socket clientsslgatewaysandboxpushapplecom2195 err errstr 60 stream client connectstream client persistent ctxsolvedas stated below it was missing the full path,['ios'] +668562,aspnet identity web api request fails authorization returns 200 ok i am getting up to speed on aspnet identity in net 45 i setup a test app that registers logs in and attempts to make a call to an api controller that requires a claim of adminauthorizerolesadminpublic class workcontroller apicontrollerwhen a request is made that does not have the claim of admin the web api still returns 200ok but with the json of messageauthorization has been denied for this requestthis seems a little odd to me since this does not represent successful request i was expecting a 401 error i am having trouble finding information on how to customize the response or return a proper status codei guess i should ask if 401 is even proper for this or is the 200 the correct status code to use and i should just handle itedit for some reason it is now returning 401 now i do not understand why i was getting the json message earlier if it was denied,['c#'] +668564,tests show await is significantly slower even when object being awaited is already complete i wanted to test the overhead ascribed to a program by using awaitasyncto test this i wrote the following test classpublic class entity inotifycompletion private action continuation private int i public void oncompletedaction continuation thiscontinuation continuation public entity getawaiter return this public entity getresult return this public bool iscompleted get return true public void execute if i 0 consolewritelinewhat and then i wrote a test harness the test harness iterates through testa and testb 1600 times measuring the latter 1500 times only to allow the jit to warm up set is a collection of entity objects but the implementation is irrelevant there are 50 entities in the set the test harness uses the stopwatch class for testingprivate static void dotesta entity objects setgetelements parallelfor0 objectslength async i entity e objectsi if e null return await eexecute private static void dotestb entity objects setgetelements parallelfor0 objectslength i entity e objectsi if e null return eexecute the two routines are identical except one is awaiting the entity before calling execute execute does nothing useful it is just some dumb code to make sure the processor is really doing something for each entityafter executing my test in release mode targeting anycpu i get the following output 1500 repetitions in nanoseconds 10ns 01msmethod avg min max jitter totala 1301465ns 1232200ns 28690ns 1567534ns 1952199msb 130053ns 1160ns 711200ns 581146ns 195081msas you can see the method with the await in it is about 10 times slowerthe thing is as far as i know there is nothing to await getresult is always true does this mean that the state machine is executed even if the awaited thing is already readyif so is there any way around this i would like to use the semantics of asyncawait but this overhead is too high for my applicationedit adding full benchmark code after requestedprogramcsusing systemusing systemcollectionsconcurrentusing systemcollectionsgenericusing systemcollectionsspecializedusing systemdiagnosticsusing systemlinqusing systemreflectionusing systemruntimecompilerservicesusing systemruntimeinteropservicesusing systemtextusing systemthreadingusing systemthreadingtasksnamespace csharpperftest public class entity inotifycompletion private action continuation private int i public void oncompletedaction continuation thiscontinuation continuation public entity getawaiter return this public entity getresult return this public bool iscompleted get return true public void execute if i 0 consolewritelinewhat static class program static concurrentsetentity set const int max elements 50 called once before all testing begins private static void oncebefore set new concurrentsetentity parallelfor0 max elements i setaddnew entity called twice each repetition once before dotesta and once before dotestb private static void pretest private static void dotesta entity objects setgetelements parallelfor0 objectslength async i entity e objectsi if e null return await eexecute private static void dotestb entity objects setgetelements parallelfor0 objectslength i entity e objectsi if e null return eexecute private const int repetitions 1500 private const int jit warmups 10 region test harness private static double atimes new doublerepetitions private static double btimes new doublerepetitions private static void mainstring args stopwatch stopwatch new stopwatch oncebefore for int i jit warmups 1 i repetitions i consolewritelinestarting repetition i pretest stopwatchrestart dotesta stopwatchstop if i 0 atimesi stopwatchelapsedtotalmilliseconds pretest stopwatchrestart dotestb stopwatchstop if i 0 btimesi stopwatchelapsedtotalmilliseconds thisplayscores private static void thisplayscores consolewriteline consolewriteline bool innanos false if atimesaverage 10 btimesaverage 10 innanos true for int i 0 i atimeslength i atimesi 10 for int i 0 i btimeslength i btimesi 10 consolewriteline repetitions repetitions innanos in nanoseconds 10ns 01ms in milliseconds 10ms 1s consolewritelinemethod avg min max jitter total consolewriteline a stringformat0n0 long atimesaverage innanos ns mspadright13 stringformat0n0 long atimesmin innanos ns mspadright13 stringformat0n0 long atimesmax innanos ns mspadright13 stringformat0n0 long mathmaxatimesaverage atimesmin atimesmax atimesaverage innanos ns mspadright13 long atimessum 10 innanos stringformat0f3 atimessum 10 ms long atimessum innanos ns ms consolewriteline b stringformat0n0 long btimesaverage innanos ns mspadright13 stringformat0n0 long btimesmin innanos ns mspadright13 stringformat0n0 long btimesmax innanos ns mspadright13 stringformat0n0 long mathmaxbtimesaverage btimesmin btimesmax btimesaverage innanos ns mspadright13 long btimessum 10 innanos stringformat0f3 btimessum 10 ms long btimessum innanos ns ms consolereadkey endregion,"['c#', '.net']" +668642,how to create a circular progress bar in pure qmljs my application is made using qmljs and i am looking to create a circular progress bar widget i can create the circle using a qml rectangle and settings its radius equal to its width2 to make it into a circle how do i create a progress bar out of iti am planning to implement the following mockup,['javascript'] +668688,error installing bcrypt with pip on os x cant find ffih libffi is installed i am getting this error when trying to install bcrypt with pip i have libffi installed in a couple places the xcode os x sdk and from homebrew but i do not know how to tell pip to look for it any suggestionsdownloadingunpacking bcrypt102 from r requirementstxt line 41 running setuppy egg info for package bcrypt osx confusion between cc versus gcc see issue 123 will not use thread in the c code c cffi backendc1410 fatal error ffih file not found include ffih 1 error generated traceback most recent call last file string line 16 in module file userscodyvirtualenvsanalyticsbuildbcryptsetuppy line 104 in module programming language python 33 file systemlibraryframeworkspythonframeworkversions27libpython27thistutilscorepy line 112 in setup setup thistribution thist klassattrs file buildbthistmacosx109inteleggsetuptoolsthistpy line 239 in init file buildbthistmacosx109inteleggsetuptoolsthistpy line 264 in fetch build eggs file buildbthistmacosx109inteleggpkg resourcespy line 620 in resolve thist bestreqkey envbest matchreq ws installer file buildbthistmacosx109inteleggpkg resourcespy line 858 in best match return selfobtainreq installer try and downloadinstall file buildbthistmacosx109inteleggpkg resourcespy line 870 in obtain return installerrequirement file buildbthistmacosx109inteleggsetuptoolsthistpy line 314 in fetch build egg file buildbthistmacosx109inteleggsetuptoolscommandeasy installpy line 593 in easy install file buildbthistmacosx109inteleggsetuptoolscommandeasy installpy line 623 in install item file buildbthistmacosx109inteleggsetuptoolscommandeasy installpy line 811 in install eggs file buildbthistmacosx109inteleggsetuptoolscommandeasy installpy line 1017 in build and install file buildbthistmacosx109inteleggsetuptoolscommandeasy installpy line 1005 in run setup thistutilserrorsthistutilserror setup script exited with error command cc failed with exit status 1 complete output from command python setuppy egg info osx confusion between cc versus gcc see issue 123will not use thread in the c codec cffi backendc1410 fatal error ffih file not foundinclude ffih 1 error generatedtraceback most recent call last file string line 16 in module file userscodyvirtualenvsanalyticsbuildbcryptsetuppy line 104 in module programming language python 33 file systemlibraryframeworkspythonframeworkversions27libpython27thistutilscorepy line 112 in setup setup thistribution thist klassattrs file buildbthistmacosx109inteleggsetuptoolsthistpy line 239 in init file buildbthistmacosx109inteleggsetuptoolsthistpy line 264 in fetch build eggs file buildbthistmacosx109inteleggpkg resourcespy line 620 in resolve thist bestreqkey envbest matchreq ws installer file buildbthistmacosx109inteleggpkg resourcespy line 858 in best match return selfobtainreq installer try and downloadinstall file buildbthistmacosx109inteleggpkg resourcespy line 870 in obtain return installerrequirement file buildbthistmacosx109inteleggsetuptoolsthistpy line 314 in fetch build egg file buildbthistmacosx109inteleggsetuptoolscommandeasy installpy line 593 in easy install file buildbthistmacosx109inteleggsetuptoolscommandeasy installpy line 623 in install item file buildbthistmacosx109inteleggsetuptoolscommandeasy installpy line 811 in install eggs file buildbthistmacosx109inteleggsetuptoolscommandeasy installpy line 1017 in build and install file buildbthistmacosx109inteleggsetuptoolscommandeasy installpy line 1005 in run setupthistutilserrorsthistutilserror setup script exited with error command cc failed with exit status 1command python setuppy egg info failed with error code 1 in userscodyvirtualenvsanalyticsbuildbcrypt,['python'] +668763,how to extract ip address in spring mvc controller get call i am working on spring mvc controller project in which i am making a get url call from the browser below is the url by which i am making a get call from the browser conf20140324dcalland below is the code in which the call comes after hitting at the browser requestmappingvalue processing method requestmethodgetpublic responsebody processresponse processdatarequestparamworkflow final string workflow requestparamconf final string value requestparamdc final string dc systemoutprintlnworkflow systemoutprintlnvalue systemoutprintlndc some other code problem statementnow is there any way i can extract ip address from some header meaning i would like to know from which ip address call is coming meaning whoever is calling above url i need to know their ip address is this possible to do,['java'] +668916,c compiletime predicate to test if a callable object of type f can be called with an argument of type t i would like to create a compiletype function that given any callable object f function lambda expression function object and a type t evaluates to true if f can be called with an argument of type t and false if it cannotexamplevoid f1int void f2const stdstring assert is callable withintf1assertis callable withintf2i am thinking that a clever use of the sfinae rule could achieve this possibly somehow like thistemplatetypename t typename fconstexpr bool is callable withf typename stdresult offttype nullptr return truetemplatetypename t typename fconstexpr bool is callable withf return falsebut this does not work because if f is callable with t both overloads participate in the overload resolution and there is an ambiguity i would like to rewrite it so in the positive case the first overload would be picked by the overload resolution over the second one not sure if i am even on the right track here though,['c++'] +668958,left shift of negative values by 0 positions in c a left shift of a negative value is undefined behavior i have encountered two libraries compiled with intels icc where the offending code was removed the same code was fine under clang comeau gcc and msvc does the standard make any mention of left shifting a negative value 0 places is it also undefined the detail i am curious about is a 0sized shift which is no shift at all in practice so i am wondering if the language is vague such that a 0sized left shift may be allowed,['c'] +669047,how should i count the number of unique rows in a binary matrix suppose i have a matrix whose entries are only 0 and 1 egsetseed123m matrix sample01 10 true nrow5 with sample output 1 21 0 02 1 13 0 14 1 15 1 0the matrix will have at most 20 columns and will have many rowsi want a function let us call it rowcounts that returnsthe number of times a particular row appears in the matrix andthe index of the first occurrence of that rowhow might i solve this problem,['c++'] +669058,how to render text in sdl2 i was wondering how to render text with sdl2 i found an api called sdl ttf and some tutorials however they do not work with my situationi am using an sdl window and sdl renderer whereas the tutorials are specific to sdl surfaceis it possible to use sdl ttf with sdl rendersdl window if so how,"['c++', 'c']" +669086,toggle gps programmatically android 44 i know do not do this i do not care it is for a root appthe app is installed to systemapp with 07 permissioni was previously usingcontentresolver cr contextgetcontentresolversettingssecuresetlocationproviderenabledcr locationmanagergps provider isgpsonthis is how i am trying it on 44 since that was deprecated int valueif isgpsonvalue settingssecurelocation mode off else value settingssecurelocation mode high accuracysettingssecureputintcr settingssecurelocation mode valueand it is silently failing according to some user reports how can i properly toggle gps with android 44 from an app in system folder,['android'] +669118,net static analysis guaranteed calls to functions in a program is there a way to find out all function calls that will execute as part of a program in c worldfor example given thisstatic void mainstring args if true calltruefunction else callfalsefunction can i say through fxcop or some other system get to know calltruefunction,['c#'] +669217,how to programmatically show and hide action bar on one activity i got this one activity wherein i need to hide actionbar on the login interface then once login it will show the action bari got one activity only if i put getactionbar on the main activity it gives me errorheres the codesuppresslintnewapipublic class mainactivity extends activity viewpager viewpagerpageradapter adapterprogressdialog pdialogimageview imglogomenu menu1imageview headerimageview footerint bookcover new int rdrawableimage1 rdrawableimage2 rdrawableimage3 suppresslintnewapioverrideprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main setupfacebookconnectsavedinstancestate imglogo imageviewfindviewbyidridlogo share imageview findviewbyidridshare locate the viewpager in viewpager mainxml viewpager viewpager findviewbyidridpager pass results to viewpageradapter class adapter new viewpageradapterthis bookcover binds the adapter to the viewpager viewpagersetadapteradapter final onpagechangelistener pagechangelistener new viewpagersimpleonpagechangelistener suppresslintnewapi override public void onpageselectedint position final int pos position sharesetonclicklistenernew onclicklistener override public void onclickview v switchpos case 0 break case 1 break case 2 break case 3 break when changing pages reset the action bar actions since they are dependent on which page is currently active an alternative approach is to have each fragment expose actions itself rather than the activity exposing actions but for simplicity the activity provides the actions in this sample invalidateoptionsmenu viewpagersetonpagechangelistenerpagechangelistener pagechangelisteneronpageselected0 facebook connect button findviewbyidridfacebook login facebook connectsetonclicklistenernew onclicklistener override public void onclickview arg0 if isfacebookconnected thisconnectfacebook else connectfacebook shared preferences msharedpreferences getapplicationcontextgetsharedpreferencesmypref 0 suppresslint inlinedapi newapi override public boolean oncreateoptionsmenumenu menu thismenu1 menu superoncreateoptionsmenumenu getmenuinflaterinflatermenumain menu menufinditemridaction previoussetenabledviewpagergetcurrentitem 0 add either a next or finish button to the action bar depending on which page is currently selected menuitem item menuaddmenunone ridaction next menunoneviewpagergetcurrentitem adaptergetcount 1 rstringaction finish rstringaction next itemsetshowasactionmenuitemshow as action if room menuitemshow as action with text return true override public boolean onoptionsitemselectedmenuitem item int itemid itemgetitemid if itemid ridaction previous go to the previous step in the wizard if there is no previous step setcurrentitem will do nothing viewpagersetcurrentitemviewpagergetcurrentitem 1 return true else if itemid ridaction next advance to the next step00 in the wizard if there is no next step setcurrentitem will do nothing viewpagersetcurrentitemviewpagergetcurrentitem 1 return true return superonoptionsitemselecteditem private sessionstatuscallback statuscallback new fbsessionstatuspublic void setupfacebookconnectbundle savedinstancestate settingsaddloggingbehaviorloggingbehaviorinclude access tokens session session sessiongetactivesession if session null if savedinstancestate null session sessionrestoresessionthis null statuscallback savedinstancestate if session null session new sessionthis sessionsetactivesessionsession if sessiongetstateequalssessionstatecreated token loaded sessionopenforreadnew sessionopenrequestthis setcallbackstatuscallback public boolean isfacebookconnected session session sessiongetactivesession return sessionisopened true falsepublic void connectfacebook session session sessiongetactivesession if sessionisopened sessionisclosed getactionbarshow sessionopenforreadnew sessionopenrequestthis setcallbackstatuscallback else sessionopenactivesessionthis true statuscallback overridepublic void onstart superonstart sessiongetactivesessionaddcallbackstatuscallbackoverridepublic void onstop superonstop sessiongetactivesessionremovecallbackstatuscallbackoverrideprotected void onsaveinstancestatebundle outstate superonsaveinstancestateoutstate session session sessiongetactivesession sessionsavesessionsession outstateoverrideprotected void onactivityresultint requestcode int resultcode intent data superonactivityresultrequestcode resultcode data sessiongetactivesessiononactivityresultthis requestcode resultcode datapublic class fbsessionstatus implements sessionstatuscallback override public void callsession session sessionstate state exception exception onsessionstatechangesession state exception public void thisconnectfacebook session session sessiongetactivesession if sessionisclosed sessioncloseandcleartokeninformation viewpagersetvisibilityviewinvisible menuitem item1 menu1finditemridaction next item1setvisiblefalse menuitem item2 menu1finditemridaction previous item2setvisiblefalse imglogosetvisibilityviewvisible btnlogintwittersetvisibilityviewvisible sharesetvisibilityviewinvisible private void onsessionstatechangesession session sessionstate state exception exception check if the user is authenticated and a deep link needs to be handled if stateisopened menuitem item1 menu1finditemridaction next item1setvisibletrue menuitem item2 menu1finditemridaction previous item2setvisibletrue getactionbarshow sharesetvisibilityviewvisible btnlogintwittersetvisibilityviewinvisible btnsharesetvisibilityviewvisible viewpagersetvisibilityviewvisible imglogosetvisibilityviewinvisible public void shareimagestring name string caption string desc string link string picture bundle params new bundle paramsputstringname name paramsputstringcaption caption paramsputstringdescription desc paramsputstringlink link paramsputstringpicture seta1020361023076600610737418291523023247type1theater paramsputstringpicture picture webdialog feeddialog new webdialogfeeddialogbuildermainactivitythis sessiongetactivesession params setoncompletelistenernew oncompletelistener override public void oncompletebundle values facebookexception error if error null when the story is posted echo the success and the post id final string postid valuesgetstringpost id if postid null toastmaketextmainactivitythis successfuly posted toastlength shortshow else user clicked the cancel button toastmaketextmainactivitythis publish cancelled toastlength shortshow else if error instanceof facebookoperationcanceledexception user clicked the x button toastmaketextmainactivitythis publish cancelled toastlength shortshow else generic ex network error toastmaketextmainactivitythis error posting story toastlength shortshow build feeddialogshow suppresswarningsunused private boolean issubsetofcollectionstring subset collectionstring superset for string string subset if supersetcontainsstring return false return true,['android'] +669336,call android methods from javascript i searched but i did not find an answer i am developing an android app based on webview using html5 and javascript can i call an android method like maketoast from javascript,"['javascript', 'android']" +669635,cc left shift unsigned vs signed i have this codeinclude iostreamint main unsigned long int i 1u 31 stdcout i stdendl unsigned long int uwantsum 1 31 stdcout uwantsum stdendl return 0it prints out214748364818446744071562067968on arch linux 64 bit gcc ivy bridge architecturethe first result makes sense but i do not understand where the second number came from 1 represented as a 4byte int signed or unsigned is01when you shift it 31 times to the left you end up with10no i know shifting left for positive numbers is essentially 2k where k is how many times you shift it assuming it still fits within bounds why is it i get such a bizarre number,['c++'] +669681,deserialize dynamic json string using newtonsoft jsonnet i have a json string that i am getting from facebook api in which i have a node whose name changes according to its content for example some time it is 45 or 58 etcit could be any numberi want its value how to get itexampledata id 1492292372 10201810786059989 created time 20140405t0900540 id 1492292372 10201804679827337 created time 20140404t0729070 id 1492292372 10201804649306574 created time 20140404t0710330 id 1492292372 10201801316823264 created time 20140403t183150 id 1492292372 10201798962284402 created time 20140403t0624470 message tags 0 id 1492292372 name yawar sohail type user offset 0 length 12 15 id 1489845168 name zeeshan anjum type user offset 15 length 13 id 1492292372 102017962747216 created time 20140402t1757050 id 1492292372 10201794080482360 created time 20140402t0726230 inside message tags there are two nodes 0 and 15 they dynamically changes according to their offset values i want names type and ids inside these nodes,['c#'] +669683,grep whole server for shell hacksmalware we host 10s of domains on multiple servers we have problems with massive amount of malware and phpshells the usage of many scanners had no effect in taking them down maybe we got 1020 vague results from those scannersso i build my own little bash file to find those scripts it found 148 phpshells this weekend im not that good at creating sh filesmy questionthe grep is terrible slow it will run for days how can i make this script more efficientarray base64 decode substrmd5strrev cwd getcwd chrord gzinflatebase64 decode php uname chrord cwdstrlencwd ini getsafe mode x62 r r documentreferrer ifstrtouppersubstrphp os 0 3 win windowtoplocationhrefhttp ini getthisable functions g3g3rg3hg3y hackedfor value in arraydo printf nvalue start date tn grep l inr value home printf nend date tndonefinal resultbinbashlc allc grep f n r f rootscannerpatterntxt homepatterntxt eval evalstripslashes postevalstripslashesarray popevalbase64 decodeevalgzinflatestr rot13base64 decodegzinflatebase64 decodearraybase64 decodesha1base64 decodeprintbase64 decodewsoscandirdirsubstrcurrentarray keyscwd getcwdo0urldecodel l base322substrmd5strrevcwdstrlencwdx62 r r documentreferrerifstrtouppersubstrphp os 0 3 winifcopycopyendlesshtmlsystemwgetsymlinksymrootcopy filesfiletmp nameerror reporting0ifx6cx28x67x7ax69ex28x65x76x61preg replaceewindows1251preg replace exit ifissetsystemcmd diertrimsecurity code,['php'] +669704,jquery sort table data i got struck in sorting tds in table using jquery my demo fiddlehow can i call it for any table with id in my projectvar sort this var table mytable var rows tbody gt trtable rowssortfunctiona b var keya tdeq0atext var keyb tdeq0btext ifsorthasclassasc return keya gt keyb 1 0 else return keya lt keyb 1 0,['jquery'] +669735,can i immediately start a new ajax request after aborting for the previous one i have a web application where the https handshake take place for every connection and i am determined to find out why the http keepalive is working so it is something else that forces a request to start a new https handshake when it should noti have something like this pseudocode startnewrequest if oldrequest oldrequestabort abort old request oldrequest ajax start new request the request object is xmlhttprequest returned by jquerys ajax method everytime when i start a request i abort for the previous requestmy questions is that whether this would force a new request to start a http handshake because the old one has not been completed the requests are regular post do i need to explicit wait for about to complete before starting off a new request so to take advantage of the http keep alivei do get a call in the error callback for ajax for every request i abort do i need to start a new request only after i get a callback in the error handler,['jquery'] +669737,lambda expression join multiple tables with select and where clause i have three table many to many relationship i have joined the three table and select the value i want but now i need to select one row from the query result by where by specifying the id this is my three table and this is the query using linq lambda expression databasecontext db new databasecontextpublic actionresult index var userinrole dbuserprofiles joindbusersinroles you uuserid uir uiruserid u uir new u uir joindbroles r ruirroleid ro roroleid r ro new r ro selectm new addusertorole username mruusername rolename mrorolename return viewuserinroletolistthe result will be like that using sql query sql query select from userprofile you join webpages usersinroles uir on uuserid uiruserid join webpages roles r on uirroleid rroleid result of the sql query now i use anther sql query to filter the result of previews sql query by where and set the condition to where uuserid 1 to only give me back the user with the id 1 like that select from userprofile you join webpages usersinroles uir on uuserid uiruserid join webpages roles r on uirroleid rroleid where uuserid 1and the result of this sql query so how can i add the where clause to my lambda expression to give me the same result as the result of the sql query and thanks for any help,['c#'] +669744,font family open sans not being used i am using googles open sans font in my applicationi have defined the stylesheet as instructedlink href relstylesheet typetextcssi then used it on the body selector as body fontfamily open sans sansserifi have not defined font family anywhere else i assume that since i have defined it at the parent the child elements will automatically inherit ithowever if i open up the inspector for say an anchor tag in my application and see the computed styles for that tag i find that chrome latest the rendered font says times new roman 18 glyphs is this correct i was expecting it to say open sans is the open sans font not being applied,['css'] +669750,gmsgeocoder how to set response language when using my app in a foreign country the google gmsgeocoder is returning the response in local language automatically how can i set it to always return the the response in englishim using gms sdk 17 and my code is something like thisgmsgeocoder geocoder gmsgeocoder alloc initgeocoder reversegeocodecoordinateselfcelocationcoordinate completionhandlergmsreversegeocoderesponse respones nserror err ifrespones firstresult gmsaddress address respones firstresult nsstring fulladdress nsstring stringwithformat addressthoroughfare addresslocality selfthetextfieldtext fulladdress else selfthetextfieldtext,['ios'] +669751,capistrano 3 deploy asking for ssh passphrase but cannot type it in i am trying to use capistrano 3 to deploy a rails 4 applicationconfig valid only for capistrano 31lock 310set application testappset scm gitset repo url sergiotapiatestappgitset user deploy the user on the vps serverset password hunter2set use sudo falseset deploy to homedeploywtestappset deploy via remote cacheset pty trueset format prettyset keep releases 1set rails env productionset migrate target latestnamespace deploy do desc restart application task restart do on rolesapp in sequence wait 5 do your restart mechanism here for example execute touch release pathjointmprestarttxt execute touch release pathjointmprestarttxt system curl silent fetchping url end end after publishing restart after restart clear cache do on rolesweb in groups limit 3 wait 10 do here we can do anything such as within release path do execute rake cacheclear end end endendwhen running cap production deploy i get the following messagedebug 322bb1fd enter passphrase for key homedeploysshid rsa when i type in the terminal i can see the characters normally you just see whitespace when typing in passwords rightdebug 484154d4 enter passphrase for key homedeploysshid rsa qwefewfqwefqwefwqefqwefwqefccap abortedinterrupt i type in the password and press enter and it just stays there without any new developments i have to ctrl c to actually leave the terminalcan i set my ssh password in the deployrb file,['ruby-on-rails'] +669756,what does inherently threadsafe mean i came across this line some functions are inherently threadsafe for example memcpywikipedia defines threadsafe asa piece of code is threadsafe if it only manipulates shared data structures in a manner that guarantees safe execution by multiple threads at the same time ok but what does inherently mean is it related to inheritance,"['java', 'c']" +669774,mysql job failed to start i am on kubuntu 1204 and after installing mysql via an aptget mysql ver 5535 i am trying to start mysql service but i got this errorsudo service mysql startstart job failed to startso i googled this problem it says i have to go to the varlogmysqlerrorlogbut my errorlog file is empty then i checked the permissionsdrwxrs 2 mysql adm 4096 apr 7 1121 mysqlrwr 1 mysql adm 0 apr 7 1121 errorlogso i do not know what to do why this error why is the error file empty,['mysql'] +669819,difference between http module and owin middleware i went through and was wondering what is the difference between http module and owin middleware some pointers that i can think of are 1 owin middleware decouples the application from hostserver so that it is no longer necessary for me to hook my application logic specifically to systemweb2 owin middleware are executed in the order they are added not sure if the same holds true for httpmodules may be depends on how i have added them in webconfig3 httpmodules helps me to attach my code specific to a application events owin middleware is independent of these eventsplease also let me know of practical example of using a owin module and not a httpmodule some more links i ended up reading i will keep on adding here as and when i encounter newupdate perhaps this has the anwer i was looking for when should i use owin katanathanks,['asp.net'] +669822,remove max or min from collection using java8 streaming api i have little problem with code design that use new streaming api from java 8 i would like to learn new things and one of the task isreject max and min from list list not contains duplicateslooks simple nope my code listinteger ranges listsnewarraylistnew range1 15 listinteger collect rangesstream filterx x rangesstream maptointintegerintvalue max getasint filterx x rangesstream maptointintegerintvalue min getasint collectcollectorstolist assertthatcollecthassize13 ok assertthatcollectisequaltolistsnewarraylistnew range214 okthis code is good if only we dont have duplicates of minmax but this is not a core problem here but problem is that i use here three streams first is main stream second to remove max and third to remove min is there any possibility to do this task in one streameditvery primitive scala versionval list listrange1 15sortwith tailreversetailwith additional sort because we could have shuiffeled list,['java'] +669884,location of generated source files for maven directory structure besides srcmainjava folder we have one folder that contains some generated java sources that are required for the main sources code generation is invoked manually when needed generated source is checked into the source repo everything will be built and packed togetherwhat would be the best location for generated java sources that are going to be compiled together with main sources should it besrcgeneratedjava following the same naming logic for srctestintjava for integration testsgeneratedsrcmainjava in collision with the src directory contains all of the source material for building the projectsrcmaingeneratedjava well generatedjava is not a typethe first option seems like the most appropriate one for this case what do you think is there anything in maven docs that describes this situation that i have overlooked do you know any repo with similar structurethank youansweras suggested by absurdmind direction we are thinking about is to split the source into the submodules which works nice in gradle so the generated source and some other related source will go into its own submodule they will produce the separate artifact and the rest will go in other submodule that uses this one thank you,['java'] +669905,keyboard interrupt in debug mode pycharm is there any way to send a keyboard interrupt event in pycharm ide 31 while in the debugging mode,['python'] +669979,reusing preparedstatement when using datastax cassandra driver i am currently using the datastax cassandra driver for cassandra 2 to execute cql3 this works correctly i started using preparedstatementssession session sessionprovidergetsessiontry preparedstatement ps sessionpreparecql resultset rs sessionexecutepsbindobjects if irsr null irsrreadrs sometimes i get a warning from the driver in my logrepreparing already prepared query please note that preparing the same query more than once is generally an antipattern and will likely affect performance consider preparing the statement only oncethis warning makes sense but i am not sure how i should reuse the preparedstatementshould i just create all my preparedstatement in a constructorinit method and than simply use thembut does this go well when multiple threads use the same preparedstatement at the same time especially calling preparedstatementbind to bind objects,['java'] +670006,why does for x in listnonenone work i have a script that attempts to read the begin and end point for a subset via a binary search these values are then used to create a slice for further processingi noticed that when these variables did not get set the search returned none the code would still run and in the end i noticed that a slice spanning from none to none works as if examining the entire list see example below usrbinenv pythonlist 12345678910for x in listnonenone print xdoes anyone know why the choice was made to see the listnonenone simply as list at least that is what i think that happens correct me if i am wrong i personally would think that throwing a typeerror would be desirable in such a case,['python'] +670027,how to get a range of items from stream using java 8 lambda in a previous question how to dynamically do filtering in java 8 stuart marks gave a wonderful answer and provided several useful utilities to handle selection of topn and toppercent from streami will include them here from his original answer functionalinterfacepublic interface criterion streamwidget applystreamwidget scriterion topncomparatorwidget cmp long n return stream streamsortedcmplimitncriterion toppercentcomparatorwidget cmp double pct return stream listwidget temp streamsortedcmpcollecttolist return tempstream limitlongtempsize pct my questions here are 1 how to get top items from 3 to 7 from a stream with certain amount of items so if the stream has items from a1 a2 a10 the call totopnfromrangecomparatorwidget cmp long from long to topnfromrangecomparingwidgetlength 3l 7lwill return a3 a4 a5 a6 a7 the simplest way i can think of is get the top 7 t7 from original get the top 3 t3 from original and then get t7 t32 how to get top items from top 10 to top 30 from a stream with certain amount of items so if the stream has items from x1 x2 x100 the call totoppercentfromrangecomparatorwidget cmp double from double to topnfromrangecomparingwidgetlength 010 030will return x10 x11 x12 x29 x30 the simplest way i can think of is get the top 30 tp30 from original get the top 10 tp10 from original and then get tp30 tp10what are some better ways to use java 8 lambda to concisely express the above situations,['java'] +670111,rails psych updating libyaml from 014 i needed capybarawebkit installed which needed the qt libraries so i went and installed them using homebrew with the following commandsbrew updatebrew install qtbrew linkappsi then bundled and all was well with the capybarawebkit however my guard is throwing the below warning you appear to have an outdated version of libyaml 014 installed on your system prior to 016 libyaml is vulnerable to a heap overflow exploit from malicious yaml payloads the easiest thing to do right now is probably to update psych to the latest version and enable the bundledlibyaml option which will install a vendored libyaml with the vulnerability patched gem install psych enablebundledlibyamlseemed simple enough however even after a successful psych installation with the bundledlibyaml option i am still seeing this warning about outdated libyaml further when i check the version of libyaml associated with psyche ruby rpsych e p psychlibyaml version it is still 14any ideas,['ruby-on-rails'] +670164,unbound classpath container jre system library java se 6 160 65b14462 in project i am trying to run an existing java project in eclipse and i am very new to java and eclipse so i am unable to figure out why this error is coming in the projecthere is the complete errordescription resource path location type unbound classpath container jre system library java se 6 160 65b14462 in project info 2413 server info 2413 server build path build path problem,['java'] +670331,malwarebytes gives trojan warning for basic c hello world program basically i just ran a scan of my computer with malwarebytes updated the definitions before running and it said my helloworld program written in c has a trojani know for a fact this is a false positive as i only wrote the program 23 days ago and followed a small tutorial website to make the program that i trust i am new to c but i cannot see anything that would give a trojan warning at allthe program flags the executable but not the source fileusing systemnamespace helloworldapplication class helloworld static void mainstring args consolewritelinenthello world consolewritelinethis is my first c programni am so proud of myself consolewritelinetteehee this is the code written in notepad and it is run from the commandline cygwin actually why does it flags this is it something that as a budding c programmer i should know about,['c#'] +670363,how do you uninstall all your bower packages sometimes it is useful to rebuild an entire site and force bower to reinstall new versions of all the packages in bowerjsonhowever there does not seem to be any way of doing thatattempt 1 bower uninstallbower notinstalled 0nope that only works on a packagebypackage basis even though a clean bower install uses bowerjson attempt 2 bower install f l 0nope despite f this does absolutely nothing if the dependencies are metattempt 3 rm r bower components ah victory wait whats thisrm bower components no such file or directoryoh darn there is a bowrc in this project that sets the directory to install things tomy current terrible solutionrun custom script that parse bowerrc if one exists load the directory if one is specified in the json block if the directory currently exists recursively delete the directoryit works i suppose but it is pretty annoying to have to setup repeatedlyam i missing somethingis there not just a simple bower command to delete the local installed modulesseems like really basic functionality i would expect bower uninstall to dothis is not really a very javascript question but i will happily accept something that hooks into the bower module somehow to make this happen in a simple node scriptcontextedit if you want motivation for such a task it is this we have a jenkins server that builds our projects and runs tests however periodically it fails for no obvious reason investigating it is almost always because jenkins is using a previous copy of the repository with just a gitpull to update to the most recent version before building and running tests as a result the previous bower components directory is there and it is full of cached copies of the various componentshere a few example of things which are d and require bower to be run again as a forced install1 some idiot fitvids deletes the previous tagged release of a project2 some project has dropped off of bower moved its github page3 some project jquery has changed the way the files are laid out in a nonmajor version revisioni realize that the correct solution to this problem is fix jenkins so it creates a new temporary directory for each build but that is not in my controlso as a build step i need to automate a way to delete the bower components and force them to all be reinstalled either as a grunt task part of the build or a jenkins build step however remember from 3 above that our projects use bowerrc so it is not as simple as simply deleting a folderit would be great if i could uninstall all the existing bower components as a prebuild step to make this workso back to the question can this be done with bower,['javascript'] +670516,angularjs directive wrap content and keep attributes on original element i am quite new to angularjs and still learning i have a bit of trouble creating a directive that wraps the element and its children that the directive is applied to i do not get why this seemingly common scenario should be so difficult considering how easy many other commonplace things are in angularjs so it could very well be that i am missing something herewhat i want to do is to wrap a select element in a div i am using transclude to preserve the original select element and its content but i cannot get it to work correctlythe html looks like thisselect mlbselect ngoptionsoptval as opttext for opt in mlb ngmodelmlboptselectand my directive looks like thisdirectivemoduledirectivemlbselect function return template div classmlbselect select ngtranscludeselect div transclude element replace true the resulting html looks like thisdiv classmlbselect ngpristine ngvalid mlbselect ngoptionsoptval as opttext for opt in mlb ngmodelmlbopt select ngtransclude classngscopeselectdivof course this is not what i want why are the properties of my select element added to the wrapping div and not the element i specify with the ngtransclude attribute the select element needs to retain the ngoptions and ngmodel propertieswhat do i need to do to accomplish this,['javascript'] +670600,apachephp large file download 2gb failing i am using a php script to control access to download files this works fine for anything under 2gb but fails for larger filesapache and php are both 64bitapache will allow the file to be downloaded if accessed directly which i cannot allowthe guts of the php ignoring the access controlif ob get level ob end cleanerror logfiletest path filesizepathheadercontentdescription file transferheadercontenttype applicationoctetstreamheadercontentthisposition attachment filenamebasenamepathheaderexpires 0headercachecontrol mustrevalidateheaderpragma publicheadercontentlength filesizepathreadfilepathexitthe error log shows the file size finetue apr 08 110116 2014 error client filetest downloadsfilename 2251373807 referer httpmyurlfilesbut the access log has a negative size 08apr2014110116 0100 get filesfilename http11 200 2043593489 httpmyurlfiles mozilla50 windows nt 61 wow64 rv240 gecko20100101 firefox240and so browsers refuse to download the file in fact using wget it is not sending anything wget s o httpmyurlfilesfilename20140408 1138 httpmyurlfilesfilenamehttp request sent awaiting response no data receivedretrying,['php'] +670637,uncaught indexsizeerror failed to execute getrangeat on selection 0 is not a valid index what is problem hereif windowgetselection editfield windowgetselectiongetrangeat0throws error uncaught indexsizeerror failed to execute getrangeat on selection 0 is not a valid index,['javascript'] +670665,windows 81 selection mode in gridview in a windows store app i have a gridview in xaml i have set the selectionmodeextended and i can select items without any kind of problem however i want to achieve windows 81s selection mode in windows 81s touch version when you hold your finger on an item in start screen the whole screen goes to some sort of management mode in which tapping on an item will select it tapping anywhere on the screen or quickly on items will deselect all of them and tapping on anywhere when nothing is selected moves out of this mode heres a picture of that modei can achieve something like this if i try to implement it myself however i just wonder if there is already something like this out there,['c#'] +670745,convert milliseconds to hours and minutes using momentjs i am new to momentjs i am trying to use it to convert milliseconds to hours and minutes below x is millisecondsx 4332760var y momentdurationx millisecondsashourscan anyone help,['javascript'] +670771,when should i use arrow functions in ecmascript 6 the question is directed at people who have thought about code style in the context of the upcoming ecmascript 6 harmony and who have already worked with the languagewith and function we are getting two very similar ways to write functions in es6 in other languages lambda functions often thistinguish themselves by being anonymous but in ecmascript any function can be anonymous each of the two types have unique usage domains namely when this needs to either be bound explicitly or explicitly not be bound between those domains there is a vast number of cases where either notation will doarrow functions in es6 have at least two limitationsdo not work with newfixed this bound to scope at initialisationthese two limitations aside arrow functions could theoretically replace regular functions almost anywhere what is the right approach using them in practice should arrow functions be used egeverywhere they work ie everywhere a function does not have to be agnostic about the this variable and we are not creating an objectonly everywhere they are needed ie event listeners timeouts that need to be bound to a certain scopewith short functions but not with long functionsonly with functions that do not contain another arrow functionwhat i am looking for is a guideline to selecting the appropriate function notation in the future version of ecmascript the guideline will need to be clear so that it can be taught to developers in a team and to be consistent so that it does not require constant refactoring back and forth from one function notation to another,['javascript'] +670817,how do you animate table rows using nganimate in the same way as one would list items it is quite simple to smoothly animate lists using angulars nganimate but tables seem to be another storyplunker listplunker tablethe table move animations do not work the items just snap into place i suppose some other cssjs is required for the table but i am not sure what would work i tried a lot of things with no successi am sure it is possible for example there is this jquery table animationbut how does this translate to angular animate do i have to delve into some jsjquery dom manipulation through a directive or is there another wayeither way i would like to see an elegant way to do this in angular,"['javascript', 'css']" +670890,gain from threading much less than expected why i have a function evaluation which is somewhat slow i am trying to speed it up by using threading since there are three things which can be done in parallel the singlethreaded version isreturn dedx shorte dedx longe dedx quantumewhere evaluation of those functions takes 250us 250us and 100us respectively so i implemented a threethread solutiondouble ret short ret long ret quantum return values for the termsauto shortf thiseret short ret short thisdedx shortestdthread t1shortfauto longf thiseret long ret long thisdedx longestdthread t2longfauto quantumf thiseret quantum ret quantum thisdedx quantumestdthread t3quantumft1joint2joint3joinreturn ret short ret long ret quantumwhich i expected to take 300us yet it actually takes 600us basically the same as the singlethreaded version these are all inherently threadsafe so there are no waits for locks i checked the thread creation time on my system and it is 25us i am not using all of my cores so i am a bit baffled as to why the parallel solution is so slow is it something to do with the lambda creationi tried to bypass the lambda egstdthread t1stoppow bpsdedx short this e ret shortafter rewriting the function being called but that gave me an error attempt to use a deleted function,['c++'] +670894,bootstrap push div content to new line somehow i can not get out how to finish my code which i formatted as a list and need to format it as grid too which is switched by javascriptmy html code below is used to list a contentdiv classlist div classrow div classcollg3 colmd3 colsm3 colxs12right is next divdiv div classcollg6 colmd6 colsm5 colxs12right is next divdiv div classcollg3 colmd3 colsm4 colxs12i am the last divdiv divdivthe css code for the list all other css is taken by bootstrapstyled view divlist padding 0 width 100the same code should be used to show griddiv classgrid div classrow div classcollg3 colmd3 colsm3 colxs12under me should be a divdiv div classcollg6 colmd6 colsm5 colxs12under me should be a divdiv div classcollg3 colmd3 colsm4 colxs12i am the last divdiv divdivthe css for the gridstyled view divgrid thisplay inlineblock overflow hidden verticalalign top width 194the 194 for each part of gallery keeps the divs next to next it will not push it to a new line how could i solve it,"['html', 'css']" +670946,xunit not awaiting async test on vs 2013 i cannot get this async test to faili have xunit 1801539 installed from nuget with the xunit test runner vs extension 0995 all current afaiki happen to also have moq autofixture and fluentassertions reference in the unit test but i do not think that matters but i am admitting it in case it doesi have done async unit tests in other areas of my solution and they worki am missing something with this newly created tests and i cannot tell what i am missing or doing wrongnote the sut code is not meant to be complete i am just trying to get the red light first before i write the code to make the test go greenheres the test codeusing systemthreadingtasksusing fluentassertionsusing xunitnamespace mobileaproxytestpublic class whenretrievingpricedatafromclient fact public async task groupreportisreturnedwithsomedata arrange var sut new client act var actual await sutgetreportgroupasync assert xunit test assertnullactual assertnotnullactual fluentassertions actualshouldbenull actualshouldnotbenull and here is the sut codeusing systemusing systemdiagnosticsusing systemnethttpusing systemthreadingtasksusing mobileaproxypropertiesnamespace mobileaproxy public class client public async taskreportgroup getreportgroupasync return await taskfromresultnew reportgroup obviously this test should fail the asserts for null and notnull cannot both succeed so my conclusion is that the test is exiting before it finishes getting the response from the sutwhat did i missor is there a better way i should have started an async test to make sure it fails before writing the sut code,['c#'] +670970,invalid method reference for overloaded method with different arities when trying to compile the expression comparatorcomparingstringtolowercase the java compiler returns an error see the following question for more informationwhy comparatorcomparing doesnt work with stringtolowercase method referencei have tried to reduce the problem as much as possible in particular i have removed almost all dependencies to other classes the main method contains two method invocations the first statement compiles without errors whereas the second statement produces an errorinterface funt r r applyt t public final class foo public static void mainstring args invokefoobar ok invokefoobaz error private static t u void invokefunt u f private string bar return null private string baz return null private string bazinteger i integer j return null this is strange because the second baz method should not be applicable in this context due to the mismatch in the number of parameters i have taken a look at the jls8 1513 however it was no help because the rules for method references are quite complexq why is there a compilation error for the second case should there really be a compilation error according to the jls according to some comments on the other question there is no compilation error in netbeansfor reference i am using the jdk8 version 180b132 if a compile the program on the command line the compiler shows the following error message optjdk8binjavac foojavafoojava6 error incompatible types cannot infer typevariables tu invokefoobaz error argument mismatch invalid method reference no suitable method found for bazobject method foobaz is not applicable actual and formal argument lists differ in length method foobazintegerinteger is not applicable actual and formal argument lists differ in length where tu are typevariables t extends object declared in method tuinvokefuntu you extends object declared in method tuinvokefuntufoojava6 error invalid method reference invokefoobaz error nonstatic method baz cannot be referenced from a static context2 errors,['java'] +671019,seek through massive data grouped with multiple keys c i want to seek through massive data grouped with multiple keys in the fastest way possiblei have a file with this information but i want to load it inmemory memory capacitance is not a problemkey1 key2 key3 key4 value1 value21 1 1 1 str 201 1 1 2 str 201 1 1 3 str 201 1 2 1 str 202 1 1 1 str 20i have looked at some collections but i am still uncertain maybe a multikey dictionary will be better because it avoid a lots of redundancy in the keys public class multikeydictionaryt1 t2 t3 dictionaryt1 dictionaryt2 t3key1 key2 key3 key4 value1 value21 1 1 1 str 20 2 str 20 3 str 20 2 1 str 202 1 1 1 str 20i will not seek every keys but maybe 50 of themi am open to even insane suggestions,['c#'] +671030,how to get availablefree sdcard space in android with adb command i am trying to get free sdcard space with adb command but i could not able to achieve any suggestions how to get the sdcard space,['android'] +671089,how to detect if ajax error is accesscontrolalloworigin or the file is actually missing my question is not about how to solve the accesscontrolalloworigin issues this errors will happen sometimes when performing requests and other times the urls might be outdated but i want to print different messages for the user depending on the different errors currently i have the following codeajax url link typehead timeout 20 error functionrequest status message consolelogajax error consolelogrequest consolelogstatus consolelogmessage openpopupthere was an error accessing the image it can be because the address is invalid or because the server where the image is stored is not allowing direct access to the images success function more stuff here looking at the console it is easy to see if the file was actually missing or if it was an accesscontrol problem but i would like to print out two different messages to the user saying exactly what the problem was looking at the variables in error functionrequest status message they do not change both cases result in a 404 error is there some other was to do this so that i can know what the problem wasthank you in advance for the attention,"['javascript', 'jquery']" +671118,validates inclusion of no longer working the same in rails 41 the following code made sure that a time zone chose is within the time zones in activesupporttimezoneus zonesvalidates inclusion of time zone in activesupporttimezonezones mapnameworked great in rails 40 just upgraded to rails 41 and i am getting this error on my index page so just simply viewing the modelsan object with the method include or a proc lambda or symbol is required and must be supplied as the in or within option of the configuration hashi am guessing from that activesupporttimezonezones mapname is no longer a valid value for the in property,"['ruby-on-rails', 'ruby']" +671156,sqlplus sp20734 error i am new to using sqlplus but not new to using sql and i get the following error after writing this in my editor and attempting to run the script that i wrote all of this appears to be valid and works on sql fiddle i am not sure what the issue is any ideas none of the files i create seem to worksql start salessqwhich contains1 create table salesreps2 empl num number30 primary key3 name varchar215 not null4 age number305 rep office number206 title varchar2107 hire date varchar210 not null8 manager number309 quota number10210 sales number102 not nullgenerating the following errorssp20734 unknown command beginning name varch rest of line ignoredsp20734 unknown command beginning age number rest of line ignoredsp20734 unknown command beginning rep office rest of line ignoredsp20734 unknown command beginning title varc rest of line ignoredsp20044 for a list of known commands enter helpand to leave enter exitsp20734 unknown command beginning hire date rest of line ignoredsp20734 unknown command beginning manager nu rest of line ignoredsp20734 unknown command beginning quota numb rest of line ignoredsp20734 unknown command beginning sales numb rest of line ignoredsp20044 for a list of known commands enter helpand to leave enter exit,['sql'] +671270,meaning of error numbers in python exceptions catching pythons overflowerror after some dumb calculation i checked the errors args and saw it is a tuple containing an integer as its first coordinate i assume this is some kind of error number errno however i could not find any documentation or reference for itexampletry 1e4100except overflowerror as ofe print ofeargs prints 34 numerical result out of rangedo you know what 34 means in this context do you know other possible error numbers for this exception,['python'] +671271,how to find key listener on any where in window i have develop one java desktop application which monitor the work of the user now i want to count the number of key press and number of mouse click anywhere in systemthat means when ever my application is running and user typing something in browser or open any folder then mouse click and key press count is incrementcan i use below code keyboardfocusmanagergetcurrentkeyboardfocusmanageraddkeyeventthispatcherif yes then how it is possible and if i cannot use that then please say me fast how it is possible i am beginner in java,['java'] +671291,cakephp xml utility library triggers domdocument warning i am generating xml in a view with cakephps xml core libraryxml xmlbuilddata arrayreturn domdocumentecho xmlsavexmlview is fed from the controller with an arraythisset array data array root array array id a b ok name c d ok sub1 array id e f ok name g h ok sub2 array array id i j ok name k l ok sub3 array id m n ok name o p ok sub4 array id q r ok s t error for whatever the reason cakephp is issuing an internal call like thisdom new domdocumentkey sub4childvalue s t errordomcreateelementkey childvalue which triggers a php warningwarning 2 domdocumentcreateelement unterminated entity reference t corecakeutilityxmlphp line 292 because as documented domdocumentcreateelement does not escape values however it only does it in certain nodes as the test case illustratesam i doing something wrong or i just hit a bug in cakephp,['php'] +671316,is the vc code dom accessible from vs addons visual studio intellisense for vc includes the complete edg c parser also used by intel and others since the c code dom is accessible to addons correct me if i am wrong is the c code dom also accessible can this be used to analyse an open vc project within the vs environment,['.net'] +671417,parse cloud code relational query syntax i have a cloud function on parse when it is called it retrieves a pfobject then adds a relation between that object and the user this part works fine seen towards the end of the functioni am having trouble getting the query that selects the pfobject to ignore those that the user is already related tohere is my codeparseclouddefinenextmedia function request response var likerequest parseobjectextendlikerequest var query new parsequerylikerequest queryequaltocompleted false consoleloguser parseusercurrentid querynotequaltouser parseusercurrent also only fetch if never been sent before here should use the below relationship var innerquery new parsequeryparseuser innerqueryexistsparseuser querymatchesquerysentto innerquery queryascendingcreatedat queryfirst success function object successfully retrieved the object consoleloggot 1 object objectgetmediaid record that the user has been sent it var user parseusercurrent var relation objectrelationsentto relation added here relationadduser objectsave responsesuccessobject error function error consolelogerror errorcode errormessage responseerrorerror getting next mediaid i am sure i am just not understanding how the relation query syntax works,"['javascript', 'sql']" +671524,rtl support thisabling it only for specific ui components i have a custom video player activityi am forced to enable rtl support in my applicationbut doing so will result in a righttoleft aligned progressbar and that looks uglyi want my progressbar to stay ltr in my rtl enabled application is there any solutionps i am using android 422,['android'] +671536,linuxc getting users directory without leaks what am i doing wrongly that there are memory leaks in the following code which simply tries to read the home directory of the userstatic stdstring gethomedir struct passwd pw getpwuidgetuid stdstring res pwpw dir endpwent return resvalgrind complains32757 160 40 direct 120 indirect bytes in 1 blocks are definitely lost in loss record 42 of 4832757 at 0x402bb7a malloc in usrlibvalgrindvgpreload memcheckx86linuxso32757 by 0x456e84e nss parse service list nsswitchc67832757 by 0x456efc9 nss database lookup nsswitchc17532757 by 0x4a8e168 32757 by 0x4a8fb5c 32757 by 0x4525fa6 getpwuid rglibc 212 getxxby rc25632757 by 0x45258ed getpwuid getxxbyc11732757 by 0x805ad56 gethomedir configreadercpp73also as a sidenote man getpwuid show an example program that also leaks the same amount of memoryand for those who want to compare with their linuxesuname a gives linux reference 35047generic 71ubuntu smp tue feb 18 235930 utc 2014 i686 athlon i686 gnulinux basically ubuntu 1210,['c++'] +671567,adding bootstrapjs to browserify so i am trying to figure out how to do this i downloaded bootstrapsass via bower and added the bootstrap javascript into a shima few things have me confused the bootstrapjs file looks like this require bootstrapaffix require bootstrapalert require bootstrapbutton require bootstrapcarousel require bootstrapcollapse require bootstrapdropdown require bootstraptab require bootstraptransition require bootstrapscrollspy require bootstrapmodal require bootstraptooltip require bootstrappopoverthis is kind of self explanatory but still confusing at the same time do i leave it commented like that when i add to the bootstrap shim do i include just the bootstrapjs file or should i link to all the ones i need just to save myself from hacking away which i will be doing in the meantime i would like to try to get some information on how to include bootstrapjs into browserifyedit i think i might just have to concat all the files i need and include that script because when i browserify the bootstrapjs i just get the abovei will try without the comments then if that fails i will concat all the scripts into one file and see what happens edit hmm looks like the concat theory works the only thing is jquery take a look jquery globaljquery requirecwampwmysiteappclientrequiresjqueryjsjqueryjs bootstrap affixjs v311 copyright 20112014 twitter inc licensed under mit this is my compiled browserify code the only way to get it to work when i call a bootstrap function say for example bodymodaltoggle i have to change the jquery above to manuallyi tried using both inside my shim but still same thing i must manually write example notice i use here not jquery like above this is the only way to get it to work globaljquery requirecwampwmysiteappclientrequiresjqueryjsjqueryjs bootstrap affixjs v311 copyright 20112014 twitter inc licensed under mit,"['javascript', 'jquery']" +671631,aspnet randomly stops obeying forms authentication whitelist the problemlast month we move our aspnet website farm from server 2008 r2 to server 2012 r2 and upgraded to aspnet 45 we are using cookied forms authentication to prevent unauthorized access to the websiteauthorization deny users allow users authorizationwe have certain assets and pages ex sign in page that are whitelisted in the webconfig location pathsignin systemweb authorization allow users authorization systemweblocationover the last few months weve been noticing that iisaspnet randomly stops obeying the whitelist and assume everything needs to be authenticated all requests to the site on that server will be redirected to the signin page which then throws a 500 error no whitelisted assets can be retrieved there are then 2 errors in the event viewer that we can see when iis is messed up the firstexception type nullreferenceexception exception message object reference not set to an instance of an object at systemwebpipelinemodulestepcontainergetnexteventrequestnotification notification boolean ispostevent int32 eventindex at systemwebhttpapplicationpipelinestepmanagerresumestepsexception error at systemwebhttpapplicationbeginprocessrequestnotificationhttpcontext context asynccallback cb at systemwebhttpruntimeprocessrequestnotificationprivateiis7workerrequest wr httpcontext contextthis second one does not show up all the time event code 4005 event message forms authentication failed for the request reason the ticket supplied has expired the iis process will be working find for hours then all the sudden start doing this weirdness as soon as we recycle the app pool or even just modify the webconfig the site starts working again things weve triedhonestly we are quite stumped this was not happening on our old servers but weve made quite a few changes to our site since then but nothing related to authentication we are in a webfarm and we define our machine key inside of our webconfig machinekey validationkeyx decryptionkeyx validationsha1 decryptionaes we are targeting aspnet 45httpruntime targetframework45 executiontimeout120 maxquerystringlength4096 minfreethreads72 minlocalrequestfreethreads88 maxrequestlength32768 we recreated the application pool within iisnot sure if it matters but we use iis shared config and shared certificates the issue is happening on all of the web servers in the farm not just one we reinstalled the os on one of the servers yesterday so well see if that fixes anything it does not seem to be tied to memory usage sometimes iis is only using 4gb sometimes 6gb it does not seem to be tied to a certain page execution that we can tell i have run debug diag against a memory dump and there are not any threads that are running long nor crazy memory usage yea we are stumped any help is appreciated,"['c#', 'asp.net', '.net']" +671778,does pandasseriesunique preserve order simple question i have not been able to find an answer to yetgiven a pandas series i think the order of values given by seriesunique is that in which they are first encountered in the series and not any sort sorted order ie from pandas import seriess seriesbaabsunique arrayb a dtypeobjectthis is the behavior i want for my application but can someone tell me if i am guaranteed to get this order the documentation is not clear,['python'] +671880,how to reset heroku rails4 asset pipeline cache according to heroku documentation heroku now caches 50mb worth of tmpcacheassets which is a cache directory for the asset pipeline to store intermediate files this means that future asset compilations will be faster due to not having to recalculate these filesmy question is how do i manually reset or delete this cache so that all of my assets have to be precompiled again i tried heroku run console and railscacheclear but it did not work the reason i want to reset the cache is i have changed the configaction controllerasset host in my productionrb file but heroku is not picking up on the change because of the cache,['ruby-on-rails'] +671993,rails secret key base not being recognized in production so i am trying to deploy my rails app in production when i go to the page i get a 500 error when i go to my error logs i get the following errorexception runtimeerror in rack application object missing secret key base for production environment set this value in configsecretsyml i am running rails 41 and my configsecretsyml looks like this development secret key base development key test secret key base test key do not keep production secrets in the repository instead read values from the environment production secret key base envsecret key base i ran rake secret to get the key and put the export in my bash profile and sourced it i ran rake assetsprecompile successfully yet i still keep getting this error any ideasupdate i tried to update the error message provided to give slightly better informationand the message did not update i then tried adding the key directly to the yml file instead of using an environment variable and still no dice im running on hostmonster so i cannot restart the serverbut something is telling me thats what needs to be doneupdate 2 after sleeping through the night it seems that this issue is no longer an issue it must have been some sort of caching now my issue is that its trying to use an old config that i changed days ago for my database if i figure out how to nullify the cache i will post it here and mark it as an answer if someone else knows how to do it please let me know and i will mark it as an answer i am using hostmonster as my hosting and followed the steps they have on their site for hosting my rails app,"['ruby-on-rails', 'ruby']" +671996,what does ynaxdh stand for yeoman so i am new to javascript automation stuff especially yeoman so new that i am still delighted by the ascii greet o a welcome to yeoman a u ladies and gentlemen a a a a y please excuse me if i have to ask the obvious question what does ynaxdh stand foryes no,['javascript'] +672099,where can possibly be a memory leak in php and how to investigate it i am using codeigniter framework development version from github for one of my projects project itself is not big just a few controllers and models and i have a memory leak in 12 hours my rams constantly go up and i have to restart php5fpm to clean them where should i start looking for memory leak i mean is it loops or variables and what tools can i use for this to investigate,['php'] +672155,is it possible to remove remembered wifi direct groups from android programatically weve noticed that when a wifi direct group is remembered by a device that it sometimes causes problems when the devices are reconnected later deleting the remembered groups seems to solve this problemit would be nice if we could do this within the application is this possiblesimply calling wifip2pmanagerremovegroup does not stop the device remembering them,['android'] +672190,what is the meaning of addtobackstack with null parameter i have a customer code there is only one activity for all of the fragments ie the single activity is managing all the fragmentsthis activity contains the following code for any fragment at the method end of that fragmentfor example fragment morefragmentmorefragment firstfragment new morefragmentgetsupportfragmentmanagerbegintransactionreplaceridarticle fragment firstfragmentaddtobackstacknullcommitso1 what is the meaning of addtobackstacknull followed by a commit 2 why you need to pass a null parameter to addtobackstack 3 how to get that fragment after being added like this seems like this code is useless as i ran the code without the last line addtobackstacknullcommit and it ran without any problems,['android'] +672221,explicit cast operator fails with assembly is not referenced error this is a very uncommon problem and there are definetly many workarounds but i would like to understand what is actually going on and why it is not workingso i have 3 assemblies in a test solution first assembly has type classapublic class classa public string name get set second assembly references first assembly and has classbpublic class classb public string name get set public static explicit operator classaclassb objb return new classa name objbname which has an explicit operator to cast to type classa let us say that we cannot use inheritance for some reason and just using casting as a convenient way of transforming one type to anothernow the last assembly references second assembly and not the first one and has type classcpublic class classc public string name get set public static explicit operator classbclassc objc return new classb name objcname which uses explicit cast operator for same reason as classbnow the interesting part if i try to cast from classc to classb in my code like thisclassc objc new classcclassb objb classbobjci get the following error error 1 the type firstassemblyclassa is defined in an assembly that is not referenced you must add a reference to assembly firstassembly version10 cultureneutral publickeytokennulli could easily create new instance of classb and just initialize it with values from classc instance like i do inside explicit cast operator and it would work fine so what is wrong here,['c#'] +672307,what is the difference between return and return function a return 1 function b return1 i tested the above code in chromes console and both returned 1function c return 1 function d return1 i also tested the code above and both of the functions returned 1so what is the difference between using return and return,['javascript'] +672334,is resttemplate thread safe is a spring resttemplate threadsafe that isis a resttemplate a strategy object that multiple connections can safely share oris a resttemplate a connection object like a database connection which can not be shared while in use and requires creation afresh or pooling for each connection,['java'] +672345,confirmation before submitting form using jquery i am trying add a confirmation before a form is submitting using jqueryi found a nice example in form confirm before submit but i cannot get it to workjqueryfunction formdeletesubmitfunction var c confirmclick ok to continue return c templateform iddelete action url item delete itemid methodpost csrf token input classfloatright typesubmit valuedelete formhow can we achieve this,['jquery'] +672391,how to thisable emoji from being entered in android edittext most implementations of the text inputtype other than uri password etc for edittext and textview allow emoji although in most google keyboard configurations this button is hidden is there a way to thisable emoji from being entered in an edittext is there an inputtype parameter that could be paired with textmultiline that would thisable emoji,['android'] +672530,which initparam to use jerseyconfigserverproviderpackages or javaxwsrsapplication i am deploying jaxrs web services to a tomcat servlet containeri have seen code examples that use either of the following two methods of indicating the resources in the webxml filemethod 1 using the jerseyconfigserverproviderpackages initparam servlet servletnamejersey web applicationservletname servletclassorgglassfishjerseyservletservletcontainerservletclass initparam paramnamejerseyconfigserverproviderpackagesparamname paramvaluecomexampleparamvalue initparam loadonstartup1loadonstartup servletwhere the resources are expected to reside in the comexample package and i suppose are thiscovered by means of java rttimethod 2 using the javaxwsrsapplication initparamservlet servletnamejerseyserlvetservletname servletclassorgglassfishjerseyservletservletcontainerservletclass initparam paramnamejavaxwsrsapplicationparamname paramvaluefullqualifiednametomyapplicationparamvalue initparam loadonstartup1loadonstartupservlet where the myapplication class identifies explicitly the resource classespublic class myapplication extends javaxwsrscoreapplication public setclass getclasses setclass s new hashsetclass saddresourceaclass return sis using the one versus the other method purely a matter of taste and configuration effort and what are some tradeoffs to consider personally i prefer the more finegrained control offered by method 2 however the maven jersey 27 archetypemvn archetypegenerate darchetypeartifactidjerseyquickstartwebapp darchetypegroupidorgglassfishjerseyarchetypes dinteractivemodefalse dgroupidcomexample dartifactidsimpleservicewebapp dpackagecomexample darchetypeversion27 is using method 1 and that got me thinking,['java'] +672603,bootstrap offcanvas sidebar toggling for any canvas size could you please explain how offcanvas sidebar toggling worksi cannot make the actual sidebar thisappear for sm i can make the button visible visiblesm but toggling does not work the sidebar is always visibletoggling works for xs size that is fine but i want to make it work for sm the same way or any other size for that matterpartial answer changing maxwidth in offcanvascss makes toggling work for bigger sizes as well sm in this casemedia screen and maxwidth 991px 991px instead of 767px makes toggling work for sm as well rowoffcanvas and so on but there is still a problem when canvas width is between 780 and 991px the sidebar is visible even if it is toggled off any idea how to fix thisthanks a lot,"['javascript', 'html', 'css']" +672617,html would not render code block so i am using google code prettify with anchorcms all other languages but html work this is what i am trying to use pre classprettyprint langhtmldoctype htmlprebut i think that the editor is interpreting the html within the pre tags and that is why its not working heres what happens when i try to show the above code and there is this example that i used pre classprettyprint langjs on i am not really sure what to do now any ideas also sorry for the direct link to my website i wouldnt of been able to show it on jsfiddle,"['javascript', 'jquery', 'html']" +672791,angularjs show loading animation for slow script eg while filtering in angularjs 12 operations like filtering an ngrepeat with many rows 20 rows can become quite slow 1 seci know i can optimize execution times using limitto pagination custom filters etc but i am still interested to know if it is possible to show a loading animation while the browser is busy running long scriptsin case of angular i think that could be invoked whenever digest is running because that seems to be the main function that takes up most time and might be called several times in a related question there were no useful answers given any help greatly appreciated,['javascript'] +672902,move adjacent divs smoothly when a div hides fiddle linkwhen i click on the green div everything hides but the green div is jerky as in it comes right next to the first green div with a jerky motion is it possible to smooth transit so that it slides and takes its places right next to the first green divjsgreenclickfunction othersfadeoutcssgreen backgroundgreen padding10px margin10px red backgroundred padding10px margin10px blue backgroundblue padding10px margin10px greenhover cursorpointerfadethisplaynone opacity0div floatleft htmldiv classgreendivdiv classred othersdivdiv classblue othersdivdiv classgreendivdiv classred othersdivdiv classblue othersdiv,"['jquery', 'css', 'html']" +672987,amcharts with angularjs i am still strugling making work other libs with angularjs because of it is differtent logic from other libsi need to visualize data with amcharts stock but there is nothing on the internet about these two wroking togetherhow can i make this work with angularjs var chart amchartsmakechartchartdiv type stock theme none pathtoimages categoryaxessettings minperiod mm datasets color b0de09 fieldmappings fromfield value tofield value fromfield volume tofield volume dataprovider chartdata categoryfield date panels showcategoryaxis false title value percentheight 70 stockgraphs id g1 valuefield value type smoothedline linethickness 2 bullet round stocklegend valuetextregular markertype none title volume percentheight 30 stockgraphs valuefield volume type column cornerradiustop 2 fillalphas 1 stocklegend valuetextregular markertype none chartscrollbarsettings graph g1 useperiod 10mm position top chartcursorsettings valueballoonsenabled true periodselector position top dateformat ymmdd jjnn inputfieldwidth 150 periods period hh count 1 label 1 hour selected true period hh count 2 label 2 hours period hh count 5 label 5 hour period hh count 12 label 12 hours period max label max panelssettings useprefixes true thanks,['javascript'] +673047,ignored parameters in android sdk v4 since i switched to sdk v4 i notice this in logcat wgav3i1 threadmain5main int configuration name not recognized ga thispatchperiodwgav3i1 threadmain5main string configuration name not recognized ga appversionall the other parameters are good but those really seem to be ignored any ideas thanks,['android'] +673067,explicit decay of an array into a pointer what is the most concise and idiomatic way of explicitly decaying an array into a pointerfor example consider the case where you need to be able to guide sfinae or be explicit about an overloadtemplatetypename t stdsize t n void footxntemplatetypename t void foot x int x2 0 1foox,['c++'] +673070,is there any solution can send message to a group of user not all user using spring4 websocket recently i use spring4 websocket to push message to end user i known that there are 2 methods convertandsend convertandsendtouser to send message in class simpmessagesendingoperations but is there any way to send message to a group of user and the user out of group cannot subscribe the messagethank you very much,['java'] +673105,max retries exceeded with url i am trying to get the content of this url and its showing this errortraceback most recent call last file homepreethamdesktopegpy line 17 in module page1 requestsgetap file usrlocallibpython27thistpackagesrequestsapipy line 55 in get return requestget url kwargs file usrlocallibpython27thistpackagesrequestsapipy line 44 in request return sessionrequestmethodmethod urlurl kwargs file usrlocallibpython27thistpackagesrequestssessionspy line 383 in request resp selfsendprep send kwargs file usrlocallibpython27thistpackagesrequestssessionspy line 486 in send r adaptersendrequest kwargs file usrlocallibpython27thistpackagesrequestsadapterspy line 378 in send raise connectionerrorerequestsexceptionsconnectionerror httpsconnectionpoolhostitunesapplecom port443 max retries exceeded with url inappadobereaderid469337564mt8 caused by class socketgaierror errno 2 name or service not knownthe code is urlpage requestsgeturltree htmlfromstringpagetextflistplistfor i in range0100 app treexpathdivclasscolumn firstulliahref apapp0 page1 requestsgetapwhen i try the range with 02 it works but when i put the range in 100s it shows this error,['python'] +673209,why do ints require three times as much memory in python on a 64bit system an integer in python takes 24 bytes this is 3 times the memory that would be needed in eg c for a 64bit integer now i know this is because python integers are objects but what is the extra memory used for i have my guesses but it would be nice to know for sure,['python'] +673218,xcodebuild fails on the write auxiliary files step i am doing a clean then archivexcodebuild workspace myappxcworkspace scheme myscheme archivepath libraryoutputfoldermyappxcarchive clean archivei get this error about 50 of the time the following build commands failed write auxiliary filesits reported twice in the apple developer forums but not yet on stackoverflow as far as i am awarehas anyone found the cause or a workaround,['ios'] +673222,how to hide records rather than delete them soft delete from scratch let us keep this simple let us say i have a user model and a post modelclass user activerecordbase idinteger namestring deletedboolean has many posts endclass post activerecordbase idinteger user idinteger contentstring deletedboolean belongs to userendnow let us say an admin wants to delete hide a post so basically he through the system sets a posts deleted attribute to 1 how should i now thisplay this post in the view should i create a virtual attribute on the post like thisclass post activerecordbase idinteger user idinteger contentstring deletedboolean belongs to user def administrated content if selfdeleted selfcontent else this post has been removed end endendwhile that would work i want to implement the above in a large number of models and i cannot help feeling that copypasting the above comparative into all of my models could be dryer a lot dryeri also think putting a deleted column in every single deletable model in my app feels a bit cumbersome too i feel i should have a state table what are your thoughts on thisclass state idinteger deletedboolean deleted byinteger belongs to user belongs to postend and then querying selfstatedeleted in the comparator would this require a polymorphic table i have only attempted polymorphic once and i could not get it to work it was on a pretty complex selfreferential model mind and this still does not address the problem of having a very very similar class method in my models to check if an instance is deleted or not before thisplaying contentin the deleted by attribute i am thinking of placing the admins id who deleted it but what about when an admin undelete a post maybe i should just have an edited by idhow do i set up a dependent destroy type relationship between the user and his posts because now i want to do this dependent set deleted to 0 and i am not sure how to do thisalso we do not simply want to set the posts deleted attributes to 1 because we actually want to change the message our administrated content gives out we now want it to say this post has been removed because of its user has been deleted i am sure i could jump in and do something hacky but i want to do it properly from the starti also try to avoid gems when i can because i feel i am missing out on learning,['ruby-on-rails'] +673316,how can i get code coverage data from python bdd functional tests using behave i have not seen an answer for this specific question test coverage tool for behave test framework and i have not seen any google search results produce a sufficient answer thereforehow can i get a code coverage report from behave i find it hard to believe that there are no python developers using bdd methodology and i find it even harder to believe that those python developers who are using bdd are doing so without code coverage statistics from their functional tests can coveragepy be used to drive behave to produce code coverage how,['python'] +673338,javascript add methods to function prototype is there a shorter way to write this var controller function constructor controllerprototypefunction1 function prototype method1controllerprototypefunction2 function prototype method2controllerprototypefunction3 function prototype method3 return controlleri am using requirejs i wondered if i can avoid the controllerprototype code repetition,['javascript'] +673347,how to upgrade merge webconfig with web deploy msdeploy i am trying to set up a deployment chain for some of our aspnet applications the tool of choice is web deploy msdeploy for now unfortunately i am stuck on a problema high level overview of the chain is thusweb developer creates the code and checks it in svnbuildserver sees the update and builds the msdeploy zip package of the websitethe zip package is automatically put inside our installer and sent to various clientsthe clients run the installer on their webserversthe installer uses msdeploy internally to deploy the zip package and create a new website or upgrade an existing onemsdeploy makes it easy to deploy a new instance but i am stumped about how to perform an upgrade install the main problem is the webconfig file each client will most certainly have made some customizations there to suit their specific environment the installer itself offers to set some more critical parameters at the firsttime installation achieved by msdeploys parameter mechanism but they can do others by handon the other hand we developers also occasionally make changes to webconfig adding some new settings or removing obsolete ones so i cannot just tell msdeploy to ignore the file entirely i need some kind of advanced xml modification mechanism it could be a script that the developers maintain but then it needs to be run only at upgrades not new installsi have no idea how to accomplish thisbesides that sometimes there is also some completely weird upgrade logic for example the application comes with our company logo but some clients have replaced that png file to show their own logo recently we needed to update the logo but only for clients that had not replaced it with their ownsimilarly there might be some cache folders that might need to be cleaned at some upgrades but not at others or folders with user content that may not be touched but come with default content at the initial installation etchow do you normally achieve this dual behavior for msdeploy packages do i really need to create 2 thistinct packages for every application,['asp.net'] +673452,is it possible to pass a flag to gulp to have it run tasks in different ways normally in gulp tasks look like thisgulptaskmytask function return gulpsrcoptionsscss source pipesastylenested pipeautoprefixerlast 10 version pipeconcatstylecss pipegulpdestoptionsscss destis it possible to pass a command line flag to gulp that is not a task and have it run tasks conditionally based on that for instance gulp mytask a 1and then in my gulpfilejsgulptaskmytask function if a 1 var source optionsscss source else var source optionsother source return gulpsrcsource pipesastylenested pipeautoprefixerlast 10 version pipeconcatstylecss pipegulpdestoptionsscss dest,['javascript'] +673663,how do i implement awesomium 1742 in a monogame project im trying to render render a browser in side my monogame project for drawing some interface stuff i have done this in the past with older versions of awesomium with no problems but i cannot figure out how to properbly initialize awesomium in this new version i get an error no matter how i try to go about it as i understand it i need to call webcorerun once instead of webcoreupdate but i get varius exceptions from that methodhere are the steps that i have followed so farinstall awesomium 1742refrenced 1742wrappersawesomiumnetassembliespackedawesomiumcoredll in my projecthere is some of my attempts webcoreinitializenew webconfig webcorerun error starting an update loop on a thread with an existing message loop is not supported webcoreinitialized sender e webcorerun webcoreinitializenew webconfig webview webview webcorecreatewebview500 400 error starting an update loop on a thread with an existing message loop is not supported webcoreinitializenew webconfig webview webview webcorecreatewebview500 400 webviewsource new uri webviewdocumentready sender e jsobject js webviewcreateglobaljavascriptobjectw no errors but documentready is never firedi have also managed to get nullrefrence errors and if i wait threadsleep400 before calling webcorerun it just enters the webcorerun and never completes that linehow do i set this up cannot find any examples anywhere all the examples online still tells you to use update wich is obsolete,['c#'] +673664,hide dcjs chart xaxis as the image below the xaxis is very messy due to big range of datai wish to remove the xaxis any luckmy current codetonechartwidth300height280 dimensiontone grouptonegroup titlefunction d return orderingfunctiond return dvalue cap10 transitionduration750 renderlabeltrue colorsd3scalecategory10 elasticxtruethanks,['javascript'] +673735,reinstall virtualenv with tox when requirementstxt or setuppy changes previously i was manually using a makefile that looked something like thisphony allall testsphony teststests py env bash c source py envbinactivate pytest testspy env requirements devtxt setuppy rm rf py env virtualenv py env bash c source py envbinactivate pip install r requirements devtxtthis had the nice sideeffect that if i changed requirements devtxt or setuppy it would rebuild my virtualenv but feels a bit clunkyi would like to use tox to do a similar thing i understand tox has a recreate option but i would rather call that only when i need tomy new setup is something like this makefilephony allall testsphony teststests toxand toxinitoxproject my projectenvlist py26py27testenvinstall command pip install usewheel opts packagesdeps rrequirements devtxtcommands pytest posargstestsan ideal solution would use just things in tox however an acceptable solution would involve the makefile and the recreate flag,['python'] +673763,how to thisable the tooltip in mysql workbench mysql workbench is an excellent tool but the tooltip really irritates me because it hides objects in the diagram and does not thisplay any useful information for me i could not thisable the tooltip any idea to thisable iti am using v 60 on os x mavericks,['mysql'] +673771,difference between singletask and singleinstance i did not find any thread on stackoverflow that answer my question i have already seen this android singletop singleinstance and singletask but that question is related to his project scenariowhat are the differences between singletask and singleinstance i have read the docs but could not understandi have read this thread also android singletask or singleinstance launch mode but i could not understand sorry,['android'] +673817,ubuntu unable to correct problems you have held broken packages trying to install this i am getting the unable to correct problems you have held broken packages error messageapache versionserver version apache242 ubuntuserver built jun 27 2012 072335 aptitude install libapache2modwsgithe following new packages will be installed apache22commonab libapache2modwsgi 0 packages upgraded 2 newly installed 0 to remove and 0 not upgradedneed to get 299 kb of archives after unpacking 1047 kb will be usedthe following packages have unmet dependencies apache2 conflicts apache22common but 21ubuntu15 is to be installed apache22common depends apache22bin 21ubuntu15 but it is not going to be installed depends apache2utils but it is not going to be installed apache2bin conflicts apache22common but 21ubuntu15 is to be installed apache2data conflicts apache22common but 21ubuntu15 is to be installedthe following actions will resolve these dependencies keep the following packages at their current version1 apache22common not installed2 libapache2modwsgi not installedaccept this solution ynq yno packages will be installed upgraded or removed0 packages upgraded 0 newly installed 0 to remove and 0 not upgradedneed to get 0 b of archives after unpacking 0 b will be usedany help appretiated,['python'] +673833,using change watchers to observe native properties under objectobserve now that objectobserve is on by default in chrome i am running into a bunch of cases where i want to reuse the browsers built in property hidden title draggable but changed watchers no longer get called when the property changesone example is hidden hiddenchanged is never calledmy current workaround is to use attributechanged to observe the attribute changingattributechanged functionattrname oldval newval cannot use changed watchers for these native properties if attrname hidden thismarkersetvisiblethishidden what is the recommended approach btw throwing a warning when trying to use native properties will go a long for debugging,['javascript'] +673863,setting edittext imeoptions to actionnext has no effect i have a fairly complex not really xml layout file one of the views is a linearlayout v1 with two children an edittextv2 and another linearlayoutv3 the child linearlayout in turn has an edittextv4 and an imageviewv5for edittext v2 i have imeoptions asandroidimeoptionsactionnextbut when i run the app the keyboards return does not check to next and i want it to change to next how do i fix this problemalso when user clicks next i want focus to go to edittext v4 i do i do thisfor those who really need to see some codelinearlayout androidididdo txt view androidlayout widthmatch parent androidlayout heightwrap content androidbackgroundcolorcol6 androidorientationvertical androidvisibilitygone edittext androidididgm title androidlayout widthmatch parent androidlayout heightwrap content androidlayout margin5dp androidbackgrounddrawablecoldo text androidhintstringenter title androidmaxlines1 androidimeoptionsactionnext androidpadding5dp androidtextcolorpigc7 androidtextsizeads2 linearlayout androidlayout widthmatch parent androidlayout height100dp androidorientationhorizontal edittext androidididrev text androidlayout width0dp androidlayout heightmatch parent androidlayout gravitycenter vertical androidlayout margin5dp androidlayout weight1 androidbackgrounddrawablecoldo text androidhintstringenter msg androidmaxlines2 androidpadding5dp androidtextcolorpigc7 androidtextsizeads2 imageview androidlayout widthwrap content androidlayout heightmatch parent androidlayout gravitycenter vertical androidbackgrounddrawablecolbtn ra androidclickabletrue androidonclickaclickacta androidpaddingleft5dp androidpaddingright5dp androidsrcdrawableabcata linearlayout linearlayout,['android'] +673867,thistributed lock manager for python i have a bunch of servers with multiple instances accessing a resource that has a hard limit on requests per secondi need a mechanism to lock the access on this resource for all servers and instances that are runningthere is a restful thistributed lock manager i found on github unfortunately there seems to be a min lock time of 1 second and it is relatively unreliable in several tests it took between 1 and 3 seconds to unlock a 1 second lockis there something well tested with a python interface i can use for this purposeedit i need something that auto unlocks in under 1 second the lock will never be released in my code,['python'] +673904,ruby gem eventmachine will not install using the bundler gem so i am trying to install gitlab and they are having me use a gem called bundler which basically installs the required gems necessary to run their application anyhow after running the bundler usingsudo u git h bundle install deployment without development test mysql awsthis will install a ton of gems perfectly then about 2 minutes into the installation i will get the following error in terminalruby version latest from svn i have checked and its fineos ubuntu 1404 lts trustygemextbuilderror error failed to build gem native extensionusrlocalbinruby extconfrbchecking for rb trap immediate in rubyhrubysigh nochecking for rb thread blocking region nochecking for inotify init in sysinotifyh yeschecking for writev in sysuioh yeschecking for rb wait for single fd yeschecking for rb enable interrupt nochecking for rb time new yeschecking for syseventh nochecking for epoll create in sysepollh yescreating makefilemake destdir cleanmake destdircompiling sslcppcompiling emcppemcpp in member function avoid eventmachine t runepollonceaemcpp57437 error arb thread selecta was not declared in this scope emselect 0 null null null tv emcpp in member function aint selectdata t selectaemcpp82767 error arb thread selecta was not declared in this scope return emselect maxsocket1 fdreads fdwrites fderrors tv emcpp in member function avoid eventmachine t runselectonceaemcpp94640 error arb thread selecta was not declared in this scope emselect 0 null null null tv make emo error 1make failed exit code 2gem files will remain installed in homegitgitlabvendorbundleruby220gemseventmachine103 for inspectionresults logged to homegitgitlabvendorbundleruby220extensionsx86 64linux220staticeventmachine103gem makeoutan error occurred while installing eventmachine 103 and bundler cannot continuemake sure that gem install eventmachine v 103 succeeds before bundling,"['ruby-on-rails', 'ruby']" +673907,sortable table by clicking on headings is it possible to create a table in tex and compile into pdf which would have its column headers so that clicking on them would sort the numerical table content by that columni understand that you can have javascript somehow in the pdf which could potentially allow something like thishas anyone done such a thing,['javascript'] +674045,unexpected data found during save on eloquent laravel i have one more field on the database over the created at and updated at as timestamp the field name is dateso i overwritten the method getdates on my model eloquent because i wanted that field be instantiated from carbonpublic function getdates return datecreated atupdated atbut when i go to create a new record on the database it throw me an exceptioninvalidargumentexception unexpected data found unexpected data found unexpected data foundps the value sent from the form is in eu format dmy hii do not know how figure out this problem any suggestion are appreciated,['php'] +674188,uipercentdriveninteractivetransition yielding extraneous animation when done i am using an interactive custom push transition with a uipercentdriveninteractivetransition the gesture recognizer successfully calls the interaction controllers updateinteractivetransition likewise the animation successfully completes when i call the interaction controllers finishinteractivetransition but sometimes i get a extra bit of thistracting animation at the end where it seems to repeat the latter part of the animation with reasonably simple animations i rarely see this symptom on the iphone 5 though i routinely see it on the simulator when working on slow laptop if i make the animation more computationally expensive eg lots of shadows multiple views animating different directions etc the frequency of this problem on the device increaseshas anyone else seen this problem and figured out a solution other than streamlining the animations which i admittedly should do anyway andor writing my own interaction controllers the uipercentdriveninteractivetransition approach has a certain elegance to it but i am uneasy with the fact that it misbehaves nondeterministically have others seen this behavior does anyone know of other solutionsto illustrate the effect see the image below notice how the second scene the red view when the animation finishes seems to repeat the latter part of its animation a second timethis animation is generated byrepeatedly calling updateinteractivetransition progressing update from 0 to 40momentarily pausing so you can differentiate between the interactive transition and the completion animation resulting from finishinteractivetransitionthen calling finishinteractivetransition to complete the animation andthe animation controllers animations completion block calls completetransition for the transitioncontext in order to clean everything updoing some diagnostics it appears that it is this last step that triggers that extraneous bit of animation the animation controllers completion block is called when the animation is finished but as soon as i call completetransition it sometimes repeats the last bit of the animation notably when using complex animationsi do not think it is relevant but this is my code for configuring the navigation controller to perform interactive transitions voidviewdidload super viewdidload selfnavigationcontrollerdelegate self selfinterationcontroller uipercentdriveninteractivetransition alloc init iduiviewcontrolleranimatedtransitioningnavigationcontrolleruinavigationcontroller navigationcontroller animationcontrollerforoperationuinavigationcontrolleroperationoperation fromviewcontrolleruiviewcontrollerfromvc toviewcontrolleruiviewcontrollertovc if operation uinavigationcontrolleroperationpush return pushanimator alloc init return nil id uiviewcontrollerinteractivetransitioningnavigationcontrolleruinavigationcontrollernavigationcontroller interactioncontrollerforanimationcontrollerid uiviewcontrolleranimatedtransitioninganimationcontroller return selfinterationcontrollermy pushanimator isimplementation pushanimator nstimeintervaltransitiondurationid uiviewcontrollercontexttransitioningtransitioncontext return 50 voidanimatetransitioniduiviewcontrollercontexttransitioningtransitioncontext uiviewcontroller toviewcontroller transitioncontext viewcontrollerforkeyuitransitioncontexttoviewcontrollerkey uiviewcontroller fromviewcontroller transitioncontext viewcontrollerforkeyuitransitioncontextfromviewcontrollerkey transitioncontext containerview addsubviewtoviewcontrollerview toviewcontrollerviewframe cgrectoffsetfromviewcontrollerviewframe fromviewcontrollerviewframesizewidth 0 uiview animatewithdurationself transitiondurationtransitioncontext animations toviewcontrollerviewframe fromviewcontrollerviewframe completionbool finished transitioncontext completetransitiontransitioncontext transitionwascancelled endnote when i put logging statement where i call completetransition i can see that this extraneous bit of animation happens after i call completetransition even though the animation was really done at that point this would suggest that that extra animation may have been a result of the call to completetransitionfyi i have done this experiment with a gesture recognizer voidhandlepanuiscreenedgepangesturerecognizer gesture cgfloat width gestureviewframesizewidth if gesturestate uigesturerecognizerstatebegan self performseguewithidentifierpushtosecond senderself else if gesturestate uigesturerecognizerstatechanged cgpoint translation gesture translationinviewgestureview selfinteractioncontroller updateinteractivetransitionabstranslationx width else if gesturestate uigesturerecognizerstateended gesturestate uigesturerecognizerstatecancelled cgpoint translation gesture translationinviewgestureview cgpoint velocity gesture velocityinviewgestureview cgfloat percent abstranslationx velocityx 025 width if percent 05 gesturestate uigesturerecognizerstatecancelled selfinteractioncontroller cancelinteractivetransition else selfinteractioncontroller finishinteractivetransition i also did it by calling the updateinteractivetransition and finishinteractivetransition manually eliminating the gesture recognizer from the equation and it still exhibits this strange behaviorself performseguewithidentifierpushtosecond senderselfthispatch afterthispatch timethispatch time now int64 t10 nsec per sec thispatch get main queue selfinteractioncontroller updateinteractivetransition040 thispatch afterthispatch timethispatch time now int64 t10 nsec per sec thispatch get main queue selfinteractioncontroller finishinteractivetransition bottom line i have concluded that this is a problem isolated to uipercentdriveninteractivetransition with complex animations i can minimize the problem by simplifying them eg snapshotting and animated snapshotted views i also suspect i could solve this by not using uipercentdriveninteractivetransition and writing my own interaction controller which would do the animation itself without trying to interpolate the animationwithduration block but i was wondering if anyone has figured out any other tricks to using uipercentdriveninteractivetransition with complex animations,['ios'] +674332,optimized bundles returning 404 when requesting from the website i am having this weird problem when i setbundletableenableoptimizations truewhen i try to open my website it just would not load when i open chromes console i see the following messageget localhostbundlesscriptsangularjscommonmodulesv13uwpwzn3u6kihvssxrdpywhxrn09twvykwodvn3su1 404 not found however if i try to open the link shown on chromes console it loads just fine in other words the link is found when i try to open it directly but the server iis 75 returns a 404 when a page tries to link it through a taghave anyone been through such a weird behaviorthe virtual paths for my bundles do not map for any existing file or directory i include them using the following codevar mybundle new scriptbundlebundlesscriptsangularjsbootstrappingbootstrappingincludeappappjs includeappconfigjs includeappconfigexceptionhandlerjs includeappconfigroutejsbundlesaddbootstrappingand i already tried to add the following lines on webconfigs systemwebservermodules runallmanagedmodulesforallrequeststrue remove namebundlemodule add namebundlemodule typesystemweboptimizationbundlemodule modulesi am not sure if this may be related but i am using umbraco v7 on this website and this only happens if i set enableoptimizations to true,['asp.net'] +674346,what is the best approach to sort mysql table rows by user choice suppose we have a mysql table id name and a draganddropenabled list view of the table user drags 90th row and places it over 10th row what is the best approach to keep this new sortingi do not mean to keep sorting for every use separatelythe htmljavascript is not the problemi have seen some programmers add a weight column to table setting lower number upper in the table in my example it will be 1 to 100 the problem is in case of above example 90 to 10 updating 81 rows is required 90 changes to 10 and each 10 to 89 increments is it efficient in mysql is there any better solutionanother way maybe is saving new order as a string in another table but in this case we lose mysql sorting in retrieval phasei remember when we learned trie tree structure in university as an indexing tool we said wow even when we took advantage of every single bit of a byte 15 gb of pure text data stored in less than 500kb so right now i still search to find a better answer,"['php', 'mysql']" +674478,type casting when used instead of i generally do not prefer using but today i was just experimenting with the following code including and the results are a bit confusing to me can someone please explain what is happeningall these are falsy values 0 false undefined nullsuppose i didif undefined null alerta else alertbthe statements below give truenull undefined0 false 0 falsebut why does the code below return falseundefined 0undefined null 0,['javascript'] +674487,does the svm in sklearn support incremental online learning i am currently in the process of designing a recommender system for text articles a binary case of interesting or not interesting one of my specifications is that it should continuously update to changing trends from what i can tell the best way to do this is to make use of machine learning algorithm that supports incrementalonline learning algorithms like the perceptron and winnow support online learning but i am not completely certain about support vector machines does the scikitlearn python library support online learning and if so is a support vector machine one of the algorithms that can make use of iti am obviously not completely tied down to using support vector machines but they are usually the go to algorithm for binary classification due to their all round performance i would be willing to change to whatever fits best in the end,['python'] +674509,android nfc writendefmessage throws ioexception tag is not ndef i am developing a nfc environment consisting of a tag as3953 chip microcontroller and a smartphone samsung galaxy fame runnung android 412 while reading a ndef message works i am stuck on writing the message to the tag i copied most of the code from and modified it to accept iso143a tag type 4 by searching the tag techlist for isodep nfca and ndef in supportedtechssince all of them are listed the app continues to writetagpublic writeresponse writetagndefmessage message tag tag try ndef ndef ndefgettag if ndef null logdtag writetag tag type ndefgettype ndefconnect logdtag writetag connected if ndefiswritable return new writeresponse0 tag is readonly if ndefgetmaxsize messagetobytearraylength return new writeresponse0 size error logdtag writetag write ndef ndefwritendefmessagemessage logdtag writetag wrote ndef if writeprotect ndefmakereadonly return new writeresponse1 wrote message to preformatted tag else logdtag writetag ndefnull return new writeresponse0 writetag ndefnull catch exception e logdtag writetag exception etostring return new writeresponse0 failed to write taglogcat shows110846400 onnewintent110846400 supportedtechs techlist androidnfctechisodepandroidnfctechnfcaandroidnfctechndef110846400 supportedtechs tech is supported110846400 writetag tag type orgnfcforumndeftype4110846410 writetag connected110846410 writetag write ndef110846490 writetag exception javaioioexception tag is not ndefas you can see an ioexception is thrown saying the tag is not ndef which contradictsthe techlist looking further into the android code writendefmessage tries to get a tagservice and a servicehandle from the tag to match them against this fails sothe exception is thrown no message written up to now public void writendefmessagendefmessage msg throws ioexception formatexception infctag tagservice mtaggettagserviceint servicehandle mtaggetservicehandleif tagserviceisndefservicehandle else throw new ioexceptiontag is not ndefis there a workaround for that or is it not possible at all with my kind of tagas i am also programming the tag the error might be on the other side but it seems to be a java problemedit 1i do not connect to any technology before so there should not be any opened connection ifi open an connection before ndefconnect there is illegalstateexception close other technology firsti configured as3953 to iso143a level4 so only tag type 4 blocks are forwarded to the microcontroller only iblocks are handled but even if there are other commands the ac has to read it outover the spi port which is not the case by logic analysis as i said reading the ndef file works and i tested it for a 4kb file looking at the logic analysis the following steps are made all returning a positive 90codeccommand rresponse corrected due to renaming mistakeselect by namec 02 00 a4 04 00 07 d2 76 00 00 85 01 01 00r 02 90 00select by id select cc filec 03 00 a4 00 0c 02 e1 03r 03 90 00read 0x0f bytes of cc filec 02 00 b0 00 00 0fr 02 00 0f 20 00 3b 00 34 04 06 e1 04 0f ff 00 00 90 00select by id select ndef filec 03 00 a4 00 0c 02 e1 04r 03 90 00read 0x02 bytes first 2 bytes are apdusizec 02 00 b0 00 00 02r 02 0f d3 90 00read 0x3b bytes frame size of first part of ndef file external type jpeg image as payloadc 03 00 b0 00 02 3br 03 c4 0c 00 00 0f c1 64 65 2e 74 65 73 74 61 70 70 3a 61 01 ff d8 ff e0 00 10 4a 46 49 46 00 01 01 01 00 60 00 60 00 00 ff db 00 43 00 49 32 36 40 36 2d 49 40 3b 40 52 4d 49 56 6d 90 00ndef fileread 0x26 bytes of last part of ndef filec 03 00 b0 0f ae 27r 03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 ff d9 00 00 90 00using the same app for writing i start the activity which filters nfcadapteraction tag thiscovered intents just as in the linked example the phone touches the tag calling onresume doing mnfcadapterenableforegroundthispatch when i log the spi communication the same reading procedure as above is done since logcatshows a working intent thispatcher i guess the app stops at the ioexception closing the connectionand immediately going over to read out as android found the tag againedit 2there might be a hint as one of the first interrupts issue a deselect command which is handled by as3953 itselfcount interrupt3 power up 1 wakeup irq at entry in active state 1 deselect command1 wakeup irq at entry in active state 1 irq due to start of receive,['android'] +674585,mediastoreimagesmediainsertimage is returning null when trying to save the image i am using an custom view and in that i am using an canvas in which a user can draw anything and after that i want to save that image in sd card bt was not able to do that do not know what is going on else ifviewgetidridsave btn save drawing alertdialogbuilder savedialog new alertdialogbuilderthis savedialogsettitlesave drawing savedialogsetmessagesave drawing to device gallery savedialogsetpositivebuttonyes new dialoginterfaceonclicklistener private fileoutputstream fout public void onclickdialoginterface dialog int which save drawing drawviewsetdrawingcacheenabledtrue attempt to save string imgsaved mediastoreimagesmediainsertimage getcontentresolver drawviewgetdrawingcache uuidrandomuuidtostringpng drawing feedback ifimgsavednull toast savedtoast toastmaketextgetapplicationcontext drawing saved to gallery toastlength short savedtoastshow else toast unsavedtoast toastmaketextgetapplicationcontext oops image could not be saved toastlength short unsavedtoastshow drawviewdestroydrawingcache savedialogsetnegativebuttoncancel new dialoginterfaceonclicklistener public void onclickdialoginterface dialog int which dialogcancel savedialogshow here is the error details0414 112428700 emediastore6866 failed to insert image0414 112428700 emediastore6866 javaiofilenotfoundexception no such file or directory0414 112428700 emediastore6866 at androiddatabasedatabaseutilsreadexceptionwithfilenotfoundexceptionfromparceldatabaseutilsjava1460414 112428700 emediastore6866 at androidcontentcontentproviderproxyopenassetfilecontentprovidernativejava5770414 112428700 emediastore6866 at androidcontentcontentresolveropenassetfiledescriptorcontentresolverjava6730414 112428700 emediastore6866 at androidcontentcontentresolveropenoutputstreamcontentresolverjava5370414 112428700 emediastore6866 at androidcontentcontentresolveropenoutputstreamcontentresolverjava5130414 112428700 emediastore6866 at androidprovidermediastoreimagesmediainsertimagemediastorejava8910414 112428700 emediastore6866 at comexampleclentmainactivity9onclickmainactivityjava2380414 112428700 emediastore6866 at comandroidinternalappalertcontrollerbuttonhandlerhandlemessagealertcontrollerjava1660414 112428700 emediastore6866 at androidoshandlerthispatchmessagehandlerjava990414 112428700 emediastore6866 at androidoslooperlooplooperjava1370414 112428700 emediastore6866 at androidappactivitythreadmainactivitythreadjava51030414 112428700 emediastore6866 at javalangreflectmethodinvokenativenative method0414 112428700 emediastore6866 at javalangreflectmethodinvokemethodjava5250414 112428700 emediastore6866 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava7370414 112428700 emediastore6866 at comandroidinternaloszygoteinitmainzygoteinitjava5530414 112428700 emediastore6866 at dalviksystemnativestartmainnative methodi am always getting this message while trying to save imageoops image could not be saved,['android'] +674622,expand jstree node when parent is clicked i am trying to implement a very simple tree using jstree i have found the documentation dense and overwhelmingright now i expand collapse a node by clicking the arrow shown herei want to be able to expand collapse by clicking the node name toothe code i am using is simple i have not altered the javascript for jstreeul idtree li subfolder1 ul idtree li datajstreeiconimagesbluefolderpngpub 1li ul liul,"['javascript', 'jquery', 'css']" +674723,quick alternative to lots of if statements i am beginner at java and i am making a simple program where i type in something and if what i type in matches one of the things on the database then it will print some text is there a simpler way to check this rather than doing thisint 1int 2int 3etcifuser inputequals1 systemoutprintlntest400 times,['java'] +674732,stanford corenlp sentiment i am trying to implement the corenlp sentiment analyzer in eclipse getting the error unable to resolve edustanfordnlpmodelslexparserenglishpcfgsergzas either class path filename or url i installed all of the nlp files using maven so i am not sure why it is looking for something else here is the code i am getting the error onimport javautilpropertiesimport edustanfordnlplingcoreannotationsimport edustanfordnlpneuralrnnrnncoreannotationsimport edustanfordnlppipelineannotationimport edustanfordnlppipelinestanfordcorenlpimport edustanfordnlpsentimentsentimentcoreannotationsimport edustanfordnlptreestreeimport edustanfordnlputilcoremappublic class stanfordsentiment stanfordcorenlp pipeline public stanfordsentiment properties props new properties propssetpropertyannotators tokenize ssplit parse sentiment pipeline new stanfordcorenlppropspublic float calculatesentiment string text float mainsentiment 0 int longest 0 annotation annotation pipelineprocesstext for coremap sentence annotationgetcoreannotationssentencesannotationclass tree tree sentencegetsentimentcoreannotationsannotatedtreeclass int sentiment rnncoreannotationsgetpredictedclasstree 2 string parttext sentencetostring if parttextlength longest mainsentiment sentiment longest parttextlength return mainsentiment,['java'] +674891,resharper warns about unused methods called by unity3d i just started using reshaper today and to get a lot of warnings about unused methods provided by unity3d like awake startand update etc those are called by unity3d with reflection resharper cannot know that and therefore warns about themis there a better way to suppress those then just thisabling the whole type or method is never used warning or adding the usedimplicitly attribute to everything,['c#'] +674918,format a date using the new date time api i was playing with the new date time api but when running thispublic class test public static void mainstring args string dateformatted localdatenow formatdatetimeformatter ofpatternymmdd hhmmss systemoutprintlndateformatted it throwsexception in thread main javatimetemporalunsupportedtemporaltypeexception unsupported field hourofday at javatimelocaldateget0localdatejava680 at javatimelocaldategetlonglocaldatejava659 at javatimeformatdatetimeprintcontextgetvaluedatetimeprintcontextjava298 at javatimeformatdatetimeformatterbuildernumberprinterparserformatdatetimeformatterbuilderjava2543 at javatimeformatdatetimeformatterbuildercompositeprinterparserformatdatetimeformatterbuilderjava2182 at javatimeformatdatetimeformatterformattodatetimeformatterjava1745 at javatimeformatdatetimeformatterformatdatetimeformatterjava1719 at javatimelocaldateformatlocaldatejava1685 at testmaintestjava23when looking at the source code of the localdate class i see private int get0temporalfield field switch chronofield field case day of week return getdayofweekgetvalue case aligned day of week in month return day 1 7 1 case aligned day of week in year return getdayofyear 1 7 1 case day of month return day case day of year return getdayofyear case epoch day throw new unsupportedtemporaltypeexceptioninvalid field epochday for get method use getlong instead case aligned week of month return day 1 7 1 case aligned week of year return getdayofyear 1 7 1 case month of year return month case proleptic month throw new unsupportedtemporaltypeexceptioninvalid field prolepticmonth for get method use getlong instead case year of era return year 1 year 1 year case year return year case era return year 1 1 0 throw new unsupportedtemporaltypeexceptionunsupported field field as it described in the docthis method will create a formatter based on a simple pattern of letters and symbols as described in the class documentationand all these letters are defined so why datetimeformatterofpattern does not allow us to use some pattern letters,['java'] +674919,how do i make this async foreach loop work with promises i have already messed around with promises in it but i am new to them and i just cannot figure out how to do it properly at the moment there is no point to the promise because it does not wait till the async get completesbasically each foreach iteration has its own get function and i need to have them all complete and then continue to the part that has the gets albumart consoleloggetidfunctiondata there is some code here var getzippyurls new promisefunctionresolve zippyarrayforeachfunctionzippy more code getzippyfull functiondata this is the foreach of gets codes here resolvezippyarray this is my failed promise getzippyurlsthenfunctionresponse consolelogwere out responselength responseforeachfunctiond consolelogpromisedmedia consolelogey consoleloggets albumart now after the previous stuff is done move on,['javascript'] +675033,django rest framework how to test viewset i am having trouble testing a viewsetclass viewsettesttestcase def test view setself factory apirequestfactory view catviewsetas view cat catnamebob catsave request factorygetreversecatdetail argscatpk response viewrequesti am trying to replicate the syntax herebut i think their accountdetail view is different from my viewset so i am getting this error from the last lineattributeerror nonetype object has no attributes itemsis there a correct syntax here or am i mixing up concepts my apiclient tests work but i am using the factory here because i would eventually like to add requestuser some user thanks in advanceoh and the client test works finedef test client viewself response apiclientgetreversecatdetail argscatpk selfassertequalresponsestatus code 200,['python'] +675123,dynamic cast vs static cast to void in the last two lines of below program static castvoid and dynamic castvoid behave differently from what i understand the result of a dynamic castvoid always resolves to the address of the complete object so it uses rtti in some way could anyone explain how compilers uses rtti to differentiate between the twoinclude iostreamusing namespace stdclass top protectedint xpublic topint n x n virtual top friend ostream operatorostream os const top t return os tx class left virtual public top protected int ypublic leftint m int n topm y n class right virtual public top protected int zpublic rightint m int n topm z n class bottom public left public right int w public bottomint i int j int k int m topi left0 j right0 k w m friend ostream operatorostream os const bottom b return os bx by bz bw int main bottom b1 2 3 4 cout sizeof b endl cout b endl cout static castvoidb endl top p static casttopb cout p endl cout p endl cout static castvoidp endl cout dynamic castvoidp endl return 0possible output 2812340xbfcce60410xbfcce6180xbfcce6180xbfcce604,['c++'] +675165,aspnet mvc 5 vs angularjs aspnet webapi i am currently evaluating the programming model for creating future webapplications in my company so i will decide between aspnet mvc 5 with razor views and angularjs with aspnet webapi what are the advantages thisadvantages of these two programming models,['asp.net'] +675219,maven throws nullpointer exception good dayi have built a project using maven throughout this project i have concluded that one more dependency has to be added for a particular module i have added this dependency in it is pom file and when i have tried to rebuild the project using maven a null pointer was thrownpom files beforechild pom dependency groupidorghibernatejavaxpersistencegroupid artifactidhibernatejpa20apiartifactid dependencydependenciesmain pom dependencymanagement dependencies dependency groupidorghibernatejavaxpersistencegroupid artifactidhibernatejpa20apiartifactid version101finalversion dependency dependency groupidcomsolveitcrmcoregroupid artifactidcrmcoreartifactid versionprojectversionversion dependency this dependency is for another module it was declared at the start of the project dependenciesdependencymanagementpom files nowwhich cause nullpointerchild pomdependencies dependency groupidorghibernatejavaxpersistencegroupid artifactidhibernatejpa20apiartifactid dependency dependency groupidcomsolveitcrmdatagroupid artifactidcrmdataartifactid dependencydependenciesmain pomdependencymanagement dependencies dependency groupidorghibernatejavaxpersistencegroupid artifactidhibernatejpa20apiartifactid version101finalversion dependency dependency groupidcomsolveitcrmcoregroupid artifactidcrmcoreartifactid versionprojectversionversion dependency dependency groupidcomsolveitcrmdatagroupid artifactidcrmdataartifactid versionprojectversionversion dependency dependenciesdependencymanagementwhy does maven throw null pointer exception i am confused right nowerror message info scanning for projectserror internal error javalangnullpointerexception help 1orgapachemaveninternalerrorexception internal error javalangnullpointerexception at orgapachemavendefaultmavenexecutedefaultmavenjava167 at orgapachemavenclimavencliexecutemavenclijava584 at orgapachemavenclimavenclidomainmavenclijava213 at orgapachemavenclimavenclimainmavenclijava157 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava62 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43 at javalangreflectmethodinvokemethodjava483 at orgcodehausplexusclassworldslauncherlauncherlaunchenhancedlauncherjava289 at orgcodehausplexusclassworldslauncherlauncherlaunchlauncherjava229 at orgcodehausplexusclassworldslauncherlaunchermainwithexitcodelauncherjava415 at orgcodehausplexusclassworldslauncherlaunchermainlauncherjava356caused by javalangnullpointerexception at orgapachemavendefaultmavendoexecutedefaultmavenjava270 at orgapachemavendefaultmavenexecutedefaultmavenjava155 11 moreerrorerror to see the full stack trace of the errors rerun maven with the e switcherror rerun maven using the x switch to enable full debug loggingerrorerror for more information about the errors and possible solutions please read the following articleserror help 1 xceptionin eclipse i get info scanning for projectserror the projects in the reactor contain a cyclic reference edge between vertexlabelcomsolveitcrmdatacrmdata1 and vertexlabelcomsolveitcrmcorecrmcore1 introduces to cycle in the graph comsolveitcrmcorecrmcore1 comsolveitcrmdatacrmdata1 comsolveitcrmcorecrmcore1 help 1error error to see the full stack trace of the errors rerun maven with the e switcherror rerun maven using the x switch to enable full debug loggingerror error for more information about the errors and possible solutions please read the following articleserror help 1 thank you,['java'] +675285,split string with multiple continuous comma in java string abc abcdstring arr abcsplitsystemoutprintlnarrlengthoutput is 4 but obviously my expectation is 7 here is my solutionstring abc abcdabc nstring arr abcsplitsystemoutprintlnarrlengthwhy does it happen anyone could give my a better solution,['java'] +675399,get the pid of a windows service could anyone help me to know how to get the pid of a windows servicei need to get the pid in order to run the following command procestartnew procestartinfo filename cmdexe createnowindow true useshellexecute false arguments stringformatc taskkill pid 0 f pidnumber,"['c#', '.net']" +675408,onactivityresult result ok can not be resolved to a variable in android i am trying to launch camera in fragment but onactivityresult in fragment does not resolve result ok what should i doi am launching camera usingpublic static final int camera request code 19intent cameraintent new intentandroidprovidermediastoreaction image capturestartactivityforresultcameraintent camera request codeget captured image usingoverridepublic void onactivityresultint requestcode int resultcode intent data superonactivityresultrequestcode resultcode data if requestcode camera request code resultcode result ok bitmap bitmap bitmap datagetextrasgetdata if bitmap null and i want captured image in current fragment,['android'] +675426,vertical centering in safari i have got a problem with vertical centering in safari using margin auto 0 on a div which is nested inside a div with thisplay inlineflexit works just fine in firefox chrome opera but fails in safari and on the default android browser but i am considering using a separate css for that and whatever ipads useheres the code i am using bootstrap btwdiv classcontainerfluid head idslide1 div classcolmd6 logo img srcimglogopng altthe logo divdivand containerfluid marginright auto marginleft auto paddingleft 15px paddingright 15pxhead color f width 100 minheight 100rem for opera minheight 100vh padding 15px backgroundcolor rgba85611489 boxshadow 0px 0px 6px 0 zindex 90 position relative backgroundimage urlimgdither2png backgroundposition center bottom backgroundrepeat repeatx thisplay oflex thisplay msflex thisplay mozflex thisplay webkitflex thisplay inlineflexcolmd6 position relative minheight 1px paddingleft 15px paddingright 15pxlogo margin auto 0 textalign center,"['html', 'css']" +675539,why use timespancompareto rather than or i have been going over some microsoft samples of code for the kinect sensor and have stumbled across the following linetimespan zeroduration timespanfromseconds00timespan timeremaining if timeremainingcomparetothiszeroduration 0i understand how compareto is useful in scenarios such as sorting but why would it be used in a conditional if instead of the more direct approachif timeremaining thiszerodurationps i would take it with a grain of salt if it was from any other source but given the general quality of the code assume there is a reason,"['c#', '.net']" +675559,rethis attempting to connect to local host in heroku why i have been using sidekiqrethis for quite some time with no issues to datefor some reason today i am getting this errorrethiscannotconnecterror error connecting to rethis on 1270016379 econnrefusedso rethis is attempting to connect to my localhost connection instead of my rethis to go url in herokumy rethisrb file looks like souri uriparseenvrethistogo url rethislocalhost6379rethis rethisnewhost urihost port uriport password uripasswordand when i type heroku config i am given thisrethistogo url rethisrethistogo10280which maps exactly to my url that i am seeing in my rethis to go addon in herokunothing changed with rethis that i know of between yesterday when it worked and today when it does not but i did spin up a mongo db using mongo hq perhaps there is a conflict somewhereany help is appreciatedediti have no mongo init file and the only mongo specific file i created was my configmongoidyml file it looks like thisdevelopment sessions default database mongoid dev hosts localhost27017 options strictly 2 spaces before raise not found error false strictly 4 spaces before not 6 production sessions default uri envmongohq url options strictly 2 spaces before raise not found error false strictly 4 spaces before not 6i installed mongo from master and am running rails 410edit2full trace error is below20140415t203305068810 appweb1 rethiscannotconnecterror error connecting to rethis on 1270016379 econnrefused20140415t203305068810 appweb1 appvendorbundleruby200gemsrethis307librethisclientrb290in rescue in establish connection20140415t203305068810 appweb1 appvendorbundleruby200gemsrethis307librethisclientrb285in establish connection20140415t203305068810 appweb1 appvendorbundleruby200gemsrethis307librethisclientrb79in block in connect20140415t203305068810 appweb1 appvendorbundleruby200gemsrethis307librethisclientrb257in with reconnect20140415t203305068810 appweb1 appvendorbundleruby200gemsrethis307librethisclientrb78in connect20140415t203305068810 appweb1 appvendorbundleruby200gemsrethis307librethisclientrb304in ensure connected20140415t203305068810 appweb1 appvendorbundleruby200gemsrethis307librethisclientrb191in block in process20140415t203305068810 appweb1 appvendorbundleruby200gemsrethis307librethisclientrb270in logging20140415t203305068810 appweb1 appvendorbundleruby200gemsrethis307librethisclientrb190in process20140415t2033050690160 appweb1 appvendorbundleruby200gemsrethis307librethisclientrb96in call20140415t2033050690160 appweb1 appvendorbundleruby200gemsrethis307librethisrb186in block in info20140415t2033050690160 appweb1 appvendorbundleruby200gemsrethis307librethisrb37in block in synchronize20140415t2033050690160 appweb1 appvendorruby200libruby200monitorrb211in mon synchronize20140415t2033050690160 appweb1 appvendorbundleruby200gemsrethis307librethisrb37in synchronize20140415t2033050690160 appweb1 appvendorbundleruby200gemsrethis307librethisrb185in info20140415t2033050690160 appweb1 appvendorbundleruby200gemssidekiq300libsidekiqwebrb218in block 2 levels in classweb20140415t2033050690160 appweb1 appvendorbundleruby200gemsconnection pool200libconnection poolrb58in with20140415t2033050690160 appweb1 appvendorbundleruby200gemssidekiq300libsidekiqrb69in rethis20140415t2033050690160 appweb1 appvendorbundleruby200gemssidekiq300libsidekiqwebrb218in block in classweb20140415t2033050692440 appweb1 appvendorbundleruby200gemssinatra145libsinatrabaserb1603in call20140415t2033050692440 appweb1 appvendorbundleruby200gemssinatra145libsinatrabaserb1603in block in compile20140415t2033050692440 appweb1 appvendorbundleruby200gemssinatra145libsinatrabaserb966in 20140415t2033050692440 appweb1 appvendorbundleruby200gemssinatra145libsinatrabaserb966in block 3 levels in route20140415t2033050692440 appweb1 appvendorbundleruby200gemssinatra145libsinatrabaserb985in route eval20140415t2033050692440 appweb1 appvendorbundleruby200gemsnewrelic rpm373204libnew relicagentinstrumentationsinatrarb133in route eval with newrelic20140415t2033050692440 appweb1 appvendorbundleruby200gemssinatra145libsinatrabaserb966in block 2 levels in route20140415t2033050692440 appweb1 appvendorbundleruby200gemssinatra145libsinatrabaserb1006in block in process route20140415t2033050692440 appweb1 appvendorbundleruby200gemssinatra145libsinatrabaserb1004in catch20140415t2033050692440 appweb1 appvendorbundleruby200gemssinatra145libsinatrabaserb1004in process route20140415t2033050699030 appweb1 appvendorbundleruby200gemsnewrelic rpm373204libnew relicagentinstrumentationsinatrarb116in process route with newrelic20140415t2033050699030 appweb1 appvendorbundleruby200gemssinatra145libsinatrabaserb964in block in route20140415t2033050699030 appweb1 appvendorbundleruby200gemssinatra145libsinatrabaserb963in each20140415t2033050699030 appweb1 appvendorbundleruby200gemssinatra145libsinatrabaserb963in route20140415t2033050699030 appweb1 appvendorbundleruby200gemssinatra145libsinatrabaserb1076in block in thispatch20140415t2033050699030 appweb1 appvendorbundleruby200gemssinatra145libsinatrabaserb1058in block in invoke20140415t2033050699030 appweb1 appvendorbundleruby200gemssinatra145libsinatrabaserb1058in catch20140415t2033050699030 appweb1 appvendorbundleruby200gemssinatra145libsinatrabaserb1058in invoke20140415t2033050699030 appweb1 appvendorbundleruby200gemssinatra145libsinatrabaserb1073in thispatch20140415t2033050699030 appweb1 appvendorbundleruby200gemsnewrelic rpm373204libnew relicagentinstrumentationsinatrarb151in thispatch and notice errors with newrelic20140415t2033050701920 appweb1 appvendorbundleruby200gemsnewrelic rpm373204libnew relicagentinstrumentationsinatrarb146in block in thispatch with newrelic20140415t2033050701920 appweb1 appvendorbundleruby200gemsnewrelic rpm373204libnew relicagentinstrumentationcontroller instrumentationrb335in perform action with newrelic trace20140415t2033050701920 appweb1 appvendorbundleruby200gemsnewrelic rpm373204libnew relicagentinstrumentationsinatrarb143in thispatch with newrelic20140415t2033050701920 appweb1 appvendorbundleruby200gemssinatra145libsinatrabaserb898in block in call20140415t2033050701920 appweb1 appvendorbundleruby200gemssinatra145libsinatrabaserb1058in block in invoke20140415t2033050701920 appweb1 appvendorbundleruby200gemssinatra145libsinatrabaserb1058in catch20140415t2033050701920 appweb1 appvendorbundleruby200gemssinatra145libsinatrabaserb1058in invoke20140415t2033050701920 appweb1 appvendorbundleruby200gemssinatra145libsinatrabaserb898in call20140415t2033050701920 appweb1 appvendorbundleruby200gemssinatra145libsinatrabaserb886in call20140415t2033050701920 appweb1 appvendorbundleruby200gemsnewrelic rpm373204libnew relicrackerror collectorrb55in call20140415t2033050706540 appweb1 appvendorbundleruby200gemsnewrelic rpm373204libnew relicrackbrowser monitoringrb27in call20140415t2033050706540 appweb1 appvendorbundleruby200gemsnewrelic rpm373204libnew relicrackagent hooksrb32in call20140415t2033050706540 appweb1 appvendorbundleruby200gemsrackprotection153librackprotectionxss headerrb18in call20140415t2033050706540 appweb1 appvendorbundleruby200gemsrackprotection153librackprotectionpath traversalrb16in call20140415t2033050706540 appweb1 appvendorbundleruby200gemsrackprotection153librackprotectionjson csrfrb18in call20140415t2033050706540 appweb1 appvendorbundleruby200gemsrackprotection153librackprotectionbaserb49in call20140415t2033050706540 appweb1 appvendorbundleruby200gemsrackprotection153librackprotectionbaserb49in call20140415t2033050706540 appweb1 appvendorbundleruby200gemsrackprotection153librackprotectionframe optionsrb31in call20140415t2033050706540 appweb1 appvendorbundleruby200gemsrack152libracknuloggerrb9in call20140415t2033050706540 appweb1 appvendorbundleruby200gemsrack152librackheadrb11in call20140415t2033050709760 appweb1 appvendorbundleruby200gemssinatra145libsinatrabaserb180in call20140415t2033050709760 appweb1 appvendorbundleruby200gemssinatra145libsinatrabaserb2014in call20140415t2033050709760 appweb1 appvendorbundleruby200gemssinatra145libsinatrabaserb1478in block in call20140415t2033050709760 appweb1 appvendorbundleruby200gemssinatra145libsinatrabaserb1788in synchronize20140415t2033050709760 appweb1 appvendorbundleruby200gemssinatra145libsinatrabaserb1478in call20140415t2033050709760 appweb1 appvendorbundleruby200gemsactionpack410libaction thispatchjourneyrouterrb71in block in call20140415t2033050709760 appweb1 appvendorbundleruby200gemsactionpack410libaction thispatchjourneyrouterrb59in each20140415t2033050709760 appweb1 appvendorbundleruby200gemsactionpack410libaction thispatchjourneyrouterrb59in call20140415t2033050709760 appweb1 appvendorbundleruby200gemsactionpack410libaction thispatchroutingroute setrb676in call20140415t2033050709760 appweb1 appvendorbundleruby200gemsnewrelic rpm373204libnew relicrackerror collectorrb55in call20140415t2033050714620 appweb1 appvendorbundleruby200gemsnewrelic rpm373204libnew relicrackagent hooksrb32in call20140415t2033050714620 appweb1 appvendorbundleruby200gemsnewrelic rpm373204libnew relicrackbrowser monitoringrb27in call20140415t2033050714620 appweb1 appvendorbundleruby200gemswarden123libwardenmanagerrb35in block in call20140415t2033050714620 appweb1 appvendorbundleruby200gemswarden123libwardenmanagerrb34in catch20140415t2033050714620 appweb1 appvendorbundleruby200gemswarden123libwardenmanagerrb34in call20140415t2033050714620 appweb1 appvendorbundleruby200gemsrack152libracketagrb23in call20140415t2033050714620 appweb1 appvendorbundleruby200gemsrack152librackconditionalgetrb25in call20140415t2033050714620 appweb1 appvendorbundleruby200gemsrack152librackheadrb11in call20140415t2033050714620 appweb1 appvendorbundleruby200gemsactionpack410libaction thispatchmiddlewareparams parserrb27in call20140415t2033050714620 appweb1 appvendorbundleruby200gemsactionpack410libaction thispatchmiddlewareflashrb254in call20140415t2033050716650 appweb1 appvendorbundleruby200gemsrack152libracksessionabstractidrb225in context20140415t2033050716650 appweb1 appvendorbundleruby200gemsrack152libracksessionabstractidrb220in call20140415t2033050716650 appweb1 appvendorbundleruby200gemsactionpack410libaction thispatchmiddlewarecookiesrb560in call20140415t2033050716650 appweb1 appvendorbundleruby200gemsactiverecord410libactive recordquery cacherb36in call20140415t2033050716650 appweb1 appvendorbundleruby200gemsactiverecord410libactive recordconnection adaptersabstractconnection poolrb621in call20140415t2033050716650 appweb1 appvendorbundleruby200gemsactionpack410libaction thispatchmiddlewarecallbacksrb29in block in call20140415t2033050716650 appweb1 appvendorbundleruby200gemsactivesupport410libactive supportcallbacksrb82in run callbacks20140415t2033050716650 appweb1 appvendorbundleruby200gemsactionpack410libaction thispatchmiddlewarecallbacksrb27in call20140415t2033050716650 appweb1 appvendorbundleruby200gemsactionpack410libaction thispatchmiddlewareremote iprb76in call20140415t2033050716650 appweb1 appvendorbundleruby200gemsactionpack410libaction thispatchmiddlewaredebug exceptionsrb17in call20140415t2033050721480 appweb1 appvendorbundleruby200gemsactionpack410libaction thispatchmiddlewareshow exceptionsrb30in call20140415t2033050721480 appweb1 appvendorbundleruby200gemsrailties410librailsrackloggerrb38in call app20140415t2033050721480 appweb1 appvendorbundleruby200gemsrailties410librailsrackloggerrb20in block in call20140415t2033050721480 appweb1 appvendorbundleruby200gemsactivesupport410libactive supporttagged loggingrb68in block in tagged20140415t2033050721480 appweb1 appvendorbundleruby200gemsactivesupport410libactive supporttagged loggingrb26in tagged20140415t2033050721480 appweb1 appvendorbundleruby200gemsactivesupport410libactive supporttagged loggingrb68in tagged20140415t2033050721480 appweb1 appvendorbundleruby200gemsrailties410librailsrackloggerrb20in call20140415t2033050721480 appweb1 appvendorbundleruby200gemsactionpack410libaction thispatchmiddlewarerequest idrb21in call20140415t2033050721480 appweb1 appvendorbundleruby200gemsrack152librackmethodoverriderb21in call20140415t2033050721480 appweb1 appvendorbundleruby200gemsrack152librackruntimerb17in call20140415t2033050725770 appweb1 appvendorbundleruby200gemsactivesupport410libactive supportcachestrategylocal cache middlewarerb26in call20140415t2033050725770 appweb1 appvendorbundleruby200gemsactionpack410libaction thispatchmiddlewarestaticrb64in call20140415t2033050725770 appweb1 appvendorbundleruby200gemsrack152libracksendfilerb112in call20140415t2033050725770 appweb1 appvendorbundleruby200gemsrailties410librailsenginerb514in call20140415t2033050725770 appweb1 appvendorbundleruby200gemsrailties410librailsapplicationrb144in call20140415t2033050725770 appweb1 appvendorbundleruby200gemsunicorn482libunicornhttp serverrb572in process client20140415t2033050725770 appweb1 appvendorbundleruby200gemsunicorn482libunicornhttp serverrb6in worker loop20140415t2033050725770 appweb1 appvendorbundleruby200gemsnewrelic rpm373204libnew relicagentinstrumentationunicorn instrumentationrb22in call20140415t2033050725770 appweb1 appvendorbundleruby200gemsnewrelic rpm373204libnew relicagentinstrumentationunicorn instrumentationrb22in block 4 levels in top required20140415t2033050725770 appweb1 appvendorbundleruby200gemsunicorn482libunicornhttp serverrb521in spawn missing workers20140415t2033050736310 appweb1 appvendorbundleruby200gemsunicorn482libunicornhttp serverrb140in start20140415t2033050736310 appweb1 appvendorbundleruby200gemsunicorn482binunicorn126in top required20140415t2033050736310 appweb1 appvendorbundleruby200binunicorn23in load20140415t2033050736310 appweb1 appvendorbundleruby200binunicorn23in main,['ruby-on-rails'] +675566,deploy war or fat jar i am noticing a lot of projects dropwizard grails etc starting to embrace the notion of a fat jar using an embedded web server like jetty or tomcat vs the traditional war deploy both methods involve a single jvm process ie no matter how many wars are deployed to tomcat it is all the same jvm processunder what circumstances is either deployment method preferable over the other,['java'] +675639,how to open a file which overwrite existing content i try to open a file like this in linux it will overwrite an existing one if exits that is what i wantfout openout file name o wronly o creat 644however if the existing is 1024 bytes when i open in above way and write 800 new bytesi still see the 224 bytes at the end of previous content how can i make it just have the 800 bytes that i have been written,['c'] +675684,java order of initialization and instantiation so i am trying to piece together the process of initialization and instantiation in the jvm but the jls is a little obtuse on a few details so if anyone would mind clearing up some details it would be apreciated this is what i have been able to figure out so farinitializationrecursively initialize static final variables of the class and it is interfaces that are compile time constantsback out of the recursion processing static blocks and static fields in textual orderinstantiationrecursively initialize final instance variables of the class that are compile time constantsback out of the recursion processing nonstatic blocks and instance fields in textual order prepending them to the constructors as it returnsokay so now for the questionsare interfaces processed in order of declarationare interfaces processed in a separate recursive stacka if yes do interfaces get processed before or after superclassesb if yes am i correct in deducing that one or the othersinterface or superclass gets its noncompiletime constant fields initialized before the others compiletime constantswhat role does calls to the nondefault super constructor play in this processam i mistaken in any of my conclusionsam i missing any other key details,['java'] +675737,c concepts vs static assert what is exactly new in c concepts in my understanding they are functionally equal to using static assert but in a nice manner meaning that compiler errors will be more readable as bjarne stroustup said you would not get 10 pages or erros but just onebasically is it true that everything you can do with concepts you can also achieve using static assertis there something i am missing,['c++'] +675839,my ios application is always asking me to sign in to itunes store i am developing an ios application with iap feature it works well but i encountered a strange issue today it always show me a message to ask me to sign in to itunes store for some reasons here is the screenshotit always shows this every time when i start the application or resume from background it even still shows this after i delete and reinstall the application when i setup breakpoints in my source code there is no any transactionpayment delegate callbacks can anybody tell me what the reason is could it be the problem of apple iap sandbox i run the same application in other devices without any problem i can purchase restore in sandbox,['ios'] +675860,matplotlib says it needs libpng15 but i have libpng16 the problem is likely a configuration issue because getting the installation correct on macs seems to be tricky i am running mavericks and matplotlib 14x yet when i open a python 275 shell and import pylib i get this error import pylabtraceback most recent call last file stdin line 1 in module file librarypython27sitepackagesmatplotlib14xpy27macosx109inteleggpylabpy line 1 in module from matplotlibpylab import file librarypython27sitepackagesmatplotlib14xpy27macosx109inteleggmatplotlibpylabpy line 230 in module import matplotlibfinance file librarypython27sitepackagesmatplotlib14xpy27macosx109inteleggmatplotlibfinancepy line 38 in module from matplotlibcollections import linecollection polycollection file librarypython27sitepackagesmatplotlib14xpy27macosx109inteleggmatplotlibcollectionspy line 27 in module import matplotlibbackend bases as backend bases file librarypython27sitepackagesmatplotlib14xpy27macosx109inteleggmatplotlibbackend basespy line 55 in module import matplotlibtextpath as textpath file librarypython27sitepackagesmatplotlib14xpy27macosx109inteleggmatplotlibtextpathpy line 22 in module from matplotlibmathtext import mathtextparser file librarypython27sitepackagesmatplotlib14xpy27macosx109inteleggmatplotlibmathtextpy line 64 in module import matplotlib png as pngimporterror dlopenlibrarypython27sitepackagesmatplotlib14xpy27macosx109inteleggmatplotlib pngso 2 library not loaded usrlocalliblibpng1515dylib referenced from librarypython27sitepackagesmatplotlib14xpy27macosx109inteleggmatplotlib pngso reason image not foundi have libpng16 installed but not libpng15,['python'] +675908,ignore fields from java object dynamically while sending as json from spring mvc i have model class like this for hibernateentitytablename user catalog userdbjsonignorepropertiesignoreunknown truepublic class user implements javaioserializable private integer userid private string username private string emailid private string encryptedpwd private string createdby private string updatedby id generatedvaluestrategy identity columnname userid unique true nullable false public integer getuserid return thisuserid public void setuseridinteger userid thisuserid userid columnname username length 100 public string getusername return thisusername public void setusernamestring username thisusername username columnname emailid nullable false length 45 public string getemailid return thisemailid public void setemailidstring emailid thisemailid emailid columnname encryptedpwd length 100 public string getencryptedpwd return thisencryptedpwd public void setencryptedpwdstring encryptedpwd thisencryptedpwd encryptedpwd public void setcreatedbystring createdby thiscreatedby createdby columnname updatedby length 100 public string getupdatedby return thisupdatedby public void setupdatedbystring updatedby thisupdatedby updatedby in spring mvc controller using dao i am able to get the object and returning as json objectcontrollerpublic class usercontroller autowired private userservice userservice requestmappingvalue getuseruserid method requestmethodget responsebody public user getuserpathvariable integer userid throws exception user user userservicegetuserid usersetcreatedbynull usersetupdatedbynull return user view part is done using angularjs so it will get json like this userid 2 username john emailid encryptedpwd co7fwd1fxyk createdby null updatedby nullif i do not want to set encrypted password i will set that field also as nullbut i do not want like this i dont want to send all fields to client side if i dont want password updatedby createdby fields to send my result json should be like userid 2 username john emailid the list of fields which i do not want to send to client coming from other database table so it will change based on the user who is logged in how can i do thati hope you got my question,['java'] +675930,open xml reading from excel file i want to implement openxml sdk 25 into my project i do everything in this linkusing documentformatopenxmlusing documentformatopenxmlpackagingusing documentformatopenxmlspreadsheetusing systemiopackagingstatic void mainstring args string filename copenxmlbigdataxlsx comment one of the following lines to test the method separately readexcelfiledomfilename dom readexcelfilesaxfilename sax the dom approach note that the code below works only for cells that contain numeric values static void readexcelfiledomstring filename using spreadsheetdocument spreadsheetdocument spreadsheetdocumentopenfilename false workbookpart workbookpart spreadsheetdocumentworkbookpart worksheetpart worksheetpart workbookpartworksheetpartsfirst sheetdata sheetdata worksheetpartworksheetelementssheetdatafirst string text int rowcount sheetdataelementsrowcount foreach row r in sheetdataelementsrow foreach cell c in relementscell text ccellvaluetext consolewritetext consolewriteline consolereadkey but i am not getting any row it has not entered loop note i also set up openxml sdk 25 my computerand i find below code this is work for numeric valuefor string value it writes 0 1 2 private static void mainstring args var filepath copenxmlbigdataxlsx using var document spreadsheetdocumentopenfilepath false var workbookpart documentworkbookpart var workbook workbookpartworkbook var sheets workbookdescendantssheet foreach var sheet in sheets var worksheetpart worksheetpartworkbookpartgetpartbyidsheetid var sharedstringpart workbookpartsharedstringtablepart var values sharedstringpartsharedstringtableelementssharedstringitemtoarray string text var rows worksheetpartworksheetdescendantsrow foreach var row in rows consolewriteline int count rowelementscellcount foreach cell c in rowelementscell text ccellvalueinnertext consolewritetext consolereadline,['c#'] +676089,animation bug in chrome v36 i have just noticed a wrong behavior of chrome 36019330 m rendering when using fullpagejs pluginthis bug did not took place in a previous version of chrome and it neither does in any other browser ie opera firefoxsome content suddenly thisappears from the site after it is animated it changes the top property of a container by using jquerythe content still being there in the dom structure and there is nothing i could find to justify that behavior i do not know exactly what causes it and why it take place only in some sections of the siteto reproduce it you can do it at the plugin sitescroll down to the 2nd sectionscroll down to the 3rd section problem1 the content seems to be fixed while scrolling downscroll up problem2 you will see the text is no longer visible you can also reproduce it this jsfiddlescroll down the 3rd slidescroll down to the 4th section problem1 the content seems to be fixed while scrolling downscroll up problem2 you will see the text is no longer visible,"['jquery', 'css']" +676119,css inputinvalid incorrectly applied i have this fiddle the code is simply an input field of type number with pattern pattern0909css adds a red border if input is invalid inputinvalid border1px solid red however if i type 13 and then tab out the field i get a red border even though this is correct according to the pattern what is wrong here ps this is in safariedit ok i added stepany and this seems to fix it can you guys confirm,['css'] +676145,make the right side of a div as an arrow i have a simple div on a pagedivsome textdivis it possible with css to make it finish as an arrow something likeupdatethis is the result i see with webtiki proposed solutionsee the cuts on the arrowthank youmiguel,"['html', 'css']" +676261,pandas dataframe stored list as string how to convert back to list i have an nbym pandas dataframe df defined as follows i know this is not the best way to do it it makes sense for what i am trying to do in my actual code but that would be tmi for this post so just take my word that this approach works in my particular scenario df dataframecolumnscol1 dfappendseriesnone ignore indextrue dfempty dataframecolumns col1index i stored lists in the cells of this dataframe as follows dfcolumn10 123 234 df col10 1 2for some reason the dataframe stored this list as a string instead of a list dfcolumn10123 234i have 2 questions for youwhy does the dataframe store a list as a string and is there a way around this behaviorif not then is there a pythonic way to convert this string into a listupdatethe dataframe i was using had been saved and loaded from a csv format this format rather than the dataframe itself converted the list from a string to a literal,['python'] +676308,is there a cucumber hook to run before and after each feature is there a way to run specific code block before and after each cucumber feature with certain tag since setup process is very expensive i do not want to run it before each scenario,['ruby'] +676375,using a factory inside another factory angularjs i have a moduleangularmodulemymodule and then a factoryangularmodulemymodulefactoryfactory1 function some vars and functionsand then another factoryangularmodulemymodulefactoryfactory2 function some vars and functions but i want to use some vars from factory1but i want to use some variables from factory1 inside factory2 how can i inject factory1 into factory2,['javascript'] +676390,map undefined is not a function in reactjs right i am probably missing the obvious here but i am getting an uncaught typeerror undefined is not a function i seems to be map that is the problem but i can not see whyvar idealist reactcreateclassloadcommentsfromserver function ajax url thispropsurl datatype json success functiondata thissetstatedata data bindthis handlebuttonclick functioninput do stuff getinitialstate function return data componentwillmount function thisloadcommentsfromserver setintervalthisloadcommentsfromserver thispropspollintervalrender function var clickfunction thishandlebuttonclick var ideas thisstatedatamapfunctioni return ideabox datai onbuttonclickclickfunction return div classnameidealist ideas div reactrendercomponentidealist urljsonquotesphp pollinterval20documentgetelementbyidquotelistif i change it to var ideas thisstatedatai do not get any errors the json data is formatted correctly what can be wrong,['javascript'] +676678,configinitializerssecret tokenrb not being generated why not currently going through a rails tutorial and i need to make some modifications to configinitializerssecret tokenrb however i cannot find this file anywhere within the initializers directory i am running the latest version of rails this is the line i used in the terminal to create a rails project rails new sample app anyone know why it is not showing up,"['ruby-on-rails', 'ruby']" +676711,how to get started with windows phone sdk 81 situation i am running windows 7 professional and i am trying to start developing windows phone 81 application i have downloaded vs2013 rtm dskexp enuiso that is microsoft visual studio 2013 express rtm since this is rtm update and windows phone 81 developement needs 2 rc updated i downloaded vs20132 rcexe which is online installer for the update mentioned to download the full local installation package 343 gb i ran evsvs20132 rcexe layout on command linefor installationi first installed microsoft visual studio 2013 express rtmthen 2 rc update both of them installed sucessfully with no errors but when i open visual studio 2013vs express 2013 for desktop from start menu and filenew projectinstalledtemplatesvisual c there is no option for windows phone development that is what i want question how can i get the options to develop windows phone 81 in visual studio 2013 express using c,['c#'] +676738,why does coffeescript use for modulo instead of the standard javascript operator in the coffeescript documentation on operators it says that you can use for true mathematical modulo but there is no explanation as to why this is different from the modulo operator in javascriptfurther down it says that a b in coffeescript is equivalent to writing a b b b in javascript but this seem to produce the same results for most simple cases,['javascript'] +676882,angularjs error unknown provider aprovider ok i am officially bald now after having been streching my hair out with this infamous problem the minfied angularjs app just does not work with this error thown outerror injectorunpr unknown provider aprovider a injectorunprp0aprovider203c20a at httplocalhostmyappthistscripts1bde0e2evendorjs411492 at httplocalhostmyappthistscripts1bde0e2evendorjs426946 at objectc as get httplocalhostmyappthistscripts1bde0e2evendorjs426250 at httplocalhostmyappthistscripts1bde0e2evendorjs427041 at c httplocalhostmyappthistscripts1bde0e2evendorjs426250 at objectd as invoke httplocalhostmyappthistscripts1bde0e2evendorjs426496 at httplocalhostmyappthistscripts1bde0e2evendorjs9910 at objectf as foreach httplocalhostmyappthistscripts1bde0e2evendorjs411927 at httplocalhostmyappthistscripts1bde0e2evendorjs9856 at j httplocalhostmyappthistscripts1bde0e2evendorjs527235lots of other people had this problem as well but looks like it could be fixed by declaring dependencies as an array instead of bare function parameters like thisangularmodulemyappcontrollerloginctrl scope httpservice functionscope httpservice instead of thisangularmodulemyappcontrollerloginctrl functionscope httpservice but it does not work in my case i checked all of my scripts coffee and generated javascripts as well they all use the proper arraystyle declarationthe problem does not come from extra packages apparently i tried moving all extra package references out of bowerjs block so that they are not minified by grunt yet the problem still remains which means it is my code to blame but then again i have tried the seems to be only fix available to no availany hint even on how to properly debug this thanks in advance,['javascript'] +676960,windows phone 8 facebook login given url is not allowed by the application i am trying to integrate the facebook login into my app by following the tutorial on facebooksdknet i am trying to use the facebook button controlwhen i click the button i get following errorgiven url is not allowed by the application configuration or more of the given urls is not allowed by the apps settings must match the website url or canvas url or the domain must be a of one of the apps domainsscreenshot for reference according to some sources there is currently a bug which will prevent facebook login for windows phone from working if you do not have any entries in the valid oauth redirect uris field in the advanced section of your app settings this can be worked around by adding in this fieldhowever that did not resolve the issue so what else can i try to resolve this,['c#'] +677100,thisable time in bootstrap date time picker i am using bootstrap date time picker in my web application made in phphtml5 and javascript i am currently using one from herewhen i am using the control without time it does not work it just shows a blank text boxi just want to remove time from date time picker is there any solution for thisdiv classwell div iddatetimepicker4 classinputappend input dataformatymmdd typetextinput span classaddon i datatimeiconicontime datadateiconiconcalendar i span div div script typetextjavascript function datetimepicker4datetimepicker picktime false script,"['javascript', 'html']" +677358,how to validate my model in a custom model binder i asked about an issue i have with comma delimited numeric values heregiven some of the replies i attempted to try to implement my own model binder as followsnamespace mvcapplication1core public class propertymodelbinder defaultmodelbinder public override object bindmodelcontrollercontext controllercontext modelbindingcontext bindingcontext object objectmodel new object if bindingcontextmodeltype typeofpropertymodel httprequestbase request controllercontexthttpcontextrequest string price requestformgetpricereplace stringempty modelbindingcontext newbindingcontext new modelbindingcontext modelmetadata modelmetadataproviderscurrentgetmetadatafortype new propertymodel price converttoint32price typeofpropertymodel modelstate bindingcontextmodelstate valueprovider bindingcontextvalueprovider call the default model binder this new binding context return basebindmodelcontrollercontext newbindingcontext else return basebindmodelcontrollercontext bindingcontext protected override object createmodelcontrollercontext controllercontext modelbindingcontext bindingcontext type modeltype return basecreatemodelcontrollercontext bindingcontext modeltype propertymodel model new propertymodel if modeltype typeofpropertymodel model propertymodelbasecreatemodelcontrollercontext bindingcontext modeltype httprequestbase request controllercontexthttpcontextrequest string price requestformgetpricereplace stringempty modelprice converttoint32price return model and updated my controller class as thisnamespace mvcapplication1controllers public class propertycontroller controller public actionresult edit propertymodel model new propertymodel agentname john doe buildingstyle colonial builtyear 1978 price 650 id 1 return viewmodel httppost public actionresult editmodelbindertypeofpropertymodelbinder propertymodel model if modelstateisvalid save property info return viewmodel public actionresult about viewbagmessage your app description page return view public actionresult contact viewbagmessage your contact page return view now if i enter the price with commas my custom model binder will remove the commas that is what i want but validation still fails so question is how to do custom validation in my custom model binder such that the captured price value with commas can be avoided in other words i suspect that i need to do more in my custom model binder but do not know how and what thanksupdateso i tried mares solution at and updated my model binder as followsnamespace mvcapplication1core public class propertymodelbinder defaultmodelbinder public override object bindmodelcontrollercontext controllercontext modelbindingcontext bindingcontext object objectmodel new object if bindingcontextmodeltype typeofpropertymodel httprequestbase request controllercontexthttpcontextrequest string price requestformgetpricereplace stringempty modelbindingcontext newbindingcontext new modelbindingcontext modelmetadata modelmetadataproviderscurrentgetmetadatafortype new propertymodel price converttoint32price typeofpropertymodel modelstate bindingcontextmodelstate valueprovider bindingcontextvalueprovider call the default model binder this new binding context object o basebindmodelcontrollercontext newbindingcontext newbindingcontextmodelstateremoveprice newbindingcontextmodelstateaddprice new modelstate newbindingcontextmodelstatesetmodelvalueprice new valueproviderresultprice price null return o else return basebindmodelcontrollercontext bindingcontext protected override object createmodelcontrollercontext controllercontext modelbindingcontext bindingcontext type modeltype return basecreatemodelcontrollercontext bindingcontext modeltype propertymodel model new propertymodel if modeltype typeofpropertymodel model propertymodelbasecreatemodelcontrollercontext bindingcontext modeltype httprequestbase request controllercontexthttpcontextrequest string price requestformgetpricereplace stringempty modelprice converttoint32price return model it sorta works but if i enter 0 for price the model comes back as valid which is wrong because i have a range annotation which says that the minimum price is 1 at my wit is endupdatein order to test out a custom model binder with composite types i have created the following view model classesusing systemcomponentmodeldataannotationsnamespace mvcapplication1models public class propertyregistrationviewmodel public propertyregistrationviewmodel public property property get set public agent agent get set public class property public int housenumber get set public string street get set public string city get set public string state get set public string zip get set requirederrormessageyou must enter the price range10 10 errormessagebad price public int price get set public class agent public string firstname get set public string lastname get set requirederrormessageyou must enter your annual sales range10 50 errormessagebad range public int annualsales get set public address address get set public class address public string line1 get set public string line2 get set and here is the controllerusing mvcapplication1coreusing mvcapplication1modelsusing systemwebmvcnamespace mvcapplication1controllers public class registrationcontroller controller public actionresult index propertyregistrationviewmodel viewmodel new propertyregistrationviewmodel return viewviewmodel httppost public actionresult indexmodelbindertypeofpropertyregistrationmodelbinderpropertyregistrationviewmodel viewmodel if modelstateisvalid save registration return viewviewmodel here is the custom model binder implementationusing mvcapplication1modelsusing systemusing systemcollectionsgenericusing systemlinqusing systemwebusing systemwebmvcnamespace mvcapplication1core public class propertyregistrationmodelbinder defaultmodelbinder protected override object getpropertyvalue controllercontext controllercontext modelbindingcontext bindingcontext systemcomponentmodelpropertydescriptor propertydescriptor imodelbinder propertybinder if propertydescriptorcomponenttype typeofpropertyregistrationviewmodel if propertydescriptorname property var price bindingcontextvalueprovidergetvaluepropertypriceattemptedvaluereplace stringempty var property new property question 1 price is the only property i want to modify is there any way such that i do not have to manually populate the rest of the properties like so propertyprice stringisnullorwhitespaceprice 0 converttoint32price propertyhousenumber converttoint32bindingcontextvalueprovidergetvaluepropertyhousenumberattemptedvalue propertystreet bindingcontextvalueprovidergetvaluepropertystreetattemptedvalue propertycity bindingcontextvalueprovidergetvaluepropertycityattemptedvalue propertystate bindingcontextvalueprovidergetvaluepropertystateattemptedvalue propertyzip bindingcontextvalueprovidergetvaluepropertyzipattemptedvalue i had thought that when this property object returns our annotation of the price property will be honored by the model binder but it does not validate it accordingly return property if propertydescriptorname agent var sales bindingcontextvalueprovidergetvalueagentannualsalesattemptedvaluereplace stringempty var agent new agent question 2 annualsales is the only property i need to process before validation is there any way i can avoid tediously populating the rest of the properties agentannualsales stringisnullorwhitespacesales 0 converttoint32sales agentfirstname bindingcontextvalueprovidergetvalueagentfirstnameattemptedvalue agentlastname bindingcontextvalueprovidergetvalueagentlastnameattemptedvalue var address new address addressline1 bindingcontextvalueprovidergetvalueagentaddressline1attemptedvalue roc addressline2 bindingcontextvalueprovidergetvalueagentaddressline2attemptedvalue md agentaddress address i had thought that when this agent object returns our annotation of the annualsales property will be honored by the model binder but it does not validate it accordingly return agent return basegetpropertyvaluecontrollercontext bindingcontext propertydescriptor propertybinder protected override void onmodelupdatedcontrollercontext controllercontext modelbindingcontext bindingcontext var model bindingcontextmodel as propertyregistrationviewmodel in order to validate our model it seems that we will have to manually validate it here baseonmodelupdatedcontrollercontext bindingcontext and here is the razor viewmodel mvcapplication1modelspropertyregistrationviewmodel viewbagtitle property registrationh2property registrationh2penter your property and agent information belowpusing htmlbeginformindex registration htmlvalidationsummary h4property infoh4 texthouse numbertext htmltextboxform mpropertyhousenumberbr textstreettext htmltextboxform mpropertystreetbr textcitytext htmltextboxform mpropertycitybr textstatetext htmltextboxform mpropertystatebr textziptext htmltextboxform mpropertyzipbr textpricetext htmltextboxform mpropertypricebr h4agent infoh4 textfirst nametext htmltextboxform magentfirstnamebr textlast nametext htmltextboxform magentlastnamebr textannual salestext htmltextboxform magentannualsalesbr textagent address l1texthtmltextboxform magentaddressline1br textagent address l2texthtmltextboxform magentaddressline2br input typesubmit valuesubmit namesubmit and here is the globalasax file where i wire up the custom model binder btw it seems this step is not needed coz i notice it still works without this stepusing mvcapplication1coreusing mvcapplication1modelsusing systemwebhttpusing systemwebmvcusing systemweboptimizationusing systemwebroutingnamespace mvcapplication1 note for instructions on enabling iis6 or iis7 classic mode visit public class mvcapplication systemwebhttpapplication protected void application start arearegistrationregisterallareas webapiconfigregisterglobalconfigurationconfiguration filterconfigregisterglobalfiltersglobalfiltersfilters routeconfigregisterroutesroutetableroutes bundleconfigregisterbundlesbundletablebundles authconfigregisterauth modelbindersbindersaddtypeofpropertyregistrationviewmodel new propertyregistrationmodelbinder maybe i am doing something wrong or not enough i have noticed the following problemsalthough i only need to modify the price value of the property object it seems i have to tediously populate all the other properties in the model binder i have to do the same for the annualsales property of the agent property is there anyway this can be avoided in the model binderi had thought that the default bindmodel method will honor our annotation of our objects properties and validate them accordingly after it calls getpropertyvalue but it does not if i enter some value way out of range for price of the property object or the annualsales of the agent object the model comes back as valid in other words the range annotations are ignored i know i can validate them by overriding onmodelupdated in the custom model binder but that is too much work and plus i have the annotations in place why does not the default implementation of the model binder honor them just because i am overriding part of itdotnetstep could you throw some insights into this thank you,['c#'] +677399,comparing scala and java doublenan why does this comparison evaluate to truescala doublenan equals javalangdoublenanres5 boolean truebut this one evaluates to falsescala doublenan javalangdoublenanres6 boolean falseaside this interesting twitter thread prompted me to ask this question,['java'] +677487,viewpager with different adapters for portrait and landscape in portrait mode my viewpager has 3 fragments a b c but in landscape mode it has only 2 fragments a and c so i create 2 fragmentstatepageradapters for each mode the problem is when screen orientation changed viewpager restores and uses previous fragments of old orientation for example when change orientation from portrait to landscape viewpager now shows 2 fragments a b instead of a and c i know why this happen but cannot find a good solution for thismy current workaround is to use different ids for viewpager eg idviewpager portrait for portrait and idviewpager landscape for landscape layout to prevent from reusing fragments but this cause me a memory leak because old fragment will not be destroyed and still be kept in memoryi have tried some workaround like call superoncreatenull in activitys oncreate or remove fragments of viewpager in activitys onsaveinstancestate but they all makes my app crashso my question is how to avoid reusing one or many fragments in fragmentstatepageradapter when orientation changedany helps will be appreciated thank in advance,['android'] +677489,how to launch telnet console in android studio device emulator i was watching a video where the instructor is using a console to type in commands that lead straight to the emulated android device i have the emulated device functioning and i am using android studio but i cannot seem to figure out where he starts the console from any ideasnote the video is not public so i cannot link it,['android'] +677576,how to create bouncing div animation i am trying to recreate the bouncing arrow animation like on but it is not going wellthe closest i have got with trying to use the built in animations in layerslider is available here devthemarketcreative dot comi have decided that trying to figure this out with layerslider is taking to long does anyone know how to do thisthe furthest i thiscovered is this 149 but i need it do do this animation onload and on a continuous loopthanks,"['javascript', 'jquery', 'css']" +677692,vlc player does not play any video i added the vlc plugin from com component dragged it to my form added two buttons to the form play and stop and wrote the following codeprivate void form1 loadobject sender eventargs e axvlcautoplay false axvlcplaylistaddcusershanifdocumentsvisual studio 2010projectseducation visualizationvlcresourcesvideo1wmvprivate void btnplay clickobject sender eventargs e axvlcplaylistplayprivate void btnstop clickobject sender eventargs e axvlcplayliststopbut when i click on play nothing happenswhat am i doing wrong,['c#'] +677713,how can i get all the plain text from a website with scrapy i would like to have all the text visible from a website after the html is rendered i am working in python with scrapy frameworkwith xpathbodytext i am able to get it but with the html tags and i only want the text any solution for this thanks,"['python', 'html']" +677741,what can cause nsuserdefaults to be cleared i have been getting some odd reports for my app where the application settings stored into the nsuserdefaults is being cleared the reports have all been on ios 7si know you can manually clear the nsuserdefaults by either uninstalling or making a call tonsstring appdomain nsbundle mainbundle bundleidentifiernsuserdefaults standarduserdefaults removepersistentdomainfornameappdomainbut are there any other known causes for an app to clear its settings,"['ios', 'iphone']" +677758,how do i set a number of retry attempts in rabbitmq i am using rabbitmq and i have a queue that holds email messages my consumer service dequeues messages and attempts to send them if for any reason my consumer cannot send the message i would like to requeue the message to send again i realize i can do a basicnack and set the requeue flag to be true however i do not want to requeue the message indefinitely say if our email system goes down i do not want to continuously requeue unsent messages i would like to define a finite number of times that i can requeue the message to be sent again i cannot set a field on the email message object however when i dequeue it and send a nack the updated field is not present on the message in the queue is there any other way in which i can approach this thanks in advance,['.net'] +677776,running grunt on vm shared directory using vagrant with a windows host and linux guest grunt returned the following error when trying to run a jobas i understand this file path exceeds the 255 character limit of windows when on a hostguest shared directorynpm err error eperm open u01aabuildshareappcoreappuinode modulesgruntcontribimageminnode modulespngquantbinnode modulesbinwrappernode modulesdownloadnode modulesrequestnode modulesformdatanode modulescombinedstreamtestintegrationtestdelayedstreamsandbuffersandstringsjsi could develop on a nonshared directory on my guest vm but i would prefer to use a shared directory since i use an ide on the hosthow can i fix this issue so that i can run grunt on the shared directory,['javascript'] +677868,using perls extutilsmakemaker how can i compile an executable using the same settings as my xs module given a perl xs module using a c library assume there is a makefilepl that is set up correctly so that all header and library locations compiler and linker flags etc work correctlynow let us say i want to include a small c program with said xs module that uses the same underlying c library what is the correct platform independent way to specify the target executable so that it gets built with the same settings and flagsif i do the followingsub mypostamble return fragtargetconfigexe ext targetconfigobj exttargetconfigobj ext targetcfragi do not get those include locations lists of libraries etc i set up in the arguments to writemakefile if i start writing rules manually i have to account for at least make dmake and nmake i cannot figure out a straightforward way to specify libraries to link against if use extutilscbuilderi must be missing something i would appreciate it if you can point it out,['c'] +678078,how to debug comandroidokhttp in android kitkat urlconnections implementation has been replaced by okhttphow can it debug it the okhttp is in this directoryexternalokhttpandroidmainjavacomsquareupokhttpwhen i call the urlinstanceopenconnectiongetclassgetname it present comandroidokhttpinternalhttphttpurlconnectionimplhow can i debug the it it seems that i cannot associate the androidmainjavacomsquareupokhttp to the comandroidokhttp when the code excute to the return streamhandleropenconnectionthis returns a new connection to the resource referred to by this url throws ioexception if an error occurs while opening the connection public urlconnection openconnection throws ioexception return streamhandleropenconnectionthisgo forward furtherbut cannot dig into the comsquareupokhttphttphandleropenconnection the the highlighted thread in debugger in the picture below is gray package comsquareupokhttpimport javaioioexceptionimport javanetproxyimport javaneturlimport javaneturlconnectionimport javaneturlstreamhandlerpublic class httphandler extends urlstreamhandler override protected urlconnection openconnectionurl url throws ioexception return newokhttpclientnull proxy openurl override protected urlconnection openconnectionurl url proxy proxy throws ioexception if url null proxy null throw new illegalargumentexceptionurl null proxy null return newokhttpclientproxyopenurl override protected int getdefaultport return 80 protected okhttpclient newokhttpclientproxy proxy okhttpclient client new okhttpclient clientsetfollowprotocolredirectsfalse if proxy null clientsetproxyproxy return client,"['java', 'android']" +678167,how do i send an email with a csv attachment using python okay i know there is a few questions out there addressing this but i cannot find a way to make it work properly i would assume it is as simple as the below code but this does not attach my file any help would be greatly appreciated i am also very new to python is there a mail module that i should be importing to make the function workimport smtplibfromaddr toaddrs msg help i cannot send an attachment to save my lifeattach csvondesktpcsvusername userpassword passwordserver smtplibsmtpsmtpgmailcom587serverstarttlsserverloginusernamepasswordserversendmailfromaddr toaddrs msg attachserverquit,['python'] +678194,cross compiling rethinkdb for raspberry pi currently running ubuntu 1404 x86 64 i want to cross compile rethinkdb for my rpi for experimental purposes which is supported in 112 and people have apparently successfully compiledi have installed the toolchainsudo aptget install g47armlinuxgnueabi gccarmlinuxgnueabiexport cxxusrbinarmlinuxgnueabig47export ccusrbinarmlinuxgnueabigcc47export arusrbinarmlinuxgnueabiarexport ldusrbinarmlinuxgnueabildconfiguration runsconfigure ccache allowfetch withouttcmalloc detecting system configurationbash 4381releaseuse ccache yesc compiler gcc 47 usrbinarmlinuxgnueabig47host system armlinuxgnueabibuild system linux 313024generic x86 64crosscompiling yeshost operating system linuxwithout tcmalloc yesbuild client drivers nobuild architecture x86 64precompiled web assets noprotobuf compiler usrbinprotocnodejs package manager usrbinnpmless css externalless 162coffeescript externalcoffeescript 171handlebars externalhandlebars 130browserify externalbrowserify 32413protobufjs externalprotobufjs 204wget usrbinwgetcurl usrbincurlprotobuf externalprotobuf 250v8 externalv8 32417re2 externalre2 201401z externalzlib 128google test externalgtest 160termcap notest protobuf externalprotobuf 250test boost externalboost 1550installation prefix usrlocalconfiguration prefix usrlocaletcruntime data prefix usrlocalvar warning arm support is still experimental wrote configuration to configmkhowever make fails binbash ccache command not foundany pointers to getting this working,['c++'] +678204,creating variable of type to store object in c i am somewhat new to programming and i have a question about classes inheritance and polymorphism in c while learning about these topics occasionally i will come across code that looks something like thisanimal fluffy new cat where animal is a superclass of catthis confuses me because i do not understand why someone would create a variable of type animal to store an object of type cat why wouldnt a person simply write thiscat fluffy new cati do understand why it is legal to store a child object in a parent type variable but not why it is useful is there ever a good reason to store a cat object in an animal variable vs a cat variable can a person give me an example i am sure it has something to do with polymorphism and method overriding andor method hiding but i cannot seem to wrap my head around it thanks in advance,['c#'] +678256,push notification when new video is uploaded on youtube channel i was looking for a way to get a push notification whenever a new video is updated on a specific channelbasically this but i cannot find this youtube push api is it already availableis there a known way to achieve something similar on android,['android'] +678267,android button or textview border programmatically without using setbackgrounddrawable method i am looking for a way to put a border for either textview or a button programmatically without using the setbackgroundresource methodthe goal i am trying to achieve here is to change the background color dynamically but with a fixed borderwhen i use the setbackgroundresource method for the background border the border does not remain after changing the background color programmatically,['android'] +678286,how to develop chrome extension for gmail i am thinking about developing chrome extension for gmail and i want to know what are the current best practicesfor instanceattaching a gpg signature by default to every emailadding an extra button that does something i have it alreadyhijacking action of sending email and prompting me to do complete somethingjust them examples helping me to thiscover what is possiblethere are quite a few notable extensions that significantly augment gmail functionality i am not affiliated with any of them i just named a fewone option would be to peek into their source which is located herelibraryapplication supportgooglechromedefaultbut maybe there is wishful thinking a good tutorial set of practises on how to fiddle with gmail ui and functionalitygmail extensiongadget api how to add a button to the compose toolbaryou will have to create and inject the button programmatically this will involve quite a bit of scouring the gmail source code spoiler it is uglyhow to build a chrome extension to add panel to gmail windowsthe greatest longterm challenge you will face is that gmails layout will change unexpectedly and break email thiscovery or the modified ui both issues either require some cleverness to solve or will require you to stay up at night wondering whether google will suddenly break your extensionthey are all building out complex apis with similar functionality that can all break independently if gmail decides to significantly change their app structure which they inevitably willgmail runs its code through the closure compiler thereby obfuscating everything on top of that gmail is probably one of the most sophisticated javascript apps out there library by the founder of parse but have not updated in 15 yearsi can show you what i got so far and just so know i do not particularly like selectors like ohjzijj5jitiax7note he also does it he also uses such an obfuscated selectorsmanifestjsoncontent scripts matches css mystylescss js jquery210js myscriptjs myscriptjsvar icon jqueryohjzijj5jitiax7var clone iconclonecloneattrdatatooltip my tooltipcloneonclick function jqueryadgappendp classpopup sample content piconbeforeclonereusing existing ui elements so my functionality looks natively overviewthere are sidebar gadgets and contextual gadgets but they don not offer what i want to achievegmail labs is a testing ground for experimental features that are not quite ready for primetime they may change break or thisappear at any timeforumgmaillabssuggestalabsfeatureit seems like the ability to develop gmail labs is locked to google employeesneed help find us on stack overflow under the gmail tag so yes i would really like to know if there are any tutorials reference materials out therei reviewed many of the similar questions and i am afraid that my options here are limited but i would be extremely happy if i shrine your enlightenment upon me,['javascript'] +678339,use a remote stylesheet inside a template tag with shadow dom i am trying to make a semiresuseable widget but i am running into a problem i am trying to encapsulate a some css code inside a shadow root so that it does not affect the rest of the webpage but this css is used across multiple widgets so i am trying to include a remote stylesheet none of the examples i have found use a remote style sheet and i was wondering if this was possibleextemplate idtemplatecontent head link relstylesheet hrefcssgeneralstyle1css head body div classaffectedbygeneralstyle1div bodytemplatescript to include templatediv idhostdivscript var importeddata html import elementimportgetelementbyidtemplatecontent var shadow documentqueryselectorhostcreateshadowroot var clone documentimportnodeimporteddatacontent true shadowappendchildclonescript,['css'] +678347,isotope relayout method error no such a method sorry if i am not the first but is the isotope relayout method works did they change it or i am doing something wrongi have a container with images at some moment i need to replace images with new images and i need to relayout the containercontainerisotoperelayoutthis method returnsno such method relayout for isotope instance what am i doing wrong,"['javascript', 'html']" +678363,can roslyn be installed without visual studio the roslyn enduser preview is a vsix visual studio extension but it replaces the compilers in the system net framework installation such that involving cscexe from the commandline will begin using roslynis it possible to install the roslyn cscexe on a computer without visual studio installed howyes roslyn works with visual studio 2013 express so licensing is not an issue but thisk space is even the express edition has a very large footprint compared to say sharpdevelop,['.net'] +678412,casperjs is too slow because of too many navigation requests as we know we can abort a resource request in casperjs like thiscasperonpageresourcerequested functionrequestdata request ifplusonegooglecomaboutblanktestrequestdataurl thisechoi can ignore this requestabort but i found it too slow it might take hours to open a page because of too many navigation requests the type of most of them is reload i want something like thiscasperonnavigationrequested functionurl navigationtype navigationlocked ismainframe utilsdumparguments ifplusonegooglecomaboutblanktesturl thisechocan i abort the request requestabort i searched whole day in google and got nothing this drives me crash,['javascript'] +678469,how to solve error missing secret key base for production environment rails 41 i have created a rails app rails 41 from scratch and i am facing a strange problem that i am not able to solveevery time i try to deploy my app on heroku i get an error 500missing secret key base for production environment set this value in configsecretsymlthe secretyml file contains the following configuration secret key base envsecret key base on heroku i have configured an environment variable secret key base with the result of rake secret command if i launch heroku config i can see the variable with the correct name and valuewhy am i still getting this errorthanks a lot,"['ruby-on-rails', 'ruby']" +678536,newtonsoft json serializer performance i have an object that i am serializing into json using newtonsoft jsonnet the object is relatively large the resulting json is about 300kb but the serialization process takes around 60 secondsthe objects to be serialized are just plain pocosthe code i am using is string json newtonsoftjsonjsonconvertserializeobjectdata formattingindentedis there anything that can be done to speed up the serialization adding attributes etcedit i have just tested with servicestacktext json serializer and that takes 48 seconds still pretty slowserializablepublic class appointmentitemviewmodel public appointmentitemviewmodel data new appointmentdata statuses new liststatus closeddays new listclosedday openhours new listopenhours public int currentday get set public int currentmonth get set public int currentyear get set public int day get set public int month get set public int year get set public int firsthour get set public int lasthour get set public int currenthour get set public int step get set public bool staffonlybookown get set public bool allowpastappointments get set public bool allowblocks get set public bool allowgooglecalendarsync get set public long currentuser get set public string debuginfo get set public bool hasresources get set public string organisationid get set public string defaulttab get set public string startday get set public bool appointmentbreaksonweek get set public bool appointmentbreaksonmonth get set public appointmentdata data get set public ienumerablestatus statuses get set public ienumerablelocationstaff staff get set public ienumerableclosedday closeddays get set public ienumerableopenhours openhours get set public iusercontext usercontext return servicelocatorcurrentgetinstanceiusercontext public override string tostring serialize the json var sb new stringbuilder stringwriter sw new stringwritersb using jsonwriter writer new jsontextwritersw writerwritestartobject writepropertywriter currentday thiscurrentday writepropertywriter currentmonth thiscurrentmonth writepropertywriter currentyear thiscurrentyear writepropertywriter day thisday writepropertywriter month thismonth writepropertywriter year thisyear writepropertywriter firsthour thisfirsthour writepropertywriter lasthour thislasthour writepropertywriter currenthour thiscurrenthour writepropertywriter step thisstep writepropertywriter staffonlybookown thisstaffonlybookown writepropertywriter allowpastappointments thisallowpastappointments writepropertywriter allowblocks thisallowblocks writepropertywriter allowgooglecalendarsync thisallowgooglecalendarsync writepropertywriter currentuser thiscurrentuser writepropertywriter hasresources thishasresources writepropertywriter organisationid thisorganisationid writepropertywriter defaulttab thisdefaulttab writepropertywriter startday thisstartday writepropertywriter appointmentbreaksonweek thisappointmentbreaksonweek writepropertywriter appointmentbreaksonmonth thisappointmentbreaksonmonth writerwritepropertynamestatuses writerwritestartarray foreach var item in thisstatuses writerwritestartobject writepropertywriter id itemid writepropertywriter description itemdescription writepropertywriter color itemcolor writerwriteendobject writerwriteendarray writerwritepropertynamestaff writerwritestartarray foreach var item in thisstaff writerwritestartobject writepropertywriter id itemid writepropertywriter name itemname writerwriteendobject writerwriteendarray writerwritepropertynamecloseddays writerwritestartarray foreach var item in thiscloseddays writerwritestartobject writepropertywriter year itemyear writepropertywriter month itemmonth writepropertywriter day itemday writerwriteendobject writerwriteendarray writerwritepropertynameopenhours writerwritestartarray foreach var item in thisopenhours writerwritestartobject writepropertywriter dayofweek itemdayofweek writepropertywriter openhour itemopenhour writepropertywriter closehour itemclosehour writerwriteendobject writerwriteendarray main data writerwritepropertynamedata writerwritestartobject writerwritepropertynameappointments writerwritestartarray foreach var item in thisdataappointments writerwritestartobject writepropertywriter id itemid writepropertywriter appointmentid itemappointmentid writepropertywriter year itemyear writepropertywriter month itemmonth writepropertywriter day itemday writepropertywriter starthour itemstarthour writepropertywriter startminute itemstartminute writepropertywriter endhour itemendhour writepropertywriter endminute itemendminute writepropertywriter resourceid itemresourceid writepropertywriter description itemdescription writepropertywriter status itemstatus writepropertywriter isclass itemisclass writepropertywriter processinglength itemprocessinglength writepropertywriter clientid itemclientid writepropertywriter clientname itemclientname writepropertywriter clientphone itemclientphone writepropertywriter clientnotes itemclientnotes writepropertywriter clienthasmobile itemclienthasmobile writepropertywriter classfull itemclassfull writepropertywriter clientwaiting itemclientwaiting writepropertywriter promotioncode itempromotioncode writepropertywriter arrivalnote itemarrivalnote writepropertywriter labels itemlabels writepropertywriter remindersent itemremindersent writepropertywriter cancelled itemcancelled writerwritepropertynameitems writerwritestartarray foreach var appointmentitem in itemitems writerwritestartobject writepropertywriter name appointmentitemname writepropertywriter length appointmentitemlength writepropertywriter processingtime appointmentitemprocessingtime writepropertywriter resource appointmentitemresource writerwriteendobject writerwriteendarray writerwriteendobject writerwriteendarray writerwritepropertynameresources writerwritestartarray foreach var item in thisdataresources writerwritestartobject writepropertywriter id itemid writepropertywriter name itemname writepropertywriter blocklength itemblocklength writepropertywriter starthour itemstarthour writepropertywriter endhour itemendhour writerwritepropertynamebreaks writerwritestartarray foreach var breakitem in itembreaks writerwritestartobject writepropertywriter year breakitemyear writepropertywriter month breakitemmonth writepropertywriter day breakitemday writepropertywriter dayofweek breakitemdayofweek writepropertywriter starthour breakitemstarthour writepropertywriter startminute breakitemstartminute writepropertywriter length breakitemlength writepropertywriter description breakitemdescription writepropertywriter otherbreak breakitemotherbreak writepropertywriter userbreak breakitemuserbreak writerwriteendobject writerwriteendarray writerwritepropertynameopenclosebreaks writerwritestartarray foreach var breakitem in itemopenclosebreaks writerwritestartobject writepropertywriter year breakitemyear writepropertywriter month breakitemmonth writepropertywriter day breakitemday writepropertywriter dayofweek breakitemdayofweek writepropertywriter starthour breakitemstarthour writepropertywriter startminute breakitemstartminute writepropertywriter length breakitemlength writepropertywriter description breakitemdescription writepropertywriter otherbreak breakitemotherbreak writepropertywriter userbreak breakitemuserbreak writerwriteendobject writerwriteendarray writerwriteendobject writerwriteendarray writerwriteendobject return sbtostring private void writepropertyjsonwriter writer string name object value writerwritepropertynamename if value null writerwritenull else writerwritevaluevalue serializablepublic class appointmentdata public ienumerableexternalevent exteralevents get set public ienumerableappointment appointments get set public ienumerableresource resources get set serializablepublic class closedday public int year get set public int month get set public int day get set serializablepublic class appointment public long id get set public long appointmentid get set public int year get set public int month get set public int day get set public int starthour get set public int startminute get set public int endhour get set public int endminute get set public long resourceid get set public string description get set public long status get set public bool isclass get set public int processinglength get set public long clientid get set public string clientname get set public string clientphone get set public string clientnotes get set public bool clienthasmobile get set public bool classfull get set public string clientwaiting get set public string promotioncode get set public string arrivalnote get set public string labels get set public bool remindersent get set public bool cancelled get set public ienumerableappointmentitems items get set serializablepublic class appointmentitems public string name get set public int length get set public int processingtime get set public string resource get set serializablepublic class openhours public int dayofweek get set public int openhour get set public int closehour get set serializablepublic class resource public resource breaks new listresourcebreak blocks new listresourceblock openclosebreaks new listresourcebreak public long id get set public string name get set public int blocklength get set public int starthour get set public int endhour get set public ienumerableresourcebreak breaks get set public ienumerableresourceblock blocks get set public ienumerableresourcebreak openclosebreaks get set serializablepublic class externalevent public long id get set public int year get set public int month get set public int day get set public int dayofweek get set public int starthour get set public int startminute get set public int endhour get set public int endminute get set public int length get set public string description get set serializablepublic class resourcebreak public int year get set public int month get set public int day get set public int dayofweek get set public int starthour get set public int startminute get set public int length get set public string description get set public bool otherbreak get set public bool userbreak get set serializablepublic class resourceblock public int starthour get set public int startminute get set public int length get set serializablepublic class status public long id get set public string description get set public int color get set serializablepublic class locationstaff public long id get set public string name get set,['c#'] +678555,androidhow to clear an edittext by cross button in the right side i have created an edittext for search which contains in the left side a search icon and in the right side a cross iconedittext androidididsearch androidlayout width250dp androidlayout heightwrap content androiddrawableleftandroiddrawableic menu search androiddrawablerightandroiddrawableic delete androidhintsearch product edittexti want to know how can i clear the content of edittext when i click in the cross buttonthank you in advance,['android'] +678613,sqlcommand with using statement i saw that in most samples sqlcommand was used like thisusing sqlconnection con new sqlconnectioncnn string using sqlcommand cmd new sqlcommandselect idname from person con sqldataadapter da new sqldataadaptercmd dataset ds new dataset dafillds return ds i know why we are using using statement but sqlcommand does not inlcude close method so should we really use it within using statement,['c#'] +678651,finite field arithmetic over gf2n i am working on a project that involves koblitz curve for cryptographic purposesneed a library in python that implements finite field operations like multiplication and inverse in galois field gf2n already tried the following library bitvectorunfortunately the modulo inverse operation is working too slow even for fields of size 2163,['python'] +678710,net clr threadpool exhaustion implementation bug i wrote a simple async based loadtesting library and it also has a console interface to test from the commandline basically it runs a huge number of requests concurrently aggregates them and shows a summary and a simple histogram nothing fancy but i run a lot of tests in the local system so i wanted to make sure the test tool got out of the way for a relatively accurate benchmark using the least resource possible so it uses bare asynchrony with beginend methods to maintain the least overhead all done fully asynchronous it works and gets out of the way well mostly but the number of threads in a normal session was well over 40 so a really neat wastage of resources for a machine with 4 hardware threads considering the local machine is also running the server being testedi am already running the program in an asynccontext which basically is just a simple queued context putting everything on to the same thread so all aync postbacks are on the main thread perfectnow all i have to do is to limit the threadpools maximum threads and see how well it performs limited it to the actual core with 4 workers and 4 iocp threadsresultexception there were not enough free threads in the threadpool to complete the operationwell this is not a new issue and is quite scattered all over the internet but is not the whole point of the threadpool that you can put things over onto the pools queue and it executes whenever a thread is availableinfact the name of the method is queue userworkitem and the documentation appropriately says queues a method for execution the method executes when a thread pool thread becomes available now if there are not enough free threads available ideally speaking whats expected is perhaps a slow down in the execution of the program iocp and asynchronous tasks should just be queued in but why is it implemented in such a way that it knocks over and fails instead increasing the number of threads is not the solution when its called a threadpool intended to be a queueedit clarificationi am fully aware of the concept of the threadpool and why the clr spins up more threads it should i agree that it is infact the correct thing to do when there are heavy iobound tasks but the point is if you do infact restrict the threads in the threadpool it is expected to queue the task for execution whenever a free thread is available not throw an exception the concurrency could be affected perhaps even slowing down the outcome but a queueworkuseritem is intented to queue not work only when a new thread is available or fail hence my speculative assertion that its an implementation bug as stated in the titleupdate 1 the same problem as documented in microsofts support forums with an example enus815637the workaround suggested obviously being to increase number of threads as it fails to queuenote this is under a very old runtime and the method to reproduce the same issue on the 451 runtime is given belowupdate 2ran the same pieces of code on the mono runtime and the threadpool seems to have no issues there it gets queued up and executed the issue happens only under the microsoft clrupdate 3after noseratios pointed out the valid issue of not being able to reproduce the same code under net 451 below is a piece of code that will reproduce the issue in order to break the code that works while being queued as expected all that really has to be done is adding a true asynchronous call to the queued delegate for example just adding the below line to the end of the delegate should end up in a exceptionawait webrequestcreategetresponseasyncclose code for reproduction heres a code that is slightly modified from the mskb article and that should fail quickly under net 451 in windows 81 feel free to change the url and the thread limits public static void main threadpoolsetminthreads1 1 threadpoolsetmaxthreads2 2 for int i 0 i 5 i consolewritelinequeued 0 i threadpoolqueueuserworkitempoolfunc consolereadlineprivate static async void poolfuncobject state int workerthreads completionportthreads threadpoolgetavailablethreadsout workerthreads out completionportthreads consolewriteline available workerthreads 0 completionportthreads 1 workerthreads completionportthreads threadsleep10 string url httplocalhost8080 httpwebrequest myhttpwebrequest creates an httpwebrequest for the specified url myhttpwebrequest httpwebrequestwebrequestcreateurl sends the httpwebrequest and waits for a response consolewritelinewait for response var myhttpwebresponse await myhttpwebrequestgetresponseasync consolewritelinedone myhttpwebresponsecloseany insight into this behavior that could bring reasoning to this is much appreciated thanks,"['c#', '.net']" +678732,new javasecurityaccesscontrolexception in java 8 previously working network code is throwing javasecurityaccesscontrolexceptionin a fully sandboxed java appletcannot get socket 2255 javasecurityaccesscontrolexception access denied javanetsocketpermission 503132255 connectresolvewhat has oracle changed what new security hoop must be jumped tokeep sockets to workingthis workedworks in java 170 55 and all previous versions of java,['java'] +678915,how to implement expandable android navigation drawer with subitems how to implement android navigation drawer like thistoplevelview1 toplevelview4 can select and no childrentopvevelview5 can collaspemy question is that if my group structure like this for exampleallstaredcategorymp3txtdocpdfwhen i select all then show all filewhen i select stared then show stared file onlywhen i select mp3 then show only mp3 filesand category can expand and collapse,['android'] +678965,how to exclude certain properties from binding in aspnet web api how do i exclude certain properties or explicitly specify which model properties should be bound by web api model binder something similar to createproductbindinclude namecategory product product in aspnet mvc without creating yet another model class and then duplicating all the validation attributes for it from the original model ef entity model classpublic class user public int id get set exclude public string name get set include public string email get set include public bool isadmin get set include for admins only http post apiusers bind name and email properties onlypublic httpresponsemessage postuser user if thismodelstateisvalid return thisrequestcreateerrorresponsethismodelstate thisdbusersadduser thisdbsavechanges return thisrequestcreateresponsehttpstatuscodeok http post apiadminusers bind name email and isadmin properties onlypublic httpresponsemessage postuser user if thismodelstateisvalid return thisrequestcreateerrorresponsethismodelstate thisdbusersadduser thisdbsavechanges return thisrequestcreateresponsehttpstatuscodeok,"['c#', 'asp.net']" +679062,django load objects instances just once make them available starting app i have an app django 16 that uses around 40 objects for natural language processing nlp previously generatedall application processes requests tests custom management commands etc need to use all of those objects in some waywhat i would like to do is to load all of those objects just once at the startup moment or so and store them in memory to make them available for all app processesthis post has some clues but i would love to hear your thoughts about what is the best approach to the situationclarification the 40 objects are used just for reading in all processes they are not being modified in any way into the appthank you so much,['python'] +679120,mono mvc5 views do not work i am trying to launch mvc5 website on my linux box using mono and xsp4 it works with no views however when i try to render something it gives me errorshere is my test code note that i did not change anything this is basically a blank site without ef or any other libraries just barebone mvc5 razorpublic actionresult index return contentsall good works return viewsysteminvalidoperationexceptioncould not locate razor host factory type systemwebmvcmvcwebrazorhostfactory systemwebmvc version50 cultureneutral publickeytoken31bf3856ad364e35description http 500error processing requestdetails nonweb exception exception origin name of application or object systemwebwebpagesrazorstacktraceat systemwebwebpagesrazorwebrazorhostfactorycreatefactory systemstring typename 0x0 in filename unknown0at systemcollectionsconcurrentconcurrentdictionary2getoraddc anonstorey3systemstringsystemfunc1systemwebwebpagesrazorwebrazorhostfactorym 0 0x0 in filename unknown0 at wrapper delegateinvoke systemfunc1systemcollectionsgenerickeyvaluepair2string systemfunc1systemwebwebpagesrazorwebrazorhostfactoryinvoke tresult this i have tried to change version50 to 40 and 30 etc but nothing works i still get the same error just now it is about 40is there any hope,['c#'] +679189,does switch case order affect speed i have tried to google this but had no lucki have a very big switch and some cases are obviously more common than othersso i would like to know if the order is really held as it is and the upper cases get tested before the lower therefore being evaluated fasteri would like to keep my order but if it hurts speed then reordering the branches would be a good ideafor illustrationswitch mark case ionnull return null case ionboolean return readboolean case ionbyte return readbyte case ionchar return readchar case ionshort return readshort case ionint return readint case ionlong return readlong case ionfloat return readfloat case iondouble return readdouble case ionstring return readstring case ionboolean array return readbooleans case ionbyte array return readbytes case ionchar array return readchars case ionshort array return readshorts case ionint array return readints case ionlong array return readlongs case ionfloat array return readfloats case iondouble array return readdoubles case ionstring array return readstrings default throw new corrupteddataexceptioninvalid mark mark,['java'] +679278,does in class member initialization takes place at compile time or runtime in c11 a new feature was introduced where the programmer can initialize class member variables inside clas definition see code below struct foo int size 3 int id 1 int type 2 unsigned char data3 1 2 3is this initialization takes place during compile time or this feature is just syntactic sugar and member variables are initialized in the default constructor,['c++'] +679307,how to darken a background using css i have an element with text in it whenever i decrease the opacity then i decrease the opacity of the whole body is there any way i can just make the backgroundimage darker and not everything else backgroundimageurl sky stars and you by muddymellyd4bg1ubpng,"['html', 'css']" +679696,syntaxerror invalid regular expression missing according to my reqex seems to work but when i implement it into my javascriptvar prefix hashreplaceg i will get the following error syntaxerror invalid regular expression missing,['javascript'] +679836,how to float different size div to left in perfect grid style here i have a problem i have many divs having same width but their heights are different and are float to left but they are not appearing as i want its appearing asbut i want to make them likeso tell me how can i do this using pure htmlcss no javascript or jquery etc,"['javascript', 'jquery', 'css', 'html']" +679866,aspnet identity with repository and unit of work i am learning repository and unit of work patterns in aspnet mvc 5 application with entity framework 6i had already read a lot of tutorials and articles but almost all of them are condradictory ones say that repository and unit of work patterns are good others say dbcontext is already a repository and unit of work others say something similar but offer a completely different approach i tried all these different approaches well maybe not all of them and still struggling regarding which approach is the most correct onewhat i currently have isirepository and genericrepository implementing irepositoryiunitofwork and unitofwork implementing iunitofworkidbcontext and mydbcontext inherited from identitydbcontext and implementing idbcontextnot sure if i need to paste the code for it i think it is pretty generic and the problem actually is not with repositoryunitofwork as such the issue i have is with using aspnet identity classes in combination with my repositories and unit of worki am sharing same database for membership and for all other data and i think it is a common scenario i cannot find the good solution how can i instantiate aspnet identity classes using my repositoriesuserstoreapplicationuser store new userstoreapplicationuser dbcontext thisusermanager new usermanagerapplicationuserstorewhat should i put in place of dbcontext so that it would share same dbcontext with my unitofwork or how it can be done in some other way to make aspnet identity to work with unitofworki tried exposing dbcontext as public property of unitofwork class something likeuserstoreapplicationuser store new userstoreapplicationuserthisunitofworkmydbcontexthowever i do not think it is right it does not work with custom idbcontext interface and makes the code not good for unit testingi also tried to implement customuserstore and customrolestore in general it worked but as i was testing it it was requiring to implement more and more methods this solution looks too complicated i really hope there should more simple way,['c#'] +679876,sql server 2012 getclob the conversion from varchar nvarchar to clob is unsupported i wonder what am i doing wrong in the scenario described below i assessing some sql server versions for a project and playing around with different db types in a simple java setting i use eclipse java 6 16u45 driver sqljdbc4jar sql server 2012 default installation windows 7 and i am trying to write and read back from a test databasetable different db types for columns of type nvarcharn or max andor varcharn or max write to db using setclob and setcharacterstream methods without any problems but when i try to read back the clobs i can only use getcharacterstream for reasons that i cannot understand i cannot use getclob with either of the db types listed above i get the following exception stackcommicrosoftsqlserverjdbcsqlserverexception the conversion from varchar to clob is unsupportedat commicrosoftsqlserverjdbcsqlserverexceptionmakefromdrivererrorsqlserverexceptionjava171at commicrosoftsqlserverjdbcdatatypesthrowconversionerrordatatypesjava17at commicrosoftsqlserverjdbcserverdtvimplgetvaluedtvjava2419at commicrosoftsqlserverjdbcdtvgetvaluedtvjava176at commicrosoftsqlserverjdbccolumngetvaluecolumnjava113at commicrosoftsqlserverjdbcsqlserverresultsetgetvaluesqlserverresultsetjava1981at commicrosoftsqlserverjdbcsqlserverresultsetgetvaluesqlserverresultsetjava1966at commicrosoftsqlserverjdbcsqlserverresultsetgetclobsqlserverresultsetjava2488at maincomtesttestmaintestjava77 i could not find any reference for this exception ms documentation claims that getclob is supported for nvarcahrvarchar columns code is very simple one insert and then select from table and then positional resultsetgetxposition callsthanks in advance for any suggestion or ideas,['sql'] +679968,minimum window in string 1 containing all characters from string 2 and no character from string 3 ok this is an interview question and no it is not a duplicate of this questiongiven 3 strings str1 str2 str3str1 spqrstrupvqwstr2 sprtstr3 qweve to find the minimum window in str1 which contains all characters from str2 in any order but no character from str3 in this case the answer would be strupi have come up with this codestatic string minimumwindowstring str1 string str2 string str3 class window implements comparablewindow int start int end public windowint start int end thisstart start thisend end public int getend return end public int getstart return start public int comparetowindow o int thisdiff end start int thatdiff oend ostart return integercomparethisdiff thatdiff override public string tostring return start end create sets of characters for contains check setcharacter str2chars new hashset for char ch str2tochararray str2charsaddch setcharacter str3chars new hashset for char ch str3tochararray str3charsaddch this will store all valid window which does not contain characters from str3 setwindow set new treeset int begin 1 this loops gets each pair of index such that substring from start end in each window does not contain any characters from str3 for int i 0 i str1length i if str3charscontainsstr1charati setaddnew windowbegin i begin i 1 int minlength integermax value string minstring iterate over the windows to find minimum length string containing all characters from str2 for window window set if windowgetend 1 windowgetstart str2length continue for int i windowgetstart i windowgetend i if str2charscontainsstr1charati got first character in this window that is in str2 start iterating from end to get last character start end substring will be the minimum length string in this window for int j windowgetend 1 j i j if str2charscontainsstr1charatj string s str1substringi j 1 setcharacter schars new hashset for char ch stochararray scharsaddch if this substring contains all characters from str2 then only it is valid window if scharscontainsallstr2chars int len scharssize if len minlength minlength len minstring s there are cases when some trailing and leading characters are repeated somewhere in the middle we do not need to include them in the minlength in the given example the actual string would come as rstrup but we remove the first r safely stringbuilder strbuilder new stringbuilderminstring while strbuilderlength 1 strbuildersubstring1contains strbuildercharat0 strbuilderdeletecharat0 while strbuilderlength 1 strbuildersubstring0 strbuilderlength 1contains strbuildercharatstrbuilderlength 1 strbuilderdeletecharatstrbuilderlength 1 return strbuildertostring but it does not work for all the test cases it does work for the example given in this question but when i submitted the code it failed for 2 test cases no i do not know the test cases for which it failedeven after trying various sample inputs i could not find a test case for which it fails can someone take a look as to what is wrong with the code i would really appreciate if someone can give a better algorithm just in pseudocode i know this is really not the optimized solution though,['java'] +680058,google cdn for angular dependencies is there a way to reduce the following includes down to onescript srcajaxgoogleapiscomajaxlibsangularjs121angularminjsscriptscript srcajaxgoogleapiscomajaxlibsangularjs121angularrouteminjsscriptscript srcajaxgoogleapiscomajaxlibsangularjs121angularsanitizeminjsscriptscript srcajaxgoogleapiscomajaxlibsangularjs121angularanimateminjsscriptscript srcajaxgoogleapiscomajaxlibsangularjs121angularcookiesminjsscripti cannot find a combined version of these hosted on googles cdn,['javascript'] +680111,setting numpoints in matplotlib legend does not work i am trying to have a single data point on a plot legend by following the suggestions here and it does not seem to workfrom pylab import scatterimport pylabimport matplotlibpyplot as pltfig pltfigureax pltgcaaxscatter12c blue marker xaxscatter23 c red marker oaxlegend12 loc 2 numpoints 1pltshowam i doing something completely stupid here some additional informationin 147 import matplotlib print matplotlib version out 147 1rc,['python'] +680113,sql azure time consuming query i have a table in sql azure contains about 6m rowsi want to create a new index for it the cmd is likecreate nonclustered index index1 on dbotable1 column1 asc column2 asc column3 asc column4 ascinclude column5column6 and after about 15 minutes an error occursmsg 10054 level 20 state 0 line 0a transportlevel error has occurred when receiving results from the server provider tcp provider error 0 an existing connection was forcibly closed by the remote hosti tried several times got the same errorbut i have executed other time consuming querieslikeinsert into table1col1col2col3 select col1col2col3 from table2which took 20 minutes and returned successfullythe queries were executed in the same sql azure db i do not know whats going on here could anyone help thanks,['sql'] +680139,memory leak using powershell remote calls in c i have a windows service that is doing a lot of exchange remote calls to get some server information i noticed that as longs as the time passes the memory used by the service starts growing until a memory exception is thrown i have searched and it looks like there is a known memory leak in the systemmanagementautomation that does not thispose all the memory of the runspace created while calling the close andor thispose method i reviewed a post that suggest using the createoutofprocessrunspace of the runspacefactory but not sure how to use ithere is how the issue can be reproduced systemmanagementautomation dll referencedfor int i 0 i 10 i var runspace runspacefactorycreaterunspace runspaceopen runspaceclose runspacethisposeif you run this code you will see how the memory is incremented due to the requirements keeping a connection open as much as possible is not a good solution do you know how i can fix this issue even using the createoutofprocessrunspace method of the runspacefactory or how to propery thispose the memorythanks in advanceedit i was using the v3 and change the runspace creation to use the createrunspacepool method and it looks like the leak is gone thanks so much for your help,['c#'] +680197,variadic unused functionmacro a wellknown and portable way to suppress c compiler warnings about unused variables is see unused parameter warnings in c codedefine unusedx voidxi am looking for a way to generalize this to take multiple inputs of different typevoid fooint a long b void c want this all unuseda b c instead of unuseda unusedb unusedcone way that seems to do the trick is to use a variadic functionstatic inline void all unusedint dummy however i suspect this solution is objectionable in the expert eye is there a standardcompliant and portable ie not using attribute unused way to make a variadic unused functionmacro many thankseditthere does not seem to exist a clean way of doing what i asked for in the context of c99 or the c preprocessor such is lifein his answer below dabo shows a pretty interesting way of doing what i asked for using a series of macros this is neat and informative at least to me so i accept that answer that said i would not deploy it in a big project because it is tearse enough to outweigh the benefit it brings in my eyes but people will come to different conclusions here as noted below the approach of using an empty variadic function is not perfect either while it is a pretty elegant oneliner it will provoke warnings about unititialized variables if they are also you have to trust your compiler to completely optimize it away which i object to in principle but that all compilers i have tried with actually doone relevant case is when stubbing functions after an early highlevel interface design phase then your unused variables will all be function arguments and initialized by definition and the following approach works finestatic inline void unusedint dummy void fooint a long b void c unuseda b b no warnings,['c'] +680216,swiperefreshlayout in android i am using swiperefreshlayout in my below layoutxml version10 encodingutf8linearlayout xmlnsandroid androidlayout widthwrap content androidlayout heightwrap content androidbackgroundcolorhomepagebackground androidorientationvertical androidsupportv4widgetswiperefreshlayout androidididswiperefreshlayout listview androidlayout widthmatch parent androidlayout heightmatch parent linearlayout androidlayout widthmatch parent androidlayout heightwrap content androidorientationvertical fragment androidididannouncementhomefragment androidnameintestappannouncementfragment androidlayout widthmatch parent androidlayout heightwrap content scrollview androidlayout widthmatch parent androidlayout heightwrap content androidbackgroundcolorhomepagebackground relativelayout androidlayout widthmatch parent androidlayout heightwrap content androidlayout marginbottom15dp androidbackgroundcolorhomepagebackground textview androidididnewstitle androidlayout widthwrap content androidlayout heightwrap content androidlayout gravitycenter androidlayout marginleft15dp androidlayout margintop5dp androidgravitycenter androidtextstringnew list androidtextappearanceandroidattrtextappearancesmall androidtextcolorcolorwhite androidtextstylebold fragment androidididnewshomefragment androidnameintestappnewsfragment androidlayout widthwrap content androidlayout height190dp androidlayout belowidnewstitle androidlayout margintop15dp textview androidididproducttitle androidlayout widthwrap content androidlayout heightwrap content androidlayout belowidnewshomefragment androidlayout gravitycenter androidlayout marginleft15dp androidlayout margintop5dp androidgravitycenter androidtextstringproduct in home androidtextappearanceandroidattrtextappearancesmall androidtextcolorcolorwhite androidtextstylebold fragment androidididprocategoryhomefragment androidnameintestappcategoryfragment androidlayout widthwrap content androidlayout height170dp androidlayout belowidproducttitle androidlayout margintop15dp textview androidididtrainingtitle androidlayout widthwrap content androidlayout heightwrap content androidlayout belowidprocategoryhomefragment androidlayout gravitycenter androidlayout marginleft15dp androidlayout margintop2dp androidgravitycenter androidtextstringtrainings in home androidtextappearanceandroidattrtextappearancesmall androidtextcolorcolorwhite androidtextstylebold fragment androidididtrainingfragment androidnameintestapptrainingfragment androidlayout widthmatch parent androidlayout height180dp androidlayout belowidtrainingtitle androidlayout marginbottom10dp androidlayout margintop15dp relativelayout scrollview linearlayoutandroidsupportv4widgetswiperefreshlayoutwhen i pull down my swiperefreshlayout it is working but as you can see in the above code i have a scroll view inside that so when i am pulling down my scroll view it goes down and half the images are not showing because it came down when i am trying to pull up again my scroll view is not going up instead swiperefreshlayout is getting call what should i doplease help me out,['android'] +680362,google analytics v303 for ios not receiving data i am having a wierd problem with analytics for iosaccording to console it seems that i am sending data but when i look at realtime overview in google analytics i see no response from my actions in the appthis is how i have implemented the trackerin appdelegate boolapplicationuiapplication application didfinishlaunchingwithoptionsnsdictionary launchoptions start google analytics gai sharedinstancedryrun no gai sharedinstancelogger setloglevelkgailoglevelverbose gai sharedinstancethispatchinterval kganthispatchperiodsec 10 secs gai sharedinstance trackerwithtrackingidkganaccountid idgaitracker tracker gai sharedinstance trackerwithtrackingidkganaccountid uax gai sharedinstancedefaulttracker trackerin myviewcontrollerh import gaitrackedviewcontrollerhinterface fradviceviewcontroller gaitrackedviewcontroller in myviewcontrollerm voidviewdidload super viewdidload nsstring goderaadpath goderad gantracker sharedtracker trackpageviewgoderaadpath stringbyappendingstringadvicetitle witherrornil selfscreenname goderaadpath stringbyappendingstringadvicetitle basically i set the screenname and hope that the gaitrackedviewcontroller will do it is thingi get the following message in console when loading the viewcontroller20140423 114746889 tank2563303 verbose googleanalytics 303c gaibatchingthispatcher persist gaibatchingthispatcherm418 saved hit parameters u o v mi303c an tu00c6nk av 182 cd su00e5danharvitestetartikelsu00e5dan har vi testet bru00f8dristere cid d1c5e459ed0b49d0b532f81fb9ff1d85 sr 320x480 t appview tid ua14180619 ul da v 1 z 15612842331434332 gaiversion 303ctimestamp 20140423 094746 020140423 114756914 tank2563303 verbose googleanalytics 303c gairequestbuilder requestgeturlpayload gairequestbuilderm177 building urlrequest for 20140423 114756923 tank2563303 verbose googleanalytics 303c gaibatchingthispatcher thispatch gaibatchingthispatcherm503 sending hits get cd2fsc3a5danharvitestetartikel2fsc3a5danharvitestetbrc3b8dristeretappviewulda uotidua14180619cidd1c5e459ed0b49d0b532f81fb9ff1d85v1sr320x480 vmi303cantc386nkht1398246466879qt10034z1561284233143433220140423 114757210 tank25660b info googleanalytics 303c gaibatchingthispatcher didsendhitsresponsedataerror gaibatchingthispatcherm157 hits thispatched http status 20020140423 114757214 tank2563303 info googleanalytics 303c gaibatchingthispatcher deletehits gaibatchingthispatcherm430 hits successfully thispatched20140423 114757225 tank2563303 info googleanalytics 303c gaibatchingthispatcher didsendhits gaibatchingthispatcherm167 1 hits sentwhat confuses me is that it says http status 200 hits successfully thispatched and 1 hits sent when i get no response on realtime graphstested on iphone 4any help would be very much appreciatededit i should have been a bit more specificour current version of the app has google analytics implemented already but an older version and xcode wont build with that versionso i do see some activity on realtime when i use the current version with old analytics it works just fine and shows in realtimebut the test devices with my updated version of analytics do not show upsincerelychristian,"['ios', 'iphone', 'objective-c']" +680393,aspnet mvc 4 automatically bind model from array of objects in form post i have built an array of objects in javascript and want to post them back to the server via ajax im using jquerythe javascript object array looks like thisvar columns name col 1 source whatever hidden false width 50 im posting it back like thispostmycontrollermyaction columns columns on the controller action im currently getting thisi have a c object called jqcolumn that i want to bind the post into it looks like thispublic class jqgridcolumn public string name public string source public int width public bool hiddenso i thought that adding a parameter in the controller action of type jqgridcolumn columns would automatically bind the posted data but it does not it generates a array with the correct number of elements but each item in the array has blank valuescan anyone tell me what im doing wrong thanksupdateat present i am manually binding the items in my controller action as follows public void columnchooserjqgridcolumn columns for int i 0 i columnslength i columnsihidden boolparserequestformcolumns i hidden columnsiwidth intparserequestformcolumns i width columnsiname requestformcolumns i name columnsisource requestformcolumns i source return which works fine but i would really like to know the net mvc correct way to do it,['javascript'] +680475,chrome getelementsbytagname returning htmlcollection vs nodelist i have found the the javascript function getelementsbytagname is returning different data depending on the browser chrome sends back and html collection that is longer really better imo than firefox ie or chromium i will outline my findings below my question is essentially why did chrome changes this will other browsers do this as well when and how reliable is the returned length attributecomparing chrome version 3401847116 mvs chromium version 3301750152 ubuntu 1310 256984 i do notice that this chromium build is a bit behind chrome v33 vs v34 so it may be heading this way as well in the ubuntu chromum build but it at least helped me compare whats going on here consider the following code blockscript typetextjavascriptfunction getelements var xdocumentgetelementsbytagnameinput consolelogxlength consolelogxscriptforminput typetext size20 idtest1brinput typetext size20 idtest2brinput typetext size20 idtest3brbrinput typebutton onclickgetelements valuehow many input elementsformrunning the above in chromium and other browsers gives result showing that the length is 4 and the data returned is an indexed array something likeinputtest1 inputtest2 inputtest3 input item function0 inputtest11 inputtest22 inputtest33 inputlength 4 proto nodelistchrome returns a similar but expanded result arrayinputtest1 inputtest2 inputtest3 input test1 inputtest1 test2 inputtest2 test3 inputtest3 item function nameditem function0 inputtest11 inputtest22 inputtest33 inputlength 4test1 inputtest1test2 inputtest2test3 inputtest3 proto htmlcollectionnotice that in both cases the length is 4 but chromium includes each input element a second time indexed by the elements id attribute instead of the index key chrome is returning an htmlcollection where chromium supplies a nodelistin the past i have processed these arrays with for x in y syntax plus some validation like sovar inputs documentgetelementsbytagnameinputfor x in inputs ifinputsxid undefined the conclusion i have drawn is that to use the results this wayvar inputs documentgetelementsbytagnameinputfor x0 xinputslength xeither way you access your elements with inputsx but using the second method we guarantee that x is always one of the integers that we use as a key in the first method x would be an integerkey then the string length then any id strings,['javascript'] +680588,delete table row using jquery the code below add and remove table row with the help of jquery the add function works fine but the remove only work if i remove the first row table tr tdbutton typebutton classremovebutton titleremove this rowxbuttontd tdinput typetext idtxttitle nametxttitletd tdinput typetext idtxtlink nametxtlinktd trtablebutton id addbuttonadd rowbuttonand the script var i 1addbuttonclickfunction table trfirstclonefindinputeachfunction thisvalattr id function id return id i name function name return name i value endappendtotable ibuttonremovebuttononclickfunction alertaa thisclosest trremove return falsecan anyone give me the explanation why i can only remove the first row thank so much,"['jquery', 'html']" +680637,libgdx android using netbeans task menu too big for screen in the libgdx netbeans run guide it says to run on android go tasks installdebug however in netbeans the task menu is so long installdebug does not show and one cannot scroll down the list someone else must have had this problem but google has yielded no results to me so my question is how can i installdebug do i have to create a custom task thanks,['java'] +680661,owin selfhost cookieauthentication legacy net 40 application formsauthenticationticket i have two bounded contextsaspnet 40 mvcwebforms applicationowin selfhosted w aspnet web api 2the former is an existing wellestablished product however its lack of architecture smartui has led to an difficulttomaintain codebase with concerns of extensibility and scalability now more glaringly visiblewe are iteratively addressing this issue by introducing a new backend application exposable via owinwebapi servicescurrently were only looking to leverage cookie authentication in the new application originally i thought it would be a breeze to use existing cookie authvalidation based upon formsauthenticationticket evidently this is not truein our webforms application we make use of machinekey to designate our decryptionkey and validationkey to support our web farm in net4 the default algorithm is aes if i am not mistaken i assumed it would be simple to leverage this information to build our own ticketdataformat if the default wouldnt sufficefirst things learnedif you selfhost with owin the default ticketdataformat uses dpapi and not aspnet iis machinekeyin net 45 microsoft has made the mvcwebforms machinekey pipeline more extensible you can replace it with your own implementation and not just change the algorithmideally were not looking to update our main application to net 45 to replace cookie encryption does anyone know of a way to integrate owins cookieauthentication with an existing formsauthenticationticketwe tried creating customidataprotector securedataformatauthenticationticket idataserializerauthenticationticket implementationsthe idataserializer would be responsible for translation between formsauthenticationticket and authenticationticketunfortunately i cannot find accurate information regarding microsofts ticket encrpytion here is our example idea for idataprotectorpublic byte unprotectbyte protecteddata using var crypto new aescryptoserviceprovider byte result null const int32 blocksize 16 cryptokeysize 192 cryptokey machinekeytobytesfromhexadecimal cryptoiv protecteddatatakeblocksizetoarray cryptopadding paddingmodenone this prevents a padding exception thrown using var decryptor cryptocreatedecryptorcryptokey cryptoiv using var msdecrypt new memorystreamprotecteddataskipblocksizetakeprotecteddatalength blocksizetoarray using var csdecrypt new cryptostreammsdecrypt decryptor cryptostreammoderead result new byteprotecteddatalength blocksize csdecryptreadresult 0 resultlength return result this assumes microsoft prepends the iv to the byte array this also assumes the machinekey is the aes key used however i have read that ms uses the machinekey for a key derivation function taking into account other settings like appisolation appvirtuallocation appid etc basically this was a shot in the dark and i need some lightour current approachwere currently prototyping using a secondary cookie to establish identity for the new application context alongside the existing aspxauth unfortunately this means keeping session sliding in sync in both authenticationticket and formsauthenticationticketrelated postsaccepting aspnet forms authentication cookies in an owinhosted signalr implementation,['asp.net'] +680681,ios cannot alloc new object in switch case i have a switch case like this switch weathercode intvalue case 1 break case 2 break but i want to alloc an object in that case like nsstring string hellobut it keep gives me an error expect expression which i do not understand whats going on at all please helpthanks,"['ios', 'objective-c']" +680684,overloading dict on python class i have a class where i want to get the object back as a dictionary so i implemented this in the dict is this correcti figured once i did that i could then use the dict custom object and get back the object as a dictionary but that does not workshould you overload dict how can you make it so a custom object can be converted to a dictionary using dict,['python'] +680719,parse starter project login and register view controllers errors when i tried to use the parse starter project i downloaded it and installed it as per the instructions but i do not have a developers license yet so no push notifications i got six errors all about referencing twitter macho link errorshere they areundefined symbols for architecture i386 acaccounttypeidentifiertwitter referenced from pf twitter getlocaltwitteraccountasync in parsepf twittero objc class acaccountstore referenced from objcclassref in parsepf twittero objc class slcomposeviewcontroller referenced from objcclassref in parsepf twittero objc class slrequest referenced from objcclassref in parsepf twittero slservicetypetwitter referenced from pf twitter getaccesstokenforreverseauthasynclocaltwitteraccount in parsepf twittero pf twitter getlocaltwitteraccountasync in parsepf twittero ld symbols not found for architecture i386clang error linker command failed with exit code 1 use v to see invocation,['ios'] +680783,floating point rounding error php how can i make sure it works correctly i have the following function that determines if i sale is fully paid for i do not remember why i did it this way but it has been working so far and i do not remember why i had to do it this wayfunction payments cover total get payments is a list of payment amounts such as 1020 1021 or even 101010101101 10 decimals max total payments 0 foreachthissale libget payments as payment total payments paymentpayment amount to currency no money rounds total to 2 decimal places if to currency no moneythissale libget total total payments 1e6 return false return truei am wondering if there is ever a case where due to a rounding error that this function would return false when it should not the main part i have a question about is 1e6i think before i had but it was causing problems in some cases 0,['php'] +680794,how to replace stdstring with vstring i recently learned that since a few years the library libstdc contains vstring also known as versa string which provides the same functionality as stdstring but is apparently more conforming to the c standard i have tried to use vstring as a replacement for stdstring but i have found no easy way to do itis there an easy way to replace stdstring with vstring without changing the libstdc sourcesi am fine with replacing all uses of stdstring within my code by an alias as indicated by the following listing however the problem with this approach is that stdstring is also used internally in some places eg in stdostringstream that means the statements stdostringstream os mystring s osstr no longer works namespace my ifdef glibcxx using string gnu cxx vstringelse using string stdstringendif,['c++'] +680824,how might apache cause duplicate requests i have two rails apps that talk to one another a few times a day requests from app a show up in duplicate or triplicatequadruplicate at app b all outbound and inbound requests are logged the logs show that app a is sending one outbound request and that app b receives that request twice or more during the same secondapp b sits behind apache and an amazon elastic load balanceri am not sure where to look or even what questions to ask to hone in on what might be causing this issue if you need more data i would be happy to provide it,['ruby-on-rails'] +680945,nodejs tailcall optimization possible or not i like javascript so far and decided to use nodejs as my engine partly because of this which claims that nodejs offers tco however when i try to run this obviously tailcalling code with nodejs it causes a stack overflowfunction foox if x 1 return 1 else return foox1 foo10now i did some digging and i found this here it seems to say i should write it like thisfunction foox if x 1 return 1 else yield foox1 foo10however this gives me syntax errors i have tried various permutations of it but in all cases nodejs seems unhappy with something essentially i would like to know the followingdoes or does not nodejs do tcohow does this magical yield thing work in nodejs,['javascript'] +680977,how to specify c11 with thistutils i have a module that needs to be compiled with c11 on gcc and clang that means a stdc11 switch or stdc0x on older compilerspython is not compiled with this switch so thistutils does not include it when compiling moduleswhat is the preferred way to compile c11 code with thistutils,['python'] +681029,deprecation warning moment construction falls back to js date i am using following codes to convert serverside datetime to local time using moment momentmomentwed 23 apr 2014 095451 0formatlfromnowbut i am getting deprecation warning moment construction falls back to js date this is thiscouraged and will be removed in upcoming major release please refer to for more infoit seems i cannot get rid of ithow can i fix itthanks in advance,['javascript'] +681032,how to convert javasqltimestamp to localdate java8 javatime in java 8 how can i convert a timestamp in javasql to a localdate in javatime,['java'] +681298,align lines of text to center in svg i need to output multiple lines of text in svgfor that i am using the following schemetext tspan first line tspan tspan second line tspantextfirst and second line of the text can have different number of characters which can change dynamicallyi want the second line to appear under the first line and text in both of them to be centeredi can make second line appear below the first line by adding dy15 for the second tspani can align the text in each individual tspan by adding textanchormiddle to itbut how to do relative centric alignment of those tspansi tried to use x0 for each tspan but apparently it does not work since each tspan has different width and the rendered text in the shorter line is shifted to the leftis there a way to align centres of 2 tspans of different width using only css andor svg,['css'] +681334,misplaced argument matcher detected here you cannot use argument matchers outside of verification or stubbing in mockito out of the following two test cases in bundleprocessortestjava i am getting below exception although my first test case passes successfullyorgmockitoexceptionsmisusinginvaliduseofmatchersexception misplaced argument matcher detected here at bundletestbundleprocessortestbundlepluginshouldnotbenullbundleprocessortestjava22you cannot use argument matchers outside of verification or stubbing examples of correct usage of argument matchers whenmockgetanyintthenreturnnull dothrownew runtimeexceptionwhenmocksomevoidmethodanyobject verifymocksomemethodcontainsfooalso this error might show up because you use argument matchers with methods that cannot be mocked following methods cannot be stubbedverified finalprivateequalshashcodeat bundletestbundleprocessortestbundleplugincollectionshouldnotbenullbundleprocessortestjava28 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokeunknown sourceplease find below simplified code listing bundlepluginjava package bundleimport javautillistpublic class bundleplugin private final string pluginname private final liststring featurecontent public bundlepluginstring pluginname liststring featurecontent super thispluginname pluginname thisfeaturecontent featurecontent public string getpluginname return pluginname public liststring getfeaturecontent return featurecontent bundleprocessorjavapackage bundleimport javautilarraylistimport javautiliteratorimport javautillistpublic class bundleprocessor public bundleplugin getbundlepluginstring pluginname iteratorstring artifactiterator liststring featurecontent new arrayliststring return new bundlepluginpluginname featurecontent bundleprocessortestjavapackage bundletestimport static orgjunitassertassertnotnullimport static orgmockitomatchersanystringimport static orgmockitomockitomockimport javautiliteratorimport javautillistimport orgjunittestimport bundlebundleprocessorpublic class bundleprocessortest bundleprocessor bundleprocessor new bundleprocessor test public void bundlepluginshouldnotbenull iteratorstring artifactiterator mockiteratorclass bundlebundleplugin bundleplugin bundleprocessorgetbundlepluginanystring artifactiterator assertnotnull bundleplugin test public void bundleplugincontentshouldnotbenull iteratorstring artifactiterator mockiteratorclass bundlebundleplugin bundleplugin bundleprocessorgetbundlepluginanystring artifactiterator liststring featurecontent bundleplugingetfeaturecontent assertnotnull featurecontent how to execute this test without problemedit 1but if i mark the bundleplugincollectionshouldnotbenull test with ignore annotation then first test case passes without any exception,['java'] +681434,why does linqpad dump enum integer values as strings i was using linqpad to test out some enum functions and i did not get integers like i expected when i used dump why did the tolist solve the problemvoid main enumgetvaluestypeofoptionscastintdump enumgetvaluestypeofoptionscastinttolistdumppublic enum options equal lessthan greaterthan,['c#'] +681594,f asynchronous event handlers for wpf similar to cs async and await how does one code an asynchronous wpf or windows forms event handler in f specifically is there any coding pattern that approximates c 5s async and awaithere is a complete c wpf appusing systemusing systemthreadingusing systemthreadingtasksusing systemwindowsusing systemwindowscontrolsclass program static int incrementslowlyint previous threadsleep30 if previous 2 throw new exceptionoops return previous 1 static async void btn clickobject sender routedeventargs e var btn sender as button btnisenabled false try var prev intbtncontent btncontent await taskrun incrementslowlyprev catch exception ex btncontent exmessage finally btnisenabled true stathread static void mainstring args var btn new button content 0 var win new window content btn btnclick btn click new applicationrunwin i am having trouble figuring out what the equivalent would be using f i have made several attempts using combinations of async workflows and async methods it just gets really messy real fast i am hoping there is an easy way that i am just overlookinghere is my starting point which locks up the ui at btncontent incrementslowly prev what do i do nextopen systemopen systemthreadingopen systemthreadingtasksopen systemwindowsopen systemwindowscontrolslet incrementslowly previous threadsleep30 if previous 2 then failwith oops previous 1let btn click sender obj e let btn sender button btnisenabled false try try let prev btncontent int btncontent incrementslowly prev with ex btncontent exmessage finally btnisenabled trueentrypointstathreadlet main let btn new buttoncontent 0 let win new windowcontent btn btnclickaddhandlerroutedeventhandlerbtn click applicationrunwinby the way assume that incrementslowly cannot be modified,['.net'] +681601,principal components analysis using pandas dataframe how can i calculate principal components analysis from data in a pandas dataframe,['python'] +681611,time since first boot up i am developing an android application and hit the problem with determining system first boot up time i mean i need to measure how much time already passed from device first boot up i know about solution with listening for action boot completed and save anything in sharedpreferences but i need another solution because this one does not work for some cases maybe there is any system propertyuse case excerpt from thiscussionthe filename of each file i receive from server includes a timestamptaken from systemcurrentmillisi compare those timestamps in order to determine which file the most current one isnow the user changes system time a few months ahead i am still able to determine the most current file downloaded after user changed system timenow the user changes time back to original setting the file downloaded on step 4 always wins when comparing timestampsthe silver bullet to solve this problem would be a timestamp that counts seconds since first boot after factory reset just like systemclockelapsedrealtime but without reset after each boot unfortunately the answers so far tell us that this silver bullet does not exist however many answers show a great variety of options how to tackle that problem oneworld123 commented each answer how that suited his needs,"['java', 'android']" +681635,conversion from type dbnull to type string is not valid i am receiving this problemconversion from type dbnull to type string is not valid line 501 hfsupemailvalue dtrows0supemaili am very new to this i am not really sure what is the exact problemcould someone guide memany thanks,['asp.net'] +681711,ignore null values when updating the database in hibernate stuck on the same problem is there any method to ignore null values when updating the database in hibernatewhenever you call update of session it will also update the null values found in the objectexample user user new userusersetuserid5usersetusernamemaartenusersetuserfirstnamenull but in database this value is not nullsessionupdate userorsessionsaveorupdate userthe db will now update the user but will set the user firstname to null because it is null in the objectis there any way or method in hibernate to avoid this i do not want to fire a select update query to set the bean that it will ignore the null value,['java'] +681809,nsurlsessiontask never calls back after timeout when using background configuration i am using nsurlsessiondownloadtask with background sessions to achieve all my rest requests this way i can use the same code without have to think about my application being in background or in foreground my backend has been dead for a while and i have taken that opportunity to test how does nsurlsession behave with timeouts to my utter surprise none of my nsurlsessiontaskdelegate callbacks ever gets called whatever timeout i set on the nsurlrequest or on the nsurlsessionconfiguration i never get any callback from ios telling me that the request did finish with timeout that is when i start a nsurlsessiondownloadtask on a background session same behavior happens the application is in background or foreground sample code voidlaunchdownloadtaskonbackgroundsession nsstring sessionidentifier commydomainmyappmysessionidentifier nsurlsessionconfiguration backgroundsessionconfiguration nsurlsessionconfiguration backgroundsessionconfigurationsessionidentifier backgroundsessionconfigurationrequestcachepolicy nsurlrequestreloadignoringcachedata backgroundsessionconfigurationtimeoutintervalforrequest 40 backgroundsessionconfigurationtimeoutintervalforresource 65 nsurlsession backgroundsession nsurlsession sessionwithconfigurationbackgroundsessionconfiguration delegateself delegatequeuensoperationqueue mainqueue nsmutableurlrequest request nsmutableurlrequest requestwithurlnsurl urlwithstring requesttimeoutinterval 30 nsurlsessiondownloadtask task backgroundsession downloadtaskwithrequestrequest task resume voidurlsessionnsurlsession session tasknsurlsessiontask task didcompletewitherrornserror error nslogurlsessiontaskdidcompletewitherror idd error tasktaskidentifier errorhowever when i use the default session then i do get an error callback after 30seconds the timeout that i set at request level sample code voidlaunchdownloadtaskondefaultsession nsurlsessionconfiguration defaultsessionconfiguration nsurlsessionconfiguration defaultsessionconfiguration defaultsessionconfigurationrequestcachepolicy nsurlrequestreloadignoringcachedata defaultsessionconfigurationtimeoutintervalforrequest 40 defaultsessionconfigurationtimeoutintervalforresource 65 nsurlsession defaultsession nsurlsession sessionwithconfigurationdefaultsessionconfiguration delegateself delegatequeuensoperationqueue mainqueue nsmutableurlrequest request nsmutableurlrequest requestwithurlnsurl urlwithstring requesttimeoutinterval 30 nsurlsessiondownloadtask task defaultsession downloadtaskwithrequestrequest task resume voidurlsessionnsurlsession session tasknsurlsessiontask task didcompletewitherrornserror error nslogurlsessiontaskdidcompletewitherror idd error tasktaskidentifier errori cannot seem to find in the documentation anything that suggests that the timeout should behave differently when using background sessions has anyone bumped into that issue as wellis that a bug or a featurei am considering creating a bug report but i usually get feedback much faster on so a few minutes than on the bug reporter six months regards,['ios'] +681816,how to cachedownload google map v2 tile programmatically how to cachedownload google map v2 tile programmatically is it possiblebcos according to this prntscrcom3cyiqf its not possible but as i have seen this link tileprovider using local tilesi thought that if android provides tileprovider class to loaduse tile from the asset than it should be something available for cachingdownloading a tile programmaticallyrun timemy actual requirement is if user is connected with internet at that time he can able to downloadcache a tile of specific area or he can downloadcache visible map in the phone screen only and whenever he goes offline at that time downloaded map should goes to be visiblewhat i have done up till nowi have seen osmdroid lib they provide very good functionality but issue is i want to use google map v2 onlyi have already checked static map api and i have also created one demo for downloading a tile but they return an image with specified zoom level so in that case if i use static map api than user can see only 1 level of map they canat able to zoominout so thatas not goodconclusion i want to know is google map v2 provide any facility to downloadcache a map tiles programmaticallyrun timeeditcan i use google map engine for the same,['android'] +681890,is there any way to release a camera from different activity after acquiring it from a different activity i am developing a flashlight app in which there is a normal flashlight in one activity and strobe light in one activity now i am acquiring the camera in oncreate of flashlight activity but when i am oving to strobe activity i need to release the camera acquired by flashlight activity i dont want to release the camera in onpause of flashlight activity because that would stop the camera even if user presses the home button i want to release the camera only when user goes to strobe activity or else he exits the app by back button also i want to reacquire the camera if the user is coming back to flashlight activity from strobe activity is their anyway to do this,"['java', 'android']" +681906,why do partial methods support ref but not out parameters i was reading up on partial methods since they will become a lot more important in c6 visual studio 2013 update 2 in combination with windows universal projects while reading the documentation i read this weird limitation on the signature of partial methodspartial methods can have ref but not out parametersi do not understand the reason for this limitation since partial methods are basically a normal method with the signature and implementation in different files what technical reason would there be to not support out parameters or any other reason for this limitation for that matter especially since they do support ref parameters which are very similar,['c#'] +681940,webrtc how many stunturn servers do i need to specify i am having trouble with nat traversal and webrtc videostreaming works with some people but not with someone whos behind a student dorm routeri think this should be solved by using a turn server i have done that it still is not working and now i am wondering if the turn server is working at all in consequence i wonder if i can or should set several turn servers and if yes howi found this list of stunturn servers in another thread right now i am setting them like thisvar stun url stunstunlgooglecom19302var turn url turn80 credential homeovar iceservers iceservers stun turnvar pc new rtcpeerconnectioniceserversso my question is basically is it possible to set several stunturn servers should i do it if possible and what would that code look like,['javascript'] +681985,sse intrinsic over int168 to extract the sign of each element i am working with sse intrinsic functions i have an m128i representing an array of 8 signed short 16 bit valuesis there a function to get the sign of each elementedit1something that can be used like thisshort tmpvec8 m128i tmp sgnfor i0i8i tmpm128i i16i tmpvecisgn mm sign epi16tmpof course mm sign epi16 does not exist so that is what i am looking forhow slow it is to do it element by elementedit2desired behaviour 1 for positive values 0 for zero and 1 for negative valuesthanks,['c'] +682101,how to use apigility with an existing zf2 application i have a zf2 application with some modules i would like to allow use my existing modules with apigility inside my application i tried installing these modules with composer require php 533 phpofficephpexcel monologmonolog 1 zendframeworkzenddevelopertools devmaster bjyoungbloodbjyprofiler devmaster radnanrdnrouter 1 bshafferoauth2serverphp devdevelop rwoverdijkassetmanager 13 zfcampuszfapigility 10dev zfcampuszfapigilityprovider 10dev zfcampuszfapigilitydocumentation 10dev zfcampuszfapiproblem 10dev zfcampuszfcontentnegotiation 10dev zfcampuszfcontentvalidation 10dev zfcampuszfhal 10dev zfcampuszfmvcauth 10dev zfcampuszfoauth2 10dev zfcampuszfrest 10dev zfcampuszfrpc 10dev zfcampuszfversioning 10devrequiredev zfcampuszfapigilityadmin devmaster zfcampuszfconfiguration 10dev zfcampuszfapigilitywelcome 10dev zendframeworkzenddevelopertools devmasteri hade these modules in my applicationconfigphp zfapigilityzfapigilityproviderzfapigilitydocumentationassetmanagerzfapiproblemzfmvcauthzfoauth2zfhalzfcontentnegotiationzfcontentvalidationzfrestzfrpczfversioningno exception errors but cannot go to apigility config space i already used apigility from scratch with the zfapigilityskeleton without problems route i tested localprojectapigility or localprojectapigilitydocumentationi suppose i have a problem with routing or layout i use the epmodulelayouts to use differents layouts for each of my modulesthanks for you help,['php'] +682147,webview shouldoverrideurlloading not called for invalid links there are two types of links in the html file1 a normal link like 2 a short link like qtypeshortfor the first kind just load the url for the second kind i should prepend it with a fixed address like before loading the urli am trying to do this with overriding the shouldoverrideurlloading function in webviewclient however this function does not gets called for the second type of link i tried prepending the to the second type of links in the html file then the function does get called when i click the second kind of linki think whats happening is webview will first check if the link is a valid url only if it is valid will the function gets called am i right how can i solve this thanks in advance contentwebview new webviewcontext webviewclient new webviewclient override public void onpagestartedwebview view string url bitmap favicon superonpagestartedview url favicon override public boolean shouldoverrideurlloadingwebview view string url string not in logger logdtag here intent intent new intentintentaction view uriparseurl contextstartactivityintent return true override public void onpagefinishedwebview view string url superonpagefinishedview url if hosted contentwebviewsetvisibilityvisible else summarytextviewsetvisibilityvisible articlelinkbuttonsetvisibilityvisible progressbarsetvisibilityviewgone contentwebviewsetwebviewclientwebviewclient contentwebviewgetsettingssetjavascriptenabledtrue contentwebviewloaddatafullstring texthtml utf8 contentwebviewsetvisibilitygonemore on thisi tried changing contentwebviewloaddatafullstring texthtml utf8tocontentwebviewloaddatawithbaseurl fullstring texthtml utf8 nullthen the function gets calledif i change the short link to a full link in the html string manually then the function also gets calledso i think this is probably what is happening the webview checks if the link url is valid only when the url is valid will the shouldoverrideurlloading be called,['android'] +682181,difference in inheritance in c and java me and my friend who is a java programmer were thiscussing inheritance the conversation almost reached the heights when we got different results for same kind of codemy code in netusing systemusing systemcollectionsgenericusing systemtextnamespace consoledemo class program static void mainstring args base objbasereftoderived new derived objbasereftoderivedshow consolereadline public class base public virtual void show consolewritelineshow from base class public class derived base public void show consolewritelineshow from derived class gives me this result show from base classwhile the code this code in javapublic class base public void show systemoutprintlnfrom base public class derived extends base public void show systemoutprintlnfrom derived public static void mainstring args base obj new derived objshow gives me this result from derivedwhy is net calling the base class function and java calling derived class function i will really appreciate if someone can answer this or just provide a link where i can clear this confusioni hope there is nothing wrong with the code provided,"['c#', 'java']" +682196,convert date to utc using momentjs probably and easy answer to this but i cannot seem to find a way to get momentjs to return a utc date time in milliseconds here is what i am doingvar date txtdateval expires momentutcdateany idea what i am doing wrong,['javascript'] +682197,prevent fixedposition backgroundimage cover from resizing in mobile browsers upon address bar hide sorry for a lack of example on this one but i figure it is easy enough to understandi have a fixed background on my site which is currently implemented like thisbackground position fixed top 0 bottom 0 left 0 right 0 backgroundcolor 28305e backgroundimage urlimagesbackgroundjpg backgroundsize cover mozbackgroundsize cover backgroundposition center center zindex 10div idbackgrounddivthis is great in all browsers so far except for mobile browsers where they hide the address bar upon scrolldown when the address bar is hidden the viewport expands vertically and the backgroundimage jarringly resizes itself on this particular site it will be common for users to scroll up and down and the effect is thistractingany ideas or strategies on working around this or implementing the background in a different wayi could wrap the entire thing in a fixed container and set the overflowy to scroll which prevents the address bar from ever being hidden but i would prefer not to do this google glass cannot scroll through those containers haha would like to demo on there as welli have been trying to think of something that provides backgroundimage cover functionality with some sort of buffer so that it renders larger than the viewport and would not rerender unless the viewport is expanded beyond that buffer but i am not sure how to implement that edit i actually did implement this and detailed the process in an answer below however even with this buffer setup which extends the height of the background image to be 60 pixels larger than the viewport height upon the address bar hiding it still shows a blank backgroundcolor segment that gets revealed and once you stop scrolling it renders the rest of the background imagestill looking for a way to keep the native address bar hide functionality which has now been expanded to ios safari on ipad in ios 8 and also have a fullscreen background image that always fully renders even if the viewport changes height when hiding the address bar starting to wonder if i should just be filing bug reports for all the browsers,"['html', 'css']" +682230,higherorder web frameworksaddons for twistedcyclonetornado web loginuseradmin i am struggling with some architectural choices for a scalable internetofthings applicationi have chosen to base my project on twisted augmented with the cyclone framework to provide many tornado convenances websockets authdecorators securecookies etcusing a twisted core has worked beautifully for me i have numerous ip protocol and hardware interfaces all of which turned out to have great library support inside of twisted and adding new protocols and interfaces to my application are the mostlikely angles i will have project scope creep all with twisted needing very low cpu and providing for very high connection countsmy problems are with secondorder webapp functionalityi pulled in cyclone thinking that with it is auth goodies openid oauth userauth decorators and securecookies it wouldnt take much to implement usersessionadmin functionality in my webapp after the 500 lines of abstracting my database via txmongo and just building user logins it became clear i bothdid not understand how little cyclonetornado bring in the usersessionadmin space and did not understand the amount of code it takes to fill in the gaps if your trying to build a multiuser auth webappa friend pointed me at flask which initially i thought was completely redundant until i found flask plugins the combination of flasklogin and flaskadmin would completely cover my user session and useradmin needs negating me writing what i would guess to be about 2k lines of code unfortunately the flask plugins are all rife with blocking code and calls to blocking libraries i do not see them as compatible with my project even if wsgi containers are used given that the usersession functionality happens with every page load additionally i do not see any short cuts that would allow me to port them to async world without work roughly equal to that of rewriting themmy question is in the python async space hopefully in the twisted space given my protocol needs are there any plugins or alternate frameworks that provide readytogo userloginadmin functionality similar to what is in flasklogin and flaskadminps i have looked at klein as the obvious twisted version of flask but it does not seem to have a plugin ecosystem and i am not finding any strong usersessionadmin therepps by the time i wrote this question i had already written my own crappy userloginsession system so what i am really after is the admin capability automated crud functions on userstyle records including web ui rendering all designed in a twistedasync way i asked about userlogin in the question in case it turn out there is an alreadyintegraded solution such as flasklogin and flaskadmin in which case i would happily drop my code and switch to that,['python'] +682260,how do i run graphx with python pyspark i am attempting to run spark graphx with python using pyspark my installation appears correct as i am able to run the pyspark tutorials and the java graphx tutorials just fine presumably since graphx is part of spark pyspark should be able to interface it correcthere are the tutorials for pysparkhere are the ones for graphxcan anyone convert the graphx tutorial to be in python,['python'] +682340,meteor a how to use template helpers inside element i want to be able to use meteor template helpers to dynamically specify the content of a meta tag it seems like there is no way to do thisif i put the meta tag in a freefloating head element ie not in a template both will be included correctly in the html but i cannot use template helpersif i move the meta to a template and try to render the template within a freefloating head element it complainsand if i move the whole head element into a template now i have a head block nested within the body which is ugly and i suspect invalid html though chrome seems to handle it gracefullyis there a solution,['html'] +682349,javascript fuzzy search that makes sense i am looking for a fuzzy search javascript library to filter an array i have tried using fuzzysetjs and fusejs but the results are terrible there are demos you can try on the linked pagesafter doing some reading on levenshtein thistance it strikes me as a poor approximation of what users are looking for when they type for those who do not know the system calculates how many insertions deletions and substitutions are needed to make two strings matchone obvious flaw which is fixed in the levenshteindemerau model is that both blub and boob are considered equally similar to bulb each requiring two substitutions it is clear however that bulb is more similar to blub than boob is and the model i just mentioned recognizes that by allowing for transpositionsi want to use this in the context of text completion so if i have an array international splint tinder and my query is int i think international ought to rank more highly than splint even though the former has a score higherworse of 10 versus the latters 3so what i am looking for and will create if it does not exist is a library that does the followingweights the different text manipulationsweights each manipulation differently depending on where they appear in a word early manipulations being more costly than late manipulationsreturns a list of results sorted by relevancehas anyone come across anything like this i realize that stackoverflow is not the place to be asking for software recommendations but implicit not anymore in the above is am i thinking about this the right wayediti found a good paper pdf on the subject some notes and excerpts affine editthistance functions assign a relatively lower cost to a sequence of insertions or deletionsthe mongerelkan thistance function monge elkan 1996 which is an affine variant of the smithwaterman thistance function durban et al 1998 with particular cost parametersfor the smithwaterman thistance wikipedia instead of looking at the total sequence the smithawaterman algorithm compares segments of all possible lengths and optimizes the similarity measure it is the ngram approacha broadly similar metric which is not based on an editthistance model is the jaro metric jaro 1995 1989 winkler 19 in the recordlinkage literature good results have been obtained using variants of this method which is based on the number and order of the common characters between two stringsa variant of this due to winkler 19 also uses the length p of the longest common prefixseem to be intended primarily for short stringsfor text completion purposes the mongerelkan and jarowinkler approaches seem to make the most sense winklers addition to the jaro metric effectively weights the beginnings of words more heavily and the affine aspect of mongerelkan means that the necessity to complete a word which is simply a sequence of additions would not thisfavor it too heavily conclusionthe tfidf ranking performed best among several tokenbased thistance metrics and a tuned affinegap editthistance metric proposed by monge and elkan performed best among several string editthistance metrics a surprisingly good thistance metric is a fast heuristic scheme proposed by jaro and later extended by winkler this works almost as well as the mongeelkan scheme but is an order of magnitude faster one simple way of combining the tfidf method and the jarowinkler is to replace the exact token matches used in tfidf with approximate token matches based on the jaro winkler scheme this combination performs slightly better than either jarowinkler or tfidf on average and occasionally performs much better it is also close in performance to a learned combination of several of the best metrics considered in this paper,['javascript'] +682380,how to style css checkboxes with font awesome i am trying to style my checkboxes with font awesome the checkboxes are auto generated from a plugin im using with wordpress i have a mockup of what everything looks like in jsfiddleit seems to be something a bit wrong with my css but i cannot figure out whatdiv idsidebarcardsarchiveul li classcatitem catitem12 label input typecheckbox nameofcardsrarity value12common 223label li li classcatitem catitem14 label input typecheckbox nameofcardsrarity value14epic 40label li li classcatitem catitem11 label input typecheckbox nameofcardsrarity value11free 83label li li classcatitem catitem15 label input typecheckbox nameofcardsrarity value15legendary 36label li li classcatitem catitem13 label input typecheckbox nameofcardsrarity value13rare 84label liuldivhere is the css import urlnetdnabootstrapcdncomfontawesome321cssfontawesomecsidebarcardsarchive ul li liststyle none custom checkboxes inputtypecheckbox thisplaynone to hide the checkbox itself inputtypecheckbox labelbefore fontfamily fontawesomethisplay inlineblockinputtypecheckbox labelbefore contentf096 unchecked icon inputtypecheckbox labelbefore letterspacing 10px space between checkbox and label inputtypecheckboxchecked labelbefore contentf046 checked icon inputtypecheckboxchecked labelbefore letterspacing 5px allow space for check mark,"['html', 'css']" +682422,valgrind gives an error for nearly everything warning client switching stacks i am corrupting memory somehow because my program crashes without error at random placesi am using valgrind with leakcheckfull compiling with o0 g and the very first problem it detects is the first line in int maincout reading file endlwith 5089 warning client switching stacks sp change 0x7ff04f8 0x7feb7de105089 to suppress use maxstackframe4728552 or greater5089 invalid write of size 85089 at 0x41e107 main dgncpp28335089 address 0x7feb7de08 is on thread 1s stackit goes on with5089 invalid read of size 85089 at 0x5de6e10 stdbasic ostreamchar stdchar traitschar stdoperator stdchar traitschar stdbasic ostreamchar stdchar traitschar char const in usrlibx86 64linuxgnulibstdcso60185089 by 0x67aede4 below main libcstartc2605089 address 0x7feb7de08 is on thread 1s stack5089 5089 invalid write of size 85089 at 0x5dbf8f2 stdios baseios base in usrlibx86 64linuxgnulibstdcso60185089 by 0x5e06bff stdbasic ifstreamchar stdchar traitschar basic ifstreamchar const std ios openmode in usrlibx86 64linuxgnulibstdcso60185089 by 0x41e131 main dgncpp28345089 address 0x7feb7e1e8 is on thread 1s stackwhich points to ifstream config filefilenearly every line has an errorwhat causes this,['c++'] +682457,autolayout what creates constraints named uiviewencapsulatedlayoutwidth height my layout constraints are fine in interface builder but an exception occurs at runtime thanks to some part of the framework applying fixed height and width constraints that i really do not want why are they there and how to turn them offthey are the last two constraints shown in the logged list20140426 090258687 bbcnews3205860b unable to simultaneously satisfy constraints probably at least one of the constraints in the following list is one you do not want try this 1 look at each constraint and try to figure out which you do not expect 2 find the code that added the unwanted constraint or constraints and fix it note if youre seeing nsautoresizingmasklayoutconstraints that you do not understand refer to the documentation for the uiview property translatesautoresizingmaskintoconstraints nslayoutconstraint0xbf478a0 uiview0xbf4a3c0height 028125uiview0xbf4a3c0width nslayoutconstraint0xbf47190 uiview0xbf4a3c0leading bnmynewscell landscape0xbf48b10leading nslayoutconstraint0xbf47160 uiview0xbf4a3c0trailing bnmynewscell landscape0xbf48b10trailing nslayoutconstraint0xbf47130 bnmynewscell landscape0xbf48b10bottom uiview0xbf4a3c0bottom nslayoutconstraint0xbf47100 uiview0xbf4a3c0top bnmynewscell landscape0xbf48b10top nslayoutconstraint0xd4c3c40 uiviewencapsulatedlayoutwidth hbnmynewscell landscape0xbf48b10304 nslayoutconstraint0xd4c38a0 uiviewencapsulatedlayoutheight vbnmynewscell landscape0xbf48b10290will attempt to recover by breaking constraint nslayoutconstraint0xbf478a0 uiview0xbf4a3c0height 028125uiview0xbf4a3c0width,['ios'] +682515,same name of two images in different folders of nsbundle i have two images in different folders of nsbundle having the same name it obviously emits a warningwarning multiple build commands for output file usersxappimagepngi know that nsbundle in nsbundle all the folders are groups not actual directories and that files in these groups are still located in the bundles rootin my application i need to have images with the same names in different folders to ease my taskso my questions areis there any way to keep two images in different folder of nsbundle without any warning and also how can i fetch itif no then any problem with this warning when i upload my app to app store i mean my app will be rejected by apple or not,['ios'] +682605,asyncio how can coroutines be used in signal handlers i am developing an application that uses asyncio from python34 for networking when this application shuts down cleanly a node needs to thisconnect from the hub this thisconnect is an active process that requires a network connection so the loop needs to wait for this to complete before shutting downmy issue is that using a coroutine as a signal handler will result in the application not shutting down please consider the following exampleimport asyncioimport functoolsimport osimport signalasynciocoroutinedef ask exitsigname printgot signal s exit signame yield from asynciosleep100 loopstoploop asyncioget event loopfor signame in sigint sigterm loopadd signal handlergetattrsignal signame functoolspartialask exit signameprintevent loop running forever press ctrlc to interruptprintpid s send sigint or sigterm to exit osgetpidlooprun foreverif you run this example and then press ctrlc nothing will happenthe question is how do i make this behavior happen with siganls and coroutines,['python'] +682712,remove all commas dots and lowercase the string with single iteration in my c application i need to remove all dots commas exclamation marks and to lower case the stringso far i figured out i can do it with stderase and stdremove like thisstring content some nice text right here contenterasestdremovecontentbegin contentend contentendcontenterasestdremovecontentbegin contentend contentendcontenterasestdremovecontentbegin contentend contentendstdtransformcontentbegin contentend contentbegin tolowerso my question is can i do this without iterating 4 times throught the string are there better ways to do this with simple c,['c++'] +682713,azure mobile services c would not return child entities i am really hitting a brick wall with the new c based azure mobile services and it is really simple too i cannot for the life of me get the query operation to return child property valuesi have the todo item of the default project modified like thispublic class todoitem entitydata public todoitem thisnumbers new collectiontodoitemnumbersnew listtodoitemnumbers new todoitemnumbersvalue 1 new todoitemnumbersvalue 2 new todoitemnumbersvalue 3 new todoitemnumbersvalue 4 new todoitemnumbersvalue 5 public virtual icollectiontodoitemnumbers numbers get set public string text get set public bool complete get set and then i have the todoitemnumbers class defined like thispublic class todoitemnumbers entitydata private int value public int value get return value set value value id valuetostring public string todoitemid get set in the todoitemcontroller i have overridden the query method like thisprotected override iqueryabletodoitem query return basequeryincludex xnumbersnone of this will return the numbers property when i make a request with fiddlerin a moment of madness i also modified the initialize method of the controller to include thisprotected override void initializehttpcontrollercontext controllercontext baseinitializecontrollercontext mycontext context new mycontext contextconfigurationlazyloadingenabled false contextconfigurationproxycreationenabled false domainmanager new entitydomainmanagertodoitemcontext request servicesnote the lazy loading and proxy creation have both been turned off does anyone know how to beat this simple scenario i am not feeling the good vibes on this oneupdateso as i answered below i was able to get the service to return the data by adding in the expand to the query now however i am really stuck on getting the client to add that parameter to the request it is always just returning the base data var data await appmobileservicegettabletodoitem tolistasyncwould not return the child properties and there is not an include option on the result type,['c#'] +682729,appengine search api vs datastore i am trying to decide whether i should use appengine search api or datastore for an appengine connected android project the only thistinction that the google documentation makes is an index search can find no more than 10 matching documents the app engine datastore may be more appropriate for applications that need to retrieve very large result setsgiven that i am already very familiar with the datastore will someone please help me assuming i do not need 10 resultsare there any advantages to using the search api versus using datastore for my queries per the quote above it seems sensible to use one or the other in my case the end user must be able to search update existing entries and create new entities for example if my app is a bookstore the user must be able to add new books add reviews to existing books search for a specific bookmy data structure is such that the content will be supplied by the end user document vs datastore entity which is cheaper to update etccan they supplement each other datastore and search api whats the advantage why would someone consider pairing the two whats the catchcost,['java'] +682863,refresh only this part of data google maps i am using jpa servlets and jsp for a google map project which i am working onthe jpa entity is called locationslocations entity class has a constructor that takes public locationsdouble latitudedouble longitudestring nameint peoplethislatitude latitude thislongitudelongitudethisnamename thispeoplepeoplei have a class called locationdata whereby i return an arraylist of all the locations in the database alongside their latitudelongitudepeopleavailablenow in a method called getlocation as such arraylist locations new arraylist listlocation locations querygetresultlist this contains all the locationsfor location s locations locationsaddnew locationslatslonsnamespeoplereturn locationsin my servlet i pass the list of locations as such arraylist list ldgetlocationsstring json new gsontojsonlistresponsesetcontenttypetextjsonresponsesetheadercachecontrol nocacheresponsegetwriterwritejsonin my mapjs which is used by jsp get locations from servergetjsonlocations functiondataeachdata functionindex element var marker new googlemapsmarker position new googlemapslatlngelementlat elementlng map map title elementname people elementpeople markerspushmarkerso now having a clear view of how the program runs all the markers appear on the map and i use info window to thisplay the people and name of markerlocation the thing is the number of people could always change in the database since a person can leave one location and go to another how could i always get the people value refreshedread from entity at certain intervals is my design incapable of accommodating this how could i change it to suffice this ability,['java'] +682885,how do i get the default app chooser dialog to appear even if the default app is already chosen already suppose i have a browser appand i would like a settings to be called make default browser to show the dialog chooser even though the current default browser is not my apphow can i make i show the app chooser dialog programmaticallythank youupdate following the lead from michals answer i wrote thisstring url finalvariablesjavelin urlintent i new intentintentaction viewiaddcategoryintentcategory defaultisetdatauriparseurlstartactivityintentcreatechooseri getstringrstringchoose javelinwhile it does show the chooser dialog it does not show the always just once option how can i have that option to showthanks,['android'] +682934,should not the code print 1 1 instead of 4 4 according to a725 and a726 should not the code below print 1 1 instead of 4 4include iostreamenum a a char1 b c underlying type is not fixedint main stdcout sizeofa sizeofa neditfrom a725if the underlying type is not fixed the type of each enumerator is the type of its initializing valuea if an initializer is specified for an enumerator the initializing value has the same type as the expression and the constantexpression shall be an integral constant expression 519,['c++'] +682997,not able to add remote ice candidate in webrtc i am trying to establish a p2p audiovideo connection bw 2 peers peer p1 sends an offer to peer p2 on getting offer p2 does pc new rtcpeerconnectionice pcsetremotedescriptionnew rtcsessiondescriptionmsgoffer onsetremotedescriptionsuccess onsetsessiondescriptionerror function onsetremotedescriptionsuccess consolelogonsetremotedescriptionsuccess called function onsetsessiondescriptionerror consolelogonsetsessiondescriptionerror called pconicecandidate functionevt if evtcandidate consoleloggot local icecandidate evtcandidate send ice candicateevtcandidatesdpmlineindex evtcandidatesdpmid evtcandidatecandidate pconaddstream function evt var remote video documentgetelementbyidremote video remote videosrc windowurlcreateobjecturlevtstream navigatorgetusermedia audio true video true gotstream logerror function gotstreamstream pcaddstreamstream var local video documentgetelementbyidlocal video local videosrc windowurlcreateobjecturlstream pccreateanswerfunctionanswer pcsetlocaldescriptionanswer consolelogcreating answer answersdp signalingchannelsendanswersdp got ice candidateremote ice candidate remote ice candidate is something which was received before offer and hence is buffered and i am trying to add after the answer is ready and other prerequisites are donebut still i am getting error while trying to add remote ice candidatepeer connection object on p2 looks likertcpeerconnection ondatachannel null oniceconnectionstatechange null onremovestream null onaddstream function onsignalingstatechange nullaiceconnectionstate newicegatheringstate gatheringlocaldescription rtcsessiondescriptionsdp v0ao 5043546633484176483 2 in ip4 127001asat0 0aagroupbundle audio videoaamsidsemantic wms iriwtgz87wfi8p6xh94i85suskycu775glzkamaudio 10990 rtpsavpf 1 103 104 0 8 106 105 13 126acin ip4 12217169180aartcp1 in ip4 0aacandidate3022624816 1 udp 21260223 19216814 50063 typ host generation 0aacandidate4205470912 1 tcp 1518280447 19216814 0 typ host generation 0aacandidate494278629 1 udp 1686052607 12217169180 10990 typ srflx raddr 19216814 rport 50063 generation 0aaiceufrag1zcyumc5i0t8mbfjaaicepwdjuisfsika8ezpxdiuzu99tvaafingerprintsha256 be16e67bc818e6b950d931f324853b6326baea6b5df44e0e294716c01d9db7f3aasetupactiveaamidaudioaaextmap1 urnietfparamsrtphdrextssrcaudiolevelaasendrecvaartcpmuxaartpmap1 opus4802aafmtp1 minptime10aartpmap103 isac160aartpmap104 isac320aartpmap0 pcmu80aartpmap8 pcma80aartpmap106 cn320aartpmap105 cn160aartpmap13 cn80aartpmap126 telephoneevent80aamaxptime60aassrc2173896727 cnamepzv2reyyzuw6kufjaassrc2173896727 msidiriwtgz87wfi8p6xh94i85suskycu775glzk fb1b496dffa943cd940a7c68df86d3b3aassrc2173896727 mslabeliriwtgz87wfi8p6xh94i85suskycu775glzkaassrc2173896727 labelfb1b496dffa943cd940a7c68df86d3b3amvideo 10990 rtpsavpf 100 116 117acin ip4 12217169180aartcp1 in ip4 0aacandidate3022624816 1 udp 21260223 19216814 50063 typ host generation 0aacandidate4205470912 1 tcp 1518280447 19216814 0 typ host generation 0aacandidate494278629 1 udp 1686052607 12217169180 10990 typ srflx raddr 19216814 rport 50063 generation 0aaiceufrag1zcyumc5i0t8mbfjaaicepwdjuisfsika8ezpxdiuzu99tvaafingerprintsha256 be16e67bc818e6b950d931f324853b6326baea6b5df44e0e294716c01d9db7f3aasetupactiveaamidvideoaaextmap2 urnietfparamsrtphdrexttoffsetaaextmap3 aasendrecvaartcpmuxaartpmap100 vp890aartcpfb100 ccm firaartcpfb100 nackaartcpfb100 nack pliaartcpfb100 googrembaartpmap116 red90aartpmap117 ulpfec90aassrc2118221653 cnamepzv2reyyzuw6kufjaassrc2118221653 msidiriwtgz87wfi8p6xh94i85suskycu775glzk a735b317175240fa96df511c0febb55eaassrc2118221653 mslabeliriwtgz87wfi8p6xh94i85suskycu775glzkaassrc2118221653 labela735b317175240fa96df511c0febb55eatype answer proto rtcsessiondescriptiononaddstream function evt arguments nullcaller nulength 1name prototype object proto function empty function scopeondatachannel nullonicecandidate function evt oniceconnectionstatechange nullonnegotiationneeded nullonremovestream nullonsignalingstatechange nullremotedescription rtcsessiondescriptionsdp v0ao 8847796014807563532 2 in ip4 127001asat0 0aagroupbundle audio videoaamsidsemantic wms na7tunpnyzpmg56ijulddf8omug8v5ndtjkkamaudio 1 rtpsavpf 1 103 104 0 8 106 105 13 126acin ip4 0aartcp1 in ip4 0aaiceufragmfl29tarmkrbn9faaicepwdmy1dzo1yjne4brcqgkn1o3iaaiceoptionsgoogleiceaafingerprintsha256 be16e67bc818e6b950d931f324853b6326baea6b5df44e0e294716c01d9db7f3aasetupactpassaamidaudioaaextmap1 urnietfparamsrtphdrextssrcaudiolevelaasendrecvaartcpmuxaacrypto1 aes cm 128 hmac sha1 80 inlinegtdsmkygu0avidv2m6ko25w5dxoknoxfnrbykaartpmap1 opus4802aafmtp1 minptime10aartpmap103 isac160aartpmap104 isac320aartpmap0 pcmu80aartpmap8 pcma80aartpmap106 cn320aartpmap105 cn160aartpmap13 cn80aartpmap126 telephoneevent80aamaxptime60aassrc702054304 cnameqjwj3eyxhsosghaassrc702054304 msidna7tunpnyzpmg56ijulddf8omug8v5ndtjkk 054d6450034f48ca85dc3a843c7f7554aassrc702054304 mslabelna7tunpnyzpmg56ijulddf8omug8v5ndtjkkaassrc702054304 label054d6450034f48ca85dc3a843c7f7554amvideo 1 rtpsavpf 100 116 117acin ip4 0aartcp1 in ip4 0aaiceufragmfl29tarmkrbn9faaicepwdmy1dzo1yjne4brcqgkn1o3iaaiceoptionsgoogleiceaafingerprintsha256 be16e67bc818e6b950d931f324853b6326baea6b5df44e0e294716c01d9db7f3aasetupactpassaamidvideoaaextmap2 urnietfparamsrtphdrexttoffsetaaextmap3 aasendrecvaartcpmuxaacrypto1 aes cm 128 hmac sha1 80 inlinegtdsmkygu0avidv2m6ko25w5dxoknoxfnrbykaartpmap100 vp890aartcpfb100 ccm firaartcpfb100 nackaartcpfb100 nack pliaartcpfb100 googrembaartpmap116 red90aartpmap117 ulpfec90aassrc846853801 cnameqjwj3eyxhsosghaassrc846853801 msidna7tunpnyzpmg56ijulddf8omug8v5ndtjkk c0dde33cf42247749f7b65cec136e107aassrc846853801 mslabelna7tunpnyzpmg56ijulddf8omug8v5ndtjkkaassrc846853801 labelc0dde33cf42247749f7b65cec136e107atype offer proto rtcsessiondescriptionsignalingstate stable proto rtcpeerconnection the error that i get isfailed to add ice candidate error processing ice candidate,['javascript'] +683045,how to generate unique id with nodejs function generatecount var founded false sym abcdefghijklmnopqrstuvwxyz1234567890 str whilefounded forvar i 0 i count i str symparseintmathrandom symlength basegetidstring functionerr res ifreslength founded true how to do it return strhow to set a variable value with database query callback how i can do itthanks in advance,['javascript'] +683070,how to check whether a driver is installed i am working on a vpn project i have a small doubt regarding tuntaphow do i programmatically checkdetect if a tuntap driver is installed on a system in c,"['c#', '.net']" +683079,maven compile gives cannot find symbol for a class sitting in the same app it is a while since i met such puzzling issue i am having a class that references another one sitting in another package in the same application that is not in another jar archive file the including class is learnintouchrestsrctestjavacomthalasoftlearnintouchrestacceptanceabstractcontrollertestjavathe included class ishomestephanedevjavaprojectslearnintouchrestsrctestjavacomthalasoftlearnintouchrestconfigwebtestconfigurationjavaunder eclipse there is no issue and no compilation error in the editorbut running a maven build gives a compilation errormvn clean testcompile pacceptanceerror failed to execute goal orgapachemavenpluginsmavencompilerplugin31testcompile defaulttestcompile on project learnintouchrest compilation failure compilation failureerror homestephanedevjavaprojectslearnintouchrestsrctestjavacomthalasoftlearnintouchrestacceptanceabstractcontrollertestjava1646 cannot find symbolerror symbol class webtestconfigurationerror location package comthalasoftlearnintouchrestconfigerror homestephanedevjavaprojectslearnintouchrestsrctestjavacomthalasoftlearnintouchrestacceptanceabstractcontrollertestjava216 cannot find symbolerror symbol class webtestconfigurationhere is the code of the including classrunwithspringjunit4classrunnerclasstransactionalwebappconfigurationcontextconfigurationclasses applicationconfigurationclass websecurityconfigclass webconfigurationclass webtestconfigurationclasspublic abstract class abstractcontrollertest this abstract test class is sitting under the acceptance test directory which mandates the explicit activation of the pacceptance profile when running the maven commandthe default profile does not run this acceptance test but only some integration testone thing to note is that this abstract class looks like the one abstract class used in the integration testhere is the including class of the integration testimport comthalasoftlearnintouchrestconfigwebtestconfigurationrunwithspringjunit4classrunnerclasswebappconfigurationcontextconfigurationclasses applicationconfigurationclass websecurityconfigclass webconfigurationclass webtestconfigurationclass transactionalpublic abstract class abstractcontrollertest as you can see it looks much like the other onei can also give the pomxml file content if it can helpprofiles profile idrestid activation activebydefaulttrueactivebydefault activation properties testsourcedirsrctestjavacomthalasoftlearnintouchresttestsourcedir properties profile profile idacceptanceid activation activebydefaultfalseactivebydefault activation properties testsourcedirsrctestjavacomthalasoftlearnintouchrestacceptancetestsourcedir properties profileprofilesif you have any clue on this one it would be greatly appreciated,['java'] +683144,determining if a number is either a multiple of ten or within a particular set of ranges i have a few loops that i need in my program i can write out the pseudo code but i am not entirely sure how to write them logicallyi need if num is a multiple of 10 do this if num is within 1120 3140 5160 7180 91100 do this else do this this part is for 110 2130 4150 6170 8190this is for a snakes and ladders board game if it makes any more sense for my questioni imagine the first if statement i will need to use modulus would if num 10010 be correctthe second one i have no idea i can write it out like if num 10 num is 21 etc but there has to be something smarter than that,['c++'] +683163,multiple php on apache centos how can i get multiple php versions running on centos 65 at the same time heres howrequirementscentos 65 possible works with 66 and 7 apache apache2215 possible works with other versions this guide installs and uses fastcgi see the comments for alternative installationphpfarmthis install was done this way so it would be compatable with iredmailyou can install iredmail on a server with this set upstep 1installing phpfarmyum install gcc libxml2devel openssldevel bzip2devel curldevel libjpegdevel freetypedevel icu libicudevel gc postgresqldevel aspelldevel git y cd opt git clone phpfarm cd phpfarmsrc cd optphpfarmsrcfor each version of php you want run this however if you want custom modules such as mysql support skip this and see the part just below it compilesh 531 compilesh 533 compilesh 5511if you get compile errors reboot and trycompilesh 531 againthis worked for me when i ran into this problemmysql module supportsteps for getting mysql support and other modules for custom phpfarm install of php version 5514 these instructions work for any version just rename 5514 to what ever like 543 you will of course need a mysql server to connect to to make use of the mysql module within phpthese steps need to be completed in this orderstep 1aensure you have these paths and the date time is correct i did this as root you should have the datetimezone you intend to usecd optphpfarmsrcvi customphpinidatetimezoneamericahalifaxinclude pathoptphpfarminstphpversionpearphpstep 1bensure you have these paths and the date time is correctcd optphpfarmsrcvi defaultcustomphpinidatetimezoneamericahalifaxinclude pathoptphpfarminstphpversionpearphpstep 1c pay special attention to this linewithconfigfilepathoptphpfarminstphp5511lib it will need to be adjusted for the version you are working with as root vi customoptions5514shbinbashgcovenablegcovconfigoptionsthisabledebug withconfigfilepathoptphpfarminstphp5511lib enableshorttags withpear enablebcmath enablecalendar enableexif enableftp enablembstring enablepcntl enablesoap enablesockets enablewddx enablezip withzlib withgettext enablepdo withpdomysql enablecgi enablejson withcurl withopenssl enableopenssl withmysql enablemysql gcovstep 1d now compile as root phpfarm will automatically look for a file named customoptions5514sh when you compile 5514 or any other version with of course respective version numberscompilesh 5514later when you check out your web page with the phpinfo function you will see support for these modules and different configure command text on the page if these steps are not completed in order you may have to do it again in order to do this again first remove the files from the src folder and the inst folderrm rf optphpfarminstphp5514rm rf optphpfarmsrcphp5514the rm will remove the folder and the rf stands for r recursive and f forceref man pagesrm1htmlif you have errors check with this site there are others but i found this one usefulreference for the mysql and module supportissue activating a php extension using php farmphp compile errorsstep 2adding phpfarm to your profilesadd this to the bottom of bashrc for root and nonroot user the bashrc file can be found in the users root folder or cd then ls all and you should see itpathpathoptphpfarminstbinoptphpfarminstcurrentbinalso execute this in terminal after you have added it to the bashrc files for root and nonroot userexport pathpathoptphpfarminstbinoptphpfarminstcurrentbinnow exit the terminal and log back in try this commandswitchphpfarm 5511you should be able to switch back and forth between diff php versions roottest joe switchphpfarm 5511setting active php version to 5511php 5511 cli built may 17 2014 220131 debugcopyright c 19972014 the php groupzend engine v250 copyright c 19982014 zend technologiesroottest joeadd the repo for centosrhel 6 64 bit x86 64cd tmprpm uvh 64rpmstep 3install the yumsyum install php phpcli mod fastcginoteat this point if you try to run the switchphpfarm 5511 it wont work properly but thats ok we will still be able to run multiple websites with different versions of phpstep 4ensure your cgibin is created and files are configured cd varwif the cgibin isnat already here create it mkdir cgibinfor each version of php you intend to use make one of these files replace the ending with the version number vi varwcgibinphpfastcgi5511step 5inside the file phpfastcgi5511binbashphprcoptphpfarmsrcphp5511phpinidevelopmentphp fcgi children4php fcgi max requests10export phprcexport php fcgi childrenexport php fcgi max requestsexec optphpfarminstbinphpcgi5511the first line phprcoptphpfarmsrcphp5511phpinidevelopmenttells you witch phpini to use this is different in ubuntu the last lineexec optphpfarminstbinphpcgi5511also needs to be changed for each particular version i am not sure what it does but i do know it needs to be changedstep 6enable fastcgi files to be executable for apacheapache user and groupexample 1roottest joe chown apacheapache varwcgibinphpfastcgi5511roottest joe chmod x varwcgibinphpfastcgi5511example 2roottest joe chown apacheapache varwcgibinphpfastcgi533roottest joe chmod x varwcgibinphpfastcgi533example 3roottest joe chown apacheapache varwcgibinphpfastcgi531roottest joe chmod x varwcgibinphpfastcgi531step 7editing the httpdconf filehereas what you need for the etchttpdconfhttpdconf filefirst find anamevirtualhost 80a and use this as a starting pointthe aa means the line is commented out uncomment this line by deleting the it should now look like this namevirtualhost 80this will allow multiple virtual host to operate on apache by their servername in each virtual host reference i left some lines commented to show you what you can do without make sure the bottom of the etchttpdconfhttpdconf looks like thisvirtualhost 80 servername test1com serveradmin documentroot varwhtmltest1 scriptalias cgibin varwcgibin directory varwhtmltest1 options indexes followsymlinks execcgi addhandler php5fastcgi php action php5fastcgi cgibinphpfastcgi5511 allowoverride all order allowdeny allow from all directoryvirtualhostvirtualhost 80 servername test2com serveradmin documentroot varwhtmltest2 scriptalias cgibin varwcgibin directory varwhtmltest2 options indexes followsymlinks execcgi addhandler php5fastcgi php action php5fastcgi cgibinphpfastcgi533 allowoverride all order allowdeny allow from all directoryvirtualhostvirtualhost 80 servername test3org serveradmin documentroot varwhtmltest3 scriptalias cgibin varwcgibin directory varwhtmltest3 options indexes followsymlinks execcgi addhandler php5fastcgi php action php5fastcgi cgibinphpfastcgi531 allowoverride all order allowdeny allow from all directoryvirtualhostvirtualhost 80 servername test4net serveradmin documentroot varwhtmltest6virtualhoststep 8editing the etchosts file here is what you need in the etchosts file127001 localhost test1com test2com test3org test4net1 localhost localhostlocaldomain localhost6 localhost6localdomain6step 9now restart your serverservice httpd restartstep 10testingif you add phpinfo to each of the indexphp sites you will notice that all the php versions will be different also the last one test4net will go with the default for centos also note that test3org and test4net are not coms but will still work in the future i plan to make a guide for the phpfarm files so you can install with mysql support this was another issue i ran into if you notice some errors in this or have difficult making it work please comment and i will get to it as soon as i can,['php'] +683283,determining bss size on object file wikipedia mentions that the bss section typically includes all uninitialized variables declared at file scope given the following fileint uninitint main uninit 1 return 0when i compile this to an executable i see the bss segment filled properly gcc prog1c o prog1 size prog1text data bss dec hex filename15 552 8 1675 68b prog1however if i compile it as an object file i do not see the bss segment i would expect it to be 4 gcc c prog1c size prog1o text data bss dec hex filename 72 0 0 72 48 prog1ois there something obvious i am missingi am using gcc version 481,['c'] +683300,getting error improper advertising identifier idfa usagewhen i am validating my app in xcode 5 when validating my app i get an error sayingimproper advertising identifier usage your app contains the advertising identifier idfa api but you have not respecting the limit ad tracking setting in iosi have check yes on the prepare for upload page for advertising identifieri am using revmob ads and flurry analytics in my appcocos2dx projecthow to fix this issue i have tried a lot but not succeedi have use below code into appdelegate but no luck nsstring identifierforadvertising ifasidentifiermanager sharedmanager isadvertisingtrackingenabled nsuuid idfa asidentifiermanager sharedmanager advertisingidentifier return idfa uuidstring return nil,"['ios', 'objective-c']" +683306,return null for missing values in an in list i have a table like this id val 1 abc 2 def 5 xyz 6 foo 8 barand a query like select id val from tab where id in 12345which returns id val 1 abc 2 def 5 xyzis there a way to make it return nulls on missing ids that is id val 1 abc 2 def 3 null 4 null 5 xyzi guess there should be a tricky left join with itself but cannot wrap my head around itedit i see people are thinking i want to fill the gaps in a sequence but actually what i want is to substitute null for the missing values from the in list for example this select id val from tab where id in 11008200should return id val 1 abc100 null 8 bar200 nullalso the order does not matter muchedit2 just adding a couple of related linkshow to select multiple rows filled with constantsis it possible to have a tableless select with multiple rows,"['mysql', 'sql']" +683325,postgresql query between date ranges i am trying to query my postgresql db to return results where a date is in certain month and year in other words i would like all the values for a monthyear the only way i have been able to do it so far is like thisselect user id from user logs where login date between 20140201 and 20140228problem with this is that i have to calculate the first date and last date before querying the table is there a simpler way to do thisthanks,['sql'] +683420,adb s emu geo fix not works without using telnet my app works on google apis 17 i want to set the gps location after an emulator is being launchedi try to this follow howtoemulategpslocationintheandroidemulator1st get the serials number of the emulatoradb devicesemulator542nd runadb s emulator54 emu geo fix 1214961236714487 3124010934431376there are no warnings and errors i am programming on windows7it not work however when i send gps info manually in eclipseadt226 it works my app can locate the location correctly what did eclipse do how to make the adb command work thanks,['android'] +683490,how to animate layout from top to 300dp of screen vice versa in android requirementi can translate layout base on toydelta100 or toydelta50 etcbut i want to animate layout only in 300dp heightslide downxmltranslate xmlnsandroid androidduration500 androidfromydelta0 androidtoydelta100 slide upxmltranslate xmlnsandroid androidduration500 androidfromydelta100 androidtoydelta0 java code animationanimation animation animationutilsloadanimationgetactivitygetapplicationcontextranimslide downanimationsetanimationlistenernew animationlistener override public void onanimationstartanimation animation todo autogenerated method stub override public void onanimationrepeatanimation animation todo autogenerated method stub override public void onanimationendanimation animation todo autogenerated method stub i can hide layout after animation completion mockupproblemhow to do base on 300dp heightplease help me for this problemthank you,['android'] +683511,mapping pixel formats from cvpixelbuffer to their equivalent v4l i need to map a range of osx corevideo pixel formats as enumerated in cvpixelbufferh to their equivalents in v4l for example kcvpixelformattype 24rgb would map to v4l2 pix fmt rgb24 i have tried to match using fourcc but the definitions for osx and v4l do not match besides inspecting their exact layout and matching them manually is there a way programatically or an information table that will show me for example where kcvpixelformattype 422ypcbcr8 would map to,"['c++', 'objective-c']" +683579,javaxnetsslsslexception during amazon s3 multipart upload i am using simpl3r a simple high level android api for robust and resumable multipart file uploads using the amazon s3 service to upload media files to my bucketon some uploads i am getting a sslexception error heres the code where the exception is thrownmy class is a subclass of an intentservice as per the simpl3r exampleoverrideprotected void onhandleintentintent intent string filepath intentgetstringextraarg file path final string s3objectkey intentgetstringextraarg object key file filetoupload new filefilepath string s3bucketname getstringrstrings3 bucket final string msg uploading s3objectkey create a new uploader for this file uploader new uploaderthis s3client s3bucketname s3objectkey filetoupload listen for progress updates and broadcastnotify them appropriately uploadersetprogresslistenernew uploadprogresslistener override public void progresschangedprogressevent progressevent long bytesuploaded int percentuploaded notification notification buildnotificationmsg percentuploaded nmnotifynotify id upload notification broadcaststates3objectkey percentuploaded msg broadcastnotify that our upload is starting notification notification buildnotificationmsg 0 nmnotifynotify id upload notification broadcaststates3objectkey 0 msg try string s3location uploaderstart initiate the upload broadcaststatedones3objectkey s3location file successfully uploaded to s3location catch uploaditerruptedexception uie broadcaststateerrors3objectkey user interrupted catch exception e eprintstacktrace broadcaststateerrors3objectkey error egetmessage heres the stack trace0428 101835482 2823628304orgdornads3test iamazonhttpclienti1 unable to execute http request write error ssl0x5c7c7760 io error during system call connection reset by peer javaxnetsslsslexception write error ssl0x5c7c7760 io error during system call connection reset by peer at orgapacheharmonyxnetproviderjssenativecryptossl writenative method at orgapacheharmonyxnetproviderjsseopensslsocketimplssloutputstreamwriteopensslsocketimpljava706 at comamazonawsorgapachehttpimplioabstractsessionoutputbufferwriteabstractsessionoutputbufferjava169 at comamazonawsorgapachehttpimpliocontentlengthoutputstreamwritecontentlengthoutputstreamjava119 at comamazonawsorgapachehttpentityinputstreamentitywritetoinputstreamentityjava102 at comamazonawshttprepeatableinputstreamrequestentitywritetounknown source at comamazonawsorgapachehttpentityhttpentitywrapperwritetohttpentitywrapperjava98 at comamazonawsorgapachehttpimplcliententityenclosingrequestwrapperentitywrapperwritetoentityenclosingrequestwrapperjava108 at comamazonawsorgapachehttpimplentityentityserializerserializeentityserializerjava122 at comamazonawsorgapachehttpimplabstracthttpclientconnectionsendrequestentityabstracthttpclientconnectionjava271 at comamazonawsorgapachehttpimplconnmanagedclientconnectionimplsendrequestentitymanagedclientconnectionimpljava197 at comamazonawsorgapachehttpprotocolhttprequestexecutordosendrequesthttprequestexecutorjava257 at comamazonawshttpprotocolsdkhttprequestexecutordosendrequestunknown source at comamazonawsorgapachehttpprotocolhttprequestexecutorexecutehttprequestexecutorjava125 at comamazonawsorgapachehttpimplclientdefaultrequestdirectortryexecutedefaultrequestdirectorjava717 at comamazonawsorgapachehttpimplclientdefaultrequestdirectorexecutedefaultrequestdirectorjava522 at comamazonawsorgapachehttpimplclientabstracthttpclientexecuteabstracthttpclientjava906 at comamazonawsorgapachehttpimplclientabstracthttpclientexecuteabstracthttpclientjava805 at comamazonawshttpamazonhttpclientexecutehelperunknown source at comamazonawshttpamazonhttpclientexecuteunknown source at comamazonawsservicess3amazons3clientinvokeunknown source at comamazonawsservicess3amazons3clientuploadpartunknown source at comreadystatesoftwaresimpl3ruploaderstartuploaderjava162 at orgdornads3testserviceuploadserviceonhandleintentuploadservicejava96 at androidappintentserviceservicehandlerhandlemessageintentservicejava65 at androidoshandlerthispatchmessagehandlerjava99 at androidoslooperlooplooperjava137 at androidoshandlerthreadrunhandlerthreadjava60the exception is not caught by my exception clause meaning that the app is stuck in a uploading state that never endsany ideas,['android'] +683602,how this simple javascript script actually works might be scoping can anybody break down for me into steps how this it looks simple in the first place is interpreted by the browservar a 1function b a 10 function a balertait will bring 1 if i would change a function name to anything else etcvar a 1function b a 10 function m balertait will alert 10,['javascript'] +683730,mysql concatenating all columns why can we not concatenate in mysql using the keywordselect concat from tableor select group concat from tableis there any other way we could access values in a column without explicitly using the columns name,['mysql'] +683760,java config for spring interceptor where interceptor is using autowired spring beans i want to add spring mvc interceptor as part of java config i already have a xml based config for this but i am trying to move to a java config for interceptors i know that it can be done like this from the spring documentationenablewebmvcconfigurationpublic class webconfig extends webmvcconfigureradapter override public void addinterceptorsinterceptorregistry registry registryaddinterceptornew localeinterceptor but my interceptor is using a spring bean autowired into it like followspublic class localeinterceptor extends handlerinterceptoradaptor autowired isomeservice someservice the someservice class looks like followsservicepublic class someservice implements isomeservice i am using annotations like service for scanning the beans and have not specified them in the configuration class as beanas my understanding since java config uses new for creating the object spring will not automatically inject the dependencies into it how can i add the interceptors like this as part of the java config,['java'] +683806,how to write css fallbacks for vh vw can anyone explain how fallbacks work in css i am trying to set it up for vh and vw and clearly i am not getting ithere is my attempted solution which does not work the height property is taken every timecsswebkitheight 52vhmozheight 52vhmsheight 52vhoheight 52vhheight 41px the fallback,['css'] +683881,windowopen event listeners not working in android 442 i have a phonegap app that uses the inappbrowser to load the google login experience as such i need an event listener that detects when the browser changes location the setup below works perfectly fine on all android versions except for 442 as best as i can tell the event listener fires and all is goodhowever on android 442 i cannot seem to get any event listeners to fire for the window loadstart onload onscroll etc nothing seems to fire cannot seem to find any solutions on google or stackoverflow unfortunatelynot sure what additional information is neededuseful but happy to provide anythingvar auth window windowopenauth url blank locationnotoolbarnoauth windowaddeventlistenerloadstart functionevent alertblahupdatei have been able to get the listener to fire by backing out of inappbrowser and opening it again i have no clue why it would work in this case but not otherwise though any help here would be very much appreciated,"['javascript', 'android']" +683948,post data to cgi file using xmlhttprequest causes badheader when i try posting data to my cgi file my cgi file says the actual post data is invalid i am using htmljavascript for the front end and python for the backend worksform namelogin actioncgibinregisterpy methodpostusernameinput typetext nameusernamebrpasswordinput typepassword namepasswordbrconfirm passwordinput typepassword nameconfirmpasswordbrformhowever this causes the page to refresh i am trying to avoid this and have text thisplay within the same pagewithout reloading hence i have chosen to use an xmlhttprequest to asynchronously process this eventthis is what i want to achievescriptfunction validateloginvar username documentgetelementbyidusernamevaluevar password documentgetelementbyidpasswordvalueif usernamelength 0 passwordlength 0 documentalertthe username or password cannot be blank return var xmlhttp if windowxmlhttprequest code for ie7 firefox chrome opera safari xmlhttpnew xmlhttprequest else code for ie6 ie5 xmlhttpnew activexobjectmicrosoftxmlhttp xmlhttponreadystatechangefunction if xmlhttpreadystate4 xmlhttpstatus200 documentgetelementbyidresulttextinnerhtmlxmlhttpresponsetext else if xmlhttpreadystate4 documentwritexmlhttpstatus xmlhttpstatustext xmlhttpopenpostcgibinlogincgitruexmlhttpsetrequestheadercontenttypeapplicationxwformurlencoded charsetutf8xmlhttpsendusername username password passwordscriptcgi fileusrbinpythonimport cgifrom dbmanager import openconnectionfrom passlibhash import sha256 crypts contenttype texthtmlnform cgifieldstorageusername formusernamevaluepassword formpasswordvaluemessage nonei am getting an error in python stating bad headerfieldstoragenone nonei do not get this error when i do it the first way but the second way is giving me this error i need it to work the second way,"['javascript', 'python', 'html']" +684298,store clientserver string filtering directives for realtime use i have an application that grabs rows from external apis and sends them to the browser without storing in the database the database only holds the urls for the api requeststhe rows received from the apis needs to be filtered per row either serverphp or client side and the filters need to be stored in the database a filter for a row can for example be substring or replacei assume you never want to have javascriptphp code in the database but how else could this be done are there any appropriate javascript solutionswhat i want in my database table is this row api url filterrow 1 apicomget datastring filter here row 2 apicomget more datastring filter here where the filter contains instructions on how to filter the string in the api result,"['javascript', 'php']" +684320,jsonnet serialization on an object with a member of type stream hopefully this is an easy fix that i have overlooked i have an object passed into an event handler that i want to serialize that object using jsonnet like so public void oneventieventobject foo serialize foo to stringthisk here var data jsonconvertserializeobjectfoo formattingindentedit appears that one or more of foos members are streams i already recognize that streams are not serializable since they are an abstraction over data and not the data itself this makes sensei do not know how to serialize this object anyway by eithera converting the streams into data and serializing thatb ignoring the streams and serialize the remaining membersone big caveat to this is that i do not have access to ieventobject or its implementations so i cannot mark up any of these objects with attribute flagsthe only solution i have come up with is to wrap this object in my own class mark it up appropriately and serialize that later i would deserialize back into my own class and convert it into the original object i do not like this approach since it involves an extra object and conversion step and would like to avoid it if possible,"['c#', '.net']" +684391,google chrome is unable to apply opacity transition on a 3d transformed element i have the following markupdiv classcube trigger cuberotate div classface init f zdiv div classface init l ydiv div classface init b zdiv div classface init r ydiv div classface init you xdiv div classface init d xdivdivwhich resembles a 3d cube every face is rotated and translated onto their proper position and i let the cube rotate using an animation on the faces parent heres the related css of itcube position absolute cursor pointer width 120px height 120px top 0 left 0 transformorigin 50 50 transformstyle preserve3dface position absolute width 120px height 120px border 0px solid f background c82 transformorigin 50 50 opacity 1 padding 0px webkittouchcallout none userselect none transition all 05s easeout i wanted to make the cube appear one face at time on document ready so i just threw in some javascript basically an interval every 500ms which simply removes the init class which overrides the opacity 1 value on the face classfunction use strict some selectors and shit var face facefirst speed 500 timer null documentreadyfunction start showing faces timer windowsetintervalfunction var next facenext faceremoveclassinit ifnexthasclassface windowclearintervaltimer face next speed jquery and the additional css belowfaceinit opacity 0in an ideal world this code should work however i am facing a problem on google chrome the opacity does not transition back to 1 after the class is removed keeping the cube completely invisible if you right click and inspect it becomes visible againcuriously on safari which is also a webkitbased browser this does not happen at all and the faces show one at time as they are supposed to doi tried to use both animate from jquery and also tried the jquery plugin transitnow safari and chrome are not supposed to behave in the same way or are there major differences under the hood despite the rendering engine being the sameis it something i did wrong there is a workaround for thisheres my penthanksupdatei have tried obviously on chrome on my mac and also on windows 7 and they both behave the same way different machines alsoalso tried firefox which works seamlessly like safari apart from the rotating animation which is not happening but i kept firefox out of consideration as it is a different browseradditional updatechrome on mobile devices both ios and android are working and behaving like safari on desktopanother updateafter playing around around i have found probably it is a browser bug chrome canary works fine as expectedi posted this on facebook where i have got a couple of good workarounds from a developer which i found quite creative the first one involved in have a rgba backgroundcolor and make the alpha change instead of having the transition on the opacity the second one involved a bit of javascript coding forcing the browser repaint the faces at each frame i am starting a bounty to see what stackoverflow can do here,['css'] +684597,pgconnectionbad fe sendauth no password supplied when i attempt to run rake test on a local postgres database it throws the above exceptionhere is my pg hbaconf file database administrative login by unix domain socket local all postgres peer type database user address method local is for unix domain socket connections onlylocal all username peerlocal myapp dev myapp md5local myapp test myapp md5local myapp prod myapp md5local all all peer ipv4 local connectionshost all all 12700132 md5 ipv6 local connectionshost all all 1128 md5 allow replication connections from localhost by a user with the replication privilegelocal replication postgres peerhost replication postgres 12700132 md5host replication postgres 1128 md5and here is the relevant section from my databaseymltestadapter postgresqldatabase myapp testpool 5timeout 50host localhostusername usernamepasswordin the real databaseyml username is replaced with my actual user name that i am logged in as since the authentication method is defined as peer no password should be requiredi have also taken care to restart postgres sudo u postgres pg ctlcluster 93 main restartwhat else am i missing here,['ruby-on-rails'] +684684,android studio quick documentation always fetching documentation i just move to android studio from eclipsei found that it always shows fetching documentation when i use quick documentationctrlqhow to solve thisi download documentation for api19still problem,['android'] +684774,get row before select query i have a table called mytable the columns aretime stamp datetime pktime stamp ms int pkdata1 intdata2 intdata3 intdata4 int data5 intdata6 intcycle intname varstringi want to order by time stamp and time stamp ms i know how to do this from another question and then each time cycle reaches 1 i want to get the time stamp and time stamp ms from the previous row cycle is 1234n means it will always increment by 1this table will problably have millions and millions of rowsalso no phpthere is a sample of my tabletime stamp time stamp ms d1 d2 d3 d4 d5 d6 cycle name 20140424 090937 765 5 4 3 2 1 123 1 name20140424 090937 845 5 4 3 2 1 123 2 name20140424 090937 925 5 4 3 2 1 123 3 name20140424 090938 5 5 4 3 2 1 123 4 name20140424 090938 85 5 4 3 2 1 123 5 name20140424 090938 165 5 4 3 2 1 123 6 name20140424 090938 245 5 4 3 2 1 123 7 name20140424 090938 325 5 4 3 2 1 123 8 name20140424 090938 405 5 4 3 2 1 123 9 name20140424 090938 485 5 4 3 2 1 123 10 name20140424 090938 565 5 4 3 2 1 123 11 name20140424 090938 645 5 4 3 2 1 123 12 name20140424 090938 725 5 4 3 2 1 123 13 name20140424 090938 805 5 4 3 2 1 123 1 name20140424 090938 885 5 4 3 2 1 123 2 name20140424 090938 965 5 4 3 2 1 123 3 name20140424 090939 45 5 4 3 2 1 123 4 name20140424 090939 125 5 4 3 2 1 123 5 name20140424 090939 205 5 4 3 2 1 123 6 name20140424 090939 285 5 4 3 2 1 123 1 name20140424 090939 365 5 4 3 2 1 123 2 name20140424 090939 445 5 4 3 2 1 123 3 name20140424 090939 525 5 4 3 2 1 123 4 name20140424 090939 605 5 4 3 2 1 123 5 name20140424 090939 685 5 4 3 2 1 123 6 name20140424 090939 765 5 4 3 2 1 123 1 name20140424 090939 845 5 4 3 2 1 123 2 name20140424 090939 925 5 4 3 2 1 123 3 nameshould return me time stamp time stamp ms d1 d2 d3 d4 d5 d6 cycle name 20140424 090938 725 5 4 3 2 1 123 13 name20140424 090939 205 5 4 3 2 1 123 6 name20140424 090939 685 5 4 3 2 1 123 6 name,['mysql'] +684805,how do i get lines column numbers in java stacktraces in some languages it is possible to get the column number of a line in a stacktrace however in java we only have line numbers to give you an example in another language we can haveerror at anonymous22 at objectinjectedscript evaluateon anonymous64139 at objectinjectedscript evaluateandwrap anonymous58052 at objectinjectedscriptevaluate anonymous49521although this might be a bad example as i am causing the error from the browser console you can see the column numbers which is really helpful in solving errorsto give you the example in java yes names were changed caused by javalangillegalargumentexception path was null at orgjbossresteasyspecimplresteasyuribuilderpathresteasyuribuilderjava362 at enterprisemoneyserviceabstractsomethingjava88this leads to line 88 which containsuri uri uriinfogetbaseuribuilderpathobjectapathobjectbbuildwith the stacktrace i have i cannot check which path call caused the exception so my question is are there any solutions that allow me to get the reference of the column to guard from some possible alternative answers we need a solution to get the column numbers other answers like how to step through the debugger or refactoring every builder pattern etc will not answer the question,['java'] +684829,when should stdstring be used over character arrays i sit around and think about whether or not i should be using const char or const stdstring pretty often when i am designing class interfaces and when it comes down to it i often feel like there is 6 in one hand with half a dozen in the othertake the following two function prototypesvoid fooconst char strvoid foostdstring strif the foo function were to store a string i would say the second is a better option due to the ability to pass a string and utilize move semantics where possible however if foo only needed to read the string would the const char solution be betteron a performance perspective a temporary stdstring wouldnt need to be created however calling the function with an already existing string as an argument looks obtrusive foomystrc str worse yet if more advanced operations need to be done on the array at some point down the road or if a copy should be stored the interface then has to changeso my questions is thisare there well defined either personal or otherwise conventions that rule when stdstring or const char is a better choice furthermore when starting a new project is it best to be consistent with usage or just take whichever one fits the current chunk of code best,['c++'] +684836,phonegap geolocation sometimes not working on android i have using cordova v341 to build android and ios app on ios geolocation function is returning very quickly and works fine alwaysbut on android sometimes it not workingthe strange thing is after i reboot my android phoneit works fine in more than a few hours geolocation gets the postion very quickly both in wifi and 3gbut after serval hours i open the app again the geolocation can not worksometimes when i outside it can get postion with gps satellitebut very slowoften occur timeout errori try to remove the app and reinstall it againbut the problem still existunless reboot my android phonewhen i reboot my android phonegeolocation function is working fine again in future a few hoursi have test serval androids phone such as samsang note2 galaxy4 etc they all have the same problemwhen i reboot it they can get location very quiclythis problem has troubled me for a long time so somebody help mehere is my code belownavigatorgeolocationgetcurrentpositionfunctionpos cbnullpos functionerrmsg navigatorgeolocationgetcurrentpositionfunctionpos cbnullpos functionerrmsg cberrmsg enablehighaccuracy true timeout 60102 maximumage 106010 enablehighaccuracy false timeout 1010 maximumage 106010my configxmlfeature namegeolocation param nameandroidpackage valueorgapachecordovageolocationgeobroker feature,['android'] +684940,thisplay initial for internet explorer i have made a website that works just fine in google chrome and firefox but when i run it in internet explorer i am experiencing problemsso i have 2 slideshows on my index page but only one should show at a specific screen resolution i created some media queries so i could set a thisplaynone to the slideshow i do not need at that resolution and to make it appear again i use thisplayinitial but internet explorer does not support that commandi need a way to make visible what i had invisible with thisplaynone in internet explorer ps using visibilityhidden is not an option because it should not reserve the spaceif you can help me please replyif you cannot i thank you for reading this anywayhere is come of the code it might help i am not sure how to post correctly sorrysection idcontainergrotepage div idpage ul idslider liimg srcimagesslideshowimage2jpg altslideshow foto 1 li liimg srcimagesslideshowimage1jpg altslideshow foto 2 li liimg srcimagesslideshowimage3jpg altslideshow foto 3 li liimg srcimagesslideshowimage4jpg altslideshow foto 4 li uldivsectiondiv idpageklein ul idsliderklein li idkleineslideli img idfotoslideshowklein srcimagesslideshowimage1jpg altslideshow foto 1 li ulbutton onclickslideshowklein idindexkleineslideshowknopvolgendebuttondivthis is what i do on the smallest screen containergrotepagethisplaynonepagethisplaynone kleineslidelibackgroundcolorblackpadding 10px 50px 10px 50pxfotoslideshowkleinwidth90marginleft4border 1px solid blackindexkleineslideshowknopwidth90margintop1marginleft4first media query min440pxmedia only screen and minwidth440pxcontainer margintop3slideshowpage thisplayinitial width600px margin50px autoslider width600px height250pxie bugfix padding0 margin0media query min610pxslider li liststylenone containergrotepagethisplayinitialthisplayblockwidth600pxmargintop2marginleftautomarginrightautopagekleinthisplaynonepage thisplayinitialwidth600px margin50px autoslider width600px height250pxie bugfixpadding0margin0media query min715pxslider width600pxheight250pxie bugfixpadding0margin0slider li liststylenonepage width600pxmargin50px autoi hope the information i provided is usefulcontainergrotepage is the big slideshow btw and pageklein is the small onei speak dutch so some names might not make sense to english speakers thanks in advance guys,['css'] +684989,is fgets returning null with a short bufer compliant in unit testing a function containing fgets came across an unexpected result when the buffer size n 2 obviously such a buffer size is foolish but the test is exploring corner casessimplified codeinclude errorhinclude stdiohvoid test fgetschar restrict s int n file stream stdin s0 42 printf sp nd streampn s n stream char retval fgetss n stream printf errnod feofd ferrord retvalp s0dnn errno feofstream ferrorstream retval s0int mainvoid char s100 test fgetss sizeof s entered 123n and works as expected test fgetss 1 fgets null feof 0 ferror 0 test fgetss 0 same as above return 0what is surprising is that fgets returns null and neither feof nor ferror are 1the c spec below seems silent on this rare casequestions is returning null without setting feof nor ferror compliant behaviorcould a different result be compliant behaviordoes it make a difference if n is 1 or less than 1platform gcc version 453 target i686pccygwinref c11 a72172 the fgets function reads at most one less than the number of characters specified by n the fgets function returns s if successful if endoffile is encountered and no characters have been read into the array the contents of the array remain unchanged and a null pointer is returned if a read error occurs during the operation the array contents are indeterminate and a null pointer is returned related postingsminishell in c how to use feof and ferror for fgetstrouble creating a shell in c segfault and ferrorfputs fgets ferror questions and c equivalentsreturn value of fgets edit comments on answersshafik yaghmour well presented the overall issue since the c spec does not mention what to do when it does not read any data nor write any data to s when n 0 it is undefined behavior so any reasonable response should be acceptable such as return null set no flags leave buffer aloneas to what should happen when n1 oliver matthews answer and matt mcnabb comment indicate a c specs lack of clarity considering a buffer of n 1 the c spec seems to favor a buffer of n 1 should return the buffer pointer with s0 0 but is not explicit enough,['c'] +685120,how to send data over a bluetooth low energy ble link i am able to thiscover connect to bluetoothsource codeconnect via bluetooth to remote deviceget the device by its serial number bddevice mbluetoothadaptergetremotedeviceblackbox for ble connection bddeviceconnectgattgetapplicationcontext true mgattcallbackgatt callback for status private bluetoothgattcallback mgattcallback new bluetoothgattcallback override public void onconnectionstatechangebluetoothgatt gatt int status int newstate connection established if status bluetoothgattgatt success newstate bluetoothprofilestate connected thiscover services gathiscoverservices else if status bluetoothgattgatt success newstate bluetoothprofilestate thisconnected handle a thisconnect event override public void onservicesthiscoveredbluetoothgatt gatt int status now we can start readingwriting characteristics now i want to send commands to remote ble device but do not know how to do thatonce the command is sent to the ble device the ble device will respond by broadcastingdata which my application can receive,['android'] +685131,what is the best practice to retrieve all customers from stripe api into one list when calling stripecustomeralimit 100 there is a limit of 100 per call we have a lot more customers than that and i would like to get them all at once am i missing something or is this only possible by writing a naive loop that checks on the has more attribute and then makes a new call until has more false,['ruby'] +685149,readwrite file with unicode file name with plain cboost i want to read write a file with a unicode file name using boost filesystem boost locale on windows mingw should be platform independent at the endthis is my codeinclude boostlocalehppdefine boost no cxx11 scoped enumsinclude boostfilesystemhppinclude boostfilesystemfstreamhppnamespace fs boostfilesysteminclude stringinclude iostreamint main stdlocaleglobalboostlocalegeneratorgenerate fspathimbuestdlocale fspath filea14txt if fsexistsfile stdcout file does not exist stdendl fsofstreamfile stdios baseapp test stdendlthe fsexists really checks for a file with the name a14txt but the written file has the name a14txtreading gives the same problem using fswofstream does not help either since this just handles wide inputhow can i fix this using c11 and boostedit bug report posted to clarify for the bounty it is quite simple with qt but i would like a cross platform solution using just c11 and boost no qt and no icu,['c++'] +685276,share to facebook in android like twitter as anyone whos tried to share to facebook via android knows the facebook team has decided to thisregard the protocol for sharing and ignores the text provided in the share intent see share text on facebook from android app via action sendhowever it appears that the twitter app has figured out how to circumvent this when youre looking at a tweetyou can click the share icon below the tweet and it brings up the normal share dialog with a list of apps including facebookif you click on facebook you get this viewwhich looks perfect and clearly twitter is sending more than just a link that other answers seem to propose furthermore if you share to messagingyou can see that the text is properly added and there are no issues how did twitter get this to work,['android'] +685309,any api to prevent windows 8 from going into connected standby mode i need to thisable connected standby mode until my desktop application has finished the desired behavior should be similar to what happens when i connect to that machine via remote desktop that is the screen is switched off but the system does not go into sleep until i thisconnect is there any documented or undocumented way to get the same behavior for my applicationi tried powersetrequest with powerrequestexecutionrequired andor powerrequestawaymoderequired but the system still goes into connected standby mode in a few mins i currently use powerrequestthisplayrequired to keep it alive but the screen always stays onedited this is the test application the timer is ticking for no more than 5 minutes after i press the hardware power button and the screen turns off running on batteryusing systemusing systemruntimeinteropservicesusing systemwindowsformsnamespace cstestapp public partial class mainform form public mainform initializecomponent thisload mainform load void mainform loadobject sender eventargs e init timer var timer new systemwindowsformstimer timerinterval 10 timertick delegate systemdiagnosticstracewritelinecstestapp datetimenow timerstart set guid execution required request timeout intptr pactiveschemeguid var hr powergetactiveschemeintptrzero out pactiveschemeguid if hr 0 marshalthrowexceptionforhrinthr guid activeschemeguid guidmarshalptrtostructurepactiveschemeguid typeofguid localfreepactiveschemeguid int savedtimeout hr powerreaddcvalueindex intptrzero activeschemeguid guid idle resiliency subgroup guid execution required request timeout out savedtimeout if hr 0 marshalthrowexceptionforhrinthr hr powerwritedcvalueindex intptrzero activeschemeguid guid idle resiliency subgroup guid execution required request timeout 1 if hr 0 marshalthrowexceptionforhrinthr create power request var powerrequestcontext new power request context powerrequestcontextversion power request context version powerrequestcontextflags power request context simple string powerrequestcontextsimplereasonstring thisable connected standby var powerrequest powercreaterequestref powerrequestcontext if powerrequest intptrzero throwlastwin32error set powerrequestexecutionrequired if powersetrequestpowerrequest powerrequesttypepowerrequestexecutionrequired throwlastwin32error thisformclosed delegate timerthispose powerclearrequestpowerrequest powerrequesttypepowerrequestexecutionrequired closehandlepowerrequest hr powerwritedcvalueindex intptrzero activeschemeguid guid idle resiliency subgroup guid execution required request timeout savedtimeout if hr 0 marshalthrowexceptionforhrinthr power api interop static void throwlastwin32error throw new systemcomponentmodelwin32exceptionmarshalgetlastwin32error enum powerrequesttype powerrequestthisplayrequired 0 powerrequestsystemrequired 1 powerrequestawaymoderequired 2 powerrequestexecutionrequired 3 powerrequestmaximum structlayoutlayoutkindsequential struct powerrequestcontextdetailedinformation public intptr localizedreasonmodule public uint32 localizedreasonid public uint32 reasonstringcount marshalasunmanagedtypelpwstr public string reasonstrings structlayoutlayoutkindsequential charset charsetunicode struct power request context detailed public uint32 version public uint32 flags public powerrequestcontextdetailedinformation detailedinformation structlayoutlayoutkindsequential charset charsetunicode struct power request context public uint32 version public uint32 flags marshalasunmanagedtypelpwstr public string simplereasonstring const int power request context version 0 const int power request context simple string 0x1 const int power request context detailed string 0x2 static readonly guid guid idle resiliency subgroup new guid0x2e601130 0x5351 0x4d9d 0x8e 0x4 0x25 0x29 0x66 0xba 0xd0 0x54 static readonly guid guid execution required request timeout new guid0x3166bc41 0x7e98 0x4e03 0xb3 0x4e 0xec 0xf 0x5f 0x2b 0x21 0x8e dllimportkernel32dll setlasterror true static extern intptr powercreaterequestref power request context context dllimportkernel32dll setlasterror true static extern bool powersetrequestintptr powerrequesthandle powerrequesttype requesttype dllimportkernel32dll setlasterror true static extern bool powerclearrequestintptr powerrequesthandle powerrequesttype requesttype dllimportkernel32dll setlasterror true exactspelling true static extern bool closehandleintptr hobject dllimportkernel32dll setlasterror true static extern intptr localfreeintptr hmem dllimportpowrprofdll charset charsetunicode static extern uint32 powerwritedcvalueindexintptr rootpowerkey marshalasunmanagedtypelpstruct guid schemeguid marshalasunmanagedtypelpstruct guid subgroupofpowersettingsguid marshalasunmanagedtypelpstruct guid powersettingguid int acvalueindex dllimportpowrprofdll charset charsetunicode static extern uint32 powerreaddcvalueindexintptr rootpowerkey marshalasunmanagedtypelpstruct guid schemeguid marshalasunmanagedtypelpstruct guid subgroupofpowersettingsguid marshalasunmanagedtypelpstruct guid powersettingguid out int acvalueindex dllimportpowrprofdll charset charsetunicode static extern uint32 powergetactiveschemeintptr userpowerkey out intptr activepolicyguid this is the output from powercfgexe requestsexecutionprocess devicehardthiskvolume4usersavotestcstestappexethisable connected standby,"['c#', 'c++', '.net']" +685421,rails server binrails6 warning already initialized constant app path error i have tried a number of things like uninstallingreinstalling rails and gems but to no availwhen i go into my new project and run rails s or bundle exec rails server i am getting this error binrails6 warning already initialized constant app pathuserstoabuisitescmsbinrails6 warning previous definition of app path was here usage rails command argsinside my binrails i see this codeusrbinenv rubybeginload fileexpand pathspring file rescue loaderrorendapp path fileexpand pathconfigapplication file require relative configbootrequire railscommandsdoes anyone know why i keep getting that error when i run rails s i have googled and it seems like there is an error with the spring gem but i canat seem to get it to work,['ruby-on-rails'] +685441,is or used on the righthandside of an assignment pythonic situationnote the following situation is just exemplary this question applys to anything that can evaluate to boola default list should be used if the user does not provide a custom listdefault list custom list if custom list list custom listelse list default listyou can shorten this todefault list custom list list custom list if custom list else default listnow as per the expression x or y first evaluates x if x is true its value is returned otherwise y is evaluated and the resulting value is returned or does not return a boolean but rather the first value whose boolean conversion is not false therefore the following would be valid codelist custom list or default listthis is similar to the c null coalescing operator except it should be recoined in python as false coalescing operator which returns the first nonfalse argumentquestionthe last example seems to be easier to read but is it considered pythonicneither pep8 the program nor pylint do complain,['python'] +685469,google maps ios remove polylines is it possible to remove all polylines without removing other objects mapview clear removes everything including markersi also tried the following but it did not work eitherfor gmspolyline strong polyline in selfmapviewsubviews polyline nilthanks in advanceps i am using google maps sdk for ios version 1727908,"['ios', 'objective-c']" +685486,custom shape while chatting in android using xml file i am able to draw custom back ground to xml file using shapebut how to add arc or curv at specified place,['android'] +685497,reading shared variables with relaxed ordering is it possible in theory is it possible in c consider the following pseudocodeexpected nullif variable expected atomic compare exchange strong variable expected desired memory order acq rel memory order acqreturn variableobserve there are no acquire semantics when the variable expected check is performedit seems to me that desired will be called at least once in total and at most once per threadfurthermore if desired never returns null then this code will never return nullnow i have three questionsis the above necessarily true ie can we really have wellordered reads of shared variables even in the absence of fences on every readis it possible to implement this in c if so how if not whyhopefully with a rationale not just because the standard says soif the answer to 2 is yes then is it also possible to implement this in c without requiring variable expected to perform an atomic read of variablebasically my goal is to understand if it is possible to perform lazyinitialization of a shared variable in a manner that has performance identical to that of a nonshared variable once the code has been executed at least once by each threadthis is somewhat of a languagelawyer question so that implies the question is not about whether this is a good or useful idea but rather about whether it is technically possible to do this correctly,['c++'] +685605,smart pointers cycles sometimes i am really sure that i want to have circular dependence of pointers and every object on cycle should be able to use his pointer so it cannot be weak ptrmy question is does this mean that i have bad designwhat if i want to implement graph can i use smart pointers in graphs there are cycles but with weak ptr i cannot use what can i doi read some articles reference and topics on stackoverflow but it looks like i still do not get smart pointers really why does not exists some variant of weak ptr with,['c++'] +685688,marshalling c array in c simple helloworld building off of my marshalling helloworld question i am running into issues marshalling an array allocated in c to c i have spent hours researching where i might be going wrong but everything i have tried ends up with errors such as accessviolationexceptionthe function that handles creating an array in c is below declspecdllexport int cdecl import csvchar path struct human persons int numpersons int res file csv char line1024 struct human humans csv fopenpath r if csv null return errno numpersons 0 init to sane value all i am trying to do for now is get more than one working starting with 2 seems reasonable my test csv file only has 2 lines humans calloc2 sizeofstruct human if humans null return enomem while fgetsline 1024 csv char tmp strdupline struct human person humansnumpersons calloc1 sizeofperson person humansnumpersons easier to work with if person null return enomem personcontact calloc1 sizeofpersoncontact if personcontact null return enomem res parse humanline person if res 0 return res numpersons persons humans fclosecsv return 0the c codeintptr humansptr intptrzeroint numhumans 0hellolibraryimport csvargs0 ref humansptr ref numhumanshellolibraryhuman humans new hellolibraryhumannumhumansintptr ptrs new intptrnumhumansintptr aindex intptrmarshalptrtostructurehumansptr typeofintptr populate the array of intptrfor int i 0 i numhumans i ptrsi new intptraindextoint64 marshalsizeoftypeofintptr i marshal the array of human structsfor int i 0 i numhumans i humansi hellolibraryhumanmarshalptrtostructure ptrsi typeofhellolibraryhuman use the marshalled dataforeach hellolibraryhuman human in humans consolewritelinefirst0 humanfirst consolewritelinelast0 humanlast hellolibrarycontact info contact hellolibrarycontact infomarshal ptrtostructurehumancontact typeofhellolibrarycontact info consolewritelinecell0 contactcell consolewritelinehome0 contacthomethe first human struct gets marshalled fine i get the access violation exceptions after the first one i feel like i am missing something with marshalling structs with struct pointers inside them i hope i have some simple mistake i am overlooking do you see anything wrong with this codesee this github gist for full source,"['c#', 'c']" +685689,error laravellog could not be opened i am pretty new at laravel in fact and i am trying to create my very first project for some reason i keep getting this error i have not even started coding yeterror in exception handler the stream or file varwlaravelappstoragelogslaravellog could not be opened failed to open stream permission denied in varwlaravelbootstrapcompiledphp8423i have read this has something to do with permissions but chmod r 775 storage did not help at all,['php'] +685776,what is the difference between upcasting and downcasting with respect to class variable what is the difference between upcasting and downcasting with respect to class variablefor example in the following program class animal contains only one method but dog class contains two methods then how we cast the dog variable to the animal variableif casting is done then how can we call the dogs another method with animals variableclass animal public void callme systemoutprintlnin callme of animal class dog extends animal public void callme systemoutprintlnin callme of dog public void callme2 systemoutprintlnin callme2 of dog public class useanimlas public static void main string args dog d new dog animal a animald dcallme acallme dog acallme2,['java'] +685806,how to properly configure rails 41 enums in activeadmin i have got a rails 41 app in which i use an enum to represent the privacy level of an objectin my schematinteger privacy level default 0in my modelenum privacy level privacy private 0 privacy trusted 1 privacy public 2 in my activeadmin register fileindex do column privacy level default actionsendform do f finputs edit my model do finput privacy level end factionsendon the activeadmin index page it works great the privacy level of each object shows up as privacy private privacy trusted and privacy publichowever when i try to edit an object the input type is a number box with up and down arrows which allow me to put any integer in regardless of whether or not the integer is a valid privacy level even negative values what i would like to see is a dropdown select input with the three enumerated string values i defined in my model,['ruby-on-rails'] +685828,pandas plotting a stacked bar chart i am trying to create a stacked bar graph that replicates the picture all my data is separate from that excel spreadsheeti cant figure out how to make a dataframe for it like pictured nor can i figure out how to make the stacked bar chart all examples i locate work in different ways to what i am trying to createmy dataframe is a csv of all values narrowed down to the following with a pandas dataframe site name abusenff0 north acton abuse1 washington 2 washington nff3 belfast 4 croydon i have managed to count the data with totals and get individual counts for each site i just cant seem to combine it in a way to graphwould really appreciate some strong guidancecompleted code many thanks for the assistance completingtest5 faultdfgroupbysite name abusenffsite namecountunstackabusenfillna0test5plotkindbar stackedtrue,['python'] +685850,incomprehensible function signature return reference to an array of and objects i have come across the following signaturedoublerotate vecdoubleval44in the comments it claims to accept and return an array of four elements my first reaction was that this does not even look standard c yet this compilesdoublerotate vecdoubleval44 return valint main double ar4 1 2 3 5 rotate vecar return 0how is this c how would you read it we cannot return an array from a function just pointers or can we,['c++'] +685864,angularjs seo using html5 mode would love some clarity on how this functions behindthescenes there are numerous resources out there for implementing seofriendly versions of angularjs applications of course despite reading all of them numerous times i am still a bit unclear on a few things particularly regarding the thistinction between the hashbang and html5 mode modelsfor hashbang or html4 apps the following setting is given on the location providerlocationhashprefixis this setting required for html5 mode as well why or why notfor html5 mode apps the following meta tag is included in the indexhtml pagemeta namefragment contentis this meta tag required for hashbang apps as well why or why notusing html5 mode my urls look similar toeven with the meta tag from 2 specified in my indexhtml i am still unable to navigate to my urls as a crawler would such as tolandinghomeis this normal should i expect to be able to navigate to my app hashbangstyle if it is an html5 mode app after adding the location provider settings andor meta tagmore than anything i guess my actual question would be whats specifically required for html5 mode crawling and whats specifically required for hashbangstyle crawling how do they overlap additionally how does the html5 mode configuration actually work behind the scenes if no hashbangstyle route is ever producedusablenote that these questions are separate from the issue of generatingserving snapshots which i generally understandangularjs seofriendly configuration generally makes sense when it comes to classical hashbangstyle apps but for html5 mode i am a bit confused would love some clarity,['javascript'] +685875,lazy loading with responsive images unknown height i am using a css grid system which is based upon percentages i have a grid with 4 columns each 25 of the pages total width i output my image tags inside of each 25 cell like thisimg srcfoojpg stylemaxwidth100 as the browser resizes the images also resize to fill in 100 of each 25 cell the browser picks a height as if i had put heightauto which is implicit when omittednow i want to add lazy loading capability to this the problem is that before the images are loaded their height on the page is unknown the browser has to download the image observe its aspect ratio and calculate a height for it prior to this all the images have a height of 1px since every image has a height of 1px they are all considered as within the viewport and are immediately loadedcurrently i have a proof of concept where prior to outputting the img tag i calculate the images aspect ratio on the server and output in a data attributeimg srcfoojpg stylemaxwidth100 dataaspect17742 then upon the event document ready i loop through every image and set a fixed height value in pixels prior to lazy loadingimgeachfunction var img this var width imgwidth var ratio imgdataaspectratio var height width ratio thiscssheight heightpx this seems to be working in the sense that it no longer loads all the images at the same time but only loads images as i scrollhowever it seems like it could cause new problems like the images becoming stretched as the user resizes the browser i would have to switch the height back to auto when a callback fires for lazy loading having completed that would take care of images the user sees but the images below the fold would still have an improper height value upon the browser being resized every time the browser is resized i would have to iterate all images that were previously below the fold measure their updated width read their aspect ratio and update the new height and then retrigger lazy loading to handle anything that is now above the fold if i do not do this loading could be triggered too early or too late due to those images having the wrong height valuemy question is is there any other ways to lazy load images with unknown heights other than the exact method i have described here and what ramifications would this have is there any downside to my method other than it being a pain to program,"['javascript', 'jquery', 'html', 'css']" +685995,subprocesscheck output return code i am usinggrepout subprocesscheck outputgrep search tmp shelltrueto run a terminal command i know that i can use a tryexcept to catch the error but how can i get the value of the error codei found this on the official documentation exception subprocesscalledprocesserror exception raised when a process run by check call or check output returns a nonzero exit status returncode exit status of the child processbut there are no examples given and google was of no help,['python'] +686028,browser is not redirecting but url is changing hey guys i want to redirect my page by clicking on entire rowfor that my html table row is below which is created by javascriptid 1tr onclickdocumentlocationhrefhttplocalhostemailcemailcampaigneditid tdbabcbtdtrbefore clicking on above code my browsers url is httplocalhostemailcafter click on code i want to redirect my page on this url httplocalhostemailcemailcampaignedit1browsers url is changes perfectly on clicking but browser is not redirecting to that url if i refresh browser on that url then it works as i wanti have tried this also for testing the syntaxtr onclickdocumentlocationhref tdbabcbtdtrit works perfectly browser is completely redirecting to google page andi have also tested other redirecting codes likes windowlocationhref or windowlocationassign or windowlocation everything has same problem,"['javascript', 'php', 'jquery']" +686038,docker cannot reach rails server development from localhost30 using docker flag p 3030 i am trying to use docker with rails building an entire stack inside one container my endgoal is to have an nginxmemcachedunicornrailspostgres stack with runit as the process manager so far i have my app ruby and postgres installed at this point i am trying to test if everything is working correctly before i move on to nginxmemcachedunicornheres my dockerfilefrom ubuntutrustyadd app update reposrun aptget update general run aptget install y git curl softwarepropertiescommon pythonsoftwareproperties ssh install ruby taken from run curl lk bash s stablerun binbash l c rvm requirementsrun binbash l c rvm install 211env path usrlocalrvmgemsruby211binusrlocalrvmrubiesruby211binpathrun gem install bundler nori nordoc install nodejs rails js runtimerun aptget install y nodejs install postgresql adapted from run echo deb lsb release scpgdg mainrun curl aptkey add run aptget updaterun aptget install y postgresql93 postgresqlclient93 postgresqlcontrib93 setup postgresqlrun mkdir pgsql chown postgres pgsqluser postgresenv path pathusrlibpostgresql93binrun initdb e utf8 d pgsqldatauser root needed for pg gem from run aptget install y libpqdevthen i create a container with the following commanddocker run it p 3030 dockerfile image binbash linside of that container i set up postgresql as a background job and run rails s sudo u postgres usrlibpostgresql93binpostgres d pgsqldataz bg sudo u postgres usrbinpsql c create role appname login createdb cd app bundle rake dbcreate dbmigrate rails s booting webrick rails 410 application starting in development on run rails server h for more startup options notice server is listening on all interfaces 0 consider using 127001 binding option ctrlc to shutdown serverbut as the title states i cannot connect from localhost30i have also tried trying to connect from 030leaving the p 3030 and trying to connect from container ip30expose 30 in the dockerfile using docker ps to find the mapped port and trying localhostmapped portalso i do not know if it matters but i am using boot2docker on osx,['ruby-on-rails'] +686358,using sqlitenet in a wpf app i am having a bit of a senior moment trying to get sqlite working on a new wpf project i have recently written a bunch of windows store and phone projects and always used the same neat sqlitenet implementation there but now i cannot seem to do that with my wpf app i have added sqlitenet through nuget but i cannot find a version of sqlite3dll that i can add to the project when i download it from sqliteorg i get the following error what am i doing wrong all the tutorials i find tell me to use systemdatasqlite instead but i do not want to rewrite all my dal code again,['c#'] +686447,python flask render template not found i am new in flask i have this code will you give me an advice what i am doing wrong thanksfrom flask import flaskfrom flask import requestfrom flask import render templateapp flask name approutedef my form return render templatemyformhtmlapproute methodspostdef my form post text requestformtext processed text textupper return processed textappdebug trueprintasdsaif name main appruni have put file myformhtml into this folder cpython33libsitepackagesflasktestsuitetemplatesbut when i refresh the 12700150 i get jinja2exceptionstemplatenotfound file cpython33libsitepackagesflaskapy line 1836 in call return selfwsgi appenviron start responsefile cpython33libsitepackagesflaskapy line 1820 in wsgi appresponse selfmake responseselfhandle exceptionefile cpython33libsitepackagesflaskapy line 1403 in handle exceptionreraiseexc type exc value tbfile cpython33libsitepackagesflask compatpy line 33 in reraiseraise valuefile cpython33libsitepackagesflaskapy line 1817 in wsgi appresponse selffull thispatch requestfile cpython33libsitepackagesflaskapy line 1477 in full thispatch requestrv selfhandle user exceptionefile cpython33libsitepackagesflaskapy line 1381 in handle user exceptionreraiseexc type exc value tbfile cpython33libsitepackagesflask compatpy line 33 in reraiseraise valuefile cpython33libsitepackagesflaskapy line 1475 in full thispatch requestrv selfthispatch requestfile cpython33libsitepackagesflaskapy line 1461 in thispatch requestreturn selfview functionsruleendpointreqview argsfile dworkspaceapproximatestringsearchtestestpy line 9 in my formreturn render templatemyformhtmlfile cpython33libsitepackagesflasktemplatingpy line 127 in render templatereturn renderctxappjinja envget or select templatetemplate name or listfile cpython33libsitepackagesjinja2environmentpy line 830 in get or select templatereturn selfget templatetemplate name or list parent globalsfile cpython33libsitepackagesjinja2environmentpy line 791 in get templatereturn self load templatename selfmake globalsglobalsfile cpython33libsitepackagesjinja2environmentpy line 765 in load templatetemplate selfloaderloadself name globalsfile cpython33libsitepackagesjinja2loaderspy line 113 in loadsource filename uptodate selfget sourceenvironment namefile cpython33libsitepackagesflasktemplatingpy line 64 in get sourceraise templatenotfoundtemplatejinja2exceptionstemplatenotfound myformhtml,['python'] +686479,javascript does not get executed the first time when i access a page from a link there is a template in my rails application that does not execute the javascript code the first time when it is loaded by clicking on a link in my home page it only happens when it is accessed from the link and only the first time i do not know why is this happening any help here is the code home page appviewsstatic pageshomehtmlerb link to nofify an absence new cancellation path this is the javascript fileappassetsjavascriptscancellations newjsvar validatedatetime function some other code that returns true or false documentreadyfunction new cancellationsubmitfunctionevent eventpreventdefault if validatedatetime alertsome alert else some more code and the template where the javascript should be executed appviewscancellationsnewerb providetitle notify an absencediv classrowdiv claspan3 offset4 h3 notify an absence h3 form for cancellation id new cancellation do f render sharederror messages some form elements fsubmit send class btn btnprimary end divdivi have already tried adding require cancellations new to the appassetsjavascriptsapplicationjs with no improvementediti did some research following radubogdan lead and i found that turbolinks is responsible for the strange behavior of javascript if you have turbolinks activated in your application the a elements get loaded from an ajax request and then the content is used to modify the body of your html since the way the dom is loaded is not the usual one the code written inside of documentready would not work unless the page is fully reloaded for example refreshing the browser if you want your javascript to run as usual you might have to change your documentready to documentonpagechange function some more code you can find some more info about this topic heremore,"['javascript', 'ruby-on-rails']" +686486,bootstrap 3 inputgroup 100 width in the bootstrap documentation they have input groups that span 100 width with no additional markup div classinputgroup input typetext classformcontrol span classinputgroupaddon00spandivi cannot seem to get my input groups to span 100 without explicitly defining width 100 on inputgroup note that i have slightly adjusted the markupdiv classinputgroup input classformcontrol placeholderauto width div classclear a href classglyphicon glyphiconremovea divdivcssclear thisplay tablecell i have created a fiddle to represent this problem,"['html', 'css']" +686532,accessviolationexception was unhandled i am attempting to use steve sandersons blog post in order to edit a variable length list in my asp mvc 3 view the project builds fine however whenever the partial view is rendered the program blows up on the usinghtmlbegincolletionitem line with this error accessviolationexception was unhandledattempted to read or write protected memory this is often an indication that other memory is corruptheres a screen shot of the full exceptioncomplete stack trace belowat microsoftvisualstudiowebhosthostprocessrequestconnection connat microsoftvisualstudiowebhostserveronsocketacceptobject acceptedsocketat systemthreadingqueueuserworkitemcallbackwaitcallback contextobject stateat systemthreadingexecutioncontextruninternalexecutioncontext executioncontext contextcallback callback object state boolean preservesyncctxat systemthreadingexecutioncontextrunexecutioncontext executioncontext contextcallback callback object state boolean preservesyncctxat systemthreadingqueueuserworkitemcallbacksystemthreadingithreadpoolworkitemexecuteworkitemat systemthreadingthreadpoolworkqueuethispatchat systemthreading threadpoolwaitcallbackperformwaitcallbackpartial viewmodel monetmodelsagentrelationshipcodesusing htmlbegincollectionitemagentrelationshipcodes exception thrown here tr tdhtmleditorformodel modeleffectivedate nullabledate new class relcodedate2 td tdhtmleditorformodel modelrelationshipid nullabledate new class relthistcode1 maxlength 3 td htmlhiddenformodel modelid htmlhiddenformodel modelrelcodeordinal trview script documentreadyfunction addcodeclickfunction ajax url urlactionnewrelationshipcode agenttransmission datatype html cache false success function html consoleloghtml experiment tbodyappendhtml script fieldset legendrelationship codeslegend table idexperiment thead tr threlationship effective dateth threlationship thist codeth tr thead tbody foreach var item in modelagentrelationshipcodes htmlpartialaddrelationshipcodepartial item tbody table br a hrefjavascriptvoid0 class addcodeadd anotherafieldsetcontroller handleprocesscorruptedstateexceptions public viewresult newrelationshipcode return viewaddrelationshipcodepartial new agentrelationshipcodes agentrelationshipcodesnamespace monetmodels using system using systemcollectionsgeneric public partial class agentrelationshipcodes public int id get set public int relcodeordinal get set public string relationshipid get set public nullablesystemdatetime effectivedate get set public systemdatetime lastchangedate get set public string lastchangeid get set public virtual agenttransmission agenttransmission get set editi have been able to get the demo working in a project outside the solution i am using right now so it apparently has to do with some dlls in this workspace now i am above my paygrade however as i am unsure how to debug something like this here are the exceptions that are identified by windbg prior to visual studio throwing the accessviolationexception there is a lot of information in between the exceptions being thrown if that is needed by anyone please let me know warning unable to verify checksum for cwindowsassemblynativeimages v4030319 32mscorlibd12f4fda3d1bfabf8342e96983e9a7mscorlibnidll error module load completed but symbols could not be loaded for cwindowsassemblynativeimages v4030319 32mscorlibd12f4fda3d1bfabf8342e96983e9a7mscorlibnidll warning unable to verify checksum for cwindowsassemblynativeimages v4030319 32systemxaml9d3572e8c3c314a0f12383d41e8bee78systemxamlnidll error module load completed but symbols could not be loaded for cwindowsassemblynativeimages v4030319 32systemxaml9d3572e8c3c314a0f12383d41e8bee78systemxamlnidll warning unable to verify checksum for cwindowsassemblynativeimages v4030319 32presentatio5ae0f00f8711b01d60a94d6ef6a02d7fd0578493presentationframeworknidll error module load completed but symbols could not be loaded for cwindowsassemblynativeimages v4030319 32presentatio5ae0f00f8711b01d60a94d6ef6a02d7fd0578493presentationframeworknidll warning unable to verify checksum for cwindowsassemblynativeimages v4030319 32windowsbaseac2e26bafa70e93b307087d7fe6b9dd2windowsbasenidll error module load completed but symbols could not be loaded for cwindowsassemblynativeimages v4030319 32windowsbaseac2e26bafa70e93b307087d7fe6b9dd2windowsbasenidll warning unable to verify checksum for cwindowsassemblynativeimages v4030319 32microsoftv4e91a071207156ac71b58fb31310a2f78c3d0c44microsoftvisualstudiowebapplicationnidll error module load completed but symbols could not be loaded for cwindowsassemblynativeimages v4030319 32microsoftv4e91a071207156ac71b58fb31310a2f78c3d0c44microsoftvisualstudiowebapplicationnidllupdateby selecting the native code option in the projects debuggers menu i now receive a slightly more detailed error message lastly by switching to iis express as suggested below i am still receiving the accessviolationexception here are the settings i used to enable iis for debugging under project propertieshere is the error messagecall stack,['c#'] +686535,undefined method attr accessible i am somewhat new to rails and i am trying to create a user login i went through the tutorial found here at the end it had me add attr accessible for mass assignment however when i did that i got the following errorundefined method attr accessible for class0x007ff70f276010i saw on this post that i ned activerecordbase but i do have that included here is the code for my user modelclass user activerecordbase attr accessor password email regex aaz09 az09az24zi validates username presence true uniqueness true length in 320 validates email presence true uniqueness true format email regex validates password confirmation true password confirmation attr validates length of password in 620 on create before save encrypt password after save clear password attr accessible username email password password confirmation def encrypt password if passwordpresent selfsalt bcryptenginegenerate salt selfencrypted password bcryptenginehash secretpassword salt end end def clear password selfpassword nil endendany other ideas on what could be causing this problem would be really appreciated thanksedit on rails 41 looks like it does not apply anymore thanks fotanus,"['ruby-on-rails', 'ruby']" +686539,how to create a list of methods then execute them i am trying to create a list that contains methods and after i add some methods i want to execute them is this possiblei tried something like thislistobject methods new listobjectthenmethodsaddmovebut when i add the program will call the methods for example in this case it called for move,['c#'] +686558,meaning of doubledoubletolongbitsx i am writing a class vec2d representing a 2 dimensional vector i store x and y in doubleswhen asked to generate equalsobject obj and hashcode eclipse generated thisoverridepublic int hashcode final int prime 31 int result 1 long temp temp doubledoubletolongbitsx result prime result int temp temp 32 temp doubledoubletolongbitsy result prime result int temp temp 32 return resultoverridepublic boolean equalsobject obj if this obj return true if obj null return false if getclass objgetclass return false vec2d other vec2d obj if doubledoubletolongbitsx doubledoubletolongbitsotherx return false if doubledoubletolongbitsy doubledoubletolongbitsothery return false return truewhat is the significance of doubledoubletolongbitsx in this context can i not simply write x otherx,['java'] +686597,how to create a java 8 stream from an iterator is it possible to create a stream from an iterator in which the sequence of objects is the same as that generated by calling the iterators next method repeatedly the specific case i am thinking of concerns the use of the iterator returned by treesetdescendingiterator but i can imagine other circumstances in which an iterator but not the collection it references is availablefor example for a treesett tset we can write tsetstream and get a stream of the objects in that set in the sets sort order but what if we want them in a different order such as that available through using descendingiterator i am imagining something like tsetdescendingiteratorstream or stream tsetdescendingiterator though neither of these forms are valid,['java'] +686633,what does exec sp updatestats do what is the use of sp updatestats can i run that in the production environment for performance improvement,['sql'] +686683,messagebodyreader not found for media typeapplicationjson i have wrote a jaxrs server and client both use jersey i want to sent a collection of my entities to client and i made this stepsmade entity extends serializablewrote a custom provider and extended it to support a collectionscopypaste entity and provider to client sidei make a request it sucessfully handled on the server side by client receives an errororgglassfishjerseymessageinternalmessagebodyprovidernotfoundexception messagebodyreader not found for media typeapplicationjson typeinterface javautillist generictypejavautillistmodelhotelsentityorgglassfishjerseymessageinternalreaderinterceptorexecutorterminalreaderinterceptoraroundreadfromreaderinterceptorexecutorjava225orgglassfishjerseymessageinternalreaderinterceptorexecutorproceedreaderinterceptorexecutorjava149orgglassfishjerseymessageinternalmessagebodyfactoryreadfrommessagebodyfactoryjava1124orgglassfishjerseymessageinternalinboundmessagecontextreadentityinboundmessagecontextjava853orgglassfishjerseymessageinternalinboundmessagecontextreadentityinboundmessagecontextjava812orgglassfishjerseyclientclientresponsereadentityclientresponsejava377orgglassfishjerseyclientjerseyinvocationtranslatejerseyinvocationjava813orgglassfishjerseyclientjerseyinvocationaccess600jerseyinvocationjava90orgglassfishjerseyclientjerseyinvocation3calljerseyinvocationjava693orgglassfishjerseyinternalerrorsprocesserrorsjava315orgglassfishjerseyinternalerrorsprocesserrorsjava297orgglassfishjerseyinternalerrorsprocesserrorsjava228orgglassfishjerseyprocessinternalrequestscoperuninscoperequestscopejava424orgglassfishjerseyclientjerseyinvocationinvokejerseyinvocationjava689orgglassfishjerseyclientjerseyinvocationbuildermethodjerseyinvocationjava405orgglassfishjerseyclientjerseyinvocationbuildergetjerseyinvocationjava301servicehotelservicegethotelshotelservicejava30actionshotelactionperformhotelactionjava42mainservletprocessresponsemainservletjava33mainservletdopostmainservletjava22javaxservlethttphttpservletservicehttpservletjava641javaxservlethttphttpservletservicehttpservletjava722server getproducesmediatypeapplication jsonpublic response gethotelslistqueryparamstartdate string startdate queryparamenddate string enddate listhotelsentity list hotelservicegetall return responsefactoryresponseresponsestatusok listclient generictypelisthotelsentity generictype new generictypelisthotelsentity webtarget target clienttargetpreparepath listhotelsentity hotels targetrequestmediatypeapplication json typegetgenerictypeproviderpublic class jsonprovidert implements messagebodyreadert messagebodywritert overridepublic boolean isreadableclass type type generictype annotation annotations mediatype mediatype return mediatypeapplication jsonequalsmediatypegettype mediatypeapplication jsonequalsmediatypegetsubtypeoverridepublic t readfromclasst type type generictype annotation annotations mediatype mediatype multivaluedmapstring string httpheaders inputstream entitystream throws ioexception webapplicationexception gson gson creategson reader reader new inputstreamreaderentitystream charsetfornameconstantsutf 8 return gsonfromjsonreader generictypeoverridepublic boolean iswriteableclass type type generictype annotation annotations mediatype mediatype return mediatypeapplication jsonequalsmediatypegettype mediatypeapplication jsonequalsmediatypegetsubtypeoverridepublic long getsizet t class type type generictype annotation annotations mediatype mediatype return 1overridepublic void writetot t class type type generictype annotation annotations mediatype mediatype multivaluedmapstring object httpheaders outputstream entitystream throws ioexception webapplicationexception gson gson creategson jsonelement element gsontojsontrentitystream writer writer null try writer new outputstreamwriterentitystream charsetfornameconstantsutf 8 gsontojsonelement writer finally if writer null writerflush private gson creategson return new gsonbuildersetprettyprintingcreateproviderpublic class jsoncollection extends jsonprovidercollection extends hospitalityentity entitytablename hotels schema catalog mydbpublic class hotelsentity implements hospitalityentityprivate int idhotelprivate string nameprivate string regionprivate string descriptionidcolumnname id hotelpublic int getidhotel return idhotelpublic void setidhotelint idhotel thisidhotel idhotelbasiccolumnname namepublic string getname return namepublic void setnamestring name thisname namebasiccolumnname regionpublic string getregion return regionpublic void setregionstring region thisregion regionbasiccolumnname descriptionpublic string getdescription return descriptionpublic void setdescriptionstring description thisdescription descriptionoverridepublic boolean equalsobject o if this o return true if o null getclass ogetclass return false hotelsentity that hotelsentity o if idhotel thatidhotel return false if description null descriptionequalsthatdescription thatdescription null return false if name null nameequalsthatname thatname null return false if region null regionequalsthatregion thatregion null return false return trueoverridepublic int hashcode int result idhotel result 31 result name null namehashcode 0 result 31 result region null regionhashcode 0 result 31 result description null descriptionhashcode 0 return result,['java'] +686720,how to create graph from phpmysql data i want to create a graph from the data fetching from database i do not have much knowledge of json or xmlis it possible to draw graph without using them i searched on net and found about google graph but there are no tutorials on how to use them i also tried to find out books on this topic but unable to find anykindly tell me any good and easy api to draw graph from mysql data and any video tutorials that can help me to learn,"['php', 'html', 'mysql']" +686760,call a method from appdelegate objectivec i was trying to call an existing method of my viewcontrollerm from appdelegatem inside the applicationdidenterbackground method so i found this link calling uiviewcontroller method from app delegate which told me to implement this codein my viewcontrollermvoidviewdidload super viewdidload appdelegate appdelegate uiapplication sharedapplication delegate appdelegatemyviewcontroller selfin my appdelegateclass myviewcontrollerinterface appdelegate uiresponder uiapplicationdelegateproperty weak nonatomic myviewcontroller myviewcontrollerendand in the appdelegates implementation voidapplicationdidenterbackgrounduiapplication application selfmyviewcontroller methodso i put this code in my project and it worked fine but i did not understand how the code works line by line what does the sharedapplication do why must i set a delegate instead of just creating an instance of viewcontroller likeviewcontroller instance viewcontroller alloc initinstance method,"['ios', 'iphone', 'objective-c']" +686826,dart vs polymer vs bootstrap whats the difference between those three things as far as i understandbootstrap is a library which helps you to use nice premade elements on your webpagedart is another language which helps you to create apps faster than those made with js but can be converted to jspolymer is something like bootstrap but let you to create all those elements bootstrap is a collection of ready elements but polymer allows you to create custom elementsdo i understand correctly what are the differences between them,['javascript'] +686865,orb is not detecting keypoints in opencv 249 i am trying to detect keypoints with orb everything is fine until i switched to opencv 249firts it seems that the number of keys decresed and for some images no keypoints are detected this is my code compiled with two version 231 and 249include iostreaminclude opencv2opencvhppinclude opencv2features2dfeatures2dhppusing namespace cvint mainint argc char argv mat img imreadargv1 stdvectorkeypoint kp orbfeaturedetector detector detectordetectimg kp stdcout found kpsize keypoints stdendl mat out drawkeypointsimg kp out scalarall255 imshowkpts out waitkey0 return 0result 231 found 152 keypoints249 found 0 keypointsi also tested with a different orb constructor but i get the same result no kptsthe same constuctor values as in 231 defaults constructor 249 custom constr include iostreaminclude opencv2opencvhppinclude opencv2features2dfeatures2dhppusing namespace cvint mainint argc char argv mat img imreadargv1 stdvectorkeypoint kp default in 249 is orb700 12f 3 31 0 orbfeaturedetector detector500 12f 8 31 0 default values of 231 detectordetectimg kp stdcout found kpsize keypoints stdendl mat out drawkeypointsimg kp out scalarall255 imshowkpts out waitkey0 return 0do you have any idea whats happening and how can i fix it thank you,['c++'] +686926,error cannot pass objects of nontriviallycopyable type stdstring aka class stdbasic string through include stdiohinclude stringmainint br el6istdstring qr naziv6 qr naziv0bath tub qr naziv1sink qr naziv2washing machine qr naziv3toilet qr naziv4kitchen sink qr naziv5thish washerfori0i6i printfinput the number for s qr nazivihere lies the problemscanfdbr elithis program is much longer so i shortened itthe thing is i will enter numbers for array br el6 and i want it to show me for what object i am entering the number so when i try to compile it gives me the errorerror cannot pass objects of nontriviallycopyable type stdstring aka class stdbasic string through i tried to declare string qr naziv6 but the string did not even bold so it did not work so i googled and found out another way stdstring qr naziv6,['c++'] +686943,ios 7 custom uinavigationbar titleview moves when pushing or popping new view controller i am using a custom title view for a uinavigationbar with the following code set a label to the nav barthlabel titlelabel thlabel alloc inittitlelabeltext testtitlelabelfont uifont fontwithnameapp font size220titlelabelframe cgrectmake0 0 100 30titlelabeltextalignment nstextalignmentcentertitlelabeltextcolor custom light bluetitlelabelstrokecolor kstrokecolortitlelabelstrokesize kstrokesizeselfnavigationitemtitleview titlelabelthe problem is that when presenting a new viewcontroller and then returning to the original view controller this custom view shifts and then recenters itself please see the video for a demonstration of thatplease see the video herefeatureyoutubei have thisabled autoresizing of every subview for the navigation controller with both the storyboard and in code for each view controller set the navigation bar hidded on the log in view uinavigationcontroller mainviewcontroller uinavigationcontrollerselfappdelegatewindowrootviewcontroller mainviewcontroller setnavigationbarhiddenyes mainviewcontroller navigationbar setautoresizessubviewsnohowever it still resizes how can i stop this what am i doing wrong thanks,"['ios', 'iphone', 'objective-c']" +687020,keep original typescript source maps after using browserify background i am compiling 2 dependent typescript files to js which produces also source maps one source map per file using tsc 10i am using m commonjs and then use browserify to generate a single bundlejshowever i noticed that i get the original source map references twice in the bundle which does not seem to workpassing debug does not seem to do the trick either i had a feeling this issue is somewhat related but i could not figure out how the issue was resolvedalso was suggested but again i do not fully understand how to use it is it a replacement to browserify bottom line i would like to merge the 2 js files but merge the js to ts source maps using browserify is that possible,['javascript'] +687023,how to thisplay the images from media library under a specific category in wordpress so i have this function code that adds category to the images that i upload in my wordpress website register taxonomy for images function olab register taxonomy for images register taxonomy for object type category attachment add action init olab register taxonomy for images add a category filter to images function olab add image category filter screen get current screen if upload screenid dropdown options array show option all view all categories olab hide empty false hierarchical true orderby name wp dropdown categories dropdown options add action restrict manage posts olab add image category filter i would like to know how can i call or thisplay all the images that falls under a specific category the category number that i want to call is category 2190what i am trying to do here is to have a photo gallery that showcases all the photos i have uploaded and tagged under the category 2190 photo of the day,['php'] +687044,how to get username using uid on android i got several uids like this10022 10011 10actually i know the usernames of them are u0 a22 u0 a11 systembut the question is how can i get the username using codes there is no etcpasswd file at all,['android'] +687094,the csrf token is invalid please try to resubmit the form im having this error message everytime i try to submit the formthe csrf token is invalid please try to resubmit the formmy form code is thisform novalidate actionpathsignup index methodpost form enctypeform roleform classformhorizontal div classformgroup form labelformemail email label attr class colmd1 controllabel form widgetformemail attr class colmd2 form errorsformemail div div classformgroup form labelformnickname nickname label attr class colmd1 controllabel form widgetformnickname attrclass colmd2 form errorsformnickname attr class colmd3 div div classformgroup form labelformpassword password label attr class colmd1 controllabel form widgetformpassword attr class colmd2 form errorsformpassword attr class colmd3 div div classformgroup form labelformpassword repeat repeat password label attr class colmd1 controllabel form widgetformpassword repeat attrclass colmd2 form errorsformpassword repeat attr class colmd3 div div classformgroup div classcolmd1 controllabel input typesubmit valuesubmit div div formany idea,['php'] +687096,bootstrap 3 collapsible sidebar who could please tell me what would be the simplest and cleanest way to do exactly the same sidebar navigation as this website but on the left sideusing bootstrap 3thanks,['css'] +687162,final output on slave pty is lost if it was not closed in parent why i wrote and maintain a program rlwrap that uses a pseudoterminal to communicate with a child process pseudoterminals ptys are found in all unixlike systems but they behave slightly differently on different platformscase in point in rlwrap the parent process keeps the slave pty open to keep tabs on the childs terminal settings on linux and freebsd one can use the master for that but not in solaris for exampleon freebsd 82 but not linux this leads to the loss of the childs final output for exampleinclude stdioh save as testc and compile with gcc o test testc lutil define bufsize 255int mainvoid int master slave char bufbufsize int nread openptymaster slave null null null if fork parent closeslave leave this out and lose slaves final words why do nread readmaster buf bufsize writestdout fileno buf nread echo childs output to stdout while nread 0 else child login ttyslave this makes child a session leader and slave a controlling terminal for it then dups stdinouterr to slave printffeeling ok n sleep1 printffeeling unwell arghn this line may get lost return 0the parent process will echo the childs output as expected but when i omit the closeslave keeping it open like in rlwrapon freebsd the parent does not see the final output line it reads an eof instead if anything i would have expected the opposite that keeping the slave end open would prevent the output from being loston linux on the other hand an eof is never seen not even after the child has died whether we close the slave or notis this behaviour documented somewhere is there a rationale for it can i circumvent it without closing the slave in the parent process i found out that not making the slave a controlling terminal replacing the login tty call with a few simple dup calls will cure the problem this is no solution for rlwrap however quite a few commands need a controlling terminal devtty to talk to so rlwrap has to provide one for them,['c'] +687176,how to have css3 animation to loop forever i want to have the whole set of animation to play forever when the last photo fades off i want the first one to appear again an so on what i did and i dont like is set the page to reload at the end of the last photo fade out is there any other way to do this using csshtml head stylecontent height 400px important margin auto important overflow hidden important width 780px importantimgholder height 400px margin auto width 780pxphoto1 opacity 0 animation fadeinphoto 7s 1 mozanimation fadeinphoto 7s 1 webkitanimation fadeinphoto 7s 1 oanimation fadeinphoto 7s 1 float left position relative top 0px zindex 1photo2 opacity 0 animation fadeinphoto 7s 5s 1 mozanimation fadeinphoto 7s 5s 1 webkitanimation fadeinphoto 7s 5s 1 oanimation fadeinphoto 7s 5s 1 float left position relative top 400px zindex 1photo3 opacity0 animation fadeinphoto 7s 10s 1 mozanimation fadeinphoto 7s 10s 1 webkitanimation fadeinphoto 7s 10s 1 oanimation fadeinphoto 7s 10s 1 float left position relative top 800px zindex 1photo4 opacity 0 animation fadeinphoto 7s 15s 1 mozanimation fadeinphoto 7s 15s 1 webkitanimation fadeinphoto 7s 15s 1 oanimation fadeinphoto 7s 15s 1 float left position relative top 1200px zindex 1photo5 opacity 0 animation fadeinphoto 7s 20s 1 mozanimation fadeinphoto 7s 20s 1 webkitanimation fadeinphoto 7s 20s 1 oanimation fadeinphoto 7s 20s 1 float left position relative top 1600px zindex 1 animation keyframeskeyframes fadeinphoto 0 opacity 0 50 opacity 1 100 opacity 0 mozkeyframes fadeinphoto 0 opacity 0 50 opacity 1 a100 opacity 0 webkitkeyframes fadeinphoto 0 opacity 0 50 opacity 1 100 opacity 0 okeyframes fadeinphoto 0 opacity 0 50 opacity 1 100 opacity 0 style body div classcontent div classimgholder img srcimagesimage1jpg width780 height400 classphoto1 img srcimagesimage2jpg width780 height400 classphoto2 img srcimagesimage3jpg width780 height400 classphoto3 img srcimagesimage4jpg width780 height400 classphoto4 img srcimagesimage5jpg width780 height400 classphoto5 div div body headhtml,['css'] +687216,embedded jetty spring mvc view resolver no xml http error 404 i am trying to set up a simple spring mvc server using embedded jetty i have set up the server enabled spring and configured a view resolver for jsp files the controller gives me 404 with the following messageproblem accessing jsptestjsp reasonnot founddoes anyone know what the problem is i have been googling for two daysthe serverprivate static final int default port 8080private static final string context path private static final string config location springconfigprivate static final string mapping url private embeddedjettyserverpublic static void mainstring args throws exception server server new serverdefault port serversethandlergetservletcontexthandlergetcontext serverstart serverjoinprivate static servletcontexthandler getservletcontexthandlerwebapplicationcontext context throws ioexception servletcontexthandler contexthandler new servletcontexthandler contexthandlerseterrorhandlernull contexthandlersetcontextpathcontext path contexthandleraddservletnew servletholdernew thispatcherservletcontext mapping url contexthandleraddeventlistenernew contextloaderlistenercontext contexthandlersetresourcebasenew classpathresourcewebappgeturitostring return contexthandlerprivate static webapplicationcontext getcontext annotationconfigwebapplicationcontext context new annotationconfigwebapplicationcontext contextsetconfiglocationconfig location return contextspring config view resolverconfigurationenablewebmvccomponentscanbasepackagescontrollerpublic class webmvcconfig extends webmvcconfigureradapter overridepublic void addresourcehandlersresourcehandlerregistry registry superaddresourcehandlersregistry registryaddresourcehandlerhtmladdresourcelocationsresourceshtmlbeanpublic internalresourceviewresolver viewresolver internalresourceviewresolver viewresolver new internalresourceviewresolver viewresolversetviewclassjstlviewclass viewresolversetprefixjsp viewresolversetcontenttypetexthtml charsetutf8 viewresolversetsuffixjsp return viewresolvercontrollerrequestmappingpublic modelandview index return new modelandviewtesteditfolder structurea pomxmlasrca amaina a ajavaa a a acontrollera a a a pingjavaa a a a primejavaa a a aa a a aruna a a a embeddedjettyserverjavaa a a aa a a aspringa a a aconfiga a a webmvcconfigjavaa a aa a aresourcesa a a ahtmla a a a testhtmla a a aa a a ajspa a a testjspa a aa a awebappa a ajspa a testjspa aa atesta ajavatargetpomxml resources resource targetpathwebapptargetpath directorysrcmainwebappdirectory resource resource directorysrcmainresourcesdirectory resource resources,['java'] +687307,intellij code completion not working for new java classes intellij idea 13 has started exhibiting a very weird behavior in my local setupnamely in any new java class added to an existing project code completion does not work so after declaring an object variable of any type in the new class and then typing the name of that variable followed by the dot no suggestions come up for any of the methods of the corresponding objectfor example after declaringfile f new filehometyping f does not bring up a list of all the methods in the file class to select one from as a matter of fact when typing the dot no suggestions appear and at the bottom left in the status bar of the ide window the message identifier expected identifier expected is thisplayed sometimes a long list of totally irrelevant methods from irrelevant components or libraries are proposedstrangely code completion works as expected if the above declaration happens in any of the existing classesthis behavior persists after many combinations of machine restart ide restart project reimporting closingreopening or rebuildingany ideas,['java'] +687308,clang only compiles c11 program using boostformat when stdc11 option is dropped please take a look at the following c11 snippetinclude boostformathppint mainint argc char argv auto s boostformat return 0when i compile it with clang using the stdc11 i get the following error clang stdc11 o main maincppin file included from maincpp1in file included from usrincludeboostformathpp19in file included from usrincludeboostdetailworkaroundhpp41in file included from usrincludeboostconfighpp40in file included from usrincludeboostconfigselect stdlib confighpp18usrbinlib64gccx86 64unknownlinuxgnu490includec490cstddef51 error no member named max align t in the global namespace using max align t 1 error generatedwithout the stdc11 everything compiles fine but clang prints a warning clang o main maincppmaincpp53 warning auto type specifier is a c11 extension wc11extensions auto s boostformat so it looks like a valid workaround is to drop the c11 flag as the current version of clang seem to be in c11 mode anyway the drawback is that you will get many warningsis there a better workaround beside completely switching to gcc patching the source code of boostformat or gcclibs is fine for mesystem informationplatform arch linux x86 64boost version 15506gcclibs 4901clang 34 tagsrelease 34final,['c++'] +687381,getting error gradle version 110 is required current version is 112 when executing gradle wrapper i am trying to execute gradle wrapper for an android project and this error is raiseda problem occurred evaluating root project myapp gradle version 110 is required current version is 112 if using the gradle wrapper try editing the thistributionurl in usersdudemyappgradlewrappergradlewrapperproperties to gradle110allzipmy wrapper task in buildgradle looks like thistask wrappertype wrapper gradleversion 112i recently updated to gradle v112 via homebrew is it not supported or something if so where can i check this sort of thing,['android'] +687400,bootstrapjs carousel with only text i follow this tutorial to make carousel slide when i define each item contain image and paragraph as div classitem img src alt div classcarouselcaption pcaption text herep divdiv it is work fine here its jsfiddle but when i reduce it to paragraph only as div classitem div classcarouselcaption pcaption text herep divdiv it stop working here its jsfiddle how could i make it work with only paragraph such that is slide the text each switch,"['javascript', 'jquery', 'html', 'css']" +687543,detect high values from numpy array im working on a detecting alogrythm for detecting storm cells on a radar imageryi have radar data in 2d numpy arrays that we plot on a basemapwe got azymuth and rangebins data that we put in a polargrid with latlon coordinatesthe values in our numpy array are based on dbz height in range from zero till maximum 80here a printout of our numpy array named data315 315 165 315 315 315315 315 315 315 315 315315 315 315 315 315 315315 315 315 315 315 315315 315 315 315 315 315315 115 315 315 315 315while 315 stands for null or hidden values we only need the positive values even decimals make no senseso what do we want to dodetect the clusters of high values and make them a red square around that celli have tried something with a image mask but i got stuck there even i dont know if an image mask is a good solution for this issuehere is my code to process the datagain 05 offset 315az nparange0360360scanscan number azimr nparangescanscan start azim scanscan start azim scanscan number range rscale rscaledata gain rawscan2scan z data offsetso the count of the detections would fluctuate very often maybe i need something like dbscan also can someone help me up with this,['python'] +687573,set command prompt on windows 7 to jdk7 after installed the jdk8 once i installed jdk 8 i am not succeeding to set the command prompt to the jdk 7 again on windows 7i have already set the system environment properties for both java home and path to point to jdk7 and my jdk7bin folder and i also restarted the so and every time i open a new command prompt and run java version i am always getting the version 8 of javain java environment settings i also have the jdk 7 enabledhow can i configure my command prompt for the jdk 7 again,['java'] +687772,how to configure probabilistic occupancy map people detector probabilistic occupancy map is a multicamera human detection procedure with its c implementation freely avaible at in order to utilize this handy piece of software one needsa series of synchronized video frames from multiple cameras after background removal procedurea configuration file for a particular scenariopom ships with an example set of video frames and related configuration filemy problem can be stated as followsgiven a sequence of synchronized videos for example from how do i generate the configuration file required by pom in particular i am interested in the rectangle tag of the configuration the readme statesrectangle camera number location number notvisiblexmin ymin xmax ymaxdefines the parameters of a certain rectangle standing for an individual at a certain location viewed from a certain camera all nonspecified rectangles are not visible by defaultfrom my understanding it defines how a persons bounding rectangle would look like at a certain location viewed from a certain camera this has to be defined for every grid location for every camera given the location is in the cameras field of view if not notvisible is used or the rectangle may be left undefinieddoing this by hand is not impossible but certainly is impractical so to sum up how do i generate the pom configuration file if i have a set of videos from multiple cameras,['c++'] +687810,limiting vertical movement of uiattachmentbehavior inside a uicollectionview i have a horizontal uicollectionview with a custom uicollectionviewflowlayout that has a uiattachmentbehavior set on each cell to give it a bouncy feel when scrolling left and right the behavior has the following propertiesattachmentbehaviorlength 10fattachmentbehaviordamping 05fattachmentbehaviorfrequency 19fwhen a new cell is added to the collection view it is added at the bottom and then animated to its position also using a uiattachmentbehavior naturally it bounces up and down a bit till it rests in its position everything is working as expected till nowthe problem i have starts appearing when the collection view is scrolled left or right before the newly added cell has come to rest the adds left and right bounciness to the up and down one the cell already has from being added this results in a very weird circular motion in the cellmy question is is it possible to stop the vertical motion of a uiattachmentbehavior while the collection view is being scrolled i have tried different approaches like using multiple attachment behaviors and thisabling scrolling in the collection view till the newly added cell has come to rest but non of them seem to stop this,"['ios', 'objective-c']" +687989,error when using setvalue forkey on an nsstrings isa pointer then calling string class heress what i have got as to error libobjcadylib objc trap0x14c13f4 pushl ebp0x14c13f5 movl esp ebp0x14c13f7 ud2 so basically i am trying to understand how nsstring works and trying to find a way to change the pointer that points to real char string which is said to be a constantso i found there is a pointer called isa which points to nscfconstantstring it led me to think that if i change that pointer then i could change the string the code i tried was thisnsstring st3 nsstring alloc initwithstringhihist3 setvaluechange forkeyisaand the result showing that beforeafterit seems changed but it changed every nsstring object that has hihi stringand then what i did was st3 class hoping it will give the isa pointer then i got that error message posted on the topcould you anyone explain whats going on and why it behaves like thisand it there any way to intern i am not so sure about the term like in java please avoid saying just use nsmutablestring i am just trying to figure it out seeing there might be some way to do it,['objective-c'] +687995,speechsynthesis api onend callback not working i am using the speech synthesis api on google chrome v3401847131 the api is implemented in chrome starting in v33the texttospeech works for the most part except when assigning a callback to onend for instance the following codevar message windowspeechsynthesisutterancehello worldmessageonend functionevent consolelogfinished in eventelapsedtime secondswindowspeechsynthesisspeakmessagewill sometimes call onend and sometimes not call it the timing appears to be completely off when it does get called the printed elapsedtime is always some epoch time like 13992378,['javascript'] +688008,canceling interactive uinavigationcontroller pop gesture does not call uinavigationcontrollerdelegate methods if you drag around a uiviewcontroller to begin an interactive pop transition within a uinavigationcontroller the uiviewcontroller underneath the current one has viewwillappear called followed by the uinavigationcontrollerdelegate method navigationcontrollerwillshowviewcontrolleranimatedif you cancel the transition both viewwillappear and viewdidappear get called on the top view controller as expected however neither of the delegate methods navigationcontrollerwillshowviewcontrolleranimated or navigationcontrollerdidshowviewcontrolleranimated are called at allit seems like at least one or both of these should be called considering the uiviewcontroller view lifecycle methods are called i am wondering whether this is deliberate or a bug in uinavigationcontroller what i really need is to be able to see when an interactive pop is cancelled either within my uinavigationcontroller subclass or its uinavigationcontrollerdelegate is there an obvious way to do thisediti am still looking for a solution to this but would like to mention that i have reported this issue as a bug with apple looking at the documentation there is no reason these delegate methods should not get called especially considering the equivalent view lifecycle methods do get callededit2my radar ticket 16823313 was closed today may 21st 2015 and marked as intended engineering has determined that this issue behaves as intended based on the following informationthis is actually the correct behavior the navigation transition that is happening from b a if you cancel it midtransition you would not get the didshowviewcontroller method a cancellation of this transition should not be considered a transition from a b because you never actually reached aviewwilldidappear should still be called as expected tooquite a bummer this is the case as it is counterintuitive but the workaround in my answer below should work fine for the foreseeable future at least for my usecase,"['ios', 'objective-c']" +688109,throttling javafx gui updates i receive data objects at random times at a high frequency and need to update the javafx gui with these however i do not want to fill the javafx event queue with a very large number of runnables i use platformrunlateri have been thinking of how to best implement a throttling algorithmwould it be best to have a separate guiupdater thread that check for example a blocking queue for new objects and then sleeps for example for 30ms and then checks again in an infinite loop in that case would a blocking queue be the optimal data structure please note i only need the latest data object and the blockingqueue is a fifo queue and i cannot seem to pick only the latest entryor would it be better to simply just update the gui with platformrunlater if nanotimestarttime 30ms in that case i do not need a separate thread to perform the platformrunlatercall however if an update is received when 30ms has not passed and then no updates are received for some time the last update will not show up in the guiany suggestions on how to design a throttling algorithm for javafx platformrunlater gui updates in a short efficient way,['java'] +688122,perl dbi and sql why not does not work in some sql queries i have the weirdest problem and my extremely basic knowledge of sql must be terribly wrong but i cannot make sense of the behaviour illustrated belowi have this file testcsvidfielda0b1c2d0e1f2ghi and this test code usrbinperluse strictuse warningsuse dbiuse develversiondump qwdump versionsmy dbh dbiconnect dbicsvdbhraiseerror 1dbhtracelevel 0my i 0foreach my cond true field 0 and field 1 field 0 or field 1 not field 0 or field 1 not field 0 or field 1 field 0 not field 0 print condition i is condn my sth dbhprepareselect from testcsv where cond sthexecute sthdump resultsprint nndump versionswhen run this is the outputcondition 0 is truea 0b 1c 2d 0e 1f 2g h i 9 rowscondition 1 is field 0 and field 1c 2f 2g h i 5 rowscondition 2 is field 0 or field 1a 0b 1d 0e 14 rowscondition 3 is not field 0 or field 1a 0b 1d 0e 14 rowscondition 4 is not field 0 or field 1b 1c 2e 1f 2g h i 7 rowscondition 5 is field 0b 1c 2e 1f 2g h i 7 rowscondition 6 is not field 0a 0d 02 rowsperl version v5163 on mswin32 cprogram filesperl64binperlexeactiveperlconfig unknownactivestatepath 101autoloader 573cprogram filesperl64sitelibsitecustomizepl unknowncarp 126clastruct 063clone 034config unknownconfig gitpl unknownconfig heavypl unknowncwd 340dbdcsv 041dbdfile 042dbi 1631dbidbdsqlengine 006dbisqlnano 1015544datadumper 2139develversiondump 002dynaloader 114encode 249encodealias 216encodeconfig 205encodeencoding 205errno 115exporter 567exporterheavy 567fcntl 1filebasename 284filespec 340filespecunix 340filespecwin32 340filestat 105io 125 06iodir 11iofile 116iohandle 133ioseekable 11listutil 127mathbigfloat 1997mathbigint 1998mathbigintcalc 1997mathcomplex 159mathtrig 123paramsutil 107sqldialectsanydata 1405sqldialectsrole 1405sqleval 1405sqlparser 1405sqlstatement 1405sqlstatementfunction 1405sqlstatementfunctions 1405sqlstatementoperation 1405sqlstatementplaceholder 1405sqlstatementram 1405sqlstatementterm 1405sqlstatementtermfactory 1405sqlstatementutil 1405scalarutil 127selectsaver 102symbol 107textcsv xs 107tiehash 104timehires 19725win32 047xsloader 016base 218bytes 104constant 125integer 100overload 118overloading 002sort 201strict 107unicoreheavypl unknownunicorelibperlwordpl unknownunicorelibperl perlidspl unknownutf8 109utf8 heavypl unknownvars 102warnings 113warningsregister 102condition 0 shows the complete dataset and is fine condition 1 is just some compound condition and works fine condition 2 is the opposite condition basic logic rules used to invert it and works fine too yet condition 3 should be the opposite of 2 and thus equal to 1 but the result is the same as 2 i cannot make any sense of this condition 4 shows that omitting the parentheses not does work fine but of course this query is different from any of the previous ones conditions 5 and 6 show a situation where not acts exactly as one would expect so why not on a compound condition acts as if the not were not specified at allby the way i read this scary post perl dbdcsv sql syntax and clause is not working properly and added develversiondump to check whether i have a similar issue but it seems to me that all relevant packages are the newest available hence i really have no clue about this,['sql'] +688124,compile ruby 20 errors without rvm or rbenv readlinec188626 error function undeclared first use in this function i want to install gitlab which do not recommend to use any ruby version managerbut this is my os linux dqadev 313024generic 46ubuntu smp thu apr 10 190814 utc 2014 i686 i686 i686 gnulinuxlinking sharedobject psychsoinstalling default psych librariesmake2 leaving directory homepocruby200p451extpsychmake2 entering directory homepocruby200p451extptycompiling ptycptyc in function chfuncptyc14312 warning ignoring return value of seteuid declared with attribute warn unused result wunusedresult seteuidgetuid linking sharedobject ptysoinstalling default pty librariesmake2 leaving directory homepocruby200p451extptymake2 entering directory homepocruby200p451extracparsecompiling cparseclinking sharedobject racparsesoinstalling default cparse librariesmake2 leaving directory homepocruby200p451extracparsemake2 entering directory homepocruby200p451extreadlinecompiling readlinecreadlinec in function init readlinereadlinec188626 error function undeclared first use in this function rl pre input hook function readline pre input hook readlinec188626 note each undeclared identifier is reported only once for each function it appears inreadlinec188636 error expected expression before token rl pre input hook function readline pre input hook readlinec at top levelreadlinec5301 warning readline pre input hook defined but not used wunusedfunction readline pre input hookvoid make2 readlineo error 1make2 leaving directory homepocruby200p451extreadlinemake1 extreadlineall error 2make1 leaving directory homepocruby200p451make buildext error 2,['ruby'] +688137,how can we remotely thismiss a push notification my app daily broadcasts a push notification pn to all users which becomes irrelevant after 4 hours is there any way i can remove that notification on every users notification centre that has not tapped it within those 4 hoursi used to think this is not possible yet but became hopeful after seeing the googles hangout app behaviour it sends pn to mac ios and if i read the message on mac it automatically immediately removes it from ios notification centeri did extensive research on google surprisingly found nothing on this just one question here which has been duly closed,['ios'] +688164,error ld library not found for lpods with cocoapods after i installed dtcoretext with cocoapods i always get an error when i try to run the simulator or deviceld warning directory not found for option lusersexampledesktopiospodsbuildreleaseiphoneosld warning directory not found for option lusersexampledesktopiospodsbuilddebugiphoneosld library not found for lpodsexampleclang error linker command failed with exit code 1 use v to see invocation in my link binary with libraries the libpods part is redhere are my build settingsthe settings of my projectthe settings of my podseditia m not exactly sure what was the problem but i solved it when i deleted all the dtcoretext and cocoapods stuff and reeinstalled everything again,"['ios', 'objective-c']" +688167,how to pass stdin to child process void writetopipevoid read from a file and write its contents to the pipe for the childs stdin stop when there is no more data dword dwread dwwritten char chbufbufsize bool bsuccess false char name malloc100fgetsname 100 stdin bsuccess writefileg hchildstd in wr name 10 dwwritten null if bsuccess errorexitvoid readfrompipevoid read output from the child proces pipe for stdout and write to the parent proces pipe for stdout stop when there is no more data dword dwread dwwritten char chbufbufsize bool bsuccess false handle hparentstdout getstdhandlestd output handle bsuccess readfileg hchildstd out rd chbuf bufsize dwread null if bsuccess dwread 0 return 100 bsuccess writefilehparentstdout chbuf dwread dwwritten null if bsuccess return 101the main not fullwhile 1 sleep500 readfrompipe writetopipei am trying to open the cmd as a child process and to pass the parent input to the child stdin stream and than to print the stdout of the childas you can see it works at the first time but then i get this more back from the child process the cmd and then it gets stuck waiting for output why am i getting this more backwhat is that more,"['c++', 'c']" +688179,gap between border and image when border radius is added i have an image with a border radius of 50 and a 3px border around itmy problem is when the border radius is given there is a 1px gap between the image and the borderissue is demonstrated in the below imageand the css i am usingimg border 3px solid 4cb7ac height 46px width 46px borderradius50note that the image size is 46px x 46px not resizedand i have to use img to get the image setting it as a background image is ruled outsolution must be compatible with all browsers even ie8is there a way to remove that gapedit js fiddle link,"['html', 'css']" +688375,adding multiple require options for angular directive usually in directives i use require ngmodel if i want to pass the scope to it this works fine but i am now creating a directive that creates 5 different html elements each with different ngmodels that is passed from parent the ngmodels that needs to be passed as attribute are ngmodel1 ngmodel2 ngmodel3 ngmodel4 ngmodel5 how do i add multiple options in the require condition inside the directivei tried these and it doesnt workrequire ngmodel1 ngmodel2 ngmodel3 ngmodel4 ngmodel5andrequire ngmodel1 ngmodel2 ngmodel3 ngmodel4 ngmodel5andrequire ngmodel1 ngmodel2 ngmodel3 ngmodel4 ngmodel5andrequire ngmodel1 ngmodel2 ngmodel3 ngmodel4 ngmodel5how do i add multiple require optionsedithtml codediv getvehiclescheckbox carsngmodelformdatacars bikesngmodelformdatabikes trucksngmodelformdatatrucks vanngmodelformdatavan busngmodelformdatabus divdirectiveappdirectivegetvehiclescheckbox functioncompile return restrict a replacetrue require scope carsngmodel bikesngmodel trucksngmodel vanngmodel busngmodel controller somecontroller link functionscope element attrs carsngmodel bikesngmodel trucksngmodel vanngmodel busngmodel scopecarsngmodel scopebikesngmodel scopetrucksngmodel scopevanngmodel scopebusngmodel var html span ngrepeatcar in cars input typecheckbox ngmodelcarsngmodelcarcode carnumber cardescription span span ngrepeatbike in bikes input typecheckbox ngmodelbikesngmodelbikecode bikenumber bikedescription span etc etc compile html,['javascript'] +688394,how to prevent python requests from percent encoding my urls i am trying to get an url of the following format using requestsget in pythonkeysitedummytypeexamplegroupwheelusrlocalbinpythonimport requestsprintrequests versiom url payload format json key sitedummytypeexamplegroupwheelr requestsgeturl paramspayloadprintrurlhowever the url gets percent encoded and i do not get the expected response221formatjsonthis works if i pass the url directlyurl keysitedummytypeexamplegroupwheelr requestsgeturlis there some way to pass the the parameters in their original form without percent encodingthanks,['python'] +688397,controller as vs isolate scope i would like to use the controlleras option in my directives let me cite the reasoning from an angularjs style guide for closure users at googlewhy putting methods and properties directly onto the controller instead of building up a scope object fits better with the google closure class style additionally using controller as makes it obvious which controller you are accessing when multiple controllers apply to an element since there is always a in the bindings you do not have to worry about prototypal inheritance masking primitivesbut i can see an issue with using this approach if the directive has isolate scope bindingsangularmodulecmwdirectivefoowidget function return controller function thisqux 123 controlleras foowidget scope bar template foowidgetqux bar in this case the bar property is attached to the scope not to the controller which results in a confusing inconsistent situation where different properties should be looked for in different places what is the official recommended way to work around thisupdate see the github issue about this,['javascript'] +688529,add hashkey to object in angular the angularspecific property on enumerated objects hashkeycan be used for a lot of thingsfor example domtargetingdiv ngrepeatobj in objects label forfieldobjhashkey label label input typetext idfieldobjhashkey divin some weird case i am experiencing now the hashkey prop is not yet set on a object i want to access it on even though it is being repeated with angularis there a way to set this property yourself when initializing the objectedit my guess is that there is some form of execution order issue that i access the property when angular has yet to process the repetitioni am deep watching an object within that object is an array with objects which is getting repeated it is also on one of those objects that i need to access the hashkey property onsimple examplevar mycontroller functionscope obj scopeobj list obj obj obj obj scopewatchobj function var lastobj scopeobjlistscopeobjlistlength 1 consoleloglastobjhashkey undefined true scopeaddobj function scopeobjlistpushnew obj edit2 jsfiddle,['javascript'] +688615,visual studio javascript breakpoint possible to set a breakpoint for the code block of javascript like the screenshot belowhow can we use them vs always ignores,"['javascript', 'asp.net']" +688625,ninjecthttpapplication does not work after porting to web api 2 i have ported my web api application to web api 2 and installed ninject web api pacckage but now i am getting an errorerror activating modelvalidatorprovider using binding from modelvalidatorprovider to ninjectdefaultmodelvalidatorprovidera cyclical dependency was detected between the constructors of two services,"['c#', '.net']" +688626,css opacity not working in ie11 i am trying to make the backgroundcolor of a tr opaque with this cssfaded backgroundcolor red height 100px opacity 04 filter alphaopacity50here is my test htmltable tr classfaded tddivtesttesttesttesttdivtd tddivtesttsttesttestdivtd trtableeverything works fine in ie910 ff24 chrome 31 but not in ie11 please keep in mind that i do not care about the content of the table rows only the background opacity screenshots and jsfiddle belowie10ie11so whats going on hereedit i have submitted a bug report to microsoft edit 2 this bug was confirmed by microsoft,"['html', 'css']" +688639,android multiple fragment transaction ordering i have a horizontalscrollview containing a horizontal linearlayout which i use as the container for adding multiple fragments upon some changes i need to remove all fragments from that container and add new ones however there seems to be a problem with ordering when i am removing the old fragmentshere are the scenariosapp startupcorrectly adding fragments a1b1c1d1 in this orderchange contentif not removing initial fragments but adding a2b2c2 as a single transaction it will show a1b1c1d1a2b2c2if removing initial fragments either as a separate or using the same transaction then adding a2b2c2 it will show c2b2a2for now i found a workaround where i am adding the new fragments first then removing the old ones still as part of the same transaction and that is working properlyedit the workaround does not work all the timei am using androidsupportv4appfragment any ideas on whats happening,['android'] +688790,thistinct on postgresql json data column trying to do thistinct on a mode with rails211 450 uprofilesselectprofilesthistinctprofile load 09ms select thistinct profiles from profiles inner join integration profiles on profilesid integration profilesprofile id inner join integrations on integration profilesintegration id integrationsid where integrationsuser id 1 user id 2pgundefinedfunction error could not identify an equality operator for type jsonline 1 select thistinct profiles from profiles inner join integ select thistinct profiles from profiles inner join integration profiles on profilesid integration profilesprofile id inner join integrations on integration profilesintegration id integrationsid where integrationsuser id 1activerecordstatementinvalid pgundefinedfunction error could not identify an equality operator for type jsonline 1 select thistinct profiles from profiles inner join integ select thistinct profiles from profiles inner join integration profiles on profilesid integration profilesprofile id inner join integrations on integration profilesintegration id integrationsid where integrationsuser id 1 from usersmmahalwyrvmgemsruby211gemsrackminiprofiler091libpatchessql patchesrb109in prepare from usersmmahalwyrvmgemsruby211gemsrackminiprofiler091libpatchessql patchesrb109in prepare from usersmmahalwyrvmgemsruby211gemsactiverecord404libactive recordconnection adapterspostgresql adapterrb834in prepare statement from usersmmahalwyrvmgemsruby211gemsactiverecord404libactive recordconnection adapterspostgresql adapterrb795in exec cache from usersmmahalwyrvmgemsruby211gemsactiverecord404libactive recordconnection adapterspostgresqldatabase statementsrb139in block in exec query from usersmmahalwyrvmgemsruby211gemsactiverecord404libactive recordconnection adaptersabstract adapterrb442in block in log from usersmmahalwyrvmgemsruby211gemsactivesupport404libactive supportnotificationsinstrumenterrb20in instrument from usersmmahalwyrvmgemsruby211gemsactiverecord404libactive recordconnection adaptersabstract adapterrb437in log from usersmmahalwyrvmgemsruby211gemsactiverecord404libactive recordconnection adapterspostgresqldatabase statementsrb137in exec query from usersmmahalwyrvmgemsruby211gemsactiverecord404libactive recordconnection adapterspostgresql adapterrb908in select from usersmmahalwyrvmgemsruby211gemsactiverecord404libactive recordconnection adaptersabstractdatabase statementsrb32in select all from usersmmahalwyrvmgemsruby211gemsactiverecord404libactive recordconnection adaptersabstractquery cacherb63in select all from usersmmahalwyrvmgemsruby211gemsactiverecord404libactive recordqueryingrb36in find by sql from usersmmahalwyrvmgemsruby211gemsactiverecord404libactive recordrelationrb585in exec queries from usersmmahalwyrvmgemsruby211gemsactiverecord404libactive recordassociation relationrb15in exec queries from usersmmahalwyrvmgemsruby211gemsactiverecord404libactive recordrelationrb471in load from usersmmahalwyrvmgemsruby211gemsactiverecord404libactive recordrelationrb220in to a from usersmmahalwyrvmgemsruby211gemsactiverecord404libactive recordrelationrb573in inspect from usersmmahalwyrvmgemsruby211gemsrailties404librailscommandsconsolerb90in start from usersmmahalwyrvmgemsruby211gemsrailties404librailscommandsconsolerb9in start from usersmmahalwyrvmgemsruby211gemsrailties404librailscommandsrb62in top required from binrails4in require from binrails4in main211 451 getting an error pgundefinedfunction error could not identify an equality operator for type jsonconverting to hstore is not an option for me in this case any work arounds,['ruby-on-rails'] +689084,why is my entity framework query with single slow i have quite a simple query that is very slow entity framework profiler says it takes about 100 msdbcontextuserssingleu uid useridafter trying around a bit i found a query that is very similar but much faster about 3 msdbcontextuserswhereu uid useridtolistsinglewhen i compare the sql of the two queries the second query does not use a nested select and no top operation but i would not expect it to be 30 times faster just because of these two things also when executing the queries using sql server management studio there is no difference measurablewhen i look at the execution plan they both make a clustered index seek which has 100 query cost whereas the additional select and the top operation have 0 query costthe query plan from efprofiler says the same indicating that it should not make any differencewhat can i do to get a better understanding about the query performance in this casebelow is the resulting sql for the first queryselect limit1id as id limit1emailaddress as emailaddress limit1firstname as firstname limit1lastname as lastnamefrom select top 2 extent1id as id extent1emailaddress as emailaddress extent1firstname as firstname extent1lastname as lastname from dbousers as extent1 where extent1id b5604f883e1842a5a45ec66cc2a632d3 p linq 0 and b5604f883e1842a5a45ec66cc2a632d3 p linq 0 is not null as limit1here the sql of the second faster queryselect extent1id as id extent1emailaddress as emailaddress extent1firstname as firstname extent1lastname as lastnamefrom dbousers as extent1where extent1id b5604f883e1842a5a45ec66cc2a632d3 p linq 0 and b5604f883e1842a5a45ec66cc2a632d3 p linq 0 is not null,['sql'] +689085,how to find and cancel a task in nsurlsession i am using an nsurlsession object to load images in my application that could be loading several images simultaneously in some moments i need to cancel the loading of one specific image and continue loading others could you suggest the correct way to do that,"['ios', 'objective-c']" +689092,how do i simplify this enumerator code i would like to optimize following code for concisenessx1each x x2each y xneach z yield mergexmergey mergez assume x1 x2 xn are enumerator objectsthe above is not conciseit works with x1 x2 as arrays but not as enumeratorsbecause enumerator iterators should be reset for inner loopsi tried this but without successx1 x2 xnreduceproductmap x xreduce merge any recommendationsupdatecurrently solved withx1 x2 xnmapto areduceproductmap x yield xflattenreducemerge,['ruby'] +689168,flattening nested hash to a single hash with rubyrails i want to flatten not in the classical sense of flatten down a hash with varying levels of depth like this foo bar hello world hello world bro whats up dude a b c d down into a hash with one single level and all the nested keys merged into one string so it would become this foo bar helloworld hello world hellobro whats up dude abc dbut i cannot think of a good way to do it it is a bit like the deep helper functions that rails adds to hashes but not quite the same i know recursion would be the way to go here but i have never written a recursive function in ruby,"['ruby-on-rails', 'ruby']" +689243,embed vimeo video with the html5 video element and without iframe i am trying to embed a vimeo video into a webpage using the html5 video element despite vimeos embed code using an iframe i want to use the video element so that i can create a fully responsive webpage including videos but i am having trouble without using html5 i have tried a couple of tools most successfully using fitvidsjs but the responsiveness is not 100 black bars etcis it at all possible to use the html5 video element with a vimeo video ie without an iframe could the vimeo api help me achieve this,['javascript'] +689312,why does not my operation work when i use bigdecimal i am trying to do an operation using bigdecimal but it always return 0 why does it work when i use doublepublic static void mainstring args double a 337688 bigdecimal b new bigdecimala systemoutprintlnaa105 systemoutprintlnbsubtractbdividenew bigdecimal105doublevaluethanks,['java'] +689314,why does default mvc site use async aspnet identity i am just curious why the aspnet mvc website template uses the asynchronous methods for aspnet identity they do not seem to be doing anything that would benefit from using asynchronous methodsfor example why useidentityresult result await usermanagerremoveloginasyncuseridentitygetuserid new userlogininfologinprovider providerkeyinstead ofidentityresult result usermanagerremoveloginuseridentitygetuserid new userlogininfologinprovider providerkeyare not they doing the exact same thing in both instances you are waiting for the identityresult before proceeding to the next line of code correct,"['c#', 'asp.net']" +689415,better to use cgrectgetheightviewbounds or viewboundssizeheight directly in objectivec i cannot find where i read it but i remember coming across something that suggested it is better to access height of cgrects using cgrectgetheightrect instead of accessing the variable via rectsizeheightcgfloat height cgrectgetheightselfframe vs cgfloat height selfframesizeheightmost of the time this has to do with views in my use and i was wondering if there is a real difference apart from syntax that separates these two lines of codeif one is preferential over the other an explanation of why would be great,['objective-c'] +689470,how do i work with precompiled libraries in cython i am trying to compile a quick extension for a module that was precompiled on install pyd below is a simplistic example of what i am trying to do given foopydbazpxdfrom foobar cimport barcdef class bazbar passbazpyxcdef class bazbar def init self a k setuppyfrom thistutilscore import setupfrom cythonbuild import cythonizefrom thistutilsextension import extensionextensions extensionbaz bazpyx librariesfoopydsetupnamebaz ext modulescythonizeextensionsi have tried many variations of the above to no avail,['python'] +689526,error while trying to edit code in debugging mode in vs2013 i am a c programmer and recently i have installed visual studio 2013 the problem is when i set a break point or get an error and trying to edit the codes while debugging i get this error and i could not find the same error searching on googlechanges are not allowed for this module as it was not built for changes while debugging or the target net runtime version does not support iti also tried to check the options on tools options debugging edit and continue but did not help any idea what the problem is,['c#'] +689835,an error occurred while parsing entityname line1 position 844 i have got the following exception from the below code blockan error occurred while parsing entityname line1 position 844i was trying to parse s set of data retrieved from table to a data setpublic dataset bindmasterdatastring xml dataset ds null try ds new dataset textreader txtreader new stringreaderxml xmlreader reader new xmltextreadertxtreader dsreadxmlreader catch exception ex return new dataset return ds i have figured out the reason for the exception but i could not solve it in this particular situation the stringwhich is retrieved from db contains a special character that causes exception how i can solve it any help on this would be greatthanks regardssebastian,['c#'] +689873,using iterators on arrays it is stated in c primer thatin c pointers and arrays are closely intertwined in particular as weall see when we use an array the compiler ordinarily converts the array to a pointeri wanted to use iterators for printing an array the program below works fine but when i try to print arr2 or arr3 if i am not mistaken which is of type int i get an error judging that the operator means reference below error no matching function for call to abeginintaint mainint argc char argv int arr 0123456789 auto arr2 arr auto arr3arr i think arr2 and arr3 are of same type forauto it stdbeginarr it stdendarr it stdcout it stdcout stdendl return 0considering the statement if an array is converted into a pointer by the compiler how does this program work for printing contents of arr using stdbegin and stdend and do not work for arr2 or arr3 if all of them are pointers to integersediti am sorry if i could not make it clear i hope i will clarify the problem by this edit now that i am aware that begin and end would not work with pointers thanks to the answers i wonder if the quoted text is not true as it specifies that there is an array pointer conversion if what text says is true then the type of arr should be a pointer is there a problem with the quoted text at this pointalso is there any way that i can use begin and end for pointers not stl containers with specifying the size possibly using the following constructortemplate class t size t and t begin t arrayn,['c++'] +689881,gradle custom repositories and dependency resolution a project i am developing requires scribejava and crashlytics libraries both libraries are available from custom repositoriesbuildgradle looks likebuildscript repositories maven url dependencies classpath comcrashlyticstoolsgradlecrashlyticsgradle1 apply plugin androidapply plugin crashlyticsrepositories is required by crashlytics library maven url is required by scribe library maven url dependencies compile comandroidsupportsupportv4 compile comcrashlyticsandroidcrashlytics1 oauthoauth2 compile orgscribescribe136 with such a setup repository resolution gets jumbled during the build process such that gradle tries to resolve artifacts from inapropriate repositoriesresource missing http get failed to get resource get http http11 400 bad request resource missing http get failed to get resource get http http11 400 bad request relying on packaging to define the extension of the main artifact has been deprecated and is scheduled to be removed in gradle 20resource missing http get failed to get resource get http http11 400 bad request resource missing http get failed to get resource get http http11 400 bad request resource missing http get failed to get resource get http http11 400 bad request resource missing http get failed to get resource get http http11 400 bad request resource missing http get failed to get resource get http http11 400 bad request resource missing http get failed to get resource get http http11 400 bad request resource missing http get failed to get resource get http http11 400 bad request resource missing http get failed to get resource get http http11 400 bad request resource missing http get failed to get resource get http http11 400 bad request resource missing http get failed to get resource get http http11 400 bad request it tries to retrieve crashlytics files from scribe repository,['android'] +689893,the compiler does not complain when vector is bound to vector i am using visual studio 2013 expressclass bpublic vectorchar a int b bvectorchar iint c aibc int main int l3 vectorchar h shared ptrb bb new bstdmovehl return 0why can the code be acceptedwhen i changed the argument l to stdmovelthe compiler will complain cannot convert argument 2 from int to int,['c++'] +690100,limit parallelism of an async method and not block a threadpool thread i have an asynchronous method requestinternalasync which makes requests to an external resource and want to write a wrapper method which limits a number of concurrent asynchronous requests to the method by reducing parallelismfirst option that comes to mind is a taskscheduler with limited concurrency limitedconcurrencyleveltaskscheduler concurrentexclusiveschedulerpair etcbut to run a task with a custom scheduler i have to start the task using a taskfactory which accepts only action ie i cannot do it by not blocking an extra thread for just waiting for execution of inner methodsecond option is semaphoreslim it does its job but in this case i am implementing throttling myself instead of using a taskschedulerstatic void mainstring args testing 1 var task1 taskwhenallenumerablerange1 10selecti requestasyncbad task1wait testing 2 var task2 taskwhenallenumerablerange1 10selecti requestasyncbetter task2waitprivate static task requestinternalasync return taskdelay500solution 1private static readonly concurrentexclusiveschedulerpair concurrentpair new concurrentexclusiveschedulerpairtaskschedulerdefault 2public static task requestasyncbad dumb because taskfactory does not provide an overload which accepts another task only action as result we blocking a thread to just wait until the inner task finishes return taskfactorystartnew requestinternalasyncwait cancellationtokennone taskcreationoptionsdenychildattach concurrentpairconcurrentschedulersolution 2 betterprivate static readonly semaphoreslim semaphore new semaphoreslim2public static async task requestasyncbetter here we do not waste threadpool thread on waiting for a completion of inner task but instead of using taskscheduler implementing a handmade stuff with semaphore await semaphorewaitasyncconfigureawaitfalse try await requestinternalasync finally semaphorerelease what is the more elegant way to do thisto reuse standard task api of tpl and taskschedulerand not block an extra thread,['c#'] +690156,warning msb3276 found conflicts between different versions of the same dependent assembly my solution consists of multiple projects and compiles fine i am using nuget and one of the packages that i use is log4net200 i have recently updated the package to log4net203 and made sure that in each project that belongs to the solution the reference is updated unfortunately i am still getting the following warning during the compilation processresolveassemblyreferences target cprogram files x86msbuild120binmicrosoftcommoncurrentversiontarge ts16355 warning msb3276 found conflicts between different versions of the same dependent assembly please set the autogeneratebindingredirects property to true in the project file for more information see fwlinklinkid294190or a more elaborate version of this warning when compiling with verbositydetailedconsider appconfig remapping of assembly log4net cultureneutral publickeytoken669e0ddf0bb1aa2a from version 12110 to version 12130 zxpackageslog4net203libnet40fulog4netdll to solve conflict and get rid of warning cprogram files x86msbuild120binmicrosoftcommoncurrentversiontargets16355 warning msb3276 found conflicts between different versions of the same dependent assembly please set the autogeneratebindingredirects property to true in the project file for more information see zxcsproj assemblyfoldersex location registrysoftwaremicrosoftnetframeworkv45assemblyfoldersexi understand what it means unfortunately i cannot track down which projectlibrary still references the old version of log4net i understand that i can mask the warning just by simply remapping in appconfig but it seems like sweeping the problem under the rug rather than actually solving it properlywhat is the best way of tracking down where in my solution i have areference to the old version of log4net i have tried all the obvious including searching through all the files for the version number i also made sure that no other nupkgs have the dependencies set to this specific version of log4netany help would be much appreciated,['.net'] +690239,how to explain object references in ecmascript terms consider thisvar a b ain terms of the spec b a boils down to putvalueb getvaluea right and getvaluea uses getbindingvaluea strictflag abstract operation which returns the value in a and the value is the object originally assigned to a then the object is stored in b just like any other value wouldbut what is the object precisely where does the specification say that values of the object type behave differently than primitives is it only that primitives are immutable and objects are mutablei am asking because we always talk about object references and reference values when trying to explain the behavior of objects but i could not find anything analogous to that in the specification,['javascript'] +690261,make a phone call in windows phone 81 i am writing a universal app for windows 81 windows phone 81 that at some point thisplays a list of phone numbers what i would like to do is allow the user to press one of these numbers and have the device call or ask permission to call that number if running on windows phone 81 i know this was previously possible in windows phone 8 by doing the followingusing microsoftphonetasksphonecalltask phonecalltask new phonecalltaskphonecalltaskphonenumber 20650123phonecalltaskthisplayname gagephonecalltaskshownote this code is wrapped in if windows phone apphowever when trying to import microsoftphonetasks visual studio is unable to find the reference i know that id cap phonedialer had to be enabled in wmappmanifestxml in windows phone 8 but this does not seem to be possible with the universal app model i have been searching around for a solution but cannot find a recent one that includes windows phone 81 not silverlightis there any way to make a phone call from within a universal app or is it simply not possible at the moment,['c#'] +690281,run nvm use automatically everytime there is a nvmrc file on the directory do you how can i configure my shell so that nvm use run automatically everytime there is a nvmrc file on the directory and use the latest version or a global config when there is no nvmrc file,['javascript'] +690331,how to implement a timed loop i need to execute some code 10 times per secondi would like to do something likeset up interval timerwhile 1 wait for timer do somethingmy attempt looks like create timertimer t timeridstruct sigevent sevsevsigev notify sigev signalsevsigev signo sigusr1if timer createclock realtime sev timeridperrortimer createexit1 every one msec 106 nsecstruct itimerspec itsitsit valuetv sec 0itsit valuetv nsec 10itsit intervaltv sec 0itsit intervaltv nsec 10if timer settimetimerid 0 its nullperrortimer settimeexit1 create mask to wait for sigusr1sigset t setsigemptysetsetsigaddsetset sigusr1while 1int sig wait for the timer do this loop once per millisecondsigwaitset sig do somethingwhen i try this i just get user defined signal 1 at the console and my program exits this is not surprising as this is the default action for the signal if i set the signal to sig ign using sigaction2 i never get to my do somethingi presume i need to do something with sigaction2 but i do not see an option for deliver the signal i do not want to ignore the signal or do the default action or call a functionwhats the best way to accomplish my goalor i can just give up and put my do something in a function edit i implemented the timerfd idea and it seems to be working on to the next bug,['c'] +690408,javascript angular how to chain unknown number of promises i am writing an angularjs service to pull some json feeds initially the service does not know whichhow many resources to request they are dependent on ids returned by a another requesti am having a headache chaining the http service requests together is there a commonly used pattern to do thisi have tried the arrayreduce technique suggested on another thread but had problems syncing the ids and the requested datathis is what i have so far does anyone have any suggestionsaservicefactorydummy functionhttp dummy resources var resources return data functioncallback var jquerysources var promisechain httpmethod get url resources0 var l resourceslength for var i 1 i l i promisechainthenfunctiondata jquerysourcespush url resourcesi source data promise chain httpmethod get url resourcesi if i l return callbackjquerysources thankyou,['javascript'] +690416,what to return from nonasync method with task as the return type assume i have a method that is not async but returns a task because the definition is from an interface intended also for async implementationspublic task doworkasyncguid id do the work return what is the best object to return my current optionsreturn taskyieldreturn taskfromresultobjectnull any of the other but cached in a static field and reused,['c#'] +690437,download and install an ipa from url on ios i need to download and install an ipa directly from an urli have tried thisnsurl url nsurl urlwithstringuiapplication sharedapplication openurlurlthe app launches safari but then this message appearsis it possible,['ios'] +690499,glassfish vs tomcat i would like to start using jee6 in the next project that i have to work on at my job but there is also a limitation sort of tomcat 55my question is what improvements would bring glassfish to the table securityspeed vs the existing tomcat55 or an upgrade to the newer version 7,['java'] +690523,how to get enum value by string or int how can i get the enum value if i have the enum string or enum int value eg if i have an enum as followspublic enum testenum value1 1 value2 2 value3 3and in some string variable i have the value value1 as followsstring str value1 or in some int variable i have the value 2 like int a 2how can i get the instance of enum i want a generic method where i can provide the enum and my input string or int value to get the enum instance,['c#'] +690579,printing integer variable and string on same line in sql ok so i have searched for an answer to this on technet to no avail i just want to print an integer variable concatenated with two string variables this is my code that does not runprint there are number alias combinations did not match a recordit seems like such a basic feature i could not imagine that it is not possible in tsql but if it is not possible please just say so i cannot seem to find a straight answer,['sql'] +690627,how to return a resolved promise from an angularjs service using q my service ismyappserviceuserservice http q rootscope location functionhttp q rootscope location var deferred deferred qdefer thisinitialized deferredpromise thisuser access false thisisauthenticated function thisuser first name first last name last email access institution return deferredresolve i am calling this in my config file viamyapprun rootscope userservice functionrootscope userservice return userserviceisauthenticatedthenfunctionresponse if responsedatauser return rootscopebroadcastlogin responsedata else return userservicelogout however it complains that then is not a function are not i returning the resolved promise,['javascript'] +690643,visual studio reference highlighting would not thisable i have thisabled reference highlighting in visual studio 2013 for c code using the instructions here yet i still see references highlighted the fontcolor combination being used does not match the fontcolor setting for highlighted reference the setting is green background with offwhite text and highlighted references appear as white background with offwhite text also the reference navigation does not work as expected pressing ctrlshiftdownup does not do anything indicating the highlighted references feature is turned offhow can i stop the references from being highlighted,['c#'] +690680,custom gitbook themes does anyone know how to modify the look of a git book i have seen 2 books that have a different look from the defaultbut can someone point me in the right direction of how to customize the look andor build a custom theme for gitbooki cannot seem to find any documentation on customizing a gitbook,['css'] +690740,revealjs print to pdf only prints the first slide i am trying to use the pdf export option of revealjs as documented in the repo readmei have the following problemsi do not see an option for layout landscape vs portrait in my chrome print windowprinting only ever prints the first slideno idea what i have done wrong or how to troubleshoot it i am using the latest version of revealjs css etc from github sha 131c00689a4c7a18e5c991fc8102347e4594b5d4 on this example filei am using googlechrome version 3401847132 on ubuntu 1404,"['javascript', 'css']" +690960,simulate a 32bit integer overflow in javascript javascript can handle the following math just finevar result 20 48271 0x7fbut in some programming languages that first intint multiplication results in a value too large to hold in a standard 32 bit integer is there any way to simulate this in javascript and see what the resulting calculation would be if the multiplication resulted in an integer overflow,['javascript'] +691104,aspnetidentity limit usernameindex length how can i limit the usernameindex unique index in the table aspnetusersi am using aspnet identity with a mysql backend and am running up against another instance ofindex column size too large the maximum column size is 767 bytesi have triedmodelbuilderentitysecuserpropertyx xusernamehasmaxlength100modelbuilderentitysecuserpropertyt tidhasmaxlength100i have done all the standardpublic class secuser identityuser required public string fullname get set required public string address get set required public string city get set required public string country get set required public bool agreetermsofserviceprivacypolicy get set required public string basepath get set dbconfigurationtypetypeofmysqlefconfigurationpublic class applicationdbcontext identitydbcontextsecuser public applicationdbcontext basedefaultconnection protected override void onmodelcreatingdbmodelbuilder modelbuilder modelbuilderentitysecuserpropertyx xusernamehasmaxlength100 modelbuilderentitysecuserpropertyt tidhasmaxlength100 baseonmodelcreatingmodelbuilder when i issueupdatedatabase verbosethe output isusing startup project secusing nuget project secspecify the verbose flag to view the sql statements being applied to the target databasetarget database is sec datasource localhost provider mysqldatamysqlclient origin configurationapplying explicit migrations 201405072209015 initialcreateapplying explicit migration 201405072209015 initialcreatecreate table aspnetusers id nvarchar128 not null fullname longtext not null address longtext not null city longtext not null country longtext not null agreetermsofserviceprivacypolicy bool not null basepath longtext not null email nvarchar256 emailconfirmed bool not null passwordhash longtextsecuritystamp longtextphonenumber longtextphonenumberconfirmed bool not null twofactorenabled bool not null lockoutenddateutc datetimelockoutenabled bool not null accessfailedcount int not null username nvarchar256 not null primary key id engineinnodb auto increment0create unique index usernameindex on aspnetusers username desc using hashmysqldatamysqlclientmysqlexception 0x804005 index column size too large the maximum column size is 767 bytesat mysqldatamysqlclientmysqlstreamreadpacketat mysqldatamysqlclientnativedrivergetresultint32 affectedrow int64 insertedidi have also made the changes to allow migration history to workpublic class mysqlhistorycontext historycontext public mysqlhistorycontextdbconnection connection string defaultschemabaseconnectiondefaultschema protected override void onmodelcreatingdbmodelbuilder modelbuilder baseonmodelcreatingmodelbuilder modelbuilderentityhistoryrowpropertyh hmigrationidhasmaxlength100isrequired modelbuilderentityhistoryrowpropertyh hcontextkeyhasmaxlength200isrequired it appears that the entire problem centers aroundusername nvarchar256modelbuilderentitysecuserpropertyx xusernamehasmaxlength100appears to not be working i am using entityframework 610 and microsoftaspnetidentitycore 201so it appears from looking ataspnetidentity limit username lengththat either i am missing something in how i implemented hasmaxlength or there is some other reason why it does not work,['mysql'] +691158,line before and after title over image i want to create a line before and after a centered title the line and text must have a transparent background to be able to position them on a uneven background the line must not be 100 width like thisthe text of the title can changewidth of title is not knownthe title can span on several linesh1 textalign center borderbottom 1px solid 0h1todayh1,['css'] +691187,what data is being signed when you git commit gpgsign i am trying to figure out how to signverify commits by hand but i cannot figure out what data is being signed to create the signature in other words i cannot figure out what data in gpg verify commitsig data needs to beheres the relevant bit of git is source code but i am also new to cheres some example datain a fresh git repo i create a file ledgertxt and commit it with a signed commitgit config global usersigningkey 7e482429git initecho eac5531f38e8967081ae4e77c7aa5fc37e482429 1n ledgertxtgit add ledgertxtgit commit m initial commit gpgsign7e482429and here it is in the loggit log showsignature commit 876793da21833b5b8197b08462523fd6aad3e5ba gpg signature made fri may 9 200155 2014 cdt using rsa key id 7e482429 gpg good signature from dan neumann author dan neumann date fri may 9 200155 2014 0500 initial commitheres the prettyprinted commit object which lives in gitobjects876793da21833b5b8197b08462523fd6aad3e5bagit catfile p 876793da21833b5b8197b08462523fd6aad3e5batree 70e7c184c3a89c749174b4987830c287fd78952dauthor dan neumann 1399683715 0500committer dan neumann 1399683715 0500gpgsig begin pgp signature version gnupg v1 iqecbaabagagbqjtbxqdaaojemeqx8nscqptbih3zcpf0w0xp8hkwz7dtv9bw erczp4upxkv1hgqcxu2rngiuzyablwtis1rcwxovc4dgrxo0f2bip0xnyl3ohju ckh8lhzvvgqvh3dopm0dkoxdawhcjokbyzwbbyjx6whvt8oi7ssymwuf4r610h hkz1xgjo4p1x9wegy296pza1wee6yy9bvvdipjhoqbvkclgfrzvte5pidbraylgf kl2f0k3pebdo6xp0zaml8nyqlfmalcv831hhgumzsbsrpghwnvrdsniltlfjgy bopb2ypptijoxyb66msjqy9glx7n43miu5wmtdk1agqh26oexbsrzcyvflk4w sree end pgp signatureinitial commitand here are the actual contents of the commit object filehexdump gitobjects876793da21833b5b8197b08462523fd6aad3e5ba zlibdecompress bintoasciicommit 6710tree 70e7c184c3a89c749174b4987830c287fd78952dnauthor dan neumann 1399683715 0500ncommitter dan neumann 1399683715 0500ngpgsig begin pgp signaturen version gnupg v1n and iqecbaabagagbqjtbxqdaaojemeqx8nscqptbih3zcpf0w0xp8hkwz7dtv9bwn erczp4upxkv1hgqcxu2rngiuzyablwtis1rcwxovc4dgrxo0f2bip0xnyl3ohjun ckh8lhzvvgqvh3dopm0dkoxdawhcjokbyzwbbyjx6whvt8oi7ssymwuf4r610hn hkz1xgjo4p1x9wegy296pza1wee6yy9bvvdipjhoqbvkclgfrzvte5pidbraylgfn kl2f0k3pebdo6xp0zaml8nyqlfmalcv831hhgumzsbsrpghwnvrdsniltlfjgyn bopb2ypptijoxyb66msjqy9glx7n43miu5wmtdk1agqh26oexbsrzcyvflk4wn sreen end pgp signaturenninitial commitn,['c'] +691201,a first chance exception of type systeminvalidcastexception occurred in windowsbasedll i am getting this exception when binding the itemssource of a listbox to an observablecollectionobjectthe collection is populated with a mix of dependencypropertychangedeventargs evententryi peeked dependencypropertychangedeventargs and foundpublic struct dependencypropertychangedeventargs public override bool equalsobject obj return thisequalsdependencypropertychangedeventargsobj huge cast right here code for evententrypublic class evententry public evententrystring name name name public string name get private set as i read the peeked code it is designed to explode is this right,['c#'] +691234,nullpointerexception at actionbarimplics using app compat on longpress nullpointerexception when longpress over fieldcompile comandroidsupportappcompatv7191xmledittext androidididfield stylestylefield androidtextsize20sp androidhintstringhint androidnextfocusdownidotherstylestyle namefield parentthemeappcompatlight item nameandroidlayout widthfill parentitem item nameandroidlayout heightwrap contentitem item nameandroidtextsize14spitem item nameandroidtextcolorcolorblueitem item nameandroidsinglelinetrueitem item nameandroidgravitycenter verticalitem item nameandroidinputtypetextcapcharacterstextnosuggestionsitem item nameandroidimeoptionsactionnextitem item nameandroidpopupbackgroundcolorwhiteitemstylelogcatjavalangnullpointerexception at androidsupportv7appactionbarimplicsgetthemedcontextactionbarimplicsjava302 at androidsupportv7appactionbarimpljbgetthemedcontextactionbarimpljbjava20 at androidsupportv7appactionbaractivitydelegategetactionbarthemedcontextactionbaractivitydelegatejava208 at androidsupportv7appactionbaractivitydelegateicsonactionmodestartedactionbaractivitydelegateicsjava195 at androidsupportv7appactionbaractivitydelegateicswindowcallbackwrapperonactionmodestartedactionbaractivitydelegateicsjava359 at comandroidinternalpolicyimplphonewindowdecorviewstartactionmodephonewindowjava2437 at comandroidinternalpolicyimplphonewindowdecorviewstartactionmodeforchildphonewindowjava2362 at androidviewviewgroupstartactionmodeforchildviewgroupjava665 at androidviewviewgroupstartactionmodeforchildviewgroupjava665 at androidviewviewgroupstartactionmodeforchildviewgroupjava665 at androidviewviewgroupstartactionmodeforchildviewgroupjava665 at androidviewviewstartactionmodeviewjava4554 at androidwidgeteditorstartselectionactionmodeeditorjava1551 at androidwidgeteditorperformlongclickeditorjava859 at androidwidgettextviewperformlongclicktextviewjava8373 at androidviewviewcheckforlongpressrunviewjava18441 at androidoshandlerhandlecallbackhandlerjava733 at androidoshandlerthispatchmessagehandlerjava95 at androidoslooperlooplooperjava136 at androidappactivitythreadmainactivitythreadjava5102 at javalangreflectmethodinvokenativenative method at javalangreflectmethodinvokemethodjava515 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava785 at comandroidinternaloszygoteinitmainzygoteinitjava601 at dalviksystemnativestartmainnative method,['android'] +691272,rpg storing player data for semicomplex tree structure i am making a web rpg in js using melon js and sql db with php this question is about how to store completed and current tasks per nonplayer character npcnpc dialog and task data all dialog is stored in a js object in the following structurevar dialog quests quest1 npcname joe taskname 1 introductions english hello here is some dialog more dialog stored in array so i can cycle through it more items per task more tasks per npc more npcs per quest more quests options per quests more options in dialog besides quests if i wanti am not storing all map dialogs in the same file because the file would get too cluttered so instead when the map changes i use js require to load in a new js file with a new set of dialogloadnpcdialog function dialognumber requiredialognpc dialog level dialognumber js functiondialog task number when a new npc is created class gamenpcentity i create a local variable per that instance of npc called tasknum set to 0 when they complete a task i just access and increment that npcs task number gameplayer megamegetentitybynamegamedatacurrnpc0 gameplayertasknumfor this rpg i want to achieve the followinggtastyle free world quest queue level progression quest progression and task per npc progression is linear complete level 1 to go to level 2 etc but for each quest a set of npcs are generated you can think of them as subquests each containing 1 through and tasks i want to build in quest queue flexibility that allows the player to talk to any of the generated npcs in any order and complete the tasks in linear order task 1 then 2 then 3 this is like gta style because the overall game follows a linear progression but gives you the flexibility to start any quest you want by talking to random people in the worldgame data the game should store the current and completed level quest names per level npc names per quest and tasks per npc name for each logged in player id it should load the following tree red completemy questionwhen the game loads it should remember those things i mentioned in the tree above i have set up the db to load level and quest information i just return the current level and quest num from db then loop through the npc dialog structure shown above storing the values in a currentandcompletelevels and currentandcompletequests array up until the loop reaches the current level and quest num from db as well as the players coordinates and experience however since i am allowing the player to start pause then resume any npc task list at any time i cannot really add a npc completed num and tasks completed num column to the database this is because i cannot loop through the npc dialog structure and load in the same way i do for level and quest information because the order in which you complete npc quests is not linear somehow i have to track the completed task num per npc how can i do this i was thinking of creating a new npcdata table to store all npcs in the game then store current task num for that npc but then i would have to create a new entry for any new player who logged into my gameor maybe create two db columns in userstats table currnpc and currtask then loop through an associative array storing all tasks per npc but then i would need to have a column for each completed npc and the completed tasks per npc oy my head is spinningcurrent db schema,"['javascript', 'php', 'mysql']" +691347,nancyfx set default charset to utf8 i have this snippet in my cshtml fileexpires on modelenddatetostringm dd yand i get this in the responsehttp11 200 okcontenttype texthtmlexpires on 3i123i123a 05 2013how do i tell nancy to use utf8 by default for responsesedit to clarify this is not a localization problem the output is already localized it is just that the localized utf8 string is sent to the client without a utf8 charset declaration so it gets mucked up in an attempt to treat it as latin1what i am looking for is thishttp11 200 okcontenttype texthtml charsetutf8and i would like to not have to specify it for each response individuallyi am using the nancyfx web framework,['c#'] +691367,find index of maximum element in x86 simd vector i am thinking of implementing 8ary heapsort for uint32 ts to do this i need a function that selects the index of maximum element in a 8element vector so that i can compare it with parent element and conditionally perform swap and further siftdown steps8 uint32 ts can be changed eg to 16 uint32 ts or 8 uint64 t or whatever x86 simd could support efficientlyi have some ideas on how to do that but i am looking for something faster than nonvectorized code especially i am looking for something that would enable me to do fast heapsorti have clang 33 and core i74670 so probably i should be able to use even the newest x86 simd thingiesbtw that is a part of a bigger project and there is for example quaternary heapsort so after implementing simd heapsort i could instantly compare themto repeat question is whats the most efficient way to compute index of maximum element in x86 simd vectorpsit is not a duplicate of linked questions notice that i am asking for an index of a maximum element not just the element value,['c++'] +691373,postsharp alternative i just tried to learn about postsharp and honestly i think it is amazingbut one thing that it is difficult for me how a pure dependency injection not service locator cannot be done in postsharp aspects perhaps in my understanding as a result of compile time weavingcame from php background symfony has jmsaopbundle which still allows dependency to be injected to it is interceptordoes net have some libraries with same capabilityor am i missing something with postsharp,"['c#', '.net']" +691390,threads limit on android is there any threads limit on androidi am creating a lot of threads in the app and thread count is unknown in compiletime how can i get allowed threads counti am getting0511 162419441 13194 edalvikvmi1 thread creation failed errinvalid argument0511 162419461 13131 alibci1 fatal signal 11 sigsegv at 0x010 code1 thread 131 idmykeyboardit is not a good idea to handle exception as i have to choose another approach to deal with it and approach depends on max threads limit,"['java', 'android']" +691417,get data attribute in my html i have a span elementspan classfield datafulltextthis is a span elementthis is aspanand i want to get the datafulltext attribute i tried these two ways but they did not work the both return undefinedfieldhoverfunction consolelogusing prop thispropdatafulltext consolelogusing data thisdatafulltextthen i searched and found these questions how to get the dataid attribute using jquery and jquery cant get data attribute valuethe boths answers are use attrdatasth or datasthi know that attr is deprecated in jquery10 which i use but however i tried itand it workdedcan someone explain why,"['javascript', 'jquery', 'html']" +691455,laravel inserting into a threeway pivot table summaryi am building a music thiscovery service my question is how do i insert data into the threeway pivot table tag track user schemai have this schema seen here at laravelsdit comprises of six main tables and a few othersartists albums tracks tags users and tag track userthe artistsalbumstracks relationship is straightforward and as youd expecttags tracks and users all relate to oneanother as no two can exist without the thirdrelationshipsartists hasmany albumsalbums hasmany tracks and belongsto an artisttracks belongsto albumstracks belongstomany tags and belongstomany an userstags belongstomany tracks and belongstomany an usersusers belongstomany tags and belongstomany an tracksmodelsuser modelpublic function tags return thisbelongstomanytag tag track user user mdbid tag mdbidwithpivottrack mdbid return illuminatedatabaseeloquentrelationsbelongstomany public function tracks return thisbelongstomanytrack tag track user user mdbid track mdbidwithpivottag mdbidthe tag and track model contain the same respective relationshipsquestionso my question ishow do i insert data into the tag track user table the tag track user table is a 3way pivot table cointaining information about tracks that users have taggedyou have to be logged in to tag a track which means i have access to the useras id the tracks id is accessed as i am thisplaying it on the page where the form is contained the tag on the other hand if it already exists in the tags table i want to get itas id and reuse that as they are unique if not i want to create it assign it an id and insert that into the tag track user tablei need to check whether the tag existsif it does get it is idinsert data into the tag track user tablethank youany help i receive on this is greatly appreciated,['mysql'] +691460,uiview background color always black when i add a uiview to a view controller programmatically i am not able to change the background color to any other color it always remains black voiddrawrectcgrectrect drawing code selfbackgroundcolor uicolor bluecolor uibezierpath path uibezierpath alloc init path movetopointcgpointmake100 33 path addlinetopointcgpointmake200 33 pathlinewidth 5 uicolor redcolor setstroke path strokewhen i comment drawrect out and add selfbackgroundcolor uicolor bluecolor to the initializer the color changes idinitwithframecgrectframe self super initwithframeframe if self initialization code selfbackgroundcolor uicolor bluecolor return selfwhy is this and what do i need to change actually i would like the background to be transparent,"['ios', 'objective-c']" +691509,how do stack overflow desktop notifications work perhaps this is a fairly big and ambiguous questionin the stack overflow chatrooms there is a button to enable desktop notifications which will show something in the system tray when someone replies to youby what mechanism does this work it is always made me curious how does a website access the system tray,"['javascript', 'html']" +691564,unable to obtain zoneddatetime from temporalaccessor using datetimeformatter and zoneddatetime in java 8 i recently moved to java 8 to hopefully deal with local and zoned times more easilyhowever i am facing an in my opinion simple problem when parsing a simple datepublic static zoneddatetime convertirafechastring fecha throws exception datetimeformatter formatter datetimeformatterofpattern constantesfechasformato diawithzone obtenerzonahorariaservidor zoneddatetime resultado zoneddatetimeparsefecha formatter return resultadoin my casefecha is 15062014constantesfechasformato dia is ddmmyobtenerzonahorariaservidor returns zoneidsystemdefaultso this is a simple example however the parse throws this exceptionjavatimeformatdatetimeparseexception text 15062014 could not be parsed unable to obtain zoneddatetime from temporalaccessor iso resolved to 20140615 of type javatimeformatparsedany tips i have been trying different combinations of parsing and using temporalaccesor but without any luck so farbest regards,['java'] +691570,std algorithms with pointer to member as comparatorkey i often find myself using stdsort stdmax element and the like with a lambda that simply invokes a member functionstdvectormytype vec populateauto m stdmax elementstdbeginvec stdendvec const mytype a const mytype b return aval bvalthis feels like a waste of characters and a loss of clarity i am aware that i could write another functioncallable and pass a function pointercallable object to these algorithm functions but i often need to do this sortby just once in a program and it does not strike me as a good way of addressing the problem what i want to do ideally is sayauto m stdmax elementstdbeginvec stdendvec mytypevaland have the objects be sorted by their vals is there some part of the stdlib i am overlooking that could assist me with this or another simple way of doing it i would like to make what this is sorting or searching by as obvious as possiblei am aware that just mytypeval is not enough i am looking for something that could perhaps wrap it or provide a similar functionality without obscurring the meaning,['c++'] +691615,android studio keep saying failed to complete gradle execution everything fine with the command linegradle buildbut android studio keep saying thatfailed to complete gradle executioncausea fatal exeption has occurred program will exitif i clear all the cache and restart everything will be fine but this dialog will easily comeback again after a build fail i guess that the increment build chain is not good but the message is not helpful at allare there anythings i can do to get a more details message about what going on why androidstudio gradle failed where can i put thing like stacktrace in the preferences of android studio,['android'] +691688,move each character of a div based on mouse movement i am developing a site and i do not know how to create a javascript animation that looks like thisi have a div that have some text on it and when the user moves his mouse over this text i want each character to move independently of each other in order to maintain a certain thistance from it the mouse also i want this animation to have rotation but it is not that important now heres an image explanationheres what i did so farhtmldiv classdiv1hello worlddivjavascriptvar chars div1htmlsplitdiv1emptyforvar i 0 i charslength i div1appendspan classlettercharsispanjsfiddlecan someone help me to achieve this effect i do not know how to proceed and there is no site or answer that helped me you can use jquery or pure javascript but please keep it simple thank you,"['javascript', 'jquery']" +691812,springboot how to properly inject javaxvalidationvalidator i have got a problem injecting the validator into the spring application bean when attempting to validate a model using jsr303 hibernatevalidator my main configuration class isenableautoconfigurationenablewebmvc enablejparepositoriescomexampleentityscancomexamplepublic class mainconfiguration according to the javadocs provide a custom link validator instead of the one created by default the default implementation assuming jsr303 is on the classpath is link orgspringframeworkvalidationbeanvalidationlocalvalidatorfactorybean leave the return value as code null to keep the default validator getvalidatorhibernatevalidator is on the classpathi am trying to inject it into the repositoryrepositorypublic class userrepositoryimpl implements userrepositorycustom autowired private validator validatorexception being thrown no qualifying bean of type javaxvalidationvalidator found for dependencyupdatethe partial workaround for this is to define this in the main configuration class bean public validator validator return new orgspringframeworkvalidationbeanvalidationlocalvalidatorfactorybean but integration tests the ones which require orgspringframeworktestcontextwebwebappconfiguration annotation and use validation logic fail,['java'] +691824,parallel execution with stackexchangerethis i have a 1m items store in listperson which i am serializing in order to insert to rethis 28i divide work among 10 tasks where each takes its own section list is thread safe for readonly it is safe to perform multiple read operations on a listsimplification examplefor items100 threads10 each task will capture its own page and deal with the relevant rangefor exaple void main var items100 var threads10 var page4 listint lst enumerablerange0itemstolist for int i0i itemsthreads i lstpageitemsthreadsidump page0 will deal with 0123456789page4 will deal with 404142434546474849all oknow back to serethisi wanted to implement this pattern and so i did with items10my testing here is dbsize checking each second as you can see 1m records were added via 10 threadsnow i do not know if it is fast but when i change items from 1m to 10m things get really slow and i get exception the exception is on the for loopunhandled exception systemaggregateexception one or more errors occurred systemtimeoutexception timeout performing set urnuser288257 inst 1 queu e 11 qu0 qs11 qc0 wr00 in00 at stackexchangerethisconnectionmultiplexerexecutesyncimpltmessage messa ge resultprocessor1 processor serverendpoint server in cteamcitybuildagen twork58bc9a6df18a3782stackexchangerethisstackexchangerethisconnectionmultip lexercsline 1722 at stackexchangerethisrethisbaseexecutesynctmessage message resultproces sor1 processor serverendpoint server in cteamcitybuildagentwork58bc9a6df 18a3782stackexchangerethisstackexchangerethisrethisbasecsline 79 press any key to continue questionis my way of dividing work is the right way fastesthow can i get things faster a sample code would be much appreciatedhow can i resolve this exceptionrelated info gcallowverylargeobjects enabledtrue is present in appconfig otherwise i am getting outofmemoryexception also build for x64bit i have 16gb ssd drive i7 cpu,['c#'] +691911,c arguments heap vs stack suppose i create two vectors one on the heap and one on the stackvectorint vector1vectorint vector2 new vectorinti then pass vector1 into two functions say foo1vectorint and foo2vectorint i also pass vector2 into foo3vectorintsince i am new to c i am rather confused by the difference in behaviours here am i right to say that for foo1 the entire vector1 gets copied and for foo2 only the reference to vector1 gets passed into the function but is not vector1 declared on the stack supposed to be inaccessible anywhere else ie from inside foo2 except the scope in which it was createdalso does modifying the contents of vector1 inside foo1 foo2 affect the original vector and is vector1 automatically destroyed at the end of its scope or do we have to delete it manually,['c++'] +691925,does vc have a compile option like fexeccharset in gcc to set the execution character set gcc has finputcharset fexeccharset and fwideexeccharset three compile options to specify particular encodings involved in a compile chain like the following finputcharset fexeccharset or source compiler exe fwideexeccharset reference gcc compiler optionsi found a question about finputcharset here specification of source charset encoding in msvc like gcc afinputcharsetcharseta but i want to know whether vc has a compiler option like fexeccharset in gcc to specify the execution character seti found a seemed relative option in visual studio project propertiesconfiguration propertiesgeneralcharacter set and the value is use unicode character set does it do the same thing as fexeccharset in gcc in that way i want to set the execution character set to utf8 how towhy i want to set the encoding of the executioni am writing an application in c which needs to communicate with a db server and the charset of the tables is utf8 after i build some tests the tests will catch exceptions thrown around insertion operations on db tables the exceptions tell me that they meet incorrect string values i suppose that it is caused by the wrong encoding right btw are there any other ways to handle this issue,['c++'] +691958,why are awaiters asyncawait structs and not classes can classes be used why are the awaiters getawaiter to make a class awaitable structs and not classes does it harm to use a class public struct configuredtaskawaiter icriticalnotifycompletionpublic struct yieldawaiter icriticalnotifycompletionpublic struct taskawaitertresult icriticalnotifycompletion,"['c#', '.net']" +692000,make custom intermediate improve c compilable tester in cmake so we have mixed cc projects i want to enforce that even if all source files are cpp c compiled that source files with the h extension are c compileable using hpp for c only files i would like to enforce it at compile time such that the build returns an error associated with the project with full line numbers and c error and warnings running at configure time is imho achieves limited resultsso i currently have a script that will do thatcmake minimum required version 28macromake c compile tester project name target sources cvarsetcmake configurable file content foreachsrc target sources messagestatus testing src src get filename componentsrc ext src ext messagestatus src extsrc ext ifsrc ext strequal h setcmake configurable file content cmake configurable file contentninclude src endifendforeachsetcvar project name binary dirproject name ccompiletestcconfigure filecmake rootmodulescmakeconfigurablefilein cvar onlyset source files propertiescvar properties generated trueendmacrousagecmake minimum required version 28includemake c compile testercmakeprojectplaylibadd definitionsdplay lib exportssetproject name src list play libh play libhpp play libcpp testc testlibhmake c compile testerproject name project name src list project name ctesteradd libraryproject name shared project name src list project name ctesterthis works but is a little more invasive than i want it requires multiple lines and if the src list is not a single variable than you may have more work than you want in addition it adds the c file which could be confusing to peoplewhat i would prefer is that i build project name ccompiletestc as an intermediate it is not included as a source file in the directory and can be added as a single line to existing files something likesetproject name src list play libh play libhpp play libcpp testc testlibhadd libraryproject name shared project name src listmake c compile testerproject namethis way it can be quickly added to all existing projects as well as future projects i know i can extract the source list using get target propertiesvar project name sources and i think is can do it with add custom commandtarget project namebut i do not know how to do it in a crossplatform dependencyefficient way any ideas how to compile a c file to a o or i without linking or including the source file in the projectedit possible solution path that i have not figured out completely yet so obviously the following code does not work setmycompile cmake c compile object stringregex replace cmake c compiler cmake c compiler mycompile mycompile stringregex replace flags flags mycompile mycompile stringregex replace mycompile mycompile stringregex replace mycompile mycompile setmycompile macroadd compile file command source get filename componentsource base name source name we setflags confignonecmake c flagsconfigdebugcmake c flags debugconfigreleasecmake c flags releaseconfigrelwithdebinfocmake c flags relwithdebinfoconfigminsizerelcmake c flags minsizerel setobject cmake current binary dirsource base nameo get propertyproject name compile definitions none directory cmake current source dir property compile definitions get propertyproject name compile definitions debug directory cmake current source dir property compile definitions debug get propertyproject name compile definitions release directory cmake current source dir property compile definitions release get propertyproject name compile definitions relwithdebinfo directory cmake current source dir property compile definitions relwithdebinfo get propertyproject name compile definitions minsizerel directory cmake current source dir property compile definitions minsizerel set defines confignoneproject name compile definitions noneconfigdebugproject name compile definitions debugconfigreleaseproject name compile definitions releaseconfigrelwithdebinfoproject name compile definitions relwithdebinfoconfigminsizerelproject name compile definitions minsizerel add custom commandtarget project name command cmake command e echo defines add custom commandtarget project name post build command mycompile endmacro messagestatus mycompilemycompile messagestatus cmake c compilercmake c compiler get propertycompile definitions directory cmake current source dir property compile definitions messagestatus compile definitionscompile definitions messagestatus compile definitions debugcompile definitions debug get propertycompile definitions release directory cmake current source dir property compile definitions release messagestatus compile definitions releasecompile definitions release messagestatus compile definitions relwithdebinfocompile definitions relwithdebinfo messagestatus compile definitions minsizerel compile definitions minsizerel setcmake configurable file content mycompile configure filecmake rootmodulescmakeconfigurablefilein project binary dircbuildcmake includeproject binary dircbuildcmake add compile file commandproject name ctesterbasically the idea is to look up the c compile command and then actually use it but it is a nightmare getting all the variables set correctly in a nonmake style generator i am currently trying to get it to work with visual studio though a cross platform solution is required,"['c++', 'c']" +692018,change position of spinner dropdown list i need to change the horisontal position of spinners dropdown list heres the screenshot and i want this dropdown list to go in one line under the main icontext so it would look fineas on the picture heres what i do in xml spinner androidididtvheader stylestylespinner style androidlayout widthwrap content androidlayout heightwrap content androidlayout alignbottomidver main donate background tile long androidlayout aligntopidver main donate background tile long androidlayout margintop5dp androidlayout torightofidicon main header androidspinnermodedropdown androiddropdownhorizontaloffset15dp androidgravityleftcenter vertical androidtextstringname of product so as i suppose androidspinnermodedropdownandroiddropdownhorizontaloffset15dpshould do the trick but as you see on the screenshot it does not work,['android'] +692134,intermittent aspnet oauth issue with google authenticationmanagergetexternalidentityasync is returning null i am trying to fix an intermittent issue when using google as an external login provider when attempting to login the user is redirected back to the login page rather than being authenticated the problem occurs on this line line 55 of link below getexternalidentityasync returns nullvar externalidentity await authenticationmanagergetexternalidentityasyncdefaultauthenticationtypesexternalcookiethe full code isauthorizepublic abstract class googleaccountcontrollertuser controller where tuser microsoftaspnetidentityiuser public iauthenticationmanager authenticationmanager get return httpcontextgetowincontextauthentication public abstract usermanagertuser usermanager get set allowanonymous httpget routelogin public actionresult loginstring returnurl viewdatamodel new loginmodel message tempdatamessage as string providers httpcontextgetowincontextauthenticationgetexternalauthenticationtypes returnurl returnurl return view allowanonymous httppost validateantiforgerytoken routelogin public actionresult loginstring provider string returnurl return new challengeresultprovider urlactioncallback account new returnurl returnurl allowanonymous routeauthenticate public async taskactionresult callbackstring returnurl var externalidentity await authenticationmanagergetexternalidentityasyncdefaultauthenticationtypesexternalcookie if externalidentity null return redirecttoactionlogin new returnurl returnurl var emailaddress externalidentityfindfirstvalueclaimtypesemail var user await usermanagerfindbynameasyncemailaddress if user null await signinasyncuser false return redirecttolocalreturnurl else tempdataaddmessage stringformatthe account 0 is not approved emailaddress return redirecttoactionlogin new returnurl returnurl httppost validateantiforgerytoken routelogout public actionresult logoutstring returnurl authenticationmanagersignout return redirecttolocalreturnurl private async task signinasynctuser user bool ispersistent authenticationmanagersignoutdefaultauthenticationtypesexternalcookie var identity await usermanagercreateidentityasyncuser defaultauthenticationtypesapplicationcookie var authenticationproperties new authenticationproperties ispersistent ispersistent authenticationmanagersigninauthenticationproperties identity private actionresult redirecttolocalstring returnurl if urlislocalurlreturnurl return redirectreturnurl else return redirecttoactionindex home protected override void thisposebool thisposing if thisposing usermanager null usermanagerthispose usermanager null basethisposethisposing which is also herethis is very much an intermittent problem and redeploying the app will often get it to work temporarily looking in fiddler i can see a call is made to signgoogle just previous to the authenticate method in which it cannot find the cookie the app uses the following code to initialize the google login appusecookieauthenticationnew cookieauthenticationoptions authenticationtype defaultauthenticationtypesapplicationcookie loginpath new pathstringlogin appuseexternalsignincookiedefaultauthenticationtypesexternalcookieappusegoogleauthenticationi have set the authentication mode to non in the webconfig and removed the forms authentication modulesystemweb authentication modenone systemweb systemwebserver validation validateintegratedmodeconfigurationfalse modules runallmanagedmodulesforallrequeststrue remove nameformsauthenticationmodule modulessystemwebserverthe sites are hosted on azure some running on 1 instance some 2 they have custom domains although still fail on both custom domain and azurewebsites domain and http https can anyone help with why this might be happening updateversion 30 of microsoftowinsecuritygoogle was released last night going to switch over and see if this fixes the issue,['c#'] +692222,nggrid expand and collaspe row i am trying to achieve an expand and collapse row for nggrid basically what we have here detailshtml if you click the plus icon your thisplayed with more detail i have seen a similar question asked here but no solution does anyone know how to achieve thisany help is appreciatedvar app angularexpandmyapp nggridappcontrollermyctrl functionscope scopemydata somedata data to be expanded in another moredata 1 somedata b data to be expanded in another moredata 2 somedata c data to be expanded in another moredata 3 somedata d data to be expanded in another moredata 4 somedata e data to be expanded in another moredata 5 scopegridoptions data mydata scopeexpandrow functione epreventdefault var getdata somedata moredata scopegridoptionsselectitemindex false scopemydataspliceindex 1 0 getdata thisrowelmappenddiv thisrowentitysomedata div script srcscriptscript srcscriptbody ngcontrollermyctrl div classgridstyle nggridgridoptionsdiv button ngclickexpandroweventadd rowbuttonbody,"['javascript', 'jquery', 'html']" +692242,skip bad record in redshift data load i am trying to load data into aws redshift using following commandcopy venue from s3mybucketvenuecredentials aws access key idaws secret access keydelimiter tbut data load is failing when i checked query section for that specific load i noticed it failed because of bad utf8 hex sequence a4 error 3is there a way to skip bad records in data load into redshift,['sql'] +692250,how to select net 452 as a target framework in visual studio i have installed net framework 452 on windows 81 but in visual studio 2013 i do not see the net framework 452 option see screenshot how do i target my project for net 452,['.net'] +692332,how to map to multiple elements with java 8 streams i have a class like thisclass multidatapoint private datetime timestamp private mapstring number keytodataand i want to produce for each multidatapointclass dataset public string key listdatapoint datapointsclass datapoint datetime timestamp number dataof course a key can be the same across multiple multidatapointsso given a listmultidatapoint how do i use java 8 streams to convert to listdatasetthis is how i am currently doing the conversion without streamscollectiondataset convertmultidatapointtodatasetlistmultidatapoint multidatapoints mapstring dataset setmap new hashmap multidatapointsforeachpt mapstring number data ptgetdata dataentrysetforeache string serieskey egetkey dataset dataset setmapgetserieskey if dataset null dataset new datasetserieskey setmapputserieskey dataset datasetdatapointsaddnew datapointptgettimestamp egetvalue return setmapvalues,['java'] +692366,how to justify a single flexbox item override justifycontent you can override alignitems with alignself for a flex itemi am looking for a way to override justifycontent for a flex itemif you had a flexbox container with justifycontentflexend but you want the first item to be justifycontent flexstart how could that be donethis was best answered by this post,['css'] +692400,how to exit the loop in pry if you keep type nyou will be in the loop for 100 timeshow could i leave the each loop and continue to keep debugging from line 7 without exiting the loop then run the remain code automaticallythe behavior of exit are not suit for mebecause i want to keep debugging the code after i exit the loop 1 require pry 2 3 bindingpry 4 1100each do x 5 print x 6 end 7 8 print hi,['ruby'] +692449,use remaining space equally for ncolumns how can i set up a table so that the last and columns use the available width of a table equallyin detaili am generating a html table in the backend aspnet mvc that has two header columns and a varying number of data columnsid region data col 1 data col 2 data col n 1 region name 1 data data data 2 region 2 data data data80 another region data data datathe table has a width100 the first and second column id and region use fixed widthsthe content of the data columns esp the headers can be strings of different lengthhow can i setup the cssjs so that the remaining columns are sized equally wide and use the full remaining width of the tablemy first thought was to simply set style100numberofcolumns on the server however as the first two columns are fixed width and i do not know the size of the table on the server side this approach fails,"['javascript', 'jquery', 'html', 'css']" +692462,mass delete in laravel 41 based on array of ids or objects i just wanted to know if it is possiblei know when you have multiple rows to insert you can just build an array and do something likedbtablesome tableinsertarraybut as far as i have read doing the same for deleting does not seem to be possible i would like to know if anyone know of a way to do something likedbtablesome tabledeletearray,['php'] +692472,what is microsoftbclasync what is microsoftbclasync and what is it used fori have read on the package page thatthis package enables visual studio 2012 projects to use the new async and await keywordsbut as could see my vs2012 supports async and await without any extra packageso should i install the package for my c 45 async project,['c#'] +692583,what is the difference between alias method and alias method chain i was working on my webapplication and i wanted to override a method for example if the original class is class a def foo original endendi want to override foo method it can be done like this class a alias method old foo foo def foo old foo and another foo endendand i can call both old and new methods like this obj anewobjfoo original and another fobjold foo originalso what is the use of alias method chain if i can access and keep both methods like the way i did,"['ruby-on-rails', 'ruby']" +692628,maintain aspect ratio according to width and height it is possible to fit and center a square div in the viewport and always maintain it is aspect ratio according to width and heightrequirements only cssthe size of the square must adapt to the smallest dimension width or height of viewport regardless of the orientation landscape or portrait of the viewportthe square must be centered horizontaly and verticaly in the viewportexample,['css'] +692655,html in chartjs labels i would like to put some images andor links in my charts labels heres the example code and jsfiddlevar data labels january sfebruarys img src a hrefa linka datasets data 65 59 90 81 var ctx documentgetelementbyidmychartgetcontext2dvar mynewchart new chartctxbardatajsfiddle linkas you can see the html is not parsed inside labels is there a way to have working images andor links in the charts labels,['javascript'] +692695,is it possible to get contacts from my skype account in android i have implemented skype videoaudio calling functionality using intent in my application it is working fine but now i want to get all contacts list from skype account is it possible is there any alternate way to show list of contacts of skype account please give any idea,['android'] +692801,accessing stdvector elements via pointers vs end i need to be able to access readonly no resizing involved or anything like that the elements of a an stdvector via pointers egstdvectorint foo10int ptr begin foo0so far so good this is guaranteed to work in the current standard 23361the elements of a vector are stored contiguously meaning that if v is a vector where t is some type other than bool then it obeys the identity vn v0 and for all 0 and vsizeso we can access all elements of the vector using pointers since they are stored in a contiguous chunk of memory but what about the onepastthelast element i mean it is legal to perform this operationint ptr end ptr begin foosizenote i am not trying to access the pastthelast value merely to define a pointer to it an equivalent to fooend if you like the standard mentions only accessing elements via pointer arithmetics but clearly here we are not accessing any elementas a side note the definition of the existence of a pastthelast something seems tightly connected to the base concept of array see for instance 575 but throughout the standard it seems like the concepts of contiguous storage and array are used interchangeably am i reading wrong,['c++'] +692816,user id not thisplaying in google analytics dashboard ios i am trying to link gas user id feature to my ios app but this does not seem to be working from the documentation i enables a user id capable view profile then i set the userid fieldmy codeappdelegatemidgaitracker tracker gai sharedinstance defaulttracker you only need to set user id on a tracker once by setting it on the tracker the id will be sent with all subsequent hitstracker setuid valueuseridtest this hit will be sent with the user id value and be visible in useridenabled views profilestracker sendgaidictionarybuilder createeventwithcategoryuser test event category required actionuser sign in event action required labelnil event label valuenil build event valuehowever in the analytics dashboardi cannot seem to find one place where i can see the user id,['ios'] +692836,menu icon not thisplaying on action bar android studio 058hellofor some reason the icon never thisplays on the actionbar i have used a combination of ifroomwithtext but still does not thisplay i have also tried rotating in landscape i am using genymotion 442xml version10 encodingutf8menu xmlnsandroid xmlnsapp item androidtitlestringnew crime androidididmenu item new crime androidicondrawableic action new appshowasactionalwaysmenui am inflating the menu in a fragment override public void oncreateoptionsmenumenu menu menuinflater inflater superoncreateoptionsmenumenu inflater inflaterinflatermenufragment crime list menu here is a screenshoti have tried hardware nexus5 in portrait and landscape mode but no iconi have also tried using the following but did not work eitherandroidiconandroiddrawableic menu addmany thanks for any suggestions,['android'] +692868,statistic estimation of total nodes in a tree where edge traversal is expensive i have a directed tree and i would like to get its size i have no information about its depth or thistribution of nodes there are two major obstacles1 the tree is very large billions of nodes2 edge traversal is expensiveare there statistical methods i can use to get an estimate of its size number of nodes quickly and with bounded error unfortunately googling just results in exactcount algorithms which would perform poorly given these restrictionsbonusif i relax the constraint from tree to dag directed acyclic graph can i get both its size and number of unique paths eg for this dag every edge points downthere are 19 nodes size and 23 paths 4 extra ones because the red edge gives 1 more path for its destination node and 3 more paths to the children of its destination nodethings i have triedfor the tree case i am thinking of something along the lines ofamounts def estimatehelpernode amountsnodedepthpushlennodechildren for each child in small random sample of nodechildren estimatehelperchilddef estimateroot estimatehelperroot reach 0 for j lenamounts 1 j 0 j avgchildrenpernodeatthislevel avgamountsj reach avgchildrenpernodeatthislevel avgchildrenpernodeatthislevel reach return reachit essentially computes the reach at the deepest nodes of the tree then propagates that back into the level above to find the reach at that level it does that until it eventually finds the reach of the root of the tree i am not sure if i am making any assumptions about a uniform thistribution of nodes or not in the above algorithm to reiterate i do not know what kind of thistribution a given tree will haveassuming it works this also solves the paths for the dag once you have all the paths i am thinking of using the inverse of the birthday paradox to figure out how many unique nodes there are birthday paradox answers how many days paths do we need to choose until we hit a duplicate day with some probability given 365 unique days of the year so we keep trying random paths days until we hit a duplicate node we repeat that several times to find a probability for that event and then we plug it into the birthday paradox to find the number of unique nodes unique days in the year note though that the birthday paradox also makes an assumption of uniformitynone of this is very rigorous what would be ideal is something that gives me an estimate with an error bound and a paper that describes the algorithm with sufficient rigor any pointers in the right direction are very much appreciated,['python'] +692945,gradle exclude specific files inside dependency i was wondering if there was anyway to exclude specific filesthat are inside a dependency not a transitive dependency from being downloaded i am switching a build from ant ivy to gradle and this was done with in ivy before i ask because i have a single dependency that contains many compiled wsdl jars in artifactory that we are pulling down but i do not want to download all of the jars in the dependencyin ivy it was setup likethese 6 artifacts are published to artifactory in to one directory repodeplocationexample73jarpublications artifact namefoo10 typejar artifact namefoo10async typejar artifact namefoo10xml typejar artifact namebar10 typejar artifact namebar10async typejar artifact namebar10xml typejar publicationsthis is how i retrieve only two of the six artifacts dependency orgdeplocation nameexample rev73 confcompileruntime include namefoo10async include namefoo10xmldependencycurrently if i attempt to do something similar in gradle the excludes are ignored and all six artifacts are downloadedcompile groupdeplocation nameexample version73 exclude modulefoo10xml exclude modulebar10 exclude modulebar10async exclude modulebar10xmli am using gradle version 18,['java'] +693019,send mongodb query result as json using express i am writing an application where i use express nodejs and mongodb using mongojs i have a module dbjs and a serverjs which have the snippets belowdbjsvar getusersbycity functioncity callback dbusersfindcity citytoarrayfunctionerr data if err callbackerr consolelogerr else consolelogdata callbackjsondata serverjsapostget users list functionreq res var body reqbody dbgetusersbycitybodycity resit is working because as you can see i am probably incorrectly using callbackjsondata when i should be using callbackdata i think the dbjs module should not be responsible for sending the response and i should pass resjson as the callback to my functionthe problem is when i do things the way i consider right i face the following errorpath to my appnode modulesmongojsnode modulesmongodblibmongodbconnectionbasejs245 throw message typeerror cannot call method get of undefined at resjson path to my appnode modulesexpresslibresponsejs18922 at path to my appdbjs3613 at path to my appnode modulesmongojsnode modulesmongodblibmongodbcursorjs16316 at commandhandler path to my appnode modulesmongojsnode modulesmongodblibmongodbcursorjs70616 at path to my appnode modulesmongojsnode modulesmongodblibmongodbdbjs18439 at serverbase callhandler path to my appnode modulesmongojsnode modulesmongodblibmongodbconnectionbasejs44541 at path to my appnode modulesmongojsnode modulesmongodblibmongodbconnectionserverjs46818 at mongoreplyparsebody path to my appnode modulesmongojsnode modulesmongodblibmongodbresponsesmongo replyjs685 at nullanonymous path to my appnode modulesmongojsnode modulesmongodblibmongodbconnectionserverjs42620 at eventemitteremit eventsjs9517how to properly send the json response without sending the response object to my db moduleps the content of line 36 of dbjs when i make the changes is callbackdata,['javascript'] +693068,how to swich theanotensor to numpyarray i have simple codes as shown belowclass testxxobject def init self input selfinput input selfoutput tsuminputa nparray1 2 3 4 5 6 7 8 9 dtype npfloat32classfier testxxaoutxx classfieroutputoutxx npasarrayoutxx dtype npfloat32however i get the following error informationvalueerror setting an array element with a sequencefurthermore when i use the function of theanotensor it seems that what it returns is called tensor and i cannot simply switch it to the type numpyarray even though what the result should shape like a matrixso that is my questionhow can i switch outxx to type numpyarray,['python'] +693094,why does eclipse automatically add a java super method in a constructor when i use the editors code generator when i write a constructor in my java class i typically do not invoke super in there when i generate the constructor from eclipse source code editor why does it always add the super in there am i wrong for not adding this by default in the constructors i write any thing wrong with leaving the super call in the constructor if i decide to use eclipse code generator,['java'] +693191,how to return the number of affected rows in a hana stored procedure how does one return the number of rows affected from an insert or update statement while inside a sap hana stored procedurein oracle one would use sqlrowcount but i cannot find an equivalent for hana in their documentationfor examplecreate procedure procedure name p inputlanguage sqlscript asbegin define c integer insert into some table values somevalues c sqlrowcountendupdatei found the answer on an sap thread finally you can run this statement after the insert or update to get the rowcountselect rowcount into l c from dummy,['sql'] +693358,custom shaped buttons in android am i doing it right i am trying to implement four custom shaped buttons like you can see in the following picturewhat i did so far i took 4 different pictures each with only one color visible see above the other part of the image is transparent this has the result that i have four pictures with the same sizenow i used a relativelayout where all my 4 pictures are added into imageviews on the same position because of the transparency i can see the desired picturefor my imageviews i have implemented ontouchlistener with the following contentprivate class imageontouchlistener implements viewontouchlistener private int categoryid public imageontouchlistenerint categoryid thiscategoryid categoryid override public boolean ontouchview v motionevent event bitmap bmp bitmapcreatebitmapvgetdrawingcache int x int eventgetx int y int eventgety boolean isinsidebitmap x bmpgetwidth y bmpgetheight x 0 y 0 boolean isactionup eventgetaction motioneventaction up if isinsidebitmap int color bmpgetpixelx y bmprecycle if color colortransparent return false else if isactionup buttonclick else bmprecycle return true this approach works but it consumes a lot of memory as i am always creating a bitmap when i move my finger i am not quite sure if this is the best way to implement this is there anything i can do different which might result in a more efficient way,['android'] +693596,need to log aspnet webapi 2 request and response body to a database i am using microsoft aspnet webapi2 hosted on iis i very simply would like to log the request body xml or json and the response body for each postthere is nothing special about this project or the controller processing the post i am not interested in using logging frameworks like nlog elmah log4net or the built in tracing features of webapi unless it is necessary to do soi am simply wanting to know where to put my logging code and how to get the actual json or xml from the incoming and outgoing request and responsemy controller post methodpublic httpresponsemessage postfrombodyemployee employee if modelstateisvalid insert employee into to database,['c#'] +693735,visual studio cordova ios build server setup i have a problem with finding stuff about how to compile cordova apps from visual studio desktop on my macbook without parallels and similar things i googled that stuff but i found nothing relevant or with parallelsvmware stuffi added some insight what i want to do in my comments yet pasted it herenope i mean i have two devices the desktop where i have windows 81 and a macbook pro mid 2012 and i want to start a build the cordova app from my desktop but run it on my macbook via ios simulator i do not want no dual booting no virtualisation just start the build from visual studio and finish the build on osx,['ios'] +693825,difference between setupclass and setup in python unittest difference between setupclass vs setup in python unittest framework why not do set up part in setup instead of setupclassi want to understand what part of setup is done in setup and setupclass functions as well with teardown and teardownclass,['python'] +693893,single page application cannot get current page meta tag for facebook share hey guys i am trying to implement the facebook share button in my app however i cannot seem to get it to work on and idk why this is what i have so farhtmlpostsomerandomstringdiv idfbrootdivmeta propertyogsite name contentappmeta propertyogurl contentpostdatapermalinkmeta propertyogtitle contentdatatitlemeta propertyogtype contentblogmeta propertyogimage content meta propertyogdescription contentdatapreviewbody scriptfunctiond s id var js fjs dgetelementsbytagnames0 if dgetelementbyidid return js dcreateelements jsid id jssrc connectfacebookneten ussdkjsxfbml1appid580882498674160versionv20 fjsparentnodeinsertbeforejs fjsdocument script facebookjssdkscript this facebook share button does not appear div classfbsharebutton datahref datatypebuttondiv so i manually make one a href ngclickfacebooksharesharea bodycontrollerjsscopefacebookshare function return windowopenencodeuricomponentlocationhref facebook share height320 width640 toolbarno menubarno scrollbarsno resizableno locationno directoriesno statusno it works however it did not read the meta tag i have written above on the html page instead it reads from my index pageindex pagedoctype htmlhtml ngappappmeta charsetutf8meta nameviewport contentwidthdevicewidth initialscale1noscript meta httpequivrefresh content7 style typetextcss pagecontainer thisplaynone style div classpureu1 textcenter titlesymsal oh no we need javascript to work title h3 please enable javascript h3 divnoscript head title ngbindtitletitle some css file headbodydiv classpuretypediv ngcontrollermasterctrldiv idlayout menu toggle a href idmenulink class white menulink spanspan adiv idmenu classpureu1 div ngbindhtmluserviewdiv divdivdiv classpuregrdiv idfeedcontainer classpureu1 slidengviewdivdivdivdiv some javascript files bodyhtmlfacebook debugger,"['javascript', 'html']" +693916,is changing from wcf binding transfermode from buffered to streamed considered a breaking change for the client i have a wcf service endpoint that serves binary documents through a stream the endpoint looks something like thispublic stream getfileint fileidthe basichttpbinding for this service endpoint is configured erroneously to use transfermodebuffered the service endpoint is currently used by integrating parties outside my control due to the memory consumption issues with buffered transfermode i want to change this to transfermodestreamed can i safely do this change on the service binding configuration and expect that this will not break anything for any integrating parties,"['c#', '.net']" +693956,how to solve php ini loaded configuration filenone i am trying to install php from source code but i got a problem herei googled it but nothing useful for mefirst here is my installshmake cleanconfigure prefixusrlocalprogramsphp5 thisablefileinfo withconfigfilepathusrlocalprogramsphp5etcphpini withconfigfilescandirusrlocalprogramsphp5etc withapxs2usrlocalprogramsapache24binapxsif 0 then echo auto installation failed configuration exitfimakeif 0 then echo auto installation failed make exitfisudo make installif 0 then echo auto installation failed configuration exitfiecho copying the min size config filesudo cp phpinicleanbk usrlocalprogramsphp5etcphpiniif a usrbinphp then sudo rm usrbinphp sudo ln s usrlocalprogramsphp5binphp usrbinphpfiphp versionphp iniafter the script is done i got some weird information hereconfiguration file phpini path usrlocalprogramsphp5etcphpiniloaded configuration file nonescan for additional ini files in usrlocalprogramsphp5etcadditional ini files parsed usrlocalprogramsphp5etcphpiniwhy loaded configuration file none is null is there anything wrong during the installation also ls usrlocalprogramsphp5etcpearconf phpini phpinibk,['php'] +694261,set a mailto link with a subject containing an ampersand im using the following mailto link to send an email a clashare3 title hrefmailtosubjectcheckampbodydomainit works well but sometimes my subject will contain an ampersand character and when it does my email is created without a bodyany way to resolve this problem,['html'] +694289,how to create a custom lock screen widget i just want to thisplay a button i need to allow users to quickly capture an image using my app when the device is locked i figure the quickest way for a user to do this is via a buttonwidget on the lock screen although i am not sure how to build thismost references i have found have related to music playback and use of the remotecontrolclient which may be just android 44 at it is most basic i would just like one button that said capture any help on how to do this,['android'] +694308,efficient algorithm to compute the median of pariwise absolute sums of a sorted array i am trying to come up with a fast algorithm to compute the quantity bi med y iy j 1jin when the y 1y n are sorted already so b is a vector of same length as y i will assume that all elements of y are unique and that and is evenso the code below computes the bis the naive on2 wayi wrote this in r for convenience but i am language agnosticn30a fastb slowrepnanysortrnormn1001zyfori in 1n b slowimedianabsyiyi i have a tentative proposal below for doing it in onbut it only works if y contains positive numbers my question is how should i change the fast algorithm to also work when y contains both positive and negative numbers is this even possibleeditand the code below the tentative on wayi wrote this in r for convenience but i am language agnostictryafloor1n121trybfloor1n12medaytryamedbytrybfori in 1trya1 a fastimedayifori in tryan a fastimedbyisimple examplesimple illustrative example if we have a vector of length 43 1 2 4then for example for i1 the 3 absolute pairwise sums are 4 1 1and their median is 1then for example for i2 the 3 absolute pairwise sums are 4 1 3and their median is 3here is a longer example with both positive and negative y 127 069 056 045 023 007 013 046 156 172and here are my new b slow this is the ground thruth computed the naive way120 092 100 101 079 053 056 053 133 149but now my new a fast do not match no more 120 062 049 038 016 016 010 023 133 149edithere is my implementation of franciss solution up to the point where we have two sorted array the median of which is easy to compute i did it in r to stay in the spirit of the questionnonetheless i seem to be missing a correction factor for the index the ww in the code below so the code below is sometimes off by a little bit this is because in the definition above we compute the medians over n1 observations ij n100 yrnormn ysorty brepnan naive on2 approch fori in 1n bimedianabsyiyi krepnan i1 kiminnaomitcwhichyyi01n binary search ologn fori in 2n on k provki1 whileyk provyi0 k prov0 k provk prov1 kimaxk prov11 fori in 1n should give the same result kiwhichyyi01 isample1n1 x1y1ki1yi x2yiynki x3cx1x2 plotx3 wwifelseiki in2n21n2 sortx3ww this can be computed efficiently ologn bi this is the on2 result,"['c++', 'c']" +694379,do nonconst references prolong the lives of temporaries once upon a time i assumed that code like this would failconst myclass obj myclassobjdosomethingbecause the myclass object would be destroyed at the end of its fullexpression leaving obj as a dangling reference however i learned here that this is not true the standard actually has a special provision that allows const references to keep temporaries alive until said references are destroyed themselves but it was emphasized only const references have this power today i ran the code below in vs2012 as an experimentstruct foo foo stdcout ctor stdendl foo stdcout dtor stdendl void f foo f foo stdcout hello world stdendlthe output when calling f wasctor hello world dtor so i had a look at the c11 draft standard and only found this a 1224there are two contexts in which temporaries are destroyed at a different point than the end of the fullexpression the first context does not apply the second context is when a reference is bound to a temporary the temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the referencethe word const is conspicuously absent from the above so has this behavior been changed for c11 was i wrong about the const thing to begin with or does vs2012 have a bug and i just have not found the relevant part of the standard,['c++'] +694640,why does nsobject respondstoselectorselectorinit return 1 why does running respondstoselector on nsobject with the selector init return 1 even though running nsobject init gives a runtime error i know that init is an instance method and therefore only runs on instances and not classes why does this return an runtime errorifnsobject respondstoselector selectorinit yes nsobject performselector selectorinitfurthermore since respondstoselector is an instance method why is it even possible to call it in the first place,['objective-c'] +694679,spin or rotate an image on hover i want to find out how to make a spinning or rotating image when it is hovered i would like to know how to emulate that functionality with css on the following code img borderradius 50img src,['css'] +694682,how to install applications programatically without opening play store as google drive does today the google drive app asked if i wanted to install the new apps sheets docsi have accepted expecting it to open google play store so i could press install it did not it just showed me the popup with the permissions of each of the apps to confirm the installation the same that appears when you press install on any app on the play storei was not aware this could be done how can we reproduce this behavior in an app have a button install app xpto which does not need to open google play store just shows the permissions dialog and proceeds to install it via play store updatefor those downvoting because they think this is the same as other questions it is not in this case the apk is not downloaded by google drive app and then installed google drive tells play store to download install that is the api that i am interestedto support my case after pressing inside google drive to install the apps without opening play store the download starts during the download i have opened the play store to check andthe screenshot proves that it is not google drive downloading the apk and the installing it it is the play store,['android'] +694724,android scala intellij 13 android is great platform scala is great language intellij idea is great ide how all of them can work together note it is a self answer but if you have more info please share it here,['android'] +694790,manually set color of points in legend i am making a scatter plot which looks like thismwe at bottom of questionas can be seen in the image above the colors of the points in the legend are set to blue automatically by matplotlib i need to set this points to some other color not present in the colormap ie black so they would not generate confusion with the colors associated with said colormapi looked around but the matplotliblegend module does not seem to accept a color keyword is there any way to do thisheres the mweimport matplotlibpyplot as pltimport numpy as npdef rand data return nprandomuniformlow0 high1 size100 generate datax y x2 x3 rand data for i in range4 this data defines the markes and labels usedx1 nprandomrandom integers7 9 size100 order all lists so smaller points are on toporder npargsortnparrayx2 order x and yx o y o nptakex order nptakey order order list related to markers and labelsz1 nptakex1 order order list related to sizesz2 nptakex2 order order list related to colorsz3 nptakex3 orderpltfigurecm pltcmget cmaprdylbu scatter plot where each value in z1 has a different marker and label assignedmrk 7 o 7 8 s 8 9 d 9for key value in mrkitems s1 z1 key pltscatterx os1 y os1 markervalue0 labelvalue1 sz2s1 100 cz3s1 cmapcm lw02 plot colorbarpltcolorbar plot legendpltlegendloclower left markerscale07 scatterpoints1 fontsize10pltshow,['python'] +694928,download files from sftp with sshnet library string host ftphoststring username userstring password string localfilename systemiopathgetfilenamelocalfilenamestring remotedirectory exportusing var sftp new sftpclienthost username password sftpconnect var files sftplistdirectoryremotedirectory foreach var file in files if filenamestartswith string remotefilename filename if filelastwritetimedate datetimetoday consolewritelinefilefullname fileopenwritelocalfilename string sdir localpath stream file1 fileopenreadremotedirectory filename sftpdownloadfileremotedirectory file1 i am using sshnet rencisshnet library to work with an sftp server what i need to do is grab files from a specific folder on the sftp server based on todays date then copy those files from the sftp server to a local drive a server of mineabove is the code i have but it is not working sometimes it says file does not exist but sometimes the files i will be downloading will not be on my local servers but i need to download whatever files were uploaded to the remote folder for that daycan someone take a look and see what is wrong i believe it has something to do with the stream portion i have worked with ftp much besides uploading files which i took some previous code i had and thought i could reverse the process but that is not working the code i used is based off of this example,"['c#', '.net']" +694952,pass existing webdriver object to custom python library for robot framework i am trying to create a custom python library for robot framework but i am new to python and robot and i am not sure how to accomplish what i am trying to do i want to pass the webdriver object that robot creates using selenium2library to my custom python library so that i could use the webdrivers methods such as find element by id i have seen some suggestions about how to do it here and here but they are for java libraries i cannot find any python instructionshow would i go about doing this in python or would i want to do this differently without passing the webdriver object,['python'] +694953,how to use boostprogram options to accept an optional flag i need to implement an optional flag say fflag since this is a flag there is no value associated in my code i only need to know whether the flag was set or not whats the proper way to do this using boostprogram options,['c++'] +694960,exit code 139 when perfroming image subtraction i am performing an image subtraction using python i have images in the form of numpy arrays the size of the list that carrying all images is 10 each numpy array in the list is of 360640 type the frame subtraction is happening correct when the number of frames is around 300 def find derframes der for a in rangelenframes1 derappendframesa 1 framesa return derframesprocessing 10for j in rangeframesprocessing img cvqueryframevideo if img is none printimages are not captured else tmp cvcreateimagecvgetsizeimg 8 3 saveimagescolor abhiram imagesrgbframe stri png saving the iplimages to the local pc cvsaveimagesaveimagescolor img saveimagesgray abhiram imagesgrayframe stri png saving the grayscale images to the local pc img1 cv2imreadsaveimagescolor grayimg cv2cvtcolorimg1cv2color bgr2gray cv2imwritesaveimagesgray grayimg graynumpyimage nparraygrayimg dtypeint64 grayscaleappendgraynumpyimage i 1first der find dergrayscalewhen i execute the code with frames processing as 10 i am getting the following outputprocess finished with exit code 139could you please help me how to overcome this error and throw some light when i will get such a kind of error,['python'] +694970,how to make pikaday datepicker always visible i am using the pikaday javascript datepickerthe default functionality is to attach it to an input whereby clicking the input would load the datepicker and its position would be relative to the inputwhat i want is to use this library to show an always visible calendar i tried several things without success such as attaching it to a div i would like to be able to have it always shown and be able to control its positionany ideas,['javascript'] +695058,previous error being masked by current exception context the following is an example i found at the website for doug hellman in a file named masking exceptions catchpy i cannot locate the link at the moment the exception raised in throws is thiscarded while that raised by cleanup is reportedin his article doug remarks that the handling is nonintuitive halfway expecting it to be a bug or limitation in the python version at the time it was written circa 2009 i ran it in the current production release of python for the mac 276 it still reports the exception from cleanup i find this somewhat amazing and would like to see a description of how it is actually correct or desirable behaviorusrbinenv pythonimport sysimport tracebackdef throws raise runtimeerrorerror from throwsdef nested try throws except try cleanup except pass ignore errors in cleanup raise we want to reraise the original errordef cleanup raise runtimeerrorerror from cleanupdef main try nested return 0 except exception err tracebackprint exc return 1if name main sysexitmainprogram output python masking exceptions catchpytraceback most recent call last file masking exceptions catchpy line 24 in main nested file masking exceptions catchpy line 14 in nested cleanup file masking exceptions catchpy line 20 in cleanup raise runtimeerrorerror from cleanupruntimeerror error from cleanup,['python'] +695263,working only with devrandom in java i have a hrng that feeds devrandom in debian wheezy it is fast so blocking will not be a problem now in my java code i want to ensure that i use the entropy in devrandom and only that entropy i have no interest in using anything out of devurandomi want to force javas securerandom to only get entropy from devrandom as i understand the implementation at present it uses devurandom when getbytes is called but devrandom when generateseed is called i am at a loss understanding whyas i understand it the only reason to read from devurandom is if you favour speed over security i want the highest quality entropy possible devurandom will just not doso how do i force securerandom to only use devrandom supplied by a hrng and never touch anything from an inferior prng like devurandomthanks a mil,['java'] +695271,crash on pthread kill got the crash report below but have no clue why it would be happening and how to fix itsigabrt abort at 0x019aa3258clibsystem kerneldylib pthread killthread crashed comapplemainthread0 libsystem kerneldylib 0x019aa3258c pthread kill 81 libsystem pthreaddylib 0x019aab516c pthread kill 1042 libsystem cdylib 0x019a9c6808 abort 1123 libcabidylib 0x0199bec994 cxa bad cast4 libcabidylib 0x0199c07184 std terminatevoid 445 libcabidylib 0x0199c06d3c cxa rethrow 1446 libobjcadylib 0x019a3443a8 objc exception rethrow 447 corefoundation 0x018dd3d74c cfrunlooprunspecific 5768 graphicsservices 0x0193a21c0c gseventrunmodal 1689 uikit 0x0190e6efdc uiapplicationmain 115610 0x010a5c80 main mainm1711 libdylddylib 0x019a937aa0 start 4,['ios'] +695282,orgspringframeworkbeansfactorybeancreationexception error creating bean with name mycontroller i am doing spring hibernate application when i run the application on tomcat server i am getting some exceptionsinfo orgspringframeworkwebservletthispatcherservlet frameworkservlet appservlet initialization startedinfo orgspringframeworkwebcontextsupportxmlwebapplicationcontext refreshing webapplicationcontext for namespace appservletservlet startup date sat may 17 195103 cest 2014 parent root webapplicationcontextinfo orgspringframeworkbeansfactoryxmlxmlbeandefinitionreader loading xml bean definitions from servletcontext resource webinfspringappservletservletcontextxmlinfo orgspringframeworkbeansfactoryannotationautowiredannotationbeanpostprocessor jsr330 javaxinjectinject annotation found and supported for autowiringinfo orgspringframeworkwebservletmvcmethodannotationrequestmappinghandlermapping mapped inscriptionmethodsparamsheadersconsumesproducescustom onto public javalangstring comgestetuprojectcontrollercomptecontrollerhellojavalangstringjavalangstringjavalangstringorgspringframeworkuimodelinfo orgspringframeworkwebservletmvcmethodannotationrequestmappinghandlermapping mapped methodsgetparamsheadersconsumesproducescustom onto public javalangstring comgestetuprojectcontrollerhomecontrollerhomejavautillocaleorgspringframeworkuimodelinfo orgspringframeworkwebservlethandlersimpleurlhandlermapping mapped url path resources onto handler orgspringframeworkwebservletresourceresourcehttprequesthandler0error orgspringframeworkwebservletthispatcherservlet context initialization failedorgspringframeworkbeansfactorybeancreationexception error creating bean with name comptecontroller injection of autowired dependencies failed nested exception is orgspringframeworkbeansfactorybeancreationexception could not autowire field private comgestetuprojectmodelservicecompteserviceimp comgestetuprojectcontrollercomptecontrollercompteserv nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name compteserviceimp injection of autowired dependencies failed nested exception is orgspringframeworkbeansfactorybeancreationexception could not autowire method public void comgestetuprojectmodelservicecompteserviceimpsetcomptedaocomgestetuprojectmodeldaocomptedaohib nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name comptedaohib defined in file cuserszouhairworkspacemetadatapluginsorgeclipsewstservercoretmp1wtpwebappstesterwebinfclassescomgestetuprojectmodeldaocomptedaohibclass instantiation of bean failed nested exception is orgspringframeworkbeansbeaninstantiationexception could not instantiate bean class comgestetuprojectmodeldaocomptedaohib no default constructor found nested exception is javalangnosuchmethodexception comgestetuprojectmodeldaocomptedaohibinit at orgspringframeworkbeansfactoryannotationautowiredannotationbeanpostprocessorpostprocesspropertyvaluesautowiredannotationbeanpostprocessorjava292 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorypopulatebeanabstractautowirecapablebeanfactoryjava1185 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorydocreatebeanabstractautowirecapablebeanfactoryjava537 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorycreatebeanabstractautowirecapablebeanfactoryjava475 at orgspringframeworkbeansfactorysupportabstractbeanfactory1getobjectabstractbeanfactoryjava304 at orgspringframeworkbeansfactorysupportdefaultsingletonbeanregistrygetsingletondefaultsingletonbeanregistryjava228 at orgspringframeworkbeansfactorysupportabstractbeanfactorydogetbeanabstractbeanfactoryjava300 at orgspringframeworkbeansfactorysupportabstractbeanfactorygetbeanabstractbeanfactoryjava195 at orgspringframeworkbeansfactorysupportdefaultlistablebeanfactorypreinstantiatesingletonsdefaultlistablebeanfactoryjava703 at orgspringframeworkcontextsupportabstractapplicationcontextfinishbeanfactoryinitializationabstractapplicationcontextjava760 at orgspringframeworkcontextsupportabstractapplicationcontextrefreshabstractapplicationcontextjava482 at orgspringframeworkwebservletframeworkservletconfigureandrefreshwebapplicationcontextframeworkservletjava658 at orgspringframeworkwebservletframeworkservletcreatewebapplicationcontextframeworkservletjava624 at orgspringframeworkwebservletframeworkservletcreatewebapplicationcontextframeworkservletjava672 at orgspringframeworkwebservletframeworkservletinitwebapplicationcontextframeworkservletjava543 at orgspringframeworkwebservletframeworkservletinitservletbeanframeworkservletjava484 at orgspringframeworkwebservlethttpservletbeaninithttpservletbeanjava136 at javaxservletgenericservletinitgenericservletjava160 at orgapachecatalinacorestandardwrapperinitservletstandardwrapperjava1189 at orgapachecatalinacorestandardwrapperloadservletstandardwrapperjava1103 at orgapachecatalinacorestandardwrapperloadstandardwrapperjava1010 at orgapachecatalinacorestandardcontextloadonstartupstandardcontextjava4935 at orgapachecatalinacorestandardcontext3callstandardcontextjava5262 at orgapachecatalinacorestandardcontext3callstandardcontextjava5257 at javautilconcurrentfuturetaskrununknown source at javautilconcurrentthreadpoolexecutorrunworkerunknown source at javautilconcurrentthreadpoolexecutorworkerrununknown source at javalangthreadrununknown sourcecaused by orgspringframeworkbeansfactorybeancreationexception could not autowire field private comgestetuprojectmodelservicecompteserviceimp comgestetuprojectcontrollercomptecontrollercompteserv nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name compteserviceimp injection of autowired dependencies failed nested exception is orgspringframeworkbeansfactorybeancreationexception could not autowire method public void comgestetuprojectmodelservicecompteserviceimpsetcomptedaocomgestetuprojectmodeldaocomptedaohib nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name comptedaohib defined in file cuserszouhairworkspacemetadatapluginsorgeclipsewstservercoretmp1wtpwebappstesterwebinfclassescomgestetuprojectmodeldaocomptedaohibclass instantiation of bean failed nested exception is orgspringframeworkbeansbeaninstantiationexception could not instantiate bean class comgestetuprojectmodeldaocomptedaohib no default constructor found nested exception is javalangnosuchmethodexception comgestetuprojectmodeldaocomptedaohibinit at orgspringframeworkbeansfactoryannotationautowiredannotationbeanpostprocessorautowiredfieldelementinjectautowiredannotationbeanpostprocessorjava508 at orgspringframeworkbeansfactoryannotationinjectionmetadatainjectinjectionmetadatajava87 at orgspringframeworkbeansfactoryannotationautowiredannotationbeanpostprocessorpostprocesspropertyvaluesautowiredannotationbeanpostprocessorjava289 27 morecaused by orgspringframeworkbeansfactorybeancreationexception error creating bean with name compteserviceimp injection of autowired dependencies failed nested exception is orgspringframeworkbeansfactorybeancreationexception could not autowire method public void comgestetuprojectmodelservicecompteserviceimpsetcomptedaocomgestetuprojectmodeldaocomptedaohib nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name comptedaohib defined in file cuserszouhairworkspacemetadatapluginsorgeclipsewstservercoretmp1wtpwebappstesterwebinfclassescomgestetuprojectmodeldaocomptedaohibclass instantiation of bean failed nested exception is orgspringframeworkbeansbeaninstantiationexception could not instantiate bean class comgestetuprojectmodeldaocomptedaohib no default constructor found nested exception is javalangnosuchmethodexception comgestetuprojectmodeldaocomptedaohibinit at orgspringframeworkbeansfactoryannotationautowiredannotationbeanpostprocessorpostprocesspropertyvaluesautowiredannotationbeanpostprocessorjava292 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorypopulatebeanabstractautowirecapablebeanfactoryjava1185 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorydocreatebeanabstractautowirecapablebeanfactoryjava537 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorycreatebeanabstractautowirecapablebeanfactoryjava475 at orgspringframeworkbeansfactorysupportabstractbeanfactory1getobjectabstractbeanfactoryjava304 at orgspringframeworkbeansfactorysupportdefaultsingletonbeanregistrygetsingletondefaultsingletonbeanregistryjava228 at orgspringframeworkbeansfactorysupportabstractbeanfactorydogetbeanabstractbeanfactoryjava300 at orgspringframeworkbeansfactorysupportabstractbeanfactorygetbeanabstractbeanfactoryjava195 at orgspringframeworkbeansfactorysupportdefaultlistablebeanfactoryfindautowirecandidatesdefaultlistablebeanfactoryjava1017 at orgspringframeworkbe rootcontextxmlxml version10 encodingutf8beans xmlns xmlnsxsi xmlnsp xsischemalocation root context defines shared resources visible to all other web components bean idpropertyconfigurer classorgspringframeworkbeansfactoryconfigpropertyplaceholderconfigurer plocationwebinfjdbcproperties bean iddatasource classorgapachecommonsdbcpbasicdatasource destroymethodclose pdriverclassnamejdbcdriverclassname purljdbcurl pusernamejdbcusername ppasswordjdbcpassword add persistence support here jpa hibernate etc bean idsessionfactory classorgspringframeworkormhibernate4localsessionfactorybean property namedatasource refdatasource property namemappingresources list valuecomgestetuprojectmodelboutilisateurhbmxmlvalue valuecomgestetuprojectmodelbocomptehbmxmlvalue valuecomgestetuprojectmodelbomessagehbmxmlvalue valuecomgestetuprojectmodelbogroupehbmxmlvalue valuecomgestetuprojectmodelboetudianthbmxmlvalue valuecomgestetuprojectmodelbofichelecturehbmxmlvalue valuecomgestetuprojectmodelbodocumenthbmxmlvalue valuecomgestetuprojectmodelbocommentairehbmxmlvalue list property property namehibernateproperties props prop keyhibernatedialectorghibernatedialectmysqldialectprop prop keyhibernateshow sqltrueprop prop keyhibernatehbm2ddlautoupdateprop props property bean transaction manager bean idtxmanager classorgspringframeworkormhibernate4hibernatetransactionmanager property namesessionfactory refsessionfactory bean beansservletcontextxmlxml version10 encodingutf8beansbeans xmlns xmlnsxsi xmlnsbeans xmlnscontext xsischemalocation thispatcherservlet context defines this servlet us requestprocessing infrastructure enables the spring mvc controller programming model annotationdriven handles http get requests for resources by efficiently serving up static resources in the webapprootresources directory resources mappingresources locationresources resolves views selected for rendering by controllers to jsp resources in the webinfviews directory beansbean classorgspringframeworkwebservletviewinternalresourceviewresolver beansproperty nameprefix valuewebinfviews beansproperty namesuffix valuejsp beansbean contextcomponentscan basepackagecomgestetuproject beansbeanscomptecontrollerjavapackage comgestetuprojectcontrollerimport orgspringframeworkbeansfactoryannotationautowiredimport orgspringframeworkstereotypecontrollerimport orgspringframeworkuimodelimport orgspringframeworkwebbindannotationrequestmappingimport orgspringframeworkwebbindannotationrequestparamimport comgestetuprojectmodelbocompteimport comgestetuprojectmodelservicecompteserviceimpcontrollerpublic class comptecontroller autowired private compteserviceimp compteserv autowired public comptecontrollercompteserviceimp compteserv thiscompteservcompteserv requestmappingvalue inscription public string hello requestparamvalue login required false defaultvalue zouhair string login requestparamvalue password required false defaultvalue pass string password requestparamvalue profil required false defaultvalue etudiant string profil model model int id 1 compte compte new compteid login password profil compteservajoutercomptecompte modeladdattributeinscription compte return addcompte compteservicepackage comgestetuprojectmodelserviceimport javautillistimport orgspringframeworkbeansfactoryannotationautowiredimport orgspringframeworktransactionannotationtransactionalimport orgspringframeworkstereotypeserviceimport comgestetuprojectmodelbocompteimport comgestetuprojectmodelboutilisateurimport comgestetuprojectmodeldaocomptedaohibservicetransactionalreadonly truepublic class compteserviceimp implements compteservice private comptedaohib comptedao autowired public void setcomptedaocomptedaohib comptedao thiscomptedao comptedao override public void ajoutercomptecompte compte comptedaoajoutercomptecompte override public listcompte getcomptes return comptedaogetcomptes override public compte findcomptebyloginstring login return comptedaofindcomptebyloginlogin override public void ajouterutilisateurcompte compte utilisateur utilisateur thisajoutercomptecompte override public utilisateur getutilisateurbyidint id return null override public listutilisateur getutilisateurs return null can anybody help to resolve thiscomptedaohib package comgestetuprojectmodeldaoimport javautillistimport orghibernatesessionfactoryimport orgspringframeworkbeansfactoryannotationautowiredimport orgspringframeworkormhibernate3supporthibernatedaosupportimport orgspringframeworkstereotyperepositoryimport orgspringframeworktransactionannotationpropagationimport orgspringframeworktransactionannotationtransactionalimport comgestetuprojectmodelbocompterepositorytransactionalpropagationpropagationrequiredpublic class comptedaohib extends hibernatedaosupport implements comptedao public comptedaohibsessionfactory sessionfactory setsessionfactorysessionfactory override public void ajoutercomptecompte compte gethibernatetemplatesaveorupdatecompte override public listcompte getcomptes try return listcompte gethibernatetemplatefindfrom compte iterator catch exception e return null override public compte findcomptebyloginstring login if login null login return null else try return compte gethibernatetemplate findfrom compte c where clogin login iteratornext catch exception e return null compteservice code package comgestetuprojectmodelserviceimport javautillistimport comgestetuprojectmodelbocompteimport comgestetuprojectmodelboutilisateurpublic interface compteservice public void ajoutercomptecompte compte public listcompte getcomptes public compte findcomptebyloginstring login public listutilisateur getutilisateurs public utilisateur getutilisateurbyidint id public void ajouterutilisateurcompte compte utilisateur utilisateur,['java'] +695297,best data persistence for angularjsjavascript apps on phonegap i am looking to find best practices for angularjs data persistence on a phonegap app i am using ionic framework on top of this but not relevant to this question as it is just built on top of angular cordovai like that angular remains flexible on data persistence solutions it makes sense since it is a web framework not specifically a hybrid app framework would love to know how people are solving thisheres an overviewrequirementsadd local database to app build for preloaded data this will be over the 5mb data limitload data from local database on startupsaving updated data to local data store for persistenceprefer schemaless if possiblesimple query interface i could load all the data into memory and just use standard angular filters for this provided the performance was decentobject query interface something like an activerecordlike orm rather than having to write sql in my appfuture proof i do not want to reinvent the wheel every time i am building an app that needs data persistence also would like to choose something that is more standard if possible so i can continue to use it in the future something like indexeddb would make sense hereoptionsi have been looking at the following options can you provide any feedback on any of thesebreezejs looks more focused on server is there an sqlite interfaceydndb seems like an option but also seems a little obscure compared to some of the other optionsjaydata is this still active concerned about commercial aspect of it persistencejs this looks promising is the project still activengstorage is this just a localstorage interface does it solve the 5m limitangularcache can i have data to preload with this how long can i persist datalocalforage do not know much about this does it solve the 5m limitpouchdb concerned about query language does not solve 5m restrictioncouchdb lite concerned about query language websql i do not to use this since it seems like it is on the way out plus 5m limitindexeddb there is a shim that builds compatlayer for most major browsers 5m limit if i could use this on top of sqlite that would prob be a winner for me since more standards basedstore in json file just use plain old objects and then use phonegap file api to load and store serialized data seems like a pain to have to serialize all the data every time we want to save but an option so long as i can use angular filterssorry for the long post i really would like to see some thoughts on best practices would love an angular way to handle large data persistence on hybrid mobile appsthanks,['javascript'] +695405,authenticate a siteapp to access a web api service brief questioni have a web api service in net and a site made only with html and angularjshow can authorize to my service only my webi am looking for a secure answer to a problem that seems to be common but is not i read a lot of answers ideas and every kind of things in the late days but i could not find the solutionlet us suppose i have a web api service the lastest one from ms so i have to application that need consumes it let us define two scenariosscenario 1in the same iis i have an aspnet mvc 34 with the particularity that all mvc work is on the client side made by angularjs so the app points directly from javascript to the web api servicescenario 2i have a third party application that points directly to the web api service and is locate in other networksiteanything but relatedso my question ishow can authenticate both systems in order to the web api service gives access to both system i do not care if is the same way or not and not give access for example to a guy with a rest client and logged to the site with userpass authorization i hope these both examples gave the idea of the point what i am interestedplease comment below anything you need to improve this question in a better wayby the way no obfuscation can not be usedi thought in something like a refreshing token but i cannot figure it,"['c#', 'asp.net']" +695439,css for select option to be transparent background i have a web page that have backgroundimage in it after that there is a combo box for filtering some content i want to create this select option background being transparent i have read many result at google to use select option at css but it did not work i have create a fiddle in here for example and as you can see the option background is not transparent so any idea how to solve that or it cannot be done by csorry for my bad english,"['html', 'css']" +695451,select and random elements from a list efficiently without toarray and change the list as in the title i want to use knuthfisheryates shuffle algorithm to select and random elements from a list but without using listtoarray and change the list here is my current codepublic liste getnelementsliste list integer n liste rtn null if list null and null and 0 int lsize listsize if lsize n rtn new arraylisten e es e listtoarray knuthfisheryates shuffle algorithm for int i eslength 1 i eslength and 1 i int irand randnextinti 1 e erand esirand esirand esi this is not necessary here as we do not really need the final shuffle result esi erand rtnadderand else if lsize n rtn new arraylisten rtnaddalist else loglistsize nsub lsize n return rtnit uses listtoarray to make a new array to avoid modifying the original list however my problem now is that my list could be very big can have 1 million elements then listtoarray is too slow and my and could range from 1 to 1 million when and is small say 2 the function is very inefficient as it still need to do listtoarray for a list of 1 million elementscan someone help improve the above code to make it more efficient when dealing with large lists thankshere i assume knuthfisheryates shuffle is the best algorithm to do the job of selecting and random elements from a list am i right i would be very glad to if there is other algorithms better than knuthfisheryates shuffle to do the job in terms of the speed and the quality of the results guarantee real randomnessupdatehere is some of my test resultswhen selection and from 10 elementswhen n104 the fastest way to through using daniel lemires bitmap function to select and random id first then get the elements with these idspublic liste getnelementsbitsetliste list int n liste rtn new arraylisten int ids gennbitsetn 0 listsize for int i 0 i idslength i rtnaddlistgetidsi return rtn the gennbitset is using the code generateuniformbitmap from when n104 the reservoir sampling method is fasterso i have built a function to combine these two methods,['java'] +695470,connection drop in httplistener in c mono i have a code like this public async void start loggerlogloggerloglevelgeneral beginning listen httplistener listener new httplistener listenerprefixesaddstaticsconfiginireadvaluehttpserver listenerstart while true httplistenercontext client await listenergetcontextasync acceptclientclient public async void acceptclienthttplistenercontext client try string srequest helpersgetrequestbodyclientrequest if srequest return clientresponsecontenttype applicationjson do a bunch of stuff here string s jsonconvertserializeobjectresponse byte bytearray encodingutf8getbytess clientresponsecontentlength64 bytearraylength clientresponseoutputstreamwritebytearray 0 bytearraylength clientresponseoutputstreamclose clientresponseclose catch exception e loggerlogloggerloglevelerror etostring the code works perfectly fine on windows using net but in my testing on ubuntu 1304 the client is dropped i am using mono 321the code is for a rpc server which is connected from a c client i cannot change the client expects the connection to remain open throughout the period and fails with broken pipe on unix and error code 5 eof on windows when using this server with mono there is no problem on connection but after the first command the client fails there is no exception raised thanks for your helpedit 1 i ripped apart the mono httplistener and used it in my project directly and now it fails on net too definitely somethings wrong with the code ps this time it was the newest commit code,['c#'] +695584,c what are freestanding references used for in which situation would you want to define a reference to some piece of memoryfor exampleconst int r 8 as opposed to simply writingint r 8,['c++'] +695643,missing production secret key base in rails i have recently deployed an app and got internal server error because of missing production secret key base after hours of testing i managed to solve this problem with two methodsmethod 1i generated a new secret key with rake secret and replaced it with envsecret key base in secretsyml deployed the app again and this time it worked but i think that this method is wrongmethod 2i generated a new secret key with rake secret and added it to environmentsproductionrb like configsecret key base d1f4810e662acf46a33960e3aa5bd0 without changing secretsyml default is production envsecret key base deployed the app again and it works fine my questionswhich method is the bestif the 2nd method is correct why rails does not generate a secret key base in productionrb by default is there any other method to do that,['ruby-on-rails'] +695792,is it undefined behavior to exceed translation limits and are there checker tools to find it original questioni am searching the c90 standard for things to be aware of when writing hignly portable code while having low trust in the good will of the compiler vendor and assuming that my software might kill somebody sometimes if i do things wrong let us say i am a little paranoidat the moment i am thinking about the translation limits 5241 ansiiso 98991990 as pointed out in the standard and in does ansi c place a limit on the number of external variables in a program those are minimum requirements for a standard conform implementation now on the other hand this means any implementation does not have to do more and if i want to be sure that my code works for any confrom implementation these limits represent absolut limits for meso far so annoyingso the compiler vendor choose limits that equals or are above the minimum required tranlation limitswhat happens now if one exceed these implementationdefined tranlation limits of a specific implementation in my copy of ansiio 98991990 c90 i have not found anything so i think it is undefined behavior of the 3 kind by omission on the other hand would this not be the first time that i misunderstood the standard or did not find the right passageso here are my questionsis exceeding the translation limits of a specific implementation undefined behavior in c90does c90 behavior hold for the corrected versions up to c95c96 and for the new iterations c99 c11have anyone seen a checker tool out there that checks for the minimal or tool user defined limitsaspects beyond the original questioninteresting aspects in answers and comments1 as michael burr pointed out in a direct comment to the question according to the cstandard i have only checked c90 without corrigendae and the c99 draft michael referenced here a conform c implementation only needs to accept one program that contains all limits at the same time which in the strictest interpretation nullifies any minimum limit guarantees2 as rubenvb and keith thompson pointed out implementations of some quality should provide diagnostics for the case that their implementation defined limits are exceeded especially if the are not conform to the minimum requirements rubenvb linked an example for msvc in a comment3 as exceeding the compiler limits might be undefined behavior but surely lead to some error the values of the variables to which the translation limits apply for a certain piece of my code represent preconditions for reusemy personal strategies to deal with them1 so for maximal paranoia i will make a fool out of myself and annoy the compiler vendors support with a request to guarantee me that the limits chosen by the implementation apply to any program 2 so i will investigate the compiler documentations and the capacity for suffering of the compiler supports for getting the confirmation that that for every translation limit if being exceeded a diagnostic will be raised and because it is undefined behavior if every instance of exceeding a translation limit will raise a diagnostic or else another error already prevented a compilation3 so i will try to get hands on a tool or develop myself if i really must that measure those values and provide them as precondition for code reuse for my program as keith thompson pointed out in this answer some of values might need a deeper knowledge on how the implementation is implemented i am not perfectly sure what can help in such cases beyond actions in 2 yet as far as i see i have to test but i only need to test if there is ub without a diagnostic and if this is the case a successful test can not guarantee correctness in the general caseansweredyes it is undefined behavior by obmissionkeith thompson has showed in his accepted anwser with terminology of and reference to the c standard documents that it is undefined behaviora tool that checks transaction limits in the code has not yet thiscovered by the commenters if a tool occurs to anyone that have even partly this functionality please leave an answer or comment,['c'] +695821,fluent api with inheritance and generics i am writing a fluent api to configure and instantiate a series of message objects i have a hierarchy of message typesto be able to access method of subclasses when using the fluent api i used generics to parametrize the subclasses and make all fluent methods that start with with return the generic type note that i omitted most of the body of the fluent method a lot of configuration goes on in them public abstract class messaget extends messaget protected message public t withidstring id return t this the concrete subclasses redefine the generic type similarlypublic class commandmessaget extends commandmessaget extends messagecommandmessaget protected commandmessage super public static commandmessage newmessage return new commandmessage public t withcommandstring command return t this public class commandwithparamsmessage extends commandmessagecommandwithparamsmessage public static commandwithparamsmessage newmessage return new commandwithparamsmessage public commandwithparamsmessage withparameterstring paramname string paramvalue contentsputparamname paramvalue return this this code works ie i can instantiate any of the classes and use all fluent methodscommandwithparamsmessage msg commandwithparamsmessagenewmessage withiddo withcommanddoaction withparameterarg valuecalling the fluent methods in any order is a major goal herehowever the compiler warns that all return t this are unsafe type safety unchecked cast from message to ti am unsure how i could reorganize the hierarchy to make this code truly safe even though it works the use of generics in this fashion feels really convoluted especially i am not able to foresee situations where runtime exceptions will happen if i just ignore the warningsthere will be new message types so i need to keep the code extensibleif the solution is to avoid inheritance altogether i would also like to obtain suggestion of alternativesthere are other questions here on so that address a similar issue they point to a solution where all intermediate classes are abstract and declare a method like protected abstract self still in the end it is not safe,['java'] +695957,agegender data in ios app google analytics i have already integrated my ios app with google analytics sdk to track everything happening on the app and to get the useful reports that it generates i have enabled the demographics reports which let me see the agesgender that are using the app but my question is how google can know the age and the gender of the user on an apple device i am assuming that on android they can know everything since the user has to enter his gmail account to manage his phone so they are able to get this information from his account but what about apple deviceshow can they know this informationi have checked thissetting user gender age in google analytics ios sdk v3but no one has replied on iteditedi have enabled the demographics and interest reports and i am not seeing anything related to the age and gender under the reporting section,['ios'] +695965,why would thistinct count return 9 instead of 1 i have the following statementselect thistinct countztitle as count from qmfilesmprlrreqdp y qmfilesmprlrtypp zwhere yrequest type zid and yrequest id 13033on this particular result set if i removed thistinct and count the result set will return nine rows of the exact same data if i add thistinct i get one row adding count i get a result of nine where i am expecting one i am assuming the order of operations are affecting my result but how can i fix this so i get the result i want note this is a subselect within a larger sql statement,['sql'] +696022,algorithm for generating a tree decomposition i want to construct a tree decomposition decomposition and i have the chordal graph and a perfect elimination ordering i am following advice given in a previous threadnamelyto construct a nonnice in general tree decomposition of a chordal graph find a perfect elimination ordering enumerate the maximal cliques the candidates are a vertex and the neighbors that appear after it in the ordering use each clique as a decomposition node and connect it to the next clique in the ordering that it intersectsthis does not work however and i can not figure out why consider the following exampleperfect elimination ordering 4 3 5 7 6 2 0 1chordal graphtree decompositioni am using python and my current algorithm is the followingtnxgraph nodelist for i in eo vertexstri bagset bagaddvertex for j in chordal graphneighborsstri bagaddstrj tadd nodefrozensetbag nodelistappendfrozensetbag chordal graphremove nodestri for node1 in rangelennodelist foundfalse for node2 in rangenode11lennodelist if foundfalse and lennodelistnode1intersectionnodelistnode20 tadd edgenodelistnode1nodelistnode2 foundtrue nxdrawt pshow where eo is a list of the perfect ordering and chordal graph is a graph object for networkx,['python'] +696031,java print string c equivalent what would be the equivalent in java of c codedefine printvarvar coutvarvarprinting string value and its name,"['java', 'c++']" +696064,httpurlconnection javalangillegalstateexception already connected i am trying to use httpurlclient to send some post data to a server using the httprestclient class shown below when executingconnsetdoinputtruei getjavalangillegalstateexception already connectedi uninstalled the app and still get the same errorin all the example i have seen openconnection is called before setdoinput if as its name suggests openconnection opens a connection it should never be used before setdoinput right what am i missingmaybe at some point it crashed before executing thisconnect could that be the reason if so how can i thisconnect the old connectionpublic class httprestclient static public int poststring urlstr listnamevaluepair data httpurlconnection conn null try url url new urlurlstr conn httpurlconnection urlopenconnection connsetdoinputtrue connsetdooutputtrue connsetrequestmethodpost outputstream os conngetoutputstream bufferedwriter writer new bufferedwriter new outputstreamwriteros utf8 writerwritegetquerydata writerflush writerclose osclose inputstream is conngetinputstream string dude readitis return 1 catch malformedurlexception e todo autogenerated catch block eprintstacktrace return 0 catch ioexception e todo autogenerated catch block eprintstacktrace return 0 finally ifconull connthisconnect,['android'] +696068,prolong uipickerview selectrow incomponent animateds animation i am using a uipickerview to thisplay random numbers the user can press a button and thus trigger a random selection of a number inside the uipickerviewit does not matter how many objects or numbers are being thisplayed inside the uipickerview when i call the methodselfpicker selectrowrandomrow incomponent0 animatedyesit always gets animated with the same time intervalis there any option or method to prolong the animation time interval of above methodi have tried placing it in an animation blockuiview beginanimationsidentifier contextnil codeuiview commitanimationsbut this seems to be a dead endi have also tried executing it in a completion blocks 034f is the approximate defualt apple animationuiview animatewithduration034f animationsselfpicker selectrowrandomrow incomponent0 animatedyes completionbool finished uiview animatewithduration034f animations selfpicker selectrowrandomrow incomponent0 animatedyes completionnilany help would be appreciated,['ios'] +696116,add modify remove celeryschedules at run time is there a way to add modify remove celeryschedules at run time i need something that reads a db table periodically to know list of schedulesdocument says one can use djceleryschedulersdatabasescheduler to achieve what i want but not sure how to do iti read how to dynamically add remove periodic tasks to celery celerybeat still not clearthanks for help,['python'] +696187,localegetpreferredencoding why does this reset stringletters import string import locale stringlettersabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz localegetpreferredencodingutf8 stringlettersabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzany workarounds for thisplatform linuxpython267 and python273 seem to be affected works fine in python3 with ascii letters,['python'] +696244,laravelcomposer the use statement with noncompound name in my laravel project i created a model called customerlinks the model resides in the appmodels folder my composer file has an autoload ofautoload classmap appmodels and i have a use statement in my extendedusercontroller that references customerlinksphpuse customerlinksclass extendedusercontroller extends usercontroller it is my understanding that since the autoload property in the composer file has appmodels in the classmap it means i should be able to use use customerlinks without a namespace prefix this works but any time i make a change to my extendedusercontroler and reload my browser i get the errorthe use statement with noncompound name customerlinks has no effectthe error points to the use customerlinks line extended user controller when i do a composer dumpautoload everything works fine but it becomes extremely irritating when i have to follow the patternmake a change dump autoload refresh browser repeatis there some way of dealing with the error,['php'] +696373,uiactivityviewcontroller mixing text and images and keeping the order is it possible to mix images and text and send them as mms uiactivityviewcontroller will share an image with text underneath but no matter how i order the text and images the images always appear on top and the text on the bottom if it is not possible with uiactivityviewcontroller is there another waythe code i am trying to usensarray activityitems smallimage love mediumimage you largeimagensarray applicationactivities nilnsarray excludeactivities niluiactivityviewcontroller activitycontroller uiactivityviewcontroller alloc initwithactivityitemsactivityitems applicationactivitiesapplicationactivitiesactivitycontrollerexcludedactivitytypes excludeactivitiesself presentviewcontrolleractivitycontroller animatedyes completionnilit produces this resultbut this is what i want,['ios'] +696420,handling listtypes with esqueleto i have data types defined asdata comitteeview committeeview committeeid committeeid committeemembers person data committeesview committeesview committeeview committeeview now as it stands i have a persistent model defined asperson name textcommittee name textcommitteeperson personid personid committeeid committeeidi can pretty easily create a query to populate a committeeview using esqueleto it would go something like thisgetcommitteeview cid committeeview rundb select from person innerjoin pxc innerjoin committee do on committee committeeid pxc committeepersoncommitteeid on person personid pxc committeepersonpersonid where committee committeepersoncommitteeid val cid return personnow consider the problem of populating committeesview in principle we get enough data to populate by running subquery in the above query okay fair enough now how can i use group by haskelist like group by in sql how can i fold rows so that i can end up with a list of lists of peoplei get the impression that esqueleto cannot handle the case as such ie it does not have a combinator that would do it and my underlying database obviously does not support haskell lists as a column but surely i cannot be the only person to face this issue what is an effective strategy folding an nlist of lists into a nlist or running n1 queries are there any other options,['sql'] +696467,php meaning of question mark colon operator what does in this line mean cookieuser getusername cookieuserthank you,['php'] +696479,build error referencing buildxml and proguard file null returned 1 while building my phonegap app with the facebook sdk plugin installed i encountered this errorbuild failed cadtbundlewindowsx86 6420130522sdktoolsantbuildxml653 the following error occured while executing this line cadtbundlewindowsx86 6420130522sdktoolsantbuildxml698 null returned 1line 653 is doonlyifmanifesthascode elsetexthascode false skipp aidlrenderscriptrjavaline 698 isproguardfileoutabsolutedirproguardtxtmy solutions so far include the followingran android update project to force generation of the proguardprojecttxt file as well as update the localproperties and projectproperties fileedited cadtbundlewindowsx86 6420130522sdktoolsantbuildxml so that all mentions to proguardtxt become proguardprojecttxtran ant logfile antlogfiletxt release here is the log filesetmodechecksetreleasemodereleaseobfuscationcheck echo proguardconfig is cadtbundlewindowsx86 6420130522sdktoolsproguardproguardandroidtxtproguardprojecttxt echo proguardconfig is enabledprebuildcheckenv checkenv android sdk tools revision 2262 checkenv installed at cadtbundlewindowsx86 6420130522sdksetup echo project name helloworld gettype project type applicationbuildsetup getbuildtools using latest build tools 1903 echo resolving build target for helloworld gettarget project target android 233 gettarget api level 10 gettarget warning attribute minsdkversion in androidmanifestxml 14 is higher than the project target api level 10 echo echo creating output directories if needed echo echo resolving dependencies for helloworld dependency library dependencies dependency dependency dependency ordered libraries dependency dependency dependency api15 adding annotationsjar to the classpath echo echo building libraries with releasenodepssetmodechecksetreleasemodereleaseobfuscationcheck echo proguardconfig is cadtbundlewindowsx86 6420130522sdktoolsproguardproguardandroidtxtproguardprojecttxt echo proguardconfig is enabledprebuildcheckenv checkenv android sdk tools revision 2262 checkenv installed at cadtbundlewindowsx86 6420130522sdksetup echo project name facebook gettype project type android librarybuildsetup getbuildtools using latest build tools 1903 echo resolving build target for facebook gettarget project target android 233 gettarget api level 10 echo echo creating output directories if needed mkdir created dir cusersbrianleedesktopeclipse workspacechumba connect trunk newfacebookandroidsdk3141facebookbinrsobj mkdir created dir cusersbrianleedesktopeclipse workspacechumba connect trunk newfacebookandroidsdk3141facebookbinrslibs echo echo resolving dependencies for facebook dependency library dependencies dependency no libraries dependency dependency dependency api15 adding annotationsjar to the classpathcodegen mergemanifest found deleted target file mergemanifest merging androidmanifest files into one mergemanifest manifest merger thisabled using project manifest only echo handling aidl files aidl no aidl files to compile echo echo handling renderscript files echo echo handling resources aapt generating resource ids aapt invalid resource directory name cusersbrianleedesktopeclipse workspacechumba connect trunk newfacebookandroidsdk3141facebookbinrescrunchbuild failed cadtbundlewindowsx86 6420130522sdktoolsantbuildxml601 the following error occurred while executing this line cadtbundlewindowsx86 6420130522sdktoolsantbuildxml653 the following error occurred while executing this line cadtbundlewindowsx86 6420130522sdktoolsantbuildxml698 null returned 1total time 2 secondsall of my attempts yielded no progress why does this error occur what must i do to build successfully,['android'] +696480,sqlite accessviolationexception in wcf service we have a net windows service exposing a wcf service to an userinterface and other parts of our system it targets net framework 45 and uses sqlite 1092 binaries to talk to the underlying sqlite database however the windows service crashes automatically stopped after running for some time with an accessviolationexception found via windows event viewer in sqliteinteropdll i have come across articles that talks about this exception in connection close but in all our cases we encounter this exception while querying or writing to the db using the methods exposed by our wcf service the stacktrace is as followsapplication ourserverexeframework version v4030319description the process was terminated due to an unhandled exceptionexception info systemaccessviolationexceptionstack at systemdatasqliteunsafenativemethodssqlite3 bind intintptr int32 int32 at systemdatasqliteunsafenativemethodssqlite3 bind intintptr int32 int32 at systemdatasqlitesqlite3bind int32systemdatasqlitesqlitestatement systemdatasqlitesqliteconnectionflags int32 int32 at systemdatasqlitesqlitestatementbindparameterint32 systemdatasqlitesqliteparameter at systemdatasqlitesqlitestatementbindparameters at systemdatasqlitesqlitecommandgetstatementint32 at systemdatasqlitesqlitedatareadernextresult at systemdatasqlitesqlitedatareaderctorsystemdatasqlitesqlitecommand systemdatacommandbehavior at systemdatasqlitesqlitecommandexecutereadersystemdatacommandbehavior at systemdatasqlitesqlitecommandexecutenonquerysystemdatacommandbehavior at dataaccesqliteexecutecommandsystemcollectionsobjectmodelcollection1systemstring systemcollectionsobjectmodelcollection1systemdatacommondbparameter at datasettingssavesystemcollectionsobjectmodelcollection1commonoperation at dynamicclasyncinvokesaveoperationsystemobject systemobject systemobject at systemservicemodelthispatchersyncmethodinvokerinvokesystemobject systemobject systemobject byref at systemservicemodelthispatcherthispatchoperationruntimeinvokebeginsystemservicemodelthispatchermessagerpc byref at systemservicemodelthispatcherimmutablethispatchruntimeprocessmessage5systemservicemodelthispatchermessagerpc byref at systemservicemodelthispatcherimmutablethispatchruntimeprocessmessage31systemservicemodelthispatchermessagerpc byref at systemservicemodelthispatchermessagerpcprocessboolean at systemservicemodelthispatcherchannelhandlerthispatchandreleasepumpsystemservicemodelchannelsrequestcontext boolean systemservicemodeloperationcontext at systemservicemodelthispatcherchannelhandlerhandlerequestsystemservicemodelchannelsrequestcontext systemservicemodeloperationcontext at systemservicemodelthispatcherchannelhandlerasyncmessagepumpsystemiasyncresult at systemruntimefxasyncthunkunhandledexceptionframesystemiasyncresult at systemruntimeasyncresultcompleteboolean at systemruntimeinputqueue1asyncqueuereadersystem canon mscorlib version40 cultureneutral publickeytokenb77a5c561934e089setitemsystem canon at systemruntimeinputqueue1system canon mscorlib version40 cultureneutral publickeytokenb77a5c561934e089enqueueandthispatchitemsystem canon boolean at systemruntimeinputqueue1system canon mscorlib version40 cultureneutral publickeytokenb77a5c561934e089enqueueandthispatchsystem canon systemaction boolean at systemservicemodelchannelssingletonchannelacceptor3system canon mscorlib version40 cultureneutral publickeytokenb77a5c561934e089system canon mscorlib version40 cultureneutral publickeytokenb77a5c561934e089system canon mscorlib version40 cultureneutral publickeytokenb77a5c561934e089enqueuesystem canon systemaction boolean at systemservicemodelchannelsconnectiondemuxercompletesingletonpreambleandthispatchrequestasyncresultonpreamblecompletesystemiasyncresult at systemruntimefxasyncthunkunhandledexceptionframesystemiasyncresult at systemruntimeasyncresultcompleteboolean at systemservicemodelchannelsserversingletonpreambleconnectionreadercompletepreambleasyncresultonwritecompletedsystemobject at systemservicemodelchannelssocketconnectiononsendasyncsystemobject systemnetsocketssocketasynceventargs at systemthreadingexecutioncontextruninternalsystemthreadingexecutioncontext systemthreadingcontextcallback systemobject boolean at systemthreadingexecutioncontextrunsystemthreadingexecutioncontext systemthreadingcontextcallback systemobject boolean at systemthreadingexecutioncontextrunsystemthreadingexecutioncontext systemthreadingcontextcallback systemobject at systemnetsocketssocketasynceventargsfinishoperationsuccesystemnetsocketssocketerror int32 systemnetsocketssocketflags at systemnetsocketssocketasynceventargscompletionportcallbackuint32 uint32 systemthreadingnativeoverlapped at systemthreading iocompletioncallbackperformiocompletioncallbackuint32 uint32 systemthreadingnativeoverlappedwe are using the sqlite assemblies from sqlitenetfx45binarybundlewin32201210920 downloaded from the assemblies are bundled as part of the windows service and are not in gac this behavior is consistent in both 32bit and 64bit machines fyi we are not using the mixed mode assembliesour connection stringdata sourceourappdbversion3newfalsecompresstruepragma cache size20 pragma page size32768 pragma synchronousoffand the sqlite database file is the windows programdata folderthe stacktrace shows the framework version as v4030319 while we have explicitly set the target version to 45 in our services application config however the machine has both the versions installedalso i wrote a simple console application that invokes the same wcf service method from multiple threads but could not simulate the same accessviolationexception hence i do not think it could be a load or concurrent access related issue the exception seems random and we have no way of consistently reproducing the issue other than just running the service and waiting for it to happenany pointers to what could be causing this issue is greatly appreciated updatecode for the two variants of executecommand being used public int executecommandstring query params dbparameter parameters try thisresult 1 thisopenconnection thiscommand new sqlitecommandquery thisconection thishandleparametersparameters thisresult thiscommandexecutenonquery catch exception ex thisresult 1 finally if thiscommand null thiscommandthispose thiscloseconnection return thisresult public int executecommandcollectionstring queries collectiondbparameter parameters try thisresult 1 thisopenconnection thiscommand new sqlitecommand thiscommandconnection thisconection thistransaction thisconectionbegintransaction for int i 0 i queriescount i thiscommandparametersclear thiscommandcommandtext queriesi thiscommandcommandtimeout thistimeout thiscommandtransaction thistransaction dbparameter cmdparams new dbparameter if parameters null cmdparams parametersi thishandleparameterscmdparams thisresult thiscommandexecutenonquery thistransactioncommit catch exception ex if thistransaction null thistransactionrollback thisresult 1 finally if thiscommand null thiscommandthispose thiscloseconnection return thisresult update 2 code for save method collectiondbparameter dbparameters new collectiondbparameter dbparameter dbparams sqliteparameter sqlparams collectionstring queries new collectionstring int icount 0 foreach operation operation in operations icount 0 dbparams new dbparameter4 queriesaddupdate table1 set col1 col1 col2 col2 timestamp timestamp where id id sqlparams new sqliteparameter sqlparamsdbtype dbtypestring sqlparamsparametername timestamp sqlparamsvalue stringformatcultureinfoinvariantculture 0ymmdd hhmmss operationtimestamp dbparamsicount sqlparams sqlparams new sqliteparameter sqlparamsdbtype dbtypestring sqlparamsparametername id sqlparamsvalue operationid dbparamsicount sqlparams sqlparams new sqliteparameter sqlparamsdbtype dbtypestring sqlparamsparametername col1 sqlparamsvalue operationcol1 dbparamsicount sqlparams sqlparams new sqliteparameter sqlparamsdbtype dbtypestring sqlparamsparametername col2 sqlparamsvalue operationcol2 dbparamsicount sqlparams dbparametersadbparams return dataaccesqliteexecutecommandqueries dbparameters 1,"['c#', '.net']" +696511,installing specific laravel version with composer createproject the fastest and simplest way of installing laravel is via composer command from the laravel docs it shows that we can install it with thiscomposer createproject laravellaravel yourprojectname preferthistbut when you run the above command it will grab the latest version of laravel how can i control it if i want to install latest version of 40x or 41x when 42 is out,['php'] +696522,io7 navigation check when finish transition i want to mark that my uinavigationcontroller is animating pushpop or noti have a bool variable isanimating and the the code below seem work voidnavigationcontrolleruinavigationcontroller navigationcontroller willshowviewcontrolleruiviewcontroller viewcontroller animatedboolanimated isanimating yes voidnavigationcontrolleruinavigationcontroller navigationcontroller didshowviewcontrolleruiviewcontroller viewcontroller animatedboolanimated isanimating nobut it work incorrectly in ios7 with swipe gesture assume my navigation is root view a view b i am currently on bin begin of swipe go back from b to a the funcion navigationcontrollerwillshowviewcontrolleranimatedboolanimated is called then isanimating yesthe normal case is the swipe is finished go back to a the function navigationcontrollerdidshowviewcontrolleranimatedboolanimated is called then isanimating no this case is ok butif the user may just swipe a half half transition to a then do not want to swipe to the previous view view a he go to the current view again stay b again then the function navigationcontrollerdidshowviewcontrolleranimatedboolanimated is not called my variable has incorrect value isanimatingyesi have no chance to update my variable in this abnormal case is there any way to update the state of navigation thank you,['ios'] +696633,get a string to reference another in c i am coming from a c background this question has been asked before but try as i might i cannot find the answer let us say i havestring arrayofreallyverylongstringnames new string500arrayofreallyverylongstringnames439 hello worldcan i create a string that references the above neither of these will compilestring a ref arrayofreallyverylongstringnames439 no compilestring a arrayofreallyverylongstringnames439 no compilei do understand that strings are immutable in c i also understand that you cannot get the address of a managed objecti would like to do thisa donkey kong now arrayofreallyverylongstringnames439 donkey kongi have read the stack overflow question make a reference to another string in c which has an excellent answer but to a slightly different question i do not want to pass this parameter to a function by reference i know how to use the ref keyword for passing a parameter by referenceif the answer is you cannot do this in c is there a convenient workaroundeditsome of the answers indicate the question was unclear lets ask it in a different way say i needed to manipulate all items in the original longnamed array that have prime indices i would like to add aliases to array2 array3 array5 etc to a list then modify the items in the list using a for loop perhaps by passing the list just created to a functionin c the using keyword creates an alias to a class or namespace it seems from the answers that it is not possible to create an alias to a variable however,['c#'] +696747,php seems to be evaluating an if statement backwards so i have a php statement of the following typeif xfunctiony z 50 what i see happening is that if z is 50 x does not get set because the function is never calledis that really possible i can and did fix this easily but i guess i am confused that that is what is happening and want to make sure i do not make mistakes like this going forward i tried to find out how or expressions like this are evaluated is there a place i can look to see how php gets compiled,['php'] +696779,appengine application using django fails to load django is constantly causing our application to crash after deployment the application is running fine but once the initial instance is restartedshutdown it often fails to start with an error similar to the followingtraceback most recent call last file basedatahomeruntimespython27python27 libversions1googleappengineruntimewsgipy line 266 in handle result handlerdictself environ self startresponse file basedatahomeruntimespython27python27 libversionsthird partydjango15djangocorehandlerswsgipy line 236 in call selfload middleware file basedatahomeruntimespython27python27 libversionsthird partydjango15djangocorehandlersbasepy line 53 in load middleware raise exceptionsimproperlyconfigurederror importing middleware s s mw module eimproperlyconfigured error importing middleware myfoldermiddleware no module named myfoldermiddlewareour file structure is similar to this appyaml init py settingspy myfolder init py middlewarepy our appyamlapplication xmodule appversion masterruntime python27api version 1threadsafe truehandlers url apiloginlogoutpasswdmasterbanners script apphandler secure alwaysbuiltins django wsgi onlibraries name django version 15env variables django settings module settingswe have 2 modules in our application and they both exhibit this behaviour they have similar configurations sometimes the modules will stay up for a whole day before crashing again after they fail to load all subsequent requests fail with he same error deploying one more time always solves the problem temporarilywe are using plain django with cloudsql the problem is not reproducible in the development server after deployment everything in both modules works fine all middleware ndb memcache cloudsql taskqueue etc including all the modules inside the myfolder and every other library xcopiedthe following attempts at solving this problem have not workedwe have tried using the appengine configpy to force django to reload the settings with from djangoconf import settingsnsettings target nonenoriginally we had shared settings inside myfolder and were importing them with from myfoldershared settings import inside the root settingspy but django could not load the module myfoldershared settings either similar problemusing a custom mysettingspy and defining the django settings module in the appyaml or in pythonthe system is not live yet but will be soon and we are running out of optionsother traces of similarly failing configurationstraceback most recent call last file basedatahomeruntimespython27python27 libversions1googleappengineruntimewsgipy line 266 in handle result handlerdictself environ self startresponse file basedatahomeruntimespython27python27 libversionsthird partydjango15djangocorehandlerswsgipy line 236 in call selfload middleware file basedatahomeruntimespython27python27 libversionsthird partydjango15djangocorehandlersbasepy line 45 in load middleware for middleware path in settingsmiddleware classes file basedatahomeruntimespython27python27 libversionsthird partydjango15djangoconf init py line 53 in getattr self setupname file basedatahomeruntimespython27python27 libversionsthird partydjango15djangoconf init py line 48 in setup self wrapped settingssettings module file basedatahomeruntimespython27python27 libversionsthird partydjango15djangoconf init py line 134 in init raise importerrorcould not import settings s is it on syspath s selfsettings module eimporterror could not import settings settings is it on syspath no module named myfoldersettingstraceback most recent call last file basedatahomeruntimespython27python27 libversions1googleappengineruntimewsgipy line 239 in handle handler config handleadd wsgi middlewareself loadhandler file basedatahomeruntimespython27python27 libversions1googleappengineapilib configpy line 353 in getattr self update configs file basedatahomeruntimespython27python27 libversions1googleappengineapilib configpy line 289 in update configs self registryinitialize file basedatahomeruntimespython27python27 libversions1googleappengineapilib configpy line 164 in initialize import funcself modname file basedatahomeappssbluemyappappmaster375531077560785947appengine configpy line 17 in settings target none file basedatahomeruntimespython27python27 libversionsthird partydjango15djangoutilsfunctionalpy line 227 in setattr self setup file basedatahomeruntimespython27python27 libversionsthird partydjango15djangoconf init py line 48 in setup self wrapped settingssettings module file basedatahomeruntimespython27python27 libversionsthird partydjango15djangoconf init py line 134 in init raise importerrorcould not import settings s is it on syspath s selfsettings module eimporterror could not import settings settings is it on syspath no module named myfoldersettingsthis is our current appengine configpyimport sysimport loggingloggingdebugnjoinsyspath since google app engines webapp framework uses django templates django will halfinitialize when webapp is loaded this causes the initialization of the rest of djangos setting to be skipped if you are getting this error you need to explicitly force django to reload your settingsfrom djangoconf import settingssettings target nonelogging syspath from appengine configpy does not change between a successful instance start and a failed instance start apart from the x bit of coursebasedatahomeappssbluepersomiappmaster3759720xbasedatahomeruntimespython27python27 thistlibpython27zipbasedatahomeruntimespython27python27 thistlibpython27basedatahomeruntimespython27python27 thistlibpython27platlinux2basedatahomeruntimespython27python27 thistlibpython27libtkbasedatahomeruntimespython27python27 thistlibpython27liboldbasedatahomeruntimespython27python27 thistlibpython27libdynloadbasedatahomeruntimespython27python27 thistlibpython27sitepackagesbasedatahomeruntimespython27python27 libversions1basedatahomeruntimespython27python27 libversionsthird partymysqldb124b4basedatahomeruntimespython27python27 libversionsthird partydjango15basedatahomeruntimespython27python27 libversionsthird partyprotorpc10basedatahomeruntimespython27python27 libversionsthird partywebapp2252basedatahomeruntimespython27python27 libversionsthird partywebob1basedatahomeruntimespython27python27 libversionsthird partyyaml310,['python'] +696843,nodejs strict mode are there any advantages to using use strict in nodejs for example a global object is not a good idea to use as all your requests will mutate said object assuming the object in question should be unique to each user of course in this case using strict mode would have been a good idea noi feel like strict mode is a good idea to pair with node but i have not been able to find any pros or cons to it via googlethisclaimer i know what use strict does this question is focusing on the server sided proscons,['javascript'] +696851,processing large files in python 10 gb or more lets say i have a text file of 10 gb i need to find how much times a phrase occurs in the text is there any faster way to do this that the one i am using bellowhow much would it take to complete the taskphrase how fast it iscount 0with openbigfiletxt as f for line in f count linecountphraseif i am right if i do not have this file in the memory i would meed to wait till the pc loads the file each time i am doing the search and this should take at least 40 sec for a 250 mbsec hard drive and a file of 10 gb,['python'] +696928,code too large how can i make a huge compiled lookup table i was at a programming competition last weekend a qualifier round for the icpc and i was trying to do a problem that involved among other things factoring integers in the range 0 i 10 into primesmy first thought was oh no factoring integers is in np we need to find a way to avoid spending time on it we were working in java being primarily a c programmer my first instinct was to precompute all of the primes up to 10 with a script format it as a java array and attempt to insert it into my code my reasoning was that it save us the time of running something like a sieve of eratosthenes during the timed section cut down the time complexity by something like a factor of n and breeze through iti was then hit with the code too large error and my fewhundredthousand int array was rejected by the compiler because of the rules of the competition it was not possible to read it in to a file or store it anywhere except the java file containing the class that had a main method i tried breaking it up into something like 10 int chunks but that did not work because it was still too large we had nothing to consult except for the java 7 documentation and i was not able to find anything about the code too large error message in it we eventually gave up tried another method and got it working but it ended up costing us something like 14 of our total time on the competition and harmed our score significantly so my question is was there any sane way to solve this problem with a lookup table is it just impossible to get a huge precompiled lookup table into a java programi am also curious about the reasoning behind this restriction of the language is it a security thing somehow why would a compiler limit the bytecode size of methods,['java'] +696958,how to resolve the failed to execute postmessage on domwindow error from a youtube embed using the youtube javascriptiframe api i am trying to seek to different times of a video among other thingsi have stripped down a demo to this var playerwindowonyoutubeiframeapiready function var iframe documentcreateelementiframe iframewidth 400 iframeheight 300 iframeid youtubeiframe iframesrc enablejsapi1originencodeuricomponentwindowlocationprotocoldocumentdomainplaysinline1rel0 iframesetattributeframeborder 0 iframesetattributeallowfullscreen documentgetelementbyidvideoappendchildiframe player new ytplayeryoutubeiframevar tag documentcreateelementscripttagsrc apivar firstscripttag documentgetelementsbytagnamescript0firstscripttagparentnodeinsertbeforetag firstscripttagif you take a look in the console you will see this errorfailed to execute postmessage on domwindow the target origin provided does not match the recipient windows origin i need this to resolve to start utilising the javascript api but i am not sure how to fix itupdatei have since restarted my computer and the error does not occur i will update if i see the error again,['javascript'] +697015,class bytes found but defineclassfailed for error when deploying ear i am trying to deploy and old code base with ejb 11 stuff to weblogic 1036 and keep getting this strange error class bytes found but defineclassfailed forthe classes are there and being found what is causing this,['java'] +697101,rails 4 skipping protect from forgery for api actions i have been implementing a rails 4 application with an api i want to be able to call the api from mobile phones and the webapp itself i came across this note while researching protect from forgeryit is important to remember that xml or json requests are also affected and if youre building an api youll need something likeclass applicationcontroller actioncontrollerbase protect from forgery skip before action verify authenticity token if json request protected def json request requestformatjson endendi was thinking of doing this but i have some reservationsquestionsthis solution seems to leave the csrf hole open because now an attacker could craft a link with an onclick javascript that posts jsonwould checking for an api token be a reasonable substitute ie what if instead of skipping the authenticity check allowing it to fail the check and recover in handle unverified request if the api token is present and correct for current useror maybe i should just make the webapp and mobile devices send the csrf token in the http headers is that safe how would the mobile phone even obtain the csrf token given that it is not rendering html forms to begin withedit for clarificationi am more concerned about the webapp user clicking a crafted csrf link the mobile users are authenticated authorized an have an api key so i am not concerned about them but by enabling csrf protection for the webapp users the mobile users are blocked from using the protected api i want to know the correct strategy for handling this and i do not believe the rails documentation gives the right answer,['ruby-on-rails'] +697164,how does the python interpreter know when to compile and update a pyc file i knew that a pyc file is generated by the python interpreter and contains the byte code as this question saidi thought python interpreter is using the time stamp to detect whether a pyc is newer than a py and if it is skipped compiling it again when executing the way what makefile doso i did a test but it seemed i was wrong i wrote tpy contains print 123 and t1py contains importt running command python t1py gave the output 123 andgenerated tpyc all as expectedthen i edited tpy as print 1234 and updated the time stamp oftpyc by using touch tpycrun python t1py again i thought i would get 123 but 1234indeed so it seemed the python interpreter still knew that tpyis updatedthen i wondered whether python interpreter will compile and generate tpyc every time running python t1py but when i run python t1py several times i found that the tpyc will not be updated when tpy is not updatedso my question is how python interpreter knows when to compile and update a pyc fileupdatedsince python interpreter is using the timestamp stored in the pyc file i think it a record of when pyc was last updated and when imported compare it with the timestamp of py fileso i tried to hack it in this way change the os time to an older one and edit py filei thought when imported again the py seems older than the pyc and the python interpreter will not update pyc but i was wrong again so does the python interpreter compare these two timestamp not in a older or newer way but in a exactly equal wayin a exectly equal way i means the timestamp in pyc records the when the py was last modified when imported it compares the timestamp with the current timestamp of py if it is not the same recompile and update pyc,['python'] +697511,list all the installed programs that can open a specific file type in java is it possible to get the list of all the applications that can open a certain file type from the os in java for eg list of all the applications that can open a txt or pdf file,['java'] +697543,http error 50019 cannot read configuration file in one of my aspnet apps all of a sudden i am unable to run it in visual studio 2013 due to the error thisplayed below it appears that it is trying to open the webconfig from a path that does not even exist all of my project code including webconfig are located under cprojectssourcecodeafemanagertrunkafemanagerweb i have found a number of posts here from users experiencing a similar error but the solutions seem to vary and none i have found so far seem applicable to my situation i looked in that tracelogfiles directory and the most recent log file there is five days old so it obviously has not been logging anything since i have been having this issue any suggestions are appreciated,"['c#', 'asp.net']" +697629,duplicate key error when creating a new mongoose subdocument when creating new document and then try to upsert a new subdocument i get this errorobject error e110 duplicate key error index salesusersgroap key objectid537b7788da19c4601d061d04 error e110 duplicate key error index salesusersgroupsgroupid 1 dup key objectid537b7788da19c4601d061d04 proto objectthe subdocument i am trying to insert is defined as subschema that has a groupid field with the requirements unique true sparse true the mongoose method call i am using to do the upsert is userfindbyidandupdateuserid push groups userupdate function err obj where userupdate groupid groupid after dropping the indexes the problem is fixed and this error no longer occursvar userschema new schema email type string required true unique true active type boolean default true username type string required true unique true password salt type string required true hash type string required true securityquestion question string salt string hash string mobile pin number number number createdate type date default datenow updatedate date lastlogindate date prevlogindate date passchangedate date locked boolean lockdate date failedcount number faileddate date profile profile preference preference courses usercourseschema groups usergroupschema rewards userrewardschema roles userroleschema scores userscoreschemavar usergroupschema new schema groupid type schematypesobjectid unique true sparse true joindate type date default datenow receivenotifications type boolean default true isadmin type boolean default false isowner type boolean default false ismoderator type boolean default false updatedate date,['javascript'] +697770,printing with a pause not working in java i have been trying to get a program writen in java to output text letter by letter with a pause in between each letter the code wordwraps a string and prints it my delay method slow works well when the delay is half a second or a second but at lower delay times it does some weird thingswhen printing and the delay is extra short the program hangs on that line for the delay times the number of letters being printed before the line return and then spits everything out at oncealso when the delay is set to 250 milliseconds the text also prints out incorrectlyin the example the string is lorem ipsum dolor sit amet consectetur adipiscing elit nulla vitae molestie leo sed molestie turpisthe expected output would belorem ipsum dolor sit amet consectetur adipiscing elit nulla vitae molestie leo sed molestie turpis but the output at 250 islrem ipsum dolrst aet conseteur adipiscing elit ulla vitae olestie lo sed oleste turis heres the codepublic static void mainstring args string x lorem ipsum dolor sit amet consectetur adipiscing elit nulla vitae molestie leo sed molestie turpis say500x works nicely does one letter at a time with a 05s wait in between systemoutprintln say250x has proper delay but prints strange stuff systemoutprintln say100x prints line by line with a wait of letters01s wait in betweenpublic static void sayint speed string words int i 0 int ii 0 while i wordslength slowspeed systemoutprint wordscharati if ii 50 wordscharati systemoutprintlnwordscharati ii 0 else ii i systemoutprintln public static void slowint time try threadsleeptime catchinterruptedexception ex threadcurrentthreadinterrupt alternate slow method with same glitchespublic static void slowint time long starttime systemcurrenttimemillis whilesystemcurrenttimemillis starttime time i am not sure if it is important but this is all done in netbeans 74 x64 with jdk 17i am new to java but not new to programming any help would be appreciatedthe main problem is the timing that is what i need to work the weird printing is just a question why,['java'] +697907,tomcat oomparachute how to configure correctly my system suffers from oom presumably due to a dos attacki am using tomcat 7 nioi am looking for ways to make my system more robust to these attacks although i do not expect to make tomcat completely immune i want to improve robustness as much as possiblemy logs showexception in thread httpnio8080exec285 exception in thread httpnio8080exec82 severememory usage is low parachute is non existent your system may start failingexception in thread poolcleaner2169425771400676008859 severememory usage is low parachute is non existent your system may start failingso i started investigating the oomparachutethe documentation says very littleintthe nio connector implements an outofmemoryerror strategy called parachute it holds a chunk of data as a byte array in case of an oom this chunk of data is released and the error is reported this will give the vm enough room to clean up the oomparachute represents the size in bytes of the parachutethe byte array the default value is 102410241mb please note this only works for oom errors regarding the java heap space and there is absolutely no guarantee that you will be able to recover at all if you have an oom outside of the java heap then this parachute trick will not helpso i am trying to figure outis there really a default like the doc says if so why am i getting parachute is non existent should i define a parachute what value should i put there what parameters play a role in determining the value of this parameter number of concurrent connections expected size of request total heapwhat does this parachute really dothanks,['java'] +697937,list lost its bullets why when i split an ul into two columns it is losing its bulletshtmlul classwithcolumns liringo ligeorge lijohn lipaululcssulwithcolumns mozcolumns 2 webkitcolumns 2 ocolumns 2 columns 2 liststyletypecircle not works example,"['html', 'css']" +697939,how to record android screen video programmatically in kitkat 44 i know this question has been asked so many times and there are so many questions answers and thiscussions available but i do not know what to do and what not to doi already referred this below all link to get solution with no luckhow to record video on kitkat 44i cannot screen record with my kitkat 44 moto xandroid kitkat start screenrecord from appscreen recorder with kitkatscreen recording kitkat with buttonwith lots of search i did not get any simple example to achieve this task since 2 days i am trying to achieve this but with no succeso the simple question is whether it is possible to record video of our own screen in android i just heard that it is possible from android 44 kitkat and i also check some app from marketi know to do this our device should be rooted and other things which required to do thisbut i am not getting how to develop this programmatically if any one have any idea then please guide me how to do this or any example or code will be great helpi appreciate your any kind of helpi try to develop with this simple piece of code but not getting anythingpublic void startrecordingview v file recordfolder environmentgetexternalstoragedirectory string record su a bit rate 80 timelimit 30 recordfolder recordmp4 recordfoldermkdir try process screenrecording runtimegetruntimeexecrecord catch ioexception e eprintstacktrace so basically i do not know what i have to do with this process screenrecording i mean how can i start progress,['android'] +697966,syntax error in constructor taking default argument stdmap consider simple code snippetinclude mapinclude stringstruct foo fooconst stdmapstdstring int bar stdmapstdstring int barbar stdmapstdstring int barint mainint argc char argv return 0when i compile it like this clang o foo foocpp i face errorsfoocpp773 error expected fooconst stdmapstdstring int bar stdmapstdstring int foocpp78 note to match this fooconst stdmapstdstring int bar stdmapstdstring int foocpp768 error expected fooconst stdmapstdstring int bar stdmapstdstring int same behaviour for clang 32 and clang 33so i am wondering if i missing something or is it a bug gcc does not complain,['c++'] +697994,spring 4 and java 8 invalid byte tag exception i am trying to run a simple junit test using spring and java 8 jdkrunwithspringjunit4classrunnerclasscontextconfigurationlocations classpathapplicationcontextxmlwebappconfigurationpublic class userservicestest test public void testjava8 setstring strings new hashset stringsadda stringsaddb stringsaddc stringsstreamfiltera aequalsaforeachp ptostring and i get this runtime error on startuporgaspectjapachebcelclassfileclassformatexception invalid byte tag in constant pool 18 at orgaspectjapachebcelclassfileconstantreadconstantconstantjava133 at orgaspectjapachebcelclassfileconstantpoolinitconstantpooljava45 at orgaspectjapachebcelclassfileclassparserreadconstantpoolclassparserjava186 at orgaspectjapachebcelclassfileclassparserparseclassparserjava131 at orgaspectjapachebcelutilnoncachingclassloaderrepositoryloadjavaclassnoncachingclassloaderrepositoryjava262 at orgaspectjapachebcelutilnoncachingclassloaderrepositoryloadclassnoncachingclassloaderrepositoryjava242 at orgaspectjapachebcelutilnoncachingclassloaderrepositoryloadclassnoncachingclassloaderrepositoryjava249 at orgaspectjweaverreflectjava15annotationfindergetannotationsjava15annotationfinderjava202 at orgaspectjweaverreflectreflectionbasedresolvedmemberimplunpackannotationsreflectionbasedresolvedmemberimpljava211 at orgaspectjweaverreflectreflectionbasedresolvedmemberimplhasannotationreflectionbasedresolvedmemberimpljava163 at orgaspectjweaverpatternsexactannotationtypepatternmatchesexactannotationtypepatternjava109 at orgaspectjweaverpatternsexactannotationtypepatternmatchesexactannotationtypepatternjava96 at orgaspectjweaverpatternsannotationpointcutmatchinternalannotationpointcutjava156 at orgaspectjweaverpatternspointcutmatchpointcutjava137 at orgaspectjweaverinternaltoolspointcutexpressionimplgetshadowmatchpointcutexpressionimpljava239 at orgaspectjweaverinternaltoolspointcutexpressionimplmatchesexecutionpointcutexpressionimpljava105 at orgaspectjweaverinternaltoolspointcutexpressionimplmatchesmethodexecutionpointcutexpressionimpljava96 at orgspringframeworkaopaspectjaspectjexpressionpointcutgetshadowmatchaspectjexpressionpointcutjava404 at orgspringframeworkaopaspectjaspectjexpressionpointcutmatchesaspectjexpressionpointcutjava271 at orgspringframeworkaopsupportaoputilscanapplyaoputilsjava224 at orgspringframeworkaopsupportaoputilscanapplyaoputilsjava262 at orgspringframeworkaopsupportaoputilsfindadvisorsthatcanapplyaoputilsjava294 at orgspringframeworkaopframeworkautoproxyabstractadvisorautoproxycreatorfindadvisorsthatcanapplyabstractadvisorautoproxycreatorjava118 at orgspringframeworkaopframeworkautoproxyabstractadvisorautoproxycreatorfindeligibleadvisorsabstractadvisorautoproxycreatorjava88 at orgspringframeworkaopframeworkautoproxyabstractadvisorautoproxycreatorgetadvicesandadvisorsforbeanabstractadvisorautoproxycreatorjava69 at orgspringframeworkaopframeworkautoproxyabstractautoproxycreatorwrapifnecessaryabstractautoproxycreatorjava376 at orgspringframeworkaopframeworkautoproxyabstractautoproxycreatorpostprocessafterinitializationabstractautoproxycreatorjava339 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactoryapplybeanpostprocessorsafterinitializationabstractautowirecapablebeanfactoryjava421 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactoryinitializebeanabstractautowirecapablebeanfactoryjava1558 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactoryinitializebeanabstractautowirecapablebeanfactoryjava398 at orgspringframeworktestcontextsupportdependencyinjectiontestexecutionlistenerinjectdependenciesdependencyinjectiontestexecutionlistenerjava1 at orgspringframeworktestcontextsupportdependencyinjectiontestexecutionlistenerpreparetestinstancedependencyinjectiontestexecutionlistenerjava75 at orgspringframeworktestcontexttestcontextmanagerpreparetestinstancetestcontextmanagerjava331 at orgspringframeworktestcontextjunit4springjunit4classrunnercreatetestspringjunit4classrunnerjava213 at orgspringframeworktestcontextjunit4springjunit4classrunner1runreflectivecallspringjunit4classrunnerjava290 at orgjunitinternalrunnersmodelreflectivecallablerunreflectivecallablejava15 at orgspringframeworktestcontextjunit4springjunit4classrunnermethodblockspringjunit4classrunnerjava292 at orgspringframeworktestcontextjunit4springjunit4classrunnerrunchildspringjunit4classrunnerjava233 at orgspringframeworktestcontextjunit4springjunit4classrunnerrunchildspringjunit4classrunnerjava87 at orgjunitrunnersparentrunner3runparentrunnerjava193 at orgjunitrunnersparentrunner1scheduleparentrunnerjava52 at orgjunitrunnersparentrunnerrunchildrenparentrunnerjava191 at orgjunitrunnersparentrunneraccess0parentrunnerjava42 at orgjunitrunnersparentrunner2evaluateparentrunnerjava184 at orgspringframeworktestcontextjunit4statementsrunbeforetestclasscallbacksevaluaterunbeforetestclasscallbacksjava61 at orgspringframeworktestcontextjunit4statementsrunaftertestclasscallbacksevaluaterunaftertestclasscallbacksjava71 at orgjunitrunnersparentrunnerrunparentrunnerjava236 at orgspringframeworktestcontextjunit4springjunit4classrunnerrunspringjunit4classrunnerjava176 at orgjunitrunnerjunitcorerunjunitcorejava157 at comintellijjunit4junit4ideatestrunnerstartrunnerwithargsjunit4ideatestrunnerjava74 at comintellijrtexecutionjunitjunitstarterpreparestreamsandstartjunitstarterjava211 at comintellijrtexecutionjunitjunitstartermainjunitstarterjava67 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava62 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43 at javalangreflectmethodinvokemethodjava483 at comintellijrtexecutionapplicationappmainmainappmainjava120i am using those aop librariesdependency groupidorgaspectjgroupid artifactidaspectjrtartifactid version1611versiondependencydependency groupidorgaspectjgroupid artifactidaspectjweaverartifactid version1611versiondependencyany idea,['java'] +698025,why would not ie implement my css rules instantly i am having difficulties with internet explorer even as uptodate as ie11 i am trying to write some javascript that will allow me to dynamically create a style sheet add it to the document and manipulate styles most of which is based on the article that david walsh wrote he had the idea of setting the media attribute of the created style tag so legacy browsers will simply ignore rules that they cannot support an idea that i really like but one that is causing me a few problemswhen i create a style tag with a media attribute more complicated than screen firefox and chrome will apply the new rules instantly assuming the media query matches but ie will not until some kind of page repaint is triggered resizing the page seems the most effectivei have created a fiddle to better demonstrate the issue i am seeing the results panel having a green background in firefox and chrome but red in ie until the repaint is forcedas for actually forcing a repaint i have tried a few tricks to no successdocumentbodyclassname documentbodyclassnameelementappendchilddocumentcreatetextnode documentbodystylewidth previouswidth 1 pxsimplifying the media query to all and minwidth 10px and even just minwidth 10pxmy question is how can i get ie to implement the styles when they are added or at least as close to the time their added a possible i can live with a settimeout being neededi am using jquery on the site itself so i will accept a jquery answer but i would prefer one without a library dependancy so i better understand whats causing the issue and how to resolve it,"['javascript', 'css']" +698041,wampmysql errors not in correct language i have reinstalled wamp multiple times searched literally hundreds of pages and its not fixed this issuei have looked inside the phpmyadmin config files setcfglang enutf8uninstalled multiple times as mentioned and seemed to have no luck what so ever any help would be appreciated,"['php', 'mysql']" +698136,cmake how to append string to the variable via command line in my cmakelisttxt i can do the following thing setcmake cxx flags cmake c flags new flags hereis it possible to to the same thing via command line like cmakeexe dcmake cxxflags new flags,['c++'] +698204,jwt json web token library for java i am working on a web application developed using java and angularjs and chose to implement token authentication and authorizationfor the exercise purpose i have come to the point where i send the credentials to the server generate a random token store it and send it back to the clientat every request to the server i am attaching the token in the header and it works perfectlyfor the authentication point of view is perfect and wouldnt need morehowever i now want to keep track of the user type admin regular user as well as it is id or any other unique field as i understood i have to encrypt that in the token that i am sending back to the client during the log in action is that correctis there any jwt library that you used and can generate encrypt and decrypt such tokensa link to the librarys api and maven dependency would be much appreciatedthanks,['java'] +698245,how to add deprecated to every class and every constructormethod of every class i have some legacy code and i want to mark all of them and all of their methods deprecated so that as we go and touch them we can remove these annotations so we can keep track of what has been modernized and what still is badi am trying to use the structural searchreplace and cannot seem to get the correct template goingsearch templateclass class returntype methodnameparametertype parameter stmt replace templatedeprecatedclass class deprecated returntype methodnameparametertype parameter stmt but this removes everything else that is in the classdeprecatedclass oldandcrusty deprecated this strips off all the visibility modifiers and final modifiers of all the classes it matcheshow do i replace these things and leave the rest of the code alone,['java'] +698284,dont stop the animation in listview i am working with animationdrawable for download progressbar i put the animation in getview an it is working fine but when i am scrolling the list the animation has been stoped is there any method in animationdrawable to fix this like setcancelable in dialogplease help me thanksimageview anim imageview rootviewfindviewbyidridimageview2animationdrawable animation animationdrawable animgetdrawableanimationstartscreenshot,['android'] +698343,find all references to child method i want to find all calls to datetimetostring references in my assembly in visual studio you can find all references by right clicking on tostring however that returns all references to tostring for all classes and not just datetimea regular search for datetimetostring would not work because of the following exampledatetime mydate new datetimemydatetostringany suggestions,['c#'] +698416,nuget package fails to add reference to project for dll inside lib directory i am attempting to package up a net dll which references a c dll the nuspec file looks like thisxml version10package metadata idmypackageid version100version authorssome authorauthors ownerssome ownerowners requirelicenseacceptancefalserequirelicenseacceptance descriptionnet wrapper for rebuilt 64bit version of mypackagedescription copyrightcopyright 2014copyright metadata files file srcx64mypackage64dll targetcontent file srcmypackagenetdll targetlib filespackagewhen i examine the generated nupkg file the internal file structure appears correct the c dll is in content and the net dll is in the lib when i install the nupkg into a project the content dll is added to the project root and the lib dll is added to the solution packages directoryhowever no reference is added to the project i am forced to manually add the reference i have tried adding the following node to metadata to no availreferences reference filemypackagenetdll referencesam i doing something wrong i have generated other nuspec nupkg files from varoius csproj files which properly add references to projects in which they have been installed is there something about the packaging of individual dlls i have missed that is keeping a reference from being added to the project on a related note if i cannot automatically add the reference can anyone direct me to any resources which would explain the syntax of the projectobjectreferenceadd method or which would help me programmatically add a reference to the dll to my project,"['c#', '.net']" +698474,java constant expressions and code elimination as thiscussed here javac and other java compilers may provide code elimination capabilities for ifstatements where the condition is a constant expressionhow is this affected if my code uses a constant expression that depends on other constant expressions defined in different packagesfor example let us say i have the following classes in the respective specified packagespackage foopublic class foo public static final boolean condition falseandpackage barimport foofoopublic class bar public void test if foocondition systemoutprintlnthis line of code could be eliminated else systemoutprintlnthis line of code will be executed clearly if the foopackage is loaded at runtime from an external jarfile the compiler cannot technically just assume that foocondition will be false and should not eliminate the truebranch of the ifstatementwhereas if foo and bar were actually in the same package the truebranch should definitely be eliminated if the compiler supports code elimination at allnot quite sure how to best phrase this question but how close does foo need to be to bar for a constant expression in foo to also be considered constant in bar would they need to be in the same file the same package the same jarfile or does it not matter at all ie would the compiler always consider foocondition as constant and use the value found in the buildpath during compile time,['java'] +698478,nodejs response from http request not calling end event without including data event so i have a simple client application communicating with a server side application in nodejs on the client side i have the following codefunction send name httprequest host 127001 port 30 url method post function response responsesetencodingutf8 responseondata function data consolelogdid get data data responseonend function consolelogn 03390m request complete039m procestdoutwriten your name responseonerror function error consolelogn error received error endquerystringify name name this posts the data to the requestthe odd part is if i do not include the data event via responseondata function data consolelogdid get data data the end event for the response is never fired off the server code is as followsvar query requirequerystringrequirehttpcreateserverfunction request response var body requestondata function data body data requestonend function responsewritehead200 responseenddone consolelogn got name 03390m queryparsebodyname 039mn listen30i would like to know why this is happening when the documentation to my knowledge does not require you to listen in on the data event in order to close a response session,['javascript'] +698488,losing superscript tag when converting html to docx using libreoffice i have the following htmlhtmlbodypnsupthsuppbodyhtmli am using the command libreoffice convertto docxms word 2007 xml testhtmlto convert that html into a docx file however i notice that the resulting docx file does not actually contain the sup tag it looks like it is using position and size to replicate the wvertalign tagwposition wval8wsz wval19what i would need to know is how to make libreoffice put in the wvertalign tag instead of using position and sizeadditonal infoi had a similar problem with bold and italics strongem but was able to get the conversion to work correctly if i converted the strong and em tags to b and i tags respectively,['html'] +698493,is there a java 8 equivalent of python enumerate builtin 3 years ago a similar question was asked hereis there a java equivalent of pythons enumerate functioni really appreciate the listiterator solution still i work a lot with the new streams and lambdas introduced in jdk 8 nowadays and wonder is there an elegant way of obtaining the index of the element being currently processed mine is presented below but i do not find it especially appealingintstreamrange0 mylistsize maptoobji dosthwithmylistgeti i,"['java', 'python']" +698563,make a property that is readonly to the outside world but my methods can still set in javascript es5 i am trying to achieve the following scenarioan object of which there will be many separate instances each with a readonly property size that can be read from the outside via direct property read but cannot be set from the outsidethe size property must be maintainedupdated from some methods which are on the prototype and should stay on the prototypemy api is already defined by a specification so i cannot modify that i am working on a polyfill for an alreadydefined es6 objecti am mostly trying to prevent people from shooting themselves in the foot accidentally and do not really have to have bulletproof readonlyness though the more bulletproof it is the better so i am willing to compromise some on side door access to the property as long as directly setting objsize 3 is not allowedi am aware that i could use a private variable declared in the constructor and set up a getter to read it but i would have to move the methods that need to maintain that variable off the prototype and declare them inside the constructor also so they have access to the closure containing the variable for this particular circumstance i would rather not take my methods off the prototype so i am searching for what the other options might bewhat other ideas might there be even if there are some compromises to it,['javascript'] +698638,getting unique clientid from chrome extension i am developing chrome extension i need the ability to identify each client as a unique clienti cannot store guid in a cookie since cookie can be deleted i need something to be read from the system itself which is uniquenow i know that js does not has access to client resources local resources but and here is my question questiondoes chrome extensions jss provide api for getting unique client information i dont care what data as long as it is uniqueedit just to clarify the user will be shown a unique key which is a hash data of his computer this code will be sent to me and i will provide matching result which the user will be sent via email and only then he will be able to use the extensionno not all countries support extension payment via wallet im at one of those countries,['javascript'] +698667,how to enable cors in angularjs i have created a demo using javascript for flickr photo search api now i am converting it to the angularjsi have searched on internet and found below configuration configurationmyappconfigfunctionhttpprovider httpproviderdefaultsusexdomain true delete httpproviderdefaultsheaderscommonxrequestedwithservicemyappservicedataservice functionhttp delete httpdefaultsheaderscommonxrequestedwith thisflickrphotosearch function return http method get url api key3f807259749363a29c76012fa93945tagsindiaformatjsoncallback datatype jsonp headers authorization token tokenxyz controllermyappcontrollerflickrcontroller functionscope dataservice scopedata null dataserviceflickrphotosearchthenfunctiondataresponse scopedata dataresponse consolelogscopedata but still i got the same errorhere are some links i triedxmlhttprequest cannot load url origin not allowed by accesscontrolalloworiginediti created a proxy server in nodejs on suggestion of quentinvar http requirehttpvar url requireurlvar fs requirefsvar serverserver httpcreateserverfunction req res your normal server code var path urlparserequrlpathname fsreadfile dirname path function err data if err return send404res reswritehead200 contenttypepath jsonjs textjavascript texthtml reswritedata utf8 resend serverlisten8001using express to load customizes static filesvar express requireexpress app expressappallapi function req res next resheaderaccesscontrolalloworigin resheaderaccesscontrolallowheaders cachecontrol pragma origin authorization contenttype xrequestedwith resheaderaccesscontrolallowmethods get put post return nextappusejs exprestatic dirname jsapplisten3001final editi removed the authorization headerheaders authorization token tokenxyz and it is running alright i have got what i wantedthanks everyone for participation in this question,['javascript'] +698726,project euler 8 i do not understand where i am going wrong i am working on project euler problem number eight in which ive been supplied this ridiculously large number 73167176531330624919225119674426574742355349194934969835203127745063262395783180169848018694788518438586156078911294949545950173795833195285320880551254069874715852386305071569329096329522744304355766896648950445244523161731856403098712172238311362989342338030813533627661428280648664523874930358907296290491560440772390713810515859307960866701724271218839987979087922749219016997208093776657273001053367881220235421809751254540594752243525849077116705560136048395864467063244157221553975369781797784617406495514929086256932197846862248283972241375657056057490261407972968652414535100474821663704844031998908895243450658541227588688116427171479924292823086346567481391912316282458617866458359124566529476545682848912883142607690042242190226710556263210937054421750694165896040807198403850962455436298123098787992724428490918458015616609791913387549920052406368991256071760605886116467109405077541002256983155205593572972571636269561882670428252483600823257530420752963450and am supposed to find the thirteen adjacent digits in the 10digit number that have the greatest product eg the product of the first four adjacent digits is 7 3 1 6my code is the following int main string num ridiculously large number omitted int greatestproduct 0 int product for int i0 i numlength 12 i product int numi 48 for int ji1 ji13 j product product int numj 48 if greatestproduct product greatestproduct product cout greatestproduct endli keep getting 2091059712 as the answer which project euler informs me is wrong and i suspect its too large anyway any help would be appreciatededit changed to unsigned long int and it worked thanks everyone,['c++'] +698825,how to get the current page url from the web view in android using webviewloadurlurl method i open an url if i click any button on the view it directs to another page now i want to get the url of the directed page how can i get iti also want the content that is thisplayed on the webview how to get the content of the webview,['android'] +698835,glassfish server startdomain domain1 would not start i recently downloaded glassfish 40 and i want to use it in netbeans for making some web applications but when i want to start the domain1 asadmin startdomain domain1 i keep getting this errorthere is a process already using the admin port 4848 it probably is another instance of a glassfish server any clue what could be the problem,['java'] +698871,how to run custom rake task via capistrano 3 which way i can run rake commands via capistrano on remote serverfor example i have a libtaskreparserake with some methods desc it is take csv file makes some changes and fill db with this infotask example1 environment do require csv rows to insert some actions endon local server all is fine i just run rake reparseexample1and it is workfill db correctlyso question is how can i run this command on real hosting after deployiam using rails 41 capistrano 3ps examples from site not work for mehow do i run a rake task from capistranoif i try cap production rakeinvoke taskreparselandit fails withcap aborteddo not know how to build task rakeinvokesome fixesnamespace somenamespace do task runrake do on rolesall in sequence wait 5 do within release path do execute rake envtask rails envproduction end end endendwith such way it begin to execute viacap production somenamespacerunrake taskcustom task filecustom method1,"['ruby-on-rails', 'ruby']" +698945,python abstract attribute not property whats the best practice to define an abstract instance attribute but not as a propertyi would like to write something likeclass abstractfoometaclassabcmeta property abstractmethod def barself passclass fooabstractfoo def init self selfbar 3instead ofclass fooabstractfoo def init self self bar 3 property def barself return self bar barsetter def setbarself bar self bar bar bardeleter def delbarself del self barproperties are handy but for simple attribute requiring no computation they are an overkill this is especially important for abstract classes which will be subclassed and implemented by the user i do not want to force someone to use property when he just could have written selffoo foo in the init abstract attributes in python question proposes as only answer to use property and abstractmethod it does not answer my question may be the right way but i am not sure it also only works with class attributes and not instance attributes,['python'] +698999,retrofit path replacements replacement over whole path including in my setup i get all the paths for my resources from the rest api from an initial call to the api we use this pattern to be able to change all the resource paths without breaking all existing app versions in the processi have been playing around with retrofit and i tried to create a method that would accept any path i pass to it as a string my try looks like thisgetpathpublic foobar getfoobarpathpath string pathi then try to call it as followsstring path foobarapigetfoobarpathunfortunately retrofit urlencodes the path replacement and i end up making a request to foo2fbar instead of foobar is there any way to thisable urlencoding for path replacements or to make replacements spanning multiple path segments unfortunately i do not even know how many path segments there are it is all controlled by the api,['android'] +699079,broadcastreceiver trying to return result during a nonordered broadcast package added in android i am getting this exception in my below given code i do not have any idea what is wrong with this code please help me out to get rid of this exception0523 2349853 ebroadcastreceiver26895 broadcastreceiver trying to return result during a nonordered broadcast0523 2349853 ebroadcastreceiver26895 javalangruntimeexception broadcastreceiver trying to return result during a nonordered broadcast0523 2349853 ebroadcastreceiver26895 at androidcontentbroadcastreceiverchecksynchronoushintbroadcastreceiverjava7830523 2349853 ebroadcastreceiver26895 at androidcontentbroadcastreceiversetresultcodebroadcastreceiverjava5490523 2349853 ebroadcastreceiver26895 at comwaypediarupeshabhiretentionapplicationaddedbroadcastreceiveronreceiveretentionapplicationaddedbroadcastreceiverjava180523 2349853 ebroadcastreceiver26895 at androidappactivitythreadhandlereceiveractivitythreadjava24460523 2349853 ebroadcastreceiver26895 at androidappactivitythreadaccess1700activitythreadjava1390523 2349853 ebroadcastreceiver26895 at androidappactivitythreadhhandlemessageactivitythreadjava12860523 2349853 ebroadcastreceiver26895 at androidoshandlerthispatchmessagehandlerjava1020523 2349853 ebroadcastreceiver26895 at androidoslooperlooplooperjava1360523 2349853 ebroadcastreceiver26895 at androidappactivitythreadmainactivitythreadjava51020523 2349853 ebroadcastreceiver26895 at javalangreflectmethodinvokenativenative method0523 2349853 ebroadcastreceiver26895 at javalangreflectmethodinvokemethodjava5150523 2349853 ebroadcastreceiver26895 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava7850523 2349853 ebroadcastreceiver26895 at comandroidinternaloszygoteinitmainzygoteinitjava6010523 2349853 ebroadcastreceiver26895 at dalviksystemnativestartmainnative methodbelow is my code public class retentionapplicationaddedbroadcastreceiver extends wakefulbroadcastreceiver overridepublic void onreceivecontext context intent intent componentname comp new componentnamecontextgetpackagename retentionaddintentserviceclassgetname start the service keeping the device awake while it is launching startwakefulservicecontext intentsetcomponentcomp setresultcodeactivityresult ok line 18,['android'] +699248,windows phone 8 development webapi authenticating via forms auth i am building an api with webapi that will accept authentication information over ssl via https from the web browser client the web browser uses forms authentication and requires https so it can securely sent usernamepassword to the api endpoint my api uses websecuritylogin and websecuritylogout to handle authentication for the web client how would this get handled in a wp8 application universal app built with winjs can i do the same thing send login registration credentials over https and use websecurity to handle forms auth heres how my webapi is currently set up for auth public httpresponsemessage loginloginmodel model if modelstateisvalid if useridentityisauthenticated return requestcreateresponsehttpstatuscodeconflict already logged in if websecurityloginmodelusername modelpassword persistcookie modelrememberme formsauthenticationsetauthcookiemodelusername modelrememberme return requestcreateresponsehttpstatuscodeok logged in successfully else return new httpresponsemessagehttpstatuscodeunauthorized if we got this far something failed return new httpresponsemessagehttpstatuscodeinternalservererrorpublic httpresponsemessage logout if useridentityisauthenticated websecuritylogout return requestcreateresponsehttpstatuscodeok logged out successfully return requestcreateresponsehttpstatuscodeconflict already doneis this approach compatible with wp8 or other native mobile app development authentication,['c#'] +699470,ie10 opera 12 opacity1 thisplayinline leads to a strange cropping in this question if the staff and community would not mind i would like to address two different bugs of different browsers though ocuring on same conditionsthe bugs happen when an element with thisplayinline and a boxshadow but this is set here more for a demonstration purpose gets opacity less than 1 thenie 10 at least chops the boxshadow as if overflowhidden was setopera 1215 leaves the box shadow only on the first line of the textthe html to demonstrate the issuespan classinline opaque spansome textspanspancssinline thisplayinline backgroundred boxshadow0 0 0 10px redinlineopaque opacity5a live example i am really frustrated with this happening seems very strange and unnatural for me would be very grateful for any helpthanksupdate seems i have found some workaround for ie it turns out that we can shift the boxshadow to the left and top the directions it does not crop in this bug and to make the element visually occupy the same space a transform can be applied it is better visible heremedia screen and mshighcontrastactivemshighcontrastnone block mstransformtranslate5px 5px transformtranslate5px 5px inline boxshadow5px 5px 0 5px c0c note that we need to shift possibly with translate the contents of inline as well,['css'] +699565,how to avoid using this in javascript prototypes heres my javascript object i would like to know how to avoid using this so many times in prototype i know there is lot of theory and links for prototypal inhericance and this has probably been answered already but as i have not been able to make all ends meet i thought this may be worth another questionfunction shapesmth thisa smth thisb 2 thisc 3shapeprototypedocalculus function return thisa thisb thisc 2 thisb thisc thisamoduleexports shape,['javascript'] +699855,cannot specify name of the download file using javascript i am using javascript to create a csv file for user to downloaduntil may 22nd chrome still downloaded the file with the name i specified however today i found that the files downloaded are named download and do not have the extension csvthis problem does not exist in firefoxhere is a fiddle with sample javascriptvar a nsqrtn initialize array of rows with header row as 1st itemforvar j1j10j apushj mathsqrtj var csvrows forvar i0lalength il i csvrowspushaijoin unquoted csv rowvar csvstring csvrowsjoinnvar a documentcreateelementaahref datatextcsvcharsetutf8base64 windowbtoacsvstringatarget blankadownload myfilecsvdocumentbodyappendchildaaclick,"['javascript', 'jquery', 'html']" +700047,xamarin android app crash in release mode parseandroid sdk i am developing app which uses parse android sdk app is working properly in debug mode but when i compile it on release mode i get following errors error occur when parse query is executed not when i initialize parsemonodroid unhandled exception systemnullreferenceexception object reference not set to an instance of an objectmonodroid at parseplatformhooksrequestasyncd 19movenext 0x0 in filename unknown0 monodroid end of stack trace from previous location where exception was thrown monodroid at systemruntimeexceptionservicesexceptionthispatchinfothrow 0x0 in filename unknown0 monodroid at parseinternalinternalextensionsc thisplayclass71systemtuple2systemnethttpstatuscodesystemcollectionsgenericidictionary2systemstringsystemobjectonsuccessb 6 systemthreadingtaskstask t 0x0 in filename unknown0 monodroid at systemthreadingtaskstaskactioninvokerfunctaskinvoke1systemthreadingtaskstask1systemtuple2systemnethttpstatuscodesystemcollectionsgenericidictionary2systemstringsystemobjectinvoke systemthreadingtaskstask owner systemobject state systemthreadingtaskstask context 0x0 in filename unknown0 monodroid at systemthreadingtaskstaskinnerinvoke 0x0 in filename unknown0 monodroid at systemthreadingtaskstaskthreadstart 0x0 in filename unknown0 monodroid end of stack trace from previous location where exception was thrown monodroid at systemruntimeexceptionservicesexceptionthispatchinfothrow 0x0 in filename unknown0 monodroid at parseinternalinternalextensionsc thisplayclass71systemcollectionsgenericienumerable1parseparseobjectonsuccessb 6 systemthreadingtaskstask t 0x0 in filename unknown0 monodroid at systemthreadingtaskstaskactioninvokerfunctaskinvoke1systemthreadingtaskstask1systemcollectionsgenericienumerable1parseparseobjectinvoke systemthreadingtaskstask owner systemobject state systemthreadingtaskstask context 0x0 in filename unknown0 monodroid at systemthreadingtaskstaskinnerinvoke 0x0 in filename unknown0 monodroid at systemthreadingtaskstaskthreadstart 0x0 in filename unknown0 monodroid end of stack trace from previous location where exception was thrown monodroid at systemruntimeexceptionservicesexceptionthispatchinfothrow 0x0 in filename unknown0 monodroid at systemruntimecompilerservicestaskawaiter1systemcollectionsgenericienumerable1parseparseobjectgetresult 0x0 in filename unknown0 monodroid at parsedalparsecallerinitc async0movenext 0x0 in filename unknown0 mono mono unhandled exceptionmono systemnullreferenceexception object reference not set to an instance of an objectmono at parseplatformhooksrequestasyncd 19movenext 0x0 in filename unknown0 mono end of stack trace from previous location where exception was thrown mono at systemruntimeexceptionservicesexceptionthispatchinfothrow 0x0 in filename unknown0 mono at parseinternalinternalextensionsc thisplayclass71systemtuple2systemnethttpstatuscodesystemcollectionsgenericidictionary2systemstringsystemobjectonsuccessb 6 systemthreadingtaskstask t 0x0 in filename unknown0 mono at systemthreadingtaskstaskactioninvokerfunctaskinvoke1systemthreadingtaskstask1systemtuple2systemnethttpstatuscodesystemcollectionsgenericidictionary2systemstringsystemobjectinvoke systemthreadingtaskstask owner systemobject state systemthreadingtaskstask context 0x0 in filename unknown0 mono at systemthreadingtaskstaskinnerinvoke monort error fatal unhandled exception systemnullreferenceexception object reference not set to an instance of an objectmonort at parseplatformhooksrequestasyncd 19movenext 0x0 in filename unknown0 monort end of stack trace from previous location where exception was thrown monort at systemruntimeexceptionservicesexceptionthispatchinfothrow 0x0 in filename unknown0 monort at parseinternalinternalextensionsc thisplayclass71systemtuple2systemnethttpstatuscodesystemcollectionsgenericidictionary2systemstringsystemobjectonsuccessb 6 systemthreadingtaskstask t 0x0 in filename unknown0 monort at systemthreadingtaskstaskactioninvokerfunctaskinvoke1systemthreadingtaskstask1systemtuple2systemnethttpstatuscodesystemcollectionsgenericidictionary2systemstringsystemobjectinvoke systemthreadingtaskstask owner systemobject state systemthreadingtaskstask context 0x0 in filename unknown0 monort at systemthreadingtaskstaskfollowing is the codeparseclientinitializeapp id dot net keyvar userquery parseobjectgetquery table namevar userdata await userqueryfindasync foreach var ud in userdata consolewriteline ud udgetstringconstantscol user namei tried with all linker option dont link link all assemblies link sdk assemblies but app is still crashing,"['c#', 'android']" +700120,c inherit class from template parameter i recently saw the following c codesnippettemplate class bclass a public b and i am wondering in which setting such a design is good practice the way i understand it is that having the superclass as a template parameter allows users of a to choose a superclass when instantiating an object of a but if this is the case wouldnt it be better to have a common superclass c for all the classes b which are used as the template argument and have a extend c,['c++'] +700126,code in try block continues executing after exception i am trying to implement google login on my website and am running into an issue here is my code after creating a google client objecttry clientauthenticate getcode plus new google service plusclient person pluspeoplegetme firstname personmodeldatanamegivenname catch google auth exception e response array error error authentication exception catch exception e response array error error uncaught exception clientauthenticate throws a google auth exception if the code passed to it is invalidif authentication failed then reading properties from the person object causes fatal errorsresponseis echod out as a jsonencoded objectthe problem is that the trycatch code does not seem to be working properly when authentication fails due to the code in getcode being invalid the following response is returned from the scripterrorerror authentication exceptionso far so good the code in the first catch block was executedhowever the code in the try block continues to execute in a weird fashion i say weird because in the above form a bunch of errors culminating in a fatal error occur meaning this linefirstname personmodeldatanamegivennameis still executed it should not be executed since an exception was thrown on a previous line if i comment out the above line the errors are not thrown again indicating this line is executed which it should not be here are the errors outputted due to the above line executing after the exception has been thrownnotice undefined index modeldata in googleapiphpclientmastersrcgooglemodelphp on line 78notice trying to get property of nonobject in ajax handlerphp on line 720 note this is the line shown above where the property is being accessednotice trying to get property of nonobject in ajax handlerphp on line 720another reason i said weird is that if i add this linediedying before reading propertyright before the above line where i read a property no errors occur but the dying before reading property text is not output onto the page this is weird because the script is clearly still executing code in the try block after the error is thrown since without this die line the line reading the property is executed and results in lots of errors being output as with before the code in the catch block is still executed and the json is output onto the pagewhat on earth is going on,['php'] +700150,is the accumulator of reduce in java 8 allowed to modify its arguments in java 8 stream has a method reducet reducet identity binaryoperatort accumulatoris the accumulator operator allowed to modify either of its arguments i presume not since the javadoc says the accumulator should be noninterfering though all examples talk of modifying the collection rather than modifying the elements of the collectionso for a concrete example if we have integersreduce0 integersumand suppose for a moment that integer was mutable would sum be allowed to modify its first parameter by adding to it in place the value of its second parameteri presume not but i would also like an example of where this interfering causes a problem,['java'] +700163,twitter bootstrap 3 navbar changes width when affix fires well i have a curious issue concerning the bootstrap3 affix script you can see the problem in this fiddle please maximise the resultframe horizontally and scroll down so that affix gets fired as you can see the navbar increases at the right side and i really cannot see any reason for this effect i temporarily solved the problem by addng containerpaddingleft 0pxpaddingright 0pxto the css but as you can see it is not very pretty and i do not want to remove these paddings alternatively i can set a static width likewidth 1140pxin navaffix but this is not very responsive i realy tried a lot of approaches but could not get any satisfying results do you know whats causing iteditokay chromes debugger gives me further informations before affix is fired the navelement got the class affixtop amongst others abstract from chromedebugger not html sourcenav idnav classnavbar navbardefault affixtop rolenavigation dataspyaffix dataoffsettop133 stylebackgroundcolor yellowcuriously affixtop is not declared in the htmlcode nevertheless navnavnavbarnavbardefaultaffixtop is sized like 1140px x 52pxafter scrolling and affix is fired the class affixtop changes to affix and affix is sized like 1170px x 52pxthese are the 30px the navbar grows to the right but how can i stop it above all i cannot find the class affixtop in any csvfiles,['css'] +700183,stackexchangerethis failing to connect with mono in mac os x i am trying to run a very simple rethis client on mono in mac os x with the following optionsvar configoptions new configurationoptions endpoints localhost 6379 resolvedns truekeepalive 180stringwriter sw new stringwriterconnectionmultiplexerconnectconfigoptions twit fails to connect here is the tracelocalhost6379keepalive180resolvednstrueusing dns to resolve localhostlocalhost 1270011 unique nodes specifiedrequesting tiebreak from 1270016379 booksleeve tiebreakallowing endpoints 01 to respond1270016379 faulted unabletoresolvephysicalconnection on ping1270016379 failed to nominate faulted unabletoresolvephysicalconnection on getno masters detected1270016379 standalone v200 master keepalive 0300 int connecting sub connecting not in use didnotrespond1270016379 int ops0 qu0 qs0 qc1 wr0 async1 socks2 sub ops0 qu0 qs0 qc0 wr0 socks1circular opcount snapshot int 0 0 opss spans 10s sub 0 0 opss spans 10ssync timeouts 0 fire and forget 0 last heartbeat 1s agostarting heartbeati have tried with and without resolvedns and specifying the ip address directly tried several ports as well server is running and is reachable by rethisclistackexchangerethis version10289 targetframeworknet45rethis64 289 updatestackexchangerethis version10297 targetframeworknet45 same problem but different loglocalhost6keepalive180resolvednstrueusing dns to resolve localhostlocalhost 1270011 unique nodes specifiedrequesting tiebreak from 1270016 booksleeve tiebreakallowing endpoints 05 to respond1270016 faulted unabletoresolvephysicalconnection on ping1270016 failed to nominate faulted unabletoresolvephysicalconnection on getno masters detected1270016 standalone v200 master keepalive 0300 int connecting sub connecting not in use didnotrespond1270016 int ops0 qu0 qs0 qc1 wr0 async1 socks2 sub ops0 qu0 qs0 qc0 wr0 socks1circular opcount snapshot int 0 0 opss spans 10s sub 0 0 opss spans 10ssync timeouts 0 fire and forget 0 last heartbeat 1s agoresetting failing connections to retryretrying attempts left 21 unique nodes specifiedrequesting tiebreak from 1270016 booksleeve tiebreakallowing endpoints 05 to respond1270016 returned but incorrectly1270016 failed to nominate faulted unabletoresolvephysicalconnection on getno masters detected1270016 standalone v200 master keepalive 0300 int thisconnected sub connecting not in use didnotrespond1270016 int ops0 qu0 qs0 qc1 wr0 async5 socks3 sub ops0 qu0 qs0 qc0 wr0 socks2circular opcount snapshot int 0 0 opss spans 10s sub 0 0 opss spans 10ssync timeouts 0 fire and forget 0 last heartbeat 1s agoresetting failing connections to retryretrying attempts left 11 unique nodes specifiedrequesting tiebreak from 1270016 booksleeve tiebreakallowing endpoints 05 to respond1270016 returned but incorrectly1270016 failed to nominate faulted unabletoresolvephysicalconnection on getno masters detected1270016 standalone v200 master keepalive 0300 int thisconnected sub connecting not in use didnotrespond1270016 int ops0 qu0 qs0 qc1 wr0 async8 socks4 sub ops0 qu0 qs0 qc0 wr0 socks3circular opcount snapshot int 0 0 opss spans 10s sub 0 0 opss spans 10ssync timeouts 0 fire and forget 0 last heartbeat 1s ago,['c#'] +700213,can dagger be used to perform injection on a content provider i have recently been integrating dagger into a project of mine that uses contentproviders i create a single objectgraph instance in my custom application object and basically in each managed componentactivity fragmentservice i call getapplication downcast to my custom application object and force the injection through some custom implementation in my application class this seems to be the prescribed method of performing injection based on the samples i have seen posted by the guys at squarethis pattern does not hold for contentprovider instances though as their lifecycle is not as predictably tied to the lifecycle of the application object ie contentproviders can be and as i am observing frequently are created before the application object is created for reasons i have yet to comprehendso does anyone have a nice way of injecting contentproviders using dagger i have so far made do by having an isinjected call at the beginning of each of my contentproviders interface methods insert query update delete basically a hacky form of lazy initialization but this seems far from ideal is there a more prescribed approach to injecting contentproviders,['android'] +700248,using shared ptr with multi inheritance class i have an class which inherit two interfacesclass multi public ifoo public ibar public virtual multi foo part virtual void foomethod bar part virtual void barmethod unfortunately this class cannot be decomposed in two separate classes for each interface in fact in class implementation those entities foo and bar are tightly coupled but in future they could become separateanother one class wants to use multi class having a pointer to ifoo and ibarclass clientclass public clientclass constructor smth private stdshared ptrifoo foo stdshared ptribar bar in constructor i do something likeclientclassclientclass auto pmulti new multi foo stdshared ptrifoopmulti bar stdshared ptribarpmulti but each of those shared pointers has separate reference counter and it leads to deleting already deleted pointer on class destruction am i righthow should i treat itwhat is best practics for such case,['c++'] +700324,changing menu order on collapsed navbar in bootstrap 3 i have a bootstrap 3 navbar that has two rightjustified ul sections which gives me thiswhen the menu is collapse for mobile i get thisi have two questions related to the collapsed menu 1 how can i get the buttons to appear at the bottom of the collapsed menu instead of the top 2 how can i change the styling of the buttons in the collapsed menu without affecting the style in the horizontal menubelow is the markup for this navbar and yes i have a reason for having two separate ul sectionsdiv classnavbar navbardefault navbarfixedtop div classcontainer div classnavbarheader button classnavbartoggle datatogglecollapse datatargetnavheadercollapse span classiconbarspan span classiconbarspan span classiconbarspan button a href classnavbarbrandmy sitea div div classcollapse navbarcollapse navheadercollapse ul classnav navbarnav navbarright lia href classbtn navbarbtn idbtn 1button oneali lia href classbtn navbarbtn idbtn 2button twoali ul ul classnav navbarnav navbarright lia hrefitem1ali lia hrefitem2ali lia hrefitem3ali lia hrefitem4ali ul div div div,['html'] +700405,using json type with flasksqlalchemy postgresql background i am building a flask app and i have stored my data into a postgresql database and within a json column type task in my view functions i would like to order a database query by keyvalue from json columnaccomplished i have been successful in performing this query at the psql commandline by using the following command for exampleselect from target where castproductprofit as float 100 order by castproductsalesrank as integer ascproblem i can not replicate this query in my code see code for model below in extra info sectionfrom app import app dbfrom models import target data targetqueryorder bytargetproductsalesrankerror received programmingerror programmingerror could not identify an ordering operator for type jsonline 2 from target order by targetproduct salesrank hint use an explicit ordering operator or modify the query select targetid as target id targetstore as target store targetproduct as target product targetasin as target asin targetdate as target date nfrom target order by targetproduct product 1s and limit param 1s product 1 salesrank param 1 1extra infomy target model was set up as suchmodelspyfrom app import dbfrom sqlalchemydialectspostgresql import jsonimport datetimeclass targetdbmodel tablename target id dbcolumndbinteger store dbcolumndbstring product dbcolumnjson asin dbcolumndbstring primary keytrue date dbcolumndbdatetime defaultdatetimedatetimeutcnowmy apy file where i define flask and sqlalchemyfrom flask import flaskimport osfrom flaskextsqlalchemy import sqlalchemyfrom flask bootstrap import bootstrapapp flask name appconfigfrom objectosenvironapp settingsdb sqlalchemyappbootstrapappimport viewsfrom app import appfrom models import resultif name main apprunhost19216815 port50 debugtruethank you for any help you can provide,['python'] +700409,get type of var with roslyn i have got a cs file named testcs which essentially looks likenamespace test public class testclass public void hello var x 1 i am trying to parse this with roslyn and get the type of x which should be int but i can only find out that it is type var i cannot seem to get the actual underlying typeheres basically what my code is nowvar location testcsvar sourcetree csharpsyntaxtreeparsefilelocationvar root compilationunitsyntaxsourcetreegetrootforeach var member in rootmembers get to a method var method methoddeclarationsyntaxmember foreach var child in methodbodychildnodes if child is localdeclarationstatementsyntax var x 1 childtyperealtype how can i get the real type of child i have seen some things saying i should use a semanticmodel or solution or a workspace but i cannot seem to find out how load my test solution with roslyn and then get the type of xalso i have not been able to find any really good roslyn documentation it all seems to be spread out among a bunch of different versions and nothing for beginners like me does anyone know of an intro to roslyn or similar quickstart i could read up on,"['c#', '.net']" +700518,how do you update an existing item in an angular array that has changed externally i am new to angular and am struggling with updating an existing item in my angular array that has changed externally not via angular powered ui here is the use casemy web page is populated via a server side call and i am loading the array into angular and thisplaying on a list now if the data on the server changes and a new record is inserted in the table my pages javascript is notified and it successfully inserts a new records into the angular array via push ref programmatically inserting array values in angular js however my page is also notified when an existing record is changed on the server side not via angular powered ui i am drawing a blank about how do i go about updating the correct record in my angular array is there a query update method that i have missed in the angular docshere is what my current code looks like the html ui updates to reflect the new data inserts div ngrepeatitem in items p classpriorityitempriority summaryp p classtypeitemtypep divhere is the script var app angularmoduledemoapp define controller var contrl appcontrollermaincontroller function scope scopeitems status new priority summary high status new priority summary high status new priority summary high status new priority summary high the insert works fine the question is how do i do an update if the notification is for an update and not for insert scopeadditem functionitem alertadditem called scopeitemspushitem scopeitem scopesubscribe function code for connecting to the endpoint alertevent received we receive this alert so event is received correctly scopeitemspush status new priority summary h scopeapply calling subscribe on controller initialization scopesubscribeany suggestions or examples highlighting this would be great thanks,['javascript'] +700555,c what are partially trusted callers i have not seen this clearly defined in one page partially trusted callers i am researching about aptca and this is always mentioned but msdn does not have an article about iti only had a few clues but i am not 100 sureare code executed from a network share qualify as partially trusted callers even if we run it as an administrator windows uacwhat are the other ways a net app is ran as partially trustedwhat are partially trusted callers in the aspnet environmenti have encountered many articles that mention the business about partially trusted callers but no direct definition on what they are per se,['.net'] +700572,elasticsearch index exists not working reliable i am writing a simple java wrapper around elasticsearchs admin client to test it i have a main method that first checks if an index exists indicesexistsrequest if so deletes it deleteindexrequest and creates the index again see code below yet i consistently get an indexalreadyexistsexceptionby the way i am trying to get a client for the node that you start from the command prompt by simply typing elastic search i have tried every combination of methods on nodebuilders fluent interface but i cannot seem to get onepublic static void mainstring args elasticsearchjavaclient esjc new elasticsearchjavaclientnda if esjcindexexists esjcdeleteindex esjccreateindex url url schemacreatorclassgetresourceelasticsearchspecimentypejson string mappings fileutilgetcontentsurl esjccreatetypespecimen mappingsfinal client esclientfinal indicesadminclient adminclientfinal string indexnamepublic elasticsearchjavaclientstring indexname thisindexname indexname esclient nodebuilderclusternameelasticsearchclienttruenodeclient adminclient esclientadminindicespublic boolean deleteindex loggerinfodeleting index indexname deleteindexrequest request new deleteindexrequestindexname try deleteindexresponse response adminclientdeleterequestactionget if responseisacknowledged throw new exceptionfailed to delete index indexname loggerinfoindex deleted return true catch indexmissingexception e loggerinfono such index indexname return false public boolean indexexists loggerinfostringformatverifying existence of index s indexname indicesexistsrequest request new indicesexistsrequestindexname indicesexistsresponse response adminclientexistsrequestactionget if responseisexists loggerinfoindex exists return true loggerinfono such index return falsepublic void createindex loggerinfocreating index indexname createindexrequest request new createindexrequestindexname indicesadminclient iac esclientadminindices createindexresponse response iaccreaterequestactionget if responseisacknowledged throw new exceptionfailed to delete index indexname loggerinfoindex created,['java'] +700581,toppostmessage origin error not catched i am trying to implement communication with postmessage there is the main page which opens a popup with an iframe which comes from a different domainthis works fine so far but i want to catch the following error which occurs when i open the iframe with a wrong originfailed to execute postmessage on domwindow the target origin provided myoriginurl does not match the recipient windows origin mywindowsoriginorigin if windowpostmessage try toppostmessagehello origin catchex alertan error occured the problem is that the code never runs into the catch block interesting part is that chrome shows an error in the console while all other major browser just do not do anything no alert no errorhow can i handle the error in the postmessagethanks,['javascript'] +700708,matplotlib hist autocropping range i am trying to make a histgram over a specific range but the matplotlibpyplothist function keeps cropping the range to the bins with entries in them a toy exampleimport numpy as npimport matplotlibpyplot as pltx nprandomuniform10010010nbins 100xmin 500xmax 500fig pltfigure ax figadd subplot1 1 1axhistx binsnbinsrangexminxmax pltshowgives a plot with a range 100100 why is the range not 500500 as specifiedi am using the enthought canopy 14 and sorry but i do not have a high enough rep to post an image of the plot,['python'] +700737,same table name different schema i have the following tables in my database all with the same table name but different schemasdboversions bpmversions wfversionall xversions have a fk to the version table i have created the poco classes from it this gave me classes like version version1 i have renamed the classnames to version and bpmversion but the mapping still exists to the right table this is an example of my mapping of bpmversion that maps to bpmversions primary keythishaskeyt tid properties table column mappingsthistotableversion bpmthispropertyt tidhascolumnnameidthispropertyt tversionidhascolumnnameversionidthispropertyt tbpmidhascolumnnamebpmid relationshipsthishasrequiredt tbpm withmanyt tbpmversions hasforeignkeyd dbpmidthishasrequiredt tversion withmanyt tbpmversions hasforeignkeyd dversionidwhen creating the migration script i have got the following exception the entity types bpmversion and version cannot share table versions because they are not in the same type hierarchy or do not have a valid one to one foreign key relationship with matching primary keys between themi found the following blogs on the internet it seams that ef has a problem with tables with the same name but different schema and is there anyway to avoid this problem without renaming the table names,['c#'] +700786,calculate ppi of android device how do i calculate ppi of android device most specifically android tablets take a note that i want to calculate ppi of the device and not dpi,['android'] +700790,angularjs ngclick on table row but not on a certain td i am facing an issue when there is an event datangclick on table rowbut i want that a certain td would not do the event in the rowis it possible to do itif so howexample html table tr datangclickdo some action td cell 1 is clickable td td cell 2 is clickable td td classnotclickablecell cell 3 is not clickable td tr table,"['javascript', 'html']" +700891,the entity type applicationuser is not part of the model for the current context i am migrating from identity 100 to identity 201 following this articleand the migrations code generated is nothing about the new identityuser it does not add the new columns so i made a new project and tried again but the migrations codes is empty to fix that problem i did the edits directly in sql server and imported my database again in my solution now my aspnetuser is exactly the same as my identityuser as you can seeidentityuserpublic virtual int accessfailedcount get set public virtual icollectiontclaim claims get public virtual string email get set public virtual bool emailconfirmed get set public virtual tkey id get set public virtual bool lockoutenabled get set public virtual datetime lockoutenddateutc get set public virtual icollectiontlogin logins get public virtual string passwordhash get set public virtual string phonenumber get set public virtual bool phonenumberconfirmed get set public virtual icollectiontrole roles get public virtual string securitystamp get set public virtual bool twofactorenabled get set public virtual string username get set identityusercspublic class applicationuser identityuser public bool has accepted policy get set public int user type id get set public class applicationdbcontext identitydbcontextapplicationuser public applicationdbcontext basedefaultconnection aspnetuserpublic string id get set requiredstringlength256public string username get set public string passwordhash get set public string securitystamp get set stringlength256public string email get set public bool emailconfirmed get set public bool is active get set requiredstringlength128public string thiscriminator get set public int user type id get set public bool has accepted policy get set public string phonenumber get set public bool phonenumberconfirmed get set public bool twofactorenabled get set public datetime lockoutenddateutc get set public bool lockoutenabled get set public int accessfailedcount get set other virtual properties and when i try to register a user i have the following exceptionthe entity type applicationuser is not part of the model for the current contextat this lineidentityresult result await usermanagercreateasyncuser modelpasswordmy startupauthcs usermanagerfactory new usermanagerapplicationusernew userstoreapplicationuserand in my accountcontroller i declare my usermanager like thispublic accountcontroller thisstartupusermanagerfactory startupoauthoptionsaccesstokenformatpublic accountcontrollerusermanagerapplicationuser usermanager isecuredataformatauthenticationticket accesstokenformat usermanager usermanager accesstokenformat accesstokenformatpublic usermanagerapplicationuser usermanager get private set i have not changed anything except the new properties in the aspnetuser class and it used to work well before the migration there is a similar issue on codeplex marked as fixed but they do not give the solutiondoes anyone know how to fix thiseditto be sure i did not do any mistakes when i edited my sql database i created another project and generated an identity database and i changed the connection string for that database and i still have the same errorsolutionwhen i have edited my database i have not noticed that in identity 200 they changed the user id for userid in aspuserclaims table after doing that i had the same error but then i did what tschmit007 said about adding the applicationdbcontext to the userstore constructor and now it works usermanagerfactory new usermanagerapplicationusernew userstoreapplicationusernew applicationdbcontext,"['c#', 'asp.net']" +700954,different entityframework versions in same solution i have an old silverlight application that uses ef5 and cannot be upgraded to ef6 i have another project that uses ef6 with a different context but i getcould not load file or assembly entityframework version60 cultureneutral publickeytokenb77a5c561934e089 or one of its dependencies the located assemblys manifest definition does not match the assembly reference exception from hresult 0x80131040i am assuming this is because ef5 is already loaded it is in the main project do not ask me why and it is still pointing to that dll instead of the ef6 one how can i get this to worki added runtime assemblybinding xmlnsurnschemasmicrosoftcomasmv1 dependentassembly assemblyidentity nameentityframework publickeytokenb77a5c561934e089 cultureneutral codebase version50 hrefcprojectsproject211ef2packagesentityframework500libnet45entityframeworkdll codebase version60 hrefcprojectsproject211ef2packagesentityframework610libnet45entityframeworkdll dependentassembly assemblybinding runtimeto my main webconfig following lgos suggestion but now i receiveasystemdataentityinternalconfigfileentityframeworksection cannot be cast to bsystemdataentityinternalconfigfileentityframeworksection type a originates from entityframework version50 cultureneutral publickeytokenb77a5c561934e089 in the context default at location cwindowsmicrosoftnetframeworkv4030319temporary aspnet filesproject211ef97babe28e7ea3fa9assemblydl30127509970646f08 d86ecf01entityframeworkdll type b originates from entityframework version60 cultureneutral publickeytokenb77a5c561934e089 in the context default at location cprojectsproject211ef2packagesentityframework610libnet45entityframeworkdllit looks like it is still trying to use ef5 despite it accessing the ef6 entity sectioni fixed this by adding binding redirects in the main webconfig i redirect to the new version then in a sub webconfig redirect to the old version,"['c#', '.net']" +701008,last evaluated expression in javascript is it possible in javascript to get the result of the last evaluated expression for examplevar a 3var b 5a bconsoleloglastevaluatedexpression should print 15so it would be something like eval where it returns the last evaluated expression but i cannot use eval,['javascript'] +701097,actionthispatchhttpuploadedfilecontent type not being initialized in rspec test background i have a book model with a cover file attribute that gets set with an uploaded file via one of my rails controllers i am using rails v404goal i want to test that only files with certain content types get saved i plan to create rspec test examples with actionthispatchhttpuploadedfile objects set with different content type attributesproblem when i initialize a new actionthispatchhttpuploadedfile with a content type it does not seem to get set see test output below that confirms that it is nil it seems that i can only set it with a setter after the uploadedfile has been initialized i do not see any mention of this behavior in the docs nor could i find a similar qa on so so i would appreciate anyones help in determine what i am doing wrong thankscodedescribe book do letbook factorygirlbuildbook describe save do context with valid data do before do cover image filenewrailsroot specfixturesimagescover validjpg bookcover file actionthispatchhttpuploadedfilenewtempfile cover image filename filebasenamecover image content type imagejpeg puts bookcover filecontent typenil bookcover filecontent type imagejpeg puts bookcover filecontent type end specifyexpectbooksaveto be true end endendoutputtrueimagejpeg,"['ruby-on-rails', 'ruby']" +701152,does php actually use ie754 floating point numbers the ie754 floating point standard saysfour mutually exclusive relations are possible less than equal greater than and unordered the last case arises when at least one operand is nan every nan shall compare unordered with everything including itselfand yet codepad herephpecho phpversion zend version php uname n 525 220 linux 2cf38fbc9b9e 311015generic 25ubuntu smp thu jan 30 172201 utc 2014 x86 64nan nan truenan nan trueinf inf trueinf inf trueso clearly there is more than one relation between nan and nan and between inf and inf when there should only be one in many most all languages with ie754 floats unordered means that nan nan is false and nan nan is false and nan nan is false does this demonstrate that php does not use ie754 floating point numbers,['php'] +701291,deserialize json in a tryparse way when i send a request to a service that i do not own it may responds either with the json data requested either with a json error that looks like that error status error message code 9 in these two cases http response code is 200 okso i cannot rely on it i have to deserialize the response to check whether it is an error or notso i have something that looks like that bool tryparseresponsetoerrorstring jsonresponse out error error check expected error keywords presence before try clause to avoid catch performance drawbacks if jsonresponsecontainserror jsonresponsecontainsstatus jsonresponsecontainscode try error new jsonserializererrordeserializefromstringjsonresponse return true catch the json response seemed to be an error but failed to deserialize it may be a successful json response do nothing error null return falsehere i have an empty catch clause that may be in the standard execution path which is a bad smell well more than a bad smell it stinksdo you know a better way to tryparse the response in order to avoid a catch in the standard execution path editthanks to yuval itzchakovs answer i improved my method like that bool tryparseresponsestring jsonresponse out error error check expected error keywords presence if jsonresponsecontainserror jsonresponsecontainsstatus jsonresponsecontainscode error null return false check json schema const string errorjsonschema type object properties error typeobject status type string code type string additionalproperties false jsonschema schema jsonschemaparseerrorjsonschema jobject jsonobject jobjectparsejsonresponse if jsonobjectisvalidschema error null return false try to deserialize try error new jsonserializererrordeserializefromstringjsonresponse return true catch the json response seemed to be an error but failed to deserialize this case should not occur error null return false i kept the catch clause just in case,"['c#', '.net']" +701321,why javascript is giving access to override the existing properties in builtin object generally javascript allows to override extend the new behavior any function except those objects which are not frozen or seal in javascript math is a builtin object but why javascript is giving access to override the existing properties in builtin object please find screenshot initially i find min function is available in math object i have updated min property with function this action replaced the existing code for more clarity i have deleted the property from min here deletion should remove the extended behavior not the core one but it is removing core property why,['javascript'] +701490,jquery datatables tabletools export only visible rows i just started out using jquery datatablesusing the tabletools of datatables is it possible to only export visible rows instead of all the rows if for example the pagination was set to 10 i would expect only 10 rows to be exported the same goes for a search resultheres part of the codedocumentreadyfunction var table exampledatatable pagingtype full numbers ithisplaylength 10 dom tclearlfrtip otabletools abuttons sextends copy mcolumns visible bselectedonly true sextends xls mcolumns visible sextends print mcolumns visible srowselect multi order 0 asc thank you,['jquery'] +701603,how to make a qlineedit not editable in windows i am using qt 52 and i would like to make a qlineedit not editable the problem with this is that it does not appear like it when using setreadonlytrue it stays with white background and looks like it is still editableif i thisable it then it turns gray and the text also gets a lighter gray the problem is that one can not copy the text from it in a thisabled stateso how can i make a qlineedit properly noneditable and also make it look like it in windows such a control is usually gray but the text stays black of course i could set the style manually but this means that it is hardcoded and may look wrong on other platforms,['c++'] +701683,athe item you were attempting to purchase could not be founda android inapp billing i am receiving this error while testing my app the app is signed and uploaded to the alpha testing portion of the developer consolethe inapp item has the status activei have entered an account other than my developer account in testing accessi am using a device with the primary account in the testing access and not the developer accounti have double checked the spelling of my skuthe exact same apk was uploaded to developer console and installed on the test devicei have double checked the license keyi have waited more than 12 hours for sku and testing accounts to be propagatedeverything appears to work when i use androidtestpurchasedthere are multiple questions concerning this error related links that got me this far includetopicandroiddevelopersa2rm4p34zo0how to resolve athe item you were attempting to purchase could not be foundathe item you were attempting to purchase could not be found after following instructionsthe item you were attempting to purchase could not be found testinghtmlbillingtestingtesttesting android inapp purchases with unpublished appsandroid inapp purchase for alpha test modeerror the item you were attemping to purchase could not be founditem could not be found in app billing issuein app billing product not foundandroid billing item not found google play inapp billing into an android application e28093 a tutorialdo test accounts require real credit card to purchase via inapp billingwhat else can be causing this errorone time i got past this point my wifes phone and account are used for testing it appeared to work after including her account to have testing access and waiting 3 hours the item was found and it asked to verify her account password i handed her the device she entered the password she said there was an error and closed the dialog i do not know what that error was and i have not been able to get back to that point i am certain that the item was not purchased because it does not show up on the owned list after this i used another device with another account and another 3 hours the new device never gets anything other than the item not found error while using the active sku,['android'] +701732,no architectures to compile for archsi386 valid archsarm64 armv7 armv7s preface i did look at similar questions and none of the answers seemed to fix my problemi am trying to build my xcode version 511 project using xcodebuild clean build sdk iphonesimulator70 arch armv7s only active archno when i run this i get no architectures to compile for archsarmv7s valid archsi386 x86 64 as an error i tried the above command with all of the valid archs rm64 armv7 armv7s as inputs so i then tried running this command xcodebuild clean build sdk iphonesimulator70 arch i386 only active archnoand i then get no architectures to compile for archsi386 valid archsarm64 armv7 armv7s as an error i tried running the above command with all the other valid archs i386 x86 64 and no luck with that either i do not know why these architecture errors are occurring i have cocoapods in my project and the first answer in the link above did not fix my issue,['ios'] +701752,why cannot laraveleloquent use join for eager loading phpclass cat extends eloquent public function user return thisbelongstouser class user extends eloquent public function cats return thishasmanycat nowcats catwithusergetperforms 2 queriesselect from catsselect from users where usersid in 1 2 xwhy cannot it just doselect from cats inner join users on catsuser id usersidfor those saying that there are both id columns in the table that could be easily avoided with aliasesselect cid as cats id cname as cats name cuser id as cats user id bid as users id bname as users namefrom cats cinner join users b on bid cuser idupdate someone pointed out that eloquent doenst know the columns of the tables from the models but i guess they could provide a way to define them in the model so then it could use aliases and do a proper join instead of an extra query,['php'] +701764,firefox 30 is not hiding select box arrows anymore i have always used the trickselect mozappearance none textindent 001px textoverflow to do custom select boxes on ff but since version 30 is released this stopped working completely i have tried to find if this was deprecated but could not find anything is there a workaround or another method to replace this,"['html', 'css']" +701782,is it a wrong code in msdn i found the following code in msdn here which appears to be wrong compiletime error is not itdelegate void dint xclass c public static void m1int i public void m2int i class test static void main d cd1 new dcm1 static method test t new c wrong d cd2 new dtm2 instance method d cd3 new dcd2 another delegate consider this linetest t new cthe class c is not derived from the class test so this assignment will not compile am i am missing something here some assumptions that i have not considered in the articlealso the following line would be wrong even if c class was derived from testd cd2 new dtm2is not it,['c#'] +701798,sharing image to whatsapp facebook i am already able to share photos to whatsapp but the way i do this is by providing whatsapp option in a uiactivityviewcontroller and then showing a uidocumentinteractioncontrollerfrom this uidocumentinteractioncontroller i choose the whatsapp option which redirects the user to whatsapp and enables him to share the photoso far my code is like thisif activitytype isequaltostringwhatsappsharing if uiapplication sharedapplication canopenurl nsurl urlwithstringwhatsappapp nsstring savepath nshomedirectory stringbyappendingpathcomponentdocumentswhatsapptmpwai uiimagejpegrepresentationfinalimage 10 writetofilesavepath atomicallyyes weakdocumentinteraction uidocumentinteractioncontroller interactioncontrollerwithurlnsurl fileurlwithpathsavepath weakdocumentinteractionuti netwhatsappimage weakdocumentinteractiondelegate weakself weakdocumentinteraction presentopeninmenufromrectcgrectzero inviewweakselfview animatedyes i want to be able to select the option from a uiactivityviewcontroller and directly show whatsapp is there a way to jump this second part of presenting the uidocumentinteractioncontroller and selecting the whatsapp app option programmaticallycurrently the user has to select the whatsapp option twice in order to share the imageps i am using uiactivityviewcontroller because i am using other activities too,"['ios', 'objective-c']" +701805,how to copy inputstream to asynchronousfilechannel i want to read from a tomcat servlet inputstream and copy the large content to a file asynchronously using the asynchronousfilechannel i can do it with a regular filechannel and read about the missing transferto but if i use the java 7 asyncfilechannel i always get the bufferoverflowexception try asynchronousfilechannel output asynchronousfilechannelopenpath standardopenoptioncreate standardopenoptionwrite outputlock need to lock this is one key reason to use channel readablebytechannel input channelsnewchannelinputstream servlet inputstream bytebuffer buf bytebufferallocate4096 int position 0 int count futureinteger lastwrite null while count inputreadbuf 0 bufposition 0 loggerinforead bytes count bufflip outputwritebuf position if count 0 position count bufcompact if lastwrite null lastwriteget10 timeunitsecondsthen when running i get141230597 httpbio9090exec3 info cbpcblobuploadservlet read 4096 bytes141230597 httpbio9090exec3 info cbpcblobuploadservlet read 0 bytes many more with 0 bytes read 141230597 httpbio9090exec3 info cbpcblobuploadservlet read 3253 bytes141230605 httpbio9090exec3 error cbpcblobuploadservlet nulljavaniobufferoverflowexception nullat javanioheapbytebufferputheapbytebufferjava183 na170 17at javaniochannelschannelsreadablebytechannelimplreadchannelsjava393 na170 17how can i fix the bufferoverflow also whats the proper way to suspend the loop and wait when 0 bytes are read,['java'] +701929,php convert utc time to local time am getting a utc time from my server like the following format my requirement is to convert the utc time to local time so users can see a user friendly time on their browser based on their timezone please help me to solve this issue thank you utc 20140529t045430934zi have tried some methods but not working in my case first time strtotimeutcdateinlocal dateymd his timeecho dateinlocalsecond time strtotimeutc utcdateinlocal dateymd his timeecho dateinlocal,['php'] +701940,when are doms removed from memory i am working on an application that is creating and removing a lot of doms i have notice that the process memory from the browser tab continuously increases despite the javascript heap memory remaining constant in a test application i create and remove divs from a parent divbutton onclickcreatestuffcreatebuttonbutton onclickdeletestuffdeletebuttondiv idparentdivfunction createstuff var parentdiv documentgetelementbyidparent for var i 0 i 50 i var child documentcreateelementdiv childid i childtextcontent i parentdivappendchildchild child null parentdiv nullfunction deletestuff var parentdiv documentgetelementbyidparent for var i 0 i 50 i var child documentgetelementbyidi parentdivremovechildchild child null parentdiv nulli have confirmed that the javascript heap is not leaking with the chrome dev tools i am new to them so i could have missed something however the memory for the process continues to increase from everything i have read i suspect that the removed doms are still in the dom heap other posts also say that the browser will eventually free the memory allocated to the removed doms in the above jsfiddle example i have hit create and delete several times my javascript heap is steady at 49mb my process memory is up to 115mb i have waited 30 mins and it has not gone down at allquestionswhen are removed dom elements completely removed from the browser process memoryis there a way to force dom garbage collectionis there a tool to get more insight into what doms are marked for garbage collection i could not find one in chrome or ie thanks for the helpediti have used the chrome dev tools and the javascript heap is not growing interestingly the only thing that changes between the heap snapshots is an array object it is my understanding that anything in parenthesis is controlled by the browser and outside of my reach each subsequent createdelete removes the old array object and creates a new one during the deletein timeline i can see that the javascript heap is constant and the nodes get cleaned up but the memory as shown with shift esc never goes down even after the node count dropsit seems like i am doing everything i can to make sure i cleanup my javascript heap but the dom cleanup is out my reach and independent of the javascript gc is this statement correctare the removed doms part of the young generation heap is there a way to set a limit on this heap size i repeated the test until i had reached 500mb and still no cleanup i am using chrome 3501916114 btw,"['javascript', 'html']" +702003,how does ptrace work in linux the ptrace system call allows the parent process to inspect the attached child for example in linux strace which is implemented with the ptrace system call can inspect the system calls invoked by the child processwhen the attached child process invokes a system call the ptracing parent process can be notified but how exactly does that happen i want to know the technical details behind this mechanismthank you in advance,['c'] +702036,is stdmove really needed on initialization list of constructor for heavy members passed by value recently i read an example from cppreferencevectoremplace backstruct president stdstring name stdstring country int year presidentstdstring p name stdstring p country int p year namestdmovep name countrystdmovep country yearp year stdcout i am being constructedn my question is this stdmove really needed my point is that this p name is not used in the body of constructor so maybe there is some rule in the language to use move semantics for it by defaultthat would be really annoying to add stdmove on initialization list to every heavy member like stdstring stdvector imagine hundreds of kloc project written in c03 shall we add everywhere this stdmovethis question moveconstructorandinitializationlist answer saysas a golden rule whenever you take something by rvalue reference you need to use it inside stdmove and whenever you take something by universal reference ie deduced templated type with you need to use it inside stdforwardbut i am not sure passing by value is rather not universal reference updateto make my question more clear can the constructor arguments be treated as xvalue i mean expiring valuesin this example afaik we do not use stdmovestdstring getname stdstring local hello so return local stdmovelocal is not needed nor probably correctso would it be needed herevoid presidentsetdefaultname stdstring local so name local stdmove or not stdmovefor me this local variable is expiring variable so move semantics could be applied and this similar to arguments passed by value,['c++'] +702079,how inject stateprovider in angular application i try to use angularui and try to inject stateproviderhtmldoctype htmlhtmlhead script srcscript script srcscript script srcscript script srctestappmodulejsscriptheadbody div ngappappmodule div ngcontrollerappcontroller date div divbodyhtmljs testappmodulejsvar module angularmoduleappmodule uiroutermodulecontrollerappcontroller scope stateprovider function scope stateprovider scopedate new date stack traceerror unknown provider stateproviderprovider stateprovider at error native at if i remove stateprovider and uirouter with comments everything will workvar module angularmoduleappmodule uiroutermodulecontrollerappcontroller scope stateprovider function scope stateprovider scopedate new date so the problem with injection stateprovider any ideas about resolvingps i have tried ui sample it works but i cannot figure out why mine does not,"['javascript', 'html']" +702222,mipmap drawables for icons since android 43 we can now make use of the resmipmap folders to store mipmap imageseg chrome for android stores its icons in these folders instead of the more normal resdrawable foldershow are these mipmap images different from the other familiar drawable imagesi see that in my manifest we use the mipmap qualifier instead of drawable which makes sense given the resource folder nameactivity androidnamemipmapdemp androidiconmipmapic launcher referencesthe android 43 apis document has the following to sayusing a mipmap as the source for your bitmap or drawable is a simple way to provide a quality image and various image scales which can be particularly useful if you expect your image to be scaled during an animationandroid 42 api level 17 added support for mipmaps in the bitmap classaandroid swaps the mip images in your bitmap when youve supplied a mipmap source and have enabled sethasmipmap now in android 43 you can enable mipmaps for a bitmapdrawable object as well by providing a mipmap asset and setting the androidmipmap attribute in a bitmap resource file or by calling hasmipmapi do not see anything in there that helps me to understandxml bitmap resources have an androidmipmap propertyboolean enables or thisables the mipmap hint see sethasmipmap for more information default value is falsethis does not apply to launcher icons as far as i can seethe question was raised on google groups the purpose of resource name mipmap to which romain guy repliedit is useful to provide an image at a larger resolution that would normally be computed for instance on an mdpi device launcher might want the larger hdpi icon to thisplay large app shortcutsi feel like this almost makes sense of it but not quitei am still inclined to go with randy sugiantos follow upwhat are the advantages of this is there any guide how to use mipmaps probably for better launcher iconsof course wikipedia has a page for mipmap which refers to an older technique invented in 1983 that i cannot quite relate to the current android implementationshould we be storing all our app icons in resmipmap folders these days and what are the guidelines for these mipmap imagesupdate 1 heres a blog post that tries to explain it a bit mipmapping for drawables in android 43but the image used in that blog post shows what looks like 1 file with many logos in it this is not what i see in chromes mipmap folder chromes mipmaphdpi folder contains 3 images one is the chrome logo on its ownstrangely it is 72x72 not 48x48 which i would expect to see perhaps that is all there is to this we just need to keep bigger icons in the mipmap foldersupdate 2the android developers blog post of 23102014 again confirms the idea of using the mipmap folders for application iconsgetting your apps ready for nexus 6 and nexus 9when talking about the nexus 6 screen density the author writesitas best practice to place your app icons in mipmap folders not the drawable folders because they are used at resolutions different from the deviceas current density for example an xhdpi app icon can be used on the launcher for an xxhdpi deviceupdate 3note that android studio creates the ic launcherpng icons in the mipmap folders rather than the drawable folders that eclipse used to create them in,['android'] +702225,converting an rgb image to grayscale and manipulating the pixel data in python i have an rgb image which i want to convert to a grayscale image so that i can have one number maybe between 0 and 1 for each pixel this gives me a matrix which has the dimensions equal to that of the pixels of the image then i want to do some manipulations on this matrix and generate a new grayscale image from this manipulated matrix how can i do this,['python'] +702232,enum in swagger i am wondering how to document enums in swaggeraccording to javadocthe datatype see the documentation for the supported datatypes if the data type is a custom object set it is name or nothing in case of an enum use string and allowablevalues for the enum constantsbut i did not find some good java example how to really use it specification is herejavafirst servicepackage betlistatestsswaggerimport betlistatestsswaggermodelinputimport betlistatestsswaggermodeloutputimport comwordnikswaggerannotationsapiimport comwordnikswaggerannotationsapioperationapivalue first position 1public class restservicefirst apioperationvalue foo1 operation httpmethod post position 1 nickname foo public void foo1input input apioperationvalue bar1 operation response outputclass httpmethod get position 2 nickname bar public output bar1 return null second servicepackage betlistatestsswaggerimport betlistatestsswaggermodelinputimport betlistatestsswaggermodeloutputimport comwordnikswaggerannotationsapiimport comwordnikswaggerannotationsapioperationapivalue second position 2public class restservicesecond apioperationvalue foo2 operation httpmethod post position 1 public void foo2input input apioperationvalue bar2 operation response outputclass httpmethod get position 2 public output bar2 return null inputpackage betlistatestsswaggermodelimport comwordnikswaggerannotationsapimodelimport comwordnikswaggerannotationsapimodelpropertyapimodelpublic class input apimodelpropertydatatype string allowablevalues m t value description notes notes public day daydaypackage betlistatestsswaggermodelpublic enum day monday tuesday wednesday thursday friday saturday sundayoutputpackage betlistatestsswaggermodelimport comwordnikswaggerannotationsapimodelapimodelvalue outputpublic class output apimodelproperty string fieldpomxmlproject xmlns xmlnsxsi xsischemalocation modelversion400modelversion groupidbetlistagroupid artifactidtestsswaggerartifactid version001snapshotversion dependencies generate rest documentation dependency groupidcomwordnikgroupid artifactidswaggerjaxrs 210artifactid version132version dependency dependencies build plugins plugin groupidcomgithubkongchengroupid artifactidswaggermavenpluginartifactid version20version configuration apisources apisource locationsbetlistatestsswaggerbetlistatestsswaggermodellocations apiversion100apiversion basepathhttplocalhostportrestbasepath outputtemplatebasedirstrapdownhtmlmustacheoutputtemplate outputpathbasedirtargetgeneratedstrapdownhtmloutputpath swaggerdirectorybasedirtargetgeneratedapidocsswaggerdirectory useoutputflatstructurefalseuseoutputflatstructure apisource apisources configuration executions execution phasecompilephase goals goalgenerategoal goals execution executions plugin plugins buildprojectyou can see the result herethere is a lot of problems in html output i see missing output description wrong urls description is used for notes but the one i do not know how to overcome is enum usagein testsswaggertargetgeneratedapidocsfirstjson should be i think models input id input description properties day type string enum m t but there is models input id input description properties day ref day enum m t and the ref is a problem i thinkany idea,['java'] +702233,issues with css currentcolor keyword in ios and safari tldrheres a fiddle thank you nicoo in safari initial red colour gets applied to all other instances of currentcolorhow can i fix with css the inheritance issue of currentcoloror how can i featuredetect support for the css colour keyword currentcolori also need to detect partial support for example apple webkit is unstable to use in most casesfull storyi am using the css colour keyword currentcolor in a project using it rather profusely i might add for examplei am using it on a site header component that floats over a fullviewport carouseleach slide has a varying backgroundcolor and a contrasting color assigned to it when the slide changes it updates the site header to inform it of the new contrast the site headers color is swapped accordingly and anything with the inherit or currentcolor keyword gets updated such as an svgs fill some bordercolors and some backgroundcolorsanother simpler examplei have various colour palettes that i apply as a class name eg bgemerald or bgblue onto boxes the contents of these boxes can be links or buttons or just text with currentcolor applied to button borders for instance the css becomes quite simple because i just need to set the color property for each colour scheme no need to update each affected child nodeall this is very slicksupport is superb under firefox chrome opera internet explorer 9 and their mobile equivalents unfortunately apple webkit ios safari and osx safari is suffering from poor and erratic support it does not work everywhere nor all the timeaeven in the simplest of examplesanor does it repaint very well or consistently when neededi have done some searching and have not found many people using this practical css keyword and ergo no existing means to featuredetect it or polyfill it i do not know how i would go about making a modernizr test for this feature especially to detect partialsupport like i would need for apple webkiti am probably just going to browserdetect it at the moment until i can think of a solution or stumble upon someone with the smarts that can think of a solution faster than mejsfiddlei have modified the fiddle linked above to grossly replicate the issues i am having what i have noticed is it is like currentcolor gets locked with the initially inherited value red and carries it along when applied to everything else for example if you switch nthchild1s color to something else that new value gets applied to all following elements using currentcolorbrowsersbrokenosx safari 6a7ios 6a7 safariworkswindows safari 5ios 5 safarisomething in safari 6 and up got borked since this is such an underrated feature nobody noticed,['css'] +702365,dynamically add items to list view using custom adapter for android app so right now i have a custom adapter class that takes in an array of locations and adds them to a listview this is all fine and dandy but i would like to add locations to this listview after this initialization for example someone can add a location and it will add it to this listview here is my main activitypackage comexamplelistviewtestimport androidappactivityimport androidosbundleimport androidviewviewimport androidwidgetlistviewpublic class mainactivity extends activity private listview listview1overridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main location location data new location new locationrdrawableic launcher location 1 fruit 2 miles 84 monfrinclosed sun new locationrdrawableic launcher location 2 veggies 2 miles 85 new locationrdrawableic launcher location 3 plants 2 miles 85 new locationrdrawableic launcher location 4 flowers 2 miles 85 new locationrdrawableic launcher location 5 backed goods 2 miles 85 locationadapter adapter new locationadapterthis rlayoutlistview item row location data adapteraddnew locationrdrawableic launcher location 6 veggies 2 miles 85 listview1 listviewfindviewbyidridlistview1 view header viewgetlayoutinflaterinflaterlayoutlistview header row null listview1addheaderviewheader listview1setadapteradapterthis works i want to now do something like adapteraddnew locationrdrawableic launcher location 6 veggies 2 miles 85 after filling it with the array here is my locationadapter classpackage comexamplelistviewtestimport androidappactivityimport androidcontentcontextimport androidviewlayoutinflaterimport androidviewviewimport androidviewviewgroupimport androidwidgetarrayadapterimport androidwidgetimageviewimport androidwidgettextviewpublic class locationadapter extends arrayadapterlocationcontext context int layoutresourceid location data nullpublic locationadaptercontext context int layoutresourceid location data supercontext layoutresourceid data thislayoutresourceid layoutresourceid thiscontext context thisdata dataoverridepublic view getviewint position view convertview viewgroup parent view row convertview locationholder holder null ifrow null layoutinflater inflater activitycontextgetlayoutinflater row inflaterinflatelayoutresourceid parent false holder new locationholder holderimgicon imageviewrowfindviewbyidridimgicon holdertxttitle textviewrowfindviewbyidridtxttitle holderdetails textviewrowfindviewbyidriddetails holderthistance textviewrowfindviewbyidridthistance holderhours textviewrowfindviewbyidridhours rowsettagholder else holder locationholderrowgettag location location dataposition holdertxttitlesettextlocationtitle holderimgiconsetimageresourcelocationicon holderdetailssettextlocationdetails holderthistancesettextlocationthistance holderhourssettextlocationhours return rowstatic class locationholder imageview imgicon textview txttitle textview details textview thistance textview hoursany ideas on how i can implement this thanks,"['java', 'android']" +702380,show blended layers reveals red uiimage but it does not have an alpha channel i have an image that does not have an alpha channel i confirmed in finders get info panel yet when i put it in a uiimageview which is within a uiscrollview and i enable show blended layers the image is red which indicates it is trying to apply transparency which will be a hit on performance how can fix this to be green so ios knows everything in this view is fully opaquei tried the following but this did not remove the red colorselfimageviewopaque yesselfscrollviewopaque yes,"['ios', 'objective-c']" +702519,how to get milliseconds from localdatetime in java 8 i am wondering if there is a way to get current milliseconds since 1970 epoch using the new localdate localtime or localdatetime classes of java 8the known way is below long currentmilliseconds new dategettimeorlong currentmilliseconds systemcurrenttimemillis,['java'] +702557,rails 4 action routes with simple form and shallow nested resources resources users shallow true do resources shoesendthis gives me two different routes for create and edit user shoes pathshoes pathin my shoes formhtmlerb if i leave the form tag url as default i get a missing routes error when i submit a new or updated shoe if i supply the url in the form i can get it to work for either the new or the edit update but i cannot get it to work for boththis works for the new simple form for shoe url user shoes path do f this works for the edit but will fail once it tries the actual update since it redirects to param id simple form for shoe url shoes pathshoe do f how can i make it work for both thanks,['ruby-on-rails'] +702590,rails 4 how to render json regardless of requested format i would like a rails controller all of them actually it is an api to render json always alwaysi do not want rails to return route not found or try and fail to find an html template or return 406 i just want it to automatically and always render json eg from a rabl or jbuilder viewis this possible related questions seem to have answers that have the aforementioned downsides,['ruby-on-rails'] +702600,what file system does android use which file system does android use i have read both ext4 and yaffs2,['android'] +702832,access request object in rails helper in my application helperrb file i have a function like thisdef find subdomain requestdomainendundefined local variable or method request and i am invoking this method in another helper how can i get the domain in helper without passing any argument from controller,"['ruby-on-rails', 'ruby']" +703164,android keystore getentry and generatekeypair throw exceptions sometimes my android app need to encrypt a file so that it can decrypt and read it later this should not be decryptable by anybody else other than the app even user following is how i am doing the encryption and decryption this works most of the time but some times for some users this is failing it is not specific to a particular handset nexus7 samsung motorola htc all types are reporting this issue but not all users are experiencing it only some users occasionallyhere is the relevant codeencrypt keystore ks keystoregetinstanceandroidkeystore final keystoreprivatekeyentry entry if kscontainsaliascert alias calendar cal calendargetinstance date now calgettime caladdcalendaryear 50 date end calgettime keypairgenerator kpg keypairgeneratorgetinstancersa androidkeystore kpginitializenew keypairgeneratorspecbuildergetapplicationcontext setaliascert alias setstartdatenow setenddateend setserialnumberbigintegervalueof1 setsubjectnew x500principalcn cert alias build keypair kp kpggeneratekeypair entry keystoreprivatekeyentry ksgetentry cert alias null pub entrygetcertificategetpublickey use the pub key to encryptdecrypt keystore ks keystoregetinstanceandroidkeystore ksloadnull final keystoreprivatekeyentry entry keystoreprivatekeyentry ksgetentry cert alias null privatekey key1 entrygetprivatekey use the private key decryptthis code sometimes throwsjavalangruntimeexception error0d07207basn1 encoding routinesasn1 get objectheader too longat comandroidorgconscryptnativecryptoengine load private keynative methodat comandroidorgconscryptopensslenginegetprivatekeybyidopensslenginejava66at androidsecurityandroidkeystoreenginegetkeyandroidkeystorejava86at javasecuritykeystorespienginegetentrykeystorespijava372at javasecuritykeystoregetentrykeystorejava644so i modified encrypt to first try to get the entry and if it raises exception generate new key pairfinal keystoreprivatekeyentry entry nullif kscontainsaliascert alias try entry keystoreprivatekeyentry ksgetentry cert alias null catch exception e if entry null generate new key pairbut even this is failing sometimes with the following exceptionjavalangillegalstateexception could not generate key in keystoreat androidsecurityandroidkeypairgeneratorgeneratekeypairandroidkeypairgeneratorjava100at javasecuritykeypairgeneratorkeypairgeneratorimplgeneratekeypairkeypairgeneratorjava275what am i doing wronghow do i fix itwork around itdoes these exceptions indicate that the files are being tampered withdoes this happen for users with screenlock passwordpinbefore i generate new pair should i delete the entry keystoredeleteentryi observed that the keystore returns null after screenlock passwordpin change some others also seem to have experienced this issue keystore getentry return null after change password,"['java', 'android']" +703209,integrating videolan in android for live streaming i have integrated videolan in my android app i followed the steps in the videolan wiki page to compile the vlc sourcei am streaming live content and i can hear the audio but no video i have been trying to find a solution onlinevideolan forums but no luck any help will be very much appreciatedi overwrote the setsurfacesize method and i still do not see the video i can only hear the audio and i see this in the logs00530 233733085 wvlc5099 yuv rgb neon filter cannot get output picture0530 233733190 wvlc5099 yuv rgb neon filter cannot get output picture0530 233733190 wvlc5099 core video output picture is too late to be thisplayed missing 31 ms0530 233733195 wvlc5099 yuv rgb neon filter cannot get output picture0530 2337300 wvlc5099 yuv rgb neon filter cannot get output picture0530 2337300 wvlc5099 core video output picture is too late to be thisplayed missing 41 ms0530 2337300 dvlc5099 core video output picture might be thisplayed late missing 8 ms0530 2337305 wvlc5099 yuv rgb neon filter cannot get output picture0530 2337310 wvlc5099 yuv rgb neon filter cannot get output picture0530 233733415 wvlc5099 yuv rgb neon filter cannot get output picture0530 233733420 wvlc5099 core video output picture is too late to be thisplayed missing 24 ms,['android'] +703224,rails flash notice via ajax long story short i have a button on clicking it i want an ajax request to be triggered which gets flashnotice and thisplays it in a div inhere is my shortened view input typebutton idsearch valuethisplay div idnotice divmy ajax request in the viewsearchsubmitfunction ajax type post url url to my show action success functiondata noticehtml flashnotice contenthtmldata return false my controllerdef homecontroller actioncontrollerbase def index end def show respond to do format formatjs flashnotice countto s results found for paramsquerysearch key end render partial search endendmy showjserbappviewsdashboard homeshowjserbnoticehtmlj flashnotice contenthtmlj render partial search the problem is when i click on button the notice is thisplayed fine but the same notice persists on the next clicks too the search partial contains the table please help,"['javascript', 'jquery', 'ruby-on-rails']" +703293,slow access to djangos requestbody sometimes this line of django app hosted using apachemod wsgi takes a lot of time to execute eg 99 of eg 6 seconds of request handling as measured by new relic when submitted by some mobile clientsraw body requestbodywhere request is an incoming requestthe questions i havewhat could have slowed down access to requestbody so muchwhat would be the correct configuration for apache to wait before invoking django until client sends whole payload maybe the problem is in apache configurationdjangos body attribute in httprequest is a property so that really resolves on what is really being done there and how to make it happen outside of the django app if possible i want apache to wait for full request before sending it to django app,['python'] +703326,restrict a click to a specific shape i have this imagepolygon defined in css like thispostwrapper position relative width 250px height 420px float left backgroundcolor ddc webkitclippath polygon50 100 100 50 50 0 0 50 webkitbackgroundsize cover mozbackgroundsize cover obackgroundsize cover backgroundsize cover you can see the imageit defines a sort of rectangle this is a clickable image that redirects to another page and people are able to click in any part of the rectangle but i only want them to click on the polygon anyone knows how can i do this here in my codefidde,['css'] +703329,angularleafletdirective custom message html with angular directives in marker popup how to i want to insert my custom html markup with scope event handlers to message property of leaflet marker for exampleappcontrollertestcontroller scope leafletevents compile leafletmarkershelpersfunctionscope leafletevents compile leafletmarkershelpersangularextendscope currentlocation lat 20 lng 20 zoom 20 markers defaults scrollwheelzoom true events map enable zoomstart drag click mousemove popupopen logic emit markers enable leafleteventsgetavailablemarkerevents var html a hrefinfoabutton typebutton ngclickdosomeactionchoosebuttonvar item some data for marker scopemarkersnewmarker lat itemlat lng itemlng message itemmessage html draggable false so dosomeaction method does not triggers because controller does not bind it to view i tried to do next stuff this code belongs to the same controller dataleafleteventpopup content html set for popup message before scopeonleafletdirectivemappopupopen functionevent data var html p dataleafleteventpopup content p var template angularelementhtml compilehtmlscope scopedigestscopedosomeaction function never fires consolelogargumentsbut it does not work so if anyone has ideas please feel free to share,['javascript'] +703345,aspnet session never expires when using signalr and transport mode long polling we have a web application that uses signalr for its notification mechanismthe problem is when we are browsing our web application using ie signalr uses long polling as its transport type thus sends back requests to our web server therefore session never expires no matter how long the browser is idlewe were thinking that maybe we could catch the requests in globalasax and see if they were from singalr and set the session timeout to the remaining time which i do not think it is a straightforward solutionis there any other solution the we are missing,['asp.net'] +703389,default value for pointer to char in c let us have the variable char si know if it is declared in global scope its value should be 0if it is declared in local scope its value is undefined it may be 0 though i have got a question in test which sounds like this what will be the value of the pointer defined as char sa null b empty string c undefined i am really confused what answer i should choose because if it is declared in global scope well the value would be null i guess if it is declared in local scope undefined though when i tried it is zero and when i try to cout it nothing is printed no segmentation fault why that means it is an empty string or is cout that awesome,"['c++', 'c']" +703474,storing data to dom element value vs data attribute to store values in a dom element we can do it through data attributeabcdataitem 1 to retrieve do abcdataitembut today i learned that we can do it this way alsoabc0item 1 to retrive do abc0itemwhat are the differences between themwhich one is better which one gets a wider compatibility,"['javascript', 'jquery', 'html']" +703514,local storage in chrome i have a javascript code which save string to the local storage the string size is 40var dataurl canvastodataurlimagejpgtostringlocalstoragesetitemdataurl dataurli open the html file from chrome in one computer its ok in the other computer i get uncaught quotaexceedederror failed to execute setitem on storage setting the value of dataurl exceeded the quotain this computer i allowed to save string length no more than 10 charsboth computers have the same chromes version 3501916114 m why,['html'] +703542,how to update ui from asynctask i have seen many examples of how to do this but i can figure how to implement it in my codei using this codei have updated the url so it will receive a json with dynamic datawhat i am trying to do is to automatically update the list every 30 secs with this codehandler handler new handler runnable refresh new runnable public void run new getcontactsexecute handlerpostdelayedrefresh 30 it refreshed and call the url and gets the data but the ui does not get updatedthank for any hints that helps my in the right direction,['android'] +703558,how do i use a typed array using a shared buffer efficiently in javascript in my code i have an object that contains a series of pixel coordinates performance of this object is critical because it is being used in a 60fps game where the output cannot always be cached after experimentation and benchmarking a 3d array proved to be the fastest way of implementing it when using untyped arraysvar pixelcollection function thispixels pixelcollectionprototype add functionx y var pixels thispixels if pixelsy pixelsypushx else pixelsy x each functioncallback var pixels thispixels for var y 0 m pixelslength y m y var row pixelsy if row for var i 0 mm rowlength i mm i callbackrowi y in some situations the object is not fast enough so i tried a uint8array implementation using a 2d array var width 255var height 160pixelcollection function thispixels new uint8arraywidth heightpixelcollectionprototype add functionx y thispixelswidth y x 1 each functioncallback var pixels thispixels for var i 0 m pixelslength i m i if pixelsi callbacki width mathfloori width this is slower i thought it would be faster because writing to and reading from uint8arrays is faster but since i am creating a huge object for every pixelcollection object retrieving pixels is way slower because it takes longer to iterate over all pixels note i also tried the implementation above with an untyped array it is a lot slowera pixelcollection typically does not have all pixels set however the bounding box may span the entire canvas so i do need to create the array using a buffer this bigthere may be a way around that though i can create one big shared buffer and use a byte offset for every pixelcollection so when pixelcollection p1 would take up 100 bytes then pixelcollection p2 would start at byte offset 100 this uses memory more efficiently but i would need to keep track of the range of bytes every pixelcollection uses is this what c calls pointers annoying part when p1s bounding box expands i need to shift p2 to make space for p1 and i would need to set a safe buffer size for the shared buffer so i need to make a safe guesstimation of how much memory it needsimplementing this is possible but it would require lots of time trial and error so before start on this does it seem a good way to do it are there better or simpler ways to do this do you know any example implementations i could learn fromedit i added a jsperf in case you want to try your hand at an optimizationplease add to this jsperf if you have a brilliant idea for an optimization,['javascript'] +703574,android studio deploy the release apk instead of debug the run configurations in android studio only let you deploy the default debugging apk but i have built a release apk by running gradle assembledebug from within android studio as an external tool and would like to deploy that instead but it does not seem like you can change the apk which android studio installs there is an option to deploy a custom artifact but i am not sure what that is or if it would help and anyway there does not seem to be an option to create a new artifact in the android studio project structure dialogdoes anyone know how i can specify the path of the apk which android studio deploys i know i can install from the command line with adb but it would speed things up if i could just click a button thanks,['android'] +703636,should use sp instead of dp for text sizes when i useandroidtextsizes20dp in my xml for a textview i got a warning should use sp instead of dp for text sizes why should dp not be used what is the correct approach how can i achieve same textsizes on different thisplays,['android'] +703657,input width in forminline bootstrap 3 i do not understand how i can customize an input formcontrol width in bootstrap 3 header div classcontainer div classrow form roleform classforminline div classformgroup input typetext classformcontrol placeholder34nn342n1 12n n on34n idsearch div input typebutton classbtn btnsuccess value1n onclickwindowlocationhref resultdocumentgetelementbyidsearchvalue form div divheadercan i do it without some styles like width in pixels,"['jquery', 'html', 'css']" +703721,encoding and muxing video using mediacodec and mediamuxer i am developing an app where i decode a video and replace certain frames and reencode using mediamuxer and mediacodec the app works if i do not replace any frames except for 1080p videos as i explain below but when i do the frames after the replaced ones are pixelated and the video is choppyalso when i try my app with 1920x1080 videos i get a strange output where the video is not showing anything until i scroll to the beginning of the video then the video starts showing up but with the same problem mentioned before of pixalation after the edithere is how i configure my encodervideo formatsetintegermediaformatkey i frame interval intervalvideo formatsetintegermediaformatkey bit rate bitratevideo formatsetintegermediaformatkey frame rate frameratevideo formatsetintegermediaformatkey max input size 0int color formatmediacodecinfocodeccapabilitiescolor formatyuv420semiplanarvideo formatsetintegermediaformatkey color format color formatencoderconfigurevideo format null null mediacodecconfigure flag encodeso to sum up i have two problems1 pixelated frames and choppy video after modified frames2 corrupted 1920x1080 videos unless i scroll to the beginningedithere is a sample 1080p video unedited which gives a green screen when i play on vlc and plays incorrectly on the phone unless i scroll to start and now strangely working normally on youtube except for a green frame at the starthere is a sample 720p video edited with also a green frame at the start and clear pixelation and lag after the edithere is the code i use to decode an reencodedo bitmap b1 ifedited framescontainskeyextractorgetsampletime b1bitmapfactorydecodefileedited framesgetextractorgetsampletime else b1decodeextractorgetsampletimepreview widthpreview height ifb1null continue bitmap b scalbitmapcreatescaledbitmapb1 preview width preview height false ifb scalnull continue encodeb scal encoder muxer videotrackindex lasttimeextractorgetsampletimewhileextractoradvancethe decode methodprivate bitmap decodefinal long timefinal int widthfinal int height mediaformat newformat codecgetoutputformat bitmap b null final int timeout usec 10 bytebuffer decoderinputbuffers codecgetinputbuffers mediacodecbufferinfo info new mediacodecbufferinfo boolean outputdone false boolean inputdone false while outputdone if inputdone int inputbufindex codecdequeueinputbuffertimeout usec if inputbufindex 0 bytebuffer inputbuf decoderinputbuffersinputbufindex int chunksize extractorreadsampledatainputbuf 0 if chunksize 0 codecqueueinputbufferinputbufindex 0 0 0l mediacodecbuffer flag end of stream inputdone true else long presentationtimeus extractorgetsampletime codecqueueinputbufferinputbufindex 0 chunksize presentationtimeus 0 inputbufclear decoderinputbuffersinputbufindexclear else bytebuffer outputbuffers if outputdone int decoderstatus codecdequeueoutputbufferinfo timeout usec if decoderstatus mediacodecinfo try again later else if decoderstatus mediacodecinfo output buffers changed outputbuffers codecgetoutputbuffers else if decoderstatus mediacodecinfo output format changed newformat codecgetoutputformat else if decoderstatus 0 else if infoflags mediacodecbuffer flag end of stream 0 outputdone true boolean dorender infosize 0 codecreleaseoutputbufferdecoderstatus false if dorender outputbuffers codecgetoutputbuffers bytebuffer buffer outputbuffersdecoderstatus buffer outputbuffersdecoderstatus outputdone true byte outdata new byteinfosize buffergetoutdata bufferclear outputbuffersdecoderstatusclear try int colr format1 ifnewformatnull newformatgetintegermediaformatkey color format21 colr formatimageformatnv21 else ifnewformatnull newformatgetintegermediaformatkey color format21 toastmaketextgetapplicationcontext unknown color format formatgetintegermediaformatkey color format toastlength longshow finish return null int arnew intformatgetintegermediaformatkey width formatgetintegermediaformatkey height yuv nv21 to rgbar outdata formatgetintegermediaformatkey width formatgetintegermediaformatkey height lastpresentationtimeus infopresentationtimeus b bitmapcreatebitmapar formatgetintegermediaformatkey width formatgetintegermediaformatkey height bitmapconfigargb 8 catch exception e eprintstacktrace return band here is the encode methodprivate void encodebitmap b mediacodec encoder mediamuxer muxer int track indx mediacodecbufferinfo enc info new mediacodecbufferinfo boolean enc outputdone false boolean enc inputdone false final int timeout usec 10 bytebuffer encoderinputbuffers encodergetinputbuffers bytebuffer enc outputbuffers encodergetoutputbuffers while enc outputdone if enc inputdone int inputbufindex encoderdequeueinputbuffertimeout usec if inputbufindex 0 bytebuffer inputbuf encoderinputbuffersinputbufindex int chunksize 0 ifbnull else int mwidth bgetwidth int mheight bgetheight byte yuv new bytemwidthmheight32 int argb new intmwidth mheight bgetpixelsargb 0 mwidth 0 0 mwidth mheight encodeyuv420spyuv argb mwidth mheight brecycle bnull inputbufputyuv chunksize yuvlength if chunksize 0 encoderqueueinputbufferinputbufindex 0 0 0l mediacodecbuffer flag end of stream else long presentationtimeus extractorgetsampletime logiencodeencode time presentationtimeus encoderqueueinputbufferinputbufindex 0 chunksize presentationtimeus 0 inputbufclear encoderinputbuffersinputbufindexclear enc inputdonetrue if enc outputdone int enc decoderstatus encoderdequeueoutputbufferenc info timeout usec if enc decoderstatus mediacodecinfo try again later else if enc decoderstatus mediacodecinfo output buffers changed enc outputbuffers encodergetoutputbuffers else if enc decoderstatus mediacodecinfo output format changed mediaformat newformat encodergetoutputformat else if enc decoderstatus 0 else if enc infoflags mediacodecbuffer flag end of stream 0 enc outputdone true boolean enc dorender enc infosize 0 encoderreleaseoutputbufferenc decoderstatus false if enc dorender enc outputdone true bytebuffer enc buffer enc outputbuffersenc decoderstatus try muxerwritesampledatatrack indx enc buffer enc info catch exception e eprintstacktrace enc bufferclear enc outputbuffersenc decoderstatusclear,['android'] +703729,how to set custom app bar button icons in windows 8 i want to set my own customs app bar icons which i downloaded how can i set that this doesnot workappbarbutton xnamesave clicksave click labelsave iconassetsicon1png,['c#'] +703878,calling a secured webservice from jquery safely i have a webservice which has several calls which are only available to members of the site i want to build a pure htmljquery mobile app which can call into this service make requests and download informationmy initial plan was to put the users username and password in the auth header but i am worried about exposing them to any traffic sniffers i can obviously create a session key so after the initial authentication they call in with a token but this may be vulnerable to session stealingmy current plan isimplement a login call this will return a token which will expire after a designated timethe js calls in with this token thereby reducing the number of times the password is sentthe user makes their callsthe token is compared against the users ip addressthe user logs out this ends the session and removes the key early to reduce riskanother thought was to encrypt the password as i send it is it possiblesensible to do publicprivate key encryption in js based on the net rsacryptoserviceprovider implementationwhat is the best approach to handle authentication ideally without purchasing an ssl certificate the data itself is not particularly sensitive,"['jquery', '.net']" +703890,grunt and hoodie test database i am currently running my test suite on angularjs using grunt karma jasmine and protractor the database library i am using is hoodie which is a library on top of couchdb i start hoodie using the following code in my gruntfilehoodie start options callback functionconfig gruntconfigsetconnectproxies0port configstackcouchport however i would like to have a separate database for running tests which automatically resets afterwards this way the production data would not conflict with the testshow should i approach this i would assume there is some kind of standard way of doing this as i can imagine other people have come across the same problem but i am unable to find anything on the internet,['javascript'] +703897,horizontalscrollview inside swiperefreshlayout i implemented the new swiperefreshlayout component in my application and it works well with any vertical views like listview gridview and scrollviewit behaves very bad with horizontal views like horizontalscrollviewwhen scrolling to the right or left the swiperefreshlayout view caches the touch prevents the horizontalscrollview from receiving it and starts scrolling vertically to perform the refreshi tried solving this issue as i previously solved issues with vertical scrollview with viewpager inside using requestthisallowintercepttouchevent but it did not work i also noticed that this method is overridden in the original swiperefreshlayout class without returning the super googles developer left a comment instead nope because swiperefreshlayout component is relatively new i could not find a solution that fixes the horizontal scroll issue while still allowing the swipe to refresh view to track and handle vertical scrolling so i thought i will share my solution with hopes it will spare someone an hour or two,['android'] +703912,is there a java map implementation that enforces final keys i need a map that once a key gets a value any additional attempt of putting a value on the same key will throw an exceptionfor examplemapputjohn 3 okmapputjohn 7 throws some exceptionmapputjohn 11 throws some exceptionof course i can implement this on my own eg by extending hashmap or surrounding every call to put with if mapcontainskey but i prefer using something readymade that keeps my code cleandoes anybody know of such implementation,['java'] +704045,how to duplicate y axis on jquery flot i am being able to use jquery flot and it is a very nice tool however i could not find a good solution for my problemi want to duplicate y axis so i can thisplay 1 on the left and 1 on the right so the users when comparing data from the rightmost side of the chart would not have to scroll through the leftmost side of the chart i am assuming they will be accessing it through a smartphonejquery flot allows multiple axis but for each axis i would need a different set of data as in this examplebut i do not want to duplicate the data cannot i just tell flot to duplicate the yaxis using the same set of data,"['javascript', 'jquery']" +704063,how to use jsonnet for json modelbinding in an mvc5 project i have been looking around the internet for an answer or example but could not find one yet i simply would like to change the default json serializer which is used to deserialize json while modelbinding to jsonnet libraryi have found this so post but cannot implement it so far i cannot even see the systemnethttpformatters namespace nor can i see globalconfigurationwhat am i missingupdatei have an aspnet mvc project it was basically an mvc3 project currently i am targetting net 45 and using the aspnet mvc 5 and related nuget packages i do not see the systemwebhttp assembly nor any similar namespace in this context i would like to inject jsonnet to be used as the default model binder for json type of requests,"['c#', 'asp.net']" +704103,is it possible to thisable following redirects in okhttp 20 in android i would like to use the new okhttp 20 to request some urls but i would like more control over redirects i have already found the option to enable or thisable following https a http or http a https redirects but i would like to not follow any redirects so i can update my gui as soon as possible and choose whether to follow them from application logic i do not see an option to do this is it possible and if so how can i achieve this,['android'] +704113,how to make changes made in ngdialog modal appear on main page i am new to both angularjs and ngdialog and i am having trouble getting my bindings to work between the ngdialog modal and my controller i injected the controllers scope into the modal by specifying scope scope and i have access to methods defined in the controller but the bindings to models defined in the controller are not functioning properlyi am trying to use a modal to allow the user to add an address to an organizationheres mainjsvar app angularmoduleapp ngroute ngcookies ngdialogappcontrollerpageorganization functionscope rootscope ngdialog route location scopeaddaddressformdata scopeaddaddress function ngdialogopen template partialsmodalsaddaddresshtml controller pageorganization scope scope scopesaveaddress function consolelogscopeaddaddressformdata scopeorganizationaddressespushscopeaddaddressformdata consolelogscopeorganization stubbed out organization scopeorganization org type nonprofit name new organization addresses phonenumber faxnumber emailaddress website primarycontact primaryemail imageurl isprivate false campaigns admins heres organizationhtmlbutton ngclickaddaddressadd an addressbuttonh1addressesh1ul li ngrepeataddress in organizationaddresses p addresstype br addressaddressline1 br addressaddressline2 br addresscity br addrestate br addresspostalcode p li uland heres addaddresshtmlh1add an addressh1form ngsubmitsaveaddress select nametype option valuebusiness defaultselectedbusinessoption option valueresidenceresidenceoption select input ngmodeladdaddressformdataaddressline1 typetext placeholderaddress line 1 input ngmodeladdaddressformdataaddressline2 typetext placeholderaddress line 2 input ngmodeladdaddressformdatacity typetext placeholdercity select ngmodeladdaddressformdatastate option valuealalabamaoption option valueakalaskaoption option valueazarizonaoption option valueararkansasoption option valuecacaliforniaoption option valuecocoloradooption option valuectconnecticutoption option valuededelawareoption option valuedcthistrict of columbiaoption option valueflfloridaoption option valuegageorgiaoption option valuehihawaiioption option valueididahooption option valueilillinoisoption option valueinindianaoption option valueiaiowaoption option valuekskansasoption option valuekykentuckyoption option valuelalouisianaoption option valuememaineoption option valuemdmarylandoption option valuemamassachusettsoption option valuemimichiganoption option valuemnminnesotaoption option valuemsmississippioption option valuemomissourioption option valuemtmontanaoption option valuenenebraskaoption option valuenvnevadaoption option valuenhnew hampshireoption option valuenjnew jerseyoption option valuenmnew mexicooption option valuenynew yorkoption option valuencnorth carolinaoption option valuendnorth dakotaoption option valueohohiooption option valueokoklahomaoption option valueororegonoption option valuepapennsylvaniaoption option valuerirhode islandoption option valuescsouth carolinaoption option valuesdsouth dakotaoption option valuetntennesseeoption option valuetxtexasoption option valueututahoption option valuevtvermontoption option valuevavirginiaoption option valuewawashingtonoption option valuewvwest virginiaoption option valuewiwisconsinoption option valuewywyomingoption select input ngmodeladdaddressformdatapostalcode typetext placeholderpostal code input typesubmit valuesave addressformthe modal has access to the parent scope it successfully calls scopesaveaddress and consolelogscopeorganization logs the whole organization including the new address added in the modal however the new address is not reflected in the ngrepeat in organizationhtml and if i add multiple addresses one after another only the most recent one shows in the log as an experiment i added this function to mainjsscopepushaddress function scopeaddaddressformdata city scopeorganizationaddresseslength 1 consolelogscopeaddaddressformdata scopeorganizationaddressespushscopeaddaddressformdata consolelogscopeorganizationand changed the add address button in organizationhtml to matchbutton classbutton colorc verticala floatright ngclickpushaddressadd an addressbuttonnow when i click add an address the new address shows immediately in the ngrepeat and each console log contains all of the addresses not just the most recent onewhats the difference between these two methods why are the changes made in the modal expiring when they were made using methods in the controllers scope,['javascript'] +704237,correct format for separating declaration and definition of c template functions i am using this method to separate the definition of a c template function from its declaration to avoid cluttering up my header files with codethe link uses as an example a function with no arguments or return but suppose i have a function with an argument the link would suggest the following arrangement file fh template typename t void ft t file fcppinclude fhtemplate typename t void ft t do somethingtemplate void fintint t other specializations as neededhowever it seems the specialization also works if you omit the type in angle brackets as i suppose the compiler deduces it from the argument typetemplate void fint tbut i am wondering is it valid to do thatvisual c 12 2013,['c++'] +704255,php json decode not working this does not workjsondecode json decodejsondata truehowever if i copy the string from jsondata and put it inside the decode function manually it does work this worksjsondecode json decodeid0bid918urlmd56361fbfbee69f4c394f3d2fa062f79time20140602 142021 truei did output jsondata copied it and put in like above in the decode function then it worked however if i put jsondata directly in the decode function it does notvar dumpjsondata showsstring144 id0bid918urlmd56361fbfbee69f4c394f3d2fa062f79time20140602 142021the jsondata comes from a encrypted get variable to encrypt it i use thiskey some keyiv size mcrypt get iv sizemcrypt blowfish mcrypt mode ecbiv mcrypt create iviv size mcrypt randenc mcrypt encryptmcrypt blowfish key data mcrypt mode ecb iviv rawurlencodebase64 encodeivenc rawurlencodebase64 encodeencto decryptiv base64 decoderawurldecode getienc base64 decoderawurldecode getedata mcrypt decryptmcrypt blowfish key enc mcrypt mode ecb iv,['php'] +704267,avxsse version of xorshift128 i am trying to make the fastest possible high quality rng having read xorshift128 seems like a good option the c code isinclude stdinthuint64 t s 2 uint64 t nextvoid uint64 t s1 s 0 const uint64 t s0 s 1 s 0 s0 s1 s1 23 a return s 1 s1 s0 s1 17 s0 26 s0 b ci am not an sseavx expert sadly but my cpu supports sse41 sse42 avx f16c fma3 xop instructions how could you use these to speed up this code assuming you want to make billions of such random numbers and what is the expected limit to this speedup in practice,['c'] +704284,sailsjs v0100rc7 grunt loading js assets in correct order i am trying to learn sailsjs however am experiencing some difficulties with lack of documentation on a newer version of sailsok so linker has been removed and my gruntfilejs is different to that in sailscastsi am running sails v0100rc7which is different to the documentation on the website which is for v090how do i modify my gruntfile to load jquery before bootstrap even better is it possible to dump grunt and run gulp insteadthanks in advance gruntfile this node script is executed when you run grunt or sails lift it is purpose is to load the grunt tasks in your projects tasks folder and allow you to add and remove tasks as you see fit for more information on how this works check out the readmemd file that was generated in your tasks folder warning unless you know what youre doing you should not change this file check out the tasks directory instead moduleexports functiongrunt load the includeall library in order to require all of our grunt configurations and task registrations dynamically var includeall try includeall requireincludeall catch e0 try includeall requiresailsnode modulesincludeall catche1 consoleerrorcould not find includeall module consoleerrorskipping grunt tasks consoleerrorto fix this please run consoleerrornpm install includeall save consoleerror gruntregistertaskdefault return loads grunt configuration modules from the specified relative path these modules should export a function that when run should either loadconfigure or register a grunt task function loadtasksrelpath return includeall dirname requirepathresolve dirname relpath filter js invokes the function from a grunt configuration module with a single argument the grunt object function invokeconfigfntasks for var taskname in tasks if taskshasownpropertytaskname taskstasknamegrunt load task functions var taskconfigurations loadtaskstasksconfig registerdefinitions loadtaskstasksregister ensure that a default task exists if registerdefinitionsdefault registerdefinitionsdefault function grunt gruntregistertaskdefault run task functions to configure grunt invokeconfigfntaskconfigurations invokeconfigfnregisterdefinitions,['jquery'] +704333,elasticsearch and net were considering to switch from solrsolrnet to elasticsearch we started with nest we have only 4 documents in search indexprivate static void mainstring args var node new urihttplocalhost9200 var settings new connectionsettings node myapplication var client new elasticclientsettings var stopwatch stopwatchstartnew var sr clientgetmovie1 consolewritelinestopwatchelapsedmillisecondsthe code above takes approx 250ms while the same code with httpclient and jsonserializer takes 3045ms 250ms is too much time for just 4 documentscan nest be used on hightraffic news website or do you recommend httpclient jsonserializer combo the search page was the most visited page on our website in 2013thanks in advance,"['c#', '.net']" +704379,get from anyobjectnsstring to string i am reading a plist key nsarray with and nsdictionaries let regionstomonitor nsbundlemainbundleinfodictionaryregions as arraydictionarystringanyobjectnow i iterate over it for regiontomonitor in regionstomonitor and now i want to to get uuidstring of the regiontomonitorin objc nsstring uuidstring regiontomonitoruuidstringin swift i try let uuidstring regiontomonitoruuidstringvaluethe above does compile but the string is always nil in swift regiontomonitoruuid when used without stringvalue works fine in printlnhow do i get a valid swiftstring herei am trying to pass it to nsuuidi also triedlet uuidstringstring regiontomonitoruuid anyobject is not convertible to stringlet uuidstring regiontomonitoruuid as string could not find an overload for subscript that accepts the supplied argumentslet uuidstring regiontomonitoruuid anyobject cannot be implicitly downcast to string did you mean to use as to force downcast,['ios'] +704433,swift with ios 5 deployment target what is the minimum deployment target for xcode 6 and the new swift language specifically can i still support ios 50,['ios'] +704450,jquery ajax form data serialize using php i am stuck in my code i need to send data from the form to the checkphp page and then process itthis is my codethe ajax partscript srcscriptscriptdocumentreadyfunctionvar formmyformsmtclickfunctionajax typepost urlformattraction dataformserialize success functionresponse consolelogresponse scriptthe formform actioncheckphp methodpost namemyform idmyforminput typetext nameuser iduser input typetext namepass idpass input typebutton namesmt valuesubmit idsmt formdiv iderrdivthe php partuser postuserpass postpassifusertony echo hi user else echo i dont know you,"['php', 'jquery']" +704526,how to declare a byte array in scala in scala i can declare a byte array this wayval ipaddr arraybyte array192tobyte 168tobyte 1tobyte 9tobytethis is too verbose is there a simpler way to declare a byte array similar to javas byte ipaddr 192 168 1 1note that the following results in an error due to the in the stringinetaddressgetbyaddress19216811tobyte,['java'] +704530,mailx send html message i want to send a html message with mailx when i try the following commandmailx s subject emailhtml i get the content of emailhtml in plain text in the message the header contenttype is set to textplain the a option tries to send a file so i did not find out how to modify the header this answer almost worked it sets well the contenttype to texthtml but does not substitute the default contenttype which is textplain mailx s echo e this is the subjectncontenttype texthtml emailhtmlgives this result from to subject this is the subjectcontenttype texthtmlmessageid 538d7b66xs0x9hsxnjkufwuiuseragent heirloom mailx 124 72908mimeversion 10 boundary 538d7b66z5gaiqnlwb1faokuucgwf1evcagxihqmbmmxby6sattjkthis is a multipart message in mime format 538d7b66z5gaiqnlwb1faokuucgwf1evcagxihqmbmmxby6sattjkcontenttype textplain charsetusasciicontenttransferencoding 7bitcontentthisposition inlinehtmlbodyphelo wolrdpbodyhtmlps i also tried with uuencode when i try to thisplay the message in the webmail i get a blank page,['html'] +704542,how do i do indexofobject or a proper containsobject with an array how do i do indexofobject or a proper containsobjecti mean i know i could just bridge the array to nsarray and do it there but there must be a native way of doing thisps for the containsobject i guess i could filter the array too but for indexof,['ios'] +704620,how to parse a json file in swift i have a json file want to parse and use list of objects in table view can any one share the code to parse json file in swift,['ios'] +704635,how to thismiss system dialog in android i have to thismiss this system dialog attached belowi am getting this value but i am not able to thismiss it programmatically in service not in activitymy question isis it possible to thismiss it if yes please help or guide me how to achieve it,['android'] +704649,should the copyandswap idiom become the copyandmove idiom in c11 as explained in this answer the copyandswap idiom is implemented as followsclass myclassprivate bigclass data unmovableclass dataptrpublic myclass data dataptrnew unmovableclass myclassconst myclass other dataotherdata dataptrnew unmovableclassotherdataptr myclassmyclass other datastdmoveotherdata dataptrotherdataptr otherdataptr nullptr myclass delete dataptr friend void swapmyclass first myclass second using stdswap swapfirstdata otherdata swapfirstdataptr otherdataptr myclass operatormyclass other swapthis other return this by having a value of myclass as parameter for operator the parameter can be constructed by either the copy constructor or the move constructor you can then safely extract the data from the parameter this prevents code duplication and assists in exception safetythe answer mentions you can either swap or move the variables in the temporary it primarily thiscusses swapping however a swap if not optimised by the compiler involves three move operations and in more complex cases does additional extra work when all you want is to move the temporary into the assignedto objectconsider this more complex example involving the observer pattern in this example i have written the assignment operator code manually emphasis is on the move constructor assignment operator and swap methodclass myclass observableiobserverprivate stdshared ptrobservable observablepublic myclastdshared ptrobservable observable observableobservable observableregisterobserverthis myclassconst myclass other observableotherobservable observableregisterobserverthis myclass ifobservable nullptr observableunregisterobserverthis myclassmyclass other observablestdmoveotherobservable observableunregisterobserverother otherobservableresetnullptr observableregisterobserverthis friend void swapmyclass first myclass second checks for nullptr and same observable omitted using stdswap swapfirstobservable secondobservable secondobservableunregisterobserverfirst firstobservableregisterobserverfirst firstobservableunregisterobserversecond secondobservableregisterobserversecond myclass operatormyclass other observableunregisterobserverthis observable stdmoveotherobservable observableunregisterobserverother otherobservableresetnullptr observableregisterobserverthis clearly the duplicated part of the code in this manually written assignment operator is identical to that of the move constructor you could perform a swap in the assignment operator and the behaviour would be right but it would potentially perform more moves and perform an extra registration in the swap and unregistration in the destructorwouldnt it make much more sense to reuse the move constructors code in steadprivate void performmoveactionsmyclass other observableunregisterobserverother otherobservableresetnullptr observableregisterobserverthis public myclassmyclass other observablestdmoveotherobservable performmoveactionsother myclass operatormyclass other observableunregisterobserverthis observable stdmoveotherobservable performmoveactionsother it looks to me like this approach is never inferior to the swap approach am i right in thinking that the copyandswap idiom would be better off as the copyandmove idiom in c11 or did i miss something important,['c++'] +704653,c11 declaring factory a friend of base class i am trying to create a factory for derived classes i only want the factory to be able to create instances of the derived classes so i have made the base constructor protected the derived classes just use the base class constructors so their constructors are protected alsoi tried to declare the factory as a friend of the base class so that it could access the protected constructor when i compile using this commandclang stdc11 stdliblibc friendscpp o friendsi get this errorfriendscpp2320 error calling a protected constructor of class a return new ti friendscpp4216 note in instantiation of function template specialization createa requested here a a createa1 friendscpp3025 note declared protected here using basebase along with a similar error for derived class b i get the feeling from reading other questions on stackoverflowcom that this is not possible in c11 but i am not sure why can someone explain why this would not work and perhaps an alternative example codeinclude iostreamusing namespace std forward declarationtemplateclass t t createint iclass base public templateclass t friend t createint virtual void say 0 protected baseint i ii this would not compile int i factory for base classtemplateclass tt createint i return new ticlass a public base public using basebase void say cout i am a and have a value of i endl class b public base public using basebase void say cout i am b and have a value of i endl int main cout i am creating a endl a a createa1 asay cout i am creating b endl b b createb2 bsay return 0,['c++'] +704672,propertysynthesize equivalent in swift we used to declare property to pass data between classes as followingh file interface fileproperty nonatomic double topspeedm file implementation filesynthesize topspeednow there is no interface class how to pass data between swift classes,"['ios', 'objective-c']" +704701,wpf datagrid not showing any scrollbar my datagrid has a binding on an observablecollection and gets filled after grouping some values fetched by ef my problem is that the datagridheight grows beyond the window sizedoes anyone know how to get that fixed i almost googled myself to death o usercontrol xclassultranizerv2viewsstorageinventorylist xmlns xmlnsx xmlnsmc xmlnsd mcignorabled grid gridrowdefinitions rowdefinition heightrowdefinition rowdefinition height25rowdefinition gridrowdefinitions dockpanel gridrow0 datagrid itemssourcebinding presentableinventoryitems verticalalignmentstretch autogeneratecolumnsfalse datagridcolumns datagridtextcolumn headerprodukttitel width350 binding binding producttitle datagridtextcolumn headersku width100 binding binding sku datagridtextcolumn headermenge width60 binding binding quantity datagridcolumns datagrid dockpanel label gridrow1arschlabel gridusercontrol,['c#'] +704765,how can i cache image files locally with phonegap cordova heres my problem i making a webmobile app using angularjs and cordova for offline purpose i use localstorage to store all the data of the app json parameters and so onthe thing is i need to store cache images locally again offline purpose as localstorage size limit is around 5mo i cannot use it i need morei thought i could use a cache manifest but it does not work as i need to update it regulary without recompiling the app i thought i could put the cache manifest on an external server but it is like i cannot use a cache manifest from another domainso i am thinking of using cordovaphonegap file api but i have no idea to achieve thatany help or ideas,['javascript'] +704778,retrofit and slash characters in path i am facing an issue with retrofit and would like to find a suitable answer as the only way i can think of it is pretty ugly and not practical retrofit path annotation requires a in the beginning as you can read in this code extracted from the library source loads link requesturl link requesturlparamnames and link requestquery private void parsepathstring path if path null pathlength 0 pathcharat0 throw methoderrorurl path s must start with path the problem that i am facing is that the path part comes from the backend in a response object meaning that all paths strings already come formatted from the backend previously in other response as follows object href resourcesloginas you can see when including something like this the url gets malformed getloginhref void loginencodedpathloginhref string loginhref callbackuser callbackto something like double in front of resourcesthis can definitely cause issues in some endpoints and i cannot think a really simple way to solve this issue apart from doing something likea modify my own version of retrofit to remove that character check this is a last resortb truncate the href before using the method from the interface which i would like to avoid at all cost as well as would add unnecessary transformation all over the place c intercept the request and correctly form the url in case this scenario happens really ugly solution as well any idea suggestions thanks,['android'] +704789,what is the preprocessor macro to test whether an application extension is being built this question is based purely on publicly released documents regarding the introduction of application extensions in ioswith the introduction of app extensions in ios 8 it is now possible to extend custom functionality and content beyond your app and make it available to users while theyare using other appsin my implementation of my extension i am including some classes from my actual app in my extension models etc the problem is that these classes make calls to uiapplication which is not available in an app extension and the compiler tells me soi thought an easy solution to this would to be enclose any calls to uiapplication in an if directivefor example if i wanted to only include code if i was running on a simulator i would useif target iphone simulator code hereendifis there a similar defined macro when the target is an application extension,['ios'] +704796,how to save a completed polygon points leafletdraw to mysql table i would like to use leafletdraw to create outlines of regions i have managed to get this working ok now i would like to save the data for each polygon to a mysql table am a little stuck on how i would go about exporting the data and the format i should be doing it in if possible i would like to pull the data back into a mapboxleaflet map in the future so guess something like geojson would be good,['mysql'] +704832,today app extension widget tap to open containing app i have implemented a today widget for my application quotes which thisplays the days quote within the notification center with the help of these apple docs what i would like to accomplish is opening the containing app in this case quotes when the user taps the quotes widget within their today notification view not entirely sure what to call this as calendar would if you tapped it in the today view i have tried overlaying a button over the label which would call voidopenurlnsurl url completionhandlervoid bool successcompletionhandlerupon it being tapped then open the custom url scheme i have declared to open the containing app the issue is it does not open the containing appibactionmybuttonidsender nsurl customurl nsurl urlwithstringpositivequotes self openurlcustomurl completionhandlerbool success if success success else fail,['ios'] +704839,subclass uiapplication with swift in objective c it was simple it was sufficient to update the mainm file and change the uiapplicationmain parametersreturn uiapplicationmainargc argv nsstringfromclasscustomuiapplication class nsstringfromclassappdelegate classbut in swift there is no mainm file since the guide saysacode written at global scope is used as the entry point for the program so you donat need a main functionaso how to subclass uiapplication in swift any suggestion,['ios'] +704886,memory leaks in the swift playground deinit not called consistently arc object deletion seems to be inconsistent in the swift playground is it a bug or by designconsider this classclass test var name string initnamestring selfname name printlnname initialized deinit printlnname deinitialized when i call it from the playground not the command line repl see comment belowvar t1 testname t1var t2 test testname t2t2 nili see only initialization messages in the consolet1 initializedt2 initializedwhats missing is deinit of t2when i run it in an app eg entry of app delegate i the output is consistent with arc deletion ie t1 init then t2 and t2 deinit and then t1 since the entire invocation block goes out of scopet1 initializedt2 initializedt2 deinitializedt1 deinitializedfinally in the command line repl see comment below for accessing the repl the results are consisent ie t1 is alive due to its top level scope but t2 is arc deleted as one would expect 1 class test 2 var name string 3 initnamestring 4 selfname name 5 printlnname initialized 6 7 deinit 8 printlnname deinitialized 9 10 11 var t1 testname t1t1 initializedt1 initializedt1 deinitializedt1 test name t1 12 var t2 test testname t2t2 initializedt2 initializedt2 deinitializedt2 test name t2 13 t2 nilt2 deinitialized 14 t1r2 test name t1 15 t2r3 test nil,['ios'] +704904,create water in libgdx i am develooping a game in libgdx with box2di spent hours of searching for a tutorial or somthing that explain how to create water in libgdx with box2d i cannot find how to do this if somone have an idea it will very help mehow to create water in libgdx with box2di am really need your help,"['java', 'android']" +704998,the impact of overflow values other than visible on the block formatting context this question is similar to this one with an excellent answer although mine does not pertain to float issuesi recently ran into some trouble when trying to apply a margin to an onlychild of a blocklevel elementparent background rgba255 0 0 01child margin 30px 0 padding 20px background rgba0 255 0 01div idparent div idchildfoodivdivalthough the margin is applied the parents background is not this remains true unless siblings are added before and after the child or more interestingly in my opinion an overflow of any value other than visible is set here is the same example but with an overflow valueparent background rgba255 0 0 01 overflow autochild margin 30px 0 padding 20px background rgba0 255 0 01div idparent div idchildfoodivdivfrom css21 section 941 block formatting contexts i found the followingfloats absolutely positioned elements block containers such as inlineblocks tablecells and tablecaptions that are not block boxes and block boxes with overflow other than visible except when that value has been propagated to the viewport establish new block formatting contexts for their contentsi am really struggling to understand the rationale behind the overflow other than visible logic in this instance the margins are seemingly not being clipped in this situation as the only thing to change is the background could someone demonstrate why a value of overflow visible creates such a situation,['css'] +705003,xcode 6 would not let me develop on my ios 8 phone i was developing an application with ios 7 and i just updated to the beta of ios 8 i downloaded xcode 6 beta and now when i plug my phone in it lists my phone under ineligible devices and would not let me develop on it why is this,['ios'] +705038,xamarinandroid jsonnet serilization fails on 422 device only timezonenotfound exception i am using jsonnet to serialize a dto and i am getting the following exception on the physical device this works on all other devices we have tested on but is failing on the samsung galaxy tab 3lite smt110 running version 422i was having this issue but when i upgraded to xamarin 30 it turned into this below0603 211741687 emonort 22071 error fatal unhandled exception systemtimezonenotfoundexception exception of type systemtimezonenotfoundexception was thrown0603 211741687 emonort 22071 at systemtimezoneinfoget local 0x0 in filename unknown0 0603 211741687 emonort 22071 at newtonsoftjsonutilitiesdatetimeutilsgetutcoffset datetime d 0x0 in filename unknown0 0603 211741687 emonort 22071 at newtonsoftjsonutilitiesdatetimeutilswritedatetimestring systemchar chars int32 start datetime value nullable1 offset datetimekind kind dateformathandling format 0x0 in filename unknown0 0603 211741687 emonort 22071 at newtonsoftjsonjsontextwriterwritevalue datetime value 0x0 in filename unknown0 0603 211741687 emonort 22071 at newtonsoftjsonjsonwriterwritevalue newtonsoftjsonjsonwriter writer primitivetypecode typecode systemobject value 0x0 in filename unknown0 0603 211741687 emonort 22071 at newtonsoftjsonserializationjsonserializerinternalwriterserializeprimitive newtonsoftjsonjsonwriter writer systemobject value newtonsoftjsonserializationjsonprimitivecontract contract newtonsoftjsonserialization0603 211741695 imonostdout22071 executing command updateregistrationthe program mono has exited with code 0 0x0edit this is the dto that i am trying to serialize you can see when the constructor gets called it sets it to datetimenow shouldnt this just assume the local timezone public class recordtargetfrequency basecommand icommand public guid targetid get private set public guid locationid get private set public guid therapistid get private set public bool increase get private set public datetime timestamp get private set public recordtargetfrequencyguid targetid guid locationid guid therapistid bool increase timestamp datetimenow targetid targetid locationid locationid therapistid therapistid increase increase public void validate validateguidtargetid validateguidtherapistid i am then serializing it with this linejsonconvertserializeobjectexecutedcommand,['c#'] +705137,load spring beans from custom groovy files in grails app trying to load spring beans from custom groovy file in grails 237 i know this question has been asked before but after hours of searching i am unable to find a consistent approach that loads from the classpaththe goalmodularize resourcesgroovy into multiple custom resource files put custom resource files in standard location grailsappconfspringuse plugin to do the magic minimize overhead tried grailsappconfspringmybeansconfiggroovy beans testsvctestservice msg hello note above i am using beans not beans apparently it makes a differenceresourcesgroovythis worksbeans loadbeans filecprojtest1grailsappconfspringmybeansconfiggroovyand according to docs this should too but does notimportbeansclasspathmybeansconfiggroovyupdate working optionsworking for grails 237option 1 srcjavafollowing lukelazarovic advice this approach works since grails automatically copies not compiles groovy files in srcjava to the classpath works fine in eclipse and with war deploymentbean config files heresrcjavamybeansconfiggroovysrcjavafoobeansconfiggroovyresourcesgroovyloadbeansclasspathbeansconfiggroovyoptions 2 grailsappconfspringthis approach allows for custom bean config files in grailsappconfspring credits to ideascultor and markesher bean config files here grailsappconfspringmybeansconfiggroovy resourcesgroovy for eclipselocal testing loadbeansfilegrailsappconfspringbeansconfiggroovy for warclasspath loadbeansclasspathbeansconfiggroovy buildconfiggroovy grailswarresources stagingdir args copytodir stagingdirwebinfclassesspring filesetdirgrailsappconfspring includename beansconfiggroovy excludename resourcesgroovy excludename resourcesxml options 3 custom pluginif youre using custom plugins this approach is ideal boiler plate config gets refactored into the pluginplugin config scripts eventsgroovy eventcreatewarstart warname stagingdir def libdir new filestagingdirwebinfclassesspring antcopytodir libdir filesetdirgrailsappconfspring includename beansconfiggroovy excludename resourcesgroovy excludename resourcesxml mygrailsplugingroovy def dowithspring loadbeansfilegrailsappconfspringbeansconfiggroovy loadbeansclasspathbeansconfiggroovy grails appno configjust create your bean config files using the beansconfiggroovy convention good to go bean config files heregrailsappconfspringmybeansconfiggroovyupdate 9242015found some issues with option 3loading of duplicate resource filesspring resources not configured correctly for testapp we managed to fix the above issue such that any resource files in grailsappconfspring work the same when executing grails in eclipse war testapp etc first step we created a class to have more control over locating and loading resource files this was necessary as some files were being loaded more than once due to crossreferenced beanswere using a plugin to encapsulate this functionality so this class lives in that pluginclass customresourceloader static loadspringbeansbeanbuilder bb def files load all resource files match resources using multiple methods def matchedresourcelist fileseach matchedresourcelist getpatternresolvedresourcesfilegrailsappconfspring it groovytolist matchedresourcelist getpathmatchedresourcesclasspathspring it groovytolist eliminate duplicates resource loaded from recursive reference def resourcemap matchedresourcelisteach ifit resourcemapputitgetfilename it make resourcesgroovy first in list def resourcesfile resourcemapremoveresourcesgroovy ifresourcesfile throw new runtimeexceptionresourcesgroovy was not found where expected def resourcestoload resourcesfile resourcemapeachkv resourcestoload v logdebugspring resource files about to load resourcestoloadeach bbloadbeansit static def getpatternresolvedresourcespath resourcepatternresolver resourcepatternresolver new pathmatchingresourcepatternresolver return resourcepatternresolvergetresourcespath static def getpathmatchedresourcespath return new pathmatchingresourcepatternresolvergetresourcespath removed beansconfiggroovy suffix war generation now picks up any resources in grailsappconfspringplugin eventsgroovyeventcreatewarstart warname stagingdir def libdir new filestagingdirwebinfclassesspring antcopytodir libdir filesetdirgrailsappconfspring includename groovy excludename resourcesxml in the plugin definition file call the loader from dowithspring passing beanbuilder the delegate as the argument very importantdef dowithspring customresourceloaderloadspringbeansdelegatethat is it there is no requirement on users of the plugin aside from creating custom resource files in grailsappconfspring,['java'] +705145,could not load file or assembly systemwebmvc version30 or one of its dependencies i am adding ninject in mvc project using the following commands in package manager consoleinstallpackage ninject version 30110installpackage ninjectwebcommon version 3007installpackage ninjectmvc3 version 3006when i run the application i get error like thiscould not load file or assembly systemwebmvc version30 cultureneutral publickeytoken31bf3856ad364e35 or one of its dependencies the located assemblys manifest definition does not match the assembly reference exception from hresult 0x80131040,['c#'] +705272,narrowing conversions and initializer lists which compiler is right considering the following piece of codeinclude iostreamauto main int double x70 int ix stdcout i x stdendl return 0when compiled in gcc49 it compiles fine with only a warningwarning narrowing conversion of axa from adoublea to ainta inside compiling with either clang33 or vc2013 gives a compile error error type double cannot be narrowed to int in initializer listerror c2397 conversion from double to int requires a narrowingquestionswhich of the compilers is right according to the standardis there any reason why the compilers mentioned above should exhibit such diverse behaviour,['c++'] +705353,hibernate tool auto cascade all i have a database and i generated all bean and hbmxml file with hibernate tooli noticed this tool not generated automatically the cascade property i read it can be done using revengxmlthere are a ways for auto generate revengexml or set a cascade property 1 time for all table,"['java', 'mysql']" +705426,wildfly 8 remote debug application i need to remotely debug y node in a jboss 8 wildfly cluster running two nodes on one machinefor this in our hostslave config we have the two nodes configuredservers server namenode1 groupmainservergroup autostarttrue jvm namewicket debugenabledfalse heap size1024m maxsize1536m jvmoptions option valuexdebug xrunjdwptransportdt socketserverysuspendnaddress8787 jvmoptions jvm server server namenode2 groupmainservergroup autostarttrue jvm namewicket debugenabledfalse heap size1024m maxsize1536m jvmoptions option valuexdebug xrunjdwptransportdt socketserverysuspendnaddress8788 jvmoptions jvm socketbindings portoffset100 serverserverswhen i now try to connect to each of the remote debugging ports intellij tells meerror running node2 unable to open debugger port javanetconnectexception connection refused connecti can confirm the nodes have startet up via the wildfly management panelalso i have checked via telnet on the machine running the nodes that telnetting the pots is not possibleany help appriciated if anyone has useful links towards a proper documentation of the wildfly config files this would be appreciated even morethanks in advance,['java'] +705461,can you use xcode63 with ios71 sdk is it possible to use xcode6 beta with an ios 71 sdk the new tools are much nicer but i need to build for ios7,['ios'] +705498,ineligible devices section appeared in xcode 6xx after installing xcode 6 my devices moved to greyedout section ineligible devices and i cannot select them as deploy targetupdatethis error occurs in all versions of xcode 6xxthere are so many different reasons causing this problemcheck this solution list for more details,['ios'] +705550,how to approach debugging c code when printdebugging changes program behavior i am working with a large and rather mature c project 10 years of development 150k sloc 3k test cases wsumosimorg we recently thiscovered that the program behavior changes in an unexpected manner when putting in one seemingly innocent print statement stdcout foon in a specific locationthe objdump output also shows large changes in the generated code depending on the presence of that print statementcurrently our best guess is that this is related to undefined behavior and compiler optimization as thiscussed in an post by john regehr this assumption is supported by our observation that the effect of the print statement is subject to optimization levelsince the application runs in single thread concurrency should not be an issueto debug undefined behavior we have used clang with flags fsanitizeundefinedunsignedintergeroverflowaddressinteger and gotten rid of all the indicated problems we have also fixed all problems indicated by the clang static analyzer but the problem remains curiously with gcc clang and msvc but with slightly different resultsnow we are at a loss of ideas on how to best continue with our debugging efforts due to the nonlocality of the effects of the print statement we do not even know where to start with a code review question 1 what tools would you recommend for doing static and runtime analysis of potential problem spots similar to the clang tools described abovequestion 2 what mechanisms other than the combination of undefined behavior compiler optimization are likely candidates for the observed effect nonfunctional statements changing program behavior,['c++'] +705566,use of bridgetoobjectivec in swift what does bridgetoobjectivec will do in swift it seems like converting a swift object into objectivec object is this same as type castingfor example i can convert a swift string into nsstring like var swingstringstring test stringvar correspondingnsstring swingstringbridgetoobjectivec using bridgevar correspondingnsstring swingstring as nsstring type castingi want to know both are same or not,['ios'] +705587,local rdma for development i am trying to build and run the rdma examples here but because i am just exploring i do not have any hardware capable of managing rdma i get errors like this when i try to run the example code librdmacm could not read abi versionlibrdmacm assuming 4cma unable to get rdma device listerror ec rdma create event channel failed returned zeronullis there any local implementation of the rdma functionality that i can use for development i understand that the r in rdma means remote but i thought this might exist for testingdevelopment purposesfor reference i am trying this on an ubuntu 1404 box having installed the packages libibverbsdev and librdmacmdev in order to get the code to compile,['c'] +705654,is it possible to import thirdparty objectivec code into a swift playground as suggested here i have been able to import my existing objectivec code into a swift file via the bridging header as of yet i have been unable to do something similar with a swift playground it does not seem to recognise the header in the same way that a swift file doesinterestingly and possibly suggestive of a negative to my question is that playgrounds do not appear to share the concept of target membership like swiftmanyone had any success with this or perhaps a different mechanism,['ios'] +705659,why does platformrunlater not check if it currently is on the javafx thread when using javafx 8 we need to run interactions with the gui via platformrunlater or else they will throw exceptions if ran from another threadhowever the implementation of platformrunlater never checks whether it currently is on the javafx threadi wrote the following methodpublic static void runsafefinal runnable runnable objectsrequirenonnullrunnable runnable if platformisfxapplicationthread runnablerun else platformrunlaterrunnable this ensures that it can never be run on a nonfxapplication threadis there any reason that the default implementation does not do this kind of shortcircuiting,['java'] +705672,encoding with pandasread csv when file name has accents i am trying to load a csv with pandas but am running into a problem if the file name has accents it is clearly an encoding problem but although read csv lets you set encoding for text within the file i cannot figure out how to encode the file name properlyinput file rcdatasetssprovincespointsscsv country provinceselflocs pandasread csvinput filesepskipinitialspacetruethe csv file is anzoateguicsv when i am getting errors input file cdatasetsvenezuelaprovincespointsanzoateguicsverror codeoserror file bcpf2qgis valmieradatasetsvenezuelaprovincespointsanzoxc3xa1teguicsv does not existso maybe it is converting my string to bytes i tried using iostringioinput file as well which puts the correct file name as a column header on an empty dataframeempty dataframecolumns cpf2qgis valmieradatasetsvenezuelaprovincespointsanzoateguicsvindex any ideas on how to get this file to load unfortunately i cannot just strip out accents as i have to interface with software that requires the proper name and i have a ton of files to format not just the one thanksedit full errortraceback most recent call last file cpf2eclipsestandardkeplersr2win32x86 64eclipsepluginsorgpythonpydev 3201401272249pysrcpydevd commpy line 891 in doit result pydevd varsevaluateexpressionselfthread id selfframe id selfexpression selfdoexec file cpf2eclipsestandardkeplersr2win32x86 64eclipsepluginsorgpythonpydev 3201401272249pysrcpydevd varspy line 486 in evaluateexpression result evalcompiled updated globals framef locals file string line 1 in module file cpython33libsitepackagespandasioparserspy line 404 in parser f return readfilepath or buffer kwds file cpython33libsitepackagespandasioparserspy line 205 in read parser textfilereaderfilepath or buffer kwds file cpython33libsitepackagespandasioparserspy line 486 in init self make engineselfengine file cpython33libsitepackagespandasioparserspy line 594 in make engine self engine cparserwrapperselff selfoptions file cpython33libsitepackagespandasioparserspy line 952 in init self reader parsertextreadersrc kwds file parserpyx line 330 in pandasparsertextreader cinit pandasparserc3040 file parserpyx line 557 in pandasparsertextreader setup parser source pandasparserc5387oserror file bcpf2qgis valmieradatasetsvenezuelaprovincespointsanzoxc3xa1teguicsv does not exist,['python'] +705721,delete all tables beginning with a certain prefix i have found another thread on this question but i was not able to use its solutions so i thought i would ask with more clarity and detaili have a large mysql database representing a vbulletin forum for several years this forum has had an error generated on each view each time creating a new table named aagregate temp 1251634200 aagregate temp 1251734400 etc etc there are about 20 of these tables in the database and i wish to delete them alli want to issue a command that says the equivalent of drop table where table name like aggregate tempunfortunately this command does not work and the google results for this problem are full of elaborate stored procedures beyond my understanding and all seemingly tailored to the more complex problems of different postersis it possible to write a simple statement that drops multiple tables based on a name like match,"['mysql', 'sql']" +705733,swift read plist i am playing around with apples new swift programming language and have some problemscurrently i am trying to read a plist file in objectivec i would do the following to get the content as a nsdictionarynsstring filepath nsbundle mainbundle pathforresourceconfig oftypeplistnsdictionary dict nsdictionary alloc initwithcontentsoffilefilepathhow do i get a plist as a dictionary in swifti assume i can get the path to the plist withlet path nsbundlemainbundlepathforresourceconfig oftype plistwhen this works if it is correct how do i get the content as a dictionaryalso a more general questionis it ok to use the default ns classes i think soor am i missing something as far as i know the default framework ns classes are still valid and alright to use,['ios'] +705744,why this code produces invalid alignment with msvc i have tested this code on ideonecom and it outputs 16 as it should however when i try it in visual studio 2013 it shows 8 is it a bug or lack of c11 support from the compilerinclude iostreaminclude type traitsusing namespace stdusing float pack aligned storage4 sizeoffloat 16typeint main cout alignment offloat packvalue endl return 0i have used alignment of because msvc does not support alignofedit i see that i cannot get 16 alignment with aligned storage but why this snippet is okinclude iostreaminclude type traitsinclude xmmintrinhusing namespace std declspecalign16 struct float pack float x4int main cout alignment offloat packvalue endloutput is 16 does that mean that compiler can provide larger alignment when using extensions why i cannot achieve the same result with aligned storage only because msvc does not provide that with aligned storage,['c++'] +705751,how to i import 3rd party frameworks into xcode playground how do i import 3rd part frameworks into xcode playground swift playground obviously has a framework import mechanism because we can import cocoa spritekit and in an osx playground xcplayground xcplayground seems missing from ios oddly what i would really like to do is hide code from my playground and be able to show a minimal example any thoughts on how to load a framework into swift playgroundsee also how to import own classes from your own project into a playgroundis it possible to import thirdparty objectivec code into a swift playgroundthis question is different because the request is to use a framework in playground rather than simply regular swift files,['ios'] +705755,rails 4 devise sign inuser method not working does not set current user i am working on a checkout for a store when the form is submitted this action takes place in my controllerdef update billing if checkoutsave sign inguest user redirect to root path notice success else render billing endendi test this by raiseing inside the action and testing it out using better errors sign inguest user if paramscheckout formcreate an account 1 user id 8 email encrypted password 2a10hcv7veso7lc9dh1tkd0jbe57pz6lasizgfiiwoys7bf reset password token nil reset password sent at nil remember created at nil sign in count 6 current sign in at 20140604 194536 last sign in at 20140604 192948 current sign in ip 127001 last sign in ip 127001 created at 20140604 185029 updated at 20140604 194536 guest false guest email guest current user user id 8 email encrypted password 2a10hcv7veso7lc9dh1tkd0jbe57pz6lasizgfiiwoys7bf reset password token nil reset password sent at nil remember created at nil sign in count 6 current sign in at 20140604 194536 last sign in at 20140604 192948 current sign in ip 127001 last sign in ip 127001 created at 20140604 185029 updated at 20140604 194536 guest false guest email guest sessionwardenuseruserkey 8 2a10hcv7veso7lc9dh1tkd0jbehowever when i go back to localhost30 current user becomes nil again sessionwardenuseruserkey nil current user nildoes not sign inguest user set the session variables so that current user will persist across requestswhat am i doing wrong,['ruby-on-rails'] +705818,logging method signature using swift i am trying to rewrite my logging class and i would like to know how to substitute pretty function or nsstringfromselector cmd in a swift file in order to track the method calls,['ios'] +705839,initiating a transactionscope from excel vba i have some existing c code that i would like to expose via com interop so that it can be called from excel vba as i will be performing many nested batch update operations i need to support transactions and to minimize the refactoring required at the c level i would like to use the transactionscope approachimplementing an implicit transaction using transaction scope the transactionscope class provides a simple way to mark a block of code as participating in a transaction without requiring you to interact with the transaction itself a transaction scope can select and manage the ambient transaction automatically due to its ease of use and efficiency it is recommended that you use the transactionscope class when developing a transaction applicationin addition you do not need to enlist resources explicitly with the transaction any systemtransactions resource manager such as sql server 2005 can detect the existence of an ambient transaction created by the scope and automatically enlistmy question is is it possible to initiate the transactionscope within the vba code or call a c method via com interop to instantiate and return a transactionscope object and then proceed to call various other c objects via com interop which will all automatically participate in the single root transaction,['c#'] +705840,nsnotificationcenter addobserver in swift how do you add an observer in swift to the default notification center i am trying to port this line of code that sends a notification when the battery level changesnsnotificationcenter defaultcenter addobserverself selectorselectorbatterylevelchanged nameuidevicebatteryleveldidchangenotification objectnil,['ios'] +705857,input field blur event does not trigger on ipad keyboard hide i have a page with an input field i want to run some javascript code on blur like this inputfieldonblur function it works fine on a desktop browser if i tab away or click the mouse outside the field on an ipad safari browser it works fine if i tap outside the input field but if i click on the hide keyboard button on the lower left corner blur event is not triggered does not blur event fire on keyboard hide i see the pointercursor moves away from the input field on keyboard hide is there any way to capture the keyboard hide eventthanks,"['javascript', 'jquery']" +705858,spring mockmvc does not consider validation in my test i am trying to set up an integration testing with mockmvc and i have a problem with it indeed spring does not integrate any validation annotation for more precision i put the code of the controller class which could be tested controllerpublic class userregistercontroller private final log log logfactorygetloguserregistercontrollerclass private usermanager usermanager autowired public userregistercontrollerusermanager usermanager thisusermanager usermanager register a new user requestmappingvalue userregister method requestmethodget public responsebody simplemessage submitform valid userinfonew userinfo bindingresult result iflogisinfoenabled loginfoexecute userregister action simplemessage message try ifresulthaserrors iflogisfatalenabled logfatalparameters sent by user for registering are not conform errors are resultgetfielderrorstostring throw new exceptionresultgetfielderrorstostring user user new user usersetloginuserinfogetlogin usersetfamilynameuserinfogetfamilyname usersetfirstnameuserinfogetfirstname usersetpassworduserinfogetpassword usersetdatebirthdayuserinfogetdatebirthday usersetemailuserinfogetemail usersetmobileuserinfogetmobile usersetaddressuserinfogetaddress usermanagercreateuseruser user newuser usermanagerfindlastusercreated change to null some sensitive or useless return parameters newusersetpasswordnull message new simplemessagenull newuser catch exception e iflogiserrorenabled logerrora problem of type egetclass has occured with message egetmessage message new simplemessage new simpleexceptionegetclass egetmessage null return message then the object with contain both hibernate and javax annotation for validation public abstract class userparameters min1 protected long id lengthmin4 max20 protected string login lengthmin4 max20 protected string familyname lengthmin4 max20 protected string firstname patternregexp820azazazaz 0909 protected string password past protected calendar datebirthday email lengthmax255 protected string email patternregexp01671 1092 1 092 1092 1092 protected string mobile lengthmax255 protected string address protected calendar datecreation protected calendar datelastaccesspublic class userinfonew extends userparameters implements serializable private static final long serialversionuid 44271314148012537l notblank public string getlogin return login public void setloginstring login thislogin login public string getfamilyname return familyname public void setfamilynamestring name thisfamilyname name public string getfirstname return firstname public void setfirstnamestring firstname thisfirstname firstname notblank public string getpassword return password public void setpasswordstring password thispassword password public calendar getdatebirthday return datebirthday public void setdatebirthdaycalendar strbirthday thisdatebirthday strbirthday public string getemail return email public void setemailstring mail thisemail mail notblank public string getmobile return mobile public void setmobilestring mobile thismobile mobile public string getaddress return address public void setaddrestring address thisaddress address and the class which realizes the testrunwithspringjunit4classrunnerclasswebappconfigurationcontextconfigurationclasses webinit testclass appconfig testclass webconfig 1class webconfig 2class websocketconfigclasspublic class usercontrollerstest autowired private webapplicationcontext wac private mockmvc mockmvc before public void setup throws exception thismockmvc mockmvcbuilderswebappcontextsetupwac alwaysexpectstatusisok alwaysexpectcontentcontenttypeapplicationjsoncharsetutf8 buildtestpublic void userregister throws exception does not consider valid during test mockmvcperformgetuserregisterloginapasswordamobile0134320285 contenttypemediatypeall andexpectjsonpatherrorexistswhen i launch the test the error item does not exist whereas login password and mobile cannot be validate by javax and hibernate annotation moreover when i try to send an url to localhost validation worked and new user is not saved in databaseas you can see i use a java code configuration for my web layer i suppose the problem come from it moreover i download a project from the spring team in github link githubcomspringprojectsspringmvcshowcase which details all kind of test we can do with mockmvc the validation one in orgspringframeworksamplesmvcvalidation package does not work with my project configuration but very well with in it is original configto finish i send you all my configuration classesconfigurationpublic class webinit test extends abstractannotationconfigthispatcherservletinitializer override protected class getrootconfigclasses return new class appconfig testclass override protected class getservletconfigclasses return new class webconfig 1class webconfig 2class websocketconfigclass override protected string getservletmappings return new string override protected void customizeregistrationdynamic registration registrationsetinitparameterthispatchoptionsrequest true registrationsetloadonstartup1 configurationimportresource classpathapplicationcontextdaoxml classpathapplicationcontextdatasourcetestxml classpathapplicationcontextservicexmlpublic class appconfig test configurationenablewebmvccomponentscan basepackages projectweb excludefilters componentscanfiltertype filtertypeannotation value configurationclasspublic class webconfig 1 extends webmvcconfigurationsupport autowired private formattingconversionservicefactorybean conversionservice bean override public formattingconversionservice mvcconversionservice formattingconversionservice conversionservice thisconversionservicegetobject addformattersconversionservice return conversionservice configurationpublic class webconfig 2 extends webmvcconfigureradapter override public void configuredefaultservlethandlingdefaultservlethandlerconfigurer configurer configurerenable configure output mapping see link for more information param converters a list of link httpmessageconverter override public void configuremessageconverterslisthttpmessageconverter converters final mappingjackson2httpmessageconverter converter new mappingjackson2httpmessageconverter final objectmapper objectmapper new objectmapper objectmappersetserializationinclusionjsonincludeincludenon null convertersetobjectmapperobjectmapper convertersaddconverter superconfiguremessageconvertersconverters configurationenableschedulingcomponentscan basepackagesprojectweb excludefilters componentscanfiltertype filtertypeannotation value configurationclassenablewebsocketmessagebrokerpublic class websocketconfig extends abstractwebsocketmessagebrokerconfigurer override public void configuremessagebrokermessagebrokerregistry config configenablesimplebrokerfriendship message journey information configsetapplicationdestinationprefixesapp override public void registerstompendpointsstompendpointregistry registry registryaddendpointclientwithsockjs thanks for your help,['java'] +705892,swift isa pointer remapping or other supported method swizzling do swift classes have something like an isa pointer that can be remapped weve seen that swift uses a more static method thispatch than objectivec which unless a class dervices from foundationnsobject prevents the style of swizzling based on remapping method implementations at runtimei am wondering how well implement method interceptionbased dynamic features like the observer pattern notifications etc currently all this stuff is provided by the objectivec layer and can be easily integrated into swift but if we want to provide these kinds of features in a framework or app of our own is it necessary to implement them in objectivec i would assume there is a way to do it natively another kind of swizzling common to objectivec is remapping the isapointer to generate a subclass on the fly is this kind of swizzling supported in swift if not what is the supported way of intercepting arbitrary method invocationsedit as jatoben points out as of arm64 isaremapping must be done by calling object setclass and not by accessing the value directly this is still referred to as isa pointer swizzling,['objective-c'] +705985,azure cache intermittent response times from wcf rest service i am building an ef6 web app in azure and i am using azure cachei am testing calls to my wcf service and i am getting wildly erratic response times between 300ms and 15seci configured my code according to the this example and it runs fine locally i have debugged remotely and i can see that the cache key is being found and the data is getting called from cache so i am struggling to understand why there is sych a huge variation in response times most of the time it is 5sec which is obviously way too longthe example i have been testing is as followswcf service get request to cache client configured by settings in application configuration file public datacachefactory cachefactory new datacachefactory public datacache cache public datacache cache get if cache null cache cachefactorygetdefaultcache return cache set operationcontract systemservicemodelwebwebgetresponseformat webmessageformatjson uritemplate getfriends public string getfriends string cachekey getfriends userid object result cachegetcachekey if result null using ekckocontext entities new ekckocontext var frnds entitiesuserconnectionswhereuc ucuserid useridselectuc new name ucfriendusername tolist jsonserializersettings jsonsettings new jsonserializersettings preservereferenceshandling preservereferenceshandlingobjects string json jsonconvertserializeobjectfrnds jsonsettings cacheaddcachekey json return json else return stringresult userconnection is a simple table in my db and currently has no data so the call returns an empty json array user is a session object and currently defaults to 1 for useridwhen remotedebugging this the object is found in cache and the cached object is returned so all good except the response time still varies by a factor of 20 300ms 6secwhen remote debugging one of the other web service methods i got the following error when attempting to access the cached object using the corresponding key object result cachegetcachekeyerrorcodesubstatusthere is a temporary failure please retry later one or more specified cache servers are unavailable which could be caused by busy network or servers for onpremises cache clusters also verify the following conditions ensure that security permission has been granted for this client account and check that the appfabric caching service is allowed through the firewall on all cache hosts also the maxbuffersize on the server must be greater than or equal to the serialized object size sent from the client additional information the client was trying to communicate with the server nettcpekckodevcachewindowsnet238i then set the maxbuffersize in my config as follows configsectionssection namedatacacheclients typemicrosoftapplicationservercachingdatacacheclientssection microsoftapplicationservercachingcore allowlocationtrue allowdefinitioneverywhere section namecachediagnostics typemicrosoftapplicationservercachingazurecommondiagnosticsconfigurationsection microsoftapplicationservercachingazurecommon allowlocationtrue allowdefinitioneverywhere configsectionssystemwebcaching outputcache defaultproviderafcacheoutputcacheprovider providers add nameafcacheoutputcacheprovider typemicrosoftwebthistributedcachethistributedcacheoutputcacheprovider microsoftwebthistributedcache cachenamedefault datacacheclientnamedefault applicationnameafcacheoutputcache providers outputcache cachingsystemweb datacacheclients datacacheclient namedefault autothiscover isenabledtrue identifierekckodevcachewindowsnet localcache isenabledtrue synctimeoutbased objectcount10 ttlvalue300 securityproperties modemessage sslenabledfalse messagesecurity authorizationinfox securityproperties transportproperties connectionbuffersize131072 maxbufferpoolsize268435456 maxbuffersize8388608 maxoutputdelay2 channelinitializationtimeout60 receivetimeout60 datacacheclient datacacheclientsbut i still get such erratic response times particularly when hitting the same service call repeatedlyafter adding the maxbuffersize config the cache calls are still hitandmiss some fetch the object other times i get the same exception however the port is different the client was trying to communicate with the server nettcpekckodevcachewindowsnet233could this be a firewall issue if so how do i open the appropriate portsi also just got the following exception when instantiating the datacache object cache cachefactorygetdefaultcacheerrorcodesubstatusthere is a temporary failure please retry later one or more specified cache servers are unavailable which could be caused by busy network or servers for onpremises cache clusters also verify the following conditions ensure that security permission has been granted for this client account and check that the appfabric caching service is allowed through the firewall on all cache hosts also the maxbuffersize on the server must be greater than or equal to the serialized object size sent from the clientany thoughts on why i am getting such results it is certainly no quicker with the cache than wihtout it so it appears there is some sort of latency in the cache which does not seem rightthanks in advance for any helpupdateafter doing some more searching it seems i am not the only one with this issuepoor performance with azure cachei find it hard to believe that this is the performance i should expectupdate 2i have commented out all cacherelated code from my service and ran the same tests again the response times are appreciably lower without the cache the getfriends callaverages about 250ms wihtout the cache but peaks at over 5sec with the cachemy other method that fetches about 4kb of data was peaking at 20 seconds with cache and now averages about 2sec without the cacheagain i find it hard to believe that this is the performance i should expectupdate 3i have now scrapped azure cache in favour of memorycache nice example heremy service calls are now consistently taking approx 300ms in the browseri have opened a ticket with microsoft azure support regarding azure cache so i will update this post when they get in touch and i have asked them why their cache is so rubbish just when my faith in microsoft was climbing,"['c#', 'asp.net']" +706006,wpf application hang by propertychangedeventmanager in concurrent environments i am working on a complex wpf application which hangs in production once several days there is a thread other than gui thread filling data to models bind to the grid and triggers inotifypropertychangedpropertychanged event i wrote a script to attach mdbg to the hanging process and dumping the current stack trace of the threads it helps a lot when finding the cause of deadlock but it does not help this timethe thread which is updating models is stopped at acquiring readlockthread 80 windowsbasedll0msinternalreaderwriterlockwrapperget readlock source line information unavailable 1 windowsbasedll0systemcomponentmodelpropertychangedeventmanageronpropertychangedsender argssystemcomponentmodelpropertychangedeventargs source line information unavailable 2 firing propertychanged event the same thing happens to the gui threadthread 00 windowsbasedll0msinternalreaderwriterlockwrapperget readlock source line information unavailable 1 windowsbasedll0systemcomponentmodelpropertychangedeventmanageronpropertychangedsendermycompanywindowsviewmodelwindowwindowviewmodel argssystemcomponentmodelpropertychangedeventargs source line information unavailable 2 mycompanywindowscontractsdll0mycompanywindowsviewmodelmodelviewmodelitembasenotifypropertychangedpropertynameisactive source line information unavailable 3 mycompanywindowscontractsdll0mycompanywindowsviewmodelwindowwindowviewmodelset isactivevaluetrue source line information unavailable 4 mycompanywindowsdll0mycompanywindowsviewmodelwindowisactivebindingonwindowisactivechangedsendermycompanyxpfviewsxpfribbonshellxpfribbonshellview esystemeventargs source line information unavailable 5 windowsbasedll0msinternalcomponentmodelpropertychangetrackeronpropertyinvalidationdna argsna source line information unavailable 6 windowsbasedll0systemwindowsdependentlistinvalidatedependentssourcena sourceargsna source line information unavailable 7 windowsbasedll0systemwindowsdependencyobjectnotifypropertychangeargsna source line information unavailable 8 windowsbasedll0systemwindowsdependencyobjectupdateeffectivevalueentryindexna dpna metadatana oldentryna newentryna coercewithdeferredreferencena coercewithcurrentvaluena operationtypena source line information unavailable 9 windowsbasedll0systemwindowsdependencyobjectsetvaluecommondpna valuena metadatana coercewithdeferredreferencena coercewithcurrentvaluena operationtypena isinternalna source line information unavailable 10 windowsbasedll0systemwindowsdependencyobjectsetvaluekeyna valuena source line information unavailable 11 presentationframeworkdll0systemwindowswindowhandleactivatewindowactivatedna source line information unavailable 12 presentationframeworkdll0systemwindowswindowwmactivatewparamna source line information unavailable 13 presentationframeworkdll0systemwindowswindowwindowfiltermessagehwndna msgna wparamna lparamna handledna source line information unavailable 14 presentationcoredll0systemwindowsinterophwndsourcepublichooksfiltermessagehwndna msgna wparamna lparamna handledna source line information unavailable 15 windowsbasedll0mswin32hwndwrapperwndprochwndna msgna wparamna lparamna handledna source line information unavailable 16 windowsbasedll0mswin32hwndsubclassthispatchercallbackoperationona source line information unavailable 17 windowsbasedll0systemwindowsthreadingexceptionwrapperinternalrealcallcallbackna argsna numargsna source line information unavailable 18 windowsbasedll0msinternalthreadingexceptionfilterhelpertrycatchwhensourcesystemwindowsthreadingthispatcher methodna argsna numargsna catchhandlernull source line information unavailable 19 windowsbasedll0systemwindowsthreadingthispatcherwrappedinvokecallbackna argsna numargsna catchhandlerna source line information unavailable 20 windowsbasedll0systemwindowsthreadingthispatcherinvokeimplpriorityna timeoutna methodna argsna numargsna source line information unavailable 21 windowsbasedll0mswin32hwndsubclasubclasswndprochwndna msgna wparamna lparamna source line information unavailable il method without metadata 22 windowsbasedll0msinternalreaderwriterlockwrapperget readlock source line information unavailable 23 windowsbasedll0systemcomponentmodelpropertychangedeventmanageronpropertychangedsendermycompanywindowsviewmodelwindowwindowviewmodel argssystemcomponentmodelpropertychangedeventargs source line information unavailable 24 mycompanywindowscontractsdll0mycompanywindowsviewmodelmodelviewmodelitembasenotifypropertychangedpropertynameisactive source line information unavailable 25 mycompanywindowscontractsdll0mycompanywindowsviewmodelwindowwindowviewmodelset isactivevaluefalse source line information unavailable 26 mycompanywindowsdll0mycompanywindowsviewmodelwindowisactivebindingonwindowisactivechangedsendermycompanyxpfviewsxpfribbonshellxpfribbonshellview esystemeventargs source line information unavailable 27 windowsbasedll0msinternalcomponentmodelpropertychangetrackeronpropertyinvalidationdna argsna source line information unavailable 28 windowsbasedll0systemwindowsdependentlistinvalidatedependentssourcena sourceargsna source line information unavailable 29 windowsbasedll0systemwindowsdependencyobjectnotifypropertychangeargsna source line information unavailable 30 windowsbasedll0systemwindowsdependencyobjectupdateeffectivevalueentryindexna dpna metadatana oldentryna newentryna coercewithdeferredreferencena coercewithcurrentvaluena operationtypena source line information unavailable 31 windowsbasedll0systemwindowsdependencyobjectsetvaluecommondpna valuena metadatana coercewithdeferredreferencena coercewithcurrentvaluena operationtypena isinternalna source line information unavailable 32 windowsbasedll0systemwindowsdependencyobjectsetvaluekeyna valuena source line information unavailable 33 presentationframeworkdll0systemwindowswindowhandleactivatewindowactivatedna source line information unavailable 34 presentationframeworkdll0systemwindowswindowwmactivatewparamna source line information unavailable 35 presentationframeworkdll0systemwindowswindowwindowfiltermessagehwndna msgna wparamna lparamna handledna source line information unavailable 36 presentationcoredll0systemwindowsinterophwndsourcepublichooksfiltermessagehwndna msgna wparamna lparamna handledna source line information unavailable 37 windowsbasedll0mswin32hwndwrapperwndprochwndna msgna wparamna lparamna handledna source line information unavailable 38 windowsbasedll0mswin32hwndsubclassthispatchercallbackoperationona source line information unavailable 39 windowsbasedll0systemwindowsthreadingexceptionwrapperinternalrealcallcallbackna argsna numargsna source line information unavailable 40 windowsbasedll0msinternalthreadingexceptionfilterhelpertrycatchwhensourcesystemwindowsthreadingthispatcher methodna argsna numargsna catchhandlernull source line information unavailable 41 windowsbasedll0systemwindowsthreadingthispatcherwrappedinvokecallbackna argsna numargsna catchhandlerna source line information unavailable 42 windowsbasedll0systemwindowsthreadingthispatcherinvokeimplpriorityna timeoutna methodna argsna numargsna source line information unavailable 43 windowsbasedll0mswin32hwndsubclasubclasswndprochwndna msgna wparamna lparamna source line information unavailable il method without metadata 44 windowsbasedll0msinternalreaderwriterlockwrapperget readlock source line information unavailable 45 windowsbasedll0systemcomponentmodelpropertychangedeventmanageronpropertychangedsendermycompanywindowsviewmodelwindowwindowviewmodel argssystemcomponentmodelpropertychangedeventargs source line information unavailable 46 mycompanywindowscontractsdll0mycompanywindowsviewmodelmodelviewmodelitembasenotifypropertychangedpropertynameisactive source line information unavailable 47 mycompanywindowscontractsdll0mycompanywindowsviewmodelwindowwindowviewmodelset isactivevaluetrue source line information unavailable 48 mycompanywindowsdll0mycompanywindowsviewmodelwindowisactivebindingonwindowisactivechangedsendermycompanyxpfviewsxpfribbonshellxpfribbonshellview esystemeventargs source line information unavailable 49 windowsbasedll0msinternalcomponentmodelpropertychangetrackeronpropertyinvalidationdna argsna source line information unavailable 50 windowsbasedll0systemwindowsdependentlistinvalidatedependentssourcena sourceargsna source line information unavailable 51 windowsbasedll0systemwindowsdependencyobjectnotifypropertychangeargsna source line information unavailable 52 windowsbasedll0systemwindowsdependencyobjectupdateeffectivevalueentryindexna dpna metadatana oldentryna newentryna coercewithdeferredreferencena coercewithcurrentvaluena operationtypena source line information unavailable 53 windowsbasedll0systemwindowsdependencyobjectsetvaluecommondpna valuena metadatana coercewithdeferredreferencena coercewithcurrentvaluena operationtypena isinternalna source line information unavailable 54 windowsbasedll0systemwindowsdependencyobjectsetvaluekeyna valuena source line information unavailable 55 presentationframeworkdll0systemwindowswindowhandleactivatewindowactivatedna source line information unavailable 56 presentationframeworkdll0systemwindowswindowwmactivatewparamna source line information unavailable 57 presentationframeworkdll0systemwindowswindowwindowfiltermessagehwndna msgna wparamna lparamna handledna source line information unavailable 58 presentationcoredll0systemwindowsinterophwndsourcepublichooksfiltermessagehwndna msgna wparamna lparamna handledna source line information unavailable 59 windowsbasedll0mswin32hwndwrapperwndprochwndna msgna wparamna lparamna handledna source line information unavailable 60 windowsbasedll0mswin32hwndsubclassthispatchercallbackoperationona source line information unavailable 61 windowsbasedll0systemwindowsthreadingexceptionwrapperinternalrealcallcallbackna argsna numargsna source line information unavailable 62 windowsbasedll0msinternalthreadingexceptionfilterhelpertrycatchwhensourcesystemwindowsthreadingthispatcher methodna argsna numargsna catchhandlernull source line information unavailable 63 windowsbasedll0systemwindowsthreadingthispatcherwrappedinvokecallbackna argsna numargsna catchhandlerna source line information unavailable 64 windowsbasedll0systemwindowsthreadingthispatcherinvokeimplpriorityna timeoutna methodna argsna numargsna source line information unavailable 65 windowsbasedll0mswin32hwndsubclasubclasswndprochwndna msgna wparamna lparamna source line information unavailable il method without metadata 66 windowsbasedll0systemcomponentmodelpropertychangedeventmanagerprivateaddlistenersourcena listenerna propertynamena source line information unavailable 67 presentationframeworkdll0msinternaldatapropertypathworkerreplaceitemkna newona parentna source line information unavailable 68 presentationframeworkdll0msinternaldatapropertypathworkerupdatesourcevaluestatekna collectionviewna newvaluena isasubpropertychangena source line information unavailable 69 presentationframeworkdll0msinternaldataclrbindingworkerattachdataitem source line information unavailable 70 presentationframeworkdll0systemwindowsdatabindingexpressionactivateitemna source line information unavailable 71 presentationframeworkdll0systemwindowsdatabindingexpressionattachtocontextattemptna source line information unavailable 72 presentationframeworkdll0systemwindowsdatabindingexpressionmsinternaldataidatabindengineclientattachtocontextlastchancena source line information unavailable 73 presentationframeworkdll0msinternaldatadatabindenginetaskrunlastchancena source line information unavailable 74 presentationframeworkdll0msinternaldatadatabindenginerunargna source line information unavailable 75 presentationframeworkdll0msinternaldatadatabindengineonlayoutupdatedsenderna ena source line information unavailable 76 presentationcoredll0systemwindowscontextlayoutmanagerfirelayoutupdateevent source line information unavailable 77 presentationcoredll0systemwindowscontextlayoutmanagerupdatelayout source line information unavailable 78 presentationcoredll0systemwindowscontextlayoutmanagerupdatelayoutcallbackargna source line information unavailable 79 presentationcoredll0systemwindowsmediamediacontextfireinvokeonrendercallbacks source line information unavailable 80 presentationcoredll0systemwindowsmediamediacontextrendermessagehandlercoreresizedcompositiontargetna source line information unavailable 81 presentationcoredll0systemwindowsmediamediacontextrendermessagehandlerresizedcompositiontargetna source line information unavailable 82 windowsbasedll0systemwindowsthreadingexceptionwrapperinternalrealcallcallbackna argsna numargsna source line information unavailable 83 windowsbasedll0msinternalthreadingexceptionfilterhelpertrycatchwhensourcesystemwindowsthreadingthispatcher methodna argsna numargsna catchhandlernull source line information unavailable 84 windowsbasedll0systemwindowsthreadingthispatcherwrappedinvokecallbackna argsna numargsna catchhandlerna source line information unavailable 85 windowsbasedll0systemwindowsthreadingthispatcheroperationinvokeimpl source line information unavailable 86 mscorlibdll0systemthreadingexecutioncontextruntrycodeuserdatana source line information unavailable 87 mscorlibdll0systemthreadingexecutioncontextrunexecutioncontextna callbackna statena ignoresyncctxna source line information unavailable 88 mscorlibdll0systemthreadingexecutioncontextrunexecutioncontextna callbackna statena source line information unavailable 89 windowsbasedll0systemwindowsthreadingthispatcheroperationinvoke source line information unavailable 90 windowsbasedll0systemwindowsthreadingthispatcherprocessqueue source line information unavailable 91 windowsbasedll0systemwindowsthreadingthispatcherwndprochookhwndna msgna wparamna lparamna handledna source line information unavailable 92 windowsbasedll0mswin32hwndwrapperwndprochwndna msgna wparamna lparamna handledna source line information unavailable 93 windowsbasedll0mswin32hwndsubclassthispatchercallbackoperationona source line information unavailable 94 windowsbasedll0systemwindowsthreadingexceptionwrapperinternalrealcallcallbackna argsna numargsna source line information unavailable 95 windowsbasedll0msinternalthreadingexceptionfilterhelpertrycatchwhensourcesystemwindowsthreadingthispatcher methodna argsna numargsna catchhandlernull source line information unavailable 96 windowsbasedll0systemwindowsthreadingthispatcherwrappedinvokecallbackna argsna numargsna catchhandlerna source line information unavailable 97 windowsbasedll0systemwindowsthreadingthispatcherinvokeimplpriorityna timeoutna methodna argsna numargsna source line information unavailable 98 windowsbasedll0mswin32hwndsubclasubclasswndprochwndna msgna wparamna lparamna source line information unavailable il method without metadata internal frame mu il method without metadata 99 windowsbasedll0systemwindowsthreadingthispatcherpushframeimplframena source line information unavailable 100 presentationframeworkdll0systemwindowsapplicationruninternalwindowna source line information unavailable 101 presentationframeworkdll0systemwindowsapplicationrun source line information unavailable 102 myprogramexe0xamlgeneratednamespacegeneratedapplicationmain source line information unavailableit seems that someone is holding the writelock but never release but how can i check whos holding that i have paste the whole stacktrace i have got here is someone to give me some hits on the root cause like whats hwndsubclass and why it happens repeatedly in the stacktrace with the change of isactive and windowstate propertyplease add comments if you need more information,['c#'] +706034,afnetworking and swift i am trying to get a json response using swifti sniffed the request and response everything okhowever the return value is always nil let httpclient appdelegateappdelegatehttprequestoperationmanager as afhttprequestoperationmanager let path datenwfs let query servicewfsrequestgetfeatureversion110typenameogdwienampelogdsrsnameepsg4326outputformatjsonstringbyaddingpercentescapesusingencodingnsutf8stringencoding func successblockoperation afhttprequestoperation responseobject anyobject printlnjson responseobject func errorblockoperation afhttprequestoperation errornserror printlnerror errorlocalizeddescription let urlstring path query printlnurlstring httpclientbaseurlabsolutestring urlstringi also tried it this way httpclientgeturlstring parameters nil success operation afhttprequestoperation responseobject anyobject void in printlnsuccess printlnjson responseobject failure operation afhttprequestoperation errornserror void in printlnfailure a but the responseobject always seems to be nileditmaybe the reason is the possible wrong initialisation in my appdelegatevar httprequestoperationmanager afhttprequestoperationmanager java server clientclass func appdelegate appdelegate return uiapplicationsharedapplicationdelegate as appdelegatefunc configurewebservice let requestserializer afjsonrequestserializer requestserializersetvalue1234567890 forhttpheaderfield clientid requestserializersetvaluetest forhttpheaderfield appname requestserializersetvalue100 forhttpheaderfield appversion let responseserializer afjsonresponseserializer afnetworkactivityindicatormanagersharedmanagerenabled true http let baseurl nsurlstring httprequestoperationmanager afhttprequestoperationmanagerbaseurl baseurl httprequestoperationmanagerrequestserializer requestserializer httprequestoperationmanagerresponseserializer responseserializerany suggestions what i am doing wrongkind regards steve,['ios'] +706037,how to aggregate the data from an async producer and write it to a file i am learning about asyncawait patterns in c currently i am trying to solve a problem like thisthere is a producer a hardware device that generates 10 packets per second i need to log this data to a file the device only has a readasync method to report a single packet at a timei need to buffer the packets and write them in the order they are generated to the file only once a secondwrite operation should fail if the write process is not finished in time when the next batch of packets is ready to be writtenso far i have written something like below it works but i am not sure if this is the best way to solve the problem any comments or suggestion what is the best practice to approach this kind of producerconsumer problem where the consumer needs to aggregate the data received from the producerstatic async task testloggerdevice device int seconds const int buflength 10 bool firstiteration true task writertask null using var writer new streamwritertestlog do var buffer new bytebuflength for int i 0 i buflength i bufferi await devicereadasync if firstiteration if writertaskiscompleted throw new exceptionwrite time out writertask taskrun foreach var b in buffer writerwritelinetohexstringb firstiteration false while seconds 0,"['c#', '.net']" +706051,extension project templates not appearing in xcode 6 i am not sure if i am the only one experiencing this program but i have tried searching and have not been able to find anyone in my current situation i downloaded xcode 6 beta and was interested in extension programming for ios 8 however i have been unable to locate the extensions in my project templates when creating a new project in xcode i saw a youtube video unrelated to extension programming but i did notice that the option was not there for the said video now i have had a look through the contents of the xcode 6 beta package and have been able to locate the actual templates themselves so i have no doubt they are present it just seems that they are not actually being loadedfor the record i also downloaded some example custom keyboard code from github in order to see whether xcode will recognise it and it does going as far as actually thisplaying the e icon beside the build target i should also mention that i do have a build of xcode 5 also present on my machineis anyone else experiencing this issue or does anyone know how to overcome itthanks,['ios'] +706075,mach exception in iphone i sometimes get following exceptionmach exception 0xx count d code 0xllx 0xllxmach skipping registered port it is invalidmach skipping registered port mask does not matchsignal d info p uapvoid pi do not have any idea what these exceptions are about can somebody throw any light on this,"['iphone', 'objective-c']" +706254,best way to package a python library that includes a c shared library i have written a library whose main functionality is implemented in c speed is critical with a thin python layer around it to deal with the ctypes nastinessi am coming to package it and i am wondering how i might best go about this the code it must interface with is a shared library i have a makefile which builds the c code and creates the so file but i do not know how i compile this via thistutils should i just call out to make with subprocess by overriding the install command if so is install the place for this or is build more appropriateupdate i want to note that this is not a python extension that is the c library contains no code to itself interact with the python runtime python is making foreign function calls to a straight c shared library,"['python', 'c']" +706325,create a button programmatically and set a background image when i try creating a button and setting a background image in swiftlet button uibuttonbuttonwithtypeuibuttontypesystem as uibutton buttonframe cgrectmake100 100 100 100 buttonsetimageimage forstate uicontrolstatenormal buttonaddtargetself action btntouched forcontrolevents uicontroleventstouchupinside selfviewaddsubviewbuttoni always get an error cannot convert the expressions type void to type uiimage,['ios'] +706334,xcode debugging not showing values i am completely stumped i have been debugging for over a year and have only had this problem when the build configuration was set to release i have the build configuration set to debug and i have checked to be sure i am attaching to the correct process and yet i still cannot see the values while stepping through the code has anybody else ran into this issuehere is a screen shotthe value is returning but i am unable to see the values of anything in this method or any of the other methods and i cannot figure out whythank you for any hints you can give me update i have tried to print out the valued and this is the output i receive notice though that the value in the variables view is correct for the result even though i cannot print it out but the other values like filepath should not be nilthis is so weird update i put the breakpoint on the return statement and still no luckthis time i see no value for result,['objective-c'] +706364,swift cannot import sqlite3 ios i added libsqlite30dylib to my project and then i tried to import using the following codeimport uikitimport sqlite3class dataware nsobjectbut it is giving me this errorno such module sqlite3,['ios'] +706369,how to create ns optionsstyle bitmask enumerations in swift in apples documentation about interacting with c apis they describe the way ns enummarked cstyle enumerations are imported as swift enumerations this makes sense and since enumerations in swift are readily provided as the enum value type it is easy to see how to create our ownfurther down it says this about ns optionsmarked cstyle optionsswift also imports options marked with the ns options macro whereas options behave similarly to imported enumerations options can also support some bitwise operations such as and in objectivec you represent an empty option set with the constant zero 0 in swift use nil to represent the absence of any optionsgiven that there is not an options value type in swift how can we create a cstyle options variable to work with,['ios'] +706375,checking for emptynull jtoken in a jobject i have the followingjarray clients jarrayclientsparsedobjectsforeach jobject item in clientschildren etc sql params stuff commandparametersmyparametervalue jtokentosqlitemthisparameterjtokentosql looks like thispublic static object jtokentosqljtoken obj if objany return objectobj else return objectdbnullvaluei have tried jobjectobjcount also but does not seem to be working,"['c#', 'sql']" +706388,is there an api for the chromewebrtcinternals variables in javascript i want to get access to some of the logged variables in the chromewebrtcinternals but i did not find anything on google not even a description of the graphs i can seei am particularly interested in packetslost googcurrentdelayms and goognackssent why i want to access the webrtcinternalsi am writing a google chrome application that shares a video stream p2p it uses peerjs to share the stream with other peers which in turn uses googles webrtc implementation underneath to make my application perfect i would need to know when a big delay occurs since i can see the delay logged in chromewebrtcinternals i was wondering if i could access it through javascriptmy guess is there is no api for the chromewebrtcinternalsmenu,['javascript'] +706449,which part of this relationship willcascadeondeletetrue this is what i have todaymodelbuilderentityuser hasoptionalp pdealdevice withrequiredc cuser willcascadeondeletefalsewhat i would like is to have the related dealdevice rows be deleted if the user is deleted so that i can just delete the user and have everything related go away can i just change willcascadeondeletefalse to willcascadeondeletetrue or will that delete the user if the deal is deleted,['c#'] +706483,what calls the setselectedno method automaticaly i have this weird problem with uitableview and uitableviewcell whenever the tableviewcellforrowatindexpath is called the setselectedno is called afterwards uitableviewcell tableviewuitableview tableview cellforrowatindexpathnsindexpath indexpath nsdictionary celldata datasourceindexpathrow nsstring cellid nil choose cell type nsinteger type celldata valueforkeytype integervalue switch type case 0 root level cellid rootheadercell break case 1 sub header cellid subheadercell break case 2 default value row radiobutton cellid radiobuttoncell break csbasefiltercell cell tableview dequeuereusablecellwithidentifiercellid forindexpathindexpath configure the cell cell setdatacelldata return cellcelldata contains information about selection and in cellvoidsetdatansdictionary data nslogset datanslogdata has selectedd data haskeyselectednslogdataselected data valueforkeyselected if data haskeyselected self setselecteddata valueforkeyselected boolvalue animatedno i set the selection but it was not selected i have put traces in setdata and the values were fine i have put trace in setselectedanimated and found that 3 calls are made voidsetselectedboolselected animatedboolanimated super setselectedselected animatedanimated nslog setselectedselecteddselfselected selfaccessorytype selected uitableviewcellaccessorycheckmarkuitableviewcellaccessorynonethis is what is thisplayed on log output20140605 2159679 uitableview filter sort4282160b set data20140605 2159679 uitableview filter sort4282160b data has selected120140605 2159680 uitableview filter sort4282160b dataselected120140605 2159680 uitableview filter sort4282160b csradiobuttoncell 0x8c80630 baseclass uitableviewcell frame 0 64 320 32 autoresize w layer calayer 0x8c76920 setselectedselected120140605 2159686 uitableview filter sort4282160b csradiobuttoncell 0x8c80630 baseclass uitableviewcell frame 0 64 320 32 autoresize w layer calayer 0x8c76920 setselectedselected020140605 2159811 uitableview filter sort4282160b csradiobuttoncell 0x8c80630 baseclass uitableviewcell frame 0 64 320 32 autoresize w layer calayer 0x8c76920 setselectedselected0table is placed in the viewcontroller it is not uitableviewcontrollerupdatei have put the setdata call in willthisplaycellforrowatindexpath and removed call to super definition of setselected and this resolved the issue it still shows in logs that setselected is called with no argument between setdata in cellforrowatindexpath and willthisplaycellforrowatindexpath but at least willthisplay is lasti have also tried successfuly with my own selection property checked which is set in setdata and in didselectrowatindexpath,['ios'] +706498,windowsessionstorage vs cookiestore what is the difference between using cookiestore and windowsessionstorage are there times when one should be used over the other security issueshere is what i know so farthe angularjs docs state that the cookiestore service is backed by session cookies cookiestore so it appears that information stored with cookiestore is tied to the windowtab where it is used this is affirmed by the use of the mysterious browser service in the code for cookiestore however since browser is an internal service and subject to change i cannot see how it is storing the data to see if it is similar to sessionstoragethe same browsertabwindow scope seems to apply to windowsessionstorage scope of sessionstorage and localstorage,['javascript'] +706584,async partialview causes httpserverutilityexecute blocked exception i have a partial view that tries to retrieve a ienumerablepost from the database using asyncmethodpublic static class postservice public static int postsperpage 50 public static async taskienumerablepost getrecentasyncint page 0 return await entityframeworkdbcontextposts tolistasync partialviewpublic async taskactionresult recentint page 0 return partialviewawait postservicegetrecentasyncpageand then if i try to call ithtmlactionrecent posti get the following exceptionhttpserverutilityexecute blocked while waiting for an asynchronous operation to completedescription an unhandled exception occurred during the execution of the current web request please review the stack trace for more information about the error and where it originated in the code exception details systeminvalidoperationexception httpserverutilityexecute blocked while waiting for an asynchronous operation to completewhy do i get this error should not it work,['c#'] +706722,can a website html5javascript access a mobile devices androidiphone contact list sdcard files can a website html5javascript access a mobile devices androidiphonecontact list sdcard filesa website as in one opened in a browser not a phonegap applicationwebapp,"['javascript', 'android', 'ios', 'iphone']" +706896,nggrid cannot set property griddim of undefined i am new in angular and i try to declare gridoption for nggrid within a function in costroller it cause an errortypeerror cannot set property griddim of undefinedi tried to solve it using scopeapply and ngif in template but nothing from this is working for me thanks for any advicemethod of the controllerscopegettest function httpget successfunction data status headers config scopemydata data consolelogsucess data definition for nggrid table scopemydata name moroni age 50 name tiancum age 43 name jacob age 27 name nephi age 29 name enos age 34 scopegridoptions data mydata scopeapply errorfunctiondata status headers config scopemydata data,['javascript'] +706897,orgmode no syntax highlighting in exported html page i have been trying to get the syntax highlighting to work when exporting orgmode formatted file to html but none of what i have done so far has worked i followed the babel configuration guide but the code block on the generated html page still looks plain i have also set setq orgsrcfontifynatively t what am i missing,['html'] +706980,npmignore not ignoring files i have a private module stored on github that i am including in one of my projects using npm the module has a npmignore file but nothing is being ignored when i install or update the moduleprojects packagejson name your cool project version 0 dependencies mymodule gitsshusermymodulegit all your other dependencies modules npmignore filegitgulpfilejsindexhtmltestsjsreadmemdwhen i run npm update mymodule these files are still being downloaded into my project am i missing something does npmignore work for privately hosted modules thanks in advance,['javascript'] +706991,nsdictionaryofvariablebindings swift equivalent the apple documentation shows an unsettling blank space under the creating a dictionary section of the uikit reference here has anyone found a replacement for the nsdictionaryofvariablebindings macro or are we expected to just write our ownedit according to this perhaps the right approach is to write a global function to handle this looks like complex macros are out entirely,['ios'] +707002,how to formally deprecate a pip package this might seem a little strange but i cannot really find an acceptable way of doing this after having googled around for quite some timebasically i have a pip package that i maintain it is mostly a wrapper for an external api and the external api just changed i sent out a new version of the wrapper but presumably not everyone keeps their pip packages completely up to date i made an effort to keep most legacy functionality around but there were a few features i was unable to preserveis there any way to formally let people know that every package before a certain version has been formally deprecated ideally this would tell people to actively upgrade but i am not sure how feasible that isit seems like pip must have some functionality or best practices for this but i cannot really find any relevant documentation,['python'] +707017,why do backslashes appear twice when i create a string containing backslashes they get duplicated my string whydoesithappen my stringwhydoesithappenwhy,['python'] +707083,weak table and gc finalizer using c api i am attempting to create a gc finalizer for a function value by storing it in a weak table using the c api i started off by writing a prototype in pure lua 52local function myfinalizer print called finalizerendfunction myfunc print called myfuncendlocal sentinels setmetatable modek sentinelsmyfunc setmetatable gcmyfinalizer myfuncmyfunc nilcollectgarbage collectprint closing luaresulting outputcalled myfunccalled finalizerclosing luathe prototype seems to be working as intended below is the c versioninclude stdlibhinclude stdiohinclude luahinclude lualibhinclude lauxlibhstatic int my finalizerlua state l putscalled finalizer return 0static int my funclua state l putscalled myfunc return 0int mainvoid lua state l lual newstate lual openlibsl create sentinels table weak keys in registry lua newtablel t lua newtablel t mt lua pushstringl k t mt v lua setfieldl 2 mode t mt lua setmetatablel 2 t lua setfieldl lua registryindex sentinels push global function and register as sentinel lua pushcfunctionl my func f lua getfieldl lua registryindex sentinels f t lua pushvaluel 1 f t k lua newuserdatal 0 f t k v lua newtablel f t k v mt lua pushcfunctionl my finalizer f t k v mt v lua setfieldl 2 gc f t k v mt lua setmetatablel 2 f t k v lua settablel 3 f t lua popl 1 f lua setgloball myfunc execute test script and exit if lual dostringl myfunc myfuncnil collectgarbagecollect printferror sn lua tostringl 1 lua gcl lua gccollect 0 suggestion two full gc cycles fflushstdout suggestion immediate flush putsclosing lua lua closel fflushstdout return exit successcompiled using gcc stdc99 wall werror pedantic o2 o main mainc ldl llua52 lmresulting outputcalled myfuncclosing luacalled finalizerthe c version has a few minor differencesinstead of a local sentinels table i am storing in the registryusing a zero sized userdata instead of a table for sentinel value with gc metamethodi am confused as to why in the c version the myfunc finalizer does not execute after running a full collection cycle what am i doing wrong,['c'] +707109,ruby on rails common method available for controllers and views i have been working with ruby on rails for a short time recently i implemented an authentication system for my application i made a method available on application helperrb to retrieve the current logged user method called current userthe method just retrieves my user object if the sessionuser id variable is presenthowever i face the following problemif i place the current user method in application helperrb my controllers cannot make use of itif i place the current user method in application controllerrb my views cannot make use of itwhats the best approach to solve this problem the easy way would be duplicate my code in both controller and helper but i know there is a better and more correct waythanks in advance,"['ruby-on-rails', 'ruby']" +707110,why nsdateformatter is returning null for a 19102014 in a brazilian time zone nsstring datestring 19102014nsdateformatter dateformatter nsdateformatter alloc initdateformatter setdateformatddmmynsdate mydate dateformatter datefromstringdatestringwhy mydate is null for this specific date 19102014 if i change the datestring to 25102014 dateformatter return the date correctly what is wrong with my code this code returns null when my iphone time zone is brasilia brasil when my time zone is washington dc eua for example the code returns the correct date,"['ios', 'objective-c']" +707130,angularjs ngmodel bound dropdown value changes visually while variable does not i have a dropdown listselect ngmodelfiltercountry ngoptionscountrycode as countryname for country in countries ngchangebroadcast option valueall countriesoptionselectscopecountries is initially populated by a service and then another dropdown change event would limit the values of scopecountries by calling the service again passing by the other dropdowns selected itemthe issue here is when scopefiltercountry is already bound to a value other than the default value and scopecountries gets updated to a new list that does not include scopefiltercountrys value i can see countries dropdown reverting back to its default option all countries however scopefiltercountry remains as it wasany ideas about this scenario should not scopefiltercountry get updated back to the default valueupdate here is a fiddleupdatejust to illustrate this here is a screenshot from the fiddlethis does look like a bug to me i have opened an issue for itupdate this has been addressed and fixed by angularjs team demo here,['javascript'] +707152,ioerror decoder jpeg not available when using pillow before someone says sudo aptget install libjpegdev or something along those lines i do not have sudo access i am on a slice of a server that does not allow me to have sudo access so i have gotta do this entire thing in my local directory that is the only way i can do iti need a python script to resize an image it works perfectly fine for png files but it falls apart on jpeg files with the error listed in the titlehere are the steps i have taken so fardownloaded libjpegdev and installed it to homejpegtest so inside the jpegtest folder is lib include and so oni downloaded pillow manually and extracted it out to homepillowi edited the setuppy fild so the jpeg root to a libincludeabsolute path to jpegtesti built and compiled pillow where it installed to homepythonbrewpythonspython275libpython27sitepackagespillow240py27linuxx86 64egg the important part of the output is as follows tkinter support not available jpeg support available openjpeg jpeg20 support not available zlib pngzip support available libtiff support not available freetype2 support not available littlecms2 support not available webp support not available webpmux support not availableso i would assume that this means jpeg support will function but when i run my program it saysioerror decoder jpeg not availablewhile typing this i also noticed the question at pillow recognizes jpeg encoder on install but not use which sounded very close to mine so i tried the solution thereln s mediasdl1homemidnightjpegtestliblibjpegso mediasdl1homemidnightpythonbrewpythonspython275libbut i still have the same errori have been working on this problem for about two days now and i am not entirely sure what to do if anyone could offer some assistance that would be very helpful,['python'] +707166,how can i test that a value is greater than or equal to in jasmine i want to confirm that a value is a decimal or 0 so the number should be greater than or equal to zero and less than 1 describepercentfunction itshould be a decimal function var percent insightspercent expectpercenttobegreaterthan0 expectpercenttobelessthan1 how do i mimic 0,['javascript'] +707240,how do i match a class against a specific class instance in a hamcrest matcher i would like to be able to assert that the annotation value matches the expected classimport orgjunittestimport static orghamcrestcorematchersimport static orghamcrestmatcherassertassertthatpublic final class annotatedclasstest test public void someannotationisstring assertthat annotatedclassclassgetannotationsomeannotationclassvalue isequaltostringclass however this is a type errorannotatedclasstestjava9 error no suitable method found for assertthatclasscap1matcherclastring assertthat method matcherassertt1assertthatt1matcher super t1 is not applicable actual argument matcherclastring cannot be converted to matcher super classcap1 by method invocation conversion method matcherassertt2assertthatstringt2matcher super t2 is not applicable cannot instantiate from arguments because actual and formal argument lists differ in length method matcherassertassertthatstringboolean is not applicable actual argument classcap1 cannot be converted to string by method invocation conversion where t1t2 are typevariables t1 extends object declared in method t1assertthatt1matcher super t1 t2 extends object declared in method t2assertthatstringt2matcher super t2 where cap1 is a fresh typevariable cap1 extends object from capture of 1 errorhere is the annotation classimport javalangannotationelementtypeimport javalangannotationretentionimport javalangannotationretentionpolicyimport javalangannotationtargetretentionretentionpolicyruntimetargetelementtypetypepublic interface someannotation class valueand the class to which i apply that annotationsomeannotationstringclasspublic final class annotatedclass the type error occurs becauseclass value annotatedclassclassgetannotationsomeannotationclassvalueandmatcherclastring classmatcher isequaltostringclasscannot satisfy the signature i intend to target which ist void assertthatt matcher super twhich made more specific by fixing t based on the first parameter would bevoid assertthatclass matcher super classi like the uniformity of assertthat and would prefer to avoid assertequalshere is how to do it with assertequals notably does not answer my questionimport orgjunittestimport static orgjunitassertassertequalspublic final class annotatedclasstest test public void someannotationisstring assertequals stringclass annotatedclassclassgetannotationsomeannotationclassvalue how do i match a class against a specific class instance in a hamcrest matcherstating that this is impossible is an acceptable answer if you can provide a compelling explanation,['java'] +707341,upgrade to rspec 3 cause error when using should have1error on since i updated my gemfile and moved to rspec 3 in many tests i am getting a error for wayit should reject attribute that are too short do short a 3 hash attrmergedetails short dealnewhashshould have1error ondetails endi am getting this errorfailureerror dealnewhashshould have1error ondetails nomethoderror undefined method have for rspecexamplegroupsdeal 2testsondealsmodelsvalidationsi read i should now be using expect instead of should but here with have1error on how should i write it to comply with rspec 3i tried the following but it still does not workit should reject attribute that are too short do short a 3 hash attrmergedetails short expectdealnewhasherror ondetailssizeto eq1 end,['ruby-on-rails'] +707388,ifstreamis open vs ifstreamfail reading savitchs problem solving in c stdifstreamfail is shown as an example to check if a file has been correctly opened ifstream or ofstreami have previously used as it is what i was first shown stdifstreamis open to perform the same checkwhich is better practiceor in the case that either one is called directly after attempting to open does it make no practical difference,['c++'] +707421,ios simulator cannot log in with icloud i am trying to test the icloud sync functionality of my app between a real device and the simulator however i cannot seem to log into icloud when i go to settingsicloud and enter my account details it just gets stuck on verifying however if i enter incorrect details it brings up the invalid password prompt as expectedhas anyone got a fix for this,['ios'] +707438,unknown type name for swift property i have a customviewcontroller class written in swift and a customnavigationcontroller class written in objective c i am trying to add my customnavigationcontroller as a property to my customviewcontroller i have added import customnavigationcontrollerh to my bridging header in my customviewcontroller i haveclass customviewcontroller uiviewcontroller var navcontroller customnavigationcontrollerinit methods override func viewdidload superviewdidload set up navigation controller navcontroller selfstoryboardinstantiateviewcontrollerwithidentifiercustomnavigationcontroller as customnavigationcontrollerthere are no errors until i try to build and runi get unknown type name customnavigationcontroller did you mean uinavigationcontrollerdoes anyone know why it does not recognize the type,['ios'] +707474,failed to instantiate the default view controller for uimainstoryboardfile main i am trying to create a new swift project and am having some issues i tried to create a new single page application but when i build i get an error saying 20140607 110413752 matchismo swift2007598021 failed to instantiate the default view controller for uimainstoryboardfile main perhaps the designated entry point is not setbut when i create the same single page application project with objectivec as the language it compiles and runs just fine is there some manual thing i must do in swift to get a project up and runningmy understanding for this error is that i need the default view to be set which is merely checking a box on your view controllers attributes picture below i tried the solution suggested in this stackoverflow post but it didnt help and i cannot find much more help on the subject with swift being so new any suggestions are appreciated,"['ios', 'iphone']" +707510,how to properly use a vector range constructor i want to load all the lines from a text file into a vectorstring by using its range constructor and then output them through coutincludeiostreamincludefstreamincludevectorincludeiteratorusing namespace stdint main ifstream filefiletxt vectorstring stringsistream iteratorstringfile istream iteratorstring forauto s strings cout s endl return 0when trying to compile the above code i get several errors for instanceerror no matching function for call to abeginstdvectorstdbasic stringchar stdistream iteratorstdbasic stringchar stdistream iteratorstdbasic stringchar a forauto s strings and several others i think i am missing something obvious here can anyone please help,['c++'] +707532,why is java pass by value only so here is another worthy downvote question i understand that java is pass by value and what this means and how it works so this is not another can you explain what pass by value is i am more curious as to why java does not include pass by reference i would imagine this would be useful it would also be helpful to know to cement the reasoning in my headi hate it is because it is scenarios surely the equivalent of because i said so so does anyone have an answer as to why java only includes pass by value,['java'] +707590,how to stop rspec warning messages i have just started learning to use rspec on my rails applicationit all seems to work ok but when i run rspec spec i get pages and pages of what i think are lint messagesi do not mind the ones that refer to my code but lots of them refer to gems that i am usingi cannot really fix thosehow can i configure rspec to apply lint only to my code and not external gemshere is a small sample i get over 20 lines of this stuffusersjcreaseyrvmgemsruby200p0gemssorcery085libsorcerymodelrb265 warning method redefined thiscarding old username attribute namesusersjcreaseyrvmgemsruby200p0gemsactivesupport3218libactive supportdependenciesrb251 warning loading in progress circular require considered harmful usersjcreaseyrvmgemsruby200p0gemssorcery085libsorceryrb from usersjcreaseyrvmgemsruby200p0binruby noexec wrapper14in main from usersjcreaseyrvmgemsruby200p0binruby noexec wrapper14in eval from usersjcreaseyrvmgemsruby200p0binrspec23in main from usersjcreaseyrvmgemsruby200p0binrspec23in load from usersjcreaseyrvmgemsruby200p0gemsrspeccore300exerspec4in top required from usersjcreaseythis is my rspec filecolorwarningsrequire spec helper,['ruby-on-rails'] +707616,badimageformatexception this will occur when running in 64 bit mode with the 32 bit oracle client components installed i am getting this error while on of my net application are trying to make a connection to oracle databasethe error says that this problem will occur when running in 64 bit mode with the 32 bit oracle client components installed but i have made sure many times that the client installed in x64 bit not 32date time 682014 105755 am systeminvalidoperationexception attempt to load oracle client libraries threw badimageformatexception this problem will occur when running in 64 bit mode with the 32 bit oracle client components installed systembadimageformatexception an attempt was made to load a program with an incorrect format exception from hresult 0x80070b at systemdatacommonunsafenativemethodsocilobcopy2intptr svchp intptr errhp intptr dst locp intptr src locp uint64 amount uint64 dst offset uint64 src offset at systemdataoracleclientocidetermineclientversion end of inner exception stack trace at systemdataoracleclientocidetermineclientversion at systemdataoracleclientoracleinternalconnectionopenonlocaltransactionstring username string password string servername boolean integratedsecurity boolean unicode boolean omitoracleconnectionname at systemdataoracleclientoracleinternalconnectionctororacleconnectionstring connectionoptions at systemdataoracleclientoracleconnectionfactorycreateconnectiondbconnectionoptions options object poolgroupproviderinfo dbconnectionpool pool dbconnection owningobject at systemdataproviderbasedbconnectionfactorycreatepooledconnectiondbconnection owningconnection dbconnectionpool pool dbconnectionoptions options at systemdataproviderbasedbconnectionpoolcreateobjectdbconnection owningobject at systemdataproviderbasedbconnectionpoolusercreaterequestdbconnection owningobject at systemdataproviderbasedbconnectionpoolgetconnectiondbconnection owningobject at systemdataproviderbasedbconnectionfactorygetconnectiondbconnection owningconnection at systemdataproviderbasedbconnectionclosedopenconnectiondbconnection outerconnection dbconnectionfactory connectionfactory at systemdataoracleclientoracleconnectionopen at customizedsetupinstallerrunscriptsinitializedbobjectsstring connectionstring string dbprovider,['.net'] +707630,swift iboutlet and custom controls i may be doing something really stupid but i do not seem to be able to use interface builder to connect iboutlet variables to custom views but only in swifti have created a class called myview which extends from uiview in my controller i have got a myview variable declared as iboutlet var newview myview i go into ib and drag a uiview onto the window and give it a class of myviewwhenever i have done similar in objective c i am then able to click on the view controller button at the top of the app window select the variable and drag it down to the control to link the two together when i try it in swift it refuses to recognise that the view is thereif i change the class of the variable in the controller to uiview it works fine but not with my custom viewhas anyone else got this problem and is it a feature or just my idiocycode for controllerimport uikitclass viewcontroller uiviewcontroller iboutlet var newviewmyview override func viewdidload superviewdidload do any additional setup after loading the view typically from a nib override func didreceivememorywarning superdidreceivememorywarning thispose of any resources that can be recreated code for viewimport uikitclass myview uiview initframe cgrect superinitframe frame initialization code only override drawrect if you perform custom drawing an empty implementation adversely affects performance during animation override func drawrectrect cgrect drawing code,['ios'] +707651,why does insertnewobjectforentityforname only return a nsmanagedobject i am trying to move some rubymotion code to swift so far it works what i do not understand iswhy the following result cannot be casted to the document classvar newobject nsmanagedobject nsentitydescriptioninsertnewobjectforentityfornamedocument inmanagedobjectcontextcontext as nsmanagedobjectthe insertnewobjectforentityforname call returns an object of type nsmanagedobject but why does not insertnewobjectforentityforname returns an object of type document as specified by entitymanagedobjectclassname my entity looks like thisfunc documententity nsentitydescription var entity nsentitydescription entityname document entitymanagedobjectclassname document var property nsattributedescription propertyname title propertyattributetype nsattributetypestringattributetype propertyoptional false entityproperties property return entityclass document nsmanagedobject nsmanaged var title stringmodel nsmanagedobjectmodelmodelentities documententityvar store nspersistentstorecoordinatormanagedobjectmodel model,['ios'] +707690,getting data from spring mvc in angular js in the initial view call i am new to angular js i have created a spring mvc web application with angular js i know that from view we can call rest services from angular js using resource restangular http but say in spring form the controller a view is been triggered and for loading the datas through angular within the view again a rest call from angular is been called from view to the server and gets the datas thereafter for loading instead is there any way to pass the json object while triggering the view from spring controller to the angular js at the first time itselfi have done a similar thing its working fine but do not know whether its a good approach or notspring controllerrequestmappinggetemployeepublic modelandview helloword jsonarray employeejsonarray contains all the information of the employee return new modelandviewemployee employemployeejsonarrayemployeejsphtml ngappmyappheadmeta httpequivcontenttype contenttexthtml charsetiso88591titlespring 30 mvc series hello worldtitlescript srcscriptscriptvar app angularmodulemyapp appcontrollermyctrl functionscope scopeemployee scopeloaddata functionemployee scopeemployee jsonparseemployee scriptheadbody ngcontrollermyctrlloaddataemployee input typetext ngvalueemployee0namebodyhtml,['javascript'] +707781,rendering problems missing styles after every update i get the rendering problems missing styles is the correct theme chosen for this layout and the gradle resolving without end after every android studio update making my entire code non runnable only solution is to just recreate my project is there any solution to this it is really really annoying,['android'] +707833,enum conversion of uiinterfaceorientation to avcapturevideoorientation in swift i am playing around with using avfoundation in swiftnormally when i set up a video camera capture session i do something like the following in objectiveccameraviewpreviewlayer connection setvideoorientationavcapturevideoorientationself interfaceorientationin swift it seems like i have to do something like this because of optional typeif let connection cameraviewpreviewlayerconnection connectionvideoorientation selfinterfaceorientation as avcapturevideoorientationhowever this complains withaavcapturevideoorientationa is not a subtype of auiinterfaceorientationaafter reading about the downcasting methodology this makes a lot of sense but i am struggling to find how to actually get this workingdo i need to write a helper method that basically does a switch statement through all the available values of uiinterfaceorientation to get this working,['ios'] +707834,the type javautilmapentry cannot be resolved it is indirectly referenced from required class files i am writing a simple java program on eclipse import javautilhashmappublic class demo public static void mainstring args hashmapstring string hash new hashmap the above program generates the following errorsthe project was not built since its build path is incomplete cannot find the class file for javautilmapentry fix the build path then try building this projectthe type javautilmapentry cannot be resolved it is indirectly referenced from required class filesi searched over the internet almost everywhere but i was not able to correct thisi have installed java se 8u5 jdk windows preferences installed jres showsa jdk cprogram filesjavajdkproject build path libraries showsa jre system library jdkb jre system library jre8please somebody help meedit changing eclipse version from helios to juno solved the problem,['java'] +707869,make a simple fade in animation in swift i am trying to make a simple animation in swift it is a fade ini attemptedselfmyfirstlabelalpha 0selfmyfirstbuttonalpha 0selfmysecondbuttonalpha 0then i haveselfviewaddsubviewmyfirstlabelselfviewaddsubviewmyfirstbuttonselfviewaddsubviewmysecondbuttonand thenuiviewanimatewithduration15 animations selfmyfirstlabelalpha 10 selfmyfirstbuttonalpha 10 selfmysecondbuttonalpha 10i have all of this in my viewdidload functionhow do i make this work,['ios'] +707886,exc bad access error when trying to change bool property i am trying to change a bool property and am receiving an exc bad access errori am using xcode 6 and swiftthe note property saves fine but the completed property throws the exc bad access errorimport foundationimport coredataclass task nsmanagedobject nsmanaged var note string nsmanaged var completed boolchanging out the property routine taskobject is an instance of task set the completed flag taskobjectcompleted true exc bad access,['ios'] +707971,g compiling c11 using wpedantic option is there an option to thisable only the warning about unnamed structs i want to keep any other checks wpedantic does but lose the warning about unnamed structs error iso c prohibits anonymous structs wpedantici want to be able to do the followingunion struct float x y z w struct float r g b a float v4what i have found so fari am using c11 and compiling with the stdc11 flag i have read that c11 supports this feature but i have not seen any mention of it being supported in c11i have come across mention of fmsextensionsin this so question about c for which it is the accepted answerin the gcc documentation for the flags use when compiling c which does not give very many detailsi tried the flag and it does not appear to have any effect no matter the permutation of ordering between fmsextensions and wpedanticedit more detailsthanks to the comments i have found the followingdetails about why unnamed classesstructs are not fully conformant with the standarda post that claims my example code relies on undefined behaviori would still like to know if there is a method of enabling this gcc extension which all compilers i know of have that will thisable the warning or is wpedantic all or nothing,['c++'] +708066,clarifications on xxe vulnerabilities throughout php versions i post a question here as a last resort i have browsed the web and went through many attempts but did not succeedreplicating a xxe attack is what i am trying to do in order to prevent them but i cannot seem to get my head around the way php works with xml entities for the record i am using php 5510 on ubuntu 1204 but i have done some tests on 54 and 53 and libxml2 seem to be of version 278 which does not seem to include the default to not resolving entitiesin the following example calling libxml thisable entity loader with true or false has no effect or i am doing something wrongxml xmlxml version10doctype root entity c public bar etcpasswdroot testtesttest subcsubrootxmllibxml thisable entity loadertruedom new domdocumentdomloadxmlxml prints testprint domtextcontentbut i could specifically pass some arguments to loadxml to allow some options and that works when the entity is a local file not when it is an external urlxml xmlxml version10doctype root entity c public bar etcpasswdroot testtesttest subcsubrootxmldom new domdocumentdomloadxmlxml libxml noent libxml dtdload prints testprint domtextcontentnow if we are changing the entity to something else as in the following example the entity is resolved but i could not thisable it at all using the parameters or function what is happeningxml xmlxml version10doctype root entity c blah blahroot testtesttest subcsubrootxmldom new domdocumentdomloadxmlxml prints testprint domtextcontentthe only way that i could find was to overwrite the properties of the domdocument objectresolveexternals set to 1substituteentities set to 1then they are resolved or notso to summarise i would really like to understand what i am obviously not understanding why do those parameters and function seem to have no effect is libxml2 taking precedence over php many thanksreferences external entity 28xxe29 processing thisable entity loader external entity processinghow can i use phps various xml libraries to get domlike functionality and avoid dos vulnerabilities like billion laughs or quadratic blowup,['php'] +708072,shared library in websphere 7 i am deploying my ear on was 6 having 3 modules in all of those 3 modules there are many jar files it makes my ear heavy to avoid that i want to use shared library wizard of websphere please provide me link or tell me what changes i have to make in my code or resource or any xml filesi am using below link to configure my jars in websphere websphere shared library link 1link 2 link 3thanks in advance,['java'] +708132,how to plot a density map in python i have a txt file containing the xy values of regularly spaced points in a 2d map the 3rd coordinate being the density at that point488281250e004 488281250e004 090722671464843750e003 488281250e004 14051742441406250e003 488281250e004 24328513417968750e003 488281250e004 10141364394531250e003 488281250e004 19913885371093750e003 488281250e004 12788986347656250e003 488281250e004 16369557324218750e003 488281250e004 15045908300781250e003 488281250e004 81463379277343750e003 488281250e004 2738610when i plot this density map in gnuplot with the following commandsset palette rgbformulae 34350set size squareset pm3d mapsplot dens mapmap you 12log10310 title density mapwhich gives me this beautiful image now i would like to have the same result with matplotlib,['python'] +708142,error uploading ios application to itunesconnect failed to open ssh session 16 i am having a real repetitive issue uploading app to itunesconnect it does not matter if i use application loader or xcodes archive utility the result is the same failed to open ssh session 16 i am doing this on a computer and network that was used for multiple uploads of applications to itunesconnect in the past and never having this problem i even uploaded an application the same day without problem but got errors for this app i reviewed the detail log and found nothing useful to determine why the problem would happeni posted the log at link bellow since it is to long to be posted herei am usingjava 160xcode 511apploader 291osx 1093what i tried alreadychecked and rechecked application meta datatried to upload via different networkchanged app bundle identifier develop site itunesconnect and applicationtried contacting support via itunesconnect with no response after multiple daysi thank you for any help you can offer me,['ios'] +708233,correct usages of qopenglfunctions i a currently working on using qt5 gui module to access to opengl functionsthen i thiscover qopenglfunctions which is useful because it wraps opengl for desktop and opengl es making sure i am using the opengl api in a portable wayi do not have to worry about including opengl headers qt does it for meyet i have doubts about a correct way to use itfollowing lines only list the three ways i know about using this classmy question is is there a good way to use qopenglfunctions inheriting from qopenglfunctionsqt official documentation says inherit you class from qopenglfunctions and use glx classes like before but i do not like this way as if my class was expected to inherit from an other class before i have to make multiinheritance something i am not kind of even when such cases are safe anyways it is aestethicsevery glx wrapping classes are nonconst i would force all methods using opengl to be nonconst that does not make a lot of sens yes openglfunctions class can legitimately be nonconst when i do glclear but why my method drawableshaperender would be and about inherinting from qopenglfunctions its constructor may accept an argument the current opengl context this parameter seems very important to me but no qt documentation calls this constructor instead they let the compiler to choose the noparameter constructorhaving qopenglfunctions as memberan other idea should be to have an instance of qopenglfunctions as member of any class calling glx functions or at least a reference to one instance and call every opengl functions from this instancepassing qopenglfunctions as parameterfor each function using opengl the caller send qopenglfunctions this way void renderrectangleqopenglfunctions opengl constbut how could i be sure this function will need it and this one would not i mean the source code will get bigger by the time and i fear the risk of seeing every methods of the classes receiving this parameter,['c++'] +708234,pandas valueerror numpydtype has the wrong size try recompiling i took a new clean install of osx 1093 and installed pip and then didpip install pandaspip install numpyboth installs seemed to be perfectly happy and ran without any errors though there were a zillion warnings when i tried to run a python script with import pandas i got the following error numpydtype has the wrong size try recompiling traceback most recent call last file moenpy line 7 in import pandas file librarypython27sitepackagespandas init py line 6 in from import hashtable tslib lib file numpypxd line 157 in init pandashashtable pandashashtablec22331 valueerror numpydtype has the wrong size try recompilinghow do i fix this error and get pandas to load properly,['python'] +708245,pyvenv34 returned nonzero exit status 1 i am in kubuntu 1404 i want to create a virtualenv with python34 i did with python27 before in other folder but when i trypyvenv34 venvi have goterror command homefmrprojectsavevenvbinpython34 im ensurepip upgrade defaultpip returned nonzero exit status 1,['python'] +708273,cx oracle dll load failed i have a problem importing cx oracle with python i know a lot of issues with cx oracle have been thiscussed here but it seems that i cannot find a solution to my problem after reading all the related topicsi have two machines one is my computer and another one is a remote workstation which have similar configs windows 7 64bits i need to install cx oracle on the remote workstation but it does not work whereas it works fine on my computer i can import the module successfully and connect to my db on the remote workstation i have the following error traceback most recent call lastfile pyshell0 line 1 in module import cx oracleimporterror dll load failed the specified module could not be foundi have doublechecked my environment variables and i reinstalled cx oracle a couple of times but i cannot get it working i did some research about this problem and i am kind of stuck here i do not understand why it is working fine on my computer but not on this remote workstation the only difference is that this remote workstation is a vmdoes anyone have an idea on what could be the issuerunning dependancy walker on both cx oraclepyd on my computer where it works fine and on the remote workstation where cx oracle does not work the only difference are the dll msvcr100 amd msvcr90 which are not found on my remote workstationi have the following environment variables setupcoracle as oracle basecoracleinstantclient 12 1 as oracle home coracleinstantclient 12 1 added to the path variableboth machines are 64bit windows 7i am running python 275 i unzipped instantclientbasicnt121010 in coracleinstantclient 12 1i installed cx oracle51211gwin32py27s on the remote workstation syspath gives me cpython27libidlelib cwindowssystem32python27zip cpython27dlls cpython27lib cpython27libplatwin cpython27liblibtk cpython27 cpython27libsitepackagesedit 1in the previous post all files python 27 cx oracle package oracle instant client were for 32 bit systemsi downloaded the same version of those files for 64 bit systems and everything is working fine on my remote workstation nowedit 2basically the fix consisted for me in reinstalling everything python oracle instant client and cx oracle for 64bit systems instead of 32bit systemsto summarize this was my problem and how it got fixed1 i installed cx oracle from 32bit windows installation package and oracle instant client 32bit and it was working perfectly on my 64bit system running python 275 for 32bit systems2 i did the same thing exactly on a virtual machine running a 64bit system as well and it was not working3 to get it working on the vm i reinstalled everything for 64bit systems python instant client cx oracle and it finally workedalso make sure to download the cx oracle and instant client corresponding to your db version 11g in my casehope this helps,['python'] +708285,unresolvable dependency resolving parameter 0 name warning this question is laravel 4 specifici have been using facades in my controllers before therefore i know the code is working now i need to introduce dependency injection for various reasonsafter refactoring the controller i get following errorilluminate container bindingresolutionexceptionunresolvable dependency resolving parameter 0 name i cannot figure out where the problem is the error message seems cryptic to me and i do not understand it i do not see any problem with my constructor parameters since i have registered the binding for the helpersinterfacehere are the important parts of my codefile appstartglobalphpphp appbindacmeinterfaceshelpersinterface acmeserviceshelpersfile composerjson autoload psr0 acme app file appacmecontrollersbasecontrollerphpphp namespace acmecontrollersuse carboncarbonuse controlleruse illuminatefoundationapplication as appuse illuminateviewfactory as viewuse acmeinterfaceshelpersinterface as helpersuse illuminatehttpresponseclass basecontroller extends controller var illuminatefoundationapplication private app var carboncarbon private carbon var illuminateviewfactory private view var acmeinterfaceshelpersinterface private helpers function constructapp app carbon carbon view view helpers helpers thisapp app thiscarbon carbon thisview view thishelpers helpers lang thisappgetlocale now thiscarbonnow thisviewsharelang lang thisviewsharenow now missing method abort the app and return a 404 response param array parameters return response public function missingmethodparameters array return thishelpersforce404 file appacmeserviceshelpersphpphp namespace acmeservicesuse illuminateconfigrepository as configuse illuminatedatabaseconnection as dbuse illuminatehttprequestuse illuminateroutingredirector as redirectuse illuminatesessionstore as sessionuse illuminatesupportfacadesresponseuse illuminatetranslationtranslator as languse illuminateviewfactory as viewuse acmeinterfacesmockablyinterfaceuse monologlogger as logclass helpers implements helpersinterface public function construct config config lang lang view view mockablyinterface mockably log log request request session session db db redirect redirect response response file appacmeprovidershelpersserviceproviderphpphp namespace acmeprovidersuse illuminatesupportserviceprovideruse acmeserviceshelpersclass helpersserviceprovider extends serviceprovider private dbprivate defaultdbconnectionprotected function init thisdb thisappdb thisdefaultdbconnection thisdbgetdefaultconnectionpublic function register thisinit thisappbindhelpers function return new helpers thisappconfig thisapptranslator thisappview thisappmockably thisappmakeloggetmonolog thisapprequest thisappsessionstore thisdbconnectionthisdefaultdbconnection thisappredirect thisappilluminatesupportfacadesresponse,['php'] +708344,delegate methods in swift for uipickerview just getting started in swift and having trouble calling the delegate methods for a uipickerviewso far i have added the uipickerviewdelegate to my class like soclass exampleclass uiviewcontroller uipickerviewdelegatei have also created my uipickerview and set the delegate for itiboutlet var year uipickerviewyeardelegate selfnow i am just having trouble turning the following into swift code nsintegernumberofcomponentsinpickerviewuipickerview pickerviewany help would be appreciated,"['ios', 'objective-c']" +708386,why is the constant httputf 8 deprecated after upgrading to apache httpclient 42 i found the following constant now deprecatedorgapachehttpprotocolhttputf 8why was this constant deprecated along with others and what is the apache httpclient recommended alternative the a httpcore javadoc here lists it as deprecated but does not recommend an alternative,['java'] +708447,drawing warped text on ios using standard apis available on ios 9 and later how can i achieve a warp effect something like the following image when drawing texthow i would imagine this might work is by specifying essentially four path segments which could be either bazier curves or straight line segments whatever single elements you can normally create within a cgpath or uibezierpath defining the shape of the four edges of the texts bounding boxthis text does not need to be selectable it may as well be an image but i am hoping to find a way to draw it in code so we do not have to have separate images for each of our localizations i would love an answer that uses coregraphics nsstringnsattributedstring drawing additions uikittextkit or even coretext i would just settle on using images before going as far as opengl or metal but that does not mean i wouldnt still accept a good opengl or metal answer if it is literally the only way to do this,['ios'] +708450,how do i create a custom event in an angularjs service i am working on an angularjs project i have a service which sets and removes events on some buttons this service is utilized by another service which i do not want to interact directly with the buttons however i would like a button click event to be filtered up through the first service and handled in the second one since i do not want the second service to be aware of the buttons i figure i will need to create a custom event in the first service how can i create a custom event and fire it when a button is clicked thanks in advance,['javascript'] +708485,scraping data dynamically generated by javascript in html document using c how can i scrape data that are dynamically generated by javascript in html document using cusing webrequest and httpwebresponse in the c library i am able to get the whole html source code as a string but the difficulty is that the data i want is not contained in the source code the data are generated dynamically by javascript on the other hand if the data i want are already in the source code then i am able to get them easily using regular expressionsi have downloaded htmlagilitypack but i do not know if it would take care of the case where items are generated dynamically by javascriptthank you very much,"['c#', 'javascript', 'html']" +708547,cannot edit files after latest resharper update just ran the latest nuget package to update the resharper c files to 82now i am unable to edit any files in visual studio 12is anyone else experiencing this is there a way to resolve this,['c#'] +708675,what is wrong with using arrays dynamically allocated in c like the following code int size mygetsizestdstring foofoo new stdstringsize using the tabledelete fooi heard that such use not this code precisely but dynamic allocation as a whole can be unsafe in some cases and should be used only with raii why,['c++'] +708694,what happens during serialization in java if two object refrences are pointing to the same serializable object what happens during serialization in java if two object refrences are pointing to the same serializable object does the serializable objects get saved twice for example class king implements javaioserializable private string nameakbar class kingdom implements javaioserializable king goodkingnew king king badkinggoodking public class testserialization public static void serializeobjectstring outputfilename object serializableobject throws ioexception fileoutputstream filestreamnew fileoutputstreamoutputfilename objectoutputstream outstreamnew objectoutputstreamfilestream outstreamwriteobjectserializableobject outstreamclose public static void mainstring args kingdom kingdomnew kingdom try testserializationserializeobjectkingdom1out kingdom catchioexception ex exgetmessage now whether only one object state is saved for both goodking and badking refrences or the king object get saved twice,['java'] +708762,android studio debug for doinbackground code of an asynctask i put some break points in my doinbackground code of asynctask class but when i am debugging the application control is not going over doinbackground please help me regarding this,['android'] +708770,is it possible to use swifts enum in objc i am trying to convert some of my objc class to swift and some other objc classes still using enum in that converted class i searched in the prerelease docs and could not find it or maybe i missed it is there a way to use swift enum in objc class or a link to the doc of this issuethis is how i declared my enum in my old objc code and new swift codemy old objc codetypedef ns enumnsinteger someenum someenuma someenumb someenumcinterface someclass nsobjectendmy new swift codeenum someenum nsinteger case a case b case cclass someclass nsobject update from the answers it cannot be done in swift older version than 12 but according to this official swift blog in swift 12 that released along with xcode 63 you can use swift enum in objectivec by adding objc in front of enum,['objective-c'] +708787,resource entry ic launcher already defined can any body plz help he with this issue i want to use this library on my android studio projectput when i put it in my gradle file it shows these errorsinformationgradle tasks appgeneratedebugsourcesinformationresdrawablemdpiv4ic launcherpng0 error resource entry ic launcher is already definedinformationresdrawablemdpiic launcherpng0 originally defined hereinformationresdrawablexhdpiv4ic launcherpng0 error resource entry ic launcher is already definedinformationresdrawablexhdpiic launcherpng0 originally defined hereinformationresdrawablexxhdpiv4ic launcherpng0 error resource entry ic launcher is already definedinformationresdrawablexxhdpiic launcherpng0 originally defined hereinformation1 errorinformation0 warningsinformationsee complete output in consoleerrorexecution failed for task aprocessdebugresources comandroididecommoninternalloggederrorexception failed to run command cusersraziappdatalocalandroidandroidstudiosdkbuildtools1910aaptexe package f nocrunch i cusersraziappdatalocalandroidandroidstudiosdkplatformsandroid19androidjar m cusersraziandroidstudioprojectsallahnamesappbuildmanifestsdebugandroidmanifestxml s cusersraziandroidstudioprojectsallahnamesappbuildresalldebug a cusersraziandroidstudioprojectsallahnamesappbuildassetsdebug m j cusersraziandroidstudioprojectsallahnamesappbuildsourcerdebug f cusersraziandroidstudioprojectsallahnamesappbuildlibsappdebugap debugmode custompackage comuaallahnamesapp outputtextsymbols cusersraziandroidstudioprojectsallahnamesappbuildsymbolsdebugerror code 1output resdrawablemdpiv4ic launcherpng0 error resource entry ic launcher is already defined resdrawablemdpiic launcherpng0 originally defined here resdrawablexhdpiv4ic launcherpng0 error resource entry ic launcher is already defined resdrawablexhdpiic launcherpng0 originally defined here resdrawablexxhdpiv4ic launcherpng0 error resource entry ic launcher is already defined resdrawablexxhdpiic launcherpng0 originally defined hereic launcher already definedwhat could be the errori have tried to change build tools to 1910 but i do not think it is an issuehere is my buildgradle codedependencies compile comandroidsupportappcompatv7 compile comdaimajiasliderlibrary101aar compile filetreedir libs include jar,['android'] +708806,authentication in play 23x i am using the play framework v23 java and i want to add some user authentication to my web app ie usernamepassword for each user and a registration processi found some information on the docs on how to do this for v21 and v22but i cannot find any updated info on v23 i have already tried looking at the api for playmvcsecurityauthenticated but it does not help anyone know how to do this properly,['java'] +708811,how to login with google oauth2 using angularjs inside phonegap using clientid and clientsecret i am trying to login from my phonegap app using angularjs using the ionic framework through google oauth2 currently i am using the for logging in but it is creating really ugly looking code and quite a hard to understand code when i am using angularuirouter for ionic this issue seems to be spiralling around without any proper answers i hope it should be solved now the google angular guys should help how to implement google auth in phonegapthe closest topic is how to use google login api with cordovaphonegap but this is not a solution for angularjsi had to transfer the javascript variable values using the following code var el documentgetelementbyidtest var scopetest angularelementelscope scopetestapplyfunction scopetestuser user scopetestlogged in true scopetestname username scopetestemail useremail,['android'] +708831,security of sending sensitive intent extras within my own app i have an activity which asks for a username and password then starts another activity in my app to complete a user signup i want to send the usernamepassword as intent extras to the second activity something likeintent intent new intentactivity secondactivityclassintentputextrau usernameintentputextrap passwordstartactivityintentand my manifest defines secondactivity likeactivity androidnamecommesecondactivity androidlabel metadata androidnameandroidsupportparent activity androidvaluecommefirstactivity activityand now i am having doubts about the security of sending the usernamepassword as intent extras like this is it possible for another app to intercept the invocation of secondactivity with a spoofed intent filter besides that i wonder what happens with the intent extras are they ever persisted to thisk by the os someone might be able to look at them there if sothanks,['android'] +708838,cgsize sizewithattributes in swift in objectivec i was able to use cgsize stringsize strlocaltelefone sizewithattributesnsfontattributenameuifont systemfontofsize140fbut in swift language i did not found any solution for this situationany help,['ios'] +708867,what is the unit of measurement in xcode this might sound silly but when i am working with sizes in xcode the total frame size is equal to 320 568 width height i am fine with that but the resolution of the phone is actually different the iphone 4s is 640960 the 5 and next generations are 6401136i know the last one is exactly double of what xcode is using as units so my question is what unit of measurement does xcode use if it pixels why not use the phone sizeresolution as reference,['ios'] +708956,angular ngrepeat causes flickering i am thisplaying a list of thumbnails with this codediv class channel ngrepeat channel in uimodelchannels ngclass evenchannel index 2 0 oddchannel index 2 1 img classchannelimg ngsrc datachannelsindex 1thumbdivin the controller i have an ajax request which grabs new thumbnail images angular thus updates the images but causes flickering is there a way to double buffer or not have the list deleted in the process of updating the dom,"['javascript', 'html']" +709185,converting an rpy2 listvector to a python dictionary the natural python equivalent to a named list in r is a dict but rpy2 gives you a listvector objectimport rpy2robjects as robjectsa robjectsrlistfoobarbat fizz123at this point a is a listvector objectlistvector python0x108f92a28 r0x7febcba86ff0strvector floatvector foo class rpy2robjectsvectorsstrvector strvector python0x108f92638 r0x7febce0ae0d8str fizz class rpy2robjectsvectorsfloatvector floatvector python0x10ac38fc8 r0x7febce0ae1081230what i would like to have is something i can treat like a normal python dictionary my temporary hackaround is thisdef as dictvector convert an rpy2 listvector to a python dict result for i name in enumeratevectornames if isinstancevectori robjectslistvector resultname as dictvectori elif lenvectori 1 resultname vectori0 else resultname vectori return resultas dictafoo barbat fizz 1230b robjectsrlistfoolistbar1 batconetwo fizzc123345as dictbfizz floatvector python0x108f7e950 r0x7febcba86b90 1230 3450 foo bar 10 bat strvector python0x108f7edd0 r0x7febcba86ea0 str strso the question is is there a better way or something built into rpy2 that i should be using,['python'] +709190,internal server error with django and uwsgi 2 emperor mode i have been trying to read everything i can find concerning this issue and have learned much while doing so the closest link i could find is here and here my issue is almost identical except i am running uwsgi exclusively in emperor mode when i run uswsgi services without running it in emperor mode my django website runs just fine no matter how i change my configuration i always get the error message my tmpuwsgilog file no python application found check your startup logs for errors i have listed my configuration and error log belowos version linux raspberrypi 3611 538 armv6l gnulinux django version 165 uwsgi version 2051 virtual environment varwtestbedenv project location varwtestbedprojectauth project tree auth init py init pyc requirementstxt settingspy settingspyc urlspy urlspyc wsgipy wsgipycfile wsgipy wsgi config for auth projectit exposes the wsgi callable as a modulelevel variable named applicationfor more information on this file see import os sys site syspathinsert0 ospathabspathospathjoinospathdirname file syspathinsert1 ospathabspathospathjoinospathdirname file syspathappendusrlibpython27 syspathappendusrlibpython27thistpackages osenvironsetdefaultdjango settings module authsettings from djangocorewsgi import get wsgi application application get wsgi applicationfile etcuwsgiemperoriniuwsgimaster trueemperor etcuwsgivassalslogto tmpuwsgilogfile etcuwsgivessalsauthiniuwsgiplugins python djangorelated settingschdir varwtestbedprojectauthmodule authwsgiapplication the virtualenv full pathhome varwtestbedenvvirtualenv varwtestbedenv processrelated settingsenablethreads truepythonpath varwtestbedprojectauthwsgifile varwtestbedprojectauthauthwsgipyenv django settings moduleauthsettingsmount testbedauthadminvarwtestbedprojectauthauthwsgipymanagescriptname truerouterun logscript namescript name maximum number of worker processesprocesses 1 simple rule is of cores on machine the socket use the full path to be safesocket varwtestbedprojectauthuwsgisock with appropriate permissions may be neededchmodsocket 664 clear environment on exitvacuum truelogto tmpuwsgilogcommand being executed listed below varwtestbedenvbinuwsgi ini etcuwsgiemperorini emperor etcuwsgivassals http 80 plugin python binarypathusrlocalbinuwsgierror file tmpuwsgilog starting uwsgi 2051 32bit on tue jun 10 190612 2014 compiled with version 463 on 10 june 2014 014152os linux3611 538 preempt fri aug 30 204208 bst 2013nodename raspberrypimachine armv6lclock source unixdetected number of cpu cores 1current working directory etcuwsgidetected binary path usrlocalbinuwsgi no internal routing support rebuild with pcre support uwsgi running as root you can use uidgidchroot options warning you are running uwsgi as root use the uid flag your processes number limit is 3376your memory page size is 4096 bytesdetected max file descriptor number 1024lock engine pthread robust mutexesthunder lock thisabled you can enable it with thunderlockuwsgi http bound on 80 fd 6 starting uwsgi emperor uwsgi socket 0 bound to tcp address 12700157524 port autoassigned fd 5python version 273 default mar 18 2014 051323 gcc 463 has emperor mode detected fd 8 uwsgi getting ini configuration from authini starting uwsgi 2051 32bit on tue jun 10 190612 2014 compiled with version 463 on 09 june 2014 230700os linux3611 538 preempt fri aug 30 204208 bst 2013nodename raspberrypimachine armv6lclock source unixdetected number of cpu cores 1current working directory etcuwsgivassalsdetected binary path usrlocalbinuwsgi no internal routing support rebuild with pcre support uwsgi running as root you can use uidgidchroot options warning you are running uwsgi as root use the uid flag your processes number limit is 3376your memory page size is 4096 bytesdetected max file descriptor number 1024lock engine pthread robust mutexesthunder lock thisabled you can enable it with thunderlockuwsgi socket 0 bound to unix address varwtestbedprojectauthuwsgisock fd 3python version 273 default mar 18 2014 051323 gcc 463set pythonhome to varwtestbedenv python threads support is thisabled you can enable it with enablethreads python main interpreter initialized at 0x1dca830your server socket listen backlog is limited to 100 connectionsyour mercy for graceful operations on workers is 60 secondsmapped 128512 bytes 125 kb for 1 cores operational mode single process no app loaded going in full dynamic mode uwsgi is running in multiple interpreter mode spawned uwsgi master process pid 23068spawned uwsgi worker 1 pid 23071 cores 1spawned uwsgi http 1 pid 23072python main interpreter initialized at 0x616918python threads support enabledyour server socket listen backlog is limited to 100 connectionsyour mercy for graceful operations on workers is 60 secondsmapped 128512 bytes 125 kb for 1 cores operational mode single process added varwtestbedprojectauth to pythonpathwsgi app 0 mountpoint ready in 2 seconds on interpreter 0x616918 pid 23070 default appmounting varwtestbedprojectauthauthwsgipy on testbedauthadminadded varwtestbedprojectauth to pythonpathwsgi app 1 mountpointtestbedauthadmin ready in 3 seconds on interpreter 0x9c6218 pid 23070 uwsgi is running in multiple interpreter mode spawned uwsgi master process pid 23070tue jun 10 190618 2014 emperor vassal authini has been spawnedspawned uwsgi worker 1 pid 23073 cores 1tue jun 10 190618 2014 emperor vassal authini is ready to accept requests no python application found check your startup logs for errors pid 23071app 1req 11 19216816 38 vars in 742 bytes tue jun 10 190711 2014 get testbedauthadmin generated 21 bytes in 1 msecs http11 500 2 headers in 83 bytes 0 switches on core 0 no python application found check your startup logs for errors pid 23071app 1req 12 19216816 36 vars in 626 bytes tue jun 10 190711 2014 get faviconico generated 21 bytes in 1 msecs http11 500 2 headers in 83 bytes 0 switches on core 0 no python application found check your startup logs for errors pid 23071app 1req 13 19216816 38 vars in 742 bytes tue jun 10 190713 2014 get testbedauthadmin generated 21 bytes in 2 msecs http11 500 2 headers in 83 bytes 0 switches on core 0 no python application found check your startup logs for errors pid 23071app 1req 14 19216816 36 vars in 626 bytes tue jun 10 190713 2014 get faviconico generated 21 bytes in 1 msecs http11 500 2 headers in 83 bytes 0 switches on core 0at this point i am grasping at straws out of all the reading that i have done i cannot see why this keeps rendering the internal server error i may have over looked something that why i have finally given in to my pride by posting my sorrows here since i have gotten this far i really do think that i have overlooked something very small any help would be greatly appreciated,['python'] +709196,pass dynamic javascript variable to djangopython i have looked at a number of answers and other websites but none answer my specific question i have a webpage with and buttons which should increment a variable called piefact this variable must be updated dynamically without having to refresh the page it should then be passed to my django view each time the value is changed this will be used to update the size of pie charts in a web map i have the followingbutton typebutton idbttnminus onclickpiefactpiefact09buttonbutton typebutton idbttnplus onclickpiefactpiefact11buttontd script typetextjavascript var piefact0scripthow can i pass the value of piefact to django based on my limited knowledge i think i may have to use ajax postget,"['javascript', 'jquery', 'python']" +709230,sql clr trigger how to make an assembly trusted due to transparent code call critical code i have dived into researching the sql clr unfortunately my first example has problem with transparent code call to security codethe point is my sql clr trigger is treated as transparent code and in trigger i use quartz to call to quartz windows service var properties new namevaluecollectionpropertiesquartzschedulerinstancename serverschedulerpropertiesquartzschedulerproxy truepropertiesquartzschedulerproxyaddress stringformattcp012 localhost 5 quartzschedulervar schedulerfactory new stdschedulerfactorypropertiesischeduler scheduler schedulerfactorygetschedulererror1351 sql72014 net sqlclient data provider msg 6522 level 16 state 1 procedure aftermarketsessioninserted line 1 a net framework error occurred during execution of userdefined routine or aggregate aftermarketsessioninserted systemmethodaccessexception attempt by security transparent methoddatabasetriggersmarketsessiontriggersaftermarketsessioninsertedto access security critical method quartzimplstdschedulerfactoryctorsystemcollectionsspecializednamevaluecollectionfailedassembly database version10527515169 cultureneutral publickeytokennull is partially trusted which causes the clr to make it entirely security transparent regardless of any transparency annotations in the assembly itself in order to access security critical code this assembly must be fully trusted systemmethodaccessexception at databasetriggersfinancialmarketsessiontriggersafterfinancialmarketsessioninsertedwhy the sql clr trigger code is considered as transparent code and trusted partiallyhow to make sql clr trigger code not a transparent code or make it trusted fullyi am open to suggesstions,['c#'] +709284,chrome and ie return different sha hashes i have written a website that utilizes a sha256 hash to validate a users password this is a relatively unsecure setup to start with as most users will have the same usernamepassword to try and protect it at least a little bit i do the followingthe client requests a new salt from the serverthe client hashes the password with this saltthe client sends the hashed password with the salt back to the serverthe server hashes the actual password and compares the twohere is my codecjust for testingprivate static dictionarystring string users new dictionarystring string user password httpgetpublic httpresponsemessage getsalt rngcryptoserviceprovider securerng new rngcryptoserviceprovider byte saltdata new byte64 securernggetbytessaltdata httpresponsemessage response new httpresponsemessage responsecontent new stringcontentsystemtextencodingunicodegetstringsaltdata systemtextencodingunicode return responsehttpgetpublic bool validateuserstring username string hashedpassword string salt sha256managed hash new sha256managed if userscontainskeyusername string fullpassword salt usersusername byte correcthash hashcomputehashsystemtextencodingutf8getbytesfullpassword if hashedpasswordtoupper bitconvertertostringcorrecthashreplace return true return falsejavascriptscopelogin function httpgetapiloginsuccessfunction salt hash the password with the salt and validate var hashedpassword sjclhashsha256hashsalttostringconcatscopepassword var hashstring sjclcodechexfrombitshashedpassword httpgetapiloginusername scopeusername hashedpassword hashstring salt saltsuccessfunction validated scopeloggedin validated this code works fine on google chrome but not on internet explorer 11 the problem as seen in the debugger is that the hash generated by the javascript is different than that generated by ci suspect this has something to do with character encoding but have not found much on the web to provethisprove this theory or help with the problem in general if there is a better way to accomplish this problem i am happy to hear about it but would like understanding as to the cause of the original error as wellwhy are the hashes different and what can i do to fix it,"['javascript', 'c#']" +709293,postgresql left join json agg ignoreremove null select cid cname json agge as emails from contacts cleft join emails e on cid euser idgroup by cidpostgres 93 creates output for example id name emails 1 ryan id3user id1emailid4user id1email 2 nick nullas i am using a left join there will be cases where there is no righttable match therefore empty null values are substituted for the righttable columns as a result i am getting null as one of the json aggregateshow can i ignoreremove null so i have an empty json array when the righttable column is nullcheers,['sql'] +709328,how to set contentlength in spring mvc rest for json i have some coderequestmappingvalue productsget method requestmethodgetpublic responsebody listproduct getproductsrequestparamrequired true value category id long categoryid some code here return new arraylisthow could i configure spring mvc or mappingjackson2httpmessageconverterclass to set right header contentlength by default because now my response header contentlength equal to 1,['java'] +709364,iframe height auto css i am having problems with my iframe i really want the frame to auto adjust heights according to the content within the iframe i really want to do this via the css without javascript however i will use javascript if i have tooi have tried height 100 and height auto etc i just do not know what else to tryhere is my css for the frameframe position relative overflow hidden width 860px height 100and then for the frames pagewrap float left position absolute overflow hidden width 780px height 100 textalign justify fontsize 16px color 6ba070 letterspacing 3pxthe pages coding looks like thisdoctype html public w3cdtd xhtml 10 transitionalen i12i12 html xmlns xmllangen langenmeta httpequivcontenttype contenttexthtmlcharsetutf8 headmeta httpequivcontenttype contenttexthtml charsetutf8 titletitle link relstylesheet hrefstylecss typetextcss headbody div idcontainer div idheader div div idnavigation a href classnavigationhomea a hrefaboutphp classnavigationabouta a hreffanlistingphp classnavigationfanlistinga a hrefreasonsphp classnavigation100 reasonsa a hrefletterphp classnavigationlettera div div idcontent h1update informationh1 iframe nameframe idframe src allowtransparencytrue frameborder0iframe div div idfooter divdivbodyhtmlplease note that the url within the iframe is different then the website the iframe will be thisplayed on however i have access to both websitescan anyone help,"['html', 'css']" +709377,uninstalling app not delete app group data do i have to remove app group container and it is content manually i created a today extension that is introduced in ios 8 first time to share data between today extension and it is container app i defined an app group and bind them to this group actually i added an embedded framework also to reuse code in both sidedetails of this method is described in apples documenti created some core data model and store it as sqlite on group container then everything works as i thoughthowever when i uninstall container app there are still shared container and it is content on my iphone i think when last member of app group is uninstalled this container should have to be deleted automatically in my case members of app group are shipped with just a single app so uninstalling this app should have to clear shared containeram i wrongps i could not find a way to delete this shared container as an user only developer who has rights to access appgroup can remove this container with programming,['ios'] +709386,casting with interface interface iclass a implements iclass bfirsti arr new a10arr0 i new b will produce classcastexception at runtimesecondwherein if i use concrete classi arr new a10arr0 a new b will produce compiletime errorwhats the difference if in my first examplei new b the java compiler should produce compileerror as wellis not it that the java compiler should be able to thistinguish that it is also an inconvertible type especially when the new operator comes immediatelyis there any instancechance that it will be possible that creating that new instance of b could produce a convertible type of type ii know at some point that the java compiler should not immediately say that it is a compiler error like when you do thisi i i getcontent wherein getcontent will return a type of objecteditlet me clarify this question why it is not a possible duplicate of this cast reference of known type to an interface outside of types hierarchythe intention of this question is not because i am not aware of what will be the result of or what is something wrong with something etc i just want to know a more detailed explanation in a technical way of why does the jvm behave that way or why does java came up with that kind of decision of not making that kind of scenario a compiletime error as what we all know it is always better to find problematic code at compiletime rather than at runtimeanother thing the answer i am looking for was found here on this thread not on those duplicates,['java'] +709459,setuservisiblehint called before oncreateview in fragment i am working on viewpager and using fragment there i found setuservisiblehint called before oncreateview in fragmenti am using fragment from support library androidsupportv4appfragmentis this is a problem with library how can i get rid of it editi override setuservisiblehint and not calling super to get rid of itoverridepublic void setuservisiblehintboolean isvisibletouser fixed setuservisiblehint called before oncreateview in fragment causes nullpointerexception supersetuservisiblehintisvisibletouser,['android'] +709502,interface builder was unable to determine the type of main ipadstoryboard i get the above error when trying to archive my app ready for uploading not sure what it means i first got an error that said the main ipad storyboard was missing so i copied the iphone storyboard and then changes the source to tell it it was an ipad storyboard followed another question on here the code i have highlighted is part of the code i changed i also changed targetruntimeioscocoatouchfollowing this question converting storyboard from iphone to ipadany ideas where i am going wrong,"['ios', 'iphone', 'objective-c']" +709539,adding extra data to django rest framework results for entire result set i am using django rest framework and need to add extra data to a result set specifically where you would usually have count 45 next httplocalhost80foobarpage2 previous null results i would like to add extra counts like so count 45 10 mi count 10 20 mi count 30 30 mi count 45 next httplocalhost80foobarpage2 previous null results the extra counts in this example are just how many of the objects have a field thistance with a value less than the miles described in the keymy issue is that i have no idea where the best place to extend and insert this behaviour isideally i would like this to work whether or not the results are paginated making no assumptionswhat i am really after here is a nod in the right direction and why that is the right place for it goi have checked the docs and cannot find anything that describes how to add things like this but i would be more than happy to be proven wrong on that score,['python'] +709598,increasing the max size of jvisualvm oql resultset i have a memory dump file which has nearly 50 instances of a particular object these objects are to be written into a db and the way i am doing this is to write an oql query in jvisualvm to generate a string that will serve as an sql insert for exampleselect insert into trades id tradenumber values xid xtradenumber from comtestapplicationtradeobject xwhen i run this via oql i get a result set like this codeinsert into trades id tradenumber values 112345 insert into trades id tradenumber values 2123456insert into trades id tradenumber values 3123457 codeetchowever since the total number of instances is large around 50 jvisualvm only shows about 100 of them and then errors out with a message too many results please refine your queryi cannot refine the query as i have to parse all instances this way is there a way in which i can ask jvisualvm to show me all instances and not restrict the number of results i also see that jvisual vm shows the first 100 instances without any filters is it possible to get the next 100 instances and so on via oql querythanks,['java'] +709632,how do i get the x and y positions of an element in an angularjs directive within the link function part of a directive we have access to the element object i wish to determine if the element object is within the current viewport if it is availablei currently have the followinglink function scope element attrs controller var page angularelementwindow pagebindscroll function var windowscroll page0pageyoffset windowheight page0innerheight elementscroll elementxpos this is undefined elementscroll elementgetboundingclientrecttop this does not work undefined elementscroll element0getboundingclientrecttop this does not work undefined logic follows that if elementscroll is between windowscroll windowscroll windowheight it is visible i just cannot seem to get the x and y positions for my specific element the directive may be repeated many times please note that i do not intend to install or use jquery in my application,['javascript'] +709670,carbon in laravel 4 invalidargumentexception unexpected data found trailing data i am trying to get an eloquent query result for dbrawdate formatcreated at mdy r as created at but each time i get this exception from carboninvalidargumentexceptionunexpected data found trailing dataif i change it to just created at instead of employing mysqls date format function then it gets the data without issuei have not only done this sort of date formatting without issue before but i checked every field in the database table there are only 10 for this seed and each is a standard valid date so i am wondering why carbon is pitching a fitrunning this in laravel 41,"['php', 'mysql']" +709694,xcode6swift unrecognized selector sent to instance thought i would try my hand at ios development since the swiftios8 announcement and i am having trouble getting a basic tableview to buildcurrently getting the following error messages when loading the app in the simulator xcode says build completes20140611 134056173 firstapp221785843 uiviewcontroller tableviewnumberofrowsinsection unrecognized selector sent to instance 0xb20fcf020140611 134056180 firstapp221785843 terminating app due to uncaught exception nsinvalidargumentexception reason uiviewcontroller tableviewnumberofrowsinsection unrecognized selector sent to instance 0xb20fcf0 first throw call stack 0 corefoundation 0x00452916 exceptionpreprocess 182 1 libobjcadylib 0x01da28d9 objc exception throw 44 2 corefoundation 0x004596f5 nsobjectnsobject doesnotrecognizeselector 277 3 corefoundation 0x003a4857 forwarding 1047 4 corefoundation 0x003a441e cf forwarding prep 0 14 5 uikit 0x00f149aa uisectionrowdata refreshwithsectiontableviewtableviewrowdata 2767 6 uikit 0x00f18ebc uitableviewrowdata numberofrows 98 7 uikit 0x00d57bb0 uitableview notenumberofrowschanged 133 8 uikit 0x00d57442 uitableview reloaddata 1055 9 uikit 0x00d5b54d uitableview reloaddataifneeded 78 10 uikit 0x00d60ed5 uitableview layoutsubviews 36 11 uikit 0x00cd9223 uiviewcalayerdelegate layoutsublayersoflayer 601 12 libobjcadylib 0x01db5763 nsobject performselectorwithobject 70 13 quartzcore 0x041b87 calayer layoutsublayers 152 14 quartzcore 0x044359e9 zn2ca5layer16layout if neededepns 11transactione 397 15 quartzcore 0x041ace calayer layoutifneeded 160 16 uikit 0x00db72e3 uiviewcontroller windowsetupwithinterfaceorientation 309 17 uikit 0x00ca5a80 uiwindow rotatetoboundswithanimatortransitioncontext 667 18 uikit 0x00ca8388 uiwindow rotatewindowtoorientationupdatestatusbardurationskipcallbacks 2151 19 uikit 0x00caa074 uiwindow setrotatableclienttoorientationapplytransformtowindowupdatestatusbardurationforceisrotating 6723 20 uikit 0x00ca785d uiwindow setrotatableclienttoorientationupdatestatusbardurationforceisrotating 128 21 uikit 0x00ca77d6 uiwindow setrotatableclienttoorientationupdatestatusbardurationforce 84 22 uikit 0x00ca769e uiwindow setrotatablevieworientationupdatestatusbardurationforce 115 23 uikit 0x00ca7729 uiwindow setrotatablevieworientationdurationforce 68 24 uikit 0x00ca66b6 57uiwindow updatetointerfaceorientationdurationforce block invoke 120 25 uikit 0x00ca6624 uiwindow updatetointerfaceorientationdurationforce 406 26 uikit 0x00ca7445 uiwindow setautorotatesforceupdateinterfaceorientation 905 27 uikit 0x00cacb1f uiwindow setdelegate 479 28 uikit 0x00da4177 uiviewcontroller trybecomerootviewcontrollerinwindow 184 29 uikit 0x00c9f69a uiwindow addrootviewcontrollerviewifpossible 683 30 uikit 0x00c9f85c uiwindow sethiddenforced 313 31 uikit 0x00c9fad9 uiwindow orderfrontwithoutmakingkey 49 32 uikit 0x00cae47b uiwindow makekeyandvisible 80 33 uikit 0x00c4fa50 uiapplication callinitializationdelegatesformainscenetransitioncontext 3228 34 uikit 0x00c528a3 uiapplication runwithmainscenetransitioncontextcompletion 1507 35 uikit 0x00c6c335 84uiapplication handleapplicationactivationwithscenetransitioncontextcompletion block invoke 59 36 uikit 0x00c515e3 uiapplication workspacedidendtransaction 29 37 frontboardservices 0x033f42af fbsworkspace clientendtransaction 87 38 frontboardservices 0x033fb71d 53fbsworkspaceclient queue handletransactionbookend block invoke 49 39 corefoundation 0x003772f0 cfrunloop is calling out to a block 16 40 corefoundation 0x0036ba83 cfrunloopdoblocks 195 41 corefoundation 0x0036b1e8 cfrunlooprun 936 42 corefoundation 0x0036ab7b cfrunlooprunspecific 443 43 corefoundation 0x0036a9ab cfrunloopruninmode 123 44 uikit 0x00c50efa uiapplication run 571 45 uikit 0x00c54dee uiapplicationmain 3727 46 firstapp 0x05011 top level code 97 47 firstapp 0x0504b main 43 48 libdylddylib 0x022beac5 start 1 49 0x01 0x0 1libcabidylib terminating with uncaught exception of type nsexceptionlldb i have tried following the stack trace to the method supposedly causing the issue but cannot find anything out of the ordinary currently following a tutorial i have also included my viewcontrollerswiftimport uikitclass viewcontroller uiviewcontroller uitableviewdatasource uitableviewdelegate override func viewdidload superviewdidload do any additional setup after loading the view typically from a nib override func didreceivememorywarning superdidreceivememorywarning thispose of any resources that can be recreated func tableviewtableview uitableview numberofrowsinsection section int int return 10 func tableviewtableview uitableview cellforrowatindexpath indexpath nsindexpath uitableviewcell let cell uitableviewcell uitableviewcellstyle uitableviewcellstylesubtitle reuseidentifier mytestcell celltext row indexpathrow celldetailtextlabeltext subtitle indexpathrow return cell edit including source for mainstoryboardxml version10 encodingutf8 standaloneno document typecomappleinterfacebuilder3cocoatouchstoryboardxib version30 toolsversion615417 systemversion13d65 targetruntimeioscocoatouch propertyaccesscontrolnone initialviewcontrollerclej8gwc dependencies plugin identifiercomappleinterfacebuilderibcocoatouchplugin version615311 dependencies scenes view controller scene sceneid53fxyvbi objects viewcontroller idclej8gwc scenememberidviewcontroller view keyview contentmodescaletofill iduoo215iu rect keyframe x00 y00 width320 height568 autoresizingmask keyautoresizingmask widthsizableyes heightsizableyes subviews tableview clipssubviewsyes contentmodescaletofill alwaysbounceverticalyes datamodeprototypes styleplain separatorstyledefault rowheight44 sectionheaderheight22 sectionfooterheight22 idkl0esoxb rect keyframe x00 y00 width320 height568 autoresizingmask keyautoresizingmask widthsizableyes heightsizableyes color keybackgroundcolor white1 alpha1 colorspacecalibratedwhite connections outlet propertydatasource destinationclej8gwc idhg5yeuoq outlet propertydelegate destinationclej8gwc idi760efpy connections tableview subviews color keybackgroundcolor white1 alpha1 colorspacecalibratedwhite view viewcontroller placeholder placeholderidentifieribfirstresponder idyaazi5eu userlabelfirst responder scenememberidfirstresponder objects point keycanvaslocation x1106 y5620837 scene scenes simulatedmetricscontainer keydefaultsimulatedmetrics simulatedstatusbarmetrics keystatusbar simulatedorientationmetrics keyorientation simulatedscreenmetrics keydestination typeretina4 simulatedmetricscontainer documenti have checked tons of questions regarding the same error and cannot seem to find anything swiftspecific or anything that solves my current issuethanks,['ios'] +709711,how to intercept ajaxrequests within qtwebkit i want to intercept inspect and if needed reject ajaxrequests based on the fingerprint of the sslcertificate i use the qnetworkaccessmanagercreaterequest function to issue requests everything works fine when i use qwebframeload even the content which is loaded within the request like css or js files emit signals unfortunately no ajaxrequests emits any signals i know that the signals are connected to the very same slots for normal as well as ajaxrequests within mynetworkaccessmanagercreaterequest functionqnetworkreply reply qnetworkaccessmanagercreaterequestop req outgoingdataconnectreply signalreadyread this slothandlestartedconnectreply signalsslerrorsconst qlistqsslerror this slothandlesslerrorsconst qlistqsslerror connectreply signalerrorqnetworkreplynetworkerror this slothandlenetworkerrorwhy are ajax requests so different where can i access them,['c++'] +709734,how to wait for a promise to be resolved i am dealing with a nodejs framework that requires a certain function to be synchronous but i need to retrieve a value that can only be accessed asynchronously in a perfect world i would be able to return a promise but i cannotas a quickanddirty solution i created the following methodexportssynchronizepromise functionpromise var value promisethenfunctionpromisevalue value promisevalue while value wait for promise to resolve consolelogdone value never reached return valuebut i get an error is there any way to accomplish what i need,['javascript'] +709778,swift creating an array of uiimage using swift i am trying to create an array of uiimage objects for a simple animation contextual help for animationimages reads the array must contain ui image objectsi have tried to create said array as follows but cannot seem to get the syntax correctvar logoimages uiimagelogoimages0 uiimagename logopngthis throws variable logoimages used before being initializedthen i triedvar logoimages logoimages0 uiimagenamed logopngwhich throws cannot assign to the result of this expressioni have checked the docs here but the context is not the same programming languagecollectiontypeshtmlthx for your help,['ios'] +709816,cmake is not able to find boost libraries i tried everything like configure environment variable make fresh buildreinstall boost from source sudo aptget install libboostalldevbut still getting following errorscmake error at usrsharecmake28modulesfindboostcmake1131 message unable to find the requested boost libraries unable to find the boost header files please set boost root to the root directory containing boost or boost includedir to the directory containing boosts headerscall stack most recent call first cmakeliststxt147 find packagecmake error at usrsharecmake28modulesfindboostcmake1131 messageunable to find the requested boost librariesunable to find the boost header files please set boost root to the rootdirectory containing boost or boost includedir to the directory containingboosts headerssource code directory for boost usrlocalsrcboost 1 45 0boost library path usrlocallibboost header file usrlocalincludeboosthere is bashrc fileboost rootusrlocalsrcboost 1 45 0boost library dirsusrlocallibboost includedirusrlocalsrcboost 1 45 0how to solve these errors am i missing somethingeditcmake dcmake toolchain fileandtoolchain dboost rootusrlocalsrcboost 1 45 0 dboost includedirusrlocalincludeboost dboost librarydirusrlocallib dpython librariesusrlocallibpython27 dpython include dirsusrincludepython27 dcmadrdk build python wrappers,['c++'] +709988,programmatically create sqlite db if it does not exist i am trying to create an sqlite db programmatically if it does not exist i have written the following code but i am getting an exception at the last lineif systemiofileexistscusersabcdesktop1syncsqlite consolewritelinejust entered to create sync db sqliteconnectioncreatefilecusersabcdesktop1syncsqlite string sql create table highscores name varchar20 score int sqlitecommand command new sqlitecommandsql sqlite2 commandexecutenonquerysqlite2 new sqliteconnectiondata sourcecusersabcdesktop1syncsqlitei get the exception at the line commandexecutenonquery the exception is invalid operation exception was unhandled is there any other way to add an sqlite file to your project can i do it manually if not then how can i solve the above issue,"['c#', '.net']" +710039,js launches before css this is currently happening in chrome in firefox i have not had this issue yethere is a very simplified version of my problemhtmldiv classthumbnail a href idclickmeclick meadivcssdiv width 200px height 300px backgroundcolor purplea position absolutemedia maxwidth 991px div height 200px javascriptdocumentreadyfunction var parent clickmeparent function resize clickmeoffset top parentoffsettop parentheightclickmeheight windowonresize resize resizethe problemso what does this give when i resize without dragging well javascript launches first and sets the position of the aa then css applies the height change if we are 992 px logically the button is now visually at the outside of the div and not on the border like i had originally defined it to betemporary solution proposed in this post jquery how to wait for the end or resize event and only then perform an actionvar doit windowonresize function cleartimeoutdoit doit settimeoutresize 500 temporary solution is not what i am looking forhowever in my situation i do not really need to only call resize when the resizing event is actually done i just want my javascript to run after the css is finished loading or finished with it is changes and it just feels super slow using that function to randomely run the js when the css might be finishedthe questionis there a solution to this anyone know of a technique in js to wait till css is completely done applying the modifications during a resizeadditional informationtesting this in jsfiddle will most likely not give you the same outcome as i my css file has many lines and iam using twitter bootstrap these two take up a lot of ressources slowing down the css application i think tell me if i am wrongmiljan puzovia proposed a solution by loading css files via js and then apply js changes when the js event on css ends,"['javascript', 'jquery', 'css']" +710146,in javascript how to wrap a promise in timeout it is a common pattern to implement timeout of some asynchronous function using defferedpromise create a deferred and return its promisefunction timeoutfunct args time var dfd new jquerydeferred execute asynchronous code functapplynull args when the asynchronous code is completed resolve the deferred dfdresolvesuccess settimeoutfunction dfdrejectsorry time return dfdpromisenow we can execute some asynchronous function called myfunc and handle timeout attach a done and fail handler for the asynceventwhen timeoutmyfunc some args 10 then functionstatus alert status things are going well functionstatus alert status you fail this time ok let us make a twist in this story imagine that the myfunc itself returns a promise note promise not deferred and i cannot change itfunction myfunc var dfd new jquerydeffered superimportantlibrarydosomethingfunctiondata ifdatalength 5 dfdrejecttoo few data else dfdresolvesuccess error callback function dfdrejectthere was something wrong but it was not timeout return dfdpromisenow if i wrap myfunc in timeout i will loose the ability to handle errors different then timeout if myfunc emit progress events i will loose this as wellso the question is how to modify timeout function so it can accept functions returning promises without loosing their errorsprogress information,"['javascript', 'jquery']" +710199,sse code runs 30 faster yet when in use show over 20 cpu increase i am attempting to optimise a routine used in vlc that converts nv12 frame into a yv12 framefor background information nv12 is identical to yv12 with the exception that the you and v chroma plane are interleavedso to convert one format into another it is simply a matter of deinterleaving a channel likeuvuvuvuvuvuvubecomesuvthe routine i am attempting to improve is this oneablobfmodulesvideo chromacopychd29843c037e494170f0d6bc976bea8439dd6115bhbheadl286now the primary issue with this routine is that it requires a 16bytes aligned memory cache as intermediary storageso the routine first deinterleave the data into the cache 4kib max and then copy the result found in the cache back into the destination framei have rewritten this function so it does not require the use of a cache using sse23 instructions working on unaligned memory when required and instructions using aligned memory when possiblethe code is as followstatic void sse splitplanesuint8 t dstu size t dstu pitch uint8 t dstv size t dstv pitch const uint8 t src size t src pitch uint8 t cache size t cache size unsigned width unsigned height unsigned cpu vlc unusedcache vlc unusedcache size const uint8 t shuffle 0 2 4 6 8 10 12 14 1 3 5 7 9 11 13 15 const uint8 t mask 0xff 0x00 0xff 0x00 0xff 0x00 0xff 0x00 0xff 0x00 0xff 0x00 0xff 0x00 0xff 0x00 const bool aligned uintptr tsrc 0xf 0 asm volatile mfencedefine load64a movdqa 0src xmm0n movdqa 16src xmm1n movdqa 32src xmm2n movdqa 48src xmm3ndefine load64u movdqu 0src xmm0n movdqu 16src xmm1n movdqu 32src xmm2n movdqu 48src xmm3ndefine store2x32 movq xmm0 0dst1n movq xmm1 8dst1n movhpd xmm0 0dst2n movhpd xmm1 8dst2n movq xmm2 16dst1n movq xmm3 24dst1n movhpd xmm2 16dst2n movhpd xmm3 24dst2n if aligned for unsigned y 0 y height y unsigned x 0ifdef can compile se3 if vlc cpu se3 for x 0 x width 31 x 32 asm volatile movdqu shuffle xmm7n load64a pshufb xmm7 xmm0n pshufb xmm7 xmm1n pshufb xmm7 xmm2n pshufb xmm7 xmm3n store2x32 dst1rdstux dst2rdstvx srcrsrc2x shufflershuffle memory xmm0 xmm1 xmm2 xmm3 xmm7 elseendif for x 0 x width 31 x 32 asm volatile movdqu mask xmm7n load64a movdqa xmm0 xmm4n movdqa xmm1 xmm5n movdqa xmm2 xmm6n psrlw 8 xmm0n psrlw 8 xmm1n pand xmm7 xmm4n pand xmm7 xmm5n pand xmm7 xmm6n packuswb xmm4 xmm0n packuswb xmm5 xmm1n pand xmm3 xmm7n psrlw 8 xmm2n psrlw 8 xmm3n packuswb xmm6 xmm2n packuswb xmm7 xmm3n store2x32 dst2rdstux dst1rdstvx srcrsrc2x maskrmask memory xmm0 xmm1 xmm2 xmm3 xmm4 xmm5 xmm6 xmm7 for x width x dstux src2x0 dstvx src2x1 src src pitch dstu dstu pitch dstv dstv pitch else for unsigned y 0 y height y unsigned x 0ifdef can compile se3 if vlc cpu se3 for x 0 x width 31 x 32 asm volatile movdqu shuffle xmm7n load64u pshufb xmm7 xmm0n pshufb xmm7 xmm1n pshufb xmm7 xmm2n pshufb xmm7 xmm3n store2x32 dst1rdstux dst2rdstvx srcrsrc2x shufflershuffle memory xmm0 xmm1 xmm2 xmm3 xmm7 elseendif for x 0 x width 31 x 32 asm volatile movdqu mask xmm7n load64u movdqu xmm0 xmm4n movdqu xmm1 xmm5n movdqu xmm2 xmm6n psrlw 8 xmm0n psrlw 8 xmm1n pand xmm7 xmm4n pand xmm7 xmm5n pand xmm7 xmm6n packuswb xmm4 xmm0n packuswb xmm5 xmm1n pand xmm3 xmm7n psrlw 8 xmm2n psrlw 8 xmm3n packuswb xmm6 xmm2n packuswb xmm7 xmm3n store2x32 dst2rdstux dst1rdstvx srcrsrc2x maskrmask memory xmm0 xmm1 xmm2 xmm3 xmm4 xmm5 xmm6 xmm7 for x width x dstux src2x0 dstvx src2x1 src src pitch dstu dstu pitch dstv dstv pitch undef store2x32undef load64uundef load64anow benchmarking this function alone it runs around 26 faster on an i72600 cpu ivybridge 34ghz a little faster on an i74650u haswell 17ghz with a 30 speed increase over the original functionwhich was expected as you go from 2 reads 2 writes to 1 read 1 writehowever when used within vlc the function is used to thisplay every frame decoded via intel vaapi interface the cpu usage for the same video jumps from 20 to 3234so i am puzzled why that would be and how could that be resolvedi had expected an opposite resultboth routines use sse23 one runs faster yet cause increase cpu usagethanks,['c'] +710273,how to access fragments child views inside fragments parent activity i have a supported fragment activity which will load diff fragments the fragment has some textview with id score and i want to get its handle but findviewbyid for scores textview returns null why sotextview is placed in fragmentpublic class myactivity extends extends actionbaractivity implements navigationdrawerfragmentnavigationdrawercallbacks private textview scoreboardtextview null protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity home mnavigationdrawerfragment navigationdrawerfragment getsupportfragmentmanagerfindfragmentbyidridnavigation drawer scoreboardtextview textview findviewbyidridscore this returns null override public void onnavigationdraweritemselectedint position set fragment,['android'] +710332,browserify and document ready i am struggling with using browserify and document ready events how do i craft a module that exports content only available after the document ready event has fired how do i depend on such a modulemy first stab was to try to set moduleexports asynchronously fail out of the box my nextx stab at this was for the module to return a function that took in a callback and called the callback when document ready fired third attempt returned a promise this seems to make dependent modules not very modular as now dependent modules and their dependencies and theirs turtles all the way down must also leverage this patternwhats a good pattern for using browserify and document ready events,['javascript'] +710368,why can s xappends can be passed as an action but xappend cannot i noticed something strange when trying to pass a stringbuilders append method to a function that took an actionstringpublic void dostuffactionstring handler do stuff call handlerdatafor testing purposes i just want to write the data into a stringbuilder so i tried to call it like thisvar output new stringbuilderdostuffoutputappendhowever this gives a compile error because the append method does not match the required signature it returns a reference back to the stringbuilder not void as my method wantssystemtextstringbuilder systemtextstringbuilderappendstring has the wrong return typewithout thinking i changed the code to thisvar output new stringbuilderdostuffs outputappendsthis compiled finethen i got confused realising that s outputappends should also return the stringbuilder are not they the sameso why does this work why can s outputappends have the return value thiscarded silently yet outputappend cannot,"['c#', '.net']" +710492,null propagation operator and dynamic variable i have been looking at the nullpropagation operator in c6 and tried to make it work with the variables of dynamic type but without successconsider the code below it compiles but clr throws accessviolationexception at runtime when the nullpropagation is applied to dynamic object class sometype public object someproperty get set static void main var obj new sometype someproperty abcd var p1 dynamicobjsomeproperty ok p1 is set to abcd var p2 dynamicobjsomeproperty accessviolationexception consolereadline at first i thought that this might be a bug but then i thought about structs normally you cannot apply operator to a value type variable because it cannot be null but you can cast it to dynamic and then apply the operator so i changed sometype to be struct and got the same exception the question is it is by design that nullpropagation for dynamic variables always is going to throw exception because the underlying object may be a value typethe accessviolationexception is pretty ugly anyway do you get the same one when you run the code,['c#'] +710511,how to add an action to a uialertview button using swift ios i want to add another button other than the ok button which should just thismiss the alerti want the other button to call a certain functionvar loginerroralert uialertview uialertviewloginerroralerttitle opsloginerroralertmessage unable to log inloginerroralertaddbuttonwithtitleokhow do i add another button to this alert and then allow it to call a function once clicks so lets say we want the new button to call retry,['ios'] +710555,nsdata from byte array in swift i am trying to create an nsdata var from an array of bytesin objc i might have done this nsdata endmarker nsdata alloc initwithbytes 0xff 0xd9 length 2i cannot figure out a working equivalent in swift,['ios'] +710590,css image maxwidth set to original image size can you do this i am having users upload images into a container that is width100 but i do not want the images to be larger than their original size many thanks,['css'] +710598,pycharm import external library i am using pycharm as an editor for python code in houdini whenever i try to import the main houdini library hou i get an error flagged in pycharm if i include the code snippettry import hou except importerror add hfshoudinipython26libs to syspath so python can find the hou module syspathappendosenvironhfs houdinipythonddlibs sysversion info2 import hou my code executes without problem from both houdini and my selected interpretermy problem is with pycharm itself the editor flags import hou as an error and any subsequent files that import this file flag modules imported by this file as errors as well hence i loose type ahead functionality and get an over abundance of error messages that make it hard to spot the real problemshow do i get pycharm to recognize the path to the hou modulei have tried for a couple of days to google a solution to this problem but they all seem to refer to tabs and settings that are not in my version of pycharm community edition 341 eg my project interpreter setting only has a list of packages and has no path tab as stated in many fixes to closely related problems,['python'] +710731,what does in a numpy type string mean many of the examples of dtype strings in the numpy documentation feature a leading character for example s10 near the top of the structured arrays page in the numpy manual but neither the structured arrays page nor the data type objects reference seem to explain what this means what does mean in this context and where is this documented,['python'] +710734,jquery scroller needs to stop scrolling after reaching end iam using a scroller in one of my website when i click the down arrow to scroll the scroller to the end 10 pm reached again if i clicked down arrow the scroller again moves up and whole content thisappears i want to stop the down arrows working if the end time here 10 pm reachedsame problem occurs in case clicking of up arrow we tried to solve this but did not succeedjsfiddle link image attatchedthanks in advance,"['javascript', 'jquery', 'html', 'css']" +710779,generate reset password link in webapi i wanted to generate a reset password link to send to the users email that will open the resetpassword page on this page i will fill in the details regarding the new password and then confirm the passwordfor this i have followed this linkbut there is a urlaction method that i am not able to find in my web api projectvar callbackurl urlaction confirmemail account new userid userid code code protocol requesturlschemehase anybody done the reset password part in the web api i need some help,['asp.net'] +710781,where are magentos log files located i am new to magento i cannot find log files in magento i googled it but the magento commerce site returns closed and some other sites explain how to create custom log files i want to know the location of builtin log files,['php'] +710788,angularjs requirejs and ngroute i am building an address book to learn angular and have it working nicely until i try to use the route manager the issue is with loading the angular route manager via require i am getting the following error uncaught objectthere have been questions about this but they have been removed by the user and other answers point to not having included the ngroute dependancy in the ngmodule dependancy list or are not using require at all i am not having much luck finding an answeri have the an html file that includes a require config filerequirejsconfig paths jquery ajaxgoogleapiscomajaxlibsjquery200jquerymin angular ajaxgoogleapiscomajaxlibsangularjs1216angularminangular 1216min angularroute ajaxgoogleapiscomajaxlibsangularjs1216angularrouteminangularroute 1216min shim jquery exports jquery angular exports angular angularroute exports ngroute deps angular baseurl jslibrequiremodulescontactsmod function and this is the contactsmodjs file called at the end of the config filedefinejquery angularrouteangularcontrollerscontactsctrlroutescontactsroutfunctionngroutengcontrollerrouter var contactsapp ngmodulecontactsapp ngroute contactsappconfigfunction routeprovider locationprovider logdebug configuring routeprovider locationproviderhtml5modetrue routeprovider when templateurl viewscontactshtml controller controller otherwise redirectto var contactsapp ngmodulecontactsapp contactsappcontrollercontroller ngbootstrapdocument contactsappthe commented out section is the part i am trying to figure out the above version works but when i try to add the ngroute dependancy to the ngmodule call in the commented out part i get the error mentionedi can see that all the assets have been loaded before the module is called but i can also see that the ngroute logs out as undefined so it makes sense that it does not work i have tried a number of different config variants like including the angularroute as a dependancy of angular which give the same error plus another of uncaught typeerror cannot read property module of undefinedi can see there is a seed app that uses custom async loader instead of require what do you recommend i do not know how to debug this problem any help or pointers appreciated,['javascript'] +710792,why does free in c not take the number of bytes to be freed just to be clear i do know that malloc and free are implemented in the c library which usually allocates chunks of memory from the os and does its own management to parcel out smaller lots of memory to the application and keeps track of the number of bytes allocated this question is not how does free know how much to freerather i want to know why free was made this way in the first place being a lowlevel language i think it would be perfectly reasonable to ask a c programmer to keep track not only of what memory was allocated but how much in fact i commonly find that i end up keeping track of the number of bytes malloced anyway it also occurs to me that explicitly giving the number of bytes to free might allow for some performance optimisations eg an allocator that has separate pools for different allocation sizes would be able to determine which pool to free from just by looking at the input arguments and there would be less space overhead overallso in short why were malloc and free created such that they are required to internally keep track of the number of bytes allocated is it just a historical accidenta small edita few people have provided points like what if you free a different amount than what you allocated my imagined api could simply require one to free exactly the number of bytes allocated freeing more or less could simply be ub or implementation defined i do not want to thiscourage thiscussion about other possibilities though,['c'] +710807,swift thread 1 signal sigabrt after upgrading xcode from 5 to 6 beta almost every project gives me an unexpected error after running the application there are some other posts with this title but the error is differentin appdelegateswift sometimes the simulator goes completely black without the error sometimes it gives me the error on this line class appdelegate uiresponder uiapplicationdelegate in xcode 5 i did not had this error before with deployment target set to 70 or 71thanks in advance,['ios'] +710834,implement stripe payment gateway in cordovaphonegap application searched a lot i want to integrate stripe payment gateway in my cordova application is there any way to achieve it in android and ios using javascript,"['javascript', 'android', 'ios']" +710944,how to suppress specific lint warning for deprecated android function i use a version switch to support older android versionsint sdk buildversionsdk intif sdk buildversion codeshoneycomb colordrawable colordrawable new colordrawableshapecolor noinspection deprecation viewholdershapesetbackgrounddrawablecolordrawable else viewholdershapesetcolorshapecolorwhen build the project with gradle from the command line the following warning is output by lintappsrcmainjavacomexamplemyappcustomlistadapterjava92 warning deprecation setbackgrounddrawabledrawable in view has been deprecated viewholdershapesetbackgrounddrawablecolordrawable can i annotate the specific line or method to mute the warning since i do it on purpose i do not want to thisable all warnings,['android'] +710947,how can i have a beforeall function in jasmine not coffeescript i need to know if there is a way to include or use a beforeall function or something similar so i can login to my application and then start testingright now i am putting my login operations in the first test case it which is not a good practiceif there is a better way to store my login code other then using a beforeall function please tell me about iti am using pure jasmine not related to any other framework like coffeescript or othersthank you,['javascript'] +711000,html elements following each other along svg path with javascript i am trying get a few html elements to follow each other along a svg path i would like them to stay the same thistance apart as they go around the path i would also like the svg image to scale to the container that holds iti have created a codepen that demonstrates what i have so farthe problem i am having is that when the elements move along the x axis they seem to get further apart than they do on the y axisis there a way to make them stay the same thistance as they travel along the linethanksupdateafter some further fiddling i have thiscovered that the thistance variation seems to be caused by the aspect ratio of the svg viewbox being increased for x greater than it is for y when it is stretched along the x axis 1px down the line may become 3px on the screenthe position of the red squares is being set by moving them in front and behind by half the width of the black box when traveling along the line if the viewbox aspect ratio is changed the thistance between each point on the line increase or decreases based off of thisi have tried creating a similar svg with the exact viewbox of the size of the container div and the red dots are exactly on the ends of the black box all the way down the line this does not solve problem because i would like the svg with the line to scale to any size container it is placed insidei think if there is a way to calculate how many pixels the size of the black box is in relation to how many pixels down the line it covers the red dots would line up exactlyany ideas how to accomplish this or any ideas on a better way to approach this problem,"['javascript', 'html']" +711024,replacing variables in i18next i have implemented i18next and after getting help on a couple of issues all works finei still have issues understanding parts of the documentation on the support sitei am trying to replicate this part found here given resources enus translation key myvar are important i18ntkey myvar variables variables are importanton my side of things this is the json file app name mytranslation back back cancel cancel closemenu close menu closeoptions close options currency currency symbol is currencysymbol date date description descriptionand the htmlbody div datai18ncurrencydiv script srcjavascripti18next173minjsscript script languagejavascript typetextjavascript i18ninit preload en fr ht es de zh vi pt it th dev i18ninit detectlngqs lang i18ninitfunctiont bodyi18n var appname tappname i18ntcurrency currencysymbol where do i place this code scriptbodynote jquery 211 and jquery mobile 142 are loaded in the headeri am sure i am not placing the various parts where they are supposed to go as it is not working not inserting the variable currencysymbol the rest of the code works fine as i get all the translated textwhat i would really like to achieve is to be able to create variables that would be called as part of the translations currency symbol company name company address etc for affiliates purposes and be able to replace those values as they are repeated in the translated textsi would like to have those variables in one place so they are easy to adjust and they will not be subject to the context of language changes,['jquery'] +711037,reduce blank space between bar button items in uinavigationbar i notice the blank space between bar button items is quite large i want to reduce the space to have more room for my title i tried to create fixed space then added it among the buttons but it did not work does anybody know how to do ituibarbuttonitem fixeditem uibarbuttonitem alloc initwithbarbuttonsystemitemuibarbuttonsystemitemfixedspace targetnil actionnil fixeditemwidth 100fselfnavigationitemrightbarbuttonitems settingsbuttonitem fixeditem speakerbuttonitem fixeditem favouritebuttonitem,['ios'] +711127,timestamp not null default current timestamp can be null on one machine but not another i have a mysql table with a field defined ascreated timestamp not null default current timestampon my local machine i can runinsert into mytbl id user id created values82341234 765 nullselect id user id created from mytbl where id 82341234and then created will show something like 20140613 211642but on my staging server if i run the same queries i get this errorcolumn created cannot be nullthe schemas of the tables are the same across local and staging which i ensured via mysqldump to clone the table before running this testi am running mysql 5617 on both machines i have also ensured that both have the same sql modewhat could be the problemps for people who do not know why i would be setting a nonnullable fields value to null mysql docs say in addition you can initialize or update any timestamp column to the current date and time by assigning it a null value unless it has been defined with the null attribute to permit null values,['mysql'] +711151,entity framework an error occurred while updating the entries see the inner exception for details i have problem i have just started learning ef model first and im staying in one point for some time i got such error an error occurred while updating the entries see the inner exception for detailsi have created an easy model on diagram generated the database and wrote easy code in c to add just one row in the table but the error is showing up all the timei post screenshot with diagramgenerated dllsimple mainand error throwinglink for bigger size,['c#'] +711301,reset ios app badge hi i am currently developing an app which uses push notification i have successfully got it to work with parse and my application is receiving the notifications my question is not how to reset the badge when i open the application because i already got that working with this code voidapplicationdidbecomeactiveuiapplication applicationuiapplication sharedapplicationapplicationiconbadgenumber 0 voidapplicationuiapplication applicationdidregisterforremotenotificationswithdevicetokennsdata devicetoken store the devicetoken in the current installation and save it to parsepfinstallation currentinstallation pfinstallation currentinstallationcurrentinstallation setdevicetokenfromdatadevicetokencurrentinstallation saveinbackground voidapplicationuiapplication applicationdidreceiveremotenotificationnsdictionary userinfo pfpush handlepushuserinfothat code removes the badge from the application but when i send another notification the number is now 2 instead of 1 how can i fix this,['ios'] +711399,passing data between view controllers in swift i am trying to convert an app from objectivec to swift but i cannot find how to pass data between views using swift my objectivec code isuistoryboard storyboard uistoryboard storyboardwithnamemain bundlenilansviewcontroller ansviewcontrolleransviewcontroller storyboard instantiateviewcontrollerwithidentifieransviewansviewcontrollernum thenumself presentviewcontrolleransviewcontroller animatedyes completionnilwhat that is doing is it basically takes the variable thenum and passes it to the variable num on a different view controller i know this may be an easy question but i am getting pretty confused with swift so if someone could explain how they changed it to swift that would be greatly appreciatedthanks,['ios'] +711490,what is causing this invalid toplevel expression error in my gulp gulpfilejs file i get an error after i start gulp i have taken out all other plugins to find problemgulpsass source string1 error invalid toplevel expressiongulpfilejsvar gulp requiregulpvar sass requiregulpsassgulptasksass function gulpsrcappassetssastylessass pipesass errlogtoconsole true pipegulpdestpublic htmlassetscssgulptaskdefault sass function gulpwatchappassetssasass sasswindows 7,['javascript'] +711549,constant value not changing when recompiling referenced assembly i have this code in an assemblypublic class class1 public const int x 10and in a different assembly i haveclass program static void mainstring args consolewritelineclass1x consolereadkey of course the output was 10 but then i changed x to 20public class class1 public const int x 20i recompiled the assembly and moved it to my command line programs bin directory however the output of my program was still 10 until i compiled assembly containing the main functionwhy is this happening,"['c#', '.net']" +711570,how to use dockerpy official docker client to start a bash shell i am trying to use dockerpy to run a docker container and drop me into a bash shell in that container i get as far as running the container i can see it with docker ps and i can attach to it just fine with the native docker client but when i use attach from the official python library it just gives me an empty string in response how do i attach to my bash shell import docker c dockerclient container ccreate containerimaged11wtqpython277 commandbinbash stdin opentrue ttytrue namedockertest containeruid udd87e4ec75496d8369e0e526f343492f7903a0a45042d312b37859a81e575303 uwarnings none cstartcontainer cattachcontainer,['python'] +711602,why variadic function cannot eat the listinitialization argument in c11 the sample code isinclude unordered mapint main stdunordered mapint stdpairint int map mapemplace1 1 1 return 0where the emplace has signature liketemplate class argspairiterator bool emplace args argsthe gcc says that function expectes 0 arguments 2 provided the clang says that function expects 1 argument 2 providedi do not even understand what the problem is with this code,['c++'] +711606,replacing spaces with 20 in java string url origindestinationsdestinationmodedrivingsensorfalselanguageenenunitsimperialurl urlreplaceall 20output destinations120palmer20sq20eprinceton20nj2008542modedrivingsensorfalselanguageenenunitsimperialbut i am getting an error saying javanetmalformedurlexception illegal character in urlcan some one help me out,['java'] +711619,c libraries installation on mac osx i have recently switched from windows to mac i was told that xcode has the cc librariesgcc included apparently the new xcode 5 does not have them as ide i have codeblocks downloaded how do i install the libraries for codeblocks in mac,['c'] +711650,how to make an ordered list with twitter bootstrap component i have a simple ordered list super easylooks like thisdiv classcontainer div classrow div classcolxs12 ol classlistgroup li classlistgroupitem plorem ipsum dolor sit amet consectetur adipisicing elit vitae aliquidp li li classlistgroupitem pquos nostrum provident ex quisquam aliquid hic odio repellendus atquep li li classlistgroupitem pfacilis id dolorum thistinctio harum accusantium atque explicabo quidem consecteturp li ol div divdivbut twitter bootstrap is not showing any numbers even though it is an ordered listi searched but did not find any twitter bootstrap compontent that styles ordered list items and this makes me curious is there a lacking in a predefined style for twitter bootstrap for ordered lists or am i missing somethingkind regardsgeorge,"['html', 'css']" +711674,loadingdownloading image from url on swift i would like to load an image from a url in my application so i first tried with objectivec and it worked however with swift i have a compilation error imagewithdata is unavailable use object construction uiimagedatamy function iboutlet var imageview uiimageviewoverride func viewdidload superviewdidload var urlnsurl nsurlurlwithstringhttpmyurlios8png var datansdata nsdatadatawithcontentsofurlurl options nil error nil imageviewimage uiimageimagewithdatadata error herein objectivec voidviewdidload super viewdidload nsurl url nsurl urlwithstringhttpmyurlios8png nsdata data nsdata datawithcontentsofurlurl imageviewimage uiimage imagewithdata data labelurltext s20styleios8png can someone please explain me why the imagewithdata does not work with swift and how can i solve the problem,['ios'] +711728,iphone would not connect in xcode 6 beta i updated both ios 8 and xcode 6 beta when i connect my phone it shows up as ineligible device where you select which platform you want to run on when i try to run the project on my actual iphone an error message in xcode appears that saysan error was encountered while enabling development on this device if anyone knows how i can fix this i would much appreciate it because i have not found much info on this error message,"['ios', 'iphone']" +711762,how to execute an azure table storage query async client version 401 want to execute queries async on azure storage client version 401there is no method executequeryasynci am missing something should we continue to use the executequerysegmentedasync still thanks,['c#'] +711768,stdmake shared with stdinitializer list include iostreaminclude memoryclass basepublic base class derived public basepublic derived derivedstdinitializer liststdpairint stdshared ptrbase int mainint argc char argv auto example new derived 0 stdmake sharedderived return 0it works live preview normally but when i try to use stdmake shared with the stdinitializer list as argument i got errorsauto example new derived 0 stdmake sharedderived 0 stdmake sharedderived as you can see here on the live previewerror too many arguments to functionit works only when i do this live previewauto example new derived 0 stdmake sharedderivedstdinitializer liststdpairint stdshared ptrbase 0 stdmake sharedderived what i want to know is why it works only when i pass the stdinitializer list as argument on stdmake shared instead of using just like thisauto example new derived 0 stdmake sharedbase is that possible to make stdmake shared accept itthanks in advance,['c++'] +711788,when to use custom directive vs uiview vs nginclude in an angularjs application i am building a large complex angularjs application think erp system i am having a hard time deciding when it is appropriate to use uiview nginclude or a custom directive templateurl i will give a few concrete examples to give yall something to work witha navigation menu that is used across all urls of the application but includes a complex ajax autosuggestdropdown search boxa simple html footer that is the same across all urls of the applicationthe content areas that go in between the header and footerthe individual components that are nestled within the content area such as and edit profile form or user dashboard modal dialogswhat are the best practices,['javascript'] +711910,gradle unexpected toplevel exception out of nowhere fairly certain gradle is out for me started a project that has been working fine just a few days ago updated android studio and opened the project again i have tried everything i can come up with from removingupdating libraries checking xmlfiles and structure removing gradle cache and installing latest jdk nothing seems to help herealso tried to addconfigurations allexclude group comandroidsupport module supportv4refered in other posts on stackoverflowi exported the error from the console and it looks like thisobjc2338 class javalaunchhelper is implemented in both libraryjavajavavirtualmachinesjdk180 05jdkcontentshomebinjava and libraryjavajavavirtualmachinesjdk180 05jdkcontentshomejreliblibinstrumentdylib one of the two will be used which one is undefinedunexpected toplevel exceptionjavalangillegalargumentexception method id not in 0 0xf 65536 at comandroiddxmergedexmerger6updateindexdexmergerjava501 at comandroiddxmergedexmergeridmergermergesorteddexmergerjava276 at comandroiddxmergedexmergermergemethodidsdexmergerjava490 at comandroiddxmergedexmergermergedexesdexmergerjava167 at comandroiddxmergedexmergermergedexmergerjava188 at comandroiddxcommanddexermainmergelibrarydexbuffersmainjava439 at comandroiddxcommanddexermainrunmonodexmainjava287 at comandroiddxcommanddexermainrunmainjava230 at comandroiddxcommanddexermainmainmainjava199 at comandroiddxcommandmainmainmainjava103derpdexderpdebug failedfailure build failed with an exception what went wrongexecution failed for task derpdexderpdebug comandroididecommoninternalloggederrorexception failed to run command applicationsandroid studioappsdkbuildtools1910dx dex numthreads4 output usersmorepathstuforalongwhile error code 2 output objc2338 class javalaunchhelper is implemented in both libraryjavajavavirtualmachinesjdk180 05jdkcontentshomebinjava and libraryjavajavavirtualmachinesjdk180 05jdkcontentshomejreliblibinstrumentdylib one of the two will be used which one is undefined,['android'] +712000,c11 implicitly convert include stringstruct string templatetypename t operator t return 0 operator stdstring return int main string mystr stdstring str1mystr ambiguous error c2668 stdstring str2 mystr error c2440 initializing cannot convert from string to stdbasic stringcharstdchar traitscharstdallocatorchar no constructor could take the source type or constructor overload resolution was ambiguous const stdstring rstr mystr ok but whyi am using vs 2013questionswhy do the definitions of str1 and str2 lead to different compile errorsas i know when rstr is created a temporary string object is created firstly then rstr will refer to the temporary but why does the creation of the temporary object not lead a compile error is there any different between tmp and strn,['c++'] +712043,handling api exceptions in rxjava i am trying to wrap my head around rxjava currently but i am having a little trouble with handling service call exceptions in an elegant mannerbasically i have a retrofit service that returns an observableserviceresponse serviceresponse is defined like sopublic class serviceresponse private int status private string message private jsonelement data public jsonelement getdata return data public int getstatus return status public string getmessage return message now what i want is to map that generic response to a listaccount contained within the data jsonelement field i assume you do not care what the account object looks like so i would not pollute the post with it the following code works really well for the success case but i cannot find a nice way to handle my api exceptionsservicegetaccounts subscribeonschedulersio observeonandroidschedulersmainthread mapnew func1serviceresponse accountdata override public accountdata callserviceresponse serviceresponse todo ick fix this there must be a better way responsetypes responsetype responsetypesfromserviceresponsegetstatus switch responsetype case success gson gson new gsonbuildercreate return gsonfromjsonserviceresponsegetdata accountdataclass case host unavailable throw new hostunavailableexceptionserviceresponsegetmessage case suspended user throw new suspendeduserexceptionserviceresponsegetmessage case system error case unknown default throw new systemerrorexceptionserviceresponsegetmessage mapnew func1accountdata listaccount override public listaccount callaccountdata accountdata gson gson new gsonbuildercreate listaccount res new arraylistaccount for jsonelement account accountdatagetaccounts resaddgsonfromjsonaccount accountclass return res subscribeaccountsrequestis there a better way to do this this does work onerror will fire to my observer and i will receive the error that i threw but it definitely does not seem like i am doing this rightthanks in advanceeditlet me clarify exactly what i want to achievei want to have a class that can be called from the ui eg an activity or fragment or whatever that class would take an observerlistaccount as a parameter like sopublic subscription loadaccountsobserverlistaccount observer boolean forcerefresh that method would return a subscription that can be unsubscribed when the ui is detacheddestroyedetcthe parameterized observer would handle onnext for the successful responses passing in a list of accounts onerror would handle any exceptions but would also get passed any api exceptions eg if the response status 200 we would create a throwable and pass it to onerror ideally i do not want to just throw the exception i want to pass it directly to the observer that is what all the examples i see dothe complication is that my retrofit service returns a serviceresponse object so my observer cannot subscribe to that the best i have come up with is to create an observer wrapper around my observer like sosingletonpublic class accountsdatabase private accountsservice service private listaccount accountscache null private publishsubjectserviceresponse accountsrequest null inject public accountsdatabaseaccountsservice service thisservice service public subscription loadaccountsobserverlistaccount observer boolean forcerefresh observerwrapper observerwrapper new observerwrapperobserver if accountscache null we have a cached value emit it immediately observeronnextaccountscache if accountsrequest null there is an inflight network request for this section already join it return accountsrequestsubscribeobserverwrapper if accountscache null forcerefresh we had a cached value and do not want to force a refresh on the data just return an empty subscription observeroncompleted return subscriptionsempty accountsrequest publishsubjectcreate accountsrequestsubscribenew observerwrappernew endobserverlistaccount override public void onnextlistaccount accounts accountscache accounts override public void onend accountsrequest null subscription subscription accountsrequestsubscribeobserverwrapper servicegetaccounts subscribeonschedulersio observeonandroidschedulersmainthread subscribeaccountsrequest return subscription static class observerwrapper implements observerserviceresponse private observerlistaccount observer public observerwrapperobserverlistaccount observer thisobserver observer override public void oncompleted observeroncompleted override public void onerrorthrowable e observeronerrore override public void onnextserviceresponse serviceresponse responsetypes responsetype responsetypesfromserviceresponsegetstatus switch responsetype case success gson gson new gsonbuildercreate accountdata accountdata gsonfromjsonserviceresponsegetdata accountdataclass listaccount res new arraylist for jsonelement account accountdatagetaccounts resaddgsonfromjsonaccount accountclass observeronnextres observeroncompleted break default observeronerrornew apiexceptionserviceresponsegetmessage responsetype break i still feel like i am not using this correctly though i definitely have not seen anyone else using an observerwrapper before perhaps i should not be using rxjava though the guys at soundcloud and netflix really sold me on it in their presentations and i am pretty eager to learn it,['android'] +712046,python 34 randomchoice on enum i would like to use randomchoice on an enumi tried class fooenum a 0 b 1 c 2bar randomchoicefoobut this code is not working how can i do that,['python'] +712069,capistrano 3 sshkitrunnerexecuteerror exception while executing on host hostname agent could not sign data with requested identity i am getting the following error while deploying my rails app to an ubuntu server i have correctly setup ssh keys and i can ssh to the server but i am getting the following when i try to do cap production deploythis is the error messagecap abortedsshkitrunnerexecuteerror exception while executing on host x agent could not sign data with requested identityi cannot figure out what i am doing wrong since i had previously deployed and i just need to update my app to changes i have made i have not changed my deployrb capfile or deployproductionrb files since i last deployed,['ruby-on-rails'] +712141,uirouter lazy load state using url i am trying to see if i can use uirouter to delegate setting of state to my apps subcomponents by implementing lazy loading of the states while i managed to get the lazy loading part to work using statego or equivalent i cannot get it to work using the urlfor example on launch my app will only setup the following 2 states view1 and view2 when view1 state is loaded it then setup it is own children states of view1profile and view1interest take a look at this sample site from gistas you will see from the example above view1profile is not a valid link on launch but if you click on it it will load view1 and then load view1profile with resulting urlhowever if you click on the generated url above the app reloads and no longer knows about view1profile and redirect you back to home any recommendation on how i can address this more specifically is there anyway i can get the url to trigger statenotfound eventperhaps the answer is in part of their cryptic documentation on how to lazy load states i was not able to figure out what they mean byhow to set the retry promise on the eventhow to define the unfoundstate using stored provider and resolve the promise,['javascript'] +712164,find elements inside forms and iframe using java and selenium webdriver i am trying to access elements that are present under form iframe form elements form iframe formcould you help me on accessing these elements which i am working with selenium webdriver and javaissue encountered able to reach the destination page where the above elements are present but those elements are not recognized with my codeoverview of xml structurebody form actionhttpsabcdefgh nameouterform methodpost targetiframetitle iframe width700 height600 src titleframe for java test nameiframetitle scrollingauto frameborder0 form idinnerformid nameinnerform actionxyz methodpost autocompleteoff fieldset idncdetailsinner div idelement1 label forlabel1 abbr titlerequired fieldabbrlabel input namelabel2 typetext maxlength30 idcardholder value div div idelement2 label forlabel3label3 abbr titlerequired fieldabbrlabel div idelement3 label forlabel4label4abbr titlerequired fieldabbrlabel input idlabel5 namelabelname5 typetext maxlength19 value div div idelement4 label forlabel6label6label input idlabel7 namelabelname7 typetext size2 maxlength2 value classtext thisabled thisabled div div fieldset form iframe formbodycode extractwebdriverwait wait iframe new webdriverwaitdriver 20wait iframeuntilexpectedconditionsvisibilityofelementlocatedbyidelement2calling functionsh1getcellcol 10 rowgetcontents sh1getcellcol 11 rowgetcontents sh1getcellcol 12 rowgetcontents sh1getcellcol 14 rowgetcontents public static void called funcitonstring string1 string string2 string string3 string string4 driverfindelementbynameelement1 namesendkeysstring1 driverfindelementbyidelement2 idsendkeysstring2 driverfindelementbyidelement3 idsendkeysstring3 driverfindelementbyidelement4 idsendkeysstring4 driverfindelementbynamesubmitbuttonclick do let me know if require any further details,['java'] +712281,how to add contact in android like skype whatsapp in native contact app i am creating a contact app but want to add contacts in the native android contact app from my app just like skype or whatsapp what class would i need to extend to implement this functionalityhere is the picture of exactly what i want to create,"['java', 'android']" +712282,write device platform specific code in xamarinforms i have the following xamarinformscontentpage class structurepublic class mypage contentpage public mypage do work to initialize mypage public void loginobject sender eventargs eventargs bool isauthenticated false string accesstoken stringempty do work to use authentication api to validate users ifisauthenticated i would to write device specific code to write to the access token to the device example of saving the access token to ios device nsuserdefaultsstandarduserdefaultssetstringaccesstoken accesstoken example of saving the access token to android device var prefs applicationcontextgetsharedpreferencesmysharedprefs filecreationmodeprivate var prefseditor prefsedit prefeditorputstringaccesstoken accesstoken prefeditorcommit i would like to write platform specific code in the mypage login method to save the access token based on which device os they are using my application onhow do i only run device specific code when the user uses my application on their device,['c#'] +712369,canonical way of starting multiple nested activities and getting a result onactivityresult i have the following requirementactivity a activity b open gallery apptraditionally i launch nested activities using the taskstackbuilder so i would do something like this taskstackbuilder tsb taskstackbuildercreatethis intent activityintenta new intentthis activityaclass tsbaddnextintentactivityintenta intent activityintentb new intentthis activitybclass tsbaddnextintentactivityintentb intent galleryintent new intentintentaction pick galleryintentsettypeimage tsbaddnextintentgalleryintent thisstartactivitiesnew intent activityintenta activityintentb galleryintent tsbstartactivitiesa side question is if there is a difference between using a task stack builder or the startactivities callthe problem with this approach though is that when the galleryintent is closed it does not call onactivityresult but rather calls the oncreate method of activityb which means i lose the information coming in from the gallery app which is supplied through the intent param data on my onactivityresult call of activityban alternative solution would be to manually kick off the calls so call first call activity b then with a flagparamargument launch the galleryintent and then follow the regular flow through with onactivityresultis there a better approach to solving this requirement,['android'] +712388,strange generics behaviour being erased early i ran into some strange behaviour of java generics today the following code compiles fine and works as you would expectimport javautilpublic class testgeneric public static void mainstring args genericclassinteger generic new genericclassinteger7 string stringfromlist genericgetstringlistget0 static class genericclassa private a obja private liststring stringlist genericclassa obja thisobja obja stringlist new arrayliststring stringlistadda string stringlistaddanother string a getobja return obja liststring getstringlist return stringlist but if you change the type of the variable generic to genericclass note no type parameters compilation fails with the message incompatible types javalangobject cannot be converted to javalangstringthis issue seems to happen with any generic class that contains a generic object with a concrete type parameter a few google searches have not turned up anything and the jls mentions nothing about this scenario am i doing something wrong or is this a bug in javac,['java'] +712411,swift nsdate formatting with strftime localtime how do i convert the following objectivec code into swift codedefine max size 11char buffermax sizetime t time nsdate date timeintervalsince1970strftimebuffer max size lmu2008p localtimetimensstring datestring nsstring stringwithutf8stringbuffernslogdatestring datestring datestring 1156apmi am formatting a date,"['objective-c', 'c']" +712420,failed on using swift to implement inapp email i want to use swift to implement inapp email when i click the button the email window pops up however i am unable to send my email moreover after i click canceldelete draft i cannot go back to the original screenimport uikitimport messageuiclass information uiviewcontroller mfmailcomposeviewcontrollerdelegate var mymail mfmailcomposeviewcontroller ibaction func sendreportsender anyobject ifmfmailcomposeviewcontrollercansendmail mymail mfmailcomposeviewcontroller mymailmailcomposedelegate set the subject mymailsetsubjectmy report to recipients var torecipients mymailsettorecipientstorecipients cc recipients var ccrecipients mymailsetccrecipientsccrecipients cc recipients var bccrecipients mymailsetbccrecipientsccrecipients add some text to the message body var sentfrom email sent from my app mymailsetmessagebodysentfrom ishtml true include an attachment var image uiimagenamed gimmepng var imagedata uiimagejpegrepresentationimage 10 mymailaddattachmentdataimagedata mimetype imagejped filename image thisplay the view controller selfpresentviewcontrollermymail animated true completion nil else var alert uialertcontrollertitle alert message your device cannot send emails preferredstyle uialertcontrollerstylealert alertaddactionuialertactiontitle ok style uialertactionstyledefault handler nil selfpresentviewcontrolleralert animated true completion nil func mailcomposecontrollercontroller mfmailcomposeviewcontroller didfinishwithresult result mfmailcomposeresult error nserror switchresultvalue case mfmailcomposeresultsentvalue printlnemail sent default printlnwhoops selfthismissviewcontrolleranimatedtrue completion nil,['ios'] +712586,how to check with intel intrinsics if avx extensions is supported by the cpu i am writing a program using intel intrinsics i want to use mm permute pd intrinsic which is only available on cpus with avx for cpus without avx i can use mm shuffle pd but according to the specs it is much slower than mm permute pd do the header files for intel intrinsics define constants that allow me to thistinguish whether avx is supported so that i can write sth like thisifdef is avx supported is there sth like this defined use mm permute pd else use mm shuffle pdendif i have found this tutorial which shows how to perform a runtime check but i need to do a static compiletime check for the current machine,['c'] +712590,large images from file not loading in picasso no obvious error seen i am writing an app which gets a list of the images from the gallery on a device and then shows them in a gridview in my adapter i have the following code where the width and height are those of the view it will be placed inpicassosingletonwithmcontextloadfile imageuriresizegetimagewidth getimageheightcenterinsideplaceholderrdrawableimage placeholdererrorrdrawableimage errorintoholderimageon most devices this works really well however on some devices where the photos taken are very large such as the samsung galaxy s5 16mp some images do not load and the error resource is thisplayed i do not see any obvious log messages from picasso debugging only the followingdpicasso20171 main errored r7501msi presume this is due to memory issues but i am not sure how to go about fixing these is it possible to tell picasso to compress the images or is there something else i am missingthanks,['android'] +712602,performance drop upgrading from hazelcast 25 to 3 because of a known fixed bug in hazelcast 25 weve decided this would be the next upgrade candidate for our project but after dropping in the latest version 322 we had horrible performancethe way we are using hazelcasttwo nodesmultiple imap instances about 7 maps in totalboth nodes update the mapsa lot of reads on the mapsnearcache enabled to speed up readsusing hazelcast 25 we had great performance when instead of using mapvalues we supplied a list of all contained keys mapgetallcontainedkeys the way we keep track of the containedkeys by adding an entrylistener to the map which stores the containedkeys in a concurrent set this was added by a colleague and feels like a hack but works like a charmnow when we upgrade to hazelcast 322 we instantly see problems with javaio for example look at the following snippet from appdynamicscomhazelcastmapproxymapproxyimplgetall326 method time 0 ms total time 18938 ms comhazelcastmapproxymapproxysupportgetallobjectinternal495 method time 0 ms total time 18938 ms comhazelcastmapmapservicetoobject852 method time 0 ms total time 18938 ms comhazelcastspiimplnodeengineimpltoobject156 method time 0 ms total time 18938 ms comhazelcastnioserializationserializationserviceimpltoobject221 method time 0 ms total time 18938 ms comhazelcastnioserializationstreamserializeradapterread59 method time 0 ms total time 18938 ms comhazelcastnioserializationdefaultserializersobjectserializerread185 method time 0 ms total time 18938 ms javaioobjectinputstreamreadobject370 method time 3398 ms total time 18938 ms javaioobjectinputstreamreadobject370 method time 15540 ms total time 15540 msthis is something we have not seen in hazelcast 25 but do have in 322 it grinds our application to a complete standstill replacing the jar with 25 again and renaming entry back to mapentry and nothing is wrong what could be causing this maybe it is not using the nearcache anymore,['java'] +712732,identity insert during seeding with entityframework 6 codefirst i have an entity that has an autoidentity int column as part of the dataseed i want to use specific identifier values for the standard data in my system after that i want to have the database to sort out the id valueso far i have been able to set the identity insert to on as part of the insert batch but entity framework does not generate an insert statement that include the id this makes sense as the model thinks the database should provide the value but in this case i want to provide the valuemodel pseudo codepublic class referencething key databasegenerateddatabasegeneratedoptionidentity public int idgetset public string namegetsetpublic class seeder public void seed dbcontext context var mything new referencething id 1 name thing with id 1 contextsetreferencethingaddmything contextdatabaseconnectionopen contextdatabaseexecutesqlcommandset identity insert referencething on contextsavechanges generates sql insert statement but without id column value contextdatabaseexecutesqlcommandset identity insert referencething off anyone able to offer any insight or suggestions,['c#'] +712765,uipageviewcontroller didfinishanimating not called if swiped quickly i have a uipageviewcontroller that works as expected i can scroll left and right and the delegate method didfinishanimating is called when i scroll each direction however if i scroll too quickly i end up on a page where didfinishanimating is not called though it is called for all previous pages does anyone know why this might be happeningi would think that didfinishanimating would be called on every page transition regardless eg even if the turn was aborted,"['ios', 'objective-c']" +712848,how to convert errors on to rspec 3 syntax i recently upgraded from rspec 299 to rspec 3 this would be one of my specsrequire spec helper describe user type model do it is invalid without a password do expectfactorygirlbuilduser password nilerrors onpasswordsizeto eq1 end endendi already ran the transpec gem that is supposed to convert most of my specs to rspec 3 syntax however i am still getting this error and a few others failureerror expectfactorygirlbuilduser password nilerrors onpasswordsizeto eq1 nomethoderror undefined method errors on for user0x0108beaba0i tried to rewrite the test in a number of different ways but the error would not go awaycan anybody help,['ruby-on-rails'] +712980,get first element of series without have information on index is that any way that i can get first element of seires without have information on indexfor examplewe have a series import pandas as pd keymcs096 subjectspddataframeidseries146index145 studyseriesmcsindex145 centerseriesmagindex145 initialsseriesmcs096index145 prints out subjects print subjectssubjectsinitialskeyid 145 146 name id dtype int64how can i get the value here 146 without using index 145thank you very much,['python'] +713013,calculating evenly spaced points on the perimeter of a circle the math behind this question has been asked numerous times so that is not specifically what i am after rather i am trying to program the equation for determining these points into a loop in javascript so that i can thisplay points the evenly around the circle so with the equations for the x and y positions of the points pointx r costheta centerx pointy r sintheta centeryi should be able to calculate it with thisvar centerx 300var centery 175var radius 100var numberofpoints 8var theta 360numberofpointsfor var i 1 i numberofpoints i pointx radius mathcostheta i centerx pointy radius mathsintheta i centery draw point pointx pointy and it should give me the xy coordinates along the perimeter for 8 points spread 45a from each other but this does not work and i am not understanding whythis is the output that i get using the html5 canvas element the points should reside on the innermost red circle as that one has a incorrect when it should look like this although this is with just 1 point placed manuallycorrect could someone help me out it is been years since i took trig but even with looking at other examples from various languages i do not see why this is not workingupdate figured it outi did not need to add the centerx and centery to each calculation because in my code those points were already relative to the center of the circle so while the canvas center was at point 300 175 all points were relative to the circle that i created and so the center for them was at 0 0 i removed this from the code and split the theta and angle calculations into two variables for better readability and voilatotalpoints 8for var i 1 i totalpoints i drawpoint100 i totalpointsfunction drawpointr currentpoint totalpoints var theta mathpi2 totalpoints var angle theta currentpoint electronpivotx 100 mathcosangle electronpivoty 100 mathsinangle return electroncorrect,['javascript'] +713067,xctestxctesth not found on old projects built in xcode 6 i have a few projects i am trying to build with xcode 6 beta 2 the projects all have some type of library that uses xctest kiwixctest and specta that do not build in xcode 6 because xctestxctesth cannot be foundfatal error xctestxctesth file not foundimport xctestxctesthi noticed that xctestframework is no longer in the link libraries with binaries build phase list but that is fine because when i create a new project with xcode 6 it appears the library is linked in automaticallyperhaps of some relevency my xctestneeding dependencies are all brought in via cocoapodsis there anything i am unaware of that i need to update with my project,['ios'] +713140,amazon rds restore snapshot to existing instance i have created a snapshot of my instance and made some unwanted changes in dbnow i want to restore my instance from this snapshotwhen i try to do it it creates me one more instance additionally to the one i havei specify db instance identifier and after that i get two instances with the same idso my question is there any way to restore snapshot to existing instancebecause in other case new instance is created with differrent endpoint hostname and i need to change my configs to access database or there is a better way to manage such cases,['mysql'] +713183,what happens when we pass int arguments to the overloading method having float as a parameter for one method and another having double param in overloading concept i am having one doubt that is when i comes to overload the method with int value the method calls the float parameter method rather the double parameter methodvoid method1float fsystemoutprintlnfloatvoid method1double fsystemoutprintlndoublemethod callmethod110output floatas stated in the java tutorials in this link a floatingpoint literal is of type float if it ends with the letter f or f otherwise its type is double and it can optionally end with the letter d or dfor the above case the method call should call the double parameter method but it calls float parameter methodhow the process of overloading taking place in this area,['java'] +713217,why do we need the glob clause in sqlite i am an android developer and recently came across the glob clause in sqlite i cannot understand why we need glob given that like is already in placeboth clauses have wildcards to represent single and multiple characters the only difference is that glob is case sensitive but is that all are there any queries where like is a bad or inappropriate choice are there any cases where we absolutely have to use globe vs like or vice versa,['sql'] +713289,nested relations with sequelize i am using sequelize with node mysqli have a model structure similar to this modelsvar group issue invite many issues per groupgrouphasmanyissueissuebelongstogroup groups can invite other groups to work on their issuesissuehasmanyinvite foreignkey groupidinvitebelongstoissue foreignkey groupidgrouphasmanyinvite foreignkey inviteeidinvitebelongstogroup foreignkey inviteeid given an issue id include all invites invited groups inviteeid but howvar query where id include issuefindquerycompletefunctionerr issue var invites issueinvites var firstinvitedgroup issueinvites0group is this at all possible what are possible workarounds thank you,"['javascript', 'mysql']" +713369,bootstrap css height of listgroupitem please consider follow jsfiddleas you might notice the listgroupitem is fully collapsed and i cannot seem to make it autoadjust eg heightautoyet when i supply the css ruleheight20px then the row size is adjustedhow can i make the height of an listgroupitem to adjust to size of the contentthank you for your time,"['html', 'css']" +713375,how do i put a bootstrap glyphicon inside an aspbutton in aspnet i am using bootstrap 3 in my project and i want to use bootstrap glyphicons in aspnet buttonshere is the code i used though it did not work out i got a sample which uses twitter bootstrap span tags instead of i tagsaspbutton idbtnrandom runatserver textspan ariahiddentrue classglyphicon glyphiconrefresh span onclickbtnrandom click maybe something extra should be donehow can i get it to work thanks in advance for the replies,"['html', 'asp.net']" +713466,safest way to get the invoke methodinfo from actions instance i am currently working on an extension method that facilitates what the questions title suggestsi could of course use the getmetohdinvoke method call on the type and be done with itbut something tells me this is not the safest way to goclasses and types may change including those in the bclso i have come up with the following linq statement which works just fine public static class actionextensions public static methodinfo getinvoketthis actiont obj var actiontype objgettype var ttype typeoft return from methodinfo in actiontypegetmethods let par methodinfogetparameters where parlength 1 par0parametertype ttype select methodinfo firstordefault the thing is even this feels somewhat iffy since one day action can change and contain another method with such traits even if i add the hasgenericparameters constraint there is no assurance of safetydo you have any ideas regarding a way to obtain the exact methodinfo instance relevant to actiontinvoke,['c#'] +713496,why we should not use protected static in java i was going through this question is there a way to override class variables in javathe first comment with 36 upvotes wasif you ever see a protected static runcan anyone explain why is a protected static frowned upon,['java'] +713503,java ternary operator influence on generics type inference public liststring foo1 liststring retval bar if retval null return collectionsemptylist else return retvalpublic liststring foo2 liststring retval bar return retval null collectionsemptylist retvalwhy does foo1 compiles fine whereas foo2 has an error to be more precise type mismatch cannot convert from listcapture1of extends object to liststringi would have thought that both functions would compile to the same bytecode so a clever compiler should infer the correct type for emptylist,['java'] +713506,gradle version 110 is required current version is 20 i am trying to use latest gradle version 20 however i keep getting this message when hitting gradle build in terminal why is it asking for 110 version i am new to gradle so i am trying to get my head around itgradle version 110 is required current version is 20here are my dependencies module buildgradle filedependencies classpath comandroidtoolsbuildgradle012 classpath filetreedir buildlibs include jarand wrapper tasktask wrappertype wrapper gradleversion 20also i have set the thistribution url as follows in the localproperties filethistributionurlthe final thing is that in filesettingsgradle i selected use customizable gradle wrappergradle home is set to cprogram files x86gradlegradle20the buildgradle filebuildscript repositories mavenlocal mavencentral dependencies classpath comandroidtoolsbuildgradle012 classpath filetreedir buildlibs include jar task wrappertype wrapper gradleversion 20update1as it stands i am using this android studio 110 with 110rc1 plugin version dependencies classpath comandroidtoolsbuildgradle110rc1gradle version is 23 in gradlewrapperpropertiesthistributionurli have tried plugin version 110 but then it complains about comandroidapplicationupdate 012016as it stands i am using gradle 29 thistribution in gradle wrapper gradlewrapperpropertiesthistributionurland plugin isclasspath comandroidtoolsbuildgradle150,['android'] +713545,trywithresources are not supported at this language level android i have a problem with trywithresources are not supported at this language level in android in the following posted code i tried to set language to 7 but it stills keeps giving me the same example plus it keeps giving me the option to change to language 7public string readfilestring filename try bufferedreader br new bufferedreadernew filereaderfilenametxt stringbuilder sb new stringbuilder string line brreadline while line null sbappendline sbappendsystemlineseparator line brreadline string everything sbtostring return everything catch filenotfoundexception ex loggergetloggersavenloadrankclassgetnameloglevelsevere null ex catch ioexception ex loggergetloggersavenloadrankclassgetnameloglevelsevere null ex return 1,['android'] +713643,svg why does external css override inline style for text i am playing with using an svg gradientfill as a way to visually truncate long text strings in a d3js chartit seems that an external css style for fill will override the inline gradient fill style in the svg is that always the case how can i enforce that gradient fillin this test case i have defined a linear gradient in the svg defs and then apply the gradient fill to two groups of text var labelcolwidth 200var svg d3selecttestappendsvg attrwidth 500 attrheight 500var defs svgappendsvgdefsvar textgradient defsappendsvglineargradient attrgradientunits userspaceonuse attrx1 0attry1 0attrx2 40attry2 0 attrid thegradient attrgradienttransform translate labelcolwidth 40 textgradientappendsvgstopattroffset 0attrstyle stopcolorrgb0stopopacity1 textgradientappendsvgstopattroffset 100attrstyle stopcolorrgb0stopopacity0var data 0 xyzzy xyzzy 1 xyzzy xyzzy xyzzy xyzzy xyzzy 2 xyzzy xyzzy xyzzy xyzzy xyzzy xyzzy 3 xyzzy xyzzy xyzzy 4 xyzzy xyzzy 5 xyzzy xyzzy xyzzy xyzzy xyzzy xyzzy xyzzy xyzzy xyzzy xyzzyvar testgroup svgappendg attrtransform translate50 100var testgroup2 svgappendg attrtransform translate50 250 attrclass group2testgroupselectalltextdatadata enterappendsvgtext attrfill urlthegradient attrx 0 attry functiond i return i1 20 textfunctiond i return d1 testgroup2selectalltextdatadata enterappendsvgtext attrfill urlthegradient attrx 0 attry functiond i return i1 20 textfunctiond i return d1 then in css i define a fill for group2 textgroup2 text fill 0the first group has the gradient fill the second group does not should not the inline style take precedence thanks,['css'] +713717,generate javadoc error android studio for some reason i cannot generate a javadoc with android studio after like 96 warnings it gives me this95 warningsjavalangnullpointerexceptionat comsuntoolsjavadoctypemakergettypetypemakerjava83at comsuntoolsjavadoctypemakergettypetypemakerjava44at comsuntoolsjavadocclassdocimplsuperclasstypeclassdocimpljava496at comsuntoolsdocletsinternaltoolkitutilutilgetallinterfacesutiljava453at comsuntoolsdocletsinternaltoolkitutilutilgetallinterfacesutiljava491at comsuntoolsdocletsinternaltoolkitutilclasstreeprocesstypeclasstreejava194at comsuntoolsdocletsinternaltoolkitutilclasstreebuildtreeclasstreejava146at comsuntoolsdocletsinternaltoolkitutilclasstreeinitclasstreejava91at comsuntoolsdocletsinternaltoolkitabstractdocletstartgenerationabstractdocletjava123at comsuntoolsdocletsinternaltoolkitabstractdocletstartabstractdocletjava83at comsuntoolsdocletsformatshtmlhtmldocletstarthtmldocletjava63at comsuntoolsdocletsstandardstandardstartstandardjava39at sunreflectnativemethodaccessorimplinvoke0native methodat sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava57at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43at javalangreflectmethodinvokemethodjava601at comsuntoolsjavadocdocletinvokerinvokedocletinvokerjava280at comsuntoolsjavadocdocletinvokerstartdocletinvokerjava160at comsuntoolsjavadocstartparseandexecutestartjava397at comsuntoolsjavadocstartbeginstartjava167at comsuntoolsjavadocmainexecutemainjava59at comsuntoolsjavadocmainmainmainjava49javadoc exited with exit code 1is there a way to create the javadoc in android studio if not how could i create one i need to give it with my project,['android'] +713757,swift syntax for block with completionhandler in delegate method this is a wrinkle on the regular nsurlsession completion block problem which i am having a heck of a time resolving into swift syntax the method is the authentication delegate callback which is invoked on auth challenge the developer calls the completion block with nsurlcredential nserrorthe objectivec method looks like thisvoid provideusernamepasswordforauthchallengensurlauthenticationchallenge authchallenge completionhandlervoid nsurlcredential nserror completionhandler nsurlcredential credential nsurlcredential credentialwithusermyname passwordmypass persistencensurlcredentialpersistenceforsession completionhandlercredential nilthe closest i think i have gotten in swift is thisfunc provideusernamepasswordforauthchallengeauthchallenge nsurlauthenticationchallenge completionhandler nsurlcredential nserror var cred nsurlcredentialuser myname password mypass persistence nsurlcredentialpersistenceforsession return cred nilbut it is still barfing any recommendations,"['ios', 'objective-c']" +713885,thisplaying an element outside overflow hidden container i have a table which is made scrollable by wrapping it in a div of fixed heightthis table has a dropdown component blue container in 2nd column of 1st row in the image and jsfiddle given below which is hiding behind the container div i want it to thisplay all the options insteadjsfiddle examplehow should i bring the dropdown component outside the container div to thisplay all the options as in the image below if i remove the prelative container then the dropdown is fully visible but when i scroll the dropdown does not scroll along with it is containerthanks in advanceps looking for cssjavascript solution only,"['javascript', 'html', 'css']" +713927,how do i get a google places api key for my android app i have spent the last 48 hours pulling my hair out trying to find the answer to this question the person who asked this question how can i make api key for google places apiis experiencing the same issue i am having but never got an answerbasically i need help getting a google places api key i already have a maps api key which works fine but i cannot get a places api key i have followed every single tutorial i could find including to name a couple but absolutely nothing has worked i added some screenshots below here to illustrate the problem1234everyone i ask keeps telling me that it is just located somewhere on the website but 2 solid days of looking has gotten me nowhere can someone please help me to find the exact location to obtain a places api again not a maps api i already have that and am getting only request denied errors due to my lack of a secondary keythanks in advance allsilmarilos,['android'] +713935,how to change gem environment settings i installed rbenv and set up ruby and gems now if i run gem env then i got the followingrubygems environment rubygems version 2 ruby version 210 20131225 patchlevel 0 x86 64darwin130 installation directory usersmyusernametoolsrbenvversions210librubygems210 ruby executable usersmyusernametoolsrbenvversions210binruby executable directory usersmyusernametoolsrbenvversions210bin spec cache directory usersmyusernamegemspecs rubygems platforms ruby x86 64darwin13 gem paths usersmyusernametoolsrbenvversions210librubygems210 usersmyusernamegemruby210 gem configuration update sources true verbose true backtrace false bulk threshold 10 remote sources shell path usersmyusernametoolsrbenvversions210bin usersmyusernametoolsrbenvlibexec usersmyusernametoolsrbenvpluginsrubybuildbin optlocalbin optlocalsbin usersmyusernametoolsrbenvshims usrbin bin usrsbin sbin usrlocalbin usersmyusernametoolsbin usersmyusernametoolsrbenvbinwell all looks good except for spec cache directory and gem paths all others have selfconfigured paths so i really do not want any devrelated directories directly placed in my user home folder is there a way to flexibly change these two env variables without affecting normal functioning of ruby gem and rbenv etcthanks,['ruby'] +713992,type modifer precedence vs logical and operator vs addressof operator updateit seems that i am not being clear enough of what exactly i am asking and as the question developed over time i also lost track a bit so here is a tldr versionvar test1 a is byte b compilesvar test2 a is byte b does not compilevar test3 a is byte b compilesthis means as i understand that the type modifier has lower precedence as it is not an operator this might not be the best word than the operator but higher than the operator is it so where is this described in the standardand the original questionwhile trying to figure out the answer to the second puzzle from jon skeets excellent blogpost a tale of two puzzles i faced a problemunsafe private void test a bool b var test1 a is byte b does not compile var test2 a is byte b compiles var test3 a is byte b b compileshere i am using an unsafe context as my actual goal requires it eg the third line but it is not necessary for reproducing the issue i raise however it might have an effect as it introduces the addressof operator as an alternative for the symbolthe first line does not compile the others do it gives the following error messagesyntax error expectedthis means that in that case the compiler sees the line asvar test1 a is byte b missing part that it complains aboutwhile in the second line it sees it asvar test2 a is byte bi checked operator precedence here and the order from highest to lowest is the following so this alone does not explain why the first line does not compile while the second does or at least not for me maybe this is where i am wrong edit i understand why the second compiles so please do not concentrate on this in your answersmy next hunch was that somehow the precedence if there is such thing for the type modifier is somewhere between those two or in fact three operators and can it be so if not could someone please explain the exact behavior that i am experiencing is the evaluating order of type modifier clearly described somewhere in the standardedit i am also aware that there is an unary addressof operator actually that is the trick i am trying to use for the solution which plays a role here but my question still stays the samein the same unsafe context those happily compilevar test1 true bvar test2 true b orvar test1 a is byte bvar test2 a is byte bso i think it must be related to the modifieroperator and not solely to the addressof operator taking precedence otherwise the two test1 lines would not compileps i know that i can add parentheses to my code so it will compile but i want to avoid thatvar test a is byte b compilesupdatei experimented with roslyn a little and i thought it might be a good idea to attach the asts for the various statementsvar test1 a is byte bvar test2 a is byte bvar test3 a is byte bi want to emphasise that i am not looking for a solution for the original problem in the linked article of course i am looking for one but i ask you not to give an answer here please as i would like to find that out on my ownalso please do not comment if i am on a completely wrong track in finding the solution i only mentioned the puzzle to give some context for my specific problem and to provide a goodenough excuse for writing code like this,['c#'] +714006,how to compile cordova project from visual studio hybrid app to android ios apk i try to compile my cordova hybrid app from visual studio to apk file after i deploy the project to android ios the project bin folder still emptyi try to upload the w folder to buildphonegapcom but i get error what is the best and correct way to compile the project html css and js to apk for android and ios thanks tomupdatei try to build from the visual studio this is my project folder when i try to build project from the visual studio on device mode i get this error,"['android', 'ios']" +714021,lodash debounce not working in anonymous function hello i cannot seem to figure out why the debounce function works as expected when passed directly to a keyup event but it does not work if i wrap it inside an anonymous functioni have fiddle of the problem edit added all the things i triedhtmlinput idanonfunctioninput idnoreturnanonfunctioninput idexedebouncedfuncinput idfunctiondiv idoutputdivjavascriptdocumentreadyfunction anonfunctiononkeyup function return debouncedebounceit 500 false why does this differ from function noreturnanonfunctiononkeyup function debouncedebounceit 500 false not being executed exedebouncedfunconkeyup function debouncedebounceit 500 false executing the debounced function results in wrong behaviour functiononkeyup debouncedebounceit 500 false this is workingfunction debounceit outputappenddebouncedanonfunction and noreturnanonfunction does not fire the debounce function but the last function does fire i do not understand why this is can anybody please help me understand thiseditok so the reason that the debounce does not happen in exedebouncedfunc the one you refer is because the function is executed in the scope of the anonymous function and another keyup event will create a new function in another anonymous scope thus firing the debounced function as many times as you type something instead of firing once which would be the expected behaviour see beviour of functioncan you please explain the difference between anonfunction and the function is this again a matter of scoping why one of them works and the other does noteditok so now i understand why this is happening and here is why i needed to wrap it inside an anonymous functionfiddle htmlinput idanonfunctiondiv idoutputdivjavascriptfunction var debounce debouncefireserverevent 500 false anonfunctiononkeyup function clear textfield outputappendclearnotificationsbr debounce function fireserverevent outputappendservereventbr,"['javascript', 'jquery']" +714032,parallelinvoke does not wait for async methods to complete i have an application that pulls a fair amount of data from different sources a local database a networked database and a web query any of these can take a few seconds to complete so first i decided to run these in parallelparallelinvoke datax loadx datay loady dataz loadzas expected all three execute in parallel but execution on the whole block does not come back until the last one is donenext i decided to add a spinner or busy indicator to the application i do not want to block the ui thread or the spinner would not spin so these need to be ran in async mode but if i run all three in an async mode then they in affect happen synchronously just not in the same thread as the ui i still want them ran parallelspinnerisbusy trueparallelinvoke async datax await taskrun return loadx async datay await taskrun return loady async dataz await taskrun return loadz spinnerisbusy falsenow the parallelinvoke does not wait for the methods to finish and the spinner is instantly off worse dataxyz are null and exceptions occur laterwhats the proper way here should i use a backgroundworker instead i was hoping to make use of the net 45 features,"['c#', '.net']" +714136,create aar file in android studio i would like to create an aar file for my library in android studio i wouldve gone with a jar option but my library has resourcesany idea how to create an aar file from a library,['android'] +714189,clip google maps js api imagemaptype to a polygon how can i clip a maptype in google maps to an arbitrary polygon for example if i have a custom imagemaptype that covers a large area ie all the world but i want to show it only inside a given polygon ie one countryis there a way to clip the imagemaptype to a given polygon or to implement a custom maptype to achieve this behaviour it should allow for zooming and panning normallythe rest of the map should stay the same and there would be a maptype covering only a specific area therefore it is not possible to simply overlay a polygon to cover the areas outside the polygon to thisplay just what is neededlike soserverside clipping is not an option,['javascript'] +714313,how to cast jquery ajax calls to bluebird promises without the deferred anitpattern right now i use promisedeferred in a core file this allows me to resolve promises at a central location i have been reading that i may be using an antipattern and i want to understand why it is badso in my corejs file i have functions like thisvar getmylocation functionlocation var promiseresolver promisedefer getsomerestapi location thenfunctionreponse promiseresolverresolveresponse catchfunctionerror promiseresolverrejecterror return promiseresolverpromiseand then in my getlocationjs file i have the followingvar core requirecorevar location coregetmylocationpetersburg thenfunctionresponse do something with data catchthrow errorafter reading the bluebird docs and many blog posts about the deferred antipattern i wonder if this pattern is practical i could change this to the followingcorejsvar getmylocation functionlocation var jqxhr getsomerestapi location return promiseresolvejqxhr catchtimeouterror cancellationerror functione jqxhrabort do not swallow it throw e getlocationjsvar location coregetmylocationpetersburg thenfunctionresponse do something catchfunctionerror throw new error i guess i am confused by what is the best way to have a central library that handles xhr requests using jquery for the calls but bluebird for the promises,['javascript'] +714388,rangebased for on multidimensional array my embedded system got a c11capable version of g so i have been cleaning up code fromfor uint16 t p array p array1 p p fill valuetofor uint16 t r array r fill valuewhich is much more readableis there a rangebased for loop which operates over all elements of array2mnthe old version isfor int16 t p array20 p array210 p p fill valueand i do not want nested loops unless it is guaranteed the compiler will flatten themfwiw the compiler is the gnu 474 linaro g arm crosscompiler that ships with ti code composer studio 600,['c++'] +714436,how do i programmatically determine if an app in the play store can be installed on current device in my app i am recommending related apps but only want to recommend them if they actually can be installed on the device eg device in related apps targeted countries correct os version etc see is there any api that allows me to query if a given app i am recommending by linking to marketdetailsidpackage name can be installed on the local deviceif not i could manually store the other apps requirements in my own app but then how do i determine items such as the country the users play store is associated with,['android'] +714439,ios get uinavigationbars back button in order to set accessibility properties i have a navigation controller stack where one of the views has a dynamic titlethe view controllers and their titles go like thismain itemstableview itemdetailstitlemain title nn items title detailsbecause the ios uinavigationcontroller sets the text of the back button to be the title of the previous screen the back button on the details screen says nn items where nn is a dynamically changing numberi am trying to do some ios ui automation but the accessibility label id of the back button is set by the system to it is button text this means that the accessibility label of the back button on the details screen will change dynamically and i cannot find it from my scriptsif i could get a reference to the uibarbuttonitem then i could easily set it is accessibilitylabel or accessibilityidentifier from code to be a fixed string however i cannot figure out how to do thisall of the stuff i have been able to find references setting the back button to a custom button via selfnavigationitembackbarbuttonitem or similar but when i read this property it is nil i have not been able to find out how to get access to the standard item without replacing it i would prefer not to replace the button if possible,['ios'] +714479,how to test application class with robolectric i am trying to test push notification with parsecom using robolectric as the initialization has to be done in an application class i need to test it so far the app is working fine on emulator but i am not able to test it with robolectricmy oncreate of application classpublic void oncreate superoncreate add your initialization code here parseinitializethis app key client id specify an activity to handle all pushes by default pushservicesetdefaultpushcallbackthis mainactivityclass save the current installation to parse this is null on test android id securegetstringgetapplicationcontext getcontentresolver secureandroid id systemoutprintlnandroid id android id parseinstallation installation parseinstallation getcurrentinstallation installationputuniqueid android id installationsaveinbackground parseuserenableautomaticuser parseacl defaultacl new parseacl if you would like all objects to be private by default remove this line defaultaclsetpublicreadaccesstrue parsesetloglevelparselog level verbose parseaclsetdefaultacldefaultacl true testrunwithrobolectrictestrunnerclasspublic class testparseapplication extends application private parseapplication parseapplicationbeforepublic void setup parseapplication new parseapplication parseapplicationandroid id 123 robolectricapplication parseapplicationtestpublic void shouldpass asserttruetruestacktracewarning no system properties value for robuilddateutcandroid id nulljavalangillegalargumentexception must subscribe to channel with a valid icon identifier at comparsepushservicesetdefaultpushcallbackpushservicejava298 at comparsepushservicesetdefaultpushcallbackpushservicejava277 at comparsestarterparseapplicationoncreateparseapplicationjava30 at orgrobolectricinternalparalleluniversesetupapplicationstateparalleluniversejava164 at orgrobolectricrobolectrictestrunnersetupapplicationstaterobolectrictestrunnerjava430 at orgrobolectricrobolectrictestrunner2evaluaterobolectrictestrunnerjava236 at orgjunitrunnersparentrunnerrunleafparentrunnerjava263 at orgjunitrunnersblockjunit4classrunnerrunchildblockjunit4classrunnerjava68 at orgjunitrunnersblockjunit4classrunnerrunchildblockjunit4classrunnerjava47 at orgjunitrunnersparentrunner3runparentrunnerjava231 at orgjunitrunnersparentrunner1scheduleparentrunnerjava60 at orgjunitrunnersparentrunnerrunchildrenparentrunnerjava229 at orgjunitrunnersparentrunneraccess0parentrunnerjava50 at orgjunitrunnersparentrunner2evaluateparentrunnerjava2 at orgrobolectricrobolectrictestrunner1evaluaterobolectrictestrunnerjava177 at orgjunitrunnersparentrunnerrunparentrunnerjava300 at orgeclipsejdtinternaljunit4runnerjunit4testreferencerunjunit4testreferencejava50 at orgeclipsejdtinternaljunitrunnertestexecutionruntestexecutionjava38 at orgeclipsejdtinternaljunitrunnerremotetestrunnerruntestsremotetestrunnerjava467 at orgeclipsejdtinternaljunitrunnerremotetestrunnerruntestsremotetestrunnerjava683 at orgeclipsejdtinternaljunitrunnerremotetestrunnerrunremotetestrunnerjava390 at orgeclipsejdtinternaljunitrunnerremotetestrunnermainremotetestrunnerjava197,['android'] +714715,hard delete custom field in salesforce i am having problem in deleting custom fields permanentlylike for egi have created a custom field in contact entity with name newsletter which salesforce internaly stores as newsletter c as custom fieldthen i use the below code to delete custom field of contactvar cstfield new customfield type fieldtypecheckbox fullname contactnewsletter c delete the objectvar r metaservicedeletenew metadata cstfield 0the above code deletes the custom field but keeps it under deletedfields category where you can again erase or undelete the custom field these custom fields are deleted automatically after 15 daysi want to delete the custom fields from these category also as if i again create cf with same name sf gives error like already existsi tried purgeondelete option too while deploying but no luck so far,['c#'] +714779,rails 4 to json produces unexpected exception nil is not a symbol i am in the process of upgrading a rails 3 application to rails 4 in rails 3 the json serialization of a hash containing an array of activerecord objects was working correctly now in rails 4 it is having unpredictable resultshere is an example object that fails with typeerror exception nil is not a symbol on rails 41230 questionanswerresponse response id 127 response set id 6 response group nil question data export identifier is co pi involved answer no question id 1230 answer id 2077 response questionanswerresponse response id 131 response set id 6 response group nil question data export identifier is co pi involved answer no question id 1230 answer id 2077 response now if i take another similar object hash containing an array of activerecord objects and run to json it works on this one1234 response id 1 response set id 2 question id 4 answer id 2 datetime value nil integer value nil float value nil unit nil text value nil string value nil response other nil response group nil created at 20140530 211723 updated at 20140530 211723 survey section id 1 api id f44b22baa93b477f8a7fc5b4566338f0 attach file name nil attach content type nil attach file size nil attach updated at nil response id 2 response set id 2 question id 10 answer id 10 datetime value nil integer value nil float value nil unit nil text value test string value nil response other nil response group nil created at 20140530 211723 updated at 20140530 211723 survey section id 1 api id e7fa8aa26e474f802949fdc902a2e attach file name nil attach content type nil attach file size nil attach updated at nil,"['ruby-on-rails', 'ruby']" +714784,validating that a has many association has at least one model when using factorygirl putting aside arguments on whether or not you should test existence of a models associations i have a model called order and i am validating that it has at least one item in its has many association usingclass order activerecordbase has many items validates items presence trueendi have set factorygirl to lint my factories checking for validity so my order factory is not valid unless i create an item for its has many collectionmy orders factory looks like thisfactorygirldefine do factory order do ignore do items count 1 end afterbuild do order evaluator create listitem evaluatoritems count order order end endendaccording to factory girls getting startedfactorygirllint builds each factory and subsequently calls valid on ithowever when i run my specs factory girl throws an factorygirlinvalidfactoryerror because the order factory is invalidworkaroundafterbuild do order evaluator evaluatoritems counttimes do orderitems factorygirlcreateitem end create listitem evaluatoritems count order order end,"['ruby-on-rails', 'ruby']" +714795,rails library not loaded homebrew prefixoptopensslliblibssl100dylib loaderror i am fighting with an error that occurs when i run rails susersadamrvmgemsruby200p481gemsmysql20316libmysql2rb8in require dlopenusersadamrvmgemsruby200p481extensionsx86 64darwin13200staticmysql20316mysql2mysql2bundle 9 library not loaded homebrew prefixoptopensslliblibssl100dylib loaderror referenced from usrliblibmysqlclient18dylib reason image not found usersadamrvmgemsruby200p481extensionsx86 64darwin13200staticmysql20316mysql2mysql2bundlemysql installed through brewunfortunately i am not sure how to fix this issue so i appreciate every helpthank you,"['mysql', 'ruby-on-rails', 'ruby']" +714800,c thread abort exception thread abort exception rethrowing itself i have the current codeclass program private static void main while true try threadcurrentthreadabort catch threadabortexception consolewritelineabort threadresetabort consolewritelinenow waiting consolereadkey now i know the method resetabort is supposed to prevent the threadabortexception from continue to rethrow itself even when a catch statement is catching it but my question is thisif anyone can use the resetabort method then whats the point of the exception specially rethrow itself the user can just do catch threadabortexception ex consolewritelineabort throw ex,['c#'] +714802,how to expose require to the browser when using browserify from within gulp when i have a file xjs that looks like thisxjsmoduleexports function n return and 1 and i run browserify from the command line like sobrowserify r xjs bundlejsi get an output file that looks like this roughly requirefunction etnrfunction appjsxfunctionrequiremoduleexportsmoduleexportsrequire0dprthen in my browser code i can do thishtml head titlereact server rendering exampletitle script srcstaticbundlejsscript head body welcome to the react server rendering example here is a serverrendered react component div id53a442ff8b39ddivscript var x requirexjs consolelogx3script bodyhtmli actually have two questions1 this does not quite work in the browser i get the error uncaught error cannot find module xjs why is that happening2 i actually want to run this in gulp using vinylsourcestream i have tried doing something like this in my gulpfile but it does not work any ideas i get the error require is not definedvar gulp requiregulp browserify requirebrowserify source requirevinylsourcestreamvar b browserify entries xjs bbundledebug false pipesourcebundlejs pipegulpdestbuild,['javascript'] +714860,doubleisnan test 100 times faster i found this in the net source code it claims to be 100 times faster than systemdoubleisnan is there a reason to not use this function instead of systemdoubleisnanstructlayoutlayoutkindexplicitprivate struct nanunion fieldoffset0 internal double doublevalue fieldoffset0 internal uint64 uintvalue the standard clr doubleisnan function is approximately 100 times slower than our own wrapper so please make sure to use doubleutilisnan in performance sensitive code ps item that tracks the clr improvement is devdiv schedule 26916 ie 754 if the argument is any value in the range 0x7ff01l through 0x7fl or in the range 0xf01l through 0xfl the result will be nan public static bool isnandouble value nanunion t new nanunion tdoublevalue value uint64 exp tuintvalue 0xf0 uint64 man tuintvalue 0x0f return exp 0x7ff0 exp 0xf0 man 0edit still according to the net source code the code for systemdoubleisnan is the followingpublic unsafe static bool isnandouble d return uint64d 0x7fl 0x7ff0l,['c#'] +714873,retrofit map json variable to keyword so i am working with retrofit with an api that has a variable called public how would i go about getting it to automatically map like all the other variables doexamplegetfiltermy imagesvoid getmyimages queryclient id string id queryapi key string key callbackimagelist callbackpublic static class image int id string name string thistribution string slug cannot do this boolean publicpublic static class imagelist string status listimage imagesexample api results json status ok images id 1 name my first snapshot thistribution ubuntu slug ubuntu1210x32 public true id 2 name automated backup thistribution ubuntu,['android'] +714909,formats supported by bitmapfactorydecodebytearray is it documented or reasonable to assume that bitmapfactorydecodebytearray can be expected to recognize any of the image formats listed here,['android'] +714927,how to debug cocos2dx 3 native code on android device i could not find any cookbooktutorial how build in debug build a cocos2dx 31 project for android and how to debug it directly on device please help by pointing out stepswhat i do and what problems i havecd projandroidcocos compile p android m debug ndkmode ndk debug1 to build with debug infococos run p android m debug to deploy on devicerun app on the devicecd jnindkgdband i get this errornareksmacbookprojni narek ndkgdbjniandroidmk67 android ndk aborting stoperror the device does not support the applications targetted cpu abis device supports armeabiv7a armeabi package supports android ndk into applicationmk i have added app abi armeabi armeabiv7aapp platform android10but it did not help what i do wrongedit adding result of ndkbuild dump app abi command called in projects jni directorynareksmacbookprojni narek ndkbuild dump app abi android ndk usersnareknoorgamesgamestest2projandroidjniandroidmk cannot find module with tag in import path android ndk are you sure your ndk module path variable is properly defined android ndk the following directories were searched android ndk usersnareknoorgamesgamestest2projandroidjniandroidmk67 android ndk aborting stop,['c++'] +714976,how can i make this repeat forever i have this terrain generator that is in my opinion pretty efficient i just cannot get it to print forever heres the current code i have for itimport randomprint joinrandomchoiceo for i in range10i tried to do this but i got a syntaxerrorimport randomprint joinrandomchoiceo while truehow can i get this to repeat forever i also want a 005 second delay in between the printing of each character if you can keep this at a max of two lines that is cool if you cannot that is okay thanks note this is not about gamedev i just happened to be using join for a terrain generator,['python'] +714990,overlapping regex i want a regex that matches any set of digits with one possible dot if there is another dot and more digits after it do an overlapping match with the previous digits the dot and the following digitsexample string aa323aa23202032399aa8701mmdesired results 323 23202 0203 0323 2399 87 01 currently usingimport rei aa323aa23202032399aa8701matches refindallrd01d iprint matches output323 23 23202 3202 202 0203 203 0323 323 2399 399 99 87 01 1 1 1 1 11,['python'] +715001,while loop ends prematurely i am trying out while loop while reading c tutorial surprisingly the below loop always exits on 2nd iteration despite i gave negative integerswhileint sz get size sz 0 below is the get size usedint get size int a 0 cin a return a,['c++'] +715005,functor reference through a stdfunction basically i would like to have the following semantic include functionalinclude iostreamclass test public void addstdfunctionvoid f f void operator x int x 33int main test t taddt wanted x 34 instead x 33 since addt copies iti understand stdfunction wraps a copy of the callable object but is there any way to get a reference to a callable object using stdfunction,['c++'] +715018,how to create a onetomany relationship with jdbi sql object api i am creating a simple rest application with dropwizard using jdbi the next step is to integrate a new resource that has a onetomany relationship with another one until now i could not figure out how to create a method in my dao that retrieves a single object that holds a list of objects from another tablethe pojo representations would be something like thispublic class user private int id private string name public userint id string name thisid id thisname name public int getid return id public void setidint id thisid id public string getname return name public void setnamestring name thisname name public class account private int id private string name private listuser users public accountint id string name listuser users thisid id thisname name thisusers users public int getid return id public void setidint id thisid id public string getname return name public void setnamestring name thisname name public listuser getusers return name public void setuserslistusers users thisusers users the dao should look something like thispublic interface accountdao mapperaccountmapperclass sqlqueryselect accountid accountname username as you name from account left join user on useraccountid accountid where accountid id public account getaccountbyidbindid int idbut when the method has a single object as return value account instead of listaccount there seems to be no way to access more than one line of the resultset in the mapper class the only solution that comes close i could find is described at but that one also only returns a set with a single object which does not seem very elegant and cannot be properly used by the resouce classesthere seems to be a way using a folder2 in the fluent api but i do not know how to integrate that properly with dropwizard and i would rather stick to jdbis sql object api as recommended in the dropwizard documentationis there really no way to get a onetomany mapping using the sql object api in jdbi that is such a basic use case for a database that i think i must be missing somethingall help is greatly appreciated tilman,['java'] +715052,how to manually force a commit in a transactional method i am using spring springdatajpa and find myself needing to manually force a commit in a unit test my use case is that i am doing a multithreaded test in which i have to use data that is persisted before the threads are spawnedunfortunately given that the test is running in a transactional transaction even a flush does not make it accessible to the spawned threads transactional public void testaddattachment throws exception final contract c1 contractdodgetnewtransientcontract15 contractrepositorysavec1 need to commit the savecontract here but do not know how emgettransactioncommit listthread threads new arraylist for int i 0 i 5 i final int threadnumber i thread t new thread new runnable override transactional public void run try do stuff here with c1 sleep to ensure that the thread is not finished before another thread catches up threadsleep10 catch interruptedexception e todo autogenerated catch block eprintstacktrace threadsaddt tstart have to wait for all threads to complete for thread t threads tjoin need to validate test results need to be within a transaction here contract c2 contractrepositoryfindonec1getid i have tried using the entity manager to but get an error message when i doorgspringframeworkdaoinvaliddataaccessapiusageexception not allowed to create transaction on shared entitymanager use spring transactions or ejb cmt instead nested exception is javalangillegalstateexception not allowed to create transaction on shared entitymanager use spring transactions or ejb cmt instead at orgspringframeworkormjpaentitymanagerfactoryutilsconvertjpaaccessexceptionifpossibleentitymanagerfactoryutilsjava293 at orgspringframeworkormjpaaspectjjpaexceptiontranslatoraspectajcafterthrowingorg springframework orm jpa aspectj jpaexceptiontranslatoraspect118a1ac9jpaexceptiontranslatoraspectaj33is there any way to commit the transaction and continue it i have been unable to find any method that allows me to call a commit,['java'] +715066,from view controller thisappears using uiviewcontrollercontexttransitioning i got one problem and i have described it belowi am using uiviewcontrollercontexttransitioning for custom transitionsi have 2 view controllers first view controller and second view controllernow i want to add secondview controller on first view controller with animation i have achieved it now i have secondview controller transparent so we can see first view controller below secondview controllerbut i am not able to see first view controller and i can see only black screen below secondview controllerhere is the codevoidanimatetransitioniduiviewcontrollercontexttransitioningtransitioncontext selftransitioncontext transitioncontext ifselfispresenting self executepresentationanimationtransitioncontext else self executethismissalanimationtransitioncontext voidexecutepresentationanimationiduiviewcontrollercontexttransitioningtransitioncontext uiview inview transitioncontext containerview uiviewcontroller toviewcontroller transitioncontext viewcontrollerforkeyuitransitioncontexttoviewcontrollerkey uiviewcontroller fromviewcontroller transitioncontext viewcontrollerforkeyuitransitioncontextfromviewcontrollerkey cgrect offscreenframe inviewframe offscreenframeoriginy inviewframesizeheight toviewcontrollerviewframe offscreenframe toviewcontrollerviewbackgroundcolor uicolor clearcolor fromviewcontrollerviewbackgroundcolor uicolor clearcolor inviewbackgroundcolor uicolor clearcolor inview insertsubviewtoviewcontrollerview abovesubviewfromviewcontrollerview inview addsubviewtoviewcontrollerview cftimeinterval duration selfpresentationduration cftimeinterval halfduration duration2 catransform3d t1 self firsttransform catransform3d t2 self secondtransformwithviewfromviewcontrollerview uiview animatekeyframeswithdurationhalfduration delay00 optionsuiviewkeyframeanimationoptioncalculationmodelinear animations uiview addkeyframewithrelativestarttime00f relativeduration05f animations fromviewcontrollerviewlayertransform t1 uiview addkeyframewithrelativestarttime05f relativeduration05f animations fromviewcontrollerviewlayertransform t2 completionbool finished uiview animatewithdurationduration delayhalfduration 03halfduration usingspringwithdamping07f initialspringvelocity60f optionsuiviewanimationoptioncurveeasein animations toviewcontrollerviewframe inviewframe completionbool finished selftransitioncontext completetransitionyes when selftransitioncontext completetransitionyes called suddenly the first view controller thisappears and black screen thisplays below second view controllerdoes any one have idea thanks,"['ios', 'iphone', 'objective-c']" +715072,installing package dependencies for scrapy so among the many packages users need to install for scrapy i think i am having trouble with pyopenssl when i try to get a tutorial scrapy project created i get this following outputtraceback most recent call last file cpython27librunpypy line 162 in run module as main main fname loader pkg name file cpython27librunpypy line 72 in run code exec code in run globals file cpython27libsitepackagesscrapycmdlinepy line 168 in module execute file cpython27libsitepackagesscrapycmdlinepy line 122 in execute cmds get commands dictsettings inproject file cpython27libsitepackagesscrapycmdlinepy line 46 in get commands dict cmds get commands from modulescrapycommands inproject file cpython27libsitepackagesscrapycmdlinepy line 29 in get commands from module for cmd in iter command classesmodule file cpython27libsitepackagesscrapycmdlinepy line 20 in iter command classes for module in walk modulesmodule name file cpython27libsitepackagesscrapyutilsmiscpy line 68 in walk modules submod import modulefullpath file cpython27libimportlib init py line 37 in import module import name file cpython27libsitepackagesscrapycommandsbenchpy line 3 in module from scrapytestsmockserver import mockserver file cpython27libsitepackagesscrapytestsmockserverpy line 6 in module from twistedinternet import reactor defer ssl file cpython27libsitepackagestwistedinternetsslpy line 59 in module from openssl import ssl file buildbthistwin32eggopenssl init py line 8 in module file buildbthistwin32eggopensslrandpy line 11 in module file buildbthistwin32eggopenssl utilpy line 3 in moduleimporterror no module named cryptographyhazmatbindingsopensslbindingand when i googled that last error no module named cryptographyhazmat i see a couple of mentions of pyopenssl so i went ahead and tried running easy install pyopenssl014 to make sure it is the latest version but when i do that i get this outputcpython27includepymathh22 warning c4273 round inconsistent dll linkage cprogram files x86microsoft visual studio 120vcincludemathh516 see previous definition of roundcusersbkappdatalocaltempeasy installtztawucryptography04tempeasy installsvxsjycffi082cmisc win32h225 error c2632 char followed by bool is illegalcusersbkappdatalocaltempeasy installtztawucryptography04tempeasy installsvxsjycffi082cmisc win32h225 warning c4091 typedef ignored on left of unsigned char when no variable is declaredc cffi backendc5295 warning c4146 unary minus operator applied to unsigned type result still unsignedc cffi backendc5296 warning c4146 unary minus operator applied to unsigned type result still unsignedc cffi backendc5297 warning c4146 unary minus operator applied to unsigned type result still unsignedc cffi backendc5298 warning c4146 unary minus operator applied to unsigned type result still unsignederror setup script exited with error command cprogram files x86microsoft visual studio 120vcbinclexe failed with exit status 2so i am a bit lost as to what i need to do to get scrapy up and running properly,['python'] +715109,how to convert a multipart file to file can any one tell me what is a the best way to convert a multipart file orgspringframeworkwebmultipartmultipartfile to file javaiofile in my spring mvc web project i am getting uploaded file as multipart filei have to convert it to a fileio there fore i can call this image storing servicecloudinarythey only take type filei have done so many searches but failedif anybody knows a good standard way please let me knowthnx,['java'] +715236,using factorygirl without rails activerecord or any database with rspec i was wondering if anyone knows whether it is possible to use factorygirl without any of the aforementioned prerequisitesi would like to use it to generate onthefly test data when driving ui automation tests for both mobile and web and even possibly apii know i could create some custom helper classesmethods and use getters and setters etc but i thought it would be good to use this awesome little gemi have searched quite extensively and also tried to set up a basic rspec project i also tried cucumber but to no avail it still appears that i need classes to be instantiated with the relevant login in order to consume itfactorygirldefine do factory user do firstname fakernamefirst name lastname fakernamelast name age 1 rand100 endendthen if i try to call it in a rspec filedescribe it user build stubbeduser endendi have also read the docs and tried all the other variants i just keep getting failureerror user build stubbeduser nameerror uninitialized constant userwhich suggests i need a class called user with all the logic,['ruby'] +715286,why does the c compiler crash on this code why does the code below crash the net compiler it was tested on cscexe version 40see eg here for online demo on different version it crashes in the same manner while it says dynamic is not supported compilation error line 0 col 0 internal compiler error 0xc05 at address xy likely culprit is transformthe extension method works fine on listdynamic thoughusing systemusing systemcollectionsgenericstatic class f public static void mtthis ienumerablet enumeration actiont action static void uck d dmkvp consolewritelinekvp class c public class k dictionarystring dynamicupdate this does not crash the compilerstatic void udictionarystring dynamic d dmkvp consolewritelinekvpupdate 2 the same bug was reported in the bug was reported for firstordefault but it seems the compiler crashes on any extension method applied to class derived from dictionaryt1t2 where at least one of the parameter types is dynamic see an even more general description of the problem below by erik funkenbuschupdate 3 another nonstandard behaviour when i try to call extension method as a static method that is fmd kvp consolewritelinekvp the compiler does not crash but it cannot find the overloadargument 1 cannot convert from ck to systemcollectionsgenericienumerablesystemcollectionsgenerickeyvaluepairstringdynamicupdate 4 solution kind of hans sketched 2nd workaround which is semantically equivalent to original code but works only for extension method call and not for standard call since the bug is likely caused by the fact that the compiler fails to cast class derived from generic class with multiple parameters with one being dynamic to its supertype the solution is to provide an explicit cast see dictionarystring dynamicdmkvp consolewritelinekvpmdictionarystring dynamicd kvp consolewritelinekvp,['c#'] +715351,styling of select2 dropdown select boxes i am using select2 in a project to style some select boxes in a search form i managed to change the gradient background of the arrow container to a black gradientselect2container select2choice select2arrow backgroundimage khtmlgradientlinear left top left bottom from424242 to030303 backgroundimage mozlineargradienttop 424242 030303 backgroundimage mslineargradienttop 424242 030303 backgroundimage webkitgradientlinear left top left bottom colorstop0 424242 colorstop100 030303 backgroundimage webkitlineargradienttop 424242 030303 backgroundimage olineargradienttop 424242 030303 backgroundimage lineargradient424242 030303i would like the arrow to be white but unfortunately select2 is using a background image for the different icons instead of fontawesome or something similar so there is no way to just change the color with csswhat would be the easiest way to make the arrow white instead of the default grey do i really have to replace the background png select2png and select2x2png with my own or is there an easier methodanother question i have is how to change the height of the select boxes i know how to change the height of the dropdown box in opened state but i want to change the height of the selectbox in closed state any ideas,['css'] +715356,how do you add additional files to a wheel how do control what files are included in a wheel it appears manifestin is not used by python setuppy bthist wheelupdatei was wrong about the difference between installing from a source tarball vs a wheel the source thistribution includes files specified in manifestin but the installed package only has python files steps are needed to identify additional files that should be installed whether the install is via source thistribution egg or wheel namely package data is needed for additional package files and data files for files outside your package like command line scripts or system config filesoriginal questioni have a project where i have been using python setuppy sthist to build my package manifestin to control the files included and excluded and pyroma and checkmanifest to confirm my settingsi recently converted it to dual python 2 3 code and added a setupcfg withbthist wheeluniversal 1i can build a wheel with python setuppy bthist wheel and it appears to be a universal wheel as desired however it does not include all of the files specified in manifestin what gets installedi dug deeper and now know more about packaging and wheel heres what i learnedi upload two package files to the multigtfs project on pypimultigtfs042targz the source tar ball which includes all the files in manifestinmultigtfs042py2py3noneanywhl the binary thistribution in questioni created two new virtual environments both with python 275 and installed each package pip install multigtfs042targz the two environments are almost identical they have different pyc files which are the compiled python files there are log files which record the different paths on thisk the install from the source tar ball includes a folder multigtfs042py27egginfo detailing the installation and the wheel install has a multigtfs042thistinfo folder with the details of that process however from the point of view of code using the multigtfs project there is no difference between the two installation methodsexplicitly neither has the zip files used by my test so the test suite will fail djangoadmin startproject demo cd demo pip install psycopg2 db driver for postgis project createdb demo create postgresql database psql d demo c create extension postgis make it a postgis database vi demosettingspy add multigtfs to installed apps update database to set engine to djangocontribgisdbbackendspostgis update database to set name to test managepy test multigtfstests run the testsioerror errno 2 no such file or directory uusersjohnvirtualenvstestlibpython27sitepackagesmultigtfstestsfixturestest3zipspecifying additional filesusing the suggestions from the answers i added some additional directives to setuppyfrom future import unicode literals setuppy now requires some funky binary stringssetup namemultigtfs packagesfind packages package databmultigtfs testfixtureszip include package datatrue this installs the zip files as well as the readme to the folder and tests now run correctly thanks for the suggestions,['python'] +715444,aspnet web api help page cannot process generic type controller i have a question about aspnet web api helppagesusually helppages can generate the webapi by xmldocumentationsample codepublic class valuecontrollerbase apicontroller summary base do summary public ienumerablestring do return new string value1 value2 public class valuescontroller valuecontrollerbase summary testing api summary public string getint id return value this can generate successfully like thisapiget apivaluesgetiddescriptiontesting apiapipost apivaluesdodescriptionbase dobut if i use a generic base controller it will not generate the api documentsamplepublic class valuecontrollerbaset apicontroller summary base do summary public ienumerablestring do return new string value1 value2 public class valuescontrollerstring valuecontrollerbase summary testing api summary public string getint id return value if i use the code at the second section helppages can generate the api document but does not generate the api annotation the difference between my two examples is just second section code use a generic typeapiget apivaluesgetid descriptiontesting apiapipost apivaluesdodescriptionnullin the method do the annotation does not thisplay compared with the firstis there any solution to fix these problems,['c#'] +715475,how to check which php extensions have been enabledthisabled in ubuntu linux 1204 lts i am using ubuntu linux 1204 lts on my local machine i have installed lamp long ago on my machine now i want to enable following php extensionsphp zipphp xmlphp gd2for it first i want to check whether these php extensions are enabled or not i searched a lot about how to check the installedenabled php extensions but every time i found how to install these extensions on ubuntu linux so can someone please let me know how should i check the enabledthisabled php extensions in ubuntu linux 1204 lts thanks in advance,['php'] +715639,skipping promise chain after handling error using the library i am wondering if it is possible to do something like this module afunction modulea exportedfunction return promisereturningservicethenfunctionserviceresults if serviceresultsaregood we can continue with the rest of the promise chain else performveryspecificerrorhandling we want to skip the rest of the promise chain module bmodulea exportedfunction thenmoduleb function thenmoduleb anotherfunction failfunctionreason handle the reason in a general way which is ok for module b functions donebasically if the service results are bad i would like to handle the failure in module a using logic that is specific to the internals of module a but still skip the remaining module b functions in the promise chainthe obvious solution for skipping module b functions is to throw an errorreason from module a however then i would need to handle that in module b and ideally i would like to do it without needing any extra code in module b for thatwhich may very well be impossible or against some design principles of qin which case what kind of alternatives would you suggesti have two approaches in mind but both have their thisadvantagesthrow a specific error from module a and add specific handling code to module bfailfunctionreason if reason is specificerror performveryspecificerrorhandling else handle the reason in a general way which is ok for module b functions perform the custom error handling in module a then after handling the error throw a fake rejection reason in module b add a condition to ignore the fake reasonfailfunctionreason if reason is fakereason skip handling else handle the reason in a general way which is ok for module b functions solution 1 requires adding module a specific code to module bsolution 2 solves this but the whole fake rejection approach seems very hackishcan you recommend other solutions,['javascript'] +715746,visual studio project type for clientside javascript could somebody advise me on which project type should i use to develop client side of webbased app html javascript for visual studio 2013i tried to create new web site aspnet empty web site then manually added all js files to the project but this is not exactly what i need because i am working on a clientside code only and the web server is not iisof course when a script error occurs i can select adebug using selected debuggera manually choose my project and jump into debugging however this is only a halfsolutionfirst i cannot start debugger with f5 a it launches web page connected to local iis insteadsecond i have duplicate source trees in solution explorer the debugger does not match my source files with files loaded with web pagesi have also tried new other project types visual studio solution add existing web site and played with start options but without much success too it launches page in ie but with script debugging thisabled and it does not start the debugger anywayis there an appropriate project type to write and debug javascript for ieps when installing vs i selected c development as my primary settings which might hide some useful web development features and i would prefer not to change thisupdate problem 1 starting with f5 was solved by setting ie as default web browser i have used firefox after specifying aspecific pagea in start options f5 starts the page under debuggeris it possible to debug scripts under ie leaving my favorite browser as default if i specify astart external programa and set aiexploreexea with page url it launches the page but does not allow me to debug it,['javascript'] +715829,listview in windows phone 81 wobbles while scrolling though long list xaml i am having issues with scrolling through listviews in my windows phone 81 app short lists scroll just fine scrolling smoothly however as soon virtualization kicks in the entire listview wobbles to the left slightly but noticeable enough to be annoying i have tried remove all the transitions to no effect as well as having items load incrementally to no success setting the item panel to a stackpanel removing virtualization fixes the issue but is not preferablemy listviews are binding to a property in the defaultviewmodel that comes with the basic page templatewhat am i doing wrong and what are causing my listviews to exhibit this behaviorxamllistview xnamesearchresultslist isitemclickenabledtrue itemclicklistview itemclick itemssourcebinding searchresults listviewitemcontainerstyle style targettypelistviewitem setter propertyhorizontalcontentalignment valuestretch setter propertymargin value020 style listviewitemcontainerstyle listviewitemtemplate datatemplate grid gridcolumndefinitions columndefinition width80 columndefinition width10 columndefinition width gridcolumndefinitions border width80 height80 image sourcebinding image border stackpanel gridcolumn2 textblock textbinding podcasttitle textwrappingwrapwholewords fontsizestaticresource textstyleextralargefontsize textblock textbinding lastupdated converterstaticresource dateconverter stylethemeresource listviewitemsubheadertextblockstyle textblock textbinding podcastartist textwrappingwrapwholewords stylethemeresource listviewitemcontenttextblockstyle stackpanel grid datatemplate listviewitemtemplate listview,['c#'] +715871,when i close a bufferedinputstream is the underlying inputstream also closed inputstream in someclassgetinputstreambufferedinputstream bis new bufferedinputstreamintry read data from bis finally bisclose inclose the javadoc for bufferedinputstreamclose does not mention whether or not the underlying stream is closedcloses this input stream and releases any system resources associated with the stream once the stream has been closed further read available reset or skip invocations will throw an ioexception closing a previously closed stream has no effectis the explicit call to inclose necessary or should it be closed by the call to bisclose,['java'] +715894,binding an event to document inside an angular directive i have a directive which implements kind of a select boxnow when the select box is open and i click somewhere outside of itanywhere else in the document i need it to collapsethis jquery code works inside my directive but i want to do it the angular way documentbindclick function e var clicked etarget if clickedparentshasclassmyclass scopecolapse i tried doing thing with injecting the document service into my directive but did not succeed,"['javascript', 'jquery']" +716030,how to access an objectivec class method from swift language in my swift app i need to access a class method called weibo as below from objectivec interface weibo nsobject weiboweiboendi have configured the bridging header and tried the following statement let w weiboweibo as weiboit does not workupdatei have forked the repo and fixed this issue as below let w weibogetweibo as weibo the method has been changedthe reason why it did not work because swift treats weiboweibo as a convenience constructor since weibo is same as the class name weibo although the case is different i need to change the name to getweibo to fix this issue to support swiftthanks for every one contributing to this answer special thanks to anil and david jake,"['ios', 'objective-c']" +716048,very strange behavior of operator is with methods why is the first result false should it not be true from collections import ordereddict ordereddict repr is ordereddict repr false dict repr is dict repr true,['python'] +716054,spring unit test jpa repository i am new to spring framework i need to write unit test for jpa repository i am trying simple repository saveandflush method but nothing saves in my repository here is my source codetestcontextclassconfiguration propertysourceclasspathlog4jproperties public class testcontext bean public roleservice roleservice return mockitomockroleserviceclass bean public rightservice rightservice return mockitomockrightserviceclass bean public rolerepository rolerepository return mockitomockrolerepositoryclass roleservicetestclassrunwithspringjunit4classrunnerclasscontextconfigurationclasses testcontextclasswebappconfigurationpublic class roleservicetest autowired private rolerepository rolerepository test public void testservices throws exception roledetails first new roledetails firstsetid1 firstsetdescriptionfirst description firstsetnamefirst rolerepositorysaveandflushnew roleentityfirst rolerepositorysavenew roleentityfirst listroleentity roles new arraylistroleentity roles rolerepositoryfindall systemoutprintlnroles assertequals1 rolessize and errorjavalangassertionerror expected1 but was0i am almost sure that problem occurs because of testcontextclass i used this class to test my controller and it worked well but now i need to test my database and i do not know how to modify contextconfiguration i hope somone will help me thanks in advance,['java'] +716159,multiprocessingpool hangs if child causes a segmentation fault i want to apply a function in parallel using multiprocessingpoolthe problem is that if one function call triggers a segmentation fault the pool hangs foreverhas anybody an idea how i can make a pool that detects when something like this happens and raises an errorthe following example shows how to reproduce it requires scikitlearn 014import numpy as npfrom sklearnensemble import gradient boostingimport timefrom multiprocessing import poolclass badobject tree nonedef fit onei if i 3 this will segfault bad nparraybad 2 dtypenpobject gradient boostingpredict stagesbad nprandomrand20 2astypenpfloat32 10 nprandomrand20 2 else timesleep1 return ipool pool2out poolimap unorderedfit one range10 we will never see 3for o in out print o,['python'] +716200,reverse string c using char array i wrote a simple c program to reverse a string i store a string in character array to reverse a string i am using same character array and temp variable to swap the characters of an arrayincludeiostreamincludestringusing namespace stdvoid reversecharchar strchar str50rstr50int inint main coutplease enter the string cingetlinestr50 reversecharstr coutstr return 0void reversecharchar str fori0isizeofstr2i char tempstri stristrsizeofstri1 strsizeofstri1temp now this method is not working and i am getting the null string as result after the program executionso i want to know why i cannot equate character array why wouldnt this program work and what is the solution or trick that i can use to make the same program work,['c++'] +716201,iis server 70 returning a 401 unauthorized access on firefox macos only i am running a php site which requires windows authentication on iis serverthe authentication is fed via active directoryfor some reason the site is not prompting users to login only on firefox and only on macosand i am getting this page instead of a dialog window prompting to login and the 401 page is thisplayed while no credentials were entered before and still not working after clearing the browser cache and rebooting my maci am not sure if this is a dns issue a server related issue a firewall issue or a browser issue or an operarting system issueall the people with macs are on the same network and they are all affected with this issue on firefox onlyit works fine on other browsers on the mac not for firefox on the mac and works fine on all the browsers on windows including firefox on windows ntlm is enabled as a provider on the servervvs71aspx,['php'] +716227,testing angularui bootstrap modal instance controller this is a somewhat of a followon question to this one angularjs ui bootstrap mocking modal in unit testthe referenced so is an excellent question with very useful answer the question i am left with after this however is this how do i unit test the modal instance controller in the referenced so the invoking controller is tested but the modal instance controller is mocked arguably the latter should also be tested but this has proven to be very tricky heres whyi will copy the same example from the referenced so herecontrollermodalinstancectrl functionscope modalinstance items scopeitems items scopeselected item scopeitems0 scopeok function modalinstanceclosescopeselecteditem scopecancel function modalinstancethismisscancel so my first thought was that i would just instantiate the controller directly in a test just like any other controller under testbeforeeachinjectfunctionrootscope scope rootscopenew ctrl controllermodalinstancectrl scope scopethis does not work because in this context angular does not have a provider to inject modalinstance since that is supplied by the ui modalnext i turn to plan b use modalopen to instantiate the controller this will run as expectedbeforeeachinjectfunctionrootscope modal scope rootscopenew modalinstance modalopen template htmlhtml controller modalinstancectrl scope scope note template cannot be an empty string or it will fail crypticallythe problem now is that i have no visibility into the scope which is the customary way to unit test resource gathering etc in my real code the controller calls a resource service to populate a list of choices my attempt to test this sets an expectget to satisfy the service my controller is using and i want to validate that the controller is putting the result in its scope but the modal is creating a new scope for the modal instance controller using the scope i pass in as a prototype and i cannot figure out how i can get a hole of that scope the modalinstance object does not have a window into the controllerany suggestions on the right way to test thisnb the behavior of creating a derivative scope for the modal instance controller is not unexpected aa it is documented behavior my question of how to test it is still valid regardless,['javascript'] +716287,python loop to run for certain amount of seconds i have a while loop and i want it to keep running through for 15 minutes it is currentlywhile true blah blah blahthis runs through and then restarts i need it to continue doing this except after 15 minutes it exits the loopthanks,['python'] +716364,how split large string in intellij idea automatically i am wirting a test with very long string so i need to split large strings like thatprivat static final string too long json field1field1 field2field2 fieldnfieldnwill becomeprivate static final string too long json field1field1 field2field2 field3field3 field4field4field6field6 field7field7 field8field8 field9field9field10field10 field11field11 fieldnfieldnis that possible to set up intellij idea to split large string automatically,['java'] +716407,swift making iboulet as strong iboutlets are weak by default in swift i have an object in the viewcontroller created in the storyboard which is not in the view hierarchy so i need it to be a strong reference in viewcontroller how can i change iboutlet property to strong,['ios'] +716414,how do you determine if an insert or update was successful using java and mysql i am using java to connect to a mysql database i am trying to insert or update data into the database even though i am quite sure the insert was successful it returns false according to the execute api the return value is true if the first result is a resultset object false if it is an update count or there are no results how can i determine whether or not my insert or update was successful public boolean insertselectionsstring selection string name string sql insert into workreport values boolean action false try preparedstatement stmt connpreparestatementsql simpledateformat dateformat new javatextsimpledateformatyi14mmi14dd hhmmss string formatdate dateformatformatnew javautildatesystemcurrenttimemillis javautildate mdate dateformatparseformatdate javasqltimestamp timestamp new javasqltimestampsystemcurrenttimemillis date time new datemdategettime stmtsetint1 integerparseintgetnumberbynamenametrim stmtsetstring2 name stmtsetdate3 time stmtsettimestamp3 timestamp stmtsetstring4 selection stmtsetstring5 na action stmtexecute catch sqlexception e todo autogenerated catch block eprintstacktrace catch parseexception e todo autogenerated catch block eprintstacktrace return action,"['java', 'mysql']" +716450,pager sliding tabstrip in ios i would like to use pager sliding tabstrip in my projectpager sliding tapstrip is there for android can we define like this i have taken one scroll view added subviews on it for tables and take one uivew added buttons as subviews and added uilabel as subview for tabstrip while using the scrollview means dragging the scrollview the tabsrip has to be movedi have been stuck to this concept and i am not getting any idea to solve this issue how do i get this concept please give any idea to me anyone,['ios'] +716621,how is it parsed constructing unnamed temporary with braced init list i recently yet again encountered the notation const int10 10 9 8 7 6 5 4 3 2 1 as i recall it is permitted in both c and c but via quite different language mechanismsi believed that in c the formal view is that it is a construction of an unnamed temporary via an epxlicit type conversion t castexpression that would reduce to a static cast that constructs an object via c11 a5294 an expression e can be explicitly converted to a type t using a static cast of the form static castte if the declaration t te is wellformed for some invented temporary variable t 85however the castexpression syntax is defined by c11 a542 as being either unaryexpression or recursively a typeid castexpression where the single base case is reduction to unaryexpressionand as far as i can tell a braced initlist is not an expressionan alternative view could be that its an explicit type conversion via functional notation c11 a5233 a simpletypespecifier or typenamespecifier followed by a bracedinitlist creates a temporary object of the specified typebut as far as i can tell a simpletypespecifier cant involve parentheses and a typenamespecifier involves the keyword typename,['c++'] +716868,convert youtube api v3 video duration in php how do i convert pt2h34m25s to 23425i searched and used this code i am new to regex can someone explain this and help me with my issuefunction covtimeyoutube time preg match alldyoutube timeparts hours floorparts0060 minutes parts0060 seconds parts01 ifhours 0 return hoursminutesseconds else return minutesseconds but this code only give me hhmm so dumb found the solution function covtimeyoutube time preg match alldyoutube timeparts hours parts00 minutes parts01 seconds parts02 ifseconds 0 return hoursminutesseconds else return hoursminutes,['php'] +717012,rails nested includes on active records i have a list of events that i fetchi am trying to include every user associated to this event and every profile associated to each user the users get included but not their profileshow would i do thiseventincludesusers profilethe docs do not seem to be clear record queryinghtml,['ruby-on-rails'] +717233,exit1 in file results in script status code 0 on ubuntu machine php vphp 55101dotdeb1 cli built mar 6 2014 1859 copyright c 19972014 the php groupzend engine v250 copyright c 19982014 zend technologies with uopz v204 copyright c 2014 by joe watkins with zend opcache v703 copyright c 192014 by zend technologies with xdebug v223 copyright c 20022013 by derick rethansmy testphp file is simple php exit1 i would expect this command php testphp echo error to show error but it exits with status code 0 php testphp echo 0but on the same machine the same code but not in file works as expected php r exit1 echo errorerroror php r exit1 echo 1on different machine archlinux with phpphp 5513 cli built may 29 2014 054658 copyright c 19972014 the php groupzend engine v250 copyright c 19982014 zend technologiesall cases work as expected even when the code is run from file the status code is 1 this is a true problem because git hooks depends on this status codes and jenkins and i could not google it out could it be somehow configrelated i checked cli phpini and could not find anything suspicious,['php'] +717236,expressionlike in c eg x xname gi have code block like this public expressionfunctentity bool searchexpression var c new constantexpression paramlistcount var b new binaryexpression paramlistcount binaryexpression comparisonexpression null var entity expressionparametertypeoftentity for int i 0 i paramlistcount i var value convertchangetype paramlistiitem2 g paramlistiitem3 systemstring ci expressionconstantvalue g problem is here bi expressionequalexpressionpropertyentity paramlistiitem1 name ci problem is here paramlistclear comparisonexpression baggregateexpressionand return expressionlambdafunctentity boolcomparisonexpression entityworks like charm but i need expressionlike like g not equal gexpressionlikeexpressionpropertyentity paramlistiitem1 cibut c expression tree does not support like method update i wrote something like this expressioncallexpressionpropertyentity paramlistiitem1 typeofstringgetmethodcontains new expression ci but i need binaryexpression not methodcallexpression,['c#'] +717378,error in resource configuration expected response to contain an object but got an array i have an angular response that expects an array and the service call passes an arraycan see it in network tab of chrome dev toolsbut i am getting the following error in chrome consoleerror in resource configuration expected response to contain an object but got an arrayhere is my angular service physicalservermodulefactoryphysicalserverservices resourcefunction resource var host appgeneralhost var port appgeneralport var serveritempath v1physicalserverx var serverpath v1physicalserverlist return physicalserver function return resourcehost serverpath query method get isarray true create method post and i am calling my service as belowvar tileservicecall physicalserverservicesphysicalservertileservicecallgetpromisethenfunction response appmetaphysicalservertileitems jsonstringifyresponse function error alerterrormy angularjs version is 1215can someone point me the root cause,['javascript'] +717417,python can reduce be translated into list comprehensions like map lambda and filter when programming in python i now avoid map lambda and filter by using list comprehensions because it is easier to read and faster in execution but can reduce be replaced as welleg an object has an operator union that works on another object a1uniona2 and gives a 3rd object of same typei have a list of objectsl a1 a2 a3 how to have the union of all these objects with list comprehensions the equivalent ofresult reducelambda a b aunionb l1 l0,['python'] +717418,detect if the phone is in pocket or not this question is not exactly about code but rather implementationi am working on an app that requires to check if the phone is in pocket or not i have a simple algorithm to detect user steps when walking the problem is movement in hand can also be registered as a step eg when user runs the app and zeros the step values from the time that heshe does this to the point that the phone is in pocket the app registeres a few stepsmy idea is to check proximity sensor and see if the phone is in pocketwhat i do with accelerometer sensor is that i continuesly read the accelerometer values in a buffer when the buffer gets full then i calculate the steps while calculating the buffer is still accepting new accelerometer readingssince i heard that proximity sensor is interrupt based and not pollbased like acc sensor is how can i coordinate these two togetheris it safe to say if i check proximity before writing acc values into buffer and check it again when calculation starts if proximity was not in far mode i can assume the phone was in the pocketany suggestion is welcome,['android'] +717482,nested promises in bluebird i am trying to figure out how to use promises correctly with the bluebird library i have come across some nested promises in my code and i noticed that in the bluebird docs it readsif you are utilizing the full bluebird api offering you will almost never need to resort to nesting promises in the first place there are many other blog posts about promises being misused and nesting is a regular antipatternloadcarsomeuri jqxhr thenfunction car if carhasfourdoorscar loadmakecarmake thenfunction make loadmodelmakemodel thenfunction model loadcardetailsmodel else if carhastwodoorscar loadmodelmakemodel thenfunction model loadcardetailsmodel all of my functions return objects looking at the bluebird docs it seems like there are multiple helper methods all join propsso my question is how could i avoid the nesting if there are dependencies perhaps this is my misunderstanding of the asynchronous nature of promises could something like this workpromisealoadcarsomeuri loadmakecarmake loadmodelmakemodel thenfunctioncar make model do logic,['javascript'] +717495,use camera for both native and web app with ionicangularjs and cordova i am trying to use the camera and i would like to know if you have any exemple on how to make it work on both web nativei have this piece of code borrowed from the ngcordova doc scopetakepicture function var options quality 75 destinationtype cameradestinationtypedata url sourcetype camerapicturesourcetypecamera allowedit true encodingtype cameraencodingtypejpeg targetwidth 100 targetheight 100 popoveroptions camerapopoveroptions savetophotoalbum false cordovacameragetpictureoptionsthenfunctionimagedata success image data is here functionerr an error occured show a message to the user when i use it it works well with my device but catch an error with the web version referenceerror camera is not definedthat is why i ask if you have any good way to do that i could simulate a click on an hidden input but it does not look pretty if you have any idea,['javascript'] +717517,swiperefreshlayout behind actionbar when using a swiperefreshlayout in combination with a overlay mode actionbar the loading animation will be thisplayed behind the actionbar making it almost invisibleis there anything i can do to show it on top of the actionbar,['android'] +717604,is it a defect to center a simulation in 05 05 05 with a box size of 1 i am a numerical physicist and i have seen some simulation codes in my community which use a 3d simulation box with a center in 05 05 05 and a normalized length of 1 so the box coordinates goes from 0 to 1 in this box a lot of physical computations are performed and generally the best possible precision is requiredi think that doing a such thing can be viewed as a defect but i would like to have the confirmation of that i tends to think this is a defect because as we have more numerical precision near 0 the numerical accuracy is not well balanced in the whole boxto have a good balance i think that such a box should be centered around 0 going from 05 to 05 if one wants a symmetric accuracy around the center of the boxshould be centered around 15 going from 1 to 2 if one wants a quasihomogeneous accuracy in the entire boxam i correct or completely wrong,['c++'] +717625,what is wrong with the implementation of nscoding protocol in swift i thought i would be cautious and try out swift on an existing objc project by converting one class and a small simple one at that oh deartransliterating the original objc into swift should be straightforward and so it seemed unfortunately whilst the encoder to persistent store seems to work it crashes with an exc breakpoint error at the first line of the init coderif and the caps are intentional nscodingswift gives the same persistent content as nscodingobjc then my all objc version should be able to read what is encoded by swift and vice versa this proves not to be the case and my perfectlyfunctioning objc version crashes out when it tries to read the persistent store from the swift version surely if nscoding is implemented correctly it ought to generate something in one that is readable in tother otherwise there ought to be separate nscodingswift and nscodingobjc protocolsso to summarise i can readwrite in objc i cannot writeobjc and readswift and i can writeswift readobjc and i cannot readwrite in swifthere are the two versionslet keybeaconitemnamekey namelet keybeaconitemuuidkey uuidlet keybeaconitemmajorvaluekey majorlet keybeaconitemminorvaluekey minorimport uikitimport corelocationclass smbeaconitem nsobject nscoding var name string var uuid nsuuid var major nsnumber var minor nsnumber initnewname string newuuid nsuuid newmajor nsnumber newminor nsnumber name newname uuid newuuid major newmajor minor newminor init coder decoder nscoder name decoderdecodeobjectforkeykeybeaconitemnamekey as string uuid decoderdecodeobjectforkeykeybeaconitemuuidkey as nsuuid major decoderdecodeobjectforkeykeybeaconitemmajorvaluekey as nsnumber minor decoderdecodeobjectforkeykeybeaconitemminorvaluekey as nsnumber func encodewithcoder encoder nscoder encoderencodeobjectname forkeykeybeaconitemnamekey encoderencodeobjectuuid forkeykeybeaconitemuuidkey encoderencodeobjectmajor forkeykeybeaconitemmajorvaluekey encoderencodeobjectminor forkeykeybeaconitemminorvaluekey and the working originalimplementation smbeaconitem instancetypeinitwithnamensstring name uuidnsuuid uuid majorclbeaconmajorvaluemajor minorclbeaconminorvalueminor self super init if self return nil name name uuid uuid majorvalue major minorvalue minor return selfpragma mark persistence instancetypeinitwithcodernscoder adecoder self super init if self return nil name adecoder decodeobjectforkeykeybeaconitemnamekey uuid adecoder decodeobjectforkeykeybeaconitemuuidkey majorvalue adecoder decodeobjectforkeykeybeaconitemmajorvaluekey unsignedintegervalue minorvalue adecoder decodeobjectforkeykeybeaconitemminorvaluekey unsignedintegervalue return self voidencodewithcodernscoder acoder acoder encodeobjectselfname forkeykeybeaconitemnamekey acoder encodeobjectselfuuid forkeykeybeaconitemuuidkey acoder encodeobjectnsnumber numberwithunsignedintegerselfmajorvalue forkeykeybeaconitemmajorvaluekey acoder encodeobjectnsnumber numberwithunsignedintegerselfminorvalue forkeykeybeaconitemminorvaluekeyendthanks for any help you can give,['objective-c'] +717628,java malformed url exception i am trying to make an http post request in an android app i am building but no matter what url i use for the request eclipse keeps raising a malformed url exception i have tried a line of code from one of the android tutorialsurl url new urland even that triggers the error is there a reason eclipse keeps raising this error for any url i try to create,"['java', 'android']" +717646,eclipse luna a autoindent is inconsistent i upgraded to luna and have a problem with autoformatting more specifically autoindentation the about eclipse dialog verifies that i am running 440when the code autoindents on save it seems to jump back and forth between two different ways of indenting it regarding the number of spaces note the level of indentationdosomething arg0 arg1 anddosomething arg0 arg1 this is extremely annoying when using scm like git whats causing this how can it be fixed,['java'] +717652,what happened to the real cassandra c library libcql is there any legitimate maintained c library for interacting with cassandra this is a thisambiguation question of sorts searching for such software always leads to the datastax cppdriver a bizarre and misleading name herewhats odd about this though is that libcql preceded it and now the libcql page directs to cppdriver stating that is no longer maintained iebut the cppdriver code seems totally different than what libcql was in fact the example code in cppdriver does not appear to be c at all more like plain c and has no incode commenting it appears to be a completely different and less mature project yet datastax still refers to it as being c furthermore it seems to be the only maintained project that provides c andor c interfacing with cassandra what happened to libcql why did it undergo some weird transformation once it was turned over to datastax,['c++'] +717703,nodejs express static server hangs on images chrome only this is a really strange bug that has been bothering me for ages i have a basic website that uses express static middleware in addition to separate routes that render jadeheres my configappsetviews dirname viewsappsetview engine jadeappusestylusmiddleware src dirname public dest dirname public compile functionstr path return stylusstr setfilename path setcompress true usenib appusebodyparserurlencoded extended false appusebodyparserjsonappusecookieparserappusesession secret confsessionsecret store new rethisstore saveuninitialized true resave trueappuseexprestatic dirname publicheres my issue after precisely 5 refreshes in a single tab in chrome image files refuse to load all other content is fine just images and just in chrome in order to remedy this you have to open a new tab i have tested this in firefox as well no issues this error does not just happen in this application it is happened in many of my others as wellas this project is currently in development i would rather not put in online as an example rest assured this is completely reproducible any ideasupdate i updated to express 4 on the slim chance that updating might fix my issue it did not you can see a screen cast i made of the issue hereupdate to test if the issue was with static server i modified my code to be like thisappgetimg function reqres consolelogrequrl consolelogpathextnamerequrl if imgextindexofpathextnamerequrl 1 ressendfilepublicrequrl appuseexprestatic dirname publicthis had no effect so i am thinking this issue is either clientside or a bug with chrome,['javascript'] +717741,typescript error runtime error cannot read property prototype of undefined when extending so i am getting the above error in the console it is caused by super being undefined when it is passed to extends in the generated jsheres some test code that can be used to reproduce the errorthis is the entirety of the file testtsmodule test export class test1 public name string public number number constructor then in a separate file i have a class that inherits from that one reference pathtestts module test export class test2 extends test1 constructor super the reference path should not be needed and is not but i added it to see if it helped it did notthe files are included in the correct order testts then test2ts via bundleconfig running with or without optimisations does not have any effecti am probably being a giant noob but i have not the slightest clue what i have messed up all the other instances of this problem i have found online are from folks using the command line compiler to combine multiple typescript files into one single file i am using the bundler to do that but even when i do not combine them i get the exact same issueplease help me i am at my wits endas requested heres the compiled javascripttestjsthis is the entirety of the file testtsvar testfunction test var test1 function function test1 return test1 testtest1 test1test test sourcemappingurltestjsmaptest2jsvar extends this extends function d b for var p in b if bhasownpropertyp dp bp function thisconstructor d prototype bprototype dprototype new reference pathtestts var testfunction test var test2 function super extendstest2 super function test2 supercallthis return test2 testtest1 testtest2 test2test test sourcemappingurltest2jsmap,['javascript'] +717765,is maptodouble really necessary for summing a list with java 8 streams as far as i can tell the way to sum a listdouble using java 8 streams is thislistdouble vals double sum valsstreammaptodoubledoubledoublevaluesumto me the maptodoubledoubledoublevalue seems kind of crufty just the sort of boilerplate ceremony that lambdas and streams were supposed to thispense withbest practices tell us to prefer list instances over arrays and yet for this sort of summing arrays seem cleanerdouble vals double sum arraysstreamvalssumgranted one could do thislistdouble vals double sum valsstreamreduce00 ij ijbut that reduce is so much longer than sumi get that this has to do with the way streams need to be retrofitted around the javas nonobject primitives but still am i missing something here is there some way to squeeze autoboxing in to make this shorter or is this just the current state of the artupdate answers digesthere is a digest of answers below while i have a summary here i urge the reader to peruse the answers themselves in fulldasblinkenlight explains that some kind of unboxing will always be necessary due to decisions made further back in the history of java specifically in the way generics were implemented and their relationship to the nonobject primitives he notes that it is theoretically possible for the compiler to intuit the unboxing and allow for briefer code but this has not yet been implementedholger shows a solution that is very close to the expressiveness i was asking aboutdouble sum valsstreamreduce00 doublesumi was unaware of the new static doublesum method added with 18 it seems intended for the very purpose i was describing i also found doublemin and doublemax going forward i will definitely use this idiom for such operations on listdouble and similar,['java'] +717875,android manifest placeholders for different build types i am very hyped about the new possibility of manifest placeholders in gradle android build i have found in the gradle documentation that i can specify my own placeholders like thisproductflavors free pro manifestplaceholders activitylabelproname but i would like to have one placeholder dependent on build type and not on product flavors when i insert that placeholder specification into build type settings it takes no effect do you know how to achieve this because it seems to me stupid have three build types and three flavors associated with it thanks,['android'] +717895,is it possible to create custom viber stickers i have been thinking about developing my own custom viber sticker but i cannot get to any good source to give me some information about thisdoes anyone know how to do this or is it possible at all if yes please let me know what do i need to do sothanks,['android'] +717920,get device token in ios 8 i need device token to implement push notification in my apphow can i get device token since didregisterforremotenotificationswithdevicetoken method is not working on ios 8i tried this code in app delegate but it is not giving me device token uiapplication sharedapplication registerusernotificationsettingsuiusernotificationsettings settingsfortypesuiusernotificationtypesound uiusernotificationtypealert uiusernotificationtypebadge categoriesnil uiapplication sharedapplication registerforremotenotifications,['ios'] +717997,generate a uuid on ios from swift in my ios swift app i want to generate random uuid guid strings for use as a table key and this snippet appears to worklet uuid cfuuidcreatestringnil cfuuidcreatenilis this safe or is there perhaps a better recommended approach,['ios'] +718005,identity 20 with custom tables i am new to aspnet identity and am still trying to get my head around how it all works unfortunately i have found many of the tutorials i have tried are for identity 10 whereas i am attempting to work with identity 20the biggest problem i am facing is something i thought would be simple but has turned out not to be what i am trying to do is use an existing database with an existing user table currently all i can seem to do is get identity to create it is own tables to store user data i do not want to use entity framework but i have had great difficulty separating entity framework from identity 20while my situation i am using sql server i thought i would try and implement the custom provider for mysql at this link and this appears to work under identity 1 only there does appear to be a newer one however that uses entity framework i have also tried with everything i have tried i get stuck with the following linevar manager new identityusermanagernew userstoreidentityusercontextgetapplicationdbcontextthe problem i am facing is that i need to remove applicaitondbcontext class according to the instructions for ravendb however i do not know what to put in this line insteadthe errors i get arethe nongeneric type aspnetidentitymysqluserstore cannot be used with type argumentsandthe type or namespace name applicationdbcontext could not be found are you missing a using directive or an assembly referencethe second error is to be expected however i am not sure what to use in this line of code instead has anyone had any experience with implementing a custom provider without using entity frameworkthanksupdate 1i have attempted the following tutorial but it appears to be incomplete with compile or runtime errors when following the tutorial exactly a few problems i still have arewhen replacing all instances of applicationuser with user have a problem with the following line in identityconfigcsvar manager new applicationusermanagernew userstoreapplicationusercontextgetmydbcontextchanging applicationuser to user produces the following errorthe type webapplicationtest2modelsuser cannot be used as type parameter tuser in the generic type or method microsoftaspnetidentityentityframeworkuserstore there is no implicit reference conversion from webapplicationtest2modelsuser to microsoftaspnetidentityentityframeworkidentityuseri am also having difficulty working out how to use the user manager and many of the async methods the following lines do not workauthenticationmanagersigninnew authenticationproperties ispersistent ispersistent await usergenerateuseridentityasyncusermanagerin accountcontrollercs with the following errorsthe best overloaded method match for microsoftowinsecurityiauthenticationmanagersigninmicrosoftowinsecurityauthenticationproperties params systemsecurityclaimsclaimsidentity has some invalid argumentswebapplicationtest2modelsuser does not contain a definition for generateuseridentityasync and no extension method generateuseridentityasync accepting a first argument of type webapplicationtest2modelsuser could be found are you missing a using directive or an assembly reference,"['c#', 'asp.net']" +718025,how wifi and mobile data both work simultaneously in android for obd2 device i am developing application which connect obd2 device by wifi and app can read speedrpmengine coolant temperature details etc in androidso wifi is used only for connecting with obd2 deviceit does not have facility to connect with internetonly for communicating and communicate with itnow i need internet connection for web servicesbut after connecting my wifi i am not able to connect internet via my mobile data network in android the similar application is also developed for ios now in ios i can use application by wifi static wifi setting and internet connection from my cellular network it means configure my wifi with some static ip i am able to use mobile data network for internet connection in iosbut in android if i use static wifi and check for internet connection it is not availablehow can i use wifi and internet connection both run parallel or any other way by configuring wifi settings in android any help would be appreciated,['android'] +718196,how to deal with pylints toomanyinstanceattributes message i have just tried to lint some code with pylint and the last remaining error isr0902 toomanyinstanceattributes 87i understand the rationale behind limiting the number of instance attributes but seven seems a bit low i also realise that the linter should not have the last word however i would like to know what i should be doing instead ofdef init self output filenone output dirnone set the frobnicator up along with default geometries selfmargin 30 selfpos 0 0 selfsep 5 5 selfcell 20 20 selffrobbr libraryfrobbr page selffrobbrget settingspage selflim pageget width selfmargin pageget height selfmargin selffilename output file selfmoddir output dirshould i package the geometries up into a dict do something else to stop pylint complaining or just ignore it which i do not really want to do,['python'] +718209,trouble connecting to lg phone with adb mac os x 1075 when i run adb devices there are no devices showing as connected my device is a lg optimus exceed 2 running 442there are many of these posts around so heres what i have donei am using the cord that came with the phone it charges and tries to sync photos so it is not an issue here switching usb ports and trying a powered usb hub does not affect it eitheri have added the vendor id 0x1004 to androidadb usbinirestarted and unplugged any combination of things you can think ofusb debugging is on and has been restarted same with unknown sourcesi have never used easytether nor is it installed anywhere on my computerupdated adb updated my sdkrestarted adb servertried installing lgs drivers they say they do not support mac sw upgrade yet they have a package to install no help therei have a nexus s running 41 that works and an old lg phone running gingerbread that connectany wizards out there whove already struggled with this who have advice,['android'] +718227,ambiguous overload for operator using move assign and pass by value copy assign if i define a copy assignment operator that invokes the copy constructor using pass by value for class thingthing operator thing x and a move assignment operator for the same classthing operator thing x trying to invoke the move assignment results in an error from gccerror ambiguous overload for aoperatora operand types are athinga and astdremove referencethingtype aka thingahowever if the copy assign instead uses pass by referencething operator thing x compilation is fine and both operators can be invoked why is this complete c11 test codeinclude iostreaminclude utilityusing namespace stdclass thing public thing thing thing x cout copy constructorn thing thing x cout move constructorn thing operator thing x cout copy assign using pass by valuen return this thing operator thing x cout move assignn return this int main void thing a b invoke move assignment a moveb return 0,['c++'] +718241,clickonce wpf application with custom and default prerequisites i have a net 4 wpf clickonce app that has net framework 4 vc 2013 runtime libraries and windows installer 45 as prerequisites i now have to add vc 2010 librariesi have followed the steps here to create a custom prerequisite package in visual studio the package shows up in my prerequisite list however the installer is not attempting to install the vc2010 packageproductxmlpackagexmli have downloaded the vcrethist x86exe into the package directory however i am unsure what to set under specify the install location for prerequisites since i am now mixing custom and default prereqs any assistance would be much appreciatededit i have logged my clickonce installation and see nothing referencing the vc package at all no errors or anything,['c#'] +718251,how does interval comparison work somehow this worksdef in rangemin test max return min test maxprint in range0 5 10 trueprint in range0 15 10 falsehowever i cannot quite figure out the order of operations here let us test the false caseprint 0 15 10 falseprint 0 15 10 trueprint 0 15 10 trueclearly this is not resolving to a simple order of operations issue is the interval comparison a special operator or is something else going on,['python'] +718257,roslyn and net runtime version is it possible to use roslyn compiler and new features of c 60 with old versions of net runtime for example net 40for example i want use the expressionbodied members int s x y instead of int s get return x y in net 40 application,"['c#', '.net']" +718265,phantomjs dies by high memory consumption we are using phantomjs to run our qunit tests page on our tfs build server our version of test runner is built from below example over a period of time number of tests increased from hundreds to couple of thousands and on a fine day phantomjs started crashing it literally dies saying upload the dump and when you see the dump it 0kb when we took a closer look at it on process explorer we found that memory consumption by phantomjs keeps going up as phantomjs is running tests and eventually crashes somewhere 833mb yes the same amount of memory was being utilized by chrome and ie and yesyes our tests were leaking memory we did fixed it memory utilization is lowered by 50 on chrome and ie and we expected phantomjs will handle it now but no phantomjs still kept crashing process explorer shows same memory consumption according to above documentation phantomjs releases heap allocation just on close could that be the reason why our fixed test consumed less memory on chrome but not phantomjs and last how to fix this how to make phantomjs keep garbage collecting javascript objects to reduce heap allocation update 1 0728we took a work around i did modified my script to execute my tests module by module in loop after executing all tests for a module i call pageclose so it releases the memory for each module and never keeps building the dead heap of objects not closing this question since since its a workaround and not a solution hope creators will fix this sometime,['javascript'] +718274,how to define extern variable along with declaration wiki says the extern keyword means declare without defining in other words it is a way to explicitly declare a variable or to force a declaration without a definition it is also possible to explicitly define a variable ie to force a definition it is done by assigning an initialization value to a variable that means an extern declaration that initializes the variable serves as a definition for that variable so just for testing purpose only include stdiohextern int y 0int main printfdn y return 0should be valid compiled in c11 but when compiled with options wall wextra pedantic stdc99 in gcc 472 produces a warning warning y initialized and declared extern enabled by defaultwhich should not afaik extern int y 0 is effectively the same as int i 0 whats going wrong here,['c'] +718309,build failed after updating tools for android l i cannot build my project after updating the tools i get this error in android studiobuildexplodedaarcomandroidsupportsupportv42100rc1androidmanifestxml3 failed to parse must be an integer number or codename any ideasthis manifest is from the support library i think i also have another for my project which is min14 target19xml version10 encodingutf8 copyright c 2014 the android open source project licensed under the apache license version 20 the license you may not use this file except in compliance with the license you may obtain a copy of the license at unless required by applicable law or agreed to in writing software thistributed under the license is thistributed on an as is basis without warranties or conditions of any kind either express or implied see the license for the specific language governing permissions and limitations under the licensemanifest xmlnsandroid packageandroidsupportv4 usessdk androidminsdkversionl androidtargetsdkversionl application manifestgradle classpath comandroidtoolsbuildgradle09,['android'] +718313,xcode 6 beta 2 issue with exporting ipa your account already has a valid ios thistribution certificate i am having trouble exporting an app for ad hoc thistribution on xcode 6 beta 2when exporting my project for ad hoc development on xcode 6 i receive this alert i have tried exporting it on xcode 5 and had no problems at all saving the ipa is anyone experiencing this problem as well,"['ios', 'iphone']" +718320,manifest merger failed usessdkminsdkversion 14 since downloading the latest sdk and installing android studio my project fails to build i get the following messageerrorgradle execution failed for task sampleprojectprocessproddebugmanifest manifest merger failed usessdkminsdkversion 14 cannot be smaller than version l declared in library comandroidsupportsupportv42100rc1,['android'] +718428,xamarin zipalign not found when hitting the play button in xamarin i receive this errorcprogram files x86msbuildxamarinandroidxamarinandroidcommontargets22 error msb6004 the specified task executable location cusersopappdatalocalandroidandroidsdktoolszipalignexe is invalid msb6004 helloworldwhen looking at the file path i do not see a zipalignexe in the folder also the double seems mysteriousi just installed xamarin so maybe it was a bad installationcan i turn off zipalign,['android'] +718432,why do unawaited async methods not throw exceptions i thought that async methods were supposed to behave like normal methods until they arrived at an awaitwhy does this not throw an exception is there a way to have the exception thrown without awaitingusing systemusing systemthreadingtaskspublic class test public static void main var t new test thelper public async task helper throw new exception,"['c#', '.net']" +718433,copy observablelist java i have a masterdata which is an observablelist and filtereddata which is also an observablelist then i want to use it to show the filtered data when the filter is set but also to be able to recover whenever necessary here is the mcvepackage brimport javafxcollectionsfxcollectionsimport javafxcollectionsobservablelistpublic class main private static observablelistfoo masterdata fxcollectionsobservablearraylist private static observablelistfoo filtereddata fxcollectionsobservablearraylist static filter filter new filter public static void adummy masterdataaddnew fooa1 masterdataaddnew fooaa3 masterdataaddnew foob2 masterdataaddnew foobb4 masterdataaddnew fooc3 public static void printdataobservablelistfoo list forfoo f list systemoutprintlnfgetname public static void mainstring args adummy applyfilter3 printdatafiltereddata applyfilter0 printdatafiltereddata public static void applyfilterint num filtersetdatamasterdata filtersetfilternum filtereddata filtergetdata the class filter which i use to filter the datapackage brimport javautilarraylistimport javautillistimport javafxcollectionsfxcollectionsimport javafxcollectionsobservablelistpublic class filter private observablelistfoo data fxcollectionsobservablearraylist public void setfilterint filter listfoo copy new arraylistfoodata forfoo f copy iffgetbarfilter dataremovef public observablelistfoo getdata return data public void setdataobservablelistfoo data thisdata data and the foo class which is just a string name and a int bar plus getters setterspackage brpublic class foo private string name private int bar public foostring name int bar thissetbarbar thissetnamename public string getname return name public void setnamestring name thisname name public int getbar return bar public void setbarint bar thisbar barwhen you run this code you will get aa bb cboth when the filter was set to 3 which filtered the data as expected and after the filter was reseted to zerohow can i make sure the filter is always processed with the data in the masterdata and then stored on the filtereddata note this is for a javafx project so i really need to use the observablelist,['java'] +718520,is stdswapx x guaranteed to leave x unchanged this question is based on thiscussion below a recent blog post by scott meyersit seems obvious that stdswapx x should leave x unchanged in both c98 and c11 but i cannot find any guarantee to that effect in either standard c98 defines stdswap in terms of copy construction and copy assignment while c11 defines it in terms of move construction and move assignment and this seems relevant because in c11 and c14 17649 says that moveassignment need not be selfassignmentsafeif a function argument binds to an rvalue reference parameter the implementation may assume that this parameter is a unique reference to this argument note if a program casts an lvalue to an xvalue while passing that lvalue to a library function eg by calling the function with the argument movex the program is effectively asking that function to treat that lvalue as a temporary the implementation is free to optimize away aliasing checks which might be needed if the argument was an lvalue aend note the defect report that gave rise to this wording makes the consequence clearthis clarifies that move assignment operators need not perform the traditional if this rhs test commonly found and needed in copy assignment operatorsbut in c11 and c14 stdswap is expected to use this implementationtemplatetypename tvoid swapt lhs t rhs auto tempstdmovelhs lhs stdmoverhs rhs stdmovetemp and the first assignment is performing an assignment to self where the argument is an rvalue if the move assignment operator for t follows the policy of the standard library and does not worry about assignment to self this would seem to court undefined behavior and that would mean that stdswapx x would have ub as wellthat is worrisome even in isolation but if we assume that stdswapx x was supposed to be safe in c98 it also means that c14s stdswap could silently break c98 code so is stdswapx x guaranteed to leave x unchanged in c98 in c11 if it is how does this interact with 17649s permission for moveassignment to not be selfassignmentsafe,['c++'] +718525,azure notification hub registered device list i am following this post to work with azure notification hub what i am trying to do is creating the web api that registers the devices with the azure notification hub when i send the request for registering the device as shown in the article it hits the azure notification hubbelow is the screen shot of my azure portal which shows there was a request for registrationbut when i try to get the details of the registered devices using the following code it is always 0 var registrationscount await hubgetallregistrationsasyncint32maxvaluereturn registrationscountcounttostringnow i have few questions 1 how can i explore the registered device details 2 how i can i send a test notification to the ios devices from back end below is the code that i am using to send test notifications var payload stringformattoasttemplate message hubsendapplenativenotificationasyncpayload worldnews3 if i am using the web api as back end is it necessary to configure the ios app details in azure notification hub ie uploading the certificate and other details on azure portal,['ios'] +718680,difference between windowopendatabase and windowsqlitepluginopendatabase functions using cordova version 3x and android version 2x to 4xi am wonderingis my understanding correct that all android devices by default have an sqlite programinterface for creating sqlite databasedo both the above database function calls create a sqlite database in the deviceif the above answer is no then what type of database do both the above function calls createif the answer is yes then is windowsqliteopendatabase function wrapper around windowopendatabaseare the databases created by the call persistent that is is the data available after closing and reopening the cordova packaged appsis there a maximum the database size that can be created by the above two methods,['android'] +718693,how to make bootstrap panel body with fixed height i am using bootstraps panel to thisplay text and image but as the text grows the body of the panel also increases i want to know how to create the body with fixed height eg 10 rows or at most 10 rows here is my codediv claspan4 div classpanel panelprimary div classpanelheadingjhdsahfjhdfhsdiv div classpanelbodyfdoinfds sdofjohisdfjdiv divdiv,"['html', 'css']" +718738,exception raised during rendering javalangsystemarraycopy i have a strange problem with the new adt version i have downloaded the new eclipse from eclipseorg then i install adt on it everything works fine i can create a project for android and all thing work well exceptwhen trying to create one xml layout i get the following errorexception raised during rendering javalangsystemarraycopyand in the error log i seefailed to render set of icons for analogclock autoncompletetextview button smallbutton ff i change edittext to textview the error thisappears i can run my program even with this warning but i want to see my layout in graphical sectionmy layout isxml version10 encodingutf8linearlayout xmlnsandroid androidlayout widthmatch parent androidlayout heightmatch parent androidbackgrounddrawablesettingback androidorientationvertical androidweightsum480 linearlayout androidlayout widthmatch parent androidlayout height0dp androidlayout weight50 androidgravityright androidorientationhorizontal button androidididclose androidlayout width50dp androidlayout heightmatch parent androidbackground0 linearlayout view androidididview1 androidlayout widthwrap content androidlayout height0dp androidlayout weight20 linearlayout androidlayout widthmatch parent androidlayout height0dp androidlayout weight40 androidorientationhorizontal androidweightsum320 view androidididview8 androidlayout width0dp androidlayout heightmatch parent androidlayout weight40 edittext androidididtextview1 androidlayout width0dp androidlayout heightmatch parent androidlayout weight240 androidgravitycenterright androidbackground0 view androidididview9 androidlayout width0dp androidlayout heightmatch parent androidlayout weight40 linearlayout view androidididview2 androidlayout widthmatch parent androidlayout height0dp androidlayout weight20 linearlayout androidlayout widthmatch parent androidlayout height0dp androidlayout weight35 androidorientationhorizontal view androidididview10 androidlayout width0dp androidlayout heightmatch parent androidlayout weight40 edittext androidididtextview2 androidlayout width0dp androidlayout heightmatch parent androidlayout weight240 androidgravitycenterright androidbackground0 view androidididview11 androidlayout width0dp androidlayout heightmatch parent androidlayout weight40 linearlayout view androidididview3 androidlayout widthwrap content androidlayout height0dp androidlayout weight10 linearlayout androidlayout widthmatch parent androidlayout height0dp androidlayout weight35 androidorientationhorizontal view androidididview12 androidlayout width0dp androidlayout heightmatch parent androidlayout weight40 edittext androidididtextview3 androidlayout width0dp androidlayout heightmatch parent androidlayout weight240 androidgravitycenterright androidbackground0 view androidididview13 androidlayout width0dp androidlayout heightmatch parent androidlayout weight40 linearlayout view androidididview4 androidlayout widthwrap content androidlayout height0dp androidlayout weight105 linearlayout androidlayout widthmatch parent androidlayout height0dp androidlayout weight40 androidorientationhorizontal view androidididview14 androidlayout width0dp androidlayout heightmatch parent androidlayout weight40 edittext androidididtextview4 androidlayout width0dp androidlayout heightmatch parent androidlayout weight240 androidgravitycenterright androidbackground0 view androidididview15 androidlayout width0dp androidlayout heightmatch parent androidlayout weight40 linearlayout view androidididview5 androidlayout widthmatch parent androidlayout height0dp androidlayout weight5 linearlayout androidlayout widthmatch parent androidlayout height0dp androidlayout weight40 view androidlayout width0dp androidlayout heightmatch parent androidlayout weight40 edittext androidididtextview6 androidlayout width0dp androidlayout heightmatch parent androidlayout weight240 androidgravitycenterright androidbackground0 view androidlayout width0dp androidlayout heightmatch parent androidlayout weight40 linearlayout view androidididview6 androidlayout widthmatch parent androidlayout height0dp androidlayout weight20 linearlayout androidlayout widthmatch parent androidlayout height0dp androidlayout weight30 androidorientationhorizontal androidweightsum320 view androidididview16 androidlayout width0dp androidlayout heightmatch parent androidlayout weight90 checkbox androidididshake androidlayout width0dp androidlayout heightmatch parent androidlayout gravitycenter androidlayout weight70 androidgravitycenter view androidlayout width0dp androidlayout heightmatch parent androidlayout weight10 checkbox androidididring androidlayout width0dp androidlayout heightmatch parent androidlayout gravitycenter androidlayout weight70 androidgravitycenter view androidididview17 androidlayout width0dp androidlayout heightmatch parent androidlayout weight80 linearlayout view androidididview7 androidlayout widthmatch parent androidlayout height0dp androidlayout weight30 linearlayouti searched for an answer here but did not find any how can i fix this ps this problem happened on adt 23 i tried it with adt 226 and it worked well,['android'] +718742,how to thiscover which friends accepted invites with facebook api v20 facebook api v20 introduced the invitable friends edgean example response from a get request to this edge is data id avkgk9flfxasdvxnbdv gyogr6lxa9sklnh name anita sujarit picture data is silhouette false url 10201991701127909 302023572 tjpg looking closely at that id it is not a normal facebook user id instead it is an invite token this token is passed to the requests dialog as a value for the to parameterthe invite token returned on each of the friend objects as the value of a field named id is a unique per user and per game string of variable length the invite token is subject to expiration and may change between game sessions it is therefore not advisable to cache these results or to try to assign them to a given personthe friends edge now only returns friends already using the appmy problem is that i now have no way to crossreference which friends i have invited and which have acceptedpreviously i would have stored a friends id as i sent them an invite and at some later point checked this against a list of friends playing the game but now this is not possible for several reasonsthe invite token is not present on the friends edgeand it is dynamic anywaythe normal user id is not present on the invitable friends edgei could use the users name as a key but this is not uniqueactual questionhas anybody devised a way of determining from users that have been invited which have accepted that invite please,['ios'] +718904,how to make a realistic roulette ball spinning animation i am using physicsjs to make a 2d roulette ball spinning animation so far i have implemented the followingused a constraint so that the ball wouldnt fly awayrigidconstraintsthistanceconstraint wheel ball 1 used drag to slow down the ballworldaddphysicsintegratorverlet drag 09 made the wheel attract the ball so that it would fall towards it when the drag has slowed down the ball enoughmy questionshow do i gradually slow down the ball spinningi have already a very high drag value but it does not look like it is doing anythinghow do i make attraction towards the wheel workthe thistance constraint should keep the ball from escaping not from getting closer to the wheelwhy does angularvelocity 05 not work at all on the wheelmy code also on jsfiddlephysicsfunction world var viewwidth windowinnerwidth viewheight windowinnerheight renderer worldaddphysicsintegratorverlet drag 09 var rigidconstraints physicsbehaviorverletconstraints iterations 10 create a renderer renderer physicsrenderercanvas el viewport width viewwidth height viewheight add the renderer worldaddrenderer render on each step worldonstep function worldrender create some bodies var ball physicsbodycircle x viewwidth 2 y viewheight 2 300 vx 005 mass 01 radius 10 cof 099 styles fillstyle cb4b16 angleindicator 72240d var wheel physicsbodycircle x viewwidth 2 y viewheight 2 angularvelocity 05 radius 100 mass 100 restitution 035 cof 099 styles fillstyle 6c71c4 angleindicator 3b3e6b treatment static worldaddball worldaddwheel rigidconstraintsthistanceconstraint wheel ball 1 worldadd rigidconstraints add things to the world worldadd physicsbehaviorinteractive el rendererel physicsbehaviornewtonian strength 5 physicsbehaviorbodyimpulseresponse physicsbehaviorbodycollisiondetection physicsbehaviorsweepprune subscribe to ticker to advance the simulation physicsutiltickeronfunction time worldstep time start the ticker physicsutiltickerstart,['javascript'] +719001,why await both the asynchronous request and the reading of its contents why is it necessary in net web api to have a a method that reads the content of an http response asynchronously given that there is already a method to make the request asynchronously said another way if i am using httpclientgetasync or postasync or putasync etc is the code really any more asynchronous by also reading the content out asynchronously if so howwhyis thisusing var client new httpclient var response await clientgetasync responseensuresuccestatuscode return await responsecontentreadasasyncfoobetter than thisusing var client new httpclient var response await clientgetasync responseensuresuccestatuscode return responsecontentreadasasyncfooresultand why,['c#'] +719036,found strange indexphp on website i found a strange and obscured file indexphp at my website i do not know who placed it at my page but i would like to understand what it doesthe file has been obscured in the first place by replacing characters with hex valuesphp copyright glx4fbx41x4cx53x6bgx6ex72x77ix6ex64x62nx74xx74egeillbpx6bx47x4cox42x41lx53x63kmjx63uiex76foreach get asegeillbpx47lx4fbx41x4csx63kx6dx6acux69ex47x4cox42x41x4cx53dx78x77x71ox61lvx61x75x65x6bifpreg matchax7ax30x3910x332x21isx47x4cox42x41lsx64x78x77x71x6fx61x6cx76ax75x65xfgspywrtx6bjdhbwekx74x78x74jdhbwekbase64 decodex50x46x4edx55klqvx43bx73yx57x35x6edwfnzt1qx59x58zx68x63x32x4eyx61xx420pgx30x4bx50x43ex74lx510kx5ax6evuy3rpb2x34gx5ax32v0x62wx55ox63x33rykx510x4bx65yb2yxx49gx61wr4idx30x67x633rx79x4cmluzgvx34x542x59x6fx4ax7ax38nx4btx73x67ax57x59gx4bgx6cx6bex43a9px53ax74x4dsx6bgcx6dv0x64x58x4aux49x48x4ex30cjsgdx6dfyx49gxx6cbx69x419x49x48x4e0ci5x73zwx35x6ex64gx67x37ix48zx68x63x69bx75x5axdx66c3rx79ix440gx49x69i7x49hzx68cx69x42x70id0x67x4dtsx67x5amx39x79ix43gx72k2x6cx6bedsx67x61x57rx34x49x44wx67x62gx56x75ox79bpx5ax48gx67x4bz0x67x4dixpx4bx79x73x70dx51x70x37ihx5ahcibx6aacx41x39x49hx42hx63nx4ex6cx53wx35x30khn0x63ix35x7ax64x57x4azx64x48x49oax57x524lcx41x79ksx77x67x4dx54ypoyx42x75zxdx66x63x33ryicsx39ifnx30x63mlx75x5ayx35x6dcmx39tx51x32x68x68cx6bx4evzx47x55ox4bx47nx6fix43x73gax53kx67x4asayntyx70x4fyx429ia0kzx479jdwx31x6cbx6ex51ud3jpx64x47ux6fx62x6dx56x33x58x33x4e0cx695zdwjx7ax64hx49ox4dx43xux5ax58x64fx633x52yx4cx6dxx6cx62x6dx640x61cx30xmskx72x49lxx31mdx41ynlx1mx44x412x4e1x781mx44x41x32rlx781x4ddax32x51x6cx781x4ddx412qlx1mx44x41x7ax52fpx61wlx70x63dx54x41x77mx6ax4acx64x54ax77x4d0x4acdtax77m0ncx64tx41x77x4dx6bzcdx54awnzx4ex63dx54x41x77x4ejnx63dtx41wx4ezx4acdtx41x77x4ejlcdx54ax77x4ezx42x63dtax77nzrx63x64tax77x4d0x55ix4bx54sncx6e0x4ecx6dx64vbx32x64x73zvx39x68x5ax46x39jbx47x6cx6cbx6eqgx50x53ax69cx48vx69x4ctex30mx7ax411x4fdqx30mx44gx7amtmx34x4ex44x4dx69ox770x4bx5ax329vx5a2xlxx32x46x6bxx33dx70x5ahx52x6fx49dx30gx4ex7aix34x4fx77x30kzx32x39vz2x78lx2x46x6bx58x32x68lax57x64ox64x43ax39idkx77owx30kz29vz2x78x6cx58x32fx6bxx32zx76cx6dx31hx64x43a9x49x43i3x4dx6ax68x34otbfx59x58x4diowx30x4bx5a29x76x5ax32x78lx58x32fkx583x525cgux67px53ax69dgx56x34dfx39x70x62x57fx6ezx53x497x44qx70x6ex6229x6ex62x47x56x66yx57rfx59x32hhx62x6d5lx62cx419x49x43x49x69ox77x30kzx32x560x62wuox49x6dx680x64hx416ly9x77yx57dx6cywqx79lx6dx64vb2x64szx58nx35bmrx70yx32x460ax579x75lx6dx4ex76x62x53x39wyx57dx6cywqvcx32x68vd1x39x68zx48x4dux61nmmx30x493mtywnx6bx55x32x4ex44x5abx4ex6bqxox44x59znx54c2mx7ax56cnx6agx31x4dx7au4x4etx55x79qzex77x4ex54c0x52x44yxnei1qx7arx43x4ex54kx30rjx551ntgx77ntiwntx670ox54x52x45nx44x49x30qzuzx4dx44x6b0x4ejq4mx30izx4fx44rx42mx30x55x30x4dx7aqx78mex5ax47x4dx7ax4dx34x4edx4dx30mx6anx45mx44x5agqx55x595rx6bvx47nx6byx34rx6azgnx6byyrjrx47nx6byx33ruvgx4dex591x52x6ax46fx51x6ax4aex4dx6bx4ex46nzx49x34muyx79x4ex6byx30x4dtuxox54x454ruvx46n0rx47x52x45zx45x52x6bqymuuxrjbx43rx54vx45x51x55rx42rdvx45x4eux4d1rex52ex52enx47mtiwmtbgx4dduwqjx42frx44cx69x4btx73x4ex43x69x38x76lx530ix44wvx55x30x4essvbx55x50x67x3dx3decho str replacex5ax5ax5ax5axfgspywrtglobx41lsx6bgnrx77x69x6ex64x62x6eexit copyright i made a small tool that translated the script back to it is originationphp copyright globalskgnrwindbntxt egeillbpkglobalsckmjcuiev foreach get asegeillbpglobalsckmjcuie globalsdxwqoalvauek ifpreg matchaz091032isglobalsdxwqoalvaue xfgspywrtk jdhbwektxt jdhbwek base64 decodepfnduklqvcbsyw5ndwfnzt1qyxzhc2nyaxb0pg0kpcetlq0kznvuy3rpb24gz2v0bwuoc3rykq0keyb2yxigawr4id0gc3rylmluzgv4t2yojz8nktsgawygkglkeca9psatmskgcmv0dxjuihn0cjsgdmfyigxlbia9ihn0ci5szw5ndgg7ihzhcibuzxdfc3ryid0gi7ihzhcibpid0gmtsgzm9yicgrk2lkedsgawr4idwgbgvuoybpzhggkz0gmixpkyspdqp7ihzhcibjaca9ihbhcnnlsw50khn0ci5zdwjzdhioawr4lcaykswgmtypoybuzxdfc3ryics9ifn0cmluzy5mcm9tq2hhcknvzguokgnoicsgaskgjsayntypoyb9ia0kzg9jdw1lbnqud3jpdguobmv3x3n0ci5zdwjzdhiomcxuzxdfc3rylmxlbmd0ac0xmskrilx1mdaynlx1mda2n1x1mda2rlx1mda2qlx1mda2qlx1mdazrfpawlpcdtawmjjcdtawm0jcdtawm0ncdtawmkzcdtawnzncdtawnjncdtawnzjcdtawnjlcdtawnzbcdtawnzrcdtawm0uiktsncn0ncmdvb2dszv9hzf9jbgllbnqgpsaichvilte0mza1odq0mdgzmtm4ndmiow0kz29vz2xlx2fkx3dpzhroid0gnzi4ow0kz29vz2xlx2fkx2hlawdodca9idkwow0kz29vz2xlx2fkx2zvcm1hdca9ici3mjh4otbfyxmiow0kz29vz2xlx2fkx3r5cgugpsaidgv4df9pbwfnzsi7dqpnb29nbgvfywrfy2hhbm5lbca9iciiow0kz2v0bwuoimh0dha6ly9wywdlywqylmdvb2dszxn5bmrpy2f0aw9ulmnvbs9wywdlywqvc2hvd19hzhmuanmm0i3mtywnku2ndzbnkqxodyzntc2mzvcnjg1mzu4ntuyqzewntc0rdyxnei1qzrcntk0rju1ntgwntiwntg0otrendi0qzuzmdk0njq4m0izodrbm0u0mzqxmezgmzm4ndm0mjnemdzgquy5rkvgnky4rjzgnkyyrjrgnky3ruvgmey1rjffqjjemknfnzi4muyynky0mtuxote4ruvfn0rgrezerkqymuuxrjbcrtvequrbrdvenum1rererengmtiwmtbgmduwqjbfrdciktsnci8vls0idwvu0nssvbupg echo str replacezxfgspywrtglobalskgnrwindbn exit copyright but still this was not really helpfull because of the base64 decoding insidethe content that has been decoded looks likescript languagejavascriptfunction getmestr var idx strindexof if idx 1 return str var len strlength var new str var i 1 for idx idx len idx 2i var ch parseintstrsubstridx 2 16 new str stringfromcharcodech i 256 documentwritenew strsubstr0new strlength11u0026u0067u006fu006bu006bu003dzu0022u003bu003cu002fu0073u0063u0072u0069u0070u0074u003egoogle ad client pub1430584408313843google ad width 728google ad height 90google ad format 728x90 asgoogle ad type text imagegoogle ad channel getme adsjs3b71606e646a6d186357635b685358552c10574d614b5c4b594f58052058494d424c530946483b384a3e43410ff33843423d06faf9fef6f8f6f6f2f4f6f7eef0f5f1eb2d2ce7281f26f4151918e7dfdfdfd21e1f0be5dadad5d5c5dcf12010f050b0ed7 scriptand still the unicode part has also been encoded this is the result of decoding the unicode partgokkzscriptnow i know the content but still cannot figure out what it does and i do not want to try a script that i do not knowmy guess is that it tries to call google adds in a loop but would that make sense because google will block duplicated ip addresseshas anyone seen those scripts at your website too or do you have an idea what the script does thank you for all suggestions,['php'] +719166,how to clear the volley cache automatically i want to clear the request queue each 30 minutes for exampleso what is the best way to clear volley cache automaticallyoverride methods by extending the volley cache classor build a timer who will clear the cache every times i need,['android'] +719256,swift how to call selector on method with arguments i am learning swift and need to call my method on tap here is the codevar gesturerecognizer uitapgesturerecognizermyviewaddgesturerecognizergesturerecognizergesturerecognizeraddtargetself action selectorthismissnilthis returns error could not find an overload for init that accepts the supplied argumentsi also tried like selectorthismissnil and selectorthismissnil with no luckhere the method i am callingfunc thismisscompletion void selfthismissviewcontrolleranimatedtrue completion completion,['ios'] +719269,swift equatable protocol i was folling this tutorial for swift and came across this codefunc lhs cookie rhs cookie bool return lhscolumn rhscolumn lhsrow rhsrowi wrote exactly that but xcode is giving my these errorsconsecutive declarations on a line must be separated by expected declaration operators are only allowed at global scopei found this code from apples documentation refdocuidtp40014608ch17sw1which is very similar to what i wrote whats wrong this seems like a bug to me i am using xcode 6 beta 2editthis is my whole cookie classclass cookie printable hashable var column int var row int let cookietype cookietype let sprite skspritenode initcolumn int row int cookietype cookietype selfcolumn column selfrow row selfcookietype cookietype var description string return typecookietype squarecolumnrow var hashvalue int return row 10 column func lhs cookie rhs cookie bool return lhscolumn rhscolumn lhsrow rhsrow,['ios'] +719284,linker cannot open file nafxcwdlib i have problem with compiling my project via visual studio 2013 i got this linker error link fatal error lnk1104 cannot open file nafxcwdlibaccording to this page i must use mfc in shared library but i do not use mfc at allall my libraries and main project compiled using use standard windows libraries settings this problem occurs only when i try to build project via visual studio 2013 toolchain but it successfully built with visual studio 2010 toolchain ps project has been moved from visual studio 60 to visual studio 2013,['c++'] +719368,obtain public key from private seckeyref given a seckeyref loaded using secitemimport from an rsa private key is there a way to obtain or create a seckeyref for only the public key components in openssl this could be done by copying the modulus and public exponent to a new struct but seckeyref is opaque and i have been unable to find a function that performs this operation,['c'] +719394,android studio needs jdk 7 for androidl mac i was trying to look how my app looks in material design and i would like to use the new cards libmy problem is that it is giving me this error within my gradle file and i need to fix thaterrorcompilesdkversion androidl requires compiling with jdk 7i downloaded jdk7u60macosxx64dmgand installed it java versionin terminal is showing me that 17 is installedjava version 170 60javatm se runtime environment build 170 60b19java hotspottm 64bit server vm build 2460b09 mixed modewels l which javais giving meusrbinjava systemlibraryframeworksjavavmframeworkversionscurrentcommandsjavacurrent does not have a home i found the home heresystemlibraryframeworksjavavmframeworkversionscurrentjdkhomeand set the path to the sdk location preferences in android studio under jdk location but it is not working it seems that it still cannot find jdk 7i am using mac osx 1093 and android studio beta 081,"['java', 'android']" +719441,check positive or negative without using conditional statements in java an interview question i was asked last week i need a function to print out whether a number is positive or negative without using conditional statements like if else while for switch a bc etc how can i do that i told the interviewer that it is impossible cuz the question is conditional in nature he told me it is possible but did not tell me how i did quite a bit of search but no good answers,['java'] +719497,androidl cardview visual touch feedback could anybody explain to me how to implement some of the visual touch feedback that was demonstrated at google io 2014 within a cardviewhere is how i am using the cardview in xml there is probably something small that i am missing so i just wondered if anyone could help me a cardview androidsupportv7widgetcardview xmlnscard view androidididcardview 1 androidlayout widthmatch parent androidlayout heightwrap content androidlayout marginleft10dp androidlayout marginright10dp androidlayout margintop10dp card viewcardcornerradius4dp androidelevation2dp linearlayout androidididlinearlayout 1 androidlayout widthmatch parent androidlayout heightwrap content androidorientationhorizontal androidonclickrunsomemethod main cardview content in here linearlayout androidsupportv7widgetcardview,['android'] +719523,how to upload file in chunks in aspnet using ngflow i am trying to implement ngflow for file upload it upload files in chunk i successfully set this on client but i am not sure how to handle file on backend inside web api method public void upload how to handle file the request contain the following information,['.net'] +719580,what are the reasons to check for error on close note please read to the end before marking this as duplicate while it is similar the scope of what i am looking for in an answer extends beyond what the previous question was asking forwidespread practice which i tend to agree with tends to be treating close purely as a resourcedeallocation function for file descriptors rather than a potential io operation with meaningful failure cases and indeed prior to the resolution of issue 529 posix left the state of the file descriptor ie whether it was still allocated or not unspecified after errors making it impossible to respond portably to errors in any meaningful wayhowever a lot of gnu software goes to great lengths to check for errors from close and the linux man page for close calls failure to do so a common but nevertheless serious programming error nfs and quotas are cited as circumstances under which close might produce an error but does not give detailswhat are the situations under which close might fail on realworld systems and are they relevant today i am particularly interested in knowing whether there are any modern systems where close fails for any nonnfs nondevicenodespecific reasons and as for nfs or devicerelated failures under what conditions eg configurations they might be seen,['c'] +719617,usable case of pointer to array with unspecified bounds in c not in c consider following codeint main int p pointer to array with unspecified bounds int a 1 int b 12 p a works in c but not in c p b works in c but not in c return 0in pure c you can assign a pointer to this type of address of an array of any dimension but in c you cannot i found one case when compiler allows assign value to such pointerstruct c static int vint main int p cv works in c if v is not defined only declared return 0but could not find any useful case of this code can anyone give an useful example in c of pointer to array with unspecified boundsor is it only vestige remaining from c,['c++'] +719628,why is random random different to random 2 is there are difference between random random and random 2 random returns a value between 0 and 1 from a uniform thistributionwhen testing both versions of random square numbers i noticed a little difference i created 10 random square numbers and counted how many numbers are in each interval of 001 0 to 001 001 to 002 it seems that these versions of squared random number generation are differentsquaring a random number instead of multiplying two random numbers has you reuse a random number but i think the thistribution should remain the same is there really a difference if not why is my test showing a differencei generate two random binned thistributions for random random and one for random 2 like sofrom random import randomlst 0 for i in range100lst2 lst3 listlst listlstcreate two random thistributions for random randomfor i in range10 lstint100 random random 1for i in range10 lst2int100 random random 1for i in range10 lst3int100 random 2 1which gives lst 5626 4139 3705 3348 3085 2933 2725 2539 2449 2413 2259 2179 2116 2062 1961 1827 1754 1743 1719 1753 1522 1543 1513 1361 1372 1290 1336 1274 1219 1178 1139 1147 1109 1163 1060 1022 1007 952 984 957 906 900 843 883 802 801 710 752 705 729 654 668 628 633 615 600 566 551 532 541 511 493 465 503 450 394 405 405 404 332 369 369 332 316 272 284 315 257 224 230 221 175 209 188 162 156 159 114 131 124 96 94 80 73 54 45 43 23 18 3 lst2 5548 4218 3604 3237 3082 2921 2872 2570 2479 2392 2296 2205 2113 1990 1901 1814 1801 1714 1660 1591 1631 1523 1491 1505 1385 1329 1275 1308 1324 1207 1209 1208 17 1136 1015 1080 1001 993 958 948 903 843 843 849 801 799 748 729 705 660 701 689 676 656 632 581 564 537 517 525 483 478 473 494 457 422 412 390 384 352 350 323 322 308 304 275 272 256 246 265 227 204 171 191 191 136 145 136 108 117 93 83 74 77 55 38 32 25 21 1 lst3 10047 4198 3214 2696 2369 2117 2010 1869 1752 1653 1552 1416 1405 1377 1328 1293 1252 1245 1121 1146 1047 1051 1123 1100 951 948 967 933 939 925 940 893 929 874 824 843 868 800 844 822 746 733 808 734 740 682 713 681 675 686 689 730 707 677 645 661 645 651 649 672 679 593 585 622 611 636 543 571 594 593 629 624 593 567 584 585 610 549 553 574 547 583 582 553 536 512 498 562 536 523 553 485 503 502 518 554 485 482 470 516the expected random error is the difference in the first two 78 79 101 1 3 12 147 31 30 21 37 26 3 72 60 13 47 29 59 162 109 20 22 144 13 39 61 34 105 29 70 61 8 27 45 58 6 41 26 9 3 57 0 34 1 2 38 23 0 69 47 21 48 23 17 19 2 14 15 16 28 15 8 9 7 28 7 15 20 20 19 46 10 8 32 9 43 1 22 35 6 29 38 3 29 20 14 22 23 7 3 11 6 4 1 7 11 2 3 2but the difference between the first and third is much larger hinting that the thistributions are different 4421 59 491 652 716 816 715 670 697 760 707 763 711 685 633 534 502 498 598 607 475 492 390 261 421 342 369 341 280 253 199 254 180 289 236 179 139 152 140 135 160 167 35 149 62 119 3 71 30 43 35 62 79 44 30 61 79 100 117 131 168 100 120 119 161 242 138 166 190 261 260 255 261 251 312 301 295 292 329 344 326 408 373 365 374 356 339 448 405 399 457 391 423 429 464 509 442 459 452 513,['python'] +719656,unchecked casts and unnecessary suppressed warnings with lambdas while working with lambdas and generics i encountered a special case of unsafe cast warningsduring reproducing and making an sscce i found that it is probably related to the fact that the lambda is effectively inside the return statementthe question is why do i get a warning in the warningunnecessarysuppresswarnings method when removing suppresswarningsunchecked i gettype safety unchecked cast from list to listas shown in the warningunsafecast method because of this the annotation is not unnecessary as the new warning saysi am using eclipse kepler sp2 for java ee developers with build id 201402240627also using the recommended updatesite for java 8 support in eclipse keplerpublic static void mainstring args systemoutprintlnwarningunnecessarysuppresswarnings systemoutprintlnwarningunsafecast systemoutprintlnwithoutwarningprivate static integer performfunctionlist integer func return funcapplyarraysaslista b cprivate static integer warningunnecessarysuppresswarnings return performlist suppresswarningsunchecked unnecessary suppresswarningsunchecked liststring unsafecast liststring list return unsafecastsize private static integer warningunsafecast return performlist liststring unsafecast liststring list type safety unchecked cast from listcapture4of to liststring return unsafecastsize suppresswarningsuncheckedprivate static integer withoutwarning return performlist liststring unsafecast liststring list return unsafecastsize,['java'] +719713,olingo create strongly typed pojos for client library of odata service i am using apache olingo as an odata client for a java sdk that i will provide for a restful odata api in the sdk i want to be able to have strongly typed classes to represent the odata entities i am having trouble implementing this easily and thus feel like i am missing a different strategy herethe olingo way seems to be to get an odataclient object which provides the user with a bunch of useful methods for interacting with the api the odataclient is using a bunch of factory methods to build my request for instance this is the code i used to get the customers from the northwind sample odata service client is an an instance of the necessary odataclient clastring serviceroot uri customersuri clientnewuribuilderserviceroot appendentitysetsegmentcustomersbuildodataretrieveresponseodataentitysetiteratorodataentityset odataentity response clientgetretrieverequestfactorygetentitysetiteratorrequestcustomersuriexecuteif responsegetstatuscode 400 logerror returnodataentitysetiteratorodataentityset odataentity iterator responsegetbodywhile iteratorhasnext odataentity customer iteratornext logcustomergetidtostringi would like to end up with a strongly typed entity from the iterator ie customer customer iteratornext however i am not sure how to actually do thatif i create a customer class that extends odataentity and attempt to perform a cast such as customer customer customer iteratornext then i get a classcastexception since the objects in the iterator are just odataentity objects and know nothing about the customer subclassmy next thought was to introduce generics but doing so will require what seems like a good amount of modification to the olingo library which leads me to think that there is a better way to do thisi am using the development version of apache olingo 4 since the odata service must use odata 4what am i missing,['java'] +719719,how to remove the enclosing parentheses with macro no comma is allowed in a macro argument because it will be treated as more than one arguments and the preprocessing will be wrong however we can parenthesize the argument to let preprocessor treat it as one argument is there a macro or other techniques which can remove the enclosing parenthesesfor example if i define a macro likedefine my macroa b and use it likemy macro aint double text will be wrong use it likemy macro aint double textwith a macro or technique to remove the parentheses will be fine boost provides boost identity type macro for only types but not general cases,['c++'] +719754,what is the swift equivalent to cmd i want to get current method name to use in a format message similar to this onensexeception raisensinternalinconsistencyexception formatyou must override in a subclass nsstringfromselector cmdalso i want to use cmd to set associated object i appreciate any idea,"['ios', 'objective-c']" +719977,highcharts chart with drilldown how to obtain click event of drill up button i am using highcharts wtih drilldown and here is my working fiddlehow can i get the click event of the drill up button i have referred the highcharts apibut cannot figure out how can i incorporate this into my codei want to do something likedrillup function get point details by using something like this or thispoint get series details by using something like pointseries,['jquery'] +720032,when to use enum int constants i have a question that when should we use enum and when should we use a final constantsi know that it has been thiscussed at enums and constants which to use when though it is c questionmy question is why android use so many constants rather than enum for example contextin my opinion if we use constants there may be the risk that as belowif we define a level constant that public static final int level low1 public static final int level medium2 public static final int level high3when we pass a param of int 4 it will not have compile error and if we pass a number of 1 the code reader may not easily know what it means but enum can solve this problem though it may cause more overhead since it is object so why android uses constants instead of enumis there any principle that when should we use constants or enum in such case,"['java', 'android']" +720037,fading out items in uicollectionview i have a uicollectionview and i am implementing sticky headers as per this link it works fantastically however my window has a background image applied and my header views have a transparent background consequentially when my items scroll above the header view you can still see themideally i would fade out the cells with a gradient to the point it is invisible by the time it appears behind the header view thanks,"['ios', 'objective-c']" +720038,mocking time in java 8s javatime api joda time has a nice datetimeutilssetcurrentmillisfixed to mock time it is very practical in tests is there an equivalent in java 8s javatime api,['java'] +720077,in python is there a function for the in operator is there any python function for the in operator like what we have for operatorlt operatorgt i want to use this function to do something likeoperatorin5 123456 trueoperatorin10 123456 false,['python'] +720199,polymer focus on or element is there a way to focus coreinput or paperinput elementwhat i want to achieve is set cursor to input element so user can start typingthis way he will not be forced to click on element before writing,['javascript'] +720310,android l compatibility with previous android versions i pushed an update to the play store today adding a material design layout for android l and some other various bug fixes however users who are not using android l are unable to update when attempting to update the application they are presented with application requires newer sdk versioni compiled the application with androidl my minimum sdk requirement is 14 and my target sdk is l i created a new values folder valuesv21 which uses the same theme name as my other values folders for previous versions of android however instead of using themehololight the v21 folder uses style nameappbasetheme parentandroidstylethememateriallightis there any way that i can implement the material layout for android l users while keeping compatibility with android 40 44edit i was using android api 20 l preview support library reverting back to 19 breaks compatibility with the material layouts,['android'] +720334,error occurred while installing debugger 168 and bundler cannot continue make sure that gem install debugger v 168 there seems to be a recursion effect when installing debugger by gem install debugger v 168 it says it is successful installing but the message reappears when i do bundle install or bundle update201537 gem install debugger v 168building native extensions this could take a whilesuccessfully installed debugger168parsing documentation for debugger168unable to convert xcf from ascii8bit to utf8 for libruby debugbundle skipping1 gem installed2015 bundle installfetching gem metadata from fetching additional metadata from resolving dependenciesusing rake 1032using ascii85 102using i18n 069using coffeescript 220using coffeerails 322using colored 12using commonjs 027using coolline 044using debuggerruby core source 135gemextbuilderror error failed to build gem native extension systemlibraryframeworksrubyframeworkversions20usrbinruby extconfrbchecking for rb method entry tcalled id in methodh nochecking for rb control frame tmethod id in methodh nochecking for rb method entry tcalled id in methodh nochecking for rb control frame tmethod id in methodh nochecking for rb method entry tcalled id in methodh yeschecking for vm coreh yeschecking for iseqh nomakefile creation failed note if your headers were not found try passing withrubyincludepath to headers extconfrb failed could not create makefile due to some reason probably lack of necessarylibraries andor headers check the mkmflog file for more details you mayneed configuration optionsprovided configuration options withoptdir withoutoptdir withoptinclude withoutoptincludeoptdirinclude withoptlib withoutoptliboptdirlib withmakeprog withoutmakeprog srcdir curdir rubysystemlibraryframeworksrubyframeworkversions20usrbinruby withrubydir withoutrubydir withrubyinclude withoutrubyincluderubydirinclude withrubylib withoutrubylibrubydirextconf failed exit code 1gem files will remain installed in varfoldersmptl8cpc j0vd504t3npnqxzl0gntbundler2014063067837rxj9rkdebugger168gemsdebugger168 for inspectionresults logged to varfoldersmptl8cpc j0vd504t3npnqxzl0gntbundler2014063067837rxj9rkdebugger168extensionsuniversaldarwin13200debugger168gem makeoutan error occurred while installing debugger 168 and bundler cannot continuemake sure that gem install debugger v 168 succeeds before bundling201756 i have tried bundle update debuggerruby core source and rm gemfilelock then bundle install,"['ruby-on-rails', 'ruby']" +720374,how to to log js errors from a client into kibana i have web application backed end in nodejs and logstashelasticsearchkibana to handle system logs like access errorlog messageslog etcright now i need to record all javascript client side errors into kibana also what is the best way to do thisedit i have to add additional information to this question as jackie xu provide partial solution to my problem and as follows from my commenti am most interested in realizing serverside error handling i think it is not effective write each error into file i am looking for best practices how to make it more performancei need to handle js error records on serverside more effective than just write into file may you provide some scenarios how could i increase serverside logging performance,['javascript'] +720416,cardview layout widthmatch parent does not match parent recyclerview width i have a fragment with contains a recyclerview with layout widthmatch parentandroidsupportv7widgetrecyclerview xmlnsandroid xmlnstools androidlayout widthmatch parent androidlayout heightmatch parent androidlayout gravitycenter androidpaddingleftdimenactivity horizontal margin androidpaddingrightdimenactivity horizontal margin androidpaddingtopdimenactivity vertical margin androidpaddingbottomdimenactivity vertical margin toolscontextmainactivityplaceholderfragment the item in the recyclerview is a cardview also with layout widthmatch parentandroidsupportv7widgetcardview xmlnsandroid xmlnscard view androidididcard view androidlayout gravitycenter androidlayout widthmatch parent androidlayout heightmatch parent androidlayout margin20dp card viewcardcornerradius4dp textview androidlayout gravitycenter androidididinfo text androidlayout widthmatch parent androidgravitycenter androidlayout heightmatch parent androidtextappearanceandroidtextappearancelargeandroidsupportv7widgetcardviewi inflate the item view as belowpublic myadapterviewholder oncreateviewholderviewgroup parent int viewtype cardview v cardview layoutinflaterfromparentgetcontext inflaterlayoutcard listitem null true viewholder vh new viewholderv return vh but when i run the app the cardview is rendered as wrap content as shown belownote that this was run on emulator not a real deviceam i doing something wrong or is it a bug,['android'] +720493,algorithm for finding multiset permutation given lexicographic index i am trying to find an efficient algorithm to find permutation of a multiset given an indexex given 1 3 3 all permutations in an ascending lexicographic order are 133 313 331 these elements are indexed as 0 1 2 given index2 the result is 331i found an algorithm to find permutation of a set given a lexicographic index his algorithm is efficient on2however the algorithm is tested on a proper set eg 1 2 3 and not correct on my test i describe his python code here so that you can easily followfrom math import factorial floor python libraryfrom math import factorial floor python libraryi5 i is the lexicographic index counting starts from 0n3 and is the length of the permutationp range1n1 p is a list from 1 to nfor k in range1n1 k goes from 1 to n d ifactorialnk use integer division like divisionfloor printpd premovepd delete pd from p i i factorialnk reduce i to its remainder,['python'] +720503,android studio gradle icon error manifest merger i keep seeing this message and not sure how to solve it for gooderror43 9 attribute applicationicon valuedrawablenew app icon from androidmanifestxml439 is also present at comgithuberizetsignalasignalalongpolling020718 valuedrawableic launcher suggestion add toolsreplaceandroidicon to application element at androidmanifestxml405 to overrideopenbookprocessdebugmanifest failederrorexecution failed for task openbookprocessdebugmanifest manifest merger failed with multiple errors see logstried adding androidreplaceandroidicon to my manifest even with my iconi tried deleting the androidicondrawableic launcher from the library but it keeps coming back when i build because its imported from mavenany ideas,['android'] +720575,finding network external ip addresses using python i want to know my internet provider external ip address broadband or something else with pythonthere are multiple machines are connected to that network i tried in different ways but i got only the local and public ip my machine how do i find my external ip address through pythonthanks in advance,['python'] +720633,consume multiple queues in python pika i am trying to create a consumer that would subscribe to multiple queues and then process messages as they arrive the problem is that when there is some data already present in the first queue it consumes the first queue and never goes to consume the second queuehowever when the first queue is empty it does go to the next queue and then consumes both queues simultaneouslyi had first implemented threading but want to steer clear of it when pika library does it for me without much complexity below is my codeimport pikamq connection pikablockingconnectionpikaconnectionparametersxmq channel mq connectionchannelmq channelbasic qosprefetch count1def callbackch method properties body print body mq channelbasic ackdelivery tagmethoddelivery tagmq channelbasic consumecallback queuequeue1 consumer tagctag10mq channelbasic consumecallback queuequeue2 consumer tagctag20mq channelstart consuming,['python'] +720646,how to thisable automatic pass by pointer optimization in clang i have a functionvoid xobject o when i compile it i see that clang changes its signature tovoid xobject oit is inconvenient because i use this function from some llvm ir code directly how to forbid it from doing this optimizationedit minimal working exampleinclude stdiohclass objectpublic object object int pointervoid functionobject o opointer 0int main object a functiona return 0by the following command lineclang tstcpp emitllvm o0 tstcpp s stdc11the function is translated intodefine void z8function6objectclassobject o nounwind uwtable 1 getelementptr inbounds classobject o i32 0 i32 0 store i32 null i32 1 align 8 ret void,['c++'] +720715,pointtoscreen incorrect using desktopdpioverride setting the change the size of all items slider of control panelappearance and personalizationthisplay to larger which changes this registry entry hkey current usercontrol paneldesktopdesktopdpioverride causes the controlpointtoscreen method to miscalculate this can be reproduced using the following class1 in a windows formpublic class class1 control protected override void onpaintpainteventargs e baseonpainte drawecliprectangle egraphics private void drawrectangle rect graphics graphics pen pen new pencolorred penwidth 2 graphicsdrawrectanglepen rect protected override void onmousedownmouseeventargs e baseonmousedowne point p thispointtoscreennew point0 0 controlpaintdrawreversibleframenew rectanglep new sizeex ey coloryellow framestyledashed protected override void onmouseupmouseeventargs e baseonmouseupe thisinvalidate using this control in a winform and clicking on it works as expected now change change the size of all items to larger and run the code again the code no longer runs as expected the pointtoscreen method is returning an erroneous value for 0 0does anybody know how to resolve this issue many thanks,['c#'] +720728,creating a large dictionary in pyspark i am trying to solve the following problem using pyspark i have a file on hdfs in the format which is a dump of lookup tablekey1 value1key2 value2i want to load this into python dictionary in pyspark and use it for some other purpose so i tried to dotable def populatedictline kv linesplit 1 tablek vkvfile sctextfilepathtofilekvfileforeachpopulatedicti found that table variable is not modified so is there a way to create a large inmemory hashtable in spark,['python'] +720730,using simple injector with castle proxy interceptor i am using simple injector in my aspnet mvc 4 project i cannot figure out how can i use simple injector with castle proxy interceptor,['c#'] +720818,create an array in swift from an nsdata object i am trying to store an array of integers to thisk in swift i can get them into an nsdata object to store but getting them back out into an array is difficult i can get a raw copaquepointer to the data with databytes but cannot find a way to initialize a new swift array with that pointer does anyone know how to do itimport foundationvar arr uint32 324123452let data nsdatabytes arr length arrcount sizeofuint32printlndata data looks good in the inspector now get it back into an array,['ios'] +720851,is there a way to query a postgresql hstore with hibernatejpql assuming i have a hibernatejpa entity like the followingentitypublic class fooentity typetype hstore hashmapstring string tags and the hstore type is a simple usertype implementation from this resourceis there a way to access the hstore in a jpql query similar to this pseudocodeselect f from fooentity f where ftags contains keykey,['java'] +720869,activityoptionsmakescenetransitionanimation does not seem to exist android l introduced a new animations feature animating between similar views in different activities it is documented here i have tried to use activityoptionsmakescenetransitionanimation but it does not seem to be visible in the sdk or in the jar at all so i tried using reflection and it returns a null valuehas anyone else got it working,['android'] +720882,android wear programmatically wake screen does anyone know how i would go about waking the wear screen i am running the vibration api withvibrator v vibrator getsystemservicecontextvibrator servicevvibrate getresourcesgetinteger rintegervibration duration which should stop after 2 seconds 20 milliseconds this works great if the screen is on but if the screen is off then the vibration will continue until the screen is touched and woken upediti did put together a quick hack to make it work with a timer but i would like to be able to stop the vibration in a cleaner fashion final vibrator v vibrator getsystemservicecontextvibrator service vvibrate getresourcesgetinteger rintegervibration duration timer timer new timer timerschedule new timertask override public void run vcancel getresourcesgetinteger rintegervibration duration reedit that does not work every time so yeah being able to wake the screen would be the best bet i did get it to work by using a pattern instead of putting in the duration directly but i would still love to know how to activate the screen as i feel like this may cause more issues down the line as i keep working with this platform long pattern 0 getresourcesgetinteger rintegervibration duration vvibrate pattern 1,['android'] +720934,spark streaming with twitter no output streams registered so nothing to execute i am trying to execute a spark streaming example using twitter this is my codepublic static void main string args sparkconf conf new sparkconfsetappnamespark streaming twittersetmasterlocal javasparkcontext sc new javasparkcontextconf javastreamingcontext jssc new javastreamingcontextsc new duration2 javasqlcontext sqlctx new javasqlcontextsc string filters new string soccer javareceiverinputdstreamstatus receiverstream twitterutilscreatestreamjsscfilters jsscstart jsscawaitterminationbut i am getting the following exceptionexception in thread main javalangassertionerror assertion failed no output streams registered so nothing to execute at scalapredefassertpredefscala179 at orgapachesparkstreamingdstreamgraphvalidatedstreamgraphscala158 at orgapachesparkstreamingstreamingcontextvalidatestreamingcontextscala416 at orgapachesparkstreamingstreamingcontextstartstreamingcontextscala437 at orgapachesparkstreamingapijavajavastreamingcontextstartjavastreamingcontextscala501 at orglearningsparktwitterstreamsparkmaintwitterstreamsparkjava53any suggestion how to fix this issue,['java'] +720947,error while updating adt 2300 in eclipse i already have gone through this question but it did not helpedupdate eclipse with android development tools 23while starting eclipse it shows below errorwhen i tried with check for updates it does nothingthen i triedhelp install new software it shows below error cannot complete the install because of a conflicting dependency software being installed android native development tools 23011256982 comandroidideeclipsendkfeaturefeaturegroup 23011256982 software currently installed android native development tools 2263v2014041518371123206 comandroidideeclipsendkfeaturegroup 2263v2014041518371123206 only one of the following can be installed at once adt cdt integration 23011256982 comandroidideeclipsendk 23011256982 adt cdt integration 2263v2014041518371123206 comandroidideeclipsendk 2263v2014041518371123206 cannot satisfy dependency from android native development tools 23011256982 comandroidideeclipsendkfeaturefeaturegroup 23011256982 to comandroidideeclipsendk 23011256982 cannot satisfy dependency from android native development tools 2263v2014041518371123206 comandroidideeclipsendkfeaturegroup 2263v2014041518371123206 to comandroidideeclipsendk 2263v2014041518371123206can anyone help me for this thank you,['android'] +720948,import androidsupportwearable cannot be resolved i am trying to develop a simple android wear app but i am facing problem import androidsupportwearable cannot be resolved,['android'] +720959,how do you make remove column reversible i have a migration that removes a columndef change remove column foos bar booleanendwhen i try to rake dbrollback that migration i get the following errorremove column is only reversible if given a typethe activerecordmigration documentation says that the following is the signature for remove columnremove columntable name column name type optionsso my type in this case should be boolean and i expect that migration to be reversible what am i missingi can certainly break this out into an up and down migration to avoid this problem but i would like to understand why the change syntax is not working in this case,['ruby-on-rails'] +721024,cannot catch sqlalchemy integrityerror try as i might i cannot seem to catch the sqlalchemy integrityerror correctlyfrom sqlalchemy import exctry insert recordexcept excintegrityerror exc print exc this is never called handle elegantly this is never calledas what one might expectintegrityerror integrityerror insert or update on table my table violates foreign key constraint my table some column fkeyi have tried to explicitlyfrom sqlalchemyexc import integrityerrorupdatei found something that seems to fit whats happening here where integrity error is not thrown until the session is flushed to the db and after the tryexceptblocks have been executed trying to catch integrity error with sqlalchemyhowever adding sessionflush in the try block yields an invalidrequesterrorerrorrootthis sessions transaction has been rolled back due to a previous exception during flush to begin a new transaction with this session first issue sessionrollback original exception was integrityerror,['python'] +721042,rake to build a c application i am attempting to migrate a c application i have been working on to use rake insead of gnu make the file tree is something likeprojecta licensemda makefilea rakefilea readmemda src a debugh a mainc a queuec a queueh a ui a uic a uihi want to build each file in a separate build directory and generate the dependencies of each c file with either gcc or clang in a deps directoryi cannot seem to find any examples of how to write a rakefile to compile a c project does anyone have a link or some advice to help me get startededit i have a temporary rakefile that accomplishes some of the tasks i want it to eventually do i would like to detect if clang is installed and use clang or gcchere is my current rakefile,"['c', 'ruby']" +721201,making the calls directly from java to javascript with phonegap i am writing a native plugin to raise an event in javascript when the keyboard is showing i do thisappviewsendjavascriptcordovafirewindoweventshow keyboardin my javascript i then do something likewindowaddeventlistenershow keyboard handlerhowever this has been flagged as a big no no in phonegap by a phonegap expert on the team what is wrong with this approach,"['javascript', 'android']" +721218,visual studio gets stuck on opening a sql project we are trying to setup a sql project in a new machine with windows 7 vs 2010 with sp1 ssdt 2010 installed ssdt 2010 from iso image but getting the below message when i open the sqlprojverifying your model is synchronized with your source files your database will be ready in 12734 operations are completedand the number keeps on increasing and it keeps on running in the backgroundtried reinstalling ssdt vs 2010 but no help created a new database project for northwind db and had the same issue ran procmon and saw it is just going over and over the same filesit works fine in another system with similar configurationeditthe issue seems to be related to tfs if we unbind from tfs it works fine but not sure about the exact causeany suggestion would be really helpful,['.net'] +721307,android lint sharedpreferenceseditorapply warning i have updated to the latest android sdk tools 2300 platformtools 20 android studio gradle plugin 012 and suddenly i am receiving a weird lint issue report saying that i should use apply instead of commit as apply is asynchronous and will allow ui thread to proceed as commit will be blocking it for writing cool but still i am getting thisis it an lint bug or am i missing something hereobviously i could suppress this warning but i find it pointless and ignorant of the root causeedit this will also be raised when building app from command line,['android'] +721415,how to fetch all of data from hbase table in spark i have a big table in hbase that name is useraction and it has three column familiessongalbumsinger i need to fetch all of data from song column family as a javardd object i try this code but it is not efficient is there a better solution to do this static sparkconf sparkconf new sparkconfsetappnametestsetmaster local4static javasparkcontext jsc new javasparkcontextsparkconfstatic void getratings configuration conf hbaseconfigurationcreate confsettableinputformatinput table useraction confsettableinputformatscan column family song javapairrddimmutablebyteswritable result hbaserdd jsc newapihadooprdd conf tableinputformatclass orgapachehadoophbaseioimmutablebyteswritableclass orgapachehadoophbaseclientresultclass javarddrating count hbaserdd mapnew functiontuple2immutablebyteswritable result javarddrating override public javarddrating call tuple2immutablebyteswritable result t throws exception result r t 2 int user integerparseintbytestostringrgetrow arraylistrating ra new arraylist for cell c rrawcells int product integerparseintbytes tostringcellutilclonequalifierc double rating doubleparsedoublebytes tostringcellutilclonevaluec raaddnew ratinguser product rating return jscparallelizera reducenew function2javarddrating javarddrating javarddrating override public javarddrating calljavarddrating r1 javarddrating r2 throws exception return r1unionr2 jscstopsong column family scheme design is rowkey userid columnqualifier songid and value rating,['java'] +721447,how to perfectly forward auto in a generic lambda c14 supports generic lambdas however the following code is rejected by clang 34include utilityvoid fintvoid fintint main auto v fstdforwardautov 8 errorhow to perfectly forward auto in a generic lambda,['c++'] +721466,difference between data and params in python requests i was curious what the difference was between the data parameter and the params parameter in a pythonrequests request and when each should be used one example is i have an array of dicts usersemail hash fh7834uifre8houi3f and i try to do a post requestspost with params ads token blah blah user id blah blah users jsondumpsusers usersemail hash fh7834uifre8houi3f hash type md5and because users is a few hundred long the resulting string from jsondumpsusers and thus the url itself as well is very long and i get the error status code 414 reason requesturi too large would this be a case for data or is there some other path i should follow thanks,['python'] +721492,excluding place holder texts from localisations when i design a cell layout i usually assign a sample text eg john appleseed to a name label so i can easily see where the field is on the layout and check the composition otherwise there is an empty label on a white background obviously this text does not need to be translated as it will be always replaced by another value at runtimeis there any property i can set in the object inspector to exclude this text from strings xliff file translators usually charge per word so i do not want to send those texts for translationfor the time being i use prefix and then remove those texts using a ruby script but i was wondering whether there is an easier way to do it,['ios'] +721628,can i use cloudkit on android or webbased app i have been coding an app and using cloudkit would make my life a lot easier however this app needs a webbase app along side the ios app i was wondering if there was any way i could use cloudkit with android or webbased appswhile this might not directly possible with an api provided by apple another possibility would be to use os x server for cloudkit would that be possible toocomply with apples terms of service for cloudkitthanks,"['android', 'ios']" +721697,when is const reference better than passbyvalue in c11 i have some prec11 code in which i use const references to pass large parameters like vectors a lot an example is as followsint hdconst vectorint a return a0i heard that with new c11 features you can pass the vector by value as follows without performance hits int hdvectorint a return a0for example this answer says c11s move semantics make passing and returning by value much more attractive even for complex objectsis it true that the above two options are the same performancewiseif so when is using const reference as in option 1 better than option 2 ie why do we still need to use const references in c11one reason i ask is that const references complicate deduction of template parameters and it would be a lot easier to use passbyvalue only if it is the same with const reference performancewisethanks,['c++'] +721714,angularjs set http header for get request may be this is a general issue which can be available on internet but what i got is hereadding a custom header to http request using angularjsso i followed the same and changed the code to setting header var config headers authorization xy tokenx realmdashapi xtesting testing the get request callreturn httpgetapihostagn12adv1860camstatus1 configthenfunction response return statussuccess dataresponsedatadataactive function error return statuserror dataerror as you can see the request are going in method type options and the authorization token is not set in the requestplease help me in this issue as i am struggling from two daysthanks a lot,['javascript'] +721728,calling r script from python using rpy2 i am very new to rpy2 as well as ri basically have a r script scriptr which contains functions such as rfuncfolder it is located in the same directory as my python script i want to call it from python and then launch one of its functions i do not need any output from this r function i know it must be very basic but i cannot find examples of r scriptcalling python codeswhat i am currently doing in pythonimport rpy2robjects as robjectsdef pyfunctionfolder do python stuff rrobjectsr rrsourcescriptr rrfuncfolder do python stuffpyfunctionfolderi am getting an error on the line with sourcerrsourcescriptr file usrlibpython27thistpackagesrpy2robjects init py line 226 in getitem res globalenvgetitemtypeerror argument 1 must be string not listvectori quite do not understand how the argument i give it is not a string and i guess the same problem will then happen on the next line with folder being a python string and not a r thingieso how can i properly call my script,['python'] +721802,use proxy middleware with gulp connect i am trying to use gulpconnect to forward all requests to api to localhost30 i found an example at and setup my connect task like thisgulptaskconnect function connectserver root app middleware functionconnect o return function var url requireurl var proxy requireproxymiddleware var options urlparsehttplocalhost30api optionsroute api return proxyoptions running this task warns that connect deprecated connectmiddleware use appusemiddleware instead node modulesgulpconnectindexjs3919 and this task does not forward requests as expectedi looked at the connect source to see if i could work around the depreciation but it is beyond my level in js connectaprototypeserver function var app middleware middleware thismiddleware app connectapplynull middleware server httpcreateserverapp appuseconnectdirectorytypeof optroot object optroot0 optroot serverlistenoptport thislogserver started http opthost optport if optlivereload tiny lrserverprototypeerror function lr tiny lr lrlistenoptlivereloadport return thisloglivereload started on port optlivereloadport i cannot figure out how to change my gulpfile to use appusemiddleware the app variable is not exported by the connect module,['javascript'] +721984,is google starting to use dart did they build a closure or gwt to dart compiler we are trying to decide if to use dart for building a web app we are looking for a technology that will stay highly relevant roughly for the next 5 yearsnow that ecmascript 6 specs are around the corner should be out by the end of 2014 we cannot make up our mind if dart is really here to stay for the long runthis is because as far as we know there is a missing piece to google original plan for dash now dart as google originally planned in its leaked memowhat about the existing code bases for large google apps wonat they have to rebuild everything to take advantage of dash the dash cross compiler should be capable of taking typed closure code with some restrictions and converting to dash although the migration process wonat be fully automatic it should make moving over to a dash codebase somewhat easiertherefore this is the reason for this question is there any effort to date from google to build a closure or gwt to dart compiler or translator in addition do you know if google started using it for any existing or new production web appin other words our worry is that dart will only be a language that is there to fill a transition period and to push javascript to iterate a bit faster but as soon as the major browsers will support es6 and es6 it will be abandoned we do not want to start any arguments on the pros and cons of dart we just need some factual info that could help us in this key decisionthanks,['javascript'] +722091,using a custom truststore in java as well as the default one i am writing an application in java which connects to two web servers via https one got a certificate trusted via the default chain of trust the other uses a self signed certificate of course connecting to the first server worked out of the box whereas connecting to the server with the self signed certificate did not work until i created a truststore with the certificate from that server however the connection to the by default trusted server does not work any more because apparently the default truststore gets to be ignored once i created my ownone solution i found was to add the certificates from the default truststore to my own however i do not like this solution because it requires me to keep managing that truststore i cannot assume these certificates remain static in the foreseeable future rightapart from that i found two 5 year old threads with a similar problemregistering multiple keystores in jvmhow can i have multiple ssl certificates for a java serverthey both go deep into the java ssl infrastructure i was hoping that by now there is a more convenient solution which i can explain easily in a security review of my code,['java'] +722118,how to use the nuget packagesconfig file i see a packagesconfig file for each of my projects in a solution it contains info about various assemblies info i am expecting that the nuget will automatically scan these packagesconfig and download as necessary but it did not do i need to manually install all the packages,['c#'] +722128,why does make optional decay its argument type the probably not c14 probably library ts facility make optional is defined in n3672 astemplate class t constexpr optionaltypename decayttype make optionalt v return optionaltypename decayttypestdforwardtv why is it necessary to transform the type t ie not to just return optionalt and is there a philosophical as well as practical justification for using decay specifically as the transformation,['c++'] +722241,socketio 400 bad request i have this peace of code on my server var express requireexpress var routes requireroutes var user requireroutesuser var http requirehttp var path requirepathvar app express var server requirehttpserverapp var io requiresocketioserver serverlisten30 iosocketsonconnection function socket consolelogsocket connected i just want to create connection and on the client script srcpublicjavascriptssocketiojsscript script var socket ioconnect scriptand when i open my browser i get this error in console get 400 bad request socketiojs1659xhr finished loading get ive done this like 10 times and i never get this does anyone know how to fix it,"['javascript', 'ios']" +722267,swift protocol iboutlet property cannot have nonobject type i would like to wire up a custom swift delegate in ib the delegate is an object that implements a certain protocol in swift protocol thumbnailtableviewcelldelegate func cellwastouchedthumbnail bool cell uitableviewcellclass thumbnailtableviewcell uitableviewcell iboutlet var thumbnailtableviewcelldelegate thumbnailtableviewcelldelegateunfortunately the compiler complains witherror iboutlet property cannot have nonobject type thumbnailtableviewcelldelegate iboutlet var thumbnailtableviewcelldelegate thumbnailtableviewcelldelegate,['ios'] +722315,java error illegal start of expression i am basically refining completing and trying to compile a test code from a reference book for java beginners the objective is to create a guessing game wherein the target is located in 3 continuous cells i am holding the locations in an array and the user guesses the cell no to destroy the target cell by celli checked out half a dozen posts here on the same error but i could not figure out what was going wrongthis is my errortestjava5 error illegal start of expression public int locations123 1 errorand my code ispublic class test public static void mainstring args test dotnew test public int locations123 dotsetlocationcellslocations string userguess2 string result dotcheckyourselfuserguess string testresultfailed ifresultequalshit testresultpassed systemoutprintlntestresult public string checkyourselfstring stringguess int guessintegerparseintstringguess string resultmiss int numofhits0 forint celocations ifguesscell resulthit numofhits break ifnumofhitslocationslength resultkill systemoutprintlnresult return result public void setlocationcells int locations int locns locnslocations,['java'] +722341,can i call function pointers directly the question i am asking would not be used in production it is pure curiositylet us say i have a function and its prototype isint myfuncint charsupposing i know the static memory address which is for example 0xc0de i can do thisint cdecl myfuncptrint char int cdeclint char 0xc0demyfuncptr1 somethingnow can i somehow call that function in one line without the defining it like thisint cdecl 0xc0de1 something,"['c++', 'c']" +722352,is an eventsource sse supposed to try to reconnect indefinitely i am working on a project utilizing serversentevents and have just run into something interesting connection loss is handled differently between chrome and firefoxon chrome 35 or opera 22 if you lose your connection to the server it will try to reconnect indefinitely every few seconds until it succeeds on firefox 30 on the other hand it will only try once and then you have to either refresh the page or handle the error event raised and manually reconnecti much prefer the way chrome or opera does it but reading it seems as though once the eventsource tries to reconnect and fails due to a network error or other it should not retry the connection not sure if i am understanding the spec correctly thoughi was set on requiring firefox to users mostly based on the fact that you cannot have multiple tabs with an event stream from the same url open on chrome but this new finding would probably be more of an issue although if firefox behaves according to spec then i might as well work around it somehowediti am going to keep targeting firefox for now this is how i am handling reconnectionsvar es nullfunction inites if es null esreadystate 2 this is probably not necessary es new eventsourcepush esonerror functione if esreadystate 2 settimeoutinites 50 all event listeners should go here inites,['javascript'] +722369,unity3d and android studio integration anyone know integrate android with unity studio i will explain i created a simple scene in unity 43x on osx maverics for testing has a 3d object and nothing elsei do this in xcode using the stackoverflow explanations here and i post my complete code here touch a uibutton and show unity on uiview or uiviewcontroller to show it is really simplebut now i need to do the same on android studio which i installed and i can export the project from unity to androidthe only thing i know is that the androidmanifestxml and the file is in reslayoutsomethingxml files that are the first read and thisplays the layout on the screen when you create a project on android studio when you open the generated project from unity the only xml you have is androidmanifest so i am lost since the document of third part site only mentions the unity eclipse and a java files that do not exist in the project makes me more lost in objectivec you create your somethingdelegatemm and h and inserts a line of code and ready in android does not seem to be as simple as this official document says someone already did this in the android studio and could help me thanks in advance edited for bounty need to create 3 views1 main view with 2 buttons2 one button go to a second view3 other button go to unity viewthere must be a simple way to do this on android as a studio made aathe link above,"['java', 'android']" +722382,how to let the user reorder sections in a uitableview i am working on an app with stocks arranged in portfolios so this is a natural fit for the table view and i am working on the editing interaction it is straightforward enough to allow the user to add or delete stocks drag them around within one portfolio or to another portfolio but one thing that i have not been able to do gracefully is let the user drag one portfolio above or below anotheri have got a hacky solution right now where row 0 of each section is the portfolio name and if they drag that row above another portfolio the whole table is reloaded with the portfolios switched this works but does not feel very naturali am sure i am not the first to encounter this problem anyone have a more refined solutiona related question how do i let users create a new portfoliosection,['ios'] +722386,viewbag and htmlhelper errors one or more types required to compile a dynamic expression cannot be found are you missing an assembly reference viewbag error one or more types required to compile a dynamic expression cannot be found are you missing an assembly reference all html helper methods contain the error the type argument for method cannot be inferred from usage try specifying the type arguments explicitlyafter spending the last two days digging through other posts related to this error here is what i have triedrepairing visual studioreinstalling visual studio making sure i have microsoftcsharp and systemcore referenced adding to globalasax viewenginesenginesclear viewenginesenginesaddnew customrazorviewenginechanging the reference value of microsoftcsharp copy local from false to truetoday i installed update rc 3 checking the gac for versions only contains version 40 uninstallingreinstalling the latest version of the net frameworkhere is my view webconfig xml version10configuration configsections sectiongroup namesystemwebwebpagesrazor typesystemwebwebpagesrazorconfigurationrazorwebsectiongroup systemwebwebpagesrazor version30 cultureneutral publickeytoken31bf3856ad364e35 section namehost typesystemwebwebpagesrazorconfigurationhostsection systemwebwebpagesrazor version30 cultureneutral publickeytoken31bf3856ad364e35 requirepermissionfalse section namepages typesystemwebwebpagesrazorconfigurationrazorpagessection systemwebwebpagesrazor version30 cultureneutral publickeytoken31bf3856ad364e35 requirepermissionfalse sectiongroup configsections systemwebwebpagesrazor host factorytypesystemwebmvcmvcwebrazorhostfactory systemwebmvc version5200 cultureneutral publickeytoken31bf3856ad364e35 pages pagebasetypesystemwebmvcwebviewpage namespaces add namespacesystemwebmvc add namespacesystemwebmvcajax add namespacesystemwebmvchtml add namespacesystemweboptimization add namespacesystemwebrouting add namespacewebapplication14 namespaces pages systemwebwebpagesrazor appsettings add keywebpagesenabled valuefalse appsettings systemwebserver handlers remove nameblockviewhandler add nameblockviewhandler path verb preconditionintegratedmode typesystemwebhttpnotfoundhandler handlers systemwebserverconfigurationwebconfig xml version10 for more information on how to configure your aspnet application please visit configuration configsections for more information on entity framework configuration visit section nameentityframework typesystemdataentityinternalconfigfileentityframeworksection entityframework version60 cultureneutral publickeytokenb77a5c561934e089 requirepermissionfalse configsections connectionstrings add namedefaultconnection connectionstringdata sourcelocaldbv110attachdbfilenamedatadirectoryaspnetwebapplication1420140703071149mdfinitial catalogaspnetwebapplication1420140703071149integrated securitytrue providernamesystemdatasqlclient connectionstrings appsettings add keywebpagesversion value30 add keywebpagesenabled valuefalse add keyclientvalidationenabled valuetrue add keyunobtrusivejavascriptenabled valuetrue appsettings systemweb authentication modenone compilation debugtrue targetframework40 httpruntime systemweb systemwebserver modules remove nameformsauthentication modules systemwebserver runtime assemblybinding xmlnsurnschemasmicrosoftcomasmv1 dependentassembly assemblyidentity namenewtonsoftjson cultureneutral publickeytoken30ad4fe6b2a6aeed bindingredirect oldversion060 newversion60 dependentassembly dependentassembly assemblyidentity namesystemwebhelpers publickeytoken31bf3856ad364e35 bindingredirect oldversion1030 newversion30 dependentassembly dependentassembly assemblyidentity namesystemwebmvc publickeytoken31bf3856ad364e35 bindingredirect oldversion105200 newversion5200 dependentassembly dependentassembly assemblyidentity namesystemweboptimization publickeytoken31bf3856ad364e35 bindingredirect oldversion101100 newversion1100 dependentassembly dependentassembly assemblyidentity namesystemwebwebpages publickeytoken31bf3856ad364e35 bindingredirect oldversion1030 newversion30 dependentassembly dependentassembly assemblyidentity namewebgrease publickeytoken31bf3856ad364e35 bindingredirect oldversion1015214234 newversion15214234 dependentassembly assemblybinding runtime entityframework defaultconnectionfactory typesystemdataentityinfrastructurelocaldbconnectionfactory entityframework parameters parameter valuev110 parameters defaultconnectionfactory providers provider invariantnamesystemdatasqlclient typesystemdataentitysqlserversqlproviderservices entityframeworksqlserver providers entityframeworkconfigurationand here is my globalasaxusing systemusing systemcollectionsgenericusing systemlinqusing systemwebusing systemwebmvcusing systemweboptimizationusing systemwebroutingnamespace webapplication14 public class mvcapplication systemwebhttpapplication protected void application start arearegistrationregisterallareas filterconfigregisterglobalfiltersglobalfiltersfilters routeconfigregisterroutesroutetableroutes bundleconfigregisterbundlesbundletablebundles really at a loss at this point on what to do this is happening when opening a brand new mvc project as well as old ones i figured after the new install and updates the error would go away but i was wrong any help would be greatly appreciated example code model webapplication14modelsresetpasswordviewmodel viewbagtitle reset password h2viewbagtitleh2 using htmlbeginformresetpassword account formmethodpost new class formhorizontal role form htmlantiforgerytoken h4reset your passwordh4 hr htmlvalidationsummary new class textdanger htmlhiddenformodel modelcode div classformgroup htmllabelform memail new class colmd2 controllabel div classcolmd10 htmltextboxform memail new class formcontrol div div div classformgroup htmllabelform mpassword new class colmd2 controllabel div classcolmd10 htmlpasswordform mpassword new class formcontrol div div div classformgroup htmllabelform mconfirmpassword new class colmd2 controllabel div classcolmd10 htmlpasswordform mconfirmpassword new class formcontrol div div div classformgroup div classcolmdoffset2 colmd10 input typesubmit classbtn btndefault valuereset div div section scripts scriptsrenderbundlesjqueryval,['c#'] +722432,how to post a json with new apple swift language i am trying to learn the swifts apple language i am at playground and using xcode 6 beta i am trying to do a simple json post to a local nodejs server i already had googled about it and the major tutorials explain how to do it in a project not at playground than do not write stupid thinks like google it or it is obvious or look this link or nevertestedandnotfunctionalcodethis is what i am tryingvar request nsurlrequesturl nsurlstring httplocalhost30 cachepolicy nsurlrequestcachepolicyreloadignoringlocalcachedata timeoutinterval 5var response nsurlresponsevar error nserrornsurlconnectionsendsynchronousrequestrequest returningresponse response error errori had triedvar datastring some datavar request nsmutableurlrequesturl nsurlstring requesthttpmethod postlet data datastring as nsstringdatausingencodingnsutf8stringencodingvar requestbodydata nsdata datarequesthttpbody requestbodydatavar connection nsurlconnectionrequest request delegate nil startimmediately falseprintlnsending requestconnectionstartthank you,['ios'] +722454,animating layouts using the animatelayoutchanges attribute in xml i have a linearlayout for which i apply androidanimatelayoutchangestrue in the parent linearlayout when the user clicks a toggle button the linearlayout collapses i set the views visibility as linearlayoutgone programmatically and when they click it again it expands by programmatically setting the visibility back to linearlayoutvisiblethe animation of it collapsing and expanding works correctlyhowever any items below the collapsableexpandable linearlayout snap back to the top before the animation of the collapse is complete the items that are snapping back are not inside the parent which has animatelayoutchanges set to true and i do not think there is any way i can put them inside ithere is my layout hierarchy i did not mention the attributes to keep it short top most linearlayoutlinearlayout linearlayout containing androidanimatelayoutchangestrue linearlayout relativelayout containing button to toggle linearlayout visibility below relativelayout relativelayout linearlayout that has its visibility toggled linearlayout linearlayout linearlayoutlinearlayoutthis entire layout is inserted programmatically into another linearlayout see belowlinearlayout androidididform container androidlayout widthmatch parent androidlayout heightwrap content androidorientationvertical this is where the previous xml layout containing the toggleable linearlayout is inserted programmatically this button snaps back up to the top before the animation is complete button linearlayouti realize the problem would be solved if i added the button that snaps up to the linearlayout that has animatelayoutchanges as true however this is not an options for a few reasonsso is there any other work around,['android'] +722568,parameter passing in java i know that java is always passbyvalue but i do not understand why this workspublic static void swapint arr int i int j int tmp arri arri arrj arrj tmppublic static void mainstring args int arr 3 4 5 6 swaparr 1 3 arr becomes 3 6 5 4and this does not workpublic static void swapint arr int arr2 int tmp arr arr arr2 arr2 tmppublic static void mainstring args int arr 3 4 5 6 int arr2 1 2 5 6 swaparr arr2why,['java'] +722667,android error upload image in different android versions i am having problem with upload image in different android versions i need to send images for php server so i am using a webservice i did test with the versions froyo e jelly beans they works but the kitkat do not work i was reading about mediastore and i saw different ways and i do not if my its right or wrong i debbuged my project and i could see in kitkat the path is null logcat tell me java null pointer just in kitkat how can i do a application works for all versionuploadimagejavapackage brgovrjbarraemexposicaoimport androidaprogressdialogimport androidcontentactivitynotfoundexceptionimport androidcontentintentimport androiddatabasecursorimport androidneturiimport androidprovidermediastoreimport androidsupportv7appactionbaractivityimport androidosbundleimport androidutillogimport androidviewmenuimport androidviewmenuitemimport androidviewviewimport androidwidgetbuttonimport androidwidgetimageviewimport androidwidgettextviewimport androidwidgettoastimport javaiodataoutputstreamimport javaiofileimport javaiofileinputstreamimport javanethttpurlconnectionimport javanetmalformedurlexceptionimport javaneturlpublic class enviafoto extends actionbaractivity final int pick file result code 1 final int camera image 2 textview messagetext button uploadbutton button btntirafoto button selectimage imageview imgfoto int serverresponsecode 0 progressdialog dialog null string uploadserveruri string filepath override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity envia foto selectimage button findviewbyidridselectimage imgfoto imageview findviewbyidridimgfoto messagetext textviewfindviewbyidridmessagetext uploadbutton buttonfindviewbyidriduploadbutton btntirafoto button findviewbyidridbtntirafoto uploadserveruri addlisteners public string uritopathuri uri string projection mediastoreimagesmediadata cursor cursor managedqueryuri projection null null null int column index cursorgetcolumnindexorthrowmediastoreimagesmediadata cursormovetofirst return cursorgetstringcolumn index override protected void onactivityresult int requestcode int resultcode intent data if data null requestcode pick file result code requestcode camera image filepath uritopathdatagetdata imgfotosetimageuridatagetdata uploadbuttonsetvisibility1 public int uploadfilestring sourcefileuri string filename sourcefileuri httpurlconnection conn null dataoutputstream dos null string lineend rn string twohyphens string boundary int bytesread bytesavailable buffersize byte buffer int maxbuffersize 1 1024 1024 file sourcefile new filesourcefileuri if sourcefileisfile dialogthismiss logeuploadfile source file not exist filepath runonuithreadnew runnable public void run messagetextsettextsource file not exist filepath return 0 else try open a url connection to the servlet fileinputstream fileinputstream new fileinputstreamsourcefile url url new urluploadserveruri open a http connection to the url conn httpurlconnection urlopenconnection connsetdoinputtrue allow inputs connsetdooutputtrue allow outputs connsetusecachesfalse do not use a cached copy connsetrequestmethodpost connsetrequestpropertyconnection keepalive connsetrequestpropertyenctype multipartformdata connsetrequestpropertycontenttype multipartformdataboundary boundary connsetrequestpropertyuploaded file filename dos new dataoutputstreamconngetoutputstream doswritebytestwohyphens boundary lineend doswritebytescontentthisposition formdata nameuploaded filefilename filename lineend doswritebyteslineend create a buffer of maximum size bytesavailable fileinputstreamavailable buffersize mathminbytesavailable maxbuffersize buffer new bytebuffersize read file and write it into form bytesread fileinputstreamreadbuffer 0 buffersize while bytesread 0 doswritebuffer 0 buffersize bytesavailable fileinputstreamavailable buffersize mathminbytesavailable maxbuffersize bytesread fileinputstreamreadbuffer 0 buffersize send multipart form data necesary after file data doswritebyteslineend doswritebytestwohyphens boundary twohyphens lineend responses from the server code and message serverresponsecode conngetresponsecode string serverresponsemessage conngetresponsemessage logiuploadfile http response is serverresponsemessage serverresponsecode ifserverresponsecode 200 runonuithreadnew runnable public void run string msg envio feito com sucesso messagetextsettextmsg toastmaketextenviafotothis file upload complete toastlength shortshow close the streams fileinputstreamclose dosflush dosclose catch malformedurlexception ex dialogthismiss exprintstacktrace runonuithreadnew runnable public void run messagetextsettextmalformedurlexception exception check script url toastmaketextenviafotothis malformedurlexception toastlength shortshow logeupload file to server error exgetmessage ex catch exception e dialogthismiss eprintstacktrace runonuithreadnew runnable public void run messagetextsettextgot exception see logcat toastmaketextenviafotothis got exception see logcat toastlength shortshow logeupload file to server exception exception egetmessage e dialogthismiss return serverresponsecode end else block private void addlisteners selectimagesetonclicklistenernew viewonclicklistener public void onclickview view intent intent new intentintentaction get content intent chooser intentcreatechooserintentescolha a foto intentsettypeimage try startactivityforresultchooser pick file result code catch activitynotfoundexception e logetag egetmessage uploadbuttonsetonclicklistenernew viewonclicklistener override public void onclickview v dialog progressdialogshowenviafotothis enviando foto true new threadnew runnable public string uritopathuri uri string projection mediastoreimagesmediadata cursor cursor managedqueryuri projection null null null int column index cursorgetcolumnindexorthrowmediastoreimagesmediadata cursormovetofirst return cursorgetstringcolumn index protected void onactivityresult int requestcode int resultcode intent data if data null requestcode pick file result code filepath uritopathdatagetdata imgfotosetimageuridatagetdata uploadbuttonsetvisibility1 public void run runonuithreadnew runnable public void run messagetextsettextenviando foto uploadfilefilepath start btntirafotosetonclicklistenernew viewonclicklistener override public void onclickview view startactivityforresultnew intentmediastoreaction image capture camera image override public boolean oncreateoptionsmenumenu menu inflate the menu this adds items to the action bar if it is present getmenuinflaterinflatermenuenvia foto menu return true override public boolean onoptionsitemselectedmenuitem item handle action bar item clicks here the action bar will automatically handle clicks on the homeup button so long as you specify a parent activity in androidmanifestxml int id itemgetitemid if id ridaction settings return true return superonoptionsitemselecteditem manifestxml version10 encodingutf8manifest xmlnsandroid packagebrgovrjbarraemexposicao usespermission androidnameandroidpermissioninternet usespermission androidnameandroidpermissionread external storage usessdk androidminsdkversion8 androidtargetsdkversion19 application androidallowbackuptrue androidicondrawableic launcher androidlabelstringapp name androidthemestyleapptheme activity androidnamebrgovrjbarraemexposicaoenviafoto androidlabelstringapp name androidscreenorientationportrait intentfilter category androidnameandroidintentcategorylauncher intentfilter activity activity androidnamebrgovrjbarraemexposicaoenquete androidlabelstringtitle activity enquete intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity applicationmanifestlogcat0704 084654084 1356513565brgovrjbarraemexposicao iadrenoegli1 qegldrvapi eglinitialize410 egl 14 qualcomm build au linux android lnxla351 rb1040402048018 msm8226 lnxla351 rb1 release au opengl es shader compiler version e0312408 build date 030714 fri local branch remote branch quiclnxla351 rb11 local patches none reconstruct branch au linux android lnxla351 rb1040402048018 f2fd134 nothing0704 084654157 1356513565brgovrjbarraemexposicao dopenglrendereri1 enabling debug mode 00704 084703105 1356513565brgovrjbarraemexposicao dandroidruntimei1 shutting down vm0704 084703121 1356513565brgovrjbarraemexposicao eandroidruntimei1 fatal exception main process brgovrjbarraemexposicao pid 13565 javalangruntimeexception failure delivering result resultinfowhonull request2 result1 dataintent actinlinedata has extras to activity brgovrjbarraemexposicaobrgovrjbarraemexposicaoenviafoto javalangnullpointerexception attempt to invoke virtual method javalangstring androidneturigetscheme on a null object reference at androidappactivitythreaddeliverresultsactivitythreadjava3432 at androidappactivitythreadhandlesendresultactivitythreadjava3475 at androidappactivitythreadaccess1300activitythreadjava139 at androidappactivitythreadhhandlemessageactivitythreadjava1258 at androidoshandlerthispatchmessagehandlerjava102 at androidoslooperlooplooperjava136 at androidappactivitythreadmainactivitythreadjava5086 at javalangreflectmethodinvokenative method at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava785 at comandroidinternaloszygoteinitmainzygoteinitjava601 caused by javalangnullpointerexception attempt to invoke virtual method javalangstring androidneturigetscheme on a null object reference at androidcontentcontentresolveracquireunstableprovidercontentresolverjava1420 at androidcontentcontentresolverquerycontentresolverjava445 at androidcontentcontentresolverquerycontentresolverjava404 at brgovrjbarraemexposicaoenviafotouritopathenviafotojava80 at brgovrjbarraemexposicaoenviafotoonactivityresultenviafotojava97 at androidappactivitythispatchactivityresultactivityjava5446 at androidappactivitythreaddeliverresultsactivitythreadjava3428a a a a a a a a a a a a at androidappactivitythreadhandlesendresultactivitythreadjava3475a a a a a a a a a a a a at androidappactivitythreadaccess1300activitythreadjava139a a a a a a a a a a a a at androidappactivitythreadhhandlemessageactivitythreadjava1258a a a a a a a a a a a a at androidoshandlerthispatchmessagehandlerjava102a a a a a a a a a a a a at androidoslooperlooplooperjava136a a a a a a a a a a a a at androidappactivitythreadmainactivitythreadjava5086a a a a a a a a a a a a at javalangreflectmethodinvokenative methoda a a a a a a a a a a a at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava785a a a a a a a a a a a a at comandroidinternaloszygoteinitmainzygoteinitjava6010704 084705066 1356513565brgovrjbarraemexposicao iprocessi1 sending signal pid 13565 sig 90704 085133298 1551815518brgovrjbarraemexposicao iadrenoegli1 qegldrvapi eglinitialize410 egl 14 qualcomm build au linux android lnxla351 rb1040402048018 msm8226 lnxla351 rb1 release au opengl es shader compiler version e0312408 build date 030714 fri local branch remote branch quiclnxla351 rb11 local patches none reconstruct branch au linux android lnxla351 rb1040402048018 f2fd134 nothing0704 0851393 1551815518brgovrjbarraemexposicao dopenglrendereri1 enabling debug mode 00704 085208015 1551815530brgovrjbarraemexposicao wcursorwrapperinneri1 cursor finalized without prior close0704 085210068 1551816522brgovrjbarraemexposicao eandroidruntimei1 fatal exception thread34287 process brgovrjbarraemexposicao pid 15518 javalangnullpointerexception attempt to invoke virtual method char javalangstringtochararray on a null object reference at javaiofilefixslashesfilejava185 at javaiofileinitfilejava134 at brgovrjbarraemexposicaoenviafotouploadfileenviafotojava102 at brgovrjbarraemexposicaoenviafoto61runenviafotojava277 at javalangthreadrunthreadjava8110704 085210815 1551815518brgovrjbarraemexposicao ewindowmanageri1 androidviewwindowleaked activity brgovrjbarraemexposicaoenviafoto has leaked window comandroidinternalpolicyimplphonewindowdecorview65280820 ve rd 00684192 that was originally added here at androidviewviewrootimplinitviewrootimpljava359 at androidviewwindowmanagerglobaladdviewwindowmanagerglobaljava248 at androidviewwindowmanagerimpladdviewwindowmanagerimpljava69 at androidappdialogshowdialogjava286 at androidaprogressdialogshowprogressdialogjava116 at androidaprogressdialogshowprogressdialogjava99 at brgovrjbarraemexposicaoenviafoto6onclickenviafotojava250 at androidviewviewperformclickviewjava4456 at androidviewviewperformclickrunviewjava18465 at androidoshandlerhandlecallbackhandlerjava733 at androidoshandlerthispatchmessagehandlerjava95 at androidoslooperlooplooperjava136 at androidappactivitythreadmainactivitythreadjava5086 at javalangreflectmethodinvokenative method at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava785 at comandroidinternaloszygoteinitmainzygoteinitjava6010704 090323546 1808318083brgovrjbarraemexposicao iadrenoegli1 qegldrvapi eglinitialize410 egl 14 qualcomm build au linux android lnxla351 rb1040402048018 msm8226 lnxla351 rb1 release au opengl es shader compiler version e0312408 build date 030714 fri local branch remote branch quiclnxla351 rb11 local patches none reconstruct branch au linux android lnxla351 rb1040402048018 f2fd134 nothing0704 090323614 1808318083brgovrjbarraemexposicao dopenglrendereri1 enabling debug mode 00704 090414226 1808318096brgovrjbarraemexposicao wcursorwrapperinneri1 cursor finalized without prior close0704 090414428 1808318083brgovrjbarraemexposicao iadrenoegli1 qegldrvapi eglinitialize410 egl 14 qualcomm build au linux android lnxla351 rb1040402048018 msm8226 lnxla351 rb1 release au opengl es shader compiler version e0312408 build date 030714 fri local branch remote branch quiclnxla351 rb11 local patches none reconstruct branch au linux android lnxla351 rb1040402048018 f2fd134 nothing0704 090417318 1808319131brgovrjbarraemexposicao eandroidruntimei1 fatal exception thread34498 process brgovrjbarraemexposicao pid 18083 javalangnullpointerexception attempt to invoke virtual method char javalangstringtochararray on a null object reference at javaiofilefixslashesfilejava185 at javaiofileinitfilejava134 at brgovrjbarraemexposicaoenviafotouploadfileenviafotojava100 at brgovrjbarraemexposicaoenviafoto61runenviafotojava275 at javalangthreadrunthreadjava8110704 090418179 1808318083brgovrjbarraemexposicao ewindowmanageri1 androidviewwindowleaked activity brgovrjbarraemexposicaoenviafoto has leaked window comandroidinternalpolicyimplphonewindowdecorview65280100 ve rd 00684192 that was originally added here at androidviewviewrootimplinitviewrootimpljava359 at androidviewwindowmanagerglobaladdviewwindowmanagerglobaljava248 at androidviewwindowmanagerimpladdviewwindowmanagerimpljava69 at androidappdialogshowdialogjava286 at androidaprogressdialogshowprogressdialogjava116 at androidaprogressdialogshowprogressdialogjava99 at brgovrjbarraemexposicaoenviafoto6onclickenviafotojava248 at androidviewviewperformclickviewjava4456 at androidviewviewperformclickrunviewjava18465 at androidoshandlerhandlecallbackhandlerjava733 at androidoshandlerthispatchmessagehandlerjava95 at androidoslooperlooplooperjava136 at androidappactivitythreadmainactivitythreadjava5086 at javalangreflectmethodinvokenative method at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava785 at comandroidinternaloszygoteinitmainzygoteinitjava601updated after instance dialog0704 095417341 2676326763brgovrjbarraemexposicao dandroidruntimei1 shutting down vm 0704 095417364 2676326763brgovrjbarraemexposicao eandroidruntimei1 fatal exception main process brgovrjbarraemexposicao pid 26763 javalangruntimeexception unable to instantiate activity componentinfobrgovrjbarraemexposicaobrgovrjbarraemexposicaoenviafoto javalanginstantiationexception brgovrjbarraemexposicaoenviafoto at androidappactivitythreadperformlaunchactivityactivitythreadjava2124 at androidappactivitythreadhandlelaunchactivityactivitythreadjava2257 at androidappactivitythreadaccess800activitythreadjava139 at androidappactivitythreadhhandlemessageactivitythreadjava1210 at androidoshandlerthispatchmessagehandlerjava102 at androidoslooperlooplooperjava136 at androidappactivitythreadmainactivitythreadjava5086 at javalangreflectmethodinvokenative method at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava785 at comandroidinternaloszygoteinitmainzygoteinitjava601 caused by javalanginstantiationexception brgovrjbarraemexposicaoenviafoto at javalangclassnewinstanceclassjava1561 at androidappinstrumentationnewactivityinstrumentationjava1084 at androidappactivitythreadperformlaunchactivityactivitythreadjava2115 at androidappactivitythreadhandlelaunchactivityactivitythreadjava2257 at androidappactivitythreadaccess800activitythreadjava139 at androidappactivitythreadhhandlemessageactivitythreadjava1210 at androidoshandlerthispatchmessagehandlerjava102 at androidoslooperlooplooperjava136 at androidappactivitythreadmainactivitythreadjava5086 at javalangreflectmethodinvokenative method at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava785 at comandroidinternaloszygoteinitmainzygoteinitjava601,"['java', 'android']" +722724,is there a way to use dynamic in lambda expression tree first spec we use mvc5 net 451 and entity framework 61in our mvc5 business application we have a lot of repetitive crud code my job is to automate most of it which means extracting it to base classes and making it reusable right now i have base classes for controllers view models and ef6 entity modelsmy abstract base class that all ef6 entities inheritpublic abstract class baseentitytsubclass where tsubclass baseentitytsubclass public abstract expressionfunctsubclass object updatecriterionupdatecriterion method is used in addorupdate method of database context i have a generic parameter for subclasses because updatecriterion needs to return lambda expression that uses exact subclass type not an interface or base class an extremely simplified subclass implementing this abstract base class would look like thispublic class worker baseentityworker public int id get set public int name get set public override expressionfuncworker object updatecriterion return worker workerid after that in saveorupdate action of my base controller i would have code like thispublic actionresult savetviewmodel viewmodel if modelstateisvalid var entitymodel viewmodelconstructentitymodel dbsettentitymodeladdorupdatetentitymodelentitymodelupdatecriterion entitymodel dbsavechanges thanks to that subclasses of the base controller do not need to implement save method themselves as they did before now all of this works and it actually works really well despite the funky syntax i mean class baseentitytsubclass where tsubclass baseentitytsubclass seriously here comes my problem for most of the entities field id is the key but for some it is not so i cannot generalise properly with a superclass implementation so for now every entity subclass implements it is own updatecriterion but since for most 90 entities e eid is the correct implementation i have a lot of duplication so i want to rewrite the entity base class to something like thispublic abstract class baseentitytsubclass where tsubclass baseentitytsubclass public virtual expressionfunctsubclass object updatecriterion return entity dynamicentityid the intention is to provide default implementation that uses id as key and allow subclasses to override it if they use a different key i cannot use an interface or a base class with id field because not all entities have it i thought i would use dynamic to pull out id field but i get following error error an expression tree may not contain a dynamic operation so any idea on how to do this would reflection work in base updatecriterion,"['c#', '.net']" +722793,how can i map a spring boot repositoryrestresource to a specific url i cannot seem to be able to map my repository in any location other than the followingrepositoryrestresourcecollectionresourcerel item path itempublic interface itemrepository extends pagingandsortingrepositoryitem long i thought i can use path someotherpathitembut the mapping does not resolve i gethttp error 404problem accessing someotherpathitem reasonnot foundin springdata javadoc path is defined as the path segment under which this resource is to be exportedwhat am i doing wrong,['java'] +722863,laravel session flash persists for 2 requests recently i have changed to laravel from codeigniter everything was going fine except i encountered a problem with sessionflashwhen i create new user i get success message but it will persist for 2 requests even i did not pass the validatormy code in userscontrollerfunction getcreateuser config array pagename createuser pagetitle create user formurl actionuserscontrollerpostcreateuser modelfields array arraydb name employee id text employee id mandatory true arraydb name full name text full name mandatory true arraydb name email text email mandatory false arraydb name password text passwordvalue 12345 mandatory true submit text create return viewmakelayoutsform configfunction postcreateuser config array pagename createuser pagetitle create user formurl actionuserscontrollerpostcreateuser modelfields array arraydb name employee id text employee id mandatory true arraydb name full name text full name mandatory true arraydb name email text email mandatory false arraydb name password text passwordvalue 12345 mandatory true submit text create validator uservalidateinputall ifvalidatorpasses user new userinputall userpassword hashmakeinputgetpassword usercompany id 1 usersave sessionflashmessage user created successfully sessionflashalertclass alertsuccess return viewmakelayoutsform config return viewmakelayoutsform configwitherrorsvalidatormessagesin formbladeif errorscount 0 div classalert alertdanger pthe following errors have occurredp ul foreach errorsall as message li message li endforeach uldivendifin masterbladeifsessionhasmessagep classalert sessiongetalertclass alertinfo alertthismissable sessiongetmessage pendifmaybe i am not alone with this issue here is another unanswered questionupdatefor anyone in future facing this problem never flash session data without redirectingmy code now looks like thisfunction postcreateuser validator uservalidateinputall ifvalidatorpasses user new userinputall userpassword hashmakeinputgetpassword usercompany id 1 usersave sessionflashmessage user created successfully sessionflashalertclass alertsuccess else sessionflashmessage helpersformaterrorsvalidatormessagesall sessionflashalertclass alertdanger return redirectactionuserscontrollergetcreateuser,['php'] +722883,classformaterror in java 8 i was making a class similar to javautillinkedlist and got a completely unexpected classformaterror my ide shows no warnings fyi i am using java 8u20 update fixed in java 8u60 tihisi iniciliuidieisi iailili irieilieiviainiti imieitihioidisii updated example as fully compilableimport javaioserializableimport javautilimport javautilfunctionfunctionpublic class fooe implements dequee serializable private static final long serialversionuid 0l private final node sentinel sentinelinit private final iterablenode nodes iterablenode serializable new iteratornode suppresswarningsunuseddeclaration private static final long serialversionuid 0l private node next sentinelnext override public boolean hasnext return next sentinel override public node next if hasnext throw new nosuchelementexception node old next next nextnext return old override public void remove if nextprevious sentinel throw new illegalstateexception removenodenextprevious override public boolean isempty return false override public object toarray return new object0 override public t t toarrayt a return null override public boolean containsallcollection c return false override public boolean removeallcollection c return false override public boolean retainallcollection c return false override public void clear override public void addfirste e override public void addlaste e override public boolean offerlaste e return false override public e removefirst return null override public e removelast return null override public e pollfirst return null override public e getfirst return null override public e getlast return null override public e peekfirst return null override public boolean removefirstoccurrenceobject o return false override public boolean removelastoccurrenceobject o return false override public e remove return null override public e element return null override public void pushe e override public e pop return null override public boolean containsobject o return false override public boolean offerfirste e return false override public e polast return null override public e peeklast return null override public boolean offere e node node new nodee sentinelpreviousnext node nodeprevious sentinelprevious sentinelprevious node nodenext sentinel return true override public e poll return null override public e peek return null override public boolean removeobject o for node node nodes if nodevalueequalso removenodenode return true return false override public int size return 0 override public iteratore descendingiterator return null override public iteratore iterator return new iteratore private final iteratornode backingiter nodesiterator override public boolean hasnext return backingiterhasnext override public e next return backingiternextvalue override public void remove backingiterremove private node sentinelinit node sentinel new node sentinelnext sentinel sentinelprevious sentinel return sentinel private void removenodenode node nodepreviousnext nodenext nodenextprevious nodeprevious private class node implements serializable private static final long serialversionuid 0l public e value public node next public node previous public nodee value thisvalue value public node thisnull public static i o listo mapfunction super i o function iterablei objects arraylisto returned new arraylist for i obj objects returnedaddfunctionapplyobj return returned override public boolean addallcollection extends e c boolean ret false for boolean changed mapthisadd c if changed ret true return ret override public boolean adde e if offere throw new illegalstateexception return true public static void mainstring args foostring list new foo systemoutprintlnconstructed list listaddallarraysaslista b c systemoutprintlnadded a b and c listforeachsystemoutprintln listremoveb listforeachsystemoutprintln here is the outputconstructed listadded a b and cexception in thread main javalangclassformaterror duplicate field namesignature in class file ukorgmefoo1 at javalangclassloaderdefineclass1native method at javalangclassloaderdefineclassclassloaderjava760 at javasecuritysecureclassloaderdefineclasecureclassloaderjava142 at javaneturlclassloaderdefineclassurlclassloaderjava455 at javaneturlclassloaderaccess100urlclassloaderjava73 at javaneturlclassloader1runurlclassloaderjava367 at javaneturlclassloader1runurlclassloaderjava361 at javasecurityaccesscontrollerdoprivilegednative method at javaneturlclassloaderfindclassurlclassloaderjava360 at javalangclassloaderloadclassclassloaderjava424 at sunmisclauncherappclassloaderloadclasslauncherjava308 at javalangclassloaderloadclassclassloaderjava357 at ukorgmefoolambdanewc83cc3811foojava18 at ukorgmefoolambda11392838282iteratorunknown source at ukorgmefoo2initfoojava2 at ukorgmefooiteratorfoojava221 at javalangiterableforeachiterablejava74 at ukorgmefoomainfoojava300 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava62 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43 at javalangreflectmethodinvokemethodjava483 at comintellijrtexecutionapplicationappmainmainappmainjava134,['java'] +723046,resolve promises one after another ie in sequence consider the following code that reads an array of files in a serialsequential manner readfiles returns a promise which is resolved only once all files have been read in sequencevar q requireqvar readfile functionfile returns a promisevar readfiles functionfiles var deferred qdefer var readsequential functionindex if index fileslength deferredresolve else readfilefilesindexthenfunction readsequentialindex 1 readsequential0 start return deferredpromisethe code above code works but i do not like having to do recursion for things to occur sequentially is there a simpler way that this code can be rewritten so that i do not have to use my weird readsequential functionoriginally i tried to use qall but that caused all of the readfile calls to happen concurrently which is not what i wantvar readfiles functionfiles return qallfilesmapfunctionfile return readfilefile,['javascript'] +723138,error javaxpersistencejoincolumnforeignkeyljavaxpersistenceforeignkey with spring controller i have a simple two table application written in spring mvc and which uses hibernate everything works perfectly well but if i try to unit test one of the controllers i get messageinvocation of init method failed nested exception is javalangnosuchmethoderror javaxpersistencejoincolumnforeignkeyljavaxpersistenceforeignkeythe unit test method is belowrunwithvaluespringjunit4classrunnerclasswebappconfigurationcontextconfigurationfilecnetbeansprojectslibrarybuildwebwebinflibrary servletxmlpublic class testpersoncontroller autowiredprivate personservice personserviceautowiredprivate webapplicationcontext wacprivate mockmvc mockmvcbeforepublic void setup thismockmvc mockmvcbuilderswebappcontextsetupthiswacbuildtestpublic void testgetprofile person mockperson new person mockpersonsetpersonid1 mockpersonsetnamemr brown mockpersonsetaddressutopia planitia on mars mockpersonsettelephone1234567890 mockpersonsetemail whenpersonserviceget1thenreturnmockperson try mockmvcperformgetpersonprofilepersonid1 andexpectstatusisok andexpectviewnameviewprofile andexpectforwardedurlwebinfjspviewprofilejsp andexpectmodelattributeperson hassize1 andexpectmodelattributeperson hasitem allof haspropertypersonid is1 haspropertyname ismr brown haspropertyaddress is53 onslow gardens haspropertytelephone is1234567890 haspropertyemail is catchexception e miscprintstacktracee verifypersonservice times1get1 verifynomoreinteractionspersonservice the two classes forming the model of the application are joined via a 1m relationship the first table person hasidcolumnnameperson id uniquetrue nullablefalse generatedvaluestrategygenerationtypeautoprivate integer personidcolumnnamename nullablefalse length50 private string namecolumnnameaddress nullablefalse length100private string addresscolumnnametelephone nullablefalse length10private string telephonecolumnnameemail nullablefalse length50private string emailonetomanycascadecascadetypeall fetchfetchtypelazy mappedbyperson jsonmanagedreferenceprivate listbook booksand the second table hasidcolumnnamebook id uniquetrue nullablefalsegeneratedvaluestrategygenerationtypeautoprivate integer bookidcolumnnameauthor nullablefalse length50private string authorcolumnnametitle nullablefalse length50private string titlecolumnnamedescription nullablefalse length500private string description columnnameonloan nullablefalseprivate boolean onloanmanytoonefetchfetchtypelazyjoincolumnnameperson idjsonbackreferenceprivate person personthese classes work correctly under all other circumstances except this new unit test of a method in the person controlleri do not use the foreignkey annotation in my classes because there seems to be no need to and if i try java says it is unnecessarydo i have a dependency issue or whatthe unit test stacktrace followstestsuite librarypersontestpersoncontrollertests run 1 failures 0 errors 1 skipped 0 time elapsed 2085 sec standard error log4jwarn no appenders could be found for logger orgspringframeworktestcontextjunit4springjunit4classrunnerlog4jwarn please initialize the log4j system properly testcase testgetprofilelibrarypersontestpersoncontroller caused an errorfailed to load applicationcontextjavalangillegalstateexception failed to load applicationcontext at orgspringframeworktestcontextcacheawarecontextloaderdelegateloadcontextcacheawarecontextloaderdelegatejava99 at orgspringframeworktestcontextdefaulttestcontextgetapplicationcontextdefaulttestcontextjava101 at orgspringframeworktestcontextwebservlettestexecutionlistenersetuprequestcontextifnecessaryservlettestexecutionlistenerjava155 at orgspringframeworktestcontextwebservlettestexecutionlistenerpreparetestinstanceservlettestexecutionlistenerjava100 at orgspringframeworktestcontexttestcontextmanagerpreparetestinstancetestcontextmanagerjava319 at orgspringframeworktestcontextjunit4springjunit4classrunnercreatetestspringjunit4classrunnerjava212 at orgspringframeworktestcontextjunit4springjunit4classrunner1runreflectivecallspringjunit4classrunnerjava289 at orgspringframeworktestcontextjunit4springjunit4classrunnermethodblockspringjunit4classrunnerjava291 at orgspringframeworktestcontextjunit4springjunit4classrunnerrunchildspringjunit4classrunnerjava232 at orgspringframeworktestcontextjunit4springjunit4classrunnerrunchildspringjunit4classrunnerjava89 at orgspringframeworktestcontextjunit4statementsrunbeforetestclasscallbacksevaluaterunbeforetestclasscallbacksjava61 at orgspringframeworktestcontextjunit4statementsrunaftertestclasscallbacksevaluaterunaftertestclasscallbacksjava71 at orgspringframeworktestcontextjunit4springjunit4classrunnerrunspringjunit4classrunnerjava175caused by orgspringframeworkbeansfactorybeancreationexception error creating bean with name admincontroller injection of autowired dependencies failed nested exception is orgspringframeworkbeansfactorybeancreationexception could not autowire field private libraryservicepersonservice librarycontrolleradminadmincontrollerpersonservice nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name personservice injection of autowired dependencies failed nested exception is orgspringframeworkbeansfactorybeancreationexception could not autowire field private librarydaopersondaoimpl libraryservicepersonservicepersondao nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name persondaoimpl injection of autowired dependencies failed nested exception is orgspringframeworkbeansfactorybeancreationexception could not autowire field private orghibernatesessionfactory librarydaopersondaoimplsessionfactory nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name sessionfactory defined in url filecnetbeansprojectslibrarybuildwebwebinflibraryservletxml invocation of init method failed nested exception is javalangnosuchmethoderror javaxpersistencejoincolumnforeignkeyljavaxpersistenceforeignkey at orgspringframeworkbeansfactoryannotationautowiredannotationbeanpostprocessorpostprocesspropertyvaluesautowiredannotationbeanpostprocessorjava292 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorypopulatebeanabstractautowirecapablebeanfactoryjava1185 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorydocreatebeanabstractautowirecapablebeanfactoryjava537 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorycreatebeanabstractautowirecapablebeanfactoryjava475 at orgspringframeworkbeansfactorysupportabstractbeanfactory1getobjectabstractbeanfactoryjava304 at orgspringframeworkbeansfactorysupportdefaultsingletonbeanregistrygetsingletondefaultsingletonbeanregistryjava228 at orgspringframeworkbeansfactorysupportabstractbeanfactorydogetbeanabstractbeanfactoryjava300 at orgspringframeworkbeansfactorysupportabstractbeanfactorygetbeanabstractbeanfactoryjava195 at orgspringframeworkbeansfactorysupportdefaultlistablebeanfactorypreinstantiatesingletonsdefaultlistablebeanfactoryjava700 at orgspringframeworkcontextsupportabstractapplicationcontextfinishbeanfactoryinitializationabstractapplicationcontextjava760 at orgspringframeworkcontextsupportabstractapplicationcontextrefreshabstractapplicationcontextjava482 at orgspringframeworktestcontextwebabstractgenericwebcontextloaderloadcontextabstractgenericwebcontextloaderjava129 at orgspringframeworktestcontextwebabstractgenericwebcontextloaderloadcontextabstractgenericwebcontextloaderjava60 at orgspringframeworktestcontextsupportabstractdelegatingsmartcontextloaderdelegateloadingabstractdelegatingsmartcontextloaderjava100 at orgspringframeworktestcontextsupportabstractdelegatingsmartcontextloaderloadcontextabstractdelegatingsmartcontextloaderjava250 at orgspringframeworktestcontextcacheawarecontextloaderdelegateloadcontextinternalcacheawarecontextloaderdelegatejava64 at orgspringframeworktestcontextcacheawarecontextloaderdelegateloadcontextcacheawarecontextloaderdelegatejava91caused by orgspringframeworkbeansfactorybeancreationexception could not autowire field private libraryservicepersonservice librarycontrolleradminadmincontrollerpersonservice nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name personservice injection of autowired dependencies failed nested exception is orgspringframeworkbeansfactorybeancreationexception could not autowire field private librarydaopersondaoimpl libraryservicepersonservicepersondao nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name persondaoimpl injection of autowired dependencies failed nested exception is orgspringframeworkbeansfactorybeancreationexception could not autowire field private orghibernatesessionfactory librarydaopersondaoimplsessionfactory nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name sessionfactory defined in url filecnetbeansprojectslibrarybuildwebwebinflibraryservletxml invocation of init method failed nested exception is javalangnosuchmethoderror javaxpersistencejoincolumnforeignkeyljavaxpersistenceforeignkey at orgspringframeworkbeansfactoryannotationautowiredannotationbeanpostprocessorautowiredfieldelementinjectautowiredannotationbeanpostprocessorjava508 at orgspringframeworkbeansfactoryannotationinjectionmetadatainjectinjectionmetadatajava87 at orgspringframeworkbeansfactoryannotationautowiredannotationbeanpostprocessorpostprocesspropertyvaluesautowiredannotationbeanpostprocessorjava289caused by orgspringframeworkbeansfactorybeancreationexception error creating bean with name personservice injection of autowired dependencies failed nested exception is orgspringframeworkbeansfactorybeancreationexception could not autowire field private librarydaopersondaoimpl libraryservicepersonservicepersondao nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name persondaoimpl injection of autowired dependencies failed nested exception is orgspringframeworkbeansfactorybeancreationexception could not autowire field private orghibernatesessionfactory librarydaopersondaoimplsessionfactory nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name sessionfactory defined in url filecnetbeansprojectslibrarybuildwebwebinflibraryservletxml invocation of init method failed nested exception is javalangnosuchmethoderror javaxpersistencejoincolumnforeignkeyljavaxpersistenceforeignkey at orgspringframeworkbeansfactoryannotationautowiredannotationbeanpostprocessorpostprocesspropertyvaluesautowiredannotationbeanpostprocessorjava292 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorypopulatebeanabstractautowirecapablebeanfactoryjava1185 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorydocreatebeanabstractautowirecapablebeanfactoryjava537 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorycreatebeanabstractautowirecapablebeanfactoryjava475 at orgspringframeworkbeansfactorysupportabstractbeanfactory1getobjectabstractbeanfactoryjava304 at orgspringframeworkbeansfactorysupportdefaultsingletonbeanregistrygetsingletondefaultsingletonbeanregistryjava228 at orgspringframeworkbeansfactorysupportabstractbeanfactorydogetbeanabstractbeanfactoryjava300 at orgspringframeworkbeansfactorysupportabstractbeanfactorygetbeanabstractbeanfactoryjava195 at orgspringframeworkbeansfactorysupportdefaultlistablebeanfactoryfindautowirecandidatesdefaultlistablebeanfactoryjava1014 at orgspringframeworkbeansfactorysupportdefaultlistablebeanfactorydoresolvedependencydefaultlistablebeanfactoryjava957 at orgspringframeworkbeansfactorysupportdefaultlistablebeanfactoryresolvedependencydefaultlistablebeanfactoryjava855 at orgspringframeworkbeansfactoryannotationautowiredannotationbeanpostprocessorautowiredfieldelementinjectautowiredannotationbeanpostprocessorjava480caused by orgspringframeworkbeansfactorybeancreationexception could not autowire field private librarydaopersondaoimpl libraryservicepersonservicepersondao nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name persondaoimpl injection of autowired dependencies failed nested exception is orgspringframeworkbeansfactorybeancreationexception could not autowire field private orghibernatesessionfactory librarydaopersondaoimplsessionfactory nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name sessionfactory defined in url filecnetbeansprojectslibrarybuildwebwebinflibraryservletxml invocation of init method failed nested exception is javalangnosuchmethoderror javaxpersistencejoincolumnforeignkeyljavaxpersistenceforeignkey at orgspringframeworkbeansfactoryannotationautowiredannotationbeanpostprocessorautowiredfieldelementinjectautowiredannotationbeanpostprocessorjava508 at orgspringframeworkbeansfactoryannotationinjectionmetadatainjectinjectionmetadatajava87 at orgspringframeworkbeansfactoryannotationautowiredannotationbeanpostprocessorpostprocesspropertyvaluesautowiredannotationbeanpostprocessorjava289caused by orgspringframeworkbeansfactorybeancreationexception error creating bean with name persondaoimpl injection of autowired dependencies failed nested exception is orgspringframeworkbeansfactorybeancreationexception could not autowire field private orghibernatesessionfactory librarydaopersondaoimplsessionfactory nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name sessionfactory defined in url filecnetbeansprojectslibrarybuildwebwebinflibraryservletxml invocation of init method failed nested exception is javalangnosuchmethoderror javaxpersistencejoincolumnforeignkeyljavaxpersistenceforeignkey at orgspringframeworkbeansfactoryannotationautowiredannotationbeanpostprocessorpostprocesspropertyvaluesautowiredannotationbeanpostprocessorjava292 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorypopulatebeanabstractautowirecapablebeanfactoryjava1185 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorydocreatebeanabstractautowirecapablebeanfactoryjava537 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorycreatebeanabstractautowirecapablebeanfactoryjava475 at orgspringframeworkbeansfactorysupportabstractbeanfactory1getobjectabstractbeanfactoryjava304 at orgspringframeworkbeansfactorysupportdefaultsingletonbeanregistrygetsingletondefaultsingletonbeanregistryjava228 at orgspringframeworkbeansfactorysupportabstractbeanfactorydogetbeanabstractbeanfactoryjava300 at orgspringframeworkbeansfactorysupportabstractbeanfactorygetbeanabstractbeanfactoryjava195 at orgspringframeworkbeansfactorysupportdefaultlistablebeanfactoryfindautowirecandidatesdefaultlistablebeanfactoryjava1014 at orgspringframeworkbeansfactorysupportdefaultlistablebeanfactorydoresolvedependencydefaultlistablebeanfactoryjava957 at orgspringframeworkbeansfactorysupportdefaultlistablebeanfactoryresolvedependencydefaultlistablebeanfactoryjava855 at orgspringframeworkbeansfactoryannotationautowiredannotationbeanpostprocessorautowiredfieldelementinjectautowiredannotationbeanpostprocessorjava480caused by orgspringframeworkbeansfactorybeancreationexception could not autowire field private orghibernatesessionfactory librarydaopersondaoimplsessionfactory nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name sessionfactory defined in url filecnetbeansprojectslibrarybuildwebwebinflibraryservletxml invocation of init method failed nested exception is javalangnosuchmethoderror javaxpersistencejoincolumnforeignkeyljavaxpersistenceforeignkey at orgspringframeworkbeansfactoryannotationautowiredannotationbeanpostprocessorautowiredfieldelementinjectautowiredannotationbeanpostprocessorjava508 at orgspringframeworkbeansfactoryannotationinjectionmetadatainjectinjectionmetadatajava87 at orgspringframeworkbeansfactoryannotationautowiredannotationbeanpostprocessorpostprocesspropertyvaluesautowiredannotationbeanpostprocessorjava289caused by orgspringframeworkbeansfactorybeancreationexception error creating bean with name sessionfactory defined in url filecnetbeansprojectslibrarybuildwebwebinflibraryservletxml invocation of init method failed nested exception is javalangnosuchmethoderror javaxpersistencejoincolumnforeignkeyljavaxpersistenceforeignkey at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactoryinitializebeanabstractautowirecapablebeanfactoryjava1553 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorydocreatebeanabstractautowirecapablebeanfactoryjava539 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorycreatebeanabstractautowirecapablebeanfactoryjava475 at orgspringframeworkbeansfactorysupportabstractbeanfactory1getobjectabstractbeanfactoryjava304 at orgspringframeworkbeansfactorysupportdefaultsingletonbeanregistrygetsingletondefaultsingletonbeanregistryjava228 at orgspringframeworkbeansfactorysupportabstractbeanfactorydogetbeanabstractbeanfactoryjava300 at orgspringframeworkbeansfactorysupportabstractbeanfactorygetbeanabstractbeanfactoryjava195 at orgspringframeworkbeansfactorysupportdefaultlistablebeanfactoryfindautowirecandidatesdefaultlistablebeanfactoryjava1014 at orgspringframeworkbeansfactorysupportdefaultlistablebeanfactorydoresolvedependencydefaultlistablebeanfactoryjava957 at orgspringframeworkbeansfactorysupportdefaultlistablebeanfactoryresolvedependencydefaultlistablebeanfactoryjava855 at orgspringframeworkbeansfactoryannotationautowiredannotationbeanpostprocessorautowiredfieldelementinjectautowiredannotationbeanpostprocessorjava480caused by javalangnosuchmethoderror javaxpersistencejoincolumnforeignkeyljavaxpersistenceforeignkey at orghibernatecfgannotationbinderbindmanytooneannotationbinderjava2881 at orghibernatecfgannotationbinderprocesselementannotationsannotationbinderjava1795 at orghibernatecfgannotationbinderprocessidpropertiesifnotalreadyannotationbinderjava963 at orghibernatecfgannotationbinderbindclassannotationbinderjava796 at orghibernatecfgconfigurationmetadatasourcequeueprocessannotatedclassesqueueconfigurationjava3788 at orghibernatecfgconfigurationmetadatasourcequeueprocessmetadataconfigurationjava3742 at orghibernatecfgconfigurationsecondpasscompileconfigurationjava1410 at orghibernatecfgconfigurationbuildsessionfactoryconfigurationjava1844 at orghibernatecfgconfigurationbuildsessionfactoryconfigurationjava1928 at orgspringframeworkormhibernate4localsessionfactorybuilderbuildsessionfactorylocalsessionfactorybuilderjava343 at orgspringframeworkormhibernate4localsessionfactorybeanbuildsessionfactorylocalsessionfactorybeanjava431 at orgspringframeworkormhibernate4localsessionfactorybeanafterpropertiessetlocalsessionfactorybeanjava416 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactoryinvokeinitmethodsabstractautowirecapablebeanfactoryjava1612 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactoryinitializebeanabstractautowirecapablebeanfactoryjava1549test librarypersontestpersoncontroller failedprops file config spring properties file for library bean idpropertiesfactory classorgspringframeworkbeansfactoryconfigpropertiesfactorybean property namelocation valuewebinflibrarypropertiesvalue property bean,['java'] +723265,how to support async methods in a transactionscope with microsoftbclasync in net 40 i have a method similar topublic async task saveitemsasyncienumerablemyitem items using var ts new transactionscope foreach var item in items await repositorysaveitemasyncitem await repositorydosomethingelse tscomplete this of course has issues because transactionscope does not play nice with asyncawaitit fails with an invalidoperationexception with the messagea transactionscope must be thisposed on the same thread that it was createdi read about transactionscopeasyncflowoption in this answer which appears to be exactly what i needhowever for this particular project i have a hard requirement to support net 40 and cannot upgrade to 45 or 451 thus the asyncawait behavior in my project is provided by the microsoftbclasync nuget packagei cannot seem to find transactionscopeasyncflowoption in this or any other oob package am i just missing it somewhereif it is not available is there an alternative for achieving the same result that is i would like the transaction scope to properly complete or rollback despite crossing threads with continuationsi added dosomethingelse in the example above to illustrate that there may be multiple calls to make within the transaction scope so simply passing all items to the database in one call is not a viable optionin case it matters the repository uses direct adonet sqlconnection sqlcommand etc to write to a sql serverupdatei thought i had a solution which involved taking systemtransactionsdll from net 451 and including it in my project however i found that this worked only on my dev box because it already had 451 installed it did not work when deploying to a machine with only net 40 it just gave a missingmethodexception i am looking for a solution that will work on a net 40 installation,"['c#', '.net']" +723336,update navigation drawer listview my application implements a navigation drawer to change fragments what i need now is to update the navigation drawer items if the user is logged in for example logged in navigation items look like thishomemy infologoutlogged off navigation items look like thishomeregisterloginthe set up of my project is a base activity which extends navigation fragment and changes to a current fragment based on the selected navigation drawer itemall my other files are fragments which change depending on the navigation drawer item selectedi have this kind of working but navgation drawer only updates when i log in then close the app completely and then re start it,['android'] +723407,how to ignore all properties that are marked as virtual i am using virtual keyword for some of my properties for ef lazy loading i have a case in which all properties in my models that are marked as virtual should be ignored from automapper when mapping source to destinationis there an automatic way i can achieve this or should i ignore each member manually,"['c#', '.net']" +723411,how to convert xelement to xdocument how can i convert xelement into xdocument is there some builtin method for thisthe only way i can think of is without new xdocumentxelementtostring which will result in creating big strings and then parsing them thus reducing the performance,['c#'] +723427,whats this javascript syntax i am new to javascript the following code is from some production codebasethe regdefinition is passed in json form but i am not quite sure about the syntax in the method bodyespecially the and partsfunction getcookievalueregdefinition return documentcookiematchregdefiniationregex regdefiniationindex null,['javascript'] +723497,updating ui contributions on handler switch in e4 application model i have defined a command global to my e4 application namely the add command so as you can see in the command is to used throughout the application 1 and to the repsective handler to be activated on context switch to the resp parts in 2 and 3now what i am missing is the possibility to update all ui contributions like 4 allocated to command 1 with the information such as in 2 add contact and when switching to 3 add account what is the general recommended way to update all ui contributions of a command considering the actual context of the command which handler is active etc in eclipse 3x we had something like the ielementupdater which was taking care of doing the respective updatethanks for your hints parallely thiscussed in eclipse forumi worked on finding a solution and have outlined the current state in my blog,['java'] +723532,error launching eclipse 44 version 160 65 of the jvm is not suitable for this product i have a problem launching eclipse 44 on my mac i am getting the following error version 160 65 of the jvm is not suitable for this product i have the latest version installed when i am running java version i am getting java version 180 05javatm se runtime environment build 180 05b13java hotspottm 64bit server vm build 255b02 mixed modehere is my eclipseini file where i already tried to explicit set the vm parameter to my jdk18 startuppluginsorgeclipseequinoxlauncher 130v201404152008jarlauncherlibrarypluginsorgeclipseequinoxlaunchercocoamacosx 11200v201406031326productorgeclipseepackagestandardproductlauncherdefaultactionopenfileshowsplashorgeclipseplatformlauncherxxmaxpermsize256mlauncherdefaultactionopenfilelauncherappendvmargsvmargsdosgirequiredjavaversion17xstartonfirstthreaddorgeclipseswtinternalcarbonsmallfontsxxmaxpermsize256mxms40mxmx512mxdockiconresourceseclipseicnsxstartonfirstthreaddorgeclipseswtinternalcarbonsmallfontsvm libraryjavajavavirtualmachinesjdk180 05jdkcontentshomebinjava,['java'] +723614,how can i access the dom elements within an iframe i am writing a jquery plugin that needs to be able to run against dom elements within an iframe i am just testing this locally right now ie url is fileexamplehtml and in chrome i keep hitting securityerror failed to read the contentdocument property from htmliframeelement blocked a frame with origin null from accessing a crossorigin frame and in safari i just get an empty documentgiven that both the parent file and the iframes file are coming off my local thisk in development and will be coming off the same server in production i would have thought that i would not be subject to the crossorigin issuesis there a way i can convince the browser that my local files are actually of the same domainasideinterestingly in safari using the console directly i can type iframeget0contentdocumentfindol and it happily finds my list in chrome this same line throws the security error just as if it were being executedasideupdatebased on the suggestions below i have fired up a simple local webserver to test this and am now not getting the crossorigin error yay but neither am i getting any contentmy javascript looks likedocumentreadyfunction var myframe iframe mydocument myframeget0contentdocument myelements mydocumentreadyfunction myelements mydocumentfindul ol consoledebugsuccess iframe myframe document mydocument elements myelements the mydocumentready is there just to ensure that the iframes document is ready in reality it makes no differencei always end up with myelements being empty in safari or jqueryfninit0 in chromebut if i manually type this into the consoleiframeget0contentdocumentfindol uli get my lists as expected this is now the case in both safari and chromeso my question becomes why cannot my script see the dom elements but the same code when entered directly into the browsers console can happily see the dom elements,['javascript'] +723678,is the caret on the first line of the textarea on the last line given a textarea with a not fixed width font i want to know on key up if the caret as given by elementselectionend is in the first line or in the last line of the textto avoid bad answers here are some solutions which do not worksplitting on n a sentence can be broken in two lines because it is too long for the textareas widthmeasuring the text before the caret for example by copying the text into a div with same style and measuring the height of the span some characters after the caret may change the wrapping point usually between wordsheres a fiddle for the tests and to remove some ambiguity yes it is a textarea element and it is not only one line etc notesi do not care for internet explorer 9 or mobile browsersi need a reliable solution working for all positions of the caretthere are a lot of tricky details which make most ideas unusable in practice please build a working fiddle before answering,"['javascript', 'jquery', 'html']" +723813,running gtm diagnose error when i try to clean my android projects in eclipse i always get this erroran internal error occurred during running gtm diagnosecomandroidtoolslintdetectorapixmlcontext method initlcomandroidtoolslintclientapilintdriverlcomandroidtoolslintdetectorapiprojectlcomandroidtoolslintdetectorapiprojectljavaiofilelcomandroidresourcesresourcefoldertypev not foundany help would be much appreciated,['android'] +723901,java exception in thread main javanetunknownhostexception test test unknown error os ubuntu this error is related to my previous question where i had an error with inetaddressgetlocalhost i found a suggestion to add an entry in etchosts myip localhost127001 localhost127011 test5but my error is still not resolvedmy code import javanetpublic class inetaddresstest public static void mainstring args throws unknownhostexception inetaddress address inetaddressgetlocalhost error exception in thread main javanetunknownhostexception sachin sachin unknown error at javanetinetaddressgetlocalhostinetaddressjava1484 at inetaddresstestmaininetaddresstestjava6caused by javanetunknownhostexception sachin unknown error at javanetinet6addressimpllookupallhostaddrnative method at javanetinetaddress2lookupallhostaddrinetaddressjava907 at javanetinetaddressgetaddressesfromnameserviceinetaddressjava1302 at javanetinetaddressgetlocalhostinetaddressjava1479 1 more,['java'] +723913,ambiguous call from static context in java the main method tries to access var but results in ambiguous call why instance variable var in base1 is not accessible visible from static context anyway class base1 int var interface base2 public static final int var 0 class test extends base1 implements base2 public static void mainstring args systemoutprintlnvar var,['java'] +724027,why base classnot implementing serializable should have no argument constructor if its subclass implements serializable i am reading the docs of interface serializablein which i find the following lines to allow subtypes of nonserializable classes to be serialized the subtype may assume responsibility for saving and restoring the state of the supertypes public protected and if accessible package fields the subtype may assume this responsibility only if the class it extends has an accessible noarg constructor to initialize the clas state it is an error to declare a class serializable if this is not the case the error will be detected at runtimebut what is the role of noarg constructor of base class in restoring the state of the object,['java'] +724137,how to use owin middleware to rewrite versioned url for request to static file eg i have a file located on the server at contentstatichomehtml i want to be able to make a request to contentv10statichomehtml for versioning and have it rewrite the url so it accesses the file at the correct url using owin middlewarei am currently using the url rewrite module an iis extension but i want to make this work in the owin pipeline instead,['c#'] +724149,making gulp write files synchronously before moving on to the next task gulpfilejsgulptaskbrowserbundle react function gulptaskreact function gulpsrcoptionsjsx source pipereact pipegulpdestoptionsjsx destas you can see i have the browserbundle task depending on the react task i believe this works as expected because in the output i see thisgulp running reactgulp finished react in 343 msgulp running browserbundlehowever although the react task is finished the files its supposed to write to the operating system are not quite there yet i have notice that if i put a sleep statement in the browser bundle command then it works as expected however this seems a little hacky to me if i want the react task to not be considered finished until the files from gulpdest have been synchronously written to thisk how would i do that,['javascript'] +724166,modifying data written to thisk by ext4 filesystem i am working on the academic project part of which is applying transparent encryption aesctr to the selected ext4 files stored on the thisk i can already mark them as encrypted using new ioctl etcin order to do so i need to find the best spot to call my algorithm on the data while it is read or written fromto the device due to large amount of features like journal inlines odirect extents provided by the filesystem i am struggling for few days now to find the proper solution i need to operate on the raw data as it is stored in the datablocksi had few ideas in mind one was to hook in somewhere on the callpath from sys read and sys write more precisely ext4 file write and generic file aio read but that wouldnt work with mmap and probably is not the way to go another approach would be to do it through ext4 writepages and ext4 readpages and it is callback as it is async when the memory pages are written down to thiskbecause it is not production version just a proof of concept i can switch off some ext4 features in order to simplify the task while using the algorithm i need to be able to access the inodes xargs where the key id is stored and as well be aware of the block number in order to generate the initial vector used in endecryption do you have any ideas andor suggestions regarding that issue,['c'] +724247,how to properly reuse connection to mongodb across nodejs application and modules i have been reading and reading and still am confused on what is the best way to share the same database mongodb connection across whole nodejs app as i understand connection should be open when app starts and reused between modules my current idea of the best way is that serverjs main file where everything starts connects to database and creates object variable that is passed to modules once connected this variable will be used by modules code as necessary and this connection stays open eg var mongoclient requiremongodbmongoclient var mongo this is passed to modules and code mongoclientconnectmongodblocalhost27017marankings functionerr db if err consolelogwe are connected these tables will be passed to modules as part of mongo object mongodbusers dbcollectionusers mongodbthisciplines dbcollectionthisciplines consoleloga usersgetall thisplays object and this can be used from inside modules else consolelogerr var users newrequiremodelsuserapp mongo consolelogb usersgetall not connected at the very first time so thisplays undefinedthen another module modelsuser looks like thatusers functionapp mongo usersprototypeadduser function consolelogadd userusersprototypegetall function return all users mongodbusers moduleexports usersnow i have horrible feeling that this is wrong so are there any obvious problems with this approach and if so how to make it better,['javascript'] +724256,angular uirouter how do i reload a state when a path parameter changes but not reload when a query parameter changes for example i want this change in navigation to reload the statedetail1detail2but i do not want this navigation to reload the statedetail1searchblahdetail1searchhuzzahaccording to the uirouter documentation setting reloadonsearch false should accomplish this but try the plunk below when reloadonsearch false changing the path parameter does not reload the state even though the documentation says it shouldplunkr,['javascript'] +724258,using alembic api from inside application code i am using sqlite as an application file format see here for why you would want to do this for my pysidebased desktop application that is when a user uses my app their data is saved in a single database file on their machine i am using the sqlalchemy orm to communicate with the databasesas i release new versions of the application i may modify the database schema i do not want users to have to throw away their data every time i change the schema so i need to migrate their databases to the newest format also i create temporary databases a lot to save subsets of the data for use with some external processes i want to create these databases with alembic so they are tagged with the proper versioni have a few questionsis there a way to call alembic from inside my python code i think it is weird to have to use popen to a pure python module but the docs just use alembic from the command line mainly i need to change the database location to wherever the users database is located if that is not possible can i specify a new database location from the command line without editing the ini file this would make calling alembic through popen not a big deali see that alembic keeps its version information under a simple table called alembic version with one column called version num and a single row specifying the version can i add an alembic version table to my schema and populate it with the latest version when i create new databases so there is no overhead is that even a good idea should i just use alembic to create all databasesi have alembic working great for the single database i use to develop with in my projects directory i want to use alembic to conveniently migrate and create databases in arbitrary locations preferably through some sort of python api and not the command line this application is also frozen with cx freeze in case that makes a differencethanks,['python'] +724282,await on a completed task same as taskresult i am currently reading concurrency in c cookbook by stephen cleary and i noticed the following technique var completedtask await taskwhenanydownloadtask timeouttask if completedtask timeouttask return null return await downloadtask downloadtask is a call to httpclientgetstringasync and timeouttask is executing taskdelay in the event that it did not timeout then downloadtask is already completed why is necessary to do a second await instead of returning downloadtaskresult given that the task is already completed,['c#'] +724307,swift setter and getter issues i know there are a few questions regarding with this already and i know swift can only customise property setter and getter for computed properties but i think this is the worst part of swift becauseall variables are exposed to outside there is no private or public properties any morethere is no way to access the internal variable of the property like the objectivec variablemy code is like thisvar value float 00 willset setvaluenewvalue animated false func setvaluenewvaluefloat animatedbool ifnewvalue selfvalue todo this will cause problem because i there is no alternative way like objectivec to access value selfvalue do whatever i want the problem is the there is no value like in objectivec the selfvalue will cause the values willset be called againany idea thanks,['ios'] +724330,find tables without data how can we retrieve all tables in database without data as in there are no rows in table in the case of a microsoft sql serveris there any method,['sql'] +724376,how to get the count of deleted entities i use the following method to delete a set of objects based on a certain where condition but in reality the number of removed objects could be lesser than the passed collection how do i get the actual count of deleted entitiesjavautilcollection,['java'] +724421,how to unit test an app extension on xcode 6 does anyone know how to perform unit testing on app extension target especially keyboard extension target what have i tried in the unit test target in the general tap set it is target to the extension target instead of the container appset the bundle loader to the path of the binary of the extension target which looks like built products dircommycompanykeyboardappexcommycompanykeyboardset the test host to bundle loaderin the build phases tap set the target dependencies to both the container app and the extensionafter these things done i can build it successfully but always get test failed with an log test target sogouinputtests encountered an error test session exited1 without checking in if you believe this error represents a bug please attach the log file at tmpteststatusuxfvxwlogi am using xcode 6 beta 3,['ios'] +724466,jquery trigger equivalent in angularjs i am using angularjs in my project and i do not want to include jqueryi want to perform jquery equivalent of this in angularjssomeclasstriggercreatei searched in internet but could not find one,"['javascript', 'jquery']" +724547,rejected app because app crashed when attempted to download one of the inapp purchases i am trying to release my new app version with in app purchases but apple rejected it twice with the following issueyour app crashed when weattempted to download one of the inapp purchasesthis occurred when your app was used offline on wifi they sent me two crash logs which gives the following issuesthe first crash logexception type exc bad access sigbusexception subtype exc arm sp align at 0x013fd4582ehighlighted thread 1thread 0 name thispatch queue comapplelibthispatchmanagerthread 00 libsystem kerneldylib 0x0197071aa8 kevent64 81 libthispatchdylib 0x0196f75998 thispatch mgr thread 48thread 1 name comapplensurlconnectionloaderthread 10 libsystem kerneldylib 0x0197071ca0 mach msg trap 81 corefoundation 0x0189f7eb70 cfrunloopservicemachport 1802 corefoundation 0x0189f7cd00 cfrunlooprun 8323 corefoundation 0x0189ebdc1c cfrunlooprunspecific 4484 foundation 0x018aab2424 nsurlconnectionloader resourceloadloop 3445 foundation 0x018ab40408 nsthread main 9966 libsystem pthreaddylib 0x019710be18 pthread body 1647 libsystem pthreaddylib 0x019710bd70 pthread start 1368 libsystem pthreaddylib 0x0197109550 thread start 0thread 2 name comapplecfsocketprivatethread 20 libsystem kerneldylib 0x019708a76c select 81 libsystem pthreaddylib 0x019710be18 pthread body 1642 libsystem pthreaddylib 0x019710bd70 pthread start 1363 libsystem pthreaddylib 0x0197109550 thread start 0thread 30 libsystem kerneldylib 0x0197071ca0 mach msg trap 81 corefoundation 0x0189f7eb70 cfrunloopservicemachport 1802 corefoundation 0x0189f7cd00 cfrunlooprun 8323 corefoundation 0x0189ebdc1c cfrunlooprunspecific 4484 corefoundation 0x0189f132a4 cfrunlooprun 1085 coremotion 0x018a676538 0x18a6380 2552886 libsystem pthreaddylib 0x019710be18 pthread body 1647 libsystem pthreaddylib 0x019710bd70 pthread start 1368 libsystem pthreaddylib 0x0197109550 thread start 0thread 40 libsystem kerneldylib 0x019708ae74 workq kernreturn 81 libsystem pthreaddylib 0x0197109548 start wqthread 0thread 50 libsystem kerneldylib 0x019708ae74 workq kernreturn 81 libsystem pthreaddylib 0x0197109548 start wqthread 0thread 60 libsystem kerneldylib 0x019708ae74 workq kernreturn 81 libsystem pthreaddylib 0x0197109548 start wqthread 0thread 70 libsystem kerneldylib 0x019708ae74 workq kernreturn 81 libsystem pthreaddylib 0x0197109548 start wqthread 0and the second oneexception type exc bad access sigsegvexception subtype kern invalid address at 0x013fefb0highlighted thread 1thread 0 name thispatch queue comapplelibthispatchmanagerthread 00 libsystem kerneldylib 0x0197071aa8 kevent64 81 libthispatchdylib 0x0196f75998 thispatch mgr thread 48thread 1 name comapplensurlconnectionloaderthread 10 libsystem kerneldylib 0x0197071ca0 mach msg trap 81 corefoundation 0x0189f7eb70 cfrunloopservicemachport 1802 corefoundation 0x0189f7cd00 cfrunlooprun 8323 corefoundation 0x0189ebdc1c cfrunlooprunspecific 4484 foundation 0x018aab2424 nsurlconnectionloader resourceloadloop 3445 foundation 0x018ab40408 nsthread main 9966 libsystem pthreaddylib 0x019710be18 pthread body 1647 libsystem pthreaddylib 0x019710bd70 pthread start 1368 libsystem pthreaddylib 0x0197109550 thread start 0thread 2 name comapplecfsocketprivatethread 20 libsystem kerneldylib 0x019708a76c select 81 libsystem pthreaddylib 0x019710be18 pthread body 1642 libsystem pthreaddylib 0x019710bd70 pthread start 1363 libsystem pthreaddylib 0x0197109550 thread start 0thread 3 name webthreadthread 30 libsystem kerneldylib 0x0197071ca0 mach msg trap 81 corefoundation 0x0189f7eb70 cfrunloopservicemachport 1802 corefoundation 0x0189f7cd00 cfrunlooprun 8323 corefoundation 0x0189ebdc1c cfrunlooprunspecific 4484 webcore 0x0193aabfd8 runwebthreadvoid 4685 libsystem pthreaddylib 0x019710be18 pthread body 1646 libsystem pthreaddylib 0x019710bd70 pthread start 1367 libsystem pthreaddylib 0x0197109550 thread start 0thread 4 name javascriptcoreblockfreethread 40 libsystem kerneldylib 0x019708a394 psynch cvwait 81 javascriptcore 0x018b1a6858 jscblockallocatorblockfreeingthreadmain 2482 javascriptcore 0x018b1a2330 wtfwtfthreadentrypointvoid 203 libsystem pthreaddylib 0x019710be18 pthread body 1644 libsystem pthreaddylib 0x019710bd70 pthread start 1365 libsystem pthreaddylib 0x0197109550 thread start 0thread 5 name javascriptcoremarkingthread 50 libsystem kerneldylib 0x019708a394 psynch cvwait 81 javascriptcore 0x018b3ce514 jscgcthreadwaitfornextphase 1042 javascriptcore 0x018b3ce5a8 jscgcthreadgcthreadmain 883 javascriptcore 0x018b1a2330 wtfwtfthreadentrypointvoid 204 libsystem pthreaddylib 0x019710be18 pthread body 1645 libsystem pthreaddylib 0x019710bd70 pthread start 1366 libsystem pthreaddylib 0x0197109550 thread start 0thread 60 libsystem kerneldylib 0x019708ae74 workq kernreturn 81 libsystem pthreaddylib 0x0197109548 start wqthread 0thread 70 libsystem kerneldylib 0x0197071ca0 mach msg trap 81 corefoundation 0x0189f7eb70 cfrunloopservicemachport 1802 corefoundation 0x0189f7cd00 cfrunlooprun 8323 corefoundation 0x0189ebdc1c cfrunlooprunspecific 4484 libavfaudiodylib 0x0188d5d5ec genericrunloopthreadentryvoid 1565 libavfaudiodylib 0x0188d5201c capthreadentrycapthread 1006 libsystem pthreaddylib 0x019710be18 pthread body 1647 libsystem pthreaddylib 0x019710bd70 pthread start 1368 libsystem pthreaddylib 0x0197109550 thread start 0thread 80 libsystem kerneldylib 0x0197071ca0 mach msg trap 81 corefoundation 0x0189f7eb70 cfrunloopservicemachport 1802 corefoundation 0x0189f7cd00 cfrunlooprun 8323 corefoundation 0x0189ebdc1c cfrunlooprunspecific 4484 corefoundation 0x0189f132a4 cfrunlooprun 1085 coremotion 0x018a676538 0x18a6380 2552886 libsystem pthreaddylib 0x019710be18 pthread body 1647 libsystem pthreaddylib 0x019710bd70 pthread start 1368 libsystem pthreaddylib 0x0197109550 thread start 0thread 90 libsystem kerneldylib 0x019708ae74 workq kernreturn 81 libsystem pthreaddylib 0x0197109548 start wqthread 0my app works fine in three devices i have tested it iphone 4 iphone5 and ipad it does not crash and i can purchase in apps without any problem my app responds to network reachability so i have tested it when device is in offline mode wifi only and when reachability changes while user is purchasing the inapps i have read and tried to analyze these crash logs i have also checked for memory leaks with allocations and leaks and for low memory warnings with zombies in xcode instruments but i cannot seem to find anything wrong with my code can you please give me a little help about what should i do and where should i look more carefully,"['ios', 'objective-c']" +724577,how to prohibit the use of global variables on compile time is there a way to prohibit the use of global variablesi want gcc to generate an error on compile time when a global variable is definedwe have a code that should be run per thread and want to allow only use of stack which is thread safeis there way to enforce it some gcc flag or other way to verify it,['c'] +724591,how do i authenticate with spnegokerberos and apache is httpclient how do i correctly setup a connection with httpclient that uses the logged in users activedirectory credentials to authenticate against a website and requires kerberosspnego authentication,['java'] +724678,postgres jdbc driver psqlexception syntax error at or near returning for some reason the jdbc postgressql driver is adding returning to the end of select statementsdoes anyone have any idea whycodeprotected static final string auth query select secret from user where name namestring password sql2oopencreatequeryauth queryaddparametername usernameexecutescalarstringclassexceptionorgpostgresqlutilpsqlexception error syntax error at or near returning position 47 at orgpostgresqlcorev3queryexecutorimplreceiveerrorresponsequeryexecutorimpljava2161 at orgpostgresqlcorev3queryexecutorimplprocessresultsqueryexecutorimpljava1890 at orgpostgresqlcorev3queryexecutorimplexecutequeryexecutorimpljava255 at orgpostgresqljdbc2abstractjdbc2statementexecuteabstractjdbc2statementjava559 at orgpostgresqljdbc2abstractjdbc2statementexecutewithflagsabstractjdbc2statementjava417 at orgpostgresqljdbc2abstractjdbc2statementexecutequeryabstractjdbc2statementjava302 at commchangev2c3p0implnewproxypreparedstatementexecutequerynewproxypreparedstatementjava76 at orgsql2oqueryexecutescalarqueryjava533 at orgsql2oqueryexecutescalarqueryjava577 at orgsql2oqueryexecutescalarqueryjava568data source jndiconfigure idwac classorgeclipsejettywebappwebappcontext new idmydb classorgeclipsejettyplusjndiresource argarg argjdbcmydbarg arg new classcommchangev2c3p0combopooleddatasource set namedriverclassorgpostgresqldriverset set namejdbcurljdbcpostgresqllocalhost5432mydbset set nameuseruserset set namepasswordpaset new arg newconfigurepostgresql jdbc driver versiondependency groupidorgpostgresqlgroupid artifactidpostgresqlartifactid version931101jdbc41versiondependencypacket captureno time source destination protocol length info 12 01756360 127001 127001 pgsql 182 pbdesframe 12 182 bytes on wire 1456 bits 182 bytes captured 1456 bits on interface 0postgresql type parse length 69 statement query select secret from user where name 1 returning parameters 1 type oid 1043,['java'] +724788,animation with cgaffinetransformscale freezes application i am trying to implement a thisappearing url bar when the users scrolls in the webviewthe function below gets called in voidscrollviewdidscrolluiscrollview scrollviewfor specific webpages the app freezes completely and uses 100 cpu from trial and error we concluded that removing the cgaffinetransformscale fixes this i am trying to understand why this happens and how else i could implement the same functionality voidcollapsequerybox urlbarstate clqurlbarstatecollapsing queryboxviewheightconstraintconstant collapsed querybox height uiview animatewithdurationcollapse animation duration animations webviewscrollviewcontentinset uiedgeinsetsmake0 0 0 0 querylabeltransform cgaffinetransformscale querylabeltransform collapse animation scale factor collapse animation scale factor querylabellayerbackgroundcolor uicolor clearcolorcgcolor browsercontainerview layoutifneeded completionbool finished urlbarstate clqurlbarstatecollapsed the full stack trace of the paused app in the frozen state thread 1 tid 0xcbf9f 0x025b40be libobjcadylibobjc msgsend 26 queue comapplemainthread stop reason signal sigstop frame 0 0x025b40be libobjcadylibobjc msgsend 26 frame 1 0x008cf411 foundationnsisengine variabletoworkonamongvariableswithintegralizationviolationsignoringlostcausesvarsalreadyadjusted 491 frame 2 0x00a41ea3 foundation 44nsisengine fixupintegralizationviolations block invoke 1285 frame 3 0x00a4368c foundationnsisengine withbehaviorsperformmodifications 107 frame 4 0x008cf21a foundationnsisengine withoutoptimizingatendrunblockwithautomaticoptimizationthisabled 48 frame 5 0x008cf1d9 foundationnsisengine fixupintegralizationviolations 96 frame 6 0x008ceef8 foundationnsisengine optimize 204 frame 7 0x008d57e3 foundationnsisengine constraintdidchangesuchthatmarkershouldbereplacedbymarkerplusdelta 336 frame 8 0x00a43e23 foundationnsisengine trytochangeconstraintsuchthatmarkerisreplacedbymarkerplusdeltaundohandler 489 frame 9 0x00a4b2d5 foundationnslayoutconstraint trytochangecontainergeometrywithundohandler 578 frame 10 0x008c8d4f foundationnslayoutconstraint setsymbolicconstantconstant 384 frame 11 0x008cb6a1 foundationnslayoutconstraint setconstant 52 frame 12 0x00e398a5 uikituiscrollview setcontentsize 566 frame 13 0x01030a5a uikituitableviewcell updatewrappercontentinset 117 frame 14 0x0103963a uikituitableviewcell setframe 701 frame 15 0x00e1b7b0 uikituiviewgeometry applyautoresizingmaskwitholdsuperviewsize 840 frame 16 0x00e1c552 uikituiviewgeometry resizewitholdsuperviewsize 290 frame 17 0x00e1c5aa uikituiviewgeometry resizewitholdsuperviewsize 80 frame 18 0x00e1b185 uikit 46uiviewgeometry resizesubviewswitholdsize block invoke 87 frame 19 0x028a1d86 corefoundation 53 nsarraym enumerateobjectswithoptionsusingblock block invoke 102 frame 20 0x028a1c5f corefoundation nsarraym enumerateobjectswithoptionsusingblock 239 frame 21 0x00e1b115 uikituiviewgeometry resizesubviewswitholdsize 149 frame 22 0x00e19c4e uikituiviewgeometry setframe 559 frame 23 0x00e1b7b0 uikituiviewgeometry applyautoresizingmaskwitholdsuperviewsize 840 frame 24 0x00e1c552 uikituiviewgeometry resizewitholdsuperviewsize 290 frame 25 0x00e1c5aa uikituiviewgeometry resizewitholdsuperviewsize 80 frame 26 0x00e1b185 uikit 46uiviewgeometry resizesubviewswitholdsize block invoke 87 frame 27 0x028a1d86 corefoundation 53 nsarraym enumerateobjectswithoptionsusingblock block invoke 102 frame 28 0x028a1c5f corefoundation nsarraym enumerateobjectswithoptionsusingblock 239 frame 29 0x00e1b115 uikituiviewgeometry resizesubviewswitholdsize 149 frame 30 0x00eadc1a uikituitableview resizesubviewswitholdsize 98 frame 31 0x00e1c819 uikituiviewgeometry setbounds 510 frame 32 0x00e39627 uikituiscrollview setbounds 1036 frame 33 0x00eadf5f uikituitableview setbounds 260 frame 34 0x00e1befd uikituiviewgeometry applyisenginelayoutvalues 324 frame 35 0x00e1c4c0 uikituiviewgeometry resizewitholdsuperviewsize 144 frame 36 0x00e457bb uikituiscrollview resizewitholdsuperviewsize 73 frame 37 0x00e1c5aa uikituiviewgeometry resizewitholdsuperviewsize 80 frame 38 0x00e1b185 uikit 46uiviewgeometry resizesubviewswitholdsize block invoke 87 frame 39 0x028a1d86 corefoundation 53 nsarraym enumerateobjectswithoptionsusingblock block invoke 102 frame 40 0x028a1c5f corefoundation nsarraym enumerateobjectswithoptionsusingblock 239 frame 41 0x00e1b115 uikituiviewgeometry resizesubviewswitholdsize 149 frame 42 0x0145961c uikituiviewadditionallayoutsupport is layout 158 frame 43 0x00e20336 uikituiviewhierarchy layoutsubviews 80 frame 44 0x00e2d964 uikituiviewcalayerdelegate layoutsublayersoflayer 355 frame 45 0x025b682b libobjcadylibnsobject performselectorwithobject 70 frame 46 0x01df345a quartzcorecalayer layoutsublayers 148 frame 47 0x01de7244 quartzcorecalayerlayout if neededcatransaction 380 frame 48 0x01de70b0 quartzcorecalayerlayout and thisplay if neededcatransaction 26 frame 49 0x01d4d7fa quartzcorecacontextcommit transactioncatransaction 294 frame 50 0x01d4eb85 quartzcorecatransactioncommit 393 frame 51 0x01d4f258 quartzcorecatransactionobserver callback cfrunloopobserver unsigned long void 92 frame 52 0x027ed36e corefoundation cfrunloop is calling out to an observer callback function 30 frame 53 0x027ed2bf corefoundation cfrunloopdoobservers 399 frame 54 0x027cb254 corefoundation cfrunlooprun 1076 frame 55 0x027ca9d3 corefoundationcfrunlooprunspecific 467 frame 56 0x027ca7eb corefoundationcfrunloopruninmode 123 frame 57 0x041895ee graphicsservicesgseventrunmodal 192 frame 58 0x0418942b graphicsservicesgseventrun 104 frame 59 0x00dbef9b uikituiapplicationmain 1225,['ios'] +724835,how do i get the key at a specific index from a dictionary in swift i have a dictionary in swift and i would like to get a key at a specific index var mydict dictionarystringmyclass dictionarystringmyclassi know that i can iterate over the keys and log them for key in mydictkeys nslogkey keyhowever strangely enough something like this is not possiblevar key string mydictkeys0why,['ios'] +724844,how to set the action for a uibarbuttonitem in swift how can the action for a custom uibarbuttonitem in swift be setthe following code successfully places the button in the navigation barvar b uibarbuttonitemtitle continue style plain target self actionnilselfnavigationitemrightbarbuttonitem bnow i would like to call func sayhello printlnhello when the button is touched my efforts so farvar b uibarbuttonitemtitle continue style plain target self actionsayhello also with sayhello sayhello and sayhelloandvar b uibarbuttonitemtitle continue style plain target self actionselectorsayhello also with sayhello sayhello and sayhelloandvar b uibarbuttonitemtitle continue style plain target self actionselectorselfsayhello also with selfsayhello selfsayhello and selfsayhellonote that sayhello appears in the intellisense but does not workthanks for your helpedit for posterity the following worksvar b uibarbuttonitemtitle continue style plain target self actionsayhello,['ios'] +724887,qmetaobjectinvokemethod no such method when using inheritance i have got a super class common which inherits from qobject then i have got a class item which inherits from commoncommonhclass common public qobject q objectpublic some methodsitemhclass item public common q objectpublic some methods void testqstring valueitemcppvoid itemtestqstring value qdebug valuei want to use qmetaobjectinvokemethod to dynamically call a functionso i implemented a test function in the item class which takes exactly one stringitem item new itemqmetaobjectinvokemethoditem test qtdirectconnection q argqstring 1234this does not work i get the following error qmetaobjectinvokemethod no such method commontestqstring which is perfectly okay and fine because the common class has no test functionhow can i tell qmetaobjectinvokemethod that it should call the method from the item class,['c++'] +724931,replication googles search ios cards animation i am trying to replicate this at the momentif youre familiar with googles app it looks like a uicollectionview with a custom flow layouti am expanding on a question that has been closed with some additional codeheres the link to the other questionin the custom flow layout class i can create a stacked effect by setting a negative minimum line spacing value and using the following nsarray layoutattributesforelementsinrectcgrectrect nsarray allattributesinrect super layoutattributesforelementsinrectrect cgpoint centerpoint cgpointmakecgrectgetmidxselfcollectionviewbounds cgrectgetmidyselfcollectionviewbounds for uicollectionviewlayoutattributes cellattributes in allattributesinrect if cgrectcontainspointcellattributesframe centerpoint cellattributestransform cgaffinetransformidentity cellattributeszindex 10 else cellattributestransform cgaffinetransformmakescale075 075 return allattributesinrectthe swiping to delete animations are working alright but i am having trouble creating the stacked look and then dragging just 1 cell up into the view while keeping the remaining cards stacked like what you see above,"['ios', 'objective-c']" +724947,java hashset equiv in c i as curious if there was something akin the the java hashset in c ie a data structure with fast look as i will only be running containse on it likewise if you could enlighten me on how to do a contains on whatever data structure you propose i would be very appreciative o please do not post just look at the c docs as i have already done so and find them burdensome,['c++'] +724979,how to access build settings in xcode 6 there seems to be a lot of variations of how to access the build settings variables ie to define the base url of a web service for different debug vs release environments i created a userdefined variable in project building settings one for each environment let us call it web service base urlhow do i access it in the code i am using xcode 6 and swifti have tried this but it does not worklet api key web service base urli have also tried this and it also does not worklet api key nsuserdefaultsstandarduserdefaultsstringforkeyweb service base urlany suggestions this seems to be a often needed solution it is so easy in rails but not so in ios development,['ios'] +725019,nohupignoring input and appending output to nohupout i want to start my server through nohupphp but the command is not running and thisplays following error nohupignoring input and appending output to nohupouti am using ssh through putty this is what i am doingnohup php server1php,['php'] +725112,build release apk with customize name format in android studio i want the apk to be built with the following name format with timestamp how can i set itformat app nameymmddhisapknow it is fixed with the name app namereleaseapk,['android'] +725136,refresh current fragment listview data remaining in the same activity calling a fragment from an activity i am thisplaying a listview with two buttons when i click on a menu item ie show online i am updating the data and so the listview now i need to reflect the updated data how can i refresh the fragment after i click show online till now i have used the following code intent intent getintentintentaddflagsintentflag activity no animationfinishstartactivityintentbut this will restart the whole activity i just need to refresh the current fragment edited code addedactivity class public class contactlistactivity extends actionbaractivity listview listview override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate final actionbar actionbar getactionbar menubuttonutilenablemenubuttonthis fragmentmanager fragmentmanager getfragmentmanager fragmenttransaction fragmenttransaction fragmentmanagerbegintransaction mycontactsfragment contactlistfragment new mycontactsfragment fragmenttransactionreplaceandroidridcontent contactlistfragment fragmenttransactioncommit override public boolean oncreateoptionsmenumenu menu inflate the menu this adds items to the action bar if it is present getmenuinflaterinflatermenumain menu return true override public boolean onoptionsitemselectedmenuitem item int id itemgetitemid if id ridshow online contentvalues values new contentvalues string where contactscontentproviderphone id notnull and contactscontentproviderphone id 17486 or contactscontentproviderphone id 17494 valuesputcontactscontentproviderstatus true thisgetcontentresolverupdatecontactscontentprovidercontent uri values where null listview listview thisfindviewbyidandroidridlist baseadapter listviewgetadapternotifydatasetchanged return true return superonoptionsitemselecteditem fragmentpublic class mycontactsfragment extends listfragmentbutton allcontactsbtnbutton neeocontactsbtnlistview listviewcustomadapterforallcontacts adapterforallcontactscustomadapterforneeocontacts adapterforneeocontactsoverridepublic void oncreatebundle savedinstancestate todo autogenerated method stub superoncreatesavedinstancestate final actionbar actionbar getactivitygetactionbar menubuttonutilenablemenubuttongetactivity adapterforneeocontacts new customadapterforneeocontacts adapterforallcontacts new customadapterforallcontactsoverridepublic view oncreateviewlayoutinflater inflater viewgroup containerbundle savedinstancestate view view inflaterinflaterlayoutcontactsfragment containerfalse allcontactsbtn button viewfindviewbyidridallcontactsbutton neeocontactsbtn button viewfindviewbyidridneeocontactsbutton listview listview viewfindviewbyidandroidridlist neeo contacts neeocontactsbtnsetonclicklistenernew onclicklistener override public void onclickview v listviewsetadapteradapterforneeocontacts all contacts allcontactsbtnsetonclicklistenernew onclicklistener override public void onclickview v listviewsetadapteradapterforallcontacts return viewadapterprivate class customadapterforallcontacts extends baseadapter public customadapterforallcontacts listcontact contactslist getallcontacts override public int getcount todo autogenerated method stub return contactslistsize override public contact getitemint arg0 todo autogenerated method stub return contactslistgetarg0 override public long getitemidint arg0 todo autogenerated method stub return arg0 override public view getviewint position view view viewgroup viewgroup ifviewnull layoutinflater inflater layoutinflater getactivitygetsystemservicecontextlayout inflater service view inflaterinflaterlayoutlist item viewgroupfalse textview contname textviewviewfindviewbyidridnametext textview contnumber textviewviewfindviewbyidridnumbertext imageview image imageviewviewfindviewbyidridcontact image contact contact contactslistgetposition string status contactgetstatus ifcontactgetstatusequals1 imagesetbackgroundresourcecomexamplemycontentproviderrdrawableperson empty online else imagesetbackgroundresourcecomexamplemycontentproviderrdrawableperson empty offline contnamesettextcontactgetname contnumbersettextcontactgetphonenumber return view public contact getcontactpositionint position return contactslistgetposition public listcontact getallcontacts listcontact contactlist new arraylistcontact string url contentcomexampleprovidercontactscontacts uri baseuri1 uriparseurl string select contactscontentproviderphone id contactscontentproviderstatus string where contactscontentproviderneeo user notnull and contactscontentproviderneeo user 1 and contactscontentproviderstatus 1 cursor cursor getactivitygetcontentresolverquerybaseuri1 select where null pid forcursormovetofirst cursormovetonext cursorisafterlast logwfiltered ids cursorgetstringcursorgetcolumnindexcontactscontentproviderphone id cursorgetstringcursorgetcolumnindexcontactscontentproviderstatus uri baseuri contactscontractcommondatakindsphonecontent uri string projection new string contactscontractcommondatakindsphone id contactscontractcommondatakindsphonethisplay name contactscontractcommondatakindsphonenumber string selection contactscontractcommondatakindsphonethisplay name notnull and contactscontractcommondatakindsphonethisplay name string selectionargs null string sortorder contactscontractcommondatakindsphone id collate localized asc cursor mcursor getactivitygetcontentresolverquerybaseuri projection selection selectionargs sortorder joinging both cursors cursorjoiner joiner new cursorjoinercursor new string contactscontentproviderphone id mcursor new string contactscontractcommondatakindsphone id for cursorjoinerresult joinerresult joiner contact cont new contact logeresult joinerresulttostring switch joinerresult case left handle case where a row in cursora is unique break case right handle case where a row in cursorb is unique contsetidmcursorgetstringmcursorgetcolumnindexcontactscontractcommondatakindsphone id contsetnamemcursorgetstringmcursorgetcolumnindexcontactscontractcommondatakindsphonethisplay name contsetphonenumbermcursorgetstringmcursorgetcolumnindexcontactscontractcommondatakindsphonenumber contsetstatus0 contactlistaddcont break case both handle case where a row with the same key is in both cursors contsetidmcursorgetstringmcursorgetcolumnindexcontactscontractcommondatakindsphone id contsetnamemcursorgetstringmcursorgetcolumnindexcontactscontractcommondatakindsphonethisplay name contsetphonenumbermcursorgetstringmcursorgetcolumnindexcontactscontractcommondatakindsphonenumber contsetstatuscursorgetstringcursorgetcolumnindexcontactscontentproviderstatus contactlistaddcont break mcursorclose cursorclose return contactlist,['android'] +725158,proper way of using begintransaction with dapperidbconnection which is the proper way of using begintransaction with idbconnection in dapper today i have created one method in which i have to use begintransaction here is the codeusing idbconnection cn dbconnection var otransaction cnbegintransaction try save basic consult detail var opara new dynamicparameters oparaaddpatientid ipatientid dbtype dbtypeint32 blahblah catch exception ex otransactionrollback return new saveresponse success false responsestring exmessage when i executed above method i got an exception invalid operation the connection is closedthis is because you cannot begin a transaction before the connection is opened so when i add this line cnopen the error gets resolved but i have read somewhere that manually open connection is a bad practice the dapper opens a connection only when it needs toin entity framework you can handle a transaction using a transactionscopeso my question is what is a good practice to handle transaction without adding the line cnopen in dapper i guess there should be some proper way for this,"['c#', '.net']" +725356,compiling simple wearable app in android studio watchactivity not found i followed the instructions at this link to create a simple mobilewearable app in android studio however it would not recognize any of the classes specific to the wearable sdk giving the error cannot resolve symbol the screenshot at this link is what i am seeingthe following is my buildgradle fileapply plugin comandroidapplicationandroid compilesdkversion 20 buildtoolsversion 20 defaultconfig applicationid comexamplelsykoraandroidwearwidget minsdkversion l targetsdkversion l versioncode 1 versionname 10buildtypes release runproguard false proguardfiles getdefaultproguardfileproguardandroidtxt proguard rulespro productflavors dependencies compile filetreeinclude jar dir libs you must install or update the support repository through the sdk manager to use this dependency you must install or update the support repository through the sdk manager to use this dependencycompile comandroidsupportsupportv13compile comgoogleandroidsupportwearablecompile comgoogleandroidgmsplayserviceswearablei have installed all sdks using sdk manager and i have tried tinkering with the minimum target and compile sdks in the buildgradle file setting them to 19 20 or androidl but i am having the same results program would not compile because of these unrecognized classes any input is appreciated thanks,['android'] +725453,how to get owincontext from globalasax i am trying to set up my dependency injection and i am in the need of injecting a iauthenticationmanager from aspnet identity to an owincontextfor this i am from my globalasax serviceconfigconfigure running containerregister httpcontextcurrentgetowincontextauthenticationbut when i am running my application i get this messageno owinenvironment item was found in the contextwhy is this httpcontextcurrentgetowincontext not available from globalasaxstartupcsassembly owinstartupattributetypeofmyappwebstartupnamespace speedopweb public partial class startup public void configurationiappbuilder app configureauthapp startupauthcspublic partial class startup public void configureauthiappbuilder app appusecookieauthenticationnew cookieauthenticationoptions authenticationtype defaultauthenticationtypesapplicationcookie loginpath new pathstringaccountlogin provider new cookieauthenticationprovider onvalidateidentity securitystampvalidatoronvalidateidentityusermanageruser int user int validateinterval timespanfromminutes30 regenerateidentitycallback manager user managercreateidentityasyncuser defaultauthenticationtypesapplicationcookie getuseridcallback id int32parseidgetuserid appuseexternalsignincookiedefaultauthenticationtypesexternalcookie,['c#'] +725534,swift cannot test core data in xcode tests i am working on a ios project that uses core data i am using swiftthe core data stack is setup right and all seems to be fine i have created a class for an entity nsmanagedobject called testentitythe class looks like thisimport uikitimport coredataclass testentity nsmanagedobject nsmanaged var name nsstring nsmanaged var age nsnumberso then i try to insert a new testentity in code using this line of codelet te testentity nsentitydescriptioninsertnewobjectforentityfornametestentity inmanagedobjectcontext ctx as testentityi then get this errori have seen some answers on stack overflow that say that i need to worry about the module name so then i looked that up on the docsthen i went in the core data entity for testentity and in the class field i entered myappnametestentitywhen i run the app this linelet te testentity nsentitydescriptioninsertnewobjectforentityfornametestentity inmanagedobjectcontext ctx as testentitystill gives me the same errorwhat else could i be doing wrongeditso i was able to make the app not crash anymore by changing the testentity nsmanagedobject class toimport uikitimport coredataobjctestentity class testentity nsmanagedobject nsmanaged var name nsstring nsmanaged var age nsnumberso i added the objctestentity in it this works with or without adding the appname before the testentity class name in the core data data model inspectorthis works but when i run tests this line still crasheslet te testentity nsentitydescriptioninsertnewobjectforentityfornametestentity inmanagedobjectcontext ctx as testentityso i found that this is an issue for other peoplehow to access core data generated objc classes in test targetshow can we get core data to work in tests in swift i am not using a bridging header in the app target and it all works great the test target still crashes thoughhow can i fix the test target so it can run core data tests,['ios'] +725735,how to copy text to clipboardpasteboard with swift i am a swift newbie looking for a clean example of how to copy text to ios clipboard that can then be usedpasted in other appsthe benefit of this function is that the text can be copied quickly without the standard text highlighting functions of the traditional text copyingi am assuming that the key classes are in uipasteboard but cannot find the relevant areas in the code example they supply classindexhtmlany help would be very much appreciatedthanksg,['ios'] +725765,avoiding chunkedencodingerror for an empty chunk with requests 230 i am using requests to download a file several gigabytes from a server to provide progress updates and to prevent the entire file from having to be stored in memory i have set streamtrue and wrote the download to a filewith openoutput w as f response requestsgeturl streamtrue if not responseok print there was an error exit for block in responseiter content1024 100 fwriteblock completed bytes lenblock write progresscompleted bytes total byteshowever at some random point in the download requests throws a chunkedencodingerror i have gone into the source and found that this corresponds to an incompleteread exception i inserted a log statement around those lines and found that epartial r i know that the server gives the downloads low priority and i suspect that this exception occurs when the server waits too long to send the next chunkas is expected the exception stops the download unfortunately the server does not implement http11s content ranges so i cannot simply resume it i have played around with increasing urllib3s internal timeout but the exception still persistsis there anyway to make the underlying urllib3 or requests more tolerant of these empty or late chunks so that the file can completely download,['python'] +725789,how to load an image in prepareforinterfacebuilder with a ibdesignable uiimageview i would like to load a sample image in an ib designable uiimageview to be shown in interface builder while editing the interface the following code does not work as the view placeholder in ib remains empty the view area contains only the uiimageview textibdesignableclass testimageview uiimageview override func prepareforinterfacebuilder let bundle nsbundlemainbundle let bundle nsbundleforclass nil let imagepath bundlepathforresourcetest oftype jpg selfimage uiimagecontentsoffile imagepath note thatin ib the custom class class for the view is correct testimageviewtestjpg is present in the project if i manually set the image property of the uiimageview in ib the image shows upi tried the two different methods of getting the bundle present in the codethis was tested with xcode 6 beta 3update in both cases the bundle path i get is applicationstemporaryxcode6beta3appcontentsdeveloperplatformsiphonesimulatorplatformdeveloperlibraryxcodeoverlays in that path the image is obviously not present,['ios'] +725864,thisable dynamic proxy in entity framework globally please how can i thisable dynamic proxies for all entities created in entity framework 5currently i am setting this espentitiesconfigurationproxycreationenabled false in every instance of a dbcontext is there a way i can do this for current and future models as a one time tasktahnks,['c#'] +725872,transform object to array with lodash how i can transform big object to array with lodashexamplevar obj 22 namejohn id22 friends53155 worksbooks films 12 nameivan id12 friends24412 worksbooks films transform to var arr namejohn id22nameivan id12thanks,['javascript'] +725911,symfony 2 how to parse parameter in my own yaml file loader i have a yaml loader that loads additional config items for a profile where one application can use different profiles eg for different local editions of the same sitemy loader is very simple yamlprofileloaderphpuse symfonycomponentconfigloaderfileloaderuse symfonycomponentyamlyamlclass yamlprofileloader extends fileloader public function loadresource type null configvalues yamlparseresource return configvalues public function supportsresource type null return is stringresource yml pathinfo resource pathinfo extension the loader is used more or less like this simplified a bit because there is caching tooloaderresolver new loaderresolverarraynew yamlprofileloaderlocatordelegatingloader new delegatingloaderloaderresolverforeach yamlprofilefiles as yamlprofilefile profilename basenameyamlprofilefile yml profilesprofilename delegatingloaderloadyamlprofilefileso is the yaml file it is parsing profilesgermanyymllocale de dehostname profilesgermanyhost nameat the moment the resulting array contains literally profilesgermanyhost name for the hostname array keyso how can i parse the parameters to get the actual parameter valuesi have been trawling through the symfony 2 code and docs and this so question and cannot find where this is done within the framework itself i could probably write my own parameter parser get the parameters from the kernel search for the foo strings and lookupreplace but if there is a component ready to be used i prefer to use thisto give a bit more background why i cannot just include it into the main configyml i want to be able to load appconfigprofilesyml where is the profile name and i am using my own loader to accomplish this if there is a way to wildcard import config files then that might also work for menote currently using 24 but just about ready to upgrade to 25 if that helps,['php'] +726033,align images side by side in html i want 3 images side by side with caption at the moment i have 3 images going from top to bottom with the caption on the left not on the centre how do i make the images appear side by side with caption in the middle thanks div classimage123 img srcimagestvgif height200 width200 stylefloatleft pthis is image 1p img classmiddleimg srcimagestvgif height200 width200 pthis is image 2p img srcimagestvgif height200 width200 pthis is image 3pdiv,"['html', 'css']" +726080,param is missing or the value is empty i am new to rails getting the error below i understand what the issue is but not sure how to fix it error param is missing or the value is empty customer def customer params paramsrequirecustomerpermit first name last name email password password confirmation end enddetailscontrollerrb class myaccountdetailscontroller mycontroller def show customer current user end def update customer current user customerupdate attributescustomer params if customererrorsany render action show else redirect to my account details path notice account details updated end end private def customer params paramsrequirecustomerpermit first name last name email password password confirmation end endview accountcontainerrow render partial myaccountsidebar section h2 your account details simple form for customer url my account details path method put html class formhorizontal do form field forminput first name field forminput last name field forminput email as email hr h4 leave password fields blank to keep the existing password hr field forminput password input html value field forminput password confirmation input html value fieldactions buttonbtnbtnprimarytype submit save,"['ruby-on-rails', 'ruby']" +726191,how can i send radio button value in php using javescript i have been at this for week and read all the stackoverflow and google and i can not fix this problemevery time i test it i get the first radio button no matter which one i clickwhat i get in the email isname testemail phone 9545027557type residentialhtmlform namecontrols idcontrols novalidate div classcontrolgroup div classcontrols input typetext classformcontrol placeholderfull name idname required datavalidationrequiredmessageplease enter your name p classhelpblockp div div div classcontrolgroup div classcontrols input typeemail classformcontrol placeholderemail idemail required datavalidationrequiredmessageplease enter your email div div div classcontrolgroup div classcontrols div classbtngroup datatogglebuttons idoptionu stylepaddingleft25px label classbtn btnprimary active input typeradio classformcontrol idoptionu nameoptionu valueresidential checked residential label label classbtn btnprimary input typeradio classformcontrol idoptionu nameoptionu valuecommercial commercial label label classbtn btnprimary input typeradio classformcontrol idoptionu nameoptionu valuehandyman handyman label div div div pp div idsuccess div for successfail messages button typesubmit classbtn btndanger pullrightrequestbuttonbr formcontact mejsvar name inputnameval var email inputemailval var phone inputphoneval var optionu inputoptionuvalvar firstname name for successfailure message check for white space in name for successfail messageif firstnameindexof 0 firstname namesplit slice0 1join ajax url bincontact mephp type post data name name email email optionu optionu phone phone cache false success function success message successhtmldiv classalert alertsuccess success alertsuccesshtmlbutton typebutton classclose datathismissalert ariahiddentruetimes append button success alertsuccess appendstrongyour message has been sent strong success alertsuccess appenddivcontact mephpname postnameoptionu value postoptionuphone postphoneemail address postemail create email body and send itto put your emailemail subject contact form submitted by nameemail body you have received a new message nn here are the detailsn nname name and email email addressn phone phonen type optionu,"['javascript', 'php', 'jquery', 'html']" +726210,sort nsarray of nsdictionary objects in swift i have retrieved some json data from an api and now have an nsarray full of nsdictionary objects each nsdictionary has a keyvalue pair of name and i want to sort the nsarray by that keyvalue pairi have done quite a bit of searching but none of the solutions i have come across seem to work in the new swift language and i am not sure if it is possibly a bug or noti have triedvar descriptor nssortdescriptor nssortdescriptorkey name ascending truevar sortedresults nsarray resultssortedarrayusingdescriptorsnssortdescriptorkey name ascending truebut that would not compile stating nssortdescriptor is not convertible to anyobjectany advice,['ios'] +726234,messagedialog breaks on windows phone 81 with 3 commands i am trying to add a messagedialog to a windows phone 81 app winrt with 3 commands looking at the documentation for messagedialog it says that the dialog has a command bar that can support up to three commands so i should think that wouldnt be a problem i took their example found on the documentation and made a simple test app out of it and it worked perfectly fine on both desktop and on windows phone then i took the same example and added a single command to itvar messagedialog new messagedialogno internet connection has been found add commands and set their callbacks both buttons use the same callback function instead of inline event handlersmessagedialogcommandsaddnew uicommand try again new uicommandinvokedhandlerthiscommandinvokedhandlermessagedialogcommandsaddnew uicommand something else new uicommandinvokedhandlerthiscommandinvokedhandlermessagedialogcommandsaddnew uicommand close new uicommandinvokedhandlerthiscommandinvokedhandler set the command that will be invoked by defaultmessagedialogdefaultcommandindex 0 set the command to be invoked when escape is pressedmessagedialogcancelcommandindex 1 show the message dialogawait messagedialogshowasyncthis works fine on a windows desktop app but when i take the exact same code and try to use it for a windows phone app it has no problem adding the 3rd command but when it gets to the await messagedialogshowasync line it will crash with an unhandled exception interestingly it does not crash in the same manner as a desktop app does when you add 4 commands for that it will throw the exception when you try to add the 4th command on the phone it would not have a problem with that but it would not work when it tries to show the messagedialogam i missing something or does the maximum number of commands on a messagedialog quietly get bumped down from 3 to 2 when youre on a phone,['c#'] +726258,difference in output printing a preinitialized java double vs inline while upgrading a build from java 16 to 17 our unit tests started failing because of a difference between how the 2 versions handle the printing of trailing zeros on doublesthis can be reproduced with this exampledouble preinit 010dsystemoutprintlnpreinit preinitsystemoutprintln inline 010djava 16 will outputpreinit 010 inline 010java 17 will outputpreinit 01 inline 010i have 2 questionswhy is the printing of an inline concatenation different than the same concatenation with a preinitialized valuewhat change between java 16 and 17 is causing the difference in output from version to version,['java'] +726268,snapchatlike swipe navigation between views in xcode 6 and swift i have been trying to implement swipe navigation between view controllers in my app using the swipe gesture recognizer and embeded navigation controller but it does not look even close to the snapchats nav what would be the most efficient and appropiate way to implement such functionalityi am quite a newbie to swift and programming really and i would appreciate every helpful comment,['ios'] +726300,kuttypeurl undefined a use of unresolved identifier kuttypeurl in swift i am having trouble getting a sharing extension to work i have the following in my sharing controllerlet item nsextensionitem selfextensioncontextinputitems0 as nsextensionitemlet itemprovider nsitemprovider itemattachments0 as nsitemprovidervar url nsstringif itemproviderhasitemconformingtotypeidentifierkuttypeurl itemproviderloaditemfortypeidentifierkuttypeurl options nil completionhandler url nsurl error nserror in url urlabsolutestring selfextensioncontextcompleterequestreturningitemsnil completionhandler nilthis gives me the error use of unresolved identifier kuttypeurl on the line if itemproviderhasitemconformingtotypeidentifierkuttypeurl it seems to be defined as a constant in swift but i cannot seem to access it is it part of an enum do i have to import something to get access to itthanks for your help,['ios'] +726351,async like pattern in pyqt or cleaner background call pattern i am trying to write a shortone file pyqt program which is responsiveso dependencies outside pythonlxmlqt especially ones i cannot just stick in the file have some downsides for this use case but i might still be willing to try them i am trying to perform possibly lengthyand cancelable operations on a worker threadactually the background operation has a lock around it to prevent multiple operations at oncesince the library it uses can only be used one call at a time and timeouts so spawning multiple threads would be fine alsoas far as i can figure out the basic way to do this with qt isnote code is not tested so it may be wrongclass mainwindowqwidget selfworker moved to background thread def inituiself selfcmd buttonclickedconnectselfsend pyqtslot def sendself get cmd from gui qtcoreqtimersingleshot0 lambda selfworkercmd pyqtslotstr def end sendself result set some gui to thisplay result class workerobjectqobject def send cmdself cmd get result of cmd qtcoreqtimersingleshot0 lambda selfmain windowend sendam i using qtimer rightit runs on different thread righti would really prefer to have something simpler and more abstracted along the lines of cs asyncnote i have not used asyncio so i might be getting some things wrongclass mainwindowqwidget asynciocoroutine def sendself get cmd from gui result yield from selfworkercmd set gui textbox to resultclass workerobjectqobject asynciocoroutine def send cmdself cmd get result of cmd yield from looprun in executornone selfmodelsend command cmdi heard that python 3 had similar features and there was a back port but does it work properly with qtif anyone knows of another saner pattern that too would be usefulan acceptable answer,['python'] +726357,html aside tag vs div tag what is the difference between the div tag and the new html5 aside tagw3schools has a very similar description for the two aside divi have also seen many sites use the aside tag where a div tag would be perfectly finealthough when i put them both into practise they behave the same way like soaside h4this is a headingh4 pthis is a very short paragraphpasidediv h4this is a headingh4 pthis is a very short paragraphpdivworking exampleso my question is what is the main difference between the two when should one be used over the other,['html'] +726376,embeded youtube video on touch device showing right click context menu automatically i am using cordova and using iframe to include youtube videoi am using this line to put the video in the iframeylinkiframe width100 heightheight srcylinkrel0controls1showinfo0modestbranding1 frameborder0 allowfullscreen allownetworkinginternaliframelist holderhtmlylinkylink format was like it loads perfectly video thumbnail loads then i start the play button video plays as expected problem is that it also trigger the right click context menu of youtube i tried to touch other places of the video to hide it but it reappears in the places where i touchedthen i tried few suggestions last i end up with this huge url for using all those suggestionsylinkiframe width100 heightheight srcylinkrel0controls1showinfo0modestbranding1thisablekb1wmodetransparent frameborder0allowfullscreen allownetworkinginternal oncontextmenureturn falseiframestill not working most suggestions were using allownetworkinginternal but i used it and no change it is happening only on touch device i am testing on android 23 and 404how can i stop this context menu or hide it thisable it i only need the seek control and fullscreen control i do not need anything else in the video what i am missing forgot to mention funny thing is that the first line worked perfectly yesterday and not working today context menu was not showing yesterday now i am wondering if youtube changed anything or not,"['android', 'ios']" +726474,understand com c interfaces the microsoftofficeinteropword document interface has a method with the following signaturevoid closeref object savechanges typemissing ref object originalformat typemissing ref object routedocument typemissinga few points i am having trouble understandinga ref parameter cannot have a default valuea default value has to be a constant and typemissing is notwhen calling this method i can use closefalse normally a ref parameter requires an assignable variablewhen navigating to the definition of type in visual studio it takes me to the documenttype property but this does not have a property named missing is this a bug in vsthank you for any explanations,['c#'] +726510,what is copymove constructor choosing rule in c when does movetocopy fallback happen the first exampleinclude iostreaminclude memoryusing namespace stdstruct a unique ptrint ref aconst a delete aa default aconst int i refnew inti a defaultint main a a2 0 1 return 0it works perfectly so here the move constructor is usedlet us remove the move constructor and add a copy oneinclude iostreaminclude memoryusing namespace stdstruct a unique ptrint ref aconst aa ref arefget new intaref nullptr aa delete aconst int i refnew inti a defaultint main a a2 0 1 return 0now the compilation falls with the error use of deleted function aso the move constructor is required and there is no fall back to a copy constructornow let us remove both copy and moveconstructorsinclude iostreaminclude memoryusing namespace stdstruct a unique ptrint ref aconst int i refnew inti a defaultint main a a2 0 1 return 0and it falls with use of deleted function aconst aa compilation error now it requires a copy constructorso there was a fallback from the move constructor to the copy constructorwhy does anyone have any idea how does it conform to the c standard and what actually is the rule of choosing among copymove constructors,['c++'] +726570,elegant way of getting number of items for ns enum is there an elegant way of getting the total number of items in a ns enum and the maximum valuesome examplestypedef ns enumnsinteger myenum myenuma 0 myenumb 1 myenumc 2 numberofitemsmyenum 3 maximumvaluemyenum 2typedef ns enumnsinteger myenum myenuma myenumb myenumc numberofitemsmyenum 3 maximumvaluemyenum 2typedef ns enumnsinteger myenum myenuma 4 myenumb myenumc numberofitemsmyenum 3 maximumvaluemyenum 6typedef ns enumnsinteger myenum myenuma 0 myenumb 2 myenumc 4 numberofitemsmyenum 3 maximumvaluemyenum 4,"['objective-c', 'c']" +726637,jsp comparison operator behaviour i want to compare two different types in cif tag of jsp basically left one is number always but right one is a string and if that string could be parse to a number i receive no error but if the string cant be parsed to a number i receive javaxelelexception cannot convert no of type class javalangstring to class javalanglongpractically1 works fine 1 4 works fine 1 yes triggers the exceptionbut even the 3rd comparison worked fine in previous versions of jsps but now it causes exceptionshas the behaviour of changed over period of timeany suggestions are highly appreciated,['java'] +726653,dirty checking on angular i was reading some article to understand a little bit more how angularjs worksone of the terms that i did not understand is dirty checking what is it exactly it seems like an observer pattern but apparently it is bettercan you help me understand this pleasethanks in advance,['javascript'] +726662,uicollectionview cell size in autolayout so i am using uicollectionview under autolayoutenabled storyboardi am trying to set cell size based on collectionview itself and it is based on collectionview layout sizeforitematindexpath methodcollectionview also depends on auto layout and it gives wrong size at first time i assume this is before view is layoutedi know they will have correct size after viewdidlayoutsubviews method is called but it causes double reloading of the collectionview items which makes ui glitches at run timehere is collectionview layout sizeforitematindexpath method of my implementation cgsizecollectionviewuicollectionview collectionview layoutuicollectionviewlayout collectionviewlayout sizeforitematindexpathnsindexpath indexpath cgsize innersize cgsizemakegalleryviewframesizewidth 80 galleryviewframesizeheight 40 glphotoasset photo pcopticsphotopoint clusterpointsindexpathrow photo cgfloat ratio mininnersizewidth photosizewidth innersizeheight photosizeheight return cgsizemakephotosizewidth ratio photosizeheight ratio,"['ios', 'objective-c']" +726834,how to reenable jquery tooltip after thisabled true trying to temporarily thisable the jquery tooltipdocumenttooltip option thisabled true when i try to reenable them again all of the title attributes are gone i was trying to reenable them usingdocumenttooltip option thisabled falsethe title attributes is actually being removed completely when i first set it to thisabled to truealso trieddocumenttooltipthisabledocumenttooltipenableit is doing the same thingupdatefound a solution to my own question with the help of jasen and zgr024 see below,"['javascript', 'jquery']" +726899,nullpointerexception with stringarray in spinner first app and so really new at android played around about a year ago but nothing came of it decent at programming wanting to make sure app renders on a phone no functionality atm compiles fine no problems there push it to my phone and unfortunately splitr has stoppededit added to the mainactivityjava edits have before and after not in actual code but now it flags adaptersetdropdownviewresourceandroidrlayoutactivity main apply the adapter to the spinnerspinnersplitsetadapteradaptersaying error18 36 identifier expectedsetdropdownviewresource activity main and setadapter all in redandroid studiomoto g cm11 4here is the code let me know if i missed anything outmainactivityjavapackage comhydr0dr4gonsplitrv2import androidappactivityimport androidosbundleimport androidviewmenuimport androidviewmenuitemimport androidwidgetarrayadapterimport androidwidgetspinnerpublic class mainactivity extends activity spinner spinnersplit spinner findviewbyidridspinner create an arrayadapter using the string array and a default spinner layoutarrayadaptercharsequence adapter arrayadaptercreatefromresourcethis rarrayarraysplitr androidrlayoutsimple spinner item specify the layout to use when the list of choices appearsadaptersetdropdownviewresourceandroidrlayoutactivity main apply the adapter to the spinnerspinnersplitsetadapteradapteroverrideprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity mainoverridepublic boolean oncreateoptionsmenumenu menu inflate the menu this adds items to the action bar if it is present getmenuinflaterinflatermenumain menu return trueoverridepublic boolean onoptionsitemselectedmenuitem item handle action bar item clicks here the action bar will automatically handle clicks on the homeup button so long as you specify a parent activity in androidmanifestxml int id itemgetitemid if id ridaction settings return true return superonoptionsitemselecteditem splitrdialogfragmentjavapackage comhydr0dr4gonsplitrv2import androidappalertdialogimport androidappdialogimport androidappdialogfragmentimport androidcontentdialoginterfaceimport androidosbundlepublic class splitrdialogfragment extends dialogfragment overridepublic dialog oncreatedialogbundle savedinstancestate use the builder class for convenient dialog construction alertdialogbuilder builder new alertdialogbuildergetactivity buildersetmessagerstringdialog split pay setnegativebuttonrstringok new dialoginterfaceonclicklistener public void onclickdialoginterface dialog int id user cancelled the dialog create the alertdialog object and return it return buildercreate stringsxmlxml version10 encodingutf8resources string nameapp namesplitrstring string namehello worldhello worldstring string nameaction settingssettingsstring string namebtnsplitsplitstring string namebtntip tipstring string nametxtsplitsplit bystring string nametxthintenter bill totalstring string namespinnersplitno of peoplestring string namedialog split payeach person paysstring string nameokokstringarray namearraysplitr item2item item3item item4item item5item item6item item7item item8item item9item item10itemarrayactvity mainxmlrelativelayout xmlnsandroidxmlnstoolsandroidlayout widthfill parentandroidlayout heightfill parentandroidpaddingleftdimenactivity horizontal marginandroidpaddingrightdimenactivity horizontal marginandroidpaddingtopdimenactivity vertical marginandroidpaddingbottomdimenactivity vertical margintoolscontextcomhydr0dr4gonsplitrmainactivitytablelayout androidlayout widthfill parent androidlayout heightfill parent androidlayout alignparenttoptrue androidlayout alignparentstarttrue androidpaddingleft40dp androidpaddingtop80dp androidpaddingright40dp androidpaddingbottom80dp tablerow androidlayout widthfill parent androidlayout heightfill parent edittext androidlayout widthwrap content androidlayout heightwrap content androidlayout span2 androidinputtypenumber androidems10 androidididedittext androidlayout column0 androidlayout weight15 androidhintstringtxthint tablerow tablerow androidlayout widthfill parent androidlayout heightfill parent textview androidlayout width0dp androidlayout heightmatch parent androidtextstringtxtsplit androidididtxtsplit androidlayout weight1 androidtextsize32dp androidtextalignmentcenter androidgravitycenter spinner androidlayout width0dp androidlayout heightmatch parent androidididspinner androidlayout weight1 androidspinnerstyleandroidstylewidgetspinnerdropdown androidtextalignmentcenter androidentriesarrayarraysplitr androidpromptstringspinnersplit tablerow tablerow androidlayout widthfill parent androidlayout heightfill parent button androidlayout width0dp androidlayout heightwrap content androidtextstringbtntip androidididbtntip androidlayout weight1 button androidlayout width0dp androidlayout heightwrap content androidtextstringbtnsplit androidididbtnsplit androidlayout weight1 tablerowtablelayoutlogcat 0711 211850899 1029010290comhydr0dr4gonsplitrv2 dactivitythreadi1 handlebindapplicationcomhydr0dr4gonsplitrv20711 211850899 1029010290comhydr0dr4gonsplitrv2 dactivitythreadi1 settargetheaputilization0750711 211850899 1029010290comhydr0dr4gonsplitrv2 dactivitythreadi1 settargetheapminfree20971520711 211851198 1029010290comhydr0dr4gonsplitrv2 dandroidruntimei1 shutting down vm0711 211851206 1029010290comhydr0dr4gonsplitrv2 eandroidruntimei1 fatal exception main process comhydr0dr4gonsplitrv2 pid 10290 javalangnullpointerexception attempt to invoke virtual method javalangstring javalangobjecttostring on a null object reference at androidwidgetarrayadaptercreateviewfromresourcearrayadapterjava394 at androidwidgetarrayadaptergetviewarrayadapterjava362 at androidwidgetabsspinneronmeasureabsspinnerjava193 at androidwidgetspinneronmeasurespinnerjava482 at androidviewviewmeasureviewjava16521 at androidwidgettablerowgetcolumnswidthstablerowjava312 at androidwidgettablelayoutfindlargestcellstablelayoutjava508 at androidwidgettablelayoutmeasureverticaltablelayoutjava473 at androidwidgettablelayoutonmeasuretablelayoutjava439 at androidviewviewmeasureviewjava16521 at androidwidgetrelativelayoutmeasurechildhorizontalrelativelayoutjava719 at androidwidgetrelativelayoutonmeasurerelativelayoutjava455 at androidviewviewmeasureviewjava16521 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava5125 at androidwidgetframelayoutonmeasureframelayoutjava310 at androidviewviewmeasureviewjava16521 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava5125 at comandroidinternalwidgetactionbaroverlaylayoutonmeasureactionbaroverlaylayoutjava327 at androidviewviewmeasureviewjava16521 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava5125 at androidwidgetframelayoutonmeasureframelayoutjava310 at comandroidinternalpolicyimplphonewindowdecorviewonmeasurephonewindowjava2552 at androidviewviewmeasureviewjava16521 at androidviewviewrootimplperformmeasureviewrootimpljava1912 at androidviewviewrootimplmeasurehierarchyviewrootimpljava1109 at androidviewviewrootimplperformtraversalsviewrootimpljava1291 at androidviewviewrootimpldotraversalviewrootimpljava996 at androidviewviewrootimpltraversalrunnablerunviewrootimpljava5600 at androidviewchoreographercallbackrecordrunchoreographerjava761 at androidviewchoreographerdocallbackschoreographerjava574 at androidviewchoreographerdoframechoreographerjava544 at androidviewchoreographerframethisplayeventreceiverrunchoreographerjava747 at androidoshandlerhandlecallbackhandlerjava733 at androidoshandlerthispatchmessagehandlerjava95 at androidoslooperlooplooperjava136 at androidappactivitythreadmainactivitythreadjava5137 at javalangreflectmethodinvokenative method at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava795 at comandroidinternaloszygoteinitmainzygoteinitjava611thanks,"['java', 'android']" +726910,why does stdistringstream appear to resolve differently to stdifstream in the ternary operator i am used to writing little command line tools that take either a file name or read from stdcin so i have been using this pattern for quite a whileint mainint argc char argv stdstring filename args processing stdifstream ifs iffilenameempty ifsopenfilename stdistream is ifsis open ifs stdcin stdstring line whilestdgetlineis line process line return 0after reading a question on stack overflow i tried to modify my usual pattern to suit the need to read either from a file or from a stdistringstream to my surprise it would not compile and gives this errortempcpp16447 error invalid initialization of nonconst reference of type astdistream aka stdbasic istreamchara from an rvalue of type avoida stdistream is ifsis open ifs iss would not compilewhich looks to me like it is trying to convert the stdistringstream object iss to a boolean and getting its operator voidint mainint argc char argv stdstring filename stdstring data args processing stdifstream ifs stdistringstream iss iffilenameempty ifsopenfilename stdistream is ifsis open ifs iss would not compile stdstring line whilestdgetlineis line process line return 0why is it treating stdistringstream differently from stdcin and stdifstream they all derive from stdistreamthen i remembered having converted my pattern to accommodate three possibilities reading from file string or stdcin and i remember that worked although it is pretty clumsy so applying the triple solution to this problem i came up with a fudge that totally worksint mainint argc char argv stdstring filename stdstring data args processing stdifstream ifs stdistringstream iss iffilenameempty ifsopenfilename stdistream is ifsis open ifs true iss stdcin fudge works stdstring line whilestdgetlineis line process line return 0why does this fudge work is gcc breaking any rules on how the ternary operator resolves its types or am i missing something,['c++'] +726991,using splitviewcontroller on iphone portrays detail view first i am currently developing for ios 8 and developing an app with the new adaptive framework the weird part is when i use the the splitviewcontroller on iphone with this storyboard configuration the app does not start with the master view controller but the detail controller is this a bug and how could i be able to fix itthis does only happen if the navigationcontroller that envelops the master exists if i remove it the app starts with master controller,"['ios', 'iphone', 'objective-c']" +727105,set key and value in spinner i have a spiner and i want set a key and a value on thisi use of hashmapit is workbut show one rowlike thiscode final view rootview inflaterinflaterlayoutfragment photos container false spinner spinspinnerrootviewfindviewbyidridspinner1 hashmapinteger string p hashnew hashmapinteger string update get informationnew updaterootviewgetcontext arrayliststring province namenew arrayliststring province nameget informationget province arraylistinteger province idnew arraylistinteger province idget informationget province id for int i 0 i province idsize i p hashputprovince idgeti province namegeti logdprovince idgeti province idgeti logd province namegeti province namegeti arrayadapterhashmapinteger string adapter new arrayadapterhashmapintegerstringrootviewgetcontext androidrlayoutsimple spinner item adapteraddp hash adaptersetdropdownviewresourceandroidrlayoutsimple spinner dropdown item spinsetadapteradapter,['android'] +727185,random forest with categorical features in sklearn say i have a categorical feature color which takes the valuesred blue green orangeand i want to use it to predict something in a random forest if i onehot encode it ie i change it to four dummy variables how do i tell sklearn that the four dummy variables are really one variable specifically when sklearn is randomly selecting features to use at different nodes it should either include the red blue green and orange dummies together or it should not include any of themi have heard that there is no way to do this but i would imagine there must be a way to deal with categorical variables without arbitrarily coding them as numbers or something like that,['python'] +727226,if i use mysqli prepared statements do i need to escape my question is that if i use mysqli prepared statements like belowstmt con1prepareupdate login set sessionloggedout where sessionstmtbind paramssessionstmtexecutestmtclosedo i still need to escape my variables like session with mysqli real escape string like belowsession mysqli real escape stringcon1 cookiesessionstmt con1prepareupdate login set sessionloggedout where sessionstmtbind paramssessionstmtexecutestmtclose,"['php', 'mysql']" +727264,filtering resources from the play services monolith to make your apk smaller a lot has been written about the monolithic nature of the google play services and why it should be split into more libraries for now the workaround to keep your apk small is to use proguard to strip out unused references this works pretty well for classesdex but not for the included resources i get around 1 mb of additional unused resources and with a bundled android wear app this overhead doubles so my apk is 2 mb larger than neededi am wondering whether there is some straightforward way in gradle to exclude some resources coming from the dependencies aars from the resulting apk it seems that the aapt options in the gradle android plugin only allow filtering assetsi was thinking about hooking in some custom aapt script which would call remove for a list of resources using aapt before signing the apk for releasedoes someone else have a simpler solution,['android'] +727275,elementreplacewith in a custom directives link only work at first time called i am new to angularjs and do not understand too much behind the scene basically i want to create an e kink directive base on the data in controller i dynamically create the html like a whole table thing to replace the directivethe directve in my html file is like thismatrixrowsmatrixrowsmy directive code is like this angularmodulematrix directivematrixrows function return restrict e replace true require matrix link function scope element attr ctrl scopewatchcurrentpage function newvalue oldvalue if newvalue newvalue oldvalue var html here is the code to generate the html elementreplacewithhtml through watching currentpages change i recreate the html and replace the directive tagwhen the first time i change currentpage the elementreplacewithhtml works fine then i change currentpage angin the watching function will be triggered but the elementreplacewithhtml would not workthen i stepped into angularjs source code i found after the first time elementreplacewiths execution element0parentnode became null this caused the replacewith crashanybody know how to make it work,['javascript'] +727282,why cannot i add first header to getpreferencescreen the standard settings activity from google android studio is now showing the first header general so i modified the code but i get javalangnullpointerexception at first occurrence of getpreferencescreenaddpreferencefakeheaderprivate void setupsimplepreferencesscreen if issimplepreferencesthis return preferencecategory fakeheader new preferencecategorythis fakeheadersettitlerstringpref header notifications getpreferencescreenaddpreferencefakeheader addpreferencesfromresourcerxmlpref general fakeheader new preferencecategorythis fakeheadersettitlerstringpref header notifications getpreferencescreenaddpreferencefakeheader addpreferencesfromresourcerxmlpref notification bindpreferencesummarytovaluefindpreferenceusername bindpreferencesummarytovaluefindpreferencepassword bindpreferencesummarytovaluefindpreferenceserver overridetargetapibuildversion codeshoneycombpublic void onbuildheaderslistheader target if issimplepreferencesthis loadheadersfromresourcerxmlpref headers target header androidfragmentcomexampleeslamrottapharmsettingsactivitygeneralpreferencefragment androidtitlestringpref header general preferenceheaders,"['java', 'android']" +727328,why can we reduce visibility of a property in extended class i have two classes parentpublic class parent public string a asd public void method and childpublic class child extends parent private string a 12 private void method in child i try to override the parent method which gives a compile time error of cannot reduce visibility of a method which is finebut why is this error not applicable to property a i am also reducing visibility of a but it does not give an error,['java'] +727344,reload or refresh a spring application context inside a test method i need to change the spring profiles that are active in my applicationcontext within a single method of my test class and to do so i need to run one line of code before refreshing the contest because i am using a profileresolver i have tried the followingwebappconfigurationcontextconfigurationlocations webwebinfspringxmlactiveprofilesresolver baseactiveprofilesresolvertestclasspublic class controllertest extends abstracttestngspringcontexttests test public void test throws exception codetosetactiveprofiles configurableapplicationcontextthisapplicationcontextrefresh tests here codetosetactiveprofiles back to prior profiles ideally refreshreload the context for future tests but i getjavalangillegalstateexception genericapplicationcontext does not support multiple refresh attempts just call refresh oncedirtiescontext does not work for me because it is run after classmethod execution not before and i need to execute a line of code prior to running the refreshreload anywayany suggestions i tried to have a look through the listenershooks that are being run but i did not see an obvious location to insert myself to achieve this behavior,['java'] +727371,what is the purpose of applicationname and keywords in meta tag what is the purpose or need of the below tagsmeta nameapplicationname contentstackoverflowmeta namekeywords contentquestions answers seo tells keywords are not given importance these days,['html'] +727430,how to create a right facing arrow using xml shapes in android how to create a right facing arrow using xml shapes in android like this,['android'] +727516,using auto and decltype to return reference from function in templated class how can i coerce a function in a templated class to return a reference to a member variable using autodecltypeheres a trivialized example of what i am trying to do suppose youve got a templated class that stores something in a private member variable a as followsinclude iostreamtemplate typename tclass aprivate t a public at a a a 1 return const reference to a const t get const return a 2 return nonconst reference to a t get return a int mainint argc char argv aint a3 const auto a1 aget 1 return const reference to a a1 4 should not compile stdcout value of a aget stdendl auto a2 aget 2 return nonconst reference to a a2 5 stdcout value of a aget stdendl return 0the expecteddesired output isvalue of a 3value of a 5but now suppose i want the compiler to deduce the type returned by the const and nonconst get functions in at and i want to ensure both calls return references to a my best guess is currentlytemplate typename tclass aprivate t a public at a a a 1 return const reference to a const auto get const stdadd lvalue referenceconst decltypea type return a 2 return nonconst reference to a auto get stdadd lvalue referencedecltypea type return a but that fails to compile the first error given by gcc isdecltypecpp1129 error expected typespecifierdecltypecpp1126 error expected aa at end of member declarationdecltypecpp1129 error aadd lvalue referencea in namespace astda does not name a typethe motivation for this lies outwith my thistilled example code but stems from an attempt to reduce the number of parameters a template takes when one or more of those parameters is used solely to specify a return type which the compiler should i think be able to deduce by itself note in the real world the return type of get is not that of a but is the return type of some function fa which i know to be deducible by the compiler thus my need for autodecltype in this examplethe thing that is puzzling me is that the compiler can deduce the return type correctly using nearidentical code in a nontemplated classclass aprivate int a public aint a a a 1 return const reference to a const auto get const stdadd lvalue referenceconst decltypea type return a 2 return nonconst reference to a auto get stdadd lvalue referencedecltypea type return a any help to understand what i am missing will be greatly appreciateddetailscentos 65gcc gcc 472 20121015 red hat 4725,['c++'] +727542,retrofit cannot connect to my local web server on port 30 my app that is using retrofit v161 to connect to rest web services cannot connect to my local web server running on localhost this is the error i am gettingthis is inside nexus4 v43 emulator i am using android studio for development and i have added androidpermissioninternet androidpermissionaccess network state permissions in manifest filethe error says its waited for 15s but it does not it errors out right away0713 155753947 820840ittestandroidappactivity dretrofiti1 http post httplocalhost30appauthsignin0713 155754132 820840ittestandroidappactivity dretrofiti1 contenttype applicationjson charsetutf80713 155754132 820840ittestandroidappactivity dretrofiti1 contentlength 440713 155754157 820840ittestandroidappactivity dretrofiti1 authemailstevepasswordpass0713 155754387 820840ittestandroidappactivity dretrofiti1 end http 44byte body0713 155754657 820840ittestandroidappactivity dretrofiti1 error httplocalhost30appauthsignin0713 155754857 820840ittestandroidappactivity dretrofiti1 javanetconnectexception failed to connect to localhost127001 port 30 after 150ms isconnected failed econnrefused connection refused at libcoreioiobridgeisconnectediobridgejava223 at libcoreioiobridgeconnecterrnoiobridgejava161 at libcoreioiobridgeconnectiobridgejava112 at javanetplainsocketimplconnectplainsocketimpljava192 at javanetplainsocketimplconnectplainsocketimpljava459 at javanetsocketconnectsocketjava842 at libcorenethttphttpconnectioninithttpconnectionjava76 at libcorenethttphttpconnectioninithttpconnectionjava50 at libcorenethttphttpconnectionaddressconnecthttpconnectionjava340 at libcorenethttphttpconnectionpoolgethttpconnectionpooljava87 at libcorenethttphttpconnectionconnecthttpconnectionjava128 at libcorenethttphttpengineopensocketconnectionhttpenginejava316 at libcorenethttphttpengineconnecthttpenginejava311 at libcorenethttphttpenginesendsocketrequesthttpenginejava290 at libcorenethttphttpenginesendrequesthttpenginejava240 at libcorenethttphttpurlconnectionimplconnecthttpurlconnectionimpljava81 at libcorenethttphttpurlconnectionimplgetoutputstreamhttpurlconnectionimpljava197 at retrofitclienturlconnectionclientpreparerequesturlconnectionclientjava68 at retrofitclienturlconnectionclientexecuteurlconnectionclientjava37 at retrofitrestadapterresthandlerinvokerequestrestadapterjava321 at retrofitrestadapterresthandleraccess100restadapterjava220 at retrofitrestadapterresthandler2obtainresponserestadapterjava278 at retrofitcallbackrunnableruncallbackrunnablejava42 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava1080 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava573 at retrofitplatformandroid21runplatformjava142 at javalangthreadrunthreadjava841 caused by libcoreioerrnoexception isconnected failed econnrefused connection refused at libcoreioiobridgeisconnectediobridgejava208a a a a a a a a a a a a at libcoreioiobridgeconnecterrnoiobridgejava161a a a a a a a a a a a a at libcoreioiobridgeconnectiobridgejava112a a a a a a a a a a a a at javanetplainsocketimplconnectplainsocketimpljava192a a a a a a a a a a a a at javanetplainsocketimplconnectplainsocketimpljava459a a a a a a a a a a a a at javanetsocketconnectsocketjava842a a a a a a a a a a a a at libcorenethttphttpconnectioninithttpconnectionjava76a a a a a a a a a a a a at libcorenethttphttpconnectioninithttpconnectionjava50a a a a a a a a a a a a at libcorenethttphttpconnectionaddressconnecthttpconnectionjava340a a a a a a a a a a a a at libcorenethttphttpconnectionpoolgethttpconnectionpooljava87a a a a a a a a a a a a at libcorenethttphttpconnectionconnecthttpconnectionjava128a a a a a a a a a a a a at libcorenethttphttpengineopensocketconnectionhttpenginejava316a a a a a a a a a a a a at libcorenethttphttpengineconnecthttpenginejava311a a a a a a a a a a a a at libcorenethttphttpenginesendsocketrequesthttpenginejava290a a a a a a a a a a a a at libcorenethttphttpenginesendrequesthttpenginejava240a a a a a a a a a a a a at libcorenethttphttpurlconnectionimplconnecthttpurlconnectionimpljava81a a a a a a a a a a a a at libcorenethttphttpurlconnectionimplgetoutputstreamhttpurlconnectionimpljava197a a a a a a a a a a a a at retrofitclienturlconnectionclientpreparerequesturlconnectionclientjava68a a a a a a a a a a a a at retrofitclienturlconnectionclientexecuteurlconnectionclientjava37a a a a a a a a a a a a at retrofitrestadapterresthandlerinvokerequestrestadapterjava321a a a a a a a a a a a a at retrofitrestadapterresthandleraccess100restadapterjava220a a a a a a a a a a a a at retrofitrestadapterresthandler2obtainresponserestadapterjava278a a a a a a a a a a a a at retrofitcallbackrunnableruncallbackrunnablejava42a a a a a a a a a a a a at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava1080a a a a a a a a a a a a at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava573a a a a a a a a a a a a at retrofitplatformandroid21runplatformjava142a a a a a a a a a a a a at javalangthreadrunthreadjava8410713 155754857 820840ittestandroidappactivity dretrofiti1 end error,['android'] +727579,springboot hibernate jpa generating drop constraint errors on startup with h2 database i am using springboot and have an h2 database configured like so in the applicationpropertiesspringdatasourceurljdbch2memazdb close delay1db close on exitfalsespringdatasourcedriverclassnameorgh2driverspringdatasourceusernamesaspringdatasourcepasswordspringjpadatabaseplatformorghibernatedialecth2dialectin the logs i am seeing the following errorsohibernatejpainternalutilloghelper h0204 processing persistenceunitinfo name default orghibernateversion h0412 hibernate core 435finalorghibernatecfgenvironment h0206 hibernateproperties not foundorghibernatecfgenvironment h021 bytecode provider name javassistohibernateannotationscommonversion hcann01 hibernate commons annotations 404finalorghibernatedialectdialect h0400 using dialect orghibernatedialecth2dialectohhiastastquerytranslatorfactory h0397 using astquerytranslatorfactoryorghibernatetoolhbm2ddlschemaexport h0227 running hbm2ddl schema exportorghibernatetoolhbm2ddlschemaexport h0389 unsuccessful alter table key request drop constraint fk 53shrbc21c25inskpp1yoxxss if existsorghibernatetoolhbm2ddlschemaexport table key request not found sql statement alter table key request drop constraint fk 53shrbc21c25inskpp1yoxxss if exists 42102178even though hibernate reports these as errors i can then login to the h2 console and see the constraints and they appear to be just fineselect table name index name column name index type name from information schemaindexes where table namekey requesttable name index name column name index type name key request primary key f request id primary keykey request fk 53shrbc21c25inskpp1yoxxss index f user id indexif really looks like hibernate is trying to drop these constraints before it actually creates the database ie some kind of bug in hibernateis there any way to avoid these errors clogging up the logs or are the indicative of a real failure somewhereupdate 1trying to force the application to only do updates using this settingspringjpahibernateddlautoupdateresults in the following errors all the other errors thisappearorghibernatetoolhbm2ddlschemaupdate h0388 unsuccessful alter table lti result add constraint fk 1cnh9amy5br8owkmafsrth3as foreign key result id references lti linkorghibernatetoolhbm2ddlschemaupdate constraint fk 1cnh9amy5br8owkmafsrth3as already exists sql statement alter table lti result add constraint fk 1cnh9amy5br8owkmafsrth3as foreign key result id references lti link 90045178note the source is here starterspecifically the config starterblobmastersrcmainresourcesapplicationpropertiesand the model startertreemastersrcmainjavaltistartermodel,['java'] +727632,core data transient values with swift does anyone know or have an example of how to handle core data transient values with swift i know to use nsmanaged before the properties but cannot figure out how to code the logic to build the transient values using swift,['ios'] +727716,segmenting license plate characters i am facing problem in segmenting characters from license plate imagei have applied following method to extract license plate characters adaptive threshold the license plate image select contours which having particular aspect ratioif there is any shade in the license plate image as in attached filei am not able to properly segment the characters due to improper binarizationshade in the image merges adjacent characters in the imagei have thresholded the images with different window sizes results are attachedhow can i segment characters from image if there is shade in the imagei am using opencv i have used following function in opencv to threshold my license plate imagecvadaptivethresholdlicenseplateimg threshimg 255 cv adaptive thresh gaussian c cv thresh binary inv windi have tried with different window sizes wind and different adaptivemethodadaptive thresh mean c and adaptive thresh gaussian cto get thresholded image,['python'] +727830,packing arbitrary triangles into a finite box i need to pack triangles into a box as tightly as reasonable as part of a 3d optimization i am stuffing alphausing segments of different textures into a single different texture for use with depthsorting so textures do not switch with every new triis there an algorithm for doing this the triangles themselves can be made to be plyable transformable to be right angles effectively making this a boxstuffing algorithm instead but i would like to avoid this if possible as it would thistort the underlying texture art,['c++'] +727916,assigning to multilevel wildcards simple classclass pairkv and a few assignmentscollectionpairstringlong c1 new arraylistpairstringlongcollectionpairstringlong c2 c1 okcollectionpairstring c3 c1 this does not compilecollection extends pairstring c4 c1 okwhy does bullet number three not compile while the fourth one is perfectly legalcompiler errortype mismatch cannot convert from collectionpairstringlong to collectionpairstring,['java'] +727976,updated bokeh to 050 now plots all previous versions of graph in one window before i updated i would run my script and output the html file there would be my one plot in the window i would make changes to my script run it output the html file look at the new plot then i installed the library again to update it using conda i made some changes to my script ran it again and the output file included both the plot before i made some changes and a plot including the changes i ran the script again out of curiosity three plots in the one file ran it again four deleted the html file instead of overwriting five changed the name of the output html file six i even tried changing the name of the script the plots just keep piling upwhats going on why is it plotting every version of the graph i have ever made,['python'] +728110,incompatible pointer types passing in generic macro the following code generates 2 warnings which are described in the questions titleinclude stdiohstatic void print ffloat fprintffloat fn fstatic void print iint i printfint dn idefine printnum genericnum int print inum float print fnumint mainvoid printint10 printfloat10f return 0outputint 10float 10i know this macro could be written like the followingdefine printnum genericnum int print i float print fnumand in that case there would not be any warnings however my example is a dummy snippet which i wrote to demonstrate the problem in my real code base i chose the former solution because some other default but type specific arguments needs to be passed to the selected functionso the question is even if the macro is working as it should and the output is exactly what i expect why are the warnings generatedflags and environment mac os x 1094 apple llvm version 51 clang503040 based on llvm 34svn cc wall v g stdc11 fmacrobacktracelimit0 iusrlocalinclude c o buildtmpmaino maincupdate1i forgot to paste the full traceback here is the first onemainc3911 warning incompatible pointer types passing int to parameter of type float wincompatiblepointertypes printint10 mainc3123 note expanded from macro print float print fnum mainc2629 note passing argument to parameter f herestatic void print ffloat fprintffloat fn f and here is the second onemainc4011 warning incompatible pointer types passing float to parameter of type int wincompatiblepointertypes printfloat10f mainc3023 note expanded from macro print int print inum mainc2727 note passing argument to parameter i herestatic void print iint i printfint dn i update2until the developers of clang fix this bug here is an ugly piece of workaround to mute the warnings which will work if all keys in the assoclist are types or all are pointers to types and will fail if types and pointers to types are in the keys too hack recasting pointers to mute warnings define printnum genericnum int print iintnum float print ffloatnum,['c'] +728212,jetbrains intellij idea taking very long time to make for some reason intellij seems to be having an issue where it takes minutes to compile a simple java program here is a picture of it taking 1 minute and 54 seconds to compile the most basic hello world program that was taken compiling using java 8 i tried again using java 7 and heres a screen shot of that attempt it took 3 minutes 42 seconds this is not only happening the very first time it is happening every time i compile even the second or third time compiling it if i was to compile it by clicking make project then click run it would remake the project taking another 2minutes just to run it this is becoming a serious issue and any help is greatly appreciated editi am running windows 8 on an intel i7solvedfor anyone else having this problem check if you have malwarebytes antiexploit installed for me it severely impacted the performance of any of the ides i tried to code java in and was the ultimate cause of this issue thankssean,['java'] +728281,ios 8 start playing sound when in the background alarm clock app i know there are many questions on sof but this is the newest one the thing is i am trying to create and alarm app and i know for a fact that there are alarm apps out there that works perfectly somehow even if the app is not running and is in the backgroundmy question is how do you start playing sound after your app is already in the background uilocalnotification is great but youll only get application didreceivelocalnotification after the user has already clicked on your notification so playing sound using avaudioplayer did not work i want to play sound regardless weather the user clicks on it or does not of course with required background modes app plays audio or streams audiovideo using airplay in infoplist already set once the music starts playing it keeps playing even if i go to the backgroundi do not want to use uilocalnotificaation sound coz it is limited to 30 secs and only the able to play the sounds that are bundled with the applicationany insights thoughts sample code var notif uilocalnotification notiffiredate selfdatepickerdate notifalertbody test uiapplicationsharedapplicationschedulelocalnotificationnotifthe above code gets called when the user selects and alarm and clicks saveand heres whats happening in appdelegatefunc applicationapplication uiapplication didfinishlaunchingwithoptions launchoptions nsdictionary bool nsloglaunched applicationregisterusernotificationsettingsuiusernotificationsettingsfortypes uiusernotificationtypesound uiusernotificationtypealert uiusernotificationtypebadge categories nil avaudiosessionsharedinstancesetcategoryavaudiosessioncategoryplayback error nil avaudiosessionsharedinstancesetactivetrue error nil selfsound nsurlfileurlwithpath nsbundlemainbundlepathforresourcesound oftype caf selfaudioplayer avaudioplayercontentsofurl sound error nil return truefunc applicationapplication uiapplication didreceivelocalnotification notification uilocalnotification audioplayerplay nslogreceived local notifyou need to hold a strong reference to the avaudioplayer btw so it would not get released and the audioplayerplay would not do anything,['ios'] +728349,install failed no matching abis how to overcome when installing my app to android l preview it fails with errorinstall failed no matching abismy app uses arm only library features that uses library is thisabled on x86 it works perfectly before android l but now i cannot even install it how to thisable this error for my app,['android'] +728389,spoofing faking screenresolution while browsing the web i need to fake my screen resolution to websites i am viewing but keep my viewport the same chromes or ffs emulating does not solve my problemfor instance if i go to from a browser in full screen mode which has 1920x1080px resolution i want that site to think i am using 1024x728px but still be able to browse in full screen modeone of my guessess is i need to override js variables screenwidth and screenheight somehow or get rid of js completely but the particular site would not work with js thisabled but how and would that be enoughit is for anonymous purposes i hope i do not need to explain in detail i need to look as one device even though i am accessing the site from various devices tor browser not an option changes ip the browser i am using is firefox 300 and it runs on vps xubuntu 1404 i am connecting to remotelythis thread spoof js objects brought me close but not quite enough it remains unanswered i have struggeled upon this question for quite a long time so any recommedation is highly appreciated,['javascript'] +728390,what happens technically in this c code i have a class b which contains a vector of class a i want to initialize this vector through the constructor class a outputs some debug info so i can see when it is constructed destructed copied or movedinclude vectorinclude iostreamusing namespace stdclass a public a cout aa endl a cout aa endl aconst a t cout a endl aa t cout a endl class b public vectora va bconst vectora va vava int mainvoid b b a return 0now when i run this program compiled with gcc option fnoelideconstructors so the move constructor calls are not optimized away i get the following outputaso instead of just one instance of a the compiler generates five instances of it a is moved two times and it is copied two times i did not expect that the vector is passed by reference to the constructor and then copied into the class field so i would have expected a single copyoperation or even just a move operation because i hoped the vector i pass to the constructor is just a rvalue not two copies and two moves can someone please explain what exactly happens in this code where and why does it create all these copies of a,['c++'] +728400,in os x why does using println cause my program to run faster than without println i have run into a really strange bug and i am hoping someone here can shed some light as it is way out of my area of expertisefirst relevant background information i am running os x 1094 on a late 2013 macbook pro retina with a 24ghz haswell cpu i am using jdk se 8u5 for os x from oracle and i am running my code on the latest version of intellij idea this bug also seems to be specific only to os x as i posted on reddit about this bug already and other users with os x were able to recreate it while users on windows and linux including myself had the program run as expected with the println version running half a second slower than the version without printlnnow for the bug in my code i have a println statement that when included the program runs at 25 seconds if i remove the println statement either by deleting it or commenting it out the program counterintuitively takes longer to run at 9 seconds it is extremely strange as io should theoretically slow the program down not make it fasterfor my actual code it is my implementation of project euler problem 14 please keep in mind i am still a student so it is not the best implementationpublic class projecteuler14 public static void mainstring args final double time start systemcurrenttimemillis collatz c new collatz int highestnumofterms 0 int currentnumofterms 0 int highestvalue 0 value which produces most number of collatz terms for double i 1 i 10 i currentnumofterms cstartcollatzi if currentnumofterms highestnumofterms highestnumofterms currentnumofterms highestvalue inti systemoutprintlnnew term highestvalue this is the offending line of code final double time stop systemcurrenttimemillis systemoutprintlnhighest term highestvalue with highestnumofterms number of terms systemoutprintlncompleted in time stop time start10 s public class collatz private static int numofterms 0 private boolean isfirstrun false public int startcollatzdouble n isfirstrun true runcollatzn return numofterms private void runcollatzdouble n if isfirstrun numofterms 0 isfirstrun false if n 1 reached last term does nothing and causes program to return to startcollatz else if n 2 0 divides and by 2 following collatz rule running recursion numofterms numofterms 1 runcollatzn 2 else if n 2 1 multiples and by 3 and adds one following collatz rule running recursion numofterms numofterms 1 runcollatz3 n 1 the line of code in question has been commented in with all caps as it does not look like so does line numbers if you cannot find it it is within the nested if statement in my for loop in my main methodi have run my code multiple times with and without that line and i consistently get the above stated 25sec times with println and 9sec without println i have also rebooted my laptop multiple times to make sure it was not my current os run and the times stay consistentsince other os x 1094 users were able to replicate the code i suspect it is due to a lowlevel bug with the compliler jvm or os itself in any case this is way outside my knowledge it is not a critical bug but i definitely am interested in why this is happening and would appreciate any insight,['java'] +728408,orchard 181 installation with mysql i have been using orchard 18 for my previous projecti decided to try 181 i am using mysqlatfer i compiled the sources of orchard 181 and installed it with a blank database the following message occurs in the dashboardsome features need to be upgraded orchardautoroute orchardmedialibrarywhen i click update this message occurs an unhandled exception has occurred and the request was terminated please refresh the page if the error persists go backthe parameters dictionary contains a null entry for parameter bulkaction of nonnullable type orchardmodulesviewmodelsfeaturesbulkaction for method systemwebmvcactionresult featurespostorchardmodulesviewmodelsfeaturesbulkaction systemcollectionsgenericilist1systemstring systemnullable1systemboolean in orchardmodulescontrollersadmincontroller an optional parameter must be a reference type a nullable type or be declared as an optional parameter parametername parameterswith 18 i have noticed some issues too with mysql it seems that there are problems with the nullable typeif there was a way to change the server configuration somehow i have full acess to the database server,['mysql'] +728561,deleteonexit not deleting file i have created a few files for temporary use and used them as inputs for some methods and i calleddeleteonexit on all files i created but one file still remains i assume it is because the file is still in use but does not the compiler go to next line only after the current line is donesingle thread while its not a problem practically because of java overwrite there is only one file always i would like to understand why it happens and also if i can use threadsleepsometimeedit file x new filextxtnew class1method1after creating all files5 i just added this linexdeleteonexit ydeletonexit and so onall the files except that last one is deleted,['java'] +728563,how to document functions that are enabled with sfinae with doxygen in a library i am developing i often have this kind of code templatetypename t p enable if chas v fieldt detaildummyconstexpr stdsize t v return tvtemplatetypename t p thisable if chas v fieldt detaildummyconstexpr stdsize t v return 1the two functions do the same thing but are enabled based on the type i would like to document only one of then and moreover i would like if possible to show it in doxygen without the template stuff as constexpr stdsize t v for the user the templates here have not value at all is that kind of thing possible with doxygen,['c++'] +728571,is it possible to restart a for loop to its first iteration in objectivec is it possible to restart to the first iteration of a for loop i do not want to do anything with my objects until i find a good object at which point i want to go back and do stuff with every object up to that good objectsobool someflag falsefor id object in array ifobject is good someflag true restart to first object in loop ifsomeflag dostuffwithobjectobject or is there a differentbetter way to do what i am trying to do obviously the easy way would be to just have two separate for loops so if i could get a second opinion telling me that is the best way that is just what i will shoot for for some reason i have a feeling there is got to be a better way though,['objective-c'] +728608,how to get a hashed device id for testing admob on ios when implementing admob you can define an array of test ids so that google knows to serve test ads to these devices instead of real ads however it requires hashed device ids this seems a little vague to me what id are they talking about and what hashing method do they expect me to usei am talking about the bit that should go in hererequesttestdevices hasheddeviceid,"['ios', 'objective-c']" +728611,bootstrap tooltippopover solving inconsistent placement to the left i have been working on a project and i have noticed some inconsistency in bootstraps behavior that i would like to solve when a popover or tooltip whatever they are basically the same is nearing the edge of the screen if it is a rightsided one when nearing the edge it will contract so as not to go offscreen it only works up to a point but that is usually enoughthis does not happen when the placement is to the leftieright placementnormal widthclose to the edgeleft placementnormal widthclose to the edgethese images are from a small demo i wrote to illustrate the problemi have messed around with the source code so far to no avail i cannot seem to place my finger on what exactly causes this behavior in the first placeany ideaspsi am using bootstrap 311 the new 32 does not solve the issue and i would like to avoid upgrading at this pointmajor updateafter some digging i figured out that this has nothing to do with bootstrap it is simple css it seems that when you position an element absolutely and push it to the sides it will try and stay withing the screeni never knew about this behavior and it happens automatically but only to the the direction youre pushing ie a div pushed from the left will contract when reaching the right edge of the screen and vice versa it just so happens that popovers are only positioned with the left assignment which is why were seeing the inconsistend behavior when it is pushed to the right it contracts but not the other directionso the solution is to assign right instead sounds simple not so much i took the source code and manipulated it a bit adding these lines somewhere arond line 250 in the jsfiddleif placement left offsetleft 0 var right windowwidth 10 offsetleft actualwidth offsetleft 0 tipoffsetoffset tipcss right right seems reasonable right if the offset to the left is less than 0 ie it goes offscreen then calculate the window width and remove from that the left offset and the width of the popover actualwidth itself and you get the thistance from the rightthen make sure to reset the offset left and apply the right positioning but it only sorta works which is to say it only works the second time around check it out for yourself hover once and it is misplaced pull the mouse to the side and try again and suddenly it is positioned correctly what the helleditok this seems to come up a lot so i will make it cleari know about auto placement i do not want it i want to control where the popover goes letting it decide automatically is not a solution to the problem it is merely avoiding it,"['javascript', 'jquery', 'css']" +728664,when to use a js framework we have a ruby on rails website which uses a lot of rails built in remote ajax with js templates we have new requirements that are taking us in the direction of a single page application where entire blocks and columns of the page will be ajax based should we continue to use rails ajax infrastructure or start incorporating a js framework like angularjs in other words what are the principle evaluation criteria for determining the need for a js framework,['ruby-on-rails'] +728762,adding a fragment on top of another fragment onclicklistener issue i am adding a fragment to an activity instead of replacing the current fragment because this corresponds to the type of behavior i want to havemy problem is that clicking in a spot on the top fragment the one that is currently visible where a view in the nonvisible fragment is located causes an onclick event on the view in the second nonvisible fragment to firewhy is this happening and how can i prevent thisthis is the code i use to first add the listview fragment to the activityoverrideprotected void oncreatebundle savedinstancestate if savedinstancestate null listfragment new listfragment getsupportfragmentmanagerbegintransaction addridframe container listfragment addtobackstacklistfragment tag commit in this same activity i am adding the second fragment on top of the list fragmentoverrideprotected void onactivityresultint requestcode int resultcode intent data createitemfragment new createitemfragment getsupportfragmentmanagerbegintransaction addridframe container createitemfragment addtobackstackcreateitemfragmenttag commit,['android'] +728897,mobile keyboard resize viewport i am doing a responsive web site and i have this problem everything works well until i select an input typetext and comes out the keyboard entire site is resized it is like the screen size is only the part above the keyboard i just want that mantain the normal size i have tried all the solution proposed on stackoverflow an other forum too bun nothing seems to work does anyone have any idea on how to fix thishead titleschoolintitle meta httpequivcontenttype contenttexthtml charsetutf8 meta nameviewport contentwidthdevicewidth heightdeviceheight initialscale10 maximumscale10 userscalableno script typetextjavascript srcscriptother codeupdatei am going to try to explain betteri have a head sectionother codediv classhead here is some text divother codethen a content sectionother codediv classcontainer div classcontent other code input typetext input typepassword input typesubmit divdivother codeall the element are in percentage there is nothin in pixelswhen the keyboad comes out the header the container and the content div are redimensioned instead the input fields and the button do not in any case they came out from their container becouse the container goes smaller and they maintain the original size i do not know if i made my self clearthe question is the same how i make it to remain to the original size when the keyboard comes out,"['jquery', 'html']" +729099,why c give me this error on the csc file i am pretty new in c development and i have the following problemwhen i try to build the application on which i am working i obtain the followings errors messageerror 2 source file loglogusermanagercs could not be found cdevelopmyframework40mymanagercsharpcsc mymanagercsharperror 8 source file antiphishingcs could not be found cdevelopearlywarningpublicimplementazionever2unittestprojectcsc unittestprojectit seeams to me that these errors appeared after an svn updatewhy what exactly means if i click on the error line it do not take me to the code line where the error appear what is the csc file how can try to fix this issuetnx,"['c#', 'asp.net', '.net']" +729223,why use a perfectly forwarded value a functor c11 and c14 introduces additional language constructs and improvements that target generic programming these include features such asrvalue referencesreference collapsingperfect forwardingmove semantics variadic templates and morei was browsing an earlier draft of the c14 specification now with updated text and the code in an example in a2051 compiletime integer sequences that i found interesting and peculiartemplateclass f class tuple stdsize t idecltypeauto apply implf f tuple t index sequencei return stdforwardffstdgetistdforwardtuplettemplateclass f class tupledecltypeauto applyf f tuple t using indices make index sequencestdtuple sizetuplevalue return apply implstdforwardff stdforwardtuplet indicesonline here intseqgeneral2questionwhy was the function f in apply impl being forwarded ie why stdforwardffstdgetwhy not just apply the function as fstdget,['c++'] +729228,android how to send interface from one activity to another i have an interface like this public interface myinterface public void amethodmy custom objectpublic class myobject private context context private myinterface inter public myobjectcontext context thiscontext context thisinter myinterface thiscontext interamethod mainactivitypublic class mainactivity extends activity implements myinterface override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main myobject my new myobjectthis override public void amethod toastmaketextthis done toastlength shortshow here inside myobject constructor i can get the interface from the context and then communicate with the activity but how can i send interface from one activity to another i need to call a method inside activity1 from activity2is there a way like this note i do not want to use fragment,"['java', 'android']" +729291,implicit intent for contact groups list i want to pick group contact groupi found code to open contacts activity but did not found for groupintent intentcontact new intentintentaction pick contactscontractcontactscontent uristartactivityintentcontactis there anyone know how to open following activity implicitlyi have done googling but no found more solutionyour help would be appreciatedthanks regardspratik,['android'] +729296,why int i byte char int long 1 is 1 i stumbled upon this code on internetpublic class test param args public static void mainstring args int i byte char int long 1 systemoutprintlni it prints 1can i know why here is the source,['java'] +729409,how to change app name per gradle build type i am trying to figure out a way to be able to change my applications app name per build type in gradle for instance i would like the debug version to have app namedebug and the qa version to have appnameqa i am familiar withdebug applicationidsuffix debug versionnamesuffix debughowever i cannot seem to find a gradle command to apply the change of the app when in the launcher,['android'] +729631,issues with java 7u65 last night a new java 7 update has been released 7u65 i have a web application where a service applet is loaded and after the update my tests on different pcs did not show issues nor wrong behaviorslater i started to receive issue reports related to my products java service applet all the reports came from users who updated java jre to 7u65 from 7u60the applet was not loading at all i thisplay a loading screen when the application starts and this was not being thisplayed also all the services provided by my java applet were unavailableafter changing the java control panels advanced configuration to always show the console in one of the pcs where this issue happened i thiscovered that the applet was not even launching the java consoleusing the same station where the error happens trying to access javacom to check the current java version the java applet is loaded and the console is thisplayed without errorsall tests were performed after clearing browser and java cache and even after removing the installed certificates mine is a valid signed appleti checked the java 7u65 release notes and none of the mentioned changes seem to affect my applet also there were no issues while using java 7u60i do not have any clues about what is going on perhaps because the java update was released hours ago as the java console can not be thisplayed even if i configure java control panel to do so i can not tell if there is any exception i can not reproduce the issue in my pcs windows 8 nor windows 7 both at 64 bits but the issue has been reported on windows 7 pcsone of my friends told me that this seems to be happening on machines where java 7u60 was in use and then it was updated to java 7u65 with no deinstallations also this tends to happen in older os ie winxp which is more naturali write this question because it seems very odd that some pcs have this issue and some others not i would like to know if any one else is having this issue knows what could be the reason or has thiscoveredapplied any solution to it also i would like to share the solution if i ever happen to find itthanksedit external references related to the same java version jreinternet explorer crashing after updated java to 7u65 an issue with the same jre version this time with internet explorer and firefoxrs loading issue java read an issue related to the same jre version update this time in a java gamethe future of java on windows xp this end of support announcement has been misread as java no longer works on windows xp or oracle will stop java updates from being applied on windows xp these statements are not correct,['java'] +729954,what is the point of mytypemyvar declaration in c in c11 standard we can declare variable in an unusual way we can declare myvar as intmyvar instead of int myvar what is the point of thisinclude iostreamusing namespace stdint main intmyvar myvar 10 cout myvar endl return 0upd actually there is a certain reason why i asked this what looked innocent just stopped to compile when we tried to port some code from msvc c03 to gcc c11here is an example include iostream using namespace std struct myassert myassertbool define assertcond myassertcond void funcvoid ptr assertptr error declaration of amyassert ptra shadows a parameter define assertcond myassertcond int main funcnullptr return 0,['c++'] +729979,c allocator and memory pool ownership i am confused about something let us say i have an arbitrary c allocator say something like thistemplateclass tstruct my allocator templateclass other struct rebind typedef my allocatorother other other members herenow consider the following code please read the commentstypedef my allocatorint allocalloc alloc get my allocator assume this works properlylong const p allocrebindlongotherallocallocate1 null notice that the rebound allocator for long is now destroyed can a new rebound allocator for long deallocate the memory from the old oneallocrebindlongotherallocdeallocatep 1 ie does the int allocator alloc keep alive the long memory pool tooat what point exactly can the backing storage pool be freedor to put it another way which allocator shares ownership of which memory pooli had always assumed without much second thought that allocators of the same value type shared ownership of their own memory pools but now it occurred to me that they may also share ownership of the memory pool behind all rebound allocators as well even though they manage entirely different typesmust allocators of rebound types keep alive each others memory pools until all of them are destroyedif the answer is different for c03 and c11 please explain both and the difference between them,['c++'] +729996,how to programmatically find the external ip address of a device without using external host when i read the ip address of the device i always get the local ip addressi use the following code snippet to do thatpublic string getipaddress try for enumerationnetworkinterface en networkinterfacegetnetworkinterfaces enhasmoreelements networkinterface intf ennextelement for enumerationinetaddress enumipaddr intfgetinetaddresses enumipaddrhasmoreelements inetaddress inetaddress enumipaddrnextelement if inetaddressisloopbackaddress string ip formatterformatipaddressinetaddresshashcode logdvpnconnectedip return ip catch exception ex logdexception extostring return empty but i need to read the external ip address without using any external host or web apis such as,"['java', 'android']" +730031,swift put multiple iboutlets in an array i made these marked with red border iboutlets using ctrl drag but i do not like to have the exact same line 9 times dry how do i put these iboutlets in an array,['ios'] +730045,does unary operator do type conversions till now i was believing that there is no use of unary operator but then i came across with following examplechar chshort shint iprintfd d dsizeofchsizeofshsizeofi output 1 2 4printfd d dsizeofchsizeofshsizeofi output 4 4 4does it mean is doing type conversion herebecause it is behaving same as following printfd d dsizeofintchsizeofintshsizeofi output 4 4 4this forces me to think is doing type conversionbut then i try it on double double fprintfd dsizeoffsizeofintfsizeoff output 8 4 8this forces me to rethink about unary operatorso my second question is does unary operator has special effect in sizeof operator,['c'] +730159,sending a form array to flask i have a html form with multiple inputs named like thisinput namehello typetext input namehello typetext input namehello typetext in php you get this as an array but is it the same way in python using flaski tried thishello requestformhello print helloin flask but that did not work i got a 400 bad requestbad requestthe browser or proxy sent a request that this server could not understandhow do i do it in flask,"['python', 'html']" +730169,first build with androidstudio failed i am new to android programming and i would like to use android studio for the start i downloaded and installed androidstudio 080 on my ubuntu 1404 machine i also set up java properlywhen i create a new project as told by it looks like it will try to build the sample files but then i always get this errorhomedanielandroidstudioprojectsheimwegappsrcmainresdrawablexhdpiic launcherpngerrorerror cannot run program homedanielandroidandroidstudiosdkbuildtoolsandroid44waapt error2 no such file or directoryerrorexecution failed for task appmergedebugresourceshomedanielandroidstudioprojectsheimwegappsrcmainresdrawablexhdpiic launcherpng error cannot run program homedanielandroidandroidstudiosdkbuildtoolsandroid44waapt error2 no such file or directoryhow can i deal with this error when i try to run the app it says aadb not responding you can wait more or kill adb process manually and click restarta,"['java', 'android']" +730185,noclassdeffounderror androidsupportv7internalviewmenumenubuilder there is an issue with the android appcompat v7 library on samsung devices running android 42 i keep getting crashes with the following stack trace in my developer consolejavalangnoclassdeffounderror androidsupportv7internalviewmenumenubuilder at androidsupportv7widgetpopupmenuinitpopupmenujava66 at commypackagenamecustomactivity5onclickcustomactivityjava215 at androidviewviewperformclickviewjava42 at androidviewviewperformclickrunviewjava17620 at androidoshandlerhandlecallbackhandlerjava800 at androidoshandlerthispatchmessagehandlerjava100 at androidoslooperlooplooperjava194 at androidappactivitythreadmainactivitythreadjava5391 at javalangreflectmethodinvokenativenative method at javalangreflectmethodinvokemethodjava525 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava833 at comandroidinternaloszygoteinitmainzygoteinitjava600 at dalviksystemnativestartmainnative methodthis is line 215 of customactivityjavapopupmenu popup new popupmenucustomactivitythis mimageviewmenuthe crashes come from an array of devices but always samsung and always android 42a quick web search leads me to believe that many people have the same issue some of the steps i have tried to solve the issue arecheck the android project properties make sure the appcompat library is added properlycheck the java build path order and export project properties make sure android dependencies and android private libraries is checkedconfirm the class is included in the library androidsupportv7internalviewmenumenubuilderconfirm rjava is located in gen directory for androidsupportv7appcompatconfirm the appcompat theme is included in the manifestxml activityclean and rebuild projectdespite these steps and despite it working on all other devices and android versions the crash reports still come through,"['java', 'android']" +730226,correct way to edit dictionary value python i have written the following code in two different ways i am trying to find the correct pythonic way of doing it i will explain the reasons for bothfirst way eafp this one uses pythons eafp priciple but causes some code duplicationtry my dictfoobar some varexcept keyerror my dictfoo my dictfoobar some varsecond way lbyl lbyl is not exactly considered pythonic but it removes the code duplicationif foo not in my dict my dictfoo my dictfoobar some varwhich way would be considered best or is there a better way,['python'] +730269,array as template parameter stack or heap my knowledge of the stack as compared with the heap is very rudimentary but when it comes to arrays from what i know something like this is created on the stackfloat x100whereas something like this is created on the heapfloat x new float100but what happens if i create a template array class and pass it in a stack array type like float100 exampleinclude iostreamusing namespace stdtemplate class tclass array public int size t data arrayint size sizesize data new tsize array delete data int main int m 10 const int and 100 arrayfloatn array new arrayfloatnm for int i 0 i m i for int j 0 j n j arraydataij i j cout arraydata109 endl delete arraywhat exactly is going on here is this memory created on the stack or on the heap my guess is the heap but how does this work does the compiler allocate one large block of memory and then store pointers that index into it every n elements or does it allocate many smaller blocks of memory not necessarily contiguous and store pointers to each blockfurthermore i cannot seem to do this without the aid of a template specifically this code does not compileint m 10const int and 100floatn array new floatnmwhat is going on hereeditthanks for the syntax tips everyone what i was really interested in is what happens in the blockint m 10const int and 100float arrayn new floatmnbut i did not know how to write it without the use of templates one thing i was really interested in is if the compiler allocates this as one large block on the heap how can you use the syntax arrayij to access a particular element without storing pointers to every nth element then i realized that since n is constant sizeoffloatn is fixed so when you make the array the compiler is allocating an array of m elements where each element is a floatn which in my case is 100 4 400 bytes now it all makes sense thanks,['c++'] +730311,how to remove element from array in foreach loop i am trying to remove an element in an array in a foreach loop but am having trouble with the standard solutions i have seen this is what i am currently tryingreviewforeachfunctionp ifp u2022 u2022 u2022 consolelogyippe reviewsplicep 1 i know it is getting into the if because i am seeing yippe in the console my problem i know that my for loop and if logic are sound but my attempt to remove the current element from the array is failingupdatetried out xotic750s answer and the element is still not being removedhere is the function in my codereviewforeachfunction item index object if item u2022 u2022 u2022 consolelogyippe objectspliceindex 1 consolelog item here is the output where the array is still not removedscott mcneilreviewed 4 months ago mitsubishi is amazingyippea a aso obviously it is going into the if statement as directed but it is also obvious that the a a a is still there,['javascript'] +730425,inheritance for extension methods how does inheritance work with extension methods in csay you have an interfaces ia ib ia and ic and a class foo ib ic now one defines extension methodspublic static class extensions public static void bar this ia instance some code public static void bar this ib instance some code public static void bar this ic instance some code public static void bar this foo instance some code how does a compiler determines the behavior of foobar based on empirical tests the compiler always selects the most specific instance like a normal call and without using dynamical binding since the this annotation is more syntactical sugar i supposein case two or more classes define a method from different branches in the inheritance hierarchy the call is ambiguous is there a way to define priority of one method over another in such casesare the claims above correct,['c#'] +730446,transfer data over sound in android i want to transfer data over soundeg text but i cannot find anyway to resolve this problem program will no need connect internetcan anyone help me,['android'] +730447,rails plain text template i would like to render an erb template into plain text in rails ideally i would be able to do something like thisappviewstesttesttxterbtest test when i tried rails complained with the following erroractionviewmissingtemplate missing template testtest applicationtest with localeen formatshtml variants handlerserb builder raw ruby coffee searched in userslandonschroppdevelopmenttestappviews,['ruby-on-rails'] +730466,jquery document ready with knockoutjs i just got thrown into the umbraco aspnet cms for my latest project i am not sure if this is how it across the board but for my setup kockoutjs is doing all the templatingi am not too keen on knockoutjs but so far it is been pretty straight forward except for when i start adding in some jquery stuff the problem i am having is jquery is firing before knockout has finished populating the page with all the elements the only solution that is worked for me thus far is all my jquery stuff is wrapped in the settimeout function which obviously is no good whats the most efficient way to make jquery and kockout work together so jquery does not before knockout is done thanks,"['javascript', 'jquery']" +730479,package file is invalid solution from the developer side android i am tired to see a lot of stackoverflow questions about this even in google forums or google official support site publishing solutions that lead to uninstall package through adb to do something with the phone rooted to delete cache of google play services etc ion1espv2ieutf8qandroid20upgrade20download20invalid20package etc is there any solution from the package side i mean i have an app with hundreds of thousands of installs and unfortunately many users are complaining about this error when upgrading from store my new versionobviously i can not go one by one telling they have to do this or that because they are not developers they just want to upgrade and run an app some users are telling me complaining this happened since the last upgrade attempt of my app and they are not experiencing this package file is invalid with any other app in their phones so i guess it is something i can fix with another upgradeis there any solution that i can do in the next apk compilation uploading to google play store and fix this without bothering my users thank you in advance,['android'] +730500,yii2 assets clear cache everytime i update my css or js files in infowebmenumoduleassets i have to empty the backendwebassets folderis there a way to automatically clear the assets cache,['php'] +730637,what is the difference between char and character in java i need to know what is the difference between char and character in java because when i was making a java program the char worked while the character did not work,['java'] +730698,code coverage for jest is there a way to have code coverage in the javascript jest testing framework that is built on top of jasminethe internal framework does not print out the code coverage it gets i have also tried using istanbul blanket and jscover but none of them work,['javascript'] +730741,how to detect an android phone contacts app supports structured postal address samsung galaxy s4 and some devices are only supporting structured postal while using intent action insertarraylistcontentvalues data new arraylistcontentvaluescontentvalues name new contentvaluesnameputdatamimetype structuredpostalcontent item typenameputstructuredpostalstreet bundlegetstringstructuredpostalstreetnameputstructuredpostalcity bundlegetstringstructuredpostalcitynameputstructuredpostalregion bundlegetstringstructuredpostalregionnameputstructuredpostalneighborhood bundlegetstringstructuredpostalneighborhoodnameputstructuredpostalpostcode bundlegetstringstructuredpostalpostcodenameputstructuredpostalcountry bundlegetstringstructuredpostalcountrydataaddnameintent intent new intentintentaction insert contactscontractcontactscontent uriintentputextracontactscontractintentsinsertname contactnameifandroidosbuildversionsdk int androidosbuildversion codeshoneycomb intentputparcelablearraylistextrainsertdata dataelse intentputextracontactscontractintentsinsertpostal addressnow for galaxy s3 which runs on 42 does not support structured address and not showing the address using the above codeso how do i find if a device supports structured postal address so that i can provide support for bothnote if i use intentputextracontactscontractintentsinsertpostal address galaxy s3 shows the address where as while using intentputparcelablearraylistextrainsertdata data this s3 not able to show the address,['android'] +730834,why am i getting a 401 unauthorized error in maven why am i getting a 401 unauthorized error in mavenheres the error i am getting when calling mvn deploy full logs at the bottominfo build failureerror failed to execute goal orgapachemavenpluginsmavendeployplugin27deploy defaultdeploy on project xbnjava failed to deploy artifacts could not transfer artifact comgithubaliteralmindxbnjavapom012 fromto sonatypenexusstaging failed to transfer file return code is 401 reasonphrase unauthorized help 1according to this sonatype support pageif you are receiving a 401 it is because maven is sending the wrong login credentials or no credentials at allbelow are the steps i have taken below that are my full settingsxml and pomxml files and below that are the full logs from mvn deploy and mvn deploy eany ideas would be appreciated i am just hitting wall after wall with maveni followed sonatypes checklist when receiving a 401 errorchecklist item 1 make sure your usernamepassword is correct by logging into the nexus ui if curl is installed on your machine you can try deploying an artifact withi successfully logged in and out of the sonatypeorg website using the userpass in settingsxmli attempted to use curl to manually deploy an artifact with the commandccurl u my sonatype dot com usernamemy sonatype dot com password request put data pomxmlbut got this errorwarning could not read data from file pomxml this makes an empty postcurl 60 ssl certificate problem verify that the ca cert is ok detailserror14090086ssl routinesl3 get server certificatecertificate verify failedmore details here curl performs ssl certificate verification by default using a bundle of certificate authority ca public keys ca certs if the default bundle file is not adequate you can specify an alternate file using the cacert optionif this https server uses a certificate signed by a ca represented in the bundle the certificate verification probably failed due to a problem with the certificate it might be expired or the name might not match the domain name in the urlif youd like to turn off curls verification of the certificate use the k or insecure optioni ran it again with the k option and this time got only thiscould not read data from file pomxml this makes an empty posti have never used curl before so i am at a loss on what to do with this informationchecklist item 2 if there is no error output ensure your user privileges are correctly configured on the server make sure to drop the repo you just createdi do not know what drop means i believe my privileges are properly installed as i received this message from sonatypeconfiguration has been prepared now you candeploy snapshot artifacts into repository deploy release artifacts into the staging repository promote staged artifacts into repository releasesdownload snapshot and release artifacts from group download snapshot release and staged artifacts from staging group and i have successfully put these items onto the server via mvn deploy in the past couple daysthe projects settingschecklist item 3 make sure you have configured a server in settingsxml and that the server id is identical to the thistribution repository id in pomxmlin settingsxml settingsserversserverid equals ossrhin pomxml thistributionmanagementsnapshotrepositoryid equals ossrhfull files are at the bottomchecklist item 4 make sure your settingsxml is in the correct place normally itas m2settingsxml you can check this by running mvn helpeffectivesettingsaccording to mavens settings reference settingsxml must be in one of two locationsthe maven install m2 homeconfsettingsxmla useras install userhomem2settingsxmlheres my setupsettingsxml capplicationsprogrammingapachemaven322confsettingsxmlm2 home is capplicationsprogrammingapachemaven322output for mvn helpeffectivesettingscapplicationsutilitiescurlinfo scanning for projectsinfoinfo info building maven stub project no pom 1info infoinfo mavenhelpplugin22effectivesettings defaultcli standalonepom infoeffective userspecific configuration settingsxml version10 encodingutf8 generated by maven help plugin on 20140718t124819 see effective settings for jeffy on kermitthefrog settings xmlns xmlnsxsi xsischemalocation localrepository xmlnscusersjeffym2repositorylocalrepository servers xmlns server usernamemy sonatype dot com usernameusername passwordpassword idossrhid server servers plugingroups xmlns plugingrouporgapachemavenpluginsplugingroup plugingrouporgcodehausmojoplugingroup plugingroupssettingsinfo info build successinfo info total time 2310 sinfo finished at 20140718t1248190400info final memory 7m17minfo checklist item 5 if the server is using https but the url in your pom is http you might get 401 as welli do not understand which url it is referring tochecklist item 6 use the latest version of maven as there is a known issue regarding 401 mng4469i am using the latest versioncmvn versionapache maven 322 45f7c06d68e745d05611f7fd14efb6594181933e 20140617t0951420400maven home capplicationsprogrammingapachemaven322java version 170 51 vendor oracle corporationjava home capplicationsprogrammingjdk 7 51jredefault locale en us platform encoding cp1252os name windows 7 version 61 arch x86 family windowsfull settingsxml and pomxml filesfull logs for mvn deploy and mvn deploy e belowsettingsxmlxml version10 encodingutf8settings xmlns xmlnsxsi xsischemalocation servers server idossrhid usernamemy sonatype dot com usernameusername passwordmy sonatype dot com passwordpassword server servers plugingroupsplugingroups proxiesproxies mirrorsmirrors profilesprofilessettingspomxmlproject xmlns xmlnsxsi xsischemalocation 0 0xsd modelversion400modelversion groupidcomgithubaliteralmindgroupid artifactidxbnjavaartifactid packagingpompackaging version012version namexbnjavaname urlurl inceptionyear2014inceptionyear organization namejeff epsteinname organization descriptionxbnjava is a collection of genericallyuseful backend server side nongui programming utilities featuring regexreplacer and filteredlineiterator xbnjava is the foundation of codelet description parent groupidorgsonatypeossgroupid artifactidossparentartifactid version7version parent licenses license namelesser general public license lgpl version 30name urlurl license license nameapache software license asl version 20name urlurl license licenses developers developer namejeff epsteinname emailemail roles rolelead developerrole roles developer developers issuemanagement systemgithub issue trackersystem urlurl issuemanagement thistributionmanagement snapshotrepository idossrhid urlurl snapshotrepository thistributionmanagement scm connectionscmgitaliteralmindxbnjavagitconnection urlscmgitaliteralmindxbnjavagiturl developerconnectionscmgitaliteralmindxbnjavagitdeveloperconnection scm properties javaversion17javaversion jarprefixrjeffyprogrammingbuildprojectartifactidprojectversiondownloadprojectartifactidprojectversionjarprefix properties profiles profile iddefaulttoolsjarid activation property namejavavendorname valuesun microsystems incvalue property activation dependencies dependency groupidcomsungroupid artifactidtoolsartifactid version142version scopesystemscope systempathjavahomelibtoolsjarsystempath dependency dependencies profile profiles build plugins plugin groupidorgcodehausmojogroupid artifactidbuildhelpermavenpluginartifactid version18version executions execution idattachartifactsid phasepackagephase goals goalattachartifactgoal goals configuration artifacts artifact filejarprefixalljarfile typejartype artifact artifacts configuration execution executions plugin plugins build profiles this profile will sign the jar file sources file and javadocs file using the gpg key on the local machine see profile idreleasesignartifactsid activation property namereleasename valuetruevalue property activation profile profilesprojectfull logs for mvn deploy and mvn deploy emvn deploy outputinfo scanning for projectsinfo info building xbnjava 012info info mavenenforcerplugin10enforce enforcemaven xbnjava info buildhelpermavenplugin18attachartifact attachartifacts xbnjava info maveninstallplugin24install defaultinstall xbnjava info installing rjeffyprogrammingsandboxz for git commit onlyxbnjavapomxml to cusersjeffym2repositorycomgithubaliteralmindxbnjava012xbnjava012pominfo installing rjeffyprogrammingbuildxbnjava012downloadxbnjava012alljar to cusersjeffym2repositorycomgithubaliteralmindxbnjava012xbnjava012jarinfo mavendeployplugin27deploy defaultdeploy xbnjava uploading 26 kb46 kb66 kbfailure sectioninfo info build failureinfo info total time 3204 sinfo finished at 20140718t1125170400info final memory 7m17minfo error failed to execute goal orgapachemavenpluginsmavendeployplugin27deploy defaultdeploy on project xbnjava failed to deploy artifacts could not transfer artifact comgithubaliteralmindxbnjavapom012 fromto sonatypenexusstaging failed to transfer file return code is 401 reasonphrase unauthorized help 1errorerror to see the full stack trace of the errors rerun maven with the e switcherror rerun maven using the x switch to enable full debug loggingerrorerror for more information about the errors and possible solutions please read the following articleserror help 1 mvn deploy e outputinfo error stacktraces are turned oninfo scanning for projectsinfo info building xbnjava 012info info mavenenforcerplugin10enforce enforcemaven xbnjava info buildhelpermavenplugin18attachartifact attachartifacts xbnjava info maveninstallplugin24install defaultinstall xbnjava info installing rjeffyprogrammingsandboxz for git commit onlyxbnjavapomxml to cusersjeffym2repositorycomgithubaliteralmindxbnjava012xbnjava012pominfo installing rjeffyprogrammingbuildxbnjava012downloadxbnjava012alljar to cusersjeffym2repositorycomgithubaliteralmindxbnjava012xbnjava012jarinfo mavendeployplugin27deploy defaultdeploy xbnjava uploading 26 kb46 kb66 kbfailure sectioninfo info build failureinfo info total time 3492 sinfo finished at 20140718t1125370400info final memory 7m17minfo error failed to execute goal orgapachemavenpluginsmavendeployplugin27deploy defaultdeploy on project xbnjava failed to deploy artifacts could not transfer artifact comgithubaliteralmindxbnjavapom012 fromto sonatypenexusstaging failed to transfer file return code is 401 reasonphrase unauthorized help 1orgapachemavenlifecyclelifecycleexecutionexception failed to execute goal orgapachemavenpluginsmavendeployplugin27deploy defaultdeploy on project xbnjava failed to deploy artifacts could not transfer artifact comgithubaliteralmindxbnjavapom012 fromto sonatypenexusstaging failed to transfer file return code is 401 reasonphrase unauthorized at orgapachemavenlifecycleinternalmojoexecutorexecutemojoexecutorjava216 at orgapachemavenlifecycleinternalmojoexecutorexecutemojoexecutorjava153 at orgapachemavenlifecycleinternalmojoexecutorexecutemojoexecutorjava145 at orgapachemavenlifecycleinternallifecyclemodulebuilderbuildprojectlifecyclemodulebuilderjava116 at orgapachemavenlifecycleinternallifecyclemodulebuilderbuildprojectlifecyclemodulebuilderjava80 at orgapachemavenlifecycleinternalbuildersinglethreadedsinglethreadedbuilderbuildsinglethreadedbuilderjava51 at orgapachemavenlifecycleinternallifecyclestarterexecutelifecyclestarterjava120 at orgapachemavendefaultmavendoexecutedefaultmavenjava347 at orgapachemavendefaultmavenexecutedefaultmavenjava154 at orgapachemavenclimavencliexecutemavenclijava584 at orgapachemavenclimavenclidomainmavenclijava213 at orgapachemavenclimavenclimainmavenclijava157 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava57 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43 at javalangreflectmethodinvokemethodjava606 at orgcodehausplexusclassworldslauncherlauncherlaunchenhancedlauncherjava289 at orgcodehausplexusclassworldslauncherlauncherlaunchlauncherjava229 at orgcodehausplexusclassworldslauncherlaunchermainwithexitcodelauncherjava415 at orgcodehausplexusclassworldslauncherlaunchermainlauncherjava356caused by orgapachemavenpluginmojoexecutionexception failed to deploy artifacts could not transfer artifact comgithubaliteralmindxbnjavapom012 fromto sonatypenexusstaging failed to transfer file return code is 401 reasonphrase unauthorized at orgapachemavenplugindeploydeploymojoexecutedeploymojojava193 at orgapachemavenplugindefaultbuildpluginmanagerexecutemojodefaultbuildpluginmanagerjava132 at orgapachemavenlifecycleinternalmojoexecutorexecutemojoexecutorjava208 19 morecaused by orgapachemavenartifactdeployerartifactdeploymentexception failed to deploy artifacts could not transfer artifact comgithubaliteralmindxbnjavapom012 fromto sonatypenexusstaging failed to transfer file return code is 401 reasonphrase unauthorized at orgapachemavenartifactdeployerdefaultartifactdeployerdeploydefaultartifactdeployerjava143 at orgapachemavenplugindeployabstractdeploymojodeployabstractdeploymojojava167 at orgapachemavenplugindeploydeploymojoexecutedeploymojojava149 21 morecaused by orgeclipseaetherdeploymentdeploymentexception failed to deploy artifacts could not transfer artifact comgithubaliteralmindxbnjavapom012 fromto sonatypenexusstaging failed to transfer file return code is 401 reasonphrase unauthorized at orgeclipseaetherinternalimpldefaultdeployerdeploydefaultdeployerjava337 at orgeclipseaetherinternalimpldefaultdeployerdeploydefaultdeployerjava268 at orgeclipseaetherinternalimpldefaultrepositorysystemdeploydefaultrepositorysystemjava413 at orgapachemavenartifactdeployerdefaultartifactdeployerdeploydefaultartifactdeployerjava139 23 morecaused by orgeclipseaethertransferartifacttransferexception could not transfer artifact comgithubaliteralmindxbnjavapom012 fromto sonatypenexusstaging failed to transfer file return code is 401 reasonphrase unauthorized at orgeclipseaetherconnectorwagonwagonrepositoryconnector6wrapwagonrepositoryconnectorjava1016 at orgeclipseaetherconnectorwagonwagonrepositoryconnector6wrapwagonrepositoryconnectorjava1004 at orgeclipseaetherconnectorwagonwagonrepositoryconnectorputtaskrunwagonrepositoryconnectorjava895 at orgeclipseaetherconnectorwagonwagonrepositoryconnectorputwagonrepositoryconnectorjava522 at orgeclipseaetherinternalimpldefaultdeployerdeploydefaultdeployerjava331 26 morecaused by orgapachemavenwagontransferfailedexception failed to transfer file return code is 401 reasonphrase unauthorized at orgapachemavenwagonprovidershttpabstracthttpclientwagonputabstracthttpclientwagonjava573 at orgapachemavenwagonprovidershttpabstracthttpclientwagonputabstracthttpclientwagonjava493 at orgapachemavenwagonprovidershttpabstracthttpclientwagonputabstracthttpclientwagonjava474 at orgapachemavenwagonprovidershttpabstracthttpclientwagonputabstracthttpclientwagonjava454 at orgeclipseaetherconnectorwagonwagonrepositoryconnectorputtaskrunwagonrepositoryconnectorjava871 28 moreerrorerror rerun maven using the x switch to enable full debug loggingerrorerror for more information about the errors and possible solutions please read the following articleserror help 1,['java'] +730847,change color of text when button is pushed i know how to change the background color but what about the actual text there does not seem to be a member on a uibutton called color or anything like that my codeibaction func yellowbtnclickedsender uibutton gameboardimage uiimagenamed yellow gb resultsviewimage uiimagenamed yellow results colorsviewimage uiimagenamed yellow colors colorsbtncolor uicolorbrowncolor this line has the issue,['ios'] +730857,lockfree stack is this a correct usage of c11 relaxed atomics can it be proven i have written a container for a very simple piece of data that needs to be synchronized across threads i want the top performance i do not want to use locksi want to use relaxed atomics partly for that little bit of extra oomph and partly to really understand themi have been working on this a lot and i am at the point where this code passes all tests i throw at it that is not quite proof though and so i am wondering if there is anything i am missing or any other ways i can test thisheres my premiseit is only important that a node be properly pushed and popped and that the stack can never be invalidated i believe that the order of operations in memory is only important in one placebetween the compare exchange operations themselves this is guaranteed even with relaxed atomicsthe aba problem is solved by adding identification numbers to the pointers on 32 bit systems this requires a doubleword compare exchange and on 64 bit systems the unused 16 bits of the pointer are filled with id numberstherefore the stack will always be in a valid state rightheres what i am thinking normally the way we reason about code that were reading is to look at the order in which it is written memory can be read or written to out of order but not in a way that invalidates the correctness of the programthat changes in a multithreaded environment that is what memory fences are for so that we can still look at the code and be able to reason about how it is going to workso if everything can go all outoforder here what am i doing with relaxed atomics is not that a bit too fari do not think so but that is why i am here asking for helpthe compare exchange operations themselves give a guarantee of sequential constancy with each otherthe only other time there is read or write to an atomic is to get the heads initial value before a compare exchange it is set as part of the initialization of a variable as far as i can tell it would be irrelevant whether or not this operation brings back a proper valuecurrent codestruct node node n if processor bits 64 inline constexpr node and nullptr inline constexpr nodenode n and and inline void tagconst stack tag t t reinterpret caststack tag tthis3 t inline stack tag t read tag return reinterpret caststack tag tthis3 inline void clear pointer tag0 elif processor bits 32 stack tag t t inline constexpr node and nullptr t 0 inline constexpr nodenode n and and t 0 inline void tagconst stack tag t t t t inline stack tag t read tag return t inline void clear pointer endif inline void setnode n const stack tag t t and n tagt using stdmemory order relaxedclass stackpublic constexpr stack head void pushnode n node nextn headhead loadmemory order relaxed do nn headn nexttagheadread tag 1 while head compare exchange weakhead next memory order relaxed memory order relaxed bool popnode n node clean next headhead loadmemory order relaxed do cleansetheadn 0 if cleann return false nextsetcleann n headread tag 1 while head compare exchange weakhead next memory order relaxed memory order relaxed and cleann return true protected stdatomicnode head whats different about this question compared to others relaxed atomics they make a big difference to the questionso what do you think is there anything i am missing,['c++'] +731024,error googleplayservicesutili1 internal error occurred please see logs for detailed information how do i fix this i have spent countless hours trying to figure out this google drive android api and i have frustrated myself to the core trying to figure out how exactly to use it i am using the getting started link on the google android developers website and this is what i have donepackage vivainspectioncominspectionpickerimport androidappactivityimport androidcontentcontextimport androidcontentintentimport androidcontentintentsenderimport androidosbundleimport androidutillogimport androidviewmenuimport androidviewmenuitemimport androidviewviewimport androidwidgetadapterviewimport androidwidgetarrayadapterimport androidwidgetbuttonimport androidwidgetspinnerimport comgoogleandroidgmscommonconnectionresultimport comgoogleandroidgmscommongoogleplayservicesutilimport comgoogleandroidgmscommonapigoogleapiclientimport comgoogleandroidgmsdrivedriveimport comgoogleandroidgmscommonapiresultcallbackimport comgoogleandroidgmsdrivedriveimport comgoogleandroidgmsdrivedriveapicontentsresultimport comgoogleandroidgmsdrivedriveidimport comgoogleandroidgmsdrivemetadatachangesetimport comgoogleandroidgmsdriveopenfileactivitybuilderimport comgoogleandroidgmscommonapiresultcallbackimport comgoogleandroidgmsdrivedriveimport comgoogleandroidgmsdrivedriveapicontentsresultimport comgoogleandroidgmsdrivedriveidimport comgoogleandroidgmsdrivemetadatachangesetimport comgoogleandroidgmsdriveopenfileactivitybuilderimport javalangreflectarrayimport javautilarraylistimport javautilarraysimport javautillistimport javautilloggingloggerimport vivainspectioncominspectionpickermultispinnerpublic class myactivity extends activity implements multispinnermultispinnerlistener adapterviewonitemselectedlistener googleapiclientconnectioncallbacks googleapiclientonconnectionfailedlistener googleapiclient mgoogleapiclient final private static int resolve connection request code 1 override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity my button save button findviewbyidridsave array for the tasks multispinner string array getresourcesgetstringarrayrarrayrooms array liststring rooms new arrayliststringarraysaslistarray create an arrayadapter using the string array and a default spinner layout final spinner roomspinner spinner findviewbyidridrooms spinner itemsspinner spinner findviewbyidridinspectionitems arrayadaptercharsequence adapter arrayadaptercreatefromresourcethis rarrayrooms array androidrlayoutsimple spinner item specify the layout to use when the list of choices appears adaptersetdropdownviewresourceandroidrlayoutsimple spinner dropdown item apply the adapter to the spinner roomspinnersetadapter new nothingselectedspinneradapter adapter rlayoutcontact spinner row nothing selected rlayoutcontact spinner nothing selected dropdown optional this roomspinnersetonitemselectedlistenerthis itemsspinnersetonitemselectedlistenerthis final multispinner multispinner multispinner findviewbyidridmulti spinner multispinnersetitemsrooms choose one this mgoogleapiclient new googleapiclientbuilderthis addapidriveapi addscopedrivescope file addconnectioncallbacksthis addonconnectionfailedlistenerthis build savesetonclicklistenernew viewonclicklistener override public void onclickview view intent intent new intentmyactivitythis listactivityclass intentputextranew value roomspinnergetselecteditemtostring startactivityintent override protected void onstart superonstart mgoogleapiclientconnect override public void onconnectionfailedconnectionresult connectionresult if connectionresulthasresolution try connectionresultstartresolutionforresultthis resolve connection request code catch intentsendersendintentexception e unable to resolve message user appropriately else googleplayservicesutilgeterrordialogconnectionresultgeterrorcode this 0show override public void onconnectedbundle bundle drivedriveapinewcontentsmgoogleapiclient setresultcallbackcontentscallback override public void onconnectionsuspendedint i override protected void onactivityresultfinal int requestcode final int resultcode final intent data switch requestcode case resolve connection request code if resultcode result ok mgoogleapiclientconnect driveid driveid driveid datagetparcelableextra openfileactivitybuilderextra response drive id break resultcallbackcontentsresult contentscallback new resultcallbackcontentsresult override public void onresultcontentsresult result if resultgetstatusissuccess handle error return metadatachangeset metadatachangeset new metadatachangesetbuilder setmimetypetexthtmlbuild intentsender intentsender drivedriveapi newcreatefileactivitybuilder setinitialmetadatametadatachangeset setinitialcontentsresultgetcontents buildmgoogleapiclient try startintentsenderforresultintentsender 1 null 0 0 0 catch intentsendersendintentexception e handle the exception this is my manifest and i have no idea how the manifest should look likexml version10 encodingutf8manifest xmlnsandroid packagevivainspectioncominspectionpicker usespermission androidnameandroidpermissionget accounts application androidallowbackuptrue androidicondrawableic launcher androidlabelstringapp name androidthemestyleapptheme metadata androidnamecomgoogleandroidgmsversion androidvalueintegergoogle play services version activity androidnamelistactivity androidlabelstringapp name androidscreenorientationportrait intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity activity androidnamemyactivity androidlabelmyactivity androidexportedtrue intentfilter action androidnamecomgoogleandroidappsdrivedrive open data androidmimetypeapplicationvndgoogleappsdrivesdk1234567890 data androidmimetypeimagepng data androidmimetypeimagejpeg data androidmimetypeimagejpg intentfilter activity activity androidnameinitialchoose androidlabelstringtitle activity initial choose androidwindowsoftinputmodestatehidden activity applicationmanifestwhen i run the app a dialog box appears that states unknown issue with google play services and then in log cat this appearserror googleplayservicesutili1 internal error occurred please see logs for detailed information but there is nothing in the logs so again i am completely confused i have looked at other questions and i have indeed set up my app with the developer console as per the instructions in the getting started link abovei really need help thanks in advance,['android'] +731092,textrendering in css what is it and how to use it i was reading an article on textrendering in cssaccording to that blogthe textrendering property in css allows you to choose quality of text over speed or vice versa allowing you to fine tune optimization by suggesting to the browser as to how it should render text on the screen it provides information to the rendering engine about what to optimize for when rendering text the browser makes tradeoffs among speed legibility and geometric precisionalso it is useful now for optimization purposes for decreasing page load time as mentioned therebut some terms confused me while reading that article and i thought experts here will elaborate those terms for better understanding so here are those termswhat is meant by rendering how it is done with regard to csswhat is legibilitycan anyone please differ in between optimizelegibility and optimizespeed how and where each of them or both should be used also except ie every browser supports this property so simply 810 of world will have no problem using it thats why i am asking this question in order to clear the understanding of these concepts,"['html', 'css']" +731137,spring boot responsebody does not serialize entity id have a strange problem and cannot figure out how to deal with it have simple pojoentitytablename personspublic class person id generatedvalue private long id columnname first name private string firstname columnname middle name private string middlename columnname last name private string lastname columnname comment private string comment columnname created private date created columnname updated private date updated prepersist protected void oncreate created new date preupdate protected void onupdate updated new date valid orderbyid onetomanymappedby person fetch fetchtypeeager cascade cascadetypeall orphanremoval true private listphonenumber phonenumbers new arraylist public long getid return id public void setidlong id thisid id public string getfirstname return firstname public void setfirstnamestring firstname thisfirstname firstname public string getmiddlename return middlename public void setmiddlenamestring middlename thismiddlename middlename public string getlastname return lastname public void setlastnamestring lastname thislastname lastname public string getcomment return comment public void setcommentstring comment thiscomment comment public date getcreated return created public date getupdated return updated public listphonenumber getphonenumbers return phonenumbers public void addphonenumberphonenumber number numbersetpersonthis phonenumbersaddnumber override public string tostring return tostringbuilderreflectiontostringthis tostringstyleshort prefix style entitytablename phone numberspublic class phonenumber public phonenumber public phonenumberstring phonenumber thisphonenumber phonenumber id generatedvalue private long id columnname phone number private string phonenumber manytoone joincolumnname person id private person person public long getid return id public void setidlong id thisid id public string getphonenumber return phonenumber public void setphonenumberstring phonenumber thisphonenumber phonenumber public person getperson return person public void setpersonperson person thisperson person override public string tostring return tostringbuilderreflectiontostringthis tostringstyleshort prefix style and rest endpointresponsebodyrequestmappingmethod requestmethodgetpublic listperson listpersons return personservicefindallin json response there are all fields except id which i need on front end side to editdelete person how can i configure spring boot to serialize id as well that is how response looks like now firstname just middlename test lastname name comment just a comment created 1405774380410 updated null phonenumbers phonenumber 74575754757 phonenumber 575757547 phonenumber 57547547547 upd have bidirectional hibernate mapping maybe it is somehow related to issue,['java'] +731149,forcing c99 in cmake to use for loop initial declaration i have been searching a portable way to force cmake to enable the compilers c99 features in order to avoid the following gcc error for instanceerror afora loop initial declarations are only allowed in c99 modefor int s 1 s in parastepnumber si also wouldnt like to check for which compiler and append something likesetcmake c flags stdc99 that would be badso i found this post enabling c99 in cmake and the associated feature request 0012300 cmake has no crossplatform way to ask for c99 in this mantis bug i learned about target compiler features and after that i found these sof answers on it how to activate c11 in cmake and how to detect c11 support of a compiler with cmakeso my questions are this target compiler features will provide a way to require a c feature as well as a c one what is the most portable way to achive this by now i am currently using cmake 28122 the target compiler features is not in cmakes most recent release version 300 do you know when it is being released,"['c++', 'c']" +731209,wtext returning strange value in unity3d c i am using unity 3ds w to make http requests it seems that no matter what kind of data i am trying to access it just returns i12i12i12i12 every time i have tried json files i have tried php that just generates a string i cannot seem to access the values on the servercpublic string url ienumerator start w w new wurl yield return w if stringisnulloremptywerror debuglogwerror else debuglogwtext phpphp echo textinessnotei have used wtexture successfully to pull images off of the server however wtext does not seem to be working,['c#'] +731247,reactive extensions subscribe calling await i want to perform an async call based for each event raised by a reactive extensions observable i am also trying to keep everything synchronized as i want the async call to finish before the next event is handledhow would one go about doing something similar to the following i say similar as the code below does not compilesettingschangedinmemory subscribeasync var settings extract await savesettingssettings i am not sure if it changes anything but i would need to subscribe to multiple observables for example another subscription like thissettingschangedonthisk subscribeasync var settings await readsettingssettings applysettings how would you use reactive extensions to do this,['c#'] +731256,how to generate a dictionary with autofixture for a list we can do fixturecreatemanyliststring10 with 10 elementsbut how to do it with a dictionary and to be able to specify the number of elements to be generated,['c#'] +731299,web api modelbinding from uri so i have a custom model binder implemented for datetime type and i register it like belowvoid application startobject sender eventargs e code that runs on application startup globalconfigurationconfigurationbindparametertypeofdatetime new currentculturedatetimeapiand then i have setup 2 sample actions to see if my custom model binding takes place httpget public void binddatetimefromuridatetime datetime httplocalhost26171webapibinddatetimedatetime09122014 httpget public void bindmodelfromuriuser user httplocalhost26171webapibindmodelnameibrahimjoindate09122014 when i run and invoke both actions from mentioned urls users joindate property successfully gets bound using the custom binder i configured but binddatetimes datetime parameter does not get bound using the custom binderi have already specified in config that all datetime should use my custom binder then why the indifference suggestions are highly appreciatedcurrentculturedatetimeapicspublic class currentculturedatetimeapi imodelbinder public bool bindmodelhttpactioncontext actioncontext modelbindingcontext bindingcontext var value bindingcontextvalueprovidergetvaluebindingcontextmodelname var date valueconverttotypeofdatetime cultureinfocurrentculture bindingcontextmodel date return true note if i use fromuribindertypeofcurrentculturedatetimeapidatetime datetime then it works as expected but then again why,['c#'] +731307,how to print types of unknown size like ino t i often experience situations where i want to print with printf the value of an integer type of implementationdefined size like ino t or time t right now i use a pattern like this for thisinclude inttypeshino t ino variable of unknown size printf priumax uintmax tinothis approach works so far but it has a couple of thisadvantagesi have to know whether the type i am trying print is signed or unsignedi have to use a type cast that possibly enlarges my codeis there a better strategy,['c'] +731338,minsdk devicesdk hi guys just recently started getting into android development i feel this is a very stupid question but i will shoot anyway since i have spent an hour on this already i am currently trying to run a project on my device with no changes to what android studio gave me i think this image should describe my problem betterwhen running i get failure install failed older sdki cannot understand why they are not compatible rather why does minsdk say api 20 when minsdkversion on buildgradle says 15 i have tried adding usessdk on manifestxml but i figured that would be unnecessary since my buildgradle file will overwrite that it did not work also am i missing some kind of setting here,['android'] +731497,which of these compilers has a bug according to the standard given the following source codeinclude memoryinclude iostreamusing namespace stdstruct concept virtual void perform 0struct model concept enable shared from thismodel void perform override cout my pointer is shared from thisget endl int mainint argc const char argv shared ptrconcept concept ptr make sharedmodel shared ptrconcept concept ptr new model concept ptrperform return 0compiling under gcc this code compiles and associates the internal weak ptr with the address of modelunder clang the code will not compile error message included at the endif you replace the initialisation of concept ptr with shared ptrconcept concept ptr make sharedmodel it will compile on bothwhich is correcteditmy version of clang is the one that ships with xcode clang versionapple llvm version 51 clang503040 based on llvm 34svntarget x86 64appledarwin1330thread model posixedit2just wanted to say thanks to everyone for contributing if youre interested the reason i want to do this is that i want an opaque interface to an implementation with sharedhandle semantics some implementations async ones require that callback objects ensure that the implementation object still exists argues for shared from this and weak ptrlock other implementations do not require this i wanted to avoid encumbering the concept public interface with the enable shared from this base class since that couples implementation with interface a known evilin most cases it is reasonable to use make shared to create the implementation object in rarer cases that require a custom destructor the following seems portable auto concept ptr static pointer castconceptshared ptrmodel new model model self some deletion operation on self appendixerror message on clangin file included from usersrichardhdocumentsdevscratchpadtryittryittry2cpp1applicationsxcodeappcontentsdevelopertoolchainsxcodedefaultxctoolchainusrbinlibcv1memory401335 error no viable overloaded e weak this this etc,['c++'] +731499,is it ok to use dictionaries when i do not need to quickly access their values normally i use a dictionary like a list but with a key of a different type i like the ability to quickly access individual items in the dictionary without having to loop through it until i find the item with the right property because the property i am looking for is in the keybut there is another possible use of a dictionary i could just use the key to store property a and the value to store property b without ever using the dictionarys special functionality for example i could store a list of persons just by storing the forename in the key and the family name in the value let us assume for the sake of simplicity that there would not ever be two people with the same forename because i just could not come up with an better example i would only use that dictionary to loop through it in a foreach loop and add items to it no removing sorting or accessing individual items there would actually be no difference to using a listkeyvaluepairstring string from using a dictionarystring string at least not in the example that i gave i know that i could e g store multiple items wiht the same key in the listso to sum it up what should i do when i do not need to use the special functionalities a dictionary provides and just use it to store something that has exactly two propertiesuse a dictionaryuse a listkeyvaluepairuse a listmytype with mytype being a custom class that contains the two properties and a constructor,['c#'] +731511,adminlte collapsed boxes by default adminlte is based on bootstrap live preview but i am unsure as to how to make the collapsable boxes collapsed by defaulti am assuming since it is built on bootstrap this should be rather straightforward i have tried fellow implementations such as setting the id to collapsedone and attempting to treat the divs as accordions but to no availon the adminlteappjs line 45 there is code that implements slide upslide down to collapse boxes ideally what wed want is to have the boxes be in the slide up state by default with the class collapsedbox so that when the icon is clicked it executes slide down add collapse and remove events to boxes datawidgetcollapseclickfunction find the box parent var box thisparentsboxfirst find the body and the footer var bf boxfindboxbody boxfooter if boxhasclasscollapsedbox boxaddclasscollapsedbox bfslideup else boxremoveclasscollapsedbox bfslidedown any suggestionsthanks in advance,"['html', 'css']" +731612,how to tell if a c template type is cstyle string i am trying to write a template is c str to test if a type is a cstyle string i need this as an attempt to write a to string function as shown in my other question herehow to write template specialization for iterators of stl containers i need to tell apart c str and other types of pointers and iterators so that i can represent the first at the face value and render pointersiterators as an opaque itor or ptr the code is as followsinclude iostreamtemplateclass tstruct is c str stdintegral constant bool stdis samechar typename stdremove referencetypename stdremove cvttypetypevalue int main auto sz hello or const char sz hello int i double d stdcout is c strdecltypeszvalue is c strdecltypeivalue is c strdecltypedvalue stdendlhowever is c str captures not only const char but also int and double the above code outputs1 1 1as of gcc481my question is how to fix is c str to properly capture cstyle strings,['c++'] +731618,intellij android ui rendering problems missing library after much headbashing i seem to have got my first hello world app running within intellij ultimate i downloaded the lastest ultimate edition today when i try and open the mainxml in the ui designer i get the error below can anyone help i liked the look of the ui designer from the videos that intellij provider here thanks in advancethis version of the rendering library is more recent than your version of intellij idea please update intellij ideaorgjetbrainsandroiduipreviewrenderingexception this version of the rendering library is more recent than your version of intellij idea please update intellij ideaat orgjetbrainsandroiduipreviewlayoutlibraryloaderloadlayoutlibraryloaderjava90at orgjetbrainsandroidsdkandroidtargetdatagetlayoutlibraryandroidtargetdatajava149at comandroidtoolsidearenderingrenderservicecreaterenderservicejava167at comintellijandroiddesignerdesignsurfaceandroiddesignereditorpanel6runandroiddesignereditorpaneljava485at comintellijutiluiupdatemergingupdatequeueexecutemergingupdatequeuejava320at comintellijutiluiupdatemergingupdatequeueexecutemergingupdatequeuejava310at comintellijutiluiupdatemergingupdatequeue2runmergingupdatequeuejava254at comintellijutiluiupdatemergingupdatequeueflushmergingupdatequeuejava269at comintellijutiluiupdatemergingupdatequeueflushmergingupdatequeuejava227at comintellijutiluiupdatemergingupdatequeuerunmergingupdatequeuejava217at comintellijutilconcurrencyqueueprocessorrunsafelyqueueprocessorjava238at comintellijutilalarmrequest1runalarmjava327at javautilconcurrentexecutorsrunnableadaptercallexecutorsjava471at javautilconcurrentfuturetaskrunfuturetaskjava262at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava1145at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava615at javalangthreadrunthreadjava724,['android'] +731715,how to control listview with mvp pattern for android i am currently developing an android app using mvp patternwhen i try to develop an activity i should use a listview so i am using adapter for listview but i heard adapter is similar to presenter on mvp patterni think if apdater is smiliar to presenter then i should make presenter for updating listview instead of adapterwhen this situation how to develop listview just use adapter and keep using mvp patternthanks for your reading,['android'] +731731,swift vs objc initialisation process in objectivec we create objects like instancetypeinit return super init here it returns initialised value class obj class allocinit but swift initialiser wont return any valuefrom swift docsunlike objectivec initializers swift initializers do not return a value their primary role is to ensure that new instances of a type are correctly initialized before they are used for the first timeinit superinit let obj classnow how swift initialiser returns the instance to variable obj how the allocation and initialisation occurs in swift,['ios'] +731771,concatenate char literal x vs single char string literal x when i have a string that i need to concatenate a single char to its endshould i prefer s over s for any performance reasoni know array string joining and of string buildersand i am not asking for suggestions on how to concatenate strings in generali also know some of would have the urge to explain to me about premature optimizations and that in general i should not bother with such minor stuff please do not i am asking because from a coding style preference i would prefer to use the laterbut it feels to me that the first one should perform marginally better because knowing that what is being appended is just a single char there is no need for any internal looping going over this single char as there might be when copying a single character stringupdateas scheintod wrote this is indeed a theoretical q and has to do more with my desire to better understand how java works and less with any real life lets save another microsecond scenariomaybe i should have said that more clearlyi like understanding the way things work behind the scenes and i find that it can sometime help me create better codethe truth i was not thinking about compiler optimizations at alli would not have expected the jit to use stringbuilders instead of strings for mebecause i possibly wrongly think of string builders as being heavier then strings on one hand but faster at building and modifying the strings on the other hand so i would assume that in some cases using stringbuilders would be even less efficient then using stings if that was not the case then the entire string class should have had its implementation changed to be such as that of a stringbuilder and use some internal representation for actual immutable strings or is that what the jit is sort of doing assuming that for the general case it would probably be better not to let the developer choose if it does change my code to such a degree then maybe my q should have been at that level asking if its is appropriate for the jit to do something like this and would it be better if it usedmaybe i should start looking at compiled byte code i will need to learn how to do that in java as a side note and example of why i would even consider looking at bytecode have a look at a quite old blog post of mine about optimizing actionscript 20 a bytecode perspective part i it shows that knowing what your code compiles into indeed can help you write better code,['java'] +731817,entity framework 611 thisable model compatibility checking i am running into the following error after updating ef to version 611an unhandled exception of type systeminvalidoperationexception occurred in entityframeworkdlladditional information the model backing the tvstcontext context has changed since the database was created consider using code first migrations to update the database we could fix this in the past as described in this question where is modelbuilderincludemetadataindatabase in ef ctp5however i cannot seem to get rid of the error,['c#'] +731847,spring mvc background process i come from a perl background and am writing my first java mvc web application using springmy webapp allows users to submit orders which the app processes synchronously by calling a thirdparty soap service the next phase of the project is to allow users to submit bulk orders eg a csv containing 500 rows and process them asynchronously here is a snippet of my existing controllercontrollerservicerequestmappingvalue orderspublic class ordercontroller autowired orderservice orderservice requestmappingvaluenew method requestmethodpost public string processnewordermodelattributeorder order order mapstring object map orderstatus orderstatus orderserviceprocessneworderorder mapputorderstatus orderstatus return new i plan to create a new requestmapping to deal with the incoming csv and modify the orderservice to be able to break the csv apart and persist the individual orders to the databasemy question is what is the best approach to creating background workers in an mvc spring app ideally i would have 5 threads processing these orders and most likely from a queue i have read about async or submitting a runnable to a simpleasynctaskexecutor bean and am not sure which way to go some examples would really help me,['java'] +731888,android ls ripple effect touch feedback for buttons using xml i am trying to understand how to implement the ripple effect touch feedback for buttons and other views i looked at the questions related to ripple touch effect on so and got some insight into it i was able to successfully get the ripple effect using this java codeimport androidanimationobjectanimatorimport androidcontentcontextimport androidgraphicscanvasimport androidgraphicscolorimport androidgraphicspaintimport androidgraphicspathimport androidgraphicsradialgradientimport androidgraphicsregionimport androidgraphicsshaderimport androidsupportannotationnonnullimport androidutilattributesetimport androidviewmotioneventimport androidviewanimationaccelerateinterpolatorimport androidwidgetbuttonpublic class mybutton extends button private float mdownx private float mdowny private float mradius private paint mpaint public mybuttonfinal context context supercontext init public mybuttonfinal context context final attributeset attrs supercontext attrs init public mybuttonfinal context context final attributeset attrs final int defstyle supercontext attrs defstyle init private void init mpaint new paint mpaintsetalpha100 override public boolean ontoucheventnonnull final motionevent event if eventgetactionmasked motioneventaction up mdownx eventgetx mdowny eventgety objectanimator animator objectanimatoroffloatthis radius 0 getwidth 30f animatorsetinterpolatornew accelerateinterpolator animatorsetduration400 animatorstart return superontoucheventevent public void setradiusfinal float radius mradius radius if mradius 0 radialgradient radialgradient new radialgradientmdownx mdowny mradius 3 colortransparent colorblack shadertilemodemirror mpaintsetshaderradialgradient invalidate private path mpath new path private path mpath2 new path override protected void ondrawnonnull final canvas canvas superondrawcanvas mpath2reset mpath2addcirclemdownx mdowny mradius pathdirectioncw canvasclippathmpath2 mpathreset mpathaddcirclemdownx mdowny mradius 3 pathdirectioncw canvasclippathmpath regionopdifference canvasdrawcirclemdownx mdowny mradius mpaint but i want to use xml approach how do i achieve this i have looked at this and this but i am not yet that comfortable with styles so i am finding it difficult to achieve the ripple effecti have a button with the following xml code button androidididbutton email androidlayout width0dip androidlayout heightwrap content androidlayout weight050 androidgravitycenter androidtextstringemail how do i get ripple effect for this button if someone can guide me i will be thankfuledit adding ripplexml and backgroundxml as mentioned in one of the links above i have created a drawablev21 folder in res and added the below files thereripplexmlxml version10 encodingutf8ripple xmlnsandroid androidcolorandroidcolorblack item androiddrawabledrawablebackground itemripplebackgroundxmlxml version10 encodingutf8shape xmlnsandroid solid androidcolorandroidcolordarker gray shapei added the ripple as background for my button here is the xml for my button nowbutton androidididbutton email androidlayout width0dip androidlayout heightwrap content androidlayout weight050 androidgravitycenter androidbackgrounddrawableripple androidtextstringemail when i run the application i get a resourcenotfoundexception here is the logcat trace0721 170339043 eandroidruntime15710 fatal exception main0721 170339043 eandroidruntime15710 process comx pid 157100721 170339043 eandroidruntime15710 androidviewinflateexception binary xml file line 60 error inflating class unknown0721 170339043 eandroidruntime15710 at androidviewlayoutinflatercreateviewlayoutinflaterjava6200721 170339043 eandroidruntime15710 at comandroidinternalpolicyimplphonelayoutinflateroncreateviewphonelayoutinflaterjava560721 170339043 eandroidruntime15710 at androidviewlayoutinflateroncreateviewlayoutinflaterjava6690721 170339043 eandroidruntime15710 at androidviewlayoutinflatercreateviewfromtaglayoutinflaterjava6940721 170339043 eandroidruntime15710 at androidviewlayoutinflaterrinflatelayoutinflaterjava7550721 170339043 eandroidruntime15710 at androidviewlayoutinflaterrinflatelayoutinflaterjava7580721 170339043 eandroidruntime15710 at androidviewlayoutinflaterinflatelayoutinflaterjava4920721 170339043 eandroidruntime15710 at androidviewlayoutinflaterinflatelayoutinflaterjava3970721 170339043 eandroidruntime15710 at comxbusinessadapteroncreateviewholderbusinessadapterjava1060721 170339043 eandroidruntime15710 at comxbusinessadapteroncreateviewholderbusinessadapterjava10721 170339043 eandroidruntime15710 at androidsupportv7widgetrecyclerviewadaptercreateviewholderrecyclerviewjava29150721 170339043 eandroidruntime15710 at androidsupportv7widgetrecyclerviewrecyclergetviewforpositionrecyclerviewjava25110721 170339043 eandroidruntime15710 at androidsupportv7widgetlinearlayoutmanagerrenderstatenextlinearlayoutmanagerjava14250721 170339043 eandroidruntime15710 at androidsupportv7widgetlinearlayoutmanagerfilinearlayoutmanagerjava90721 170339043 eandroidruntime15710 at androidsupportv7widgetlinearlayoutmanageronlayoutchildrenlinearlayoutmanagerjava5240721 170339043 eandroidruntime15710 at androidsupportv7widgetrecyclerviewthispatchlayoutrecyclerviewjava14610721 170339043 eandroidruntime15710 at androidsupportv7widgetrecyclerviewonlayoutrecyclerviewjava160721 170339043 eandroidruntime15710 at androidviewviewlayoutviewjava148170721 170339043 eandroidruntime15710 at androidviewviewgrouplayoutviewgroupjava46310721 170339043 eandroidruntime15710 at androidwidgetframelayoutlayoutchildrenframelayoutjava4530721 170339043 eandroidruntime15710 at androidwidgetframelayoutonlayoutframelayoutjava3880721 170339043 eandroidruntime15710 at androidviewviewlayoutviewjava148170721 170339043 eandroidruntime15710 at androidviewviewgrouplayoutviewgroupjava46310721 170339043 eandroidruntime15710 at androidwidgetframelayoutlayoutchildrenframelayoutjava4530721 170339043 eandroidruntime15710 at androidwidgetframelayoutonlayoutframelayoutjava3880721 170339043 eandroidruntime15710 at androidviewviewlayoutviewjava148170721 170339043 eandroidruntime15710 at androidviewviewgrouplayoutviewgroupjava46310721 170339043 eandroidruntime15710 at comandroidinternalwidgetactionbaroverlaylayoutonlayoutactionbaroverlaylayoutjava3740721 170339043 eandroidruntime15710 at androidviewviewlayoutviewjava148170721 170339043 eandroidruntime15710 at androidviewviewgrouplayoutviewgroupjava46310721 170339043 eandroidruntime15710 at androidwidgetframelayoutlayoutchildrenframelayoutjava4530721 170339043 eandroidruntime15710 at androidwidgetframelayoutonlayoutframelayoutjava3880721 170339043 eandroidruntime15710 at androidviewviewlayoutviewjava148170721 170339043 eandroidruntime15710 at androidviewviewgrouplayoutviewgroupjava46310721 170339043 eandroidruntime15710 at androidviewviewrootimplperformlayoutviewrootimpljava19830721 170339043 eandroidruntime15710 at androidviewviewrootimplperformtraversalsviewrootimpljava17400721 170339043 eandroidruntime15710 at androidviewviewrootimpldotraversalviewrootimpljava9960721 170339043 eandroidruntime15710 at androidviewviewrootimpltraversalrunnablerunviewrootimpljava560721 170339043 eandroidruntime15710 at androidviewchoreographercallbackrecordrunchoreographerjava7610721 170339043 eandroidruntime15710 at androidviewchoreographerdocallbackschoreographerjava5740721 170339043 eandroidruntime15710 at androidviewchoreographerdoframechoreographerjava5440721 170339043 eandroidruntime15710 at androidviewchoreographerframethisplayeventreceiverrunchoreographerjava7470721 170339043 eandroidruntime15710 at androidoshandlerhandlecallbackhandlerjava7330721 170339043 eandroidruntime15710 at androidoshandlerthispatchmessagehandlerjava950721 170339043 eandroidruntime15710 at androidoslooperlooplooperjava1360721 170339043 eandroidruntime15710 at androidappactivitythreadmainactivitythreadjava50010721 170339043 eandroidruntime15710 at javalangreflectmethodinvokenativenative method0721 170339043 eandroidruntime15710 at javalangreflectmethodinvokemethodjava5150721 170339043 eandroidruntime15710 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava7850721 170339043 eandroidruntime15710 at comandroidinternaloszygoteinitmainzygoteinitjava6010721 170339043 eandroidruntime15710 at dalviksystemnativestartmainnative method0721 170339043 eandroidruntime15710 caused by javalangreflectinvocationtargetexception0721 170339043 eandroidruntime15710 at javalangreflectconstructorconstructnativenative method0721 170339043 eandroidruntime15710 at javalangreflectconstructornewinstanceconstructorjava4230721 170339043 eandroidruntime15710 at androidviewlayoutinflatercreateviewlayoutinflaterjava5940721 170339043 eandroidruntime15710 50 more0721 170339043 eandroidruntime15710 caused by androidcontentresresourcesnotfoundexception resource is not a drawable color or path typedvaluet0x1d0x7f020075 a1 r0x,['android'] +731902,python how to reload modules that have been imported with i know that if i import a module by name importmodulename then i can reload it with reloadmodulenamebut i am importing a bunch of modules with a kleene star from proj import how can i reload them in this case,['python'] +732096,is this strict aliasing example correct i have been reading up on the strict aliasing rules over the last week or so and ran into this article understanding cc strict aliasingthe article goes through several ways two swap the halves of a 32bit integer giving both good examples and ones that violate the strict aliasing rule i am having trouble understanding one of the examples thoughthis code is described as brokenuint32 tswaphalvesuint32 t a a a 16 a 16 return athe reason given isthis version looks reasonable but you do not know if the right and left sides of the will each get the original version of a or if one of them will get the result of the other there is no sequence point here so we do not know anything about the order of operations here and you may get different results from the same compiler using different levels of optimizationi thisagree this code looks fine to me there is only one write to a in the a a 16 a 16 line and i expect that both reads of a take place before that write further there are no pointers or references and no incompatible typesam i missing a strict aliasing violation in this code or is the article incorrect,"['c++', 'c']" +732212,how do i stop wpf keydown events from bubbling up from certain contained controls such as textbox my program is quite large and uses wpf and i want to have a global shortcut key that uses r with no modifiersthere are many controls such as textbox listbox combobox etc that all use letters inside the control itself which is fine that is correct for mebut i want to keep that keydown event from bubbling up to the main window where it would trigger the shortcut any time a user is typing the letter r in a textbox for exampleideally i would like to be able to do this without having to specify and do ifthen logic on every instancetype of control that might receive normal alphabetical key presses not just the textbox controls though they are the worst offenders,['c#'] +732258,pass multiple complex objects to a postput web api method can some please help me to know how to pass multiple objects from a c console app to web api controller as shown belowusing var httpclient new systemnethttphttpclient httpclientbaseaddress new uriconfigurationmanagerappsettingsurl httpclientdefaultrequestheadersacceptclear httpclientdefaultrequestheadersacceptaddnew mediatypewithqualityheadervalueapplicationjson var response httpclientputasyncapiprocestartprocessiong objecta objectbmy web api method is like thispublic void startprocessiongfrombodycontent content frombodyconfig config,"['c#', 'asp.net']" +732330,how to thistinguish programmatically between different ioexceptions i am doing some exception handling for code which is writing to the standardinput stream of a process object the process is kind of like the unix head command it reads only part of it is input stream when the process dies the writing thread fails withioexceptionthe pipe has been ended exception from hresult 0x8007006di would like to catch this exception and let it fail gracefully since this is expected behavior however it is not obvious to me how this can robustly be thistinguished from other ioexceptions i could use message but it is my understanding that these are localized and thus this might not work on all platforms i could also use hresult but i cannot find any documentation that specifies that this hresult applies only to this particular error what is the best way of doing this,['c#'] +732347,how to detect if android device is paired with android wear watch i am creating an android wear app that extends push notifications my app downloads approximately 10 images from a server when a push notification comes in and thisplays these additional images on the watch these images are specific to the android wear app and are not shown on the handheld devicehow do i tell if the handheld device is paired with an android wear device so that i can determine if it is necessary to download the additional images required for the wear appthanks,['android'] +732397,how to use roundedbitmapdrawable has anyone managed to use roundedbitmapdrawable correct me if i am wrong but to my understanding it makes a circular image from a regular rectangular imagewhat i have tried so far is thisroundedbitmapdrawablecreateroundedbitmapdrawablegetresources bitmapfactorydecoderesourcegetresources iconresourcewhat i tried to achieve transform any image to a circular image and show it using an imageviewin case i mixed things up and all that i said is nonsense is it possible or simpler to do it with any of the new framework android l or new support library,['android'] +732420,async deadlock i am fairly positive that i am creating a deadlock in my application and i am not sure how to resolve the issue i have a few moving parts and am new to async and await so please bear with mei have a client that uploads a file as followspublic static async taskstring uploadtoservicehttppostedfile file string authcode int id var memorystream new memorystream fileinputstreamcopytomemorystream var requestcontent new multipartformdatacontent var filecontent new bytearraycontentmemorystreamtoarray filecontentheaderscontenttype mediatypeheadervalueparsefilecontenttype requestcontentaddfilecontent file filefilename using var httpclient new httpclient httpclientbaseaddress new uribaseurl httpclientdefaultrequestheadersacceptclear var message await httpclientpostasync stringformatuploadauthcode0id1 authcode id requestcontent return await messagecontentreadasstringasync the piece receiving the filehttppostpublic taskhttpresponsemessage uploadstring authcode int id var request request var provider new custommultipartformdatastreamproviderroot var task requestcontentreadasmultipartasyncprovider continuewitho save file return new httpresponsemessage content new stringcontentfile uploaded successfully statuscode httpstatuscodeok return taskit is all kicked off with the followingprotected void page loadobject sender eventargs e if ispostback var file httpcontextcurrentrequestfiles0 var response uploadtoservicefile hiddenauthcodevalue intparsehiddenidvalue everything appears to be working except that the postasync never recognizes that task has been returned i can see that the status of the await postasync task is waitingforactivation but i am not entirely sure what that means remember i am a n00b to this stuff my file is saved to the correct location but the application never recognizes the response from my serviceif someone could point me in the right direction it would be much appreciated,"['c#', '.net']" +732508,couchbase lite on android l after updating to android l i got errors like this though before on android 44 nexus 7 2013 everything was finejavalangnosuchfielderror no i field mconnectionptr in class landroiddatabasesqlitesqliteconnection or its superclasses at comcouchbasetouchdbtdcollatejsonnativeregistercustomcollatorsnative method at comcouchbasetouchdbtdcollatejsonregistercustomcollatorstdcollatejsonjava11 at comcouchbaseliteandroidandroidsqlitestorageengineopenandroidsqlitestorageenginejava46 at comcouchbaselitedatabaseopendatabasejava909 at comcouchbaselitemanagergetdatabasemanagerjava228 at comexplainmessengermodelutilscbhelperinitcbhelperjava55exeption occures after trying to create database manager new managernew androidcontextappcontext managerdefault options database db managergetdatabasedb name exception heredoes anyone knows how to fix it,['android'] +732557,armcc problems with memcpy alignment exceptions i am porting some software from the gcctoolchain to the armcctoolchain processor stays the same cortexa9 in the ccode memcpy is used armcc replaces a call to memcpy by a call to aeabi memcpy the faq sais the following about aeabi memcpy how do the arm compilers handle memcpy in many cases when compiling calls to memcpy the arm c compiler will generate calls to specialized optimised library functions instead since rvct 21 these specialized functions are part of the abi for the arm architecture aeabi and include aeabi memcpythis function is the same as ansi c memcpy except that the return value is voidbut in contrast to gcc where a call to memcpy works fine in all of my cases with armcc the call to memcpy respectivly aeabi memcpy continuously produces alignment exceptions meanwhile i found out that a call to memcpy can handle calls where source and destination address are not 4byte aligned but only if they are both not 4byte aligned for example volatile uint32 t len 10 uint8 t src uint8 t0x0602 2byte aligned uint8 t dst uint8 t0x0602 20 2byte aligned memcpydst src lenwill work but for example volatile uint32 t len 10 uint8 t src uint8 t0x0602 2byte aligned uint8 t dst uint8 t0x0602 22 4byte aligned memcpydst src lenwill cause an alignment exception since i am using pointers of type uint8 t i explicitly tell the compiler that the addresses can have any alignment but obviously this aeabi memcpy can not handle every combination of alignments how can i solve this problem preferably without changing all calls to memcpy in the existing code with a userspecific version of memcpy thanks for help,['c'] +732567,momentjs check a date is today how do i check a date is actually today the same date rather than the difference between hours in a dayi have three timestamps as examples one is today 220714 and the other two are yesterday 2107141406019110 today14059518670 yesterday14059518510 yesterdayi have tried this but all return falsetimestamp momenttztimestamp tzname var today momentddmmyisaftertimestamp ddmmyconsolelogtoday,['javascript'] +732650,why android gradle predexdebug source and destination must be different build failed i have an android application built with android studio 081 and facing the issueerrorexecution failed for task apredexdebug javalangillegalargumentexception source cusersmfedorovandroidstudioprojectsepos2appbuildintermediatespredexeddebugmateapi001snapshot0ef7e3259aeaf19202f545da97dc6b1ae2502c9ajar and destination cusersmfedorovaltiusplusandroidstudioprojectsepos2appbuildintermediatespredexeddebugmateapi001snapshot0ef7e3259aeaf19202f545da97dc6b1ae2502c9ajar must be differentheres my buildgradle file contents the part that i have changed the rest is defaultconfigurationsall check for updates every build resolutionstrategycachechangingmodulesfor 0 secondsdependencies compile filetreedir libs include jar compile orgapachecommonscommonscollections440 compile orgslf4jslf4jandroid177 compile comaltiusloggingloggingutils001snapshot compile group comaltiusmate name matebluetooth version 001snapshot changing true compile group comaltiusmate name mateapi version 001snapshot changing true compileorgsimpleframeworksimplexml271 exclude group stax module staxapi exclude group xpp3 module xpp3 contents of the root buildgradle are default as created with android projectmateapi001snapshot artifacts are from maven local repository mavenlocal,['android'] +732712,usage of protocols as array types and function parameters in swift i want to create a class that can store objects conforming to a certain protocol the objects should be stored in a typed array according to the swift documentation protocols can be used as types because it is a type you can use a protocol in many places where other types are allowed includingas a parameter type or return type in a function method or initializeras the type of a constant variable or propertyas the type of items in an array dictionary or other containerhowever the following generates compiler errors protocol someprotocol can only be used as a generic constraint because it has self or associated type requirementshow are you supposed to solve thisprotocol someprotocol equatable func blaclass someclass var protocols someprotocol func addelementelement someprotocol selfprotocolsappendelement func removeelementelement someprotocol if let index findselfprotocols element selfprotocolsremoveatindexindex,['ios'] +732732,ios 8 removed minimalui viewport property are there other soft fullscreen solutions this is a multipart question i will try my best to summarise the scenariowe are currently building a responsive web app news reader that allow users to swipe between tabbed content as well as scroll vertically inside each tabbed contenta common approach to the problem is to have a wrapper div that fills the browser viewport set overflow to hidden or auto then scroll horizontally andor vertically inside itthis approach is great but has one main drawback since the height of the document is exactly the same as the browser viewport the mobile browser will not hide the address barnavigation menuthere are numerous hacks and viewport properties that enable us to get more screen real estate but none are quite as effective as minimalui introduced in ios 71news came yesterday that ios 8 beta4 had removed minimalui from mobile safari see webkit section in ios 8 release notes which left us wonderingq1 is it still possible to hide the address bar on mobile safarias far as we know ios 7 no longer responds to the windowscrollto hack this suggests we have to live with the smaller screen space unless we adopt a vertical layout or use mobilewebappcapableq2 is it still possible to have a similar soft fullscreen experienceby soft fullscreen i really mean without using the mobilewebappcapable meta tagour web app is built to be accessible any page can be bookmarked or shared using the native browser menu by adding mobilewebappcapable we prevent users from invoking such menu when it is saved to homescreen which confuses and antagonises usersminimalui used to be the middleground hiding the menu by default but keeping it accessible with a tap though apple might have removed it due to other accessibility concerns such as users not knowing where to tap to activate the menuq3 is a fullscreen experience worth the troubleit would seem that a fullscreen api is not coming to ios anytime soon but even if it is i do not see how the menu will be kept accessible same goes for chrome on androidin this case maybe we should just leave mobile safari as it is and account for viewport height for iphone 5 it is 460 568 108 where 108 includes the os bar address bar and navigation menu for iphone 4 or older it is 372would love to hear some alternatives besides building a native app,"['javascript', 'ios', 'css']" +732850,python 34 and 27 cannot install numpy package for python 34 i am using ubuntu 1204 and want to use python 34 side by side with python 27the installation of python 34 worked properly however i cannot install the numpy package for python 3 and as a consequence i cannot install scipy pandas etcusing sudo pip3 install numpyspits out the following errorfile numpycoresetuppy line 289 in check typescannot compile pythonh perhaps you need to systemerror cannot compile pythonh perhaps you need to install pythondevpythondevelbtw i already have pythondev installedmoreover installing numpy via sudo aptget install pythonnumpydoes not work either since i already installed numpy for python 27 and the installer responds that numpy is already up to datewhat can i do thanks,['python'] +733056,get family members supose the families bellowthe build schema of this iscreate table personconn child int parent intinsert into personconn values 12insert into personconn values 13insert into personconn values 53insert into personconn values 54insert into personconn values 67insert into personconn values 68insert into personconn values 29insert into personconn values 210insert into personconn values 311insert into personconn values 312to get the ancestors of a family member i can use recursion as showed bellowwith childs as select thistinct child parent from personconn where child 1 union all select t2child t2parent from childs t1 inner join personconn t2 on t2child t1parentselect parent from childssql fiddleit will take all the ancestors of selected member id 1 in this example but not the brothers for example the query goes up only in family treemy question ishow to get all members of a family sons parents grandfathers uncles cousins etc starting from a single personupdateone method to solve this is a loop that inserts a person in a temporary table after you could join personconn table with this temporary table and inserts other people do this until no one is inserted anymore i am looking for a more efficient and elegant way i have about 200mm records in personconn table,['sql'] +733176,regex for any english ascii character including special characters i want to write a regex in php to match only any english characters spaces numbers and all special charsfrom this questionregex any ascii characteri tried this preg matchx00x7f strbut it throws a warningno ending delimiter found so how to write this regex in phpthe alternative would be smth like azds and also one by one consider all special chars but is not there a way to do simpler thanks,['php'] +733197,javascript domcontentloaded event not firing in internet explorer i have the following code to attach a function to the domcontentloaded event but the function is never called in internet explorer 11codeif documentaddeventlistener documentaddeventlistenerdomcontentloaded init falseelse documentattacheventondomcontentloaded init,['javascript'] +733235,scalar object requires one element in initializer why when i want to initialize the following vector of uint8 t uint8 t mmac source1 0x01 0x80 0xc2 0x00 0x00 0x01 i get this errorerror scalar object mmac source1 requires one element in initializerbut when i am using this uint8 t mmac source16 0x01 0x80 0xc2 0x00 0x00 0x01 it is working fine,['c'] +733318,android classes not found during sonar anaysis i trying to set a sonar analysis on an android project the analysis is done with version 43 of sonarqube trough sonarrunner androidplugin install android home env variable is set on pathtoandroidsdk the build is done with ant without any problems the execution run well but i have tons of error messages 142346563 error class not found androidcontenturimatcher142346563 error class not found androidneturi142346563 error class not found androiddatabasesqlitesqlitedatabase142346568 error class not found androidproviderbasecolumns142346757 error class not found androidneturi142346829 error class not found androidcontentcontentprovider142346829 error class not found androidneturi142346830 error class not found androiddatabasesqlitesqlitedatabase142346830 error class not found androidcontentcontextmy sonarprojectpropeties sonarprojectkeyclientprojectsonarprojectnameclientprojectsonarprojectversion20sonarsourcessrcsonarbinariesbinclassessonarlibrairiesbindexedlibsusrlocalandroidsdklinuxsonarlanguagejavasonarsourceencodingutf8sonarprofileandroid linthow to set sonar to find these android classes,['android'] +733347,mail attachment wrong media type gmail api i am trying to send a message with a jpeg file attached through the gmail api in javascript client side the code i have written so far is as followsajax type post url headers authorization bearer accesstoken contenttype multipartrelated boundaryfoo bar baz data datawhere data is a string built up like the example found herefoo bar bazcontenttype applicationjson charsetutf8 raw rnjvbtogrw1pbcbuag9saw4gpgvtdghvbgluqgdtywlslmnvbt4kvg86iev4yw1wbgugtmftzsa8zw10ag9saw5az21hawwuy29tpgptdwjqzwn0oibzzhnkcgpzzhnkfoo bar bazcontenttype imagejpegdataimage jpegbase64 9j 4aaqskzjrgabaqeayabgaad 2wbdaaibaqibaqicagicagicabhymnk0tpu1dbx2nna4upk5ebn6onq8vp09fb3pn6 9oadambaairaxeapwdfigd 2qfoo bar bazthe error i get is media type imagejpeg is not supported valid media types messagerfc822 which is understandable since messagerfc822 is the only valid mimetype for the media according to the specification but the example linked above states otherwisewhat am i doing wrong it would be much appreciated if someone could shed some light on this,['javascript'] +733366,is it possible to preregister handlers before jquery is loaded the situation where jquery is loaded late on the page but javascript that relies on jquery being available is loaded before jquery is a pretty common scenario especially if you follow the practice of putting your scripts closer to bodyso basically i want to go from thisscript somefunctionthatuseslatejquery code that relies on jquery scriptscript srcjqueryjsscriptscript function somefunctionthatuseslatejquery scriptto something like thisscript readyfunction code that relies on jquery scriptscript srcjqueryjsscriptmuch like asynchronous stats tracking a la google analytics is there anything out there that allows you to register javascript function calls to be executed once jquery is loaded without getting the dreaded is undefined errori mean for this to happen without registering and deregistering timeoutsintervalshas there ever beenis there the possibility of adding some sort of preregistration variable to jquery that it recognises and handles once it is loadeduse caseit is worth noting that the specific usecase i have got is a dropin js widget where i want some dom manipulation to happen at the scene of the script placement which therefore has the very real possibility of appearing before jquery has loaded in the case of jquery loading happening near bodyi then do not want to burden the user further by requiring them to register a specific function call at the correct point in code execution which will be dependent on their implementation i want it to just work,"['javascript', 'jquery']" +733368,integrate google voice recognition in android app i want to introduce a new feature into my app permanent voice recognitionfirst of all i followed these posts voice recognitionspeech recognition in androidoffline speech recognition in android jellybeanand more others plus other posts from different websitesproblemwhat actually i am trying to do is to have a permanent voice recognition without thisplaying googles voice activity for example when i start the application the voice recognition should start and listen when the recognizer matches some words then my app will do different actions accordingly i do not like to press a button every time i want to do voice recognition and also i do not like to appear anything on the screen to talk to can i do that any suggestions are welcome thank you,['android'] +733474,constructor inheritance failure with boostmultiprecisionmpz int i tried to create a class deriving from boostmultiprecisionmpz int and to have it inherit the base class constructorsinclude boostmultiprecisiongmphppusing namespace boostmultiprecisionstruct integer mpz int using mpz intmpz intg 490 gives me the following errormaincpp820 error templateclass tag class arg1 class arg2 class arg3 class arg4 integerintegerconst boostmultiprecisiondetailexpressiontag arg1 arg2 arg3 arg4 inherited from boostmultiprecisionnumberboostmultiprecisionbackendsgmp int using mpz intmpz int maincpp820 error conflicts with version inherited from boostmultiprecisionnumberboostmultiprecisionbackendsgmp intmaincpp820 error templateclass other boostmultiprecisionexpression template option et integerintegerconst boostmultiprecisionnumberbackend expressiontemplates inherited from boostmultiprecisionnumberboostmultiprecisionbackendsgmp intmaincpp820 error conflicts with version inherited from boostmultiprecisionnumberboostmultiprecisionbackendsgmp intmaincpp820 error templateclass other boostmultiprecisionexpression template option et integerintegerconst boostmultiprecisionnumberbackend expressiontemplates inherited from boostmultiprecisionnumberboostmultiprecisionbackendsgmp intmaincpp820 error conflicts with version inherited from boostmultiprecisionnumberboostmultiprecisionbackendsgmp intmaincpp820 error templateclass v integerintegerconst v inherited from boostmultiprecisionnumberboostmultiprecisionbackendsgmp intmaincpp820 error conflicts with version inherited from boostmultiprecisionnumberboostmultiprecisionbackendsgmp intmaincpp820 error templateclass v constexpr integerintegerconst v inherited from boostmultiprecisionnumberboostmultiprecisionbackendsgmp intmaincpp820 error conflicts with version inherited from boostmultiprecisionnumberboostmultiprecisionbackendsgmp intmaincpp820 error templateclass v integerintegerconst v inherited from boostmultiprecisionnumberboostmultiprecisionbackendsgmp intmaincpp820 error conflicts with version inherited from boostmultiprecisionnumberboostmultiprecisionbackendsgmp intthe truth is that i have no idea why this is happening the following workaround achieves what i want to dostruct integer mpz int templatetypename args integerargs args mpz intstdforwardargsargs can anybody explain why the first example produces an error i thought that inheriting the base class constructors and forwarding values to them did roughly the same thing i guess i was wrong but i am still interested in knowing the differenceedit i will make things clear i do not care at all whether there are better methods to achieve this there are tons the only thing i asked is why constructor inheritance failed in this case is it due to a compiler bug or to some obscure rule somewhere in the standard,['c++'] +733666,android studio lint reports cannot infer argument types i have reviewed the inspection report for my project that is provided by android studio after having executed the following commandanalyzeinspect codethe report indicates a problem with this code snippet in my gradlebuild filebuildtypes release runproguard false proguardfiles getdefaultproguardfileproguardandroidtxt proguardrulestxt signingconfig signingconfigsrelease the specific problem is cannot infer argument types at line 34 i have included a snapshot for clarityone so answer seems to suggest this is just a bogus warning if that is the case can i safely suppress this warning,['android'] +733681,what does the or operator return while playing around with the operator i tried to write the followingii expected this to compile at first but i got a compiler errorthe operand of an increment or decrement operator must be a variable property or indexeri then tried writing i to help the compiler understand what i meant but it also unsurprisingly did not workso i am left wondering what does the operator return with the compiler error i am getting i was expecting i to not return an int representing the value of i incremented but that is also not the case since i can do i i 1 with successanybody have any idea why the operator cannot be chained also igettype does return systemint32,['c#'] +733724,the provided regular expression is using multiline anchors or i trying to write a image validation format that makes sure url ends with either png jpg or gif class product activerecordbase mount uploader image url validates title presence true uniqueness true validates image url presence true format with rgifjpgpngi message must be a url for gif jpg or png image endbut when i start my server seeing thisthe provided regular expression is using multiline anchors or which may present a security risk did you mean to use a and z or forgot to add the multiline true option,['ruby-on-rails'] +733801,what does hot swap error with intellij in java mean i have no idea what a hot swap is and for the life of me cannot construct a google search that will find what it means in the context of my program i was editing my class the same way i do all the time and when i went to run it i all of a sudden got a hot swap failed myclassname schema not implementederrorcan anyone explain this to me in laymans terms,['java'] +733899,cassandra java driver querybuilder api vs preparedstatements datastax java driver cassandradrivercore 202 for cassandra supports preparedstatements as well as querybuilder api any specific advantages using one over the other thisadvantages documentation rhtmlthe above doc does not state any advantages over using querybuilder api over preparedstatements other than writing queries programmatically which is not much of an advantage in my book please share your thoughts and experiences thanks,['java'] +734016,ios uibackgroundmode remotenotification does not work on 4g i am testing push notifications with contentavailable1 and they do not seem to be delivered to the app in the background unless on wifii have a simple log statement at the beginning of the push notification handler voidapplicationuiapplication application didreceiveremotenotificationnsdictionary userinfo fetchcompletionhandlervoid uibackgroundfetchresultcompletionhandler nslognotification received userinfo completionhandleruibackgroundfetchresultnewdatahere is my testrun the app then press the home button to put the app in the backgroundsend a push notification with contentavailable1watch console logs on wifi the console log shows the notification if i go to settings and turn off wifi switching to 4g notifications no longer appear in the log although they do slide in at the top of the screen so i know they are being deliveredthere are no crash logs and the notification is logged if i manually tap on it furthermore this problem does not occur if i am debugging the app in xcode ie if i am debugging in xcode the app will receive the notification in the background on 4g has anyone else experienced this behavior or am i doing something wrongeditto be specific according to my tests if the following conditions are true then the remote notification delegate method above will not be calledapp is running in the background phone is on lte network not connected to wifiapp is not running in the xcode debuggernotification with contentavailable1 is received by the phonehowever if condition 2 is removed ie the phone is connected to wifi then the handler will be called,['ios'] +734076,c operator overload performance issue consider following scheme we have 3 filesmaincppint main clock t begin clock int a 0 for int i 0 i 10 i a i clock t end clock printfnumber d elapsed time fn a doubleend begin clocks per sec begin clock c b0 for int i 0 i 10 i b ci end clock printfnumber d elapsed time fn a doubleend begin clocks per sec return 0classhinclude iostreamstruct c public int m number cint number void operatorconst c rhsclasscppccint number m numbernumbervoid coperatorconst c rhs m number rhsm numberfiles are compiled using clang with flags stdc11 o3what i expected were very similar performance results since i thought that compiler will optimize the operators not to be called as functions the reality though was a bit different here is the resultnumber 1243309312 elapsed time 03number 1243309312 elapsed time 5375751i played around a bit and found out that if i paste all of the code from class into the maincpp the speed dramatically improves and results are very similarnumber 1243309312 elapsed time 03number 1243309312 elapsed time 03than i realized that this behavior is probably caused by the fact that compilation of maincpp and classcpp is completely separated and therefore compiler is unable to perform adequate optimizationsmy question is there any way of keeping the 3file scheme and still achieve the optimization level as if the files were merged into one and than compiled i have read something about unity builds but that seems like an overkill,['c++'] +734083,jquery each reversebackward iteration i am parsing an array using each but inside it i am using splice method so i need to iterate backward is it possible var store var rules eachstore functionindex element this loop needs to iterate backward eachrules functionindex2 rule if elementid ruleid storespliceindex 1 warn i do not want to reverse the array it wouldnt be the same behavioralso i know i could use for i just want to know if it is achievable using each,['jquery'] +734120,rest webservice returning 415 unsupported media type i have created a rest webservice using jaxrs and jersey that is supposed to consume json on a post request my web service class looks like thispathwebhookservicepublic class webhook post consumesmediatypeapplication json public response readdata song song prints out the song info systemoutprintlnsong info n systemoutprintlnsongname songgetsongname systemoutprintlnartist songgetartist repsonse with a http 200 ok response response responsestatus200build return response my song classpublic class song private string songname private string artist public string getsongname return thissongname public string getartist return thisartist public void setsongname string songname thissongname songname public void setartist string artist thisartist artist my webxml if neededxml version10 encodingutf8webapp xmlnsxsi xmlns xsischemalocation 3 0xsd idwebapp id version30 servlet servletnamesnapscanwebhookservletname servletclasscomsunjerseyspicontainerservletservletcontainerservletclass initparam paramnamecomsunjerseyconfigpropertypackagesparamname paramvaluezacolancetserviceparamvalue initparam initparam paramnamecomsunjerseyapijsonpojomappingfeatureparamname paramvaluetrueparamvalue initparam loadonstartup1loadonstartup servlet servletmapping servletnamesnapscanwebhookservletname urlpatternurlpattern servletmappingwebappi am using restclient a little well rest client heres a screenshot of what i am sendingwhen i send that off i get the 415 unsupported media type error anybody have an idea why,['java'] +734130,django ajax submission with validation and multiple forms handling in the django admin interface there is the nice ability to dynamically add new items to foreign key fields and i want to make a similar one using bootstrap modal for popup window and ajax for form submission and validationthis is my use case this is the main form for adding item item have a ref and a categoryand this is the second form for adding a new category i have no problem with showing the modal and submission the form to add new categoryinstead the problem is with the form validation in case the user submit an empty form and with refreshing the select content to add the new added categorythis is my codeformspyclass itemformformsmodelform ref formscharfieldwidgetformstextinputattrsclassformcontrolmax length255 category formsmodelchoicefieldquerysetitemcategoryobjectsall empty labelchoose from the listclass itemcategoryformformsmodelform category formscharfield max length255 requiredtrue help textadd a new categoryviewspydef addrequest if requestmethod post form itemformrequestpost if formis valid item item itemref formcleaned datagetref itemsave return redirectitem list else form itemform form1 itemcategoryform return renderrequest itemaddhtml form form form1form1 def add categoryrequest if requestmethod post form1 itemcategoryformrequestpost if form1is valid vulncategory itemcategory itemcategorycategory form1cleaned datagetcategory itemcategorysave if requestis ajax todo what should i redirect else todo what should i redirect else todo what sould i do to return errors without reloding the page and to refresh the list of categoriesurlspyurlradd add nameaddurlradd category add category nameadd categoryand i have also added this jquery function to load the resultaddclickfunction ajax url itemsadd category data formserialize cache false type post beforesend function add category modalbodyhtmldiv styletextalign center paddingtop 1emimg srcstaticimgloadinggifdiv success function data add category modalbodyhtmldata ps i know that it may be duplicated but non of the answers get me to the point,"['jquery', 'python']" +734157,img src svg changing the fill color htmlimg srclogosvg altlogo classlogoimgcsslogoimg path fill 0the above svg loads and is natively fill f but when i use the above css to try change it to black it does not change this is my first time playing with svg and i am not sure why it is not working,['css'] +734179,intentreceiver components are not allowed to register to receive intents when trying to determine battery level i am trying to get battery info from my application following the guidelines at this is the method is came up with to check the battery levelpublic void sendbatteryinfomessage intentfilter ifilter new intentfilterintentaction battery changed intent batterystatus cregisterreceivernull ifilter int status batterystatusgetintextrabatterymanagerextra status 1 boolean ischarging status batterymanagerbattery status charging status batterymanagerbattery status full int chargeplug batterystatusgetintextrabatterymanagerextra plugged 1 boolean isusbcharge chargeplug batterymanagerbattery plugged usb boolean isaccharge chargeplug batterymanagerbattery plugged ac int batterylevel batterystatusgetintextrabatterymanagerextra level 1 int scale batterystatusgetintextrabatterymanagerextra scale 1 float batterypct batterylevel float scalec is initialized as context object earlier in the classthis is the error message i am getting 0724 181123445 634634wifimyappsudaralksudara app wdalvikvmi1 threadid1 thread exiting with uncaught exception group0x400288900724 181123485 634634wifimyappsudaralksudara app eandroidruntimei1 fatal exception main javalangruntimeexception unable to start receiver wifimyappsudaralksudara appsmsactivity androidcontentreceivercallnotallowedexception intentreceiver components are not allowed to register to receive intents at androidappactivitythreadhandlereceiveractivitythreadjava2821 at androidappactivitythreadaccess3200activitythreadjava125 at androidappactivitythreadhhandlemessageactivitythreadjava2083 at androidoshandlerthispatchmessagehandlerjava99 at androidoslooperlooplooperjava123 at androidappactivitythreadmainactivitythreadjava4627 at javalangreflectmethodinvokenativenative method at javalangreflectmethodinvokemethodjava521 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava858 at comandroidinternaloszygoteinitmainzygoteinitjava616 at dalviksystemnativestartmainnative method caused by androidcontentreceivercallnotallowedexception intentreceiver components are not allowed to register to receive intents at androidappreceiverrestrictedcontextregisterreceivercontextimpljava138 at androidappreceiverrestrictedcontextregisterreceivercontextimpljava132 at wifimyappsudaralksudara appbatteryinfosendbatteryinfomessagebatteryinfojava25 at wifimyappsudaralksudara appsmsactivityonreceivesmsactivityjava53 at androidappactivitythreadhandlereceiveractivitythreadjava2810a a a a a a a a a a a a at androidappactivitythreadaccess3200activitythreadjava125a a a a a a a a a a a a at androidappactivitythreadhhandlemessageactivitythreadjava2083a a a a a a a a a a a a at androidoshandlerthispatchmessagehandlerjava99a a a a a a a a a a a a at androidoslooperlooplooperjava123a a a a a a a a a a a a at androidappactivitythreadmainactivitythreadjava4627a a a a a a a a a a a a at javalangreflectmethodinvokenativenative methoda a a a a a a a a a a a at javalangreflectmethodinvokemethodjava521a a a a a a a a a a a a at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava858a a a a a a a a a a a a at comandroidinternaloszygoteinitmainzygoteinitjava616a a a a a a a a a a a a at dalviksystemnativestartmainnative methodwhat i need to know is the meaning of intentreceiver components are not allowed to register to receive intents and how to over come it thank you,['android'] +734264,is it still advisable to test routes in rails 4 with minitest in rails 3 when writing functional tests in minitest i got in the habit of testing routes separately from testing my controller actions i got the idea from the rails guide on testing section 9 testing routes however after upgrading my application to rails 4 i noticed that the controller action tests themselves have started balking about unknown routes if i do not supply the getpatchpostdelete method with a proper set of paramsfor example given routes configroutesrbnamespace api do namespace v2 defaults format json do resources users do resources posts do resources comments end end endendand functional test testcontrollersapiv2comments controller testrbdescribe apiv2commentscontroller it does something do get index endendin rails 3 the above would work but in rails 4 i get a url generation erroractioncontrollerurlgenerationerror no route matches actionindex controllerapiv2commentsfrom this i can infer that the get helper simply failed to match a route from the routes file when trying to locate the controller and action fair enough i can fix this by changing the get call to include the parameters needed to satisfy the nested route like this testcontrollersapiv2comments controller testrbdescribe apiv2commentscontroller it does something do get index user id 1 post id 1 endend then all is well againso my question is since it was not the case in in rails 3 is it now ok to trust the controller action tests to fully testvalidate my routes in rails 4 or is there additional advantage in testing the routes as well still is there perhaps some other angle that the route tests cover that the controller action tests do not cover note i am not asking for an opinion on whats good to test i am asking for functional differences between route integration tests and controller action tests in regard to route requirementsalso i could not find a specific reference to this change in behavior in the rails 4 release notes or in minitest so i am wondering why this behavior change was made in the first place i do not think it is a bad thing i think it is good but i feel weird not seeing it mentioned in a changelog somewhere and i thought that half the point of the getpatchpostdelete methods were to free you from having to think about what params are needed for routing in the first placefor completeness here is the route test i would use for thisdescribe commentscontroller route integration test do letdefault options controller apiv2comments user id 1 posts id 1 format json it index do assert routing apiv2users1posts1comments default optionsmergeaction index endendupdatei have been looking through actionthispatch code for an answer the only thing i can see so far is that the url for stuff has changed a lot since rails 3 and that the actioncontrollerurlgenerationerror class itself has been added in rails 4 so it could be that these new more strict routing requirements are incidental change to the decoupling of actionview and actioncontroller,"['ruby-on-rails', 'ruby']" +734271,why default move ctor and assignment are no more added by compiler when a destructor is defined i cannot understand the rationale behind the automatic addition of default ctors in particular i find very awkward that every single time i just need to add an empty virtual destructor and nothing more i loose the move stuffs but adding them i loose the copy and default things so i end up adding all this chunk of codevirtual someclass you are the guiltyvirtual someclass default would be the samesomeclasomeclass default no more autoaddedsomeclass operatorsomeclass default no more autoaddedsomeclassconst someclass default but with the moves definedsomeclass operatorconst someclass default i am now missing the copysomeclass and the default as welli am sure there is a reason for making my classes ugly and letting me desire an evil macro i just would like to know it to feel more comfortable,['c++'] +734331,how to clone as derived object in c i define two classes in c ones is the base class and one is a derived class class cbaseclass a class cderivedclass public cbaseclass a and want to implement a clone function as follows cbaseclass cloneconst cbaseclass pobject when an object of cderivedclass is passed to clone then the function will also create a cderivedclass object and returnwhen an object of cbaseclass is passed to clone then the function will also create a cbaseclass object and returnhow to implement such a feature,['c++'] +734453,when is it useful to include the same header multiple times in one file i was reading about multiple inclusions of the same header in one file and found an interesting statement linkthere are a couple of tricks with header files were you deliberately include it multiple times this does actually provide a useful featurei understand that those tricks are probably undesired and confusing in realworld projects especially since people take precautions against multiple inclusions like include guards and pragma oncebut still what are those tricks i came up with a few ideas but would like to see some actual examples ideally safe and tried my thoughtspseudotemplates in c where template parameters are substituted with preprocessor definitionsit can be done without inclusions but functions may be too big or too numerous so making a separate file would make senseblockbyblock structclass construction concatenation of pieces it may help emulate inheritance in c and prevent code duplication when defining structs with common memberslookup tables and other compiletime data structures again with the aid of preprocessor definitions,"['c++', 'c']" +734533,broadcastreceiver not working when i kill my application i have noticed than whenever i manually kill my application by longpressing the back button of my cellphone my broadcast receiver stops working the receiver is in charge of thisplaying a notification every time the user hangs up a phone call and the same is registered in the manifestxmlis this the normalexpected behaviour i thought the receiver should continue to work even if the user decides to kill my application is there a way to prevent thisthankseditheres the manifest entry for the receiverreceiver androidnamebroadcastreceiverscallreceiver androidenabledtrue intentfilter action androidnameandroidintentactionnew outgoing call action androidnameandroidintentactionphone state intentfilterreceiver,['android'] +734543,ask for permission for local notifications in ios 8 but still have the app support ios 7 i have an app which uses local notifications in ios 7 everything works fine but in ios 8 the app needs to ask for user permission to thisplay notifications to ask for permission in ios 8 i am using boolapplicationuiapplication application didfinishlaunchingwithoptionsnsdictionary launchoptions application registerusernotificationsettingsuiusernotificationsettings settingsfortypesuiusernotificationtypealertuiusernotificationtypebadgeuiusernotificationtypesound categoriesnilit works fine in xcode 6 and in ios 8 when i open the same project in xcode 5 the error is a semantic issue use of undeclared identifier uiusernotificationsettings how can i get the app to work with ios 7 8 and have the notifications work properly on both versions,"['ios', 'objective-c']" +734553,protractor tests inconsistently passing failing for angularjs app my protractor e2e tests are inconsistently passing and failingit seems this could be due to asynchronous javascript as thiscussed hereprotractor how to wait for page complete after click a button however here it is mentioned that protractor tests automatically execute sequentially synchronously my test scriptdescribelogin function var ptor beforeeachfunction browserget ptor protractorgetinstance elementbyidsplashclick browserignoresynchronization true to proceed beyond splash screen describewith correct email and password function beforeeachfunction elementbyidemailsendkeys elementbyidpasswordsendkeysadminpassword elementbyidloginbuttonclick aftereachfunction ptorfindelementbyidlogoutthenfunctionelem elemclick itdoes not show alert function sometimes passes sometimes fails expectbrowseriselementpresentbycssalertdangertobefalse itchanges route to admin function sometimes passes sometimes fails expectbrowsergetcurrenturltomatchadmin in the two tests above either both tests will pass or oneboth of the tests will fail with these messagesfailures1 login with correct email and password does not show alertmessage nosuchelementerror no such element async task webdriverfindelementbyidlogoutorfailures1 login with correct email and password changes route to adminmessage nosuchelementerror no such element async task webdriverfindelementbyidlogoutthoughts help much appreciated,['javascript'] +734601,bootstrap is very slow how to make it faster my site is design spicymy website is slow during the bootstrapcss and jsload time 356s by pingdombootstrapcss 979 kbbootstrapjs 287by google pagespeed checkercompressing tentthemesdesgnspycycssbootstrapcss could save 808kib 82 reductioncompressing contentthemesdesgnspycyjsjquery1js could save 593kib 64 reductioncompressing ontentthemesdesgnspycyjsbootstrapjs could save 209kib 73 reductioncompressing could save 108kib 74 reductioncompressing could save 59kib 70 reductioni uses bootstrap for mobile optimize css but my site load time is low any suggestion,"['html', 'css']" +734710,elegant way to pass multiple arguments to a function i have got a function which looks like thisbool generate script bool net bool tv bool phone stdstring clientsid stdstring password int index stdstring number stdstring iport stdstring sernoid stdstring voip number stdstring voip pass stdstring target int slot int port int onu int extra stdstring ip stdstring macin my opinion it looks ugly what is the proper way of handling this problem should i create few vectors with different data types int string and bool and pass them as arguments to this function,['c++'] +734750,bloch effective java favor static classes over nonstatic how many instances i want to know how many instances of a static member class can be created by the enclosing class i assume one only but then the following extract from bloch does not make sense to mequoting joshua blochs effective java item 22 favor static member classes over nonstatica common use of private static member classes is to represent components of the object represented by their enclosing class for example consider a map instance which associates keys with values many map implementations have an internal entry object for each keyvalue pair in the map while each entry is associated with a map the methods on an entry getkey getvalue and setvalue do not need access to the map therefore it would be wasteful to use a nonstatic member class to represent entries a private static member class is best if you accidentally omit the static modifier in the entry declaration the map will still work but each entry will contain a superfluous reference to the map which wastes space and timehe states that the map creates an entry object for each keyvalue pair in the map ie multiple instances of the static member class so my assumption is wrong that means my understanding of static member classes is wrong everyone knows how a static member variable behaves the classic static final string for instance there is only one instance of the object does this mean then that a static member class is not actually instantiated when the enclosing object is instantiated well in that case whats the point of map using a static member class for entry why not just use an interface on the api every other collections class could then just provide it is own implementation just realised that it is item 18 in the pdf version of the book i have,['java'] +734898,onmessagereceived not called in wearablelistenerservice i am working on android wear app using eclipse idei am using same package names for wear app and mobile app and i am packing wearable app manually according to google documentationeverything is working fineit is installed on android wear emulator using usb debugging with phonemy problem is when i am sending a message to wearable using following codelistnode nodelistgetnodesfornode node nodelist logv telling nodegetid pendingresultmessageapisendmessageresult result wearablemessageapisendmessage mgoogleapiclient nodegetid start activity path null resultsetresultcallbacknew resultcallbackmessageapisendmessageresult override public void onresultmessageapisendmessageresult sendmessageresult logv phone sendmessageresultgetstatusgetstatusmessage the onpeerconnected method is running when devices are peered but onmessagereceived never called in wearablelistenerservicethis is my wearablelistenerservice codepublic class datalayerlistenerservice extends wearablelistenerservice private static final string tag datalayersample private static final string start activity path startmainactivity private static final string data item received path dataitemreceived private static final string log tag log override public void onpeerconnectednode peer superonpeerconnectedpeer string id peergetid string name peergetthisplayname logdlog tag connected peer name id name id override public void ondatachangeddataeventbuffer dataevents systemoutprintlnrecevive message3 override public void onmessagereceivedmessageevent messageevent systemoutprintlnservice watch message1 if messageeventgetpathequalsstart activity path systemoutprintlnservice watch message2 intent startintent new intentthis mainactivityclass startintentaddflagsintentflag activity new task startactivitystartintent also a warning message in logcat always appears app does not match records app key appkeycommyappc3f31717fa35401056c20a2798907f1232efa75e appkeycommyappf36e726eefc7e528db26a1c25f6fbf2f93dacd70if app key for both apps should be same then how can i create same app key for both the appsany help is highly appreciatedthanks,['android'] +734948,windows phone emulator not starting when i run the emulator from the vs13 hangs self in windows phone os is starting but in hyperv manager is running properly and then keep getting two errorserror dep6200 boostrapping emulator 81 wvga 4 inch 512mb failed device cannot be found app deployment failed please try again error dep6100 the following unexpected error occurred during boostrapping stage connecting to the device smartdeviceexception app deployment failed please try againhelp,['c#'] +735086,sublime text3 and virtualenvs i am totally new with sublime3 but i could not find anything helpful for my problemi have differents virtualenvs made with virtualenwrapper and i would like to be able to specify which venv to use with each projectsince i am using sublimerepl plugin to have custom builds how can i specify which python installation to build my project withfor example when i work on project a i want to run scripts with venvas python and when i work on project b i want to run things with venvb using a different build scriptsorry my terrible english,['python'] +735243,xcode compile errori14lipo cannot open input file fatal error applicationsxcodeappcontentsdevelopertoolchainsxcodedefaultxctoolchainusrbinlipo cannot open input file userszicjinlibrarydeveloperxcodederiveddatabaozouiosgsgjiwiqjwffeheenpeffrqpytqxbuildintermediatesbaozouiosbuilddebugiphoneosbaozouiosbuildobjectsnormalarmv7baozouios no such file or directoryuse virtual machines to compiler does not complain but switched to the real machine iphone5s runtime compilation error will be sothe sourcecode,['ios'] +735254,facebook audience network proguard settings i am currently using proguard in my app and the audience network is not working i need some different configuration rather than the usualkeep class comfacebook the problem is the integration guide does not refer any kind of proguard configuration does someone already faced this problem and figured out what is missing,['android'] +735297,why is declaring an array as an object correct in java the following expression compilesobject oa new float20 how is this expression validas per my opinion the correct syntax would be object oa new float20,['java'] +735331,connect to vpn programmatically in ios 8 since the release of ios 8 beta i found a network extension framework in its bundle which is going to let developers configure and connect to vpn servers programmatically and without any profile installationthe framework contains a major class called nevpnmanager this class also has 3 main methods that let me save load or remove vpn preferences iave written a piece of code in viewdidload method as followingnevpnmanager manager nevpnmanager sharedmanagernsnotificationcenter defaultcenter addobserverself selectorselectorvpnconnectionstatuschanged namenevpnstatusdidchangenotification objectnilmanager loadfrompreferenceswithcompletionhandlernserror error iferror nslogload error error nevpnprotocolipsec p nevpnprotocolipsec alloc initpusername amy usernameappasswordreference keychainaccess loaddataforservicenamedvitpserveraddress amy server addressapauthenticationmethod nevpnikeauthenticationmethodcertificateplocalidentifier amy local identifierapremoteidentifier amy remote identifierapuseextendedauthentication nopidentitydata my vpn certification private keypthisconnectonsleep nomanager setprotocolpmanager setondemandenablednomanager setlocalizeddescriptionvit vpnnsarray array nsarray newmanager setondemandrules arraynslogconnection desciption managerlocalizeddescriptionnslogvpn status i managerconnectionstatusmanager savetopreferenceswithcompletionhandlernserror error iferror nslogsave error error i also placed a button in my view and set its touchupinside action to the method below ibactionbuttonpressedidsender nserror starterror nevpnmanager sharedmanagerconnection startvpntunnelandreturnerrorstarterror ifstarterror nslogstart error starterrorlocalizeddescription there are two problems here1 when i try to save the preferences the following error will be thrown a save error error domainnevpnerrordomain code4 the operation couldnat be completed nevpnerrordomain error 4aa what is this error how can i solve this issue2 nevpnmanager sharedmanagerconnection startvpntunnelandreturnerrorstarterror method doesnat return any error when i call it but the connection status changes from thisconnected to connecting for just a moment and then it gets back to thisconnected stateany help will be appreciated,"['ios', 'objective-c']" +735433,warning mysqli query could not fetch mysqli i have a problem where i can not retrieve the result from my mysql database via php i use the same function in other places and it works flawlessly however at this point i keep getting the warning mysqli query could not fetch mysqli error details of the problem are explained belowi use a quite similar function elsewhere getallcountries as seen below in my php which does work perfectlyfunction getallcountries result db queryselect countryid name from country order by name asc echo select classaddresscountry namecountry whilerow mysqli fetch arrayresult echo option value rowcountryid rowname option echo select mysqli closedb connectso the problem is the following i have a php file containing the following codephprequire includesfunctionsphpfunction getuserpicpath userid sessionuserid result db queryselect picture from user where useriduserid whilerow mysqli fetch arrayresult picturepath rowpicture echo picturepath mysqli closedb connectmy functionsphp file has the following line together with other nonrelevant functionsrequire dbfunctionsphpand my dbfunctionsphp looks like thisphpfunction db connect require db passwordphp static connection ifissetconnection connection mysqli connectlocalhostusernamepassworddbname ifconnection false return mysqli connect error return connectionfunction db queryquery connection db connect result mysqli queryconnectionquery return resultin my php document i call the following function if userid 1 shownotauthorizedpage else myaccountpage and the myaccountpage function is declared in the same file as the getuserpicpath function this getuserpicpath function is called as followsdiv idtabs2 pphp getuserpicpath p divi use the tabs on my webpage and that is where i want to call it inthe myaccountpage function which gives the following error warning mysqli query could not fetch mysqli in cusersdennisdocumentsmy dropboxzwproject filesincludesdbfunctionsphp on line 29call stack time memory function location1 0 256880 main myaccountphp02 010 283328 myaccountpage myaccountphp1813 070 285368 getuserpicpath myaccountphp1214 070 285528 db query myaccountphp115 070 285624 mysqli query dbfunctionsphp29 warning mysqli fetch array expects parameter 1 to be mysqli result null given in cusersdennisdocumentsmy dropboxmeroxywefinal projectproject filesmyaccountphp on line 13call stack time memory function location1 0 256880 main myaccountphp02 010 283328 myaccountpage myaccountphp1813 070 285368 getuserpicpath myaccountphp1214 080 285768 mysqli fetch array myaccountphp13 notice undefined variable picturepath in cusersdennisdocumentsmy dropboxmeroxywefinal projectproject filesmyaccountphp on line 17call stack time memory function location1 0 256880 main myaccountphp02 010 283328 myaccountpage myaccountphp1813 070 285368 getuserpicpath myaccountphp121 warning mysqli close could not fetch mysqli in cusersdennisdocumentsmy dropboxmeroxywefinal projectproject filesmyaccountphp on line 19call stack time memory function location1 0 256880 main myaccountphp02 010 283328 myaccountpage myaccountphp1813 070 285368 getuserpicpath myaccountphp1214 00100 285864 mysqli close myaccountphp19,"['php', 'mysql']" +735457,c pointers doubts i have a doubt about this code i saw at the universitystruct nodelist int data nodelist nexttypedef nodelist listvoid filter list l list aux l whileaux if auxdata 3 list todelete aux aux auxnext delete todelete else aux auxnext i do not know what does list aux l actually do because list is the same as nodelist so the code would be nodelist aux l and that is actually what i do not understand is that a pointer to a pointer that holds the address of a pointer of a nodelist structthe second thing i have trouble understanding is the last line aux auxnextwhy is aux without a on the left side if it was declared as list aux l is list just a pointer to the first nodethank you in advance i googled a lot but i did not find any answers if you can answer my questions i will appreciate a lot,['c++'] +735674,why decltype is not implicit why decltype cannot be implicitly added to an expression when type was expectedtemplate class x class y class zauto foox x y y z z stdvectordecltypexyz values valid in c11c14 stdvectorxyz values invalid valuespush backxyz return values type deduced from expression okin c14 compilers will able to deduce function return type based on return expressions why this cannot be extended to any expression type conversionthe same apply to declval why i have to writestdvectordecltypedeclvalx declvaly declvalz valuesinstead ofstdvectorxyz values,['c++'] +735743,admob memory leaking i am using swift language for admob whenever new advertisement comes up my memory is increasing i think there is a leaking without admob everything else is finevar inter gadinterstitial override func viewwillappearanimated bool inter gadinterstitial interdelegate self interadunitid var requestgadrequest gadrequest requesttestdevices interloadrequestrequestand i am using uiactionalert for thisplaying the interstitialselfinterpresentfromrootviewcontrollerselfmemory report link am i doing something wrong i am using arc can i force to release this interstitials by myselfedati tried gadbanner too i am just opening the app i am not doing anything else and memory is increasingoverride func viewwillappearanimated bool banner gadbannerview bannerdelegate self banneradsize kgadadsizesmartbannerportrait banneradunitid var requestgadrequest gadrequest bannerrootviewcontroller self requesttestdevices selfviewaddsubviewbanner,['ios'] +735859,angularjs bootstrap dropdown not working am bit new to angularjs and bootstrapam trying to add a simple dropdown but it is not workingtried out the suggestion bootstrap 3 simple dropdown not working that is also not workingli classdropdowna classdropdowntoggle datatoggledropdown uisrefaaspan classcaretspanaul classdropdownmenu lia uisrefali lia uisrefbbali lia uisrefccali lia uisrefddali lia uisrefeeali lia uisrefali lia uisrefggali lia uisrefhhali lia uisrefiiali lia uisrefjjali lia uisrefkkaliullicomplete code hope someone would help me out,"['javascript', 'html']" +735945,jpa enum comparision not equal fails i am using jpa 212i want to execute a select query with a where clause the where statement should compare not equal enums stored in database stringentitytablename my entitypublic class myentity implements serializable columnname reminder state enumeratedenumtypestring private reminderstage reminderstage class daoimpl override public listmyentity findallreminderstage stage return emcreatequeryselect c from myentity c where creminderstage reminderstage myentityclass setparameterreminderstage stagegetresultlist but when i execute the query i get the following exception280714 082707910 cest 04e systemerr r caused by openjpa212snapshotr42661530146 nonfatal user error orgapacheopenjpapersistenceargumentexception an error occurred while parsing the query filter select c from certinfo c where creminderstage reminderstage error message orgapacheopenjpakerneljpqltokenmgrerror lexical error at line 1 column 50 encountered 33 after 280714 082707910 cest 04e systemerr r at orgapacheopenjpakerneljpqljpqlexpressionbuilderparsedjpqlparsejpqlexpressionbuilderjava2449280714 082707910 cest 04e systemerr r at orgapacheopenjpakerneljpqljpqlexpressionbuilderparsedjpqlinitjpqlexpressionbuilderjava2432280714 082707910 cest 04e systemerr r at orgapacheopenjpakerneljpqljpqlparserparsejpqlparserjava49280714 082707910 cest 04e systemerr r at orgapacheopenjpakernelexpressionstorequerynewcompilationexpressionstorequeryjava154280714 082707910 cest 04e systemerr r at orgapacheopenjpakernelqueryimplnewcompilationqueryimpljava672280714 082707911 cest 04e systemerr r at orgapacheopenjpakernelqueryimplcompilationfromcachequeryimpljava654280714 082707911 cest 04e systemerr r at orgapacheopenjpakernelqueryimplcompileforcompilationqueryimpljava620280714 082707911 cest 04e systemerr r at orgapacheopenjpakernelqueryimplcompileforexecutorqueryimpljava682280714 082707911 cest 04e systemerr r at orgapacheopenjpakernelqueryimplcompilequeryimpljava589280714 082707911 cest 04e systemerr r at orgapacheopenjpapersistenceentitymanagerimplcreatequeryentitymanagerimpljava996280714 082707911 cest 04e systemerr r at comibmwspersistenceentitymanagerimplcreatequeryentitymanagerimpljava107280714 082707911 cest 04e systemerr r at comibmwspersistenceentitymanagerimplcreatequeryentitymanagerimpljava86280714 082707911 cest 04e systemerr r at comibmwspersistenceentitymanagerimplcreatequeryentitymanagerimpljava34280714 082707911 cest 04e systemerr r at orgapacheopenjpapersistenceentitymanagerimplcreatequeryentitymanagerimpljava974280714 082707911 cest 04e systemerr r at comibmwsjpamanagementjpatxeminvocationcreatequeryjpatxeminvocationjava353280714 082707911 cest 04e systemerr r at comibmwsjpamanagementjpaentitymanagercreatequeryjpaentitymanagerjava550280714 082707911 cest 04e systemerr r at findalldaoimpljava271280714 082707911 cest 04e systemerr r 13 morewhen i change from not equal to equal the query works fineso how can i use enum comparison with not equal,"['java', 'sql']" +735977,android integration with ccavenue i have an android app and want to integrate with ccavenue payment gateway same as flipkart and othersbut i do not know how can i integrate ccavenue because there is no sdk providedi have used paypal sdk thats so simple to integratebut not able to integrate ccavenueso please help me for this problemthanks,['android'] +736039,how to uglify output with browserify in gulp i tried to uglify output of browserify in gulp but it does not work gulpfilejsvar browserify requirebrowserifyvar gulp requiregulpvar uglify requiregulpuglifyvar source requirevinylsourcestreamgulptaskbrowserify function return browserifysourcescriptsappjs bundle pipesourcebundlejs pipeuglify pipegulpdestbuildscriptsas i understand i cannot make it in steps as below do i need to make in one pipe to preserve the sequencegulptaskbrowserify function return browserifysourcescriptsappjs bundle pipesourcebundlejs pipeuglify pipegulpdestsourcescriptsgulptaskscripts function return gruntsrcsourcescriptsbudlejs pipeuglify pipegulpdestbuildscriptsgulptaskdefault function gulpstartbrowserify scripts,['javascript'] +736082,card view material design i am trying to use card view but it keeps giving an errorerror13 no resource identifier found for attribute cardcornerradius in package comgoogleexampletest apprelativelayout xmlnsandroid xmlnstools androidlayout widthmatch parent androidlayout heightmatch parent androidpaddingleftdimenactivity horizontal margin androidpaddingrightdimenactivity horizontal margin androidpaddingtopdimenactivity vertical margin androidpaddingbottomdimenactivity vertical margin androidbackground610b0b toolscontextmyactivity androidididmyactivity androidsupportv7widgetcardview xmlnscard view androidididcard view androidlayout width200dp androidlayout height200dp androidlayout gravitycenter androidbackgroundf card viewcardcornerradius4dp textview androidididmy textview androidlayout widthwrap content androidlayout heightwrap content androidtextstringnext androidbackgroundf androidelevation5dp androidsupportv7widgetcardviewrelativelayoutwhat am i doing wrong here,['android'] +736114,nullreferenceexception at systemwebmvcfilterprovidercollectiongetfilters i have an mvc 5 app net 451 running on windows 2008 r2 iis 75the following exception keeps being thrown periodically when running load tests unfortunately i cannot reproduce locally and am rather stuck so am hoping the community may have more ideas update have now been able to reproduce under loadlooking at the source for filterprovidercollectiongetfilters suggests that its possibly the dependency resolver but without more information i am reluctant to simply replace the library currently its using simpleinjectorif this is the case my guess would be its caused by app pool recycles but have not been able to confirm this enabling logging of all causes for a recycle in the app pool gave me nothing usefulafter much searching i did find a few references to it potentially being glimpse i have confirmed this is not the case i have also stripped and rebuilt the project to help gain confidence that its not simply nugetpackage upgrade weirdnessany suggestions as to what could be causing it or how i may add extra logging to catch more information would be appreciated thanksexception information exception type nullreferenceexception exception message object reference not set to an instance of an object at systemwebmvcfilterprovidercollectiongetfilterscontrollercontext controllercontext actiondescriptor actiondescriptor at systemwebmvccontrolleractioninvokergetfilterscontrollercontext controllercontext actiondescriptor actiondescriptor at systemwebmvcasyncasynccontrolleractioninvokerbegininvokeactioncontrollercontext controllercontext string actionname asynccallback callback object state at systemwebmvccontrollerbeginexecutecoreb 1casynccallback asynccallback object asyncstate executecorestate innerstate at systemwebmvcasyncasyncresultwrapperwrappedasyncvoid1callbegindelegateasynccallback callback object callbackstate at systemwebmvcasyncasyncresultwrapperwrappedasyncresultbase1beginasynccallback callback object state int32 timeout at systemwebmvcasyncasyncresultwrapperbegintstateasynccallback callback object callbackstate begininvokedelegate1 begindelegate endinvokevoiddelegate1 enddelegate tstate invokestate object tag int32 timeout synchronizationcontext callbacksynccontext at systemwebmvccontrollerbeginexecutecoreasynccallback callback object state at systemwebmvcasyncasyncresultwrapperwrappedasyncresultbase1beginasynccallback callback object state int32 timeout at systemwebmvcasyncasyncresultwrapperbegintstateasynccallback callback object callbackstate begininvokedelegate1 begindelegate endinvokevoiddelegate1 enddelegate tstate invokestate object tag int32 timeout synchronizationcontext callbacksynccontext at systemwebmvccontrollerbeginexecuterequestcontext requestcontext asynccallback callback object state at systemwebmvcmvchandlerbeginprocessrequestb 4asynccallback asynccallback object asyncstate processrequeststate innerstate at systemwebmvcasyncasyncresultwrapperwrappedasyncvoid1callbegindelegateasynccallback callback object callbackstate at systemwebmvcasyncasyncresultwrapperwrappedasyncresultbase1beginasynccallback callback object state int32 timeout at systemwebmvcasyncasyncresultwrapperbegintstateasynccallback callback object callbackstate begininvokedelegate1 begindelegate endinvokevoiddelegate1 enddelegate tstate invokestate object tag int32 timeout synchronizationcontext callbacksynccontext at systemwebmvcmvchandlerbeginprocessrequesthttpcontextbase httpcontext asynccallback callback object state at systemwebhttpapplicationcallhandlerexecutionstepsystemwebhttpapplicationiexecutionstepexecute at systemwebhttpapplicationexecutestepiexecutionstep step boolean completedsynchronouslyupdate 1i have been able to find a method to replicate on the test environmentput a constant load on the app as few as 20 virtual usersmanually recycle the app pool repeatedly until failure triggeredrecycling the app pool without load does not seem to trigger the failuremore worrying setting thisable overlapped recycle to true does not stop them from occurring this i had assumed would stop any recycling issues as it tears the worker process down completely before starting a new oneupdate 2globalasax and associated config doesnat look to me to be too far off the default templates see what you think public class myhttpapplication httpapplication public myhttpapplication simpleinjectorconfiginitializecontainer seems to need to be in ctor to support httpmodule dependencies protected void application start mvchandlerthisablemvcresponseheader true arearegistrationregisterallareas viewengineconfigregisterviewenginesviewenginesengines webapiconfigregisterglobalconfigurationconfiguration filterconfigregisterglobalfiltersglobalfiltersfilters routeconfigregisterroutesroutetableroutes binderconfigregisterglobalbindersmodelbindersbinders the various xconfig classes are pretty much out of the template public static class filterconfig public static void registerglobalfiltersglobalfiltercollection filters filtersaddnew authorizeattribute public static class simpleinjectorconfig summaryinitialize the container and register it as mvc dependency resolversummary public static void initializecontainer var container new container containeroptionsallowresolvingfuncfactories registerservicescontainer containerregistermvccontrollersassemblygetexecutingassembly containerregistermvcintegratedfilterprovider containerregisterwebapicontrollersglobalconfigurationconfiguration containerverify see for more info dependencyresolversetresolvernew simpleinjectordependencyresolvercontainer globalconfigurationconfigurationdependencyresolver new simpleinjectorwebapidependencyresolvercontainer update 3when run with overlapped recycling off i was able to obtain the following variant stack tracesindexoutofrangeexception index was outside the bounds of the array systemcollectionsgenericenumeratormovenext 112 systemlinqconcatiteratord 711movenext 643 systemlinqbuffer1ctorienumerable1 source 520 systemlinqenumerabletoarrayienumerable1 source 103 systemwebmvcfilterprovidercollectiongetfilterscontrollercontext controllercontext actiondescriptor actiondescriptor 89 systemwebmvccontrolleractioninvokergetfilterscontrollercontext controllercontext actiondescriptor actiondescriptor 38 systemwebmvcasyncasynccontrolleractioninvokerbegininvokeactioncontrollercontext controllercontext string actionname asynccallback callback object state 3 systemwebmvccontrollerbeginexecutecoreb 1casynccallback asynccallback object asyncstate executecorestate innerstate 45 systemwebmvcasyncwrappedasyncvoid1callbegindelegateasynccallback callback object callbackstate 1 systemwebmvcasyncwrappedasyncresultbase1beginasynccallback callback object state int32 timeout 150 systemwebmvcasyncasyncresultwrapperbeginasynccallback callback object callbackstate begininvokedelegate1 begindelegate endinvokevoiddelegate1 enddelegate tstate invokestate object tag int32 timeout synchronizationcontext callbacksynccontext 203 systemwebmvccontrollerbeginexecutecoreasynccallback callback object state 879 systemwebmvcasyncwrappedasyncresultbase1beginasynccallback callback object state int32 timeout 150 systemwebmvcasyncasyncresultwrapperbeginasynccallback callback object callbackstate begininvokedelegate1 begindelegate endinvokevoiddelegate1 enddelegate tstate invokestate object tag int32 timeout synchronizationcontext callbacksynccontext 154 systemwebmvccontrollerbeginexecuterequestcontext requestcontext asynccallback callback object state 527 systemwebmvcmvchandlerbeginprocessrequestb 4asynccallback asynccallback object asyncstate processrequeststate innerstate 108 systemwebmvcasyncwrappedasyncvoid1callbegindelegateasynccallback callback object callbackstate 1 systemwebmvcasyncwrappedasyncresultbase1beginasynccallback callback object state int32 timeout 150 systemwebmvcasyncasyncresultwrapperbeginasynccallback callback object callbackstate begininvokedelegate1 begindelegate endinvokevoiddelegate1 enddelegate tstate invokestate object tag int32 timeout synchronizationcontext callbacksynccontext 203 systemwebmvcmvchandlerbeginprocessrequesthttpcontextbase httpcontext asynccallback callback object state 665 systemwebcallhandlerexecutionstepsystemwebhttpapplicationiexecutionstepexecute 12638163 systemwebhttpapplicationexecutestepiexecutionstep step boolean completedsynchronously 288andindexoutofrangeexception index was outside the bounds of the array systemcollectionsgenericenumeratormovenext 112 systemlinqoftypeiteratord aa1movenext 344 systemcollectionsgenericlist1ctorienumerable1 collection 536 systemlinqenumerabletolistienumerable1 source 80 simpleinjectorsimpleinjectormvcextensionsregistermvcintegratedfilterprovidercontainer container 271 webprojectsimpleinjectorconfiginitializecontainer in capp startsimpleinjectorconfigcs35 webprojectmyhttpapplicationctor in cglobalasaxcs14 aspglobal asaxctor in capp globalasax3szzcx020cs0targetinvocationexception exception has been thrown by the target of an invocation systemruntimetypehandlecreateinstanceruntimetype type boolean publiconly boolean nocheck boolean canbecached runtimemethodhandleinternal ctor boolean bneedsecuritycheck 0 systemruntimetypecreateinstanceslowboolean publiconly boolean skipcheckthis boolean fillcache stackcrawlmark stackmark 159 systemruntimetypecreateinstancedefaultctorboolean publiconly boolean skipcheckthis boolean fillcache stackcrawlmark stackmark 256 systemactivatorcreateinstancetype type boolean nonpublic 127 systemruntimetypecreateinstanceimplbindingflags bindingattr binder binder object args cultureinfo culture object activationattributes stackcrawlmark stackmark 14259433 systemactivatorcreateinstancetype type bindingflags bindingattr binder binder object args cultureinfo culture object activationattributes 200 systemactivatorcreateinstancetype type bindingflags bindingattr binder binder object args cultureinfo culture 28 systemwebhttpruntimecreatenonpublicinstancetype type object args 83 systemwebhttpapplicationfactorygetnormalapplicationinstancehttpcontext context 246 systemwebhttpapplicationfactorygetapplicationinstancehttpcontext context 178 systemwebhttpruntimeprocessrequestnotificationprivateiis7workerrequest wr httpcontext context 3,['c#'] +736133,how to use the swiftmailer in yii2 i cannot finally understand how to use the swiftmailer extension in yii2 judging by that on this subject i did not find questions the task is trivial but up to the end i could not understandthere are examples which do not describe in more detail all cycle of sending the letter or i do not understand something setup return components mail class yiiswiftmailermailer transport class swift smtptransport host localhost username username password password port 587 encryption tls sendyiiappmailcomposesettotoemailsetfromthisemail thisnamesetsubjectthissubjectsettextbodythisbodysendi want will receive a concrete working example thank youps i adjusted domain records mx dkim spf addedupd some answeremail which is passed in from field it is put down by default in the field of returnpath has to be the existing address some providers do not allow sending mail from nonexistent email addresses,['php'] +736349,shenzen ios build giving error i am getting the following error when running the shenzen utility i am using xcode 6 beta 4 trying to build an ios app any thoughtsipa build select a scheme1 fieldapplocal2 fieldapprelease 2 xcodebuild fieldappxcworkspace20140728 090043703 xcodebuild353261912070 mt dvtassertions warning in sourcecacheideframeworksideframeworks62446idefoundationsourcecontrolmodelidesourcecontrolmanagerm432details error domaincomappledtidesourcecontrolerrordomain code1 missing extension publicvcssubversion userinfo0x7fb4a2cb14a0 nslocalizeddescriptionmissing extension publicvcssubversionobject idesourcecontrolmanager 0x7fb4a072c9e0method loadrepositoriesthread nsthread 0x7fb4a0605350number 1 name mainplease file a bug at with this warning message and any useful information you can provide archive failed the following build commands failed datamodelversioncompile usersseanzehnderlibrarydeveloperxcodederiveddatafieldappheytvqitcxovbbegdtzbrxjofatybuildintermediatesarchiveintermediatesfieldappreleaseinstallationbuildproductslocationapplicationsvisit trackerappfieldappmomd datamodelfieldappxcdatamodeld datamodelversioncompile usersseanzehnderlibrarydeveloperxcodederiveddatafieldappheytvqitcxovbbegdtzbrxjofatybuildintermediatesarchiveintermediatesfieldappreleaseinstallationbuildproductslocationapplicationsvisit trackerappfieldappmomd datamodelfieldappxcdatamodeld2 failures,['ios'] +736396,parse ios sdk understanding cloud code scenario i am slowly but surely wrapping my head around what is going on with parses cloud code features i just need some help from those who would like to answer some short relatively simple questions about what is going on in some sample cloud code functions the code i will use in this example is below1 cloud codeparseclouddefineedituser functionrequest response var userid requestparamsuserid newcoltext requestparamsnewcoltext var user parseobjectextend user user new user objectid userid usersetnew col newcoltext parsecloudusemasterkey usersavethenfunctionuser responsesuccessuser functionerror responseerrorerror 2 called from iospfcloud callfunctionedituser withparameters userid someuseridhere newcoltext new textthis code was taken from herequestion 1 request response i am confused by what this is is this like typecasting in ios where i am saying in the ios call i want to pass an nsstring into this function userid and inside the cloud code function i am going to call it request is that whats going on herequestion 2 parseobjectextend user is this grabbing the user class from the parse database so that a pfobject of sorts can update it by creating a new user in the line below it is this like apfobject userobject pfobject objectwithclassnameuserquestion 3 usersetnew col newcoltextthis obviously sets the values to be saved to the pfuser i think i know that the newcoltext variable is the text that is to be set but what is new col only thing i can think of is that this sets the name of a new column in the database of whatever type is being passed through the request is this like a pfuser currentuser setobject forkeyquestion 4 parsecloudusemasterkey without getting too technical is this basically all i have to type before i can edit a user object from another userquestion 5 usersavethenfunctionuser responsesuccessuser is this like a user saveinbackgroundwithblock and if so is functionerror responseerrorerrorjust setting what happens if there is an error in the saveinbackgroundwithblockplease keep in mind i know ios not javascript so try to be as descriptive as possible to someone who understands the apple realm,"['javascript', 'ios', 'objective-c']" +736445,android wear app not installing through handset i am trying to get a wearable app installed through an android handset using the package with android studio method found here but it is not working the apk is never installed to the wearable device this is the logcat output0728 151154107 766820 wpackagemanageri1 unknown permission comgoogleandroidwearableread settings in package comgoogleandroidgms0728 151154117 766820 wpackagemanageri1 not granting permission comgoogleandroidgmpermissionauto send to package comgoogleandroidwearableapp protectionlevel2 flags0x88be440728 151154117 766820 wpackagemanageri1 not granting permission androidpermissionmedia content control to package comgoogleandroidwearableapp protectionlevel18 flags0x88be440728 151155047 632632 dwearablepkginstalleri1 got packageupdatereceiver message intent actandroidintentactionpackage removed datpackagemypackagename flg0x4010 cmpcomgoogleandroidwearableappcomgoogleandroidclockworkcompanionpackagemanagerpackageupdatereceiver has extras 0728 151155177 632632 dwearablepkginstalleri1 got packageupdatereceiver message intent actandroidintentactionpackage added datpackagemypackagename flg0x4010 cmpcomgoogleandroidwearableappcomgoogleandroidclockworkcompanionpackagemanagerpackageupdatereceiver has extras as a side note i am able to package manually also described in the link above and the apk gets installed on the wearable device when i run it on the handset i am using buildtoolsversion 20 i am running android studio 082 and have this line in my handset modules buildgradlewearapp projectwearablei have run out of ideas on how to debug this the logs seem pretty useless any ideasedit going to post relevant sections of manifest and buildgradle for both the handset and wearable module handset manifestxml version10 encodingutf8manifest xmlnsandroid packagemypackagename androidinstalocationauto androidversioncode259 androidversionname461 permissions permission androidnamemyappnamepermissionc2d message androidprotectionlevelsignature usespermission androidnameandroidpermissioninternet usespermission androidnameandroidpermissionwake lock usespermission androidnameandroidpermissionwrite external storage usespermission androidnameandroidpermissionread external storage application properties usessdk androidminsdkversion9 androidtargetsdkversion19 supportsscreens androidanydensitytrue androidlargescreenstrue androidnormalscreenstrue androidsmallscreenstrue androidxlargescreenstrue application androidnameappstate androidicondrawableic launcher androidlabelstringapp name androidthemestylethememyapp androidhardwareacceleratedtrue google play services metadata androidnamecomgoogleandroidgmsversion androidvalueintegergoogle play services version android wear service androidnameweardatalayerlistenerservice intentfilter action androidnamecomgoogleandroidgmswearablebind listener intentfilter service this is used for manual packaging i have this commented out when packaging with android studio metadata androidnamecomgoogleandroidwearablebetaapp androidresourcexmlwearable app desc the rest of the activities applicationmanifesthandset buildgradlebuildscript repositories maven url dependencies apply plugin comandroidapplicationapply plugin crashlyticsapply plugin newrelicrepositories mavencentral maven url dependencies compile filetreedir libs include jar compile comandroidsupportsupportv4200 compile comandroidsupportappcompatv7200 compile projectfacebook compile projectmopubsdk compile projectgoogleplay compile comnewrelicagentandroidandroidagent3 compile comcrashlyticsandroidcrashlytics1 androidtestcompile filetreedir testslibs include jar wearapp projectwearableandroid compilesdkversion 19 buildtoolsversion 20 build type is debug to avoid conflict with proguard testbuildtype debug defaultconfig testapplicationid mypackagenametest testinstrumentationrunner comzutubiandroidjunitreportjunitreporttestrunner lintoptions we do not want to abort the build due to lint errors abortonerror false sourcesets main is the default unless stated otherwise main manifestsrcfile androidmanifestxml javasrcdirs src resourcessrcdirs src aidlsrcdirs src renderscriptsrcdirs src ressrcdirs res assetssrcdirs assets testing androidtestsetroottests androidtest javasrcdirs testssrc ressrcdirs testsres cannot add beta icons in here because custom flavour source sets are created during compilation and name duplication will result in a crash signingconfigs debug storefile file storepassword keyalias keypassword release storefile file storepassword keyalias keypassword buildtypes development configuration debug debuggable true jnidebugbuild true signingconfig signingconfigsdebug runproguard false release configuration release debuggable false jnidebugbuild false signingconfig signingconfigsrelease commented proguard out for now to see if it will help configure proguard runproguard true general configuration proguardfile proguardproguardcfg add all of our componentspecific configurations excluding the android generic as we want it to be last filetree tree filetreedir proguard include txt exclude androidtxt treach file file proguardfile filegetcanonicalpath add a fallback configuration for all android apps proguardfile proguardandroidtxt release configuration but debuggable and without proguard used for testing features like g and inapp billing where a release config is required staging debuggable true jnidebugbuild true signingconfig signingconfigsrelease runproguard false productflavors production applicationid mypackagename internalbeta applicationid myinternalbetapackagename beta icons sourcesetsinternalbetaressrcdirs resbetainternal externalbeta applicationid myexternalbetapackagename beta icons sourcesetsexternalbetaressrcdirs resbetaexternal testing applicationid mypackagename without this gradle will complain that duplicate files were added to the apk see packagingoptions exclude metainflicensetxt twitter4j exclude metainfasl20 jackson exclude metainflicense jackson exclude metainfnotice jackson task maketestapks dependson assembleproductionrelease dependson assembleproductiontestwearable manifestxml version10 encodingutf8manifest xmlnsandroid packagemypackagename usesfeature androidnameandroidhardwaretypewatch androidrequiredfalse application androidallowbackuptrue androidicondrawableic launcher androidlabelstringapp name androidthemeandroidstylethemedevicedefault metadata androidnamecomgoogleandroidgmsversion androidvalueintegergoogle play services version activity androidnamewearreaderactivity androidlabelmyapp intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter intentfilter action androidnamemypackagenameread category androidnameandroidintentcategorylauncher intentfilter activity service androidnameweardatalayerlistenerservice intentfilter action androidnamecomgoogleandroidgmswearablebind listener intentfilter service applicationmanifestwearable buildgradlerepositories mavencentralapply plugin comandroidapplicationapply plugin newrelicandroid compilesdkversion 19 buildtoolsversion 20 defaultconfig minsdkversion 19 targetsdkversion 19 versioncode 259 versionname 461 signingconfigs debug keyalias keypassword storefile filesameashandsetdebugkeystore storepassword release storefile filesameashandsetandroidkeystore storepassword keyalias keypassword buildtypes release debuggable true jnidebugbuild false signingconfig signingconfigsrelease productflavors production applicationid mypackagename internalbeta applicationid myinternalbetapackagename beta icons sourcesetsinternalbetaressrcdirs resbetainternal externalbeta applicationid myexternalbetapackagename beta icons sourcesetsexternalbetaressrcdirs resbetaexternal testing applicationid mypackagename dependencies compile filetreedir libs include jar compile projectgoogleplay compile comnewrelicagentandroidandroidagent3,['android'] +736451,create an optional block as a variable i have a simple class where i declare a block as a variableclass myobject nsobject var progressblockprogressdouble init as far as i understand if defined this way progressblock does not have to be initialized in the init initializerhowever when i try to compile i get his errorproperty selfprogressblock not initialized at superinitso the question is how do i create an optional progressblock so i do not get this error,['ios'] +736468,goto before local variable does the following piece of code constitute undefined behaviour since i am jumping before the variable declaration and using it via a pointer if so are there differences between the standardsint main int p 0label1 if p printfdn p return 0 int i 9 p i goto label1 return 1,['c'] +736512,how to use gruntgulp with pm2 pm2 is a great tool to manage node apps how does it work with gruntglup i did not find any useful clues after googling for 20 minutes,['javascript'] +736533,using async await inside the timer elapsed event handler within a windows service i have a timer in a windows service and there is a call made to an async method inside the timer elapsed event handlerprotected override void onstartstring args timerstart private async void timer elapsedobject sender elapsedeventargs e timerstop await dosomething timerstartis the above code ok firstly i have read that async void is not a good idea secondly why would i need the timer elapsed method to be async in the first place it is not like the elapsed event handler us going to get called in parallel by multiple callers however if i do not make the method async then my logic will break because timer will start before dosomething completesso is making timer elapsed async the correct approach,"['c#', '.net']" +736683,owin twitter login the remote certificate is invalid according to the validation procedure i started getting this error recently when trying to login using twitter any idea whystack trace authenticationexception the remote certificate is invalid according to the validation procedure systemnettlsstreamendwriteiasyncresult asyncresult 230 systemnetpooledstreamendwriteiasyncresult asyncresult 13 systemnetconnectstreamwriteheaderscallbackiasyncresult ar 123webexception the underlying connection was closed could not establish trust relationship for the ssltls secure channel systemnethttpwebrequestendgetresponseiasyncresult asyncresult 6432446 systemnethttphttpclienthandlergetresponsecallbackiasyncresult ar 64,['.net'] +736698,using markdown for source code documentation i am looking for an alternative to cs xml source code documentation which introduced by the very nature of xml a lot of noise that is heavy on the eye and more work to write summary this is text of importance linking to see crefanotherclassis somewhat verbosesee summary param nameandsois parameter documentationparaminstead i would like to use markdown for the documentation this is text of importance linking to anotherclass is less verbose empty lines would make a new paragraph aparameter could possibly be documented in definitionlist manner as in i could bet i found a question and answer for exactly this on stackoverflow before unfortunately i do not manage to find it anymore i tried all variations of search keywords i could imagine without luck so i hope that any of you will find the duplicate at least my question will add some value to so by providing a proxy to the existing qa with different wording thus improving the odds for future visitors to find their informationupdatei guess i finally found the other question by using a different search engine markdown for automatic doc generation it seems that doxygen supports markdown doxygen supports c too but this probably does not go a long way as for the requirements that sam harwell mentioned,['c#'] +736752,systemnetwebexception the remote name could not be resolved i am testing an endpoint that i am experience some issues withi am simply using httpclient in a loop that each hour do a requestvar httpclient new httpclientvar message httpclientgetasyncurlresultconsolewritelinemessagestatuscodeonce a while i am getting this exceptionsystemnethttphttprequestexception an error occurre d while sending the request systemnetwebexception the remote name could not be resolved xthe experience is that right after the exception the url can be accessed in a browser its simply to refresh the page and all is goodi still havent got any reports from users experience it so i am wondering if its just a local issue here but could use a little information to help diagnoseis there a way to check if the remote name could not be resolved is caused by an dns issue or by a webserver issue from the exceptions can i get more information out of httpclient or do i need more advanced diagnostic tools,"['c#', '.net']" +736759,how does boost program options work the weird thing to me is that boosts options description uses multiline code without backslash or semicolon or comma i did a little research but found nothingcode taken from official boosts tutorialint optpooptions description descallowed options descadd options help produce help message optimization povalueintoptdefault value10 optimization level includepathi povalue vectorstring include path inputfile povalue vectorstring input file how is it implemented is it a macro,['c++'] +736925,thisable browsers form inputs prefillautofill feature when hitting back button i want to prevent browsers from prefilling form inputs when hitting the back button indeed i want the initial values to be filled in added via jsp not the browsers cached valuessolution 1 i found out that this can be done by thisabling the browser caching for the current page this seems a rather extreme solution considering that i only want to thisable this prefill feature for a form hence thisable caching for the form only not the whole pagesolution 2 then the obvious next solution is to use javascript that is store the initial value in a data attribute then on page load replace the input value by the initial value if they differboth solutions seem rather unperfect these are rather work arounds i turn to you guys hoping to hear of a better oneresourceshow does sos form remember previous input valuesthisable firefoxs autofillpressing back prefills inputs with value from right before submithtml form values and back button,['html'] +736952,undefined symbols for architecture x86 64 mavericks yosemite el capitan edit if you fall on this post you may want to jump directly to the answeri sent a post about my confusion earlier this morningmachine type c librairies i386 vs x86 64but i guess i did a mistake by being not precise so i decided to give an example of situations i face and that i can not understandstep 1i build a library on machine a a 2 years old mac with os x 1075 that i guess is 64 bits my guess being based on the commands you will see below in additional info using the following filesa header simpleclasshppifndef simpleclass hppdefine simpleclass hppclass simpleclasspublic simpleclass simpleclassconst simpleclass orig virtual simpleclassprivate endif simpleclass hpp a source file simpleclasscppinclude simpleclasshinclude iostreamsimpleclasimpleclass stdcout a new instance of simple class was created stdendlsimpleclasimpleclassconst simpleclass origsimpleclasimpleclassi create the library using cpp test clang c o sco i simpleclasshpp simpleclasscppcpp test ar rcs libtest sca scoadditional info on machine acpp test clang versionapple llvm version 42 clang425028 based on llvm 32svntarget x86 64appledarwin1142cpp test uname mx86 64cpp test uname pi386cpp test lipo info libtest sca input file libtest sca is not a fat filenonfat file libtest sca is architecture x86 64step 2i copy simpleclasshpp as well as the library to another machine b that is a 5 years old mac with osx 1067 that i believe is 32 bits and i write the following hello file to test the libraryinclude iostreaminclude simpleclasshppint main stdcout hello world stdendl simpleclass testobj return 0 surprisingly no problems at linking with the library and i getdownloadsgmail9 g o hello l ltest sc hellocppdownloadsgmail9 hellohello worlda new instance of simple class was createdadditional info on machine bdownloadsgmail9 uname mi386downloadsgmail9 uname pi386downloadsgmail9 g versioni686appledarwin10g421 gcc 421 apple inc build 56 dot 3copyright c 2007 free software foundation incthis is free software see the source for copying conditions there is nowarranty not even for merchantability or fitness for a particular purposestep 3i copy the same library again with the same header and hello file on machine c that is a new mac with 1092 that i believe is 64 bitssurprisingly i have linking problemsmacbookprotestcpp g o hello l ltest sc hellocppundefined symbols for architecture x86 64 stdostreamoperatorstdostream stdostream referenced from simpleclasimpleclass in libtest scasco stdios baseinitinit referenced from cxx global var init in libtest scasco stdios baseinitinit referenced from cxx global var init in libtest scasco stdcout referenced from simpleclasimpleclass in libtest scasco stdbasic ostreamchar stdchar traitschar stdendlchar stdchar traitschar stdbasic ostreamchar stdchar traitschar referenced from simpleclasimpleclass in libtest scasco stdbasic ostreamchar stdchar traitschar stdoperatorstdchar traitschar stdbasic ostreamchar stdchar traitschar char const referenced from simpleclasimpleclass in libtest scascold symbols not found for architecture x86 64clang error linker command failed with exit code 1 use v to see invocationadditional info on machine cg versionconfigured with prefixapplicationsxcodeappcontentsdeveloperusr withgxxincludedirusrincludec421apple llvm version 51 clang503040 based on llvm 34svntarget x86 64appledarwin1310thread model posixmacbookprotestcpp uname mx86 64macbookprotestcpp uname pi386i would have expected the linking problem with machine b that is 32bits and not with machine c that is 64bits but i got the opposite can anyone please explain what i am missing hereedit step 4on machine c when i add to the g command the option stdliblibstdc the undefined symbols error thisappear and the executable is running correctly running g with the option v allowed me to notice the default stdlib was libcand not libstdc so it seems that although the machine a and machine c are both 64 bits they do not use the same stdlib by default which caused the error undefined symbols for architecture x86 64,['c++'] +736956,confused about angularjs dependency injection inconsistency i am new to angularjs and went through several tutorials including all of the ones here on codeschool i found them very useful and learned a lot but now that i have finished my introduction and am getting into trying to use it in some things i am finding some confusing inconsistencies most notably dependency injectionin the tutorials i took dependencies for services were done like thisappcontrollername http scope functionhttp scope code this strikes me as odd but it works anyway i was confused as to why the did not terminate before the function i am presuming this is what you refer to as a callback function in javascript i was expecting it more like requirejs where it would have been appcontrollername http scope functionhttp scope however then i began to look at examples and demos of angular online and i found this was not consistent for instance examine the following linksmediumcomrevolunetcomkendouiin each of these i see dependency injection used like thisappcontrollername functionhttp advancedgithubuser appcontrollername functionscope function controllernamescope they completely bypass the array like syntax and all three are different in one it takes a type of object that is declared somewhere else but i do not see any wiring done to point to it in another it just kind of has these objectsand still in another the name part of the controller is the name of the function and i see nothing that really denotes it as a controller but it is used that way in directivescan anyone explain this to me i am completely lost now this inconsistency makes it a bit difficult to pick up the techniques,['javascript'] +737029,explain imagesrcmatch in javascript i was following this tutorial and i found some javascript code difficult to understandlink to tutorial lightbulbcode i need to clarifyscriptfunction changeimage var image documentgetelementbyidmyimage if imagesrcmatchbulbon imagesrc pic bulboffgif else imagesrc pic bulbongif scripti do not understand what match in imagesrcmatch actually meansis it something that has a toggling actioni could not find any useful article for this,"['javascript', 'html']" +737103,how do i test if an activerecord attribute is an enum how would i test if an activerecord attribute is an enum as per rails 41 enum declarationit is stored in the database and using the type method on columns hash identifies the attribute as an integer enum definition in modelenum status in progress accepted approved declined closed cancelled submitted to pull the typeirbmain0300 applicationcolumns hashstatustype integer,['ruby-on-rails'] +737145,show values on top of bars in a barchart i have a bar chart with ordinal scale for the xaxis i want to thisplay the yvalues on the top of each bar or in the bottom of each bar it would be also acceptable to thisplay the yvalues when one hovers over the bar is there a function or a way in a dcjs to do that here is the jsfiddle and my code is below the picedit here is my codehtmlbody div idchart divbodyjsvar data category a id 1 category a id 1 category a id 1 category a id 2 category a id 2 category b id 1 category b id 1 category b id 1 category b id 2 category b id 3 category b id 3 category b id 3 category b id 4 category c id 1 category c id 2 category c id 3 category c id 4 category c id 4 category c id 5var ndx crossfilterdatavar xdimension ndxdimensionfunction d return dcategoryvar ydimension xdimensiongroupreducecountfunction d return dvaluedcbarchartchart width480height300 dimensionxdimension groupydimension transitionduration500 xunitsdcunitsordinal labelfunctiond return dvalue xd3scaleordinaldomainxdimension dcrenderall,['javascript'] +737250,dynamically create listmodel in qml when i need to create any qml component in runtime i can use that guideie just call qtcreatecomponent and componentcreateobjectbut i cannot found how can i create listmodel in runtime right in qml file not in cyou can ask why i need it so i have a nested listmodel there is outer model which delegates contained inner models so when i am calling outer modelappend i must pass newly created listmodel for inner model i cannot use statically defined inner model in outer delegate because i cannot access such model in runtime by the way can it be accessed somehowps maybe it is completely wrong idea to try managing models in javascript,['javascript'] +737291,gcm push notification large icon size hi iam implementing push notifications in android using gcm i am trying to set an image for the notification instead of the default app icon i am able to achieve this using the following codeifextrasgetstringsrc null url url new urlextrasgetstringsrc httpurlconnection connection httpurlconnection urlopenconnection connectionsetdoinputtrue connectionconnect inputstream input connectiongetinputstream bitmap large icon bitmapfactorydecodestreaminput mbuildersetlargeiconlarge icon typically the image will be from the webjpg png etc and not something in the device the above code works but the image is either too big or too small i would like to know the optimum size or aspect ratio for the bitmap so that i can supply an appropriate image,['android'] +737323,use of undeclared type uiimage in swift on using this function in swift and i am getting compiler errorfunction isclass func imagewithimage imagetoresize uiimage scaledtosize newsize cgsize return imagetoresizeand the error areuse of undeclared type uiimageuse of undeclared type cgsizewhats wrong with this what can i do to use uiimage in swift,['ios'] +737405,ck editor uncaught typeerror cannot read property clearcustomdata of null in chrome i am using ck rich text editor in my application i have a modal popup and within it i have three tabs each of these tabs renders the same partial view in which i have a field call description which is what i use ck editor on when i use ie 11 everything works as expected and the tabs load with the textarea turned into a ck editor box and navigating between the tabs each time the text area stays as a rich text editor however i am seeing strange behaviour in chrome when i first open the modal box the description text area on each tab is turned into a ck editor as expected and as i tab between them each one is correctly a text area however in chrome if i close the modal box and repoen i get the error above in the console if i have the modal box open and navigate between the tabs 6 times i get the same error appearing and then lose the functionality of the text areas being rendred as ck rich text editors has anyone had anything similar or got a possible solutionthe code in my js file is asdocumentreadyfunction var editor ckeditorinstancesdescription if editor editordestroytrue ckeditorreplaceallcshtml markup from the partial view that is rendered in the 3 tabs is as below div classrow htmllabelformodel modeldescription div classcolmd10 htmltextareaformodel modeldescription div div,"['javascript', 'jquery']" +737415,guardrspec error no cmd option specified unable to run specs after upgrading to guard 261 guard stopped executing specs for changed file132709 info livereload is waiting for a browser to connect 132709 info guardrspec is running 132709 info guard is now watching at path to project132713 info running specmodelssome model specrb132713 error no cmd option specified unable to run specsmy bundle isusing guard 261using guardlivereload 230using guardrails 053using guardrspec 431using rspeccore 2148using rspecexpectations 2145using rspecmocks 2146using rspec 2141using rspecrails 2142using rails 404,['ruby'] +737582,open facebook messenger from ios app does anyone know how can i open the facebook messenger application with a prefilled textfor example to open the messenger app at a specified user you can write the following nsurl fburl nsurl urlwithstringfbmessengeruserthreaduser id if uiapplication sharedapplication canopenurl fburl uiapplication sharedapplication openurl fburlfor whats app is very easynsurl whatsappurl nsurl urlwithstringnsstring stringwithformatwhatsappsendtext string to post hereif uiapplication sharedapplication canopenurl whatsappurl uiapplication sharedapplication openurl whatsappurl,['ios'] +737654,convert sorted ruby array to ranks with possible repeats i have the the following array of numbers in ruby higher is better and i would like to rank them in other words i want to convert the following sorted list89 52 52 36 18 18 5to the following ranks1 2 2 4 5 5 7for instance the winner gets first place there is a tie for second place and so on the important point obviously is that ties are possible and those ties must then skip the corresponding ranks any number of ties might be possible 3 people sharing second placeis there an elegant way to perform this kind of operation,['ruby'] +737797,failed to construct audiocontext number of hardware contexts reached maximum is there a way to remove an audiocontext after i have created itvar analyzers var contexts try forvar i 0 i20 i contextsi new audiocontext analyzersi contextsicreateanalyser catche consoleloge too many contexts created how do i remove themi have tried this but it does not let me create new contexts after the fact analyzersforeachfunctionanalyzeranalyzerthisconnectanalyzercontextdestinationi am using chrome 36 on ubuntu linux 1404,['javascript'] +737799,how to thisable macros imported from cheader class a uses a library written in c this library provides some data types and constants which are used in a unfortunately the library also defines macros in its header file which collide with my c code in maincpp or in other classes using ahow can i prevent macros of c libraryh being executed when ah is included somewhere i would also be open for architectural changes but i would prefer not to touch the c libraryof course there is the undef directive but this would mean a lot of manual work for every macro or for every collision ok there are not too many but hey this must be possible more elegantcodemaincppinclude aha astdmaxx y oops problem since max is defined as macro in c libraryhahinclude c libraryhclass apublic a static void callbackforclibrarydatatypeofclibrary dprivate private datatypeofclibrary1 private datatypeofclibrary2,"['c++', 'c']" +737803,what does repo init and repo sync actually do i posted this question at android enthusiasts but figured it was the wrong place to ask so i deleted it from there and asking it again herethis is such a noob question and pardon me if it is but i just want to understand the underlying concepts clearly reading repo help and googles repo command reference page does not really enlighten much i understood some bits from googles reference page but i still need some more clarificationsfollowing the instructions on how to download android source i executed these two commands on an ubuntu shell i have taken cared of all the prerequisites for the environmentandroid422 repo init u b android422 r12android422 repo sync j4after waiting half a day for repo to finish downloading i ended up with 19g of downloaded material in android422 directory so what exactly just happened and why did it reach 19g when google said i should only be expecting around 8g of source files,['android'] +737829,what could cause floating point numbers to suddenly be off by 1 bit without arithmetic changes in making a somewhat large refactoring change that did not modify any kind of arithmetic i managed to somehow change the output of my program an agent based simulation system various numbers in the output are now off by miniscule amounts examination shows that these numbers are off by 1 bit in their least significant bitfor example 24198110084326416 would become 2419811008432642 the floating point representation of each number is24198110084326416 0 1011 10110010101101010101010110100110100101002419811008432642 0 1011 1011001010110101010101011010011010010101in which we notice that the least significant bit is differentmy question is how i could have introduced this change when i had not modified any type of arithmetic the change involved simplifying an object by removing inheritance its super class was bloated with methods that were not applicable to this classi note that the output thisplaying the values of certain variables at each tick of the simulation sometimes will be off then for another tick the numbers are as expected only to be off again for the following tick eg on one agent its values exhibit this problem on ticks 57 83 but are as expected for ticks 84 and 85 only to be off again for tick 86i am aware that we should not compare floating point numbers directly these errors were noticed when an integration test that merely compared the output file to an expected output failed i could and perhaps should fix the test to parse the files and compare the parsed doubles with some epsilon but i am still curious as to why this issue may have been introducededitminimal diff of change that introduced the problemdiff git asrcmainjavamodelclassesgridsquarejava bsrcmainjavamodelclassesgridsquarejavaindex 4c1076080276bd 100644 asrcmainjavamodelclassesgridsquarejava bsrcmainjavamodelclassesgridsquarejava 637 637 public class gridsquare extends variablelevel public void addhouseholdhousehold hh assert household null subagentsaddhh neighborhoodgethouseholdlistaddhh household hh 737 737 public class gridsquare extends variablelevel public void removehousehold assert household null subagentsremovehousehold neighborhoodgethouseholdlistremovehousehold household null diff git asrcmainjavamodelclassesneighborhoodjava bsrcmainjavamodelclassesneighborhoodjavaindex 834a3218470035 100644 asrcmainjavamodelclassesneighborhoodjava bsrcmainjavamodelclassesneighborhoodjava 1669 16614 public class neighborhood extends variablelevel world world list of all grid squares within the neighborhood arraylistvariablelevel gridsquarelist new arraylist a list of empty grid squares within the neighborhood arraylistgridsquare emptygridsquarelist arraylistgridsquare emptygridsquarelist new arraylist the neighborhoods grid square bounds 8367 8417 public class neighborhood extends variablelevel public gridsquare getgridsquareint i return gridsquare subagentsgeti return gridsquare gridsquarelistgeti 8657 8707 public class neighborhood extends variablelevel override public arraylistvariablelevel getgridsquarelist return subagents return gridsquarelist 87412 8797 public class neighborhood extends variablelevel override public arraylistvariablelevel gethouseholdlist arraylistvariablelevel list new arraylistvariablelevel for int i 0 i subagentssize i listaddallsubagentsgetigethouseholdlist return list return subagents unfortunately i am unable to create a small compilable example due to the fact that i am unable to replicate this behavior outside of the program nor cut this very large and entangled program down to sizeas for what kind of floating point operations are being done there is nothing particularly exciting a ton of addition multiplication natural logarithms and powers almost always with base e the latter two are done with the standard library random numbers are used throughout the program and are generated with random class included with the framework being used repastmost numbers are in the range of 1e3 to 1e5 there is almost no very large or very small numbers infinity and nan is used in many placesbeing an agent based simulation system many formulas are repetitively applied to simulate emergence the order of evaluation is very important as many variables depend on others being evaluated first eg to calculate the bmi we need the diet and cardio status to be calculated first the previous values of variables is also very important in many calculations so this issue could be introduced somewhere early in the program and be carried throughout the rest of it,['java'] +737846,using googleapiclient locationservices not updating this is my first question so i hope it goes welli am just trying to do a simple tutorial app to get my phones location to learn how to use it later in some other app but i am just not getting anywherewhat i have doneandroid developers tutorial first of i followed the tutorial in the androids developer site developerandroidcomtraininglocationreceivelocationupdateshtml just like indicated in there i used a location locationclient and locationrequest initializing them and setting them up in oncreate locationclient is connected and thisconnected in onstart and onstopi am requesting location update after i am connected in onconnected i verify that googleplayservices are available before making this call and i am still not getting any update in onlocationchangedgoogleapiclient i noticed that locationclient is deprecated and locationservices are preferred developerandroidcomreferencecomgoogleandroidgmslocationlocationclienthtmlas indicated here i use a googleapiclient and set it to locationservices also so then i set it all to use this but still i am not getting any updates on the location onlocationchanged it should print if there is a response i also put a button that prints location or nothingremarksi checked using google maps to see if maybe i had something off but it is working just fineprojectbuildgradledependencies compile filetreedir libs include jar compile comgoogleandroidgmsplayservices5077 compile comandroidsupportsupportv4200manifestusespermission androidnameandroidpermissionaccess fine locationmetadata androidnamecomgoogleandroidgmsversion androidvalueintegergoogle play services version codepublic class myactivity extends activity implements googleapiclientconnectioncallbacks googleapiclientonconnectionfailedlistener locationlistener private googleapiclient mlocationclient private location mcurrentlocation locationrequest mlocationrequest constant fields request interval override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity my mlocationclient new googleapiclientbuildergetapplicationcontext addapilocationservicesapi addconnectioncallbacksthis addonconnectionfailedlistenerthis build mlocationrequest new locationrequest mlocationrequestsetintervalupdate interval mlocationrequestsetprioritylocationrequestpriority high accuracy mlocationrequestsetfastestintervalfastest interval override protected void onstart superonstart mlocationclientconnect override protected void onstop superonstop locationservicesfusedlocationapiremovelocationupdatesmlocationclient this mlocationclientthisconnect public void onclickview view if mcurrentlocation null logilocation mcurrentlocationtostring else logilocation nothing override public void onlocationchangedlocation location logdlocation update changed mcurrentlocation location override public void onconnectedbundle bundle thisplay the connection status toastmaketextthis connected toastlength shortshow ifservicesconnected locationservicesfusedlocationapirequestlocationupdatesmlocationclient mlocationrequest this override public void onconnectionsuspendedint i toastmaketextthis thisconnected please reconnect toastlength shortshow logcat89488948exampleandroidcomtest dlocation updatesi1 google play services is available89488948exampleandroidcomtest ilocationi1 nothingi feel that i might be forgetting something really simple but i just cannot see it and i have spent too much time trying to get just a simple locationi could maybe just use the androidlocation api but it bothers me that this is so hard supposedly being easier,['android'] +737847,rails belongs to with custom column name i am working with a legacy database that gives the following schema for the tables product and familia producto rake dbschemadumpcreate table producto primary key barcode force true do t tstring codigo corto limit 16 null false tstring marca limit 35 tstring descripcion limit 50 tstring contenido limit 10 tstring unidad limit 10 tfloat stock default 00 tfloat precio tfloat precio neto tfloat costo promedio tfloat fifo tfloat vendidos tboolean aplica iva tinteger otros impuestos limit 2 tinteger familia limit 2 default 1 null false tinteger id tipo producto limit 2 null false tboolean es perecible tfloat dias stock default 10 tfloat margen promedio default 00 tboolean es venta fraccionada tfloat stock pro default 00 tfloat tasa canje default 10 tfloat precio mayor tfloat cantidad mayor tboolean es mayorista tboolean estado tboolean precio editableendcreate table familia producto force true do t tstring nombre limit 32 null falseendin the models i have thisclass familiaproducto activerecordbase selftable name familia producto has many productos class name producto primary key barcode foreign key familiaendclass producto activerecordbase selftable name producto belongs to familia producto class name familiaproductoendbut when i call the familia the producto object throws me a number not the familiaproducto object please help210 012 p productoall0 producto load 17ms select producto from producto product210 013 pfamilia 2 that 2 should be the familiaproducto object,"['ruby-on-rails', 'ruby']" +737852,should i use java 8 streams api to combine two collections i have this situation where it seems that the java 8 streams api would be helpful but i am not fully sure how it could befrom two collections with thistinct element types i want to build a third collection whose elements are all the possible pairs of elements from both collections basicallythe two thistinct element typespublic class a public class b a pair of as and bspublic class pair private a a private b b public paira a b b this a a this b b the combination made using oldstyle javautilcollection api public collectionpair combinecollectiona as collectionb bs collectionpair pairs new arraylist foreacha a as foreachb b bs pair pair new pairab pairsaddpair return pairs the ordering in the resulting pairs collection is not important so every instance of pair could be created and added to the resulting collection in parallel how could i achieve thisthe best i could figure out by myself was to use the streams version of foreachasforeach a bsforeach b pair pair new pairab pairsaddpair this example was made trivial for the sake of simplification the class pair is an example of processing two elements into a third one that is a javautilfunctionbifunction and adding them to a collection is just an example of a mutable reductionis there a more elegant way to do that or preferable in a more profitable way in regards to efficiency something likebifunctionabpair combinator pairnew or any other function fabcstreampair pairstream streamsunknownelegantmethodasstream bsstream combinator,['java'] +737955,selective shallow copy from one array to another assuming i have 2 array of different size ieint arr 0123456789int arr2 new int5i want to shallow copy some of themdeep copy equivalent would beint j 0 ifi2 arr2jarri j right now a print of arr2 will output 0 2 4 6 8the reason i want to shallow copy is because i want arr2 to update with any changes to arrthat is if i loop and square all the elements in arri want arr2 to output 0 4 16 36 64these 2 arrays are part of the same class one is my polygonal information and the other part is data driven arr is actually 40 elements in size and arr2 is close to 30 at the moment my algorithm works great with deep copy but because i need to deep copy 30 elements per update frame i am wasting resources and was wondering if i could somehow do this via shallow copy so i do not have to have to update arr2 every frame the way my code needs it to work arr actually has repeated values of arr2 arr2 is a list of points that is animated then the data is duplicated to arr which hold the positional data for vertices this is because arr contains multiple bezier patches some of them share one edge or more with another patch but i want that to be ignored when animating else there are breaks in the surfaceit is important that the copy involves indices likearr2jarribecause that is how my code is setupand that the operation be low load,['c++'] +737974,how can i monitorsample output audio in java or c lately i have been experimenting with real time visualizations on the audio i play on my computer via any arbitrary program such as spotify but i have been using soundflower to pipe the output audio in to a fake line inwhat i am wondering is if there is a way that is native to cc or java that will allow me to capture whatever audio is sent to my computers i am using a mac line out in a similar way to how i can capture a line in ie a sample buffer that is continually filled with pcm datai have no desire to emulate the other features of soundflower except for reading the line out data,"['java', 'c++', 'c']" +738043,read resourcebundle as utf8 getstring method seems to change encoding to iso8859 i have the honorable assignment to change the encoding of our complete workspace projects and files to the utf8 encoding we have several resourcebundles which used to code special chars with unicode we also wanted to get rid of that unicode stuff by switching to utf8 so i changed the encoding of the resourcebundles properties files too and replaced the unicode characterswe also have german resourcebundles and some chars like a a a a a a a14 and also special characters like a or aare not shown properly in the browser exampleresourcebundleentry executeshellcommandlabel shellkommando ausfa14hrenresult in browserthe resourcebundles are read with the javautilresourcebundlegetstringstring key method public string getlocalizedstringresourcebundle bundle string key try systemoutprintlngetlocalizedstring key key resourcebundle bundlegetstringkey return bundlegetstringkey catch missingresourceexception e return key if i check the output of the above sysout i get followinggetlocalizedstring key executeshellcommandlabel resourcebundle shellkommando ausfaa14hrenit seems that the getstringkey method changes the encoding of the chars while reading them from the bundles to the standard resourcbundleencodingiso8859i tried to counter this issue public string getlocalizedstringresourcebundle bundle string key try systemoutprintlngetlocalizedstring key key resourcebundle new string bundlegetstringkeygetbytes utf8 return new string bundlegetstringkeygetbytes utf8 catch missingresourceexception e return key catch unsupportedencodingexception e return key this helped to recover the most special characters but there are still a plenty of them which are not shown properlyi also checked the contenttype configuration of the webapp and of every single request which gets the resource bundles everything is utf8does anyone have an idea how to prevent the getstringmethod from changing the encoding or is there a better way to solve this issue,['java'] +738079,complex authentication with existing user database in mvc5 i am migrating a saas app from classic asp to net mvc5 and will use ef6 database first the login form for end users is customisable by each tenant on their own subdomain but pointing to the same web application we wish to use the existing database schema and the new authentication authorization filters for example a user on one tenant may login by entering their first name surname and a code generated by our system a user on another tenant may login by entering their email address and a password additionally each tenant has a separate administrator login which uses a username and password another tenant may use ldap authentication against a remote ad serveris there a definitive best practice way of doing custom authenticationalmost every article appears to suggest different ways of accomplishing this simply setting formsauthenticationsetauthcookie using a custom owin provider override authorizeattribute etcin classic asp we queried the database to find out the type of login for that tenant thisplayed the appropriate fields on the login screen and then on post back checked the fields match whats in the database and then set the session variables appropriately which were checked on each page requestthanks,['asp.net'] +738305,laravel call filter in filter how i can call filter in filter using laraveli have this filterroutefilterauth function if authguest if requestajax return responsemakeunauthorized 401 else return redirectguestlogin now i create another filter called admin and i want call auth filter in thisroutefilteradmin function call auth filter code it is possible do that,['php'] +738387,get json data from a php file for an angular scope i am trying to get json data from a php file to use within an angular controller im echoing json encodepg fetch assocresult within the php file and when i consolelogscopecontents in the angular controller it brings back the json data but it comes back empty when i try doing an ngrepeatcontrollersjsmyappcontrollercontentctrl function scope http httpmethod get url contentphpsuccessfunctiondata scopecontents data contentphpphprequire oncesdbphpresult pg querydbconn select from content order by name ascecho json encodepg fetch assocresultindexphpdoctype htmlhtml langenheadlink relstylesheet hrefcstylecssheadbody ngappmyapp div ngcontrollercontentctrl ul li ngrepeatcontent in contents a hrefcontentnamea li ul divbody script srcjsjquery1102jsscript script srcjsangularminjsscript script srcjscontrollersjsscripthtml,"['javascript', 'php']" +738427,android bluetooth scan for classic and btle devices the android documentation statesnote you can only scan for bluetooth le devices or scan for classic bluetooth devices as described in bluetooth you cannot scan for both bluetooth le and classic devices at the same timehowever i am noticing that calling mbtadapterstartthiscovery is returning both classic and btle devices does anybody know what is correct here,['android'] +738430,requestargsgetkey gives null flask i am trying to pass the variable email from the signup method in my view to the character method however requestargsgetemail is saving null into the database i cannot figure out whyhere is what shows up after passing the email variable to characterhere is my code in viewspyapproutesignup methodsgetpostdef signup if requestmethod get return render templatesignuphtml email requestformemail return redirecturl forcharacter emailemailapproutecharacter methodsget postdef character if requestmethod get return render templatecharacterhtml email requestargsgetemail password requestformpassword name requestformusername temp modelactorrequestformgender requestformheight requestformweight requestformphysique user modelusername email password temp dbsessionaddtemp dbsessionadduser dbsessioncommit return redirecturl formovieseverything else works just fine it is just that email is not being saved as and instead as nullthank you for your help ahead of timeedit solved using sessions in flask,['python'] +738434,what is the value of n under c compilers for old mac os backgroundin versions of mac os up to version 9 the standard representation for text files used an ascii cr carriage return character value decimal 13 to mark the end of a linemac os 10 unlike earlier releases is unixlike and uses the ascii lf line feed character value decimal 10 to mark the end of a linethe question is what are the values of the character constants n and r in c and c compilers for mac os releases prior to os xthere are at least two possible approaches that could have been takentreat n as the ascii lf character and convert it to and from cr on output to and input from text streams similar to the conversion between lf and crlf on windows systems ortreat n as the ascii cr character which requires no conversion on input or outputthere would be some potential problems with the second approach one is that code that assumes n is lf could fail such code is inherently nonportable anyway the other is that there still needs to be a thistinct value for r and on an asciibased system cr is the only sensible value and the c standard does not permit n r thanks to mafso for finding the citation 522 paragraph 3 so some other value would have to be used for rwhat is the output of this c program when compiled and executed under mac os n for n less than 10include stdiohint mainvoid printfn dn n printfr dn r if n r printfhmm this could be a problemn the question applies to both c and c i presume the answer would be the same for boththe answer could also vary from one c compiler to another but i would hope that compiler implementers would have maintained consistency with each otherto be clear i am not asking what representation old releases of mac os used to represent endofline in text files my question is specifically and only about the values of the constants n and r in c or c source code i am aware that printing n whatever its value is to a text stream causes it to be converted to the systems endofline representation in this case ascii cr that behavior is required by the c standard,"['c++', 'c']" +738499,create pystring from c character array without copying i have a large buffer of strings basically 12gb from a c appi would like to create pystring objects in c for an embedded python interpreter without copying the strings is this possible,"['python', 'c']" +738520,jenkins guide needed for build deploy provision and rollback keeping 5 releases i am pretty new to jenkins and have some sort of understanding but need guidance furtheri have a php application on a git repo that uses composer has assets has user uploaded media files uses memcacherethis has some agentsworkers and has migration filesso far i understood i need to create two jobs in jenkins job 1 buildjob 2 deployin the build job i setup the git repo as source and i setup a post shell script that has one single line composer update1 my first question relates to howwhere are the files cloned i understand there is a workspace and every time gets cloned there or only new things are pulled2 composer update seams to load again and again the same stuff and looks like it is not being cached with multiple builds i would love to hear the opinion here but i was expecting on the next build it will check for changes and get the diff only doing a full composer update takes several minutesin the deploy job i would love to setup a process that takes the most recent stable build and moves the files to a dedicated folder like releases2 then runs some provision scripting and in the end it updates the htdocs folder symlink to the new releases2 folder so the webserver starts to serve from this folder the website3 how can i get the latest build in the build folder i saw only a couple of log and xml files could not locate the files from git and move to a fresh destination4 how shall i setup the destination so that i can keep media files between different deploys5 when shall i deal with the assets like publishing to a cdn after successful build and before deploy is finished shall this be a prepost hook or a different job6 when shall i clear the caches memcache rethis7 how can i rollback to previous versions and how can i setup to keep last 5 successful releases8 how can i get email of failed build and failed deploy email alerts9 how can operations get a list of recents commit messages after a successful deploy by email i noticed jenkins has a lot of plugins not sure if these are handled by those plugins but feel free to recommend anything that gets these done i also read about phing but not sure what is and were shall i use iti understand there are lots of questions in this topic but if you know the answer for a few of them please post as answer,['php'] +738581,declaring main as friend considered harmful thiscussioni know that main can be a friend of a classinclude iostreamclass foo friend int main int i 4int main foo obj stdcout obji stdendllive demohowever i feel that although this is perfectably allowable it conceals many dangersquestionsare there any valuable uses in making main a friend of a classare there any reasons that declaring main as friend of a class should be considered harmful,['c++'] +738614,bootstrap 3 table inside a panel overflowing div classcolxs6 colsm4 div classpanel panelprimary div classpanelheadingrecently filtereddiv table classtable tablestriped trtdsensor idtdtdtemperaturetdtdvoltagetdtddatetd trtdsensor idtdtdtemperaturetdtdvoltagetdtddatetd trtdsensor idtdtdtemperaturetdtdvoltagetdtddatetd trtdsensor idtdtdtemperaturetdtdvoltagetdtddatetd table divdivthe table inside a panel is overflowing when i zoom in heres a picture example whats the proper mark up accommodating this problem i know that it can scale properly for sure,"['html', 'css']" +738710,is aa or aa undefined behaviour if a is not initialized consider this programinclude stdiohint mainvoid unsigned int a printfu un aa aa return 0is it undefined behaviouron the face of it a is an uninitialized variable so that points to undefined behaviour but aa and aa are equal to 0 for all values of a at least i think that is the case is it possible that there is some way to argue that the behaviour is well defined,['c'] +738749,temporarily set dbcontexts commandtimeout i know i can set the dbcontexts commandtimeout for all queries with something like thispublic class yourcontext dbcontext public yourcontext baseyourconnectionstring get the objectcontext related to this dbcontext var objectcontext this as iobjectcontextadapterobjectcontext sets the command timeout for all the commands to 2 min instead of the default 30 sec objectcontextcommandtimeout 120 however i want to keep the default 30 sec except for one single method that takes a bit longerhow should i change this for this single queryi did try to usepublic void dosomething the using had another reason but in this case it also automatically thisposes of the dbcontext usingimydbcontext delegatedbcontext iobjectcontextadapterusingdbobjectcontextcommandtimeout 120 myquery everything works perfectly until i run my unittest with a mockdbcontext and yes i did set my delegate to this mockdbcontext it gives me an invalidcastexceptionsysteminvalidcastexception unable to cast object of typecastleproxiesfakemydbcontextproxy to typesystemdataentityinfrastructureiobjectcontextadapter,['c#'] +738798,java 8 lambdas equivalent of c oftype i am learning the new java 8 features now after 4 years exclusively in c world so lambdas are on top for me i am now struggling to find an equivalent for cs oftype methodwhat i have is a list mynodes i want to get a list out of it where node is an interface and specificnode is implementing it in c it would beilistinode mynodes new listinodesnew specificnode new othernodeilistspecificnode specificnodes mynodesoftypespecificnode,"['java', 'c#']" +738815,replace references to a typenamespace using monocecil background unnecessary confusing only for the curiousi am using the free version of unity3d for mobile and it does not allow me to use the systemnetsockets namespace on mobile devices the problem is that i am using a compiled dll library namely ikvm that references the systemnetsockets i am not actually using the classes in ikvm that references that references systemnetsockets so instead of buying the 30 unity pro mobile licenses i made a stub library of the sockets namespace called dudeprgmnetsockets that just replaces all the classes and methods with stubs i did this using the mono source codemy problemi need to replace all systemnetsockets references in my dlls to dudeprgmnetsockets i know that something like this is possible and done by other peoplesee edit below at the bottom of the page i would like to know how to do it myselfi was able to come up with the following code using monocecilit goes through all the il instructions checks if the operand is an inlinetype then checks if the inline type is part of systemnetsockets then renames it to dudeprgmnetsockets and writes it i am not sure if this is the right way to go about findingandreplacing in monocecil problem is this does not catch all sockets usages see belowprivate static assemblydefinition stubsassemblystatic void mainstring args assemblydefinition asm assemblydefinitionreadassemblyargs0 stubsassembly assemblydefinitionreadassemblysocket stubsdll call procesockets on everything asmwriteargs1 this will be run on every property constructor and method in the entire dll given private static void procesocketsmethoddefinition method if methodhasbody monocollectionsgenericcollectioninstruction instructions methodbodyinstructions for int i 0 i instructionscount i instruction instruction instructionsi if instructionopcodeoperandtype operandtypeinlinetype string operand instructionoperandtostring if operandstartswithsystemnetsockets consolewritelinemethoddeclaringtype methodname uses type operand consolewritelinetinstruction instructionopcodetostring instructionoperandtostring instructionoperand methodmoduleimportstubsassemblymainmodulegettypedudeprgmnetsockets operandsubstring19 consolewritelinetreplaced with type dudeprgmnetsockets operandsubstring18 it works fine but only catches simple instructions decompiled with ildasm i can see where it replaced the types like herebox socket stubs2309dudeprgmnetsocketssocketoptionlevel01058but it did not catch these complex instructionscallvirt instance void system2303systemnetsocketssocket0103fsetsocketoptionvaluetype system2303systemnetsocketssocketoptionlevel01055 valuetype system2303systemnetsocketssocketoptionname01056 int32 0a094 now the dlls are a jumble of dudeprgmnetsockets and systemnetsockets referencesi am pretty sure that this is happening because i am only changing operandtypeinlinetypes but i am not sure on how else to do this i have tried looking around everywhere but it seems to me like monocecil has no way to set operands to a string everything seems to have to be done using the cecil api only sorry if i am using incorrect terms i am pretty new to il in generalquestionhow can i replace all places where systemnetsockets appear in monocecil rather than just where the operand is an inlinetype i do not really want to go through every operandtype there is in cecil i was just looking for some findandreplace method in cecil where i wouldnt have to work with plain il myselfedit also unnecessary confusing and only for the curiousthis person was able to do something similar for 25 ol sockets net sockets for mobile withoutautomatic patcher tool that detects and fixes socket usage in scripts and dll dlls are patched using monocecil you can go look at the second screenshot at content13166 and see that it says that it can replace namespacesthat library does not fit my needs because 1 it does not rename to the namespace i want dudeprgmnetsockets 2 the library that it is renaming to does not support all the systemnetsockets classes that ikvm needs because ikvm uses pretty much every sockets class and 3 it costs 25 and i do not really want to buy something that i am not going to use i just wanted to show that replacing namespacetype references in monocecil is possible,['c#'] +738853,python subprocesspopen check for success and errors i want to check if a subprocess has finished execution successfully or failed currently i have come up with a solution but i am not sure if it is correct and reliable is it guaranteed that every process outputs its errors only to stderr respectfully to stdoutnote i am not interested in just redirectingprinting out the output that i know already how to dopipe subprocesspopencommand stdoutsubprocesspipe stderrsubprocesspipe universal newlinestrueif pipestdoutreadline printsuccess selfiscommandexectutionsuccessful trueif not pipestdereadline printerror selfiscommandexectutionsuccessful truealternatively if pipestdoutreadline printsuccess selfiscommandexectutionsuccessful true else printerror selfiscommandexectutionsuccessful falseand if not pipestdereadline printsuccess selfiscommandexectutionsuccessful true else printerror selfiscommandexectutionsuccessful false,['python'] +739083,run a process asynchronously and read from stdout and stderr i have some code that runs a process and reads from the stdout and stderr asynchronously and then handles when the process completes it looks something like thisprocess process builderstart thread outthread new thread try bufferedreader reader new bufferedreadernew inputstreamreaderprocessgetinputstream read stream here catch exception e thread errthread new thread try bufferedreader reader new bufferedreadernew inputstreamreaderprocessgeterrorstream read stream here catch exception e outthreadstart errthreadstart new thread int exitcode 1 try exitcode processwaitfor outthreadjoin errthreadjoin catch exception e process completed and read all stdout and stderr here startmy issue is with the fact that i am using 3 threads to achieve this asynchronous runandgetoutput task i do not know why but i feel it does not feel right using 3 threads i could allocate the threads out of a thread pool but that would still be blocking those threadsis there anything i can do maybe with nio to reduce this to fewer 1 thread anything i can think of will be constantly spinning a thread unless i add a few sleeps which i do not really want to do eithernote i do need to read as i go rather than when the process has stopped and i do need to separate stdin from stderr so cannot do a redirect,['java'] +739193,using class with angular vs ngclass while using a mixed expression i have a div that i want to give a dynamic class with angularjsthe div is withing an ngrepeat statement where langprefix is first en then svusing the following code works and sets the class to iflagen than iflagsv but is it correctdiv classfloatleft flag iflaglangprefixdivi know there exist a ngclass directive which can be used to dynamically set the class of an element with angularjsi think i read somewhere in a book that the normal class directive not should be used to set the class property dynamically with angularjs because of the way angular manipulates the domhowever the following code does not workdiv classfloatleft flag ngclassiflaglangprefixdivand i rather want to set the class in this way instead of creating another scope variableis it bad practice to use the class attribute with angularjs to dynamically set the class does it work all the time even if it would be bad practice,"['javascript', 'css']" +739215,how to update a mongodb collection in meteorjs i have a collection that i need to update when the user presses a buttoni just need to change one variable to anotherin the console this line of code works dbusersupdateusername jackage 13 username jackbut when i put in this codetemplatebodyeventsclick updateage function alert meteorusersupdateusername jackage 13 username jack into my javascript file for meteorjs it does not do anything at all i do not get an error message and i see the alert but the update just does not worki have read through the meteor documentation on updating but i just cannot seem to get it to workdoes anybody know what i am doing wrong here,['javascript'] +739221,why am i getting no overload method for add takes 1 argument when adding a dictionary to a list of dictionaries sorry if this is basic i am a little new to c but why cant i add a dictionary to the list of dictionaries the documentation i have looked up does it like thislistdictionarystring string data new listdictionarystring stringdataaddnew dictionarystring string test,['c#'] +739296,how can i create this bar with a circle i am trying to create a style using css and html my style is like this i tried it and this is my html div classdownloadcontent div classdownloaditem div classdownloadfile div classfrontnumber1div pa hreffinancial ratio analysisap smallspan20130112spanspanformat power pointspansmall div div div this is my css downloadcontent downloaditem downloadfile background 027bc6 float right width 100downloadcontent downloaditem downloadfile frontnumber background none repeat scroll 0 0 0 border 5px solid f borderradius 50 color f float left fontsize 40px fontweight bold height 70px textalign center width 70pxit was so close to my expected result but not 100 js fiddle,"['html', 'css']" +739335,example communicating with handlerthread i want to set up a handlerthread from the gui thread then some time later when a button is clicked on the gui it runs callhello which then send a message to a hellologger object residing on the nongui thread which asynchronously logs hello world i have tried a number of things some block indefinitely some never receive the message etc etc the code below is more or less as close as i have got please could someone modify it to work public class handlerthreadexample private myhandlerthread mmyhandlerthread private looper mlooper private handler mhandler public handlerthreadexample mmyhandlerthread new myhandlerthread mmyhandlerthreadstart mlooper mmyhandlerthreadgetlooper public void callhello mhandlersendemptymessage1 private class myhandlerthread extends handlerthread private hellologger mhellologger private handler mhandler public myhandlerthread superthe myhandlerthread thread handlerthreadnorm priority public void run mhellologger new hellologger mhandler new handlergetlooper public void handlemessagemessage msg mhellologgerloghello superrun private class hellologger public hellologger public void loghello logdhandlerthreadexample hello world best examples foundhandlerthread testhow to create a looper thread then send it a message immediatelyasync calls with handlerhandlerthread vs executor when is one more appropriate over the otherbest use of handlerthread over other similar classesandroid handlerthreadhandlerthread examplesandroid passing data between main and worker threadsjava synchronisedsending messages between threads using activity thread queue and handler classintro to loopers and handlersdeveloperandroid specifying the code to run on a threadat least now i can close the damned tabssolution courtesy of help from pskinkpublic class handlerthreadexample2 private static int msg start hello 0 private static int msg hello complete 1 private handlerthread ht private handler mhthandler private handler muihandler private boolean helloready false public handlerthreadexample2 ht new handlerthreadthe new thread htstart logdapptag ui handler thread started muihandler new handler public void handlemessagemessage msg if msgwhat msg hello complete logdapptag ui thread received notification of sleep completed helloready true mhthandler new handlerhtgetlooper public void handlemessage message msg if msgwhat msg start hello logdapptag handlemessage msgwhat in threadcurrentthread now sleeping try threadsleep20 catch interruptedexception e eprintstacktrace logdapptag woke up notifying ui thread muihandlersendemptymessagemsg hello complete public void sendlonghello if helloready logdapptag sending hello threadcurrentthread mhthandlersendemptymessagemsg start hello helloready false else logeapptag cannot do hello yet not ready,['android'] +739449,how to delete thumbsdb it is being used by another process i have a simple console application that i am trying to delete a folderdirectorydeletefoldertruei got the exception of the annoying thumbsdbthe process cannot access the file thumbsdb because it is being used by another processi cannot change the registry to avoid thumbnail to process in folderwhat are my options here to be able to delete the folder with everything in itthanks,"['c#', '.net']" +739504,concept of and basic questions about separating logic c and gui qt i finished a project in c it is a console application created with codeblocks although i consider it not so important in the scope of this question the application manages data about bills and customers of a small company the program is complete and could be very easily expanded by a console user interface right now i run it as a programmernow i decided to learn gui programming using qt and the qtcreator with its qtdesignernot only because it is common practice to separate logic from gui when creating a gui application i want to put my project into practice in two big parts namely of course logic and guiyou already know that the logic part is complete what i have is a project folder called project containing another folder codeblocks project project logic which again contains several classes thus header files and implementation files and a main which will of course be obsolete eventually it also contains files frominto which the program readswrites it is written in pure c and uses none of the means provided by qt and it is important to me that it stays that waynow i added a qt project project gui into the projectfolder and started to create the gui implementing only the most basic functionality like changing between dialogues closing the application etc so far it knows nothing about its future backend project logicas a third component i need some kind of controlling which links the applications logic with its gui here comes my conceptual question what is the best way to put them together in one applicationsuggestionssince project logic could work alone as a console application it already provides the most essential controlling components and functions this will stay this way because i want to keep its standalone functionality even more so because i am totally new to gui programming andor in two weeks i could happen to create another gui for the same logic the result would be that the classes of the logic part are included in the gui source like any other header and used to create a program with full functionality validating user input would rest on the gui part the programs logic would in any case remain updatableto make the gui as reusable as possible should i implement a third component a la project controlling that provides interaction between gui and logic user input validation done by controlling in that each of the two remain as independent as possible gui not including headers of logic so to say but including controlling headersthe second point may sound a little bit weird i admit to put it short my aims arekeeping the project logic standard c and independent in terms of patching adding functionality etc andusing qt for gui at maximum at the same time reasonable separation of gui and logictrains of thoughtsshould i include the project logic headers via include project logicheader1h etc there may be a problem with using the classes which i will post in a separate questionshould i include them as a subprojecthow would i connect the parts in codedo the logic functions still find the files i mentioned earlier readwriteplease keep the following in mind i am new to gui programming and i gave my best to explain my thoughtsproblems however i know c and c and write console applications which i use for eg simulations at university and can handle the standard stuff quite well i reckon even if the potential answerer feels like suggesting a very different approach i would appreciate a solution for the concept i proposed the reason for that i explained in the introduction unnecessary to mention though that i am of course interested in hearing different suggestionsi decided to post the question after i did some research and tried my best in trial error fashion before there is a lot of information about this topic out there on stackoverflow and other boards so i wanted to present my idea and collect criticism and inputs rather than adding another how to to the hodgepodge of questionssince this question is about the general approach i will maybe quite sure p ask more technical questions later which i would like to edit into this question hyperlinks as soon as they arisehowever basic recipes in this matter if available are welcomed of courseafter some comments and answers i feel like posting a little edit just to make things clearcurrent status of logicproject logic is more or less finished and coded in codeblocks as a codeblocks projectit could work as a console application with console user interface it has a maincpp which is now only used for debuggingits components are divided in classes headers and cpp implementation files as much as possiblecurrent status of guiproject gui is being set up as a qtwidgetapplication project using qtcreatordesignerso far it is only gui an nothing more no connection to project logic in any wayaims and the workflow i want to follow since this is my first big projectproject logic and project gui would not leave their respective directories they both are in a directory called project exception logic will be exported as a dll or something similar if necessary which is then provided to the guiif there were things to be changed in the project logic i want to do so in codeblocks and repeat a possible export as described aboveproject logic or any third layer like for instance project controlling have to be made thisposable for project gui in the most easiest fashion imaginable see trains of thoughts number 1 p,['c++'] +739505,nonblocking io vs async io and implementation in java trying to summarize for myself the difference between these 2 concepts because i am really confused when i see people are using both of them in one sentence like nonblocking async io which i am trying to figure out what does it meanso in my understanding nonblocking io is primary the os mechanism to process the io if there is any data ready otherwise just return errordo nothing in async io you just provide a callback and your application will be notified when the data is availableso what is actually nonblocking async io and how all them can be implemented in java standard jdk without external libs i know there are javaniochannelschannels selector selectorkey and javaniochannelsasynchronoussocketchannel nonblocking io async io and nonblocking async io if there is such thing,['java'] +739659,check if userdefault exists swift i am trying to check if the a user default exists seen belowfunc useralreadyexist bool var userdefaults nsuserdefaults nsuserdefaultsstandarduserdefaults if userdefaultsobjectforkeykuserid return true return falsehowever no mater what it will always return true even when the object does not exist yet is this the right way for checking existence,['ios'] +739698,cannot assign to a parameter i have declared a functionfunc somefunctionparametername int parametername 2 cannot assign to let value parameter name var a parameternameand trying to assign it a value during runtime but it gives me errorcannot assign to let value parameter nameis the parameter name constant by default can i change it to a variablethanks in advancepriyanka,['ios'] +739768,brackets live preview not working i found this awesome programhtml editor called brackets and it is by adobenow reason why i got the editor was because i wanted to live preview php code but i found out later that i needed a wamp server now i was in the mood of making an about page but i could not live preview live preview base url is empty and when i try to live preview i get this and the lightning bolt is half orangei heard it needs to be red to work i have tried the lot entering as live preview base url to httpsemicolonlocalhostinsertporthere wamp server tried only localhost left it empty i do not know how to make this work i am stuck and i basically need real previewplease please help me d i have searched the internet looking for solutions but no if you can a stepbystep tutorial would be much appreciated kind regards pigufilms,"['html', 'css']" +739844,why does not css feature work in browser but works in others i tried using transition on firefox 15 and it did not work even though it worked on other versions of firefox and other browsers like chrome and safari when i view the properties using firefoxs inspector the transition is struck through and gives an error of invalid property value mdn and caniuse say it is supported on firefox 4 and abovemydiv transition width 1s did i do this wrong background f00 width 100px height 100pxmydivhover width 200px how come sometimes properties like transition and animation work in some browsers and are invalid in othersthisclaimer this is the canonical duplicate for all questions solvable completely by adding vendor prefixes stack overflow questions should not be this broad unless thiscussed on meta and a canonical answer created thereafter like this one was,['css'] +739914,how to set environment variables from within packagejson nodejs how to set some environment variables from within packagejson to be used with npm start like commandshere is what i want to achievepackagejson scripts help actionhero help start actionhero start startcluster actionhero startcluster workers1 actionhero actionhero here i want to set environment variables like node env and others in start script section and i want to start app with just one command npm start,['javascript'] +740041,how to export data from 3 tables in one csv file php i want to export the data from the 3 tables without joins in one csv filei am trying with joins but i am not getting the result which i wantbelow are my table structureplaylist songs ratingcodemysql host db hostmysql user db usermysql pass db passwordmysql db db namepre wpdbprefixlink mysql connectmysql host mysql user mysql pass or diecould not connect mysql errormysql select dbmysql db link or diecould not select database mysql dbquery select plist psong prate from pre foo playlists as plist left join pre foo songs as psong on plistplaylist name psongsplaylist name left join pre foo rating as prate on psongsong id pratersong idresult mysql queryqueryrow mysql fetch assocresultline comma foreach row as name value line comma str replace name comma line n out line mysql data seekresult 0 while row mysql fetch assocresult line comma foreach row as value line comma str replace value comma line n outline csv file name songs dateymd his csv csv file name will be table name ymmdd hhmmsscsv headercontenttype textcsv headercontentthisposition attachment filename csv file name headercontentdescriptionfile transfer headercontenttransferencoding binary headercachecontrol mustrevalidate postcheck0 precheck0 headerpragma public headercontenttype applicationoctetstream echo out foo exiti got this result with i want this desired resulthow can i do this,['php'] +740062,how can i createfind in mongoose sometimes i need a document to exist in the db and am happy to either work with the existing document or create the document if it is missing and work with the new onethis seems like a fairly common use case but i have looked through the mongoose docs and i cannot find anythingmongoose collection methods like findoneandupdate and update with upsert true are about modifying documents i do not wish to modify the document if it exists just get a reference to it example added for neillunn i want to add a user with a reference to a company whose name is foo before that i would like to lookup a company with name foo and create that if it does not existexample 2 added for neillunn code i am using now to handle the example scenario find or create an an instance and return a cb with a reference to itvar findorcreate functionmodel criteria cb modelupdatecriteria criteria upsert true functionerr numberaffected raw if rawupdatedexisting consolelogcreated instance else consolelogfound existing instance modelfindonecriteria cb note findoneandupdate would not work because it will try and modify the existing document and get a duplicate key error index,['javascript'] +740087,flow of program execution during thread creation i am new to threadsi have written a sample program to create a threadincludestdiohincludestdlibhincludelimitshincludestringhincludepthreadhvoid funcvoid temp printfinside functionn return nullint main pthread t pt1 printfcreating threadn pthread creatept1nullfuncnull printfinside main created threadnreturn 0after compilation the answer is found to be creating threadinside main created threadinside functioninside functioni understand that answer may vary as return 0 may be called before the printf in func is executedbut how come in the solution inside function is printed two timeson compiling with gcc o temp thread1c lpthreadon first runcreating threadinside main created threadon second runcreating threadinside main created threadinside functioninside functionon compiling with gcc pthread o temp thread1con first runcreating threadinside main created threadinside functioninside functioni have observed this behavior ongcc version 443 ubuntu 4434ubuntu5kernel release263224genericglib version21,['c'] +740107,multitenancy in ef6 with multiple schemas having the same tables in our system it has become required to provide a multitenant solution where each tenant has the same data structureduring investigation i came across an article thiscussing multitenancy with ef41this looks like a sensible solution but we would prefer to avoid multiple database contexts if possiblealso we have a large number of migrations for our current single tenant solution with ef6 it is possible for a migration to target a specific context and when none is supported a default is targetedi have a couple of quesions hereis there a better approach to multitenancy when using ef6 other than that specified for ef4is there a better way to handle the migrationsany help is much appreciated,"['c#', '.net']" +740122,difference between oncreateview and onviewcreated in fragment whats the essential difference between these two methods when i create a textview should i use one over the other for performanceeditwhats the difference fromoncreateview root some view view v new viewsome context rootaddv return rootonviewcreated view v new viewsome context getviewaddv,['android'] +740233,how to stop after cordova run ios what is the command to stop running after using cordova run ios in terminali found one topic about this with 1 answer saying it is quit but that did not work right now i close terminal every time which is very time consumingif i press ctrlc i get the followinglldb ctraceback most recent call last file privatetmpfruitstrap py line 17 in connect command event lldbsbevent file applicationsxcodeappcontentssharedframeworkslldbframeworkversionsaresourcespythonlldbinitpy line 3395 in init this lldbnew sbeventargs keyboardinterrupt error the platform is not currently connected executing commands in tmpfruitstraplldbprepcmds lldb platform select remoteios sysroot usersdoekewartenalibrarydeveloperxcodeios devicesupport712 11d257symbols platform remoteios connected no sdk path usersdoekewartenalibrarydeveloperxcodeios devicesupport712 11d257symbols lldb target create usersdoekewartenadocumentsjbc2014platformsiosbuilddevicejbc2014app current executable set to usersdoekewartenadocumentsjbc2014platformsiosbuilddevicejbc2014app armv7 lldb script fruitstrap device aprivatevarmobileapplicationse23498af29c54a9f8afb65631db725jbc2014app lldb script fruitstrap connect urlconnect12700112345 lldb command script import tmpfruitstrap py lldb command script add f fruitstrap connect command connect lldb command script add s asynchronous f fruitstrap run command run lldb command script add s asynchronous f fruitstrap autoexit command autoexit lldb connect lldb run,['ios'] +740347,how to keep animated gifs animated while scrolling on ios devices i know this has been asked before but i am still not convinced there is not a workaround the reason i am not convinced is because i managed to keep those gifs animated on a website of mine by accident i posted this in the chat here and with help from carriekendall came up with this fiddlethis is obviously not a proper solution so i wanted to post it here for you geniuses to pick apart and try to help me figure out how i can fix this problem in a way that preferably is not too resource heavyupdateok so i tinkered a bit more with the jsfiddle and came up with thishtmlimg classlink srcimg classlink srcimg classlink srccsswebkitkeyframes wiggle 0 webkittransform translate0px 0px 100 webkittransform translate0px 0px keyframes wiggle 0 webkittransform translate0px 0px 100 webkittransform translate0px 0px link webkitanimation wiggle 1ms animation wiggle 1msit is strange but it works an animation that does absolutely nothing oh and i tried replacing translate with something like scale but that did not do the trick this is the purest form of this weird bugsolutionthat said though i am not quite satisfied yet i would love it if someone more knowledgeable than me could have a look at this and try to figure what is really going on that makes this workaround work hopefully there is something in here that can be used albeit in a more elegant wayalso i have no idea how resource intensive something like the above workaround would be so if someone could help me measure that that would be awesome,"['ios', 'css']" +740397,servlet has started a thread but failed to stop it memory leak in tomcat apache tomcat says many timesthe web application myservlet appears to have started a thread named pool61thread2 but has failed to stop it this is very likely to create a memory leakis this dangerous the servlet should be able to handle 10requestsdayhow to close the threads when they have finishedclass worker private final countdownlatch startsignal private final countdownlatch donesignal private final int threadnumber worker countdownlatch startsignal countdownlatch donesignal int threadnumber thisstartsignal startsignal thisdonesignal donesignal thisthreadnumber threadnumber public string getsomestrarrarr string isrs new string820 string inrs new string820 string iwrs new string820 try startsignalawait if threadnumber 1 get string result for thread number 1 isrs getiserg1 erg2 request if threadnumber 2 get string result for thread number 2 inrs getinsearch plz request if threadnumber 3 get string result for thread number 3 iwrs getiwerg1 erg2 request donesignalcountdown catch interruptedexception ex systemoutprintln thread number threadnumber has been interrupted if threadnumber 1 return isrs if threadnumber 2 return inrs if threadnumber 3 return iwrs return null public callablestring getsomecallablestrarrarr return new callablestring public string call throws exception return getsomestrarrarr executorservice pool executorsnewfixedthreadpool3 setfuturestring set new hashsetfuturestring countdownlatch startsignal new countdownlatch1 countdownlatch donesignal new countdownlatch3 for int i1i3i worker worker new workerstartsignaldonesignali callablestring callable workergetsomecallablestrarrarr futurestring future poolsubmitcallable setaddfuture startsignalcountdown try donesignalawait,['java'] +740400,saving coredata tomany relationships in swift i have a onetomany relationship that looks like soi have set up my model classes in a file to matchimport coredataimport foundationclass board nsmanagedobject nsmanaged var boardcolor string nsmanaged var boardcustombackground anyobject nsmanaged var boardid string nsmanaged var boardname string nsmanaged var lists nssetclass list nsmanagedobject nsmanaged var listid string nsmanaged var listname string nsmanaged var board boardbecause i am fetching data from multiple json endpoints i have to save my lists seperately from my boards what i want to do is createupdate a list for a board with a matching boardidheres where i am after multiple attemptsfunc savelistboardid string listname string listid string let request nsfetchrequestentityname board var error nserror nil requestpredicate nspredicateformat boardid like boardid let results nsarray contextexecutefetchrequestrequest error error if resultscount 0 for result in results let board result as board let list nsentitydescriptioninsertnewobjectforentityfornamelist inmanagedobjectcontext context as list printlni 12i2 want to save listname in boardboardname boardlistsaddlistobjectlists listlistname listname listlistid listid based on defining coredata relationships in swift and this i tried to implement keenles answer for define list objects inside a boardimport foundationextension board func addlistobjectvaluelist var items selfmutablesetvalueforkeylists itemsaddobjectvalue func removelistobjectvaluelist var items selfmutablesetvalueforkeylists itemsremoveobjectvalue however i ran into the following error at boardlistsaddlistobjectlistsnsset does not have a member named addlistobjectinstead of boardlistsaddlistobjectlists i also tried boardlistslistname listname as implied in this objc example but that sadly did not work eitheralso the println output is correctly specifying the right board and listthanks in advance,['ios'] +740478,mixing two audio streams into a single audio stream in android i am trying to mix two audio streams to get a single output stream is it possible in android in my case i have one input stream coming from microphone ie i am recording the users speech using audiorecord i want to mix this recording with a short sound clip and then create a new stream which is a mix of both the stream and then send it over a datagram socketi have researched a lot and here is what i came to knowfirstly soundpool may help me achieve my goal but i think i cannot provide microphone as input sourcecurrently i am saving the recording from mic in a buffer and then streaming it over the datagram socket i thought i can save the sound clip in another buffer and then add both the bufferwhich i know is dumb a idea as there are various properties of sound that i will have to managealso may be i can save the recording from microphone to a file and the recording of sound clip to a different file and mix them however i think i cannot do this as i am trying to stream the recording over the datagram socketi think what i am trying to achieve may be possible using javas sound api but it is not supported by android to summarize what i am trying to achieve as my end goal is to inject a sound effect in a voip sip based call sound effect like crickets sound along with my voicei hope i gave a clear explanation about my problemquestion 1 how can i achieve thisquestion 2 can i create a jar file using javas sound api and use it in my project about this i think it is not possiblehere is some code of my audio recording and audio playbackthis is my code for audio recording public void run todo autogenerated method stub try int minbuffer audiorecordgetminbuffersizesample config format datagramsocket socket new datagramsocket logdtag socket created socketsetbroadcasttrue byte ubuff new byteminbuffer datagrampacket packet logdtag packet created inetaddress dest inetaddressgetbyname10101126 inetaddress dest inetaddress inetsocketaddress dest new inetsocketaddresshost port logdtag addressdest rec new audiorecordmediarecorderaudiosourcemicsample configformatminbuffer recstartrecording whilestatus true minbuffer recreadubuff 0ubufflength logdtag reading while packet new datagrampacketubuff ubufflengthdestport socketsendpacket catchexception e logdtag bad datagram streamstart this is my code for audio playback override public void run todo autogenerated method stub try androidosprocesetthreadpriorityprocessthread priority urgent audio audiomanager mm audiomanagergetsystemserviceaudio service datagramsocket rsocket new datagramsocket8080 logdtag recive socket int m buf audiorecordgetminbuffersizesample config format byte buff new bytem buf audiotrack rspeaker new audiotrackmmstream musicsampleconfig formatm bufaudiotrackmode stream mmsetspeakerphoneonfalse mmsetstreamvolumeaudiomanagerstream music 100 audiomanagermode in communication logdtag zzrecorder rspeakersetplaybackratesample rspeakerplay whiletrue try datagrampacket rpacket new datagrampacket buff bufflength rsocketreceiverpacket buff rpacketgetdata rspeakerwrite buff 0 m buf logdtag yo start write catchexception e catchexception e rvstrmstart,"['java', 'android']" +740718,how to highlight the filtered text while using searchview widget in android i have implemented searchview widget in my app its working fine now i need to do is whenever i type a word in my searchview bar the filtered result should show the searched word highlighted like i am using this searchview widget as overridepublic void oncreateoptionsmenumenu menu menuinflater inflater inflaterinflatermenumymenu menu menuitem searchitem menufinditemridaction search searchview sv new searchviewgetactivity changing the color of searchview widget text field to white int searchsrctextid getresourcesgetidentifierandroididsearch src text null null edittext searchedittext edittext svfindviewbyidsearchsrctextid searchedittextsettextcolorcolorwhite svsetonquerytextlistenerthis searchitemsetactionviewsv superoncreateoptionsmenumenu inflater,['android'] +740752,building interfaces for 35inch iphones in xcode 6 in xcode 6 the way layout is done for devices of varying sizes has been changed somewhat we now have size classes but how can i lay an interface out for a 35inch iphone the compact height class does not seem to apply here i understand i can change the constraint compression resistance etc values but in my case i want to be able to change the font size for this device sizeis this completely impossible i realize ios 8 removes support for iphone 4 but not 4s we also cannot all target purely ios 8 and need to support 7 and even 6,"['ios', 'objective-c']" +740813,afnetworking http delete use body instead of url i am trying to send a http delete request to a restful django web service from my ios appi use afnetworking 20 24 after analysing the afhttprequestoperation in the success block of my api call i found that the body of the request is nil the parameters url encoded and sent in the url afhttprequestoperation 0x10c587940 state isfinished cancelled no request nsmutableurlrequest 0x10c521ab0 url response nshttpurlresponse 0x10c5c7590 url anurlcomconnectionsdata5bconnections5d5b5d5bid5d106 status code 200 headers connection keepalive contenttype applicationjson date tue 05 aug 2014 140753 gmt keepalive timeout5 max100 server apache247 ubuntu transferencoding identity now i wonder if it is possible to send the parameters in the body of the request as done with http post instead of sending them in the url is that possiblehow to do it using afnetworkinghow i send atmafhttprequestoperationmanager manager afhttprequestoperationmanager managermanagerrequestserializer afjsonrequestserializer serializermanager deletehost url parametersparams succesuccess failurefailurethe body i want to sendits whats in the params parameter above data connections id 92 id 91,['ios'] +740837,xdomainrequest vs xmlhttprequest we are creating an application using pixijs which has a dynamic json loader in it it loads the json files using the followingifwindowxdomainrequest thisajaxrequest new windowxdomainrequestelse if windowxmlhttprequest thisajaxrequest new windowxmlhttprequestelse thisajaxrequest new windowactivexobjectmicrosoftxmlhttpwhich seems to work everywhere except on windows phone and iehowever if i swap xmlhttprequest with xdomainrequest it works fineso finally can someone please explain the differences between xdomainrequest and xmlhttprequest which one should take precedence over the other,['javascript'] +740851,opencv open mobotix camera feed i have a mobotix camera it is an ip camera in the api they offer us the possibility to get the feed viahttp userpasswordip adressportcgibinfaststreamjpgoptionswhat i have tried is to open it like a normal webcam feed cvvideocapture capturehttpcvmat frameif captureisopened always false anywaywhile1 capturereadframe cvimshowhi there frame cvwaitkey10fyi developer mobotix api docsedit now thanks to berak i just had to add datavmjpg to the options streamfullfps50noaudiodatavmjpgnote that in vmjpg only the dotmjpg is important you could as well put myfilemjpgnow the problem is the speed at which the feed update i got a 2 seconds delay plus the feed is very very slow and when i change the stream option for mxjpg or mxg i get a corrupted image where the bytes are not ordering properllyedit i tried to change the camera parameters directly with the mobotix control center but only the resolution affected my opencv program without actually changing the speed at which i access the images,['c++'] +740865,why do i need a factorysupplier in the project i am working on not my project just working on it there are many structures like thisprojectprivlogicmyserviceimpljavaprojectprivservicemyservicefactoryimpljavaprojectpublogicmyserviceifjavaprojectpubservicemyservicefactoryifjavaprojectpubservicemyservicefactorysupplierjavaand the service is called like thismyservicefactorysuppliergetmyservicefactorygetmyservicei understand that a factory is used to hide the implementation of myserviceimpl if the location or content of myserviceimpl changes but why is there another factory for my factory the supplier i think the probability of my factory and my factorysupplier to change is roughly equal additionally i have not found one case where the created factory is created dynamically i think this would be the case in the abstract factory pattern but only returns myservicefactoryimplgetinstance is it common practice to implement a factorysupplier what are the benefits,['java'] +740915,implicit conversion from class to enumeration type in switch conditional g 490 accepts the following codeenum e foo struct c operator e const return foo operator e return foo int main c c switch c case foo break but clang 341 rejects it with the following diagnostic12 error multiple conversions from switch condition type c to an integral or enumeration typeswitch c 5 note conversion to enumeration type eoperator e const return foo 6 note conversion to enumeration type eoperator e return foo which one is correct is it a clang bug g bug libstdc bug standard defect or other did i do something stupidin the code which triggered this question c is stdatomice and stdatomictoperator t is overloaded on the cvqualifiers const and const volatileboth compilers accept e e c so it seems to be something peculiar to the switch statement,['c++'] +740932,presenting view controllers on detached view controllers is thiscourage i am using xcode 511 with storyboard i have a button on main menu and it pops to another view controller with this codevc secondvc vc alloc initself presentviewcontrollersecondvc animatedyes completion niland there i have back button with this codeself thismissviewcontrolleranimatedyes completion niland when i pop to secondvc xcode gives me is errorpresenting view controllers on detached view controllers is thiscourage uinavigationcontroller 0x8c94510i am also having problem with rotation it does not work properly,['ios'] +741016,python convert back slashes to forward slashes i am working in python and i need to convert thiscfolderafolderb to cfolderafolderbi have three approachesdir sreplacedir pathosnormpaths dir pathosnormcasesin each scenario the output has beencfolderafolderbi am not sure what i am doing wrong any suggestions,['python'] +741135,get hours difference between two dates in moment js i am able to get the difference between two dates using momentjs as followsmomentenddiffstarttimeformatmm sshowever i also want to thisplay the hour when applicable only when 60 minutes have passedhowever when i try to retrieve the duration hours using the followingvar duration momentdurationenddiffstarttimevar hours durationhoursit is returning the current hour and not the number of hours between the two dates how do i get the difference in hours between two moments,['javascript'] +741137,mongoerror cannot extract geo keys from object with type point i try to prepare my database field for geocoding with thismycollection ensureindexdataaddresslocated2dspherebut then this error comesmongoerror cannot extract geo keys from object malformed geometry type point coordinates 324586858 1108571443 i can not see whats wrong with this field any idea when i take a look to this it shows up thisthe following example stores a geojson point loc type point coordinates 40 5,['javascript'] +741164,what functions or codes require get tasks permission in android i think the get tasks permission is an orphan line in my androidmanifestxml i want to remove it safely do you know any function or code that requires this permission thank youusespermission androidnameandroidpermissionget tasks,['android'] +741211,angularjs put binary data from arraybuffer to the server ok so i try to read a pdf file like this readerreadasarraybufferfileand then try to send it to the server using http like thishttpputurl data headers contenttype applicationpdfso just read send the binary to the server in raw form according to some resources i found passing an arraybuffer to xhr should work but passing it as data to http just results in a request body like this and contentlength2reading the file readasbinarystring results in a corrupted file and is apparently deprecated for that very reasonthe use case seems so trivial to me am i missing somethingchrome 36 angular 1220,['javascript'] +741221,how to implement fifo in sql i working on fifo implementation in sqli have batch number concept in my applicationif suppose i am selling on inventory then my application should tell me that which inventory is the first comelets say i purchased inventory a on 4thaug 5thaug 6thaugon 4th aug a inventory has batch number bt002 10 qtyon 5th aug as inventory has batch number bt003 15 qtyon 6th aug as inventory has batch number bt001 10 qtyso now i am having stock now in my hand as following a inventorybt002 10 4augbt003 15 5augbt001 10 6augnow if i want to sell that inventory to anybody then my application should tell me that i should sellbt002 batch number inventory first beacause it came firstthat was the concept i am using in my applicationnow i want to sell 15 qty from a inventorythen op should be like this bt002 10bt003 5heres my query select isnullsumqty0 as qtybatch noaccept date from rs gin master group by batch noaccept datehaving isnullsumqty0 15order by accept date ascop of given query how can i get op like this bt002 10bt003 5any help will be appreciatedthank you in advance,['sql'] +741235,expose the const and nonconst versions of begin and end to iterate member vector with smart pointer cath class catpublic void const meow const void meow class catlibrarypublic stdvectorstdshared ptrcatiterator begin return m cat listbegin compile error the compiler complains cannot covert type from stdvectorstdshared ptrcatconst iterator to stdvectorstdshared ptrconst catconst iterator stdvectorstdshared ptrconst catconst iterator begin const return m cat listcbegin private stdvectorstdshared ptrcat m cat list maincppcatlibrary cat library cat libraryaddstdmake sharedcatcat libraryaddstdmake sharedcatforauto cat cat library catconst meow catmeow forconst auto cat cat library catconst meow catmeow hope to compile error due to invoking non const method of catconst catlibrary const cat library cat library forauto cat const cat library catconst meow catmeow hope to compile error due to invoking non const method of catconst catlibrary const cat library cat library forconst auto cat const cat library catconst meow catmeow hope to compile error due to invoking non const method of cati want my catlibrary expose the nonconst begin and nonconst end in which a client can iterate the smart pointer pointing to the mutable cat and the const begin and const end return the iterator which points the immutable onethen when the client iterates the const catlibrary i would not worry he could modify the content of cat in librarybut the const added to my member function begin only qualifies the pointer to be a const pointer not the cat it pointswithout the pointer involved the vector with constness makes the iterator point to a element with constness also but i want this effect also applies the element pointed by smart pointeri have a approach to solve my problem but i am not sure what problems would happen in future usemaintain two vectors in const and nonconstinclude iostreaminclude memoryinclude vectorclass catpublic void const meow const stdcout meow stdendl void meow stdcout meow stdendlclass catlibrarypublic void addstdshared ptrcat cat m cat listpush backcat m cat const listpush backcat stdvectorstdshared ptrcatconst iterator begin return m cat listbegin stdvectorstdshared ptrconst catconst iterator begin const return m cat const listbegin stdvectorstdshared ptrcatconst iterator end return m cat listend stdvectorstdshared ptrconst catconst iterator end const return m cat const listend private stdvectorstdshared ptrcat m cat list stdvectorstdshared ptrconst cat m cat const listint main catlibrary cat library cat libraryaddstdmake sharedcat cat libraryaddstdmake sharedcat cat libraryaddstdmake sharedcat const catlibrary const cat library cat library forauto cat cat library catmeow return 0or is there another solution to solve this kind of constness problem on smart pointer in vector,['c++'] +741324,validating uk phone number regex c public static bool validatephonenumberstring number return regexmatchnumber 44s7d307d3sd3sd3 regexoptionsignorecasesuccessthis is what i have but i get errors saying unrecognized escape sequence can anbody help needs to be able to have 44,['c#'] +741366,make wpf app accessible to screen reader i have a wpf application and part of the requirements are that it is accessible including keyboard navigation and screen readersi have had some success with a a treeview in the application by setting the automationpropertiesname in the itemcontainerstyle of the treeview but i am having problems with a window that contains a text area and some buttonszoomtext will correctly read out the title of the window but do so twice as well as the text in the buttons but i cannot get it to read the contents of the textblockthe text block is defined in a window as below there are no binding errors showing up in the visual studio output while debugging and the nvda screen reader can read the content correctly although this is not good enough for me as the customer uses zoomtextwindow xclassusercontrolsmodaldialog xmlns xmlnsx xmlnsmc xmlnsd mcignorabled ddesignheight160 ddesignwidth400 minheight85 minwidth400 maxwidth400 sizetocontentheight heightauto windowstartuplocationcenterscreen resizemodenoresize titlebinding titletext dockpanel widthauto margin2020010 stackpanel orientationvertical stackpanel orientationhorizontal textblock textbinding pathdialogtext modetwoway cursorarrow focusabletrue textwrappingwrapwithoverflow heightauto width325 textoptionstextformattingmodethisplay tooltipbinding pathtext relativesourcerelativesource self automationpropertiesnamebinding pathtext relativesourcerelativesource self automationpropertiesautomationidbinding pathtext relativesourcerelativesource self textblock stackpanel stackpanel orientationhorizontal horizontalalignmentright margin01050 button contentbinding pathoption1buttontext modetwoway padding5050 margin02050 minwidth100 isdefaulttrue commandbinding pathoption1buttoncommand modetwoway button contentbinding pathoption2buttontext modetwoway padding5050 margin220100 minwidth75 commandbinding pathoption2buttoncommand modetwoway visibilitybinding option2buttonvisibility modetwoway button contentbinding pathcancelbuttontext modetwoway padding5050 margin220100 minwidth75 iscanceltrue visibilitybinding cancelbuttonvisibility modetwoway stackpanel stackpaneldockpanelif anyone has had any success with wpf and screen readers and has any insight or can point me in the right direction it would be greatupdateit seems the problem is because the textblock is within another element if the window has the textblock as it is only element the screen reader reads the text correctly however i need the dock and stack panels for layout so i need to find a way to get the screen reader to work when the textblock is not the only content in the window,['c#'] +741419,convert iso date to date format ymmdd format in javascript how can i get date having format ymmdd from iso datemy iso date is 20130310t020zhow can i get20130310,['javascript'] +741427,rake dbsetup results in fe sendauth no password supplied when i run rake dbsetup i get fe sendauth no password suppliedcould not create database for adapterpostfresql encodingunicodehostlocalhost pool5 usernamemy user passwordnil databasemy db test enable extensionplpgqslrake abortedtasks top dbschemaloadmy databaseymlconnection connectionadapter postgresqlencoding unicodehost localhostpool 5username my userpassworddevelopment connection database my db developmenttest test connection database my db testalready change my pg hbaconf like in this question trying to set up postgres for ror app getting error fe sendauth no password suppliedbut it not help at all,"['ruby-on-rails', 'ruby']" +741442,java 1718 jit compiler broken i have a problem with some code from glazedlist 18 that causes a sigsegv when running under java 18 0564 bitfc20 windows 8i have the thisassembled output xxunlockdiagnosticvmoptions xxcompilecommandprintboyermoorecaseinsensitivetextsearchstrategyindexof see below but i no clue on how to debug itso any help with debugging the code or a hint to where to ask for help is appreciated the thisassembled code is more than 30 chars long so you will have to go here pagecomatlassianjirapluginsystemissuetabpanelscommenttabpanelcomment378982 to read the codea fatal error has been detected by the java runtime environmentsigsegv 0xb at pc0x07fdc2d93bcfc pid12092 tid140582414018304jre version javatm se runtime environment 80 05b13 build 180 05b13 java vm java hotspottm 64bit server vm 255b02 mixed mode linuxamd64 compressed oopsproblematic frame j 12756 c2caodellglazedlistsimplfilterboyermoorecaseinsensitivetextsearchstrategyindexofljavalangstringi 147 bytes 0x07fdc2d93bcfc 0x07fdc2d93baa00x25c,['java'] +741454,decode mp4h264 using mediacodec without mediaextractor expected access unit format i am trying to use the mediacodec api for decoding without using the mediaextractor api instead i use mp4parser to get the samples from the mp4 files for now i am only using h264 avc coded video contentthe official documentation of the mediacodec api statesbuffers do not start and end on arbitrary byte boundaries this is not a stream of bytes it is a stream of access unitsmeaning i have to feed access units to the decoder however i miss some details in this informationfor h264 in an mp4 sample there can be multiple nal units that are each preceded by 4 default bytes specifying the nal unit lengthnow my questionsthere can be mp4 samples where codec config nal units sps pps are mixed with nal units containing coded parts of frames in that case should i pass the flag buffer flag codec config at the call of queueinputbuffersthere can also be other additional nal units in mp4 samples like sei or access unit delimiter nal units what about those no problemi tried different kinds of possibilities but all the feedback i get from android is that the calls of dequeueoutputbuffer time out or do not return if i pass 1 as timeout parameter as a result i do not seem have a way to troubleshoot this issueany advice what to do or where to look is of course very welcome as well,['android'] +741536,how do i configure intellij for a fullstack javascript web app i am building a web application using a mean stack mongodb express angular and nodejs based on daftmonks angularfullstack yeoman generatormy preferred ide is intellij idea partly because i also work on rubyrails java etc and partly because it is fing bads and i love itwhats the best way to configure it for this project,['javascript'] +741555,hibernate override lazyfalse i am working on a new module in an existing project the project already has a user table a pojo and a corresponding mapping file the problem is that they are fetching all the properties eagerly by mentioning lazyfalse but in my module i am doing lot of read write in a single request so i do not want to fetch eagerly what i want to know is that is it possible to create an another mapping file for the same table same pojo to load all the properties lazily i have tried by assigning different entityname for the mapping files but while deploying i am getting the error repeated column in mapping for entityi saw this answer but it says do not map child then how will i get the proxies,['java'] +741587,there is an example of spyne client i am trying to use spyne in my server with zeromq and msgpack i have followed the examples to program the server side but i cannot find any example that helps me to know how to program the client sidei have found the class spyneclientzeromqzeromqclient but i do not know what it is supposed to be the app parameter of its constructorthank you in advanceeditthe simplified serverside codefrom spyneapplication import applicationfrom spyneprotocolmsgpack import messagepackrpcfrom spyneserverzeromq import zeromqserverfrom spyneservice import servicebasefrom spynedecorator import srpcfrom spynemodelprimitive import unicodeclass radianterpcservicebase srpc returnsunicode def whoiam return hello i am seldonradiante rpc application radianterpc tnsradianterpc in protocolmessagepackrpcvalidatorsoft out protocolmessagepackrpcs zeromqserverradiante rpc tcp1270015001sserve forever,['python'] +741642,angularjs with serversent events i have an angularjs app with the following controller it worked fine with get on regular json resource and manual request for updates but i cannot make it work with serversent events the problem i am facing is that after i receive an sse event and setupdate openlistingsreport variable my view is not getting updated i am obviously missing a very basic concept please help me fix thisvar rpctrl angularmodulerpctrl rpsvcrpctrlcontrollerrpopenlistingsctrl scope rpopenlistingssvc function scope rpopenlistingssvc scopeupdating false if typeofeventsource undefined yes serversent events support var source new eventsourcelistingsevents sourceonmessage function event scopeopenlistingsreport eventdata scopeapply consolelogscopeopenlistingsreport else sorry no serversent events support alertsse not supported by browser scopeupdate function scopeupdatetime datenow scopeupdating true rpopenlistingssvcupdate scopereset function scopeupdating false,['javascript'] +741785,swift framework with libxml i have swift framework project that uses the kissxml objectivec library kissxml internally uses libxml when i build the xcode project xcode 6 beta 5 i get this errorerror unknown0 error swiftframeworkswiftframeworkkissxmlddxmlnodeh2 include of nonmodular header inside framework module swiftframeworkddxmlnodei have seen this answer that thiscusses making the relevant header files public i have done that but i am not sure how to address the case of this header that is imported in the ddxmlnodeh and that is not explicitly part of my projectimport libxmltreehany suggestions on how to handle thisnote i have used kissxml on a objectivec only project and it worked fine xcode 5,['ios'] +741809,how to declare a property of a particular class which is also protocol conformant suppose i want to create a property which is a subclass of uiviewcontroller and also conformant to the protocol mydelegateprotocol in objectivec i would write something likeproperty strong nonatomic uiviewcontrollermydelegateprotocol delegatehowever i am not sure how to write this in swift i know how to declare a property which is protocolconformant or a property which is of a particular typelet delegate mydelegateprotocollet delegate uiviewcontrollerbut i cannot quite figure out how to make it do both if i try something likelet delegate uiviewcontrollermydelegateprotocol then i get a compiler error about cannot specialize nongeneric type uiviewcontroller probably because i am wandering into the land of generics now i have tried looking through the swift book on protocols and other stack overflow questions regarding protocols but i have not found quite what i am looking for,['ios'] +742062,iboutlets in nib are nil on both awakefromnib and initwithcoder a no subviews i have a custom uiview subclass with three subviews added to it via nib file a uiimageview a uiview and a uitextfield and iboutlets set but when the awakefromnib or initwithcoder get called in the subclass then all iboutlets are nil and even the subviews array is emptyi am using swift and xcode 6 beta 5 where this uiview subclass is in a framework and i added the uiview subclass to a storyboard within my project so i can use the new live view technology but i cannot see the added subviews in the live view either which is very sadi could not find any way to fix this heres the code from my uiview subclassimport uikitibdesignable public class blurredsheetentryview uiview iboutlet var iconimageview uiimageview iboutlet var separatorview uiview iboutlet public var textfield uitextfield override initframe cgrect superinitframe frame required public initcoder adecoder nscoder superinitcoder adecoder for subview in selfsubviews printlnsubview subview printlnselftextfield selftextfield printlnselficonimageview selficonimageview printlnselfseparatorview selfseparatorview override public func awakefromnib for subview in selfsubviews printlnsubview subview printlnselftextfield selftextfield printlnselficonimageview selficonimageview printlnselfseparatorview selfseparatorview and my nib file looks like thisxml version10 encodingutf8 standalonenodocument typecomappleinterfacebuilder3cocoatouchxib version30 toolsversion6205 systemversion14a314h targetruntimeioscocoatouch propertyaccesscontrolnone useautolayoutyes usetraitcollectionsyes dependencies plugin identifiercomappleinterfacebuilderibcocoatouchplugin version6198 capability nameaspect ratio constraints mintoolsversion51 dependencies objects placeholder placeholderidentifieribfilesowner id1 userlabelfiles owner placeholder placeholderidentifieribfirstresponder id2 customclassuiresponder view contentmodescaletofill idin0l3epb customclassblurredsheetentryview custommoduleblurredsheetentry custommoduleprovidertarget rect keyframe x00 y00 width300 height50 autoresizingmask keyautoresizingmask widthsizableyes heightsizableyes subviews imageview userinteractionenabledno contentmodescaletofill horizontalhuggingpriority251 verticalhuggingpriority251 translatesautoresizingmaskintoconstraintsno idznngymc6 rect keyframe x8 y5 width40 height40 constraints constraint firstattributewidth seconditemznngymc6 secondattributeheight multiplier11 idc4nzcwoh constraints imageview textfield opaqueno clipssubviewsyes contentmodescaletofill contenthorizontalalignmentleft contentverticalalignmentcenter placeholderplaceholder minimumfontsize17 clearbuttonmodewhileediting translatesautoresizingmaskintoconstraintsno idnpgxinso rect keyframe x66 y8 width226 height34 fontdescription keyfontdescription typesystem pointsize15 textinputtraits keytextinputtraits textfield view contentmodescaletofill translatesautoresizingmaskintoconstraintsno id8la9yyoa rect keyframe x56 y5 width2 height40 color keybackgroundcolor white063 alpha1 colorspacecalibratedwhite constraints constraint firstattributewidth constant2 idqggpw8q0 constraints view subviews color keybackgroundcolor white1 alpha1 colorspacecustom customcolorspacecalibratedwhite constraints constraint firstattributebottom seconditem8la9yyoa secondattributebottom constant5 id51oilvga constraint firstitem8la9yyoa firstattributeleading seconditemznngymc6 secondattributetrailing constant8 idaegi2vst constraint firstattributebottom seconditemnpgxinso secondattributebottom constant8 ide0hfnlg4 constraint firstitem8la9yyoa firstattributetop seconditemin0l3epb secondattributetop constant5 ideyrl896j constraint firstattributebottom seconditemznngymc6 secondattributebottom constant5 idgfwr2jgi constraint firstattributetrailing seconditemnpgxinso secondattributetrailing constant8 idlwslvn37 constraint firstitemznngymc6 firstattributetop seconditemin0l3epb secondattributetop constant5 idpv0zvat4 constraint firstitemznngymc6 firstattributeleading seconditemin0l3epb secondattributeleading constant8 idxoijosv7 constraint firstitemnpgxinso firstattributetop seconditemin0l3epb secondattributetop constant8 idda3wgxfn constraint firstitemnpgxinso firstattributeleading seconditem8la9yyoa secondattributetrailing constant8 idmq66rz2b constraints nil keysimulatedstatusbarmetrics freeformsimulatedsizemetrics keysimulateddestinationmetrics connections outlet propertyiconimageview destinationznngymc6 id0hpsrmqx outlet propertyseparatorview destination8la9yyoa idvfxenk3c outlet propertytextfield destinationnpgxinso idtiyn2g2j connections point keycanvaslocation x371 y327 view objectsdocumentupdatei have created an absolutely simple example project where i only did the followingchoose masterview template for iosadd new framework called mycustomtableviewcell with xib fileadd a uiview with blue background color as a subview in xib fileadd iboutlet and connection in the swift fileadd a println statement within awakefromnib in swift fileset the class of cells in the master tableview to the subclass from the frameworkwhen i build run and click the sign on the top right corner i get nil printed out on the console as a result for the iboutletthis is my issue and what annoys me but maybe i am doing something wrong here i have uploaded the example project heres the download urli am using a framework because i have to as i want to see my subclass as a live view in my main storyboardthanks for any help in advance,['ios'] +742063,make input value uppercase in css without affecting the placeholder is there a way i can make an input value uppercase without making the placeholder uppercase seems like i get one or the other i would prefer to do this cleanly just using css js last resort,['css'] +742070,what is the difference between bootstrapcss and bootstrapcombinedmincss i am using bootstrapcss and i found that there is another css file named bootstrapcombinedmincss is there any difference in style is there any need to include both css files which one is more preferable,['css'] +742092,java double epsilon i am currently in the need of an epsilon of type double preferred are constants in javas libraries instead of own implementationsdefinitionsas far as i can see double has min value and max value as static memberswhy there is no epsilonwhat would a epsilondouble beare there any differences to a stdnumeric limits double epsilonepsilon the difference between 1 and the smallest value greater than 1 that is representable for the data type,['java'] +742123,modern alternatives to packaging and deploying enterprise applications what are the modern alternatives to package and deploy server side java software1 in heterogeneous environments2 i could not find a lot of coherent or up to date information on the topic but i have a few ideas i will startthe traditional application server approach jetty tomcat etcassemble software into war files and craft your own provisioning and deployment script eg using izpack ant scripts cargo or something similar rely on integration platforms eg fabric8 servicemix fuse etcseems like a nice opinionated approach if not already using one of these apart from a lockin rerolling an application into this format requires a bit of work is not the trend to move away from large frameworks bundle application war files into ear enterprise archives filesrequires a fullfledged java ee server eg wildfly glassfish etc unless the capabilities of such server is needed it adds a lot of overhead to what a ziparchive could do already virtual machines vagrant docker etc docker is nice but on a windows host needs to be run in a vm anyway vms vagrant or not incurs a performance overhead and tends to rely on complex provisioning tools such as puppet or salt runnable jars eg capsule maven shade plugin onejar capsule seems great it is like an executable selfextracting zip file which also runs the application with an embedded jetty multiple traditional war files can be served from one executable the first option has been my reference approach for long but requires a lot of provisioning install scripts both which varies on different environments eg linux windows what modern alternatives are out there that makes packaging and deployment easier 1 picture a soa like setup with microservices restful communication etc 2 with that in mind let us rule out paas providers such as cloudbees cloudfoundy etc they deserve a topic of their own,['java'] +742125,thisable unicode replacement emoji in android chrome certain unicode characters in the miscellaneous range would be nice to use but most phones thisplay them as emoji and that is unwanted because then they cannot be styled by css font declarations i know there is a fix for ios but i have not found a solution for android is it possible to thisable themexample,['android'] +742153,template class friendship i recently came across a c piece of code where a class is made friend to itself as i have read on different forums a class is already a friend to itself so i was wondering if there is a specific reason why one would want to make a class friend to itself explicitly another question would be whats the reason in making a class a friend of itselfmaybe someone with a lot of experience can clarify this topichere is the code example to illustrate my questiontemplate typename tclass foo public tprotected template typename u friend class foo,['c++'] +742163,htmlactionlink and angularjs value hey i am currently workin on a project that has implemented angularjs i was wondering if there is a way around to use angular value in html helperthis is what i cannot get to workhtmlactionlinkedit edit new id rowid how do you use the value in razor syntax,['html'] +742255,cannot find six but it is installed i have six installed even reinstalled it pip show sixname sixversion 173location usrlibpython26sitepackagesrequires but when i try to run csvcut it cannot find it csvcut n monstercsvtraceback most recent call last file usrbincsvcut line 5 in module from pkg resources import load entry point file usrlibpython26sitepackagespkg resourcespy line 2655 in module working setrequire requires file usrlibpython26sitepackagespkg resourcespy line 648 in require needed selfresolveparse requirementsrequirements file usrlibpython26sitepackagespkg resourcespy line 546 in resolve raise thistributionnotfoundreqpkg resourcesthistributionnotfound six161heres the relevant but of csvcutusrbinpython easyinstallentryscript csvkit080console scriptscsvcut requires csvkit080import sysfrom pkg resources import load entry pointif name main sysexit load entry pointcsvkit080 console scripts csvcut this is on centos,['python'] +742296,adapterfill takes long i have created a radgrid programmatically and binding it using needdatasource getdatatablewithin the getdatatable i am calling my connstring and fill the grid with an adapter see code below problem is that in my sql server the query takes 0 sec to run but in the aspnet debug mode it is taking about 35s in my case of having a lot of radgrids on the page this is causing my page to load slowlyis this processing speed of adapterfill a general issue or have i done something wrong with the setting ie orders of connopenclose or any otherspublic datatable getdatatableint year int month string datatype string connstring configurationmanagerconnectionstringsihg mstconnectionstringconnectionstring sqlconnection conn new sqlconnectionconnstring sqldataadapter adapter new sqldataadapter adapterselectcommand new sqlcommandyield planner with strategy conn adapterselectcommandcommandtype systemdatacommandtypestoredprocedure adapterselectcommandparametersaddwithvalueholidex code radcombobox hotelsselectedvalue adapterselectcommandparametersaddwithvalueevent year year adapterselectcommandparametersaddwithvalueevent month month adapterselectcommandparametersaddwithvaluedatatype datatype adapterselectcommandparametersaddwithvaluemktseg fruitfulget checked values as csvradcombobox mktseg string exportdate datetimenowtostringymmdd if radcombobox exporttimestamptext radcombobox exporttimestamptext create new strategy exportdate converttodatetimeradcombobox exporttimestamptexttostringymmdd adapterselectcommandparametersaddwithvalueexporttimestamp exportdate datatable mydatatable new datatable connopen try adapterfillmydatatable finally connclose return mydatatable,"['c#', 'asp.net']" +742329,the type systemdatetime is not a supported type change to use systemdatetimeoffset we are creating a webapi 22 service and are using the technologies listed above our backend datastore is mysql 56 we are using dotconnect for mysql to work with the data store in the database there is a rowversion column with a type of timestamp in ef i successfully generated the model but i noticed that rowversion is set to datetime when i run the webapi i get the following runtime exception so i need to change the type to datetimeoffset because timestamp is not available in our application we will use the rowversion with etags for concurrency handling so we will only read the rowversion in our application the database will automatically update the rowversion whenever an insert or update happens i do not know how to correct this issue perhaps there is some way to add an automatic type conversion so the rowversion in the model is an int64 and we automatically convert between the int64 and timestamp by sending the timestampvalue to our application we are only reading it so this seems reasonablewhen i change the rowversion to int64 in the ef model and build the application i receive the following errorerror 1 error 2019 member mapping specified is not valid the type edmint64nullabletruedefaultvalue of member version in type modelcustomer is not compatible with devartdatamysqltimestampnullabletruedefaultvalueprecision0 of member version in type modelstorecustomers cprojectsservicemysqlservicemysqlmodelsmodeledmx 898 17 servicemysqli would really appreciate your help to figure out how to resolve this issuethank you for your time and suggestionsmikeexception mentioned at the beginning of this postingsystemargumentexception was unhandled by user code hresult2147024809 messagethe type systemnullable1systemdatetime mscorlib version40 cultureneutral publickeytokenb77a5c561934e089 of property version in the xservicemysqlmodelscustomer type is not a supported type change to use systemdatetimeoffset or ignore this type by calling ignorexservicemysqlmodelscustomer on systemwebodatabuilderodatamodelbuilder parameter name navigationproperty sourcesystemwebodata paramnamenavigationproperty stacktrace at systemwebodatabuilderentitytypeconfigurationaddnavigationpropertypropertyinfo navigationproperty edmmultiplicity multiplicity boolean containstarget at systemwebodatabuilderentitytypeconfigurationaddnavigationpropertypropertyinfo navigationproperty edmmultiplicity multiplicity at systemwebodatabuilderodataconventionmodelbuildermapentitytypeentitytypeconfiguration entity at systemwebodatabuilderodataconventionmodelbuildermaptypestructuraltypeconfiguration edmtype at systemwebodatabuilderodataconventionmodelbuildermaptypes at systemwebodatabuilderodataconventionmodelbuildergetedmmodel at xservicemysqlwebapiconfiggenerateedmmodel in cprojectsxservicemysqlxservicemysqlapp startwebapiconfigcsline 89 at xservicemysqlwebapiconfigregisterhttpconfiguration config in cprojectsxservicemysqlxservicemysqlapp startwebapiconfigcsline 55 at systemwebhttpglobalconfigurationconfigureaction1 configurationcallback at xservicemysqlwebapiapplicationapplication start in cprojectsxservicemysqlxservicemysqlglobalasaxcsline 17 innerexception,['mysql'] +742446,creating lowpass filter in scipy understanding methods and units i am trying to filter a noisy heart rate signal with python because heart rates should never be about 220 beats per minute i want to filter out all noise above 220bpm i converted 220minute into 36 hertz and then converted that hertz to rads to get 230383461 radsecthe sampling frequency of the chip that takes data is 30hz so i converted that to rads to get 1884959 radsafter looking up some stuff online i found some unctions for a bandpass filter that i wanted to make into a lowpass here is the link the bandpass code so i converted it to be thisfrom scipysignal import butter lfilterfrom scipysignal import freqsdef butter lowpasscutoff fs order5 nyq 05 fs normalcutoff cutoff nyq b a butterorder normalcutoff btypelow analog true return b adef butter lowpass filterdata cutoff fs order4 b a butter lowpasscutoff fs orderorder y lfilterb a data return ycutoff 231 cutoff frequency in radsfs 1884959 sampling frequency in radsorder 20 order of filterprint sticker dataps1 dxdt2y butter lowpass filterdata cutoff fs orderpltplotyi am very confused by this though because i am pretty sure the butter function takes in the cutoff and sampling frequency in rads but i seem to be getting a weird output is it actually in hzsecondly what is the purpose of these two lines nyq 05 fs normalcutoff cutoff nyqi know its something about normalization but i thought the nyquist was 2 times the sampling requency not one half and why are you using the nyquist as a normalizercan one explain more about how to create filters with these functionsi plotted the filter usingw h signalfreqsb apltplotw 20 nplog10abshpltxscalelogplttitlebutterworth filter frequency responsepltxlabelfrequency radians secondpltylabelamplitude dbpltmargins0 01pltgridwhichboth axisbothpltaxvline100 colorgreen cutoff frequencypltshowand got this that clearly does not cut off at 23 rads,['python'] +742453,what is the best way to thistribute a closedsource ios sdk i would really like to be able to publish the sdk through cocoapods but i was not able to find anything apparent that detailed how i could thistribute an sdk without also publishing the source files if a solution for cocoapods is given i will likely prefer that answer otherwise how would i go about thistributing an sdk to millions of objectivec swift developers under an apache v2 license subsequently not publishing the m files thisclaimer i have already created the framework am aware of setting the compile sources to make only the headers viewable by a framework target in xcode this question only pertains to how to thistribute it,"['ios', 'objective-c']" +742556,is there a way to set a uitableviews contentinset through storyboard selftableviewcontentinset uiedgeinsetsmake232 0 232 0is there a way of setting this in storyboard,['ios'] +742558,get firebase to work with java not android im trying to get a libgdx project up and running and i want to firebase for user logins i am finding that the simlelogin class is depending on androidjar is there a way around this as i would like to have a desktop java application running as well as androidhere is the code that is causing the issuesimplelogin authclient new simpleloginmyrefauthclientcreateuser much wow new simpleloginauthenticatedhandler override public void authenticatedfirebasesimpleloginerror error firebasesimpleloginuser user if error null systemoutprintlnerror else systemoutprintlnuser and this thowing this at runtimeexception in thread lwjgl application combadlogicgdxutilsgdxruntimeexception javalangnoclassdeffounderror androidneturi at combadlogicgdxbackendslwjgllwjglapplication1runlwjglapplicationjava120caused by javalangnoclassdeffounderror androidneturi at comfirebasesimpleloginsimpleloginmakerequestsimpleloginjava634 at comfirebasesimpleloginsimplelogincreateusersimpleloginjava417 at commygdxgamemygdxgamecreatemygdxgamejava63 at combadlogicgdxbackendslwjgllwjglapplicationmainlooplwjglapplicationjava136 at combadlogicgdxbackendslwjgllwjglapplication1runlwjglapplicationjava114caused by javalangclassnotfoundexception androidneturi at javaneturlclassloader1rununknown source at javaneturlclassloader1rununknown source at javasecurityaccesscontrollerdoprivilegednative method at javaneturlclassloaderfindclassunknown source at javalangclassloaderloadclassunknown source at sunmisclauncherappclassloaderloadclassunknown source at javalangclassloaderloadclassunknown source 5 moream i going about this or is the java platform they claim to support really just android,['java'] +742689,android studio does not recognize my device here is the problem i want to run my android studio apps on my device samsung galaxy ace 2 but nothing works for me tell me what i have missed1 usb debugging is on2 adb driver is installed in device manager i can see android composite adb interface3 adb device list is still clear even if i reset serveradb killserver adb startserver adb devices list of devices is clear4 in google usb driver directory in android winusbinf file i added my device identificators5 android device manager still cannot connect to my device showing this error when i reset it adb connection error an existing connection was forcibly closed by the remote hostso i will be glad to hear any advices hope youll help me,['android'] +742705,generate a random derangement of a list how can i randomly shuffle a list so that none of the elements remains in its original positionin other words given a list a with thistinct elements i would like to generate a permutation b of it so thatthis permutation is randomand for each n an bnega 1234b 4123 goodb 4213 gooda 1234x 2431 badi do not know the proper term for such a permutation is it total thus having a hard time googling the correct term appears to be derangement,['python'] +742741,after update errorfailed to find comgoogleandroidgmsplayservices528 gradle project sync failedafter update the android sdk i got this errorerrorfailed to find comgoogleandroidgmsplayservices528i have checked that the sdk location wich is updated is used by android studioi have got google repository installed and android support repository too all up 2 datealso i have a android home local variable pointing to the sdk im actually using,['android'] +742743,apache not starting on mamp pro apache wont start and it throws an errororapache could not be started please check the log file for more informationdyld symbol not found iconv referenced from usrliblibmecabradylib expected in applicationsmamplibraryliblibiconv2dylib in usrliblibmecabradylib applicationsmamplibrarybinapachectl line 80 2799 tracebpt trap 5 httpd this is the same for multiple ports the reccomended mamp ports and the regular apache portsmysql starts perfectly fineany suggestions,['mysql'] +742747,deactivate a maven profile from command line i have a profile activated by default in my maven setting file m2settingsxmlis it possible to deactivate it from the command line by doing something like thismvn pprofileactivatedbydefault,['java'] +742774,c template instantiation avoiding long switches i have a class depending on an integer template parameter at one point in my program i want to use one instantiation of this template depending on a value of this parameter determined at runtime here is a simple example demonstrating how i would go about this currently using a big switch statementinclude stringinclude iostreaminclude type traitstemplateunsigned astruct wrapper typedef typename stdconditionala1 int floattype datatype datatype contenta void foo stdcout a stdendl int mainint argc char argv stdstring arg argv1 int arg int stdstoiarg switch arg int case 1 wrapper1 w wfoo break case 2 wrapper2 w wfoo break case 3 wrapper3 w wfoo break default return 1 return 0this will quickly get unwieldy once i have not only one parameter a but multiple template arguments in various combinations let us also assume that in reality there is a really good reason to implement a as a template parameteris there a way to replace the huge switch statement with almost identical case statements eg using some metaprogramming magic from boost or a preprocessor hackideally i would like to be able write something like the followinginstantiate dependingi 1 2 3 wrapperi w wfoo,['c++'] +742819,what is the lifecycle of a fragment when replace is called i have a number of fragments which are dynamically added using the following codeprivate class draweritemclicklistener implements listviewonitemclicklistener override public void onitemclickadapterview parent view view int position long id selectitemposition private void selectitemint position update the main content by replacing fragments fragment fragment null ifposition 0 fragment new firstfragment else ifposition 1 fragment new secondfragment else ifposition 2 fragment new thirdfragment fragmentmanager fragmentmanager getsupportfragmentmanager fragmentmanagerbegintransactionreplaceridcontent frame fragmentcommit update selected item and title then close the drawer mdrawerlistsetitemcheckedposition true settitlemcalculatortitlesposition mdrawerlayoutclosedrawermdrawerlistin one of my fragments i have a timer and i have just thiscovered that when the fragment is replaced the timer in the old fragment is still running where in my fragments lifecycle should i kill the timereditokay so i added a timercancel in the fragments onstop method but onstop also gets called when i load the preferences from a button on the action bar this is not the desired effect any other ideas,"['java', 'android']" +742893,quickly square a double i am looking for the fastest way to square a double double d so far i came up with two approaches1 dd2 mathpowd 2to test the performance i set up three test cases in each i generate random numbers using the same seed for the three cases and just calculate the squared number in a loop 100 0 0 timesin the first test case numbers are generated using randomnextdouble in the second case using randomnextdoubledoublemax value and in the third one using randomnextdoubledoublemin valuethe results of a couple of runs approximate results theres always some variation run using java 18 compiled for java 16 on mac osx mavericksapproach case 1 case 2 case 3a 1 216s 216s 216s 2 9s 30s 60sthe conclusion seems to be that approach 1 is way faster but also that mathpow seems to behave kind of weirdso i have two questions1 why is mathpow so slow and why does it cope badly with 1 and even worse with 1 numbers2 is there a way to improve the performance over what i suggested as approach 1 i was thinking about something likelong l doubledoubletorawlongbitsdlong sign l 1 63doublelongbitstodoublel1signbut that is a wrong and b about the same speed as approach 1,['java'] +742937,how to set current spinner text without changing associated selection list items i have a spinner with some values monday thuesday wednesday thursday friday saturday user defined when the user choose user defined he can input a custom value in a dialog assuming that i get this value as string userdefyour choicei need to set this string as current item without change the spinner selection list that must appear the same described above also when the user clicks again on the spinner something like in google analytics android app see the imageunclicked spinnerclicked spinnerhow could i do this,['android'] +742963,is comgoogleandroidc2dmintentreceive still in use i have seen that c2dm itself is deprecated but the new method google cloud messaging seems to send intents with comgoogleandroidc2dmintentreceive as the actionmy code is using this to get the registration keygcm googlecloudmessaginggetinstancegetapplicationcontextgcmregistersender idthings are arriving correctly but i am wondering if i have left something in a halfdeprecated state,['android'] +743002,implement both uisearchcontroller and uisearchthisplaycontroller i am trying to make my ios7 app work on ios8 and i saw that the uisearchcontroller replaces the uisearchthisplaycontroller in ios8of course i can use uisearchcontroller instead of uisearchthisplaycontroller but than my app is no longer working on ios7how can i make my app work on both ios versions do i need to make another storyboard for ios8thanks in advance,['ios'] +743071,how to auto adjust the div size for all mobile tablet thisplay formats i have designed a page where four div tags are there in the page if i test the page in mobile phone 5 inch it fits the page perfectly if i test the same page in tablet the page fits with in 30 of the screen so how can i set the div size so that it will fit for all type of screensfiddle linkhtml div classbubble0 aligncenter h3three levels h3 div div classbubble aligncenter divbrbr div classbubble1 aligncenter divbrbr div classbubble2 aligncenter divbrbr buttonplaybuttonany suggestions please,"['html', 'css']" +743162,hide elements in xcode storyboad is there a way to hide elements in storyboard interface what i am talking about is like in photoshop how you can hide layers while working i ask because i have some stacked items and it would be nice to not see everything at once while working sometimes,['ios'] +743224,why are stdbegin and stdend overloaded for stdinitializer list in c11 in c11 quoting n37 stdbegin and stdend are specified as a247 iteratorrangep23template class c auto beginc c decltypecbegintemplate class c auto beginconst c c decltypecbegin2 returns cbegintemplate class c auto endc c decltypecendtemplate class c auto endconst c c decltypecend3 returns cendstdinitializer list however provides its own overloads for these functions a1893 supportinitlistrangetemplateclass e const e begininitializer liste il noexcept1 returns ilbegintemplateclass e const e endinitializer liste il noexcept2 returns ilendit seems that these overloads do not do anything beyond the base template other than 1 having a noexcept specification and 2 taking their parameter by value however copying an initializer list does nothing special it just copies a pair of pointers or something equally lightweight so 2 creates no difference in behavior moreover the begin and end member functions of many standard containers are also noexcept yet no overloads of stdbeginstdend are specified for those containers so it seems unlikely the committee specified these overloads just for 1 why then are these overloads provided,['c++'] +743281,how to see top and entries of termdocument matrix after tfidf in scikitlearn i am new to scikitlearn and i was using tfidfvectorizer to find the tfidf values of terms in a set of documents i used the following code to obtain the samevectorizer tfidfvectorizerstop wordsuenglishngram range15lowercasetruex vectorizerfit transformlecturesnow if i print x i am able to see all the entries in matrix but how can i find top and entries based on tfidf score in addition to that is there any method that will help me to find top and entries based on tfidf score per ngram ie top entries among unigrambigramtrigram and so on,['python'] +743360,another winforms versus wpf thread i have got a legacy visual basic 6 desktop app which i am porting over to net i am trying to determine whether or not it makes sense to use winforms or wpf i know there are many threads covering this but i cannot seem to find anything decisivei know that winforms is technically dead and it is truly a legacy technology but having read numerous threads on this i still have strong reservations about using wpf moreover sorry to say this but i find windows 8 to be a pain to use and did not even consider writing a desktop app using windows 8html 5javascript an option i fear that a lot of that stuff will suffer the same fate as j j silverlight etci could use some help from the community in making the right choicearguments for using winforms1 i have seen the arguments against coding in winforms as it encourages poor architecture otoh i see nothing in winforms that forces this upon anyone having built numerous systemsthings using tdd oop d etc i have pretty solid coding habits that yield clean systems with testable reusable code2 porting the legacy code from visual basic 6 to winforms is a closer translation to winforms than it is to wpf wpf may add complexity in the ui engineering which is totally absent from the winforms it is easy to be really productive with winforms fast also winforms has builtin mdi support which the legacy app uses3 it is not clear to me what the future is for wpf while it appears that microsoft will embrace xaml in the future it is not clear what will be the fate of wpf even if winforms is dead because win32 is so pervasive it seems unlikely that anything built on top of it will completely cease to function right with rumours of wpfs death i am concerned about porting to a platform that may eventually be more dead than winforms already is ie silverlight4 the front end of the application is fairly simple and uses textboxes comboboxes grids date pickers and grids we enter data generate reports and send emails nothing fancy using wpf adds nothing to this lineofbusiness app other than being the most recently viable desktop platform5 because of the sheer simplicity of winforms and the new clean architecture with whatever new technology comes along i can easily port the ui and keep the middledata layers the same the code behind our ui will be very straightforward6 if we ever need a mobile version of our app we can expose restful endpoints and write a front end as needed no reason to try to shoehorn our app into multiple platforms thus there is no advantage to vectorbased graphicsarguments against winforms1 although wpfs fate is unclear microsoft seems to be embracing xaml i think even if today wpf is doa whatever next technology they release for desktop development may likely use xaml thus even if wpf truly dies and our app becomes inoperable on the latest os we will have reusable assets in xaml and porting will be a small step2 wpf represents a newer programming model follows new standards more closely etc etc3 winforms is really old at least by our industry standards the risk exists that winforms may be become completely inoperable it is possible that microsoft may cease to support winforms development in visual studio in which case well be stuck on an older version of net4 developers will more likely want to work with xaml than winforms if i get hit by a bus it may be harder to find talent willing to work on that app not the strongest argument but still a factor and i cannot think of any other arguments when i take off my developer hat and think like the actual business owner of this application it is actually kind of hard to justify using wpf if we build the app on winforms and get another 10 years of usage out of that effort it more than pays for itself i see a lot of developers urging other developers to use wpf because it is the wave of the future but when i think from the business perspective i cannot see any advantage i want the app to run smoothly and be as simple to maintain as possiblewhat are your thoughtsthanks in advance,['c#'] +743362,summernote add class in img i want to add a class classimgresponsive in the images which i add with the editoractually i get this code after i saved my textltimg srcquotlinkquot stylequotwidth 628px height 4707191413237925pxquotgtin the summernotejs i found this code create image from url string param string surl return promise then image var createimage function surl return deferredfunction deferred imgoneload function deferredresolvethis oneerror abort function deferredrejectthis css thisplay none appendtodocumentbodyattrsrc surl promise return readfileasdataurl readfileasdataurl createimage createimage i dont know if that is the right code to add a class and also i dont know how and where to add classimgresponsive,['javascript'] +743369,java replace line in a text file i found this code from another questionprivate void updatelinestring toupdate string updated throws ioexception bufferedreader file new bufferedreadernew filereaderdata string line string input while line filereadline null input line n input inputreplacetoupdate updated fileoutputstream os new fileoutputstreamdata oswriteinputgetbytes fileclose osclosethis is my file before i replace some linesexample1example2example3but when i replace a line the file now looks like thisexample1example2example3which makes it impossible to read the file when there are a lot of lines in ithow would i go about editing the code above to make my file look what it looked like at the start,['java'] +743377,set embeddable field as primary key from parent entity mapping doctrine2 tldr doctrine2 i need to know if it is possible to make a field within an embeddable into a primary key from the parent entities or mappedsuperclass mapping i already know how to set the primary key from the embeddables mapping but this is not ideal see the long versionthe long versioni am trying to create identity value objects for my entities using doctrine2 embeddableshere is my problemi have two different embeddables myentityid and otherentityid in an entity myentityi want a field within myentityid to be myentitys primary keyas i have two identity embeddables in the same entity i want to define the primary key field in the entity mapping file rather than the embeddable mappingif i define the primary key from within the embeddable i run into problems when i want to do the same for otherentityid as i am using it elsewhere mapping the primary key in myentityid and otherentityid leads to myentity having a composite key which i do not wanthere are my mappings at the momentmyentity embedded myentityid class myentityid columnprefix false otherentityid class otherentityid columnprefix falsemyentityid type embeddable id id column myentityid type stringotherentityid type embeddable id id column otherentityid type stringsolutionscreate two seperate embeddables to represent the same id value object not very dry and too complexmap the embeddables primary key field from the entity is this possible i cannot find it anywhere in documentation,['php'] +743565,xcode not recognizing cgfloat uifont cgsize while using objectivec with swift i created a new swift project and tried to import my existing objective c code into the swift project everything is going fine except xcode 6 beta 5 is complaining about cgfloat uifont cgsizethe error i see is expect a type and unknown type name cgfloat right next to some of my methods i thought swift should be friendly with objective c and accept all my objective c code but unfortunately this is not the caseany idea suggestions or comments i would appreciate it thanks,['objective-c'] +743568,swift version of componentsseparatedbystring i know its noob question i really search around before ask but there is not exact answer of what i want to know how we split string into the array without using objective c for examplevar str today is so hotvar arr strcomponentsseparatedbystring i know it doesnt work but i am looking for like that i want to split string with or another charstring ideait might be very good for me making extension of string class but i dont know how i do that edit forgetting import foundation if i import foundation it will work but is there any way to do with extending string classthank you,['ios'] +743573,best way to plot an angle between two lines in matplotlib i am fairly new to using matplotlib and cannot find any examples that show two lines with the angle between them plottedthis is my current imageand this is an example of what i want to achievei usually take a look at the matplotlib gallery to get an idea of how to perform certain tasks but there does not seem to be anything similar,['python'] +743688,is it possible to allow didset to be called during initialization in swift question apples docs specify thatwillset and didset observers are not called when a property is first initialized they are only called when the propertyas value is set outside of an initialization contextis it possible to force these to be called during initializationwhylet us say i have this classclass someclass var someproperty anyobject didset dostuff initsomeproperty anyobject selfsomeproperty someproperty dostuff func dostuff do stuff now that someproperty is set i created the method dostuff to make the processing calls more concise but i would rather just process the property within the didset function is there a way to force this to call during initialization update i decided to just remove the convenience intializer for my class and force you to set the property after initialization this allows me to know didset will always be called i have not decided if this is better overall but it suits my situation well,['ios'] +743700,what are canonical types in clang i have a simple header parser based on clang and i get the typedefs from some sourcestruct poire int gtomate rougetypedef struct poire kudamonoafter parsing this i have a clangtypedefdecl then i get the clangqualtype of the typedef with clangtypedefdeclgetunderlyingtypewith the qualtype if i use the getasstring method i can find the struct poire stdstring all this is ok the problem is if i try to see if this type is a canonical type with qualtypeiscanonical it returns falseso i try to get the canonical type with qualtypegetcanonicaltypegetasstring and it returns the same string struct poireaccording to the clang reference on type i thought that the iscanonical should return true when no typedef is involvedso what are really canonical type,"['c++', 'c']" +743725,autolayout causing ui elements to snap into place at runtime i have a uiview with a uiimageview at the very top a uilabel below it a uibutton below that and a uisegmentedcontrol that determines what determines what embedded uiview to thisplay at the bottom which also a choice to not show any at alli have run into the problem where i have set up all of my constraints in the interface builder and everything seems to be fine when i switch between screen sizes in the storyboard however when i actually run the project on a device or emulated the uiimage at the top is briefly stretched before snapping into a size the fits the constraints also it seems as if the label thisappears for a brief second and reappears after the image has snapped into a size after the snap has occurred everything is in place and there are no problemsthis snapping occurs both when testing on a 4 and 35 inch thisplay i find this odd because i have designed the ui for the 4inch screen perfectly does anyone know why this is happening editheres whats the constraints look like in ib,"['ios', 'objective-c']" +743756,connecting drilldown nssplitview outlets using storyboards i have an nssplitview that manages a drilldown hierarchy the parentleft side thisplays groups while the childright side receives notification that the group selection has changed and updates to thisplay the child itemshowever when creating an nssplitview using storyboards there are 3 scenes created one for the split view itself and one for each of the rightleft nsviewcontroller instancesthe problem here is that i have two controllers that are also acting as nstableviewdatasource items and the parent controller should have an iboutlet to the child controller so that it can provide direct notification that the selection has changedbut because these controllers are in different scenes i cannot connect them nor can i move them both up to the parent scene for the split view because they would then not have access to the nstableview outlets nor would the tables reference the controllers as delegatesdatasourcesdo i need to use nsnotification here it seems so indirect and wishywashy and i have not found a seguebased approach on the mac,['objective-c'] +743772,how to find the version of library from gradle dependency android studio questionhow do i find the version of libraries that are being used when my gradle file mentions a dependency using the operator in the version number of the dependencycontextmy buildgradle under app module reads like sodependencies compile filetreedir libs include jar compile comgoogleandroidgmsplayservices5what is the version of the playservices library that is being used here,['android'] +743877,php how to get mimetype of a image with file get contents i need to get the mimetype of an image but i only have the body of the image which i have got with file get contents is there a possibility to get the mimetype,['php'] +743932,ios 8 rotation methods deprecation backwards compatibility in ios 8 the methods for interface rotation are deprecated this includeswillrotatetointerfaceorientationdurationdidrotatefrominterfaceorientationwillanimaterotationtointerfaceorientationdurationthe replacement methods includewilltransitiontotraitcollectionwithtransitioncoordinatorviewwilltransitiontosizewithtransitioncoordinatorif the new rotation methods are not implemented and a project is compiled with the ios 8 sdk the view controllers will not receive calls to the deprecated rotation methodsmy concern is this what happens to an app already in the appstore built with the ios 7 sdk will the deprecated rotation methods still be called on an ios 8 device or noteditthe rotation methods are still called but there exist some changesissuesbugs in ios 8also uiscreen is now interface oriented,['ios'] +743952,compilation error for annotations in java using mavencompilerplugin 251 with java 18 and netbeans i am newborn in writing anotations in java i was trying to write my own following this tutorial playing with java annotation processingi wrote everything like it is there but during compilation i am getting an error bad service configuration file javaxannotationprocessingprocessor provider my class not foundi am using netbeans and maven with plugin mavencompilerplugin v 251 and java sources v18in my pomxml file i have like suggested in page following codeplugin artifactidmavencompilerpluginartifactid version251version configuration source18source target18target thisable annotation processing for ourselves compilerargumentprocnonecompilerargument configurationpluginmy os is linux leatest ubuntu and maven is that one integrated in netbeans i was trying to google it but nothing helped me all tutorials were for older release of plugin and java i tried older release of mavencompilerplugin but with no effect i cannot switch to older version of java because of new features introduced in java 8thanks a lot for any pointing me how to fix it edit here is full list of my sourcesconfigjavaretentionretentionpolicysourcetargetvalue elementtypefield elementtypelocal variable elementtypeparameterpublic interface config string name string type string defaultvalueconfigannotationprocessorjavasupportedannotationtypes sklieskove301jianghongtiaomotionanalyserconfigconfigannotationspublic class configannotationprocessor extends abstractprocessor override public boolean proceset extends typeelement annotations roundenvironment env messager messager processingenvgetmessager annotationsstreamforeachte envgetelementsannotatedwithtestreamforeache messagerprintmessagediagnostickindnote printing etostring return true override public sourceversion getsupportedsourceversion return sourceversionlatestsupported metainfservicesjavaxannotationprocessingprocessorsklieskove301jianghongtiaomotionanalyserconfigconfigannotationprocessorpomxmlxml version10 encodingutf8project xmlns xmlnsxsi xsischemalocation modelversion400modelversion groupidsklieskove301jianghongtiaogroupid artifactidmotionanalyserartifactid version10snapshotversion packagingjarpackaging dependencies some dependencies dependencies properties projectbuildsourceencodingutf8projectbuildsourceencoding mavencompilersource18mavencompilersource mavencompilertarget18mavencompilertarget properties profiles profile build plugins plugin artifactidmavencompilerpluginartifactid version251version configuration source18source target18target thisable annotation processing for ourselves compilerargumentprocnonecompilerargument configuration plugin plugins build profile profilesprojectand this is log of my compilercd homexjurajdropboxworkmotionanalyser java homeusrlibjvmjava8oracle usrlocalnetbeans80javamavenbinmvn clean installscanning for projectsbuilding motionanalyser 10snapshot mavencleanplugin241clean defaultclean motionanalyser deleting homexjurajdropboxworkmotionanalysertarget mavenresourcesplugin25resources defaultresources motionanalyser debug execute contextualizeusing utf8 encoding to copy filtered resourcescopying 6 resources mavencompilerplugin232compile defaultcompile motionanalyser compiling 27 source files to homexjurajdropboxworkmotionanalysertargetclassescompilation error error bad service configuration file or exception thrown while constructing processor object javaxannotationprocessingprocessor provider sklieskove301jianghongtiaomotionanalyserconfigconfigannotationprocessor not found1 errorbuild failuretotal time 1661sfinished at mon aug 11 195616 cest 2014final memory 12m180mfailed to execute goal orgapachemavenpluginsmavencompilerplugin232compile defaultcompile on project motionanalyser compilation failureerror bad service configuration file or exception thrown while constructing processor object javaxannotationprocessingprocessor provider sklieskove301jianghongtiaomotionanalyserconfigconfigannotationprocessor not found help 1to see the full stack trace of the errors rerun maven with the e switchrerun maven using the x switch to enable full debug loggingfor more information about the errors and possible solutions please read the following articleshelp 1 edit 2 and so on screenshot of my environment is herescreenshot of my folder structureoutput of nonintegrated mavenxjurajxjurajpcdropboxworkmotionanalyser mvn e package error stacktraces are turned oninfo scanning for projectsinfo info building unnamed sklieskove301jianghongtiaomotionanalyserjar10snapshotinfo tasksegment packageinfo info resourcesresources execution defaultresourcesinfo using utf8 encoding to copy filtered resourcesinfo copying 6 resourcesinfo compilercompile execution defaultcompileinfo compiling 27 source files to homexjurajdropboxworkmotionanalysertargetclassesinfo error compilation error info error error bad service configuration file or exception thrown while constructing processor object javaxannotationprocessingprocessor provider sklieskove301jianghongtiaomotionanalyserconfigconfigannotationprocessor not foundinfo 1 errorinfo info error build failureinfo info compilation failureerror bad service configuration file or exception thrown while constructing processor object javaxannotationprocessingprocessor provider sklieskove301jianghongtiaomotionanalyserconfigconfigannotationprocessor not foundinfo info traceorgapachemavenbuildfailureexception compilation failureerror bad service configuration file or exception thrown while constructing processor object javaxannotationprocessingprocessor provider sklieskove301jianghongtiaomotionanalyserconfigconfigannotationprocessor not found at orgapachemavenlifecycledefaultlifecycleexecutorexecutegoalsdefaultlifecycleexecutorjava715 at orgapachemavenlifecycledefaultlifecycleexecutorexecutegoalwithlifecycledefaultlifecycleexecutorjava556 at orgapachemavenlifecycledefaultlifecycleexecutorexecutegoaldefaultlifecycleexecutorjava535 at orgapachemavenlifecycledefaultlifecycleexecutorexecutegoalandhandlefailuresdefaultlifecycleexecutorjava387 at orgapachemavenlifecycledefaultlifecycleexecutorexecutetasksegmentsdefaultlifecycleexecutorjava348 at orgapachemavenlifecycledefaultlifecycleexecutorexecutedefaultlifecycleexecutorjava180 at orgapachemavendefaultmavendoexecutedefaultmavenjava328 at orgapachemavendefaultmavenexecutedefaultmavenjava138 at orgapachemavenclimavenclimainmavenclijava362 at orgapachemavenclicompatcompatiblemainmaincompatiblemainjava60 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava62 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43 at javalangreflectmethodinvokemethodjava483 at orgcodehausclassworldslauncherlaunchenhancedlauncherjava315 at orgcodehausclassworldslauncherlaunchlauncherjava255 at orgcodehausclassworldslaunchermainwithexitcodelauncherjava430 at orgcodehausclassworldslaunchermainlauncherjava375caused by orgapachemavenplugincompilationfailureexception compilation failureerror bad service configuration file or exception thrown while constructing processor object javaxannotationprocessingprocessor provider sklieskove301jianghongtiaomotionanalyserconfigconfigannotationprocessor not found at orgapachemavenpluginabstractcompilermojoexecuteabstractcompilermojojava729 at orgapachemavenplugincompilermojoexecutecompilermojojava128 at orgapachemavenplugindefaultpluginmanagerexecutemojodefaultpluginmanagerjava490 at orgapachemavenlifecycledefaultlifecycleexecutorexecutegoalsdefaultlifecycleexecutorjava694 17 moreinfo info total time 2 secondsinfo finished at thu aug 14 151026 cest 2014info final memory 19m187minfo cheers juraj,['java'] +743967,python requests speed up using keepalive in the http protocol you can send many requests in one socket using keepalive and then receive the response from server at once so that will significantly speed up whole process is there any way to do this in python requests lib or are there any other ways to speed this up that well using requests lib,['python'] +744035,querying on relationship arrays in realm lets say i have a dog and person realm objects likeinterface dog rlmobjectproperty nsstring nameproperty nsinteger ageproperty rlmarrayperson ownersendimplementation dogendrlm array typedoginterface person rlmobjectproperty nsstring nameproperty rlmarraydog dogsendimplementation personendrlm array typepersonthis is the sample code from realms example project the only difference is that dog entity has an array of person objects as owners in other words an inverse relationship to persons dogsnow the thing i want to accomplish is querying the dog objects having a person as one of the ownershow can i do that,"['ios', 'objective-c']" +744197,chrome app webview and touch scroll propagation i am in the happy position of replacing a windows 8 metro app with a chrome packaged app for the time being it needs to mimic the look and feel of the metro app the main page consists of multiple webviews arranged horizontally with a large amount of horizontal scrolling possible i have run into a problem when attempting to scroll horizontally using a touch device if the scroll gesture starts on a webview it is capturing the scroll event and preventing the host from scrolling overflow is hidden on all of the webviews as they form the bulk of the content on the page then the valid scroll targets for the host are limitedthe webview contents are interactive so i cannot get away with placing a transparent overlay over the scrollable content to capture the event at least not without some way to propagate the clickstouches through to the webviews themselvesany ideas on how this could be achievedthanks for your help,"['javascript', 'html']" +744217,numpyvoid type how to use it i loaded a matlab mat file via scipyioloadmat and it gave me a list of numpyvoid objectscan someone tell me what are they how they can be used and where can i get some reference documentation on them,['python'] +744305,uislider events not cancelled in ios 8 were currently testing our apps ios 7 apps that are in the store on an ios 8 device we noticed a big performance problem with uislidersif we pull the slider fast from left to right several times the slider will not immediately go to our last position it will perform every move we have done with our finger it seems as if the intermediate touch events are not properly cancelledon ios 7 the slider performance is finehas anyone experienced the same problem is this a known problem is there a solution to this,['ios'] +744342,c98 v c11 stdsetinsert specifications the meaning of the iterator passed as a position hint to stdsetinsertiterator position const value type val and stdmultisetinsertiterator position const value type val changes between c98 and c 11 is there an easy way at compiletime to detect which is in use and use different codea general check on c11 does not appear to be a good idea 1 2 and i did not see a suitable boostconfig macrospecifically the documentation for c98 saysthe function optimizes its insertion time if position points to the element that will precede the inserted elementwhile for c11 it saysthe function optimizes its insertion time if position points to the element that will follow the inserted element or to the end if it would be the lastthis matters because the hint effects the complexity of the insertion call if the hint is correct the complexity is only an amortized constant but if it is not it is logarithmic in sizeupdateas so nicely described below by jerrycoffin the c98 specification is essentially a typo,['c++'] +744463,communicating withopening containing app from share extension here is what i have tried that has not workedusing openurl to attempt to open the containing apphere is what i have thought of that wouldnt workusing local notifications to provide a link to the containing app creating the local notification from the extensionhere are options i am consideringusing a uidocumentinteractioncontroller and a custom file extension type to provide a link to my containing app and my containing app onlystarting a fake nsurl session to get the following functionality in ios if your extension isnat running when a background task completes the system launches your containing app in the background and calls the applicationhandleeventsforbackgroundurlsessioncompletionhandler app delegate methodthe uidocumentinteractioncontroller is confirmed to work in xcode 65 but the flow is kind of wonky the nsurl thing should work as well but it is also a bit fishy does anyone have any other ideas of getting my containing app to open from a share extension or an idea to communicate with it from a share extension,['ios'] +744539,backboneassociations vs backbonerelational i have been looking for information about how can we build relationship in backbone and came across following two nice pluginsbackbonerelationalbackboneassociationsboth seems to have exist more than two years and seems to be stable however backbonerelational outshines against backboneassociations in following termsproviding almost all relations like onetoone onetomany manytoone as we have in databasenice documentation similar to backbonejs on first glancesince i have not had time to go through both the plugins extensively i would like to know from the experienced person following thingsdoes both support amd like requirejshow easy to use the plugin with backendserver like ruby on railshow easy to implement polymorphic relationship,"['javascript', 'jquery']" +744608,firefox log ionmonkey compilation and bailouts i can start google chrome with jsflagstraceopt tracedeopt to get a log of what the v8 optimizer is compiling and what is falling out of the optimized execution but is there anything comparable for firefox ionmonkey,['javascript'] +744641,how to optimize image like facebook and whatapp does i want to optimize the image file size like whatsapp and facebook are doing i have send 5mb image on whatsapp and received image has size of 80kb received image looks identical to the original ones but resolution is less than the original onei tried almost all the source codes of android image compression available on stackoverflow but that does not work for me and then i came across this link to optimize the image which is doing good work but still not getting the result like whatsapphow can i achieve maximum image compression without degrading the quality of image same like whatsapp did answer with a source code will be very helpfulthanks in advance,['android'] +744703,directory structure for a project that mixes c and python say you want want to create a programming project that mixes c and python the foo c project structure uses cmake and a python module is created by using swig the tree structure would look something like thisa cmakeliststxta fooconfigcmakeina fooconfigversioncmakeina makefilea readmea fooaa a a cmakeliststxtaa a a confighppinaa a a foocppaa a a foohppa swig a fooinow you would like to make use of the foo project within a python project say bara authorsrsta contributingrsta historyrsta licensea manifestina makefilea readmersta docsaa a a makefileaa a a authorsrstaa a a confpyaa a a contributingrstaa a a historyrstaa a a indexrstaa a a installationrstaa a a makebataa a a readmerstaa a a usagersta baraa a a init pyaa a a barpya requirementstxta setupcfga setuppya testsaa a a init pyaa a a test barpya toxinithis structure was crated by using cookiecutters pypackage template a boilerplatepp template is also available to generate a cmake c project using cookiecutter no swig partso now that i have the structure of both projects and considering that the development will take place mainly in python and the the project will be run in different systems i need to address the following questionswhats the best way to mix them should i collapse both root directories should i have the foo c project as a directory of the bar project or the other way around i may be inclined to put the entire c structure shown above in a folder at the root level of the python project but i would like to know a priori any pitfalls as the cmake system is quite powerful and it may be convenient to do it the other way aroundin case i decide to put the foo project as a directory within bar is the python setuptools package as powerful as the cmake build system i ask this because when i take a look at the bar project at the top level it seems there is only a bunch of scripts but i do not know if this is the equivalent to cmake as i am new to pythonthe bar project outlined above has a single bar directory but i assume that whenever this project expands instead of having many other directories at the root level other directories containing python code will be placed within bar is this correct in the pythonic sensei assume that a single egg will be produced from the entire project so that it can be installed and run in many different python systems is the integration of the module created by the foo project easy i assume that this module will be created in a different directory than barin order for the python code within the bar directory the module created by swig has to be available so i guess the most straightforward way to do this is to modify the environmental variable pythonpath using the cmake system is this fine or is there a better way,"['python', 'c++']" +744758,intels haxm equivalent for amd on windows os is there any equivalent of intels haxm for amd windows os or has anybody been able to hack haxm to make it work on amd processors windows osalso would genymotion be significantly faster compared to the default google apis arm x86 system images provided by googlemy exact dev machine specsos windows 7 ultimateprocessor amd fx 8120 8 core 281 ghzthanks in advance,['android'] +744770,does capistrano 3 still put rails logs in sharedlog i have upgraded to capistrano 3 and successfully deployed several rails apps on a new serverpreviously with capistrano 2 deployments the rails logs magically went to myappsharedlogproductionlogwith my cap3 deployments the logs are in the app folder myappcurrentlogproductionlogis this intentional or have i missed setting something upis there some special way to set it up so that they go to sharedlog,['ruby-on-rails'] +744795,passing property as parameter i am creating a merit function calculator which for the uninitiated takes a selection of properties and calculates a value based on how close those properties are to some idealized values the merit function this then enables the user to find an item that most closely matches their requirementsthis is the code i would like to usepublic class meritfunctionline public funccalculationoutput double property get set public double value get set public comparisontypes comparisontype get set public class meritfunction public listmeritfunctionline lines get set public double calculatecalculationoutput values double m 0 foreach var item in lines m mathabsvaluesproperty itemvalue return m public class calculationoutput public double property1 get set public double property2 get set public double property3 get set public double property4 get set obviously this does not compile as values does not contain a member called property but here is an explanation of what i want to docreate a new meritfunctionadd an arbitrary number of meritfunctionlines to meritfunctionlinesthe meritfunctionlineproperty should specify what property of calculationoutput should be compared in meritfunctioncalculateiemeritfunction mf new meritfunctionmflinesaddnew meritfunctionline property x xproperty1 value 90 comparisontype comparisontypesgreaterthan mflinesaddnew meritfunctionline property x xproperty3 value 50 comparisontype comparisontypesequals calculationoutput c1 new calculationoutput property1 1 property2 20 property3 150 property4 500 calculationoutput c2 new calculationoutput property1 15 property2 32 property3 15 property4 45 double value1 mfcalculatec1double value2 mfcalculatec2i am not asking how to pass a property as a parameter into a function which is prohibited by c,['c#'] +744873,selecting values from list i have the following listpublic class products public string sku public int warehouseidlistproducts products new listproductswhich after populating the list i end up with the following dataproductcodewarehouseidsku0012sku0013sku0023sku0033sku0041sku0045i have multiple skus as the item can be supplied from more then one warehouse location as it is in stock in the case of sku001 warehouse id 2 has more stock than warehouse id 3i need to select the items from the least number of warehouse locations what i am trying to end up with is something likesku0013sku0023sku0033sku0041this limits product selection to only 2 locations as sku001 sku002 sku003 can all be obtained from warehouse id 3 ideally selecting from a location with the most stock but limiting the number of locations is more importanti am using linq to try and achieve this while trying to loop each list item but am struggling as linqs not a strong point for me i tried to first get the highest count of repeating warehouse ids usingproductsgroupbyi iorderbydescendinggrp grpcountselectgrp grpkeyfirstordefaultbut am getting lost on the rest of the items any ideas on how i could achive this,['c#'] +744874,how to add html content at select2 dropdown box i have used select2 plugin for tag input here is the fiddle of my basic work i need showing used number of each optionstags at dropdown box like this wayi have created a class for that number in my css usednumber but i do not understand how can i add that number for each options at my html file is there a way to add those something like thisor any other waytagselect2 datatag redtext3classname usednumbertag greentext12classname usednumbertag bluetext5 classname usednumbertag blacktext7,['jquery'] +744971,androidgradle include version name from flavor in apk file name i have found similar questions but nothing that quite works for what i want to do i am developing with android studio and gradle and i have several flavors in my build file each of which has a versionname is there a way to include the flavors version name in the apk file,['android'] +745049,single page webapp screen transitions with maintaining the scroll position i am build a single page web application for mobile phones the application should implement transitions between screens like any other mobile app eg facebook twitter and these transitions should be animated slide leftright each screen has to preserve its scroll position between transitionsone obvious solution that comes in mind is thisviewport div1 div2 div3 div4 the different screens are put into containers div1 div2 which are styled to fit the screen position absolute width 100 height 100 top 0 and have overflowx scroll the containers are positioned next to each other and the transition is as easy as animating their left propertyeasy so farthe problem is the following in this implementation the address bar does not thisappear in the mobile browser when the user scrolls downi am talking about this featureit is because mobile browsers do this only if the user scrolls the body not a container in the body there are several suggestions for solution but they do not work in all targeted platforms android chrome and native browser iphone safari and are quite hacky i would like to preserve the original behavior of the browser as it isfor that reason apparently need to leave the scrolling on the body this means that containers have to be fulength and not overflowscroll still positioned next to each other this is where transitions become difficult if you think about itmy current solution has the following steps when transitioning from div1 to div2position top of div2 to the current scrolltop of the windowanimate div1s and div2s left property so that div2 fills the screenmove div2s top to 0 once the animation has finished so that the user cannot scroll back further than the top of this screenmove the windows scrolltop to 0hide div1 in case it is longer than div2transitioning back to div1 is similar in reverse this actually works quite nice although it is insanely complex and uses transition event listeners but unfortunately there is a really ugly flickering effect between step 3 and 4 under ios safari because it renders the page right after step 3 without waiting for step 4i am looking for a frameworkindependent vanilla js solution,"['javascript', 'html', 'css']" +745090,how to resolve athis is an invalid webresource requesta error in asp net after upgrading asp net 35 app to net 452 we started receiving numerous athis is an invalid webresource requesta errors we have traced the error to missing css from obout control dll the control is used widely and we cannot replace it the upgrade was performed month and half ago and we still receive the same number of errorsi am aware of other stackoverflow questions regarding the same problem but some of the answers suggest problem thisappears with time this has not happened in our case yet almost 2 months after upgrade,['asp.net'] +745144,how to write a module that works with nodejs requirejs as well as without them i am working on a javascript library for jsonxml processing my library works in browser as well as nodejs with xmldom and xmlhttprequest modulesone of the users recently asked for requirejs support i have taken a look at the requirejsamd thing and think it is a good approach so i would like to provide thishowever i would like to retain the portability my library must work in browsers with and without requirejs as well as nodejs and in the browser environment i do not depend on xmldom or xmlhttprequest since these things are provided by the browser itselfmy question is how can i implement my library so that it works in browsers as well as in nodejs with an without requirejsa bit of historyand my current solutioni initially wrote my library for browsers so it just created a globalscope object and put everything inside itvar jsonix later on users asked for nodejs support so i addediftypeof require function moduleexportsjsonix jsonixi also had to import few modules mentioned above i did it conditionally depending on whether the require function is available or notif typeof require function var xmlhttprequest requirexmlhttprequestxmlhttprequest return new xmlhttprequestnow there is this story with requirejs if requirejs is present then the require function is present as well but module loading works differently i have to use the define function etc i also cannot just require things since require has an async api in requirejs moreover if my library is loaded via requirejs it seems to process the source code and detects requiresomething even if i do it conditionally likeif typeof require function typeof requirespecified function requirejs still detects requirexmlhttprequest an tries to load the corresponding js filecurrently i am coming to the following solution module factory function amd stylevar jsonix function jsonix xmldom jsonix xmlhttprequest jsonix fs complete jsonix script is included below var jsonix complete jsonix script is included above return jsonix jsonix if require function exists if typeof require function but define function does not exists assume were in the nodejs environment in this case load the define function via amdefine if typeof define function var define requireamdefinemodule definexmldom xmlhttprequest fs jsonix else otherwise assume were in the requirejs environment define jsonix since require function does not exists assume were neither in nodejs nor in requirejs environment this is probably a browser environmentelse call the module factory directly var jsonix jsonixand this is how i check for dependencies nowif typeof jsonix xmlhttprequest undefined var xmlhttprequest jsonix xmlhttprequestxmlhttprequest return new xmlhttprequestif i have require but not define then i assume this is a nodejs environment i use amdefine to define the module and pass the required dependenciesif i have require and define thet i assume this is a requirejs environment so i just use the define function currently i also assume this is a browser environment so dependencies like xmldom and xmlhttprequest are not available and do not require them this is probably nor correctif i do not have the require function then i assume this is a browser environment without requirejsamd support so i invoke the module factory jsonix directly and export the result as a global objectso this is my approach so far seems a little bit awkward to me and as a newbie to requirejsamd i am seeking advise is it the right approach are there better ways to address the problem i would be grateful for your help,['javascript'] +745277,switch statement in swift i am learning syntax of swift and wonder why the following code is not working as i expect it tofor i in 1100 switch i case 1 inti3 0 printlnfizz case 2 inti5 0 printlnbuzz default printlni i want to print fizz every time number is divisible by 3 3 6 9 12 etc and print buzz every time it is divisible by 5 what piece of the puzzle is missingnote i did solve it using the followingfor var i 0 i 101 i if inti3 0 printlnfizz else if inti5 0 printlnbuzz else printlni i want to know how to solve this using switch thank you,['ios'] +745391,can mybatis create the database schema has mybatis any feature to allow create the sql schema from de class model like hibernate doesi am looking for that in google and i only found information about mybatis generator this tool seems to be useful for generate the java model from the sql schema which is just the opposite i want,['java'] +745465,position a floated div vertically within text i am attempting to find a pure css solutions to create an article with a featured quote section that starts 50px or so down the page this section should be 50 width and the text should wrap around it top and bottomcurrent i have the standard float solution where it appears at the top of the textfiddle demoinsettext thisplayblock width 50 float left background pink margin 0 5 2 0,"['html', 'css']" +745563,ajax post multiple data to aspnet mvc i am facing problem while posting multiple objects via ajax jquery to mvc 4 controller it has been weeks but i cannot seem to find a solutioni tried several approaches sometimes the filtermodel object is null and sometimes string parameters are null does not matter even if i stringify of if i specify contenttype or notwhat i wanti want to pass three objects 1 filtermodel 2testparama 3testparambwhat should i do to pass all three objects to mvc controller what do i need to write in data so i get all 3 object valuesthe simplest controllerhttppostpublic jsonresult teststring testparama string testparamb filtermodel filter using rbsystementities repository new rbsystementities return jsonnew datalist repositoryitemsselectx new xpkid xitemnametolist result ok the simplest viewvar filtermodel htmlrawjsonencodenew filtermodelitemname pepperoni pizzafiltermodel jsonstringifyfiltermodelfunction testme post the javascript variable back to the controller ajax url menutest type post contenttype applicationjson charsetutf8 data filter filtermodel testparama a value testparamb b value with this approach i get filtermodel null in the controller however testparama and testparamb has values data filtermodel with this approach i get values for filtermodel but i cannot pass testparama and testparamb success function result todo do something with the results alertsuccess testmethe simplest filtermodel classpublic class filtermodel public filtermodel public filtermodelstring filtercolumn string filtervalue thisfiltercolumn filtercolumn thisfiltervalue filtervalue thisfiltercolumncriteria public string filtercolumn get set public string filtervalue get set public string filtercolumncriteria get set,"['c#', 'jquery']" +745682,why is len called implicitly on a custom iterator i am writing a simple linked list implementation as followsclass nodeobject def init self value selfvalue value self next none def iter self here self while here yield here here here next def len self printcalling len on formatself return sum1 for in self def append to tailself value if self next is none self next nodevalue else self nextappend to tailvaluedef print listll printllvalue if ll next print listll nextmy list nodeamy listappend to tailbmy listappend to tailcprint listmy listthis code runs fine without the len method deleting those three lines and running the code above outputs first second thirdhowever if the len method is present then the results are first calling len on main node object at 0x108804dd0 calling len on main node object at 0x108804dd0 snip calling len on main node object at 0x108804dd0 calling len on main node object at 0x108804dd0 traceback most recent call last file len examplepy line 31 in module print listmy list file len examplepy line 24 in print list if ll next file len examplepy line 14 in len return sum1 for in self file len examplepy line 14 in genexpr return sum1 for in self file len examplepy line 8 in iter while here file len examplepy line 14 in len return sum1 for in self file len examplepy line 14 in genexpr return sum1 for in self snip file len examplepy line 8 in iter while here file len examplepy line 13 in len printcalling len on formatself runtimeerror maximum recursion depth exceeded while calling a python objectnote the presence of first in the output print list is executed once but something is implicitly calling the len method before recursing what is calling that methodi see the same behavior with python 331 and 273,['python'] +745689,swift and coredata problems with relationship nsset nsset intersectsset set argument is not an nsset i have been trying to get my head around adding objects in relationships using coredata and swift i am at a loss i do not understand why my code does not work i am trying to add an event to a team i can not find the difference between accepted answers that should work and my code that does notteamsswiftimport foundationimport coredataclass teams nsmanagedobject nsmanaged var teamname string nsmanaged var matches nssetextension teams func addeventtoteameventevent selfmutablesetvalueforkeypathmatchesaddobjectevent var matchez nsmutableset matchez selfmutablesetvalueforkeymatches matchezaddobjectevent var manyrelation selfvalueforkeypathmatches as nsmutableset manyrelationaddobjectevent func getteamname string return teamname calling code from configure viewimport uikitimport coredataclass detailviewcontroller uiviewcontroller nsfetchedresultscontrollerdelegate var managedobjectcontext nsmanagedobjectcontext nil iboutlet weak var detaildescriptionlabel uilabel var detailitem anyobject didset update the view selfconfigureview func configureview update the user interface for the detail item if let detail event selfdetailitem as event if let detail anyobject selfdetailitem if let label selfdetaildescriptionlabel labeltext detailvalueforkeytimestampdescription selfinsertnewobjectself labeltext stringdetailgetnumberofteams detailgetteams var hej arrayteams hej detailgetteams labeltext tjosan for tmpteam teams in hej labeltext labeltext tmpteamgetteamname if true override func viewdidload superviewdidload do any additional setup after loading the view typically from a nib selfconfigureview override func didreceivememorywarning superdidreceivememorywarning thispose of any resources that can be recreated var fetchedresultscontroller nsfetchedresultscontroller if fetchedresultscontroller nil return fetchedresultscontroller let fetchrequest nsfetchrequest edit the entity name as appropriate let team nsentitydescriptionentityfornameteams inmanagedobjectcontext selfmanagedobjectcontext fetchrequestentity team set the batch size to a suitable number fetchrequestfetchbatchsize 20 edit the sort key as appropriate let sortdescriptor nssortdescriptorkey teamname ascending false let sortdescriptors sortdescriptor fetchrequestsortdescriptors sortdescriptor edit the section name key path and cache name if appropriate nil for section name key path means no sections let afetchedresultscontroller nsfetchedresultscontrollerfetchrequest fetchrequest managedobjectcontext selfmanagedobjectcontext sectionnamekeypath nil cachename master afetchedresultscontrollerdelegate self fetchedresultscontroller afetchedresultscontroller var error nserror nil if fetchedresultscontrollerperformfetcherror replace this implementation with code to handle the error appropriately abort causes the application to generate a crash log and terminate you should not use this function in a shipping application although it may be useful during development printlnunresolved error error erroruserinfo abort return fetchedresultscontroller var fetchedresultscontroller nsfetchedresultscontroller nil func insertnewobjectsender anyobject let context selffetchedresultscontrollermanagedobjectcontext let team selffetchedresultscontrollerfetchrequestentity let newmanagedobject nsentitydescriptioninsertnewobjectforentityfornameteamname inmanagedobjectcontext context as teams if appropriate configure the new managed object normally you should use accessor methods but using kvc here avoids the need to add a custom class to the template newmanagedobjectsetvaluelagur namnurk forkey teamname newmanagedobjectaddeventtoteamselfdetailitem as event save the context var error nserror nil if contextsaveerror replace this implementation with code to handle the error appropriately abort causes the application to generate a crash log and terminate you should not use this function in a shipping application although it may be useful during development printlnunresolved error error erroruserinfo abort error message20140813 183846651 score calculator 210538829319 terminating app due to uncaught exception nsinvalidargumentexception reason nsset intersectsset set argument is not an nsset first throw call stack 0 corefoundation 0x01028a53e5 exceptionpreprocess 165 1 libobjcadylib 0x01043b8967 objc exception throw 45 2 corefoundation 0x010280fc6c nsset intersectsset 940 3 foundation 0x0102d0c4a6 nskeyvaluewillchangebysetmutation 156 4 foundation 0x0102c804fa nskeyvaluewillchange 386 5 foundation 0x0102d0c3fb nsobjectnskeyvalueobservernotification willchangevalueforkeywithsetmutationusingobjects 310 6 coredata 0x01024178d7 nsmanagedobject nsinternalmethods includeobjectintopropertywithkeyandindex 551 7 coredata 0x0102418294 nsmanagedobject nsinternalmethods maintaininverserelationshipforpropertyforchangeonset 276 8 coredata 0x0102416ef2 nsmanagedobject nsinternalmethods didchangevalueforrelationshipnamedwithinverse 562 9 foundation 0x0102c835d6 nskeyvaluenotifyobserver 356 10 foundation 0x0102c827fd nskeyvaluedidchange 466 11 foundation 0x0102d0c7ee nsobjectnskeyvalueobservernotification didchangevalueforkeywithsetmutationusingobjects 118 12 coredata 0x01024180b0 nsmanagedobject didchangevalueforkeywithsetmutationusingobjects 80 13 coredata 0x010242fa11 nsnotifyingwrappermutableset addobject 161edit a couple of clarifications teams and event have a multitomulti unordered relationship,['ios'] +745719,java allows to assign byte to javalangshort but not to javalanginteger final byte b 12 short s b integer i bprogram compiles fine for short but for integer compilation fails with incompatible types message i am having difficult time trying to understand this behavior i could not find anything for this specific scenario,['java'] +745816,bootstrap tags input width i am trying to use bootstrap tagsinput in a form contained in a modallike thisdiv classformgroup label formytaglabeltagslabel input classformcontrol idmytag typetext dataroletagsinput divas you can see in the image above i cannot see why the input does not have the width of the containing formupdatethis reproduces the issue,['css'] +745835,why would an indexed column return results slowly when querying for is null i have a table with 25 million rows indexed appropriatelybut adding the clause and status is null turns a super fast query into a crazy slow query please help me speed it upqueryselect student id grade statusfrom gradeswhere class id 1 and status is null this line delays results from 200ms to 4070s and grade between 0 and 07limit 25tablecreate table if not exists grades student id bigint20 not null class id int11 not null grade float106 default null status int11 default null unique key unique key student idclass id key class id class id key status status key grade grade engineinnodb default charsetutf8 collateutf8 unicode cilocal development shows results instantly 200ms production server is huge slowdown 4070 secondscan you point me in the right direction to debugexplain id select type table type possible keys key key len ref rows extra 1 simple grades index merge class idstatusgrade statusclass id 54 null 26811 using intersectstatusclass id using where,"['mysql', 'sql']" +745840,observablewhere with async predicate is there a convenient way to use an async function as the predicate of a where operator on an observable for example if i have a nice tidy but possibly longrunning function defined like thistaskint rankobject itemis there a trick to passing it to where and maintaining the asynchronous execution as inmyobservablewhereasync item await rankitem 5in the past when i have needed to do this i have resorted to using selectmany and projecting those results into a new type along with the original value and then doing the filtering based on thatmyobservableselectmanyasync item new shouldinclude await rankitem 5 item item whereo oshouldinclude selecto oitemi think that is terribly unreadable though and i feel like there must be a cleaner way,['c#'] +745880,mysql considers and n equal how do i set it to consider them different i have a table with a unique constraint on a varchar field when i try to insert e and n in two different rows i am prompted with a unique constraint violation executing the following select shows that mysql considers the letters equivalent in spite of their hex values being d0b5 and d191 respectively select n hex hexnfollowing a fair amount of googling i came across this mysql bug report which seems to deal with this issue the very last response by sveta smirnova states that this behavior is by design and refers to the collation chart for utf8 unicode ci european alphabets mysql 604how do i tell mysql that is not equal to n for query purposes and how do i change the unique constraint to take note of this fact,['mysql'] +745882,operator friend function and templates this is my codemovhinclude iostreamtemplate class tclass movie public moviet in a in friend stdostream operatorstdostream os const moviet movieprivate t atemplateclass tstdostream operatorstdostream os const moviet movie return osmaincppinclude movhint main movieint movie11 stdcout movie1 stdendl return 0i try to compile this code and i get the errorerror 1 error lnk2019 unresolved external symbol class stdbasic ostreamcharstruct stdchar traitschar cdecl operatorclass stdbasic ostreamcharstruct stdchar traitschar class movieint const 6yavbasic ostreamduchar traitsdstdstdaav01abvmoviehz referenced in function main cusersadidocumentsvisual studio 2013projectsbdika01bdika01mainobj bdika01error 2 error lnk1120 1 unresolved externals cusersadidocumentsvisual studio 2013projectsbdika01debugbdika01exe 1 1 bdika01if i try the code inline like this it is okaymovh include iostream templateclass t class movie public moviet in a in friend stdostream operatorstdostream os const moviet movie return os private t awhat can i do if i want to separate the defination and declarationthanks,['c++'] +745943,mysql error 18 row size too large when restoring djangomailer database i dumped a working production database from a django app and am trying to migrate it to my local development environment the production server runs mysql 51 and locally i have 56when migrating the djangomailers messagelog table i am running into the dreaded error 18error 18 420 at line 26 row size too large 8126 changing some columns to text or blob may help in current row format blob prefix of 0 bytes is stored inlinei have read lots of stuff online about this error but none of it has solved my problemnb this error is not coming from the creation of the table but rather the insertion of a row with pretty large datanotesthe innodb file format and innodb file format max variables are set to barracudathe row format is set to dynamic on table creationthe table does not have very many columns schema below field type null key default extra id int11 no pri null auto increment message data longtext no null when added datetime no null priority varchar1 no null when attempted datetime no null result varchar1 no null log message longtext no null again the error happens only when i try to insert a quite large message data is about 5 megabytes row creating the table works fine and about 50 rows are added just fine before the failurei am out of ideas i have tried dyanmic and compressed row formats and i have triple checked the values of the relevant innodb variablesmysql show variables like innodb file variable name value innodb file format barracuda innodb file format check on innodb file format max barracuda innodb file per table on the creation code from show create table looks likecreate table mailer messagelog id int11 not null auto increment message data longtext not null when added datetime not null priority varchar1 not null when attempted datetime not null result varchar1 not null log message longtext not null primary key id engineinnodb auto increment869906 default charsetlatin1 row formatdynamic,['mysql'] +746045,what precision are floatingpoint arithmetic operations done in consider two very simple multiplications belowdouble result1long double result2float var131float var26789double var38745double var4234987result1var1var2result2var3var4are multiplications by default done in a higher precision than the operands i mean in case of first multiplication is it done in double precision and in case of second one in x86 architecture is it done in 80bit extendedprecision or we should cast operands in expressions to the higher precision ourselves like belowresult1doublevar1doublevar2result2long doublevar3long doublevar4what about other operationsadd division and remainder for example when adding more than two positive singleprecision values using extra significant bits of doubleprecision can decrease roundoff errors if used to hold intermediate results of expression,['c++'] +746163,view bring to front doesnt work i want to change z order of some views during animationon androids above 412 it works just fine and on androids below 412 the z order doesnt change the top view remains on topthis is what i am trying myviewbringtofrontviewmyviewgetparentinvalidatehow to make it work on older devices,['android'] +746186,how do i make recyclerview update its layout i have a recyclerview with a bunch of custom views which may change height after a while because they contain imageviews which load their image asynchronously the recyclerview does not pick up on this layout change although i call forcelayout on the imageview and the recyclerview is initialized with sethasfixedsizefalse all containerparents of the imageview have set androidlayout heightwrap contenthow can i make the recyclerview update its layout with goodol listview this was not a problem,['android'] +746251,java fileoutputstream consecutive close takes a long time i am facing a little weird situationi am copying from fileinputstream to fileoutputstream a file that is sized around 500mbit goes pretty well takes around 500ms when i close this fileoutputstream the first time it takes about 1ms but here comes the catch when i run this again every consecutive close takes around 150020msthe duration is dropped back to 1ms when i delete this fileis there some essential javaio knowledge i am missingit seems to be related to os i am running on archlinux the same code run on windows 7 have all the times under 20ms note that it does not matter if it runs in openjdk or oracles jdk hard drive is a solid state drive with ext4 filesystemhere is my testing codepublic void copymultipletimes throws ioexception copy copy copy new filehomed1xtemp500mboutdelete copy copy runtimegetruntimeexecsync same results threadsleep30 same results combination of sync sleep same results copyprivate void copy throws ioexception fileinputstream fis new fileinputstreamhomed1xtemp500mbin fileoutputstream fos new fileoutputstreamhomed1xtemp500mbout ioutilscopyfis fos copylarge same results copying takes always the same amount of time only close enlarges fisclose input stream close this is always fast fosflush has no effect fosgetfdsync solves the problem but takes 25s long start systemcurrenttimemillis fosclose systemoutprintlnoutputstream close took systemcurrenttimemillis start msthe output is thenoutputstream close took 0msoutputstream close took 1951msoutputstream close took 1934msoutputstream close took 1msoutputstream close took 1592msoutputstream close took 1727ms,['java'] +746298,crossorigin resource sharing cors concept i have a question on the concept cross domain javascriptthere is serverex amazoncom where in only selected domains can use their webserviceso definitely if i try to use their service from my local i cannot i got this on my console crossorigin request blocked the same origin policy thisallows reading the remote resource at l52761wjson0 this can be fixed by moving the resource to the same domain or enabling corsps i used jquery cross domain way too but didnt workbut if some domain who is among the selected ones to use amazons webservice has a javascript which if we include in our html it worksscript srcscriptthey have a method to get response by ajaxmy questions arewhat happens when we refer a javascript file from an internet url do we have a local copy running on our machineis the httprequest created will have a request source as my domain or the xyz,"['javascript', 'jquery']" +746327,why is turning into after page load i am using firefox and working on a page when i notice that turns into amp usually i can fix this by using html entitiy decode but in this case it is not workingthen i thiscovered this the alert is fired once the page is loadedbeforeafterthe data is loaded using php yii not through js ajax i am however adding removing brands using js knockoutul databindtemplate name branditemtemplate data rootbrands li span id brandid databindtext brand name attr id brand id brandname span a href classremove eliconremovecircle databindclick parentremovebranda liulupdate i have thiscovered that this js knockout code is what makes the change but this code should not be triggered until i add a brand so why is this affecting my sit is the selfaddbrand function that makes the change if i remove this function and leave the rest as it is everything is fine can it be a knockout bugstoremanagespecialoffersexistsfunction storemangespecialoffersfunction managebrandlistmodel var self this var store id dataitemidval var exiting list brandlist ulclone data selfbrands koobservablearraycreate listexiting list selfbrand name koobservable selfbrand id koobservable selfstore id koobservablestore id this is the function that makes the chage selfaddbrand function if selfbrand name update db storemanagebrandsexistsfunction ajax url site url associatebrand type post datatype json data brand brandid selfbrand id storeid selfstore id add true success function data add brand to gui list selfbrandspushnew brandselfbrand id selfbrand name selfbrand name bindself function create listexiting list var arr list exiting listfindlieachfunctioneli var id lifindspanpropid var name lifindspanhtml this is the problem must be text arr listpushnew brandidname return arr listcan anyone explain why this is happening,['html'] +746374,bubblepopuphelper filling android debug log so i noticed when i was debugging that there seems to be a tag that is repeating through my app entitled bubblepopuphelper with text isshowingbubblepopup falsescreenshot of the logto my knowledge i am not using or causing it does anyone have an idea of whats going on the application is the one i am writingupon further inspection i did notice that every time i am updating text via a textview it thisplays onscreen if there is a better way of doing so please let me knowthanks,['android'] +746534,determining whether a c class has a private destructor let us say i have the following codeclass exampleifndef private destructorpublicendif example public friend class friendclass friendpublic void membervoid friendmember stdprintfexamples destructor is sn isdestructorprivateexamplevalue private publicis it possible to implement the isdestructorprivate template above to determine whether a clas destructor is private or protectedin the cases i am working with the only times i need to use this isdestructorprivate are within places that have access to such a private destructor if it exists it does not necessarily exist it is permissible for isdestructorprivate to be a macro rather than a template or be a macro that resolves to a template c11 is fine,['c++'] +746537,changing database name in laravelhomestead i started learning laravel just an hour ago and following tutorialsmy settings for database are as follow file appconfigdatabasephpdefault mysqlconnections array sqlite array driver sqlite database dir databaseproductionsqlite prefix mysql array driver mysql host localhost database laraveltest username root password secret charset utf8 collation utf8 unicode ci prefix in mysql on homestead i already created laraveltest database i also created migration file in databasemigration directory with following codepublic function up schemacreateusers functiontable tableincrementsid tablestringemailunique tablestringname tabletimestamps and migration commands werevagranthomesteadcodelaravel php artisan migratemigration table created successfullymigrated 2014 08 14 195103 create users tableas thisplayed table users created but in homestead database not in laraveltest database can someone please tell where i went wrong and how to force laravel to use laraveltest databaseedit after first commentfile bootstrapstartphpenv appdetectenvironmentarray local arrayhomestead,['php'] +746733,most efficient way to insert rows into mysql database i have read a lot of questions about that but i could not find one that is fast enough i think there are better ways to insert a lot of rows into a mysql databasei use the following code to insert 100k into my mysqldatabasepublic static void csvtomysql string connectionstring server1921681x string command insert into user firstname lastname values firstname lastname using mysqlconnection mconnection new mysqlconnectionconnectionstring mconnectionopen forint i 0i 10i inserting 100k items using mysqlcommand mycmd new mysqlcommandcommand mconnection mycmdcommandtype commandtypetext mycmdparametersaddwithvaluefirstname test mycmdparametersaddwithvaluelastname test mycmdexecutenonquery this takes for 100k rows about 40 seconds how can i make this faster or a little more efficient might be faster to insert multiple rows via a datatabledataadapter or at onceinsert into user fn ln values fn1 ln1 fn2 ln2due to security issues i cannot load the data into a file and mysqlbulkload it,"['c#', 'mysql']" +746847,why cannot we use a for loop to create an animation with the help of the jquery library and the offset method it seems logical to think that by writing this simple code the element will gradually change positionfor i 0 i 900 i i 5 movingelementoffset top i the browser will stop for a while and will finally move the element to a position 900px apart from the top no transition can be observed out of curiosity i wrote this for i 0 i 900 i i 5 movingelementoffset top i consolelogito see that the console is outputting the succession of numbers fine but it only offsets the element once the for loop is over why is this not done gradually as the code is being executed,"['javascript', 'jquery']" +746921,ios8 extension needs own provisioning profile i am starting an ios 8 extension but i cannot run it on my device the error when trying to run it isno matching provisioning profiles foundthe provisioning profile specified in your build settings aextensionnamea has an appid of netcompanyappname which does not match your bundle identifier netcompanyappnameextensionname xcode can resolve this issue by downloading a new provisioning profile from the member centerdo i need a separate provisioning profile for both the main app and the extension should they share a bundle identifier by default it adds the extension name to the bundle identifier so perhaps not if it has a separate bundle identifier how is that reflected in the provisioning profile if there is a separate one,['ios'] +746963,jersey redirect after post to outside url i am using jersey to create rest api i have one post method and as a response from that method user should be redirected to custom url like that does not have to be related to api i was looking at other similar questions on this topic here but did not find anything that i could use,['java'] +746967,using gradle to test android apps in an emulator ok i want to use gradle to run my tests in an emulatorgradle has two targets that allow me to run testsconnectedcheckdevicecheckif i understood correctly we should use devicecheck to test stuff in an emulator but when i run it runs no testsconnectedcheck also does not work because it cannot find a device emulators do not appear in the android studio the way my cell phone dowhat i would like is ideallyrun my gradle scriptit boots up an emulatorit runs tests on that emulatorit turns down the emulatori would also like to have a target that would not boot or turn down the emulator but it will use one if one is upit is possible to do any of these things i cannot find documentation anywhere on how to configure gradle android plugin,['android'] +747026,how can mywebsite ship a javascript package jquery or angularjs that websitea and websiteb can use without conflicts say i have a website mywebsite where you can build content for a calltoactionbox that should show on another website websitea and on more websites that choose our solution without using an iframe how can that box be created using jquery or angularjs without conflicts without knowing what the customer has in their webpage they just import our some scriptjs set some settings and that is it most importantly we cannot mess up the customers side obviously nor should whatever tech the customer is using mess up our superduper boxi would love to see a working example this is hard i think so please take more time to think before answering if you have not solved such a problem appreciate the help guys,"['javascript', 'jquery']" +747030,getenginebynamenashorn returns null cant get nashorn enginescriptengine engine new scriptenginemanagergetenginebynamenashornengineevalprinthello worldengine returns nulli am using eclipse jdk180 11java versionjava version 180 20eajavatm se runtime environment build 180 20eab23,['java'] +747041,using sound effects with audioengine background i saw a video titled avaudioengine in practice from the following list of videos published at apples recent wwdc to apply sound effects to an audioafter that i was successfully able to change the pitch of an audio with the following code audio engine is initialized in viewdidload audioengine avaudioengine the following action is called on clicking a button ibaction func chipmunkplaybacksender uibutton var pitchplayer avaudioplayernode var timepitch avaudiounittimepitch timepitchpitch 10 audioengineattachnodepitchplayer audioengineattachnodetimepitch audioengineconnectpitchplayer to timepitch format myaudiofileprocessingformat audioengineconnecttimepitch to audioengineoutputnode format myaudiofileprocessingformat pitchplayerschedulefilemyaudiofile attime nil completionhandler nil audioenginestartandreturnerrorer pitchplayerplay from what i understand i used the audioengine to attach the audioplayernode with the audioeffect which i in turn attached to the outputi am now curious about adding multiple sound effects to the audio for instance pitch change and reverb how would i go about adding multiple sound effects to the audioalso would it make sense to attach and connect the nodes in viewdidload rather than how i have done it here in an ibaction,['ios'] +747055,pip python differences between installoptionprefix and root and target the pip documentation lacks too much wordings to my eyes about parameters to deal with source and destinationsi have experienced strange things installing sphinx with pip3 and playing with the options available to seemingly allow me to install it precisely where i wanted for some reasons i want to have each thing in its own directory i say aplayinga not that i did not read the doc nor tried help but because the pip3 help install did not help and the pip install official documentation page is too short on this and actually says not more than the pip3 help installhere are the experiments done and the observationsfirst case with rooti downloaded the current sphinx repository tarball unpacked it get into the newly created directory and didpip3 install root homeusernameappssphinx e i though this would be the same as prefix as there was no prefix option visibly available to my surprise it installed the commands in the bin directory of python3 which is also installed locally in its own directory along to some things in its library directory and strange instead of a homeusernameappssphinx directory i get a homeusernameappssphinxhomeusernameappssphinxa it appended the specified path to itselfhow especially the last point does make sense whats the purpose of rootsecond case with targetthen i though if it is not root that may be target so i did after a clean uppip3 install target homeusernameappssphinx e it did not work complaining about an unrecognized home optionwhat is this home which i did not specified it complains about and what exactly is targetthird case with installoptionprefixaafter some webasearching and a thread on stackoverflow i tried thispip3 install installoptionprefixhomeusernameappssphinx e it just complained it could not install a pth file and something is wrong with my pythonpath which was addressable restarting the same with the addition of a variable definitionexport pythonpathhomeusernameappssphinxlibpython34sitepackagespip3 install installoptionprefixhomeusernameappssphinx e i just had to the set pythonpath even before the directory actually exists and anything was installed in it but this one was ok whether or not pip should update pythonpath itself during the process and remind to set it up definitively is a debatable questionthis option which was the good one was also the less clearly visible oneanother last related onewhats the difference between editable and srcupdate 1i cannot tell if it is sphinx related but i noticed two additional thingsdoing pip3 install installoptionprefixinstalldir e repositorydirwhere repositorydir is a local check out of sphinx sphinx gets installed in installdir is listed by pip3 list but cannot be uninstalledon the opposite doingpip3 install installoptionprefixinstalldir sphinxthat is letting pip3 retrieving an archive sphinx is not installed in installdir is installed in the python directory instead is listed by pip3 list and can be uninstalleddepending on whether the source is a local repository or a remote archive it would not be installed at the same location and will not be or will be uninstallabledependencies were not affected were handled the same way in both cases installed where expected listed and uninstallableupdate 2the behaviour with root make me feel about a kind of fakearoot like the one you get when building a debian package or when crossacompiling if it is intended to be the same then the path which surprised me is on the contrary expected,['python'] +747060,how do i call a controller action from an ember route while doing a transition my objective is to thisplay a fancy loading graphic on my page while ember fetches model data through the ember routethis led me to that inspired me to create an action on my pages controller which would show the loading overlay window in the dom for example heres my controllercontrollersusersjsexport default emberarraycontrollerextend actions thisplayloading function show the dom element that says loading i would like to call that while my data is loading so i then define a route as followsroutesusersjsexport default emberrouteextend model function params return thisstorefinduser params actions loading functiontransition originroute transitionsendthisplayloading but when i do this i get this erroruncaught error nothing handled the action thisplayloading if you did handle the action this error can be caused by returning true from an action handler in a controller causing the action to bubbleso my question is where can i define this action so that my loading method will be able to call itnote that trying thissendthisplayloading gave me this errorcannot trigger action thisplayloading because your app has not finished transitioning into its first route to trigger an action on destination routes during a transition you can call send on the transition object passed to the modelbeforemodelaftermodel hooksupdate i am able to catch this action on the route itself but then i still cannot call the action on my controllerupdate 2 thanks to kingpin2ks answer i have resolved this for those interested here is a full solutioncontrollersusersjsexport default emberarraycontrollerextend actions showloading function thissetisloading true hideloading function thissetisloading false routersusersjsexport default emberrouteextend model function params return thisstorefinduser params actions loading function thiscontrollerforuserssendshowloading didtransition function thiscontrollerforuserssendhideloading a key insight was that i can set an isloading property on my controller which determines whether my modal loading window is showing in the handlebars template,['javascript'] +747082,how to get the amount of ram 512 mb 1gb 2gb of the device in windows phone 81 universal i have a fairly simple question that i cannot answer my self also google and stackoverflow provided no results i want my decodepixelheight of my bitmapimage to be depended on the amount of ram the device has if the device has 512 mb then the decodepixelheight should be lower than 1gb and 2gb i do this because i am struggling with memory issueshow do i recognize a lowend device with 512 mb on windows phone 81 universal appkind regardsniels,['c#'] +747140,pip install error package directory x does not exist i am trying to install this package via pip it gives me the following errorerror package directory rtbatch does not existi find this weird because the relevant setuppy does not mention any packages variable but only py moduleswhats wrong can you help me out here is the full output of pip install e rtbatchobtaining filehomechymerartbatch running setuppy pathhomechymerartbatchsetuppy egg info for package from filehomechymerartbatch usrlib64python27thistutilsthistpy267 userwarning unknown thistribution option heywords warningswarnmsg error package directory rtbatch does not exist complete output from command python setuppy egg info usrlib64python27thistutilsthistpy267 userwarning unknown thistribution option heywords warningswarnmsgrunning egg infocreating rtbatchegginfowriting requirements to rtbatchegginforequirestxtwriting rtbatchegginfopkginfowriting toplevel names to rtbatchegginfotop leveltxtwriting dependency links to rtbatchegginfodependency linkstxtwriting manifest file rtbatchegginfosourcestxtwarning manifest maker standard file c not founderror package directory rtbatch does not existcleaning upcommand python setuppy egg info failed with error code 1 in homechymerartbatchstoring debug log for failure in homechymerapippiplog,['python'] +747234,reactive programming rxjs vs eventemitter in nodejs recently i have started looking at rxjs and rxjavafrom netflix libraries which work on the concept of reactive programming nodejs works on the basis of event loops which provides you all the arsenal for asynchronous programming and the subsequent node libraries like cluster help you to get best out of your multicore machine and nodejs also provides you the eventemitter functionality where you can subscribe to events and act upon it asynchronously on the other hand if i understand correctly rxjs and reactive programming in general works on the principle of event streams subscribing to event streams transforming the event stream data asynchronously so the question is what does using rx packages in nodejs mean how different is the nodes event loop event emitter subscriptions to the rxs streams and subscriptions,['javascript'] +747252,initializing char vs int this is possible in cconst char ch hellobut something like this is not possibleint i 1 2 3 both char ch and int i are plain pointers why can char be assigned with multiple chars while int can not be assigned with multiple intsi know we can use int x 1 2 3but that is not the question,['c++'] +747370,subclassing nsobject in swift best practice with initializers here is the layout of an example class can someone guide me on whats best practice when creating a subclass of nsobjectclass myclass nsobject var someproperty nsstring nil override init selfsomeproperty john superinit initfromstring string nsstring selfsomeproperty string superinit is this correct am i following best practice herei wonder if i am correctly setting up the initializers one that sets the string to a default and one which i can pass in a stringshould i call superinit at the end of each of the initializersshould my more specific the one that takes a string initializer simply call selfinit at the end rather than superinitwhat is the right way to set up the initializers in swift when subclassing nsobject and how should i call the super init this question albeit in objective c suggests you should have an init which you always call and simply set the properties in more specific inits objectivec multiple initialisers,['ios'] +747398,how to handle exceptions thrown by observers onnext in rxjava consider the following exampleobservablerange1 10subscribei systemoutprintlni if i 5 throw new runtimeexceptionoops throwableprintstacktracethis outputs numbers from 1 to 5 and then prints the exceptionwhat i want to achieve is make the observer stay subscribed and continue to run after throwing an exception ie print all numbers from 1 to 10i have tried using retry and other various error handling operators but as said in the documentation their purpose is handling errors emitted by the observable itselfthe most straightforward solution is just to wrap the whole body of onnext into a trycatch block but that does not sound like a good solution to me in the similar rxnet question the proposed solution was to make an extension method which would do the wrapping by creating a proxy observable i tried to remake itobservableinteger origin observablerange1 10observableinteger proxy observablecreateobservableonsubscribeinteger s originsubscribei try sonnexti catch exception ignored sonerror soncompletedproxysubscribei systemoutprintlni if i 5 throw new runtimeexceptionoops throwableprintstacktracethis does not change anything because rxjava itself wraps the subscriber into a safesubscriber using unsafesubscribe to get around it does not seem to be a good solution eitherwhat can i do to solve this problem,['java'] +747411,pick image from css instead of html i have a tricky question might funny to some people herei am trying to overcome html img and use image via css background propertyso code is simple a idlogo hrefimg srclogo1pngacssposition relativeheight 85pxwidth 200pxbackground urllogo2png norepeatbackgroundsize 200px 200pxso i want logo1 from html removed and css image logo2 overtake logo1note no extra divs and classes only with that html markuptried everything but i think this is impossible,"['html', 'css']" +747446,multiple thens on single angularjs promise all use original data i am writing an angularjs app relying on promises and though it is working i wonder if i could do it more optimallyat the beginning of the code i am creating a promise that goes off to fetch some data when this is done i want to run several functions that all use this data the functions are attached at unrelated parts of the app so i do not know the order in which they are attached to the promise they do not need to be done in sequence eitherappservicefetch function q return function var def qdefer somelibraryasynccallfunctionerror data callback if error defrejecterror else defresolvedata return defpromise appcontrollerctrl function scope fetch var prom fetch somewhere promthenfunctiondatascopevar1 datavar1 somewhere else promthenfunctiondatascopevar2 datavar2the main thisadvantage here is that the later thens are only executed whenever the preceding ones are finished which is not necessary here also i need to add return data inside every functiondata otherwise the following then does not have the data available is there not another way to do this more apt for this situation edit as mentioned by jfriend00 i was mistaken in fact the 2 functions both run in parallel as soon as the promise is successfully resolved and they are not chained and therefore not dependent on each other thanks for your help,['javascript'] +747563,multiple uiview html files in uirouter is it possible to make something using 2 or more html files using uiview i need it to be something like this i have tryed to do something working on plinker but looks like i clearly do not uderstand concepts i have read a nested uivew tutorial but they simple make a single indexhtml and place multiple uiview there but i need multiple html filestesthtml is just a file with some text that should be thisplayed under master headerindexhtml looks like thishtml ngappmyapphead link hrefstylesheetsstylecss relstylesheetheadbodyh4 this should be master headerh4div uiviewdivscript datarequireangularjs datasemver130beta5 srcscriptscript datarequireuirouter datasemver0210 srcscriptscript srcappjsscriptscript srccontrollersmainjsscriptbodyhtmlthis is apphtmlhead link hrefstylesheetsstylecss relstylesheetheadbodyh4 this should be sub master header h4div uiviewdivbodyand appjs is written on pseudo code showing how i want it to work because i clearly have no idea how to make it work angularmodulemyapp uirouterconfigfunctionstateprovider urlrouterprovider urlrouterproviderotherwise stateprovider stateindex templateurl indexhtml controller indexctrl stateindextest url templateurl testhtml controller testctrl stateapp templateurl apphtml controller appcontroller stateapptest2 url test2 templateurl test2html controller test2controller test2html is just a text,"['javascript', 'html']" +747642,why is stringequals much slower for nonidentical but equal string objects i am delving into the question of is stringequals really that bad and while trying to do some benchmarking of it came across some surprising resultsusing jmh i wrote up a simple test code and pom at end which sees how many times the function can be run in 1 secondbenchmark mode samples score score error unitscssimplebenchmarktestequalsintern thrpt 5 698910949710 47115846650 opsscssimplebenchmarktestequalsnew thrpt 5 529118774 21164872 opsscssimplebenchmarktestisempty thrpt 5 470846539546 19922172099 opssthe this is a 1300x factor between testequalsintern and testequalsnew which is frankly quite surprising to methe code for stringequals does have a test for the same object which would kick the identical interned in this case string objects out quite quickly i just have have significant difficulty believing that the additional code which appears to amount to walking over an array of size 1 for the two tests and comparing elements is that much of a performance hiti have also put in a test with another simple method call in the string to make sure i was not seeing something that is too crazypackage comshagieimport orgopenjdkjmhannotationsbenchmarkimport orgopenjdkjmhrunnerrunnerimport orgopenjdkjmhrunnerrunnerexceptionimport orgopenjdkjmhrunneroptionsoptionsimport orgopenjdkjmhrunneroptionsoptionsbuilderpublic class simplebenchmark public final static int iterations 10 public final static string empty public final static string new empty new string benchmark public int testequalsintern int count 0 string str empty forint i 0 i iterations i ifstrequalsempty count return count benchmark public int testequalsnew int count 0 string str new empty forint i 0 i iterations i ifstrequalsempty count return count benchmark public int testisempty int count 0 string str new empty forint i 0 i iterations i ifstrisempty count return count public static void mainstring args throws runnerexception options opt new optionsbuilder include simplebenchmarkclassgetsimplename warmupiterations5 measurementiterations5 forks1 build new runneroptrun the pom for maven to quickly set it up yourself if you wish to reproduce thisproject xmlns xmlnsxsi xsischemalocation modelversion400modelversion groupidcomshagiegroupid artifactidbenchartifactid version10version packagingjarpackaging namestring benchmarks with jmhname prerequisites maven30maven prerequisites dependencies dependency groupidorgopenjdkjmhgroupid artifactidjmhcoreartifactid versionjmhversionversion dependency dependency groupidorgopenjdkjmhgroupid artifactidjmhgeneratorannprocessartifactid versionjmhversionversion scopeprovidedscope dependency dependencies properties projectbuildsourceencodingutf8projectbuildsourceencoding jmhversion095jmhversion javactarget16javactarget uberjarnamebenchmarksuberjarname properties build plugins plugin groupidorgapachemavenpluginsgroupid artifactidmavencompilerpluginartifactid version31version configuration compilerversionjavactargetcompilerversion sourcejavactargetsource targetjavactargettarget configuration plugin plugin groupidorgapachemavenpluginsgroupid artifactidmavenshadepluginartifactid version22version executions execution phasepackagephase goals goalshadegoal goals configuration finalnameuberjarnamefinalname transformers transformer implementationorgapachemavenpluginsshaderesourcemanifestresourcetransformer mainclassorgopenjdkjmhmainmainclass transformer transformers configuration execution executions plugin plugins pluginmanagement plugins plugin artifactidmavencleanpluginartifactid version25version plugin plugin artifactidmavendeploypluginartifactid version281version plugin plugin artifactidmaveninstallpluginartifactid version251version plugin plugin artifactidmavenjarpluginartifactid version24version plugin plugin artifactidmavenjavadocpluginartifactid version291version plugin plugin artifactidmavenresourcespluginartifactid version26version plugin plugin artifactidmavensitepluginartifactid version33version plugin plugin artifactidmavensourcepluginartifactid version221version plugin plugin artifactidmavensurefirepluginartifactid version217version plugin plugins pluginmanagement buildprojectthis was auto generated with appropriate tweaks made for group and artifact mvn archetypegenerate dinteractivemodefalse darchetypegroupidorgopenjdkjmh darchetypeartifactidjmhjavabenchmarkarchetype dgroupidorgsample dartifactidtest dversion10to run the tests mvn clean install java jar targetbenchmarksjar simplebenchmark wi 5 i 5 f 1as it will be a question the java version this is running under java versionjava version 160 65javatm se runtime environment build 160 65b1446211m4609java hotspottm 64bit server vm build 2065b04462 mixed modethe hardware which might come into question is os x 1094 on an intel xeon processor,['java'] +747650,what are the differences between maven jar plugin and maven assembly plugin could somebody explain me the exactly differences between these two maven plugins and when it is useful to work with one of these pluginsthanks a lot,['java'] +747678,infix vs prefix syntax name lookup differences operators in c are usually considered to be an alternative syntax for functionsmethods especially in the context of overloading if so the two expressions below should be synonymousstdcout 42operatorstdcout 42in practise the second statement leads to the following errorcall of overloaded aoperatorstdostream inta is ambiguousas usual such error message is accompanied with a list of possible candidates these areoperatorbasic ostream chart traits out char coperatorbasic ostreamchar traits out char coperatorbasic ostreamchar traits out signed char coperatorbasic ostreamchar traits out unsigned char csuch error raises at least two questionsin what way are the two statements different in terms of name lookupwhy operatorbasic ostreamchar traits outint c is missingit seems that infix and prefix notations are not fully interchangeable different syntax entails different name resolution tactics what are the differences and where did they come from,['c++'] +747688,cardview background color states not being respected in briefhow can we define color states of cardviews cardbackgroundcolor property in a listview layout in this case i am using rc1 of android l developer preview on a phone with 44 installed and comandroidsupportcardviewv72100rc1 in buildgradlelongerin cardview layout we set the corner radius and background color of the cardview via cardcornerradius and cardbackgroundcolorhowever the background color does not repect selected states ie if the list item is pressed for exampleif in the inner view of the cardview you set a background colour and associated states which are respected however it will thisplay over the corners you defined in the cardviewso how can we ensure the states in cardviews cardbackgroundcolor are respectedheres the color used for the cardbackgroundcolor colour with statesxmlselector xmlnsandroid item androidstate focusedtrue androidstate enabledfalse androidstate pressedtrue androidcolorandroidcolorholo green dark item androidstate focusedtrue androidstate enabledfalse androidcolorandroidcolorholo green dark item androidstate focusedtrue androidstate pressedtrue androidcolorandroidcolorholo green dark item androidstate focusedfalse androidstate pressedtrue androidcolorandroidcolorholo green dark item androidstate focusedtrue androidcolorandroidcolorholo green dark only this below is seen in the cardview thispaly item androidcolorandroidcolorholo blue bright selectorand the layout that uses the cardviewandroidsupportv7widgetcardview xmlnsandroid xmlnscardview xmlnstools androidlayout widthmatch parent androidlayout heightwrap content cardviewcardcornerradius10dp cardviewcardbackgroundcolorcolorcolour with states if we set a background color below it will overwrite our radius defined above textview xmlnsandroid xmlnstools toolstextlorem ipsum androididandroididtext1 androidlayout widthmatch parent androidlayout heightwrap content androidtextappearanceandroidattrtextappearancelistitem androidbackgroundnull androidgravitycenter vertical androidpaddingtop8dip androidpaddingbottom8dip androidpaddingstart8dip androidpaddingend8dip androidsupportv7widgetcardview,['android'] +747720,swift project crashing with thread 1 exc bad access code 1 address 0x0 i have been searching all over for a solution to this problem it looks like a bad memory access like trying to access an object that does not exist i tried using nszombie to see if something came up as far as i could tell nothing did it is crashing at the declaration for the app delegateappdelegateswiftuiapplicationmainclass appdelegate uiresponder uiapplicationdelegatevar window uiwindowfunc applicationapplication uiapplication didfinishlaunchingwithoptions launchoptions nsdictionary bool override point for customization after app launches parsesetapplicationidremoved on purpose clientkey removed on purpose pfanalyticstrackappopenedwithlaunchoptionslaunchoptions pffacebookutilsinitializefacebook return truefunc applicationapplication uiapplication openurl url nsurl sourceapplication string annotation anyobject bool return fbappcallhandleopenurlurl sourceapplication sourceapplication withsession pffacebookutilssessionfunc applicationdidbecomeactiveapplication uiapplication fbappcallhandledidbecomeactivewithsessionpffacebookutilssessionfunc applicationwillresignactiveapplication uiapplication sent when the application is about to move from active to inactive state this can occur for certain types of temporary interruptions such as an incoming phone call or sms message or when the user quits the application and it begins the transition to the background state use this method to pause ongoing tasks thisable timers and throttle down opengl es frame rates games should use this method to pause the gamefunc applicationdidenterbackgroundapplication uiapplication use this method to release shared resources save user data invalidate timers and store enough application state information to restore your application to its current state in case it is terminated later if your application supports background execution this method is called instead of applicationwillterminate when the user quitsfunc applicationwillenterforegroundapplication uiapplication called as part of the transition from the background to the inactive state here you can undo many of the changes made on entering the backgroundfunc applicationwillterminateapplication uiapplication called when the application is about to terminate save data if appropriate see also applicationdidenterbackgrounddashboardviewcontrollerswiftimport uikitclass dashboardviewcontroller uiviewcontrolleroverride func viewdidload superviewdidload do any additional setup after loading the viewoverride func didreceivememorywarning superdidreceivememorywarning thispose of any resources that can be recreatedusing breakpoints i have determined that it is not even getting past the class declaration for the app delegate i tried checking all of the classes in my mainstoryboard file as well to make sure everything was linked properly again as far as i can tell it is would really appreciate some more ideas on how to fix this thanksedit i solved the problem and the code has now been fixed hopefully this can help someone else if they are having a similar problem,['ios'] +747765,android change device system locale programmatically i want to change device locale not just the application locale from my app like the user can do in settings language keyboard languagecan someone please explain how to do it i have been searching for hours and can not find a way,['android'] +747791,mysql jconnector spends 50 time in commyqljdbcutilsreadaheadinputstreamfill i am profiling my application which uses spring hibernate mysqljavaconnector the visualvm shows that more than 50 cpu time is cost in commyqljdbcutilsreadaheadinputstreamfill when there are 10 parallel connections doing readis there any optimization to make it faster,"['java', 'mysql']" +747887,what purpose does a i have been on a view source spree lately on websites with interesting design and content one of those websites squarespace has blocks of script tags inside of a noscript tag like so page is at noscript idinlinedeps link relstylesheet typetextcss hrefcloudtypographycom7811972758964cssfontscss script typetextjavascript srcscript link relstylesheet href typetextcss noscriptit struck me as odd and got me googling for info to see if there is some kind of hidden functionalitypurpose for such an odd bit of html but to no avail is there some kind of purpose to having script tags inside of noscript elements or is this just an example of bad html,"['javascript', 'html']" +747971,how to thisable a navigation bar button item in ios i have created a navigation controller in the second view which is pushed i have some webservice call and placing a overlay view and setting selfviewuserinteractionenabled no once web service call is complete then i am reverting to selfviewuserinteractionenabled yes when i do this every other buttons except the buttons on the navigation bar are thisabled how to thisable those two navigation bar button items a button similar to back button which pops to first view controller and another button which gives info about helpi have tried using selfnavigationitembackbarbuttonitemenabled no but still i am able to tap on the button and can navigate to first screen how can i thisable these two buttons,['ios'] +748070,how to create docker image for local application taking file and value parameters i have a java application jar file that i want to be able to run from a docker imagei have created a dockerfile to create an image using centos as base and install java as suchdockerfilefrom centosrun yum install y java170openjdki ran docker build t mejava7 after to obtain the image mejava7however i am stuck at some dead endshow do i copy the jar file from the host into the imagecontaineri require 2 parameters 1 is a file which needs to be copied into a directory into the container at runtime the other is a number which needs to be passed to the jar file in the java jar command automatically when the user runs docker run with the parametersextra notesthe jar file is a local file not hosted anywhere accessible via wget or anything the closest i have at the moment is a windows share containing it i could also access the source from a git repository but that would involve compiling everything and installing maven and git on the image so i would rather avoid thatany help is much appreciated,['java'] +748132,error nonstatic method findviewbyidint cannot be referenced from a static context i am using android studio beta and while using this java code in oncreateview i get an errorlistview listview listview findviewbyidridsomelistviewthis is the errornonstatic method findviewbyidint cannot be referenced from a static contexthow do i fix this,"['java', 'android']" +748199,angular ngclass if else i would like to know how to do to make the false ngclasspageisselected1 is true if the page if the page is selected else falsediv idhomepage ngclass center pageisselected1 i therefore want you if isselected is true center isselected is false lefti trieddiv idhomepage ngclass pageisselected1 center left but it doesnt worki do not know what i am doing wrong can you help me please,"['javascript', 'html']" +748227,will multithreading improve performance significantly if i have a fixed amount of calculations that are independet from each other i am programming a raycasting game engineeach ray can be calculated without knowing anything about the other rays i am only calculating thistancessince there is no waiting time between calculations i wonder whether it is worth the effort to make the ray calculations multithreaded or notis it likely that there will be a performance boost,['c++'] +748339,move a view when scrolling in uitableview i have a uiview with a uitableview below itwhat i would like to do is to have the view above the uitableview move up out of the way when the user starts scrolling in the table in order to have more space for the uitableview and come down when you scroll down againi know that this is normally done with a table header view but my problem is that my table view is inside a tab actually it is a sidescrolling page view implemented using ttsliddingpageviewcontroller so while i only have one top uiview there are three uitableviewsis it possible to accomplish this manually my first thought is to put everything in a uiscrollview but according to apples documentation one should never place a uitableview inside a uiscrollview as this leads to unpredictable behavior,['ios'] +748440,mysqli xdebug breakpoint after closing statment result in many warnings i have a piece of code like thisconn new mysqlihost username passwd dbnamestmt connprepareselect stmtbind paramstmtexecutestmtbind resultwhilestmtfetch do something herestmtclose do something more here that has absolutely nothing to do with stmtthis works perfectly fine i get the results i expected there are no errors or anything that is not supposed to happenbut if i set a break point xdebug 225 226 228 232 and php 553 5515 560 566 5610 to a line after stmtclose i get many warnings likeproperty access is not allowed yetorcould not fetch mysqli stmti thought i missed to close another mysqli statement but i get all results there seems to be just no problem in my codeis there a way to get rid of this wrong warningsupdate this problem still exist in php 701 xdebug 240 rc3,['php'] +748441,multiple inheritance without virtual inheritance i am trying to understand multiple inheritance here is my codestruct a a static int n static int increment return n int an 0struct b public a struct c public a struct d public b c int main d d coutdincrementendl coutdincrementendlthis code works however if i change increment to nonstatic it will failmy questionswhy compiler complains ambiguous call of nonstatic version of increment while satisfies with the static oneif i add another increment function to b or c compiler will complain too even declared as static why,['c++'] +748508,nashorn java collections how to implement equals and hashcode in pure javascript iave faced with the following problem iad like to use javautilhashmap and javautilpriorityqueue in nashorn script where i need to use particular custom object as a key in the hashmap and also use hashmapcontainskey to check if there is a key in the map another option is to check if the object in a collectioncontainsobject oso obviously i need to implement equals and hashcode in my object basing on some field valuesfor exampletrying to use javascript doesnat work due to javascript doesnat have those methods please see sample 1 and sample 2extending javalangobject sample 3 works partially methods are being invoked buthow to plugin constructor with parametershow to do the cast from thisobject object to otherjdknashornjavaadaptersjavalangobject0 or vice versaimplementing my custom class in java and extend it in javascript sample 4 works but do i need nashorn if i have to use javavar priorityqueue javautilpriorityqueuevar hashmap javautilhashmapvar integer javalanginteger sample 1 does not work equals and hashcode are not being invokedfunction vertex1from cost thisfrom from thiscost cost thisequals functionother return thisfrom otherfrom thishashcode function return integerhashcodethisfrom var hm new hashmaphmputnew vertex11 10 10hmputnew vertex11 20 21 prints size is 2 but i would like to see 1printhashmap size hmsize prints falseprinthashmap1 contains hmcontainskeynew vertex11 20 sample 2 does not work equals and hashcode are not being invokedfunction vertex1from cost thisfrom from thiscost costvertex1prototype equals functionother return thisfrom otherfrom hashcode function return integerhashcodethisfrom var hm new hashmaphmputnew vertex11 10 10hmputnew vertex11 20 21 prints size is 2 but i would like to see 1printhashmap size hmsize prints falseprinthashmap1 contains hmcontainskeynew vertex11 20 sample 3 works partially methods are being invoked but 1 how to plugin construstor with parameters 2 how to do the cast from thisobject object to otherjdknashornjavaadaptersjavalangobject0 or vice versavar jobject javatypejavalangobjectvar vertex2 javaextendjobject from 0 equals functionother return thisfromequalsotherfrom hashcode function return integerhashcodethisfrom var hm new hashmap how to implement constructor for new vertex210 10hmputnew vertex2 10hmputnew vertex2 21 prints size is 2 because hashcode is the same and equals returns falseprinthashmap size hmsize prints false because equals returns falseprinthashmap1 contains hmcontainskeynew vertex2 sample 4 comarsenykomyobject is implemented in java works but nashorn is ambiguous thenvar myobject javatypecomarsenykomyobjectvar vertex2 javaextendmyobject var hm new hashmaphmputnew vertex21 10 10hmputnew vertex21 20 21printhashmap size hmsizeprinthashmap1 contains hmcontainskeynew vertex21 10edit 1 tomasz thanks have seen all the mentioned links but though that somewhat undocumented exists almost gave up with nashorn came to the following partial solution methods are being invoked constructor is being used but how to cast otherfrom in the equals method in order to get access to the from field of the original object this code produces different classes for each instance of a vertexloadnashornmozilla compatjsvar priorityqueue javautilpriorityqueuevar hashmap javautilhashmapvar integer javalangintegerfunction vertex1from cost thisfrom from thiscost cost thisequals functionother var value1 thisfrom how to get otherfrom here var value2 otherfrom printvalue1 value1 value2 value2 printother var eq value1equalsvalue2 printequals is eq return eq thishashcode function var hashcode integerhashcodethisfrom printhashcode is hashcode return hashcode var jobject javatypejavalangobject return javaextendjobject this does not work return this does not work return new javaadapterjavalangobject this works with loadnashornmozilla compatjs var type javaextendapplyjava jobject return new typethisvar hm new hashmaphmputnew vertex11 10 10hmputnew vertex11 20 21 prints size is 2 but i would like to see 1printhashmap size hmsize prints falseprinthashmap contains hmcontainskeynew vertex11 20edit 2thanks for tomasz as he pointed out every invocation of the javaextend function with a claspecific implementation object produces a new java adapter class thus we need to have one object extender and instantiate objects with that one type as he showed in his sample i modified it a little bit so it produces instances with the same class with either factory or direct constructor since we are using the same object extendervar hashmap javautilhashmapvar jinteger javalangintegervar jobject javaextendjavalangobjectvar createvertex function var equals functionother printthis vs other return this from otherfrom hashcode function var hashcode jintegerhashcodethis from printhashcode return hashcode return functionfrom cost return new jobject from from cost cost equals equals hashcode hashcode var jsvertex functionfrom cost return new jobject from from cost cost equals functionother printthis vs other return this from other from hashcode function var hashcode jintegerhashcodethis from printhashcode return hashcode var v1 jsvertex1 10var v2 jsvertex1 20var v1 createvertex1 10var v2 createvertex1 20var v3 createvertex1 20printv1class v2class returns trueprintv2class v3class returns truevar hm new hashmaphmputv1 10hmputv2 21printhashmap size hmsize prints 2 but i would like to see 1printhashmap contains hmcontainskeyv3 prints falsehowever there is a still an issue the type of the parameter of the equals is jdknashornjavaadaptersjavalangobject in other words the other and this inside equals are different types is there a way to cast or get from value from the object passed to the equalsthe solutionsee the solution for the problem is in the tomaszs answergreat work tomasz thanksps it is very sad that there is no neat and straightforward way to implement equals and hashcode in nashorn it would be useful for prototyping just compare that with this import groovytransformequalsandhashcodeequalsandhashcodeexcludescostclass vertex int from cost,"['java', 'javascript']" +748531,how to use retrofit and simplexml together in downloading and parsing an xml file from a site i just started working with retrofit i am working on a project that uses simplexml can somebody provide me an example in which one fetches an xml from a site eg and reads it out,['android'] +748577,cast int to pointer why cast to long first as in p void 42 in the glib documentation there is a chapter on type conversion macrosin the thiscussion on converting an int to a void pointer it says emphasis minenaively you might try this but it is incorrectgpointer pint ip void 42i int pagain that example was not correct do not copy it the problem is that on some systems you need to do thisgpointer pint ip void long 42i int long psource glib reference manual for glib 23992 chapter type conversion macros why is that cast to long necessaryshould any required widening of the int not happen automatically as part of the cast to a pointer,['c'] +748582,how to call simple get method using retrofit it would be nice if you help me to call a simple api get method using retrofit i have added the gson and retrofit jar file to the build path here is the interface public interface myinterface getmy apishop list response getmythingquerymid string param1 i am getting results only in log cat if i call the following in asynctask else i am getting networkormainthreadexception how should i call thisoverride protected void doinbackgroundvoid params todo autogenerated method stub restadapter restadapter new restadapterbuilder setendpointhttpipport setloglevelrestadapterloglevelfullbuild myinterface service restadapter createmyinterfaceclass mresponse servicegetmything455744 return null do i really have to call the restadapter in asynctask how can i get the jsonobject from the response,['android'] +748671,how to prevent momentjs from loading locales with webpack hello is there anyway you can stop momentjs from loading all the localesi just need english when your using webpack i am looking at the source it seems that if hasmodule is defined which it is for webpack then it always tries to require every locale i am pretty sure this needs pull request to fix but is there anyway we can fix this with a webpack confighere is my webpack config to load momentjsresolve alias moment pathjoin dirname srclibbowermomentmomentjs then anywhere i need it i just do requiremoment this works but its adding about 250kb of unneeded language files to my bundle also i am using the bower version of momentjs and gulpalso if this cannot be fixed by a webpack config here is a link to the function where it loads the locales i tried adding moduleexportsloadlocales to the if statement but i guesse webpack doesnt acaully work in a way where that would work it just requires no matter what i think it uses a regex now so i do not really know how you would even go about fixing it anyways thanks for any help,['javascript'] +748748,how to allow urls to contain dots in aspnet mvc5 i am working on a website that should allow dots in urls like wmysitecomsomedatamyname123my desired behaviour is to make that url equivalent to wmysitecomsomedatamyname123 but instead i am getting 404 errors because those dots make iis try to find a static file a similar question can be found here but the proposed solutions do not work in my case as i explain below this is what i have triedadding a new handler like suggested in the answer accepted in the old question does not work because i need this to work for several paths if i set path then all static files for example css files fail i can specify a url pattern using regex but the path attribute does not allow it as far as i know only wildcards are allowedusing lines like httpruntime relaxedurltofilesystemmappingtrue and requestfiltering allowdoubleescapingtrue to the webconfig simply does not work in mvc5adding modules runallmanagedmodulesforallrequeststrue to the systemwebserver section in the webconfig does actually work but this practice is thiscouraged for many reasons exposed in this article so i am trying to avoid this approach if possibleappending a trailing slash to the url also solves the problem but doing so would lead google to think that i am serving duplicate content so i cannot use this solutioni cannot think of any other alternatives ideally i would like to add a new handler and make it work for all urls except those ending with certain patterns css jsupdatei have found a solution that works for me i will try to explain the steps i tookfirst of all i found a really good explanation of why this behaviour is happening scott forsyths blog some of the solutions listed above are also thiscussed after rading the article i decided to handle dotted urls with a rewrite rule instead of adding a trailing slash i decided to serve the url without the troublesome dots and then check what the user is looking for in the controller of my application my base rule looks like this onerule nameremove troublesome dots stopprocessingfalse match urls conditions add inputrequest filename matchtypeisfile negatetrue add inputrequest filename matchtypeisdirectory negatetrue conditions action typerewrite urlr1r2 rulenote that dots are removed one at a time so urls with several dots will hit this rule several time this is bad if urls are likely to have a large number of dotsif a static file path does not map directly it is thisk location my approach will make it crash to avoid problems we need to add exceptions to the remove dots rule for the file endings we need seb nilsson explains how to do it in this blog post under the adding conditions for specific fileendings section,"['c#', 'asp.net']" +748752,c99 structure designated initialisers and other value i am aware that in c99 you can initialize members of the structure using member name as follows struct mystruct int i char c float fso following is valid struct mystruct m f 1011 i 5 c aalso it is said that uninitialised members will be set to 0 sostruct mystruct m f 1011 c ahere i will be set to 0but for the following struct mystruct m f 1011 c a 6 i is still initialized to 0 what is the reason if we do such compound initialization,['c'] +748759,pandas plotting with multiindex after performing a groupbysum on a dataframe i am having some trouble trying to create my intended plothow can i create a subplot kindbar for each code where the xaxis is the month and the bars are cola and colb,['python'] +748780,not possible to set filter value using data binding this issue came forth from drilling down the original question how to set filter in table dropdown based on table row databackgroundi want to use a filter on a sapui5 dropdown control where i set the filter value based on a model property data binding the issueif i use a filter where the filter value value1 is specified by data bindingnew sapuimodelfilter path division operator sapuimodelfilteroperatoreq value1 somepropertythen the dropdown does not render any itemshowever if i hardcode a value at property value1new sapuimodelfilter path division operator sapuimodelfilteroperatoreq value1 testthen the filter works as expectedthe questionis it true we cannot use data binding for specifying a filter value or should i implement it in another way a small part of me can actually understand that setting a filter on a controls model using a value from that same model could induce some referential issues but this behavior also occurs when using two thistinct named models one for the dropdown and one for the filter value any help is greatly appreciated,['javascript'] +748782,ibeacon region monitoring and proximity for 20 beacons i have been working on a prototype ios app utilizing ibeacons to provide locationrelevant information to office employees depending on where in the office they are the ideal use case is that whenever an employee enters or exits their office a callback is fired which provides them some information in the form of a notification it might make a server query to get information first etc that sort of thing we also want to be able to do this when the app is backgrounded or terminated fortunately we already know that beacon region boundary crossings trigger the appropriate corelocation callbacks even if the app is backgrounded or suspendedfrom looking around i understand that broadly i have two options for how to approach the beacon region monitoringgive each ibeacon its own clbeaconregion and monitor for each of these regions independentlymonitor for clbeaconregions that correspond to multiple ibeacons for example each ibeacon has the same uuid and only monitor for a clbeaconregion corresponding to that uuid then try to determine which beacon triggered the boundary crossing using rangingthus far i had chosen option 1 the advantage of this approach is that i get didenterregion and didexitregion calls for each individual beacon and immediately know which beacon i have enteredexited also i only get one enter call and one exit call which is exactly what i want unfortunately i just realized that this approach also limits me to 20 beacons since each beacon gets its own regioni am not as familiar with the exact implementation details of 2 so correct me if i am wrong but it seems that this approach has more drawbacksapple thiscourages ranging when the app is in the background because the results may not be as accuratethe ranging calls fire once every second while i only want to have enterexit callbacksif the beacons have region overlap the ranging calls might continually flip which one is closest which would further complicate thingsbasically i am wondering if there is a way to utilize option 2 but still have the benefits of option 1 a quick and easy way to immediately determine which beacon triggered the region change with only one enter or exit callback i hope this question is clear enough it is not all entirely clear in my own head especially how ranging works,['ios'] +748820,create my own custom keyboard with my own images emoticons i would like to create a custom keyboard with my own images and layout similar to the app emotikarl on the appstore please take a look at this screenshot i would like to add my own list of images emoticons all the images will be created by me to the keyboard and when i tap an image emoticon the image emoticon will be inserted in the text view at the top of the appi already tried looking on github and other websites but i did not find anything like this how should i do this,['ios'] +748982,py2app modulegraph missing scan code for some reason i cannot explain or google py2app crashes on me even with the simplest examples im using a python 341 virtual environment created as projectstestvirtenv which has py2app installed via pip here is the output of pip listaltgraph 012macholib 17modulegraph 012pip 156py2app 09setuptools 36foopy is a hello world example file saved in projectstest and contains a single lineprinthello worldsetuppy is saved in projectstest as generated by py2applet makesetup foopythis is a setuppy script generated by py2appletusage python setuppy py2appfrom setuptools import setupapp foopydata files options argv emulation truesetup appapp data filesdata files optionspy2app options setup requirespy2apphere is the full output of running python setuppy py2app all pip and python commands were done with the virtual enviroment activated running py2appcreating usersmikdesktopprojectstestbuildcreating usersmikdesktopprojectstestbuildbthistmacosx108x86 64creating usersmikdesktopprojectstestbuildbthistmacosx108x86 64python34standalonecreating usersmikdesktopprojectstestbuildbthistmacosx108x86 64python34standaloneappcreating usersmikdesktopprojectstestbuildbthistmacosx108x86 64python34standaloneappcollectcreating usersmikdesktopprojectstestbuildbthistmacosx108x86 64python34standaloneapptempcreating usersmikdesktopprojectstestthistcreating buildbthistmacosx108x86 64python34standaloneapplibdynloadcreating buildbthistmacosx108x86 64python34standaloneappframeworks using recipe lxml using recipe ftplib using recipe sip using recipe ctypes using recipe xml using recipe pydoc traceback most recent call last file setuppy line 18 in module setup requirespy2app file usrlocalcellarpython3341frameworkspythonframeworkversions34libpython34thistutilscorepy line 148 in setup thistrun commands file usrlocalcellarpython3341frameworkspythonframeworkversions34libpython34thistutilsthistpy line 955 in run commands selfrun commandcmd file usrlocalcellarpython3341frameworkspythonframeworkversions34libpython34thistutilsthistpy line 974 in run command cmd objrun file usersmikdesktopprojectstestvirtenvlibpython34sitepackagespy2appbuild apy line 659 in run self run file usersmikdesktopprojectstestvirtenvlibpython34sitepackagespy2appbuild apy line 865 in run selfrun normal file usersmikdesktopprojectstestvirtenvlibpython34sitepackagespy2appbuild apy line 943 in run normal selfprocess recipesmf filters flatpackages loader files file usersmikdesktopprojectstestvirtenvlibpython34sitepackagespy2appbuild apy line 824 in process recipes rval checkself mf file usersmikdesktopprojectstestvirtenvlibpython34sitepackagespy2apprecipesvirtualenvpy line 80 in check mfscan codeco mattributeerror modulegraph object has no attribute scan codecan someone please explain whats going on and how to fix itedit here is the documentation for scan code in modulegraphpy however the file found in projectstestvirtenvlibpython34sitepackagesmodulegraphmodulegraphpy contains a function called scan code with a leading underscore is this some type of change that broke py2appedit posted thisedit manually removing leading underscores from a couple function definitions in the file mentioned allowed py2app to run without error i am still confused regarding what happened,['python'] +749144,parsing integer value as datetime i have date represented as integer like 20140820 and i want to parsing it as datetime like 20140820do i need to parse each integer value 20140802 using index or is there simpler way,"['c#', '.net']" +749161,using pandas combiningmerging 2 different excel filessheets i am trying to combine 2 different excel files thanks to the post import multiple excel files into python pandas and concatenate them into one dataframethe one i work out so far isimport osimport pandas as pddf pddataframefor f in cfile1xls c file2xls data pdread excelf sheet1 df dfappenddatadfto excelcallxlshere is how they look likehowever i want toexclude the last rows of each file ie row4 and row5 in file1xls row7 and row8 in file2xlsadd a column or overwrite column a to indicate where the data fromfor exampleis it possible thanks,['python'] +749167,determine an array submit button using javascript then outputs data using ajax i have a list of fetched data and to every data has a form below it like a comment box form where other users can leave a message to the specific data what i have tried so far is putting the submit button into an array to thistinguish it from one to another do not know if i am doing this right as this is one of my first attempt in using javascriptjquery library and ajaxi can submit the data and insert it into the sql database just by using phpmysql but i wanted to achieve at least the commentlike system of this community stackoverflow wherein once a comment is posted it would show up right after hitting the button not by reloading the whole page in order to submit the data into the databasethis is the dynamically post dataphp whileloopquery div php echo rowdata div idflashdiv new posted comment should be shown here form action methodpost input typetext namecomment idcomment input typesubmit idsubmit form divphp end of loop and once the submit is clickedfunction var submit documentgetelementbyidsubmit for var a 0 a submitlength a submitaclickfunction var comment documentgetelementbyidcomment var hiddentaskid documentgetelementbyidhiddentaskid var datastring commentcommentahiddentaskidhiddentaskida if commenta hiddentaskida alertplease give valid details else var flash documentgetelementbyidflash flashashow flashafadein400htmlloading message ajax type post url commentajaxphp data datastring cache false success function html olupdateappendhtml olupdate lilastfadeinslow flashahide return false i have tried using array to thistinguish the data from one to another but it is not working when i try to tweak the script new posted messagecomment should popout in the div flashdiv area by using ajax can anyone help me how i can achieve my wanted output,"['javascript', 'php', 'jquery', 'mysql']" +749172,assigning list of integer into a list of string i was learning generics in java and i came close to a very interesting piece of code i know in java it is illegal to add list of one type to anotherlistinteger integerlist new arraylistintegerliststring stringlistintegerlistso in the second line i get a compile time errorbut if i create a generic method inside a class like thisclass genericclass e void genericfunctionliststring stringlist stringlistaddfoo some other codeand in the main class call the method with list of integer i am not getting any errorpublic class main public static void mainstring args genericclass genericclassnew genericclass listinteger integerlist new arraylistinteger integerlistadd100 genericclassgenericfunctionintegerlist systemoutprintlnintegerlistget0 systemoutprintlnintegerlistget1 output 100 foowhy i am not getting any error,['java'] +749271,bootstrap 3 responsive h1 tag i am creating a site and want it to be responsive so i am using bootstrap 3 however the h1 tag on the privacy policy page and about page come out of the container on small mobile devices since the word is too large is there a way i can make the h1 tag reduce in size to fit in the container on smaller mobile devices the site is muscadinewinerecipecom if anyone wants to view what i am talking about it is the about page and privacy policy page,['css'] +749335,symfony 2 performance optimisations were looking for a php framework to work with in future and are currently testing out things with symfony 2 for this weve redesigned our api and implemented it as a bundle in symfony it turned out that symfony seems to be very slow actually far slower than our old not even welldesigned systemwe tried to optimise the performance by caching the byte code using apc for this while weve noticed a huge improvement in performance before about 3 seconds to load the api after 06 seconds in average still 05 seconds slower than our old system without apc were kind of excited but still not really pleased with the high loading time of such an easy task like getting one result out of an almost empty databasei do not know but i could imagine this is due to symfony autoloading all classes even when not needed for a specific bundlenow before we deepsix symfony wed like to look out for further optimisations possibly a way to exclude unneeded components in a specific bundle as i personally think this would make a big differencei would be thankful for any ideas on how to further improve the performance experience reports with using symfony or anything else that could be helpful for us on the lookout for a frameworkeditsome information about the testing environmentoperating system ubuntu 12044 lts gnulinux 38038generic x86 64apache version apache2 ubuntuphp version 53101ubuntu313considerable php extensions apcalso all tests are done on a local copy of our system so possible network issues can be excluded,['php'] +749362,what is a uitapandahalfrecognizer i notice that when i cycle through the gesture recognizers of a uitextview and output the description of each to the console one of the recognizers that seemed utterly curious was the uitapandahalfrecognizer i know about the others such as uitexttaprecognizer but this one really piqued my interest does anyone know what gestures this recognizer handles how can you have half a tap is that a tap and then a press and hold,['objective-c'] +749400,looking for jsonpathany api to update any value in given json string in java inshort i am trying to find some api that could just change the value by taking first parameter as jsonstring second parameter as jsonpath and third will be new value of that parameter but all i found is thisthis api allows me to find any value in json string but i am not finding easy way to update the value of any key for example here is a bookjson store book categoryreference authornigel rees titlesayings of the century price895 categoryfiction authorevelyn waugh titlesword of honour price1299 isbn0553213113 bicycle colorred price1995 i can access color of bicycle by doing thisstring bicyclecolor jsonpathreadjson storebicyclecolorbut i am looking for a method in jsonpath or other api some thing like this jsonpathchangenodevaluejson storebicyclecolor green string bicyclecolor jsonpathreadjson storebicyclecolor systemoutprintlnbicyclecolor this should print green now i am excluding these optionscreate a new json string create a json object to deal with changing value and convert it back to jsonstring reason i have about 500 different requests for different types of service which return different json structure so i do not want to manually create new json string always because ids are dynamic in json structure any idea or direction is much appreciated updating this question with following answer copy mutablejsonjavacopy this little snippet and modify as per you need private static void updatejsonvalue jsonparser parser new jsonparserjsonobject jsonobject new jsonobjectfilereader reader nulltry file jsonfile new filepath to bookjson reader new filereaderjsonfile jsonobject jsonobject parserparsereader catch exception ex systemoutprintlnexgetlocalizedmessagemapstring object userdata nulltry userdata new objectmapperreadvaluejsonobjecttojsonstring mapclass catch ioexception e todo autogenerated catch block eprintstacktracemutablejson json new mutablejsonuserdatasystemoutprintlnbeforet jsonmapjsonupdatestorebook0author jigishjsonupdatestorebook1category actionsystemoutprintlnaftert jsonmaptostringuse these libraries import orgjsonsimplejsonobjectimport orgjsonsimpleparserjsonparserimport orgcodehausjacksonmapobjectmapper,['java'] +749419,jooq general way to insert multiple data and get generated ids what is the general way to insert multiple data via jooq when i need the generated key of each elementnormally i would use a batch insert which is not possible at the moment because of thisi could use createnewrecord and insert each element separately afterwards the id is set correctly but this approach has a bad performancei hope someone has a better approach i cannot be the only one who need this featurethanks a lot in advancetohoe,"['java', 'sql']" +749473,is it possible to supply template parameters when calling operator i would like to use a template operator but am not sure if it is possible here is a simple test case that would not compile is there something wrong with my syntax or is this simply not possiblestruct a templatetypename t void f templatetypename t void operator int main a a afint this compiles aoperatorint this compiles aint this would not compile return 0,['c++'] +749668,string format with a markup extension i am trying to make stringformat available as a handy function in wpf so that the various text parts can be combined in pure xaml without boilerplate in codebehind the main problem is support of the cases where the arguments to the function are coming from other nested markup extensions such as bindingactually there is a feature which is quite close to what i need multibinding unfortunately it can accept only bindings but not other dynamic type of content like dynamicresourcesif all my data sources were bindings i could use markup like thistextblock textblocktext multibinding converterstaticresource stringformatconverter binding pathformatstring binding patharg0 binding patharg1 multibinding textblocktexttextblockwith obvious implementation of stringformatconveteri tried to implement a custom markup extension so that the syntax is like thattextblock textblocktext lstringformat formatbinding formatstring dynamicresource resourcekeyarg0id binding patharg1 staticresource resourcekeyarg2id multibinding textblocktexttextblockor maybe justtextblock textlstringformat binding formatstring arg0dynamicresource arg0id arg1binding arg2 arg2literal string but i am stuck at the implementation of providevalueiserviceprovider serviceprovider for the case of argument being another markup extensionmost of the examples in the internet are pretty trivial they either do not use serviceprovider at all or query iprovidevaluetarget which mostly says what dependency property is the target of the markup extension in any case the code knows the value which should be provided at the time of providevalue call however providevalue will be called only once except for templates which are a separate story so another strategy should be used if the actual value is not constant like it is for binding etci looked up the implementation of binding in reflector its providevalue method actually returns not the real target object but an instance of systemwindowsdatabindingexpression class which seems to do all the real work the same is about dynamicresource it just returns an instance of systemwindowsresourcereferenceexpression which is caring about subscribing to internal inheritancecontextchanged and invalidating the value when appropriate what i however could not understand from looking through the code is the followinghow does it happen that the object of type bindingexpression resourcereferenceexpression is not treated as is but is asked for the underlying valuehow does multibindingexpression know that the values of the underlying bindings have changed so it have to invalidate its value as welli have actually found a markup extension library implementation which claims to support concatenating the strings which is perfectly mapping to my use case project code the concatenation implementation relying on other code but it seems to support nested extensions only of the library types ie you cannot nest a vanilla binding insideis there a way to implement the syntax presented at the top of the question is it a supported scenario or one can do this only from inside the wpf framework because systemwindowsexpression has an internal constructoractually i have an implementation of the needed semantics using a custom invisible helper ui elementlformathelper xnameh1 formatdynamicresource format id lformatargument valuebinding data1 lformatargument valuestaticresource data2lformathelpertextblock textbinding value elementnameh1where formathelper tracks its children and its dependency properties update and stores the uptodate result into value but this syntax seems to be ugly and i want to get rid of helper items in visual treethe ultimate goal is to facilitate the translation ui strings like 15 seconds till explosion are naturally represented as localizable format 0 till explosion which goes into a resourcedictionary and will be replaced when the language changes and binding to the vm dependency property representing the timeupdate report i tried to implement the markup extension myself with all the information i could find in internet full implementation is here 1 2 3 here is the core partvar result new multibinding converter new stringformatconverter mode bindingmodeonewayforeach var v in values if v is markupextension var b v as binding if b null resultbindingsaddb continue var bb v as bindingbase if bb null targetobjfesetbindingaddbindingtotargetobjfe result bb continue if v is systemwindowsexpression dynamicresourceextension mex null did not find other way to check for dynamic resource try rrc is a new resourcereferenceexpressionconverter mex markupextensionrrcconverttov typeofmarkupextension as dynamicresourceextension catch exception if mex null targetobjfesetresourcereference addbindingtotargetobjfe result mexresourcekey continue fallback resultbindingsadd new binding mode bindingmodeoneway source v return resultprovidevalueserviceproviderthis seems to work with nesting bindings and dynamic resources but fails miserably on try to nest it in itself as in this case targetobj obtained from iprovidevaluetarget is null i tried to work around this with merging the nested bindings into the outer one 1a 2a added multibinding spill into outer binding this would perhaps work with the nested multibindings and format extensions but stills fails with nested dynamic resourcesinteresting enough when nesting different kinds of markup extensions i get bindings and multibindings in the outer extension but resourcereferenceexpression instead of dynamicresourceextension i wonder why is it inconsistent and how is the binding reconstructed from bindingexpressionupdate report unfortunately the ideas given in answers did not bring the solution of the problem perhaps it proves that the markup extensions while being quite powerful and versatile tool need more attention from wpf teamanyway i thank to anyone who took part in the thiscussion the partial solutions which were presented are complicated enough to deserve more upvotesupdate report there seems to be no good solution with markup extensions or at least the level of wpf knowledge needed for creating one is too deep to be practicalhowever adabyron had an idea of improvement which helps to hide the helper elements in the host item the price of this is however subclassing the host i will try to see if it is possible to get rid of subclassing using a behaviour which hijacks the hosts logicalchildren and adds helper elements to it comes to my mind inspired by the old version of the same answer,['c#'] +749739,how is val in scala different from const in java anyone care to elaborate on how val in scala is different from const in javawhat are the technical differences i believe i understand what const is in c and java i get the feeling that val is somehow different and better in some sense but i just cannot put my finger on it thanks,['java'] +749787,how can i start new activity as an expended circle from center i want to start a new activity from center of screen as an expended circle so the activity will be revealed as a circle like thishere is my current codeanimxmlset xmlnsandroid scale xmlnsandroid androidduration200 androidfromxscale0 androidfromyscale0 androidpivotx50 androidpivoty50 androidtoxscale1 androidtoyscale1 scaleanimbackxml xml version10 encodingutf8set xmlnsandroid scale xmlnsandroid androidduration10 androidfromxscale10 androidfromyscale10 androidpivotx50 androidpivoty50 androidtoxscale10 androidtoyscale10 scalesetcalling the animationoverridependingtransitionranimanimranimanimbackthe current code just zooms in the new activity but i want the activity to be revealed from center as a circle,['android'] +749821,limit the number of pages thisplayed in bootstrap 3 pagination i have various web pages on my website which are using bootstraps bootstrap 3 pagination but i need to know how to limit the number of pages thisplayed in it eg thisplay pages 1 to 10 onlyif you then select page 2 page 11 would b thisplayed and so onhow do you do thisi know it will probably be javajquery but any help is appreciated and if it can be done without having to use javajquery then all the betterbelow is a screenshot of my paginationas you can see there are 12 pages thisplayed i would like pages 11 12 to be hidden until page 2 or the next page is selected then pages 11 would be thisplayed and pages one would be hidden so on and so on,"['javascript', 'jquery', 'css']" +749968,loop does not see changed value without a print statement in my code i have a loop that waits for some state to be changed from a different thread the other thread works but my loop never sees the changed value it waits forever however when i put a systemoutprintln statement in the loop it suddenly works whythe following is an example of my codeclass myhouse boolean pizzaarrived false void eatpizza while pizzaarrived false systemoutprintlnwaiting systemoutprintlnthat was delicious void deliverpizza pizzaarrived true while the while loop is running i call deliverpizza from a different thread to set the pizzaarrived variable but the loop only works when i uncomment the systemoutprintlnwaiting statement whats going on,['java'] +750020,how to have stored properties in swift the same way i had on objetivec i am switching an application from objectivec to swift which i have a couple of categories with stored properties for exampleinterface uiview mycategory voidaligntoviewuiview view alignmentuiviewrelativealignmentalignment uiview cloneproperty strong pfobject xoproperty nonatomic bool isanimatingendas swift extensions do not accept stored properties like these i do not know how to maintain the same structure as the objc code stored properties are really important for my app and i believe apple must have created some solution for doing it in swiftas said by jou what i was looking for was actually using associated objects so i did in another contextimport foundationimport quartzcoreimport objectivecextension calayer var shapelayer cashapelayer get return objc getassociatedobjectself shapelayer as cashapelayer setnewvalue objc setassociatedobjectself shapelayer newvalue uintobjc association retain var initialpath cgpathref get return objc getassociatedobjectself initialpath as cgpathref set objc setassociatedobjectself initialpath newvalue uintobjc association retain but i get an exc bad access when doingclass uibubble uiview required initcoder adecoder nscoder selflayershapelayer cashapelayer any ideas,['ios'] +750027,what is the use of secret key base in rails 4 i am new to rails 4 and do not understand the use of secret key base under configsecretsyml in rails 4 can you please explain this conceptalso when i am working in the production environment it is asking to set the secret key with deviserb configsecret key and secret key base however i can generate a new secret using the rake secret command what is the difference between development and production environmentshow is it matching the newly generated secret key when i add it with secret key base every time i generatehow is it securing the application with other servers,"['ruby-on-rails', 'ruby']" +750033,how can i configure path to git executable in android studio i need to configure path to git executable in android studio i am working in linux can anyone help me pls,['android'] +750116,coroutine wrapper not executing callback in a timely manner okay so i have a pretty good idea of how to use coroutines in unity3d but i want to make a reusable component for deferred execution that allows me to take code like thisstartcoroutinewaitfordamagecooldowndamagecooldownienumerator waitfordamagecooldownfloat duration yield return new waitforsecondsduration hastempinvincibility falsetaking that and convert it to something like thiscoroutineutildeferredexecutorfloat waittimeaction oncompleteto be used like thisstartcoroutinecoroutineutildeferredexecutorwaittime debuglogdeferredexecutor wait complete hastempinvincibility falsei have tried implementing that in the followingusing systemusing systemcollectionsusing unityenginepublic static class coroutineutil public static ienumerator deferredexecutorfloat waitduration action oncomplete yield return new waitforsecondswaitduration oncompleteinvoke public static ienumerator deferredexecutortfloat waitduration t obj actiont oncomplete yield return new waitforsecondswaitduration oncompleteinvokeobj thinking that that might not work as a static i have also attempted to add it to the objects class like thispublic class player monobehaviouretc ienumerator deferredexecutorfloat waitduration action oncomplete yield return new waitforsecondswaitduration oncompleteinvoke etcthe results have been sporadic i cannot figure a rhyme or reason to when the coroutine completes but it does so well after the expected timeis there something wrong with my approach,['c#'] +750168,capturing browser logs with selenium is there a way to capture browser logs while running automated test cases with selenium i found an article where javascript errors could be captured but that is just for firefox and only for errors i would like to get all the console logs,['java'] +750180,aspnet vnext is host agnostic what does it deeply mean according to aspnet vnext tutorialvnext is host agnostic you can host your app in iis or selfhost in a custom processcould anyone help me to understand this in deepth with showing the difference between current aspnet host and new one,['asp.net'] +750213,images not being loaded in img tag inside an ngrepeat my problemi want to thisplay a list of images stored localy using ngrepeat directive but the images re not being thisplayedangularjs version 12the codedirectory structuremyapp common images imagepng subapp1 indexhtml subapp1js controllers subapp1controllerjs views imagelistviewhtmlindexhtmldoctype htmlhtml langen datangappsubapp1head meta charsetutf8 headbody div idpage datangview div include required libs models and controllers script typetextjavascript srccommonlibsangularminjsscript script typetextjavascript srccommonlibsangularrouteminjsscript script typetextjavascript srccommonlibsangulartouchminjsscript controllers script typetextjavascript srccontrollerssubapp1controllerjsscript app module main script typetextjavascript srcsubapp1jsscriptbodyhtmlsubapp1js instantiate the subapp1 modulevar subapp1 angularmodulesubapp1 ngroute ngtouch setting controllerssubapp1controllersubapp1controller scope subapp1controller define the routes for the modulesubapp1configfunction routeprovider routeproviderwhenhome controller subapp1controller templateurl viewsimagelistviewhtml routeproviderotherwiseredirectto homesubapp1controllerjsfunction subapp1controllerscope private method run the main function of the subapp1controller where all the magic happens function run this variable will define which style will be loaded on the image list view scopesection subapp1 var imagesource imagesource commonimagesimagepng list of media elements to be thisplayed on the list scopemedialist thumbnailpath imagesource imagepath imagesource thumbnailpath imagesource imagepath imagesource thumbnailpath imagesource imagepath imagesource thumbnailpath imagesource imagepath imagesource thumbnailpath imagesource imagepath imagesource runs the main method of this class runimagelistviewhtmldiv classgridbackgrounddivheader classgridheader section div classbuttonrightdivheaderul idgrid classgrid li classgriditem datangrepeatmedia in medialist img datangsrcmediathumbnailpath datasrcmediaimagepath liulextra infothe images are not being loaded and no error message is printed in the consolei opened the web inspector tool to see what was processed in the li element and it did not have the src attribute see bellowli classgriditem ngscope datangrepeatmedia in medialist img datangsrccommonimagesimagepng datasrccommonimagesimagepng liif i add the src attribute in the img element it is loaded but i get an error see bellowli classgriditem datangrepeatmedia in medialist img datangsrcmediathumbnailpath datasrcmediaimagepath srcmediathumbnailpath li error message printed in the console get fileabs path7b7bmediathumbnailpath7d7d neterr file not found i have read many posts and questionsanswers about similar issues but none of them worked for me does anyone have a cluethanks in advance,"['javascript', 'html']" +750292,nothrow dereferencing of stdunique ptr i write code in c which uses a stdunique ptr u to handle a stdstring resource and i want to dereference u so that i can pass the stdstring to a call of the stdstring copy constructorstdstring copy new stdstring dereference you here i know that new or the stdstring copy constructor could throw but this is not my point here i was just wondering whether dereferencing u could already throw an exception i find it strange that operator is not marked noexcept while the stdunique ptr method get is actually marked noexcept in other words uget is noexcept as a whole whileuis not is this a flaw in the standard i do not get why there could be a difference any ideas,['c++'] +750381,how to send message to multiple recipients i am having some trouble sending a message to multiple addresses using the gmail api i have successfully sent a message to only one address but get the following error when i include multiple commaseparated addresses in the to fieldan error occurred returned invalid to headeri am using the createmessage and sendmessage methods from this gmail api guidethat guide states that the gmail api requires messages that are rfc2822 compliant i again did not have much luck using some of these addressing examples in the rfc2822 guidei am under the impression that should be a valid string to pass into the to parameter of createmessage but the error that i received from sendmessage leads me to believe otherwiseplease let me know if you can recreate this problem or if you have any advice on where i may be making a mistake thank youedit here is the actual code that yields an errordef createmessagesender to subject message text message mimetextmessage text messageto to messagefrom sender messagesubject subject return raw base64urlsafe b64encodemessageas stringdef sendmessageservice user id message try message serviceusersmessagessenduseriduser id bodymessage execute print message id s messageid return message except errorshttperror error print an error occurred s errordef composeemail build gmail service object using oauth credentials to addr mary smith who from addr message createmessagefrom addrto addrsubject textmessage body message sendmessagegmail servicememessage,['python'] +750397,how do i properly include an external jar file for a cordova plugin i am trying to make a simple cordova android plugin that requires classes defined in a jar file i have a test project here that includes the example usage a simplified version of my pluginin my pluginxml i have thisplatform nameandroid configfile targetresxmlconfigxml parent feature namepebble param nameandroidpackage valuecomjetboystudiopebblepebblepgplugin feature configfile sourcefile srcsrcandroidpebblepgpluginjava targetdirsrccomjetboystudiopebble sourcefile srcsrcandroidlibspebble kitjar targetdirlibs platformin my test project i have pebblekit jar inplace where it needs to be i think pluginscomjetboystudiopebblepebblepgpluginsrcandroidlibspebble kitjarwhen i cordova build i get no errors but when i install the apkfile i get class not found in chrome device inspect i am assuming this class it cannot find is one of the classes defined in pebble kitjar also it does not seem to be copying this file into platformsandroidif i could just debug better which class is not found that might be a good start if no one has the actual answer of why this does not work,"['java', 'android']" +750409,thisable laravel error handler is there anyway to thisable the laravel error handler all together i want to simply thisplay standard php errors not the whoops looks like something went wrong errors,['php'] +750509,configuring android annotations v301 with android studio beta 084 configuring android annotations is quite irksome but i finally figured out a solution and wish to share with everyone,['android'] +750568,possible oracle bug with greater than 0 in where clause i have a select statement which delivers the wrong number of rowsi can reproduce the problem on oracle database 11g enterprise edition release 112040 64bit production and on oracle database 12c enterprise edition release 121020 64bit production i can not reproduce it on oracle database 11g enterprise edition release 112030 64bit productiontestdatacreate table person asselect level as id person level as name 10 as maxvalfrom dual connect by level 5create table orders asselect level as id order level as namefrom dual connect by level 3if i try the following query i get only 3 results instead of 5select p from person p where maxval select count from orders o where oid pid 0if i modify the query to the following i get 5 results which should be the correct numberselect p from person p where maxval select count from orders o where oid pid 1also the following modification delivers the correct resultselect p from person p where maxval select count from orders o where oid pid 0 0i also get the correct number of results if i use bind variablesselect p from person p where maxval select count from orders o where oid pid numso is there any known bug if i use greater than 0,['sql'] +750718,annotate bars with values on pandas bar plots i looking for a way to annotate my bars in a pandas bar plot with the values rounded in my dataframe dfpddataframeanprandomrand2bnprandomrand2indexvalue1value2 df a b value1 0440922 0911800 value2 0588242 0797366i would like to get something like thisi tried with this but the annotations are all centered on the xthicks ax dfplotkindbar for idx label in enumeratelistdfindex for acc in dfcolumns value nprounddfixidxaccdecimals2 axannotatevalue idx value xytext0 15 textcoordsoffset points,['python'] +750728,getting random numbers in a threadsafe way here is a nice article describing thread safety of random numbersgetting random numbers in a threadsafe waybut i am stuck with the randomgen2 examplepublic static class randomgen2 private static random global new random threadstatic private static random local public static int next random inst local if inst null int seed lock global seed globalnext local inst new randomseed return instnext why is the thread static field copied to local variable random inst local why not to simply use if local nullreturn localnext,"['c#', '.net']" +750769,undocumented net code related to multitouch manipulations throwing exception a favorable outcome would be preventing this exception preferably or at least handling it gracefullyi am getting an exception thrown within microsoft code on top of that the method throwing the exception is systemwindowsinputmanipulationsmanipulationsequenceprocessmanipulators which i cannot find in microsoft reference sourcewhen the exception is thrown i can see that one line down in the call stack window it references windowsinputmanipulationsmanipulationprocessor2dprocessmanipulators which does exist in microsoft reference sourcebut as you can see it does not have a sibling class named manipulationsequenceas for the exception itself it is a systemargumentoutofrangeexception with a value of timestamp values must not decrease parameter name timestamp actual value was 6590630705479the fully qualified signature of the method throwing the exception is systemwindowsinputmanipulationsmanipulationsequenceprocessmanipulatorslong timestamp systemcollectionsgenericienumerablesystemwindowsinputmanipulationsmanipulator2d manipulators systemwindowsinputmanipulationsmanipulationsequenceisettings settingsit appears as if one other person in the universe has had this problem but it could not be reproduced according to the only commenti have 6 mediaelement objects on a canvas that are all running videos when being manipulated so i feel as though it might have something to do with the cpu being taxed and slowing down possibly making timestamps be sent into the method out of order though the same problem occurs when using image rather than mediaelement the exception happens sporadically sometimes it will happen after just a few seconds of messing around with the objects sometimes it can go for a few minutes or more of manipulating the objectsmy code that does the actual manipulation within manipulationdelta looks like thisget current values to manipulatetransformgroup group transformgroupelementrendertransformclonetranslatetransform translate translatetransformgroupchildren0clonescaletransform scale scaletransformgroupchildren1clonerotatetransform rotate rotatetransformgroupchildren2clonedoes manipulations on each by changing valuesapply transformation changesgroupchildren0 translategroupchildren1 scalegroupchildren2 rotateelementrendertransform groupi have a storyboard in xaml messing with the rotatetransform so i cannot really use matrixtransformi am creating this using wpf with net 451 the error occurs in both windows 81 and windows 7 any ideas on how to prevent this exception from occurringsome thoughts as i investigate the problemi also have manipulationinertiastarting in play here as a possible cause of this errori just added ehandled true to the end of manipulationcompleted which was not there before i have not got the error since though again very sporadic so it is hard to tell when it is fixedif a manipulationdelta method is not yet complete and it is hit again from user input could there be some sort of race condition occurring where the first method hit is starved for cpu resources and the second runs through then when the first method finally completes the timestamp created is in the pastper a comment this is not likelyi conferred with a coworker to gain better understanding he helped me realize i cannot swallow the exception from within my methods that handle manipulation events because the exception is happening before it gets there in the actual creation of the manipulation data so the only place i can handle the exception is on appmain the first place in the call stack where my code exists which makes handling it gracefully all the more difficult,"['c#', '.net']" +750904,make image wider than parent while preserving vertical space if you have a parent div of fixed width is it possible to make a child img wider than the parent while constraining proportions while also preserving vertical spacewhile positionabsolute can break the image out of the normal document flow i do not want to remove the vertical space the image retains if i did any content that appears after the image would be pushed upwards and as a result it would appear behind the imageheres an example fiddleimage one represents the vertical behavior i want obviously if the image were horizontally larger the height should increase proportionally image two represents the horizontal behavior i would want however this does not preserve vertical space i experimented with negative margins but could not get anything viable workingassuming unknown image dimensions is the desired effect possible without javascript,"['html', 'css']" +750963,how can i elide additional calls to an idempotent function is there a way to tell gcc that a function that has side effects should only be called once if two subsequent calls have the same arguments i want the following behaviourfoo6run this functionfoo6optimize this awayfoo6optimize this awayfoo5run this functionfoo6run this function againi can make foo check a global variable before it does any work but that is less than optimal void inline fooint i static int last ii1 iflast i i last ii do work since foo is an inline function the compiler should be able to look across invokations of foo and see that it does not have to execute it the problem is the compiler cannot optimize like that for global variables is there a way to let the compiler know it is safe to do so,"['c++', 'c']" +751249,comparing java swing mvc with android design pattern i am doing a small research on design patterns in various platforms and i have prior experience in programming with java while reading these posts mvc pattern in android and mvc architecture in android i had an interesting question in mind why java swing mvc can not be compared with android development pattern or why we cannot say that android follows mvc in the context of overall look and feelin one answer someone clarified mvc asmodel what to renderview how to rendercontroller events user inputok well now what i understand isjava swing mvcin java swing mvc component class is an abstract class for allattributes in visual environment there is a thistinct keyword calledcontrols is used for some components such as buttons lists etcso all controls and components are part of model in mvccontainer inherits component and there are severallayoutmanagers that defines layouts and place of components incontainer also there are listenershave to be registered withaccording eventsources so they all are the view in mvcclass that implements listener interface methods in which we put our mainlogic and there are some eventclasses for each event they all arepart of controller in mvcputting all these examples together in an image in swing mvc we haveandroid design pattern visualizing as mvci think widgets are same as controls here also there are someother eventsourcesthey all act as a modelview package has viewgroups that also contains several kinds oflayouts and listener interfaces they all are the part ofview in mvcsame as swing mvc we can say listener interface methods and activities arethe part of controllerputting all together in an image in android we haveas per above comparison i consider following similaritiescontainer same as viewlayout managers same as viewgrouplisteners overall same in both architecture controls overall same as widgetsevent delegation registering appropriate listener with event source and then implementing listeners methods overall same in both architecture so can anyone explain which are the things that makes the android design pattern different than java swing mvc patternor if you believe that both are different things in the context of design patterns used for development then explain why,"['java', 'android']" +751660,error inflating class androidsupportv7widgetrecyclerview i am trying to use recyclerview in my existing project builds without errors but getting no class found error for the recyclerview while inflating cannot see what i am doing wrong thanks for helpingactivity mainxmllinearlayout xmlnsandroid androidlayout heightmatch parent androidlayout widthmatch parent androidorientationvertical androidsupportv7widgetrecyclerview androidididrecyclerview androidlayout widthmatch parent androidlayout heightwrap contentlinearlayoutmainactivityoncreate override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main recyclerview recyclerview findviewbyidridrecyclerview itemdata itemsdata new itemdatahelprdrawablevisa new itemdatadeleterdrawablesample new itemdatacloudrdrawablesample new itemdatafavoriterdrawablesample new itemdatalikerdrawablesample new itemdataratingrdrawablesample 2 set layoutmanger recyclerviewsetlayoutmanagernew linearlayoutmanagerthis 3 create an adapter myadapter madapter new myadapteritemsdata 4 set adapter recyclerviewsetadaptermadapter 5 set item animator to defaultanimator recyclerviewsetitemanimatornew defaultitemanimator recyclerviewsethasfixedsizetrue buildgradleapply plugin comandroidapplicationandroid compilesdkversion 20 buildtoolsversion 1910 defaultconfig applicationid comdomainproject minsdkversion 19 targetsdkversion 20 versioncode 1 versionname 10 buildtypes release runproguard false proguardfiles getdefaultproguardfileproguardandroidtxt proguardrulespro dependencies compile filetreeinclude jar dir libs compile comandroidsupportsupportv4 compile comandroidsupportsupportv13 compile projectfacebook315 compile projectparse151 compile projectviewpagerindicator241 compile comgithubmanuelpeinadofadingactionbarfadingactionbar312 compile comandroidsupportcardviewv7 compile comandroidsupportrecyclerviewv7 compile comgoogleandroidgmsplayservicesconfigurations to avoid double inclusion of support libraries allexclude group comandroidsupport module supportv4logcat0824 174927626 2754427544comdomainproject eandroidruntimei1 fatal exception main process comdomainproject pid 27544 javalangruntimeexception unable to start activity componentinfocomdomainprojectcomdomainprojectmainactivity androidviewinflateexception binary xml file line 7 error inflating class androidsupportv7widgetrecyclerview at androidappactivitythreadperformlaunchactivityactivitythreadjava2215 at androidappactivitythreadhandlelaunchactivityactivitythreadjava2264 at androidappactivitythreadaccess800activitythreadjava144 at androidappactivitythreadhhandlemessageactivitythreadjava1205 at androidoshandlerthispatchmessagehandlerjava102 at androidoslooperlooplooperjava136 at androidappactivitythreadmainactivitythreadjava5139 at javalangreflectmethodinvokenativenative method at javalangreflectmethodinvokemethodjava515 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava796 at comandroidinternaloszygoteinitmainzygoteinitjava612 at dalviksystemnativestartmainnative method caused by androidviewinflateexception binary xml file line 7 error inflating class androidsupportv7widgetrecyclerview at androidviewlayoutinflatercreateviewlayoutinflaterjava620 at androidviewlayoutinflatercreateviewfromtaglayoutinflaterjava696 at androidviewlayoutinflaterrinflatelayoutinflaterjava755 at androidviewlayoutinflaterinflatelayoutinflaterjava492 at androidviewlayoutinflaterinflatelayoutinflaterjava397 at androidviewlayoutinflaterinflatelayoutinflaterjava353 at comandroidinternalpolicyimplphonewindowsetcontentviewphonewindowjava343 at androidappactivitysetcontentviewactivityjava1929 at comdomainprojectmainactivityoncreatemainactivityjava35 at androidappactivityperformcreateactivityjava5231 at androidappinstrumentationcallactivityoncreateinstrumentationjava1087 at androidappactivitythreadperformlaunchactivityactivitythreadjava2169a a a a a a a a a a a a at androidappactivitythreadhandlelaunchactivityactivitythreadjava2264a a a a a a a a a a a a at androidappactivitythreadaccess800activitythreadjava144a a a a a a a a a a a a at androidappactivitythreadhhandlemessageactivitythreadjava1205a a a a a a a a a a a a at androidoshandlerthispatchmessagehandlerjava102a a a a a a a a a a a a at androidoslooperlooplooperjava136a a a a a a a a a a a a at androidappactivitythreadmainactivitythreadjava5139a a a a a a a a a a a a at javalangreflectmethodinvokenativenative methoda a a a a a a a a a a a at javalangreflectmethodinvokemethodjava515a a a a a a a a a a a a at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava796a a a a a a a a a a a a at comandroidinternaloszygoteinitmainzygoteinitjava612a a a a a a a a a a a a at dalviksystemnativestartmainnative method caused by javalangreflectinvocationtargetexception at javalangreflectconstructorconstructnativenative method at javalangreflectconstructornewinstanceconstructorjava423 at androidviewlayoutinflatercreateviewlayoutinflaterjava594a a a a a a a a a a a a at androidviewlayoutinflatercreateviewfromtaglayoutinflaterjava696a a a a a a a a a a a a at androidviewlayoutinflaterrinflatelayoutinflaterjava755a a a a a a a a a a a a at androidviewlayoutinflaterinflatelayoutinflaterjava492a a a a a a a a a a a a at androidviewlayoutinflaterinflatelayoutinflaterjava397a a a a a a a a a a a a at androidviewlayoutinflaterinflatelayoutinflaterjava353a a a a a a a a a a a a at comandroidinternalpolicyimplphonewindowsetcontentviewphonewindowjava343a a a a a a a a a a a a at androidappactivitysetcontentviewactivityjava1929a a a a a a a a a a a a at comdomainprojectmainactivityoncreatemainactivityjava35a a a a a a a a a a a a at androidappactivityperformcreateactivityjava5231a a a a a a a a a a a a at androidappinstrumentationcallactivityoncreateinstrumentationjava1087a a a a a a a a a a a a at androidappactivitythreadperformlaunchactivityactivitythreadjava2169a a a a a a a a a a a a at androidappactivitythreadhandlelaunchactivityactivitythreadjava2264a a a a a a a a a a a a at androidappactivitythreadaccess800activitythreadjava144a a a a a a a a a a a a at androidappactivitythreadhhandlemessageactivitythreadjava1205a a a a a a a a a a a a at androidoshandlerthispatchmessagehandlerjava102a a a a a a a a a a a a at androidoslooperlooplooperjava136a a a a a a a a a a a a at androidappactivitythreadmainactivitythreadjava5139a a a a a a a a a a a a at javalangreflectmethodinvokenativenative methoda a a a a a a a a a a a at javalangreflectmethodinvokemethodjava515a a a a a a a a a a a a at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava796a a a a a a a a a a a a at comandroidinternaloszygoteinitmainzygoteinitjava612a a a a a a a a a a a a at dalviksystemnativestartmainnative method caused by javalangnoclassdeffounderror androidsupportv4utilpoolssimplepool at androidsupportv7widgetrecyclerviewinitrecyclerviewjava121 at androidsupportv7widgetrecyclerviewinitrecyclerviewjava213a a a a a a a a a a a a at javalangreflectconstructorconstructnativenative methoda a a a a a a a a a a a at javalangreflectconstructornewinstanceconstructorjava423a a a a a a a a a a a a at androidviewlayoutinflatercreateviewlayoutinflaterjava594a a a a a a a a a a a a at androidviewlayoutinflatercreateviewfromtaglayoutinflaterjava696a a a a a a a a a a a a at androidviewlayoutinflaterrinflatelayoutinflaterjava755a a a a a a a a a a a a at androidviewlayoutinflaterinflatelayoutinflaterjava492a a a a a a a a a a a a at androidviewlayoutinflaterinflatelayoutinflaterjava397a a a a a a a a a a a a at androidviewlayoutinflaterinflatelayoutinflaterjava353a a a a a a a a a a a a at comandroidinternalpolicyimplphonewindowsetcontentviewphonewindowjava343a a a a a a a a a a a a at androidappactivitysetcontentviewactivityjava1929a a a a a a a a a a a a at comdomainprojectmainactivityoncreatemainactivityjava35a a a a a a a a a a a a at androidappactivityperformcreateactivityjava5231a a a a a a a a a a a a at androidappinstrumentationcallactivityoncreateinstrumentationjava1087a a a a a a a a a a a a at androidappactivitythreadperformlaunchactivityactivitythreadjava2169a a a a a a a a a a a a at androidappactivitythreadhandlelaunchactivityactivitythreadjava2264a a a a a a a a a a a a at androidappactivitythreadaccess800activitythreadjava144a a a a a a a a a a a a at androidappactivitythreadhhandlemessageactivitythreadjava1205a a a a a a a a a a a a at androidoshandlerthispatchmessagehandlerjava102a a a a a a a a a a a a at androidoslooperlooplooperjava136a a a a a a a a a a a a at androidappactivitythreadmainactivitythreadjava5139a a a a a a a a a a a a at javalangreflectmethodinvokenativenative methoda a a a a a a a a a a a at javalangreflectmethodinvokemethodjava515a a a a a a a a a a a a at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava796a a a a a a a a a a a a at comandroidinternaloszygoteinitmainzygoteinitjava612a a a a a a a a a a a a at dalviksystemnativestartmainnative method,['android'] +751682,incorporating thiscourse sso with existing rails site with devise i have an existing rails app that is using devise as it is user authentication i added a thiscourse forum and everything went smoothly and it resides on a subdomain i have read the post at but still do not know what to do with the devise side of things once the user logs in on the existing rails site currently this is the process as i understand itstep1 user hits thiscourse forum on subdomain user needs to login so clicks login button step2 user is sent to the login page on the existing rails site step3 user logs in on rails site step4 user should be redirected to thiscourse forum subdomain logged in my question is what do i need to to do to make it so that when a user logs in on step 3 they get redirected back to the subdomain has anyone successfully implemented this i saw this code snippet on that walkthrough page class thiscoursessocontroller applicationcontroller def sso secret my secret string sso singlesignonparserequestquery string secret ssoemail ssoname bill hicks ssousername ssoexternal id 123 unique to your application ssosso secret secret redirect to ssoto url login endendis this what i would need to add in my existing rails app i am guessing the parse checks if that information is in the url and if so it redirects once it finishes the devise login process and if not it just functions as usual would i place this code somewhere in the devise files,['ruby-on-rails'] +751826,duplicate files during packaging of apk appdebugunalignedapk i got this error duplicate files during packaging of apk appdebugunalignedapk when put 2 jar files httpclient435jarhttpmime435jarinto the libs folder after sync with gradle and runif user 1 jar file httpmime435jar i will not get this errorplease help me how to avoid this error still can use 2 jar files in above alsothanksps i use android studio version 086error detailerrorduplicate files during packaging of apk appbuildoutputsapkappdebugunalignedapk path in archive metainfdependencies origin 1 applibshttpclient435jar origin 2 applibshttpmime435jarbuildgradleandroid compilesdkversion 20buildtoolsversion 20defaultconfig applicationid comapp minsdkversion 9 targetsdkversion 20 versioncode 1 versionname 10buildtypes release runproguard false proguardfiles getdefaultproguardfileproguardandroidtxt proguardrulespro productflavors packagingoptions exclude metainflicensetxtdependencies compile filetreeinclude jar dir libscompile comandroidsupportsupportv420compile comandroidsupportappcompatv720compile comgoogleandroidgmsplayservices5208compile comviewpagerindicatorlibrary241aarcompile dehdodenhofcircleimageview120compile fileslibshttpmime435jarupdate i changed from compile fileslibshttpmime435jar to use maven link i got same error again after put 2 maven link together compile orgapachehttpcomponentshttpmime44alpha1compile orgapachehttpcomponentshttpcore44alpha1this is the warningwarningdependency orgapachehttpcomponentshttpclient44alpha1 is ignored for debug as it may be conflicting with the internal version provided by android in case of problem please repackage it with jarjar to change the class packages warningdependency orgapachehttpcomponentshttpclient44alpha1 is ignored for release as it may be conflicting with the internal version provided by android in case of problem please repackage it with jar to change the class packagesplease help me fixsoulition i know good answer now by ading these lines will fix duplicate files error packagingoptions exclude metainfdependenciestxt exclude metainflicensetxt exclude metainfnoticetxt exclude metainfnotice exclude metainflicense exclude metainfdependencies exclude metainfnoticetxt exclude metainflicensetxt exclude metainfdependenciestxt exclude metainflgpl21,['android'] +751896,how to access ios simulator camera hi friends i am doing camera app i need to test the app in simulator but i cannot able to access the ios simulator camera any help for my problem if not possible in simulator means i need to access my system camera whether it is possiblei tried image picture view controller but it not works any help will be appreciatedthe below code only i triedselfimagepicker uiimagepickercontroller alloc init uiimagepickercontrollersourcetype sourcetype uiimagepickercontrollersourcetypephotolibraryselfusingpopover yesif uiimagepickercontroller issourcetypeavailableuiimagepickercontrollersourcetypecamera sourcetype uiimagepickercontrollersourcetypecameraselfusingpopover noselfimagepicker setsourcetypesourcetypeselfimagepickerallowsediting noselfimagepickerdelegate selfif sourcetype uiimagepickercontrollersourcetypecamera selfpopover uipopovercontroller alloc initwithcontentviewcontrollerselfimagepickerselfpopoverdelegate selfselfpopover presentpopoverfromrectpopoverframe inviewselfview permittedarrowdirectionsuipopoverarrowdirectionany animatedyes else self presentmodalviewcontrollerimagepicker animatedyes,['ios'] +752003,using threadstop on carefully locked down but untrusted code i am aware that threadstop is deprecated and for good reason it is not in general safe but that does not mean that it is never safe as far as i can see it is safe in the context in which i want to use it and as far as i can see i have no other optionthe context is a thirdparty plugin for a twoplayer strategy game chess will do as the working example the thirdparty code needs to be given a current board state and say 10 seconds to decide on its move it can return its move and terminate within the allowable time or it can whenever it wants to signal its current preferred move if the time limit expires it should be stopped in its tracks and its most recent preferred move should be playedwriting the plugin to stop gracefully on request is not an option i need to be able to take arbitrary untrusted thirdparty plugins so i have to have some way of forcibly terminating itheres what i am doing to lock it downthe classes for the plugin get put into their own thread into their own thread groupthey are loaded with a class loader that has a highly restrictive securitymanager in place all the classes can do is number crunchingthe classes do not get a reference to any other threads so they cannot use threadjoin on anything they have not createdthe plugin gets only two references to objects from the host system one is the state of the chess board this is a deep copy and is thrown away afterwards so it does not matter if it gets into an inconsistent state the other is a simple object that allows the plugin to set its current preferred movei am checking when cpu time has exceeded the limit and i am periodically checking that at least one thread of the plugin is doing something so that it cannot sleep indefinitely and avoid cpu time ever hitting the limitthe preferred move does not have enough state to be inconsistent but in any case it is carefully and defensively cloned after it is returned and the one that was returned is thiscarded by this point there is nothing left in the host system to which the plugin had a reference no threads no object instancesin consequence it seems the plugin cannot leave anything in an inconsistent state except for any objects it might create which will then be thiscarded and it cannot affect any other threads except for any threads it spawns which will be in the same threadgroup and so will also be killed offit looks to me as though the reasons that threadstop is deprecated do not apply here by design have i missed anything is there still danger here or have i isolated things carefully enough that there cannot be a problemand is there a better way the only alternative i think is to start up a whole new jvm to run the untrusted code and forcibly kill the process when it is no longer wanted but that has a thousand other problems expensive fragile osdependentplease note i am not interested in answers along the lines of ooh it is deprecated for a reason you want to watch it mate i know it is deprecated for a reason and i completely understand why it is not safe to be let out of the cage in general what i am asking is whether there is a specific reason for thinking that it is unsafe in this contextfor what it is worth here is the abridged relevant bit of the codepublic void playmoveinternalgamestate game throws illegalmoveexception instantiationexception illegalaccessexception illegalmovespecificationexception threadgroup group new threadgroupplaythread group thread playthread null groupsetmaxprioritythreadmin priority gamemetadata meta null strategygameplayer player null try gamestate newgame gamestate gameclone sandboxedurlclassloader loader new sandboxedurlclassloader recreating this each time means static fields do not persist urlsnewgamegetcurplayer 1 playerinterface class playerclass loaderfindplayerclass gametimer timer new gametimer newgamegetcurplayer 1 timelimit timelimit2 time starts ticking here meta new gamemetadatagametimer timerclone try player strategygameplayer playerclassnewinstance catch exception e systemerrprintlncould not create player module instance eprintstacktrace gameresigngamemovetypemove illegal return boolean checksleepy true playthread new threadgroup new movemakerthreadplayer meta newgame movemaker thread int badcount 0 playthreadstart try while timergettimeremaining 0 playthreadisalive stopping forcemove playthreadjoin50 if checksleepy threadstate thdstate playthreadgetstate if thdstate threadstatetimed waiting thdstate threadstatewaiting normally main thread will be busy thread allthreads new threadgroup activecount 2 int numthreads groupenumerateallthreads boolean bad true for int i 0 i numthreads i check some player thread somewhere is doing something thdstate allthreadsigetstate if thdstate threadstatetimed waiting thdstate threadstatewaiting bad false break found a good thread so carry on if bad badcount 100 means player has been sleeping for an expected 5 sec which is naughty break catch interruptedexception e systemerrprintlninterrupted e catch exception e systemerrprintlncould not play the game e eprintstacktrace playthreaddestroy try threadsleep10 catch exception e groupstop forcemove false try if stopping try if gameislegalmovemetagetbestmove gameresigngamemovetypemove illegal else gamemakemovegamemove metagetbestmoveclone we rely here on the islegalmove call to make sure that the return type is the right final class so that the clone call cannot execute dodgy code catch illegalmoveexception e gameresigngamemovetypemove illegal catch nullpointerexception e did not ever choose a move to make gameresigngamemovetypemove out of time catch exception e eprintstacktrace gameresigngamemovetypemove out of time,['java'] +752049,how to use python to execute a curl command i am new to python and i want to execute a curl command in pythonusually i just need enter the command in terminal and press return key however i do not know how it works in python the command shows belowcurl d requestjson header contenttype applicationjson there is a requestjson file to be sent to get responsei searched a lot and got confused i tried to write a piece of code although i could not fully understand it did not workimport pycurlimport stringioresponse stringiostringioc pycurlcurlcsetoptcurl csetoptcwritefunction responsewritecsetoptchttpheader contenttype applicationjsonacceptcharset utf8csetoptcpostfields requestjsoncperformccloseprint responsegetvalueresponseclosethe error message is parse errorcan anyone tell me how to fix it or how to get response from the sever correctly thanks a lot,['python'] +752109,cannot upload android app to device stale dexed jars i am using android studio to develop this app and today when i tried to upload it to my device to test i got a popup window sayinginstallation failed since the device possibly has stale dexed jars that do not match the current version dexopt error in order to proceed you have to uninstall the existing applicationwarning uninstalling will remove the application datado you want to uninstall the existing applicationit gave two options ok or cancel upon hitting ok the following message showed up in the run tabdevice shell command pm uninstall mybundleidunknown failurethe app seems to be uninstalled the is no trace of it under manage applicationsi am unable to upload the app i tried cleaning the project and rebuilding but it did not workwhat can i do,['android'] +752120,python nltk unicodedecodeerror ascii codec cannot decode byte i am new to nltk i am getting this error and i have searched around for encodingdecoding and specifically the unicodedecodeerror but this error seems specific to the nltk source codeheres the errortraceback most recent call last file apythonprojectstestmainpy line 2 in module printpos tagword tokenizejohns big idea is not all that bad file apythonpythonlibsitepackagesnltktag init py line 100 in pos tag tagger load pos tagger file apythonpythonlibsitepackagesnltkdatapy line 779 in load resource val pickleloadopened resourceunicodedecodeerror ascii codec cannot decode byte 0xcb in position 0 ordinal not in range128how do i go around fixing this errorheres what causes the errorfrom nltk import pos tag word tokenizeprintpos tagword tokenizejohns big idea is not all that bad,['python'] +752151,is there a shortcut on android studio to convert a text to uppercase i am trying to find a command on android studio to convert a selected text to uppercase but i am unable to do sois there any shortcut for this i think it is a very common action on ide but have not found any clue yet,['android'] +752208,how correctly use rethis with koa nodejs i try to get an information from a rethis db and return it as the body of the response to the user first here is a code that fails var rethis requirerethis koa requirekoavar app koa port processargv2 30 client rethiscreateclientappusefunction next clientgettest function err res thisbody res yield nextapplistenportconsoleloglisten on port portsurely because the yield calls end before the callback is calledthen here is a code that success function askredit callback clientgettest callbackappusefunction next thisbody yield askredit yield nextbut i clearly misunderstand why the second one is working does the yield in yield askredit have the same behavior than the one in yield next edit i just seen a page that seems to answers a little so now i will try to understand these misterious yield is this a way of doing synchronous things with asynchronous calls,['javascript'] +752473,lambda expression throws exception i just started a new vaadin project with maven comvaadinin the default myvaadinuijava i have replaced the buttenclicklistener with a lambda expression after that i get a exception while running package jettyrunbeforebutton button new buttonclick me buttonaddclicklistenernew buttonclicklistener public void buttonclickclickevent event layoutaddcomponentnew labelthank you for clicking layoutaddcomponentbuttonafterbutton button new buttonclick mebuttonaddclicklistenerevent layoutaddcomponentnew labelthank you for clickinglayoutaddcomponentbuttonexception20140826 132330069warnoejaannotationparserexception javalangarrayindexoutofboundsexception 1612 at orgobjectwebasmclassreaderreadclassunknown source at orgobjectwebasmclassreaderacceptunknown source at orgobjectwebasmclassreaderacceptunknown source at orgeclipsejettyannotationsannotationparserscanclassannotationparserjava899 at orgeclipsejettyannotationsannotationparserparseannotationparserjava755 at orgeclipsejettyannotationsannotationparserparseannotationparserjava744 at orgeclipsejettyannotationsannotationparserparseannotationparserjava744 at orgmortbayjettypluginmavenannotationconfigurationdoparsemavenannotationconfigurationjava73 at orgmortbayjettypluginmavenannotationconfigurationparsewebinfclassesmavenannotationconfigurationjava52 at orgeclipsejettyannotationsannotationconfigurationconfigureannotationconfigurationjava119 at orgeclipsejettywebappwebappcontextconfigurewebappcontextjava468 at orgeclipsejettywebappwebappcontextstartcontextwebappcontextjava1237 at orgeclipsejettyserverhandlercontexthandlerdostartcontexthandlerjava717 at orgeclipsejettywebappwebappcontextdostartwebappcontextjava494 at orgmortbayjettypluginjettywebappcontextdostartjettywebappcontextjava298 at orgeclipsejettyutilcomponentabstractlifecyclestartabstractlifecyclejava64 at orgeclipsejettyserverhandlerhandlercollectiondostarthandlercollectionjava229 at orgeclipsejettyserverhandlercontexthandlercollectiondostartcontexthandlercollectionjava172 at orgeclipsejettyutilcomponentabstractlifecyclestartabstractlifecyclejava64 at orgeclipsejettyserverhandlerhandlercollectiondostarthandlercollectionjava229 at orgeclipsejettyutilcomponentabstractlifecyclestartabstractlifecyclejava64 at orgeclipsejettyserverhandlerhandlerwrapperdostarthandlerwrapperjava95 at orgeclipsejettyserverserverdostartserverjava282 at orgmortbayjettypluginjettyserverdostartjettyserverjava65 at orgeclipsejettyutilcomponentabstractlifecyclestartabstractlifecyclejava64 at orgmortbayjettypluginabstractjettymojostartjettyabstractjettymojojava520 at orgmortbayjettypluginabstractjettymojoexecuteabstractjettymojojava365 at orgmortbayjettypluginjettyrunmojoexecutejettyrunmojojava523 at orgapachemavenplugindefaultbuildpluginmanagerexecutemojodefaultbuildpluginmanagerjava132 at orgapachemavenlifecycleinternalmojoexecutorexecutemojoexecutorjava208 at orgapachemavenlifecycleinternalmojoexecutorexecutemojoexecutorjava153 at orgapachemavenlifecycleinternalmojoexecutorexecutemojoexecutorjava145 at orgapachemavenlifecycleinternallifecyclemodulebuilderbuildprojectlifecyclemodulebuilderjava116 at orgapachemavenlifecycleinternallifecyclemodulebuilderbuildprojectlifecyclemodulebuilderjava80 at orgapachemavenlifecycleinternalbuildersinglethreadedsinglethreadedbuilderbuildsinglethreadedbuilderjava51 at orgapachemavenlifecycleinternallifecyclestarterexecutelifecyclestarterjava120 at orgapachemavendefaultmavendoexecutedefaultmavenjava347 at orgapachemavendefaultmavenexecutedefaultmavenjava154 at orgapachemavenclimavencliexecutemavenclijava582 at orgapachemavenclimavenclidomainmavenclijava214 at orgapachemavenclimavenclimainmavenclijava158 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava62 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43 at javalangreflectmethodinvokemethodjava483 at orgcodehausplexusclassworldslauncherlauncherlaunchenhancedlauncherjava289 at orgcodehausplexusclassworldslauncherlauncherlaunchlauncherjava229 at orgcodehausplexusclassworldslauncherlaunchermainwithexitcodelauncherjava415 at orgcodehausplexusclassworldslauncherlaunchermainlauncherjava356 at orgcodehausclassworldslaunchermainlauncherjava46 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava62 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43 at javalangreflectmethodinvokemethodjava483 at comintellijrtexecutionapplicationappmainmainappmainjava134im using intellij131 with jdk8 on osx,['java'] +752538,how to see cscexe or vbcexe parameters when building from visual studio is there a way to see what the csc or vbc parameters are when building an application using the visual studiovisual studio calls cscexevbcexe behind the scenes i want to know if there is a way to see that calli need this info to replicate the equivalent build script using the command linei set the different levels of verbosity for the build still i do not see any cscexe call in the output windowi am really surprised why microsoft did not put an easy way to see the underlying csc commandaj if i go through your steps i get i do not see any reference to cscok here is how i resolved thisfirst i went to tools and options and set the verbosity to detail after this point still build output was emptythen i got service pack for vs2010i also had similar issue for visual studio 2012 i had to get update 4 to see the logs and cscexe ion the output,['c#'] +752544,development mode for angularjs using gruntjs i have a couple of products that started off with the yeoman angular generator and it has been a pretty good dev setup one thing i have not been able to find a good solution for is setting a developmentproduction mode flagnaturally we use a few tools that we only want on in production so having proddev variable that we can use both inline javascript andor html files would be quite useful i searched for solutions online before but have not found anything usefulultimately i am looking for a good solution to use in an angularjs setting ideally set via grunt serve andor build run what are other teams doing here,['javascript'] +752583,fastest way to parse large csv files in pandas i am using pandas to analyse the large data files here they are around 100 megs in sizeeach load from csv takes a few seconds and then more time to convert the datesi have tried loading the files converting the dates from strings to datetimes and then resaving them as pickle files but loading those takes a few seconds as wellwhat fast methods could i use to loadsave the data from thisk,['python'] +752607,wrong value from uitableviewrowheight at ios8 the code i used to create a rectangle at least until ios7 wascgrect rect ctableview framerectoriginy ctableview rowheightsearchoverlayview becomefirstrespondercontrol alloc initwithframerecton ios7 ctableview an instance of a uitableview returned 44 testing in ios8 with an iphone 5s returns 1 why is this happening what is the correct code that needs to be used in order for my app to be backwards compatible with ios7,['ios'] +752664,spring data rest repositoryeventhandler methods not invoked i am trying to add a repositoryeventhandler as described on spring data rest documentation to the rest repository shown belowrepositoryrestresourcecollectionresourcerel agents path agentspublic interface agentrepository extends crudrepositoryagent long no implementation required spring data will create a concrete repositoryi created an agenteventhandlercomponentrepositoryeventhandleragentclasspublic class agenteventhandler called before link agent is persisted param agent handlebeforesave public void handlebeforesaveagent agent systemoutprintlnsaving agent agenttostring and declared it in a configuration componentconfigurationpublic class repositoryconfiguration declare an instance of the link agenteventhandler return bean agenteventhandler agentevenhandler return new agenteventhandler when i am posting to the rest resource the entity gets persisted but the method handlebeforesave never gets invoked what am i missingi am using spring boot 115release,['java'] +752709,healthkit hkauthorizationstatus for reading data i am using healthkit to read certain types of information i am specifically not asking for write functionality the problem comes in when trying to detect if the user has allowed a certain health type to be readi believe the intended way to do this is using an hkhealthstores authorizationstatusfortype method but this is only returned denied or unknown it is only returning authorized for write types has anyone found a way to use this method for reading or another work aroundhkquantitytype stepstype hkquantitytype quantitytypeforidentifierhkquantitytypeidentifierheighthkauthorizationstatus status selfhealthstore authorizationstatusfortypestepstype,['ios'] +752717,passing variadic template arguments to a variadic function we are using a thirdparty c library which provides a printfstyle log functionvoid logconst char format for reasons that are not worth going in to we need to limit the rate at which messages get logged something along the lines ofvoid rate limited logconst char format if not too fast logformat fortunately the authors of the c library knew what they were doing and providedvoid logvconst char format va list apso writing the above function is a relatively simple matter unfortunately however variadic functions do not play well with inlining and so i came up with a second solutiontemplate typename tvoid rate limited logconst char format t args if not too fast logformat stdforwardtargs this works perfectly and inlines the rate limiting condition as wed like but i have a couple of questions about itis expanding a parameter pack into a cstyle variadic function call like this a legal welldefined thing to do in c11 or have we just got lucky that it worksare the and stdforward actually necessary here given were calling a c function it seems to work just as well if i use const t or even just t by value with or without stdforward,['c++'] +752739,how to provide python syntax coloring inside webstorm i have a python project and i use webstorm as my editor the problem is that pythons syntax does not get colored how can i thisplay python pages with a nice syntax i am not searching more than than i am not going to develop pages in python but i do want them to get thisplayed nicely in webstorm,['python'] +752793,windows phone 81 mediacapture freezes the phone i want to make a simple app that will allow me to check few parameters of every frame of preview but i got stuck at running and stopping preview summary an empty page that can be used on its own or navigated to within a frame summary public sealed partial class mainpage page mediacapture mediacapture bool recording public mainpage thisinitializecomponent thisnavigationcachemode navigationcachemoderequired summary invoked when this page is about to be thisplayed in a frame summary param namevent data that describes how this page was reached this parameter is typically used to configure the pageparam protected override async void onnavigatedtonavigationeventargs e var devices await windowsdevicesenumerationdeviceinformationfindallasyncdeviceclassvideocapture var rearcamera devices0 if devicescount 0 rearcamera devicessinglecurrdev currdevenclosurelocationpanel windowsdevicesenumerationpanelback mediacapture new mediacapture await mediacaptureinitializeasyncnew mediacaptureinitializationsettings videodeviceid rearcameraid this is captureelement xcapturesource mediacapture recording false protected override async void onnavigatedfromnavigationeventargs e if mediacapture null await mediacapturestoppreviewasync await mediacapturestoprecordasync mediacapturethispose mediacapture null xcapturesource null baseonnavigatedfrome button click handler private async void startmeasureobject sender routedeventargs e if recording await mediacapturestoppreviewasync mediacapturevideodevicecontrollertorchcontrolenabled false recording false else await mediacapturestartpreviewasync mediacapturevideodevicecontrollertorchcontrolenabled true recording true in this form it works perfectlyif i uncomment those preview lines it works but only onceif i press the button three times on off and on again i get exception at line with enabling torchcontrolsystemexception exception from hresult 0xe8010d at windowsmediadevicestorchcontrolput enabledboolean value at pulsometr3mainpaged dmovenextthe hresult varieswhats even more weird it sometimes freezes the phone like 2 out of 3 times and i need to hold power volume downi tried decorating all methods with stathread but it did not help whats even more more interesting when i hold operations by debbuger using f10 to step over lines i am able to toggle preview as many times as i possibly want it is werid since debugger hold all threads right so in theory there is no differencealso phone sometimes freezes on deploy and that is just annoyingany ideas,['c#'] +752852,how to trick an os x app into thinking the mouse is a finger i am writing a mac app that contains a collection view this app is to be run on a large touchscreen thisplay 55 ep series from planar due to hardware limitation the touchscreen does not send scroll events or even any multitouch events how can i go about tricking the app into thinking a mousedowndrag is the same as a mousescrolli got it working halfway by subclassing nscollectionview and implementing my own nspangesturerecognizer handler in it unfortunately the result is clunky and does not have the feeling of a normal os x scroll ie the velocity effect at the end of a scroll or scroll bounce at the ends of the contentimplementation uctouchscrollcollectionview ibactionshowgestureforscrollgesturerecognizernspangesturerecognizer recognizer cgpoint location recognizer locationinviewself if recognizerstate nsgesturerecognizerstatebegan touchstartpt location startorigin nsclipviewself superview documentvisiblerectorigin else if recognizerstate nsgesturerecognizerstateended some notes here about a future feature the scroll bounce i do not want to have to reinvent the wheel here but it appears i already am crud 1 when the touch ends get the velocity in view 2 using the velocity and a constant deceleration factor you can determine a the time taken to decelerate to 0 velocity b the thistance travelled in that time 3 if the final scroll point is out of bounds update it 4 set up an animation block to scroll the document to that point make sure it uses the proper easing to feel natural 5 make sure you retain a pointer or something to that animation so that a touch during the animation will cancel it is this even possible selfscrolldelegatepointsmoother clearpoints refreshdelegatetriggered no else if recognizerstate nsgesturerecognizerstatechanged cgfloat dx 0 cgfloat dy startoriginy selfscrolldelegatescrollscaling locationy touchstartpty nspoint scrollpt nsmakepointdx dy selfscrolldelegatepointsmoother addpointscrollpt nspoint smoothedpoint selfscrolldelegatepointsmoother getsmoothedpoint self scrollpointsmoothedpoint cgfloat end selfframesizeheight selfsuperviewframesizeheight cgfloat threshold selfsuperviewframesizeheight kucpulltorefreshscreenfactor if smoothedpointy threshold end refreshdelegatetriggered nslogtrigger pull to refresh refreshdelegatetriggered yes selfrefreshdelegate scrollviewreachedbottomself a note about this implementation i put together scrollscaling and pointsmoother to try and improve the scroll ux the touchscreen i am using is irbased and gets very jittery especially when the sun is outin case it is relevant i am using xcode 6 beta 6 6a280e on yosemite beta 14a329r and my build target is 1010thanks,['objective-c'] +752934,how to import all tasks from another gulp filejs is it possible to have one main gulpfilejs from which to call tasks from other gulp filesjs simple require of child gulpfilejs into main one does not worki have a platform project which includes several sub projects with separate gulpfiles so i need a solution to manage all child gulpfiles from within main one,['javascript'] +752955,how to identify the issue when java outofmemoryerror how to identify the issue when java outofmemoryerror or stackoverflow comes in production by which reason it is coming or why the server is downfor example i am developing an application which is lived on production and uat instantly on production java outofmemoryerror or stackoverflow then how can we track this issue by which reason it has happened is there any technique that can tell me by which code flow this is happening please explain it i have faced this issue many times,['java'] +752972,google account login integration for android xamarin i need to integrate google login to android xamarin applicationgone through the code from bellow link it shows the error connection failed and googleplayservicesutil google play store is missing even ofter adding google play servicefroyo componenteven i gone through the bellow linksandroid login using google accountgoogle login for android appbut this is related to android eclipse using java code can anybody suggest me how to do this in xamarin any hintslinks are appreciatedthank you,"['c#', '.net']" +752979,when setting a fontsize in css what is the real height of the letters there is a similar question here whose answer in essence saysthe height specifically from the top of the ascenders eg h or l el to the bottom of the descenders eg g or ythis has also been my experiance ie in 14px arial the height of the letter k the baseline height is about 10px the specs say nothing about the calculated fontsize so i am guessing this is bowserspecific but i could not find any reference to itother questions here and here ask roughly the same thing but sadly no answer gives a satisfying explanationis there any documentation on why the fontsize seems to be the size from ascenders to descendes,['css'] +752998,store mouse click event coordinates with matplotlib i am trying to implement a simple mouse click event in matplotlib i wish to plot a figure then use the mouse to select the lower and upper limits for integrationso far i am able to print the coordinates to screen but not store them for later use in the program i would also like to exit the connection to the figure after the second mouse clickbelow is the code which currently plots and then prints the coordinatesmy questionshow can i store coordinates from the figure to list ie click xpos yposis it possible to get two sets of x coordinates in order to do a simple integration over that section of lineimport numpy as npimport matplotlibpyplot as pltx nparange1010y x2fig pltfigureax figadd subplot1axplotxydef onclickevent global ix iy ix iy eventxdata eventydata print x d y d ix iy global coords coords ix iy return coordsfor i in xrange01 cid figcanvasmpl connectbutton press event onclickpltshow,['python'] +753012,can mutexlocking function be marked as const i have threadsafe document class representing custom documentit have getters const functions and setters to modify it is stateall these functions are mutexprotected to guarantee document will not changeduntil the method will be completely executedbut due to qmutex usage i cannot mark stateaccessed functionas const without mutable usage capturing qmutex change it is stateis this code correct or it can be written in a more nice waywithout hacky mutable usageclass document this method should be const it changes only mutex and do not touch document state bool iscorrect const mutable qmutex m lockbool documentiscorrect const capturing mutex object change it qmutexlocker lock m lock constaware code bool result m context null return result,['c++'] +753039,rebuild solution parameter not supported by the signfile task i am trying to create a small exceladdin with just 1 project in the solutioni downloaded the tools at and could create a addini can even debug it but as soon as i rebuild the solution i get the 2 following errors error 1 the targetframeworkversion parameter is not supported by the signfile task verify the parameter exists on the task and it is a settable public instance property error 2 the signfile task could not be initialized with its input parametersfunny enought on another machine the rebuilding is working perfectly and as far as the other developer knows he did not do anything speciali checked a bout abut this signfile task fe but when i unload the project and check the file there are no such entries thereon the problematic machine i created a new addinsolution and run even on a empty solution in the exact same problemsps i cannot uncheck the sign the clickonce manifists checkbox in the signing tab from what i have found a certifate expired but how is that possible if i create a new solutionthanks in advancematthias,['c#'] +753053,virtual function table of multiple inheritance the sample code are as followclass apublic int k virtual int fclass bpublic virtual apublic virtual int aint main coutsizeofasizeofbit prints8 12it seems class b has its own new virtual function table if class a changes toclass apublic virtual int fit prints4 4could anyone explain the reason,['c++'] +753074,comment shortcut android studio i am searching for useful android studio keyboard shortcut for commenting code as in sublime text or eclipse when i press either cmd or cmd maj nothing happens,['android'] +753127,preserving the implicitness of construction in a policybased class consider a policybased smart pointer class ptr with only one policy that will prevent dereferencing it in a null state somehow let us consider 2 policies of this kindnotnullnocheckingsince the notnull policy is more restrictive we would like to allow implicit conversions from ptr t nochecking to ptr t notnull but not in the opposite direction that one has to be explicit for safety please take a look at the following implementationinclude iostreaminclude type traitsinclude typeinfostruct nocheckingstruct notnullstruct nochecking nochecking default nochecking const nochecking default explicit nochecking const notnull stdcout explicit conversion constructor of nochecking stdendl protected nochecking defaulting the destructor in gcc 481 makes it public somehow ostruct notnull notnull default notnull const notnull default notnull const nochecking stdcout explicit conversion constructor of notnull stdendl protected notnull template typename t class safety policy class ptr public safety policyprivate t pointee public template typename f t class f safety policy friend class ptr we need to access the pointee of other policies when converting so we befriend all specializations of ptr implicit conversion operator template class target safety operator ptrt target safety const stdcout implicit conversion operator of typeid this name stdendl static assert stdis convertibleconst safety policy const target safetyvalue what is the condition to check this requires constructibility safety policy of this is not implicitly convertible to targets safety policy calls the explicit conversion constructor of the target type return ptr t target safety this explicit conversion constructor template class target safety explicit ptr const ptrt target safety other safety policy other this is an explicit constructor call and will call explicit constructors when we make ptr constructor implicit pointee otherpointee stdcout explicit ptr constructor of typeid this name stdendl ptr default also binds to temporaries from conversion operatorsvoid test nochecking const ptr int nochecking void test notnull const ptr int notnull int main ptr int notnull notnullptr enforcing not null value not implemented for clarity ptr int nochecking fastptr notnullptr ok calling explicit constructor and notnull is explicitly convertible to nochecking test notnull fastptr should be ok nochecking is implictly convertible to notnull test nochecking notnullptr should be error notnull is explicitly convertible to nochecking return 0live examplethe code above fails when implicitly converting in both directions which means that stdis convertible fails even though the classes have compatible constructors the problems areconstructor overloads cannot differ simply by explicit keyword so we need an explicit constructor and implicit conversion operator or vice versa in the host classexplicit constructor is better because any constructor will call explicit constructors from initialization list even if is implicit itselfimplicit conversion operator cannot create objects of policy type because their destructor is protected this is why stdis convertible fails when it should not and this is also why we cannot use something like boostimplicit cast const target policy this in the conversion operator as it would create a temporary policy object which is forbiddenas for the obvious solutions that are not optimal in my opinionmake the policy destructor public and risk ub when casting the ptr to policy and deleting it this unlikely in the example provided but is possible in realworld applicationmake the destructor public and use protected inheritance i need the enriched interface the public inheritance providesthe question is is there a static test for existence of implicit constructor from one type to another that does not create objects of these typesor alternativelyhow do i preserve the information of implicit construction when calling the policies constructors from the host class constructorediti just realized that the second question can be easily answered with a private implicitflagged constructor like thisinclude iostreaminclude type traitsinclude typeinfostruct implicit flag struct nocheckingstruct notnullstruct nochecking nochecking default nochecking const nochecking defaultprotected explicit nochecking const notnull stdcout explicit conversion constructor of nochecking stdendl nochecking defaulting the destructor in gcc 481 makes it public somehow ostruct notnull notnull default notnull const notnull defaultprotected notnull implicit flag const nochecking stdcout explicit conversion constructor of notnull stdendl notnull template typename t class safety policy class ptr public safety policyprivate t pointee public template typename f t class f safety policy friend class ptr we need to access the pointee of other policies when converting so we befriend all specializations of ptr implicit conversion operator template class target safety operator ptrt target safety const stdcout implicit conversion operator of typeid this name stdendl static assert stdis convertibleconst safety policy const target safetyvalue what is the condition to check this requires constructibility safety policy of this is not implicitly convertible to targets safety policy calls the explicit conversion constructor of the target type return ptr t target safety implicit flag this explicit conversion constructor template class target safety explicit ptr const ptrt target safety other safety policy other this is an explicit constructor call and will not preserve the implicity of conversion pointee otherpointee stdcout explicit ptr constructor of typeid this name stdendl private internal implicitflagged constructor caller that is called from implicit conversion operator template class target safety ptr implicit flag implicit const ptrt target safety other safety policy implicit other this constructor is required in the policy pointee otherpointee stdcout explicit ptr constructor of typeid this name stdendl public ptr default also binds to temporaries from conversion operatorsvoid test nochecking const ptr int nochecking void test notnull const ptr int notnull int main ptr int notnull notnullptr enforcing not null value not implemented for clarity ptr int nochecking fastptr notnullptr ok calling explicit constructor and notnull is explicitly convertible to nochecking test notnull fastptr should be ok nochecking is implictly convertible to notnull test nochecking notnullptr should be error notnull is explicitly convertible to nochecking return 0the errors however are not very readable and we introduce an unnecessary requirement to the policies so an answer to the first question is more preferable,['c++'] +753129,linker command failed with exit code 1 use v to see invocation in swift i used swift language in my ios application project in xcode6 beta6 and then i had to work on it with another computer then i got this errorclang error linker command failed with exit code 1 use v to see invocation this error is shown only different computers than the computer on which i opened my project at first it does not give an error in the first computer which i opened and started to the projecti tried to clean and delete the contents of deriveddata folder but it gives me the same error again below this error it also says that file not found for inside of the deriveddata folderfile not found usersmacbooklibrarydeveloperxcodederiveddatasihirlisayilargmmsqkhqgygosqeuqdiibnrjasbqbuildproductsdebugiphonesimulatorprojectaprojecti looked the other titles for this issue but none of them solve this problem thank you for any help,['ios'] +753316,could not load or assembly or one of its dependencies i am using aforgenet frame work for doing image processing worki have add aforgevideoffmpegdll as a referance to my projecti am using vs2012 and 32 bit build targetwhen buiding i get systemiofilenotfoundexception was unhandled hresult2147024770 messagecould not load file or assembly aforgevideoffmpegdll or one of its dependencies the specified module could not be found sourcevideoreadere filenameaforgevideoffmpegdll fusionlog stacktrace at videoreadereform1ctor at videoreadereprogrammain in cusersprabaddocumentsvisual studio 2012projectsvideoreaderevideoreadereprogramcsline 19 at systemappdomain nexecuteassemblyruntimeassembly assembly string args at systemappdomainexecuteassemblystring assemblyfile evidence assemblysecurity string args at microsoftvisualstudiohostingprocesshostprocrunusersassembly at systemthreadingthreadhelperthreadstart contextobject state at systemthreadingexecutioncontextruninternalexecutioncontext executioncontext contextcallback callback object state boolean preservesyncctx at systemthreadingexecutioncontextrunexecutioncontext executioncontext contextcallback callback object state boolean preservesyncctx at systemthreadingexecutioncontextrunexecutioncontext executioncontext contextcallback callback object state at systemthreadingthreadhelperthreadstart innerexception my code for that is occur exception using systemusing systemcollectionsgenericusing systemlinqusing systemthreadingtasksusing systemwindowsformsnamespace videoreadere static class program summary the main entry point for the application summary stathread static void main applicationenablevisualstyles applicationsetcompatibletextrenderingdefaultfalsehere below line give exception applicationrunnew form1,['c#'] +753386,xamarin ios memory leaks everywhere weve been using xamarin ios for the last 8 months and developed a nontrivial enterprise app with many screens features nested controls weve done our own mvvm arch cross platform bll dal as recommended we share code between android and even our blldal is used on our web productall is good except now in release phase of project we thiscover irreparable memory leaks everywhere in the xamarin iosbased app weve followed all the guidelines to resolve this but the reality is that c gc and objc arc appear to be incompatible garbage collection mechanisms in the current way they overlay each other in monotouch platformthe reality weve found is that hard cycles between native objects and managed objects will occur and frequently for any nontrivial app it is extremely easy for this to happen anywhere you use lambdas or gesture recognizers for example add in the complexity of mvvm and it is almost a guarantee miss just one of these situations and entire graphs of objects will never get collected these graphs will lure other objects in and grow like a cancer eventually resulting in a prompt and merciless extermination by iosxamarins answer is an uninterested deferral of the issue and an unrealistic expectation that devs should avoid these situations careful consideration of this reveals this as an admission that garbage collection is essentially broken in xamarinthe realization for me now is that you do not really get garbage collection in xamarin ios in the traditional c net sense you need employ garbage maintanence patterns actually get the gc moving and doing its job and even then it will never be perfect non deterministicmy company has invested a fortune trying to stop our app from crashing andor running out of memory weve basically had to explicitly and recursively thispose every damn thing in sight and implement garbage maintanence patterns into the app just to stop the crashes and have a viable product we can sell our customers are supportive and tolerant but we know this cannot hold forever we are hoping xamarin have a dedicated team working on this issue and get it nailed once and for all does not look like it unfortunatelyquestion is is our experience the exception or the rule for nontrivial enterpriseclass apps written in xamarinupdatesee answer for thisposeex method and solution,"['c#', 'ios']" +753398,android exifinterface saveattributes without overwriting previous data i am trying to write latlong and other data to the exif header of a jpeg in my custom camera app typically android automatically populates the header with data such as aperture iso shutter speed etc however when i manually add create an exifinterface instance set the gps location with setattributes and call saveattributes all of the other camera data thissapears is this supposed to happen how can i simply add a tag without overwriting everything elsei saw an example elsewhere of creating two exifinterfaces an oldfrom the picture and a new and copying every populated value from the old to the new along with any other data this however is annoying and lengthy i would like to find a better solutionhere is my codetry exifinterface exif new exifinterfacepicturefilegetabsolutepath exifsetattributeexifinterfacetag gps latitude mgpslocationgetlatdms exifsetattributeexifinterfacetag gps longitude mgpslocationgetlondms exifsetattributeexifinterfacetag gps altitude mgpslocationgetaltdms exifsaveattributes catchioexception e eprintstacktrace thanks,['android'] +753428,fluentmigrator not running migrations i have inherited a project that uses fluentmigrator to manage migrations originally the project was executing the migrations inprocess when the application started up but it has cracked down on that and we now have to provide scripts to a dba for all of our database changesas part of this transition i have moved the migrations to a new project called migrations when i try to execute the migrations using the command line tool it seems to work but no migrations are applied to the database the database string is correct because if the versioninfo table does not exist it is createdthere are a number of migrations but most of them are very simple here is an example of the first onei am using sql server 2012 and fluentmigrator 121here is the command line in text for gunr2171packagesfluentmigrator1210toolsmigrateexe c data sourceintegrated securitytrueinitial catalogportal test db sqlserver2012 a sourcemigrationsbindebugmigrationsdlland the sample migrationusing systemusing systemcollectionsgenericusing systemlinqusing fluentmigratornamespace migrations systemdiagnosticscodeanalysissuppressmessagemicrosoftnaming ca1707identifiersshouldnotcontainunderscores migration1 public class m001 createaccounttable migration public override void up createtableaccounts withcolumnidasint32notnullableidentityunique withcolumnpartnercodeasstringnullable withcolumnaccounttypeasint32notnullable withcolumncodeasstringnotnullableuniqueprimarykey withcolumnnameasstringnotnullable withcolumnprimarydomainnameasstringnullable withcolumnisfederatedasbooleannotnullable withcolumnisactiveasbooleannullablewithdefaultvalue1 withcolumnfederatedendpointasstringnullable withcolumncreatedbyasstringnotnullable withcolumncreatedonasdatetimenotnullablewithdefaultvaluedatetimenow withcolumnmodifiedbyasstringnotnullable withcolumnmodifiedonasdatetimenotnullablewithdefaultvaluedatetimenow public override void down deletetableaccounts,['c#'] +753596,why does not not in always retrieve the same results as minus in oracle i have two tablescreate table test1id intcreate table test2id intinsert into test1values 1insert into test1values 2insert into test2values 1then i want to see a list of all the ids that are in test1 and not in test2there is at least three ways i can think of to do thisouter joinselect aidfrom test1 a left outer join test2 b on aid bidwhere bid is nullminusselect idfrom test1minusselect idfrom test2not inselect idfrom test1where id not in select id from test2 so far so good all three of these queries should give me the same results 1 row with the value 2if i insert a null into test2 then the outer join and minus queries continue to return the same results but the not in brings back no rowsthis greatly confused me i then noticed that if i changed it to select idfrom test1where id not in select id from test2 where id is not null that i get the results i was expecting one row againwhy does this occur i assume this is something quite fundamental to sql but i am unclear what it is and i am pretty sure that in other databases i have used previously the three methods i have listed have given equivalent results although i do not have sql server or postgres to test against right now so i may be misremembering their behaviouri suppose one answer to this is stop worrying and just do not use not in but that can be expensive in terms of code readability sometimes that is more elegant than doing everything with outer joins or minus,['sql'] +753683,anonymous union and struct how would you go about doing this in standard c14 because if i am not mistaken this is not standard compliant code with the anonymous structsi wish to access the members the same way as you would with thistemplate typename some typestruct vec union struct some type x y z struct some type r g b some type elements3,['c++'] +753732,error orgtestngtestngexception cannot find class in classpath empclass when i am trying to run the test suite am getting this exception we are using maven projetct here and i done refreshing cleaning reinstalling testng and then imported the maven projects but then also am getting the same exception please suggest any ways that am missing hereerror consoleorgtestngtestngexception cannot find class in classpath empclassat orgtestngxmlxmlclassloadclassxmlclassjava81at orgtestngxmlxmlclassinitxmlclassjava73at orgtestngxmlxmlclassinitxmlclassjava59at orgtestngxmltestngcontenthandlerstartelementtestngcontenthandlerjava543at comsunorgapachexercesinternalparsersabstractsaxparserstartelementabstractsaxparserjava509at comsunorgapachexercesinternalparsersabstractxmldocumentparseremptyelementabstractxmldocumentparserjava182at comsunorgapachexercesinternalimpldtdxmldtdvalidatoremptyelementxmldtdvalidatorjava766at comsunorgapachexercesinternalimplxmldocumentfragmentscannerimplscanstartelementxmldocumentfragmentscannerimpljava1350at comsunorgapachexercesinternalimplxmldocumentfragmentscannerimplfragmentcontentdrivernextxmldocumentfragmentscannerimpljava2778at comsunorgapachexercesinternalimplxmldocumentscannerimplnextxmldocumentscannerimpljava606at comsunorgapachexercesinternalimplxmldocumentfragmentscannerimplscandocumentxmldocumentfragmentscannerimpljava510at comsunorgapachexercesinternalparsersxml11configurationparsexml11configurationjava848at comsunorgapachexercesinternalparsersxml11configurationparsexml11configurationjava7at comsunorgapachexercesinternalparsersxmlparserparsexmlparserjava141at comsunorgapachexercesinternalparsersabstractsaxparserparseabstractsaxparserjava1213at comsunorgapachexercesinternaljaxpsaxparserimpljaxpsaxparserparsesaxparserimpljava649at comsunorgapachexercesinternaljaxpsaxparserimplparsesaxparserimpljava3at javaxxmlparserssaxparserparsesaxparserjava195at orgtestngxmlxmlparserparsexmlparserjava39at orgtestngxmlsuitexmlparserparsesuitexmlparserjava17at orgtestngxmlsuitexmlparserparsesuitexmlparserjava10at orgtestngxmlparserparseparserjava168at orgtestngtestnginitializesuitesandjarfiletestngjava311at orgtestngremoteremotetestngrunremotetestngjava88at orgtestngremoteremotetestnginitandrunremotetestngjava204at orgtestngremoteremotetestngmainremotetestngjava175,['java'] +753785,is it possible to create a generic closure in swift func myfunctit t return iis it possible to make this generic function a closurelet myfunc tit t in return ithis does not work,['ios'] +754024,best practice on using async await say i have the following class definitionspublic class calculator public calculatorresult calculate return longrunningcalculation private calculatorresult longrunningcalculation return new calculatorresult0 public class classthatusesacalculator private readonly calculator calculator public classthatusesacalculator thiscalculator new calculator public void dowork for int i 0 i 10 i var result calculatorcalculate dosomethingwithcalculationresultresult dolightwork onprogresschanged public partial class form form public form initializecomponent private void methodobject sender eventargs e dowork private void dowork var calculator new classthatusesacalculator calculatorprogresschanged s e update progressbar calculatordowork if i would want to do the work done in dowork on the form asynchronously i could add a method getcalculationtask that returns a task using taskrun and add a async eventhandler ie for a button methodone please correct me if i am wrong but it seems to me that this would be the only option when the classthatusesacalculator and calculator classes reside in a library i do not ownprivate task getcalculationtaskiprogresscalculatorprogress progress var calculator new classthatusesacalculator calculatorprogresschanged s e progressreportnew calculatorprogress0 return taskrun calculatordowork private async void methodoneobject sender eventargs e iprogresscalculatorprogress progress new progresscalculatorprogress updateprogressbar await getcalculationtaskprogressin the case i do own the library i think there are two more options one of which very much like the first one probably due to the lack of my own understandingcreate a method on on classthatusesacalculator that encapsulates the dowork method and then call that from an asynchronous method on the formorencapsulate the longrunningcalculation on the calculator class with a taskrunpublic taskcalculatorresult calculateasync return taskrun return longrunningcalculation create an async method on classthatusesacalculator the calls that awaits the newly created methodpublic async task doworkasync for int i 0 i 10 i var result await calculatorcalculateasync dosomethingwithcalculationresultresult dolightwork onprogresschanged create an asynchronous method on the form methodthreeprivate async void methodthreeobject sender eventargs e iprogresscalculatorprogress progress new progresscalculatorprogressupdateprogressbar var calculator new classthatusesacalculator calculatorprogresschanged s args progressreportnew calculatorprogress0 await calculatordoworkasyncnow in my opinion the last option would be the best as i would remain more control but maybe i am way off and would like someones opinion or pointers on this as i can only find explanations on how to consume async but never really how to build methods for others to consume,['c#'] +754059,oneliner to take some properties from object in es 6 how one can write a function which takes only few attributes in mostcompact way in es6i have came up with solution using destructuring simplified object literal but i do not like that list of fields is repeated in the codeis there an even slimmer solutionv let id title v return id title,['javascript'] +754097,android keyboard moves tabs so i have an ionicphonegap app that i just built using ionic start myapp tabs then i added an input on one of the views when i focus the input using an android emulator or device the keyboard come up but so do the tabs do i have to explicitly hide the tabs whenever the keyboard is active on android i would think this would be a common issue but i have not seen any complaints do i just have a bad project or something,['android'] +754110,does selfreference in the constructor counts as escaping reading this article about jsr133 it saysall of the writes to final fields and to variables reachable indirectly through those final fields become frozen if an objects reference is not allowed to escape during construction then once a constructor has completed and a thread publishes a reference to an object that objects final fields are guaranteed to be visible the one caveat with initialization safety is that the objects reference must not escape its constructor the constructor should not publish directly or indirectly a reference to the object being constructedmy question is about what is considered escaping more specifically i want to know if this somewhat artificial and strange code results in a safelypublishable child objectclass parent not final private int answer public int getanswer return answer public void setanswerfinal int answer answer answer public class child extends parent private final object self public child supersetanswer42 self this override public void setanswerfinal int answer throw new unsupportedoperationexception firstly while parent is clearly mutable child is effectively immutable since the parent setter that would allow mutability is not reachable anymorethe reference to this in the constructor is not visible to anyone not getter and not passed to any other object so does this count as escapingbut the object as a whole is being referenced by a final field self and so in theory it is whole content should then be frozen otoh the final field is itself not reachable so maybe it does not count i could very well imagine the jit just completely optimizing it awayif self was made accessible through a getter but the getter is not called in the constructor does it then count as escaping assuming it did not before this would prevent the jit from optimizing it away so that it must then count maybeso is child safelypublishable and if not why and would a getter for self change the answerin case the purpose of the question is not clear i think that if this works it would allow one to easily make a mutable class safelypublishable by just extending it as shown above,['java'] +754403,is it possible to write c functions that modify structs of types defined in go code this is a followup to this question i made an assumption there that might not be true which is why i am explicitly asking about it because i forgot to ask if this is actually possible i have already filed issue 8114 about thiswith cgo it is possible to have go code operate on c types like thispackage fooinclude sysstathimport cfunc filesizefromstatstat cstruct stat int64 return int64statst sizeis the reverse possible ie writing c functions that operate on go types the concrete point of this is outlined in the question linked above i want to marshall c structures that cannot be accessed from go code either because they use unions or bitfields or because their alignment makes them incompatible with go code,['c'] +754459,how to get rid of a vertical line in the editor pane of intellij idea recently a gray vertical line appeared in about the middle of the editor pane of my intellijidea community edition 1314 probably due to some manipulations with the settings that i cannot remember i cannot find how to get rid of it which is annoying who can helpthanks,['java'] +754613,hazelcast query in custom objects i am using hazelcast as a shared map in my application my map is like thatmapstring myobjectand myobjectclass myobject implements serializeble map fieldname fieldvalue mapstring object mymapso i would like to use hazelcast thistributed query support to query in my object i have checked that hazelcast uses gets method to retrieve the object value but in my case i do not have a get instead of i would like to implement my own getfield likeobject getfieldstring fieldname return mymapfieldnameand force hazelcast to call this method as a workaround i have hacked hazelcast code to use a customgetter in the classhazelcastsrcmainjavacomhazelcastqueryimplreflectionhelperjavaline 144if localgetter null localgetter new customfieldgettername objand here my customfieldgetter clastatic class customfieldgetter extends getter final object value final class type final string fieldname customfieldgetterstring fieldname object obj throws nosuchmethodexception invocationtargetexception illegalaccessexception supernull thisfieldname fieldname thisvalue objgetclassgetmethodgetfield stringclassinvokeobj fieldname thistype valuegetclass override object getvalueobject obj throws exception return value override class getreturntype return type override boolean iscacheable return false override public string tostring return fieldgetter parent parent field fieldname ok cool after recompilation of hazelcast and using this new jar i could reach queries using plain sql but for pagingqueries i got some errorsso my finally question isi would like to avoid hack hazelcast code for further updates does hazelcast has some supports on this issue is there any other solution for this problemps i am using hazelcast version hazelcast33rc3thanks in advance,"['java', 'sql']" +754627,scipy signal find peaks cwt not finding the peaks accurately i have got a 1d signal in which i am trying to find the peaks i am looking to find them perfectlyi am currently doingimport scipysignal as signalpeaks signalfind peaks cwtdata nparange100200the following is a graph with red spots which show the location of the peaks as found by find peaks cwtas you can see the calculated peaks are not accurate enough the ones that are really important are the three on the right hand sidemy question how do i make this more accurateupdate data is here for some background what i am trying to do is locate the space inbetween the fingers in an image what is plotted is the xcoordinate of the contour around the hand cyan spots peaks if there is a more reliablerobust approach this please leave a comment,['python'] +754631,compress video like whatsapp i am not an expert in video editing but what i want to understand the logic of whatsapp video processingfirst of all i have noticed that whatever the file is whatsapp sets the limit of uploaded videos to 16mo after which whatsapp crops the video to not exceed the limit is this a convention or it is a personal choice secondly when a video is recorded using the camera it is not compressed by default so whatsapp compresses it using ffmpeg i guess and it takes no time tried for a video of 1min 1920x1080 with 125mo of size becomes 640x360 with 5mo of size in no time and the upload starts automatically how may they do this and why the choice of 640x360 it seems to me very fast for 2 asynchronous tasks compression uploadwhen i run the compression command ffmpeg y i inmp4 codecv libx264 crf 23 preset medium codeca libfdk aac vbr 4 vf scale1640formatyuv420p outmp4 it takes approximatively 1 min and the video is being rotated dfinally when we download a video from youtube it is already compressed i guess and whatsapp does not even try to compress it so i think that it automatically detects thats the video is compressed how can we detect this thank you,['android'] +754639,intellij could not autowire inspection a more than one bean for spring jpa repositories in our code we have a number of spring jpa repositories one for each of our model classes they are defined as where name is the name of our modal classrepositorypublic interface namerepository implements jparepositoryname long awe inject them in our beans using the injectannotation from javaxinjectpublic void setnamerepositorynamerepository namerepo thisnamerepo namerepoprivate namerepository namerepothe issue is that intellij underlines the namerepo in the setnamerepository function as an error with the textcould not autowire there is more than one bean of repository type beans repo repothis is only a problem with the inspection compilation and running our app works fine but in the effort of making the inspections in ij usable this is a big problem anyone have suggestions on how to get intellij to behavefor reference we are using hibernate as our jpa provider and the data source is set up in both the database and persistence tool windows,['java'] +754650,quartz job vs thread for immediate one time task let us say i have some unit of work that needs to get done and i want to do it asynchronously relative to the rest of my application because it can take a long time eg 10 seconds to 2 minutes to accomplish this i am considering two options schedule a quartz job with a simple trigger set to fire only once and as soon as possible create a runnable instance hand it off to a thread and call runin the context of the above i have the following questions what does using the quartz job get me that the thread does not have what does using the runable get me that using the quartz job does not in terms of best practices what criteria ought be used for deciding between quartz jobs and runnables for this use case,['java'] +754656,javascript touchend versus click dilemma i am working on some javascript ui and using a lot of touch events like touchend for improved response on touch devices however there are some logical issues which are bugging me i have seen that many developers mingle touchend and click in the same event in many cases it will not hurt but essentially the function would fire twice on touch devicesbuttononclick touchend functionevent this fires twice on touch devicesit has been suggested that one could detect touch capability and set the event appropriately for examplevar myevent ontouchstart in documentdocumentelement touchend clickbuttononmyevent functionevent this fires only once regardless of devicethe problem with the above is that it will break on devices that support both touch and mouse if the user is currently using mouse on a dualinput device the click will not fire because only touchend is assigned to the buttonanother solution is to detect device like ios and assign based event based on deviceclick event called twice on touchend in ipad of course the solution in the link above is only for ios not android or other devices and seems more like a hack to solve something quite elementaryanother solution would be to detect mousemotion and combine it with touchcapability to figure out if the user is on mouse or touch problem of course being that the user might not be moving the mouse from when you want to detect it the most reliable solution i can think of is to use a simple debounce function to simply make sure the function only triggers once within a short interval for example 100msbuttononclick touchend debounce100 functionevent this fires only once on all devicesam i missing something or does anyone have any better suggestionsedit i found this link after my post which suggests a similar solution as the abovehow to bind touchstart and click events but not respond to both,"['javascript', 'jquery', 'ios']" +754808,how to enable compression in ruby on rails i posted a similar question hereserving compressed assets in heroku with rackzippybut decided to give up on that service since i could not get it to worki ran pagespeed insights on my website to determine the speed of my websitethe most important suggestion i received was to enable compressioncompressing resources with gzip or deflate can reduce the number of bytes sent over the networkenable compression for the following resources to reduce their transfer size by 1912kib 74 reductioni have followed the instructions on this websiteand it says to consult the documentation for your web server on how to enable compressioni have used this website to find out my web serverit turns out that my web server is webrickthe pagespeed insights page only lists the following 3 serversapache use mod deflatenginx use ngx http gzip moduleiis configure http compressioni have searched for documentation on gzip compression for webrick servers but could not find anythingi have searched for how to enable compression in rails and could not find anything that is why i am asking herei have tried using rack zippy but gave up on itright now i do not even know where to begin my first step is finding out what i should doediti followed ahmeds suggestion of using rackdeflatori confirmed that i had it by runningrake middleware use rackdeflatorand thengit add git commit m git push heroku masterunfortunately pagespeed still says it needs to be compress i confirmed that by going into developer tools network settings and refreshing the page size and content were virtually identical for every resource meaning the files are not compressedis there something wrong with one of my filesthank you for your helphere is my full configapplicationrb filerequire fileexpand pathboot file require railsallbundlerrequirerailsgroupsmodule appname class application railsapplication configmiddlewareuse rackdeflater configassetsprecompile wpng jpg jpeg gif configexceptions app selfroutes configcache store memory store endendif there is a problem the source is likely over there rightdo i need to install the deflator gem,"['ruby-on-rails', 'ruby']" +754810,mbprogresshud and uitableview i am thisplaying a hud while populating the tableview but it seems to be showing behind the tableview tableview separator breaking the hudheres the code in the tableviewcontroller voidviewdidload super viewdidloadmbprogresshud hud mbprogresshud showhudaddedtoselfview animatedyeshudmode mbprogresshudmodetexthudlabeltext loading populate the tableself gettabledataselftableviewrowheight 90it is doing this only with tableviews,['ios'] +754959,dynamic syntax highlighting with angularjs and highlightjs i am building a site that illustrates common application vulnerabilities such as sql injection i am using angularjs and highlightjs to create interactive examples how can i make both angularjs and highlightjs update my code snippetsexamplethis fiddle demonstrates how entering or 11 in the email field could change the intended behavior of the query if the users input is not validated or sanitized select from dbousers where emailemail and passwordpassword when a user enters an email address and password angular updates the query however syntax highlighting does not updateselect from dbousers where email and passwordi tried reinitializing hljs but when i do angular stops updating the queryhljsinithighlightingcalled falsehljsinithighlightingapplicationscript var app angularmoduleapp hljs appcontrollercontroller functionscope scopeemail scopepassword scriptdiv ngappapp ngcontrollercontroller div div classrow div classcolsm4email input typetext classformcontrol ngmodelemail div div classcolsm4password input typetext classformcontrol ngmodelpassword div div br div hljs includecompileme compiletrue languagesqldiv div script typetextngtemplate idcompileme select from dbousers where email email and password password scriptdiv,['javascript'] +754969,type viewcontroller does not conform to protocol uitableviewdatasource started practice swift in singleviewcontroller i am trying to make a uitableview in storyboard i set the datasource and delegate here i am getting the error viewcontroller does not conform to protocol uitableviewdatasource class viewcontroller uiviewcontroller uitableviewdatasource uitableviewdelegate iboutlet weak var table uitableview override func viewdidload superviewdidload do any additional setup after loading the view typically from a nib override func didreceivememorywarning superdidreceivememorywarning thispose of any resources that can be recreated func numberofsectionsintableviewtableview uitableview int return 20func tableviewtableview uitableview cellforrowatindexpath indexpath nsindexpath uitableviewcell let celluitableviewcelluitableviewcellstyle uitableviewcellstylesubtitle reuseidentifier mycellcelltextlabeltextrowindexpathrow celldetailtextlabeltextsubtitleindexpathrow return cell,['ios'] +754985,why an expression instead of a constant in a c forloops conditional in many programming competitions i have seen people write this type of forloopfori 0 i 1 7 iunless i am missing something that is the same asfori 0 i 128 iwhy use the 1 7 versionis not calculating the condition every time an unnecessary overhead,['c'] +754986,what is the difference between mingw mingww64 and mingwbuilds what are the differences between mingw mingww64 and mingwbuildsand which one should i use to compile c 11 source code with the eclipse ide on a windows 8 machine,['c++'] +755000,how does the c compiler parse the following c statement consider the following linesint iprintfdiwill the lexical analyzer go into the string to parse and d as separate tokens or will it parse d as one token,['c'] +755069,can objgettypeisinterface be true while doing something almost completely irrelevant a question popped into my headcan an expression of the form objgettypeisinterface ever be true in a codebase consisting exclusively of c codei suspect the answer is no becausegettype will always return the runtime typethe runtime type for concrete types matches the invoked constructor thus it is never an interface because interfaces do not have constructorsanonymous types cannot implement an interface and if they did they would still have their anonymous class typeinstances of internal classes of other assemblies implementing public interfaces will still have the class as the runtime typeusing comimport coclasstypeofmyclass on an interface makes it look like you can instantiate it but the constructor call actually instantiates the referenced classi cannot think of any other case am i missing something or is my guess correct,['c#'] +755093,running python from atom in sublime we have an easy and convent way to run python or almost any language for that matter using a b or ctrl bwhere the code will run in a small window below the source code and can easily be closed with the escape key when no longer neededis there a way to replicate this functionally with githubs atom editor,['python'] +755117,rake route error missing action key on routes definition i am getting rake routesrake abortedargumenterror missing action key on routes definition please check your routesusrlocalrvmgemsruby212gemsactionpack415libaction thispatchroutingmapperrb243in default controller and actionusrlocalrvmgemsruby212gemsactionpack415libaction thispatchroutingmapperrb117in normalize optionsusrlocalrvmgemsruby212gemsactionpack415libaction thispatchroutingmapperrb65in initializeusrlocalrvmgemsruby212gemsactionpack415libaction thispatchroutingmapperrb1487in newusrlocalrhere is my routesrbrailsapplicationroutesdraw do get scriptindex get landingindex root landingindexendwhat is causing the problem and how do i fix it,"['ruby-on-rails', 'ruby']" +755138,estimote beacons difference between monitoring and ranging listeners i do not seem to really understand the difference between the monitoringlistener and the ranginglistenerin my particular use case i would like to constantly know all beacons within range and would like to know when a region associated with any of them is exitedthis is a snippet of what i am talking about beaconmanagersetranginglistenernew beaconmanagerranginglistener override public void onbeaconsthiscoveredregion region final listbeacon beacons beaconmanagersetmonitoringlistenernew beaconmanagermonitoringlistener override public void onenteredregionregion region listbeacon beacons override public void onexitedregionregion region i do not really get the difference between the onbeaconsthiscovered and onenteredregion methods when you start listening for any one of them you pass a region as a parameter so that confuses me a little bit more since at first glance i assumed the first one was just constantly searching while the other one just looked for a specific regionthanks,['android'] +755148,angular ui router nested views i have a structure like thisdiv uiviewmain content populated here by angularjs uirouter aside uiviewsidebar content populated here by angularjs uirouter asidedivi want to be able to define the templates in the main state like below instead of having to manage it in the child statestatestate1 url views main templateurl modulesblogpartialsindexhtml controller blogcontroller sidebar templateurl modulescorepartialssidebarhtml i would like the uiview named sidebar to not be a child state of main and be populated by the main states views object instead of by a child states templateurl field how can i do that,['javascript'] +755212,trying to understand protocoldelegates in swift i am new to programming swift and i am trying to understand how to pass data between two view controllers no segue with protocols and delegatesi have a view controller view a which has a text field and button when the user hits that button it should then show that text in a label in another view controller view bi cannot get the label to show the text i would appreciate an explanation of what is required to make this workthanks so much import uikit protocol sendnametoviewb func shownamelabelnamestring class viewa uiviewcontroller var delegate sendnametoviewb iboutlet weak var textfield uitextfield ibaction func addbuttonsender anyobject delegateshownamelabeltextfieldtext override func viewdidload superviewdidload do any additional setup after loading the view typically from a nib override func didreceivememorywarning superdidreceivememorywarning thispose of any resources that can be recreated class viewb uiviewcontroller sendnametoviewb iboutlet weak var thelabel uilabel func shownamelabelname string thelabeltext name,['ios'] +755266,nginx serves php files as downloads instead of executing them i am installing a website in a droplet digital ocean i have a issue for install nginx with php properly i did a tutorial but when i try to run some php file it is just downloading it for example it is working but if i go to the main it is downloading my indexphp any idearwrr 1 agitar user wdata 418 jul 31 1827 indexphprwrr 1 agitar user wdata 21 aug 31 1120 infophpmy etcnginxsitesavailabledefaultserver listen 80 default server listen 80 default server ipv6onlyon root varwhtml index indexhtml indexhtm indexphp make site accessible from httplocalhost server name agitarycompartircom location php fastcgi split path info php note you should have cgifix pathinfo 0 in phpini with php5cgi alone fastcgi pass 12700190 with php5fpm fastcgi pass unixvarrunphp5fpmsock fastcgi index indexphp include fastcgi params location try files uri uri 404 uncomment to enable naxsi on this location include etcnginxnaxsirules others location are commented,['php'] +755288,fragment transaction load empty view but fragment is shown after rotating device i am building a navigation drawer as designed by the google documentation however i have an issue where the fragment is not being replaced when the app first loads the default fragment is loadedclicking on another item on the drawer list leaves an empty viewhowever on rotating the device loads the fragment chosenpublic void selectnavactivtyint position todo changing between the different screens selection fragment null switch position case 0 fragment overlaynewinstance break case 1 fragment dummynewinstance break iffragment null attach added to handle viewpager fragments fragmenttransaction trans getsupportfragmentmanagerbegintransaction transreplaceridcontent frame fragmentattachfragment addtobackstacknull transcommit getfragmentmanagerexecutependingtransactions else logddrawer activityerror in creating fragment,['android'] +755359,how can i mock private static method with powermockito i am trying to mock private static method anothermethod see code belowpublic class util public static string method return anothermethod private static string anothermethod throw new runtimeexception logic was replaced with exception here is me test codepreparefortestutilclasspublic class utiltest extends powermocktestcase test public void should prevent invoking of private method but return result of it throws exception powermockitomockstaticutilclass powermockitowhenutilclass anothermethodthenreturnabc string retrieved utilmethod assertnotnullretrieved assertequalsretrieved abc but every tile i run it i get this exceptionjavalangassertionerror expected object to not be nulli suppose that i am doing something wrong with mocking stuff any ideas how can i fix it,['java'] +755409,onthisconnected no suitable method found to override signalr i have been trying to implement a chat room by following the aspnet signalr chat room tutorial on codeproject however i am getting the error hubschathubsonthisconnected no suitable method found to overridechathub classpublic class chathub hub region data members static listuserdetail connectedusers new listuserdetail static listmessagedetail currentmessage new listmessagedetail endregion region methods public void connectstring username var id contextconnectionid if connecteduserscountx xconnectionid id 0 connectedusersaddnew userdetail connectionid id username username send to caller clientscalleronconnectedid username connectedusers currentmessage send to all except caller client clientsallexceptidonnewuserconnectedid username public void sendmessagetoallstring username string message store last 100 messages in cache addmessageincacheusername message broad cast message clientsallmessagereceivedusername message public void sendprivatemessagestring touserid string message string fromuserid contextconnectionid var touser connectedusersfirstordefaultx xconnectionid touserid var fromuser connectedusersfirstordefaultx xconnectionid fromuserid if touser null fromuser null send to clientsclienttouseridsendprivatemessagefromuserid fromuserusername message send to caller user clientscallersendprivatemessagetouserid fromuserusername message public override systemthreadingtaskstask onthisconnected var item connectedusersfirstordefaultx xconnectionid contextconnectionid if item null connectedusersremoveitem var id contextconnectionid clientsallonuserthisconnectedid itemusername return baseonthisconnected endregion region private messages private void addmessageincachestring username string message currentmessageaddnew messagedetail username username message message if currentmessagecount 100 currentmessageremoveat0 endregionany clues as to why this is happening,['c#'] +755432,issues with touch scroll on ios when focusing inputs i am having some issues with a scrolleable div on ios when trying to scroll by touching outside an input it scrolls ok without any problem but when i try to scroll and i touch an input to start scrolling there are a lot of chances that it happens because it is a div with a lot of inputs it scrolls the whole window instead scrolling the div i do not have that problem either in desktop or android i found a similar question ios html input tag stops scrolling in scrollable element but it does not have any answer either while i do not find any good solution i decided to prevent the event touchmove when the user touches an input but it is not exactly what i wantmay be someone already faced this problem and can help i would really appreciate itthanks in advanceregardsmarcelo,"['html', 'ios']" +755470,passing variables between view controllers using a segue i use swift and xcode 6 and would like to pass a variable from one view controller to another using a seguei have created a segue called maintotimer which is trigger once button is pressed i would like to be able to use the variable called duration on the second view controlleris it possible to pass multiple variables and constantswhat code do i need associated to each view controller thank you in advance,['ios'] +755593,facebook messenger accessibility i am writing an accessibility app that helps users navigate on android using a mixture of voice controls and controls provided via external aiding tools it uses monkeytalk java api to do the heavier workto help the user about what is happening we use an accessibility service as well which reads notification so the user can take action fasteri have been informed that they get no audio cue when a message arrives on facebook messenger and checking logs what i see isdnotificationservice2665 package comfacebookorcatext and eventgettextsize returns 0 on accessibilityevent eventright now they have to open the app and get the text read to them which is 2 voice commands morei get all the other notifications correctly i tried looking for documentation from facebook about their stance on accessibility but i found nothingis there any way to get the text from their notifications,['android'] +755876,syntax error installing gunicorn i am following this heroku tutorial and when i am trying to install gunicorn in a virtualenv i am getting this errorvenvjabuntu14ubuntudesktophelloflask pip install gunicorndownloadingunpacking gunicorndownloading gunicorn1911py2py3noneanywhl 104kb 104kb downloadedinstalling collected packages gunicorncompiling homejabuntu14desktophelloflaskvenvbuildgunicorngunicornworkers gaiohttppy file homejabuntu14desktophelloflaskvenvbuildgunicorngunicornworkers gaiohttppy line 64 yield from selfwsgiclose syntaxerror invalid syntaxsuccessfully installed gunicorncleaning uphowever when i run foreman start it appears to work properlyhow important is this error any idea how to solve it,['python'] +755893,events and dom elements let us assume that i have a page with a two column layout where the left column is a set of links and it loads the associated html pagetemplate in the right column when that link is clickedupon loading a template there is a template handler that gets initialized as a singleton via requirejs and it defines some methods and handlers likesomepageprototypesavehandler functione page handler has a handlersomepageprototypeinitialize function btnsaveonclick savehandlerthen i am attaching dom events through an initialize method every time the page loadssomepageinitialize this attaches the click eventnow when i click another link on the left a different template page is loaded and the above process repeats for that pagei am wondering what happens to the click event that was attached earlier to the btnsave element is it now a dangling event handler in the jquery cacheif i try to remove it when the same page loads again will it actually remove the original event btnsaveoffclick savehandlerdoes executing the following block prevent memory leaks dangling references the potential problem here is that btnsave is part of the newly loaded template and not the element i attached the handler to earlier which does not exist anymorebtnsaveoffclick savehandlerbtnsaveonclick savehandler what is the best way to ensure i do not end up with dangling references and memory leaks this is a potential question for plain javascript too my understanding is that the above will not work when the template page is refreshed i am going experiment with it in the meanwhile but it would be nice to know how the experts handle this thanks,"['javascript', 'jquery']" +755963,matching constructor to counterpart in generic type definition i have been thinking about this problem for a while and it feels like there must be a simple solution that i am missinglet us say i have the following classpublic class foot public foot value public fooint value if i get all constructors on the type foosystemint32 i will get back two constructors both with a single parameter of type systemint32 which cannot be differentiatedif i get all constructors from the generic type definition of foosystemint32 foot i will get back two constructors one which accepts a generic parameter t and one that accepts a parameter of type systemint32 will return two constructors with signatures that look identical var type typeoffooint var ctors1 typegetconstructors will return two constructors as well parameters can be differentiatedvar generictypedefinition typeoffoointgetgenerictypedefinitionvar ctors2 generictypedefinitiongetconstructorsis there a way to match a constructor to its counterpart in its generic type definition,['c#'] +756027,variable 1 statement 1statement 2 construct in c main int a10b30c0 if c abba printfdc why the construct is legal in c and why it returns the last statement value as the result of the expression why it work similar to comma operator,['c'] +756035,refreshing parent viewcontroller after thismissing modalviewcontroller in my ios app a user can select an image from a list upon which they are presented with a modal that contains the image and options to delete the image if the user chooses to delete the image she is returned to the original viewcontroller containing the list of images i need to then refresh the original viewcontroller to take into account the deleted imagei tried using nsnotificationcenter to broadcast when an image is deleted to the parent view controller however it seems like the broadcast is never received is there some other way to send data back to the parent viewcontroller after the modal is thismissed anddetect when the modal is thismissed from the parent viewcontrolleri tried following the example outlined here but it did not seem to workbelow is my codeeditstepviewcontroller original view controlleruistoryboard storyboard uistoryboard storyboardwithnamemain bundlenilmediapreviewviewcontroller mediapreviewvc mediapreviewviewcontroller storyboard instantiateviewcontrollerwithidentifiermediapreviewviewcontrollermediapreviewvcselectedimageurl nsstring stringwithformatgesturerecognizerviewtaguinavigationcontroller navigationcontroller uinavigationcontroller alloc initwithrootviewcontrollermediapreviewvcnsnotificationcenter defaultcenter addobserverself selectorselectordidthismissmediapreview namemediapreviewthismissed objectnilself presentviewcontrollernavigationcontroller animatedyes completionnilmediapreviewviewcontroller second viewcontroller self deleteimage nsnotificationcenter defaultcenter postnotificationnamemediapreviewthismissed objectnil userinfonil self thismissviewcontrolleranimatedyes completion nslogthismissed controller then back in editstepviewcontrollervoiddidthismissmediapreview nslogthismissed media preview this is never logged selfview setneedsthisplay refresh view to account for deleted imagethanks in advance for your help,"['ios', 'objective-c']" +756074,app crashes when storing nsarray in nsuserdefaults i could not store an nsarray in nsuserdefaults the app gets crashedin this line saveddata setobjectjsonvalue forkeyjsondatabelow is my code and i have mention my log error belownsarray jsonvalue nsjsonserialization jsonobjectwithdatadata options0 errornilnsuserdefaults saveddata nsuserdefaults standarduserdefaultssaveddata setobjectjsonvalue forkeyjsondatasaveddata synchronizeerror log terminating app due to uncaught exception nsinvalidargumentexception reason nsuserdefaults setobjectforkey attempt to insert nonproperty list object cfbasichash 0x8c62b10 0x1d2aec8type immutable dict count 3 entries,"['ios', 'objective-c']" +756081,some containers in stl do not have find function some of the stl containers such as stdlist and stdvector do not have find method as a member function why is that i know that there is the alternative of using stdfind from algorithm but still this use is not 100 natural,['c++'] +756097,html5 date picker opens up only on 2nd click i am using html5 date picker for my date calendar date boxinput typedate however in nexus 7 chrome 36 and motorolla chrome 33 i found out that we need to click on the date box twice for the date picker to open up what is the reason behind it how can this problem be solved,['android'] +756104,if the oncomplete call is made for a rxjava subject do i have to manually unsubscribe again i am using an rxjava replaysubject in my fragment i am attempting to use the replaysubject in a way where i would like the subject to execute a process until completion possibly beyond the life of the fragment on completion of the process i would like to release the resources which as i understand is done by unsubscribing the subscription at the time of registering the observer which in my case is the subject itself in this github issue thread benjchristensen saysif it is an observable then it should emit an oncompleted and be doneif it is an observer then it should unsubscribe from the subscription it received when it called observablesubscribe and it will give the observable a chance to shutdown and clean upif it is a subject which is both an observer and an observable what is the behavior if i call oncomplete on the subject does that basically mean the subscription is stopped and i am therefore relieved of needing to manually unsubscribe the subscription i get by registering the observer,['android'] +756133,how to access cellular data usage statistics per application programmatically in iphone i want to get cellular data usage details per application programmatically also please note that it should not be mandatory to be executed on jailbroken device please suggest some api,"['ios', 'iphone']" +756240,php how to check if a date is today yesterday or tomorrow i would like to check if a date is today tomorrow yesterday or elsebut my code does not workcodetimestamp 20140902t1334date datedmy himatch date datedmy hi strtotimetimestampifdate match date today elseifstrtotime1 day date match date yesterday elseifstrtotime1 day date match date tomorrow else sometimethe code always goes in the else case,['php'] +756436,accessing camera in phone for ios and android using html5 i need to create a photobooth mobile application and decided to use html5 to work on my mobile application currently i am using the getusermedia method which works perfectly well on my laptop webcam however when i tried to test it out on my phone as an mobile application it could not work and all it shows is a video icon which leads me to find out that getusermedia does not support in android browseri would still like to continue using html5 to get my photobooth mobile application working but how can i access the camera in my phone and is it possible to do it,"['android', 'ios']" +756542,swift different images for annotation i managed to get a custom icon for a annotation pin in swift but now i am still stuck using 2 different images for different annotations right now a button adds a annotation to the map there should be another button that also adds a annotation but with another iconis there a way to use the reuseid for thisclass viewcontroller uiviewcontroller mkmapviewdelegate iboutlet weak var map mkmapviewibaction func btpressedsender anyobject var latcllocationdegrees 40748708 var longcllocationdegrees 73985643 var latdeltacllocationdegrees 001 var longdeltacllocationdegrees 001 var spanmkcoordinatespan mkcoordinatespanmakelatdelta longdelta var locationcllocationcoordinate2d cllocationcoordinate2dmakelat long var regionmkcoordinateregion mkcoordinateregionmakelocation span mapsetregionregion animated true var information mkpointannotation informationcoordinate location informationtitle test title informationsubtitle subtitle mapaddannotationinformationfunc mapviewmapview mkmapview viewforannotation annotation mkannotation mkannotationview if annotation is mkpointannotation return nil let reuseid test var anview mapviewdequeuereusableannotationviewwithidentifierreuseid if anview nil anview mkannotationviewannotation annotation reuseidentifier reuseid anviewimage uiimagenamed1png anviewcanshowcallout true else anviewannotation annotation return anview,['ios'] +756592,constant integer promotion rules to give a little background unrelated to the question which will follow in c11 i noticed a narrowing issueint foo 0xf this was failing to compile narrowing conversion because 0xf is an unsigned int however i have seen cases where 0xff is signedi have looked over integer promotion rules but this is mostly within the context of lvalues and not rvaluesconstants how does the compiler determine the type of constants without literal suffixes is there documentation or a nice little table cheat sheet that shows the rules for this i am not even really sure what this is called otherwise i would have attempted to find it myself in the c11 standardthanks in advance,['c++'] +756599,ios 8 xcode 6 whats the point of the grayed out constraints in the xcode 6 betas when i delete a constraint it does not remove it completely but grays it out i thought that was to imply that the constraint was used in a different size class but that does not seem to be the case also how do you permanently delete these constraints,['ios'] +756689,exception raised during rendering javalangsystemarraycopyciciiv exception details are logged in window show view error log i cannot find any other android api in the project it is showing only api 20 android 44w how do i overcome from it,['android'] +756761,reinterpret castp or static castvoidp for bytewise pointer difference which is better is there any difference between the following three casts for extracting raw byte pointers for use in pointer arithmetic assume a platform where char is 1 bytestatic castcharvoidptrreinterpret castcharptrupdated or static castcharstatic castvoidptrwhich should i preferin more detailgiven pointers to two member objects in a class i would like to compute an offset from one to the other so that i can reconstruct the address of one member given an offset and the address of the other member assumed data layoutstruct c a a b bthe code that i use at the moment is along the lines ofvoid approach1 a pa b pb compute offset stdptrdiff t offset static castcharvoidpa static castcharvoidpb then in some other function given offset and ptr to b compute ptr to a a a static casta voidstatic castcharvoidpb offset main c c approach1ca cbi would like to know whether the following is better or worsevoid approach2 a pa b pb stdptrdiff t offset reinterpret castcharpa reinterpret castcharpb a a reinterpret casta reinterpret castcharpb offset are the two methods entirely equivalent are they equally portablemy impression is that approach1 is more portable because static casting a pointer to and from void preserves the address whereas reinterpret cast guarantees less see accepted answer at linki would like to know what the cleanest way to do this isupdate explanation of purposea number of people have asked what is the purpose of computing these offsets the purpose is to construct a metaclass table of instance offsets this is used by a runtime reflection mechanism for automatic gui building and persistance the offsets are not serialized just used to traverse the structure the code has been in production for over 15 years for the purposes of this question i just want to know the most portable way of computing the pointer offsets i have no intention of making large changes to the way the metaclass system works in addition i am also generally interested in the best way to do this as i have other uses in mind eg difference pointers for shared memory codenote i can not use offsetof because in my actual code i only have the pointers to instances a and b i do not necessarily have the type of the containing object c or other static info to use offsetof all i can assume is that a and b are members of the same object,['c++'] +756771,validity of this in destructor on the last line of a destructor i have a diagnostic type message which takes a printflike formobject destroyed at p thisi have concerns though about how well this is defined at such a pointshould i have such reservations is the behaviour welldefined,['c++'] +756980,how to open existing android projectbuildgradle into android studio i am new to android studioi have an existing android project which was build from android studio now i need to open that project from buildgradethat projects filefilei followed this step fileopenbuildgradlefrom that existing projectbut it shows the processing window as below image for so long time does not responding well so any one have idea about this please help me,['android'] +756987,python convert timedelta to int in a dataframe i would like to create a column in a pandas data frame that is an integer representation of the number of days in a timedelta column is it possible to use datetimedays or do i need to do something more manualtimedelta column 7 days 232900day integer column7,['python'] +757041,why does new stringhello new stringhello evaluate to false why does the following statement return false in javascriptnew stringhello new stringhello,['javascript'] +757043,atomic getload and setstore with older gcc sync builtins i am working with a vendor branch of gcc 46 and need 4 basic atomic operations on an unsigned integeratomic incrementatomic decrementatomic setatomic get the newer atomix x builtins are not supported by this gcc version only the sync builtinsthis means i can do these operationsdefine atomic incptr sync fetch and addptr1define atomic decptr sync fetch and subptr1define atomic getptr sync fetch and addptr0however i cannot find a way to implement an define atomic set which would atomically set a variable is there any way to achiece this with gcc 46x also is there a better way to implement the above atomic get the generated assembly does look fine from an atomic point of view albeit it is suboptimal due to actually performing an add operationedit the architectures in question is armv6 x86 and x86 64,['c'] +757064,should not char implicitly converted to stdstring here is my codeinclude iostreamusing namespace stdstruct st bool operatorconst struct st s1 const string s2 return trueint main struct st st new st const char p abc if st p return 0 return 1i get compile errorprogcpp1412 error comparison between thistinct pointer types asta and aconst chara lacks a cast fpermissive if st p i wonder why the implicit conversion from char to string does not work here updateantons answer makes sense i updated the codeinclude stringusing namespace stdstruct st bool operatorconst struct st s1 const string s2 return trueint main struct st st const char p abc if st p return 0 return 1now it compiles,['c++'] +757065,is ie 11 tractive selector broken i can select and highlight td elements in ie but cannot highlight all td in a tr using tractive this works as expected in firefox and chrome here is a jsfiddle example am i doing something wrong in the css still doing itin chrome safari opera and ffhtmlbody br div idrowcount table classt2 tr thclick a cell should highlight all in the rowth tr tr tdtractive tdtd tdtdactivetd tr table divbodycsstable cursor default border 1px solid black backgroundcolor transparentdiv zindex 0 thisplay block border4px solid cc3300 width 80 backgroundcolor 4d70dbth textalign lefttd border 1px solid 0trhover td border1px solid cc3300tractive td backgroundcolor cc3300tdactive color aqua,['css'] +757165,intellij content is not allowed in prolog i run intellij and when i try to run an android app i always have an internal error content is not allowed in prolog i think that i have tried everything to fix it but nothings works before i did nothing special in androidmanifest so i do not know why it is not working errorinternal error orgjdominputjdomparseexception error on line 1 content is not allowed in prologorgjdominputjdomparseexception error on line 1 content is not allowed in prolog at orgjdominputsaxbuilderbuildsaxbuilderjava533 at orgjdominputsaxbuilderbuildsaxbuilderjava946 at comintellijopenapiutiljdomutilloaddocumentjdomutiljava364 at comintellijopenapiutiljdomutilloaddocumentjdomutiljava342 at orgjetbrainsjpsmodelserializationjpsloaderbaseloadrootelementjpsloaderbasejava69 at orgjetbrainsjpsmodelserializationjpsloaderbaseloadrootelementjpsloaderbasejava40 at orgjetbrainsjpsmodelserializationjpsloaderbaseloadcomponentsjpsloaderbasejava52 at orgjetbrainsjpsmodelserializationjpsprojectloaderloadfromdirectoryjpsprojectloaderjava119 at orgjetbrainsjpsmodelserializationjpsprojectloaderloadprojectjpsprojectloaderjava98 at orgjetbrainsjpsmodelserializationimpljpsserializationmanagerimplloadmodeljpsserializationmanagerimpljava41 at orgjetbrainsjpscmdlinejpsmodelloaderimplloadmodeljpsmodelloaderimpljava45 at orgjetbrainsjpscmdlinebuildrunnerloadbuildrunnerjava71 at orgjetbrainsjpscmdlinebuildsessionrunbuildbuildsessionjava198 at orgjetbrainsjpscmdlinebuildsessionrunbuildsessionjava113 at orgjetbrainsjpscmdlinebuildmainmymessagehandler1runbuildmainjava133 at orgjetbrainsjpsserviceimplsharedthreadpoolimpl1runsharedthreadpoolimpljava41 at javautilconcurrentexecutorsrunnableadaptercallexecutorsjava511 at javautilconcurrentfuturetaskrunfuturetaskjava266 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava1142 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava617 at javalangthreadrunthreadjava745caused by orgxmlsaxsaxparseexception linenumber 1 columnnumber 1 content is not allowed in prolog at comsunorgapachexercesinternalutilerrorhandlerwrappercreatesaxparseexceptionerrorhandlerwrapperjava203 at comsunorgapachexercesinternalutilerrorhandlerwrapperfatalerrorerrorhandlerwrapperjava177 at comsunorgapachexercesinternalimplxmlerrorreporterreporterrorxmlerrorreporterjava441 at comsunorgapachexercesinternalimplxmlerrorreporterreporterrorxmlerrorreporterjava368 at comsunorgapachexercesinternalimplxmlscannerreportfatalerrorxmlscannerjava1436 at comsunorgapachexercesinternalimplxmldocumentscannerimplprologdrivernextxmldocumentscannerimpljava9 at comsunorgapachexercesinternalimplxmldocumentscannerimplnextxmldocumentscannerimpljava606 at comsunorgapachexercesinternalimplxmlnsdocumentscannerimplnextxmlnsdocumentscannerimpljava117 at comsunorgapachexercesinternalimplxmldocumentfragmentscannerimplscandocumentxmldocumentfragmentscannerimpljava510 at comsunorgapachexercesinternalparsersxml11configurationparsexml11configurationjava848 at comsunorgapachexercesinternalparsersxml11configurationparsexml11configurationjava7 at comsunorgapachexercesinternalparsersxmlparserparsexmlparserjava141 at comsunorgapachexercesinternalparsersabstractsaxparserparseabstractsaxparserjava1213 at comsunorgapachexercesinternaljaxpsaxparserimpljaxpsaxparserparsesaxparserimpljava649 at orgjdominputsaxbuilderbuildsaxbuilderjava518 20 morecaused by orgxmlsaxsaxparseexception linenumber 1 columnnumber 1 content is not allowed in prolog at comsunorgapachexercesinternalutilerrorhandlerwrappercreatesaxparseexceptionerrorhandlerwrapperjava203 at comsunorgapachexercesinternalutilerrorhandlerwrapperfatalerrorerrorhandlerwrapperjava177 at comsunorgapachexercesinternalimplxmlerrorreporterreporterrorxmlerrorreporterjava441 at comsunorgapachexercesinternalimplxmlerrorreporterreporterrorxmlerrorreporterjava368 at comsunorgapachexercesinternalimplxmlscannerreportfatalerrorxmlscannerjava1436 at comsunorgapachexercesinternalimplxmldocumentscannerimplprologdrivernextxmldocumentscannerimpljava9 at comsunorgapachexercesinternalimplxmldocumentscannerimplnextxmldocumentscannerimpljava606 at comsunorgapachexercesinternalimplxmlnsdocumentscannerimplnextxmlnsdocumentscannerimpljava117 at comsunorgapachexercesinternalimplxmldocumentfragmentscannerimplscandocumentxmldocumentfragmentscannerimpljava510 at comsunorgapachexercesinternalparsersxml11configurationparsexml11configurationjava848 at comsunorgapachexercesinternalparsersxml11configurationparsexml11configurationjava7 at comsunorgapachexercesinternalparsersxmlparserparsexmlparserjava141 at comsunorgapachexercesinternalparsersabstractsaxparserparseabstractsaxparserjava1213 at comsunorgapachexercesinternaljaxpsaxparserimpljaxpsaxparserparsesaxparserimpljava649 at orgjdominputsaxbuilderbuildsaxbuilderjava518 at orgjdominputsaxbuilderbuildsaxbuilderjava946 at comintellijopenapiutiljdomutilloaddocumentjdomutiljava364 at comintellijopenapiutiljdomutilloaddocumentjdomutiljava342 at orgjetbrainsjpsmodelserializationjpsloaderbaseloadrootelementjpsloaderbasejava69 at orgjetbrainsjpsmodelserializationjpsloaderbaseloadrootelementjpsloaderbasejava40 at orgjetbrainsjpsmodelserializationjpsloaderbaseloadcomponentsjpsloaderbasejava52 at orgjetbrainsjpsmodelserializationjpsprojectloaderloadfromdirectoryjpsprojectloaderjava119 at orgjetbrainsjpsmodelserializationjpsprojectloaderloadprojectjpsprojectloaderjava98 at orgjetbrainsjpsmodelserializationimpljpsserializationmanagerimplloadmodeljpsserializationmanagerimpljava41 at orgjetbrainsjpscmdlinejpsmodelloaderimplloadmodeljpsmodelloaderimpljava45 at orgjetbrainsjpscmdlinebuildrunnerloadbuildrunnerjava71 at orgjetbrainsjpscmdlinebuildsessionrunbuildbuildsessionjava198 at orgjetbrainsjpscmdlinebuildsessionrunbuildsessionjava113 at orgjetbrainsjpscmdlinebuildmainmymessagehandler1runbuildmainjava133 at orgjetbrainsjpsserviceimplsharedthreadpoolimpl1runsharedthreadpoolimpljava41 at javautilconcurrentexecutorsrunnableadaptercallexecutorsjava511 at javautilconcurrentfuturetaskrunfuturetaskjava266 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava1142 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava617 at javalangthreadrunthreadjava745,"['java', 'android']" +757268,the ngram that is the most frequent one among all the words i came across the following programming interview problemchallengea 1a ngramsan ngram is a sequence of and consecutive characters from a given word for the word pilot there are three 3grams pil ilo and lotfor a given set of words and an ngram lengthyour task is toa write a function that finds the ngram that is the most frequent one among all the wordsa print the result to the standard output stdouta if there are multiple ngrams having the same maximum frequency please print the one that is the smallest lexicographically the first one according to the dictionary sorting ordernote that your function will receive the following argumentsa text a which is a string containing words separated by whitespacesa ngramlength a which is an integer value giving the length of the ngramdata constraintsa the length of the text string will not exceed 250 charactersa all words are alphanumeric they contain only english letters az az and numbers 09efficiency constraintsa your function is expected to print the result in less than 2 secondsexampleinputtext ab a0a bab caoutput angramlength 3explanationfor the input presented above the 3grams sorted by frequency area a with a frequency of 3a aab with a frequency of 2a a0a with a frequency of 1a baa with a frequency of 1if i have only one hour to solve the problem and i chose to use the c language to solve it is it a good idea to implement a hash table to count the frequency of the ngrams with that amount of time because in the c library there is no implementation of a hash tableif yes i was thinking to implement a hash table using separate chaining with ordered linked lists those implementations reduce the time that you have to solve the problemis that the fastest option possiblethank you,['c'] +757400,automated refactoring to add parameter names to method calls i am in the middle of a big refactoringi have dozens of methods which are called via positional parameters now i would like to have them called via named parameters the methods exist in several noninherited classes and have the same name and their signatures differ exampledefinitionspublic class foo public static foo createint count string name public class bar public static bar createstring description bool yesno float factor and the following calls i would like to replace frompublic void createsomeobjects var foo foocreate123 foo var bar barcreatebar true 123topublic void createsomeobjects var foo foocreatecount 123 name foo var bar barcreatedescription bar yesno true factor 123i use visual studio premium 2013 and resharper any ideas how to achieve this i just need a hint no complete solution,['c#'] +757460,check if property is set in core data how can i check if an property is set in an core data objecti load all my core data objects in an directoryvar formquestions questionsand my core data nsmanagementobject isnsmanaged var noticetext stringformquestionsindexpathrownoticetext load withvar fetchrequest nsfetchrequestentityname questionsfetchrequestpredicate nspredicateformat forms currentformformquestions contextexecutefetchrequestfetchrequest error nil as questionsmy property noticetext could be empty or not so when i create my core data object some values could be not set the property is set as optional in core datawhen i now try to proove if there is a value it always brings me an exc bad access ifformquestionsindexpathrownoticetextisempty falsei could set an empty string when i create my core data object but that should be not a good solutionso how can i check if an optinal and not setted value existsthanks in advance,['ios'] +757574,ionic textareas getting too large i have some textareas in a ionicframeworkproject that are nested in a list the textarea is not shown fully a part of it is out of screendiv classlist stylewidth100 label classitem iteminput stylemaxwidth100 span classinputlabeldescriptionspan textarea requiredtextarea labeldivwhat happens is that the width of the textarea is getting too big spanwidthtextareawidth 100if i manually set the textarea width down a little bit it is shown 100i set the maxwidth of it is parent to 100 so it should not get larger but it doeshow can i prevent this behaviour and let the textarea not grow over the screen,['css'] +757655,ngrepeat count within html loop is there anyway to count an item then thisplay it outside of the looptr ngrepeatvalue in values tdvaluetotaltdtrtr tdtotal of all values total tdtri have tried using nginit to no success as i think it is overriding each timetr ngrepeatvalue in values td nginittotal total valuetotalvaluetotaltdtrtr tdtotal of all values total tdtris there anyway of doing it here without making a function in my controller,['javascript'] +757690,clang vs gcc optimization including operator new i have this simple example i was testing against and i noticed that gcc optimizations o3 seems not be as good as clang ones when operator new is involved i was wondering what might be the issue and if it possible to force gcc to produce more optimized code somehowtemplatetypename tt create return new t int main auto result 0 for auto i 0 i 10 i result createint nullptr return resultclang36 o3 s stdc11 testcppsize aout text data bss dec hex filename 1324 616 8 1948 79c aouttime aout real 0m02suser 0m01ssys 0m0sgcc49 o3 s stdc11 testcppsize aout text data bss dec hex filename 1484 624 8 2116 844 aouttime aoutreal 0m0045suser 0m0035ssys 0m09sexample above is just a simple version of the code i have been testing in the beginningbut it still illustrates the difference between gclangi checked the assembly code as well and there is not a huge difference in size but definitely in performance on the other hand maybe clang is doing something which is not allowed,['c++'] +757695,is 10 a valid output from stdgenerate canonical i always thought random numbers would lie between zero and one without 1 ie they are numbers from the halfopen interval 01 the documention on cppreferencecom of stdgenerate canonical confirms thishowever when i run the following programinclude iostreaminclude limitsinclude randomint main stdmt19937 rng stdseed seq sequence0 1 2 3 4 5 6 7 8 9 rngseedsequence rngthiscard12 629143 6 float random stdgenerate canonicalfloat stdnumeric limitsfloatdigitsrng if random 10f stdcout bugn return 0it gives me the following outputbugie it generates me a perfect 1 which causes problems in my mc integration is that valid behavior or is there an error on my side this gives the same output with g 473g stdc11 testc aoutand clang 33clang stdliblibc stdc11 testc aoutif this is correct behavior how can i avoid 1edit 1 g from git seems to suffer from the same problem i am oncommit baf369d7a57fb4d0d5897b02549c3517bb8800fddate mon sep 1 082651 2014 0and compiling with tempprefixbinc stdc11 wlrpathhomecschwantempprefixlib64 testc aout gives the same output ldd yieldslinuxvdsoso1 0x07f39d0d0libstdcso6 homecschwantempprefixlib64libstdcso6 0x07f123d7850libmso6 lib64libmso6 0x0317ea0libgcc sso1 homecschwantempprefixlib64libgcc sso1 0x07f123d54e0libcso6 lib64libcso6 0x0317e60lib64ldlinuxx8664so2 0x0317e20edit 2 i reported the behavior here bugcgiid63176edit 3 the clang team seems to be aware of the problem bugcgiid18767,['c++'] +757717,is there a way to thisable rotation in openlayers 3 i am currently upgrading my openlayers 2 mapview to openlayers 3 i really like the new openlayers client but i wanted to deactivate the ability to rotate the map on mobile devices rotating with 2 fingers but i cannot find any settings for this is this not possible or am i only to dumb to find the settingi am using the current release version 300 of the openlayers javascript client,['javascript'] +757719,models inside tests django 17 issue i am trying to port my project to use django 17 everything is fine except 1 thing models inside tests foldersdjango 17 new migrations run migrate command internally before syncdb was ran that means if a model is not included in migrations it would not be populated to db and also to test db that is exactly what i am experiencing right nowwhat i do isin my apptestsmodelspy i have dummy model class testbaseimagebaseimage passall it does is to inherit from an abstract baseimage modelthen in tests i create instances of that dummy model to test itthe problem is that it does not work any more it is not included in migrations that is obvious as i do not want to keep my test models in a production db running my tests causes db error saying that table does not exist that makes sense as it is not included in migrationsis there any way to make it work with new migrations system i cannot find a way to fix thatcode i useapptestsmodelspyfrom models import baseimageclass testbaseimagebaseimage dummy model just to test baseimage abstract class passappmodelspyclass baseimagemodelsmodel fields class meta abstract truefactoriesclass baseimagefactoryfactorydjangodjangomodelfactory factory class for vessel model factory for baseimage abstract factory trueclass portimagefactorybaseimagefactory factory for portimageexample testdef get model fieldmodel field name returns field instance return model metaget field by namefield name0def test owner fieldself tests owner field field get model fieldbaseimage owner selfassertisinstancefield modelsforeignkey selfassertequalfieldrelto get user model,['python'] +757785,function that returns a function pointer syntax i am having trouble with the following syntax in cfloat funcunsigned idfloat value i understand thatit is a definition of a function called funcfunc accepts one argument of type unsigned called idfunc returns a pointer to a function that looks like float ffloat value but i do not understand why the return value of f the returned function pointer is separated from its argument listalso is funcunsigned id an expression that evaluates to some pointer is this the reason why funcunsigned id workscan someone clarify this syntax step by step,['c'] +757970,swfobject detect flash without the allow to run firefox message i have been using swfobject in one of my projects in order to detect if the enduser has a version of flash installed the problem is with firefox because it shows the message allow to run adobe flash and that is something i want to avoidit is not about showing alternative content to the enduser what i want is to only try to detect flash and if flash is not installed do not show anything but if flash is installed then do not show the allow to run message in firefoxdoes anyone know any way to prevent this from happening with swfobjectnote just by including the next line in the html headerscript typetextjavascript srcswfobjectjsscriptit triggers the allow to run message sif you think there is a better alternative to swfobject in order to solve this and it is a good multipurpose swfhandler tool i am all earsheres an example of the messagethanks,['javascript'] +757997,angular passing scope to nginclude i have a controller that i wrote that i use in multiple places in my app with nginclude and ngrepeat like thisdiv ngrepeatitem in items ngincludeitemhtml ngcontrolleritemcontrollerdivin the controllertemplate i expect the item value to exist and the whole thing is built around this idea now though i need to use the controller in a slightly different way without the ngrepeat but still need to be able to pass in an item i saw nginit and thought it could do what i needed like thisdiv nginititem leftitem ngincludeitemhtml ngcontrolleritemcontrollerdivdiv nginititem rightitem ngincludeitemhtml ngcontrolleritemcontrollerdivbut that does not seem to be working anyone have any ideas how i can pass in a variable for scope in a singular instance like thiseditthe controller above this is loading in the leftitem and rightitem values something like thiscontrollermaincontroller functionscope itemmodel itemmodelloaditems thenfunctionitems scopeapplyfunction scopeleftitem itemsleft scoperightitem itemsright,['javascript'] +758107,thisable internet access for jvm i would like to know if there is a way to tell the jvm that it cannot connect to any web resource for a certain java program or to immediately fail when doing so ie to do a software equivalent of turning off internet access with a hardware switch this is to assist an automated test thisabling the systems firewall is no option for me background i am currently working on a java issue where xml identity transformation does not work with a doctype referenced in xml like this xml version10 encodingutf8doctype svg public w3cdtd svg 11en svg version11 xmlns xmlnsxlink x0px y0px width32px height32px viewbox0 0 32 32 enablebackgroundnew 0 0 32 32 xmlspacepreserve content svgthe standard behavior of documentbuilderfactory transformerfactory etc is to access the web for the missing entities while the fix suggested a nullentityresolver resolved most of my problems i would like to test this functionality for regression in an automated way in an offline environment,['java'] +758143,release audiorecord android when other app request for recording i have an audio recording service in my app which will record the sound continuously so it will always occupy the audiorecord it means no other app can use audio recorder as it is already occupied by the service is there any way to notify that other app is requesting for audio recorderso that i can release it and also when the app releases itso that i can assign it back to the service,['android'] +758160,springboot logging with log4j2 i am using springbootstarter and would like to configure log4j2xml to log asynchron different content to different logfilesi created the log4j2 file but spring still uses the springboot default logging how can i switch the logging,['java'] +758195,how to read words from identity card using tesseract ocr i am working information reading from identity card information using tesseract libraryi got confidence score of each word or each linebox0 x13 y12 w1134 h57 confidence 40 text repuyblique francaisebox1 x21 y75 w19 h50 confidence 42 text 7 nn99 3w f 59wbox2 x17 y137 w539 h52 confidence 30 text v7 7 d5 nom1bohelbox3 x6 y189 w954 h46 confidence 0 text box4 x12 y239 w1016 h34 confidence 40 text 5 q hv2 h christianl nicble hbnioijebox5 x21 y310 w975 h53 confidence 67 text 2 e 20 06 1329box6 x28 y372 w1043 h83 confidence 0 text box7 x11 y397 w1147 h67 confidence 0 text box8 x251 y461 w837 h46 confidence 0 text box9 x157 y475 w1019 h105 confidence 0 text box10 x59 y648 w1045 h32 confidence 81 text idfradouel932013box11 x57 y722 w1047 h34 confidence 76 text 0506932020438christianeni2906209f3here is code usedpix image pixreadusrsrctesseract302phototesttif tesseracttessbaseapi api new tesseracttessbaseapi apiinitnull eng apisetimageimage boxa boxes apigetcomponentimagestesseractril textline true null null printffound d textline image componentsn boxesn for int i 0 i boxesn i box box boxagetboxboxes i l clone apisetrectangleboxx boxy boxw boxh char ocrresult apigetutf8text int conf apimeantextconf fprintfstdout boxd xd yd wd hd confidence d text s i boxx boxy boxw boxh conf ocrresult now i need to read all the words from identity cardbut i set the value tesseractril textline as tesseractril word and ran the code i got high confidence value even words there not in image1is confidence score used to read information from identity card1what is actually confidence score returned from tesseract ocr,['ios'] +758266,ios 8 auto cell height cannot scroll to last row i am using ios 8 new selfsizing cells visually it works good each cell gets its right size however if i try to scroll to the last row the table view does not seem to know its right size is this a bug or is there a fix for thatheres how to recreate the problemusing this project tableviewcellwithautolayoutios8 referenced from this so answer i got the autoresizing cells as expected however if i am calling the scrolltorowatindexpath function like thistableviewscrolltorowatindexpathnsindexpathforrow modeldataarraycount 1 insection 0 atscrollposition bottom animated truei do not get to the last row it only gets me around halfway there even by trying to use a lower level function like thistableviewsetcontentoffsetcgpointmake0 tableviewcontentsizeheight tableviewframesizeheight animated truethe result is not as expected it would not get to the end if i click it a lot of times or wait a few moments eventually it will get to the right place it seems the tableviewcontentsizeheight is not set correctly so the ios does not know where that last cell iswould appreciate any helpthanks,['ios'] +758356,why does adding a nullable default constraint to an existing column take so long i have an existing table with approximately 400 million rows that table includes a set of bit columns named ismodified isdeleted and isexpiredcreate table dboactivityaccumulator activityaccumulator sk int identity11 not null activityaccumulatorpk1 int null userpk1 int null data varchar510 null coursepk1 int null timestamp datetime null sessionid int null status varchar50 null eventtype varchar40 null dwcreated datetime null dwmodified datetime null ismodified bit null dwdeleted datetime null isdeleted bit null activityaccumulatorkey bigint null contentpk1 bigint null on primaryi would like to add a default constraint to the table that for all future inserted rows will default those bit columns to 0 i am trying to do this via the following commandalter table activityaccumulator add constraint df activityaccumulatorisexpired default 0 for isexpiredalter table activityaccumulator add constraint df activityaccumulatorisdeleted default 0 for isdeletedalter table activityaccumulator add constraint df activityaccumulatorismodified default 0 for ismodifiedi would eventually like to go back and clean up the existing data to put the zero value in wherever there are null values but i do not really need to do so right now just trying to run the first add constraint command has been executing for over an hour now given that i am not trying to change any existing values why is this taking so long,['sql'] +758360,debug ionic app on ios my html5 app is packaged by ionic using cordova and loads onto my iphone like a normal appcan i debug whilst connected to the device i know with android you have logcat and in the browser i have dev tools but there are differences between the app on device and the browser and i want to know whyany help appreciatedthanks,"['ios', 'iphone']" +758400,how do i view the fxml using scenebuilder sorry for such a simple question but i am finding it hard to believe that i cannot actually view the fxml whilst developing a user interface using javafx scenebuilderi would expect that i should be able to write a user interface using the controls as well as being able to directly write the fxmlhow do i viewedit the fxml of my user interface in scenebuilder without doing the following savingediting with text editorreopen with javafx scene builderie as above i would like to be able to work on either the fxml or the wysiwyg front end,['java'] +758482,move textfield when keyboard appears swift i am using swift for program with ios and i use this code for move the textfield but does not work i call correctly the function keyboardwillshow but the textfield does not move i am using autolayoutoverride func viewdidload superviewdidloadnsnotificationcenterdefaultcenteraddobserverself selector selectorkeyboardwillshow nameuikeyboardwillshownotification object nilnsnotificationcenterdefaultcenteraddobserverself selector selectorkeyboardwillhide nameuikeyboardwillhidenotification object nildeinit nsnotificationcenterdefaultcenterremoveobserverselffunc keyboardwillshownotification nsnotification if let keyboardsize notificationuserinfouikeyboardframebeginuserinfokey as nsvaluecgrectvalue let contentinsets uiedgeinsetstop 0 left 0 bottom keyboardsizeheight right 0 var frame selfchatfieldframe frameoriginy frameoriginy keyboardsizeheight 167 selfchatfieldframe frame printlnasdasd,['ios'] +758502,ios 8 custom keyboard crash when debugging issue most times when i try to debug my custom keyboard extension i receive the following error and then the keyboard thisappears presumably crashes so the system removes it from screen and replaces it with the standard keyboard plugin comdbtrypetrypekeyboard interruptednote trype is the name of my keyboardprocessi am debugging the keyboard the following way i have the keyboard extension as a target i have modified the trypekeyboard scheme to run my app executable on launch the keyboard has been added in the simulators settings app i have tried different version of xcodebeta and tried restarting the simulator computer etc all to a varying degree of temporary success anyone else run into this error and have a suggestionupdatehere is an accompanying error message maybe there is some way to print out more of the userinfo viewservicedidterminatewitherror error domain uiviewserviceinterfaceerrordomain code3 the operation couldnat be completed uiviewserviceinterfaceerrordomain error 3 userinfo0x7fc99c900a50 messageservice connection interrupted,['ios'] +758538,constructors difference between defaulting and delegating a parameter today i stumbled upon these standard declarations of stdvector constructors until c14explicit vector const allocator alloc allocator since c14vector vector allocator explicit vector const allocator alloc this change can be seen in most of standard containers a slightly different exemple is stdset until c14explicit set const compare comp compare const allocator alloc allocator since c14set set compare explicit set const compare comp const allocator alloc allocator what is the difference between the two patterns and what are their thisadvantages are they strictly equivalent does the compiler generate something similar to the second from the first,['c++'] +758546,how to thisplay a reverseordered list in html i need you quick help is there any way in cscss to show reverse ordered list something like this 5 i am a list item 4 i am a list item 3 i am a list item 2 i am a list item 1 i am a list item,"['html', 'css']" +758577,toggle iconbar color change on hover using bootstrap i am trying to make the iconbar class change color when you hover over it i got the toggle button to change color and the iconbar usingnavbarpreheader navbartoggle border 1px solid white backgroundcolor transparent marginright 0navbarpreheader navbartogglehover backgroundcolor 4d4d4dnavbarpreheader navbartoggle iconbar backgroundcolor whitethe hover code i used wasnavbarpreheader navbartoggle iconbarhover backgroundcolor 4d4d4dbut this is basically making each iconbar change color individually see below but they should all change color at once i am sure it is something silly i am missing but any help is much appreciated thank you,['css'] +758657,can an aar include transitive dependencies so right now i have a library project say project foo that depends on a library like okhttp now the foo has a maven buildstep that generates an aar and pushes it up to a public placeso now lets say i have project b well call it bar bar is an android application and bar depends on foowell i have that however when i make a call to a public static function in foo from bar that calls okhttp i get this messagejavalangnoclassdeffounderror comsquareupokhttpokurlfactory at comfoosdkutilsokhttpstackinitokhttpstackjava15so is such a thing possible or will bar need to manually depend on okhttp as well as any other dependencies foo has,['android'] +758674,replace all occurrences of a string in a pandas dataframe python i have a pandas dataframe with about 20 columnsit is possible to replace all occurrences of a string here a newline by manually writing all column namesdfcolumnname1 dfcolumnname1strreplacenbrdfcolumnname2 dfcolumnname2strreplacenbrdfcolumnname3 dfcolumnname3strreplacenbrdfcolumnname20 dfcolumnname20strreplacenbrthis unfortunately does not workdf dfreplacenbris there any other more elegant solution,['python'] +758714,where is the isempty referencemember in this xaml code i cannot understand where the isempty comes from in this snippet of code pathtextisempty about a watermark textboxgrid gridrow0 backgroundstaticresource brushwatermarkbackground stylestaticresource entryfieldstyle textblock margin52 texttype to search foregroundgray visibilitybinding elementnameentry pathtextisempty converterstaticresource booleantovisibilityconverter textbox nameentry backgroundtransparentgridyou can see a string does not have any isempty property a dependencyproperty also does not have any isempty member i have even tried searching the isempty in the object browser window but there was not any relevant result explaining the codecould you explain to me the isempty reference here any reference link about it is greatthank you,"['c#', '.net']" +758745,crashlytics found an invalid api key when i am trying to build project with value of metadata tag as a string reference crashlytics fail with following errorcrashlytics found an invalid api key stringcrashlytics check the crashlytics plugin to make sure that the application has been added successfully contact for assistancedoes not workmetadata androidnamecomcrashlyticsapikey androidvaluestringcrashlyticsworksmetadata androidnamecomcrashlyticsapikey androidvalue1234567890i am want to define different keys inside stringxml for different productflavors of my android projectupdateafter writing to crashlytics supportcurrently we only are able to evaluate the androidmanifestxml at build time so we do not look at any strings resources so we only support a hard coded string i will definitely share this with the team that youre interested so we can look into supporting this in a future release,['android'] +758752,how to repeat local notifications every day at different times i am working on a prayers application that enables users to set an alarmlocal notification for prayer times ie the user sets the application to notify him for fajr prayer every day the problem is that the time for each prayer changes daily so the time the app will notify the user for fair in thursday will differ from the time in friday i need to repeat the local notification every day but according to the daily prayer time please could anyone give me an idea,"['ios', 'objective-c']" +758813,can c net be used for hard realtime given that the familiar form of net is run on windows which is not a realtime os and mono runs on linux standard kernel is also not a realtime osgiven also that any memory allocation scheme offering garbage collection as in managed net and indeed any heap memory scheme will introduce nondeterministic potentially nontrivial delays into an applications execution behavioris there any combination of alternate host os and coding paradigm in which one can leverage all of the power and conveniences of c net while implementing a solution which can execute designated portions of code within tightly specified time constraints eg start a c method every 10ms to a tolerance of less than 1ms with completion time determined only by the work performed in the method itselfobviously the application would have to be carefully written timecritical code would have to avoid memory allocations the application would have to have completed all its memory allocation etc work and have no other threads active once the hard realtime loop is started also the host os would have to support realtime schedulingis this possible within the net mono framework or is it precluded by the design of the net runtime framework and oss on which it or compatible equivalent is supportedfor example is it possible to do reliable finegrained 1ms machine control purely in c with something like netduino or do they have limits or require alternate strategies for such applications,"['c#', '.net']" +758827,iam policy for s3 folder access based on cognito id i have created an iam policy to allow cognito users to write to my s3 bucket but i would like to restrict them to folders based on their cognito id i have followed amazons instructions here and created a policy that looks like this effect allow action s3putobjects3getobject resource arnawss3mybucketmyappfoldercognitoidentityamazonawscomsub but when i try to upload using the v2 of the aws ios sdk i get an access denied error if i modify the last path component of the resource to replace cognitoidentityamazonawscomsub with the explicit identityid value i am getting from the sdks awscognitocredentialsprovider it works effect allow action s3putobjects3getobject resource arnawss3mybucketmyappfolderuseast1x my understanding was that these should equate to the same thing am i missing something in my policy or should i be using a different path in my upload request update i originally had this problem in ios so tonight i tried doing the same thing in nodejs and the result is identical here is the simple code i am using in nodevar s3 new awss3awsconfigregion useast1awsconfigcredentials new awscognitoidentitycredentialsawsparamsawsconfigcredentialsgetfunction err if err consolelogcognito identity id awsconfigcredentialsidentityid var bucketname ch123 test bucket var keyname awsconfigcredentialsidentityid txt var params bucket bucketname key keyname body hello world s3putobjectparams function err data if err consolelogerr else consolelogsuccessfully uploaded data to bucketname keyname and i get the same results that i get with ios unless i supply an explicit cognito id in the iam policy the api responds with 403i have stripped my iam policy down to the very bare minimum this does not work statement effect allow action s3putobjects3getobject resource arnawss3ch123 test bucketcognitoidentityamazonawscomsub this doesstatement effect allow action s3putobjects3getobject resource arnawss3ch123 test bucketuseast168a5dc496cc742898257d3d5636f7034 i do not see what i am missing herethe only documentation i have been able to find always shows the same example resource value that i have been using,['ios'] +759039,exclude soft deleted items in self referential relationship sqlalchemy i currently have a self referential relationship on the fooparent id dbcolumndbinteger dbforeignkeyfooidparent dbrelation foo remote sideid backrefdbbackref children primaryjoinand foocidfoocparent id foocis deletedfalse now i am trying to exclude any children with is deleted set as true i am pretty sure the problem is it is checking is deleted against the parent but i have no idea where to go from herehow to modify the relationship so that children with is deleted are not included in the result set,"['python', 'sql']" +759087,pip install requests exception and pip install beautifulsoup4 exception i have installed python 341 on windows 7 pip included and during install have selected add pythonexe to pathwhen running pip install requests i get cpython34pip install requestsrequirement already satisfied use upgrade to upgrade requests in cpython34libsitepackagescleaning up exceptiontraceback most recent call last file cpython34libshutilpy line 370 in rmtree unsafe osunlinkfullnamepermissionerror winerror 5 access is denied cusersuserappdatalocaltemppip build userpippip vendorthistlibw32exeduring handling of the above exception another exception occurredtraceback most recent call last file cpython34libsitepackagespipbasecommandpy line 122 in main status selfrunoptions args file cpython34libsitepackagespipcommandsinstallpy line 302 in run requirement setcleanup filesbundleselfbundle file cpython34libsitepackagespipreqpy line 13 in cleanup files rmtreedir file cpython34libsitepackagespiputilpy line 43 in rmtree onerrorrmtree errorhandler file cpython34libshutilpy line 477 in rmtree return rmtree unsafepath onerror file cpython34libshutilpy line 367 in rmtree unsafe rmtree unsafefullname onerror file cpython34libshutilpy line 367 in rmtree unsafe rmtree unsafefullname onerror file cpython34libshutilpy line 367 in rmtree unsafe rmtree unsafefullname onerror file cpython34libshutilpy line 367 in rmtree unsafe rmtree unsafefullname onerror file cpython34libshutilpy line 372 in rmtree unsafe onerrorosunlink fullname sysexc info file cpython34libsitepackagespiputilpy line 53 in rmtree errorhandler exctype is permissionerror and valueargs3 5 python33indexerror tuple index out of range storing debug log for failure in cusersuserpippiplogwhen running pip install beautifulsoup4 i get cpython34pip install beautifulsoup4downloadingunpacking beautifulsoup4 running setuppy pathcusersuserappdatalocaltemppip build userbeautifulsoup4setuppy egg info for package beautifulsoup4installing collected packages beautifulsoup4 running setuppy install for beautifulsoup4 skipping implicit fixer buffer skipping implicit fixer idioms skipping implicit fixer set literal skipping implicit fixer ws commasuccessfully installed beautifulsoup4cleaning up exceptiontraceback most recent call last file cpython34libshutilpy line 370 in rmtree unsafe osunlinkfullnamepermissionerror winerror 5 access is denied cusersuserappdatalocaltemppip build userpippip vendorthistlibw32exeduring handling of the above exception another exception occurredtraceback most recent call last file cpython34libsitepackagespipbasecommandpy line 122 in main status selfrunoptions args file cpython34libsitepackagespipcommandsinstallpy line 302 in run requirement setcleanup filesbundleselfbundle file cpython34libsitepackagespipreqpy line 13 in cleanup files rmtreedir file cpython34libsitepackagespiputilpy line 43 in rmtree onerrorrmtree errorhandler file cpython34libshutilpy line 477 in rmtree return rmtree unsafepath onerror file cpython34libshutilpy line 367 in rmtree unsafe rmtree unsafefullname onerror file cpython34libshutilpy line 367 in rmtree unsafe rmtree unsafefullname onerror file cpython34libshutilpy line 367 in rmtree unsafe rmtree unsafefullname onerror file cpython34libshutilpy line 367 in rmtree unsafe rmtree unsafefullname onerror file cpython34libshutilpy line 372 in rmtree unsafe onerrorosunlink fullname sysexc info file cpython34libsitepackagespiputilpy line 53 in rmtree errorhandler exctype is permissionerror and valueargs3 5 python33indexerror tuple index out of range storing debug log for failure in cusersuserpippiplogcpython34i am wondering what those exceptions meanhave the packages really successfully installed like given in the log and will they run fine or am i doing something wrongwhy the exceptions and how do i get rid of them,['python'] +759199,swarm app android actionbar what is the element that is used for swarm android apps actionbar i think it is neither the native android actionbar nor actionbarsherlock,['android'] +759240,xcode ios file not found i have an ios application that i am trying to add ocmock to in order to better unit test it i have followed the instruction on ocmockorg as well as instructions i have found in other places but still i cannot get my test code to compile heres what i have doneadded the source code to my project directorycreate the groups in my project to mimic my file systemi selected the option to add to my test targets so the framework was added appropriately as well as the library search paththen i manually added the headers to the header search pathand added the objc linker flag then when i go to import the header file i get the file not found errorany ideas what i am missing here,['ios'] +759277,why is gcc tricked into allowing undefined behavior simply by putting it in a loop the following is nonsensical yet compiles cleanly with g wall wextra werror winitself i tested gcc 472 and 490include iostreaminclude stringint main for int ii 0 ii 1 ii const stdstring str str stdcout str stdendl the line marked results in undefined behavior yet is not diagnosed by gcc however commenting out the for line makes gcc complainerror astra is used uninitialized in this function werroruninitializedi would like to know why is gcc so easily fooled here when the code is not in a loop gcc knows that it is wrong but put the same code in a simple loop and gcc does not understand anymore this bothers me because we rely quite a lot on the compiler to notify us when we make silly mistakes in c yet it fails for a seemingly trivial casebonus triviaif you change stdstring to int and turn on optimization gcc will diagnose the error even with the loopif you build the broken code with o3 gcc literally calls the ostream insert function with a null pointer for the string argument if you thought you were safe from null references if you did not do any unsafe casting think againi have filed a gcc bug for this bugcgiid63203 i would still like to get a better understanding here of what went wrong and how it may impact the reliability of similar diagnostics,['c++'] +759305,android alpha testing item not found i have published my app for alpha testing but not able to download it from play store i have opened the url and accepted to be a tester and now it shows me you are a tester but when i click on the link download it from the play store it shows me item not found in my test device play store and requested url was not found in desktop browserapp is in published state for more than 48 hoursapp is published in all countriesgoogle groups for testers are added i can see the group in manage testers tab tester account is added to the group triple checked ittest device has only one tester accounti can access the inapp purchases which means the app is published properly google does not support draft mode anymorei went through some similar posts in stackoverflow but there is no definite answer looks like for some people it resolved automatically and some people are not lucky enough,['android'] +759337,how to solve javalangoutofmemoryerror trouble in android altough i have very small size image in drawable folder i am getting this error from users and i am not using any bitmap function in code at least intentionally javalangoutofmemoryerror at androidgraphicsbitmapfactorynativedecodeassetnative method at androidgraphicsbitmapfactorydecodestreambitmapfactoryjava683 at androidgraphicsbitmapfactorydecoderesourcestreambitmapfactoryjava513 at androidgraphicsdrawabledrawablecreatefromresourcestreamdrawablejava889 at androidcontentresresourcesloaddrawableresourcesjava3436 at androidcontentresresourcesgetdrawableresourcesjava1909 at androidviewviewsetbackgroundresourceviewjava16251 at comautkusoytasbilbackalimsoruekranicevapsecimisoruekranijava6 at comautkusoytasbilbackalimsoruekrani91runsoruekranijava862 at androidoshandlerhandlecallbackhandlerjava733 at androidoshandlerthispatchmessagehandlerjava95 at androidoslooperlooplooperjava146 at androidappactivitythreadmainactivitythreadjava5602 at javalangreflectmethodinvokenativenative method at javalangreflectmethodinvokemethodjava515 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava1283 at comandroidinternaloszygoteinitmainzygoteinitjava1099 at dalviksystemnativestartmainnative methodaccording to this stacktrace i am gettin this error at this line tv is a textviewtvsetbackgroundresourcerdrawableyanliswhat is the problem if you need some other information about code i can add itthanks,['android'] +759400,is it possible to create custom jquery selectors that navigate ancestors eg a closest or parents selector i write a lot of jquery plugins and have custom jquery selectors i use all the time like focusable and closeto to provide commonly used filters eg focusable looks like thisjqueryextendjqueryexpr focusable function el index selector return elisa button inputtypehidden tabindex and is used like any other selectorfocusablecsscolor red color all focusable elements redi notice none of the jquery selectors available can navigate back up ancestors i gather that is because they were designed to follow the basic css selector rules which drill downtake this example which finds the label for an input that has focusinputfocusclosestformgroupfindlabeli need the equivalent type of complex selectors for plugins so it would be useful to provide such a selector as a single string so they can be provided as options to the plugineg something likeinputfocus formgroup labelor inputfocusclosestformgroup labelnote please assume more complex operations and that ancestor navigation is required i realize this particular example can be done with has but that does not helpeg it also needs to support thisoptionsselector closestformgroup labelinputclickfunction var label thisfindoptionsselectoris it possible to extend jquery selectors to extend search behavior and not just add more boolean filters how do you extend custom search behaviorupdateit appears a complete custom selector like would not be as easy as adding a pseudo selector to jquerys sizzle parser i am currently looking at this sizzle documentation but i am finding inconsistencies with the jquery version eg no sizzleselectorsorder property exists at runtimefor reference jquery stores sizzle on its jqueryfind property and sizzleselectors on its jqueryexpr propertyso far i have added this jqueryexprmatchclosest closest jqueryexprfindclosest function match context isxml consolelogjqueryexprfindclosest and call it with a simple test but it never gets to the consolelog statement and i still get syntax error unrecognized expression unsupported pseudo closest on tracing inside jquery it is trying to apply it as a filter instead of a find so i am missing some key partupdate 2the processing for selectors works righttoleft see extract from jquery 1 below so if the last argument does not existing in the context it aborts early this means navigating upwards will not occur with the current jquery sizzle code in the common case where we want to look for an element in another dom branch of an ancestor fetch a seed set for righttoleft matchingi matchexprneedscontexttestselector 0 tokenslengthwhile i token tokensi abort if we hit a combinator if exprrelativetype tokentype break if find exprfindtype search expanding context for leading sibling combinators if seed find tokenmatches0replacerunescape funescape rsiblingtesttokens0type testcontextcontextparentnode context if seed is empty or no tokens remain we can return early tokenssplicei 1 selector seedlength toselectortokens if selector pushapplyresults seed return results break i was surprised to see this but realise now that it made the rule engine much easier to write it does mean however we need to make sure the righthand end of a selector is as specific as possible as that is evaluated first everything that happens after that is just progressive pruning of the result set i had always assumed the first items in the selector had to be more specific to increase efficiency,"['javascript', 'jquery']" +759414,is c linkage smart enough to avoid linkage of unused libs i am far from fully understanding how the c linker works and i have a specific question about itsay i have the followingutilshnamespace utils void func1 void func2utilscppinclude some huge lib needed only by func2namespace utils void func1 do something void func2 make use of some functions defined in some huge lib maincppint main utilsfunc1my goal is to generate as smaller binary files as possiblemy question is will some huge lib be included in the output object file,['c++'] +759493,template class with a single method specialized in c i only have an hpp file for a school assignment in c i am not allowed to add a cpp file declaration and implementation should be both written in the filei wrote this code inside ittemplateclass tclass matrix void foo do something for a t variable i would like to add another foo method but this foo will be specialized for only an inti have read in some places that i need to declare a new specialization class for this to work but what i want is that the specialized foo will lie just beneath the original foo so it will look like thistemplateclass tclass matrix void foot x do something for a t variable template void foointint x do something for an int variable why am i getting an error for this syntax expected unqualifiedid before tokenwhy is not this possiblehow can i fix this without declaring a new specialized classthanks,['c++'] +759543,laravel 42 generates new csrf token depending of requests frequecy i have encountered strange behavior of csrf token in laravel 42 token was changing between requests not always but randomlyfirst thought was that i had problems with garbage collection or there was some bug in laravel and even more this happens only on remote server and locally everything is ok however server settings and session config is the samegarbage collection in phpini is turned off the only gc that works is the one started by cron every 30 minutes however that also does not relate to this problem i have checked1 if i send ajax requests not frequently eg one time every second it works during hours without problems2 when i send ajax requests very often during small period of time 20 times during 35 seconds the token is changed after 15th or 20th request sometimes even on the 10this there some hidden functionality i did not found that however that changes token if it looks like dangerous requests checking frequency,['php'] +759577,javas fluentwait in python in java seleniumwebdriver package there is a fluentwait classeach fluentwait instance defines the maximum amount of time to wait for a condition as well as the frequency with which to check the condition furthermore the user may configure the wait to ignore specific types of exceptions whilst waiting such as nosuchelementexceptions when searching for an element on the pagein other words it is something more than implicit and explicit wait gives you more control for waiting for an element it can be very handy and definitely has use cases is there anything similar in python selenium package or should i implement it myselfi have looked through documentation for waits nothing there,"['java', 'python']" +759590,jquery updating a script to support touchscreens scrollview i have been using the jquery scroll view the script does not appear to support touchscreens so i have spent the better part of a day trying to figure out how i might add touchscreen support to the scripti considered switching over to jquery draggable but it just does not work in the same way that the above script seems to workcould someone give me some pointers or tips on how to add touch support to this,['jquery'] +759682,bug in weakaction in case of closure action in one of the projects i take part in there is a vast use of weakaction that is a class that allows to keep reference to an action instance without causing its target not be garbage collected the way it works is simple it takes an action on the constructor and keeps a weak reference to the actions target and to the method but thiscards the reference to the action itself when the time comes to execute the action it checks if the target is still alive and if so invokes the method on the targetit all works well except for one case when the action is instantiated in a closure consider the following examplepublic class a weakaction action null private void registerstring msg action new weakaction messageboxshowmsg since the lambda expression is using the msg local variable the c compiler auto generates a nested class to hold all the closure variables the target of the action is an instance of the nested class instead of the instance of a the action passed to the weakaction constructor is not referenced once the constructor is done and so the garbage collector can thispose of it instantly later if the weakaction is executed it will not work because the target is not alive anymore even though the original instance of a is alivenow i cannot change the way the weakaction is called since it is in wide use but i can change its implementation i was thinking about trying to find a way to get access to the instance of a and to force the instance of the nested class to remain alive while the instance of a is still alive but i do not know how to do get itthere are a lot of questions about what a has to do with anything and suggestions to change the way a creates a weak action which we cannot do so here is a clarificationan instance of class a wants an instance of class b to notify it when something happens so it provides a callback using an action object a is not aware that b uses weak actions it simply provides an action to serve as callback the fact that b uses weakaction is an implementation detail that is not exposed b needs to store this action and use it when needed but b may live much longer then a and holding a strong reference to a normal action which by itself holds a strong reference of the instance of a that generated it causes a to never be garbage collected if a is a part of a list of items that are no longer alive we expect a to be garbage collected and because of the reference that b holds of the action which by itself points to a we have a memory leakso instead of b holding an action that a provided b wraps it into a weakaction and stores the weak action only when the time comes to call it b only does so if theweakaction is still alive which it should be as long as a is still alive a creates that action inside a method and does not keep a reference to it on his own that is a given since the action was constructed in the context of a specific instance of a that instance is the target of a and when a dies all weak references to it become null so b knows not to call it and thisposes of the weakaction object but sometimes the method that generated the action uses variables defined locally in that function in which case the context in which the action runs include not just the instance of a but also the state of the local variables inside of the method that is called a closure the c compiler does that by creating a hidden nested class to hold these variables lets call it a closure and the instance that becomes the target of the action is an instance of a closure not of a this is something that the user should not be aware of except that this instance of a closure is only referenced by the action object and since we create a weak reference to the target and do not hold a reference to the action there is no reference to the a closure instance and the garbage collector may and usually does thispose of it instantly so a lives a closure dies and despite the fact that a is still expecting the callback to be invoked b can not do itthat is the bug my question was if somebody knows of a way that the weakaction constructor the only piece of code that actually holds the original action object temporarily can in some magic way extract the original instance of a from the a closure instance that it finds in the target of the action if so i could perhaps extend a closure life cycle to match that of a,['c#'] +759693,how to get only images in the camera roll using photos framework the following code loads images that are also located on icloud or the streams images how can we limit the search to only images in the camera rollvar assets phassetfetchassetswithmediatypephassetmediatypeimage options nil,['ios'] +759842,chrome extension error unchecked runtimelasterror while running browseractionseticon no tab with id i am coding my google chrome extension where i set the apps icon from the background script as suchtry objicon 19 imagesicon19png 38 imagesicon38png chromebrowseractionseticon path objicon tabid ntabid catchenote that i wrapped the call in trycatch blockstill sometimes i am getting the following message in the console logunchecked runtimelasterror while running browseractionseticon no tab with id 11618it is hard to debug this error because it seems to come up only when i close or reload the chrome tab it does not have a line number or any info for me to track plus it is not easy to run through a debugger ie i cannot set a breakpoint on the moment when error occurs but if i blindly set a breakpoint on the chromebrowseractionseticon line i do not see the message in the log anymoreso i am curious if anyone could suggest how to remedy this erroredit just to post an update i am still unable to resolve this issue the suggestion proposed by abraham below offers a somewhat working approach but it is not fail safe for instance in a situation when the tab is closing i may call his suggested chromebrowseractionseticon that may succeed if the tab is not yet closed but while within its callback function the tab may eventually close and thus any consecutive calls to some other api that requires that same tab id say setbadgebackgroundcolor may still give me that same no tab with id exception in other words for those who know native programming this is a classic race condition situation and i am not sure if it is a bug in chrome because obviously js does not offer any thread synchronization methodsi have witnessed this behavior several times while doing my tests it does not happen often because were talking about very precise timing situation but it does happen so if anyone finds a solution please post it below,['javascript'] +759886,how to localise a string inside the ios infoplist file as you might know the ios 8 requires nslocationwheninuseusagedescription key for using users location i have added this key and some general information into my info plist how can i use translation string inside the plist file update i already have a localizable string i am just wondering that can i use something like nslocalizedstringmystringnil inside the plist string i know that i can create multiple file of infoplist for localisation but i was wondering there might be an easier way,['ios'] +759972,how to create refresh token with external login provider i have searched over the web and could not find a solution to my problem i am implementing oauth in my app i am using asp net web api 2 and owin the scenario is this once a user request to the token end point he or she will receive an access token along with a refresh token to generate a new access token i have a class the helps me to generate a refresh token here is it public class simplerefreshtokenprovider iauthenticationtokenprovider private static concurrentdictionarystring authenticationticket refreshtokens new concurrentdictionarystring authenticationticket public async task createasyncauthenticationtokencreatecontext context var refreshtokenid guidnewguidtostringn using authrepository repo new authrepository var refreshtokenlifetime contextowincontextgetstring asclientrefreshtokenlifetime var token new refreshtoken id helpergethashrefreshtokenid clientid clientid subject contextticketidentityname issuedutc datetimeutcnow expiresutc datetimeutcnowaddminutes15 contextticketpropertiesissuedutc tokenissuedutc contextticketpropertiesexpiresutc tokenexpiresutc tokenprotectedticket contextserializeticket var result await repoaddrefreshtokentoken if result contextsettokenrefreshtokenid this method will be used to generate access token using the refresh token public async task receiveasyncauthenticationtokenreceivecontext context string hashedtokenid helpergethashcontexttoken using authrepository repo new authrepository var refreshtoken await repofindrefreshtokenhashedtokenid if refreshtoken null get protectedticket from refreshtoken class contextdeserializeticketrefreshtokenprotectedticket one refresh token per user and client var result await reporemoverefreshtokenhashedtokenid public void createauthenticationtokencreatecontext context throw new notimplementedexception public void receiveauthenticationtokenreceivecontext context throw new notimplementedexception now i am allowing my users to register through facebook once a user register with facebook i generate an access token and give it to him should i generate a refresh token as well onething comes to my mind is to generate a long access token like one day then this user has to login with facebook again but if i do not want to do that i can give the client a refresh token and he can use it to refresh the generated access token and get a new how do i create the refresh token and attach it to the response when someone register or login with facebook or externally here is my external registration api public class accountcontroller apicontroller allowanonymous routeregisterexternal public async taskihttpactionresult registerexternalregisterexternalbindingmodel model if modelstateisvalid return badrequestmodelstate var accesstokenresponse generatelocalaccesstokenresponsemodelusername return okaccesstokenresponse private method to generate access token private jobject generatelocalaccesstokenresponsestring username var tokenexpiration timespanfromdays1 claimsidentity identity new claimsidentityoauthdefaultsauthenticationtype identityaddclaimnew claimclaimtypesname username identityaddclaimnew claimrole user var props new authenticationproperties issuedutc datetimeutcnow expiresutc datetimeutcnowaddtokenexpiration var ticket new authenticationticketidentity props var accesstoken startupoauthbeareroptionsaccesstokenformatprotectticket jobject tokenresponse new jobject new jpropertyusername username new jpropertyaccess token accesstoken here is what i need new jpropertyresfresh token getrefreshtoken new jpropertytoken type bearer new jpropertyrefresh tokenrefreshtoken new jpropertyexpires in tokenexpirationtotalsecondstostring new jpropertyissued ticketpropertiesissuedutctostring new jpropertyexpires ticketpropertiesexpiresutctostring return tokenresponse,['asp.net'] +760315,how to find pairs with product greater than sum supposing that we have a array c with all element in c 0a pair of indices a b is multiplicative if 0 a a b n and ca cb a ca cbwith the timecomplexity is o and expected worstcase time complexity is oni appreciate your help in supporting this casethanks,['java'] +760401,set background image and icon image in iphone 6 and 6 plus how can i differentiate the background images and icon images between the different resolutions for the iphone 5 and for the iphone 6 and 6 plus,['ios'] +760468,too many symbol files after successfully submitting my apps i downloaded xcode 6 gm and submitted two swift apps to the app store today both passed all preupload verification and all the other stuff they had to pass and were successfully submitted but then i got two emails from apple one for each program and they both said thisdear developerwe have thiscovered one or more issues with your recent delivery for x my app name removed your delivery was successful but you may wish to correct the following issues in your next delivery too many symbol files these symbols have no corresponding slice in any binary 1431d972bc308fab7171529f25400bsymbols 158c72a798ac3f07b2be88427591b413symbols 44973eac563e340cb54955a5014a68basymbols 678bf06f0c3d3a09bfbf699c7079fecdsymbols 90907ddb040038edbb5f0c123c0624symbols 93b799495757374a97b9825ae1a61b7dsymbols aba052204fb0397fafbb08774a82f4casymbols ad70f02a442232b88c40cf9b45a2c6symbols b0cc9f7dc5423e18a518b28b7ecabe80symbols bf6a4c3b6fa53c51840419c2f132458dsymbols c9d6e0788e2a39d98dee476916a69ceesymbols cf5320dfab313845bad5f6e51045d396symbols d4967aa38fb03712b0de7f4144af8f4bsymbols d813b314ad3731d4b675442052994495symbols df42a13f08d83e71b221fc357e0b60f5symbols f5f636c2f0e03ca78f7dc49a36cd5c65symbols after youave corrected the issues you can use xcode or application loader to upload a new binary to itunes connect regardsthe app store teami am going to guess that really has nothing to do with me or my apps and it is just a quirk of day one swift app submissions both apps are still sitting in waiting for approval mode i certainly cannot think of anything i could change to make what they said go away anyone else submit a swift app yet and get that response think i should just ignore it and wait to see what happens,['ios'] +760591,how to add a private cocoapod as a dependency in another pod podspec file i am working on a private pod and that is dependent on other private pod so i just want to mention it in my pod podspec fileits looks like this in podspec file of pod2sdependency pod1 001 git companypod1git commit 9f9f4fe5b5959e0f2ea89e472eccf7aea6f37eeaand i came to know that there is no git and commit options in podspec dependency specifier so if not then how to achieve that thing,"['ios', 'objective-c', 'iphone']" +760712,image effects with rotation and pinch to zoom using glsurfaceview android i was developing an application to apply effectsrotationpinch to zoom inout functionality on image i have downloaded demo application from it works well now my problemsquestions are as belowapply multiple effects on images with progress change value eg first apply brightness effect and result of this apply another effect say contrast problem in code effect always apply on original image so change in code to apply effect on final image likeifisapplyeffectonoriginalimagecall first time only meffectapplymtextures0 mimagewidth mimageheight mtextures1else meffectapplymtextures1 mimagewidth mimageheight mtextures1now if apply brightness effect on progress change first time it works fine but if i apply the same or othercontrast effect now i think on progress change effect apply on mtextures1 and result set in mtextures1 so is it possible to create temporary mtextures2 to store mtextures1 initially and when user change the progress value apply effect on mtextures2 and set result on mtextures1 like happen in if conditionhow to apply pinch to zoom on imagesrotation issue i was rotating image at 90 angle clockwise just by setting values90180270 etc but the problem is when rotating image from 90 to 180 image rendering is not properlysee a 0 angle image b 90 angle imagec 180 angle image,['android'] +760743,why cannot i refer to a column alias in the order by using case sorry if this a duplicate but i have not found one why cannot i use my column alias defined in the select from the order by when i use caseconsider this simple queryselect newvaluecase when value is null then nullvalue else value endfrom dbotableaorder by case when newvaluenullvalue then 1 else 0 endthe result is an error invalid column name newvalueheres a sqlfiddle replace the order by newvalue with the case when thata s commented outi know i can use order by case when value is null then 1 else 0 end like here in this case but actually the query is more complex and i want to keep it as readable as possible do i have to use a subquery or cte instead if so why is that soupdate as mikael eriksson has commented any expression in combination with an alias is not allowed so even this pointless query fails for the same reasonselect as emptyfrom dbotableaorder by empty resultinvalid column name emptyso an alias is allowed in an order by and also an expression but not both why is it too difficult to implement since i am mainly a programmer i think of aliases as variables which could simple be used in an expression,['sql'] +760844,emplacing a stdpair is there a way of emplacing a stdpairstdunordered mapint stdpairstdstring stdstring my mapmy mapemplace1 foo bar errorof course inserting is possiblemy map2 stdmake pairbar foobut does not this require unnecessary copyingmoving,['c++'] +760867,how to consume web api in xamarin crossplatform application i have created web api that retrieves data from sql database i need to consume web api in xamrin for android and xamarin for ios as of now xamarin for android i am not sure how to call get and post method based on button click eventhere is web apiusing systemusing systemcollectionsgenericusing systemlinqusing systemnetusing systemnethttpusing systemwebhttpnamespace mvcappdeptcontrollerspublic class deptcontroller apicontroller get apivalues public ienumerabledept get androidappdbentities db new androidappdbentities var data from dept in dbdepts orderby deptno select dept return datatolist get apivalues5 public dept getint id androidappdbentities db new androidappdbentities var data from dept in dbdepts where deptno id select dept return datasingleordefault post apivalues public void postdept obj androidappdbentities db new androidappdbentities dbdeptsaddobj dbsavechanges put apivalues5 public void putint iddept obj androidappdbentities db new androidappdbentities var data from dept in dbdepts where deptno id select dept dept old datasingleordefault oldno objno oldname objname dbsavechanges delete apivalues5 public void deleteint id androidappdbentities db new androidappdbentities var data from dept in dbdepts where deptno id select dept dept obj datasingleordefault dbdeptsremoveobj dbsavechanges globalasaxcsusing systemusing systemcollectionsgenericusing systemlinqusing systemwebusing systemwebhttpusing systemwebmvcusing systemweboptimizationusing systemwebrouting namespace mvcappdeptpublic class webapiapplication systemwebhttpapplication protected void application start arearegistrationregisterallareas webapiconfigregisterglobalconfigurationconfiguration filterconfigregisterglobalfiltersglobalfiltersfilters routeconfigregisterroutesroutetableroutes bundleconfigregisterbundlesbundletablebundles globalconfigurationconfigurationformattersxmlformattersupportedmediatypesclear mainactivitycsusing systemusing systemnethttpusing systemthreadingtasksusing androidappusing androidcontentusing androidruntimeusing androidviewsusing androidwidgetusing androidosnamespace deptandroidapp activitylabel deptandroidapp mainlauncher true icon drawableicon public class mainactivity activity protected override void oncreatebundle bundle baseoncreatebundle setcontentviewresourcelayoutmain button getbutton findviewbyidbuttonresourceidgetbutton var txtvalue1 findviewbyidedittextresourceidtxtvalue1 int id converttoint32txtvalue1text var no findviewbyidtextviewresourceidno var name findviewbyidtextviewresourceidname getbuttonclick getdeptid getbuttonclickasyncsenderargs error cannot await deptandroidappdept dept deptawait getdeptid notextdeptno nametextdeptname error the return type ofasync method must be voidtask ortaskt public async dept getdeptint id using var client new httpclient clientbaseaddress new urihttp clientdefaultrequestheadersacceptclear clientdefaultrequestheadersacceptaddnew systemnethttpheadersmediatypewithqualityheadervalueapplicationjson var result await clientgetasyncstringformatapidept0id return jsonconvertdeserializeobjectdeptawait resultcontentreadasstringasync,['android'] +760953,how can i insert 10 million records in the shortest time possible i have a file which has 10 million records like below line1 line2 line3 line4 10 million linesso basically i want to insert 10 million records into the databaseso i read the file and upload it to sql serverc codesystemiostreamreader file new systemiostreamreaderctesttxtwhileline filereadline null insertion code goes here dalexecutesqlinsert into table1 valueslinefileclosebut insertion will take a long timehow can i insert 10 million records in the shortest time possible using cupdate 1bulk insertbulk insert dbnamedbodatasfrom fdt10dt10txtwith rowterminator n my table is like belowdatas datasfield varcharmaxbut i am getting following errormsg 4866 level 16 state 1 line 1 the bulk load failed the column is too long in the data file for row 1 column 1 verify that the field terminator and row terminator are specified correctly msg 7399 level 16 state 1 line 1 the ole db provider bulk for linked server null reported an error the provider did not give any information about the errormsg 7330 level 16 state 2 line 1 cannot fetch a row from ole db provider bulk for linked server nullbelow code workedbulk insert dbnamedbodatasfrom fdt10dt10txtwith fieldterminator t rowterminator n,['c#'] +760976,java why does it work differently with english and slavic characters i have found a rather strange thing for me while working with java maybe it is an ordinary thing but i do not understand why it works this wayi have a code like thischaracter x bobject o xsystemoutprintlno bit works fine and the output is truethen i change the english b to slavic b character x object o xsystemoutprintlno now the output is false how comeby the way the output is still true if i compare the x variable with directly but when i do it through an object it works differentlycan anyone please explain this behaviour,['java'] +761111,thread safety in android libraries i am trying to implement a native shared libraryso for the android system naturally there are some code blocks that need to be threadsafe i found out here that pthreads locks mutexes or condition variables are not supported i would like to know what is usually used at the library level to achieve threadsafety,['android'] +761376,visual studio express 2013 program output in unit tests console debug etc i am really banging my head against the wall here is it so hard to get program output in visual studio express 2013 when writing code i find it absolutely essential to be able to print out the values of variables operations etc while working and troubleshooting in java and eclipse the systemoutprintln allways works printing to the ide console when writing c programs i allways use the console so echoing anything is no problem however in vs express 2013 i cannot seem to get any outputcan the problem be related to the fact that i am writing unit tests and not normal executable programs if so is there some way to get vs to show program output in unit test classes i have tried using debug but that does not show anything either thinking that there is a config problem i have looked for solutions to debug messages not showing but none of the options i have found in here or other places seem to helpor of course if there is another commonly used method for checking program values output etc while writing code in vsc i would like to hear about it anyone got any ideas and please if the question is too unclear or something tell me and i will fix itnb i am using unit test classes for functional testing in case someone wants to point out what i should and and should not do with unit testsedit 1 i forgot to mention that i am not able to run the code with start debug if i try i get this error a project with an output type of class library cannot be started directly the unit test project uses classes in another project which i a class library project this is of course because i have no executable project in the solution the way i run it is to run the selected test from the test exploreredit 2 codeusing systemusing systemdiagnosticsusing microsoftvisualstudiotesttoolsunittestingusing wordpressautomationnamespace wordpresstests testclass public class logintests wordpresstest testmethod public void adminusercanlogin systemdiagnosticsdebugwritelinesomething systemdiagnosticstracewritelinesomething,['c#'] +761417,question mark syntax from coffeescript without coffeescript coffeescript has such syntax sugaritemgetfoofooparambarwhich translates into long javascript equivalent with getfoonull and fooparamnull checks the question is are there any ways to use this syntax in vanilla javascript with a librarytranslatorcompiler other than coffeescript we use traceur in our project but it does not have such syntax because it is not es6 compliant although i wish it to maybe some way to implement it within traceur fork,['javascript'] +761463,how to remove dashed line from html context to draw a dashed line in a canvas context i use this var canvas documentgetelementbyidcanv ctx canvasgetcontext2d ctxsetlinedash5when i do not want to draw more dashed lines i do this ctxsetlinedash0removing the dashs works in desktop browsers but this is not working in mobile safari is there another way to remove the dashes and draw plain continious solid linesthanks,"['javascript', 'html']" +761532,nsfastenumeration in swift i am trying to convert an objectivec project to swift but i am unable to find how to use nsfastenumeration for an object of a class that conforms to nsfastenumerationhere is the code in objc get the decode resultsidnsfastenumeration results info objectforkey zbarreadercontrollerresultszbarsymbol symbol nilforsymbol in results just grab the first barcode breakso far i tried to find how to do this but this doe not seems work here is the swift codevar results zbarsymbolset infodictionaryobjectforkeyzbarreadercontrollerresults as zbarsymbolset var symbol zbarsymbol nil for symbol in results just grab first barcode break the error comes in for condition zbarsymbolset does not have a member named generatorwhat am i doing wronghere is the screen shot,"['ios', 'objective-c']" +761703,how to check if input file is empty in jquery brand new to jsi am trying to check if the file input element is empty when submitting the form with jqueryjavascripti have gone through a bunch of solutions and nothing is working for me i am trying to avoid the cfakepath unless there is no other optioninput typefile namevideofile idvideouploadfile this does not workvar vidfile videouploadfilevaluethe only way i can get the filename is if i use the followingvar vidfile documentgetelementbyidvideouploadfilefiles0nameif there is no file available the code throws an error cannot read property name of undefinedwhich makes sense because the array is not set but i cannot figure out how to do any error handling with thishow do i properly grab the file input element videouploadfile check if it is empty throw an error message if it is empty,"['javascript', 'jquery', 'html']" +761706,parserparse in swift leads to exc bad access i am following this tutorial as a jump start for an rss feeder app i am working on in swift i know there are some things that have changed in swift since this tutorial but none of them seem to explain why i am having this issuerelevant code as far as i can tell is as follows in my tableviewcontroller override func viewdidload superviewdidload let urlnsurl nsurlstring myurlstring parser nsxmlparsercontentsofurl url parserdelegate self parserparse thread 1 exc bad access code1 address0x0there does not seem to be a problem with the actual parser delegate methods as i put breakpoints on them and they are not even being called before the crashmy assumption is that it is a swift bug but i wanted to make sure i was not missing something before i go complaining to apple about it,['ios'] +761718,xamarin studio build targets trying to get fody working i am trying to get xamarin studio to use propertychangedfody i have fody installed via nuget which puts fodytargets in its nuget packages folder but when i build the output never shows that the target is runhow can i tell xamarin studio to use the fody build targetthanks,['c#'] +761789,black bars on launch screen on iphone5 and iphone6 when iphone 5 first came out we had to go through the silliness of adding a to the project to get the app to use the full height of the iphone 5 in late 2014 are we still doing thatwe have asset catalogs and the launchscreenxib file do we still need to add the file if so where does it go now i have tried a few different things and i cannot get rid of the black bars in a new app created with xcode 6 gm,['ios'] +761839,fileupload with jaxrs i try to do file upload from a javascript client to a jaxrs java serveri use the following rest upload function on my serverpostproducesapplicationjsonuploaddto upload context httpservletrequest request queryparamcookie string cookie def contenttype byte filebytes logdebug upload cookie cookie try if request instanceof multiparthttpservletrequest logdebug request instanceof multiparthttpservletrequest multiparthttpservletrequest myrequest request commonsmultipartfile file commonsmultipartfile myrequestgetfilefile filebytes filebytes contenttype filecontenttype logdebug upload size of the file in byte filesize else if request instanceof securitycontextholderawarerequestwrapper logdebug request instanceof securitycontextholderawarerequestwrapper securitycontextholderawarerequestwrapper myrequest request get uploaded files inputstream inputstream inputstream myrequestinputstream filebytes ioutilstobytearrayinputstream contenttype myrequestgetheadercontenttype logdebug upload size of the file in byte filebytessize else logerror request is not a multiparthttpservletrequest or securitycontextholderawarerequestwrapper println request requestclass catch ioexception e logerrorupload failed to save file error e on the client side i send the file as followsvar str2ab blobreader functionstr callback var blob blobbuilder windowmozblobbuilder windowwebkitblobbuilder windowblobbuilder if typeof blobbuilder undefined var bb new blobbuilder bbappendstr blob bbgetblob else blob new blob str var f new filereader fonload functione callbacketargetresult freadasarraybufferblobvar filename filenamejpgvar contenttype imagejpegif filetypetostringtolowercaseindexofpng 1 filename filenamepng contenttype imagepngvar xhrnativeobject new xmlhttprequestvar urlparams test123xhrnativeobjectopenpost url urlparams truexhrnativeobjectsetrequestheadercontenttype contenttypexhrnativeobjectonload functionevent var targetresponse eventcurrenttarget if targetresponsereadystate 4 targetresponsestatus 200 var obj jsonparsetargetresponseresponsetext consolelogobjuploadimageid else consolelogfail var buffer str2ab blobreaderfile functionbuf xhrnativeobjectsendbufwhen i use the code in my grails controller it worked well but when i use it in a rest resource i always get request is not a multiparthttpservletrequest or securitycontextholderawarerequestwrapperthe log output isrequest comsunproxyproxy58the send a file blob from javascript i use xmlhttprequest which contains the blob in the body and some query parametershow can i make jaxrs file upload working how do i receive some additional query params with my post request,['java'] +761857,capture ios simulator video for app preview okay so we can now submit video previews of our apps on the app store according to apple we should do so with an ios8 device and osx 1010 the problem is you have to have all the different devices 4 47 55 and ipad is there an alternative to thisi am thinking of capturing a video of the simulator the problem is the device screen is bigger than my fullhd monitor when shown in 100 resolution any solution that can capture a video right from the simulator in full resolutioneditsince a lot of people are answering questions i am not asking let me say recording one device size and scaling it is not what i am asking how to record any app preview is not what i am asking how you do your previews is not what i am askingwhat i am asking is can you record a video from the simulator in 100 resolution if it does not fit on the screen,['ios'] +761858,running nodeinspector alongside nodemon i am currently using node along with nodemon then i got to thinking it might be sometimes nice to use an inspector with node so have started using nodeinspectorhowever is it possible to run both at the same timenormally to run nodemon i would use nodemon serverjsand similarly nodedebug serverjsi have also triednodemon debug httpjsbut sadly this did not work eitherbut both together,['javascript'] +762068,karmarunner on ubuntu usrbinenv node no such file or directory error i am trying to set up the javascript code tester karma but when i run the command to initialise karma i get the error usrbinenv node no such file or directory how can i fix it,['javascript'] +762089,windowclose does not work on ios 8 gm seed i am trying to open new tab via javascript using windowopen then using windowclose to close but it seems windowclose does not work in safari ios 8 gm seed here is the code ahtmlbutton onclickwindowopenbhtml return falseopen bbuttonbhtmlbutton onclickwindowcloseclosebuttoni tried several ways like settimeout windowopen then close but does not helpis there any workaround for this situation,"['javascript', 'ios']" +762119,how to quickly check if url server is available i have a url in the formfromstosand want to check if it is availablethe links redirect me on a bad request page if i try to open these with a browser however via code i can get the data that i needusing a trycatch block on a http request procedure is pretty slow so i am wondering how i could ping a similar address to check if its server is activei have triedboolean reachable inetaddressgetbynamemylinkisreachable60but returns always falsei have also triedpublic static boolean existsstring urlname try httpurlconnectionsetfollowredirectsfalse httpurlconnection con httpurlconnection new urlurlnameopenconnection consetconnecttimeout10 consetreadtimeout10 consetrequestmethodhead return congetresponsecode httpurlconnectionhttp ok catch exception e eprintstacktrace return false that returns the correct value at the end of the process bit is too slow if server is not availableediti have understood what is the cause of slownessa if server returns some data but interrupts the request before complete the request the timeout is ignored and stuck until returns an exception that lead the execution to reach the catch block this is the cause of the slowness of this method and still i have not found a valid solution to avoid thisb if i start the android device and open the app without connection the false value is returned correctly if the app is opened with internet connection active and the device lost its internet connection happens the same thing of the case a also if i try to terminate and restart the app i do not know why i suppose that something remains cachedall this seems related to the fact java urlconnection does not provide no failsafe timeout on reads looking at the sample at this link i have seen that uses a thread to interrupt the connection in some way but if i add simply the line new threadnew interruptthreadthreadcurrentthread constart like in the sample nothing changes,"['java', 'android']" +762140,c pure virtual multiple inheritance i need help for an implementation that uses multiple inheritance of interfacesthere is an existing code whith an interface which has a lot of functions the instances are created using a factoryclass ibig lot of pure virtual functionsand his inplementationclass cbig public ibig implementationi want to split the interface in multiple smaller interfaces but it should stay compatible to the existing code for some timehere is a sample of what i tried to doclass ibaseapublic virtual void doa 0class ibasebpublic virtual void dob 0 the same interface now based on multiple smaller interfacesclass ibig public ibasea public ibasebclass cbasea public ibaseapublic virtual void doa printfdoan class cbaseb public ibasebpublic virtual void dob printfdobn inherit from base classes where the implementation is and from ibig as the instance of cbig is returned as ibigclass cbig public cbasea public cbaseb public ibigthe problem here is that the class cbig cannot be instanciated the compiler says the functions doa and dob are pure virtual even if they are inplemented in cbasea and cbaseb what should i do if i do not want to implement again the functions just to call the function of the base class nb i know the design is ugly but this is only temporary until the big interface can be replaced and i want to understand thanks in advance,['c++'] +762220,c string comparison equates to false i have a string comparison issue that for the most part behaves as expected but is leaving me with a large number f duplicate db insertions because my code is not detecting the string pairs as duplicatei thought i had narrowed it down to a culture issue cyrillic characters which i resolved but i am now getting false negatives two apparently equal strings showing up as notequali have looked at the following similar questions and tried the following comparison approachessimilar so questions that i have checkedwhy does my comparison always return falsec string equality operator returns false but im pretty sure it should be true whatstring equals method fails even the two strings are same in cdifferences in string compare methods in cheres an example of the strings being compared title and descriptionfeed title ellsberg he is a herofeed desc daniel ellsberg tells cnns don lemon that nsa leaker edward snowden showed courage has done an enormous servicedb title ellsberg he is a herodb desc daniel ellsberg tells cnns don lemon that nsa leaker edward snowden showed courage has done an enormous servicemy app compares values fetched from rss feeds with values i have in the db and should only insert new valuesfetch existing articles from db for the current feed listarticle thisfeedarticles from ar in entitiesitems where aritemtypeid intenumsitemtypearticle arparentid feedfeedid ardatepublished datelimit select new article title artitle description arblurb tolisteveryone of the below comparison show no match for the ellsberg titledescription ie matches1 to matches6 all have count0please excuse the enumerated variable names they are just for testing comparison methods compareoptions compareoptions compareoptionsordinalignorecasecompareoptions compareoptions2 compareoptionsignoresymbols compareoptionsignorenonspace1ienumerablearticle matches thisfeedarticleswhereb stringcomparebtitletrimnormalize atitletrimnormalize cultureinfoinvariantculture compareoptions 0 stringcomparebdescriptiontrimnormalize adescriptiontrimnormalize cultureinfoinvariantculture compareoptions 0 2ienumerablearticle matches2 thisfeedarticleswhereb stringcomparebtitle atitle cultureinfocurrentculture compareoptions2 0 stringcomparebdescription adescription cultureinfocurrentculture compareoptions2 0 3ienumerablearticle matches3 thisfeedarticleswhereb stringcomparebtitle atitle stringcomparisonordinalignorecase 0 stringcomparebdescription adescription stringcomparisonordinalignorecase 0 4ienumerablearticle matches4 thisfeedarticleswhereb btitleequalsatitle stringcomparisonordinalignorecase bdescriptionequalsadescription stringcomparisonordinalignorecase 5ienumerablearticle matches5 thisfeedarticleswhereb btitletrimequalsatitletrim stringcomparisoninvariantcultureignorecase bdescriptiontrimequalsadescriptiontrim stringcomparisoninvariantcultureignorecase 6ienumerablearticle matches6 thisfeedarticleswhereb btitletrimnormalizeequalsatitletrimnormalize stringcomparisonordinalignorecase bdescriptiontrimnormalizeequalsadescriptiontrimnormalize stringcomparisonordinalignorecase if matchescount 0 matches2count 0 matches3count 0 matches4count 0 matches5count 0 matches6count 0 matches7count 0 insert values this if statement was the first approach if thisfeedarticlesanyb btitle atitle bdescription adescription insert obviously i have only been using one of the above options at a timefor the most part the above options do work and most duplicates are detected but there are still duplicates slipping through the cracks i just need to understand what the cracks are so any suggestions would be most welcomei did even try converting the strings to byte arrays and comparing those deleted that code a while ago sorrythe article object is as follows public class article public string title public string description updatei have tried normalizing the strings as well as including the ignoresymbols compareoption and i am still getting a false negative nonmatch what i am noticing though is that apostrophes seem to make a consistent appearance in the false nonmatches so i am thinking it might be a case of apostrophe vs singlequote ie vs a and the like but surely ignoresymbols should avoid thati found a couple more similar so postsc string comparison ignoring spaces carriage return or line breaksstring comparison invariantcultureignorecase vs ordinalignorecasenext step try using regex to strip white space as per this answer update 2after the 6 comparison still returned no matches i realised that there had to be another factor skewing the results so i tried the following7ienumerablearticle matches7 thisfeedarticleswhereb regexreplacebtitle 09azaz equalsregexreplaceatitle 09azaz stringcomparisoninvariantcultureignorecase regexreplacebdescription 09azaz equalsregexreplaceadescription 09azaz stringcomparisoninvariantcultureignorecase this does find the matches the others missthe string below got through all 6 comparisons but not number 7atitletrimnormalize and atitletrim both returncorrigendum identification of a unique tgfi2adependent molecular and functional signature in microgliavalue in the db iscorrigendum identification of a unique tgfaadependent molecular and functional signature in microgliacloser inspection shows that the german eszett character is different in the db compared to whats coming through from the feed i2 vs ai would have expected at least one of comparisons 16 to pick that upinterestingly after some performance comparisons the regex option is by no means the slowest of the seven normalize appears to quite more intensive than the regular expressionhere are the stopwatch durations for all seven when the thisfeedarticles object contains 12077 items time elapsed 0662 time elapsed 09 time elapsed 09 time elapsed 09 time elapsed 09 time elapsed 09 time elapsed 016,"['c#', '.net']" +762285,listview header ignores layout height i inflate this view and add it to my listview as a header i am trying to make it 500dp high hard coded for the sake of this example xml version10 encodingutf8linearlayout xmlnsandroid androidorientationvertical androidlayout widthmatch parent androidbackgrounddrawablerepeat background androidlayout height500dp imageview androidididfilter menu androidsrcdrawableic sort androidlayout gravitycenter vertical androidpadding8dp androidlayout weight0 androidlayout widthwrap content androidlayout heightwrap content androidonclickshowpopuplinearlayoutthe listview does not respect the authoritah of its header and wraps it on its content can anyone please explain what happens,['android'] +762300,trigger function just before exit i am using dhtmlx scheduler on the front end and dhtmlx connector on the backend as part of my radio automation app every time a user edits the calendar an ajax call is made to a file that looks like thisrequire oncedhtmlxscheduler v4connectorscheduler connectorphprequire onceqdraconfphpres mysql connectqdraconfmysqlhost qdraconfmysqluser qdraconfmysqlpassmysql select dbqdraconfmysqldb init the schedulerconnectorconn new schedulerconnectorres render the tableconnrender tableeventsidstart dateend datetextthis file is my shim that hooks up the fronted to the back end i want to run another php script that writes the changes to my crontab but it needs to happen after the dhtmlx library has updated the database trouble is the dhtmlx library will automatically exit whenever it thinks it is done sometimes it might not get past the first require once line so i cannot just put require oncecronwriterphp at the last line of the scriptmy solution to this was to create a class with a destructor that updates the crontab with the latest changes since the php manual states that destructors will still be run if the exit or die function is called i added a dummy class with a destructor that runs cronwriterphp script i added this to the beginning of the fileclass exitcatcher function destruct require oncecronwriterphp init the classexitcatcher new exitcatcherfor some reason it does not work,['php'] +762304,how to define global variable for twig i am using a file serving as a form layout to overwrite certain elements form start form row etc i register it liketwig acmemainbundleformformlayouthtmltwigis there a way to use in it my veriables provided along with a form for example when i send to indexhtmltwigarray form formview var varvar is defined only in indexhtmltwigso how to make var defined in formlayouthtmltwig,['php'] +762376,opensslsslsslerror ssl connect syscall returned5 errno0 statesslv3 read server hello a the code below yields the following error opensslsslsslerror ssl connect syscall returned5 errno0 statesslv3 read server hello arequire nethttpsuri uriparsehttpsservercomhttp nethttpnewurihost uriporthttpuse ssl truehttpssl version sslv3httpgeturirequest uriany idea why i tried everything mentioned in all other questions still no luckruby 193p484 20131122 revision 43786 x86 64darwin1330openssl 098y 5 feb 2013update itried the followingruby 200p353 20131122 revision 43784 x86 64darwin1330openssl 101i 6 aug 2014update iiforced ssl version to tlsv1 2still no luckupdate ialright heres the final code thanks to steffen see answer belowrequire nethttpsuri uriparsehttpsservercomhttp nethttpnewurihost uriporthttpuse ssl truehttpssl version tlsv1httpciphers rc4shahttpgeturirequest urii doubt that my question will be relevant to anyone else since it was related to a remote misconfigured server,"['ruby-on-rails', 'ruby']" +762393,storyboard how do i let xcode automatically update frames when i change layout constraints i have seen a wwdc 2014 video whats new in interface builder where the presenter uses storyboard and changes the height of a table view cell prototype within a table view controller at around 7m30s i see all the subviews of that cell resize as he drags the heighthandle on the cell this is great because now you can see how your layout constraints behave in different scenarios very quicklyhe does not explain how he does it because when i drag the heighthandle of a table view cell prototype the frames of all my subviews do not update they only update when i select from the menu editor resolve auto layout issues update frames all views in table view controlleris there an xcode setting anywhere that toggles liveupdating the view frames i see in storyboard obeying the layout constraints,['ios'] +762508,unable to run app in simulator xcode 60 after migrating from xcode 50 to xcode 60 the project fails to run with the following erroran error was encountered while running domain fbsopenapplicationerrordomaincode 4any suggestions,['ios'] +762511,swift trying to link a tap event on a table view cell to a controller method i am new to swift and havnet programmed in objective c so i am new trying to do something fairly simple link a table view cell click to call a method in the controller like soediti have these methods in my mastercontroller override func tableviewtableview uitableview numberofrowsinsection section int int override func tableviewtableview uitableview cellforrowatindexpath indexpath nsindexpath uitableviewcell override func tableviewtableview uitableview caneditrowatindexpath indexpath nsindexpath bool override func tableviewtableview uitableview commiteditingstyle editingstyle uitableviewcelleditingstyle forrowatindexpath indexpath nsindexpath override func tableviewtableview uitableview didselectrowatindexpath indexpath nsindexpath i have added breakpoints in all 4 of themand when clicking on the cell it does not stop in either of themsee screen shot,['ios'] +762521,android how to use a wifi network for specific hosts but have phone use mobile network for everything else i am developing a mobile application ios and android to control a device over wifi the device creates a wireless network softap but does not provide access to the interneton ios i can connect to the device and make requests to its ip address 192168701 but all other requests fall back to the mobile network this allows the phone to maintain internet connectivity while connected to the device over wifion android if i connect to the device wireless network internet requests do not fall back to the mobile connection they just failin my android app i can use connectivitymanagerrequestroutetohost to force requests from my app to use the mobile network however requests made by other apps still use the device wifi network and faili have also tried to use the connectivitymanager to change the network preference with connectivitymanagersetnetworkpreferenceconnectivitymanagertype mobilethis causes the phone to use the mobile network for all requests from all applications wifi is thisabled it seems that in previous versions of android wifi could still be used even if it is not the preferred network but this does not seem to work in kitkat it is possibly related to a change in android 42 connectivitymanager since 42 tears down networks that are not the networkpreferenceis there a solution that allows an android app to use wifi for a specific ip address and the mobile network for everything else maybe this can be done via the ndk,['android'] +762579,what is css scrollbehavior property i have recently noticed a scrollbehavior property that i can specify in my css it can take only 2 properties inherit and initial i have never heardseen it before so i tried to look at it the problem is that all the links are going into explaining different things about overflow propertythen i tried to test it div idscroll div idinsidedivscroll width 100px height 500px scrollbehavior inherit overflow auto border 2px solid blackinside height 10pxthe problem is that i see no difference so what does it do,"['html', 'css']" +762581,undefined symbols for architecture x86 64 ios swift i am working on a project with the swift programming language and i am trying to use some code from some older objectivec projects i have created the bridge file and imported the headers that i need but i get the following error which i know it has to do with linking some framework but even when i added coregraphics as an added framework it still appears any ideasundefined symbols for architecture x86 64 cgpointmake referenced from cgpointadd in skactioneffects669e235bd7235d6aold symbols not found for architecture x86 64clang error linker command failed with exit code 1 use v to see invocationthanksupdate setting the basesdk did not do the trick this is what my build settings are like with xcode6,"['ios', 'objective-c']" +762650,incorrect image rendered with glide library i am using the glide library in my android project to fetch and thisplay imagesearlier i was using version 205 and facing rendering issue the problem was that the wrong images were rendering i have updated library to 33 version and it now crashes with the following exception 14sep2014 084131 pm javalangillegalargumentexception you cannot start a load for a destroyed activity at combumptechglidemanagerrequestmanagerretrievergetrequestmanagerretrieverjava63 at combumptechglidemanagerrequestmanagerretrievergetrequestmanagerretrieverjava29 at combumptechglideglidewithglidejava537 at commiamiheatcommonmhimagedownloadwrapperloadimagemhimagedownloadwrapperjava12 at commiamiheatuimodulemhwallpapermodulesetwallpaperviewdatamhwallpapermodulejava234 at commiamiheatuimodulemhwallpapermoduletaskmanagerresponsecallbackmhwallpapermodulejava257 at commiamiheatservicetaskmanagermhwallpapertaskmanagerasyncresultcallbackmhwallpapertaskmanagerjava133 at commiamiheatserviceframeworkmhasyncservicetaskonpostexecutemhasyncservicetaskjava191 at androidosasynctaskfinishasynctaskjava631 at androidosasynctaskaccess600asynctaskjava177 at androidosasynctaskinternalhandlerhandlemessageasynctaskjava644 at androidoshandlerthispatchmessagehandlerjava99 at androidoslooperlooplooperjava176 at androidappactivitythreadmainactivitythreadjava5419 at javalangreflectmethodinvokenativenative method at javalangreflectmethodinvokemethodjava525 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava1046 at comandroidinternaloszygoteinitmainzygoteinitjava862 at dalviksystemnativestartmainnative methodis there anyway to cancel the image download request on activity destroy,['android'] +762681,access the settingsbundle from todayextension in the app i can choose in the settings which language of three should be used if nothing is selected the iphone language is detected and selected for english french or german if none of this languages is the iphone language english is set to be used manually changing the language in the settings works as it should now i added a todayextension which works nearly well but i need to access the settingsbundle to get the nsuserdefaults for the languages if manually changed in both targets i activated the appgroups withgroupcomcompanynameappnameand selected itin the app i get the language with nsstring manuallanguageset nsuserdefaults standarduserdefaults valueforkeysprachwahland in the todayextension i try to get it bynsstring manuallanguageset nsuserdefaults alloc initwithsuitenamegroupcomcompanynameappname valueforkeysprachwahlfor nslogsettingssprache manuallanguageset when running the todayextension the result is does not matter if and which language is selected in the settings20140913 164836331 hdb today3734284836 settingssprache nullwhat can i do it correct how can i access to the settings settingsbundle,['ios'] +762831,chartjs with angularjs canvas would not thisplay anything i am trying to use the angularchartjs library but running into some issues there are no errors on the page but the canvas is empty anyone has an ideai have tried reordering the scripts a few times i just cannot figure it out here is the htmlhtml ngaprofitly head script srcjslibjqueryminjsscript script srcjslibchartjsscript script srcjslibangularminjsscript script srcjslibangularrouteminjsscript script srcjslibangularchartjsminjsscript script srcjscontrollerjsscript head body ngcontrollermaincontroller classcontainerfluid div classwrapper ngview article ngcontrollergraph cjsdoughnut datasetsomedata optionssomeoptions segmentstrokewidth5cjsdoughnut article div bodyhtmland here is the app initialization var app angularmoduleprofitly ngroute chartjsand here is the controller for this partappcontrollergraph functionscope scopesomedata labels supply may jun datasets data 1 7 15 19 31 40 data 6 12 18 24 30 36 scopesomeoptions segmentstrokewidth 20 segmentstrokecolor 0,['javascript'] +762879,getting shufflejs and filtering to work i am stumped got the masonry part set up but cannot understand why filtering does not work i have been through the script compared to the one on the demo site and i am going nutsi am using and bootstrap 3 this probably has nothing to do with bootstrapdemo wedit demo html contains all dependencies jquery 191 or higher modernizr etchtmldiv classcontainer div classfilteroptions button classbtn btndefault datagroupwallpaperwallpapersbutton button classbtn btndefault datagroupgraphicsgraphic designbutton button classbtn btndefault datagroupphotographyphotosbutton button classbtn btndefault datagroup3d3d rendersbutton div div idgrid classrow div classcolxs6 colsm4 colmd3 datagroupsphotography img src alt classimgresponsive div div classcolxs6 colsm4 colmd3 datagroupsgraphics img src alt classimgresponsive div div classcolxs6 colsm4 colmd3 datagroupsphotography img src alt classimgresponsive div div classcolxs6 colsm4 colmd3 datagroupsphotography img src alt classimgresponsive div div classcolxs6 colsm4 colmd3 datagroupsphotography img src alt classimgresponsive div div classcolxs6 colsm4 colmd3 datagroups3d img src alt classimgresponsive div div classcolxs6 colsm4 colmd3 datagroupsphotography img src alt classimgresponsive div div classcolxs6 colsm4 colmd3 datagroups3d img src alt classimgresponsive div div classcolxs6 colsm4 colmd3 datagroups3d img src alt classimgresponsive div div classcolxs6 colsm4 colmd3 datagroups3d img src alt classimgresponsive div div classcolxs6 colsm4 colmd3 datagroupsgraphics img src alt classimgresponsive div div classcolxs6 colsm4 colmd3 datagroupsgraphics img src alt classimgresponsive div div classcolxs6 colsm4 colmd3 datagroupsgraphics img src alt classimgresponsive div div classcolxs6 colsm4 colmd3 datagroupsgraphics img src alt classimgresponsive div div classcolxs6 colsm4 colmd3 datagroupsgraphics img src alt classimgresponsive div div classcolxs6 colsm4 colmd3 datagroupsgraphics img src alt classimgresponsive div div classcolxs6 colsm4 colmd3 datagroupsgraphics img src alt classimgresponsive div div classcolxs6 colsm4 colmd3 datagroupsgraphics img src alt classimgresponsive div div classcolxs6 colsm4 colmd3 datagroupsgraphics img src alt classimgresponsive div div classcolxs6 colsm4 colmd3 datagroupsgraphics img src alt classimgresponsive div sizer div classcolxs6 colsm4 colmd3 shuffle sizerdiv div grid div container jqueryvar shuffleme function use strict var grid grid filteroptions filteroptions sizer gridfindshuffle sizer init function none of these need to be executed synchronously settimeoutfunction listen setupfilters 100 instantiate the plugin gridshuffle itemselector classcol sizer sizer set up button clicks setupfilters function var btns filteroptionschildren btnsonclick function var this this isactive thishasclass active group isactive all thisdatagroup hide current label show current label in title if isactive filteroptions activeremoveclassactive thistoggleclassactive filter elements gridshuffle shuffle group btns null re layout shuffle when images load this is only needed below 768 pixels because the pictureitem height is auto and therefore the height of the pictureitem is dependent on the image i recommend using imagesloaded to determine when an image is loaded but that does not support ie7 listen function var debouncedlayout throttle 300 function gridshuffleupdate get all images inside shuffle gridfindimgeachfunction var proxyimage image already loaded if thiscomplete thisnaturalwidth undefined return if none of the checks above matched simulate loading on detached element proxyimage new image proxyimage onload function thisoffload debouncedlayout proxyimagesrc thissrc because this method does not seem to be perfect settimeoutfunction debouncedlayout 500 return init init jquery documentreadyfunction shufflemeinitcssgrid marginleft5pxmarginright5pxpositionrelative overflow hiddengrid classcol padding5pxmedia maxwidth320px grid classcol width100shuffle sizer position absolute opacity 0 visibility hidden,['jquery'] +763206,xcode 6 pchfile not found i load my project from xcode 5 to xcode 6 and see error myprojectprefixpch is not found in myprojecttests i add this file and see new errorld userswillrocklibrarydeveloperxcodederiveddata34 n12n i extreme fitnesscdfxpafcwvsczkfjvlwznradvmhmbuildproductsdebugiphonesimulator34 n12n i extreme fitnesstestsxctest34 n12n i extreme fitnesstests normal x86 64cd userswillrockdesktopextremefitnessexport iphoneos deployment target71export pathapplicationsxcodeappcontentsdeveloperplatformsiphonesimulatorplatformdeveloperusrbinapplicationsxcodeappcontentsdeveloperusrbinusrbinbinusrsbinsbinapplicationsxcodeappcontentsdevelopertoolchainsxcodedefaultxctoolchainusrbinclang arch x86 64 bundle isysroot applicationsxcodeappcontentsdeveloperplatformsiphonesimulatorplatformdevelopersdksiphonesimulator80sdk luserswillrocklibrarydeveloperxcodederiveddata34 n12n i extreme fitnesscdfxpafcwvsczkfjvlwznradvmhmbuildproductsdebugiphonesimulator fuserswillrocklibrarydeveloperxcodederiveddata34 n12n i extreme fitnesscdfxpafcwvsczkfjvlwznradvmhmbuildproductsdebugiphonesimulator fapplicationsxcodeappcontentsdeveloperplatformsiphonesimulatorplatformdevelopersdksiphonesimulator80sdkdeveloperlibraryframeworks fapplicationsxcodeappcontentsdeveloperlibraryframeworks fapplicationsxcodeappcontentsdeveloperplatformsiphonesimulatorplatformdeveloperlibraryframeworks fapplicationsxcodeappcontentsdeveloperplatformsiphonesimulatorplatformdevelopersdksiphonesimulator80sdkdeveloperlibraryframeworks filelist userswillrocklibrarydeveloperxcodederiveddata34 n12n i extreme fitnesscdfxpafcwvsczkfjvlwznradvmhmbuildintermediates34 n12n i extreme fitnessbuilddebugiphonesimulator34 n12n i extreme fitnesstestsbuildobjectsnormalx86 6434 n12n i extreme fitnesstestslinkfilelist bundle loader userswillrocklibrarydeveloperxcodederiveddata34 n12n i extreme fitnesscdfxpafcwvsczkfjvlwznradvmhmbuildproductsdebugiphonesimulatorextreme fitnessappextreme fitness xlinker objc abi version xlinker 2 framework xctest fobjcarc fobjclinkruntime xlinker no implicit dylibs miossimulatorversionmin71 framework xctest framework uikit framework foundation xlinker dependency info xlinker userswillrocklibrarydeveloperxcodederiveddata34 n12n i extreme fitnesscdfxpafcwvsczkfjvlwznradvmhmbuildintermediates34 n12n i extreme fitnessbuilddebugiphonesimulator34 n12n i extreme fitnesstestsbuildobjectsnormalx86 6434 n12n i extreme fitnesstests dependency infodat o userswillrocklibrarydeveloperxcodederiveddata34 n12n i extreme fitnesscdfxpafcwvsczkfjvlwznradvmhmbuildproductsdebugiphonesimulator34 n12n i extreme fitnesstestsxctest34 n12n i extreme fitnesstestsld file not found userswillrocklibrarydeveloperxcodederiveddata34 n12n i extreme fitnesscdfxpafcwvsczkfjvlwznradvmhmbuildproductsdebugiphonesimulatorextreme fitnessappextreme fitnessclang error linker command failed with exit code 1 use v to see invocationif i load project see in xctestclang error no such file or directory userswillrockdesktopextremefitnessextreme fitnessextreme fitnessprefixpchclang error no input filescommand applicationsxcodeappcontentsdevelopertoolchainsxcodedefaultxctoolchainusrbinclang failed with exit code 1but in xcode 5 is work fine,['objective-c'] +763254,bluebird promises join behaviour if i execute the following code with nodejsvar promise requirebluebirdpromisejoin function a consoleloga function b consolelogb done function done consolelogdonethe console will logbdonehowever i would expectabdoneorbadoneif it set a break point in function a it is never reached why is it that it processes b but not a,['javascript'] +763336,onclick event not running on first button click in mithril why does the click callback not invoked the first time after some text is entered into the input like in this fiddlevar app appcontroller function thisdata mprop thisclick function alertbutton clicked appview functionctrl return mhtml mbody mdiv mp ctrldata minputtypetext onchange mwithattrvalue ctrldata mbutton onclick ctrlclick click mmoduledocument app,['javascript'] +763459,should i use stdfunction or a function pointer in c when implementing a callback function in c should i still use the cstyle function pointervoid callbackfuncintor should i make use of stdfunctionstdfunction voidint callbackfunc,['c++'] +763500,css blur in ie 11 i have been trying to get a css blur effect in ie 11 for hours and did not make any progress i tried to use the following simple html doctype htmlhtml head style typetextcss blur msfilterprogiddximagetransformmicrosoftblurpixelradius50 style head body img src cb20120627075127kirbyenimages001kdcol kirby k64png classblur bodyhtmli also tried just using the filter without the ms prefix i saw that filter code on and even consulted the microsoft example which does not work in my ie 11 on win7 do you have any ideas what i could be doint wrongprobably interesting if you are struggling too svgfiltereffectshtm,['css'] +763524,auth with unirest java i need to execute a request to a web app that execute a patch process i am giving to this request the parameters it is requesting me but i do not know how to pass the credentials from a login request i am executing before the patch requesti am trying to get the cookie data from the headers of the login response and giving it to the patch request as a simple string but i am not sure if it is the right way to do itbasically what i am doing is thishttpresponsejsonnode respuesta unirestposturllogin headersheaders fieldsfields asjsonjsonobject body respuestagetbodygetobjectheaders headerbody respuestagetheadersstring tmp headerbodygetsetcookieget0thiscookie sdtouchmodefalse concattmpreplacepathhttponlymapstringstring cabeceras new hashmapstring stringcabeceraputcookie thiscookiehttpresponsejsonnode respuesta unirestposturlfixpack headersheaders fieldsfields asjsoni am not comfortable with the way i am getting and setting the cookie data but i am not finding in the documentation any proper way to do itcan anybody help me pleasethanks,['java'] +763631,opening a postgres connection in psycopg2 causes python to crash i am getting the following error message when i try to open up a connection to a postgres database perhaps it is related to openssl but i cannot understand the error message can anyone help import psycopg2 conn psycopg2connecthost port dbname user password auto configuration failed12848error02001015system libraryfopenis a directorycryptobiobss filec169fopendbuildopensslopenssl101hvc9x64sslopensslcnfrb12848error2006d002bio routinesbio new filesystem libcryptobiobss filec17412848error0e078002configuration file routinesdef loadsystem libcryptoconfconf defc199,['python'] +763643,frameloader fetching extra ua string uaprofurl i will be using my app loading html pages into the webview and sometimes the webview seems to take a lot longer to load a page when it does that i see the message spammed to logcat 0915 1556880 dframeloader issue 13523 frameloader fetching extra ua string uaprofurl0915 1556880 dframeloader issue 13523 frameloader fetching extra ua string uaprofurl0915 1556880 dframeloader issue 13523 frameloader fetching extra ua string uaprofurl0915 1556880 dframeloader issue 13523 frameloader fetching extra ua string uaprofurl0915 1556880 dframeloader issue 13523 frameloader fetching extra ua string uaprofurl0915 1556880 dframeloader issue 13523 frameloader fetching extra ua string uaprofurl0915 1556880 dframeloader issue 13523 frameloader fetching extra ua string uaprofurl0915 1556880 dframeloader issue 13523 frameloader fetching extra ua string uaprofurl0915 1556890 dframeloader issue 13523 frameloader fetching extra ua string uaprofurl0915 1556890 dframeloader issue 13523 frameloader fetching extra ua string uaprofurl0915 1556890 dframeloader issue 13523 frameloader fetching extra ua string uaprofurl0915 1556890 dframeloader issue 13523 frameloader fetching extra ua string uaprofurl0915 1556890 dframeloader issue 13523 frameloader fetching extra ua string uaprofurl0915 1556890 dframeloader issue 13523 frameloader fetching extra ua string uaprofurl0915 1556890 dframeloader issue 13523 frameloader fetching extra ua string uaprofurl0915 1556890 dframeloader issue 13523 frameloader fetching extra ua string uaprofurl0915 1556890 dframeloader issue 13523 frameloader fetching extra ua string uaprofurl0915 1556890 dframeloader issue 13523 frameloader fetching extra ua string uaprofurl0915 1556890 dframeloader issue 13523 frameloader fetching extra ua string uaprofurl0915 1556890 dframeloader issue 13523 frameloader fetching extra ua string uaprofurl0915 1556900 dframeloader issue 13523 frameloader fetching extra ua string uaprofurl0915 1556900 dframeloader issue 13523 frameloader fetching extra ua string uaprofurl0915 1556900 dframeloader issue 13523 frameloader fetching extra ua string uaprofurl0915 1556900 dframeloader issue 13523 frameloader fetching extra ua string uaprofurl0915 1556900 dframeloader issue 13523 frameloader fetching extra ua string uaprofurl0915 1556900 dframeloader issue 13523 frameloader fetching extra ua string uaprofurl0915 1556900 dframeloader issue 13523 frameloader fetching extra ua string uaprofurl0915 1556900 dframeloader issue 13523 frameloader fetching extra ua string uaprofurl0915 1556900 dframeloader issue 13523 frameloader fetching extra ua string uaprofurl0915 1556900 dframeloader issue 13523 frameloader fetching extra ua string uaprofurl0915 1556900 dframeloader issue 13523 frameloader fetching extra ua string uaprofurl0915 1556900 dframeloader issue 13523 frameloader fetching extra ua string uaprofurl0915 1556900 dframeloader issue 13523 frameloader fetching extra ua string uaprofurl0915 1556900 dframeloader issue 13523 frameloader fetching extra ua string uaprofurl0915 1556900 dframeloader issue 13523 frameloader fetching extra ua string uaprofurlwhat does it mean how can i avoid it,['android'] +763748,how to suppress compiler warning to add await inside razor view i am using mvc 5 and i have helper extension methods to generate links and other urls based on expressionactiontcontrollers that invoke controller actions these expressions obviously are not invoked in generating the view they are only used for metadatagiven this excerpt from my razor viewthisformaccountcontroller c cregisternullthe compiler generates a warningwarning 1 because this call is not awaited execution of the current method continues before the call is completed consider applying the await operator to the result of the callthis warning does not seem appropriate because it could only apply if that lambda were invoked which i know never happensis there a way to suppress this if not i will probably make the action nonasync,"['c#', 'asp.net']" +763827,enable cors post request from angularjs to jersey i am attempting to post a json document from an angularjs app to a jersey rest service the request fails informing me thatxmlhttprequest cannot load httplocalhost8080myrestserviceapiorderaddorder no accesscontrolalloworigin header is present on the requested resource origin httplocalhost is therefore not allowed accessjersey rest post functioni have enabled what i believe to be the appropriate headers accesscontrolalloworigin and accesscontrolallowmethods on the response as seen in the method belowpostproducesmediatypeapplication jsonconsumesmediatypeapplication jsonpathaddorderpublic response addorderdbobject dbobject db db mongogetdbstaffing dbcollection col dbgetcollectionorders colinsertdbobject objectid id objectiddbobjectget id return responseok entityid headeraccesscontrolalloworigin headeraccesscontrolallowmethods get post delete put allowoptions buildangular js controlleri have declared the app and configured the httpprovider with all of the settings suggested in similar stack overflow questionsvar staffingapp angularmodulemyapp ngroute uibootstrapmyappconfighttpprovider function httpprovider httpproviderdefaultsusexdomain true delete httpproviderdefaultsheaderscommonxrequestedwith httpproviderdefaultsheaderscommonaccept applicationjson httpproviderdefaultsheaderscommoncontenttype applicationjson i have also created this controller to open a modal and handle the form var modalctrl functionscope modal log http location scopeorder activitytitle null anticipatedawarddate null component null activitygroup null activitycategory null activitydescription null scopeopen function var modalinstance modalopen templateurl addorderhtml windowclass modal controller modalinstancectrl resolve order function return scopeorder modalinstanceresultthenfunction oid loginfoform submitted headed to page locationpathorders oid function loginfoform cancelled var modalinstancectrl function scope modalinstance log http order scopeorder order scopeok function loglogsubmitting user info loglogorder loglogand now in json loglogjsonstringifyorder httpposthttplocalhost8080myrestserviceapiorderaddorder jsonstringifyordersuccessfunctiondata loglogheres the datan loglogdata modalinstanceclosedata idoid scopecancel function modalinstancethismisscancel myappcontrollermodalctrl modalctrlto no avail i have tried removing allowoptions from the response headersremoving the httpprovider configuration from the applicationchanged the httpprovider configuration to call myappconfigfunction httpprovider passing the function itself rather than the arrayget requests work with the same configurationgetpathlistallproducesmediatypeapplication jsonpublic response listall db db mongogetdbstaffing dbcollection col dbgetcollectionorders listdbobject res colfindlimit200toarray return responseok entityrestostring headeraccesscontrolalloworigin headeraccesscontrolallowmethods get post delete put allowoptions build with this controller that works finemyappcontrollerorderlistctrl function scope http httpgethttplocalhost8080myrestserviceapiorderlistallsuccessfunctiondata for var i 0 i datalength i if dataidescriptionlength 200 dataishortdesc dataidescriptionsubstring0196 else dataishortdesc dataidescription scopeorders data update 1i have tried the same request on a same origin basis essentially serving the angular application alongside the rest service from locahost8080 this configuration worked but required a slight change and some general clean up in my code which i have edited abovethe post still fails as a cors request however so i am still looking for the missing piece in this configurationupdate 2i have investigated the headers of the working request as they are delivered to the browser and compared them with the nonworking requestthe working get request returns the following headers with its responsethe nonworking post request returns headers with its response but is missing the accesscontrolalloworigin headeri believe this has now become an issue of the headers being stripped off of the response prior to returning it to the client which would then cause the browser to fail the requestupdate 3submitting a test post request to the same url from chromes rest console extension returns the appropriate response headers as seen in the screencap belowat this point i cannot determine whats removing the headers between jersey and my angular client but i am fairly confident that is the culprit,['java'] +763834,this application does not have the debuggable attribute enabled in its manifest cannot debug application comdomaintest on device samsunggt i9300323020cfc86b804fthis application does not have the debuggable attribute enabled in its manifestif you have manually set it in the manifest then remove it and let the ide automatically assign itif you are using gradle make sure that your current variant is debuggable,['android'] +763919,javafxs task seem to consume exceptions is it a bug or a feature consider this codethreadsetdefaultuncaughtexceptionhandlerthread t throwable e systemoutprintlnan exception occurred set the exception handler for the javafx application threadthreadcurrentthreadsetuncaughtexceptionhandlerthread t throwable e systemoutprintlnan exception occurredtask task new task override public void call throws exception throw new runtimeexceptionfoobar new threadtaskstartif we run the code the runtime exception never triggers the default exception handler but is instead consumed by the task the only way to counteract this that i found is to rethrow the exception in tasksetonfailedtasksetonfailedworkerstateevent t throw new runtimeexceptiontaskgetexceptionsince javafx 8 now has support for the uncaughtexceptionhandler why is not the exception propagated to the exception handler,['java'] +763978,how to install python mysqldb module using pip how can i install the mysqldb module for python using pip,"['python', 'mysql']" +763988,global exception handling in web api 21 and nlog in web api 21 is new global error handling i found some example how to log exceptions into elmah elmah sample but i use nlog to log errors into database table is it posible to use web api global error handling with nlog please provide some example,"['c#', 'asp.net']" +764086,why is defau4t legal in a switch statement i came up with this program in some other site and thought of trying it heres the programinclude stdiohint main int a10 switcha case 1 printfone break case 2 printftwo break defau4t printfnone return 0suprisingly enough this compiles without errors or warnings how is this possible is not there an error on keyword defaultcould anyone explain this behaviour,"['c++', 'c']" +764142,installation failed on android gingerbread and froyo install failed dexopt when i try to install my apk file on devices running gingerbread and froyo it throws this errorapplication could not be installed pkg sdcardtempapk failure install failed dexopt if someone installs it through google play it shows a popup with the following message package file invalidi contacted google play developer support and they advised me to do a search for dexopt failed gingerbread froyo on android dev forums and i did search for this issue but couldt find any solution any help would be appreciatededit does this error helpdexinv end mntasecorgexampleandroid1pkgapk status0x0b process faileddexopt failed on datadalvikcachemnt res 11,"['java', 'android']" +764205,angular bootstrap ui modal with same controller instead of new controller i am using angular bootstrap ui modal box it says to give a new modalinstance for new controlleri want to use the same controller where i have initialized the modal boxi searched but no successi found this links but no success how to use the same controller for modal and nonmodal form in angular ui bootstrapangularui bootstrap modal without creating new controllerappcontrolleruserctrlscopefilterngtableparamsmodalfunctionscope filter ngtableparamsmodal var modalinstance modalopen templateurl mymodalcontenthtml controller modalinstancectrl instead of this i want to use the same controller userctrl size size resolve items function return scopeitems modalinstanceresultthenfunction selecteditem scopeselected selecteditem function loginfomodal thismissed at new date so that i can call the save function on this same controller which is called on save click of modal box,['javascript'] +764214,presenting uialertcontroller actionsheet in popover on iphone i am creating and presenting an actionsheet as followslet alertcontroller uialertcontrollertitle nil message nil preferredstyle actionsheetalertcontrollermodalpresentationstyle popover add some buttonsalertcontrollerpopoverpresentationcontrollerdelegate selfalertcontrollerpopoverpresentationcontrollerbarbuttonitem somebarbuttonselfpresentviewcontrolleralertcontroller animated true completion nilthis works fine on the ipad but alertcontrollerpopoverpresentationcontroller is nil on the iphonei have successfully presented popovers on the iphone using adaptive segue style present as popover in interface builder and implementing adaptivepresentationstyleforpresentationcontroller delegate method to return the correct uimodalpresentationstyle but i am stuck how to do it in code with uialertcontroller as it has no popoverpresentationcontroller on the iphone,"['ios', 'iphone']" +764234,unable to copy file microsoftsqlservertypes after installing microsoftsqlservertypes spatial packagei get build errorserror 14 could not copy myapackagesmicrosoftsqlservertypes1101nativebinariesx86msvcr100dll to binsqlservertypesx86msvcr100dll exceeded retry count of 10 failederror 26 could not copy myapackagesmicrosoftsqlservertypes1101nativebinariesx86sqlserverspatial110dll to binsqlservertypesx86sqlserverspatial110dll exceeded retry count of 10 failederror 15 unable to copy file myappmicrosoftsqlservertypes1101nativebinariesx86msvcr100dll to binsqlservertypesx86msvcr100dll the process cannot access the file binsqlservertypesx86msvcr100dll because it is being used by another processerror 27 unable to copy file myapackagesmicrosoftsqlservertypes1101nativebinariesx86sqlserverspatial110dll to binsqlservertypesx86sqlserverspatial110dll the process cannot access the file binsqlservertypesx86sqlserverspatial110dll because it is being used by another processafter investigation i have found that my iis worker process block these filesafter restart iisapplication building successfulybut than erros appearshow can i solve this problem,['.net'] +764235,how to check if device can make a phone call ios 8 on ios 8 you could use function boolcanopenurlnsurl urlon ios 8 this function returns yes even on ipad i guess it is connected with calling over wifi or another new functionality but my ipad cannot make phone calls anyone know better way to detect that capability,"['ios', 'objective-c']" +764279,routesappendtrailingslash exclude some routes in mvc 522 i can set routesappendtrailingslash to true so that trailing slash are appended to urlshowever i also have a robots controller which returns the content for the robotstxt how can i prevent a slash from being appended to the robotstxt route and have it callable with out the trailing slashmy controller coderouterobotstxtpublic async taskactionresult robots string robots getrobotscontent return contentrobots textplainmy route config looks like thisroutesignorerouteresourceaxdpathinforoutesmaproute name default url controlleractionid defaults new controller home action index id urlparameteroptional routetableroutesappendtrailingslash true,"['c#', 'asp.net']" +764303,sb admin 2 menu does not collapse when i edit some content i am working to edit some content for this bootstrap theme when i delete some content from the indexhtml file the left side bar navigation menu has been expanded and did not collapse againhere is the edited indexhtml codedoctype htmlhtml langenhead meta charsetutf8 meta httpequivxuacompatible contentieedge meta nameviewport contentwidthdevicewidth initialscale1 meta namedescription content meta nameauthor content titlesb admin 2 bootstrap admin themetitle bootstrap core css link hrefcssbootstrapmincss relstylesheet metismenu css link hrefcsspluginsmetismenumetismenumincss relstylesheet timeline css link hrefcsspluginstimelinecss relstylesheet custom css link hrefcsbadmin2css relstylesheet morris charts css link hrefcsspluginsmorriscss relstylesheet custom fonts link hreffontawesome410cssfontawesomemincss relstylesheet typetextcss html5 shim and respondjs ie8 support of html5 elements and media queries warning respondjs does not work if you view the page via file if lt ie 9 script srcscript script srcscript endifheadbody div idwrapper navigation nav classnavbar navbardefault navbarstatictop rolenavigation stylemarginbottom 0 div classnavbarheader button typebutton classnavbartoggle datatogglecollapse datatargetnavbarcollapse span clasronlytoggle navigationspan span classiconbarspan span classiconbarspan span classiconbarspan button a classnavbarbrand hrefindexhtmlsb admin v20a div navbarheader ul classnav navbartoplinks navbarright li classdropdown a classdropdowntoggle datatoggledropdown href i classfa fabell fafwi i classfa facaretdowni a ul classdropdownmenu dropdownalerts li a href div i classfa facomment fafwi new comment span classpullright textmuted small4 minutes agospan div a li li classdividerli li a href div i classfa fatwitter fafwi 3 new followers span classpullright textmuted small12 minutes agospan div a li li classdividerli li a href div i classfa faenvelope fafwi message sent span classpullright textmuted small4 minutes agospan div a li li classdividerli li a href div i classfa fatasks fafwi new task span classpullright textmuted small4 minutes agospan div a li li classdividerli li a href div i classfa faupload fafwi server rebooted span classpullright textmuted small4 minutes agospan div a li li classdividerli li a classtextcenter href strongsee all alertsstrong i classfa faanglerighti a li ul dropdownalerts li dropdown li classdropdown a classdropdowntoggle datatoggledropdown href i classfa fauser fafwi i classfa facaretdowni a ul classdropdownmenu dropdownuser lia hrefi classfa fauser fafwi user profilea li lia hrefi classfa fagear fafwi settingsa li li classdividerli lia hrefloginhtmli classfa fasignout fafwi logouta li ul dropdownuser li dropdown ul navbartoplinks div classnavbardefault sidebar rolenavigation div clasidebarnav navbarcollapse ul classnav idsidemenu li clasidebarsearch div classinputgroup customsearchform input typetext classformcontrol placeholdersearch span classinputgroupbtn button classbtn btndefault typebutton i classfa fasearchi button span div inputgroup li li a classactive hrefindexhtmli classfa fadashboard fafwi dashboarda li li a hrefi classfa fabarcharto fafwi chartsspan classfa arrowspana ul classnav navsecondlevel li a hrefflot chartsa li li a hrefmorrisjs chartsa li ul navsecondlevel li li a hrefi classfa fatable fafwi tablesa li li a hrefi classfa faedit fafwi formsa li li a hrefi classfa fawrench fafwi ui elementsspan classfa arrowspana ul classnav navsecondlevel li a hrefpanels and wellsa li li a hrefbuttonsa li li a hrefnotificationsa li li a hreftypographya li li a hrefgrida li ul navsecondlevel li ul div sidebarcollapse div navbarstaticside nav div idpagewrapper div classrow div classcollg12 h1 classpageheaderdashboardh1 div collg12 div row div classrow div classcollg3 colmd6 div classpanel panelprimary div classpanelheading div classrow div classcolxs3 i classfa facomments fa5xi div div classcolxs9 textright div classhuge26div divnew commentsdiv div div div a href div classpanelfooter span classpuleftview detailsspan span classpullrighti classfa faarrowcirclerightispan div classclearfixdiv div a div div div classcollg3 colmd6 div classpanel panelgreen div classpanelheading div classrow div classcolxs3 i classfa fatasks fa5xi div div classcolxs9 textright div classhuge12div divnew tasksdiv div div div a href div classpanelfooter span classpuleftview detailsspan span classpullrighti classfa faarrowcirclerightispan div classclearfixdiv div a div div div classcollg3 colmd6 div classpanel panelyellow div classpanelheading div classrow div classcolxs3 i classfa fashoppingcart fa5xi div div classcolxs9 textright div classhuge124div divnew ordersdiv div div div a href div classpanelfooter span classpuleftview detailsspan span classpullrighti classfa faarrowcirclerightispan div classclearfixdiv div a div div div classcollg3 colmd6 div classpanel panelred div classpanelheading div classrow div classcolxs3 i classfa fasupport fa5xi div div classcolxs9 textright div classhuge13div divsupport ticketsdiv div div div a href div classpanelfooter span classpuleftview detailsspan span classpullrighti classfa faarrowcirclerightispan div classclearfixdiv div a div div div row div row div pagewrapper div wrapper jquery version 10 script srcjsjquery10jsscript bootstrap core javascript script srcjsbootstrapminjsscript metis menu plugin javascript script srcjspluginsmetismenumetismenuminjsscript morris charts javascript script srcjspluginsmorrisraphaelminjsscript script srcjspluginsmorrismorrisminjsscript script srcjspluginsmorrismorrisdatajsscript custom theme javascript script srcjssbadmin2jsscriptbodyhtml,"['html', 'css']" +764359,subsampling every nth entry in a numpy array i am a beginner with numpy and i am trying to extract some data from a long numpy array what i need to do is start from a defined position in my array and then subsample every nth data point from that position until the end of my array basically if i hada 123412341234 i want to subsample this to start at a1 and then sample every fourth point from there to produce something likeb 2,['python'] +764399,do not know how to build task elasticsearchimportmodel well i have elasticsearchrails gem installed version 015 and i can clearly see the task inside the gem filesbut when i run bundle exec rake environment elasticsearchimportmodel classcommenti get this errorrunning rake environment d does not show me the task eitherelasticsearch is running if i curl httplocalhost9200 it responds mecan someone help me find out why the heck this is not working,['ruby-on-rails'] +764442,angularjs how to pass up to date routeparams to resolve how do you pass current routeparams to resolve so they can be used to do a specific httpget right now i have just tested routeparams and passed back the param to be logged in my controller to see if it works but it is a route behind each time for example on load it is undefined and on subsequent routes the param is the previous routes param so i click a new link and it shows the param from the previous links routeroute snippet whensomethingparamtype templateurl appviewssomethinghtml controller somethingcontroller controlleras somectrl access authentication true resolve somedata function routeparams return routeparamsparamtype controller snippet controllersomethingcontroller scope somedata function scope somedata consolelogsomedata how do you initialize the param on load and have it sync correctly each time the reason i want to do this is so i can perform an httpget and pass the routeparams to define the returned data,['javascript'] +764504,clangformat breaks lint annotations we use lint in our codebase at work for cc i am trying to start integrating clangformat in my workflow as wellunfortunately lint occasionally requires annotations to ignore a specific check either of the formatlint annotation orlint annotationspecifically if there is a space between the opening token for the comment and lint it does not recognize it as an annotation directive unfortunately the default settings i have for clangformat see that as an error and helpfully insert the spaceis there any way to get clangformat to recognize comments matching that pattern and leave them alone right now i am using 34 but could upgrade if needed,['c++'] +764546,rotating a nxn matrix in java this is a question from cracking the coding interview the solution says that the program rotates the exterior edges then the interior edges however i am having trouble following the logic of both the for loops could somebody explain the logic of the code eg why they do layer n2 and the four steps of left top and bottom left etc on a side note how would ones thought process be when coming up with this during a coding interviewgiven an image represented by an nxn matrix where each pixel in the image is 4 bytes write a method to rotate the image by 90 degrees can you do this in placepublic static void rotateint matrix int n for int layer 0 layer and 2 layer int first layer int last and 1 layer forint i first i last i int offset i first int top matrixfirsti save top left top matrixfirsti matrixlastoffsetfirst bottom left matrixlastoffsetfirst matrixlastlast offset right bottom matrixlastlast offset matrixilast top right matrixilast top right saved top,['java'] +764646,google cloud messaging fake message id i have nodejs servervar gcm requirenodegcm create a message with default valuesvar message new gcmmessage or with object valuesvar message new gcmmessage collapsekey demo delaywhileidle true timetolive 3 data key1 message1 key2 message2 var sender new gcmsenderaizasychp2jtqsgpklaavgfh6yoovu1td7tuqmovar registrationids optional add new keyvalue in data objectmessageadatawithkeyvaluekey1message1messageadatawithkeyvaluekey2message2 or add a data objectmessageadatawithobject key1 message1 key2 message2 or with backwards compability of previous versionsmessageadatakey1message1messageadatakey2message2messagecollapsekey demomessagedelaywhileidle truemessagetimetolive 3messagedryrun true end optional at least one requiredregistrationidspushapa91bgv0w6lgapc07ahcsqdd462f lcouy0r5mqvtdfx1zfk31njmueyvx0siap29dkyxdj5y8cl2to1aih0kevia9hk3q47atou8qsd6itbg params messageliteral registrationidsarray no of retries callbackfunction sendersendmessage registrationids 4 function err result consolelogresulti got an multicast id 1 success 1 failure 0 canonical ids 0 results message id fake message id and message does not send to receivers what does fake message id mean,"['javascript', 'android']" +764822,game center authentication does not work in ios 8 i am trying to implement game center in my game i have tried it on the ios 8 gmi am not able to get the authentication to work on device but it works fine in the simulator i am using the code provided in apples documentationdo other people have the same issue any advice,"['ios', 'iphone']" +764823,uilabel causes app to crash when added to view xcode 6 and ios 8 only i have transitioned my project to xcode 6 in order to build for ios 8 however a particular uilabel is causing the app to crash when it is added to the view hierarchy this is the only error log i receivemyviewcontroller contentinsetsfromfonts unrecognized selector sent to instance 0x16d90da0i have been unable to locate the contentinsetsfromfonts method anywhere in my project additionally i have not even been able to find a reference for it anywhere online including apples documentation i am not using a nib for this uiviewcontroller so the ui is built in the loadview method voidloadview uiimage trackimage uiimage imagenamedslidertrackpng sliderbackground uiimageview alloc initwithimagetrackimage uiview view uiview alloc initwithframesliderbackgroundframe view addsubviewsliderbackground slider uislider alloc initwithframesliderbackgroundframe cgrect sliderframe sliderframe sliderframesizewidth 46 sliderframe sliderframe slidercenter sliderbackgroundcenter sliderbackgroundcolor uicolor clearcolor slider setminimumtrackimageuiimage imagenamedslidermaxmintrackimagepng forstateuicontrolstatenormal slider setmaximumtrackimageuiimage imagenamedslidermaxmintrackimagepng forstateuicontrolstatenormal uiimage thumbimage uiimage imagenamedcancelsliderpng slider setthumbimagethumbimage forstateuicontrolstatenormal sliderminimumvalue 00 slidermaximumvalue 10 slidercontinuous yes slidervalue 00 set the slider action methods slider addtargetself actionselectorsliderup forcontroleventsuicontroleventtouchupinside slider addtargetself actionselectorsliderdown forcontroleventsuicontroleventtouchdown slider addtargetself actionselectorsliderchanged forcontroleventsuicontroleventvaluechanged nsstring labeltext label text uifont labelfont nsstring osversion uidevice currentdevice systemversion if osversion floatvalue 70 labelfont uifont systemfontofsize220 else labelfont uifont systemfontofsize240 cgsize labelsize labeltext sizewithattributesnsdictionary dictionarywithobjectsandkeyslabelfont nsfontattributename nil label uilabel alloc initwithframecgrectmake00 00 labelsizewidth labelsizeheight cgfloat labelhorizontalcenter slidercenterx thumbimagesizewidth 2 labelcenter cgpointmakelabelhorizontalcenter slidercentery set other label attributes and add it to the view labeltextcolor uicolor whitecolor labeltextalignment nstextalignmentcenter labelbackgroundcolor uicolor clearcolor labelfont labelfont labeltext labeltext view addsubviewlabel view addsubviewslider labellayerdelegate self selfview viewthe app does not crash at view addsubviewlabel it crashes after the loadview method returns,"['ios', 'objective-c']" +764868,lucene cannot find documents after update it seems that whenever i update an existing document in the index same behavior for delete add it cannot be found with a termquery heres a short snippetiw new indexwriterdirectory configdocument doc new documentdocaddnew stringfieldstring a storeyesdocaddnew intfieldint 1 storeyesiwadocumentdocquery query new termquerynew termstringadocument hits searchquerydoc hits0printdocdocremovefieldintdocaddnew intfieldint 2 storeyesiwupdatedocumentnew termstringa dochits searchquerysystemoutprintlnhitslengthsystemoutprintln fordocument hit searchnew matchalldocsquery printhitthis produces the following console outputstoredindexedtokenizedomitnormsindexoptionsdocs onlystringastoredint1 0 storedindexedtokenizedomitnormsindexoptionsdocs onlystringastoredint2 it seems that after the update the document rather the new document in the index and gets returned by the matchalldocsquery but cannot be found by a termqueryfull sample code available at also this only happens second search not working when the stringfield value contains special characters eg filef,['java'] +764881,download binary file from okhttp i am using okhttp client for networking in my android application this example shows how to upload binary file i would like to know how to get inputstream of binary file downloading with okhttp clienthere is the listing of the example public class inputstreamrequestbody extends requestbody private inputstream inputstream private mediatype mediatype public static requestbody createfinal mediatype mediatype final inputstream inputstream return new inputstreamrequestbodyinputstream mediatype private inputstreamrequestbodyinputstream inputstream mediatype mediatype thisinputstream inputstream thismediatype mediatype override public mediatype contenttype return mediatype override public long contentlength try return inputstreamavailable catch ioexception e return 0 override public void writetobufferedsink sink throws ioexception source source null try source okiosourceinputstream sinkwriteallsource finally utilclosequietlysource current code for simple get request isokhttpclient client new okhttpclientrequest new requestbuilderurlurl string here addheaderxcsrftoken csrftoken addheadercontenttype applicationjson buildresponse getclientnewcallrequestexecutenow how do i convert the response to inputstream something similar to response from apache http client like this for okhttp responseinputstream is responsegetentitygetcontenteditaccepted answer from belowmy modified coderequest new requestbuilderurlurlstringbuildresponse getclientnewcallrequestexecuteinputstream is responsebodybytestreambufferedinputstream input new bufferedinputstreamisoutputstream output new fileoutputstreamfilebyte data new byte1024long total 0while count inputreaddata 1 total count outputwritedata 0 countoutputflushoutputcloseinputclose,['android'] +765017,valid characters in custom data attribute name in html5 i am creating some custom data attributes in my site and i am having a hard time reading the spec here and herei can tell az 09 and are allowed but i cannot decipher anything more from thati also think az will automatically converted to lower spec link 1 before being processed but it mentions not using them spec link 2questions1 what characters are allowed and not allowed in a custom data attribute2 are special characters like etc allowedthanks,"['javascript', 'html']" +765118,how does stdstring prevent me from carelessly stomping on its data i have the following c codeinclude stringinclude iostreamint mainint argc char argv int size stdstring strarray3 stdstring str0 string 0 stdstring str1 string 1 stdstring str2 string 2 strarray0 str0 strarray1 str1 strarray2 str2 for int i 0 i 3 i stdcout strarrayi stdendl str1resize200 a for int i 0 i 3 i stdcout strarrayi stdendl stdcout str1 stdendl stdcinget return 0the idea here is that i have an array which is a contiguous block of memory where each member is a stdstring which are mutable and therefore variable in size i expected this code to break since i resize str1 to take up loads more space than original and therefore overflowing into str2instead i get this outputstring0string1string2string0string1string2string1ai have two questions about this first of all how is it that increasing the size of str1 and adding loads of characters to it does not flow over into str2 even though they should be in a contiguous block of memorysecond how come when i print the array for the second time after resizing str1 and add the characters to it it still prints the original str1i have a feeling that this will have something to do with the answer to my first question but i cannot quite see what is going on here,['c++'] +765178,cut rectangle in minimum number of squares i am trying to solve the following problema rectangular paper sheet of mn is to be cut down into squares such thatthe paper is cut along a line that is parallel to one of the sides of the paperthe paper is cut such that the resultant dimensions are always integersthe process stops when the paper cannot be cut any furtherwhat is the minimum number of paper pieces cut such that all are squareslimits 1 and 100 and 1 m 100example let n1 and m2 then answer is 2 as the minimum number of squares that can be cut is 2 the paper is cut horizontally along the smaller side in the middlemy codecin and mint and minnmint m maxnmint ans 0while n m ans int x m n int y n m maxx y and minx yif n m m 0 ansbut i am not getting whats wrong with this approach as it is giving me a wrong answer,['c++'] +765188,creating objects on the stack memory in java this is just a simple theoretical question out of curiosity i have always been like a java fan boy but one thing makes me wonder why java does not provide mechanism for creating objects on the stack wouldnt it be more efficient if i could just create small pointint xint y object on the stack instead of the heap like creating a structure on c is there any special security reason behind this restriction in java,['java'] +765240,uiactivityviewcontroller on ios 8 show more button with custom activities now xcode 6 with ios 8 sdk is out we can talk about stuffi tried to use custom activities with uiactivityviewcontroller on ios 7 everything worked finebut on ios 8 when custom activities are shown there is more button sitting next to them and clicking on this button show exactly the same custom activitiesdid anyone find a workaround to remove this button i could not find any solution yet,['ios'] +765258,importerror no module named tkinter for some reason i cannot use the tkinter modulei have no idea what could cause it and it is so annoying is there anything wrong with this lineimport tkinteralso tried running it in the python terminal still do not work,['python'] +765388,how to recursively iterate through files in php i have set up a basic script that is posting an array of paths to find template files inside them currently it is only searching two levels deep and i am having some troubles getting my head around the logic for an extensive loop to iterate all child directories until the length is 0so if i have a structure like thiscomponentscomponentstemplatehtmlcomponentstemplate2htmlcomponentssidetemplatehtmlcomponentssidetemplate2htmlcomponentssidesecondtemplatehtmlcomponentssidesecondtemplate2htmlcomponentssidesecondthirdtemplatehtmlcomponentssidesecondthirdtemplate2htmlit is only searching up to the side directory for html files when ideally i want it to check all child directories and the passed directory for html files here is my working code so farphpfunction getfilespath dh opendirpath foreachglobpathhtml as filename files filename if issetfiles return files foreach post as path foreach globpath glob onlydir as secondlevel files getfilessecondlevel files getfilespathsortfilesprint rjson encodefiles,['php'] +765390,xcode 6 and embedded frameworks only supported in ios8 when using an embedded framework dyld in xcode 601 with deployment target less that ios 8 i getbuild is successfulruntime library loading errorerrordyld library not loaded rpathobjectivelyricstouch2frameworkobjectivelyricstouch2 referenced from privatevarmobilecontainersbundleapplicationdc65aca998e546cd95f8829d3416f6c0musixmatchappmusixmatchreason image not foundlldb,['objective-c'] +765407,ios alertview for location permission does not pop up i just started my project for ios 8 and i ran in too the problem that i cant get the question to pop up for permission i added the following to my infoplistkeynslocationwheninuseusagedescriptionkeystringthe spirit of stack overflow is coders helping codersstringkeynslocationalwaysusagedescriptionkeystringi have learned more on stack overflow than anything elsestringand this is my code interface viewcontroller mkmapviewdelegateproperty nonatomic strong uipopovercontroller userdatapopoverproperty weak nonatomic iboutlet mkmapview mapviewproperty strong nonatomic retain cllocationmanager locationmanagerendimplementation viewcontrollercllocationmanager locationmanager if locationmanager locationmanager cllocationmanager allocinit return locationmanager voidviewdidload super viewdidload selfmapviewdelegate self selflocationmanager requestwheninuseauthorization selflocationmanager requestalwaysauthorization selflocationmanager startupdatinglocation selfmapviewshowsuserlocation yes selfmapview showsuserlocation selfmapview setmaptypemkmaptypestandard selfmapview setzoomenabledyes selfmapview setscrollenabledyes voidmapviewmkmapview mapview didupdateuserlocationmkuserlocation userlocation mkcoordinateregion region mkcoordinateregionmakewiththistanceuserlocationcoordinate 800 800 selfmapview setregionselfmapview regionthatfitsregion animatedyes,['ios'] +765472,how to set an encoding for the javadoc in gradle i have written javaclasses with javadoccommands that contain special characters like a14 i generate the javadoc using a gradle buildfileapply plugin javaand the in the commandline gradle javadocthe encoding of the original files is utf8 the encoding of the javadoc files is also utf8 but there is no hint in the htmlsources that the files are utf8 thats why my browser always thinks it is iso8859how can i tell javadoc via gradle to also add meta charsetutf8 to the source codes when generating the javadoc,['java'] +765500,xamarinforms binding from xaml to property i am a total newbie with bindings in xaml and i really do not get it sometimesi have this in my xamlactivityindicator isrunningbinding isloading isvisiblebinding isloading the binding isloading where do i declareset this propertymy cs looks like this public bool isloading public cardslistxaml initializecomponent isloading true,['c#'] +765520,pycharm 34 would not run on yosemite pycharm 34 fresh install will not run on yosemite with apple jdk 16crashed thread 32 java awteventqueue0dyld error message symbol not found cgcontextsetallowsacceleration referenced from libraryjavajavavirtualmachines160 65b14462jdkcontentslibrarieslibawtjnilib expected in systemlibraryframeworksapplicationservicesframeworkversionsaapplicationservicesthere are advices to switch to oracle jdk 17 but since apple 16 is recommended i would rather stick with that version,['java'] +765530,parallel generation of random forests using scikitlearn main question how do i combine different randomforests in python and scikitlearni am currently using the randomforest package in r to generate randomforest objects using elastic map reduce this is to address a classification problemsince my input data is too large to fit in memory on one machine i sample the data into smaller data sets and generate random forest object which contains a smaller set of trees i then combine the different trees together using a modified combine function to create a new random forest object this random forest object contains the feature importance and final set of trees this does not include the oob errors or votes of the treeswhile this works well in r i want to do the same thing in python using scikitlearn i can create different random forest objects but i do not have any way to combine them together to form a new object can anyone point me to a function that can combine the forests is this possible using scikitlearnhere is the link to a question on how to this process in rcombining random forests built with different training sets in r edit the resulting random forest object should contain the trees that can be used for prediction and also the feature importance any help would be appreciated,['python'] +765560,how to use extension methods in powershell i have the following codeusing systempublic static class intex summary yields a power of the given number summary param namenumberthe base numberparam param namepowerofthe power to be applied on te base numberparam returnspowers applied to the base numberreturns public static ienumerableint listpowersofthis int number int powerof for var i number i powerof yield return i i have loaded the dll in powershellwindows 8 i try to use it the following waytest 1listpowersof2should return 1 2 4 8 16instead it says there is no such methodi tried the followingbasedllnamespacelistpowersof12still nothing i have no namespace in the intex classhow do i make it work,"['c#', '.net']" +765576,iphone web app prevent keyboard from movingpush up view ios8 in all versions prior to ios8 i was able to prevent the iphone keyboard from pushing up and destroying my htmlcssjs view when the keyboard appeared by the following methodinput selectfocusfunctionevent windowscrolltop0 or via the scrollto functionsince ios8 this no longer works one workaround is to place this code within a settimeoutsettimeoutfunction windowscrolltop0 0but it only makes the view do a jerky motion as the view is initially pushed up by ios then dragged back down by my js code preventdefault and stoppropagation does not help eitheri have tried everything available on the web of course including my own solution posted here how to prevent keyboard push up webview at ios app using phonegap but so far nothing works for ios8 any clever ideas on how to prevent the keyboard in ios8 to pushmove the view,"['javascript', 'jquery', 'css']" +765687,angular model fails to update after select option is filtered out trying to figure out why the model does not update when the bound selected option no longer exists i would expect the models property to update to undefinednullempty stringsituation one select drives another select using filter after selections are made go to the original select and choose another option filter will remove the second select option as expected but the model property on the second select will be unchangedproblem when you go to pass the model it will be populated with badprevious values in addition using angular validation the select being requiredthe form is technically valid because the model has a value the previous value for the propertyhtmlselect namecategory ngmodelselectedcategory ngoptionsitemname as itemname for item in categories option valueall categoriesoptionselectselect namesubcategory ngmodelselectedsubcategory ngoptionsitemname as itemsubcategory for item in categories filterselectedcategory option valueall subcategoriesoptionselectmodelappcontrollermainctrl functionscope scopecategories id 1 name truck subcategory telescope id 2 name truck subcategory hazmat id 3 name van subcategory mini i am fairly certain i could tie an ngchange function to the first to force it to update the model but is there a better wayexample plunker demonstrating the problem,['javascript'] +765708,when running clang built from source how to specify location of libc or someone explain to me what stdliblibc does i am developing plugins and tools using clangs provisions for doing so via plugins and clangs libtooling i am able to do the following things compile llvm with clang inside from svn linux and osx by following the getting started page by running the configure script without using cmakecompile libcxxlibc on linux also from svn and i have no reason to expect any trouble with this on osx the thing is that libc headers already exist on my osx system atapplicationsxcodeappcontentsdevelopertoolchainsxcodedefaultxctoolchainusrlibcv1and the libc dylib lives at usrlibedit 4 i was able to compile libcxx just fine on os x by following the directions i have got a brand new libc10dylib sitting here nowon osx use the releaseasserts and debugasserts builds of clang to compile c source code by appendingiapplicationsxcodeappcontentsdevelopertoolchainsxcodedefaultxctoolchainusrlibcv1and without using stdliblibc using this flag to explicitly specify libc as an include directory allows the clang that i built to see the standard c headers surprisingly it seems to be happy with it while compiling a moderately basic source file which still exercises a good amount of c11 madness in itbased on this you can see that i am hacking my freshly built clang version 360 trunk 217905 to look up apples xcodepackaged libc this is ostensibly working for now because apples libc that came with xcode remains abicompatible with the compiler that i just built from source what is still very curious to me is how my freshly compiled clang is able to figure out where to find the corresponding libc dylib this raises the question later on of when i actually get libc compiled how am i supposed to tell my new svncompiled clang to look up and use the new svncompiled libc dylibso basically i am still utterly confused about what i am really supposed to do to set up libc properly what specifically does clang actually do when you tell it stdliblibcis it a hardcoded include path i probably want to be building libcabi and libc from svn to use along with the clang that has been built from svn that makes the most sense then how should i go about installing it having to put ilibcxxincludecv1 or whatever it would be into a build config is inelegantpresumably i can just set up my llvm build to build clang along with libcabi and libc by also checking out libcxxabi and libcxx from svn and my expectation is that installing it ought to make stdliblibc magically work note also that the clang that apple gives you with xcode does not really require you to use stdliblibc it just magically knows where to grab the library fileshowever the fly in the ointment at least the only one so far that i know to look for my machine already has a usrbinclang ls la which clangrwxrxrx 1 root wheel 14240 mar 17 2014 usrbinclangthis is not a symlink to inside xcodeapp as i expected i now have real concern about running make install from my llvm build directory it could probably break my xcode environment or prevent my mac from booting as the libc llvm doc clearly states will happen if something bad happens to usrliblibc1dylibhopefully there is not already documentation out there that i have missed that answers these questions because i really should have found it by now edit i see in the sparse instructions found on that clang stdc11 stdliblibc nostdinc ipathtolibcxxinclude lpathtolibcxxlib testcppmight actually be the proper way right now but what this fails at is explaining what stdliblibc causes clang to do or what nostdinc causes clang to do edit 2 thanks to nm now we know that nostdinc means no standard c include path searched this means that standard include path is a thing is this path hardcoded when clang is built i googled and found something referencing a variable clang includepath this appears like possibly a makefile variable unfortunately i am running full filesystem text search over my llvm source dir and finding no matches to such a string so it cannot be a config used by clang or during the process of building clangedit 3 with the aid of verbose i can now see some helpful output xcodes clangclang cc1 version 51 based upon llvm 34svn default target x86 64appledarwin1340ignoring nonexistent directory usrincludecv1include search starts hereinclude search starts here applicationsxcodeappcontentsdevelopertoolchainsxcodedefaultxctoolchainusrbinlibcv1 usrlocalinclude applicationsxcodeappcontentsdevelopertoolchainsxcodedefaultxctoolchainusrbinlibclang51include applicationsxcodeappcontentsdevelopertoolchainsxcodedefaultxctoolchainusrinclude usrinclude systemlibraryframeworks framework directory libraryframeworks framework directoryend of search listsvn fresh clang clang cc1 version 360 based upon llvm 360svn default target x86 64appledarwin1340ignoring nonexistent directory usersusernamedocumentsllvmbuildreleaseassertsbinincludecv1ignoring nonexistent directory usrincludecv1include search starts hereinclude search starts here usrlocalinclude usersusernamedocumentsllvmbuildreleaseassertsbinlibclang360include usrinclude systemlibraryframeworks framework directory libraryframeworks framework directoryend of search listokay so this is painting a picture of a few places to deposit some libc files the presence of two ignoring nonexistent directory entries indicates to me that xcodes clang is able to find a libc at its hardcoded appsxcodeappcv1 while my svn clang is not finding one at the place it wants to look inside the releaseasserts build dir which seems silly but it may actually be where libcxx copies its headers into by the llvm build system no hints on where it is fetching the libc dylibs from though not even when looking through the strings that are in the clang executables using string which was a long shot anywaynot exactly crystal clear what exactly to do but i do appear to sort of have the tools now to get going on my project the main issue now is whats going on with the libcdylib i cannot tell if the freshly built clang is hardcoded to find it at usrliblibc1dylib or what i need to do this not touch usrliblibc1dylib so as not to break my entire operating systempoint freshly compiled clang to use the libc1dylib that is now been built and is sitting in a different location than usrliblibc1dylib i do not care where it goes at this point but i am not about to run make install which will likely overwrite usrliblibc1dylibit is just not clear what makes sense to do does specifying stdliblibc cause clang to link the hardcoded usrliblibc1dylib if so can i just drop it and lcompiled libcdylib explicitly otherwise how do i compile clang in a way to modify this path to get it to use the right onefor the time being i will use stdliblibc nostdinc see first edit and pray that it actually means for clang to listen to the inew libc header path lnew libc dylib path i guess if it still does not work and the system files get used anyway despite these efforts i will still be happy as long as my programs continue to compile,['c++'] +765784,icloud container changes with release of ios 8 since the release of ios 8 on the 17th all my development and deployment profiles are showing as invalid in the apple dev center also none of my apps using icloud will run in either xcode 51 or 6 gm on an actual device get a message stating entitlements do not match provisioning profile the only acceptable icloud containers now have to start with icloud which do not recognize data already stored in icloud using the previously require icloud container naming structureany solutions i have searched the web and apple dev site for hours with no solutions found i cannot be the only one having this problem very frustrating after just releasing an app on the app store and now cannot change any code to update it,['ios'] +765801,how to call swift initializer that has a parameter from objectivec i have a swift classclass mytextfield nsobject uitextfielddelegate var myfield uitextfield no idea how to pass in my uitextfield from objectivec code init x uitextfield myfield x i have added a property not shown so i could set myfield and everything is working would like to use the init function if only the syntax were not a complete mystery any ideas,"['ios', 'objective-c']" +765954,laravel database table and column naming conventions i am using laravel eloquent data objects to access my data what is the best way to name my tables columns foreignprimary keys etci found there are lots of naming conventions out there i am just wondering which one best suits for laravel eloquent modelsi am thinking of following naming conventionsingular table names ex postsingular column names ex userid user id in the post tablecamel casing for multiple words in table names ex postcomment postreview postphotocamel casing for multiple words in column names ex firstname postcategoryid postphotoidso with this i could use similar syntax in the controllerresult postwherepostcategoryid 4getare there any recommended laravel guidelines for this can i proceed with these naming conventionsif someone has better suggestions i will be very happy to hear themthanks a lot,['php'] +765990,casting struct with generic parameter with swift i am trying to do the followingprotocol vehicle class car vehicle class vehiclecontainerv vehicle let carcontainer vehiclecontainercarlet vehiclecontainer carcontainer as vehiclecontainervehiclebut i get the compile error on the last linecar is not identical to vehicle is there any workaround for thisalso i believe this type of casting should be possible because i can do it with arrays which are built on generics the following workslet cararray arraycarlet vehiclearray cararray as arrayvehicle,['ios'] +766009,how to calculate position on a circle with a certain angle i am trying to figure out how i could be able to calculate coordinates on a circle for simplicity i made some imagesthat is the start with information i have now i need to calculate the new coordinates when for example the circle would turn 90 degrees to the right just like the next imagei need to calculate the coordinates of the new red dot i also need this with different degrees such as 20 degreesto do this my plan was to do the followingcalculate the thistance between the two pointscalculate the degree between the north up and the given pointcalculate the new location with the degree from a step back the degrees it needs to turn in the images 90 degreesmy first step isthistance mathsqrtpoint1xpoint2xpoint1xpoint2x point1ypoint2ypoint1ypoint2ythe part to calculate the new degrees isdouble theta mathatan2targetpty centerpty targetptx centerptxtheta mathpi20and the last part to calculate the new location would bedouble x mmiddleviewgetx thistance mathcosmathtoradiansthetadouble y mmiddleviewgety thistance mathsinmathtoradiansthetahowever when i do these calculations with for example 0 degrees it still returns another value than the original coordinatesany help would be appreciatededit for philipp jahodamy values are thistance 70 currentdegree 0pointf point new pointffloatmmiddleviewgetx floatmmiddleviewgetypointf point2 getpositionpoint float thistance currentdegreeand my results are center pointf4900 7280 radius 780 angle 00new point pointf5680 7280as you can see the degree is 0 so the point is not supposed to turn it should keep the 490 728 coordinates but it does not keep those,"['java', 'android']" +766058,animate addingremoving items from listview with cursoradapter possible i was just wondering if it is possible to animate the removingadding from items when i requery my cursor and for example some underlying data changed or do i have to check the differences manually and assignremove them from my listview to get the desired animations i use a slightely different version of listviewanimations and created my own cursoradapter for usageso basically i would like to know a good way of how to check if there are differences inside of the cursor element missing element added so i could animate their apperance,['android'] +766074,why is documentgetelementbyid not needed 1 question 1the following example works without using documentgetelementbyidmyid why is that and is it ok to skip documentgetelementbyidmyiddoctype htmlhtmlheadmeta charsetutf8titlejavascript questiontitlescriptwindowonload function myidstylecolor redscriptheadbodydiv idmyidpmake this color redpdivbodyhtml2 question 2i usually store browserobjects to reduce dom traversal see example below will it be more dom traversal if i dont store the id in a variable or is it some how already a variablewindowonload functionvar myid documentgetelementbyidmyid stored id that will be used multiple times myidstylecolor redthanks,['javascript'] +766095,how to play video with avplayerviewcontroller avkit in swift how do you play a video with av kit player view controller in swiftoverride func viewdidload superviewdidload let videourlwithpath http5m3u8 let videourl nsurlstring videourlwithpath playerviewcontroller avplayerviewcontroller thispatch asyncthispatch get main queue selfplayerviewcontrollerplayer avplayerplayerwithurlvideourl as avplayer,['ios'] +766112,android studio gradle github repo does anyone have an idea if it is possible to use a github repo as a dependency without it being published to maven central let us say i am developing an android library that has it is own github repo i would like to be able to compile this library has gradle dependency in my android studio project without having to publish to maven central at least for the momentin other words i want to use a dependency that is not on maven central it is a straight github repo an android library that also uses gradlei would like my buildgradle to do something like this dependencies google play services normal dependency compile comgoogleandroidgmsplayservices5208 the library i want to pull from github compile path to my github repothanks,['android'] +766136,load denied by xframeoptions does not permit crossorigin framing i am using laravel 4 for one of my development where i am trying to load an iframe using cross origin call but it throws an error like load denied by xframeoptions does not permit crossorigin framingi am trying to set a headers likeheaderxframeoptions allowfrom sameoriginheaderxframeoptions allowfrom goforitbut still i am getting the above issue please suggest if i am missing something,['php'] +766220,sailsjs model insert or update records been trying out sailsjs and i am writing an app that imports data from a thirdparty api and saves in into a mysql table basically i am trying to sync data over to my app for further analysis updating my records or creating new records as neededi have looked through sails api and i see methods to find create and update records but no builtin method to insertupdate records based on the situation did i overlook something or will i need to implement this myselfif i have to implement this myself does anyone know of a good design pattern for insertupdatethis is what i think it might look likea eachimportedrecords functionrecord mymodelfindid recordidexecfunction findcberr found iffoundlength mymodelupdaterecordid taskexecfunctionerr updated iferr returns if an error has occured ie id does not exist consolelogerr else consolelogupdated mymodel record updated0name else mymodelcreaterecordexecfunctionerr created iferr returns if an error has occured ie invoice id does not exist consolelogerr else consolelogcreated client record createdname am i headed in the right direction or is there a more elegant solutionalso i am dealing with a lot of different models in this app which would mean recreating this block of code across each of my models is there a way i can extend the base model object to add this functionality for all modelsthanksjohn,['javascript'] +766278,ruby count the number of times a string appears in another string i am trying to count the number of times a string appears in another stringi know you can count the number of times a letter appears in a stringstringaabbccddbbstringcounta 2but if i search for how many times aa appears in this string i also get twostringcountaa 2i do not understand this i put the value in quotation marks so i am searching for the number of times the exact string appears not just the letters,['ruby'] +766306,c array size declaration and const i am just jumping into c coming from cin c 8990 a const is not actually a constant as opposed to a defined enum or literal but rather readonly once set ie i canconst int x randand that is fine the point being x is not known until runtime hence i cannotint arrx error x is not a compiletime constantthen one of the c standards 99 went ahead and allowed for variablelength arrays although i normally code against the ansi standard in c this has actually had an impact now that i am trying to pickup c11as far as i know c does not allow for variablelength arrays however many compilers allow it as an extension gcc the problem is now that i am trying to learn c11 i cannot tell if what i am coding is valid c or c extended with c99compatibility exstddefault random engine estduniform int thistributionint dconst int xdeint arrx compilesi cannot tell if this is valid c or not clearly the value of x is not known until runtime i think i may not understand the difference between c and c const,"['c++', 'c']" +766387,how is arrayoutofboundsexception possible in stringvalueofint why does this code sometimes produce arrayoutofboundsexception how is that even possible for stringvalueofintpublic static string iptostringbytestring bs if bs null bsisempty return null else stringbuilder sb new stringbuilder boolean started false for byte byt bs if started sbappend sbappendstringvalueofbyt 0xff started true return sbtostring javalangarrayindexoutofboundsexception 81914 at javalangintegergetcharsintegerjava458 at javalangintegertostringintegerjava402 at javalangstringvalueofstringjava3086 at commystuffmypackageiptostringmycodejava1325 at javautilconcurrentfuturetaskrunfuturetaskjava266 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava1142 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava617 at javalangthreadrunthreadjava745updatesi do not know the value of the byte when this occurs but it does not seem like it should be possible for any possible value of byteonce it happens once every invocation then errors out with the same exceptionenvironmentjava version 180 20javatm se runtime environment build 180 20b26java hotspottm 64bit server vm build 2520b23 mixed mode,['java'] +766400,backgroundtaskhostexe has exited with code 1 0x1 geofence issue i am writing windows phone 81 application using geofence api my problem is that i cannot trigger change of location in background task because app exits with code 1i have read multiple threads about this error but no solution solved my problemi have checked if my backgroundtask is a runtime component and it isi have checked name of my class and it is correcti have checked if i use any await function in my backgroundtask function and i did not find anyi have checked if i registered background task in app manifest and yes i did with entry point ofcin fact error appears even before running run function from backgroundtask namespace backgroundtask public sealed class geofencebackgroundtask ibackgroundtask public void runibackgroundtaskinstance taskinstance toasttemplatetype toasttemplate toasttemplatetypetoasttext02 xmldocument toastxml toastnotificationmanagergettemplatecontenttoasttemplate xmlnodelist toasttextelements toastxmlgetelementsbytagnametext toasttextelements0appendchildtoastxmlcreatetextnodemy app toasttextelements1appendchildtoastxmlcreatetextnodetest ixmlnode toastnode toastxmlselectsinglenodetoast xmlelement audio toastxmlcreateelementaudio toastnotification toast new toastnotificationtoastxml toastnotificationmanagercreatetoastnotifiershowtoast and my register function async private void registerbackgroundtask get permission for a background task from the user if the user has already answered once this does nothing and the user must manually update their preference via pc settings backgroundaccestatus backgroundaccestatus await backgroundexecutionmanagerrequestaccessasync regardless of the answer register the background task if the user later adds this application to the lock screen the background task will be ready to run create a new background task builder backgroundtaskbuilder geofencetaskbuilder new backgroundtaskbuilder geofencetaskbuildername geofencebackgroundtask geofencetaskbuildertaskentrypoint backgroundtaskgeofencebackgroundtask create a new location trigger var trigger new locationtriggerlocationtriggertypegeofence associate the locationi trigger with the background task builder geofencetaskbuildersettriggertrigger if it is important that there is user presence andor internet connection when oncompleted is called the following could be called before calling register systemcondition condition new systemconditionsystemconditiontypeuserpresent systemconditiontypeinternetavailable geofencetaskbuilderaddconditioncondition register the background task var geofencetask geofencetaskbuilderregister geofencetaskcompleted sender args my code here geofencetask geofencetaskbuilderregister i have no other ideas any help,['c#'] +766442,django package to generate random alphanumeric string i am building an app that has a separated frontend angular or some other js library and backend django to ensure some security of requests being sent to the server i want to append a url parameter say serversomeurlunique idsomethingunique i am storing this unique code on the machines localstorage for a specific time however i want to set this code using some sort of function on the server end which will not only generate this random alphanumeric text but also validate it based on incoming requests for examplewhen a user opens the app it will send a serversetcode which will respond with this randomly generated string which i will store to local storage using js on an outgoing request say servergetdatasomeparametersome dataunique idstring from local storage which the server can validate against the generating function and only then process the rest of the url is there a package or a module that could help me achieve the generation and validation i hope i could convey what i want as i am not able to find any solution for this short of writing the function to generate and test myself,['python'] +766448,c using declaration with typename in inheritingconstructors while reading this question i found a strange pointtemplate typename tclass subclass public baseclasstpublic using typename baseclasstbaseclass since typename baseclasstbaseclass should be injected class name not a constructor as far as i know it is the same case as thistemplate typename tclass basepublic typedef short some typetemplate typename tclass sub public basetpublic using typename basetsome typeto make sure i wrote a test codeinclude iostreamtemplate typename tclass basepublic base stdcout aan baseint stdcout aaintn baseconst char stdcout aaconst char n template typename tclass sub public baset using typename basetbaseint main subchar s1 subchar s23 subchar s3asdfhowever it runs on gcc 483 g stdc1y wall wextra werror pedantic testcpp o test testaintaaconst char it also runs without typename cat testcpp using basetbase g stdc1y wall wextra werror pedantic testcpp o test testaintaaconst char why did i get these results what did i miss,['c++'] +766580,how to convert string to jsonobject i am using a httprequest to get json from a web into a stringit is probably quite simple but i cannot seem to convert this string to a javaxjsonjsonobject how can i do this,['java'] +766582,how to prevent the flash when calling drawviewhierarchyinrectafterscreenupdates on ios 8 under ios 8 a call to uiviews self drawviewhierarchyinrectselfbounds afterscreenupdatesyesresults in a 1 frame flash of the image you can see it for a split second on the screen it only happens when afterscreenupdates parameter is yesthis is my complete code to take screenshotuigraphicsbeginimagecontextwithoptionsselfboundssize no sfcgcontextref ctx uigraphicsgetcurrentcontextcgcontextsavegstatectxcgcontextconcatctmctx selflayer affinetransformif self respondstoselectorselectordrawviewhierarchyinrectafterscreenupdates ios 7 self drawviewhierarchyinrectselfbounds afterscreenupdatesyes else ios 6 selflayer renderincontextctxuiimage image uigraphicsgetimagefromcurrentimagecontextcgcontextrestoregstatectxuigraphicsendimagecontextis there a workaround,"['ios', 'iphone']" +766583,how spring security addconfigure authenticationmanagerbuilder i am working on spring security javabased configurationi have created my own myauthenticationprovider which i want to register in the providermanager single instance of authenticationmanageri have found that providermanager has a list of providers to which i can register my single myauthenticationproviderhere is the part of my configurationconfigurationenablewebsecuritypublic class securityconfig extends websecurityconfigureradapter autowired public void configureglobalauthenticationmanagerbuilder auth throws exception authauthenticationprovidermyauthenticationprovider i found out that authenticationmanagerbuilder has parentauthenticationmanager defaultuserdetailsservice and many other fieldsmy questions arewhere is this autowired annotation adding authenticationmanagerbuilder auth from is the authenticationmanagerbuilder already created in the application contextwhat would be the default state of authenticationmanagerbuilder which is being injected by default state i mean will there be some parentauthenticationmanager authenticationproviders already registered in the authenticationmanagerbuilderif i am adding authauthenticationprovidermyauthenticationprovider does this mean that i am adding one more provider in the authenticationmanagerbuilderwhat does this mean taken from spring documentationthe name of the configureglobal method is not important however it is important to only configure authenticationmanagerbuilder in a class annotated with either enablewebsecurity enablewebmvcsecurity enableglobalmethodsecurity or enableglobalauthentication doing otherwise has unpredictable results,['java'] +766601,how to install laravel 50 i am having trouble getting a test instance of laravel 50 up and running so i can assist with this transition1 creating a new app from leads to the following error when running composer installerror typeerrorexception messageundefined index timezone fileprojectsindatusthispatchertestappvendorlaravelframeworksrcilluminatefoundationstartphp line167error typeerrorexception messageundefined index timezone fileprojectsindatusthispatchertestappvendorlaravelframeworksrcilluminatefoundationstartphp line167am i completely missing somethingupdate this questionanswer was only relevant when laravel 5 was in the development stage you should now reference the laravel documentation for how to install laravel,['php'] +766687,undefined symbols for architecture when add admob i am adding admob to my project but i get this error undefined symbols for architecture i386 objc class ekevent referenced from objcclassref in libgoogleadmobadsagadopenero objc class ekeventeditviewcontroller referenced from objcclassref in libgoogleadmobadsagadopenerold symbols not found for architecture i386clang error linker command failed with exit code 1 use v to see invocationi have addedstorekitaudiotoolboxmessageuisystemconfigurationcoregraphicsadsupportand also use objc link flagswhat is the problemthanks,['objective-c'] +766698,scalable nodejs application architecture in the past i was playing with nodejs only on my local machine so i only have experience with single process nodejs applications now i would like to create a web application which i could publish on the web this web app would be something like a multiplayer game using socketio for clientserver communication express for handling http requests grunt for task management and so on i would like to use other npm packages as well for various tasksi would like to design the architecture of this application toenable horizontal scalability later when i have lots of visitors i do not have to rewrite the whole appminimize the dependencies on different execution environments to maximize portabilityhow can i achieve this using node i guess the highlevel architecture would consistdifferent server processes each process would run an instance of express and would handle the incoming http requests there should be a load balancer somewhereoptionally background processes which could run periodically and process the shared datasince my application would be a multiplayer app where each user could interact with the other online users i should store some common state shared data somewhere which could be shared between those processesto keep things simple at first i do not have to persist this shared data so i think i should use an inmemory data store like rethisthe big picture would look something like thisthis design raises some questionshow to spawn the processesshould i use nodes child process or the cluster modules and start worker processes manually btw is it possible at all to start these manually for example if i deploy my app to heroku or nodejitsu or is there a better way to store these information in a config filei mean it would be better if i could configure how many server instances do i want not with editing the code but a config entrysystem boundariesif i spawn the processes manually then i guess all processes would run on the same virtual server if this server has let us say 4 cpu cores then you can spawn 4 node instances at a maximum because if you spawn more your cpu will make context switches which would ruin the overall performance what do i have to do if i need more process instances let us say i need 100 server instances do i have to deploy my app to 25 servers and spawn 4 processes on every serverit seems to me that hosting services like nodejitsu somehow hide this system boundary layer from you but i do not see how does it work in practice especially that there is this shared data provider component i guess this provider like a rethis server has to run on a different server so it would be available to all processes but in this case it could easily become a bottleneck is not itload balancerif i use some hosting service do i have to setup the load balancer layer myselfeditto answer a few practical questions at the first step i want to handle 4500 concurrent users socketio connections seamlessly this is an amount of visitors that i can realistically achieve but i am just curious that is it possible and if yes how to design an application architecture which could be easily scalable let us say that my website will become popular from one day to the next and instead of dealing with few hundred concurrent users next day i have to serve few thousandsas far as i know cloud hosting services like heroku and nodejitsu could be easily adapted to these scenarios you just have to increase the number of workers dynos whatever but it only works if you have the right application architectureregarding the shared data i do not want to persist it i just want to keep it inmemory some shared data provider on the one hand is needed because of socketio one user would be able to send a message to a user which is in another node for this i would use rethis as a shared data provider the number of transactions which rethis needs to handle equals to the amount of the sentrecieved messages with socketio 101500 messagesecon the other hand some shared data provider is needed because i want to connect the users based on several criteria later background processes would periodically recalculate refine the probability the weight of those connections i already have some idea how to implement efficient data structure to handle fast insertsremoves to this inmemory table so the shared data provider component would consist of some serverside code maybe nodejs which could store these connections i know it is tldr but i hope it will answer all your technical questions about the problem,['javascript'] +766716,do something every x minutes in swift how can i run a function every minutein javascript i can do something like setinterval does something similar exist in swiftwanted outputhello world once a minute,['ios'] +766786,warning implicit conversion loses integer precision in xcode 6 i know it could be a duplicate but i got about 30 implicit conversion loses integer precision warnings in my ios project after updating xcode to version 6first examplensarray stations self stationsjsonkey item listint newsize stationscount 1 implicit conversion loses integer precision unsigned long to intsecond example uitableviewcell tableviewuitableview tableview cellforrowatindexpathnsindexpath indexpath int index indexpathrow 2 implicit conversion loses integer precision long to int i know what the warning means using nsinteger can help to avoid this warning i do not understand why there was no warnings in xcode 5 and why there is no warning after i change the line int index indexpathrow 2to int index indexpathrow 2i,"['ios', 'objective-c']" +766787,mysql does not start when upgrading osx to yosemite or el capitan i know similar questions exist such as mysql with mamp does not work with osx yosemite 1010 however i do have mamp nor xampp installed on my computerwhen i try to start mysql from the prefpane nothing happenswhen i try to start mqsql from the command line via sudo usrlocalmysqlsupportfilesmysqlserver start i get starting mysql error the server quit without updating pid fileusrlocalmysqldataadamglocalpidany and all help would be appreciated i can supply any file output necessary,['mysql'] +766815,android duplicate class error when including apache poi i have got a problem with the apache poi excel api xlsx i am using android studio and i have added the poi libs to the libs folders this error is popping up for some reason see below how would i solve it could you please explain how you identified the issuexmlbeans260 poiooxmlschemas310120140818 poiooxml310120140818 poi310120140818 log4j1213 junit411 dom4j161 commonslogging11 commonscodec15thanksmy buildgradle looks like the following excluding the generic other stuffdependencies compile filetreeinclude jar dir libs android packagingoptions exclude metainflicense exclude metainfnotice exclude metainflicensetxt exclude metainfnoticetxt my appiml has no duplicate entries eithererrorerrorclass orgapachexmlbeansxmlstreamlocation has already been added to output please remove duplicate copies compiler that did not target the modern class file format the recommended orgapachelog4jchainsawcontrolpanel1 that does not come with an associated enclosingmethod attribute this class was probably produced by a solution is to recompile the class from source using an uptodate compiler 1 error aborting,"['java', 'android']" +766820,sqlalchemy performing a bulk upsert if exists update else insert in postgresql i am trying to write a bulk upsert in python using the sqlalchemy module not in sqli am getting the following error on a sqlalchemy addsqlalchemyexcintegrityerror integrityerror duplicate key value violates unique constraint posts pkeydetail key idtest1234 already existsi have a table called posts with a primary key on the id columnin this example i already have a row in the db with idtest1234 when i attempt to dbsessionadd a new posts object with the id set to test1234 i get the error above i was under the impression that if the primary key already exists the record would get updated how can i upsert with flasksqlalchemy based on primary key alone is there a simple solutionif there is not i can always check for and delete any record with a matching id and then insert the new record but that seems expensive for my situation where i do not expect many updates,['python'] +766906,material design support library are there efforts underway to backport the new material design style and widgets to prel versions of android similar to the holoeverywherelibrary the creator of that library has initialized an empty githubrepository but it does not seem to be in active development i know there is a backport of lstyle dialogs and the floating action button but there are obviously so many more widgets that have changed in android l has the android team made any announcement whether they are working on a support library exceeding whats currently available,['android'] +766990,loading initial data with django 17 and data migrations i recently switched from django 16 to 17 and i began using migrations i never used southbefore 17 i used to load initial data with a fixtureinitial datajson file which was loaded with the python managepy syncdb command when creating the databasenow i started using migrations and this behavior is deprecated if an application uses migrations there is no automatic loading of fixtures since migrations will be required for applications in django 20 this behavior is considered deprecated if you want to load initial data for an app consider doing it in a data migration the official documentation does not have a clear example on how to do it so my question is what is the best way to import such initial data using data migrations write python code with multiple calls to mymodelcreateuse or write a django function like calling loaddata to load data from a json fixture filei prefer the second optioni do not want to use south as django seems to be able to do it natively now,['python'] +767141,optionsmenu of fragments in viewpager showing each others buttons i have got three fragments in a viewpagertwo of these fragments have their own version of the oncreateoptionsmenu method overridepublic void oncreateoptionsmenumenu menu menuinflater inflater superoncreateoptionsmenumenu inflater set up 1 action button inflaterinflatermenuhome snapshot add menuoverridepublic void oncreateoptionsmenumenu menu menuinflater inflater superoncreateoptionsmenumenu inflater set up 2 action buttons inflaterinflatermenuhome snapshot send menuthe home activity has a basic oncreateoptionsmenu method overridepublic boolean oncreateoptionsmenumenu menu return falsein the oncreate method each fragment calls the methodsethasoptionsmenutrueeach of the menu items have the tagandroidshowasactionalwaysseems like as i open the activity all three buttons appearhowever when i scroll through them the wrong ones magically thisappearit feels like the activity is calling every fragments options menu on activity creation and then changes the menu appropriately when i swipe left and righti have checked the menus but not sure whats wronganything you reckon i need to check i am a little out of ideasthanks,['android'] +767201,how to unit test a joomla 25 component can someone provide an example of how to unit test a joomla 25 component i am working through this joomla mvc component example which does not include unit tests and i cannot find a full example anywhere my main questions arewhere to put component test codehow to run component unit testsis my test code correctthe joomla documentation seems incomplete and fragmented i have read what i can find on unit testing cannot post links due to low rep which seem to be about testing joomla itself rather than extensions the closest i have found is this which i have based my dummy test onwhat i have done so farcomponent directory structurehelloworldadmintestsbootstrapphpphpunitxmlmodelhelloworldstestphpsitehelloworldxmlto run the tests i installcopy the component to my joomla installation i then run the following command from joomlaadministrationcomponentscom helloworldtestsphp phpunit42phar bootstrap bootstrapphp from which i receivefatal error class contentcontroller not found in cinetpubwrootws cairnstestadministratorcomponentscom helloworldtestsmodelshelloworldstestphp on line 5bootstrapphpphperror reportinge alldefine jexec 1definebasepathrealpathdirname file definejoomla pathrealpathdirname file definejoomla admin pathrealpathdirname file serverhttp host localhost serverrequest method getif file existsjoomla admin path definesphp include once joomla admin path definesphpif defined jdefines definejpath base joomla admin path require once jpath base includesdefinesphprequire once jpath base includesframeworkphprequire once jpath base includeshelperphprequire once jpath base includestoolbarphpdefinejpath componentjoomla admin pathcomponentscom contentapp jfactorygetapplicationadministratorinclude basepathcontrollerphpmodelshelloworldstestphpphpclass helloworldstest extends phpunit framework testcase public function testlist c new contentcontroller model cgetmodelhelloworlds worlds modelgetitems var dumpworlds thisassertnotemptyworlds phpunitxmlphpunit bootstrapbootstrapphp colorstrue converterrorstoexceptionstrue convertnoticestoexceptionstrue convertwarningstoexceptionstrue processisolationfalse stoponfailurefalse syntaxcheckfalse verbosetruephpunit,['php'] +767212,how to detect the mobile connection is 2g3gwifi using javascript i have a similar requirement as in link below but i have to handle it by using javascript where i have to detect whether the mobile internet connection is 2g3g or it is wifi based on connection i have to perform diffent operations note mobile can b of any os like andriod iosbb i need to handle any mobile osis there a way to detect what kind of connection im using wifi 3g or ethernet request masters to help me with inputs thanks,['javascript'] +767290,tally database synchronization with c application i want to make an application to sync tally sales order and sales invoice from tally to our sql database currently for testing purpose i am using tally erp 9 educational versioni have created some sales orders in tally and need all order with their details from tally using tally odbc sql queryuptil as per my research i am getting few sales order details like voucher numberorder datevoucher type etc from tally odbc table companyvoucher but few details came empty although related data exist in tally order like reference party name etc also i am unable to find tally odbc table to get few other sales order related data like item name item number item quantity rate and order total order no etccan anybody suggest sql query or tally odbc table from where i can find these order related data also i am not sure if we can not access these details due to educational version and any limitations on educational version on access of these details so please suggest me on this,['c#'] +767312,multiple markers google maps embed api i need to place several markers which specified by coordinates on embed map i know how to do it for one marker but do not know for multipleiframe width100 height100 frameborder0 scrollingno marginheight0 marginwidth0 srcmsa0ieutf8tmll407904273945541spn04626771056747outputembediframe,['html'] +767379,ios 8 embedded youtube in html web app fails youtube ios8 media load issue media plays successfully while in safari but when the app is loaded from a home screen web clip playing the video failsmoreover tapping a link to navigate away from the page while the media is failing to load results in a complete crash of the app to the home screenhere is a link that demonstrates this obviously run on your idevice you can run it initially in safari browser it will work fine install it as a home screen icon playing video will fail and clicking the bottom link will crash the appthe code that works when the app is loaded up in the safari browser isiframe width100 maxwidth432 height270 srcwyoutubecomembed j4krmaygji frameborder0 allowfullscreeniframeanyone have any thoughts is this bad embed code,['html'] +767391,jar extracting specific files i have class and java files in jar archive is there any way to extract only java files from iti have tried this command but it does not workjar xf jarfilejar java,['java'] +767419,how to thisplay highchart series line marker symbol from tooltip formatter by default highcharts thisplay the line marker symbol in the tooltip function containerhighcharts xaxis categories jan feb mar apr may jun jul aug sep oct nov dec series data 299 715 1064 1292 1440 1760 1356 1485 2164 1941 956 544 data 1941 956 544 299 715 1064 1292 1440 1760 1356 1485 2164 using tooltip formatter how can we add the line marker symbolfunction containerhighcharts tooltip formatter function return thisxbrthisseriesname thisy xaxis categories jan feb mar apr may jun jul aug sep oct nov dec series data 299 715 1064 1292 1440 1760 1356 1485 2164 1941 956 544 data 1941 956 544 299 715 1064 1292 1440 1760 1356 1485 2164 i want to add the circle symbol in front of the series name from formatter like it is in default scenario,['javascript'] +767477,method getlogger no longer a member of logger in log4j2 i have the log4japi200jar and log4jcore202jar import into my build path but somehow the following code were failimport orgapachelogginglog4jcoreloggerpublic class theclass private static logger log loggergetloggertheclassclassand the error message shows thatthe method getloggerclasstheclass is undefined for the type loggeri am just so curious is getlogger no longer a valid method in logger,['java'] +767487,how to handle mixed rtl ltr languages in notifications backgroundandroid 43 has added a lot of support for rtl righttoleft languages such as hebrew and arabicthe problemeven though there is textdirection layoutdirection and gravity i cannot find the equivalents for the notification builder not even in the compatibility librarythis means that if there are hebrew and english words together the order is wrongfor example and i write in english for simplicity instead of x called y you get y called x suppose called is a word in hebrew as the string is supposed to be in this formatstring namenotification1s called 2sstringnote x and y can be either rtl or ltr words and even numbersthe requirements is that in hebrew the word on the right should be x then the word called but in hebrew of course and then y on the left as i have tried to show in the english analogy example it is the oppositewhat i have trieda i have tried to search the documentation and all i have found is that i will probably need to override the layout but that is not a good solution the reasonsi might not use the correct styling of android it is not future proof for next android versions which might use a different stylingit does not support the ticker textb i have also tried to investigate which special characters will force the text direction to be different and it worked by adding u200f to the beginning and end of the text to show but it has a few flawsit is not as flexible as the other attributesi am not sure i use the official way to handle this problemi need to add this for each time i use a notificationit does not work at all for tickertext only for notifications and even then not for all casesheres a sample code prepares a string to be shown in a notification so that it will be shown even on rtl languages targetapibuildversion codesjelly bean mr1public static string preparenotificationtextfinal context context final string text if versionsdk int version codesjelly bean mr1 return text final boolean isrtl contextgetresourcesgetconfigurationgetlayoutdirection viewlayout direction rtl if isrtl return text return u200f text u200fc i could also switch between the 1 and 2 in the string but this does not handle all cases plus it is even more confusing to the translatorsthe questionis there any way to make the notification builder handle texts correctly for both notifications and tickertext any way to tweak it without actually making totally new layouts for the notifications or change strings which might not be in the same native style of android whats the official way to handle such a thing,['android'] +767517,factory method in base access protected ctor in derived i want to all objects that derive from initable to call terminate on destruction for this i create a shared ptr with custom deleter my problem is that i cannot access the protected ctor of derived classes in order to create the instance in initable factory method the ctor should be protected in order to prevent creation of instances without using the factory methodclass initable public virtual void terminate 0 templatetypename t typename ts static shared ptrt make initableconst ts args return shared ptrtnew tstdforwardconst tsargs initable aptr cout custom deleter endl class b public initable friend class initable i would like to avoid declaring as friend every derived class what can i do,['c++'] +767607,could not load systemwebcors in owin startupcs i have a net 451 application using web api 2 and running in my local azure emulator i have some owin components installed and in my startupcs file within the configurationiappbuilder app function i have the following code block and the last line causes an exceptionhttpconfiguration httpconfiguration new httpconfigurationwebapiconfigregisterhttpconfigurationappusewebapihttpconfigurationappusecorsmicrosoftowincorscorsoptionsallowallthis line is causing an exception could not load file or assembly systemwebcors version50 cultureneutral publickeytoken31bf3856ad364e35 or one of its dependenciesi am having trouble figuring out why nuget didnt install this if it is a dependency additionally i am not able to find a corresponding dll already installed to add a reference myself nor the correct nuget package to install to provide said dllhas anyone experienced a similar issue if so perhaps you could point me in the right direction,['asp.net'] +767609,how to use avsamplebufferthisplaylayer in ios 8 for rtp h264 streams with gstreamer after getting notice of the hwh264decoder being available to programmers in ios 8 i want to use it now there is a nice introduction to direct access to video encoding and decoding from wwdc 2014 out there you can take a look herebased on case 1 there i started to develop an application that should be able to get an h264rtpudpstream from gstreamer sink it into an appsinkelement to get direct access to the nal units and do the conversion to create cmsamplebuffers which my avsamplebufferthisplaylayer can thisplay then the interesting piece of code doing all that is the following gstreamerbackendm import gstreamerbackendhnsstring const nalutypesstrings unspecified nonvcl coded slice of a nonidr picture vcl coded slice data partition a vcl coded slice data partition b vcl coded slice data partition c vcl coded slice of an idr picture vcl supplemental enhancement information sei nonvcl sequence parameter set nonvcl picture parameter set nonvcl access unit delimiter nonvcl end of sequence nonvcl end of stream nonvcl filler data nonvcl sequence parameter set extension nonvcl prefix nal unit nonvcl subset sequence parameter set nonvcl reserved nonvcl reserved nonvcl reserved nonvcl coded slice of an auxiliary coded picture without partitioning nonvcl coded slice extension nonvcl coded slice extension for depth view components nonvcl reserved nonvcl reserved nonvcl unspecified nonvcl unspecified nonvcl unspecified nonvcl unspecified nonvcl unspecified nonvcl unspecified nonvcl unspecified nonvcl unspecified nonvclstatic gstflowreturn new samplegstappsink sink gpointer user data gstreamerbackend backend bridge gstreamerbackend user data gstsample sample gst app sink pull samplesink gstbuffer buffer gst sample get buffersample gstmemory memory gst buffer get all memorybuffer gstmapinfo info gst memory map memory info gst map read int startcodeindex 0 for int i 0 i 5 i if infodatai 0x01 startcodeindex i break int nalu type uint8 tinfodatastartcodeindex 1 0x1f nslognalu with type received nalutypesstringsnalu type ifbackendsearchforspsandpps if nalu type 7 backendspsdata nsdata datawithbytesinfodatastartcodeindex 1 length infosize 4 if nalu type 8 backendppsdata nsdata datawithbytesinfodatastartcodeindex 1 length infosize 4 if backendspsdata nil backendppsdata nil const uint8 t const parametersetpointers2 const uint8 tbackendspsdata bytes const uint8 tbackendppsdata bytes const size t parametersetsizes2 backendspsdata length backendppsdata length cmvideoformatdescriptionref videoformatdescr osstatus status cmvideoformatdescriptioncreatefromh264parametersetskcfallocatordefault 2 parametersetpointers parametersetsizes 4 videoformatdescr backend setvideoformatdescrvideoformatdescr backend setsearchforspsandppsfalse nslogfound all data for cmvideoformatdescription creation status noerr successfully failed if nalu type 1 nalu type 5 cmblockbufferref videoblock null osstatus status cmblockbuffercreatewithmemoryblocknull infodata infosize kcfallocatornull null 0 infosize 0 videoblock nslogblockbuffercreation status kcmblockbuffernoerr successfully failed const uint8 t sourcebytes uint8 tinfosize 24 uint8 tinfosize 16 uint8 tinfosize 8 uint8 tinfosize status cmblockbufferreplacedatabytessourcebytes videoblock 0 4 nslogblockbufferreplace status kcmblockbuffernoerr successfully failed cmsamplebufferref sbref null const size t samplesizearray infosize status cmsamplebuffercreatekcfallocatordefault videoblock true null null backendvideoformatdescr 1 0 null 1 samplesizearray sbref nslogsamplebuffercreate status noerr successfully failed cfarrayref attachments cmsamplebuffergetsampleattachmentsarraysbref yes cfmutabledictionaryref dict cfmutabledictionaryrefcfarraygetvalueatindexattachments 0 cfdictionarysetvaluedict kcmsampleattachmentkey thisplayimmediately kcfbooleantrue nslogerror status backendthisplaylayererror backendthisplaylayerstatus avqueuedsamplebufferrenderingstatusunknownunknownbackendthisplaylayerstatus avqueuedsamplebufferrenderingstatusrenderingrenderingfailed thispatch asyncthispatch get main queue backendthisplaylayer enqueuesamplebuffersbref backendthisplaylayer setneedsthisplay gst memory unmapmemory info gst memory unrefmemory gst buffer unrefbuffer return gst flow okimplementation gstreamerbackend instancetypeinit if self super init selfsearchforspsandpps true selfppsdata nil selfspsdata nil selfthisplaylayer avsamplebufferthisplaylayer alloc init selfthisplaylayerbounds cgrectmake0 0 300 300 selfthisplaylayerbackgroundcolor uicolor blackcolorcgcolor selfthisplaylayerposition cgpointmake500 500 selfqueue thispatch get global queuethispatch queue priority default 0 thispatch asyncselfqueue self app function return self voidstart ifgst element set stateselfpipeline gst state playing gst state change failure nslogfailed to set pipeline to playing voidapp function gstelement udpsrc rtphdepay capsfilter gmaincontext context glib context used to run the main loop gmainloop main loop glib main loop context g main context new g main context push thread defaultcontext g set application name appsink selfpipeline gst pipeline new testpipe udpsrc gst element factory make udpsrc udpsrc gstcaps caps gst caps new simpleapplicationxrtp media g type string video clockrate g type int 90 encodingname g type string h264 null g object setudpsrc caps caps port 50 null gst caps unrefcaps rtphdepay gst element factory makertph264depay rtph264depay capsfilter gst element factory makecapsfilter capsfilter caps gst caps new simplevideoxh264 streamformat g type string bytestream alignment g type string nal null g object setcapsfilter caps caps null selfappsink gst element factory make appsink appsink gst bin add many gst bin selfpipeline udpsrc rtphdepay capsfilter selfappsink null ifgst element link many udpsrc rtphdepay capsfilter selfappsink null nslogcannot link gstreamer elements exit 1 ifgst element set stateselfpipeline gst state ready gst state change success nslogcould not change to ready gstappsinkcallbacks callbacks null null new sample null null gst app sink set callbacks gst app sinkselfappsink callbacks bridge gpointerself null main loop g main loop new context false g main loop run main loop free resources g main loop unref main loop main loop null g main context pop thread defaultcontext g main context unref context gst element set state gst element selfpipeline gst state null gst object unref gst object selfpipelineendwhat i get when running the app and starting to stream to the ios devicenalu with type sequence parameter set nonvcl receivednalu with type picture parameter set nonvcl receivedfound all data for cmvideoformatdescription creation successfullynalu with type coded slice of an idr picture vcl receivedblockbuffercreation successfullyblockbufferreplace successfullysamplebuffercreate successfullyerror null statusunknownnalu with type coded slice of a nonidr picture vcl receivedblockbuffercreation successfullyblockbufferreplace successfullysamplebuffercreate successfullyerror null statusrendering repetition of the last 5 linesso it seems to decode as it should do but my problem is that i could not see anything in my avsamplebufferthisplaylayer it might be a problem with the kcmsampleattachmentkey thisplayimmediately but i have set it like i was told to here see the important noteevery idea is welcome,['ios'] +767644,python numpy einsum multiply a stack of matrices for performance reasons i am curious if there is a way to multiply a stack of a stack of matrices i have a 4d array 500 201 2 2 its basically a 500 length stack of 20122 matrices where for each of the 500 i want to multiply the adjacent matrices using einsum and get another 20122 matrix i am only doing matrix multiplication on the 2x2 matrices at the end since my explanation is already heading off the rails i will just show what i am doing now and also the reduce equivalent and why its not helpful because its the same speed computationally preferably this would be a numpy oneliner but i do not know what that is or even if its possible codearr rand50020122def loopmultarr arrmult arr0 for i in range1lenarr arrmult npeinsumfijfjkfik arrmult arri return arrmultdef myeinsuma1 a2 return npeinsumfijfjkfik a1 a2a1 loopmultarra2 reducemyeinsum arrprint npalla1 a2print shapea1 print shapea2timeit loopmultarrtimeit reducemyeinsum areturnstrue201 2 2201 2 210 loops best of 3 348 ms per loop10 loops best of 3 352 ms per loopany help would be appreciated things are functional but when i have to iterate this over a large series of parameters the code tends to take a long time and i am wondering if there is a way to avoid the 500 iterations through a loop,['python'] +767668,getting itms4238 redundant binary upload error no mater what i change the build version or app version to i rejected a binary i had which was 10 10the status went into rejected by developeri went to upload a new binary and ran into this issue i then saw that i needed to increment my buildi increased both the app version and build to 11 this was a mistakei got some error about the app version not matching understoodthen i tried app version 10 and many different build numbers11 101 12 13 103nothing worksi keep getting this error there is only one build listed on itunes connect 10i tried submitting with no binary and it says i need onei even tried changing the app version to 11 in itunes connected and then uploading11 10 and that fails as well with the same duplicate issueanyone ever have this issue,['ios'] +767706,is sanitizing json necessary i think it is a wellknown best practice on the web to mistrust any input the sentenceall input is evilis probably the most cited quote with respect to input validation now for html you can use tools such as dompurify to sanitize itmy question is if i have a nodejs server running express and bodyparser middleware to receive and parse json do i need to run any sanitizing as wellmy maybe naive thoughts on this are that json is only data no code and if somebody sends invalid json bodyparser which uses jsonparse internally will fail anyway so i know that my app will receive a valid javascript object as long as i do not run eval on that or call a function i should be fine should not iam i missing something,['javascript'] +767849,what does a visual studio 2013 project makes it a katana project i just started my struggle to understand owin and katana following the aspnet tutoriali created a blank aspnet project in vs2013 and added a nuget package reference to microsoftowinhostsystemweb the project i created is bear blank as shownthis contains nothing except assemblyinfocs webconfig and packagesconfig now when i runf5 this it says no assembly found containing an owinstartupattributeno assembly found containing a startup or assemblynamestartup class to thisable owin startup thiscovery add the appsetting owinautomaticappstartup with a value of false in your webconfig to specify the owin startup assembly class or method add the appsetting owinappstartup with the fully qualified startup class or configuration method name in your webconfignow the question is how come just by adding a nuget reference to microsoftowinhostsystemweb it started to look for something specific to owin like startup class and so on as indicated in the error messagei mean i ran a different project without that nuget reference and the error message is totally different nothing seems to have changed at least in the two files assemblyinfocs webconfig by adding the nuget reference as i understand adding the nuget added a packagesconfig file and added some project reference also i have compared the project properties for the two projects tab by tab and i did not find any difference so i wonder what in the world is causing the owin project look for a startup class,['asp.net'] +767861,c unexpected implict conversion the following code compiles due to the implicit conversion for char i am not sure why since the only implicit conversion i would expect and expect to fail is from char const to size tinclude cstddefstruct foo int operatorsize t i const return 1 operator char const return a int main foo f fhello compilation error desired herewhat is the implicit conversion here that allows this to compile if i remove operator char or make it explicit then the compile fails at the desired locationthe class that this code is extracted from really does need both the implicit conversion and the operator so is there a way i can prevent the behaviour without making the conversion explicit,['c++'] +767929,a better way to handle template creation trying to figure out a better design for thisconsider that we have a template image class that inherits from a template matrix library in this case eigen but it could be anythingtemplate typename tclass image public eigenmatrix t eigendynamic eigendynamic eigenrowmajornow think of the case that we want to write a function to handle reading images from a fileof course images can be of different types ie unisnged char uint16 t float and even have different channels as in grayscale rgb or even rgbaso we could have of course template classes to easily handle thisas inimagergbunisgned char or imagergbafloatits simple when one knows the type of the image say monochrome 8bitimageunisgned char image readimageconst char const filenameor it could even beimageunisgned char imagebool b readimageconst char const filename imageunisgned char imagehowever when reading an image file we never know the type prior to reading the imagefor example tiff and png both support 8bit and 16 bit with tiff even supporting floatin such cases its impossible to use any of the functions mentioned above however we can have a temmplate factory class to sort that outfor that we first need to introduce a baseimage classclass baseimagepublic inline baseimage virtual inline baseimage virtual inline int width const 0 virtual inline int height const 0 virtual inline int depth const 0 etctemplate typename tclass image public baseimage public eigenmatrix t eigendynamic eigendynamic eigenrowmajorthen we can have our factory class where we pass our unsigned char float etc and let it handle the creationclass imagefactory typename t static baseimage createimageconst t const src const int width const int height const int depth if depth 1 return new imaget else if depth 3 return new imagergbt etc of course this forces me to use dynamic allocation and inheritancei guess i can get around the dynamic allocation by hiding it inside a class that takes care of itin the constructor the factory clas will be calledclass image2public image2const char const path where readimage and external function that will call imagefactory pbaseimage readimagepath image2private baseimage pbaseimagein either case my baseimage class will have to expose all the functionality that i need to use from my matrix library which kinda defies the purpose of inheritingthe question is then if there is a better design than could be used here cause its becoming quite cumbersome,['c++'] +768029,mvc aspnet is using a lot of memory if i just browse some pages on the app it sits at around 500mb many of these pages access the database but at this point in time i only have roughly a couple of rows each for 10 tables mostly storing strings and some small icons that are less than 50kbthe real problem occurs when when i download a file the file is roughly 140mb and is stored as a varbinarymax in the database the memory usage suddenly rises to 13gb for a split second and then falls back to 1gb the code for that action is herepublic actionresult downloadipaint buildid var build unitofworkrepositorybuildgetbyidbuildid var buildfiles unitofworkrepositorybuildfilesgetbyidbuildid if buildfiles null throw new httpexception404 item not found var app unitofworkrepositoryappgetbyidbuildappid var filename appname ipa appdownloads unitofworkrepositoryappupdateapp unitofworksave return downloadfilebuildfilesipa filenameprivate actionresult downloadfilebyte file string filename string type applicationoctetstream if file null throw new httpexception500 empty file if filenameequals throw new httpexception500 no name return filefile type filename on my local computer if i do not do anything the memory usage stays at 1gb if i then go back and navigate to some pages it falls back down to 500mb on the deployment server it stays at 16gb after the first download no matter what i do i can force the memory usage to increase by continually downloading files until it reaches 3gb where it drops back down to 16gb in every controller i have overriden the thispose method as soprotected override void thisposebool thisposing unitofworkthispose basethisposethisposingthis refers topublic void thispose thisposetrue gcsuppressfinalizethispublic void thisposebool thisposing if thisposed if thisposing contextthispose thisposed trueso my unit of work should be thisposed every time the controller is thisposed i am using unity and i register the unit of work with a heirarchical lifetime managerhere are a few of screenshots from the profileri believe this could be the problem or i am going down the wrong track why would find use 300mb editrepositorypublic class repositorytentity irepositorytentity where tentity class internal idbcontext context internal idbsettentity dbset public repositoryidbcontext context context context dbset contextsettentity public virtual ienumerabletentity getall return dbsettolist public virtual tentity getbyidobject id return dbsetfindid public tentity getsingleexpressionfunctentity bool predicate return dbsetwherepredicatesingleordefault public virtual repositoryquerytentity query return new repositoryquerytentitythis internal ienumerabletentity get expressionfunctentity bool filter null funciqueryabletentity iorderedqueryabletentity orderby null listexpressionfunctentity object includeproperties null iqueryabletentity query dbset if includeproperties null includepropertiesforeachi queryincludei if filter null query querywherefilter if orderby null query orderbyquery return querytolist public virtual void inserttentity entity dbsetaddentity public virtual void updatetentity entity dbsetattachentity contextentryentitystate entitystatemodified public virtual void deleteobject id var entity dbsetfindid deleteentity public virtual void deletetentity entity if contextentryentitystate entitystatedetached dbsetattachentity dbsetremoveentity edit 2i ran dotmemory for a variety of scenarios and this is what i gotthe red circles indicate that sometimes there are multiple rises and drops happening on one page visit the blue circle indicates download of a 40mb file the green circle indicates download of 140mb file furthermore a lot of the time the memory usage keeps on increasing for a few more seconds even after the page has instantly loaded,"['c#', 'asp.net']" +768060,netbeans deploy javafx app admin rights how can i deploy a javafx application for windows so that the exe containing my jar launches with admin rights i had this working with my old method of deployment but the netbeans way seems much easier and more efficient so i would really like to use it it helps eliminate a lot of extra steps that i normally need to doi am sure the solution is right under my nose but i just cannot seem to figure it outbest regardsalen,['java'] +768118,not able to run wkhtmltopdf commad through exec function in php but same command works on command line i am using wkhtmltopdf to generate pdfs from html i am trying to run the below command through php exec function but its does not generate the pdf i does not show any error though but when i ran the same command through command line it worksbelow is my php code taht i am using to execute the pdf generate commandcommand wkhtmltopdf s a4 inputhtmlfilepathtesthtml outputfilepathoutputpdfexeccommandsome info about my setupoperating system ubuntu 1204php version 543any help would be appreciated thanks,['php'] +768285,should main method copy input arguments can someone imagine when this codepublic static void mainfinal string args do somethingshould become thispublic static void mainfinal string args string argscopy docopyargs do somethingin our company we have a sonar rule that forces such coping or arguments for all methods i can imagine why it can be important for standard methods but i cannot find any benefit of having it done at a start of tools main method am i missing something,['java'] +768289,androidcontentresresourcesnotfoundexception string resource id 0x1 error i am using listview to dynamically add checkboxes in android i am using a contextadapter class to add inflate the listview my error log is as follows0923 13450 eandroidruntime1192 fatal exception main0923 13450 eandroidruntime1192 process comprojectattendancemanager pid 11920923 13450 eandroidruntime1192 androidcontentresresourcesnotfoundexception string resource id 0x10923 13450 eandroidruntime1192 at androidcontentresresourcesgettextresourcesjava2440923 13450 eandroidruntime1192 at androidwidgettextviewsettexttextviewjava380923 13450 eandroidruntime1192 at comprojectattendancemanagercustomadaptergetviewcustomadapterjava310923 13450 eandroidruntime1192 at androidwidgetabslistviewobtainviewabslistviewjava22630923 13450 eandroidruntime1192 at androidwidgetlistviewmeasureheightofchildrenlistviewjava12630923 13450 eandroidruntime1192 at androidwidgetlistviewonmeasurelistviewjava11750923 13450 eandroidruntime1192 at androidviewviewmeasureviewjava164970923 13450 eandroidruntime1192 at androidwidgetrelativelayoutmeasurechildrelativelayoutjava6890923 13450 eandroidruntime1192 at androidwidgetrelativelayoutonmeasurerelativelayoutjava4730923 13450 eandroidruntime1192 at androidviewviewmeasureviewjava164970923 13450 eandroidruntime1192 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava51250923 13450 eandroidruntime1192 at androidwidgetframelayoutonmeasureframelayoutjava3100923 13450 eandroidruntime1192 at androidviewviewmeasureviewjava164970923 13450 eandroidruntime1192 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava51250923 13450 eandroidruntime1192 at comandroidinternalwidgetactionbaroverlaylayoutonmeasureactionbaroverlaylayoutjava3270923 13450 eandroidruntime1192 at androidviewviewmeasureviewjava164970923 13450 eandroidruntime1192 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava51250923 13450 eandroidruntime1192 at androidwidgetframelayoutonmeasureframelayoutjava3100923 13450 eandroidruntime1192 at comandroidinternalpolicyimplphonewindowdecorviewonmeasurephonewindowjava22910923 13450 eandroidruntime1192 at androidviewviewmeasureviewjava164970923 13450 eandroidruntime1192 at androidviewviewrootimplperformmeasureviewrootimpljava19160923 13450 eandroidruntime1192 at androidviewviewrootimplmeasurehierarchyviewrootimpljava130923 13450 eandroidruntime1192 at androidviewviewrootimplperformtraversalsviewrootimpljava12950923 13450 eandroidruntime1192 at androidviewviewrootimpldotraversalviewrootimpljava10923 13450 eandroidruntime1192 at androidviewviewrootimpltraversalrunnablerunviewrootimpljava56700923 13450 eandroidruntime1192 at androidviewchoreographercallbackrecordrunchoreographerjava7610923 13450 eandroidruntime1192 at androidviewchoreographerdocallbackschoreographerjava5740923 13450 eandroidruntime1192 at androidviewchoreographerdoframechoreographerjava5440923 13450 eandroidruntime1192 at androidviewchoreographerframethisplayeventreceiverrunchoreographerjava7470923 13450 eandroidruntime1192 at androidoshandlerhandlecallbackhandlerjava7330923 13450 eandroidruntime1192 at androidoshandlerthispatchmessagehandlerjava950923 13450 eandroidruntime1192 at androidoslooperlooplooperjava1360923 13450 eandroidruntime1192 at androidappactivitythreadmainactivitythreadjava50170923 13450 eandroidruntime1192 at javalangreflectmethodinvokenativenative method0923 13450 eandroidruntime1192 at javalangreflectmethodinvokemethodjava5150923 13450 eandroidruntime1192 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava7790923 13450 eandroidruntime1192 at comandroidinternaloszygoteinitmainzygoteinitjava5950923 13450 eandroidruntime1192 at dalviksystemnativestartmainnative methodcontextadapter class is as followsimport androidappactivityimport androidcontentcontextimport androidviewlayoutinflaterimport androidviewviewimport androidviewviewgroupimport androidwidgetarrayadapterimport androidwidgetcheckboximport androidwidgettextviewpublic class customadapter extends arrayadapterlistdatalistdata itemsnullcontext contextpublic customadaptercontext context listdata resource supercontextrlayoutactivity list row resource todo autogenerated constructor stub thiscontextcontext thisitemsresourceoverridepublic view getviewint position view convertview viewgroup parent todo autogenerated method stub layoutinflater inflatoractivitycontextgetlayoutinflater convertviewinflatorinflaterlayoutactivity list row parent false textview nametextviewconvertviewfindviewbyidridnametv textview rollnotextviewconvertviewfindviewbyidridrollnotv checkbox cbcheckboxconvertviewfindviewbyidridstudentcb namesettextitemspositiongetname rollnosettextitemspositiongetrollno ifitemspositiongetvalue1 cbsetcheckedtrue else cbsetcheckedfalse return convertview my listdata classpackage comprojectattendancemanagerpublic class listdata string nameint valuerollnolistdatastring nameint rollno int value thisnamename thisrollnorollno thisvaluevaluepublic string getname return thisnamepublic int getrollno return thisrollnopublic int getvalue return thisvalueinside the oncreate function in the activity i am doing thislistview lvlistdata itemscustomadapter adapternew customadapterthisitemslvsetadapteradapterit would be of great help is someone could point out the mistake in my codethanks cheers,['android'] +768337,qt on android reducing the binary size am using qt to build app on android qt quick mainly its really nice but my main problem is the start up size is around 27 mb which is huge for initial size is there a way to reduce this size,"['android', 'c++']" +768447,g does not include files it says it includes for c11 short versionwhen i compile even a simple code using a feature of the c11 standard the stdstod function gcc 491 fails with the following errorexamplecpp in function int mainexamplecpp1018 error stod is not a member of std double earth stdstod orbitssz examplecpp17 error stod is not a member of std double moon stdstod orbitssubstrsz whatthe command i use is g stdc11 examplecppthis is the test code which compiles fine on other systems stod example from include iostream stdcoutinclude string stdstring stdstodint main stdstring orbits 36524 2953 stdstringsize type sz alias of size t double earth stdstod orbitssz double moon stdstod orbitssubstrsz stdcout the moon completes earthmoon orbits per earth yearn return 0detailsi am using a version of gcc 491 i compiled myself on two different clusters running centos 65 i use the modules system on stuff in my home dir since i am not an admini will call them cluster 1 and cluster 2 cluster 1 is where the failure happensthe gccs were compiled in the same way and at the same time and loaded using identical module files save for a minor difference in the base path the installations are as far as i can easily check identical the same include files exist on both clusters and have the same contentsthe output from g v is the same on both clusters again except for the install pathusing builtin specscollect gccgcollect lto wrapperhomeandyrasbingcc491libexecgccx86 64unknownlinuxgnu491ltowrappertarget x86 64unknownlinuxgnuconfigured with gcc491configure prefixhomeandyrasbingcc491 enablelanguagesccfortranthread model posixgcc version 491 gccg v using the system gcc gives the same output on both clusters except on cluster 1 it says it is gcc version 447 20120313 red hat 4473 gcc and on cluster 2 says gcc version 447 20120313 red hat 4474 gcci am trying to debug using g stdc11 savetemps md examplecpp for more info this gives some clues but i do not know where to go from herethe intermediate ii files on cluster 1 are missing some lines for example excerpt from diffing the ii files 277 optgcc491includec491cwchar 3 277 homeandyrasbingcc491includec491cwchar 3961963c934936 using stdwcstold using stdwcstoll using stdwcstoull as i interpret it gcc on both clusters tries to include files like cwchar but on cluster 1 there are blank lines instead of things being defined on cluster 2 the stod function is in the intermediate file but not on cluster 1could it be a preprocessor errornow looking at the d dependency files i also see a concrete difference there are some files listed on cluster 2 that are not listed on cluster 1 here is the list i processed the contents of the d files to account for the different base paths stands in for the install path85a86108 gcc491includec491extstring conversionsh gcc491includec491cstdlib usrincludestdlibh usrincludebitswaitflagsh usrincludebitswaitstatush usrincludesystypesh usrincludesysselecth usrincludebitsselecth usrincludebitssigseth usrincludesyssysmacrosh usrincludeallocah gcc491includec491cstdio usrincludelibioh usrinclude g configh usrincludebitsstdio limh usrincludebitssys errlisth gcc491includec491cerrno usrincludeerrnoh usrincludebitserrnoh usrincludelinuxerrnoh usrincludeasmerrnoh usrincludeasmgenericerrnoh usrincludeasmgenericerrnobasehi was curious if cpp was looking for includes in all the wrong places but this seems legit cpp vinclude search starts here homeandyrasbingcc491include homeandyrasbingcc491includec491 homeandyrasbingcc491includec491x86 64unknownlinuxgnu homeandyrasbingcc491libgccx86 64unknownlinuxgnu491include usrlocalinclude homeandyrasbingcc491libgccx86 64unknownlinuxgnu491includefixed usrincludeend of search listthis has been a very frustrating couple of hours trying to track down the source of the problem i could of course use something like atofmystringc str instead of stdstod but i am wondering if there is an underlying issue that will foul up future projects using other bits of c11any more clues or insight would be very much appreciated,['c++'] +768497,how to resume javascript timer on ios8 web app after screen unlock on ios8 this html5 web app does not resume the js timer after the screen is locked and then unlocked if the webapp was active and launched from the homescreen icon on ios7 the timer would continue in this situation i need the timer to continue after the screen is unlocked any tips to achieve thisnote please add the web app to the homescreen first using safaris add to home screen via the sharing button running the page inside safari does not cause the issue described abovehtmlhead meta nameapplemobilewebappcapable contentyes titletesttitle script var tim function go tim windowsetintervalaction 10 function action documentgetelementbyidxinnerhtml new dategettimetostring scriptheadbody onloadgo div idxdivbodyhtml,['javascript'] +768537,what improvements does gccs builtin malloc provide over plain malloc i have recently been made aware of gccs builtin functions for some of the c librarys memory management functions specifically builtin malloc and related builtins see upon learning about builtin malloc i was wondering how it might work to provide performance improvements over the plain malloc related library routinesfor example if the function succeeds it has to provide a block that can be freed by a call to plain free since the pointer might be freed by a module that was compiled without builtin malloc or builtin free enabled or am i wrong about thisand if builtin malloc is used the builtins must be globally used therefore the allocated object has to be something that can be managed with the data structures that plain malloc and free deal withi cannot find any details of how builtin malloc works or what it does exactly i am not a compiler dev so spelunking through gcc source code is not in my wheelhouse in some simple tests where i have tried calling builtin malloc directly it simply ends up being emitted in the object code as a call to plain malloc however there might be subtlety or platform detail that i am not providing in these simple testswhat kinds of performance improvements can builtin malloc provide over a call to plain malloc does builtin malloc have a dependency on the rather complex data structures that glibcs malloc implementation use or conversely does glibcs mallocfree have some code to deal with blocks that might be allocated by builtin malloc basically how does it work,['c'] +768659,threadsafe lazy initialization static vs stdcall once vs double checked locking for threadsafe lazy initialization should one prefer a static variable inside a function stdcall once or explicit double checked locking are there any meaningful differencesall three can be seen in this questiondoublechecked lock singleton in c11two versions of double checked locking in c11 turn up in googleanthony williams shows both double checked locking with explicit memory ordering and stdcall once he does not mention static but that article might have been written before c11 compilers were availablejeff preshing in an extensive writeup describes several variations of double checked locking he does mention using a static variable as an option and he even shows that compilers will generate code for double checked locking to initialize a static variable it is not clear to me if he concludes that one way is better than the otheri get the sense that both articles are meant to be pedagogical and that there is no reason to do this the compiler will do it for you if you use a static variable or stdcall once,['c++'] +768708,angularjs binds unsafejavascriptvoid0 when value is javasciptvoid0 a ngattrhrefpage1 javascriptvoid0 atidpage1prevai want to get that when page 1a hrefjavascriptvoid0prevabut the resulta hrefunsafejavascriptvoid0preva,['html'] +768710,debugging mobile safari in ios 8 and ios 9 after switching to new versions of ios i have not been able to debug my web app from os x safari to my iphone safari browser my iphone shows up but i get no optionson my iphone i have allowed the web inspectorenglish developer johans iphone no inspectable applicationsif i however save my web app to my home screen i can get the developer tools for that app but it is not what i want at this occasion unfortunately i have no other ios os x devices to test with so any help would be greatly appreciated,"['ios', 'iphone']" +768713,angularjs form reset error i am trying to do a form with validations using angularjs and so far i did a good job but when i commit my reset button all the fields reset except for the error messages i get from my validation part how can i get rid of all the fields and error messages when i reset my formthis is how it is when i press my reset buttonthis is my codediv classpageheadercenterh2give us your feedbackh2centerdiv pass in the variable if our form is valid or invalid form nameuserform ngsubmitsubmitformuserformvalid novalidate name div classformgroup ngclass haserror userformnameinvalid userformnamedirty labelnamelabel input typetext namename classiteminputwrapper formcontrol ngmodelusername required p ngshowuserformnameinvalid userformnamepristine classhelpblockfont color009acdyou name is requiredfontp div email div classformgroup ngclass haserror userformemailinvalid userformemaildirty labelemaillabel input typeemail nameemail classiteminputwrapper formcontrol ngmodeluseremail required p ngshowuserformemailinvalid userformemailpristine classhelpblockfont color009acdenter a valid emailfontp div username div classformgroup ngclass haserror userformusernameinvalid userformusernamedirty labeldescriptionlabel input typetext nameusername classiteminputwrapper formcontrol ngmodeluserusername ngminlength5 ngmaxlength60 required font colorwhitep ngshowuserformusernameerrorminlength classhelpblockfont color009acddescription is too shortfontp p ngshowuserformusernameerrormaxlength classhelpblockfont color009acddescription is too longfontp div div classcolstyletextalign center button alignleftclassbutton buttonblock buttonresetstylethisplay inlineblockwidth100pxtextaligncenter typereset ngclickresetpaddingtoptrueresetbutton button classbutton buttonblock buttonpositive stylethisplay inlineblockwidth100px ngclicksubmitpaddingtoptruesubmitbutton div formdiv ioncontentionviewmy controllercontrollercontactctrl functionscopestateionicpopup timeout scopeshowfeedback function stategoappsfeedback scopesubmitform functionisvalid scopesubmitted true check to make sure the form is completely valid if isvalid var alertpopup ionicpopupalert title invalid data entered else var alertpopup ionicpopupalert title feedback submitted scopereset function var original scopeuser scopeuser angularcopyoriginal scopeuserformsetpristine,"['javascript', 'html']" +768722,deterministic no sql or reads sql data in its declaration and binary logging is enabled while importing the database in mysql i have got following error1418 hy0 at line 10185 this function has none of deterministic no sql or reads sql data in its declaration and binary logging is enabled you might want to use the less safe log bin trust function creators variable i do not know which things i need to change can any one help me how to resolve this,['mysql'] +768751,time remaining to the next 5 minutes javascript i am trying to thisplay the time remaining for the next 5 minutes snapped to the full 5 minutes of the current time eg 1505 1510i was able to achieve the same for the time remaining for next hour not minutesspan classtimerspanscriptfunction secondpassed var cur date new date var hour cur dategethours var minutes cur dategetminutes var seconds cur dategetseconds var minutes remain parseint59 parseintminutes var seconds remain parseint60 parseintseconds var timers documentgetelementsbyclassnametimer for var i 0 i timerslength i timersiinnerhtml minutes remainseconds remain var countdowntimer setintervalsecondpassed 10scriptjsfiddle,['javascript'] +768773,how to install old version of android build tools from command line i am installing android sdk to create an automated build server i got into a problem where many gradlebased android projects i manage rely on different build tools version some of the projects still requiring old buildtools version eg v1910my androidsdk package was downloaded when buildtools version 20 has just released so that is the only version available to download via android update sdk u filter buildtoolsi have tried to invoke android update sdk u filter buildtools1910 but it did not work is there an easy way to install old version of android build tools from command linenote installing via gui is not possible,['android'] +768787,why does php occasionally hang on session start nb this is not a dupe of php session start causing http requests to hang and other similarly named questions on so as my hang is occasional not permanentusing ubuntu 1204 magento phpfpm 54 and default php session handler with files on ext4incidentally once per month all php processes hang on session start according to fpmslowlog24sep2014 110304 pool w pid 24259script filename datawebpublicindexphp0x07f00b4ec6480 session start datawebpublicincludessrc defaultphp76870x07f00b4ec6130 start datawebpublicincludessrc defaultphp77300x07f00b4ec5fb8 init datawebpublicincludessrc defaultphp80860x07f00b4ec5e30 init datawebpublicincludessrc defaultphp339020x07f00b4ec5bd0 construct datawebpublicincludessrc defaultphp238410x07f00b4ec5ae8 getmodelinstance datawebpublicappmagephp4630x07f00b4ec59c8 getmodel datawebpublicappmagephp4770x07f00b4ec49a0 getsingleton datawebpublicincludessrc defaultphp140440x07f00b4ec4848 prethispatch datawebpublicincludessrcmage adminhtml controller actionphp1600x07f00b4ec3b00 prethispatch datawebpublicincludessrc defaultphp139580x07f00b4ec26e0 thispatch datawebpublicincludessrc defaultphp183310x07f00b4ec20c0 match datawebpublicincludessrc defaultphp178650x07f00b4ec1a98 thispatch datawebpublicincludessrc defaultphp204650x07f00b4ec1908 run datawebpublicappmagephp6840x07f00b4ec17f8 run datawebpublicindexphp87lsof sayscommand pid user fd type device sizeoff node namephp5fpm 24259 app 10uw reg 2021 82492 1220594 datawebpublicvarsessionsess gr2clur9icgd7s2j9linag7ue6php5fpm 24262 app 10u reg 2021 82492 1220594 datawebpublicvarsessionsess gr2clur9icgd7s2j9linag7ue6php5fpm 24351 app 10u reg 2021 82492 1220594 datawebpublicvarsessionsess gr2clur9icgd7s2j9linag7ue6php5fpm 24357 app 10u reg 2021 82492 1220594 datawebpublicvarsessionsess gr2clur9icgd7s2j9linag7ue6php5fpm 24358 app 10u reg 2021 82492 1220594 datawebpublicvarsessionsess gr2clur9icgd7s2j9linag7ue6php5fpm 25563 app 10u reg 2021 82492 1220594 datawebpublicvarsessionsess gr2clur9icgd7s2j9linag7ue6php5fpm 25564 app 10u reg 2021 82492 1220594 datawebpublicvarsessionsess gr2clur9icgd7s2j9linag7ue6according to strace all these processes are waiting for flock lock ex even the one who has the w flag in the lsof output abovethe cpu usage during this incident is near 0 so why does the first session start hang even though it seems to have acquired a write lock on the session file how could i debug this further here is a thiscussion called race condition with ajax and php sessions in fact the requests that trigger the problem above are consistenly ajax calls however this article states thatif youve used phps builtin default session handling that uses files youll never come across the problemso currently i am at a loss where to look next,['php'] +768846,openeventopenfilemapping fails with error access denied i am developing an open source net assembly winscp net assembly that spawns a native c application and communicates with it via events and file mapping objects the assembly spawns the application using process class with no special settings the assembly creates few events using eventwaithandle and file mapping using pinvoked createfilemapping and the application opens these using openevent and openfilemappingit works fine in most cases but now i am having a user that uses the assembly from an aspx application on windows server 2008 r2 64 bitin his case both openevent and openfilemapping return null and the getlasterror returns error access deniedi have tried to improve the assembly code by explicitly granting the current user necessary permissions to the event objects and the application code to require only the really needed access rights instead of original event all access as per example on msdn it did not help so i did not even bother to try the same for the file mapping objectthe c code that creates the event iseventwaithandlesecurity security new eventwaithandlesecuritystring user environmentuserdomainname environmentusernameeventwaithandleaccessrule rulerule new eventwaithandleaccessrule user eventwaithandlerightssynchronize eventwaithandlerightsmodify accesscontroltypeallowsecurityaddaccessrulerulerule new eventwaithandleaccessrule user eventwaithandlerightschangepermissions accesscontroltypedenysecurityaddaccessrulerulenew eventwaithandle false eventresetmodeautoreset name out creatednew securitythe c code that opens the events isopeneventevent modify state false namefor other events the access level is synchronize depending on needsdoes anyone have any idea what causes the access denied error in openevent or createfilemapping,"['c#', 'c++']" +768858,app crashing in uipopoverpresentationcontroller but no explicit popovers my app ios 8 only has been rejected due to a crash when iap are attempted i have tried pretty much every incantation of the purchase process in an adhoc build but cannot reproduce a crash looking at the crash log that the review team attached i am seeing a very weird stack trace in the last exception backtrace the crash looks to be involving uipopovercontroller however my app though universal does not explicitly or implicitly thisplay popovers anywhere does anyone have any idea what might trigger the activity that is causing this crash what might cause my app to thisplay popovers when the review team is looking at it onlylast exception backtrace0 corefoundation 0x186d52084 exceptionpreprocess 1321 libobjcadylib 0x1977a40e4 objc exception throw 602 uikit 0x18bc0aee0 uipopoverpresentationcontroller presentationtransitionwillbegin 24643 uikit 0x18b7d27d8 71uipresentationcontroller initviewhierarchyforpresentationsuperview block invoke 13244 uikit 0x18b7d1310 56uipresentationcontroller runtransitionforcurrentstate block invoke 2125 uikit 0x18b557388 applyblocktocfarraycopiedtostack 3566 uikit 0x18b4c8e4c aftercacommithandler 5327 corefoundation 0x186d0a388 cfrunloop is calling out to an observer callback function 328 corefoundation 0x186d07314 cfrunloopdoobservers 3609 corefoundation 0x186d076f4 cfrunlooprun 83610 corefoundation 0x186c35664 cfrunlooprunspecific 39611 graphicsservices 0x18fd435a4 gseventrunmodal 16812 uikit 0x18b53a984 uiapplicationmain 1488,['ios'] +768864,include runtime dependencies in python wheels i would like to thistribute a whole virtualenv or a bunch of python wheels of exact versions with their runtime dependencies for examplepycurlpycurlsolibcurlsolibzsolibsslsolibcryptosolibgssapi krb5solibkrb5solibresolvsoi suppose i could rely on the system to have libsslso installed but surely not libcurlso of the correct version and probably not kerberoswhat is the easiest way to package one library in a wheel with all the runtime dependencyor is that a fools errand and i should package entire virtualenvhow to do that reliablyps compiling on the fly is not an option some modules are patched,['python'] +768887,huge stdvector does not release all memory on destruction when using a very large vector of vectors weve found that part of the memory is not released include iostreaminclude vectorinclude unistdhvoid foo stdvectorstdvectorunsigned int voxeltopixel unsigned int numelem 127 voxeltopixelresize numelem for unsigned int idx0 idx numelem idx voxeltopixelatidxpush backidxint main foo stdcout end stdendl sleep30 return 0that leaves around 4gb of memory hanging until the process endsif we change the for line tofor unsigned int idx0 idx numelem idx voxeltopixelat0push backidxthe memory is releasedusing gcc48 on a linux machine weve used htop to track the memory usage on a computer with 100 gb of ram you will need around 8 gb of ram to run the code can you reproduce the problem any ideas on why that is happeningeditweve seen that that does not happen in a mac with either gcc or clang also in linux the memory is freed if we call foo two times but happens again the third time,['c++'] +768906,law of demeter with data model objects i came back to work from vacation yesterday and in our daily standup my teammates mentioned they were refactoring all of the model objects in our java code to remove all getters and setters and make the model fields all public objects instead invoking the law of demeter as the reason for doing so because to facilitate the our adherence to demeters law a module should not know about the innards of the objects it manipulates since data structures contain no behavior they naturally exposes their internal structure so in that case demeter does not apply i admit i had to brush up on my knowledge of the lod but for the life of me i cannot find anything to indicate that this is within the spirit of the law none of the getterssetters in our models contain any business logic which is his justification for doing this so clients of these objects do not have to unerstand whether or not there is some business logic being executed within the getset methods i think this is a misunderstanding of what it means to need internal knowledge of an objects structure or at the very least is taking it too literally and breaking a pretty standard convention in the process so my question is does it actually make any sense to expose model objects interal structure directly instead of via getterssetters in the name of the lodthanks,['java'] +768950,the response content must be a string or object implementing tostring boolean given i am trying to return a rendered view using responsejson but i am getting this errorthe response content must be a string or object implementing tostring boolean giventhis is my codeposts postwhere orderby getdataposts viewmakepostspartialsloadhomewithposts postsrenderdatamsg okreturn responsejsondataif i var dumpdata i get thispre classxdebugvardump dirltrbarrayb isize2i posts font color8a85gtfont smallstringsmall font colorcc0ltdiv classquotpost postgridquot dataidquot1864quotgt10 lta target39 blank39 hrefquotquotgtltimg srcquotquot idquotimgwrapquot dataoriginalquotthumbsyao4wfzipl76jpgquot classquotlazyquot altquotdeset manje poznatih ainjenica o jozefu staljinuquotgtltagt10 10 ltdiv idquotbodypreviewquotgt10 10 lta target39 blank39 hrefquotquotgtlth1 classquotpreviewtitlequotgtdeset manje poznatih ainjenica o jozefu staljinulth1gtltagt1010 lth3 idquotpostinfoquotgt10 lta classquotpaintquot hrefquotcategory17quotgtzanimljivostiltagt10 font ilength12172i msg font color8a85gtfont smallstringsmall font colorcc0okfont ilength2iprethis is postspartialsloadhome viewforeachposts as postdiv classpost postgrid dataid postid a target blank href urlactionpostscontrollershow postid htmlimagenull posttitle id imgwrap dataoriginal postgetthumb class lazy a div idbodypreview a target blank href urlactionpostscontrollershow postid h1 classpreviewtitle eposttitle h1a h3 idpostinfo foreachpostcategories as c a classpaint hrefcategory cid cname a endforeach h3 h2 classbodypreview strip tagstruncstringpostbody 160 h2 div idcreatedby a href urlactionuserscontrollershow postuserfirstid htmlimagepostuserfirstgetavatar postuserfirstusername width 32 height 32 postuserfirstusername a label idtimeago localdatepostcreated at label div divdivendforeachi tested this on localhost and everything works fine what could be the problem,['php'] +768978,c function explanation can someone please explain to me the syntax of this function where sys fork is some constant and sys fork is a functionstatic int syscallsvoid sys fork sys forksys exit sys exitsys wait sys waitsys pipe sys pipesys read sys readsys kill sys killsys exec sys execthank you,['c'] +769009,trouble creating a mysql function through pdo i have created a cli php script designed to allow me to run update scripts against my database the script works as expected runs sequential update files rolls back on errors etc however the only thing i cannot get it to do properly is create functions what am i missingscriptheres the basics of how the script workssql file get contentsfilesql use database sqlstmt pdopreparesqltry stmtexecute ifstmterrorcode 0 throw new exceptionerror unable to run update filen print rstmterrorinfo true catchexception ex pdorollback echo error exception occured running update filen print rex true n throw exsqland heres an example of the function portions of the sql codedelimiter create definercurrent user function uuid from binb binary16 returns char36 charset latin1 deterministicbegin declare hex char32 set hex hexb return lowerconcatlefthex 8 midhex 94 midhex 134 midhex 174 righthex 12return 1end if i run this code inside mysql workbench it runs as expected when i run it through my script using pdo everything except the functions are created and populated i get no errors and no exceptionsso fari have tried removing the definer thinking that the user that was current user might be userrandomip and the user in the system is defined as useri also just removed the definer from the sql still works in mysql workbench but not in this scripti have also pulled the functions out into their own sql same resultother infomysql 55370ubuntu014041php 55when i connect with pdo i am not setting the db since the script may need to create the database but the scripts are appended with a use statement again all the other ddl statements workthe user has all but grant permissions on schema based on a pattern specifically ci solution update delimiterupdated the code to remove the delimiterdelimiter used to be herecreate definercurrent user function uuid from binb binary16 returns char36 charset latin1 deterministicbegin declare hex char32 set hex hexb return lowerconcatlefthex 8 midhex 94 midhex 134 midhex 174 righthex 12return 1end,"['php', 'mysql', 'sql']" +769010,dyld library not loaded rpathlibswiftcoredylib i am trying to run a swift app on my iphone 4s it works fine on the simulator and my friend can successfully run it on his iphone 4s i have ios 8 and the official release of xcode 6i have tried restarting xcode iphone computer cleaning rebuilding revoking and creating new certificateprovision profile runpath search paths is inherited executable pathframeworksembedded content contains swift code is yes code signing identity is developerbelow is the error in entirety dyld library not loaded rpathlibswiftcoredylib referenced from privatevarmobilecontainersbundleapplicationlongserialnumberappnameappappname reason no suitable image found did find privatevarmobilecontainersbundleapplicationlongserialnumberappnameappframeworkslibswiftcoredylib mmap error 1 ataddress0x008a10 size0x001a40 segment text in segmentmap mappingprivatevarmobilecontainersbundleapplicationlongserialnumberapplication nameframeworkslibswiftcoredylib,['ios'] +769072,android library project transient dependencies loose aar type i am working on a project which includes two android library projects when i upload these libraries to my maven repo nexus the generated pom does not include a typeaartype element in the dependencyheres my dependency tree app1 lib1 lib2 other libsyou can see in this diagram that my app depends on lib1 which depends on lib2 both of the libraries are android library projects thus aarslib1buildgradleapply plugin comandroidlibraryapply from android compilesdkversion rootprojectextcompilesdkversion buildtoolsversion rootprojectextbuildtoolsversion defaultconfig minsdkversion rootprojectextminsdkversion targetsdkversion 20 versioncode 1 versionname 10 dependencies compile filetreedir libs include jar provided projectlib2 compile comsquareuppicassopicasso233lib2buildgradleapply plugin comandroidlibraryapply from android compilesdkversion rootprojectextcompilesdkversion buildtoolsversion rootprojectextbuildtoolsversion defaultconfig minsdkversion rootprojectextminsdkversion targetsdkversion 19 versioncode 1 versionname 10 dependencies compile filetreedir libs include jar compile comandroidsupportappcompatv719 compile comsquareupretrofitretrofit161 compile comsquareupokhttpokhttpurlconnection200 compile comsquareupokhttpokhttp200notice how lib1 includes lib2 as a project dependencynow when i deploy this using chris banes excellent gradlemvnpush plugin everything works as expected there is only one oddity that i notice in the generated pomxmldependencies dependency groupidcomexamplegroupid artifactidlib2artifactid version001snapshotversion scopecompilescope dependency dependenciesnotice that the mavendeployer plugin left out the typeaartype element in the dependency when it generated the pomin my app project which is a maven project i have this dependency listeddependencies dependency groupidcomexamplegroupid artifactidlib1artifactid version001snapshotversion typeaartype dependency dependencieswhen trying to build this with maven i get the following errorcould not resolve dependencies for project comexampleappapk100snapshot the following artifacts could not be resolved comexamplelib2jar001snapshotnotice how it is looking for a jar version of the library i believe since the mavendeployer plugin is not generated the typeaartype in the dependencies list of the generated pom maven is defaulting to looking for a jardoes anyone know how to build android library projects that include transient dependencies with gradle,['android'] +769110,wkwebview add to subview i can add a wkwebview programmatically to a subview with the code below how can i add wkwebview to the view containerview2 that was added via interface builderimport uikitimport webkitclass viewcontroller uiviewcontroller iboutlet var containerview uiviewiboutlet weak var containerview2 uiviewvar webview wkwebviewoverride func loadview superloadview selfwebview wkwebview selfwebviewframe cgrectmake50 50 200 200 selfwebviewsizetofit selfcontainerview selfwebview how can i set a view containerview2 added by interface builder to selfwebview selfviewaddsubviewselfcontainerviewoverride func viewdidload superviewdidload var url nsurlstring var req nsurlrequesturlurl selfwebviewloadrequestreqoverride func didreceivememorywarning superdidreceivememorywarning thispose of any resources that can be recreated,['ios'] +769146,how to reuse code between const and nonconst functions that call other functions in this example code the loop inside the two process functions is duplicated the only difference is that one is const and the other is notis there a way to remove the code duplication such that the loop only exists once this is only an example but in the real code the loop is quite complex so for maintenance reasons i only want the loop to exist onceinclude iostreaminclude vectortypedef unsigned int itemtypedef stdvectoritem datastruct readonlyaction void actionconst item i read item do not modify stdcout reading item i n struct modifyaction void actionitem i modify item stdcout modifying item i n i void processdata d modifyaction cb this loop is actually really complicated and there are nested loops inside it three levels deep so it should only exist once for dataiterator i dbegin i dend i item item i cbactionitem void processconst data d readonlyaction cb this is the same loop as above and so the code should not be duplicated for dataconst iterator i dbegin i dend i const item item i cbactionitem void incrementdatadata d here we modify the pointer and need to loop through it modifyaction incrementitem processd incrementitemvoid savedataconst data d here we are not allowed to modify the pointer but we still need to loop through it readonlyaction printitem processd printitemint mainvoid data d populate with dummy data for example purposes unsigned int a 123 unsigned int b 456 dpush backa dpush backb incrementdatad savedatad return 0please be aware that this is not a duplicate question the following similar questions and answers are different123758 only covers simple functions that return values whereas this function calls other functions so the solutions given there do not work for this problem23809745 same issue only covers simple functions that return values answers do not work for this problemif i attempt the solution given in those answers it does not work but looks like thistemplate class cbvoid processtconst data d cb cb single loop in only one location for dataconst iterator i dbegin i dend i const item item i compilation fails on the next line because const item cannot be be converted to item for the call to modifyactionaction cbactionitem void processconst data d readonlyaction cb processtd cbvoid processdata d modifyaction cb procesststatic castconst data d cbthis is a simplified example so it would be much appreciated if answers could focus on the problem how to remove the duplicated loop from within the two process functions rather than comments about the design changes to the design are fine of course if it removes the duplicate loop in the process,['c++'] +769171,ios8 icons sizes and names for icons and launch image i am not finding a straight forward site with the ios8 sizes and names for the app icons and launch imagei have seen the ios human interface guidelines but they do not really tell you how to name themcan someone list them out specifically,['ios'] +769223,how to parse multidimensional json to html easily i want to parse json to html easily i have a multidimensional json so i want to parse this to html easily any plugin or any simple code is available the following my json file country india state name delhi capital new delhi name tamilnadu capital chennai country usa state name alabama capital montgomery name alaska capital juneau the html is like thisul liindiali ul listate1 capitalli listate2 capita2liul liusali ul listate1 capitalli listate2 capita2liululi want to get output like thiswhich is best and simplest way to get this output,['jquery'] +769229,importerror no module named datetime when i upgrade my ubuntu into 1404 from 1204 this time i get this error importerror no module named datetime,['python'] +769240,android webview ignoring target blank when added webviewclient i am facing a strange issuein my application i need to load a static html file based on clicked button in a webview from assets foldernow among 5 html files one html file contains 15 static links these links need to redirect user to the mentioned url in a mobile browser i have used target blank for that purpose as follows in my html filediv classlida href target blankrailway reservation adivnow this works fine in a sample application with a simple webview without any webviewclient added to itbut i need a webviewclient for my other functionalities so at that time target blank is totally ignored and the url is opened in a webview itselfi found a workaround that i can use shouldoverrideurlloading as followsmywebviewsetwebviewclientnew webviewclient public boolean shouldoverrideurlloadingwebview view string url todo autogenerated method stub ifurlequalsignorecase viewgetcontextstartactivity new intentintentaction view uriparseurl return true else return supershouldoverrideurlloadingview url so this is opening that particular url in a default browserso basically my questions arewhy is target blank ignored while we use webviewclient and is there any other workaround for this issue because i have 15 links which i would need to compare i cannot load all urls in a new browser as there are a few links which need to be opened in a same webview too,['android'] +769277,difference between image formats rgb8 and argb8 i am new to image processing and game development i was following a tutorial in which it suggest to use background image of format rgb8and for sprites buttons and other rest icons it suggest to use argb8 formatmost basic difference is there bits rgb8 is 24bit and argb8 is 32 bitso i want to know what is real difference between these two format and how they effect in visual representation,['android'] +769303,uicollection view scroll lag with sdwebimage backgroundi have searched around so and apple forum quite a lot of people talked about performance of collection view cell with image most of them said it is lag on scroll since loading the image in the main thread by using sdwebimage the images should be loading in separate thread however it is lag only in the landscape mode in the ipad simulatorproblem descriptionin the portrait mode the collection view load 3 cells for each row and it has no lag or insignificant delay in the landscape mode the collection view load 4 cells for each row and it has obvious lag and drop in frame ratei have checked with instrument tools with the core animation the frame rate drop to about 8fps when new cell appear i am not sure which act bring me such a low performance for the collection viewhope there would be someone know the tricks parthere are the relate codein the view controller uicollectionviewcell collectionviewuicollectionview collectionview cellforitematindexpathnsindexpath indexpath productcollectionviewcell cellcollectionview dequeuereusablecellwithreuseidentifierproductviewcell forindexpathindexpath product tmpproduct product ploaderloadedproductindexpathrow cellproduct tmpproduct if cellshouldanimate cellalpha 00 uiview animatewithduration02 delay0 optionsuiviewanimationoptioncurvelinear uiviewanimationoptionallowuserinteraction animations cellalpha 10 completionnil ifindexpathrow ploaderloadedproductcount ceillimit count 03 ploader loadproductswithcompleteblocknserror error if nil error cellshouldanimate no collectionview reloaddata thispatch afterthispatch timethispatch time now 2 nsec per sec thispatch get main queue cellshouldanimate yes else if errorcode 1 ifdef debug mode ulogerrordes errordescription else customalertview alertview customalertview alloc initwithtitleconnection error messageplease retry buttontitlesok alertview show endif return cellprepareforreuse in the collectionviewcell voidprepareforreuse super prepareforreuse cgrect bounds selfbounds thumbnailimgview sd cancelcurrentimageload cgfloat labelstotalheight boundssizeheight thumbnailimgviewframesizeheight cgfloat brandtoimageoffset 20 if ui user interface idiom uiuserinterfaceidiompad brandtoimageoffset 530 cgfloat labelstarty thumbnailimgviewframesizeheight thumbnailimgviewframeoriginy brandtoimageoffset cgfloat namelblheight labelstotalheight 046 cgfloat pricelblheight labelstotalheight 018 brandlblframe cgrect15 labelstarty boundssizewidth 30 namelblheight cgfloat pricetonameoffset 80 if ui user interface idiom uiuserinterfaceidiompad pricetonameoffset 180 pricelblframe cgrect5 labelstarty namelblheight pricetonameoffset boundssizewidth10 pricelblheight spinner stopanimating spinner removefromsuperview spinner niloverride the setproduct method voidsetproductproduct product product product spinner uiactivityindicatorview alloc initwithactivityindicatorstyleuiactivityindicatorviewstylegray spinnercenter cgpointmakecgrectgetmidxselfbounds cgrectgetmidyselfbounds self addsubview spinner spinner startanimating spinnerhideswhenstopped yes add a spinner block uiactivityindicatorview tmpspinner spinner block uiimageview tmpimgview thumbnailimgview productimage thumbnailimage productimages0 thumbnailimgview sd setimagewithurlnsurl urlwithstringthumbnailimagemediumurl completeduiimage image nserror error sdimagecachetype cachetype nsurl imageurl thismiss the spinner tmpspinner stopanimating tmpspinner removefromsuperview tmpspinner nil if nil error resize the incoming images thispatch asyncthispatch get global queuethispatch queue priority default 0 cgfloat imageheight imagesizeheight cgfloat imagewidth imagesizewidth cgsize newsize tmpimgviewboundssize cgfloat scalefactor newsizewidth imagewidth newsizeheight imageheight scalefactor uigraphicsbeginimagecontextwithoptionsnewsize no 00 image drawinrectcgrectmake0 0 newsizewidth newsizeheight uiimage small uigraphicsgetimagefromcurrentimagecontext uigraphicsendimagecontext thispatch asyncthispatch get main queue tmpimgviewimage small if cachetype sdimagecachetypenone tmpimgviewalpha 00 uiview animatewithduration02 delay0 optionsuiviewanimationoptioncurvelinear uiviewanimationoptionallowuserinteraction animations tmpimgviewalpha 10 completionnil else loading error tmpimgview setimageuiimage imagenamedbroken image small brandlbltext productbrandname uppercasestring namelbltext productname namelbl sizetofit format the price nsnumberformatter floatformatter nsnumberformatter alloc init floatformatter setnumberstylensnumberformatterdecimalstyle floatformatter setdecimalseparator floatformatter setmaximumfractiondigits2 floatformatter setminimumfractiondigits0 floatformatter setgroupingseparator pricelbltext nsstring stringwithformat usd floatformatter stringfromnumber productprice if productsalepriceintvalue 0 nsstring rawstr nsstring stringwithformat usd floatformatter stringfromnumber productprice floatformatter stringfromnumber productsaleprice nsmutableattributedstring string nsmutableattributedstring alloc initwithstringrawstr change all the text to red first string addattributensforegroundcolorattributename valueuicolor colorwithred1572550 green382550 blue292550 alpha10 rangensmakerange0rawstrlength find the first space nsrange firstspace rawstr rangeofstring change from zero to space to gray color string addattributensforegroundcolorattributename value pricelbltextcolor rangensmakerange0 firstspacelocation string addattributensstrikethroughstyleattributename value2 rangensmakerange0 firstspacelocation pricelblattributedtext string,"['ios', 'objective-c']" +769328,inverted order of json elements in java after xml conversion i am using the json in java for the transformation of xml to json i have the problem that this implementation is inverting all child elementswhen i pass this xmlpersonchild1achild1child2bchild2personi will end up with a json having the childs invertedpersonchild2b child1amy java codejsonobject jsonobject xmltojsonobjectpersonchild1achild1child2bchild2personstring myjsonstring jsonobjecttostring4how to transform to json with keeping the order of the elements like in xml,['java'] +769363,how avsamplebufferthisplaylayer thisplays h264 i want to share my knowledge which i worked out in some days about it there isnt a lot to find about iti am still fizzeling about the sound comments and tips are welcomed,['ios'] +769443,mkmapview showing blank screen in ios 8 i am having an issue with thisplaying a mkmapview in ios 8it worked fine in ios 7 and it is working fine now but only on simulatoron device it shows only annotations but no map behindit looks like this the error that i am getting20140924 220715349 x1509265380 stylesheet does not include style matching tree or includes an old version perhaps it was compiled by an old version of the style compiler20140924 220715351 x1509265380 please create a radar about this check it is not a dup of rdar16346611 first though20140924 220715351 x1509265380 active tile set geoactivetilesetmy code cllocationcoordinate2d coord cllocationcoordinate2dmake217798 59447816 mkcoordinatespan span mkcoordinatespanmake07 07 mkcoordinateregion region coord span mkpointannotation annotation mkpointannotation alloc init annotation setcoordinatecoord annotation settitley selfcellmymapview setregionregion selfcellmymapview addannotationannotation selfcellmymapview setdelegateselfthanks in advance,['ios'] +769601,how to store key using android key store provider i am trying to use the android key store provider that became available in android 43 to securely save a private key and to then use this private key to encrypt and decode datai think i have implemented the correct approach and code for this so far however i am currently facing an odd issue that i cannot figure outi have a class called keystorage that i use to create the key pair load the keystore and retrieve the private key the code for this class is as followspublic class keystorage public static final string android keystore androidkeystoreprivate keystore keystorepublic void loadkeystore try keystore keystoregetinstanceandroid keystore keystoreloadnull enumerationstring aliases keystorealiases whilealiaseshasmoreelements logee aliases aliasesnextelement catch exception e todo handle this appropriately in your app eprintstacktrace public void generatenewkeypairstring alias context context throws exception calendar start calendargetinstance calendar end calendargetinstance expires 1 year from today endadd1 calendaryear keypairgeneratorspec spec new keypairgeneratorspecbuildercontext setaliasalias setsubjectnew x500principalcn alias setserialnumberbigintegerten setstartdatestartgettime setenddateendgettime build use the android keystore keypairgenerator gen keypairgeneratorgetinstancersa android keystore geninitializespec generates the keypair gengeneratekeypairpublic privatekey loadprivtekeystring alias throws exception if keystoreiskeyentryalias logee could not find key alias alias return null keystoreentry entry keystoregetentryenhancedcredentialstorekey alias null if entry instanceof keystoreprivatekeyentry logee alias alias is not a privatekey return null return keystoreprivatekeyentry entrygetprivatekeyi then have a class called credentialstore that i try to use this in i create an alias called mysecurekey and try to create and store a private key based on this so as you can see i try to create the new key pair based on the alias load the keystore and then finally retrieve the private key however it does not workpublic class credentialstore public static final string key alias mysecurekeyprivate keystorage keystoragepublic credentialstoreactivity context keystorage new keystorage try keystoragegeneratenewkeypairkey alias context catch exception e eprintstacktrace bluebirdkeystorageloadkeystore try keystorageloadprivtekeykey alias catch exception e eprintstacktrace i get the logs as followaliases mysecurekeycould not find key alias mysecurekeyso when i check the aliases in the loadkeystore method it looks like it is there as it is coming back in the log however when i try to call it using the loadkeystore method i get the log saying it can not find the key mysecurekeyi cannot find any reason for this and researching online has proven unfruitful so i was wondering if anyone has any idea what might be going wrong,['android'] +769753,whywhen is it important to specify an operator as explicit i have borrowed the code below from another question slightly modified to use in my code internal class positivedouble private double value public positivedoubledouble val if val 0 throw new argumentoutofrangeexceptionvalue needs to be positive value val this conversion is safe we can make it implicit public static implicit operator doublepositivedouble d return d value this conversion is not always safe so were supposed to make it explicit public static explicit operator positivedoubledouble d return new positivedoubled this constructor might throw exception the original author of this code correctly adheres to the warnings given in msdns implicit explicit documentation but heres my question is explicit always necessary in potentially exceptional code so i have got some types in my code eg volume that derive from positivedouble and i would like to be able to set instances conveniently like the first line belowvolume v 10 only allowed by implicit conversionvolume v new volume10 required by explicit conversion but gets messy quickbeing forced to use explicit casts everywhere makes the code much less readable how does it protects the user in the semantics of my program i never expect a volume to be negative indeed if it ever happens i expect an exception to be thrown so if i use an implicit conversion and it throws what unexpected results might clobber me,['c#'] +769837,calculate a 32bit crc lookup table in cc i want to calculate a 32bit crc lookup table one way i tried is by using the following code from this websiteinclude iostreaminclude stdinthvoid make crc table unsigned long polynomial 0x04c11db7 unsigned long width 8 sizeofunsigned long unsigned long topbit 1 width 1 unsigned long crctable256 unsigned long remainder compute the remainder of each possible dividend for int dividend 0 dividend 256 dividend start with the dividend followed by zeros remainder dividend width 8 perform modulo2 division a bit at a time for unsigned long bit 8 bit 0 bit try to divide the current data bit if remainder topbit remainder remainder 1 polynomial else remainder remainder 1 crctabledividend remainder print the crc table for int i 0 i 256 i if i 4 0 stdcout n stdcout stdhex crctablei stdcout int main make crc table return 0another way i tried is by using the following code that i found from this stackoverflow question and the code can be downloaded from here in a file called crc calculatorzipinclude iostreaminclude stdinthdefine polynomial 0x04c11db7uint32 t a crclookuptable256 0define width 8 sizeofuint32 tdefine topbit uint32 t1 width 1define fp reflect data dato datodefine fp reflect crctablevalue crctablevalue crctablevalueuint32 t f crc obtenvalordetablauint8 t vp pos tabla uint32 t vp crctablevalue 0 uint8 t vp pos bit 0 vp crctablevalue uint32 t fp reflect datavp pos tabla width 8 for vp pos bit 0 vp pos bit 8 vp pos bit if vp crctablevalue topbit vp crctablevalue vp crctablevalue 1 polynomial else vp crctablevalue vp crctablevalue 1 return fp reflect crctablevaluevp crctablevaluevoid f crc inicializatablavoid uint16 t vp pos array 0 for vp pos array 0 vp pos array 256 vp pos array a crclookuptablevp pos array f crc obtenvalordetablauint8 tvp pos array 0xff void make crc table f crc inicializatabla print the crc table for int i 0 i 256 i if i 4 0 stdcout n stdcout stdhex a crclookuptablei stdcout int main make crc table return 0here is what the correct final table should be based on this link the constants here are for the crc32 generator polynomial as defined in the microsoft systems journal march 1995 pp 107108const table array0255 of dword 0 77073096 ee0e612c 990951ba 076dc419 706af48f e963a535 9e6495a3 0edb8832 79dcb8a4 e0d5e91e 97d2d988 09b64c2b 7eb17cbd e7b82d07 90bf1d91 1db71064 6ab020f2 f3b97148 84be41de 1adad47d 6de4eb f4d4b551 83d385c7 136c9856 646ba8c0 fd62f97a 8a65c9ec 14015c4f 63066cd9 fa0f3d63 8d080df5 3b6e20c8 4c69105e d56041e4 a2677172 3c03e4d1 4b04d447 d20d85fd a50ab56b 35b5a8fa 42b2986c dbc9d6 acbcf940 32d86ce3 45df5c75 dcd60dcf abd13d59 26d930ac 51de003a c8d75180 bfd06116 21b4f4b5 56b3c423 cfba9599 b8bda50f 2802b89e 5f058808 c60cd9b2 b10be924 2f6f7c87 58684c11 c1611dab b62d3d 76dc4190 01db7106 98d220bc efd5102a 71b18589 06b6b51f 9fbfe4a5 e8b8d433 7807c9a2 0f00f934 9609a88e e10e9818 7f6a0dbb 086d3d2d 91646c97 e6635c01 6b6b51f4 1c6c6162 856530d8 f262004e 6c0695ed 1b01a57b 8208f4c1 f50fc457 65b0d9c6 12b7e950 8bbeb8ea fcb9887c 62dd1ddf 15da2d49 8cd37cf3 fbd44c65 4db26158 3ab551ce a3bc0074 d4bb30e2 4adfa541 3dd895d7 a4d1c46d d3d6f4fb 4369e96a 346ed9fc ad678846 da60b8d0 44042d73 33031de5 aa0a4c5f dd0d7cc9 5005713c 270241aa be0b1010 c90c2086 5768b525 206f85b3 b966d409 ce61e49f 5edef90e 29d9c998 b0d09822 c7d7a8b4 59b33d17 2eb40d81 b7bd5c3b c0ba6cad edb88320 9abfb3b6 03b6e20c 74b1d29a ead54739 9dd277af 04db2615 73dc1683 e3630b12 94643b84 0d6d6a3e 7a6a5aa8 e40ecf0b 9309ff9d 0a00ae27 7d079eb1 f00f9344 8708a3d2 1e01f268 6906c2fe f762575d 806567cb 196c3671 6e6b06e7 fed41b76 89d32be0 10da7a5a 67dd4acc f9b9df6f 8ebeeff9 17b7be43 60b08ed5 d6d6a3e8 a1d1937e 38d8c2c4 4fdff252 d1bb67f1 a6bc5767 3fb506dd 48b2364b d80d2bda af0a1b4c 36034af6 41047a60 df60efc3 a867df55 316e8eef 4669be79 cb61b38c bc66831a 256fd2a0 5268e236 cc0c7795 bb0b4703 220216b9 5505262f c5ba3bbe b2bd0b28 2bb45a92 5cb36a04 c2d7ffa7 b5d0cf31 2cd99e8b 5bdeae1d 9b64c2b0 ec63f226 756aa39c 026d930a 9c0906a9 eb0e363f 72076785 05005713 95bf4a82 e2b87a14 7bb12bae 0cb61b38 92d28e9b e5d5be0d 7cdcefb7 0bdbdf21 86d3d2d4 f1d4e242 68ddb3f8 1fda836e 81be16cd f6b9265b 6fb077e1 18b747 88085ae6 ff0f6a70 66063bca 11010b5c 8f659eff f862ae69 616bffd3 166ccf45 a00ae278 d70dd2ee 4e048354 3903b3c2 a7672661 d06016f7 4969474d 3e6e77db aed16a4a d9d65adc 40df0b66 37d83bf0 a9bcae53 debb9ec5 47b2cf7f 30b5ffe9 bdbdf21c cabac28a 53b39330 24b4a3a6 bad03605 cdd70693 54de5729 23d967bf b3667a2e c4614ab8 5d681b02 2a6f2b94 b40bbe37 c30c8ea1 5a05df1b 2d02ef8dhowever this is what my output is from both programs i diffed the output and it is the same for both of them and it is incorrect0 4c11db7 9823b6e d4326d9 130476dc 17c56b6b 1a864db2 1e475005 2608edb8 22c9f00f 2f8ad6d6 2b4bcb61 350c9b64 31cd86d3 3c8ea00a 384fbdbd 4c11db70 48d0c6c7 4593e01e 4152fda9 5f15adac 5bd4b01b 569796c2 52568b75 6a1936c8 6ed82b7f 639b0da6 675a1011 791d4014 7ddc5da3 709f7b7a 745e66cd 9823b6e0 9ce2ab57 91a18d8e 95609039 8b27c03c 8fe6dd8b 82a5fb52 8664e6e5 be2b5b58 baea46ef b7a96036 b3687d81 ad2f2d84 a9ee3033 a4ad16ea a06c0b5d d4326d90 d0f37027 ddb056fe d9714b49 c7361b4c c3f706fb ceb42022 ca753d95 f23a8028 f6fb9d9f fbb8bb46 ff79a6f1 e13ef6f4 e5ffeb43 e8bccd9a ec7dd02d 34867077 30476dc0 3d044b19 39c556ae 278206ab 23431b1c 2e003dc5 2ac12072 128e9dcf 164f8078 1b0ca6a1 1fcdbb16 18aeb13 54bf6a4 808d07d cc9cdca 7897ab07 7c56b6b0 71159069 75d48dde 6b93db 6f52c06c 6211e6b5 66d0fb02 5e9f46bf 5a5e5b08 571d7dd1 53dc6066 4d9b3063 495a2dd4 44190b0d 40d816ba aca5c697 a864db20 a527fdf9 a1e6e04e bfa1b04b bb60adfc b6238b25 b2e29692 8aad2b2f 8e6c3698 832f1041 87ee0df6 99a95df3 9d684044 902b669d 94ea7b2a e0b41de7 e4750050 e9362689 edf73b3e f3b06b3b f771768c fa325055 fef34de2 c6bcf05f c27dede8 cf3ecb31 cbffd686 d5b88683 d1799b34 dc3abded d8fba05a 690ce0ee 6dcdfd59 608edb80 644fc637 7a089632 7ec98b85 738aad5c 774bb0eb 4f040d56 4bc510e1 46863638 42472b8f 5c007b8a 58c1663d 558240e4 51435d53 251d3b9e 21dc2629 2c9f00f0 285e1d47 36194d42 32d850f5 3f9b762c 3b5a6b9b 315d626 7d4cb91 a97ed48 e56f0ff 1011a0fa 14d0bd4d 19939b94 1d528623 f12f560e f5ee4bb9 f8ad6d60 fc6c70d7 e22b20d2 e6ea3d65 eba91bbc ef68060b d727b6 d3e6a601 dea580d8 da649d6f c423cd6a c0e2d0dd cda1f604 c960ebb3 bd3e8d7e b9ff90c9 b4bcb610 b07daba7 ae3afba2 aafbe615 a7b8c0cc a379dd7b 9b3660c6 9ff77d71 92b45ba8 9675461f 8832161a 8cf30bad 81b02d74 857130c3 5d8a9099 594b8d2e 5408abf7 50c9b640 4e8ee645 4a4ffbf2 470cdd2b 43cdc09c 7b827d21 7f436096 7200464f 76c15bf8 68860bfd 6c47164a 61043093 65c52d24 119b4be9 155a565e 18197087 1cd86d30 29f3d35 65e2082 b1d065b fdc1bec 3793a651 3352bbe6 3e119d3f 3ad08088 2497d08d 2056cd3a 2d15ebe3 29d4f654 c5a92679 c1683bce cc2b1d17 c8ea00a0 d6ad50a5 d26c4d12 df2f6bcb dbee767c e3a1cbc1 e760d676 ea23f0af e2ed18 f0a5bd1d f464a0aa f9278673 fde69bc4 89b8fd09 8d79e0be 803ac667 84fbdbd0 9abc8bd5 9e7d9662 933eb0bb 97ffad0c afb010b1 ab710d06 a6322bdf a2f33668 bcb46d b8757bda b5365d03 b1f740b4,"['c++', 'c']" +769839,using thiscriminator in a entity that extends another i am trying to use a thiscriminator in a entity that extends from another this is the code i made ormentity ormtablenameusuarios externosusuarios schemausuarios externos orminheritancetypejoined ormthiscriminatorcolumnnamethiscr typestring ormthiscriminatormap natural natural empresa empresa uniqueentityfieldscorreo alternativo messageel correo electra3nico ya esta siendo usado gedmosoftdeleteablefieldnamedeletedat timeawarefalse class usuario extends baseuser but i am getting this error while ran the command doctrineschemavalidatedoctrineormmappingmappingexception entity usuariobundleentityusuario has to be part of the thiscriminator map of usuariobundleentityusuario to be properly mapped in the inheritance hierarchy alternatively you can make usuariobundleentityusuario an abstract class to avoid this exception from occurringany way to fix this it is possible to use thiscriminator in extended classes,['php'] +769843,uitableviewcell awakefromnib wrong frame size i have a uitableviewcell with constraints so that the cells layout correctly on iphone 6 and iphone 6the cell contents correctly resize correctly however i need to draw a sublayer gradient over one of the views inside in order to do so i am using awakefromnib to draw the sublayer awakefromnib is giving the size of the frame prior to it autoresizing and therefore the gradient subview is not the right size if i use layoutsubviews the first time it is called the size is also wrong and the cell needs to be scrolled before it has the right size so that method also is not workingwhat method should i be using to get the right frame size in order to draw correctly,"['objective-c', 'iphone']" +769869,android layout wrap two textview i would like to achieve the following layouta bwhere a is a textview ellipsize end and b is a textview as wellit will never have more than two lines i just need the first textview to be wrapped around the second sort ofhow should i do thatthanksedit added screenshot,['android'] +769947,why does gcc implement isnan more efficiently for c than c heres my codeint fdouble x return isnanxif i include cmath i get this assemblyxorl eax eaxucomisd xmm0 xmm0setp althis is reasonably clever ucomisd sets the parity flag if the comparison of x with itself is unordered meaning x is nan then setp copies the parity flag into the result only a single byte hence the initial clear of eaxbut if i include mathh i get this assemblyjmp isnannow the code is not inline and the isnan function is certainly no faster the the ucomisd instruction so we have incurred a jump for no benefit i get the same thing if i compile the code as cnow if i change the isnan call to builtin isnan i get the simple ucomisd instruction instruction regardless of which header i include and it works in c too likewise if i just return x xso my question is why does the c mathh header provide a less efficient implementation of isnan than the c cmath header are people really expected to use builtin isnan and if so whyi tested gcc 472 and 490 on x8664 with o2 and o3 optimization,"['c++', 'c']" +769962,why is app not getting registered for push notifications in ios 8 i upgarded my xcode to xcode 601 now remote notification registration is not happening for ios 8 device it is working fine for ios 7 devicei have added the code in app delegate as mentioned below set notificationif uidevice currentdevice systemversion floatvalue 80 uiusernotificationsettings settings uiusernotificationsettings settingsfortypesuiremotenotificationtypebadge uiremotenotificationtypesounduiremotenotificationtypealert categoriesnil uiapplication sharedapplication registerusernotificationsettingssettings nslogcurrent notifications uiapplication sharedapplication currentusernotificationsettingselse uiapplication sharedapplication registerforremotenotificationtypes uiusernotificationtypebadge uiusernotificationtypesound uiusernotificationtypealerteven the current notification is present and it is not niland yet the below method is not called voidapplicationuiapplicationapplication didregisterforremotenotificationswithdevicetokennsdatadevicetokenscreenshot below explains that i have enabled certain options in background modeand the notification is set in the device settings for my app,"['objective-c', 'iphone']" +770003,set visibility of progress bar gone on completion of image loading using glide library hi i want to have a progress bar for image which will shown while image loading but when image loading will be completed i want to set it to gone earlier i was using picasso library for this but i do not know how to use it with glide library i have idea that some resource ready function is there but i do not know how to use it can anyone help me code for picasso librarypicassowithmcontextloadimglinkarraygetpositionmurllink intoimageview new callback override public void onsuccess progressbarsetvisibilityviewgone override public void onerror now how can i do this with glideglidewithmcontextloadimglinkarraygetpositionmurllink intoimageviewi am able to load image by this with glide but how can i write progressbarsetvisibilityviewgone somewhere in code if image get loaded,['android'] +770034,uiactivityviewcontroller not showing my custom activity image in the more list on ios8 heres the screenshotin my subclass of uiactivity i override the activityimage method to use my own icon for the facebook share item but it appears in the share panel but thisappears in the more list,['ios'] +770150,windows mobile 65 vs windows embedded handheld 65 whats the difference i need to develop an app for a windows embedded handheld 65i start looking for some tutorials or documentation for a getting startedafter all i think i got the main facts but something still wonders mei look everywhere for an sdk or dtk but found nothingi found a small tutorial url herebut everything refers to windows mobile 65 sdk and dtk so is there really a difference between them or why do i need windows mobile 65 to develop for windows embedded handheld 65or am i totally wrong,['c#'] +770173,what is the right way to override a property in a subclass in swift i also stumbled upon this question however there is no definitive answerambiguous use of propertyname error given overridden property with didset observerproblem i would like to override a property in a subclasslet me illustrate the problem with an example i have a class called a and a subclass thereof called bclass aclass a var somestoredproperty int class bclass b a override var somestoredproperty int willset add to superclas setter somestoredproperty newvalue 10 as soon as i try to set the inherited property of b var b bbsomestoredvalue 10 ambiguous use of somestoredpropertythe compiler tells me ambiguous use of somestoredpropertywhy is that update class tableviewrow typealias clickaction tableviewuitableview indexpathnsindexpath void var clickaction clickactionclass switchtableviewrow tableviewrow override var clickaction clickaction didset override setter usage var switchrow switchtableviewrowswitchrowclickaction ambiguous use of clickactionunowned self unowned switchrow tableview uitableview indexpath nsindexpath in do something,['ios'] +770189,swift ios module not being deployed to expected debug directory i have a moduleframework written in swift intended to be used on ios when i try to include the framework in my app i first notice some red not found hints in the build phasesbut the project builds fine the target dependency is found so there are no compilation issues it is just the resulting built framework and sure enough upon launching i have a linker error it cannot find the image looking at the build log it is looking hereuserscraigprojectsfluffybuilddebugiphoneoswhich makes sense that is what is defined in the build settings for my frameworkbut the copy fails as the source framework does not existpbxcp userscraigprojectsfluffybuilddebugiphoneosfluffy iosframework userscraiglibrarydeveloperxcodederiveddatamyappdcjfhcnyzkwzxiejuuxqlsgajrebbuildproductsdebugiphoneosmyappframeworksfluffy iosframeworkerror userscraigprojectsfluffybuilddebugiphoneosfluffy iosframework no such file or directoryhowever looking at the build log for my framework i see that it is actually ending up hereuserscraiglibrarydeveloperxcodederiveddatafluffyfuuewsvogdkycegheyrsabkiicxcbuildproductsdebugiphonesimulatorfluffy iosframeworki suppose that makes sense deriveddata has for a while now been the default location for any built productsand when i take a look at the expected build folder there is not much a lot of it is old and none of it relates to the debug configurationso my questions are why is my framework being placed in the deriveddata folder when it seems to be asking in the build settings to be placed in the build folder relative to the project are these parameters perconfiguration build products path etc consulted at alland what should i do to reconcile this how can my application know to look in the right deriveddata folder for the framework for the right configuration debug vs release in a way that is extensible and will work without me having to manually specify the absolute path to it,['ios'] +770266,how to generate html documentation for swift files in xcode with headerdoc i tried to document my swift project in xcode with headerdoc but are processed only files h and are ignored files swiftthis is my swift file test param ann blablafunc testfunc ann foo i run the following in the terminalheaderdoc2html o desktopdocum ninjathis is the error documentation will be written to usersmedesktopdocum html output mode no valid input files specified usage headerdoc2html dq o output directory input files or directory imacmyapp me headerdoc2html o desktopdocum ninja documentation will be written to usersmedesktopdocum html output mode dir ninja parsing input files processing ninjatestm skipping no headerdoc comments found processing ninjabridgingheaderh,['ios'] +770270,pip install dependency links i am using python version 27 and pip version is 156 i want to install extra libraries from url like a git repo on setuppy is being installed i was putting extras in install requires parameter in setuppy this means my library requires extra libraries and they must also be installedinstall requires django but urls like git repos are not valid string in install requires in setuppy assume that i want to install a library from github i have searched about that issue and i found something which i can put libraries such that in dependency links in setuppy but that still does not work here is my dependency links definitiondependency links the links are valid i can download them from a internet browser with these urls these extra libraries are still not installed with my setting up i also tried processdependencylinks parameter to force pip but result is same i take no error when pippingafter installation i see no library in pip freeze result in dependency linkshow can i make them to be downloaded with my setuppy installationeditedhere is my complete setuppyfrom setuptools import setuptry long description openreadmemdreadexcept ioerror long description setup nameesefsso version10 description url keywordsdjango egemsoft sso esefsso install requires django webservices requests esefauth10 djangosimplesso093 dependency links packages esef sso client esef sso clientmodels esef sso server esef sso servermodels include package datatrue zip safefalse platformsanyedited 2here is pip logdownloadingunpacking esefauth10 from esefsso10 getting page could not fetch url 404 client error not found will skip url when looking for download links for esefauth10 from esefsso10 getting page urls to search for versions for esefauth10 from esefsso10 getting page could not fetch url 404 client error not found will skip url when looking for download links for esefauth10 from esefsso10 getting page could not fetch url 404 client error not found will skip url when looking for download links for esefauth10 from esefsso10 could not find any downloads that satisfy the requirement esefauth10 from esefsso10cleaning up removing temporary dir usersahmetdalvirtualenvsesefssoexamplebuildno thistributions at all found for esefauth10 from esefsso10exception informationtraceback most recent call last file usersahmetdalvirtualenvsesefssoexamplelibpython27sitepackagespipbasecommandpy line 122 in main status selfrunoptions args file usersahmetdalvirtualenvsesefssoexamplelibpython27sitepackagespipcommandsinstallpy line 278 in run requirement setprepare filesfinder force root egg infoselfbundle bundleselfbundle file usersahmetdalvirtualenvsesefssoexamplelibpython27sitepackagespipreqpy line 1177 in prepare files url finderfind requirementreq to install upgradeselfupgrade file usersahmetdalvirtualenvsesefssoexamplelibpython27sitepackagespipindexpy line 277 in find requirement raise thistributionnotfoundno thistributions at all found for s reqthistributionnotfound no thistributions at all found for esefauth10 from esefsso10it seems it does not use the sources in dependency links,['python'] +770332,better way to condition preference sql i have a table named items as followsid oid key value1 0 color green2 0 size 303 1 color red 4 2 color blueabove rows with oid0 specifies the default values of items i need to select all key value of an item with a particular oid which will include the default oid0 if a specific key and value for that oid does not existsfor eg for item 2 it should returnid oid key value1 0 size 302 2 color bluei have written the following queryselect from items as iwhere ioid0 andikey not in select key from items where oid2 union allselect from items where oid2is there a way to optimize the above query,"['php', 'mysql', 'sql']" +770454,do i need to return after throw in javascript i am throwing an error from a method of mine that i want an early exit from as below no route foundifnull nextroute throw new errorbad routedo i need to put a return statement after my throw it works for me for now if it is superfluous i would rather not put it in but i cannot be sure what different browsers might do,['javascript'] +770460,can i override operators in c i knew that we can overload operators for a class but my question is whether i can override operators let us consider that i have a base class and derived class is it possible to override an operator defined overloaded in the base class in the derived class as with function overriding,['c++'] +770512,passing a collection to editorfor in aspnet mvc i have a lengthy form which i have broken to several parts and am using htmleditorfor for each section which is working great but need your thoughts on whether this approach can be improved or notthere are segments and every segment can have multiple activities so i have a collection of segments and every segment in this collection contains a collection of activities public class activity public string activityid get set public string activitydescription get set public bool isselected get set public class segment public string segmentid get set public string segmentdescription get set public listactivity activitites get set this was how i wanted the viewmodel that i use as a model for the view should look like but could not make it to work since htmleditorfor did not accept a collection type public class userpreferencesviewmodel other properties public listsegment segments get set here is the viewmodelmodel userpreferencesviewmodel other properties htmleditorform msegments i assigned segments three segments in the controller get methodhere is the editorfor template for segmentsmodel listsegment other properties foreachvar segment in model do the stuff but this does not work saying editorfor cannot take collections and the exception is thrown at runtimehere is my work around i created another class uglysegmentworkaround which contains the segment collection and then in the userpreferencesviewmodel i removed the list property and instead defined a property for thatpublic class uglysegmentworkaroundpublic listsegment segments get setpublic class userpreferencesviewmodel other properties public uglysegmentworkaround uglysegmentworkaround get set and here is the editorfor templatemodel uglysegmentworkaround other properties foreachvar segments in modelsegments do the stuff it works perfectly but i just do not feel comfortable with this approach is there anything i am missing in the first approach how this should be done i do not want the editorfor to do an implicit loop if i pass it a collection because i am rendering a complex ui structure in the editorfor and i need the editorfor to have the loop inside it,['asp.net'] +770529,pip does not acknowledge cython i just installed pip and python via homebrew on a fresh mac os installationfirst of all my pip is not installing dependencies at all which forces me to rerun pip install tables 3 times and every time it will tell me a dependency and i will install that and then rerun it again is this expected behaviorsecond it does not accept the installation of cython that it installed itself moments ago pip show cythonname cythonversion 021location usrlocallibpython27sitepackagesrequires but pip install tablesdownloadingunpacking tables downloading tables311targz 67mb 67mb downloaded running setuppy pathprivatevarfoldersr 9cc9 ldj7g35cqnfql52hqt80gntpip build excuvatortablessetuppy egg info for package tables using python 278 default aug 24 2014 212619 found numpy 190 package installed found numexpr 24 package installed error you need cython 013 or greater to compile pytables complete output from command python setuppy egg info using python 278 default aug 24 2014 212619 found numpy 190 package installed found numexpr 24 package installed error you need cython 013 or greater to compile pytables,['python'] +770573,robust atanyx on glsl for converting xy coordinate to angle in glsl specifically 300 that i am using there are two versions of atan atany over x can only return angles between pi2 pi2 while atanyx can take all 4 quadrants into account so the angle range covers everything from pi pi much like atan2 in c i would like to use the second atan to convert xy coordinates to anglehowever atan in glsl besides not able to handle when x 0 is not very stable especially where x is close to zero the division can overflow resulting in an opposite resulting angle you get something close to pi2 where you suppose to get approximately pi2what is a good simple implementation that we can build on top of glsl atanyx to make it more robust,['c++'] +770574,ios8 scale glitch when calling drawviewhierarchyinrect afterscreenupdatesyes i was converting a project from ios7 to ios8 which uses custom transitions and needs to capture the modal after it finishes loading afterscreenupdatesyes and was seeing that the entire screen scale up for a second and scale back down i also see this happening in the flickr app for ios between sections and on yelp app when transitioning to a photo on ios8 uigraphicsbeginimagecontextwithoptionsselfviewframesize yes 220 selfview drawviewhierarchyinrectselfviewframe afterscreenupdatesyes uigraphicsendimagecontextadding a larger scale factor helps emphasize the glitch more but i am just calling this on a button press in the exampleedit this appears to happen on iphone 6 and 6 plus not on the 5sample project github,['ios'] +770601,openlayers 3 how to calculate thistance between 2 points using openlayers 3 how can i determine the thistance between two points in the spherical mercator srid 3857 projectioni know that thistanceto was used in openlayers 2point1thistancetopoint2i looked through the openlayers 3 docs but i am not finding anything similar,['javascript'] +770834,ios 8 uitableviewrowaction swipe left images i have just come across this new api on ios8 i cannot however find any solution on if it is possible to use images instead of text and to allow left and right swipe is this even possible the only implementation i have found is this nsarray tableviewuitableview tableview editactionsforrowatindexpathnsindexpath indexpath uitableviewrowaction moreaction uitableviewrowaction rowactionwithstyleuitableviewrowactionstylenormal titlebutton1 handleruitableviewrowaction action nsindexpath indexpath maybe show an action sheet with more options selftableview seteditingno moreactionbackgroundcolor uicolor bluecolor uitableviewrowaction moreaction2 uitableviewrowaction rowactionwithstyleuitableviewrowactionstylenormal titlebutton2 handleruitableviewrowaction action nsindexpath indexpath selftableview seteditingno moreaction2backgroundcolor uicolor bluecolor uitableviewrowaction deleteaction uitableviewrowaction rowactionwithstyleuitableviewrowactionstyledestructive titledelete handleruitableviewrowaction action nsindexpath indexpath selftableview deleterowsatindexpathsindexpath withrowanimationuitableviewrowanimationautomatic return deleteaction moreaction moreaction2,"['ios', 'objective-c']" +770863,cfurlcopyresourcepropertyforkey failed because passed url no scheme i have a program that saves a file to the icloud and this has worked great for ios7 but now i get this error with ios8 and cannot seem to find the answer on how to fix it anyone else had this problem any ideas would be greatly appreciatedthe errorcfurlcopyresourcepropertyforkey failed because it was passed this url which has no scheme varmobilecontainersdataapplicationasfhdde3b1bb41d7a47cdcc328362w21documentsmypictostorepngthe line of code throws errorfilemanager setubiquitousyes itematurlbackupurl destinationurlubiq urlbyappendingpathcomponentdocuments isdirectorytrue urlbyappendingpathcomponentbackupname errortheerrorurlsdestinationurl fileprivatevarmobilelibrarymobile20documentsabc23455myprogrambackupurl varmobilecontainersdataapplicationasdfgeewb1bba6fr6a47cdccf21876d36documentsmypicpngthank youjon,['objective-c'] +771059,swift converting between uint and int i have the following methodsvar photos mwphoto mwphotofunc numberofphotosinphotobrowserphotobrowser mwphotobrowser uint return selfphotoscountfunc photobrowserphotobrowser mwphotobrowser photoatindex index uint mwphotoprotocol return selfphotosindexhowever for the first i get int is not convertible to uint since selfphotoscount is an int and for the second uint is not convertible to int since the selfphotos can only take an int for its indexhow can i correctly convert the uint to int and back,['ios'] +771075,python unittest to mockpatch or just replace method with mock when mocking classes or methods when writing unittests in python why do i need to use patch decorator i just could replace the method with mock object without any patch annotationexamplesclass testfoobarunittesttestcasedef setupself selffoobar foobar 1 with patch decoratorpatchobjectfoobar get barpatchobjectfoobar get foodef test get foobar with patchself mock get foo mock get bar mock get barreturn value bar1 mock get fooreturn value foo1 actual selffoobarget foobar selfassertequalfoo1bar1 actual 2 just replacing the real methods with mock with proper return valuedef test get foobar with replacementself selffoobar get foo mockreturn valuefoo2 selffoobar get bar mockreturn valuebar2 actual selffoobarget foobar selfassertequalfoo2bar2 actualcould someone produce an example where patch decorator is good and replacing is badwe have always used patch decorator with our team but after reading this comment for a post i got the idea that maybe we could write nicerlooking code without the need of patch decoratorsi understand that patching is temporary so maybe with some cases it is dangerous to not use patch decorator and replace methods with mock instead could it be that replacing objects in one test method can affect the result of the next test methodi tried to prove this but came up empty both tests pass in the next codedef test get foobar with replacementself selffoobar get foo mockreturn valuefoo2 selffoobar get bar mockreturn valuebar2 actual selffoobarget foobar selfassertisinstanceselffoobar get bar mock selfassertisinstanceselffoobar get foo mock selfassertequalfoo2bar2 actualdef test get foobar with real methodsself actual selffoobarget foobar selfassertnotisinstanceselffoobar get bar mock selfassertnotisinstanceselffoobar get foo mock selfassertisinstanceselffoobar get bar typesmethodtype selfassertisinstanceselffoobar get foo typesmethodtype selfassertequalfoobar actualfull source code python 33 dropboxcomst8bewsdaalzrgketest foobarpydl0,['python'] +771211,permissionerror winerror 5 access is denied python using moviepy to write gif i am using windows 81 64 bitmy codeimport pdbfrom moviepyeditor import clip videofileclipamp4clipwrite gifaasdagifthe exception is at write gif methodtraceback most recent call last file cabiyoutubetogif projecttestpy line 5 in module clipwrite gifgabiaasdagif file string line 2 in write gif file cpython34libsitepackagesmoviepy021812py34eggmoviepydecoratorspy line 49 in requires duration return fclip a k file cpython34libsitepackagesmoviepy021812py34eggmoviepyvideovideoclippy line 435 in write gif thispose thispose colorscolors file string line 2 in write gif file cpython34libsitepackagesmoviepy021812py34eggmoviepydecoratorspy line 49 in requires duration return fclip a k file cpython34libsitepackagesmoviepy021812py34eggmoviepyvideoiogif writerspy line 186 in write gif stdoutsppipe file cpython34libsubprocesspy line 848 in init restore signals start new session file cpython34libsubprocesspy line 1104 in execute child startupinfopermissionerror winerror 5 access is deniedi moved the script to another folder and partition running moviepy dependancies and python as admin turning off uac still gives me error,['python'] +771297,what is stamped locks in java i am working on a java code i need to implement threading in it i was going through java 8 api and i come to know about stamped locks can anyone tell me why to use stamped locks in multithreading thanks in advance,['java'] +771308,safe activerecord like query i am trying to write like queryi read that pure string quires are not safe however i could not find any documentation that explain how to write safe like hash queryis it possible should i manually defend against sql injection,['ruby'] +771330,why are stdfstreams so slow i was working on a simple parser and when profiling i observed the bottleneck is in file read i extracted very simple test to compare the performance of fstreams and file when reading a big blob of datainclude stdiohinclude chronoinclude fstreaminclude iostreaminclude functionalvoid measureconst stdstring test stdfunctionvoid function auto start time stdchronohigh resolution clocknow function auto duration stdchronoduration caststdchrononanosecondsstdchronohigh resolution clocknow start time stdcouttest static castdoubledurationcount 01 msstdendldefine buffer size 1024 1024 1024int mainint argc const char argv auto buffer new charbuffer size memsetbuffer 123 buffer size measurefile write buffer file file fopentest file write wb fwritebuffer 1 buffer size file fclosefile measurefile read buffer file file fopentest file read rb freadbuffer 1 buffer size file fclosefile measurefstream write buffer stdofstream streamtest stream write stdiosbinary streamwritebuffer buffer size measurefstream read buffer stdifstream streamtest stream read stdiosbinary streamreadbuffer buffer size delete bufferthe results of running this code on my machine are file write 138859 msfile read 129251 msfstream write 310538 msfstream read 331982 msfstream writeread are about 2 times slower than file writeread and this while reading a big blob of data without any parsing or other features of fstreams i am running the code on mac os intel i7 26ghz 16gb 1600 mhz ram ssd drive please note that running again same code the time for file read is very low about 200 ms probably because the file gets cached this is why the files opened for reading are not created using the codewhy when reading just a blob of binary data using fstream is so slow compared to fileedit 1 i updated the code and the times sorry for the delayedit 2 i added command line and new results very similar to previous ones clang maincpp stdc11 stdliblibc o3 aoutfile write 14179 msfile read 129259 msfstream write 321402 msfstream read 305256 msfollowing the results for the second run aoutfile write 142898 msfile read 196902 msfstream write 334369 msfstream read 228593 msit looks like the file gets cached when reading for both file and stream as the time reduces with the same amount for both of themedit 3 i reduced the code to thisfile file fopentest file write wbfwritebuffer 1 buffer size filefclosefilestdofstream streamtest stream write stdiosbinarystreamwritebuffer buffer sizeand started the profiler it seems like stream spends lots of time in xsputn function and the actual write calls have the same duration as it should be it is the same functionrunning time self symbol name32660ms 669 00 std 1basic ostreamchar std 1char traitschar writechar const long32650ms 669 21450 std 1basic streambufchar std 1char traitschar xsputnchar const long11200ms 229 70 std 1basic filebufchar std 1char traitschar overflowint120ms 227 20 fwrite11270ms 230 00 fwriteedit 4 for some reason this question is marked as duplicate i wanted to point out that i do not use printf at all i use only stdcout to write the time the files used in the read part are the output from the write part copied with different name to avoid caching,['c++'] +771352,adding a promise to a google maps api call i need to return an array from a function in javascriptjquery but the function is returning before the array has been set as it is an ajax call i have been advised to use a promise but i have not used these before and have so far been unable to implement this into my code here is my codemapclasetlatlng functionlocation clubs documentgeocoderequestcompleteflag 0 geocoder new googlemapsgeocoder geocodergeocodeaddress location functionresults status consolelogresults ifstatus ok var latlngarray latlngarraypushparsefloatresults0geometrylocationlat latlngarraypushparsefloatresults0geometrylocationlng var sortedarray mapclasscalculatethistancesclubs latlngarray return sortedarray as you can see the sortedarray variable is empty when i return is does anyone have any ideas as to how i could add blocking code into this to ensure the array variables are set before returningthanks,"['javascript', 'jquery']" +771576,getting the remote certificate is invalid according to the validation procedure when smpt server has a valid certificate this seems a common error but while i have found a workaround see below i cannot pin down the reason i am getting it in the first placei am writing smtp functionality into our application and i am attempting to add ssl functionality to the working smtp we already havei am testing using our companys ms exchange server and specifically the webmail option enabled on that i can send emails internally through my code by not authenticating my connection and sending anonymously however those emails would not relay to external email addresses due to our companies policy besides which i am programming this for our customers and they do not all allow open relay andor anonymous connectionsi believe the exchange server is using explicit ssl tls i have tried telnet to the servers address on port 25 and got a text response human readable response which according to some of my searches previously means it is using explicit ssl tlsi have the following test codesmtpclient smtpclient new smtpclientwebmailaddresmtpclientport 25smtpclientusedefaultcredentials truesmtpclientenablessl truesystemnetmailmailmessage message new systemnetmailmailmessageemailfromemailtosubjectbodysmtpclientsendmessageduring my searching for a solution i came across this the remote certificate is invalid according to the validation procedure using gmail smtp serverfrom which i got the following codeservicepointmanagerservercertificatevalidationcallback new remotecertificatevalidationcallbackvalidateservercertificatepublic static bool validateservercertificateobject senderx509certificate certificatex509chain chainsslpolicyerrors sslpolicyerrors if sslpolicyerrors sslpolicyerrorsnone return true else if systemwindowsformsmessageboxshowthe server certificate is not validnaccept certificate validation systemwindowsformsmessageboxbuttonsyesno systemwindowsformsmessageboxiconquestion systemwindowsformsdialogresultyes return true else return false this works in my test code however the actual process i am writing rather than my test code is going to run in the background and cannot really ask the user instead it reports errors in the windows error logas i started my question is really why i am getting this error at all if i go to httpswebmailourdomaincouk in a browser it shows a valid certificate and there is no option to install the certificate as i would have done if it were a selfsigned onehowever when i run my code with a debug break poing in the validateservercertificate method i look at the certificate values and see an issuer of our local server and do not use before and do not use after properties of today this does not match the certificate i am gettingi have also checked what the sslpolicyerrors flags are in the debug of validateservercertificate and they are showing remotecertificatechainerrors and remotecertificatenamemismatchso what am i missing about this why is it not using the correct certificate if there are steps i need to take to install the certificate locally for it to use then i need to know them so i can tell my customers what to do if they get thisi do not want to just bypass the check by returning true from the validateservercertificate method and because it is a background process i cannot ask the user so i need to understand how to get my code to use the correcttrusted certificatehope someone can advise,['c#'] +771661,unknown template object error with handlebars 20 runtime i have published all my code as a runnable that uses express for loading static contenti have precompiled this handlebars template img srccoverimageul lititleli liauthorli lireleasedateli likeywordsliuldeletei have obtained this function function var template handlebarstemplate templates handlebarstemplates handlebarstemplates templatesbooktemplate templatefunction handlebarsdepth0helperspartialsdata thiscompilerinfo 4 100helpers thismergehelpers handlebarshelpers data data var buffer stack1 helper functiontypefunction escapeexpressionthisescapeexpression buffer img src if helper helperscoverimage stack1 helpercalldepth0 hashdatadata else helper depth0 depth0coverimage stack1 typeof helper functiontype helpercalldepth0 hashdatadata helper buffer escapeexpressionstack1 rn ulrn li if helper helperstitle stack1 helpercalldepth0 hashdatadata else helper depth0 depth0title stack1 typeof helper functiontype helpercalldepth0 hashdatadata helper buffer escapeexpressionstack1 lirn li if helper helpersauthor stack1 helpercalldepth0 hashdatadata else helper depth0 depth0author stack1 typeof helper functiontype helpercalldepth0 hashdatadata helper buffer escapeexpressionstack1 lirn li if helper helpersreleasedate stack1 helpercalldepth0 hashdatadata else helper depth0 depth0releasedate stack1 typeof helper functiontype helpercalldepth0 hashdatadata helper buffer escapeexpressionstack1 lirn li if helper helperskeywords stack1 helpercalldepth0 hashdatadata else helper depth0 depth0keywords stack1 typeof helper functiontype helpercalldepth0 hashdatadata helper buffer escapeexpressionstack1 lirn ulrnbutton classdeletedeletebutton return buffer i have added the scripts like this script srcjslibhandlebarsruntimev200jsscript script srcjstemplatesjsscripti see in chrome dev tools that both scripts loadhowever when i use it like this inside a backbone view templatehandlebarstemplatesbooktemplatei get this error uncaught error unknown template object function handlebarsruntimev200js455template handlebarsruntimev200js455hbtemplate handlebarsruntimev200js644anonymous function templatesjs3anonymous functioni get this error at line 455 in handlebars runtime 200 in the function templateupon doing a little debugging i find that templatespec is a functionbut templatespecmain is undefined this function makes a call to templatesbooktemplate templatefunction handlebarsdepth0helperspartialsdata in the booktemplatejs function templatetemplatespec env istanbul ignore next if env throw new exceptionno environment passed to templateerror occurs here if templatespec templatespecmain throw new exceptionunkn own template object typeof templatespecadditionally i find that handlebarstemplates is an empty objectwhat is going on here,['javascript'] +771765,is it already worth to give derbyjs or meteor a shot for an app for production with authentication i started reading about derbyjs and meteor to do some research on an project i am working on it uses a lot of real time functionalities so they both seem handy but i have some major concerns and am wondering if it makes sense to use them at this timeare they yet production ready or are there still major security issuesdo they by now support sessions and authenticationam i right with the assumption that by relying on frameworks that do a lot of the work you might have it easier for the simple stuff but much much harder if it gets a bit more complicatedam i right with the assumption that i could achieve exactly the same effects from a userexperience perspective when i just use express socketio or expressio and that i just have to invest more timeworkat the moment i am more drawn to express socketio and think derby and meteor are a bit hyped what do you thinkto get a better idea of what i am planninguser authentication is neededcomplex routing is neededseo is an issuefull text search using elasticsearch db probably mongodbcomplex relations between objectsrealtime updates socketiosecurity is an issueperformance and scalability are issuesthanks,['javascript'] +771783,why are my uisegmentcontrol segments highlighting in ios 8 when i have set background images for all states in ios 67 i have used uisegmentedcontrol with background images to create an effect like soi accomplished this by setting the background image for the uisegmentedcontrol for each of standard states like souiimage segmentedcontrolbackgroundimage uiimage imagenamedprofilesegmentedcontrolbackgrounduiimage segmentedcontrolbackgroundselectedimage uiimage imagenamedprofilesegmentedcontrolbackgroundselectedselfsegmentedcontrol setbackgroundimagesegmentedcontrolbackgroundimage forstateuicontrolstatenormal barmetricsuibarmetricsdefaultselfsegmentedcontrol setbackgroundimagesegmentedcontrolbackgroundimage forstateuicontrolstatethisabled barmetricsuibarmetricsdefaultselfsegmentedcontrol setbackgroundimagesegmentedcontrolbackgroundselectedimage forstateuicontrolstatehighlighted barmetricsuibarmetricsdefaultselfsegmentedcontrol setbackgroundimagesegmentedcontrolbackgroundselectedimage forstateuicontrolstateselected barmetricsuibarmetricsdefaultwhen a segment becomes select or is highlighted it has the nice blue bar underneath and i set text attributes to change the text color to be blue there is some extra code for the dividers but i think that is unrelated so i have omitted itmy problem is that in ios 8 there are a couple of actions that cause the background of the segment to turn gray and look bad one being when you change your selection the cell you tapped turns gray until the transition completes and the other is that if you tap and hold an already selected segment it turns gray both look identical and can be seen belowsome extra pieces of possibly relevant informationthe tintcolor for the segmentedcontrol is cleari am not subclassing uisegmentedcontroli have not changed any properties for uisegmentedcontrol using its appearance proxyi am using 1 point wide images for the background images and uisegmentedcontrol is automatically determining the capinsets and tiling the image,['ios'] +771812,why is the extension of my swift class not visible outside the defining file i have an xcodegenerated nsmanagedobject class for my coredata modelobjcsomeclass class someclass nsmanagedobject it is defined in a file named someclaswift i would like to extend this class so i created someclassextensionswift i define the extension like thisextension someclass class func typemethod1 func instancemethod2 these extension methods can be used within this defining file but they are not visible outside of it what is causing this issue,['ios'] +771814,file to import not found or unreadable compasscss3animation i need to use animation wih compass so i try to use like said in doc i put at top of my fileimport compasscss3animationbut i have error file to import not found or unreadable compasscss3animationi have the latest version of compass and railscompass gem so i do not know where is my mistakethx,['ruby-on-rails'] +771838,android create circular image with picasso the question had been asked and there had been a promise made for the very version of picasso that i am using how do i send a circular bitmap to an imageview using picasso i am very new to picasso and only thing i have used so far is picassowithcontextloadurlresizew hintoimageviewi have already found but i am not sure how to combine it with the line above in a nonackward way,['android'] +771924,responsive grid of hexagons i loaded in multiple images on my website from the internet is it possible to give all those images an hexagon shape in a responsive griddiv img srclink classimagedivdiv img srclink classimagedivi found multiple ways to do this but you needed to fill in the image src in the css codethis isnt possible for me cause the website loads in random images from the internet with jquery so i cannot use background imagesi tried this,"['html', 'css']" +771969,php extension mcrypt must be loaded i was following a tutorial online about installing magento on ubuntu but i get this error at the config php extension mcrypt must be loaded i already tried sudo aptget install php5mcrypt but this did not work for me i had the same problem with curl but when i tried sudo aptget install php5curl it did work for me how do i fix this with mcrypt i already tried to restart the webserver,['php'] +771999,dragdrop not working in nhaarmans listviewanimation library i am using nhaarmans listviewanimation library which works greatbut i am facing following issuesthe main problem i am facing is i am not able to debug my code i have directly copypasted the four required libraries into libs folder placing a debug point inside any of the listview methods like onitemlongclick does not workthe second problem is dragdrop listview is not working in my code whenever i try to drag any list item on dropping the list item the item takes the same position from which it was draggedheres the code i have usedlistviewenabledraganddroplistviewsetdraggablemanagernew touchviewdraggablemanager ridlist row draganddrop textviewlistviewsetonitemmovedlistenerthislistviewsetonitemlongclicklistenerthisoverride public void onitemmovedfinal int originalposition final int newposition if mtoast null mtoastcancel mtoast toastmaketextgetapplicationcontext moved swingbottominanimationadaptergetitemnewposition newposition toastlength short mtoastshow override public boolean onitemlongclickfinal adapterview parent final view view final int position final long id if listview null listviewstartdraggingposition listviewgetheaderviewscount return true,['android'] +772029,free transform plugin for svg creating placeholder element i am trying to create html5 collage editor where you can edit images in similar way to one you see in word cropping images instead of scaling them when dragging edges being able to dragrotatescale images inside free transform area so sort of placeholder funcionality etc it means we need using svg and clippingmasking and binding position of free transform elements to those masksclippingswhole generated svg should later be scalable for print dimensions but that is not the issue herethe idea is simple use already made jquery free transform plugin bind it is controlls area transformation to svg masksthe issueeven if transformed svg mask has exact copy of transformation and position of ft div it acts weird when transformation contains rotationseems like transform origin does not work rotating and scaling somehow is connected to leftupper corner instead of center do not know whyhere is a fiddle just try to rotate element and you will see what is the problemfiddle simplifed code with already made svgmain js part var refreshsvgmask functionget element transformvar eltransform ftcsstransformquick parse of matrix transformvar elmatrix eltransformsubstringeltransformindexofmatrix 7 eltransformindexofmodify matrix to apply last two values top and left position which in jquery free transform are in top and left css attributes note i have also tried applying same matrix but changing x and y attributes in svg like attrx eltop got exactly same results var eltop parseintftpositiontopvar elleft parseintftpositionleftvar matrixchanged elmatrixsubstring0 elmatrixlength6 elleft eltopapply matrix to svg elementsvgjsrect1008attrtransform matrixmatrixchangedattrtransformorigin 5050 also put transform origin but it does not seem to workdoes anybody know how to fix this i am starting to loose my mind on this edit 1 08102014following advice given in comment by phorgz i have recreated svg with svgjs library in order to add transformation separately instead of copy whole matrix and before applying rotation i have repositioned it to it is orgin and then restore it is proper positionfiddleas you can see it is little bit better rotated mask is somehow closer to ft positions but still it is not in proper place,"['javascript', 'jquery']" +772080,reactjs how to pass global data to deeply nested child components how do people typically approach having global data in a react applicationfor example say i have the following data for a user once they are logged into my appuser email name john doethis is data that almost any component in my app might like to know about so it could either render in a logged in or logged out state or perhaps thisplay the users email address if logged infrom my understanding the react way of accessing this data in a child component is for a top level component to own the data and pass it to child components using properties for exampleapp page1 page2 widget1 widget2 useruser page2appbut this seems unwieldy to me as that would mean i would have to pass the data through each composite just to get it to the child that needed it is there a react way of managing this type of data note this example is very simplified i like to wrap intents up as composites so implementation details of entire ui features can be drastically changed as i see fitedit i am aware that by default calling setstate on my top level component would cause all child components to be rerendered and that in each child component i can render using whatever data i like eg global data not just state or props but how are people choosing to notify only certain child components that they should be rendered,['javascript'] +772215,why does msvc emit a useless movsx before performing this bit test compiling the following code in msvc 2013 64bit release build o2 optimizationwhile s s s r s n si get the following code which has a really cool optimization using a 64bit register as a lookup table with the bt bit test instruction mov rcx 17596481020928 0100102400h npad 5ll82myfunc movzx eax byte ptr rsi cmp al 44 02ch ja short ln81myfunc movsx rax al bt rcx rax jae short ln81myfunc inc rsi jmp short ll82myfuncln81myfunc code after loopbut my question is what is the purpose of the movsx rax al after the first branchfirst we load a byte from the string into rax and zeroextend itmovzx eax byte ptr rsithen the cmpja pair performs an unsigned comparison between al and 44 and branches forwards if al is greaterso now we know 0 al 44 in unsigned numbers therefore the highest bit of al could not possibly be setnonetheless the next instruction is movsx rax al this is a signextended move but sinceal is the lowest byte of raxwe already know the other 7 bytes of rax are zeroedwe just proved that als highest bit could not possibly be setthis movsx must be a noopwhy does msvc do it i am assuming it is not for padding since in that case another npad would make the meaning clearer is it flushing data dependencies or somethingby the way this bt optimization really makes me happy some interesting facts it runs in 06x the time of the 4 cmpje pairs you might expect it is way faster than strspn or stdstringfind first not of and it only happens in 64bit builds even if the characters of interest have values under 32,['c++'] +772404,how to use lambda expressions for a function that takes a list of delegates i am building an extension method on ilist to be able to output the specified properties of any object passed into it as a list and output it as a csv string it looks likepublic static string outputcsvstringtthis ilistt list listfunct string properties foreach var row in list foreachvar item in properties do the output work including calling itemrow output new line right now i have to call this method like assuming i have populated list product productlist up abovevar columns new listfuncproduct stringcolumnsaddx xidcolumnsaddx xnamestring s productlistoutputcsvstringcolumnsis there a better way to pass in my lambda expressions without having to explicitly declare the columns variable something like this does not compilestring s productsoutputcsvstringnew p pid p pname,['c#'] +772462,simulating palette swaps with opengl shaders in libgdx i am trying to use libgdx to make a retrostyle little game and i would like to let the players to choose the colors of several characters so i thought about loading png indexed images and then updating palettes programatically how wrong i was u it seems that color pallettes are something of the past and also seems that the best option to achieve a similar result is by using shadershere is an image explaining what i am trying right now my intention is to use 2 images one of them pixel guypng is a png image with only 6 colors those colors are its original palette the other image colortablepng would be a 6x6 pixel png that contains 6 palettes of 6 colors each each row is a different palette the colors from the first row of pixels of colortablepng would match the colors used in pixel guypng that would be the firstoriginal palette and the other rows would be palettes 2 to 6 what i try to achieve is to use colortables first palette to index pixelguy colors and then change the palette by sending a number from 2 to 6 to the shaderafter doing some research i found a post in gamedev stackexchange and apparently it was what i was looking for so i tried to test it i created the vertex and fragment shaders and loaded my textures the one whose palette i wanted to swap and the one that contained several palettes for that but the output is an unexpected white imagemy vertex shaderattribute vec4 a positionattribute vec4 a colorattribute vec2 a texcoord0uniform mat4 you projtransvarying vec4 v colorvarying vec2 v texcoordsvoid main v color a color v texcoords a texcoord0 gl position you projtrans a positionmy fragment shader fragment shader thanks to zack the human uniform sampler2d texture texture to which well apply our shader should its name be you textureuniform sampler2d colortable color table with 6x6 pixels 6 palettes of 6 colors eachuniform float paletteindex index that tells the shader which palette to use passed here from javavoid main vec2 pos gl texcoord0xy vec4 color texture2dtexture pos vec2 index vec2colorr paletteindex 0 vec4 indexedcolor texture2dcolortable index gl fragcolor indexedcolor the code i used to make the texture binding and pass the palette number to the shaderpackage comtestshaderstestimport combadlogicgdxapplicationadapterimport combadlogicgdxgdximport combadlogicgdxgraphicsgl20import combadlogicgdxgraphicstextureimport combadlogicgdxgraphicsg2dspritebatchimport combadlogicgdxgraphicsglutilsshaderprogrampublic class shaderstestmain extends applicationadapter spritebatch batch texture imgpixelguy texture colortable private shaderprogram shader private string shadervertindexpalette shaderfragindexpalette override public void create batch new spritebatch imgpixelguy new texturepixel guypng texture to which well apply our shader colortable new texturecolortablepng color table with 6x6 pixels 6 palettes of 6 colors each shadervertindexpalette gdxfilesinternalshadersindexpalettevertreadstring shaderfragindexpalette gdxfilesinternalshadersindexpalettefragreadstring shaderprogrampedantic false important since we are not using some uniforms and attributes that spritebatch expects shader new shaderprogramshadervertindexpalette shaderfragindexpalette ifshaderiscompiled systemoutprintlnproblem compiling shader else batchsetshadershader systemoutprintlnshader applied shaderbegin shadersetuniformicolortable 1 set an uniform called colortable with index 1 shadersetuniformfpaletteindex 20f set a float uniform called paletteindex with a value 20f to select the 2nd palette shaderend colortablebind1 we bind the texture colortable to the uniform with index 1 called colortable override public void render gdxglglclearcolor03f 03f 03f 1 gdxglglcleargl20gl color buffer bit batchbegin batchdrawimgpixelguy 0 0 draw the image with the shader applied batchend i do not know if that is the correct way to pass a float value to an uniform of the fragment not sure either about how the code snippet i tried to use worksedit i tried the changes suggested by tenfour04 and they worked flawlessly here is the preprocessed sprite i have updated the repository with the changes java code here fragment shader here in case somebody is interested it can be downloaded here edit 2 i have just added to the repository the last optimization that tenfour04 adviced to pass the palette index to each sprite within the r channel calling spritesetcolor method and again it worked perfect,['android'] +772621,collectionfs access denied 403 error meteor js i am using collectionfs for file upload my code is bellow logged user can insert image to images collection also i can see that file is uploaded on server image links and download button is thisplaying before remove insecure package able to see images and download after removed insecure package from project images are not thisplaying also download is not workingcan retrieve image name and url receiving access denied 403 error what i really wanted is that signed user can insert files to server and everyone can see images also able to download filesi wrote allow rules and also publish and subscribe what is the problem herejs file if meteorisclient templatemyformevents change myfileinput functionevent template fsutilityeachfileevent functionfile var fsfile new fsfileeventtargetfiles0 fsfileowner meteoruserid imagesinsertfile function err fileobj if err we have inserted new doc with id fileobj id and kicked off the data upload using http templateimageviewhelpers images function return imagesfind where images is an fscollection instance meteorsubscribeimages if meteorisserver meteorstartupfunction code to run on server at startup meteorpublishimages function return imagesfind images new fscollectionimages stores new fsstorefilesystemimages path uploaded imagesallow insert functionuserid doc return userid update functionuserid doc return userid remove functionuserid doc return false html file head titleuploadertitleheadbody loginbuttons imageview myformbodytemplate nameimageview div classimageview each images div a hrefthisurl target blankimg srcthisurl alt classthumbnail thisurlabr strongthisnamestrong a hrefthisurl downloadtrue classbtn btnprimarydownloada div each divtemplatetemplate namemyform p please specify a file or a set of filesbr input typefile namedatafile classmyfileinput ptemplate,['javascript'] +772633,what happens when you go back with the browser when i press back button in the browser what is going onis the query with the same url made againis the current dom state saved and restored html onlyis the current page state saved and restored html javascriptis the server queried but if sends unchanged then local cache is usedin general can we consider we have uptodate information on the previous page i am unclear because of those situationsstackoverflows sometimes handles my upvotes very badly not thisplaying it preventing me from undoing because i last voted 5 minutes ago but it was in another tab etcwhen i work on local environment i do not have the feeling much is queried theni am always pretty unsure of whats going to come when going back hence as a developper avoid using it as much as possible only to find back a url in the history actuallymy opinion is that querying again would be the best idea but it is not the fastest and browser may want to be fast in that case to impress the user on the other hand storing page states must cost a lot of memory,['javascript'] +772690,testui jenkins using espresso the app is passing the espresso tests locally i mean directly to the devices and genymotion emulators when i use jenkins to built an apps image the espresso test are not successful i get this errorjenkins javalangruntimeexception waited for the root of the view hierarchy to have window focus and not be requesting layout for over 10 seconds if you specified a non default root matcher it may be picking a root that never takes focus otherwise something is seriously wrong selected rootrootapplicationwindowtokenandroidviewviewrootimplw536a97d4 windowtokenandroidviewviewrootimplw536a97d4 haswindowfocusfalse layoutparamstype1 layoutparamsstringwmlayoutparams00fillxfill sim100 ty1 fl1810100 pfl0x8 wanim0x103028f decorviewstringdecorviewid1 visibilityvisible width800 height1184 hasfocustrue hasfocusabletrue haswindowfocusfalse isclickablefalse isenabledtrue isfocusedfalse isfocusablefalse islayoutrequestedfalse isselectedfalse rootislayoutrequestedfalse hasinputconnectionfalse x00 y00 childcount1 all rootsrootapplicationwindowtokenandroidviewviewrootimplw536a97d4 windowtokenandroidviewviewrootimplw536a97d4 haswindowfocusfalse layoutparamstype1 layoutparamsstringwmlayoutparams00fillxfill sim100 ty1 fl1810100 pfl0x8 wanim0x103028f decorviewstringdecorviewid1 visibilityvisible width800 height1184 hasfocustrue hasfocusabletrue haswindowfocusfalse isclickablefalse isenabledtrue isfocusedfalse isfocusablefalse islayoutrequestedfalse isselectedfalse rootislayoutrequestedfalse hasinputconnectionfalse x00 y00 childcount1at comgoogleandroidappscommontestinguiespressobaserootviewpickergetrootviewpickerjava84at comgoogleandroidappscommontestinguiespressoviewinteractionmoduleproviderootviewviewinteractionmodulejava51at comgoogleandroidappscommontestinguiespressoviewinteractionmodulemoduleadapterproviderootviewprovidesadaptergetviewinteractionmodulemoduleadapterjava187at comgoogleandroidappscommontestinguiespressoviewinteractionmodulemoduleadapterproviderootviewprovidesadaptergetviewinteractionmodulemoduleadapterjava151at comgoogleandroidappscommontestinguiespressobaseviewfinderimplgetviewviewfinderimpljava52at comgoogleandroidappscommontestinguiespressoviewinteraction2runviewinteractionjava141at javautilconcurrentexecutorsrunnableadaptercallexecutorsjava442at javautilconcurrentfuturetasksyncinnerrunfuturetaskjava305at javautilconcurrentfuturetaskrunfuturetaskjava137at androidoshandlerhandlecallbackhandlerjava615at androidoshandlerthispatchmessagehandlerjava92at androidoslooperlooplooperjava137at androidappactivitythreadmainactivitythreadjava4745at javalangreflectmethodinvokenativenative methodat comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava786at comandroidinternaloszygoteinitmainzygoteinitjava553at dalviksystemnativestartmainnative method,['android'] +772826,getting gradle error could not reserve enough space for object heap constantly in intellij idea so i have a problem with memory allocation sometimes it works and sometimes it does not i have read this thread and tried the advice there multiple times sometimes xms512m xmx768m works sometimes xms256m xmx512m i am sick and tired of having to tweak this setting in intellij under the build execution deployment build tools gradle gradle vm options setting is there no setting that solves this once and for alli have 16gb of ram on my windows 7 computer i am running intellij idea eap 14 build 13822103 64 bit version android gradle build plugin v012 i am suspecting gradle is not running in 64 bit mode or else it would have 7 gb of free memory to eat from why is it not utilizing thisediti got the same error in visual studio 2015 with cordova 511 under windows 10 see my solution below,['android'] +772937,ngdialog dark overlay covers the dialog i am trying to use the angularjs ngdialog addon to make a simple popup dialog it basically works but when the dialog appears it starts out white but then quickly fades into the dark background i assume there is some css conflict but i can reproduce the problem with a very simple bit of html below thanks in advance for any suggestionshtml head titledialog testtitle link hrefassetsngdialogcssngdialogcss relstylesheet script srcassetsangularjsangularjsscript script srcassetsngdialogjsngdialogjsscript script angularmoduledialogtest ngdialog script head body ngappdialogtest button ngdialogmy dialoghtml dialog button bodyhtml,['css'] +772941,convert row to column header for pandas dataframe the data i have to work with is a bit messy it has header names inside of its data how can i choose a row from an existing pandas dataframe and make it rename it to a column headeri want to do something likeheader dfdfold header name1 new header name1dfcolumns header,['python'] +772982,error when installing ruby 213 with rvm i am trying to install ruby 213 with rvm i have the latest version of xcode installed and i have a clean install of rvmi am basically doingrvm autolibs brewrvm install ruby213everything looks to be working ok but then i get this errorempty path passed to certificates update functions stack requirements osx update openssl cert run rvm requiremnts fail or run action rvm osx ssl certs ensure for ruby rvm osx ssl certs ensure for ruby except jruby external import setup external import mainthe only references i can get to this is an issue with ruby 211 when a developer checked in a hardcoded path but i cannot see how this is relatedhere is the full trace i am gettingsearching for binary rubies this might take some timefound remote file 64ruby213tarbz2checking requirements for osx brewcertificates in usrlocaletcopensslcertpem are already up to daterequirements installation successfulruby213 configureruby213 download total received xferd average speed time time time current dload upload total spent left speed 0 0 0 0 0 0 0 0 0100 6864k 100 6864k 0 0 1143k 0 06 06 1412kno checksum for downloaded archive recording checksum in user configurationruby213 validate archiveruby213 extractruby213 validate binaryruby213 setupruby213 gemset created usersjacorvmgemsruby213globalruby213 importing gemset usersjacorvmgemsetsglobalgemsruby213 generating global wrappersruby213 gemset created usersjacorvmgemsruby213ruby213 importing gemsetfile usersjacorvmgemsetsdefaultgems evaluated to empty gem listruby213 generating default wrappersusersjacorvmscriptsfunctionssupport line 480 2804 tracebpt trap 5 ruby path rrbconfig e fileopenconfig pathw file rbconfigconfigsorteachkeyvalue filewritekeygsub valuegsubn devnull 21empty path passed to certificates update functions stack requirements osx update openssl cert run rvm requiremnts fail or run action rvm osx ssl certs ensure for ruby rvm osx ssl certs ensure for ruby except jruby external import setup external import main,['ruby'] +772989,testing for uiapplicationopensettingsurlstring existance with swift on ios 8 apple gave us the possibility to go to the app settings right from our app using the constant uiapplicationopensettingsurlstringuiapplicationsharedapplicationopenurlnsurlurlwithstringuiapplicationopensettingsurlstringthere is a code to test if this constant exists on ios 7 but it uses objc and pointes apple did this on their code mhtmlhow can i make something like this using swift,['ios'] +773139,textboxes would not take focus i have this very strange problem that occurs in the ripple emulator where a textbox would not take focusor at least it appears to not take focus there is no cursor blinking in it once i click into it however if i start typing then click out of the textbox the content of the textbox suddenly updates to reflect what i have typedthis seems to have something to do with css angularjs and ionic framework combinedi have the below html this is not reproducible in plunkrionview ionnavbuttons sideleft button menutoggleleft classbutton buttonicon icon ionnaviconbutton ionnavbuttons ioncontent classhasheader div stylemargintop 20px label classitem iteminput span classinputlabeldatespan input typedate ngchangesearch ngmodelfilterdate label label classitem iteminput span classinputlabelonly unscheduledspan ioncheckbox ngchangesearch styleborder none ngmodelfilteronlyunscheduledioncheckbox label label classitem iteminput button classbutton buttonpositive ngclickclearmatchesclear matchesbutton label label classitem iteminput button classbutton buttonpositive ngclickmaketestusersplaymake test users playbutton label label classitem iteminput button classbutton buttonpositive ngclickmaketestdatemake test datebutton label div ionlist ionitem ngrepeatitem in dates track by index stylepadding 0 paddingtop 10px form novalidatenovalidate onvalidsubmitsaveitem div div classitem itemdivider styletextalign center marginbottom 20px itemdescriptionitemiscancelled cancelled div label classitem iteminput span classinputlabellocationspan input typetext ngmodelitemlocation namelocation label label classitem iteminput span classinputlabeltimespan input typetime ngmodelitemtime nametime label div classpadding button typesubmit classbutton buttonenergized save button div stylewidth 75px padding 0 ngclickchargeitem itemuserid1 ngthisableditemuser1chargeid classbutton buttonenergized charge 1 div a stylewidth 75px padding 0 ngclickchargeitem itemuserid2 ngthisableditemuser2chargeid classbutton buttonenergized charge 2 a div div form ionitem ionlist ioncontentionviewif i remove the button and buttonpositive classes from all the buttons it suddenly works as expectedupdatehere is the source of ioniccss where all the styles can be foundif i change the button class tobutton minheight inherit minwidth inherit padding inherit lineheight inheritthe problem thisappears this suggests to me a browser rendering bug having to do with the button trying to spill out of bounds or something,['javascript'] +773155,problems debugging simple console program clion i am trying to learn basic c after being a java developer so i decided to give clion a try i wrote this basic code just to familiarize myself with some c syntax include iostreamusing namespace stdint main string word cout enter a word to reverse characters endl getlinecin word forint i wordlength i 1 i cout wordi return 0the code is functional it reverses whatever word you input i wanted to step through it to see variables and what not and to test out clions debugger my problem occurs when i get to getlinecin wordwhen i step onto this line i enter a word and hit enter then step over after i do this nothing happens all the step over in etc buttons are thisabled i am unable to continue through the loop or run the remainder of the code i have used eclipses debugger many times for java development without any issues any ideas could be helpful tldr how do i step through a c command line program with basic input and output using clion,['c++'] +773249,does net have the history of time zone changes our government loves to change local time or enablethisable daylight saving timems deployed patch for russia to take new time change into accountnow there is the question whether history of the changes existswhen i get utc time of the day in 010120 system should remember that moscow time zone had 3 utc in summer 4 at that momentfor 01012012 we had 4 utc for both winter and summer and soon we will have 3 utcsimple test shows that net does not keep records about the changesvar t new datetime201211 utc 4 expectedsystemconsolewritelinettolocaltime utc 4 expectedt new datetime2012061systemconsolewritelinettolocaltime utc 3 expectedt new datetime2011systemconsolewritelinettolocaltime utc 4 expectedt new datetime2061systemconsolewritelinettolocaltimedoes some additional api exist to cope with the problemupdatehave found class timezoneinfo and related adjustmentrule class left to test whether customization of timezoneinfolocal time zone affects datetime apisupdate 2seems like utc offsets are not stored as history and adjustmentrule changes only daylight time during the year,['.net'] +773294,convert a simple one line string to rdd in spark i have a simple lineline hello worldi would like to convert it to an rdd with only one element i have tried scparallelizelinebut it getscparallelizelinecollecth e l l o w o r l dany ideas,['python'] +773329,impossible to load an image in xcassets on bundle i need to include images in a static library i created a bundle and inserted in my images the problem is that it seems to work if i include the images directly in the bundle but stops working if i put in a xcassets file i followed many guides and searched for a solution on this site the most popular solution is to insert this line of code uiimage imagenamedmybundlebundleimagename but it seems not work for me any ideas,['ios'] +773408,how to implement an appendonly versioned model in sqlalchemy i would like to reimplement some of my existing sqlalchemy models in an appendonly datastore appendonly meaning that object are only updated with insert statements not using update or delete statementsthe update and delete statements would be replaced with another insert that increments the version there would be an is deleted flag and instead of delete a new version with is deletedtrue would be createdid version is deleted name description 1 1 f fo text text text 1 2 f foo text text text 2 1 f bar null 1 3 t foo text text text additionally all select statements will need to be rewritten to only the maximum version number for each id as described in this question postgresql fetch the row which has the max value for a columnall unique indexes need to be rewritten to be unique by the id primary key as each id may be present more than oncei know how to solve most of these issues but i am struggling with the event hooks in sqlalchemy that would handle certain things that need to be done on update deletethe sqlalchemy documentation already has some basic examples for versioning the versioned rows example comes close to what i want but they do not handle 1 deletion and 2 foreign key relationships 1 deletion i know there is a sessiondeleted field and i would iterate over it in a similar way to how sessiondirty is iterated over in the versioned rowspy exampleabut how would i unflag the item from the tobedeleted list create a new item2 the abovementioned example only deals with a parentchild relationship and the way it does expiring the relationship seems to require custom code for each model 21 is there a way to make this more flexible 22 is it possible to configure sqlalchemys relationship to return the object with maxversion for a given foreign key,"['python', 'sql']" +773440,how can i join a qt gui to a nonc main program qt appears to be the best crossplatform gui toolkit available unfortunately it is in c and bindings for it to many interesting languages such as d rust julia and mono on nix are either not available or not maintained gtk bindings are usually available but gtk looks ugly on windows and especially os x wxwidgets bindings would also be nice but are not available or are unmaintained for d rust and julia for julia i could go through python for both toolkits but that is slow and clumsyhow can i bind my c gui to an nonc main program,['c++'] +773538,uitableviewcell selection storyboard segue is slow double tapping works though i have a uitableviewcontroller in a storyboard i have the selection of my uitableviewcell prototype trigger a segue to present another controller the presentation itself is working i noticed a strange bug possibly introduced in ios 8 that tapping on the cell highlights the cell as expected but sometimes takes several seconds before performing the segue tapping on the cell twice causes the segue to happen immediatelyhas anyone else noticed this in ios 8edit i have now noticed that it is not just a double tap that triggers the segue faster it is also a tap on the cell followed by a swipe anywhere starting to seem like a threading issue to me,['objective-c'] +773617,my cordova webview app is really slower than in the android browser on the same phone i built an android app with ionicframework and cordova but when i try to run on my samsung galaxy s4 the app is really slower than the same code in the webbrowsers of my phonehow can i expect to have the same perfs i have tried androidhardwareacceleratedtruethisappviewgetsettingssetrenderpriorityrenderpriorityhighthisappviewgetsettingssetpluginstateandroidwebkitwebsettingspluginstateon demandusessdk androidminsdkversion14 androidtargetsdkversion19 with the last 36 cordova versionhow can i do to have the same performance as i can see on the phone browser with meta appcapable for example,['android'] +773749,how should i choose a video format to be played on web android ios i am working on a video sharing project and wonder what if there is a video format that is compatible with most players on web android iosthe app will work like thisusers can take videos from mobile devices ios and androidother users can play videos on mobile devices ios and android and web browsersi am not familiar with different video formats i noticed that mov and mp4 are used in ios but i assume mov cannot be played on android and web browsers except safari could anyone give a hint,"['android', 'ios']" +773905,how to create a c project with clion since clion has released a month ago there are not many documents about it so i am confused about how to create a c project with clion when i want to create a new project i just asks the name of the project and creates a default maincpp and cmakeliststxt file which refers to maincpp file well i can rename the file maincpp to mainc and edit cmakeliststxt manually but there are a few things in txt file too so i need some help over heredefault cmakeliststxt filecmake minimum requiredversion 284projectexamplesetcmake cxx flags cmake cxx flags stdc11setsource files maincppadd executabledbsg source filesnote the problem might have an easier solution like create a c project instead of c project but i cannot see so i have to let people who read this about the problem might have an easier solution then editing manually thanks,"['c++', 'c']" +773917,iphone app size smaller than screen i am developing an app and have come against a strange issue i cannot find the answer for when testing the app on an iphone 5 the whole app thisplay window is shrunk down to what looks like a 35 size thisplay the top and bottom of the screen are black and even the status bar is pushed down when i test the app on an iphone 5s running ios 8 it thisplays full screen as expected also when testing in the ios simulator for iphone 5 and 5s it thisplays as expected i am using xcode 6 for developmentany help would be greatly appreciated,"['ios', 'iphone']" +773950,ios 8 uitableview inset if you have cells with custom layout youll probably have this issue too on ios 8 for larger devices the default tableview inset seems to change if youre laying out custom cells and matching their left layout constraint to the default size 15 inset for a cell your layout will look fine on smaller devices but on larger devices where the inset changes youll get something akin to the followinghow can i fix this,"['ios', 'iphone']" +773992,spring security enablethisable csrf by client type browser nonbrowser spring doc says when you use csrf protection our recommendation is to use csrf protection for any request that could be processed by a browser by normal users if you are only creating a service that is used by nonbrowser clients you will likely want to thisable csrf protection what if my service is going to be used by both browser and nonbrowser clients such as third party external services does spring security provide a way to thisable csrf exclusively for certain type of clientsreference,['java'] +774013,unable to find valid certification path to requested target but browser says it is ok i am developing a java application that connects to soap services exposed at test environment for european datawarehouse i am working on my development machine recently reformatted with windows 81 today i tried to send them a creation request via soap from my program and got this errorcaused by javaxxmlwswebserviceexception could not send message at orgapachecxfjaxwsjaxwsclientproxyinvokejaxwsclientproxyjava146 at comsunproxyproxy110createdealunknown source at itcsttechedwinservicesspringedwinserviceimplcreatedealedwinserviceimpljava102 at itcsttechedwinconsumercreditdatamanagersspringdealmanagerimplcreateedcodedealmanagerimpljava319 77 morecaused by javaxnetsslsslhandshakeexception sslhandshakeexception invoking sunsecurityvalidatorvalidatorexception pkix path building failed sunsecurityprovidercertpathsuncertpathbuilderexception unable to find valid certification path to requested target at sunreflectnativeconstructoraccessorimplnewinstance0native method at sunreflectnativeconstructoraccessorimplnewinstancenativeconstructoraccessorimpljava57 at sunreflectdelegatingconstructoraccessorimplnewinstancedelegatingconstructoraccessorimpljava45 at javalangreflectconstructornewinstanceconstructorjava526 at orgapachecxftransporthttphttpconduitwrappedoutputstreammapexceptionhttpconduitjava1339 at orgapachecxftransporthttphttpconduitwrappedoutputstreamclosehttpconduitjava1323 at orgapachecxftransportabstractconduitcloseabstractconduitjava56 at orgapachecxftransporthttphttpconduitclosehttpconduitjava628 at orgapachecxfinterceptormessagesenderinterceptormessagesenderendinginterceptorhandlemessagemessagesenderinterceptorjava62 at orgapachecxfphasephaseinterceptorchaindointerceptphaseinterceptorchainjava272 at orgapachecxfendpointclientimpldoinvokeclientimpljava565 at orgapachecxfendpointclientimplinvokeclientimpljava474 at orgapachecxfendpointclientimplinvokeclientimpljava377 at orgapachecxfendpointclientimplinvokeclientimpljava330 at orgapachecxffrontendclientproxyinvokesyncclientproxyjava96 at orgapachecxfjaxwsjaxwsclientproxyinvokejaxwsclientproxyjava135 80 morecaused by javaxnetsslsslhandshakeexception sunsecurityvalidatorvalidatorexception pkix path building failed sunsecurityprovidercertpathsuncertpathbuilderexception unable to find valid certification path to requested target at sunsecuritysslalertsgetsslexceptionalertsjava192 at sunsecuritysslsslsocketimplfatalsslsocketimpljava1884 at sunsecuritysslhandshakerfatalsehandshakerjava276 at sunsecuritysslhandshakerfatalsehandshakerjava270 at sunsecuritysslclienthandshakerservercertificateclienthandshakerjava1341 at sunsecuritysslclienthandshakerprocessmessageclienthandshakerjava153 at sunsecuritysslhandshakerprocessloophandshakerjava868 at sunsecuritysslhandshakerprocess recordhandshakerjava804 at sunsecuritysslsslsocketimplreadrecordsslsocketimpljava1016 at sunsecuritysslsslsocketimplperforminitialhandshakesslsocketimpljava1312 at sunsecuritysslsslsocketimplstarthandshakesslsocketimpljava1339 at sunsecuritysslsslsocketimplstarthandshakesslsocketimpljava1323 at sunnetwprotocolhttpshttpsclientafterconnecthttpsclientjava563 at sunnetwprotocolhttpsabstractdelegatehttpsurlconnectionconnectabstractdelegatehttpsurlconnectionjava185 at sunnetwprotocolhttphttpurlconnectiongetoutputstreamhttpurlconnectionjava1091 at sunnetwprotocolhttpshttpsurlconnectionimplgetoutputstreamhttpsurlconnectionimpljava250 at orgapachecxftransporthttpurlconnectionhttpconduiturlconnectionwrappedoutputstreamsetupwrappedstreamurlconnectionhttpconduitjava174 at orgapachecxftransporthttphttpconduitwrappedoutputstreamhandleheaderstrustcachinghttpconduitjava1283 at orgapachecxftransporthttphttpconduitwrappedoutputstreamonfirstwritehttpconduitjava1239 at orgapachecxftransporthttpurlconnectionhttpconduiturlconnectionwrappedoutputstreamonfirstwriteurlconnectionhttpconduitjava201 at orgapachecxfioabstractwrappedoutputstreamwriteabstractwrappedoutputstreamjava47 at orgapachecxfioabstractthresholdoutputstreamwriteabstractthresholdoutputstreamjava69 at orgapachecxftransporthttphttpconduitwrappedoutputstreamclosehttpconduitjava1296 90 morecaused by sunsecurityvalidatorvalidatorexception pkix path building failed sunsecurityprovidercertpathsuncertpathbuilderexception unable to find valid certification path to requested target at sunsecurityvalidatorpkixvalidatordobuildpkixvalidatorjava385 at sunsecurityvalidatorpkixvalidatorenginevalidatepkixvalidatorjava292 at sunsecurityvalidatorvalidatorvalidatevalidatorjava260 at sunsecuritysslx509trustmanagerimplvalidatex509trustmanagerimpljava326 at sunsecuritysslx509trustmanagerimplchecktrustedx509trustmanagerimpljava231 at sunsecuritysslx509trustmanagerimplcheckservertrustedx509trustmanagerimpljava126 at sunsecuritysslclienthandshakerservercertificateclienthandshakerjava1323 108 morecaused by sunsecurityprovidercertpathsuncertpathbuilderexception unable to find valid certification path to requested target at sunsecurityprovidercertpathsuncertpathbuilderenginebuildsuncertpathbuilderjava196 at javasecuritycertcertpathbuilderbuildcertpathbuilderjava268 at sunsecurityvalidatorpkixvalidatordobuildpkixvalidatorjava380 114 moreas you can see by clicking my above link that is no selfsigned certificate but released by godaddy public ca recognized by my firefox browser my java version is 170 60b19 it will be a bad idea to modify the code in order to allow insecure ssl connectionsi would like instead to ensure that eurodws certificate is in the trust store how do i check that and how do i possibly import a new certificateps i cannot currently test on the server where the final application is deployed i can only use my own tomcat installation,['java'] +774069,javafx 8 hidpi support i just tried out the javafx hello world example on a 4k screen on arch linux but unfortunately the gui does not scale the documentation sayshidpi support javafx 8 now supports hidpi thisplaysso how can i make my application dpi aware,['java'] +774093,set priority for custom created serial asynchronous queue how might i set high priority to a custom created serial asynchronous queue using gcdsi had a look at this qa where suggestion is made to make use of thispatch set target queue pass high priority queue thispatch queue priority high which is a concurrent queue to custom serial asynchronous queuemy understanding is that this will make all the tasks on the serial queue concurrent is my understanding correct if so what is an alternate solution,"['ios', 'objective-c']" +774128,how does v differ from x0b or x0c typing stringwhitespace gives you a string containing all whitespace characters defined by pythons string moduletnx0bx0cr both x0b and x0c seem to give a vertical tab print firstx0bsecondfirst secondv gives the same effect how are these three different why does the string module use x0b or x0c over the simpler v,['python'] +774131,alias a templated function you can use a typedef to create a shorter and simpler name for typestypedef stdchronohigh resolution clock clocktypedef clocktime point timepointtypedef stdchronoseconds secondstypedef stdchronomilliseconds millisecondsas well as for instantiated templated typestypedef stdchronodurationfloat stdratio1 realduration example usagefloat dt realdurationa bcountand for function pointerstypedef void funcptrintintyou can also use type aliases for templatestemplatetypename t using uptr stdunique ptrt example usageuptrint myintuptrfoo myfoobut how can you create an aliaspointer to a templated function for example if i want to be able to use the name durationcast to write things like thisx durationcastsecondsa by durationcastmillisecondsc dwhat needs to be done to shorten the function stdchronoduration castt to just durationcastt without simply going the using namespace stdchrono or using stdchronoduration cast route and without writing my own function objects to achieve itediti guess i can just write a simple wrapper around ittemplatetypename totype typename fromtypetotype durationcastconst fromtype d return stdchronoduration casttotypeddoes not work like an alias but the end result is that i can use it in the exact same way i was aiming forx durationcastsecondsa b,['c++'] +774216,bootstrap modal relatedtarget is undefined i am trying to get the clicked element using the property relatedtarget of the showbsmodal event it is always getting undefined thoughthis is what i have curcarselectonclick functione curcarmodalonshowbsmodal functionevent modalopenedby eventrelatedtarget alertmodalopenedby modaltoggle,"['javascript', 'jquery']" +774266,javascript sideeffects of freezing a constructor prototype i noticed that freezing the prototype of a constructor function had a side effect that basically broke constructor chainingfunction ax thisxxfunction bx y acallthis x thisyybprototype new aobjectfreezebprototypebnew b12 i expected bx to be 1 here but it is undefinedhere is a fiddle to demonstrate the problemis there a good reason why bx is undefined at the endif this is not a bug then how come x2 is 1 in the fiddle,['javascript'] +774281,cython are typed memoryviews the modern way to type numpy arrays let us say i would like to pass a numpy array to a cdef functioncdef double mysumdouble arr cdef int and lenarr cdef double result 0 for i in rangen result result arri return resultis this the modern way to handle typing numpy arrays compare with this question cython numpy type of an arraywhat if i want to do the followingcdef double mydifferenceint a int b cdef double arr a nparangea cdef double arr b nparangeb return arr a arr bthis will return an error because is not defined for memoryviews so should that case have been handled as followscdef double mydifferenceint a int b arr a nparangea arr b nparangeb return arr a arr b,['python'] +774283,how to count number of visitors for website in aspnet c how do i count the number of visitors for website in aspnet ci am using the code belowin globalasax page application languagec void application startobject sender eventargs e code that runs on application startup applicationnoofvisitors 0void session startobject sender eventargs e code that runs when a new session is started applicationlock applicationnoofvisitors intapplicationnoofvisitors 1 applicationunlockin aspx pageasplabel runatserver idlbluser in aspxcsprotected void page loadobject sender eventargs e lblusertext applicationnoofvisitorstostringthe application counter is resetting to 0 every one hour where have i erred in counting the number of users thank u,"['c#', 'asp.net']" +774294,custom segue to a different storyboard questionhow might one write a custom segue that would allow you to embed view controllers from a different storyboardcontexti am trying to write a custom segue with which i can link from one storyboard to another a good article on atomicobjectcom illustrates how to create a segue that originates from a button event etc translated into swift and allowing for non uinavigationcontrollers the code looks likepublic class seguetostoryboard uistoryboardsegue private class func viewcontrollerinstoryboardidentifierstring bundlensbundle nil uiviewcontroller let boardscene splitidentifier 0 maxsplit intmax allowemptyslices false switch boardscenecount case 2 let sb uistoryboardname boardscene0 bundle bundle return sbinstantiateviewcontrollerwithidentifierboardscene1 as uiviewcontroller case 1 let sb uistoryboardname boardscene0 bundle bundle return sbinstantiateinitialviewcontroller as uiviewcontroller default return nil override initidentifier string source uiviewcontroller destination ignore uiviewcontroller let target seguetostoryboardviewcontrollerinstoryboardidentifier bundle nil superinitidentifier identifier source source destinationtarget nil target ignore public override func perform let source selfsourceviewcontroller as uiviewcontroller let dest selfdestinationviewcontroller as uiviewcontroller sourceaddchildviewcontrollerdest destdidmovetoparentviewcontrollersource sourceviewaddsubviewdestview sourcenavigationcontrollerpushviewcontrollerdest animated true problemthe problem that i am having with both their objc and the above swift code is that when you try to use the via a container view with semantics of an embed segue starting with an embed segue deleting the segue and then use the above custom segue it crashes before ever calling the segue code with the following methodnotfound error terminating app due to uncaught exception nsunknownkeyexception reason uistoryboardseguetemplate 0x7ffc8432a4f0 setvalueforundefinedkey this class is not key value codingcompliant for the key containerviewi have tried to inspect the address listed but get no meaningful results i do the see the bold statement that it expecting the containerview but do not know how one might isolate satisfy andor work around this problemsummarymy end goal is to embed view controllers defined in separate storyboards to facilitate collaboration and testing without having to write additional code a non invasive solution does anyone have any insight into how to accomplish this greater task i could fall back to hybrid approach of calling performsegue but would like to find a single contained and complete solution the above code gets there for event driven buttons etc segues but not with the embed segueany input is appreciated thanks in advance,"['ios', 'objective-c', 'iphone']" +774355,ajax does not work with bootstrapselect i found flaskjqueryajax example where the user selects an item from the vehicle make drop down menu the vehicle model drop down menu is populated by making an ajax request for a list of models for the make selectedi tried to replace the dropdown menus by bootstrapselect and as soon as i include claselectpicker formcontrol in the second dropdown menu it does not get any more populated after the first dropdown has been chosenthis is the html templatedoctype htmlhtml langenhead meta charsetutf8 titleflask jquery ajax drop down menu exampletitle link relstylesheet typetextcss hrefnetdnabootstrapcdncombootstrap320cssbootstrapmincss link relstylesheet typetextcss hrefcdnjscloudflarecomajaxlibsbootstrapselect162cssbootstrapselectmincss link relstylesheet href url forstatic filenamewebcss custom styles for this template link href relstylesheetheadbody h1select vehicleh1 form classformhorizontal action methodpost div classinputgroup span classinputgroupaddonmakespan formmakeidmake select claselectpicker formcontrol div div classinputgroup span classinputgroupaddonmodelspan formmodelidmodel select claselectpicker formcontrol div button typesubmitsubmitbutton form if chosen make h2you selectedh2 ul limake id chosen make li limodel id chosen model li ul endif script typetextjavascript srcajaxgoogleapiscomajaxlibsjquery1101jqueryminjsscript script typetextjavascript srcnetdnabootstrapcdncombootstrap320jsbootstrapminjsscript script typetextjavascript srccdnjscloudflarecomajaxlibsbootstrapselect162jsbootstrapselectminjsscript script selectpickerselectpicker script script srcassetsvehiclejsscriptbodyhtmlthis is the javascript code responsible for populating the dropdown menusmake selectchangefunction var make id thisfindselectedval var request ajax type get url models make id requestdonefunctiondata var option list select one concatdata model selectempty for var i 0 i option listlength i model selectappend optionoptionattr value option listi0textoption listi1 why does claselectpicker formcontrol from bootstrapselect cause that the second dropdown menu get not anymore populated,['jquery'] +774381,how to make rectangle view in showcaseview for listview i am using library for showcaseviewhow to make rectangle view instead of circle and how to using it for one of the listview itemthanks1,['android'] +774422,elegant way to pass empty closures in swift in swift i often have to pass a noop closure to a method just to comply with the methods expected parameters arity in the good old days of obj c one could pass nil for a noop callback and be done with it is there a quicker more elegant way to do that in swift without passing an empty block like belowuialertactiontitle ok style uialertactionstyledefault handler uialertaction void in do nothing in callbackcomplete exampleimport uikitclass uialertcontrollerfactory class func oktitle string message string uialertcontroller var alertcontroller uialertcontrollertitle title message message preferredstyle uialertcontrollerstylealert var okaction uialertactiontitle ok style uialertactionstyledefault handler uialertaction void in alertcontrolleraddactionokaction return alertcontroller,['ios'] +774499,multiple vertical background colors in css3 problemtrying to create a solution that would allow me to have five multiple background colors that fill out a webpage regardless of width i have managed to do this with 5 div tags but i wonder if it is possible to do this completely using css3the outcome i would like isi have searched stackoverflow and the web without any results or i am simply very bad at searching,"['jquery', 'html', 'css']" +774519,hide status bar while scrolling ios 8 adds a super new cool feature hiding the navigation bar when user is scrollingthis with a single line in viewdidload navigationcontrollerhidesbarsonswipe truecool is not itbut now i have a little problem when the navigation bar is hidden the status bar is still here and overlaps content which is uglywhat should i do to make it hidden when the navigation bar is hidden,['ios'] +774534,making a generic type constraint on func i wanted to know if this is possiblepublic class foot where t functorpublic class foot where t funcit seems like the compiler is telling me it not possible i suppose i can throw a runtime exception in the constructor but was hoping to have it a compiler errorany ways about doing this,['c#'] +774544,animate smoothly scrollviewer programatically is there a way to smoothly animate a scrollviewers vertical offset in windows phone 81 runtimei have tried using the scrollviewerchangeview method and the change of vertical offset is not animated no matter if i set the thisableanimation parameter to true or falsefor example myscrollviewerchangeviewnull myscrollviewerverticaloffset p null falsethe offset is changed without animationi also tried using a vertical offset mediator summary mediator that forwards offset property changes on to a scrollviewer instance to enable the animation of horizontalverticaloffset summarypublic sealed class scrollvieweroffsetmediator frameworkelement summary scrollviewer instance to forward offset changes on to summary public scrollviewer scrollviewer get return scrollviewergetvaluescrollviewerproperty set setvaluescrollviewerproperty value public static readonly dependencyproperty scrollviewerproperty dependencypropertyregisterscrollviewer typeofscrollviewer typeofscrollvieweroffsetmediator new propertymetadatanull onscrollviewerchanged private static void onscrollviewerchangeddependencyobject o dependencypropertychangedeventargs e var mediator scrollvieweroffsetmediatoro var scrollviewer scrollviewerenewvalue if null scrollviewer scrollviewerscrolltoverticaloffsetmediatorverticaloffset summary verticaloffset property to forward to the scrollviewer summary public double verticaloffset get return doublegetvalueverticaloffsetproperty set setvalueverticaloffsetproperty value public static readonly dependencyproperty verticaloffsetproperty dependencypropertyregisterverticaloffset typeofdouble typeofscrollvieweroffsetmediator new propertymetadata00 onverticaloffsetchanged public static void onverticaloffsetchangeddependencyobject o dependencypropertychangedeventargs e var mediator scrollvieweroffsetmediatoro if null mediatorscrollviewer mediatorscrollviewerscrolltoverticaloffsetdoubleenewvalue summary multiplier for scrollableheight property to forward to the scrollviewer summary remarks 00 means scrolled to top 10 means scrolled to bottom remarks public double scrollableheightmultiplier get return doublegetvaluescrollableheightmultiplierproperty set setvaluescrollableheightmultiplierproperty value public static readonly dependencyproperty scrollableheightmultiplierproperty dependencypropertyregisterscrollableheightmultiplier typeofdouble typeofscrollvieweroffsetmediator new propertymetadata00 onscrollableheightmultiplierchanged public static void onscrollableheightmultiplierchangeddependencyobject o dependencypropertychangedeventargs e var mediator scrollvieweroffsetmediatoro var scrollviewer mediatorscrollviewer if null scrollviewer scrollviewerscrolltoverticaloffsetdoubleenewvalue scrollviewerscrollableheight and i can animate the verticaloffset property with doubleanimationstoryboard sb new storyboarddoubleanimation da new doubleanimationdaenabledependentanimation truedafrom mediatorscrollviewerverticaloffsetdato dafrom pdaduration new durationtimespanfrommilliseconds300daeasingfunction new exponentialease easingmode easingmodeeaseout storyboardsettargetda mediatorstoryboardsettargetpropertyda mediatorverticaloffsetsbchildrenadasbbeginmediator is declared in xamlbut this animation is not smooth on my device lumia 930,['c#'] +774557,c stacks push vs emplace trying to understand the difference between using push or emplace for stdstack i was thinking that if i create a stdstackint then i would use push because integer is a primitive type and there is nothing for emplace to construct however if i was creating stdstackstring then i would choose emplace because stdstring is an object is this correct usage,['c++'] +774569,entityframework contains query of composite key given a list of ids i can query all relevant rows bycontexttablewhereq listofidscontainsqidbut how do you achieve the same functionality when the table has a composite key,"['c#', '.net']" +774597,jboss server 71 not starting in eclipse luna i have eclipse luna 441 and jboss server 71 the problem is when i start the server it never starts and after a long time it says time out error jboss is unable to start within 450 secondsplease any guidance i am very new to java provide any beginners approach to resolve this issuethe console shows the following output and just hangs here for much time124754100 info orgjbossmodules jboss modules version 1ga124754438 info orgjbossmsc jboss msc version 102ga124754552 info orgjbossas jbas015899 jboss as 711final brontes startingthe server never starts i have changed the time settings but it never helps,['java'] +774623,fused location provider unexpected behavior this is how i register my app to receive location updatesmlocationrequest locationrequestcreatemlocationrequestsetintervalconstsone minute 10mlocationrequestsetprioritylocationrequestpriority balanced power accuracymlocationrequestsetfastestintervalconstsone minutebuilder builder new googleapiclientbuildercontextbuilderaddapiactivityrecognitionapimgoogleapiclient builderaddconnectioncallbacksthis addonconnectionfailedlistenerthis buildmgoogleapiclientconnectoverridepublic void onconnectedbundle connectionhint locationservicesfusedlocationapirequestlocationupdatesmgoogleapiclient mlocationrequest locationupdatespendinginentmy pending intent been invoked in background almost in the exact requested intervalsso far so goodthe problem when wifi is thisabled not connected to any network or when there is no 3g4g network data enabled the fused location provider not providing new location updatesmy location access settings are turned on and gps satellites and wifi mobile network location is checkedthe even bigger problem sometimes in that case i do receive location updates callbacks via the pending intent but with the last location it knew even if it was an hour ago and i am long long gone away miles from that placeaccording to the documentation of priority balanced power accuracy used with setpriorityint to request block level accuracy block level accuracy is considered to be about 100 meter accuracy using a coarse accuracy such as this often consumes less poweri am expecting that the fused location provider will open the gps when it have no other choice or at least would not provide a new location updates if he do not have anyanother unpredictable and thisturbing issuei changed priority balanced power accuracy to priority high accuracy in order to see how it behaves for 24 hours all the intervals stayed the same 10 minutes interval between updates accurate location indeed received even in phones with no networksim card but the battery drained out fast when i looked on the battery history i was surprised to see that gps radio was on full transmission mode all the time and i saw also in my log that loction was received every minute even that i requested location each ten minutes i do not have any other installed apps that opens gps to receive locations i noticed this behavior on several devices such as moto x 2013 htc one x nexus 5 all with latest google play services version 61 and android kitkat 4my application depends a lot on the user current location and periodically receives location updates in the specified interval as long as the user logged in so i do not want to use the priority high accuracy mode to prevent battery drainmy questionsis the fused location provider suppose to use gps at all if it set to receive updates with priority balanced power accuracy and do not have any wifi or cell towers info if it does then what am i doing wrongwhy i am getting this misleading location updates that are not correct as i explained in the the even bigger problem sectionwhy gps radio is opened all the time instead of been opened for the 10 minutes interval when i used the priority high accuracy parameter i do not have other installed apps that triggers location updates faster,['android'] +774648,retrofit with rxjava handling network exceptions globally i am trying to handle exceptions in app on global level so that retrofit throws an error i catch it in some specific class with logic for handling those errors i have an interfaceposttokenauthtoken refreshtokenfieldgrant type string granttype fieldrefresh token string refreshtokenand observables refreshes auth token param refreshtoken return public observableauthtoken refreshtokenstring refreshtoken return observablecreatesubscriber super authtoken subscriber try subscriberonnextapimanagerrefreshtokenrefresh token refreshtoken subscriberoncompleted catch exception e subscriberonerrore subscribeonschedulersiowhen i get 401 from server invalid token or some other network related error i want to refresh the token and repeat the rest call is there a way to do this with rxjava for all rest calls with some kind of observable that will catch this error globally handle it and repeat the call that throwed itfor now i am using subject to catch the error on subscribe like thisprivate static behaviorsubject errorevent behaviorsubjectcreatepublic static behaviorsubjectretrofiterror geterrorevent return erroreventand in some call getcurrentuser userapigetcurrentuserobserveonandroidschedulersmainthread subscribe user thisuser user erroreventonnext then in my main activity i subscribe to that behaviour subject and parse the error someapigeterroreventsubscribe e parse the error but i cant repeat the call for the observable that throw the error,['android'] +774693,how to find out if the linux kernel will insert a leap second at the end of the month suppose my program runs on a linux machine that is properly configured to handle leap seconds how that configuration is done exactly ntp config file should not be relevant to this questionin effect the kernel will insert an additional second or skip over a second at the utc end of the month this has an effect on the time value read by gettimeofday2 the last utc second of the month is either repeated or skipped example readings of the time during a leap second are listed heremy question how can i find out in a cc program if a leap second will occur at the end of the month and in which direction so how do i implement the following function on linuxint leap seconds scheduled for end of month if kernel will insert extra second return 1 if kernel will skip over last second return 1 return 0it is ok if the result is incorrect if the end of the month is far in the future far for my purposes is 2 seconds the answer has to be correct during the last second before a possible leap second ie 235958 utc on the last day of the month it is not sufficient if i learn about the leap second after it has occurred as i have to prepare for it in advancei have been trying to find any leap second indicator in sysfs or procfs but so far have been unsuccessful of course if the kernel itself learns about the leap second only a fraction before it occurs eg due to an outage of the ntp service during the whole last month the answer cannot be correct then that is ok,['c'] +774733,xcode 6 cannot connect any iboutlet to viewcontroller after upgrading to xcode 6 i opened an old project that contains a subproject so it has many targetsand i noticed that no link from my storyboard viewcontoller to the relative objects worksfor example i have a viewcontroller with a tableview inside and now i cant do cannot do anyhing with it because the connection is missing i cannot even redefine a new iboutlet in the vc because the arrow in the storyboard from the vc would not connect to anythingto be more clear the class is defined in the custom class section so i cannot find the problemwhat should i dobtw i am using objc not swift i found some related answer but all about swiftthanks,"['ios', 'objective-c']" +774740,get li element onclick with pure javascript without applying onclick to each element first of all i do not want to use jquery just pure javascript please do not link to duplicate jquery postsif i have a list likeul idbulk li idoneli li idbmwliuli want to get the id of the clicked list elementi am aware i could add onclick to each element but the production list i have has 20 entries and i think a better way existsfor exampleif i had only one li element with idsingular i could use the following javascript to get the id clickedvar li documentgetelementbyidsingularonclick function do something as there are thousands of li elements this code would not worki have been able to get a list of the element names with the following javascriptvar bulk documentgetelementbyidbulkvar bulkli tabsgetelementsbytagnamelibulkli contains one bmwbut this does not tell me which one was clicked,"['javascript', 'html']" +774812,yii2 links between frontend and backend advanced template if i need add links to frontend stuff from backend part in menuor from backend to admin how i can do this without hardcodethis yiiapprequestbaseurl returns path from parents dir sitenamebackendwebsitenamefrontendweb,['php'] +774825,is srandtimenull bad in rand considered harmful it is pointed out that srandtimenull is bad because srand takes an unsigned int but for microsofts compiler time t by default is a 64bit number therefore a narrowing conversion happens however time t is implementationdefinedsince i see srandtimenull so prevalent even on this site should it be thiscouraged,['c++'] +774909,what is the use of 0length array or stdarray in c11 it allows you to create a 0 length c array and stdarray like thisint arr10stdarray arr2int0so i am thinking what is the use of a array that does not have a space to storesecondly what is the zero length array if it is a pointer where does it pointing to,['c++'] +774956,support multiple aspect ratio in unity i have been trying to create a unity 2d game that supports each and every aspect ratios of devices for both android and tablets is there a way to do so that is been provided or recommended by unity,"['android', 'ios']" +775036,cast from int to unsigned short after applying bitwise operator static analysis tool i use raises a warning for this code uint16 var1 1uuint16 var2 var1i check misra c 2004 rules and i find 105 rule if the bitwise operators and are applied to an operand od underlying type unsigned char or unsigned short the result shall be immediately cast to the underlying type of the operandok it is not a problem implicit cast is applied i think cast means implicit or explicit cast but 101 rule says the value of an expression of integer type shall not be implicitly converted to a different underlying type the expression is complexan previous example of complex operation are u16ai change my code to uint16 var1 1uuint16 var2 uint16 var1and i obtain another warning i think conversion of int negative value to unsigned int value not safe i check c99 standard iso c99 a 6313 but i do not understand if conversion of int to unsigned short are clearly specifiedin embeddedgurus article i read c unsigned int a since a is positive this cast is safe my questions have explicit conversion from signed int to unsigned short unspecified behavior if yes how to use complement operator with unsigned short in safe way,['c'] +775115,venv does not create activate script python3 when trying to create a virtulenv using venv with python 3 on ubuntu it isnat creating an activate script it conitunally exits with an error 1following docs and other posts on so such as i have tried creating it 2 different wayssaythsaythtravelmate5740gscripts python3 m venv test4error command homesaythscriptstest4binpython3 im ensurepip upgrade defaultpip returned nonzero exit status 1saythsaythtravelmate5740gscripts source test4binactivatebash test4binactivate no such file or directorysaythsaythtravelmate5740gscripts ls test4binpython python3orsaythsaythtravelmate5740gscripts pyvenv34 test5error command homesaythscriptstest5binpython34 im ensurepip upgrade defaultpip returned nonzero exit status 1saythsaythtravelmate5740gscripts ls test5binpython python3 python34how can i get it to fully create a venvif i do it as below with stil no success unsure what the issue issaythsaythtravelmate5740gscripts python3 im venv panda3error command homesaythscriptspanda3binpython3 im ensurepip upgrade defaultpip returned nonzero exit status 1saythsaythtravelmate5740gscripts python3 m venv panda4error command homesaythscriptspanda4binpython3 im ensurepip upgrade defaultpip returned nonzero exit status 1,['python'] +775152,webkit throwing exception on ios 8 for call to setbeingremoved i have an app which relies on uiwebviews for some of its screens but starting on ios 8 i started seeing the following exception being thrown occasionallywebkit thiscarded an uncaught exception in the webviewwillremovescrollinglayerwithcontentslayerfornode delegate nsinvalidargumentexception webactionthisablingcalayerdelegate setbeingremoved unrecognized selector sent to instance this will normally happen in response to tapping a button or link on the webview without anything else going on on the objectivec side and after that most of the functionality in the webview will be broken links not clickable etci have seen at least one other question referring to this error message but no conclusive answers yethas anyone ran into this issue and figured out what was wrong what causes itit appears to depend entirely on the html content meaning that the fact that this exception is thrown is an ios 8 bug,['ios'] +775165,expand cell when tapped in swift i have been trying to implement a feature in my app so that when a user taps a cell in my table view the cell expands downwards to reveal notes i have found plenty of examples of this in objectivec but i am yet to find any for swiftthis example seems perfect accordion table cell how to dynamically expandcontract uitableviewcelli had an attempt at translating it to swiftvar selectedrowindex nsindexpathoverride func tableviewtableview uitableview didselectrowatindexpath indexpath nsindexpath selectedrowindex indexpath tableviewbeginupdates tableviewendupdatesoverride func tableviewtableview uitableview heightforrowatindexpath indexpath nsindexpath cgfloat if selectedrowindex selectedrowindexrow indexpathrow selectedrowindexrow return 100 return 70however this just seems to crash the appany ideasedithere is my cellforrowatindexpath code override func tableviewtableview uitableview cellforrowatindexpath indexpath nsindexpath uitableviewcell var cellcustomtransactiontableviewcell selftableviewdequeuereusablecellwithidentifiercell forindexpath indexpath as customtransactiontableviewcell cellselectionstyle uitableviewcellselectionstylenone if tableview selfsearchthisplaycontrollersearchresultstableview cellpaymentnamelabeltext searchresultsobjectatindexindexpathrow as string printlnsearchresultsobjectatindexindexpathrow var indexvalue namesindexofobjectsearchresultsobjectatindexindexpathrow cellcostlabeltext valuesobjectatindexindexvalue as string celldatelabeltext datesobjectatindexindexvalue as string if imagesobjectatindexindexvalue as nsobject 0 cellpaymentarrowimagehidden false cellcreditarrowimagehidden true else if imagesobjectatindexindexvalue as nsobject 1 cellcreditarrowimagehidden false cellpaymentarrowimagehidden true else cellpaymentnamelabeltext namesobjectatindexindexpathrow as string cellcostlabeltext valuesobjectatindexindexpathrow as string celldatelabeltext datesobjectatindexindexpathrow as string if imagesobjectatindexindexpathrow as nsobject 0 cellpaymentarrowimagehidden false cellcreditarrowimagehidden true else if imagesobjectatindexindexpathrow as nsobject 1 cellcreditarrowimagehidden false cellpaymentarrowimagehidden true return cellhere are the outlet settings,['ios'] +775250,duplicate opengl orthographic projection behaviour without opengl i am encountering a problem trying to replicate the opengl behaviour in an ambient without openglbasically i need to create an svg file from a list of lines my program creates these lines are created using an othigraphic projectioni am sure that these lines are calculated correctly because if i try to use them with a opengl context with orthographic projection and save the result into an image the image is correctthe problem raises when i use the exactly same lines without opengli have replicated the opengl projection and view matrices and i process every line point like this3d output point projection matrix view matrix 3d input pointand then i calculate it is screen svg file position like this2d point x windowwidth 2 3d point x windowwidth 22d point y windowheight 2 3d point y windowheight 2i calculate the othographic projection matrix like thisfloat range 70ffloat l t r b n fl ranger rangeb ranget rangen 60f 80matprojsetvalore0 0 20f r lmatprojsetvalore0 1 00fmatprojsetvalore0 2 00fmatprojsetvalore0 3 00fmatprojsetvalore1 0 00fmatprojsetvalore1 1 20f t bmatprojsetvalore1 2 00fmatprojsetvalore1 3 00fmatprojsetvalore2 0 00fmatprojsetvalore2 1 00fmatprojsetvalore2 2 10f f nmatprojsetvalore2 3 00fmatprojsetvalore3 0 r l r lmatprojsetvalore3 1 t b t bmatprojsetvalore3 2 n f nmatprojsetvalore3 3 10fand the view matrix this waycvettore position lookat uppositionassegnacoordinatertraym pcamvpx rtraym pcamvpy rtraym pcamvpzlookatassegnacoordinatertraym pcamlpx rtraym pcamlpy rtraym pcamlpzupassegnacoordinatertraym pcamupx rtraym pcamupy rtraym pcamupzup0 up0up1 up1up2 up2cvettore zaxis xaxis yaxisfloat length result1 result2 result3 zaxis normallookat positionzaxis0 lookat0 position0zaxis1 lookat1 position1zaxis2 lookat2 position2length sqrtzaxis0 zaxis0 zaxis1 zaxis1 zaxis2 zaxis2zaxis0 zaxis0 lengthzaxis1 zaxis1 lengthzaxis2 zaxis2 length xaxis normalcrossup zaxisxaxis0 up1 zaxis2 up2 zaxis1xaxis1 up2 zaxis0 up0 zaxis2xaxis2 up0 zaxis1 up1 zaxis0length sqrtxaxis0 xaxis0 xaxis1 xaxis1 xaxis2 xaxis2xaxis0 xaxis0 lengthxaxis1 xaxis1 lengthxaxis2 xaxis2 length yaxis crosszaxis xaxisyaxis0 zaxis1 xaxis2 zaxis2 xaxis1yaxis1 zaxis2 xaxis0 zaxis0 xaxis2yaxis2 zaxis0 xaxis1 zaxis1 xaxis0 dotxaxis positionresult1 xaxis0 position0 xaxis1 position1 xaxis2 position2 10f dotyaxis eyeresult2 yaxis0 position0 yaxis1 position1 yaxis2 position2 10f dotzaxis eyeresult3 zaxis0 position0 zaxis1 position1 zaxis2 position2 10f set the computed values in the view matrixmatviewsetvalore0 0 xaxis0matviewsetvalore0 1 yaxis0matviewsetvalore0 2 zaxis0matviewsetvalore0 3 00fmatviewsetvalore1 0 xaxis1matviewsetvalore1 1 yaxis1matviewsetvalore1 2 zaxis1matviewsetvalore1 3 00fmatviewsetvalore2 0 xaxis2matviewsetvalore2 1 yaxis2matviewsetvalore2 2 zaxis2matviewsetvalore2 3 00fmatviewsetvalore3 0 result1matviewsetvalore3 1 result2matviewsetvalore3 2 result3matviewsetvalore3 3 10fthe results i get from opengl and from the svg output are quite different but in two days i could not come up with a solutionthis is the opengl outputand this is my svg outputas you can see it is rotation is not correntany idea why the line points are the same and the matrices too hopefullypasing the matrices i was creating did not work i mean the matrices were wrong i think because opengl did not show anythingso i tryed doing the opposite i created the matrices in opengl and used them with my code the result is better but not perfect yetnow i think the i do something wrong mapping the 3d points into 2d screen points because the points i get are inverted in y and i still have some lines not perfectly matchingthis is what i get using the opengl matrices and my previous approach to map 3d points to 2d screen space this is the svg not opengl renderok this is the content of the view matrix i get from openglthis is the projection matrix i get from opengland this is the result i get with those matrices and by changing my 2d point y coordinate calculation like bofjas saidit looks like some rotations are missing my camera has a rotation of 30a on both the x and y axis and it looks like they are not computed correctlynow i am using the same matrices opengl does so i think that i am doing some wrong calculations when i map the 3d point into 2d screen coordinates,['c++'] +775251,remove black load flash on html5 video i have been creating a website for an online game that i play in the header i have a html5 video that plays very briefly 1second in internet explorer there is no issue however in chrome as the video is loading there is a very brief flash of black screen is there any way that i can remove this flash or failing that make it white to match the background you can see what i mean here if you try it in ie and the chrome you will see the difference in how the video loads alternatively is there any better way of implementing this i have tried using a animated gif however quality is significantly reduced thanks,"['javascript', 'html', 'css']" +775347,ambiguous overload in java8 is ejc or javac right i have the following classimport javautilhashsetimport javautillistpublic class overloadtestt extends hashsetlistt private static final long serialversionuid 1l public overloadtestoverloadtest extends t other public overloadtesthashset extends t source private overloadtestobject source public void notambigious overloadtestobject o1 new overloadtestobjectsource public void ambigious overloadtestobject o2 new overloadtestsource this compiles fine under jdk 7s javac as well as eclipse with compliance set to 17 or 18 however attempting to compile under jdk 8s javac i get the following errorerror srcmainjavaoverloadtestjava1835 reference to overloadtest is ambiguouserror both constructor toverloadtestoverloadtest extends t in overloadtest and constructor toverloadtestjavautilhashset extends t in overloadtest matchnote that this error applies only to the constructor invocation in the ambigous method not the one in the notambiguous method the only difference is that ambiguous is relying on the diamond operatormy question is this is javac under jdk 8 properly flagging an ambiguous resolution or was javac under jdk 7 failing to catch an ambiguity depending on the answer i need to either file a jdk bug or an ecj bug,['java'] +775405,using an url scheme in xctestcase i want to run a test which awaits the response of a browsera test target has an infoplist where i can register custom url schemes but those are never called i know that an test target is not a real applicationis there a wayedit for bounty i want to write an integration test for a class that calls openurltel some phone number how do i subscribe to this url scheme in an xctestcase,['objective-c'] +775482,where is qt designer app on mac anaconda can you guys help me find qt designer app on mac i installed anaconda package and conda reports that qt sip and pyqt are installed still i could not find the designer app in any of the folders my python app that uses pyqt works perfectly i am very new to macs and probably missing something very simplei did search folder tree for anything named designer i found qtdesignerso supposed to be executable atusersxanacondapkgspyqt4104py27 0libpython27sitepackagespyqt4 but it would not even run saying cannot execute binary fileanacondabin does not have itthere is a folder anacondaincludeqtdesigner but noting i can runanacondapkgsqt4853bin no designeri am totally confused now,['python'] +775512,coldfusion openxml error could not load file or assembly documentformatopenxml i am net coder and i am really really new to coldfusion i wrote a dll library which automatically generates an invoice i needed to use the library from a coldfusion application i have successfully loaded the classes in my library as coldfusion objects as i can call the methods however there is one method in my class which uses wordprocessingdocument which is a class of documentformatopenxmlpackaging i am actually getting this error systemiofilenotfoundexception could not load file or assembly documentformatopenxml version2556310 cultureneutral publickeytoken31bf3856ad364e35 or one of its dependencies the system cannot find the file specified file name documentformatopenxml version2556310 cultureneutral publickeytoken31bf3856ad364e35 at invoicelibrarydocumenthandlerconvertdocumenttodocxstring file at invoicelibrarydocumenthandlerprocessdocumenti have imported the documentformatopenxmldll so is the windowsbasedll filescfobject typenet namewordprocessingdocument classdocumentformatopenxmlpackagingwordprocessingdocument assemblycusersmydocsdocumentsvisual studio 2012projectsinvoicegeneratorinvoicelibrarybinreleasedocumentformatopenxmldllcprogram files x86reference assembliesmicrosoftframeworknetframeworkv45windowsbasedlli need your guidance to what am i doing wrong or what am i missing here,"['c#', '.net']" +775579,swift sourcekitservice crashed i have a swift project using core data and the generated code for savecontext is causing xcode to crash with the sourcekitservice crashed error when i comment it out the error stops and it seems to be selfmanagedobjectcontext which is causing the error i have commented out my code so it is like a new project but its still crashing thanksxcode 601func savecontext if let moc selfmanagedobjectcontext var error nserror nil if mochaschanges mocsaveerror replace this implementation with code to handle the error appropriately abort causes the application to generate a crash log and terminate you should not use this function in a shipping application although it may be useful during development nslogunresolved error error erroruserinfo abort i made a new project and copied my code across and the new project is fine and exactly the same so i have reported this to apple as a potential bugthanksupdatefound this to make things a little easier,['ios'] +775593,what does margin auto mean i checked mdn to see what means to have an auto value for margin property and it says auto is replaced by some suitable value eg it can be used for centering of blocksbut what it is that suitable value and suitable for whati tried myself some experiments and i saw that if i add marginleft auto the container goes to right like is floating to rightcontainer background red width 120px marginleft autodoes it mean that adding margin auto is actually something like take all the space available and when you add both left and right margins it centers the div because it tries to take all the space from left and from right,"['html', 'css']" +775618,error domaincomalamofireerrorserializationresponse code1011 request failed internal server error 500 i am using afnetworking in my applicationto post data on server i wrote following code void caloginapinsdictionary dictprofile 1 nsdictionary params usernamedictprofile valueforkeyname first namedictprofile valueforkeyfirst name last namedictprofile valueforkeylast name emaildictprofile valueforkeyemail dobdictprofile valueforkeybirthday genderdictprofile valueforkeygender locationdictprofile valueforkeylocation valueforkeyname timezonedictprofile valueforkeytimezone language profile pic urlnsstring stringwithformatdictprofile valueforkeyid cover pic url nsstring host url nsstring stringwithformatloginbase url afhttprequestoperationmanager operationmanager afhttprequestoperationmanager manager operationmanagerrequestserializer afjsonrequestserializer serializer operationmanager posthost url parametersparams successafhttprequestoperation operation id responseobject nslogrespresponseobject enter what happens here if succesful failureafhttprequestoperation operation nserror error nslogerrorerror enter what happens here if failure happens but in response i got following errorerrorerror domaincomalamofireerrorserializationresponse code1011 request failed internal server error 500 userinfo0x7cc8bb50 comalamofireserializationresponseerrorresponsenshttpurlresponse 0x7ca9d4d0 url status code 500 headers contenttype texthtml date tue 07 oct 2014 082540 gmt server wsgiserver01 python276 vary cookie xframeoptions sameorigin nserrorfailingurlkey nslocalizeddescriptionrequest failed internal server error 500i do not understand where i made mitakeany help would be appriciable,"['objective-c', 'iphone']" +775685,apn apple push notification payload size limit in official documentation you can find the infoeach push notification includes a payload the payload contains information about how the system should alert the user as well as any custom data you provide the maximum size allowed for a notification payload is 256 bytes apple push notification service refuses any notification that exceeds this limithowever in wwdc 14 we can see this screenshoti wonder if there is any official apple statement about the size limit of push notification i tested it and larger that 256 bytes works but documentation said it should not can someone confirm or deny the size of remote notifications,['ios'] +775731,error domaincomalamofireerrorserializationresponse code1011 request failed bad request 400 i am using afnetworking library to post data on serverfollowing is my code to post data on server void caloginapinsdictionary dictprofile 1 nsdictionary params nsdictionary dictionarywithobjectsandkeysdictprofile valueforkeyname username dictprofile valueforkeyfirst namefirst name dictprofile valueforkeylast namelast name dictprofile valueforkeyemailemail dictprofile valueforkeybirthdaydob dictprofile valueforkeygendergender dictprofile valueforkeylocation valueforkeynamelocation dictprofile valueforkeytimezonetimezone language nsstring stringwithformatdictprofile valueforkeyidprofile pic url cover pic urlnil afhttprequestoperationmanager manager afhttprequestoperationmanager manager managerrequestserializer afjsonrequestserializer serializer manager post parametersparams successafhttprequestoperation operation id responseobject nslogjson responseobject failureafhttprequestoperation operation nserror error nslogerror error and in response i got following errorerror domaincomalamofireerrorserializationresponse code1011 request failed bad request 400 userinfo0x7c87b6f0 comalamofireserializationresponseerrorresponsenshttpurlresponse 0x7cc220e0 url status code 400 headers allow post options contenttype applicationjson date tue 07 oct 2014 104508 gmt server wsgiserver01 python276 vary accept cookie xframeoptions sameorigin nserrorfailingurlkey nslocalizeddescriptionrequest failed bad request 400 comalamofireserializationresponseerrordata7b226465 7461696c 223a2022 4a534f4e 20706172 73652065 72726f72 202d204e 6f204a53 4f4e206f 626a6563 7420636f 756c6420 62652064 65636f64 6564227di am not able to understand why i got the such kind of error what is missing in my code,"['ios', 'objective-c', 'iphone']" +775900,why are typedef identifiers allowed to be declared multiple times from the c99 standard 675a declaration specifies the interpretation and attributes of a set of identifiers a definition of an identifier is a declaration for that identifier that for an object causes storage to be reserved for that object for a function includes the function body for an enumeration constant or typedef name is the only declaration of the identifierif identifiers with typedef are in fact definitions then why are they allowed to be declared more than once exampleint main typedef int x typedef int xabove program compiles with no errors how is this possible i was expecting the program to give me a multiple definition error,['c'] +776002,could not find method android for arguments when building android project from gradle i have an gradlebased android project with 4 submodules two libraries and two applications i was trying to simplify the buildgradle files of each submodule by moving some of of the shared codeconfigurations to the top level buildgradle file and use subprojects to make that code available to each submodulethe file system structure looks like thisroot app1 app2 lib1 lib2 buildgradle settingsgradlethe problem is that if i add an android section to the subprojects then gradle tasks fail for example this is my toplevel buildgradle filesubprojects project android buildtoolsversion 20 running gradle returns thiswhat went wrong a problem occurred evaluating root project android could not find method android for arguments build 7dngpra6ldok366maq0on77r7e run closure3 closure543d95624 on root project androidi searched for similar posts and some people suggest adding the line apply plugin android to each subproject in order to expose the missing android method that gradle is complaining about however that solution does not work for me because it would effectively add that line to library project which require apply plugin androidlibrary insteadis there a way to use android inside of subprojects when you have apps and libraries in the same project,['android'] +776083,whats missingsuboptimal in this memcpy implementation i have become interested in writing a memcpy as an educational exercise i would not write a whole treatise of what i did and did not think about but heres some guys implementation forceinline a a oea sizea2ci14aeac14e a a aa14aae a c ac void mymemcpychar dst const char src size t size void start dst for size sizeof m256i size sizeof m256i m256i ymm mm256 loadu si256const m256i src mm256 storeu si256 m256i dst ymm define cpy 1b uint8 t dst const uint8 t srcdefine cpy 2b uint16 t dst const uint16 t srcdefine cpy 4b uint32 t dst const uint32 t srcif defined m x64 defined m ia64 defined amd64 define cpy 8b uint64 t dst const uint64 t srcelse define cpy 8b mm storel epi64 m128i dst mm loadu si128const m128i src const uint64 t src uint64 t dstendifdefine cpy16b mm storeu si128 m128i dst mm loadu si128const m128i src const m128i src m128i dst switch size case 0x00 break case 0x01 cpy 1b break case 0x02 cpy 2b break case 0x03 cpy 1b cpy 2b break case 0x04 cpy 4b break case 0x05 cpy 1b cpy 4b break case 0x06 cpy 2b cpy 4b break case 0x07 cpy 1b cpy 2b cpy 4b break case 0x08 cpy 8b break case 0x09 cpy 1b cpy 8b break case 0x0a cpy 2b cpy 8b break case 0x0b cpy 1b cpy 2b cpy 8b break case 0x0c cpy 4b cpy 8b break case 0x0d cpy 1b cpy 4b cpy 8b break case 0x0e cpy 2b cpy 4b cpy 8b break case 0x0f cpy 1b cpy 2b cpy 4b cpy 8b break case 0x10 cpy16b break case 0x11 cpy 1b cpy16b break case 0x12 cpy 2b cpy16b break case 0x13 cpy 1b cpy 2b cpy16b break case 0x14 cpy 4b cpy16b break case 0x15 cpy 1b cpy 4b cpy16b break case 0x16 cpy 2b cpy 4b cpy16b break case 0x17 cpy 1b cpy 2b cpy 4b cpy16b break case 0x18 cpy 8b cpy16b break case 0x19 cpy 1b cpy 8b cpy16b break case 0x1a cpy 2b cpy 8b cpy16b break case 0x1b cpy 1b cpy 2b cpy 8b cpy16b break case 0x1c cpy 4b cpy 8b cpy16b break case 0x1d cpy 1b cpy 4b cpy 8b cpy16b break case 0x1e cpy 2b cpy 4b cpy 8b cpy16b break case 0x1f cpy 1b cpy 2b cpy 4b cpy 8b cpy16b break undef cpy 1bundef cpy 2bundef cpy 4bundef cpy 8bundef cpy16b return startthe comment translates as size is usually known as the compiler can optimize the code inline out most uselessi would like to improve if possible on this implementation but maybe there is not much to improve i see it uses sseavx for the larger chunks of memory then instead of a loop over the last 32 bytes does the equivalent of manual unrolling with some tweaking so here are my questionswhy unroll the loop for the last several bytes but not partially unroll the first and now single loopwhat about alignment issues are not they important should i handle the first several bytes up to some alignment quantum differently then perform the 256bit ops on aligned sequences of bytes and if so how do i determine the appropriate alignment quantumwhats the most important missing feature in this implementation if anyfeaturesprinciples mentioned in the answers so faryou should restrict your parameters chuxthe memory bandwidth is a limiting factor measure your implementation against itzbosonfor small arrays you can expect to approach the memory bandwidth for larger arrays not as much zbosonmultiple threads may be are necessary to saturate the memory bandwidth zbosonit is probably wise to optimize differently for large and small copy sizes zbosonalignment is important not explicitly addressedthe compiler should be made more explicitly aware of obvious facts it can use for optimization such as the fact that size 32 after the first loop chuxthere are arguments for unrolling your sseavx calls benjackson here and arguments against doing so paulrnontemporal transfers with which you tell the cpu you do not need it to cache the target location should be useful for copying larger buffers zboson,['c'] +776100,how to insert a new value to a set and erase another at the same time each set contains elements in a specified order i want to specify a bound on the size of a set and automatically delete the last element if a new one strictly smaller in terms of the order is inserted and the specified size is already reachedof course i could do something like the followingclass bounded setprivate using set stdsetkey compare allocator using iterator typename setiteratorpublic bounded setstdsize t size m sizesize stdpairiterator bool insertkey const value if m setsize m size return m setinsertvalue auto last stdprevm setend if comparevalue last m seteraselast return m setinsertvalue return stdmake pairlast false private set m set stdsize t m sizebesides the fact that bounded set is not the best name since bounded containers are a well known thing in the world of concurrent programming i am worried about memory allocation in this implementation most likely at first the space used by last will be freed but immediately after that new memory needs to be allocated for valuewhat i really would like to do is using the memory allocated for last and copy over the data for value to this place while preserving the order,['c++'] +776168,rxjava fetching observables in parallel i need some help in implementing parallel asynchronous calls in rxjava i have picked up a simple use case wherein the first call fetches rather searches a list of products tile to be thisplayed the subsequent calls go out and fetch a reviews and b product imagesafter several attempts i got to this place 1 observabletile searchtile searchserviceclientgetsearchresultssearchterm 2 listtile alltiles new arraylisttile 3 clientresponse response new clientresponse 4 searchtileparallelotile 5 return otileflatmapt 6 observablereviews reviews reviewsserviceclientgetsellerreviewstgetsellerid 7 observablestring imageurl reviewsserviceclientgetproductimagetgetproductid 8 return observablezipreviews imageurl r u 9 tsetreviewsr10 tsetimageurlu11 return t12 13 14 subscribee 15 alltilesaddtile e16 line 1 goes out and fetches the product tile to be thisplayedline 4 we take the list of the observable and shard it to fetch reviews and imageurlslie 67 fetch the observable review and observable urlline 8 finally the 2 observables are zipped up to return an updated observableline 15 finally line 15 collates all the individual products to be thisplayed in a collection which can be returned back to the calling layerwhile the observable has been sharded and in our tests run over 4 different threads fetching of reviews and images seems to be one after another i suspect that the zip step on line 8 is basically causing the sequential invocation of the the 2 observables reviews and urldoes this group have any suggestion to parallely fetch reiews and image urls in essence the waterfall chart attached above should look more vertically stacked the calls to reviews and images should be in parallelthanksanand raman,['java'] +776211,xero api integration in php for a public type application i want to integrate xero api for public application in phpi am stuck with oauth application authorizationi have download code from github find on xero api code sample for public applicationi am using following code requirelibxerooauthphp require configphp useragent xerooauthphp public signatures array consumer key app consumre key shared secret app secret key core version 20 xerooauth new xerooauth array merge array application type xro app type oauth callback oauth callback user agent useragent signatures include testsphpi am passing following xml data xml invoices invoice typeaccrectype contact namemartin hudsonname contact date20130513t0date duedate20130520t0duedate lineamounttypesexclusivelineamounttypes lineitems lineitem descriptionmonthly rental for property at 56a wilkins avenuedescription quantity43400quantity unitamount39500unitamount accountcode200accountcode lineitem lineitems invoice invoices params array oauth callback oauth callback response1 xerooauthrequest get xerooauthurl requesttoken params if xerooauthresponse code 200 outhtoken xerooauthresponse response oauth exp explodeouthtoken oauth exp token explodeoauth exp1 oauth token oauth exp token1 first i am oauth token and passing into oauth invoice url response xerooauthrequestpost xerooauthurlinvoices core arrayoauth tokenoauth token xml now i am getting 401 error in response oauth token mismatchcan anyone please suggest me asap what mistake i am doing,['php'] +776220,what does aar means in gradle compile task i am new in gradle and cannot find any documentation about this feature all i noticed is thatcompile comgithubasneasnevk021 caused some manifest merging problems some grunting abot different minsdkversions and that compile comgithubasneasnevk021aar works fine,['android'] +776223,how do i benchmark or trace a specific function in the linux kernel how do i use ftrace or anything else to trace a specific userdefined function in the linux kernel i am trying to create and run some microbenchmarks so i would like to have the time it takes certain functions to run i have read through at least as much as i can the documentation but a step in the right direction would be awesomei am leaning towards ftrace but having issues getting it to work on ubuntu 1404,['c'] +776228,how to use wxpython for python 3 i installed wxpython 3011 but i am unable to import wx using python 341 i am getting the following errorpython 341 v341c0e311e010fc may 18 2014 005421 gcc 421 apple inc build 56 dot 3 on darwintype help copyright credits or license for more information import wxtraceback most recent call last file stdin line 1 in moduleimporterror no module named wxnevertheless i can import wx if i use python 27 the default installation in my os x 109python 275 default mar 9 2014 221505 gcc 421 compatible apple llvm 50 clang5068 on darwintype help copyright credits or license for more information import wxhow can i use wxpython for python 3 and specifically for python 341,['python'] +776256,why does react require jsdom for testing when writing tests for react components you have to render them into the dom in order to make assertions about their correctness for example if you want to test that a certain class is added to a node given a certain state you have to render into a dom node then inspect that dom node via the normal dom apithe thing is considering react maintains a virtual dom into which it renders why cannot we just assert on the virtual dom once the component is rendered that seems to me like a very good reason to have something like the virtual domhave i missed something,['javascript'] +776267,still not optimized for iphone 6 and iphone 6 plus i have an app that just went live and it is still not saying optimized for iphone 6 and iphone 6 plusi added launch screens and app icons in required resolutionsadjusted all inner screen to fit with the new iphone screensadded screenshots for 47 and 55 inches devices on itunes connect what am i missing now,['ios'] +776275,detect if views are overlapping i have problem with drawing views on another size screens i need method which has two parameters of view type and return true if first view overlapping on second view and false in another case and,['android'] +776353,parse string to long using a specified locale sv and numberformat i tried to parse a string 14 123 to a long in java using swethish locale using this codestring longstring 14 123numberformat swethishnumberformat numberformatgetinstancenew localesvsystemoutprintlnswethishnumberformatparselongstringlongvaluethe output of this code is 14 it should be 14123 as per this question i tried with both the sv and sv se locale but this time the result was identical in both cases according to and the grouping separator in both cases is a space so why does the string to long parsing not handle a for the locale properly formatted double value stored as string,['java'] +776467,how do i add a bullet point in front of a text binding in wpf i have the following abbreviated for simplicityitemscontrol itemsourcebinding enumerablelist itemscontrolitemtemplate datatemplate textbox textbinding thisplayname modeoneway datatemplate itemscontrolitemtemplateitemscontrolhow can i get it so that my textbox shows a bullet point in front of the text bound to it desired formatlist item 1list item 2,['c#'] +776468,strange behavior dateinterval in php i have this codei1 dateintervalcreatefromdatestring10 minutesi2 dateintervalcreatefromdatestring30 minutesvar dumpi1 i2var dumpi1 i2var dumpi1var dumpi1 i2var dumpi1 i2and this outputboolfalseboolfalseobjectdateinterval3 8 booltruebooltrueis it a php bughelp me to understand the reason for this behavior,['php'] +776625,crop image to square android how can i cut rectangular image 600 x 300 from left and right to fit in square imageview i do not want to resize image i just want to crop it to be 300 x 300solutionas blackbelt said bitmap cropimg bitmapcreatebitmapsrc startx starty dstwidth dstheightis great for cropping images so how can you automatically crop images with different sizes i create this simple code for that from drawablebitmap src bitmapfactorydecoderesourcecontextgetresources rdrawableimage from urlbitmap src nulltry string url inputstream in new javaneturlurlopenstream src bitmapfactorydecodestreamin catch exception e eprintstacktraceint width srcgetwidthint height srcgetheightint crop width height 2bitmap cropimg bitmapcreatebitmapsrc crop 0 height heightimageviewsetimagebitmapcropimg,['android'] +776687,django naive datetime while time zone support is active sqlite i am going around in circles on this on and need some help i continue to get a naive timezone warning not sure what i am doing wrong arg here is the warningdjangodbmodelsfields init py12 runtimewarning datetimefield videomodified received a naive datetime 20141007 0 while time zone support is active runtimewarninghere is the model code redacted somewhatfrom djangodb import modelsfrom djangoutils import timezoneclass itembasemodelsmodel created modelsdatetimefieldeditablefalse modified modelsdatetimefieldeditablefalse class meta abstract true def saveself args kwargs updates timestamps on save if not selfid selfcreated timezonenow selfmodified timezonenow return superitembase selfsaveargs kwargsclass videoitembase passand the relevant i think part of my settings filetime zone utcuse tz trueis this a sqlite issue am still testing things or am i missing something fundamental here i have read up on it here and here and of course at the docs here but i am stumped thanksedit added test that throws the erroram getting the error when i run my tests i left the redacted stuff in there but you should get the ideafrom djangotest import testcasefrom djangocontribauth import get user modelfrom videomodels import video videoaccountclass videotestcasetestcase def setupself user get user modelobjectscreate user usernamejacob email passwordtop secret selfvideo account videoaccountobjectscreate account type1 account id12345 thisplay nametest account selfpk1 videoobjectscreatevideo type1 video idq7x3fyid2u0 video accountselfvideo account owneruser def test video creationself creates a video object selfassertequalselfpk1video id q7x3fyid2u0 selfassertequalselfpk1video link,['python'] +776714,retrofit throwing error expected begin array but was begin object hi i am new to the retrofit library i am having problems parsing some json i have looked at some other solutions on stackoverflow but not having much luck with my problem im trying to get a a simple webservice to work any suggestions would be gratefully appreciated json file employeesfirstnamejohn lastnamedoe firstnameanna lastnamesmithfirstnamepeter lastnamejonesrequest method public void requestemployeedatastring uri restadapter adapter new restadapterbuildersetendpointendpointbuild employeesapi employeesapi adaptercreateemployeesapiclass employeesapigetemployeesnew callbacklistemployeesemployeesclass override public void successlistemployeesemployeesclass employees response response liststring names new arrayliststring logvnas the employees webservice success response override public void failureretrofiterror retrofiterror logvnas the employees webservice failed retrofiterror employeesjava public class employees liststring listofstrings new arrayliststringserializednamevalueemployeespublic listemployees employeespublic void setemployeeslistemployees employees thisemployees employeespublic static class employeesclass string firstname string lastname override public string tostring return firstname lastname employeesapijava public interface employeesapi getget namesjsonpublic void getemployeescallbacklistemployeesemployeesclass responsethe error im getting is the employees webservice failed retrofitretrofiterror comgooglegsonjsonsyntaxexception javalangillegalstateexception expected begin array but was begin object at line 1 column 2 path i understand the error is saying the data is an object and it should start with an array but i cant work it out thanks,['android'] +776729,in clang how do you use perfunction optimization attributes i am trying to compile a specific function with no optimization using clang in order to prevent certain securityrelated calls to memset from being optimized awayaccording to the documentation that can be found here there exists an optnone attribute which allows this also an example can be found hereunfortunately at least on the below version of clang on os x 1095 this is causing compiler warnings as can be seen in this example clang versionapple llvm version 60 clang6051 based on llvm 35svntarget x86 64appledarwin1340thread model posix cat optnonecinclude stringh attribute optnone voidalways memsetvoid b int c size t len return memsetb c len clang wall o3 c o optnoneo optnonecoptnonec316 warning unknown attribute optnone ignored wattributes attribute optnone void 1 warning generatedi also tried using pragma clang optimize off but this caused an unknown pragma ignored warningdoes anyone know why this is not working did i miss a prerequisite for using this feature i also tried using various different std parameters including c11 gnu11 c99 and gnu99 but nothing changed the behavior,['c'] +776788,error when adding a reference to my unit test project in visual studio 2013 i am using visual studio 2013from my newly created test project i try to add a reference to my actual project like thisin solution explorer select references in the banktests project and then choose add reference from the context menui get an error saying unable to add a reference to project myproject,['c#'] +776917,memory starting location in c i am looking into to the memory layout of a given process i notice that the starting memory location of each process is not 0 on this website text starts at 0x080480 one reason can be to thistinguish the address with the null pointer i am just wondering if there is any another good reasons thanks,['c'] +776939,error c2678 binary no operator found which takes a lefthand operand of type or there is no acceptable conversion i am trying to compile the following codeinclude boostgeometrygeometriespoint xyhppinclude iostreaminclude utilitytypedef boostgeometrymodeld2point xylong pointtypedef stdpairpoint point vectorbool operatorconst point p1 const point p2 return p1x p2x p1y p2yint main vector vec1point00 point11 vector vec2point00 point12 stdcout vec1 vec2 false stdendl stdcout vec1 vec1 true stdendlvs2012 c compiler returns the following compilation errorvcincludeutility219 error c2678 binary no operator found which takes a lefthand operand of type const point or there is no acceptable conversiongcc c compiler returns the following compilation errorusrincludec48bitsstl pairhin instantiation of abool stdoperatorconst stdpair t1 t2 const stdpair t1 t2 with t1 boostgeometrymodeld2point xy t2 boostgeometrymodeld2point xyatestcpp28 required from here usrincludec48bitsstl pairh21551 errorno match for aoperatora operand types are aconst boostgeometrymodeld2point xya and aconst boostgeometrymodeld2point xya return xfirst yfirst xsecond ysecond error thisappears if i overload operator for vectorbool operatorconst vector v1 const vector v2 return v1first v2first v1second v2second,['c++'] +777024,laravel 5 viewshare i am trying to do a viewsharecurrent user authuser but in laravel 5 i cannot find where to do this in l4 you could do this in the basecontroller but that one does not exists anymoregrt glenn,['php'] +777047,how to get current url in jinja2flask requesturl not working is there a way to print the current url in jinja2flaskeg if the current url is requestpath works and prints example12 but how to i get the full url with http as wellfrom the docs here requesturl should work but it does not yield anythingthanksupdatehere are the rendercontext args from viewspyclass eventdetailvieweventobjectmixin formview template name gigpublicabouthtml context object name event form class eventpurchaseticketform def get context dataself kwargs context supereventdetailview selfget context datakwargs return context,['python'] +777119,how to get indexpath in prepareforsegue voidprepareforsegueuistoryboardsegue segue senderidsender if segueidentifier isequaltostringaction nsindexpath indexpath selftbl indexpathforselectedrow secondviewcontroller destviewcontroller seguedestinationviewcontroller destviewcontrollergetstring getarray objectatindexindexpathrow i wanna to access the selected row indexbut show null for every selected row please help me,['ios'] +777174,remove byte order mark from signed pdf file i am using itextsharp 551 in order to sign pdf files digitally with a detached signature obtained from a third party authority everything seems to work fine the file is valid and eg adobe reader reports no problems thisplays the signatures as valid etcthe problem is that the java clients have apparently some problems with those files the file can be neither opened nor parsedthe files have a byte order mark in the header which seems to cause the behavior x00efx00bbx00bfi could identify the bom like thispdfreader reader new pdfreaderpathbyte metadata readermetadata metadata0 metadata1 metadata2 contain the bomhow can i either remove the bom without losing the validity of the signature or force the itextsharp library not to append these bytes into the files,['c#'] +777328,implementing singleton with an enum in java i have read that it is possible to implement singleton in java using an enum such aspublic enum mysingleton instance but how does the above work specifically an object has to be instantiated here how is mysingleton being instantiated who is doing new mysingleton,['java'] +777370,how to make a window fullscreen in a secondary thisplay with tkinter i know how to make a window fullscreen in the main thisplay but even when moving my apps window to a secondary thisplay connected to my pc when i callselfmasterattributesfullscreen trueto fullscreen that window it does so in the main thisplay and not in the secondary one the apps window thisappears from the secondary thisplay and instantly appears in the main one in fullscreenhow can i make it fullscreen in the secondary thisplay,['python'] +777624,pyplot using percentage on x axis i have a line chart based on a simple list of numbers by default the xaxis is just the an increment of 1 for each value plotted i would like to be a percentage instead but cannot figure out how so instead of having an xaxis from 0 to 5 it would go from 0 to 100 but keeping reasonably spaced tick marks code below thanksfrom matplotlib import pyplot as pltfrom mpl toolkitsaxes gridaxislines import subplotdata812151718185figpltfigure174axsubplotfig1figadd subplotaxpltplotdata,['python'] +777679,oracle sql execution plan changes due to sys op c2c internal conversion i am wondering why cost of this query select from address aleft join name and on nadress idaidwhere astreet01is higher thanselect from address aleft join name and on nadress idaidwhere astreetn01where address table looks like thisid numberstreet varchar2255 charpostal code varchar2255 charand name table looks like thisid numberaddress id numbername varchar2255 charsurname varchar2255 charthese are costs returned by explain planexplain plan for 01 id operation name rows bytes cost cpu time 0 select statement 3591 1595k 87 0 02 1 nested loops outer 3591 1595k 87 0 02 2 table access full address 3 207 3 0 01 3 table access by index rowid name 1157 436k 47 0 01 4 index range scan name hsi 1157 1 0 01 predicate information identified by operation id 2 filterastreet01 4 accessnaddress idaidexplain plan for n01 id operation name rows bytes cost cpu time 0 select statement 347 154k 50 0 01 1 nested loops outer 347 154k 50 0 01 2 table access full address 1 69 3 0 01 3 table access by index rowid name 1157 436k 47 0 01 4 index range scan name hsi 1157 1 0 01 predicate information identified by operation id 2 filtersys op c2castreetu01 4 accessnaddress idaidas you can see cost for n01 query is lower than cost for 01 any idea why n01 needs additionally convert varchar to nvarchar so cost should be higher sys op c2c the other question is why rows processed by n01 query is lower than 01edittable address has 30 rowstable name has 19669 rows,['sql'] +777794,searchview results list width is there a way to make searchviews results list occupy whole screen width i have tried using custom layout for searchview but this does not change the search results lists width see screenshot,['android'] +777828,how to change option menu icon in the action bar how to change the index icon of option menui mean icon 3here is my codeoverridepublic boolean oncreateoptionsmenumenu menu menuinflater inflater getmenuinflater inflaterinflatermenuoptions menu return trueand here is the xml fileitem androidididbugreport androidtitlestringoption bugreport item androidididinfo androidtitlestringoption info item androidididabout androidtitlestringoption about,['android'] +778068,how to avoid clashing php traits used for dependency injection i am finally getting around to exploring traits in php the first place i thought i would try it out is injection of config bits into classes if i am using dic i might have code like this in any class that needs a config objectprotected function setconfigconfig thisconfig configprotected configthis seems like a natural fit to traits to avoid having that boilerplate code all over the place so i might create thistrait config protected function setconfigconfig thisconfig config protected configand then use it like soclass foo use config public function construct can now use thisconfig that is great now let us say i want to create a second trait say for loggingtrait logger protected function setloggerlogger thislogger logger protected loggerwhich i can use like thisclass foo use logger public function construct can now use thislogger also great now the problem comes if those two traits want to use each other it seems quite reasonable that a logger class would need to have a config object injected which means doing thistrait logger use config protected function setloggerlogger thislogger logger protected loggerbut then things will break when another class uses both of these traitsclass foo use config logger public function construct want to use thisconfig and thislogger this of course does not work because the config bits are effectively duplicated in fooi could just leave out the use config piece from the logger trait knowing that it will be there in the end but this feels weird to me as it creates a sort of external dependency what if i want to use the logger someplace that did not already have the config trait this solution also means i need to suffer my ide phpstorm 8 warning me about unknown methods and not offering autocompletion i realize i could fix these problems in turn by using method but that is just putting lipstick on a pig so to speaki could also alias the config bits in logger but that is also problematicall of this has a bit of a smell to it but i have not figured out yet whether that is because this is a new pattern for me or if it really is a stinky pattern either way i am not sure the best way to make this approach actually workany advice on the best way to solve this problem in traits or is it better to avoid traits for dic shortcutting,['php'] +778082,mysql and jdbc with rewritebatchedstatementstrue i have been reading around here here and here about the advantages of using rewritebatchedstatementstrueif i understood it right with rewritebatchedstatementstrue the jdbc will pack as many queries as possible into a single network packet lowering this way the network overhead am i rightthen it comes into my attention that the value defined in the mysql server for the max allowed packet may cause problems with the queries queries not being executed on the serverso my second question is does jdbc knows the value assigned to max allowed packet and therefore make the packet smaller than the defined value for max allowed packet or that is something that the developer has to take in considerationif i understood something wrong please let me know as well,"['java', 'mysql', 'sql']" +778089,how to change page title in angular using routeprovider i found several similar questions however none of the answers helped they all seem to involve some type of location dependencies that i am unable to get injected rightmy code belowfunction app dependencies var app angularmoduleportalexchange ngroute aproducts appmanage aprofile main controller portalcontroller appcontrollerportalcontroller functionscope if top link dashboardhasclassunactive top top link dashboardremoveclassunactive top top link dashboardaddclassactive top controller for dashboard appcontrollerdashboardcontroller function controller for developers appcontrollerdeveloperscontroller functionscope pagesettitledevelopers controller for quote appcontrollerquotecontroller functionscope pagesettitlebegin quote directive for header appdirectiveappheader function type of directive e for element a for attribute url of a template return restrict e templateurl templatesmodulesglobalsappheaderhtml directive for footer appdirectiveappfooter function return restrict e templateurl templatesmodulesglobalsappfooterhtml controller function thisdate datenow controllerasfooter configure our routes appconfigfunctionrouteprovider routeprovider route for the dashboard page when templateurl templatessectionsappdashboardhtml controller dashboardcontroller route for the dashboard page whendashboard title my dashboard templateurl templatessectionsappdashboardhtml controller dashboardcontroller route developers page whendevelopers title for developers templateurl templatessectionsappdevelopershtml controller developerscontroller route begin quote whenquote title begin quote templateurl templatessectionsappquotehtml controller quotecontroller apprunrootscope route functionrootscope rootscopeonroutechangesuccess functionnewval oldval if oldval newval documenttitle routecurrenttitle the run functionapprunrootscope route functionrootscope rootscopeonroutechangesuccess functionnewval oldval if oldval newval documenttitle routecurrenttitle htmldoctype htmlhtml langen ngaportalexchange ngcontrollerportalcontroller as portalhead meta charsetutf8 title ngbindtitlemyapptitlehead,['javascript'] +778172,how to connect viewcontrollerswift to viewcontroller in storyboard i made a new view controller in storyboard and made a new swift file that inherits uiviewcontroller however my viewdidload is not being calledwhat do i need to do to connect my view controller in my story board to my swift code so viewdidload is calledi see there is this how to connect storyboard to viewcontrollerhowever in a default project firstviewcontrollerstoryboard does not have firstviewcontroller in that box it is empty yet viewdidload is still called it does not make sense,['ios'] +778189,what is the equivalent of javascript settimeout in java i need to implement a function to run after 60 seconds of clicking a button please help i used the timer class but i think that that is not the best way,"['java', 'javascript']" +778246,find if 24 hrs have passed between datetimes python i have the following method last updated is a datetime object representing the last time this program randef time difflast updated day period last updatedreplacedaylast updatedday1 hour1 minute0 second0 microsecond0 delta time day period last updated hours delta timeseconds 3600 make sure a period of 24hrs have passed before shuffling if hours 24 print hello else print do nothingi want to find out if 24 hrs have passed since last updated how can i do that in python,['python'] +778431,whats the best practice for naming swift files that add extensions to existing objects it is possible to add extensions to existing swift object types using extensions as described in the language specificationas a result it is possible to create extensions such asextension string var utf8datansdata return selfdatausingencodingnsutf8stringencoding allowlossyconversion false however whats the best naming practice for swift source files containing such extensions in the past the convention was to use extendedtypecategorynamem for the objectivec type as thiscussed in the objectivec guide but the swift example does not have a category name and calling it stringswift does not seem appropriateso the question is given the above string extension what should the swift source file be called,['objective-c'] +778528,why is not my char passing correctly problem statement using a contrived exampleworking as expected b is printed to screenvoid fooconst char barvoid main const char bar4 bar foobarvoid fooconst char bar pointer to first text cell of video memory char memory char 0xb80 memory bar0not working as expected 0 is printed to screenvoid fooconst char barvoid main foobarvoid fooconst char bar pointer to first text cell of video memory char memory char 0xb80 memory bar0in other words if i pass the const char directly it does not pass correctly the const char i get in foo points to zeroed out memory somehow what am i doing wrongbackground info as requestedi am developing an operating system for fun using a guide i found here the guide generally assumes you are on a unixbased machine but i am developing on a pc so i am using mingw so that i have access to gcc ld etcin the guide i am currently on page 54 where you have just bootstrapped your custom kernel rather than simply thisplaying an x as the guide teaches i decided to use my existing knowledge of cc to attempt to write my own rudimentary print string function the function is supposed to take a const char and write it char by char into video memorythree files are currently involved in the projectthe boot sector compiled through nasm to a bin filethe kernel entry routine compiled without linking through nasm to a o linked against the kernelthe kernel compiled through gcc linked along with the kernel entry routine through the ld command which produces a bin which is appended to the bin file produced by the boot sectoronce the combined bin file is generated i am converting it to vdi virtualbox thisk image and running it in a vm i have set upadditional infoi just noticed that when virtualbox is converting the bin file to vdi it is reporting different sizes for the two examples i had a hunch that maybe the string was getting omitted entirely from the compiled product sure enough when i look at bin for the first example in a hex editor i can find the text bar but i cannot when i look at a hex dump for the bin of the second examplethis leads me to believe that the compilation process i am using has a flaw in it somewhere here are the commands i am usingnasm boot sectorasm f bin o boot sectorbinnasm kernel entryasm f elf o kernel entryogcc ffreestanding c kernelc o kernelold t nul o kerneltmp ttext 0x10 kernel entryo kerneloobjcopy o binary j text kerneltmp kernelbincopy b boot sectorbinkernelbin os imagebinos imagebin is what is converted to the vdi file which is used in the vm,['c'] +778603,title of historypushstate is unsupported whats a good alternative the second parameter of historypushstate and historyreplacestate can be used to set the title of the history entrythis means that when the user clicks through page 1 to page 8 this is what he should see in his history barand it is working on safari and operabut on chrome and firefox this is what the user seestrying to change documenttitle does not work as it changes all the entries within the history titlewhats the best solution to this problemare we forced to using only one history title for all the pages implemented using pushstate and replacestate,['javascript'] +778694,intellij idea getclassgetresource return null i am using intellij idea 1315 i used to work with eclipse i am working on javafx application i try to load fxml file within my mainapp class using getclassgetresourcei read the documentation and i try several idea at the end i have nullthis is the hierarchy dzbilaldjagohomekodemainappjavadzbilaldjagohomekodeviewrootlayoutfxmlthis is the code snippet i usedfxmlloader loader new fxmlloaderloadersetlocationgetclassgetresourceviewrootlayoutfxmli tried other solution such giving the url from the root and using the classloaderthe result is the same any idea please,['java'] +778795,javascript learning how to consume restful apis i have been coding js for a few years and am now learning more seeing a lot of employers asking for knowledge of rest apis or experience consuming restful services i know the basics of ajax both in native js and jquery i have done a fair bit o goggling on rest both on so and the web there seems to be a ton of info on how to build restful apis serverside with java c etc but little on how to access those services with javascript here are questionsis consuming restful services another way of saying getting data from a server with ajax or something else altogetherif it is something else where are some good tutorials on the subjectonce i get the basics down where can i find restful apis on the web to consume,"['javascript', 'jquery']" +778948,bridging issue while using afnetworking with pods in a swift project i am facing problem when i initialise afhttpsessionmanager in my swift class i have added afnetworking using pods in my project it shows error use of undeclared type but when i press cmd click on afhttpsessionmanager it takes me to the right classi have added bridging header and imported afnetworkingh class in it i have try to fix this issue by added bridging header in many ways1 i have created bridging header class myself by creating new header file2 i have created objective c test class in swift project and added bridging header when it asks to add bridging header in projectbridging header also did not work with myself created test class when i tried to initialise it in my swift classcan anyone help me sorting out this issue,['objective-c'] +779046,in swift fileexistsatpath path string isdirectory isdirectory unsafemutablepointer bool accepts single parameter only the method fileexistsatpath in the example below accept single argument onlyif fmfileexistsatpathresult isdirectoryisdir the exact error message is extra argument isdirectory in callany idea whats wrong,['ios'] +779105,issue with genstrings for swift file genstrings works well to extract localizable content from m file as find name m xargs genstrings o enlprojbut not working for swift file asfind name swift xargs genstrings o enlproj,['objective-c'] +779169,rubocop linelength how to ignore lines with comments using a rails 4 app i would like rubocop to ignore lines with comments just a comment or some code with an end of line comment when checking if a line is to long is there a way to do this,['ruby'] +779214,requests got stuck in activerecordquerycache middleware after deploying our rails app 409 ruby 212 we notice requests to our app get hang after a while usually 1 day or so using the gem rack timer were able to find out requests got stuck at activerecordquerycache middlewarerack timer incoming activerecordquerycache 9256267731189728 msafter removing it our app seems to be back to normal however i understand the purpose of this middleware is to increase the performance so removing is just a temporary solution were using mysql 5167 with adapter mysql2 0313update right after i posted this question the server started hang again this time requests were stuck at actionthispatchroutingrouteseti 20141013t231703661346 32498 info rack timer application action actionthispatchroutingrouteset 36676612360477448 msi 20141013t231703661946 32498 info rack timer application action actionthispatchroutingrouteset 4373914719343185 msdo you know any reason could cause thisthank you in advance,"['mysql', 'ruby-on-rails']" +779232,how to specify javaxxmlaccessexternalschema for the jaxb2 maven plugin i have a maven plugin jaxb2 and i need to supply a jvm arg to it i do not think there is a tag to add jvm args in the pom for iti know i can pass in jvm args on the command line eg mvn clean install djavaxxmlaccessexternalschemaallis it possible to set this jvm arg in the pom so that i do not have to type it into the command line every timeas aside this jvm arg is required in order for it to work with java8 it works fine with java7,['java'] +779278,javaxjson add new jsonnumber to existing jsonobject i want to add properties to an existing instance of jsonobject if this property is boolean this is quite easyjsonobject jo joputbooleanproperty jsonvaluetruehowever i also want to add a jsonnumber but i could not find a way to create an instance of jsonnumber heres what i could dojsonobjectbuilder job jsoncreateobjectbuilderjsonnumber jn jobaddnumber 42buildgetjsonnumbernumberjoputnumberproperty jnbut i could not think of a more dirty way to accomplish my task so is there are more direct cleaner approach to add a jsonnumber to an existing instance of jsonobject,['java'] +779292,uidocumentinteractioncontroller presentoptionsmenufrombarbuttonitem error in ios8 unknown activity items supplied uidocumentinteractioncontroller presentoptionsmenufrombarbuttonitem gives me a console error in ios8 hardware and not on 71 hardware or earlier unknown activity items supplied comadobepdf in my official app store version of my app the app crashes at this point when i compile and run on my ipad it just gives the error but does not crashmy codein the huidocumentinteractioncontroller docinteractioncontrollerin the m selfdocinteractioncontroller uidocumentinteractioncontroller interactioncontrollerwithurlfileurlselfdocinteractioncontrollerdelegate selfuibarbuttonitem element is an element in my toolbarselfdocinteractioncontroller presentoptionsmenufrombarbuttonitemelement animatedyesif i do a nslog of docinteractioncontrolleruti i see comadobepdf at the console so the uti is being recognized properlyi can get around the unknown activity items by using presentopeninmenufrombarbuttonitem instead of presentoptionsmenufrombarbuttonitem for the uidocumentinteractioncontroller call but i want to show the user the print and email options as well not only the external app opening optionstested on ipad version 802 xcode version 601 deployment target 60 also tested with deployment target 80 all objectivec running on ipad version 71 does not produce the error,"['ios', 'objective-c']" +779408,sending sms in ios with swift first of all i am really surprised that this is not a duplicate because there are tons of stackoverflow questions that solve this in objectivec but i have yet to see a good answer that used swiftwhat i am looking for is a code snippet in swift that sends an arbitrary string as a the body of a text message to given phone number essentially i would like something like this from apples official documentation but in swift instead of objectiveci imagine this is not too difficult as it can be done in just a couple of lines of code in androidedit what i am looking for is 520 lines of swift code i do not agree that this is too broad in java for android the solution looks like thispackage comcompanyappnameimport androidappactivityimport androidtelephonysmsmanagerpublic class mainactivity extends activity protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate public static final mphonenumber 1 public static final mmessage hello phone smsmanagergetdefaultsendtextmessagemphonenumber null mmessage null null now this is the android solution and it is only 11 lines java tends to be much more verbose than swift so i doubt what i am asking is too broad it is more likely that i do not know how to use the objectivec messagecomposer object because the documentation that i linked to above is unclear with regard to usage in swift,['ios'] +779409,can i get the return value inside ensure in ruby def some method puts in method return i am a return valueensure puts will print at the end can i somehow get the return value of some method hereendis there some possibly metaprogramming principleway to get the return value of a method inside the ensure clause which is a part of the method definition which we all know executes no matter what,['ruby'] +779532,how to achieve base64 url safe encoding in c i want to achieve base64 url safe encoding in c in java we have the common codec library which gives me an url safe encoded string how can i achieve the same using cbyte toencodeasbytes systemtextasciiencodingasciigetbytesstringtoencodestring returnvalue systemconverttobase64stringtoencodeasbytesthe above code converts it to base64 but it pads is there is way to achieve url safe encoding,['c#'] +779556,dashed border not showing in firefox i have a radius div with 5px dashed border but border not show properly in firefoxit show well in ie and chromedemo div height100px width 100px backgroundcolor c borderradius 50 border5px dashed 3,"['html', 'css']" +779645,ios 8 completion block not called in my app i am using ttopeninappactivity to insert open in action inside uiactivitycontrollerinside it works like thissome view controller presents uiactivitycontroller with ttopeninactivity already built invoidopenwithaction nsurl fileurl some url cgrect rect some rect ttopeninappactivity openinappactivity ttopeninappactivity alloc initwithviewselfview andrectrect uiactivityviewcontroller activityviewcontroller uiactivityviewcontroller alloc initwithactivityitemsfileurl applicationactivitiesopeninappactivity ifui user interface idiom uiuserinterfaceidiomphone store reference to superview uiactionsheet to allow thismissal openinappactivitysuperviewcontroller activityviewcontroller show uiactivityviewcontroller self presentviewcontrolleractivityviewcontroller animatedyes completionnull else code for ipad irrelevant when user taps open in button the following method is triggered voidperformactivity ifselfsuperviewcontroller self activitydidfinishyes return thismiss activity view ifui user interface idiom uiuserinterfaceidiomphone iphone thismiss uiactivityviewcontroller selfsuperviewcontroller thismissviewcontrolleranimatedyes completionvoid if selffileurlscount 1 self openselectfileactionsheet else open uidocumentinteractioncontroller self opendocumentinteractioncontrollerwithfileurlselffileurlslastobject else code for ipad irrelevant as the app is for iphone only this piece of code should be executedselfsuperviewcontroller thismissviewcontrolleranimatedyes completionvoid if selffileurlscount 1 self openselectfileactionsheet else open uidocumentinteractioncontroller self opendocumentinteractioncontrollerwithfileurlselffileurlslastobject in ios7 everything works fine in ios8 uiactivitycontroller is thismissed and then nothing happenswhile debugging i did manage to detect that in ios8 completion handler is never calledplease help me find out the reason for this behavior and make it work as it shouldthank you in advance,['ios'] +779741,making bxslider full screen filling entire browser window i am currently trying to implement this very simple content slider i have reached a point where it is working however using the css code below i need to make the slider full screen filling the entire browser window however i can not see where to put the code for this can someody help me i feel like a bit of a dummy for asking such a simple questionmy current code is belowmy html codebodydiv clasliderul classbxsliderliimg srcimagesslide1png liliimg srcimagesslide2png liliimg srcimagesslide3png liuldivbodymy css codebxwrapper position relativeleft 0pxtop 0pxpadding 0zoom 1bxwrapper img maxwidth 100height 100thisplay block themebxwrapper bxviewport mozboxshadow 0 0 5px cwebkitboxshadow 0 0 5px cboxshadow 0 0 5px cborder 5px solid fleft 5pxbackground fix other elements on the page moving on chromewebkittransform translatez0moztransform translatez0 mstransform translatez0 otransform translatez0 transform translatez0bxwrapper bxpagerbxwrapper bxcontrolsauto position absolutebottom 30pxwidth 100 loader bxwrapper bxloading minheight 50pxbackground urlimagesbx loadergif center center norepeat fheight 100width 100position absolutetop 0left 0zindex 20 pager bxwrapper bxpager textalign centerfontsize 85emfontfamily arialfontweight boldcolor 6paddingtop 20pxbxwrapper bxpager bxpageritembxwrapper bxcontrolsauto bxcontrolsautoitem thisplay inlineblockzoom 1thisplay inlinebxwrapper bxpagerbxdefaultpager a background 6textindent 9pxthisplay blockwidth 10pxheight 10pxmargin 0 5pxoutline 0mozborderradius 5pxwebkitborderradius 5pxborderradius 5pxbxwrapper bxpagerbxdefaultpager ahoverbxwrapper bxpagerbxdefaultpager aactive background 0 direction controls next prev bxwrapper bxprev left 10pxbackground urlimagescontrolspng norepeat 0 32pxbxwrapper bxnext right 10pxbackground urlimagescontrolspng norepeat 43px 32pxbxwrapper bxprevhover backgroundposition 0 0bxwrapper bxnexthover backgroundposition 43px 0bxwrapper bxcontrolsdirection a position absolutetop 50margintop 16pxoutline 0width 32pxheight 32pxtextindent 9pxzindex 9bxwrapper bxcontrolsdirection athisabled thisplay none auto controls start stop bxwrapper bxcontrolsauto textalign centerbxwrapper bxcontrolsauto bxstart thisplay blocktextindent 9pxwidth 10pxheight 11pxoutline 0background urlimagescontrolspng 86px 11px norepeatmargin 0 3pxbxwrapper bxcontrolsauto bxstarthoverbxwrapper bxcontrolsauto bxstartactive backgroundposition 86px 0bxwrapper bxcontrolsauto bxstop thisplay blocktextindent 9pxwidth 9pxheight 11pxoutline 0background urlimagescontrolspng 86px 44px norepeatmargin 0 3pxbxwrapper bxcontrolsauto bxstophoverbxwrapper bxcontrolsauto bxstopactive backgroundposition 86px 33px pager with autocontrols hybrid layout bxwrapper bxcontrolsbxhascontrolsautobxhaspager bxpager textalign leftwidth 80bxwrapper bxcontrolsbxhascontrolsautobxhaspager bxcontrolsauto right 0width 35px image captions bxwrapper bxcaption position absolutebottom 0left 0background 69background rgba80 80 80 075width 100bxwrapper bxcaption span color fontfamily arialthisplay blockfontsize 85empadding 10px,['css'] +779747,labeled continue statement within while loop the following simple examples cause compiletime error but it is not clear whypublic static void main string args throws javalangexception int i 0 d systemoutprintlnd whilei 10 i continue d andpublic static void main string args throws javalangexception int i 0 d systemoutprintlnd whilei 10 i continue d demobut the following works finepublic static void main string args throws javalangexception int i 0 d whilei 10 systemoutprintlnd i continue d does it allow to tranfer control to the only while for or do statement it does not say in the jls what it actual says isa continue statement with label identifier attempts to transfer control to the enclosing labeled statement a147 that has the same identifier as its label that statement which is called the continue target then immediately ends the current iteration and begins a new one,['java'] +780242,android performing stop of activity that is not resumed when i push my app to background and do some other stuff like whatsapp or sms onresume it works great but i recently thiscovered that when i openlaunch facebook app while my app is on background i dont know what happensbut onresume the app misbehavesdont do what it is required to do but when i go back to homepage and come back it works fineplease help me out how to fix it logcat with all messages without filter1015 125359899 iadrenoegl32033 remote branch quiclnxla351 rb1015 125359899 iadrenoegl32033 local patches none1015 125359899 iadrenoegl32033 reconstruct branch au linux android lnxla351 rb1040402048018 f2fd134 nothing1015 125359924 dopenglrenderer32033 enabling debug mode 01015 12540 valarmmanager7677 sending alarm alarm42cfa490 type 3 android1015 125400110 iactivitymanager7677 thisplayed ukorghumanfocushfievaluatetrainingactivity 838ms1015 125400114 dwifistatemachine7677 handlemessage e msgwhat1515721015 125400114 dwifistatemachine7677 processmsg connectedstate1015 125400114 dwifistatemachine7677 processmsg l2connectedstate1015 125402258 valarmmanager7677 sending alarm alarm42ebd600 type 1 comfacebookkatana1015 125402274 valarmmanager7677 sending alarm alarm42ec0ff0 type 1 comandroidchrome1015 125402428 dhardware info7386 hw info append hw type device name speaker1015 125403011 wbroadcastqueue7677 permission denial broadcasting intent actandroidnetconninet condition action flg0x4010 has extras from null pid1 uid1 requires comfacebookpermissionprodfb app communication due to registered receiver broadcastfilter41fdecd0 u0 receiverlist42b2f608 31941 comfacebookkatana10103u0 remote429a17e81015 125403011 wbroadcastqueue7677 permission denial broadcasting intent actandroidnetconnconnectivity change flg0x4010 has extras from null pid1 uid1 requires comfacebookpermissionprodfb app communication due to registered receiver broadcastfilter41fdecd0 u0 receiverlist42b2f608 31941 comfacebookkatana10103u0 remote429a17e81015 125403118 dwifistatemachine7677 handlemessage e msgwhat1515721015 125403118 dwifistatemachine7677 processmsg connectedstate1015 125403118 dwifistatemachine7677 processmsg l2connectedstate1015 125403140 dwifistatemachine7677 handlemessage x1015 125403141 dgcoreflp8174 unknown pending intent to remove1015 125403145 wfb4adefaultabstractmqttpushservice31941 attempt to start service that is already started1015 125403242 dwifistatemachine7677 handlemessage e msgwhat1311551015 125403242 dwifistatemachine7677 processmsg connectedstate1015 125403243 dwifistatemachine7677 processmsg l2connectedstate1015 125403245 dwifistatemachine7677 handlemessage x1015 125403319 ddalvikvm31941 gc concurrent freed 1833k 9 free 20190k22072k paused 5ms7ms total 86ms1015 125403320 ddalvikvm31941 wait for concurrent gc blocked 68ms1015 125403323 wmediaplayerjni31941 mediaplayer finalized without being released1015 125403452 wbroadcastqueue7677 permission denial broadcasting intent actandroidnetconnconnectivity change flg0x4010 has extras from null pid1 uid1 requires comfacebookpermissionprodfb app communication due to registered receiver broadcastfilter42b51d68 u0 receiverlist429feb50 31941 comfacebookkatana10103u0 remote41fb87881015 125403573 wfb4adefaultjackson fallback31941 using comfasterxmljacksondatabinddeserstdenumdeserializer42914bc8 to deserialize simple type class comfacebookcommonutiltristate1015 125403587 wfb4adefaultjackson fallback31941 using comfasterxmljacksondatabinddeserstdenumdeserializer42bb3100 to deserialize simple type class comfacebookcontactsgraphqlcontactprofiletypecontactprofiletype1015 125403957 ddalvikvm31941 gc concurrent freed 3400k 15 free 20455k23952k paused 4ms7ms total 88ms1015 125403957 ddalvikvm31941 wait for concurrent gc blocked 75ms1015 125404099 wfb4adefaultjackson fallback31941 using beanserializer for comfacebookkatananewbookmarkqenewbookmarkconfig to serialize class comfacebookkatananewbookmarkqenewbookmarkconfig1015 125404119 dwifistatemachine7677 handlemessage e msgwhat1515721015 125404120 dwifistatemachine7677 processmsg connectedstate1015 125404120 dwifistatemachine7677 processmsg l2connectedstate1015 125404124 dwifistatemachine7677 handlemessage x1015 125404177 wfb4adefaultjackson fallback31941 using comfasterxmljacksondatabinddeserstdenumdeserializer42a30980 to deserialize simple type class comfacebookplatformwebdialogsplatformwebviewactionmanifestfetchstate1015 125404197 idalvikvm31941 could not find method comandroidinternalwidgetilocksettingsstuba referenced from method comfacebookkeyguardtypelocksettingsservicekeyguardtyperesolverb1015 125404197 wdalvikvm31941 vfy unable to resolve static method 5338 lcomandroidinternalwidgetilocksettingsstuba landroidosibinderlcomandroidinternalwidgetilocksettings1015 125404197 ddalvikvm31941 vfy replacing opcode 0x71 at 0x00231015 1254040 isbarnetworkcontroller7758 onsignalstrengthschanged signalstrength 19 0 120 160 120 1 1 99 2147483647 2147483647 2147483647 2147483647 2147483647 gsmlte 0 108 1 false 5 5 0 0 0 99 99 99 5 level51015 125404814 vwebviewchromiumfactoryprovider31941 binding chromium to main looper looper main tid 1 41f8cbd01015 125404815 ilibraryloader31941 expected native library version number actual native library version number 1015 125404816 ichromium31941 infolibrary loader hookscc116 chromium logging enabled level 0 default verbosity 01015 125404817 ibrowserstartupcontroller31941 initializing chromium process renderers01015 125404822 eaudiomanagerandroid31941 bluetooth permission is missing1015 125404864 wchromium31941 warningproxy servicecc890 pac support thisabled because there is no system implementation1015 125405121 dwifistatemachine7677 handlemessage e msgwhat1515721015 125405121 dwifistatemachine7677 processmsg connectedstate1015 125405122 dwifistatemachine7677 processmsg l2connectedstateand this is onresumesuperonresume if backgroundthreadrunning true backgroundthreadrunning false if constantsisvideoediting editingprogresetvisibilityviewvisible else editingprogresetvisibilityviewgone if constantsisaudioprocessing addaudioprogresetvisibilityviewvisible else addaudioprogresetvisibilityviewgone if ishomekeypressed isrecentactivity isrecentactivity false homekeypressedfalse alertdialogbuilder ab new alertdialogbuilder createtrainingactivitythis absetmessage due to other application launches video process will be cancellednare you sure you want to cancel setpositivebuttonyes dialogclicklistener setnegativebuttonno dialogclicklistenershow edit how i fixed the issue i wrote this code in onresume method try check if any view exists on current view style button findviewbyidridxyz button catch exception e button was not found it means your button does not exist on the current view it was freed from the memory therefore stop of activity was performed in this case i restart my app intent i new intent isetclassgetapplicationcontext mainactivityclass isetflagsintentflag activity clear top startactivityi show toast to the user toastmaketextgetapplicationcontext data lost due to excess use of other apps toastlength longshow,['android'] +780290,how to do perform a dynamic cast with a unique ptr i have a class hierarchy as followsclass basesession public boostenable shared from thisbasesessionclass derivedsessiona public basesessionclass derivedsessionb public basesessionwithin the derived class functions i regularly call functions like thisfuncboostdynamic pointer castderivedsessionashared from thissince i was working with shared ptr to manage the sessions this was working fine recently i thiscovered that my use of shared ptr is not optimal for this case that is because these sessions are singleton objects that maintain one socket per client if socket is reconnected the session copies used to become zombiesas workaround i started passing shared ptr by reference rather than copies this solved the zombie problemideally i felt i should be using unique ptr to store the session and then pass references to other functions that opened a whole can of wormshow do i cast a base class unique ptr object to derived class unique ptr object what is the unique ptr version of the following linefuncboostdynamic pointer castderivedsessionashared from thisi just want one copy of the session object everything else should be reference,['c++'] +780292,ios corebluetooth centralmanagerdidconnectperipheral didfailtoconnectperipheral not getting called i am pulling my hair out of this problems i am trying to connect to ble devices cannot see what i have done wrong in my code below voidviewdidload super viewdidload do any additional setup after loading the view typically from a nib cm cbcentralmanager alloc initwithdelegateself queuenil voidviewdidappearboolanimated super viewdidappearanimated voiddidreceivememorywarning super didreceivememorywarning thispose of any resources that can be recreated nsstringuuidstringcfuuidrefuuid cfstringref string cfuuidcreatestringnull uuid return bridge transfer nsstringstring voidcentralmanagerdidupdatestatecbcentralmanager central if centralstate cbcentralmanagerstatepoweredon self scanforperipherals voidcentralmanagercbcentralmanager central didthiscoverperipheralcbperipheral peripheral advertisementdatansdictionary advertisementdata rssinsnumber rssi nslogreceived peripheral n peripheral nslogadv data advertisementdata peripheral setdelegateself central connectperipheralperipheral optionsnil peripheral readrssi intscanforperipherals nsdictionary options nsdictionary dictionarywithobjectsandkeys nsnumber numberwithboolno cbcentralmanagerscanoptionallowduplicateskey nil cm scanforperipheralswithservicesnil optionsoptions return 0 voidcentralmanagercbcentralmanager central didconnectperipheralcbperipheral peripheral nslogdidconnectperipheral voidcentralmanagercbcentralmanager central didthisconnectperipheralcbperipheral peripheral errornserror error nslogdidthisconnectperipheral voidcentralmanagercbcentralmanager central didfailtoconnectperipheralcbperipheral peripheral errornserror error nslogfailed to connect voidperipheralcbperipheral peripheral didreadrssinsnumber rssi errornserror error nslogdidreadrssithese devices are not my own i do not know its proximity uuid but as far as i know it would not be needed in connecting via corebluetooth rightall of the devices are thiscovered in didthiscoverperipheral in the selector i tried to connect them but there is nothing comes after thatam i to expect a dialog with pairing password request when i called to didthiscoverperipheralif so i do not see any dialog why is thatfrom apple documents it clearly stated that after trying to connect to a device you should get a called to either didconnectperipheral or didfailtoconnectperipher but i got noneany thoughts i have been trying for almost a week nowappreciate every helps thanks,"['ios', 'objective-c']" +780411,cannot choose camera in file upload in cordova application on android so i made a cordova 36 app i added android platform and made a simple html with an imput fieldinput typefile capturecamera acceptimage idtakepicturefieldi have added usespermission androidnameandroidpermissioncamera usesfeature androidnameandroidhardwarecamera androidrequiredfalse usesfeature androidnameandroidhardwarecameraautofocus feature name to the manifest filebut when i press the button i cannot choose to take a new picture with the camera are there any permission i miss or anything else i cannot use the cordova take picture functions it has to be done in pure html,"['android', 'html']" +780462,how to thisable the sslv3 protocol in jetty to prevent poodle attack is there any specific exclusion list available which thisables only sslv3 ciphers are not tlsv12i have jetty 8 and upgrading to 9 is not an option now my current jettysslxml looks as followsconfigure idserver classorgeclipsejettyserverservercall nameaddconnector arg new classorgeclipsejettyserversslsslselectchannelconnector arg new classorgeclipsejettyhttpsslsslcontextfactory new arg set nameexcludeciphersuites array typejavalangstring itemssl rsa with null md5item itemssl rsa with null shaitem itemssl rsa export with rc4 40 md5item itemssl rsa with rc4 128 md5item itemssl rsa with rc4 128 shaitem itemssl rsa export with rc2 cbc 40 md5item itemssl rsa with idea cbc shaitem itemssl rsa export with des40 cbc shaitem itemssl rsa with des cbc shaitem itemssl rsa with 3des ede cbc shaitem itemssl dh dss export with des40 cbc shaitem itemssl dh dss with des cbc shaitem itemssl dh dss with 3des ede cbc shaitem itemssl dh rsa export with des40 cbc shaitem itemssl dh rsa with des cbc shaitem itemssl dh rsa with 3des ede cbc shaitem itemssl dhe dss export with des40 cbc shaitem itemssl dhe dss with des cbc shaitem itemssl dhe dss with 3des ede cbc shaitem itemssl dhe rsa export with des40 cbc shaitem itemssl dhe rsa with des cbc shaitem itemssl dhe rsa with 3des ede cbc shaitem itemssl dh anon export with rc4 40 md5item itemssl dh anon with rc4 128 md5item itemssl dh anon export with des40 cbc shaitem itemssl dh anon with des cbc shaitem itemssl dh anon with 3des ede cbc shaitem itemssl fortezza kea with null shaitem itemssl fortezza kea with fortezza cbc shaitem itemssl fortezza kea with rc4 128 shaitem itemssl dhe rsa with aes 128 cbc shaitem itemssl rsa with aes 128 cbc shaitem array set new argcallstill when i run sslscan nofailed ssl3 localhost443 i get supported server ciphers accepted sslv3 128 bits dhersaaes128sha accepted sslv3 128 bits aes128shaprefered server ciphers sslv3 128 bits dhersaaes128sha,['java'] +780493,how to unit test routes in embercli app using qunit i cannot seem to get the model hooks and actions triggered from a unit testany sampleblog doing this embercli environment would be a great helpi found this linkwhat kind of unit test solution for the routes in emberjsbut routemodel is throwing errors as transition is not defined import test modulefor from emberqunitmoduleforroutesample sampleroute specify the other units that are required for this testtestbeforemodel hook works function var route thissubject emberrunfunction routesetmodel sample data consolelogmodel set was beforemodel hook calledthe sample routeimport ember from emberexport default emberrouteextend beforemodel function transition consoleloginside beforemodel hook aftermodel function consolelogin aftermodel hook,['javascript'] +780567,does a declaration using auto match an extern declaration that uses a concrete type specifier consider the following programextern int xauto x 42int main clang 35 accepts it live demo gcc 49 and vs2013 do not live demo for the former who is right and where is the correct behavior specified in the c standard,['c++'] +780582,generate html string from angularjs template string i have angularjs template as a string including ngrepeat and other directives i want to compile it in the controller to produce the result html as stringexample on what i want to apply in angularinputvar template div ngrepeatitem in itemsitemdatadivoutputvar result div1divdiv2divdiv3divdiv4divi want this to be done in the controller i have and i tried the followingvar template div ngrepeatitem in itemsitemdatadivvar linkfunction compiletemplatevar result linkfunctionscopeconsolelogresult prints the template itselfthanks,['javascript'] +780628,android studio automatically opens documentation view idk if it is bug or kind of settings but it is very annoying while typing value ie androidlayout gravity it opens hints with dropdown and after a while documentation view get opened and hide the dropdown with hints i checked that no button is suspended or anything like that i use ubuntu 1404regards,"['java', 'android']" +780690,application hangs when profiling with instrument in xcode 601 i am observing that whenever i am profiling my application using instrument in xcode 601 application hangs every time while i am browsing through the application i am using iphone 5s ios 802 to run my application when i run the application on device it runs all fine anyone faced the similar issue and know the workaround please advise,"['ios', 'objective-c']" +780766,using momentjs to convert date to epoch then back to date i am trying to convert a date string to epoch then epoch back to the date string to verify that i am providing the correct date stringvar epoch moment10152014 900unix do i need to do localvar momentdate momentepoch i have also tried momentutcepoch var momentdatestr momentdatecalendaralertvalues are epoch epoch momentdatestr momentdatestrrendersvalues are epoch 14133780 momentdatestr 01171970note i am using the following version of the moment js script cdnjscloudflarecomajaxlibsmomentjs283momentwithlocalesjs,['javascript'] +781010,androidgraphicsdrawablecolordrawable cannot be cast to androidsupportv7widgetroundrectdrawablewithshadow i tried to use cardview in my application which worked pretty good within my xml layout since i want to generate them in my code and not via xml i tried to set the radius with cardviewsetradiusmethod as suggested by android developers this does not work at all i hope someone can help me with my problem or got a nice workaround with xml layoutsthis is my codeint height int typedvalueapplydimensiontypedvaluecomplex unit dip 100 getresourcesgetthisplaymetrics float radius int typedvalueapplydimensiontypedvaluecomplex unit dip 4 getresourcesgetthisplaymetrics for string color colors cardview card new cardviewgetactivity textview text new textviewgetactivity cardsetbackgroundcolorcolorparsecolorcolor cardsetlayoutparamsnew viewgrouplayoutparams viewgrouplayoutparamsmatch parent height cardsetradiusradius error textsettextargsgetcolorsindexofcolor color cardaddviewtext groupaddviewcard this is my logjavalangruntimeexception unable to start activity componentinfocombroboxmaterialcolorpalettecombroboxmaterialcolorpalettemainactivity javalangclasscastexception androidgraphicsdrawablecolordrawable cannot be cast to androidsupportv7widgetroundrectdrawablewithshadow at androidappactivitythreadperformlaunchactivityactivitythreadjava2212 at androidappactivitythreadhandlelaunchactivityactivitythreadjava2271 at androidappactivitythreadaccess800activitythreadjava144 at androidappactivitythreadhhandlemessageactivitythreadjava1205 at androidoshandlerthispatchmessagehandlerjava102 at androidoslooperlooplooperjava136 at androidappactivitythreadmainactivitythreadjava5146 at javalangreflectmethodinvokenativenative method at javalangreflectmethodinvokemethodjava515 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava796 at comandroidinternaloszygoteinitmainzygoteinitjava612 at dalviksystemnativestartmainnative method caused by javalangclasscastexception androidgraphicsdrawablecolordrawable cannot be cast to androidsupportv7widgetroundrectdrawablewithshadow at androidsupportv7widgetcardvieweclairmr1setradiuscardvieweclairmr1java76 at androidsupportv7widgetcardviewsetradiuscardviewjava89 at combroboxmaterialcolorpalettecolorfragmentoncreateviewcolorfragmentjava61 at androidsupportv4appfragmentperformcreateviewfragmentjava1504 at androidsupportv4appfragmentmanagerimplmovetostatefragmentmanagerjava942 at androidsupportv4appfragmentmanagerimplmovetostatefragmentmanagerjava1121 at androidsupportv4appbackstackrecordrunbackstackrecordjava682 at androidsupportv4appfragmentmanagerimplexecpendingactionsfragmentmanagerjava1484 at androidsupportv4appfragmentactivityonstartfragmentactivityjava571 at androidappinstrumentationcallactivityonstartinstrumentationjava1171 at androidappactivityperformstartactivityjava5241 at androidappactivitythreadperformlaunchactivityactivitythreadjava2178a a a a a a a a a a a a at androidappactivitythreadhandlelaunchactivityactivitythreadjava2271a a a a a a a a a a a a at androidappactivitythreadaccess800activitythreadjava144a a a a a a a a a a a a at androidappactivitythreadhhandlemessageactivitythreadjava1205a a a a a a a a a a a a at androidoshandlerthispatchmessagehandlerjava102a a a a a a a a a a a a at androidoslooperlooplooperjava136a a a a a a a a a a a a at androidappactivitythreadmainactivitythreadjava5146a a a a a a a a a a a a at javalangreflectmethodinvokenativenative methoda a a a a a a a a a a a at javalangreflectmethodinvokemethodjava515a a a a a a a a a a a a at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava796a a a a a a a a a a a a at comandroidinternaloszygoteinitmainzygoteinitjava612a a a a a a a a a a a a at dalviksystemnativestartmainnative methodupdatei use the new lollipop sdk now with appcompat version 21 now it does not work at all even when i try it without setradiusnew logjavalangclasscastexception androidgraphicsdrawablecolordrawable cannot be cast to androidsupportv7widgetroundrectdrawablewithshadow at androidsupportv7widgetcardvieweclairmr1getshadowbackgroundcardvieweclairmr1java148 at androidsupportv7widgetcardvieweclairmr1getminwidthcardvieweclairmr1java139 at androidsupportv7widgetcardviewonmeasurecardviewjava181 at androidviewviewmeasureviewjava16521 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava5125 at androidwidgetlinearlayoutmeasurechildbeforelayoutlinearlayoutjava1404 at androidwidgetlinearlayoutmeasureverticallinearlayoutjava695 at androidwidgetlinearlayoutonmeasurelinearlayoutjava588 at androidviewviewmeasureviewjava16521 at androidwidgetscrollviewmeasurechildwithmarginsscrollviewjava1226 at androidwidgetframelayoutonmeasureframelayoutjava310 at androidwidgetscrollviewonmeasurescrollviewjava326 at androidviewviewmeasureviewjava16521 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava5125 at androidwidgetframelayoutonmeasureframelayoutjava310 at androidviewviewmeasureviewjava16521 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava5125 at androidwidgetframelayoutonmeasureframelayoutjava310 at androidviewviewmeasureviewjava16521 at androidsupportv4widgetdrawerlayoutonmeasuredrawerlayoutjava848 at androidviewviewmeasureviewjava16521 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava5125 at androidwidgetframelayoutonmeasureframelayoutjava310 at androidviewviewmeasureviewjava16521 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava5125 at androidsupportv7internalwidgetactionbaroverlaylayoutonmeasureactionbaroverlaylayoutjava453 at androidviewviewmeasureviewjava16521 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava5125 at androidwidgetframelayoutonmeasureframelayoutjava310 at androidviewviewmeasureviewjava16521 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava5125 at androidwidgetlinearlayoutmeasurechildbeforelayoutlinearlayoutjava1404 at androidwidgetlinearlayoutmeasureverticallinearlayoutjava695 at androidwidgetlinearlayoutonmeasurelinearlayoutjava588 at androidviewviewmeasureviewjava16521 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava5125 at androidwidgetframelayoutonmeasureframelayoutjava310 at comandroidinternalpolicyimplphonewindowdecorviewonmeasurephonewindowjava2552 at androidviewviewmeasureviewjava16521 at androidviewviewrootimplperformmeasureviewrootimpljava1915 at androidviewviewrootimplmeasurehierarchyviewrootimpljava1109 at androidviewviewrootimplperformtraversalsviewrootimpljava1291 at androidviewviewrootimpldotraversalviewrootimpljava996 at androidviewviewrootimpltraversalrunnablerunviewrootimpljava5603 at androidviewchoreographercallbackrecordrunchoreographerjava761 at androidviewchoreographerdocallbackschoreographerjava574 at androidviewchoreographerdoframechoreographerjava544 at androidviewchoreographerframethisplayeventreceiverrunchoreographerjava747 at androidoshandlerhandlecallbackhandlerjava733 at androidoshandlerthispatchmessagehandlerjava95 at androidoslooperlooplooperjava136 at androidappactivitythreadmainactivitythreadjava5146 at javalangreflectmethodinvokenativenative method at javalangreflectmethodinvokemethodjava515 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava796 at comandroidinternaloszygoteinitmainzygoteinitjava612 at dalviksystemnativestartmainnative methodupdate 2i guess this is a bug by google so i pointed it out for them,['android'] +781106,continue jacoco code coverage report after fail test case code coverage report not generated when test case failed in android studio using jacoco pluginhow to skip failed test case and generate code coverage report,['android'] +781140,increment operator is not invoked at sizeofn expression in c or c increment and decrement operator n n are not performed when it is in a sizeof operatorint and 100int size int sizeofnstdcoutni have written this code and run the program of course i think 101 will be showed for mebut n was not 101 it was 100why is that,"['c++', 'c']" +781175,how do i correctly setup and teardown my pytest class with tests i am using selenium for end to end testing and i cannot get how to use setup class and teardown class methodsi need to set up browser in setup class method then perform a bunch of tests defined as class methods and finally quit browser in teardown class method but logically it seems bad solution because in fact my tests will work not with class but with object i pass self param inside every test method so i can access objects varsclass testclass def setup classcls pass def test buttonsself data selfattribute can be used but not clsattribute pass def test buttons2self data selfattribute can be used but not clsattribute pass def teardown classcls passand it even seems not to be correct to create browser instance for class it should be created for every object separately rightso i need to use init and del methods instead of setup class and teardown class,['python'] +781333,nsstring containsstring crashes i am trying to filter an array according to one of it is string fieldsboth namelower and filterlower has nsstring value inside and yet i keep getting nscfstring containsstring unrecognized selector sent to instance 0x7f876b79e160void filterfriendsarraynsstringfilter filteredfriendsarray removeallobjects for facebookuser user in friendsarray nsstring namelower userusername lowercasestring nsstring filterlower filter lowercasestring if namelower containsstringfilterlower filteredfriendsarray addobjectuser thisplayedfriendsarray filteredfriendsarray,['ios'] +781341,adding property to each object of an array independently with angularjs angularextend i have an existing array with an object and several properties created on a first step it is created by the following functionscoperecordlist extractrecordjsonfromlocalstoragescopeaddrecord function scoperecordlistpush date scopedatejson time scopetime car scopecarlistcode driver scopedriverlistname from scopelocationlistplace destination scopelocationlist2place pax scopepaxlist scopecustom scopecustom false true false scopecarlist 0 scopedriverlist 0 scopelocationlist 0 scopelocationlist2 0 jsontorecordlocalstoragescoperecordlistit results in the following array date2014 10 16 time2022 car396 driverseb froma destinationb pax3what i am trying to do is to add another property into the existing object on the next step with ngclick i have tried with the following function but it does not seem to workscopeinsertrecord function recordlist var arrival arrival momentformathhmm consolelogarrival angularextendscoperecordlist arrival jsontorecordlocalstoragescoperecordlistthe end result i am looking for is the following date2014 10 16 time2022 car396 driverseb froma destinationb pax3 arrival2310maybe another thing to take also into consideration is that in the app it exists the possibility of having many different objects being listed some that have the arrival property already defined but some that will have it later in timeany pointerseditthe 2 solutions i got worked but did not accomplish what i am looking for so probably i was unclear on what i am trying to doi am saving a collection of objects into an array each object has a property arrival that will be defined on a second stepso first i create an array of objects like this date2014 10 16 time2042 car396 driverseb froma destinationb pax3 date2014 10 16 time2012 car319 driverseb fromc destinationd pax4 date2014 10 16 time2022 car396 driverseb fromg destinationa pax1 this is thisplayed on the view in a tablelike layout each row contains the data from an object and initially does not include the property arrival because the app tracks car movements and the car has not arrived to destination each row has also a button triggering insertrecord that defines the arrival time and its supposed to include the arrival property into each object independentlyso in this example maybe the car from the second object arrived and i want to be able to add the arrival property only for this particular object leaving the array like this date2014 10 16 time2042 car396 driverseb froma destinationb pax3 date2014 10 16 time2012 car319 driverseb fromc destinationd pax4 arrival2035 date2014 10 16 time2022 car396 driverseb fromg destinationa pax1 the 2 proposed solutions from dfsq allowed me to both define arrival for the first object of the array or for all the objects at once but not for each object separatelythis is the html code where insertdata is calleddiv classrow msfrow ngrepeatrecord in recordlist filter search div classcolmd1recordtimediv div classcolmd1strongrecordcarstrongdiv div classcolmd1recorddriverdiv div classcolmd3recordfromdiv div classcolmd3recorddestinationdiv div classcolmd1recordpaxdiv div classcolmd1 button ngclickinsertrecord ngshowrecordarrivali classfa facogibuttonrecordarrival divdiv being so any hints on how to get there,['javascript'] +781485,date constructors provide unexpected results when called with similar arguments i got one weird issue with date object initialization and wondering if someone can explain whyvar exp1 new date20141017var exp2 new date2014917var exp3 new date17 oct 2014consolelogexp1consolelogexp2consolelogexp3results thu oct 16 2014 180 gmt0600 mdt 16th fri oct 17 2014 0 gmt0700 mst why gmt 7 fri oct 17 2014 0 gmt0600 mdt the only one that works as expectedwhy are these three date objects so different,['javascript'] +781497,image slider is choppy i have put together a plain javascriptcss image slider started out as just a learning exercise but am now looking to apply it in the real world the problem is that the animation is choppy on my desktop which is a v high spec gaming rig and even worse on a mobile to the degree it is not really an animation anymoreyou can see it in action herewchrishowiecouksandsjsfiddle isolates much of the pertinent code it is not a this does not work issue so hopefully the fiddle gives enough to help optimize itin summary i have a div with 4 images in a row each image is 100 the width of the page i use javascript to translatex i have tried translate3d as heard this uses gpu but didnt make much diff and i set css transitions to easein the transformi also thought that potentially i am just trying to do too much on this site but then i look at some other sites doing a heck of a lot more and it is smooth as silk so i guess i am missing somethingfunction slideright if sliding return falsewindowsliding trueel documentgetelementbyidslidercst getcomputedstyleeltransformst csttransform cstwebkittransform cstmoztransformwidthst cstwidthwidthst widthstreplacepx computed width of slider 7680pxslidewidth widthst 4transformst transformstreplacematrix transformst transformstreplace transformst transformstsplittransformst transformst4 returns current transform in px without unit pxif transformst transformst 0var activebtn sldr mathroundnumbertransformst 1 slidewidthdocumentgetelementbyidactivebtnclasslistremovesliderbuttonactiveif activebtn sldr3 documentgetelementbyidslider mathround2 numbertransformst 1 slidewidthstylevisibility visible documentgetelementbyidslider mathround2 numbertransformst 1 slidewidthstylethisplay initial documentgetelementbyidsliderstyletransform translate3d 25 numbertransformst slidewidth 1 0 0 documentgetelementbyidsliderstyletransform webkittranslate3d 25 numbertransformst slidewidth 1 0 0 documentgetelementbyidsliderstyletransform moztranslate3d 25 numbertransformst slidewidth 1 0 0 documentgetelementbyidsliderstyletransform mstranslate3d 25 numbertransformst slidewidth 1 0 0 documentgetelementbyidleftslidebtnstylevisibility visible documentgetelementbyidleftslidebtnstylethisplay blockactivebtn activebtnreplacesldr activebtn sldr 1 numberactivebtndocumentgetelementbyidactivebtnclasslistaddsliderbuttonactiveif numberactivebtnreplacesldr 3 documentgetelementbyidrightslidebtnstylevisibility hidden documentgetelementbyidrightslidebtnstylethisplay nonesettimeoutfunction windowsliding false 20update still not resolved but on mobile i have made it usable by reducing the image size for small screens and also not thisplaying images that are offscreen not perfectly smooth but getting therethanks a lotc,"['javascript', 'html']" +781514,why is this trying to find the destructor twice i was trying out the following piece of codegeneraltemplatehifndef generatemplate h define generatemplate h include iostreamtemplate class tclass generaltemplate public generaltemplate generaltemplateconst generaltemplate g generaltemplate generaltemplate operator generaltemplate const g template class m void arbitraryfunctionconst m mendifmaincppinclude generaltemplatehinclude iostreamint main generaltemplateint gint gintarbitraryfunction23 return 0note that i do not have any implementation for the member functions of the class template but that is not the problem i know how to do that if i try to compile maincpp i should get a linking error and that is what i get the question is why is it trying to find the destructor twice last two lines of error belowg maincpp tmpcckrdpcso in function mainmaincpptext0x13 undefined reference to generaltemplateintgeneraltemplatemaincpptext0x34 undefined reference to void generaltemplateintarbitraryfunctiondoubledouble constmaincpptext0x45 undefined reference to generaltemplateintgeneraltemplatemaincpptext0x61 undefined reference to generaltemplateintgeneraltemplatecollect2 ld returned 1 exit status,['c++'] +781575,is p 2 well defined i am not sure whether statement below is well defined by standard c or notp1 2or other similar statemente1 operator e2from standard c about postincrementthe result of the postfix operator is the value of the operand after the result is obtained the value of the operand is incremented that is the value 1 of the appropriate type is added to it see the thiscussions of additive operators and compound assignment for information on constraints types and conversions and the effects of operations on pointers the side effect of updating the stored value of the operand shall occur between the previous and the next sequence pointand about coumpundassignmenta compound assignment of the form e1 op e2 differs from the simple assignment expression e1 e1 op e2 only in that the lvalue e1 is evaluated only once,"['c++', 'c']" +781623,run app on ipad mini retina on xcode 6 i build app for ipad and sent to my client and gave me feedback that it runs on every ipad devices which we supportedcompatible with ios5 ipad 1g 2g 3g 4g mini mini 2 air except ipad mini retina he said that app install fine but does not i do not have ipad mini retina but i want to check this on my side i install latest xcode 6 but still i am not able to see ipad mini simulator which you can see attached image so kindly any one give me suggestion how to accomplish this task thanks in advance,['ios'] +781738,good practice to pass variables between cucumberjvm steps to pass variables between steps now i am doing something like the example as followsfeature demo scenario create user given user creation form management when create user with name test then user is created successfullyjava class with steps definitionspublic class createusersteps private string username givenuser creation form management public void user creation form management throws throwable whencreate user with name public void create user with namestring username throws throwable thisusername username thenuser is created successfully public void user is created successfully throws throwable assert if exists an user with name equals to thisusername my question is if this is good practise to share information between steps or would be better define the feature asthen user with name test is created successfullyi am new with cucumberjvm so sorry if it is a brainless questionany help would be appreciated thanks,['java'] +781750,android studio library error package does not exist i have created android library as android studio module added as dependency to my root module while coding i can import any class from library package but while i am trying run the application i am getting an error package somemylibraryproject does not existbuildgradle root modulebuildscript repositories mavencentral dependencies classpath comandroidtoolsbuildgradle012 apply plugin comandroidapplicationdependencies compile filetreedir libs include jar compile comandroidsupportappcompatv720 compile comgoogleandroidgmsplayservices5 compile projectlibrariesmylibraryandroid compilesdkversion 17 buildtoolsversion 20 lintoptions thisable invalidpackage checkreleasebuilds false abortonerror false buildgradle library modulebuildscript repositories mavencentral dependencies classpath comandroidtoolsbuildgradle012 apply plugin comandroidapplicationapply plugin ideaandroid compilesdkversion 17 buildtoolsversion 20 dependencies compile filetreedir libs include jarsettingsgradle include librariesmylibraryps i have to mention that the project was exported from eclipse ide so the project structure is different from default one,['android'] +781767,breakpoints not getting hit in android studio i am using windows 7 and have recently switched from eclipse to android studio i am now having trouble debuggingrunning android studio 086 i set up a completely default install i create a default empty project targeting the ics sdk using the new project wizard i then put a breakpoint in oncreate click on the debug button and runthe debugger attached as i can see the message connected to the target vm in the debugger windowi know the code is being executed because i am updating some text in the ui to show thisi have tried putting breakpoints in many places but none are hiti am pulling my hair out here as i just cannot see what i am doing wrong i am new to gradle so i think there may be some settings in gradle that i should be changing but surely an absolutely standard project built with the wizard should let me hit breakpointsone thing i noticed is that in my buildgradle file there is no mention of a debug build only a release i wondered if that might be the problembuildtypes release runproguard false proguardfiles getdefaultproguardfileproguardandroidtxt proguardrulespro note i have tried this on both my own device and the emulatorupdatei changed the settings in the view breakpoints options to turn on java exception breakpoints but only for uncaught exceptions then at the end of oncreate i deliberately cause a nullpointerexception when i run in debug now i still do not hit my actual code and do not see the code break on my source but the program does pause i know it is my nullpointerexception that is causing this because when i remove it i can see that the code continues and does not breakat the point that my code breaks the debug window shows that i am in the main thread in a function called performlaunchactivity i cannot see any more information than this presumably therefore i am debugging through whatever level of code is calling performlaunchactivity but that my source is being treated as if i cannot step through it,['android'] +781790,concurrent arraylist i need an arraylistlike structure allowing just the following operationsgetint indexadde elementsetint index e elementiteratorbecause of the iterator being used in many places using collectionssynchronizedlist would be too errorprone the list can grow to a few thousand elements and gets used a lot so i am pretty sure that copyonwritearraylist will be too slow i will start with it to avoid premature optimizations but i would bet it would not work wellmost accesses will be singlethreaded reads so i am asking whats the proper data structure for thisi though that wrapping the synchronizedlist in something providing a synchronized iterator would do but it would not because of the concurrentmodificationexception concenrning concurrent behavior i obviously need that all changes will be visible by subsequent reads and iterators the iterator does not have to show a consistent snapshot it may or may not see the updates via setint index e element as this operation gets used only to replace an item with its updated version containing some added information which is irrelevant for the user of the iterator the items are fully immutablei clearly stated why copyonwritearraylist would not do concurrentlinkedqueue is out of question as it lacks an indexed access i need just a couple of operations rather than a fully fledged arraylist so unless any java concurrent listrelated question is a duplicate of this question this one is not,['java'] +781878,is accessing a global array outside its bound undefined behavior i just had an exam in my class today reading c code and input and the required answer was what will appear on the screen if the program actually runs one of the questions declared a44 as a global variable and at a point of that program it tries to access a2727 so i answered something like accessing an array outside its bounds is an undefined behavior but the teacher said that a2727 will have a value of 0afterwards i tried some code to check whether all uninitialized golbal variable is set to 0 is true or not well it seems to be trueso now my questionseems like some extra memory had been cleared and reserved for the code to run how much memory is reserved why does a compiler reserve more memory than it should and what is it forwill a2727 be 0 for all environmentedit in that code a44 is the only global variable declared and there are some more local ones in maini tried that code again in devc all of them is 0 but that is not true in vse in which most value are 0 but some have a random value as vyktor has pointed out,['c'] +781990,will the java compiler optimize out stringlength in a forloops condition consider the following java code fragmentstring buffer for int i 0 i bufferlength i systemoutprintlnbuffercharatisince string is immutable and buffer is not reassigned within the loop will the java compiler be smart enough to optimize away the bufferlength call in the for loops condition for example would it emit byte code equivalent to the following where bufferlength is assigned to a variable and that variable is used in the loop condition i have read that some languages like c do this type of optimizationstring buffer int length bufferlengthfor int i 0 i length i systemoutprintlnbuffercharati,['java'] +782003,typedef foo foo compiles but is it valid the following bit of code compiles in vs2008 and gcc 482templatetypename tvoidstruct foo typedef foo foo does not compileint main typedef foo foo foo f1 foochar f2 does not compile foochar f3 compilesis it valid,['c++'] +782282,how to generate laravel request in namespace path for laravel 5 i am familiar with the laravel artisan commandmakerequesthowever i cannot seem to get it to place it in a directory for example i have a directory structure apphttprequestsuser and i would like to place a request in that folder namespaced appropriately but php artisan makerequest usercreateuserrequest does not work,['php'] +782290,what does the exclamation mark mean for a swift initializer i have seen code like this that xcode created from objectivec initializersinitlogmsg string level loglevel ddloglevel flag logflag ddlogflag context logcontext int32 file unsafepointerint8 function unsafepointerint8 line int32 tag anyobject options optionsmask ddlogmessageoptionsinitlogmsg string level loglevel ddloglevel flag logflag ddlogflag context logcontext int32 file unsafepointerint8 function unsafepointerint8 line int32 tag anyobject options optionsmask ddlogmessageoptions timestamp atimestamp nsdatethe original code is instancetypeinitwithlogmsgnsstring logmsg levelddloglevelloglevel flagddlogflaglogflag contextintlogcontext fileconst char file functionconst char function lineintline tagidtag optionsddlogmessageoptionsoptionsmask instancetypeinitwithlogmsgnsstring logmsg levelddloglevelloglevel flagddlogflaglogflag contextintlogcontext fileconst char file functionconst char function lineintline tagidtag optionsddlogmessageoptionsoptionsmask timestampnsdate atimestampwhat does the exclamation mark mean after the init keyword,['objective-c'] +782385,appcompat show progress in action bar causes npe after updating my sdk to all the latest android 50 goodies i cannot use progress bars built into the actionbar in appcompat i have done all the usual fixed move supportrequestwindowfeature call to before setcontent and before super call in oncreate but nothing works here is what i am doingpublic class loginactivity extends actionbaractivity protected void oncreatebundle savedinstancestate supportrequestwindowfeaturewindowfeature indeterminate progress superoncreatesavedinstancestate setcontentviewrlayoutlogin loginbuttonsetonclicklistenernew viewonclicklistener override public void onclickview v setsupportprogressbarindeterminatevisibilitytrue and the stack trace1018 193821053 eandroidruntime11206 javalangnullpointerexception attempt to invoke virtual method void androidsupportv7internalwidgetprogressbarcompatsetvisibilityint on a null object reference1018 193821053 eandroidruntime11206 at androidsupportv7appactionbaractivitydelegatebaseupdateprogressbarsactionbaractivitydelegatebasejava7861018 193821053 eandroidruntime11206 at androidsupportv7appactionbaractivitydelegatebasesetsupportprogressbarindeterminatevisibilityactionbaractivitydelegatebasejava6921018 193821053 eandroidruntime11206 at androidsupportv7appactionbaractivitysetsupportprogressbarindeterminatevisibilityactionbaractivityjava3271018 193821053 eandroidruntime11206 at commyapackageloginactivity2onclickloginactivityjava82this is on a nexus 5 running android 4 the app theme inherits from themeappcompat the app is built with android 50 and targetsdk is 21 when i use setsupportprogress for a normal horizontal progress bar the same thing happens any help much appreciatededitfound the problem in androidsupportv7internalwidgettoolbarwidgetwrapperoverridepublic void initindeterminateprogress logitag progress thisplay unsupportedmaybe not a bug but a feature toolbars seem to be the new actionbarsi have a copy of v20 appcompat on another computer so i am going back to that,['android'] +782420,javalangclassnotfoundexception orgglassfishjerseyservletservletcontainer you may feel this is a duplicated question but none of the questions with the same title solve my problems i am using jersey 20 creating a restful web service in eclipse i use tomcat 70 as my server i have the following webxmlxml version10 encodingutf8webapp xmlnsxsi xmlns xsischemalocation 2 5xsd version25 servlet servletnamejaxrs servletservletname servletclassorgglassfishjerseyservletservletcontainerservletclass initparam paramnamejerseyconfigserverproviderpackagesparamname paramvaluecomshopdomainparamvalue initparam loadonstartup1loadonstartup servlet servletmapping servletnamejaxrs servletservletname urlpatternjaxrsurlpattern servletmappingwebappi have a simple class called hellopathcustomerspublic class hello get producesmediatypetext plain public string getcustomer return hello i have a jersey library called jerseyevery time i ran this project i got error ofjavalangclassnotfoundexception orgglassfishjerseyservletservletcontainerany ideas,['java'] +782488,android gradle project upgrading build tools to 2101 aapt throws exception we have an android gradle project today i wanted to upgrade the android build tools version from 20 to 2101 but now the aapt is failing what went wrongexecution failed for task myprojectandroidprocessdebugresources comandroididecommoninternalloggederrorexception failed to run command c developandroidsdksdkbuildtools2101aaptexe package f nocrunch i c developandroidsdksdkplatformsandroid16androidjar m d my projecttrunkmyproject bingradlebuildreleasemyprojectandroidintermediatesmanifestsfulldebugandroidmanifestxml s d my projecttrunkmyproject bingradlebuildreleasemyprojectandroidintermediatesresdebug a d my projecttrunkmyproject bingradlebuildreleasemyprojectandroidintermediatesassetsdebug m j d my projecttrunkmyproject bingradlebuildreleasemyprojectandroidgeneratedsourcerdebug f d pivoscore p4trunkmyproject bingradlebuildreleasemyprojectandroidintermediatesresresourcesdebugap debugmode custompackage commyprojectapp 0 apk outputtextsymbols d my projecttrunkmyproject bingradlebuildreleasemyprojectandroidintermediatessymbolsdebugerror code 255i had some warnings sayinglibpng warning iccp not recognizing known srgb profile that has been editedi fixed those but there are 6 more in the appcompatv7 libraryif i revert the build tools version to 20 everything works finehas anyone came across this problem,['android'] +782494,androidsupportv7widgettoolbar icon alignment issue using the new android 50 toolbar approach and following the google io example i am setting a navigation icon and a spinner in the toolbarthe issue is the navigation icon is bottomaligned i cannot find any reason why this is happeningnote that i deliberately set it to a solid square to see the alignment issue more clearlymy code is as followstoolbarxmlandroidsupportv7widgettoolbar xmlnsandroid xmlnsapp appthemestyleactionbarthemeoverlay apopupthemestyleactionbarpopupthemeoverlay androidididtoolbar actionbar androidlayout widthmatch parent androidlayout heightandroidactionbarsize main stylestyle nameactionbarthemeoverlay parent item nameandroidbackgroundcolorappmaincoloritem item nameandroidtextcolorprimaryfitem item namecolorcontrolnormalfitem item namecolorcontrolhighlight3fitemstyleactivitymaingetsupportactionbarsetthisplayhomeasupenabledtrueif mactionbartoolbar null mactionbartoolbarsetnavigationiconrdrawableic drawer,['android'] +782506,patching sshuttles firewallpy ipfw to pf has anyone fixed firewallpy for sshuttle to use pf instead of ipfw for the yosemite 1010 update i have looked around for a fix but nothing seems to be available yet i am more of rails guy and do not know python too well besides being able to make a little sense of it i do not know where to begin with making this change and hoping the community could help or hoping someone has a fork already fixed,['python'] +782514,generic injectd fields in an abstract superclass consider a mvpish set of types an abstract presenter exists with a view interfacepublic interface view public abstract class abstractpresenterv extends view inject v view then lets have a specific concrete presenter subclass with its view interface and implementationpublic interface loginview extends view public loginpresenter extends abstractpresenterloginview public class loginviewimpl implements loginview in a dagger module of course we would define a provides methodprovidesloginview provideloginview return new loginviewimplin guice you could write this the same way or just bindloginviewclasstologinviewimplclasshowever in dagger both v1 and the 20snapshot from google this produces an error since it cannot figure out what v is when creating the binding wiring for abstractpresenterv on the other hand guice figures out that that because it is actually creating a loginpresenter so it needs an implementation of loginview dagger 122foobarabstractpresenterinjectadapterjava2131 cannot find symbol symbol class v location class foobarabstractpresenterinjectadapterdagger 20snapshotcaused by javalangillegalargumentexception v at daggerinternalcodegenwritertypenames2defaultactiontypenamesjava39 at daggerinternalcodegenwritertypenames2defaultactiontypenamesjava36 at javaxlangmodelutilsimpletypevisitor6visittypevariablesimpletypevisitor6java179 at comsuntoolsjavaccodetypetypevaraccepttypejava1052 at daggerinternalcodegenwritertypenamesfortypemirrortypenamesjava36 at daggerinternalcodegenmembersinjectorgeneratorwritemembersinjectorgeneratorjava142 at daggerinternalcodegenmembersinjectorgeneratorwritemembersinjectorgeneratorjava61 at daggerinternalcodegensourcefilegeneratorgeneratesourcefilegeneratorjava53 at daggerinternalcodegeninjectbindingregistrygeneratesourcesforrequiredbindingsinjectbindingregistryjava101 at daggerinternalcodegencomponentprocessorprocesscomponentprocessorjava149my question is this a bug is this a missing feature or is this a performance issue that dagger is protecting us from a la serializabletypeoraclebuilder in gwt rpcnote that this same issue occurs when v is referred to as providerv lazyv etc,['java'] +782622,osx 1010 and eclipse luna own app crashes when started from inside eclipse i have updated to yosemite today and have much problems with java most java applications crashes on start but after reinstall of the old macjava 16 that problem seems to be solved but i have an other big problem when i start eclipse luna and build my own java application and start this application with the run button in eclipse it crashes with the following reportdyld lazy symbol binding failed symbol not found cgcontextsetallowsacceleration referenced from libraryjavajavavirtualmachines160 35b10428jdkcontentslibrarieslibawtjnilib expected in systemlibraryframeworksapplicationservicesframeworkversionsaapplicationservicesdyld symbol not found cgcontextsetallowsacceleration referenced from libraryjavajavavirtualmachines160 35b10428jdkcontentslibrarieslibawtjnilib expected in systemlibraryframeworksapplicationservicesframeworkversionsaapplicationserviceswhen i export the app as jar file and start it from outside eclipse eveything works finedo you have any solution how i can fix this otherwise i must reinstall mavericks to be productive tomorrow,['java'] +782662,web api 2 sample not available i am trying to auto generate the help docs for my web apihowever i see on one particular method a sample request could not be generated as shown in the picturebelow are the arguments request parameterswhy is it unable to generate a sample request format,['asp.net'] +782667,why should javas valuebased classes not be serialized since version 8 java has the concept of valuebased classes this is in preparation of a future version which will most likely allow the definition of value types both definitionsdescriptions mention serialization bold face added by meabout the existing valuebased classesa program may produce unpredictable results if it attempts to thistinguish two references to equal values of a valuebased class whether directly via reference equality or indirectly via an appeal to synchronization identity hashing serialization or any other identitysensitive mechanismabout future value typesthe default identitybased hash code for object available via systemidentityhashcode also does not apply to value types internal operations like serialization which make identitybased thistinctions of objects would either not apply to values as they do not apply to primitives or else they would use the valuebased thistinction supplied by the value typeas hashcode methodbecause future jvm implementations might not use object headers and reference pointers for valuebased classes some of the limitations are clear eg not locking on an identity which the jvm must not uphold a reference on which is locked could be removed and replaced by another later which makes releasing the lock pointless and will cause deadlocksbut i do not get how serialization plays into this why is it considered an identitysensitive mechanism why does it make identitybased thistinctions of objects,['java'] +782701,qt movetothread what resources are brought with the object say i have created a qobject a and it has a member qobject b actually both a and b are subclasses of qobject and class a has a member b bwhen b is created its parent is 0 default in the code if i never set bs parent to a and if i call movetothread to move a into a worker thread will b be moved into that thread tooif it is not moved if i call binit from the worker thread the one i moved a into which use new operator to create another qobject that has b as a parent then i will get the following error rightqobject cannot create children for a parent that is in a different thread,['c++'] +782745,get localhost running on mac os x yosemite i have updated my os to yosemite and the only issue i have is that my localhost is not working anymore please excuse if the questions sounds dumb but i have limited knowledge about serverswith mavericks i was able to use localhost and customdomaindev right after a system start also my mysql server has been started without any actionsnow google chrome throws an err connection refused error when using localhosti runapachectl configtestwhich returnshttpd syntax error on line 58 of privateetcapache2httpdconf cannot load libexecapache2mod authn defaultso into server dlopenusrlibexecapache2mod authn defaultso 10 image not foundif i comment out this line it continues with other modules when i comment out all modules which causes this syntax error i getah00526 syntax error on line 131 of privateetcapache2httpdconfinvalid command user perhaps misspelled or defined by a module not included in the server configurationi am using the httpdconf file from mavericks where everything worked finei have no idea what i should do next,"['php', 'mysql']" +782810,how to make iphone vibrate using swift i need to make the iphone vibrate but i do not know how to do that in swift i know that in objectivec you just writeimport audiotoolbox audioservicesplayalertsoundksystemsoundid vibratebut that is not working for me,['iphone'] +782833,what does asm volatile do in c i looked into some c code from they use stuff like inline asm etc like the followingcode1static inline tick gettick void unsigned a d asm volatile rdtsc a a d d return ticka tickd 32code2volatile int attribute noinline foo2 int a0 int a1 asm volatile i was wondering what does the code1 and code2 do,['c'] +782949,how can i analyze a heap dump in intellij memory leak i have generated a heap dump from my java application which has been running for some days with the jmap tool this results in a large binary heap dump filehow can i perform memory analysis of this heap dump within intellij ideai know that there are tools for eclipse and netbeans but i would rather use idea if possiblethe basic results of the analysis would tell me the number of instances of each object in memory perclass to allow me to be able to start debugging memory leaks,['java'] +783052,why is it not possible to get local variable names using reflection if i have a code like thispublic class program public static void main string bar int foo 24 i can get the local variables declared in main usingvar flag bindingflagsstatic bindingflagspublicvar fields typeofprogramgetmethodmain flagsgetmethodbodylocalvariablesthis returns a ilistlocalvariableinfo and the localvariableinfo has only three properties ispinnedlocalindex and localtypeso there is no name property existswhat i am wondering is that you can see the variable names in the generated il codemethod public hidebysig static void main cil managed entrypoint code size 11 0xb maxstack 1 locals init 0 string bar 1 int32 foo il 0 nop il 01 ldstr il 06 stloc0 il 07 ldci4s 24 il 09 stloc1 il 0a ret end of method programmainbut it is not possible to get them using reflectionis it because local variables do not have a name and they are only accessed by their indices if so how the ildasmexe shows the names or because such feature is not implemented or if it is possible using another way then the question would be hownote i have seen some questions like this and most of them is using expressions to get variable name it does not work if i would like to get all locals including temporary variables that generated by the compiler,['c#'] +783234,subtask execution without explicit definition does anyone have a solution for automatically running subtasks in gulpi am new to gulp and currently structure my gulp file like thisgulptaskbuildccss functioncb gulptaskbuildjs functioncb gulptaskbuildimg functioncb gulptaskbuildindex functioncb and then i explicitly define the base task and have it execute the subtasksgulptaskbuild buildscss buildjs buildimg buildindexi use this structure for several groups of tasks cleaning building lintingi am curious if someone has a solution for automatically executing subtasks when the base task is run without creating an explicit definition as i have,['javascript'] +783473,concurrent stdcall once calls could please someone explain me why both of the threads in this program when compiled using the compilers shipped with visual studio 20122013 are blocked until both stdcall once calls are executed another visual studio bug given that it behaves as expected when compiled with gcc can someone please come up with a workaround imagine all the pain i have been through to narrow the problem down and please be mercifulinclude chronoinclude iostreaminclude mutexinclude threadnamespace stdonce flag did nothing void do nothing void sleep shorter and do nothing once stdthis threadsleep forstdchronoseconds3 stdcout 1n stdcall oncedid nothing do nothing stdcout 2n stdonce flag sleeped longer void sleep longer stdthis threadsleep forstdchronoseconds10 void sleep longer once stdcout 3n stdcall oncesleeped longer sleep longer stdcout 4n int main stdthread t1sleep shorter and do nothing once stdthread t2sleep longer once t1join t2join return 0to elaborate it behaves as expected when compiled using gccprints 3waits 3 secondsprints 1immediately prints 2waits another 67 secondsand prints 4when compiled using the compilers shipped with visual studio 20122013 it behaves like thisprints 3waits 3 secondsprints 1waits another 67 secondsand only then immediately prints 2 and 4clearly it is a misbehavior or is not itupdate i cannot submit this as a visual studio bug because my work account is for some reason not authorized to submit feedback for this connection whatever this means i have got a reply from the microsoft stl maintainer saying he will hopefully investigate the issue at some time in the future,['c++'] +783495,recyclerview crashes when scrapped or attached views may not be recycled i am using a simple implementation of recyclerview taken from the android website using a staggeredgridlayoutmanager and i keep getting this error that crashes my app javalangillegalargumentexception scrapped or attached views may not be recycled isscrapfalse isattachedtrue at androidsupportv7widgetrecyclerviewrecyclerrecycleviewholderinternalrecyclerviewjava3501 at androidsupportv7widgetrecyclerviewlayoutmanagerscraporrecycleviewrecyclerviewjava5355 at androidsupportv7widgetrecyclerviewlayoutmanagerdetachandscrapattachedviewsrecyclerviewjava5340 at androidsupportv7widgetstaggeredgridlayoutmanageronlayoutchildrenstaggeredgridlayoutmanagerjava572 at androidsupportv7widgetrecyclerviewthispatchlayoutrecyclerviewjava1918 at androidsupportv7widgetrecyclerviewonlayoutrecyclerviewjava2155 at androidviewviewlayoutviewjava14008 at androidviewviewgrouplayoutviewgroupjava4373 at androidwidgetrelativelayoutonlayoutrelativelayoutjava1021 at androidviewviewlayoutviewjava14008 at androidviewviewgrouplayoutviewgroupjava4373 at androidwidgetframelayoutonlayoutframelayoutjava448 at androidviewviewlayoutviewjava14008 at androidviewviewgrouplayoutviewgroupjava4373 at androidwidgetframelayoutonlayoutframelayoutjava448 at androidviewviewlayoutviewjava14008 at androidviewviewgrouplayoutviewgroupjava4373 at androidsupportv7internalwidgetactionbaroverlaylayoutonlayoutactionbaroverlaylayoutjava502 at androidviewviewlayoutviewjava14008 at androidviewviewgrouplayoutviewgroupjava4373 at androidwidgetframelayoutonlayoutframelayoutjava448 at androidviewviewlayoutviewjava14008 at androidviewviewgrouplayoutviewgroupjava4373 at androidwidgetlinearlayoutsetchildframelinearlayoutjava1663 at androidwidgetlinearlayoutlayoutverticallinearlayoutjava1521 at androidwidgetlinearlayoutonlayoutlinearlayoutjava1434 at androidviewviewlayoutviewjava14008 at androidviewviewgrouplayoutviewgroupjava4373 at androidwidgetframelayoutonlayoutframelayoutjava448 at androidviewviewlayoutviewjava14008 at androidviewviewgrouplayoutviewgroupjava4373 at androidviewviewrootimplperformlayoutviewrootimpljava1892 at androidviewviewrootimplperformtraversalsviewrootimpljava1711 at androidviewviewrootimpldotraversalviewrootimpljava989 at androidviewviewrootimpltraversalrunnablerunviewrootimpljava4351 at androidviewchoreographercallbackrecordrunchoreographerjava749 at androidviewchoreographerdocallbackschoreographerjava562 at androidviewchoreographerdoframechoreographerjava532 at androidviewchoreographerframethisplayeventreceiverrunchoreographerjava735 at androidoshandlerhandlecallbackhandlerjava725 at androidoshandlerthispatchmessagehandlerjava92 at androidoslooperlooplooperjava137 at androidappactivitythreadmainactivitythreadjava5041 at javalangreflectmethodinvokenativenative method at javalangreflectmethodinvokemethodjava511 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava793 at comandroidinternaloszygoteinitmainzygoteinitjava560 at dalviksystemnativestartmainnative method by simple i literally mean it is the same implementation taken from this page on their website the only difference being is that my grid items layout is an imageview and a couple of textviews so i would not bother reposting my codeanyone else getting this error and know how to deal with it,['android'] +783501,change android 50 actionbar color i am working with the new lollipop material design guidelines and would like to incorporate that nifty navigation drawer animation in my app i have gotten that far by using the androidsupportv7appactionbardrawertoggle but now i am having difficulty changing the color of said action bar it stays bright gray no matter what i set the theme to how would one go about changing the color of the actionbar this is what my app theme looks likeresvaluesstylesxmlstyle nameapptheme parentstylethemeappcompatlightdarkactionbar item nameandroidactionbarstylestyleactionbaritem item nameandroidcolorprimarycolorprimarydefitem item nameandroidcolorprimarydarkcolorprimarydarkdefitem item nameandroidactivatedbackgroundindicatordrawabledefbgitem item nameandroidcoloraccentcolorprimarydefitem item nameandroidnavigationbarcolorcolorprimarydarkdefitemstylestyle nameactionbar parentandroidwidgetactionbar item nameandroidbackgroundcolorprimarydefitemstyle,['android'] +783507,converting linearsvcs decision function to probabilities scikit learn python i use linear svm from scikit learn linearsvc for binary classification problem i understand that linearsvc can give me the predicted labels and the decision scores but i wanted probability estimates confidence in the label i want to continue using linearsvc because of speed as compared to sklearnsvmsvc with linear kernel is it reasonable to use a logistic function to convert the decision scores to probabilities import sklearnsvm as suppmach fit modelsvmmodelsuppmachlinearsvcpenaltyl1c1predicted test svmmodelpredictx testpredicted test scores svmmodeldecision functionx test i want to check if it makes sense to obtain probability estimates simply as 1 1 expx where x is the decision score alternately are there other options wrt classifiers that i can use to do this efficiently thanks,['python'] +783564,expression tree getstring result i am trying to copy the behavior of entity framework in creating the query from expression and i found my way using expressionvisitor when getting the property of the model by using attribute this is what i got so far internal class nvisitor expressionvisitor private readonly parameterexpression parameter private readonly type type public nvisitortype type type type parameter expressionparametertype protected override expression visitparameterparameterexpression node return parameter protected override expression visitmembermemberexpression node if nodemembermembertype membertypesproperty var membername nodemembername propertyinfo othermember typegetpropertymembername var ncols nodemembergetcustomattributestypeofncolumn true if ncolsany var ncol ncolumnncolsfirst othermember typegetpropertyncolname var inner visitnodeexpression return expressionpropertyinner othermember return basevisitmembernode i have an attribute ncolumn that indicates the real name of the property from table column so i mark the property of the model by attribute public class bonustypex ncolumnbonustypename public string name get set now when im trying to get the expression testmethod public void expressiontesting2 string searchkey xmas expressionfuncbonustypex bool expression x xnamecontainssearchkey type t typeoftbl bonustype var body new nvisitortvisitexpressionbody string a stringjoin bodytostringsplitskip1 assertareequalbonustypenamecontainsxmas a i got this bonustypenamecontainsvaluepayrolltestadministrationtestrepositoriesc thisplayclass13searchkeywhat i am expecting to get is bonustypenamecontainsxmasis there any method that gets the expression string i am using string a stringjoin bodytostringsplitskip1which i think it might be wrong any help would be appreciated,['c#'] +783632,actionbar styling after updating to android lollipop i was developing custom actionbar by selecting api19 yesterday today i updated support libraries and project to api21 with cause me into problem in my actionbar there is a menutoarrow button with i do not need and style of actionbar changesbefore updateafter updatefollowing is the stylexmlresources style nameappbasetheme parentthemeappcompatlightdarkactionbar style base application theme style nameapptheme parentappbasetheme item nameandroidbuttonstylestylebuttonappthemeitem item nameactionbaritembackgrounddrawableselectable background appthemeitem item namepopupmenustylestylepopupmenuappthemeitem item namedropdownlistviewstylestyledropdownlistviewappthemeitem item nameactionbartabstylestyleactionbartabstyleappthemeitem item nameactiondropdownstylestyledropdownnavappthemeitem item nameactionbarstylestyleactionbarsolidappthemeitem item nameactionmodebackgrounddrawablecab background top appthemeitem item nameactionmodesplitbackgrounddrawablecab background bottom appthemeitem item nameactionmodeclosebuttonstylestyleactionbuttonclosemodeappthemeitem lightdarkactionbar specific item nameactionbarwidgetthemestylethemeappthemewidgetitem style base application theme for full screen activities style nameappthemefullscreen parentandroidstylethemelightnotitlebarfullscreen item nameandroidbuttonstylestylebuttonappthemeitem style button style style namebuttonapptheme parentandroidwidgetbutton item nameandroidbackgrounddrawablebtn backgrounditem item nameandroidminheight48dipitem item nameandroidminwidth64dipitem item nameandroidtextcolorcolorbtn text color defaultitem style style nameactionbarsolidapptheme parentstylewidgetappcompatlightactionbarsolidinverse item namebackgrounddrawableab solid appthemeitem item namebackgroundstackeddrawableab stacked solid appthemeitem item namebackgroundsplitdrawableab bottom solid appthemeitem item nameprogressbarstylestyleprogressbarappthemeitem style style nameactionbartransparentapptheme parentstylewidgetappcompatactionbar item namebackgrounddrawableab transparent appthemeitem item nameprogressbarstylestyleprogressbarappthemeitem style style namepopupmenuapptheme parentstylewidgetappcompatpopupmenu item nameandroidpopupbackgrounddrawablemenu dropdown panel appthemeitem style style namedropdownlistviewapptheme parentstylewidgetappcompatlistviewdropdown item nameandroidlistselectordrawableselectable background appthemeitem style style nameactionbartabstyleapptheme parentstylewidgetappcompatactionbartabview item nameandroidbackgrounddrawabletab indicator ab appthemeitem style style namedropdownnavapptheme parentstylewidgetappcompatspinnerdropdownactionbar item nameandroidbackgrounddrawablespinner background ab appthemeitem item nameandroidpopupbackgrounddrawablemenu dropdown panel appthemeitem item nameandroiddropdownselectordrawableselectable background appthemeitem style style nameprogressbarapptheme parentstylewidgetappcompatprogressbarhorizontal item nameandroidprogressdrawabledrawableprogress horizontal appthemeitem style style nameactionbuttonclosemodeapptheme parentstylewidgetappcompatactionbuttonclosemode item nameandroidbackgrounddrawablebtn cab done appthemeitem style this style is only referenced in a lightdarkactionbar based theme style namethemeappthemewidget parentstylethemeappcompat item namepopupmenustylestylepopupmenuappthemeitem item namedropdownlistviewstylestyledropdownlistviewappthemeitem styleresourcesoncreate from mainactivityoverrideprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main mnavigationdrawerfragment navigationdrawerfragment getsupportfragmentmanagerfindfragmentbyidridnavigation drawer mtitle gettitle set up the drawer mnavigationdrawerfragmentsetup ridnavigation drawer drawerlayout findviewbyidriddrawer layout actionbar getsupportactionbar toolbar toolbar toolbar findviewbyidridtoolbar setsupportactionbartoolbar layoutinflater minflater layoutinflaterfromthis layoutparams layout new layoutparams layoutparamsmatch parent layoutparamsmatch parent view mcustomview minflaterinflaterlayoutactionbar null actionbarsetcustomviewmcustomviewlayout actionbarsetthisplayshowcustomenabledtrue actionbarsetthisplayshowhomeenabledfalse actionbarsetthisplayshowtitleenabledfalse actionbarsetdefaultthisplayhomeasupenabledfalse actionbarsetthisplayuselogoenabledfalseany solution to restore actionbar like previously using latest sdkupdate i am able to remove arrow from actionbar by deleting actionbardrawertoggle from everywhere in my drawerfragmentnow i am facing only styling issue of actionbar padding on left and background color of actionabr,['android'] +783782,android 50 material design tabs what is the best and easy way to implement material design style tabs just like in the latest google newsstand app that is exactly what i am looking for but do not know where to start any helpdirection provided is greatly appreciated thanks,['android'] +783805,in android app toolbarsettitle method has no effect a application name is shown as title i am trying to create simple application using androidsupportv721 librarycode snippetsmainactivityjavapublic class mainactivity extends actionbaractivity toolbar mactionbartoolbar override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main mactionbartoolbar toolbar findviewbyidridtoolbar actionbar mactionbartoolbarsettitlemy title setsupportactionbarmactionbartoolbaractivity mainxmllinearlayout xmlnsandroid xmlnstools androidlayout widthmatch parent androidlayout heightmatch parent androidfitssystemwindowstrue androidorientationvertical androidsupportv7widgettoolbar androidididtoolbar actionbar androidbackgroundnull androidlayout widthmatch parent androidlayout heightactionbarsize androidfitssystemwindowstrue linearlayoutbut instead of my title on toolbar application name is shownseems like settitle method has no effecti would like to show my titleupdbefore stylesxml wasstyle nameapptheme parentthemeappcompat item namewindowactionbarfalseitemstyleso i thought that actionbar is not usedi add noactionbar to style parentstyle nameapptheme parentthemeappcompatnoactionbar item namewindowactionbarfalseitemstylebut the problem is not resolvedany help is very appreciated,['android'] +783818,xcode 6xios 8 hides status bar in landscape orientation application build with xcode 6x automatically hides the status bar in landscape orientation iphone the same application when compiled with xcode 5x does not do thathow can i prevent the application from hiding the status bar in landscape orientation basically how can i thisable this super awesome feature that applexcode has shoved down my throatps i have tried updating the view controllers with the following code but it does not help boolprefersstatusbarhidden return no,"['ios', 'iphone']" +783839,android 50lollipop force rescan of systemprivapp in android 4x it was enough to put an apkfile into systemprivapp and the packagemanager recognized that new file and uninstalled the corresponding application or servicesince android l it seems to be not enough to just put the file into that directory a reboot of the system is required to force android to recognize that changehas anyone an idea how to circumvent this maybe with any setprop ctlrestart x or by killing a dedicated serviceedithere are some logs from logcat1 move apk from system to systemprivapp installationsumount o remount rw systemcd systemprivappmv aarscserviceapk move from system to systemprivappwmv 3268 type1400 audit0053 avc denied rename for nameaarscserviceapk devmmcblk0p22 ino23041 scontexturinits0 tcontextuobject rsystem files0 tclassfilebut file has been moved as the current rootimplementation for nexus 7 android android l p2 thisables selinux for the rootcommands apk not loaded and not listed in applist not as expected apk is going to be automatically installed once put into privapp folder on android 442 reboot device having apk inside systemprivapprebootipackagemanager 567 systemprivappaarscserviceapk changed collecting certs apk is loaded and listed in applist as expected3 move apk from systemprivapp to system deinstallationsumount o remount rw systemcd systemprivappmv aarscserviceapk move from systemprivapp to systemwmv 3189 type1400 audit0031 avc denied rename for nameaarscserviceapk devmmcblk0p22 ino23041 scontexturinits0 tcontextuobject rsystem files0 tclassfilebut file has been moved as the current rootimplementation for nexus 7 android android l p2 thisables selinux for the rootcommands apk still loaded and listed inside applist service inside app can still be bound from another app not as expected apk is going to be automatically uninstalled once removed from privapp folder on android 4 reboot device having apk not inside systemprivappreboot wpackagemanager 570 system package euairaudioaarscservice no longer exists wiping its data apk is no more loaded and no more listed in applist as expectededit 2there is the same behaviour on unrooted android l 21 emulator sure without the selinuxwarningbut the apk is also just uninstalled after reboot kill zygote,['android'] +783864,how can i trust casting from double to integer i have been working on some simple code for creating histograms and found that following codedouble value 12double bucketsize 04double bucketid value bucketsizestdcout bucketid as double bucketid stdendlstdcout bucketid as int intbucketid stdendlresults in crazy output ofbucketid as double 3bucketid as int 2which basically ruins my trust in computers when looking for the right bucketid for the value while creating a histogrami know that there are rounding errors etc but is there any general solution to that problem just in case please do not suggest adding 05 to result of the division before casting to int as apparently it does not work very well in some cases eg double value 3 double bucketsize 2thanks in advance,['c++'] +783880,rethis stack exchange how to delete or get keys by pattern i installed stack exchange rethis client in ci can only delete one key or array of keys but i do not know how to delete keys with prefixor another solution can be first get all keys by pattern and then delete them but i do not know how to get keys by pattern too,['c#'] +783886,zoom vs scale in css3 i was looking for some css properties that i never used and came to know about zoom property of css3what is the similarities and difference between themwhen to use zoom and when scale both does pretty much same jobwhich is more efficient to use and whywhat have i noticedboth scales the object but default transformorigin for scale its center and for zoom its topleft i thinkwhen we use them for scaling on hover zoom will scale and again shrinks to the original dimention while scale will only shrink on hoverout jsfiddle showing hover effectst webkittransitionduration 03smoztransitionduration 03smstransitionduration 03sotransitionduration 03stransitionduration 03sbox box2 thisplay inlineblock width 100px height 100px margin 20pxbox background b00boxhover zoom 11box2 background 00bbox2hover webkittransform scale11moztransform scale11mstransform scale11otransform scale11transform scale11boxboxbox2box2some stackoverflow qawhat does zoom do in csszoom versus transform scalediv thisplay inlineblock height 50px width 50px position absoluteone top 10px left 10px background 07a webkittransform scale2 moztransform scale2 mstransform scale2 otransform scale2 transform scale2 transformorigin top lefttwo top 10px left 100px background e zoom 200div classonedivdiv classtwodiv,['css'] +784045,remove tab bar item text show only image simple question how can i remove the tab bar item text and show only the image i want the bar items to like in the instagram appin the inspector in xcode 6 i remove the title and choose a 2x 50px and a 3x 75px image however the image does not use the free space of the removed text any ideas how to achieve the same tab bar item image like in the instagram app,['ios'] +784087,android emulator with haxm freezes on mac os yosemite has anyone else faced an issue after updrading mac os x to 1010 android emulator without haxm runs now very very slow and the one with haxm enabled freezes after couple second of iteration with some app also cpu goes mad until i kill an emulator instanceany help or advice would be very appreciated im struggling with this whole day alreadythanks,['android'] +784222,responsive bootstrap datatable not collapsing columns at the correct point i am using datatablesnet latest with datatables and bootstrap i suppose my question is what does datatables responsive bootstrap use to detect overflow because it clearly is not the parent widthhere is my resultit is a pretty straight forward problem if i reduce the width of my window 1 more pixel the column will finally collapse if i then expand it it returns to this state i would like to prevent overflow from the parent bootstrap panel i have removed the bootstrap grid divs rowcolxs12 etc to eliminate potitial problems but once this is resolved or i better understand the problem i intend to utilize the bootstrap grid system as well here is a plunkr that perfectly replicated the problem collapse the run viewdoctype htmlhtmlhead titletables pixeladmintitle link relstylesheet href link relstylesheet href link relstylesheet href style body fontsize 140 tabledatatable th tabledatatable td whitespace nowrap styleheadbody stylepaddingtop 40pxdiv classpanel panelprimary stylemargin 51px padding 0 div classpanelheading h3 classpaneltitlepanel titleh3 div div classpanelbody stylepadding 0 div stylewidth 100 border 1px solid red table idexample classtable tablestriped tablehover dtresponsive cellspacing0 width100 thead tr thnameth thpositionth thofficeth thextnth thstart dateth thsalaryth tr thead table div divdivscript srccodejquerycomjquery1minjsscriptscript typetextjavascript languagejavascript srccdndatatablesnet1103jsjquerydatatablesminjsscriptscript typetextjavascript languagejavascript srccdndatatablesnetresponsive102jsdatatablesresponsivejsscriptscript typetextjavascript languagejavascript srccdndatatablesnetpluginsa5734b29083integrationbootstrap3datatablesbootstrapjsscriptscript documentreadyfunction example datatable responsive true ajax datajson scriptbodyhtml,['jquery'] +784230,why do generator expressions and dictset comprehensions in python 2 use a nested function unlike list comprehensions list comprehensions have their code placed directly in the function where they are used like this thisthislambda a for b in c 1 0 build list 0 3 load global 0 c 6 get iter 7 for iter 12 to 22 10 store fast 0 b 13 load global 1 a 16 list append 2 19 jump absolute 7 22 return value whereas generator expressions and dictset comprehensions are mostly placed in a separate nested function like this thisthislambda a for b in c 1 0 load const 1 code object setcomp at 0x7ff41a3d59b0 file stdin line 1 3 make function 0 6 load global 0 c 9 get iter 10 call function 1 13 return value thisthislambda a for b in cfunc codeco consts1 1 0 build set 0 3 load fast 0 0 6 for iter 12 to 21 9 store fast 1 b 12 load global 0 a 15 set add 2 18 jump absolute 6 21 return value in python 3 all of these are placed in a nested functionwhy is the code placed in a separate nested function i vaguely remember reading something about people wanting to fix comprehension andor genexpr variables spilling to the surrounding scope a long time ago was this the fix for that or somethingwhy are list comprehensions implemented differently from the rest in python 2 because of backwards compatibility i thought i heard the talk about spillage fixing a lot after generator expressions were introduced though but i might have just been reading really old thiscussions or something,['python'] +784245,nsstreamdelegate not receiving nsstreameventhasspaceavailable i had my code working in another project in a class with the following signatureclass viewcontroller uiviewcontroller nsstreamdelegate uitextfielddelegate then i moved the connection to it is own class so i can potentially reuse it in each connectionclass xmppconnection nsobject nsstreamdelegatewhen i did this i moved all the viewdidload code into init i also tried putting that init code in a separate function and calling that function after instantiating the class that did not change anything i can switch between the 2 projects the old and new just to make sure that it is not a server problem and doing that confirms that it is notafter each run of the application the result is different it either does not call the hasspaceavailable and just sits there or there is a lldb error thrown on thread 1 in my class class appdelegate uiresponder uiapplicationdelegate fbloginviewdelegate that error may be related to facebook integration though but with lldb there is not much to look at however with each and every run hasspaceavailable is never called unlike the other projectheres the full code of the nsstreamdelegate so there is no confusion this class is a meant to be a fairly standard method of connection using xmpp protocol import uikitimport foundationclass xmppconnection nsobject nsstreamdelegate nsobject var input nsinputstream var output nsoutputstream let xmlstream string streamstream xmlnsstream version10 xmlnsjabberclient tomydomaincom xmllangen xmlnsxml let xmlstream string streamstream tomydomaincom xmlnsjabberclient xmlnsstream version10 var xmlauth string let xmlstreamend string streamstream let xmlresource string iq typeset idbind 1bind xmlnsurnietfparamsxmlnsxmppbindresourceonesideresourcebindiq let xmlsession string iq typeset idsess 1session xmlnsurnietfparamsxmlnsxmppsessioniq let xmlstarttls string starttls xmlnsurnietfparamsxmlnsxmpptls var messagestobesentstring var lastsentmessageid 0 var lastreceivedmessageid 0 initfacebookid string superinit let username should hash device id let password 123456 hash it var utf8authstr 0username0passworddatausingencodingnsutf8stringencoding let base64str utf8authstrbase64encodedstringwithoptionsnsdatabase64encodingoptionsfromraw0 xmlauth auth xmlnsurnietfparamsxmlnsxmppsasl mechanismplainbase64strauth printlnxmlauth selfconnecttosocketmydomaincom port 52 sendselfxmlstream sendselfxmlstarttls sendselfxmlauth sendselfxmlstream sendselfxmlresource sendselfxmlsession sendmessagehi func connecttosockethost string port int nsstreamgetstreamstohostwithnamehost port port inputstream selfinput outputstream selfoutput selfinputdelegate self selfoutputdelegate self selfinputscheduleinrunloopnsrunloopcurrentrunloop formode nsdefaultrunloopmode selfoutputscheduleinrunloopnsrunloopcurrentrunloop formode nsdefaultrunloopmode selfinputopen selfoutputopen printlnconnected let byteswritten selfoutputwriteunsafepointerdatabytes maxlength datalength printlnbyteswritten the delegate receives this message when a given event has occurred on a given stream func streamthestream nsstream handleevent streamevent nsstreamevent printlnmessage received switch streamevent case nsstreameventnone printlnnsstreameventnone case nsstreameventopencompleted printlnnsstreameventopencompleted case nsstreameventhasbytesavailable printlnnsstreameventhasbytesavailable if let inputstream thestream as nsinputstream printlnis nsinputstream if inputstreamhasbytesavailable printlnhasbytesavailable let buffersize 1024 var buffer arrayuint8count buffersize repeatedvalue 0 var bytesread int inputstreamreadbuffer maxlength buffersize printlnbytesread if bytesread 0 lastreceivedmessageid var output string nsstringbytes buffer length bytesread encoding nsutf8stringencoding printlnoutput is printlnoutput else printlnerror handle error case nsstreameventhasspaceavailable printlnnsstreameventhasspaceavailable sendnil send next item send next message or what if there is no next message to send and instead waiting user input case nsstreameventerroroccurred printlnnsstreameventerroroccurred case nsstreameventendencountered printlnnsstreameventendencountered default printlndefault func sendmessagestring if selfoutputhasspaceavailable stream ready for input printlntrue hasspaceavailable var datansdata var thismessagestring if message nil no message specified if messagestobesentcount 0 messages waiting to be sent thismessage messagestobesent0 data messagestobesent0datausingencodingnsutf8stringencoding allowlossyconversion false messagestobesentremoveatindex0 else no data to be sent no message specified and nothing to be sent return else thismessage message data messagedatausingencodingnsutf8stringencoding allowlossyconversion false printlnsent the following wait let byteswritten selfoutputwriteunsafepointerdatabytes maxlength datalength lastsentmessageid printlnthismessage printlnmessage sent to server and response is printlnbyteswritten int count else steam busy printlnno space available in stream if message nil messagestobesentappendmessage func sendmessagemessagestring fromstring tostring let xmlmessage message totomydomaincom fromfrommydomaincom typechat xmllangen bodymessagebodymessage sendxmlmessage func wait while true printlnwaiting if lastsentmessageid lastreceivedmessageid break nsrunloopcurrentrunlooprununtildatensdatetimeintervalsincenow 01 nsthreadsleepfortimeinterval01 so i can see 2 things that may have caused this either moving it into it is own class and making an instance of it or the change of inheritance thinking about the first possiblity i am looking into the threading lines of code selfinputscheduleinrunloopnsrunloopcurrentrunloop formode nsdefaultrunloopmodeafter checking the streamstatustoraw it says 1 which is nsstreamstatusopening i am not sure if this ever changes,['ios'] +784265,visual studio website is redirecting http to https when debugging i am having an issue with iis express or visual studio 2013the site has no https or ssl enabled or setup in the propertieswhen i click debug the site launches in the broswer and tries to load httplocalhost61488defaultaspxit then for some reason gets automatically redirected tohttpslocalhost61488defaultaspxand i then get an error code err ssl protocol error in chromeim not quite sure what to do,"['c#', 'asp.net']" +784328,create sidebar or vertical menu in vaadin how can i create a verticalmenu or sidebar in vaadin is there any specific component or have i do programatically and using cssi would like to create something like vaadin demoi am using the new valo theme,['css'] +784371,spinning effect anchor tag css3 helo guysi was trying to create a spinning hover effect with css3 just made a circle spinning effect check the jsfiddle here however what i want to do now is to create something tthat spins but this time its box typejust like this image so basically i want similar effect just like the jsfiddle i shown above however this time it must be box really having a hard time figuring this out heres my css body background 292929 paddingleft 30px fontsize 12pxtwist thisplay inlineblock fontsize 45px lineheight 90px cursor pointer margin 20px width 90px height 90px borderradius 50 textalign center position relative textdecoration none zindex 1 color ftwistafter pointerevents none position absolute width 100 height 100 borderradius 50 content webkitboxsizing contentbox mozboxsizing contentbox boxsizing contentboxtwistbefore speak none fontsize 48px lineheight 90px fontstyle normal fontweight normal fontvariant normal texttransform none thisplay block webkitfontsmoothing antialiased twistdemo4 width 92px height 92px boxshadow 0 0 0 4px rgba255 255 255 1twistdemo4before lineheight 92pxtwistdemo4after top 4px left 4px padding 0 zindex 10 border 4px dashed ftwistdemo4hover boxshadow 0 0 0 0 rgba255 255 255 0 color ftwistdemo4hover i color f twistdemo4spinhover webkittransition boxshadow 02s moztransition boxshadow 02s transition boxshadow 02stwistdemo4spinhoverafter webkitanimation spinaround 9s linear infinite mozanimation spinaround 9s linear infinite animation spinaround 9s linear infinitewebkitkeyframes spinaround from webkittransform rotate0deg to webkittransform rotate360deg mozkeyframes spinaround from moztransform rotate0deg to moztransform rotate360deg keyframes spinaround from transform rotate0deg to transform rotate360deg hope you can help me with a jsfiddle file thanks,"['html', 'css']" +784389,evaluate math equations from unsafe user input in python i have a website where the user enters math equations expressions and then those equations are evaluated against data constants provided by the website the math operations needed include symbols arithmetic operations min max and some other basic functions a sample equation could bemaxa b 100 a b 200one could simply eval this using python but as we all know this leads compromising the site what would be the safe approach of doing math equation evaluation what math equation parsing and evaluation engines there are for pythonif one chooses to use python itself to evaluate the expression are there any python sandboxes which would limit the python so that only user supplier operators and functions are available fullfledged python like defining functions should be totally thisabled subprocesses are ok see pypy sandbox specially for loops and other holes for exploiting memory and cpu usage should be closedany other approaches eg by using a command line binary bc,['python'] +784508,no actionbar in preferenceactivity after upgrade to support library v21 after i upgraded to the support library v21 my actionbar in my preferenceactivity is gonedid i miss some attributes in my theme to activate it again i had some similar trouble with a black actionbari also tried to add it a little hackish by adding a toolbar to the root layout but that did not work as expected,['android'] +784534,checksum error while provisioning android lollipop i get the message could not use the admin app due to a checksum error contact your it department when using the code below basically you have two android lollipop devices one device is unprovisioned factory reset and the other has this programming app on it the programming app sends an nfc command to the unprovisioned device to tell it to start provisioning using the data you pass to it there are three fields required apk location apk file checksum and package name as per devicepolicymanagermime type provisioning nfcthe apk is getting downloaded i am checking my server logs and it is clearly coming from the device androiddownloadmanager is in the user agentaccording to devicepolicymanagerextra provisioning device admin package checksum it is a sha1 checksum of the file the checksum is not matching i have tried many different formats of this checksum hex hex with spaces uppercaselowercase base64 text and i guess it is possible i missed a testunfortunately the android lollipop source is not yet available otherwise i would be checking therehow do i fix this any thoughtspublic class provisioneractivity extends activity implements createndefmessagecallback override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main nfcadapter mnfcadapter nfcadaptergetdefaultadapterthis mnfcadaptersetndefpushmessagecallbackthis this override public ndefmessage createndefmessagenfcevent event try properties p new properties psetpropertydevicepolicymanagerextra provisioning device admin package name comexampledeviceownertest psetpropertydevicepolicymanagerextra provisioning device admin package download location psetpropertydevicepolicymanagerextra provisioning device admin package checksum 19138948d8a607617971af724ffd08dd7eab771b bytearrayoutputstream bos new bytearrayoutputstream outputstream out new objectoutputstreambos pstoreout byte bytes bostobytearray ndefmessage msg new ndefmessagendefrecordcreatemimedevicepolicymanagermime type provisioning nfc bytes return msg catch exception e throw new runtimeexceptione note this is using the latest android l developer preview i guess it is entirely possible that this feature is not finished yetupdate actual release acts this way tooapk checksum fraasqdpsjp9nc5hkiuelpve4result using this url and this checksum gives an error and does not even get to the encrypt device screen i also posted two applications to github one sends the nfc data to provision the other is just an app to check if the app is device admin or device owner hopefully someone finds this useful youll need to modify the url and the checksum if you want to build deviceownercheck yourself,['android'] +784542,why is my object properly removed from a list when eq is not being called i have the following code which is making me scratch my head class element def init self name selfname name def repr self return selfnamedef eqself other printcomparing to formatselfname othername selfname othername return selfname othernameelement eq eqelements elementa elementb elementc elementd printbefore formatelementselementsremoveelements3printafter formatelementswhich yields the following output before a b c dcomparing a to d falsecomparing b to d falsecomparing c to d falseafter a b cwhy is not eq outputting comparing d to d truethe reason i am monkey patching eq instead of simply implementing it in my element class is because i am testing how monkey patching works before i implement it with one of the libraries i am using,['python'] +784543,how can i place a progressbar at the right of the toolbar with the new lollipop api we have to use a toolbar if we want to personalize the action bar aspectadding a progressbar to the toolbar is as simple as adding it to the toolbar viewgroup as chris banes saidandroidsupportv7widgettoolbar xmlnsandroid xmlnsapp androidididtoolbar androidlayout widthmatch parent androidlayout heightwrap content androidbackgroundcolormaterial green 500 androidminheightattractionbarsize apopupthemestylethemeoverlayappcompatlight appthemestylethemeoverlayappcompatdarkactionbar color is brown 500 progressbar androidididtoolbar progress bar androidlayout widthwrap content androidlayout heightwrap content androidindeterminatetint795548 androidindeterminatetintmodesrc inandroidsupportv7widgettoolbarbut how can we place it at the right of the toolbar where it belongsthe layout gravity attribute seems to not be defined for the toolbar setting it from the xml has no effecti tried to change the width of the progressbar with no successwhat do i doedit there is a programmatical solution to this problem see mdelolmo reply for that,['android'] +784553,porting gpuimage filter subclasses to swift i am trying to port an app from objectivec to swift but i am having problems with a subclass of gpuimagefilterin objc subclassing gpuimagefilter and using a different fragment shader was as easy as idinit nsstring fragmentshaderpathname nsbundle mainbundle pathforresourcetestshader oftypefsh nsstring fragmentshaderstring nsstring stringwithcontentsoffilefragmentshaderpathname encodingnsutf8stringencoding errornil if self super initwithfragmentshaderfromstringfragmentshaderstring return nil return selfi cannot figure out how to do this in swift this is my new initializeroverride init let fragmentshaderpathname nsbundlemainbundlepathforresourcetestshader oftype fsh let fragmentshaderstring nsstringcontentsoffile fragmentshaderpathname encoding nsutf8stringencoding error nil superinitfragmentshaderfromstring fragmentshaderstringas soon as this gets called the app crashes with this error messageuserspeterwunderdocumentsxcodewelpwelpgpuimagetestfilterswift 12 7 fatal error use of unimplemented initializer initvertexshaderfromstringfragmentshaderfromstring for class welpgpuimagetestfilterwhat am i doing wrong,"['ios', 'objective-c']" +784573,android lollipop add popup menu from title in toolbar i am unable to see how adding a popup menu from the title is accomplished like is shown in many of the material design examples any help would be much appreciated,['android'] +784611,usage of multidexapplication causes robolectric test for the application class to break adding multi dex support with the support v4r21 using gradle def apply plugin comandroidapplicationandroid compilesdkversion 19buildtoolsversion 20defaultconfig applicationid infoosommultidex minsdkversion 19 targetsdkversion 19 versioncode 1 versionname 10buildtypes release runproguard false proguardfiles getdefaultproguardfileproguardandroidtxt proguardrulespro dexoptions predexlibraries falseafterevaluate tasksmatching itnamestartswithdex each dx if dxadditionalparameters null dxadditionalparameters dxadditionalparameters multidex dxadditionalparameters maindexlistprojectdirmultidexkeeptostringnow this works for the app itself and i am able to build and deploy but when i run a robolectric test for my application class i get a failure from ziputils which is caught in multidexjava the other tests are running fine here is the trace caused by javalangruntimeexception multi dex installation failed userscodeandroidcodeandroid is a directory at androidsupportmultidexmultidexinstallmultidexjava178 at androidsupportmultidexmultidexapplicationattachbasecontextmultidexapplicationjava39 at androidappapplicationattachapplicationjava181 at orgfestreflectmethodinvokerinvokeinvokerjava112 at orgrobolectricinternalparalleluniversesetupapplicationstateparalleluniversejava155 at orgrobolectricrobolectrictestrunnersetupapplicationstaterobolectrictestrunnerjava430 at orgrobolectricrobolectrictestrunner2evaluaterobolectrictestrunnerjava236 at orgjunitrunnersparentrunnerrunleafparentrunnerjava271 at orgjunitrunnersblockjunit4classrunnerrunchildblockjunit4classrunnerjava70 at orgjunitrunnersblockjunit4classrunnerrunchildblockjunit4classrunnerjava50 at orgjunitrunnersparentrunner3runparentrunnerjava238 at orgjunitrunnersparentrunner1scheduleparentrunnerjava63 at orgjunitrunnersparentrunnerrunchildrenparentrunnerjava236 at orgjunitrunnersparentrunneraccess0parentrunnerjava53 at orgjunitrunnersparentrunner2evaluateparentrunnerjava229 at orgrobolectricrobolectrictestrunner1evaluaterobolectrictestrunnerjava177 at orgjunitrunnersparentrunnerrunparentrunnerjava309 at orggradleapiinternaltaskstestingjunitjunittestclassexecuterruntestclassjunittestclassexecuterjava86 at orggradleapiinternaltaskstestingjunitjunittestclassexecuterexecutejunittestclassexecuterjava49 at orggradleapiinternaltaskstestingjunitjunittestclassprocessorprocesstestclassjunittestclassprocessorjava69 at orggradleapiinternaltaskstestingsuitetestclassprocessorprocesstestclasuitetestclassprocessorjava48 at orggradlemessagingthispatchreflectionthispatchthispatchreflectionthispatchjava35 at orggradlemessagingthispatchreflectionthispatchthispatchreflectionthispatchjava24 at orggradlemessagingthispatchcontextclassloaderthispatchthispatchcontextclassloaderthispatchjava32 at orggradlemessagingthispatchproxythispatchadapterthispatchinginvocationhandlerinvokeproxythispatchadapterjava93 at comsunproxyproxy2processtestclassunknown source at orggradleapiinternaltaskstestingworkertestworkerprocesstestclasstestworkerjava105,['android'] +784710,why java charactertouppercasetolowercase has no locale parameter like stringtouppercasetolowercase i am wondering that why charactertouppercasetolowercase has no locale parameter like stringtouppercasetolowercasei have to first uppercase of a text that can be in any language i have 2 solutionsuse charactertouppercasestring text stack overflowstringbuilder sb new stringbuildertext sbsetcharat0 charactertouppercasesbcharat0 no locale parameter herestring out sbtostring out stack overflowuse stringtouppercaselocale mylocale new localelocateidstring text stack overflowstring text1 textsubstring01touppercasemylocale string text2 textsubstring1string out text1 text2 out stack overflowfor my locale both way has the same resultmy question issince the text can be in any language which way should i usewhy charactertouppercasetolowercase has no locale parameter because there is not much difference between charactertouppercasetolowercase and stringtouppercasetolowercase because string is array of characters,['java'] +784726,mysql jdbc driver 5133 time zone issue some backgroundi have a java 16 webapp running on tomcat 7 the database is mysql 55 previously i was using mysql jdbc driver 5123 to connect to the db everything worked i recently upgraded to mysql jdbc driver 5133 after the upgrade tomcat would throw this error when starting the appwarning unexpected exception resolving referencejavasqlsqlexception the server timezone value utc is unrecognized or represents more than one timezone you must configure either the server or jdbc driver via the servertimezone configuration property to use a more specifc timezone value if you want to utilize timezone supportwhy is this happening,"['java', 'mysql']" +784736,try with resources vs trycatch i have been looking at code and i have seen try with resources i have used the standard trycatch statement before and it looks like they do the same thing so my question is try with resources vs trycatch what are the differences between those and which is betterhere is a try with resources objects jar new objectsbrandobjects can new objectsbrandtry fileoutputstream outstream new fileoutputstreampeoplebin objectoutputstream stream new objectoutputstreamoutstream streamwriteobjectjar streamwriteobjectcan streamclose catchfilenotfoundexception e systemoutprintlnsorry it did not work out catchioexception f systemoutprintlnsorry it did not work out,['java'] +784815,how to make a smooth rounded volumelike os x window with nsvisualeffectview i am currently trying to make a window that looks like the volume os x windowto make this i have my own nswindow using a custom subclass which is transparenttitlebarleshadowless that has a nsvisualeffectview inside its contentview heres the code of my subclass to make the content view round voidsetcontentviewnsview aview aviewwantslayer yes aviewlayerframe aviewframe aviewlayercornerradius 140 aviewlayermaskstobounds yes super setcontentviewaviewand heres the outcome as you can see the corners are grainy os xs are way smootherany ideas on how to make the corners smoother thanks,['objective-c'] +784845,constraintautolayout bar hidden xcode 6 in my storyboard file i would like to add constraints but the button to insert constraint is not shown any idea how to get it back,['ios'] +784952,what does pivotx pivoty mean in android animations i see these two terms occur at many instances related to animations but what exactly do these terms mean in android animations and i do not understand many terms in android animation xmls like objectanimator set etc is there any clear documentation apart from developerandroidcom,['android'] +784958,today extension view flashes when redrawing according to apple documentation to help your widget look up to date the system occasionally captures snapshots of your widgetas view when the widget becomes visible again the most recent snapshot is thisplayed until the system replaces it with a live version of the viewwhat i am seeing however is that the snapshot is removed from screen before the live view is prepared this results in a flash effect where the old snapshot is taken off screen the view is blank for a split second then the new view appearsis the developer responsible for making the transition between the snapshot and the live view seamless if so what is the strategy behind doing that i do not see any way to directly control that transitioni was able to mitigate the effect greatly by moving data loading to widgetperformupdatewithcompletionhandler and keeping drawing in viewwillappear but i do still see a flash once every 15 or so opens of the notification center,['ios'] +784978,how does the expressjs 4 router let things reach the 404 page the express generator generates the following code in the appjs pageappuse routesappuseusers users catch 404 and forward to error handlerappusefunctionreq res next var err new errornot found errstatus 404 nexterrhowever in the documentation it says since path defaults to middleware mounted without a path will be executed for every request to the appand gives this example this middleware will not allow the request to go beyond itappusefunctionreq res next ressendhello world requests will never reach this routeappget function req res ressendwelcomeso how could the 404 page ever be reached or the users route for that matter if nothing can get passed the appuse routes line,['javascript'] +784984,c2593 operator is ambiguous when populating stdmap i have a stdmap i am trying to initialize with an initialization list i do this in two places in two different ways the first one works while the other one causes the error mentioned in the titleheres the one that worksvoid foo static stdmapstdstring stdstring foomap first abc second def while this one does notclass bar public bar private stdmapstdstring stdstring barmapbarbar barmap this is the error line first abc second def why do i get the error when trying to initialize the class member while the static map works at the moment i can populate the member by first creating a local variable and then swapping it with the member like thisbarbar stdmapstdstring stdstring tmpmap first abc second def barmapswaptmpmaphowever this feels rather counterintuitive compared to just populating the member directlyedit heres the compiler output,['c++'] +785020,destroy stdvector without releasing memory lets say i have a function to get data into an std vectorvoid getdatastdvectorint tobefilled push data into tobefillednow i want to send this data to another function that should free the data when finishedvoid usedataint data do something with the data delete databoth functions getdata and usedata are fixed and cannot be changed this works fine when copying the data once stdvectorint data getdatadata int heapdata new intdatasize memcpyheapdata datadata datasizesizeofint usedataheapdata dataclearhowever this memcpy operation is expensive and not really required since the data is already on the heap is it possible to directly extract and use the data allocated by the std vector something like pseudocode stdvectorint data getdatadata usedatadatadata dataclearnodeleteeditthe example maybe does not make too much sense since it is possible to just free the vector after the function call to usedata however in the real code usedata is not a function but a class that receives the data and this class lives longer than the vector,['c++'] +785052,plotting datetimeindex on xaxis with matplotlib creates wrong ticks in pandas 015 in contrast to 014 i create a simple pandas dataframe with some random values and a datetimeindex like soimport pandas as pdfrom numpyrandom import randintimport datetime as dtimport matplotlibpyplot as plt create a random dataframe with datetimeindexdaterange pddate range112011 3302011 freqdrandomints randint1 50 lendaterangedf pddataframerandomvalues randomints indexdaterangethen i plot it in two different ways plot with pandas own matplotlib wrapperdfplot plot directly with matplotlib pyplotpltplotdfindex dfrandomvaluespltshowdo not use both statements at the same time as they plot on the same figurei use python 34 64bit and matplotlib 14 with pandas 014 both statements give me the expected plot they use slightly different formatting of the xaxis which is okay note that data is random so the plots do not look the samehowever when using pandas 015 the pandas plot looks alright but the matplotlib plot has some strange tick format on the xaxisis there any good reason for this behaviour and why it has changed from pandas 014 to 015,['python'] +785165,java aes javaxcryptobadpaddingexception given final block not properly padded public class aes public string getencryptstring pass string password encryptpass return password public string getdecryptstring pass string key aessecretkeyabcd byte passwordbyte decryptkeypass string password new stringpasswordbyte return password private byte decryptstring key string encrypted try secretkeyspec skeyspec new secretkeyspeckeygetbytes aes cipher cipher ciphergetinstanceaes cipherinitcipherdecrypt mode new secretkeyspecskeyspecgetencoded aes getting error here byte original cipherdofinalencryptedgetbytes return original catch illegalblocksizeexception ex exprintstacktrace catch badpaddingexception ex exprintstacktrace catch invalidkeyexception ex exprintstacktrace catch nosuchalgorithmexception ex exprintstacktrace catch nosuchpaddingexception ex exprintstacktrace return null private string encryptstring value try byte raw new bytea e s s e c r e t k e yabcd secretkeyspec skeyspec new secretkeyspecraw aes cipher cipher ciphergetinstanceaes cipherinitcipherencrypt mode skeyspec byte encrypted cipherdofinalvaluegetbytes systemoutprintlnencrypted string new stringencrypted return new stringencrypted catch nosuchalgorithmexception ex exprintstacktrace catch illegalblocksizeexception ex exprintstacktrace catch badpaddingexception ex exprintstacktrace catch invalidkeyexception ex exprintstacktrace catch nosuchpaddingexception ex exprintstacktrace return null i am having a null pointer whenever i decrypt sometimes it gives me the correct decrypted password but sometimes it gives me a null pointer cannot guess what the problem is here,['java'] +785282,android toolbar center title and custom font i am trying to figure out the right way to use a custom font for the toolbar title and center it in the toolbar client requirementat the moment i am using the good old actionbar and i was setting the title to empty value and using setcustomview to put my custom font textview and center it using actionbarlayoutparamsis there a better way to do that using the new toolbar as my actionbarthanks,['android'] +785286,do thistinct functions have thistinct addresses consider these two functionsvoid foo void bar is it guaranteed that foo barsimilarlytemplateclass t void foo is it guaranteed that fooint foodoublethere are two linkers i know of that fold function definitions togethermsvc aggressively comdat folds functions so two functions with the same implementation can be turned into one function as a side effect the two functions share the same address i was under the impression that this was illegal but i cannot find where in the standard it is made illegalthe gold linker also folds functions with both a safe and all setting safe means that if a function address is taken it is not folded while all folds even if the address is taken so golds fold safe behaves asif functions have thistinct addresseswhile folding might be unexpected and there is code that relies on thistinct identical implementation functions having different addresses so it can be dangerous to fold is it actually illegal under the current c standard c14 at this point naturally asif safe folding is legal,['c++'] +785413,how to deleteremove nodes on firebase i am using firebase for a web app it is written in plain javascript using no external librariesi can push and retrieve data with onchild added but remove does not work the way it says it should according to the apifirebaseremove remove the data at this firebase location any data at child locations will also be deleted the effect of the delete will be visible immediatelyhowever the remove is not occurring immediately only when the entire script is done running i need to remove and then use the cleared tree immediately afterexample coderef new firebasemyfirebasecom worksrefpushkeyval worksrefonchild added functionsnapshotdo stuff worksrefremovedoes not remove until the entire scriptpage is donethere is a similar post here but i am not using ember libraries and even so it seems like a workaround for what should be as simple as the api explains it to be,['javascript'] +785422,binding ngmodel to a custom directive so i have been working on this issue for a week now and i cannot seem to get my head around this whole directive thing i have read lots of posts demystifying directivesdirectivescompile pre and post linkinga bunch of videos creating reusable directives in angularjswriting directivesand gone through stackoverflow and other forums links to follow hoping something will sink in i think that the problem that i am running into is that i want to understand whyhow these work so that i am not cutpasting someone elses solution into my code but then having to ask again later when something else crops up because i do not know what my pasted code is doing i am finding however that everyone has a different way to skin this cat and none of them seem to match up with my understanding of how this is supposed to workwhat i am attempting to do is build a form using the metro ui css library i thought i would start with a simple textbox yep just a simple text box a metro ui textbox has some nice built in functionality that i wanted to preserve so i thought that was good place to starti read that in order to leverage metro ui behaviors with angularjs i would need to wrap it in a custom directive custom datadirectives inside an angularjs ngrepeat while this example was not exactly what i was looking for it seemed to easily explain what i needed to do just call the function that applies the behavior in the link function of the directive and add the directive attribute to the input element so i created a directive called metroinputtransform and added it as an attribute to an input element div datangcontrollerpageoneformctrl as page input typetext idtxproductname datangmodelpagedataproductname datametroinputtransform placeholderproduct name divin the link function of the directive i simply called the method that applies the behavior i was looking for i know that this is a little more verbose than it needs to be but i am trying to learn it so i am stepping through it as best as i can for full code see this fiddlevar metrodirectives angularmodulemetrodirectives metrodirectivesdirectivemetroinputtransform function compile function postlinkscope element attrs controller elementinputtransform return priority 100 compile function element attrs return postlink so this worked partially it created the metro look and feel and associated behavior but ngmodel was not binding to the element so this began a long journey through concepts such as isolate scope breaking out the various compile controller prelink postlink functions at least two different ways of persisting ngmodel all of which did not work after a variety of reading it was my understanding that the dom manipulation should happen in the compile function so that any dom transformations would be available for the compile and then linking stages of the digest process so i moved the inputtransform call to the compile function fiddle return priority 100 terminal true if i did not put this everything would execute twice compile function element attrs elementinputtransform return pre prelink post postlink no luck same thing not binding to ngmodel so i thiscovered the concept of isolate scope understanding isolate scope videousing isolate scopes in directives videousing ngmodel with isolate scopebased on that i tried the following fiddle return priority 100 scope ngmodel terminal true if i did not put this everything would execute twice compile function element attrs elementinputtransform return pre prelink post postlink no change i tried a number of other things but am afraid i may lose you attention soon if i have not already the closest i got was oneway binding doing something like below and even here you can see that the extraction of the ngmodel reference is utterly unacceptable fiddle var metrodirectives angularmodulemetrodirectives metrodirectivesdirectivemetroinputtransform function function postlinkscope element attrs controller successfully perfomes oneway binding i need twoway but is clearly very hardcoded i suppose i could write a pasrsing function that would do this for whatever they assign to the ngmodel but ther emust be a btter way elementonchange datametroinputtransform functione scopeapplyfunction scopepagedataproductname ecurrenttargetvalue return priority 100 terminal true if i did not put this here the compile would execute twice compile function element attrs elementinputtransform return pre function scope element attrs controller transcludefn post postlink i am exhausted and have absolutely no idea whats left to try i know that this is a matter of my ignorance and lack of understanding on howwhy angularjs works the way it does but every article i read leaves me asking as many questions as were answered or takes me down a rabbit hole in which i get more lost than i was when i started short of dropping 30 on live inperson seminars that i cannot afford where i can ask the questions i need answered i am at a complete dead end with angular i would be most grateful if anyone could provide guidance direction a good resource anything that can help shed some light on this issue in particular but anything that might help me stop spinning my wheels in the meantime i will continue to read and reread everything i can find and hopefully something will breakthanksgupdate 10302014i am so over this issue but want to follow it through i need and want to learn this also i really want to express appreciation for the effort that folks have put into this and while they have presented some solutions which ultimately may be the best way to go they have both skirted the issue which is that i am attempting to use the behaviors provided with the metro ui css library i would prefer to not have to rewrite them if possible both solutions provided so far have eliminated the key statement from the solution which is the line elementinputtransformi do not want to post the entire jquery widget that comprises the inputtransform definition but i cut the meat of it out and included it here function createinputvalelement name buttonname var wrapper divaddclassinputcontroladdclassname var button buttonaddclassbuttonname var clone elementclonetrue clone the original element var parent elementparent cloneappendtowrapper buttonappendtowrapper wrapperinsertbeforeelement elementremove delete the original element return wrapper so i have applied the directive as an attribute because the metro code behind it wants to clone the textbox which would not do if it was an element directive and then removes the original input element it then creates the new dom elements and wraps the cloned input element in the newly created div container the catch i believe is that the binding is being broken when the original element is being cloned and removed from the dom makes sense if the ngmodel attribute assignment is bound to a reference of the textbox so the expectation that i originally had was since the ngmodel attribute was cloned along with the rest of the element that in the compile eventfunctionphase of the directive the reference would bereestablished to the newly created input element this apparently was not the case you can see in this updated fiddle that i have made some attempts at reconnecting the ngmodel to the new dom elements with no success perhaps this is impossible it certainly seems that just rebuilding these things may ultimately be the easier way to go thanks again mikko viitalia and azium,"['javascript', 'html']" +785456,how to write a generic method that takes two arguments of the same types in java i was very surprised when i noticed that following code compiles without warnings and prints integer stringpublic final class genericstest private static t void methodt arg1 t arg2 systemoutprintlnarg1getclassgetsimplename systemoutprintlnarg2getclassgetsimplename public static void mainstring args method1 1 i expected a compilation erroris there a reason why this code compileswhat is the correct way to ensure that arguments have the same typeedit what about bounded type parameters the best i can think of is thisprivate static t you extends t void methodt arg1 you arg2 systemoutprintlnarg1getclassgetsimplename systemoutprintlnarg2getclassgetsimplenameunfortunately java does not allow cyclic constraints t extends u you extends t does not compile is this a dead end,['java'] +785670,take a screenshot using mediaprojection with the mediaprojection apis available in android l it is possible to capture the contents of the main screen the default thisplay into a surface object which your app can then send across the networki have managed to get the virtualthisplay working and my surfaceview is correctly thisplaying the content of the screen what i want to do is to capture a frame thisplayed in the surface and print it to file i have tried the following but all i get is a black filebitmap bitmap bitmapcreatebitmap surfaceviewgetwidth surfaceviewgetheight bitmapconfigargb 8canvas canvas new canvasbitmapsurfaceviewdrawcanvasprintbitmaptofilebitmapany idea on how to retrieve the thisplayed data from the surfaceeditso as j m suggested i am now setting up the virtualthisplay using the surface of an imagereaderthisplay thisplay getwindowmanagergetdefaultthisplaypoint size new pointthisplaygetsizesizethisplaywidth sizexthisplayheight sizeyimagereader imagereadernewinstancethisplaywidth thisplayheight imageformatjpeg 5then i create the virtual thisplay passing the surface to the mediaprojectionint flags thisplaymanagervirtual thisplay flag own content only thisplaymanagervirtual thisplay flag publicthisplaymetrics metrics getresourcesgetthisplaymetricsint density metricsdensitydpimediaprojectioncreatevirtualthisplaytest thisplaywidth thisplayheight density flags imagereadergetsurface null projectionhandlerfinally in order to get a screenshot i acquire an image from the imagereader and read the data from itimage image imagereaderacquirelatestimagebyte data getdatafromimageimagebitmap bitmap bitmapfactorydecodebytearraydata 0 datalengththe problem is that the resulting bitmap is nullthis is the getdatafromimage methodpublic static byte getdatafromimageimage image imageplane planes imagegetplanes bytebuffer buffer planes0getbuffer byte data new bytebuffercapacity buffergetdata return datathe image returned from the acquirelatestimage has always data with default size of 7672320 and the decoding returns nullmore specifically when the imagereader tries to acquire an image the status acquire no bufs is returned,['android'] +785688,errorattribute theme has already been defined i am using android studio for building application i am using this following dependenciesplay services compile comgoogleandroidgmsplayservices5208app combat v7 compile comandroidsupportappcompatv72100support cardview compile comandroidsupportcardviewv72100support recycler view compile comandroidsupportrecyclerviewv72100i am getting following error while building my appappbuildintermediatesexplodedaarcomgoogleandroidgmsplayservices5208resvalueswallet attrsxml errorattribute theme has already been definedcode stylesxmlresources base application theme style nameapptheme parentthemeappcompatlightdarkactionbar customize your theme here styleresourcescode wallet attrsxmlxml version10 encodingutf8 copyright 2014 google inc all rights reserved resources attributes for the walletfragment ltfragmentgt tag declarestyleable namewalletfragmentoptions theme to be used for the wallet selector attr nametheme formatenum enum nameholo dark value0 enum nameholo light value1 attr google wallet environment to use attr nameenvironment formatenum enum nameproduction value1 enum namesandbox value0 enum namestrict sandbox value2 attr a style resource specifing attributes to customize the look and feel of walletfragment attr namefragmentstyle formatreference fragment mode attr namefragmentmode formatenum enum namebuybutton value1 enum nameselectiondetails value2 attr declarestyleable attributes that may be specified in a style resource to customize the look and feel of walletfragment declarestyleable namewalletfragmentstyle height of the buy button this includes an 8dp padding 4dp on each side used for pressed and focused states of the button the value can be a specific height eg 48dp or special values match parent and wrap content attr namebuybuttonheight formatdimension enum namematch parent value1 enum namewrap content value2 attr width of the buy button this includes an 8dp padding 4dp on each side used for pressed and focused states of the button the value can be a specific width eg 300dp or special values match parent and wrap content attr namebuybuttonwidth formatdimension enum namematch parent value1 enum namewrap content value2 attr text on the buy button must be one of buy with google buy now and book now attr namebuybuttontext formatenum enum namebuy with google value1 enum namebuy now value2 enum namebook now value3 attr appearance of the buy button must be one of classic grayscale and monochrome attr namebuybuttonappearance formatenum enum nameclassic value1 enum namegrayscale value2 enum namemonochrome value3 attr textappearance for masked wallet details attr namemaskedwalletdetailstextappearance formatreference textappearance for headers describing masked wallet details attr namemaskedwalletdetailsheadertextappearance formatreference masked wallet details background attr namemaskedwalletdetailsbackground formatreferencecolor textappearance for the change button in masked wallet details view attr namemaskedwalletdetailsbuttontextappearance formatreference change button background in masked wallet details view attr namemaskedwalletdetailsbuttonbackground formatreferencecolor color of the google wallet logo text in masked wallet details view attr namemaskedwalletdetailslogotextcolor formatcolor type of the wallet logo image in masked wallet details view attr namemaskedwalletdetailslogoimagetype formatenum enum nameclassic value1 enum namemonochrome value2 attr declarestyleableresources,['android'] +785745,how to listen for picasso android load complete events is there a way to listen for events from picasso when using the builder likepicassowithgetcontextloadurlintoimageviewi am trying to call requestlayout and invalidate on the parent gridview so it will resize properly but i do not know how to set a listener or callback i see that picasso has error event reporting but is there a success event,"['java', 'android']" +785753,xmpp vs websocket i am about to develop a website that has near real time chat i know that it can be implemented using xmpp or websocket protocols i know also that the xmpp protocol has been developed in 19 and i guess it should be mature nowadays on the other hand the websocket protocol has been developed in 2011 what was the need for websocket if xmpp was good in handling real time conversationswhat are the major differences between the 2 protocols and when should i choose one of them over the other,['java'] +785754,query on a manytomany relationship using doctrine with symfony2 i am triyng to understand how the many to many relationship works with doctrine and symfony2i have recreated the example shown on the official documentation googlgycve0 and i have two entity classes user and group as you can see belowphp entity class user manytomanytargetentitygroup inversedbyusers jointablenameusers groups private groups public function construct thisgroups new doctrinecommoncollectionsarraycollection entity class group manytomanytargetentityuser mappedbygroups private users public function construct thisusers new doctrinecommoncollectionsarraycollection if i update my db i get this mysql schemacreate table user id int auto increment not null primary keyid engine innodbcreate table users groups user id int not null group id int not null primary keyuser id group id engine innodbcreate table group id int auto increment not null primary keyid engine innodbalter table users groups add foreign key user id references useridalter table users groups add foreign key group id references groupidthe problem is that in symfony2 i need the entity to generate a query and in this case i do not have an entity associated to the table users group because this table is created automatically by the frameworkso how can i retrieve the information related to this relationship table for example i need to get all the users in a group which are the users that have an id that appears in the table users grouphow can i do that using for example the dql or querybuilder or other methodsthanks a lot,"['php', 'mysql']" +785771,swift random number for 64bit integers so with my current project i need to work with 64bit integers and i need to grab random numbers between ranges up to 100 billion arc4randomarc4random uniform only works with unsigned 32bit integersi can probably fudge it a little because my minmax range for every call will likely not exceed 2 billion but i would like to futureproof myself in case i decide that well i do need a broader rangeany advice,['ios'] +785783,flask blueprint attributeerror module object has no attribute name error my api is being built to allow developers to extend it is functionality my plan is to do this by providing an extensions directory where they can drop in blueprints and they will be dynamically loaded this is the code i am utilizing to import modifed from this tutorialfrom flask import flaskimport pkgutilimport sysapp flask name extensions dir extensionsmodules pkgutiliter modulespathextensions dirfor loader mod name ispkg in modules if mod name not in sysmodules it imports fine loaded mod import extensions dirmod namemod name fromlistmod name it does not register appregister blueprintloaded modthis is the directory layout of my project the extensions directory is where developers drop in their expanded functionalityroot extensions extension1 init py extension1py extension2 init py extension2py simple examplepythe problem is that i get this error and am not sure what it is telling mepython simple examplepytraceback most recent call last file simple examplepy line 14 in module appregister blueprintloaded mod file cpython27libsitepackagesflaskapy line 62 in wrapper func return fself args kwargs file cpython27libsitepackagesflaskapy line 880 in register blueprint if blueprintname in selfblueprintsattributeerror module object has no attribute namea simple extension looks like thisfrom flask import blueprintextension1 blueprintextension1 name extension1routemy routedef treasure list return list of objectshow do i solve the attributeerror in a way that allows my appregister blueprint call to succeed,['python'] +785803,html5 can session storage local storage be thisabled and cookies enabled for most modern browsers is it possible to have session or local storage thisabled while cookies are enabled or does the thisabling of cookies also automatically thisable the use of session local storage,['html'] +785900,switchcompat throwing error i am trying to use switchcompat in my fragment the min supported api is 14 and max is 21 i am trying to apply the material view to switch for all pre lollipop android versions but when use the below code i get an errorhow can i correct itandroidsupportv7widgetswitchcompat androidlayout widthwrap content androidlayout heightwrap content inflating in java code which is throwing the exception override public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate final view view inflaterinflaterlayoutfragment scheduler ui container false referenceexception1024 141515880 15611561comstackoverflowranjithandroidprojdel eandroidruntimei1 fatal exception mainprocess comstackoverflowranjithandroidprojdel pid 1561javalangnullpointerexception at androidtextlayoutgetdesiredwidthlayoutjava67 at androidsupportv7widgetswitchcompatmakelayoutswitchcompatjava570 at androidsupportv7widgetswitchcompatonmeasureswitchcompatjava495 at androidviewviewmeasureviewjava16497 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava5125 at androidwidgetlinearlayoutmeasurechildbeforelayoutlinearlayoutjava1404 at androidwidgetlinearlayoutmeasureverticallinearlayoutjava695 at androidwidgetlinearlayoutonmeasurelinearlayoutjava588 at androidviewviewmeasureviewjava16497 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava5125 at androidwidgetframelayoutonmeasureframelayoutjava310 at androidviewviewmeasureviewjava16497 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava5125 at androidwidgetframelayoutonmeasureframelayoutjava310 at androidviewviewmeasureviewjava16497 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava5125 at comandroidinternalwidgetactionbaroverlaylayoutonmeasureactionbaroverlaylayoutjava327 at androidviewviewmeasureviewjava16497 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava5125 at androidwidgetframelayoutonmeasureframelayoutjava310 at comandroidinternalpolicyimplphonewindowdecorviewonmeasurephonewindowjava2291 at androidviewviewmeasureviewjava16497 at androidviewviewrootimplperformmeasureviewrootimpljava1916 at androidviewviewrootimplmeasurehierarchyviewrootimpljava13 at androidviewviewrootimplperformtraversalsviewrootimpljava1295 at androidviewviewrootimpldotraversalviewrootimpljava10 at androidviewviewrootimpltraversalrunnablerunviewrootimpljava5670 at androidviewchoreographercallbackrecordrunchoreographerjava761 at androidviewchoreographerdocallbackschoreographerjava574 at androidviewchoreographerdoframechoreographerjava544 at androidviewchoreographerframethisplayeventreceiverrunchoreographerjava747 at androidoshandlerhandlecallbackhandlerjava733 at androidoshandlerthispatchmessagehandlerjava95 at androidoslooperlooplooperjava136 at androidappactivitythreadmainactivitythreadjava5017 at javalangreflectmethodinvokenativenative method at javalangreflectmethodinvokemethodjava515 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava779 at comandroidinternaloszygoteinitmainzygoteinitjava595 at dalviksystemnativestartmainnative methodbuildgradledependencies compile comandroidsupportcardviewv7 compile comandroidsupportrecyclerviewv7 compile comandroidsupportpalettev7 compile comandroidsupportsupportv4 compile comandroidsupportappcompatv7210 compile filetreedir libs include jar,['android'] +785925,using a materialbased dialog theme with appcompat i have an activity in my manifest i used to style with a dialog theme i can not find how to replace this in appcompat library activity androidnameloginactivity androidthemeandroidstylesthemeholodialog androidconfigchangesorientationscreensizekeyboardhidden androidlabellogin is there a materialbased equivalent,['android'] +785964,how to close the side bar menu manually when using swrevealviewcontroller ios i am trying to implement a side bar slide out menu using the swrevealviewcontroller i have a bunch of menus one of the menu is to get app version info so when i click on the cell an alert view thisplays the version number and on pressing the ok button i would like to closehide the side bar menu and return to the pervious viewfront controller for example if i am on log in controller and i press the settings button to reveal the side bar and i choose version menu from table view cells a pop will open thisplaying version and when i press ok the side bar should close and return to the login screen without me having to tap the settings button again or swiping to return how can i return to the login screen when i press ok on the alert view voidalertviewuialertview alertview didthismisswithbuttonindexnsintegerbuttonindex the user clicked ok if buttonindex 0 close the side bar and return to front view controller,['ios'] +785983,intermittently cannot connect to mysql on aws rds error 2003 we are having an intermittent issue with connections to our mysql server timing outthe error we are receiving is as following2003 cannot connect to mysql server on connection 2013 lost connection to mysql server during query error104 connection reset by peercallstack file usrlib64python27sitepackagespymysqlconnectionspy line 818 in connect 2003 cannot connect to mysql server on r s selfhost e file usrlib64python27sitepackagespymysqlconnectionspy line 626 in init self connectsome more infowe have a flight of ec2 servers that are constantly running queries to a backend rdswe average about 500 connections per second to the rdswe have around 0 4 hiccups per rds per daythe hiccups do not correspond with our maintenance windowwhen we hit a hiccup it can affect quite a few connections 50when a hiccup happens it will thisrupt connections across all servers and portsthe error itself looks to be generated from the tcp connection being closed on the ec2 our tcp keep alive time is set to 7200 seconds and that is when the error is fired offmy question is what can be done to track down why these hiccups happen it is great that they do not happen often but it is not ideal that they happen at allany advice would be appreciated thanksupdate 1029i have been running a service checking to see if i have any long processes running on the sql server and it looks like these errors are not getting that far a new process is never created for this connection i have still been receiving the hiccups just no signs of connections,['mysql'] +786046,styling the searchview widget using support library v21 i am trying to style the searchview widget using the new appcompat v21 but i am facing some problems no matter what layout i set on suggestionrowlayout attribute it does nothing at all the suggestion dropdown list of the searchview remains the same wayother problem that i am having is when the accent color is the same color as the primary color in the searchview is impossible to thistinguish where is the caret do you know how can i change the accent color in the searchview to only be applied there i have found that play music has the same problemi am following the guide from android developers blogi,['android'] +786055,bootstrap 32 how to make 3 columns containing text in another div same height using bootstrap 32 i have a section of website that has three divs collg3 box that will have differing amounts of text in them i would like them all to extend to the bottom of the containing div row a link to the css file i am using is here the answers i have seen on stack exchange for this general issue same height divs in a container either do not use bootstrap or are have outdated syntax if you can link me to a sxe question that perfectly mirrors mine i will gladly take the downvotes in exchange for an answer div classcontainerfluid join h2 classtextcenter whiteheading idjoinitastrongjoin itastrongh2 hr classlineblack div classrow div classcollg3 box div h3 classtextcenter blueheadingnewcomers begin hereh3 div pyou will immediately earn 75 of paid commission payable to you within 2 weeks of receipt upon registering you immediately receive your own span classemphasisbluegazoomspan personalized website with product and software training as well as mentoring you will have at your fingertips all the tools necessary to immediately begin your business in the travel industryp button typebutton classcenterblock btn btnsuccess btnlgjoin nowbutton div div classcollg3 box div h3 classtextcenter blueheadingexperienced parttime agentsh3 div pimmediately earn 80 of paid commissions paid within 2 weeks of receipt enjoy your business at your pace with the span classemphasisbluegazoomspan family of products and services upon registering you will immediately receive your personalized website with our diverse and unique travel opportunities for your clients at your fingertips a 24 hour assist program is available for you and your clients youll be eligible to participate in our corporate and leisure lead generation program no monthly minimum requirementsp button typebutton classcenterblock btn btnwarning btnlgjoin nowbutton div div classcollg3 box div h3 classtextcenter blueheadingexperienced fulltime agentsh3 div pyoure eligible to receive one of the highest paid commission levels in the industry 85 which is payable within 2 weeks of receipt when you maintain monthly bookings bring your clients and enjoy one of the industrys most dynamic and unique inventory and booking sites be confident that you and your book of business is protected and can be serviced with our 24 hour assist program we can assist in growing your business by offering you a lead generation program for corporate travelers as well as leisure travelersp button typebutton classcenterblock btn btnred btnlgjoin nowbutton div divdiv,"['html', 'css']" +786085,phpstorm generate setter with type hint in phpstorm you can generate a setter method for class members by alt insert setters picking the variables to make setter methods forbut even when phpstorm knows the typeclass of the variable it does not insert a type hint into the parameter list how to make phpstorm generate setters with type hints but only for type hintable typesexample classclass codegenerationtest var datetimeinterface private date var int private numthe desired generated setters should be param datetimeinterface date public function setdatedatetimeinterface date thisdate date param int num public function setnumnum thisnum numsetnum is correct but setdate gets generated missing the type hint on the parameter param datetimeinterface date public function setdatedate thisdate date,['php'] +786246,creating a preference screen with support v21 toolbar i was having trouble using the new material design toolbar in the support library on a preference screeni have a settingsxml file as belowpreferencescreen xmlnsandroid preferencecategory androidtitlestringaddingitems androidkeypref key storage settings listpreference androidkeypref key new items androidtitlestringlocationofnewitems androidsummarystringlocationofnewitemssummary androidentriesarraynew items entry androidentryvaluesarraynew item entry value androiddefaultvalue1 preferencecategorypreferencescreenthe strings are defined elsewhere,['android'] +786258,searchview using appcompat i implemented searchview in actionbar before using appcompatv7but when i want to use the searchview with support library v7 it shows null exceptionin styleitem androidididaction search androidtitlestringaction search androidicondrawableic action search appshowasactionalwayscollapseactionview androidactionviewclassandroidsupportv7widgetsearchview in java classoverridepublic boolean oncreateoptionsmenumenu menu getmenuinflaterinflatermenumenu menu searchview searchview searchview menufinditemridaction searchgetactionview searchviewsetonquerytextlistenerthis return superoncreateoptionsmenumenumy question is how to declare searchview in oncreateoptionsmenu to be able to set query listener,['android'] +786347,static properties in swift i am trying to convert the following objectivec code to swift in my objectivec code there is a static variable and its accessed from a class methodimplementation someclastatic nsmutablearray items voidsomemethod items removeallendsince you cannot access types declared like this private var items anyobject from class functions in swift i created a stored property for it like thisclass var items anyobject return anyobjectand i am trying to call a method on it from a class function like soclass func somefunction itemsremoveallkeepcapacity falsebut i get this error immutable value of type anyobject only has mutating members named removeallcan anyone please tell me whats the cause of this error and how to correct itthank you,['ios'] +786354,live rendering a custom component using ib designable from a pod dependency i am having some difficulty using ib designable in a podi created a custom view which i marked as ib designable and made a sample project that uses it no problems so farthe issue happens when adding that custom view as a pod dependency although the project builds and runs successfully there is an error when the storyboard that uses the custom view is opened the live rendering process starts and tries to show the view live inside interface builder but it fails with the following errorthis is too bad because we lose live rendering which is in my opinion one of the best features from xcode 6cocoapods gem version 0344xcode version 61 6a1052di have tried with other projects that use ib designable and have a podspec class eacolourfulprogressview class hrbutton class estindoorlocationviewsomeone else had the same issue in estimote indoor location error but the solution described means losing live rendering capabilitieshas anyone been able to use a ib designable component through cocoapodserror failed to load designables from path null,"['ios', 'objective-c']" +786498,why does union has deleted default constructor if one of its member does not have one whatsoever n3797952 classunion saysif any nonstatic data member of a union has a nontrivial default constructor 121 copy constructor 128 move constructor 128 copy assignment operator 128 move assignment operator 128 or destructor 124 the corresponding member function of the union must be userprovided or it will be implicitly deleted 843 for the unioni was trying to understand that note by exampleinclude iostreaminclude limitsstruct a aconst a stdcout a stdendl a has no default constructorunion u a au u error call to implicitlydeleted default constructor of uint maindemothat behavior is not quite clear to me struct a does not have implicitlydeclared default constructor because 1214 classctor saysif there is no userdeclared constructor for class x a constructor having no parameters is implicitly declared as defaulted 84which means struct a does not have a nontrivial default constructor there is no default constructor at all in particular nontrivial that is union u does not have to have a deleted default constructor whats wrong,['c++'] +786552,how to properly add custom view to the toolbar i am using toolbar with extended height 56dp 80dp and want to add edittext to the bottom of the toolbar the problem i have is that edittext does not expands itself to the right edge like in picture belowthe code looks like belowtoolbar edit textxmlxml version10 encodingutf8edittext xmlnsandroid androidididtitle androidlayout widthmatch parent androidlayout heightwrap content androidhinttitle androidsinglelinetrue adding layout to toolbarlayoutinflater inflater layoutinflaterfrommactivitygetactionbartoolbargetcontext mtoolbarlayout edittext inflaterinflaterlayouttoolbar edit text null toolbarlayoutparams layoutparams new toolbarlayoutparamsviewgrouplayoutparamsmatch parent viewgrouplayoutparamswrap content layoutparamsgravity gravitybottom mactivitygetactionbartoolbaraddviewmtoolbarlayout layoutparams,['android'] +786638,can i use the workstealing behaviour of forkjoinpool to avoid a thread starvation deadlock a thread starvation deadlock occurs in a normal thread pool if all the threads in the pool are waiting for queued tasks in the same pool to complete forkjoinpool avoids this problem by stealing work from other threads from inside the join call rather than simply waiting for exampleprivate static class forkabletask extends recursivetaskinteger private final cyclicbarrier barrier forkabletaskcyclicbarrier barrier thisbarrier barrier override protected integer compute try barrierawait return 1 catch interruptedexception brokenbarrierexception e throw new runtimeexceptione testpublic void testforkjoinpool throws exception final int parallelism 4 final forkjoinpool pool new forkjoinpoolparallelism final cyclicbarrier barrier new cyclicbarrierparallelism final listforkabletask forkabletasks new arraylistparallelism for int i 0 i parallelism i forkabletasksaddnew forkabletaskbarrier int result poolinvokenew recursivetaskinteger override protected integer compute for forkabletask task forkabletasks taskfork int result 0 for forkabletask task forkabletasks result taskjoin return result assertthatresult equaltoparallelismbut when using the executorservice interface to a forkjoinpool workstealing does not seem to occur for exampleprivate static class callabletask implements callableinteger private final cyclicbarrier barrier callabletaskcyclicbarrier barrier thisbarrier barrier override public integer call throws exception barrierawait return 1 testpublic void testworkstealing throws exception final int parallelism 4 final executorservice pool new forkjoinpoolparallelism final cyclicbarrier barrier new cyclicbarrierparallelism final listcallabletask callabletasks collectionsncopiesparallelism new callabletaskbarrier int result poolsubmitnew callableinteger override public integer call throws exception int result 0 deadlock in invokeall rather than stealing work for futureinteger future poolinvokeallcallabletasks result futureget return result get assertthatresult equaltoparallelismfrom a cursory look at forkjoinpools implementation all the regular executorservice apis are implemented using forkjointasks so i am not sure why a deadlock occurs,['java'] +786831,summing values across nested lists at each index i have a listliststring called datacollection where each of the nested lists have an equal number of values although all strings the values in the nested lists will be strings consisting of alphanumeric characters empty strings or a currency value for example datacollection0 tom abc 52534 123 datacollection1 dick xyz 100 234 datacollection2 harry 25001 40 datacollection2 bob 25001 what i need to do is come up with a way to sum all values per index across all the nested lists and add this to a listnewsumlist0 na since tom dick harry bob cannot be aggregatednewsumlist1 na since abc xyz cannot be aggregatednewsumlist2 112536newsumlist3 397 even though the last value of the last nested list is basically total all numeric values in nested lists for each indexthe only way i can think of is to iterate though these and keep a running total but i was wondering if i can do it using linq or something else,['c#'] +786858,assigning retained object to weak property i am using xcode 6 and i have created my app with a uitableview and a custom cell in itthis is my custom cellinterface suggestingtableviewcell uitableviewcellproperty nonatomic weak iboutlet suggestedseriesview seriesoneproperty nonatomic weak iboutlet suggestedseriesview seriestwoproperty nonatomic weak iboutlet suggestedseriesview seriesthreeproperty nonatomic weak iboutlet suggestedseriesview seriesfourendas you can see i have four iboutets to a suggestedseriesview that is a subclass of uiviewin the tableview datasource methods i have created these suggestedseriesview and assign them likecellidentifier suggestioncellsuggestingtableviewcell suggesting suggestingtableviewcell tableview dequeuereusablecellwithidentifiersuggestioncellseries ser1 series0suggestingseriesone suggestedseriesview alloc initwithframesuggestingseriesonebounds andseriesdatajv series image url ser1imageurl jv series title ser1titleseries ser2 series1suggestingseriestwo suggestedseriesview alloc initwithframesuggestingseriestwobounds andseriesdatajv series image url ser2imageurl jv series title ser2titleseries ser3 series2suggestingseriesthree suggestedseriesview alloc initwithframesuggestingseriesthreebounds andseriesdatajv series image url ser3imageurl jv series title ser3titleseries ser4 series3suggestingseriesfour suggestedseriesview alloc initwithframesuggestingseriesfourbounds andseriesdatajv series image url ser4imageurl jv series title ser4titlethe compiler gives me the warning that assigning retained object to weak property object will be released after assignmentwhy this is happening to the suggestedseriesview gets retained by the cell because it has no iboutletthanks for the help,"['ios', 'objective-c']" +786929,why does stdmax return the wrong value in the grill the committee session from cppcon 2014 committee member walter brown mentioned that stdmax returns the wrong value in the case that both arguments have an equal valuethis was accepted without comment and not elaborated upon what did he mean by this why should it matter which value is returned,['c++'] +786958,do uninitialized primitive instance variables use memory in java does it cost memory to declare a class level instance variable without initializing itfor example does int i use any memory if i do not initialize it with i 5detailsi have a huge superclass that many different not different enough to have their own super classes subclasses extend some subclasses do not use every single primitive declared by the superclass can i simply keep such primitives as uninitialized and only initialize them in necessary subclasses to save memory,['java'] +786991,why is strcmp not simd optimized i have tried to compile this program on an x64 computerinclude cstringint mainint argc char argv return stdstrcmpargv0 really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really long string i compiled it like thisg stdc11 msse2 o3 g acpp o abut the resulting thisassembly is like this 0x0400480 0 mov rsirsi 0x0400483 3 mov 0x400628edi 0x0400488 8 mov 0x22decx 0x040048d 13 repz cmpsb esrdidsrsi 0x040048f 15 seta al 0x0400492 18 setb dl 0x0400495 21 sub edxeax 0x0400497 23 movsbl aleax 0x040049a 26 retq why is no simd used i suppose it could be to compare say 16 chars at once should i write my own simd strcmp or is it a nonsensical idea for some reason,['c++'] +787036,angular get request error but only on safari ios i am building a website using wordpress as backend and angularjs as frontend i am using the wordpress json api to get my data to the frontendthe problemi am using angular to get my data from the wordpres json api i have created the following servicethisgetpage function slug return httpgetwordpressapiget pageslug slugi use this service in my controller to get the current pagehttpservicegetpagehome successfunction data scopepage datapage consolelogarguments error function consolelogarguments so this is working fine in all browsers except for safari ios on safari ios i get the following response if i log the error argumentsthis is the safari debugger i connected my iphone to my macbook the error response that i get is error code 0what i have tried so fari have set accesscontrolalloworigin in the htaccess file but this doesnt seem to work the request is done on the same domain with a relative url so i dont even think that this is the problemso does any1 know why this is not working on safari ios onlythanks in advanceeditsome extra info as requested,['javascript'] +787140,how can we increment and then decrement a counter without conditionals i am looking for a clever way to increment and then decrement a counter variable i want the counter variable to begin at a low value and increment towards a higher value once it reaches the higher value the counter decrements until it reaches back to the lower value once it reaches the lower value the counter increments again to the higher value i think you get the pointi am working on a a canvas animation where i would like to employ some cleverness without using if or other conditional testshere is the conditional logic that handles the counter variableincrementing truefoo length 1 if incrementing length 1 if not incrementing incrementing false if length 100 incrementing true if length 1initially i thought i could use modulo however modulo division only resets the counter back to the lower value it does not decrement the counter once it reaches the top value 0 10 0 1 10 1 2 10 2 3 10 3 4 10 4 5 10 5 6 10 6 7 10 7 8 10 8 9 10 910 10 011 10 112 10 213 10 3i am sure there has to be a way to do this without using conditional tests assuming a bottom value of 0 and a top value of 10 the method should output the following 0 1 2 3 4 5 6 7 8 9 8 7 6 5,['javascript'] +787148,launching aspx soap services project in visual studio 2013 causes stackoverflowexception this is a c web services project in visual studio that has existed for a number of years today it started throwing an exception upon startup within visual studio but only when the debugger is attachedthe exception issystemstackoverflowexception was unhandledmessage an unhandled exception of type systemstackoverflowexception occurred in mscorlibdllthis is visual studio 2013 update 3relevant section of stack tracesystemruntimeserializationdllsystemruntimeserializationjsonjsondatacontractwritejsonvaluesystemruntimeserializationxmlwriterdelegator jsonwriter object obj systemruntimeserializationjsonxmlobjectserializerwritecontextcomplexjson context systemruntimetypehandle declaredtypehandle unknownsystemruntimeserializationdllsystemruntimeserializationxmlobjectserializerwritecontextinternalserializesystemruntimeserializationxmlwriterdelegator xmlwriter object obj bool isdeclaredtype bool writexsitype int declaredtypeid systemruntimetypehandle declaredtypehandle unknownsystemruntimeserializationdllsystemruntimeserializationxmlobjectserializerwritecontextinternalserializereferencesystemruntimeserializationxmlwriterdelegator xmlwriter object obj bool isdeclaredtype bool writexsitype int declaredtypeid systemruntimetypehandle declaredtypehandle unknownlightweight function systemruntimeserializationdllsystemruntimeserializationjsonjsondatacontractwritejsonvaluesystemruntimeserializationxmlwriterdelegator jsonwriter object obj systemruntimeserializationjsonxmlobjectserializerwritecontextcomplexjson context systemruntimetypehandle declaredtypehandle unknownsystemruntimeserializationdllsystemruntimeserializationxmlobjectserializerwritecontextserializeandverifytypesystemruntimeserializationdatacontract datacontract systemruntimeserializationxmlwriterdelegator xmlwriter object obj bool verifyknowntype systemruntimetypehandle declaredtypehandle systemtype declaredtype unknownsystemruntimeserializationdllsystemruntimeserializationjsonxmlobjectserializerwritecontextcomplexjsonserializewithxsitypesystemruntimeserializationxmlwriterdelegator xmlwriter object obj systemruntimetypehandle objecttypehandle systemtype objecttype int declaredtypeid systemruntimetypehandle declaredtypehandle systemtype declaredtype unknownsystemruntimeserializationdllsystemruntimeserializationxmlobjectserializerwritecontextinternalserializesystemruntimeserializationxmlwriterdelegator xmlwriter object obj bool isdeclaredtype bool writexsitype int declaredtypeid systemruntimetypehandle declaredtypehandle unknownsystemruntimeserializationdllsystemruntimeserializationxmlobjectserializerwritecontextinternalserializereferencesystemruntimeserializationxmlwriterdelegator xmlwriter object obj bool isdeclaredtype bool writexsitype int declaredtypeid systemruntimetypehandle declaredtypehandle unknownlightweight function systemruntimeserializationdllsystemruntimeserializationjsonjsonclassdatacontractwritejsonvaluecoresystemruntimeserializationxmlwriterdelegator jsonwriter object obj systemruntimeserializationjsonxmlobjectserializerwritecontextcomplexjson context systemruntimetypehandle declaredtypehandle unknownsystemruntimeserializationdllsystemruntimeserializationjsonjsondatacontractwritejsonvaluesystemruntimeserializationxmlwriterdelegator jsonwriter object obj systemruntimeserializationjsonxmlobjectserializerwritecontextcomplexjson context systemruntimetypehandle declaredtypehandle unknownsystemruntimeserializationdllsystemruntimeserializationxmlobjectserializerwritecontextserializewithoutxsitypesystemruntimeserializationdatacontract datacontract systemruntimeserializationxmlwriterdelegator xmlwriter object obj systemruntimetypehandle declaredtypehandle unknownsystemruntimeserializationdllsystemruntimeserializationjsondatacontractjsonserializerinternalwriteobjectcontentsystemruntimeserializationxmlwriterdelegator writer object graph unknownsystemruntimeserializationdllsystemruntimeserializationjsondatacontractjsonserializerinternalwriteobjectsystemruntimeserializationxmlwriterdelegator writer object graph unknownsystemruntimeserializationdllsystemruntimeserializationxmlobjectserializerwriteobjecthandleexceptionssystemruntimeserializationxmlwriterdelegator writer object graph systemruntimeserializationdatacontractresolver datacontractresolver unknownsystemruntimeserializationdllsystemruntimeserializationjsondatacontractjsonserializerwriteobjectsystemxmlxmldictionarywriter writer object graph unknownsystemruntimeserializationdllsystemruntimeserializationjsondatacontractjsonserializerwriteobjectsystemiostream stream object graph unknownmicrosoftvisualstudiowebpageinspectorruntimedllmicrosoftvisualstudiowebpageinspectorruntimetracingjsonutilityserializeobject data systemiostream outputstream unknownmicrosoftvisualstudiowebpageinspectorruntimedllmicrosoftvisualstudiowebpageinspectorruntimetracingrequestdatahttphandlersystemwebihttphandlerprocessrequestsystemwebhttpcontext context unknownsystemwebdllsystemwebhttpapplicationcallhandlerexecutionstepsystemwebhttpapplicationiexecutionstepexecute unknownsystemwebdllsystemwebhttpapplicationexecutestepsystemwebhttpapplicationiexecutionstep step ref bool completedsynchronously unknownsystemwebdllsystemwebhttpapplicationpipelinestepmanagerresumestepssystemexception error unknownsystemwebdllsystemwebhttpapplicationbeginprocessrequestnotificationsystemwebhttpcontext context systemasynccallback cb unknownsystemwebdllsystemwebhttpruntimeprocessrequestnotificationprivatesystemwebhostingiis7workerrequest wr systemwebhttpcontext context unknownsystemwebdllsystemwebhostingpipelineruntimeprocessrequestnotificationhelpersystemintptr rootedobjectspointer systemintptr nativerequestcontext systemintptr moduledata int flags unknownsystemwebdllsystemwebhostingpipelineruntimeprocessrequestnotificationsystemintptr rootedobjectspointer systemintptr nativerequestcontext systemintptr moduledata int flags unknownnative to managed transition managed to native transition systemwebdllsystemwebhostingpipelineruntimeprocessrequestnotificationhelpersystemintptr rootedobjectspointer systemintptr nativerequestcontext systemintptr moduledata int flags unknownsystemwebdllsystemwebhostingpipelineruntimeprocessrequestnotificationsystemintptr rootedobjectspointer systemintptr nativerequestcontext systemintptr moduledata int flags unknownappdomain transition,"['asp.net', '.net']" +787170,is there a way to convert owinrequest to httprequestbase i am writing a piece of owin middleware where i need to use some legacy code which uses httprequestbase as method argument the legacy code does not follow solid so it is impossible to extend it to use owinrequest instead of httprequestbaseis there an extension or a way to convert an owinrequest into a httprequestbase,['c#'] +787299,how to install ruby 214 on ubuntu 1404 i dont know how to install the latest ruby on ubuntu first i installed the default ruby 193 usingsudo aptget install rubythen i tried to install the 20 version usingsudo aptget install ruby20my version of ruby is still ruby 193p484 20131122 revision 43786 x86 64linuxwhat should i do,['ruby'] +787321,adding sections separated by dates to uitableview in swift i am a complete rookie at swift and ios programming so youll have to forgive the perhaps simple question i have created a tableview which thisplays the contents of an array strings at the press of a button now i would like to group these strings in tableview sections sorted by datein more detail when the user taps the button the string should be inserted at index 0 of the array and be thisplayed in a section with a header of todays date if there is values older than todays date in the array these should be thisplayed in a separate section for that date each section should correspond to a 24 hour day and thisplay all the strings added during that dayheres some sample code of what i have achieved so farvar testarraystringvar sectionsintablestringiboutlet weak var testtable uitableviewibaction func savebuttonsender anyobject testarrayinsertstrtest atindex 0testtablereloaddatafunc numberofsectionsintableviewtableview uitableview int return sectionsintablecountfunc tableviewtableview uitableview numberofrowsinsection section int int return testarraycountfunc tableviewtableview uitableview cellforrowatindexpath indexpath nsindexpath uitableviewcell var cell uitableviewcellstyle uitableviewcellstyledefault reuseidentifier cell celltextlabeltext stringtestarrayindexpathrow return celli really do not know how to manage the sections part hopefully someone can point me in the right direction thanks,['ios'] +787424,celery rabbitmq a socket error ocurred i am using celery within django with rabbitmq as the broker on heroku my rabbitmq service is cloudamqp tough on heroku if relevant weve been having somewhat frequent memory leaks that i have been trying to plug but generally service is not degraded when it happenswhen the site is heavily trafficked like today i start getting occasional errors like the followingcould not log in a socket error occurredthe task is completely thrown out and not registered anywhere this is obviously a businesscritical problem my celery settings are belowbroker url osgetenvcloudamqp url default amqpcelery task serializer picklecelery result serializer jsoncelery accept content pickle jsoncelery enable utc true celery result backend djcelerybackendsdatabasedatabasebackendcelery store errors even if ignored truecelery send task error emails truecelery result backend falsecelery imports businessadmin mainsiteviews utilscrons mainsiteforms broker pool limit 5 trying to clean up this memory leakceleryd max tasks per child 5celeryd task time limit 6060i am a bit new to celery so i am happy to provide as followup whatever logsetc will be helpful but i am not even sure what to provide at this point is there anything obvious in my settings or environment that seems like it could be causing this problem when heavily trafficked,['python'] +787475,how do i set uibutton background color forstate uicontrolstatehighlighted in swift i can set the background color for a button but i cannot work out how to set the background color for uicontrolstatehighlighted is it even possible or do i need to go down the setbackgroundimage path,['ios'] +787480,resharper the build could not be started there are multiple projects in the solution at when trying to run nunit tests with resharper the following message appears in a dialog box and the tests are not runthe build could not be started there are multiple projects in the solution at name of the csproj filei have this problem with resharper 821i have several projects in my solution most of the projects are class libraries one of the projects is a web site not project exactly another one is a web application the web site and the web application projects are located in the same directory the web site is set to be built only in the release buildi have this problem only in the web application project when i try to run some embedded tests in this project i do not have this problem in other class library projectsthe problem was in jetbrains bug tracker but was closed perhaps there some workaroundupdatewhen i project unload project on the web site the problem thisappears,['c#'] +787662,how to use uiremotenotificationtypevoip from documentation for setkeepalivetimeouthandler method of uiapplicationin ios 8 and later voiceoverip voip apps register for uiremotenotificationtypevoip push notifications instead of using this method using push notifications eliminates the need for a timeout handler to check in with the voip service instead when a calls arrives for the user the voip service sends a voip push notification to the useras device upon receiving this notification the device launches or wakes the app as needed so that it can handle the incoming callbut i cannot find anything about it is this a thing,['ios'] +787697,android v21 themeappcompat color accent is ignored no padding on dialogs i am using actionbaractivity from the android 5 sdk and here is my themexml for v21style nameapptheme light parentthemeappcompatlightdarkactionbar item nameandroidcolorprimarycolorabc1item item nameandroidcolorprimarydarkcolorabc2item item nameandroidcoloraccentcolorabc3itemstylebut the colors are ignored and are replaced by a default teal color and all the dialogs appear without paddingalso padding is also ignored in other places like custom toast problem only occurs in lollipop devices editthe padding problem was due to fitssystemwindow and i got it fixed usingthis questionbut the accent color problem is still there and it does not just affect dialogs but the whole app,['android'] +787724,building libvlc for x86 i have been trying to use libvlc for android and i followed the instructions at and got it to work perfectly for arm however when trying to compile it to x86 i setexport android abix86and then compiled in the same way but now i have a problem as it fails to compile heres a truncated build logvlcandroid sh compileshvlc source foundbuilding toolsyou are ready to build vlc and its contribsbuilding the contribsgenerating egl pkgconfig filegenerating glesv2 pkgconfig fileguessing build system x86 64linuxgnucreating configuration file configmakbootstrap completedconfigstatus executing libtool commandstype make make install to compile and install speexcd speexdsp make installmake1 entering directory homeuservlcandroidvlccontribcontribandroidi686linuxandroidspeexdspmaking install in libspeexdspmake2 entering directory homeuservlcandroidvlccontribcontribandroidi686linuxandroidspeexdsplibspeexdsp cc resampleloin file included from resamplec1040resample neonh14221 error redefinition of inner product single static inline float inner product singleconst float a const float b unsigned int len in file included from resamplec10resample sseh4021 note previous definition of inner product single was here static inline float inner product singleconst float a const float b unsigned int len make2 resamplelo error 1make2 leaving directory homeuservlcandroidvlccontribcontribandroidi686linuxandroidspeexdsplibspeexdspmake1 installrecursive error 1make1 leaving directory homeuservlcandroidvlccontribcontribandroidi686linuxandroidspeexdspmake speexdsp error 2as far as i can tell in that project for some reason both the arm headers and the sse headers are being included causing a redefinition error however i do not know why or what to try to fix it any suggestions would be much appreciated,['android'] +787844,ticks for typerange html input after reading this i was wondering if it is possible to show ticks in chrome and firefox for a typerange number input the closest thing i could find on this subject is this,"['html', 'css']" +787912,how to run linq let statements in parallel i have code like thisvar list new listint 1 2 3 4 5var result from x in listasparallel let a longrunningcalc1x let b longrunningcalc2x select new a blet us say the longrunningcalc methods each take 1 second the code above takes about 2 seconds to run because while the list of 5 elements is operated on in parallel the two methods called from the let statements are called sequentiallyhowever these methods can safely be called in parallel also they obviously need to merge back for the select but until then should run in parallel the select should wait for themis there a way to achieve this,['c#'] +788033,difference between java enum with no values and utility class with private constructor a common thing to do to utility classes is to give them a private constructorpublic final class utilclass private utilclass but unfortunately some tools do not like that private constructor they may warn that it is never called within the class that it is not covered by tests that the block does not contain a comment etca lot of those warnings go away if you do this insteadpublic enum utilclass my question is besides the unending hatred of future developers what important differences are there between an enum with no values and a class with a private constructor in javanote that i am not asking whats the advantage of a java enum versus a class with public static final fields i am not deciding between whether a list of things should be a bunch of constants or an enum i am deciding between putting a bunch of functions in a constructorless class or a valueless enumalso note that i do not actually want to do this i just want to know the tradeoffs as part of general language knowledgefor example using an enum pollutes the autocomplete with useless methods like utilclassvalues what other downsides are there upsides,['java'] +788111,thisplay a recyclerview in fragment i am trying out the new recyclerview in android lollipop and i am stucki am trying to receive a list with an icon and a textview to the right of the icon inside a fragmenti found this great tutorial on how to set up a recyclerview i have followed every point and only changed the item layoutxml to fit my needsthe project builds without any errors but when it launches on my device i am getting this errorjavalangruntimeexception unable to start activity componentinfocomfredrikaldgardmaterialcolorscomfredrikaldgardmaterialcolorsmainactivity javalangnullpointerexception attempt to invoke virtual method void androidsupportv7widgetrecyclerviewsetlayoutmanagerandroidsupportv7widgetrecyclerviewlayoutmanager on a null object referencei have tried to google the problem but i am quite an amateur with android developmentheres my mainactivityoverrideprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main 1 get a reference to recyclerview recyclerview recyclerview recyclerview findviewbyidridlist 2 set layoutmanger recyclerviewsetlayoutmanagernew linearlayoutmanagerthis this is data fro recycler view itemdata itemsdata new itemdataindigordrawablecircle new itemdataredrdrawablecolor ic launcher new itemdatabluerdrawableindigo new itemdatagreenrdrawablecircle new itemdataamberrdrawablecolor ic launcher new itemdatadeep orangerdrawableindigo 3 create an adapter myadapter madapter new myadapteritemsdata 4 set adapter recyclerviewsetadaptermadapter 5 set item animator to defaultanimator recyclerviewsetitemanimatornew defaultitemanimatorand my myadapterpublic class myadapter extends recyclerviewadaptermyadapterviewholder private itemdata itemsdatapublic myadapteritemdata itemsdata thisitemsdata itemsdata create new views invoked by the layout manageroverridepublic myadapterviewholder oncreateviewholderviewgroup parent int viewtype create a new view view itemlayoutview layoutinflaterfromparentgetcontext inflaterlayoutitem layout null create viewholder viewholder viewholder new viewholderitemlayoutview return viewholder replace the contents of a view invoked by the layout manageroverridepublic void onbindviewholderviewholder viewholder int position get data from your itemsdata at this position replace the contents of the view with that itemsdata viewholdertxtviewtitlesettextitemsdatapositiongettitle viewholderimgviewiconsetimageresourceitemsdatapositiongetimageurl inner class to hold a reference to each item of recyclerviewpublic static class viewholder extends recyclerviewviewholder public textview txtviewtitle public imageview imgviewicon public viewholderview itemlayoutview superitemlayoutview txtviewtitle textview itemlayoutviewfindviewbyidriditem title imgviewicon imageview itemlayoutviewfindviewbyidriditem icon return the size of your itemsdata invoked by the layout manageroverridepublic int getitemcount return itemsdatalengthedit heres the fragmentpublic class colorsfragment extends fragment public colorsfragment override public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate view rootview inflaterinflaterlayoutfragment colors container false return rootview what has possibly gone wrong,"['java', 'android']" +788208,user authentication with grape and devise i have difficulties to understand and also properly implement user authentication in apis in other words i have serious problem to understand the integration of grape api with frontend frameworks such as backbonejs angularjs or emberjs i am trying to pivot all different approaches and read a lot about that but google returns me truly bad resources and it seems to me like there is no really good article on this topic rails and user authentication with devise and frontend frameworksi will describe my current pivot and i hope you can provide me some feedback on my implementation and maybe point me to the right directioncurrent implementationi have backend rails rest api with following gemfilei will purposely shorten all file codegem rails 416gem mongoid 400gem devisegem grapegem rackcors require rackcorsmy current implementation has only apis with following routesroutesrbapi base api apibase get versionpostsformat get versionpostsidformat post versionpostsformat delete versionpostsidformat post versionusersauthenticateformat post versionusersregisterformat delete versionuserslogoutformati created have following model userrbclass user include mongoiddocument devise database authenticatable registerable recoverable rememberable trackable validatable field email type string default field encrypted password type string default field authentication token type string before save ensure authentication token def ensure authentication token selfauthentication token generate authentication token end private def generate authentication token loop do token devisefriendly token break token unless userwhereauthentication token tokenfirst end end endin my controllers i created following folder structure controllersapiv1 and i have created following shared module authentication authenticationrbmodule api module v1 module authentication extend activesupportconcern included do before do error401 unauthorized 401 unless authenticated end helpers do def warden envwarden end def authenticated return true if wardenauthenticated paramsaccess token user userfind byauthentication token paramsaccess token end def current user wardenuser user end end end end endendso every time when i want to ensure that my resource will be called with authentication token i can simply add this by calling include apiv1authentication to the grape resourcemodule api module v1 class posts grapeapi include apiv1defaults include apiv1authenticationnow i have another grape resource called usersusersrb and here i implement methods for authentication registration and logouti think that i mix here apples with pears and i should extract the loginlogout process to another grape resource sessionmodule api module v1 class users grapeapi include apiv1defaults resources users do desc authenticate user and return user object access token params do requires email type string desc user email requires password type string desc user password end post authenticate do email paramsemail password paramspassword if emailnil or passwordnil errorerror code 404 error message invalid email or password 401 return end user userfind byemail emaildowncase if usernil errorerror code 404 error message invalid email or password 401 return end if uservalid passwordpassword errorerror code 404 error message invalid email or password 401 return else userensure authentication token usersave status201status ok token userauthentication token end end desc register user and return user object access token params do requires first name type string desc first name requires last name type string desc last name requires email type string desc email requires password type string desc password end post register do user usernew first name paramsfirst name last name paramslast name password paramspassword email paramsemail if uservalid usersave return user else errorerror code 404 error message invalid email or password 401 end end desc logout user and return user object access token params do requires token type string desc authenticaiton token end delete logout do user userfind byauthentication token paramstoken if usernil userremove authentication token status200 status ok token userauthentication token else errorerror code 404 error message invalid token 401 end end end end endendi realize that i present here a ton of code and it might not make sense but this is what i currently have and i am able to use the authentication token for calls against my api which are protected by module authenticationi feel like this solution is not good but i really looking for easier way how to achieve user authentication through apis i have several questions which i listed belowquestionsdo you think this kind of implementation is dangerous if so why i think that it is because of the usage of one token is there a way how to improve this pattern i have also seen implementation with separate model token which has expiration time etc but i think this is almost like reinventing wheel because for this purpose i can implement oauth2 i would like to have lighter solutionit is good practice to create new module for authentication and include it only into resources where it is neededdo you know about any good tutorial on this topic implementingrails devise grape additionally do you know about any goodopensource rails project which is implemented this wayhow can i implement it with different approach which is more saferi apologize for such a long post but i hope that more people has the same problem and it might help me to find more answers on my questions,['ruby-on-rails'] +788243,how to set navigation mode list on toolbar new appcompat v7 21 now all methods related to navigation modes in the actionbar class such as setnavigationmode are now deprecatedthe documentation explainsaction bar navigation modes are deprecated and not supported by inline toolbar action bars consider using other common navigation patterns insteadin my current application there is a spinner on actionbar how do i apply navigation mode list on the new widget toolbar in the new version appcompat v7 21thanks in advance,['android'] +788276,what is the purpose of the extension method createperowincontext in owin implementation by microsoft i am a newbie in aspnet and currently learning aspnet identity i know it is built on top of owin implementation by microsoft and i am also still learning that too so i came across the extension method createperowincontext in the owin startup code and i do not see a clear purpose of using it is it some kind of dependency injection container what is the real purpose of the method in what case it should be applied,['asp.net'] +788368,ios autolayout frame size not set in viewdidlayoutsubviews i am working on a keyboard for ios 8 using autolayout to place the buttons on the viewwhen i am changing the layout using constraints everything is appearing correctly on the screen but when i want to know the views frame size i do not get the right sizefor example i press a key the keyboard layout changes and layouts everything according to my constraints then i want to know the size of any button on the screen i do that in viewdidlayoutsubviews and get that result in the console20141029 122709088 keyboard219360674 view did layout subviews20141029 122709088 keyboard219360674 inf inf 0 0the button has the correct size and correct position but when trying to get its frame the size is not setwhere do i have to put my code when it is not working in viewdidlayoutsubviewsi found a lot of questions on stackoverflow and other websited but none of them covered my question,"['ios', 'iphone']" +788420,after upgrading xcode gives the package does not contain an infoplist error when archiving i have an ios 7 app in the app store which has many inapp purchases the inapp purchases are simply new json data structures that i have hosted with apple the iaps used to submit perfectly but i just upgraded to xcode 61 when i upgraded my machine from mountain lion to yosemite now whenever i archive a new iap package or rearchive an old one that submitted properly last week i getunable to validate your application the package does not contain an infoplistwhen i click on my target in the navigator pane build settings packaging shows infoplist file as north carolinapittsburghcontentinfoplist debug and release subheadings show the same informationproduct name is north carolinapittsburgh the contentinfoplist file is in the supporting files folder of my target in the navigator pane in it i have keys for contentversion value set to 20 iapproductidentifierbundle versions string short value set to 20 finally in the products folder of the navigator i have north carolinapittsburgh next to the red target icon and the words are in red how can i get this archive to validate properly,"['ios', 'iphone']" +788452,eclipse unable to clean build output i have an eclipse 441 working set consisting of 60 projects the number may be relevant as it takes more time to refresh the workspace occasionally i encounter build failures because eclipse is unable to clean the output folder before buildit turned out that the process which locks the file is eclipse itselfit also turned out that files being locked are always of xml content particularly if i define resources with foo extension as xml files via preferences general content types there is a good chance they will be locked too once they are copied to the output pathi thought the problem was caused by all xml resources being validated automatically so i added exclusion filters 1st and even thisabled xmlxsd validation entirely the problem stopped occurring that often but still emerges from time to time refreshing or closingreopening a project is not helpfulthe only remedy is restarting eclipse or running unlocker every 12 hour which is not very convenientany ideas how to solve or at least further diagnose this,['java'] +788528,xcode 61 iphoneipad storyboard trying to design iphone ui on xcodes new storyboardthis seems a little haphazard for designing just iphone uii expected some form of iphone ipad extendable boundaries or lines but all i can find is this one single storyboard is it really just the single storyboard now or am i missing some additional controls,"['ios', 'iphone']" +788545,how to pass array to odata function in aspnet web api implementation the specification of odata v4 states that it must be possiblecomplex types and arrays can only be passed to functions through parameter aliaseswhen i am trying to pass an array with odata parameter aliases an exception occurstestentitiesnstestfunctionarrayherepp123results inunable to cast object of type edmvalidcoremodelprimitivetype to type microsoftodataedmiedmstructuredtypethe interesting thing is that the metadata document is correctly composed for such casesfunction nametestfunction isboundtrue parameter namebindingparameter typecollectionnstestentity parameter namearrayhere typesystemint32 returntype typecollectionnstestentityfunctionis it possible with aspnet mvc web api 2 odata to pass an array to odata function in query stringupdate here is the code to build the edm model and the controller var builder new odataconventionmodelbuilder buildernamespace ns builderentitysettestentitytestentities builderentitytypetestentitycollection functiontestfunction returnscollectionfromentitysettestentitytestentities parameterintarrayherecontrollerpublic class testentitiescontroller odatacontroller public ienumerabletestentity testfunctionint arrayhere throw new notimplementedexception marking parameter with fromodatauri does not solve the problemupdate 2here is the stack traceat microsoftodatacoreuriparsertypepromotionutilscanconverttosinglevaluenode sourcenodeornull iedmtypereference sourcereference iedmtypereference targetreferenceat microsoftodatacoreuriparserparsersmetadatabindingutilsconverttotypeifneededsinglevaluenode source iedmtypereference targettypereferenceat microsoftodatacoreuriparserparsersfunctioncallbinderbindsegmentparametersodatauriparserconfiguration configuration iedmoperation functionoropertion icollection1 segmentparametertokensat microsoftodatacoreuriparserparsersodatapathparsertrybindingparametersandmatchingoperationstring identifier string parenthesisexpression iedmtype bindingtype odatauriparserconfiguration configuration icollection1 boundparameters iedmoperation matchingoperationat microsoftodatacoreuriparserparsersodatapathparsertrycreatesegmentforoperationodatapathsegment previoussegment string identifier string parenthesisexpressionat microsoftodatacoreuriparserparsersodatapathparsercreatenextsegmentstring textat microsoftodatacoreuriparserparsersodatapathparserparsepathicollection1 segmentsat microsoftodatacoreuriparserparsersodatapathfactorybindpathicollection1 segments odatauriparserconfiguration configurationat microsoftodatacoreuriparserodatauriparserparsepathimplementationat microsoftodatacoreuriparserodatauriparserinitializeat systemwebodataroutingdefaultodatapathhandlerparseiedmmodel model string serviceroot string odatapath boolean enableuritemplateparsingat systemwebodataroutingdefaultodatapathhandlerparseiedmmodel model string serviceroot string odatapathat systemwebodataroutingodatapathrouteconstraintmatchhttprequestmessage request ihttproute route string parametername idictionary2 values httproutedirection routedirectionat systemwebhttproutinghttprouteprocessconstrainthttprequestmessage request object constraint string parametername httproutevaluedictionary values httproutedirection routedirectionat systemwebhttproutinghttprouteprocessconstraintshttprequestmessage request httproutevaluedictionary values httproutedirection routedirectionat systemwebhttproutinghttproutegetroutedatastring virtualpathroot httprequestmessage requestat systemwebhttpwebhostroutinghttpwebroutegetroutedatahttpcontextbase httpcontext,['c#'] +788574,in clangformat what do the penalties do the clangformat sytle options documentation includes a number of options called penaltyx the documentation does not explain how these penalties should be used can you describe how to use these penalty values and what effect they achieve perhaps with an example,['c++'] +788639,ios 61 simulator on osx 1010 yosemite i am developing an application based on ios 61 and after upgrading to osx yosemite can not run the simulatori have been reading on stackoverflow and some people say that osx 1010 no longer supports ios 6 only 7 and 8i chose to develop on ios 6 because of the large amount of users that still use this versioni have seen this topic in os x 1010 yosemite beta how do i test using ios 61 simulator but i would like an opinion on the path to be taken i return to osx 109 maverick or advance to ios 71thank you in advance,['ios'] +788643,prevent retrofit from encoding my http request body i am trying to pass a string of the format below as the body of a http post requestparam1param1param2param2param3param3but retrofit encodes my body so that becomes u003d and becomes u0026 and i end up with a string which actually looks like thisparam1u003dparam1u0026param2u003dparam2u0026param3u003dparam3how can i prevent thatmy retrofit rest api is defined as followspublic interface restapi postoauthtoken public void getaccesstokenbody string requestbody callbackresponse response,['java'] +788823,proper russian month string translation java i want to convert a date in to russian and using the code belowsimpledateformatgetdateinstancesimpledateformatlonglocaleformatdatewhere locale is of type localethe problem is months are not parsed correctly january is coming as n122nn it should be n122nn and february is coming as n2nn should be n2nnand so onone idea is to convert incorrect months to proper ones in my logicis there any thing by which java do this automatically thanks,['java'] +788909,socketio clients to receive offline messages when coming back environmentnodejssocketioproblemclient a and client b both connect to serverclient b is offlineclient a sends a message to client bclient b still offlineclient b connect to server againproblem client b cannot receive the message from aserver codevar clients iosocketsonconnection function socket socketononline function data if clientsdatausername clientsdatausername socket iosocketsemitmessage datauser online nowsocketonsay function data if datato all iosocketsemitmessage datamessage else to specific client clientsdatatoemitmessage datamessage descriptionclient b connected to server at one place firstduring the period of client bs offline client a sent messages to client b then client b connect to server at another place again and client b needs to receive those message from client a how to make it workthis is my first question here i am desperately expecting any suggestion from youthanks in advance,['javascript'] +789033,ios testflight beta app get new advertising identifier in each run i am getting new advertising identifier each time i run a beta app uploaded to testflight in itunesconnect is it a normal behaviour will it happen for appstore app too i am using the advertising identifier to identify users and his credentials in some context but if it changes in every run the user have to activate in each run asidentifiermanager sharedmanager advertisingidentifier uuidstringin testflight build in 3 runs i got eg id 3e841b61b00744d3b6546c857122301eid 2ec3682ad1624ce6b07a8b73282456a4id 1d8513ea07574e5f8ceeb6c4f782e966this does not happen in debug or ad hoc builds can anybody shed some light on itthanks in advance,['ios'] +789044,show segue in xcode 6 presents the viewcontroller as a modal in ios 7 i have two view controllers in my iphone application built with swift built with xcode 61 and uses storyboardsthe first view controller is embedded in a navigation controller in the storyboard and the segue for the second view controller is a show segue when the application is run it properly shows the transition as a push in ios 8x but in ios 7x it appears as a modal without the navigation barmy application requirement is to show the transition as a push regardless of whether it is ios 7 or ios 8 any ideas to get this working as push in both versions of the iosi saw a related post where this issue is mentioned but could not find a solution to the problem adaptive segue in storyboard xcode 6 is push deprecatedany help is appreciatedthanks,['ios'] +789056,angularjs access local json files i am new to angularjs and i have been searching on the web the whole day just to find a solution in getting data from a local json file without having to use a localhost for my webapp unfortunately i have not found any i tried using httpget but i get cross origin error is there no other way that i could get the data from my local json file without having to locally host my webappdoes angularjs have any other function to get data from local json files without having to use its httpget,['javascript'] +789224,c get address of variable without operator i have got a class that has overloaded unary operator the objects of that type were created using new so address of variable was accessible but now i need to use static object is it possible to get its address,['c++'] +789284,gwt editor framework for polymorphic types i have following class hierarchyclass a string id notemptymessagetitle cannot be empty string title string description string commentsclass b extends a string manufacturerclass c extends a long sizenow i want an editor which reuses editor of a and also works well with values of b and c so i went ahead with followingclass editora extends composite implements editora uifield textbox id uifield textbox title uifield textbox description constructor etcclass editorb extends composite implements editorb pathaa uifield editora editora uifield textbox manufacturer public interface driver extends simplebeaneditordriverb editorb initializationclass editorc extends composite implements editorc pathaa uifield editora editora uifield longbox size public interface driver extends simplebeaneditordriverc editorc initializationthen i choose the editor based on actual type being edited driver flushes object correctly but when i show constraint violations every violation is duplicated before its sent to widgets eg atitle canat be empty atitle canat be emptyaworse if i include multiple such widgets with path annotation in one form violations keep increasing so in the setup below 3 violations are setclass editorafooter extends composite implements editora uifield textbox commentsclass editorb extends composite implements editorb pathaa uifield editora editora uifield textbox manufacturer pathaa uifield editorafooter editorafooter public interface driver extends simplebeaneditordriverb editorb initializationworkaround is not to used editora inside editorb instead copy all widgets of editora and paste into editorbuixml and then only single violations are set as expected however thatas a lot of code duplication as editora is pretty complex in realitywhatas wrong with this kind of editor setup iam essentially following guidelines mentioned here large objectsupdatei debugged it further no success yetin simpleviolationjava following code is able to find 3 matching delegates for 1 propertypublic static void pushviolationsiterablesimpleviolation violations editordriver driver keymethod keymethod if violations null return delegatemap delegatemap delegatemapofdriver keymethod for each violation for simpleviolation error violations object key errorgetkey listabstracteditordelegate delegatelist delegatemapgetkeydelegatelist above has 2 or 3 editors depending on my configuration probable reason is because subtype has access to all supertype properties so subtype editor driver can be considered a delegate for that property supertypes editor is a delegate in itself since everyone implements editor everyone is responsible for setting violations for every editor involved it pushes violation to same textbox which shows violation multiple timesis this expected if yes how to correctly use editor framework for polymorphic types and thisplay constraintviolation only once,['java'] +789287,uibutton with ib designable throws runtime attribute warning and does not render in interface builder i am running xcode 61 and i have been using ib designable with ibinspectable for quite a few projects already but all of the sudden it just does not work anymore i have created subclassed buttons that arrange the image and the title vertically centred above each other and enable the user to set a border width and color through ib with ibinspectablethe following warning is logged and there is no preview available of my code in drawrectwarning ib designables ignoring user defined runtime attribute for key path spacingbetweenlabelandimage on instance of uibutton hit an exception when attempting to set its value uibutton 0x7f9278591260 setvalueforundefinedkey this class is not key value codingcompliant for the key spacingbetweenlabelandimagestill runtime it renders like i intended it to render and it also honours that same custom spacing i have added through ibheres the code of the menubutton that rearranges the button and the titleimport hamburgerbuttonhib designableinterface hamburgerimagebutton hamburgerbuttonproperty ibinspectable cgfloat spacingbetweenlabelandimageendimplementationimport hamburgerimagebuttonhimplementation hamburgerimagebutton voiddrawrectcgrectrect super drawrectrect cgsize imagesize selfimageviewframesize cgsize titlesize selftitlelabelframesize move the label left and the image right by half the width cgfloat leftinset titlesizewidth 2 cgfloat rightinset imagesizewidth 2 cgfloat halfspacing selfspacingbetweenlabelandimage 0 0 selfspacingbetweenlabelandimage 2 cgfloat topinset imagesizeheight 2 halfspacing cgfloat bottominset titlesizeheight 2 halfspacing uiedgeinsets imageinsets uiedgeinsetsmakebottominset leftinset bottominset leftinset uiedgeinsets titleinsets uiedgeinsetsmaketopinset rightinset topinset rightinset selfimageedgeinsets imageinsets selftitleedgeinsets titleinsetsendyouve probably noticed it inherits hamburgerbutton this basic hamburger button does not have an image and it only draws the border around the button this basic hamburger button has exactly the same problem it does not draw it is border in drawrect in ib and it has the same type of errors heres that code for sake of completenessimport uikituikithib designableinterface hamburgerbutton uibuttonproperty ibinspectable cgfloat borderwidthproperty ibinspectable uicolor bordercolorendimplementationimport hamburgerbuttonhimport quartzcorequartzcorehimplementation hamburgerbutton voidcopyinspectables selflayerborderwidth selfborderwidth selflayerbordercolor selfbordercolorcgcolor voiddrawrectcgrectrect self copyinspectablesendi do not really understand why it just throws a warning and nothing else i did not really change what i did i have checked the storyboard it is ios 7 and up meant to run in xcode 6 latestit complains about not being able to find that value on uibutton and that is a bit weird because i have subclassed itupdate so i changed everything around and it worked now it craps out again without changing anything else i think there is a bug in xcode 61,"['ios', 'objective-c']" +789305,error on g 482 at list methodargument default initialization i am trying the new features of c11 and i found an issue this is my codeinclude iostreaminclude listinclude stringusing namespace stdclass a public int f liststring a liststring b cout asize endl cout bsize endl this line return 0 int main a a liststring lhelloworld afl return 0the execution stuck at this line line i continue debugging and it looks like the problem is here returns the number of elements in the list size type size const glibcxx noexcept return stdthistancebegin end i compile my program in this wayg stdc11 ggdb3 fpic o test testlistinitcppi am using this version of gg ubuntu 48219ubuntu1 482thanks in advance,['c++'] +789326,google maps infowindow scrolling bug how to solve for all cases it is a known bug that the google maps api shows the scrollbar for the first time clicked infowindowthe issue first timerest of the timesso i found out that adding maxwidth solved the problemfor me it does not if i set the maxwidth to 200px the scrollbar thissapears but its smaller than i needif i set 250px size i need the scrollbar persistsany idea what could i tryjsfiddle sescam ventana init function thismapa mapa function var script documentcreateelementscript scripttype textjavascript scriptsrc mapsgoogleapiscommapsapijsv3expsensorfalsecallbacksescam ventanamapsetup documentbodyappendchildscript mapsetup function var styles stylers saturation 100 featuretype roadelementtype geometrystylers visibility simplified featuretype poibusinesselementtype labelsstylers visibility simplified var styledmap new googlemapsstyledmaptypestyles name sescam var mapoptions zoom 16 scrollwheel false center new googlemapslatlng396177074 49725879 maptypecontroloptions maptypeids googlemapsmaptypeidroadmap map style var handlemarkerclick functionmarker index var navigationmenu jquerydiv jquerymenuitemeachfunctioni var button jquerybutton buttontextjquerythistext buttonaddclassjquerythisdataclass navigationmenuappendbutton if typeof infowindow undefined infowindow new googlemapsinfowindow height 380 var centro infocentrosindex helpful data infowindowsetcontent div clasescaminfowindow h3 centronombre h3 p centrolugar h3 p classtitulocoordinadorp pstrong centrocoordinadornombre strongp pa hrefmailto centrocoordinadoremail centrocoordinadoremail ap p classtituloresponsablep pstrong centroresponsablenombre strongp pa hrefmailto centroresponsableemail centroresponsableemail ap div classmenu navigationmenuhtml div div infowindowopenmarkergetmap marker var handlemenu function jquerybodyonclick menu button function var itemclass jquerythisattrclass jquerylistado itemclastoptrue trueslidedownsiblingslistadostoptrue trueslideup thisgmap new googlemapsmapdocumentgetelementbyidmapa mapoptions thisgmapmaptypessetmap style styledmap thisgmapsetmaptypeidmap style thismapmarkers thismapinfowindow new googlemapsinfowindow height 380 jquerywindowresizefunction sescam ventanagmapfitboundssescam ventanamapbounds for var i 0 i thismapmarkerslength i primero eliminamos todos los markers que pudiera haber de una visualizacia3n anterior thismapmarkersisetmapnull thismapmarkerslength 0 reseteamos el array thismapbounds new googlemapslatlngbounds var c 0 de inicio no sabemos cuantos elementos tienen realmente latitud y longitud este contador nos lo chivara var latlon lo guardamos fuera del each para poder verlo despuas si resulta que es el aonico elemeto a mostrar for var i 0 i infocentroslength i var centro infocentrosi var lat centrocordenadaslat var lon centrocordenadaslong if lat lon c latlon new googlemapslatlnglat lon var moptions position latlon map sescam ventanagmap moptionsicon var marker new googlemapsmarkermoptions sescam ventanamapmarkerspushmarker googlemapseventaddlistenermarker click handlemarkerclick googlemapseventaddlistenermarker click handlemarkerclickbindundefined marker i sescam ventanamapboundsextendlatlon if c 1 sescam ventanagmapfitboundsthismapbounds else si solo hay uno el fitbounds no hace un zoom ni un centrado correctos sescam ventanagmapsetcenterlatlon handlemenu jqueryfunction sescam ventanainitgmapa position relative paddingbottom 50mapa position absolute left 0 top 0 width 100 height 100script srcscriptdiv classgmapa script var infocentros nombre el nombre 0 texto lorem ipsum sit met hamet amid0 lugar toledo coordinador nombre ana mu00aa del mar alonso fernu00e1ndez email responsable nombre ana mu00aa del mar alonso fernu00e1ndez email cordenadas lat 39150544196 long 48019412125 nombre el nombre 1 texto lorem ipsum sit met hamet amid1 lugar toledo coordinador nombre ana mu00aa del mar alonso fernu00e1ndez email responsable nombre ana mu00aa del mar alonso fernu00e1ndez email cordenadas lat 39150544196 long 47019412125 nombre el nombre 2 texto lorem ipsum sit met hamet amid2 lugar toledo coordinador nombre ana mu00aa del mar alonso fernu00e1ndez email responsable nombre ana mu00aa del mar alonso fernu00e1ndez email cordenadas lat 39150544196 long 46019412125 nombre el nombre 3 texto lorem ipsum sit met hamet amid3 lugar toledo coordinador nombre ana mu00aa del mar alonso fernu00e1ndez email responsable nombre ana mu00aa del mar alonso fernu00e1ndez email cordenadas lat 39150544196 long 45019412125 nombre el nombre 4 texto lorem ipsum sit met hamet amid4 lugar toledo coordinador nombre ana mu00aa del mar alonso fernu00e1ndez email responsable nombre ana mu00aa del mar alonso fernu00e1ndez email cordenadas lat 39150544196 long 44019412125 script div idmapadivdiv,"['javascript', 'html', 'css']" +789434,undefined method column for foreignerconnectionadaptersforeignkeydefinition i am getting the following when i try to run a migrationnomethoderror undefined method column for foreignerconnectionadaptersforeignkeydefinition0x007fa020938740heres the migration codeclass createadvertisement activerecordmigration def change create table advertisement do t tinteger issue id null false tstring client name null false tdecimal size null false tdecimal price null false tdecimal commission amount null false tstring first payment null false tstring second payment null false ttimestamps null false tforeign key issue end endendi have foreigner 161 installed rails 420 any ideas,['ruby-on-rails'] +789452,how do i place jars in jettylib on the jetty classpath i have jetty jetty923v20140905my understanding was that jars in libjar or libext were automatically on the classpath but this may have been old behavior from jetty 8 i am trying to deploy a webapp with websockets with my deployed war file in the webapps directory jetty keeps complaining that it cannot find jars sitting right there in the jettylib directory jettyhttp jettyio jettysecurity jettyserver jettyservlet jettyutil are the ones my webapp needs that it cannot findjars placed in libext are also not picked up when i do a moduleexthow can i resolve thisto address the answer below editing the original question i have tried enabling the server module whose servermod file contains the following linesliblibservletapi31jarlibjettyschemas31jarlibjettyhttpjettyversionjarlibjettyserverjettyversionjarlibjettyxmljettyversionjarlibjettyutiljettyversionjarlibjettyiojettyversionjarfrom the command line i do java jar startjar moduleserver jettyport8182and the result is 20141030 152613907warnoejucabstractlifecyclemain failed orgeclipsejettyannotationsservletcontainerinitializersstarter2635068e javalangnoclassdeffounderror orgeclipsejettyserverhandlerjavalangnoclassdeffounderror orgeclipsejettyserverhandlerorgeclipsejettyserverhandler is right there in jettyserver jar sitting in my jettylib directory perhaps the jettyversion or jettybase variables are incorrect when i perform a listclasspathi do see all the jars in the lib directory there,['java'] +789454,aspnet application executing powershell scripts as iis usr i am building an aspnet mvc application which will operate as a wrapper for a number of powershell scripts weve written to manage day to day tasks with the end goal of making it easy for a non technical person to use the scripts i have managed to get the scripts executing nicelyvar ctx systemwebhttpcontextcurrentvar file ctxservermappathcontentpowershellpsstoreliveps1 activate a storevar shell powershellcreateshelladdcommandfile shelladdargumentodbname which store should we activatevar results shellinvoke and then process the resultsthisplay output of scriptthe problem is that the scripts are being executed as iis usr or similari need to find a way to get the iis server to execute the scripts as the current logged in user using windows authentication authentication modewindows i have seen and while that looks like it will maybe work i am not satisfied with the idea it seems to me that i should be able to do this with some c code as in the codeblock above but i have been unable to turn up anything with my searches that will do ithow can i create a powershell environment in c that will execute as a loggedin user i would settle for even reasking for credentials if necessarythanksedit 1i have looked at the pscredential object and that seems to be the right kind of thing but i still cannot figure out how i might plug it into a session overall lots of info about using it as a parameter to a cmdlet that requires a credential,"['c#', 'asp.net']" +789507,cannot print text file using java 8 in windows 7 i have created a report and exported it as a text file to print in a matrix printer however the result of the job is a blank page i did the same in ubuntu and it is printing correctlyis it a java bugthis is a example code i did to show you the problempublic class printerror extends application public static void mainstring args launchargs public void startstage stage throws printexception printerjob printerjob printerjobcreateprinterjob printerjobshowprintdialogstage printrequestattributeset printrequestattributeset new hashprintrequestattributeset printrequestattributesetaddnew copiesprinterjobgetjobsettingsgetcopies printrequestattributesetaddnew jobnametest localegetdefault docflavor flavor docflavorinput streamautosense doc mydoc new simpledocclassloaderclassgetresourceasstreamshouldbeprintedtxt flavor null docprintjob job getprintserviceprinterjobgetprintergetnamecreateprintjob jobprintmydoc printrequestattributeset private printservice getprintservicestring name for printservice printservice javaawtprintprinterjoblookupprintservices if nameequalsignorecaseprintservicegetname return printservice return null this example was created in javafx 8 and is running in java build 180b132 in windows 7i have also created a simple project at github,['java'] +789619,curl causes ssl unable to get local issuer certificate after installing homebrew php 55 on mac os yosemite following this answers steps i found that i could connect to the external ssl hosts which prompted me a error number56 error stringsslread return error 9806 beforethis problem has been fixedbut now at my day job i run into another ssl issue with another host canvas apirunning the following curl on terminal using osx native curlcurl v h accept applicationjson h contenttype applicationjson x get d userid mohit passwordpassword work fine but through php i am getting ssl certificate problem unable to get local issuer certificate so my original issue is fixed now that i use openssl in php curling but i got this new issuei did try to add a pem file to my phpini curlcainfo usrlocalcacertpem but that triggered another error error setting certificate verify locations cafile usrlocalcacertpem capath nonei am a bit puzzled i need to have the brew php curl version working for both apis now the one who was not working is working but the other one which was working is not throwing the unable to get local issuer certiciface message any wisdom would be appreciatededit curl output from php icurl support enabledcurl information 7380age 3featuresasynchdns nocharconv nodebug nogssnegotiate noidn noipv6 yeskrb4 nolargefile yeslibz yesntlm yesntlmwb yesspnego nossl yespi notlssrp yesprotocols dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtsp smtp smtps telnet tftphost x86 64appledarwin1400ssl version openssl101jzlib version 125,['php'] +789642,while sorting the map based on value some values are missing what causes this weird behaviour i am trying to sort a map based on word frequency ie based on value for that i have overridden comparator and passed to treemap but i am getting this weird outputpublic class wordfrequency public static string sentence one three two two three three four four four public static mapstring integer map public static void mainstring args map new hashmap string words sentencesplits for string word words integer count mapgetword if count null count 1 else count mapputword count comparatorstring mycomparator new comparatorstring override public int comparestring s1 string s2 if mapgets1 mapgets2 return 1 else if mapgets1 mapgets2 return 1 else return 0 sortedmapstring integer sortedmap new treemapstring integermycomparator systemoutprintlnbefore sorting map sortedmapputallmap systemoutprintlnafter sorting based on value sortedmap outputbefore sorting two2 one1 three3 four3after sorting based on valueone1 two2 three3expected outputone1 two2 four3three3,['java'] +789675,in xcode how do i use a different appicon for each target ios app i have one xcode project in xcode 61 with a 4 targets for 4 different apps that share a lot of the same source codei am trying to have each one of them show a different app icon going into project general select target app icons and launch images i see thisbut clicking on each appicon i get to the exact same app icons not the ones that i would like for each projectis this just a bug in xcode how can i use different app icons for different targets,['ios'] +789692,safari crash while taking photo in iphone 4s ios 81 i am using following code for capture photo and thisplaystore this same code working fine in iphone 5 with ios 712 but in iphone 4s with ios 81 safari will crash every time when i take photobody img iduploadpreview stylewidth 100px height 100px input iduploadimage typefile namemyphoto onchangepreviewimage script typetextjavascript function previewimage var ofreader new filereader ofreaderreadasdataurldocumentgetelementbyiduploadimagefiles0 ofreaderonload function ofrevent documentgetelementbyiduploadpreviewsrc ofreventtargetresult scriptbodydemofollowing message show in safari after take photoa problem occurred with this webpage so it was reloadedupdatenow i am doing same task on same device but with ios version 812 still same problem occured,"['ios', 'iphone']" +789913,unexpectedly found nil while unwrapping optional value in my app i am checking to see whether a post has a picture or notfor this i am usingif picturesstring nil if var image nsdata picturesstring imageviewimage uiimagedata image however it still comes up with the errorfatal error unexpectedly found nil while unwrapping an optional valuei am sure it is something easy to fix but i am quite new to this what am i doing wrong,"['ios', 'iphone']" +789966,java hotspottm 64bit server vm warning centos smartgit smartsvn on running the shell script provided with smartgit java hotspottm 64bit server vm warning you have loaded library homeusersmartgit6jnatmpcomsunjnalinuxi386libjnithispatchso which might have thisabled stack guard the vm will try to fix the stack guard now it is highly recommended that you fix the library with execstack c libfile or link it with z noexecstackalthough it opens up fine on doing a commit i get java cairomiscc380 cairo operator bounded by source assertion not reached failedsmartgithgsh line 100 394 aborted java exec vm properties xmxsmartgithg max heap size xverifynone dsmartgitvmxmxsmartgithg max heap size jar smartgit homelibbootloaderjar on researching up a bit i found64 bit library should be used if this is the cause please tell me how to do itcorrect jre isnt found downloaded a new jre and gave its path inside the shell script same warning and crashwhat could be causing this and how do i fix it,['java'] +790104,using oclazyload to lazy load a controller with stateprovider i am having issues using oclazyload with stateprovideri have specified that the controller js should be loaded in the router config and it does but it is not available to use as an ngcontroller attribute in the file loaded in templateurl uiroute config corerun rootscope state stateparams function rootscope state stateparams rootscopestate state rootscopestateparams stateparams config stateprovider urlrouterprovider function stateprovider urlrouterprovider consoleinforouting urlrouterprovider otherwiseappdashboard stateprovider stateapp abstract true url app templateurl templatesapphtml stateapporders abstract true url orders templateurl templatesordersordershtml stateappordersindex url index templateurl templatesordersindexhtml resolve deps oclazyload function oclazyload consoleinfopath ot order controller in route configmomentopathsjs controllersordersindexjs return oclazyloadload momentopathsjs controllersordersindexjs and my templateurl file starts div class id ngcontrollerordersindexcontrollerdivbut when it loads console throws the error infoordersindex controller loaded controllersordersindexjs3infonow i have finished loading the controllerorderindexjs configuirouterjs69infoorders template loaded vm304371 this is the apporders abstract template with uiview directive ready for appordersindex viewerrorerror ngareq argument ordersindexcontroller is not a function got undefined traceso the file is loaded correctly by lazyload confirmed by console output above and network tab in developer tools but it is not available in the templateurl to use as controller does it need to be aliased either in router config using controller key or in template does it need to be specifically attached to the only module in this app what am i missingps confirming that the name of the controller is in fact ordersindexcontroller core controllerordersindexcontroller model scope window function model scope window consoleinfoordersindexcontroller fired,['javascript'] +790268,material effect on button with background color i am using android v21 support library i have created a button with custom background color the material design effects like ripple reveal are gone except the elevation on click when i use the back ground color button styleandroidattrbuttonstylesmall androidbackgroundattrcolorprimary androidtextcolorcolorwhite androidtextallcapstrue androidlayout widthfill parent androidlayout heightwrap content androidtextbutton1 the following is a normal button and the effects are working just finebutton styleandroidattrbuttonstylesmall androidlayout widthfill parent androidlayout heightwrap content androidtextallcapstrue androidtextbutton1,['android'] +790287,add and tasks to celery queue and wait for the results i would add multiple tasks to celery queue and wait for results i have various ideas how i would achieve this utilising some form of shared storage memcached rethis db etc however i would have thought it is something that celery can handle automatically but i cannot find any resources onlinecode exampledef do tasksb for a in b cdelaya return call results some how,['python'] +790334,how is infinity represented in a c double i learned from the book computer systems a programmers perspective that the ie standard requires the double precision floating number to be represented using the following 64bit binary formats 1 bit for signexp 11 bits for exponentfrac 52 bits for fractionthe infinity is represented as a special value with the following patterns 0all exp bits are 1all fraction bits are 0and i think the full 64bit for double should be in the following ordersexpfracso i write the following c code to verify itcheck the infinitydouble x1 double0x7ff0 this should be the infinitydouble x2 double0x7ff01 note the extra ending 1 x2 should be nanprintfnx1 f x2 f sizeofdouble d x1x2 sizeofx2if x1 x2 printfnx1 x2else printfnx1 x2but the result isx1 921886843722740530 x2 921886843722740530 sizeofdouble 8x1 x2why is the number a valid number rather than some infinity errorwhy x1x2i am using the mingw gcc compileradd 1i modified the code as below and the validated the infinity and nan successfullycheck the infinity and nanunsigned long long x1 0x7ff0ull infinity as doubleunsigned long long x2 0xf0ull infinity as doubleunsigned long long x3 0x7ff01ull nan as doubledouble y1 double x1double y2 double x2double y3 double x3printfnsizeoflong long d sizeofx1printfnx1 f x2 f x3 f x1 x2 x3 f is good enough for outputprintfny1 f y2 f y3 f y1 y2 y3the result issizeoflong long 8x1 1inf00 x2 1inf00 x3 1snan0y1 1inf00 y2 1inf00 y3 1qnan0the detailed output looks a bit strange but i think the point is clearps it seems the pointer conversion is not necessary just use f to tell the printf function to interpret the unsigned long long variable in double formatadd 2out of curiosity i checked the bit represetation of the variables with the following codetypedef unsigned char byte pointervoid show bytesbyte pointer start int len int i for i len1 i0 i printf2x starti printfnand i tried the code belowcheck the infinity and nanunsigned long long x1 0x7ff0ull infinity as doubleunsigned long long x2 0xf0ull infinity as doubleunsigned long long x3 0x7ff01ull nan as doubledouble y1 double x1double y2 double x2double y3 double x3unsigned long long x4 x1 x2 i want to check infinityinfinitydouble y4 y1 y2 i want to check infinityinfinityprintfnx1 show bytesbyte pointerx1 sizeofx1printfnx2 show bytesbyte pointerx2 sizeofx2printfnx3 show bytesbyte pointerx3 sizeofx3printfnx4 show bytesbyte pointerx4 sizeofx4printfny1 show bytesbyte pointery1 sizeofy1printfny2 show bytesbyte pointery2 sizeofy2printfny3 show bytesbyte pointery3 sizeofy3printfny4 show bytesbyte pointery4 sizeofy4the output isx1 7ff0x2 f0x3 7ff01x4 7fe0y1 7ff0y2 f0y3 7ff801y4 f80 different with x4the strange part is though x1 and x2 have the identical bit pattern as y1 and y2 the sum x4 is different from y4andprintfny4f y4gives thisy41ind00 what does it meanwhy are they different and how is y4 obtained,['c'] +790365,canvas particles collisions and performance i am creating a web app which has an interactive background with particles bouncing around at all times there are about 200 circular particles on the screen and at most around 800 particles some of the collisions and effects that are being run for the particles are the following prototypes i wonder if i could improve the performance by using web workers to do these calculations particlesjarvisprototypegenforegroundparticles functionoptions count count count thislogoparticlesnum for var i 0 i count i thislogoparticlespushnew particle jarvisprototypegenbackgroundparticles functionoptions count count count thisbackgroundparticlesnum for var i 0 i count i thisbackgroundparticlespushnew particleoptions jarvisprototypemotion linear functionparticle pindex particles particlex particlevx particley particlevy normalizevelocity functionparticle pindex particles if particlevx particlevxinitial 1 particlevx 005 else if particlevx particlevxinitial 1 particlevx 005 if particlevy particlevyinitial 1 particlevy 005 else if particlevx particlevxinitial 1 particlevy 005 explode functionparticle pindex particles if particleisbottomout particlessplicepindex 1 else particlex particlevx particley particlevy particlevy 01 if particleslength 0 particlesmotionremovemotionexplode thisallowmenu true jarvisprototypecollision boundingbox functionparticle pindex particles if particley thisheight particleradius particley particleradius particlevy 1 ifparticlex thiswidth particleradius particlex particleradius particlevx 1 boundingboxgravity functionparticle pindex particles todo fix gravity to work properly in combination with fx and motion if particley thisheight particleradius particley particleradius particlevy 1 particlevy 5 ifparticlex thiswidth particleradius particlex particleradius particlevx 1 particlevx 5 infinity functionparticle pindex particles if particlex thiswidth particlex 0 if particlex 0 particlex thiswidth if particley thisheight particley 0 if particley 0 particley thisheight jarvisprototypefx link functionparticle pindex particles forvar j pindex 1 j particleslength j var p1 particle var p2 particlesj var particlethistance getthistancep1 p2 if particlethistance thisparticleminlinkthistance thisbackgroundctxbeginpath thisbackgroundctxstrokestyle rgbap1red p1green p1blue p1opacity particlethistance thisparticleminlinkthistance thisbackgroundctxmovetop1x p1y thisbackgroundctxlinetop2x p2y thisbackgroundctxstroke thisbackgroundctxclosepath shake functionparticle pindex particles if particlexinitial particlex thisshakeareathreshold particlexoper randbtwnthisshakefactormin thisshakefactormax 2 thiswidth else if particlexinitial particlex thisshakeareathreshold particlexoper randbtwnthisshakefactormax thisshakefactormin 2 thiswidth if particleyinitial particley thisshakeareathreshold particleyoper randbtwnthisshakefactormin thisshakefactormax 2 thisheight else if particleyinitial particley thisshakeareathreshold particleyoper randbtwnthisshakefactormax thisshakefactormin 2 thisheight particlex particlexoper particley particleyoper radialwave functionparticle pindex particles var thistance getthistanceparticle thiscenter if particleradius thisdim 085 particleradiusoper 002 else if particleradius 1 particleradiusoper 002 particleradius particleradiusoper particleradius responsive functionparticle pindex particles var newposx thislogoparticleslogooffsetx thislogoparticlesparticleradius thislogoparticlesparticlethistance thislogoparticlesparticleradius particlearrposx var newposy thislogoparticleslogooffsety thislogoparticlesparticleradius thislogoparticlesparticlethistance thislogoparticlesparticleradius particlearrposy if particlexinitial newposx particleyinitial newposy particlexinitial newposx particleyinitial newposy particlex particlexinitial particley particleyinitial motiondetect functionparticle pindex particles var isclose false var thistance null for var i 0 i thistoucheslength i var t thistouchesi var point x tclientx y tclienty var d getthistancepoint particle if d thisblackhole isclose true if d thistance thistance null thistance d if isclose if particleradius thisdim 085 particleradius 025 if particlegreen 0 particleblue 0 particlegreen 10 particleblue 10 else if particleradius particleinitialradius particleradius 025 if particlegreen 255 particleblue 255 particlegreen 10 particleblue 10 reverseblackhole functionparticle pindex particles for var i 0 i thistoucheslength i var t thistouchesi var point x tclientx y tclienty var thistance getthistancepoint particle if thistance thisblackhole var diff getpointsdifferencepoint particle particlevx diffx thistance particlevy diffy thistance furthermore in case anyone wonders i have 3 canvas layers i will add the particles rendering functionand the clear function for all canvas layers background which draws a full screen radial gradient particlesmenu canvasmenu button overlay selectors show which menu is active etcjarvisprototypebackgrounddraw function particles var that this thislogoparticlesforeachfunctionparticle i particledrawthatbackgroundctx thatlogoparticlesmotionforeachfunctionmotiontype motionindex thatmotionmotiontypecallthat particle i thatlogoparticles foregroundparticles thatlogoparticlesfxforeachfunctionfxtype fxindex thatfxfxtypecallthat particle i thatlogoparticles foregroundparticles thatlogoparticlescollisionforeachfunctioncollisiontype collisionindex thatcollisioncollisiontypecallthat particle i thatlogoparticles foregroundparticles thisbackgroundparticlesforeachfunctionparticle i particledrawthatbackgroundctx thatbackgroundparticlesmotionforeachfunctionmotiontype motionindex thatmotionmotiontypecallthat particle i thatbackgroundparticles backgroundparticles thatbackgroundparticlesfxforeachfunctionfxtype fxindex thatfxfxtypecallthat particle i thatbackgroundparticles backgroundparticles thatbackgroundparticlescollisionforeachfunctioncollisiontype collisionindex thatcollisioncollisiontypecallthat particle i thatbackgroundparticles backgroundparticles jarvisprototypeclearcanvas function switchthisbackgroundtype case radial gradient thissetbackgroundradialgradientthisbackgroundcolor1 thisbackgroundcolor2 break case plane color thissetbackgroundcolorthisbackgroundred thisbackgroundgreen thisbackgroundblue thisbackgroundopacity break default thissetbackgroundcolor142 214 255 1 thisforegroundctxclearrectthisclearstartx thisclearstarty thisclearthistance thisclearthistance thismiddlegroundctxclearrectthisclearstartx thisclearstarty thisclearthistance thisclearthistancejarvisprototypemainloop function thisclearcanvas thisbackgrounddraw thisdrawmenu windowrequestanimframethismainloopbindthisany other optimization tips will be greatly appreciated i have read a couple of articles but i am not sure how to optimize this code further,['javascript'] +790371,how to find an apps available restrictions for devicepolicymanagersetapplicationrestrictions the new android lollipop api provides a new pair of methods for getting and setting restrictions on other apps devicepolicymanagergetapplicationrestrictions and devicepolicymanagersetapplicationrestrictionsthere is an example of them being used in the basicmanagedprofile sample app to set restrictions on the chrome app by passing a set of keyvalue pairs that seem to correlate to the chromes published policy list this works perfectly for mebut i cannot find any documentation on any other apps that can be restricted in this way does anyone know of any other apps that can be restricted with these methods and the keys that can be setdevicepolicymanagergetapplicationrestrictions only seems to return the restrictions youve already set for that app not a list of all available restrictions i also tried using restrictionsmanagergetmanifestrestrictions on chrome but this returns an empty list so i think this is something different,['android'] +790379,react js invariant violation processupdates when rendering a table with a different number of child rows i am getting the following error when my react component is rerendered after a click eventuncaught error invariant violation processupdates unable to find child 2 of element this probably means the dom was unexpectedly mutated this only happens when my table has a different number of rows than the previously rendered version for example jsx reactdom react requirereactvar requireunderscorevar testcomp reactcreateclass getinitialstate function return collapsed false handlecollapseclick function thissetstatecollapsed thisstatecollapsed render function var rows tr onclickthishandlecollapseclickthheader 1ththheader 2ththheader 3thtr ifthisstatecollapsed rowspushtrthrow1 1ththrow1 2ththrow1 3thtr rowspushtrthfooter 1ththfooter 2ththfooter 3thtr return div table rows table div moduleexports testcompif i render different content but with the same number of rows i do not get the error so if i update the if statement toifthisstatecollapsed rowspushtrthrow1 1ththrow1 2ththrow1 3thtrelse rowspushtrthrow2 1ththrow2 2ththrow2 3thtr everything worksdo i need to force react to rerender the entire component in this case instead of just the changed elements,['javascript'] +790398,matplotlib valueerror x and y must have same first dimension i am trying to fit a linear line of best fit to my matplotlib graph i keep getting the error that x and y do not have the same first dimension but they both have lengths of 15 what am i doing wrongimport matplotlibpyplot as pltfrom scipy import statsimport numpy as npx 046059068099039031109077072049055062058088078y 031503830452065002790215072705120478033503650424039005850511xerr 00115yerr 0115pltrcfont familyserif size13m b nppolyfitx y 1pltplotxyscolor0066ffpltplotx mx b r breaks on this lineplterrorbarxyxerrxerryerr0linestylenonecolorblackpltxlabeldelta t sfontsize20pltylabeldelta p hpafontsize20pltautoscaleenabletrue axisuboth tightfalsepltgridfalsepltxlim0212pltylim008pltshow,['python'] +790405,xcode project not showing list of simulators i open my project in xcode 61 when i try to run the project the button is grayed out when i try to go to product clean the option is grayed out when i look at the list of simulators all i get is my mac instead of the usually ios device how do i get my simulators to come back,['ios'] +790483,is there a way i can replace this lodash chain code with javascript in modern browsers i have this code which use a lodash chain i would like to simplify the code not use lodash and do this in another wayexamobjectives chainobjectives where examid exam uniqtrue id mapfunction s any return id sid text stext numberandtext snumberandtext valuecan someone give me some advice on how i could remove the dependency on lodash the chain and code this making maximum use of the available javascript functions that can now be found in new browsers note i would like to use the built in filter and map functions and not use any external functions to create the examobjectivesi hope someone can come up with some ideas i am not so familiar with javascript so welcome the chance to learn,['javascript'] +790537,when where and how to add class to the documentbody when using reactjs currently i am doing this but this is not the reactjs way right is render the right place what is the alternative var app reactcreateclass render function if thisstatetouchmode 2 bodyaddclasstouchmode return div etc div,['javascript'] +790599,difference between stdregex match stdregex search below program has been written to fetch the day information using the c11 stdregex match stdregex search however using the first method returns false and second method returns trueexpected i read the documentation and already existing so question related to this but i do not understand the difference between these two methods and when we should use either of them can they both be used interchangeably for any common problem difference between regex match and regex searchincludeiostreamincludestringincluderegexint main stdstring input mon nov 25 205436 2013 day exactly two number surrounded by spaces in both side stdregex rrsd2s stdregex rsd2s stdsmatch matchif stdregex matchinputmatchr stdcout found n else stdcout did not found n if stdregex searchinput matchr stdcout found n if matchready stdstring out match0 stdcout out n else stdcout did not found n outputdid not foundfound 25 why first regex method returns false in this case the regex seems to be correct so ideally both should have been returned true i ran the above program by changing the stdregex matchinputmatchr to stdregex matchinputr and found that it still returns falsecould somebody explain the above example and in general use cases of these methods,['c++'] +790603,how does this static code work codepublic static void main string args string a new stringhello string b pardner systemoutprintlnab systemoutprintlnaequalshello aequalshello systemoutprintlna astatic try field value stringclassgetdeclaredfieldvalue valuesetaccessibletrue valuesethello valuegethowdy catch exception e resulthowdy pardneraequalshello truea howdyhow does this code change hello to howdy when printing,['java'] +790615,change android l keyboard enter key color the new android l keyboard uses system themes coloraccent as the background color of enter key which does not match apps custom theme is there a way to change thati would assume that there is a themestyle for keyboard but i could not find it in themes materialxml the only style i found is androidkeyboardviewstyle but it gives error9 21 no resource found that matches the given name attr androidkeyboardviewstyle,['android'] +790702,value initialization default initialization or zero initialization i have templated gray code class which is meant to store some unsigned integer whose underlying bits are stored in gray code order here it istemplatetypename unsignedintstruct gray code static assertstdis unsignedunsignedintvalue gray code only supports builtin unsigned integers variable containing the gray code unsignedint value default constructor constexpr gray code default construction from unsignedint constexpr explicit gray codeunsignedint value value value 1 value other methodsin some generic algorithm i wrote something like thistemplatetypename unsignedintvoid foo gray codeunsignedint bar other stuffin this piece of code i expected bar to be zerointialized and therefore barvalue to be zeroinitialized however after having struggled with unexpected bugs it appears that barvalue is initialized with garbage 4606858 to be exact instead of 0u that surprised me so i went to cppreferencecom to see what the line above was exactly supposed to dofrom what i can read the form t object corresponds to value initialization i found this quote interestingin all cases if the empty pair of braces is used and t is an aggregate type aggregateinitialization is performed instead of valueinitializationhowever gray code has a userprovided constructor therefore it is not an aggregate thus aggregate initialization is not performed gray code has no constructor taking an stdinitializer list so list initialization is not performed either the valueinitialized of gray code should then follow the usual c14 rules of value initialization1 if t is a class type with no default constructor or with a userprovided default constructor or with a deleted default constructor the object is defaultinitialized 2 if t is a class type without a userprovided or deleted default constructor that is it may be a class with a defaulted default constructor or with an implicitlydefined one then the object is zeroinitialized and then it is defaultinitialized if it has a nontrivial default constructor3 if t is an array type each element of the array is valueinitialized4 otherwise the object is zeroinitializedif i read correctly gray code has an explicitly defaulted not userprovided default constructor therefore 1 does not apply it has a defaulted default constructor so 2 applies gray code is zeroinitialized the defaulted default constructor seems to meet all the requirements of a trivial default constructor so default initialization should not happen let us have a look then at how gray code is zeroinitializedif t is a scalar type the objects initial value is the integral constant zero implicitly converted to t if t is an nonunion class type all base classes and nonstatic data members are zeroinitialized and all padding is initialized to zero bits the constructors if any are ignored if t is a union type the first nonstatic named data member is zeroinitialized and all padding is initialized to zero bits if t is array type each element is zeroinitialized if t is reference type nothing is donegray code is a nonunion class type therefore all of its nonstatic data members should be initialized which means that value is zeroinitialized value satisfies stdis unsigned and is therefore a scalar type which means that it should be initialized with the integral constant zero implicitly converted to tso if i read correctly all of that in the function foo above barvalue should always be initialized with 0 and it should never be initialized with garbage am i rightnote the compiler i compiled my code with is mingw w4 gcc 491 with posix threads and dwarf exceptions in case that helps while i sometimes get garbage on my computer i never managed to get anything else than zero with online compilersupdate it seems to be a gcc bug that the error is mine and not that of my compiler actually when writing this question i assumed for the sake of simplicity thatclass foo foo defaultandclass foo foofoofoo defaultwere equivalent they are not here is the quote from the c14 standard section dclfctdefdefaulta function is userprovided if it is userdeclared and not explicitly defaulted or deleted on its first declarationin other words when i got garbage values my defaulted default constructor was indeed userprovided since it was not explicitly efaulted on its first declaration therefore what happened was not zero initialization but default initialization thanks columbo again for pointing out the real problem,['c++'] +790721,how to updateadd element of the array in javascript how can i updateadd element in the arrayvar persons data var bob name bob age 15var fill name fill age 20var mark name mark age 19var john name john age 4personsdatapushbobpersonsdatapushfillpersonsdatapushmarkpersonsdatapushjohnvar updatedjohn name john age 100if personsdataupdatedjohnname personsdatapushupdatedjohn else personsdataupdatedjohnname updatedjohn this line does not worki cannot figure out how to update an element of the array if element john already existupdatejsfiddle example,['javascript'] +790743,android studio no installation wizard i have downloaded the latest android studio and when i run studio64exe it opens android studio as a standalone application however i would like to install it to my system the website says there is an installation wizard however i get taken straight to the android studio start screen is there still a way to install it on a windows machine,"['java', 'android']" +790788,change status bar color with appcompat actionbaractivity in my one activity i change the toolbar color using palette but on 50 devices using actionbaractivity the status bar color is the color of my colorprimarydark in my activity theme so i have 2 very different color and it does not look goodi realize that in 50 you can use windowsetstatusbarcolor but actionbaractivity does not have thisso my question is in 50 how can i change the status bar color with actionbaractivity,['android'] +790921,custom uiwindows do not rotate correctly in ios 8 get your application into landscape mode and execute the following codeuiwindow toastwindow uiwindow alloc initwithframeuiscreen mainscreen boundstoastwindowhidden notoastwindowbackgroundcolor uicolor cyancolor colorwithalphacomponent05fthispatch afterthispatch timethispatch time now int64 t5 nsec per sec thispatch get main queue toastwindow removefromsuperviewin ios 7 you will get a transparent blue overlay on top of the entire screen that thisappears after 5 seconds in ios 8 you will get a transparent blue overlay that covers a little over half the screenthis obviously has something to do with the change apple did in ios 8 where the screen coordinates are now interface oriented instead of device oriented but in true apple fashion they seem to have left a myriad of bugs in landscape mode and rotationi can fix this by checking if the device orientation is landscape and flip the width and height of the main screen bounds but that seems like a horrible hack that is going to break when apple changes everything again in ios 9cgrect frame uiscreen mainscreen boundsif uiinterfaceorientationislandscapeuidevice currentdeviceorientation framesizewidth framesizeheight framesizeheight uiscreen mainscreen boundssizewidthuiwindow toastwindow uiwindow alloc initwithframeframetoastwindowhidden notoastwindowbackgroundcolor uicolor cyancolor colorwithalphacomponent05fthispatch afterthispatch timethispatch time now int64 t5 nsec per sec thispatch get main queue toastwindow removefromsuperviewhas anyone been experiencing this problem and come across a better less brittle solutionedit i know i could just use a uiview and add it to the key window but i would like to put something on top of the status bar,"['ios', 'objective-c']" +790958,why is xcodes debugger jumping around this way with swift i debugged the following code with f6 in xcode 6 and the sequence of execution is very interestinghere is the code 7 lines a breakpoint is set on line 1 let request awsdynamodbputiteminput requesttablename blah let card awsdynamodbattributevalue cards 1234 let email awsdynamodbattributevalue emails notset requestitem card number card email emailwhen i f6d through the code it showed the following sequence the numbers are line numbers1242346456767why is this is this something with xcode or the language those classes are defined in amazons aws sdk not sure whether that matters they are accessed through swiftobjectivec bridging could this be related to the bridgingby the way the net result of the execution is correct,['objective-c'] +790959,size classes in ios 7 i created a new app in xcode 6 using size classes after testing with ios 7 i cannot figure out how to get iphone to thisplay a certain size class while in landscape modei first developed the ui with iphone landscape as wany hcompact but ios 7 does not recognize that i had iphone portrait in wany hanyi then changed it so now i am using wcompact hregular for iphone portrait i then modified wany hany to be the landscape layout but it is not using that layout when the ios 7 device is in landscapeis ios 7 able to use different size classes based on the device being portrait or landscape if so which size class should i be usingreference really helpful information about backwards compatibility with size classesps i am not concerned with ipad because the device does not thisplay a different size class based on the device rotation in ios 8,['iphone'] +790991,how to tell gulp to skip or ignore some files in gulpsrc how can i tell gulp to skip or ignore some files in gulpsrc for instance i do not want to compress and concat this file in my css folder cssignnorecssvar autoprefix requiregulpautoprefixer concat requiregulpconcat minifycss requiregulpminifycssgulptaskstyles function gulpsrc cssignnorecss ignore this file csscss pipeconcatstylescss pipeautoprefixlast 2 versions pipeminifycss pipegulpdestlocalviewstylebasecssthist,['css'] +791017,uitableview cell exception must translate autoresizing mask into constraints to have sethostslayoutengineyes i am using the uitableview categorycell cell tableview dequeuereusablecellwithidentifiercellidentifierlinkthis is the line i am getting the error it is working in ios 7 but when i run the application in ios 8 i am getting the error terminating app due to uncaught exception nsinternalinconsistencyexception reason must translate autoresizing mask into constraints to have sethostslayoutengineyeseditfull code uitableviewcell tableviewuitableview tableview cellforrowatindexpathnsindexpath indexpath static nsstring cellidentifierimagelink newsimageandlink static nsstring cellidentifierimage newsimage static nsstring cellidentifierlink newslink static nsstring cellidentifier newsdescription nsstring image news objectatindexindexpathrow valueforkeyimageurl nsstring link news objectatindexindexpathrow valueforkeylink nsstring description news objectatindexindexpathrow valueforkeydescription nsstring date news objectatindexindexpathrow valueforkeydate nsstring title news objectatindexindexpathrow valueforkeytitle nsmutablestring html nsmutablestring stringwithstring continue building the string html appendstringhtmlbody html appendstringdescription html appendstringbodyhtml sdwebimagemanager manager sdwebimagemanager sharedmanager if image nsstring nsnull null link nsstring nsnull null categorycell cell tableview dequeuereusablecellwithidentifiercellidentifierimagelink celblheadingtexttitle nsurl url nsurl urlwithstringimage manager downloadimagewithurlurl options0 progressnsinteger receivedsize nsinteger expectedsize completeduiimage image nserror error sdimagecachetype cachetype bool finished nsurl imageurl cellnewsimageimage image if date nsstring nsnull null celbldatetextdate pass the string to the webview cellwebview loadhtmlstringhtml description baseurlnil celbllinktextlink return cell else if image nsstring nsnull null linknsstring nsnull null categorycell cell tableview dequeuereusablecellwithidentifiercellidentifierimage celblheadingtexttitle nsurl url nsurl urlwithstringimage manager downloadimagewithurlurl options0 progressnsinteger receivedsize nsinteger expectedsize completeduiimage image nserror error sdimagecachetype cachetype bool finished nsurl imageurl cellnewsimageimage image if date nsstring nsnull null celbldatetextdate cellwebview loadhtmlstringhtml description baseurlnil return cell else if image nsstring nsnull null linknsstring nsnull null categorycell cell tableview dequeuereusablecellwithidentifiercellidentifierlink celblheadingtexttitle if date nsstring nsnull null celbldatetextdate celltxtdescriptiontextdescription pass the string to the webview cellwebview loadhtmlstringhtml description baseurlnil celbllinktextlink return cell else if image nsstring nsnull null linknsstring nsnull null categorycell cell tableview dequeuereusablecellwithidentifiercellidentifier celblheadingtexttitle if date nsstring nsnull null celbldatetextdate celltxtdescriptiontextdescription pass the string to the webview cellwebview loadhtmlstringhtml description baseurlnil return cell return nil,"['ios', 'objective-c']" +791275,python cannot allocate memory using multiprocessingpool my code part of a genetic optimization algorithm runs a few processes in parallel waits for all of them to finish reads the output and then repeats with a different input everything was working fine when i tested with 60 repetitions since it worked i decided to use a more realistic number of repetitions 200 i received this errorfile usrlibpython27threadingpy line 551 in bootstrap inner selfrunfile usrlibpython27threadingpy line 504 in run self targetself args self kwargsfile usrlibpython27multiprocessingpoolpy line 302 in handle workers pool maintain poolfile usrlibpython27multiprocessingpoolpy line 206 in maintain pool self repopulate poolfile usrlibpython27multiprocessingpoolpy line 199 in repopulate pool wstartfile usrlibpython27multiprocessingprocesspy line 130 in start self popen popenselffile usrlibpython27multiprocessingforkingpy line 120 in init selfpid osforkoserror errno 12 cannot allocate memoryhere is a snippet of my code that uses pooldef runmanyinputsfrom multiprocessing import cpu count poolprocinputs0poolpoolprocesses proc resultsfor arg1 in inputs1 for arg2 in inputs2 for arg3 in inputs3 resultsappendpoolapply asyncrunone argsarg1 arg2 arg3casenum0datadictdictfor p in results get results of simulation once it has finished datadictcasenumpget casenum1return datadictthe runone function creates an object in class i created uses a computationallyheavy python package to solve a chemistry problem that takes about 30 seconds and returns the object with the output of the chemistry solverso my code calls runmany in serial and runmany then calls runone in parallel in my testing i have called runone using 10 processors the computer has 16 and a pool of 20 calls to runone in other words lenarg1lenarg2lenarg320 everything worked fine when my code called runmany 60 times but i ran out of memory when i called it 200 times does this mean some process is not correctly cleaning up after itself do i have a memory leak how can i determine if i have a memory leak and how do i find out the cause of the leak the only item that is growing in my 200repetition loop is a list of numbers that grows from 0 size to a length of 200 i have a dictionary of objects from a custom class i have built but it is capped at a length of 50 entries each time the loop executes it deletes an item from the dictionary and replaces it with another itemedit here is a snippet of the code that calls runmanyfor run in rangenruns create inputs object for runmany using genetic methods either use starting population or create child inputs from successful previous runs datadict runmanyinputs sumsquare0 for i in rangelendatadictsenk input condition sumsquarecomparedatadictitargeti compare result to target with openospathjoinmainpathoutputsoutputtxta as f fwritetjoinstrx for x in inputsname sumsquaren objectiveappendsumsquare add sum of squares to list to be plotted outside of loop populationinputssumsquare addupdate the model in the population using the inputs object as a key and it is objective function as the value if lenpopulationinitialpopulation population populationreductionpopulation reduce the population by killing unfit genes avgtimedatetimedatetimenowstarttime2run1 remainingnrunsrun1avgtime print finished strrun1 strnruns elapsed strdatetimedatetimenowreplacemicrosecond0starttime remaining strremaining finish at strdatetimedatetimenowremainingreplacemicrosecond0 endr,['python'] +791281,why does new date1970 0 1getfullyear return 1969 can someone explain why new date1970 0 1getfullyear returns 1969 and not 1970resulttextcontent new date1970 0 1getfullyeardiv idresultdivfiled firefox bug bugcgiid1093130,['javascript'] +791336,why this code throws collection was modified but when i iterate something before it it does not var ints new list int new 1 2 3 4 5 var first trueforeach var v in ints if first for long i 0 i intmaxvalue i the thing i iterate intsadd 1 intsremoveat intscount 1 intsadd 6 intsadd 7 consolewriteline v first falseif you comment out the inner for loop it throws it is obviously because we did changes to the collectionnow if you uncomment it why this loop allow us to add those two items it takes awhile to run it like half a minute on pentium cpu but it does not throw and the funny thing is that it outputs it was a bit of expected but it indicates that we can change and it actually changes the collection any ideas why this behaviour occuring,['c#'] +791396,what is a value known at compile time i am studying the c programming language and in a chapter my book introduces me the concept of constant a constexpr symbolic constant must be given a value that is known at compile timewhat is a value known at compile time why we need of them,['c++'] +791408,readonly changing the behavior of a struct i am trying to understand some basic conceptsclass program private static readonly mystruct m new mystruct static void mainstring args new mutablesamplerunsample consolewritelinemchangeinternal consolewritelinemchangeinternal consolewritelinemchangeinternal consoleread public struct mystruct private int x public int changeinternal thisx thisx 1 return thisx when i run this code it gives me 1 1 1 but when i remove the readonly it says 1 2 3can someone explain to me this,['c#'] +791421,adding a subview and position it with constraints programmatically i have added a uiview using the ib on to the view controller let us call it the redview then i have pinned its all four sides using auto layout constraints in code and when i run it it looks like this as expectednow i want to add a uilabel to this view programmatically and position it in the center using auto layout constraintsbelow is the code i have so farimport uikitclass viewcontroller uiviewcontroller iboutlet private var redview uiview override func viewdidload superviewdidload redviewsettranslatesautoresizingmaskintoconstraintsfalse let leadingconstraint nslayoutconstraintitem redview attribute leading relatedby equal toitem view attribute leading multiplier 1 constant 0 let trailingconstraint nslayoutconstraintitem redview attribute trailing relatedby equal toitem view attribute trailing multiplier 1 constant 0 let topconstraint nslayoutconstraintitem redview attribute top relatedby equal toitem view attribute top multiplier 1 constant 0 let bottomconstraint nslayoutconstraintitem redview attribute bottom relatedby equal toitem view attribute bottom multiplier 1 constant 0 viewaddconstraintsleadingconstraint trailingconstraint topconstraint bottomconstraint let label uilabel labeltext auto layout exercise redviewaddsubviewlabel let xcenterconstraint nslayoutconstraintitem label attribute centerx relatedby equal toitem redview attribute centerx multiplier 1 constant 0 let ycenterconstraint nslayoutconstraintitem label attribute centery relatedby equal toitem redview attribute centery multiplier 1 constant 0 let leadingconstraint1 nslayoutconstraintitem label attribute leading relatedby equal toitem redview attribute leading multiplier 1 constant 20 let trailingconstraint1 nslayoutconstraintitem label attribute trailing relatedby equal toitem redview attribute trailing multiplier 1 constant 20 redviewaddconstraintsxcenterconstraint ycenterconstraint leadingconstraint1 trailingconstraint1 the problem is the label does not appear on the redview can anyone please tell me what i am missing herethank you,['ios'] +791565,get search bar in navigation bar in swift so i have tried everything trying to get a search bar into the navigation bar in swift but sadly i have not gotten it working just yet for those of you who do not know what i am talking about i am trying to do something like thisnote the search bar in the navigation bar so heres what i am currently using selfsearchthisplaycontrollerthisplayssearchbarinnavigationbar truei popped that in my viewdidload and then when i load up the app i am presented with just an empty navigation bar any ideas,['ios'] +791573,identity email with dash in aspnet identity i am using aspnet mvc identity and when i add an email of the form i get the validation error message user name is invalid can only contain letters or digitshow can i change the validation so that it will allow the email to be acceptedmy cshtml isusing htmlbeginformlogin account new returnurl viewbagreturnurl formmethodpost new role form htmlantiforgerytoken div classregheader h2registerh2 div fieldset if viewbagisregister htmlvalidationsummarytrue new class textdanger div classmarginbottom20 htmllabelform mregisterviewmodelfirstnamebr div classinputgroup span classinputgroupaddoni classfa fauserispan htmltextboxform mregisterviewmodelfirstname new class formcontrol div htmlvalidationmessageform mregisterviewmodelfirstname new class textdanger div div classmarginbottom20 htmllabelform mregisterviewmodellastnamebr div classinputgroup span classinputgroupaddoni classfa fauserispan htmltextboxform mregisterviewmodellastname new class formcontrol div htmlvalidationmessageform mregisterviewmodellastname new class textdanger div div classmarginbottom20 htmllabelform mregisterviewmodelemailbr div classinputgroup span classinputgroupaddoni classfa fauserispan htmltextboxform mregisterviewmodelemail new class formcontrol div htmlvalidationmessageform mregisterviewmodelemail new class textdanger div div classmarginbottom20 htmllabelform mregisterviewmodelpasswordbr div classinputgroup span classinputgroupaddoni classfa falockispan htmlpasswordform mregisterviewmodelpassword new class formcontrol div htmlvalidationmessageform mregisterviewmodelpassword new class textdanger div div classmarginbottom20 htmllabelform mregisterviewmodelconfirmpasswordbr div classinputgroup span classinputgroupaddoni classfa falockispan htmlpasswordform mregisterviewmodelconfirmpassword new class formcontrol div classcleardiv div htmlvalidationmessageform mregisterviewmodelconfirmpassword new class textdanger div div classrow div classcolmd12 button classbtnu typesubmit namecommand valueregisterregisterbutton div div fieldset this is my controller registerviewmodel model loginregisterviewmodel var user new applicationuser username modelemail firstname modelfirstname lastname modellastname userrole userrolerider identityresult result await usermanagercreateasyncuser modelpassword if resultsucceeded await signinasyncuser ispersistent false for more information on how to enable account confirmation and password reset please visit send an email with this link string code await usermanagergenerateemailconfirmationtokenasyncuserid var callbackurl urlactionconfirmemail account new userid userid code code protocol requesturlscheme await usermanagersendemailasyncuserid confirm your account please confirm your account by clicking a href callbackurl herea return redirecttolocalreturnurl return redirecttoactionindex home else viewbagreturnurl returnurl adderrorsresult,['asp.net'] +791622,position mbprogresshud at the bottomtop of the screen is there a way to make the mbprogresshud show at the bottom or top of the screeni have tried setting the frame using hud setframe initwithframe and setting thecenter property of the hud none of these worked i did an nslog of the frames after trying these methods the values had changed but the hud still thisplayed at the center of the screena thing to note the hud is thisplayed using a uiwindowuiwindow window uiapplication sharedapplication windows lastobjectmbprogresshud hud mbprogresshud showhudaddedtowindow animatedyeshudmode mbprogresshudmodetexthudlabeltext some textdid this because the hud is thisplayed by a background execution block thus the hud could be thisplayed on any view currently in thisplay,['ios'] +791637,android appcompat 21 elevation is there any way to add elevation to a view in prelollipop devices without wrapping them in a cardview,['android'] +791642,curlopt post vs curlopt postfields is curlopt post option required i am new to curl in php i have a question regarding usage of curl optionsconsider two script files test1php and test2php both present in root w i am using ubuntu 1204 lts the libcurl version for php is 7220contents of test1phpphp ch curl init post data array firstname john lastname doe curl setoptch curlopt url localhosttest2php curl setoptch curlopt post true is it optional curl setoptch curlopt postfields post data curl execch curl closechcontents of test2phpphp var dump postwhen i execute test1php via browser i can see results posted now if i remove curl option containing curlopt post the example still works even if i set curlopt post to false post is performed and result is thisplayed so is that curlopt post not required at all it looks option curlopt postfields takes care of sending data via post without use of curlopt post option when i print server in test2php request method is always set to post with or without option curlopt postcould anyone please let me know the exact use of curlopt post option is it neccessary required for sending data via post,['php'] +791651,xcode 61 cannot find debug view hierarchy button my xcode version is 61 i can find debug view hierarchy button in a new created project but not with my old projectand the menu item capture view hierarchy are always grayed outmy old project is 32bit only mac projectnot ios with no arc my code written mixed with objectivec and canyone knows why my old project cannot use view debugger,['objective-c'] +791659,spring data mongodb auditing not working java config i am currently using spring data mongodb 160release and i know it has auditing feature iput enablemongoauditing annotation on top of my configuration class and my bean is belowdocumentpublic class mybeanidprivate anothercustombean anothercustombean new anothercustombeancreateddateprivate date creationdatelastmodifieddateprivate date lastmodifieddatewhen i save this bean with mongotemplatesavemybean it is not setting created date and last modified dateand it has no errorsany help would be appreciatedthanks,['java'] +791794,could not load file or assembly presentationuiaero2 or one of its dependencies why not in my wpf application i get the following exception on startupa first chance exception of type systemiofilenotfoundexception occurred in mscorlibdlladditional information could not load file or assembly presentationuiaero2 version40 cultureneutral publickeytoken31bf3856ad364e35 or one of its dependencies edit using fusion log i get a little more valuable info than the call stacklog thisplayname presentationuiaero2 version40 cultureneutral publickeytoken31bf3856ad364e35 fullyspecifiedlog appbase filebindebuglog initial privatepath nulog dynamic base nulog cache base nulog appname engidesklaunchervshostexecalling assembly presentationframework version40 cultureneutral publickeytoken31bf3856ad364e35log this bind starts in default load contextlog using application configuration file bindebugengidesklaunchervshostexeconfiglog using host configuration file log using machine configuration file from cwindowsmicrosoftnetframeworkv4030319configmachineconfiglog postpolicy reference presentationuiaero2 version40 cultureneutral publickeytoken31bf3856ad364e35log gac lookup was unsuccessfullog attempting download of new url filebindebugpresentationuiaero2dlog attempting download of new url filefilebindebugpresentationuiaero2presentationuiaero2dlog attempting download of new url filefilebindebugpresentationuiaero2exelog attempting download of new url filefilebindebugpresentationuiaero2presentationuiaero2exelog all probing urls attempted and failedwhat i find strange is that the calling assembly is presentationframework which is a net framework assembly obviously a net framework assembly wouldnt call an assembly which is not a net framework assembly anyway i cannot find a presentationuiaero2dll anywhere and not even google seems to know anything about itany ideasadditional informationnet framework 40windows 81,['c#'] +791978,plotting the projection of 3d plot in three planes using contours i have a three columns catalogue of data and i would like to make a 3d plot of them plus the projection of each axis as a projected contour in the the plane of the other two axises so far i could make the 3d plot using matplotlib which still does not show anything from the properties of the datafrom mpl toolkitsmplot3d import axes3dimport matplotlibpyplot as pltfrom numpy import dataloadtxttestcatxdata0ydata1zdata2fig pltfigureax figadd subplot1 projection3daxscatterx y z cr markeraxset xlabelxaxset ylabelyaxset zlabelzpltshowhow could i plot the projection of the data in each plane with colorbar as well,['python'] +792078,uiscrollview in storyboard not working with ios 8 size classes and autolayout so i am trying to create a uiscrollview only in storyboard that allows me to add scrolling labels for more than the height of the vc heres what i did created uiscrollview that took up the size of the any width any height vcmade constraints 0 for spacing to nearest neighbor on top bottom left and rightcreated a view that is a subview of the uiscrollview with the same width as the any width any height vc but height of 1500 because i only want it to scroll vertically set constraints to nearest neighbor as 0 for only left top and right and set the height constraint as 1500i put a label at the top of the subview and at the bottomwhen i run the app on an iphone 6 does not scroll vertically as i want it to any ideas why this is not working thanks in advance,['ios'] +792084,android how totutorial for changing actionbar to actionbarcompat toolbar i have been stuck on this checked the official guidance etc any tutorialswhat are the steps to change from actionbar to actionbarcompat for the toolbar and support of older versions i have imported appcompatv7210 tried getsupportactionbar and toolbar toolbar toolbar findviewbyidridtoolbar actionbarsetsupportactionbartoolbarchanged theme to appcompat theme in styles any common errors to note or ideaskeep getting this kind of errorjavalangruntimeexception unable to start activity componentinfocombatteryplusfreecombatteryplusfreemaincollectionactivity javalangnullpointerexception at androidappactivitythreadperformlaunchactivityactivitythreadjava2212 at androidappactivitythreadhandlelaunchactivityactivitythreadjava2271 at androidappactivitythreadaccess800activitythreadjava144 at androidappactivitythreadhhandlemessageactivitythreadjava1205 at androidoshandlerthispatchmessagehandlerjava102 at androidoslooperlooplooperjava136 at androidappactivitythreadmainactivitythreadjava5146 at javalangreflectmethodinvokenativenative method at javalangreflectmethodinvokemethodjava515 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava732 at comandroidinternaloszygoteinitmainzygoteinitjava566 at derobvandroidxposedxposedbridgemainxposedbridgejava132 at dalviksystemnativestartmainnative method caused by javalangnullpointerexception at combatteryplusfreemaincollectionactivityoncreatemaincollectionactivityjava133 at androidappactivityperformcreateactivityjava5231 at androidappinstrumentationcallactivityoncreateinstrumentationjava1087 at androidappactivitythreadperformlaunchactivityactivitythreadjava2169a a a a a a a a a a a a at androidappactivitythreadhandlelaunchactivityactivitythreadjava2271a a a a a a a a a a a a at androidappactivitythreadaccess800activitythreadjava144a a a a a a a a a a a a at androidappactivitythreadhhandlemessageactivitythreadjava1205a a a a a a a a a a a a at androidoshandlerthispatchmessagehandlerjava102a a a a a a a a a a a a at androidoslooperlooplooperjava136a a a a a a a a a a a a at androidappactivitythreadmainactivitythreadjava5146a a a a a a a a a a a a at javalangreflectmethodinvokenativenative methoda a a a a a a a a a a a at javalangreflectmethodinvokemethodjava515a a a a a a a a a a a a at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava732a a a a a a a a a a a a at comandroidinternaloszygoteinitmainzygoteinitjava566a a a a a a a a a a a a at derobvandroidxposedxposedbridgemainxposedbridgejava132a a a a a a a a a a a a at dalviksystemnativestartmainnative method,['android'] +792173,navigation drawer semitransparent over status bar not working i am working on android project and i am implementing the navigation drawer i am reading through the new material design spec and the material design checklistthe spec says that the slide out pane should float above everything else including the status bar and be semitransparent over the status bar my navigation panel is over the status bar but its not got any transparency i have followed the code from this so post as suggested in the google developers blog spot link above how do i use drawerlayout to thisplay over the actionbartoolbar and under the status bar below is my xml layoutandroidsupportv4widgetdrawerlayout xmlnsandroid androidididmy drawer layout androidlayout widthmatch parent androidlayout heightmatch parent androidfitssystemwindowstrue linearlayout androidlayout widthmatch parent androidlayout heightmatch parent androidorientationvertical androidsupportv7widgettoolbar androidididmy awesome toolbar androidlayout heightwrap content androidlayout widthmatch parent androidminheightattractionbarsize androidbackgroundcoloraprimarycolour linearlayout linearlayout androidididlinearlayout androidlayout width304dp androidlayout heightmatch parent androidlayout gravityleftstart androidfitssystemwindowstrue androidbackgroundf listview androidididleft drawer androidlayout widthmatch parent androidlayout heightmatch parent androidchoicemodesinglechoicelistview linearlayoutandroidsupportv4widgetdrawerlayoutbelow is my apps themestyle nameapptheme parentthemeappcompatlightnoactionbar item namecolorprimarycoloraprimarycolouritem item namecolorprimarydarkcoloraprimarycolourdarkitem item namecoloraccentcoloraprimarycolouritem item namewindowactionbarfalseitem item namewindowactionmodeoverlaytrueitem stylebelow is my apps v21 themestyle nameapptheme parentthemeappcompatlightnoactionbar item namecolorprimarycoloraprimarycolouritem item namecolorprimarydarkcoloraprimarycolourdarkitem item namecoloraccentcoloraprimarycolouritem item namewindowactionbarfalseitem item namewindowactionmodeoverlaytrueitem item nameandroidwindowdrawssystembarbackgroundstrueitem item nameandroidstatusbarcolorandroidcolortransparentitemstylebelow is my oncreate methodprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main toolbar toolbar toolbar findviewbyidridmy awesome toolbar setsupportactionbartoolbar mdrawerlayout drawerlayoutfindviewbyidridmy drawer layout mdrawerlist listviewfindviewbyidridleft drawer mdrawerlayoutsetstatusbarbackgroundcolor getresourcesgetcolorrcoloraprimarycolourdark if buildversionsdk int buildversion codeslollipop linearlayout linearlayout linearlayoutfindviewbyidridlinearlayout linearlayoutsetelevation30 below is a screenshot of my navigation drawer showing the top is not semi transparent,['android'] +792283,odoo add widget to website frontend i am new to odoo and i am stuck at an easy pointi already added some widgets to the backend in my custom module now i want to add a widget to my website frontend and i do not get it worki have the following snippetsfrontend viewsxmlopenerp data templates template idassets frontend nametest module asset frontend inherit idwebsitetheme xpath expr positioninside custom js and css link relstylesheet hreftest modulestaticsrccssfrontendcss script typetextjavascript srctest modulestaticsrcjsfrontendjs xpath template dataopenerpand the javascript code for the widgetstaticsrcjsfrontendjsopenerptest module functioninstance local localtestwidget instancewidgetextend start function consolelogwidget loaded this super instancewebclient actionsaddexampleaction instancetest moduletestwidgethow could i call the widget in my templatei tried the following thingsfrontend viewsxmlrecord modeliractionsclient idaction client example field namenameexample client actionfield field nametagexampleactionfieldrecordtemplate iddetails t tcallwebsitelayout t tsettitledetailst div classoe structure div classcontainer button idtest nameaction client example sequence0 typeobjectrun widgetbutton div div ttemplatebut i do not get the widget running i am a little confused maybe i do not understand the whole thing how to integrate a widget because in the backend i just put in the following line to add the widgetwidget typetest modulemywidget but how to do that in in frontend,['javascript'] +792288,custom circular reveal transition results in javalangunsupportedoperationexception when paused i created a custom circular reveal transition to use as part of an activitys enter transition specifically i am setting the transition as the windows enter transition by calling windowsetentertransitionpublic class circularrevealtransition extends visibility private final rect mstartbounds new rect use the views location as the circular reveals starting position public circularrevealtransitionview v int loc new int2 vgetlocationinwindowloc mstartboundssetloc0 loc1 loc0 vgetwidth loc1 vgetheight override public animator onappearviewgroup sceneroot final view v transitionvalues startvalues transitionvalues endvalues if endvalues null return null int halfwidth vgetwidth 2 int halfheight vgetheight 2 float startx mstartboundsleft mstartboundswidth 2 halfwidth float starty mstartboundstop mstartboundsheight 2 halfheight float endx vgettranslationx float endy vgettranslationy vsettranslationxstartx vsettranslationystarty create a circular reveal animator to play behind a shared element during the activity transition animator revealanimator viewanimationutilscreatecircularrevealv halfwidth halfheight 0f floatmathsqrthalfwidth halfheight halfheight halfheight revealanimatoraddlistenernew animatorlisteneradapter override public void onanimationendanimator animation set the views visibility to visible to prevent the reveal from blinking at the end of the animation vsetvisibilityviewvisible translate the circular reveal into place as it animates propertyvaluesholder pvhx propertyvaluesholderoffloattranslationx startx endx propertyvaluesholder pvhy propertyvaluesholderoffloattranslationy starty endy animator translationanimator objectanimatorofpropertyvaluesholderv pvhx pvhy animatorset anim new animatorset animsetinterpolatorgetinterpolator animplaytogetherrevealanimator translationanimator return anim this works ok normally however when i click the back button in the middle of the transition i get the following exceptionprocess comadpactivitytransitions pid 13800javalangunsupportedoperationexception at androidviewrendernodeanimatorpauserendernodeanimatorjava251 at androidanimationanimatorsetpauseanimatorsetjava472 at androidtransitiontransitionpausetransitionjava1671 at androidtransitiontransitionsetpausetransitionsetjava483 at androidappactivitytransitionstatestartexitbacktransitionactivitytransitionstatejava269 at androidappactivityfinishaftertransitionactivityjava4672 at comadpactivitytransitionsdetailsactivityfinishaftertransitiondetailsactivityjava167 at androidappactivityonbackpressedactivityjava2480is there any specific reason why i am getting this error how should it be avoided,['android'] +792376,clientabortexception when using jersey 213 i am using jersey 213 in my web application for retrieving data async there are some cases where requests take some time ie when executing complex reports until their response returns to the clientwhen the client does not wait for the async response leaves the page closes the browser etc a clientabortexception is thrown this behaviour is as expected but it is flooding my log files with stack traces because every single async request that gets canceled before the response returns prints a stack tracethe stack trace looks like thisoct 15 2014 22523 pm orgglassfishjerseyserverserverruntimeresponder writeresponsesevere an io error has occurred while writing a response message entity to the container output streamorgglassfishjerseyserverinternalprocessmappableexception clientabortexception javaioioexception at orgglassfishjerseyserverinternalmappableexceptionwrapperinterceptoraroundwritetomappableexceptionwrapperinterceptorjava91 at orgglassfishjerseymessageinternalwriterinterceptorexecutorproceedwriterinterceptorexecutorjava162 at orgglassfishjerseymessageinternalmessagebodyfactorywritetomessagebodyfactoryjava1154 at orgglassfishjerseyserverserverruntimeresponderwriteresponseserverruntimejava621 at orgglassfishjerseyserverserverruntimeresponderprocessresponseserverruntimejava377 at orgglassfishjerseyserverserverruntimeresponderproceserverruntimejava367 at orgglassfishjerseyserverserverruntime1runserverruntimejava274 at orgglassfishjerseyinternalerrors1callerrorsjava271 at orgglassfishjerseyinternalerrors1callerrorsjava267 at orgglassfishjerseyinternalerrorsprocesserrorsjava315 at orgglassfishjerseyinternalerrorsprocesserrorsjava297 at orgglassfishjerseyinternalerrorsprocesserrorsjava267 at orgglassfishjerseyprocessinternalrequestscoperuninscoperequestscopejava297 at orgglassfishjerseyserverserverruntimeproceserverruntimejava254 at orgglassfishjerseyserverapplicationhandlerhandleapplicationhandlerjava1030 at orgglassfishjerseyservletwebcomponentservicewebcomponentjava373 at orgglassfishjerseyservletservletcontainerserviceservletcontainerjava381 at orgglassfishjerseyservletservletcontainerserviceservletcontainerjava344 at orgglassfishjerseyservletservletcontainerserviceservletcontainerjava221 at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava305 at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava210 at orgapachetomcatwebsocketserverwsfilterdofilterwsfilterjava52 at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava243 at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava210 at orgapachecatalinacorestandardwrappervalveinvokestandardwrappervalvejava2 at orgapachecatalinacorestandardcontextvalveinvokestandardcontextvalvejava123 at orgapachecatalinaauthenticatorauthenticatorbaseinvokeauthenticatorbasejava502 at orgapachecatalinacorestandardhostvalveinvokestandardhostvalvejava171 at orgapachecatalinavalveserrorreportvalveinvokeerrorreportvalvejava100 at orgapachecatalinavalvesaccesslogvalveinvokeaccesslogvalvejava953 at orgapachecatalinacorestandardenginevalveinvokestandardenginevalvejava118 at orgapachecatalinaconnectorcoyoteadapterservicecoyoteadapterjava409 at orgapachecoyotehttp11abstracthttp11processorprocessabstracthttp11processorjava1044 at orgapachecoyoteabstractprotocolabstractconnectionhandlerprocessabstractprotocoljava607 at orgapachetomcatutilnetaprendpointsocketprocessordorunaprendpointjava2441 at orgapachetomcatutilnetaprendpointsocketprocessorrunaprendpointjava2430 at javautilconcurrentthreadpoolexecutorrunworkerunknown source at javautilconcurrentthreadpoolexecutorworkerrununknown source at javalangthreadrununknown sourcecaused by clientabortexception javaioioexception at orgapachecatalinaconnectoroutputbufferrealwritebytesoutputbufferjava413 at orgapachetomcatutilbufbytechunkflushbufferbytechunkjava480 at orgapachetomcatutilbufbytechunkappendbytechunkjava366 at orgapachecatalinaconnectoroutputbufferwritebytesoutputbufferjava438 at orgapachecatalinaconnectoroutputbufferwriteoutputbufferjava426 at orgapachecatalinaconnectorcoyoteoutputstreamwritecoyoteoutputstreamjava91 at orgglassfishjerseyservletinternalresponsewriternoncloseableoutputstreamwrapperwriteresponsewriterjava298 at orgglassfishjerseymessageinternalcommittingoutputstreamwritecommittingoutputstreamjava229 at orgglassfishjerseymessageinternalwriterinterceptorexecutoruncloseableoutputstreamwritewriterinterceptorexecutorjava299 at comfasterxmljacksoncorejsonutf8jsongenerator flushbufferutf8jsongeneratorjava1862 at comfasterxmljacksoncorejsonutf8jsongeneratorcloseutf8jsongeneratorjava1087 at comfasterxmljacksonjaxrsbaseproviderbasewritetoproviderbasejava637 at orgglassfishjerseymessageinternalwriterinterceptorexecutorterminalwriterinterceptorinvokewritetowriterinterceptorexecutorjava265 at orgglassfishjerseymessageinternalwriterinterceptorexecutorterminalwriterinterceptoraroundwritetowriterinterceptorexecutorjava250 at orgglassfishjerseymessageinternalwriterinterceptorexecutorproceedwriterinterceptorexecutorjava162 at orgglassfishjerseyserverinternaljsonwithpaddinginterceptoraroundwritetojsonwithpaddinginterceptorjava106 at orgglassfishjerseymessageinternalwriterinterceptorexecutorproceedwriterinterceptorexecutorjava162 at orgglassfishjerseyserverinternalmappableexceptionwrapperinterceptoraroundwritetomappableexceptionwrapperinterceptorjava85 38 morecaused by javaioioexception at orgapachecoyotehttp11internalaproutputbufferflushbufferinternalaproutputbufferjava205 at orgapachecoyotehttp11internalaproutputbufferaccess100internalaproutputbufferjava37 at orgapachecoyotehttp11internalaproutputbuffersocketoutputbufferdowriteinternalaproutputbufferjava235 at orgapachecoyotehttp11filterschunkedoutputfilterdowritechunkedoutputfilterjava117 at orgapachecoyotehttp11abstractoutputbufferdowriteabstractoutputbufferjava192 at orgapachecoyoteresponsedowriteresponsejava517 at orgapachecatalinaconnectoroutputbufferrealwritebytesoutputbufferjava408 55 morei am also using the jersey exceptionmapper to map several exceptions but this does neither work fororgglassfishjerseyserverinternalprocessmappableexceptionnor fororgapachecatalinaconnectorclientabortexceptionis there any way to catch this exception and prevent printing the whole stack traceeditstill looking for an answer,['java'] +792455,appcompatv7 v21 navigation drawer not showing hamburger icon i am implementing the lollipop style navigation drawer with latest appcompat support library but the problem is the hamburger icon is never thisplayed only back icon is shownthis is my activity codeimport androidosbundleimport androidsupportv4widgetdrawerlayoutimport androidsupportv7appactionbaractivityimport androidsupportv7appactionbardrawertoggleimport androidsupportv7widgettoolbarimport androidviewviewpublic class home extends actionbaractivity private drawerlayout mdrawerlayoutprivate actionbardrawertoggle mdrawertoggleoverrideprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity home initviewsprivate void initviews toolbar toolbar toolbar findviewbyidridtoolbar mdrawerlayout drawerlayout findviewbyidriddrawer layout toolbarsettitletextcolorgetresourcesgetcolorandroidrcolorwhite setsupportactionbartoolbar mdrawertoggle new actionbardrawertogglethis mdrawerlayouttoolbar rstringdrawer open rstringdrawer close called when a drawer has settled in a completely closed state public void ondrawerclosedview view superondrawerclosedview getactionbarsettitlemtitle invalidateoptionsmenu creates call to onprepareoptionsmenu called when a drawer has settled in a completely open state public void ondraweropenedview drawerview superondraweropeneddrawerview getactionbarsettitlemdrawertitle invalidateoptionsmenu creates call to onprepareoptionsmenu set the drawer toggle as the drawerlistener mdrawerlayoutsetdrawerlistenermdrawertoggle getsupportactionbarsetthisplayhomeasupenabledtrue getsupportactionbarsethomebuttonenabledtrue this is my styles file resources application theme style namethemetest parentstylethemeappcompatlight customize the color palette item namecolorprimarycolorprimaryitem item namecolorprimarydarkcolorprimary darkitem item namecoloraccentcoloraccentitem item namewindowactionbarfalseitem item namedrawerarrowstylestylethemetestdrawerarrowstyleitemstylestyle namethemetestdrawerarrowstyle parentstylewidgetappcompatdrawerarrowtoggle item namespinbarstrueitem item namecolorandroidcolorwhiteitemstylethe layout file relativelayout xmlnsandroidxmlnsappandroidlayout widthmatch parentandroidlayout heightmatch parent androidsupportv7widgettoolbar androidididtoolbar androidlayout widthmatch parent androidlayout heightwrap content androidbackgroundattrcolorprimary androidminheightattractionbarsize appthemestylethemeoverlayappcompatactionbar androidsupportv4widgetdrawerlayout androidididdrawer layout androidlayout widthmatch parent androidlayout heightmatch parent androidlayout belowidtoolbar the main content view framelayout androidididcontent frame androidlayout widthmatch parent androidlayout heightmatch parent the navigation drawer listview androidididleft drawer androidlayout width240dp androidlayout heightmatch parent androidlayout gravitystart androidbackground1 androidchoicemodesinglechoice androiddividerandroidcolortransparent androiddividerheight0dp androidsupportv4widgetdrawerlayoutrelativelayoutin both cases only back arrow is shown i have read many posts but nothing seems to make a difference any help would be appreciated,['android'] +792465,php and mysql showing different results with same query i have a mysql query which works fine when executed directly on my local mysql database but shows a different result when executed via phpselect aid atitle apublic asysstamp apassword tthumburl tcountfrom 0 lychee albums as aleft join select id album thumburl num ifgroup album num 1 0 as count group album as dummy from 0 lychee photos where album 0 order by album star desc as t on aid talbumwhere count 2 or count is nullor as a onelinerselect aid atitle apublic asysstamp apassword tthumburl tcount from 0 lychee albums as a left join select id album thumburl num ifgroup album num 1 0 as count group album as dummy from 0 lychee photos where album 0 order by album star desc as t on aid talbum where count 2 or count is nullthe result id title public sysstamp password thumburl count 71 import 01 0 1415091268 null cad008943372d984a9b74378874128f8jpeg 0 72 import 9n401238 0 1415091268 null 7b832b56f182ad3403521589e2815f67jpeg 0 72 import 9n401238 0 1415091268 null f058f379ce519f1d8a2ff8c0f5003631jpeg 1 72 import 9n401238 0 1415091268 null a4d59377bed059e3f60cf01a69c299jpeg 2 73 untitled 0 1415114200 null null null the php result id title public sysstamp password thumburl count 71 import 01 0 1415091268 null cad008943372d984a9b74378874128f8jpeg 0 72 import 9n401238 0 1415091268 null 7b832b56f182ad3403521589e2815f67jpeg 0 72 import 9n401238 0 1415091268 null f058f379ce519f1d8a2ff8c0f5003631jpeg 0 72 import 9n401238 0 1415091268 null a4d59377bed059e3f60cf01a69c299jpeg 0 72 import 9n401238 0 1415092318 null 7b832b56f182ad3403521589e2815f67jpeg 0 72 import 9n401238 0 1415092369 null cad008943372d984a9b74378874128f8jpeg 0 72 import 9n401238 0 1415092369 null 84030a64a1f546e223e6a46cbf12910fjpeg 0 73 untitled 0 1415114200 null null null a count is not increasing like it shouldb because of a it shows more rows than it should should be limited to 3 per idi checked it multiple times both queries are exactly the same there is no user input or any difference in phpi already checked similar questions but non of them helped the following queries are showing the same result on both mysql and phpshow variables like character setshow variables like collationis anyone aware of an issue casing this differenceedit with further informationdatabase new mysqlihost user password databasequery select aid atitle apublic asysstamp apassword tthumburl tcount from 0 lychee albums as a left join select id album thumburl num ifgroup album num 1 0 as count group album as dummy from 0 lychee photos where album 0 order by album star desc as t on aid talbum where count 2 or count is nullalbums databasequeryquerywhile album albumsfetch assoc print ralbum i also tried it with and without the following before executing the querydatabaseset charsetutf8databasequeryset names utf8,"['php', 'mysql', 'sql']" +792467,use of struct identifier to signify pod types and c structures consider the following piece of codestruct foo templatetypename forwarditeratorstruct foobarforwarditerator first forwarditerator last voidfirst voidlast foo foonullptr return foothe above piece of code compiles fine in clangv35 and gccv49however it fails to compile in vc2013removing the struct identifier see below from the return type solves the problemstruct foo templatetypename forwarditeratorfoobarforwarditerator first forwarditerator last voidfirst voidlast foo foonullptr return fooq1is this a visual studio bugq2this issue came up because in my codebase the foo struct lies in a hc file ie is a c struct and in order to signify cpod structs in my code i use the struct identifier is this a bad idea ie in c code i should avoid to use struct identifier in this fashion,['c++'] +792504,how to make bootbox closing when using custom dialog i am using bootbox to show dialogif i use bootboxconfirm bootboxalert or bootboxprompt when pressing escape key or clicking outside the dialog the dialog closed as expectedbut when using bootboxdialog when i click outside the dialog or pressing escape key the dialog does not close how to make it behave as other dialog dovar box bootboxdialog show false backdrop true animate false title bla message bla bla bla buttons cancel label cancel classname btnwarning save label parse classname btnsuccess callback function handling with ajax return false boxmodalshow,['javascript'] +792550,entity framework databasefirst multiple relations to same table naming conventions control let us suppose that we have this situationtables in databasecountry id country name person id login countrymanager id country id person countrystakeholder id country id personif we had to create the model from the database using entity framework databasefirst in vs wed have a class like thisclass country int idstring country namevirtual icollectionperson person1 navigation propertiesvirtual icollectionperson person2 i have simplified the code a lot but hopefully you got the pointseems that when entity framework deals with foreign keys it creates generic navigation properties is there a possibility to control how navigation properties are created by name person1 person2 is not very explainatory unfortunately,['c#'] +792636,react does not rerender after setstate used in promise every time the props are changed the component will call ontermchange and get the details for this component with a promise that returns an array of objectsthe problem is that when setstate is called nothing happens and the component is not rerendered with fresh detailsmoduleexports reactcreateclassthisplayname taxonomyselectgetinitialstate function return children undefined componentdidmount function thisontermchangethispropstermcomponentwillreceiveprops function nextprops thispropsterm thispropsterm null if thispropsterm thisontermchangenextpropstermid else thisontermchangenextpropsterm ontermchange function term thissetstatechildren undefined taxonomystoregettermthispropsterm bindthis thenfunction term taxonomystoremerge9 description no specific topic id 9 if termpath termpathlength 3 termchildrenunshifttaxonomystoreget9 consolelogtermid termchildren thissetstatechildren termchildren thisforceupdate thisrender onselect function id if thispropsonchange thispropsonchangetaxonomystoregetid render function if arrayisarraythisstatechildren thisstatechildrenlength 1 return null var options thisstatechildrenmapfunction term return value termidtostring label termdescription var value thispropsvalue thispropsvaluetostring return div select namethispropsname valuevalue optionsoptions onchangethisonselect div,['javascript'] +792680,how do i get accurate exception stack in wcf taskbased operation i am using the wcf ierrorhandler interface to trap and log errors on the server side of a wcf service however the stacktrace of the exception passed to handleerror and providefault is messed upat systemservicemodelthispatchertaskmethodinvokerinvokeendobject instance object outputs iasyncresult result at systemservicemodelthispatcherthispatchoperationruntimeinvokeendmessagerpc rpc at systemservicemodelthispatcherimmutablethispatchruntimeprocessmessage7messagerpc rpc lots morei am not surprised to see random thispatcher methods in the stack trace but i assumed i would see my own method at the top of the stack i have determined that this only happens on operations that look likeoperationcontractpublic taskint myoperation throw new applicationexceptiontestservices that look like this have a proper stack trace for me to logoperationcontractpublic int mysyncoperation throw new applicationexceptiontestas an fyi heres what the error handler methods are likepublic class myerrorhandler ierrorhandler public bool handleerrorexception error variable error has wrong stack trace if exception sourced from taskint operation return false public void providefaultexception error messageversion version ref message fault variable error has wrong stack trace if exception sourced from taskint operation note that the exception type and message are correct so it is as if they are incorrectly rethrowing my exception somewhere with a throw ex rather than just throwis there any way to get the correct stack trace of the exception from one of the ierrorhandler methods,['c#'] +792714,responsively align slanted divs using a modified version of this technique i have managed to make slanted responsive divs for a website i am working on the problem i am running into is that there are 3 slanted divs on top of each other and they are meant to create one diagonal line down the page so each slanted div needs to align properly with the ones around it using percentage widths for these divs has not worked so far but i am not sure what else to trya good solution for this would be responsive and preferably cssonly margin 0 padding0hero width 100 position relative border 1px solid black backgroundcolor greenslanted position relative backgroundcolor purple width 40 padding 3em 0 3em 1emslantedafter content backgroundcolor purple position absolute top 0 bottom 0 right 6em width 20em overflow visible zindex 1 webkittransform skewx13deg moztransform skewx13deg mstransform skewx13deg otransform skewx13deg transform skewx13degslanted h2 position relative zindex3hero1 slanted width 30hero2 slanted width 20hero3 slanted width 10div classhero hero1 div claslanted h2some texth2 divdivdiv classhero hero2 div claslanted herotext h2some texth2 divdivdiv classhero hero3 div claslanted herotext h2some texth2 divdivjsfiddle,"['html', 'css']" +792715,leaking views when changing rootviewcontroller inside transitionwithview while investigating a memory leak i thiscovered a problem related to the technique of calling setrootviewcontroller inside a transition animation blockuiview transitionwithviewselfwindow duration05 optionsuiviewanimationoptiontransitionflipfromleft animations selfwindowrootviewcontroller newcontroller completionnilif the old view controller the one being replaced is currently presenting another view controller then the above code does not remove the presented view from the view hierarchythat is this sequence of operationsx becomes root view controllerx presents y so that ys view is on screenusing transitionwithview to make z the new root view controllerlooks ok to the user but the debug view hierarchy tool will reveal that ys view is still there behind zs view inside a uitransitionview that is after the three steps above the view hierarchy isuiwindowuitransitionviewuiview ys viewuiview zs viewi suspect this is a problem because at the time of the transition xs view is not actually part of the view hierarchyif i send thismissviewcontrolleranimatedno to x immediately before transitionwithview the resulting view hierarchy isuiwindowuiview xs viewuiview zs viewif i send thismissviewcontrolleranimated yes or no to x then perform the transition in the completion block then the view hierarchy is correct unfortunately that interferes with the animation if animating the thismissal it wastes time if not animating it looks brokeni am trying some other approaches eg making a new container view controller class to serve as my root view controller but have not found anything that works i will update this question as i gothe ultimate goal is to transition from the presented view to a new root view controller directly and without leaving stray view hierarchies around,['ios'] +792796,what does variable as a expression mean in c this is the snippet of a program code char authenticated 0 char guard1 234 char guard2 234 more variables initliased char buf128 authenticated guard1 guard2so what does it mean when the reference stands there as a single expression in the program codeedit more context it is compiled with gcc on a debian server and it is related to a security project where you can overflow the buf array,['c'] +792803,how to unencrypt web api 2 jwt tokens i am trying to work with the oauth bearer tokens web api 2 supplies but i do not know how to unencrypt them or get the data outwhat i would really like to do is either find or write myself an equivalent tool to this google tool for the tokens i am getting from web api the google tool allows you to paste in the string of text representing a jwt token and it splits it up and unencodes the json withinin visual studio 2013 if you choose new aspnet project and then choose the web api template with individual user accounts you get a sample project that contains a token endpoint if you start the project you can then post a request grant typepasswordusernamejoepasswordjoe to token on the built in webserver and you get a token backaccess tokenx3vhm40wuxbimzi 3emdmcwlluv4fsgjsg4s5ya8kppdy 2ejn7qf5y nbq0byvikl6mnzl2gtxvmauwjippaav5vdaxokdxevxefrq exsknaqk7ivmvs1riz9eerfrgk2aq59wwqcyttyo0dpjx9k7pgrskz4adaz9sezqq4iesvhybrcwtoyxoyu5l9qdu8jxdhumkirulrqhf68riabrea bev0rzwj644frlvv3z69xohs3az7pineilynwbdck9uu2jkaxnwxocta4qlk8brlei9vxpndbcvfgb5h9wfysjcw2cmznxnhv8v9yvzet90evylwttcepxq4t3zrcqvrpbcvzrxqj8uvlfeqcsvvhliksfphby8nm2ocwtbgpzm58zle5fmi1jept0b54u38zxkzlrgqkar47jkmnc6gplrkpdbp7cwztoken typebearerexpires in1209599usernamejoeissuedfri 01 aug 2014 161602 gmtexpiresfri 15 aug 2014 161602 gmtwhat i want to find out is what format the access token is in and what information is containeda clue i found was you can choose what kind of tokens web api uses by setting the oauthauthorizationserveroptionsaccesstokenformat property in startupauthcs the documentation for oauthauthorizationserveroptions says the data format used to protect the information contained in the access token if not provided by the application the default data protection provider depends on the host server the systemweb host on iis will use aspnet machine key data protection and httplistener and other selfhosted servers will use dpapi data protection if a different access token provider or format is assigned a compatible instance must be assigned to the oauthbearerauthenticationoptionsaccesstokenprovider or oauthbearerauthenticationoptionsaccesstokenformat property of the resource serverso it is probably encoded using the machinekey that is fine i can set the machine key ok but if i know the machine key that the token was created with how do i decrypt it,"['c#', 'asp.net']" +792958,having difficulty understanding a java 8 lambda private executorservice exec executorsnewsinglethreadexecutorr thread t new threadr tsetdaemontrue allows app to exit if tasks are running return t i understand the idea behind an executor but the paramater r is confusing me i used final executorservice exec executorsnewsinglethreadexecutorr thread t new threadr systemoutprintlnclass of r rgetclass r to string rtostring systemoutprintlnclass of t tgetclass name of t tgetname tsetdaemontrue return t to dig deeper and the result isclass of r class javautilconcurrentthreadpoolexecutorworker r to string javautilconcurrentthreadpoolexecutorworker1dc3963state 1 empty queueclass of t class javalangthread name of t thread3r is being passed as a parameter to the thread object constructor how is the simple letter r indicating that the object being passed is a threadpoolexecutorhow is a threadpoolexecutorpassable as a parameter if it does not implement runnable as required by the by threads constructorif someone could provide me with a nonlambda version of the code as well it would be of great benefit to my understanding,['java'] +793102,portable hack to leak raw pointer from weak ptr i have object structure which is made of shared ptrs plus weak ptrs to avoid circularity raw pointers are a nogo as boostserialization needs to restore shared and weak pointers when deserializing via object tracking as serialization time object lifetime patterns are complex particle simulation but entirely predictable whenever i use weak ptrlock i am sure the pointer is still valid typically i use lockget as i only need the object for a very short timenow lockget has performance implications as it will increment shared count in lock and then decrement it shortly afterwards the temporary shared ptr is destructedthis boostdevel post from 2002 says that while weak ptr was being developed the functionality of accessing the raw pointer directly was considered to be named unsafe get or leak but never made it to the actual implementation its absence forces programmer to use suboptimal interface under given conditionsnow the question is how to emulate the unsafe getleak in another words get the raw pointer from weak ptr invalid at the programmers risk only reading not writing data i can imagine that some trickery like finding out the offset of the raw pointer inside shared ptr or such would do the jobi am using boostshared ptr but the solution could work for c11s stdshared ptr as well,['c++'] +793166,tyrus simple java application could not find an implementation class i am developing simple application to help me in learning websocket and tyrus concepts in java here is my serverside server endpoint and my pomxml and my client side and pomxmlserver side serverendpointvaluewebsocketclientid public class myserverendpoint private static final linkedlistsession clients new linkedlistsession onopen public void onopensession session clientsaddsession onmessage public void onmessagestring messagepathparamclientid string clientid for session client clients try clientgetbasicremotesendobjectclientid message catch ioexception e eprintstacktrace catch encodeexception e eprintstacktrace onclose public void onclosesession peer clientsremovepeer pomxmlproject xmlns xmlnsxsi xsischemalocation modelversion400modelversion groupidtyrusjacpfxservergroupid artifactidtyrusjacpfxserverartifactid version001snapshotversion packagingwarpackaging dependencies dependency groupidjavaxwebsocketgroupid artifactidjavaxwebsocketapiartifactid scopecompilescope version10version dependency dependencies build sourcedirectorysrcsourcedirectory plugins plugin artifactidmavencompilerpluginartifactid version31version configuration source17source target17target configuration plugin plugin artifactidmavenwarpluginartifactid version24version configuration warsourcedirectorywebcontentwarsourcedirectory failonmissingwebxmlfalsefailonmissingwebxml configuration plugin plugins build projectclient sidemyclientjava clientendpointpublic class myclient onopen public void onopensession session systemoutprintlnconnected to endpoint sessiongetbasicremote try sessiongetbasicremotesendtexthello catch ioexception ex onmessage public void onmessagestring message systemoutprintlnmessage onerror public void onerrorthrowable t tprintstacktrace appjavapublic class app public session session protected void start websocketcontainer container containerprovidergetwebsocketcontainer string uri wslocalhost8080tyrusjacpfxclientwebsocketdesktopclient systemoutprintlnconnecting to uri try session containerconnecttoservermyclientclass uricreateuri catch deploymentexception e eprintstacktrace catch ioexception e eprintstacktrace public static void mainstring args app client new app clientstart bufferedreader br new bufferedreadernew inputstreamreadersystemin string input try do input brreadline ifinputequalsexit clientsessiongetbasicremotesendtextinput whileinputequalsexit catch ioexception e todo autogenerated catch block eprintstacktrace pomxmlproject xmlns xmlnsxsi xsischemalocation modelversion400modelversion groupidtyrusjacpfxclientgroupid artifactidtyrusjacpfxclientartifactid version001snapshotversion dependencies dependency groupidjavaxwebsocketgroupid artifactidjavaxwebsocketapiartifactid scopecompilescope version10version dependency dependency groupidorgglassfishtyrusgroupid artifactidtyrusclientartifactid version183version dependency dependency groupidorgglassfishtyrusgroupid artifactidtyruscontainergrizzlyartifactid version11version dependency dependencies build sourcedirectorysrcsourcedirectory plugins plugin artifactidmavencompilerpluginartifactid version31version configuration source18source target18target configuration plugin plugins buildprojecti am getting this errorexception in thread main javalangruntimeexception could not find an implementation classat javaxwebsocketcontainerprovidergetwebsocketcontainercontainerproviderjava73at orghwcappstartappjava25at orghwcappmainappjava40can someone help me see the problem server is running inside glassfish 40,['java'] +793321,convert 12 hour ampm string to 24 date object using moment js i have a output resulting from a timepicker giving 12 hour format of timeeg 145 am or 1215 pm as stringis there a way to parse this string format to 24 hour using moment js back to date object,['javascript'] +793395,unregister android client from aerogear unified push server ia m facing a problem on handling the registerunregister my activitiesservices or whatever i use from an aerogear installationif i register from a service oncreate and unregister in ondestroy when i uninstall the application the device keeps registered on server side if i install the application again it registers the device again and you can repeat this until you get tired and of course sending a push to the alias given by the user the messages will arrive once per registrationalso each time the application registers to aerogear the devicetoken is different meaning that ita s got more to do with a generated hash for each installation than for a unique identifier for the pair app deviceso now the question how to handle the whole cycle and i mean the daily run and the issue about if the user decides to uninstall the app it gets killed and could not unregister and one month later decides he liked it so much that ends up reinstalling the thing againthxupdatethe problem grows as i go testing my application if i log with two different users in the same device then i get both user messages and i have got to twist a little bit more the client implementationupdate with aerogear database dataherea s the installation log for two devices with three reinstallsid alias devicetoken devicetype enabled operatingsystem osversion platform variantid0dd99505bba945e9bfbf38621bd41c3d apa91bg9xsppwbfenw0uetflrxr2xofwhlh5yzppgocivzlnv0qsqcx5ikqqhjtwf5crisbydv6itwzkxkld8optfxvuq1ekqei3xkbfajsmgij3yjuic0mgw3v2itvd6byvtzlsi9utfidxyenrxtxprzvxr9ng android 1 android 4 android 4ae832725db741f6879dc907a39bd3fc0ee3619f0eb44139b1fafe3403eb380c apa91bfrnknt7d57dfr5dage4nf1bcvyb93jl1xu5 qelwyn5jmjyupxrle10yc6bezdugae0zgtkxgli4lie roafei4xizphue8uzb6k05l miwsk7kt32d7s9g2clw3wg51zvcqmaeg8xsg vwrnwfkzqvcg android 1 android 4 android 4ae832725db741f6879dc907a39bd3fc107d4dacfbcf4f829135702b83d06f7f apa91bean4amjpzgml931ro4adrmudftmgvmypqqarvlx1rxifyyb46fgxlsk0w7g3qnu2d cvobi907tfimoxbaoe3bvki8dqsacrxmmtdjhfofrs2z4qcec9u0arpmeb9uwhfmre3rrctdxddncq0douuppyvq android 1 android 4 android 4ae832725db741f6879dc907a39bd3fc161474b6067d4b54a750e21a9896814e apa91bgfe6cxlcxpdormvheipa2jqndccrcryur3q5bn4pg3eyhxisfomciwappxx8biinrjovncbwpirvokw msv5tclznsgonr1grpirkj0mmwbfcme2crwompklkvup7zjwnysr0hr3mkzmjlakrnlnemkrg android 1 android 4 android 4ae832725db741f6879dc907a39bd3fca5cddabe1c004369b4ccf6c5da8f8740 apa91bgmft7ncpfb1q4whfk2wmqcqdmtw9ulqlizywrt9oyu4mqv9gcbn959pcw wky2zhwjbu0p5sczdpkn5l8i7uqpwk24orhke1vf6rruinkirjhekvt6v6wk38wq7rw1agrqyxzn7wuimvsgd5cqq p8llisg android 1 android 4 android 4ae832725db741f6879dc907a39bd3fcf751471668d94d00837af1f9da503151 apa91bhtfje7nz kb4aa2rucenftvb0izqzzffptujlwgi60xtmueaet6youzjnxknhbosdapgoaldw18pwnwkxtc2mxxkjmyqqennddoxkqiv4fnmrafwfwd vt6x5xojuwdqovguwximx9sshcdvzj4qnm1x w android 1 android 4 android 4ae832725db741f6879dc907a39bd3fc,['android'] +793433,pandas to csv first extra column remove how to i am trying to create csv with pandas but when i export to csv it gave me one extra row d one pdseries1 2 3two pdseries1 2 3 4df0 fa pddataframeddf csv df0 fato csvrevenuedatatestcsvmode wso my result would be onetwo010101202023030340but what i want isonetwo10102020303040,['python'] +793435,questions on fork i am trying to understand fork and so i put together the following exampleinclude stdiohinclude systypeshinclude unistdhvoid main iffork0 printf2 iffork0 printf4 else printf3 else printf1 when i was tracing this on paper i drew the following sketch so i believe the output should be 1234 however when i run this code the output is 12324 why is that where is my mistakeupdateafter reading the comments it was suggested to do any of the followingadd n to each printf statementor add fflushstdout after each printf statementor add setbufstdout null this is what i endedup doing after updating my code the output was indeed 1234,['c'] +793436,exc bad access when updating swift dictionary after using it for evaluate nsexpression i am using a dictionary to evaluate an expression when the expression has variables and the dictionary is actually used by nsexpression something happens and i get exc bad access when trying to update the dictionary this only happens when debugging in an iphone6 not in the simulator and not in an iphone 4s let strexpression ab20 let exp nsexpressionformatstrexpression selfdictionary a100 b150 c250 let valueanyobject expexpressionvaluewithobjectselfdictionary context nil let doublevalue value as double selfdictionaryupdatevaluedoublevalue forkey c something really weird is that if i add this line just after creating the dictionary then it woks finelet newdic selfdictionary im using ios 81 thanks in advance,['ios'] +793555,rate limit exceeded error when using google cloud messaging api when using the google cloud messaging api to send messages between a backend server and an androidchrome client the backend server can at times receive a rate limit exceeded response code this code is adevicemessagerateexceededa for a http connection server and adevice message rate exceededa for a cloud connection serverwhat is this error code and how should it be managed,['android'] +793580,simulator is not available error xcode 61 i am about to upload the latest version of my app to the app store however up until this point i have not done a whole lot of testing on ios 7when i go to use the simulator i am getting the erroriphone 4s is not available please select a different device and try againmy deployment target is set correctly to 70has anyone experienced this error any solutions,['ios'] +793584,es6 module concatenation developing a web project in javascript es6 i currently use traceur to compile my modules from es6 to es5 thinking that in the future when browser will support es6 i would be able to skip that transpilation stepin the end because i do not want to download several js pieces at start up i have a single file that contains all my modules converted into es5 thanks to traceurbut to validate this choice i was wondering if this could still be possible the day i would keep the source in es6 if i simply concatenate them there will be invalid imports and name conflictsit looks like it has not been designed for it and it would require a extra processing step to merge them correctlyhow are we suppose to handle es6 single file project defined with several modules,['javascript'] +793599,javalangunsupportedoperationexception unsupported service accessibility android studio i have ran into a problem with this unsupportedoperationexception i have recently switched to android studio so it is quite new for me i wanted to add the recyclerview into my project and do stuff with it but the layout designer throws me this errorjavalangunsupportedoperationexception unsupported service accessibilityat comandroidlayoutlibbridgeandroidbridgecontextgetsystemservicebridgecontextjava465at androidsupportv7widgetrecyclerviewinitrecyclerviewjava290at androidsupportv7widgetrecyclerviewinitrecyclerviewjava266at sunreflectnativeconstructoraccessorimplnewinstance0native methodat sunreflectnativeconstructoraccessorimplnewinstancenativeconstructoraccessorimpljava39at sunreflectdelegatingconstructoraccessorimplnewinstancedelegatingconstructoraccessorimpljava27at javalangreflectconstructornewinstanceconstructorjava513at orgjetbrainsandroiduipreviewviewloadercreatenewinstanceviewloaderjava379at orgjetbrainsandroiduipreviewviewloaderloadviewviewloaderjava99at comandroidtoolsidearenderinglayoutlibcallbackloadviewlayoutlibcallbackjava172at androidviewbridgeinflaterloadcustomviewbridgeinflaterjava207at androidviewbridgeinflatercreateviewfromtagbridgeinflaterjava132at androidviewlayoutinflaterrinflate originallayoutinflaterjava806at androidviewlayoutinflater delegaterinflatelayoutinflater delegatejava64at androidviewlayoutinflaterrinflatelayoutinflaterjava782at androidviewlayoutinflaterinflatelayoutinflaterjava504at androidviewlayoutinflaterinflatelayoutinflaterjava385at comandroidlayoutlibbridgeimplrendersessionimplinflaterendersessionimpljava401at comandroidlayoutlibbridgebridgecreatesessionbridgejava329at comandroididecommonrenderinglayoutlibrarycreatesessionlayoutlibraryjava3at comandroidtoolsidearenderingrenderservice5computerenderservicejava674at comandroidtoolsidearenderingrenderservice5computerenderservicejava663at comintellijopenapiapplicationimplapplicationimplrunreadactionapplicationimpljava932at comandroidtoolsidearenderingrenderservicecreaterendersessionrenderservicejava663at comandroidtoolsidearenderingrenderservicerenderrenderservicejava790at comintellijandroiddesignerdesignsurfaceandroiddesignereditorpanel6runandroiddesignereditorpaneljava480at comintellijutiluiupdatemergingupdatequeueexecutemergingupdatequeuejava320at comintellijutiluiupdatemergingupdatequeueexecutemergingupdatequeuejava310at comintellijutiluiupdatemergingupdatequeue2runmergingupdatequeuejava254at comintellijutiluiupdatemergingupdatequeueflushmergingupdatequeuejava269at comintellijutiluiupdatemergingupdatequeueflushmergingupdatequeuejava227at comintellijutiluiupdatemergingupdatequeuerunmergingupdatequeuejava217at comintellijutilconcurrencyqueueprocessorrunsafelyqueueprocessorjava238at comintellijutilalarmrequest1runalarmjava327at javautilconcurrentexecutorsrunnableadaptercallexecutorsjava439at javautilconcurrentfuturetasksyncinnerrunfuturetaskjava303at javautilconcurrentfuturetaskrunfuturetaskjava138at javautilconcurrentthreadpoolexecutorworkerruntaskthreadpoolexecutorjava895at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava918at javalangthreadrunthreadjava662what should be the problem i do not honestly know i have watched tutorials for implementing recyclerview into the project but this is what android studio gives me back after i use the official google codeedit it seems it is resolved as the answer i accepted is correct but i did not tried it on my ownedit as i accepted the current answer it is somewhat relevant to my issue but it is not a full solution if anyone can or could provide some fix or workaround to this i will update the accepted answer as long as its providing such an information or if the issue was solved by intellij or whoever is the developer also thank you dave for pointing out where it fails at least we can write a ticket to devs,"['java', 'android']" +793618,historyreplacestate still adds entries to the browsing history specifically calling the following snippet of codehistoryreplacestateundefined undefined valuewill correctly not affect the back button behavior of the current page but will add an entry to the browsing history page pictured below is chromes but this also happens in firefoxis there some way to replace the current url without adding an entry to the users browsing history,['javascript'] +793725,android palette why not working with this particular image i am currently working with the palette api from support library the code below works fine with hundreds of pictures no problem at all i set the text and background color depending on the palette results the result is awesome and really nice looking if you want to reuse it in your application do not hesitateunfortunately in hundreds of pictures only one is not working and gives weird resultsthis is this one as the palette has no documentation or debug mode i really wonder what could happen and if there is a way to understand if there is a flaw in the original picture or whateverpicassowithgetactivityloadintotprivate target t new target override public void onbitmaploadedbitmap bitmap picassoloadedfrom from palettegenerateasyncbitmap new palettepaletteasynclistener public void ongeneratedpalette palette imageview vfindviewbyidridivsetimagedrawablenew bitmapdrawablebitmap at this point the imageview is correctly filled so the bitmap object has no issue int textcolor palettegetlightmutedcolorandroidrcolordarker gray int bgcolor palettegetdarkmutedcolorandroidrcolorwhite logdcvetextcolorint textcolor logdcvebgcolorint bgcolor logdcvetextcolorhexa stringformat06x 0xf textcolor logdcvebgcolorhexa stringformat06x 0xf bgcolor and this is the outputtextcolorint 17170432bgcolorint 17170443textcolorhexa 060bgcolorhexa 060bif someone could help me to reproduce the bug or tell me that it is only happening on my side this would be awesome,['android'] +793785,protractor switch to previous tab after opening a new tab second i am trying to switch to the first tab commonclickopennewsession it opens the new tab browsergetallwindowhandlesthenfunction handles var secondwindowhandle handles1 var firstwindowhandle handles0 browserswitchtowindowsecondwindowhandlethenfunction the focus moves on new tab browsersleep30 expectbrowserdrivergetcurrenturltocontainurldo some actions below it does not work i try to go back on previous tab without closing the second tab browseractionssendkeysprotractorkeycontrolsendkeysprotractorkeytabperform browsersleep40 browserdriverswitchtowindowfirstwindowhandle browsersetlocation,['javascript'] +794026,nsubstitute testfixture 1 causes ambiguousargumentsexception in testfixture 2 i am writing c unit tests using nunit and nsubstitute i am testing a class which will attempt to retrieve objects from a config provider implementing the following interfacepublic interface iconfigprovidert t getconfigint id t getconfigstring idthe class being tested only uses the int version of getconfig so in the setupfixture i do the following to set up a mocked config provider that will always return the same dummy objecticonfigproviderconfigtype configprovider substituteforiconfigproviderconfigtypeconfigprovidergetconfigarganyintreturnsconfigtypenew configtype args this runs absolutely fine if that testfixture is the only one being run however in a different testfixture in the same assembly i check for received calls like thisconnectionreceived1setcallbacksarganyactionmessage arganyactionlong arganyactionlong exceptionif these received tests run before the config provider tests then the config tests fail in the setupfixture with an ambiguousargumentsexceptionherebenamespaceprofilemanagertestssetup testfixturesetupsetup nsubstituteexceptionsambiguousargumentsexception cannot determine argument specifications to useplease use specifications for all arguments of the same typeat nsubstitutecoreargumentsnonparamsargumentspecificationfactorycreateobject argument iparameterinfo parameterinfo isuppliedargumentspecifications suppliedargumentspecificationsat systemlinqenumerableselectiteratord 72movenextat systemcollectionsgenericlist1ctorienumerable1 collectionat nsubstitutecoreargumentsmixedargumentspecificationsfactorycreateilist1 argumentspecs object arguments iparameterinfo parameterinfosat nsubstitutecoreargumentsargumentspecificationsfactorycreateilist1 argumentspecs object arguments iparameterinfo parameterinfos matchargs matchargsat nsubstitutecorecallspecificationfactorycreatefromicall call matchargs matchargsat nsubstituteroutinghandlersrecordcallspecificationhandlerhandleicall callat systemlinqenumerablewhereselectarrayiterator2movenextat systemlinqenumerablefirstordefaulttsourceienumerable1 source func2 predicateat nsubstituteroutingroutehandleicall callat nsubstituteproxiescastledynamicproxycastleforwardinginterceptorinterceptiinvocation invocationat castledynamicproxyabstractinvocationproceedat castleproxiesiconfigprovider1proxygetconfigint32 idat herebenamespaceprofilemanagertestssetupdosetupwhats really confusing me is that i can observe this effect even between test runs if i use the nunit gui to run the received tests alone and then run the config tests alone the config tests will fail if i then immediately run the config tests again they will passthings i have triedadding configprovidergetconfigarganystringreturns as well in case the overloading was the problemi have read the nsubstitute docs on argument matching but i cannot find a solution there if it is a case of having to supply argument matchers for both the int and string versions of the method i cannot work out how to do thatas it happens the tests i am using will only ever call the getconfig method with values of 0 or 1 so i can just provide returns specifications for those two values and not use matching at all but i want to understand how to fix this more generally,['c#'] +794080,can switching inandout pyframeobjects be a good implementation of continuations i am interested in continuations specifically in pythons capi from what i understand the nature of continuations requires unabstracting lowlevel calling conventions in order to manipulate the call stack as needed i was fortunate enough to come across a few examples of these scattered here and there in the few examples i have come across this unabstraction is done using either clever c with assumptions about the environment or custom assemblyhowever whats cool about python is that it has its own interpreter stack made up of pyframeobjects assuming singlethreaded applications for now should not it be enough to just switch inandout pyframeobjectss to implement continuations in pythons capi why do these authors even bother with the lowlevel stuff,"['python', 'c']" +794083,http thisconnecttimeout between request and response handling assume following scenarioclient is sending http post to server request is valid andhave been processed by server data has been inserted into databaseweb application is responding to client client meets timeoutand does not see http responsein this case we meet situation where client does not know if his data was valid and been inserted properly web server rails 32 application does not show any exception no matter if it is behind apache proxy or noti cannot find how to handle such scenario in http documentation my question area should client expect that his data may be processed already so then try for example get request to check if data has been submittedb if not a should server detect it is there possibility to do it in rails in such case changes can be reversed in such case i would expect some kind of expection from rails application but there is not,['ruby-on-rails'] +794113,css only animate draw circle with borderradius and transparent background i am trying to draw a circle with borderradius and animate it i can do this but what i cannot do is overlay elements and set the circles background to transparent without unhiding the mask i am not able to make it transparent over elements because the mask needs to be applied to hide the left half of the circle as it rotates to mimic the draw effecthtmldiv classbackground div classwrapper div classpie spinnerdiv div classpie fillerdiv div classmaskdiv divdivcssbackground backgroundgreen zindex 10wrapper width 250px height 250px position relative margin 40px auto background rgba002551wrapper wrapper mozboxsizing borderbox webkitboxsizing borderbox boxsizing borderboxwrapper pie width 50 height 100 transformorigin 100 50 position absolute background transparent border 5px solid rgba09wrapper spinner borderradius 100 0 0 100 50 0 0 50 zindex 0 borderright none webkitanimation rota 5s linear infinitewrapperhover spinnerwrapperhover fillerwrapperhover mask animationplaystate runningwrapper filler borderradius 0 100 100 0 0 50 50 0 left 50 opacity 0 webkitanimation opa 5s steps1 end infinite reverse borderleft nonewrapper mask width 50 height 100 position absolute background inherit opacity 1 webkitanimation opa 5s steps1 end infinitewebkitkeyframes rota 0 transform rotate0degbordercolorred 100 transform rotate360degzindex0webkitkeyframes opa 0 opacity 1 50 100 opacity 0in my example i need to change the blue background to transparent without unhiding the borderradius before it starts rotatingexcuse the colors these are not what i will be working with but provide a clearer approach to the issue this is my temporary product where i have to remove the draw to accomplish the transparency,['css'] +794145,is it good practice to lock a pthread mutex before destroying it class a a pthread mutex lock m mutex pthread mutex destroy m mutex question i saw this code somewhere in a project is it good practice to do soor it is undefined behavior to lock a mutex before destroying it,['c++'] +794282,how to install maven on osx 1010 yosemite i am trying to install maven on my mac but i can not get the java home variable right the path that the maven website gives isusrjavajdk170 51however the java folder does not exist in usr for me i installed the jre and jdk nothing changed how can i fix this,['java'] +794401,java8 collectionssort sometimes does not sort jpa returned lists java8 keeps doing strange things in my jpa eclipselink 252 environment i had to delete the question yesterday since the sorting in that case was influenced by a strange jpa behaviour i found a workaround for that one by forcing the first sort step before doing the final sortstill in java 8 with jpa eclipselink 252 the following code some times does not sort in my environment linux macosx both using build 180 25b17 it works as expected in the jdk 17 environmentpublic listdocument getdocumentsbymodificationdate listdocument docsthisgetdocuments loggerloglevelinfosorting docssize by modification date comparatordocument comparatornew bymodificationcomparator collectionssortdocscomparator return docswhen called from a junit test the above function works correctlywhen debbuging in a production environment i get a log entryinformation sorting 34 by modification datebut in timsort the return statement with nremaining 2 is hit so no sorting happens the indirectlist see what collections does jpa return supplied by jpa is considered to be emptystatic t void sortt a int lo int hi comparator super t c t work int workbase int worklen assert c null a null lo 0 lo hi hi alength int nremaining hi lo if nremaining 2 return arrays of size 0 and 1 are always sortedthis workaround sorts correctly if docs instanceof indirectlist indirectlist ilist indirectlistdocs object sorttargetobject ilistgetdelegateobject if sorttargetobject instanceof list listdocument sorttargetlistdocument sorttargetobject collectionssortsorttargetcomparator else collectionssortdocscomparator question is this a jpa eclipselink bug or what could i generally do about it in my own code please note i cannot change the software to java8 source compliance yet the current environment is a java8 runtime i am suprised about this behaviour it is especially annoying that the testcase runs correctly while in production environment there is a problemthere is an example project at which has a comparable structure as the original problem it contains a example with a junit test which makes the issue reproducible by calling emclear thus detaching all objects and forcing the use of an indirectlist see this junit case below for reference with eager fetching onetomanycascade cascadetypeall mappedby parentfolder fetchfetchtypeeagerthe unit case works if fetchtypelazy is used or the fetch type is omitted in jdk 8 the behaviour might be different than in jdk 7 i will have to check this now why is that soat this time i assume one needs to specify eager fetching or iterate once over the list to be sorted basically fetching manually before sorting what else could be donejunit testpersistencexml and pomxml can be taken from the test can be run with a mysql database or inmemory with derby defaultpackage combitplanjava8sortingimport static orgjunitassertassertequalsimport javautilarraylistimport javautilcollectionsimport javautilcomparatorimport javautilhashmapimport javautillistimport javautilmapimport javautillogginglevelimport javautilloggingloggerimport javaxpersistenceaccessimport javaxpersistenceaccesstypeimport javaxpersistencecascadetypeimport javaxpersistenceentityimport javaxpersistenceentitymanagerimport javaxpersistenceentitymanagerfactoryimport javaxpersistencefetchtypeimport javaxpersistenceidimport javaxpersistencemanytooneimport javaxpersistenceonetomanyimport javaxpersistencepersistenceimport javaxpersistencequeryimport javaxpersistencetableimport orgeclipsepersistenceindirectionindirectlistimport orgjunittest testcase for author wf public class testjpasorting the number of documents we want to sort public static final int num documents 3 logger for debug outputs protected static logger logger loggergetloggercombitplanjava8sorting a classic comparator author wf public static class bynamecomparator implements comparatordocument override public int comparedocument d1 document d2 loggerloglevelinfocomparing d1getname d2getname return d1getnamecomparetod2getname document entity the sort target entityname document tablename document accessaccesstypefield public static class document id string name manytoone folder parentfolder return the name public string getname return name param name the name to set public void setnamestring name thisname name return the parentfolder public folder getparentfolder return parentfolder param parentfolder the parentfolder to set public void setparentfolderfolder parentfolder thisparentfolder parentfolder folder entity owning entity for documents to be sorted entityname folder tablename folder accessaccesstypefield public static class folder id string name onetomanycascade cascadetypeall mappedby parentfolder fetchfetchtypeeager listdocument documents return the name public string getname return name param name the name to set public void setnamestring name thisname name return the documents public listdocument getdocuments return documents param documents the documents to set public void setdocumentslistdocument documents thisdocuments documents get the documents of this folder by name return a sorted list of documents public listdocument getdocumentsbyname listdocument docs thisgetdocuments loggerloglevelinfo sorting docssize documents by name if docs instanceof indirectlist loggerloglevelinfo the document list is an indirectlist comparatordocument comparator new bynamecomparator here is the culprit do or do not we sort correctly here collectionssortdocs comparator return docs get a folder example for testing return a test folder with num documents documents public static folder getfolderexample folder folder new folder foldersetnametestfolder foldersetdocumentsnew arraylistdocument for int inum documentsi0i document documentnew document documentsetnametesti documentsetparentfolderfolder foldergetdocumentsadocument return folder possible database configurations using generic persistencexml xml version10 encodingutf8 generic persistencexml which only specifies a persistence unit name persistence xmlns version20 persistenceunit namecombitplanjava8sorting transactiontyperesource local descriptionsorting testdescription providerorgeclipsepersistencejpapersistenceproviderprovider excludeunlistedclassesfalseexcludeunlistedclasses properties set programmatically properties persistenceunit persistence in memory database public static final jpasettings jpa derbynew jpasettingsderbyorgapachederbyjdbcembeddeddriverjdbcderbymemorytestjpacreatetrueappapp mysql database needs preparation create database testsqlstorage grant all privileges on testsqlstorage to cmlocalhost identified by secret public static final jpasettings jpa mysqlnew jpasettingsmysqlcommysqljdbcdriverjdbcmysqllocalhost3306testsqlstoragecmsecret wrapper class for jpasettings author wf public static class jpasettings string driver string url string user string password string targetdatabase entitymanager entitymanager param driver param url param user param password param targetdatabase public jpasettingsstring targetdatabasestring driver string url string user string password thisdriver driver thisurl url thisuser user thispassword password thistargetdatabase targetdatabase get an entitymanager based on my settings return the entitymanager public entitymanager getentitymanager if entitymanager null mapstring string jpaproperties new hashmapstring string jpapropertiesputeclipselinkddlgenerationoutputmode both jpapropertiesputeclipselinkddlgeneration dropandcreatetables jpapropertiesputeclipselinktargetdatabase targetdatabase jpapropertiesputeclipselinklogginglevel fine jpapropertiesputjavaxpersistencejdbcuser user jpapropertiesputjavaxpersistencejdbcpassword password jpapropertiesputjavaxpersistencejdbcurlurl jpapropertiesputjavaxpersistencejdbcdriverdriver entitymanagerfactory emf persistencecreateentitymanagerfactory combitplanjava8sorting jpaproperties entitymanager emfcreateentitymanager return entitymanager persist the given folder with the given entitymanager param em the entitymanager param folderjpa the folder to persist public void persistentitymanager em folder folder emgettransactionbegin empersistfolder emgettransactioncommit check the sorting assert that the list has the correct size num documents and that documents are sorted by name assuming test to be the name of the documents param sorteddocuments the documents which should be sorted by name public void checksortinglistdocument sorteddocuments assertequalsnum documentssorteddocumentssize for int i1inum documentsi document documentsorteddocumentsgeti1 assertequalstestidocumentgetname this test case shows that the list of documents retrieved will not be sorted if jdk8 and lazy fetching is used test public void testsorting get a folder with a few documents folder folderfoldergetfolderexample get an entitymanager jpa derbyinmemory jpa mysqlmysql thisk database entitymanager emjpa derbygetentitymanager persist the folder persistemfolder sort list directly created from memory checksortingfoldergetdocumentsbyname detach entities emclear get all folders from database string sqlselect f from folder f query query emcreatequerysql suppresswarningsunchecked listfolder folders querygetresultlist there should be exactly one assertequals1folderssize get the first folder folder folderjpafoldersget0 sort the documents retrieved checksortingfolderjpagetdocumentsbyname,['java'] +794429,why i cannot save wkwebview to nsuserdefaults standarduserdefaults nsuserdefaults prefs nsuserdefaults standarduserdefaultsprefs setobjectselfwebview forkeywebviewthe code above is made to save a wkwebview object but i am getting a compiler error20141108 145852561 restoration2431482391 property list invalid for format 200 property lists cannot contain objects of type cftype 20141108 145852564 restoration2431482391 attempt to set a nonpropertylist object as an nsuserdefaultscfpreferences value for key webview 20141108 145852566 restoration2431482391 terminating app due to uncaught exception nsinvalidargumentexception reason attempt to insert nonproperty list object for key webview first throw call stack 0x2c491c1f 0x39c78c8b 0x2c491b65 0x2c4cbe51 0x2c436599 0x2c4358d7 0x2c4cc0d1 0x2c4cb769 0x2c4ce95b 0x2c4ce875 0x2d0eab69 0x66bdf 0x2f981c2b 0x2f981bd1 0x2f96c863 0x2f98163d 0x2f981317 0x2f97abe1 0x2f9513dd 0x2fbc4c29 0x2f94fe39 0x2c458377 0x2c457787 0x2c455ded 0x2c3a4211 0x2c3a4023 0x3379d0a9 0x2f9b01d1 0x66ead 0x3a1f8aaf libcabidylib terminating with uncaught exception of type nsexceptionhow can i save the wkwebview and restore it with its history intactedit8 months have passed and there is no solution to this problemedit 2i am making a web browser and it is crucial when the user restarts the app the web views tabs to restore so he can press the back button and go backif i save the previous urls in a simple list i cannot put them back into the web view when the app restarts i can only load the first page so the user cannot press back because there is no page to back if it was as simple as saving a list of urls i wouldnt start a bounty since a web browser is a very complex app i have been very close to the fundamentals of the webviews and i have even submitted 3 bugs from which only 2 have been resolved including the infamous screenshot bugthe standarduserdefaults method does work with uiwebview but apple states that all developers should use the wkwebview following the release of ios 7 i am expecting uiwebview to be deprecated in the near future,"['ios', 'objective-c', 'iphone']" +794437,didregisterforremotenotificationswithdevicetoken never called on specific device first of all i am on iphone 6 plusios 81 and i have tried everything here why didregisterforremotenotificationswithdevicetoken is not calledstill no avail to summarizei have checked my bundle identifier matches the one in provisioning profiledevelopment portali have created a new development push apns certificatei have created a new development certificatei have created a new provisioning profile for that development certificatei have downloaded both the certificate and provisioning profile and obviously double clicked them to installi have verified that everything is right on developer portal all certificates and provisioning profiles valid push enabled and configured with my new apns certificatei have uploaded my new apns certificate to parse it is irrelevant at this step but anyway as i am using parse for my backendi have made sure that i am using the correct certificateprovisioning profile pair at xcode to codesigni have checked notifications settings in case my app is not allowed to receive pushes it is not therei have tried setting date manually to tomorrow and tried reinstalling the appi have deleted the app from my devicei have deleted any related provisioning profiles from my devicei have restarted my device multiple timesin applicationdidfinishlaunchingwithoptions i callifapplication respondstoselectorselectorregisterusernotificationsettings ios 8 application registerusernotificationsettingsuiusernotificationsettings settingsfortypesuiusernotificationtypesound uiusernotificationtypealert uiusernotificationtypebadge categoriesnil else preios 8 uiapplication sharedapplication registerforremotenotificationtypes uiremotenotificationtypebadge uiremotenotificationtypesound uiremotenotificationtypealert in applicationdidregisterusernotificationsettings i callapplication registerforremotenotificationsi have checked it with a breakpoint it does get called i have also implemented two methodsapplicationdidregisterforremotenotificationswithdevicetokenandapplicationdidfailtoregisterforremotenotificationswitherrorhowever neither of them is called not an error nothing no error at the console either i have had an issue about entitlements earlier today but creating new certificateprovisioning profile solved thatwhat could be the issueupdate here is something in applicationdidregisterusernotificationsettings i have checked the notification settings and here is what i have gotlldb po notificationsettingsuiusernotificationsettings 0x170031cc0 types noneupdate 2 i have checked notifications again and found out that now my app is added to the notifications in settings it is enabled given permissions but still the handler is not calledtypes are none i am 99 sure it is related to the problemupdate 3 i have tested on another device ipod touch ios 81 and i have got no problems there it immediately called the applicationdidregisterforremotenotificationswithdevicetoken method with its token the problem is specific to my iphone,['ios'] +794659,looking for an example of the new android api setmediabuttonreceiver currently i am using maudiomanagerregistermediabuttoneventreceivermremotecontrolresponderbut this is now deprecated in 50 and replaced by setmediabuttonreceiver there are 5 links in google all pointing to developerandroidcomhas anyone used this yet if so can you provide an example,['android'] +794717,python3 urllibrequest will not close connections immediately i have got the following code to run a continuous loop to fetch some content from a websitefrom httpcookiejar import cookiejarfrom urllib import requestcj cookiejarcp requesthttpcookieprocessorcjhh requesthttphandleropener requestbuild openercp hhwhile true build url req requestrequesturlurl p openeropenreq c pread process c pclose check for abort condition or continuethe contents are correctly read but for some reason the tcp connections would not close i am observing the active connection count from a ddwrt router interface and it goes up consistently if the script continue to run it will exhaust the 4096 connection limit of the router when this happens the script simply enter waiting state the router would not allow new connections but timeout has not hit yet after couple minutes those connections will be closed and the script can resume againi was able to observe the state of those hanging connections from the router they share the same state time wait i am expecting this script to use no more than 1 tcp connection simultaneously what am i doing wrongi am using python 342 on mac os x 1010,['python'] +794841,reading a symbolic link in kernelspace i am writing a lkm and need to find out where a specific symlink is pointing to basically i need the functionality of the syscall readlinkat or readlink but in kernelspace is there an easy way to do thisusing readlinkat directly is not working for me i am always getting efault i guess this is because my buffer is obviously in kernel memory space and not in userspace,['c'] +794945,angular img src console error i am using ngrepeat to print all the images from desired folder and those images are in a because i am using fancyboxheres an example of controllervar parentctrl function scope scopegettimesfunctionn for the ngrepeat return new arrayn appcontrollerprojectcontroller scopeinjector functionscope injector injectorinvokeparentctrl this scope scope scopetitle project scopeimage url imgproject scopeimage num 14 image count 0jpg 1jpg 2jpg 13jpgand the templatea href classfancybox relprojectgallery datangrepeatt in gettimesimage num track by index datanghrefimage urlindexjpg img srcimage urlindexjpgaand this code works fine it shows all the 14 images however i am getting this error in the consoleget httplocalhostprojectsprojectname7b7bimage urlindexjpg7d7d 404 not foundhow to fix that error,['javascript'] +795034,how can i access constants in the libconstantsjs file in meteor i followed the documentation to put the constants in the libconstantsjs file however i am unsure how to access these constants in my client side html and js files how can i do this,['javascript'] +795111,the application icon does not show on action bar i followed up the instructions of building a new android project and i got a runnable one except a problem with action bar the problem is that the application icon is not showed beside the application title on action bar i created the project with the configuration belowminimum required sdkapi 8 android 22froyo target sdkapi 21android 4xl previewcompile withapi 21android 4xl preview themeholo light with dark action bareclipse set the corresponding appcompat themeandroid support library 2101android sdk buildtools 21because my minimum sdk is api 8 which does not support action bar so the project includes a appcompat v7 library to allow the action bar feature if i set the minimum sdk to api 14android 40 or higher then the project does not include appcompat v7 library and application icon is showed successfully also but i need my app to support older android os as low as api 8 so what should i do to fix this problem really appreciate you guys attentionps i went through the task above on windows mac eclipse android studio and got the same result,['android'] +795115,autofac register assembly types in castle i used to do the following to register types from a different assemblyclassesfromassemblynamedmyserverdal wheretype typenameendswithrepository withserviceallinterfaces lifestyleperwebrequestin autofac i change the above code to thisbuilderregisterassemblytypesappdomaincurrentdomaingetassemblies wheret tnameendswithrepository instanceperrequestis it correct,['c#'] +795144,storing dates with morethan4digits years i need a way to serialize and unserialize dates that are potentially far away in the past for instance 10i first look at iso8601 but it does not seem to support years with more than four digits or at least python libraries i tried do notthe different solutions i can think ofchange the year before serializingdeserializing give it to the parsingformatting library and fix it back sounds hackydefine my own format like yearmonthdayhourminutesecond that is reinventing the wheel since i have to handle timezones etcuse a unix timestamp without bounds or something equivalent may overflow in some programming languages and still the timezone stuffstore dates before 9 or 0 differently than those after since there was no timezone issueleap yearsa issue at that time two different formats at the same placedo you see any other way that would be better than these ones or recommand one of those,"['javascript', 'php', 'python']" +795208,prioritizing class specializations let us say we have a dual parametrized template liketemplateclass a class bclass class and that there are specializations for a particular a and a particular btemplateclass b class classa1b templateclass a class classab1 now when i have to instantiate classa1b1 the compiler complains for ambiguity since it find ab1 and a1b equally usablethe problem can of course be eliminated by adding an a1b1 specialization but in my context it will be identical a1bis there a way to eliminate the ambiguity without repeating the entire a1b full code,['c++'] +795427,stopping a service that reads msmq i am a java programmer who has been asked to make some changes to c applications i have been working with c for a week now and i have finally hit a point where looking at the documentation is not helping and i cannot find solutions when i googlein this case i have a windows service that processes messages that arrive in a msmq when a message is received the currently listening thread picks it up and goes off to do an operation that takes a couple of secondspublic void start thislisten true for int i 0 i constantsthreadmaxcount i threadpoolqueueuserworkitemnew waitcallbackthisstartlistening i private void startlisteningobject threadcontext int threadid intthreadcontext threadsthreadid threadcurrentthread postrequest postreq whilethislisten systemthreadingmonitorenterlocker try postreq gettingamessage finally systemthreadingmonitorexitlocker gettingamessage has the following lines that listen for a messagetaskmessage ts taskfactoryfromasyncmessage queuebeginreceive queueendreceivetswaitthe problem is when the stop method is called and there are no messages going into the msmq the threads all sit there waiting for a message i have tried using timeouts but that method does not seem elegant to meand having switched over to the task factory i am not sure how to implement them currently my solution to this was to add a reference of each thread to an array so that i could cancel them the following is called by each worker thread after being createdthreadsthreadid threadcurrentthreadand then supposed to be aborted bypublic void stop try thislisten false foreachthread a in threads aabort catch any advice on why this is not shutting the threads down or even better can anyone tell me where i should look for how to cancel the tswait properly,['c#'] +795477,inset drawable not working as described in documentation as described on android developer site a drawable defined in xml that insets another drawable by a specified thistance this is useful when a view needs a background that is smaller than the views actual bounds instead of just moving the background and leaving the content in place in my case the inset is also moving the textview this is the layout xml version10 encodingutf8linearlayout xmlnsandroid androidlayout widthmatch parent androidlayout heightmatch parent androidbackgroundandroidcolorwhite androidorientationvertical linearlayout androidlayout widthmatch parent androidlayout heightmatch parent androidbackgrounddrawablebg inset androidorientationhorizontal textview androidididtext1 androidlayout widthwrap content androidlayout heightwrap content androidtextsome text androidtextsize23sp linearlayoutthis is the bg inset drawablexml version10 encodingutf8inset xmlnsandroid androiddrawableandroidcolordarker gray androidinsetleft100dp and this is the result i get,['android'] +795505,android gradle build error9 0 gradle dsl method not found compile i am getting the following build error when i try and sync my project error9 0 gradle dsl method not found compilepossible causesthe project alextest may be using a version of gradle that does not contain the methodthe build file may be missing a gradle pluginlink apply gradle plugini have tried applying every single gradle plugin they link me to in that link on the bottom yet same issue so i conclude that the first error is the cause here is the buildgradle file for alextest the project directorybuildscript repositories jcenter dependencies classpath comandroidtoolsbuildgradle0132 compile comgoogleandroidgmsplayservices61 note do not place your application dependencies here they belong in the individual module buildgradle files allprojects repositories jcenter i think that was the gradle file it was having trouble with but i am not sure what method it is referring to also here is the gradlewrapperproperties which it also referred tomon nov 10 010612 pst 2014thistributionbasegradle user homethistributionpathwrapperthistszipstorebasegradle user homezipstorepathwrapperthiststhistributionurlperhaps the gradle version in the thistributionurl needs to match the one in the dependencyi also have a buildgradle file in the app directory itself 1 level lower though i do not think that is what it was referring to but here it is apply plugin comandroidapplicationandroid compilesdkversion 20 buildtoolsversion 21 defaultconfig applicationid comsnappiestickeralextest minsdkversion 16 targetsdkversion 20 versioncode 1 versionname 10 buildtypes release runproguard false proguardfiles getdefaultproguardfileproguardandroidtxt proguardrulespro dependencies compile filetreedir libs include jar compile comgoogleandroidgmsplayservices61,['android'] +795537,set printer tray when printing excel document i have seen many posts with regards to setting printer tray in c for word document i need a solution for excel a better solution if possible for any document some kind of method i can pass a file path and the trayeditso far i have tried the following but no visible changes have been made in the printer settingsprintersettings ps new printersettingspsprintername localhosthp4515nvar dps psdefaultpagesettingsdpspapersourcerawkind 260orprintersettings ps new printersettingspsprintername localhosthp4515npapersource psrc new papersourcepsrcrawkind 260psrcsourcename unknowndpspapersource psrcedit 2i am hardcoding rawkind since the tray somehow does not show in the papersourcesand currently when i print eg excel document i show the printerdialog get the name of the selected printer and pass it to interop excel active printer property but now i need to print mass of documents and i need to set the selected printer and it is property specially the tray programmatically,['c#'] +795589,laravel where to store global arrays data and constants i just started working with laravel i need to rewrite a whole system i made some years ago using laravel 4 as base framework in my old system i use to have a constantphp file with some constants declared and a globalsphp file which contained lots of array sets for example categories statuses type of events langs etc by doing so i could use something likeforeach langs as code domain some stuffanywhere in my appmy question is how can i store that info in the so called laravel way i tried using some sort of object to store this info setting this as a service and creating for it a facadeapplibrariesprojectconstantsphpnamespace pjclass constants public static langs es wdomaines en wdomainus uk wdomainuk br wdomainbr it wdomainit de wdomainde fr wdomainfr applibrariesprojectconstantsserviceproviderphpnamespace pjuse illuminatesupportserviceproviderclass constantsserviceprovider extends serviceprovider public function register thisappsingletonpjconstants function return new constants applibrariesprojectconstantsfacadephpnamespace pjuse illuminatesupportfacadesfacadeclass constantsfacade extends facade protected static function getfacadeaccessor return pjconstants composerjsonpsr4 pj applibrariesprojectand so i access that property as pjconstantslangsthis works but i doubt it is the most efficient correct way to do it i mean is it the right way to propagate a variable by creating a while service provider and facades and all such stuff or where should i put this datathanks for any adviceedit 01data i want to pass to all controllers and views can be directly set in script like in the example at the beginning of my post but it can also be generated dinamically from a database for example this data could be a list of categories i need them in all views to generate a navigation bar but i also need them to define some routing patterns like categorysubcategoryproduct and also to parse some info in several controllers like get info from the category that holds x product my array is something likecategories 1 name general parent 0 description lorem ipsum 2 name nature parent 0 description lorem ipsum 3 name world parent 0 description lorem ipsum 4 name animals parent 2 description lorem ipsumjust as an example index is the id of the category and the value is info associated with the categoryi need this array also available in all controllers and views so if i save it as a config variable is it ok or how else could i store these data what would be a best and semantically correct waythanks,['php'] +795602,volatile and const volatile stdtuple and stdget looking at the c11 standard i can see that specialization of stdtuple size and stdtuple element are provided for volatile and const volatile tupletemplate size t i class t class tuple elementi volatile ttemplate size t i class t class tuple elementi const volatile ttemplate class t class tuple sizevolatile ttemplate class t class tuple sizeconst volatile tbut stdget do no offer specialization for volatile or const volatile tuplei tried the following code on gcc481volatile stdtupleint int a1 1stdcout a0 stdget0a ni get error no matching function for call to getvolatile stdtupleint intso if i understand i can create const volatile tuples but i can not access their elementsis this an expected behavior or an oversight thanks very much,['c++'] +795608,what is dominance in the context of virtual functions code sampleconsider the following diamond hierarchystruct a virtual void f void g struct b virtual a virtual void f override void g struct c virtual a struct d b c int main d d df bf is called dg bg is calledwhat i do understandas far as the nonvirtual function g is concerned everything is clear the name bg hides ag even though the name ag could be reached without being hidden through c there is no ambiguity bg is called the standard explicitly confirms this in 102 p10 note when virtual base classes are used a hidden declaration can be reached along a path through the subobject lattice that does not pass through the hiding declaration this is not an ambiguity the identical use with nonvirtual base classes is an ambiguity in that case there is no unique instance of the name that hides all the others a end note exampleadditionally this answer to a related question provided an exhaustive explanation of the issuethe problemwhat i do not understand is how the quote mentioned above pertains to the virtual function f there is no name hiding involved with f is there only overriding is involved and 103 p2 reads a virtual member function cvf of a class object s is a final overrider unless the most derived class 18 of which s is a base class subobject if any declares or inherits another member function that overrides vf in a derived class if a virtual member function of a base class subobject has more than one final overrider the program is illformednow it seems to me that the virtual function f exactly fits the definition of not having a final overrider and the program should be illformed but it is not or is it msvc compiles it just fine with the following warningwarning c4250 d inherits bbf via dominanceto be honest i had never come across the term dominance before when i search it in the standard it has a single occurrence in the index and refers me to the chapter where my first quote comes from and as i already mentioned the quote seems to pertain only to name hiding rather than virtual function overriding questionsdoes f have more than one final overrider in d does the rule of dominance apply in this case how does it follow from the standard,['c++'] +795759,nodejs serverjs socket implementation problems having a hard time implementing a nodejsserverjs setupi am a bit stuck right now and hoping someone can shed some light i am relatively new to sockets in general but have been programming in javascript on and off for several years although only about as deep as is necessary to accomplish the task at hand as a result my understanding of some of the concepts surrounding the javascript stack heap and sockets in general are somewhat limited ok heres the situationi have created an application intended to simply increment a counter on several machines several users can click the next button and it will update instantly on all machineswhen you first connect it retrieves the current number and spits it out locally i have created the server herevar io requiresocketiovar sockets iolisten80var currentlyserving0socketsonconnection function socket consolelogclient connected socketemitreceive currentlyserving socketonupdate functionserving currentlyservingserving ifcurrentlyserving100 currentlyserving0 ifcurrentlyserving0 currentlyserving99 socketbroadcastemitreceive currentlyserving consolelogupdate received currentlyserving consolelogserver startedhere is the relevant i hope excerpt from the client sidevar socket ioconnectfunction to update the page when a new update is receivedsocketonreceive functionreceivedserving documentgetelementbyidmsgsvaluestring00 receivedservingslice2 documentgetelementbyidnowservingvaluereceivedservingthis is called in an onclick event in the html sourcesends the new number to all other stations except this one handled by server sidefunction nextserving var sendserving parseintdocumentgetelementbyidnowservingvalue1 socketemitupdate sendserving documentgetelementbyidnowservingvaluesendserving documentgetelementbyidmsgsvaluestring00 sendservingslice2ok so heres my problem this runs absolutely fine in every system i have put it in smoothly and beautifully except for ie8 if left alone for more than 23 minutes with no activity at all i eventually receive a stack overflow error the line number it appears on fluctuates have not determined the factors involved yet but it always happens at that interval on some workstations it takes longer which i am beginning to think has a direct correlation to the amount of phsyical ram the machine has or at least how much is being allocated to the web browser i found an online function to determine max stack size which i realize is not an exact science however i did consistently get a number in the area of 30 on my ie11 machine with considerable more resources i found it to be in the area of 20 this may not be relevant but i figured the more info the better to avoid this problem for now so that the end users do not see this error message i have take the entire client script and put it into an iframe which reloads itself every 60 secondsessentially resetting the stack which feels so dirty sitting so close to a web socket but has bought me the time to post here i have googled until i cannot google any more but when you search nodejs or socketio along with stack overflow on google you just get a lot of posts about the two topics that are hosted on the stackoverflow dot com website arg lolanyoneedit on november 18th 2014 as per comments belowthe error message is most often claiming stack overflow at line 1056 ie developer tools points towards the file socketiojs line 1056 isreturn fnapplyobj argsconcatslicecallargumentswhich is insdie this section of the filevar slice slice bind obj to fn param object obj param functionstring fn or string return function api public moduleexports functionobj fn if string typeof fn fn objfn if function typeof fn throw new errorbind requires a function var args slicecallarguments 2 return function return fnapplyobj argsconcatslicecallarguments,['javascript'] +795782,prynav work unexpectedly i put bindingpry in my scriptbut now when it is stopped at the breakpointis shows me that informationwhich is out of my expectation how to fix it frame number 011from usersmerbenvversions212librubygems210gemsprynav024libprynavtracerrb line 21 prynavtracerrun 12 def runblock 13 for performance thisable any tracers while in the console 14 unfortunately does not work in 192 because of 15 works fine in 187 and 193 16 stop unless ruby version 192 17 18 return value nil 19 command catchbreakout nav do coordinates with prynavcommands 20 return value yield 21 nothing thrown no navigational command 22 end,['ruby'] +795811,recover unsaved sql query scripts in oracle sql developer i know how to do this in sql server thanks to this clever bit of code use databaseselect execquerylast execution time as date time execsqltext as script from sysdm exec query stats as execquerycross apply sysdm exec sql textexecquerysql handle as execsqlorder by execquerylast execution time descsource recover unsaved sql query scripts sql serveris there a way to do this in oracle sql developer,['sql'] +795819,bests practice for browserify in large web projects gulp here is the thingi come from a world where you have several js files included to a web page some are always included in the page your libs menu etc and others are depending on the current page js for login page js for subscription etc basically let us say that i have 1 different js file per page plus the libsnow i want to start a new project with browserify and i am in front of a big problem in all the examples i have seen there is always a single entry point like appjsin my case i would have n entry points 1 per pageso my questions areis it against good practices to have 1 entry point per page why if yes what is the good practice for browserifying a large app with lot of pagespecific js if no how to automate that with gulp in every examples i found you have to know the name of every files and process it one after another which is very annoying in a large project with hundreds of pages for examplehow are you dealing with this in your projects do i have to completely rethink my way to deal with pagespecific js code,['javascript'] +795874,android support toolbar actionbardrawertoggle not changing to arrow i am struggling with the toolbar and drawer i am trying to make the burger switch to arrow when i am adding a new fragment to the backstack but there is no way to do itmaybe i am missing something but i could not find a way anyone had the same problemthis is the declarationmdrawertoggle new actionbardrawertoggle getactivitycompat host activity mdrawerlayout drawerlayout object baseactivity getactivitycompatgettoolbar rstringnavigation drawer open open drawer description for accessibility rstringnavigation drawer close close drawer description for accessibility this is the function i call when a fragment is added to the back stackpublic void settogglestateboolean isenabled if mdrawerlayout null return if isenabled mdrawerlayoutsetdrawerlockmodedrawerlayoutlock mode unlocked mdrawertoggleondrawerstatechangeddrawerlayoutlock mode unlocked else mdrawerlayoutsetdrawerlockmodedrawerlayoutlock mode locked closed mdrawertoggleondrawerstatechangeddrawerlayoutlock mode locked closed mdrawertogglesyncstate,['android'] +795880,how to change the background color of the uialertcontroller due to strange behavior of uiactionsheet in ios 8 i have implemented uialertcontroller with uiaction as buttons in it i would like to change the entire background of the uialertcontroller but i cannot find any ways to do ittried even withactioncontrollerviewbackgroundcolor uicolor blackcolorbut did not help me out any inputs on this regard will be appreciablethanks in advance,"['ios', 'objective-c']" +795928,why does c allow trailing comma in collection initializers but not in params valid syntaxvar test new liststring a b cvalid trailing commainvalid syntaxprivate void testparams string argstest a b cinvalid trailing commais it a matter of syntax inconsistency or a calculated decision,['c#'] +796088,opencv haar cascade face tracking is very slow i have developed a project to tracking face through camera using opencv libraryi used haar cascade with haarcascade frontalface altxml to detect face my problem is if image capture from webcame does not contain any faces process to detect faces is very slow so images from camera which are showed continuosly to user are delayed my source code void camera string face cascade name haarcascade frontalface altxml string eye cascade name haarcascade eye tree eyeglassesxml cascadeclassifier face cascade cascadeclassifier eyes cascade string window name capture face detection videocapture cap0 if face cascadeloadface cascade name printferror loadingn if eyes cascadeloadeye cascade name printferror loadingn if capisopened cerr capture device id 0 cannot be opened endl else mat frame vectorrect faces vectorrect eyes mat original mat frame gray mat face mat processedface for capreadframe original frameclone cvtcolororiginal frame gray cv bgr2gray equalizehistframe gray frame gray face cascadedetectmultiscaleframe gray faces 2 0 0 cascade scale image size200 200 if facessize 0 rectangleoriginal faces0 scalar0 0 255 2 8 0 namedwindowwindow name cv window autosize imshowwindow name original if waitkey30 27 break please help me,['c++'] +796141,put cllocationcoordinate2d into cllocation for swift i have a method i want to call however when i get back the center of the map it is in cllocationcoordinate2d typehow do i put the results of cllocationcoordinate2d into cllocation,['ios'] +796168,xcode 6 swift wkwebview keyboard settings i am using a wkwebview to load a website and everything is working fine however i do not have access to the keyboard properties the same way i do with a textfield can someone point me to some resources that will help me access properties through the gui or programmatically of the keyboard on the web,['ios'] +796276,ruby gem equivalent of pip install e in python i can install a package from source in editable mode using pip install e then i can carry on editing the code and any changes will be automatically picked by other python scripts that import libraryis there a comparable workflow for developing ruby gems what is the ruby way of using libs as they are being developed rather than for example compiling and installing a gem every time i make a change to the source,['ruby'] +796603,c constexpr member of template type i want to create a template class with a member which is a constexpr array the array needs of course a different initialization depending on the type it is but i cannot declare the array without initializing it the problem is that i do not know the values of array until template specializationahpptemplatetypename tclass a public static constexpr t a constexpr a a bhppclass b public aint public constexpr b bbcpptemplateconstexpr int ainta12345bb bb how can i properly initialize aa in b,['c++'] +796611,error when attempting to run ui automation script from jenkins i am using xcode 61 and i need to run a ui automation script from jenkins as a post build action the command that i use is shown belowinstruments t tracetemplate w device app path e uiascript script e uiaresultspath results path grep testreportstestresultsxmlwhen i run that the following error is thrown by jenkinsfailed to authorize rights 0x1 with status 607201412 163130685 instruments4882607 xrsimulatordevice prepareconnection unable to authorize simulated daemon 99637 8instruments trace error target failed to run permission to debug comtestapp was deniedany help is much appreciated,['ios'] +796697,intellij incorrectly saying no beans of type found for autowired repository i have created a simple unit test but intellij is incorrectly highlighting it red marking it as an errorno beansas you can see below it passes the test so it must be autowired,['java'] +796839,xcode 6 creates storyboard warnings i have a storyboard file with 22 scenes and i recently migrated to using size classes and the new showpresent modally segues for ios 8my problem is that every other time i open the storyboard in interface builder there are new warnings about misplaced frames that i have to fix after i fix them and save they keep coming backhave others experienced this issue is there a way to fix my storyboard so this stopsthanks,['ios'] +796887,swift uitableviewcell selected background color on multiple selection do not workscellselectionstyle blueworks when the selection is not multiple if it is multiple with each selection the previos one thisappearlet cellbgview uiviewcellbgviewbackgroundcolor uicolorred 0 green 0 blue 200 alpha 04cellselectedbackgroundview cellbgviewany answer how to set background color of the cells which are selected,['ios'] +796927,resource not found after spring 412 update when deploy with jrebel 600 spring 412 408 and 3212 contains a security bugfix spr12354 that prevents the resourcehttprequesthandler the thing behind mvcresources to load files from outside the the resource folder on the other hand is jrebel i use it with its default configuration and it seams that jrebel do some magic to load the resources not from the wtp folder but directly form the source folderso after upgrading from spring 3211 to 3212 and an other similar application from 407 to 408 springs resourcehttprequesthandler does not longer deliver the resource files that are maintained by jrebel instead is delivers a 404 the reason is that spring compare the absolute file path of the configured resource folder with the absolute file path of the file that is going to be delivered if the resourcehttprequesthandler perceived that the file is outside of configured resource folder then it assume that the url that was used to select the file is malicious therefore the resourcehttprequesthandler and response with a 404 resource not foundi expect that jrebel can been configured not to maintain js png and css files but i do not know how and this is the question how to configure jrebel that a spring mvc application v 408 still deliver resources with resourcehttprequesthandleri expect that almost every jrebel user is facing this problem after upgrading to spring 412 408 or 3212do not get me wrong this is not a question how to manipulate spring not to check that the files are outside of the configures resource folder i have had a look at the source code and the observed behaviour is the behaviour that is intended by the authors of the bug fix this question is about configuring jrebel,['java'] +797005,nullpointerexception in google play services when calling play on remoteplaybackclient this sample application of mine used to work just finesomewhere in the past few months though google updated google play services and chromecast itself and now when i call play on remoteplaybackclient for the chromecast google play services itself crashes witheandroidruntimei1 fatal exception mainjavalangnullpointerexception at comgoogleandroidgmscastmediaaqasourcefile96 at comgoogleandroidgmscastmedianisourcefile1856 at comgoogleandroidgmscastmediaurunsourcefile2092 at androidoshandlerhandlecallbackhandlerjava730 at androidoshandlerthispatchmessagehandlerjava92 at androidoslooperlooplooperjava137 at androidappactivitythreadmainactivitythreadjava5103 at javalangreflectmethodinvokenativenative method at javalangreflectmethodinvokemethodjava525 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava737 at comandroidinternaloszygoteinitmainzygoteinitjava553 at dalviksystemnativestartmainnative methodnote that the play call itself has the desired effect in that the chromecast plays the media but sometime after it calls the itemactioncallback with onresult the aforementioned crash in google play services occurs that in turn causes the connection to the chromecast to collapse so my mediarouteactionprovider vanishes and i have to rerun my app to connect again despite the chromecast actually playing the media that i requestedi have tested this with two devices nexus 4 and galaxy nexus with the same resultsi have even created a new app trying to just show an image instead of play a movie as with the original sample and i get the same crashhas anyone seen this and found some workaroundfixwhatever,['android'] +797008,python seaborn to reset back to the matplotlib i am using seaborn version o4 and matplotlib version 142i have a chart thisplays both line and marker through simple plot command egpltplot15384bodue to a potential bug after import seaborn same code shows line only without markerimport seaborn as sb pltplot15384boso my question is after import seaborn is there a way to reset all the parameters back to original,['python'] +797022,android 50 how to change recent apps title color i am using appcompat and my theme is extending themeappcompatlightdarkactionbarwhen in android 5 lollipop and i press the recent apps button my app appears with a dark title instead of a white title in the actionbarwhen i am inside the app everything looks fine what can i do to change the title color in the recent apps view edit just figured out that if i use a darker colorprimary the title becomes white i still need a way to force the white title with the original color,['android'] +797093,ipython notebook on linux vm running matplotlib interactive with nbagg i want buttons and other interactive matplotlib objects to appear from within my ipython notebook here is what i have doneinstalled it is a vagrant box with ipython installed and version 131 of matplotlibi needed to upgrade matplotlib to the latest version because it has this capability to do inline interactive plots whats new in matplotlib 141i needed to run sudo aptget install pkgconfig andsudo pip install matplotlib upgradein order to get that goingthen in order to produce the nice ie errorfree screenshot below i went into the ipythondstprofileipython notebook configpy file and erased the line about ipkernelapylabinline to be able to run the matplotlibusenbagg commandthen i was able to create the screenshot below however things still look poor those buttons are not buttons that is an image of buttons please advise on how to make those buttons come to lifeoh and check this out if this helps you help methanks,['python'] +797223,device owner on android 50 and others whitout rooted devices device provisioning by nfc i need to know how to set my application as device owner in android 50 44 and 43 i have yet tried the method for rooted devices described in there successfully i saw that works great in android 50 and 442 emulator and in cyanogen aosp 4 all rooted devices but i must need to try this on other non rooted devices in android 50 developer api you can read this to deploy and activate a device owner you must perform an nfc data transfer from a programming app to the device while the device is in its unprovisioned statebut i do not understand what it means or better what i have to do can someone help me or explain me the step to dops i know what nfc is and how it works but i cannot understand how to use for this issue,['android'] +797242,django rest framework authentication credentials were not provided i am developing an api using django rest framework i am trying to list or create an order object but when i am trying to access the console gives me this errordetail authentication credentials were not providedviewsfrom djangoshortcuts import renderfrom rest framework import viewsetsfrom djangocontribauthmodels import userfrom rest frameworkrenderers import jsonrenderer yamlrendererfrom rest frameworkresponse import responsefrom rest frameworkviews import apiviewfrom ordermodels import from apiserializers import from rest frameworkpermissions import isauthenticatedclass orderviewsetviewsetsmodelviewset model order serializer class orderserializer permission classes isauthenticatedserializerclass orderserializerserializershyperlinkedmodelserializer class meta model order fields field1 field2and my urls coding utf8 from djangoconfurls import patterns include urlfrom djangoconf import settingsfrom djangocontrib import adminfrom djangoutilsfunctional import curryfrom djangoviewsdefaults import from rest framework import routersfrom apiviews import adminautothiscoverhandler500 webviewsserver errorhandler404 webviewspage not found errorrouter routersdefaultrouterrouterregisterrorders ordersviewseturlpatterns patterns urlrapiauth includerest frameworkurls namespacerest framework urlrapitokenauth rest frameworkauthtokenviewsobtain auth token urlrapi includerouterurlsand then i am using this command in the consolecurl x get h authorization token 12383dcb52d627eabd39e7e88501e96a2sadc55and the error saydetail authentication credentials were not provided,['python'] +797256,constraints before and after rotating i have some problems with using constraints the main issue is i have some view controller configured as container for several conditions some menu every condition has constraints so all actions for changing states are changing active constraints all works fine for me when i do not rotate it if i start to rotating all constraints are reset to default i tried to fix this by adding my custom view with overriden method voidupdateconstraintsifneeded super updateconstraintsifneeded if selfcustomconstraints self removeconstraintsselfconstraints self addconstraintsselfcustomconstraints self layoutifneeded customconstraints is property with my last changed constraints i know that it is not good solution but it fixed my problem for one state for another state i have to add big part of logic and code to apply this method is there another way to fix my issue thank you,"['ios', 'objective-c']" +797270,vertical position of an aelement and buttonelement i want to style a button and a element both into the same format i use the following codebuttona border solid 1px black backgroundcolor white color black fontfamily arial padding 0 15px fontsize 13px height 35px lineheight 35px thisplay inlineblockdummyblock backgroundcolor black padding 0 margin 0 height 20pxdiv iddummyblockdivbuttonmy buttonbuttonamy linkabut the button element seems to ignore the height and my a element does not touch the edge of the black dummy div aboveyou can test the code in my fiddle,"['html', 'css']" +797277,optional dot in regex say i want to replace all the matches of mr and mr with misteri am using the following regex bmrb to match either mr or just mr then i use the resub method to do the replacementwhat is puzzling me is that it is replacing mr with mister why is this keeping the dot at the end it looks like it is not matching the mr case but just mrimport resa rmr nobody mr nobody is mr nobody and mra nobodyresubrbmrbmister sreturnsa rmr nobody mister nobody is mister nobody and mra nobodyi also tried with the following but also without luckresubrbmrmrbmister smy desired output isa rmr nobody mister nobody is mister nobody and mra nobody no dot this should be kept as it is,['python'] +797300,why does the ripple effect remove my original background so i am trying to create a ripple effect with a cusotm color and kind of succeeds except the ripple effect removes the original background and thus creates a semitransparent ripple effect which is not what i wantlayout button androidlayout width80dp androidlayout height80dp androidtextclicky androidcolorcontrolhighlightandroidcolorholo blue light androidbackgrounddrawableselector buttondrawableselectorxmlxml version10 encodingutf8selector xmlnsandroid item androidstate pressedtrue androiddrawabledrawableripple item androiddrawablecolornormalselectordrawableripplexmlxml version10 encodingutf8ripple xmlnsandroid androidcolor7f7ripplecolorxmlresources color namenormal070colorresourceswhat do i have to do to keep the green 070 background while the ripple effect is overlayed i believe that is the intention rightediti have now introduced a shape as suggested by academicduckdrawablered shapexmlxml version10 encodingutf8shape xmlnsandroid androidshaperectangle solid androidcolorcolornormal shapethis shape is referenced by the now modified rippledrawableripplexmlxml version10 encodingutf8ripple xmlnsandroid androiddrawalebdrawablered shaperipplewhat changes now is that when i press the background is a solid red color instead of transparent still no ripple though,['android'] +797473,make navigation drawer draw behind status bar i am trying to create a nav drawer like the one from the material spec like the one from the new gmail app note how the contents of the nav drawer draw behind the status barusing chris banes answer from this question i was able to successfully make the navigation drawer in my app draw behind the status bar that is working fine what is not working is drawing the contents of the nav drawer behind the status bar i want the blue image in my drawer to be thisplayed behind the status bar but that area is drawn with the color of status bar as seen in this screenshotso how can i make my navigation drawer draw in the area behind the status bar i have posted the relevant parts of my project belowbase layout containing the navigation drawerandroidsupportv4widgetdrawerlayout xmlnsandroid xmlnstools androidididnav drawer layout androidlayout widthmatch parent androidlayout heightmatch parent androidorientationvertical androidfitssystemwindowstrue framelayout to thisplay fragments framelayout androidididcontent androidlayout widthmatch parent androidlayout heightmatch parent androidlayout aboveidwarning container framelayout androidididnavigation drawer fragment container androidlayout width300dp androidlayout heightmatch parent androidfitssystemwindowstrue androidlayout gravitystart fragment androidididnavigation drawer fragment androidnamecomtheblueallianceandroidclientfragmentsnavigationdrawerfragment androidlayout widthmatch parent androidlayout heightmatch parent toolslayoutlayoutfragment navigation drawer framelayoutandroidsupportv4widgetdrawerlayouttheme of my activitystyle nameappthemenoactionbar parentapptheme item namewindowactionbarfalseitem item nameandroidwindownotitletrueitem item nameandroidwindowdrawssystembarbackgroundstrueitem item nameandroidstatusbarcolorandroidcolortransparentitemstylein oncreate of my activity i do the followingmdrawerlayoutsetstatusbarbackgroundrcolorprimary dark,['android'] +797506,transferring android app with subscription to another account i understand that google does not allow the transfer of app ownership with in appsubscription from one developer account to another i have been waiting for them to enable that feature but till now it is not available and there is no eta on iti have a paid app with inappsubscription as part of it a company is looking to acquire my app but the transfer is not possible so i am thinking about alternativesshould i create another identifcal app and ask users in my old app to move to this new identical app that will involve buying it again but i can provide incentive like enabling the subscription feature to be free other suggestions basically what would you do in my casethank you so much,['android'] +797798,device macro id for tapjoy google analytics i wanted to create custom url for tracking ios installs in google analytics dashboard i have been using tapjoy to drive the installs while creating the custom url from it asks for a device id macro for custom ad networksany idea what is the device id macro for tapjoy quick google search didnt get me any specific result,['ios'] +797878,calling nsstringfromclass on a swift class in objectivec returns module mangled name i am aware of this question regarding how we can get a readable class name of an objectivec class in swiftwhat i want to achieve is getting the readable class name of a swift class from inside objectivec without mangling the class name with the moduleso if i have a swift classclass foo nsobjectthen inside objectivec i would love to use the convenient nsstringfromclass to convert the class name to a stringi would expect nsstringfromclassfoo class to return foo but instead it returns barfoo withbarbeing the module namei came across this gist but it seems a little hacky and messy is there a better way something that does not include typing the class name manually into a string would be preferred,"['ios', 'objective-c']" +797960,process utf8 characters in c from a text file i need to read utf8 characters from a text file and process themfor instance to calculate the frequency of occurrence of a certain character ordinary characters are fine the problem occurs with characters like a14 or afollowing is my code to check if a certain character occurs comparing the ascii code of the incoming characterfile finfile foutwchar t cfinfopen inputtxtrfoutfopenouttxtwint frequency 0whilecfgetwcfinweof ifc some number frequency some number is what i cannot figure out for those characters infact those characters print out 5 different numbers when trying to print it as a decimalwhereas for example for character a i would do as ifc 97 frequency since the ascii code of a is 97is there anyway that i could identify those special characters in cps working with ordinary char not wchar t creates the same problem but this time printing the decimal equivalent of the incoming character would print 5 different negative numbers for those special characters problem stands,['c'] +798002,addthis 2 different configurations on the same page i would like to have 2 different configurations of addthis on the same pagetake note that i am using the new addthis where the code looks like thisscript typetextjavascript srcs7addthiscomjs300addthis widgetjspubidrax asyncasyncscriptdiv classaddthis addthisblogue clearfix div classaddthis sharing toolboxdivdivwhat i am trying to do is have 1 that have the share numbers tooltips and the other does not is it possible,['html'] +798037,how to change name of project in android studio imported an eclipse project into android studio and saved it in a new folder changed the package name and everything to new names but the projects name is still the one from the old projecthow do i change the pointed name into something else,['android'] +798089,google drive pdf viewer does not work anymore on android i have an app in android which was able to render a pdf in a web viewthe pdf is hosted online and and one of my requirements was not to download the pdf locallyuntil some days ago i was able to fulfill every requirement by using the urlurlpdf urlnow google has changed this url the new url is the followingurlpdf urlwith the new viewer android do not render the pdf anymore instead every time i try to load the pdf in the viewer both the emulator and the devices show the following image how can i solve this issuethank yourik,['android'] +798158,how to implement is enum class type trait how can one implement type trait whose value member is true if and only if the passed in type t is a class enum while i know that for instancetwill work if t is an enum and fail if it is an enum class i could not find a way so far to use this for sfinae,['c++'] +798181,copy constructor not called when initializing an object with return value of a function consider the following codeinclude iostreamusing namespace stdclass a public int a a a5 cout constructorn aconst a b a ba cout copy constructorn a funa a return a int main a a c a b afunc return 0the output of the above code with g filecpp isconstructorconstructorcopy constructorcopy constructorthe output of the above code with g fnoelideconstructors filecpp isconstructorconstructorcopy constructorcopy constructorcopy constructori know return value optimization my question is which call to copy constructor is elidedtemporary object during returning or returned object being copied to bif the elided copy constructor is the one used for creating b then how is b created at all because there is no constructor call in this case alsoif i replace the line a b afunc with afunc and compile using the first method or even the second method then also the copy constructor is being called 2 times so if in the case explained in the previous paragraph the temporary objects copy constructor is elided then why is not it elided in this case,['c++'] +798209,executorservice vs casual thread spawner i have a basic question about how executorservice works in javait is quite hard to see the difference between simply creating threads to perform some tasks in parallel and assigning each tasks to the threadpoolthe executorservice also looks very simple and efficient to use so i was wondering why we do not use it all the time is it just a matter of one way executing its job faster than the other heres two very simple examples to show the difference between the two ways using executor service hello world task static class hellotask implements runnable string msgpublic hellotaskstring msg thismsg msg public void run long id threadcurrentthreadgetid systemoutprintlnmsg from thread id using executor service hello world creating executor submittingstatic class hellotask public static void mainstring argsint ntasks 10executorservice exs executorsnewfixedthreadpool4for int i0 intasks i hellotask t new hellotaskhello from task i exssubmittexsshutdownthe following shows a similar example but extending the callable interface could you tell me the difference between the two and in which cases one should use a specific one instead of the other using executor service counter taskstatic class hellotaskret implements callablelong string msgpublic hellotaskretstring msg thismsg msg public long call long tid threadcurrentthreadgetid systemoutprintlnmsg from thread tid return tid using executor service creating submitting static class hellotaskret public static void mainstring argsint ntasks 10executorservice exs executorsnewfixedthreadpool4futurelong futures futurelong new futurentasksfor int i0 intasks i hellotaskret t new hellotaskrethello from task i futuresi exssubmittexsshutdown,['java'] +798215,picasso library out of memory i am using picasso library latest version 240 in my app for downloading and caching images there are roughly 2530 images of size 300kb400kb each i think that this is no way something big or heavy even though the app is running fine i am getting out of memory allocations in my logcat can anyone explain why is this happeningcode for loading images in gridview adapter picassowithmcontextloadgeturlplaceholderrdrawableplaceholder intoviewholderimagehere is my logcat output idalvikvmheap142 grow heap frag case to 53860mb for 2720016byte allocationidalvikvmheap142 forcing collection of softreferences for 3265936byte allocationedalvikvmheap142 out of memory on a 3265936byte allocationidalvikvm142 picassoimagesposters3471jpg prio5 tid18 runnableidalvikvm142 groupmain scount0 dscount0 obj0x4283f248 self0x60a47830idalvikvm142 systid196 nice10 sched00 cgrpappsbg non interactive idalvikvm142 stater schedstat 2070202497 1858185620 3947 utm172 stm35 core3idalvikvm142 at androidgraphicsbitmapnativecreatenative methodidalvikvm142 at androidgraphicsbitmapcreatebitmapbitmapjava726idalvikvm142 at androidgraphicsbitmapcreatebitmapbitmapjava703idalvikvm142 at androidgraphicsbitmapcreatebitmapbitmapjava636idalvikvm142 at comsquareuppicassobitmaphuntertransformresultbitmaphunteridalvikvm142 at comsquareuppicassobitmaphunterhuntbitmaphunterjava168idalvikvm142 at comsquareuppicassobitmaphunterrunbitmaphunterjava1idalvikvm142 at javautilconcurrentexecutorsrunnableadaptercallexecutorsjava390idalvikvm142 at javautilconcurrentfuturetaskrunfuturetaskjava234idalvikvm142 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutoridalvikvm142 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutoridalvikvm142 at javalangthreadrunthreadjava841idalvikvm142 at comsquareuppicassoutilspicassothreadrunutilsjava408idalvikvmheap142 forcing collection of softreferences for 3265936byte allocationedalvikvmheap142 out of memory on a 3265936byte allocationidalvikvm142 picassoimagesposters3471jpg prio5 tid17 runnableidalvikvm142 groupmain scount0 dscount0 obj0x42841b88 self0x5ec91f90idalvikvm142 systid183 nice10 sched00 cgrpappsbg non interactive idalvikvm142 stater schedstat 2050467088 1713164574 3713 utm172 stm32 core3idalvikvm142 at androidgraphicsbitmapnativecreatenative methodidalvikvm142 at androidgraphicsbitmapcreatebitmapbitmapjava726idalvikvm142 at androidgraphicsbitmapcreatebitmapbitmapjava703idalvikvm142 at androidgraphicsbitmapcreatebitmapbitmapjava636idalvikvm142 at comsquareuppicassobitmaphuntertransformresultbitmaphunteridalvikvm142 at comsquareuppicassobitmaphunterhuntbitmaphunterjava168idalvikvm142 at comsquareuppicassobitmaphunterrunbitmaphunterjava1idalvikvm142 at javautilconcurrentexecutorsrunnableadaptercallexecutorsjava390idalvikvm142 at javautilconcurrentfuturetaskrunfuturetaskjava234idalvikvm142 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutoridalvikvm142 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutoridalvikvm142 at javalangthreadrunthreadjava841idalvikvm142 at comsquareuppicassoutilspicassothreadrunutilsjava408,['android'] +798245,how do you override a moduledependency in a unit test with dagger 20 i have a simple android activity with a single dependency i inject the dependency into the activitys oncreate like thisdagger hellocomponentbuilder hellomodulenew hellomodulethis build initializethisin my activityunittestcase i want to override the dependency with a mockito mock i assume i need to use a testspecific module which provides the mock but i cannot figure out how to add this module to the object graphin dagger 1x this is apparently done with something like thisbeforepublic void setup objectgraphcreatenew testmoduleinjectthiswhats the dagger 20 equivalent of the aboveyou can see my project and its unit test here on github,['android'] +798307,vc no longer vectorize simple for loops with rangebased syntax before replacing a lot of my old for loops with range based for loops i ran some test with visual studio 2013stdvectorint numbersfor int i 0 i 50 i numberspush backiint sum 0vectorizationfor auto number numbersbegin number numbersend number sum numbervectorizationfor auto number numbersbegin number numbersend number auto ref number sum refdefinition of range based for loops from vectorizationfor auto begin numbersbegin end numbersend begin end begin auto ref begin sum refno vectorization for auto number numbers sum numberno vectorization for auto number numbers sum numberno vectorization for const auto number numbers sum numberno vectorization for auto number numbers sum numberprintffn sumlooking at the thisassembly standard for loops were all vectorized00bfe9b0 vpad xmm1xmm1xmmword ptr eax 00bfe9b4 add ecx4 00bfe9b7 add eax10h 00bfe9ba cmp ecxedx 00bfe9bc jne main140h 0bfe9b0h but range based for loops were not 00bfeac6 add esidword ptr eax 00bfeac8 lea eaxeax4 00bfeacb inc ecx 00bfeacc cmp ecxedi 00bfeace jne main256h 0bfeac6h is there any reason why the compiler could not vectorize these loops i really would like to use the new syntax but loosing vectorization is too badi just saw this question so i tried the qvecreport2 flag giving another reasonloop not vectorized due to reason 1200that isloop contains loopcarried data dependences that prevent vectorization different iterations of the loop interfere with each other such that vectorizing the loop would produce wrong answers and the autovectorizer cannot prove to itself that there are no such data dependencesis this the same bug i also tried with the last vc compiler nov 2013 ctpshould i report it on ms connect too editdu to comments i did the same test with a raw int array instead of a vector so no iterator class is involved just raw pointers now all loops are vectorized except the two simulated rangebased loopscompiler says this is due to reason 501induction variable is not local or upper bound is not loopinvarianti do not get whats going onconst size t size 50int numberssizefor size t i 0 i size i numbersi iint sum 0vectorizationfor auto number numbers0 number numbers0 size number sum numbervectorizationfor auto number numbers0 number numbers0 size number auto ref number sum refdefinition of range based for loops from no vectorization for auto begin numbers0 end numbers0 size begin end begin auto ref begin sum refno vectorization for auto begin numbers0 end numbers0 size begin end begin auto ref begin sum refvectorization for auto number numbers sum numbervectorization for auto number numbers sum numbervectorization for const auto number numbers sum numbervectorization for auto number numbers sum numberprintffn sum,['c++'] +798333,proguard optimization settings enabling class merging casts and field in modern api and proguard versions i have been obfuscating my apps for a long while with the following settings i took like mantras because they were googles recommendationsoptimizations codesimplificationarithmeticcodesimplificationcastfieldclassmerginghowever the other day i commented this line by mistake the app got built correctly and apparently works i have made a lot of tests and could not made it crashso i wonder if those thisabled optimization settings are needed as of todays android sdk and latest proguard versions i only target devices from android 403 onwards 15 and use proguard 51and for applications that do not do exotic stuff and have a properly written proguardcfg instructing to keep the relevant problematic classes etc most answers here releated to this very issue have conflicting information and are related to pretty old api versionsone by onecodesimplificationarithmetici found a thiscussion on google groups where they say that simplificationarithmethic is not needed for sdks after android donut i assume then i can safely enable this optimizationclassmergingit looks like proguard makes a good job in my projects with this optimization turned onproguard number of vertically merged classes 296proguard number of horizontally merged classes 445are there other side effects besides the stack traces being incorrect i mean side effects related to the application crashing rather than to debug issues i found this related question but it does not conclude wether it is safe or notfield and codesimplificationcasti read in this question answered by proguards author that those were included to avoid bugs with older proguard versions so is it safe to activate them on proguard 51,['android'] +798429,jackson serialization how to ignore superclass properties i want to serialize a pojo class which is not under my control but want to avoid serializing any of the properties which are coming from the superclass and not from the final class examplepublic class mygeneratedrecord extends orgjooqimplupdatablerecordimpl examplegeneratedtablesinterfacesimygenerated public void setfield1 public integer getfield1 public void setfield2 public integer getfield2you can guess from the example that that this class is generated by jooq and inherits from a complex base class updatablerecordimpl which also has some bean propertylike methods which cause problems during the serialization also i have several similar classes so it would be good to avoid duplicating the same solution for all of my generated pojosi have found the following possible solutions so farignore the specific fields coming from superclass using mixin technique like this how can i tell jackson to ignore a property for which i dont have control over the source codethe problem with this is that if the base class changes eg a new getanything method appears in it it can break my implementationimplement a custom serializer and handle the issue there this seems a bit overkill to meas incidentally i have an interface which describes exactly the properties i want to serialize maybe i can mixin a jsonserializeasimygeneratedclass annotation can i use this for my purposebut from pure design point of view the best would be to be able to tell jackson that i want to serialize only the final class properties and ignore all the inherited ones is there a way to do thatthanks in advance,['java'] +798547,sfinae enable if explicit constructor i am trying to switch between an explicit and an implicit conversion constructor via enable ifmy code currently looks likeinclude type traitsinclude cstdintenum class enabled template bool b typename t void using enable if t typename stdenable ifb ttypetemplate bool b typename t void using thisable if t typename stdenable ifb ttypetemplate stdintmax t a struct sstruct static constexpr stdintmax t a atemplate typename t struct scheckenable stdintegral constantbool ta 0template typename u typename t class cclass public template typename t2 enable if tscheckenableuvalue enabled constexpr cclasst2 v valv template typename t2 thisable if tscheckenableuvalue enabled explicit constexpr cclasst2 v valv private t valint main cclastruct0 double a 1 should use implicit constructor cclastruct1 double b cclastruct1 double1 should use explicit constructorthe true in the enable ifs is dependent of the template parameter uif i try to compile this minimal example with g 491 and stdc11 enabled i get the following errorssfinaecpp in substitution of atemplatebool b class t using thisable if t typename stdenable if b ttype with bool b true t enabledasfinaecpp1352 required from heresfinaecpp795 error no type named atypea in astruct stdenable iffalse enableda template bool b typename t void using thisable if t typename stdenable ifb ttype sfinaecpp1968 error prototype for aconstexpr cclassu tcclasst2a does not match any in class acclassu ta template typename u typename t template typename t2 constexpr cclassu tcclasst2 v valv sfinaecpp1377 error candidates are templateclass u class t templateclass t2 int anonymous constexpr cclassu tcclasst2 template typename t2 thisable if ttrue enabled explicit constexpr cclasst2 v sfinaecpp1267 error templateclass u class t templateclass t2 enabled anonymous constexpr cclassu tcclasst2 template typename t2 enable if ttrue enabled constexpr cclasst2 v any idea how to select between explicit and implicit construction based on parameter u here,['c++'] +798556,unable to copy symbols from this device i try to develop app for ios with mac os x mavericks but i have not bought a mac i virtualize it after download and install xcode 61 i connect my ipad 2 on ios 81 but when my computer copying symbol files i have error after a long timethe error is unable to copy symbols from this device this device has a version of ios different from that of this installation of xcode in order to copy the information needed to work with this device xcode must be run by a user with readwrite access to userslortedolibrarydeveloperxcodeios devicesupport81 12b410symbolsusrlibdyldi have been in the folder and i saw the folder dyld was not here so i create it manually too i have give the chmod 7 for all the folder mentionnedthanks lortedo,['ios'] +798804,how to implement the python zip function in golang sometimes it is convenient to combine two lists into a tuple using zip builtin function in python how to make this similarly in golang,['python'] +798847,how to alias the name of a column in eloquent i have an eloquent model named eloquentproductswhereactice truegettoarraynow i want to add joinstatement to it i have defined a scopequery withpublic function scopejoinwithtagsquery return queryleftjointags tagsid productstag id then our main query changes toproductswhereactice truejoinwithtagsgettoarraywhat i get is ok it is what i do expect but i want to change the name property of tags table to tag name how should i do that i mean i say somewhere in my query to tagsname as tag nameso that in the final result array i do resultitag namewhile now i have to resultiname,['php'] +798969,what is the common way of dealing with libraries dependencies when building with compilers different from target thistributions in case when let us say your project is built with one version of c compiler and its potential target system provides shared libraries built with another version how is this commonly approached in particular it is a question about libstdcwhen something is built within the same thistribution for example on linux and etc it is rather straightforward everything is built with the same compiler but what about projects like mozilla firefox which ship a binary supposedly compatible with many potential targets i know one way to do it is statically link c dependencies which reduces abi incompatibility issues and limits external linking just to a few c libraries but when i look at actual firefox binary from the stock mozilal build for linux x86 64 i see thisldd firefox linuxvdsoso1 0x07f561fc0 libpthreadso0 libx86 64linuxgnulibpthreadso0 0x07ff868c9f0 libdlso2 libx86 64linuxgnulibdlso2 0x07ff868a9b0 librtso1 libx86 64linuxgnulibrtso1 0x07ff8688920 libstdcso6 usrlibx86 64linuxgnulibstdcso6 0x07ff8685870 libmso6 libx86 64linuxgnulibmso6 0x07ff8682860 libgcc sso1 libx86 64linuxgnulibgcc sso1 0x07ff86806f0 libcso6 libx86 64linuxgnulibcso6 0x07ff867cc60 lib64ldlinuxx8664so2 0x07ff868ee80here firefox dynamically links with libstdc so how can it properly work across different versions of libstdc or it just assumes abi compatibility and that is it,['c++'] +799173,android camera preview is dark i am trying to create a custom camera app i followed the android developer example from here with minor tweaks however my camera preview turns out to be rather dark on the other hand the stock camera gives a much brighter previewi have tried several settings to make it work better but it seems none of them are having any impact relevant code is posted herecameraactivity mainprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity camera ifcamerahelpercheckcamerahardwarethis mhelper new camerahelperthis getwindowmanagergetdefaultthisplay framelayout preview framelayout findviewbyidridcamera preview mpreview new camerapreviewthis camerahelpercamera mpreviewsetlayoutparamsnew layoutparamscamerahelpermsizewidth camerahelpermsizeheight gravitycenter previewaddviewmpreviewcamerahelper class initialize the camera and set the default parameters public camerahelpercameralistener listener thisplay thisplay mlistener listener camera getcamerainstance mparameters cameragetparameters initcameraparameters msize getpreviewsizethisplay mparameterssetfocusmodeparametersfocus mode auto mparameterssetpicturesize2560 1920 mparameterssetautoexposurelockfalse mparameterssetautowhitebalancelockfalse mparameterssetiso iso800 tried with 400 800 600 values obtained from flatten mparameterssetcoloreffectnone mparameterssetpicturesize2560 1920 mparameterssetpreviewframerate20 mparameterssetscenemode auto mparameterssetfocusmodeauto mparameterssetexposurecompensation4 camerasetparametersmparameters the camera sends the frames to surfaceholdersurface from the example linked from developer pages abovesee the difference herestock camera appmy camera apptried setting the iso etc based on upack parameters from the camera as posted here it still did not workparameters16369 effectvaluesnonemononegativesepiaaquasharpenpurplegreentintbluetintpinkyellowredtintmonoantiqueexposurecompensationstep05focallength343focusareas0focusthistances010120infinityfocusmodevaluesautomacrofacedetectgpsaltitude0gpslatitude0gpslongitude0gpsprocessingmethodgpsgpstimestamp0horizontalviewangle512isoautoisovaluesautoiso50iso100iso200iso400iso800iso1600jpegquality1jpegthumbnailheight480jpegthumbnailsizevalues640x4800x0jpegthumbnailwidth640maxexposurecompensation4maxnumfocusareas1maxzoom12minexposurecompensation4pictureformatjpegpictureformatvaluesjpegpicturesizevalues2560x19202560x15362048x15362048x12321600x12001600x960800x480640x480previewformatyuv420sppreviewformatvaluesyuv420sppreviewfpsrange15030previewfpsrangevalues15030previewframerate30previewframeratevalues30previewsize640x480previewsizevalues1280x720800x480720x480640x480352x288rotation0scenemodeautoscenemodevaluesautoportraitlandscapenightbeachsnowsunsetfireworkssportspartycandlelightasdbacklightduskdawntextfallcolorverticalviewangle394videoframeformatyuv422iyuyvwhitebalancevaluesautoincandescentfluorescentdaylightcloudydaylightzoom0zoomratios100125150175200225250275300325350375400zoomsupportedtruefocusmodeautopicturesize2560x1920exposurecompensation4edit upon further testing based on comments below it appears that its just the preview that is turning out darker than it should be the actual captured image is well lit and exposure compensatiion seems to be working fine its just the preview that is giving me a headache tested on i9003 running cm11 and nexus 10 running stock android,['android'] +799183,css set backgroundimage by dataimage attr i have sort of elements with this patterndiv dataimageimageurl divi want to set this elements backgroundimage to dataimage i test this css codedivdataimage border 2px solid black backgroundimage attrdataimage urlborder show correctly but nothing happened for backgroundhow can do i fix this code only with css not js or jq,"['html', 'css']" +799185,forward vertical scrolls from uiscrollview to a sibling uitableview i have a view controller with this hierarchyview controlleruiscrollview scrollable horizontallyuitableview scrollable verticallyi want to forward the vertical scrolls from my uiscrollview to the sibling uitableview so that when the user scrolls up on the uiscrollview the uitableview will scroll up instead what would be the best way to do iti have tried thesedetecting the vertical scroll in scrollviewdidscroll it does not get called because the contentoffset of the scroll view does not changesubclassing the uiscrollview and overriding touchesmoved i cannot forward the touches to the table view because i do not have a reference to it in this class,['ios'] +799254,gradle android plugin variant dependencies dsl method not found i have a multiflavor project with flavors called qa and prod i need to include different versions of a library depending on both the build type and the flavorthe documentation at suggests that build types and flavors can be combined using a flavorbuildcompile notation however when i do this i get this errorerror88 0 gradle dsl method not found qadebugcompilei am pretty sure this used to work in an older version of gradle currently using gradle 21 i have not found an explanation if the way to do this has changed note it works fine if i use flavorcompile notation it only fails when i include the build type as wellhere is the outline of my build scriptandroid compilesdkversion 17 buildtoolsversion 20 productflavors qa applicationid commyappqa prod applicationid commyaprod sourcesets main javasrcdirs src resourcessrcdirs src aidlsrcdirs src renderscriptsrcdirs src ressrcdirs res assetssrcdirs assets manifestsrcfile androidmanifestxml qa ressrcdirs res qa prod ressrcdirs res prod dependencies compile filetreedir libs include jar qacompile commyappintegrationother lib30aar this is fine qadebugcompile commyappintegrationmylib qa30aar this fails proddebugcompile commyappintegrationmylib prod30aar qareleasecompile commyappreleasemylib qa30aar prodreleasecompile commyappreleasemylib prod30aar,['android'] +799277,how to build an angularjs app with yesod i managed to successfully write a small app using yesod now i am in the phase in which i want to add better interaction to it and i would like to do this using angularjsas far as i can see the support for angularjs in yesod is still experimental moreover the documentation i found so far is quite unaccessible for me i do not master all of the yesod conceptsso i was wondering what are possible ways to integrate angularjs and the yesod framework what i am thinking about doing iswriting the frontend in angularjsdevelop the webservice using yesodconnect the frontend and the webservice by means of get and post http requests information can be sent to the server by means of input forms leveraging some of yesod capabilities in this way and information can be sent to the frontend by means of json objectsideally i would like to write everything in haskell but in the current state of affairs that may not be a possibility thus i wanted to ask if the alternative i have in mind is a good one and whether there are ways to improving itthank you,['javascript'] +799291,how do i run an terminal command in a swift script eg xcodebuild i want to replace my ci bash scripts with swift i cant figure out how to invoke normal terminal command such as ls or xcodebuildusrbinenv xcrun swiftimport foundation worksprintlntest worksls failsxcodebuild workspace myappxcworkspace fails scriptswiftscriptswift51 error use of unresolved identifier lsls fails etc,['ios'] +799363,setting a max character length in css i am making responsive website for school and my question ishow do i set a max character length of the sentenceswith css on my websitelike 75 characters that when i have a very large screenthe sentences wont go further than 75 charactersi have tried a max width but that messes up my layout i am using flexbox and mediaqueries to make it responsive,"['html', 'css']" +799372,large notification icon background since android 50 large icons in notifications have color backgroundfor small icon it is the accent color of notification notificationbuildersetcolorint how do i set it for large icon is it part of the actual image if it is what should the circle radius be,['android'] +799498,uitableviewcell systemlayoutsizefittingsize returning 0 on ios 7 i have a uitableviewcell with a uiimage fixed at the left top corner and a label at its right uitableviewcell adcellfromtableviewuitableviewtableview build the text nsstring adtext nslocalizedstringmyfamily fremiumad nil nsmutableattributedstring attrstring nsmutableattributedstring alloc initwithstringadtext nsuinteger newlinelocation adtext rangeofcharacterfromsetnscharacterset newlinecharactersetlocation set the first line in orange nsdictionary firstlineattributes nsfontattributenameuifont systemfontofsize15 nsforegroundcolorattributenameorange attrstring addattributesfirstlineattributes rangensmakerange0 newlinelocation set other lines in white nsdictionary otherlinesattributes nsfontattributenameuifont systemfontofsize11 nsforegroundcolorattributenameuicolor whitecolor attrstring addattributesotherlinesattributes rangensmakerangenewlinelocation adtextlength newlinelocation get the cell if adcell adcell tableusers dequeuereusablecellwithidentifierfremiumad set the text uilabel label uilabeladcell viewwithtag1 labelattributedtext attrstring hide the separator adcellseparatorinset uiedgeinsetsmake0 adcellboundssizewidth 0 0 return adcellcgfloat tableviewuitableview tableview heightforrowatindexpathnsindexpath indexpathuitableviewcell cell self adcellfromtableviewtableview make sure the cells bounds are the same as tableviews before calculating the height this is important when we calculate height after a ui rotation cellbounds cgrectmake0 0 tableviewboundssizewidth 0 nslogcellbounds nsstringfromcgrectcellbounds cell setneedslayout cell layoutifneeded cgsize fittingsize cell systemlayoutsizefittingsizeuilayoutfittingcompressedsize nslogfittingsize nsstringfromcgsizefittingsize return fittingsizeheightwhen i run the app on ios 71 simulator systemlayoutsizefittingsize always return 0cellbounds 0 0 320 0 fittingsize 00when i run the app on ios 81 simulator systemlayoutsizefittingsize return a correct valuecellbounds 0 0 320 0fittingsize 320 1545what am i missingediti kinda fixed the problem using cellcontentview systemlayoutsizefittingsizeuilayoutfittingcompressedsize instead of cell systemlayoutsizefittingsizeuilayoutfittingcompressedsizebut this is just an half fix when i rotate while the cell is visible the size calculation is ok but when i scroll the cell out of the screen rotate the ui and then scroll back to the cell the height calculation is wrong again in ios 71here are logs before rotating from landscape to portrait tableview bounds 0 0 569 227 cellbounds 0 0 5690 cellcontentview 0 0 569 0 fittingsize 559 162here are logs after rotating from landscape to portrait tableview bounds 0 249 321 463 cellbounds 0 0 3210 cellcontentview 0 0 321 0 fittingsize 559 162as you can see the size calculation is the same no matter what the cellcellcontentview width isthis result in a oversized cell when rotating from portrait to landscape and an undersized cell when rotating from landscape to portrait,['ios'] +799631,create a with method on immutables i would like to mimic the f with keyword which can be used on records in c for now when i create a new immutable class i just add manually some custom with methods like this public class myclass public readonly string name public readonly string description public myclastring name string description thisname name thisdescription description custom with methods public myclass withnamestring name return new myclassname thisdescription public myclass withdescriptionstring description return new myclassthisname description for my personal c development i tried to create a generic method to do this in a perfect world i would use f the best i did is something like public static class myextensions public static tsource withtsource tfield this tsource obj string fieldname tfield value where tsource class reflection stuff to use constructor with the new value check parameters names and types it works but i am not quite satisfied because i lose compile time errors by using a string parameter for now i do not care of performance issues i would really like to be able to write something like the code below where i replace the string parameter by a projection lambda var myclass1 new myclassname descvar myclass2 myclass1withobj objname newnamemy extension method would look something like public static tsource withtsource tfield this tsource obj expressionfunctsource tfield projection tfield value where tsource class todo so here are my questions is it possible to use reflection on the projections result and get the field name from it has someone else already done a robust with method in c,['c#'] +799727,python matplotlib line plot aligned with contourimshow how can i set the visual width of one subplot equal to the width of another subplot using python and matplotlib the first plot has a fixed aspect ratio and square pixels from imshow i would then like to put a lineplot below that but am not able to do so and have everything alignedi am fairly sure the solution involves the information on this transform tutorial page i have tried working with figtransfigure axtransaxes axtransdata etc but have not been successful i need to find the width and height and offsets of the axes in the upper panel and then be able to set the width height and offsets of the axes in the lower panel axis labels and ticks and etc should not be included or change the alignmentfor example the following codefig pltfigure1figclfdata nprandomrandom33xaxis nparange03yaxis nparange03ax figadd subplot211aximshowdata interpolationnonec axcontourxaxis yaxis data colorskax2 figadd subplot212,['python'] +799729,navigation drawer below toolbar i am trying to get the navigation drawer to open below the toolbarandroidsupportv4widgetdrawerlayoutxmlnsandroidxmlnstoolsandroidlayout widthmatch parentandroidlayout heightmatch parentandroidididdrawer layouttoolscontextmainactivityrelativelayout androidlayout width match parent androidlayout height wrap content include layoutlayouttoolbar androidididtoolbar framelayout androidlayout belowidtoolbar androidlayout widthmatch parent androidlayout heightmatch parent androidbackgroundcolorbackground colorrelativelayoutlistview androidididdrawer androidlayout width260dp androidlayout heightmatch parent androidlayout belowidtoolbar androidlayout margintop56dp androidlayout gravitystartlistviewandroidsupportv4widgetdrawerlayouthow do i reformat the xml so that the navigation bar opens below the toolbar,['android'] +799745,argparse do not catch positional arguments with nargs i am trying to write a function wo which you can parse a variable amount of arguments via argparse i know i can do this via nargs sadly the way argparse help works and the way people generally write arguments in the cli puts the positional arguments last this leads to my positional argument being caught as part of the optional argumentsusrbinpythonimport argparseparser argparseargumentparserparseradd argumentpositional helpmy positional arg typeintparseradd argumento optional helpmy optional arg nargs typefloatargs parserparse argsprint argspositional argsoptionalrunning this as testpy h shows the following usage instructionusage testpy h o optional optional positionalbut if i run testpy o 021 011 033 013 100 gives me testpy error too few argumentsto get a correct parsing of args i have to run testpy 100 o 021 011 033 013so how do imake argparse reformat the usage output so that it is less misleading or even bettertell argparse to not catch the last element for the optional argument o if it is the last in the list,['python'] +799749,what is the difference between onload ondomready no wrap in and no wrap in i use jsfiddle for editing my code however in certain codes when i am running javascript or jquery it does not work unless i select no wrap head or no wrap bodyjsfiddle herein the fiddle above you will notice that clicking the button element will not alert you unless youve selected either the extension no wrap head or no wrap bodyi am a curious person who likes to understand how things work what exactly does that option change and why would you change it,['javascript'] +799778,why is a destructor called if it is deleted and not called if it is not deleted consider the following codeinclude iostreamstruct a a a stdcout aa stdendl struct b a b b new b does not produce any sideeffectint main demothe program does not produce any output which means the destructor is not being called but if we replace the destructors body with the delete specifier the program would not even compile include iostreamstruct a a a delete stdcout aa stdendl struct b a b b new b error use of deleted functionint main demodue to call to the deleted function that is the destructor that is being called in that case why is there such a differenceit would not work even if we define bs constructor explicitlyinclude iostreamstruct a a a delete stdcout aa stdendl struct b a b b b new bint main demo,['c++'] +799784,3d navbar that rotates i am trying to create a 3d navbar using pure css with transforms transitions and perspectivehere is my codenavbarfixedbottom background transparentnavbarperspective width 100 height 100 position relative webkitperspective 1100px mozperspective 1100px perspective 1100px webkitperspectiveorigin 50 0 mozperspectiveorigin 50 0 perspectiveorigin 50 0navbarperspective div margin 0 auto position relative textalign justify webkitbackfacevisibility hidden mozbackfacevisibility hidden backfacevisibility hidden webkittransition all 05s moztransition all 05s transition all 05s height 50px fontsize20pxnavbarprimary backgroundcolor c zindex 2 webkittransformorigin 0 100 moztransformorigin 0 100 transformorigin 0 100navbar navbarsecondarynavbar navbartertiary backgroundcolor bfbfbf width 100 webkittransformorigin 0 0 moztransformorigin 0 0 transformorigin 0 0 zindex 1 webkittransform rotatex90deg moztransform rotatex90deg transform rotatex90deg webkittransition top 05s moztransition top 05s transition top 05s position absolute top 0navbar navbartertiary backgroundcolor b3b3b3navbarrotateprimary height 50pxnavbarrotateprimary navbarprimary webkittransform translatey0 rotatex0deg moztransform translatey0 rotatex0deg transform translatey0 rotatex0degnavbarrotateprimary navbarsecondarynavbarrotateprimary navbartertiary top 100 webkittransition webkittransform 05s moztransition moztransform 05s transition transform 05s webkittransform rotatex90deg moztransform rotatex90deg transform rotatex90degnavbarrotatesecondarynavbarrotatetertiary height 50pxnavbarrotatesecondary navbarprimarynavbarrotatetertiary navbarprimary webkittransform translatey100 rotatex90deg moztransform translatey100 rotatex90deg transform translatey100 rotatex90degnavbarrotatesecondary navbarsecondarynavbarrotatetertiary navbarsecondary top 100 webkittransition webkittransform 05s moztransition moztransform 05s transition transform 05s webkittransform rotatex0deg translatey100 moztransform rotatex0deg translatey100 transform rotatex0deg translatey100navbarrotatesecondaryfallback navbarprimarynavbarrotatetertiaryfallback navbarprimary thisplay nonenavbarrotatetertiary navbarsecondary webkittransform translatey100 rotatex90deg moztransform translatey100 rotatex90deg transform translatey100 rotatex90degnavbarrotatetertiary navbartertiary top 100 webkittransition webkittransform 05s moztransition moztransform 05s transition transform 05s webkittransform rotatex0deg translatey100 moztransform rotatex0deg translatey100 transform rotatex0deg translatey100htmlheadscript srcscriptheadbodynav idnavigationbottom classnavbar navbarfixedbottomdiv classnavbarperspectivediv classnavbarprimarya hrefjavascriptvoid0 onclicknavigationbottomattrclassnavbar navbarfixedbottom navbarrotatesecondaryrotate to face 2adivdiv classnavbarsecondarya hrefjavascriptvoid0 onclicknavigationbottomattrclassnavbar navbarfixedbottom navbarrotatetertiaryrotate to face 3adivdiv classnavbartertiarya hrefjavascriptvoid0 onclicknavigationbottomattrclassnavbar navbarfixedbottom navbarrotateprimaryrotate back to face 1adivdivnavbodyhtmli have got the first two faces to rotate properly using a 3d effect but the third face does not look right you will notice as you rotate from second to third that the top does not rotate correctly and looks flatany help is greatly appreciated,['css'] +799872,custom seekbar thumb not transparent on lollipop api21 this is my seekbar seekbar androidididseek1 androidlayout widthfill parent androidlayout heightwrap content androidlayout margin10dp androidprogressdrawabledrawablestyle progressbar androidthumbdrawablestyle progressbar circle androidprogress20 this is style progressbarxmlitem androididandroididbackground shape androidshaperectangle corners androidradius5dp gradient androidangle270 androidendcolorcolorgris hint androidstartcolorcolorgris hint shape item item androididandroididsecondaryprogress clip shape androidshaperectangle corners androidradius5dp gradient androidangle270 androidendcolorcolorgris androidstartcolorcolorgris shape clip item item androididandroididprogress clip shape androidshaperectangle corners androidradius5dp gradient androidangle270 androidendcolorcolorgris androidstartcolorcolorgris shape clip itemlayerlistand this is style progressbar circlexmlselector xmlnsandroiditem androiddrawabledrawablered scrubber control thisabled holo androidstate enabledfalseitem androiddrawabledrawablered scrubber control pressed holo androidstate pressedtrueitem androiddrawabledrawablered scrubber control focused holo androidstate selectedtrueitem androiddrawabledrawablered scrubber control normal holo selector this is how i see it in lollipopthis is how it should look this is how it looks on kitkat and lower versionsany idea i have got some issues with layouts on lollipop but this is the only one i cannot solve for my own,['android'] +799941,android parent fragment of a nested fragment a getparentfragment from my nested fragment is returning a null i realise that getting a null means that the fragment is attached to the activity and not to the nested container fragment but i am explicitly nesting the child fragment inside the parent fragment using the child fragmentmanager and thus think that i should not be getting a null could you tell me what i am missing parent fragmentpublic class usagebreakup extends fragment implements filteronfragmentinteractionlistener override public void onviewcreatedview view nullable bundle savedinstancestate superonviewcreatedview savedinstancestate getchildfragmentmanagerbegintransactionaddridfilter new filtercommit child fragmentpublic class filter extends fragment public filter if getparentfragment null logdlog tag parent fragment is null,['android'] +799952,mongoengine storing embeddeddocument in dictfield i am modelling a mongobd database in mongoengine for a web project i want to store the data in a slightly unusual way to be able to efficiently query it laterour data in mongodb looks something like this outer outer data directors embed some md5 key name pt anderson another md5 key name t malick my first instinct was to model it like this in mongoengineclass innerembeddeddocument name stringfieldclass outerdocument outer data stringfield embed dictfieldembeddeddocumentinner this is not allowed but you get the pointin other words what i essentially want is the same an storing an embeddeddocument in a listfield but rather in a dictfield with dynamic keys for each embeddeddocument example that is allowed with a listfield for referenceclass innerembeddeddocument inner id stringfielduniquetrue this replaces the dict keys name stringfieldclass outerdocument outer data stringfield embed listfieldembeddeddocumentinneri would prefer to have mongoengine objects returned also for the nested inner documents while still using a dictfield embeddeddocument as dict value how can i model this in mongoengine is it even possible or do i have to naively place all data under a generic dictfield,['python'] +799954,php code not indenting in adobe brackets i am using adobe brackets 10 code editori have php pages that include html php lineshtml lines indenting fine but php lines do not indent correctlyis there any extension or way to force php lines to indent correctlyi have used and tried the following extensions but non of them did the jobphpsig php smarthintsphp syntax hintquickdocsphpquickdocsregextab tagswordhintthanksps i cannot believe such good editor lack this important feature functionality outoftheboxupdate after nicola2s answerbefore using indentator extension manual indentationafter installing indentator extension and applying ctrl alt i,"['php', 'html']" +800124,elastic beanstalk unable to install packages i am trying to deploy my application on aws elastic beanstalk i am getting this error and totally unable to see where the problem isthe below is the code present in ebextensionsmysiteenvconfigpackages yum pythondevel postgresqldevel container commands 01 syncdb command djangoadminpy syncdb noinput leader only true 02 createadmin command scriptscreateadminpy leader only trueoption settings option name wsgipath namespace awselasticbeanstalkcontainerpython value mysitewsgipy option name django settings module value mysitesettingsafter several hitandtry methods i figured out few thingsthe above config file seems to run after requirementstxt present in rootunable to install those packages mentioned above but i could get installed by getting into ssh of the ec2 instance weirdthe issue with 1 is that for psycopg2 to install i need the above mentioned packages so how do i install them firstwhen i run these settings i am getting the below error201419t094519819z info 6703 cmdappdeployappdeploystage0ebextensionprebuild activity execution failed because command failed with error code 1 error occurred during build yum does not have postgresqldevel available for installation executornonzeroexitstatusthen i used the below settingspackages yum pythondevel apt postgresqldevel then i am getting the below error201419t094754271z error 6789 command execution failed cmdappdeployappdeploystage0ebextensionprebuild command failed with error code 1 error occurred during build errno 2 no such file or directory elasticbeanstalkactivityfatalerror at optelasticbeanstalklibrubylibrubygems210gemsbeanstalkcore10libelasticbeanstalkactivityrb189in rescue in exec caused by command failed with error code 1 error occurred during build errno 2 no such file or directory executornonzeroexitstatuswhen i could install those packages directly from ssh whats the problem with automation whats wrong with my settings,['python'] +800150,meteor mongo how do you reference a lookup collection denormalize vs normalize i am a meteor and mongo noob now a huge meteor fan and am struggling with how to implement lookup collections within meteorscenarioi have a product with custom colors user definedunknown amounta user can add in their own custom colors then go to theproduct page and choose from a colors select box what color they wantto use for that productif the user goes back and modifies the color hex value and saves on the colors page the product on the product page reflects that new colorhex valuewhat i am trying to doallow the user to go back and modify a preexisting color on the colors pagehave that color hex value change be reflected on the product pagetrying to not duplicate data on different collections and worrying about updating data across multiple collectionsdata inconsistencies if update fails part way throughinitially i set up my product schema to hold the color data as well denormalized data though when the color is updated it is not being updated on the typography document i have seen that you can use observe of observechange to essentially listen to changes then make additional changes though this seems more complicated than it needs to be is there a way that i can reference the colors collection for all colors added to a specific product so that any change is reflected on the product pagebelow is some of the code that i have been working on i am using collection2 and ironrouter if that helps any i have tried concatenating both collections though this not what i am after since the each loop also loops through the colors not desiredany help is appreciated thank you in advance chrisproductpage helpertemplateproductpagetplhelpers ownproduct function return thisuserid meteoruserid productitems function return productcollectionfindproductid this id colorsitems function return colorscollectionfindproductid this id this is my attempt and although give me back both collections i only need to reference the colors productandcolorsitems function var product productcollectionfindproductid this idfetch var colors colorscollectionfindproductid this idfetch var productcolorsjoin productconcatcolors consolelogproductcolorsjoin return sortbyproductcolorsjoin functiondoc return doccreatedat product page htmltemplate nameproductpagetpl div classproduct each productandcolorsitems productitemtpl each divtemplate all the properties below reference the productcollection except for the colorhex colorhex is a property on the colorscollectiontemplate nameproductitemtpl div idproductsentencejs stylecolor colorhex fontfamily fontfamily fontweight fontweight fontsize fontsizefontunit fontstyle fontstyle texttransform fonttexttransform lineheight fontlineheightfontlineheightunit padding fontpaddingtopfontpaddingtopunit fontpaddingright fontpaddingtopunit fontpaddingbottomfontpaddingtopunit fontpaddingleftfontpaddingtopunit margin fontmargintopfontmargintopunit fontmarginrightfontmargintopunit fontmarginbottomfontmargintopunit fontmarginleftfontmargintopunit productsentence divtemplatecolors collection schemacolorscollection new mongocollectioncolorsvar schema schemacolorscollectionschema new simpleschema productid type string label product id max 500 userid type string label user id max 500 author type string label author max 500 submitted type date label submitted max 500 colorname type string label color name max 500 colorhexvalue type string label color hex value max 500 colorhexvalueid type string label color hex value id max 500 colorscollectionattachschemaschemacolorscollectionschemaso in short anytime the user changes a color on the colors page the color document is updated with a new hex value within the colorscollection and all products that are using that color now reflect that new color hex value,"['javascript', 'jquery']" +800211,generate components in subfolders in emberembercli based on recommendations for the preparation for ember 20a in general replace views controllers with components a only use controllers at the route levelwere supposed to eschew controllers and views in favor of components i have not been able to figure out andor understand how to generate components that are not direct parents of the components folder ie componentscomponentnamejsmy current controllers folder looks something likecontrollers account indexjs editjs business indexjsbasically there are subfolders that group logic based on the sections of the application how do i accomplish this with just componentsseeing that components must have a in them i tried but get an errorember generate component accountindexmodulejsyou specified accountindexmodulejs but due to a bug in handlebars 20 slashes within componentshelpers are not alloweddo all components have to be like components accountindexjs accountnewjs businessindexjsie all in the same folder this will start to get out of hand with the addition of what i actually consider to be components things like videoviewerjs texteditorjs radiobuttonjsi would really like to have components in subfolders but unsure how to do thiscomponents media audio audioplayerjs video videoplayerjs textediting texteditorjs editortoolbarjsmy components folder is already gross and i just got startedis it okay to leave the accountbusiness logic in controllers seeing that it does say you should only use controllers at the route leveli am really confused about this all components all the time convention,['javascript'] +800221,javascript object bracket notation on left side to assign i have not seen this syntax before and am wondering what it is all about the brackets on the left are throwing a syntax error unexpected token var navigation requirereactrouteri am not sure what part of the webpack config is transforming or what the purpose of the syntax is is it a harmony thing can someone enlighten me,['javascript'] +800319,is there any way to access the accelerometer from the apple watch it does not look like watchkit released today has such api included,['ios'] +800355,how to install java locally no root on linux if possible i need java 17 and server has only got 16 i have no root privileges i tried to google out something but it seems like nobody was doing it can i somehow compile it or get ready binaries so i could put those into my path could you help system is redhat,['java'] +800439,android imeoptionsactiondone not working i am trying to get a login screen for an android app and so far this is my coderelativelayout xmlnsandroid androidlayout widthfill parent androidlayout heightfill parent linearlayout androidididlinearlayout1 androidlayout widthwrap content androidlayout heightwrap content androidlayout centerinparenttrue androidorientationvertical edittext androidididusername androidlayout widthmatch parent androidlayout heightwrap content androidhintusername androidinputtypetext androidsinglelinetrue androidimeoptionsactionnext requestfocus edittext edittext androidididpassword androidlayout widthmatch parent androidlayout heightwrap content androidhintpassword androidinputtypetextpassword androidsinglelinetrue androidimeoptionsactiondone button androidididbuttonlaunchtriage androidlayout widthmatch parent androidlayout height0dp androidlayout weight1 androidtextstringlogin linearlayoutrelativelayoutwhen i try to run it the keyboard shows the right keys but when i try to press done after entering the password nothing happens i am using this to handle the button pressprivate void setuploginbutton button launchbutton button findviewbyidridbuttonlaunchtriage launchbuttonsetonclicklistenernew viewonclicklistener override public void onclickview v edittext username edittext findviewbyidridpatient start username value edittext password edittext findviewbyidridpatient start password value try iftriageapplicationmainvalidateuserusernamegettexttostringpasswordgettexttostringgetapplicationcontext toastmaketextstartactivitythis launching triage application toastlength short show startactivitynew intentstartactivitythis mainactivityclass else alertdialogbuilder alertdialogbuilder new alertdialogbuilder startactivitythis set dialog message alertdialogbuilder setmessageincorrect credentials setcancelablefalse setpositivebuttonoknew dialoginterfaceonclicklistener public void onclickdialoginterface dialogint id if this button is clicked close current activity dialogcancel create alert dialog alertdialog alertdialog alertdialogbuildercreate show it alertdialogshow catch ioexception e todo autogenerated catch block eprintstacktrace i know this is a lot of code but if anyone could help me here it would be great this is for a school project ps i have searched through google for a solid hour before posting this so please do not criticize for not doing that if you find a link that is useful then please share,['android'] +800484,developer use of taptic engine on apple watch according to apples press info about the release of ios 82 and xcode 62 found here they mention developers being able to use the new technologies presented with the apple watchwith the ios 82 beta sdk developers can now start using watchkit to create breakthrough new apps glances and actionable notifications designed for the innovative apple watch interface and work with new technologies such as force touch digital crown and taptic engineafter combing through the watchkit framework documentation i have found no mention of using the taptic engine is there a way for developers to use it perhaps they have not implemented that yet and it may come in a later update for ios 82 but i do not think this is the case what am i missing,"['ios', 'iphone']" +800671,why viewdidlayoutsubviews call multiple times i am developing ios universal app on swiftusing auto layout and support only portraiti found uiviewcontrollerviewdidlayoutsubviews called multiple times instead viewdidload only call once on starting up myapps uiviewcontroller why viewdidlayoutsubviews call multiple times constraints on each uiviewuibuttonsuitextfields etc will perform in orderany information will be appreciated,['ios'] +800684,map rotation horribly slow on ios8 i got the following code in a vc in an old project no storyboard pure code voidviewdidload super viewdidload selfmapview mkmapview alloc initwithframecgrectinsetselfviewframe 10 10 selfview addsubviewselfmapview selfviewbackgroundcolor uicolor redcolor selfmapviewautoresizingmask uiviewautoresizingflexiblerightmargin uiviewautoresizingflexiblebottommargin uiviewautoresizingflexibleheight uiviewautoresizingflexiblewidth selfviewtranslatesautoresizingmaskintoconstraints no this lineif i comment the last line a rotation from portrait to landscape or the other way is about 3 seconds under ios8 also occasionally at random times unable to allocate render buffer storage errors appearif i do not comment it it is almost instantaneous 07seconds it seems it is only related to mapviews the other viewsvcs rotate just fineunder ios7 the rotation is fast in any case with that line commented or not why and why is only the mapview affected edit it seems clearly the autoresizingmask is wrong if in viewdidload i set its value to none and manually change the frame in willrotate it works fast,['ios'] +800699,polymer my corelist is no rendered when is in coreanimatedpages element i have a render problemno render of a corelist element when my custom element is in coreanimatedpageshere is a jsfiddle when it works grey list albumgrid outside coreanimatedpageshere is a jsfiddle when id does not works no grey list albumgrid inside coreanimatedpagescould you help me thankshere is my code script src script link href relimport link href relimport link href relimport link href relimport link href relimport link href relimport style html body margin 0 webkittaphighlightcolor transparent overflow hidden remoteapp thisplay block height 100 margin 0 auto style head body fit remoteapp remoteapolymerelement namealbumdetail attributesalbum layout vertical template style details width 740px margin auto height 100 boxshadow 0 27px 24px 0 rgba0 0 0 06 poositionrelative mycard height 540px borderradius 3px textalign start overflow hidden background f boxshadow 0 6px 20px 0 rgba0 0 0 019 cardleft width 200px height 200px backgroundcolorblue btn backgroundcolorred height63px title backgroundcoloryellow colorblack info height200px item height48px colorblack backgroundcolorgrey style section iddetails classdetails div classmycard layout vertical div layout horizontal div classcardleft div div flex autohorizontal layout vertical classinfo div layout vertical flex classtitle div flex autotitlediv div flex autotitle2div div div layout horizontal a flex classbtna a flex classbtnba a flex classbtnca div div div corelist idlist3 dataalbumpistes height48 flex template div layout horizontal classitem center divindex toto modelnamediv div template corelist div section template script polymer scriptpolymerelementpolymerelement nameremoteapp layout vertical template style drawer backgroundcolor b99588 borderright 1px solid c main backgroundcolor 4f7dc9 height100 host thisplay block position absolute top 0 left 0 width 100 height 100 overflow hidden albumgrid thisplay block height 100 width 100 margin 0 auto pages thisplay block height 100 margin 0 auto item height48px colorblack backgroundcolorgrey style coredrawerpanel div drawer div div main albumdetail albumele flex coreanimatedpages idpages selected0 albumdetail albumele coreanimatedpages div coredrawerpanel template script polymer elepistesname1name2name3name4 scriptpolymerelement,['css'] +800873,how to handle dependency on scipy in setuppy i am trying to create a setuppy for a project that depends on scipy the following setuppy reproduces thissetup nametest version01 install requiresscipywhen installing this using python setuppy develop it generates the following errorimporterror no module named numpythistutilscorehowever when i install scipy using pip it installed it from a wheel and it works just fineso my questions is how can i create a setuppy that depends on scipy why would not setuptools install dependencies from wheels would this work better when using python 3 we plan to migrate anyway so if it works there i will just wait until the migration is completei am using python 278 on mac os x 10101 with setuptools 36 and pip 156,['python'] +800940,kibana for sql database i need to build a kibana like dashboard over a sql database is this possible or is there an alternative as easy as kibana in term of integration for sql,['sql'] +800961,how to check expiry date of pfx file i want to check the expiry date of pfx fileplease guide me with the steps anywhere in visual studio we can check this expiry date,['c#'] +801078,make tumblr photo post act as photoset i am new to tumblr i have such problemi am using indy theme when i post several photos by clicking it acts like slideshow i mean it is posted as blockphotoset but when i post one photo after clicking it redirects me to another pageall i want is to make even one photo act as photoset and after clicking be thisplayed on the same pagethans in advancehere is part of the html of the themeblockphoto article classpostphoto idpostid div classpostcontent blockindexpagea hrefpermalinkimg srcphotourl500 datahighresphotourlhighres altphotoaltablockindexpage blockpermalinkpagelinkopentagimg srcphotourlhighres altphotoaltlinkclosetagblockpermalinkpage blockcaptionpcaptionpblockcaption blockphotoblockphotoset article classpostphotoset idpostid div classpostcontent div classphotoslideshow idphotoset postid datalayoutphotosetlayout blockphotos div classphotodata a relpostpostid hrefphotourlhighres blockcaptiontitlecaptionblockcaption div classpxuphoto img altphotoalt srcphotourl500 widthphotowidth500 heightphotoheight500 datahighresphotourlhighres datawidthphotowidthhighres dataheightphotoheighthighres div a div blockphotos div blockcaptionpcaptionpblockcaption blockphotoset,['html'] +801267,what are the 15 classifications of types in c during a cppcon2014 conference talk by walter e brown he states that there are 15 classifications of types in c that the standard describes 15 partitions of the universe of c typesvoid is one of them walter e brown what are the other 14while digging through the standard i found the following 201141primary type categoriestemplate class t struct is voidtemplate class t struct is integraltemplate class t struct is floating pointtemplate class t struct is arraytemplate class t struct is pointertemplate class t struct is lvalue referencetemplate class t struct is rvalue referencetemplate class t struct is member object pointertemplate class t struct is member function pointertemplate class t struct is enumtemplate class t struct is uniontemplate class t struct is classtemplate class t struct is function 201142 composite type categoriestemplate class t struct is referencetemplate class t struct is arithmetictemplate class t struct is fundamentaltemplate class t struct is objecttemplate class t struct is scalartemplate class t struct is compoundtemplate class t struct is member pointerhmm that is more than 15 these are type traits anyhow they are used to test certain properties of types at compile time for example an integer type would give back true for is integral is fundamental and is is scalar perhaps the 15 are some of the ones listed above and the rest are sub categories to others heres my attempt of trying to make a type tree of the language my guess 1 void 2 bool 3 char 4 nullptr 5 integral signed 6 integral unsigned 7 floating 8 enum 9 array 10 class 11 union 12 lvalue reference 13 rvalue reference 14 member object pointer 15 member function pointerbut also note that bool char and enum are all integral types so i am really not very confident in this list,['c++'] +801283,android gradle plugin multidex zipexception i am trying to use the new multidex option but i get the following errorexecution failed for task packageallvarianttestclassesformultidex javautilzipzipexception duplicate entry androidsupportmultidexbuildconfigclassi have been able to thiscover the issue only happens when running the connectedandroidtests task and not when simply building the project build,['android'] +801466,implementing google custom search api in ios i went through several links in order to find the proper steps to implement google customsearchapi in an ios application and spent about 67 hours in that processlinks h1topiccustomsearchht2fnfervwogoogle custom search 403 error in iosand father of allall these provide bits and peaces of formation is there any place to have a summarize precise info that can help to implement the custom search in an ios application,['ios'] +801471,programmatically set image to uiimageview with xcode 61swift i am trying to set uiimageview programmatically in xcode 61iboutlet weak var bgimage uiimageviewvar image uiimage uiimagenamedafternoonbgimage uiimageviewimage imagebgimageframe cgrectx 0 y 0 width 100 height 200viewaddsubviewbgimagebut xcode is saying expected declaration with bgimage uiimageviewimage image image afternoonis a png and my understanding is png does not need an extension in xcode 61also tried just bgimageimage uiimagenamed afternoon but still getupdateok i have put the code to update uiimageview into the viewdidload function but uiimageview is still not showing the image which exists in the base directory as afternoonpng iboutlet weak var bgimage uiimageview iboutlet weak var datelabel uilabel iboutlet weak var timelabel uilabel override func viewdidload superviewdidload do any additional setup after loading the view typically from a nib updatetime var timer nstimer let aselector selector updatetime timer nstimerscheduledtimerwithtimeinterval001 target self selector aselector userinfo nil repeats true var image uiimage uiimagenamedafternoon bgimage uiimageviewimage image,['ios'] +801607,how to preserve timezone when deserializing datetime using jsonnet i am parsing some json in c using jsonnet one of the fields in the json is a datetime like this thetime20141120t0715110500 a lot more fields note that the time part is 071511 tz of gmt5 hrsi parse the json from a stream like this using var streamreader new streamreaderrcvdstream jsontextreader reader new jsontextreaderstreamreader jsonserializer serializer new jsonserializer jobject data serializerdeserializejobjectreader then access the timedatetime thetime datetimedatathetimehowever this gives me this datetime object20112014 121511date 20112014 0day 20dayofweek thursdaydayofyear 324hour 12kind localmillisecond 0minute 15month 11second 11ticks 635520825110timeofday 121511year 2014i need to know the original local time and tz offset but i seem to have lost that information in the deserialization process and it is giving me the time in what i presume is my local time i am in the uk so currently at gmt0is there a way for me to preserve the timezone information when deserializingedit added more detail about how i am deserializing,['c#'] +801749,path variables in spring websockets sendto mapping i have what i think to be a very simple spring websocket application however i am trying to use path variables for the subscription as well as the message mappingi have posted a paraphrased example below i would expect the sendto annotation to return back to the subscribers based on their fleetid ie a post to fleetmyfleetdrivermydriver should notify subscribers of fleetmyfleet but i am not seeing this behaviorit is worth noting that subscribing to literal fleetfleetid works is this intended am i missing some piece of configuration or is this just not how it worksi am not very familiar with websockets or this spring project yet so thanks in advancecontrollerjavamessagemappingfleetfleetiddriverdriveridsendtotopicfleetfleetidpublic simple simpledestinationvariable string fleetid destinationvariable string driverid return new simplefleetid driveridwebsocketconfigjavaconfigurationenablewebsocketmessagebrokerpublic class websocketconfig extends abstractwebsocketmessagebrokerconfigurer override public void configuremessagebrokermessagebrokerregistry config configenablesimplebrokertopic configsetapplicationdestinationprefixeslive override public void registerstompendpointsstompendpointregistry registry registryaddendpointfleetwithsockjs indexhtmlvar socket new sockjsfleetvar stompclient stompoversocketstompclientconnect functionframe does not work stompclientsubscribetopicfleetmyfleet functiongreeting works stompclientsubscribetopicfleetfleetid functiongreeting do some stuff send sample stompclientsendlivefleetmyfleetdrivermydriver jsonstringify some simple content,['java'] +801760,django batchingbulk update or create i have data in the database which needs updating peridocially the source of the data returns everything that is avalible at that point in time so will include new data that is not already in the databaseas i loop through the source data i do not want to be making 10s of individual writes if possibleis there anything such as update or create but works in batchesone thought was using update or create in combination with manual transactions but i am not sure if that just queues up the individual writes or if it would combine it all into one sql insert or similarly could using commit on success on a function with update or create inside a the loop worki am not doing anything with the data other than translating it and saving it to a model nothing is dependant on that model existing during the loop,['python'] +801777,cannot set translatesautoresizingmaskintoconstraints in an attempt to solve an autolayout issue related to programmatically adding sub views to a scroll view i have run into many references throughout the internet that in various scenarios say to set translatesautoresizingmaskintoconstraints yes or translatesautoresizingmaskintoconstraints no depending on the casehowever in swift when i typevar view uiviewviewtranslatesautoresizingmaskintoconstraints falsei get the inline error cannot assign to translatesautoresizingmaskintoconstraints in view why because when inspected youll find that it is a parameterless function not a propertyi have gotten around this by subclassing but it is a major inconvenience to have to subclass every view i am dealing with just to set translatesautoresizingmaskintoconstraintsclass cardview uiview override func translatesautoresizingmaskintoconstraints bool return false does anyone know a way around this or can shed light on the thiscrepancy between what the general internet councils tell you and what you can actually do in swift,['ios'] +801808,necessary and sufficient conditions to run java applets and jws applications in browser i have already asked this and was heavily downvoted unfortunately i still cannot solve it i do not know what i do but sooner or later i loose an ability to run java applets and java web start applications in all browsershere is an example what is happeningi am opening page with applets and getting the following picturewith signs plugins were blocked i am trying to unblockwhich causes another dialogafter ok i have anothernextif clickedand so onapplet does not runafter dancing with pathes java updates and so one once i can have applet run but sooner or later i will stuck in this position againi would like to know is it possible to exclude this situation in principle i mean i do not want to thisable security at all but i mean that in case my explicit permission everything should run is it possible to do thatupdatefirst of all i do not understand why cannot i run applet on outdated java if i want i am a human and robots should obey me suppose i wish to debug my applet on old version of java why notsecond there is no information about what version it thinks i have and what version it wants without this information it is possible that there is just a bug in version detection mechanismi have multiple versions of java in program files since i am a java developer then how can i know which one it usesupdate 2i have updated my java from 180 20 to 180 25 and now situation have changed but applets are sill impossible to runthe proof i have latest javathe proof i have added the site above to exclusions listthe effect of applet runapplet not runsclicking details resultno any details in factso what to doupdate 3this site is not working orb1cov0log0cad0orbshow orbit diagramreloadingrestarting browser does not help,['java'] +801902,css transform scale do not scale child element if i have a div with a few child elements and it is being css transform scaled i have got one child element which i do not want to scaleparent webkittransform scale5 spanlastchild webkittransform something to ignore the parent scalediv idparent spanchild 1span spanchild 2span spanchild 3 do not scale mespandivcan this be done with css only without changing the html or using js,['css'] +802069,findnearest findinrange how to use in screeps i try to use findnearest like thatvar sources creeproomfindnearestgamesources creepmovetosources0creepharvestsources0and this is what i gettypeerror undefined is not a functionat moduleexports528at main116how to use this method and findinrange so that they do not cause this error,['javascript'] +802086,best place to call recyclerviewadapternotifyitem updating listviews with a cursorloader was a simple way of thisplaying datas from a db into ui model modifications where propagated to the ui with no extra work and maybe not so efficientlyrecyclerviewadapter gives access to more granularity allowing for instance to specify the adapter that a particular item was removedbut what is the best place to call those preferred methods notifyitem replacing notifydatasetchangedobviously the adapter must not observe the contentprovider otherwise it would not know the nature of the model modification just as beforedifferent patterns could be used like adding a bus to publish modifications from the provider creating a singleton model which would hold a reference to the adapter maybe using presenters introduced in l or creating an activitybound servicehere is a common use case a sync process inserts an entry in db or a gcm notification is received which also inserts an entry in db then i want ui if launched to be updated via a call to notifyiteminserted where to place this callthanks,['android'] +802163,get uitextview dynamic height with auto layout after setting text i have a uitextview not scrollable with auto layout set by interface builder and the text increase or decrease dynamically with no problem but i want know what is the new uitextview height after setting text i am trying to do thisnslogtext before 2fselfmytextframesizeheightselfmytext settextselfstringnslogtext after 2fselfmytextframesizeheightthis is the resulttext before 4750text after 4750the text is increased in the view when i run it but the size is the same how i can get the real height after setting text,"['ios', 'objective-c']" +802228,does entity frameworks dbcontext save changes if no changes were made i could not find an answer on the internetlet us suppose i have a dbcontext and i just select all the entities from it i do not add update or delete any entity on the dbsetif i call savechanges afterwards on the dbset does it actually waste resources establishing a connection and other stuff even if i did not made any changes to the dbsetis it smart enough to detect if a change was made or not and behave differently,"['c#', '.net']" +802394,css circles shaking on animation i have drawn a circle in css i tried playing around with the code to fix this issue but to no avail i have 2 main issues in chrome the circles shake while rotatingin firefox there appears a taillike dot when the circle is animating in circular motionsthis is the css styling i am using followers arc outer positionabsolute width300px height300px borderradius100 border2px solidfollowers arc start bordercolortransparent ecd201 ecd201 ecd201 webkittransform rotate45deg moztransform rotate45deg mstransform rotate45deg otransform rotate45deg transform rotate45degfollowers arc inner positionabsolute top18px left 18px width 280px height280px borderradius100 border2px solid bordercolortransparent ecd201 ecd201 ecd201o circle webkitanimation rotation 2s infinite linear animation rotation 2s infinite linearwebkitkeyframes rotation from webkittransform rotate0degtransform rotate0deg to webkittransform rotate359degtransform rotate359degkeyframes rotation from webkittransform rotate0degtransform rotate0deg to webkittransform rotate359degtransform rotate359degi circle webkitanimation rotation2 2s infinite linear animation rotation2 2s infinite linearwebkitkeyframes rotation2 from webkittransform rotate359degtransform rotate359deg to webkittransform rotate0degtransform rotate0degkeyframes rotation2 from webkittransform rotate359degtransform rotate359deg to webkittransform rotate0degtransform rotate0degdiv classfollowers arc outer followers arc start o circlediv div classfollowers arc inner followers arc start i circledivi have created a fiddle here is the link am i doing something wrong,['css'] +802493,recycleview notifydatasetchanged illegalstateexception i am trying to update the items of a recycleview using notifydatasetchangedthis is my onbindviewholder method in the recycleview adapteroverridepublic void onbindviewholderviewholder viewholder int position checkbox view listener viewholdergetcheckboxsetoncheckedchangelistenernew compoundbuttononcheckedchangelistener override public void oncheckedchangedcompoundbutton buttonview boolean ischecked update list items notifydatasetchanged what i want to do is update the list items after i check a checkbox i get an illegal exception though cannot call this method while recyclerview is computing a layout or scrollingjavalangillegalstateexception cannot call this method while recyclerview is computing a layout or scrolling at androidsupportv7widgetrecyclerviewassertnotinlayoutorscrollrecyclerviewjava1462 at androidsupportv7widgetrecyclerviewrecyclerviewdataobserveronchangedrecyclerviewjava2982 at androidsupportv7widgetrecyclerviewadapterdataobservablenotifychangedrecyclerviewjava7493 at androidsupportv7widgetrecyclerviewadapternotifydatasetchangedrecyclerviewjava4338 at comappmyappscreensrecycleadapteronrowselectrecycleadapterjava1i also used notifyitemchanged same exception any secret way to update to notify the adapter that something changed,['android'] +802547,with net open sourcing is a ms runtime avaliable on linux and mac i have read much of the news around ms open sourcing net eg however i am still in the dark as to whether ms has released a runtime to run a net application on linux andor mac i still have a number of questions i hope someone can answercan i run my net application on linuxmac without mono if so i read only the serverside stack has been open sourced which assemblies exactly does that entail can i run a hello world console applicationcan i include the ms runtime for linuxmac if there is one with my application so it does not need to be installed separately system wide like it does on windowssimilarly can i include net assemblies without having them installed on the system,"['c#', '.net']" +802662,webapi post works without frombody i have this controller action httppost actionnamea public httpresponsemessage az z notice no frombody return requestcreateresponsehttpstatuscodeok 1 where z is public class z public string a get set but when i post via fiddler post httplocalhost11485apiprofilesa http11contenttype applicationxwformurlencoded charsetutf8host localhost11485contentlength 3acceptencoding gzip deflateacceptlanguage enusenq08heq06cachecontrol nocacheconnection keepalivea1i can actually see it is working questionif so how does it working without the frombody attribute and do i still need not write this attribute also what is the scenario where not writing this attribute will cause problems,['c#'] +802675,access violation using thttpget with openssl under ios after upgrading to xe7 update 1 after upgrading to delphi xe7 update 1 i am seeing the following error when connecting to a server using tidhttp with tidssliohandlersocketopenssldebugger exception notificationproject test ios raised exception class eaccessviolation with message access violation at address 8fe090c9 accessing address c03f1e32break continue help the exception is thrown at line 3133 in idsslopenssltested and works fine on windows and android platformsbefore the upgrade everything worked correctly i also updated to xcode 61 at the same time so perhaps this is part of the problemanybody else seeing a similar error is there a workaround,['ios'] +802741,libgdx reading from json file to arraylist i need help with reading json file to arraylisti have json file name wall symbol name floor symbol i have a classpublic class tile public string name public string symboland i have another class with arraylistpublic class data public static arraylisttile tilesdata public static void loaddata tilesdata new arraylisttile json json new json jsonfromjsontileclass gdxfilesinternaldatatilesjson i need to fill this arraylist with data from json file but i have some problems i guess the line jsonfromjsontileclass gdxfilesinternaldatatilesjsonis wrong when i try to run it there is exception in thread lwjgl application combadlogicgdxutilsserializationexception error reading file datatilesjsoncaused by combadlogicgdxutilsserializationexception unable to convert value to required type name wall symbol name floor symbol i have read the libgdx article about json files but i found it unclear i do not understand how to fill array please help me with this case,['java'] +802901,uitabbar and uitabbaritem with specific image 2x for iphone 5 and iphone 6 iam developing a new app and iam facing some problems to customize the uitabbar and make it work design great in iphone 5 and 6 using 2x imagein the appdelegatem in the didfinishlaunchingwithoptions method i set the images for background item selectedtabbaruitabbarcontroller tabbarcontroller uitabbarcontroller selfwindowrootviewcontrolleruitabbar tabbar tabbarcontrollertabbaruitabbaritem tabbaritem1 tabbaritems objectatindex0uitabbaritem tabbaritem2 tabbaritems objectatindex1uitabbaritem tabbaritem3 tabbaritems objectatindex2uitabbaritem tabbaritem4 tabbaritems objectatindex3uitabbaritem tabbaritem5 tabbaritems objectatindex4uitabbar appearance setbackgroundimageuiimage imagenamedtab bguitabbar appearance setselectionindicatorimageuiimage imagenamedicone home selecionadouitabbar appearance setshadowimageuiimage alloc initand then in the same method for each item i set the image and insettabbaritem1title niltabbaritem1imageinsets uiedgeinsetsmake6 0 6 0tabbaritem1 setimageuiimage imagenamedicone home teste imagewithrenderingmodeuiimagerenderingmodealwaysoriginaltabbaritem2title niltabbaritem2imageinsets uiedgeinsetsmake6 0 6 0tabbaritem2 setimageuiimage imagenamedicone home teste imagewithrenderingmodeuiimagerenderingmodealwaysoriginaltabbaritem3title niltabbaritem3imageinsets uiedgeinsetsmake6 0 6 0tabbaritem3 setimageuiimage imagenamedicone home teste imagewithrenderingmodeuiimagerenderingmodealwaysoriginaltabbaritem4title niltabbaritem4imageinsets uiedgeinsetsmake6 0 6 0tabbaritem4 setimageuiimage imagenamedicone home teste imagewithrenderingmodeuiimagerenderingmodealwaysoriginaltabbaritem5title niltabbaritem5imageinsets uiedgeinsetsmake6 0 6 0tabbaritem5 setimageuiimage imagenamedicone home teste imagewithrenderingmodeuiimagerenderingmodealwaysoriginalmy problem is related iphone 5 and 6 width using the same 2x image as the iphone 5 has 640px 320pts and iphone 6 has 750px 375pts so i decide to create the selectedindicatorimage called aicone home a with width size150pxbecause i have 5 uitabbaritem so 7505 150px each itemimage icone home 150px x 96pxit works really great when run on iphone 6 as ou can seebut when test it on iphone 5 when the item is selected the uitabbaritem area is expanded for the same 150px as is of the image width instead of reduce to 128px it suppose to has this size to fit on iphone 5 as you can seenote the width difference from the first item to the second item for example but it happens to all them it seem that the selected image overlays the uitabbaritemmy 2x image has 150px but as i am supposed to use 2x images for iphone 5 and 6 how can i handle this case to fit the image in uitabbaritem it seems that it will only work if i have one image 150px for 6 and another image 128px for 5is there any solutions using the same 2x image or i need to code to identify that screen size and then select which image,"['ios', 'iphone']" +802962,swift complains extraneous argument label trying to start some swift work i am using var imagedata uiimagejpegrepresentationimage compressionquality10but i get a warning extraneous argument label compressionquality in call i thought that in swift the secondary parameters were either required or allowed to be labelled but this would not let me use it at all fails building if i leave it since this is a system function i cannot use the to require it but i would like to be able to name as many parameters as possible to make code more readable for myself i like the objc method names as verbose as they sometimes areis there a way to set a compiler flag to allow extra argument labels,['ios'] +803036,angularjs nginclude and ngcontroller i have an app which i am building with angular i have about 810 views to build outall the views have a shared footer based on the view and a set of business rules i need to conditionally show hide some of the content on the footersoi have controllers for each view and then one for the footeri include the common footer layout using nginclude where the html i am including references the footer controller in the ngcontrollerindexhtmlbody ngcontrollermainctrl as vm pmessage from main controller vmmainmessagep div ngincludecommonfooterhtmldivbodycommonfooterhtmldiv ngcontrollerfooterctrl as vm pmessage from footer controller vmmessagep p ngshowvmshowsomthingconditional footer contentpdivi want each views controller to determine the state of the footer and whether specific content is hidden or not shouldthisplaysomthinginfooter belowappcontrollermainctrl functionscope var vm this vmmainmessage heelo vmshouldthisplaysomthinginfooter true windowconsolelogmain scope id scopeidthen i had intended that in the footercontroller would reach back into the parent controller and pull out the specific settings to enable thisable content based on the business rulesappcontrollerfooterctrl functionscope var vm this vmmessage vm footer windowconsolelogfooter scope id scopeid windowconsolelogfooter parent scope id scopeparentid windowconsolelogfooter grandparent scope id scopeparentparentid windowconsolelogfooter grandparent scope name scopeparentparentmainmessage windowconsolelogfooter grandparent scope condition scopeparentparentshouldthisplaysomthinginfooter vmshowsomthing false how to pull from parent scope to bind the ngshow to a value set in the parent from within a ngincludei have this example here what i am finding is that i when i reach into the parent scope to pull out the content it is coming back as undefined and i am not sure why i can see that the scopes are nested to the grandparent level by checking the scopeid i believe this is because the nginclude adds an extra scope layer below the view scopesextra points if i can not have to use the scope object and can stick with the var vm this way of doing it that would be preferable but beggars cant be choosers appcontrollermainctrl functionscope var vm thisthank you very much in advance,['javascript'] +803072,implement explorer contextmenu and pass multiple files to one program instance situationi have a 3rd party gui application that accepts multiple files via clifor examplemyprogramexe file1 file2then all the files are loaded at once into the same instance of the applicationto optimize my time i would like to load multiple files by doing rightmouseclick on some files from windows explorer eg select 5 files do rightclick select open in myprogram commandi know how to create the needed registry keys to add that command in the context menu for specific file types that is not a problemproblemthis 3rd party program does not comes with any driver shell extension or methodology that can catch multiple files from contextmenu so instead of that if i select 2 files from explorer each file is open in a separated instance of the program and i do not have idea of developing drivers so a driver is not what i am looking forfocusi am open to suggestions maybe this is not the efficient way but seems the easiest waymy idea is to develop a mini cli application to catch those multiple files maybe based in windows messages or in so inactivity i do not know that is why i am asking write those filesarguments in a text file then join all the arguments in a single line to call my 3rd party program with those arguments to load all the files at once in a single instance of this programin other words just a simple loader to use it from the contextmenu when selecting multiple files to open all the files at once in this 3rd party applicationquestionfirst of all i would like to know if exists a known term to name this thing of an application that is capable to load multiple files in the same instance selecting the files from explorer then contextmenu i would like to research for that termwhich could be the most efficient way to accomplish this task under a vbnetc console application not a driverhow to start developing this any existent sourcecode example from known pages like codeproject,"['c#', '.net']" +803103,jekyll produce custom html for external links target and css class i understand that the target attribute of an a link cannot be specified by css i would like to be able to generate external links in a jekyll based markdown document with the following outputa hreftheurl classexternal target blankthe textawithout resorting to something like thisthe textthe urltarget blank classexternali do not want to hardcode the target in each link because i might want to change it at some point also it is noisy so ideally i would havethe textthe urlclassexternalbut then css cannot add the target blankso my idea would be a custom plugin that allows me to write extlink theurl the text does such a plugin exist are there better ways to achieve this,['css'] +803174,mysql notifier not able to startstoprestart mysql service i have installed mysql 56 with workbench and mysql notifieri can startstop the mysql service service name mysql56 from servicesmsc but i am not able to startstop it from mysql notifier i am having the following errori do not whats going on there i can confirm that a service named mysql56 is present and it startsstops successfully from servicesmscmy system is windows 7 professional 64 bit,['mysql'] +803260,user defined object equality for a set in harmony es6 i have a problem where i am generating many values and need to make sure i only work with unique onessince i am using node js with the harmony flag and have access to harmony collections i decided that a set may be an optionwhat i am looking for is something similar to the following exampleuse strictfunction piecexy thisx x thisy yfunction boardwidthheightpieces thiswidth width thisheight height thispieces piecesfunction generatepieces return new piece00 new piece11 boarda and boardb are two different but equivalent boardsvar boarda new board1010generatepieces var boardb new board1010generatepiecesvar boards new setboardsaddboardaboardshasboardb return truenow normally to achieve this in another language say c i would expect to have to implement an equals function as well as a hash code generating function for both board and piece since i would expect the default object equality to be based on referencesor perhaps use a special immutable value type say a case class in scalais there a means to define equality for my objects to solve my problem,['javascript'] +803273,laravel checking if record exists new to laravel so excuse the newbie question but how do i find if a record existsuser userwhereemail inputgetemailwhat would i do here to see if user has a record,['php'] +803322,writing tests for flow and mortar apps i was wondering if there were any examples of writing unit tests for flow and mortar android apps part of the advantage of the mvp pattern that it offers the split of the presentation and view logic and the presentation logic is what you want to write tests against i was hoping i could see some samples of how people are doing this with flow mortar and what libraries they are relying on it would be great to establish some best practicesedit it is worth noting that google just released junit support for android,['android'] +803418,selenium webdriver tests with javascript thisabled one of our internal applications written in angularjs has a special error box appearing if javascript is thisabled in the browser using noscript similar to the one on stackoverflowi am trying to write an automated test for it but having difficultieswe are using protractor but i am pretty sure this is not about it here is the protractor configuration fileuse strictvar helper requirehelperjsexportsconfig seleniumaddress httplocalhost4wdhub baseurl httplocalhost9001 capabilities helpergetfirefoxprofile framework jasmine allscriptstimeout 20 jasminenodeopts showcolors true isverbose true includestacktrace true where helperjs isvar q requireqvar firefoxprofile requirefirefoxprofileexportsgetfirefoxprofile function var deferred qdefer var firefoxprofile new firefoxprofile firefoxprofilesetpreferencejavascriptenabled false firefoxprofileencodedfunctionencodedprofile var capabilities browsername firefox firefox profile encodedprofile specs specjs deferredresolvecapabilities return deferredpromiseas you see we are setting javascriptenabled firefox preference to false which has been proven to work if you manually open up aboutconfig in firefox change it to false you would see the contents of noscript sectionbut when i run the tests i am getting the following errorexception thrown orgopenqaseleniumwebdriverexception waiting for evaluatejs load failedhere is the complete tracebackfyi selenium 2440 and firefox 3311 are usedas far as i understand with the help of several points raised here thisabling javascript is killing the javascript webdriver itself is it true if yes what are my options or workaroundsnotes in case of chrome in the past it was possible to thisable javascript via thisablejavascript commandline argument but not anymorethis leads to a workaround number 0 downgrade chrome to an old version which supported the commandline flag this would be a nottested plan bsetting javascriptenabledfalse firefox preference works with python selenium bindingsfrom selenium import webdriverprofile webdriverfirefoxprofileprofileset preferencejavascriptenabled falsedriver webdriverfirefoxfirefox profileprofiledrivergethttpsmy internal urlcom no errors and i can assert the error is presenti am open to any suggestions and can provide you with any additional information,['javascript'] +803459,allow unverified ssl certificates in wkwebview i am trying to load a https url with an selfsigned certificate in a wkwebview for ios 8 and it keeps failing the workaround used with uiwebview using setallowsanyhttpscertificate from nsurlrequest does not seem to work does anyone know of any workaround i do not need a solution that is valid for appstore as i only need to access selfsigned certificate sites on development phases not on production but it is really a problem for development and testing server instancesthank you in advance,['ios'] +803524,libreoffice commysqljdbcdriver cannot be loaded i am trying to connect libreoffice base with an mysql database in phpmyadmin with a jdbcconnection the first step is to select which database you want to select the second step is to select which connection the third step is to select your database when i press klasse testen test class i get the following error commysqljdbcdriver cannot be loadeddoes anyone know how to avoid this error,"['java', 'mysql']" +803725,tuples of closed continuous intervals say i have the following list of numbersmy array 0 3 4 7 8 9 10 20 21 22 70i would like to find every closed interval containing consecutive integers without gaps in this list if for any number in the list there are multiple such intervals we only retain the largest of any such intervals the correct answer above should be0 03 47 1020 2270 70to see this note for examplethe closed interval 00 contains the integer 0 contains no gaps and none of its members are contained in any other closed intervalthe closed interval 34 contains no gaps and its members are not contained in any other closed interval with no gaps that is larger than itselfhow can i do this in numpy i started writing an algorithm that uses npdiffmy array to detect transitions in the array but it fails on corner cases such as intervals containing only one item,['python'] +803735,safari 8 multiple select scrolling issue i have been encountering an issue when using multiple select select fields within safari 8 on os x yosemite if the select field has an applied width either inline or as a class i am unable to use the keyboards arrow keys to scroll down through the select as per normal behaviourselect size5 nameselectmultiple multiplemultiplemultiple select jsfiddleselect size5 nameselectmultiple multiplemultiple stylewidth100with style tag jsfiddlewhen the select has style the selection moves out of view instead of scrolling the list downwards keeping the selected item in viewis this a bug in the version of safari version 80 10600125 i am using i am using browserstack for my testing or is this something i can address with a fix through my codethank you,"['html', 'css']" +803794,understanding attributes in aws dynamodb with ruby i cannot seem to wrap my head around the aws ruby sdk documentation for dynamodb or more specifically the concepts of the dynamodb data modelspecifically i have been reading awsdynamodbhtmlnote i have read through the data model documentation as well and it is still not sinking in i am hoping a proper example in ruby with clear up my confusionin the following code snippet i create a table called my books which has a primary key called item id and it is a hash key not a hashrange combinationdyn awsdynamodbclientv20120810new awsdynamodbclientv20120810dyncreate table attribute definitions attribute name item id attribute type n table name my books key schema attribute name item id key type hash provisioned throughput read capacity units 10 write capacity units 10 table descriptionattribute definitionsattribute nameitem id attribute typen table namemy books key schemaattribute nameitem id key typehash table statusactive creation date time20141124 165947 0 provisioned throughputnumber of decreases today0 read capacity units10 write capacity units10 table size bytes0 item count0dynlist tables table namesmy booksdynscan table name my books member count0 scanned count0i then try and populate the table with a new item my understanding is that i should specify the numerical value for item id which is the primary key and then i could specify other attributes for the new itemrecorddocument i am adding to the tabledynput item table name my books item item id 1 item title my book title item released false but that last command returns the following errorexpected hash value for value at key item id of option itemso although i do not quite understand what the hash will be made of i try doing thatdynput item table name my books item item id n 1 item title my book title item released false but this now returns the following errorexpected string value for key and of value at key item id of option itemi have tried different variations but cannot seem to figure out how this workseditupdate as suggested by uri agassi i changed the value from 1 to 1 i am not really sure why this has to be quoted as i have defined the type to be a number and not a string but ok let us just accept this and move on,['ruby'] +803909,adding cocoapod dependencies to a cocoa touch framework iam trying to work out how to add cocoa pod dependencies to an ios app that has an embedded cocoa touch framework i have my podfile set up like thislink with atestappa atestappframeworkaplatform ios 80source pod googleplusiossdk 17then i add a view controller with a sign in button as per the instructions hereand everything compiles with no problems if i then run the app it will start up and thisplay a google plus sign in button but i get a lot of warnings about the google classes being defined in two places for exampleobjc6727 class gppsignin is implemented in both usersjamesburkelibrarydeveloperxcodederiveddatatestappeiqrhcijoqplxgaoodgtwzncvhjkbuildproductsdebugiphonesimulatortestappframeworkframeworktestappframework and usersjamesburkelibrarydevelopercoresimulatordevices730a1805d46f4d119f9eda37c1147f9adatacontainersbundleapplicationeb7ee52a7fb645ce81b41e9a45875e69testappapptestapp one of the two will be used which one is undefinedif i then click on the sign in button i get an error saying that i havenat set the google client id which i have but because the gppsignin class relies on a shared instance it looks like the duplicate classes have confused things20141124 2054257 testapp6727155282 terminating app due to uncaught exception nsinvalidargumentexception reason you must specify clientid for gppsigninlooking in the stack trace we flip from the testapp scope to the testappframework one even though thereas no code in the framework at this pointa3 testappframework 0x010c7f1a9c gppsignin assertvalidparameters 774 testappframework 0x010c7f35e7 gppsignin authenticatemaybeinteractivelywithparams 1185 testappframework 0x010c7f5ac8 gppsigninbutton buttonpressed 1646 uikit 0x010b4c38be uiapplication sendactiontofromforevent 75a19 uikit 0x010b4c2420 uiapplicationmain 128220 testapp 0x010a25e9f3 main 115i get this problem with some other cocoa pods for example mailcore2ios but some other pods donat seem to raise the same warningsis there a way to set my podfile up so that both my framework and my app have access to the same dependencies but without clashing at runtime or should i just not be setting my dependencies up like this,['ios'] +803943,android hide navigation barstay in immersive mode with soft keyboard appearance working on a clients app that is using immersive mode to hide the navigation bar and status bar on every activity using the following codeint currentapiversion androidosbuildversionsdk intfinal int flags viewsystem ui flag layout stable viewsystem ui flag layout hide navigation viewsystem ui flag layout fullscreen viewsystem ui flag hide navigation viewsystem ui flag fullscreen viewsystem ui flag immersive sticky this work only for android 44if currentapiversion 19 getwindowgetdecorviewsetsystemuivisibilityflags code below is for case when you press volume up or volume down without this after pressing valume buttons navigation bar will show up and do not hide final view decorview getwindowgetdecorview decorview setonsystemuivisibilitychangelistenernew viewonsystemuivisibilitychangelistener override public void onsystemuivisibilitychangeint visibility if visibility viewsystem ui flag fullscreen 0 decorviewsetsystemuivisibilityflags the only problem is that they would like the app to stay in immersive mode and not show the navigation bar even when the soft keyboard is showing to type into an edittext can anyone think of a way to always have the navigation buttons backhide keyboard home etc always be hidden even while using the keyboard,['android'] +803993,how to use jquery in meteor 10 i am trying to use jquery like this in meteorjs appjs if meteorisclient meteorstartupfunction button clickfunction p toggle or without meteorstartup function neither workshtmlbuttonclickbuttonpcan you see mepi get no errors and nothing happens when i click the button,['jquery'] +804118,android open failed enoent no such file or directory hi i am trying to read excel from assets and wanted to convert it into json but i am getting the error open failedenoentno such file or directory searched many so questions but could not find the solutionbelow is my codepublic void readxlsfileandconverttojsonobject jsonarray jsonarray new jsonarray jsonarray mainjsonarray new jsonarray try file file new filefileandroid assetfiltersxls fileinputstream fis new fileinputstreamfile final fileinputstream file new fileinputstreamnew filefiltersxls int count 0 get the workbook instance for xls file hssfworkbook workbook new hssfworkbookfis get first sheet from the workbook hssfsheet sheet workbookgetsheetat0 iterate through each rows from first sheet iterator row rowiterator sheetiterator while rowiteratorhasnext row row rowiteratornext loggerinfocount is count if count 0 count 1 else try jsonobject jsonmaterialobject new jsonobject name jsonmaterialobjectputname rowgetcell0 tostring thick ness jsonmaterialobjectputthickness rowgetcell4 tostring rating 1 jsonmaterialobjectputrating 1 rowgetcell5 tostring rating 2 jsonmaterialobjectputrating 2 rowgetcell6 tostring jsonmaterialobjectputlow frequency rank row getcell7tostring jsonmaterialobjectputmedium frequency rank row getcell8tostring jsonmaterialobjectputhigh frequency rank row getcell9tostring add file size final file dir new filefileandroid assetfilename final file listfiles dirlistfiles boolean found false if listfileslength 0 else for file afile listfiles systemoutprintlnafile name afilegetname systemoutprintlna file from json name rowgetcell0tostring if afilegetnameequalsignorecase rowgetcell0tostring pdf jsonmaterialobjectputfilesize truncatedecimalafilelength 1024 2 found true if found break jsonmaterialobjectputpdffilename row getcell0tostring pdf jsonarrayputjsonmaterialobject catch jsonexception e todo autogenerated catch block eprintstacktrace count closeable fileclose catch filenotfoundexception e catch ioexception e creatematerialjsonjsonarraytostring finalfilejson i mentioned the permissions as belowusespermission androidnameandroidpermissionread external storage usespermission androidnameandroidpermissionaccess network state usespermission androidnameandroidpermissionwrite external storagebelow is my trace1125 123235535 isystemout20019 exception accured in readxlsfileandconverttojsonobject fileandroid assetfiltersxls open failed enoent no such file or directory,['android'] +804171,why does the java api use int instead of short or byte why does the java api use int if short or even byte would be sufficientexample the day of week field in class calendar uses intif the difference is too minimal then why do those datatypes short int exist at all,['java'] +804209,angularjs long polling i am trying to perform a simple long poll request in angularjs i make a get request and it hangs on till the server responds then i make the request again and wait for the next response and so onhowever for some reason the code is quite unreliable and misses around 80 of the responses sent from the server below is my codemainmessagesmainpollfunction httpgethttplocalhost8080message successfunctiondata consolelogdata mainmessagespushdata mainpoll erroris there something obvious that i am missing herethe server can detect that the browser is connected and the server does send a response but the code above does not get the response no console output and no error i tried making this request with postman chrome extension and the longpoll worked perfectly there so i think the problem is somewhere in here update the problem occurs only on google chrome and only when there is more than one tab performing the longpoll simultaneously there is some seemingly random behaviour on creating and closing new tabs with the longpoll,['javascript'] +804230,currying for templates in c metaprogramming this is more of a conceptual question i am trying to find the easiest way of converting a twoarg template the arguments being types into a onearg template ie binding one of the typesthis would be the metaprogramming equivalent of bind in booststd my example includes a possible usecase which is passing stdis same as template argument to a template that takes a onearg template template argument stdis same being a twoarg template ie to typelistfindif the typelist is not fully implemented here neither is findif but you get the idea it takes a unary predicate and returns the type for which that predicate is true or void if not such typei have 2 working variants but the first is not a oneliner and the 2nd uses a rather verbose bindfirst contraption that would not work for nontype template arguments is there a simple way to write such a oneliner i believe the procedure i am looking for is called curryinginclude iostreamtemplatetemplatetypename typename class function typename firstargstruct bindfirst templatetypename secondarg using result functionfirstarg secondargtemplatetypename type using isint bindfirst equaltypes intresulttypetemplatetypename type using isint stdis sameint typestruct typelist templatetemplatetypename class predicate struct findif this needs to be implemented return void for now typedef void result int main static assertisintintvalue static assertisintfloatvalue variant 1 using the predefined parameterized type alias as predicate typedef typelistfindifisintresult result1 variant 2 oneliner using bindfirst and stdis same directly typedef typelistfindif bindfirststdis same intresultresult result2 variant 3 oneliner using currying typedef typelistfindifstdis sameint result result2 return 0click here for code in online compiler godbolt,['c++'] +804257,material close button in toolbar instead of back i have seen in googles inbox app composing a new email in the toolbar instead of the back button an arrow it has a close button see picture how can i achieve this,['android'] +804284,yii2 getting bad request 400 on ajax calls this is my codedocumentonchange tblhotelint zone id functione var zoneid thisval var form data zone zoneid ajax url state type post data form data success functionresponse alertresponse this shows bad request 400 unable to verify your data submissionand already having htmlcsrfmetatags any suggestion,['jquery'] +804342,binding between inputdate and momentjs in angularjs in order to formulate question i prepared the simplified exampleinput typedate ngmodelselectedmoment script angularmoduledateinputexample controllerdatecontroller scope functionscope scopeselectedmoment moment more code scriptbasically i just need binding between modelmomentjss date viewinputdate field to work properly date input is updated when model is updated and vice versaapparently trying the example above would bring you error that model is not of the date typethat is why i am asking experienced angularjs developers how can i implement this binding properlyany advices appreciated,['javascript'] +804533,textview onabove button does not work in android 5api 21 it looks like a bug in 5 androidapi 21 i need a textview on button textview should placed above the button it works correct on android 41api 16 and incorrect on 5 androidapi 21 there are screenshots and codeandroid 41 it is correct red textview above the buttonandroid 5 it is incorrect red textview under the buttoncodexml version10 encodingutf8relativelayout xmlnsandroidandroidididrlbottomandroidlayout widthfill parentandroidlayout heightmatch parent framelayout androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentlefttrue androidbackground00ff00 button androidididbvio androidlayout widthwrap content androidlayout height50dip androidtextviobutton textview androidididbvio count androidlayout widthwrap content androidlayout heightwrap content androidtext00 androidtextsize12dip androidtextcolorf androidbackgrounddrawablerounded textbox framelayoutrelativelayoutrounded textbox it is just shape if remove background all looks same textview under button in 5 androidplease advice,['android'] +804674,is there a way to integrate springbatchadmin and springboot properly according to the documentation spring batch admin is very easy to embed into the existing application simply copying webxml and indexjsp then adding needed dependencies is enough getting it to work but if i want to use it in an existing spring boot project it getting worse according to this example the configuration is a bit hacky but it works until i try to use enablebatchprocessing annotation in my configuriton bean then i get the following exception exception in thread main orgspringframeworkbeansfactorybeancreationexception error creating bean with name jobbuilders defined in class path resource orgspringframeworkbatchcoreconfigurationannotationsimplebatchconfigurationclass instantiation of bean failed nested exception is orgspringframeworkbeansfactorybeandefinitionstoreexception factory method public orgspringframeworkbatchcoreconfigurationannotationjobbuilderfactory orgspringframeworkbatchcoreconfigurationannotationabstractbatchconfigurationjobbuilders throws javalangexception threw exception nested exception is javalangclasscastexception orgspringframeworkbatchcorerepositorysupportjobrepositoryfactorybeanenhancerbyspringcglib49fa0273 cannot be cast to orgspringframeworkbatchcorerepositoryjobrepository at orgspringframeworkbeansfactorysupportconstructorresolverinstantiateusingfactorymethodconstructorresolverjava597 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactoryinstantiateusingfactorymethodabstractautowirecapablebeanfactoryjava1095 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorycreatebeaninstanceabstractautowirecapablebeanfactoryjava990 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorydocreatebeanabstractautowirecapablebeanfactoryjava504 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorycreatebeanabstractautowirecapablebeanfactoryjava475 at orgspringframeworkbeansfactorysupportabstractbeanfactory1getobjectabstractbeanfactoryjava302 at orgspringframeworkbeansfactorysupportdefaultsingletonbeanregistrygetsingletondefaultsingletonbeanregistryjava228 at orgspringframeworkbeansfactorysupportabstractbeanfactorydogetbeanabstractbeanfactoryjava298 at orgspringframeworkbeansfactorysupportabstractbeanfactorygetbeanabstractbeanfactoryjava193 at orgspringframeworkbeansfactorysupportdefaultlistablebeanfactorypreinstantiatesingletonsdefaultlistablebeanfactoryjava706 at orgspringframeworkcontextsupportabstractapplicationcontextfinishbeanfactoryinitializationabstractapplicationcontextjava762 at orgspringframeworkcontextsupportabstractapplicationcontextrefreshabstractapplicationcontextjava482 at orgspringframeworkbootcontextembeddedembeddedwebapplicationcontextrefreshembeddedwebapplicationcontextjava109 at orgspringframeworkbootspringapplicationrefreshspringapplicationjava691 at orgspringframeworkbootspringapplicationrunspringapplicationjava320 at orgspringframeworkbootspringapplicationrunspringapplicationjava952 at orgspringframeworkbootspringapplicationrunspringapplicationjava941 at demoapplicationmainapplicationjava35caused by orgspringframeworkbeansfactorybeandefinitionstoreexception factory method public orgspringframeworkbatchcoreconfigurationannotationjobbuilderfactory orgspringframeworkbatchcoreconfigurationannotationabstractbatchconfigurationjobbuilders throws javalangexception threw exception nested exception is javalangclasscastexception orgspringframeworkbatchcorerepositorysupportjobrepositoryfactorybeanenhancerbyspringcglib49fa0273 cannot be cast to orgspringframeworkbatchcorerepositoryjobrepository at orgspringframeworkbeansfactorysupportsimpleinstantiationstrategyinstantiatesimpleinstantiationstrategyjava188 at orgspringframeworkbeansfactorysupportconstructorresolverinstantiateusingfactorymethodconstructorresolverjava586 17 morecaused by javalangclasscastexception orgspringframeworkbatchcorerepositorysupportjobrepositoryfactorybeanenhancerbyspringcglib49fa0273 cannot be cast to orgspringframeworkbatchcorerepositoryjobrepository at orgspringframeworkbatchcoreconfigurationannotationsimplebatchconfigurationenhancerbyspringcglibb5c6eb04jobrepositorygenerated at orgspringframeworkbatchcoreconfigurationannotationabstractbatchconfigurationjobbuildersabstractbatchconfigurationjava58 at orgspringframeworkbatchcoreconfigurationannotationsimplebatchconfigurationenhancerbyspringcglibb5c6eb04cglibjobbuilders8generated at orgspringframeworkbatchcoreconfigurationannotationsimplebatchconfigurationenhancerbyspringcglibb5c6eb04fastclassbyspringcglibd88bd05finvokegenerated at orgspringframeworkcglibproxymethodproxyinvokesupermethodproxyjava228 at orgspringframeworkcontextannotationconfigurationclassenhancerbeanmethodinterceptorinterceptconfigurationclassenhancerjava312 at orgspringframeworkbatchcoreconfigurationannotationsimplebatchconfigurationenhancerbyspringcglibb5c6eb04jobbuildersgenerated at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokeunknown source at sunreflectdelegatingmethodaccessorimplinvokeunknown source at javalangreflectmethodinvokeunknown source at orgspringframeworkbeansfactorysupportsimpleinstantiationstrategyinstantiatesimpleinstantiationstrategyjava166 18 moremy configuration is quite simple i have two configuration beans configurationimportresourceclasspathorgspringframeworkbatchadminwebresourcesservletconfigxml classpathorgspringframeworkbatchadminwebresourceswebappconfigxmlpublic class batchadminconfiguration andconfigurationenablebatchprocessingpublic class batchimporterconfiguration when i remove enablebatchprocessing and try to create jobs with jobbuilderfactory and use stepscope annotation i am getting other classcastexceptions now i am using xml based configuration to create jobs steps and other beans it work well but i would actually preffer xml free configuration is there a way to easily integrate spring boot spring batch and spring batch admin,['java'] +804703,how does mithril and jquery interact with each other i am using mithril as our mvc framework i want to leverage of rich jqueryjquery ui functionalities i would like to understand the dos and do nots when combining jquery with mithrilwhat i understand is i can use mithril config to access the real dom element bind to various jquery functions safelyusing jquery ui functions with mithrilbut what about using jquery selectors on classes or ids to locate the real dom element likeattaching a jquery date picker beforeshow functioninput inst uidatepickerdivaddclassmydatepicker or hiding a div mydivhidewhat is the danger of inprogress mrender causing blah undefinedwould really like to understand the how these 2 components couldshould interact with each other,['jquery'] +804752,turning off tick marks in bokeh i am working on the bokeh 061 tutorial and trying to turn off the tick marks and labels in one of the exercise plots the scatter plotfrom future import divisionimport numpy as npfrom sixmoves import zipfrom bokehplotting import from bokehobjects import range1doutput filescatterhtmlfiguren 40x nprandomrandomsizen 100y nprandomrandomsizen 100radii nprandomrandomsizen 15colors 02x02x02x r g 150 for r g in zipnpfloor502x npfloor302ycirclex y radiusradii fill colorcolors fill alpha06 line colornone titlecolorful scattergridgrid line color noneaxisaxis line color none question part 1 is this the right way to turn off tick labelsaxismajor label text font size 0pt question part 2 and how to turn off tick marks alsoshow open a browseri have managed to turn off the tick labels but no amount of searching the documentation and googling has revealed the incantation needed to turn off the tick marks also i am not sure that setting axismajor label text font size to 0pt is the right way to turn off tick labels or if it is a kludge nothing else seemed to workam i missing something obvious,['python'] +804853,whats the meaning of thisthis0 whats the meaning of thisthis0 in this codewhat does it stands fori know why we use this but i have no idea about thisthis0 class mainactivity1 implements textwatcher public void aftertextchangededitable parameditable public void beforetextchangedcharsequence paramcharsequence int paramint1 int paramint2 int paramint3 public void ontextchangedcharsequence paramcharsequence int paramint1 int paramint2 int paramint3 thisthis0changetonumberparamcharsequencetostring or class mainactivity2 implements viewonclicklistener public void onclickview paramview thisthis0startactivitynew intentthisthis0 aboutclass,"['java', 'android']" +804899,code first cannot enable migrations i am trying to enable migrations but it is throwing an exceptionchecking if the context targets an existing database systemtypeinitializationexception the type initializer for systemdataentitymigrationsdbmigrationsconfiguration1 threw an exception systemtypeinitializationexception the type initializer for systemdataentityinternalappconfig threw an exception systemconfigurationconfigurationerrorsexception configuration system failed to initialize systemconfigurationconfigurationerrorsexception the name attribute must be specified on the section tagi am assuming that the appconfig file is not correctly set up it was automatically set up when i added ef package all i did was add the connection stringxml version10 encodingutf8configuration configsections section nameentityframework typesystemdataentityinternalconfigfileentityframeworksection entityframework version60 cultureneutral publickeytokenb77a5c561934e089 requirepermissionfalse for more information on entity framework configuration visit configsections connectionstrings add namemycontext connectionstringdata sourcemyserverinitial catalogcodefirsttestuser idpasswordmultipleactiveresultsetstrueappentityframework providernamesystemdatasqlclient connectionstrings entityframework defaultconnectionfactory typesystemdataentityinfrastructurelocaldbconnectionfactory entityframework parameters parameter valuev110 parameters defaultconnectionfactory providers provider invariantnamesystemdatasqlclient typesystemdataentitysqlserversqlproviderservices entityframeworksqlserver providers entityframeworkconfigurationi am using sql server 2008 r2as i do have a connection string i do not believe i need the defaultconnectionfactory am i correct note even without this section i am still getting the same exceptionwhat else am i missing,['c#'] +804932,how to clean images in python django i am asking this question because i cannot solve one problem in pythondjango actually in pure python it is ok which leads to runtimeerror tcl asyncdelete async handler deleted by the wrong thread this is somehow related to the way how i render matplotlib plots in django the way i do it isimport matplotlibpyplot as pltfig pltfigurepltclosei extremely minimized my code but the catch is even if i have just one line of codefig pltfigurei see this runtimeerror happening i hope i coud solve the problem if i knew the correct way of closingcleaningdestroying plots in pythondjango,['python'] +804938,programmatically adding animation effect to a programmatically added popupwindow in android so i have a programmatically added popupwindow which looks like this dialog new popupwindowcontext dialogsetcontentviewll dialogshowatlocationview gravityleft gravitytop 70 0 dialogsetwidthw dialogsetheighth 50 dialogsetoutsidetouchabletrue the dialogupdate is somewhere else i did not bother adding it too as it is not important for this matter i guesswhat i want to do is to have some sort of animation effect like it pops right from the button i press so the popup appears this is just an example i just want any sort of animationdocumentation would be ok too as long as it is not xml based i found those already not really helping meif other details are needed i will comment or edit the question,['android'] +804950,nullpointerexception or will print the static variables content i came across following code public class tradingsystem private static string category electronic trading system public static void mainstring args tradingsystem system null systemoutprintlnsystemcategoryoutput electronic trading systemi was surprised to not find a nullpointerexception q1 why did not it throw the nullpointerexception q2 or while compile time due to categorys declaration having static made it to replace the systemie object reference with tradingsystem and as such essentially tradingsystemcategory was called,['java'] +805104,cocoa blocks as strong pointers vs copy i did work several times with blocks as with pointers to which i had strong referencei heard that you should use copy but what is the implication in working with blocks as pointers and not with the raw objecti never got a complain from the compiler that i should not useproperty nonatomic strong myblock blockbut should useproperty nonatomic copy myblock blockas far as i know the block is just an object so why to preferrer copy anyway,['objective-c'] +805132,how can i echo the version of the current laravel version in php i do not want to check my laravel version in the command prompt php artisan version but in the view itselflike thisphp laravel version laravel version check codein the view laravel version do anyone know how i can do that maybe it is not possible,['php'] +805180,android l permission conflict between release and debug apks i have upgraded to android l and have both a released version of my app in google play and a debug version which we use for developmentthey are signed with different keysmy problem is that i install the google play version and then when i try installing the debug version which is defined like sodebug debuggable true packagenamesuffix debug buildconfigfield boolean is dev true and this is the error i receivefailure install failed duplicate permission permcomappnamepermissionc2d message pkgcomappnamethis is the problematic permissionpermission androidnamecomappnamepermissionc2d message androidprotectionlevelsignatureusespermission androidnamecomappnamepermissionc2d messagei am aware of and of the fact that this was created due to a security issue but i still need to be able to work with a team each having their own debug signing keyi have tried uninstalling using adb uninstall and i have tried clearing all apps cache on device,['android'] +805227,change textcolor in searchview using android toolbar i have the following problem i have setup my actionbar to use a toolbar instead using the api 21 with the appcompatv721 the textcolorprimary style tag is configured to use the color androidcolorwhite so all the titles in the new android toolbar will have a white text color so far so goodnow ia ve added a searchview and setup a custom background to it like thisstyle nameappthemebase parentthemeappcompatlight item namecolorprimarycoloraction bar backgrounditem item namecolorprimarydarkcolorstatus backgrounditem item nameandroidwindownotitletrueitem item namewindowactionbarfalseitem item nameandroidtextcolorprimaryandroidcolorwhiteitem item namesearchviewstylestylesearchviewstyleitemstylestyle namesearchviewstyle parentwidgetappcompatsearchview item namequerybackgrounddrawablesearch backgrounditem item namesearchicondrawableicon searchitemstylethe drawable drawablesearch background is a plain white rectangle so guess what as the title text color in the toolbar is white now the text color in the searchview is white as well and as the searchview background is a white rectangle the user cannot see what he is typingmy question is how can i have different text colors for the android toolbar title and the searchview text,['android'] +805252,knockoutjs afterrender callback when all nested components have been rendered i have a hierarchy of nested knockoutjs components using 320 it is working very well but i am looking to execute some code once my entire hierarchy of components has been loaded and rendered it is a rough equivalent of afterrender needed for the same common uses cases as afterrenderi have tried a few approaches but no luck so faradded the following to the root template but it gets called before the nested components are loaded so too earlyko template afterrender onloadbinddata using the latest 330alpha and specifying synchronoustrue on all components but i believe since i am using amd the components are still loaded asynchronously which mean that just because my root applybindings returns does not mean that all components have been loaded and renderedeven tried building a collection of deferred objects that get resolved only when their corresponding components are loaded this got overly complicated and still did not work for reasons i would not go intois there a way to get a callback called once a complete hierarchy of knockoutjs components have been loaded and rendered thanksi just came across these two threads so it seems others are looking for this as well the key differentiator from the existing workarounds are they do not work with nested components,['javascript'] +805297,should a classmember usingdeclaration with a dependent qualifiedid be a dependent name draft n37 of the c11 standard states in namespaceudecla usingdeclaration introduces a name into the declarative region in which the usingdeclaration appearsevery usingdeclaration is a declaration and a memberdeclaration and so can be used in a class definitionin a usingdeclaration used as a memberdeclaration the nestednamespecifier shall name a base class of the class being definedthis is generally used to make a protected typedef within a baseclass public in the derived class as in the following example which compiles successfully in the latest version of clangstruct aprotected typedef int typestruct b a using atypebtype xthe usingdeclaration can refer to a template class this compilesstruct aprotected templatetypename t struct type struct b a using atypebtypeint xit is also possible to refer to a template in a dependent baseclass the following compiles successfully with the typedef commentedtemplatetypename tstruct aprotected templatetypename u struct type templatetypename tstruct b at using typename attype at is dependent typename required typedef typeint inttype error unknown type name typebinttypeint xuncommenting the typename causes an error when instantiating bint error typename keyword used on a nontypeuncommenting the typedef causes an error when parsing b before its first instantiation i am guessing this is because the compiler does not treat type as a dependent typenamethe last paragraph of namespaceudecl suggests that usingdeclarations may specify dependent names and that the typename keyword must be used in order to thisambiguate further usage of the name introducedif a usingdeclaration uses the keyword typename and specifies a dependent name 1462 the name introduced by the usingdeclaration is treated as a typedefnamemy reading of tempdep suggests that attype is a dependent name it follows logically that the name introduced by the usingdeclaration should also be dependent but tempdep does not explicitly mention the case of a dependent usingdeclaration am i missing something,['c++'] +805346,why do ipython cells stop executing i am sure this is a very newb question so i apologize in advance i am trying to use ipython notebook for a group project the program we are building is fairly large and pulls in a large number of external datasets much of the time ipython seems to stop working i will try to run a cell or multiple cells and nothing will happen except a little asterisk will appear in the brackets to the left of the cell even if i try to just add a new cell and execute 22 nothing will happen what is going on here how do i fix this thanks,['python'] +805396,fix for bizarre a format behavior with g 491 compiler 64bit mingw g 491 from the nuwen thistro under windows 81codeifdef include iostream include iostreamendifinclude stdioh snprintfinclude stdlibh exit success exit failureinclude stdexcept stdexceptionifdef snprintf error snprintf defined as macroendififdef msc ver auto const snprintf snprintfendifvoid test double const value int const precision char buffer34 snprintf buffer sizeof buffer a precision value printf hex of 3f with 2d digits sn value precision buffer auto main int using namespace std try for int precision 6 precision 8 precision test 50 precision test 00 14 return exit success catch exception const x fprintf stderr sn xwhat return exit failureworks fine with visual c but visual c appears to lack the opposite conversionhdevtestso0187cl nologo 21 find i ler vermicrosoft r cc optimizing compiler version 180030723 for x86hdevtestso0187cl barxcpp d include iostream febbarxcpphdevtestso0187bhex 50 with 6 digits 0x140p2hex 50 with 7 digits 0x140p2hex 50 with 8 digits 0x140p2hex 0 with 14 digits 0x0p0hdevtestso0187 also works fine with g when iostream is not includedhdevtestso0187g version find g gcc 491hdevtestso0187g stdc11 barxcpphdevtestso0187ahex of 50 with 6 digits 0x140p2hex of 50 with 7 digits 0x140p2hex of 50 with 8 digits 0x140p2hex of 0 with 14 digits 0x0p0hdevtestso0187 bizarre result whang when iostream is includedhdevtestso0187g stdc11 d include iostream barxcpphdevtestso0187ahex of 50 with 6 digits 0xa0p1hex of 50 with 7 digits 0xa0p1hex of 50 with 8 digits 0x0p33 weirdc hang ctrlchdevtestso0187 im asking for a fix or workaround,['c++'] +805466,ipython notebook pandas max allowable columns i have a simple csv file with ten columnswhen i set the following option in the notebook and print my csv file which is in a pandas dataframe it does not print all the columns from left to right it prints the first two the next two underneath and so oni used this option why is not it workingpdoption contextthisplaymax rows1thisplaymax columns100even this does not seem to workpandasset optionthisplaymax columns none,['python'] +805506,is there any way i can fold all methods in xcode project xcode provides method folding option for the current file but is there any way to apply this to all the m files in the project ps i tried xcode run scripts xcode plugin development but failed to comeup with a proper solution,"['ios', 'objective-c']" +805541,what does the dot operator before the generic parameter mean i saw this code today immutablemapclass extends clientcommand commandprocessorinterface immutablemap immutablemapclass extends clientcommand commandprocessorinterfaceofwhat does this syntax meanimmutablemapclass i knew generics was right after the class name nowhat is the difference betweenimmutablemapclass and immutablemapclass,['java'] +805563,clean messages in windows message pump i do not know much about windows message pump but i guess events are triggered using message pump1 when my web browser control navigates to some websites it creates different events of document completion once i have got what i needed in webbrowser document completedi want to ignore all further document completionhow can i do it2 if i show a messagebox in document completed it shows multiple message boxshows that it runs on parallel threadsbut when i debug it i find that it run always on main threadso when other two threads are created3 at the same time when i press close it closes the window but process is still running in the background i am not using any other thread still i see two other threads when i debug thanks a lot,['c#'] +805697,wordpress redirect to referring page after logging in note i already created the same question in wordpress stackexchange but i did not receive any responses sorry about thati am not using any custom login plugins or any bespoke code a few of my pages have got this bit of code in them at the very beginningphp ifis user logged in wp redirectloginso this does not allow the users to view the page when not logged in i have these pages bearing this bit of codewpcontentmythememyaccountwpcontentmythememyaccountworldphpwpcontentmythememyaccountsubscriptionphpwpcontentmythememydashboardphpwpcontentmythememyfilesphpnow when a user goes to any of the above pages without logging in it redirects to the login page and when the user logs in it lands them to the myaccount pagei want to change the current scenario to make the user redirect to the referring page where he came from i tried the following things which never workedusing a http referrerin the login form i placed this bit of codeinput typehidden nameredirect valuephp echo serverhttp referer hacking functionsphpin the functionsphp i placed this bit of codeif isset getaction getaction logout isset postlogin location empty postlogin location add filterlogin redirect my login redirect 10 3 function my login redirect location serverhttp referer wp safe redirectlocation exit referencesredirect wordpress back to referring page after loginwordpress tip redirect to previous page after logini have also tried these and failedredirecting users to referrer page after logging in using custom login formredirect user to original url after loginnothing was working out i am happy to provide further details if needed thanks in advance my work so fari have modified the code this wayphp ifis user logged in wp redirectloginredirect to serverrequest urithis renders the login page this wayloginphpredirect tomyaccountsubscriptionphpthis would be enough for me to authenticate and redirect but i need to find the bit where the real redirection happens and i want to redirect it using the redirect to parameter,['php'] +805745,importerror cannot import name check array from sklearnutilsvalidation when i import the function check array from module sklearnutilsvalidation it got an import error importerror cannot import name check array the tab completion got check arrays but i am wondering there only exists a function called check array in validationpy source code on github besides the spectral clustering algorithm implemented in scikitlearnsklearnclusterspectralpy also used from utilsvalidation import check array not check arrays i am quite confused about this and my scikitlearn version is 0150b1 hope somebody gives me a clue sample codeimport numpy as npfrom sklearnutilsvalidation import check arraydef my fit affinityx affinity type and neighbors kernel params create an affinity matrix for x using the selected affinity type x check arrayx accept sparse csr csc coo return affinity matrix,['python'] +805919,angular ctrl click how can i catch when user press ctrl click i can do it for single click usinginput ngclicksome functionbut i need something likeinput ngctrlclicksome nice functionis that possible,['javascript'] +805949,c atomic readwrite misunderstanding why program with this code sometimes prints 2 int main stdatomicint a a 0 stdthread t1a stdthread t2a stdthread t3 a aload 1 t1join t2join t3join if a 3 stdcout a a stdendl i have thought stdatomic guarantees that all operations will be done atomically so writing hereincrementing will use a memory barrier and we will have always 3 at the end of threads work i have explored the code and found out that the problem thread is t3 but i cannot understand why it is wrong,['c++'] +806040,how to reconnect to a socket gracefully i have a following method that connects to an end point when my program startschannelsocket new socketaddressfamilyinternetwork sockettypestream protocoltypetcpvar remoteipaddress ipaddressparsechannelipchannelendpoint new ipendpointremoteipaddress channelportchannelsocketconnectchannelendpointi also have a timer that is set to trigger every 60 seconds to call checkconnectivity that attempts to send an arbitrary byte array to the end point to make sure that the connection is still alive and if the send fails it will attempt to reconnectpublic bool checkconnectivitybool isreconnect if channelsocket null var blockingstate channelsocketblocking try var tmp new byte 0 channelsocketblocking false channelsocketsendtmp catch socketexception e try reconnectchannel catch exception ex return false else connectivitylogwarnstringformat01 is null channelip channelport return false return true private void reconnectchannel try channelsocketshutdownsocketshutdownboth channelsocketthisconnecttrue channelsocketclose catch exception ex connectivitylogerrorex channelsocket new socketaddressfamilyinternetwork sockettypestream protocoltypetcp var remoteipaddress ipaddressparsechannelip channelendpoint new ipendpointremoteipaddress channelport channelsocketconnectchannelendpoint threadsleep10 if channelsocketconnected connectivityloginfostringformat01 is reconnected channelip channelport else connectivitylogwarnstringformat01 failed to reconnect channelip channelport so how i would test the above is to physically unplug the lan cable from my ethernet device allowing my code to attempt to reconnect which fails obviously and reconnect back the lan cable however even after reconnecting the lan cable able to ping channelsocketconnectchannelendpoint in my reconnect method always throws this errorno connection could be made because the target machine actively refused it 1921681681604001if i were to restart my whole application it connects successfully how can i tweak my reconnect method such that i do not have to restart my application to reconnect back to my ethernet device,"['c#', '.net']" +806092,android twitter login not working with fabric sdk callback must not be null i am working on a feature that needs to access the public data of twitter users through the twitter rest api and i am using twitters fabric sdk for logging into twitter here is the code of my activityoverrideprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate supportrequestwindowfeaturewindowfeature indeterminate progress setcontentviewrlayoutfragment twitter settingsoverrideprotected void onresume superonresume buttonadd button findviewbyidridadd buttonlogin twitterloginbutton findviewbyidridlogin twittersession session twittergetsessionmanagergetactivesession ifsession null login else long userid sessiongetuserid logoutuserid overridepublic void onactivityresultint requestcode int resultcode intent data superonactivityresultrequestcode resultcode data btnloginonactivityresultrequestcode resultcode dataoverridepublic void onbackpressed superonbackpressed overridependingtransition ranimslide in right ranimslide out rightprivate void login buttonloginsettextlogin buttonloginsetonclicklistenernew onclicklistener override public void onclickview v vpostnew runnable override public void run dologin private void logoutlong userid buttonloginsettextlogout buttonloginsetonclicklistenernew onclicklistener override public void onclickview v vpostnew runnable override public void run dologout private void dologin buttonloginsetcallbacknew callbacktwittersession override public void successresulttwittersession result do something override public void failuretwitterexception exception do something suppresslintnewapiprivate void dologout alertdialog alertdialog if buildversionsdk int buildversion codeshoneycomb alertdialog new alertdialogbuildercontext alertdialogtheme holo lightcreate else alertdialog new alertdialogbuildercontextcreate alertdialogsettitlelogout alertdialogsetmessageare you sure alertdialogseticonrdrawabletwitter alertdialogsetbuttonalertdialogbutton positive ok new dialoginterfaceonclicklistener override public void onclickdialoginterface dialog int which twittergetsessionmanagerclearactivesession alertdialogsetbuttonalertdialogbutton negative cancel new dialoginterfaceonclicklistener override public void onclickdialoginterface dialog int which todo autogenerated method stub dialogcancel alertdialogshowafter following all the instructions here i keep getting the following exception when i click on the twitterloginbuttonfatal exception mainjavalangillegalargumentexception callback must not be nullat comtwittersdkandroidcoreidentitytwitterauthclientauthorizetwitterauthclientjava67at comtwittersdkandroidcoreidentitytwitterloginbuttonloginclicklisteneronclicktwitterloginbuttonjava138at androidviewviewperformclickviewjava4438at androidviewviewperformclickrunviewjava18422at androidoshandlerhandlecallbackhandlerjava733at androidoshandlerthispatchmessagehandlerjava95at androidoslooperlooplooperjava136at androidappactivitythreadmainactivitythreadjava5017at javalangreflectmethodinvokenative methodat comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava779at comandroidinternaloszygoteinitmainzygoteinitjava595,"['java', 'android']" +806155,applicationsigninmanager class is null during authentication process the following code is being used in aspnet mvc 5 project everytime i run the following code the applicationsigninmanager class always comes to be null causing null reference exception being fairly a newbie i do not understand what code calls in the constructor of accountcontroller class passing in the instance of usermanager and sign in manager perhaps that is where i need to focus but the truth is i cannot find that part of the code anyone up for helpto be precise the exception is thrown from the httpost login method the signinmanager is always nullvar result await signinmanagerpasswordsigninasyncmodelusername modelpassword modelrememberme shouldlockout falsebelow is the c sharp codeauthorizepublic class accountcontroller controller private applicationusermanager usermanager private applicationsigninmanager signinmanager public accountcontroller public accountcontrollerapplicationusermanager usermanager applicationsigninmanager signinmanager usermanager usermanager signinmanager signinmanager get accountlogin allowanonymous public actionresult loginstring returnurl viewbagreturnurl returnurl return view public applicationsigninmanager signinmanager get return signinmanager httpcontextgetowincontextgetapplicationsigninmanager private set signinmanager value post accountlogin httppost allowanonymous validateantiforgerytoken public async taskactionresult loginloginviewmodel model string returnurl if modelstateisvalid return viewmodel this does not count login failures towards account lockout to enable password failures to trigger account lockout change to shouldlockout true var result await signinmanagerpasswordsigninasyncmodelusername modelpassword modelrememberme shouldlockout false switch result case signinstatussuccess return redirecttolocalreturnurl case signinstatuslockedout return viewlockout case signinstatusrequiresverification return redirecttoactionsendcode new returnurl returnurl rememberme modelrememberme case signinstatusfailure default modelstateaddmodelerror invalid login attempt return viewmodel code from identityconfig configure the application signin manager which is used in this applicationpublic class applicationsigninmanager signinmanagerapplicationuser string public applicationsigninmanagerapplicationusermanager usermanager iauthenticationmanager authenticationmanager baseusermanager authenticationmanager public override taskclaimsidentity createuseridentityasyncapplicationuser user return usergenerateuseridentityasyncapplicationusermanagerusermanager public static applicationsigninmanager createidentityfactoryoptionsapplicationsigninmanager options iowincontext context return new applicationsigninmanagercontextgetusermanagerapplicationusermanager contextauthentication,"['c#', 'asp.net', '.net']" +806234,conditionally enforce template types in c i have a class template that needs to be able to compare between two objects via comparison objects derived from a compare class i havetemplatetypename tclass container public templatetypename a typename b class compare public virtual bool eqconst a const b const 0 i provide a default comparison objects assuming type t has the operator templatetypename a typename b class default public compareab public bool eqconst a a const b b const return ab private comparett comparison object bool uses default container comparison objectnew default uses defaulttrue containercomparett cmp comparison objectcmp uses defaultfalse container ifuses default delete comparison object however when i try to compile this with a custom class that does not have an operator overload even if i provide an object derived from comparemyobjcmp moccontainermyobjmocthe compiler complains that the operator does not existerror no match for operator operand types are const myobj and const myobjthis makes sense because the default class still needs to be created even though i do not need it but now i need a workaroundany ideas,['c++'] +806261,running foreman from a rake task i have the following rake tasknamespace foreman do task dev do foreman start f procfiledev endenddesc run foreman using procfiledevtask foreman foremandevthe forman command works fine from the shell however when i run rake foreman i get the following errorusersmegemruby200gemsbundler152libbundlerrubygems integrationrb240in block in replace gem foreman is not part of the bundle add it to gemfile gemloaderror from usersmegemruby200binforeman22in mainforman specifically states ruby users should take care not to install foreman in their projects gemfileso how can i get this task to run,"['ruby-on-rails', 'ruby']" +806267,best way to do a task looping in windows service i have a method that send some sms to our customers that look like belowpublic void proccesmsqueue smsdbcontext context new smsdbcontext ismsprovider provider new zenviaprovider smsmanager manager new smsmanagercontext provider try managerprocessqueue catch exception ex eventlogwriteentryexmessage eventlogentrytypeerror finally contextthispose protected override void onstartstring args taskfactorystartnewdoworkcontinuewith so i have some issuesi dona t know how long it takes for the method runthe method can throw exceptions that i want to write on eventlogi want to run this method in loop every 10 min but only after last execution finishhow i can achieve this i thought about using continuewith but i still have questions on how to build the entire logic,['c#'] +806370,how to delete multiple records with entity framework aspnet mvc 5 i have table like the following imagehow can i delete all records of table using entity framework based on projectid,['c#'] +806529,what is are difference between nolock and uncommitted i use sql server 2012i write two queries but what is a different between nolock and uncommitted select lastname firstnamefrom hremployees with readuncommittedselect lastname firstname from hremployees with nolock,['sql'] +806549,difference between divdiv and divnotfirstoftype is there a difference between divdiv and divnotfirstoftype aside from ie6 whatever errors are there cases where they would do different things,"['html', 'css']" +806767,symbols for the module mylibrarydll were not loaded i am trying to learn windows phone dev by making a basic app that provides information about pokemon to do this i have created a portable class library pokelibdll so it is compatible with universal apps i have tested this via a project in the same solution test and it works fine you can take a look at the code for these on my github but as far as i can tell it is all good these two projects are in the one solution for the windows phone apps solution i added pokelib as an existing project added the references and written some a couple lines of code to make sure i could call it okaymainpagexamlgrid gridrowdefinitions rowdefinition heightauto rowdefinition height gridrowdefinitions button namegetdatabutton contentgetdata clickgetdatabutton click gridrow0 horizontalalignmentcenter textblock namedatatext textclick to get data gridrow1 padding10gridmainpagexamlcs protected override void onnavigatedtonavigationeventargs e p new pokemon1 gets data for pokemon 1 bulbasaur pokemon p int counter 0 private async void getdatabutton clickobject sender routedeventargs e datatexttext fetching count counter if counter 1 first time buttons clicked await pcreate populates the data container datatexttext stringformatpokemon 0 1 pid pname when i try to run this on a phone emulator i get the following message i am building the project as debug and have enable just my code unchecked i am not sure what to do under the symbols pane but i can add a screenshot of that too if it would be usefulanyway the app opens but freezes when i press the getdata button i expected it would freeze for a moment since that call is done synchronously but this is permanent however no errorsexceptions are thrown the debugger also does not respond when i attempt to step into the pcreate call likely stemming from the message in the screenshotanyone have an idea of what i am doing wrong thanks,"['c#', '.net']" +806785,android studio intellij gradle errorcause peer not authenticated having a fight with intelliji at the moment the darn thing would not download me gradle 21 i have an android project hosted on github which i have cloned to my laptopi have got working ssl certificates i know this as i can download sdk software from google using ssl and i can also download gradle 112 what i cannot download is gradle 21 i can download gradle 21 using my web browserthe message i have recieved from intellij is the rather infamous errorcause peer not authenticated error from the terminal running intellij i get this what went wronga problem occurred configuring root project x could not resolve all dependencies for configuration classpath could not resolve comandroidtoolsbuildgradle0130 required by xunspecified could not head peer not authenticatedthe xs are to hide the identity of the application it is not an errorit has not got a reason to fail yet it doesi have search far and wide across the internet with no avail please help me wise so gurus,"['java', 'android']" +806919,how does string interning work in java 7 so i realize the questions i am about to ask relate to a topic that has been beaten to death time and time again however even after reading all of the answers and documentation i could find i am still kind of confused about string interning perhaps it is due to my lack of understanding for the jvm perhaps it is due to the changes introduced in java 7 depreciating many of the aforementioned answers and documentation either way i am stuck and i am hoping someone can help me understand the concept a bit more clearlystring a textstring b new stringtextin the above example i understand that two string objects will be created i also understand that there will be only one char array containing the sequence t e x and t in memory however where in memory are each of the string objects actually stored if what i have read i have read correctly the referent of variable a will be stored in the constant pool whereas the referent of b will be stored in the heap right if that be the case i am confused as to how the intern pool maintains interned strings does it keep track of the strings defined in the constant pool and those that have been manually internalized invoked intern from the heap does the jvm create the string objects defined in the constant pool and load them into the intern pool i am confused as to how it all worksagain sorry for asking such confusingasinine questions it is just that i am relatively new to the structure and innerworkings of the jvm and a lot of it has left my head spinning thanks,['java'] +806921,responseobject is not json but nsinlinedata for afhttprequestoperationmanager following code is to submit images through an operationqueue the requests are all fired one by one correctly the server response contains the image file name which client needs to get hold of the problem is that the reponseobject for the successfailure block is not expected parsed json but type of nsinlinedata shown in debugger now i suspect the code to construct the operation from the nsmutableurlrequest caused the issue please helpafhttprequestoperationmanager manager afhttprequestoperationmanager managermanagerresponseserializer afjsonresponseserializer serializernsmutableurlrequest request managerrequestserializer multipartformrequestwithmethodpost urlstringpodurlstring parametersnil constructingbodywithblockidafmultipartformdata formdata nserror error bool success formdata appendpartwithfileurlimgurl nameimages filenameimgpath mimetypeimagejpg errornil if success nslogappendpartwithfileurl error error errornilafhttprequestoperation operation afhttprequestoperation alloc initwithrequestrequestoperation setcompletionblockwithsuccessafhttprequestoperation operation id responseobject nslogimage success responseobject description nsstring imagepath response objectforkeyimagefilename selfdelegate networkmanagerself didsubmitdeliveryimageforimageidimagepath failureafhttprequestoperation operation nserror error nslogimage error error nslogimage error operationresponseobject description nsstring imagefilepath operationresponseobject objectforkeyimagefilename selfdelegate networkmanagerself didfailsubmitdeliveryimageforimageidimagefilepathmanageroperationqueue addoperationoperation,['ios'] +806984,nsinvalidunarchiveoperationexception cannot decode object error in apple watch extension i have got a user object that i need to store in nsuserdefaults and share with an ios 8 extension app watchkit in the main container app i can encode and decode the object without any problem however when i try to retrieve the stored user object in the extension i get a nsinvalidunarchiveoperationexception reason nskeyedunarchiver decodeobjectforkey cannot decode object of class error as far as i can see nscoding has been implemented correctly in the object and i am able to encode and decode the object in the main appcode in container app to store user objectstore user data in nsuserdefaultsnsuserdefaults defaults nsuserdefaults alloc initwithsuitenamegroupcommygroupsfuseraccount user sfuseraccountmanager sharedinstancecurrentusernsdata userencodedobject nskeyedarchiver archiveddatawithrootobjectuserdefaults removeobjectforkeysf user acct1 remove any old valuesdefaults setobjectuserencodedobject forkeysf user acct1defaults synchronizesfuseraccount decodeduser nskeyedunarchiver unarchiveobjectwithdatauserencodedobjectthe last line above to perform a test decode in the main app works finethe code to retrieve from nsuserdefaults and decode in the extension target is below nsuserdefaults defaults nsuserdefaults alloc initwithsuitenamegroupcommygroup nsdata archiveduser defaults objectforkeysf user acct1 if archiveduser sfuseraccount user nskeyedunarchiver unarchiveobjectwithdataarchiveduser in the extension code i get a nsinvalidunarchiveoperationexception reason nskeyedunarchiver decodeobjectforkey cannot decode object of class any suggestions as to where i should start looking the app compiles fine which leads me to believe that the required frameworks have been included in the extension target,['objective-c'] +806990,recyclerview hides actionbar when softkeyboard is opened i have the following layoutxml version10 encodingutf8relativelayout xmlnsandroid androidlayout widthmatch parent androidlayout heightmatch parent androidididcontainer comexamplesendmessagelayout androidididchatmessagelayout androidlayout widthmatch parent androidlayout heightwrap content androidlayout alignparentbottomtrue view androidididseparator androidlayout widthmatch parent androidlayout height0dp androidlayout aboveidchatmessagelayout androidbackgroundcolorseperator line inpost androidsupportv4widgetswiperefreshlayout androidididswipe container androidlayout widthmatch parent androidlayout heightmatch parent androidlayout alignparenttoptrue androidlayout aboveidseparator androidsupportv7widgetrecyclerview androidididrecycleview stylestylebeepmelistview androidlayout widthmatch parent androidlayout heightmatch parent androidlayout aboveidchatmessagelayout androidlayout alignparenttoptrue androidtranscriptmodealwaysscroll androidsupportv4widgetswiperefreshlayoutrelativelayoutwhile sendmessagelayout is just a layout with edittext and a buttonin the old implementation i used plain old listview so when i requested focus for the edit text a keyboard would appear the listview did not move and the first item was visiblebut with the recyclerview everything is pushed up not only the top item is out of the screen but it the whole layout is on top of the actionbarheres how it looks,['android'] +807058,confused with interesting printf statement by reading this code i stumbled upon the following printf statement reset hide cursor and clear screenprintfe0me25le2ji must admit that i am not a fully qualified c hacker and do not fully understand this i tweaked around removing the arguments and i understand what it does well the comment actually says it all but i have no idea how it is done also this is something kind of hard to google forhow does this printf call work,['c'] +807097,how to bring imageview in front of button in android 5 in android versions previous to lolipop the following code works and an image is in front of the button but in android 5 the imageview is put behind the buttonrelativelayout xmlnsandroidxmlnstoolsandroidlayout widthmatch parentandroidlayout heightmatch parentandroidorientationvertical button androidididbutton androidlayout width210sp androidlayout height210sp androidlayout centerhorizontaltrue androidlayout centerverticaltrue androidbackgrounddrawableround button androiddrawablepadding10dip androidgravitycenter verticalcenter horizontal imageview androidididimageview androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparenttoptrue androidlayout centerhorizontaltrue androidcontentdescriptionstringtorch androidsrcattrimageview relativelayout,['android'] +807380,intermittent noclassdeffounderror when running a mavensurefire build in jenkins we are building a large multi module maven project on jenkins including running a large number of unit test once every few builds the build fails on noclassdeffounderror on runlistener which is located in the unit jar as you can see from the log below junit is included in the classpath the error seems to appear completely at randomlog waiting for jenkins to finish collecting dataerror failed to execute goal orgapachemavenpluginsmavensurefireplugin217test defaulttest on project taboolasvc execution defaulttest of goal orgapachemavenpluginsmavensurefireplugin217test failed a required class was missing while executing orgapachemavenpluginsmavensurefireplugin217test orgjunitrunnernotificationrunlistenererror error realm pluginorgapachemavenpluginsmavensurefireplugin217error strategy orgcodehausplexusclassworldsstrategyselffirststrategyerror urls0 filehomebuilderm2repositoryorgapachemavenpluginsmavensurefireplugin217mavensurefireplugin217jarerror urls1 filehomebuilderm2repositoryorgapachemavensurefiresurefirejunit47217surefirejunit47217jarerror urls2 filehomebuilderm2repositoryorgapachemavensurefirecommonjunit48217commonjunit48217jarerror urls3 filehomebuilderm2repositoryorgapachemavensurefirecommonjunit4217commonjunit4217jarerror urls4 filehomebuilderm2repositoryorgapachemavensurefirecommonjunit3217commonjunit3217jarerror urls5 filehomebuilderm2repositoryorgapachemavensurefiresurefiregrouper217surefiregrouper217jarerror urls6 filehomebuilderm2repositoryorgapachemavensharedmavensharedutils04mavensharedutils04jarerror urls7 filehomebuilderm2repositoryorgapachemavensurefirecommonjava5217commonjava5217jarerror urls8 filehomebuilderm2repositoryjunitjunit411junit411jarerror urls9 filehomebuilderm2repositoryorghamcresthamcrestcore13hamcrestcore13jarerror urls10 filehomebuilderm2repositoryorgapachemavensurefiremavensurefirecommon217mavensurefirecommon217jarerror urls11 filehomebuilderm2repositoryorgapachemavensurefiresurefirebooter217surefirebooter217jarerror urls12 filehomebuilderm2repositoryorgcodehausplexusplexusutils151plexusutils151jarerror urls13 filehomebuilderm2repositoryorgapachemavenreportingmavenreportingapi209mavenreportingapi209jarerror urls14 filehomebuilderm2repositoryorgapachecommonscommonslang331commonslang331jarerror urls15 filehomebuilderm2repositoryorgapachemavensurefiresurefireapi217surefireapi217jarerror urls16 filehomebuilderm2repositoryorgapachemavenplugintoolsmavenpluginannotations32mavenpluginannotations32jarerror number of foreign imports 1error import entryimport from realm classrealmmavenapi parent nullerror error orgjunitrunnernotificationrunlistenererror help 1orgapachemavenlifecyclelifecycleexecutionexception failed to execute goal orgapachemavenpluginsmavensurefireplugin217test defaulttest on project taboolasvc execution defaulttest of goal orgapachemavenpluginsmavensurefireplugin217test failed a required class was missing while executing orgapachemavenpluginsmavensurefireplugin217test orgjunitrunnernotificationrunlistenerrealm pluginorgapachemavenpluginsmavensurefireplugin217strategy orgcodehausplexusclassworldsstrategyselffirststrategyurls0 filehomebuilderm2repositoryorgapachemavenpluginsmavensurefireplugin217mavensurefireplugin217jarurls1 filehomebuilderm2repositoryorgapachemavensurefiresurefirejunit47217surefirejunit47217jarurls2 filehomebuilderm2repositoryorgapachemavensurefirecommonjunit48217commonjunit48217jarurls3 filehomebuilderm2repositoryorgapachemavensurefirecommonjunit4217commonjunit4217jarurls4 filehomebuilderm2repositoryorgapachemavensurefirecommonjunit3217commonjunit3217jarurls5 filehomebuilderm2repositoryorgapachemavensurefiresurefiregrouper217surefiregrouper217jarurls6 filehomebuilderm2repositoryorgapachemavensharedmavensharedutils04mavensharedutils04jarurls7 filehomebuilderm2repositoryorgapachemavensurefirecommonjava5217commonjava5217jarurls8 filehomebuilderm2repositoryjunitjunit411junit411jarurls9 filehomebuilderm2repositoryorghamcresthamcrestcore13hamcrestcore13jarurls10 filehomebuilderm2repositoryorgapachemavensurefiremavensurefirecommon217mavensurefirecommon217jarurls11 filehomebuilderm2repositoryorgapachemavensurefiresurefirebooter217surefirebooter217jarurls12 filehomebuilderm2repositoryorgcodehausplexusplexusutils151plexusutils151jarurls13 filehomebuilderm2repositoryorgapachemavenreportingmavenreportingapi209mavenreportingapi209jarurls14 filehomebuilderm2repositoryorgapachecommonscommonslang331commonslang331jarurls15 filehomebuilderm2repositoryorgapachemavensurefiresurefireapi217surefireapi217jarurls16 filehomebuilderm2repositoryorgapachemavenplugintoolsmavenpluginannotations32mavenpluginannotations32jarnumber of foreign imports 1import entryimport from realm classrealmmavenapi parent null at orgapachemavenlifecycleinternalmojoexecutorexecutemojoexecutorjava225 at orgapachemavenlifecycleinternalmojoexecutorexecutemojoexecutorjava153 at orgapachemavenlifecycleinternalmojoexecutorexecutemojoexecutorjava145 at orgapachemavenlifecycleinternallifecyclemodulebuilderbuildprojectlifecyclemodulebuilderjava84 at orgapachemavenlifecycleinternallifecyclethreadedbuilder1califecyclethreadedbuilderjava167 at orgapachemavenlifecycleinternallifecyclethreadedbuilder1califecyclethreadedbuilderjava163 at javautilconcurrentfuturetasksyncinnerrunfuturetaskjava303 at javautilconcurrentfuturetaskrunfuturetaskjava138 at javautilconcurrentexecutorsrunnableadaptercallexecutorsjava439 at javautilconcurrentfuturetasksyncinnerrunfuturetaskjava303 at javautilconcurrentfuturetaskrunfuturetaskjava138 at javautilconcurrentthreadpoolexecutorworkerruntaskthreadpoolexecutorjava895 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava918 at javalangthreadrunthreadjava662caused by orgapachemavenpluginpluginexecutionexception execution defaulttest of goal orgapachemavenpluginsmavensurefireplugin217test failed a required class was missing while executing orgapachemavenpluginsmavensurefireplugin217test orgjunitrunnernotificationrunlistenerrealm pluginorgapachemavenpluginsmavensurefireplugin217strategy orgcodehausplexusclassworldsstrategyselffirststrategyurls0 filehomebuilderm2repositoryorgapachemavenpluginsmavensurefireplugin217mavensurefireplugin217jarurls1 filehomebuilderm2repositoryorgapachemavensurefiresurefirejunit47217surefirejunit47217jarurls2 filehomebuilderm2repositoryorgapachemavensurefirecommonjunit48217commonjunit48217jarurls3 filehomebuilderm2repositoryorgapachemavensurefirecommonjunit4217commonjunit4217jarurls4 filehomebuilderm2repositoryorgapachemavensurefirecommonjunit3217commonjunit3217jarurls5 filehomebuilderm2repositoryorgapachemavensurefiresurefiregrouper217surefiregrouper217jarurls6 filehomebuilderm2repositoryorgapachemavensharedmavensharedutils04mavensharedutils04jarurls7 filehomebuilderm2repositoryorgapachemavensurefirecommonjava5217commonjava5217jarurls8 filehomebuilderm2repositoryjunitjunit411junit411jarurls9 filehomebuilderm2repositoryorghamcresthamcrestcore13hamcrestcore13jarurls10 filehomebuilderm2repositoryorgapachemavensurefiremavensurefirecommon217mavensurefirecommon217jarurls11 filehomebuilderm2repositoryorgapachemavensurefiresurefirebooter217surefirebooter217jarurls12 filehomebuilderm2repositoryorgcodehausplexusplexusutils151plexusutils151jarurls13 filehomebuilderm2repositoryorgapachemavenreportingmavenreportingapi209mavenreportingapi209jarurls14 filehomebuilderm2repositoryorgapachecommonscommonslang331commonslang331jarurls15 filehomebuilderm2repositoryorgapachemavensurefiresurefireapi217surefireapi217jarurls16 filehomebuilderm2repositoryorgapachemavenplugintoolsmavenpluginannotations32mavenpluginannotations32jarnumber of foreign imports 1import entryimport from realm classrealmmavenapi parent null at orgapachemavenplugindefaultbuildpluginmanagerexecutemojodefaultbuildpluginmanagerjava127 at orgapachemavenlifecycleinternalmojoexecutorexecutemojoexecutorjava209 13 morecaused by orgapachemavenpluginplugincontainerexception a required class was missing while executing orgapachemavenpluginsmavensurefireplugin217test orgjunitrunnernotificationrunlistenerrealm pluginorgapachemavenpluginsmavensurefireplugin217strategy orgcodehausplexusclassworldsstrategyselffirststrategyurls0 filehomebuilderm2repositoryorgapachemavenpluginsmavensurefireplugin217mavensurefireplugin217jarurls1 filehomebuilderm2repositoryorgapachemavensurefiresurefirejunit47217surefirejunit47217jarurls2 filehomebuilderm2repositoryorgapachemavensurefirecommonjunit48217commonjunit48217jarurls3 filehomebuilderm2repositoryorgapachemavensurefirecommonjunit4217commonjunit4217jarurls4 filehomebuilderm2repositoryorgapachemavensurefirecommonjunit3217commonjunit3217jarurls5 filehomebuilderm2repositoryorgapachemavensurefiresurefiregrouper217surefiregrouper217jarurls6 filehomebuilderm2repositoryorgapachemavensharedmavensharedutils04mavensharedutils04jarurls7 filehomebuilderm2repositoryorgapachemavensurefirecommonjava5217commonjava5217jarurls8 filehomebuilderm2repositoryjunitjunit411junit411jarurls9 filehomebuilderm2repositoryorghamcresthamcrestcore13hamcrestcore13jarurls10 filehomebuilderm2repositoryorgapachemavensurefiremavensurefirecommon217mavensurefirecommon217jarurls11 filehomebuilderm2repositoryorgapachemavensurefiresurefirebooter217surefirebooter217jarurls12 filehomebuilderm2repositoryorgcodehausplexusplexusutils151plexusutils151jarurls13 filehomebuilderm2repositoryorgapachemavenreportingmavenreportingapi209mavenreportingapi209jarurls14 filehomebuilderm2repositoryorgapachecommonscommonslang331commonslang331jarurls15 filehomebuilderm2repositoryorgapachemavensurefiresurefireapi217surefireapi217jarurls16 filehomebuilderm2repositoryorgapachemavenplugintoolsmavenpluginannotations32mavenpluginannotations32jarnumber of foreign imports 1import entryimport from realm classrealmmavenapi parent null at orgapachemavenplugindefaultbuildpluginmanagerexecutemojodefaultbuildpluginmanagerjava125 14 morecaused by javalangnoclassdeffounderror orgjunitrunnernotificationrunlistener at javalangclassloaderdefineclass1native method at javalangclassloaderdefineclasscondclassloaderjava631 at javalangclassloaderdefineclassclassloaderjava615 at javasecuritysecureclassloaderdefineclasecureclassloaderjava141 at javaneturlclassloaderdefineclassurlclassloaderjava283 at javaneturlclassloaderaccess0urlclassloaderjava58 at javaneturlclassloader1runurlclassloaderjava197 at javasecurityaccesscontrollerdoprivilegednative method at javaneturlclassloaderfindclassurlclassloaderjava190 at javalangclassloaderloadclassclassloaderjava306 at javalangclassloaderloadclassclassloaderjava247 at orgapachemavensurefirebooterisolatedclassloaderloadclassisolatedclassloaderjava97 at javalangclassloaderdefineclass1native method at javalangclassloaderdefineclasscondclassloaderjava631 at javalangclassloaderdefineclassclassloaderjava615 at javasecuritysecureclassloaderdefineclasecureclassloaderjava141 at javaneturlclassloaderdefineclassurlclassloaderjava283 at javaneturlclassloaderaccess0urlclassloaderjava58 at javaneturlclassloader1runurlclassloaderjava197 at javasecurityaccesscontrollerdoprivilegednative method at javaneturlclassloaderfindclassurlclassloaderjava190 at javalangclassloaderloadclassclassloaderjava306 at javalangclassloaderloadclassclassloaderjava247 at orgapachemavensurefirebooterisolatedclassloaderloadclassisolatedclassloaderjava97 at javalangclassgetdeclaredconstructors0native method at javalangclassprivategetdeclaredconstructorsclassjava2398 at javalangclassgetconstructor0classjava2708 at javalangclassgetconstructorclassjava1659 at orgapachemavensurefireutilreflectionutilsgetconstructorreflectionutilsjava76 at orgapachemavensurefireutilreflectionutilsinstantiateoneargreflectionutilsjava129 at orgapachemavensurefirebootersurefirereflectorinstantiateprovidersurefirereflectorjava235 at orgapachemavensurefirebooterproviderfactorycreateproviderproviderfactoryjava113 at orgapachemavenpluginsurefirebooterclientforkstartergetsuitesiteratorforkstarterjava512 at orgapachemavenpluginsurefirebooterclientforkstarterrunsuitesforkpertestsetforkstarterjava277 at orgapachemavenpluginsurefirebooterclientforkstarterrunforkstarterjava169 at orgapachemavenpluginsurefireabstractsurefiremojoexecuteproviderabstractsurefiremojojava967 at orgapachemavenpluginsurefireabstractsurefiremojoexecuteafterpreconditionscheckedabstractsurefiremojojava831 at orgapachemavenpluginsurefireabstractsurefiremojoexecuteabstractsurefiremojojava729 at orgapachemavenplugindefaultbuildpluginmanagerexecutemojodefaultbuildpluginmanagerjava101 14 morecaused by javalangclassnotfoundexception orgjunitrunnernotificationrunlistener at javaneturlclassloader1runurlclassloaderjava202 at javasecurityaccesscontrollerdoprivilegednative method at javaneturlclassloaderfindclassurlclassloaderjava190 at javalangclassloaderloadclassclassloaderjava306 at javalangclassloaderloadclassclassloaderjava247 at orgapachemavensurefirebooterisolatedclassloaderloadclassisolatedclassloaderjava97 53 moreerror error rerun maven using the x switch to enable full debug loggingerror error for more information about the errors and possible solutions please read the following articleserror help 1 error error after correcting the problems you can resume the build with the commanderror mvn goals rf taboolasvcmore infothe build is running on a slave jenkins ver 15652tried with both maven 304 and 311tried with surefire 216 17 18tried with junit 410 411 i have verified the sha1 of junit jar in the maven repository and made sure the jar file is not corrupted command linedefined in a jenkins jobclean install p fasttests thisbuildsystem1 t 4 x erelevant parts from the parent pomxmlthe project itself is a multi module pom project with the parent pom defining the surefire definitions as attached generic tests plugin for maven plugin groupidorgapachemavenpluginsgroupid artifactidmavensurefirepluginartifactid versiontestingsurefireversionversion configuration systempropertyvariables startportfordebugstartportfordebugstartportfordebug surefireforknumberfork surefireforknumbersurefireforknumber geoipdbdirbasedirframeworktargetgeoipdbdir javaawtheadlesstruejavaawtheadless redirecttestoutputtofiletrueredirecttestoutputtofile systempropertyvariables use new jvm for each test parallelclassesparallel threadcount1threadcount forkcounttestingforkcountforkcount reuseforkstestingreuseforkreuseforks usesystemclassloadertestingusesystemclassloaderusesystemclassloader usemanifestonlyjartestingusemanifestonlyjarusemanifestonlyjar thisplay extra information on exception prints usefiletrueusefile redirecttestoutputtofiletrueredirecttestoutputtofile runorderalphabeticalrunorder thisplay extra information on exception prints usefilefalseusefile forkedprocesstimeoutinseconds300forkedprocesstimeoutinseconds arglinexxpermsize128m xxmaxpermsize512m thisbuildsystemisbuildsystemargline configuration dependencies dependency groupidorgapachemavensurefiregroupid artifactidsurefirejunit47artifactid versiontestingsurefireversionversion dependency dependency groupidjunitgroupid artifactidjunitartifactid versionjunitversionversion dependency dependencies plugin profile idfasttestsid properties testingforkcount05ctestingforkcount testingreuseforkfalsetestingreusefork testingusesystemclassloadertruetestingusesystemclassloader testingusemanifestonlyjarfalsetestingusemanifestonlyjar properties profile,['java'] +807442,provide data from a code class to the reporting services designer in vs 2013 i am trying to create a local sql server reporting services report rdlc file and connect this report to some data sets that i generate in code no direct sql server connectioni create a reportdataprovider class with some instance methods that return ilistt for various sets of criteria but i cannot seem to find a way to make those data providing methods show up in the reporting services designer inside visual studio 2013when i look at the dialog that appears after clicking on add dataset on the datasets node in the report data explorer window i see a ton of my classes listed there but not my data provider classis there anything special i need to be aware of make the class static decorate it with some attribute in order for it to show up in that dropdown list of possible data sources i tried various things but have failed to find any way to get this to work properly,['c#'] +807530,conditional statements in a class but outside of scope of the function we know that with notationclass fobject a 1 def init self selfb 2 def cself printcwe can create static variable fooa normal variable b which will be available after creating and instance of foo and method ctoday i was really surprised that i can use conditional statements in a class but outside of scope of the functionclass c if true a 1 b 2languages like cjava taught me that legal notation is similar toclass name variable expressioncould you describe other rules which refer to this specific scope how i should name this scope,['python'] +807634,android studio could not find method runproguard for arguments libraryjavajavavirtualmachinesjdk170 60jdkcontentshomebinjava comintellijrtexecutionapplicationappmain orggradlelaunchergradlemain buildfile userstomdocumentsgit open sourcesandroidmaterialdrawertemplateappbuildgradlefailure build failed with an exception wherebuild file userstomdocumentsgit open sourcesandroidmaterialdrawertemplateappbuildgradle line 16 what went wronga problem occurred evaluating project app could not find method runproguard for arguments false on buildtype decoratednamerelease debuggablefalse testcoverageenabledfalse jnidebuggablefalse pseudolocalesenabledfalse renderscriptdebuggablefalse renderscriptoptimlevel3 applicationidsuffixnull versionnamesuffixnull minifyenabledfalse zipalignenabledtrue signingconfignull embedmicroapptrue mbuildconfigfields mresvalues mproguardfiles mconsumerproguardfiles mmanifestplaceholders tryrun with stacktrace option to get the stack trace run with info or debug option to get more log outputbuild failedtotal time 6741 secsprocess finished with exit code 1apply plugin comandroidapplicationandroid compilesdkversion 21buildtoolsversion 2110defaultconfig applicationid compoliveiraappsmaterialtests minsdkversion 11 targetsdkversion 21 versioncode 1 versionname 10buildtypes release runproguard false proguardfiles getdefaultproguardfileproguardandroidtxt proguardrulespro dependencies compile filetreedir libs include jarcompile comandroidsupportsupportv42100noinspection gradledependencycompile comandroidsupportappcompatv72100compile comandroidsupportrecyclerviewv72100,['android'] +807648,spring datetimeformat ignored in nested objects in my example the datetimeformat annotation is ignored when nesting objectsclass person private date birthdate other fields datetimeformatpatternddmmy public date getbirthdate return birthdate other getterssetters and i have a class which nests this objectsclass persongroup private person person1 private person person2 other fields valid public person getperson1 return person1 also tried without validannotation public person getperson2 return person2 other getterssetters i add an object of the type persongroup to my model in a controlermethod like thismodeladdattributemygroup filledpersongroupin an jsp i use print the nested variablesformform modelattributemygroup action forminput pathperson1birthdate forminput pathperson2birthdate formform but unfortunately the datevalues in the inputfields are not formatted correctly but the date is shown in principleit works when i directly add an instance of the class person to the modelcan anybody tell me how i can handle this i want the date of my nested objects be formatted correctlyi use spring 411release,['java'] +807652,how to parse sentences based on lexical content phrases with pythonnltk can pythonnltk recognize input string and parse it not only based on white space but also on the content say computer system became a phrases in this situation can anyone provide a sample codeinput string a survey of user opinion of computer system response timeexpected output a survey of user opinion of computer system response time,['python'] +807659,can i color table columns using css without coloring individual cells is there a way to color spans of columns all the way down see starting example belowtable border1 tr thmotorth th colspan3engineth thcarth th colspan2bodyth tr tr td1td td2td td3td td4td td5td td6td td7td tr tr td7td td1td td2td td3td td4td td5td td6td trtableand i am looking for a better way less code nonindividual coloring to color for example engine and body spans including all the cells underneath them in dstyle color backgroundcolor d styletable border1 tr thmotorth th colspan3 classcolorengineth thcarth th colspan2 classcolorbodyth tr tr td1td td classcolor2td td classcolor3td td classcolor4td td5td td classcolor6td td classcolor7td tr tr td7td td classcolor1td td classcolor2td td classcolor3td td4td td classcolor5td td classcolor6td trtable,"['html', 'css']" +807732,thisadvantages of shared ptr with shared ptr included in c11 one could achieve a semi garbagecollected enviroment does the inflationary usage come along with some thisadvantagesi could imagine a class model where you create a class in which you typedef your class at the end as a shared ptr to abbreviate the syntax myclass include memoryclass myclass public myclasstypedef stdshared ptrmyclass sharedmyclass example class class example public example myclassobjectnew myclass private sharedmyclass myclassobject,['c++'] +807765,run websocket on gae i am trying adapt my app using websocket to run on gae but reading the docs i am not find a pretty solution to this problemusing a really simple application like that this is my sample demo trying use but i am receive this error when i try to connect to my websocketfollow the image about the request,['javascript'] +807940,compatiblity of material design to versions below android 50 is it possible to use material design themes for versions below android 50according to this link it is not the casematerial design is a comprehensive guide for visual motion and interaction design across platforms and devices android now includes support for material design apps to use material design in your android apps follow the guidelines defined in the material design specification and use the new components and functionality available in android 50 api level 21 and above,['android'] +808309,localized routing in cakephp how to redirect to default language since 2012 this post appears to be the most definitive resource on how to do localized routes in cakephp code copied belowit works great with one exception it does not redirect requests that are missing the language prefix for example will show the same content as if english is the default language and similarly if it is not the homepage there is some mention of this problem in the comments but no conclusive solution which is what i am looking forcode step 1 appconfigroutesphprouterconnectlanguagecontrolleraction array arraylanguage engfrarouterconnectlanguagecontroller arrayaction index arraylanguage engfra routerconnectlanguage arraycontroller welcome action index arraylanguage engfrastep 2 appconfigcorephpconfigurewriteconfiglanguage engstep 3 create appviewhelpermyhtmlhelperphpappuseshtmlhelper viewhelperclass myhtmlhelper extends htmlhelper public function urlurl null full false ifisseturllanguage issetthisparamslanguage urllanguage thisparamslanguage return parenturlurl full step 4 appcontrollerappcontrollerphpclass appcontroller extends controller public components arraycookiesession set an alias for the newly created helper htmlmyhtml public helpers arrayhtml arrayclassname myhtml public function beforefilter this setlanguage private function setlanguage if the cookie was previously set and configlanguage has not been set write the configlanguage with the value from the cookie if thiscookiereadlang thissessioncheckconfiglanguage thissessionwriteconfiglanguage thiscookiereadlang if the user clicked the language url else if issetthisparamslanguage thisparamslanguage thissessionreadconfiglanguage then update the value in session and the one in cookie thissessionwriteconfiglanguage thisparamslanguage thiscookiewritelang thisparamslanguage false 20 days override redirect public function redirect url status null exit true if isseturllanguage thissessioncheckconfiglanguage urllanguage thissessionreadconfiglanguage parentredirecturlstatusexit add the links to the languagesstep 5 appviewecho thishtmllinkenglish arraylanguageeng echo thishtmllinkfranaais arraylanguagefra update 1i tried the suggestion by user221931 but it does not seem to work here is what i added to my routes add default language param routerredirectcontrolleraction arraylanguage fra arraypersist false routerredirectcontroller arraylanguage fra arraypersist false routerredirect arraycontrollerpages actionthisplay language fra home arraypersist false it seems to have no effect the following urls are not redirected httpexamplecom update 2as requested here is my complete routes filephp routes configuration in this file you set up routes to your controllers and their actions routes are very important mechanism that allows you to freely connect different urls to chosen controllers and their actions functions cakephptm rapid development framework copyright c cake software foundation inc licensed under the mit license for full copyright and license information please see the licensetxt rethistributions of files must retain the above copyright notice copyright copyright c cake software foundation inc link cakephptm project package appconfig since cakephptm v 029 license mit license routerparseextensionsjson here we are connecting base path to controller called pages its action called thisplay and we pass a param to select the view file to use in this case appviewpageshomectp routerconnect arraycontroller pages action thisplay home and connect the rest of pages controllers urls routerconnectpages arraycontroller pages action thisplay localized urls see routerconnectlanguagecontrolleraction array arraylanguage engfrarouterconnectlanguagecontroller arrayaction index arraylanguage engfra routerconnectlanguage arraycontroller pages action thisplay home arraylanguage engfra prevent routing conflicts with plugins make an array of loaded pluginsloaded cakepluginloadedarray walkloaded functionitemkey item inflectorunderscoreitemloaded implode loadedrouterconnectlanguageplugincontrolleraction array arraylanguage engfraplugin loaded hide index routerconnectcontroller arrayactionindex routerconnectlanguagecontroller arrayactionindex load all plugin routes see the cakeplugin documentation on how to customize the loading of plugin routes cakepluginroutes load the cakephp default routes only remove this if you do not want to use the builtin default routes require cake config ds routesphp,['php'] +808338,ionic where to put header and top navbar in ionview i am trying to put header and top navbar inside of the ionview directive if i put header nav navbar outside of the ionview tag page is blinking black if page is initializedbut if i try to insert header and top navbar inside of the ionview title and heading in the header is not thisplayedcould somebody tell me what i am doing wrongmaybe some tag inside is missingthanks for any help here is the code of the templatediv classbar barheader barpositive hastabstop button classbutton buttonicon icon ionchevronleft uisrefhome button h1 classtitle results by day translate h1 button classbutton buttonicon icon ionstatsbars uisrefdailychart buttondivtop tab bar div classtabsstriped tabstop tabsbackgroundlight tabslight tabscolordark div classtabs a classtabitem orange home a a classtabitem favorites a a classtabitem settings a divdivionviewdiv classbar barheader barpositive hastabstop button classbutton buttonicon icon ionchevronleft uisrefhome button h1 classtitle results by day translate h1 button classbutton buttonicon icon ionstatsbars uisrefdailychart buttondivtop tab bar div classtabsstriped tabstop tabsbackgroundlight tabslight tabscolordark div classtabs a classtabitem orange home a a classtabitem favorites a a classtabitem settings a divdiv ioncontent ngcontrollerdailylistctrl writeout overal stats for days ionlist classlist ionitem classitem itemlistcustom ngrepeatlistdataitem in listdata div classlistdatetimeblock div classdayh3listdataitemdate from ddh3div div classmonthh3listdataitemdate from mmh3div div row one div idleft div classleftinner appointment success rate translate div div classrightinner listdataitemsuccess rate div div div idright div classleftinner floatright dials translate div div classrightinner listdataitemdials cnt div div row two div idleft div classleftinner success rate since start translate div div classrightinner listdataitemsuccess rate since div div div idright div classleftinner floatright conversations translate div div classrightinner listdataitemconvers cnt div div row three div idleft div classleftinner my deficit translate div div classrightinner listdataitemdeficit div div div idright div classleftinner floatright appointments translate div div classrightinner listdataitemappt cnt div div ionitem ionlist ioninfinitescroll iconionloadingc thistance30 oninfinitesetdaterange ioninfinitescroll ioncontent bottom tabs div classtabsstriped tabsbackgroundpositive tabslight div classtabs a classtabitem active uisrefdailylist hrefdailylist i classicon ionios7paperoutlinei a a classtabitem uisrefweeklylist hrefweeklylist i classicon ionstari a a classtabitem uisrefdailylist hrefdailylist i classicon iongearai a a classtabitem uisrefdailylist hrefdailylist i classicon iongearai a div divionview,"['html', 'css']" +808347,thisabling selectize dropdown when a checkbox is checked i have implemented selectize on my html form however a dropdown only becomes active when the enable checkbox is clicked i know there is a thisable property on the selectize object but i dont know how to use it when the checkbox is clicked i have tried adding the thisabled class to the selectize div element but that does not work either any help will be well appreciated thanks,"['javascript', 'jquery']" +808457,why does not my idea work in python2 here is an idea for a dict subclass that can mutate keys this is a simple self contained example that is just like a dict but is case insensitive for str keysfrom functools import wrapsdef key fix decoratorf wrapsf def wrappedself args kwargs if args and isinstanceargs0 str args args0lower args1 return fself args kwargs return wrappedclass lowerdictdict passfor method name in setitem getitem delitem contains get pop setdefault new method key fix decoratorgetattrlowerdict method name setattrlowerdict method name new methoddev note if you copy my code for your own uses you should implement lowerdict init to check for any key collisions i have not bothered to include that for the purposes of this questionon python3 it all seems to works fine d lowerdictpotato123 spameggs dpotato123 dpopspameggs da keyerror ain python2 it does not even import here is the traceback file tmpthingpy line 15 in module new method key fix decoratorgetattrlowerdict method name file tmpthingpy line 4 in key fix decorator wrapsf file usrlibpython27functoolspy line 33 in update wrapper setattrwrapper attr getattrwrapped attrattributeerror wrapper descriptor object has no attribute module what could be the problem i cannot see any versionspecific code except for the strbasestring thing which is just a minor detail not a codebreaking issue,['python'] +808579,how to install anaconda python for all users anaconda python thistribution is very convenient to deploy scientific computing env sce and switch python versions as you want by default the installation will locate python into anaconda and the sce can only benefit the local userbut what i need is to provide a complete sce wit anaconda while masking the systemwide python version because my cluster is running spark and provides services for multiple users in our team is it possible with current anaconda versionxiaming,['python'] +808664,how to flatten nested array in javascript as we know to flatten the array 0 1 2 3 4 5 by using the method reducevar flattened 0 1 2 3 4 5reducefunctiona b return aconcatbso how to flatten this array 0 1 2 3 4 5 to 0 1 2 3 4 5,['javascript'] +808691,eclipse mat error i am developing an android application in which i am trying to find out the memory leaks using mat for the first time i refereed following linklinktill the step 3 its working but when i try to run step 4 i am getting error in eclipse the error log isorgeclipsecoreruntimecoreexception plugin orgeclipsematui was unable to instantiate class orgeclipsematuisnapshoteditorheapeditorat orgeclipsecoreinternalregistryosgiregistrystrategyosgithrowexceptionregistrystrategyosgijava194at orgeclipsecoreinternalregistryosgiregistrystrategyosgicreateexecutableextensionregistrystrategyosgijava188at orgeclipsecoreinternalregistryextensionregistrycreateexecutableextensionextensionregistryjava905at orgeclipsecoreinternalregistryconfigurationelementcreateexecutableextensionconfigurationelementjava243at orgeclipsecoreinternalregistryconfigurationelementhandlecreateexecutableextensionconfigurationelementhandlejava55at orgeclipseuiinternalworkbenchplugincreateextensionworkbenchpluginjava274at orgeclipseuiinternalregistryeditordescriptorcreateeditoreditordescriptorjava235at orgeclipseuiinternaleditorreferencecreateparteditorreferencejava318at orgeclipseuiinternale4compatibilitycompatibilitypartcreatepartcompatibilitypartjava266at orgeclipseuiinternale4compatibilitycompatibilityeditorcreatepartcompatibilityeditorjava61at orgeclipseuiinternale4compatibilitycompatibilitypartcreatecompatibilitypartjava304at sunreflectnativemethodaccessorimplinvoke0native methodat sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava57at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43at javalangreflectmethodinvokemethodjava606at orgeclipsee4coreinternaldimethodrequestorexecutemethodrequestorjava56at orgeclipsee4coreinternaldiinjectorimplprocessannotatedinjectorimpljava877at orgeclipsee4coreinternaldiinjectorimplprocessannotatedinjectorimpljava857at orgeclipsee4coreinternaldiinjectorimplinjectinjectorimpljava119at orgeclipsee4coreinternaldiinjectorimplinternalmakeinjectorimpljava3at orgeclipsee4coreinternaldiinjectorimplmakeinjectorimpljava254at orgeclipsee4corecontextscontextinjectionfactorymakecontextinjectionfactoryjava162at orgeclipsee4uiinternalworkbenchreflectioncontributionfactorycreatefrombundlereflectioncontributionfactoryjava102at orgeclipsee4uiinternalworkbenchreflectioncontributionfactorydocreatereflectioncontributionfactoryjava71at orgeclipsee4uiinternalworkbenchreflectioncontributionfactorycreatereflectioncontributionfactoryjava53at orgeclipsee4uiworkbenchrenderersswtcontributedpartrenderercreatewidgetcontributedpartrendererjava129at orgeclipsee4uiinternalworkbenchswtpartrenderingenginecreatewidgetpartrenderingenginejava949at orgeclipsee4uiinternalworkbenchswtpartrenderingenginesafecreateguipartrenderingenginejava633at orgeclipsee4uiinternalworkbenchswtpartrenderingenginesafecreateguipartrenderingenginejava735at orgeclipsee4uiinternalworkbenchswtpartrenderingengineaccess2partrenderingenginejava706at orgeclipsee4uiinternalworkbenchswtpartrenderingengine7runpartrenderingenginejava700at orgeclipsecoreruntimesaferunnerrunsaferunnerjava42at orgeclipsee4uiinternalworkbenchswtpartrenderingenginecreateguipartrenderingenginejava685at orgeclipsee4uiworkbenchrenderersswtstackrenderershowtabstackrendererjava1096at orgeclipsee4uiworkbenchrenderersswtlazystackrenderer1handleeventlazystackrendererjava66at orgeclipsee4uiservicesinternaleventsuieventhandler1runuieventhandlerjava41at orgeclipseswtwidgetssynchronizersyncexecsynchronizerjava180at orgeclipseuiinternaluisynchronizersyncexecuisynchronizerjava150at orgeclipseswtwidgetsthisplaysyncexecthisplayjava4688at orgeclipsee4uiinternalworkbenchswte4application1syncexece4applicationjava205at orgeclipsee4uiservicesinternaleventsuieventhandlerhandleeventuieventhandlerjava38at orgeclipseequinoxinternaleventeventhandlerwrapperhandleeventeventhandlerwrapperjava197at orgeclipseequinoxinternaleventeventhandlertrackerthispatcheventeventhandlertrackerjava197at orgeclipseequinoxinternaleventeventhandlertrackerthispatcheventeventhandlertrackerjava1at orgeclipseosgiframeworkeventmgreventmanagerthispatcheventeventmanagerjava230at orgeclipseosgiframeworkeventmgrlistenerqueuethispatcheventsynchronouslistenerqueuejava148at orgeclipseequinoxinternaleventeventadminimplthispatcheventeventadminimpljava135at orgeclipseequinoxinternaleventeventadminimplsendeventeventadminimpljava78at orgeclipseequinoxinternaleventeventcomponentsendeventeventcomponentjava39at orgeclipsee4uiservicesinternaleventseventbrokersendeventbrokerjava80at orgeclipsee4uiinternalworkbenchuieventpublishernotifychangeduieventpublisherjava58at orgeclipseemfcommonnotifyimplbasicnotifierimplenotifybasicnotifierimpljava374at orgeclipsee4uimodelapplicationuiimplelementcontainerimplsetselectedelementelementcontainerimpljava171at orgeclipsee4uiinternalworkbenchmodelserviceimplshowelementinwindowmodelserviceimpljava576at orgeclipsee4uiinternalworkbenchmodelserviceimplbringtotopmodelserviceimpljava543at orgeclipsee4uiinternalworkbenchpartserviceimpldelegatebringtotoppartserviceimpljava605at orgeclipsee4uiinternalworkbenchpartserviceimplbringtotoppartserviceimpljava322at orgeclipsee4uiinternalworkbenchpartserviceimplshowpartpartserviceimpljava1028at orgeclipseuiinternalworkbenchpagebusyopeneditorworkbenchpagejava3120at orgeclipseuiinternalworkbenchpageaccess21workbenchpagejava3042at orgeclipseuiinternalworkbenchpage8runworkbenchpagejava3024at orgeclipseswtcustombusyindicatorshowwhilebusyindicatorjava70at orgeclipseuiinternalworkbenchpageopeneditorworkbenchpagejava3020at orgeclipseuiinternalworkbenchpageopeneditorworkbenchpagejava2984at orgeclipseuiinternalworkbenchpageopeneditorworkbenchpagejava2967at orgeclipseuiideideopeneditoronfilestoreidejava1132at comandroidideeclipseddmsviewsdeviceviewhprofhandleropendeviceviewjava298at comandroidideeclipseddmsviewsdeviceviewhprofhandleraccess2deviceviewjava261at comandroidideeclipseddmsviewsdeviceviewhprofhandler3rundeviceviewjava245at orgeclipseswtwidgetsrunnablelockrunrunnablelockjava35at orgeclipseswtwidgetssynchronizerrunasyncmessagessynchronizerjava135at orgeclipseswtwidgetsthisplayrunasyncmessagesthisplayjava4145at orgeclipseswtwidgetsthisplayreadandthispatchthisplayjava3762at orgeclipsee4uiinternalworkbenchswtpartrenderingengine9runpartrenderingenginejava13at orgeclipsecoredatabindingobservablerealmrunwithdefaultrealmjava332at orgeclipsee4uiinternalworkbenchswtpartrenderingenginerunpartrenderingenginejava997at orgeclipsee4uiinternalworkbenche4workbenchcreateandrunuie4workbenchjava138at orgeclipseuiinternalworkbench5runworkbenchjava610at orgeclipsecoredatabindingobservablerealmrunwithdefaultrealmjava332at orgeclipseuiinternalworkbenchcreateandrunworkbenchworkbenchjava567at orgeclipseuiplatformuicreateandrunworkbenchplatformuijava150at orgeclipseuiinternalideapplicationideapplicationstartideapplicationjava124at orgeclipseequinoxinternalappeclipseapphandleruneclipseapphandlejava196at orgeclipsecoreruntimeinternaladaptoreclipseapplauncherrunapplicationeclipseapplauncherjava110at orgeclipsecoreruntimeinternaladaptoreclipseapplauncherstarteclipseapplauncherjava79at orgeclipsecoreruntimeadaptoreclipsestarterruneclipsestarterjava354at orgeclipsecoreruntimeadaptoreclipsestarterruneclipsestarterjava181at sunreflectnativemethodaccessorimplinvoke0native methodat sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava57at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43at javalangreflectmethodinvokemethodjava606at orgeclipseequinoxlaunchermaininvokeframeworkmainjava636at orgeclipseequinoxlaunchermainbasicrunmainjava591at orgeclipseequinoxlaunchermainrunmainjava1450caused by javalanglinkageerror loader constraint violation when resolving overridden method orgeclipsematuieditormultipaneeditorcreatepartcontrollorgeclipseswtwidgetscompositev the class loader instance of orgeclipseosgiinternalbaseadaptordefaultclassloader of the current class orgeclipsematuieditormultipaneeditor and its superclass loader instance of orgeclipseosgiinternalbaseadaptordefaultclassloader have different class objects for the type eclipseswtwidgetscompositev used in the signatureat javalangclassgetdeclaredconstructors0native methodat javalangclassprivategetdeclaredconstructorsclassjava2483at javalangclassgetconstructor0classjava2793at javalangclassnewinstanceclassjava345at orgeclipsecoreinternalregistryosgiregistrystrategyosgicreateexecutableextensionregistrystrategyosgijava184 92 morei searched on google but not getting what is the issue and how to resolve itplease give me your valuable suggestion to resolve the error,['android'] +808722,iphone 6 plus screen size there were many articles written and questions asked about iphone 6 and iphone 6 plus screen sizes this article provides a great explanationhowever i am confused when testing my app in the simulatori have the following code in appdelegate bool application uiapplication application didfinishlaunchingwithoptions nsdictionary launchoptions uiscreen screen uiscreen mainscreen nslogscreen width 0f px height 0f px scale 1fx double screenboundssizewidth double screenboundssizeheight double screenscale return yesi get the following results from ios simulator for various devicesiphone 4s screen width 320 px height 480 px scale 20xiphone 5 screen width 320 px height 568 px scale 20xiphone 5s screen width 320 px height 568 px scale 20xiphone 6 screen width 320 px height 568 px scale 20xiphone 6 plus screen width 320 px height 568 px scale 20xthe results are fine for iphone 4s iphone 5 and iphone 5s however i expect larger screen size for iphone 6 and iphone 6 plus and i also expect scale 30 for iphone 6 plus what is wrongthanks for explanation,"['ios', 'objective-c']" +808803,add a variation to cart using ajax woocommerce api i have an item with the following data var item id 124 name x price 1313 quantity 1 options size xl color pink when the user clicks on add to cart i would like to make an ajax request using the wc api and add the above item to the cartjqueryajax url somewoocommerceapiaddtocartrequestpath data item type postthen on the cart page i would like to make another ajax request using the wc api and retrieve the contents of the cart i have not found any documentation official or unofficial on how to do that from the client using javascriptdoes anyone know and can provide me with an example pleasealso does anyone know why the woocommerce api documentation is so horrible lacking any kind of information regarding obviousstandard questions like the above i am seriously thinking of having our company switch to shopify,['javascript'] +808944,advice on unsigned int gangnam style edition the video gangnam style i am sure youve heard it just exceeded 2 billion views on youtube in fact google says that they never expected a video to be greater than a 32bit integer which alludes to the fact that google used int instead of unsigned for their view counter i think they had to rewrite their code a bit to accommodate larger viewschecking their style guide typesthey advise do not use an unsigned integer type and give one good reason why unsigned could be buggy it is a good reason but could be guarded against my question is is it bad coding practice in general to use unsigned int,['c++'] +808987,boolean identity true vs is true it is standard convention to use if foo is none rather than if foo none to test if a value is specifically noneif you want to determine whether a value is exactly true not just a truelike value is there any reason to use if foo true rather than if foo is true does this vary between implementations such as cpython 2x and 3x jython pypy etcexample say true is used as a singleton value that you want to differentiate from the value bar or any other truelike valueif foo is true vs foo true elif foo bar is there a case where using if foo is true would yield different results from if foo truenote i am aware of python booleans if x vs if x true vs if x is true however it only addresses whether if foo if foo true or if foo is true should generally be used to determine whether foo has a truelike valueupdate according to pep 285 a specificationthe values false and true will be singletons like none,['python'] +809129,trouble understanding the backpropagation algorithm in neural network i am having trouble understanding the backpropagation algorithm i read a lot and searched a lot but i cannot understand why my neural network do not work i want to confirm that i am doing every part the right wayhere is my neural network when it is initialize and when the first line of inputs 1 1 and the output 0 is set as you can see i am trying to do the xor neural network i have 3 layers input hidden and output the first layer input and the hidden layer contains 2 neurons in which there is 2 synapses each the last layer output contains one neuron with 2 synapses tooa synapse contains a weight and itas previous delta at the beginning it is 0 the output connected to the synapse can be found with the sourceneuron associated with the synapse or in the inputs array if there is no sourceneuron like in the input layerthe class layerjava contains a list of neurons in my neuralnetworkjava i initialize the neural network then i loop in my training set in each iteration i replace the inputs and the output values and call train on my backpropagation algorithm and the algorithm run certain number of time epoch of 10 times for now for the current setthe activation fonction i use is the sigmoidtraining set and validation set is input1 input2 output11001010here is my neuronjava implementationpublic class neuron private iactivation activation private arraylistsynapse synapses inputs private double output output private double errortopropagate public neuroniactivation activation thisactivation activation thissynapses new arraylistsynapse thisoutput 0 thiserrortopropagate 0 public void updateoutputdouble inputs double sumweights thiscalculatesumweightsinputs thisoutput thisactivationactivatesumweights public double calculatesumweightsdouble inputs double sumweights 0 int index 0 for synapse synapse thisgetsynapses if inputs null sumweights synapsegetweight inputsindex else sumweights synapsegetweight synapsegetsourceneurongetoutput index return sumweights public double getderivative return thisactivationderivativethisoutput the synapsejava containspublic synapseneuron sourceneuron thissourceneuron sourceneuron random r new random thisweight 05 05 05 rnextdouble thisdelta 0 getter and setter the train method in my class backpropagationstrategyjava run a while loop and stop after 10 times epoch with one line of the training set it looks like thisthisforwardpropagationneuralnetwork inputsthisbackwardpropagationneuralnetwork expectedoutputthisupdateweightsneuralnetworkhere is all the implementation of the methods above learningrate 045 and momentum 09public void forwardpropagationneuralnetwork neuralnetwork double inputs for layer layer neuralnetworkgetlayers for neuron neuron layergetneurons if layerisinput neuronupdateoutputinputs else neuronupdateoutputnull public void backwardpropagationneuralnetwork neuralnetwork double realoutput layer lastlayer null loop a travers les hidden layers et le output layer uniquement arraylistlayer layers neuralnetworkgetlayers for int i layerssize 1 i 0 i layer layer layersgeti for neuron neuron layergetneurons double errortopropagate neurongetderivative output layer if layerisoutput errortopropagate realoutput neurongetoutput hidden layers else double sumfromlastlayer 0 for neuron lastlayerneuron lastlayergetneurons for synapse synapse lastlayerneurongetsynapses if synapsegetsourceneuron neuron sumfromlastlayer synapsegetweight lastlayerneurongeterrortopropagate break errortopropagate sumfromlastlayer neuronseterrortopropagateerrortopropagate lastlayer layer public void updateweightsneuralnetwork neuralnetwork for int i neuralnetworkgetlayerssize 1 i 0 i layer layer neuralnetworkgetlayersgeti for neuron neuron layergetneurons for synapse synapse neurongetsynapses double delta thislearningrate neurongeterror synapsegetsourceneurongetoutput synapsesetweightsynapsegetweight delta thismomentum synapsegetdelta synapsesetdeltadelta for the validation set i only run thisthisforwardpropagationneuralnetwork inputsand then check the output of the neuron in my output layerdid i do something wrong need some explanationshere are my results after 10 epochreal 00current 0025012156926937503real 10current 0022566830709341495real 10current 002768416343491415real 00current 0024903432706154027why the synapses in the input layer are not updated everywhere it is written to only update the hidden and output layerslike you can see it is totally wrong it does not go to the 10 only to the first train set output 00update 1here is one iteration over the network with this set 1010 here is the result for the forward propagation method input layer neuron 1 synapse 1weight 0192835831573614input 10 synapse 2weight 004023817185601586input 10sum 015259765969972028output 04619242180935 neuron 2 synapse 1weight 03281099260608612input 10 synapse 2weight 04388250065958519input 10sum 07669349326567131output 031714251453174147 hidden layer neuron 1 synapse 1weight 016703288052854093input 04619242180935 synapse 2weight 031683996162148054input 031714251453174147sum 0177639229679783output 05442935820534 neuron 2 synapse 1weight 045330313978424686input 04619242180935 synapse 2weight 03287014377113835input 031714251453174147sum 010514659949771789output 047373754172497556 output layer neuron 1 synapse 1weight 008643751629154495input 05442935820534 synapse 2weight 029715579267218695input 047373754172497556sum 009372646936373039output 047658552081912403update 2i probably have a bias problem i will look into it with the help of this answer role of bias in neural networks it does not shift back at the next dataset so,['java'] +809132,explicit template function specializations with overloads why would you do it suppose the followingtemplate typename t void foo t 1template typename t void foo t 2template void foo int 3when introducing an explicit specialization of a base template which also has overloads the specialization is not considered during overload resolution by design i understand thisbut given that i could make 3 a nontemplate overload and it would be then considered for overload resolution why would i still want to do it as i have done above is there a valid usecase for the setup demonstrated above the only thing i can think of is that if you did not rely on template type deduction the nontemplate functions could not be used since they would not accept the syntax when you call thembtw i have only reviewed the rules for c03 i am not sure ifhow c11 changes these rulesbehaviors,['c++'] +809369,tracking user activity on window opened by windowopen method i want to open a ftp browser at client site so that he can upload files in ftpi am using windowopen method to open the ftp in a child windowvar windowobjectreference windowopenftp username password server blank toolbaryes locationyes statusyes scrollbarsauto copyhistoryno menubaryes width 500px height500px left300px top100px resizableyes the ftp looks like this1 now i want to track the user activity like directories he visitedand send the path to the jsp page how to do that,"['java', 'javascript']" +809551,swipe to thismiss for recyclerview i used to swipetothismiss library but now i am trying to migrate to recyclerview and things are not so obvious do you know any replacements for this lib any ideas how to implement it from the scratch,['android'] +809611,javaxwsrsnotfoundexception could not find resource for full path with resteasy and wildfly 810final i am facing following problem i have spent more than 3 days on this but cannot find a solution please guide me what i am doing wrong here i am new to resteasy with wildflyhere is the stacktrace190557610 warn orgjbossresteasycoreexceptionhandler default task14 failed to execute javaxwsrsnotfoundexception could not find resource for full path httplocalhost8080adminwsservicesusergetuser at orgjbossresteasycoreregistryclassnodematchclassnodejava73 resteasyjaxrs308finaljar at orgjbossresteasycoreregistryrootclassnodematchrootclassnodejava48 resteasyjaxrs308finaljar at orgjbossresteasycoreresourcemethodregistrygetresourceinvokerresourcemethodregistryjava4 resteasyjaxrs308finaljar at orgjbossresteasycoresynchronousthispatchergetinvokersynchronousthispatcherjava234 resteasyjaxrs308finaljar at orgjbossresteasycoresynchronousthispatcherinvokesynchronousthispatcherjava171 resteasyjaxrs308finaljar at orgjbossresteasypluginsserverservletservletcontainerthispatcherserviceservletcontainerthispatcherjava220 resteasyjaxrs308finaljar at orgjbossresteasypluginsserverservlethttpservletthispatcherservicehttpservletthispatcherjava56 resteasyjaxrs308finaljar at orgjbossresteasypluginsserverservlethttpservletthispatcherservicehttpservletthispatcherjava51 resteasyjaxrs308finaljar at javaxservlethttphttpservletservicehttpservletjava790 jboservletapi 31 spec100finaljar100final at ioundertowservlethandlersservlethandlerhandlerequestservlethandlerjava85 undertowservlet1015finaljar1015final at ioundertowservlethandlerssecurityservletsecurityrolehandlerhandlerequestservletsecurityrolehandlerjava61 undertowservlet1015finaljar1015final at ioundertowservlethandlersservletthispatchinghandlerhandlerequestservletthispatchinghandlerjava36 undertowservlet1015finaljar1015final at orgwildflyextensionundertowsecuritysecuritycontextassociationhandlerhandlerequestsecuritycontextassociationhandlerjava78 at ioundertowserverhandlerspredicatehandlerhandlerequestpredicatehandlerjava25 undertowcore1015finaljar1015final at ioundertowservlethandlerssecuritysslinformationassociationhandlerhandlerequestsslinformationassociationhandlerjava113 undertowservlet1015finaljar1015final at ioundertowservlethandlerssecurityservletauthenticationcallhandlerhandlerequestservletauthenticationcallhandlerjava56 undertowservlet1015finaljar1015final at ioundertowserverhandlerspredicatehandlerhandlerequestpredicatehandlerjava25 undertowcore1015finaljar1015final at ioundertowsecurityhandlersabstractconfidentialityhandlerhandlerequestabstractconfidentialityhandlerjava45 undertowcore1015finaljar1015final at ioundertowservlethandlerssecurityservletconfidentialityconstrainthandlerhandlerequestservletconfidentialityconstrainthandlerjava61 undertowservlet1015finaljar1015final at ioundertowsecurityhandlersauthenticationmechanismshandlerhandlerequestauthenticationmechanismshandlerjava58 undertowcore1015finaljar1015final at ioundertowservlethandlerssecuritycachedauthenticatedsessionhandlerhandlerequestcachedauthenticatedsessionhandlerjava70 undertowservlet1015finaljar1015final at ioundertowsecurityhandlerssecurityinitialhandlerhandlerequestsecurityinitialhandlerjava76 undertowcore1015finaljar1015final at ioundertowserverhandlerspredicatehandlerhandlerequestpredicatehandlerjava25 undertowcore1015finaljar1015final at orgwildflyextensionundertowsecurityjaccjacontextidhandlerhandlerequestjacontextidhandlerjava61 at ioundertowserverhandlerspredicatehandlerhandlerequestpredicatehandlerjava25 undertowcore1015finaljar1015final at ioundertowserverhandlerspredicatehandlerhandlerequestpredicatehandlerjava25 undertowcore1015finaljar1015final at ioundertowservlethandlersservletinitialhandlerhandlefirstrequestservletinitialhandlerjava240 undertowservlet1015finaljar1015final at ioundertowservlethandlersservletinitialhandlerthispatchrequestservletinitialhandlerjava227 undertowservlet1015finaljar1015final at ioundertowservlethandlersservletinitialhandleraccess0servletinitialhandlerjava73 undertowservlet1015finaljar1015final at ioundertowservlethandlersservletinitialhandler1handlerequestservletinitialhandlerjava146 undertowservlet1015finaljar1015final at ioundertowserverconnectorsexecuteroothandlerconnectorsjava177 undertowcore1015finaljar1015final at ioundertowserverhttpserverexchange1runhttpserverexchangejava727 undertowcore1015finaljar1015final at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava1142 rtjar180 20 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava617 rtjar180 20 at javalangthreadrunthreadjava745 rtjar180 20here is my webxmlxml version10 encodingutf8webapp version31 xmlns xmlnsxsi xsischemalocation 3 1xsdwebapphere is the application classpackage comabcadminservicesconfigimport javaxwsrsapplicationpathimport javaxwsrscoreapplicationapplicationpathservicespublic class webconfig extends application here is the web service classpackage comabcadminserviceimport javaioserializableimport javaxwsrsgetimport javaxwsrspathimport javaxwsrsproducesimport javaxwsrscoremediatypeimport comabccommonswsentityuserwspojopathuserpublic class userresource implements serializable private static final long serialversionuid 6766329501327292893l get pathservicesusergetuser producesmediatypeapplication json public userwspojo getuserstring id userwspojo uwp new userwspojo uwpsetnameaayush uwpsetsurnamedevmurari return uwp now in the above mentioned class i also tried to change the path of path with getuser and also tried full path ie pathservicesusergetuser none of these are working everytime i get the same errorif you need to see anything else please let me know i will post it herethanks for reading and helpingps i have tried reading other questions on so documentation on resteasy none of this helped me much however i corrected my code while looking for the solutionbased on the answers i did this toopathuserpublic class userresource implements serializable private static final long serialversionuid 6766329501327292893l get pathgetuser producesmediatypeapplication json public userwspojo getuser userwspojo uwp new userwspojo uwpsetnameaayush uwpsetsurnamedevmurari return uwp other things are same as they are still i am getting the same error221558489 warn orgjbossresteasycoreexceptionhandler default task5 failed to execute javaxwsrsnotfoundexception could not find resource for full path httplocalhost8080adminwsservicesusergetusers at orgjbossresteasycoreregistryclassnodematchclassnodejava73 resteasyjaxrs308finaljar at orgjbossresteasycoreregistryrootclassnodematchrootclassnodejava48 resteasyjaxrs308finaljar at orgjbossresteasycoreresourcemethodregistrygetresourceinvokerresourcemethodregistryjava4 resteasyjaxrs308finaljar at orgjbossresteasycoresynchronousthispatchergetinvokersynchronousthispatcherjava234 resteasyjaxrs308finaljar at orgjbossresteasycoresynchronousthispatcherinvokesynchronousthispatcherjava171 resteasyjaxrs308finaljar at orgjbossresteasypluginsserverservletservletcontainerthispatcherserviceservletcontainerthispatcherjava220 resteasyjaxrs308finaljar at orgjbossresteasypluginsserverservlethttpservletthispatcherservicehttpservletthispatcherjava56 resteasyjaxrs308finaljar at orgjbossresteasypluginsserverservlethttpservletthispatcherservicehttpservletthispatcherjava51 resteasyjaxrs308finaljar at javaxservlethttphttpservletservicehttpservletjava790 jboservletapi 31 spec100finaljar100final at ioundertowservlethandlersservlethandlerhandlerequestservlethandlerjava85 undertowservlet1015finaljar1015final at ioundertowservlethandlerssecurityservletsecurityrolehandlerhandlerequestservletsecurityrolehandlerjava61 undertowservlet1015finaljar1015final at ioundertowservlethandlersservletthispatchinghandlerhandlerequestservletthispatchinghandlerjava36 undertowservlet1015finaljar1015final at orgwildflyextensionundertowsecuritysecuritycontextassociationhandlerhandlerequestsecuritycontextassociationhandlerjava78 at ioundertowserverhandlerspredicatehandlerhandlerequestpredicatehandlerjava25 undertowcore1015finaljar1015final at ioundertowservlethandlerssecuritysslinformationassociationhandlerhandlerequestsslinformationassociationhandlerjava113 undertowservlet1015finaljar1015final at ioundertowservlethandlerssecurityservletauthenticationcallhandlerhandlerequestservletauthenticationcallhandlerjava56 undertowservlet1015finaljar1015final at ioundertowserverhandlerspredicatehandlerhandlerequestpredicatehandlerjava25 undertowcore1015finaljar1015final at ioundertowsecurityhandlersabstractconfidentialityhandlerhandlerequestabstractconfidentialityhandlerjava45 undertowcore1015finaljar1015final at ioundertowservlethandlerssecurityservletconfidentialityconstrainthandlerhandlerequestservletconfidentialityconstrainthandlerjava61 undertowservlet1015finaljar1015final at ioundertowsecurityhandlersauthenticationmechanismshandlerhandlerequestauthenticationmechanismshandlerjava58 undertowcore1015finaljar1015final at ioundertowservlethandlerssecuritycachedauthenticatedsessionhandlerhandlerequestcachedauthenticatedsessionhandlerjava70 undertowservlet1015finaljar1015final at ioundertowsecurityhandlerssecurityinitialhandlerhandlerequestsecurityinitialhandlerjava76 undertowcore1015finaljar1015final at ioundertowserverhandlerspredicatehandlerhandlerequestpredicatehandlerjava25 undertowcore1015finaljar1015final at orgwildflyextensionundertowsecurityjaccjacontextidhandlerhandlerequestjacontextidhandlerjava61 at ioundertowserverhandlerspredicatehandlerhandlerequestpredicatehandlerjava25 undertowcore1015finaljar1015final at ioundertowserverhandlerspredicatehandlerhandlerequestpredicatehandlerjava25 undertowcore1015finaljar1015final at ioundertowservlethandlersservletinitialhandlerhandlefirstrequestservletinitialhandlerjava240 undertowservlet1015finaljar1015final at ioundertowservlethandlersservletinitialhandlerthispatchrequestservletinitialhandlerjava227 undertowservlet1015finaljar1015final at ioundertowservlethandlersservletinitialhandleraccess0servletinitialhandlerjava73 undertowservlet1015finaljar1015final at ioundertowservlethandlersservletinitialhandler1handlerequestservletinitialhandlerjava146 undertowservlet1015finaljar1015final at ioundertowserverconnectorsexecuteroothandlerconnectorsjava177 undertowcore1015finaljar1015final at ioundertowserverhttpserverexchange1runhttpserverexchangejava727 undertowcore1015finaljar1015final at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava1142 rtjar180 20 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava617 rtjar180 20 at javalangthreadrunthreadjava745 rtjar180 20,['java'] +809731,in c can i declare a reference so as to indicate that nothing will ever modify it if i dotypedef void cbint fooint const a cb cb int x a cb return x aand compile with g o3 savetemps c foocpp i see that the subtraction is preserved whereas if cb is commented out the entire function optimizes toxorl eax eaxis there something i can do to the specification of the parameter a so that the subtraction will be optimized out regardless of the call to cb and without forcing a to be a unique reference ie that it may be referred to elsewhere but that via none of those references will it be modified,['c++'] +809816,errorunable to locate adb within sdk in android studio does anyone know what this means i am kind of noobish to android when i click the run button on my simulator i get this messagethrowable unable to locate adb within sdki am running the latest version 0814edit i am using android studio,['android'] +809866,constexpr array of constexpr objects using move ctor i have a class with a constexpr value constructor but no copy or move ctorclass c public constexpr cint cconst c delete c operatorconst c deleteint main constexpr c arr 1 2i have found that this code does not work because it is actually trying to use the move constructor for c rather than the value constructor to construct in place one issue is that i want this object to be unmovable for test purposes but i thought okay fine i will add a move constructorclass c public constexpr cint cconst c delete c operatorconst c delete c operatorc delete cc something added assume this must be non trivialokay fine now it uses the move constructor and everything works under gcc but when i use clang it complains because the move constructor is not marked constexprerror constexpr variable arr must be initialized by a constant expression constexpr c arr 1 2if i mark the move constructor constexpr it works under gcc and clang but the issue is that i want to have code in the move constructor if it runs at all and constexpr constructors must have empty bodies the reason for my having code in the move ctor is not worth getting intoso who is right here my inclination is that clang would be correct for rejecting the codenoteit does compile with initializer lists and noncopyable nonmovable objects as belowclass c public constexpr cint cconst c delete c operatorconst c delete c operatorc delete cc deleteint main constexpr c arr 1 2my main concern is which compiler above is correct,['c++'] +809885,how do i apply the outputcache attribute on a method in a vnext project what is the correct way of using the following in a vnext application on an async methodoutputcachenostore true duration 0 varybyparam i see it is part of systemwebcaching but the only place i could add that would be in the aspnet50 frameworkassemblies section of my projectjson file which is incorrect,['asp.net'] +810096,reorder rows in bootstrap i have the following layout when viewing my page on a phoneabwhen the viewport is larger ie md i want to invert the two such asbai thought i could do this by thinking mobile first viadiv classrow div classcolxs12 colmd4first guydivdiv classcolxs12 colmd8 second guy div classcolxs12 colmdpush12adiv div classcolxs12 colmdpull12bdivdivrather it appears that this offsets the columns to the left and right outside of the container such as a b hard to illustrate here but rather than switching row positions since they are each size 12 they offset to the outside of their containing element which should be colmd8,"['html', 'css']" +810170,progress bar for long running server calls in aspnet mvc i just want to create a progress bar while long running server calls i could not create a ajax post request to the controller while the controller is doing a long running job i want to create an additional action to get the actual statement of current long running task i tried to create poll in ajax request then i can able to return the status from the server side and thisplay it in a client side progress bar any ideas,['asp.net'] +810265,how to config yii2 urlmanager rules with aliases and get parameter for my current advanced yii2based project i just need one controller sitecontroller so there is no need to show it in the url thats why i added this rule to the frontend configurlmanager rules array aliasproductcontactabout sitealias this is working fine and localhostproduct points to localhostsiteproductof course i activated prettyurl and added this default rules to the common config rules array controllerwidw controller controllerwactionwidw controlleraction controllerwactionw controlleraction now i want to access a get parameter like this localhostproductproductname but i get the error unable to resolve the request productbut localhostsiteproductproductname is working properlythe productname should be getid what do i have to change to make this happenthanks,['php'] +810320,why can i pass an instance method to multiprocessingprocess but not a multiprocessingpool i am trying to write an application that applies a function concurrently with a multiprocessingpool i would like this function to be an instance method so i can define it differently in different subclasses this does not seem to be possible as i have learned elsewhere apparently bound methods cannot be pickled so why does starting a multiprocessingprocess with a bound method as a target work the following codeimport multiprocessingdef test1 print hello world 1def incrementx return x 1class testclass def proceself process1 multiprocessingprocesstargettest1 process1start process1join process2 multiprocessingprocesstargetselftest2 process2start process2join def poolself pool multiprocessingpool1 for answer in poolimapincrement range10 print answer print for answer in poolimapselfsquare range10 print answer def test2self print hello world 2 def squareself x return x xdef main c testclass cprocess cpoolif name main mainproduces this outputhello world 1hello world 212345678910exception in thread thread2traceback most recent call last file cpython27libthreadingpy line 551 in bootstrap inner selfrun file cpython27libthreadingpy line 504 in run self targetself args self kwargs file cpython27libmultiprocessingpoolpy line 319 in handle tasks puttaskpicklingerror cannot pickle type instancemethod attribute lookup builtin instancemethod failedwhy can processes handle bound methods but not pools,['python'] +810325,angular validation ngmessage dont show required after submit and erase text this is my current validation set up for my formngmessages forsearchformerror ngifsearchformsubmitted ngmessage whenrequired classerrormessagethis search field is requiredngmessagengmessagesand my formform roleform ngsubmitsearchformvalid searchcode namesearchform novalidateit works finebut here is what i do not like this scenario1 hit enter on empty searchbox it shows the correct message field is required2 start typing and erase text without hitting enter it shows error message againit is the second scenario i dont wantany ideas,['javascript'] +810364,cannot use illuminateroutingcontroller as controller because the name is already in use i have been learning to use laravel watching larcasts and using the docs i came across a lesson where eloquent is being described but i am stuck with the error at handleexceptionsfatalexceptionfromerror array type 64 message cannot use illuminateroutingcontroller as controller because the name is already in use i am very confused and have now copied the examples provided exactly but i still get the error i am using laravel 5 so i do not know if there has been some undocumented change or if i am simply doing something wrong i have not found anything related in google searches that solve the issue so i was hoping someone here might be able to help here is the code that is producing the errorphp namespace apphttpcontrollersuse illuminateroutingcontrolleruse appvarnameclass varcontroller extends controller public function var variable varnameget ddvariable according to the documentation this should work and in the video that i watched it did work what am i missingi tried deleting the controller class since it seems to be whats causing the already in use error which broke everything reinstalled and tried to just use controller since it extends the eloquent model but now its sayingerrorexception in pluralizerphp line 258 call user func expects parameter 1 to be a valid callback function mb strtolower not found or invalid function namewhich is beyond my understanding of the inner workings of laravel i am stuck and i do not understand the problem according to documentation i do not see anything wrong with my code this seems like such a simple step all i am trying to do is retrieve info from a database what is going onthanks in advance for any help,['php'] +810399,how can i use the android keystore to securely store arbitrary strings i would like to be able securely store some sensitive strings in the android keystore i get the strings from the server but i have a use case which requires me to persist them keystore will only allow access from the same uid as that assigned to my app and it will encrypt the data with the device master password so it is my understanding that i do not have to do any additional encryption to protect my data my trouble is i am missing something about how to write the data the code i have below works perfectly as long as the call to keystorestorenull is omitted that code fails and as long as i cannot store the data after putting it to the keystore then i cannot persist iti think i am missing something about the keystore api but i do not know what any help appreciatedstring metakey oursecretkeystring encodedkey this is supposed to be a secretbyte encodedkeybytes new byteintencodedkeylengthencodedkeybytes encodedkeygetbytesutf8keystoreparameter ksp nullstring algorithm desstring algorithm desedesecretkeyfactory secretkeyfactory secretkeyfactorygetinstancealgorithmsecretkeyspec secretkeyspec new secretkeyspecencodedkeybytes algorithmsecretkey secretkey secretkeyfactorygeneratesecretsecretkeyspeckeystore keystore keystoregetinstancekeystoregetdefaulttypekeystoreloadnullkeystoresecretkeyentry secretkeyentry new keystoresecretkeyentrysecretkeykeystoresetentrymetakey secretkeyentry kspkeystorestorenullstring recoveredsecret if keystorecontainsaliasmetakey keystoresecretkeyentry recoveredentry keystoresecretkeyentrykeystoregetentrymetakey ksp byte bytes recoveredentrygetsecretkeygetencoded for byte b bytes recoveredsecret charb logvtag recovered recoveredsecret,['android'] +810440,how should a custom guice scope be integrated with testng we use a custom guice scope testscoped for some of our junit tests that lasts for a single test method and a junit rule to enter and exit the scope appropriately it looks like thispublic class myjunittest rule public customrule customrule new customrulemymoduleclass inject private thing thing test public void test1 use thing test public void test2 assuming thing is testscoped well have a new instance were starting to use testng for some of our tests in other projects and wed like to have a similar pattern so far weve come up with thislistenerscustomtestnglistenerclassguicemodules mymoduleclasspublic class mytestngtest inject private providerthing thingprovider test public void test1 thing thing thingproviderget use thing test public void test2 thing thing thingproviderget assuming thing is testscoped well have a new instance public class customtestnglistener implements ihookable override public void runihookcallback callback itestresult testresult testscopeinstanceenter try callbackruntestmethodtestresult finally testscopeinstanceexit there are a couple issues with this designunlike junit testng uses the same instance of the test class for each method that means we have to inject providerthing instead of just thing which is awkwardfor some reason customtestnglistener is running on all of our tests even ones that do not have that listenerscustomtestnglistenerclass annotation i have worked around this by explicitly checking for that annotation in the listener itself but it feels like a hack though i do see that mockitotestnglistener does the same thingdoes someone with more familiarity with testng have any suggestions for dealing with these issues,['java'] +810503,scrapy convert html string to htmlresponse object i have a raw html string that i want to convert to scrapy html response object so that i can use the selectors css and xpath similar to scrapys response how can i do it,['python'] +810504,bulk insert row terminator for unix file l row terminator so i have been wrestling a perplexing issue with bulk insert for some time the files come from a linux box and when i look at them in hex edit modenotepad they appear to have just a linefeed 0a as a row terminator i store bulk insert statements in a table which later a job selects from and executes the statement in the table to load data into a staging tablethe particular case that is perplexing to me is a table that has 7 columns the data file only has the first 4 columns the rest should be left null typically they look like thisbulk insert staging table from file location with datafiletype widechar fieldterminator rowterminator something here the row terminator has been the biggest source of my issueswhen i try to use n the bulk insert fails on an truncation error it seems to treat the file as one long string and only delimits the columns correctly until it runs out of columns hence truncation errorwhen i use 0x0a the bulk insert fails on unexpected end of file error there was a blank line at the end of the file but even when i removed that it still threw the same error so i am not sure what is wrong therethe only one so far that has worked for getting data actually into the table was l does anyone know what that means i have searched far and wide but there does not seem to be documentation on it that or i have been looking in the wrong place completelythe weird thing with l as the rowterminator is that even though it load successfully it still does not respect the rowterminator the rows just get loaded into all 7 columns and split on seemingly random intervalsanyone have any idea should i clarify some more,['sql'] +810508,thisable ssl client certificate on some webapi controllers edit for future readers unfortunately the bounty awarded answer does not work nothing i can do about that now but read my own answer below through testing confirmed to work with minimal code changeswe have an azure cloud service webrole that is entirely in aspnet webapi 22 no mvc front end is angular some of our controllersrest endpoints talk to a 3rd party cloud service over ssl client cert authmutual auth and the rest of the controllersendpoints talk to the html5angularjs front end also over ssl but more traditional server auth ssl we do not have any nonssl endpoint weve enabled client ssl via a cloud service startup task likeif not defined appcmd set appcmdsystemrootsystem32inetsrvappcmdexeappcmd unlock config sectionsystemwebserversecurityaccessissue that setting is sitewide so even when users hit the first page say returns the indexhtml for angularjs their browser asks them for client ssl cert image belowif there a way to eitherlimit the client ssl certificate requests to just the webapi controllers that talk to the 3rd party cloud serviceorskip client ssl auth for our front end powering webapi controllersour servers webconfig is complex but the relevant snippet is belowsystemwebserver security access sslflagslnegotiatecert securitysystemwebserverand the screenshot of the client hitting a regular webapi endpoint yet attempting client ssl authentication happens in any browser chrome firefox or ie,['c#'] +810516,no valid apsenvironment entitlement string found for application on app store so i have this app called dripper that i put out about a month ago and then an update a couple days ago the update added push notifications and a few little tweaks i tested it with the sandboxapn using the development profile and things worked great then i switched things to the productionapn and pushed it to testflight again things worked perfectly once i put update on the market and ran it i noticed i wasnat getting any new push registrations on the server i looked at the console logs for the device and found thisdec 4 175515 inatouchit coffco1210 registering for remote notifications dec 4 175515 inatouchit springboard52 no valid apsenvironment entitlement string found for application dripper null notifications will not be delivered dec 4 175515 inatouchit coffco1210 warning failed to register with error error domainnscocoaerrordomain code30 no valid apsenvironment entitlement string found for application userinfo0x174270900 nslocalizeddescriptionno valid apsenvironment entitlement string found for applicationi am a bit confused because i thought that the productionapn would function the same between adhoc and app store builds here is my app id and its entitlements here is the provisioning profile for the apps store,"['ios', 'objective-c']" +810595,how can i compare pojos by their fields reflectively i am basically looking for a unit testing framework which i can use to compare pojos which do not override equals and hascode methods i had a look at junit test ng and mockito but they do not seem to solve the purposefor example consider the code below public class carbean private string brand private string color public carbean public carbean string brand string color thisbrand brand thiscolor color return the brand public string getbrand return brand param the brand to set public void setbrandstring brand thisbrand brand return the color public string getcolor return color param the color to set public void setcolorstring color thiscolor color the pojo carbean represents a real world car it has two parameters brand and color now suppose you have two car objects as below carbean car1 new carbeanfordblackcarbean car2 new carbeanfordblackboth the objects have same parameter values but when you compare this using equals it returns false car1equalscar2 this returns falsenow i need to unit test a method that returns carbean object in this scenario i would either need to compare the carbean attributes one by one or i would need to implement equals and hashcode methodsso my question is is there already a unit testing framework which can handle this,['java'] +810646,unable to choose appropriate method using java generics this program does not do what i wanted it prints sad twice whereas i was hoping it would print happy and then sadpublic class woof public static class arft t yap public arft yap thisyap yap public string woof should select which doyapstuff based on whether t happens to be an integer or something else return doyapstuffyap special case implementation of doyapstuff where t is integer public string doyapstuffinteger x return happy default implementation of doyapstuff where t is something else public string doyapstufft x return sad public static void mainstring args integer i 5 arfinteger arf1 new arfintegeri systemoutprintlnarf1woof should print happy string s foo arfstring arf2 new arfstrings systemoutprintlnarf2woof should print sad,['java'] +810710,how to add dividers between thisabled items in listview lollipop to add the dividers between thisabled items not clickable in listview for android previous to lollipop i override adapters method areallitemsenabled to return true but now in lollipop this method does not fix the problem the dividers are invisible in expandablelistview toois there a way to fix this problem without adding the divider in my item layout,['android'] +810769,how to know cast failed in mysql could somebody tell me how i can detect if a cast failed in mysql using cast function these two lines return the same value 0select castbanana as unsigned integer as cast1select cast0 as unsigned integer as cast2,['mysql'] +810797,how to create a birdeyeview of image to a given plane i am given a plane support vector and planes normal vector an image which was taken by a camera of which i know the intrinsic parameters fxfycxcy how do i obtain the transformation of this image to a birdeyeview like image so that birds view is collinear to the planes normal vector i am confused with the coordinate systems i have to use some matrices are in world coordinates and some in local i know that there is warpperspective in opencv would this do the job im using opencv 249thanks alot updatedo i have to calculate 4 points with the camera facing normal then 4 points from the bird eye view and pass them to findhomography to obtain the transformation matrixupdatesolved got it to work,['c++'] +810813,crossbrowser get keycode i am trying to get a crossbrowser way to listen to keycode of users keydown for mobile browsers i have to trigger the virtual keyboard so i use an input hidden by css triggered with a click event this works well except that when i try to listen to keycode on fennec mobile firefox i have got strange behavior here is the function i use to listen to keycode documentqueryselectorallinput0addeventlistenerkeydown handlerfunction handlere epreventdefault var k ewhich ewhich ekeycode documentgetelementbyidloginnerhtml k thisstylebackgroundcolor ffaaffinput typetext span idlogspanin firefox for android v34 to v37 it would not fire until the usertyped returnaactually i found that if the value of the input is notempty it works well at least on load so i thought of aworkaround like this one ifthisvaluethisvalue seems to work but if you spam it the backspacea is not blocked so when the input is cleared the bugcomes back the workaround does not fire eitherthis a ugly workaround which i am sure will create other bugs in other browsers documentqueryselectorallinput0addeventlistenerkeydown handler function handlere ifthisvaluethisvalue epreventdefault var k ewhich ewhich ekeycode documentgetelementbyidloginnerhtml k thisstylebackgroundcolor ffaaff input typetext value span idlogspan in b2g firefox os 13 on device or 20 emulated the behavior iseven odderthe function only reads keycode for backspaceakeycode 8 or returnakeycode13 keys any other key will return 0so my question is do you know a better cross browser way to listen to keycode a one working in all major browsers desktop or mobile and on fennecps even if i write my app in vanillajs it is ok for me to see solutions with any library,"['javascript', 'android', 'html']" +810900,surprising inttostring output i have been working on a project and found an interesting problem2tostringte0 output te02tostringtr0 output tr002i also have tried with several strings other than te but all have the same correct outputout of curiosity i am wondering how come this could have happened,['c#'] +811032,column size and row size of a 2d vector in c i have a vector like this vector vectorint myvectorall row and column numbers are same in this vectori want to find row count and column count of this vectorfor row count i come up with myvector0sizefor column count i cannot come up with anything can you tell me if my row count is correct and can you tell me how i can get column count thanks,['c++'] +811055,javascript primitive vs reference types in the below code we are passing an object so according to javascript we are passing a reference and manipulatingvar a new number10xaalertafunction xn n and 2but 10 is alerted instead of 12 why,['javascript'] +811085,testing ruby modules with rspec i am having a bad time finding on sogoogle this particular case i have a module with functions and in order to use them you have to create a class which includesextends the module depending if youll want instance methods or class methodsmodule a def say hello name hello name end def say bye bye endendhow can i test this module using rspeci have something like this and i am not sure where is the point i should create the class and extend moduledescribe a do class myclass extend a end beforeeach name radu describe say hello do it should greet a name do expectmyclasay hellonameto eq hello radu end endendthank you,['ruby'] +811201,double to int implicit conversion in mingw32 i cannot explain the behaviour of the following program compiled with gcc on mingw 32 bits i am aware of the possible precision loss when implicitly converting from double to int but i would expect the two cases to give the same output since it is doing the exact same operations why are the two outputs differentinclude stdiohinclude mathhint main int table3 2 3 4 int i n and 0 and table0 pow100 0 and table1 pow100 1 and table2 pow100 2 printfdn n and 0 fori 0 i 3 i and tablei pow100 i printfdn n return 0output 4030240300,['c'] +811230,understanding exitreenter shared element transitions i am doing some rudimentary exploration of shared element transitions in android l the simple example i have setup has an image view translating from the top of the screen to the bottom of the screen during activity transitions and i have extended the transition duration so i can see things working i have hit two problems so far trying to understand how shared element transitions works 1when using only enterreturn transitions exitreenter set to null the enter transition is fine but when the back button is pressed the view animates for a time stops then reappear in the final position seems similar to this question but i have set all the existreenter transitions to null so not sure why it happens2when using only exitreenter transitions enterreturn set to null nothing is happening the view transitions down the screen like its following a default enter transition 300ms duration and when back is pressed the view pops back to its original positionhow do i use exitreenter transitionshere is my codeactivity mainxmlrelativelayout xmlnsandroid xmlnstools androidlayout widthmatch parent androidlayout heightmatch parent androidpaddingleftdimenactivity horizontal margin androidpaddingrightdimenactivity horizontal margin androidpaddingtopdimenactivity vertical margin androidpaddingbottomdimenactivity vertical margin toolscontextmainactivity imageview androidlayout widthwrap content androidlayout heightwrap content androidididimageview androidsrcdrawableic launcher androidlayout alignparenttoptrue androidlayout centerhorizontaltrue button androidlayout widthwrap content androidlayout heightwrap content androidtextanimate androidididbutton androidlayout centerverticaltrue androidlayout alignparentstarttrue relativelayoutactivity secondxmlimageview androidlayout widthwrap content androidlayout heightwrap content androidididimageview2 androidsrcdrawableic launcher androidlayout alignparentbottomtrue androidlayout centerhorizontaltrue mainactivityjavapublic class mainactivity extends activity override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate getwindowrequestfeaturewindowfeature content transitions getwindowrequestfeaturewindowfeature activity transitions getwindowsetallowentertransitionoverlapfalse getwindowsetallowreturntransitionoverlapfalse getwindowsetsharedelementexittransitionexittransition getwindowsetsharedelementreentertransitionreentertransition getwindowsetsharedelementexittransitionnull getwindowsetsharedelementreentertransitionnull setcontentviewrlayoutactivity main final view iview findviewbyidridimageview iviewsettransitionnameimage final button button buttonfindviewbyidridbutton buttonsetonclicklistenernew viewonclicklistener override public void onclickview v intent intent new intentmainactivitythis secondactivityclass activityoptions options activityoptions makescenetransitionanimationmainactivitythis iview image startactivityintent optionstobundle private transition exittransition changebounds bounds new changebounds boundssetinterpolatornew bounceinterpolator boundssetduration20 return bounds private transition reentertransition changebounds bounds new changebounds boundssetinterpolatornew overshootinterpolator boundssetduration20 return bounds secondactivityjavapublic class secondactivity extends activity override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate getwindowrequestfeaturewindowfeature content transitions getwindowrequestfeaturewindowfeature activity transitions getwindowsetallowentertransitionoverlapfalse getwindowsetallowreturntransitionoverlapfalse getwindowsetsharedelemententertransitionentertransition getwindowsetsharedelementreturntransitionreturntransition getwindowsetsharedelemententertransitionnull getwindowsetsharedelementreturntransitionnull setcontentviewrlayoutactivity second final view iview findviewbyidridimageview2 iviewsettransitionnameimage override public void onbackpressed superonbackpressed finishaftertransition private transition entertransition changebounds bounds new changebounds boundssetduration20 return bounds private transition returntransition changebounds bounds new changebounds boundssetinterpolatornew decelerateinterpolator boundssetduration20 return bounds,['android'] +811345,when i update my game in itunes connect will the leaderboards carry over if i update my game in itunes connect will the leaderboards and achievements carry overi have left everything related to game center the same in the new update but itunes connect says you do not have any new leaderboards for this appjust wondering if i need to make and integrate a new leaderboard for the update,['ios'] +811540,how to remove relationship in neo4jrb 30 i have two modelsclass topic include neo4jactivenode has many in favorited by model class user origin favorite topicsendandclass user include neo4jactivenode has many out favorite topics model class topic type favorited byendhow i can remove only association irbmain0080 topicfirstfavorited bydeleteuserfirstnomethoderror undefined method delete for neo4jactivenodequeryqueryproxy0x04b27f10thank you,['ruby-on-rails'] +811698,is there a list implementation that would allow gaps i am looking for a collection that would be some sort of a list that allows gaps the objectives areevery element has some index in the collection that is meaningfulthe collection is to be sparse and not continuous its size should return the number of proper elements hence the workaround of initializing with null wouldnt worksublist method is desirable to access sublists according to index intervalssample use caselistinteger list listadd05listadd14listadd53for integer i list systemoutprint i desired output 5 4 3,['java'] +811772,can i use updated when extending a firebase factory to run a gettotal function like in the example can i receive what is returned by updated or have updated run a function that i can then receive from every time a task is checked off at the end of the day i need to keep a count of how many tasks users complete it seems like firebase has ways of automatically syncing that data but it is unclear how to do that specifically i have run into problems with watch and running functions when a task is completed this looks like an interesting way of doing it but i cannot put the pieces together here is working plnkr of the code below code goes hereangularmoduleapp firebaseangular moduleapp controllermain functionscope firebase timeout window listwithtotal var ref new firebase scopelistwithtotal listwithtotalref scopeaddtask functiontask scopelistwithtotaladd title tasktitle complete false tally 0 tasktitle scopecompletetask functiontask if taskcomplete true taskcomplete true tasktally 1 else taskcomplete false tasktally 0 scopelistwithtotalsavetask scopetallycount it would be cool if i can get tallycount to receive the result of gettotal or automagically with updated factorylistwithtotal firebasearray firebase functionfirebasearray firebase create a new factory based on firebasearray var totalfactory firebasearrayextendfactory gettotal function var total 0 angularforeachthislist functionrec total rectally return total updated function return thislistgettotal return functionlistref var sync firebaselistref arrayfactory totalfactory return syncasarray this will be an instance of totalfactory,['javascript'] +811779,javac junit gives error package orgjunit does not exist i am trying to use junit in a makefile but i cannot get it to work my folder structure is as follows makefile is in myprojectmyprojectbinmain org mypackagetest org mypackage libwhere main contains main files test contains test files and lib contains hamcrestcore13jar and junit412jarmy makefile is as followsjavac javacjvm javajavadoc javadocmkbin mkdir p binjavac flags g d binjavac cp cpsrc mainsrctest testlib libjarpackage orgmypackagejavatarget binmain orgmypackagemainsuffixes class javaall mkbin javac javac flags srcpackagetest mkbin javac javac cp lib srctestpackageclean rm rf targetrun jvm javac cp target mainphony all test cleanwhen i am running make test i get the followingmyproject 180729make testmkdir p bin javac cp libjar testorgmypackagejavatestorgmypackagemyclassjava3 error package orgjunit does not existimport static orgjunitassertin eclipse the tests work perfectly fine what am i doing wrong,['java'] +811876,getting nosuchfielderror instance orgapachehttpmessagebasicheadervalueparser i am working on an app on android i am using httpcore 433 i get this when i try to use contenttypeparsestringjavalangnosuchfielderror no static field instance of type lorgapachehttpmessagebasicheadervalueparser in class lorgapachehttpmessagebasicheadervalueparser or its superclasses declaration of orgapachehttpmessagebasicheadervalueparser appears in systemframeworkextjari have done some googling and i understand why i am getting the error but i am unsure how to fix it from what i have read it seems that contenttype tries to make use of the basicheadervalueparser that comes with android and that class does not have the instance field yet any help pleasethese are the relevant importscompileorgapachehttpcomponentshttpmime436 exclude module httpclientcompile orgapachehttpcomponentshttpcore433,['android'] +811935,should i use owincontexts environment to hold application specific data per request i need a way to store a logging object per request with httpcontext i would add this to the items dictionary i do not want to bring httpcontext into this if i can help itthe below code is what i propose for a unity lifetimemanager that will store objects in owincontexts environment property which i have access to with my owin middlewarepublic class owincontextlifetimemanager lifetimemanager private string key new guidtostring private idictionarystring object environment public owincontextlifetimemanageridictionarystring object environment thisenvironment environment public override object getvalue if environment null environmentcontainskeykey return environmentkey else return null public override void removevalue if environment null environmentremovekey public override void setvalueobject newvalue if environment null environmentkey newvalue then i can use it like this from my middlewarecontainerregistertypeirequestlog requestlognew owincontextlifetimemanagerenvironmentit occurs to me that i can choose whatever key i want except those that already are reserved by owinis there any reason i should not be using the owincontextenvironment for this purpose the msdn documentation is vague on the best practices of thisdarrel millers response here how should i store per request data when using owin to selfhost aspnet web api leads me to believe the properties collection on the request object is the way to go how can i access this object from middleware,"['c#', 'asp.net']" +812074,what is error in connection block invoke 2 connection interrupted in ios i am tried to make ios application using afnetworking in uitableview tableview loads 20 datas like twitters timelinewhen it loads over 80 datas xcode shows spending about 70mb memory and console shows received memory warninganderror in connection block invoke 2 connection interruptedwhat is this and how do i treat this error,"['ios', 'objective-c']" +812145,ibdesignable error ib designables failed to update auto layout status interface builder cocoa touch tool crashed i have a very simple subclass of uitextview that adds the placeholder functionality that you can find native to the text field object here is my code for the subclassimport uikitimport foundationibdesignable class placeholdertextview uitextview uitextviewdelegate ibinspectable var placeholder string didset setplaceholdertext private let placeholdercolor uicolor uicolorlightgraycolor private var textcolorcache uicolor override initframe cgrect superinitframe frame selfdelegate self required initcoder adecoder nscoder superinitcoder adecoder selfdelegate self func textviewdidbegineditingtextview uitextview if textviewtext placeholder textviewtext textviewtextcolor textcolorcache func textviewdidendeditingtextview uitextview if textviewtext placeholder setplaceholdertext func setplaceholdertext if placeholder if textcolorcache nil textcolorcache selftextcolor selftextcolor placeholdercolor selftext placeholder after changing the class for the uitextview object in the identity inspector to placeholdertextview i can set the placeholder property just fine in the attribute inspector the code works great when running the app but does not thisplay the placeholder text in the interface builder i also get the following nonblocking errors i assume this is why it is not rendering at design timeerror ib designables failed to update auto layout status interface builder cocoa touch tool crashederror ib designables failed to render instance of placeholdertextview rendering the view took longer than 200 ms your drawing code may suffer from slow performancei am not able to figure out what is causing these errors the second error does not make any sense as i am not even overriding drawrect any ideas,['ios'] +812192,all exeption break point is stoping for no reason on simulator this is very annoying every time i am trying to debug on the simulator with all exception break point app stops for no reason on this linereturn uiapplicationmainargc argv nil nsstringfromclastappdelegate classdid any one else found him self struggling with this issue thankseditback trace on first throw thread 1 tid 0x1d96b 0x36fbf540 libcabidylib cxa throw queue comapplemainthread stop reason breakpoint 32 frame 0 0x36fbf540 libcabidylib cxa throw frame 1 0x306975cc libfontparserdylibtfiledescriptorcontexttfiledescriptorcontextchar const 112 frame 2 0x306973d8 libfontparserdylibtfiledatareferencetfiledatareferencechar const 164 frame 3 0x306971fc libfontparserdylibtfiledatasurrogatetfiledatasurrogatechar const bool 188 frame 4 0x30695a libfontparserdylibtfontcreatefontentitiesforfilechar const bool tsimplearraytfont bool short char const 1402 frame 5 0x30694a80 libfontparserdylibfpfontcreatefontswithpath 224 frame 6 0x2a5032bc libcgxtypeadylibcreate private data with path 12 frame 7 0x2a3ca3c4 coregraphicscgfontcreatefontswithpath 24 frame 8 0x2a4855d6 coregraphicscgfontcreatefontswithurl 310 frame 9 0x313dfee4 graphicsservicesaddfontsfromurlorpath 68 frame 10 0x313e39de graphicsservices initialize block invoke 934 frame 11 0x0121fabe libthispatchdylib thispatch client callout 22 frame 12 0x01220750 libthispatchdylibthispatch once f 100 frame 13 0x313df72c graphicsservicesinitialize 196 frame 14 0x377944c4 libobjcadylib class initialize 536 frame 15 0x3779a046 libobjcadyliblookupimporforward 254 frame 16 0x37799f3e libobjcadylib class lookupmethodandloadcache3 34 frame 17 0x377a01f8 libobjcadylib objc msgsend uncached 24 frame 18 0x2d673b6e uikituistatusbarnewuiforegroundstyleattributes maketextfontforstyle 78 frame 19 0x2d634d94 uikituistatusbarforegroundstyleattributes textfontforstyle 104 frame 20 0x2d5e767e uikituistatusbarserviceitemview updateforcontenttypeservicestringservicecrossfadestringmaxwidthactions 390 frame 21 0x2d5e74ee uikituistatusbarserviceitemview updatefornewdataactions 186 frame 22 0x2d6428d0 uikituistatusbaritemview initwithitemdataactionsstyle 324 frame 23 0x2d642568 uikituistatusbarlayoutmanager createviewforitemwithdataactions 108 frame 24 0x2d5e6f74 uikituistatusbarlayoutmanager prepareenableditemtypewithenableditemswithdataactionsitemappearingitemthisappearing 264 frame 25 0x2d5e6e22 uikituistatusbarlayoutmanager prepareenableditemswithdataactions 74 frame 26 0x2d5e6c72 uikituistatusbarforegroundview setstatusbardataactionsanimated 162 frame 27 0x2d5e6b96 uikituistatusbarforegroundview setstatusbardataactionsanimated 710 frame 28 0x2d671ebe uikit 44uistatusbar preparetosetstyleanimation block invoke 358 frame 29 0x2d5fc230 uikituiviewanimation performwithoutanimation 72 frame 30 0x2d66fcf4 uikituistatusbar preparetosetstyleanimation 688 frame 31 0x2d6579ca uikituistatusbar requeststyleattributesanimationparameters 290 frame 32 0x2d65696e uikituistatusbar requeststyleanimated 86 frame 33 0x2d659a uikituiapplication createstatusbarwithrequestedstyleorientationhidden 406 frame 34 0x2d85122a uikituiapplication runwithmainscenetransitioncontextcompletion 970 frame 35 0x2d85bc68 uikit 84uiapplication handleapplicationactivationwithscenetransitioncontextcompletion block invoke 36 frame 36 0x2d84fc5a uikituiapplication workspacedidendtransaction 130 frame 37 0x3086c0e0 frontboardservices 31fbsserialqueue performasync block invoke 12 frame 38 0x2a13782c corefoundation cfrunloop is calling out to a block 12 frame 39 0x2a136af0 corefoundation cfrunloopdoblocks 216 frame 40 0x2a13564a corefoundation cfrunlooprun 1714 frame 41 0x2a082db0 corefoundationcfrunlooprunspecific 476 frame 42 0x2a082bc2 corefoundationcfrunloopruninmode 106 frame 43 0x2d653c36 uikituiapplication run 558 frame 44 0x2d64ea30 uikituiapplicationmain 1440 frame 45 0x003b4ec2 stoxmainargc1 argv0x01200b08 178 at mainm17third thread 1 tid 0x1d96b 0x36fbf540 libcabidylib cxa throw queue comapplemainthread stop reason breakpoint 32 frame 0 0x36fbf540 libcabidylib cxa throw frame 1 0x30798c22 libtruetypescalerdylibscalernewblockmemorycontext long long void unsigned char unsigned char 430 frame 2 0x3077e172 libtruetypescalerdyliboutlinetopathmemorycontext fnt elementtype const 178 frame 3 0x3079502a libtruetypescalerdylibobtaindesiredoutlinememorycontext fnt elementtype const unsigned long void 10 frame 4 0x3077e07c libtruetypescalerdylibrenderpathfsg splinekey memorycontext scalerglyph const 36 frame 5 0x3077c980 libtruetypescalerdylibttrenderglyphs 436 frame 6 0x306c5722 libfontparserdylibtconcretefontscalercopyglyphpathunsigned short cgaffinetransform const const 378 frame 7 0x306a0ce6 libfontparserdylibfpfontcopyglyphpath 494 frame 8 0x2a3abb4a coregraphicscgfontcreateglyphpath 30 frame 9 0x2a3aba56 coregraphicscgfontcreateglyphbitmap 266 frame 10 0x2a3b3c1a coregraphicscgglyphbuildercreate missing bitmapscgglyphidentifier const unsigned long cgglyphbitmap const 82 frame 11 0x2a6fd4dc libripadylibrender glyphs 172 frame 12 0x2a6fcaca libripadylibdraw glyph bitmaps 906 frame 13 0x2a6fc430 libripadylibripc drawglyphs 1108 frame 14 0x2a3a1002 coregraphicsdraw glyphs 274 frame 15 0x2ae268 coretextdrawsbixglyphsatpositionstfont const cgfont tcfref cfdata const const unsigned short const cgpoint const unsigned long cgcontext cgaffinetransform cgaffinetransform 1880 frame 16 0x2aa6bcce coretextctfontdrawglyphswithadvances 470 frame 17 0x349eba1a uifoundation nsstringdrawingengine 6710 frame 18 0x349efa64 uifoundationnsattributedstringnsextendedstringdrawing drawwithrectoptionscontext 532 frame 19 0x2d603370 uikituilabel drawtextinrectbaselinecalculationonly 40 frame 20 0x2d668ed4 uikituilabel drawtextinrect 488 frame 21 0x2d668ce8 uikituilabel drawrect 84 frame 22 0x2d668c70 uikituiviewcalayerdelegate drawlayerincontext 400 frame 23 0x2d045910 quartzcorecalayer drawincontext 228 frame 24 0x2d02f350 quartzcorecabackingstoreupdate 2068 frame 25 0x2d110b6c quartzcore zn2ca5layer8thisplay ev block invoke 52 frame 26 0x2d02eb34 quartzcorex blame allocations 88 frame 27 0x2d02e7e4 quartzcorecalayerthisplay 1156 frame 28 0x2d012d9c quartzcorecalayerthisplay if neededcatransaction 200 frame 29 0x2d012a60 quartzcorecalayerlayout and thisplay if neededcatransaction 24 frame 30 0x2d012446 quartzcorecacontextcommit transactioncatransaction 2 frame 31 0x2d012250 quartzcorecatransactioncommit 324 frame 32 0x2d5e51c8 uikit aftercacommithandler 132 frame 33 0x2a137844 corefoundation cfrunloop is calling out to an observer callback function 20 frame 34 0x2a134f28 corefoundation cfrunloopdoobservers 276 frame 35 0x2a13532a corefoundation cfrunlooprun 914 frame 36 0x2a082db0 corefoundationcfrunlooprunspecific 476 frame 37 0x2a082bc2 corefoundationcfrunloopruninmode 106 frame 38 0x313e7050 graphicsservicesgseventrunmodal 136 frame 39 0x2d64ea30 uikituiapplicationmain 1440 frame 40 0x003b4ec2 stoxmainargc1 argv0x01200b08 178 at mainm17,['objective-c'] +812248,after update of as to 10 getting method id not in 0 0xf 65536 error in project i updated android studio to the latest version and let it fix the project and the like but now my project does not compile gives me failedfailure build failed with an exception what went wrongexecution failed for task appdexdebug comandroididecommoninternalloggederrorexception failed to run command dvgaandroidstudiosdkbuildtools21dxbat dex nooptimize output dvgaprojectssalesappandroidprojectsvnandroidappbuildintermediatesdexdebug inputlistdvgaprojectssalesappandroidprojectsvnandroidappbuildintermediatestmpdexdebuginputlisttxterror code 2output unexpected toplevel exception comandroiddexdexindexoverflowexception method id not in 0 0xf 65536 at comandroiddxmergedexmerger6updateindexdexmergerjava502 at comandroiddxmergedexmergeridmergermergesorteddexmergerjava277 at comandroiddxmergedexmergermergemethodidsdexmergerjava491 at comandroiddxmergedexmergermergedexesdexmergerjava168 at comandroiddxmergedexmergermergedexmergerjava189 at comandroiddxcommanddexermainmergelibrarydexbuffersmainjava454 at comandroiddxcommanddexermainrunmonodexmainjava302 at comandroiddxcommanddexermainrunmainjava245 at comandroiddxcommanddexermainmainmainjava214 at comandroiddxcommandmainmainmainjava106however this is not resolved by just multidexing because when i added thisdefaultconfig multidexenabled truethis happensdvgaandroidstudiosdkbuildtools21dxbat dex nooptimize multidex maindexlist dvgaprojectssalesappandroidprojectsvnandroidappbuildintermediatesmultidexdebugmaindexlisttxt output dvgaprojectssalesappandroidprojectsvnandroidappbuildintermediatesdexdebug inputlistdvgaprojectssalesappandroidprojectsvnandroidappbuildintermediatestmpdexdebuginputlisttxterror code 3outputunexpected toplevel errorjavalangoutofmemoryerror gc overhead limit exceeded at comandroiddxcfcodeconcretemethodmakesourceposistionconcretemethodjava254 at comandroiddxcfcoderoppermachinerunroppermachinejava306 at comandroiddxcfcodesimulatorsimvisitorvisitlocalsimulatorjava612 at comandroiddxcfcodebytecodearrayparseinstructionbytecodearrayjava367 at comandroiddxcfcodesimulatorsimulatesimulatorjava94 at comandroiddxcfcoderopperprocessblockropperjava787 at comandroiddxcfcoderopperdoitropperjava742 at comandroiddxcfcoderopperconvertropperjava349 at comandroiddxdexcfcftranslatorprocessmethodscftranslatorjava280 at comandroiddxdexcfcftranslatortranslate0cftranslatorjava137 at comandroiddxdexcfcftranslatortranslatecftranslatorjava93 at comandroiddxcommanddexermainprocessclassmainjava729 at comandroiddxcommanddexermainprocessfilebytesmainjava673 at comandroiddxcommanddexermainaccess300mainjava82 at comandroiddxcommanddexermain1processfilebytesmainjava602 at comandroiddxcfdirectclasspathopenerprocessarchiveclasspathopenerjava284 at comandroiddxcfdirectclasspathopenerprocessoneclasspathopenerjava166 at comandroiddxcfdirectclasspathopenerprocessclasspathopenerjava144 at comandroiddxcommanddexermainprocessonemainjava632 at comandroiddxcommanddexermainprocessallfilesmainjava505 at comandroiddxcommanddexermainrunmultidexmainjava332 at comandroiddxcommanddexermainrunmainjava243 at comandroiddxcommanddexermainmainmainjava214 at comandroiddxcommandmainmainmainjava106i tried changing the build tools to latestandroid compilesdkversion 21 buildtoolsversion 21because by default it changed to 20 which seemed to use the sdk for 44w but this did not fix my problemdoes anyone know what could be wrong hereeditchanging the build tools or the compile sdk did not fix the problemturning the app into a multidex project and also adding the followingandroid compilesdkversion 21 buildtoolsversion 21 defaultconfig multidexenabled true dexoptions incremental true javamaxheapsize 4g fixed the build process however this still seems to be just a treatment but not a fix to the problemi am not sure if this is related but this is my dependency listdependencies compile filetreedir libs include jar compile comandroidsupportmultidex100 compile comandroidsupportappcompatv72102 compile comsquareupotto135 compile comsquareuppicassopicasso240 compile comsquareupretrofitretrofit171 compile comjakewhartonbutterknife600 compile commadgagspongycastlecore15100 compile commadgagspongycastleprov15100 compile commadgagspongycastlepkix15100 compile comgooglecodegsongson23 compile commonsiocommonsio24 compile orgapachehttpcomponentshttpclientandroid435 compile comsquareupdaggerdagger122 compile comsquareupdaggerdaggercompiler122 compilecomgooglecodejsonsimplejsonsimple1 exclude module junit compile comgoogleandroidgmsplayservices6587the only new dependency since then has been the last line which i added as per so i do not think that is the source of the problemedit2yes it was the source of the problem as i needed google cloud messaging i replaced that dependency with the base as per compile comgoogleandroidgmsplayservicesbase6587and it fixed the problem thank you for the helpedit3as of play services 700 the gcm is incompile comgoogleandroidgmsplayservicesgcm700edit4play services updated to 730please keep check of the latest version here,['android'] +812272,what is the equivalent listviewsetselection in case of recycler view in case of a listview if we want to make a particular item selected we use setselection method how do we do this in case of recycler view,['android'] +812299,scope of eval function in python consider the following examplei7j8k10def test i1 j2 k3 return dictnameevalname for name in ijkit returns testi 7 k 10 j 8why eval does not take into consideration the variables defined inside the function from the documentation optionally you can pass a globals and a locals dictionary what does it meansfinally how can i modify this small case to make it work,['python'] +812368,xcode items greyed out in the document outline i have been using icloud to sync xcode projects i am working on from my laptop to my desktop it does not seem to work that well unfortunately i opened up a project today on the desktop that i worked on the laptop yesterdayif i open the file on the desktop certain buttons and labels in the storyboard are missing looking at the document ouline i can see these but they are greyed out see pic however when i when i build the file they appear as normal in the simulator any idea why or how to get them showing up normally if i open this up on the laptop these are not greyed out and all looks normal,['ios'] +812383,php built in server and htaccess mod rewrites does phps built in server not make use of htaccess makes sense i suppose as it is not relying upon apache anyway is it possible to tell the server to make use of these files can it handle url rewrites i have some porjects in frameworks that rely upon these filesapplication envdevelopment php s localhost80 t public,['php'] +812797,make imageview fit width of cardview i have a cardview with rounded corners i want to have an imageview at the top like shown in the example taken from the material design guidelines belowandroidsupportv7widgetcardview xmlnscard view androidididcard view androidlayout widthwrap content androidlayout heightwrap content card viewcardcornerradius4dp androidsupportv7widgetcardviewthen inside the cardview i have this imageviewimageview androidididimageview androidlayout widthfill parent androidlayout height150dp androidlayout alignparentlefttrue androidlayout alignparentstarttrue androidlayout alignparenttoptrue androidscaletypecentercrop androidsrcdrawabledefault cover if i have the card viewcardcornerradius set to 0dp then the imageview fits the card like how i want it tohowever the material design guidelines state that cards should have rounded corners and not square cornersthe problem i have is when i set the card viewcardcornerradius to something other than 0dp eg 4dp then the following happensas can be seen the imageview does not fit into the cardviewmy question is how can i make this imageview fit to the layout of the cardview when it has rounded corners,['android'] +812814,fatal error call to a member function bind param on boolean so i am busy on a function that gets settings from a db and suddenly i ran into this errorfatal error call to a member function bind param on boolean in cxampp2htdocsapplicationclassesclassfunctionsphp on line 16normally this would mean that i am selecting stuff from unexisting tables and stuff but in this case i m notheres the getsetting functionpublic function getsettingsetting query thisdbconnprepareselect value param from ws settings where name querybind params setting queryexecute querybind resultvalue param querystore result if querynum rows 0 while queryfetch return value if param 1 thistplcreateparametersetting value else invalidsettingrequest setting the thisdb variable is passed through a constructor in case of need here is itpublic function constructdb data tpl thisdb db thistpl tpl thisdata data thisdatasetdataglobal theme thisgetsettingthemealso since i am making use of a database my database connectionclass database private data public function constructdata thisdata data thisconn new mysqli thisdatagetdatadatabase hostname thisdatagetdatadatabase username thisdatagetdatadatabase password thisdatagetdatadatabase database if thisconnerrno faileddbconnection thisconnerrno date default timezone seteuropeamsterdami have already tested the connection 100 positive that it works as intendedi am setting the db connection things in a configuration filedatabase array hostname 127001 username root password database wscriptnow the weird thing is the table exists the requested setting exists the db exists but still that error would not leave heres some proof that the db is correcti am sorry for the long post,"['php', 'mysql']" +812870,why is there no operator for stdunique ptr utilsmartptrsharedio in the c11 standard mandates an operator forshared ptrstemplateclass e class t class ybasic ostreame t operator basic ostreame t os shared ptry const phowever unless i am missing it i see nothing similar in uniqueptr and thereference on encppreferencecom agrees is there a reason for thedifference,['c++'] +812874,google plus login apple now rejecting flip to safari i have an app on the app store search for mths that uses google loginthe login feature was accepted in aug 2014i submitted a bug fix in dec 2014 and apple rejected it for flipping over to safari to loginwe found the following issues with the user interface of your appthe app opens a web page in mobile safari for creating an account or logging in then returns the user to the app the user should be able to create an account or log in without opening safari firstis there a way to implement google login and not have the flip to safarii have seen it in other apps,['ios'] +812920,validate soap requests against schema in a jaxws codefirst approach i created a jaxws webservice using jaxb annotations on some request fields to make them mandatoryxmlelementrequired trueprotected string numberthe wsdl generated by cxfjava2wsplugin is correct there is no minoccurs0 on the fields xselement namenumber typexsstringbut when the service receives a request that does not respect these constraints missing fields no soapfault or exception is throwni also tried adding schemavalidation to my ws class with no effecthow request validation against schmema or rather validation against annotationbased constraints can be automated,['java'] +813079,thread safe collection with upper bound i am after a collection with the following propertiesthreadsafe it will be used in aspnet and multiple clients could try to add remove and access members concurrentlymax elements i want to be able to set an upper bound a maximum number of elements at construction timetryadd a method that works the same as blockingcollectionttryaddt would be perfect ie it would return false if the maximum number of elements has been reacheddictionarylike in most other respects a concurrentdictionary would be perfect ie ability to identify elements by a key remove any item not just the first or last which i think would be the limitation with blockingcollectionbefore i attempt to roll my own my questions arehave i missed a built in type that would put a safe ceiling on the number of elements in a collectionis there a way to achieve this functionality with blockingcollection somehowfinally if i do need to try and make my own what approach should i think about is it as simple as a wrapped dictionary with locksexample usea chat room with a defined limit on number of participants could store the connection information of participants and reject new entrants until there is room to enter when full,"['c#', '.net']" +813122,typescript she is gotta have it where it global scope i am converting an angular app to use typescript but this is a general typescript question not about angularthe angular js files are along the linesfunction var app angularmodulemymodule appcontrollermycontroller scope function scope scopemynewproperty bob and i have converted that to lovely typescript class syntaxclass mycontroller constructorscope scopemynewproperty bob angularmodulemymodule controllermycontroller mycontrollerall works fine except the generated js is not wrapped according to the js module pattern ie in an outer anonymous functionvar mycontroller function appcontrollermycontroller scope function scope scopemynewproperty bob var app angularmodulemymodule so mycontroller is now global if i put the class in a typescript module then the js generates with the module name as a global variablevar tsmodulefunction tsmodule var mycontroller function appcontrollermycontroller scope function scope scopemynewproperty bob var app angularmodulemymodule tsmodule tsmodule how do i stop typescript polluting the global scope in this way i just want it all wrapped in a nice local scopei have seen it said elsewhere just go back to the old js syntax ie no typescript classhow can i define an angularjs service using a typescript class that doesnt pollute the global scopebut the whole point of us using typescript is the class syntax is typescript at odds with any sensible js programmer who knows not to go global,['javascript'] +813174,visual vm thread states can someone please explain me the difference between sleeping wait park and monitor thread states in visual vmthis is what i have foundrunning thread is still running sleeping thread is sleeping method yield was called on the thread objectwait thread was blocked by a mutex or a barrier and is waiting for another thread to release the lockpark parked threads are suspended until they are given a permit unparking a thread is usually done by calling method unpark on the thread objectmonitor threads are waiting on a condition to become true to resume executionwhat i am unable to understand is the state park what actually suspends the thread how do i detect in the code what has made the thread suspend its executioncan someone please guide me in this regardthanks,['java'] +813219,programmatically setting tabbaritem title in swift i have four uiviewcontrollers that are linked to a uitabbarcontrollers tab bar i need to set the tab bar item titles outside of the storyboard and inside of their classesi have triedclass myviewcontroller uiviewcontroller required initcoder adecoder nscoder superinitcoder adecoder selftitle nslocalizedstringmyconstantsstringkeystabname tablename constantsstringsmytable comment constantsemptystring this is called but the title is never set same with selftabbaritemtitle the titlei have also tried setting the title in viewdidload but that only updates the title after going to the view controllerthoughts,['ios'] +813401,how to create a dynamic linq select projection function from a string of names using cis there any way to specify property names for a projection function on a linq select method from an array public class album public int id get set public string name get set public short rate get set public string genre get set public short tracks get set public class class1 private void somet example of source var names new id name tracks var query mydatacontext gettablet asqueryable select dynamic projection from names array something like selectx new xid xname xtracks goanddosomethingwithquery could this be done without systemlinqdynamic,['c#'] +813727,alternate to array column i have used array column in a project and after uploading i found out that only php 55 or above support this function and i think the hosting i use do not support php 55 or aboveso i want to know if is there any alternate to fix this errorthis is how i am using array count in my projectarray count valuesarray columnjson decodejson encodequeryresultarray true idforbarthis is working fine in my local xampp and wampp also but on server it is giving issue looking any alternate function or solution,['php'] +813763,android google analytics causing black screen i just followed this tutorial for adding google analytics sdk v4 into an android app problem now is that when i run the app it just gives a black screen on any view i have setup with tracking for example below the is the oncreate onstart and onstop methods from the first view after the splash screen the splash screen loads fine then i just get a black screen on the view if you commented out the analytics code everything work override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutlanding screen get a tracker should autoreport define font for use typeface typeface typefacecreatefromassetgetassets fontscabinregularotf set font to all elements textview findviewbyidridtextflatsettypefacetypeface textview findviewbyidridtextcoolsettypefacetypeface textview findviewbyidridtextwarmsettypefacetypeface textview findviewbyidridtextpastelssettypefacetypeface textview findviewbyidridtextdecadessettypefacetypeface textview findviewbyidridtextneutralssettypefacetypeface textview findviewbyidridtextmidtonessettypefacetypeface textview findviewbyidridappheadertextsettypefacetypeface create all the listeners to catch button presses imagebutton buttonflat imagebutton findviewbyidridbuttonflat buttonflatsetonclicklistenerthis imagebutton buttoncool imagebutton findviewbyidridbuttoncool buttoncoolsetonclicklistenerthis imagebutton buttonwarm imagebutton findviewbyidridbuttonwarm buttonwarmsetonclicklistenerthis imagebutton buttonpastels imagebutton findviewbyidridbuttonpastels buttonpastelssetonclicklistenerthis imagebutton buttondecades imagebutton findviewbyidridbuttondecades buttondecadessetonclicklistenerthis imagebutton buttonneutrals imagebutton findviewbyidridbuttonneutrals buttonneutralssetonclicklistenerthis imagebutton buttonmidtones imagebutton findviewbyidridbuttonmidtones buttonmidtonessetonclicklistenerthis colorlibapplicationclass getapplicationgettrackercolorlibapplicationclasstrackernameapp tracker public void onstart superonstart get an analytics tracker to report app starts amp uncaught exceptions etc googleanalyticsgetinstancethisreportactivitystartthis public void onstop superonstop stop the analytics tracking googleanalyticsgetinstancethisreportactivitystopthis heres the application class package comexampleappcolorlib import androidappapplication import comgoogleandroidgmsanalyticsgoogleanalytics import comgoogleandroidgmsanalyticstracker import javautilhashmappublic class colorlibapplicationclass extends application the following line should be changed to include the correct property id private static final string property id uaremovedforsecurity logging tag private static final string tag myapp public static int general tracker 0 public enum trackername app tracker tracker used only in this app global tracker tracker used by all the apps from a company eg rollup tracking ecommerce tracker tracker used by all the apps from a company eg rollup tracking hashmaptrackername tracker mtrackers new hashmaptrackername tracker public colorlibapplicationclass super synchronized tracker gettrackertrackername trackerid if mtrackerscontainskeytrackerid googleanalytics analytics googleanalyticsgetinstancethis tracker t trackerid trackernameapp tracker analyticsnewtrackerrxmlapp tracker trackerid trackernameglobal tracker analyticsnewtrackerproperty id analyticsnewtrackerrxmlecommerce tracker mtrackersputtrackerid t return mtrackersgettrackerid,['android'] +813842,storyboard assistant editor stopped showing associated file xcode storyboard assistant editor stopped showing related filesautomatic is selected and class is filled in identity inspectorit was working before but know it has stopped auto or counterpart modes are still woking for other files except storyboarda few days ago i tried to update from xcode 5 to 6 but later on gave upwould that have something to do with it,"['ios', 'objective-c']" +813939,documenting a private constructor with jsdoc i have got a class where individual methods may be called statically but will return a new instance of class in order to chain for examplevar builder ns setstatea a setstateb bwhere builder is defined as such module builder class builder private function builder thisstate query builderprototype param string k the key param object v the value return builder setstate functionk v var that this instanceof builder this new builder thatk v return that other properties and methodsathe builder constructor is never supposed to be called explicitly by user code and thus i would like it not to show up in the docs however all of the combinations i have tried with jsdoc tags eg private constructs etc cannot seem to suppress it from the built docs,['javascript'] +813978,why cannot you declare a variable inside the expression portion of a do while loop the following syntax is validwhile int i get databut the following is notdo while int i get datawe can see why via the draft standardn4140641 condition expression attributespecifierseqopt declspecifierseq declarator initializerclause attributespecifierseqopt declspecifierseq declarator bracedinitlist2 the rules for conditions apply both to selectionstatements and to the for and while statements 65 n4140651 iteration statements specify looping iterationstatement while condition statement do statement while expression instead youre forced to do something ugly likeint i get datado while i get data double parentheses sicwhat is the rationale for this,['c++'] +814006,using zend db table abstractfindid mysql set field returns string instead of wanted int basic question how can i fetch the type column as integer value from inside the table mapperi have a php zend framework 112 application running a website inside mysql are multiple tables with multiple columns inside two tables i use the set type the column is named type and as setlocalexternal do not mix up this field type with the enum pleaseso far no problems querying the table and fetching the type column as int or string is not a problemsql dbselectfromtablename type as int new zend db exprtype0 returns int if both are selected 3sql dbselectfromtablename type returns string if both are selected localexternalbut in this application also has table mappers that extend zend db table abstractinside the mapper resides the find method default built in into the abstract to find records by their primary keybut when i use the object to fetch a record i find the following response inside my populate methodarraytype localexternal querying it by hand and defining the columns myself would be an options thisselectfrom but is not there a more elegant wayi know that i am using an older version of zf but upgrading would cost too much time at this moment,"['php', 'mysql']" +814035,java servlet mapping a servlet to every url but a string i have a servlet configured to handle all urls servlet servletnamemyservservletname servletclassmyservletservletclaservletservletmapping servletnamemyservservletname urlpatternurlpatternservletmappingi need that for urls beginning with static it should serve them from the static webinf that is myserv should serve everything but statichow can i do thatupdate to clarify what i would like is goes to myservstaticdirfilecss jetty serves the static filecss from the diri am not sure what webxml to do or where to put the static filesi tried adding thisservletmapping servletnamedefaultservletname urlpatternstaticurlpatternservletmappingbut when i go to a static url i just gethttp error 404problem accessing staticdirfilecss reason not foundpowered by jettyi am not sure if my webxml is wrong or if i am simply putting the files in the wrong place i have tried under srcmainwebapp and srcmainwebapplibmetainfresourcesjettyi am using jetty i want to avoid any other layers such as nginx apache etcto win the bounty please make sure you answer works for jetty,['java'] +814077,how to clip polar plot in pylabpyplot i have a polar plot where theta varies from 0 to pi2 so the whole plot lies in the first quater like thispylab inlinexlinspace0pi2polarxcos6x2is it possible by means of pyplot or matplotlib to clip the polar plot so that only first quater is shown and therefore no space is wasted i want a picture like this but properly scaledi would like to do it by means of pyplot because i have several images like this and want to arrange them into a big figure with subplot is it possible,['python'] +814079,what would cause wordnetcorpusreader to have no attribute lazycorpusloader i have got a short function to check whether a word is a real word by comparing it to the wordnet corpus from the natural language toolkit i am calling this function from a thread that validates txt files when i run my code the first time the function is called it throws a attributeerror with the message wordnetcorpusreader object has no attribute lazycorpusloader argswhen i pause execution the same line of code does not throw an error so i assume that the corpus is not yet loaded on my first call causing the errori have tried using nltkwordnetensure loaded to force load the corpus but i am still getting the same error heres my functionfrom nltkcorpus import wordnet as wnfrom nltkcorpus import stopwordsfrom nltkcorpusreaderwordnet import wordneterrorimport syscachedstopwords stopwordswordsenglishdef is good wordword word wordstrip if lenword 2 return 0 if word in cachedstopwords return 0 try wnensure loaded if lenwnlemmasstrword langen 0 return 0 except wordneterror as e print wordneterror on concept formatword except attributeerror as e print attribute error on concept formatword emessage except print unexpected error on concept formatword sysexc info0 else return 1 return 1print is good worddog does not throw errorif i have a print statement in the same file at the global scope it does not throw the error however if i call it from my thread it does the following is a minimal example to reproduce the error i have tested it and on my machine it gives the output attribute error on concept dog wordnetcorpusreader object has no attribute lazycorpusloader argsattribute error on concept dog wordnetcorpusreader object has no attribute lazycorpusloader argsattribute error on concept dog wordnetcorpusreader object has no attribute lazycorpusloader argsattribute error on concept dog wordnetcorpusreader object has no attribute lazycorpusloader argsattribute error on concept dog wordnetcorpusreader object has no attribute lazycorpusloader argsattribute error on concept dog wordnetcorpusreader object has no attribute lazycorpusloader argsattribute error on concept dog wordnetcorpusreader object has no attribute lazycorpusloader argsattribute error on concept dog wordnetcorpusreader object has no attribute lazycorpusloader argsattribute error on concept dog wordnetcorpusreader object has no attribute lazycorpusloader argsminimal exampleimport timeimport threadingfrom filter tag import is good wordclass processmetathreadthreadingthread def init self threadingthread init self def runself is good worddog throws errordef process metanumberofthreads threadslist for i in rangenumberofthreads t processmetathread tsetdaemontrue tstart threadslistappendt numcomplete 0 while numcomplete numberofthreads iterate over the active processes for processnum in range0 numberofthreads if a process actually exists if threadslist none if the process is finished if not threadslistprocessnum none if not threadslistprocessnumis alive numcomplete 1 threadslistprocessnum none timesleep5 print processes finishedif name main process meta10,['python'] +814158,debugging with android studio stuck at waiting for debugger forever whenever i try to use android studios debug function the run status would always stuck atlaunching application comastrotekparashootdebugcomastrotekptpviewerstarteractivitydevice shell command am start n comastrotekparashootdebugcomastrotekptpviewerstarteractivity a androidintentactionmain c androidintentcategorylauncherstarting intent actandroidintentactionmain catandroidintentcategorylauncher cmpcomastrotekparashootdebugcomastrotekptpviewerstarteractivity while the device samsung galaxy s3 android 43 i am debugging would thisplaythis has being the case from android studio 088 all the way to 10 and on the same computer i can perform debugging using eclipse on the same device without any issues so the question is what can i do to make android studio debugging workupdate the same thing happens when debugging on nexus 7 2013 running android 50 and testing on another machine rendered the same result i cannot be the only one encountering this issue update opened a bounty since this issue is so annoying even reinstalling the app does not solve nexus 5 running cyano win7 64 the adb log is telling85688568itmyappmyprocess wactivitythreadi1 application itmyapp is waiting for the debugger on port 810085688568itmyappmyprocess isystemouti1 sending wait chunkalso i cannot find an easy way to thisconnect nor reset adb connection in android studio,['android'] +814264,swift uiview background color opacity i have a uiview with a uilabel in it i want the uiview to have white background color but with an opacity of 50 the problem whith setting viewalpha 05 is that the label will have an opacity of 50 as well so i figured out that it maybe would be possible to have a uiview with white background color and opacity white view and then have another uiview with the label label view then add the white view to label view by doing this label viewaddsubviewwhite view this apparently does not work i would like to do like label viewbackgroundviewwhite view but you cannot set a background view on a uiview like you can do in a uicollectionview for instancedoes anyone have any clue of how to solve thiseditbecause several answers are approx the same i will type it herenow i have tried even theselabel view1backgroundcolor uicolorwhitecolorcolorwithalphacomponent05label view1addsubviewfirstplacelblendgameviewaddsubviewlabel view1andlabel view1backgroundcolor uicolorwhite 1 alpha 05label view1addsubviewfirstplacelblendgameviewaddsubviewlabel view1and still the label is also affected by the alpha and it gets an opacity of 50 i do not get it what i do wrong because i only set the colors alpha to 05 and not the labels any ideas,['ios'] +814289,what is the difference between int and int32 in swift in core data you can store int16 int32 int64 but it is different from int what is the reason for their existence how do you use them,['ios'] +814479,why does my foreach only throw one exception i have the following codeif errorlist null errorlistcount 0 foreach var error in errorlist throw new exceptionerrorpropertyname errorerrormessage errorentityvalidationfailed why does it only throw one exception when multiple errors are in the list,"['c#', '.net']" +814498,immutablejs relationships imagine a situation that john have two childrens alice and bob and bob have a cat orion var immutable requireimmutablevar parent immutablemapname johnvar childrens immutablelist immutablemapname alice parent parent immutablemapname bob parent parentvar cat immutablemapname orion owner childrensget1after few years john wants to rename to janevar renamedparent parentsetname janeand let childrens know about itchildrens childrensmapfunctionchildren childrensetparent renamedparentthen i have to update cat because bob changedcat catsetowner childrensget1is it possible to automatically update all related objects when one object change i looked at cursors but i am not sure if they are a solution if it possible can you give me an example,['javascript'] +814555,elastic beanstalk cmdappdeploy activity failed composer issue i have php application laravel and the eb cli installed locally everything is finethe initial application is working as expected uploaded as an archivezip on createdwhen i push my repo to my application usinggit awspushit fails the logs say this20141212t165338652z info 28264 cmdappdeployappdeploystage0appdeployprehook10 composer installsh activity failed20141212t165338652z info 28264 cmdappdeployappdeploystage0appdeployprehook activity failed20141212t165338652z info 28264 cmdappdeployappdeploystage0 activity failed20141212t165338653z info 28264 cmdappdeploy completed activity resultcommand cmdappdeploy failedand this20141212t165338653z error 28264 command cmdappdeploy failed20141212t165338654z info 28264 command processor returning results statusfailureapi version10truncatedtrueresultsstatusfailuremsgcmdappdeployappdeploystage0appdeployprehook10 composer installsh command failed with error code 1optelasticbeanstalkhooksappdeploypre10 composer installshn optelasticbeanstalkbingetconfig container k app staging dirn eb app staging dirvarappondeckn cd varappondeckn f composerjson n export composer homerootn composer homerootn d vendor n optelasticbeanstalkbingetconfig optionsettings n awselasticbeanstalkcontainerphpphpini o composer optionsn php composer optionsn echo found composerjson file attempting to install vendorsnfound composerjson file attempting to install vendorsn composerphar install noansi nointeractionnloading composer repositories with package informationninstalling dependencies including requiredev from lock filen installing symfonyfinder v258n returncode1eventsi was thinking it was a composer issue i have gone into the instance and done a composer update within the machine but that worked fine i have removed the composerlock file from the gitignorei cannot find anything similar online so i am assuming i am doing something missing something very obvious here,['php'] +814560,does c standard guarantee diagnostic message for error directive i have some trouble understanding semantics of 51131 diagnostics subclause from n1570 c11 draft emphasis minea conforming implementation shall produce at least one diagnostic message identified in an implementationdefined manner if a preprocessing translation unit or translation unit contains a violation of any syntax rule or constraint even if the behavior is also explicitly specified as undefined or implementationdefined diagnostic messages need not be produced in other circumstances9i understand that the intent was to exclude nonconstraint undefined behavior thus that are no diagnostics on eg buffer overflow but what about error directive as in 61051 error directivea preprocessing directive of the form error pptokensopt newlinecauses the implementation to produce a diagnostic message that includes the specified sequence of preprocessing tokensdoes these both subclauses are not mutually exclusivefor some other reference see also dr176,['c'] +814573,correctly returning uiview in viewforheaderinsection ios 8 swift i am fairly new to swift language and ios development as a whole so please pardon me for my lack of fundamental knowledge previously i tried and successfully implemented multiple sectioned uitableview custom sections by making a xib file creating tableviewcell and then loading it into my main viewcontroller and returning it as coded belowvar customview nsbundlemainbundleloadnibnamedcustomheaderowner self options nil0 as uiviewreturn customviewbut since i started getting no index path for table cell being reused i went back to drawing board and tried to do things programmatically creating a uiview and return it so far i am have been unsuccessful however this is what i codedfunc tableviewtableview uitableview viewforheaderinsection section int uiview ifsection 0 var view uiviewframe cgrectmake0 0 tableviewframesizewidth 50 var label uilabelframe cgrectmake00 tableviewframesizewidth2 20 labeltextmy details let button uibuttonbuttonwithtypeuibuttontypesystem as uibutton buttonframe cgrectmake0 0 tableviewframesizewidth2 20 buttonaddtargetself action visiblerow forcontroleventstouchupinside labelsettranslatesautoresizingmaskintoconstraintsfalse buttonsettranslatesautoresizingmaskintoconstraintsfalse let views label labelbuttonbuttonview view var horizontallayoutcontraints nslayoutconstraintconstraintswithvisualformath10label2060button2010 options nslayoutformatoptions0 metrics nil views views viewaddconstraintshorizontallayoutcontraints return view as you can see i am trying to create a layout where i want my label and button horizontally laid out but somehow logic is not working out i tried thisabling autoresize constraints on view itself but that too did not worked too please help,"['ios', 'iphone']" +814627,how can i correctly handle malloc failure in c especially when there is more than one malloc suppose this is a part of my code int foo char p q ifp mallocbufsiz null return error code ifq mallocbufsiz null freep return error code do some other work freep freeq since it is possible that the first malloc is successful but the second one fails i use freep in the second error handler but what if there are more mallocs and what if i want to modify the code adjusting their orders adding or deleting some malloci know in c there are things like raii and exception safe etc but in general what is the correct way to handle malloc failure in c maybe using some goto,['c'] +814688,is there any way of implementing the insert method for a standardscompliant vector firstly assume a is a type witha potentially throwing copy constructorassignment operatorno move constructorassignmentthis is a common example of a c03 raii type now let me cite the c14 standard snipped irrelevant partsa2321 general container requirements11 unless otherwise specified see and 23365 all container types defined in this clause meet the following additional requirementsif an exception is thrown by an insert or emplace function while inserting a single element that function has no effectsa23365 vector modifiersiterator insertconst iterator position const t x1 remarks causes reallocation if the new size is greater than the old capacity if no reallocation happens all the iterators and references before the insertion point remain valid if an exception is thrown other than by the copy constructor move constructor assignment operator or move assignment operator of t or by any inputiterator operation there are no effects if an exception is thrown while inserting a single element at the end and t is copyinsertable or is nothrow move constructibletvalue is true there are no effects otherwise if an exception is thrown by the move constructor of a noncopyinsertable t the effects are unspecified2 complexity the complexity is linear in the number of elements inserted plus the thistance to the end of the vectornow consider thisstdvectora v5vreserve10vinsertbegin 2 aclearly were inserting a single element so a2321 11 applies and either the operation succeeds or v is unchanged a23365 does not change anything about this the exception is thrown by the copy constructor we are not inserting at the end the move constructor is not usedbut now consider this possible scenario during the implementation of insert assuming no reallocation happens01234 initial state0123 4 making space by copying012 34 continued01234 continued but copy operation threwat this point all future copy operations could throw making it impossible to restore the state as required oopsi cannot see any implementation without reallocation that enables strong exception safety this means that any implementation must always reallocate when inserting a type without a move constructor and a throwing copy constructor in the middle howeverinsertpos value becomes unbearably slow due to constant reallocationsthe complexity requirement is not met reallocation always requires n operationsit could be argued that causes reallocation if the new size is greater than the old capacity implies that no reallocation is allowed if the new size is not greater than the old capacityto support this consider that if an implementation may reallocate anytime the user has no way of knowing this makes the guarantee about preserving iterators if no reallocation happens all the iterators and references before the insertion point remain valid useless information and makes you wonder why both sentences were inserted into the standard in the first place1 2 are pretty damning observations but if 3 is true then it is as far as i can see plain impossible to be compliant with the standardso is there any way of implementing the insert method for a standardscompliant vector or is this a standard defecta demonstration of this issue can be seen here,['c++'] +814699,you need to add at least 2 nonandroid tv screenshots in my developer console for google play i dragged two pngs at 21 ratio 10px x 500px into the graphic assets slots for the tv and they were accepted but i still get the message you need to add at least 2 nonandroid tv screenshots when i click to publish the app so it remains in draft mode i am unsure what i should be doing differently to finalize iti signed out then signed back in and the issue persists i am using the chrome browser i tried in the firefox browserthis app was uploaded in alpha testing if that matters also i thought tv images were optional,['android'] +814758,why cannot modern c ides autogenerate header files i understand the benefits and flexibility that header files provide symbol thiscovery the speedup of processing for the compiler etc what i do not understand is why modern c ides do not autogenerate header files based on the membersmethods added into the code file thus reducing the manual labour involved in keeping the header uptodate with the code file and viceversa since the ide only makes incremental changes to the header file developers may modify the header and changes are preservedrefactoring could be provided for addingrenamingremoving method arguments for renaming methods for moving methods into another class and so on during such refactoring the ide would take care of updating the header source filesthe functionality could be similar to the visual form designer in visual studio when you design a form the ide autogenerates code for the same which is stored in a separate idemanaged source file devs may also modify such code files or may include additional code in the usermanaged source fileworking with professional c source code i have encountered all kinds of dubious practices entire classes defined in the header file that include function code why should i define a class in two places when i can define it in oneuseful functions defined in the header file why bother keeping the header uptodate when i can define the function in the header itself let other devs use go to declaration to find the function if they do not think of looking in the header filemissing header definitions for publicstatic functions reduces compilation time or saves dev timealthough i am not a professional c programmer coming from a highlevel background js c as3 i can feel the downgrade working with c firsthand and i do not see why some of these thisadvantages cannot be eliminated by the ide itselfby no means am i mocking the ide or the compiler in any way i understand c allows for more complex methods of defining a program than modernday languages do eg c and though the complexities of templating elude me i would like to see some of the benefits of higher level languages brought into c application development,['c++'] +814764,retrive the text of wkinterfacelabel in swift how can i get the text of label in swift or objectivc in watchkitthe class is not uilabel but it is wkinterfacelabeli have also tried to search in class library of apple but there is only three methods are available,['ios'] +814933,renderview in my service i am new of symfony worldi want to use render inside my service but i got this errorcall to undefined method renderviewi know that renderview is shortcut of returns a rendered view param string view the view name param array parameters an array of parameters to pass to the view return string the rendered view public function renderviewview array parameters array return thiscontainergettemplatingrenderview parametersbut i do not know what i have to injection in my service i know even that with php appconsole containerdebug command i can see all my services available but i do not know how can takechoose the correct updatei tried to addarguments mailertemplatingbut i got servicecircularreferenceexceptionupdatei changed my serviceyml with arguments service containerand even my serviceemail thisservice containergetmailertwig thisservice containergettemplatingfor use service mail swift and renderi do not think that it is best solution i would like to injection only mailer and templatingupdate after jasons answeri am using symfony 23my servicesymlservices emailservice class emailserviceclass arguments mailertemplatingemailserviceadminemaili got this servicecircularreferenceexception,['php'] +815037,gccs tsan reports a data race with a thread safe static local i wrote the following toy examplestdmapchar size t getmapconst stdstring s stdmapchar size t map size t i 0 for const char b sdata end b ssize b end b mapb i return mapvoid checkconst stdstring s the creation of the map should be thread safe according to the c11 rules static const auto map getmap12abcd12ef now we can read the map concurrently size t and 0 for const char b sdata end b ssize b end b auto iter mapfindb if iter mapend and itersecond stdcout check s and stdendlint main stdthread t1check abc stdthread t2check def t1join t2join return 0according to the c11 standard this should not contain any data race cf this posthowever tsan with gcc 492 reports a data racewarning threadsanitizer data race pid14054 read of size 8 at 0x7f409f5a3690 by thread t2 0 testservercheckstdstring const null0 testserver0x0cc30a 1 stdthread implstd bind simplevoid char conststdstring const m run null0 testserver0x0cce37 2 execute native thread routine gcc492libstdcv3srcc11threadcc84 libstdcso60x0b5bdf previous write of size 8 at 0x7f409f5a3690 by thread t1 0 testservergetmapstdstring const null0 testserver0x0cc032 1 testservercheckstdstring const null0 testserver0x0cc5dd 2 stdthread implstd bind simplevoid char conststdstring const m run null0 testserver0x0cce37 3 execute native thread routine gcc492libstdcv3srcc11threadcc84 libstdcso60x0b5bdf location is global testservercheckstdstring constmap of size 48 at 0x7f409f5a3680 testserver0x062b690 thread t2 tid14075 running created by main thread at 0 pthread create gcc492libsanitizertsantsan interceptorscc877 libtsanso00x047c03 1 gthread create homeguillaumecompileobjdirx86 64unknownlinuxgnulibstdcv3includex86 64unknownlinuxgnubitsgthrdefaulth662 libstdcso60x0b5d00 2 stdthread m start threadstdshared ptrstdthread impl base gcc492libstdcv3srcc11threadcc142 libstdcso60x0b5d00 3 testservermain null0 testserver0x0ae914 4 starquberunsuitechar const void null0 testserver0x0ce328 5 main null0 testserver0x0ae8bd thread t1 tid14074 finished created by main thread at 0 pthread create gcc492libsanitizertsantsan interceptorscc877 libtsanso00x047c03 1 gthread create homeguillaumecompileobjdirx86 64unknownlinuxgnulibstdcv3includex86 64unknownlinuxgnubitsgthrdefaulth662 libstdcso60x0b5d00 2 stdthread m start threadstdshared ptrstdthread impl base gcc492libstdcv3srcc11threadcc142 libstdcso60x0b5d00 3 testservermain null0 testserver0x0ae902 4 starquberunsuitechar const void null0 testserver0x0ce328 5 main null0 testserver0x0ae8bdsummary threadsanitizer data race 0 testservercheckstdstring constwhat is wrong here is tsan buggy when i am using clangs toolchain i get no data race reportdoes gcc emit code which is not thread safe i am not using fnothreadsafestatics thoughis my understanding of static locals incorrect,['c++'] +815078,pass data httppost from angularjs and aspnet mvc gets null i am trying to pass data from angularjs to aspnet mvc and is always getting nullheres my code only posting the essential button controller and chtmla classbtn btngrey btnlg btnblock ngclickaddcarsaveacontrollerscopeaddcar function httppostcarsaddcar jsonstringifyscopenewjsoncarsuccessfunction data alertok cpublic string addcarstring jsoncar try in jsonstringifyscopenewjsoncar i am getting this namefiat 500descriptionnew carmaxusercapacity5photopathnonewhat i am doing wrong,['c#'] +815091,typeerror routeruse requires middleware function but got a object there have been some middleware changes on the new version of express and i have made some changes in my code around some of the other posts on this issue but i cannot get anything to stickwe had it working before hand but i cannot remember what the change was throw new typeerrorrouteruse requires middleware function but got a typeerror routeruse requires middleware function but got a objectnode binwjsbson failed to load c bson extension using pure js versionjsbson failed to load c bson extension using pure js versionusersdatisdocumentsbbdashboardnode modulesexpresslibrouterindexjs438 throw new typeerrorrouteruse requires middleware function but got a typeerror routeruse requires middleware function but got a object at usersdatisdocumentsbbdashboardnode modulesexpresslibrouterindexjs43813 at arrayforeach native at functionuse usersdatisdocumentsbbdashboardnode modulesexpresslibrouterindexjs43613 at usersdatisdocumentsbbdashboardnode modulesexpresslibapplicationjs18821 at arrayforeach native at functionuse usersdatisdocumentsbbdashboardnode modulesexpresslibapplicationjs1857 at objectanonymous usersdatisdocumentsbbdashboardappjs465 at module compile modulejs45626 at objectmodule extensionsjs modulejs47410 at moduleload modulejs35632appjsvar express requireexpressvar path requirepathvar favicon requireservefaviconvar logger requiremorganvar cookieparser requirecookieparservar bodyparser requirebodyparservar mongoose requiremongoosevar session requireexpresessionvar mongoclient requiremongodbmongoclientvar routes requireroutesindexvar users requireroutesusersvar users requiremodelsuservar items requiremodelsitemvar store requiremodelsstorevar storeitem requiremodelsstoreitemvar app expreset mongo db connectionvar db mongooseconnection mongoclientconnectmongodblocalhost27017test functionerr db iferr consolelogwe are connected var mongohq urlmongodblocalhost27017test view engine setupappsetviews pathjoin dirname viewsappsetview engine ejs uncomment after placing your favicon in publicappusefavicon dirname publicfaviconicoappuseloggerdevappusebodyparserjsonappusebodyparserurlencoded extended false appusecookieparserappusesession secret something resave true saveuninitialized trueappuse routesappuseusers usersappuseexprestaticpathjoin dirname public catch 404 and forward to error handler appusefunctionreq res next var err new errornot found errstatus 404 nexterr make our db accessible to our routerappusefunctionreq res next reqdb db next error handlers development error handler will print stacktraceif appgetenv development appusefunctionerr req res next resstatuserrstatus 500 resrendererror message errmessage error err production error handler no stacktraces leaked to userappusefunctionerr req res next resstatuserrstatus 500 resrendererror message errmessage error moduleexports appit appears the answer to this question has changed for versioning reasons thanks to nik,['javascript'] +815126,nightwatch cannot findclick on dropdown option i am a backpacker and a programmer trying to use the second skill to find openings in a full campsite rather than crawling fro scratch i am using the endtoend testing framework nightwatchjs to navigate for mei have hit a roadblock because nightwatch is having difficulty finding a specific element using css selectorshere are the elements and pagehere is my test codeprevious attemptsmy test code will click on the selection box with permittypeid it will see that permittypeid option is visible it will not see or click on any of the options when more specific values are specified the five clicks are all css selectors i have already tried none of the options are set to thisplayhidden or thisplaynone i have also tried all of the above without the waitforelementtobevisible just incase the waiting causes the dropdown to hidei have successfully clicked options from different dropdown menus on this website without any problem just this one is causing a headachethe tests are running with the most current selenium server and firefox on mac yosemite tldrnightwatchjsselenium would not click on something from a dropdown menu,['css'] +815135,angular directive memory leaks i am using this simple html file to reproduce a memory leak i founddoctype htmlhtml head script srcscript script var app angularmoduletestapp appdirectivedirective1 function return template div directive2div scope true appdirectivedirective2 function function leakobject function foo thisbar functionscope scopenottheredude return scope true link functionscope scopememorythatleaks new leakobject new foobar new foobarscope script head body ngapptestapp button ngclickshow showtogglebutton div ngifshowthe directive div directive1divdiv div ngifshownothingdiv bodyhtmli have a directive that only creates a new scope and has another directive in its templatethe other directive does something a bit strange i tried to narrow down the problem to whats causing the leak and that is the shortest code i found that reproduces the issuein my main html i just toggle between nothing and directive1 with a simple ngifnotice that directive2 also creates a new object on the scope called leakobject i expect this object to be garbage collected when i am toggling back to the nothing div since the scope of the directive should die and all the data on it with it but according to chromes heap snapshot tool in incognito mode it is not getting unallocatedi am trying to understand why that happens and why if i comment out the statement in the bar method it does not happensteps to reproduceopen this file in incognitoopen dev tools and go to profilesrefresh the pageclick toggle twice so now you see nothing on the screen againtake a heap snapshotwrite leak in the filter so you can see the leakobject still exists when it should not really existthis is how it should look likecan someone please helpexplain,['javascript'] +815155,is there a way to copy only the structure not the data of a pandas dataframe i receive a dataframe from somewhere and want to to create other dataframe with the same number and names of columns and rows indexes for example suppose that the original data frame was created asimport pandas as pddf1 pddataframe122122columnsc1c2indexi1i2i copied the structure by explicitly defining the columns and namesdf2 pddataframecolumnsdf1columnsindexdf1index i do not want to copy the data otherwise i could just write df2 df1 in other words after df2 being created it must contain only nan elementsin 23 df1out23 c1 c2i1 11 12i2 21 22in 24 df2out24 c1 c2i1 nan nani2 nan nanis there a more idiomatic way of doing it,['python'] +815222,integration testing dropwizard apps i just read over dropwizards testing docs and am in love with its builtin integrated testing capabilities tldr it allows your junit tests to spin up inmemory instances of jetty and essentially serve your api endpoints resource methods as they will exist in the wild this allows you to actually hit your api endpoints with a client against localhost and see how they doperform awesomei am wondering if it is possible to use this dropwizardapprule or something similar to it to start upshutdown my dropwizard app and verify no exceptions were thrown smoke testing andthe smoke testing would be useful because there could be some initializationrelated exception that prevents the app from starting up bad config file etc and it would be nice to know about this in advance similarly smoke testing on shutdown is helpful because we might have something not closingtearing down gracefully and might have a hanging thread that just would not die etcit would also be nice to stress test the running inmemory server and see where it pushes over perhaps throwing an oomeso given the following code snippetpublic class integrationtest classrule public static final dropwizardappruletestconfiguration rule new dropwizardappruletestconfigurationmyappclass resourcefilepathmyappconfigyaml test public void shouldstartwithnoexceptions test public void stresstest10kusers what exceptions could i check for to see if the server pushed over after 10 random endpoints were hit test public void shouldshutdowngracefully i askhow do i test the server started without throwing exceptionshow do i test whether the server is still responding and has not died due to stress testinghow do i shut the server down and make sure no exception were thrown or that nothing prevented a graceful shutdown,['java'] +815228,is there a way to prove properties about my c programs i understand how languages like coq and idris can be used to prove properties of programs written in those languages judging by my little experience in the subject but i wonder if there is an approachable way to do the same externally on an already existing codebaseis there a way to use a tool like coq or some other specialized tool to prove correctness on algorithms written in c if so what are the requirements for doing so,['c++'] +815250,how to use gensim doc2vec with pretrained word vectors i recently came across the doc2vec addition to gensim how can i use pretrained word vectors eg found in word2vec original website with doc2vecor is doc2vec getting the word vectors from the same sentences it uses for paragraphvector trainingthanks,['python'] +815332,using static html with react i am learning how to use react and so far i am very much enjoying it however i am running into a bit of a problemas practice with react i am trying to build a navigation menu that shows different content based on the active item or tab these different views will for my purposes be static in nature mainly informative with maybe some embedded audio or video but there may be a lot of content in each view to me it makes the most sense to create separate html files and use their content in these different views however the only way i can see to do this without the use of an external library is to put the static content for each view in its own react component that does nothing but render that static contentthis seems silly to me is there some way to accomplish what i am trying to do in react if not is there a lightweight or widelyused library out there that will allow me to accomplish this thanks in advance,"['javascript', 'html']" +815382,webkit bug overflow auto triggered after resizing a child element to matching size i have the following simple setup jsfiddle the issue can be reproduced inchrome 390217195 64bit for os xchrome 390217195 m for windowsopera 260165632 for windowssafari 517 for windowsthe issue is not present infirefox 3311 for os xfirefox 3401 for windowsie 110 for windowsionclick function var t this tcss width 200 height 100 c background blue width 200px height 100px overflow autoi background green width 210px height 110pxscript srcscriptdiv classc div classidivdivupon clicking the inner element i green i would expect the scrollbars on the parent to thisappear since the two elements now have matching sizes this works as expected in firefoxhowever the container element c does not lose scrollbars in chrome as can be seen in the below screenshotthe scrollbars themselves create an offset large enough to create overflowingis this a webkitspecific issue is there a crossbrowser reliable solution to this seemingly trivial issue i am looking for a solution that does not change the parents properties as my content i will be placed in dom i do not have control overso far i have tried hidingshowing andor detachingreinserting the element at different points of execution but the problem persists likely because the operations are simply optimized away the issue occurs both in jsfiddle and in the stack snippetthe bug has been filed on webkit bugzilla,"['javascript', 'css']" +815456,why is the file i am attempting to write nonexisting i have a custom config file in my ci application in my web applications admin panel i want to have a form that i can use to change the values of the config array of the custom file my problem right now is that the write file function always returns false and i do not know why i am pretty sure i am writing the path in the function correctly and the config directory is not readonlythis is wamp so windows the file definitely exists what am i doing wrongthis is applicationcontrollersconfigassetsphpfile fcpath applicationconfigassets fephpifis writablefile open fopenfile w iffwriteopen frontend echo could not write file else echo file written else echo file not writablethis is a screenshot of the file in it is location in windows exploreri have tried the following file paths in the write file functionwrite filefcpathapplicationconfigassets fephp frontend wwrite fileapplicationconfigassets fephp frontend wwrite fileapplicationconfigassets fephp frontend wnone of the above file paths have worked could it be something elsefyi fcpath wwampwzeus and it is defined by cis front controller to return the path of that fileupdate i tried using just the native php version and it is saying that the file or directory does not exist maybe i am using the wrong path what should it be,['php'] +815479,faking a closures function name leaving out a long story i have a scenario like thisclass foo function dosomething print i was just called from debug backtrace1function function triggerdosomething this outputs i was just called from triggerdosomething this output makes me happy thisdosomething function callmethod args this way outputs i was just called from call i need it to be i was just called from method thisdosomething this way outputs i was just called from closure also not what i need c function thisdosomething c this causes an infinite loop thismethod function thisdosomething thismethod in the case that i call foorandomfunction i need the the output to read i was just called from randomfunctionis there a way to name a closure or approach this problem differentlynote i cannot change the dosomething function it is a sample of thirdparty code i am calling that considers the function name of who called it in order to do something,['php'] +815496,how to toggle the visibility of two buttons using datatrigger behavior in xaml wp 81 i have two buttons button a button b both are kept hidden initially data is fetched from an observable collection ocollection this is what i am trying to acheive1 initially both buttons are hidden done2 on the first click clicking any list view item button a should be made visible done3 on rest of the clicks clicking any other listview item other than the one in which button a has been kept visible button b should be made visible and visibility of button a should not change back to collapsednb each listview item must contain only one button either button a or button bocollection is set as the itemsource of a listvieweach listview item is a grid containing a default imagexaml listview namelv itemssourcebinding ocollection backgroundlinen gridcolumnspan3 listviewitemtemplate datatemplate grid backgroundlightgray namebuttongrid tagbinding dumystring iinteractionbehaviors icdatatriggerbehavior bindingbinding elementnamelv pathselectedvaluedumystring valuebinding dumystring comparisonconditionequal icchangepropertyaction targetobjectbinding elementnamebuttona propertynamevisibility valuevisible icdatatriggerbehavior icdatatriggerbehavior bindingbinding elementnamelv pathselectedvaluedumystring valuebinding dumystring comparisonconditionnotequal icchangepropertyaction targetobjectbinding elementnamebuttona propertynamevisibility valuecollapsed icdatatriggerbehavior icdatatriggerbehavior bindingbinding elementnamelv pathbuttongridtag valuebinding dumystring comparisonconditionequal icchangepropertyaction targetobjectbinding elementnamebuttonb propertynamevisibility valuevisible icdatatriggerbehavior iinteractionbehaviors image sourceassetslogopng button namebuttona contentbuttona backgroundblack visibilitycollapsed button namebuttonb contentbuttonb backgroundblack visibilitycollapsed grid datatemplate listviewitemtemplate listviewto acheive 3 i am comparing the tag of the grid with the button content it does not work because the logic is wrong well how can this be acheived without using code behind i am following mvvm pattern so adios to code behinda sample would be nice because i am just a beginnerclasspublic class dumyclass public string dumystring get set,['c#'] +815506,using coalesce to handle null values in postgresql i have the following query select thistinct ptincentive marketing ptincentive channel ptincentive advertising from testpricing pt where ptcontract id 90 group by 123 order by ptincentive marketingthe above query returns the op as shown in the attached imagehowever i want to replace all null values by 0 using coalesceplease let me know how this can be achieved in above select querynow i further modified the query using coalesce as belowselect coalesce ptincentive marketing 0 coalesceptincentive channel0 coalesce ptincentive advertising0 from testpricing pt where ptcontract id 90 group by 123 the result of which is as attached in image 2i still receive one row with blank values,['sql'] +815527,getting top 10 values in a json file this is an example of my json file variablehellovariable120 variablehivariable130 variablehowvariable140 variablewhovariable150 variablewherevariable160 variablethisvariable1100 variableporkvariable110 variablecreepvariable190 variablemega creepsvariable180 variablelolvariable10 variableroflvariable10 variablelmaovariable10 variablepopvariable10 variablelovevariable10 variablepickvariable10 variablewhizvariable10 variableboredvariable10 variablekillahvariable10 variablelollingvariable10 variablehaloo haloovariable10how can i get only the top 10 from highest variable1 number to the least but gonna be passing the json file as the same format,"['javascript', 'html']" +815550,http11 505 http version not supported i am running a php script to grab a web page it worked fine with many sites but with one site it fails returning an error saying http11 505 http version not supportedthis is part of my scriptfori 0 i 1 i page file get contents fantasyseitei do something with pagemany answers recommend setting the http version explicity i have tried setting 09 10 and 11 but it did not change anything and actually the headers seems to show that the http version requested by my browser and that expected by the server matchreply headershttp11 200 okdate mon 15 dec 2014 090115 gmtserver apachexpoweredby php5435keepalive timeout2 max200connection keepalivetransferencoding chunkedcontenttype texthtmlrequest headersget pathscriptphp http11host wmydomandeuseragent mozilla50 macintosh intel mac os x 109 rv340 gecko20100101 firefox340accept texthtmlapplicationxhtmlxmlapplicationxmlq09q08acceptlanguage deenusq07enq03acceptencoding gzip deflatednt 1authorization basic mjqwmje5njc6mdcwnjiwmdcconnection keepalivecachecontrol maxage0what else can be wrong,['php'] +815575,using a jquery clone outside the dom i have been working on a small project where i am using the jquery clone methodpitfall with this is using it on html that has unique identifiersso i went on implementing getcomputedstyle to find the style properties of the original unique elements in order to copy it to the clone and give that an new id afterwards yes it can give performance issues but it is experimentalaccording to the jquery spec doing this after cloning but before appending will make the manipulation happen outside of the dom so no id violation will occur but i noticed some strange behaviour across browsers when i try to find style properties of the elements after the object was cloned before it all browsers return the same values but after being cloned firefox carefree and interestingly the clones computed style is the actual css value rather than computed data in pixelsie seems to work but value is not necessarily correctchrome does not compute heres an example var elements var objects bodyfindideachfunction elementspushthisbodyclonefindideachfunction objectspushthiseachelements functionkey element var current windowgetcomputedstyleelement nullgetpropertyvaluewidth logappendp elementid current plogappendbreachobjects functioncount object var current windowgetcomputedstyleobject nullgetpropertyvaluewidth logappendp objectid current panybody know if this is a bug or has similar behaviour been seen beforenot a lot to go on webwise not even stackoverflowthanks in advance for any insightedit did some more testing and it looks like ie behaves the same as chromeonly instead of not returning anything everything is set to autoif the style of the cloned objects is accessed by using css all values return 0px including properties like backgroundseems only mozilla treats the cloned object as if any style has been applied to it at all,"['jquery', 'css']" +815592,differences between javas swingworker and android asynctask i was comparing the differences between swings swingworker and androids asynctask classes while android has a main threadui thread and then spawns a background thread using asynctask swingworker has three threads that are involved current threadworker threadevent thispatch threadand then i also came across the statement in docs often the current thread is the event thispatch threadnow what does this meandoes it mean that swing also has only 1 thread the main thread andeven the events are received on the same thread oris it different for different jvm implementations,"['java', 'android']" +815626,java overloading with variable length arguments why there is no compile error in this codepublic class overloadingvarargs public void fun1int b systemoutprintlnint public void fun1long a systemoutprintlnlong public static void mainstring args overloadingvarargs obj new overloadingvarargs objfun1 but this code gives compile errorpublic class overloadingvarargs public void fun1int b systemoutprintlnint public void fun1boolean a systemoutprintlnboolean public static void mainstring args overloadingvarargs obj new overloadingvarargs objfun1 i believe there should be compile error in both the case but this is not so,['java'] +815743,handle 1 to and elements i am using xmltodict to parse an xml config the xml has structures where an element can occur in 1 to and instances where both are validitems itemrefabcitemrefitemsand items itemrefabcitemref itemrefdcaitemref itemrefabbitemrefitemsi am parsing this with xmltodict as followsdocumentitemsitemrefand it gives back a single unicode or a list depending the items found so i always need to add an extra check to ensure if i need to handle a list or a stringif isinstancedocumentitemsitemref list my var documentitemsitemrefelse my var documentitemsitemref create list manuallyis there a bettersimplermore elegant way to handle these,['python'] +815747,is multiplying by 01 the same as dividing by 10 in java is multiplying a double by 01 the same as dividing it by 10 my intuition is that there could be a difference because 01 cannot be represented exactly in a double,['java'] +815771,python pandas filter rows after groupby for example i have following tableindexab0108208310415after grouping by a0indexab01082081indexab315413what i need is to drop rows from each group where the number in column b is less than maximum value from all rows from groups column b well i have a problem translating and formulating this problem to english so here is the examplemaximum value from rows in column b in group 0 8so i want to drop row with index 0 and keep rows with indexes 1 and 2maximum value from rows in column b in group 1 5so i want to drop row with index 4 and keep row with index 3i have tried to use pandas filter function but the problem is that it is operating on all rows in group at one timedata example tablegrouped datagroupbyafiltered groupedfilterlambda x xb xbmaxso what i ideally need is some filter which iterates through all rows in group thanks for helpps is there also way to only delete rows in groups and do not return dataframe object,['python'] +815871,what does 0 represent in closures in swift i have seen closures in swift have 0 inside of it and sometimes they use 1 what exactly is 0 and what are other x can you usehere are examples of it in useapplymutliplication2 0 3arraymap0 1thanks,['ios'] +815895,searching an array string with a binary search sub string i have a filetxt containing about 20 recordsthe format of each record is 12345699text the 123456 are unique account numbers the 99 is a location code that i need it changes from 01 to 99 and the text is irrelevant these account numbers are sorted in order and with a line break in the file per ac1 12 13 etci made a visual studio textbox and search button to have someone search for the account number the account number is actually 11 digits long but only the first 6 matter i wrote this as string actnum textbox1textsubstring06i wrote a foreach string x in filereadlinefiletxt with an if xcontainsactnum then string code xsubstring82 statement the program works well but because there are so many records if someone searches an account number that doesnt exist or a number at the bottom of the list the program locks up for a good 10 seconds before going to the number not found else statement or taking forever to find that last recordmy questionreading about binary searches i have attempted to try one without much success i cannot seem to get the array or file to act like a legitimate binary search is there a way to take the 6 digit actnum from textbox1 compare it to an array substring of the 6 digit account number then grab the substring 99 code from that specific linea binary search would help greatly i could take 5 and compare it to the top or bottom half of the record file then keep searching until i fine the line i need grab the entire line then substring the 99 out the problem i have is i cant seem to get a proper integer conversion of the file because it contains both numbers and text and therefore i cant properly use signsany help on this would be greatly appreciated the program i currently have actually works but is incredibly slow at times,['c#'] +816043,does storing the strlength value in a variable before using it in a for loop have any performance improvements in java in short does the jvm internally optimize the following code public void teststring str int a 0 for int i 0 i 10 i a a strlength to behave as efficiently as the one below public void teststring str int len strlength int a 0 for int i 0 i 10 i a a len if it does optimize does it do so by caching the strlength value internally,['java'] +816049,stl containers move semantics and return by value how many times of copying get avoided away i know that in c11 the move semantics have been implemented in the stl containers to avoid temporary objects and people say that now it is perfect to write functions which return by value but i have some confusions about on earth how many times of copying are actually get avoided please see the following examplevectorint myvector vectorint res respush back4 respush back5 return resvectorint v myvector my understanding is that in c03 myvector returns a copy of res 4 5 copied once when evaluating vectorint v myvector vectorints copy constructor vectorintconst vectorint is invoked 4 5 copied twice however in c11 with move semantics i want to know which copy of 4 and 5 gets avoided both is return value optimization also invoked to reduce one time of copying 4 and 5,['c++'] +816064,setuptools finds wrong package during install in myriapython we use setuptools with install requires to configure which packages are needed in our particular setup file we include requeststoolbelt and requests in that listwhen we create a new virtual environment and then run python setuppy install it fails the first time with cannot find required thistribution requests this happens seemingly because pip identifies requests toolbelt031 note the space as the right match for package requestsrunning python setuppy install again seems to install requests after allhere is a github issue with a full log of the install procesteps to reproducegit clone cd myriapythonmkvirtualenv myriapythonpython setuppythe entire lab seems to have this issue however all of us use mac os x with either 109 or 1010 installed here are my machines specsos x 10101python 279 default dec 10 2014 234604 pip 156mkvirtualenv 16i was also able to duplicate it on one of our ubuntu serversubuntu 14041 lts and lpython 276pip 154mkvirtualenv 14here is the tail of the error logsearching for requeststoolbeltreading toolbeltbest match requeststoolbelt 031downloading processing requeststoolbelt031targzwriting varfoldersm qltd g 13qd1v5tvr4l6q2rc0gnteasy install2lqn7grequeststoolbelt031setupcfgrunning requeststoolbelt031setuppy q bthist egg thistdir varfoldersm qltd g 13qd1v5tvr4l6q2rc0gnteasy install2lqn7grequeststoolbelt031eggthisttmpriz25eno previouslyincluded directories found matching pycwarning manifest maker manifestin line 6 recursiveinclude expects dir pattern1 pattern2 warning manifest maker manifestin line 7 recursiveinclude expects dir pattern1 pattern2 no previouslyincluded directories found matching docs buildzip safe flag not set analyzing archive contentsadding requeststoolbelt 031 to easyinstallpth fileinstalled usersdhalperienvsmyriapython2libpython27sitepackagesrequests toolbelt031py27eggsearching for requestsbest match requests toolbelt031downloading processing requeststoolbelt031targzwriting varfoldersm qltd g 13qd1v5tvr4l6q2rc0gnteasy instalkxx9erequeststoolbelt031setupcfgrunning requeststoolbelt031setuppy q bthist egg thistdir varfoldersm qltd g 13qd1v5tvr4l6q2rc0gnteasy instalkxx9erequeststoolbelt031eggthisttmp3tgz5eno previouslyincluded directories found matching pycwarning manifest maker manifestin line 6 recursiveinclude expects dir pattern1 pattern2 warning manifest maker manifestin line 7 recursiveinclude expects dir pattern1 pattern2 no previouslyincluded directories found matching docs buildzip safe flag not set analyzing archive contentsrequeststoolbelt 031 is already the active version in easyinstallpthinstalled usersdhalperienvsmyriapython2libpython27sitepackagesrequests toolbelt031py27eggerror could not find required thistribution requestshow can i fix this so that the package installs without running setuppy twice,['python'] +816174,how to let the app know if its running unit tests in a pure swift project one annouting thing when running tests in xcode 61 is that the entire app has to run and launch its storyboard and root viewcontroller in my app this runs some server calls that fetch api data and i do not want the app to do this behaviour when its running its testswitch preprocessor macros gone whats the best for my project to be aware that it was launched running tests and not ordinary launch i run them normally with cmdu and on a bot pseudo code would be appdelegateswiftif runningtests return else do ordinary api calls,['ios'] +816187,the implementation of stdforward i am reading overview of the new c c14 pdf only at slide 288 it gives an implementation of stdforwardtemplatetypename t for lvalues t is tt stdforwardt param takereturn lvalue refs for rvalues t is t return static casttparam takereturn rvalue refsand then gives another implemention in textthe usual stdforward implementation istemplatetypename tstruct identity typedef t typetemplatetypename tt forwardtypename identityttype param return static castidentityttypeparam what is the difference why is latter the usual implementation,['c++'] +816199,nodejs 100 cpu i have a problem with my nodejs application i am using websocket to transfer data to mysql and all works good and fast till the time when node will raise to consume 100 cpu such 100 take a long time about 1 hour and during this all communications between server and websockets are much slow down somebody know where is reason and how to resolve ithere are screens from servertop commandprofiler,['javascript'] +816489,why do i need a tolist to avoid thisposed context errors i am writing some code to access a database using entityframework the code ispublic ienumerablerows getrowsint id using var context new applicationdbcontext var repository new entityframeworkrepositoryint rowentitycontext need a tolist here to prevent thisposed dbcontext errors return repositorygetrowsfromdbidtolist getrowsfromdb uses linq to query the database and filter the results using idi originally wrote the above method without the tolist call but when i tried to access objects in the ienumerable which was returned i would get an exception about the dbcontext already being thisposed i do not understand how the above code fixes things although it does then work i assume tolist is deep copying the object and that this perhaps provides the required separation from the contextdatabase but surely the original object should be usable,['c#'] +816502,is there a pattern for dealing with mainframe data note clarified some of my question at the bottomi am wondering if there might be a sane pattern to deal with requestresponse from older mainframe systems in the examples below iq is the request and rsiq is the response in the first example i am requesting a list of all account codes and in the second request i am asking for the closed date for each account code since these are only linked by the ordinal position it is easy enough to pull the data into a structured data class each response in this case represents multiple recordsin the 2nd example i am requesting several bits of information for a single record in this case each response represents a single record and a smattering of data pointsthis is the message a client sends to the server to request specific information from the database the inquiry message has this general formatiqmsg idaunitbdevice typedacctfpasswordgfilehhierarchicrecordpathjfieldone field from many recordsbeginning with first share ordinal zero on account 101 return all the share id fields in firstmessage then get all close dates in second message ids and close dates correspondpositionally within the two responsesiq1a0bvendord101f7hshare0jidallrsiq1k0jid0jid03jid04jid05jid0025jid0050iq1a0bvendord101f7hshare0jclosedateallrsiq1k0jclosedate0jclosedate20030601jclosedate0jclosedate0jclosedate0jclosedate0many fields from one recordusing the previous requests get additional information from open shares two examplesiq1a0bvendord101f7hshare05jclosedatejsharecodejdivtypejbalancejavailablebalancersiq1k0jclosedate0jsharecode0jdivtype2jbalance234567javailablebalance234567iq1a0bvendord101f7hshare0025jclosedatejsharecodejdivtypejbalancejavailablebalancersiq1k0jclosedate0jsharecode1jdivtype5jbalance654321javailablebalance654321background i am already using the unit of workrepository pattern in my applications each application is dealing with multiple data stores sql dbs files web services sockets etc the idea being that each repository exposes a part of the full data modelmy initial thinking is to create the specific calls i need in the repository like getaccountsacctid and have the method send the correct requests and then build up the object graph from all the reponses finally returning the object graph i am now looking for a design pattern to handle the internals of each of these methods without doing a ton of stringreplace statements or stringbuilder calls since the max size of any request is 80 characters you can see where the j fields can get quite complex and i am still looking for all the possible codes that can go in the j fieldssmallish examplepublic listsymitaraccount getaccountsstring accountid var retaccounts new listsymitaraccount is there a pattern to do this repetitve but ever changing task example mock response then handle note there will be many requestresponse calls here not just one var rsp rsiq1k0jclosedate0jsharecode1jdivtype5jbalance654321javailablebalance654321 var response rspsplitnew foreach var q in response if qstartswithj qcontains get key value pair map kvp to symitaraccount data point big ugly switch said kvp for id sabalanace kvp for balance retaccountsaddsa return retaccountsany thoughts or ideasnote i am using c latestaddition 1public listsymitaraccount getaccountsstring accountid var retaccounts new listsymitaraccount get all account ids var response unitofworksendmessageiq1a0bvendord101f7hshare0jidall parseresponseresponse ref retaccounts get all account close dates 0 means it is open response unitofworksendmessageiq1a0bvendord101f7hshare0jclosedateall parseresponseresponse ref retaccounts get extra info for all open accounts foreach var account in retaccountswherea aisclosed var request iq1a0bvendord101f7hshareacctjclosedatejsharecodejdivtypejbalancejavailablebalance request requestreplaceacct accountidtostring0 response unitofworksendmessagerequest parseresponseresponse ref retaccounts accountid return retaccountsprivate void parseresponsestring response ref listsymitaraccount accountlist int id null var list responsesplitnew var index 0 var chain new chaininquiryaccountinfo var parser chainparser foreach var q in listwhereq qstartswithj qcontains if accountlistcount index accountlistindex null accountlistaddnew symitaraccount positionalindex index var val qsplitnew if idhasvalue accountlistindexid idvalue idhasvalue accountlistindex parserparseval accountlistindex index,['c#'] +816510,stdresult of for builtin operators what is the proper syntax for determining result of something like int or doubledouble via result ofthis failsstdresult ofoperatorinttypestdresult ofoperatordoubledoubletype,['c++'] +816672,backbone model state when tied to a form i am building a form with backbone and looking to have it validate its fields on the blur eventhooking into the event is easy enough but what i am curious about is whether or not the model should be updated on blur or only when the form is submittedupdating model on blurmodelset validatetrueif your model has multiple attributes validation will be run for all of them every timewhen creating a new item the model state is not as important because it is probably not shared with any other modules yetwhen editing an item the model is in this weird outdatedupdated state depending on where the person is in the form what if the model is being shared between multiple modulesupdating model on submitcannot use modelset for validation so the model needs to expose some validation methods eg mymodelvalidzipon submit even though all fields have been validated set needs to be called to update the model which will cause validation to happen one more time not entirely sure this is bad thoughi have read through a couple of relevant backbone github issues 1 2 3 and backbone devs seem to draw a line between a model and a form additionally the backboneform plugin appears to keep an internal fields property to track the form fields and when done call commit to update the modelso it seems like updating the model on submit is the better approach is that the experience youve had,['javascript'] +816686,debugging jsx using browser plugins is there a way to debug jsx filesi am unable to see the jsx files when i check the resources tab in either safari chrome can we use a debugger,['javascript'] +816692,add class to all elements with a certain class i am a bit new to javascript and jquery and i have some troubles doing what i want in a nice wayi have a html web page like thisdiv classlistgroup a hrefall idcategoryall classlistgroupitem activealla a href idcategory0 classlistgroupitemfooa a href idcategory1 classlistgroupitembara a href idcategory2 classlistgroupitemfoobaradivdiv classrow div classcategory0element 1div div classcategory1element 1div div classcategory1element 1div div classcategory0element 1div div classcategory2element 1div div classcategory0element 1div div classcategory2element 1divdivi would like to add some kind of filter where if you click on a certain category link all elements from other categories will thisappeari managed to do it by adding a class to my css called invis with thisplaynone and then wrote this listgroupitem clickfunction listgroupitemremoveclassactive this toggleclassactive var test eventtargetid category0addclassinvis category1addclassinvis category2addclassinvis if test category0 category0removeclassinvis if test category1 category1removeclassinvis if test category2 category2removeclassinvis if test categoryall category0removeclassinvis category1removeclassinvis category2removeclassinvis this does the job but i would like to find a cleaner way of doing it how can i improve itthanks,"['javascript', 'jquery']" +816889,how to show buffered data on uislider using mpmovieplayercontroller in ios i am using mpmovieplayercontroller to play audio and i want to show the buffered data on slider like this i want to show the buffer data like red section in slider i have tried to google it but i did not get any solution for it and how to make slider customizethanks in advance,"['ios', 'objective-c', 'iphone']" +817060,highlighting all rowspans within a table row using css only is there a way of getting the css to highlight the entire row including the cells within the rowspans rather than just the first lineas you can see from the example only the first line of the row is highlighted but not the other cells this obviously looks quite messy and i would rather be able to clear it up using css only but will use javascript if there is no other wayhtmltable classtb stylewidth 100 border1 cellpadding10 cellspacing10 tbody tr tdpackagetd tdincludestd tdnumber of recruitstd tdcost per recruit vattd tr tr td rowspan4lorem ipsum dolor sit amettd td rowspan4aenean commodo ligula eget dolor aenean massa cum sociis natoque penatibus et magnis this parturient montes nascetur ridiculus mus donec quam felis ultricies nec pellentesque eu pretium quis sem nulla consequat massa quis enim donec pede justo fringilla vel aliquet nec vulputate eget arcu in enim justo rhoncus ut imperdiet a venenatis vitae justo nullam dictum felis eu pede mollis pretium integer tincidunt cras dapibus vivamus elementum semper nisitd td20td tda105td tr tr td10a19td tda120td tr tr td6a9td tda135td tr tr td1a5td tda150td tr tr td rowspan4lorem ipsum dolor sit amettd td rowspan4aenean commodo ligula eget dolor aenean massa cum sociis natoque penatibus et magnis this parturient montes nascetur ridiculus mus donec quam felis ultricies nec pellentesque eu pretium quis sem nulla consequat massa quis enim donec pede justo fringilla vel aliquet nec vulputate eget arcu in enim justo rhoncus ut imperdiet a venenatis vitae justo nullam dictum felis eu pede mollis pretium integer tincidunt cras dapibus vivamus elementum semper nisitd td20td tda175td tr tr td10a19td tda200td tr tr td6a9td tda225td tr tr td1a5td tda250td tr tr td rowspan2lorem ipsum dolor sit amettd td rowspan2aenean commodo ligula eget dolor aenean massa cum sociis natoque penatibus et magnis this parturient montes nascetur ridiculus mus donec quam felis ultricies nec pellentesque eu pretium quis sem nulla consequat massa quis enim donec pede justo fringilla vel aliquet nec vulputate eget arcu in enim justo rhoncus ut imperdiet a venenatis vitae justo nullam dictum felis eu pede mollis pretium integer tincidunt cras dapibus vivamus elementum semper nisitd td20td tda220 40 payable upfronttd tr tr td10a19td tda275 40 payable upfronttd tr tr td rowspan2lorem ipsum dolor sit amettd td rowspan2aenean commodo ligula eget dolor aenean massa cum sociis natoque penatibus et magnis this parturient montes nascetur ridiculus mus donec quam felis ultricies nec pellentesque eu pretium quis sem nulla consequat massa quis enim donec pede justo fringilla vel aliquet nec vulputate eget arcu in enim justo rhoncus ut imperdiet a venenatis vitae justo nullam dictum felis eu pede mollis pretium integer tincidunt cras dapibus vivamus elementum semper nisitd td20td tda300 40 payable upfronttd tr tr td10a19td tda375 40 payable upfronttd tr tr tdlorem ipsum dolor sit amettd tdaenean commodo ligula eget dolor aenean massa cum sociis natoque penatibus et magnis this parturient montes nascetur ridiculus mus donec quam felis ultricies nec pellentesque eu pretium quis sem nulla consequat massa quis enim donec pede justo fringilla vel aliquet nec vulputate eget arcu in enim justo rhoncus ut imperdiet a venenatis vitae justo nullam dictum felis eu pede mollis pretium integer tincidunt cras dapibus vivamus elementum semper nisitd tdbr td tdbr td tr tbodytablecssbody padding 50pxtable width 100 bordercollapse collapsetd th padding 20px border 1px solid blacktrhover td backgroundcolor blue,['css'] +817078,calling protected ctor of inheriting class from within static template method of base class fails i have a component class that defines a static template method of how a component should be created in generalclass component protected uint32 t id componentuint32 t id idid templatetypename t uint32 t c static t createcomponent content here not relevant return new tsomeparameter then there is an implementation for example a button the constructor of this class should not be used directly instead there is a static method that calls the componentcreatecomponent template functionclass button public component protected buttonuint32 t id componentid public static button createthe implementation looks like this passing the type to instantiate and a constant thats used in creationbutton buttoncreate return createcomponentbutton ui component buttonnow the problem is that the compiler complains with error buttonbuttonuint32 t is protected for my understanding this constructor call should be ok as button extends component but this seems to be a problem herehow can i solve this,['c++'] +817094,how to do django json web token authentication without forcing the user to retype their password my django application uses the rest framework jwt for authentication it works great and very eleganthowever i have a usecase which i am struggling to build i have already coded up a working solution for the forgot password workflow i allow an unauthenticated user to reset their password ifandonlyif they click on a secret link that i send to their email address however i would like to modify this solution such that after the passwordreset workflow is successfully completed the user is automatically logged in without having to retype their username and new password i would like to do this to make the users experience as frictionless as possiblethe problem is i do not know how to make this work without having the user retype their password or storing it in cleartext in the db which is obviously very bad below is the current way i get the jwt token you can see that in line 12 i need the users clear password i do not have it i only have the encrypted password stored in my userpassword how can i use the encrypted password in my userpassword instead of the clear password to obtain the jwt if i cannot use it then how is this workflow achieved using the rest framework jwtfrom rest framework jwtviews import obtainjsonwebtokenfrom rest framework statusfrom djangocontribauthmodels import usermy user userobjectsgetpk1ojwt obtainjsonwebtokenif mutable in dirrequestdata mutable requestdata mutable requestdata mutable truerequestdatausername my userusernamerequestdatapassword my users clear passwordif mutable in dirrequestdata requestdata mutable mutabletoken response ojwtpostrequestif statusis successtoken responsestatus code tell the user login succeededelse tell the user login failed but hopefully this should not happen,['python'] +817100,applets embedding and the bokehserver there seem to be at at least two or three major ways of building apps that communicate with bokehserver in bokeh they correspond to the folders app embed and plottingglyphs under the examples directory in bokeh on the differences between them i read here the followingon the stock apy app folder example you are using bokehserver to embed an applet and serve it from the url you specify that is why you crate a new stockapp class and create a function that creates a new instance of it and decorates it with bokeh approutebokehstocks and object pagestocks you can follow the app examples sliders stock and crossfilter and use bokeh object page and bokeh approute decorators to create your custom url on the taylor serverpy example glyphs folder it is the session object that is taking care of creating everything on bokehserver for you from this interface is not possible to customize urls or create aliasbut this confused me what is meant by an applet embedding in bokeh terminology and what isexactly he difference between applets presumably app and embed and plottingglyphsalso i thought that the notion of embedding only referred to the design pattern that we see in the embed folder as in the example animatedpy where we embed a tag in the body of an html file i do not see that in the stock apy so why is it an embedding example,['python'] +817119,qt charts rendering problems on a pdf i am using qt charts module to draw a pie chart directly on a pdf file heres the problem for some unknown reason the chart needs to be thisplayed with show before it is rendered to the pdf for it is size to be ok left imageon the other hand i do not want to have to thisplay every chart on the screen since my application generates a lot of them however if the chart is not thisplayed in a window with show then the drawing gets too small in the pdf right image even though the size of the chart is properly set with resize black borders were added to these images to improve visualizationthisplaying all charts on a window before they are rendered to the pdf is not an option the fact that the chart needs to execute show for qpainter to draw it to the pdf correctly seems to indicate that without it qpainter ignores the charts dimensionon a side note show opens the window but it takes several seconds for thechart to appear so rendering is very very slow another reason for me not to want to thisplay the chartsso here are my main questionsare these bugs or am i missing somethingif not what would be the proper way to specify the size and xy position of the drawing inthe pdfhere is a minimal complete and verifiable examplemaincppinclude qapplicationinclude qtchartsqchartviewinclude qtchartsqpieseriesinclude qtchartsqpiesliceinclude qpainterinclude qpdfwriterint mainint argc char argv qapplication aargc argv qtchartsqchartview chartview new qtchartsqchartview chartviewsetrenderhintqpainterantialiasing chartviewresize640 480 qtchartsqchart chart chartviewchart chartsettitlebeautiful pie chart chartlegendhide qtchartsqpieseries series new qtchartsqpieseries float hits 730f misses 270f seriesappendhits hits seriesappendmisses misses qtchartsqpieslice hit slice seriesslicesat0 hit slicesetbrushqcolor87 147 243 blue qtchartsqpieslice miss slice seriesslicesat1 miss slicesetbrushqcolor221 68 68 red chartaddseriesseries due to qt bug must show the chart before render or it will be draw too tiny in the pdf by qpainter chartviewshow qpdfwriter writeroutpdf writersetcreator writersetpagesizeqpagedpaintdevicea4 qpainter painterwriter chartviewrenderpainter painterend return aexecqtcharts pdfproqt core gui chartsgreaterthanqt major version 4 qt widgetstarget qtcharts pdftemplate appsources maincpp,['c++'] +817304,how to connect to a remote mysql database via ssl using play framework i deploy play applications in thistributed environments backed by a remote mysql database specifically the applications are hosted on heroku and the database is on amazon rds though this really applies to any remote database connection since the database is not just on localhost i would prefer that the remote mysql connection is made through ssl for security given a ca certificate to trust how can i configure a play application to connect to the mysql server through ssl only if the host certificate can be verified assume this as the current database configurationdbdefaultdrivercommysqljdbcdriverdbdefaulturljdbcmysqlurltodatabasetest dbdbdefaultuserroot dbdefaultpassword,"['java', 'mysql']" +817372,how can i add an instance method to all models in sailsjs i would like to add a default tothisplay function to all models which will use metadata not unlike attributeassociation definitions to perform manipulations on the instances attributesassociations making them suitable for thisplay in the ui for examplefoofindonesomeid execfunctionerr foo resview foo footothisplay so i would like to add this function too all models i can imagine a modelprototypetothisplay solution but i am not sure where to get model from some long requirewaterlinemodel path and if i had model where to put that snipit please advise,['javascript'] +817383,springdataelasticsearch metadata annotations for version id etc using the id annotation i can add an id field to my model object and when i execute a query the resulting model object will contain the value of the elasticsearch id in the id annotated fieldhowever i have yet to figure out how to get other document metadata such as the version i tried adding a version field to my model and annotating it with the version annotation but nothing happened and the field remained null index twitter type tweet id 1 version 1 found true source user kimchy postdate 200915t141212 message trying out elasticsearch i am referring to the fields such as index type id version etci am especially concerned with version because that is used for optimistic lockingit seems to me that if id is supported then version and the other metadata fields should be supported somehow tooi have just read the springdataelasticsearch docs and i cannot find anything if someone knows please adviseare all of the elasticsearch document metadata fields supported in springdataelasticsearch if so howfurther if i can get the version somehow then how can i use it for optimistic locking when using springdataelasticsearchthanks,['java'] +817407,order of loading contextconfiglocation in webxml of spring servlet project suppose that i have a spring java project and i am trying to configure it as a web server servlet here is a strippeddown version of the webxml filecontextparam paramnamecontextconfiglocationparamname paramvalue webinfspringgeneralapplicationcontextxml paramvaluecontextparamservlet servletnamemyservletservletname servletclassorgspringframeworkwebservletthispatcherservletservletclass initparam paramnamecontextconfiglocationparamname paramvaluewebinfspringspecificapplicationcontextxmlparamvalue initparam loadonstartup1loadonstartupservletservletmapping servletnamemyservletservletname urlpatternfoourlpatternservletmappingthe key thing to note here is that i have specified two xml files to be loaded one is general for my entire application while the other is specific to the myservlet servlet for a setup with just one servletmapping this wouldnt make sense however my project has multiple servletmappings and each one has specific spring settings to themmy question which contextconfiglocation is going to be loaded first by spring will it be the generalapplicationcontextxml or will it be the specificapplicationcontextxml more importantly does the order of loading even matter from my debugging efforts it seems apparent that it does because i get different errors when i move some independent spring configuration from one file to the othernb whether or not using multiple spring configurations for multiple servlet mappings is a good practice is debatable same goes for using xml config instead of the new java config but that is not what i am trying to ask here let us try to focus on my main question,['java'] +817447,what is the usage of angular directive novalidate in a form html tag i wanted to understand the meaning of novalidate directive usage in form tag especially when used to validate the formthanks,['html'] +817455,when to use show segues when to use show detail segues i am new to ios development i am confused between when to use show segue when to use show detail segue both them are used in the default masterdetail projectso when do we use either of them what is the best case to use show segue when to use show detail segue,['ios'] +817473,what is the best way of create and test a library project in android studio to share in any project in android studio 101 you only have the initial option of create a new project but not a new libraryi would like create a library that i can share with multiple and future appsmust i create a new project and create library modules insidecan create only a library projectif a library only have a custom view how i testing with androidtest using an activity activity should not compile into librarythanks,['android'] +817548,referencing fixture record in yii2codeception data files is there a way to specify a related row of another fixture in fixture data file in yii2codeception activefixture consider this example of userprofile relationuserphpreturn user1 email profilephpuse commonmodelsuserreturn profile1 user id userfindoneemail id name my name the documentation states that you may give an alias to a row so that later in your test you may refer to the row via the alias is there a way to reference rows inside another fixture for example use something like thisuseruser1id in profilephp i could not find any mention on how to do that how do you create this kind of related fixtures,['php'] +817564,how does type inference work with overloaded generic methods i have these classes data classes public class data public int id get set public class infodatatinfo data where tinfo infobase public tinfo info get set info classes public abstract class infobase public int id get set public interface irelated ilistinfobase related get setpublic class extrainfo infobase irelated public string extras get set public ilistinfobase related get set then i have two generic methods with this signaturepublic tdata addtdatatdata data where tdata datapublic tdata addtdata tinfotdata data where tdata infodatatinfo where tinfo infobase irelatednow when i create an instance of data class and call add method data is of type dataadatathe first generic method is used and generic type data is correctly inferredbut when i call the same method with a more implemented type object instance data is of type infodataextrainfo extrainfo is of type infobase and implements irelatedadatai would expect the second generic method to be invoked but to my surprise it is not if i check generic type constraints on the second one beingwhere tdata infodatatinfowhere tinfo infobase irelatedthe first one matches and the second one as well and these types are more implemented than simple data type if that makes any differenceworking examplehere is a working net fiddle for you to play withquestionswhy is second method not being called because both generic type constraints match and could be inferredhow can i rewrite my second add method so type inference would work and would not have to explicitly provide these types just to make sure that correct overload is being usedediti have found the answer to my first question in msdn documentationthe compiler can infer the type parameters based on the method arguments you pass in it cannot infer the type parameters only from a constraint or return valuein my case the first generic type can be inferred directly from parameter but second one is more tricky it cannot be inferred from parameter only type constraint should be used but compiler does not evaluate iti also have one possible solution to my second question that changes one type to concrete and keeps the other one genericpublic infodatatinfo addtinfoinfodatatinfo data where tinfo infobase irelatedbut i am wondering if there is a more generalgeneric way of mitigating around this problem so i can still keep both type parameters but somehow have both types as generic,['c#'] +817656,angular js currency symbol euro after how to move the symbol euro from the front of the value to after itexampleproductprice currency a will produce a 1200but i would like 1200 a,['javascript'] +817697,android compiled resources resourcesarsc i am trying to figure out what it mean to compile resourceswhat i did in order to understand this issuei have read many articles about the subject but did not find a simple answerthe best one i have read was this how does the mapping between android resources and resources id workhow i understand itfrom my understanding when we compile our project either by ant eclipse or gradle aswe use a tool called aapt android asset packaging tool whichis used to generate unique ids for each of our resources such as our layouts our styles and more and store them in a lookup table then it persists this lookup table by generating two files 1 it generates the rjava file with these unique ids so we will be able to use our resources from our java code during compilation 2 it generate the resourcesarsc file which can be found in resourcesap filethis resourcesarsc file will later be packed by the apktool to the apkthis arsc file format is a format that will be easily mapped and parsed by the device at runtimean exampleso to make it simple lets say i have this in my activity mainxml textview androidididmy textview androidtextstringhello world androidlayout widthwrap content androidlayout heightwrap content and i call it from my oncreate usingfindviewbyidridmy textviewin my rjava file i will seepublic static final int my textview0x7f08003fusing aapt dump resources on the generated apk i can see it contains two lines with my textviewec resource 0x7f08003f comexampleliziliortest2idmy textview flags0x0resource 0x7f08003f comexampleliziliortest2idmy textview t0x12 d0x0 s0x08 r0x00what i do not understandi would have thought that this resourcesarsc file will not just contain the resource id but also all the properties i have defined for the view such as androidlayout widthwrap contentso now during runtime when the vm tries to run findviewbyidridmy textviewhow does it know which view to get its properties to createi simply cannot understand how it works should not this lookup table contain also the properties dataand what is this 0x7f08003f number should it represent a value that will later be mapped to physical memory in which the object will be storedi have no idea can some1 please enlighten me,['android'] +817734,add androidnamesomething to androidmanifestxml application tag from cordova pluginxml i decided to open new question because none of those that are already posted has a good answeri need to update androidmanifestxml from pluginxml so that the application tag has the following property alongside those it already hasandroidnamemypackagehow can do thatthank you,['android'] +817766,android themeappcompatlight with dark toolbar for light text i have an app using themeappcompatlight which i need to use so dialogs have the light theme but this makes the text in my toolbar black where i would rather it be white i have tried setting the toolbars specific apptheme to appcompatdarkactionbar but no luck i searched around for a while and could not find a specific question and answer to thisheres my default appthemestyle nameappthemeparent parentthemeappcompatlightnoactionbar item namecolorprimarycolorblueitem item namecolorprimarydarkcolordark blueitem item namecoloraccentcolorpinkitem item nameandroidwindownotitletrueitem item namewindowactionbarfalseitemstyleheres my toolbarxmlandroidsupportv7widgettoolbar xmlnsandroid xmlnsapp androidlayout widthmatch parent androidlayout heightwrap content androidbackgroundattrcolorprimary androidminheightdimenabc action bar default height material appthemestylethemeoverlayappcompatdarkactionbar apopupthemestylethemeoverlayappcompatlight,['android'] +817935,why cannot you omit the array size in a new initializer this is allowedint a1 2 3but not thisauto a new int1 2 3you have to specify the bounds whyedit the proper syntax that does not compile isauto a new int1 2 3this gives the real error message which iserror invalid use of array with unspecified bounds,['c++'] +817954,how is a tuple different from a class how is a tuple different from a class instead of the following code we can make a class with 3 fields and make objects from it how is this tuple different from that is it only reducing the code we write or does it have something to do with speed as well given the fact that you cannot change the items in a tuple tupleint string bool tuple new tupleint string bool1 cat true,['c#'] +817963,crash at startup on port to cordova crosswalk android i am porting an existing android cordova app to cordova crosswalkusing cordova 4 crosswalkcordova10392359x86 and android sdk 19the app crashes at startup with the following logs in logcatdandroidruntime 7208 shutting down vmwdalvikvm 7208 threadid1 thread exiting with uncaught exception group0x41caeda0eandroidruntime 7208 fatal exception maineandroidruntime 7208 process myappcqa pid 7208eandroidruntime 7208 javalangexceptionininitializererroreandroidruntime 7208 at orgapachecordovacordovaactivitymakewebviewcordovaactivityjava295eandroidruntime 7208 at orgapachecordovacordovaactivityinitcordovaactivityjava348eandroidruntime 7208 at orgapachecordovacordovaactivityinitcordovaactivityjava323eandroidruntime 7208 at myappcqacordovaapponcreatecordovaappjava31eandroidruntime 7208 at androidappactivityperformcreateactivityjava5451eandroidruntime 7208 at androidappinstrumentationcallactivityoncreateinstrumentationjava1093eandroidruntime 7208 at androidappactivitythreadperformlaunchactivityactivitythreadjava2358eandroidruntime 7208 at androidappactivitythreadhandlelaunchactivityactivitythreadjava2452eandroidruntime 7208 at androidappactivitythreadaccess900activitythreadjava172eandroidruntime 7208 at androidappactivitythreadhhandlemessageactivitythreadjava1302eandroidruntime 7208 at androidoshandlerthispatchmessagehandlerjava102eandroidruntime 7208 at androidoslooperlooplooperjava136eandroidruntime 7208 at androidappactivitythreadmainactivitythreadjava5586eandroidruntime 7208 at javalangreflectmethodinvokenativenative methodeandroidruntime 7208 at javalangreflectmethodinvokemethodjava515eandroidruntime 7208 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava1268eandroidruntime 7208 at comandroidinternaloszygoteinitmainzygoteinitjava1084eandroidruntime 7208 at dalviksystemnativestartmainnative methodeandroidruntime 7208 caused by javalangruntimeexception javalangruntimeexception use sharedxwalkview if you want to support shared modeeandroidruntime 7208 at orgxwalkcorereflectionhelperhandleexceptionreflectionhelperjava233eandroidruntime 7208 at orgxwalkcorereflectionhelperhandleexceptionreflectionhelperjava237eandroidruntime 7208 at orgxwalkcorereflectionhelperinitreflectionhelperjava132eandroidruntime 7208 at orgxwalkcorereflectionhelperloadclassreflectionhelperjava199eandroidruntime 7208 at orgxwalkcorexwalkpreferencessetvaluexwalkpreferencesjava112eandroidruntime 7208 at orgapachecordovacordovawebviewclinitcordovawebviewjava890eandroidruntime 7208 18 moreeandroidruntime 7208 caused by javalangruntimeexception use sharedxwalkview if you want to support shared modeeandroidruntime 7208 23 moreany idea why it crashes,['android'] +818000,pgduplicatetable error when i run rake dbmigrate i get following output 20141219011612 createpost migrating create tableposts rake aborted standarderror an error has occurred this and all later migrations canceled 20141219011612 postposts migrating create tableposts rake aborted standarderror an error has occurred this and all later migrations canceledpgduplicatetable error relation posts already exists create table posts id serial primary key post text release date timestamp created at timestamp updated at timestamp homeadminrvmgemsruby215gemsactiverecord418libactive recordconnection adapterspostgresqldatabase statementsrb128in async exec homeadminrvmgemsruby215gemsactiverecord418libactive recordconnection adapterspostgresqldatabase statementsrb128in block in execute homeadminrvmgemsruby215gemsactiverecord418libactive recordconnection adaptersabstract adapterrb373in block in log homeadminrvmgemsruby215gemsactivesupport418libactive supportnotificationsinstrumenterrb20in instrument homeadminrvmgemsruby215gemsactiverecord418libactive recordconnection adaptersabstract adapterrb367in log homeadminrvmgemsruby215gemsactiverecord418libactive recordconnection adapterspostgresqldatabase statementsrb127in execute homeadminrvmgemsruby215gemsactiverecord418libactive recordconnection adaptersabstractschema statementsrb205in create table homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb649in block in method missing homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb621in block in say with time homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb621in say with time homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb641in method missing homeadmindesktoppostrdbmigrate20141219011612 post postsrb3in up homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb598in exec migration homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb579in block 2 levels in migrate homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb578in block in migrate homeadminrvmgemsruby215gemsactiverecord418libactive recordconnection adaptersabstractconnection poolrb294in with connection homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb577in migrate homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb752in migrate homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb991in block in execute migration in transaction homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb1037in block in ddl transaction homeadminrvmgemsruby215gemsactiverecord418libactive recordconnection adaptersabstractdatabase statementsrb201in block in transaction homeadminrvmgemsruby215gemsactiverecord418libactive recordconnection adaptersabstractdatabase statementsrb209in within new transaction homeadminrvmgemsruby215gemsactiverecord418libactive recordconnection adaptersabstractdatabase statementsrb201in transaction homeadminrvmgemsruby215gemsactiverecord418libactive recordtransactionsrb208intransaction homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb1037in ddl transaction homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb990in execute migration in transaction homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb952in block in migrate homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb948in each homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb948in migrate homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb807in up homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb785in migrate homeadminrvmgemsruby215gemsactiverecord418libactive recordrailtiesdatabasesrake34in block 2 levels in activerecordstatementinvalid pgduplicatetable error relation posts already exists create table posts id serial primary key post text release date timestamp created at timestamp updated at timestamp homeadminrvmgemsruby215gemsactiverecord418libactive recordconnection adapterspostgresqldatabase statementsrb128in async exec homeadminrvmgemsruby215gemsactiverecord418libactive recordconnection adapterspostgresqldatabase statementsrb128in block in execute homeadminrvmgemsruby215gemsactiverecord418libactive recordconnection adaptersabstract adapterrb373in block in log homeadminrvmgemsruby215gemsactivesupport418libactive supportnotificationsinstrumenterrb20in instrument homeadminrvmgemsruby215gemsactiverecord418libactive recordconnection adaptersabstract adapterrb367in log homeadminrvmgemsruby215gemsactiverecord418libactive recordconnection adapterspostgresqldatabase statementsrb127in execute homeadminrvmgemsruby215gemsactiverecord418libactive recordconnection adaptersabstractschema statementsrb205in create table homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb649in block in method missing homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb621in block in say with time homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb621in say with time homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb641in method missing homeadmindesktoppostrdbmigrate20141219011612 post postsrb3in up homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb598in exec migration homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb579in block 2 levels in migrate homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb578in block in migrate homeadminrvmgemsruby215gemsactiverecord418libactive recordconnection adaptersabstractconnection poolrb294in with connection homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb577in migrate homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb752in migrate homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb991in block in execute migration in transaction homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb1037in block in ddl transaction homeadminrvmgemsruby215gemsactiverecord418libactive recordconnection adaptersabstractdatabase statementsrb201in block in transaction homeadminrvmgemsruby215gemsactiverecord418libactive recordconnection adaptersabstractdatabase statementsrb209in within new transaction homeadminrvmgemsruby215gemsactiverecord418libactive recordconnection adaptersabstractdatabase statementsrb201in transaction homeadminrvmgemsruby215gemsactiverecord418libactive recordtransactionsrb208intransaction homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb1037in ddl transaction homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb990in execute migration in transaction homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb952in block in migrate homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb948in each homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb948in migrate homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb807in up homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb785in migrate homeadminrvmgemsruby215gemsactiverecord418libactive recordrailtiesdatabasesrake34in block 2 levels in pgduplicatetable error relation posts already exists homeadminrvmgemsruby215gemsactiverecord418libactive recordconnection adapterspostgresqldatabase statementsrb128in async exec homeadminrvmgemsruby215gemsactiverecord418libactive recordconnection adapterspostgresqldatabase statementsrb128in block in execute homeadminrvmgemsruby215gemsactiverecord418libactive recordconnection adaptersabstract adapterrb373in block in log homeadminrvmgemsruby215gemsactivesupport418libactive supportnotificationsinstrumenterrb20in instrument homeadminrvmgemsruby215gemsactiverecord418libactive recordconnection adaptersabstract adapterrb367in log homeadminrvmgemsruby215gemsactiverecord418libactive recordconnection adapterspostgresqldatabase statementsrb127in execute homeadminrvmgemsruby215gemsactiverecord418libactive recordconnection adaptersabstractschema statementsrb205in create table homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb649in block in method missing homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb621in block in say with time homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb621in say with time homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb641in method missing homeadmindesktoppostrdbmigrate20141219011612 post postsrb3in up homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb598in exec migration homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb579in block 2 levels in migrate homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb578in block in migrate homeadminrvmgemsruby215gemsactiverecord418libactive recordconnection adaptersabstractconnection poolrb294in with connection homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb577in migrate homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb752in migrate homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb991in block in execute migration in transaction homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb1037in block in ddl transaction homeadminrvmgemsruby215gemsactiverecord418libactive recordconnection adaptersabstractdatabase statementsrb201in block in transaction homeadminrvmgemsruby215gemsactiverecord418libactive recordconnection adaptersabstractdatabase statementsrb209in within new transaction homeadminrvmgemsruby215gemsactiverecord418libactive recordconnection adaptersabstractdatabase statementsrb201in transaction homeadminrvmgemsruby215gemsactiverecord418libactive recordtransactionsrb208intransaction homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb1037in ddl transaction homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb990in execute migration in transaction homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb952in block in migrate homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb948in each homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb948in migrate homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb807in up homeadminrvmgemsruby215gemsactiverecord418libactive recordmigrationrb785in migrate homeadminrvmgemsruby215gemsactiverecord418libactive recordrailtiesdatabasesrake34in block 2 levels in tasks top dbmigrate see full trace by running task with tracei do not understund how this is possible bescause in scheme file i do not have post table,['ruby-on-rails'] +818054,ngflow upload programmatically i am currently using ngflow to perform a file upload it appears that the default action of selecting a file is to upload immediately i would like to override this so that files are selected and only uploaded on button click perhaps i am misreading the documentation but thus far i have the followingdiv flowinittarget upload flowfilessubmittedflowupload flowfilesuccessfilemsg message input typefile flowbtn input or other element as upload button span classbtn flowbtnupload filespan table tr ngrepeatfile in flowfiles tdindex1td tdfilenametd tdfilemsgtd tr tabledivthis appears to work and i can see the network request going out i located flowjs upload file on click and attempted to follow the suggested answer however flow was undefined in the respective functionso how does one programmatically upload files using ngflow,['javascript'] +818056,composition of method reference this is related to this question how to do function compositioni noticed that a method reference can be assigned to a variable declared as function and so i assume it should have andthen or compose function and hence i expect that we can compose them directly but apparently we need to assign them to a variable declared as function first or typecast before invocation before we can call andthen or compose on themi suspect i might have some misconception about how this should workso my questionswhy do we need to typecast or assign it to a variable first before we can call the andthen methodwhat exactly is the type of method reference that it needs to be done in this waysample code belowpublic class mymethods public static integer tripleinteger areturn 3a public static integer quadrupleinteger areturn 4a public int operateint num functioninteger integer f return fapplynum public static void mainstring args mymethods methods new mymethods int three methodsoperate1 mymethodstriple this is fine error below int twelve methodsoperate1 mymethodstripleandthenmymethodsquadruple but this one is fine functioninteger integer triple mymethodstriple functioninteger integer quadruple mymethodsquadruple int twelve methodsoperate1 tripleandthenquadruple this one is also fine int twelve2 methodsoperate1 functioninteger integermymethodstripleandthenmymethodsquadruple more description on the errorin eclipse it is highlighted with the error messagethe target type of this expression must be a functional interfaceand in java 8 compiler the error isjava8testjava14 error method reference not expected here int twelve methodsoperate1 mymethodstripleandthenmymethodsquadruple 1 erroractually why is the error in eclipse different from the one from java 8 compiler,['java'] +818119,how to apply a custom style to switchcompat i would like to apply a custom style to switchcompat change drawables and text for on and off state how can i achieve this i cannot find any examples on how this is done i tried the following in my stylesxml but apparently i am not using the right parentstyle nameswitch parentandroidwidgetappcompatwidgetcompoundbuttonswitchcompat item nameandroidtextonstringcommon yesitem item nameandroidtextoffstringcommon noitem item nameandroidthumbdrawablebtn switch selectoritem item nameandroidtrackdrawablebtn switch bg selectoritemstyleediti managed to change the drawables in code switchviewsetthumbresourcerdrawablebtn switch selectorswitchviewsettrackresourcerdrawablebtn switch bg selectorbut i have not found a way yet to change the text of the switch the following snippet does not seem to work maybe i need to set some more textpropertiesswitchviewsettextoncontextgetstringrstringcommon yesswitchviewsettextoffcontextgetstringrstringcommon noaccording to the switchcompat source code there should be support for onoff textthe link settextcharsequence textproperty controls the text thisplayed in the label for the switch whereas thelink settextoffcharsequence off and link settextoncharsequence on textcontrols the text on the thumbedit 2finally found a code solution apparently setshowtext needs to be set to true for the text to appear on the switch switchviewsettextoncontextgetstringrstringcommon yesswitchviewsettextoffcontextgetstringrstringcommon noswitchviewsetshowtexttrueswitchviewsetthumbresourcerdrawablebtn switch selectorswitchviewsettrackresourcerdrawablebtn switch bg selectorand xml solutionandroidsupportv7widgetswitchcompat androidididview switch androidlayout widthwrap content androidlayout heightwrap content androidthumbdrawablebtn switch selector apptrackdrawablebtn switch bg selector androidtextonstringcommon yes androidtextoffstringcommon no appshowtexttrue i would still like to know if there is a way to put this in stylesxml,['android'] +818179,fortranc interoperability passing array via void pointer i roughly have the following situation i have a c function which is called from fortran code and takes a function pointer and a void pointer as arguments like thisint stdcall fortran namecppfunction cppfunction int userfunctionconst int object const void userfunctionuserdata const void userdata int index int result result userfunctionindex userdata this is called from fortran like this double precision allocatable datainteger n result allocatedata3n data 00 fill data with somethingresult cppfunctionfortranfunction data the fortran function which i want to pass via the function pointer looks likeinteger function fortranfunctionidx dataimplicit noneinteger intentin idxdouble precision intentin datainteger i offsetoffset 3 idx 1write dataoffset 1 dataoffset 1write dataoffset 2 dataoffset 2write dataoffset 3 dataoffset 3end function fortranfunctionif i start the whole thing cppfunction seems to be correctly called it calls fortranfunction and i get an exception code c05 access violation exactly in the line in fortranfunction where the first access to the array data is donewrite dataoffset 1 dataoffset 1can somebody tell me where my mistake is i should also mention that the cfunction is not mine it is not impossible to change it but it would affect lots of other code the fortan part is completely under my control and i can do what i want with itthank you,['c++'] +818257,mediametadataretriever setdatasource throws illegalargumentexception i am trying to get the size of a remote video using this class and i am getting illegalargumentexception if the video is remotethe video is an mp4 stored in one serverthe video plays correctly if i play it with mediaplayer but it gives the error if i try to do thistry mediametadataretriever retriever new mediametadataretriever bitmap bmp null retrieversetdatasourcecontext uri bmp retrievergetframeattime videoheight int bmpgetheightfloatgetintwidthbmpgetwidth catch exception e eprintstacktrace the error is thrown in this lineretrieversetdatasourcecontext uriand uri contains uriparsewhat is wrong in the code1219 133808610 wsystemerr13 javalangillegalargumentexception1219 133808611 wsystemerr13 at androidmediamediametadataretrieversetdatasourcemediametadataretrieverjava175,['android'] +818279,what kind of python magic does dir perform with getattr the following is in python 27 with mysqldb 123i needed a class wrapper to add some attributes to objects which did not support it classes with slots andor some class written in c so i came out with something like thisclass wrapperobject def init self obj self wrapped obj obj def getattr self obj return getattrself wrapped obj attri was expecting that the dir builtin called on my instance of wrapper should have returned just the names inherited by object plus wrapped obj and i thiscovered that this is actually the case for most cases but not for all i tried this with a custom old style class a custom new style class and some builtin classes it always worked this way the only exception that i found is when the wrapped object was an instance of the class mysqlconnection in this case dir on my object happens to know also all the method names attached to the wrapped connection objecti read in the python documentation about dir and this behaviour appears to be legit dir is supposed to return a list of interesting names not the real content of the instance but i really cannot figure how it does this it actually understands the implementation of my getattr and resolves to the attached item if this is true why only with that connection class and not for instance with a simpler dicthere is some pasted code as an example of this curious behaviour from mysql import connection c connectionconnection parameters c mysqlconnection open to 127001 at a16920 dircaffected rows autocommit change user character set name close commit dump debug info errno error escape escape string field count get character set info get host info get proto info get server info info insert id kill next result ping query rollback select db set character set set server option shutdown sqlstate stat store result string literal thread id use result warning count w wrapperc dirw class delattr dict doc format getattr getattribute hash init module new reduce reduce ex repr setattr sizeof str subclasshook weakref wrapped obj affected rows autocommit change user character set name close commit dump debug info errno error escape escape string field count get character set info get host info get proto info get server info info insert id kill next result ping query rollback select db set character set set server option shutdown sqlstate stat store result string literal thread id use result warning count d wrapper dird class delattr dict doc format getattr getattribute hash init module new reduce reduce ex repr setattr sizeof str subclasshook weakref wrapped obj,['python'] +818289,anaconda vs miniconda space on my desktop pc i have anaconda installed and on my laptop to save space i thought i would install miniconda and be selective about the modules i install so i installed a handful numpy scipy etc i did not install anything which is not part of the default anaconda install but i just realized my miniconda install is taking up more space than the anaconda install 18gb vs 22gb no environments in eitherthe bulk of the difference comes from the pkgs folder the miniconda install seems to have the tarbz2 of all of the installed packages as well as the exploded versions are these safe to delete will they be deleted automatically after a while is there an option to not cache theseps i am developing on both windows and mac i have tried installed anaconda and miniconda on both mac and windows to see and i get very similar results,['python'] +818347,is there an easy way to get all common module extensions i am making a library that deals with python modules without getting into details i need a list of the common python module extensionsobviously i want py but i would also like to include ones such as pyw pyd etc in other words i want anything that you can importis there a tool in the standard library which will make this list for me or do i have to make it myself and hardcode all of the valuesextensions py pyw,['python'] +818368,error31 0 gradle dsl method not found jnidebugbuild today i have updated my android studio and i keep getting this error no matter what i do i imported a project from github everything was running smoothly until i updated now i keep getting this errorerror31 0 gradle dsl method not found jnidebugbuildpossible causesthe project my application may be using a version of gradle that does not contain the methodopen gradle wrapper filethe build file may be missing a gradle pluginapply gradle plugincan anyone help out,['android'] +818399,jackson prefers private constructor over jsoncreator when deserializing a class with jsonvalue i have a simple class with a private constructor and a static factory i want the class to serialize as a number so i have annotated the getter for the field with jsonvalue however jackson appears to prefer the private constructor over the static factory even when i annotate the static factory with jsoncreator it works if i annotate the private constructor with jsonignore but that feels a bit offi have seen some posts claiming that jsoncreator only works if the parameters are annotated with jsonproperty however that seems to be the case for objects serialized as json objects this object is being serialized as a number and thus there is no property to supply to the annotationis there something i am missingexample classpackage comexampleimport comfasterxmljacksonannotationjsoncreatorimport comfasterxmljacksonannotationjsonvalueimport comgooglecommonbasepreconditionspublic class nonnegative private final double n private nonnegativedouble n thisn n jsoncreator public static nonnegative checkeddouble n preconditionscheckargumentn 00 return new nonnegativen jsonvalue public double getvalue return n override public int hashcode return objectshashn override public boolean equalsobject obj if this obj return true if obj instanceof nonnegative nonnegative that nonnegative obj return objectsequalsn thatn return false example testspackage comexampleimport static orgassertjcoreapiassertionsassertthatimport orgjunittestimport comfasterxmljacksondatabindjsonmappingexceptionimport comfasterxmljacksondatabindobjectmapperpublic class nonnegativetest private static final objectmapper mapper new objectmapper test public void itserializesanddeserializes throws exception nonnegative nonnegative nonnegativechecked05 assertthatmapperreadvaluemapperwritevalueasstringnonnegative nonnegativeclassisequaltononnegative this test fails testexpected jsonmappingexceptionclass public void itdoesnotdeserializeanegativenumber throws exception mapperreadvaluemapperwritevalueasstring05 nonnegativeclass,['java'] +818569,error inheritance security rules violated by type systemwebwebpagesrazorwebpagerazorhost out of no where my aspnet mvc 4 solution gives me this errorinheritance security rules violated by type systemwebwebpagesrazorwebpagerazorhost derived types must either match the security accessibility of the base type or be less accessiblei googled the problem and everybody says it has happened when any one update this solution from one version to another but i did not update my solution just change the ide from vs12 to vs13 is this what creates the problemthe full stack trace is as followstypeloadexception inheritance security rules violated by type systemwebwebpagesrazorwebpagerazorhost derived types must either match the security accessibility of the base type or be less accessible systemwebwebpagesrazorrazorbuildproviderget codecompilertype 0 systemwebcompilationbuildprovidergetcompilertypefrombuildproviderbuildprovider buildprovider 59 systemwebcompilationbuildproviderscompilerprocessbuildproviders 209 systemwebcompilationbuildproviderscompilerperformbuild 30 systemwebcompilationbuildmanagercompilewebfilevirtualpath virtualpath 9971917 systemwebcompilationbuildmanagergetvpathbuildresultinternalvirtualpath virtualpath boolean nobuild boolean allowcrossapp boolean allowbuildinprecompile boolean throwifnotfound boolean ensureisuptodate 299 systemwebcompilationbuildmanagergetvpathbuildresultwithnoasserthttpcontext context virtualpath virtualpath boolean nobuild boolean allowcrossapp boolean allowbuildinprecompile boolean throwifnotfound boolean ensureisuptodate 103 systemwebcompilationbuildmanagergetvirtualpathobjectfactoryvirtualpath virtualpath httpcontext context boolean allowcrossapp boolean throwifnotfound 165 systemwebcompilationbuildmanagergetobjectfactorystring virtualpath boolean throwifnotfound 33 systemwebmvcbuildmanagerwrappersystemwebmvcibuildmanagerfileexistsstring virtualpath 40 systemwebmvcbuildmanagerviewenginefileexistscontrollercontext controllercontext string virtualpath 54 microsoftwebmvcfixedrazorviewenginemicrosoftwebmvciviewengineproxyfileexistscontrollercontext controllercontext string virtualpath 42 microsoftwebmvcviewenginefixworker1fileexistscontrollercontext controllercontext string virtualpath 57 microsoftwebmvcc thisplayclass4getpathfromgeneralnameb 0string path 66 systemwebwebpagesdefaultthisplaymodegetthisplayinfohttpcontextbase httpcontext string virtualpath func2 virtualpathexists 90 systemwebwebpagesc thisplayclassbb 8ithisplaymode mode 66 systemlinqwhereselectlistiterator2movenext 103 systemlinqenumerablefirstordefaultienumerable1 source func2 predicate 94 systemwebwebpagesthisplaymodeprovidergetthisplayinfoforvirtualpathstring virtualpath httpcontextbase httpcontext func2 virtualpathexists ithisplaymode currentthisplaymode boolean requireconsistentthisplaymode 297 systemwebwebpagesthisplaymodeprovidergetthisplayinfoforvirtualpathstring virtualpath httpcontextbase httpcontext func2 virtualpathexists ithisplaymode currentthisplaymode 108 microsoftwebmvcviewenginefixworker1getpathfromgeneralnamecontrollercontext controllercontext list1 locations string name string controllername string areaname string cachekey string searchedlocations 653 microsoftwebmvcviewenginefixworker1getpathcontrollercontext controllercontext string locations string arealocations string locationspropertyname string name string controllername string cachekeyprefix boolean usecache string searchedlocations 1508 microsoftwebmvcviewenginefixworker1findviewcontrollercontext controllercontext string viewname string mastername boolean usecache 329 microsoftwebmvcfixedrazorviewenginefindviewcontrollercontext controllercontext string viewname string mastername boolean usecache 66 systemwebmvcc thisplayclasscfindviewb biviewengine e 68 systemwebmvcviewenginecollectionfindfunc2 lookup boolean tracksearchedpaths 182 systemwebmvcviewenginecollectionfindfunc2 cachelocator func2 locator 110 systemwebmvcviewenginecollectionfindviewcontrollercontext controllercontext string viewname string mastername 329 systemwebmvcviewresultfindviewcontrollercontext context 135 systemwebmvcviewresultbaseexecuteresultcontrollercontext context 230 systemwebmvccontrolleractioninvokerinvokeactionresultcontrollercontext controllercontext actionresult actionresult 39 systemwebmvcc thisplayclass1ab 17 74 systemwebmvccontrolleractioninvokerinvokeactionresultfilteriresultfilter filter resultexecutingcontext precontext func1 continuation 388 systemwebmvcc thisplayclass1cinvokeactionresultwithfiltersb 19 72 systemwebmvccontrolleractioninvokerinvokeactionresultwithfilterscontrollercontext controllercontext ilist1 filters actionresult actionresult 303 systemwebmvcasyncc thisplayclass2ab 20 155 systemwebmvcasyncc thisplayclass25b 22iasyncresult asyncresult 184 systemwebmvcasyncwrappedasyncresult1end 136 systemwebmvcasyncasyncresultwrapperendiasyncresult asyncresult object tag 56 systemwebmvcasyncasynccontrolleractioninvokerendinvokeactioniasyncresult asyncresult 40 systemwebmvcc thisplayclass1dbeginexecutecoreb 18iasyncresult asyncresult 40 systemwebmvcasyncc thisplayclass4makevoiddelegateb 3iasyncresult ar 47 systemwebmvcasyncwrappedasyncresult1end 151 systemwebmvcasyncasyncresultwrapperendiasyncresult asyncresult object tag 59 systemwebmvcasyncasyncresultwrapperendiasyncresult asyncresult object tag 40 systemwebmvccontrollerendexecutecoreiasyncresult asyncresult 44 systemwebmvcasyncc thisplayclass4b 3iasyncresult ar 47 systemwebmvcasyncwrappedasyncresult1end 151 systemwebmvcasyncasyncresultwrapperendiasyncresult asyncresult object tag 59 systemwebmvcasyncasyncresultwrapperendiasyncresult asyncresult object tag 40 systemwebmvccontrollerendexecuteiasyncresult asyncresult 39 systemwebmvccontrollersystemwebmvcasynciasynccontrollerendexecuteiasyncresult asyncresult 39 systemwebmvcc thisplayclass8beginprocessrequestb 3iasyncresult asyncresult 45 systemwebmvcasyncc thisplayclass4makevoiddelegateb 3iasyncresult ar 47 systemwebmvcasyncwrappedasyncresult1end 151 systemwebmvcasyncasyncresultwrapperendiasyncresult asyncresult object tag 59 systemwebmvcasyncasyncresultwrapperendiasyncresult asyncresult object tag 40 systemwebmvcmvchandlerendprocessrequestiasyncresult asyncresult 40 systemwebmvcmvchandlersystemwebihttpasynchandlerendprocessrequestiasyncresult result 38 systemwebcallhandlerexecutionstepsystemwebhttpapplicationiexecutionstepexecute 96516 systemwebhttpapplicationexecutestepiexecutionstep step boolean completedsynchronously 155,['c#'] +818692,extending math object through prototype does not work i try to extend javascript math but one thing surprised mewhen i tried to extend it by prototypemathprototyperandombetween function a b return mathfloormathrandom b a 1 ain console i have error cannot set property randombetween of undefined but if i asigne this function to math proto math proto randombetween function a b return mathfloormathrandom b a 1 athen everything works finecan anybody explain me why it works in this way i appreciate any help,['javascript'] +818695,resharper null check is always false warning using resharper 82 i get a warning expression is always false for the null check inpublic bool trygetvaluetkey key out tvalue value if key nullfrom nhibernate nullabledictionary why is this when i try it withclass testt where t classthen i do not get the warning for null checks on t variables as expectededit to make things easier here is the class signature of the linked sourcepublic class nullabledictionarytkey tvalue idictionarytkey tvalue where tkey class,['c#'] +818706,angularjs get element position in jquery we can get position of an object with thisthispositionlefthow can we get the current element position with angularjs,"['javascript', 'jquery']" +818752,g enables wrong flags at os at the moment i am doing some experiments with the gnu ccompiler and the os optimization option for minimal code size i checked the enabled compiler flags at os with the following command g c q os helpoptimizers grep enabledi got this list of enabled optionsfaggressiveloopoptimizations enabledfalignfunctions enabledfalignjumps enabledfalignlabels enabledfalignloops enabledfasynchronousunwindtables enabled this seems a bit strange because i also looked up which flags should be enabled at os here and under the os section it is written that all the falign options should be thisabled for code minimizationq so is this a bug or am i doing something wrong here cause after reading what the falign flags do i really think they should be thisabled in os my gccversion is 492 and i am working on archlinuxalready thanks for helping,['c++'] +818781,deterministic python script behaves in nondeterministic way i have a script which uses no randomisation that gives me different answers when i run it i expect the answer to be the same every time i run the script the problem appears to only happen for certain illconditioned input data the snippet comes from an algorithm to compute a specific type of controller for a linear system and it mostly consists of doing linear algebra matrix inversions riccati equation eigenvalues obviously this is a major worry for me as i now cannot trust my code to give me the right results i know the result can be wrong for poorly conditioned data but i expect consistently wrong why is the answer not always the same on my windows machine why do the linux windows machine not give the same resultsi am using python 279 default dec 10 2014 122455 msc v1500 32 bit intel on win 32 with numpy version 182 and scipy 0140 windows 8 64bitthe code is below i have also tried running the code on two linux machines and there the script always gives the same answer but the machines gave differing answers one was running python 278 with numpy 182 and scipy 0140 the second was running python 273 with numpy 161 and scipy 0120i solve the riccati equation three times and then print the answers i expect the same answer every time instead i get the sequence 175305103767e09 325501787302e07 325501787302e07 import numpy as np import scipylinalg matrix npmatrix a matrix 0e00 296156260e01 0e00 10e00 296156260e01 677626358e21 10e00 211758237e22 0e00 0e00 206196064e00 559424e01 0e00 0e00 212407340e01 206195974e00 b matrix 0 0 0 0 0 0 34235401351 1420486532216 3122469724 139044997337 34233745324 12681720597 q matrix 501 0 0 0 0 501 0 0 0 0 0 0 0 0 0 0 r matrix 375632852e04 0e00 0e00 0e00 375632852e04 0e00 0e00 0e00 40e00 counter 0 while counter 3 counter 1 x scipylinalgsolve continuous area b q r print344915531628 x00my numpy config is as below print npshow configlapack opt info libraries mkl blas95 mkl lapack95 mkl intel c mkl intel thread mkl core libiomp5md mkl blas95 mkl lapack95 mkl intel c mkl intel thread mkl core libiomp5md library dirs cprogram files x86intelcomposer xe 2013 sp1mkllibia32 cprogram files x86intelcomposer xe 2013 sp1compilerlibia32 define macros scipy mkl h none include dirs cprogram files x86intelcomposer xe 2013 sp1mklincludeblas opt info libraries mkl blas95 mkl lapack95 mkl intel c mkl intel thread mkl core libiomp5md library dirs cprogram files x86intelcomposer xe 2013 sp1mkllibia32 cprogram files x86intelcomposer xe 2013 sp1compilerlibia32 define macros scipy mkl h none include dirs cprogram files x86intelcomposer xe 2013 sp1mklincludeopenblas info not availablelapack mkl info libraries mkl blas95 mkl lapack95 mkl intel c mkl intel thread mkl core libiomp5md mkl blas95 mkl lapack95 mkl intel c mkl intel thread mkl core libiomp5md library dirs cprogram files x86intelcomposer xe 2013 sp1mkllibia32 cprogram files x86intelcomposer xe 2013 sp1compilerlibia32 define macros scipy mkl h none include dirs cprogram files x86intelcomposer xe 2013 sp1mklincludeblas mkl info libraries mkl blas95 mkl lapack95 mkl intel c mkl intel thread mkl core libiomp5md library dirs cprogram files x86intelcomposer xe 2013 sp1mkllibia32 cprogram files x86intelcomposer xe 2013 sp1compilerlibia32 define macros scipy mkl h none include dirs cprogram files x86intelcomposer xe 2013 sp1mklincludemkl info libraries mkl blas95 mkl lapack95 mkl intel c mkl intel thread mkl core libiomp5md library dirs cprogram files x86intelcomposer xe 2013 sp1mkllibia32 cprogram files x86intelcomposer xe 2013 sp1compilerlibia32 define macros scipy mkl h none include dirs cprogram files x86intelcomposer xe 2013 sp1mklincludenoneedits to trim the question down,['python'] +818842,there is no use for development in xcodes organizer window i signed up with apples 99 development for ios program todayunder certificates identifiers profiles in xcode no matter what i click on it tells me to connect your device to your mac and click use for development in xcodes organizer window sign in with the apple id associated with your ios developer program membership and xcode will automatically generate your certificates in xcode 61 i go to window then organizer and i only see projects and archives no device next to it and no button to click use for development and i have my iphone connected funny thing is i already connected my iphone app game to work on an iphone device yet i still have no button to click on use for development what am i missing this is all i am being told to do by apple and i do not see the button,['ios'] +818872,ksecattraccessibleafterfirstunlock not allowing access even after first unlock ios so i have an old sensitive access key that currently has an accessibility of ksecattraccessible whenunlocked and i want to update it to ksecattraccessibleafterfirstunlocki am using lockbox and call thislockbox setstringaccesskey forkeyselfaccesskeyname accessibilityksecattraccessibleafterfirstunlockwhich in turn calls thisboolsetobjectnsstring obj forkeynsstring key accessibilitycftyperefaccessibility osstatus status nsstring hierkey self hierarchicalkeykey if the object is nil delete the item if obj nsmutabledictionary query self query query setobjecthierkey forkeylockbox idksecattrservice status secitemdeletelockbox dictrefquery return status errsecsuccess nsmutabledictionary dict self service dict setobject hierkey forkey lockbox id ksecattrservice dict setobject lockbox idaccessibility forkey lockbox id ksecattraccessible dict setobject obj datausingencodingnsutf8stringencoding forkey lockbox id ksecvaluedata status secitemadd lockbox dictref dict null if status errsecduplicateitem nsmutabledictionary query self query query setobjecthierkey forkeylockbox idksecattrservice status secitemdeletelockbox dictrefquery if status errsecsuccess status secitemaddlockbox dictref dict null if status errsecsuccess dlogsecitemadd failed for key d hierkey intstatus return status errsecsuccessas you can see above the lockbox code seems to try to add the item if there is a duplicate i have put a breakpoint there and can confirm that it does work however sometimes it still gives an error oferror secosstatuswith error25308 the operation couldnat be completed osstatus error 25308 remote error the operation couldna t be completed osstatus error 25308 ks crypt e02e2 failed to unwrap item class 6 bag 0 access to item attempted while keychain is lockedi do not understand why i would be getting this i have already unlocked my phone and it should be working fine any ideasi should also add that i need to access this when the app is killed and revived in the background through a region monitoring update,['ios'] +818876,why does the java compiler give rawtypes warning for class literal i am using mockito to write some tests and i am using the following bit of codeargumentcaptorlinkedlist captor argumentcaptorforclasslinkedlistclass this compiles and runs just fine except for the warning that captor is raw type and i should replace it with something likeargumentcaptorlinkedliststring captor argumentcaptorforclasslinkedliststringclassthe problem is that linkedliststringclass does not exist so the right side of the assignment will never compileassuming that suppressing the warning is inelegant is there an elegant solution if not why does the compile warn me about something i cannot really fix,['java'] +818877,rubygmail uncaught exception 5345714 i can manually login my account but when i use rubygmail it will raise errthis is my coderequire gmailgmail gmailnew passwdgmaildeliver do to subject having fun in puerto rico text part do body text of plaintext message end html part do content type texthtml charsetutf8 body ptext of emhtmlem messagep end add file file endthis is my full outputuncaught exception 5345714 scc1pltakgnsbtmk homerorocorbenvversions215libruby210netsmtprb969in check auth response homerorocorbenvversions215libruby210netsmtprb740in auth plain homerorocorbenvversions215libruby210netsmtprb732in authenticate homerorocorbenvversions215librubygems210gemsrubygmail031libsmtp tlsrb57in do tls start homerorocorbenvversions215librubygems210gemsrubygmail031libsmtp tlsrb18in start homerorocorbenvversions215librubygems210gemsmail261libmailnetworkdelivery methodssmtprb112in deliver homerorocorbenvversions215librubygems210gemsmail261libmailmessagerb248in deliver homerorocorbenvversions215librubygems210gemsrubygmail031libgmailrb107in deliver homerorocodropboxrbsro plansexexrb5in top requiredupdatesolution generate new for mail remember it fill it in rubygmail passwd,['ruby'] +818926,attempted to finish an input event but input event receiver has already been thisposed i have a custom adapter for my listview the adapter contains a textview and a image button i have implemented a popup menu on clicking the image button everything is working fine but when selecting the options from popup menu logcat thisplaying a single line message attempted to finish an input event but input event receiver has already been thisposed and nothing is happeningpublic class myadapter extends arrayadapterstring public myadaptercontext context int resourceid supercontext resourceid public myadaptercontext context int resourceid liststring string supercontext resourceid string override public view getviewint position view convertview viewgroup parent view v convertview ifv null layoutinflater inflater layoutinflaterfromgetcontext v inflaterinflaterlayoutadapter layout null string str getitemposition ifstr null textview textview textviewvfindviewbyidridedittext1 textviewsettextstr imagebutton button imagebuttonvfindviewbyidridimagebutton1 buttonsetonclicklistenernew custom adapter button click listenergetitemidposition getcontext return v onclicklistener interface is public class custom adapter button click listener implements onclicklistener onmenuitemclicklistener long position context context public custom adapter button click listenerlong id context appcontext position id context appcontext override public boolean onmenuitemclickmenuitem item adaptercontextmenuinfo info adaptercontextmenuinfoitemgetmenuinfo int index infoposition logditemclicked selected index index switchitemgetitemid case ridoption toastmaketextcontext selected index index toastlength shortshow return true default toastmaketextcontext default toastlength shortshow return false override public void onclickview v popupmenu popup new popupmenucontext v menuinflater popupinflater popupgetmenuinflater popupinflaterinflatermenucontextmenu popupgetmenu popupshow what i understood from the message is that some thing is eating the event before onmenuitemclick gets execute i am running my app on nexus 5 android 501i find a solution for similar kind of problem from here but i am not getting how to use this approach to my problemi tried using context menu instead of popup menu but still i had the same message attempted to finish an input event but input event receiver has already been thisposed after clicking on the context menu itemplease help me,['android'] +818952,how to avoid 65k method limit while using google play services if you find yourself writing a big android application that depends on many different libraries which i would recommend instead of reinventing the wheel it is very likely that you have already come across the 65k method limit of the dalvik executable file classesdex furthermore if you depend on large libraries like the google play services sdk which itself in already contained more than 20k methods in version 50 you are forced to use tricks like stripping packages or multidex support to avoid errors while packaging with androids new runtime art which is publicly available since android lollipop multiple dex files are easier to handle but currently developers are still forced to do method countingwhat is the simplest way to reduce your applications method count while using google play services,['android'] +819010,android google plus cannot share image from my content provider i have used this code and can successfully share an image from my phones gallery with text to google from my android apphowever when i try to post an image from my apps content provider the image is showing up on my google page like thisand that is despite the intended image being thisplayed fine on the google app preview screenthe code i am using to share isstring message my message uri localimageuri contenturiswithappendediddbcontentprovidercontent uri products mproductidplussharebuilder builder new plussharebuildergetactivitybuildersettextmessagebuilderaddstreamlocalimageuribuildersettypeimagejpegintent shareintent buildergetintentstartactivityforresultshareintent rc google plusand like i say the image is successfully thisplayed on the final google page if the localimageuri value is for a resource in my phones gallery whereas the above placeholder image is shown if i set localimageuri to a uri from my apps own content providerso i presume there must be an issue with my content provider which is defined in my manifest asprovider androidnamedbcontentprovider androidauthoritiescomexampleprovider androidexportedtrue androidgranturipermissionstrue so could there be something missing from my manifefst or even from my searchablexml filexml version10 encodingutf8searchable xmlnsandroid androidlabelstringapp name androidhintstringsearch hint androidsearchsuggestauthoritycomexampleprovider androidsearchsuggestintentactionandroidintentactionview androidsearchsuggestintentdatacontentcomexampleprovidersuggest androidsearchsuggestthreshold3 androidincludeinglobalsearchtrue androidsearchsettingsdescriptionstringsearch settings description androidqueryafterzeroresultstrue androidvoicesearchmodeshowvoicesearchbutton searchableif not then what could the problem beupdate following commonswares commentexceptions were indeed thrown by the google library because as well doing a query on the data column which existed the google api was also looking for columns that did not exist namely datetaken date added date modifiedso i have added these columns to my database table adding them all as text columns with recent millis values such as 1419379390 ref here but i still get the same placeholder image being thisplayed on my google pageso i added some logging code to the query method of my dbcontentprovider class and when google does its singlecolumn query for datetaken the value returned in the cursor is indeed 1419379390 however the value returned for the separate data query is nulli am not sure why the google api queries the data column because i do not need to call it in my code when i retrieve the image from the database in order to show in on the ui instead i calluri localimageuri contenturiswithappendediddbcontentprovidercontent uri products mproductidinputstream in cropeninputstreamlocalimageuribitmap img bitmapfactorydecodestreaminimageviewsetimagebitmapimgbut presumably the null in my cursor for the data value is the problem not sure where to start to address this though30dec2014 updatehere is the logcat output so when i click my g button1230 214534344 ddbcontentprovider24633 gettypecontentcomexampleproviderproducts16681230 214534534 ddbcontentprovider24633 gettypecontentcomexampleproviderproducts16681230 214534544 ddbcontentprovider24633 openfilecontentcomexampleproviderproducts1668 r1230 214534584 ddbcontentprovider24633 openfilecontentcomexampleproviderproducts1668 r1230 214534604 ddbcontentprovider24633 openfilecontentcomexampleproviderproducts1668 r1230 214534604 ddbcontentprovider24633 openfilecontentcomexampleproviderproducts1668 r1230 214534624 ddbcontentprovider24633 openfilecontentcomexampleproviderproducts1668 rthat brings up the g screen for customising the share message which i confirm does include the image from my content provider so i then click the share button on the g screen and the logcat output is1230 214557526 ddbcontentprovider24633 openfilecontentcomexampleproviderproducts1668 r1230 214557576 ddbcontentprovider24633 gettypecontentcomexampleproviderproducts16681230 214557576 ddbcontentprovider24633 dbcontentprovider querycontentcomexampleproviderproducts16681230 214557576 ddbcontentprovider24633 projection datetaken1230 214557576 ddbcontentprovider24633 selection null1230 214557576 ddbcontentprovider24633 selectionargs null1230 214557576 ddbcontentprovider24633 sortorder null1230 214557576 ddbcontentprovider24633 sql without selectionargs select datetaken from products where id 1668 limit 11230 214557596 ddbcontentprovider24633 returned value 14193793901230 214557596 ddbcontentprovider24633 cursor count 11230 214603642 ddbcontentprovider24633 gettypecontentcomexampleproviderproducts1668 returns vndandroidcursoritemvndexampleelemental23jan2015 updatehere is my manifest in fullxml version10 encodingutf8manifest xmlnsandroid packagecomexample androidversioncode10 androidversionname010 usessdk androidminsdkversion11 androidtargetsdkversion20 usespermission androidnameandroidpermissioninternet usespermission androidnameandroidpermissionaccess network state usespermission androidnameandroidpermissionwrite external storage usespermission androidnameandroidpermissionget accounts usespermission androidnameandroidpermissionuse credentials usespermission androidnameandroidpermissionwake lock usespermission androidnamecomgoogleandroidc2dmpermissionreceive permission androidnamecomexamplepermissionc2d message androidprotectionlevelsignature usespermission androidnamecomexamplepermissionc2d message usespermission androidnamecomandroidvendingbilling application androidnamemyapplication androidallowbackuptrue androidicondrawableic launcher androidlabelstringapp name androidthemestyleapptheme metadata androidnamecomgoogleandroidgmsversion androidvalueintegergoogle play services version receiver androidnamegcmbroadcastreceiver androidpermissioncomgoogleandroidc2dmpermissionsend intentfilter action androidnamecomgoogleandroidc2dmintentreceive category androidnamecomexample intentfilter receiver service androidnamegcmintentservice provider androidnamedbcontentprovider androidauthoritiescomexampleprovider androidexportedfalse androidgranturipermissionsfalse granturipermission androidpathprefixproducts provider activity androidnamecomgoogleandroidgmsadsadactivity androidconfigchangeskeyboardkeyboardhiddenorientationscreenlayoutuimodescreensizesmallestscreensize androidthemeandroidstylethemetranslucent metadata androidnamecomgoogleandroidgmsversion androidvalueintegergoogle play services version activity activity androidnamesplashactivity androidlabelstringapp name androidlaunchmodesingletop intentfilter androidlabelstringapp name short action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity activity androidnameloginactivity androidlabelstringtitle activity login androidwindowsoftinputmodestatehidden activity activity androidnamehomeactivity androidlabelstringapp name short androidwindowsoftinputmodeadjustpan metadata androidnameandroidappdefault searchable androidvaluesearchresultsactivity activity activity androidnamesearchresultsactivity androidlabelstringapp name short androidlaunchmodesingletop androidparentactivitynamehomeactivity androidwindowsoftinputmodestatehidden intentfilter action androidnameandroidintentactionsearch intentfilter metadata androidnameandroidsupportparent activity androidvaluehomeactivity metadata androidnameandroidappsearchable androidresourcexmlsearchable metadata androidnameandroidappdefault searchable androidvaluesearchresultsactivity activity activity androidnamesingleshoppinglistactivity androidlabelstringshopping list androidparentactivitynamehomeactivity metadata androidnameandroidsupportparent activity androidvaluehomeactivity activity activity androidnamesingleproductactivity androidlabelstringshopping list item androidparentactivitynamehomeactivity metadata androidnameandroidsupportparent activity androidvaluehomeactivity activity activity androidnameinfomenuactivity androidlabelstringwhy gmo free androidparentactivitynamehomeactivity metadata androidnameandroidsupportparent activity androidvaluehomeactivity activity activity androidnameinfocontentactivity androidlabelstringwhy gmo free androidparentactivitynameinfomenuactivity metadata androidnameandroidsupportparent activity androidvalueinfomenuactivity activity activity androidnamesettingsactivity androidlabelstringsettings androidparentactivitynamehomeactivity metadata androidnameandroidsupportparent activity androidvaluehomeactivity activity activity androidnametwittercallbackactivity androidlabelstringapp name intentfilter action androidnameandroidintentactionview category androidnameandroidintentcategorydefault category androidnameandroidintentcategorybrowsable data androidhosttwitter androidschemeoauth intentfilter activity activity androidnamedummyactivity androidlabelstringtitle activity dummy activity activity androidnamesmartsearchresultsactivity androidlabelstringapp name short androidparentactivitynamesearchresultsactivity androidwindowsoftinputmodestatehidden intentfilter action androidnameandroidintentactionsearch intentfilter metadata androidnameandroidsupportparent activity androidvaluesearchresultsactivity metadata androidnameandroidappsearchable androidresourcexmlsearchable metadata androidnameandroidappdefault searchable androidvaluesearchresultsactivity activity activity androidnamewebviewactivity androidlabelstringapp name short androidparentactivitynamehomeactivity metadata androidnameandroidsupportparent activity androidvaluehomeactivity activity activity androidnameupgradeactivity androidlabelstringupgrade to pro qm activity applicationmanifest,['android'] +819021,why constexpr parameters are not allowed it would be useful to have constexpr parameters in order to thistinguish compilerknown values and so to be able detecting errors at compiletime examplesint do somethingconstexpr int x static assertx 0 x must be 0 return x 5int do somethingint x ifx 0 cout x must be 0 endl exit1 return x 5int vardo something9 instance do somethingconstexpr int x and check arg validity at compiletimedo something0 produces compilererrordo somethingvar instance do somethingint xwhich is an invalid code for now can somebody explains me why this cannot be implementededitusing templates users should assure that literals are always passed as template arguments and not as function ones which is very uncomfortabletemplateint xint do something static assertx 0 x must be 0 return x 5int do somethingint x ifx 0 cout x must be 0 endl exit1 return x 5int vardo something9 instance do somethingint x and does not checks validity at compiletimedo something0 same as above if check was performed compiler error should occurdo something9 instance template do somethingintdo something0 produces compiler errordo somethingvar instance do somethingint x,['c++'] +819073,why is performselector not present in swift apparently the following is not available in swift anymoreself performselectorselectoronflip withobjectnil afterdelay03why is this the case if the following is still presentnsobjectcancelpreviousperformrequestswithtargetself selector singletapselector object nildoes not nsobjectcancel work with performselector why have the cancel functionality but not the perform functionality,['ios'] +819105,how to use activerecord outside rails i am building a rails application based on hexagonal architectureone of my adapters is storage adapter maintained as a gem that manages access to database and provides simple interface for rails application to store and query data in databasei would like to use activerecord in this gem with all rake tasks create migrate drop rollback for managing database how can i use ar outside rails but with all rake tasks,"['ruby-on-rails', 'ruby']" +819251,xcode 6 no provisioning profiles with a valid signing identity ie certificate and private key pair were found i got p12 file from my colleague and installed into my mac and i find the certificate along with private key properly installed in my keychainand also i installed provisioning profilei selected provisioning profile respective certificate in xcode 6 when i try to build the app i get this error no provisioning profiles with a valid signing identity ie certificate and private key pair were foundin the keychaing appin xcode 6i tried the following but no luckrestart xcodedelete and reinstalled p12 provisioning profileturnedoff online certificate status protol certificate revocation list in keychain preferencecan anyone help me to solve this issuenote i do not have access to developer portal,['ios'] +819262,phpunit tests gives warning no tests found in class i am trying to learn how to test with phpunit and laravel when start the test using phpunit command i am getting a warning there was 1 failure1 warningno tests found in class poststestfailures tests 2 assertions 1 failures my test classname and filename matches i have read other problems about unmatching names my filename is poststestphp and my test file class poststest extends apitester public function it fetches posts thistimes5makepost thisgetjsonapiv1posts thisassertresponseok private function makepostpostfields post array merge title thisfakesentence content thisfakeparagragraph postfields whilethistimes postcreatepost if necessary my apitester use fakerfactory as fakerclass apitester extends testcase protected fake protected times 1 function constructfaker thisfake fakercreate i dont have any clue where the error is laravel or my local phpunit settings or anything else any helps is appreciatedthanks,['php'] +819436,why does not thisplay block width auto stretch a button to fill the container when i set thisplay block and width auto on a button i would expect the button to stretch to fill the container as other block elements do for some reason it does not at least not in latest chromewhen googling around i found a lot of people asking the same question who were satisfied with an answer to how do i stretch my buttons to fill the container that is not what i am interested in i am perfectly able to stretch my buttons any way i need inspecting button properties including the ones imposed by default by the browser did not help me eitheri would like to understand what causes buttons to ignore thisplay block width auto and stay horizontally sized based on their contentsheres a demonstration of what i meanbutton thisplay blockbutton stylewidth autobutton with thisplayblock widthautobuttonbutton stylewidth 100button with thisplayblock width100buttoni would expect the button with widthauto to be stretched as welljust to be absolutely clear this is not a duplicate to input with thisplayblock is not a block why not or any similar question unless that has only answers describing ways to stretch the elements in questionedit it might be a duplicate of what is it in the cssdom that prevents an input box with thisplay block from expanding to the size of its container on the other hand that question does not mention buttons at all you need to read the answer to find out it applies to buttons as well,"['html', 'css']" +819483,highlighting a tag using css i have an html tag i created using css3 i would like to highlight a particular tab ideally i would like to have a glow around the tag that shows it is active i am using after to create the shape of the tag but this does not allow me to highlight around the actual shapeheres a fiddlehtmla href classtag inserthtmlacssactive border 1px solid rgb246 255 0 boxshadow 0px 1px 3px rgba0 0 0 005 inset 0px 0px 8px rgba255 252 14 06as you can see the highlight is around everything except the arrowtriangle part does anyone know how i could have the same highlighted look around the arrowtriangle as well,"['html', 'css']" +819585,code coverage for angularjs html templates we are using istanbul for code coverage in our karma tests this works great for tracking code coverage of our unit tests in javascript however this does not track code coverage in our html templateswe have very little logic in our templates but there is still complexity that we want to track and ensure we have properly covered in our tests what are the best practices to ensure that you have proper coverage over all of your html templates in our particular case we use ngif and ngswitch wed like to ensure that all branches are properly covered,['html'] +819609,unable to fix signing identity issue on xcode i am not new to this but i am unable to fix my signing identity from xcode version 62 6c86e when i click fix issue on the following messagei get a pop up window sayingthe selected teams agent name surname must agree to the latest ios program license agreement please visit the member center i went on and accepted the latest ios program agreement this is what i can see on my legal agreements sectionhowever the message on xcode keeps popping up i tried loggin in and out but it does not show me the legal agreement message anymore so i assume on their server side is accepted i wonder if this is because itunes connect is temporarily unavailableany idea on how to fix this,['ios'] +819709,uikeyboarddidshownotification called multiple times and sometimes with incorrect keyboard dimensions i am trying to move a uitextview above the keyboard whenever the keyboard appearschanges let us say i have the english keyboard thisplaying and then switch directly to the chinese keyboard which is taller than the standard english keyboard in this scenario my text view always appears too high to the naked eye it looks like the text view is incorrectly offset by the size of the chinese keyboard input accessory view i would post an image but lack the reputation to do so i am adjusting my text view position when my app receives a uikeyboarddidshownotification using uikeyboardframeenduserinfokey to get the height and after some investigation uikeyboarddidshownotification is called multiple times oftentimes with the incorrect keyboard dimensions i have nslogged the userinfo dictionary i register for my keyboard notifications in viewwillappear and unregister in viewwillthisappear i am unable to determine what might be causing this notification to fire multiple times my understanding is that this notification should only be fired one time right after the keyboard finishes thisplaying an additional note i have nslogged self in the method that responds to uikeyboarddidshownotification and it is in fact always the same view controller object even with this notification firing multiple times however i still do not understand why the keyboard height would be different for some of these notifications one of the notifications always has the correct height but when it is not the last notification fired the text view ends up in the wrong spot any insight on how to further troubleshoot would be much appreciatededit the more i test the more it seems to be a problem with the chinese keyboard specifically whenever i switch the keyboard from english to chinese i get three uikeyboardwillshownotifications 20141224 224929385 example1055421943 info dictionary uikeyboardanimationcurveuserinfokey 0uikeyboardanimationdurationuserinfokey 0uikeyboardboundsuserinfokey nsrect 0 0 320 252uikeyboardcenterbeginuserinfokey nspoint 160 460uikeyboardcenterenduserinfokey nspoint 160 442uikeyboardframebeginuserinfokey nsrect 0 352 320 216uikeyboardframeenduserinfokey nsrect 0 316 320 25220141224 224929408 example1055421943 info dictionary uikeyboardanimationcurveuserinfokey 0uikeyboardanimationdurationuserinfokey 0uikeyboardboundsuserinfokey nsrect 0 0 320 216uikeyboardcenterbeginuserinfokey nspoint 160 442uikeyboardcenterenduserinfokey nspoint 160 460uikeyboardframebeginuserinfokey nsrect 0 316 320 252uikeyboardframeenduserinfokey nsrect 0 352 320 21620141224 224929420 example1055421943 info dictionary uikeyboardanimationcurveuserinfokey 0uikeyboardanimationdurationuserinfokey 0uikeyboardboundsuserinfokey nsrect 0 0 320 288uikeyboardcenterbeginuserinfokey nspoint 160 442uikeyboardcenterenduserinfokey nspoint 160 424uikeyboardframebeginuserinfokey nsrect 0 316 320 252uikeyboardframeenduserinfokey nsrect 0 280 320 288the first one has the correct end height 252 however the next two are incorrect at 216 and 288 this happens reliablyhere are a couple of snippets to demonstrate how i am managing subscriptions to notificationsvoidviewwillappearboolanimated super viewwillappearanimated self registerforkeyboardnotificationsvoidviewwillthisappearboolanimated super viewwillthisappearanimated nsnotificationcenter defaultcenter removeobserverself nameuikeyboardwillhidenotification objectnil nsnotificationcenter defaultcenter removeobserverself nameuikeyboarddidshownotification objectnil voidregisterforkeyboardnotifications nsnotificationcenter defaultcenter addobserverself selectorselectorkeyboarddidhide nameuikeyboardwillhidenotification objectnil nsnotificationcenter defaultcenter addobserverself selectorselectorkeyboarddidshow nameuikeyboarddidshownotification objectnil,['ios'] +819756,webdriver how to check if browser still exists or still open i want to check if browser still exists and if it is not then i want to open a new browser is there a api available in webdriver to check if the browser still exists,['java'] +819757,why are not method references singleton in java the following code returns false on both queries why wouldnt it be simpler for method references to be singleton it would certainly make attaching and detaching listeners a lot simpler as it is you need to keep a constant for any method reference that will need to be equivalence checked you cannot just use the method reference operator at every necessary locationpublic class main public main todo autogenerated constructor stub public void dostuff public static void mainstring args main main new main runnable thing1 maindostuff runnable thing2 maindostuff systemoutprintlnthing1 thing2 false systemoutprintlnthing1equalsthing2 false,['java'] +819773,do references get updated when garbage collectors move data in heap i read that gc garbage collectors moves data in heap for performance reasons which i do not quite understand why since it is random access memory maybe for better sequential access but i wonder if references in stack get updated when such a move occurs in heap but maybe the offset address remains the same but other parts of data get moved by garbage collectors i am not sure thoughi think this question pertains to implementation detail since not all garbage collectors may perform such optimization or they may do it but not update references if it is a common practice among garbage collector implementations but i would like to get some overall answer specific to clr common language runtime garbage collectors thoughand also i was reading eric lipperts references are not addresses article here and the following paragraph confused me little bitif you think of a reference is actually being an opaque gc handle then it becomes clear that to find the address associated with the handle you have to somehow fix the object you have to tell the gc until further notice the object with this handle must not be moved in memory because someone might have an interior pointer to it there are various ways to do that which are beyond the scope of this screedit sounds like for reference types we do not want data to be moved then what else we store in the heap which we can move around for performance optimization maybe type information we store there by the way in case you wonder what that article is about then eric lippert is comparing references to pointers little bit and try to explain how it may be wrong to say that references are just addresses even though it is how c implements itand also if any of my assumptions above is wrong please correct me,"['c#', '.net']" +819800,identity password reset token is invalid i am writting mvc 5 and using identity 20 now i m trying to reset password but i always getting invalid token error for reset password token public class accountcontroller controller public usermanagerapplicationuser usermanager get private set public accountcontroller thisnew usermanagerapplicationusernew userstoreapplicationusernew applicationdbcontext and i set dataprotectortokenprovider public accountcontrollerusermanagerapplicationuser usermanager usermanager config usermanagerpasswordvalidator new passwordvalidator requiredlength 5 usermanageremailservice new iddaawebsitecontrollersmembershipmembershipcomponentsemailservice var provider new microsoftowinsecuritydataprotectiondpapidataprotectionprovider usermanagerusertokenprovider new microsoftaspnetidentityowindataprotectortokenproviderapplicationuserprovidercreateusertoken as iusertokenproviderapplicationuser string usermanager usermanager i generate password reset before sending mail httppost validateantiforgerytoken public async taskactionresult managepasswordmanageuserviewmodel model if requestformemail null var email requestformemailtostring var user usermanagerfindbyemailemail var token await usermanagergeneratepasswordresettokenasyncuserid mail send i click link in mail and i am getting passwordreset token and using var result await usermanagerresetpasswordasyncmodeluserid modelpasswordtoken modelnewpasswordthe result always false and it says invalid tokenwhere should i fix,"['c#', '.net']" +819849,identify primary key candidates through sql code i have a raw data with millions of rows and no constraints and i want to identify unique columns for primary keys through sql code is there any way we can identify primary key candidates through sql code,['sql'] +820005,launch a completely independent process i wanted to initiate a process from my python script mainpy specifically i want to run the below commandnohup python myfilepy and this file myfilepy should even after my main python script exitsadditionally i wish to get the pid of the new processi tried osspawnl osexec subprocesspopen methods all are terminating my myfilepy if my mainpy script exitsi may be missing somethingupdate can i use osstartfile with xdgopen is it a right approachexamplea subprocesspopensysexecutable nohup usrbinpython25 long processpy stdoutsubprocesspipe stderrsubprocesspipe stdinsubprocesspipeprint apidif i check ps aux grep long process i could not see any process runninglong processpy which keeps on printing some text no exitam i doing anything wrong here,['python'] +820131,chunking stanford named entity recognizer ner outputs from nltk format i am using ner in nltk to find persons locations and organizations in sentences i am able to produce the results like thisuremaking uo uthe uo urepublican uorganization uparty uorganizationis that possible to chunk things together by using itwhat i want is like thisuremaking uo utheuo urepublican upartyuorganizationthanks,['python'] +820151,wicked pdf ignores bootstrap grid system in my template xpdferb site i have linked all the stylesheets and javascript tags wicked pdf stylesheet link tag bootstrapcss wicked pdf stylesheet link tag stylecss wicked pdf stylesheet link tag styleumowacss wicked pdf stylesheet link tag animatecss wicked pdf javascript include tag application when the pdf site is generated everything is good except bootstrap grid system i mean wicked pdf ignores mydiv classcontainer div classrow div classcollg4div div classcollg4div div classcollg4div divdivso its thisplayed like normal divs without bootstrap grid can you help me with this,"['html', 'ruby-on-rails', 'ruby']" +820164,pythonselenium incognitoprivate mode i can not seem to find any documentation on how to make selenium open the browser in incognito mode do i have to setup a custom profile in the browser or,['python'] +820202,how can i post a simple html form in r i am relatively new to r programming and i am trying to put some of the stuff i am learning in the johns hopkins data science track to practical use specifically i would like to automate the process of downloading historical bond prices from the us treasury websiteusing both firefox and r i was able to determine that the us treasury website uses a very simple html post form to specify a single date for the quotes of interest it then returns a table of secondary market information for all outstanding bondsi have unsuccessfully tried to use two different r packages to submit a request to the us treasury web server hare are the two approaches i triedattempt 1 using rcurlurl tdhtml postformurl submit show prices pricedateyear 2014 pricedatemonth 12 pricedateday 15 opts curloptionslverifypeer falsethis results in a web page being returned and stored in tdhtml but all it contains is an error message from the treasurydirect server i know the server is working because when i submit the same request via my browser i get the expected resultsattempt 2 using rvests html sessionurlf0 html formsf1 set valuesf02 pricedateyear2014 pricedatemonth12 pricedateday15test submit forms f1unfortunately this approach does not even leave r and results in the following error message from rsubmitting with submiterror in function type msg aserror true url malformedi cannot seem to figure out how to see what malformed text is being sent to rvest so that i can try to diagnose the problemany suggestions or tips to solving this seeming simple task would be greatly appreciated,['html'] +820251,dynamic height in cell issue in iphone6 and iphone6 plus i am implementing a functionality in which all labels of my cell has been resized as per the text containing with each labeli have implemented this functionality with the help of raywanderlich tutorial and its working fine for iphone 4s5 and 5s with ios 81 as shown in image below which shows iphone 5s simulator with ios 81 while i am running my app with iphone 6 or iphone 6 plus i got unexpected behavior as shown below image which shows iphone 6 simulatorand iphone 6 plus simulator i have created two custom cell nib files one for iphone 44s5 and 5s and second one is for iphone 6 and 6 plus as i am new with auto layout i have set constraints same both nibs i am showing both custom cell nib files with set constraints at below imagesiphone 44s5 and 5s nib file snapshotiphone 6 and iphone 6 plus custom cell nib file snapshoti also used following code snippet from where cell has been resized with dynamic height the code works for iphone iphone 4for ios 74s5 and 5s for ios 7 and ios 8 and 81 fine but not for iphone 6 and iphone 6 pluscode snippet cgfloatcalculateheightforconfiguredsizingcell 3memberlisttableviewcell withoutimage 3 iphone sizingcell sizingcellbounds cgrectmake00f 00f cgrectgetwidthselftblviewframe cgrectgetheightsizingcellbounds sizingcell setneedslayout sizingcell layoutifneeded cgsize size sizingcellcontentview systemlayoutsizefittingsizeuilayoutfittingcompressedsize cgsize size sizingcellcontentview systemlayoutsizefittingsizeuilayoutfittingcompressedsize withhorizontalfittingpriorityuilayoutprioritydefaulthigh verticalfittingpriorityuilayoutprioritydefaulthigh return sizeheight 10f add 10f for the cell separator heightplease give me a proper solution where am i going wrongi have surfed lot of things but unable to get proper way to solve this issue your help would be appreciablethanks in advanced,['ios'] +820279,coldfusion cfstatic includes all css files i am trying to use cfstatic in my indexcfm i am adding only greencss using cfstatic cfstatic should add minimized version of greencss only so my h1 text h1i should be greenh1 should be in green color but cfstatic is adding both greencss redcss am i missing configurationapplicationcfccomponent outputfalse thisname testing thissessionmanagement true thissessiontimeout createtimespan1 23 59 59 thismappingsorg expandpathorg function onrequeststart applicationcfstatic createobject orgcfstaticcfstatic init staticdirectory expandpathassets staticurl cfstaticassets indexcfmdoctype htmlhtml langenhead meta charsetutf8 titletesttitle cfscript applicationcfstaticinclude cssgreencsstrue cfscriptcfoutputapplicationcfstaticrenderincludescsscfoutputheadbody h1i should be greenh1bodyhtmlgreencss this is assetscssgreencss h1 colorgreenredcss this is assetscssredcss h1 colorredmy browser output is,['css'] +820347,unable to resolve target android21 i have the latest adt plugin for eclipse adt2304eclipse version luna service release 1 441still i am getting this error while importing a project unable to resolve target android21,"['java', 'android']" +820403,understanding js promises i would like to get a deeper understanding of how promises work internallytherefore i have some sample codevar p1 new promisefunctionresolve reject windowsettimeout function resolveres called 20var p2 new promisefunctionresolve reject windowsettimeout function resolveres called 20function chainpromises return p1thenfunctionval consolelogp1 return p2thenfunctionval consolelogp2 return val chainpromisesthenfunctionval consolelogvalhere a link to execute this codeas you would predict first p1 is resolved afterwards p2 and in the end the final then prints the resolv valuebut the api ref states the followingthen returns a new promise equivalent to the value you return from onfulfilledonrejected after being passed through promiseresolveso it would be interesting to know when exactly the then function is executedbecause the final then in the code is chained to the chainpromises i first thought thatit would execute after the function chainpromises returns something in this case another promiseif this would have been the case the val of the final then function would be the returned promisebut instead the final then waits until all promises inside the first then which are returned have been resolvedthis absolutely makes sense because in this way the then functions can be stacked buti do not really get how this is done since the api spec does not really cover what then returns and when the then functions is executedor in other words why does the final then function wait until all the promises are resolved inside the chainpromises function instead of just waiting for the first returned object as the api doc saysi hope i could make clear what i mean,['javascript'] +820482,using import in a cocoapods project i have a header in a cocoapods project i am working on in xcode 6 in which i have an import cocoa statement it builds fine in its own project but when i integrate it into the client app i get the following erroruse of import when modules are thisabledi checked the clang enable modules setting in every target of my client project as well as every target in the pods project and every single one is set to yes what could be triggering this error i can switch back to a import which does fix it but i would like to understand why this is happening since everything looks like it is configured properlyi pushed my podspec unzipkit but i also replaced the import statements with import to get it working also i am using cocoapods 0350 if you use this in your podfile it will get you the import versionpod unzipkit git commit 38cd0225015a245b0d31676b3f40d57f99147a,['objective-c'] +820495,what is the difference between json web signature jws and json web token jwt i have been coding a restful service in java this is what i have understood till now correct me if i am wrongtoken authorization is done using json web tokens jwt which have three parts the header the payload and the secret shared between the client and the server i understood this concept and stumbled over json web signature jws while reading about jwtjws also is an encoded entity similar to jwt having a header payload and a shared secretquestion what is the difference between the two concepts namely jwt and jws and if they are alike technically then whats the difference in their implementationthis is the first time i am working with token based auth so it is possible i have misunderstood the concept altogetherps i learned about jws while browsing through the examples on this websitethanks,['java'] +820507,is there general method to solve for a single unknown if the unknown variable changes i have a simple algebraic relationship that uses three variables i can guarantee that i know two of the three and need to solve for the third but i do not necessarily know which two of the variables i will know i am looking for a single method or algorithm that can handle any of the cases without a huge batch of conditionals this may not be possible but i would like to implement it in a more general sense rather than code in every relationship in terms of the other variablesfor example if this were the relationship3x 5y z 5i do not want to code thisfunctionint x int y return 5 3x 5yfunctionint x int z return 5 z 3x5and so on is there a standard sort of way to handle programming problems like this maybe using matrices parameterization etc,['c#'] +820519,python psycopg2 timeout i have a huge problemthere seems to be some hardware problems on the router of the server my python software runs on the connection to the database only is successfull about every third time so a psycopg2connect can take up to 5 minutes before i get an timeout exception20141223 150312461 error could not connect to server connection timed out is the server running on host 17220191 and acceptingthat is the code i am using connection to the dbtry db psycopg2connecthostdhost databaseddatabase userduser passworddpassword cursor dbcursorcursor factorypsycopg2extrasdictcursorexcept psycopg2databaseerror err printstrerr loggingerrorstrerr logginginfoprogram terminated sysexit1i tried some timeout additions for the query but that did not helped since the connection did not got established at allis there a way i can stop the program immediately when the connection could not be established,['python'] +820535,rendering an image as a node in threejs with svgrenderer or otherwise rendering spheres i have a circle element in an svg document to which i apply a radialgradient to give the illusion of it being a spheresvg version11 idsphere svg xmlns xmlnsxlink x0px y0px width640px height640px viewbox0 0 640 640 enablebackgroundnew 0 0 640 640 xmlspacepreserve defs radialgradient idsphere gradient cx2923262 cy2874077 r2492454 fx1477949 fy2745532 gradienttransformmatrix10729 0 0 10729 2359 2359 gradientunitsuserspaceonuse stop idsphere gradient 0 offset0 stylestopcolorf37d7f stop idsphere gradient 1 offset04847 stylestopcolored1f24 stop idsphere gradient 2 offset1 stylestopcolor7e1416 radialgradient defs circle fillurlsphere gradient cx320 cy320 r320svgit looks something like thisjsfiddlei can render this in a threejs webglrenderer container by using gabe lerners canvg library sphere asset is a div containing the svg element var red svg html new stringsphere assethtml var red svg canvas documentcreateelementcanvascanvgred svg canvas red svg htmlvar red svg texture new threetexturered svg canvasvar red particles new threegeometryvar red particle material new threepointcloudmaterial map red svg texture transparent true size 015 alphatest 010 var red particle count 25for var p 0 p red particle count p var px 09 mathrandom 05 py 09 mathrandom 05 pz 09 mathrandom 05 red particle new threevector3px py pz red particlesverticespushred particlevar red particle system new threepointcloudred particles red particle materialsceneaddred particle systemso far so good i can even programmatically modify the gradient and render different categories of particleswhat i would like to do is now switch over from webglrenderer to using an svgrenderer so that i can allow the end user to set the desired orientation and then export a vector image svg or converted to pdf on the back end that can be used for publicationquality workusing the svg sandbox example from threejs as the basis for experimentation i have tried a couple different techniques and have not had much luck i am hoping someone with experience with threejs may have some suggestionsmy first attempt was to use canvg to render the svg into a png image and then apply that to an image nodevar red svg html new stringsphere assethtmlvar red svg canvas documentcreateelementcanvascanvgred svg canvas red svg htmlvar red png data red svg canvastodataurlimagepngvar red node documentcreateelementns imagered nodesetattributens href red png datared nodesetattributens height 10red nodesetattributens width 10var red particle count 25for var i 0 i red particle count i var object new threesvgobjectred nodeclonenode objectpositionx 09 mathrandom 05 objectpositiony 09 mathrandom 05 objectpositionz 09 mathrandom 05 sceneaddobjectno nodes show up in my viewboxthe next thing i tried was a threesprite object using canvg and threetexture routinesvar red svg html new stringsphere assethtmlvar red svg canvas documentcreateelementcanvascanvgred svg canvas red svg htmlvar red svg texture new threetexturered svg canvasred svg textureneedsupdate truevar red sprite threeimageutilsloadtexturered png datavar red particle count 25for var p 0 p red particle count p var material new threespritematerial map red svg texture transparent true size 015 alphatest 010 var sprite new threesprite material spritepositionx 09 mathrandom 05 spritepositiony 09 mathrandom 05 spritepositionz 09 mathrandom 05 spritescaleset01 01 01 sceneaddspritethis was slightly better in that i get white opaque boxes where the spheres would otherwise appear in the rendered viewboxa third attempt was made to create an svg to nest within the parent svg node which contains a referenceable radialgradient with the id sphere gradientvar xmlns var svg documentcreateelementnsxmlns svgsvgsetattributensnull version 11svgsetattributensnull x 0pxsvgsetattributensnull y 0pxsvgsetattributensnull width 640pxsvgsetattributensnull height 640pxsvgsetattributensnull viewbox 0 0 640 640svgsetattributensnull enablebackground new 0 0 640 640var defs documentcreateelementnsxmlns defsvar radialgradient documentcreateelementnsxmlns radialgradientradialgradientsetattributensnull id sphere gradientradialgradientsetattributensnull cx 2923262radialgradientsetattributensnull cy 2874077radialgradientsetattributensnull r 2492454radialgradientsetattributensnull fx 1477949radialgradientsetattributensnull fy 2745532radialgradientsetattributensnull gradienttransform matrix10729 0 0 10729 2359 2359radialgradientsetattributensnull gradientunits userspaceonusevar stop0 documentcreateelementnsnull stopstop0setattributensnull offset 0stop0setattributensnull stopcolor f37d7fradialgradientappendchildstop0var stop1 documentcreateelementnsnull stopstop1setattributensnull offset 04847stop1setattributensnull stopcolor ed1f24radialgradientappendchildstop1var stop2 documentcreateelementnsnull stopstop2setattributensnull offset 1stop2setattributensnull stopcolor 7e1416radialgradientappendchildstop2defsappendchildradialgradientsvgappendchilddefsvar red circle documentcreateelementnsxmlns circlered circlesetattributefill urlsphere gradientred circlesetattributer 320red circlesetattributecx 320red circlesetattributecy 320svgappendchildred circlevar red particle count 25for var i 0 i red particle count i var object new threesvgobjectsvgclonenodetrue objectpositionx 085 mathrandom 05 objectpositiony 085 mathrandom 05 objectpositionz 085 mathrandom 05 sceneaddobjectno nodes are rendered adjustments of the circle elements r cx or cy do not change the end result interestingly if i change the fill attribute from urlsphere gradient to red i get a large circle mostly rendered outside my viewbox which is not attached to the scene it does not rotate with other elements in my parent scene like the sides of a cubeis there a working and performant way to draw spheres or rounded spherelike particles in space using a svgrenderer in threejs,['javascript'] +820565,global onstart on play framework 237 not working sorry if this question turns to be silly but i simply cannot find my mistake and i checked already plenty of posts here in so and other sitesi have setup a play 237 project using java i have created a globaljava file in the common package under the app directory in that file i override onstart and other hooks but i do not get them to work they simply do not execute at all heres the globaljava filepackage commonimport playapplicationimport playglobalsettingsimport playloggerpublic class global extends globalsettings override public void beforestartapplication application loggererrorgood bye cruel world superbeforestartapplication throw new runtimeexceptionwtf override public void onstartapplication application loggererrorgood bye cruel world superonstartapplication throw new runtimeexceptionwtf override public void onstopapplication application loggererrorgood bye cruel world superonstopapplication throw new runtimeexceptionwtf and inside the applicationconf heres the relevant part which is commented by default define the commonglobal object class for this application default to commonglobal in the root package applicationglobalcommonglobalwhat can be the problem thanks,['java'] +820566,java localdatetime parse error been trying for 4 hours to figure this outthis worksstring date jul012014 091012localdatetime dt localdatetimeparsedate datetimeformatterofpatternmddy hhmmss localeusthis will notstring date jul012014 091012localdatetime dt localdatetimeparsedate datetimeformatterofpatternmddy hhmmss localeusonly difference being the month all capitalized proper case of jul works neither jul or jul will work i also tried pattern of l with no luck what am i missing,['java'] +820601,spring boot commandlinerunner exception handling we are using springboot for a commandline application we are using javaxvalidation for validating commandline arguments now if we have a validation error how can we print friendly error message we do not want to show stack traceis there a exceptionhandler mechanism we could use when we are running springboot as commandlinerunnerthanksarunsource springbootapplication public class deploy implements commandlinerunner private static final logger logger loggerfactorygetloggerdeployclass autowired private deployconfig config autowired private deployservice deployservice mvn clean package springbootrepackage java jar targetspringbootexample100snapshotjar springprofilesactiveqa version10 param strings arguments throws exception override public void runstring strings throws exception try deployservicedeployconfig catch exception ve loggererrorerror vegetmessage loggerinfocreated stack configgetversion public static void mainstring args loggerinfostarting to run springapplicationrundeployclass args loggerinfocompleted the run configurationconfigurationenableconfigurationpropertiesconfigurationpropertiespublic class deployconfig notnull private string hello notnull private string version private string envkey public string gethello return hello public void sethellostring hello thishello hello public string getversion return version public void setversionstring version thisversion version public string getenvkey return envkey public void setenvkeystring envkey thisenvkey envkey public string tostring return tostringbuilderreflectiontostringthis clean runmvn clean package springbootrepackagejava jar targetspringbootexample100snapshotjar springprofilesactivepreprodqa version10validation checkjava jar targetspringbootexample100snapshotjar springprofilesactivepreprodqavalidation error20141225 205113325 error main osbspringapplicationrun application startup failedorgspringframeworkbeansfactorybeancreationexception error creating bean with name deploy injection of autowired dependencies failed nested exception is orgspringframeworkbeansfactorybeancreationexception could not autowire field private comexampledeployconfig comexampledeployconfig nested exception is orgspringframeworkbeansfactorybeancreationexception error creating bean with name deployconfig could not bind properties nested exception is orgspringframeworkvalidationbindexception orgspringframeworkvalidationbeanpropertybindingresult 1 errorsfield error in object target on field version rejected value null codes notnulltargetversionnotnullversionnotnulljavalangstringnotnull arguments orgspringframeworkcontextsupportdefaultmessagesourceresolvable codes targetversionversion arguments default message version default message may not be null at orgspringframeworkbeansfactoryannotationautowiredannotationbeanpostprocessorpostprocesspropertyvaluesautowiredannotationbeanpostprocessorjava334 springbeans413releasejar413release at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorypopulatebeanabstractautowirecapablebeanfactoryjava1202 springbeans413releasejar413release at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorydocreatebeanabstractautowirecapablebeanfactoryjava537 springbeans413releasejar413releasecomplete source source can be found in github,['java'] +820715,why is float64 cast to int when multiplying with a list when multiplying a numpy float with a list the float is automatically cast to int import numpy as np a 1 2 3 npfloat6420 a this behaves as 2 a1 2 3 1 2 3a normal float gives a typeerror 20 a this does nottraceback most recent call last file stdin line 1 in moduletypeerror cannot multiply sequence by nonint of type floathowever the numpy float cannot be used for indexing anpfloat6420traceback most recent call last file stdin line 1 in moduletypeerror list indices must be integers not numpyfloat64what is the logic behind this behaviour,['python'] +820741,struct or enum to use for serialization keys is there any reason why apple prefers using structs over enums in the lister demo for declaring keys for serialization is there might be some benefitsfor exampleprivate struct serializationkeys static let text text static let uuid uuid static let completed completed duplicated key static let descriptiontext texthere we might have potential duplicates for keys it is not a big question for small objects do not forget copypaste but for large objects with tens fields it can be a real problemwith enum we do not have such a problem private enum serializationkeys string case text text case uuid uuid case completed completed case descriptiontext text here we have compilers warning raw value for enum case is not uniquewill be happy to hear some thoughts on this,['ios'] +820779,javascript event listener for svg transform svg can perform transformations like sog transformtranslate800also whenever this attribute is manipulated by javascript for example the svg will move to the new point or scale etci was wondering whether it was possible to set an event listener that runs each time any svg object in the document is changed this is more of a concept question of how do browsers keep polling all the svg elements and is there a nice way to intercept that change i tried doing my homework understanding how svgs work and it seems like they have a transformation matrix that can be accessed via the dom the question is how does the browser know when to make that changereferences in short is there an event listener in javascript that can be built to listen for changes of svgs in genereal,"['javascript', 'html']" +820789,running spring boot within intellij results in unable to load javaxelexpressionfactory i am trying to run a simple spring boot application that has the following maven pomfileproperties projectbuildsourceencodingutf8projectbuildsourceencoding startclasscomptkonlineewsdproxyapplicationstartclass javaversion18javaversionpropertiesdependencies dependency groupidorgspringframeworkbootgroupid artifactidspringbootstarterwebartifactid dependency dependency groupidorgspringframeworkbootgroupid artifactidspringbootstartertomcatartifactid scopeprovidedscope dependency dependency groupidorgspringframeworkbootgroupid artifactidspringbootstartertestartifactid scopetestscope dependencydependenciesbuild plugins plugin groupidorgspringframeworkbootgroupid artifactidspringbootmavenpluginartifactid plugin pluginsbuildif i package the file using maven and run the application through java jar applicationjar the application starts up normally however if i run it from intellij by executing the main class the startup fails with the following error20141225 221855831 error 3388 main osbootspringapplication application startup failedorgspringframeworkbeansfactorybeancreationexception error creating bean with name orgspringframeworkbootcontextpropertiesconfigurationpropertiesbindingpostprocessor invocation of init method failed nested exception is javaxvalidationvalidationexception unable to instantiate configuration at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactoryinitializebeanabstractautowirecapablebeanfactoryjava1566 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorydocreatebeanabstractautowirecapablebeanfactoryjava539 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorycreatebeanabstractautowirecapablebeanfactoryjava476 at orgspringframeworkbeansfactorysupportabstractbeanfactory1getobjectabstractbeanfactoryjava302 at orgspringframeworkbeansfactorysupportdefaultsingletonbeanregistrygetsingletondefaultsingletonbeanregistryjava230 at orgspringframeworkbeansfactorysupportabstractbeanfactorydogetbeanabstractbeanfactoryjava298 at orgspringframeworkbeansfactorysupportabstractbeanfactorygetbeanabstractbeanfactoryjava198 at orgspringframeworkcontextsupportpostprocessorregistrationdelegateregisterbeanpostprocessorspostprocessorregistrationdelegatejava199 at orgspringframeworkcontextsupportabstractapplicationcontextregisterbeanpostprocessorsabstractapplicationcontextjava615 at orgspringframeworkcontextsupportabstractapplicationcontextrefreshabstractapplicationcontextjava465 at orgspringframeworkbootspringapplicationrefreshspringapplicationjava691 at orgspringframeworkbootspringapplicationrunspringapplicationjava321 at orgspringframeworkbootspringapplicationrunspringapplicationjava961 at orgspringframeworkbootspringapplicationrunspringapplicationjava950 at comptkonlineewsdproxyapplicationmainewsdproxyapplicationjava13 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava62 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43 at javalangreflectmethodinvokemethodjava483 at comintellijrtexecutionapplicationappmainmainappmainjava134caused by javaxvalidationvalidationexception unable to instantiate configuration at javaxvalidationvalidationgenericbootstrapimplconfigurevalidationjava279 at orgspringframeworkvalidationbeanvalidationlocalvalidatorfactorybeanafterpropertiessetlocalvalidatorfactorybeanjava223 at orgspringframeworkbootcontextpropertiesconfigurationpropertiesbindingpostprocessorjsr303validatorfactoryrunconfigurationpropertiesbindingpostprocessorjava361 at orgspringframeworkbootcontextpropertiesconfigurationpropertiesbindingpostprocessorafterpropertiessetconfigurationpropertiesbindingpostprocessorjava174 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactoryinvokeinitmethodsabstractautowirecapablebeanfactoryjava1625 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactoryinitializebeanabstractautowirecapablebeanfactoryjava1562 19 common frames omittedcaused by javaxvalidationvalidationexception hv0183 unable to load javaxelexpressionfactory check that you have the el dependencies on the classpath at orghibernatevalidatormessageinterpolationresourcebundlemessageinterpolatorinitresourcebundlemessageinterpolatorjava172 at orghibernatevalidatormessageinterpolationresourcebundlemessageinterpolatorinitresourcebundlemessageinterpolatorjava118 at orghibernatevalidatorinternalengineconfigurationimplinitconfigurationimpljava110 at orghibernatevalidatorinternalengineconfigurationimplinitconfigurationimpljava86 at orghibernatevalidatorhibernatevalidatorcreategenericconfigurationhibernatevalidatorjava41 at javaxvalidationvalidationgenericbootstrapimplconfigurevalidationjava276 24 common frames omittedhas anyone been able to run a spring boot application directly from intellij,['java'] +820861,how to run multiple test classes or test methods using maven in order to run all maven tests we can use mvn clean testif we want to run specific test class we can usemvn clean test dtestclassnameif we want to run specific method from specific test class we can usemvn clean test dtestclassnamemethodnamebut i want to runmultiple test classesnot all that belong to srctestjavamultiple test methods from specific test classnot all test methods of specific test class that belong to srctestjavaare there maven commands using which i can achieve above two,['java'] +820946,issues with six under django i am trying to use a package called vcrpy to accelerate the execution of my django application test suite i am using django 17 on mac with python 27 i added the following couple of lines to one of my tests import vcrwith vcruse cassetterecordingyamlthe result is an import error import vcr file libraryframeworkspythonframeworkversions27libpython27sitepackagesvcr init py line 2 in module from config import vcr file libraryframeworkspythonframeworkversions27libpython27sitepackagesvcrconfigpy line 6 in module from cassette import cassette file libraryframeworkspythonframeworkversions27libpython27sitepackagesvcrcassettepy line 12 in module from patch import cassettepatcherbuilder file libraryframeworkspythonframeworkversions27libpython27sitepackagesvcrpatchpy line 8 in module from stubs import vcrhttpconnection vcrhttpsconnection file libraryframeworkspythonframeworkversions27libpython27sitepackagesvcrstubs init py line 9 in module from sixmoveshttp client import importerror no module named http clientthe problematic code in the vcr package itself is import sixfrom sixmoveshttp client import httpconnection httpsconnection httpmessage httpresponsethe funny thing this code seems to run fine when i am just running it from a plain python console but it results in the above importerror under django or under the django managepy shell any idea what might be wrong some additional details about the location of the six module when i am running plain python console i get the following python 278 v278ee879c0ffa11 jun 29 2014 210735 gcc 421 apple inc build 56 dot 3 on darwintype help copyright credits or license for more information import six print six file libraryframeworkspythonframeworkversions27libpython27sitepackagessixpycdoing the same thing with import django djangosetup from managepy shell results in exactly the same directory and same sixpyc file,['python'] +821045,where is the pythonpath defined in the first place referring to the question here i would like to know where is the pythonpath defined in the very first place instead of adding a directory permanently to pythonpath by defining it in a bashrc local or global or through any other way i feel it would be better if it is added in the default source itself,['python'] +821070,uiviewanimatewithduration swift loop animation i am totally new to xcode and trying to learn swiftin viewcontrollerswift i managed to make a box animate from one point to another i thought it would be easy to loop this so the box will animate to one point and then animate back to its original position and then loop again i have managed to move the object to a position and in complete move it back again but that does not make i loop how can this be achievedi thought maybe this could work but i honestly do not knowlet boxmoves cgrectx 120 y 220 width 100 height 100 cgrectx 120 y 120 width 100 height 100for boxmove in boxmoves coloredsquareframe boxmovehow could i center it based on the devicewidth i assume there are some math involvedany good newbie tutortial sites on xcode to recommendkind regardsjohanmy codelet coloredsquare uiviewcoloredsquarebackgroundcolor uicolorbluecolorcoloredsquareframe cgrectx 120 y 120 width 100 height 100selfviewaddsubviewcoloredsquare found repeate but this will not animate as i wantuiviewanimatewithduration20 delay 02 options uiviewanimationoptionsrepeat animations uiviewanimatewithduration20 animations coloredsquareframe cgrectx 120 y 220 width 100 height 100 completion finished in uiviewanimatewithduration20 animations coloredsquareframe cgrectx 120 y 120 width 100 height 100,['ios'] +821104,javautildate equals does not seem to work as expected problemi have a mapdate foo and a list of objects from the database with an effectivedate property and i want to check to see if the date keys in my map are equal to any of the effectivedates in the database if so do stuff with foothe code looks something like thisfor bar bar databasebars foo foo new foo if datemapcontainskeybargeteffectivedate foo datemapgetbargeteffectivedate do stuff with foo and barhowever the datemapcontainskey call always returns false even though i am sure it is sometimes thereinvestigationas a sanity check i have printed out the long values of the dates as well as the results of an equals call and a compareto callfor date keydate datemapkeyset if keydate null continue make things simpler for now date effdate bargeteffectivedate string template keydate d effdate d equals b compareto dn systemoutprintftemplate keydategettime effdategettime effdateequalskeydate effdatecomparetokeydatethe resultskeydate 138853440 effdate 138853440 equals false compareto 0keydate 142007040 effdate 138853440 equals false compareto 1keydate 138853440 effdate 142007040 equals false compareto 1keydate 142007040 effdate 142007040 equals false compareto 0keydate 138853440 effdate 138853440 equals false compareto 0keydate 142007040 effdate 138853440 equals false compareto 1keydate 138853440 effdate 142007040 equals false compareto 1keydate 142007040 effdate 142007040 equals false compareto 0keydate 138853440 effdate 138853440 equals false compareto 0keydate 142007040 effdate 138853440 equals false compareto 1keydate 138853440 effdate 142007040 equals false compareto 1keydate 142007040 effdate 142007040 equals false compareto 0question1 should not equals and compareto agree i assume the implementation of javautildate at least should try to follow the recommendation of javalangcomparable2 the dateequals doc says thisthus two date objects are equal if and only if the gettime method returns the same long value for bothlooks like the gettime method returns the same long value for both of these dates yet equal returns false any ideas why this might be happening i have searched high and low but i have not found anyone describing the same problemps i am stuck using javautildate please do not just recommend jodatimepps i realize i could just change the structure of this code and probably get it working but this should work and i do not want to just work around it unless it is a known issue or something it just seems wrong,['java'] +821228,c portable class library equivalent of systemdiagnosticsstacktrace a program i am working on has a logging function appropriately named error to notify of errors without crashing the program however i would like to include a stack trace so these nonfatal errors can be more easily debugged my first instinct was to use systemdiagnosticsstacktrace which is unfortunately not available in pcls then i tried to throw and promptly catch an exceptiontry throw new exception catch exception ex return exstacktrace unfortunately this only provides the top of the call stack as it does not unravel the stack on its way down it does not provide any useful information so my question is this how do i get a stack trace in a c pcl function without throwing an error and catching it at the bottom of the stack i would prefer to keep the code entirely in the pcl and avoid using abstractions and platform specific implementation code for something so trivialedit as a response to a comment throw new exceptionex only adds another layer to the stack trace so it has two lines in the stack trace function but still fails to retrieve the full trace,['c#'] +821328,how should i braceinitialize an stdarray of stdpairs stdarraystdpairint int 2 ids 0 1 1 2 vs2013 errorerror c2440 initializing cannot convert from int to stdpair no constructor could take the source type or constructor overload resolution was ambiguouswhat am i doing wrong,['c++'] +821378,understand assembly code in c i am reading some c code embedded with a few assembly code i understand that asm is a statement to run assembly code but what does asm do in the following code according to the output ie r 16 it seems that asm does not effect the variable r is not itinclude stdiohstatic void foo static volatile unsigned int r asm 0x0019 r 1 4 printffoo un rplatform apple llvm version 60 clang6056 based on llvm 35svn on osx yosemite,['c'] +821384,why to inline source maps today i learned that it is possible to include source maps directly into your minified javascript file instead of having them in a separate exampleminmap file i wonder why anybody wants to do something like thatthe benefit from having source maps is clear to me one can for example debug errors with the original noncompressed source files while running the minified files the benefit from minimization is also clear the size of source file is greatly reduced making it quicker for browsers to downloadso why on earth i would want to include the source maps into the minified file given that the maps have size even greater than the minified code itself,['javascript'] +821418,viewpager first fragment shown is always wrong with fragmentstatepager i am trying to have the same view pager tabs design as the playstore 51x here is my layout xml version10 encodingutf8linearlayout xmlnsandroid androidlayout widthmatch parent androidlayout heightmatch parent androidlayout gravitycenter verticalcenter horizontal androidgravitycenter verticalcenter horizontal androidorientationvertical comastuetzpagerslidingtabstrip androidididtabs androidlayout widthmatch parent androidlayout height50dp androidbackgrounddrawablebackground tabs androidsupportv4viewviewpager androidididpager androidlayout widthmatch parent androidlayout heightmatch parent linearlayoutmy adapterpublic class mainpageradapter extends fragmentstatepageradapter private arraylistfakefragment fragments public mainpageradapterfragmentmanager fm superfm todo autogenerated constructor stub fragments new arraylistfakefragment override public fragment getitemint position todo autogenerated method stub ifposition getcount fakefragment fragment fakefragmentnewinstanceposition fragmentsaddfragment return fragmentsgetposition override public int getcount todo autogenerated method stub return categoryvalueslength override public charsequence getpagetitleint position todo autogenerated method stub return categoryvaluespositiongettitle override public int getitempositionobject object todo autogenerated method stub return position none my tabs and pager are showing correctly but i have noticed that the first fragment shown in the view pager is always the same as the second one then when i swipe once twice and swipe back to the first page i find that the correct fragment is now shown i cannot understand why this behaviour please i need some explanationssolution the issue was due to my fakefragmentnewinstance method definitionprivate static int positionpublic static fakefragment newinstanceint position todo autogenerated method stub fakefragmentposition position return new fakefragmenti changed it by using a setargumentsargs to my fakefragment instance and then retrieve it in oncreate method now all is working nice can somebody explain me why i think that in this way value of position will entierly depend on fragments lifecycle so will be always the expected position right,['android'] +821582,nsyearcalendarunit deprecated in ios i am using nsyearcalendarunit nsmonthcalendarunit nsdaycalendarunit but unfortunately these calendar units are reported as deprecated first in ios 80whats the alternative of them or how do i avoid these warningsunsigned unitflags nsyearcalendarunit nsmonthcalendarunit nsdaycalendarunit,['ios'] +821589,making a java applet meet high security standards this is my first post so please bear with me i have a working applet and i am trying to add it to my website for my portfolio my problem is i cannot get the applet to run without adding the directory i am running it locally for now to the site exception list my applet code is as followsapplet code mytetristetrisapplet archive mytetrisjarjar height 400 width 200i have created a jar file using intellij idea the manifest is as followsmanifestversion 10 permissions sandboxapplicationname tetrisi have signed the jar filethanks in advanceandy,['java'] +821729,relativelayout zorder lollipop i have a little layout working correctly on api 19 422 but cannot make it work on api 21 501here is the layoutxml version10 encodingutf8relativelayout xmlnsandroid androidlayout widthmatch parent androidlayout heightmatch parent button androidididstart button androidlayout widthmatch parent androidlayout heightmatch parent androidtextstylebold androidtextsize30sp androidbackgroundcolorstart button bg androidtextcolorcolorstart button text androidtextstringstart process textview androidididpro icon androidlayout widthmatch parent androidlayout heightmatch parent androidlayout margin10dp androidlayout alignparentrighttrue androidlayout alignparenttoptrue androidtextcolorandroidcolorwhite androidbackgrounddrawablepro icon androidtextpro androidgravitycenter androidtextappearanceandroidattrtextappearancemediumrelativelayoutreally simple stuff i just want the textview to be over the button in the relative layout i know relative layout stacks views in the order they are added in the xml but this seems not to be working the same on lollipop i cannot get the textview to be rendered over the button any ideacheers,['android'] +821751,calculating due date using business hours and holidays i need to calculate due date end date for slas as input values i have the start date and a timespan in minutes this calculation needs to take into account business hours weekends and holidaysi have seen a lot of examples where the input is start date and end date but have been struggling finding anything similar to the above input valuesis there an elegant solution to this problem is there a way to calculate due date without using a loop i cannot think of a way to do the calculation without doing something similar to the following terrible algorithmcreate a return variable due date and set it to input variablestart datecreate a control variable used minutes and set it to 0create a loop with the condition used minutes input timespaninside the loop add a second to the due date return variableinside the loop check if the second is within hours of operationchecking business hours weekends and holidays if so incrementcontrol variable used minutes by 1upon exiting the loop return variable due date,['sql'] +821778,how to add an entry point arrow to a tab bar controller in xcode 62 beta i am able to make some view controllers such as view controller or navigation view controller the entry point of my interface by dragging and dropping the entry point arrow on it it gives me something like this but when i want to drag this arrow on a tab bar controller it does not work so is that a bug or should i do it in another way,['ios'] +821889,creating string index with code first i am using entity framework 61 codefirst and my domain model is belowclass item index public string createdby set get when i use updatedatabase for migration i get the following error however as far as i researched index should work as annotation to stringcolumn createdby in table dboitems is of a type that is invalid for use as a key column in an index,['c#'] +821908,delete popup in silverlight for windows phone 8 i have tested my app for memory usage and suddenly seen a spike in memory when i load popups further it does not seem to go down after i try to close it i add the popup from the first pages cs file the one i navigate away frompopup popupif secondscreensecondscreenloaded popup popuptest new popup popuptestisopen true layoutrootchildrenaddpopuptestand when the second page is done i wish to delete the popup and thus free up memorytherefore i am unsure of how to delete a popup correctly in c can anyone please tell me this,['c#'] +821979,spring boot with spring security error creating bean with name securityfilterchainregistration i am trying to get the spring security filterchain working but spring boot seems to ignore my own bean and uses the one from websecurityconfigurationthese are the exceptions i get starting with an tomcat embedded failed to startorgspringframeworkbeansfactoryunsatisfieddependencyexception error creating bean with name securityfilterchainregistration defined in class path resource orgspringframeworkbootautoconfiguresecurityspringbootwebsecurityconfigurationclass unsatisfied dependency expressed through constructor argument with index 0 of type javaxservletfiltercaused by orgspringframeworkbeansfactorybeancreationexception error creating bean with name springsecurityfilterchain defined in class path resource orgspringframeworksecurityconfigannotationwebconfigurationwebsecurityconfigurationclass bean instantiation via factory method failedcaused by orgspringframeworkbeansbeaninstantiationexception failed to instantiate javaxservletfilter factory method springsecurityfilterchain threw exception nested exception is javalangillegalaccesserror class orgspringframeworksecurityconfigannotationauthenticationconfigurationproxy53 cannot access its superinterface orgspringframeworksecurityconfigannotationauthenticationconfigurationauthenticationconfigurationlazybeancaused by javalangillegalaccesserror class orgspringframeworksecurityconfigannotationauthenticationconfigurationproxy53 cannot access its superinterface orgspringframeworksecurityconfigannotationauthenticationconfigurationauthenticationconfigurationlazybeansorry for not showing the full stacktracemy security filterchain bean in my runclass bean public filterregistrationbean securityfilterchainregistration delegatingfilterproxy delegatingfilterproxy new delegatingfilterproxy delegatingfilterproxysettargetbeannameabstractsecuritywebapplicationinitializerdefault filter name filterregistrationbean registrationbean new filterregistrationbeandelegatingfilterproxy registrationbeansetnameabstractsecuritywebapplicationinitializerdefault filter name registrationbeanaddurlpatterns return registrationbean the runclass has following annotationsspringapplicationconfigurationenableautoconfigurationconfigurationmultipartconfigcomponentscanmy applicationproperties has no springsecurity keysdoes anyone know a solution thank youeditfull stacktraceorgspringframeworkcontextapplicationcontextexception unable to start embedded container nested exception is orgspringframeworkbootcontextembeddedembeddedservletcontainerexception unable to start embedded tomcat at orgspringframeworkbootcontextembeddedembeddedwebapplicationcontextonrefreshembeddedwebapplicationcontextjava124 at orgspringframeworkcontextsupportabstractapplicationcontextrefreshabstractapplicationcontextjava474 at orgspringframeworkbootcontextembeddedembeddedwebapplicationcontextrefreshembeddedwebapplicationcontextjava109 at orgspringframeworkbootspringapplicationrefreshspringapplicationjava691 at orgspringframeworkbootspringapplicationrunspringapplicationjava321 at orgspringframeworkbootspringapplicationrunspringapplicationjava961 at orgspringframeworkbootspringapplicationrunspringapplicationjava950 caused by orgspringframeworkbootcontextembeddedembeddedservletcontainerexception unable to start embedded tomcat at orgspringframeworkbootcontextembeddedtomcattomcatembeddedservletcontainerinitializetomcatembeddedservletcontainerjava97 at orgspringframeworkbootcontextembeddedtomcattomcatembeddedservletcontainerinittomcatembeddedservletcontainerjava74 at orgspringframeworkbootcontextembeddedtomcattomcatembeddedservletcontainerfactorygettomcatembeddedservletcontainertomcatembeddedservletcontainerfactoryjava374 at orgspringframeworkbootcontextembeddedtomcattomcatembeddedservletcontainerfactorygetembeddedservletcontainertomcatembeddedservletcontainerfactoryjava150 at orgspringframeworkbootcontextembeddedembeddedwebapplicationcontextcreateembeddedservletcontainerembeddedwebapplicationcontextjava148 at orgspringframeworkbootcontextembeddedembeddedwebapplicationcontextonrefreshembeddedwebapplicationcontextjava121 7 common frames omittedcaused by orgspringframeworkbeansfactorybeancreationexception error creating bean with name springsecurityfilterchain defined in class path resource orgspringframeworksecurityconfigannotationwebconfigurationwebsecurityconfigurationclass bean instantiation via factory method failed nested exception is orgspringframeworkbeansbeaninstantiationexception failed to instantiate javaxservletfilter factory method springsecurityfilterchain threw exception nested exception is javalangillegalaccesserror class orgspringframeworksecurityconfigannotationauthenticationconfigurationproxy49 cannot access its superinterface orgspringframeworksecurityconfigannotationauthenticationconfigurationauthenticationconfigurationlazybean at orgspringframeworkbeansfactorysupportconstructorresolverinstantiateusingfactorymethodconstructorresolverjava602 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactoryinstantiateusingfactorymethodabstractautowirecapablebeanfactoryjava1 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorycreatebeaninstanceabstractautowirecapablebeanfactoryjava1006 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorydocreatebeanabstractautowirecapablebeanfactoryjava504 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorycreatebeanabstractautowirecapablebeanfactoryjava476 at orgspringframeworkbeansfactorysupportabstractbeanfactory1getobjectabstractbeanfactoryjava302 at orgspringframeworkbeansfactorysupportdefaultsingletonbeanregistrygetsingletondefaultsingletonbeanregistryjava230 at orgspringframeworkbeansfactorysupportabstractbeanfactorydogetbeanabstractbeanfactoryjava298 at orgspringframeworkbeansfactorysupportabstractbeanfactorygetbeanabstractbeanfactoryjava198 at orgspringframeworkbootcontextembeddedservletcontextinitializerbeansgetorderedbeansoftypeservletcontextinitializerbeansjava176 at orgspringframeworkbootcontextembeddedservletcontextinitializerbeansaddasregistrationbeanservletcontextinitializerbeansjava141 at orgspringframeworkbootcontextembeddedservletcontextinitializerbeansaddasregistrationbeanservletcontextinitializerbeansjava136 at orgspringframeworkbootcontextembeddedservletcontextinitializerbeansaddadaptablebeansservletcontextinitializerbeansjava119 at orgspringframeworkbootcontextembeddedservletcontextinitializerbeansinitservletcontextinitializerbeansjava69 at orgspringframeworkbootcontextembeddedembeddedwebapplicationcontextgetservletcontextinitializerbeansembeddedwebapplicationcontextjava216 at orgspringframeworkbootcontextembeddedembeddedwebapplicationcontext1onstartupembeddedwebapplicationcontextjava202 at orgspringframeworkbootcontextembeddedtomcatservletcontextinitializerlifecyclelistenerlifecycleeventservletcontextinitializerlifecyclelistenerjava64 at orgapachecatalinautillifecyclesupportfirelifecycleeventlifecyclesupportjava117 at orgapachecatalinautillifecyclebasefirelifecycleeventlifecyclebasejava90 at orgapachecatalinacorestandardcontextstartinternalstandardcontextjava5095 at orgapachecatalinautillifecyclebasestartlifecyclebasejava150 at orgapachecatalinacorecontainerbasestartchildcallcontainerbasejava1409 at orgapachecatalinacorecontainerbasestartchildcallcontainerbasejava1399 at javautilconcurrentfuturetasksyncinnerrununknown source at javautilconcurrentfuturetaskrununknown source at javautilconcurrentthreadpoolexecutorrunworkerunknown source at javautilconcurrentthreadpoolexecutorworkerrununknown source at javalangthreadrununknown sourcecaused by orgspringframeworkbeansbeaninstantiationexception failed to instantiate javaxservletfilter factory method springsecurityfilterchain threw exception nested exception is javalangillegalaccesserror class orgspringframeworksecurityconfigannotationauthenticationconfigurationproxy49 cannot access its superinterface orgspringframeworksecurityconfigannotationauthenticationconfigurationauthenticationconfigurationlazybean at orgspringframeworkbeansfactorysupportsimpleinstantiationstrategyinstantiatesimpleinstantiationstrategyjava189 at orgspringframeworkbeansfactorysupportconstructorresolverinstantiateusingfactorymethodconstructorresolverjava591 27 common frames omittedcaused by javalangillegalaccesserror class orgspringframeworksecurityconfigannotationauthenticationconfigurationproxy49 cannot access its superinterface orgspringframeworksecurityconfigannotationauthenticationconfigurationauthenticationconfigurationlazybean at javalangreflectproxydefineclass0native method at javalangreflectproxygetproxyclass0unknown source at javalangreflectproxynewproxyinstanceunknown source at orgspringframeworkaopframeworkjdkdynamicaopproxygetproxyjdkdynamicaopproxyjava121 at orgspringframeworkaopframeworkproxyfactorybeangetproxyproxyfactorybeanjava368 at orgspringframeworkaopframeworkproxyfactorybeangetsingletoninstanceproxyfactorybeanjava322 at orgspringframeworkaopframeworkproxyfactorybeangetobjectproxyfactorybeanjava246 at orgspringframeworksecurityconfigannotationauthenticationconfigurationauthenticationconfigurationlazybeanauthenticationconfigurationjava118 at orgspringframeworksecurityconfigannotationauthenticationconfigurationauthenticationconfigurationgetauthenticationmangerbeanauthenticationconfigurationjava122 at orgspringframeworksecurityconfigannotationauthenticationconfigurationauthenticationconfigurationgetauthenticationmanagerauthenticationconfigurationjava81 at orgspringframeworksecurityconfigannotationwebconfigurationwebsecurityconfigureradapterauthenticationmanagerwebsecurityconfigureradapterjava229 at orgspringframeworksecurityconfigannotationwebconfigurationwebsecurityconfigureradaptergethttpwebsecurityconfigureradapterjava171 at orgspringframeworksecurityconfigannotationwebconfigurationwebsecurityconfigureradapterinitwebsecurityconfigureradapterjava276 at orgspringframeworksecurityconfigannotationwebconfigurationwebsecurityconfigureradapterinitwebsecurityconfigureradapterjava61 at orgspringframeworkbootactuateautoconfiguremanagementsecurityautoconfigurationmanagementwebsecurityconfigureradapterenhancerbyspringcglibd563c0b2initgenerated at orgspringframeworksecurityconfigannotationabstractconfiguredsecuritybuilderinitabstractconfiguredsecuritybuilderjava369 at orgspringframeworksecurityconfigannotationabstractconfiguredsecuritybuilderdobuildabstractconfiguredsecuritybuilderjava322 at orgspringframeworksecurityconfigannotationabstractsecuritybuilderbuildabstractsecuritybuilderjava39 at orgspringframeworksecurityconfigannotationwebconfigurationwebsecurityconfigurationspringsecurityfilterchainwebsecurityconfigurationjava92 at orgspringframeworksecurityconfigannotationwebconfigurationwebsecurityconfigurationenhancerbyspringcglib3cd4bac3cglibspringsecurityfilterchain3generated at orgspringframeworksecurityconfigannotationwebconfigurationwebsecurityconfigurationenhancerbyspringcglib3cd4bac3fastclassbyspringcgliba33c0bbainvokegenerated at orgspringframeworkcglibproxymethodproxyinvokesupermethodproxyjava228 at orgspringframeworkcontextannotationconfigurationclassenhancerbeanmethodinterceptorinterceptconfigurationclassenhancerjava309 at orgspringframeworksecurityconfigannotationwebconfigurationwebsecurityconfigurationenhancerbyspringcglib3cd4bac3springsecurityfilterchaingenerated at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokeunknown source at sunreflectdelegatingmethodaccessorimplinvokeunknown source at javalangreflectmethodinvokeunknown source at orgspringframeworkbeansfactorysupportsimpleinstantiationstrategyinstantiatesimpleinstantiationstrategyjava162 28 common frames omitted20141229 152039476 error 5736 main osbootspringapplication application startup failedorgspringframeworkcontextapplicationcontextexception unable to start embedded container nested exception is orgspringframeworkbootcontextembeddedembeddedservletcontainerexception unable to start embedded tomcat at orgspringframeworkbootcontextembeddedembeddedwebapplicationcontextonrefreshembeddedwebapplicationcontextjava124 at orgspringframeworkcontextsupportabstractapplicationcontextrefreshabstractapplicationcontextjava474 at orgspringframeworkbootcontextembeddedembeddedwebapplicationcontextrefreshembeddedwebapplicationcontextjava109 at orgspringframeworkbootspringapplicationrefreshspringapplicationjava691 at orgspringframeworkbootspringapplicationrunspringapplicationjava321 at orgspringframeworkbootspringapplicationrunspringapplicationjava961 at orgspringframeworkbootspringapplicationrunspringapplicationjava950 caused by orgspringframeworkbootcontextembeddedembeddedservletcontainerexception unable to start embedded tomcat at orgspringframeworkbootcontextembeddedtomcattomcatembeddedservletcontainerinitializetomcatembeddedservletcontainerjava97 at orgspringframeworkbootcontextembeddedtomcattomcatembeddedservletcontainerinittomcatembeddedservletcontainerjava74 at orgspringframeworkbootcontextembeddedtomcattomcatembeddedservletcontainerfactorygettomcatembeddedservletcontainertomcatembeddedservletcontainerfactoryjava374 at orgspringframeworkbootcontextembeddedtomcattomcatembeddedservletcontainerfactorygetembeddedservletcontainertomcatembeddedservletcontainerfactoryjava150 at orgspringframeworkbootcontextembeddedembeddedwebapplicationcontextcreateembeddedservletcontainerembeddedwebapplicationcontextjava148 at orgspringframeworkbootcontextembeddedembeddedwebapplicationcontextonrefreshembeddedwebapplicationcontextjava121 7 common frames omittedcaused by orgspringframeworkbeansfactorybeancreationexception error creating bean with name springsecurityfilterchain defined in class path resource orgspringframeworksecurityconfigannotationwebconfigurationwebsecurityconfigurationclass bean instantiation via factory method failed nested exception is orgspringframeworkbeansbeaninstantiationexception failed to instantiate javaxservletfilter factory method springsecurityfilterchain threw exception nested exception is javalangillegalaccesserror class orgspringframeworksecurityconfigannotationauthenticationconfigurationproxy49 cannot access its superinterface orgspringframeworksecurityconfigannotationauthenticationconfigurationauthenticationconfigurationlazybean at orgspringframeworkbeansfactorysupportconstructorresolverinstantiateusingfactorymethodconstructorresolverjava602 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactoryinstantiateusingfactorymethodabstractautowirecapablebeanfactoryjava1 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorycreatebeaninstanceabstractautowirecapablebeanfactoryjava1006 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorydocreatebeanabstractautowirecapablebeanfactoryjava504 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorycreatebeanabstractautowirecapablebeanfactoryjava476 at orgspringframeworkbeansfactorysupportabstractbeanfactory1getobjectabstractbeanfactoryjava302 at orgspringframeworkbeansfactorysupportdefaultsingletonbeanregistrygetsingletondefaultsingletonbeanregistryjava230 at orgspringframeworkbeansfactorysupportabstractbeanfactorydogetbeanabstractbeanfactoryjava298 at orgspringframeworkbeansfactorysupportabstractbeanfactorygetbeanabstractbeanfactoryjava198 at orgspringframeworkbootcontextembeddedservletcontextinitializerbeansgetorderedbeansoftypeservletcontextinitializerbeansjava176 at orgspringframeworkbootcontextembeddedservletcontextinitializerbeansaddasregistrationbeanservletcontextinitializerbeansjava141 at orgspringframeworkbootcontextembeddedservletcontextinitializerbeansaddasregistrationbeanservletcontextinitializerbeansjava136 at orgspringframeworkbootcontextembeddedservletcontextinitializerbeansaddadaptablebeansservletcontextinitializerbeansjava119 at orgspringframeworkbootcontextembeddedservletcontextinitializerbeansinitservletcontextinitializerbeansjava69 at orgspringframeworkbootcontextembeddedembeddedwebapplicationcontextgetservletcontextinitializerbeansembeddedwebapplicationcontextjava216 at orgspringframeworkbootcontextembeddedembeddedwebapplicationcontext1onstartupembeddedwebapplicationcontextjava202 at orgspringframeworkbootcontextembeddedtomcatservletcontextinitializerlifecyclelistenerlifecycleeventservletcontextinitializerlifecyclelistenerjava64 at orgapachecatalinautillifecyclesupportfirelifecycleeventlifecyclesupportjava117 at orgapachecatalinautillifecyclebasefirelifecycleeventlifecyclebasejava90 at orgapachecatalinacorestandardcontextstartinternalstandardcontextjava5095 at orgapachecatalinautillifecyclebasestartlifecyclebasejava150 at orgapachecatalinacorecontainerbasestartchildcallcontainerbasejava1409 at orgapachecatalinacorecontainerbasestartchildcallcontainerbasejava1399 at javautilconcurrentfuturetasksyncinnerrununknown source at javautilconcurrentfuturetaskrununknown source at javautilconcurrentthreadpoolexecutorrunworkerunknown source at javautilconcurrentthreadpoolexecutorworkerrununknown source at javalangthreadrununknown sourcecaused by orgspringframeworkbeansbeaninstantiationexception failed to instantiate javaxservletfilter factory method springsecurityfilterchain threw exception nested exception is javalangillegalaccesserror class orgspringframeworksecurityconfigannotationauthenticationconfigurationproxy49 cannot access its superinterface orgspringframeworksecurityconfigannotationauthenticationconfigurationauthenticationconfigurationlazybean at orgspringframeworkbeansfactorysupportsimpleinstantiationstrategyinstantiatesimpleinstantiationstrategyjava189 at orgspringframeworkbeansfactorysupportconstructorresolverinstantiateusingfactorymethodconstructorresolverjava591 27 common frames omittedcaused by javalangillegalaccesserror class orgspringframeworksecurityconfigannotationauthenticationconfigurationproxy49 cannot access its superinterface orgspringframeworksecurityconfigannotationauthenticationconfigurationauthenticationconfigurationlazybean at javalangreflectproxydefineclass0native method at javalangreflectproxygetproxyclass0unknown source at javalangreflectproxynewproxyinstanceunknown source at orgspringframeworkaopframeworkjdkdynamicaopproxygetproxyjdkdynamicaopproxyjava121 at orgspringframeworkaopframeworkproxyfactorybeangetproxyproxyfactorybeanjava368 at orgspringframeworkaopframeworkproxyfactorybeangetsingletoninstanceproxyfactorybeanjava322 at orgspringframeworkaopframeworkproxyfactorybeangetobjectproxyfactorybeanjava246 at orgspringframeworksecurityconfigannotationauthenticationconfigurationauthenticationconfigurationlazybeanauthenticationconfigurationjava118 at orgspringframeworksecurityconfigannotationauthenticationconfigurationauthenticationconfigurationgetauthenticationmangerbeanauthenticationconfigurationjava122 at orgspringframeworksecurityconfigannotationauthenticationconfigurationauthenticationconfigurationgetauthenticationmanagerauthenticationconfigurationjava81 at orgspringframeworksecurityconfigannotationwebconfigurationwebsecurityconfigureradapterauthenticationmanagerwebsecurityconfigureradapterjava229 at orgspringframeworksecurityconfigannotationwebconfigurationwebsecurityconfigureradaptergethttpwebsecurityconfigureradapterjava171 at orgspringframeworksecurityconfigannotationwebconfigurationwebsecurityconfigureradapterinitwebsecurityconfigureradapterjava276 at orgspringframeworksecurityconfigannotationwebconfigurationwebsecurityconfigureradapterinitwebsecurityconfigureradapterjava61 at orgspringframeworkbootactuateautoconfiguremanagementsecurityautoconfigurationmanagementwebsecurityconfigureradapterenhancerbyspringcglibd563c0b2initgenerated at orgspringframeworksecurityconfigannotationabstractconfiguredsecuritybuilderinitabstractconfiguredsecuritybuilderjava369 at orgspringframeworksecurityconfigannotationabstractconfiguredsecuritybuilderdobuildabstractconfiguredsecuritybuilderjava322 at orgspringframeworksecurityconfigannotationabstractsecuritybuilderbuildabstractsecuritybuilderjava39 at orgspringframeworksecurityconfigannotationwebconfigurationwebsecurityconfigurationspringsecurityfilterchainwebsecurityconfigurationjava92 at orgspringframeworksecurityconfigannotationwebconfigurationwebsecurityconfigurationenhancerbyspringcglib3cd4bac3cglibspringsecurityfilterchain3generated at orgspringframeworksecurityconfigannotationwebconfigurationwebsecurityconfigurationenhancerbyspringcglib3cd4bac3fastclassbyspringcgliba33c0bbainvokegenerated at orgspringframeworkcglibproxymethodproxyinvokesupermethodproxyjava228 at orgspringframeworkcontextannotationconfigurationclassenhancerbeanmethodinterceptorinterceptconfigurationclassenhancerjava309 at orgspringframeworksecurityconfigannotationwebconfigurationwebsecurityconfigurationenhancerbyspringcglib3cd4bac3springsecurityfilterchaingenerated at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokeunknown source at sunreflectdelegatingmethodaccessorimplinvokeunknown source at javalangreflectmethodinvokeunknown source at orgspringframeworkbeansfactorysupportsimpleinstantiationstrategyinstantiatesimpleinstantiationstrategyjava162 28 common frames omittedmy pomxml dependencies spring boot dependency groupidorgspringframeworkbootgroupid artifactidspringbootstarterwebartifactid version120releaseversion dependency dependency groupidorgspringframeworkbootgroupid artifactidspringbootstarterremoteshellartifactid version120releaseversion dependency spring framework dependency groupidorgspringframeworkgroupid artifactidspringcoreartifactid versionorgspringframeworkversionversion dependency dependency groupidorgspringframeworkgroupid artifactidspringcontextartifactid versionorgspringframeworkversionversion dependency dependency groupidorgspringframeworkgroupid artifactidspringwebartifactid versionorgspringframeworkversionversion dependency dependency groupidorgspringframeworkgroupid artifactidspringtxartifactid versionorgspringframeworkversionversion dependency dependency groupidorgspringframeworkgroupid artifactidspringormartifactid versionorgspringframeworkversionversion dependency dependency groupidorgspringframeworkgroupid artifactidspringtestartifactid versionorgspringframeworkversionversion dependency dependency groupidorgspringframeworkgroupid artifactidspringwebmvcartifactid versionorgspringframeworkversionversion dependency dependency groupidorgspringframeworkgroupid artifactidspringjdbcartifactid versionorgspringframeworkversionversion dependency spring security dependency groupidorgspringframeworksecuritygroupid artifactidspringsecuritycoreartifactid versionorgspringframeworksecurityversionversion dependency dependency groupidorgspringframeworksecuritygroupid artifactidspringsecuritywebartifactid versionorgspringframeworksecurityversionversion dependency dependency groupidorgspringframeworksecuritygroupid artifactidspringsecurityconfigartifactid versionorgspringframeworksecurityversionversion dependency spring data mongodb dependency groupidorgspringframeworkdatagroupid artifactidspringdatamongodbartifactid version152releaseversion version161releaseversion dependency mongodb dependency groupidorgmongodbgroupid artifactidmongojavadriverartifactid version2123version dependency servlet dependency groupidorgapachetomcatgroupid artifactidtomcatservletapiartifactid version8015version dependency jsp dependency groupidorgapachetomcatgroupid artifactidtomcatjspapiartifactid version8015version dependencyedit 2could it be that the problem is in my security classconfigurationenablewebmvcsecuritypublic class applicationsecurity extends websecurityconfigureradapter autowired private mongotemplate mongotemplate override protected void configurehttpsecurity http throws exception httpauthorizerequestsantmatchersregister login lostpasswordanonymous antmatchersadminadminhasroleadmin antmatchersuser user page pagehasanyroleuser company user company master admin antmatcherscompany companyhasanyrolecompany user company master admin anyrequestauthenticated and formloginloginpageloginfailureurlloginerrortrueusernameparameterusernamepasswordparameterpasswordloginprocessingurlsecurity check successhandlernew myauthenticationsuccesshandlerthismongotemplate httplogoutlogouturllogoutinvalidatehttpsessiontruelogoutsuccessurl override public void configureauthenticationmanagerbuilder auth throws exception daoauthenticationprovider provider new daoauthenticationprovider providersetuserdetailsservicenew myuserdetailsservicethismongotemplate providersetpasswordencodernew shapasswordencoder256 authauthenticationproviderprovider edit 3the app is running but when i get the app via the browser i getwhitelabel error pagethis application has no explicit mapping for error so you are seeing this as a fallbackmon dec 29 172929 cet 2014there was an unexpected error typenot found status404no message availablewhat is now wrong,['java'] +822044,best pratice for reusing sqlconnection i have come from java experience and am trying to start with c i have read sqlconnection sqlcommand sqldatareader ithisposable and i can understand that the best practice to connecting to a db is wrapping sqlconnection sqlcommand and sqldatareader in their own using blockbut in java we use to encapsulate the connection into a factory method create it only once and reuse it for all queries even multithreaded ones only statements and result sets are created for each query and closed asapis not creating a new sqlconnection for each query kinda overkill cannot it be reused,"['c#', '.net']" +822102,behavior of f unmanaged type constraint f supports a type constraint for unmanaged this is not the same as a value type constraint like struct constraints msdn notes that the behavior of the unmanaged constraint isthe provided type must be an unmanaged type unmanaged types are either certain primitive types sbyte byte char nativeint unativeint float32 float int16 uint16 int32 uint32 int64 uint64 or decimal enumeration types nativeptr or a nongeneric structure whose fields are all unmanaged typesthis is a very handy constraint type when doing platform invocation and more than once i wish c had a way of doing this c does not have this constraint c does not support all constraints that can be specified in cil an example of this is an enumeration in c you cannot do thispublic void foott bar where tenumhowever the c compiler does honor the enum constraint if it comes across it in another library jon skeet is able to use this to create his unconstrained melody projectso my question is is fs unmanaged constraint something that can be represented in cil like an enum constraint and just not exposed in c or is it enforced purely by the f compiler like some of the other constraints f supports like explicit member constraint,['c#'] +822104,not being prompted to enable location services in app update this is not a duplicate i have already added the required key to the infoplist as stated in my original question and the issue remains i have tried all three keys in various combinationsbefore anyone gets upset i have read through many apple dev forum posts and stack overflow posts and cannot figure out why my app refuses to prompt the user to allow when in use authorizationi have added the following key to my infoplist file with an accompanying string valuenslocationwheninuseusagedescriptioni have then written both in swift and objc the code that should prompt the userproperty cllocationmanager locationsynthesize locationlocation cllocationmanager alloc initlocationdelegate selflocationdesiredaccuracy kcllocationaccuracybestlocationthistancefilter kclthistancefilternonelocation requestwheninuseauthorizationlocation startupdatinglocationi am using the following cllocationmanagerdelegate methods void locationmanagercllocationmanager manager didupdatelocationsnsarray locations void locationmanagercllocationmanager manager didchangeauthorizationstatusclauthorizationstatusstatusthis was basically copied straight from the apple locateme sample codeno matter what various sequences or minor changes i try the app never prompts to allow authorization i have used a switch statement to determine the state of cllocationmanager authorizationstatus but continually recieve a not determined responseif cllocationmanager locationservicesenabled switch cllocationmanager authorizationstatus case kclauthorizationstatusauthorizedalways nslogalways authorized break case kclauthorizationstatusdenied nslogdenied break case kclauthorizationstatusauthorizedwheninuse nslogauthorized in use break case kclauthorizationstatusnotdetermined nslognot determined break case kclauthorizationstatusrestricted nslogrestricted break any help would be greatly appreciated i am running xcode 62 6c101 with ios 812 physical device and ios 82 12d5452a simulator for testing,"['ios', 'objective-c']" +822123,get all element attributes using protractor according to the documentation to get a single attribute by name you can use getattribute on a webelementvar myelement elementbyidmyidexpectmyelementgetattributemyattrtoequalmyvaluebut how can i get all of the attributes that an element has there is no information about this use casefunctionality in the protractor api,['javascript'] +822225,hibernate thisabled insert batching when using an identity identifier generator the hibernate documentation says hibernate thisables insert batching at the jdbc level transparently if you use an identity identifier generatorbut all my entities have this configurationidgeneratedvaluestrategy javaxpersistencegenerationtypeidentityprivate integer idwhen i am using this identity above sowhats the problem with identity is the batch insert thisabledhow can i solve this,['java'] +822280,can i use knitr to apply css styles to individual table cells is it possible to apply a class attribute to individual table cells using knitr i have successfully applied a class attribute to the section heading that contains a knitrkable generated table and used that to format the entire table however i would like to be able to conditionally format individual cells which would require being able to apply a class to specific td elementsmy current workaround is to programmatically wrap the cell contents in a pair of span tags and pass that on to knitrkable this approach only allows me to format the text inside the cell versus the entire cell eg setting the cell background color heres an example of what i am currently using read in the report process the data send to kablerpt generatereportmutaterpt col2 ifelseabscol2 threshold pastespan classwarning sprintf2f col2 span sprintf2f col2 knitrkableformatmarkdown align cl repr 4 colnames gsub br colnameswhich results in the following example html outputtd alignrightspan classwarning 174 spantdi would like to be able to have knitrkable generate something like thistd alignright classwarning 174 tdthat way i could apply css styles to the td tag vice the span tag,"['html', 'css']" +822302,ipad landscape and portrait different layouts with size class how to design ipad landscape and portrait screens with different layouts using size classi could find only wregular and hregular for both orientations example i need to align 2 views vertically in portrait and horizontally in landscape using size class,"['ios', 'iphone']" +822367,why are there frozen constants everywhere we can easily find such style from lots of famous repositories like rack rails etcfor example in rackpath info path infofreezerequest method request methodfreezescript name script namefreezequery string query stringfreezecache control cachecontrolfreezecontent length contentlengthfreezecontent type contenttypefreezeanother examle in railshttp if modified since http if modified sincefreezehttp if none match http if none matchfreezehttp if none match http if none matchfreezei wonder why these constant strings are frozen since they are all constants there should be only one instance of course we can put foofreeze somewhere to reference the same singleton instance however people usually write literal variable name like http if modified sinceinsteadso in my opinion it does not make any difference in spite of using freeze so why do people freeze constants,"['ruby-on-rails', 'ruby']" +822401,if both 0 0 and 0 0 are true than why is 0 0 false we all know javascript does funky conversions when testing for equality but what exactly happens under the hood 0 0true 0 0true 0 0falseyes it was naive of me to expect transitivity from operator,['javascript'] +822429,interactive pixel information of an image in python short version is there a python method for thisplaying an image which shows in real time the pixel indices and intensities so that as i move the cursor over the image i have a continually updated thisplay such as pixel103214 198 for grayscale or pixel103214 13824211 for rgblong versionsuppose i open a grayscale image saved as an ndarray im and thisplay it with imshow from matplotlibim pltimreadimagepngpltimshowimcmgraywhat i get is the image and in the bottom right of the window frame an interactive thisplay of the pixel indices except that they are not quite as the values are not integers x13464 y129169 for exampleif i set the thisplay with correct resolutionpltaxisequalthe x and y values are still not integersthe imshow method from the spectral package does a better jobimport spectral as spcspcimshowimthen in the bottom right i now have pixel103152 for examplehowever none of these methods also shows the pixel values so i have two questionscan the imshow from matplotlib and the imshow from scikitimage be coerced into showing the correct integer pixel indicescan any of these methods be extended to show the pixel values as well,['python'] +822438,android view 3d rotate transformation on big resolution screens i am implementing 3d card flip animation for android api 14 and have an issue with big screen tablets 2048 dpi during problem investigation i have come to the following basic blocktried to just transform a view simple imageview using matrix and rotatey of camera by some angle and it works ok for angle 60 and angle 120 transformed and thisplayed but image thisappears just not thisplayed when angle is between 60 and 120 here is the code i useprivate void applytransformfloat degree float values 10f 00f 00f 00f 10f 00f 00f 00f 10f float centerx image1getmeasuredwidth 20f float centery image1getmeasuredheight 20f matrix m new matrix msetvaluesvalues camera camera new camera camerasave camerarotateydegree cameragetmatrixm camerarestore mpretranslatecenterx centery 1 draws fine without these 2 lines mposttranslatecenterx centery 2 image1setimagematrixmand here is my layout xml xml version10 encodingutf8 framelayout xmlnsandroid androidlayout widthmatch parent androidlayout heightmatch parent imageview androidididimageview01 androidlayout widthwrap content androidlayout heightwrap content androidlayout gravitycenter androidsrcdrawablenaponer androidclickabletrue androidscaletypematrix imageviewframelayout so i have the following casesworks fine for any angle any center point if running on small screens 800x480 1024x720 etcworks ok for angle 60 and 120 when running on big screen devices 2048x1536 2560x1600works ok for any angle on any device if rotation not centered matrix pre and post translations commented out fails image thisappears when running on big screen device rotation centered and angle is between 60 and 120 degreesplease tell what i am doing wrong and advise some workaround thank you,['android'] +822459,updown arrow key issue with typeahead control angular bootstrap ui check this plnkr i have implemented typeahead control by default in type ahead control they are not setting any maxheight or height to list but as per requirement i have to fix height of list to 110px so when we have longer list at a time only 4 data will be shown and rest can be seen by scrolling downscrolling is working while user click on scroll updown arrows but it is not working with keyboard updown keysthe problem is explained in stepstype something ie a to get data in typeahead list will be populated press downarrow key focus will be on list itempress downarrow key 45 time to go further down when we traversedown to list scroll is not getting movedit always show top 4 items in list ideal behavior is it should shiftuser is able to scroll by clicking on scroll manually but with arrow key it is not scrollinghtmldoctype htmlhtml ngappuibootstrapdemohead script srcajaxgoogleapiscomajaxlibsangularjs1216angularjsscript script srcangularuigithubiobootstrapuibootstraptpls0120jsscript script srcexamplejsscript link hrefnetdnabootstrapcdncombootstrap311cssbootstrapmincss relstylesheet link hrefstylecss relstylesheetheadbodydiv classcontainerfluid ngcontrollertypeaheadctrl h4static arraysh4 premodel selected jsonpre input typetext ngmodelselected typeaheadstate for state in states filterviewvalue limitto8 classformcontrol divbodyhtmlcssdropdownmenu height110px overflowautojavascript datalistscopestates alabama alaska arizona arkansas california colorado connecticut delaware florida georgia hawaii idaho illinois indiana iowa kansas kentucky louisiana maine maryland massachusetts michigan minnesota mississippi missouri montana nebraska nevada new hampshire new jersey new mexico new york north dakota north carolina ohio oklahoma oregon pennsylvania rhode island south carolina south dakota tennessee texas utah vermont virginia washington west virginia wisconsin wyoming,['css'] +822526,php create multiple csv files in memory then compress i have a requirement to create 3 csv files in memory during a single http request zip the files into a single compressed file and return the compressed file as a http responsei have the following code to create the zip filefiles arrayfile1 file2zipname filezipzip new ziparchivezipopenzipname ziparchivecreateforeach files as file zipaddfilefilezipcloseheadercontenttype applicationzipheadercontentthisposition attachment filenamezipnameheadercontentlength filesizezipnamereadfilezipnamehowever i do not know how to create the csv files in memory how can i achieve this,['php'] +822655,watchkit simulator would not load app originally i thought this was an issue of the code i was writing but i have just downloaded four or five watchkit projects even one from apple all of them fail to loadi have uninstalled xcode reinstalled it and still nothing any one else experiencing the same issue workarounds solutionsyou can see in the screenshot above what the loading screen looks like,['ios'] +822717,pdfjs get the text colour i have a simple pdf file containing the words hello world each in a different colouri am loading the pdf like thispdfjsgetdocumenttestpdfthen onpdf function onpdf pdf pdfgetpage 1 then onpage function onpage page pagegettextcontentthen ontext function ontext text consolelog jsonstringify text and i get a json output like this items str hello dir ltr width 29592 height 12 transform 12 0 0 12 568 7741 fontname g font 1 str world dir ltr width 2798398 height 12 transform 12 0 0 12 865 7741 fontname g font 1 styles g font 1 fontfamily serif ascent 0891 descent 0216 however i have not been able to find a way to determine the colour of each word when i render it it renders properly so i know the information is in there somewhere is there somewhere i can access this,['javascript'] +822724,indent even rows of hexagons in css i currently have a list of hexagons images that i have wrap to the next line when the browser width decreases however when this happens they form even lines as seen in the first image each starting at the same point on the x axis here is the js fiddle albeit the hexes do not flow right because they are not images the real code for this isdiv classcontainer span img classhex srcimghexpng span divand the css iscontainer paddingtop 80px width 50 marginleft auto marginright autocontainer span lineheight 129px thisplay inlineblockcontainer hex thisplay block marginleft auto marginright autowhat i would like to do is alternate the rows such that every other row starts at an offset of the hexagon size as seen in figure two it should also be noted that this example also has a negative y position relative to the respective position as determined from the first image is there a way to do this with just css i would like to avoid using a library if at all possiblethis is similar to the question asked here but i need the entire structure to be able to have an undetermined number of rows so the solution where i specify which items are in which rows is not feasible for my application,"['html', 'css']" +822847,what is the path of oat file in android 50 android 50 uses dex2oat to convert dex file to oat file when app installingbut in can only find bootoat on my phonewhere is the exactly path of convrted oat filei want to have one for investigation,['android'] +822858,android how to make step by step wizard i want to make a registration form for my application i want to ask afew question in each step i want to have 3 steps and users should move to next step how can i do something like this in android in one activity,['android'] +822924,thisplay background grid by using image with css the updated demo works quite well except for the fact that the background image is getting resized when i changebackgroundsize 20px 20pxis it possible to keep the original image size and make background images overlap hide the part of image that exceeds the topleft box 20px 20px the b plan would be to to crop the image with js in set base64 image content,"['javascript', 'css']" +822955,threaded video player sync thisclaimeri asked this question a few days ago on codereviewbut got no answerhere i change the question format from review request to a specific problemsi am developing a video player with the following designthe main thread is gui thread qt sdksecond thread player thread which accepts commands from the gui thread to play forward backward stop etc nowthis thread runs in a constant loop and and uses mutexes and wait conditions to live in sync with the main thread commandsi have 2 problems with this codei do not feel my design is completely correcti am using both mutex locks and atomic variablesi wonder if i can stay only with the atomics and use locks only for setting the wait conditionsi am experiencing inconsistent bugsprobably due to the condition race when the play command tries to lock mutex which is already locked by the thread while the play loop is working when i run play commands which activates a loop inside the thread loop so i suppose it blocks the access to the shared variables to the main threadi have stripped off the code from unneeded stuff and it generally goes like this void playerthreaddrawthreadthread method passed into new boostthread some init goes here whiletrue boostunique lockboostmutex lockm mutex m eventwaitlock wait for event ifm threadrun break exit the tread if we are in playback modeplay in a loop till interrupted ifm isplaymode true whilem frameindex m totalframes m isplaymode play m frameindex m isplaymode false elsewe are in a single frame play mode ifm cleanmode just clear the screen with a color clear the screen from the last frame wait for the new movie to get loaded m eventwaitlock load new movie else render a single frame play single frame here are the member functions of the above class which send commands to the thread loopvoid playerthreadplayforwardslot boostunique lockboostmutex lockm mutex ifm cleanmodereturn m isplaymode false m frameindex m eventnotify one void playerthreadplaybackwardslot boostunique lockboostmutex lockm mutex ifm cleanmodereturn m isplaymode false m frameindex ifm frameindex 0 m frameindex 0 m eventnotify one void playerthreadplayslot boostunique lockboostmutex lockm mutex ifm cleanmodereturn m isplaymode true m eventnotify one tell thread to start playing all the flag members like m cleanmode m isplaymode and m frameindex are atomics stdatomicint32 t m frameindex stdatomicbool m isplaymode stdatomicbool m cleanmodethe questions summarydo i need mutex locks when using atomicsdo i set waiting in the correct place inside the while loop of thethread any suggestion of a better designupdatethough i got an answer which seems to be in the right direction i do not really understand itespecially the pseudocode part which is talking about serviceit is completely unclear to me how it would worki would like to get a more elaborated answerit is also strange that i received only one constructive answer to such a common problemso i am resetting the bounty,['c++'] +823014,why do i not get a warning for casting a pointer to an int the following piece of code gives a warning for casting from a pointer to an int which makes a perfect senseint foo 1 2 3define barx foointx 3char baz quuxbarbazon the other hand the following code compiles without any warnings regardless of the fact that it may cause a runtime errorinclude ctypeh some codechar baz quuxisalphabazwhen i opened ctypeh to look at isalpha i found that it is a macro that uses a couple of other macros define isbitbit 1 bitenum some identifiers isalpha isbit 2 some identifiersextern const unsigned short int ctype b loc void throw attribute const define isctypec type ctype b loc int c unsigned short int type define isalphac isctypec isalphaas you can probably see the result of expanding the isalpha macro still explicitly casts the pointer baz to an int however this does not give any warnings when compiled so apparently both pieces of code perform the same operation ie casting a char to an int yet one gives a warning and the other does not whynote compilation commands with the same options were used to compile the programs that contained these pieces of codecompiler versiongcc ubuntu 48219ubuntu1 482,['c'] +823161,swift error reference to generic type dictionary requires arguments in the error reference to generic type dictionary requires arguments in is appearing on the first line of the function i am trying to have the function return an nsdictionary retrieved from an api anyone know what could be going on hereclass func getcurrentweatherlongitude float latitude floatdictionarylet baseurl nsurlstring apikeylet forecasturl nsurlstring longitudelatitude relativetourlbaseurllet sharedsession nsurlsessionsharedsessionlet downloadtask nsurlsessiondownloadtask sharedsessiondownloadtaskwithurlforecasturl completionhandler location nsurl response nsurlresponse error nserror void in iferror nil printlnlocation let dataobject nsdatacontentsofurllocation let weatherdictionary nsdictionary nsjsonserializationjsonobjectwithdatadataobject options nil error nil as nsdictionary return weatherdictionary else printlnerror return nil editsecond issue class func getcurrentweatherlongitude float latitude floatnsdictionary let baseurl nsurlstring apikey let forecasturl nsurlstring longitudelatitude relativetourlbaseurl let sharedsession nsurlsessionsharedsession let downloadtask nsurlsessiondownloadtask sharedsessiondownloadtaskwithurlforecasturl completionhandler location nsurl response nsurlresponse error nserror void in iferror nil printlnlocation let dataobject nsdatacontentsofurllocation let weatherdictionary nsdictionary nsjsonserializationjsonobjectwithdatadataobject options nil error nil as nsdictionary return weatherdictionary error nsdictionary not convertible to void else printlnerror return nil error type void does not conform to protocol nilliteralconvertible,"['ios', 'iphone']" +823214,is declaration of variables expensive while coding in c i came across the below situationint function if somecondition return false internalstructure str1 internalstructure str2 char datapointer float xyz do something here with the above local variables considering the if statement in the above code can return from the function i can declare the variables in two places before the if statementafter the if statement as a programmer i would think to keep the variable declaration after if statement does the declaration place cost something or is there some other reason to prefer one way over the other,['c'] +823348,how to make selector in android studio while taking a course i was instructed to make an xml selector for a button the course said to make a new android xml in eclipse but i am using android studioalso when i custom write the code it gives me an error it says element selector must be declaredgot code from here android how to make a drawable selector does anyone know how to do this in android studio,['android'] +823406,lollipops backgroundtint has no effect on a button i have a button in my activity and i would like it to have my themes accent colorinstead of making my own drawables like we had to do prelollipop naturally i would like to use the new backgroundtint attributebutton androidididbtnaddcode androidlayout widthmatch parent androidlayout heightwrap content androidbackgroundtintcoloraccent androidtextstringaddressinfo edit addcode unfortunately it has no effect the button stays grayi tried different values for backgroundtintmode which did not change anythingi also tried doing it programmatically in my activity which did not change anythingaddcodeviewfindviewbyidridbtnaddcodesetbackgroundtintlist getresourcesgetcolorstatelistrcoloraccentwhy is my tint ignorededitjust to clarify i am indeed testing on a lollipop deviceother widgets eg edittext are correctly and automatically tinted,['android'] +823458,async tasks and locks i have a list of elements that should be updated by two processes first one is the ui thread controlled by the user second one is a background process that retrieves information from a web servicesince this second process is io bound it seems suitable for async tasks this leads me to a few questionssince async tasks do not run on separate threads it seems i do not need any kind of lock when updating this list righton the other hand can we assume that async tasks will never run on separate threadsi am talking about a windows forms application maybe in the future i want it to run it as a console application afaik in console applications async tasks run on separate threads whats the preferred idiom to ask a task if it is running on a separate thread this way i can establish a lock when necessarythe fact that i do not know if i really need a lock makes me wonder wether this is the best design or not would it make sense to stick to taskrun even for this kind of io bound code,"['c#', '.net']" +823624,angularjs error cross origin requests are only supported for protocol schemes http data chromeextension https i have three files of a very simple angular js applicationindexhtmldoctype htmlhtml ngappgemstore head script srcscript script typetextjavascript srcappjsscript head body ngcontrollerstorecontroller as store div classlistgroupitem ngrepeatproduct in storeproducts h3productname em classpullrightproductprice currencyemh3 div productcolorproductcolor bodyhtmlproductcolorhtmldiv classlistgroupitem h3hello em classpullrightbrotheremh3divappjsfunction var app angularmodulegemstore appcontrollerstorecontroller functionhttp thisproducts gem appdirectiveproductcolor function return restrict e element directive templateurl productcolorhtml var gem name shirt price 2311 color blue name jeans price 509 color red i started getting this error as soon as i entered an include of productcolorhtml using custom directive named productcolorxmlhttprequest cannot load filecproductcolorhtml cross origin requests are only supported for protocol schemes http data chromeextension https chromeextensionresourceangularjs11594 error failed to execute send on xmlhttprequest failed to load filecproductcolorhtmlwhat may be going wrong is it a path issue for productcolorhtmlall my three files are in the same root folder cuserproject,"['javascript', 'html']" +823629,deleter type in unique ptr vs shared ptr i thought it is very curious when i thiscovered that the standard defines stdunique ptr and stdshared ptr in two totally different ways regarding a deleter that the pointer may own here is the declaration from cppreferenceunique ptr and cppreferenceshared ptrtemplate class t class deleter stddefault deletet class unique ptrtemplate class t class shared ptras you can see the unique ptr saves the type of the the deleterobject as a template argument this can also be seen in the way the deleter is retrieved from the pointer later on unique ptr has a member function to retrieve the deletertemplate class t class deleter stddefault deletetdeleter unique ptrt deleterget deleter for shared ptr this is not a member functiontemplateclass deleter class tdeleter get deleterconst stdshared ptrt pcan someone explain the rational behind this difference i clearly favor the concept for unique ptr why is this not applied to shared ptr aswell also why would get deleter be a nonmember function in the latter case,['c++'] +823631,drag and drop with selenium webdriver on java drag and drop with selenium webdriver on javasrcdiv classddimg altworld srctestpng stylemargintop 5pxwidthautoheight16pxpaddingright5pxspansamplespandivtargetdiv idhierarchydiv classdd idtree nodesol classddlist idancestorli classdditem div classddhandleimg alttesting srctest2png a nametree stylemargin5pxfirst pageadivlili classdditem div classddhandleimg alttesting srctest2png sa nametree stylemargin5pxsecond pageadivlili classdditem div classddhandleimg alttesting srctest2png a nametree stylemargin5pxthird pageadivlili classdditem div classddhandleimg alttesting srctest2png sa nametree stylemargin5pxfourth pageadivlioldivdivam using this code for drag and dropactions builder new actionsdriveraction draganddrop builderclickandholdsrcmovetoelementtrgtreleasetrgtbuilddraganddropperformi want to drag the src element to target elementinsert as a li tag inside ol of div tag how can i insert as a first or last or intermediate li tag inside ol of divtarget elementi want to create a li taglike as li in target element and then drag the src element to the newly created li tag inside olpresent in target elementhow do i create a li tag in selenium,['java'] +823752,external stylesheets for shadow dom in web components i am learning web components with a shadow root and cannot seem to find on google if loading external stylesheets is possible with outofthebox code i am not using polymer or any other web component library yet code belowscript srclibsjquery211minjsscriptscript var hollaproto objectcreatehtmlelementprototype hollaprotocreatedcallback function var shadow thiscreateshadowroot var content documentqueryselectorlinkrelimportimportqueryselectordiv buttondatacommandholla contentonclick function alertholla shadowappendchildcontent var hollawidget documentregisterelementhollaback prototype hollaproto scriptdiv classhollaback button datacommandhollahollabuttondivif i put my link tag up top above the first script tag i style the whole web age but not the web componentif i put it under divhollaback it does not style anythinghow do you use external stylesheets with web components,['javascript'] +823757,exception in thread main javalangnosuchmethoderror comfasterxmljacksoncorejsonfactoryrequirespropertyorderingz i need to convert json to pojo i decided to use jackson and have added jacksoncore220jar jacksondatabind244jar and jacksonannotations212jar to my projects classpathi created following main classimport javaioioexceptionimport javanetmalformedurlexceptionimport javaneturlimport javautillistimport comfasterxmljacksoncorejsongenerationexceptionimport comfasterxmljacksoncorejsonprocessingexceptionimport comfasterxmljacksondatabindjsonmappingexceptionimport comfasterxmljacksondatabindjsonnodeimport comfasterxmljacksondatabindobjectmapperimport comfasterxmljacksoncorejsongenerationexceptionimport comfasterxmljacksoncoretypetypereferenceimport comfasterxmljacksondatabindjsonmappingexceptionimport comfasterxmljacksondatabindobjectmapperimport comfasterxmljacksondatabinddeserializationfeaturepublic class json private static string src public static void mainstring args awardlist awardlist null objectmapper mapper new objectmapper try awardlist awardlist mapperreadvaluenew urlsrc awardlistclass catch jsongenerationexception e eprintstacktrace catch jsonmappingexception e eprintstacktrace catch ioexception e eprintstacktrace systemoutprintlnawardlist and following awardlist classpublic class awardlist private flights flights private string connections private savereconomy savereconomy private standarteconomy standarteconomy private saverbusiness saverbusiness private standartfirst standartfirst private saverfirst saverfirst public flights getflights return flights public void setflightsflights flights thisflights flights public savereconomy getsavereconomy return savereconomy public void setsavereconomysavereconomy savereconomy thissavereconomy savereconomy public standarteconomy getstandarteconomy return standarteconomy public void setstandarteconomystandarteconomy standarteconomy thisstandarteconomy standarteconomy public saverbusiness getsaverbusiness return saverbusiness public void setsaverbusinesaverbusiness saverbusiness thissaverbusiness saverbusiness public standartfirst getstandartfirst return standartfirst public void setstandartfirststandartfirst standartfirst thisstandartfirst standartfirst public saverfirst getsaverfirst return saverfirst public void setsaverfirstsaverfirst saverfirst thissaverfirst saverfirst public string getconnections return connections public void setconnectionsstring connections thisconnections connections i want to convert json to pojo and save it in the database i keep getting following errorexception in thread main javalangnosuchmethoderror comfasterxmljacksoncorejsonfactoryrequirespropertyorderingz at comfasterxmljacksondatabindobjectmapperinitobjectmapperjava457 at comfasterxmljacksondatabindobjectmapperinitobjectmapperjava379 at jsonmainjsonjava72,['java'] +823790,is there a really working example which showing the benefits of ilpinstructionlevel parallelism on x86 64 as known cpu is pipeline and it works most efficiently if the sequence of commands independent from each other this known as ilp instructionlevel parallelism parallelismbut is there a really working example which showing the benefits of ilp at least syntetic example for cpu x86 64 but for the same amount of cmpjne in both casesi will write the following example add up all the elements of the array but it does not show any advantages of ilp sequential fori 0 i arr size i 8 result arri0 arri1 arri2 arri3 arri4 arri5 arri6 arri7 ilp register unsigned int v0 v1 v2 v3 v0 v1 v2 v3 0 fori 0 i arr size i 8 v0 arri0 arri1 v1 arri2 arri3 v2 arri4 arri5 v3 arri6 arri7 result v0v1v2v3resultseq 010 sec res 10 ipl 0110 sec faster 0909091 x res 10 seq 010 sec res 10 ipl 010 sec faster 10 x res 10 seq 010 sec res 10 ipl 0110 sec faster 0909091 x res 10 seq 010 sec res 10 ipl 010 sec faster 10 x res 10 seq 0110 sec res 10 ipl 0110 sec faster 10 x res 10 seq 010 sec res 10 ipl 0110 sec faster 0909091 x res 10 seq 010 sec res 10 ipl 0110 sec faster 0909091 x res 10 seq 0110 sec res 10 ipl 010 sec faster 110 x res 10 seq 0110 sec res 10 ipl 010 sec faster 110 x res 10 seq 0110 sec res 10 ipl 0120 sec faster 09167 x res 10 faster avg 0975303ilp even a little slower than sequentialccode include timehinclude stdiohinclude stdlibhint main create and init array const size t arr size 10 unsigned int arr unsigned int mallocarr size sizeofunsigned int size t i k fori 0 i arr size i arri 10 unsigned int result 0 clock t start end const int c iterations 10 iterations of experiment float faster avg 0 fork 0 k c iterations k result 0 sequential start clock fori 0 i arr size i 8 result arri0 arri1 arri2 arri3 arri4 arri5 arri6 arri7 end clock const float c time seq floatend startclocks per sec printfseq f sec res u c time seq result result 0 iploptimization start clock register unsigned int v0 v1 v2 v3 v0 v1 v2 v3 0 fori 0 i arr size i 8 v0 arri0 arri1 v1 arri2 arri3 v2 arri4 arri5 v3 arri6 arri7 result v0v1v2v3 end clock const float c time ipl floatend startclocks per sec const float c faster c time seqc time ipl printfipl f sec faster f x res u n c time ipl c faster result faster avg c faster faster avg faster avgc iterations printffaster avg f n faster avg return 0updatesequential thisassembler ms visual studio 2013 for i 0 i arr size i 8 result arri 0 arri 1 arri 2 arri 3 arri 4 arri 5 arri 6 arri 7 013f131080 mov ecxdword ptr rdx18h 013f131083 lea rdxrdx20h 013f131087 add ecxdword ptr rdx34h 013f13108a add ecxdword ptr rdx30h 013f13108d add ecxdword ptr rdx2ch 013f131090 add ecxdword ptr rdx28h 013f131093 add ecxdword ptr rdx24h 013f131096 add ecxdword ptr rdx1ch 013f131099 add ecxdword ptr rdx20h 013f13109c add ediecx 013f13109e dec r8 013f1310a1 jne main80h 013f131080h ilp thisassembler ms visual studio 2013 for i 0 i arr size i 8 v0 arri 0 arri 1013f1310f0 mov ecxdword ptr rdx0ch v1 arri 2 arri 3 v2 arri 4 arri 5013f1310f3 mov eaxdword ptr rdx8 013f1310f6 lea rdxrdx20h 013f1310fa add ecxdword ptr rdx28h 013f1310fd add eaxdword ptr rdx1ch 013f131100 add ebpecx 013f131102 mov ecxdword ptr rdx24h 013f131105 add ebxeax 013f131107 add ecxdword ptr rdx20h v3 arri 6 arri 7013f13110a mov eaxdword ptr rdx10h v3 arri 6 arri 7013f13110d add eaxdword ptr rdx14h 013f1310 add esiecx 013f1312 add edieax 013f1314 dec r8 013f1317 jne main0f0h 013f1310f0h result v0 v1 v2 v3compiler command linegs gl w3 gy zcwchar t zi gm o2 ob2 sdl fdx64releasevc120pdb fpprecise d mbcs errorreportprompt wx zcforscope gd oi mt fax64release ehsc nologo fox64release ot fpx64releaseipl reduce testpch additional notes to the answerthe simple example which showing the benefits of ilp between unroloop and unroloopilp for array of 50 double elements faster avg 1152778falsesequential which can be optimized by cpupipeline thisassembler ms visual studio 2013 for add 8 elements in each iteration uses temporary register xmm0 which then adds to the result xmm6 ie can be used register renamingresult arri 0 arri 1 arri 2 arri 3 arri 4 arri 5 arri 6 arri 7013fba1090 movsd xmm0mmword ptr rcx10h 013fba1095 add rcx40h 013fba1099 addsd xmm0mmword ptr rcx48h 013fba109e addsd xmm0mmword ptr rcx40h 013fba10a3 addsd xmm0mmword ptr rcx38h 013fba10a8 addsd xmm0mmword ptr rcx30h 013fba10ad addsd xmm0mmword ptr rcx28h 013fba10b2 addsd xmm0mmword ptr rcx20h 013fba10b7 addsd xmm0mmword ptr rcx18h 013fba10bc addsd xmm6xmm0 013fba10c0 dec rdx 013fba10c3 jne main90h 013fba1090h truesequential which can not be optimized by cpupipeline thisassembler ms visual studio 2013 for add 8 elements in each iteration uses the result register xmm6 ie can not be used register renaming result arri 013ffc1090 addsd xmm6mmword ptr rcx10h 013ffc1095 add rcx40h result arri 1013ffc1099 addsd xmm6mmword ptr rcx48h result arri 2013ffc109e addsd xmm6mmword ptr rcx40h result arri 3013ffc10a3 addsd xmm6mmword ptr rcx38h result arri 4013ffc10a8 addsd xmm6mmword ptr rcx30h result arri 5013ffc10ad addsd xmm6mmword ptr rcx28h result arri 6013ffc10b2 addsd xmm6mmword ptr rcx20h result arri 7013ffc10b7 addsd xmm6mmword ptr rcx18h 013ffc10bc dec rdx 013ffc10bf jne main90h 013ffc1090h,['c++'] +823909,how to use jquery how to change the ariaexpandedfalse part of a dom element bootstrap i have the following elementbutton typebutton classnavbartoggle collapsed datatogglecollapse datatargetnavbar ariaexpandedfalse ariacontrolsnavbari want to use jquery or just javascript would work to alter the ariaexpanded field to toggle it between true and false how would i go about thisthanks,"['javascript', 'jquery', 'html', 'css']" +823949,initializer list vs vector in c11 one can use initializer lists to initialize parameters in functions what is the purpose of it cannot the same be done with const vectors what is the difference of the two programs belowusing initializer listinclude iostreamusing namespace stdint sumlinitializer listint l int sum 0 for const auto i l sum i return sumint main cout suml1 2 3 n return 0using const vectorinclude iostreaminclude vectorusing namespace stdint sumvconst vectorint l int sum 0 for const auto i l sum i return sumint main cout sumv1 2 3 n return 0,['c++'] +824038,android virtual device armeabiv7a vs x86 64 i want to make my own android application i am using ubuntu 64bit and intellij in virtual device configuration it asks me to choose a system image all of the options have a download beside which means i have not downloaded any system imagethere are 3 options available for lollipopapi level 21 which are armeabiv7a x86 64 and x86i am using ubuntu 64 bit so i should not use x86 rightcan anyone explain what is armeabiv7a for what are the differences between armeabiv7a and x84 64 what version should i choose and which one runs faster,['android'] +824123,alamofire follow http redirects or not i am trying to configure alamofire to follow redirects or not on a perrequest basisalamofire has a private internal class sessiondelegate which serves as the nsurlsessiontaskdelegate for the current url session sessiondelegate does implement the relevant delegate method urlsessionsession task willperformhttpredirection response request completionhandler which is exactly what i wanteven better the delegates implementation consults a custom variable closure named taskwillperformhttpredirection to determine how to handle the redirect again exactly what i wantand as far as i can tell that closure is always nil by default it is not assigned to internally by alamofire which suggests that it is intended to let the user assign a closure to itthe problem i cannot access this private sessiondelegate class to assign a closure to its taskwillperformhttpredirection variable it is a private class and it is not visible to my swift files what is the proper means of configuring an alamofire request to not follow redirects,['ios'] +824147,first random number after setseed in java always similar to give some context i have been writing a basic perlin noise implementation in java and when it came to implementing seeding i had encountered a bug that i could not explainin order to generate the same random weight vectors each time for the same seed no matter which set of coordinates noise level is queried and in what order i generated a new seed newseed based on a combination of the original seed and the coordinates of the weight vector and used this as the seed for the randomization of the weight vector by runningrndsetseednewseedweight new nvector2weightsetelement0 rndnextdouble 2 1weightsetelement1 rndnextdouble 2 1weightnormalizewhere nvector is a selfmade class for vector mathematicshowever when run the program generated very bad noiseafter some digging i found that the first element of each vector was very similar and so the first nextdouble call after each setseed call resulting in the first element of every vector in the vector grid being similarthis can be proved by runninglong seed longvalueofargs0int loops integervalueofargs1double avgfirst 00 avgsecond 00 avgthird 00double lastfirst 00 lastsecond 00 lastthird 00forint i 0 iloops i ransetseedseed i double first rannextdouble double second rannextdouble double third rannextdouble avgfirst mathabsfirst lastfirst avgsecond mathabssecond lastsecond avgthird mathabsthird lastthird lastfirst first lastsecond second lastthird thirdsystemoutprintlnaverage first difference avgfirstloopssystemoutprintlnaverage second difference avgsecondloopssystemoutprintlnaverage third difference avgsecondloopswhich finds the average difference between the first second and third random numbers generated after a setseed method has been called over a range of seeds as specified by the programs arguments which for me returned these resultscjava test 462454356345 10average first difference 744638117976783e4average second difference 034131692827329957average third difference 034131692827329957cjava test 46245445 10average first difference 0171960123287126average second difference 03416750057190849average third difference 03416750057190849cjava test 1 10average first difference 021601598225344998average second difference 03409914232342002average third difference 03409914232342002here you can see that the first average difference is significantly smaller than the rest and seemingly decreasing with higher seedsas such by adding a simple dummy call to nextdouble before setting the weight vector i was able to fix my perlin noise implementationrndsetseednewseedrndnextdoubleweightsetelement0 rndnextdouble 2 1weightsetelement1 rndnextdouble 2 1resulting ini would like to know why this bad variation in the first call to nextdouble i have not checked other types of randomness occurs andor to alert people to this issueof course it could just be an implementation error on my behalf which i would be greatful if it were pointed out to me,['java'] +824352,how do i safely and sensibly determine whether a pointer points somewhere into a specified buffer i am looking to implement a function that determines whether a given pointer points into a given buffer the specificationtemplate typename tbool points into buffer t p t buf stdsize t lenif there is some n 0 and and len for which p buf n returns trueotherwise if there is some n 0 and and len sizeoft for which reinterpret castchar p reinterpret castchar buf n the behaviour is undefinedotherwise returns falsethe obvious implementation would look something liketemplate typename tbool points into buffer t p t buf stdsize t len return p buf p buf lenbut that has undefined behaviour in standard c relational comparisons of pointers are only defined for pointers into the same arrayan alternative would be to use the standard librarys comparer objectstemplate typename tbool points into buffer t p t buf stdsize t len return stdgreater equalt p buf stdlesst p buf lenwhich is guaranteed to return true when i want it to return true and avoids undefined behaviour but allows for false positives given int a int b it allows a result of true for points into buffera b 1it can be implemented as a looptemplate typename tbool points into buffer t p t buf stdsize t len for stdsize t i 0 i len i if p buf i return true return falsehowever compilers have trouble optimising away that loopis there a valid way of writing this where with current compilers and optimisations enabled the result is determined in constant time,['c++'] +824398,could not select ok in mysqlaptconfig ubuntu 1404 purging not working i am using ubuntu 1404 mintsudo dpkg configure a takes me to the package configuration of the mysqlaptconfig however when i select the server version that i wish to receive mysql56 the terminal does not respond when i click enter in i tried purging with sudo aptget purge mysqlaptconfig as addressed in a previous question could not select ok in mysqlaptconfig ubuntu 1404 however this returns me to e dpkg was interrupted you must manually run sudo dpkg configure a to correct the problemnot sure how to move on from thisthanks,['mysql'] +824414,gem installation error you have to install development tools first i tried installing the gem sinatrawebsocket but when i ran gem install sinatrawebsocket i got this errorerror failed to build gem native extension along with cruby193binrubyexe extconfrbchecking for main in lc extconfrb failed could not create makefile due to some reason probably lack ofnecessary libraries andor headers check the mkmflog file for moredetails you may need configuration optionsprovided configuration options withoptdir withoutoptdir withoptinclude withoutoptincludeoptdirinclude withoptlib withoutoptliboptdirlib withmakeprog withoutmakeprog srcdir curdir rubycruby193binruby withthin parserdir withoutthin parserdir withthin parserinclude withoutthin parserincludethin parserdirinclude withthin parserlib withoutthin parserlibthin parserdirlib withclib withoutclibcruby193libruby191mkmfrb381in try do the compiler failed to generate an executable file runtimeerroryou have to install development tools first from cruby193libruby191mkmfrb461in try link0 from cruby193libruby191mkmfrb476in try link from cruby193libruby191mkmfrb619in try func from cruby193libruby191mkmfrb845in block in have library from cruby193libruby191mkmfrb790in block in checking for from cruby193libruby191mkmfrb284in block 2 levels in postpone from cruby193libruby191mkmfrb254in open from cruby193libruby191mkmfrb284in block in postpone from cruby193libruby191mkmfrb254in open from cruby193libruby191mkmfrb280in postpone from cruby193libruby191mkmfrb789in checking for from cruby193libruby191mkmfrb840in have library from extconfrb4in mainheres what the mkmf file in cruby193librubygems191gemsthin163extthin parser looks likegcc o conftest icruby193includeruby191i386mingw32 icruby193includeruby191rubybackward icruby193includeruby191 i dfd setsize2048 dfd setsize2048 o3 fnoomitframepointer g wall wextra wnounusedparameter wnoparentheses wnolonglong wnomissingfieldinitializers wpointerarith wwritestrings wdeclarationafterstatement wimplicitfunctiondeclaration conftestc l lcruby193lib l marchi486 lmsvcrtruby191 lshell32 lws2 32 limagehlp lshlwapi checked program was begin 1 include rubyh2 3 include winsock2h4 include windowsh5 int mainint argc char argv6 7 return 08 end i am using windows 7 why am i getting the error there is a line stating could not create makefile but is that relevant,['ruby'] +824418,yii2dropdown list for multiple values concat in one line for my dropdown list i am using this code formfieldmedicinerequest id medicine namedropdownlistarrayhelpermapappmodelsmedicinefindasarrayall id medicine namemedicine id prompt please select i am getting the dropdown list as in the picture but i want it to be concatenated by hyphen in one line how can i do this,['php'] +824423,ionic get users phone number i am very new to ionic and cordova i want to get users phone number somehow is it possible i am trying to create number registration for my app when user opens an app the very first time he is asked to enter a code that he gets via text message it is similar to viber the first view contains a button send me a code and the next view has a form enter code and a button log me in,['android'] +824566,where is the load barrier for the volatile statement i wrote this simple java programpackage comsalilthreadspublic class incrementclass static volatile int j 0 static int i 0 public static void mainstring args forint a0a10a i j this generate the following thisassembled code for i and j remaining thisassembled code removed 0x02961a6c 49ba98e8d0d5070 mov r107d5d0e898h oopa javalangclass comsalilthreadsincrementclass 0x02961a76 41ff4274 inc dword ptr r1074h if icmpge comsalilthreadsincrementclassmain5 line 10 0x02961a7a 458b5a70 mov r11ddword ptr r1070h 0x02961a7e 41ffc3 inc r11d 0x02961a81 45895a70 mov dword ptr r1070hr11d 0x02961a85 f083042400 lock add dword ptr rsp0h putstatic j comsalilthreadsincrementclassmain27 line 14this is what i understand about the following assembly codemov r107d5d0e898h moves the pointer to the incrementclassclass to register r10inc dword ptr r1074h increments the 4 byte value at the address at r10 74hie imov r11ddword ptr r1070h moves the 4 value value at the address r10 70h to register r11d ie move value of j to r11dinc r11d increment r11dmov dword ptr r1070hr11d write value of r11d to r10 70h so it is visible to other threadslock add dword ptr rsp0h lock the memory address represented by the stack pointer rsp and add 0 to itjmm states that before each volatile read there must be a load memory barrier and after every volatile write there must be a store barrier my question iswhy is not there a load barrier before the read of j into r11dhow does the lock and add to rsp ensure the value of j in r11d is propogated back to main memory all i read from the intel specs is that lock provides the cpu with an exclusive lock on the specified memory address for the duration of the operation,['java'] +824701,wave or shape with border on css3 there is a the task to realize the figure on css3 i tried to implement with css3 shapes but i has not reached the desired result margin 0 padding 0body background 007fc1containerpanel borderbottom 4px solid b4cad8container backgroundcolor fcontainer text padding 05empanel position relative float right width 200px height 40px margintop 4px backgroundcolor f lineheight 42px textalign centerpanelbefore content position absolute left 44px width 0 height 0 bordertop 44px solid b4cad8 borderleft 44px solid transparentdiv classcontainer div classtext plorem ipsum dolor sit amet consectetur adipisicing elit voluptates nam fuga eligendi ipsum sed ducimus quia adipisci unde atque enim quasi quidem perspiciatis totam soluta tempora hic voluptatem optio perferenthisp divdivdiv classpanelthis is a paneldivit is impossible to implement border and set background color i need to achieve this result,['css'] +824939,get line number in file following tsql error message consider the following sql scripton error exitprint line 3goprint line 6goselect from nonexistingtablegoprint line 12gowhen you run with sqlcmd sqlcmd i myscriptsqlline 3line 6msg 208 level 16 state 1 server myserver line 2invalid object name nonexistingtablewhen you run in sql server management studio with sqlcmd mode enabled you getline 3line 6msg 208 level 16 state 1 server myserver line 2invalid object name nonexistingtable an error was encountered during execution of batch exitingbut when you double click on the error line the query editor will jump to the problematic linereported line 2 means a line number relative to the batch batches are separated by go statement we want to get a real line 9 answeri have also tried powershells invokesqlcmd but it is even worse since it does not detect such errors at all error detection from powershell invokesqlcmd not always workingis there a simple way to wrap our sql script with some helpers to get the desired real error linesupd i have changed the error script to make sure it would fail for sure,['sql'] +824953,python on windows 10 i have python 272 on windows 10 when i load win32api and wmi it fails to load the python install on the windows 10 is same as on another windows 7 pc i do not have this issue on win 7 below are the errors i get when i try to import the above modules on windows 10 import win32apitraceback most recent call last file stdin line 1 in moduleimporterror dll load failed the specified module could not be found import wmitraceback most recent call last file stdin line 1 in module file cpython27libsitepackageswmipy line 88 in module from win32comclient import getobject thispatch file cpython27libsitepackageswin32com init py line 5 in module import win32api sys osimporterror dll load failed the specified module could not be foundwhat could be the cause for my issue is there a minimum python version that is supposed to be used with windows 10,['python'] +824986,named async lambda function i want to create within a function a named lambda function so that i can call it repeatedly afterwards in the same functioni used to do this synchronouslywithout tasks withfuncstring bool pingable url return pingtesturlbut in this case i want to call the pingable function as a task so i would need a task return typethis is where i am stuckfor all below i am getting compile errors funcstring taskbool pingable input return pingtesturl taskbool pingable new taskboolinput return pingtesturl i can declare the function normally though but then i cannot call it as a task funcstring bool pingable input return pingtesturl var tasks new listtask tasksaddasync new taskpinggoogledeall the lines i have marked with a produce copmile errors seems to have a hint at a solution but the sample there does not allow for not provided input parameters sample taken from there and simplifiedtaskint task new taskintobj return obj 1 300how to create and call named task lambdas in c and i would like to declare them on a function rather than class leveli want the named lambda in order to call it multiple times several urls in this caseeditupdate since you asked for codefuncstring taskbool ping url taskrun try ping pinger new ping pingreply reply pingersendurl return replystatus ipstatussuccess catch exception return false var tasks new listtasktasksaddpingandreasreiffdetasksaddpinggoogledetaskwaitalltaskstoarraybool online tasksselecttask taskbooltaskresultcontainstruethis already makes use of the solution proposed here,"['c#', '.net']" +825010,how to use rippledrawable programmatically in code not xml with android 50 lollipop i have the following code for my ripplexml version10 encodingutf8ripple xmlnsandroid androidcolorandroidcolorcontrolhighlight item androidididrip shape androidshapeoval solid androidcolorandroidcoloraccent shape itemripplenow i want to give the user the possibility to choose own colors so i need to create the ripple programmaticallyi found this and i think this is the right way to do it but i do not know how to handle with thisthe ripple will be used hereimagebutton androidididadd button androidlayout widthdimendiameter androidlayout heightdimendiameter androidlayout gravityendbottom androidlayout marginbottomdimenadd button margin androidlayout marginenddimenadd button margin androidlayout alignparentbottomtrue androidlayout alignparentendtrue androidsrcdrawableic action add person androidtintandroidcolorwhite androidbackgrounddrawableoval ripple androidelevationdimenelevation low androidstatelistanimatoranimbutton elevation androidcontentdescriptionneuer spieler i need to set the background to a rippledrawable like thisaddbuttonsetbackgroundripple,['android'] +825177,32 or 64 bit for the jvm while reading this book over here i can see the following section which says32 or 64 bit if you have a 32bit operating system then you must use a 32bit version of the jvm if you have a 64bit operating system then you can choose to use either the 32 or 64bit version of java donat assume that just because you have a 64bit operating system you must also use a 64bit version of javaif the size of your heap will be less than about 3 gb the 32bit version of java will be faster and have a smaller footprint this is because the memory references within the jvm will be only 32bits and manipulating those memory references is less expensive than manipulating 64bit references even if you have a 64bit cpu the 32bit references also use less memorychapter 8 thiscusses compressed oops which is a way that the jvm can use 32bit addresses even within the 64bit jvm however even with that optimization the 64bit jvm will have a larger footprint because the native code it uses will still have 64bit addressesthe downside to the 32bit jvm is that the total process size must be less than 4gb 3gb on some versions of windows and 35gb on some old versions of linux that includes the heap permgen and the native code and native memory the jvm uses programs that make extensive use of long or double variables will be slower on a 32bit jvm because they cannot use the cpuas 64bit registers though that is a very exceptional caseprograms that fit within a 32bit address space will run anywhere between 5 and 20 faster in a 32bit jvm than a similarlyconfigured 64bit jvm the stock batching program thiscussed earlier in this chapter for example is 20 faster when run on a 32bit jvm on my desktopthe lines says 32bit will be faster for lesser heap size less than 3gb if this is true i want to know the reason behind it what makes 32bit jvm is faster,['java'] +825381,rails 42 server port forwarding on vagrant does not work i have a vagrant vm with rails installed with a sample app the vm is configured to forward the port 30 of rails webrick server to my host 30 port configvmnetwork forwarded port guest 30 host 30everything is configured as seen in a lot of examplesbut when i try to access httplocalhost30 nothing happens i have also tried to forward to other random ports like 8081 25600 without success doing a curl request also does not get anything just a connection reset by the peer message and a curl request inside vm works perfectly as expectedboth my pc and my vm runs ubuntu 1204 i am using ruby 220 and rails 420an important point is that apache works normally i forwarded the port 80 to port 8080 and everything works it seems that the problem is just with the rails server even if when i use other ports rails server p 40 for example,['ruby-on-rails'] +825485,is there a way to call python with xlwings without reopening the excel file i am calling python from excel using xlwings i find that when running my macro excel closes and reopens in order to run the code it functions correctly but it slows things down in addition if the excel file is unsaved a dialog will mention that the file is already open and that i will lose unsaved changesis there a way to call python without reopening the excel filethis is my python code in loaddfpyfrom xlwings import workbook range sheetdef my macro wb workbookcaller rangea1value rangea1value 1and the vba code in my excel filesub loaddfsub runpython import loaddf loaddfmy macroend subthanks for the help,['python'] +825500,ipython console in spyder stuck on connecting to kernel i am new to python and coming from matlab and i have installed the latest version of pythonxy 2790 on my win 8 64 bit pc the problem that i have is that each time i start spyder the default ipython console gets stuck on connecting to kernel i can see that a new kernel is launched each time because a new json file appears in the directory ipythonprofile defaultsecurity i can access this kernel by opening a new ipython console by clicking on connect to an existing kernel and then browsing to find it then it works fine except that the variables i create do not appear in the variable explorer i can also quit the kernel from this new ipython console but this does not solve my problem because when i launch a new ipython console by clicking on open an ipython console or restarting spyder it still hangs on connecting to kernel and creates a new json filethe closest issue that i could find on a forum is this one the only difference being that i do not have the import sitecustomize error in the internal console i have tried uninstalling pythonxy and python but to no avail any hint would be really appreciated,['python'] +825572,python urllib2 ssl error python 279 is now much more strict about ssl certificate verification awesomei am not surprised that programs that were working before are now getting certificate verify failed errors but i cannot seem to get them working without thisabling certificate verification entirelyone program was using urllib2 to connect to amazon s3 over httpsi download the root ca certificate into a file called verisignpem and try thisimport urllib2 sslcontext sslcreate default contextcontextload verify locationscafile verisignpemprint contextget ca certsurllib2urlopen contextcontextand i still get certificate verify failed errors even though the root ca is printed out correctly in line 4openssl can connect to this server fine in fact here is the command i used to get the ca certopenssl s client showcerts connect buckets3amazonawscom443 devnulli took the last cert in the chain and put it in a pem file which openssl reads fine it is a verisign certificate withserial number 35973187f3873a07327ece580c9b7edasubject key identifier 7fd365a7c2ddecbbf03009f34339fa02af3133sha1 fingerprint f4a80a0cd1e6cf190b8cbc6fbc991711d482c9d0any ideas how to get this working with validation enabled,['python'] +825579,aspnet mvc web api2 angularjs authorization and authentication i am developing one large application which will consist of both aspnet mvc and angularjsweb api2 on backend previously i have used mvc forms authorization in my applications there are lots of examples how to use token based authorization with angularjsweb api but cannot find complete solution that will fit both cases please provide me some information where i can read on this topic maybe stepbystep examples tutorials or blogs where mixed authorization for both is described,['asp.net'] +825585,how to make this point to the outer class where the inner class has the same method name let us say i have the following codeabstract class mystream public abstract iterableinteger getiterable public mystream appendfinal int i return new mystream override public iterableinteger getiterable return consouter clasgetiterable i public static iterableinteger consiterableinteger iter int i implementation how can i reference getiterable of the outer class from the inner class with the same namemystreamthis should point to the inner class here right how to show an outer class with the same name,['java'] +825589,performance of inline python function definitions a general question for someone that knows function definition internals better than i doin general is there a performance trade off to doing something like thisdef my function def other function pass do some stuff other functionversusdef other function passdef my function do some stuff other functioni have seen developers inline functions before to keep a small single use function close to the code that actually uses it but i always wondered if there were a memory or compute performance penalty for doing something like thisthoughts,['python'] +825695,minimal example of push in vaadin 7 app push i want to see the most minimal example of using the new push technology in vaadin 7 such as the new push annotation i am having problems getting serverpush to work in my app i would like to try a simple example app before trying to fix my own app,['java'] +825854,ruby on rails provide vs content for i came across the view helper function provide today by looking into its manual i am still confused on how it is different from content forprovidename content nil blockthe same as content for but when used with streaming flushes straight back to the layout in other words if you want to concatenate several times to the same buffer when rendering a given template you should use content for if not use provide to tell the layout to stop looking for more contentsquestion 1 this is quite abstract to me could anyone flesh it out by giving a demonstrative examplequestion 2 working with asset pipeline which performs better and whythanks,"['ruby-on-rails', 'ruby']" +825860,do int ref parameter get boxed say i have the following codevoid main int a 5 f1ref apublic void f1ref int a ifa 7 return a f1ref a consolewritelineaoutput is 8 8 8 ie when the stack unwinds the value of the ref parameter is maintained does it mean that adding ref keyword to int parameter causes it to get boxed how does the actual stack look like during the recursive call,"['c#', '.net']" +825896,what happens if thisk space runs out while using nsurlsessiondownloadtask in background in a ios 81 app i am using nsurlsessiondownloadtask to download an archive in the background which can sometimes get quite large everything works fine but what will happen if the phone runs out of thisk space will the download fail and indicate that it was a problem of remaining thisk space is there any good way to check in advance,['ios'] +826002,ios incall status bar update viewcontroller presented modaly on screen i am afford to ask this question because after large research almost 2days of googling stack overflowing etcmy issue is this i am presenting viewcontroller from my main viewcontroller like thisuinavigationcontroller navigation uinavigationcontroller alloc initwithrootviewcontrollervcontrollernavigationtransitioningdelegate selfnavigationmodalpresentationstyle uimodalpresentationcustomself presentviewcontrollernavigation animatedyes completionnilwhenever an iphone user is in call or is using his or her phone as a hotspot status bar is enlarged pushing my modaly presented vc to the bottom but the origin is set to 00the problem is when user finish call during he is in my application status bar resize to normal size but modal vc didnt move up i knew about this when it happen in code thanks to this notificationnsnotificationcenter defaultcenter addobserverself selectorselectorstatubarchange nameuiapplicationdidchangestatusbarframenotification objectnilthe worst thing is that the frames are corect and origin are still 00is there a way to refres modal presented vc with out thissmiss and presenting it again,['ios'] +826174,jgit pushing a branch and add upstream u option in jgit i search a way to push a branch and add the upstream reference tracking it is the option u or setupstream into the push commandi do not see a method in the class pushcommand which permits to do thisplease could you tell me how i can do this pushcommand pushcommand gitpush setremoteremotealias setrefspecsspec,['java'] +826298,variable named the same as enumerator what is the defined behavior for something like the followinginclude stdiohtypedef enum enum val 1 1 enum val 2 2 test enumint main test enum testvar1 enum val 1 test enum enum val 1 enum val 1 test enum testvar2 enum val 1 printfenum val 1 unenum val 1 printftestvar1 untestvar1 printftestvar2 untestvar2 return 0from my testing with both gcc and msvc compilers the behavior of this is that testvar1 will be set equal to the enumeration value enum val 1 or 1 however the next statement will try to set the variable enum val 1 equal to its own value which is of course current uninitialized and thus garbage instead of setting the variable enum val 1 equal to the enumeration value enum val 1 then of course testvar2 will also get the same garbage value as the variable enum val 1what is the defined behavior of this according to the c standards or is this undefined behavior whether or not it is defined i am guessing this type of example is bad practice at very least due to the ambiguitythanks,['c'] +826301,pass constexpr intializer list as argument in c14 why does not this workconstexpr initializer listint ilist 1234constexpr int my min minilistwhile this doesconstexpr int my min min1234i am basing my code on the constexpr stdmin function as shown here and i am using clang350 to compiler g491 does not seem to be aware of a constexpr stdmini cannot make sense of the error i am gettingclang35 stdliblibc stdc14 testcpp o testtestcpp15835 error constexpr variable ilist must be initialized by a constant expression constexpr initializer listint ilist 1234 testcpp15835 note pointer to subobject of temporary is not a constant expressiontestcpp15843 note temporary created here constexpr initializer listint ilist 1234 testcpp15917 error constexpr variable my min must be initialized by a constant expression constexpr int my min minilist testcpp15930 note initializer of ilist is not a constant expression constexpr int my min minilist testcpp15930 note in call to initializer listilisttestcpp15835 note declared here constexpr initializer listint ilist 1234,['c++'] +826337,opencv 30 videoio error i tried to compile opencv 30 alpha library for qt creator 54 with cmake 310 but i have error 44 building cxx object modulesvideoiocmakefilesopencv videoiodirsrccap dshowcppobjdopencvsourcesmodulesvideoiosrccap dshowcpp12211 error base class struct iunknown has accessible nonvirtual destructor werrornonvirtualdtor interface ienumpidmap public iunknown dopencvsourcesmodulesvideoiosrccap dshowcpp141 error base class struct iunknown has accessible nonvirtual destructor werrornonvirtualdtor interface impeg2pidmap public iunknown dopencvsourcesmodulesvideoiosrccap dshowcpp231 error base class struct iunknown has accessible nonvirtual destructor werrornonvirtualdtor interface isamplegrabbercb public iunknown dopencvsourcesmodulesvideoiosrccap dshowcpp24511 error base class struct iunknown has accessible nonvirtual destructor werrornonvirtualdtor interface isamplegrabber public iunknown cc1plusexe some warnings being treated as errorsmodulesvideoiocmakefilesopencv videoiodirbuildmake150 recipe for targetmodulesvideoiocmakefilesopencv videoiodirsrccap dshowcppobj failedmingw32make2 modulesvideoiocmakefilesopencv videoiodirsrccap dshowcppobj error 1cmakefilesmakefile22719 recipe for target modulesvideoiocmakefilesopencv videoiodirall failedmingw32make1 modulesvideoiocmakefilesopencv videoiodirall error 2makefile136 recipe for target all failedmingw32make all error 2i selectedcmake cmake build type debugwith with eigen 0with with opengl 0with with ipp 0the rest of settings is default my os is windows 7 64 bit opencv library source what is wrong any ideas,['c++'] +826355,child margin does not affect parent height this might be obvious for some but i found it hard to find the solution for thisnote for answerers please jump to the real question thanks but i found it it is below description of the problemthe problemin simple example like this one the child margin does not affect parent heighthtmldiv classparent div classchildsome textdivdivcssparent background black child background lightblue margin 20pxfiddle the solutionis quite simple by default child margins do not affect parent height respectively parent dimensions in general it is easily fixed by adding something that margin could push to in parent element eg add a padding or border to parentadjusted cssparent background black padding 1px padding added child background lightblue margin 20pxfiddle the real questionhowever i actually want to know why does this work this way not just how it is fixedso please could someone please write an answer explaining this behaviour and add some doc referencesmany thanks,['css'] +826386,remove rows that sum zero for a given key i have a query that will result in a customer bill being created on our ssrs 2008 r2 server the sql server instance is also 2008 r2 the query is large and i do not want to post the entire thing for security reasons etc what i need to do with the example data below is to remove the two rows with 7319 and 7319 from the result set so if two rows have the same absolute value in the linebalance column and their sum is 0 and if they have the same value in the ref1 column the should be removed from the result set the line with ref1 14598 and a line balance of 28147 should still be returned in the result set and the other two rows below with ref1 14598 should not be returnedthe point of this is to hide accounting errors and their correction from the customer by hide i mean not show it on the bill they get in the mail what happened here is the customer was mistakenly billed 7319 when they should have been billed 28147 so our ar dept returned 7319 to their account and charged them the correct amount of 28147 as you can see they all have the same ref1 value,['sql'] +826392,laravel blade comments blade rendering causing page to crash i am rendering a page that is primarily a form with viewmake in laravel and it is crashing causing err connection reset after a long investigation and many red herrings i started erasing not commenting random sections out of the blade file for the view and realized that if i a erase 2 of the form calls inside this section of the form b remove the and from around this section of the form div classformrow formlabelfoo foo formtextfoo div div classformrow formlabelfoo foo formtextfoo div div classformrow formlabelfoo foo formtextfoo div the page will render i am not sure what exactly the cause here is there are other blocks above and below although this is a 3div commented out section which none of the others areanyone have a clue what is causing this running on wamp if that matters,['php'] +826464,error error installing mysql2 error failed to build gem native extension i am having some problems when trying to install gem install mysql2 v 0317 for rails when i try to install it by running gem install mysql2 v 0317 or gem install mysql2 v 0317 it gives me the following errorerror error installing mysql2 error failed to build gem native extensioncould not create makefile due to some reason probably lack ofnecessary libraries andor headers check the file for moredetails you may need configuration optionsprovided configuration options withoptdir withoptinclude withoutoptincludeoptdirinclude withoptlib withoutoptliboptdirlib withmakeprog withoutmakeprog withmysqldir withoutmysqldir withmysqlinclude withoutmysqlincludemysqldirinclude withmysqllib withoutmysqllibmysqldirlib withmysqlconfig withoutmysqlconfiggem files will remain installed in gemsruby193p392gemsmysql20317 for inspectionresults logged to gemsruby193p392extensionsx86 64darwin14191mysql20317gem makeouthow can i fix this and successfully install mysql2thanks all,"['mysql', 'ruby-on-rails', 'ruby']" +826565,laravelhow to seperate cache and session into different rethis database i want to put session and cache data into rethisthis is my configuration in databasephprethis array cluster false default array host 19216856101 port 6379 database 0 session array host 19216856101 port 6379 database 1 sessionphpreturn array driver rethis connection sessioncachephpdriver rethishoweverwhere i write code like this cacherememberaa1function return bbcache driver uses the same rethis database as session driver doeswhich results in12700163791 keys 1 aa2 e0606244bec40b0352fb2b7b65d98049e49f6189anyone knows how to force cache to use a specific rethis connentionor i have to mix them up together,['php'] +826593,locks between two methods starving one method in my program i have two methodspublic void methoda gets called very often write something to filepublic void methodb write something to filemethoda gets called by the client very often whereas methodb gets only called from time to time however i need to make sure that whenever a client wants to call methodb it can do so after possible current execution of methoda has finished i tried to introduce a synchronized block with an locking object within each method however methodb seems to starve since methoda gets called more oftenhow can i solve this issue,['java'] +826624,ionic ioncontent not scrolling down when keyboard shows android i have a simple view with a login form on android if the keyboard is opened the content is not scrolling up to prevent it from getting behind the keyboardi followed the keyboard instructions from the docs and read a lot of forum posts but i have not figured it outi installed the keyboard plugin comionickeyboardthis is the structure of the pageionnavview ionview ioncontent formlogin formform ioncontent ionviewionnavviewif i put some extra dummy content in the page it shows that ioncontent is indeed scrollable however it is not moving up when the keyboard is opened by focusing on an inputionic version 100beta13is my app fullscreen nodid i test if the keyboard plugin is working yesis there anything else i have to do,['javascript'] +826708,how can i thistinguish between stage and production builds on itunes connect apple testflight stage builds talk to stage servers which are as identical as possible to production servers for testing purposesproduction builds talk to production servers which store real critical datathese are builds that are essentially for the same application however the itunes connect interface will show you the followingie builds are uniquely identified by their build numbers and nothing elsetherein lies the problem nothing indicates to me whether any particular build is stage or production how could i possibly be expected to rememberso aa how am i supposed to manage stage and production builds separately any thoughtsps okay i imagine the simplest way to do this is to create two separate apps on itunes connect aa one for stage and one for production youd do this for any other hosted service so i guess there is no difference here,['ios'] +826781,how to know whether a recyclerview linearlayoutmanager is scrolled to top or bottom currently i am using the follow code to check whether swiperefreshlayout should be enabledprivate void layswipetoggle if mrecyclerviewgetchildcount 0 mrecyclerviewgetchildat0gettop 0 mlayswipesetenabledtrue else mlayswipesetenabledfalse but here is the problem when it is scrolled to another items views boundary mrecyclerviewgetchildat0gettop also returns 0is there something like recyclerviewisscrolledtobottom or recyclerviewisscrolledtotopedit mrecyclerviewgetchildat0gettop 0 linearlayoutmanagerfindfirstvisibleitemposition 0 kind of does the recyclerviewisscrolledtotop but what about recyclerviewisscrolledtobottom,['android'] +826806,service intent must be explicit intent i have an app some time now in which i call a service through a broadcast receiver mystartupintentreceiver the code in the broadcast receiver in order to call the service ispublic void onreceivecontext context intent intent intent serviceintent new intent serviceintentsetactioncomduk3reortologio2myservice contextstartserviceserviceintentthe problem is that in android 50 lollipop i get the following error in previous versions of android everything works okunable to start receiver comduk3reortologio2mystartupintentreceiver javalangillegalargumentexception service intent must be explicit intent actcomduk3reortologio2myservice what do i have to change in order for the service to be declared as explicit and start normally tried some answers in other similar threads but although i got rid of the message the service wouldnt start,['android'] +827020,configjson adding database connection strings in aspnet vnext i am in the process of learning aspnet vnext i need to store two connection strings in the configjson file how do i store those can i do thisconfigjson connectionstrings connection1 server connection2 server i have not been able to find a schema for configjson for that reason i was not sure how to do it i saw the use of iconfiguration here still i was not sure how configuration was available in the app,['c#'] +827176,cannot use dynamic type with aspnet vnext core i need to read and save a json file inside an aspnett vnext app and i would like to use a dynamic variable to store the value loaded using jsonnet but when i go to compile i received this error messageaspnet core 50 error cs1980 cannot define a class or member that utilizes dynamic because the compiler required type systemruntimecompilerservicesdynamicattribute cannot be found are you missing a referencehow can solve this if i use dynamic can i run an application using aspnet core,['c#'] +827305,how to return an anonymous struct in c trying some code i realized that the following code compilesstruct int x y foovoid it seems as if we are defining a function named foo which returns an anonymous structnow my question is does it only happen to compile with my compiler or is this legal c99 if so what is the correct syntax for a return statement and how can i correctly assign the returned value to a variable,['c'] +827399,how to set default phpini to be used osx yosemite i set up a new environment using osx yosemitei am using the builtin phpi would like to change some config in phpini such as datetimezone but none of the modifications are working despite restarting the apache server sudo apachectl restartphpinfo is giving a different path than php ini commandphpinfoconfiguration file phpini path usrlocalphp5libloaded configuration file usrlocalphp5libphpinivia commands which phpusrbinphpphp iniconfiguration file phpini path etcloaded configuration file etcphpiniscan for additional ini files in libraryserverwebconfigphpadditional ini files parsed noneso i guess i have to tell somewhere where i should set the default phpini to be usedany ideas hints,['php'] +827520,reactrouter pass props to handler component i have such structure of my reactjs app with reactrouter var dashboard requiredashboardvar comments requirecommentsvar index reactcreateclass render function return div headersome headerheader routehandler div var routes route path handlerindex route pathcomments handlercomments defaultroute handlerdashboard routereactrouterrunroutes function handler reactrenderhandler documentbodyi want to pass some properties into comments component normally like comments mypropvalue whats the easiest and right way to do so with reactrouter,['javascript'] +827564,thiskpart does not process script correctly when executed from createprocess thiskpart myscripttxtselect thisk 1convert dynamic noerrselect thisk 2convert dynamic noerrcreate volume stripe thisk12 noerrassign letterx noerr when running from the command prompt thiskpart s myscripttxt it works as expectedhowever when run using win apis createprocess both the convert commands do work but when it gets tocreate volume it thisplays the arguments you specified for this command are not valid now to make things more interestingif the script is executed again from createprocess a 2nd time given the thisks are now converted and it gives a correct error for the convert comamnds when it gets to the create volume it does work this makes me think it has something do with the thisks and or executableany point in the right direction is appreciated as this is very confusing thanks startupinfo siprocess information pizeromemorysi sizeofsizeromemorypi sizeofpisicb sizeofsistrncpy command thiskpartexe s myscripttxt sizeofcommand 1 createprocess cwindowssystem32thiskpartexe command null null true 0 null null si pi end original question editupdates and more info added about 15 20 seconds worth of delay before create volume command still got the same error messagealso split the work into two scripts with two calls tocreateprocess on the second script just calling create volumeand assign it hung for a while and then came back with a thiscommand cannot be completed at this timeor something to theeffectanother thing to note on the first script putting them intodynamic it was running about twice as slow compared to running withcommand promptmaybe should just run the whole thing twice with errors on the second run as that did workedit2the 2 scripts is now working or worked when i tried it again not sure why it did not work the first time,['c++'] +827578,suicide object implementation leveraging stdweak ptr i am considering using suicide objects to model entities in a game that is objects able to delete themselves now the usual c03 implementation plain old delete this does nothing for other objects potentially refering to the suicide object which is why i am using stdshared ptr and stdweak ptrnow for the code dump include memoryinclude iostreaminclude cassertstruct suobj suobj stdcout func n suobj stdcout func n void die ptrreset static stdweak ptrsuobj create stdshared ptrsuobj obj stdmake sharedsuobj return objptr stdmoveobj private stdshared ptrsuobj ptrint main stdweak ptrsuobj obj suobjcreate assertobjexpired stdcout still aliven objlockdie assertobjexpired stdcout deletedn return 0questionthis code appears to work fine however i would like to have someone elses eye to gauge it does this code make sense did i blindly sail into undefined lands should i drop my keyboard and begin art studies right now i hope this question is sufficiently narrowed down for so seemed a bit tiny and lowlevel for crminor precisioni do not intend to use this in multithreaded code if the need ever arises i will be sure to reconsider the whole thing,['c++'] +827625,java remove specific item from concurrenthashmap is using the remove method okay i have read an article that synchronization has not been added to the remove method how do i properly remove a specific item from a concurrenthashmap example code concurrenthashmapstringinteger storage new concurrenthashmapstringinteger storageputfirst 1 storageputsecond 2 storageputthird3 is this the proper way of removing a specific item from a treadsafe collection storageremovefirst for entrystring integer entry storageentryset string key entrygetkey object value entrygetvalue systemoutprintlnkey value,['java'] +827817,stopping the timeout angularjs var app angularmodulemyapp appcontrollerpopupctrl functionscope timeoutscopeshow none scopemouseover function consolelogmouse enter scopeshow block scopemouseout function consolelogmouse leave var timer timeoutfunction scopeshow none 20 when i mouseover a button a pop up dialog box is show when i mouseout the pop up dialog box is going to be hidden in two seconds the problem come when i mouseover the button for the second time even my cursor is still on the button the pop up dialog box is hide in two second how to stop the timer when the mouse is over the button again,['javascript'] +827830,applicationinsight causing website to hang at startup is anyone using applicationinsight successfully at the momenti have had nothing but trouble trying to get it to workfirstly i had lots of problems with vs refusing to create a new website with applicationinsight and with adding applicationinsight to an existing website the errors it gave where next to uselessi finally managed to get a new website with ai working on my machine after waiting some time which was the official answer to the initial problem from microsoft however this website suddenly started hanging on startup with absolutely no error message or debug info that i could findi wasted over a day looking into db connectivity issues as that is what i was working on when it started to hang before thisabling ai and it started working againis there any debug info available for ai so that if it happens again i can catch itall help and experience from others very much appreciatedcheers mikeadded informationi am running vs 2013 update 4all other software should be up to datesteps to reproducestart vsnew projectmvc project connected to applicationinsightthis should fail to run it just hangs waiting for localhost if you add some breakpoints then it actually seems to hang in globalasax when it registers the areas protected void application start arearegistrationregisterallareas hangs here filterconfigregisterglobalfiltersglobalfiltersfilters routeconfigregisterroutesroutetableroutes bundleconfigregisterbundlesbundletablebundles which does not make much sense as that line does not do anything in a clean mvc projectif you thisable ai in the webconfig the project will work againmodules remove nameformsauthentication remove nameapplicationinsightswebtracking add nameapplicationinsightswebtracking typemicrosoftapplicationinsightsextensibilitywebrequesttrackingwebrequesttrackingmodule microsoftapplicationinsightsextensibilityweb preconditionmanagedhandler modulesif someone else could try to replicate this that would be a great startthanks,"['asp.net', '.net']" +827951,apple macho linker error sqlite3 i got this error when building my apps can anyone help me solve this problemi am using swift and parsecom thank you so much for your helpsince i cannot post image below i post the whole error messageundefined symbols for architecture i386 sqlite3 bind blob referenced from pfsqlitedatabase bindobjecttocolumninstatement in parsepfsqlitedatabaseo sqlite3 bind double referenced from pfsqlitedatabase bindobjecttocolumninstatement in parsepfsqlitedatabaseo sqlite3 bind int64 referenced from pfsqlitedatabase bindobjecttocolumninstatement in parsepfsqlitedatabaseo sqlite3 bind null referenced from pfsqlitedatabase bindobjecttocolumninstatement in parsepfsqlitedatabaseo sqlite3 bind parameter count referenced from 59pfsqlitedatabase executequeryasyncwithargumentsinarray block invoke in parsepfsqlitedatabaseo 57pfsqlitedatabase executesqlasyncwithargumentsinarray block invoke in parsepfsqlitedatabaseo sqlite3 bind text referenced from pfsqlitedatabase bindobjecttocolumninstatement in parsepfsqlitedatabaseo sqlite3 close referenced from 30pfsqlitedatabase closeasync block invoke in parsepfsqlitedatabaseo sqlite3 column blob referenced from pfsqlitedatabaseresult dataforcolumnindex in parsepfsqlitedatabaseresulto sqlite3 column bytes referenced from pfsqlitedatabaseresult dataforcolumnindex in parsepfsqlitedatabaseresulto sqlite3 column count referenced from pfsqlitedatabaseresult columnnametoindexmap in parsepfsqlitedatabaseresulto sqlite3 column double referenced from pfsqlitedatabaseresult doubleforcolumnindex in parsepfsqlitedatabaseresulto sqlite3 column int referenced from pfsqlitedatabaseresult intforcolumnindex in parsepfsqlitedatabaseresulto sqlite3 column int64 referenced from pfsqlitedatabaseresult longforcolumnindex in parsepfsqlitedatabaseresulto sqlite3 column name referenced from pfsqlitedatabaseresult columnnametoindexmap in parsepfsqlitedatabaseresulto sqlite3 column text referenced from pfsqlitedatabaseresult stringforcolumnindex in parsepfsqlitedatabaseresulto sqlite3 column type referenced from pfsqlitedatabaseresult objectforcolumnindex in parsepfsqlitedatabaseresulto pfsqlitedatabaseresult columnindexisnull in parsepfsqlitedatabaseresulto sqlite3 errmsg referenced from pfsqlitedatabase errorwitherrorcode in parsepfsqlitedatabaseo sqlite3 finalize referenced from 59pfsqlitedatabase executequeryasyncwithargumentsinarray block invoke in parsepfsqlitedatabaseo 57pfsqlitedatabase executesqlasyncwithargumentsinarray block invoke in parsepfsqlitedatabaseo pfsqlitestatement close in parsepfsqlitestatemento sqlite3 open referenced from 29pfsqlitedatabase openasync block invoke in parsepfsqlitedatabaseo sqlite3 prepare v2 referenced from 59pfsqlitedatabase executequeryasyncwithargumentsinarray block invoke in parsepfsqlitedatabaseo 57pfsqlitedatabase executesqlasyncwithargumentsinarray block invoke in parsepfsqlitedatabaseo sqlite3 reset referenced from pfsqlitestatement reset in parsepfsqlitestatemento sqlite3 step referenced from 57pfsqlitedatabase executesqlasyncwithargumentsinarray block invoke in parsepfsqlitedatabaseo pfsqlitedatabaseresult next in parsepfsqlitedatabaseresultold symbols not found for architecture i386clang error linker command failed with exit code 1 use v to see invocation,['ios'] +827954,spacebar triggering click event on checkbox if you spacebar on a checkbox it checks the box everything was fine until i decide to thisable the click event on the parent div which i realized thisabled the spacebar on the checkbox as welldiv1addeventlistenerclickfunction e if epreventdefault epreventdefault ecancelbubble true return false truediv iddiv1 input idchk1 typecheckboxdivhow can i prevent that it seems like a very odd behaviour to me click events are click events not keyboard eventsnote tested with chrome and ffedit worst outputing the event in the console gives a mouseevent see the updated fiddle this is absurd,"['javascript', 'html']" +828011,swift extract regex matches i want to extract substrings from a string that match a regex pattern so i am looking for something like thisfunc matchesforregexintextregex string text string string so this is what i havefunc matchesforregexintextregex string text string string var regex nsregularexpressionpattern regex options nil error nil var results regexmatchesinstringtext options nil range nsmakerange0 countelementstext as arraynstextcheckingresult return the problem is that matchesinstring delivers me an array of nstextcheckingresult where nstextcheckingresultrange is of type nsrange nsrange is incompatible with rangestringindex so it prevents me of using textsubstringwithrangeany idea how to achieve this simple thing in swift without too many lines of code,['ios'] +828107,can i get an unspecialized vector type in c a vectorbool is specialized to reduce space consumption 1 bit for each element but it is slower to access than vectorchar sometimes i use a vectorchar for performance reason but if i convert a char to a bool my compiler visual c may generate a c4800 warning which i do not likealso i think the vectorchar is semantically wrong if i treat it as unspecialized vectorbool so can i get a real unspecialized vectorbool type in c,['c++'] +828381,fabric twitterkit on xamarin has anyone been able to get twitterkit to work with xamarin android fabric does not have a plugin for xamarin so has anyone been able to get it to work,['android'] +828408,dependencies could not create plugin of type aplugin i am trying to continue working on an older project of mine it is about a year old and was working fine back then but now after that i have updated androidstudio it cannot even build anymorei am getting an error saying that i have got the same dex file twicecomandroiddexdexexception multiple dex files define landroidsupportv4accessibilityserviceaccessibilityserviceinfocompataccessibilityserviceinfoversionimplto fix this i could simply do gradle dependencies to find the culprit and exclude the faulty files but this is where i run into my actual problemwhen i do gradle dependencies i get the following errorfailure build failed with an exception where build file fgithubcoinbookappbuildgradle line 1 what went wronga problem occurred evaluating project app could not create plugin of type aplugin try run with stacktrace option to get the stack trace run with info or debug option to get more log outputand here is my full buildgradle fileapply plugin comandroidapplicationandroid compilesdkversion 21 buildtoolsversion 2112 defaultconfig applicationid commoonraincoinbook minsdkversion 14 targetsdkversion 21 versioncode 1 versionname 07 buildtypes release minifyenabled false proguardfiles getdefaultproguardfileproguardandroidtxt proguardrulespro dependencies compile projectlibsandroidbootstrap compile fileslibssocialauth44jar compile fileslibssocialauthandroid32jar compile comdoomonafireballbetterpickerslibrary152 compile comjakewhartonbutterknife600 compile comastuetzpagerslidingtabstrip101 compile comgithubcastorflexsmoothprogressbarlibrary100 compile comsquareuppicassopicasso234 compile comreadystatesoftwaresystembartintsystembartint104 compile comgooglecodegsongson23so this is were i am basically stuck at the moment i have tried the following to fix the issue updated androidstudio updated all sdk related items updated gradle recreated the entire project in a new folder then copied over my files to the new project each post i find regarding this issue it says to use gradle 073 instead of 072 because of a bug but that is like a year old and no longer valid,['android'] +828550,android lollipop animation glitch i have a strange behaviour with the default layout animation in devices running android 5 lollipop i am using an activity with multiple fragments which are replaced at runtime using the default fragment manager when replacing the old fragment i want to use an animation for a smooth ui flow on prelollipop devices the animation works like expected but on devices running the latest os the animation between fragment glitchesi tried using the default animation xml tag androidanimatelayoutchangestruebecause it does not work i changed it using this code with no effectmtransaction mmanagerbegintransaction mtransactionsetcustomanimationsandroidranimatorfade in androidranimatorfade out mtransactionremovemfragment mtransactionaddridcontainer mfragment fragment mtransactioncommiti have tested the code on different devices and in the android emulator the strange thing is that it works like expected on devices running prelollipop and in the android emulator running the latest os 501 but it does not work on devices like nexus 4 and nexus 5 running android 50any suggestions any helpthanks in advanceeditit seems to be a bug depending on the used device i have tested the code on different devices samsung galaxy s4 htc one mini2 one m8 desire s nexus 45 and it only appears on google nexus devices editone workaround to fix the animation issue is to thisable the hardware acceleration via theapplication androidhardwareacceleratedfalse tag in the app manifest but using this makes the app very slow solutionthe solution to fix this issue is to set a background imagecolordrawable to the activity see,['android'] +828600,uitableview editactionsforrowatindexpath stops working if you return an empty array i have a uitableview for which i have added some custom slide out buttons these all work as expected there is however a scenario in my table where a row can be in a state where none of the slide out buttons are relevant and so i have been returning an empty array of actions so the slide out buttons wont appear unfortunately once this occurs the uitableview stops calling my editactionsforrowatindexpath effectively thisabling slide out buttons for all rows in my table and it seems permanent until the app is restartedis this expected behaviourfunc tableviewtableview uitableview editactionsforrowatindexpath indexpath nsindexpath anyobject if mydataindexpathroweditavailable var editaction uitableviewrowactionstyle default title edit handler edithandler return editaction else return,['ios'] +828655,google analytics demographics for android app i used google analytics demographics on android app using google play service libraryi have updated my android code using enableadvertisingidcollectionits working fine with screens and data but its demographics info is not workingplease suggest how do i handle demographicsthanking youcode application code synchronized tracker gettracker trackername trackerid string appkey logdapplication in application class gettracker pid appkey if mtrackerscontainskeytrackerid googleanalytics analytics googleanalyticsgetinstancethis analyticssetdryrunfalse analyticsgetloggersetloglevelloggerloglevelinfo tracker t trackerid trackernameapp tracker analyticsnewtrackerappkey analytics newtrackerrxmlapp tracker if t null tenableadvertisingidcollectiontrue mtrackersputtrackerid t return mtrackersgettrackeridcode on oncreate try googleanalyticsgetinstancegetactivityreportactivitystartgetactivity tracker t appapplication getactivitygetapplicationgettrackertrackernameapp tracker appkey tsetscreennamehome screen tsetsampleratesamplerate tenableadvertisingidcollectiontrue tsendnew hitbuildersappviewbuilderbuild catch exception ex customloggershowloggacode exgetmessage,['android'] +828726,swift add iconimage in uitextfield i would like to add iconimage in uitextfield the iconimage should be left to placeholderi tried thisvar imageview uiimageviewvar image uiimagenamed emailpngimageviewimage imageemailfieldleftview imageviewthanks,['ios'] +828854,android camera 2 api i have been trying camera2 api i have downloaded code from to learn about how it works it works fine till i stop recording when i stop recording it runs following code private void stoprecordingvideo ui misrecordingvideo false mbtn videosettextrstringrecord stop recording try mmediarecorderstop mmediarecorderreset catch exception e eprintstacktrace activity activity getactivity if null activity systemoutprintlnfile getvideofileactivity toastmaketextactivity video saved getvideofileactivity toastlength shortshow startpreviewat mmediarecorderstop it throw following error0112 162423115 21612200comcameratwoapi esurfacei1 queuebuffer error queuing buffer to surfacetexture 190112 162423135 21612200comcameratwoapi eegl emulationi1 tid 2200 swapbuffers285 error 0x3003 egl bad alloc0112 162423197 21612200comcameratwoapi ecameradeviceglthread0i1 received exception on gl render thread javalangillegalstateexception swapbuffers egl error 0x3003 at androidhardwarecamera2legacysurfacetexturerenderercheckeglerrorsurfacetexturerendererjava487 at androidhardwarecamera2legacysurfacetexturerendererswapbufferssurfacetexturerendererjava480 at androidhardwarecamera2legacysurfacetexturerendererdrawintosurfacessurfacetexturerendererjava681 at androidhardwarecamera2legacyglthreadmanager1handlemessageglthreadmanagerjava103 at androidoshandlerthispatchmessagehandlerjava98 at androidoslooperlooplooperjava135 at androidoshandlerthreadrunhandlerthreadjava61any idea what i am doing wrong i spent few hours but could not find any solutionedit i am using geneymotion emulator the path i am using file storageemulated0androiddatacomgoldcameratwoapifilesvideomp4thanks,['android'] +828907,how to enable front camera in webview for android how do you enable the front camera on a webview i have enable the features in androidmanifestxml usesfeature androidnameandroidhardwarecamera androidrequiredtrue usesfeature androidnameandroidhardwarecamerafront androidrequiredtrue the camera is not going to be used for taking photos or recording just to switch on the front camerawhen i go to the website using the phone browser the phone camera works once allow the prompt message how can this work with a webview in the html file has a canvas and video tag that thisplays webcam it does not record or take pictures it just shows you the camera viewhere is the html code canvas idincanvas width500 height500 stylethisplaynonecanvas video idinputvideo width100 height100 autoplay loop videoit work with webcam but not with webview in android,"['javascript', 'android', 'html']" +828947,how to compile forked library in gradle i want to comile following library in my project in buildgradleit is forked from but no documentation given how to include in in projecti tried something like thiscompile comthedazzlerandroidbootstrapbut gradle failed and shows error that library not foundedit can anyone fork it andor publish it,['android'] +829151,numpy merge sorted array to an new array is there any way we can do something like merge in mergesort using numpy function some function like mergea nparray135b nparray246c mergea b c nparray123456i wish i could get high performance for large data thanks to numpy,['python'] +829285,constructor as a function try block exception aborts program i am not sure if this is a issue with the compiler or if i am doing something wrong i am using visual studio 2013 compileri have a class where i need to acquire significant amount of resources in my constructor initializer list most of which can throw an exception i wrapped up the member initializer list in a function try block and caught the exception there but my program still aborts even though the catch clause does not rethrow the exception i am not allowed to post the actual code so i have reproduced the issue with this equivalent demo code can someone please help me address thisinclude iostreamusing namespace stdclass apublic a try i 0 throw 5 catch cout exception endl private int iint main a objon executing this code i get a windows alert abort has been called so i guess the system is treating this as an uncaught exception and calling terminate on the other hand if i wrap the construction of the object in main in a trycatch block then the exception is caught properly and the program terminates normallycan someone please tell me if i am doing something wrong here,['c++'] +829340,static initializer not invoked for a derived class the following java code does not invoke the static initializer of class b whycodeclass a static systemoutprintlna static init public static void f systemoutprintlnf called class b extends a static systemoutprintlnb static init public class app public static void main string args bf invokestatic 16 method comdbtestbfv program outputa static initf calledtested on jdk 180 25,['java'] +829366,asynchronous http request handling with tomcat and spring it is my first so question so be patient with me i am trying to create a service thatreceives http get requests containing a url to queryfor a single get request the service extracts the urlqueries a local db about the urlif a result was found in the db it will return it to the client and if not it will need to query some external services that may take relatively long time to respondreturn the result of the url to the clienti am running this on a virtual machine and tomcat7 with springi will apologize in advance and mention that i am pretty new to tomcatanyway i am expecting a lot of concurrent get requests to this service hundreds of thousands of simultaneous requestswhat i am basically trying to achieve is to make this service as scalable as possible and if that is not possible then at least a service that can handle hundreds of thousands of simultaneous requestsi have been reading a lot about asynchronous requests handling in services and especially in tomcat but i have some things that are still unclear to mefrom the official tomcat website it seems that tomcat contains number of acceptor threads and number of working threadsif so why should i use asynccontext whats the benefit of releasing a tomcats working thread and occupying a different thread in my application to do the exact same actions there is still 1 active thread in the systemsomewhat similar to the first question but are there any benefits for creating the asynccontext and using it with a different thread a thread from a thread pool created in my applicationregarding the same issue i have seen here that i can also return a callable or a deferredresult and process it with either one of tomcats threads or with one of my own threads are there any benefits for returning a callable or using a deferredresult over just processing the asynccontext from the requestsalso if i decide to return a callable from what thread pool does tomcat gets the thread to process my callable are the threads being used here the same working threads from tomcat that i previously mentioned if so what benefits do i get from releasing one tomcat working thread and using a different one insteadi have seen from oracles documentation that i can pass asynccontext a runnable object that will be processed concurrently from where do the threads used to execute this runnable come from do i have any control over it also any benefits to passing the asynccontext a runnable over just passing the asynccontext to one my threadsi apologize for asking so many questions regarding the same things but me and my colleagues are arguing over these things for over a week without any concrete answeri have 1 more general question what do you think is the best way to make the service i described scalable putting aside adding more machines at the moment could you post any examples or references for the purposed solutioni would post more links of links i have been looking at but my current reputation does not allow it i will be grateful for any understandable references or for concrete examples and i will obviously be happy to clarify on any relevant issuecheers,['java'] +829370,how to get response headers when using alamofire in swift i am using alamofire for my rest post request and getting json response seamlessly but i can access only response body i want to get response headers is not it possible when using alamofirehere is my code snippetibaction func loginbuttonpressedsender uibutton let baseurl globalsapiconstantsbaseurl let endpoint globalsapiconstantsendpointsauthorize let parameters apikey api key is here apipass api pass is here agent agent is here alamofirerequestpost baseurl endpoint parameters parametersresponsejson request response data error in let json jsondata if let result jsonresultbool selflblresulttext result result,"['ios', 'iphone']" +829466,how to approach base exception thrown by api method say i am dealing with forced to use a library api method that throws some sort of nondescript base exception for example throws exception in java assume i do not have the option to modify the library source and i must deal with the base exception any time i call the api method from my own methods for some context my code might look like this without interventionpublic void mymethod throws exception i do not want to do this someapiobjecttheirmethod api method throwing base exceptionand here might be the api method i am calling in topublic void theirmethod throws exception this is my problem does stuff that could cause problems but is lazy and implicitly throws base exception now it is my problemmy question is how do i best go about dealing with this base exception being thrown at my methods i assume it is in my best interest to somehow preserve all of the original exception information while propagating something more useful than a base exception for example i have considered catching and storing the base exception in my own exception type and throwing that insteadpublic void mymethod try someapiobjecttheirmethod api method throwing base exception catch exception e throw new myspecificexceptione rethrow my own exception i am not looking for opinions but rather some solid and straightforward evidence pros as to why a particular solution is a good solution as well as any cavaets cons my focus is on java but i am curious of any general concepts or bestpractices,['java'] +829467,react render component using its name i am experimenting reactjs and it is working really well i am wondering if it is possible to inject classes to other classes like so var container reactcreateclass render function thispropsimplcomponent assuming implcomponent has been passed like soreactrender container implcomponentsomepredefinedvariable documentgetelementbyidcontentthis does not work because of a syntax error i can easily understand why in other words i would like to inject classes to other classes based on names is this possible how can i do that,['javascript'] +829507,thisable click on recyclerview inside a swiperefreshlayout i implemented a swiperefreshlayout using a recyclerview and i need that my adapter items are thisabled during the onrefreshlisteneri tried the following approach but the click occurs normallymrecyclerviewsetenabledfalsemrecyclerviewsetclickablefalse,"['java', 'android']" +829553,any workaround for ios8 bug that affects html select inside uiwebview eg cordova phonegap so there is a major unresolved issue with ios8 uiwebview which basically means cordova apps using the select element are extremely prone to crash this is a major unresolved issue and has been open for several monthsthe bug can be reproduced by create a phonegap sample project and putting one html select element in it and clicking on it repeatedly on an ipad 34 on ios8 the app crashes with one of several exceptionsi have applied one solution as mentioned at but the app still crashes with one of several other exceptionsthe most common exception is20150112 144137971 helloworld912832062 application tried to represent an active popover presentation uiwebselecttableviewcontroller 0x17d169d0 from mainviewcontroller 0x17e84ba020150112 144157048 helloworld912832062 terminating app due to uncaught exception nsrangeexception reason uitableview contentoffsetforscrollingtorowatindexpathatscrollposition row 4 beyond bounds 0 for section 0libcabidylib terminating with uncaught exception of type nsexceptionit seems to be some sort of race condition with when the select element is pressed but i have no idea where to start fixing it as it is inside complied librariesit is definitely some sort of race condition,"['html', 'objective-c']" +829653,java reserved name compilation i have seen this cod why it works pleasepublic void nw systemoutprintlnit is compile in java i think new is a reserved word,['java'] +829714,why does not closure typecheck the parameters when using functionapply see below param string a param string b var f functiona b param string a param boolean c var h functiona c fapplythis arguments no compile error fapplythis a c no compile error fcallthis a c compile error does not match formal parameterwhy does closure raise an error only when using call and not applyis there a way i can made closure typecheck the parameters even when i am using apply,['javascript'] +829730,can gulpusemin accept multiple files i have an issue with usemin and am not sure if it is a bugmy application structure is simple root gulpfilejs app indexhtml abouthtml contacthtml js ajs bjs cjs djs ejs thisteach of my html files has a usemin block in it to include all of the scripts for example buildjs jsappjs script srcjsajsscriptscript srcjsbjsscriptscript srcjscjsscriptscript srcjsdjsscriptscript srcjsejsscript endbuild when i run the following taskgulptaskusemin function gulpsrcapphtml pipeusemin assetdir app pipedestthistonly the first html file will copy to the new directory the js in this case is concatenated as expectedwhen i change the gulpsrc to gulpsrcindexhtmlabouthtmlcontacthtml i get a diffrent issue all the html files copy over but only the first one in alphabetical order runs the usemin block replacing the 5 scripts with the new scriptany insights would be great i have extensively read through the gulp documentation and the gulpusemin documentation and cannot find any reasons why this should be happeningthe example on the npm website for the first of my two cases is even given as an example not sure whats going on here maybe something to do with where i am running the gulpfile fromis this even possiblecheerseditnot sure what was happening here but i created a totally new project and built installed the npm plugins and scripts from scratch and everything worked not a great solution but it saved me some time,['javascript'] +829740,deterministic bit scrambling to filter coordinates i am trying to write a function that given an xy coordinate pair and the random seed of the program will psuedorandomly return true for some preset percentage of all such pairs there are no limits on x or y beyond the restrictions of the data type which is a 32bit signed intmy current approach is to scramble the bits of x y and the seed together and then compare the resulting number to the percentagefloat percentage 05unsigned int and x y seedreturn float and uint max percentagehowever it seems that this approach would be biased for certain values of x and y for example if it returns true for 0a it will also return true for a0 i know this implementation that just xors them together is naive is there a better bitscrambling algorithm to use here that will not be biasededit to clarify i am not starting with a set of xy coordinates nor am i trying to get a fixedsize set of coordinates that evaluate to true the function should be able to evaluate a truth value for arbitrary x y and seed with the percentage controlling the average frequency of true coordinates,['c'] +829873,how to prevent css keyframe animation to run on page load i have a div in which i animate the contentcontainer position relative width 100px height 100px borderstyle insetcontent visibility hidden webkitanimation animdown 1s ease position absolute top 100px width 100 height 100 backgroundcolor lightgreencontainerhover content webkitanimation animup 1s ease animationfillmode forwards webkitanimationfillmode forwardswebkitkeyframes animup 0 webkittransform translatey0 visibility hidden opacity 0 100 webkittransform translatey100 visibility visible opacity 1 webkitkeyframes animdown 0 webkittransform translatey100 visibility visible opacity 1 100 webkittransform translatey0 visibility hidden opacity 0 div idcontainer div idcontentdivdivon hover content slides into the container divmy problem is when i refresh the page and the page loads the contents animdown animation will run and i would prefer it to run only after a hover eventis there a way to do this pure css or i have to figure something out in js,['css'] +829894,widget not tinted on lollipop i am using appcompat v2103 for my app i did everything like it is written here androiddevelopersblogspotcom201410appcompatv21materialdesignforprehtmlbut on lollipop and on older devices of course some widget are not tinted with my accent color for exampleswitchcompat is tinted listpreference is not tinted progressdialog is not tinted heres my codebuildgradlecompile comandroidsupportappcompatv7210androidmanifestxmlapplication androidallowbackuptrue androidicondrawableic launcher androidlabelstringapp name androidthemestylecet androidhardwareacceleratedtrue toolsreplacelabelthemesxmlresources style namecet parentthemeappcompatlightnoactionbar item namewindowactionbarfalseitem item namecolorprimarycolorprimaryitem item namecolorprimarydarkcolorprimary darkitem item namecoloraccentcoloraccentitem styleresourcescolorsxmlresources app branding color color nameprimarya32b30color darker variant for status bar and contextual app bars color nameprimary dark0color theme ui constrols like checkboxes and text fields color nameaccenta32b30colorresourcesdoes someone have an ideaupdate as of june 2015 still does not work but i ended up using works really nice for dialogs including listpreferences,['android'] +829915,android studio execution failed for task apredexdebug when i am trying to run an application in emulator through android studio i get the error execution failed for task apredexdebugfull stacktrace failure build failed with an exception what went wrongexecution failed for task apredexdebug comandroididecommoninternalloggederrorexception failed to run command edeveloperandroidsdkbuildtools2112dxbat dex output edeveloperandroidstudioprojectsomgandroidappbuildintermediatespredexeddebugsupportannotations2103c91f7c2a85920982313a91e2dffb704ba92c7823jar edeveloperandroidsdkextrasandroidm2repositorycomandroidsupportsupportannotations2103supportannotations2103jarerror code 1output error could not create the java virtual machine error a fatal exception has occurred program will exit tryrun with info or debug option to get more log output exception isorggradleapitaskstaskexecutionexception execution failed for task apredexdebug at orggradleapiinternaltasksexecutionexecuteactionstaskexecuterexecuteactionsexecuteactionstaskexecuterjava69 at orggradleapiinternaltasksexecutionexecuteactionstaskexecuterexecuteexecuteactionstaskexecuterjava46 at orggradleapiinternaltasksexecutionpostexecutionanalysistaskexecuterexecutepostexecutionanalysistaskexecuterjava35 at orggradleapiinternaltasksexecutionskipuptodatetaskexecuterexecuteskipuptodatetaskexecuterjava64 at orggradleapiinternaltasksexecutionvalidatingtaskexecuterexecutevalidatingtaskexecuterjava58 at orggradleapiinternaltasksexecutionskipemptysourcefilestaskexecuterexecuteskipemptysourcefilestaskexecuterjava42 at orggradleapiinternaltasksexecutionskiptaskwithnoactionsexecuterexecuteskiptaskwithnoactionsexecuterjava52 at orggradleapiinternaltasksexecutionskiponlyiftaskexecuterexecuteskiponlyiftaskexecuterjava53 at orggradleapiinternaltasksexecutionexecuteatmostoncetaskexecuterexecuteexecuteatmostoncetaskexecuterjava43 at orggradleapiinternalabstracttaskexecutewithoutthrowingtaskfailureabstracttaskjava305 at orggradleexecutiontaskgraphabstracttaskplanexecutortaskexecutorworkerexecutetaskabstracttaskplanexecutorjava79 at orggradleexecutiontaskgraphabstracttaskplanexecutortaskexecutorworkerprocesstaskabstracttaskplanexecutorjava63 at orggradleexecutiontaskgraphabstracttaskplanexecutortaskexecutorworkerrunabstracttaskplanexecutorjava51 at orggradleexecutiontaskgraphdefaulttaskplanexecutorprocessdefaulttaskplanexecutorjava23 at orggradleexecutiontaskgraphdefaulttaskgraphexecuterexecutedefaulttaskgraphexecuterjava88 at orggradleexecutionselectedtaskexecutionactionexecuteselectedtaskexecutionactionjava29 at orggradleexecutiondefaultbuildexecuterexecutedefaultbuildexecuterjava62 at orggradleexecutiondefaultbuildexecuteraccess200defaultbuildexecuterjava23 at orggradleexecutiondefaultbuildexecuter2proceeddefaultbuildexecuterjava68 at orggradleexecutiondryrunbuildexecutionactionexecutedryrunbuildexecutionactionjava32 at orggradleexecutiondefaultbuildexecuterexecutedefaultbuildexecuterjava62 at orggradleexecutiondefaultbuildexecuterexecutedefaultbuildexecuterjava55 at orggradleinitializationdefaultgradlelauncherdobuildstagesdefaultgradlelauncherjava149 at orggradleinitializationdefaultgradlelauncherdobuilddefaultgradlelauncherjava106 at orggradleinitializationdefaultgradlelauncherrundefaultgradlelauncherjava86 at orggradlelauncherexecinprocessbuildactionexecuterdefaultbuildcontrollerruninprocessbuildactionexecuterjava80 at orggradletoolinginternalproviderbuildmodelactionrunbuildmodelactionjava43 at orggradletoolinginternalproviderbuildmodelactionrunbuildmodelactionjava30 at orggradletoolinginternalproviderconfiguringbuildactionrunconfiguringbuildactionjava119 at orggradlelauncherexecinprocessbuildactionexecuterexecuteinprocessbuildactionexecuterjava36 at orggradlelauncherexecinprocessbuildactionexecuterexecuteinprocessbuildactionexecuterjava26 at orggradlelauncherdaemonserverexecexecutebuilddobuildexecutebuildjava47 at orggradlelauncherdaemonserverexecbuildcommandonlyexecutebuildcommandonlyjava34 at orggradlelauncherdaemonserverexecdaemoncommandexecutionproceeddaemoncommandexecutionjava119 at orggradlelauncherdaemonserverexecwatchforthisconnectionexecutewatchforthisconnectionjava35 at orggradlelauncherdaemonserverexecdaemoncommandexecutionproceeddaemoncommandexecutionjava119 at orggradlelauncherdaemonserverexecresetdeprecationloggerexecuteresetdeprecationloggerjava24 at orggradlelauncherdaemonserverexecdaemoncommandexecutionproceeddaemoncommandexecutionjava119 at orggradlelauncherdaemonserverexecstartstopifbuildandstopexecutestartstopifbuildandstopjava33 at orggradlelauncherdaemonserverexecdaemoncommandexecutionproceeddaemoncommandexecutionjava119 at orggradlelauncherdaemonserverexecforwardclientinput2callforwardclientinputjava71 at orggradlelauncherdaemonserverexecforwardclientinput2callforwardclientinputjava69 at orggradleutilswapperswapswapperjava38 at orggradlelauncherdaemonserverexecforwardclientinputexecuteforwardclientinputjava69 at orggradlelauncherdaemonserverexecdaemoncommandexecutionproceeddaemoncommandexecutionjava119 at orggradlelauncherdaemonserverexeclogtoclientdobuildlogtoclientjava60 at orggradlelauncherdaemonserverexecbuildcommandonlyexecutebuildcommandonlyjava34 at orggradlelauncherdaemonserverexecdaemoncommandexecutionproceeddaemoncommandexecutionjava119 at orggradlelauncherdaemonserverexecestablishbuildenvironmentdobuildestablishbuildenvironmentjava70 at orggradlelauncherdaemonserverexecbuildcommandonlyexecutebuildcommandonlyjava34 at orggradlelauncherdaemonserverexecdaemoncommandexecutionproceeddaemoncommandexecutionjava119 at orggradlelauncherdaemonserverexecdaemonhygieneactionexecutedaemonhygieneactionjava39 at orggradlelauncherdaemonserverexecdaemoncommandexecutionproceeddaemoncommandexecutionjava119 at orggradlelauncherdaemonserverexecstartbuildorrespondwithbusy1runstartbuildorrespondwithbusyjava46 at orggradlelauncherdaemonserverdaemonstatecoordinator1rundaemonstatecoordinatorjava246 at orggradleinternalconcurrentdefaultexecutorfactorystoppableexecutorimpl1rundefaultexecutorfactoryjava64caused by orggradleinternaluncheckedexception comandroididecommoninternalloggederrorexception failed to run command edeveloperandroidsdkbuildtools2112dxbat dex output edeveloperandroidstudioprojectsomgandroidappbuildintermediatespredexeddebugsupportannotations2103c91f7c2a85920982313a91e2dffb704ba92c7823jar edeveloperandroidsdkextrasandroidm2repositorycomandroidsupportsupportannotations2103supportannotations2103jarerror code 1output error could not create the java virtual machine error a fatal exception has occurred program will exit at orggradleinternaluncheckedexceptionthrowasuncheckedexceptionuncheckedexceptionjava39 at orggradleinternalreflectjavamethodinvokejavamethodjava66 at orggradleapiinternalprojecttaskfactoryannotationprocessingtaskfactoryincrementaltaskactiondoexecuteannotationprocessingtaskfactoryjava235 at orggradleapiinternalprojecttaskfactoryannotationprocessingtaskfactorystandardtaskactionexecuteannotationprocessingtaskfactoryjava211 at orggradleapiinternalprojecttaskfactoryannotationprocessingtaskfactoryincrementaltaskactionexecuteannotationprocessingtaskfactoryjava2 at orggradleapiinternalprojecttaskfactoryannotationprocessingtaskfactorystandardtaskactionexecuteannotationprocessingtaskfactoryjava200 at orggradleapiinternaltasksexecutionexecuteactionstaskexecuterexecuteactionexecuteactionstaskexecuterjava80 at orggradleapiinternaltasksexecutionexecuteactionstaskexecuterexecuteactionsexecuteactionstaskexecuterjava61 55 morecaused by comandroididecommoninternalloggederrorexception failed to run command edeveloperandroidsdkbuildtools2112dxbat dex output edeveloperandroidstudioprojectsomgandroidappbuildintermediatespredexeddebugsupportannotations2103c91f7c2a85920982313a91e2dffb704ba92c7823jar edeveloperandroidsdkextrasandroidm2repositorycomandroidsupportsupportannotations2103supportannotations2103jarerror code 1output error could not create the java virtual machine error a fatal exception has occurred program will exit at comandroididecommoninternalcommandlinerunnerruncmdlinecommandlinerunnerjava123 at comandroididecommoninternalcommandlinerunnerruncmdlinecommandlinerunnerjava96 at comandroididecommoninternalcommandlinerunnerruncmdlinecommandlinerunnerjava76 at comandroidbuildercoreandroidbuilderpredexlibraryandroidbuilderjava1339 at comandroidbuilderinternalcompilerpredexcachepredexlibrarypredexcachejava119 at comandroidbuildercoreandroidbuilderpredexlibraryandroidbuilderjava1273 at comandroidbuildercoreandroidbuilderpredexlibrary3callunknown source at comandroidbuildgradletaskspredexpredextaskcallpredexgroovy148 at comandroidbuildgradletaskspredexpredextaskcallpredexgroovybuild failedthe java version used in the application is 170 6532 biti am running windows 7 sp1 32 bitany possible reasons also any suggestions on how to solve this error,['android'] +829977,an established connection was aborted by the software in your host machine when using java nio socket i had developed an java server using java nio sockets it is the code of my applicationpublic class echoserver static final orgapachelog4jlogger logger orgapachelog4jloggergetloggermainclassprivate static final int buffer size 1024private final static int default port 4664private inetaddress hostaddress nullprivate int portprivate string ipaddress my ipprivate selector selector the buffer into which well read data when it is availableprivate bytebuffer readbuffer bytebufferallocatebuffer sizeint timestamp 1hashmapinteger string connectedclients new hashmapinteger stringhashmapstring integer clientids new hashmapstringintegerhashmapstring string messagetoclients new hashmapstring stringpublic echoserver thisdefault portpublic echoserverint port try thisport port hostaddress inetaddressgetbynameipaddress selector initselector loop catchexception ex loggererrorexception accouredex private selector initselector try selector socketselector selectorproviderprovideropenselector serversocketchannel serverchannel serversocketchannelopen serverchannelconfigureblockingfalse inetsocketaddress isa new inetsocketaddresshostaddress port serverchannelsocketbindisa serverchannelregistersocketselector selectionkeyop accept return socketselector catchexception ex loggererrorexception accouredex return null private void loop while true try do defined operations for clients selectorselect iteratorselectionkey selectedkeys selectorselectedkeys iterator while selectedkeyshasnext selectionkey key selectedkeysnext selectedkeysremove if keyisvalid loggerwarnkeyhashcode is invalid continue check what event is available and deal with it if keyisacceptable acceptkey else if keyisreadable readkey else if keyiswritable writekey fetch list from server try resultset resultset databasegetinstance getqueryresult boolean flag false while resultsetnext string mobilenumber resultsetgetstringmobileno string message resultsetgetintismessage resultsetgetintisdeliver resultsetgetintisgroup resultsetgetintisseen messagetoclientsputmobilenumber message catch exception ex exprintstacktrace loggererrorexception accouredex wait for 1 second threadsleep10 timestamp catch exception e eprintstacktrace systemexit1 private void acceptselectionkey key try initialize the connection serversocketchannel serversocketchannel serversocketchannel key channel socketchannel socketchannel serversocketchannelaccept socketchannelconfigureblockingfalse socketchannelsetoptionstandardsocketoptionsso keepalive true socketchannelsetoptionstandardsocketoptionstcp nodelay true loggerinfonew client accepted fire read for reading phone number socketchannelregisterselector selectionkeyop read catchexception ex loggererrorexception accouredex private void readselectionkey key try initialize socket socketchannel socketchannel socketchannel keychannel reading client number readbufferclear int numread try numread socketchannelreadreadbuffer catch ioexception e loggererrorforceful shutdown keycancel return read was not successful if numread 1 loggererrorgraceful shutdown keycancel return read was successful and now we can write it to string readbufferflip byte bytes new bytereadbufferlimit readbuffergetbytes string number new stringbytes number numberreplacern number numbertrim update connect clients status integer clientidclientidsgetnumber if clientid null connectedclientsputkeyhashcode number clientidsputnumber keyhashcode loggererrornumber keyhashcode has connected else connectedclientsremoveclientid connectedclientsputkeyhashcode number clientidsputnumber keyhashcode loggererrornumber keyhashcode reconnected systemerrprintlnall clients number are connectedclientssize loggererrorall clients number are connectedclientssize fire write operations socketchannelregisterselector selectionkeyop write catchexception ex exprintstacktrace loggererrorexception accouredex private void writeselectionkey key try check channel still alive string clientnumber connectedclientsgetkeyhashcode ifclientnumber null keycancel return get channel socketchannel socketchannel socketchannel keychannel send message if client number have new message if messagetoclientsgetclientnumber null loggerinfoclientnumber keyhashcode sent write message string timestamp stringvalueoftimestamp string message messagetoclientsgetclientnumber bytebuffer dummyresponse bytebufferwrapmessage rngetbytesutf8 socketchannelwritedummyresponse messagetoclientsremoveclientnumber fire new write state socketchannelregisterselector selectionkeyop write catch ioexception iox loggererrorexception accourediox string number connectedclientsgetkeyhashcode clientidsremovenumber connectedclientsremovekeyhashcode keycancel catchexception ex loggererrorexception accouredex when i am testing with 23 clients it is working fine but when i start testing it with about 100300 client i recived below exception at several timesactually it is happeingin on write method and line socketchannelwritedummyresponsejavaioioexception an established connection was aborted by the software in your host machine at sunniochsocketthispatcherwrite0native method at sunniochsocketthispatcherwriteunknown source at sunniochioutilwritefromnativebufferunknown source at sunniochioutilwriteunknown source at sunniochsocketchannelimplwriteunknown source at netbehbooditestserverechoserverwriteechoserverjava274 at netbehbooditestserverechoserverloopechoserverjava106 at netbehbooditestserverechoserverinitechoserverjava56 at netbehbooditestserverechoserverinitechoserverjava47 at netbehbooditestservermainmainmainjava44and then i can not receive messages from the server,['java'] +830036,slide and change position with jquery i am trying to create a very simple slideshow just for the learning purpose i want to slide the list items to the left automatically in a loopi have come up with following code it slides but i am unable to set the correct position for the slide as it only flashes and thisappears check the demo to see the problemheres my fiddlehtmldiv classwrap ul classlist li1li li2li li3li li4li li5li uldivjqueryvar width liwidthvar totalwidth lilength widthvar count lilengthvar first lieq0var last lieqcount1ulcss width totalwidthfirstaddclassactivevar start function target activeindex target last target 0 target target1 nextslidetarget var nextslide functiontarget consolelogtarget activeanimateleft widthtarget px300 liremoveclassactiveeqtargetaddclassactivesetintervalfunction start 30,"['javascript', 'jquery', 'html', 'css']" +830154,thistinction between the capacity of an array list and the size of an array i read the below snippet in core java i bookallocating an array list as new arraylist employee100 capacity is 100is not the same as allocating a new array as new employee100 size is 100there is an important thistinction between the capacity of an array list and the size of an array if you allocate an array with 100 entries then the array has 100 slots ready for use an array list with a capacity of 100 elements has the potential of holding 100 elements and in fact more than 100 at the cost of additional reallocations but at the beginning even after its initial construction an array list holds no elements at allwhen i saw the source code array list the constructor creates of an object array of given capacity which is ready to hold elements of given capacity below is the code snippet public arraylistint initialcapacity super if initialcapacity 0 throw new illegalargumentexceptionillegal capacity initialcapacity thiselementdata new objectinitialcapacity i am not able to figure out the actual difference what the author has mentioned in above text,['java'] +830204,override the require function is it possible to override the global require function affecting it at process levelfrom what i know the require function is provided as argument in the function that wraps the nodejs scriptsfunction require dirname something like this the wrapped codeis there any way to modify the require functionfunction var require require require function consolelog requireapplythis arguments this will probably affect only the script where it is locatedhow can we modify it at the process level,['javascript'] +830408,a using statement compiles with g fails compilation with clang i have code of the following structure which is of course much more complex in reality especially base is a threeliner but i have tried to capture the gist of ittemplate class tclass a template class tclass b public btemplate class tclass c public bat public using base bat using basebstatic const cint cthe code compiles fine with g viag c testcpp stdc11however with clang i get an error message i do not really understandclang c testcpp stdc11testcpp1414 error dependent using declaration resolved to type without typename using basebis there anything wrong with my code or is this a bug in clangnote when writing using batb it compiles fine with both compilers but this not a real solution to my problemedit clang version is 350 gcc version is 492,['c++'] +830414,building a dynamic json response in mvc 5 how to tack on properties to a result set i am returning an array of objects to a page that renders a slideshow based on a photo albumi fetch my pictures from the databasebefore i return this array as a result i would like to tack on a thumbnail url property this property does not exist on the albumpicture but i want it in the responsethis illustrates the idealistalbumpicture pics dbalbumpictureswherep palbumid albumidorderbyp prankordertolistforeachalbumpicture p in pics paddpropertythatdoesntexistthumbnail thumbmanagergetthumbpidreturn jsonpics jsonrequestbehaviorallowgetwhat is the most elegant way to add this json field to my result setthis question is so basic that it is probably a duplicate however i googled for 10 minutes and could only find janky solutions that depend on 3rd party libraries i am interested in the current best practicepossible duplicate of how to add dynamically more properties to json response from the controller however that answer will make the dynamically added fields uncles instead of siblings to my albumpicture properties in the resulting json,['c#'] +830449,why fputs and fprintf reverse stream order i do not get it why fputs and fprintf reverse stream orderint fputs const char str file streamint fprintf file stream const char format ssize t writeint fd const void buf size t counti known fprintf put stream in forward to support variable argumentsbut why fputs series do not keep consistency,['c'] +830510,access control list to manage database column that are fetched i have a site built in codeigniter for which i have designed an access control list to manage permissions of different types of users various users logged in to site are super adminadminseo userdevelopernow i have completed the access control for this and permission for add update list and delete can be assigned to every user through a module accessible to super adminnow this is a part of clients new requirement i want to make the columns accessible to certain users egif a table products has 4 columns products id products price status1 prod1 200 1 2 prod2 356 0now i want that for seo users column price does not show up during the listingnote this is just an example i need to make this dynamic so admin controls who has permission to which column i cannot simply write if else logic in my view file to exclude unwanted columnsplease tell me how i can do this without redesign the whole system or making very major changes,"['php', 'mysql']" +830513,how to use mapreduce to bulk update datastore entities that satisfy a query i want to use the mapreduce library to update all entities that satisfy a query there are a couple of complicationsthe query that finds the entities to update checks if the value of aparticular property property1 is contained in a long list of values 10entries from a csv filefor each entity satisfying the query another property property2 needs to be updated to be equal to the value in the second column and same row of the csv filei know how to upload the csv file to blobstore and read each row using a blobstore input reader i am also aware of the datastore input reader that gets entities using a querymy question is how can i create a mapper class that reads input data from the blobstore fetches the datastore entities and updates them as efficiently as possible,['java'] +830614,hangfire dependency injection lifetime scope i am rewriting this entire question because i realize the cause but still need a solutioni have a recurring job in hangfire that runs every minute and check the database possibly updates some stuff then exitsi inject my dbcontext into the class containing the job method i register this dbcontext to get injected using the followingbuilderregistertypeapplicationdbcontextasapplicationdbcontextinstanceperlifetimescopehowever it seems that hangfire does not create a seperate lifetime scope every time the job runs because the constructor only gets called once although the job method gets called every minutethis causes issues for me if the user updates some values in the database dbcontext gets injected somewhere else and used to update values the context still being used hangfire starts returning outdated values that have already been changed,['c#'] +830668,why does the new c standard use isoiec 148822015 according to the iso web site the new standard is named isoiec 148822015 rather than isoiec 148822014 why is that so and will that change there are alreadly lots of things tagged c14 for examplein case you are interested in the technical content rather than the standards document it is available from github from the iso c repository as n4140,['c++'] +830712,scrapy only follow internal urls but extract all links found i want to get all external links from a given website using scrapy using the following code the spider crawls external links as wellfrom scrapycontribspiders import crawlspider rulefrom scrapycontriblinkextractors import linkextractorfrom myprojectitems import someitemclass somespidercrawlspider name crawltest allowed domains someurlcom start urls rules rule linkextractor callbackparse obj followtrue def parse objselfresponse item someitem itemurl responseurl return itemwhat am i missing does not allowed domains prevent the external links to be crawled if i set allow domains for linkextractor it does not extract the external links just to clarify i want to crawl internal links but extract external links any help appriciated,['python'] +830758,gradle exclude or add reference for jar file hard included inside library classesjar i am running into some trouble with a library i included into my project at the begging it was just a conflicting dependencies issue that i resolved by excluding supportv4 which is the commonly shared module the problem is that one of those lbslibrelease seems to have been built with a plain jar file inside of the root project before the developer build by running gradlew appdependencies i verified that the dependency is not referenced in the build graphand i found this supportv4 embedded into the classesjar located at appbuildintermeditesexplodedaarmyqandroidlbslibreleaseunspecifiedclassesjar as you can see on the picture below i cannot rebuild the project myself because it is not an opensourced lib so there is two problem if i add compile comandroidsupportsupportv4180 to the buildgradle a multiple dex file error is thrown at build time so the library is referenced twiceunexpected toplevel exception comandroiddexdexexception multiple dex files define landroidsupportv4appbackstackstate at comandroiddxmergedexmergerreadsortabletypesdexmergerjava596 at comandroiddxmergedexmergergetsortedtypesdexmergerjava554 at comandroiddxmergedexmergermergeclassdefsdexmergerjava535 at comandroiddxmergedexmergermergedexesdexmergerjava171 at comandroiddxmergedexmergermergedexmergerjava189 at comandroiddxcommanddexermainmergelibrarydexbuffersmainjava454 at comandroiddxcommanddexermainrunmonodexmainjava303 at comandroiddxcommanddexermainrunmainjava246 at comandroiddxcommanddexermainmainmainjava215 at comandroiddxcommandmainmainmainjava106if i remove all libs which requires supportv4 it throws a missing dependencies error at the application runtimeso i would like to know if it is possible to exclude this jar file from the build or to make the others libs depends on the lbslibrelease embedded supportv4 jarcompile projectlbslibrelease exclude module supportv4compile comsothreeslidinguppanellibrary204 exclude module supportv4compilecomgoogleandroidgmsplayservices6587 exclude module supportv4thanks in advance for your answers,['android'] +830807,how to send cookies with casperjs i think that every request that i send is being sent without cookies when i listen to the onresourcerequested event like thisthispageonresourcerequested functionrequest utilsdumprequestand every request has the same form of headersheaders name useragent value mozilla50 x11 linux x86 64 applewebkit53736 khtml like gecko chrome390217195 safari53736 name accept value textcssq01 name referer value httpssome sitecompage i never get a header with the cookies that are supposed to be therewhen i try to look at the cookies i run thisutilsdumpthispagecookiesi get a list of many cookies entriesi think this giving me some errors on my scraping scriptyour thoughtsthanksediti try to make a post request to download a filei can log into the site browse to a few pages get to the download page but then when i send the request i get a message error to register with the the site you have to enable your browser to accept cookiesthis is why it is confusing i can log in and browse the site so i must have some cookies passed around but i cannot download so i might not have a cookie here,['javascript'] +830832,check if two instances of instant are on the same date in java 8 i have two instances of the instant class from javatime such as thisinstant instant1 instantnowinstant instant2 instantnowplus5 chronounithoursnow i would like to check if the two instances of instant are actually on the same date day month and year match easy i thought let us just use the shiny new localdate and the universal from static methodlocaldate localdate1 localdatefrominstant1localdate localdate2 localdatefrominstant2if localdate1equalslocaldate2 all the awesomeexcept that universal from method is not so universal and java complains at runtime with an exceptionjavatimedatetimeexception unable to obtain localdate from temporalaccessor 20141104t181812z of type javatimeinstantwhich leaves me back at square 1what is the recommendedfastest way check if two instances of instant actually have the same date have the same day month and year,['java'] +830909,default activity not found for a wearable app created with android studio template i have created a wear app and used the android studio template to create it and have not made any changes other than to drag and drop a button onto the mainactivity of the wear appwhen i try and run the watch app in the rundebug configurations is launch default activity is ticked then there is an error message saying error default activity not foundi have searched for previous posting on this and the answer is messing around with module sources and stuff is that really the correct solution in this situation if so then why is not the android studio setting everything up correctly in the first place after all the project was created by an as template why is not the template setting things up correctlyif its not applicable then how do i get the watch app to execute and launch its activity when executed directly using studiostudio version 102,['android'] +830913,why does not stdweak ptr have operator it could be implemented thusly stdshared ptrt operator auto shared lock ifshared nullptr throw stdbad weak ptr or some other exception return shared live demowhy did the authors of weak ptr decide to not have operator they must have thought of iti can think of potential reasons but i wonder what the official reason is if one exists potential reasonsthiscourage extra incrementdecrement of reference count for multiple callsencourage explicit locking rather than somewhat hidden exceptionsif you are confused about the lifetime of the returned shared ptr see this paperalso someone asked why would one use a weak ptr if you expect it to not be expired answer cycles,['c++'] +830916,svg with widthheight does not scale on ie91011 there is a known issue with ie 91011 where if you have an svg file where the svg element specifies a width and height and then you scale the svg image using the width and height attributes of an img tag ie does not properly scale the imagei have run into this issue i have a series of svg flag icons for the us flag icon the svg object is written assvg xmlns xmlnsxlink height480 width640 elements to draw flag svgand heres the full source for the svgi insert the svg into an html document with an img tag and downscale it to 20x15on chrome 39 the svg is rendered properly like sobut on ie10 it renders as followsso what seems to be happening here is that even though ie10 sizes the img element to 20x15 it does not downscale the svg so we end up seeing just the topleft corner of the flag icon which appears as a plain blue boxokay so this seems to be a known issue with documented solutions one solution is to simply remove all the width and height attributes in the svg file this seems a bit dangerous as i do not want to screw up the actual designs it is also a bit cumbersome to do if you have a lot of svg files requiring more scripts to process the filesa nicer solution is to use css to specifically target svg elements in ie10 which apparently is possible using a vendor specific media querymedia screen and mshighcontrast active mshighcontrast none imgsrcsvg width 100 okay but i do not understand this solution when i try the above ie10 simply expands the size of the svg to fill the entire parent container which is not what i want okay so maybe i can force ie to scale the svg by setting the svg width to 100 but then constraining the size of the parent container so i wrapped the img in a div with a width and height of 20x15 but that just resulted in the same problem as before the container div is fixed at 20x15 but the svg does not shrink so all we end up with is the topleft blue corner of the flag as before so i am probably just not understanding something about this solution how can i get ie1011 to scale the flag icon down to 20x15,"['html', 'css']" +830922,how to go from xml spring scheduling configuration to annotationcode configuration i am trying to convert the following spring task xml configuration to a purely codeannotation based versiontaskexecutor idxyzexecutor poolsizexyzjobexecutorpoolsize140 queuecapacityxyzjobexecutorqueuecapacity0 rejectionpolicycaller runstaskscheduler idxyzscheduler pool sizexyzjobschedulerpoolsize4 taskannotationdriven executorxyzexecutor schedulerxyzscheduler bean idxyzprocessor classxyzqueueingqueueprocessor taskscheduledtasks schedulerxyzscheduler taskscheduled refpartitioner methodcreatepartitions cronxyzjobpartitionerinterval0 0 3 taskscheduledtasksper the spring spec 2841 they say that to go from xml like thistaskannotationdriven executormyexecutor schedulermyschedulertaskexecutor idmyexecutor poolsize5taskscheduler idmyscheduler poolsize10to code configuration is as simply as enabling either enablescheduling andor enableasynchowever i do not see anywhere i can actually instantiate the scheduler the javadoc for enablescheduling shows how i can get plug in my own created executor though i am not exactly sure what class it should be i still want to be able to control the pool size queue capacity and rejection policy it also shows how i can schedule my createpartitions method using the configuretasks override however i would like to be able to name my scheduler so i can identify its threads and control its pool sizeso i wish to know these things1 what class can i use to set the executor fields that the xml has2 is there a way to create a scheduler instance that i can control the name and pool size of,['java'] +830924,custom symfony2 filter not triggering with custom twig tag tldr adding typeapplicationdart makes assetic ignore the filter flag filtermycustomfilterremoving the latter attribute type triggers filtermycustomfilter just fine but i need the filter and the attribute how do i make assetic trigger my custom filter while having the typeapplicationdart attributei believe part of the problem is that it only accepts typeapplicationjavascript or an empty html type attribute for the filter to trigger i am not sure where to go from herefull detailsi want to make a tag similar to javascripts but for dart files darts acmebundleresourcesdartacmemainwebmaindart script typeapplicationdart src asset url script enddarts i want to be able to use the notation instead of bundlesetcafter a bit of searching i tried the followingi extended symfonybundleasseticbundletwigasseticextensioni inherited the following functionpublic function gettokenparsers return array thiscreatetokenparserjavascripts jsjs thiscreatetokenparserstylesheets csscss thiscreatetokenparserimage images true in my own child class i added to the parent array thiscreatetokenparserdarts dartdartinitially this works when i have darts mybundlemaindart filtermycustomfilter script src asset url scripthowever the bootloader dartjs requires as typeapplicationdart attribute in order for the bootstrap to workas soon as i add the required attribute editing the source file does not recompile it is pretty much ignored the following code is ignored and does not trigger mycustomfilter filter darts mybundlemaindart filtermycustomfilter script typeapplicationdart src asset url scripti cannot seem to find where to go next from here seeing how it all works is pretty overwhelming in itself i only need it to recognize typeapplicationdart as valid so that my mycustomfilter gets triggered,['php'] +830993,how does const modifier for member functions affect overload resolution i have the following test codeinclude stringinclude iostreamclass cstringpublic cstringchar const class testbedpublic void comparisoncstring const stdcout cstring overload stdendl void comparisonstdstring const stdcout stdstring overload stdendl int main testbed tb tbcomparisonhello worldthis code fails to compile because the call to comparison is ambiguous i expect this behaviorhowever when i make either of the comparison overloads const as in void comparisonstdstring const const or void comparisoncstring const const but not both the code compiles and chooses the nonconst overloadoverload resolution rules are pretty complex and i have not seen anything that describes how const affects this situation my understanding isfunction with exact matching argument is chosen first1level implicit conversion is tried nextin both cases 1 2 are ambiguous can someone explain this thanks,['c++'] +831008,uicollisionbehavior views pass through boundaries as part of implementing a uicollisionbehaviour i set up boundaries for the screen edgei then added some views and finally attached a uipangesturerecognizer to one of themnow i can push around the smaller views with my draggable viewproblemif i corner a smaller view and keep pushing it against the screen edge it will eventually slip past the boundary and get trapped on the other side my hammer view that i use to hit and push the other views around with will also get caught in the boundaries ie it gets stuckundraggable against the side of the screeni did a very small example to see if i could reproduce it when i had very few views and no conflicting behaviours views still go through the boundaries either uidynamics cannot handle very much or more likely i am somehow configuring it wrongthe small example below has the weird behaviourclass viewcontroller uiviewcontroller var animator uidynamicanimatorvar collisionbehaviour uicollisionbehaviorvar panbehaviour uiattachmentbehavioroverride func viewdidload superviewdidloadoverride func viewwillappearanimated bool superviewwillappearanimated setupfunc setup setup collisionbehaviour and animator collisionbehaviour uicollisionbehavior collisionbehaviourcollisionmode uicollisionbehaviormodeallzeros animator uidynamicanimatorreferenceview view add boundaries collisionbehaviouraddboundarywithidentifierverticalmin frompoint cgpointmake0 0 topoint cgpointmake0 cgrectgetheightviewframe collisionbehaviouraddboundarywithidentifierverticalmax frompoint cgpointmakecgrectgetmaxxviewframe 0 topoint cgpointmakecgrectgetmaxxviewframe cgrectgetheightviewframe collisionbehaviouraddboundarywithidentifierhorizontalmin frompoint cgpointmake0 cgrectgetmaxyviewframe topoint cgpointmakecgrectgetmaxxviewframe cgrectgetmaxyviewframe collisionbehaviouraddboundarywithidentifierhorizontalmax frompoint cgpointmake0 0 topoint cgpointmakecgrectgetmaxxviewframe 0 collisionbehaviourtranslatesreferenceboundsintoboundary true same effect as the above boundaries setup up some round views to push around for i in 05 let ball uiviewframe cgrectmake0 30 50 50 ballcenter viewcenter ballbackgroundcolor uicolorgreencolor balayercornerradius cgrectgetwidthballframe 05 viewaddsubviewball collisionbehaviouradditemball setup a hammer view which can be dragged and used to squeze the ball views of the screen let hammer uiviewframe cgrectmake0 0 100 100 hammerbackgroundcolor uicolorredcolor viewaddsubviewhammer collisionbehaviouradditemhammer let norotationbehaviour uidynamicitembehavioritems hammer norotationbehaviourallowsrotation false animatoraddbehaviornorotationbehaviour let pangesturerecognizer uipangesturerecognizertarget self action selectorhandlepan hammeraddgesturerecognizerpangesturerecognizer start the collision detection animatoraddbehaviorcollisionbehaviourmove the hammer aroundfunc handlepanrecognizer uipangesturerecognizer if let view recognizerview let location recognizerlocationinviewselfview switch recognizerstate case began panbehaviour uiattachmentbehavioritem view attachedtoanchor location animatoraddbehaviorpanbehaviour printlnbegin case changed panbehaviouranchorpoint location printlnchange location case ended printlnended animatorremovebehaviorpanbehaviour default printlndone override func didreceivememorywarning superdidreceivememorywarning thispose of any resources that can be recreatedthanks for any help given,['ios'] +831032,android program flow control in presence of startactivityforresult call the program in question when run on android controls slave bluetooth bt devices it has few buttons which enable different functions of the peer devicesbluetooth is not enabled by default on the android device and the connection is established for short periods after buttons clickso the flow after each button click isensure bt enabled startactivityforresult with bt enable intent if notconnect to the remote deviceenable some function of the remote devicethisconnect from the devicemy issue is that if bt is not enabled then a call to startactivityforresult in 1 breaks the program flow later when onactivityresult is called i want to resume the flow from the point where it was breakedfor that purpose i defined additional member field and few constants and used them in onactivityresultprivate int mrerunmethodindex 0private static final int rerun method1 1private static final inr rerun method2 2public void onactivityresultint requestcode int resultcode intent data switch requestcode case request enable bt if resultcode activityresult ok int rerunmethodindex mrerunmethodindex mrerunmethodindex 0 switch rerunmethodindex case rerun method1 method1 break case rerun method2 method2 break the same for other cases break default break now one more complication onactivityresult will be called before activitys onresume this will matter if any of the methodx need to alter views hierarchy in my case these methods replace some fragments and if this operation is executed from onactivityresult then exception is thrownin order to resolve this additional issue the ugly switch from onactivityresult migrates to onpostresumethe approach described above works but it is one of the ugliest pieces of code i have ever written methodx registers itself for rerun by assigning rerun method x constant to mrerunmethodindex onactivityresults sets some rerun flag after bt is enabled onpostresume checks the flag clears this flag clears mrerunmethodindex and reruns the appropriate methodxis there a more elegant approach preferably confined to 1 or 2 methods,['android'] +831234,how to patch a single field using django rest framework i have a model mymodel with many fields and i would like to update a field status using patch method i am using class based views is there any way to implement patch,['python'] +831242,integrate visual studio online git repository to android studio 102 i am using visual studio online for my development process and i want to integrate my android studio 102 codes in it however as i know android studio has no tfs plugin that is why i want to use git for source controlhow can i integrate visual studio online git repository to android studio 102 what are the steps that should i follow,['android'] +831309,trigger google analytics event when form is valid in django i have one form on my site that other forms uses as base and are on different urls but they all do the same job creating usersi was thinking pythondjango could push a specific event to google analytics when the form is validclass formbaseformview def form validself form push to google analytics gaqpush setaccount ua123451 gaqpush trackpageview homelandingpage return superformbase selfform validformis this possible would there be any caveats of doing it server side apposed to client side javascript,['python'] +831319,generate javadocs android studio is there any way to generate javadoc in android studio in a similar way it is done in eclipse where i just go to project generate java docs i mean export it as html page i cannot find a similar option in android studio i searched multiple posts and i cannot find an answer,['android'] +831478,kotlin incremental compilation with gradle in the m9 announcement it was said that incremental compilation is now supported does this also work with gradle especially android if yes how to enable it,['android'] +831551,calling a bean annotated method in spring java configuration i am curious about how spring injection handles calling methods with the bean annotation if i put a bean annotation on a method and return an instance i understand that that tells spring to create a bean by calling the method and getting the returned instance however sometimes that bean has to be used to wire other beans or setup other code the usual way this is done is to call the bean annotated method to get an instance my question is why does not this cause there to be multiple instances of the bean floating aroundfor example see the code below taken from another question the entrypoint method is annotated with bean so i would imagine spring will create a new instance of basicauthenticationentrypoint as a bean then we call entrypoint again in the configure block but it seems like entrypoint returns the bean instance and is not called multiple times i tried logging and only got one log entry potentially we could call entrypoint multiple times in other parts of the configuration and we would always get the same instance is my understanding of this correct does spring do some magical rewriting of methods annotated with beanbeanpublic basicauthenticationentrypoint entrypoint basicauthenticationentrypoint basicauthentrypoint new basicauthenticationentrypoint basicauthentrypointsetrealmnamemy realm return basicauthentrypointoverrideprotected void configurehttpsecurity http throws exception http exceptionhandling authenticationentrypointentrypoint and authorizeurls anyrequestauthenticated and httpbasic,['java'] +831621,template for directive must have exactly one root element i am new to angularjs i am trying to create new directive which contains input element and a button i want to use this directive to clear input text when button is clickedwhen i use my directive in html i am getting below error error compiletplrt template for directive cwclearableinput must have exactly one root element htmldiv classinputgroup cwclearableinput ngmodelattributenamecwclearableinput divclearable inputjsangularmodulecwuidirectivecwclearableinput function return restrict eac require ngmodel transclude true replace true template input typetext classformcontrolspan classinputgroupbtnbutton typebutton classbtn ngclick titleeditspan classglyphiconpencilspanbuttonspan controller function scope i am not able to figure it out how to achieve this,['javascript'] +831672,percentage padding behaves unexpectedly in firefox i am experiencing strange behavior in firefox v35 v39 regarding percentage padding i cannot reproduce this issue in chromei have an element with top padding set as a percentage like thisp padding10 0 0 margin0 0 1em backgroundcolorcpercentage padding on an element is relative to its parents width so i expect that the padding at the top of the element will grow as the windows width is enlarged this is indeed the result for my simple p taghowever when that element is floated or has width the percentage padding does not behave as expected when the window is resized the padding is calculated correctly upon load but as the window is resized the total height of elements that are floated or have width seems to remain the same text in the element is inexplicably placed at the bottom of an area that gets mysterious height this happens for elements like thisp padding10 0 0 margin0 0 1em backgroundcolorc floatleftp padding10 0 0 margin0 0 1em backgroundcolorc width150pxhere is an image to illustrate what i am seeing color coding is added by firebug purple is padding yellow is margin and blue is the content of the elementwhat causes this inconsistency can anyone else reproduce this issue in firefox or any other browserheres a fiddle to demonstrate in firefox try expanding or contracting the result pane to see the elements resizei have not added a runnable code snippet as i could not find an easy way of resizing the snippet area ontheflyi have added a stack snippet to demonstrate the issue use the full page button so you can stretch the windows widthhtmlbody margin 0divcontainer width 100p padding 10 0 0 margin 0 0 1em backgroundcolor cpwidth limited width 150pxpfloated float leftdiv idcontainer pnormalp p classfloatedfloatedp div styleclearbothheight0div p classwidth limitedhas widthpdiv,['css'] +831690,how to convert java 8 mapremove to java 16 i have the following fruitmapremovefruitid fruitpropertiesthe fruitmap isprivate mapfruitid fruitproperties fruitmap new hashmapfruitid fruitpropertieswhen i attempt to build my code i get aerrorthe method removeobject in the type mapmyimplementationfruitid fruitpropertiesis not applicable for the arguments mapmyimplementationfruitid fruitpropertieswhat is the issuenote that thiis call is inside of a method removefruit inside my fruitimplementation class,['java'] +831708,numpy record array or structured array or recarray what if any is the difference between a numpy structured array a record array and a recarraythe numpy docs imply that the first two are the same if they are which is the prefered term for this objectthe same documentation says at the bottom of the pageyou can find some more information on recarrays and structured arrays including the difference between the two here is there a simple explanation of this difference,['python'] +831839,how to use inputaccessoryviewcontroller in ios 8 in ios 8 apple introduced a new property under uiresponder called inputaccessoryviewcontroller however there has been no documentation explaining how one can use it moreover in ios 8 setting the inputaccessoryview property of a uiviewcontroller subclass and making the subclass the first responder seems to cause the view controller to leak my question is how can i use an inputaccessoryviewcontroller in a uiviewcontroller subclass does that solve the memory leak problem,"['ios', 'objective-c']" +831909,qpython or kivy for android programming with python producing installable apk having read several qas on so i realize that one has 2 options ie qpython and kivy to do programming for android however apparently both take different approaches i am trying to validate my understanding and see if i am missing some key piece of informationqpython allows usage of kivy library for developing graphical applicationsqpython and kivy both use sl4a while qpython has expanded standard sl4a or it is bindings for python by adding some nfc and similar functionsqpython is used to create python scripts that can use wide range of modules libraries but they need qpython installed to be executed on target device there is no way to package script into an apkkivy otoh allows developer to write applications that compile to apk using their cloud based build system alternative local build system can be set up on ubuntu linux however i noticed that most of the sample apks that use kivy are pretty large in the 40mb range did i miss anything qpython apk has 2 version ie one for python27 and another one for python3x for kivy i am not sure which version it isqpython example script helloworldpy does not seem to behave as expected from latest qpython3x from market on an android kitkat 442 system i get the dialog to enter text but then i expect a toast to popup but nothing happensget the impression that both qpython and kivy are developed by a single developer each or only one person is really active at present and do not yet have a biggish community this is my biggest concern i notice that there are 34 questions with qpython tag on so and more than thousand with kivyalso get the impression that at this moment kivy development is somewhat more active perhaps quite active but for qpython i do not have a clear picturekivy seems to be trying to expand the nature of application that could possibly be written using it compare to qpython there are apis like plyer and pyjnius that help expand the possibilities perhaps quite significantly compared to qpythonboth qpython and kivy seem to be heavily under development program script crashes failures seem to be reported on both set of toolsoverall the opinion as a result of above points appears to swing in favour of kivy a bit more is the understanding correct did i miss any crucial point this is not a rhetorical question and i am looking for factual answers only,"['android', 'python']" +831973,if an nxm multiplication table is put in order what is number in the middle if i have a multiplication table sized for example 3x51 2 3 4 52 4 6 8 103 6 9 12 15and i put all these numbers in order1 2 2 3 3 4 4 5 6 6 8 9 10 12 15what is the number in the middle in this case it is 5n and m are always odd so there can be only one answeris there a fast solution for this i am looking for something among the lines of on log nmthis is homework of sorts but i am really lost with this one i have come up with some ideas but they all had some shortcomingspublic class table public static void mainstring ar scanner scanner new scannersystemin int w scannernextint int h scannernextint int s new intw h 1 for int i 1 i w i for int j 1 j h j si j si j 1 int sum 0 for int i 0 i slength i sum si if sum slength 2 systemoutprintlni break this solves most of the tests fast enough 4s but for big and and m the memory limits are exceeded i do not know the exact limitationsthe idea is to keep track of the occurrences of each number and then iterate through all the numbers in order adding the number of occurrences each iteration when the number of occurrences is higher or equal to w h 2 it is the number in the middle and we print itpublic class table public static void mainstring ar scanner scanner new scannersystemin int w scannernextint int h scannernextint int sum 0 for int i 1 i w h i for int j 1 j mathsqrti j if i j 0 int k i j if k w k j sum if k h k j sum if k w k h k j sum if sum w h 1 2 systemoutprintlni break trying to overcome the memory limits i tried counting the occurrences of each number up to the middle one as they come i noticed that the number of occurrences in a multiplication table of each number is the number of factors they havenot fast enoughcan anyone come up with any pointers i know that in the suggested on log nm solution binary search is used1 and 1051 m 105solutionok so thanks to peterderivaz i was able to find and implement a solution for my problem the idea is as he describes it and heres the actual implementation public class kertotaulu public static void mainstring ar scanner scanner new scannersystemin long h scannernextlong long w scannernextlong long min 1 long max wh long mid 0 while min max mid min max 2 long sum 0 for int i 1 i h i sum mathminmid i w sum if sum w h 2 min mid 1 else if sum w h 2 max mid 1 else break long sum 0 for int i 1 i h i sum mathminmid 1 i w sum if sum w h 2 systemoutprintlnmid 1 else systemoutprintlnmid,['java'] +832033,sudo pip install django so this is my first attempt at trying to install django and when i ran it it successfully installed django173 but i received these warnings below i was not able to find any information about it online so i was hoping someone could clarify what they mean if i need to fix them and how i could go about doing that thanks below is the output from my terminalmacbook asif sudo pip install djangopasswordthe directory usersasiflibrarylogspip or its parent directory is not owned by the current user and the debug log has been thisabled please check the permissions and owner of that directory if executing pip with sudo you may want the h flagthe directory usersasiflibrarycachespiphttp or its parent directory is not owned by the current user and the cache has been thisabled please check the permissions and owner of that directory if executing pip with sudo you may want the h flagthe directory usersasiflibrarycachespiphttp or its parent directory is not owned by the current user and the cache has been thisabled please check the permissions and owner of that directory if executing pip with sudo you may want the h flagcollecting django downloading django173py2py3noneanywhl 74mb 100 74mb 23mbs installing collected packages djangosuccessfully installed django173enter code here,['python'] +832105,android mediaplayer persistent cache using exoplayer i would like to implement a persistent cache for streamed audio data in my appi have scoured the internets and looked at the few existing solutions most of them require you to create a local proxy which writes the data to cache as well as serving it to androids builtin mediaplayeri finally came across googles exoplayer which appears to do exactly what i want it to i believe in order to create the cache i need to use cachedatasource however i cannot figure out how to use iti have been through the google documentation and demo app but they do not provide much info about caching at allcould anybody help me out and provide an example,['android'] +832125,detecting integral overflow with scanf when recently answering another question i thiscovered a problem with code likeint nscanf d nwith strtol you can detect overflow because in that case the maximum value allowed is inserted into n and errno is set to indicate the overflow as per c11 72214 the strtol strtoll strtoul and strtoull functions 8if the correct value is outside the range of representable values long min long max llong min llong max ulong max or ullong max is returned according to the return type and sign of the value if any and the value of the macro erange is stored in errnohowever in the sections of the standard dealing with scanf specifically c11 72162 the fscanf function 10 we seeif this object does not have an appropriate type or if the result of the conversion cannot be represented in the object the behavior is undefinednow to me that means any value can be returned and there is no mention of errno being set to anything this came to light because the asker of the linked question above was entering 9 into a 32bit int and getting back 1410065407 a value 233 too small indicating it had simply wrapped around at the limit of the typewhen i tried it i got back 2147483647 the largest possible 32bit unsigned valueso my question is as follows how do you detect integral overflow in a portable way when using the scanf family of functions is it even possiblenow i should mention that on my system debian 7 errno is actually set to erange in these circumstances but i can find nothing in the standard that mandates this additionally the return value from scanf is 1 indicating success in scanning the item,['c'] +832130,how to to make a file private by securing the url that only authenticated users can see i was wondering if there is a way to secure an image or a file to be hidden when it is not authenticatedsuppose there is an image in my website which can only be seen if that user is authenticated but the thing is i can copy the url or open the image in the new tab files1421499811 82 chrysanthemumjpgand again even if i am not authenticated i can view that particular image by going to that url so my question is or my problem is how do i secure the files so that only authenticated users will see i hope i was clear if not please ask i will really appreciate if you could help me and if possible in a pythonicdjango way thank youupdateviewdef picturesrequest user id user userobjectsgetiduser id all userphoto setall return renderrequest pictureshtml pictures all modelsdef get upload file nameinstance filename return uploaded filess s strtimereplace filenameclass photomodelsmodel photo privacy modelscharfieldmax length1choicesprivacy defaultf user modelsforeignkeyuser image modelsimagefieldupload toget upload file namesettingsif debug media url media static root ospathjoinospathdirnamebase dir myproject static staticonly media root ospathjoinospathdirnamebase dir myproject static media staticfiles dirs ospathjoinospathdirnamebase dir myproject static static updatetemplate if pictures for photo in pictures img srcmedia photoimage width300 alt photocaption endfor else pyou have no picturep endif urlurlrpuser namewphotos picturesviewsphotos namephotosif settingsdebug urlpatterns staticsettingsstatic url document rootsettingsstatic root urlpatterns staticsettingsmedia url document rootsettingsmedia root,['python'] +832182,get weekdaydayofweek for datetime column of dataframe i have a dataframe df like the following excerpt timestamp are the indextimestamp value20120601 0 10020120601 001500 15020120601 0030 12020120601 010 22020120601 011500 80and so oni need a new column dfweekday with the respective weekdaydayofweek of the timestampshow can i get this,['python'] +832218,javalangnosuchmethoderror orgspringframeworkbeansfactorysupportdefaultlistablebeanfactorygetdependencycomparatorljavautilcomparator i am trying add spring security to my project i am using spring 4 and i would like to use spring security 32 i have problem with configurationthis is my exceptioncaused by javalangruntimeexception orgspringframeworkbeansfactorybeandefinitionstoreexception unexpected exception parsing xml document from servletcontext resource webinfspringrootcontextxml nested exception is javalangnosuchmethoderror orgspringframeworkbeansfactorysupportdefaultlistablebeanfactorygetdependencycomparatorljavautilcomparator caused by orgspringframeworkbeansfactorybeandefinitionstoreexception unexpected exception parsing xml document from servletcontext resource webinfspringrootcontextxml nested exception is javalangnosuchmethoderror orgspringframeworkbeansfactorysupportdefaultlistablebeanfactorygetdependencycomparatorljavautilcomparator caused by javalangnosuchmethoderror orgspringframeworkbeansfactorysupportdefaultlistablebeanfactorygetdependencycomparatorljavautilcomparatorand this is projects dependency treeinfo scanning for projectsinfoinfo info building engineeringprojectweb maven webapp 001snapshotinfo infoinfo mavendependencyplugin28tree defaultcli engineeringprojectweb info compawelengineeringprojectwebwar001snapshotinfo orgaspectjaspectjweaverjar180compileinfo comfasterxmljacksoncorejacksondatabindjar223compileinfo comfasterxmljacksoncorejacksonannotationsjar223compileinfo comfasterxmljacksoncorejacksoncorejar223compileinfo orgspringframeworkspringcontextjar400releasecompileinfo orgspringframeworkspringaopjar400releasecompileinfo orgspringframeworkspringexpressionjar400releasecompileinfo orgspringframeworkspringcorejar400releasecompileinfo commonsloggingcommonsloggingjar1compileinfo orgspringframeworkspringwebmvcjar400releasecompileinfo orgspringframeworkspringwebjar400releasecompileinfo orgspringframeworksecurityspringsecuritywebjar320releasecompileinfo aopallianceaopalliancejar10compileinfo orgspringframeworksecurityspringsecurityconfigjar320releasecompileinfo orgspringframeworksecurityspringsecuritycorejar320releasecompileinfo orgspringframeworkspringormjar400releasecompileinfo orgspringframeworkspringjdbcjar400releasecompileinfo orgspringframeworkspringtxjar400releasecompileinfo orgspringframeworkspringbeansjar400releasecompileinfo orgspringframeworkspringaspectsjar400releasecompileinfo orgspringframeworkspringcontextsupportjar400releasecompileinfo orgaspectjaspectjrtjar174compileinfo orgslf4jslf4japijar175compileinfo orgslf4jjcloverslf4jjar175runtimeinfo orgslf4jslf4jlog4j12jar175runtimeinfo log4jlog4jjar1215runtimeinfo javaxinjectjavaxinjectjar1compileinfo javaxservletservletapijar25providedinfo javaxservletjspjspapijar21providedinfo javaxservletjstljar12compileinfo junitjunitjar47testinfo info build successinfo info total time 1654 sinfo finished at 20150118t1438190100info final memory 13m245minfo,['java'] +832301,spinner graphical bug api 21 i have one spinner in a fragment that have a very annoying graphical glitchthis occurs only on my nexus 5 with api 21i have try to set spinnersetlayertypeviewlayer type software null but the glitch is still presentany ideas,['android'] +832329,how to add regular class lib reference in aspnet 5 and visual studio 2015 ctp according to you should now be able to include regular class libraries to aspnet 5vnext projects when i use the add reference the packageconfig is updated so it looks something like thisframeworks aspnet50 dependencies classlib 100 aspnetcore50 everything looks fine in visual studio and intellisense works but it fails to build i get the cs103 error the name x does not exist in the current context any ideasalso is it supposed to work when targeting core as well,['asp.net'] +832370,how to fade color i would like to fade the color of a pixel out toward white but obviously maintain the same color if i have a pixel 20012040 will adding 10 to each value to make 21013050 make it the same color just lighter or will it change the color entirely for example i know that 100100100 going to 110110110 is a greyscale fade i would like the same with rgb values and i would like to do it numerically as indicated is there an equation to do so,['python'] +832536,chrome stalls request for about a minute i am running an nginx 121 with hhvm 350 in fastcgi modeas the title says chrome stalls the request for a long time after i do the followingopen up my website takes just about 15 secondswait for 2 minutesclick on another link on the menugo get yourself a cup of coffee and wait a biti reproduced this on ie 11 firefox and chrome for androidie 11 no stalling no problems blazing fastfirefox same as chromechrome for android oneplus one no stalling no problems blazing fasti am convinced that my server is not configured wrong since it works on other browsersany help or tips are appreciatedthank you,['php'] +832645,iterating a weakhashmap i am using a weakhashmap concurrently i want to achieve finegrained locking based on an integer parameter if thread a needs to modify a resource identified by integer a and thread b does the same for resource identified by integer b then they need not to be synchronized however if there are two threads using the same resource say thread c is also using a resource identified by integer a then of course thread a and c need to synchronize on the same lockwhen there are no more threads that need the resource with id x then the lock in the map for keyx can be removed however another thread can come in at that moment and try to use the lock in the map for idx so we need global synchronization when addingremoving the lock this would be the only place where every thread must synchronize regardless of the integer parameter but a thread cannot know when to remove the lock because it does not know it is the last thread using the lockthat is why i am using a weakhashmap when the id is no longer used the keyvalue pair can be removed when the gc wants itto make sure i have a strong reference to the key of an already existing entry and exactly that object reference that forms the key of the mapping i need to iterate the keyset of the mapsynchronized mrlocks do other stuff for integer entrykey mrlockskeyset if entrykeyequalsid key entrykey break if keynull no thread has a strong reference to the integer key so no thread is doing work on resource with id so we can add a mapping new integerid new reentrantlock here as we are in a synchronized block we must keep a strong reference to the newly created integer because otherwise the idlock mapping may already have been removed by the time we start using it and then other threads will not use the same lock object for this resourcenow can the content of the map change while iterating it i think not because by calling mrlockskeyset i created a strong reference to all keys for the scope of iteration is that correct,['java'] +832773,html email ios formatdetection i just found that there is a meta tag for removing the phone number as a link in html on ios does this work with html emails meta nameformatdetection contenttelephonenobut is there one for address and date as well i have always been writing hacks to over come this but if it is a meta tag that is great does anyone know the syntax for address and date,['html'] +832783,how to remote compile in qtcreator i am developing an application using qtcreator in mac os x and it must be crossplatform i have a mac os x as host also i have a ms windows installed on virtual machine and a ubuntu installed on another virtual machinemac os x qt 540 64bit clang xcode 60 ms windows qt 530 32bit vc 2013 ubuntu qt 530 64bit gcc how can i develop my application in mac os and build it in another platforms macwindowsubuntu all at onceis there any remote compiler option in qtcreator,['c++'] +832797,wkwebview cookie storage location i am transitioning an app from uiwebview to wkwebview and there is an auto login feature that was handled by saving a cookie with the information that the user was authenticated into nshttpcookiestorage however wkwebview does not seem to look at this location for the cookie and therefore the user is prompted with the login screen every timeis there something i need to activate to have the wkwebview use cookies properly,"['ios', 'objective-c']" +832895,does php have an exposed implementation for abstract interfaces the concept i am thinking of comes from the traversable interface this interface cannot be directly implemented but instead is satisfied by implementing an interface that extends itcan i declare an interface that cannot be implemented and instead extend with public interfacesedit i realize the possibility would be rather pointless as it could be circumvented by a third party creating an interface that could extend the base interface i am looking for a cleaner way to express polymorphismfor exampleabstract interface vehicleinterface car extends vehicle public function driverouteprovider routeprovider speedinterface boat extends vehicle public function sailbodyofwater water headingclass peoplemover public function movevehicle vehicle if vehicle instanceof boat move people across bodies of water elseif vehicle instanceof car move people along roads,['php'] +833030,rxjava fetch every item on the list i have a method that returns an observablearraylistlong which are ids of some items i would like to go through this list and download every item using another method that returns observableitemhow would i do this using rxjava operators,['java'] +833043,in python how can i get the next and previous keyvalue of a particular key in a dictionary okay so this is a little hard to explain but here goesi have a dictionary which i am adding content to the content is a hashed username key with an ip address value i was putting the hashes into an order by running them against base 16 and then using collectionordereddict so the dictionary looked a little like thisd 1234 8 23450 32134 45231 76541337 9127001what i needed was a mechanism that would allow me to pick one of those keys and get the keyvalue item one higher and one lower so for example if i were to pick 2345 the code would return the keyvalue combinations 12348 and 32134so something likefor i in d while i lend if i 2345 print inextitem print ipreviousitem break,['python'] +833053,when does stringsplit return an empty array my logs show this exception arrayindexoutofboundsexception length0 index0 triggered by the following piece of codepublic static string getinitialsfromfullnamestring fullname string splitnames fullnamesplit string firstname splitnames0 here i am trying to figure out the condition for which stringsplit returns an empty array my understanding is that if no match is found an array of size 1 with the original string is returnedthis is java compiled for the android build sdk version 21 i am looking forward to hear what obvious detail i am missing,"['java', 'android']" +833086,sending mail with aspnet vnext in legacy aspnet and net in general sending mail was accomplished via systemnetmail classes which resided in systemdll now with kre vnext does not seem to have systemnetmail as a separate packagereferencing the net453 framework in projectjson frameworks aspnet50 aspnetcore50 net453 throws compilation errorscauses all hell to break loose with errors likenet framework 453 error cs0234 the type or namespace name aspnet does not exist in the namespace microsoft are you missing an assembly referenceit virtually complains about all vnext dependencies that are part of kpm packagesso has anyone figured out a way to send mails using aspnet vnext yetnote even though system appears under references and even though intellisense shows systemnetmail is available for use the code does not compile eg a simple statement like this although appears valid using systemnetmail var m new mailmessagewill throw compilation error such asaspnet core 50 error cs0234 the type or namespace name net does not exist in the namespace system are you missing an assembly referenceaspnet core 50 error cs0246 the type or namespace name mailmessage could not be found are you missing a using directive or an assembly referenceupdate with latest visual studio 2015 ctp 5 they seemed to have fixed the intellisense glitch now systemnet does not have mail namespace anymore on a side note the vnext project i created with vs 2015 preview is no longer working i get an 4033 error on the home page ah the joy of working with beta software,"['c#', '.net']" +833223,creating a drawable zoomable image view in android goalcreate an imageview that is drawable and zoomable that means when i press a button to on it is drawable or when i turn off that is zoomable notice the drawings should zoom align with the imageviewrecently i wrote a custom drawable image view like this public class drawview extends imageview private int color colorblack private float width 4f private listholder holderlist new arraylistholder private class holder path path paint paint holderint color float width path new path paint new paint paintsetantialiastrue paintsetstrokewidthwidth paintsetcolorcolor paintsetstylepaintstylestroke paintsetstrokejoinpaintjoinround paintsetstrokecappaintcapround public drawviewcontext context supercontext init public drawviewcontext context attributeset attrs supercontext attrs init public drawviewcontext context attributeset attrs int defstyle supercontext attrs defstyle init private void init holderlistaddnew holdercolor width override protected void ondrawcanvas canvas superondrawcanvas for holder holder holderlist canvasdrawpathholderpath holderpaint override public boolean ontoucheventmotionevent event float eventx eventgetx float eventy eventgety switch eventgetaction case motioneventaction down holderlistaddnew holdercolorwidth holderlistgetholderlistsize 1pathmovetoeventx eventy return true case motioneventaction move holderlistgetholderlistsize 1pathlinetoeventx eventy break case motioneventaction up break default return false invalidate return true public void resetpaths for holder holder holderlist holderpathreset invalidate public void setbrushcolorint color thiscolor color public void setwidthfloat width thiswidth width and the xml is comexampletooldrawview androidididdraw androidlayout widthmatch parent androidlayout heightmatch parent androidadjustviewboundstrue the problem is how to make it zoomable as well notice that the drawings should align with the imageview when zooming attempt using some custom imageview library but no luckeg when i use photoview it can be zoom but the drawings not align and zoom level will reset after i turn on off the zoomingalso find some other library like that but not fit the custom view caseupdate1 demo recommended to reference this app the drawing function is actually the same as what i am struggling to achieve but i cannot figure out how they get it donehlenthanksupdate2 from sandeep maram sourcethanks a lot sandeep maram after testing the code everything work well the only thing remain is the drawings is not align with the zoom view please take a look at the screenshotbeforeafterthe circle is not scale up down when zoom would be really nice if fix that also that is not matter if the image overlap the button,['android'] +833241,how to debug my app using adbwithout ide android i am using gradle script for building the app in eclipse by using gradle i can run the application to the device by using the script in gradletask runtype exec dependson installdebug def adb systemenvandroid homeplatformtoolsadb commandline adb shell am start n comexamplemultidexprojectmainactivity and it is working fine now i would like to write a task for debugging the app so there is any command for this in adb,['android'] +833595,uitextview is not scrolled to top when loaded when i have text that does not fill the uitextview it is scrolled to the top working as intended when there is more text than will fit on screen the uitextview is scrolled to the middle of the text rather than the tophere are some potentially relevant detailsin viewdidload to give some padding on top and bottom of uitextviewselfmaintextviewtextcontainerinset uiedgeinsetsmake90 0 70 0the uitextview uses auto layout to anchor it 20px from top bottom and each side of the screen done in ib to allow for different screen sizes and orientationsi can still scroll it with my finger once its loadedediti found that removing the auto layout constraints and then fixing the width only seems to fix the issue but only for that screen width,['ios'] +833611,typeid does not work with nonstatic member function clang does not compile the third call to typeid below see live example but i cannot see anything in a528 that thisallows this specially when we consider that the expression bf is not a glvalue of polymorphic class type see paragraph 3 also according to this paragraph the expression bf is an unevaluated operand and as such the call typeidbf should compile note that gcc does not compile any of the calls to typeid belowinclude iostreaminclude typeinfostruct a int i struct b int i void f int main stdcout typeidainame n stdcout typeidbiname n stdcout typeidbfname n,['c++'] +833712,how do you copy and paste into the xamarin android player in the ios emulator i would just in desktop text commandcin emulatorcommandvlong touchthen select pastehowever this does not seem to be an option in the xamarin android emulator,['android'] +833793,why do not small changes in code affect exe file size i am curious sometimes i make changes in my code recompile then copy my exe or dll file over the old version and see windows telling me that the date of the file changed but the size stayed exactly the same why is thatas an example i tested with the following console applicationusing systemusing systemcollectionsgenericusing systemlinqusing systemtextnamespace consoleapplication4 class program static void mainstring args int a 1 int b 2 consolewritelinea b this produced an exe file of 5120 bytes visual studio 2012 debug build then i changed the code to thisusing systemusing systemcollectionsgenericusing systemlinqusing systemtextnamespace consoleapplication4 class program static void mainstring args int a 1 int b 2 int c 3 consolewritelinea b c the size of the exe is exactly the samei look at the thisassembly which is showing a difference in the il code so it cannot be that the difference is optimized awayfirst versionmethod private hidebysig static void mainstring args cil managed entrypoint code size 15 0xf maxstack 2 locals init int32 v 0 int32 v 1 il 0 nop il 01 ldci41 il 02 stloc0 il 03 ldci42 il 04 stloc1 il 05 ldloc0 il 06 ldloc1 il 07 add il 08 call void mscorlibsystemconsolewritelineint32 il 0d nop il 0e ret end of method programmainsecond versionmethod private hidebysig static void mainstring args cil managed entrypoint code size 19 0x13 maxstack 2 locals init 0 int32 a 1 int32 b 2 int32 c il 0 nop il 01 ldci41 il 02 stloc0 il 03 ldci42 il 04 stloc1 il 05 ldci43 il 06 stloc2 il 07 ldloc0 il 08 ldloc1 il 09 add il 0a ldloc2 il 0b add il 0c call void mscorlibsystemconsolewritelineint32 il 0011 nop il 0012 ret end of method programmainif the code is physically bigger how can the files be exactly the same size is this just some random chance it happens to me a lot when making small changes to the code,"['c#', '.net']" +833824,why is stdcout convertible to void if using g why can one cast a stdostream to a void pointer i am not aware of any such conversion operator in stdostream code belowinclude iostreamint main void p stdcout why does this work i am asking this question since i have seen a placement operator new invoked asfoo pfoo new stdcerr fooand have absolutely no idea why would one write such a thingps i am compiling with g 492 with or without stdc11 clang does not accept the codepss found out that due to the so called safe bool problem see nicebytes answer in pre c11 a void conversion operator was defined for stdostream which was then removed in c11 however my code compiles fine in c11 using g more than that clang rejects it no matter what version of the standard i use even with stdc98 although my understanding is that it should accept if compiled as prec11,['c++'] +833859,espresso click a single list view item i tried doing the followingonviewallofwithidridsingle row text withtextitem1performclickbut all i got is androidsupporttestespressonomatchingviewexception no views in hierarchy found matching with id nettestandroididsingle row text and with text is item1if the target view is not part of the view hierarchy you may need to use espressoondata to load it from one of the following adapterviewsandroidwidgetlistview410d6ab0view hierarchydecorviewid1 visibilityvisible width480 height800 hasfocustrue hasfocusabletrue haswindowfocustrue isclickablefalse isenabledtrue isfocusedfalse isfocusablefalse islayoutrequestedfalse isselectedfalse rootislayoutrequestedfalse hasinputconnectionfalse x00 y00 childcount1linearlayoutid1 visibilityvisible width480 height800 hasfocustrue hasfocusabletrue haswindowfocustrue isclickablefalse isenabledtrue isfocusedfalse isfocusablefalse islayoutrequestedfalse isselectedfalse rootislayoutrequestedfalse hasinputconnectionfalse x00 y00 childcount3actionbarcontainerid16909032 resnameaction bar container visibilityvisible width480 height48 hasfocusfalse hasfocusablefalse haswindowfocustrue isclickablefalse isenabledtrue isfocusedfalse isfocusablefalse islayoutrequestedfalse isselectedfalse rootislayoutrequestedfalse hasinputconnectionfalse x00 y480 childcount2actionbarviewid16909033 resnameaction bar visibilityvisible width480 height48 hasfocusfalse hasfocusablefalse haswindowfocustrue isclickablefalse isenabledtrue isfocusedfalse isfocusablefalse islayoutrequestedfalse isselectedfalse rootislayoutrequestedfalse hasinputconnectionfalse x00 y00 childcount3linearlayoutid1 visibilitygone width0 height0 hasfocusfalse hasfocusablefalse haswindowfocustrue isclickabletrue isenabledfalse isfocusedfalse isfocusablefalse islayoutrequestedtrue isselectedfalse rootislayoutrequestedfalse hasinputconnectionfalse x00 y00 childcount2imageviewid16908838 resnameup visibilitygone width0 height0 hasfocusfalse hasfocusablefalse haswindowfocustrue isclickablefalse isenabledtrue isfocusedfalse isfocusablefalse islayoutrequestedtrue isselectedfalse rootislayoutrequestedfalse hasinputconnectionfalse x00 y00linearlayoutid1 visibilityvisible width0 height0 hasfocusfalse hasfocusablefalse haswindowfocustrue isclickablefalse isenabledtrue isfocusedfalse isfocusablefalse islayoutrequestedtrue isselectedfalse rootislayoutrequestedfalse hasinputconnectionfalse x00 y00 childcount2textviewid16908845 resnameaction bar title visibilityvisible width0 height0 hasfocusfalse hasfocusablefalse haswindowfocustrue isclickablefalse isenabledtrue isfocusedfalse isfocusablefalse islayoutrequestedtrue isselectedfalse rootislayoutrequestedfalse hasinputconnectionfalse x00 y00 text inputtype0 imetargetfalse haslinksfalsetextviewid16908846 resnameaction bar subtitle visibilitygone width0 height0 hasfocusfalse hasfocusablefalse haswindowfocustrue isclickablefalse isenabledtrue isfocusedfalse isfocusablefalse islayoutrequestedtrue isselectedfalse rootislayoutrequestedfalse hasinputconnectionfalse x00 y00 text inputtype0 imetargetfalse haslinksfalsehomeviewid1 visibilityvisible width127 height48 hasfocusfalse hasfocusablefalse haswindowfocustrue isclickabletrue isenabledfalse isfocusedfalse isfocusablefalse islayoutrequestedfalse isselectedfalse rootislayoutrequestedfalse hasinputconnectionfalse x190 y00 childcount2imageviewid16908838 resnameup visibilitygone width0 height0 hasfocusfalse hasfocusablefalse haswindowfocustrue isclickablefalse isenabledtrue isfocusedfalse isfocusablefalse islayoutrequestedtrue isselectedfalse rootislayoutrequestedfalse hasinputconnectionfalse x00 y00imageviewid16908332 resnamehome visibilityvisible width119 height25 hasfocusfalse hasfocusablefalse haswindowfocustrue isclickablefalse isenabledtrue isfocusedfalse isfocusablefalse islayoutrequestedfalse isselectedfalse rootislayoutrequestedfalse hasinputconnectionfalse x40 y120actionmenuviewid1 visibilityvisible width0 height0 hasfocusfalse hasfocusablefalse haswindowfocustrue isclickablefalse isenabledtrue isfocusedfalse isfocusablefalse islayoutrequestedfalse isselectedfalse rootislayoutrequestedfalse hasinputconnectionfalse x4800 y240 childcount0actionbarcontextviewid16909034 resnameaction context bar visibilitygone width0 height0 hasfocusfalse hasfocusablefalse haswindowfocustrue isclickablefalse isenabledtrue isfocusedfalse isfocusablefalse islayoutrequestedtrue isselectedfalse rootislayoutrequestedfalse hasinputconnectionfalse x00 y00 childcount0framelayoutid16908290 resnamecontent visibilityvisible width480 height704 hasfocustrue hasfocusabletrue haswindowfocustrue isclickablefalse isenabledtrue isfocusedfalse isfocusablefalse islayoutrequestedfalse isselectedfalse rootislayoutrequestedfalse hasinputconnectionfalse x00 y960 childcount1customdrawerlayoutid2131362153 resnamemain frame visibilityvisible width480 height704 hasfocustrue hasfocusabletrue haswindowfocustrue isclickablefalse isenabledtrue isfocusedtrue isfocusabletrue islayoutrequestedfalse isselectedfalse rootislayoutrequestedfalse hasinputconnectionfalse x00 y00 childcount2framelayoutid2131362154 resnamemain content frame visibilityvisible width480 height704 hasfocusfalse hasfocusablefalse haswindowfocustrue isclickablefalse isenabledtrue isfocusedfalse isfocusablefalse islayoutrequestedfalse isselectedfalse rootislayoutrequestedfalse hasinputconnectionfalse x00 y00 childcount0nosavestateframelayoutid2131362155 resnamemenu fragment visibilityvisible width260 height704 hasfocusfalse hasfocusablefalse haswindowfocustrue isclickablefalse isenabledtrue isfocusedfalse isfocusablefalse islayoutrequestedfalse isselectedfalse rootislayoutrequestedfalse hasinputconnectionfalse x00 y00 childcount1linearlayoutid1 visibilityvisible width260 height704 hasfocusfalse hasfocusablefalse haswindowfocustrue isclickablefalse isenabledtrue isfocusedfalse isfocusablefalse islayoutrequestedfalse isselectedfalse rootislayoutrequestedfalse hasinputconnectionfalse x00 y00 childcount2viewid1 visibilityvisible width260 height1 hasfocusfalse hasfocusablefalse haswindowfocustrue isclickablefalse isenabledtrue isfocusedfalse isfocusablefalse islayoutrequestedfalse isselectedfalse rootislayoutrequestedfalse hasinputconnectionfalse x00 y00listviewid2131362159 resnamebrowse types list visibilityvisible width260 height703 hasfocusfalse hasfocusablefalse haswindowfocustrue isclickabletrue isenabledtrue isfocusedfalse isfocusablefalse islayoutrequestedfalse isselectedfalse rootislayoutrequestedfalse hasinputconnectionfalse x00 y10 childcount0actionbarcontainerid16909035 resnamesplit action bar visibilitygone width0 height0 hasfocusfalse hasfocusablefalse haswindowfocustrue isclickablefalse isenabledtrue isfocusedfalse isfocusablefalse islayoutrequestedtrue isselectedfalse rootislayoutrequestedfalse hasinputconnectionfalse x00 y00 childcount0i also tried a lot of ondata stuff but they are all failondataallofisanytextviewclass withtextitem1performclickondatamatchersallofmatchersismatchersinstanceoflistviewclass matchershastostringmatchersstartswithitem1performviewactionsclickondataanythinginadapterviewwithcontentdescriptionmenu item iconatposition0performclickondatahastostringstartswithitem1 inadapterviewwithidridbrowse types list performclickany suggestions for this thanks solutions updatedit turns out to be a timing issue i run threadsleep50 before executing the test and it worked,['android'] +833936,search by order item sku or id in woocommerce orders admin page what i am trying to do is to be able to search by order item sku or id in the woocommerce orders admin page what i have founddone till now but with no success is the following at functionsphp fileadd filter woocommerce shop order search fields woocommerce shop order search sku function woocommerce shop order search sku search fields args array post type shop order orders new wp queryargsifordershave posts whileordershave posts post ordersthe post order id get the id order new wc orderorder id items orderget items foreachitems as item search order item sku wp get post terms itemproduct id search sku foreachsearch order item sku as search sku add post metaorder id search sku search skusku search fields search skureturn search fieldsi suppose the issue is the value of search sku at the line with the add post meta i have also tried it with get sku itemsku with no luckany suggestions,['php'] +833989,android camera androidhardwarecamera deprecated if androidhardwarecamera is deprecated and you cannot use the variable camera then what would be the alternative to this,['android'] +834239,how to access a json request body of a post request in slim i am just a newbie in the slim framework i have written one api using slim framework a post request is coming to this api from an iphone app this post request is in json format but i am not able to access the post parameters that are sent in a request from iphone when i tried to print the post parameters values i got null for every parameterallpostvars applicationrequestpost always i get nullthen i tried to get the body of a coming request convert the body into json format and sent it back as a response to the iphone then i got the parameters values but they are in very weird format as followspasswordadmin123logindevice typeiphonedevice token785903860i5y1243i5so one thing for sure is post request parameters are coming to this api file though they are not accessible in applicationrequestpost they are coming into request body my first issue is how should i access these post parameters from request body and my second issue is why the request data is getting thisplayed into such a weird format as above after converting the request body into json format following is the necessary code snippetphp require slimslimphp slimslimregisterautoloader instantiate slim class in order to get a reference for the object application new slimslim body applicationrequestgetbody headercontenttype applicationjsonsetting header before sending the json response back to the iphone echo json encodenew body converting the request body into json format and sending it as a response back to the iphone after execution of this step i am getting the above weird format data as a response on iphone die,['php'] +834328,ios different font sizes within single size class for different devices in ios 8 we can design a different ui layout for each size class the issue i am facing is i have designed a layout for compact width and regular height size class for all iphones in portrait but i want to keep font size of labels smaller for 35 and 4 inch devices iphone 4 and 5 then relatively bigger for 47 inch iphone 6 and more bigger for 55 inch iphone 6 plus devices i have searched but unable to find a solution to set different font size for different devices within same size class,['ios'] +834460,managing promise dependencies i am using nodejs and bluebird to create some fairly complicated logic involving uncompressing a structured file parsing json creating and making changes to several mongodb documents and writing related files in multiple locations i also have fairly complicated error handling for all of this depending on the state of the system when an error occurs i am having difficulty thinking of a good way to manage dependencies through the flow of promisesmy existing code basically looks like thisvar dostuff function var dependency1 null var dependency2 null promise1 thenfunction value dependency1 value return promise2 thenfunction value dependency2 value return promise3dependency1 thensuccessfunction catchfunction err cleanupdependingonsystemstateerr dependency1 dependency2 note that dependency1 is not needed until promise3 and that the error handler needs to know about the dependenciesto me this seems like spaghetti code and my actual code is far worse with a lot of parallel control flow i have also read that returning another promise inside of a then callback is an antipattern is there a bettercleaner way of accomplishing what i am trying to do,['javascript'] +834477,images being rotated after imagejob but not wanted i am having an issue with some images being rotated during the processing of imagejobi am having an issue with detecting the correct rotation of an image uploaded from some modern mobile devicesthe images are coming from an ipad mini and a galaxy s5 i am taking portrait pictures but they get rotated after upload and resize if i take a landscape picture the processing works finei have tried using the autorotate plugin but this does not seem to make a differencethe code is basic and works on some images but not others as mentioned above httppostedfilebase file baserequestfilesphoto imageresizerimagejob i new imageresizerimagejobfile origfiles cvmid ext new imageresizerinstructions width768height1024formatjpgmodemaxautorotatetrue icreateparentdirectory true ibuildi emailed the photo from the phone to my laptop and uploaded it and it worked fine which is odd could this be a mobile browser upload issue the problem happens on both ios safari and chrome on new devices what is odd is that on a older first gen nexus 7 portrait images workfurther noteshere is the diagnosticsyou are using plugins from the creative edition thiskcache performance edition watermarkplugin creative editionregistered pluginsimageresizerpluginsbasicdefaultencoderimageresizerpluginsbasicnocacheimageresizerpluginsbasicclientcacheimageresizerpluginsbasicdiagnosticimageresizerpluginsbasicsizelimitingimageresizerpluginsmvcroutingshimmvcroutingshimpluginimageresizerpluginsthiskcachethiskcacheimageresizerpluginswatermarkwatermarkpluginimageresizerpluginsbasicautorotateconfigurationresizer plugins add namemvcroutingshim add namethiskcache add namewatermark add nameautorotate pluginswatermarksotherimages pathwatermarks right20 bottom20 width20 height20 group nameportraitbg image pathportraitpng imagequery top0 left0 text textname verticalfalse aligncenter top818 fontsize60 colorf groupgroup namelandscapebg image pathlandscapepng imagequery top0 left0 text textname verticalfalse left50 top650 fontsize60 colorf groupwatermarksresizersample imagehere is a sample imagesample image 8jpgwhen i download the sample image and upload from my laptop it works saved as portrait when i download it and upload from my phone samsung s5 running 442 it does not work and is saved landscape,['c#'] +834510,how to customize edittext field in android using appcompat v721 i am using the appcompatv7 21 and trying to customize the edittext fieldweird thing is that it is working fine on lollipop but does not work on kitkat or any prelollipop devices i thought support libraries worked on all platformsstyle namemapptheme parentthemeappcompatlightnoactionbar item namecolorprimarycolorcolorprimaryitem item namecolorprimarydarkcolorcolorprimarydarkitem item namecoloraccentcolorcoloraccentitem item namecolorcontrolnormalcolorverylightgreyitem item namecolorcontrolactivatedcolorcoloraccentitem item namecolorcontrolhighlightcolorcoloraccentitemstylecompile comandroidsupportappcompatv72103screenshot from the physical device,['android'] +834878,chartjs hiding series by clicking on legend i am developing a site that uses chartjs wchartjsorgi have to make a line chart that shows multiple series of data that users can hide or show by clicking on the respective legend symbol similar to this azurechartlinechartis there any way to do it with chartjs,['javascript'] +835003,precedence of andor versus method arguments in ruby here are two testsif 1234include 2 nilnil puts helloendandif 1234include2 nilnil puts helloend hellothe above tells me that has higher precedence than method arguments so it logically ands 2 nilnil which is true and passes that as an argument to includehowever there is this testif 1234include 2 and nilnil puts helloend helloso this is telling me that method arguments and and have the same precedence or method args are higher than and since it passed 2 to include before it processed andnote i understand that and and have different precedence the question is not regarding this but regarding and or or vs the arguments to a ruby methodi cannot find documentation that affirms this for instances this does not mention method arguments at all 184 or operatorscould anyone explain this behavior namely in that how does ruby know to pass values as arguments to a method vs process operators,['ruby'] +835018,when is a divide by zero not a divide by zero a puzzle in the debugger static variable issues i am very confused and i think my debugger is lying to me i have the following loop in my codemyclassuploadfilecstring strfile static dword dwlockwaittime engkeygetdworddneng server upload lock wait time dneng server upload lock wait time default static dword dwlockpollinterval engkeygetdworddneng server upload lock poll interval dneng server upload lock poll interval default longlong llreturnedoffset0ll bool blockedfalse for dword sanity 0 sanity 0 status resumable file locked sanity dwlockwaittime dwlockpollinterval sanity this loop has been executed hundreds of times during the course of my program and the two static variables are not changed anywhere in the code they are written to just once when they are statically initialized and read from in the loop conditions and in one other place since they are user settings which are read from the windows registry they almost always have the constant values of dwlockwaittime 60 and dwlockpollinterval 5 so the loop is always doing 60 5 very rarely i get a crash dump which shows that this line of code has thrown a division by zero error i have checked what windbg says and it showsfaulting ip procnamecserveragentresumableupload54a serveragentcpp 725013f72d74a f73570151c00 div eaxdword ptr procdwlockpollinterval 013f8eecc0exception record f exr 0xfexceptionaddress 013f72d74a proccserveragentresumableupload0x054a exceptioncode c094 integer dividebyzero exceptionflags 0numberparameters 0error code ntstatus 0xc094 exception integer division by zeroi have checked the assembler code and it shows that the crash occurred on this div instruction013f72d744 8b0572151c00 mov eaxdword ptr dwlockwaittime 013f8eecbc013f72d74a f73570151c00 div eaxdword ptr dwlockpollinterval 013f8eecc0so as you can see the value at 013f8eecbc was moved into eax and then eax was divided by the value at 013f8eecc0what is at those two values you ask0048 dd 013f8eecbc013f8eecbc 03c 05 01 013f8eec 0 02 0 013f8eecdc 0 7f a9ad25cf 7f013f8eecec a9ad25cf 0 0 013f8eecfc 0 0 0 013f8eed0c 0 0 0 013f8eed1c 0 0 0 013f8eed2c 0 0 0 048 dd 013f8eecc013f8eecc0 05 01 0 013f8eecd0 02 0 0 013f8eece0 7f a9ad25cf 7f a9ad25cf013f8eecf0 0 0 0 013f8eed00 0 0 0 013f8eed10 0 0 0 013f8eed20 0 0 0 013f8eed30 0 0 0 0the constants 60 and 5 exactly as i would expect so wheres the divide by zero is my debugger lying surely the divide by zero has been thrown by the hardware so it cannot have made a mistake about that and if it was a divide by zero in a different place in my code what are the odds that the debugger would show the instruction pointer in exactly this place i confess i am stumped,['c++'] +835119,sass watch is detecting changes but not compiling to css when i run sass watch appsassappcss terminal shows that changes have been detected to sass but would not compile to css i am using bourbon so all my scss and sass files are imported via mixinsex sass is watching for changes press ctrlc to stop change detected to css2modulestopnavscss,['css'] +835226,does repository pattern follow solid principles i am doing some research on solid principal and found some issues in implementations of repository pattern i am going to explain each and every problem please correct me if i am wrong problem 1repository pattern breaks single responsibility principle slet say we have a interface which define as public interface irepositoryt where t ientity ienumerablet list get void addt entity void deletet entity void updatet entity t findbyidint idclearly it violates the single responsibility principle because when we implement this interface in a single class we are putting command and query both and this not expectedproblem 2repository pattern breaks interface segregation principle isay we have 2 implementation of the above interface first implementation customerrepository irepositorycustomer all implementationsecond implementation productrepository irepositoryproduct all implementation except delete method so delete method will be void delete product product throw not implement exception and as per isp no client should be forced to depend on methods it does not use so we saw that clearly it also violates the isp so my understanding is repository pattern does not follow solid principal what do you think why should we choice this type of pattern which violates the principal need your opinion,"['c#', 'asp.net']" +835438,passing member function pointer to the cstyle function i am trying to pass member function pointer to the cstyle function as it is lib in cthe pointer it wants is defined asvoid int const charso the function i am trying to pass isvoid applicationonerrorint error const char descriptioni am trying to pass that with this codesetcallbackbindgameonerror this placeholders 1 placeholders 2this gives me the following errorcannot convert astd bind helperfalse void applicationapplication intconst char application const const std placeholder1 const std placeholder2type aka std bindstd mem fnvoid applicationapplication int const charapplication std placeholder1std placeholder2a to aglfwerrorfun aka void int const chara for argument a1a to avoid glfwseterrorcallbackglfwerrorfunint const charaglfwseterrorcallbackbindapplicationonerror this placeholders 1 placeholders 2is there any way to successfully pass a member function as a bound function to the cstyle function,"['c++', 'c']" +835540,mysqlclient blacklisting server in serverpool is there anything in the net mysqlclient 6950 where when a mysql server in the server pool is not responding possibly due to temporary network issues the server gets blacklisted or bypassed permanently in our logging we notice that an authentication error is thrownmysqldatamysqlclientmysqlexception 0x804005 authentication to host host for user user using method mysql native password failed with message reading from the stream has failed mysqldatamysqlclientmysqlexception 0x804005 reading from the stream has failed systemioendofstreamexception attempted to read past the end of the streamimmediately after this error occurs every attempt to write or read from the database fails with this error messagemysqldatamysqlclientmysqlexception 0x804005 no available server foundany ideas when the db server was moved to be on the same host that our application is running on the problem no longer occurs,"['c#', 'mysql']" +835574,what is the best way to use rethis in a multithreaded rails environment puma sidekiq i am using rethis in my application both for sidekiq queues and for model cachingwhat is the best way to have a rethis connection available to my models considering that the models that will be hitting rethis will be called both from my web application ran via puma and from background jobs inside sidekiqi am currently doing this in my initializersrethiscurrent rethisnewhost localhost port 6379and then simply use rethiscurrentget rethiscurrentset and similar throughout the codethis should be threadsafe as far as i understand since the rethis client only runs one command at a time using a monitornow sidekiq has its own connection pool to rethis and recommends doingsidekiqrethis do conn connget connsetendas i understand it this would be better than the approach of just using rethiscurrent because you do not have multiple workers on multiple threads waiting on each other on a single connection when they hit rethishowever how can i make this connection that i get from sidekiqrethis available to my models without having to pass it around as a parameter in every method calli cannot set rethiscurrent inside that block since it is global and i am back to everyone using the same connection plus switching between them randomly which might even be nonthreadsafeshould i store the connection that i get from sidekiqrethis into a threadlocal variable and use that threadlocal variable everywherein that case what do i do in the puma context how do i set the threadlocal variableany thoughts on this are greatly appreciatedthank you,['ruby'] +835620,boto ssl certificate verify failed certificate verify failed while connecting to s3 i am trying to connect to s3 using boto but it seems to fail i have tried some workarounds but they do not seem to work can anyone please help me with this below is the code import botoif not botoconfighas sectioncredentials botoconfigadd sectioncredentialsbotoconfigsetcredentials aws access key id aws keybotoconfigsetcredentials aws secret access key aws secret keyif not botoconfighas sectionboto botoconfigadd sectionboto botoconfigsetboto https validate certificates false botoconfigadd sectionaws info botoconfigsetaws infoaws validate certsfalses3 botoconnect s3validate certsfalsebucket s3get bucketbucket name,['python'] +835672,calling directives methods from parent controller in angularjs i am using angularjs with the alias controllers pattern i cannot access or i do not know how to directive methods from a parent controller i have a function inside my controller that should call a directive method but this directive method is not available inside the this controller valuethis is what i have what i am doing wrongjsangularmodulemyapp controllermyctrl function thistext controller text thisdirtext directive text thisclick function thischangetext directivemydir function return restrict e scope text link functionscope element attrs scopechangetext function scopetext new directive text template h2texth2 htmldiv ngappmyapp div ngcontrollermyctrl as ctrl h1ctrltexth1 mydir textctrldirtextmydir button ngclickctrlclickchange directive textbutton divdivhere a codepen with the code,['javascript'] +835716,how to specify dark action mode with my theme i know there are a couple of questions about styling the contextual action bar actionmode piece of the action bar but they do not quite seem to address what i am afteri am using the toolbar with a light theme and dark action bar the toolbar looks like i want it but the action mode looks like the regular dark theme what do i need to change in my style to get the dark themed action mode not just action bar it seems i should be able to do this quickly by tapping into themeappcompat since that shows the cab how i want it but i do not want the rest of the application to be dark i am only concerned about api 14 and am using the support toolbar in place of action barhere is my base stylestyle nameappthemebase parentthemeappcompatlightnoactionbar item namecolorprimarycolorcolorprimaryitem item namecolorprimarydarkcolorcolorprimarydarkitem item nameandroidactionmodebackgroundcolorcoloractionmodeitem item nameandroidwindowactionmodeoverlaytrueitemstyletoolbar stylestyle nameappthemetoolbar parentthemeoverlayappcompatdarkactionbar item nameandroidtextcolorprimarycolorabc primary text material darkitem item nameactionmenutextcolorcolorabc primary text material darkitem item nameandroidtextcolorsecondarycolorabc primary text material darkitem item nameandroidbackgroundcolorcolorprimarydarkitemstyletoolbar layout file setting popuptheme here does not seem to have any effectandroidsupportv7widgettoolbar androidididtoolbar androidlayout widthmatch parent androidlayout heightandroidattractionbarsize appthemestyleappthemetoolbar apopupthemestylethemeoverlayappcompatdark androidpopupthemestylethemeoverlayappcompatdark androidelevation2dp androidfocusablefalseheres my toolbar which is how i want itheres my actionmode which i need to invertheres what i want the actionmode to look like which i got by changing my style to inherit from themeappcompat instead of themeappcompatlightdarkactionbar the problem being that the rest of the application goes dark which i do not want,['android'] +835767,ios8 how do i make statusbar opaque after navigationbar is hidden using hidesbarsonswipe i am building ios8 app on my tableview controller i am using selfnavigationcontrollerhidesbarsonswipe yes to hide the navigationbar on swipe up gesture it is working nicely but my statusbar becomes transparent and shows the table content underneathon storyboard status bar are top bar are set to inferredi want to 1 keep my status bar opaque 2 maintain the same color as the navigationbar 3 table content scrolls underneath the statusbarthank you,['objective-c'] +836037,how to install pygame on python 34 so i have this little problem when i try to install pygame for python 34 i download a whl wheel file and do not know how to use it some guys told me something about pip but do not know how to useinstall it,['python'] +836061,didregisterforremotenotificationswithdevicetoken not called in ios8 but didregistersettings is i followed this thread but the method didregisterforremotenotificationswithdevicetoken is still not called the documentation says after you call the registerforremotenotifications method of the uiapplication object the app calls this method when device registration completes successfullydidregisteruser appears well but not did register notifhere is my code in the appdelegate the app version is 81 boolapplicationuiapplication application didfinishlaunchingwithoptionsnsdictionary launchoptions register notif uiusernotificationtype usernotificationtypes uiusernotificationtypealert uiusernotificationtypebadge uiusernotificationtypesound uiusernotificationsettings settings uiusernotificationsettings settingsfortypesusernotificationtypes categoriesnil application registerusernotificationsettingssettings return yes voidapplicationuiapplication application didregisterusernotificationsettingsuiusernotificationsettings notificationsettings register to receive notifications application registerforremotenotifications nslogdidregisteruservoidapplicationuiapplication application didfailtoregisterforremotenotificationswitherrornserror error nslogerror here errornot called voidapplicationuiapplication application didregisterforremotenotificationswithdevicetokennsdata devicetoken store the devicetoken in the current installation and save it to parse pfinstallation currentinstallation pfinstallation currentinstallation currentinstallation setdevicetokenfromdatadevicetoken currentinstallationchannels global currentinstallation saveinbackground nslogdid register notifnot calledi also have background mode remote notification in the infoplist,"['ios', 'objective-c']" +836144,set a method breakpoint for a particular object and not all instances of that type in java suppose i have a classpublic class foo public void dothing say i have a lot instances of foo but i am only particularly interested in one of themhow would i tag that instance and set a conditional breakpoint in dothings that would stop only for the tagged instanceis there a builtint way particularly by the eclipse debugger to do thiscurrently i have to manually create a boolean flag in the foo class setting it to false by default and create a conditional breakpoint based on that in dothingsthen when i encounter the interested object i would set the flag to true by executing the setter code in the thisplay windowbut clearly that requires modifying the code and adding some boilerplate which is not always possible or a good thing to do,['java'] +836239,gson remove unnecessary parent object while deserializing i am trying to deserialize a json array using gson all of my nested objects are embedded inside an embedded object book name book 1 published 19 links url wbook1com embedded author name john doe links url wjohndoecom i could also have a situation like this book name book 1 published 19 links url wbook1com embedded publisher name publishing company links url wpublishingcompanycom this is an extremely simple example some of my objects may be nested 2 or 3 levels deep and all are in an embedded object also each object has a nested url inside a links object i have around 20 different model objects each with several fields and everyone of them have the embedded object i started to write custom deserializers for each model but that seems to miss the whole point of using gson and i may not always know what the embedded object isi found this answer but it was for serializing objects i have been trying to figure this out for a while now and have not found anything that worksmy book model looks like thispublic class book string name int published string url author author publisher publisherauthor classpublic class author string name string urlpublisher classpublic class publisher string name string urland here is my book deserializer so farpublic class bookdeserializer implements jsondeserializerbook override public book deserializejsonelement json type typeoft jsondeserializationcontext context throws jsonparseexception final jsonobject jsonobject jsongetasjsonobject book book new book booksetnamejsonobjectgetnamegetasstring booksetpublishedjsonobjectgetpublishedgetasint string url jsonobjectgetasjsonobjectlinksgeturlgetasstring bookseturlurl 1 how to get rid of this and skip to the real nested object final jsonobject embeddedobject jsonobjectgetasjsonobjectembedded 2 see what the embedded object actually is string embeddedmodel setmapentrystring jsonelement entryset embeddedobjectentryset for mapentrystring jsonelement entry entryset author or publisher embeddedmodel entrygetkey we have the models key now add code here to deserialize whatever the object is return book i still have to parse the json and set each field for book then i would have to add code to determine and use the correct deserializer for the nested object looks like i still would need a custom deserializer for each object to get the url i am fairly new to gson so maybe there is just something that i am overlooking but it seems that i might as well just manually parse all of the json and not even use gson maybe there is a way to flatten out jsonany ideas on how to parse this and still use the convenience of gson or is this even possible maybe jackson could handle this better,['java'] +836369,java 8 default method readability java 8 introduces the concept of default methods consider the following interface with a default method public interface idefaultmethod public abstract void musimplementthismethod public default void mayormaynotimplementthismethod systemoutprintln this method is optional for classes that implement this interface and a class that implements this interface public class defaultmethodimpl implements idefaultmethod override public void musimplementthismethod systemoutprintlnthis method must be implementd override public void mayormaynotimplementthismethod todo autogenerated method stub idefaultmethodsupermayormaynotimplementthismethod i have a question about the readability of the following call in the mayormaynotimplementthismethod idefaultmethodsupermayormaynotimplementthismethodi understand that the reason for explicitly specifying the interface name in the above call is to avoid confusion in case multiple interfaces implemented by the class have the same method what i do not understand is the meaning of the super keyword in this context when we say idefaultmethodsuper what exactly are we referring to here wouldnt idefaultmethodmayormaynotimplementthismethod be more readable than idefaultmethodsupermayormaynotimplementthismethod removing the super keyword makes it more readable at the cost of thistinguishing between a static or non static method call,['java'] +836529,can pandas read and modify a single excel file worksheet tab without modifying the rest of the file many spreadsheets have formulas and formatting that python tools for reading and writing excel files cannot faithfully reproduce that means that any file i want to create programmatically must be something i basically create from scratch and then other excel files with the aforementioned sophistication have to refer to that file which creates a variety of other dependency issuesmy understanding of excel file tabs is that they are actually just a collection of xml files well is it possible to use pandas or one of the underlying readwrite engines such as xlsxwriter or openpyxl to modify just one of the tabs leaving other tabs with more wicked stuff in there intactedit i will try to further articulate the problem with an exampleexcel sheet testxlsx has four tabs aka worksheets sheet1 sheet2 sheet3 sheet4i read sheet3 into a dataframe let us call it df using pandasread excelsheet1 and sheet2 contain formulas graphs and various formatting that neither openpyxl nor xlrd can successfully parse and sheet4 contains other data i do not want to touch those tabs at allsheet2 actually has some references to cells on sheet3i make some edits to df and now want to write it back to sheet3 leaving the other sheets untouched and the references to it from other worksheets in the workbook intactcan i do that and if so how,['python'] +836556,how can i download a file with batch file without using any external tools first to clarify this question is aimed to https download for ftp may be i will ask and answer another questionhere are some similar questions but i want to be more precise besides excluding external tools i want the solutions to be applicable for the widest possible types of windows machines including xpwin2003vista which still have big enough sharealso as wsh is one of the possible options i prefer no using of temp files and everything to be packed in a single bat file which is possible with both jscript and vbscriptwhat are possible approachespure batch solution with bitsadmin a command line utilityavailable on every windows machine it is not pretty convenient but is anthe only option whereno other scripting language should be usedusing wsh three approaches are possible winhttp msxml2xmlhttpinternetexlorerapplication all of them are accessible activexobjects in order of how i prefer themwinhttp and msxml2xmlhttpare pretty similar in their capabilities but winhttp has areputation of more stableinternetexlorerapplication is in factjust the internet explorer accessible through activex object andsome ui elements are unavoidable are they so i will skip this oneusing net it is possible to create a hybrid batch file with allthe three default net compilers jscriptnet vbnet c withjscriptnet there is no redundant error messages so i will preferitif we ignore the fact that there is a compiled exe all the codeis in one file so according to me this fits in the requirements with net we can use systemnetwebclient orsystemnethttpwebrequest the webclient relies on it orsystemwebhttprequest but for now i will post onlysystemnetwebclient solutionand even more same activex objectsaccessible with wsh are available here tooso there are really manyways to dowanload a file with netmay be in the future i will updatemy answeranyway only the webclient is especially designed for downloadusing powershell has same possibilities as net but with lesschances to be installed on all machines you can meetso i will skipthis one too,['.net'] +836797,bootstrap navbar center text i have recently implemented a collapse bootstrap navbar to my website however i have an issue with it when it is in its full form the text is aligned to the left of the navbar and despite much css config and browsing of stackoverflow none of the changes i have tried have been successful at alli am trying to change the navbar so that the textlinks within it are centralized div classnavbarheader button classnavbartoggle datatogglecollapse datatargetnavbarcollapse span classiconbarspan span classiconbarspan span classiconbarspan button div end navbarheader div classcollapse navbarcollapse ul classnav navbarnav lia hrefhomehomea lia hrefhomedays outali lia hrefhomeghostsali lia hrefhomebeastsali lia hrefhomehistoryali lia hrefhomeabout usali lia hrefhomegiftsali lia hrefhomeblogali lia hrefhomecontact usali ul div end collapse div,['css'] +836935,stdthread taking lambda with ref arg fails to compile i am reading c concurrency in action chapter 24 describes a parallell accumulate algorithmi tried as a learning experiment to replace the functor used there with a generic lambdai have thistilled the compilation error down toinclude threadtemplate typename tstruct f void operator t result result 1int main int x 0 auto g auto result result 1 stdthreadfint stdrefx compiles stdthreadg stdrefx fails to compilethe error message in file included from usrincludec49thread390 from foocpp1usrincludec49functional in instantiation of astruct std bind simplemainlambdaauto1stdreference wrapperintausrincludec49thread14047 required from astdthreadthread callable args with callable mainlambdaauto1 args stdreference wrapperintafoocpp1331 required from hereusrincludec49functional166561 error no type named atypea in aclass stdresult ofmainlambdaauto1stdreference wrapperinta typedef typename result of callable argstype result type usrincludec49functional16959 error no type named atypea in aclass stdresult ofmainlambdaauto1stdreference wrapperinta m invoke index tuple indices my compiler version g versiong ubuntu 49116ubuntu6 491why do the compilation fail for the lambda but not the functoredit how can i achieve what the functor is doing assigning to a ref with a generic lambda,['c++'] +836983,xcode projectapp name with spaces issue framework not found is it possible that xcode 61 does not finds my previously imported frameworks because of my 3 word app name i am using parse and never ever had any problems with it but actually when i open my project in xcode i got an error that the framework does not found which is absurd because it worked well earlier and i do not removed it however if i delete the frameworks and add them again everything is fine am i doing something wrong or is it an xcode bug ld warning directory not found for option fusersdonipdocumentsfl travel guideflld warning directory not found for option ftravelld warning directory not found for option fguideld framework not found parsefacebookutilsclang error linker command failed with exit code 1 use v to see invocation,"['ios', 'objective-c']" +837111,using optional query parameters in f web api project i was converting a c webapi project to f using the f aspnet templates everything is working great except optional query parameters i keep getting this error message the request is invalid messagedetail the parameters dictionary contains an invalid entry for parameter start for method systemthreadingtaskstask1systemnethttphttpresponsemessage getvendorfilesint32 systemnullable1systemdatetime in thorwebapivendorfilescontroller the dictionary contains a value of type systemreflectionmissing but the parameter requires a value of type systemnullable1systemdatetimef function signaturehttpget routemember xgetvendorfiles optional defaultparametervalue100 count optional defaultparametervaluenull start nullabledatetime c function signaturehttpgetroutepublic async taskhttpresponsemessage getvendorfilesint count 100datetime start nulldoes anyone know of any workaroundsupdatedi figured out the cause of this issue aspnet extracts default values for controller actions using parameterinfo apparently the f compiler does not compile default values the same way as c does even with the defaultparametervalueattributewhats the best way or working around this would it be some filter that i need to inject or implement my own parameterbinding,['.net'] +837134,using npm as a task runnerbuild tool having problems with some cli modules i am trying to use npm as a task runnerbuild tool after reading this articlehow to use npm as a build tooland while i am having some success i am stuck on one thing when running a commandline global tool like jslint jshint or eslint npm will always show the exit 1 code in the console windowas you can see the command works fine but npm sees it as an error and thisplays the error log info is this normal andor is there a way to turn it off for specific commandsadditional info this is script block in my packagejson configscripts start node srcserverindexjs test lint eslint indexjs then from npm cli i type npm run lintthis will execute the script found in the packagejson file with the label lint,['javascript'] +837192,webview not loading at first time i am struggle with a strange issue i am trying to load a https web page but the first time the webview does not load after wait 60 seconds i have to click again in my button to load my page my device is a nexus 4 with lollipop but this issue happens at devices with android 44 and 41 as well the url does not have heavy content only a few javascript files and css fileslog iwebviewfactoryi1 loading comgoogleandroidwebview version 37 1602158arm code 1201 ilibraryloaderi1 loading webviewchromium ilibraryloaderi1 time to load native libraries 3 ms timestamps 53315334 ilibraryloaderi1 expected native library version number actual native library version number ilibraryloaderi1 expected native library version number actual native library version number ichromiumi1 infolibrary loader hookscc106 chromium logging enabled level 0 default verbosity 0 ibrowserstartupcontrolleri1 initializing chromium process renderers0 warti1 attempt to remove local handle scope entry from irt ignoring wchromiumi1 warningresource bundlecc315 locale file pathempty ichromiumi1 infoaw browser main partscc63 load from apk succesful fd72 off159196 len3264 ichromiumi1 infoaw browser main partscc78 loading webviewchromiumpak from fd73 off229484 len643667 waudiomanagerandroidi1 requires bluetooth permission wchromiumi1 warningproxy servicecc901 pac support thisabled because there is no system implementation wchromiumi1 warningdata reduction proxy settingscc403 spdy proxy off at startup warti1 attempt to remove local handle scope entry from irt ignoring wawcontentsi1 ondetachedfromwindow called when already detached ignoring ichromiumi1 infoskutilsarmcpp179 device supports arm neon instructionsmy codefinal webview wv webview alertfindviewbyidridmodal wv wvgetsettingssetappcacheenabledtrue wvgetsettingssetcachemodewebsettingsload default wvgetsettingssetappcachepathdatadata getpackagename cache wvgetsettingssetallowfileaccesstrue wvgetsettingssetjavascriptenabledtrue wvloadurlconnectionresponsegeturlsame behavior wvpostnew runnable override public void run wvloadurlconnectionresponsegeturl i set a new webclient overriding the following methods shouldoverrideurlloading onloadresource onpagefinishedfor tests purpose i removed this custom webclient but it still was not load at the first timethanks,['android'] +837196,why is chartjs canvas not respecting the padding of the container element i am using chartjs with a simple line chart but the width and height properties calculated by chartjs seem to be based on the total width and height of the parent element ignoring paddinghtmldiv classcontainercanvas idmychart1 classchildcanvasdivbrdiv classcontainer div classchildtestdivdivcsscontainer padding 15px 15px 15px 15px width 300px height 200px border 1px solid blackchild thisplay inlineblock border 1px solid red width100 height100jsvar options maintainaspectratio false responsive truevar data labels datasets label my first dataset fillcolor rgba22022022002 strokecolor rgba2202202201 pointcolor rgba2202202201 pointstrokecolor f pointhighlightfill f pointhighlightstroke rgba2202202201 data 65 59 80 81 56 55 40 label my second dataset fillcolor rgba15118720502 strokecolor rgba1511872051 pointcolor rgba1511872051 pointstrokecolor f pointhighlightfill f pointhighlightstroke rgba1511872051 data 28 48 40 19 86 27 90 var ctx1 documentgetelementbyidmychart1getcontext2dvar mynewchart new chartctx1linedata optionsjsfiddlethe second container and child shows the behaviour i am expecting is this a bug with how chartjs calculates the width and height of the canvas or am i making a styling mistake,"['javascript', 'html', 'css']" +837217,jdbc vs hibernate we have been using jdbc for a very long time in our web applications the main reason we used it is because we have 100 control over the code sql and fix things by our hands apart from that we used triggers inside the database and the database is developed separately by db expertshowever many now recommend using hibernate so we also thought about using it but we found the below issueshibernate cannot connect with an existing database it always try to create a one of its ownour database might access by same application which is in different platforms cloud server vps personal computer hibernate can make problems because of its caching in this situationwe never like to give the table creating work to the java code we create tables manually alwayswe might have to use very long and complex sql statements last time we used an statement with more than 150 lines joining more than 20 tables we doubt whether we will face troubles in this when it comes to hibernateour sql code is nice and standard hibernate generated code seems to be bit dirty for uswe always use mysql never use any other dbthe application we create require max security related to medical if at least one data record is leaked we are donethere are lot of foreign keys primary keys composite keys unique keys etc etc in database in forums some complained that hibernate messed with thosewe decided to try hibernate because some people claims are you software engineers you are using already dead jdbc considering these please let me know whether the above points are actually true as i said i got to know them via googling thiscussion etc or not and what are the pros and cons of hibernate vs java jdbc,"['java', 'mysql']" +837420,is is possible to apply a generic method to a list of items lets say i have written my own method to reverse a list in placepublic static void myreversetlistt source var length sourcecount var hlength length 2 for var i 0 i hlength i t temp sourcei sourcei sourcelength 1 i sourcelength 1 i temp i call it like so and it worksvar foolist new listfoomyreversefoolistif i want to reverse multiple lists i call it like sovar foolist new listfoovar barlist new listbarvar bazlist new listbazmyreversefoolistmyreversebarlistmyreversebazlistif i want to reverse an arbitrary number of lists i would trypublic static void mainstring args var lists new listobject new listfoo new listbar new listbar reverselistslistspublic static void reverselistslistobject sourcelists foreach var sourcelist in sourcelists myreversesourcelist error type arguments cannot be inferred from usage but this throws a compile time error is what i am trying to do possible could the reverselists method be implemented,['c#'] +837426,ios how to set app icon and launch images omg i just barely figured out the old system and now they have changed it againhow do i set the images so that i can archive and validate my app the screen looks like this now so the first one says 29pt but then it also says 2x so do i put a 29x29 image or a 58x58 image and where do i put all of the other ones i know that there are more sizes than 29 40 and 60anyway what i tried was i dragged a 29x29 png onto the first slot a 40x40 onto the second and a 60x60 onto the third and fourth when i went to productarchive i get userskendondocumentsiphone appssales toolsales toolimagesxcassets the app icon set named appicon did not have any applicable content,['ios'] +837523,wrong last day of month where is some function to get the last day of month in my service dateformat format new simpledateformatymmdd localeenglish date date formatparsestringdate calendar calendar calendargetinstance calendarsettimedate calendaraddcalendarmonth 1 calendarsetcalendarday of month 1 calendaraddcalendardate 1 date lastdayofmonth calendargettime dateformat sdf new simpledateformatymmdd return sdfformatlastdayofmonthso this method correctly works elsewhere but in us last day is always 29 last day 1stringdate is date in format ymmdd,['java'] +837531,js function named animate does not work in chrome but works in ie this would not work nothing happens how do i make it work what am i doing wrongfunction animate var div documentgetelementbyiddemo divstyleleft 200px divstylecolor reddemo position absolutep iddemo onclickanimatelololp,"['javascript', 'html', 'css']" +837563,in x86 why do i have the same instruction two times with reversed operands i am doing several experiments with x86 asm trying to see how common language constructs map into assembly in my current experiment i am trying to see specifically how c language pointers map to registerindirect addressing i have written a fairly helloworld like pointer programinclude stdiohintmain void int value 5 int int val value printf the value we have is dn int val return 0and compiled it to the following asm using gcc o pointers fnoasynchronousunwindtables pointerc12 file pointerc section rodatalc0 string the value we have is dn text globl main type main functionmain function prologue pushq rbp movq rsp rbp subq 32 rsp movq fs40 rax movq rax 8rbp xorl eax eax movl 5 20rbp this is where the value 5 is stored in value automatic allocation leaq 20rbp rax guess if i have understood correctly this is where the address of value is extracted and stored into rax movq rax 16rbp movq 16rbp rax why do i have two times the same instructions with reversed operands movl rax eax movl eax esi movl lc0 edi movl 0 eax call printf movl 0 eax movq 8rbp rdx xorq fs40 rdx je l3 call stack chk faill3 leave ret size main main ident gcc ubuntu 49116ubuntu6 491 section notegnustackprogbitsmy issue is that i do not understand why it contains the instruction movq two times with reversed operands could someone explain it to me1 i want to avoid having my asm code interspersed with cfi directives when i do not need them at all2 my environment is ubuntu 1410 gcc 491 modified by ubuntu and gnu assembler gnu binutils for ubuntu 2249020141014 configured to target x86 64linuxgnu,['c'] +837671,c alternative to enums for a nmrelation there are several threads on valueranges in enums not possiblebut i have the following problem and search the best solution where none of the provided once really satisfied mea specification of a protocol says that bytex of a message the messagetype has the following possible values fantasy values 0x00 get0x01 set 0x02 to 0xff identifyso there are only 3 different logical options which would best be dealt with in an enum but one of the and logical options has m different numerical counterparts which is impossible to be dealt with in an enumnow what is the best cleanest solution for such a problemi could build a classclass messagetype public enum messagetypeenum get 0x00 set 0x01 identify 0x02 public static messagetypeenum getlogicalvalue byte numericalvalue if numericalvalue 0x02 return messagetypeenumnumericalvalue else return messagetypeenumidentify i could also create a class without an enum but with static memberseither way there is one problem if someone tries to thispatch a packet he might use if messagebytesx bytemessagetypeenumidentify do stuffbut messagebytex could be anything between 0x02 and 0xff so hitting the value specified in the enum would be pure luck on the other side i want the enum or static member to be public for easy messagebuilding can i somehow enforce the use of my getlogicalvaluefunctionis there a more elegant solutionall i want is an easy and wellstructured way to link logical values to numerical values in a nm relation especially as the given protocol has many such cases and i would like to keep my code neatthanks for your help and time janis,['c#'] +837697,increasing code performance of codility today i heard about this website called codility where a user can give various programming test to check their codes performancewhen i started they presented me with this sample testtask description a small frog wants to get to the other side of the road the frog is currently located at position x and wants to get to a position greater than or equal to y the small frog always jumps a fixed thistance d count the minimal number of jumps that the small frog must perform to reach its target write a function class solution public int solutionint x int y int d that given three integers x y and d returns the minimal number of jumps from position x to a position equal to or greater than y for example givenx 10y 85d 30 the function should return 3 because the frog will be positioned as follows after the first jump at position 10 30 40 after the second jump at position 10 30 30 70 after the third jump at position 10 30 30 30 100assume that x y and d are integers within the range110 x a y complexity expected worstcase timecomplexity is o1 expected worstcase space complexity is o1the question was pretty straight forward and it took me like 2 minutes to write the solution which is followingclass solution public int solutionint x int y int d int p 0 while x y p x x d return p however the test result shows that the performance of my code is just 20 and i scored just 55here is the link to result that was so simple code where i have just used a single while loop how could it possibly be make much faster,['java'] +838002,c enforce secondpass name lookup in template function is there some way to force c compilers to perform name lookup for a given symbol during template instantiation and not beforegiven the following codetemplate class tauto wrapper t t decltype f t return f t unsigned char f int x return x 256 unsigned char f unsigned char x return x int main int char auto x wrapper 3100 return 0is there anything i can do apart from moving the definition of f to the top in order to make that code compile and give the same results as if all definitions of f were available before the definition of wrapperi could not find anything probably because i do not know how to phrase this question properly all argument types of f can be assumed to be userdefined types if this helps,['c++'] +838171,indexnotreadyexception android studio while changing the values of a widget in properties tab androidstudio keeps on throwing indexnotreadyexception but after few minutes while retrying the error is not occurringhere is the error logcomintellijopenapiprojectindexnotreadyexception please change caller according to comintellijopenapiprojectindexnotreadyexception documentation at comintellijutilindexingfilebasedindeximplhandledumbmodefilebasedindeximpljava856 at comintellijutilindexingfilebasedindeximplensureuptodatefilebasedindeximpljava805 at comintellijutilindexingfilebasedindeximplprocessexceptionsfilebasedindeximpljava930 at comintellijutilindexingfilebasedindeximplcollectfileidscontainingallkeysfilebasedindeximpljava1190 at comintellijutilindexingfilebasedindeximplprocessfilescontainingallkeysfilebasedindeximpljava1018 at comintellijpsiimplsearchpsisearchhelperimpl26computepsisearchhelperimpljava1096 at comintellijpsiimplsearchpsisearchhelperimpl26computepsisearchhelperimpljava1093i have updated the androidstudio to latest one but still the error occurs any fix or work around,['android'] +838230,binary tree static methods in java i have these instance methods in my java implementation of binary tree and search binary tree getsize getheight getdepth getpreorder getinorder getpostorder and getlevelorder these methods use the root of the tree in others recursive methods that have a parameter node which is more appropiate to use from the point of view of the oopusing these recursive methods as static methods because they use an object node that does not belong to the actual class and they do not use any class attributesthey can be instance methods because they can use in a subtree of this tree and they do not use any static attributesor they may be in other static class like utilstree,['java'] +838259,why is this error appearing in chrome load resource neterr quic protocol error this is the error i am seeing in my chromes console load resource neterr quic protocol error how can i fix it i want to thisplay a google map,['javascript'] +838488,how to force popupmenu to overlap anchor how to force popupmenu to overlap anchor i would like to recreate something similar to this,['android'] +838515,how to show query parameter options in django rest framework swagger this has been bugging me for a while nowmy ultimate goal is to show query parameter options inside swaggerui and give a form input for each query parameter similar to how it is thisplayed when providing a serializer for posti am using a viewset which inherits from genericviewset and i have tried the followingprovide filter fields attribute provide and set filter backends attribute to filtersdjangofilterbackendprovide filter class defined inside my module override options method to provide actionsget informationheres a small catch i am not using any models so i do not think djangofilterbackend will really help me i am using djangorestframework to talk to an outside api and i am simply getting json result back and passing it through to the frontend layer here is a small modified snippet of my code to better explain my problemviewspyclass someviewsetgenericviewset note that i have all of these defined but i have tried various combinations filter fields query option 1 query option 2 filter backeds filtersdjangofilterbackend filter class somefilter query metadata some dict this works when request is options def optionsself request args kwargs if selfmetadata class is none return selfhttp method not allowedrequest args kwargs data selfmetadata classdetermine metadatarequest self dataactionsget selfquery metadata return responsedata statusstatushttp 200 okfilterspyclass somefilterfilterset strict true query option 1 django filtersnumberfilternamequery option 1 query option 2 django filtersnumberfilternamequery option 2 class meta fields query option 1 query option 2thank you for looking and thanks in advance for responding,['python'] +838538,how to use cython typed memoryviews to accept strings from python how can i write a cython function that takes a byte string object a normal string a bytearray or another object that follows the buffer protocol as a typed memoryviewaccording to the unicode and passing strings cython tutorial page the following should workcpdef object printbufunsigned char buf chars chrx for x in buf print reprjoincharsit does work for bytearrays and other writable buffers python c import test testprintbufbytearraytest0ingtestx00ingbut it does not work for normal strings and other readonly buffer objects python c import test testprintbuftest0ingtraceback most recent call last file string line 1 in module file testpyx line 1 in testprintbuf testc1417 file stringsource line 614 in viewmemoryviewmemoryview cwrapper testc6795 file stringsource line 321 in viewmemoryviewmemoryview cinit testc3341buffererror object is not writablelooking at the generated c code cython is always passing the pybuf writable flag to pyobject getbuffer which explains the exceptioni can manually get a view into the buffer object myself but it is not as convenientfrom cpythonbuffer cimport pybuf simple pybuf writable pyobject checkbuffer pyobject getbuffer pybuffer releasecpdef object printbufobject buf if not pyobject checkbufferbuf raise typeerrorargument must follow the buffer protocol cdef py buffer view pyobject getbufferbuf view pybuf simple try chars chrunsigned char viewbufi for i in rangeviewlen print reprjoinchars finally pybuffer releaseview python c import test testprintbufbytearraytest0ingtestx00ing python c import test testprintbuftest0ingtestx00ingam i doing something wrong or does cython not support coercing readonly buffer objects such as normal strings into typed memoryview objects,['python'] +838576,height auto on svg not working i am trying to use an svg sprite sheet using the symbol method detailed heremy html is very simplesvguse xlinkhrefimagesiconspritesvgcamerasvgand here is an example symbol from the svg filesymbol viewbox0 0 24 24 idclockg transformtranslate0 10284path dm22085 1035955a10997 10997235 1 12017 877 10997 10997235 1 1 2017877z fill1abc9cpath dm21 1040335a9 9 0 1 118 0 9 9 0 1 1 18 0z fillecf0f1path dm1034 10398c083 17176 33875 49 242 56 8898 82 14468 58 42919 677862 6593106202 4263 786592 96557 2412047214475855612822687439z fill16a085path dm20 10404c0 5448 11 1h6v2h6c552 0 1 4 1 1z fill3498dbpath dm12 10334c552 01 4481 1v5h2v5c05524481z fill2c3e50path fillc0392b dm6017 1045705l495495707707495 495zpath dm12 10384c1105 02 92 2s895 2 2 2 29 228952zm0 1c552 0 1 4 1 1 0 5448 11 1s1511c064481 11z fill34495egsymbolthe problem i am having is that when i use css to set the width of the svg element to 64px the height of the svg is automatically set to 150 pixels i have tried setting heightauto and height100 on the svg element but it makes no difference the only way to get it to work is to set height64px which i do not want to do because the aspect ratio of my icons may not always be square what i want it to do is automatically scale the svg in its original aspect ratio so a 43 icon as defined by the viewbox would automatically get a heightof 300px if i set the width to 400pxi have read several guides on scaling svg and preserving aspect ratio and some have solutions when using an img element but i cannot find one for inline svgs or using an external svg with useanybody know a solution which works in all browsers including ie9 and android 40,['css'] +838583,ios viewdidlayoutsubviews called before autolayout completed on ios7 were currently having a problem that only seems to affect ios7 deviceswithin our xib file we have two views within a container view ie not at the top level of the view hierarchy that need to be circular on thisplay the views have constraints applied to their position and horizontal spacing within the container and an aspect ratio condition requiring they are square the views should expand in widthheight on larger screen sizes respecting the constraints describedin our vc we have the following in viewdidlayoutsubviews to force these views to appear circular voidviewdidlayoutsubviews selfprogresscontentcontainerviewlayercornerradius selfprogresscontentcontainerviewframesizewidth2this seems to work fine on ios8 however on ios7 there is a period after the view has been thisplayed where the constraints have not yet been applied and the size of the viewviews is incorrect see attached screenshots this resolves itself and correctly renders a circle after half a second this only appears to happen when the views that we intend to be circular are not at the top level of the vcs view hierarchy which seems to imply that viewdidlayoutsubviews is called before the subviews of subviews have also been laid outmy guess is that we could potentially fix this issue by subclassing uiview for the nested container adding references to the circular view within this subclass and overriding viewdidlayoutsubviews here to make the cornerradius adjustment this seems like a bit of a workaround though and i am interested to see if there are other optionsis there a cleanermore idiomatic solution to this problem,['ios'] +838621,using group by and joins in sequelize i have two tables on a postgresql database contracts and payments one contract has multiple payments donei am having the two following models moduleexports functionsequelize datatypes var contracts sequelizedefinecontracts id type datatypesinteger autoincrement true createdat false updatedat false classmethods associate functionmodels contractshasmanymodelspayments foreignkey contract id return contractsmoduleexports functionsequelize datatypes var payments sequelizedefinepayments id type datatypesinteger autoincrement true contract id type datatypesinteger payment amount datatypesinteger classmethods associate functionmodels paymentsbelongstomodelscontracts foreignkey contract id return paymentsi would like to sum all the payments made for every contract and used this functionmodelscontractsfindall attributes id include model modelspayments attributes modelssequelizefnsum modelssequelizecolpaymentspayment amount total cost group contractsidbut it generates the following queryselect contractsid paymentsid as paymentsid sumpaymentspayment amount as paymentstotal cost from contracts as contracts left outer join payments as payments on contractsid paymentscontract id group by contractsidi do not ask to select paymentsid because i would have to include it in my aggregation or group by functions as said in the error i havepossibly unhandled sequelizedatabaseerror error column paymentsid must appear in the group by clause or be used in an aggregate functionam i missing something here i am following this answer but even there i do not understand how the sql request can be valid,['sql'] +838687,algorithm or sql to find where conditions for a set of columns which ensures result set has value in a particular column always 0 i am working on a javaoracle based project where i stuck with an problem which seems to me requires an analytic solutioni am looking for solution either based on sql query or any algorithm or any free analytic tool which i can follow to get desired resultsproblem statementlets us say i have below table with columnad and last column as score i want to find an criteria on values for each of the columns which when combined in sql where clause will always give me positive value for score column so basically what combination of columnad will always give me positive scorecolumnacolumnbcolumnccolumndscore 1 40 10 3 20 0 40 2 3 10 0 10 3 3 20 1 15 3 3 5 0 10 2 2 15 0 15 6 3 10expected result for above data setvisual interpretation of above data set gives me condition acolumna 0 and columnb 10 and columnc 5 will ensure score always 0a visually its clear columnd does not have an effectplease note above data set is for sake of simplicity in reality my project contains around 40 columns with almost 2500 rows one thing is for sure each of columns have finite range of valuesfollowing information copied from ops answer belowhere is an algorithm i started with need inputs to refine it further if someone thinks i am in right directionpreparation create an list of all possible expressions like a0 b10c5 for 40 columns i finalized total approx 150 expressionslet us call it expressions variablealogrithm for 1st runset totalpositiverows select count from my tables where score0set totalnegativerows select count from my tables where score0for each expr in expressions calculate following three variables set positivepercentage find percentage of totalpositiverows which satisfy this expr like if 60 rows out of total 100 rows having score0 satisfy expr then positivepercentage60set negativepercentage find percentage of totalnegativerows which satisfy this expr like if 40 rows out of total 100 rows having score0 satisfy expr then negativepercentage40set diffpercentagepositivepercentagenegativepercentageset initialexprchoose expr having maximum value of diffpercentageset initalpositivepercentagechoose corresponding positivepercentage value set initalnegativepercentagechoose corresponding negativepercentage valuemy thinking is that i need to now keep expanding initalexpr until initalnegativepercentage becomes 0alogrithm for subsequent runs until initalnegativepercentage becomes 0for each expr in expressions calculate following three variablesset newexprinitialexpr and exprset positivepercentage find percentage of totalpositiverows which satisfy newexprset negativepercentage find percentage of totalnegativerows which satisfy newexprcalculate how much negative percentage it has reducedset positivereductioninitalpositivepercentagepositivepercentageset negativereductioninitalnegativepercentagenegativepercentageifnegativereductionpositivereductionnote it downelsethiscard itchoose the expr which gives maxium negative reduction that becomes new inital exprset initialexprchoose expr having maximum value of negativereductionset initalpositivepercentagechoose corresponding value set initalnegativepercentagechoose corresponding valuerepeat the algorithm above please comment,"['java', 'sql']" +838708,changing html of resets selectedindex property of from 1 to 0 using jquery when changing html of an option inside a select which i had previously set selectedindex property to 1 resets selectedindex property of select from 1 to 0doctype htmlhtmlheadscript srccodejquerycomjquery211minjsscript meta charsetutf8 titlejs bintitleheadbodyselect idmyselect classdrpmnu option idone 01option option idtwo 02option option idthree 03optionselect script drpmnupropselectedindex 1 threehtmlmoo scriptbodyhtml,"['javascript', 'jquery', 'html']" +838893,repeatedly creating and deleting databases in entity framework when writing some unit tests for our application i stumbled upon some weird behaviour in ef6 tested with 61 and 612 apparently it is impossible to repeatedly create and delete databases same namesame connection string within the same application contexttest setuppublic class a public int id get set public string name get set class amap entitytypeconfigurationa public amap haskeya aid propertya anameisrequiredismaxlengthhascolumnnamename propertya aidhascolumnnameid public class somecontext dbcontext public somecontextdbconnection connection bool ownsconnection baseconnection ownsconnection public dbseta as get set protected override void onmodelcreatingdbmodelbuilder modelbuilder baseonmodelcreatingmodelbuilder modelbuilderconfigurationsaddnew amap testfixturepublic class basictest private readonly hashsetstring m databases new hashsetstring region setupteardown testfixturesetup public void setup systemdataentitydatabasesetinitializer new createdatabaseifnotexistssomecontext testfixtureteardown public void teardown foreach var database in m databases if stringisnullorwhitespacedatabase deletedatabasedatabase endregion test public void repeatedcreatedeletesamename var dbname guidnewguidtostring m databasesadbname for int i 0 i 2 i assertistruecreatedatabasedbname failed to create database assertistruedeletedatabasedbname failed to delete database consolewriteline test public void repeatedcreatedeletedifferentname for int i 0 i 2 i var dbname guidnewguidtostring if m databasesadbname assertistruecreatedatabasedbname failed to create database assertistruedeletedatabasedbname failed to delete database consolewriteline test public void repeatedcreatedeletereusename var testdatabases new hashsetstring for int i 0 i 3 i var dbname guidnewguidtostring if m databasesadbname testdatabasesadbname assertistruecreatedatabasedbname failed to create database assertistruedeletedatabasedbname failed to delete database var repeatname testdatabasesorderbyn nfirstordefault assertistruecreatedatabaserepeatname failed to create database assertistruedeletedatabaserepeatname failed to delete database consolewriteline region helpers private static bool createdatabasestring databasename consolewritecreating database databasename using var connection createconnectioncreateconnectionstringdatabasename using var context new somecontextconnection false var a contextastolist compatiblewithmodel must not be the first call var result contextdatabasecompatiblewithmodelfalse consolewritelineresult done fail return result private static bool deletedatabasestring databasename using var connection createconnectioncreateconnectionstringdatabasename if systemdataentitydatabaseexistsconnection consolewritedeleting database databasename var result systemdataentitydatabasedeleteconnection consolewritelineresult done fail return result return true private static dbconnection createconnectionstring connectionstring return new sqlconnectionconnectionstring private static string createconnectionstringstring databasename var builder new sqlconnectionstringbuilder datasource server initialcatalog databasename integratedsecurity false multipleactiveresultsets false persistsecurityinfo true userid username password password return builderconnectionstring endregionrepeatedcreatedeletedifferentname completes successfully the other two fail according to this you cannot create a database with the same name already used once before when trying to create the database for the second time the test and application throws a sqlexception noting a failed login is this a bug in entity framework or is this behaviour intentional with what explanationi tested this on a ms sqlserver 2012 and express 2014 not yet on oracleby the way ef seems to have a problem with compatiblewithmodel being the very first call to the databaseupdatesubmitted an issue on the ef bug tracker link,"['c#', '.net']" +838930,how to bind array elements by id with dom class elements in directive i am trying to bind a page elements array with appropriate gridcell index in string html so that it would be thisplayed on the page instead within my directive i store indexes of given cell elements and then filter them to retrieve matching page elements objects however i cannot rid of the redundancy of ngrepeat in grid where is more then one element a removed element is replaced with an empty object but it should be spliced in order to keep grid elements in right places moved elements should be able to drop into other grid cells if indexes would be properly assigned then directive should work with angulardraganddroplists how to fix ithow can i thisplay ngrepeat with matched page elements only once in given grid eg now page elements where grid id 2 is thisplayed three times in ngrepeat in third grid how to remove permanently page element object and keep cell elements in right places also dragdrop mechanism is broken in current solutioncurrent code snippet and jsfiddevar app angularmoduleapp dndlistsappcontrollerhomectrl function scope scopehtml string div classcontainerdiv classrowdiv classcolxs12div classrowdiv classcolxs4 gridcelldivdiv classcolxs4 gridcelldivdiv classcolxs4 gridcelldivdivdiv classrowdiv classcolxs4 gridcelldivdiv classcolxs4 gridcelldivdiv classcolxs4 gridcelldivdivdivdivdiv scopepage elements grid id 0 position 0 snippet h4first grid 0h4 template snippet grid id 0 position 1 snippet h2second grid 0h2 template snippet grid id 1 position 0 snippet h2first grid 1h2 template snippet grid id 1 position 1 snippet h2second grid 1h2 template snippet grid id 2 position 0 snippet h1first grid 2h1 template snippet grid id 2 position 1 snippet h2second grid 0h2 template snippet grid id 2 position 2 snippet h2third grid 0h2 template snippet grid id 5 position 0 snippet h2before lasth2 template snippet grid id 5 position 1 snippet h2lasth2 template snippet scopepage elements pretty angulartojsonscopepage elements true scopermelement function i debugger directivegrid function compile return restrict e replace true scope html string htmlstring page elements pageelements link function scope element attrs scopewatchhtml string function html elementhtmlhtml var grid cell elementfindgridcell for var celli 0 celli grid celength celli var cell eli for var eli 0 eli scopepage elementslength eli if scopepage elementseligrid id celli cell eli scopepage elementsindexofscopepage elementseli var cell html div classlayoutgriddiv classdropareadiv dndlistpage elements cell html div ngrepeatitem in page elements cell elements cell eli dnddraggableitem dndmovedpage elementspage elementsindexofitempop ngclickpage elementspage elementsindexofitem ngincludeitemtemplate html dndeffectallowedmovediv cell html divdivdiv grid cellcelliemptyappendcell html compileelementcontentsscope filtercell elements function return function page elements cell eli str var cell elms cell eli strsplitmapnumber var matched for var i 0 i page elementslength i for var j 0 j cell elmslength j if i cell elmsj matchedpushpage elementsi return matched item minheight 50px paddingleft 0pxdroplayout layoutgrid marginbottom 15pxdroplayout layoutgrid classcol backgroundcolor e backgroundcolor rgba86 61 124 15 border 1px solid d border 1px solid rgba86 61 124 2droplayout divdndlist droplayout divdndlist div position relativedroplayout droparea divdndlist minheight 50px paddingleft 0pxdroplayout droparea div backgroundcolor e border 1px solid d thisplay block padding 0pxdroplayout droparea dnddragging opacity 07droplayout droparea dnddraggingsource thisplay nonedroplayout droparea dndplaceholder backgroundcolor d backgroundcolor rgba86 61 124 2 minheight 48px thisplay block position relativescript srcscriptscript srcscriptscript srcscriptlink hrefmaxcdnbootstrapcdncombootstrap331cssbootstrapmincss relstylesheet typetextcss div ngappapp div ngcontrollerhomectrl classdroplayout h1gridh1 grid htmlstringhtml string pageelementspage elementsgrid script typetextngtemplate idsnippethtml div classitemitemsnippet itempositiondiv script h1compile dynamic htmlh1h5how to live preview of filled by elements htmlh5 textarea ngmodelhtml string rows5 cols100textarea passign elements to gridcells prepage elementsprep divdiv,['javascript'] +839001,woocommerce hook for after payment complete actions i am using woocommerce and wordpress i have a custom license key generator and i would like it to generate a license key when someone successfully purchases my plugin through woocommerceit seems pretty straightforwarduser completes checkout on my siteuser is redirected to paypal where they enter their payment credentialspaypal tells my site that the payment is completei hook in to some sort of payment complete or order complete woocommerce action and generate the licenseheres the problem i am really not sure what hook would work well for this woocommerce has their entire collection of hooks listed on their site but virtually no documentation about which is good for whatbased on just the hook names i would think that woocommerce payment complete would be a good action to use unfortunately it does not seem to be fired at all some places i have read say that it is not ever firedi have also read something about paypal ipn but i do not understand how i could hook in to the notification from that does that connect to a woocommerce hookin short i would like to generate the license key as soon as the payment has been verified what do i hook in to in order to achieve this,['php'] +839056,remove authentication in aspnet mvc single page application i am trying to play about with the aspnet mvc spa template in visual studio 2013 i do not need any of the authentication bits i just need to load directly onto one of the controllers pages how do i get rid of all the authentication stuff from the initial template,['c#'] +839261,windows phone 81 bad performance when trying to get thumbnail images from camera roll i am building a windows phone 81 app windows runtime not windows phone silverlight 81 in my app i need to thisplay all photos of cameraroll in a gridview but as thumbnails to reduce memory usage when i try my app everything works fine but it is extremely slowly my code is as follows mainpagexamlcsvar files await knownfolderscamerarollgetfilesasynclistimagesource imagesources new listimagesourceforint i0 ifilescount i await executecodei files knownfolderscameraroll imagesourcesphotosgriddatacontext imagesourcesprivate async task executecodeint index ireadonlyliststoragefile files storagefolder folder listimagesource imagesources uint requestedsize 90 usingstorageitemthumbnail itemthumbnail await filesindexgetthumbnailasyncthumbnailmodepicturesview requestedsize usingirandomaccestream fstream itemthumbnailasstreamforreadasrandomaccestream bitmapimage bitmapimage new bitmapimage await bitmapimagesetsourceasyncfstream imagesourcesaddbitmapimage bitmapimage null gcaddmemorypressurelongitemthumbnailsize mainpagexamlgridview xnamephotosgrid height392 width400 itemssourcebinding margin030 selectionmodemultiple backgroundblack gridviewitemtemplate datatemplate image width90 height90 margin5 sourcebinding stretchuniformtofill datatemplate gridviewitemtemplate gridviewitemspanel itemspaneltemplate itemsstackpanel itemspaneltemplate gridviewitemspanel gridview,['c#'] +839330,java is backward compatible but why we need to upgrade many libraries when we upgrade jdk from 16 to 18 recently we upgrade the jdk version from 16 to 18 in one of my java project but there are some compilation or runtime errors so i have to upgrade some librariesgradle 19 to 110spring 3x to 4xthat because they are using some early versions of asm but which supports jdk 18 only from 5xjava said it is backward compatible but why the original versions of libraries cannot work with jdk 18 directly,['java'] +839415,how to chain multiple rxjavas groupby methods such as groupbygroupby given input1 2 3 4 5 6 7 8 9 10group the numbers by odd or even and then by less than or greater than 5expected output 1 3 5 2 4 6 8 10 7 9the order of the output is not restrictedi am now using the following approachobservablerange1 10 groupbyn and 2 0 flatmapgroupedobservableboolean integer g return observablejustgflatmapobservableutilsboolean integerflatgroupgroupbyn and 5 subscribefinal groupedobservableboolean integer g observablejustgflatmapobservableutilsboolean integerflatgroupforeachn printlng n note that observableutils is written by me to simplify the codebut i am not satisfied with it because it still not short enough to simply indicate the goal onlywhat i expected is like the followingobservablerange1 10 groupbyn and 2 0 groupbyn and 5 subscribefor now i can only shrink it toobservablerange1 10 liftnew operatorgroupbygroupn and 2 0 liftnew operatorgroupbygroupn and 5 subscribei still have to write the operatorgroupbygroup class which is a little bit complex any suggestion for improving,"['java', 'android']" +839470,using declaration as sfinae could i use sfinae or another technique for using declaration while private deriving from template classfor better understanding see code belowinclude iostreamstruct s1 void f stdcout s1fn struct s2 void f stdcout s2fn void g stdcout s2gn template class tstruct d private t using tf using tg need this only if t provides g functionint main ds1f ok prints s1f ds2f ok prints s2f ds2g fail but wants to be ok and prints s2g return 0how can i reach desired behaviour if it possible,['c++'] +839563,using latest opengl functions across classes in qt 54 i posted a question earlier on how to get opengl working on qt but now i want to be able to use the latest functions opengl has for use before qt i was using glew but qt is saying that glew is conflicting with its qtopengl header file i looked into qglwidget and qglfunctions but to be frank i am confused as to what i should really be doing in order to simply access opengls functionsnow i got qt 54 using qt creator 330 and am utilising the new qopenglwidget however lack of guidance in how it ought to be used throws me off a little the qt documentation is there and does help but it only demonstrates how to instantiate it rather than utilise it in other locations of the program i understand that this qopenglwidget functions similar to qglwidget qt details that i should be inheriting from it however i am not instantiating an opengl context within the class it wants to use opengl functions that happens in the class glwidget which inherits from qopenglwidgetfor example take this excerpt from one of my classes that uses opengl codevoid meshinit pnumindices pindicessize glgenvertexarrays1 pvao glgenbuffers1 pvertexbuffer glgenbuffers1 pindexbuffer glbindvertexarraypvao glbindbuffergl array buffer pvertexbuffer glbufferdatagl array buffer pverticessize sizeofvertex pvertices0 gl static draw etcmesh is a class that does not inherit from anything originally it only used glew so that it can get declarations of opengl functions it did not need to know whether they were valid or not since that is glews job then in the mainapp class i would be instantiating glew i also understand that there is also a qopenglfunctions class which somewhat functions similar to that of glew but with all these gl classes it is blatantly confusing to know what to use whats more is that i tried look for glgenvertexarrays but it is not found in qopenglbuffer qopenglfunctions or qopenglwidget and as far i am aware as of opengl 45 it is still part of the spec but my graphics drivers do not use opengl 45 so i use opengl 43 instead suffice it to say that i am willing to abandon glew to adopt qts own approach to calling opengl functions in a program where various classes are using opengl functions how can i utilise qt to be able to call them without the use of glew mesh is one of those classes that does not instantiate opengl but merely uses the functions thereofjust so people know i have been using qt for some time not enough though and do enjoy qt but i do need to know how i can use qt in conjunction with opengl to continue development most tutorials out there still use pre54 stuff,['c++'] +839582,upload file using spring mvc and mockmvc i have successfully uploaded a image file to webcontentresourcesuploadsimagejsp but i am facing a problem in testing this using mockmvc when i run the test case i am getting the exceptions file not found and access deniedthe controller looks like thisrequestmappingvalueaddcontacts methodrequestmethodpost public responsebody string addcontactscontactbean cbhttpservletrequest requesthttpservletresponse responserequestparamupload multipartfile file throws illegalstateexception ioexception string errorcbvalidate iferrorequals model mnew model string retmadatacb systemoutprintlncontact bean cb ifretequalsdbfail responsesetstatus500 else ifretequalsexist responsesetstatus409 else responsesetstatus200 to upload a file iffile null filegetsize 0 systemoutprintlnfile name filegetoriginalfilename string dircweb latestadmin fileupload 29 01 15webcontentresourcesuploadscbgetname cbgetid string dircuploadcbgetname cbgetid file directory new filedir if directoryexists systemoutprintlndirectory already exists else systemoutprintlndirectory not exists creating now boolean success directorymkdir if success systemoutprintfsuccessfully created new directory sn dir else systemoutprintffailed to create new directory sn dir string filename filegetoriginalfilename filetransfertonew filedirfilename return error else responsesetstatus500 return error my test case is like thispublic void testaddcontacts throws exception fileinputstream fisnew fileinputstreamcuserspublicpicturessample picturespenguinsjpg mockmultipartfile upload new mockmultipartfileupload penguinsjpg imagejpeg cuserspublicpicturessample picturespenguinsjpggetbytes mockmultipartfile upload new mockmultipartfileuploadfis mockmvc mockmvc mockmvcbuilderswebappcontextsetupwebapplicationcontextbuild mockmvcperformmockmvcrequestbuildersfileuploadaddcontacts fileupload paramsomerandom 4 paramnamedeerdad paramemail paramphone 1234567890 andexpectstatusis200my jsp file is like thistaglib uri prefixform page languagejava contenttypetexthtml charsetiso88591 pageencodingiso88591doctype html public w3cdtd html 401 transitionalen html head meta httpequivcontenttype contenttexthtml charsetiso88591 titleinsert title heretitle link relstylesheet typetextcss hrefpagecontextservletcontextcontextpathresourcescssformcss script typetextjavascript srcpagecontextservletcontextcontextpathresourcesjsjquery1jsscript script function doadd get the form values var name nameval var email emailval var phone phoneval var file documentgetelementbyiduploadfile var formdata new formdata formdataappendupload filefiles0 formdataappendnamenameval formdataappendemailemailval formdataappendphonephoneval ajax type post url addcontacts data formdata processdata false contenttype false success functionresponse errortext ifresponse infotextsuccessfully added mytableappendtrtdinput typecheckbox namecb value responsetdname tdtdemail tdtdphone tdtr addformhide else infotextresponse error function infotext errortextinternal server error statuscode 409 functionresponsestatustext infotext errortextname already exists responsestatustext 500 functionresponsestatustext infotext errortextdatabase problem responsestatustext script head body bgcolorfcc center formform action methodpost nameaddform idufile modelattributeupload classdarkmatter h1 add contacts spanplease fill all the texts in the fieldsspan h1 p label input idid typehidden label label spanyour namespan input idname typetext namename placeholderyour full name label label spanyour emailspan input idemail typetext nameemail placeholderyour email label label spanyour phonespan input idphone typetext namephone placeholderyour phone label label spanupload photospan input typefile iduploadfile acceptimage nameuploadfile label label spannbspspan input typebutton classbutton idbtn valueadd me onclickdoadd label p formform div stylecolor ff3 backgroundcolor 8ff width 100px borderradius 10px cursor pointer idsub add me div input typehidden idid br name input typetext idnamebrbr email input typetext idemailbrbr phone input typetext idphonebrbr input typebutton valueadd me onclickdoadd br center bodyhtml,['java'] +839586,recyclerview store restore state between activities i am migrating my listviews to recyclerviews with listviews i used the common technique described here to store and restore scroll position between activitieshow to do the same with recyclerviews the recyclerviewonsaveinstancestate seem to have protected access so cannot be used directly,['android'] +839601,undefined reference to stdcout shall this be the exampleinclude iostreamusing namespace stdint main cout hola moondonit throws the errorgcc c maincpp gcc o edit maino maino in function mainmaincpptext0xa undefined reference to stdcoutmaincpptext0xf undefined reference to stdbasic ostreamcharstdchar traitschar stdoperator stdchar traitscharstdbasic ostreamchar stdchar traitschar char constmaino in function static initialization and destruction 0intintmaincpptext0x3d undefined reference to stdios baseinitinitmaincpptext0x4c undefined reference to stdios baseinitinit collect2 error ldreturned 1 exit status make qs error 1also this exampleinclude iostreamint main stdcouthola moondonthrows the errorgcc c maincpp gcc o edit maino maino in function mainmaincpptext0xa undefined reference to stdcoutmaincpptext0xf undefined reference to stdbasic ostreamcharstdchar traitschar stdoperatorstdchar traitscharstdbasic ostreamcharstdchar traitschar char constmaino in function static initialization and destruction 0intint maincpptext0x3d undefined reference to stdios baseinitinitmaincpptext0x4c undefined reference to stdios baseinitinit collect2 error ldreturned 1 exit status make qs error 1note i am using debian wheezy,['c++'] +839700,does c11 14 or 17 provide a way to get just the arguments out of a decltype this question is very similar to extract just the argument type list from decltypesomefunction i am not sure the answers there work for what i am intending though i would like to be able to create a template function that deduces the type of its runtime arguments based on the type of a function pointer template argument whistlesfor an example use case let us say i want to instrument straight c posix file io using a shim library loaded with ld preload i could write separate wrappers for fopen fread fwrite fclose if all of those wrappers do similar stuff though wouldnt it be nice if i could define a template that captures the common behaviorpartial example not using templates that demonstrates how much boilerplate is involvedextern c file real fopenconst char const char nullfile fopenconst char path const char mode file returned file if real fopen null real fopen file const char const char dlsymfopen rtld next do precall instrumentation returned file real fopenpath mode do postcall instrumentation return returned fileint real fclosefile nullint fclosefile fp int retval if real fclose null real fclose intfile dlsymfclose rtld next do precall instrumentation retval real fclosepath mode do postcall instrumentation return retval additional definitions following the same general idea we can save some code using a variadic template functiontemplate typename func ptr type func ptr type real func ptr const char dl name typename argsstdresult offunc type wrap funcargs args stdresult offunc type retval if real func ptr null real func ptr func ptr typedlsymdl name rtld next do precall instrumentation retval real func ptrargs do postcall instrumentation return retvalfile real fopenconst char const char nullfile fopenconst char path const char mode return wrap funcdecltypereal fopen real fopen fopen const char const char path modeint real fclosefile nullint fclosefile fp return wrap funcdecltypereal fclose real fclose fclose file fpthere is gotta be some way we can avoid passing all of those redundant types in the list of template parameters though what i would like to do that i have not found valid syntax for yet presumes the existence of something i will call stdarguments of that is sort of like the opposite of stdresult oftemplate typename func ptr type func ptr type real func ptr const char dl name stdarguments offunc ptr typestdresult offunc type wrap funcstdarguments offunc ptr type args stdresult offunc type retval if real func ptr null real func ptr func ptr typedlsymdl name rtld next do precall instrumentation retval real func ptrargs do postcall instrumentation return retvalfile real fopenconst char const char nullfile fopenconst char path const char mode return wrap funcdecltypereal fopen real fopen fopenpath modeint real fclosefile nullint fclosefile fp return wrap funcdecltypereal fclose real fclose fclosefpis there a valid way to do this in c11 14 or 17 how or if not why not,['c++'] +839702,how to put a delay on a loop in ruby for example if i want to make a timer how do i make a delay in the loop so it counts in seconds and do not just loop through it in a millisecond,['ruby'] +839732,applying appcompat theme to individual preferences in a preferencefragment i have been wrestling with trying to get my preferencefragment to have the same materialbased theme and styling via appcompat as the rest of my application the preferencefragment that i am using to manage all of my application settings is shown belowas you can see from the screenshot above i was able to customize the preferencefragment by using coloraccent colorprimary and a few other attributes my theme for the preferencefragment is as followsstyle namesettingstheme parentthemeappcompatlightdarkactionbar item namecolorprimarycolorblue grey 500item item namecoloraccentcolorblue grey 500item item nameandroidtextcolorcolorblack text altitem item nameandroidtextcolorsecondarycolorblack secondary textitemstylehowever despite my best efforts i am unable to apply themes to the individual elements within my preferencefragment such as listpreference and edittextpreference all of the preferences still retain the standard appcompat themei found an 2 year old post that thiscusses this issue albeit with no real solution how to apply theme to preferencescreen elements of a preferencecategoryi am wondering if anyone has been able to successfully apply themes to the preferences since appcomat v21 has been released if not are there any viable workarounds that can be used to apply custom themes to individual preferences,"['java', 'android']" +839777,google cloud messaging implementation in java using mysql iam a java developer on a mac learning to write android code in android studio i have been asked to integrate google cloud messaging into an appi understand that android studio has a button that puts all the gcm required stuff into the phone tablet app however i have no idea about all the changes its making to my app along with a requirement that i not use google as the database instead i need to use a local instance of mysql since we have business logic to apply to send out messages to particular usersi have done all the google server side tasks i have my app key project keya etcwhen it comes to examples and tutorials that iave tried to find they are either dated use different terminology than what google currently uses use a language other than java for the server side examples are eclipse based use a third party library to hide functionality kii cloud or donat implement the appserver app using xmmp ccsiam looking for a straight java server implementation tutorial or example that communicates to google using xmmp and securely to the app on the phone tablet and classes that someone new to android can followiave done the activities on this page and iave followed the links under anext stepsa however they assume a level of understanding that i donat have yet this page and its links give me what configurations and settings i need but not where to put them and whywhen iam successful at this my plan is to condense all the details into a youtube tutorial on how to do this or at the very least a very detailed web page because i feel that implementing this should not be this hard especially using java tomcat mysql and an android app this seems like it would be the base case for starting off,"['java', 'android', 'mysql']" +839868,how do i access child elements within riotjs if i have a custom riot tag with a p in it like thiscustom pthis is a textpcustomhow do i access the p element from within the custom tagupdate i have received a whole bunch answers that are of ways to select it from the dom what i want is a way to select the inner p tag from within the component library riotjs itself i am looking for a more riotjs specific answer for example with polymer you use thiscontentgetthistributednodes,['javascript'] +839903,angulargooglemaps run function once after initial map load using angulargooglemaps to incorporate a google map into an appi need a command that will run a function once after initial map load is complete but only on the initial load not after each map manipulationi cannot use idle or tilesloaded since these are fired after every movementthe function i want to run needs to get map bounds to pull data off a server on initial page load i want this to occur once on initial load then be a manual function using a refresh mapcontrol if i use idle or tilesloaded to fire this it will pull server data every time a user moves the mapdoes anyone know how to fire a once off command to get map details bounds etc after initial map load i have tried putting mapsgetbounds in the 2nd promise function but it does not worknote i have got a fiddle working here i just cannot chain any more promises after the scopemap controls options etc are defined because they do not return a promisethe code example in the docs does not show how to chain a promise after the scopemap is defined htmldiv classangulargooglemapcontainer ngcontrollermainctrl uigmapgooglemap centermapcenter zoommapzoom draggabletrue optionsmapoptions eventsmapevents controlgooglemap uigmapgooglemapdivcontrollermyappcontrollermainctrl functionscope uigmapgooglemapapi uigmapgooglemapapi thenfunctionmaps scopemap center latitude 3749295 longitude 1224194155 zoom 12 events tilesloaded function maps eventname args myservicefuntionmaps this work fine but fires every time dragend function maps eventname args myservicefuntionmaps this work fine but fires every time zoom changed function maps eventname args myservicefuntionmaps this work fine but fires every time scopebounds mapsgetbounds this gives me getbounds not a function myservicefuntionmaps this gives an error return maps no promise returned here so no chance to delay the function below thenfunctionmaps is this where i need to put my function does not delay on map load since no promise returned obviously the maps object returned by the uigmapgooglemapapi promise is completely different to the maps object returned by events like tilesloaded etc quite confusing also the faq only indicates how to use tilesloaded to get the map instance which does not work for reasons already described,['javascript'] +840018,how do i access previous promise results in a then chain i have restructured my code to promises and built a wonderful long flat promise chain consisting of multiple then callbacks in the end i want to return some composite value and need to access multiple intermediate promise results however the resolution values from the middle of the sequence are not in scope in the last callback how do i access themfunction getexample return promiseaathenfunctionresulta some processing return promiseba thenfunctionresultb more processing return how do i gain access to resulta here,['javascript'] +840052,forward data from one controller action to other in yii2 is it possible to forward data from one controller action to other before the render basically i want to now if we have something that zend forward doeshere is my scenario i have payment gateway that returns data back to my controller action what i want is to handle data on seperate controlleraction but render the home page without redirection is it possible to forward control from one controlleraction to other can anybody suggest me can i go for,['php'] +840063,url rewrite in owin middleware i have a problem with url rewriting which works in globalasax but not in owin middlewareglobalasax codeprotected void application beginrequest perfectly working rewrite by route rules this resolves to the action global of the homecontroller httpcontextcurrentrewritepathhomeglobalowin middleware code used for culture detection code shortened for brevitypublic class globalizationmiddleware owinmiddleware public globalizationmiddlewareowinmiddleware next basenext public async override task invokeiowincontext context contextrequestpath new pathstringhomeglobal await nextinvokecontext i expect that global action of the controller home gets calledbut instead the default action index is calledafter the path is changed contextrequesturiabsoluteuri is httplocalhostglobalhomebut controllers requesturlabsoluteuri is still httplocalhosti even tried contextenvironmentowinrequestpath homeglobal but that doesns seem to work eitherbefore anyone asks yes i call the iappbuilderusetypeofglobalizationmiddleware in startupcs and the debugger enters the invoke methodwhat am i doing wrongediti even tried referencing systemweb and then doing thisdoes not work either systemwebroutingrequestcontext requestcontext contextenvironmentsystemwebroutingrequestcontext as systemwebroutingrequestcontextrequestcontexthttpcontextrewritepathhomeglobalsystemwebhttpcontextbase contextbase contextenvironmentsystemwebhttpcontextbase as systemwebhttpcontextbasecontextbaserewritepathhomeglobaledit 2 found a working solution see below but i am unsure whether it is the right solution comments would be appreciated,"['c#', 'asp.net']" +840076,android studio you must specify a path to genymotion folder to use this feature i have downloaded and installed the genymotion emulator plugin via the plugin wizard in android studio i am running android studio on a windows machinei am getting a warning saying that i must provide a path to genymotion folderwhere is this folder located i can not seem to find it in my android studio installation folder,['android'] +840211,why does adding to a pointer with work but pointer 1 does not i am allocating memory for an array but i am moving where the pointer points forward a little accessing the elements works fine it started to produce a problem with freeing the allocated memory though malloc complains that the pointer being freed was never allocated the problem can reproduced with this simplified codeint pointer mallocsizeofint 1freepointer 1i started experimenting and found this slight variation of the code to workint pointer mallocsizeofintpointer 1freepointer 1what is the doing different than just adding 1 to the pointer malloc returns in one line,['c'] +840218,factory pattern using variadic template i have an abstract classtemplate class t struct a virtual methods and several concrete derived classes with various constructors the constructor of b takes 1 inputtemplate class tstruct b public at b default ctor b t input initializer implement virtual methods the constructor of c takes 2 inputstemplate class tstruct c public at double some member c default ctor c t input double value initializer implement virtual methodsi created a factory that returns pointers to a and i am trying to use variadic templates to forward inputs to the constructor of the selected derived class it is working fine but i had to duplicate the code for the cases withwithout constructor inputs and i am looking for a way to prevent code duplication see below template class tstruct a factory typedef stdshared ptra out type version without constructor inputs static out type create id type id out type out switch id select the derived class case type b outreset new b break return out version with constructor inputs template class args static out type create id type id args args out type out switch id select the derived class case type b outreset new b stdforwardargsargs break return out very sorry for the long question any suggestion to make this shorter appreciated,['c++'] +840270,trouble installing nokogiri on mac os x yosemite v10101 because of libxml2 while upgrading to rails 420 i am trying to install rails 420 on my computer but i am having issues installing nokogiri i followed the steps in the first answer for bundle install stopped at nokogiri but when i run brew install nokogiri i get the followingactivating libxslt 1128 from usersdseibertrvmrubiesruby220librubygems220gemsnokogiri1662portsx86 64appledarwin1400libxslt1128checking for main in llzma yeschecking for xmlparsedoc in libxmlparserh nochecking for xmlparsedoc in lxml2 nochecking for xmlparsedoc in llibxml2 nolibxml2 is missing please locate mkmflog to investigate how it is failing extconfrb failed could not create makefile due to some reason probably lack of necessarylibraries andor headers check the mkmflog file for more details you mayneed configuration optionsprovided configuration options withoptdir withoptinclude withoutoptincludeoptdirinclude withoptlib withoutoptliboptdirlib withmakeprog withoutmakeprog srcdir curdir rubyusersdseibertrvmrubiesruby220binruby base name help clean usesystemlibraries enablestatic thisablestatic withzlibdir withoutzlibdir withzlibinclude withoutzlibincludezlibdirinclude withzliblib withoutzliblibzlibdirlib enablecrossbuild thisablecrossbuild withxml2lib withoutxml2lib withlibxml2lib withoutlibxml2libextconf failed exit code 1gem files will remain installed in usersdseibertrvmrubiesruby220librubygems220gemsnokogiri1662 for inspectionresults logged to usersdseibertrvmrubiesruby220librubygems220extensionsx86 64darwin14220nokogiri1662gem makeouti cant find the mkmf file to locate the details of my libxml2 file and i do not see either the libxml2 file or the nokogiri folder within my ruby source folderand when i run brew install libxml2 i get warning libxml2292 already installedfollowing the comment i got the response successfully installed nokogiri1662 but when i ran sudo gem install rails i got back the above error again,['ruby-on-rails'] +840323,how to perform an async task against es6 generators in loop i understand how to use generators to make async code look nice i have a simple generator all that takes a page will return a single valuethen i have another generator alldo that will use all for pages 1 to 30 and for each result do some async taskthen i have another generator allbatchdo that will batch 3 pages and do some async taskfunction mockpromisevalue return promisefunctionresolve reject resolvevalue function allpage var ls yield mockpromisepage page do all kinds of promises return yield lsfunction alldotask var page 1 while true var res yield allpage res yield taskres if page 30 break page function allbatchdotask var page 1 var arr while true var res yield allauthor page arrpushres if arrlength 3 yield taskarr arr if page 30 break page function logtaskres return mockpromiseresthenfunctionv consolelogv example use of these generators would be return a single page promiseasyncall1thenfunctionvalue consolelogvalue do logtask for all pages 1 thru 30asyncalldologtask do logtask for all pages with batches of 10asyncallbatchdologtaskthe question is is this a legitimate use of es6 async features or is there an abstract builtin solution for my use case,['javascript'] +840548,is that ok to use the mro in order to override a mixin problem description i have a class c inheriting from mixins a and bi want a new class c having all the methodsattributes defined in the class c but with b swapped with b same api in the inheritance scheme one possible use of this is easy mocking all classes are new style classesi got what i wanted by messing with the inheritance order therefore the mroa b b b a b c c c1 c2c1cb c2b cc1 mro c1 c a b b objectc2 mro c2 b c a b objectthe c2 method inheriting the modified mixin before the c class works without much surprise and if i call a method defined in the b mixin the b s definition is chosenfor the moment it works but i feel like fingers crossed i hope a special case does not arise and break the system the question is is it a finallynotsowrong way to solve the problem or is there a better way to do it ps i think i could take my bazooka and create a metaclass to redefine the mro as said in the official doc but my instinct says it is not going to be necessarily prettier,['python'] +840602,adding underline attribute to partial text uilabel in storyboard how can i underline partial text of uilabel using only storyboard i am able to do this in code and i am able to underline the entire text of a label but not just one or two words in the string,['ios'] +840931,splines with python using control knots and endpoints i am trying to do something like the following image extracted from wikipediausrbinenv pythonfrom scipy import interpolateimport numpy as npimport matplotlibpyplot as plt samplingx nplinspace0 10 10y npsinx spline trough all the sampled pointstck interpolatesplrepx yx2 nplinspace0 10 200y2 interpolatesplevx2 tck spline with all the middle points as knots not working yet knots x11 it should be something like thisknots nparrayx1 not working with above line and just seeing what this line doesweights npconcatenate1nponesxshape02011tck interpolatesplrepx y tknots wweightsx3 nplinspace0 10 200y3 interpolatesplevx2 tck plotpltplotx y go x2 y2 b x3 y3rpltshowthe first part of the code is the code extracted from the main reference but it is not explained how to use the points as control knotsthe result of this code is the following image the points are the samples the blue line is the spline taking into account all the points and the red line is the one that is not working for me i am trying to take into account all the intermediate points as control knots but i just cannot if i try to use knotsx11 it just does not work i would appreciate any helpquestion in short how do i use all the intermediate points as control knots in the spline functionnote this last image is exactly what i need and it is the difference between what i have spline passing all the points and what i need spline with control knots any ideas,['python'] +840946,what is the risk of numerical instabilities when predividing denominators supposing i want to divide one number into manya xb xc xsince multiplication is faster the temptation is to do thistmp 10f xa tmpb tmpc tmp1 is this guaranteed to produce identical answers i suspect not but some confirmation would be nice2 if x is extremely large or extremely small i expect this could cause a significant loss of accuracy is there a formula which will tell me how much accuracy i will sacrifice3 perhaps there is no convenient formula but can we at least state a rule of thumb for when numerical instabilities will be an issue is it to do with the magnitudes of the operands or the difference between the magnitudes of the operands perhaps,['c'] +841025,how to add a simple user roles aspnet mvc c i am pretty new to aspnet mvc and i have been looking at a lot of different ways of adding user rolesfor my asp mvc site i want to use the users databases that are automatically made for you when you make a new mvc projectthat contain the tablesaspnetrolesaspnetuserclaimsaspnetuserloginsaspnetuserrolesaspnetusersi have been looking at a few tutorials and it is a bit of a mindfield for beginners i thinkall i want to be able to do is something like thisauthorizeroles adminpublic actionresult index return viewso users with the role admin can access the index pageall help appreiciated,"['c#', 'asp.net']" +841195,authorization not working in aspnet mvc 5 thisclaimer this is my first time with aspnet mvc 5i have no idea why it does not work i cannot get my mvc5 app to authorize users i have done this in previous versions 2 3 and 4 but i cannot seem to make it work in owini am using local iis with the needed features enablededit i am using ssl on iis and requirehttps at cthis is the codeprotected void application start globalfiltersfiltersaddnew authorizeattributestartupauthcsappusecookieauthenticationnew cookieauthenticationoptions authenticationtype defaultauthenticationtypesapplicationcookie loginpath new pathstringadminaccountloginappuseexternalsignincookiedefaultauthenticationtypesexternalcookieappusegoogleauthenticationeven though i am using global authorize i tried to force it to see if this was the problempublic class homecontroller controller authorize public actionresult index return view no lucki am not sure it was necessary with owin but i even tried enabling forms authenticationauthentication modeforms edit 2well i found out the problem iis finally now would anyone know how to fix that do i need anything special to run owin on iis i can work now but soon i will have to deploy the app and will probably run into the same problem in the serveri have already read thesehow do you loginauthenticate a user with aspnet mvc5 rtm bits using aspnetidentityauthorize attribute not working mvc 5any ideas,['c#'] +841257,creating persistent search bar in android i want a search box which sits on top of the layout like thisi do not know whether i have to build it myself from scratch using text boxes white frames etc or there is already a builtin widget or an open source work actually designing everything from scratch does not seem to me right because by doing so i would have a incompatible view or user experience in future android apis what are the options available and what is the most adopted approach,['android'] +841452,what is the best smart pointer return type for a factory function with respect to smart pointers and new c14 features i am wondering what the bestpractice return values and function parameter types would be for classes that have these facilitiesa factory function outside of the class that creates objects and returns them to users of the class for example opening a document and returning an object that can be used to access the contentutility functions that accept objects from the factory functions use them but do not take ownership for example a function that counts the number of words in the documentfunctions that keep a reference to the object after they return like a ui component that takes a copy of the object so it can draw the content on the screen as neededwhat would the best return type be for the factory functionif it is a raw pointer the user will have to delete it correctly which is problematicif it returns a unique ptr then the user cannot share it if they want toif it is a shared ptr then will i have to pass around shared ptr types everywhere this is what i am doing now and it is causing problems as i am getting cyclic references preventing objects from being destroyed automaticallywhat is the best parameter type for the utility functioni imagine passing by reference will avoid incrementing a smart pointer reference count unnecessarily but are there any drawbacks of this the main one that comes to mind is that it prevents me from passing derived classes to functions taking parameters of the baseclass typeis there some way that i can make it clear to the caller that it will not copy the object ideally so that the code will not compile if the function body does try to copy the objectis there a way to make it independent of the type of smart pointer in use maybe taking a raw pointeris it possible to have a const parameter to make it clear the function will not modify the object without breaking smart pointer compatibilitywhat is the best parameter type for the function that keeps a reference to the objecti am guessing shared ptr is the only option here which probably means the factory class must return a shared ptr also righthere is some code that compiles and hopefully illustrates the main pointsinclude iostreaminclude memorystruct document stdstring contentstruct ui stdshared ptrdocument doc this function is not copying the object but holding a reference to it to make sure it does not get destroyed void setdocumentstdshared ptrdocument newdoc thisdoc newdoc void redraw do something with thisdoc this function does not need to take a copy of the document so it should access it as efficiently as possible at the moment it creates a whole new shared ptr object which i feel is inefficient but passing by reference does not work it should also take a const parameter as it is not modifying the objectint charcountstdshared ptrdocument doc i realise this should be a member function inside document but this is for illustrative purposes return doccontentlength this function is the same as charcount but it does modify the objectvoid appendtextstdshared ptrdocument doc doccontentappendhello return create a derived type that the code above does not know aboutstruct textdocument public document stdshared ptrtextdocument createtextdocument return stdshared ptrtextdocumentnew textdocumentint mainvoid ui thisplay use the factory function to create an instance as a user of this class i do not want to have to worry about deleting the instance but i do not really care what type it is as long as it does not stop me from using it the way i need to auto doc createtextdocument share the instance with the ui which takes a copy of it for later use thisplaysetdocumentdoc use a free function which modifies the object appendtextdoc use a free function which does not modify the object stdcout your document has charcountdoc charactersn return 0,['c++'] +841496,jquery interface file for flow static type checker for javascript from facebook in nov 2014 3 months ago facebook opensourced a new command line tool a static type checker called flow now i want to run it on a few of my older existing javascript files these contain references to the jquery library my js files were not written with static typechecking in mindhowever after including flow at the top of the file when i run flow with this command flow myfilejs resultvarwmyfilejs701217 identifier jqueryunknown global namefound 1 erroras i understand it the way to include jquery into flows type checking process is to create an interface file has anyone done this yet for the jquery library i use jquery 19,"['javascript', 'jquery']" +841550,what is the right screen size and density configuration of nexus 6 my app does not list nexus 6 as a supported device in google play consolei read the blog post getting your apps ready for nexus 6 and nexus 9 which saysnexus 6 has a quantized density of 560 dpi which falls in between the xxhdpi and xhdpi primary density bucketsthere is a paragraph exactly about my problemmake sure you are not filtered on google playif you are using the element in the androidmanifestxml file you should stop using it because itas not scalable to recompile and publish your app each time new devices come out however if you must use it make sure to update the manifest to add the configuration for these devices by screen size and density otherwise your app may be excluded from google play search results on these deviceswell i have to use compatiblescreens because i am trying to exclude my app from tabletsmy current compatiblescreens element in manifest looks likecompatiblescreens small size screens screen androidscreendensityldpi androidscreensizesmall screen androidscreendensitymdpi androidscreensizesmall screen androidscreendensityhdpi androidscreensizesmall screen androidscreendensityxhdpi androidscreensizesmall screen androidscreendensity480 androidscreensizesmall normal size screens screen androidscreendensityldpi androidscreensizenormal screen androidscreendensitymdpi androidscreensizenormal screen androidscreendensityhdpi androidscreensizenormal screen androidscreendensityxhdpi androidscreensizenormal screen androidscreendensity480 androidscreensizenormal screen androidscreendensity640 androidscreensizenormal compatiblescreenswhat is the right configuration for nexus 6i have tried screen androidscreendensity560 androidscreensizenormal screen androidscreendensity480 androidscreensizelarge screen androidscreendensity560 androidscreensizelarge screen androidscreendensity640 androidscreensizelarge but none of it seems to do the trick,['android'] +841574,inserting analytic data from spark to postgres i have cassandra database from which i analyzed the data using sparksql through apache spark now i want to insert those analyzed data into postgresql is there any ways to achieve this directly apart from using the postgresql driver i achieved it using postrest and driver i want to know whether there is any methods like savetocassandra,['java'] +841748,how to include images and tables in textfields when exporting to pdf is there a way to include images and tables in textfields with markuphtml when exporting a pdf using jasperreportswhen i add a textfield with markuphtml to my report basic html support is provided out of the box egtextfield reportelement textelement markuphtml textfieldexpressioncdatahtmlsome bboldb texthtmltextfieldexpressiontextfieldhowever more complex html seems not to be supported if i got that right one would have to write a custom markupprocessor to transform the incoming html to jrxml and plug it into the jasperreports engine to handle more complex examplessince we use a ckeditor to handle the input the list of used tags should be manageable secondly we already use jsoup to parse and cleanup html which might be useful implementing the markupprocessoris there an example i could build on as i said i am mainly looking for image img and table table tr td supportif not is there an alternative to achieve this using jasperreports,['html'] +841757,send uiimage to localwebserver using gcdwebserver my app using gcdwebserver i get a photo from my iphone album by using assetslibrary and i store them in nsdocumentdirectory i just want to get access url to this photo to show them in a web page there is my code webserver addhandlerformethodpost path requestclassgcdwebserverurlencodedformrequest class processblockgcdwebserverresponse gcdwebserverrequest request alasset asset selfarraypictures objectatindex0 alassetrepresentation rep asset defaultrepresentation cgimageref iref rep fullresolutionimage uiimage thumbnail uiimage imagewithcgimageiref nsstring path if thumbnail nil nsarray paths nssearchpathfordirectoriesindomainsnsdocumentdirectory nsuserdomainmask yes nsstring documentsdirectory paths objectatindex0 path nsstring alloc initwithstringdocumentsdirectory stringbyappendingpathcomponenttestpng nsdata data uiimagepngrepresentationthumbnail data writetofilepath atomicallyyes nsurl url nsurl fileurlwithpathpath nsstring html nsstring stringwithformathtmlbodyimg src width400 height500bodyhtml url return gcdwebserverdataresponse responsewithhtmlhtml,"['ios', 'objective-c']" +841767,androidosmessagequeuenext taking up the plurality of exclusive time is this normal behavior i have recently run a method tracing session on the process of opening a fragmentactivity that takes about 75010ms to open from the previous activity and has a listview into which it loads its initial batch of data in times that vary from as low low as 1500ms to as high as 50ms after sorting by exclusive time i noticed that a method named androidosmessagequeuenext is taking up the plurality of the timea view of all the main thread after a method tracing session notice androidosmessagequeuenext is first in the listnow my question is as such is this standard operating procedure in an android appthat is does androidosmessagequeuenext refer to the main queue waiting for another operation or alternately could this indicate some sort of temporary deadlock should i be worried,['android'] +842051,object does not support this property or method rails windows 64bit i installed rails on my surface pro 3 and run into this error after trying to view a page i have tried several suggestions such as installing rubyracer with libv8 but it did not helptypeerror object does not support this property or method in crailsinstallerruby200librubygems200gemsturbolinks253libassetsjavascriptsturbolinksjscoffeehere is my gemfilesource bundle edge rails instead gem rails github railsrailsgem rails 418 use sqlite3 as the database for active recordgem sqlite3 use scss for stylesheetsgem sassrails 403 use uglifier as compressor for javascript assetsgem uglifier 130 use coffeescript for jscoffee assets and viewsgem coffeerails 400 see for more supported runtimesgem therubyracer platforms ruby use jquery as the javascript librarygem jqueryrails turbolinks makes following links in your web application faster read more gem turbolinks build json apis with ease read more gem jbuilder 20 bundle exec rake docrails generates the api under docapigem sdoc 040 group docgem libv8 316147 use activemodel has secure password gem bcrypt 317 use unicorn as the app server gem unicorn use capistrano for deployment gem capistranorails group development use debugger gem debugger group development test windows does not include zoneinfo files so bundle the tzinfodata gemgem tzinfodata platforms mingw mswingem twitterbootstraprails git gitgithubcomseyhunaktwitterbootstraprailsgitgem fontawesomerailsgem simple formgem devise,"['javascript', 'ruby-on-rails']" +842289,create ice cold taskcompletionsource i am writing a library which includes scheduling functionality not the standard taskscheduler ischeduler based on net tasks i am using taskcompletionsource and taskstatus is critical for representing the status of underlying operations including taskstatuscreated ie created but not yet started i know returned tasks should normally be hot but for my manually controlled proxy tasks i really do want them initially as createdunfortunately for me the initial status of taskcompletionsourcetask is waitingforactivation ie it is already gone past created put differently taskcompletionsource supports two states but i need three statesquestion how can i get a task that i can manually set to three different states ie taskstatus can be set to 1 created2 one of waitingforactivationwaitingforchildrentocompletewaitingtorunrunning3 either of rantocompletioncanceledfaultedthe code below understandably complains about the type mismatch i can instead wrap the task by changing new tasktresult to new tasktasktresult but to get back to tasktresult i have to unwrap it and the unwrapped task will have status waitingforactivation bringing me back to square onei will have a large number of these so blocking a thread with wait for each is not an optioni have considered inheriting from task and overriding members using new but if possible it would be nice to give the library user an actual task instead of a derivedtask especially since i present regular tasks to also be awaited in many other placesideasprivate taskcompletionsourcetresult tcsprivate async tasktresult createstartcompleteasync await tcstask if tcstaskiscanceled throw new operationcanceledexception else if etcpublic coldtaskcompletionsource tcs new taskcompletionsourcetresult task new tasktresult createstartcompleteasyncerrors cannot convert lambda expression to delegate type systemfunc because some of the return types in the block are not implicitly convertible to the delegate return type cannot implicitly convert type systemthreadingtaskstask to tresult,"['c#', '.net']" +842366,why is vc unable to optimize an integer wrapper in c i am trying to write a wrapper around a 64 bits integer my expectation is that if written correctly and all methods are inlined such a wrapper should be as performant as the real type answer to this question on so seems to agree with my expectationi wrote this code to test my expectation class bprivate uint64 t vpublic inline b inline buint64 t v vv inline b operatorb rhs v rhs v return this inline b operatorb rhs v rhs v return this inline operator uint64 t const return v int mainint argc char argv typedef uint64 t typedef b t const unsigned int x 10 utilsctimer timer timerstart t sum 0 for unsigned int i 0 i 100 i for uint64 t f 0 f x f sum f float time timergetseconds cout sum endl time seconds endl return 0when i run this with typedef b t instead of typedef uint64 t t the reported times are consistently 10 slower when compiled with vc with g the performances are same if i use the wrapper or notsince g does it i guess there is no technical reason why vc can not optimise this correctly is there something i could do to make it optimize iti already tried to play with the optimisations flag with no success,['c++'] +842532,difference between java options java tool options and java opts i thought it would be great to have a comparison between java options and java tool optionsi have been searching a bit for one but i cannot find anything so i hope we can find the knowledge here on stackoverflowjava opts is included for completeness it is not part of the jvm but there is a lot of questions about it out in the wildwhat i knowso far i have found out thatjava opts is not used by the jdk but by a bunch of other apps see this postjava tool options and java options are ways to specify jvm arguments as an environment variable instead of command line parameters the are picked up by at least java and javacthey have this precedence java options overwrites the otherscommand line parametersjava tool options is overwritten by the otherswhat i would like to knoware there any official documentation comparing java tool options and java optionsare there any other differences between java tool options and java options except from precedencewhich executables pick up java tool options and java options in addition to java and javacany limitation on what can be included on java tool options and java optionsofficial documentationi have not been able to find any documentation about java options the documentation for java tool options does not shed much light on the differencesince the commandline cannot always be accessed or modified for example in embedded vms or simply vms launched deep within scripts a java tool options variable is provided so that agents may be launched in these cases example scriptthis is the code i used to figure this out console output is included as commentsexport java optsfoobarexport java tool options export java optionsxmx512m xms64mjava version picked up java tool options picked up java options xmx512m xms64m java version 170 40openjdk runtime environment icedtea 241 suse3411x86 64openjdk 64bit server vm build 240b50 mixed modejavac version picked up java tool options picked up java options xmx512m xms64m javac 170 40export java tool optionsxmx1 xms1export java optionsxmx512m xms64mjavac version picked up java tool options xmx1 xms1 picked up java options xmx512m xms64m javac 170 40export java tool optionsxmx512m xms64mexport java optionsxmx1 xms1javac version picked up java tool options xmx512m xms64m picked up java options xmx1 xms1 error occurred during initialization of vm too small initial heapexport java tool optionsxmx1 xms1export java optionsjava xmx512m xms64m version picked up java tool options xmx1 xms1 picked up java options java version 170 40 openjdk runtime environment icedtea 241 suse3411x86 64 openjdk 64bit server vm build 240b50 mixed modeexport java tool optionsexport java optionsxmx1 xms1java xmx512m xms64m version picked up java tool options picked up java options xmx1 xms1 error occurred during initialization of vm too small initial heap,['java'] +842581,is there a way to use php websocket in heroku it seems by default there is only support for other technologies i have made a chat room app i tested locally and it works but when i deploy it to heroku there is a connection refuse error i saw that heroku now support websocket but it seems it is only for all supported technologies but php,['php'] +842938,how can i use my sql knowledge with cloudantcouchdb some developers who have a good knowledge of querying sql databases struggle to implement the equivalent query patterns in cloudantcouchdbhow can these developers translate their sql knowledge to cloudantcouchdb,['sql'] +842969,how to make my phonegap android app crash i am developing a crash reporter plugin for phonegap android apps for the testing purpose i have to make my application crash unfortunately application has stopped window has to be invoked when i make an unhandled exception in the javascript the app is not crashing instead its showing the same screen i made the app screen stop respond to user input by executing some infinite loop in javascript waited around 1 hour still the app was not crashing is the phonegap library by default handling the exceptions how i can make my app crash by making exception in javascript level i tried the below codeadded a java method to generate crash in the cordovaactivity class public static void generatecrash int a 0 int b 10 int c ba the app is crashing when i call this method from java from the oncreate in the activity class but when i invoke the same method from the javascript using plugin the app is not crashing i want my app to crash by callinginvoking some function from the javascript,['javascript'] +843040,how to prevent multiple event on same uibutton in ios i want to prevent continuous multiple clicks on the same uibuttoni tried with enabled and exclusivetouch properties but it did not work such asibaction buttonclickidsender buttonenabled false uiview animatewithduration10 delay00 optionsuiviewanimationoptionallowanimatedcontent animations code to execute completionbool finished code to execute buttonenabled true,['ios'] +843091,how to handle datetime between php laravel api and javascript angularjs i am utterly stuck trying to make php api exchange dates with angular frontendfrom php to js i seem to have it sorted since laravel handles dates through carbon i just added carboncarbonsettostringformatc to aphp which makes dates come out in iso 8601php example20150204t0053510200angularjs date filter also seems to understand this format well and even reads the timezone correctlywhat i have yet to get working is posting js date objects back to php apijs example20150205t130zjavascript date format ends up with milliseconds added to the string and in default configuration carbon complains about trailing dataalso browsers seem to automatically translate my dates into utc timemanually using new carbonjsdatestring seems to work at first but on closer inspection timezone data is not consideredso my question is what would be the best and most automatic solution to send dates back to laravel php api from angularjs frontend,"['javascript', 'php']" +843114,android studio java home does not point to a valid jvm installation having trouble firing up android studio get the following message the environment variable java home with the value of cprogram filesjavajdk180 31 does not point to a valid jvm installation the problem is that as far as i can tell the environment variable i set up is pointing to a valid install i have tried everything from renaming it to jdk home to pointing it to all the sub directories in the jdk folder to uninstalling and reinstalling java and android studio about 3 time i have triple checked that i have 64 bit java installed and that my computer is 64 bit pretty much at the end of my rope here help would be appreciated big time heres a screen cap of my windows you might spot something obvious i have not,"['java', 'android']" +843280,how do i play a des encrypted file using exoplayer i am using exoplayer to play media filesmp4s h264 encoded from the sd card of a device some of the files are des encrypted i can decrypt the files and get back an inputstream but then i am unsure of how to play this inputstream using exoplayer any help would be appreciated protected void playvideofile file inputstream is if filegetnameendswithdes is filemanagerdecryptfilefile what to do with this input stream uri uri uriparsefilegetabsolutepath if mplayer null mplayerrelease mplayer new videoplayergetrendererbuilderuri mplayeraddlistenerthis if mlastposition 0 mplayerseektomlastposition mplayerprepare mplayersetsurfacemsurface mplayersetplaywhenreadytrue,"['java', 'android']" +843316,why does a generic class implementing a generic interface with type constraints need to repeat these constraints let us say i have a following c interfacepublic interface iinterfacet where t someclass void interfacemethodand someclass is defined as followspublic class someclass public void somemethodnow i would like to define the implementation of the interface which would not compilepublic class interfaceimplt iinterfacet public void interfacemethod t test defaultt testsomemethod gives error before i change it topublic class interfaceimplt iinterfacet where t someclass public void interfacemethod t test defaultt testsomemethod compiles fine wouldnt it make sense that the type constraints are also inherited not the right word i know from the interface,"['c#', '.net']" +843326,implementing oauth2 login fatal error class google service not found i am updating my websites login system from lightopenid to googles oauth 20when i require the clientphp and the serviceoauth2php i get an errorfatal error class google service not found in homemynamereposwebsite currentlibgoogleapiphpclientsrcgoogleserviceoauth2php on line 32the code i am using from my loginphp file looks like thisrequire oncedirname serverdocument rootlibautoloadphprequiregoogleclientphprequiregoogleserviceoauth2phpecho exitexiti have added the include path in the phpini in etcphp5apache2phpini asinclude path usrlocallibphphomemynamereposwebsite currentlibgoogleapiphpclientsrcso its seems my oauth2php file cannot see any of the other includes including the class google service which is one folder up in servicephpmy folder structure looks like thislib autoloadphp functionsphp googleapiphpclient src google etc etcpublic html login loginphpi have no idea why this is occuring the include path should be seen and shows up as an included path using phpinfo can someone please give me some insight,['php'] +843507,java local reference over instance variable while going through the libgdx source code for a stage i encountered this segmentpublic void draw camera camera viewportgetcamera cameraupdate if rootisvisible return batch batch thisbatch if batch null batchsetprojectionmatrixcameracombined batchbegin rootdrawbatch 1 batchend if debug drawdebuglink on githubwhat interested me was this line batch batch thisbatchmy first guess was some caching improvement am i right or is there another reason to avoid using the instance variable directly,['java'] +843737,detect bluetooth le devices in android i am a beginner in android app development i have tried reading the documentation but am getting nowhere functions in androids tutorial such as startlescan have been deprecated etcis there a simple function that returns a list of bluetooth devices something like getdevices list of devices thank you,['android'] +843775,custom deployment to azure websites i recently started using gulpjs to package all my css and javascript into single files which i then include in my web app my web app is written in python using flaski obviously do not want to track the gulp output css and js files using git since they are build output filesi deploy my website to azure websites using push to deploy that is i simply run git push azure master and azure automatically figures out that i am using python sets up virtualenv installs pip dependencies and so on this article describes how to set this upthis process works great but now that i have started using gulp i want to ensure that the concatenated javascript and css files are also produced on the server side whenever i deploy the websitemoreover in the future i would like to have azure run all the tests upon deployment and only successfully deploy if they all pasadly i have yet to find a satisfying solution for this workflow since i cannot add custom steps to azures automatic deployment processi have tried writing a custom deployment script using kudu as suggested by this blog post but doing so thisables all the automatic steps azure normally does running azure site deploymentscript python only generates a very basic kudu deployment file which does not handle reading in the webconfig file setting up virtualenv or installing the dependencies i found no documentation regarding how to do this myself i have use the default automatic azure deployment script which gets generated serverside when i push the code so i cannot access it myself because otherwise stuff like virtualenv and pip dependencies are not handledis there any workaround available so that i may customize my deployment script eg to run gulp while still correctly deploying flask,['python'] +843873,phimagemanagerrequestimageforasset returns nil when creating thumbnail for video for some videos the requestimageforasset completes with a uiimage that is nil for other videos it works fine and i have not figured out why yet func createthumbnailforvideovideo phasset futurensurl let promise promisensurl let options phimagerequestoptions optionssynchronous true imagemanagerrequestimageforassetvideo targetsize cgsizemake640 640 contentmode aspectfill options options imageuiimage info void in if image nil printlnerror could not create thumbnail for video promiseerrormyerrorsvideothumb else if let thumburl selfsavephotoastemporaryfileimage promisesuccessthumburl else promiseerrormyerrorsvideothumb return promisefuturei also get back the info for the request but i do not know how to interpret the informationphimageresultisdegradedkey 0 phimageresultwantedimageformatkey 4037 phimageresultisplaceholderkey 0 phimageresultisincloudkey 0 phimageresultdeliveredimageformatkey 9,['ios'] +843912,play framework use in memory h2 database for unit tests i am trying to configure my play framework application so that it uses a mysql database when running and a in memory database for the testswhen i run the tests it connects to the mysql database and not the in memory databaseanyone know whythis is my configdbdefaultdrivercommysqljdbcdriverdbdefaulturljdbcmysqllocalhostcommunityrootscharacterencodingutf8dbdefaultuserrootdbdefaultpassword dbtestdriverorgh2driverdbtesturljdbch2memplaymodemysqldbtestusersadbtestpasswordthis is my testrunningfakeapplicationinmemorydatabasetest new runnable public void run new user bob secretsave assertnotnulluserauthenticate secret assertnulluserauthenticate badpassword assertnulluserauthenticate secret,"['java', 'mysql']" +843930,forwarding initializer list expressions initializer list expressions are really convenient for initializing c containersstdvectorint123but it seems that a braceenclosed initializer list expression like 123 will only bind to a function that takes a stdinitializer listint it does not seem to bind to a universal forwarding referencetemplate class tvoid foot v stdvectorintstdforwardtv int main foo123this outputstest2cpp116 note templateclass u void fooutest2cpp116 note template argument deductionsubstitution failedtest2cpp3313 note could not deduce template parameter auathis was the result with gcc 472this unfortunately means we cannot forward an initializer list expression since it would be very convenient to do that i would like to ask why is it that this does not work why cannot a brace enclosed initializer list expression bind to a forwarding reference or is this allowed and perhaps my compiler is just too old,['c++'] +843957,css flex last and first item in a row selector i am having a problem trying to select the last element of the first row and the first element of the last row of a flex containermy flex container is flexwrap wrap and all my elements are flex auto and they have different sizes and by flex auto i let the elements fit like justify on my container and my corner elements have their respective corner roundedbut the problem is i am hiding and showing the elements with events like on click and i need to set the corners elements rounded every time it changes if it has a grid container i could pick by nthchild because it never change the number of columns but in the flex have a different number of elements per rowi came up with a jquery solution link down bellow but i think it is to ogle and big may have a smarter way or a simple selector i cant useplease help me to came up with a better code so not just me cant make a good use of iteditjust improved a bit the code,"['javascript', 'jquery', 'html', 'css']" +843985,embed an svg in a bootstrap popover is there any way to embed an svg in a bootstrap 3 popover i can get the html to work in a popover like thisvar mytext here is some textmyelementpopover container body content mytext placement right html truewhat i would really like to do is to programmatically create the svg inside a function like thismyelementpopover container body content function add a new div mypopoverdiv then build an svg here by appending onto the newly created mypopoverdiv placement right html trueis it possible to create a svg inside a popover,"['javascript', 'jquery']" +843996,how to set contenttype for the file in multipart upload when using resttemplate from a rest client the file i am trying to upload will always be a xml file i want to set the contenttype as applicationxml here is my code multivaluemapstring object parts new linkedmultivaluemapstring object partsaddsubject some info bytearrayresource xmlfile new bytearrayresourcestringwithxmlcontentgetbytesutf8 override public string getfilename return documentname partsaddattachment xmlfilesending the request using resttemplate template the request is successfull string result templatepostforobjectgetresturi httpentitystringclass but the contenttype of file is applicationoctetstreamthe raw request looks like this contenttype multipartformdataboundarygbtw7zjbcdbhiecrqdx81dvtffaotehheqgmlz useragent java170 67 host somehost connection keepalive contentlength 202866 gbtw7zjbcdbhiecrqdx81dvtffaotehheqgmlz contentthisposition formdata namesubject contenttype textplaincharsetiso88591 contentlength 19 some info gbtw7zjbcdbhiecrqdx81dvtffaotehheqgmlz contentthisposition formdata nameattachment filenamefilenamexml contenttype applicationoctetstream contentlength 201402 xml file contents here the contenttype of the file is being generated as applicationoctetstream where as i want it to be applicationxml how can i set the content type for the file,['java'] +844012,android parse string to date unknown pattern character x i have service fetch date string from web and then i want to pare it to date object but somehow application crashesthis is my string that i am parsing 20150205t0520020onstartcommandstring datetime 20150205t0520020date new date stringtodatedatetimestringtodateprivate date stringtodatestring s dateformat df new simpledateformatymmddthhmmssx try return dfparses catchparseexception e eprintstacktrace return nulogcat0206 203702008 eandroidruntime28565 fatal exception main0206 203702008 eandroidruntime28565 process comdotmavrunescapenotifier pid 285650206 203702008 eandroidruntime28565 javalangruntimeexception unable to start service comdotmavrunescapenotifiergeservice384655b5 with intent cmpcomdotmavrunescapenotifiergeservice javalangillegalargumentexception unknown pattern character x0206 203702008 eandroidruntime28565 at androidappactivitythreadhandleserviceargsactivitythreadjava28810206 203702008 eandroidruntime28565 at androidappactivitythreadaccess2100activitythreadjava1440206 203702008 eandroidruntime28565 at androidappactivitythreadhhandlemessageactivitythreadjava13760206 203702008 eandroidruntime28565 at androidoshandlerthispatchmessagehandlerjava1020206 203702008 eandroidruntime28565 at androidoslooperlooplooperjava1350206 203702008 eandroidruntime28565 at androidappactivitythreadmainactivitythreadjava52210206 203702008 eandroidruntime28565 at javalangreflectmethodinvokenative method0206 203702008 eandroidruntime28565 at javalangreflectmethodinvokemethodjava3720206 203702008 eandroidruntime28565 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava8990206 203702008 eandroidruntime28565 at comandroidinternaloszygoteinitmainzygoteinitjava6940206 203702008 eandroidruntime28565 caused by javalangillegalargumentexception unknown pattern character x0206 203702008 eandroidruntime28565 at javatextsimpledateformatvalidatepatterncharactersimpledateformatjava3140206 203702008 eandroidruntime28565 at javatextsimpledateformatvalidatepatternsimpledateformatjava3030206 203702008 eandroidruntime28565 at javatextsimpledateformatinitsimpledateformatjava3560206 203702008 eandroidruntime28565 at javatextsimpledateformatinitsimpledateformatjava2490206 203702008 eandroidruntime28565 at comdotmavrunescapenotifiergeservicestringtodategeservicejava680206 203702008 eandroidruntime28565 at comdotmavrunescapenotifiergeserviceonstartcommandgeservicejava440206 203702008 eandroidruntime28565 at androidappactivitythreadhandleserviceargsactivitythreadjava28640206 203702008 eandroidruntime28565 9 moreedit ondestroy set alarm for periodical updatealarmmanager alarm alarmmanagergetsystemservicealarm servicealarmset alarmmanagerrtc wakeup systemcurrenttimemillis 10 60 pendingintentgetservicethis 0 new intentthis geserviceclass 0,"['java', 'android']" +844030,spring programmatically generate a set of beans i have a dropwizard application that needs to generate a dozen or so beans for each of the configs in a configuration list things like health checks quartz schedulers etcsomething like thiscomponentclass mymodule inject private myconfiguration configuration bean lazy public quartzmodule quartzmodule return new quartzmodulequartzconfiguration bean lazy public quartzconfiguration quartzconfiguration return thisconfigurationgetquartzconfiguration bean lazy public healthcheck healthcheck throws schedulerexception return thisquartzmodulequartzhealthcheck i have multiple instances of myconfiguration that all need beans like this right now i have to copy and paste these definitions and rename them for each new configurationcan i somehow iterate over my configuration classes and generate a set of bean definitions for each onei would be fine with a subclassing solution or anything that is type safe without making me copy and paste the same code and rename the methods ever time i have to add a new serviceedit i should add that i have other components that depend on these beans they inject collectionhealthcheck for example,['java'] +844164,how to use http outside of a controller in angularjs i want to forget jquery because i like angularjs however i need to know how to use independent tasks that incorporate angularjs elsewhere in my application on this occasion i want to use https angularjs function to import a javascript file for exampleexample it used to do in jquerygeturljs functiondata evaldata okconsoleinfoget code code code okexample as documented in angularjsin a controllerappcontrollerctrllr http function http httpgeturljssuccessfunctiondata evaldata ok consoleinfohttp code code code okoutsidehttpgeturljs http is undefinedhow to use http hereas you see in the last call http is outside of a process now would like to know how to use the class http or another angular utils outside of a controllerapplication,"['javascript', 'jquery']" +844168,laravel 5 package development i am having trouble to create package in laravel 5 as workbench has been removed as in this thread how create package in laravel 5 goldorak suggest that we have to create our own package structure ourselvesso how can i create the workbench manually and get everything ready for package development,['php'] +844369,scikitlearns pipeline a sparse matrix was passed but dense data is required i am finding it difficult to understand how to fix a pipeline i created read largely pasted from a tutorial it is python 342df pddataframedf dataframefrom recordstraintest blah1 blah2 blah3pipeline pipelinevectorizer countvectorizer classifier randomforestclassifierpipelinefitnumpyasarraydf0 numpyasarraydf1predicted pipelinepredicttestwhen i run it i gettypeerror a sparse matrix was passed but dense data is required use xtoarray to convert to a dense numpy arraythis is for the line pipelinefitnumpyasarraydf0 numpyasarraydf1i have experimented a lot with solutions through numpy scipy and so forth but i still do not know how to fix it and yes similar questions have come up before but not inside a pipelinewhere is it that i have to apply toarray or todense,['python'] +844451,performance comparison fortran numpycython and numexpr i have following functiondef get denomn compqsxcpcslenn comp 1 number of proteinslencp and comp protein concentrationlenqp and comp protein capacitylenx 3n comp 1 fit parameterslencs 1 k x0n comp sigma xn comp2n comp z x2n comp3n comp a sigma z kqscsz1 cp denom npsuma cs return denomi compare it against a fortran implementation my first fortran function eversubroutine get denom qsxcpcsn compdenom calculates the denominator in the sma model brooks and cramer 1992 the function is called at a specific salt concentration and isotherm point i loops over the number of componentsimplicit none declaration of input variablesinteger intentin and comp number of componentsdouble precision intentin csqs salt concentration free ligand concentrationdouble precision dimensionn comp intentin cp protein concentrationdouble precision dimension3n comp 1 intentin x parameters declaration of local variablesdouble precision dimensionn comp ksigmazdouble precision ainteger i declaration of outpur variablesdouble precision intentout denomk x1n comp equlibrium constantsigma xn comp12n comp steric hindrance factorz x2n comp13n comp charge of proteina 0do i 1n comp a a sigmai zikiqscszi1cpiend dodenom a csend subroutine get denomi compiled the f95 file by using1 f2py c m get denom get denomf95 fcompilergfortran2 f2py c m get denom vec get denomf95 fcompilergfortran f90flagsmsse2 the last option should turn on autovectorizationi test the functions byimport numpy as npimport get denom as fort denomimport get denom vec as fort denom vecfrom matplotlib import pyplot as pltmatplotlib inlinedef get denomn compqsxcpcs k x0n comp sigma xn comp2n comp z x2n comp3n comp calculates the denominator in equ 14a 14c brooks cramer 1992 a sigma z kqscsz1 cp denom npsuma cs return denomn comp 100cp nptile1243n compcs 100qs nptile1100n compx nprandomrand3n comp1denom npempty1timeit get denomn compqsxcpcstimeit fort denomget denomqsxcpcsn comptimeit fort denom vecget denomqsxcpcsn compi added following cython codeimport cython import both numpy and the cython declarations for numpyimport numpy as npcimport numpy as npcythonboundscheckfalsecythonwraparoundfalsedef get denomint and compnpndarraydouble ndim1 modec qs npndarraydouble ndim1 modec xnpndarraydouble ndim1 modec cp double cs cdef int i cdef double a cdef double denom cdef double k x0n comp cdef double sigma xn comp2n comp cdef double z x2n comp3n comp calculates the denominator in equ 14a 14c brooks cramer 1992 a 0 for i in rangen comp a sigmai zi pow kiqsics zi1 cpi a sigmai zi kiqsicszi1 cpi denom a cs return denomeditadded numexpr using one threaddef get denom numexpn compqsxcpcs k x0n comp sigma xn comp2n comp z x2n comp3n comp calculates the denominator in equ 14a 14c brooks cramer 1992 a neevaluatesigma z kqscsz1 cp return cs npsumaneset num threads1 using just 1 threadtimeit get denom numexpn compqsxcpcsthe result is smaller is betterwhy is is the speed of fortran getting closer to numpy with increasing size of the arrays and how could i speed up cython using pointers,['python'] +844463,sendkeyssendv does not paste an image but it does paste text i am trying to set clipboard data and invoke a paste to windows my data is successfully set into the clipboard but when i perform asendkeyssendvwith an image in the clipboard it does not paste the image when text is in the clipboard it does successfully paste the textwhen i set the clipboard content to contain an image and then close my application and manually perform a ctrlv the image pastes successfully does anyone have any idea what i am doing wrong is there another way to invoke a pastemany thanks,"['c#', '.net']" +844491,why does chrome debugger think closed local variable is undefined with this codefunction baz var x foo function bar debugger barbazi get this unexpected resultwhen i change the codefunction baz var x foo function bar x debugger bari get the expected resultalso if there is any call to eval within the inner function i can access my variable as i want to do does not matter what i pass to evalmeanwhile firefox dev tools give the expected behavior in both circumstanceswhats up with chrome that the debugger behaves less conveniently than firefox i have observed this behavior for some time up to and including version 410227243 beta 64bitis it that chromes javascript engine flattens the functions when it caninterestingly if i add a second variable that is referenced in the inner function the x variable is still undefinedi understand that there are often quirks with scope and variable definition when using an interactive debugger but it seems to me that based on the language specification there ought to be a best solution to these quirks so i am very curious if this is due to chrome optimizing further than firefox and also whether or not these optimizations can easily be thisabled during development maybe they ought to be thisabled when dev tools are openalso i can reproduce this with breakpoints as well as the debugger statement,['javascript'] +844624,in a for loop is there a difference between prepostincrementing a loop control variable in terms of the total quantity of iterations when i compile and run the code below with either counter or counter substituted for x the output is identical in both cases numbers 1 10for int counter 1 counter 11 x stdcout counter endloriginally i thought counter would increment by 1 and then return the new value before for boolean expression in the loop header was evaluated ie when starting with counter 1 and using counter counter would have a value of 2 in the boolean expression this appears to not be the case as both outputs are identical rather than the counter version having one less iteration like i expectedreading around it appears counter and counter increment counter by 1 at either the start or end of the loop body respectively in which case is this not at least conceptually an identical action because the end and the start of the loop are the same thing once the loop has past the first iteration the only time i can see this making a difference is in the first iteration where stdcout counter endlshould output 1 to the console if counter is used because 1 is added to counter at the end of the loop whilst stdcout counter endl should output 2 to the console if counter is used because 1 is added to counter at the start of the loop in addition to the question above could you please precisely explain the order in which the three actions are evaluated in the for loop header and explain exactly where the iterations occur when using i and imany thanks,['c++'] +844808,keeping many databases in sync all the time i have a network of desktop pcs windows 7 which are located geographically apart from each other connected with lanthe network has an oracle backendi want to install a database locally on each pc about 12 of them currently thinking of sqlite but open to other possibilitiesi need to guarantee the local databases are kept in sync with each other and with the oracle db all the time or at least as long as there is network connectivity mesh topologythe synchronization involves only a single tablewhat are some possible effective solutions for this problem preferably something you have worked with beforehand,['.net'] +844940,ionslidebox with different slide heights i am using ionslidebox but the issue is my ionslides are not in the same height so it sets all the ionslides to the size of heights one following is an exampleionslide 1 height 30pxionslide 2 height 100pxso ionslidebox height will be 100px which make a blank space 70px in the slide1 and when the user slide by using that blank space 70px slider doesnt work pardon me if the question was not clear its bit hard to explainwhat could be the wayworkaround to have the slidebox work for different slide heightsthanks in advancecheerssam,['javascript'] +844949,wrong value for windowinnerwidth during onload event in firefox for android okay so the problem i am facing is this my mobile firefox browser is not retrieving the correct values for windowinnerwidth documentdocumentelementclientwidth or even the width of a div styled to take up the whole client window after page loadi am not crazy my code works just fine in every other browser for some reason firefox initializes these values with defaults and then gets the correct values later on if at any point i interrupt my javascript with an alert these properties magically become accurate afterwards i have scoured the internet for an answer and all i can find is a hack workaround use windowsettimeout to delay the use of these properties until they have time to populate correctly that is crazy users want speed not an extra delay just to view my site on a firefox browserwhat i do not understand is that i can set a div up to fill the client window perfectly before the values become accurate i do this in css by setting width and height of my divs id to 100 documentdocumentelement is basically the same as documentgetelementbyidmy div after all the document elements have loaded so how does the browser know how big the div should be when it does not have the correct dimensions of the client window in the first placei have tried running my code inside a windowaddeventlistenerloadfunctionevent my code but still these values will not generate is there a page load event that comes after windowonloadif anyone can tell me why only firefox mobile seems to thisplay this odd behavior i will give you a mental high fiveheres a bit of sample code for recreating the problemdoctype htmlhtml head added after javascript during edit script typetextjavascript windowaddeventlistenerloadfunctionevent var outputdocumentgetelementbyidoutput returns some default value like 980 outputinnerhtmlwindowinnerwidth alertafter this alert the value will change returns an accurate value like 511 outputinnerhtmlwindowinnerwidth script added title during edit titletitletitle head body p idoutputdefault outputp bodyhtmlmy firefox for android version is 3501 my android version is 4 on my device firefox thisplays 980 in the output p element shows the alert and then thisplays 980 again after page refresh the first two steps remain the same but the output after the alert changes to 360 this happens with documentdocumentelementclientwidth as well no properties i try seem to get the correct values it seems that firefox has some sort of delay after page load before it has access to the client windows dimensionsi tried the vergeairvecom plugin without jquery and its initial feedback remained at 980 it also initialized as 980 on chrome which was weird because chrome worked as expected without it after much debate a solution was found firefox apparently resizes the window after it is loaded i guess for good measure who really knows so by adding a resize event handler in addition to windowonload this problem can be averted see accepted answer below for more details,"['javascript', 'html', 'css']" +844987,exit a thread upon app unload i maintain a library that starts a daemon thread to do work in the background in regular java and android applications this thread is started once and runs for the lifetime of the process it never exits and that is okaywhen my library is included in an application container that supports application unloading such as tomcat the application never unloads my running thread holds strong references to its own class and that prevents the entire application from being unloaded users of my library cannot hotswap their app without leaking memory each timewhats the best way to get signaled when the application container wishes to unload my librarythis is a small library without any dependency on application container apis it does not know which application container it is running in and it does not want tothe fact that this library starts a thread is an implementation detail end users of the library should not have to know that a thread is being started and it is not their responsibility to shut it down,['java'] +845165,jquery changing the dom on dragstart event fires dragend immediately i came across a bug for chrome and opera and i would like to know if its known and if so is there a solutionif i change the dom on the dragstart event it immediately fires the dragend event is this a bug or is there some reason behind it only happens in chrome and opera firefox worksi appreciate every answerbodyon dragstart functione dragprofilefieldsrcelformid thisattrdataprofilefieldidformid edatatransfer eoriginaleventdatatransfer edatatransfereffectallowed move edatatransfersetdatatexthtml thisattrdataprofilefieldid changing the dom fires the dragend event in chrome plugin loginlogout pfcontainer dragprofilefieldsrcelformidfindplugin loginlogout pf entryfieldaddclasshighlight this does not work in chrome and opera but in firefox dragend function consolelogdragend plugin loginlogout pfeditputting the dom change in a settimeout function seems to solve the problem,"['javascript', 'jquery']" +845352,apply color filter with xml in imageview i have got an imageview and programmatically i can change its color using imageviewsetcolorfiltercolorredthere is something similar using xml,['android'] +845353,android nullpointerexception from creating an adapter i am creating an array adapter for a list vieweverything works ok i have 2 fragments and 2 buttons at the top of the action bar that changes between this 2 fragmentsmy problem is that i get crashes if i move too fast between those frags when i open fragone switch to fragtwo and then quickly move back to fragone fragone throws a npe from the getactivity contextthat is the line that crashesadapter new mainfragmentdocumentadaptergetactivity docslist documentsfragmentthis pagethe log report eandroidruntimei1 fatal exception mainprocess combapp pid 17438javalangnullpointerexception attempt to invoke virtual method javalangobject androidcontentcontextgetsystemservicejavalangstring on a null object reference at androidwidgetarrayadapterinitarrayadapterjava310 at androidwidgetarrayadapterinitarrayadapterjava104 at combappuiadaptersmainfragmentdocumentadapterinitmainfragmentdocumentadapterjava51any idea how can i solve this issue,"['java', 'android']" +845475,i cannot install intel haxm so i installed android studio and i had no problems with that however when i tried to run the emulator it said that intel haxm was not installedso i found the installer run it and it even though it said my laptop supports it that it was no enabledso i went enabled the intel virtualization technology vtx but i still get the same messagei hear something about hyperv needs to be unable but when i go to turn windows features onoff i cannot find it in that listcan someone help me with this thanks,['android'] +845483,using rvest or httr to log in to nonstandard forms on a webpage i am attempting to use rvest to spider a webpage that requires an emailpassword login on a formrmlistlslibraryrvest trying to sign into a form using emailpassword url page to spiderpgsession html sessionurl create sessionpgform html formpgsession1 pull form from sessionset valuespgform ctl00header2headertop1tbusername set valuespgform ctl00header2headertop1tbpassword mypasswordsubmit formpgsessionpgformsubmitctl00header2headertop1button1this gives me the following error messageerror in submit requestform submit object ctl00header2headertop1button1 not foundif i submit the form without specifying the submit parameter i get thissubmitting with ctl00header2headertop1button1error in function type msg aserror true url malformedi also tried passing the parameters directly to httr as mentioned in this question how can i post a simple html form in r but the submit parameter did not accept the submit button either with backwards quotes quotation marks or without any quoteslibraryhttrurl num500fd list submit ctl00header2headertop1button1 ctl00header2headertop1tbusername ctl00header2headertop1tbpassword mypasswordrespposturl bodyfd encodeformcontentresp any ideas for how i can log in from an r session and spider the data that is behind the login wall,['html'] +845632,update itemscontrol when an item in an observablecollection is updated the problemyou declare an itemscontrol or a control derived from itemscontrol in theviewyou bind the itemscontrolitemssource property to an observablecollection in your viewmodel your view updates as expected when an item is added to removed from the observablecollection but the view does not update when you change a property of an item in the observablecollection backgroundit seems that this is a common problem many wpf developers have encountered it has been asked a few timesnotify observablecollection when item changesobservablecollection not noticing when item in it changes even with inotifypropertychangedobservablecollection and item propertychangedmy implementationi tried to implement the accepted solution in notify observablecollection when item changes the basic idea is to hook up a propertychanged handler in your mainwindowviewmodel for each item in the observablecollection when an items property is changed the event handler will be invoked and somehow the view is updated i could not get the implementation to work here is my implementation viewmodelsclass viewmodelbase inotifypropertychanged public event propertychangedeventhandler propertychanged protected void raisepropertychangedstring propertyname var handler propertychanged if handler null handlerthis new propertychangedeventargspropertyname item viewmodelclass employeeviewmodel viewmodelbase private int age private string name public int age get return age set age value raisepropertychangedage public string name get return name set name value raisepropertychangedname public override string tostring return stringformat0 is 1 years old name age main window viewmodelclass mainwindowviewmodel viewmodelbase private observablecollectionemployeeviewmodel collection public mainwindowviewmodel collection new observablecollectionemployeeviewmodel collectioncollectionchanged myitemssource collectionchanged addemployeecommand new delegatecommand addemployee incrementemployeeagecommand new delegatecommand incrementemployeeage public observablecollectionemployeeviewmodel employees get return collection public icommand addemployeecommand get set public icommand incrementemployeeagecommand get set public void addemployee collectionaddnew employeeviewmodel age 1 name random joe public void incrementemployeeage foreach var item in collection itemage private void myitemssource collectionchangedobject sender notifycollectionchangedeventargs e if enewitems null foreach employeeviewmodel item in enewitems itempropertychanged itempropertychanged if eolditems null foreach employeeviewmodel item in eolditems itempropertychanged itempropertychanged private void itempropertychangedobject sender propertychangedeventargs e raisepropertychangedemployees viewwindow xclasswpfapplication2mainwindow xmlns xmlnsx xmlnsthemesclrnamespacemicrosoftwindowsthemesassemblypresentationframeworkaero xmlnsdclrnamespaceiressiosplusdynamicoecontrols titlemainwindow height350 width350grid gridcolumndefinitions columndefinition width03columndefinition columndefinition width07columndefinition gridcolumndefinitions stackpanel gridcolumn0 button commandbinding addemployeecommandadd employeebutton button commandbinding incrementemployeeagecommandincrement employee agebutton stackpanel grid gridcolumn1 gridrowdefinitions rowdefinition height01rowdefinition rowdefinitionrowdefinition gridrowdefinitions textblock gridrow0 textbinding pathemployees0textblock itemscontrol gridrow1 itemssourcebinding pathemployees borderbrushred borderthickness1itemscontrol gridgridmy resultsto verify my implementation i create a view like so the textblocktext is bound to the first item in the collection the itemscontrol is bound to the collection itself pressing the add employee button adds an employeeviewmodel object in the collection and both the textblock and itemscontrol are updated as expected pressing the add employee again the itemscontrol is updated with another entry greatpressing the increment employee age button the age property of each item is incremented by 1 the propertychanged event is raised the itempropertychanged event handler is invoked the textblock is updated as expected however the itemscontrol is not updated i am under the impression that the itemscontrol should be updated too when the employeeage is changed according to the answer in notify observablecollection when item changes,['c#'] +846130,in array does not work correctly when dealing with strings this codevar dumpin array0 array00 00var dumpin array1 array11 11outputbooltrueboolfalsewhy does the first line return true,['php'] +846419,memory leak detectors working principle how do memory leak detectors actually work what are the underlying concepts in general can take c as the language to explain this,"['c++', 'c']" +846520,java name for getter that returns boolean class according to naming convention i have noticed that for getters that return boolean not boolean netbeans generates getter with get prefix for exampleprivate boolean mainpublic boolean getmain return thismainis this wrong according to naming convention or is prefix only for primitive type,['java'] +846541,get date of first day of week based on localdatenow in java 8 i would like the get the date of the first day of the week based on localdatenow the following was possible with jodatime but seems to be removed from the new date api in java 8localdate now localdatenowsystemoutprintlnnowwithdayofweekdatetimeconstantsmondayi can not call withdayofweek because it does not existso my question is how to get the date of the first day of the week based on some localdate,['java'] +846586,newtonsoft json deserialize dictionary as keyvalue list from datacontractjsonserializer i have a dictionary serialized to storage with datacontractjsonserializer which i would like to deserialize with newtonsoftjsonthe datacontractjsonserializer has serialized the dictionary to a list of keyvalue pairsdictkeykey1valueval1keykey2valueval2is there any cool options i can give the jsonconvertdeserializeobject that will make it support both that data format and the format from newtonsoftjsondictkey1val1key2val2is the pretty format newtonsoftjson creates and i would like to be able to read both the old datacontract format and the new newtonsoft format in a transition periodsimplified example jsonarray public sealed class data public idictionarystring string dict get set testmethod public void testserializedatacontractdeserializenewtonsoftdictionary var d new data dict new dictionarystring string key1 val1 key2 val2 var oldjson stringempty var formatter new datacontractjsonserializertypeof data using var stream new memorystream formatterwriteobjectstream d oldjson encodingutf8getstringstreamtoarray var newjson jsonconvertserializeobjectd jsonarray on data class gives systeminvalidcastexception unable to cast object of type data to type systemcollectionsienumerable consolewritelineoldjson this is tha data i have in storage and want to deserialize with newtonsoftjson an array of keyvalue pairs dictkeykey1valueval1keykey2valueval2 consolewritelinenewjson this is what newtonsoftjson generates and should also be supported dictkey1val1key2val2 var d2 jsonconvertdeserializeobjectdatanewjson assertareequalval1 d2dictkey1 assertareequalval2 d2dictkey2 var d3 jsonconvertdeserializeobjectdataoldjson newtonsoftjsonjsonserializationexception cannot deserialize the current json array eg 123 into type systemcollectionsgenericidictionary2systemstringsystemstring because the type requires a json object eg namevalue to deserialize correctly to fix this error either change the json to a json object eg namevalue or change the deserialized type to an array or a type that implements a collection interface eg icollection ilist like listt that can be deserialized from a json array jsonarrayattribute can also be added to the type to force it to deserialize from a json array path dict line 1 position 9 assertareequalval1 d3dictkey1 assertareequalval2 d3dictkey2,['c#'] +846612,codecontracts boolean condition evaluates to a constant value why i am getting this warning but cannot figure out the problemcodecontracts warning the boolean condition d1count d2count always evaluates to a constant value if it or its negation appear in the source code you may have some dead code or redundant checkthe code is as followspublic static bool dictionaryequalstkey tvalueidictionarytkey tvalue d1 idictionarytkey tvalue d2 if d1 d2 return true if d1 null d2 null return false if d1count d2count return false warning here equality check goes here return truethe equality check goes here part can be as is or replaced by a proper implementation and i still get the same warning,['c#'] +846688,uitextfield changes font while editing in swift 12 20 i have a uitextfield with a custom font everything worked fine until swift update to 12 and 20 afterwards each time i try to edit a text field it changes its font to a different one that seems a sort of times new roman does anyone have experience of that,['ios'] +846697,how to center div vertically inside of absolutely positioned parent div i am trying to get blue container in the middle of pink one however seems verticalalign middle does not do the job in that casediv stylethisplay block position absolute left 50px top 50px div styletextalign left position absoluteheight 56pxverticalalign middlebackgroundcolor pink div stylebackgroundcolor lightbluetestdiv divdivresultexpectationplease suggest how can i achieve that jsfiddle,"['html', 'css']" +846859,specifying the maximum string length to scanf dynamically in c like s in printf i can specify the maximum amount of characters for scanf to read to a buffer using this techniquechar buffer64 read one line of text to buffer scanf63n bufferbut what if we do not know the buffer length when we write the code what if it is the parameter of a functionvoid functionfile file size t n char buffern fscanffile n buffer what now this code is vulnerable to buffer overflows as fscanf does not know how big the buffer isi remember seeing this before and started to think that it was the solution to the problemfscanffile n n buffermy first thought was that the in n meant that the maximum string size is passed an argument in this case n this is the meaning of the in printfwhen i checked the documentation for scanf i found out that it means that scanf should thiscard the result of nthis left me somewhat thisappointed as i think that it would be a very useful feature to be able to pass the buffer size dynamically for scanfis there any way i can pass the buffer size to scanf dynamically,['c'] +846869,how to build a horizontal listview with recyclerview i need to implement a horizontal listview in my android application i did a bit of research and came across how can i make a horizontal listview in android and horizontal listview in android however these questions were asked before recyclerview was released is there a better way to implement this now with recyclerview,['android'] +846907,obtaining all subpacks from a pack powersetpacktypestype is to give a pack consisting of packs formed by all subsets of types for now assume the static assertion that every type in types are thistinct for examplepowersetpackint char doubletypeis to bepackpack packint packchar packdouble packint char packint double packchar double packint char doublenow i have solved this exercise and tested it but my solution is very long and would like to hear some more elegant ideas i am not asking anyone to review my solution but suggest a new method altogether perhaps sketch their idea with some pseudocodein case you wanted to know this is what i did first i recalled from high school that a set of and elements has 2n subsets each subset corresponds toan ndigit binary number eg 00101001 n digits long where 0 means that the element is in the subset and 1 means thatthe element is not in the subset thus 0 would represent the empty subset and 1 would represent the entire set itselfso using the template sequence 01232n1 i formed 2n index sequences each corresponding to the binary representation of theintegers in that sequence eg index sequence1101 would correspond to 13 from that sequence then each of those 2n index sequenceswill be converted to the desired 2n subsets of packtypesmy solution below is quite long and i know that there is a more elegant method than the very mechanical one described aboveif youve thought of a better plan perhaps shorter too because it is more recursive or whatever please post your idea so that i can take onyour better plan hoping to write out a shorter solution i do not expect you to write out your solution in full if you think it will probably takesome time unless you want to but currently i cannot think of another way than what i have done here is my current longish solution in case you want to read itinclude iostreaminclude cmathinclude typeinfo subsetfrombinarydigitsptypes istype gives the subpack of ptypes where 1 takes the type and 0 does not take the type the size of the two packs must be the same for example subsetfrombinarydigitspackint double char 101type gives packint chartemplate typename typename int struct subsetfrombinarydigitshelpertemplate template typename class p typename accumulated int isstruct subsetfrombinarydigitshelperp paccumulated is using type paccumulatedtemplate template typename class p typename first typename rest typename accumulated int firstint int restintstruct subsetfrombinarydigitshelperpfirst rest paccumulated firstint restint stdconditionalfirstint 0 subsetfrombinarydigitshelperprest paccumulated restint subsetfrombinarydigitshelperprest paccumulated first restint type template typename int struct subsetfrombinarydigitstemplate template typename class p typename types int isstruct subsetfrombinarydigitsptypes is subsetfrombinarydigitshelperptypes p is struct nsubsetsptypes intpackstype is a pack of packs with each inner pack being the subset formed by the intpacks for example nsubsets packint char long object float double blob short index sequence01101011 index sequence01101010 index sequence101010 type will give pack packchar long float blob short packchar long float blob packint char long float blob template typename typename typename struct nsubsetshelpertemplate template typename class p typename types typename accumulatedstruct nsubsetshelperptypes paccumulated using type paccumulatedtemplate template typename class p typename types typename accumulated template int class z int is typename reststruct nsubsetshelperptypes paccumulated zis rest nsubsetshelperptypes paccumulated typename subsetfrombinarydigitsptypes istype rest template typename typename struct nsubsetstemplate template typename class p typename types typename intpacksstruct nsubsetsptypes intpacks nsubsetshelperptypes p intpacks now given a pack with and types we transform index sequence0122n to a pack of 2n index sequence packs with the 0s and 1s of each index sequence pack forming the binary representation of the integer for example if and 2 then we have packindex sequence00 index sequence01 index sequence10 index sequence11 from these we can get the power set ie the set of all subsets of the original packtemplate int n int exponent int poweroftwostruct largestpoweroftwouptohelper using type typename stdconditionalpoweroftwo n stdintegral constantint exponent largestpoweroftwouptohelpern exponent 1 2 poweroftwo type static const int value typevaluetemplate int nstruct largestpoweroftwoupto stdintegral constantint largestpoweroftwouptohelpern 1 1value constexpr int power int base int exponent return stdpow base exponenttemplate int struct index sequence for example prebinaryindexsequence13type is to be index sequence023 since 13 23 22 20template int n int accumulatedstruct prebinaryindexsequence could use another helper since largestpoweroftwouptohelpern 1 1value is being used twice using type typename prebinaryindexsequencen power2 largestpoweroftwouptohelpern 1 1value largestpoweroftwouptohelpern 1 1value accumulatedtypetemplate int accumulatedstruct prebinaryindexsequence0 accumulated using type index sequenceaccumulated for example binaryindexsequencehelperindex sequence index sequence023 0 7type is to be index sequence10110 the first index with position 0 and the last index is position 7template typename typename int int struct binaryindexsequencehelpertemplate template int class z int accumulated int first int rest int count int maxcountstruct binaryindexsequencehelperzaccumulated zfirst rest count maxcount stdconditionalfirst count binaryindexsequencehelperzaccumulated 1 zrest count 1 maxcount binaryindexsequencehelperzaccumulated 0 zfirst rest count 1 maxcount type when the input pack is emptied but count is still less than maxcount fill the rest of the acumator pack with 0stemplate template int class z int accumulated int count int maxcountstruct binaryindexsequencehelperzaccumulated z count maxcount binaryindexsequencehelperzaccumulated 0 z count 1 maxcount template template int class z int accumulated int maxcountstruct binaryindexsequencehelperzaccumulated z maxcount maxcount using type zaccumulated at last binaryindexsequencen is the binary representation of and using index sequence eg binaryindexsequence137 is index sequence10110template int n int numdigitsusing binaryindexsequence typename binaryindexsequencehelperindex sequence typename prebinaryindexsequencentype 0 numdigitstype now define make index sequencen to be index sequence012n1template int n int isstruct make index sequence helper make index sequence helpern1 n1 is make index sequence helpern1 n1 is is derived from make index sequence helpern2 n2 n1 is which is derived from make index sequence helpern3 n3 n2 n1 is which is derived from which is derived from make index sequence helper0 0 1 2 n2 n1 istemplate int isstruct make index sequence helper0 is using type index sequenceistemplate int nusing make index sequence typename make index sequence helperntype finally ready to define powerset itselftemplate typename typename struct powersethelpertemplate template typename class p typename types template int class z int isstruct powersethelperptypes zis nsubsets ptypes binaryindexsequenceis sizeoftypes template typename struct powersettemplate template typename class p typename typesstruct powersetptypes powersethelperptypes make index sequencepower2 sizeoftypes testingtemplate typename struct pack template typename laststruct packlast static void print stdcout typeidlastname stdendltemplate typename first typename reststruct packfirst rest static void print stdcout typeidfirstname packrestprinttemplate int laststruct index sequencelast static void print stdcout last stdendltemplate int first int reststruct index sequencefirst rest static void print stdcout first index sequencerestprintint main powersetpackint char doubletype powerset powersetprint,['c++'] +847058,spring data elasticsearch multiple index with same document i am using springdataelasticsearch and for the beginning everything works finedocument type products indexname empty public class productpublic interface productrepository extends elasticsearchrepositoryproduct stringin my model i can search for productsautowiredprivate productrepository repositoryrepositoryfindbyidentifier x getcategory so my problem is i have the same elasticsearch type in different indices and i want to use the same document for all queries i can handle more connections via a pool but i do not have any idea how i can implement thisi would like to have something like thatproductrepository customerrepo elasticsearchpoolgetrepobycustomerabc productrepositoryclassrepositoryfindbyidentifier x getcategoryis it possible to create a repository at runtime with an different index thanks a lotmarcel,['java'] +847192,multiple overloaded methods does null equal nullpointerexception public class testmain public static void methodtestexception e systemoutprintlnexception method called public static void methodtestobject e systemoutprintlnobject method called public static void methodtestnullpointerexception e systemoutprintlnnullpointerexception method called public static void mainstring args methodtestnull output nullpointerexception method called,['java'] +847198,zooming in a specific div in cordovaionic i added the viewport with properties allowing zoomingscaling and i added these to the native codewebsettings settings superappviewgetsettingssettingssetbuiltinzoomcontrolstruesettingssetthisplayzoomcontrolstruesettingssetsupportzoomtruei am able to zoom but along with my view ionheaderbar and ionnavbar gets zoomed i tried giving the header css to keep it fixedposition fixedtop 0pxleft 0pxbut still it would get zoomedmy indexhtml has an ionheaderbar which contains an imagethe templates go into ionnavview classhasheaderionnavviewthe template in which i require zooming in a particular div is having a ionview and it looks like ionview ionnavbar classbarstable ionnavbuttons sideright icon1 ionnavbuttons ionnavbuttons sideleft icon2 ionnavbuttons ionnavbar div multiple divs in here which are containers for html and css data we receive via ajax requests and this is here i need zooming in divionviewps would it matter if i add a full html codewith meta viewport no header but body and divs inside the ionview,"['html', 'css']" +847326,overwrite laravel 5 helper function i am using the response helper very often and i just return the data with a message to the user now i have to include the http status code as well but i do not want to change every response which is likely bad anywayso i am trying to overwrite the response helper function by creating my own helpersphp within apphttphelpersphp when i add it to my composer files it does autoload the current helpersphp from the framework first and when i add it before the autload include in bootstrapglobalphp i wont be able to use the app and other laravel functionshow would i be able to solve this issue i just want to include the status code as well in the response array,['php'] +847374,xcode keeps building storyboard after each keystroke my xcode project using a storyboard entered in a very weird state recently xcode keeps building the whole project and notably the storyboard after each keypress i found no reason for this behavior neither in my project diffing all interesting files storyboard and project neither a setting in xcode maybe i just could not find it needless to say that this feature makes working on my project nearly impossible since the cpu is constantly occupying with rebuilding the storyboard when i type new code anybody seen this,['ios'] +847443,android studio two flavors with different manifest files i am having issues with defining two different manifest files for my flavors in android studio this is my current project structurethe androidmanifestxml in the free flavor looks like thisxml version10 encodingutf8manifest xmlnsandroid packageseexamplepackage usespermission androidnameandroidpermissioninternet usespermission androidnameandroidpermissionaccess network state usespermission androidnameandroidpermissionaccess wifi state manifestthe androidmanifestxml in the main flavor has no usespermissions but contains the rest of the manifest code that is shared between all flavorsthe androidmanifestxml in the pro flavor looks like thisxml version10 encodingutf8manifest xmlnsandroid packageseexamplepackage usespermission androidnamecomandroidvendingcheck license manifestbuildgradle defines the two flavors like productflavors free applicationid seexamplepackagefree minsdkversion 14 targetsdkversion 21 versioncode 1 versionname 10 pro minsdkversion 14 applicationid seexamplepackagepro targetsdkversion 21 versioncode 2 versionname 11 the result that i am expecting is that the different flavors defines different usespermissions this is not the case the result is currently that the both flavors only defines the usespermission androidnamecomandroidvendingcheck license as defined in androidmanifestxml in the pro flavor i have triedclean project rebuild projectrestart android studiosync gradlebut without success how am i to fix this any help is appreciatededit 1i changed the location of each flavors androidmanifestxml file from each of the res folders to free and pro folder the result of thispro flavor shows licence permission as expectedfree flavor shows permissions from both androidmanifestxmlfiles license and network permissions should be only networkthis feels like an issue of project structure what to make of thisedit 2i pulled the merge reports as commonsware hinted these are the reports regarding usespermissionsfreeusespermissioncomandroidvendingcheck licenseadded from qwknotegitlicencinglibraryunspecified265 androidname added from qwknotegitlicencinglibraryunspecified2622prousespermissioncomandroidvendingcheck licensemerged from qwknotegitlicencinglibraryunspecified265,['android'] +847619,rvalue reference is treated as an lvalue i posted this answer which contains the following codevoid foostring bar string temp bar cout temp temp endlis bar an rvalue or an lvaluei ask because i obviously cannot take the address of an rvalue yet i can take the address of an rvalue reference as is done hereif you can perform any operation on an rvalue reference that you can on an lvalue reference what is the point in differentiating between the two with the instead of just an,['c++'] +847627,android fragments on backstack taking up too much memory problemi have an android application that allows a user to browse to a users profile viewprofilefragment inside viewprofilefragment a user can click on an image that will take him to storyviewfragment where various users photos show up it is possible to click on a user profile photo that will take them to another instance of viewprofilefragment with the new users profile if a user repeatedly clicks on users profiles clicks an image that takes them to the gallery then clicks on another profile the fragments stack up in memory quickly causing the dreaded outofmemoryerror here is a diagram flow of what i am describingusera clicks on bobs profile inside bobs profile usera clicks on imagea taking him to a gallery of photos of various users including bobs usera clicks on profile of sue then on one of her images process repeats etc etc usera viewprofilefragment storyviewfragment viewprofilefragment storyviewfragment viewprofilefragmentso as you can see from a typical flow there are lots of instances of viewprofilefragment and storyviewfragment piling up in the backstackrelevant codei am loading these in as fragments with the following logicfrom mainactivityfm getsupportfragmentmanagerft fmbegintransactionftreplaceridactivity main content fragment fragment titleftaddtobackstacktitlewhat i have tried1 i am specifically using fragmenttransaction replace so that the onpause method will be triggered when the replace takes place inside onpause i am trying to free up as many resources as i can such as clearing out data in listview adapters nulling out variables etc so that when the fragment is not the active fragment and pushed onto the backstack there will be more memory freed up but my efforts to free up resources is only a partial success according to mat i still have a lot of memory that is consumed by galleryfragment and viewprofilefragment2 i have also removed the call to addtobackstack but obviously that offers a poor user experience because they cannot traverse back the app just closes when the user hits the back button3 i have used mat to find all of the objects that i take up a lot of space and i have dealt with those in various ways inside the onpause and onresume methods to free up resources but they are still considerable in size4 i also wrote a for loop in both fragments onpause that sets all of my imageviews to null using the following logic for int ishellgetheaderviewcount ishellgetcount i view h shellgetchildati imageview v imageview hfindviewbyidridgalleryimage if v null vsetimagebitmapnull mylistviewadapterclearquestions1 am i overlooking a way to allow a fragment to remain on the backstack but also free up its resources so that the cycle of replacefragment does not eat up all of my memory 2 what are the best practices when it is expected that a lot of fragments could be loaded onto the backstack how does a developer correctly deal with this scenario or is the logic in my application inherently flawed and i am just doing it wrongany help in brainstorming a solution to this would be greatly appreciated,['android'] +847645,copying words from one file to another in cpp i am trying to copy words from one file to another in cpp heres my code int main string from to cin from to ifstream ifsfrom ofstream ofsto setstring wordsistream iteratorstringifs istream iteratorstring copywordsbegin wordsend ostream iteratorstringofs n return ifseof ofsthis way i get a compilation error expression must have class typeat the line of where i call copyif i change the construction of the iterators to the following it works setstring words istream iteratorstring ifs istream iteratorstring i thought choosing between and when initializing objects in cpp is just a matter of choice but i guess i am wrongcan someone explain this to me,['c++'] +847694,how to structure a modular app in laravel 5 i would like to divide my application in modules for instance there would be a core modules that contains the basic login functionality app layoutformatting css etc user management and a diarylater on i may create other modules like a contact manager that can easily be added or removed from the applicationthere would be some logic in the apps navigation for determining which modules are present and to showhide the links to themhow can i do this in terms of directory structure namespaces and anything else that is neededi am looking at creolablaravelmodules but it states that it is for laravel 4 can i still use it with 5 in exactly the same waythe documentation says to place models controllers and views within each module directory but how does this work with routes ideally i would like each module to have its own routesphp file how will all of this work with the stuff in the http and the resources directoryi was thinking of something like thisbut i have no idea how i would get it to worki have just tried the tutorial herewith no extra libraries etc just pure laravel 5i seem to have hit a brick wall with an error messagefatalerrorexception in serviceproviderphp line 16call to undefined method illuminateconfigrepositorypackageregarding the followingphp namespace appmodulesabstract class serviceprovider extends illuminatesupportserviceprovider public function boot if module thisgetmodulefunc get args thispackageapp module module app path modules module public function register if module thisgetmodulefunc get args thisappconfigpackageapp module app path modules module config add routes routes app path modules module routesphp if file existsroutes require routes public function getmoduleargs module issetargs0 and is stringargs0 args0 null return module what is causing this and how can i fix itgot my head around this a bit more now got my packagemodule routes and views working which is greatabstract class serviceprovider extends illuminatesupportserviceprovider public function boot if module thisgetmodulefunc get args include dir moduleroutesphp thisloadviewsfrom dir moduleviews core public function register if module thisgetmodulefunc get args public function getmoduleargs module issetargs0 and is stringargs0 args0 null return module i have one last question how would i load all my controllers from inside my package much like how the loadviewsfrom method works,['php'] +847846,error inflating class recyclerview so my code simply makes a list of cardviews using recyclerview upon running my code i kept getting a weird error claiming there was an error in my xml after tinkering for a while i found out that in my layout file if i change recyclerview to androidsupportv7widgetrecyclerview everything would work just fine why is this happening my activityimport androidsupportv7appactionbaractivityimport androidosbundleimport androidsupportv7widgetlinearlayoutmanagerimport androidsupportv7widgetrecyclerviewimport androidviewmenuimport androidviewmenuitemimport javautilarraylistpublic class cardlistactivity extends actionbaractivity override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity card list recyclerview recyclerview recyclerviewfindviewbyidridcardlist recyclerviewsethasfixedsizetrue linearlayoutmanager linearlayoutmanager new linearlayoutmanagerthis linearlayoutmanagersetorientationlinearlayoutmanagervertical recyclerviewsetlayoutmanagerlinearlayoutmanager arrayliststring list new arraylist forint i 0 i 20 i listadditem i cardlistadapter cardlistadapter new cardlistadapterlist recyclerviewsetadaptercardlistadapter my adapter import androidsupportv7widgetrecyclerviewimport androidviewlayoutinflaterimport androidviewviewimport androidviewviewgroupimport androidwidgettextviewimport javautillistpublic class cardlistadapter extends recyclerviewadaptercardlistadaptercardlistviewholder private liststring list public cardlistadapterliststring list thislist list override public cardlistviewholder oncreateviewholderviewgroup viewgroup int i view v layoutinflaterfromviewgroupgetcontextinflaterlayoutcard layoutviewgroupfalse return new cardlistviewholderv override public void onbindviewholdercardlistviewholder cardlistviewholder int i string s listgeti cardlistviewholdertitlesettexts override public int getitemcount return listsize public static class cardlistviewholder extends recyclerviewviewholder textview title public cardlistviewholderview itemview superitemview title textviewitemviewfindviewbyidridtitle my layout file note changing recyclerview to androidsupportv7widgetrecyclerview fixes the error relativelayout xmlnsandroidxmlnstools androidlayout widthmatch parentandroidlayout heightmatch parent androidpaddingleftdimenactivity horizontal marginandroidpaddingrightdimenactivity horizontal marginandroidpaddingtopdimenactivity vertical marginandroidpaddingbottomdimenactivity vertical margin toolscontextcardlistactivityrecyclerview androidlayout widthmatch parent androidlayout heightmatch parent androidididcardlist recyclerviewwhen i run with recyclerview i get this error process comliquidinklollipopmaterialui pid 7317 javalangruntimeexception unable to start activity componentinfocomliquidinklollipopmaterialuicomliquidinklollipopmaterialuicardlistactivity androidviewinflateexception binary xml file line 8 error inflating class recyclerview at androidappactivitythreadperformlaunchactivityactivitythreadjava2298 at androidappactivitythreadhandlelaunchactivityactivitythreadjava2360 at androidappactivitythreadaccess800activitythreadjava144 at androidappactivitythreadhhandlemessageactivitythreadjava1278 at androidoshandlerthispatchmessagehandlerjava102 at androidoslooperlooplooperjava135 at androidappactivitythreadmainactivitythreadjava5221 at javalangreflectmethodinvokenative method at javalangreflectmethodinvokemethodjava372 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava899 at comandroidinternaloszygoteinitmainzygoteinitjava694 caused by androidviewinflateexception binary xml file line 8 error inflating class recyclerview at androidviewlayoutinflatercreateviewfromtaglayoutinflaterjava757 at androidviewlayoutinflaterrinflatelayoutinflaterjava806 at androidviewlayoutinflaterinflatelayoutinflaterjava504 at androidviewlayoutinflaterinflatelayoutinflaterjava414 at androidviewlayoutinflaterinflatelayoutinflaterjava365 at androidsupportv7appactionbaractivitydelegatebasesetcontentviewactionbaractivitydelegatebasejava228 at androidsupportv7appactionbaractivitysetcontentviewactionbaractivityjava102 at comliquidinklollipopmaterialuicardlistactivityoncreatecardlistactivityjava18 at androidappactivityperformcreateactivityjava5933 at androidappinstrumentationcallactivityoncreateinstrumentationjava1105 at androidappactivitythreadperformlaunchactivityactivitythreadjava2251a a a a a a a a a a a a at androidappactivitythreadhandlelaunchactivityactivitythreadjava2360a a a a a a a a a a a a at androidappactivitythreadaccess800activitythreadjava144a a a a a a a a a a a a at androidappactivitythreadhhandlemessageactivitythreadjava1278a a a a a a a a a a a a at androidoshandlerthispatchmessagehandlerjava102a a a a a a a a a a a a at androidoslooperlooplooperjava135a a a a a a a a a a a a at androidappactivitythreadmainactivitythreadjava5221a a a a a a a a a a a a at javalangreflectmethodinvokenative methoda a a a a a a a a a a a at javalangreflectmethodinvokemethodjava372a a a a a a a a a a a a at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava899a a a a a a a a a a a a at comandroidinternaloszygoteinitmainzygoteinitjava694 caused by javalangclassnotfoundexception did not find class androidviewrecyclerview on path dexpathlistzip file dataappcomliquidinklollipopmaterialui2baseapknativelibrarydirectoriesvendorlib systemlib at dalviksystembasedexclassloaderfindclassbasedexclassloaderjava56 at javalangclassloaderloadclassclassloaderjava511 at javalangclassloaderloadclassclassloaderjava469 at androidviewlayoutinflatercreateviewlayoutinflaterjava571 at androidviewlayoutinflateroncreateviewlayoutinflaterjava665 at comandroidinternalpolicyimplphonelayoutinflateroncreateviewphonelayoutinflaterjava65 at androidviewlayoutinflateroncreateviewlayoutinflaterjava682 at androidviewlayoutinflatercreateviewfromtaglayoutinflaterjava741a a a a a a a a a a a a at androidviewlayoutinflaterrinflatelayoutinflaterjava806a a a a a a a a a a a a at androidviewlayoutinflaterinflatelayoutinflaterjava504a a a a a a a a a a a a at androidviewlayoutinflaterinflatelayoutinflaterjava414a a a a a a a a a a a a at androidviewlayoutinflaterinflatelayoutinflaterjava365a a a a a a a a a a a a at androidsupportv7appactionbaractivitydelegatebasesetcontentviewactionbaractivitydelegatebasejava228a a a a a a a a a a a a at androidsupportv7appactionbaractivitysetcontentviewactionbaractivityjava102a a a a a a a a a a a a at comliquidinklollipopmaterialuicardlistactivityoncreatecardlistactivityjava18a a a a a a a a a a a a at androidappactivityperformcreateactivityjava5933a a a a a a a a a a a a at androidappinstrumentationcallactivityoncreateinstrumentationjava1105a a a a a a a a a a a a at androidappactivitythreadperformlaunchactivityactivitythreadjava2251a a a a a a a a a a a a at androidappactivitythreadhandlelaunchactivityactivitythreadjava2360a a a a a a a a a a a a at androidappactivitythreadaccess800activitythreadjava144a a a a a a a a a a a a at androidappactivitythreadhhandlemessageactivitythreadjava1278a a a a a a a a a a a a at androidoshandlerthispatchmessagehandlerjava102a a a a a a a a a a a a at androidoslooperlooplooperjava135a a a a a a a a a a a a at androidappactivitythreadmainactivitythreadjava5221a a a a a a a a a a a a at javalangreflectmethodinvokenative methoda a a a a a a a a a a a at javalangreflectmethodinvokemethodjava372a a a a a a a a a a a a at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava899a a a a a a a a a a a a at comandroidinternaloszygoteinitmainzygoteinitjava694 suppressed javalangclassnotfoundexception androidviewrecyclerview at javalangclassclassfornamenative method at javalangbootclassloaderfindclassclassloaderjava781 at javalangbootclassloaderloadclassclassloaderjava841 at javalangclassloaderloadclassclassloaderjava504 26 more caused by javalangnoclassdeffounderror class not found using the boot class loader no stack available,['android'] +847885,hide and show depending on screen size bootstrap 3 classes for some this may seem very easy and from what i have written i seems like it would do what i want it to but sadly that is not the case i have two images each image will be shown depending on the screen size so for the first one in the html i have placed hiddenmd hiddensm hiddenxs which would give me the impression it will only show on large screens the second one i only want to be visible on the tabletsmobiles so i have assigned the visiblesm visiblemd and hiddenlg but when i resize the browser the first image does not thisappear when i minimize down to a tablet size however it does thisappear when minimizing the browser down to a mobile device size can anyone spot what i have done wrong a classnavbarbrand hiddenmd hiddensm hiddenxs style backgroundimage urlcontentimagesfirstimagepng backgroundrepeat norepeat hrefurlactionindex homea a classnavbarbrand hiddenlg visiblesm visiblemd style backgroundimage urlcontentimagessecondimagepng backgroundrepeat norepeat hrefurlactionindex homea,"['html', 'css']" +847938,gradle failed to resolve library in android studio i want to include a library in android studio but it thisplays error like below failed to resolvecomlemonlabexpandablebuttonmenu100how to fix this problem apply plugin comandroidapplication android compilesdkversion 21 buildtoolsversion 2112 defaultconfig applicationid ayowescomnewecampus minsdkversion 15 targetsdkversion 21 versioncode 1 versionname 10 buildtypes release minifyenabled false proguardfiles getdefaultproguardfileproguardandroidptimizetxt proguardrulestxt dependencies compile filetreedir libs include jar compile comandroidsupportappcompatv72103 compile comgoogleandroidgmsplayservices6587 compile comlemonlabexpandablebuttonmenu100 compile fileslibspinchzoomjar,['android'] +847993,thermal imaging palette since the early days of thermal imaging infrared cameras often use a thistinctive palette that runs from black through blue magenta orange yellow to bright white this palette is often called iron or ironbowhere is a typical false color visualization of an image taken with a forward looking infrared camera source wikipediatermografia kot by lcamtuf a typical false color infraredon a specialized infrared imagery forum i have found a post from 2005 with a thiscrete palette that seems to be close to what i am looking for a thiscrete flir palette of unknown originhowever as with the rainbow palette it would be nice to have a concise analytical expression that defines the paletteto those who have used gnuplot this palette might look familiar as the default pm3d palette runs blackbluemagentaorangeyellowgnuplot pm3d palettethis palette has a concise definitionr mathround255mathsqrtx g mathround255mathpowx3 b mathround255mathsin2 mathpi x0 mathsin2 mathpi x 0 however it is not quite how the other palette looks a bit too brownish to my taste any additional information on the origins or an analytical expression for the palette used in flir cameras would helpi have created a jsfiddle to play with different palettes,['javascript'] +848168,add a custom color palette to xcode interface builder my current long term project utilizes a palette of custom colors in code we are using a category to access these colors by name this works great but there are times such as when building a nib that these colors would not be set programmaticallyi am looking for a way to define a named set of colors for instance when setting a background color for a uiview i would like my drop list in interface builder to list my custom colors by name does anyone know of a way to achieve this thanks,['ios'] +848175,how can i reduce the stack frame of a deeply recursive function in c suppose i have some recursive function that manipulates a graph structuretypedef struct node data data size t visited size t num neighbors struct node neighbors nodevoid dosomethingwithnodenode node if node nodevisited return nodevisited 1 do something with nodedata size t some local variables size t i for i 0 i nodenum neighbors i do some calculations with the local variables if something dosomethingwithnodenodeneighborsi because of the local variables i use in the loop the compiler gcc creates a largerthaniwouldlike stack frame for this function a good number of pushq and popq instructions even with o3 which is a problem since it is deeply recursive since it does not matter what order i visit the nodes in i could refactor this code to use a stack of node pointers thus reducing the overhead to one pointer per iterationare there any hints i can give the compiler gcc to fix this problemif not is it possible to make use of the call stack itself for my stack of pointers without resorting to assembly,['c'] +848182,speech recognitionspeech to text is not working in android 422 i have device which has android 422 is installed on it is is not supporting speechrecognition api i tried one speech to text application and it is giving speech to text doesnot support in your device error i also tried installing google search application and tried to search using voice icon but it is giving following exception0213 215848077 eandroidruntime9403 javalangruntimeexception javautilconcurrentexecutionexception javalangunsatisfiedlinkerror could not load google recognizer jni from loader dalviksystempathclassloaderdexpathsystemappcomgoogleandroidgooglequick searchbox40261499465arm300400260minapi16apklibrarypathdataapp libcomgoogleandroidgooglequicksearchbox40261499465arm300400260 minapi16 findlibrary returned null0213 215848077 eandroidruntime9403 at emtafterexecutepg4870213 215848077 eandroidruntime9403 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava10880213 215848077 eandroidruntime9403 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava5730213 215848077 eandroidruntime9403 at javalangthreadrunthreadjava8560213 215848077 eandroidruntime9403 caused by javautilconcurrentexecutionexception javalangunsatisfiedlinkerror could not load google recognizer jni from loader dalviksystempathclassloaderdexpathsystemappcomgoogleandroidgooglequick searchbox40261499465arm300400260minapi16apklibrarypathdataapp libcomgoogleandroidgooglequicksearchbox40261499465arm300400260 minapi16 findlibrary returned null0213 215848077 eandroidruntime9403 at javautilconcurrentfuturetaskreportfuturetaskjava940213 215848077 eandroidruntime9403 at javautilconcurrentfuturetaskgetfuturetaskjava1600213 215848077 eandroidruntime9403 4 more0213 215848077 eandroidruntime9403 caused by javalangunsatisfiedlinkerror could not load google recognizer jni from loader dalviksystempathclassloaderdexpathsystemappcomgoogleandroidgooglequick searchbox40261499465arm300400260minapi16apklibrarypathdataapp libcomgoogleandroidgooglequicksearchbox40261499465arm300400260 minapi16 findlibrary returned null0213 215848077 eandroidruntime9403 at javalangruntimeloadlibraryruntimejava3650213 215848077 eandroidruntime9403 at javalangsystemloadlibrarysystemjava5350213 215848077 eandroidruntime9403 at gjragapg390213 215848077 eandroidruntime9403 at gjoapg840213 215848077 eandroidruntime9403 at javalangreflectmethodinvokenativenative method0213 215848077 eandroidruntime9403 at javalangreflectmethodinvokemethodjava5110213 215848077 eandroidruntime9403 at erunpg1020213 215848077 eandroidruntime9403 at javautilconcurrentexecutorsrunnableadaptercallexecutorsjava3900213 215848077 eandroidruntime9403 at javautilconcurrentfuturetaskrunfuturetaskjava2340213 215848077 eandroidruntime9403 at javautilconcurrentscheduledthreadpoolexecutorscheduledfuturetaskaccess201 scheduledthreadpoolexecutorjava1530213 215848077 eandroidruntime9403 at javautilconcurrentscheduledthreadpoolexecutorscheduledfuturetaskrunscheduledthreadpoolexecutorjava2670213 215848077 eandroidruntime9403 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava1080can anyone help me to solve this issuethanks,['android'] +848228,itunes connect warning your binary doesnat support ipad i just uploaded a new binary to itunes connect and added it to a new version of an ios app after adding the binary and saving changes itunes connect thisplays the warning message your binary doesnat support ipad the screenshots or app video preview for ipad wonat be shown on the app storethe xcode project was generated using the cordova 3 cli the uploaded binary is the first cordova 3 version since the app was migrated from cordova 2the app has been tested on ipad and it works finexcode project setting for devices is universal targeted device family 12 in projectpbxprojxcode architecture settings are the defaults so they are not explicitly specified in projectpbxproji have googled this warning message and found no useful information so hoping someone here has come across this before and can offer some advice,['ios'] +848298,elusive recaptcha bug copy code always fails a very small amount of my users get a captcha that asks them to copy and paste a code but it always fails for them while most of the users get the normal one checkbox which goes through correctlygoogling only returned three instances of people getting that captcha none of which had any valuable informationany ideas as to why they are getting that captcha and most importantly why does it fail,"['javascript', 'html']" +848417,nosuchmethoderror on startup in java jersey app i have been getting a very strange error when trying to start a jersey app on tomcat the same code works on other computers i tried reinstalling tomcat all my maven dependencies even eclipse and java itself no luck it seems like a bad jersey version is being loaded i thinkany pointers in the right direction will be appreciatedheres the effective pom and the actual pom 20150213 134340870 localhoststartstop1 error orgapachecatalinacorecontainerbasecatalinalocalhostmiddlewareserver standardwrapperthrowablejavalangnosuchmethoderror javaxwsrscoreapplicationgetpropertiesljavautilmap at orgglassfishjerseyserverapplicationhandlerinitapplicationhandlerjava304 at orgglassfishjerseyserverapplicationhandlerinitapplicationhandlerjava285 at orgglassfishjerseyservletwebcomponentinitwebcomponentjava311 at orgglassfishjerseyservletservletcontainerinitservletcontainerjava170 at orgglassfishjerseyservletservletcontainerinitservletcontainerjava358 at javaxservletgenericservletinitgenericservletjava158 at orgapachecatalinacorestandardwrapperinitservletstandardwrapperjava1231 at orgapachecatalinacorestandardwrapperloadservletstandardwrapperjava1144 at orgapachecatalinacorestandardwrapperloadstandardwrapperjava1031 at orgapachecatalinacorestandardcontextloadonstartupstandardcontextjava4901 at orgapachecatalinacorestandardcontextstartinternalstandardcontextjava5188 at orgapachecatalinautillifecyclebasestartlifecyclebasejava150 at orgapachecatalinacorecontainerbasestartchildcallcontainerbasejava1409 at orgapachecatalinacorecontainerbasestartchildcallcontainerbasejava1399 at javautilconcurrentfuturetaskrunfuturetaskjava266 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava1142 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava617 at javalangthreadrunthreadjava745,['java'] +848533,how to add custom search box in django admin i know this is gonna be a very basic questionin django i have successfully created a admin panelnow i want a add a custom search box in one of my field namely photo fieldbut i do not know how to add custom search box in a django admin panelif i get some proper hints than i believe that i can do itadminpyfrom djangocontrib import adminfrom photomodels import photoclass photoadminadminmodeladmin list thisplaynameapprovedapproved timeuploaded timeusermodelspyclass photomodelsmodel name modelscharfieldmax length 100 photo modelsimagefieldupload to photos blankfalsenulltrue approved modelsbooleanfielddefault false approved time modelsdatetimefieldauto nowtruenulltrueblanktrue uploaded time modelsdatetimefield description modelscharfieldmax length 500 blank false null truekeyword modelscharfieldmax length 500 blank false null true image id modelscharfieldmax length300 blanktrue nulltrue certified modelsbooleanfielddefault false approved by modelscharfieldmax length 100 user modelsforeignkeyuser total download modelsintegerfielddefault0 watermarked image modelsimagefieldupload to temp blanktruenulltruei want a add a custom search box in this photo field where image can be searched by it is idnow how can i add this search box in my above given model,['python'] +848892,angular uitree and accept callback for restricting nodes i am using i want to acceptcategories to root scope of uitreeapps to the apps of same categoriesmy controller is partialaccept categories at root scope and accept apps only inside same categoryscopeoptions accept functionsourcenodescope destnodesscope destindex todo check nodes and return alertcalled logdebugsourcenodescope logdebugsourcenodescope logdebugdestnodesscope logdebugdestnodesscope return false dropped functionevent beforedrop functionevent my html is div ngcontrollercpotreeviewctrl divscript typetextngtemplate idapps rendererhtml div uitreehandle appname divscriptscript typetextngtemplate idcategory rendererhtml div uitreehandle categoryname div ol uitreenodes ngmodelcategoryapps li ngrepeatapp in categoryapps uitreenode ngincludeapps rendererhtml li olscriptdiv uitreeoptions ol uitreenodes ngmodeltreedata idtreeroot li ngrepeatcategory in treedata uitreenode ngincludecategory rendererhtmlli oldivdivdivi want to acceptcategories to root scope of uitreeapps to the apps of same categoriesthe accept callback is not getting fired whats not right herethanks,"['javascript', 'html']" +848920,conversion to branchless of consecutive if statements i am stuck there trying to figure out how to convert the last two if statements of the following code to a branchless stateint u x yx rand 100 50y rand 100 50u rand 4if y x you 5if y x you 4or in case the above turns out to be too difficult you can consider them asif x 0 you 5if y 0 you 4i think that what gets me is the fact that those do not have an else catcher if it was the case i could have probably adapted a variation of a branchless abs or maxmin functionthe rand functions you see are not part of the real code i added them like this just to hint at the expected ranges that the variables x y and u can possibly have at the time the two branches happenassembly machine code is allowed for the purposeeditafter a bit of braingrinding i managed to put together a working branchless versionint u x yx rand 100 50y rand 100 50u rand 4u 4uunsigned intxy 31u 5uunsigned intxy 31unfortunately due to the integer arithmetic involved the original version with if statements turns out to be faster by a 30 rangecompiler knows where the party is at,['c'] +849021,why am i getting windowserror error 5 access is denied trying to create program that adds folders into program filesrecieving this error windowserror error 5 access is denied cprogram filesimphere is my codeimport os sys randomnumb 1xtruewhile xtrue newpath rcprogram filesimpfolder s numb if not ospathexistsnewpath osmakedirsnewpath numbnumb1 if numb11 xfalse,['python'] +849155,simd latency throughput on the intel intrisics guide for most instructions it also has a value for both latency and throughput example m128i mm min epi32performancearchitecture latency throughputhaswell 1 05ivy bridge 1 05sandy bridge 1 05westmere 1 1nehalem 1 1what exactly do these numbers mean i guess slower latency means the command takes longer to execute but throughput 1 for nehalem and 05 for ivy means the command is faster on nehalem,['c++'] +849173,extract identify tables from pdf python are there any open source libraries that support table identification extractionby this i mean identify a table structure existsclassify the table from its contentsextract data from the table in a useful output format eg json csv etci have looked through similar questions on this topic and found the followingpdfminer which addresses problem 3 but it seems the user is required to specify to pdfminer where a table structure exists for each table correct me if i am wrongpdftableextract which attempts to address problem 1 but according to the todo list cannot currently identify tables that are separated by whitespace this is a problem as all tables in my pdfs are separated by whitespacecurrently i am thinking that i would have to spend a lot of time developing a machine learning solution to identify table structures from pdfs therefore any alternative approaches would be more than welcome,['python'] +849220,orientdb sql query to select edge and vertex fields property i do have following database structure users comment productsa users and products are the vertexes that contain some info etc user name product name and b comment is the edge that contains comment and createdmodified date what is the sql query may look like in order to show the following result note i have to show all of the products that may have or no have comment product name user name comment comment created date comment modified dateproduct name user name product name user name comment comment created date comment modified date,['sql'] +849493,how to generate a barcode from a string in swift i am a new ios developer i was wandering how to generate a barcode in swifti have the code already there are multiple resources from where to learn how to read a barcode but i did not found any that talks about generating one from a stringthanks a lotps i know there is a similar question about this but in objectivec i do not know oc and i find it difficult coming from net,['ios'] +849508,simple injector lifestyle warnings for web api controllers i am following the docs on the simple injector docs sitevar container new containercontainerregisterwebapicontrollersconfigcontainerverifyvar results analyzeranalyzecontainerresultsshould havecount0 stringjoin environmentnewline resultsselectx xdescriptionhowever when i run my test i get the following errorxunitsdkassertexception expected collection to contain 0 items because mycontroller is registered as transient but implements ithisposable but found 1i am not sure how to set the scope for controllers as the method containerregisterwebapicontrollersconfig is part of the webapi package and does not have any overloads how do i set these to per web request elsewhere i would do this containerregisteripinger pingerlifestyle but it seems like i should be using the packaged helper methodadd this line in to filter out the unwanted false negativesresults resultswherex xservicetypebasetype typeof apicontroller xdescriptioncontainsithisposable toarray,['c#'] +849579,create circular reveal for prelollipop devices android is it possible to get this new animator for prelollipop devicesi am newbie and i am trying to get the java files from its official documentation but i am really lost i do not know how to find it etc,['android'] +849582,dataoriented tree traversal without recursion i have a tree structure like this a model has a root node and each node has any number of child nodes and also any number of meshesalot of time in my application is spent traversing this tree and doing computations like view frustrum culling and doing matrix multiplications currently it is naively implemented where each node has vectors of child nodes and meshes and the tree is recursively traversed this is very slowi have been looking at dataoriented design and i like the idea of it being very cache friendly i have been thinking of something like thisstruct mesh misc data meshid mmeshid probably needs more informationstruct node begin and end index into models mnodes uint32 t mchildrenbegin uint32 t mchildrenend as above but for meshes uint32 t mmeshesbegin uint32 t mmeshesendstruct model stdvectornode mnodes stdvectormesh mmeshesnow i need to traverse the tree to get a list of visible meshes at each node i must check if the node is visible the following branchesthe node is visible all child nodes and meshes below it are visible too dont go deeper into this branch check other nodes at the same depththe node is not visible no child nodes or meshes at this node or below it will be visible dont go deeper into this branch check other nodes at the same depththe node is partially visible some nodes andor some meshes are visible must go deeper into hierarchythe tree is static once a model is loaded in the application the tree never changes so somehow surely i must be able to use this information to get an efficient structurei am puzzled how to approach this thougha couple of questionshow do i layout the nodes in memory is the root node the first index are the other nodes added based on depthhow do i iterate the tree without using recursion i do not want to visit each node unless i really have to for example if a node at depth2 is not visible all its meshes and children and their meshes should not be tested but skipped completely,['c++'] +849738,loading html file to webview on android from assets frolder using android studio i am using android studiogradleappsrcmainandroid asset folder has the file called charthtmli am trying to load this file to my webview like thiswebview view new webviewthisviewgetsettingssetjavascriptenabledtrueviewloadurlfileandroid assetcharthtmlsetcontentviewviewbut i always get the error could not be loaded because err file not foundwhat am i missing here,"['java', 'android']" +850035,why does ostreamwrite require aconst char typea instead of aconst voida in c the fwrite function in c uses const void restrict buffer as the first argument so you can pass pointer to your struct as the first parameter directlyeg fwritesomestruct sizeofsomestruct 1 filebut in c the ostreamwrite requires const char type which forces you to use reinterpret cast in visual studio 2013 it is const char ostreamwriteeg filewritereinterpret castcharsomestruct sizeofsomestructin almost all cases the binary data to be written to files is not a char array so why does the standard prefer the style which seems more complexps1 actually i used the write method in ofstream with iosbinary mode but according to the reference it inherits ofstream so i use ostreamwrite above2 if you want to print a stream of characters you could use operatoris not write method designed for writing raw data3 if write is not the way to write binary data then what is the way to do it within the standard although this may bother portability of the code due to various memory align strategies on different platforms,['c++'] +850054,postgresql foreign key syntax i have 2 tables as you will see in my posgresql code below the first table students has 2 columns one for student name and the other student id which is the primary key in my second table called tests this has 4 columns one for subject id one for the subject name then one for a student with the higest score in a subject which is higheststudent id am trying to make higheststudent id refer to student id in my students table this is the code i have below am not sure if the syntax is correctcreate table students student id serial primary key player name textcreate table tests subject id serial subject name higheststudent id serial references studentsis the syntax higheststudent id serial references students correct because i have seen another one like higheststudent id references studentsstudent idwhat would be the correct way of creating the foreign key in postgresql please,['sql'] +850222,getting specific ids from indexeddb in my project i am using browsers indexeddb and i would like to retrieve some objects from the db with specific ids according to mdn you could use ranges to get the results you wantaccording to mdn only match donnavar singlekeyrange idbkeyrangeonlydonna match anything past bill including billvar lowerboundkeyrange idbkeyrangelowerboundbill match anything past bill but do not include billvar lowerboundopenkeyrange idbkeyrangelowerboundbill true match anything up to but not including donnavar upperboundopenkeyrange idbkeyrangeupperbounddonna true match anything between bill and donna but not including donnavar boundkeyrange idbkeyrangeboundbill donna false true to use one of the key ranges pass it in as the first argument of opencursoropenkeycursorindexopencursorboundkeyrangeonsuccess functionevent var cursor eventtargetresult if cursor do something with the matches cursorcontinue however what do you do if you wish to get an array of specific ids that are not in order and are not sequential ex918193424501 with a single request,['javascript'] +850241,keep keyboard on when uialertcontroller is presented in swift when the alert pops up the keyboard is thismissed i have looked everywhere but did not find solutions to keep the keyboard visible when alert is presented the textfield seems to resign first responder automatically as the alert is presented modally how is it possible to keep the keyboard behind this alert which means the textfield still editing even if no interaction will be possible,['ios'] +850301,entity framework 1to1 relationship via association table not working in edmx i have the following tables in sql server databasewhich has a 11 association table foobar which has unique indexes on corresponding fooid barid and the primary key is fooid baridto be clear foobar does not allow any fooid due to unique constraint to be in the table more than once neither can any barid due to unique constraint be in the table more than once this is what makes it a 11 associative tablei want to have this association table instead of 11 relationship between foo and bar because in my real world scenario bar will have other relationships to different unrelated tables and i will want similar association tables as opposed to adding new fk columns to bar for each new tablewhich i then bring these tables into my edmx designer the relationship is brought in as a many to many instead of one to onewhich of course is not what i want i can manually change the model to a 11 relationshipbut then i get an error in the designeris this a bug or is it not possible to create a 11 association in this manner in ef,['c#'] +850332,how to pass a swift struct as parameter to an objectivec method i have an objective c that accepts an id parameters and i want to pass it a swift structfile objcclassmimplementation objcclass voidaddlisteneridlistener do something with listenerfile demostructswiftstruct demostruct func registeraslistener objcclassaddlistenerself cant find a way to do this the compile error message i gettype demostruct does not conform to protocol anyobjectso my question would be how do i make an objectivec method accept any instead of anyobject and is there such a thing,['objective-c'] +850352,filenamewhl is not supported wheel on this platform i would like to install scipy0151cp33nonewin amd64whl that i have saved to local drive i am usingpip 608 from cpython27libsitepackagespython 279 default dec 10 2014 122803 msc v1500 64 bit amd64when i runpip install scipy0151cp33nonewin amd64whli get the following errorscipy0151cp33nonewin amd64whlwhl is not supported wheel on this platformi would like to know where is the problem,['python'] +850384,what is the difference if any between x and x initialization i am trying to understand the semantic difference between these two ways of initializationfoo fooxfoo foo xi am interested to know the difference in the following casesx is of type foofoo has a constructor that takes an argument of the same type as that of xx is not of type foo but a converting constructor is availablex is not of type foo but an explicit converting constructor is availableby difference i mean in each caseconceptually which constructors are invokedwhich constructors calls are usually optimized away by the compileris implicit conversion allowed,['c++'] +850506,conditional build based on environment using webpack i have some things for development eg mocks which i would like to not bloat my thistributed build file within requirejs you can pass a config in a plugin file and conditonally require things in based on thatfor webpack there does not seem to be a way of doing this firstly to create a runtime config for an environment i have used resolvealias to repoint a require depending on the environment eg all settingsvar all fish salmon envsettings is an alias resolved at build timemoduleexports objectassignall requireenvsettingsthen when creating the webpack config i can dynamically assign which file envsettings points to ie webpackconfigresolvealiasenvsettings envhowever i would like to do something likeif settingsmock shortcircuit ajax calls require in all the mock modulesbut obviously i do not want to build in those mock files if the environment is not mocki could possibly manually repoint all those requires to a stub file using resolvealias again but is there a way that feels less hackyany ideas how i can do that thanks,['javascript'] +850538,java 8 automatically using multicore i did some tests a year ago concerning multicore with java 7 first i implemented some calculations only in the main thread cpu usage showed that only one core did all the work and then i implemented callable with an executorservice instance while running it all cores where doing the worknow one year later i have to implement a little programm using java 8 which interpolates a lot of data all the work is implemented in the main thread without callable and executorservice but when i am running the programm the cpu usage shows me that all 4 cores are at 98so does java 8 automatically thistribute the work on all cpu cores i am confusedhere some codemapgeneratorjava region regions new regionnumofregionsnumofregions forint x 0 x regionslength x forint z 0 z regionsxlength z newlat srtmhandlergetnewlatitudestartlat z regionsize 16 newlon srtmhandlergetnewlongitudestartlon x regionsize 16 newlat regionsxz new regionx z regionsize newlat newlon regionjavaprivate chunk chunks public regionint x int z int size float startlat float startlon thischunks new chunkthissizethissize init stuff float newlat thisstartlat newlon thisstartlon forint newx 0 newx thissize newx forint newz 0 newz thissize newz newlat srtmhandlergetnewlatitudethisstartlat newz 16 newlon srtmhandlergetnewlongitudethisstartlon newx 16 newlat thischunksnewxnewz new chunkthisx thissize newx thisz thissize newz 16 900 this newlat newlon chunkjava srtmhandlergetheightforlatlon does some geo calculations and then reads a value in a byte array nothing specialpublic chunkint x int z int size int height region r float startlat float startlon thisblocks new blocksizesizeheight init stuff try thiscalcsurface systemoutprintlnfinished thistostring catch ioexception e todo autogenerated catch block eprintstacktrace private void calcsurface throws ioexception int x1 thisx int x2 thisx 16 int z1 thisz int z2 thisz 16 final int radius 45 float q11 srtmhandlergetheightforlatlonsrtmhandlergetnewlatitudethisstartlat 1radius srtmhandlergetnewlongitudethisstartlon 1radius thisstartlat float q12 srtmhandlergetheightforlatlonsrtmhandlergetnewlatitudethisstartlat radius srtmhandlergetnewlongitudethisstartlon 1radius thisstartlat float q21 srtmhandlergetheightforlatlonsrtmhandlergetnewlatitudethisstartlat 1radius srtmhandlergetnewlongitudethisstartlon radius thisstartlon float q22 srtmhandlergetheightforlatlonsrtmhandlergetnewlatitudethisstartlat radius srtmhandlergetnewlongitudethisstartlon radius thisstartlat forint x 0 x thisblockslength x forint z 0 z thisblocksxlength z float height interpolationbilerpx z q11 q12 q21 q22 x1 x2 z1 z2 thisblocksxzintmathroundheight new blockthisx thissize x thisz thissize z intmathroundheight blocktypegrass this,['java'] +850570,laravel requestall should not be called statically in laravel i am trying to call input requestall on a store method in my controller but i am getting the following errornonstatic method illuminatehttprequestall should not be called statically assuming this from incompatible contextany help figuring out the best way to correct this i am following a laracast,['php'] +850619,what are direct and indirect subclasses i was looking at android development documentation and i saw thispublic abstract classbufferextends objectknown direct subclassesbytebuffer charbuffer doublebuffer floatbuffer intbuffer longbuffer shortbufferknown indirect subclassesmappedbytebufferbuffer is a abstract class that cannot be instaniated it inheritents extends objectbut i am confused about the direct and indirect subclassesmy best guesses would bedirect extend directly from the super classindirect it extends from a super class that directly extends the class in questionmany thanks for any suggestions,['java'] +850644,jquery datatables left align sort icon as you can see the sort icons on my datatable are on the far right of the columnis it possible to align these on the left so they appear just after the textie technician completed date thank youcode as requested div classdatatable wrapper table classtable tablestriped tablehover idtabled thead tr th trans id endtrans th th trans technician endtrans th th trans date endtrans th th trans summary endtrans th tr thead table divandtableddatatable processing true serverside true ajax pathtable data pagelength 10,"['jquery', 'html', 'css']" +850666,how can i normalize the data in a range of columns in my pandas dataframe suppose i have a pandas data frame surveydatai want to normalize the data in each column by performingsurveydata norm surveydata surveydatamean surveydatamax surveydataminthis would work fine if my data table only contained the columns i wanted to normalize however i have some columns containing string data preceding likename state gender age income heightsam ca m 13 10 70bob az m 21 250 55tom fl m 30 10 45i only want to normalize the age income and height columns but my above method does not work becuase of the string data in the name state and gender columns,['python'] +850694,android proguard multidex causes classnotfoundexception i have multidex enabled in my android project it was working fine until i tried enabling proguard i can successfully build the project but i get runtime exception on startup it is unable to find the application class and the mainactivity i had the same problem before enabling multidex now i guess for some reason the multidex is not working properly with proguard here is what i get in the logcat 0217 190109749 imultidex2079 vm with version 210 has multidex support0217 190109749 imultidex2079 install0217 190109749 imultidex2079 vm has multidex support multidex support library is thisabled0217 190109750 iart2079 rejecting reinit on previouslyfailed class javalangclassandroidsupportv4appfragmentactivity0217 190109750 iart2079 rejecting reinit on previouslyfailed class javalangclassandroidsupportv4appfragmentactivity0217 190109751 iart2079 rejecting reinit on previouslyfailed class javalangclassmypackageactivitiesmainactivity0217 190109751 iart2079 rejecting reinit on previouslyfailed class javalangclassmypackageactivitiesmainactivity0217 190109751 dandroidruntime2079 shutting down vm0217 190109751 dandroidruntime2079 beginning of crash and after that the rest of the stack trace is about classnotfoundexception for the mainactivity 0217 190109752 eandroidruntime2079 fatal exception main0217 190109752 eandroidruntime2079 process commypackage pid 20790217 190109752 eandroidruntime2079 javalangnoclassdeffounderror failed resolution of lcommypackageactivitiesmainactivity0217 190109752 eandroidruntime2079 at cmypackageapplicationapplicationcontextprovideroncreateunknown source0217 190109752 eandroidruntime2079 at androidappinstrumentationcallapplicationoncreateinstrumentationjava10110217 190109752 eandroidruntime2079 at androidappactivitythreadhandlebindapplicationactivitythreadjava45180217 190109752 eandroidruntime2079 at androidappactivitythreadaccess1500activitythreadjava1440217 190109752 eandroidruntime2079 at androidappactivitythreadhhandlemessageactivitythreadjava13390217 190109752 eandroidruntime2079 at androidoshandlerthispatchmessagehandlerjava1020217 190109752 eandroidruntime2079 at androidoslooperlooplooperjava1350217 190109752 eandroidruntime2079 at androidappactivitythreadmainactivitythreadjava52210217 190109752 eandroidruntime2079 at javalangreflectmethodinvokenative method0217 190109752 eandroidruntime2079 at javalangreflectmethodinvokemethodjava3720217 190109752 eandroidruntime2079 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava8990217 190109752 eandroidruntime2079 at comandroidinternaloszygoteinitmainzygoteinitjava6940217 190109752 eandroidruntime2079 caused by javalangclassnotfoundexception did not find class mypackageactivitiesmainactivity on path dexpathlistzip file dataappmypackage1baseapknativelibrarydirectoriesvendorlib systemlib0217 190109752 eandroidruntime2079 at dalviksystembasedexclassloaderfindclassbasedexclassloaderjava560217 190109752 eandroidruntime2079 at javalangclassloaderloadclassclassloaderjava5110217 190109752 eandroidruntime2079 at javalangclassloaderloadclassclassloaderjava4690217 190109752 eandroidruntime2079 12 more0217 190109752 eandroidruntime2079 suppressed javalangnoclassdeffounderror mypackageactivitiesmainactivity0217 190109752 eandroidruntime2079 at dalviksystemdexfiledefineclassnativenative method0217 190109752 eandroidruntime2079 at dalviksystemdexfiledefineclassdexfilejava2260217 190109752 eandroidruntime2079 at dalviksystemdexfileloadclassbinarynamedexfilejava2190217 190109752 eandroidruntime2079 at dalviksystemdexpathlistfindclassdexpathlistjava3210217 190109752 eandroidruntime2079 at dalviksystembasedexclassloaderfindclassbasedexclassloaderjava540217 190109752 eandroidruntime2079 14 more0217 190109752 eandroidruntime2079 suppressed javalangclassnotfoundexception mypackagemainactivity0217 190109752 eandroidruntime2079 at javalangclassclassfornamenative method0217 190109752 eandroidruntime2079 at javalangbootclassloaderfindclassclassloaderjava7810217 190109752 eandroidruntime2079 at javalangbootclassloaderloadclassclassloaderjava8410217 190109752 eandroidruntime2079 at javalangclassloaderloadclassclassloaderjava5040217 190109752 eandroidruntime2079 13 more0217 190109752 eandroidruntime2079 caused by javalangnoclassdeffounderror class not found using the boot class loader no stack availableedithere is my proguard rules file libraryjars libs we only want obfuscationkeepattributes innerclassessignaturedontusemixedcaseclassnamesdontskipnonpubliclibraryclassesdontpreverifydontoptimizeverbose sdkkeep public interface comzendesksdk keep public class comzendesksdk appcompat and supportkeep interface androidsupportv7 keep class androidsupportv7 keep interface androidsupportv4 keep class androidsupportv4 gsonkeep interface comgooglegson keep class comgooglegson retrofitkeep class comgoogleinject keep class orgapachehttp keep class orgapachejamesmime4j keep class javaxinject keep class retrofit keep interface retrofit retrofitkeep class comsquareupokhttp keep interface comsquareupokhttp dontwarn comsquareupokhttpdontwarn rxdontwarn retrofitdontwarn okiokeep class retrofit keepclasseswithmembers class retrofithttp methods jacksonkeepattributes annotationenclosingmethodsignaturekeepnames class comfasterxmljackson dontwarn comfasterxmljacksondatabind keep class orgcodehaus keepclassmembers public final enum orgcodehausjacksonannotatejsonautodetectvisibility public static final orgcodehausjacksonannotatejsonautodetectvisibility keep public class mypackageparsersjacksonparser public void set public getpicassodontwarn comsquareupokhttpdontwarn javaxmanagementdontwarn javalangmanagementdontwarn orgapachelog4jdontwarn orgapachecommonsloggingdontwarn orgjsondontwarn orgapachecommonscodecbinarybase64keep class javax keep class org dontwarn orgmortbaydontwarn orgslf4jdontwarn orgapachelog4jdontwarn orgapachecommonsloggingdontwarn orgapachecommonscodecbinary,['android'] +850750,files loading slower on second run of application with repro code application descriptioni have an offline data processing tool this tool loads hundreds of thousands of files for each one it performs some calculations and when done writes a single index file it is all c all io is via standard library objectsfunctions and is being compiled with visual studio 2013 targeting amd64performancemy test dataset has 115757 files that need to be processed files total 731mb in size and the median file size is 6kbfirst run 12 secondssecond run 18 minutesthats 90x slower the second run is extrapolated from one minute of run time all runs after that as i have experienced thus far are equally slowsurpriseif i rename the folder with the files in it and then rename it back to what it originally was the next time i run the application it will again perform quicklyits the same app machine and source data the only difference is that one folder was temporarily renamedso far i can reproduce this 100 of the timeprofilingnaturally the next step was to profile i profiled the quick run and the slow run and compared the hot spots in the slow version about 86 of the application was spent in a function called ntfsfindprefix the quick version spends about 04 of its time here this is the call stackntfssysntfsfindprefixitselfntfssysntfsfindprefixntfssysntfsfindstartingnodentfssysntfscommoncreatentfssysntfscommoncreatecalloutntoskrnlexekyswitchkernelstackcalloutntoskrnlexekiswitchkernelstackcontinuentoskrnlexekeexpandkernelstackandcalloutexntfssysntfscommoncreateonnewstackntfssysntfsfsdcreatefltmgrsysfltplegacyprocessingafterprecallbackscompletedfltmgrsysfltpcreatentoskrnlexeiopparsedevicentoskrnlexeobplookupobjectnamentoskrnlexeobopenobjectbynamentoskrnlexentqueryattributesfilentoskrnlexekisystemservicecopyendntdlldllntqueryattributesfilekernelbasedllgetfileattributeswdatageneratorexeboostfilesystemdetailstatusthe boost call in question is an exists call it will test for the zipped version of a file fail to find it and then test for the unzipped one and find itprofiling also showed that the thisk did not get hit by either runs of the application however file io was expectedly high i believe this indicates that the files were already paged to memoryfile io also showed that the duration of file create events were on average much higher in the slow version 26 us vs 11704 usmachinesamsung ssd 830 seriesintel i7 860windows 7 64 bitntfs file system32gb ramsummaryon the second run the calls into ntfsfindprefix take much longerthis is a function in the ntfs driverthe thisk did not get hit in either profiles the files were served from pages in memorya rename operation seems to be enough to stop this issue occurring on the next runquestionnow that the background info is out of the way does anyone recognise what is going on and know how to fix itit seems like i could work around it by renaming the folder myself but that seemsdirty plus im not sure what that even worksis the rename invalidating the pages in memory and causing them to get updated before the next run is this a bug in the ntfs driverthanks for readingupdateafter some more profiling it looks like the part that is performing slower is testing to see if the nonexistent zipped file exists if i remove this test everything seems to get quicker againi have also managed to reproduce this issue in a small c app for everyone too see note that the sample code will create 100k 6kb files on your machine in the current directory can anyone else repro it using vs tr2 could replace with boostfilesysteminclude filesystemnamespace fs stdtr2sysnamespace fs boostfilesysteminclude iostreaminclude stringinclude chronoinclude fstreamvoid createfiles fspath outdir create 100k 6kb files with junk data in them it does not matter that they are all the same fscreate directory outdir char buf6144 for int i 0 i 10 i stdofstream fout outdir fspath stdto string i stdiosbinary foutwrite buf 6144 fsrename outdir fspath outdirstring tmp fsrename fspath outdirstring tmp outdir int main int argv const char argc fspath outdir out if fsexists outdir createfiles outdir auto start stdchronohigh resolution clocknow int counter 0 for fsrecursive directory iterator i outdir iend i iend i test the non existent one then the other if fsexists fspath ipathstring z fsexists ipath counter 1 if counter 100 0 stdcout counter stdendl stdcout counter stdendl auto end stdchronohigh resolution clocknow stdchronoduration double stdmilli s end start stdcout time passed scount ms stdendl return 0update 2i have logged an issue with ms here hopefully they can help shed some light on the issue,['c++'] +850803,net wcf w3wp native memory leak and 18k dynamic assemblies of 0 sizes in loader heap our wcf service showed an instance of large memory usage so we took a full memory dump to identify the issueoperating system windows server 2008 r2service pack 1 number of processors 4 process image cwindowssystem32inetsrvw3wpexe system uptime 40 days 092309 process uptime 14 days 114901 net 40processor type x64 process bitness 64bithelicopter view of the problem from debugdiag reportprocess was garbage collecting so as per warning i should not be trusting all the output from heap commandsgc heap 137 gbytes net cache size is 750mbvirtual memory details virtual allocations 1745 gbloaded modules 20868 mbthreads 25 mbnative heaps 306 gb i am concerned about thisfrom above 302 gb is present on heap 0x003f0 alonewe have good amount of traffic that way 13 gb gc heap size feels normal to me also we have machine with 32 gb ram and 64bit address space so cache size of 750 mb is acceptable as per the size of native heap i feel this is native memory leakdebugdiag warning there are 18149 dynamic assemblies loaded in the dump filehelp links net memory leak xmlserializing your way to a memory leakanalysis we do use xmlserialisers but they are cached that way they are created only oncenet memory leak xslcompiledtransform and leaked dynamic assemblies we seems to have same kind of problem described in this blog post all these 18149 dynamic assemblies are of 0 sizes so i cannot dump them to get details also we do not use xsl transform any where in this application so these assemblies are not due to xsl transformssome more stats related object counts systemreflectionemitinternalmodulebuilder 1 mbytes 18149 objects systemreflectionemitinternalassemblybuilder 99252 kbytes 18149 objects systemreflectionemit fixupdata 59541 kbytes 752 objects systemreflectionemitgenericfieldinfo 58003 kbytes 18561 objects systemreflectionruntimemethodinfo 12 mbytes 11276 objects systemruntimetype 113 mbytes 21228 objects top objects in the finalizer queuesystemreflectionemitdynamicresolver 379systemreflectionemitdynamicresolverdestroyscout 271application domain statisticsdomain default 13 assemblies size 89677824 90 mb domain roottvengine1 18236 assemblies size 152834048 150 mb i guess these leaked dynamic assemblies accounting for 150 mb of space not sure whether 3 gb of native memory is due to these assemblies more digging around with this assemblies dumpdomain give me large unknown dynamic assemblies as below assembly 0fa9d0d0 dynamic classloader 02be1d40securitydescriptor 0fc08a00 module name07fe96d38e68 dynamic moduleand eeheap loader gives same number of 0 sized modules module 07fea0b7b758 size 0x0 0 bytesmodule 07fea0b7c1e8 size 0x0 0 bytesmodule 07fea0b7cc78 size 0x0 0 byteschecked for blocked gc finalizer thread it is not the case from below stack trace it is waiting for finalization event to occur0 20 kchildsp retaddr call site0eedf3b8 07fefd6f1430 ntdllzwwaitformultipleobjects0xa0eedf3c0 077501723 kernelbasewaitformultipleobjectsex0xe80eedf4c0 07fef60939d4 kernel32waitformultipleobjectseximplementation0xb30eedf550 07fef6094799 clrsvrwaitforfinalizerevent0xcc0eedf590 07fef5f0458c clrsvrgcheapfinalizerthreadworker0x4a0eedf5d0 07fef5f0451a clrframepop0x50dump has the same number of systemreflectionemitinternalmodulebuilder and systemreflectionemitinternalassemblybuilder objects as that of leaked dynamic assembliesi noticed systemreflectionemitdynamicresolver in top finalizer queue and dumped all of them and correlated these to dynamic assembly address as followsdumped around 5 dynamicresolver objects and tracked dynamicresolver m method m module 01801728a01801728a0 this is the address of one module from list of internalmodulebuilder list most of them was pointing to same module0 dumpheap type systemreflectionemitdynamicresolver address mt size018017d5a8 07fef4c7c8b0 72 018018d5b0 07fef4c7c8b0 72 01801931b0 07fef4c7c8b0 72 and on0 do 018017d5a8name systemreflectionemitdynamicresolvermethodtable 07fef4c7c8b0eeclass 07fef4754300size 720x48 bytesfile cwindowsmicrosoftnetassemblygac 64mscorlibv40 40 b77a5c561934e089mscorlibdllfields mt field offset type vt attr value name07fef4c458 4002a 8 systemobject 0 instance 0 m exceptions07fef4c9a690 4002aab 10 systembyte 0 instance 0 m exceptionheader07fef4ca20c0 4002aac 18 mitdynamicmethod 0 instance 0180172690 m method07fef4c9a690 4002aad 20 systembyte 0 instance 018017d5f0 m code07fef4c9a690 4002aae 28 systembyte 0 instance 018017d650 m localsignature07fef4c992b8 4002aaf 38 systemint32 1 instance 3 m stacksize07fef4c7c788 4002ab0 30 emitdynamicscope 0 instance 0180172b80 m scope0 do 0180172690 name systemreflectionemitdynamicmethodmethodtable 07fef4ca20c0eeclass 07fef475e298size 1120x70 bytesfile cwindowsmicrosoftnetassemblygac 64mscorlibv40 40 b77a5c561934e089mscorlibdllfields mt field offset type vt attr value name07fef4c458 4002ac6 8 systemobject 0 instance 0180172700 m parametertypes07fef4cafa88 4002ac7 10 runtimemethodinfo 0 instance 018017d678 m methodhandle07fef4c987f8 4002ac8 18 systemruntimetype 0 instance 04800e7900 m returntype07fef4c7c578 4002ac9 20 ynamicilgenerator 0 instance 0180172a30 m ilgenerator07fef4c4eb18 4002aca 28 mitdynamicilinfo 0 instance 0 m dynamicilinfo07fef4c97de0 4002acb 60 systemboolean 1 instance 1 m finitlocals07fef4c9f1d8 4002acc 30 ionruntimemodule 0 instance 01801728a0 m module07fef4c97de0 4002acd 61 systemboolean 1 instance 0 m skipvisibility07fef4c987f8 4002ace 38 systemruntimetype 0 instance 0 m typeowner07fef4c7c330 4002acf 40 drtdynamicmethod 0 instance 01801729d8 m dynmethod07fef4c7c8b0 4002ad0 48 tdynamicresolver 0 instance 018017d5a8 m resolver07fef4c97de0 4002ad1 62 systemboolean 1 instance 0 m profileapicheck07fef4c99d18 4002ad2 50 nruntimeassembly 0 instance 0 m creatorassembly07fef4c97de0 4002ad3 63 systemboolean 1 instance 1 m restrictedskipvisibility07fef4c88d70 4002ad4 58 gcompressedstack 0 instance 01801729b0 m creationcontext07fef4c88020 4002ad5 16b8 rnalmodulebuilder 0 shared static s anonymouslyhosteddynamicmethodsmodule domainvalue 02b66ba0notinit 02c24a901801728a0 07fef4c96ae8 4002ad6 16c0 systemobject 0 shared static s anonymouslyhosteddynamicmethodsmodulelock domainvalue 02b66ba0notinit 02c24a90180172798 opened log file cdebugnew dynamic asmlog0 dumpheap type systemreflectionemitinternalmodulebuilder address mt size01800fe918 07fef4c88020 64 01801728a0 07fef4c88020 64 018017fa88 07fef4c88020 64 01801bee20 07fef4c88020 64 and oni am not that handy with windbg can somebody give me some clues how to relate above dynamic modules to reach out to buggy code i believe this is due to linq or lambda expressionas per report size of dynamic assemblies is 150 mb is 3 gb leak will be any different or dynamic modules might be linking to some native memoryheap l gave me 188722 potential unreachable blocks were detectednative heap statistics using windbg pykd plugin gave me below stats of native heapnotice the values rolling around 180statistics type name count size clrrecordpool 817335 unknown clrregmeta 272445 unknown clrcblobpoolhash 36326 unknown clrmdinternalrw 36326 unknown clrstgblobpool 36326 unknown clrcceegen 36298 unknown clrpeassembly 18267 unknown clrassemblysecuritydescriptor 18249 unknown clrdomainassembly 18249 unknown clrsharedsecuritydescriptor 18236 unknown clrcstringpoolhash 18163 unknown clrcminimdrw 18163 unknown clrstgguidpool 18163 unknown clrstgstringpool 18163 unknown clrccustattrhash 18163 unknown clrcguidpoolhash 18163 unknown clrpesectionman 18149 unknown clrceesectionstring 18149 unknown clrpesection 18149 unknown nativerdconfig element 4932 unknown nativerdattribute value 3912 unknown nativerdschema attribute 1473 unknown clrcassemblyname 16 unknown nativerdcollection key entry 919 unknown nativerdschema element 766 unknown clrassemblymdinternalimport 720 unknown nativerdconfig section 652 unknown nativerdconfig collection 570 unknown clrlistnodechashnode ptr64 4 unknown,"['c#', '.net']" +851007,using dependency in swift module framework i am trying to create a swift module cocoa touch framework with reusable code inside the environment set up by cocoa pods which includes third party libraries written in objectivec namely here restkitunfortunately i am not able to use restkit in the module i createheres what i did to create the modulefile new target cocoa touch framework language swift project myproject embed in application myprojectin the info tab of the project settings in the configurations section i define the podsdebug and podsrelease xcconfig file for my newly created targetin the header file which xcode automatically created for me networkmoduleh i add the following lineimport restkitrestkithresult when trying to compile i get the error include of nonmodular header inside framework module networkmodulei have set the flag for allow nonmodular includes in framework modules to yes in the build settings for the project target and the moduleframework targeti went to the cocoa pod project and have tried setting the visibility of the restkith header file to public in the target membership which of course is not a good solution to mess with the cocoa pods environmenti am not able to compile i still get the same erroris it possible in the first place to create a cocoa touch framework with dependencies to a cocoa pod managed frameworkbtw my first idea of creating a private cocoa pod did not work out as well as it does not seem to be supported although i am using the prerelease of cocoa pods 036 with support for swift,['ios'] +851068,flag activity reorder to top causing runtimeexception or black screen on rotation i have two activities and i want to switch between them without recreating or duplicating them each activity has a button that will send the user to the other using an intent with the flag activity reorder to top this works great except for the following conditionstart the app fresh after a force closehit the button to go to activity 2hit the button to go back to activity 1rotate the screenat this point the app crashes with performing stop of activity that is not resumed lollipop just shows a black screenweirdly if you go to the home screen before step 4 and resume the app and then rotate the above condition does not have any problem and the app works fine until it is closedrestartedthis condition seems specific to flag activity reorder to top and happens on android 50 and 44 and only on a fresh starti have no attributes on the activities in the manifest the layouts just have a button that calls a method that looks like thismainactivitypublic void gosecondview v intent i new intentthis secondactivityclass isetflagsintentflag activity reorder to front startactivityisecondactivity public void gofirstview v intent i new intentthis mainactivityclass isetflagsintentflag activity reorder to front startactivityi i am not overriding any other lifecycle methods or doing anything elseany ideas,['android'] +851086,how long ago did i load a page is there a way to get how long ago a page was loaded using javascript without having first recorded the time to a javascript variable on page load i am hoping to create a scriptlet javascript bookmark that i can run on any web page and have it output how much time has passed since the browser loaded the pageall of the time spent on a page solutions i have found so far rely on recording the time when the page first loads which requires either access to modify a site or a browser plugin is there no document property that stores when the page was loaded started finished etc which can be accessed in javascript,['javascript'] +851105,create a spiders web under a hr element in css i am trying to generate a spiders web under a hr element but am having some issue when it comes to the circular parts i am avoiding insertingusing svg since this may or may not be inserted by the user ie user may include an hr element in a post for example and i want the web to appear there alsothis would suggest that the hr element would need to be styled in such a way that this would appear under all instances of the hr element suggesting littleno extra html elements i have included a quick mockup of what i am trying to achieve belowwanted resultsomething like this image portrayscurrent codeat present i am struggling to make the spindles between the two pseudo elements and the closest way i have generated the spindles is like thishtml margin0 padding0 backgroundrgba01 colorblack hr height30px borderbottomnone borderrightnone positionrelative hrbefore hrafter contentm positionabsolute height40px width1px top0 left0 transformorigintop left transformrotate20deg backgroundblackhraftertransformrotate40deg hr this of course looks terrible mainly to do with the horrible ms overlapping but i cannot seem to find a way of generating this kind of shape without themattempts so fari have attempted to make the web links by using different letters within the content of the pseudo elementsi have tried using curvesoverflow hidden but this failed miserably i might addi would really appreciate any and all responses to this and if it was possible using pure css it would be even better but right now i am at a lose as to how to achieve this sort of functionality,"['html', 'css']" +851212,why is the bigo of this algorithm n2log n fill array a from a0 to an1 generate random numbers until you get one that is not already in the previous indexes this is my implementationpublic static int firstint n int a new intn int count 0 while count n boolean issame false int rand rnextintn 1 for int i 0 i n i ifai rand issame true if issame false acount rand count return ai thought it was n2 but it is apparently n2logn and i am not sure when the log function is considered,['java'] +851227,gulp copy and rename a file i am extremely new to gulp i am basically trying to watch for a modified javascript file and then make a new copy of it with a new name eventually therell be some processing on it but rome was not built in a daymy naive attempt is thisgulptaskdefault function return gulpwatchjs functionobj gulpsrcobjpath pipegulpdestfoobarjs this takes the modified file and successfully copies it into a folder now called foobarjs is there anything simple i can replace gulpdestfoobarjs with that will simply copy and rename the src file in placeeditby copy in place i mean i want to take the modified file and make a copy of it right where it currently is with a new name the equivalent of clicking the file in windows and hitting controlc controlv then renaming the resulting file,['javascript'] +851313,throw an exception if an optional is present let us say i want to see if an object exists in a stream and if it is not present throw an exception one way i could do that would be using the orelsethrow methodliststring values new arraylistvaluesaddonevaluesaddtwo exception thrownvaluesaddthreestring two valuesstream filters sequalstwo findany orelsethrow new runtimeexceptionnot foundwhat about in the reverse if i want to throw an exception if any match is foundstring two valuesstream filters sequalstwo findany ifpresentthrow new runtimeexceptionnot foundi could just store the optional and do the ispresent check afteroptionalstring two valuesstream filters sequalstwo findanyif twoispresent throw new runtimeexceptionnot foundis there any way to achieve this ifpresentthrow sort of behavior is trying to do throw in this way a bad practice,['java'] +851385,spacing between uitableviewcells i am creating a ios app in swift and want to add spacing between cells like facebook pic bellowi am using a custom nib for the posts i know to use uitableviewcontroller i figure i would use a separator style but it does not achieve the effect i goggled around for hours and cannot find a single tutorial in swift that makes sense could some one explain how they did it in there app using swift thanks,['ios'] +851437,format timezone for carbon date i am trying to set the timezone for a date in a carbon object it works fine locally but on my production box it keeps giving me bad timezone errori have trieddatesettimezone7datesettimezone7datesettimezone700datesettimezone700datesettimezoneutc 7datesettimezoneutc 7datesettimezoneutc 700datesettimezoneutc 700no idea why it is complaining on my production box cannot find documentation either on what is the proper format to enter here can someone please helpfyi local is windows and prod is ubuntu box,['php'] +851499,how to get breakpoint in ndk native code and debug native code in android studio i am developing android app using ndk i have two projects one is for my native library which uses ndk and generates so filei am using android studio but thisabling auto build and enabled build using ndkbuild i am using windows 7 now after generating so file i copy those in my main application project which also uses ndkbuild to compile jni functions in which i am calling functions of my library i hope i am clean till this point if not then i will give more detail on request now i am running my application in device using android studio and i can put break point in java code and debug that code but i am not able to debug jni call and also native code which i have in separate project i need to debug inside my library code so is there any way to achieve thisi have seen visualgdb but it is paid so let me know if there is any alternative to full fill my debugging requirementsi have searched lot but did not get any concrete solutioni can see option in android studio for attaching to android process where i can see my running device but i am not sure how to use it so i can debug by native library code which is in separate project without any activity let me know if more detail is required,['android'] +851624,real world examples of using reduceright in javascript a while ago i posted a question on stackoverflow showing that the native implementation of reduceright in javascript is annoying hence i created a haskellstyle foldr function as a remedyfunction foldrarray callback initial var length arraylength if argumentslength 3 if length 0 var result arraylength else throw new errorreduce of empty array with no initial value else var result initial while length 0 var index length result callbackarrayindex result index array return resulthowever i never used this foldr function simply because i never needed to iterate over an array from righttoleft this got me thinking why do not i use foldr in javascript as much as i do in haskell and what are some real world examples of using foldr in javascripti could be wrong but i believe that the foldr function is used widely in haskell because oflazy evaluation foldl is tail recursive so how come foldr runs faster than foldlshort cut fusion using foldrbuild correctness of short cut fusion foldrbuildthis would explain why foldr or reduceright are not widely used in javascript i have yet to see a real world use of foldr only for its righttoleft iteration orderthis brings me to my two questionswhat are some real world examples of using reduceright in javascript perhaps you have used it in an npm package it would be great if you could link me to your code and explain why you needed to use reduceright instead of reducewhy is reduceright not used as widely as reduce is in javascript i already provided my two cents on this matter i believe that foldr is primarily used only for its laziness which is why reduceright is not very useful in javascript however i could be wrongfor the first question i tried to find some real world examples for using reduceright in javascript however i did not find any satisfactory answers the only examples i found were trivial and theoreticalwhen to use reduce and reducerightwhat i am looking for is a practical example when is it practical to use reduceright in javascript instead of reducefor the second question i understand that it is primarily opinion based which is why it is alright if you do not answer it the main focus of this post is on the first question not the second,['javascript'] +851638,sessions in a microservice architecture for an ecommerce system i plan on developing a microservice ecommerce system as proof of concept the architecture consists of 3 componentsa javascript based single page application which sends ajax requests toa server api gateway with a rest api which feeds json data received by calling other services3 services catalogprovider customersprovider checkoutproviderfor now the services all are api endpoints of a magento shopsystem when i try to log in a user into they magento system by sending a request to the rest api obviously the server does not remember the session when sending the next requestalso i handle the shopping cart on the server side with magento and addupdateremove items by rest api calls here also the added items get lost when sending the next request as the session got lostso my question iswhat are possible approaches to solve issues regarding session handling in a microservice architecture,['php'] +851676,how to convert volume guid of the mount point to actual path i am using this code to get pathvolumelabeltotalsizefreespacegwmi computername computername namespace rootmscluster mscluster thiskpartition credential cred authentication packetprivacy formattable path volumelabel totalsize freespace autosizeoutputpath volumelabel totalsize freespace u archive1 4194184 379651volume76795fb2254e454da95a739018690cf4 archive3 4194184 524883x archive2 4194184 735366volume57e9391060f944b98d9d29d506e1e3d7 archive4 4194184 1483274how i can get real path or maybe drive name of the mounting point from the volume guid i try to use getrelated class but with no success can somebody help me with this,['c#'] +851756,twitter fabric login button only working once i am using with success the fabric login button twtrloginbutton in my swift app i can authenticate myself make calls and all the only problem is that i have implemented a logout button that calls twitterlogoutas specified by the documentation this deletes the local session but does not invalidate the remote session the effect is that once i am authenticated and then logged out if i click the login button again i am loggedin again with the same user effectively preventing me from switching userany help,"['ios', 'objective-c']" +851806,what is encapsulation exactly i have got two definitions of encapsulation which could not fit into one definitionencapsulation is data hiding with the use of private protected and public pack the data into single componentwhatever changes encapsulate it protecting anything which is prone to changehow these two definitions are talking about the same concept,['java'] +851808,why anaconda does not recognize conda command i installed the latest version of anacondanow i want to install opencv within it when i typeconda install c opencvi get this message error conda is not recognized as internal command sorry i try to translate from french because my os is in french the problem is that conda comes with anaconda so i wonder why lauching anaconda and type the above command does not work,['python'] +852008,how to identify the subject of a sentence can python nltk be used to identify the subject of a sentence from what i have learned till now is that a sentence can be broken into a head and its dependents for eg i shot an elephant in this sentence i and elephant are dependents to shot but how do i thiscern that the subject in this sentence is i,['python'] +852035,configure bower to install only thist folder i am trying to learn tools such as bowergruntrequirejs in order to speed up the development process for my website and to make my code more modularizedefficient i am currently following this tutorial how does one make bower only install the thist folder for my dependencies setup in my componentjson file instead of the entire git repository,['javascript'] +852096,php object of class dateinterval could not be converted to string i have tried using date diff and date create to get a difference from two date that is already converted to stringheres the codedate 1 date createdate now date formatdate 1 ymdecho date now ndatedate createdate nowdate adatedate interval create from date string3 daysdate return date formatdateymddiff date diffdate createdate now date createdate returnecho diffand i am getting this errorobject of class dateinterval could not be converted to string,['php'] +852147,protected member function address in derived class is not accessible include iostreamclass a protected void foo class b public a public void bar stdcout afoo stdendl int main b b bbarhere i am trying to get address of protected member function of base class i am getting this errormaincpp in member function avoid bbaramaincpp5 error avoid afooa is protectedmaincpp13 error within this contextmake all error 1changing foo to public works also printing bfoo works can you please explain why we cannot get address of protected member function of base class,['c++'] +852219,ie 754iec 559 is the ie 754 floating point format well defined across platforms in terms of both bit format and endiannessi am willing to add the following to my code for an initial versionstatic assertstdnumeric limitsfloatis iec559 only support iec 559 ie 754 floatstatic assertsizeoffloat char bit 32 only support float single precision iec 559 ie 754static assertstdnumeric limitsdoubleis iec559 only support iec 559 ie 754 doublestatic assertsizeoffloat char bit 64 only support double double precision iec 559 ie 754static assertstdnumeric limitslong doubleis iec559 only support iec 559 ie 754 long doublestatic assertsizeoffloat char bit 128 only support long double exteneded precision iec 559 ie 754 more asserts if required i noticed my current system has a sizeoflong double 128 but numeric limitslong doubledigits 63 so we are not storing quad precision floats only extendedif i write my floatdoublelong double in binary format can these be transported between systems without further interpretation ievoid writestdostream stream double value streamwritereinterpret castchar constvalue 8double readstdistream stream double value streamreadreinterpret castcharvalue 8 return valueor do i need to break the double up into integer components for transport as suggested by this answerthe difference here is i am willing to limit my supported representation to ie754 will this basically solve my binary storage of floating point values or do i need to take further stepsnote for non conforming platforms when i find them i am willing to special case the code so that they readwrite ie754 into local representation but i want to know if the bitendian is well enough defined cross platform to support storagetransport,['c++'] +852281,using gwt 27 in eclipse is there a gwt 27 version of the eclipse pluginif i install the eclipse plugin from the official repository it will list google web toolkit sdk 260 as the only version of gwt available is there no eclipse plugin for 270 and here are som extra text because the text above is aparently not good enough be be a question i really do not understand why and the info box just say that it does not meet our quality standards without mentioning what those are,['java'] +852322,why does mule flow defaultexceptionstrategy have no effect i am using mule standalone 310 and i have a flow with a default exception strategy my fooimpl class throws an exception on purpose and its stacktrace gets vomited onto the mule stdout exceptiontransformer is not triggered and i get no email if i remove the defaultexceptionstrategy completely nothing at all changesi want it to send an email and print the exception with exceptiontransformer what am i doing wrongflow namefooservice inboundendpoint addresshttplocalhost63082foo exchangepatternrequestresponse cxfjaxwsservice serviceclasscomexamplemulefoofooimpl component classcomexamplemulefoofooimpl all fileoutboundendpoint pathhomehodormulestandalone310old outputpatternfoo functiondatestampxml stdiooutboundendpoint systemout exchangepatternoneway connectorrefstdioconnector transformerrefsobjecttoinputstream all defaultexceptionstrategy vmoutboundendpoint pathgeneralerrorhandler exchangepatternoneway defaultexceptionstrategyflowflow namegeneralerrorhandler vminboundendpoint pathgeneralerrorhandler exchangepatternoneway customtransformer classcomexamplemulefooexceptiontransformer all smtpoutboundendpoint hosterrorsmtphost porterrorsmtpport subjecterrorsmtpsubject toerrorsmtpto ccerrorsmtpcc bccerrorsmtpbcc fromerrorsmtpsender allflowfurther on i tried to use customexceptionstrategy classcomarcusysnkeservicemuledynastyexceptiontest instead of defaultexceptionstrategy then exceptiontest gets instantiated during service startup but override handleexception never gets calledmy forced exception i get to stdout is like thiswarn 20150223 105917159 fooconnectorhttp0receiver2 orgapachecxfphasephaseinterceptorchain interceptor for fooimplservicegetcase has thrown exception unwinding noworgapachecxfinterceptorfault component that caused exception is orgmulecomponentdefaultjavacomponent component for simpleflowconstructfooservice message payload is of type object at orgmulemodulecxfmuleinvokerinvokemuleinvokerjava85 at orgmulemodulecxfmulejaxwsinvokerinvokemulejaxwsinvokerjava47 at orgapachecxfserviceinvokerabstractinvokerinvokeabstractinvokerjava75 at orgapachecxfinterceptorserviceinvokerinterceptor1runserviceinvokerinterceptorjava58 at javautilconcurrentexecutorsrunnableadaptercallexecutorsjava471 at javautilconcurrentfuturetaskrunfuturetaskjava262 at orgapachecxfworkqueuesynchronousexecutorexecutesynchronousexecutorjava37 at orgapachecxfinterceptorserviceinvokerinterceptorhandlemessageserviceinvokerinterceptorjava106 at orgapachecxfphasephaseinterceptorchaindointerceptphaseinterceptorchainjava247 at orgapachecxftransportchaininitiationobserveronmessagechaininitiationobserverjava113 at orgmulemodulecxfcxfinboundmessageprocessorsendtodestinationcxfinboundmessageprocessorjava292 at orgmulemodulecxfcxfinboundmessageprocessorprocesscxfinboundmessageprocessorjava131 at orgmulemodulecxfconfigflowconfiguringmessageprocessorprocessflowconfiguringmessageprocessorjava50 at orgmuleprocessorabstractinterceptingmessageprocessorprocessnextabstractinterceptingmessageprocessorjava75 at orgmuleprocessorasyncinterceptingmessageprocessorprocessasyncinterceptingmessageprocessorjava103 at orgmuleprocessorchaindefaultmessageprocessorchaindoprocessdefaultmessageprocessorchainjava62 at orgmuleprocessorchainabstractmessageprocessorchainprocessabstractmessageprocessorchainjava90 at orgmuleprocessorabstractinterceptingmessageprocessorprocessnextabstractinterceptingmessageprocessorjava75 at orgmuleinterceptorabstractenvelopeinterceptorprocessabstractenvelopeinterceptorjava55 at orgmuleprocessorabstractinterceptingmessageprocessorprocessnextabstractinterceptingmessageprocessorjava75 at orgmuleinterceptorabstractenvelopeinterceptorprocessabstractenvelopeinterceptorjava55 at orgmuleprocessorabstractinterceptingmessageprocessorprocessnextabstractinterceptingmessageprocessorjava75 at orgmuleprocessorabstractfilteringmessageprocessorprocessabstractfilteringmessageprocessorjava41 at orgmuleprocessorchaindefaultmessageprocessorchaindoprocessdefaultmessageprocessorchainjava62 at orgmuleprocessorchainabstractmessageprocessorchainprocessabstractmessageprocessorchainjava90 at orgmuleprocessorchaininterceptingchainlifecyclewrapperdoprocessinterceptingchainlifecyclewrapperjava60 at orgmuleprocessorchainabstractmessageprocessorchainprocessabstractmessageprocessorchainjava90 at orgmuleconstructabstractflowconstruct11processabstractflowconstructjava107 at orgmuleprocessorchaindefaultmessageprocessorchaindoprocessdefaultmessageprocessorchainjava62 at orgmuleprocessorchainabstractmessageprocessorchainprocessabstractmessageprocessorchainjava90 at orgmuleprocessorabstractinterceptingmessageprocessorprocessnextabstractinterceptingmessageprocessorjava75 at orgmuleprocessorexceptionhandlingmessageprocessorprocessexceptionhandlingmessageprocessorjava25 at orgmuleprocessorchaindefaultmessageprocessorchaindoprocessdefaultmessageprocessorchainjava62 at orgmuleprocessorchainabstractmessageprocessorchainprocessabstractmessageprocessorchainjava90 at orgmuleprocessorchaininterceptingchainlifecyclewrapperdoprocessinterceptingchainlifecyclewrapperjava60 at orgmuleprocessorchainabstractmessageprocessorchainprocessabstractmessageprocessorchainjava90 at orgmuleprocessorchaindefaultmessageprocessorchaindoprocessdefaultmessageprocessorchainjava62 at orgmuleprocessorchainabstractmessageprocessorchainprocessabstractmessageprocessorchainjava90 at orgmuleprocessorchaininterceptingchainlifecyclewrapperdoprocessinterceptingchainlifecyclewrapperjava60 at orgmuleprocessorchainabstractmessageprocessorchainprocessabstractmessageprocessorchainjava90 at orgmuletransportabstractmessagereceiverroutemessageabstractmessagereceiverjava188 at orgmuletransportabstractmessagereceiverroutemessageabstractmessagereceiverjava161 at orgmuletransportabstractmessagereceiverroutemessageabstractmessagereceiverjava148 at orgmuletransporthttphttpmessagereceiverhttpworkerdorequesthttpmessagereceiverjava247 at orgmuletransporthttphttpmessagereceiverhttpworkerprocessrequesthttpmessagereceiverjava206 at orgmuletransporthttphttpmessagereceiverhttpworkerrunhttpmessagereceiverjava164 at orgmuleworkworkercontextrunworkercontextjava309 at eduemorymathcsbackportjavautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava1061 at eduemorymathcsbackportjavautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava575 at javalangthreadrunthreadjava745caused by orgmulecomponentcomponentexception component that caused exception is orgmulecomponentdefaultjavacomponent component for simpleflowconstructfooservice message payload is of type object at orgmulecomponentdefaultcomponentlifecycleadapterinvokedefaultcomponentlifecycleadapterjava359 at orgmulecomponentabstractjavacomponentinvokecomponentinstanceabstractjavacomponentjava89 at orgmulecomponentabstractjavacomponentdoinvokeabstractjavacomponentjava80 at orgmulecomponentabstractcomponentinvokeinternalabstractcomponentjava114 at orgmulecomponentabstractcomponentaccess0abstractcomponentjava52 at orgmulecomponentabstractcomponent1processabstractcomponentjava236 at orgmuleprocessorchaindefaultmessageprocessorchaindoprocessdefaultmessageprocessorchainjava62 at orgmuleprocessorchainabstractmessageprocessorchainprocessabstractmessageprocessorchainjava90 at orgmuleprocessorchaininterceptingchainlifecyclewrapperdoprocessinterceptingchainlifecyclewrapperjava60 at orgmuleprocessorchainabstractmessageprocessorchainprocessabstractmessageprocessorchainjava90 at orgmulecomponentabstractcomponentprocessabstractcomponentjava147 at orgmuleprocessorchaindefaultmessageprocessorchaindoprocessdefaultmessageprocessorchainjava62 at orgmuleprocessorchainabstractmessageprocessorchainprocessabstractmessageprocessorchainjava90 at orgmulemodulecxfcxfinboundmessageprocessorprocessnextcxfinboundmessageprocessorjava334 at orgmulemodulecxfmuleinvokerinvokemuleinvokerjava80 49 morecaused by javaioioexception test ioexception at comfoofooimplgetcasefooimpljava240 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava57 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43 at javalangreflectmethodinvokemethodjava606 at orgmulemodelresolversabstractentrypointresolverinvokemethodabstractentrypointresolverjava151 at orgmulemodelresolversmethodheaderpropertyentrypointresolverinvokemethodheaderpropertyentrypointresolverjava112 at orgmulemodelresolversdefaultentrypointresolversetinvokedefaultentrypointresolversetjava39 at orgmulecomponentdefaultcomponentlifecycleadapterinvokedefaultcomponentlifecycleadapterjava350 63 more,['java'] +852404,upload sources to nexus repository with gradle i successfully uploaded my jars to a nexus repository using the maven plugin for gradle but it did not upload the sources this is my configurationuploadarchives repositories mavendeployer repositoryurl http authenticationusername user password mypassword i searched and found that i can add the sources by adding a new task task sourcesjartype jar dependsonclasses classifier sources from sourcesetsmainallsourceartifacts archives sourcesjarthis works fine but i think there must be a better solution by configuring the maven plugin something like uploadsource true like this uploadarchives repositories mavendeployer repositoryurl http authenticationusername user password mypassword uploadsources true,['java'] +852612,resharper closing parenthesis indentation on function with multiple arguments i have some lines of code in c that resharper indents like thisconsolewritelinehellothismysuperfunction argument1 argument2 argument3 consolewritelineworlddue to my personal coding style i would like the above to appear with the closing parenthesis or brace without any indentation like soconsolewritelinehellothismysuperfunction argument1 argument2 argument3consolewritelineworldi tried playing with the various options on resharper but could not find any is there a way i can make this work,['c#'] +852721,stdsetoperator is not using c but stdless cannot delete my own question so overwrite it instead,['c++'] +852743,thisplaying an html file with a js inside an ipython notebook i have a piece of code in an ipython notebook that programmatically generates a folder named sound containing the following files indexhtml canvasjs graphjs and stylecssif i open indexhtml in my browser i can see exactly the output i want a graph with a nice js animation representing vectors in and out of a process i am modelinghowever i would like to thisplay the html file from inside the ipython notebook itselffor that i type the following codefrom ipythonthisplay import iframeiframeusersuseirddesktopsoundindexhtml width700 height350which returns the followingi am not an expert with css or js but i think that ipython can thisplay js inside an iframe so whats wrong herethanks,"['javascript', 'html', 'css']" +852773,creating a 3x3 grid with auto layout constraints xcode has said there are no layout issues but as you can see there is i have tried everything apple docs youtube google etc it seems i am doing it right however maybe the order i am doing things in or something else is causing these issues after trying everything i finally let xcode add missing constraints and it is the best result so far i have 9 buttons onto of 9 uiimages so i have to do the same thing i do to the buttons as i do with the uiimages i have temporarily placed the uiimages on top of the buttons so i can see what i am doing more easily i have got 2 screenshots please advise beginningthis is after using xcodes add missing constraints option sorta what i want but no cigar,['ios'] +853214,why is int implicitly cast to float rather than double when invoking constructor i wrote this test codepublic class constructortestapplication private static string result public static void mainstring args constructortest test1 new constructortest0 systemoutprintlnresult private static class constructortest public constructortestdouble param result double constructor called public constructortestfloat param result float constructor called the result wasfloat constructor calledwhy was the float constructor called rather than the double constructor is this part of the dynamic method lookup,['java'] +853236,how to embed javascript code directly in scalajs when i use scalajs to write scala code to generate javascript i found it difficult sometimes to wrap the 3rdparty javascript code into scala objectsis there anyway to embed some javascript code directly eg as strings,['javascript'] +853263,dangers of syssetdefaultencodingutf8 there is a trend of thiscouraging setting syssetdefaultencodingutf8 in python 2 can anybody list real examples of problems with that arguments like it is harmful or it hides bugs do not sound very convincingupdate please note that this question is only about utf8 it is not about changing default encoding in general caseplease give some examples with code if you can,['python'] +853353,does reallocp 0 really involves freep in glibc i found that some people and references like books state that if p null and p origins from previous allocation eg by malloc then reallocp 0 is equivalent to freep on gnulinux to support this thesis man realloc states exactly in that manner emphasis mine going forwardthe realloc function changes the size of the memory block pointed to by ptr to size bytes the contents will be unchanged in the range from the start of the region up to the minimum of the old and new sizes if the new size is larger than the old size the added memory will not be initialized if ptr is null then the call is equivalent to mallocsize for all values of size if size is equal to zero and ptr is not null then the call is equivalent to freeptr unless ptr is null it must have been returned by an earlier call to malloc calloc or realloc if the area pointed to was moved a freeptr is doneas you may find in this question the c standard does not define precisely what should happen and actual behavior is implementationdefined more specificallythe c11 a7223p1 memory management functions saysif the size of the space requested is zero the behavior is implementationdefined either a null pointer is returned or the behavior is as if the size were some nonzero value except that the returned pointer shall not be used to access an objectand c11 a72235 the realloc function contains3 if memory for the new object cannot be allocated the old object is not deallocated and its value is unchanged4 the realloc function returns a pointer to the new object which may have the same value as a pointer to the old object or a null pointer if the new object could not be allocatedi wrote some basic code to find out actual behavior with help of mcheck memory checker that is supplied with glibcinclude mcheckhinclude stdiohinclude stdlibhint mainvoid int a 5 int p q mtrace p mallocsizeofint q a printfpn void p printfpn void q q reallocp 0 printfpn void p printfpn void q return 0and results are gcc g checkc export malloc tracereport aout 0xfd34600x7fbc955cc0xfd3460nilgrzegorzcentos workspace mtrace aout report memory not freed address size caller0x0fd3460 0x4 at homegrzegorzworkspacecheckc12as you may see q was set to null it seems that free was not really called in fact it cannot be unless my interpretation is incorrect since realloc has returned null pointer the new object could not have been allocated which implies thatthe old object is not deallocated and its value is unchangedis this correct,['c'] +853356,configuring nlogs layout to show all the eventcontext entries im currently in the process of developing a webapi2 application and in the stages of conducting my logs using nlogin my application i log in a keyvalue manner using the logeventinfoproperties dictionary in this waythiscontrollerlogparamsaddcontrollernamecontrollernamethiscontrollerlogparamsaddactionname actionnamethiscontrollerlogparamsaddtotaltime actionwatchelapsedmillisecondslogeventinfo logevent new logeventinfo message stringisnulloremptythiscontrollerlogmessage finished successfulythiscontrollerlogmessage level loglevelinfo timestamp datetimenow logeventpropertiesmergethiscontrollerlogparamsloggerloglogeventeverything works fine however i cant seem to find the way to render the layout so it prints all the keyvalue entries that are in the logeventinfoproperties dictionarylets assume my target is a file then i have to explicitly mention the key nameis there a way to render it to show all the content of the dictionary this is how i do it today where i can log only the entries i know oftarget namef1 xsitypefile filenamebasedirlogslogtxt maxarchivefiles60 archivenumberingdate archivedateformatymmdd archiveeveryday layoutlongdate callsiteclassnametruemethodnametrue eventcontextitemcontrollername eventcontextitemactionname eventcontextitemtotaltime message,['c#'] +853461,would it be a good idea if compiler resolved nulls when optional is expected as argument that would be so obviously useful that i am starting to think i am missing a rationale to avoid it since i am sure oracle would have made it that way it would be the most valuable feature on optional for mepublic class testoptionals public static void mainstring args testnull public static void testoptionalobject optional systemoutprintlnoptionalorelsenew defaultobject this throws a nullpointerexceptionwithout that feature i see too verbose using optional for the argumenti prefer a simple object optional signature and checking it by if null optional that creating the object optional for comparing later it is not valuable if that does not help you checking the null,['java'] +853520,how to create global locksemaphore with multiprocessingpool in python i want limit resource access in children processes for example limit http downloads thisk io etc how can i achieve it expanding this basic codeplease share some basic code examplespool multiprocessingpoolmultiprocessingcpu countwhile job queueis jobs for processing for job in job queuepull jobs for processing poolapply asyncdo job callback callbackpoolclosepooljoin,['python'] +853625,cannot install pip packages inside a docker container with ubuntu i am following the fig guide to using docker with a python application but when docker gets up to the commandrun pip install r requirementstxti get the following error messagestep 3 run pip install r requirementstxt running in fe0b84217ad1collecting blinker13 from r requirementstxt line 1 retrying retrytotal4 connectnone readnone redirectnone after connection broken by protocolerrorconnection aborted gaierror2 name or service not known simpleblinkerthis repeats several times and then i get another messagecould not find any downloads that satisfy the requirement blinker13 from r requirementstxt line 1 no thistributions at all found for blinker13 from r requirementstxt line 1so for some reason pip cannot access any packages from inside a docker container is there anything i need to do to allow it internet accesshowever pip works fine to install things outside of the docker container and worked fine even with that exact package blinker13 so that is not the problem also this problem is not specific to that package i get the same issue with any pip install command for any packagedoes anyone have any idea whats going on here,['python'] +853635,using orgslf4jmdc with netty channels what i want to do is in essence what how to use mdc with thread pools is asking but with nettyi want mdc information associated per channel what options are there for netty if i need to reset mdc manually what methods can i hook up to do this from one place,['java'] +853653,spring transaction not working as expected in junit in non debug mode all myservice methods are transactional the junit test below gets count of items saves a new item and gets count of items to make sure that counts has been incremented by 1public class mytest extends servicetest 1 int countbefore myservicegetcount return n 2 myserviceadditem item is really added to db 3 int countafter myservicegetcount return and sometimes n1transactionalpropagationpropagationrequires new isolationisolationread committedgetcountatransactionalpropagationpropagationrequires new isolationisolationserializableaddaignorecontextconfigurationlocations filesrcmainresourcesxcontextxml filesrcmainresourcesxdataxml filesrcmainresourcesxservicesxml transactionconfigurationtransactionmanager txmanager defaultrollback falsetestexecutionlisteners dependencyinjectiontestexecutionlistenerclass dirtiescontexttestexecutionlistenerclass transactionaltestexecutionlistenerclass testlistenerclasspublic class servicetest extends abstractutignorerunwithspringjunit4classrunnerclasstestexecutionlisteners testlistenerclasspublic class abstractutwhen debugging 3 returns n1 which is what i want but when running the test without debug i get neven sometimes when running the test i get n1 and next time i get and and when comparing the std output between the two execution it looks exactly the same i have enabled log4jloggerorgspringframeworktransactiontrace and i can see initializing transaction synchronizationgetting transaction for myservicegetcountcompleting transaction for myservicegetcountclearing transaction synchronizationinitializing transaction synchronizationgetting transaction for myserviceaddcompleting transaction for myserviceaddclearing transaction synchronizationinitializing transaction synchronizationgetting transaction for myservicegetcountcompleting transaction for myservicegetcountclearing transaction synchronizationso transactions are being executed one after the other but how is possible that 3 do not see the saved itemtransaction managment is setup in my test class as per how can i find what is going wrongthanks,['java'] +853698,when debugging with intellij idea what do the different variable colors mean so when debugging with intellij idea the variable window often looks like this the white box is added by me afterwardsnow i have some variables colored red others colored bluewhats the meaning of the color what is difference between these colorsi have also noticed red variables with blue fields and the other way aroundi didnt find anything on the web about this,['java'] +853906,why is not pycharms autocomplete working for libraries i install pycharms autocomplete is not working for installed libraries i have the following codefrom botoemrconnection import emrconnectionconn emrconnectionaws keysaccess key id aws keyssecret keyi want the editor to tell me what methods i have available to me when i press ctrlspacethe boto library is installed in my environment but it does not seem to be detected by pycharm how can i set this up correctly,['python'] +853999,how to drop rows from pandas data frame that contains a particular string in a particular column i have a very large data frame in python and i want to drop all rows that have a particular string inside a particular columnfor example i want to drop all rows which have the string xyz as a substring in the column c of the data framecan this be implemented in an efficient way using drop method,['python'] +854183,create deep link for mobile app i want to create a promotional link for my app which i can thistribute via email when the user clicks on the link from the email a webpage does thisdetermines which os ios or androidif app installed on device opens the appelse takes user to appstore or playstore or a custom urli tried using the applinks applinksorg but i am unable to get it to work how does the browser understand the alx tags does it only work for facebooktwitter html head meta propertyaliosurl contentapplinksdocs meta propertyaliosapp store id content12345 meta propertyaliosapp name contentapp links meta propertyalandroidurl contentapplinksdocs meta propertyalandroidapp name contentapp links meta propertyalandroidpackage contentorgapplinks meta propertyalweburl content headi also tried some javascript from another post but if the app is not installed the browser shows an errorscript windowonload function windowlocation settimeoutwindowlocation 10 scriptplease help with thisthanks,"['android', 'ios']" +854301,cannot call getbootclasspath before settargetinfo is called i am new in android studio when i sync android application i got errorcusersmansukhdesktoplayoutmaterialdesignlibrarymastermaterialdesignbuildgradleerror97 0 cannot call getbootclasspath before settargetinfo is calledplease anyone tell me what is error mean and what are the solution for this error i try to find out problem on internet but i unable to got particular solutionhere is my gradlebuild fileapply plugin comandroidlibraryapply plugin comgithubdcendentsandroidmavenapply plugin comjfrogbintrayandroid compilesdkversion 19 buildtoolsversion 20 sourcesets main manifestsrcfile androidmanifestxml javasrcdirs src resourcessrcdirs src aidlsrcdirs src renderscriptsrcdirs src ressrcdirs res assetssrcdirs assets androidtestsetroottests defaultconfig minsdkversion 8 targetsdkversion 21 versioncode 6 versionname 14 extsiteurl extissueurl extgiturl bintray user haspropertybintray user bintray user navasmdc key haspropertybintray key bintray password configurations archives pkg repo maven name materialdesignlibrary desc this is a library with components of android l to you use in android 22 websiteurl siteurl issuetrackerurl issueurl vcsurl giturl licenses apache20 labels publicdownloadnumbers true dependencies compile comnineoldandroidslibrary24 compile comandroidsupportsupportv421install repositoriesmaveninstaller pom project packaging aar name materialdesignlibrary url siteurl licenses license name the apache software license version 20 url developers developer id navasmdc name ivan navas email scm connection giturl developerconnection giturl url siteurl task sourcesjartype jar from androidsourcesetsmainjavasrcdirs classifier sourcestask javadoctype javadoc source androidsourcesetsmainjavasrcdirs classpath projectfilesandroidgetbootclasspathjoinfilepathseparatortask javadocjartype jar dependson javadoc classifier javadoc from javadocdestinationdirartifacts archives javadocjar archives sourcesjartask findconventions println projectgetconvention,['android'] +854328,method added in api 17 works in lower api levels too the method settextcharsequence text boolean filter of autocompletetextview which was introduced in api 17 seems to be working in lower android versions too i was expecting it to crash in 23 device with nosuchmethoderror but it is just working fine that is not really a problem but i am just curious to know how it is working here is my code autocompletetextview androidididautocompletetextview1 androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentlefttrue androidlayout belowidtextview1 androidtextcolorandroidcolorblack androidems10 androidtextautocompletetextview requestfocus autocompletetextviewimport androidosbundleimport androidsupportv7appactionbaractivityimport androidwidgetautocompletetextviewpublic class mainactivity extends actionbaractivity override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main autocompletetextview autocompletetextview autocompletetextview findviewbyidridautocompletetextview1 method introduced in api 17 autocompletetextviewsettextexample text false,['android'] +854337,how can i capitalize all the strings inside an array directly i am learning swift i have been trying this in playground i have no idea why the string is not being capitalized here or is there any other way to capitalize the string inside the array directlyheres my codevar dognames sean fido sarah parker walt abby yangfor index in 0dognamescount var dogname dognamesindexcapitalizedstring dognamesremoveatindexindex dognamesappenddognamewhen i try to thisplay again the variable dognames the strings inside are not being capitalized,['ios'] +854487,pylint says unnecessary parens after r keyword after my first codereview q i got tip in answeryour code appears to be for python 2x to be a bit more ready for a possible future migration to python 3x i recommend to start writing your print statements as printthus in my following code i am using python 26 and 27 on my boxes i always us for printprinthellotoday i first time test my code with pylint and it saysc 43 0 unnecessary parens after print keyword superfluousparenswhich explained hereso does printstr is really incorrect or i can thisregard this pylint messages,['python'] +854493,jmeter javalangoutofmemoryerror gc overhead limit exceeded i am using jmeter to inject workload to an application deployed on an aws ec2 instance the test has to be very huge it lasts for 10 hours and the workload profile has a bimodal shapes with a pitch of about 2600 requests in 5 minutes actually i have one m3xlarge instance in which the application is deployed and 8 m3xlarge instances each one running a jmeter instance with a python script the workload to inject is splitted among the 8 client instances so in example if the original workload as to inject 800 requests each jmeter instance will inject 100 requests the full test as i said lasts for 10 hours and is divided into timesteps of 5 min each every 5 min a little workload variation is applied actually i get from each jmeter instance the javalangoutofmemoryerror gc overhead limit exceeded error immediatly after the test is started and no request arrive to the application i read a lot online and on stackoverflow and i concluded the possible mistake could bejmv heap size too low i solved setting the following in the jmeterbat files in each jmeter instanceset heapxms4g xmx4gset newxxnewsize4g xxmaxnewsize4g some mistakes in the code that results in a continue unuseful usage of the garbage collector so i remove from my test all the jmeter listeners in particular i was using tablevisualizer viewresultsfullvisualizer statvisualizer and graphvisualizeranyway the problem persists i really have no idea about how to solve it i know 10 hours of test with 2600 pitch request could be a very heavy test but i think there should be a way to perform this i am using ec2 m3xlarge instance so i could even raise the heap size to 8g if it could be useful or splitting the workload among even more clients since i am using spot instances so i will not pay so much more but since i have already doubled the number of client instance from 4 to 8 in order to solve the problem and is does not work i am a little bit confused and i want to know r suggestions before continue to get more and more resources thank you a lot in advance,['java'] +854724,aspnet web api returns 200 ok when it should return 404 i have the following action methods on a controller in an aspnet web api projectrouteapiv2projectprojectidstuff httpgetpublic ihttpactionresult getint projectidrouteapiv2projectprojectidstuffidguid httpgetpublic ihttpactionresult getint projectid fromuri guid idrouteapiv2projectprojectidstuff httppostpublic ihttpactionresult postint projectid required stuff stuffrouteapiv2projectprojectidstuffidguid httpputpublic ihttpactionresult putint projectid fromuri guid blastid stuff stuffrouteapiv2projectprojectidstuffidguid httpdeletepublic ihttpactionresult deleteint projectid fromuri guid iddue to a javascript error i made a delete request to apiv2project1234stuffundefinedie instead of a guid for the id i got the string undefined as far as i can tell this should not match any of my routes but instead of a 404 not found or even 405 method not allowed i got a 200 ok as responsei set a breakpoint in each of these action methods and repeated the request using fiddler but none of the breakpoints was hit i also tried installing the webapiroutedebugger package from nuget but were using a custom controller factory which hooks things up through our di container so i could not get it to work at all i even tried throwing the following exception from one of my globally registered filtersthrow new exceptionactioncontextcontrollercontextcontrollerdescriptorcontrollername actioncontextactiondescriptoractionnamebut the delete request still goes through to 200 ok no requests to valid urls seem to do thathow else can i troubleshoot this what could be the root cause,['asp.net'] +854729,how to set hex color code in xib in ios i am not finding an option for hex color code in xib color picker in xcodebut i have seen in stack over flow answerin this image is having hex color code option in color pickerxcode version 611how can i get that hex color code in color picker in xibplease suggest methanksupdate is there any plugin for xcode to select color in hexa color code i am using xcode 611or is there any setting in xcode to change the colr in hexa codeplease help me guys,['ios'] +854810,bind you are binding a component method to the component react does this for you automatically i get this warning from reactjsnetbind you are binding a component method to the component react does this for you automatically in a highperformance way so you can safely remove this call see likeconcomponent looks like thisvar likecon reactcreateclass handleclick function var data new formdata var like thisstatelike var likecounter thisstatelikecount dataappendcatgorytype thisstatecategorykey dataappendobjectid thisstateobjectid dataappendlike like iflike likecounter else likecounter thissetstate like like likecount likecounter userid thisstateuserid categorykey thisstatecategorykey objectid thisstateobjectid var xhr new xmlhttprequest xhropenpost httplocalhost2215homesetlike true xhronload function xhrsenddata getinitialstate function return like thispropsinitiallike likecount thispropsinitiallikecount userid thispropsuserid categorykey thispropscategorykey objectid thispropsobjectid render return thisrenderlikebutton renderlikebutton return content div classnamelikecon div classnamethisstateliketrue likebutconact likebutcon div classnamelikeb titlethisstateliketrue unlike like onclickthishandleclickbindthis nbsp div thisstatelikecount 0 div classnamelikecountthisstatelikecountdiv null div div i uses a bind when calling the method handleclick if i remove this i will get another exception so what am i supose to do,['javascript'] +854835,updating owin from 21 to 301 breaks external auth i am having a difficult time debugging an owin package upgrade in my open source project the short description is that using external logins breaks in the new v3 version when i upgrade from v21 and in the debugging process i cannot figure out whats different keep in mind that none of my code is changed i am only updating the owin components the packages in microsoftowin and the other child namespacesit starts with this form postform actionforumsauthorizationexternalloginreturnurlhttp3a2f2flocalhost3a19732fforums methodpostinput name requestverificationtoken typehidden valueverificationtoken h2external loginsh2 p button typesubmit idgoogle nameprovider valuegoogle classbtn btnprimarygooglebutton pformit posts to this methodhttppostvalidateantiforgerytokenpublic actionresult externalloginstring provider string returnurl return new challengeresultprovider urlactionexternallogincallback authorization new loginprovider provider returnurl returnurl area popforums the callback lands herepublic async taskactionresult externallogincallbackstring loginprovider string returnurl var authentication owincontextauthentication var authresult await externalauthenticationgetauthenticationresultauthentication if authresult null return redirecttoactionlogin account new error resourcesexpiredlogin that second line calls thispublic async taskexternalauthenticationresult getauthenticationresultiauthenticationmanager authenticationmanager var authresult await authenticationmanagerauthenticateasyncexternalcookiename if authresult null return nullauthenticationmanager can be any of the implementations of iauthenticationmanager in the google facebook etc packages the problem is that they all fail and return a null object so the app cannot login the userto reproduceclone the v13 branch run the app locally per instructions in the admin choose the external logins page and add credentials for one of the providers and check the boxlogout then use the button to login with the new providerwatch it fail and see that the authresult the above externalauthentication getauthenticationresult method is nulli keep wondering if something changed in the owin configuration that i do not understand for the record that is here using systemusing microsoftowinsecurityusing microsoftowinsecuritycookiesusing owinusing popforumsexternalloginusing popforumsservicesusing popforumswebnamespace popforumsconfiguration public class popforumsowinstartup public void configurationiappbuilder app var setupservice popforumsactivationservicelocatorgetinstanceisetupservice if setupserviceisdatabasesetup return var settings popforumsactivationservicelocatorgetinstanceisettingsmanagercurrent appsetdefaultsigninasauthenticationtypeexternalauthenticationexternalcookiename appusecookieauthenticationnew cookieauthenticationoptions authenticationtype externalauthenticationexternalcookiename authenticationmode authenticationmodepassive cookiename cookieauthenticationdefaultscookieprefix externalauthenticationexternalcookiename expiretimespan timespanfromminutes60 if settingsusetwitterlogin appusetwitterauthentication consumerkey settingstwitterconsumerkey consumersecret settingstwitterconsumersecret if settingsusemicrosoftlogin appusemicrosoftaccountauthentication clientid settingsmicrosoftclientid clientsecret settingsmicrosoftclientsecret if settingsusefacebooklogin appusefacebookauthentication appid settingsfacebookappid appsecret settingsfacebookappsecret if settingsusegooglelogin appusegoogleauthenticationsettingsgoogleclientid settingsgoogleclientsecret any ideas,['c#'] +854908,assembly code redundancy in optimized c code i am trying to learn about vectorization by studying simple c code compiled in gcc with o3 optimization more specifically how well compilers vectorize it is a personal journey towards being able to verify gcc o3 performance with more complex computation i understand that conventional wisdom is that compilers are better than people but i never take such wisdom for granted in my first simple test though i am finding some of the choices gcc makes quite strange and quite honestly grossly negligent in terms of optimization i am willing to assume there is something the compiler is purposeful and knows something about the cpu intel i52557m in this case that i do not but i need some confirmation from knowledgeable people my simple test code segment isint ifloat a100for i0i100i ai float iithe resulting assembly code segment that corresponds to the forloop is as followsl6 loop starts here movdqa xmm0 xmm1 copy packed integers in xmm1 to xmm0l3 movdqa xmm1 xmm0 wait what why this is redundant cvtdq2ps xmm0 xmm0 convert integers to float add rax 16 increment memory pointer for next iteration mulps xmm0 xmm0 pack square all integers in xmm0 pad xmm1 xmm2 pack increment all integers by 4 movaps xmmword ptr rax16 xmm0 store result cmp rax rdx test loop termination jne l6 i understand all the steps and computationally all of it makes sense what i do not understand though is gcc choosing to incorporate in the iterative loop a step to load xmm1 with xmm0 right after xmm0 was loaded with xmm1 ie l6 movdqa xmm0 xmm1 loop starts here l3 movdqa xmm1 xmm0 gr this alone makes me question the sanity of the optimizer obviously the extra movdqa does not thisturb data but at facevalue it would seems grossly negligent on the part of gccearlier in the assembly code not shown xmm0 and xmm2 are initialized to some value meaningful for vectorization so obviously at the onset of the loop the code has to skip the first movdqa but why does not gcc simply rearrange as shown belowl3 movdqa xmm1 xmm0 initialize xmm1 prior to loopl6 movdqa xmm0 xmm1 loop starts here or even better simply initialize xmm1 instead of xmm0 and dump the movdqa xmm1 xmm0 step altogetheri am prepared to believe that the cpu is smart enough to skip the redundant step or something like that but how can i trust gcc to fully optimize complex code if it can even get this simple code right or can someone provide a sound explanation that would give me faith that gcc o3 is good stuff,['c'] +854928,wildfly and auto reconnect to the database i have got a client a server and a database the client communicates with the server via a ejb remote interfaces as the server i use a wildfly 820 as the database i use a mysql the server communicates with the mysql via a jpahibernate when i turn off the mysql server the wildfly throws an exception of course but when i turn on the mysql again the wildfly still throws the same error i have to turn off the wildfly and turn it back that the wildfly reconnect to the databasehow to set auto reconnect in the wildflyi tried to set auto reconnect in a connection url jdbcmysqllocalhostdbautoreconnecttrueampuseunicodeyesampcharacterencodingutf8 and i tried to add to the standalonefullxml file which i use this line checkvalidconnectionsqlselect 1checkvalidconnectionsql but both solutions do not workstandalonefullxml datasource jtatrue jndinamejavajbossdatasourcesmysqlds poolnamemysqlds enabledtrue useccmtrue connectionurljdbcmysqllocalhostdbautoreconnecttrueampampuseunicodeyesampampcharacterencodingutf8connectionurl driverclasscommysqljdbcdriverdriverclass drivermysqldriverdriver security usernameuserusername passwordpassword security validation checkvalidconnectionsqlselect 1checkvalidconnectionsql validateonmatchfalsevalidateonmatch backgroundvalidationfalsebackgroundvalidation validation timeout settxquerytimeoutfalsesettxquerytimeout blockingtimeoutmillis0blockingtimeoutmillis idletimeoutminutes0idletimeoutminutes querytimeout0querytimeout usetrylock0usetrylock allocationretry0allocationretry allocationretrywaitmillis0allocationretrywaitmillis timeout statement sharepreparedstatementsfalsesharepreparedstatements statementdatasourcedrivers driver namemysqldriver modulecommysql xadatasourceclasscommysqljdbcdriverxadatasourceclass driverdrivers,"['java', 'mysql']" +854981,understanding recyclerview sethasfixedsize i am having some trouble understanding sethasfixedsize i know that it is used for optimization when the size of recyclerview does not change from the docswhat does that mean though in most common cases a listview almost always has a fixed size in what cases would it not be a fixed size does it mean that the actual real estate that it occupies on screen grows with the content,['android'] +855019,some android devices extremely slow when rendering canvas elements im developing an app for android devices and found that samsung galaxy s4 specifically has extremely poor performance when appweb page uses canvas odd thing is that its not always the case i have tested 2 sample appsand the first one works fine and outperforms my nokia which is dual core and is expected however the other demo is almost completely unresponsive and framerate is close to 1 where as all other devices render it finesince the first app runs well and the other one doesnt it beggs the question why first one has no event listeners where as the other one has touch listeners could touchmove be the cause instead of canvasor is that demo using some canvas features that the other one isnt and thus has poor performancei have read lots of topics about this issue and none seem to have answer most are many months oldso i thought ill make a new topicis there any way to solve the canvas issue on samsung s4 and potentially other android devices running 42x if any stackoverflow users here has s4 can you test both demos and confirm my observations,"['javascript', 'android']" +855433,c expressions fatalexecutionengineerror today i was debugging some code of mine that builds a few expressiontrees compiles them to callable delegates and calls them afterwards if required while doing this i encountered a fatalexecutionengineerror stepping through the codeat first i was a little bit shocked since i had no idea what could have been possibly wrong with my expressions they looked all fine then i found out that this only happens in the following situationmethod a is a static method that is called and generates the expressiontree which can possibly contain an expressioncall to method a again so after i compile the lambda for the expressiontree the generated delegate let us call it method b may possible cause recursion if i call it from within this method method a generatedmethod b method awhich is totally possible in my scenario as described above i was debugging this piece of code so i set a breakpoint in method athe first time method a is called by the regular code the breakpoint hits as usual when method b is called the breakpoint hits a second time still everything is okbut as soon as i leave the second call with the debugger by stepping over the last line the fatalexecutionengineerror occursif i run the code without debugging or do not step into the recursive call to method a or if i do not step over the last line of the method the problem does not occur and my expression code is executed as expectedi cannot determine if this is an error in the vsdebugger or the net framework or if i do something horribly horribly wrong that only comes up when debugging the relevant lineshere is a very bare example code you can run out of the box i am using visual studio 2013 prof update 4 and net 451 just set a breakpoint in dosomething and try to step through to the end if you can can anyone confirm a bug or is my expression illformedusing systemusing systemcollectionsgenericusing systemlinqusing systemlinqexpressionsusing systemreflectionusing systemtextusing systemthreadingtasksnamespace expressionproblem public class mainclass public static void dosomethingbool stop var method typeofmainclassgetmethod dosomething bindingflagspublic bindingflagsstatic typedefaultbinder new type typeofbool null var expparam expressionparametertypeofbool stop var expcall expressioncallnull method expparam var lambda expressionlambdaexpcall expparam var delegate lambdacompile ifstop delegatedynamicinvoketrue public static void mainstring args dosomethingfalse,['c#'] +855522,java8 streams sequential and parallel execution produce different results running the following stream example in java8 systemoutprintlnstream ofa b c d e f reduce s1 s2 s1 s2 yieldsabcdefwhich is of course no surprisedue to it should not matter whether the stream is executed sequentially or parallel except for operations identified as explicitly nondeterministic such as findany whether a stream executes sequentially or in parallel should not change the result of the computation afaik reduce is deterministic and s1 s2 s1 s2 is associative so that adding parallel should yield the same result systemoutprintlnstream ofa b c d e f parallel reduce s1 s2 s1 s2 however the result on my machine isabcdefwhats wrong herebtw using the preferred collectcollectorsjoining instead of reduce yields the same result abcdef for sequential and parallel executionjvm detailsjavaspecificationversion 18javaversion 180 31javavmversion 2531b07javaruntimeversion 180 31b13,['java'] +855541,how does ruby return two values whenever i swap values in an array i make sure i stored one of the values in a reference variable but i found that ruby can return two values as well as automatically swap two values for examplearray 1 3 5 6 7array0 array1 array1 array0 3 1 i was wondering how ruby does this,['ruby'] +855565,difference between abstract class and interface in objectivec one of the most frequently asked questions on ios developer interview is difference between abstract classed and interfacei do not know an answer and i do not get it neither interface is a section of class when you declared methods it could be open for other classes public h file or hidden in implementationabstract class is a class that is only used to create hidden subclasses and it should not have own init methods if i understand correctso what exactly is answer for that question and what does that question meani did spend time searching for an answers but answers was not related to objc so i cannot figure out by myself i hope someone could provide clear answer and that question would be helpful for those guys who want to pass an interview,['objective-c'] +855594,why does the preprocessor thistinguish between number and character tokens according to the language specification the lexical elements are defined like thistoken keyword identifier constant stringliteral operator punctuatorpreprocessingtoken headername identifier ppnumber characterconstant stringliteral operator punctuator each nonwhitespace character that cannot be one of the abovewhy is there a thistinction between a number and a character on the preprocessing token level whereas on the token level there are only constants i do not see the benefit in this thistinction,"['c++', 'c']" +855605,migrations treferences does not allow index name to be specified i have the following in a migrationcreate table model with a long name do t treferences other model with an equally long name index trueendthat produces an index with too long of a name for postgresis there a way to manually specify the index name without adding the integer column and the index separatelysomething like the followingcreate table model with a long name do t treferences other model with an equally long name index true index name model and otherend,"['ruby-on-rails', 'ruby']" +855680,sharing uiimage to uiactivityviewcontroller twitterfacebook very slow to show dialog i have an image i took from the camera and saved to the tmp folderwhen i add this image to the activityitems of an uiactivityviewcontroller and then press to share with either twitter or facebook i have to wait up to 20 seconds for the share dialog to appearnote that i am referring to the actual post dialog that appears for twitterfacebook not the native share popup that spawns itwhen i share the same image from the photos app it appears instantly at first i was thinking the photos app was resizing the image as a smaller image appears more quickly but than i thiscovered that when i share the same image directly to twitter or facebook with slcomposeviewcontroller it appears almost instantlyassuming it is something i am doing incorrectly in code here is what results in the glacially slow dialog appearancensarray items foo uiimage imagewithcontentsoffilevalid path to test imageuiactivityviewcontroller vc uiactivityviewcontroller alloc initwithactivityitemsitems applicationactivitiesnilself presentviewcontrollervc animatedyes completionnilheres what works almost instantlyslcomposeviewcontroller controller slcomposeviewcontroller composeviewcontrollerforservicetypeslservicetypetwittercontroller setinitialtextfoocontroller addimageuiimage imagewithcontentsoffilevalid path to test imageself presentviewcontrollercontroller animatedyes completionnilfor what it is worth i have also tried excluding the other share types i read that in the past airdrop caused issues as well as wrapping the block to ensure i was executing on the main threadi assume i am doing something wrongif i am not and these two other methods are in fact resizing the image is there some documentation i am missing that provides guidance as to how much resizing to do edit additional testing seems to show this problem is unique to ios8 as i did not experience it on an older ios7 devicethanks,"['ios', 'objective-c']" +855775,keeping generic types when implementing in class i have done a lot of searching through generic type questions and just have not found anything that has helped me figure out what i am doing wrong here i have an interface as followspublic interface sortanalysise extends comparable super e public long analyzesortarrayliste listnow the next step is making a class that implements this interface this particular class is going to use an insertion sort and i need to keep the arraylist type e generic so i tried all sorts of things and ended up with the followingpublic class insertionsorte extends comparable super e implements sortanalysis overridepublic long analyzesortarraylist list todo autogenerated method stub return 0my problem is that when i try to do this for the parameterarrayliste listthe compiler gripes at me about implementing a supertype methodi would really appreciate any direction of helpthanksi cannot mark this as answered yet but it is i think my problem had been that when i hadsortanalysisei did not have the generic typing listed after the class name,['java'] +855824,swift adjusting fontsize to fit the with of the layout programatically i have been looking for something to dynamically adjust my fontsize to fit the width of my layout box but all the answers i can find is either to use thislabeladjustsfontsizetofitwidth truewhich does work but only if i do not have settranslatesautoresizingmaskintoconstraints set to falseplease note that i do not use storyboards so to have full control over my other constraints i need this line labelsettranslatesautoresizingmaskintoconstraintsfalseso how can i adjust the fontsize to fit the width without using storyboard and when i cannot use adjustsfontsizetofitwidthafter i figure out how to adjust the fontsize to fit the width i also need to adjust the height of the layoutbox to fit the fontsize there seems to be documentation on that though but if you happen to know the answer of this as well it would be greatly appreciatedthanks in advance,['ios'] +855974,columntransformer in hibernate i have an entity which i use the columntransformer for bind and extract valuesentityclass bpoint id private integer id columntransformerread astextshape write toshape private shape shapeand the daoclass bpointdao autowired private entitymanager em override public pagebpoint findallpageable pageable query q emcreatequeryfrom bpoint listbpoint r qgetresultlist int total emcreatequeryselect count from bpointgetfirstresult return new pageimplr pageable total override public integer savebpoint hbds empersisthbds return hbdsgetid it works however once i have to do some query which need the use the sql functions i meet some problems take this valid native sql for exampleselect from bpoint h where insidehshape 100 1first i tried to use the hql like thisquery q emcreatenativequeryselect astextshape from bpoint h where insidehshape 1however i found that the generated sql contains things like where insideastexthshape100 it seems that the columntransformer read value is used in the sql function inside which is not expectedso i tried to use the native sql query like thisquery q emcreatenativequeryselect from bpoint h where insidehshape 1not the sql can be executed but the result cannot be mapped correctlythen i have to add the select fileds manualy like thisquery q emcreatenativequeryselect idastextshape from bpoint h where insidehshape 1but how about if my entity have a lot of fileds say it is more than 20 and how about if some columns name changedis there an alternative method to meet my requirement,['java'] +856011,crashlyticsupload a cordova project the crashlytics say we need to download the fabric plugin on android studio and then registerupload the app by running it i have few questions about the same topichow to upload a cordova ionic based project to crashlytics how to use this cordovacrashlytics plugin any help is very helpful,['android'] +856080,css marquee for variable message lengths i am looking for marquee tag alternatives and found how to do this through css however the messages i am using are of variable lengths so is there an alternative to putting in the 45s attribute to maybe 100 so that no matter how long or short the message is the message will show all of the message and loop again once the message has been thisplayed marquee margin 0 auto whitespace nowrap overflow hidden position absolute color f backgroundcolor 0 fontfamily arial rounded mt boldmarquee span thisplay inlineblock paddingleft 100 show the marquee just outside the paragraph animation marquee 45s linear infinitekeyframes marquee from textindent 0 to textindent 150 p idpassengernews scrollbar classmicrosoft marquee styleheight 95 width 90left 5top 2fontsize 7 spannewsdataspanp,"['html', 'css']" +856222,why is not biginteger a primitive if you use biginteger or bigdecimal and want to perform arithmetic on them you have to use the methods add or subtract for example this may sound fine until you realize that this i d p ywould be written like this for a biginteger i iadaddpaddyas you can see it is a little easier to read the first line this could be solved if java allowed operator overloading but it does not so this begs the question why is not biginteger a primitive type so it can take advantage of the same operators as other primitive types,['java'] +856263,how does java scope declarations in switch case statements the following java code executes without error in java 17public static void mainstring args int x 5 switchx case 4 int y 3423432 break case 5 y 33 how does java figure out that y is an int since the declaration never gets run does the declaration of variables within a case statement get scoped to the switch statement level when braces are not used in a case statement,['java'] +856264,laravel 5 auth logout not working when i use the builtin authentication and try to log the user out at authlogout it does not work as hoped it appears to keep the user logged in but when i clear my browser cache i can see that is has actually logged the user outi do not get any errors on the page nor errors in the log filei am guessing that sessionflush at the logout method would possibly solve this but i do not know where to put it can someone point me in the right direction,['php'] +856454,force barchart y axis labels to be integers i have created a barchart using mpandroidchart and i am entering the data dynamically this means that i need my y axis to also be determined dynamically all of my data is represented as integers however the y axis is sometimes thisplaying the legend as decimal values with 1 decimal pointi have attempted to use a valueformatter to round the values but the problem is that sometimes the y values are not at integer value locations ex 081624etc therefore if i just edit these to be integers they would not be in the right locationis there anyway that i can force the barchart to only thisplay values at integer locations its ok if it skips some in fact i want it to when the values get largeedit when i said that the integers are not in the right locations i meant that once i modify what each label thisplays they are not correct in my example i have 5 bars thisplaying the values 34232 the first image is the default the second is the image once i have edited the value formatter using mybarchartgetylabelssetformatternew valueformatter override public string getformattedvaluefloat v return int v as we can see from these images my integer values are not where they should be and there are two 2s in this example i would except it to thisplay the values 01234 if i have a lot more data i am hoping it would be smart enough to only show what values i have room for so for examples if the data contains values of 050 it would show something like 01020304050 or possibly 0153045 etc,['android'] +856649,best practices to invalidate jwt while changing passwords and logout in nodejs i would like to know the best practices to invalidate jwt without hitting db while changing passwordlogout i have the idea below to handle above 2 cases by hitting the user database 1incase of password changes i check for passwordhashed stored in the user db2incase of logout i save lastlogout time in user db hence by comparing the token created time and logout time i can able to invalidate this casebut these 2 cases comes at the cost of hitting user db everytime when the user hits the api any best practise is appreciatedupdate i dont think we can able to invalidate jwt without hitting db so i came up with a solution i have posted my answer if you have any concern you are welcome,['javascript'] +856688,difference between mt rand and rand what is the difference between using mt randmin max and randmin max about the speed,['php'] +856705,how to use ecmascript6 modules within webpages i am pretty excited about using ecmascript 6 features now via babeljs in particular i would love to start making my javascript code more modular using the new modules featureheres what i have written so far ecmascript 6 code libjsexport const sqrt mathsqrtexport function square x return x xexport function diag x y return sqrtsquarex squarey ecmascript 6 code mainjsimport square diag from libconsolelogsquare11consolelogdiag4 3i understand that i can transpile this code from es6 to es5 via babel on the command linebabel libjs lib6to5jsbabel mainjs main6to5jsbut what do i need to do to use this code within my htmlfor example what would this indexhtml file look like indexhtml doctype htmlhtml head meta charsetutf8 titleecmascript 6title what goes here how do i include main6to5js and lib6to5js to make this work in the browser script srcscript head body bodyhtmlthank you,['javascript'] +856796,table cells height calculated differenly in ie11 the problem i face is ie 11 seem to have inconsistent td inner height across single tr while other browsers keep it the sameheres a pen illustrating my problem in my layout i have an absolutely positioned pseudoelement green border which i want to thisplay on a outside td i would like it to be always as high as the whole tr it is in the content of tds is dynamic i have no control over it is size like i do in the peni gave it height 100 assuming that every td in a row has the same heighttd position relativetdbefore content thisplay block position absolute top 0 left 5px width 3px height 100 backgroundcolor greenand yeah that height calculates to the same value across all of the cells in the same row in firefox and chromebut to different height for each cell in ie 11the problem seems to be that in height 100 ie refers to the inner height the one inside the padding of the containing td while other browsers take total height height padding border and even then the inner height of all tds along one tr is identical in firefox while it is not in ie is any of those approaches wrong is there a way to force ie to work like other browsers do,['css'] +856816,how to post a field value which is available in iframe in php how to post iframe value in phpexampleusernamephp form actiondataphp methodpost input typetext nameusername idusername iframe srcpasswordphpiframeinput typesubmitformpasswordphp input typetext namepassword idpasswprdi want to post password and username value to dataphp,['php'] +856883,autolayout add constraint to superview and not top layout guide i have a uiview in my uiviewcontroller in storyboard which i want to add a constraint on to space that view a thistance from the top edgenow when i do the usual by ctrl drag to the viewcontrollers main view i only get option to set it to top layout guidethis is a problem for me because at one point in the app im going to move the main view up around 2050px and what happens then is that view i have will not move because its not aligned to superviewhow can i manually do this in storyboard or do i have to add it programaticallyim using xcode 6,['ios'] +856962,angularjs best practice templates vs javascript per default angular fetches the html templates from the server when the user navigates to a route with that in mind imagine this scenariouser loads the angular app the main view has a subpage called orderwhile the user is studying the main view a new version of the app is rolled out in production the new version has a complete rewrite of the order page with new javscript and htmlthe user navigates to the order page the javascript is already loaded by the browser in step 1 so the user is on the old version until app is reloaded but the new template gets fetched from the server on navigation so now the javascript and template are our of syncis my assumption that the javascripthtml is out of sync correctif so are there any best practices related to this issuei guess one solution is the make angular fetch all the templates on app initialization but this could be a performance penalty if the app has hundreds of html views,['javascript'] +857019,how to hide actionbartoolbar while scrolling down in webview in google chrome and play store the app can hide the actionbar while scrolling and allows the user to browse conveniently please help me to do like thisi have used ontouchlistener for webview it does not worksmwebviewsetontouchlistenernew viewontouchlistener override public boolean ontouchview v motionevent event switch eventgetaction case motioneventaction down getsupportactionbarshow break case motioneventaction up getsupportactionbarhide break default break return false thanks in advance,['android'] +857086,in firefox click on absolute element inside focusable element does not focus focusable element unless it has a css position context an absolute element inside a focusable elementin firefox 36 if the focusable element does not have a css position relative fixed or absolute a click on the inside element will not set focus to the focusable elementany idea whether that is a known bugnot reproductible on ie11 and chromefor better understanding of the issue heres an examplecodepen this is just so that the squares are similarly thisplayed section position relative thisplay inlineblock marginright 75px div backgroundcolor red width 100px height 100px color white padding 5pxdivfocus backgroundcolor greendiv span position absolute thisplay inlineblock top 50px left 50px backgroundcolor blue width 100px height 100px padding 5pxcontext an absolute element inside a focusable elementbrin firefox 36 if the focusable element does not have a position relative a click on the inside element will not set the focus on the focusable elementbrred block turns green when focusedbrbredit none works in iebrbrsection div styleposition relative tabindex1 with position relative span click here span divsectionsection div tabindex1 with no position span click here span divsection,['css'] +857154,how does c handle nested generic types i am trying to understand how c views types in the face of nestingmore specifically i am trying to understand why some types are not considered assignment compatible or even castable when there kind of only exist one definition of the nested class does the compiler clr actually generate different types for these or what rules are at play exactlyexample codepublic class foot protected class private2 private1foot protected class private1t2 where t2 foot public sealed class nested public void testt2 foo foomethod2this nope var nes private2nestedthis nope public void method1 var nested new private2nested nestedtestthis private void method2private2nested nested something code so even though the nested instance is created as a private2nested it can not be casted to that type and well how do the different nested types relate to each other given that nested is in fact sealed they cannot be inheriting from each other right but on the other hand their implementation should be 100 identical am i wrongprimary question what exactly is the compiler doing when it compiles this nested class how many unique types excluding valuetyperelated are actually generated and if it is all the same type is the restriction artificial as in wouldnt an unsafe cast actually work what i am saying is that the il for all these types comes from the same code definition so at some level the compiler must know are instances of these types not bitforbit identical apart from their typenamessecondary question not what i am really asking here mostly for brevity context is there some simple change that would make the above work am i missing something obvious the type foot must never be directly referenced inside private1t2 only use of t2 is allowed foot is just my example stand in for nasty generic classes with 1020 generic types it is all just a workaround for not being able to alias a generic class with its typespublic class bargoodname othername readability nopemr dontthinkso suffering thispair if only this was real using bart bargoodname othername readability nopemr dontthinkso suffering thispair public void method1bart bar so good goodbye readability see you never public void method2bargoodname othername readability nopemr dontthinkso suffering thispair whatisthisvariable purpose to avoid types of fields and methodparameters that are several screens wide and utterly unreadable as a side note i really wished this could be used as a type inside classes and interfaces as in private2 private1this well ok that wouldnt work because it collides with extension syntax on methods but something similar perhaps this super base used like methodthis arg or private2 private1super kind of weird maybe,['c#'] +857198,how to embed custom html5 player on facebook post thanks for reading my questioni have googled enough to die to find how to embed custom html5 player on facebook post i have seen youtube soundcloud and recently sketchfab links when share on facebook it will be transformed into html5 player i knew how to embed custom flash player but it is really hard to embed custom html5 playeri have tried to use all og tag they youtube sketchfab used i bought ssl certificate to have https url but when share on facebook my link would not transform to html5 playermaybe only selected companies can use this featurethanks a lot,['javascript'] +857229,practical differences between do while 0 and void0 in macros it is common practice in c to usedefine foo do body while 0while this is fine it is also possible to dodefine foo body void0void0 has many of the same benefits you cannot accidentally merge logic and a is required at the end of the line so odd expressions like this do not go by unnoticed foo else the only difference i have noticed is it means you need to use braces in ifstatementsif a fooelse barmust be written asif a foo else barother then this quirk it seems to work well preventing the same kinds of problems dowhile method is typically used forare there any significant differences between the 2 methodssaid differently if you see a codebase using void0 are practical reasons to switch to using dowhile0 besides the one difference already noted,['c'] +857402,load csv file with spark i am new to spark and i am trying to read csv data from a file with sparkheres what i am doing sctextfilefilecsv maplambda line linesplit0 linesplit1 collecti would expect this call to give me a list of the two first columns of my file but i am getting this error file ipythoninput6073ea98550983 line 1 in lambdaindexerror list index out of rangealthough my csv file as more than one column,['python'] +857689,how to limit the height of the modal i am looking for a way to keep a modal dialog within screen bounds ie that its height is always less than the screen height and the width is adjusted accordingly i triedmodaldialog maxheight 100but this does not seem to have any effectan illustrationi prefer a pure css solution no js if it exists for clarity i am looking for maxheight not height ie is the modal is no taller than screen leave it as is,['css'] +857760,how to add google places autocomplete to xcode with swift tutorial i want to add google places autocomplete to xcode with swift so users can search on a city and press enter so should the app show that city on the map ia m using google maps so it has to be connected to that map and the search bar would i like to have in the navibar just above the mapdoes anyone know a good tutorial to do that,['ios'] +857861,set backgroundcolor of first word in textbox i have an text box input in my html i know how to set the background color of the whole thing with css backgroundcolor but is it possible to only set the backgroundcolor of the first word i want it so that if someone types in for example hello there the background color of the word hello will turn orange but if they type in how are you the word how will turn bluei have gotten it to style the whole textbox in this jsfiddle here with jquery and css but is it possible to make it only set the background color of the first word,"['javascript', 'jquery', 'html', 'css']" +857864,infinite horizontal line in bokeh is there a way to plot an infinite horizontal line with bokeh the endpoints of the line should never become visible no matter how far out the user is zooming this is what i have tried so far it just prints an empty canvasimport bokehplotting as bkimport numpy as npp bkfigureplinenpinfnpinf 00 legendyx 0bkshowpone way would be to set the endpoints extremely highlow and the figures x range and y range very small in relation to them import bokehplotting as bkimport numpy as npp bkfigurex range1010plinenpiinfonpint64max npiinfonpint64max 00 legendyx 0bkshowphowever i am hoping that somebody has a more elegant solutionedit removed outdated solution,['python'] +857936,how to wait to activity using appium on begin and during test itself i am starting an already installed app using appiumafter my driver is initialized how do i make it pollwait till certain activity is thisplayedi saw only this way to wait for activity when starting upcapsetcapabilityappwaitactivity activitytowaitfor is there any other way how do i wait to another specific activity when not initializing say after a button clickjust sleep x seconds,"['java', 'android']" +857963,log4net with application insights i am trying to configure my azure aspnet website to send log4net traces to azure application insights i can see in my azure console page views etc hence i know that is working fine i can also see log4net traces when configured with a file handler but when configuring log4net to use the application insights handler i do not see any log4net entries appear in the application insight dashboard no errors or warnings at build or run time just no results in the dashboard i have looked at the network traffic in fiddler and i can see the pageview data etc being sent to application insights but not the log4net trace traffic hence i suspect this is a configuration issue separately i have tried the telemetryclient in my main project and i see the tracetraffic sucesfully in the dashboard however this does not fit my use case as telemetryclient does not seem to support non aspnet dlls as yet ie my business and data logic which are in separate dlls anyone offer any insight or advicei have installed the nuget package for microsoftapplicationinsightslog4netappenderdll and i am using microsoftapplicationinsights0132build00132i have the following in my webconfig as per configuration configsections section namelog4net typelog4netconfiglog4netconfigurationsectionhandler log4net configsections log4net root level valueall appenderref refaiappender root appender nameaiappender typemicrosoftapplicationinsightslog4netappenderapplicationinsightsappender microsoftapplicationinsightslog4netappender layout typelog4netlayoutpatternlayout conversionpattern valuemessagenewline layout appender log4netconfiguration,"['c#', 'asp.net']" +858144,passing results to depending on job python rq how do i pass the result of a job to a job that depends on itwhat i currently do is passing id of the first job to the secondfirst queueenqueuefirstjobsecond queueenqueuesecondjob firstid depends onfirstand inside secondjob fetching the first job to get the resultfirst queuefetch jobprevious job idprint firstresultis this the recomended way is there any other pattern that i can use to directly pass first jobs result to second,['python'] +858193,where exactly can i download the latest version of scene builder for java i have searched around oracles sites and cannot find the actual executable to download i get sites that point to older versions or to the source of scene builder instead i am looking for the actual windowsmac executable installer for the latest version of scene builder,['java'] +858304,inapp purchases with multiple accounts i am facing a problem with in app purchasessubscriptionsif there are multiple accounts on the device i cannot get the purchases which were made with the second accountthis can sometimes be temporarily fixed by installing the app from the google play web interface but after a while the purchases would not appear in the query forcing the user to reinstalli am using the iabhelper classes from this sampledoing some google searches i found that this bug exists since a while but unfortunately i could not find out if the error is in the iabhelper classes or on googles side i would like to draw attention to google so they provide a proper fix for this either in the iabhelper classes or in the play services or to provide information how this should be handledi am using the code in an app with at the time of writing 90 active user installs and i have to trigger quite a lot of refunds due to thisif there is a fix for this which i missed please let me knoweditsometimes it is not possible at all to retrieve the purchases even if there is only one account on the phone,['android'] +858506,spring jpa multiple persistence units injecting entitymanager i need to use one database for queries nonmodifying and one for commands modifying i am using spring data jpa so i have two configuration classesconfigurationenablejparepositoriesvalue comcompanyread entitymanagerfactoryref readingentitymanagerfactory transactionmanagerref readingtransactionmanagerenabletransactionmanagementpublic class springdatajpareadingconfiguration beanname readingentitymanagerfactory public entitymanagerfactory readingentitymanagerfactory return persistencecreateentitymanagerfactorypersistencereading beanname readingexceptiontranslator public hibernateexceptiontranslator readinghibernateexceptiontranslator return new hibernateexceptiontranslator beanname readingtransactionmanager public jpatransactionmanager readingtransactionmanager return new jpatransactionmanager configurationenablejparepositoriesvalue comcompanywrite entitymanagerfactoryref writingentitymanagerfactory transactionmanagerref writingtransactionmanagerenabletransactionmanagementpublic class springdatajpawritingconfiguration beanname writingentitymanagerfactory public entitymanagerfactory writingentitymanagerfactory return persistencecreateentitymanagerfactorypersistencewriting beanname writingexceptiontranslator public hibernateexceptiontranslator writinghibernateexceptiontranslator return new hibernateexceptiontranslator beanname writingtransactionmanager public jpatransactionmanager writingtransactionmanager return new jpatransactionmanager in my repository i sometimes need to decide with entitymanager to use like sorepositorypublic class userreadingrepository persistencecontextunitname persistencereading private entitymanager em some useful queries herei am using persistence unit is name as defined in my persistencexmlpersistence xmlns xmlnsxsi xsischemalocation 2 0xsd version20 persistenceunit namepersistencereading transactiontyperesource local providerorghibernatejpahibernatepersistenceproviderprovider nonjtadatasourcereadingdsnonjtadatasource properties property namehibernatedialect valueorghibernatedialectmysqldialect property namehibernateshow sql valuetrue properties persistenceunit persistenceunit namepersistencewriting transactiontyperesource local providerorghibernatejpahibernatepersistenceproviderprovider nonjtadatasourcewritingdsnonjtadatasource properties property namehibernatedialect valueorghibernatedialectmysqldialect property namehibernateshow sql valuetrue properties persistenceunitpersistencespring throws orgspringframeworkbeansfactorynosuchbeandefinitionexception no bean named persistencereading is defined oddly it looks like spring tries to instantiate a bean with persistence unit name did i misconfigure somethingupdate when i remove unitname persistencereading from persistencecontext annotation i will get following error insteadorgspringframeworkbeansfactorynouniquebeandefinitionexception no qualifying bean of type javaxpersistenceentitymanagerfactory is defined expected single matching bean but found 2 readingentitymanagerfactorywritingentitymanagerfactoryupdate 2 rohit suggested in the comment to wire entitymanagerfactory instead so i tried to do the followingpersistenceunitunitname persistencereadingprivate entitymanagerfactory emfbut spring only reports orgspringframeworkbeansfactorynosuchbeandefinitionexception no bean named persistencereading is definedfinal fixthanks to vlads answer i was able to update the code to use the following just make sure you define your datasource bean as wellbeanname readingentitymanagerfactorypublic entitymanagerfactory readingentitymanagerfactory localcontainerentitymanagerfactorybean em new localcontainerentitymanagerfactorybean emsetpersistenceunitnamepersistencereading emsetdatasourcedatasource emsetpackagestoscancomcompany emsetjpavendoradapternew hibernatejpavendoradapter emafterpropertiesset return emgetobject,['java'] +858509,adbcommandrejectedexception getting properties when testing on emulator it is getting really frustrating to test any apps at all i start up the emulator and run the app the first time and it works and immediately starts throwing this in the adb logs devicemonitor failed to connect to client 2560 eofpropertyfetcher adbcommandrejectedexception getting properties for device emulator54 device offlinelogcat thisplays nothing i have tried everything to stop this killing and starting the adb server does not solve the problem i have to restart the avdany help will be appreciated thanks,['android'] +858534,recursively fetch file contents from subdirectories using sctextfile it seems that sparkcontext textfile expects only files to be present in the given directory location it does not either a recurse orb even support directories tries to read directories as filesany suggestion how to structure a recursion potentially simpler than creating the recursive file list descent logic manuallyhere is the use case files under datatablesmy tablei want to be able to read via an hdfs call all the files at all directory levels under that parent directoryupdatethe sctextfile invokes the hadoop fileinputformat via the subclass textinputformat inside the logic does exist to do the recursive directory reading ie first detecting if an entry were a directory and if so then descending for filestatus globstat matches 218 if globstatisdir 219 forfilestatus stat fsliststatusglobstatgetpath220 inputfilter 221 resultaddstat2 223 else 224 resultaddglobstat225 226 however when invoking sctextfile there are errors on directory entries not a file this behavior is confusing given the proper support appears to be in place for handling directories,['java'] +858570,get cobjectarray out of a jsonstring so this is my classpublic class user public user public string username get set public string password get set public string firstname get set public string lastname get set and this is how my jsonstring looks likeresultsfirstnamefirstname1lastnamelastname1passwordtestpasswordusernametestusercreatedat20150302t173625232zobjectida8bkxdg2y2updatedat20150302t203548755zfirstnamefirstname2lastnamelastname2passwordtestpwusernametestuser2createdat20150302t203526604zobjectid2xpikle3uwupdatedat20150302t203553712zi would like to get a user users out of itmy problem is the resultsparti have tried it this wayjavascriptserializer js new javascriptserializeruser user jsdeserializeuserjsonstringbut i think the resultspart is messing everything up somehowwhat would be the best way to solve this problem,['c#'] +858581,drawing dom elements svgs as foreign elements on a canvas does not work in internet explorer i have successfully used this technique to draw user input from dom elements such as input and selection fields on a canvas and make it available as an imagethis works fine in chrome safari and firefox but on internet explorer 11 i get the following errorxml5634 an attribute with the same name already exists on this element line 1 column 242 when i try on the full site i vedeveloped this error is supposedly shown when there are duplicate values on name and id fields but i checked every element on the dom and there is noneunexpected call to method or property access when i try to reproduce the whole procedure on this fiddle it seems from the debugger that the error happens when ctxdrawimage is calledessentially what i am trying to do in this fiddle is to draw the svg yellow circle image and an arbitrary svg provided by me on the canvas this seems to work in all major browsers except ie11 is there anyone else having faced the same problem and knows some workaround,['jquery'] +858681,dragging elements on a scaled div i have tried using jquerys built in draggable and i have tried using custom drag functions with no avail both have their respected issues and i will try to highlight both of thembasically i am trying to allow the dragging of an element that is on a scaled div container the following methods work okay on a scaled element that is less than around 2 but if you go any higher than that we see some issuesany help would be appreciated thank you for your timehtmldiv idcontainer div iddragmehidivdivmethod 1 jquery draggable functioni have tried the jquery draggable function as you can see in this jsfiddle examplethe problems i found in this example are the followingbiggest concern the droppable container does not change when it is scaled up so if the element is being dragged over part of the scaled container that is not a part of it is original size it will failwhen you click to drag a div it teleports a little bit away from the mouse and is not a seamless dragjsvar percent 25dragmedraggable zindex 30 appendto body helper function e ui var draggable element this width draggable elementcsswidth height draggable elementcssheight text draggable elementtext fontsize draggable elementcssfontsize textalign draggable elementcssfontsize return div id draggable elementid name draggable elementattrname classtext text divcss position absolute textalign textalign backgroundcolor red fontsize fontsize lineheight height width width height height transform scale percent moztransform scale percent webkittransform scale percent mstransform scale percent start function e ui thishide stop function e ui thisshow containerdroppable drop function event ui var formbg this x uioffsetleft y uioffsettop drag type uidraggableattrid var element top y formbgoffsettop uidraggableheight percent 1 2 percent element left x formbgoffsetleft uidraggablewidth percent 1 2 percent uidraggablecss top element top left element left method 2 custom drag functioni have tried using a custom drag function but it unusable after around a 2 scalejsfiddle on a scale2 looks like the draggable div is having a seizurejsfiddle on a scale25 the draggable div flys away when you try to drag itjsfunction fndrags function opt opt extend handle cursor move opt if opthandle var el this else var parent this var el thisfindopthandle return elcsscursor optcursoronmousedown function e if opthandle var drag thisaddclassdraggable else thisaddclassactivehandle var drag parentaddclassdraggable var drg h dragouterheight drg w dragouterwidth pos y dragoffsettop drg h epagey pos x dragoffsetleft drg w epagex follow function e dragoffset top epagey pos y drg h left epagex pos x drg w windowonmousemove followonmouseup function dragremoveclassdraggable windowoffmousemove follow epreventdefault thisable selection onmouseup function if opthandle thisremoveclassdraggable else thisremoveclassactivehandle parentremoveclassdraggable jquerydragmedrags function e,"['javascript', 'jquery']" +858742,error creating bean with name defaultservlethandlermapping i converted all my xml spring configuration to java code ones but i am not getting able to run all my test which they worked before because i have an ugly exceptionorgspringframeworkbeansfactorybeancreationexception error creating bean with name defaultservlethandlermapping defined in class path resource orgspringframeworkwebservletconfigannotationdelegatingwebmvcconfigurationclass bean instantiation via factory method failed nested exception is orgspringframeworkbeansbeaninstantiationexception failed to instantiate orgspringframeworkwebservlethandlermapping factory method defaultservlethandlermapping threw exception nested exception is javalangillegalargumentexception a servletcontext is required to configure default servlet handlingat orgspringframeworkbeansfactorysupportconstructorresolverinstantiateusingfactorymethodconstructorresolverjava602at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactoryinstantiateusingfactorymethodabstractautowirecapablebeanfactoryjava13at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorycreatebeaninstanceabstractautowirecapablebeanfactoryjava1008at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorydocreatebeanabstractautowirecapablebeanfactoryjava505at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorycreatebeanabstractautowirecapablebeanfactoryjava476at orgspringframeworkbeansfactorysupportabstractbeanfactory1getobjectabstractbeanfactoryjava302at orgspringframeworkbeansfactorysupportdefaultsingletonbeanregistrygetsingletondefaultsingletonbeanregistryjava229at orgspringframeworkbeansfactorysupportabstractbeanfactorydogetbeanabstractbeanfactoryjava298at orgspringframeworkbeansfactorysupportabstractbeanfactorygetbeanabstractbeanfactoryjava193at orgspringframeworkbeansfactorysupportdefaultlistablebeanfactorypreinstantiatesingletonsdefaultlistablebeanfactoryjava762at orgspringframeworkcontextsupportabstractapplicationcontextfinishbeanfactoryinitializationabstractapplicationcontextjava757at orgspringframeworkcontextsupportabstractapplicationcontextrefreshabstractapplicationcontextjava480at orgspringframeworktestcontextsupportabstractgenericcontextloaderloadcontextabstractgenericcontextloaderjava125at orgspringframeworktestcontextsupportabstractgenericcontextloaderloadcontextabstractgenericcontextloaderjava60at orgspringframeworktestcontextsupportabstractdelegatingsmartcontextloaderdelegateloadingabstractdelegatingsmartcontextloaderjava109at orgspringframeworktestcontextsupportabstractdelegatingsmartcontextloaderloadcontextabstractdelegatingsmartcontextloaderjava261at orgspringframeworktestcontextdefaultcacheawarecontextloaderdelegateloadcontextinternaldefaultcacheawarecontextloaderdelegatejava68at orgspringframeworktestcontextdefaultcacheawarecontextloaderdelegateloadcontextdefaultcacheawarecontextloaderdelegatejava86at orgspringframeworktestcontextdefaulttestcontextgetapplicationcontextdefaulttestcontextjava72at orgspringframeworktestcontextsupportdependencyinjectiontestexecutionlistenerinjectdependenciesdependencyinjectiontestexecutionlistenerjava117at orgspringframeworktestcontextsupportdependencyinjectiontestexecutionlistenerpreparetestinstancedependencyinjectiontestexecutionlistenerjava83at orgspringframeworktestcontexttestcontextmanagerpreparetestinstancetestcontextmanagerjava212at orgspringframeworktestcontextjunit4springjunit4classrunnercreatetestspringjunit4classrunnerjava200at orgspringframeworktestcontextjunit4springjunit4classrunner1runreflectivecallspringjunit4classrunnerjava252at orgjunitinternalrunnersmodelreflectivecallablerunreflectivecallablejava12at orgspringframeworktestcontextjunit4springjunit4classrunnermethodblockspringjunit4classrunnerjava254at orgspringframeworktestcontextjunit4springjunit4classrunnerrunchildspringjunit4classrunnerjava217at orgspringframeworktestcontextjunit4springjunit4classrunnerrunchildspringjunit4classrunnerjava83at orgjunitrunnersparentrunner3runparentrunnerjava290at orgjunitrunnersparentrunner1scheduleparentrunnerjava71at orgjunitrunnersparentrunnerrunchildrenparentrunnerjava288at orgjunitrunnersparentrunneraccess0parentrunnerjava58at orgjunitrunnersparentrunner2evaluateparentrunnerjava268at orgspringframeworktestcontextjunit4statementsrunbeforetestclasscallbacksevaluaterunbeforetestclasscallbacksjava61at orgspringframeworktestcontextjunit4statementsrunaftertestclasscallbacksevaluaterunaftertestclasscallbacksjava68at orgjunitrunnersparentrunnerrunparentrunnerjava363at orgspringframeworktestcontextjunit4springjunit4classrunnerrunspringjunit4classrunnerjava163at orgeclipsejdtinternaljunit4runnerjunit4testreferencerunjunit4testreferencejava50at orgeclipsejdtinternaljunitrunnertestexecutionruntestexecutionjava38at orgeclipsejdtinternaljunitrunnerremotetestrunnerruntestsremotetestrunnerjava467at orgeclipsejdtinternaljunitrunnerremotetestrunnerruntestsremotetestrunnerjava683at orgeclipsejdtinternaljunitrunnerremotetestrunnerrunremotetestrunnerjava390at orgeclipsejdtinternaljunitrunnerremotetestrunnermainremotetestrunnerjava197caused by orgspringframeworkbeansbeaninstantiationexception failed to instantiate orgspringframeworkwebservlethandlermapping factory method defaultservlethandlermapping threw exception nested exception is javalangillegalargumentexception a servletcontext is required to configure default servlet handlingat orgspringframeworkbeansfactorysupportsimpleinstantiationstrategyinstantiatesimpleinstantiationstrategyjava189at orgspringframeworkbeansfactorysupportconstructorresolverinstantiateusingfactorymethodconstructorresolverjava591 42 morecaused by javalangillegalargumentexception a servletcontext is required to configure default servlet handlingat orgspringframeworkutilassertnotnullassertjava112at orgspringframeworkwebservletconfigannotationdefaultservlethandlerconfigurerinitdefaultservlethandlerconfigurerjava53at orgspringframeworkwebservletconfigannotationwebmvcconfigurationsupportdefaultservlethandlermappingwebmvcconfigurationsupportjava423at orgspringframeworkwebservletconfigannotationdelegatingwebmvcconfigurationenhancerbyspringcglibc5df7504cglibdefaultservlethandlermapping21generatedat orgspringframeworkwebservletconfigannotationdelegatingwebmvcconfigurationenhancerbyspringcglibc5df7504fastclassbyspringcglib7686853einvokegeneratedat orgspringframeworkcglibproxymethodproxyinvokesupermethodproxyjava228at orgspringframeworkcontextannotationconfigurationclassenhancerbeanmethodinterceptorinterceptconfigurationclassenhancerjava312at orgspringframeworkwebservletconfigannotationdelegatingwebmvcconfigurationenhancerbyspringcglibc5df7504defaultservlethandlermappinggeneratedat sunreflectnativemethodaccessorimplinvoke0native methodat sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava57at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43at javalangreflectmethodinvokemethodjava606at orgspringframeworkbeansfactorysupportsimpleinstantiationstrategyinstantiatesimpleinstantiationstrategyjava162 43 more20150302 230413 error testcontextmanager215 caught exception while allowing testexecutionlistener orgspringframeworktestcontextsupportdependencyinjectiontestexecutionlistener725f5 to prepare test instance orgmunaycooptaskmanagerservicestaskservicetest822d9bjavalangillegalstateexception failed to load applicationcontextat orgspringframeworktestcontextdefaultcacheawarecontextloaderdelegateloadcontextdefaultcacheawarecontextloaderdelegatejava94at orgspringframeworktestcontextdefaulttestcontextgetapplicationcontextdefaulttestcontextjava72at orgspringframeworktestcontextsupportdependencyinjectiontestexecutionlistenerinjectdependenciesdependencyinjectiontestexecutionlistenerjava117at orgspringframeworktestcontextsupportdependencyinjectiontestexecutionlistenerpreparetestinstancedependencyinjectiontestexecutionlistenerjava83at orgspringframeworktestcontexttestcontextmanagerpreparetestinstancetestcontextmanagerjava212at orgspringframeworktestcontextjunit4springjunit4classrunnercreatetestspringjunit4classrunnerjava200at orgspringframeworktestcontextjunit4springjunit4classrunner1runreflectivecallspringjunit4classrunnerjava252at orgjunitinternalrunnersmodelreflectivecallablerunreflectivecallablejava12at orgspringframeworktestcontextjunit4springjunit4classrunnermethodblockspringjunit4classrunnerjava254at orgspringframeworktestcontextjunit4springjunit4classrunnerrunchildspringjunit4classrunnerjava217at orgspringframeworktestcontextjunit4springjunit4classrunnerrunchildspringjunit4classrunnerjava83at orgjunitrunnersparentrunner3runparentrunnerjava290at orgjunitrunnersparentrunner1scheduleparentrunnerjava71at orgjunitrunnersparentrunnerrunchildrenparentrunnerjava288at orgjunitrunnersparentrunneraccess0parentrunnerjava58at orgjunitrunnersparentrunner2evaluateparentrunnerjava268at orgspringframeworktestcontextjunit4statementsrunbeforetestclasscallbacksevaluaterunbeforetestclasscallbacksjava61at orgspringframeworktestcontextjunit4statementsrunaftertestclasscallbacksevaluaterunaftertestclasscallbacksjava68at orgjunitrunnersparentrunnerrunparentrunnerjava363at orgspringframeworktestcontextjunit4springjunit4classrunnerrunspringjunit4classrunnerjava163at orgeclipsejdtinternaljunit4runnerjunit4testreferencerunjunit4testreferencejava50at orgeclipsejdtinternaljunitrunnertestexecutionruntestexecutionjava38at orgeclipsejdtinternaljunitrunnerremotetestrunnerruntestsremotetestrunnerjava467at orgeclipsejdtinternaljunitrunnerremotetestrunnerruntestsremotetestrunnerjava683at orgeclipsejdtinternaljunitrunnerremotetestrunnerrunremotetestrunnerjava390at orgeclipsejdtinternaljunitrunnerremotetestrunnermainremotetestrunnerjava197caused by orgspringframeworkbeansfactorybeancreationexception error creating bean with name defaultservlethandlermapping defined in class path resource orgspringframeworkwebservletconfigannotationdelegatingwebmvcconfigurationclass bean instantiation via factory method failed nested exception is orgspringframeworkbeansbeaninstantiationexception failed to instantiate orgspringframeworkwebservlethandlermapping factory method defaultservlethandlermapping threw exception nested exception is javalangillegalargumentexception a servletcontext is required to configure default servlet handlingat orgspringframeworkbeansfactorysupportconstructorresolverinstantiateusingfactorymethodconstructorresolverjava602at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactoryinstantiateusingfactorymethodabstractautowirecapablebeanfactoryjava13at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorycreatebeaninstanceabstractautowirecapablebeanfactoryjava1008at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorydocreatebeanabstractautowirecapablebeanfactoryjava505at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorycreatebeanabstractautowirecapablebeanfactoryjava476at orgspringframeworkbeansfactorysupportabstractbeanfactory1getobjectabstractbeanfactoryjava302at orgspringframeworkbeansfactorysupportdefaultsingletonbeanregistrygetsingletondefaultsingletonbeanregistryjava229at orgspringframeworkbeansfactorysupportabstractbeanfactorydogetbeanabstractbeanfactoryjava298at orgspringframeworkbeansfactorysupportabstractbeanfactorygetbeanabstractbeanfactoryjava193at orgspringframeworkbeansfactorysupportdefaultlistablebeanfactorypreinstantiatesingletonsdefaultlistablebeanfactoryjava762at orgspringframeworkcontextsupportabstractapplicationcontextfinishbeanfactoryinitializationabstractapplicationcontextjava757at orgspringframeworkcontextsupportabstractapplicationcontextrefreshabstractapplicationcontextjava480at orgspringframeworktestcontextsupportabstractgenericcontextloaderloadcontextabstractgenericcontextloaderjava125at orgspringframeworktestcontextsupportabstractgenericcontextloaderloadcontextabstractgenericcontextloaderjava60at orgspringframeworktestcontextsupportabstractdelegatingsmartcontextloaderdelegateloadingabstractdelegatingsmartcontextloaderjava109at orgspringframeworktestcontextsupportabstractdelegatingsmartcontextloaderloadcontextabstractdelegatingsmartcontextloaderjava261at orgspringframeworktestcontextdefaultcacheawarecontextloaderdelegateloadcontextinternaldefaultcacheawarecontextloaderdelegatejava68at orgspringframeworktestcontextdefaultcacheawarecontextloaderdelegateloadcontextdefaultcacheawarecontextloaderdelegatejava86 25 morecaused by orgspringframeworkbeansbeaninstantiationexception failed to instantiate orgspringframeworkwebservlethandlermapping factory method defaultservlethandlermapping threw exception nested exception is javalangillegalargumentexception a servletcontext is required to configure default servlet handlingat orgspringframeworkbeansfactorysupportsimpleinstantiationstrategyinstantiatesimpleinstantiationstrategyjava189at orgspringframeworkbeansfactorysupportconstructorresolverinstantiateusingfactorymethodconstructorresolverjava591 42 morecaused by javalangillegalargumentexception a servletcontext is required to configure default servlet handlingat orgspringframeworkutilassertnotnullassertjava112at orgspringframeworkwebservletconfigannotationdefaultservlethandlerconfigurerinitdefaultservlethandlerconfigurerjava53at orgspringframeworkwebservletconfigannotationwebmvcconfigurationsupportdefaultservlethandlermappingwebmvcconfigurationsupportjava423at orgspringframeworkwebservletconfigannotationdelegatingwebmvcconfigurationenhancerbyspringcglibc5df7504cglibdefaultservlethandlermapping21generatedat orgspringframeworkwebservletconfigannotationdelegatingwebmvcconfigurationenhancerbyspringcglibc5df7504fastclassbyspringcglib7686853einvokegeneratedat orgspringframeworkcglibproxymethodproxyinvokesupermethodproxyjava228at orgspringframeworkcontextannotationconfigurationclassenhancerbeanmethodinterceptorinterceptconfigurationclassenhancerjava312at orgspringframeworkwebservletconfigannotationdelegatingwebmvcconfigurationenhancerbyspringcglibc5df7504defaultservlethandlermappinggeneratedat sunreflectnativemethodaccessorimplinvoke0native methodat sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava57at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43at javalangreflectmethodinvokemethodjava606at orgspringframeworkbeansfactorysupportsimpleinstantiationstrategyinstantiatesimpleinstantiationstrategyjava162 43 morethis is my test classrunwithspringjunit4classrunnerclasscontextconfigurationclassesapplicationcontexttestclasspublic class accountservicetest and my applicationcontexttestconfigurationenabletransactionmanagementpropertysource classpathdatabasetestproperties componentscanbasepackages orgexamplespringproject public class applicationcontexttest autowired private environment env beanname datasource public datasource datasource return new embeddeddatabasebuilder settypeembeddeddatabasetypehsql addscriptclasspathsqlschemasql addscriptclasspathsqltestdatasql build beanname sessionfactory public localsessionfactorybean sessionfactory localsessionfactorybean sessionfactory new localsessionfactorybean sessionfactorysetdatasourcedatasource sessionfactorysetpackagestoscannew string orgexamplespringprojectdomains sessionfactorysethibernatepropertieshibernateproperties return sessionfactory beanname transactionmanager public hibernatetransactionmanager transactionmanager hibernatetransactionmanager txmanager new hibernatetransactionmanager txmanagersetsessionfactorysessionfactorygetobject return txmanager suppresswarningsserial private properties hibernateproperties return new properties setpropertyhibernatecacheprovider class envgetpropertyhibernateprovider class setpropertyhibernateshow sql envgetpropertyhibernateshow sql setpropertyhibernatehbm2ddlauto envgetpropertyhibernatehbm2ddl i tried the put webappconfiguration on my test class but this did not work the project is a spring mvc project but now i am testing just the services layer so why should i need to put that annotation on my classeven with that annotation another error is comingso what is coming on here,['java'] +858834,google oauth error at least one client secrets installed or web should be set i am using googles oauth 20 to upload videos to youtube via our servermy client id is a service account i downloaded the json key and added it to my solutionhere is the relevant code private async task runstring filepath usercredential credential var keyurl systemwebhttpcontextcurrentservermappathcontentoauth keyjson using var stream new filestreamkeyurl filemodeopen fileaccessread credential await googlewebauthorizationbrokerauthorizeasync googleclientsecretsloadstreamsecrets this oauth 20 access scope allows an application to upload files to the authenticated users youtube channel but does not allow other types of access new youtubeservicescopeyoutubeupload user cancellationtokennone var youtubeservice new youtubeservicenew baseclientserviceinitializer httpclientinitializer credential applicationname assemblygetexecutingassemblygetnamename when i run it i get this error at least one client secrets installed or web should be sethowever in my json there is no client secret private key id 9d98c06b3e730070806dcf8227578efd0ba9989b private key begin private keynmiicdqibadanbgkqhk etc client email client id 5462394056528igo05a5m8cutggehk3rk3hspjfm3t04appsgoogleusercontentcom type service accountso i assume i overlooked somethingmaybe i cannot use the service account do not know,['c#'] +859010,ajax controller action in yii2 i am new to programming and i am trying to call a function when the user imputs data and clicks submit button i am using yii2 and i am not familiar with ajax i tried developing a function but my controller action is not calledhere is the example code i am tryingviewsindexphpscript function myfunction ajax url php echo yiiapprequestbaseurl supermarketssample type post data searchname searchnameval searchbysearchbyval success function data alertdata scriptphpuse yiihelpershtmluse yiiwidgetslinkpagerh1supermarketsh1ulselect idsearchby option value thisabledthisabled selectedselectedsearch byoption option valuenamenameoption option valuelocationlocationoptionselectinput typetext value namesearchname idsearchnamebutton onclickmyfunctionsearchbuttonh3 h3controllerpublic function actionsample echo ok my problem is that when i click on the search button nothing happens and when i try to debug it the debugger runs no code,"['javascript', 'php', 'jquery']" +859037,google play services error bug report incomprehensible i have released an alpha version of my app with google play serviceshowever i have encountered this error when i tested the app on a phone with google play services i had not got this error during compilation or running the app on a phone with an out of date google play service i googled this error and in stack overflow but it did not give me much answerif anyone have any idea please helpby the way i did not enable proguard so that is not a problemhere is the bug reportjavalangillegalstateexception a fatal developer error has occurredcheck the logs for further informationat comgoogleandroidgmsinternaljlhbunknown sourceat comgoogleandroidgmsinternaljlhgunknown sourceat comgoogleandroidgmsinternaljlbhyunknown sourceat comgoogleandroidgmsinternaljlahandlemessageunknown sourceat androidoshandlerthispatchmessagehandlerjava99at androidoslooperlooplooperjava153at androidappactivitythreadmainactivitythreadjava5338at javalangreflectmethodinvokenativenative methodat javalangreflectmethodinvokemethodjava511at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava833at comandroidinternaloszygoteinitmainzygoteinitjava600at dalviksystemnativestartmainnative methodby the way i use libgdx and i used google play services for leader boards a achievementsi have followed this tutorial but it did not help me muchthanks in advance,"['java', 'android']" +859064,java puzzler casting a double to int int anint 1double adouble 25anint anint adouble error need to cast double to intanint adouble this is ok whyanint adouble this is also an erroranint 1 adouble this is also an errorso my questions is why is it not a compile error to do anint adouble,['java'] +859313,aspnet mvc 5 not rendering jquery ui css bundle i am trying to include the jquery ui css theme bundle in my project i have all the required files in my contentthemes directory and set up my bundleconfigcs as followspublic class bundleconfig for more information on bundling visit public static void registerbundlesbundlecollection bundles bundlesaddnew scriptbundlebundlesjqueryinclude scriptsjqueryversionjs bundlesaddnew scriptbundlebundlesjqueryuiinclude scriptsjqueryuiversionjs bundlesaddnew scriptbundlebundlesjqueryvalinclude scriptsjqueryvalidate use the development version of modernizr to develop with and learn from then when youre ready for production use the build tool at to pick only the tests you need bundlesaddnew scriptbundlebundlesmodernizrinclude scriptsmodernizr bundlesaddnew scriptbundlebundlesbootstrapinclude scriptsbootstrapjs scriptsrespondjs bundlesaddnew stylebundlecontentcssinclude contentbootstrapcss contentsitecss bundlesaddnew stylebundlecontentthemesbasecssinclude contentthemesbasejqueryuicorecss contentthemesbasejqueryuiresizablecss contentthemesbasejqueryuiselectablecss contentthemesbasejqueryuiaccordioncss contentthemesbasejqueryuiautocompletecss contentthemesbasejqueryuibuttoncss contentthemesbasejqueryuidialogcss contentthemesbasejqueryuislidercss contentthemesbasejqueryuitabscss contentthemesbasejqueryuidatepickercss contentthemesbasejqueryuiprogressbarcss contentthemesbasejqueryuithemecss my layoutcshtml has the following headhead meta charsetutf8 meta nameviewport contentwidthdevicewidth initialscale10 titleviewbagtitletitle link hreffontsgoogleapiscomcssfamilyopensans300400 relstylesheet typetextcss stylesrendercontentthemesbasecss contentcss contentdatepicker3css scriptsrenderbundlesjquery scriptsrenderbundlesjqueryui scriptsrenderbundlesbootstrap scriptsrenderbundlesmodernizr scriptsrendercontentbootstrapdatepickerjs rendersectionhead required false link relicon hrefurlcontentcontentfaviconico headhowever this is the html that is emitted note the absent jquery css themehead meta charsetutf8 meta nameviewport contentwidthdevicewidth initialscale10 titletitle link hreffontsgoogleapiscomcssfamilyopensans300400 relstylesheet typetextcss link hrefpackagemanagercontentbootstrapcss relstylesheet link hrefpackagemanagercontentsitecss relstylesheet link hrefpackagemanagercontentdatepicker3css relstylesheet script srcpackagemanagerscriptsjquery1102jsscript script srcpackagemanagerscriptsjqueryui13jsscript script srcpackagemanagerscriptsbootstrapjsscript script srcpackagemanagerscriptsrespondjsscript script srcpackagemanagerscriptsmodernizr262jsscript script srcpackagemanagercontentbootstrapdatepickerjsscript link relicon hrefpackagemanagercontentfaviconico headheres my solution structurewhat am i missing,"['jquery', 'css']" +859416,two different pages with reportlab simpledoctemplate and django i am using django and generating reports following this example i need to generate a last page but without headers or footers and different contenti am trying to do thisdef print exampleself buffer selfbuffer doc simpledoctemplatebuffer rightmargin72 leftmargin72 topmargin72 bottommargin72 pagesizeselfpagesize elements elementsappendparagraphcontent for all pages my custom style docbuildelements onfirstpageself header footer onlaterpagesself header footer canvasmakernumberedcanvas doc2 simpledoctemplatebuffer rightmargin72 leftmargin72 topmargin72 bottommargin72 pagesizeselfpagesize elements2 elements2appendparagraphcontent for the last page only my custom style doc2buildelements2 canvasmakernumberedcanvas get the value of the bytesio buffer and write it to the response pdf buffergetvalue bufferclose return pdfthen only the last content appears and previous content thissapearshow can i generate the last page with different content,['python'] +859425,web api gzip not being applied i have added the webconfig entry to enable gzip compression based on this so answer enable iis7 gzipi then checked the chrome developer window while loading an aspx page and saw the header in the response cachecontrolprivatecontentencodinggzipcontentlength3669contenttypetexthtml charsetutf8datewed 04 mar 2015 004605 gmtservermicrosoftiis75varyacceptencodingxaspnetversion4030319xpoweredbyaspnetso that means it is working correct but when looking for that header when making a web api call it is not presentcachecontrolnocachecontentlength551contenttypeapplicationjson charsetutf8datewed 04 mar 2015 005305 gmtexpires1pragmanocacheservermicrosoftiis75xaspnetversion4030319xpoweredbyaspneti have tried all kinds of different configurations starting with the one recommended in the linked so answer above finally in an act of desperation i set it to this which i thought would make it try to compress all requests everything except commented out httpcompression directorysystemdriveinetpubtempiis temporary compressed files scheme namegzip dllwindirsystem32inetsrvgzipdll dynamictypes add mimetype enabledtrue add mimetypetext enabledtrue add mimetypemessage enabledtrue add mimetypeapplicationjavascript enabledtrue add mimetypeapplicationjson enabledtrue add mimetype enabledfalse dynamictypes statictypes add mimetype enabledtrue add mimetypetext enabledtrue add mimetypemessage enabledtrue add mimetypeapplicationjavascript enabledtrue add mimetypeapplicationjson enabledtrue add mimetype enabledfalse statictypes httpcompression urlcompression dostaticcompressiontrue dodynamiccompressiontruewhat can be preventing the gzip from being applied to my web api methodsupdatei have since tried both the nuget web api compression package and editing the applicationhostconfig in both iis express 80 visual studio and a locallyinstalled iis 75 all have yielded the same results requests for other mime types like text work but applicationjson refuses to be gzipped,['c#'] +859514,is it never truly safe to reinterpret cast input into stdunique ptr when using various apis that have variable size structures structures that must be allocated as byte and then cast into the struct it would be nice if the unique ptr holder could point to the structure since that is what well be usingexamplestdunique ptrvariable size struct v vresetreinterpret castvariable size structnew bytebytesrequiredthis allowed v to provide the view to the structure itself which is preferable because that we do not need a second variable and we do not care about the byte pointer except for deletionthe problem comes in with the possibility of thunking the pointer on the cast making it unsafe to free i see no reasonable reason why the compiler would change the pointer value on cast since there is no inheritance but i hear that the standard reserves the right to thunk any pointer on any cast so as far as standardcompliant coding goes this approach is out the window right or is there some reason it is safe is there a way to at least static assert this or some other way to make it safe or cleanly deal with this type of structure,['c++'] +859527,import matplotlibpyplot gives importerror dlopena library not loaded libpng1515dylib i am aware that this exact same question has been asked before i did follow the instructions given in the answer there and it did not solve my problem and i do not have enough reputation to just comment on the q or a in that thread anyway heres whats going oni try to doimport matplotlibpyplotand in return i gettraceback most recent call last file usersrussellrichieanacondalibpython27sitepackagesipythoncoreinteractiveshellpy line 3032 in run code execcode obj selfuser global ns selfuser ns file ipythoninput3eff513f636fd line 1 in module import matplotlibpyplot as plt file usersrussellrichieanacondalibpython27sitepackagesmatplotlibpyplotpy line 27 in module import matplotlibcolorbar file usersrussellrichieanacondalibpython27sitepackagesmatplotlibcolorbarpy line 34 in module import matplotlibcollections as collections file usersrussellrichieanacondalibpython27sitepackagesmatplotlibcollectionspy line 27 in module import matplotlibbackend bases as backend bases file usersrussellrichieanacondalibpython27sitepackagesmatplotlibbackend basespy line 56 in module import matplotlibtextpath as textpath file usersrussellrichieanacondalibpython27sitepackagesmatplotlibtextpathpy line 22 in module from matplotlibmathtext import mathtextparser file usersrussellrichieanacondalibpython27sitepackagesmatplotlibmathtextpy line 63 in module import matplotlib png as pngimporterror dlopenusersrussellrichieanacondalibpython27sitepackagesmatplotlib pngso 2 library not loaded libpng1515dylib referenced from usersrussellrichieanacondalibpython27sitepackagesmatplotlib pngso reason image not foundmy python version277 anaconda 201 x86 64 default jun 2 2014 124816 gcc 401 apple inc build 5493editcels suggestion worked i just tried conda remove matplotlib pip install matplotlib and then conda install matplotlib and presto man you have no idea how long this problem has vexed me bless you all,['python'] +859631,same flt eval method different results in gclang the following program adapted from here is giving inconsistent results when compiled with gcc 482 and clang 351 in particular the gcc result does not change even when flt eval method doesinclude stdiohinclude floathint r1double ten 100int mainint c char v printfflt eval method dn flt eval method r1 01 10 ten printf01 a 10ten an 01 10 ten printfr1dn r1tests gcc stdc99 tc aoutflt eval method 001 0x19ap4 10ten 0x19ap4r11 gcc stdc99 mpfmath387 tc aoutflt eval method 201 0x01p1022 10ten 0x0p0r11 clang stdc99 tc aoutflt eval method 001 0x19ap4 10ten 0x19ap4r11 clang stdc99 mfpmath387 mnosse tc aoutflt eval method 201 0x007f01p1022 10ten 0x0p0r10note that according to this blog post gcc 443 used to output 0 instead of 1 in the second testa possibly related question indicates that a bug has been corrected in gcc 46 which might explain why gccs result is differenti would like to confirm if any of these results would be incorrect or if some subtle evaluation steps eg a new preprocessor optimization would justify the difference between these compilers,['c'] +859643,char with an unusual memory word size knuths mix architecture the original mix architecture features 6bit bytes and memory is addressed as 31bit words 5 bytes and a sign bit as a thought exercise i am wondering how the c language can function in this environment givenchar has at least 8 bits annex e of c99 specc99 spec section 6323 pointers paragraph 8 says when a pointer to an object is converted to a pointer to a character type the result points to the lowest addressed byte of the object successive increments of the result up to the size of the object yield pointers to the remaining bytes of the object my interpretation of this requirement is that it underpins memcpydst obj src obj sizeofsrc objapproaches that i can think ofmake char 31 bits so indirection through char is simple memory access but this makes strings wasteful and means it is not posixcompliant as that apparently requires 8 bit charspack three 8 bit chars into one word with 7 ignored bits char might be composed of word address and char index within it however this seems to violate 6323 ie memcpy would necessarily skip the ignored bits which are probably meaningful for the real object typefully pack chars into words eg the fourth 8 bit char would have 7 bits in word 0 and one bit in word 1 however this seems to require that all objects are sized in 8 bit chars eg a uint31 t could not be declared to match the word length since this again has the memcpy problemso that seems to leave the first wasteful option of using 31bit chars with all objects sized as multiples of char am i correct in reading it this way,['c'] +859691,you cannot install this app because another user has already installed an incompatible version on this device trying to install my own app from play store it says you cannot install this app because another user has already installed an incompatible version on this devicenote i have uninstalled the debug version and also cleared my cache still cannot get it to install from play storemy phone is not rooted so as another similar answer here on stackoverflow suggests i cannot use a root file explorer to clear data,['android'] +859705,numpy array casting ruled not safe indexing one numpy array with another both are defined as dtypeuint32 using numpytake to index and get an unsafe casting error not come across this before any idea what is going onpython 278 anaconda 210 32bit default jul 2 2014 151335 msc v1500 32 bit intel on win32type copyright credits or license for more information import numpy numpy version 190 a numpyarray9 7 5 4 3 1 dtypenumpyuint32 b numpyarray1 3 dtypenumpyuint32 c atakebtraceback most recent call last file pyshell12 line 1 in module c atakebtypeerror cannot cast array data from dtypeuint32 to dtypeint32 according to the rule safe,['python'] +859755,what is the difference when concatenating a string as a variable with a character vs concatenating with an other string when i see something pseudo 1liner like thisstr1 a str2is it much worse or betterequal than the following pseudo 1linerstr1 a str2update better example by qpaystaxes to reduce confusion regarding my original example what i triedvarious stuff for the past 10 years programming java but i never managed to realy see whats under the hood eg i would assume the second is slightly fasterbetter because there is no stringobjects created for the slashsign andor the garbage collector of java has to handle less i once prepared for the java certificates and might would have been able to argue better back in that time but it seems even thus its my daily business the theory about java must be keept up to date as well i know without any better explanation than my assumptation that indexofc should be used rather than indexofc and i wondered if the same counts for stringconcatenation i also googled a bit but as my title might imply i am not quite good to describe what i am looking for without a example i am sorry for this and the possibility this handicap just produced a duplicate what i will trybased on the accepted answer here string concatenation concat vs operator i hope to be able to have a start to see whats under the hood and one day be able to argue answer such questions that profund,['java'] +859818,err insecure response handing tips in javascript we have a lot of ajax calls from our web application and the thing is all are https request our it team mandates yes we have opened up the headers to allow cross domain but the problem is we have our own custom certificate used internally for all of our apps so basically i get error when we call ajaxfailed to load resource neterr insecure responseif i open the url in browser and accept the certificates the ajax calls works fine so my question is is there a way to handle this via javascript or would adding trusted certificate would resolve this issue also even after we add trusted certificate would again i face any issue in ajaxnote we are testing all these in chrome browser,"['javascript', 'jquery']" +859836,classnotfoundexception did not find class androidospersistablebundle otto android 50 i have a strange issuei have an app which i deployed on an android 44 device and use otto libraryi deployed the app on an android 50 device it still worksi retried on the 44 and the app would not launchedapparently it tries to use persistablebundleclass which a api 21 classhere my log caused by javalangclassnotfoundexception did not find class androidospersistablebundle on path dexpathlistzip file dataappfrmyappapknativelibrarydirectoriesdataapplibfrmyapp vendorlib systemlib at dalviksystembasedexclassloaderfindclassbasedexclassloaderjava56 at javalangclassloaderloadclassclassloaderjava497 at javalangclassloaderloadclassclassloaderjava457a a a a a a a a a a a a at javalangclassgetdeclaredmethodsnative methoda a a a a a a a a a a a at javalangclassgetdeclaredmethodsclassjava656a a a a a a a a a a a a at comsquareupottoannotatedhandlerfinderloadannotatedmethodsannotatedhandlerfinderjava52a a a a a a a a a a a a at comsquareupottoannotatedhandlerfinderfindallproducersannotatedhandlerfinderjava126a a a a a a a a a a a a at comsquareupottohandlerfinder1findallproducershandlerfinderjava33a a a a a a a a a a a a at comsquareupottobusregisterbusjava191,['android'] +859873,how to render heatmapjs on an image i am using heatmapjs to overlay a heatmap using the googlemaps plugin i would like to be able to download the picture as an image along with the heatmap overlay i tried the method heatmapinstancegetdataurl only returns the overlay region and not along with the image on which it is overlayed,['javascript'] +859917,check pin without leaving the ios keychain i have a user pin stored in the ios keychain for every pin attempt i use secitemcopymatching to retrieve the reference pin and then do the comparisonthe problem is that for a short amount of time the retrieved reference pin enters the apps working memory if the phone is compromised the reference pin can potentially be read offis there a way to pass the pin attempt to the keychain and have the keychain do the comparison with the reference pin in its secure environment can the secure element do that kind of stuff,['ios'] +859968,what is the actual purpose of stdtype infoname today a colleague of mine came and asked me the question as mentioned in the titlehe is currently trying to reduce the binaries footprint of a codebase that is also used on small targets like cortex m3 and alike apparently they have decided to compile with rtti switched on gcc actually to support proper exception handlingwell his major complaint was why stdtype infoname is actually needed at all for support of rtti and asked if i know a way to just suppress generation of the string literals needed to support this or at least to shorten them stdtype infonameconst char name const returns an implementation defined nullterminated character string containing the name of the type no guarantees are given in particular the returned string can be identical for several types and change between invocations of the same programa however compiler specific implementation of eg the dynamic cast operator would not use this information but rather something like a hashtag for type determination similar for catch blocks with exception handlingi think the latter is clearly expressed by the current standard definitions for stdtype infohash codestdtype indexi had to agree that i also do not really see a point of using stdtype infoname other than for debugging logging purposes i was not a 100 sure that exception handling will work just without rtti with current versions of gcc i think they are using 491 so i hesitated to recommend simply switching off rttialso it is the case that dynamic casts are used in their code base but for these i just recommended not to use it in favor of static cast they do not really have something like plugins or need for runtime type detection other than assertionsquestionare there real life production code level use cases for stdtype infoname other than loggingsubquestions more concretedoes anyone have an idea how to overcome work around the generation of these useless string literals under assumption they will never be usedis rtti really still needed to support exception handling with gccthis part is well solved now by sehe is answer and i have accepted it the other subquestion still remains for the left over generated stdtype info instances for any exceptions used in the code were pretty sure that these literals are never used anywherebit of related strip unused runtime functions which bloat executable gcc,['c++'] +860122,laravel eloquent update just if changes have been made is there any wat to update a record in laravel using eloquent models just if a change has been made to that record i do not want the user requesting the database for no good reason over and over just hitting the button to save changes i have a javascript function that enable and thisable the save button according with whether something has changed in the page but i would like if possible to make sure to do that on the server side too i know i can accomplish that by myself meaning without appealing to an internal functionality of the framework just by cheking if the record has change but before doing it that way i would like to know if laravel eloquent model already take care of that for one so i do not reinvent the wheelthis is the way i use to update a recordproduct productfinddataidproducttitle datatitleproductdescription datadescriptionproductprice datapriceetc string values were previously sanitized for xss attacksproductsave,['php'] +860134,appengine urlfetch validate certificatefalsenone not being respected in the appengine developer appserver i am getting an error like thislcertificateerror invalid andor missing ssl certificate for url when i am making a fetch like this to an https server with a selfsigned certificate almost always localhost portforwarded over ssh to a vmresult urlfetchfetchurlurl methodmethod payloadpayload deadlinedeadline validate certificatenoneone would not expect ssl failures for invalid certificates where validate certificate is false though this is quite possibly a sideeffect of the 279 policy in python to always validate ssl certificatesnote that passing false instead of none for validate certificate does not work eitherthis problem happens on python 27910 via homebrewxcode on os x 101024 with appengine 1918 through 11926there are issues eg 12096 about this on google app engine but i am looking for a workaroundheres what i have tried to work around thisadd the certificate to the macs login keychain works in the browser not from pythonadd the certificate to appenginepythonlibcacertscacertstxt andor libcacertsurlfetch cacertstxt though this probably requires turning verification on for it to work since that appears to be the only case where they are used with eg echo usrlocalshareappenginepythonlibcacertsurlfetch cacertstxt openssl x509 subject in servercrt usrlocalshareappenginepythonlibcacertsurlfetch cacertstxtthisable ssl https checking with the pep0476 workaround iessl create default https context ssl create unverified contextat or after import ssl around line 1149 of googleappenginethist27python std libhttplibpythis is particularly problematic on mac since downgrading as of xcode 7os x el capital is no longer a practical optiona preferable workaround would not involve monkeypatching the appengine code proper every time the development appserver is updatededitnote that the mac builtin openssl certificates are stored in systemlibraryopenssl which is protected with siprootlessness which frankly is a pain to muck with and a worthwhile feature to keep if we cani have verified that the certificate validates by using openssl s client connect localhost7500 cafile serverpemit is been added to the keychain and to usrlocaletcopensslcerts with the hash format where the hash comes from openssl x509 subject hash in serverpem or the homebrew ssl namely usrlocalcellaropenssl102d 1binopenssl in which case usrlocalcellaropenssl102d 1binopenssl s client connect localhost7500 verifies the certificate but python still does noti have tried using the homebrew version of python and openssl but to no avail running the following in python seems to always failpvebinpython c import requests requestsgethttpslocalhost7500this also fails where ssl cert file is set to the servers certificate ie for added measure one might expect it to work since the openssl command essentially works like this and also fails where ssl cert path is set to usrlocaletcopensslcertsnote pve is a virtual env where helpssl shows a file of usrlocalcellarpython2710 2frameworkspythonframeworkversions27libpython27sslpyfurther verifying that homebrew pythons sslso links to homebrews openssl i ranxcrun otool l usrlocalcellarpython2710 2frameworkspythonframeworkversions27libpython27libdynload sslsowhich returnscellarpython2710 2frameworkspythonframeworkversions27libpython27libdynload sslsousrlocaloptopensslliblibssl100dylib compatibility version 100 current version 100usrlocaloptopensslliblibcrypto100dylib compatibility version 100 current version 100usrliblibsystembdylib compatibility version 100 current version 122511if one runs brew info openssl it remarks under caveatsa ca file has been bootstrapped using certificates from the system keychain to add additional certificates place pem files in usrlocaletcopensslcertsbut clearly for some reason python is not using homebrews openssl algorithm for finding certificatesso i remain at a loss as to why python standard library is not validating certificates that are in the openssl directory specified in the documents as well as the keychain in both pem and p12 formats with always trust for secure sockets layer ssl,['python'] +860163,why do i constantly see resetting dropped connection when uploading data to my database i am uploading hundreds of millions of items to my database via a rest api from a cloud server on heroku to a database in aws ec2 i am using python and i am constantly seeing the following info log message in the logsrequestspackagesurllib3connectionpool info resetting dropped connection hostnamethis resetting of the dropped connection seems to take many seconds sometimes 30 sec before my code continues to execute againfirstly what exactly is happening here and whysecondly is there a way to stop the connection from dropping so that i am able to upload data fasterthanks for your help andrew,['python'] +860310,conversion from nstimeinterval to hourminutessecondsmilliseconds in swift my code is herefunc stringfromtimeintervalintervalnstimeinterval nsstring var ti nsintegerinterval var ms ti 10 var seconds ti 60 var minutes ti 60 60 var hours ti 3600 return nsstringformat 02d02d02dhoursminutessecondsmsin output the milliseconds give wrong resultplease give an idea how to find milliseconds correctly,['ios'] +860314,c with extern c in namespace prefix resolution and optimization level dependency i have a file testcxx withnamespace net extern c include arpaineth int main htons1024when compiling with o1 or more everythings finewhen compiling with o0error ahtonsa was not declared in this scopesuggested alternative anethtonsathen i change htons to nethtonswhen compiling with o0 everythings finewhen compiling with o1 or moreerror expected unqualifiedid before aa tokenreproduced that on gcc492 and clang370can someone explain why does it happen,"['c++', 'c']" +860413,proper way to monitorcontrol a server remotely over http in realtime on my client a phone with a browser i want to see the stats of the server cpuram hdd and gather info from various logsi am using ajax pollingon the client every 5 sec setinterval i call a php filescan a folder containing and logsread the last line of each logconvert that to jsonproblemsopen new connection every 5 secmultiple ajax callsrequest headers they are also data and so consume bandwidthresponse headers use php to read files every 5 sec even if nothing changedthe final json data is less than 5 kb but i send it every 5 sec and there are the headers and new connection every time so basically every 5 sec i have to send 510 kb to get 5 kb which are 1020 kbthose are 60 sec 5 sec 12 new connections per minute and about 15 mb per hour of traffic if i leave the app openlets say i have 100 users that i let monitor control my server that would be around 15 gb outgoing traffic in one hournot to mention that the php server is reading multiple files 100 times every 5 seci need something that on the server reads the last lines of those logs every 5 sec and maybe writes them to a file then i want to push this data to the client only if it is changedsse server sent events with phpheadercontenttype texteventstreamheadercachecontrol nocachewhiletrue echo id timendata readthelogsnn ob flush flush sleep1in this case after the connection is established with the first user the connection keeps open php is not made for that and so i save some space request headersresponse headers this work on my server bu most server do not allow to keep the connection open for long timealso with multiple users i read the log multiple timesslowing down my old serverand i cannot control the server i would need to use ajax to send a commandi need websocketsnodejs and websocketsusing nodejs from what i understand i can do all this without consuming alot of resources and bandwich the connection keeps open so no unnecessary headers i can recieve and send datait handles multiple users very welland this is where i need your helpthe nodejs server should in background update and store the logs data every 5 sec if the files are modifiedor should that do the operating system with iwatchdnotifythe data should be pushed only if changedthe reading of the logs should be happen only one time after 5 sec so not triggered by each userthis is the first example i have foundand modifiedvar wsrequirenodejswebsocketvar serverwscreateserverfunctionconn var datareadwheretostorethelogs connsendtextdata send the logs data to the user on first connection settimeoutchecklogs50 here i need to continuosly check if the logs are changed but if i use setintervalchecklogs50 or settimeout every user invokes a new timer and so having lots of timers on the server can i do that in background connontextfunctionstr dostuffstr various commands to control the server connonclosefunctioncodereason consolelogconnection closed listen8001var checklogsfunction var datareadwheretostorethelogs ifdataolddata connsendtextdata settimeoutchecklogs50the above script would be the notification server but i also need to find a solution to store somwhere the info of those multiple logs and do that everytime something is changed in the backgroundhow would you do to keep the bandwich low but also the server resourceshow would you do editbtw is there a way to stream this data simultaneosly to all the clinetsedit about the logs i also want to be able to scale the time dilatation between updates i mean if i read the logs of ffmpeg i ned the update every sec if possible but when no conversion is active i need to get the basic machine info every 5min maybe and so ongoals1 performant way to read store somewhere the logs data only if clinets connectedmysqlfile it is possible to store this info inside the ramwith nodejs2 performant way to stream the data to the various clients simultanously3 be able to send commands to the server bidirectional4 using web languages jsphp lunix commands something that is easy to implement on multiple machines free software if needed best approach would beread the logs based on current activity to the system memory and stream simultaneously and continuosly with an already open connection to the various clients with websocketsi wouldo not know anything that could be fasterupdatethe nodejs server is up and running using the websocketserver implementation as it appears to be the fastest onei wrote with the help of headcode the following code to handle properly the client situation to keep the process as low as possible checking various things inside the broadcast loop now the pushing the client handling is at a good pointvar wssnew requirewsserverport8080isbusylogsclientsichecklogsfunction ifwssclientsclientswssclientslength isbusylogsreadlogsisbusytrue iflogs i0 whileiclients wssclientsisendlogs setintervalchecklogs20but atm i am using a really bad way to parse the logs nodejshttprequestphp lol after some googling i found out that i totally could stream the output of linux software directly to the nodejs app i did not checked but maybe that would be the best way to do it nodejs also has a filesystem api where icould read the logs linux has it is own filesystem apithe readlogscan be async function is still something i am not happy withnodejs filesystemlinuxsoftwarenodejs output implementationlinux filesystem apikeep in mind that i need to scan various folders for logs and then parse somehow the outputted data and this every 2 secondsps i adde isbusy to the server variables in case the logreading sytem is async editanswer is not completemissinga performant way to readparse and store the logs somewhere linux filesystem api or nodejs api so the i store directly into system memory an explaination if it is possible to stream data directly to multiple users apparently nodejs loops trough the clients and so i think sending multiple times the databtw is it possibleworth to close the node server if there are no clients and restart on new connections on the apache side ex if i connect to the apache hosted html file a script launches the nodejs server again doing so would further reduce the memory leakingrighteditafter some experimenting with websockets some videos are in the comments i learned some new stuff raspberry pi has the possibility to use some cpu dma channels to to high frequency stuff like pwm i need to somehow understand how that workswhen using sensors and stuff like that i should store everything inside the ram nodejs already does that in a variable inside the scriptwebsocket remains the best choice as it is basically easely accessible from any device now simply using a browser,"['javascript', 'php']" +860426,throw a temporary argument passed by reference inline void my assert bool cond const stdexception e my assert failed if cond throw ethe standard ensures thata temporary bound to a reference parameter in a function call 522 persists until the completion of the full expression containing the calland for a thrown temporary objectthe temporary persists as long as there is a handler being executed for that exceptioncan i infer that a temporary that is passed to my assert survives until the catch block finishes,['c++'] +860540,what happens if the filter of an exception filter throws an exception i have not worked in c 6 yet but was wonderingas the title says what happens if the filter of an exception filter throws an exception i guess the really answer is the filter should be written in such a way that it never throws an exception but lets say it does will it be as if the exception happened inside the catch itselftry throw new exceptionforced exceptioncatch exception ex if methodthatthrowsanexception writelinefiltered handler 1catch exception ex writelinefiltered handler 2ortry throw new exceptionforced exceptioncatch exception ex if methodthatthrowsanexception writelinefiltered handler 1edit interesting examplethis section was removed because of a bug in alleged volatileread upon which the example was based further investigation is required,['c#'] +860622,a strange deadlock in mysql i have 10 vouchers with 2 different types i want to give them to some special users on our website so each user will get 1 vouchers for each typeto do that i created a table t voucher pool create table t voucher pool iautoid int10 unsigned not null auto increment icrowdid int10 unsigned default null stypecode varchar50 not null scode varchar255 not null spassword varchar255 not null ibindstatus tinyint1 unsigned not null default 1 ivoucherid int10 unsigned default null ibindtime int10 unsigned default null istatus tinyint1 unsigned not null default 1 icreatetime int10 unsigned default null iupdatetime int10 unsigned default null primary key iautoid key idx crowdid typecode icrowdidstypecodeibindstatus engineinnodb default charsetutf8here is the sql which will be executed in my logic1start transaction2select from t voucher pool where istatus1 and ibindstatus1 and icrowdid7 and stypecodeluckydraw limit 1 for update get one available voucher for luckydraw3select from t voucher pool where istatus1 and ibindstatus1 and icrowdid7 and stypecodejd limit 1 for update get one available voucher for jd4update t voucher pool set ibindstatus2 where iautoid401 update bindstatus for luckydraw voucher5update t voucher pool set ibindstatus2 where iautoid10401 update bindstatus for jd6committhis worked fine when the concurrency level is 1 but when the concurrency level got raised i found some requests will fail and they were caused by a deadlock here the deadlock will be detected if session 2 is pending on step 1 while session 1 tries to execute step 5here is the sequence to reproduce the deadlocksession1start transactionsession1select from t voucher pool where istatus1 and ibindstatus1 and icrowdid7 and stypecodeluckydraw limit 1 for updatesession2start transactionsession2select from t voucher pool where istatus1 and ibindstatus1 and icrowdid7 and stypecodeluckydraw limit 1 for updatependingsession1select from t voucher pool where istatus1 and ibindstatus1 and icrowdid7 and stypecodejd limit 1 for updatesession1update t voucher pool set ibindstatus2 where iautoid401session1update t voucher pool set ibindstatus2 where iautoid10401session2error 1213 401 deadlock found when trying to get lock try restarting transactioni guess an update to the field bindstatus cause this deadlock but since i have already got x lock for this record on step 3 why this still happenany detailed explantion on this will be very appreciate thanksupdate on 201536sorry guys it seems the example i posted before can not reproduce the problem i just updated the example and here is the information from the innodb status20150306 091053 7f975a02b700 1 transactiontransaction 264943793 active 44 sec starting index readmysql tables in use 1 locked 1lock wait 2 lock structs heap size 360 1 row locksmysql thread id 6608579 os thread handle 0x7f98f81b5700 query id 284931572 1921681016 devadmin sending dataselect from t voucher pool where istatus1 and ibindstatus1 and icrowdid7 and stypecodeluckydraw limit 1 for update 1 waiting for this lock to be grantedrecord locks space id 10453 page no 156 and bits 792 index idx crowdid typecode of table crowd dbt voucher pool trx id 264943793 lock mode x waitingrecord lock heap no 320 physical record and fields 4 compact format info bits 32 0 len 4 hex 07 asc 1 len 9 hex 4c55434b5944524157 asc luckydraw 2 len 1 hex 01 asc 3 len 4 hex 0191 asc 2 transactiontransaction 264941874 active 374 sec updating or deleting thread declared inside innodb 49mysql tables in use 1 locked 19 lock structs heap size 2936 7 row locks undo log entries 2mysql thread id 6608580 os thread handle 0x7f975a02b700 query id 284931884 1921681016 devadmin updatingupdate t voucher pool set ibindstatus2 where iautoid10401 2 holds the locksrecord locks space id 10453 page no 156 and bits 792 index idx crowdid typecode of table crowd dbt voucher pool trx id 264941874 lock mode xrecord lock heap no 320 physical record and fields 4 compact format info bits 32 0 len 4 hex 07 asc 1 len 9 hex 4c55434b5944524157 asc luckydraw 2 len 1 hex 01 asc 3 len 4 hex 0191 asc 2 waiting for this lock to be grantedrecord locks space id 10453 page no 156 and bits 792 index idx crowdid typecode of table crowd dbt voucher pool trx id 264941874 lock mode x locks gap before rec insert intention waitingrecord lock heap no 320 physical record and fields 4 compact format info bits 32 0 len 4 hex 07 asc 1 len 9 hex 4c55434b5944524157 asc luckydraw 2 len 1 hex 01 asc 3 len 4 hex 0191 asc we roll back transaction 1,['mysql'] +860628,overload resolution with ctyped enum consider the following minimal examplemodule module1 private enum myenum a end enum public sub mainargs as string areequalctype0 myenum myenuma error here end sub private function areequalof titem1 as t item2 as t as boolean return false end function private function areequalitem1 as object item2 as object as boolean return false end functionend modulefor some strange reason overload resolution fails in the line marked with error hereerror 6 overload resolution failed because no accessible areequal is most specific for these argumentsprivate function areequalitem1 as object item2 as object as boolean not most specificprivate function areequalof myenumitem1 as myenum item2 as myenum as boolean not most specificwhy is the second function not most specific both ctype0 myenum and myenuma should be expressions that are statically typed as myenuminterestingly i can only reproduce this problem with casting an enum areequalctype0 int32 0 and areequalmyenuma myenuma both compile without problemsi know how to fix this i know that i can just use areequalof myenum that is not the question i am curious why this happens some compiler bug interestingly the corresponding c code does workenum myenum a b static void mainstring args areequalmyenum0 myenumastatic bool areequaltt item1 t item2 return false static bool areequalobject item1 object item2 return false,['c#'] +860666,swift prepareforsegue cancel i am trying to implement a login screen when login is clicked it does the segue logini added a prepareforsegue override to try to cancel it if the login fails but i do not see any method to cancel the segue if there is a failurewhat is the best way to do this,['ios'] +860685,can constexpr be combined with volatile the following snippet works fine in clang 35 but not in gcc 492int main constexpr volatile int i 5with errorerror both volatile and constexpr cannot be used hereif i inspect the assembly that clang generates it shows 5 as expectedmovl 5 4rspin gcc constexpr int i 5 is optimized away but volatile int i 5 also shows 5 in the assembly volatile const int i 5 compiles in both compilers it is not a foreign concept for something to be both volatile and const at the same timewhich compiler is correct by the standards,['c++'] +860747,why does default rake task run specs in rails app i have one app that runs the specs with just rake but do not know where or how this task is defined there are no tasks in libtaskspart of gemfilegroup test do gem capybara gem guardrspec gem rspecrails gem database cleaner gem launchy gem oauth2 gem rack session access gem factory girl gem webmock gem seleniumwebdriverendrspec gemsguardrspec 450rspec 310rspeccore 317rspecexpectations 312rspecmocks 313rspecrails 310rspecsupport 312i am using rake 1042 and rails 416also when i addtask default do puts no default taskendto the rakefile first it runs the specs and then prints no default taskedit add rakefile add your own tasks in files placed in libtasks ending in rake for example libtaskscapistranorake and they will automatically be available to rakerequire fileexpand pathconfigapplication file railsapplicationload tasks,"['ruby-on-rails', 'ruby']" +860824,what is eating my memory the saw js mem usage edition so i heard you can supposedly do all fancy realtime games using js these days and i am no beginner at it so i though i should give it a try wrote some micro incomplete physics engine with some collision detection all sweet somewhat laggy though expected gc interrupts so tried to minimize any allocation till i was unable to see anything that should allocate memory in game loop no allocations no cleanup i though but here is what i getnow this is not neat at all so i tried removing my stuff from game loop in various ways still saw so no i present you the complete code that generates thishtmlbodyscript function draw consolelog1 function function maintframe draw windowrequestanimationframe main main scriptbodyhtmlamazing well this uses requestanimationframe as it seems this is what should be used for smooth performance at first i tried set interval like sohtmlbodyscript function draw consolelog1 windowsetintervaldraw 0scriptbodyhtmlexactly the same thingthis seems completely unacceptable but i have no ideas how to stop this saw i looked a lot about debugging memory and stuff that was while i though that problem was in my drawing and updating functions but these to snippets have basically nothing and yet they produce that memory patter maybe it is my browser or is it inescapable and js is unusable for anything realtime i would like to believe that someone on the web knows something i do not as there are lots of people promising wonders with jswhat am i doing wrong in these snippetsedit by the way removing console log changes nothing in case anyone thinks thats the problem,['javascript'] +860889,when should i use return in es6 arrow functions the new es6 arrow functions say return is implicit under some circumstancesthe expression is also the implicit return value of that functionin what cases do i need to use return with es6 arrow functions,['javascript'] +861100,how to comment code using a generic class of a specific type i am trying to document my code in a proper wayi have a method that can throw a faultexception of a specific type when i view the documentation for the method it does not show the specific type of the faultexceptionsummary description of methodsummary exception creffaultexceptionvalidationfaultdescription hereexceptionorganizationdto updateupdateorganizationrequest organizationdtodocumentation shows faultexceptiontdetail description herei want it to show faultexceptionvalidationfaultdescription herehow can i achieve this,['c#'] +861119,paperjs would not resize the canvas correctly i am trying out paperjs for fun but it seems i am already stuck at the very startadding resizetrue to the canvas tag is supposed to make the element as high and wide as the browser window however doing that results in some rather strange behaviori expected the canvas to adjust itself to the viewport right after loading the page but it did not do so which is why i initially thought it did not resize at all what actually happens though is even more bizarre the canvas starts out at its default size of 300x150 and when i resize the viewport it grows slowly but indefinitelyfor the record i have tried using datapaperresizetrue or just resize instead or using chrome instead of firefox all to no availi am not expecting an answer if this problem is caused by some inexplicably weird setup on my end i am wondering however if the problem is common or even known to exist at all and has known causes and solutionsheres the code i am usingdoctype htmlhtml head meta charsetutf8 script typetextjavascript srcpaperfullminjsscript script typetextpaperscript canvasmycanvas var path new path pathstrokecolor black pathmovetonew point120 120 pathlinetonew point500 500 script head body canvas idmycanvas styleborder 1px dotted red resizetruecanvas bodyhtml,['javascript'] +861120,why does javascript es6 promises continue execution after a resolve as i understand a promise is something that can resolve or reject but i was suprised to find out that code in the promise continues to execute after a resolve or reject is calledi considered resolve or reject being an asyncfriendly version of exit or return that would halt all immediate function executioncan someone explain the thought behind why the following example sometimes shows the consolelog after a resolve callvar call function return new promisefunctionresolve reject resolve consolelogdoing more stuff should not be visible after a resolve callthenfunction consolelogresolvedjsbin,['javascript'] +861138,not receiving cloudkit push notifications for custom record zone on the mac i have setup a custom zone subscription to receive silent push notifications from my custom record zone everything works fine on my ios devices but i am not able to receive the notifications on my macto register the notifications i am registering the notification type in applicationdidfinishlaunchingnsapplication sharedapplication registerforremotenotificationtypesnsremotenotificationtypenonetried the other types with the same resultapplicationdidregisterforremotenotificationswithdevicetokenis then called with a valid token everything seems fine but when the custom zone registers changes i receive no notification and applicationdidreceiveremotenotificationis not called i have also tried to set the alert body to an empty string like thiscknotificationinfo info cknotificationinfo alloc initinfoalertbody infoshouldsendcontentavailable yesbut it did not work either when i set a string as the alert body and register the appropriate notification type i also get a notification with that body in the top right corner but applicationdidreceiveremotenotification is not called hope you can help me thanks,['ios'] +861146,how to make a line break on the python ternary operator sometimes a line containing a ternary operator in python gets too longanswer ten for that you must be mad if does not hagglebrian else it is worth ten if it is worth a shekelis there a recommended way to make a line break at 79 characters with a ternary operator i did not find it in pep 8,['python'] +861165,exclude assets for release build type i am importing an android library in an application built with gradle like thatdependencies compile comexamplegreatlib01snapshotthis library contains only assets js css and images to be used in a webview with a layout like thatassets greatcss greatminjs greatminjsmap js plopjs foojs img the js folder contains source files to be used with source maps i would like to include it and the map file for the debug builds and have only the minified js in release builds but i cannot find a way to do thatso far i have tried a android this does not exclude anything packageoptions exclude assetsjs buildtypes release this does exclude the js folder but in both release and debug aaptoptions ignoreassetspattern js any idea if what i want is possible to achieve and if so howi have also thought of publishing two versions of the library greatlib and greatlibdebug and have the dependency in debugcompile and releasecompile but i would prefer avoiding that and publishing a single version,['android'] +861176,abstraction with java in android i was studying some tutorials concerning the java language i was wondering if i should abstract every time that i code something and on any type of standard and stacki have seen that with every spring services for example we could even abstract controllers using interfaces with ejbs on javaee stack etci was wondering what is the aim of that should i do the same thing while developing with the android sdkshould i abstract every class that i code,"['java', 'android']" +861209,deserializing a flagged enum with a space results in serializationexception when deserializing a flagged enum that is decorated with a enummemberattribute with a value containing a space a serializationexception is thrown the space in the value is treated as a separatoris there a way to change the separator or put the values in quotes or is there even a more simple solution options i already am considering are replacing the flagged enum with a list of this enum type replacing the spaces with underscores this is used in a wcf service and i amaware that enums in datacontracts by some are considered a bad thingso i am also thinking about losing the enumas all togetherbut i really feel that this should be something configurable or something other people already solved but i cannot find anythingi have boiled the problem down to a simple unit test the code below results inmessageinvalid enum value test cannot be deserialized into type unitteststestenum ensure that the necessary enum values are present and are marked with enummemberattribute attribute if the type has datacontractattribute attribute sourcesystemruntimeserializationusing systemusing systemiousing systemruntimeserializationusing systemxmlusing fluentassertionsusing microsoftvisualstudiotesttoolsunittestingnamespace unittests testclass public class enumserizalizationtests testmethod public void serializinganddesrializingaflaggedenumshouldresultinsameenumvalues arrange var orgobject new testclass value testenumtestvalue1 testenumtestvalue2 act var temp datacontractserializeobjectorgobject var newobject datacontractdeserializeobjecttestclasstemp assert newobjectshouldbeequivalenttoorgobject roundtripping serialization should result in same value public string datacontractserializeobject objecttoserialize using var output new stringwriter using var writer new xmltextwriteroutput formatting formattingindented new datacontractserializertypeof twriteobjectwriter objecttoserialize return outputgetstringbuildertostring public t datacontractdeserializeobjecttstring stringtodeserialize datacontractserializer ser new datacontractserializertypeoft t result using stringreader stringreader new stringreaderstringtodeserialize using xmlreader xmlreader xmlreadercreatestringreader result tserreadobjectxmlreader return result datacontract knowntypetypeoftestenum public class testclass datamember public testenum value get set flags datacontract public enum testenum enummembervalue test value one testvalue1 1 enummembervalue test value two testvalue2 2 enummember testvalue3 4 enummember testvalue4 8,['c#'] +861210,copy elision misunderstanding include iostreamstruct a a stdcout def constrn aconst a stdcout copy constrn a func1 return avoid func2a a int main func2func1after compiling with g copycpp stdc11 fnoelideconstructorsoutput is def constrcopy constrcopy constrand my questions is why 2 copy constr i thought only 1 copy was neededi might have a guess that func1 throws a temp object and this temp object needs to be copied to another memory region and from that region again a copy must be made for the func2 parameter but it is vague for me could you explain it in detail please,['c++'] +861317,how to use springs jdbctemplate to connect to a simple mysql database i am trying to use springs jdbctemplate class to connect to a simple mysql database based on this tutorial in fact i used their project setuppomxml project xmlns xmlnsxsi xsischemalocation modelversion400modelversion groupidtestgroupid artifactidjdbctestartifactid version001snapshotversion parent groupidorgspringframeworkbootgroupid artifactidspringbootstarterparentartifactid version122releaseversion parent dependencies dependency groupidorgspringframeworkbootgroupid artifactidspringbootstarterartifactid dependency dependency groupidorgspringframeworkgroupid artifactidspringjdbcartifactid dependency dependency groupidmysqlgroupid artifactidmysqlconnectorjavaartifactid dependency dependency groupidorgprojectlombokgroupid artifactidlombokartifactid version1148version scopeprovidedscope dependency dependencies build plugins plugin groupidorgspringframeworkbootgroupid artifactidspringbootmavenpluginartifactid plugin plugins buildprojectthe lombok dependency is for getters and settersthen there is the application classpackage testimport orgspringframeworkbeansfactoryannotationautowiredimport orgspringframeworkbootcommandlinerunnerimport orgspringframeworkbootspringapplicationimport orgspringframeworkbootautoconfigurespringbootapplicationimport orgspringframeworkjdbccorejdbctemplatespringbootapplicationpublic class application implements commandlinerunner public static void mainstring args springapplicationrunapplicationclass args autowired jdbctemplate jdbctemplate override public void runstring arg0 throws exception systemoutprintlncreating tables jdbctemplateexecutedrop table customers if exists jdbctemplateexecutecreate table customers id serial first name varchar255 last name varchar255 and finally a customer pojopackage testimport lombokallargsconstructorimport lombokdatadataallargsconstructorpublic class customer private long id private string firstname lastnamefor datasource configuration i have an applicationproperties file in my resources folderspringdatasourceurljdbcmysqllocalhost3306testspringdatasourceusernametestspringdatasourcepasswordtestspringdatasourcedriverclassnamecommysqljdbcdriverspringjpadatabase mysqlspringjpashowsql truespringjpahibernateddlauto updatespringjpahibernatedialect orghibernatedialectmysql5dialectspringjpahibernatenaming strategy orghibernatecfgimprovednamingstrategythe database is up and running and still the autowirig dosent seem to workhere is the exception i get when i try to run itorgspringframeworkbeansfactorybeancreationexception error creating bean with name application injection of autowired dependencies failed nested exception is orgspringframeworkbeansfactorybeancreationexception could not autowire field orgspringframeworkjdbccorejdbctemplate testapplicationjdbctemplate nested exception is orgspringframeworkbeansfactorynosuchbeandefinitionexceptionno qualifying bean of type orgspringframeworkjdbccorejdbctemplate found for dependency expected at least 1 bean which qualifies as autowire candidate for this dependency dependency annotationsorgspringframeworkbeansfactoryannotationautowiredrequiredtrue at orgspringframeworkbeansfactoryannotationautowiredannotationbeanpostprocessorpostprocesspropertyvaluesautowiredannotationbeanpostprocessorjava334 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorypopulatebeanabstractautowirecapablebeanfactoryjava1202 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorydocreatebeanabstractautowirecapablebeanfactoryjava537 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorycreatebeanabstractautowirecapablebeanfactoryjava476 at orgspringframeworkbeansfactorysupportabstractbeanfactory1getobjectabstractbeanfactoryjava303 at orgspringframeworkbeansfactorysupportdefaultsingletonbeanregistrygetsingletondefaultsingletonbeanregistryjava230 at orgspringframeworkbeansfactorysupportabstractbeanfactorydogetbeanabstractbeanfactoryjava299 at orgspringframeworkbeansfactorysupportabstractbeanfactorygetbeanabstractbeanfactoryjava194 at orgspringframeworkbeansfactorysupportdefaultlistablebeanfactorypreinstantiatesingletonsdefaultlistablebeanfactoryjava755 at orgspringframeworkcontextsupportabstractapplicationcontextfinishbeanfactoryinitializationabstractapplicationcontextjava757 at orgspringframeworkcontextsupportabstractapplicationcontextrefreshabstractapplicationcontextjava480 at orgspringframeworkbootspringapplicationrefreshspringapplicationjava686 at orgspringframeworkbootspringapplicationrunspringapplicationjava320 at orgspringframeworkbootspringapplicationrunspringapplicationjava957 at orgspringframeworkbootspringapplicationrunspringapplicationjava946 at testapplicationmainapplicationjava12 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokeunknown source at sunreflectdelegatingmethodaccessorimplinvokeunknown source at javalangreflectmethodinvokeunknown source at orgspringframeworkbootloadermainmethodrunnerrunmainmethodrunnerjava53 at javalangthreadrununknown sourcecaused by orgspringframeworkbeansfactorybeancreationexception could not autowire field orgspringframeworkjdbccorejdbctemplate testapplicationjdbctemplate nested exception is orgspringframeworkbeansfactorynosuchbeandefinitionexceptionno qualifying bean of type orgspringframeworkjdbccorejdbctemplate found for dependency expected at least 1 bean which qualifies as autowirecandidate for this dependency dependency annotations orgspringframeworkbeansfactoryannotationautowiredrequiredtrue at orgspringframeworkbeansfactoryannotationautowiredannotationbeanpostprocessorautowiredfieldelementinjectautowiredannotationbeanpostprocessorjava561 at orgspringframeworkbeansfactoryannotationinjectionmetadatainjectinjectionmetadatajava88 at orgspringframeworkbeansfactoryannotationautowiredannotationbeanpostprocessorpostprocesspropertyvaluesautowiredannotationbeanpostprocessorjava331 21 common frames omittedcaused by orgspringframeworkbeansfactorynosuchbeandefinitionexception no qualifying bean of type orgspringframeworkjdbccorejdbctemplate found for dependency expected at least 1 bean which qualifies as autowire candidate for this dependency dependency annotations orgspringframeworkbeansfactoryannotationautowiredrequiredtrue at orgspringframeworkbeansfactorysupportdefaultlistablebeanfactoryraisenosuchbeandefinitionexceptiondefaultlistablebeanfactoryjava1301 at orgspringframeworkbeansfactorysupportdefaultlistablebeanfactorydoresolvedependencydefaultlistablebeanfactoryjava1047 at orgspringframeworkbeansfactorysupportdefaultlistablebeanfactoryresolvedependencydefaultlistablebeanfactoryjava942 at orgspringframeworkbeansfactoryannotationautowiredannotationbeanpostprocessorautowiredfieldelementinjectautowiredannotationbeanpostprocessorjava533 23 common frames omittedwhat i find curious is the fact that if i replace the mysqlconnectorjava dependeny with a comh2database it just works as in the spring exampledo i need to configure the mysql datasource in a dirfferent wayany suggestions,"['java', 'mysql']" +861391,persist data in a db issue receiving null on console i am new to nodejs and i am having an issue trying to persistsave some data in a db let us start from the beginning so you can understand easier i have a list of sports with an option to checked or unchecked that is what i need to persist that checkedfront endcontrollerjsscopetogglesportselection functionsport var params paramsuser scopecustomercustomer sportchecked sportchecked sportsfactorysetsportcheckedparamsservicejs setsportchecked functionparams var defer qdefer httppostconstant varsbackend url sportschecked params successfunctionsportchecked localforagefactoryremoveconstant varslocalforage sports checked params deferresolvesportchecked errorfunctionerr consolelogerr deferrejecterr return deferpromise i have been debugging this front end part and everything seems to be oknow back endsetsportctrljsmoduleexports setcheck functionreq res var checkedsportparams reqbody sportselectionservicesportcheckedcheckedsportparamsthenfunction resjson200 msg ok functionerr resjson400 err sportselectionjs modelmoduleexports connection rethisserver attributes sport type array required false user type string required true in this part i can see how that console are print in the terminal but if i do consolelogsportchecked or consolelognewsport all i get is an array which says null everywheresportselectionservicejsmoduleexports sportchecked functionparams var promise requirebluebird return new promisefunctionfullfill reject consoletimesportchecked findone sportselectionfindone user paramsuser execfunctionerr sportchecked consoletimeendsportchecked findone var newsport if err rejectnew errorerror finding user consoleerrorerr else if sportchecked newsport sportcheckedsport consoletimesportchecked update sportselectionupdate user paramsuser sport newsport execfunctionerr sportcheckedupdated consoletimeendsportchecked update if err rejectnew errorerror on sportchecked else fullfillsportcheckedupdated if sportcheckedsport sportcheckedsportpushparamssport consolelognew sport added else sportcheckedsport paramssport else consoletimesportchecked create sportselectioncreate sport paramssport user paramsuser execfunctionerr created consoletimeendsportchecked create if err rejectnew errorerror on sportchecked else fullfillcreated so what do you think is my issue here what am i doing wrong,['javascript'] +861702,microoptimization iterating with local variable vs class member i thought i will save some time if i declare iterating variable once as a class memberstruct foo int i void method1 fori0 ia i void method2 fori0 ib i foohowever this seems to be cca 20 fasterstruct foo void method1 forint i0 ia i void method2 forint i0 ib i fooin this codevoid loop arduino loops foomethod1 foomethod2can you explain the performance differencei need to run many simple paralel processes on arduino where such microoptimalization makes a difference,['c++'] +861747,spring mvc lookup validators automatically suppose i have a sample entity class like thispublic class address and a corresponding validatorcomponentpublic addressvalidator implements validator override public boolean supportsclass entityclass return entityclassequalsaddressclass override public void validateobject obj errors errors when i use a controller like the following everything worksrestcontrollerrequestmappingaddressespublic class addresscontroller autowired private addressvalidator validator initbinder protected void initbinderwebdatabinder binder bindersetvalidatorvalidator requestmappingmethodpost public long addnewaddressvalid requestbody address address however if i omit the validator registering part ie the following validation is not performedautowiredprivate addressvalidator validatorinitbinderprotected void initbinderwebdatabinder binder bindersetvalidatorvalidatorhaving to register validators manually seems pointless can i instruct spring to look up validators automatically similar to how controllers are looked upit is a spring boot based application,['java'] +861775,what does promisevalue mean in javascript console and how to do i get it i have the following function attempting to use promises var getdefinitions function return new promisefunctionresolve resolvecontactmanagerrequestdefinitionentities var definitions getdefinitions is returningpromise promisestatus resolved promisevalue childi want to get the value of promisevalue but asking for var value definitionspromisevalue gives me an undefined result my question is what do the double brackets mean and how do i retrieve the value of promisevalue,['javascript'] +861805,not able to use mysql2 gem with rails 415 in rubymine i am trying to use the mysql 2 gem with rails so i added gem mysql2 i am not able to install it using bundle install and it gives me this errorgemextbuilderror error failed to build gem native extension usersbenrvmrubiesruby220binruby r siteconf20150307171431jx7cobrb extconfrb checking for rubythreadh yeschecking for rb thread call without gvl in rubythreadh yeschecking for rb thread blocking region nochecking for rb wait for single fd yeschecking for rb hash dup yeschecking for rb intern3 yeschecking for mysql query in lmysqlclient nochecking for main in lm yeschecking for mysql query in lmysqlclient nochecking for main in lz yeschecking for mysql query in lmysqlclient nochecking for main in lsocket nochecking for mysql query in lmysqlclient nochecking for main in lnsl nochecking for mysql query in lmysqlclient nochecking for main in lmygcc nochecking for mysql query in lmysqlclient no extconfrb failed could not create makefile due to some reason probably lack of necessarylibraries andor headers check the mkmflog file for more details you mayneed configuration optionsprovided configuration options withoptdir withoptinclude withoutoptincludeoptdirinclude withoptlib withoutoptliboptdirlib withmakeprog withoutmakeprog srcdir curdir rubyusersbenrvmrubiesruby220binruby base name withmysqldir withoutmysqldir withmysqlinclude withoutmysqlincludemysqldirinclude withmysqllib withoutmysqllibmysqldirlib withmysqlconfig withoutmysqlconfig withmysqldir withoutmysqldir withmysqlinclude withoutmysqlincludemysqldirinclude withmysqllib withoutmysqllibmysqldirlib withmysqlclientlib withoutmysqlclientlib withmlib withoutmlib withmysqlclientlib withoutmysqlclientlib withzlib withoutzlib withmysqlclientlib withoutmysqlclientlib withsocketlib withoutsocketlib withmysqlclientlib withoutmysqlclientlib withnsllib withoutnsllib withmysqlclientlib withoutmysqlclientlib withmygcclib withoutmygcclib withmysqlclientlib withoutmysqlclientlibextconf failed exit code 1gem files will remain installed in usersbenrvmgemsruby220gemsmysql20318 for inspectionresults logged to usersbenrvmgemsruby220extensionsx86 64darwin14220mysql20318gem makeoutan error occurred while installing mysql2 0318 and bundler cannot continuemake sure that gem install mysql2 v 0318 succeeds before bundlingi have no idea how to get it to work so any help would be appreciatedhere is some info on my computerruby v ruby 220p0 20141225 revision 49005 x86 64darwin14gem rails 415 rails v would not workbundler v bundler version 184os mac yosemite,"['mysql', 'ruby-on-rails', 'ruby']" +861862,prevent uialertcontroller to thismiss i would like to prevent the uialertcontroller from thismissing i have a uialertaction that simply appends a string into the uialerttextfield however once tapped it thismisses the view controller undesired i have tried adding an nsnotification with undesired results uialertaction pastemessage uialertaction actionwithtitlepaste message styleuialertactionstyledefault handleruialertaction action uitextfield textfield alertctextfieldsfirstobject textfieldtext textfieldtext stringbyappendingstringnsstring stringwithformat copiedstring i have also tried setting no to pastemessage by alertc canperformactionselectorthismissviewcontrolleranimatedcompletion withsenderpastemessagevoidthismissviewcontrolleranimatedboolflag completionvoid voidcompletion uialertcontroller alertcontroller uialertcontroller selfpresentedviewcontroller uialertaction paste alertcontrolleractionsfirstobject if paste flag no else flag yes edit i am not looking to prevent the tapping of uialertaction i am looking to prevent the uialertcontroller from thismissing when tapping on said action the action can be enabledthisabled whatever but my goal is to simply paste the copied message into the uitextfield by pressing an action hence the reason i do not want it to be thismissedi also realize setting the bool to thismissviewcontrolleranimated simply sets it to not animate the view controllers thismissal i do not want it to imply it was for stopping the actual thismissal process simply offering the things i have tried in relation to my goal i have also tried presenting a new uialertcontroller when selecting pastemessage autopopulating the new uialertcontrollers textfield with the copied message it works but i feel like it is too hacky for what could be done,['ios'] +862066,how to add todos and track project issues in android studio not in sources i am writing a new better version of my old android project that will fix a lot of ui bugs but also has a better design needed for integration of some new featuresas i go through the source i can see all my old and new todos in the source but there are things i remember and forget i want to do in the future and do not fit in any source yeteclipse had a simple list of tasks in the project on which you could write down and track all bug fixes and new features you wanted for that project very handyis there a way add such tasksissuesnotestodos in android studio in the project in general without adding them at a specific place in the sources,['android'] +862110,add function that works with different combinations of chainingarguments i am trying to write an add function that will work in many scenariosadd2 6add2 8add2 6add2value 8add2 2 8add2add2 4add2add2add22value 12add2add2value 8this is what i have so farfunction add var sum 0 for var i in arguments sum argumentsi var ret addbindnull sum retvalue function return sum retadd function for var i in arguments sum argumentsi return sum retvalueof function return sum return retconsolelogadd2consolelogadd2consolelogadd2consolelogadd2valueconsolelogadd2 2consolelogadd2add2consolelogadd2add2valueconsolelogadd2add2add22valuei am having a problem with the last two cases add2add2add22value 12 add2add2value 8it seems like i would have to keep nesting the add functions if i wanted to chain more than two together and also add the value function to each of them but obviously i am missing something simple that will allow me to chain them as much as i like and call value on any of themalso they need to always return ints not strings and it seems like sometimes they do and other times they do not,['javascript'] +862271,how to get div shaped as a flag with css i want to add a label on some of my elements on a website and design for a label that is a flag with an inverted vshaped cut at the bottomso far i have thishtmldiv classcshapesdivcsscshapes borderleft 99px solid f00f borderright 99px solid f00f borderbottom 39px solid transparenthowever i need the background to be white and border around this shape in purple and 1px i was trying to fit the same shape just in white inside of this one but everything got messy and did not go as expectedmaybe it is a wrong approach but i want to end up with labels that would look something like this,"['html', 'css']" +862377,is it possible to have multiple dynamic method names in a class i am reading through the es6 class information on babeljss documentation and noticed that it says that objects can now have dynamic property namesvar obj computed dynamic property names prop 42 42this seems like it would be useful in classes as well is it possible to do something similar in an es6 class without doing it in a constructor ieclass foo read format1 format2 my format reading function rather than doing something like this in the constructorclass foo constructoropts let formats format1 format2 let self this formatsforeachfunctionformat selfread format function my format reading function in other words i want to be able to take some array such as format1 format2 and create two methods readformat1 and readformat2 in the class dynamically without using the constructor is this possible,['javascript'] +862440,can you have two asynctasks in one activity i have already developed an activity which will parse json data and thisplay the results in a listview i am using an asynctask for this purposewhat i want now is that when i click on an item in the listview the file should start downloading can i write another asynctask in the same activity so that this asynctask will do the downloading work for me is there any problem with having multiple asynctasks in the same activity,['android'] +862632,what is the most simple setup for a mean stack docker container to have the same config on os x and digitalocean i am playing around with a mean javascript projectmongodb angular sailsjs nodejsas i am offline a lot of the time i would like to keep my dev environment running in a docker container on os x laptop using boot2dockerthe production not actual production just somewhere i deploy to to show it to friends is a digital ocean droplet running ubuntu as host and hopefully the same docker containeri expect that the environment would not change very often and that i can continue using git pushpull to push just the code changesdo i need anything else other than what i described abovedo i need vagrant for example to deploy that docker container or is that an overkillcan docker specify all all my needs that is the right version of nodejs sails etcis there a ready made container i can reuse or modify rather than starting from scratch,['javascript'] +862660,how to enable tls 12 support in an android application running on android 41 jb as per the docs in android for sslsocket and sslcontext tls v11 and v12 protocols are supported in api level 16 but are not enabled by defaulthow do i enable it on a device running android 41 or later but below 50i have tried creating a custom sslsocketfactory which enables all the supported protocols when sockets are created and later use my custom implementation ashttpsurlconnectionsetdefaultsslsocketfactorynew mysslsocketfactorypublic class mysslsocketfactory extends sslsocketfactory private sslcontext sc private sslsocketfactory ssf public mysslsocketfactory try sc sslcontextgetinstancetls scinitnull null null ssf scgetsocketfactory catch nosuchalgorithmexception e eprintstacktrace catch keymanagementexception e eprintstacktrace override public socket createsocketsocket s string host int port boolean autoclose throws ioexception sslsocket ss sslsocket ssfcreatesockets host port autoclose setenabledprotocolsgetsupportedprotocols setenabledciphersuitesgetsupportedciphersuites return ss override public string getdefaultciphersuites return ssfgetdefaultciphersuites override public string getsupportedciphersuites return ssfgetsupportedciphersuites override public socket createsocketstring host int port throws ioexception unknownhostexception sslsocket ss sslsocket ssfcreatesockethost port setenabledprotocolsgetsupportedprotocols setenabledciphersuitesgetsupportedciphersuites return ss override public socket createsocketinetaddress host int port throws ioexception sslsocket ss sslsocket ssfcreatesockethost port setenabledprotocolsgetsupportedprotocols setenabledciphersuitesgetsupportedciphersuites return ss override public socket createsocketstring host int port inetaddress localhost int localport throws ioexception unknownhostexception sslsocket ss sslsocket ssfcreatesockethost port localhost localport setenabledprotocolsgetsupportedprotocols setenabledciphersuitesgetsupportedciphersuites return ss override public socket createsocketinetaddress address int port inetaddress localaddress int localport throws ioexception sslsocket ss sslsocket ssfcreatesocketaddress port localaddress localport setenabledprotocolsgetsupportedprotocols setenabledciphersuitesgetsupportedciphersuites return ss but it still gives an exception while trying to establish a connection with a server on which only tls 12 is enabledhere is the exception i get0309 092138427 wsystemerr2496 javaxnetsslsslhandshakeexception javaxnetsslsslprotocolexception ssl handshake aborted ssl0xb7fa0620 failure in ssl library usually a protocol error 0309 092138427 wsystemerr2496 error14077410ssl routinesl23 get server hellosslv3 alert handshake failure externalopensslssls23 clntc741 0xa90e69900x0,['android'] +862721,weakeventmanager removehandler does not always work when called asynchronously i am using the weakeventmanagerteventsource teventargs class in order to subscribe to events in c event subscription works fine however calling weakeventmanagerteventsource teventargsremovehandler from a task does not always remove the handler most but not all of the time the handler is still executed when the event firesthis is illustrated in the following examplepublic class eventsource public event eventhandler fired delegate public void fireevent firedthis eventargsempty class program private static bool added removed handled static void mainstring args for int i 1 i 100 i added removed handled false var source new eventsource addhandlerasyncsourcewait removehandlerasyncsourcewait sourcefireevent if removed handled consolewritelineevent handled after removal else consolewriteline consolereadkey private async static task addhandlerasynceventsource source await taskrun systemwindowsweakeventmanagereventsource eventargsaddhandlersource fired handleevent added true private async static task removehandlerasynceventsource source await taskrun systemwindowsweakeventmanagereventsource eventargsremovehandlersource fired handleevent removed true private static void handleeventobject sender eventargs e handled true the handler is removed all of the time however in most cases the event is still handledam i making an error in the way that these methods are called do these methods support being called asynchronously is there an alternative approach that would workmany thanks for your help in advance,"['c#', '.net']" +862793,is line height determined by the first font in a css font stack i ask this because when i try to create a css font stack for multilanguage content such as english and chinese the final rendering is affected by the first font in the stack usually latin ones since most chinese font comes with latin supportsee this codepen for examplediva p overflow hiddenp backgroundcolor red border 1px solid black thisplay inlineblockchineseonly fontfamily hiragino sans gb sansserif fontsize 24px lineheight 48pxenglishchinese fontfamily avenir next hiragino sans gb sansserif fontsize 24px lineheight 48pxchineseenglish fontfamily hiragino sans gb avenir next sansserif fontsize 24px lineheight 48pxwhat i am seeingsince chinese glyphs only appear in the hiragino sans gb i expect all chinese blocks to use the same line height but they are apparently affected by adding the avenir next font at the top of the stacksince both firefox and chrome on osx renders my example the same i wonder if the css specification mentions anything about this css 21 fonts spec does not appear to state what to do with line height when you fallback on missing glyphsupdated safari does render differently but unfortunately the difference is due to overflow hidden not glyph fallback my updated example may show this a bit cleareron chrome and firefoxon safariand if you are really into fontrelated headaches try this example showing different font stacks and see how they differ on each browser,['css'] +863073,intellijpycharm cannot debug python modules i use pycharmintellij community editions from a wile to write and debug python scripts but now i am trying to debug a python module and pycharm does a wrong command line instruction parsing causing an execution error or maybe i am making a bad configurationthis is my rundebug configurationand this is executed when i run the module no problems hereusrbinpython34 m histrawbut when i debug this is the output in the intellij consoleusrbinpython34 m optappspycharmhelperspydevpydevdpy multiproc client 127001 port 57851 file histrawusrbinpython34 error while finding spec for optappspycharmhelperspydevpydevdpy class importerror no module named optappspycharmhelperspydevpydevdprocess finished with exit code 1as you can see the parameters are wrong parsed and after m option a intellij debug script is passed before the module namei also tried just put m histraw in the script field but does not work that field is only to put python script paths not modulesany ideas,['python'] +863158,why in the code 4561 output is 56 include iostreamint main stdcout 251 return 0i am getting 5 as outputwhen i use 51output is blank4561 output is 56confused what is going behind the scenes,['c++'] +863171,react flux getting initial state into a store we have recently switched over to react flux from angular to build a rather complex business applicationtaking the approach of having one container component that passes all state as properties down the component tree is not a practical way to develop the app for us as the app makes use of large pagelike modals enough state does get passed down to the modals for them to load their data into their storesthe problem i have is i need to get some initial state passed down as props into the modal components store in this post the good guys over at facebook say it is ok to use props for initial state when synchronization is not the goal this is how i get the initial state into my store currentlyvar abc reactcreateclass getinitialstate function return abcstoregetinitialabcstatethispropsinitiala var abcstore refluxcreatestore init function state a null b b init c c init getinitialabcstate functioninitiala statea initiala return state getabcstate function return state i am unsure what the best practice is to do this or whether this is a flux antipattern,['javascript'] +863191,bug in javatimeduration i need to parse durations from strings java 8 provide a method for that taking the iso8601 standard as a basisdurationparsep10d parses as ten daysdurationparsept1h parses as one houras the standard states that it is permitted to omit the t character by mutual agreement some of the javadoc examples of durationsparse leave out the t according to them the following expression should parse as 6 hours and 3 minutesp6h3mbut i found that all expressions ommitting the t throw a datetimeparseexception is that a bug in the parse method or am i missing something,['java'] +863347,does php silently optimize consecutive fseekcommands into one fseek command i am running windows 7 64 bit with the latest xampp version that has a 32bit php versionon testing for a very big file bigger than php max int 2147483647 i am now pretty sure that the consecutively following fseeks are summed up before being executed on the filepointer i have two questionscould i break up this summing up with reasonable means or only with the workaround mentioned in the link aboveis this aggregation happening in php as i assume though i do not know where in php or in windows 7answering myself trying two workarounds with multiple seeks did not work on my system instead they put the filepointer to different positions at under php max int 32bit php only can seek up to php max int 8192 reading from there on is still possible but i do not know how far therefore the question is obsolete for my specific case as 32bit php only can seek up to php max int 8192 whatever you do i leave the question because two people voted it up and might be interested in a general answeri filed a bug report hereresult with a 64bit php build it might work but i did not try it,['php'] +863401,cannot find an outgoing row head for incoming head uibutton i have a crash on an autolayout issue on ios7 only ios8 it worksthe thing is that the uibutton indicated 0x7b7780a0 does not exist when i look at recursivedescription of the uiview how do i investigate this where to startediti encountered this answer and indeed i have a very small float in the traceback however i am not adding constraints in code and all my multipliers are 1editposted an answer to myself however is an excellent answer that directed me to the solution eventuallythe crash 20150310 155008152 cookila copy5779607 objective objective 0x7b84c960 750104308e05 250661612e05 750104308e07 25089407e08uibutton0x7b6299c0widthid 408 750223517e08 25089407e08uibutton0x7b661ad0widthid 385 750186265e07 25089407e08uibutton0x7b7780a0widthid 388 750104308e07 25013411e07uiview0x7b6547d0widthid 41920150310 155009674 cookila copy5779607 terminating app due to uncaught exception nsinternalinconsistencyexception reason nsisengine 0x7b84c120 rows uilayoutcontainerview0x7b6505a0heightid 118 960 10x7b7679b0markerid 49 20x7b638350markerid 135 uilayoutcontainerview0x7b6505a0widthid 115 640 10x7b767980markerid 46 20x7b6592b0markerid 131 uilayoutcontainerview0x7b6505a0minxid 121 0 20x7b642e00markerid 130 10x7b6592b0markerid 131 uilayoutcontainerview0x7b6505a0minyid 122 0 20x7b657350markerid 134 10x7b638350markerid 135 uinavigationtransitionview0x7b756bc0heightid 110 960 10x7b7679b0markerid 49 20x7b664d50markerid 119 20x7b638350markerid 135 uinavigationtransitionview0x7b756bc0widthid 107 640 10x7b767980markerid 46 20x7b664cf0markerid 116 20x7b6592b0markerid 131 uinavigationtransitionview0x7b756bc0minxid 113 0 20x7b6584c0markerid 112 10x7b664cf0markerid 116 uinavigationtransitionview0x7b756bc0minyid 114 0 20x7b664d20markerid 117 10x7b664d50markerid 119 uiviewcontrollerwrapperview0x7b77add0heightid 102 960 10x7b7679b0markerid 49 20x7b659c40markerid 1 20x7b664d50markerid 119 20x7b638350markerid 135 uiviewcontrollerwrapperview0x7b77add0widthid 99 640 10x7b767980markerid 46 20x7b655430markerid 108 20x7b664cf0markerid 116 20x7b6592b0markerid 131 uiviewcontrollerwrapperview0x7b77add0minxid 105 0 20x7b655400markerid 104 10x7b655430markerid 108 uiviewcontrollerwrapperview0x7b77add0minyid 106 0 20x7b659c10markerid 109 10x7b659c40markerid 1 uiwindow0x7b742a60heightid 45 960 10x7b7679b0markerid 49 uiwindow0x7b742a60widthid 42 640 10x7b767980markerid 46 uiwindow0x7b742a60minxid 41 0 20x7b767710markerid 40 050x7b767980markerid 46 uiwindow0x7b742a60minyid 44 0 20x7b767840markerid 43 050x7b7679b0markerid 49 objectiveid 1 objective 0x7b84c960 750104308e05 250661612e05 750104308e07 25089407e08uibutton0x7b6299c0widthid 408 750223517e08 25089407e08uibutton0x7b661ad0widthid 385 750186265e07 25089407e08uibutton0x7b7780a0widthid 388 750104308e07 25013411e07uiview0x7b6547d0widthid 419 constraints nsautoresizingmasklayoutconstraint0x7b638350 h v uilayoutcontainerview0x7b6505a0height uiwindow0x7b742a60height marker0x7b638350markerid 135 nsautoresizingmasklayoutconstraint0x7b642e00 h v uilayoutcontainerview0x7b6505a0midx uiwindow0x7b742a60midx marker0x7b642e00markerid 130 nsautoresizingmasklayoutconstraint0x7b655400 h v uiviewcontrollerwrapperview0x7b77add0midx uinavigationtransitionview0x7b756bc0midx marker0x7b655400markerid 104 nsautoresizingmasklayoutconstraint0x7b655430 h v uiviewcontrollerwrapperview0x7b77add0width uinavigationtransitionview0x7b756bc0width marker0x7b655430markerid 108 nsautoresizingmasklayoutconstraint0x7b657350 h v uilayoutcontainerview0x7b6505a0midy uiwindow0x7b742a60midy marker0x7b657350markerid 134 nsautoresizingmasklayoutconstraint0x7b6584c0 h v uinavigationtransitionview0x7b756bc0midx uilayoutcontainerview0x7b6505a0midx marker0x7b6584c0markerid 112 nsautoresizingmasklayoutconstraint0x7b6592b0 h v uilayoutcontainerview0x7b6505a0width uiwindow0x7b742a60width marker0x7b6592b0markerid 131 nsautoresizingmasklayoutconstraint0x7b659c10 h v uiviewcontrollerwrapperview0x7b77add0midy uinavigationtransitionview0x7b756bc0midy marker0x7b659c10markerid 109 nsautoresizingmasklayoutconstraint0x7b659c40 h v uiviewcontrollerwrapperview0x7b77add0height uinavigationtransitionview0x7b756bc0height marker0x7b659c40markerid 1 nsautoresizingmasklayoutconstraint0x7b664cf0 h v uinavigationtransitionview0x7b756bc0width uilayoutcontainerview0x7b6505a0width marker0x7b664cf0markerid 116 nsautoresizingmasklayoutconstraint0x7b664d20 h v uinavigationtransitionview0x7b756bc0midy uilayoutcontainerview0x7b6505a0midy marker0x7b664d20markerid 117 nsautoresizingmasklayoutconstraint0x7b664d50 h v uinavigationtransitionview0x7b756bc0height uilayoutcontainerview0x7b6505a0height marker0x7b664d50markerid 119 nsautoresizingmasklayoutconstraint0x7b767980 h v huiwindow0x7b742a60320 marker0x7b767980markerid 46 nsautoresizingmasklayoutconstraint0x7b7679b0 h v vuiwindow0x7b742a60480 marker0x7b7679b0markerid 49 uiwindowanchoringconstraint0x7b767710 h v uiwindow0x7b742a60midx 160 marker0x7b767710markerid 40 uiwindowanchoringconstraint0x7b767840 h v uiwindow0x7b742a60midy 240 marker0x7b767840markerid 43 integralization adjustmentsnone statistics 16 rows variable counts 1 2 2 10 3 2 4 2 internal error cannot find an outgoing row head for incoming head uibutton0x7b7780a0widthid 388 which should never happen first throw call stack 0 corefoundation 0x03e051e4 exceptionpreprocess 180 1 libobjcadylib 0x03b848e5 objc exception throw 44 2 corefoundation 0x03e04fbb nsexception raiseformat 139 3 foundation 0x035b4079 nsisengine minimizeconstantinobjectiverowwithhead 256 4 foundation 0x035b3ee3 nsisengine optimize 183 5 foundation 0x037286d8 nsisengine withbehaviorsperformmodifications 183 6 foundation 0x035b83c5 nsisengine withautomaticoptimizationthisabled 48 7 uikit 0x02695830 uiviewhierarchy postmovedfromsuperview 313 8 uikit 0x026a0dd4 uiviewinternal addsubviewpositionedrelativeto 1875 9 uikit 0x02693c4f uiviewhierarchy insertsubviewatindex 64 10 uikit 0x02628089 53 uinavigationparallaxtransition animatetransition block invoke 1896 11 uikit 0x0269a81f uiviewanimation performwithoutanimation 82 12 uikit 0x026274f6 uinavigationparallaxtransition animatetransition 1155 13 uikit 0x0276e3ae uinavigationcontroller startcustomtransition 3446 14 uikit 0x0277a8f7 uinavigationcontroller startdeferredtransitionifneeded 688 15 uikit 0x0277b4e9 uinavigationcontroller viewwilayoutsubviews 57 16 uikit 0x028bc0d1 uilayoutcontainerview layoutsubviews 213 17 uikit 0x026a3964 uiviewcalayerdelegate layoutsublayersoflayer 355 18 libobjcadylib 0x03b9682b nsobject performselectorwithobject 70 19 quartzcore 0x0250845a calayer layoutsublayers 148 20 quartzcore 0x024fc244 zn2ca5layer16layout if neededepns 11transactione 380 21 quartzcore 0x024fc0b0 zn2ca5layer28layout and thisplay if neededepns 11transactione 26 22 quartzcore 0x024627fa zn2ca7context18commit transactionepns 11transactione 294 23 quartzcore 0x02463b85 zn2ca11transaction6commitev 393 24 quartzcore 0x02464258 zn2ca11transaction17observer callbackep19 cfrunloopobservermpv 92 25 corefoundation 0x03dcd36e cfrunloop is calling out to an observer callback function 30 26 corefoundation 0x03dcd2bf cfrunloopdoobservers 399 27 corefoundation 0x03dab254 cfrunlooprun 1076 28 corefoundation 0x03daa9d3 cfrunlooprunspecific 467 29 corefoundation 0x03daa7eb cfrunloopruninmode 123 30 graphicsservices 0x0585b5ee gseventrunmodal 192 31 graphicsservices 0x0585b42b gseventrun 104 32 uikit 0x02634f9b uiapplicationmain 1225 33 cookila copy 0x08a0fd main 141 34 libdylddylib 0x048276d9 start 1 35 0x01 0x0 1libcabidylib terminating with uncaught exception of type nsexceptionselfview recursivedescription ran before the crash on a breakpoint in viewwillappearuiview 0x7b67d660 frame 0 0 320 480 autoresize wh layer calayer 0x7b67d6c0 uiimageview 0x7b67cfb0 frame 0 0 320 568 opaque no autoresize rmbm userinteractionenabled no layer calayer 0x7b67d030 uibutton 0x7b674310 frame 160 515 75 30 opaque no autoresize rmbm tag 115 layer calayer 0x7b674400 uibutton 0x7b67ecf0 frame 235 515 75 30 opaque no autoresize rmbm tag 116 layer calayer 0x7b67ede0 uibutton 0x7b67ccd0 frame 85 515 75 30 opaque no autoresize rmbm tag 114 layer calayer 0x7b67cdc0 uibutton 0x7b6764c0 frame 10 455 75 60 opaque no autoresize rmbm tag 13 layer calayer 0x7b6765b0 uibutton 0x7b6745d0 frame 85 455 75 60 opaque no autoresize rmbm tag 14 layer calayer 0x7b6746c0 uibutton 0x7b67f1f0 frame 160 455 75 60 opaque no autoresize rmbm tag 15 layer calayer 0x7b67f2e0 uibutton 0x7b67c890 frame 10 515 75 30 opaque no autoresize rmbm tag 113 layer calayer 0x7b67f9c0 uibutton 0x7b672dc0 frame 235 455 75 60 opaque no autoresize rmbm tag 16 layer calayer 0x7b679950 uiview 0x7b67d520 frame 0 428 320 27 autoresize rmbm layer calayer 0x7b67d580 uibutton 0x7b67f430 frame 160 398 75 30 opaque no autoresize rmbm tag 1 layer calayer 0x7b67f520 uibutton 0x7b6733f0 frame 235 398 75 30 opaque no autoresize rmbm tag 112 layer calayer 0x7b67a9c0 uibutton 0x7b675850 frame 85 398 75 30 opaque no autoresize rmbm tag 110 layer calayer 0x7b675940 uibutton 0x7b656330 frame 10 338 75 60 opaque no autoresize rmbm tag 9 layer calayer 0x7b642d40 uibutton 0x7b6753a0 frame 85 338 75 60 opaque no autoresize rmbm tag 10 layer calayer 0x7b665bd0 uibutton 0x7b6737f0 frame 160 338 75 60 opaque no autoresize rmbm tag 11 layer calayer 0x7b6738e0 uibutton 0x7b6762e0 frame 10 398 75 30 opaque no autoresize rmbm tag 109 layer calayer 0x7b6763d0 uibutton 0x7b675ba0 frame 235 338 75 60 opaque no autoresize rmbm tag 12 layer calayer 0x7b673a20 uiview 0x7b67d3d0 frame 0 311 320 27 autoresize rmbm layer calayer 0x7b67d430 uibutton 0x7b675d50 frame 160 281 75 30 opaque no autoresize rmbm tag 107 layer calayer 0x7b675e40 uibutton 0x7b663970 frame 235 281 75 30 opaque no autoresize rmbm tag 108 layer calayer 0x7b663a60 uibutton 0x7b675580 frame 85 281 75 30 opaque no autoresize rmbm tag 106 layer calayer 0x7b675670 uibutton 0x7b665a00 frame 10 221 75 60 opaque no autoresize rmbm tag 5 layer calayer 0x7b663c40 uibutton 0x7b67ca90 frame 85 221 75 60 opaque no autoresize rmbm tag 6 layer calayer 0x7b67cb80 uibutton 0x7b674150 frame 160 221 75 60 opaque no autoresize rmbm tag 7 layer calayer 0x7b6564b0 uibutton 0x7b6734e0 frame 10 281 75 30 opaque no autoresize rmbm tag 105 layer calayer 0x7b6796e0 uibutton 0x7b67efb0 frame 235 221 75 60 opaque no autoresize rmbm tag 8 layer calayer 0x7b67f0a0 uibutton 0x7b67f700 frame 160 164 75 30 opaque no autoresize rmbm tag 103 layer calayer 0x7b67f7f0 uibutton 0x7b676020 frame 235 164 75 30 opaque no autoresize rmbm tag 104 layer calayer 0x7b676110 uibutton 0x7b676700 frame 85 164 75 30 opaque no autoresize rmbm tag 102 layer calayer 0x7b674ea0 uibutton 0x7b67eab0 frame 10 104 75 60 opaque no autoresize rmbm tag 1 layer calayer 0x7b67eba0 uibutton 0x7b674810 frame 85 104 75 60 opaque no autoresize rmbm tag 2 layer calayer 0x7b674900 uibutton 0x7b674a50 frame 10 164 75 30 opaque no autoresize rmbm tag 101 layer calayer 0x7b674b40 uibutton 0x7b642bd0 frame 235 104 75 60 opaque no autoresize rmbm tag 4 layer calayer 0x7b6752a0 uiview 0x7b67d1f0 frame 0 194 320 27 autoresize rmbm layer calayer 0x7b67d250 uibutton 0x7b675060 frame 160 104 75 60 opaque no autoresize rmbm tag 3 layer calayer 0x7b675150 uibutton 0x7b67b7f0 frame 258 20 46 30 opaque no autoresize rmbm layer calayer 0x7b672b90 uilayoutguide 0x7b67d790 frame 0 0 0 0 hidden yes layer calayer 0x7b67d800 uilayoutguide 0x7b67c0a0 frame 0 0 0 0 hidden yes layer calayer 0x7b67c110,['ios'] +863469,triangle shadow on css ribbon i am trying to replicate as pixel perfect as i can get and im having trouble trying to do the shadow on the right is this possible with csscssmargin0pxpadding0pxhtml width100 height100 textalign center bold fontweight700ribbon padding 34em 1em margin 0 margintop 5 positionrelative color 0 textalign center letterspacing01em paddingtop12px paddingbottom12px thisplay inlineblock background ffd82b zindex100 boxshadow 0 7px 0px 2px ebeced ribbonafter content width32em bottom5em positionabsolute thisplayblock border 9em solid ffd82b boxshadow 0 7px 0px 2px ebeced zindex2 ribbonafter right 43em borderleftwidth 75em borderrightcolortransparent contentafter content bottom5em positionabsolute thisplayblock borderstylesolid bordercolor fc9f42 transparent transparent transparent zindex1 contentbefore content top5em transform rotate90deg positionabsolute thisplayblock borderstylesolid bordercolor fc9f42 transparent transparent transparent zindex1contentbefore left 0 borderwidth 5em 0 0 5em contentafter right 0 borderwidth 5em 5em 0 0 htmldiv idribbon span idcontentspan classboldspecial offerspan recieve bonus rewards points for signing upspandivor heres a jsfiddle,"['html', 'css']" +863510,how to convert a pymongocursorcursor into a dict i am using pymongo to query for all items in a region actually it is to query for all venues in a region on a map i used dbcommandson before to search in a spherical region which can return me a dictionary and in the dictionary there is a key called results which contains the venues now i need to search in a square area and i am suggested to use dbplacesfind however this returns me a pymongocursorcursor class and i have no idea how to extract the venue results from it does anyone know whether i should convert the cursor into a dict and extract the results out or use another method to query for items in a square regionbtw db is pymongodatabasedatabase classthe codes are import pymongo db pymongomongoclienthostpsrc resp dbplacesfindloc within box ll lngll lat ur lngur lat for doc in resp printdoci have values of ll lng ll lat your lng and your lat use these values but it prints nothing from this codes,['python'] +863549,how properly inject httpcontext in mvc6 my data service layer in my api required information that are of the request in the httpcontext i read this question and they said that i should used the actioncontext instead of httpcontextcurrent thiscontinue in mvc6the first way is to set the data inside the controller by overriding this methodpublic void onactionexecutingactionexecutingcontext context var routedata contextroutedata var httpcontext contexthttpcontext or using di by injecting into the service layer public myserviceicontextaccessoractioncontext contextaccessor httpcontext contextaccessorvaluehttpcontext routedata contextaccessorvalueroutedatabut i am not sure with of the both line of code listed below is correct way to do the diservicesaddtransienticontextaccessoractioncontextcontextaccessorservicesaddtransienticontextaccessoractioncontextwhen i do this i get this errorunable to resolve service for type microsoftaspnetmvcactioncontext while attempting to activate updateprojectjson web projectdimultitenaninfrastructure dimultitenanmongoimplementation microsoftaspnetserveriis 100beta3microsoftaspnetmvc 600beta3microsoftaspnetstaticfiles 100beta3microsoftaspnetserverweblistener 100beta3,['c#'] +863595,chrome v41 performance issue with thisplay none on lots of nodes i have recently noticed chrome puking when applying thisplay none to lots of nodescodepen examplein the codepen above you can see the lag when toggling thisplay none on 10 elements if you bump the 10 to 30 and toggle it again the tab will hang completely the same code works without any lag in safari and i am 90 sure this was working fine in chrome until the last month or so so i am guessing this is a recent chrome bug has anyone else run into this and found a work around i have web app functionality that renders 30 elements hides them all with css and then shows them on demand with js currently the page would not even loadedit should have mentioned i am seeing this in chrome 410227276 and canary 43023180 this does appear to be a bug that appeared somewhere in chrome 41x and has been reportedbuttonhideonclickfunction divwraptoggleclasshidewraphide p thisplay nonebutton cursor pointerscript srcscriptbutton classhidetoggle thisplay nonebutton this just creates a div containing 10 p tags div classwrap p1p p2p p3p p4p p998p p9p p10pdiv,['css'] +863601,fake status bar color when navigation bar is hidden i am running into an issue with status bars navigation bars by default the navigation bar of uinavigationcontroller extends behind the status bar and colors it left screenshotwhen the search bar is used i hide the navigation bar this results in an uncolored status bar apples mail app does not have this issueis there any other solution than creating a separate uiview with a background color and placing it behind the status barheres what i would like to accomplish,['ios'] +863734,feature activity transitions vs feature content transitions i am having some trouble understanding the difference between these two window flags and am not 100 certain when each needs to be used and why the docs for windowfeature activity transitions sayenables activities to run activity transitions either through sending or receiving activityoptions bundle created with makescenetransitionanimationactivity pair or makescenetransitionanimationactivity view stringand the docs for windowfeature content transitions sayflag for requesting that window content changes should be animated using a transitionmanagerthe transitionmanager is set using settransitionmanagertransitionmanager if none is set a default transitionmanager will be usedthe documentation states that the following window methods require the feature activity transitions flag to be enabled but say nothing about whether or not the feature content transitions needs to be enabled as well note that according to the source code feature activity transitions is true and feature content transitions is false for materialthemed applications by defaultgetenterexitreturnreentertransitionsetenterexitreturnreentertransitiongetsharedelemententerexitreturnreentertransitionsetsharedelemententerexitreturnreentertransitiongettransitionbackgroundfadedurationsettransitionbackgroundfadedurationin other words it seems like based on this information feature activity transitions is the feature flag that applications will need to enable in order to use lollipops new activity transition apis what confuses me however is that this article from the android developers site states that enabling the feature content transitions is required in order to implement custom activity transitionsso here are my questionswhat is the difference between these two flags what is the difference between an activity transition and a content transition in this contextwhy is feature activity transitions enabled and feature content transitions thisabled by default when is enabling the feature content transitions flag actually requiredwould it ever make sense to sense to thisable feature activity transitions and enable feature content transitions or does feature content transitions require feature activity transitions to be enabled as wellthanks,['android'] +863755,reactjs how to make inline styles automatically update progress bar on state change i have a progress bar that i am building in reactjs and zurb foundation that i would like to reflect the current state i understand that in the beginning i can set the width with something like thisrender function var spanpercent thispropsa thispropsbthispropsa var spanstyle width spanpercent return div classnameprogress span classnamemeter stylespanstylespan div however when the value of props changes due to a state change the inline style does not update even though the props value changes is there a best practice for doing this such as using a callback or placing the code somewhere else i would appreciate any help,['javascript'] +863863,repeat password does not work in yii2 i have written rules in the model as public password repeat inheritdoc public function rules return password required password string min 6 password repeat compare compareattributepassword messagepasswords do not match if i use different password in password and password repeat field it gives error so that is mean it works but problem is that it does not give any error if password repeat field is empty,['php'] +863878,pip does not see setuptools i am migrating from python2 to python3i created a virtualenv with python3 m venv py3 and am trying to pip install r requirementstxt but it sayscollecting mock101 from r requirementstxt line 8 using cached mock101targz setuptools must be installed to install from a source thistributioni checked my virtualenv and it does have setuptoolspy3 1d3 1 ls py3libpython34sitepackages pycache easy installpy pip608thistinfo setuptools markerlib pip pkg resources setuptools1205thistinfobut when i still try to reinstall setuptools it sayspy3 1d3 1 pip install setuptoolsrequirement already satisfied use upgrade to upgrade setuptools in systemlibraryframeworkspythonframeworkversions27extraslibpythonso i have 2 questionswhy does not it see setuptools in virtualenv folder why does it look in python 2 folders instead of python 3thanks,['python'] +864035,chrome packaged app use angularjs in backgroundevent page as we create a chrome app we put scripts on the background property in the manifestjson file this will serve as the apps backgroundevent page what i want is i want to use angularjs on background script but i dont know how and also is it possible i just saw some answer but it is for chrome extensions i tried to use that solution in chrome app but it didnt workededitwhat i did was i changed some from manifestjson filefrom this app background scripts assetsjsbackgroundjs to thisapp background page viewsbackgroundhtml and my backgroundhtmlhtml ngappbackgroundmodule ngcsp head meta charsetutf8 titlebackground page point background property here to enable using of angular in backgroundjstitle head body javascript includes script srcassetsjsvendorangular12minjsscript script srcassetsbackgroundjsscript bodyhtmland my backgroundjsvar backgroundmodule angularmodulebackgroundmodule backgroundmodulerunfunctionrootscope http rootscopedomain httplocalhostldindexphp consolelogrootscopedomainbut still i got an error and it says resource interpreted as script but transferred with mime type texthtml chromeextensionpdknlhegnpbgmbejpgjodmigodolofoiviewsbackgroundhtml,['javascript'] +864040,is it possible to set a background color for the icon in the notification drawer on android if using parse push is it possibile to change the background color for the icon in the notification in the notification drawer on android if using parse pushi am talking about the background color for the circle you can take a look at from the image belowthanks in advanceadriano,['android'] +864155,autosuggestbox not showing results i am having trouble thisplaying the results in the autosuggestbox on windows phone 81 i am using mvvm light to bind my itemsource to the autosuggestboxautosuggestbox headervan textbinding searchtextfrom modetwoway itemssourcebinding suggestionfrom autosuggestboxitemtemplate datatemplate textblock textbinding description datatemplate autosuggestboxitemtemplate iinteractionbehaviors coreeventtriggerbehavior eventnametextchanged coreinvokecommandaction commandbinding searchchangedfrom coreinvokecommandaction coreeventtriggerbehavior iinteractionbehaviors autosuggestboxmy viewmodelprivate relaycommand searchchangedfrom public relaycommand searchchangedfrom get return searchchangedfrom searchchangedfrom new relaycommand async if stringisnullorwhitespaceusercountrycode debugwritelinecould not autocomplete the country because there was no country code provided return var predictions await servicegetgooglemapssuggestionfromqueryusercountrycode searchtextfrom suggestionfrom predictions private listprediction suggestionfrom public listprediction suggestionfrom get return suggestionfrom set setlistprediction suggestionfrom ref suggestionfrom value debugwritelinesuggestionfromcount were received thisplayong them in the autosuggestbox foreach prediction prediction in suggestionfrom debugwritelinepredicition predictiondescription the objects are set and are not nullso why do not they show upupdatemy model public class prediction observableobject private string description public string description get return description setsetstring description ref description value private string id public string id get return id set setstring id ref id value private listmatchedsubstring matchedsubstrings public listmatchedsubstring matched substrings get return matchedsubstrings setsetlistmatchedsubstring matched substrings ref matchedsubstrings value private string place id public string place id get return place id set setstring place id ref place id value private string reference public string reference get return reference set setstring reference ref reference value private listterm terms public listterm terms get return terms set setlistterm terms ref terms value private liststring types public liststring types get return types set setliststring types ref types value public override string tostring return thisdescription,['c#'] +864227,why my app is taking so much ram so i made a game app using bitmaps and surfaceview for a school project but the app itself is taking so much ram only when you start it it can get up to 60mb of ram and the more you play it the higher it gets at one point it got to 90mb of ram and the game was lagging horribly after watching google io 2011 cruqy55hok i relaized it might be a memory leak because the app starts like that and after playing 2 minutes it end up like that the app itself was made to look as simple as possible with 8bit graphics and not many colors all of the images i used weight only 400kb so why in the hell it takes so much ram i thought it might be the sounds but all the sounds together weight only 445mb of ram that is like 110 of the amount the app takes i understand bitmaps take a lot of ram but this is ridiculous this is my onload public gameviewcontext c todo autogenerated constructor stub superc thisc c bitmapfactoryoptions options new bitmapfactoryoptions optionsinjustdecodebounds true scoreparticlep new pointf newscoreparticlep new pointf int srcwidth optionsoutwidth int srcheight optionsoutheight itblocksiterator decode with insamplesize optionsinjustdecodebounds false optionsindither false optionsinscaled false optionsinpreferredconfig bitmapconfigargb 8 thissetkeepscreenontrue windowmanager wm windowmanager c getsystemservicecontextwindow service thisplay thisplay wmgetdefaultthisplay thisscreenw thisplaygetwidth thisscreenh thisplaygetheight thisdifferencew double screenw normalw thisdifferenceh double screenh normalh try mediaplayer mediaplayercreatec rrawnyan whilemediaplayer null mediaplayer mediaplayercreatec rrawnyan mediaplayersetloopingtrue ifmediaplayernull mediaplayerstart catchexception e try mediaplayer2 mediaplayercreatec rrawremix whilemediaplayer2null mediaplayer2 mediaplayercreatec rrawremix mediaplayer2setloopingtrue catchexception e try mediaplayer3 mediaplayercreatec rrawweed whilemediaplayer3null mediaplayer3 mediaplayercreatec rrawweed mediaplayer3setloopingtrue catchexception e sharedpreferences prefs2 cgetsharedpreferences spgamespiceinspace contextmode private counter2 prefs2getintscore 0 thissprite bitmapfactorydecoderesourcegetresources rdrawablesprite options thissprite bitmapcreatescaledbitmapsprite spritegetwidth 3 spritegetheight 3 false thisheart bitmapfactorydecoderesourcegetresources rdrawableheart thisexplosionheartbitmapfactorydecoderesourcegetresources rdrawableexplosionheart thisheart bitmapcreatescaledbitmapheart heartgetwidth 3 heartgetheight 3 false currentspeed new pointf0 0 currentdirection new point0 0 currentposition new point350 350 thisbackground bitmapfactorydecoderesourcegetresources rdrawablespace thisbackground2bitmapfactorydecoderesourcegetresources rdrawablespace2 thiselectricexplosion bitmapfactorydecoderesourcegetresources rdrawableeffect explosion thisnormalexplison bitmapfactorydecoderesourcegetresources rdrawableeffect explosion2 thisbackground bitmapcreatescaledbitmapbackground backgroundgetwidth 5 backgroundgetheight 5 false thisbackground2 bitmapcreatescaledbitmapbackground2 background2getwidth 5 background2getheight 5 false thislost bitmapfactorydecoderesourcegetresources rdrawablegameover thislostnew bitmapfactorydecoderesourcegetresources rdrawablegameovernew lostnew fitalldeviceslostnew lost fitalldeviceslost thisalien bitmapfactorydecoderesourcegetresources rdrawablemob alien thiscoin bitmapfactorydecoderesourcegetresources rdrawableitem coin partic bitmapfactorydecoderesourcegetresources rdrawableparticle star fire bitmapfactorydecoderesourcegetresources rdrawableparticle fire smoke bitmapfactorydecoderesourcegetresources rdrawableparticle smoke partic bitmapcreatescaledbitmappartic particgetwidth 2 particgetheight 2 false fire bitmapcreatescaledbitmapfire firegetwidth 2 firegetheight 2 false smoke bitmapcreatescaledbitmapsmoke smokegetwidth 2 smokegetheight 2 false electricexplosion bitmapcreatescaledbitmapelectricexplosion electricexplosiongetwidth 2 electricexplosiongetheight 2 false normalexplison bitmapcreatescaledbitmapnormalexplison normalexplisongetwidth 3 normalexplisongetheight 3 false thisalien bitmapcreatescaledbitmapalien aliengetwidth 3 aliengetheight 3 false asteroid bitmapfactorydecoderesourcegetresources rdrawablemob astroid bomb bitmapfactorydecoderesourcegetresources rdrawablemob spacebomb asteroid bitmapcreatescaledbitmapasteroid asteroidgetwidth 3 asteroidgetheight 3 false bomb bitmapcreatescaledbitmapbomb bombgetwidth 3 bombgetheight 3 false goldasteroid bitmapfactorydecoderesourcegetresources rdrawablemob goldastroid goldasteroid bitmapcreatescaledbitmapgoldasteroid goldasteroidgetwidth 3 goldasteroidgetheight 3 false mushroom bitmapfactorydecoderesourcegetresources rdrawableitem mushroom mushroom bitmapcreatescaledbitmapmushroom mushroomgetwidth 4 mushroomgetheight 4 false coin bitmapcreatescaledbitmapcoin coingetwidth 2 coingetheight 2 false drug bitmapfactory decoderesourcegetresources rdrawableitem not drug bitmapcreatescaledbitmapdrug druggetwidth 4 druggetheight 4 false rocket bitmapfactorydecoderesourcegetresources rdrawableitem rocket rocket bitmapcreatescaledbitmaprocket rocketgetwidth 4 rocketgetheight 4 false electricexplosion fitalldeviceselectricexplosion alien fitalldevicesalien normalexplison fitalldevicesnormalexplison explosionheart fitalldevicesexplosionheart mushroom fitalldevicesmushroom drug fitalldevicesdrug rocket fitalldevicesrocket bomb fitalldevicesbomb asteroid fitalldevicesasteroid goldasteroid fitalldevicesgoldasteroid sprite fitalldevicessprite heart fitalldevicesheart player new spicysprite heart hit soundpoolloadc rrawhit 1 pass soundpoolloadc rrawwin 1 remix soundpoolloadc rrawremix 1 destroy soundpoolloadc rrawdestroy 1 aliensound soundpoolloadc rrawalien 1 alienexpload soundpoolloadc rrawexplosion2 1 particlesound soundpoolloadc rrawparticle 1 bigexplosionsoundpoolloadc rrawexplosion 1 gameloopthread new gameloopthreadthis thisrequestfocus thissetfocusableintouchmodetrue holder getholder holderaddcallbacknew surfaceholdercallback override public void surfacedestroyedsurfaceholder holder boolean retry true gameloopthreadsetrunningfalse while retry try gameloopthreadjoin retry false catch interruptedexception e public void surfacecreatedsurfaceholder holder if gameloopthreadgetstatethreadstateterminated gameloopthread new gameloopthreadg gameloopthreadsetrunningtrue gameloopthreadstart override public void surfacechangedsurfaceholder holder int format int width int height am i doing something wrong my app is just a small game of bitmaps coming out of one side and going to the other side at first it starts slow but the more you play the more bitmaps are coming i would understand this amount of ram if there were many bitmaps on the screen but it takes 60mb when there is nothing but the player and the background on the screen i will be happy to email anyone the app to try and see for himself how simple it is yet how much ram it takes for no reason editi mentioned that the app is taking more ram over time i understand that it has to do with the fact i create new bitmaps and move them around and then remove them and the more you play the more bitmaps are created but i try my best to remove them right after and recycle them to make sure they are collected by the garbage collector i wonder how can i minimize the amount of usage and still make my game playablethis is how i spawn mobs mob gets the bitmap i loaded on onloadprivate void spawnmob if timer2 0 int mobtype randint1 40 switch mobtype case 1 case 2 case 3 case 4 case 5 case 6 case 7 case 8 case 9 case 10 case 11 case 12 case 13 case 14 case 15 mob m new mobalien mobeffectcomeback 1 point p new point0 0 py randint0 screenh aliengetheight px screenw aliengetwidth spawnedputp m break case 16 case 17 case 18 case 19 case 20 case 21 case 22 case 23 case 24 case 25 case 26 case 27 case 28 case 29 case 30 case 31 case 32 mob m2 new mobasteroid mobeffectthissapire 0 point p2 new point0 0 p2y randint0 screenh asteroidgetheight p2x screenw asteroidgetwidth spawnedputp2 m2 break case 33 case 34 case 35 case 36 case 37 case 38 case 39 mob m3 new mobgoldasteroid mobeffectthissapire 1 point p3 new point0 0 p3y randint0 screenh goldasteroidgetheight p3x screenw goldasteroidgetwidth spawnedputp3 m3 case 40 if counter 3 mob m4 new mobbomb mobeffectexpload 1 5 false false point p4 new point0 0 p4y randint0 screenh bombgetheight p4x screenw bombgetwidth spawnedputp4 m4 else mob m5 new mobasteroid mobeffectthissapire 0 point p5 new point0 0 p5y randint0 screenh asteroidgetheight p5x screenw asteroidgetwidth spawnedputp5 m5 break if rocketspeed 10 timer2 randint1 8 else if bleedoff 35 if bleedoff 1 timer2 randint35 int bleedoff 150 int bleedoff else timer2 randint35 150 else timer2 randint1 10 else timer2 and on ondraw i make sure to remove the mobs so they would not take extra memory when they are not on the screen iteratormapentrypoint mob spawnedentry spawned entrysetiterator while spawnedentryhasnext mapentrypoint mob entry spawnedentrynext ifentrygetvaluedestroycompleteentrygetvaluethissapired spawnedentryremove else entrygetvaluedrawcanvas entrygetkeyalso on mob classifmobeffectstarted ifdestroycomplete cdrawbitmapmobpxpy null else mobrecycleedit 2this is what the memory tool of eclipse tells meit is definatly the bitmaps,"['java', 'android']" +864322,why does the compiler not optimize this initialization consider the following c codeextern void fooint ipvoid myfuncvoid int arr15 0 for int i0 i10 i arri 42 fooarri tried with gcc and clang with o3 and os in all cases the compiled assembly writes all 15 zeroes before overwriting 10 of them with 42 i suppose it could just be that no optimization has been written for this case yet but it seems like a fairly obvious and common case to me is there something that prevents the optimizationi am on x8632 linux and used these commandsgcc stdc99 s o3 hellocclang stdc99 s o3 helloc,['c'] +864406,best practices to use realm with a recycler view do you guys have any best practices regarding using realm with a recyclerview i know it is generic question but i found nothing on it on the internet for example i run into a lot of troubles trying to implement a simple color change on a row for example consider this typical usagepublic class user extends realmobject primarykey string name boolean isselected constructor getter and setters public class useradapter extends recyclerviewadapterrecyclerviewviewholder private realmresultsuser users public useradapterrealmresultsuser users thisusers users public void markasselectedint position get the old selected user and deselect it notifyitemchanged how do i get the position given my user has no index mark as selected the new user at position i ran into a lot of issues since i could not find anything on the internet i know this is because i do not know how to properly use realm but finding the right way is a struggle in itself i read all their documentation but to no avail edit since i was asked to instead of saying i have a bunch of issues with that describe your issues and well try to provide insights and answers to your incomprehensionsso my problem is simple i have a realmuser public class realmuser extends realmobject primarykey private string key private string name private boolean isselected private boolean editmode private realmlistrealmitemlist lists public realmuser public realmuserstring name realmlistrealmitemlist lists boolean isselected boolean editmode thiskey uuidrandomuuidtostring thisname name thisisselected isselected thiseditmode editmode if lists null thislists new realmlistrealmitemlist else thislists lists public string getkey return key public void setkeystring key thiskey key public string getname return name public void setnamestring name thisname name public boolean isselected return isselected public void setselectedboolean isselected thisisselected isselected public boolean iseditmode return editmode public void seteditmodeboolean editmode thiseditmode editmode public realmlistrealmitemlist getlists return lists public void setlistsrealmlistrealmitemlist lists thislists lists wich i put in a realmresults array using realmresults users realmwhererealmuserclassfindalli pass my user array to my custom user adapter public class useradapter extends recyclerviewadapterrecyclerviewviewholder private realmresultsrealmuser users public useradapterrealmresultsrealmuser users thisusers users override public recyclerviewviewholder oncreateviewholderviewgroup parent int viewtype layoutinflater inflater layoutinflaterfromparentgetcontext ifviewtype 1 view v inflaterinflaterlayoutdetail user parent false return new userholderv else ifviewtype 2 view v inflaterinflaterlayoutedit user parent false return new edituserholderv else return null override public void onbindviewholderrecyclerviewviewholder holder int position realmuser user usersgetposition string username usergetname boolean isselected userisselected if holder instanceof userholder userholder uholder userholder holder uholderusertextsettextusername if isselected uholderusercontainersetbackgroundcolorcolorparsecolor607d8b else ifholder instanceof edituserholder edituserholder euserholder edituserholder holder euserholderusereditcontainersetbackgroundcolorcolorparsecolore override public int getitemviewtypeint position realmuser user usersgetposition if useriseditmode return 2 else return 1 override public int getitemcount return userssize public void markasselectedint position drawerlayout mdrawerlayout toolbar toolbar realm realm here is my problem how do i get the already selected user asuming there is one in my db and notify the ui that i changed that item that has a custom click listener that gets reciclerview item that was clicked using public class userclicklistener implements recyclerviewonitemtouchlistener public static interface onitemclicklistener public void onitemclickview v int position private onitemclicklistener mlistener private gesturedetector mgesturedetector public userclicklistenercontext context final recyclerview recyclerview onitemclicklistener listener mlistener listener mgesturedetector new gesturedetectorcontext new gesturedetectorsimpleongesturelistener override public boolean onsingletapconfirmedmotionevent e view childview recyclerviewfindchildviewunderegetx egety ifchildview null mlistener null mlisteneronitemclickchildview recyclerviewgetchildpositionchildview return true return false override public boolean onintercepttoucheventrecyclerview view motionevent e view childview viewfindchildviewunderegetx egety ifchildview null mlistener null mgesturedetectorontouchevente mlisteneronitemclickchildview viewgetchildpositionchildview return false override public void ontoucheventrecyclerview rv motionevent e wich i add to my reciclerview with addonitemtouchlistener mlistrecycleraddonitemtouchlistenernew userclicklistenergetactivity mlistrecycler new userclicklisteneronitemclicklistener override public void onitemclickview view int position useradapter myadapter useradapter mlistrecyclergetadapter myadaptermarkasselectedposition mdrawerlayout mtoolbar realm,['android'] +864416,questions about viper clean architecture i have been reading about clean architecture from robert martin and more specifically about viperthen i ran into this articlepost brigadeas experience using an mvc alternative which describes pretty much what i am currently doingafter actually trying to implement viper on a new ios project i have ran into some questionsis it ok for the presenter to query information in the view or should the information passing always start from the viewfor example if the view triggered some action in the presenter but then depending on the parameters passed through that action the presenter might need more informationwhat i mean is the user tapped adonewithstatea if state asomethinga get information from the view to create an entity if state asomething elsea animate something in the view how should i handle this kind of scenariolets say a module group of viper components decide to present another module modally who should be responsible for deciding if the second module will be presented modally the first modules wireframe or the second modules wireframealso lets say the second modules view is pushed into a navigation controller how should the back action be handled should i manually set a back button with an action in the second modules view controller that calls the presenter that calls the second modules wireframe that thismiss and tells the first modules wireframe that it was thismissed so that the first modules view controller might want to thisplay somethingshould the different modules talk only through the wireframe or also via delegates between presenters for example if the app navigated to a different module but after that the user pressed cancel or save and that choice needs to go back and change something in the first module maybe thisplay an animation that it was saved or remove somethinglets say a pin was selected on a map than the pineditviewcontroller is thisplayed when going back the selected pins color might need to change depending on use actions on the pineditviewcontroller who should keep the state of the current selected pin the mapviewcontroller the mappresenter or the mapwireframe in order for me to know when going back which pin should change color,['ios'] +864456,use of unresolved identifier in swift so i have been making an app and everything has been working great but today i made a new class like usual and for some reason in this class i cannot access publicglobal variable from other classes all the other classes can but now when ever i try to make a new class i cannot how would this be fixedi am using swift and xcode 6working classimport uikitimport foundationimport parseimport coredatavar signedin trueclass viewcontroller uiviewcontroller new classimport uikitclass newclass uiviewcontroller override func viewdidload superviewdidload signedin falsebut on signedin falsei get use of unresolved identifier signedin,['ios'] +864551,swift uitableview custom cell programatically documentation i have been trying to find some documentationtutorialexamples on how to do an advanced tableview in swift but i have come up empty besides the endless storyboard tutorialsi am doing this without storyboards and nibs and i havnt been able to find any documentation beyonds apples poorly explained libraryrather than trying to explain exactly what i am looking for i will simply show an image of the design belowright now i am obviously not asking you guys to create this for me i am simply hoping you can send me a link to some documentationtutorial that explains how to make cells different and how you position elements within a cell programaticallyi have been searching for cell constraints but i cannot find anyi looked into prototype cells too but all i could find was storyboard relatedi am hoping you guys could show me an example of something similar some documentation tutorialanother important thing any documentation i did find that was not using storyboards all used a tableviewcontrolleri am using a uiviewcontroller with a uitableview not a tableviewcontroller which seems to make a huge difference on how it worksright now i am just trying to get a prototype workingheres my data belowvar objects nsmutablearrayvar dataarray stocknamectc media incactionsellstockprice1244 stocknametransglobal energyactionbuystockprice3940 stocknamenu skin enterprisesactionbuystockprice418 i have only been able to grab and thisplay one piece of data from it though func tableviewtableview uitableview numberofrowsinsection section int int return selfstockscount return dataarraycountfunc tableviewtableview uitableview cellforrowatindexpath indexpath nsindexpath uitableviewcell let cell tableviewdequeuereusablecellwithidentifiercell forindexpath indexpath as uitableviewcell let object dataarrayindexpathrow as nsdictionary celltextlabeltext objectstockname as string return cellfunc tableviewtableview uitableview didselectrowatindexpath indexpath nsindexpath printlnyou selected cell indexpathrowbut i am still clueless on how i position this data or add more to it such as the uiview on the right with a specific background color centering a uilabel within that uiview adding a uiview on the left with padding custom spacing between cells etc etc any help links to documentation suggestions would be greatly appreciatedediti tried adding constraints inside the cell with cellviewaddconstraintsbut of course it throws an error saying uitableviewcell does not have a member named viewso as for how to do constraints inside cells i am still blank edit 2 progressi managed to get a uiview to show up using the following code testviewsettranslatesautoresizingmaskintoconstraintsfalse testviewbackgroundcolor uicolorredcolor celladdsubviewtestview var viewsdictionary testviewtestview celladdconstraints nslayoutconstraintconstraintswithvisualformat h50testview options nil metrics nil views viewsdictionary celladdconstraints nslayoutconstraintconstraintswithvisualformat vtestview options nil metrics nil views viewsdictionaryhowever for some reason it only shows up in the last cell not all cells,['ios'] +864575,ipython notebook 3 thisables seaborn settings i just upgraded to ipython notebook version 30 and it is thisabling the formatting for seaborn heres some sample code that replicates the problemimport numpy as npimport matplotlib as mplimport matplotlibpyplot as pltimport seaborn as snsmatplotlib inlinedata nprandomrandn100figax pltsubplotsfigsize 1185axplotdatathis code works just fine in ipython notebook v241 see but in ipython notebook v30 the axes become invisible see strangely in v3 when i switch the order of the seaborn import and the matplotlib inline magic the plot renders normally the first time i run then if i rerun the axes and gridlines thisappear so it seems to have something to do with the inline magic thisabling seaborn propertiesany workarounds other than not reexecuting my imports after the first time,['python'] +864610,vectordrawable android loads xhdpi pngs instead of the vector resource i am trying to use a vectordrawable on api21 but android loads the png resource from xxhdpi folder insteadmy current res structure as followsresdrawablexxhdpitest iconpngdrawable21test iconxmland my xml layoutimageview androidlayout widthwrap content androidlayout heightwrap content androidsrcdrawabletest iconare there any other ways to solve this from my understanding android will always pick the png resource but if that is the case how one can use vectordrawables for api21 and png for lower apisupdate 1if we use a drawablexxhdpi21 resource folder android will pick the vector instead of the png resource but that means we would have to have a copy or symlink of the file for other densities as well eg xhdpi hdpi etc,['android'] +864620,starting an activity from a system overlay window after pressing home button i have a system overlay window a floating view like facebooks chat headwhen user presses the window an activity will be started to show the contentthe problem is that if the user leave my app by pressing home button then the activity cannot be started within 5 seconds due to system restriction the activity shows up after 5 secondsi did not find any solution on previous so questions however there is an app link bubble which overcomes this problem when user presses the floating bubble view an activity can always popup immediatelydoes anyone know how to make thisthis is layoutparams of my system overlay windowwindowparams new windowmanagerlayoutparams width height windowmanagerlayoutparamstype system alert windowmanagerlayoutparamsflag hardware accelerated windowmanagerlayoutparamsflag not focusable windowmanagerlayoutparamsflag layout no limits pixelformattranslucentwindowparamsgravity gravitytop gravityleftwindowparamsx 0windowparamsy 0i got windowmanager withwindowmanager windowmanager getapplicationcontextgetsystemservicewindow serviceand add the floating view withwindowmanageraddviewmy view windowparamswhere my view has an ontouchlistener that starts an activity after user pressed it,['android'] +864774,prevent backspace from navigating back in angularjs i faced this issue in my angularjs webappwhen a user enters a page with a form to fill and he starts typing if he presses the backspace key and the focus is not on the input text then the page goes to the previous statei looked up this solution using jquery but it does not seem the appropiate way for achieve this in angularjs,"['javascript', 'jquery']" +864779,how to handle a lot of different view types in recyclerview viewholder what if i have 50 types of views should i have 50 static inner classes in my adapteraccording to this answer yesmy first thought was to move each viewholder inner class into a seperate public class but they have to be static so encapsulate each one into a public class to make the inner class static are there any nicer alternativeseditcode sampleso this would be a good solution does not this also kill performancepublic class mainviewholder extends dragsortadapterviewholder implements viewonclicklistener viewonlongclicklistener view containertextview titlecalled in oncreateviewholder in adapterpublic mainviewholderdragsortadapter adapter view itemview superadapter itemview container itemviewfindviewbyidridcard root title containerfindviewbyidridtextcalled by onbindviewholder in adapterpublic void setdatadata data titlesettextdatatitleedit2sample for when a new instance is returned of the viewholderoverridepublic recyclerviewviewholder oncreateviewholderviewgroup parent int viewtype switch viewtype case 0 return new mainviewholder case 2 return new mainviewholderother,['android'] +864808,fingerprint api for android phone i am new to fingerprint authentication in smartphones as we know samsung s5 currently supports fingerprint scanner is it possible to develop a custom application that can use the scanner to authenticate a user i just need to know the identity of the user and if he has been authenticated correctly my app can then take it from there and integrate with backend,['android'] +864866,prestashop backoffice works but the frontoffice does not the url is not found i have developed a multilanguage prestashop store completely in localhost using xampp in mac and it works both the backoffice and the store frontoffice after that i have deployed it to amazon but there comes my problem the backoffice works but the store does not the browser just thisplays an apache 404 page and tells me the requested url domainprestashopen was not found on this server but it does exist besides the backoffice confirms itinspecting the errorlog i find the following messagethu mar 12 1237 2015 error client x file does not exist varwprestashopenfor what i see apache is treating the language en as file when it is not i have searched all across the web and i cannot find how to fix it i know it is a server issue but somehow cannot find the solutionwhats the matter here edit i fixed the issue doing the following stepsdeleted the root htaccesscleared the smarty cache files under cachesmartycompileload the mod rewrite module that was not installed a2enmod rewriteadded the allowoverride all directive to etcapache2apache2confdirectory varwprestashop options indexes followsymlinks allowoverride alldirectoryrestarted apache2 service apache2 restart,['php'] +864928,initialization order of final fields consider these two classespublic abstract class bar protected bar systemoutprintlngetvalue protected abstract int getvaluepublic class foo extends bar private final int i 20 public foo override protected int getvalue return i public static void mainstring args new foo if i execute foo the output is 20if i make the field nonfinal or if i initialize it in the foo constructor the output is 0my question is what is the initialization order in case of final fields and where is this behavior described in the jlsi expected to find some exceptional rule about final fields here but unless i miss something there is notnote that i know i should never call an overridable method from a constructor that is not the point of the question,['java'] +864993,angularjs di with es6 classes and inheritance background current implementation of classesmodules in our app is commonjs and coffeescript classes i am desperately looking for a solution to work with es6 or typescript but the problem remainshow to do di with class inheritance using angular1xgiven the code superservicejsclass superservice constructorhttp q etc implementation is not important export subservice subservicejsimport superservice from superserviceclass subservice extends superservice constructormore di things here implementation is not important problem exists here superwe need all the super class di things every time we inherit from it export subservice must one in the subservice here redefine all the parent di requirements in order to successfully call superwere presently doing something akin to the following coffeescript javascriptappfactory subservice service appfactorysubservice functionservice subservice var subservice servicecall subservice function servicecallthis return this overwrite some stuff on the service servicebasepath environments serviceprototypebasepath environments servicemodel environment serviceprototypemodel environment return new subservice new subservice which is also less than ideal aside from being ugly,['javascript'] +864995,entity framework return list from stored procedure i am trying to return a list of int from a stored procedure in entity frameworki created the stored procedure fine and added it into entity framework i am trying to bind it to a complex type of but when i open the function import it auto generates a complex type that only returns an int instead of a results setdoes anyone know how i can import an entity that returns a list as a result set,['c#'] +865107,aspnet vnext core clr missing typeisprimitive i am trying to migrate a web app to aspnet vnext with the eventual aim of getting it running on linuxthe app has a lot of reflection code and i must be missing some dependencies as i am getting compile errors on code such as thistypeisprimitive typegetconstructor typegetmethod typegettypearray error cs1061 type does not contain a definition for isprimitive and no extension method isprimitive accepting a first argument of type type could be found are you missing a using directive or an assembly referenceerror cs1061 type does not contain a definition for getmethod and no extension method getmethod accepting a first argument of type type could be found are you missing a using directive or an assembly reference error cs1061 type does not contain a definition for getproperties and no extension method getproperties accepting a first argument of type type could be found are you missing a using directive or an assembly referenceerror cs1061 type does not contain a definition for getinterface and no extension method getinterface accepting a first argument of type type could be found are you missing a using directive or an assembly referencei have the following dependencies in my projectjson filesframeworks aspnetcore50 dependencies systemruntime 4020beta22416 systemlinq 40beta22605 systemreflection 40100beta22605 systemreflectionprimitives 40beta22605 systemruntimeextensions 40100beta22605 systemreflectionextensions 40beta22605 the following compiles fine under vs 2013 and net 45 but wont compile in vs 2015 using the dependencies aboveusing systemusing systemreflectionnamespace project1 public class class1 public class1 type lbasearraytype typeofarray type lstringtype typeofstring string lstringarray new string1 if lstringtypeisprimitive constructorinfo lconstructor lstringtypegetconstructornew type0 methodinfo lmethod lstringtypegetmethodequals type ltarray typegettypearraylstringarray propertyinfo lprops lstringtypegetproperties,['asp.net'] +865147,shimming a package with webpack there is a javascript file that i need to use in my project as a dependency it does not have a github repository it is not on bower or npm it just lives herei can install it with bower withbower install savei know that it will then live in my project atbower componentslearnmarkletindexjsand i know it attaches a variable called learnq to the global window objectwhat i want is simply thisvar learnq requireklaviyoi need to alias klaviyo something like this klaviyo bower componentslearnmarkletindexjsand shim an export of the learnq variable like this klaviyo learnqhow can i do this with webpackthis is what i have tried this is what my webpackconfigjs looks likemoduleexports resolve alias klaviyo bower componentslearnmarkletindexjs externals klaviyo learnq,['javascript'] +865366,how can i allow background music to continue playing while my app still plays its sounds while using swift i created an app and i am attempting to allow the user to continue to listen to their music while playing my game but whenever they hit play and the ingame sounds occur it will stop the background music i am developing on ios using swift here is a piece of the code that initiates the ingame soundsfunc playspawneddot var alertsound nsurl nsurlfileurlwithpath nsbundlemainbundlepathforresourcespawndot oftype mp3 var errornserror audioplayer avaudioplayercontentsofurl alertsound error error audioplayerpreparetoplay if volumebool audioplayerplay,['ios'] +865466,getting cannot read property offsetwidth of undefined with bootstrap carousel script i created a carousel with bootstrap 33 and it works on my local machine but when i upload the whole thing on server where the bootstrap js file is being compiled together with other files in a single file i get this errorcannot read property offsetwidth of undefined has anybody faced this and are there any known solutions to this issue,"['javascript', 'jquery']" +865504,why cannot i map integers to strings when streaming from an array this code works taken in the javadoclistinteger numbers arraysaslist1 2 3 4string commaseparatednumbers numbersstream mapi itostring collectcollectorsjoining this one cannot be compiledint numbers 1 2 3 4string commaseparatednumbers arraysstreamnumbers mapinteger i itostring collectcollectorsjoining idea tells me i have an incompatible return type string in lambda expressionwhy and how to fix that,['java'] +865594,initializer does not override a designated initializer from its superclass so i have just upgraded to xcode 63 beta 3 and a lot of errors are appearing relating to the followinginitializer does not override a designated initializer from its superclassoverride init superinitfor example this is a uibutton classclass custombutton uibutton var target anyobject var selector selector var action void override init initializer does not override a designated initializer from its superclass superinit must call a designated initializer of the superclass uibutton required initcoder adecoder nscoder superinitcoder adecoder override initframe cgrect superinitframe frame this is one of my uiviewcontroller classesclass customalertview uiviewcontroller required initcoder adecoder nscoder fatalerrornscoding not supported required override init initializer does not override a designated initializer from its superclass superinit must call a designated initializer of the superclass uiviewcontroller override initnibname nibnameornil string bundle nibbundleornil nsbundle superinitnibname nibnameornil bundle nibbundleornil,['ios'] +865677,noclassdeffounderror below sdk 21 i just experienced an awkward bug in my appon my nexus 57 running android 501502 everything works just finehowever if i try running the exact same code on a device with an earlier version tested 4 and 43 i get the following error0313 134941140 2171421714 edalvikvmi1 could not find class comdefaultpackageapplicationmodelappcomponent referenced from method comdefaultpackageapplicationcontrollerdatabasehandlergetscreencomponents0313 134941140 2171421714 edalvikvmi1 could not find class androidsupportv7appactionbaractivitydelegate1 referenced from method androidsupportv7appactionbaractivitydelegateinit0313 134941140 2171421714 edalvikvmi1 could not find class androidsupportv7appactionbaractivitydelegatehc referenced from method androidsupportv7appactionbaractivitydelegatecreatedelegate0313 134941140 2171421714 edalvikvmi1 could not find class androidsupportv7appactionbaractivitydelegatebase referenced from method androidsupportv7appactionbaractivitydelegatecreatedelegate0313 134941150 2171421714 edalvikvmi1 could not find class androidsupportv7appactionbaractivitydelegateactionbardrawabletoggleimpl referenced from method androidsupportv7appactionbaractivitydelegategetdrawertoggledelegate0313 134941150 2171421714 edalvikvmi1 could not find class androidsupportv7internalviewsupportmenuinflater referenced from method androidsupportv7appactionbaractivitydelegategetmenuinflater0313 134941150 2171421714 edalvikvmi1 could not find class androidsupportv7appactionbaractivitydelegateactionbardrawabletoggleimpl referenced from method androidsupportv7appactionbaractivitydelegategetv7drawertoggledelegate0313 134941150 2171421714 eandroidruntimei1 fatal exception main process comdefaultpackage pid 21714 javalangnoclassdeffounderror androidsupportv7appactionbaractivitydelegatehci have already tried adding the supportv7 library as jar but makes no differencebut since it works on lollipop devices this wouldnt make sense anywaycould it be that there is some issue concerning the dalvikart changeor maybe the fact that i had to use comandroidsupportmultidex100 since it is a rather large appupdate i tried removing some dependencies to get under the 65k method limit after that the app ran on 4 and 43 devices all i did for enabling multidex support was settingmultidexenabled truein the defaultconfig section and adding compile comandroidsupportmultidex100below in the dependencies section of my buildgradleany idea why this causes these issues on the older android versions,['android'] +865798,roman to integer but using a different roman number system i had an interview in which i did terribly so now i am trying to find the solution to the question here is the interview question we have the following mappingm 10 d 500 c 100 l 50 x 10 v 5 i 1and we have the following ruleseach letter maps to a positive integer valueyou add the values together exceptwhen a value or runs of the same values is followed by a greater value you subtract the total of that run of valuesexamplesiix 8mccmiix 1808we are given this java method int valueofromanchar romanwe have implement the java method int romantointstring si know it is not a proper roman number system but that is the actual questioni was able to code a working solution to a proper roman system but i am unable to change it so that it adapts to these new rules particularly rule 3 i have tried but with no success the way my solution is right now for iix it prints 10 instead of the correct answer of 8 here is my code i also implemented valueof for my testingstatic int romantointstring s char curr int currval char prev int prevval int total valueofromanscharat0 for int i 1 i slength i curr scharati currval valueofromancurr prev scharati1 prevval valueofromanprev total currval ifcurrval prevval total total 2prevval return totalstatic int valueofromanchar c if c m return 10 else if c d return 500 else if c c return 100 else if c l return 50 else if c x return 10 else if c v return 5 else if c i return 1 return 1any help is really appreciated specially useful would be if you can tell me how to modify my code thanksedit i edited the names of the methods so they are clearer,['java'] +865894,how to call a cpu instruction from c my processor intel i7 supports the popcnt instruction and i would like to call it from my c application is this possiblei believe i read somewhere that it is not but the jit will invoke it if it finds it available but what function would i have to call that may be substituted with such an instructionpopcount is being called millions of times in a loop so i would like to be able to have this cpu optimization if possible,['c#'] +866052,attributed text center alignment i have tried everything but cannot seem to center this text can someone please tell me where the error isnsmutableparagraphstyle paragraphstyle nsmutableparagraphstylenew paragraphstylealignment nstextalignmentcenter labelattributedtextnsattributedstring alloc initwithstringcelleventtitletext attributesnsforegroundcolorattributename uicolor whitecolornsparagraphstyleattributenameparagraphstylensbaselineoffsetattributename 0nsfontattributename uifont fontwithnamebrandongrotesqueblack size34nsparagraphstyleattributenameparagraphstyle,['ios'] +866091,bowerjson main is present but i get a is missing main entry in bowerjson warning i am trying to register this jquery plugin to bowerthe bowerjson file looks like this name domajax version 210 homepage description domajax is a free jquery plugin that give you tools to add ajax calls within your application without a piece of javascript main jsjquerydomajaxjs keywords domajax ajax jquery plugin javascript dom html authors alain tiemblo repository type git url gitgithubcomninsuodomajaxgit bugs license mit ignore jsjquerydomajaxjs dependencies jquery 17 jqueryui json2js you can see that both main and ignore entries are set but i get the following warnings when i register the plugin to bowerbower domajax invalidmeta domajax is missing main entry in bowerjsonbower domajax invalidmeta domajax is missing ignore entry in bowerjsonwhy those entries are marked as missing on my bowerjson filefyi here is the full outputninsuodomajax alain bower register domajax bower convert converted to gitgithubcomninsuodomajaxgitbower domajax resolve gitgithubcomninsuodomajaxgitbower domajax download bower domajax extract archivetargzbower domajax invalidmeta domajax is missing main entry in bowerjsonbower domajax invalidmeta domajax is missing ignore entry in bowerjsonbower domajax resolved gitgithubcomninsuodomajaxgit210 registering a package will make it installable via the registry continue no,['jquery'] +866119,htmlcheckboxfor generates clientside validation attributes while htmlcheckbox does not let us say i have this modelpublic class person public bool isapproved get set and whis this codes i am trying to render input with check typehtmlcheckboxforx xisapprovedhtmlcheckboxisapprovedbut the results are different checkboxfor resultinput datavaltrue datavalrequiredthe isapproved field is required idisapproved nameisapproved typecheckbox valuetrueinput nameisapproved typehidden valuefalse checkbox resultinput idisapproved nameisapproved typecheckbox valuetrueinput nameisapproved typehidden valuefalsehow and why the first one generates attributes for clientside validation while the other did not update after swapping the order of htmlcheckboxfor and htmlcheckbox the order of markup elements did not change,['c#'] +866212,run mocha programatically and pass results to variable or function i have setup a suite of tests in mocha using zombiejs and chai the tests load up a website and check if various services are booked in correctly and are thisplaying to visitors of the websitewhat i am aiming for is that the tests will run daily and then email the results to my team the tests are all running as expected but the blockage i have hit is the followinghow do i pass the json reporter results to another nodejs script where i can email the results building the email and sending it is going to be straight forward using nodemailer and underscore templatingmy current thinking is there are two approaches run the mocha test with a shell script and pipe the json output to a node script and process the json from a command line argument something likemocha testserviceshomepagejs node emailjsthe other alternative is to run the tests from within a node script and get the returned result in a variable i have been using information from here to run the tests within nodethis runs correctly but i am lost with how to get the json reporter results into a variable from the below codevar mocha requiremocha suite mochasuite runner mocharunner test mochatest first you need to instantiate a mocha instancevar mocha new mocha reporter jsonvar suite new suitejson suite rootvar runner new runnersuitevar mochareporter new mocha reporterrunnermochaaddfile usersdominicgittestingrigtestserviceshomepagejsrunnerrunfunctionfailures the json reporter gets a testresults json object on end var testresults mochareportertestresults consolelogtestresults send your email hereif anyone has some guidance about the best way to approach this or if i am going in the completely wrong direction with this i would appreciate any suggestions,['javascript'] +866219,checkstyle eclipse plugin error cannot initialize module treewalker token wildcard type i have a problem with eclipse checkstyle plugin i just installed this one and when i execute checkstyleconfiguration with sun checkstyleeclipse on java file i have this errorcannot initialize module treewalker token wildcard type was not found in acceptable tokens list in check compuppycrawltoolscheckstylecheckswhitespacewhitespacearoundcheck2261fbd cannot initialize module treewalker token wildcard type was not found in acceptable tokens list in check compuppycrawltoolscheckstylecheckswhitespacewhitespacearoundcheck2261fbdbut when i use checkstyle configuration sun checks or google checks it is worksdo you have a solution thanks neyoh,['java'] +866286,role based authentication in hapijs i am working on a rest api first project written with hapijs after the login process the user gets a token to pass in the header of every requestusers have different roles admin standard guest partners and some api endpoint are reachable only by users with a certain rolesomeone could help me in defining this check in a nice way so without writing the check everytime inside the route,['javascript'] +866423,is visual studio 2013 optimizing correctly in the presence of opticf i expect the following program to return 0 all of the time however with visual studio 2013 update 4 the program exits 1 in release builds i am not sure if this is a bug or if the compilers optimizer is correct and is relying on some edge behavior if the const macro is turned off the release exe returns 0 if the optimizer is indeed correct could i get the reason why it is allowed to emit the code it doesif 1 define const constelse define constendifclass typeid public bool operator typeid const other const return id otherid private typeid void const id idid public template typename t static typeid get static char const uniquememloc 0 return typeiduniquememloc private void const idint mainint char typedef int a typedef unsigned int b if typeidgeta typeidgetb return 1 return 0,['c++'] +866549,polymorphism in c calling an overridden method first i am java coder and want to understand polymorphism in c i wrote the example for learning purposesincludeiostreamusing namespace stdclass apublic virtual void foo stdcout foo stdendl class b public apublic void foo stdcout overriden foo stdendl a c b int main cfoo prints foo not overriden fooi expected that overriden foo would be printed but it was not why we overrode the method foo in the class b and i thought that the decision which method should be called is being making from the runtime type of the object which in my case is b but not a static type a in my caselive example is there,['c++'] +866593,how to thisable recyclerview item decoration drawing for the duration of item animations i have some basic item decoration which draws some stuff in itemdecorationondrawover methodthis recyclerview also has defaultitemanimator set on itanimations are working all is great except one thingwhen all existing items are swapped with a new item set in this adapter the decorations are being shown while animation is running i need a way to hide themwhen animation finishes they need to be shown but while it is running they must be hiddeni tried the followingpublic void ondrawover recyclerviewstate state ifstatewillrunpredictiveanimations statewillrunsimpleanimations return else do drawing stuff herebut this is not helping decoration is only removed for the short period of animation but then appears again while it is still runningalso setup includes a recyclerviewadapter which hasstableids in case that bit matters,['android'] +866642,middleware how to redirect after check laravel 5 i need after check if user is logged as editor to redirect to profile pagehere is my codephp namespace apphttpmiddlewareuse illuminatesupportfacadesauthuse illuminatesupportfacadesredirectuse closureclass adminmiddleware handle an incoming request param illuminatehttprequest request param closure next return mixed public function handlerequest closure next ifauthcheck ifauthuserrolestoarray0role editor return redirectprofile return nextrequest else return nextrequest problem with this code is when user is editor i get infinite loophere is my routsroutegroupmiddleware auth function routegethome middleware admin function return viewhome routegetprofile array as profile uses usercontrollergetprofile anyone know what is problem,['php'] +866825,cardview has extra margin in each edge on prelollipop here are two pictureson lollipopon prelollipopwe can see that it is just close to the screen side on lollipop that is what i want but on the prelollipop device it has extra margin to the screen edge do you guys have any experience thank youhere is the layout xmlandroidsupportv7widgetcardview androidididcard title schedule androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparenttoptrue androidlayout alignparentlefttrue androidlayout alignparentstarttrue androidlayout centerverticaltrue appcardcornerradius0dp appcardbackgroundcolorcolorcoloraccent,['android'] +866841,completely transparent status bar and navigation bar on lollipop i am trying to make an android launcher i want to achieve a completely transparent status bar and navigation bar here is my theme xml fileresources style nametheme parentandroidthemematerialwallpapernotitlebar item nameandroidstatusbarcolorandroidcolortransparentitem item nameandroidnavigationbarcolorandroidcolortransparentitem item nameandroidwindowtranslucentstatusfalseitem item nameandroidwindowtranslucentnavigationfalseitem styleresourcesthe last two items do not work there is still a shadow on lollipopthis is what it looks likenote there is actually a shadow on status bar and navigation barwhat i want to achieve nova launcherhow to make the status bar and navigation bar transparent instead of translucent,['android'] +866847,watchkit unable to find interface controller class i tried adding an interface controller to a storyboard setting its custom class to a wkinterfacecontroller subclass launched the app in the simulator and navigated to the specified interface controllerwhen i do so i get the following errorwatchkit error unable to find interface controller class testcontroller to instantiateif i try to interact with the controller eg try launching its buttons action i get the following error error spremoteinterface interfacecontrollerclientidforcontrollerid clientidentifier for interfacecontrolleridnull not found error spremoteinterface interfacecontrollerclientidforcontrollerid clientidentifier for interfacecontrollerid71204 not foundi tried setting the module name as recommended on this answer but that still gives me the following errorswatchkit error unable to find interface controller class ttc29mywatchapp watchkit app19testcontroller to instantiate error spremoteinterface interfacecontrollerclientidforcontrollerid clientidentifier for interfacecontrolleridnull not found error spremoteinterface interfacecontrollerclientidforcontrollerid clientidentifier for interfacecontrollerid6e204 not found,['ios'] +867081,cannot define member of dependent typedef i am writing custom lazy string classtemplate typename chart typename traits stdchar traitschartclass lazy basic string class char proxy char proxy operatorchart ch char proxy operatorsize type ithen i want to define these methods outside of class declaration template typename chart typename traitsusing char proxy typename lazy basic stringchart traitschar proxytemplate typename chart typename traitschar proxychart traits char proxychart traitsoperatorchart ch but i got compile errorcannot define member of dependent typedef char proxyso i cannot figure out whats problem here why compiler cannot use shortcut char proxy instead of lazy basic stringchar proxy,['c++'] +867148,how do i run a symfony console command after composer install my composerjson contains the following declaration postinstallcmd incenteevparameterhandlerscripthandlerbuildparameters sensiobundlethistributionbundlecomposerscripthandlerbuildbootstrap sensiobundlethistributionbundlecomposerscripthandlerclearcache sensiobundlethistributionbundlecomposerscripthandlerinstallassets sensiobundlethistributionbundlecomposerscripthandlerinstallrequirementsfile i want to run a custom console command that i have in srcmybundlecommandmycommandphp how do i add this to the scripts to run in composer,['php'] +867229,scrapy str object has no attribute iter i added restrict xpaths rules to my scrapy spider and now it immediately fails with20150316 1546530 tsr error spider error processing get traceback most recent call last file systemlibraryframeworkspythonframeworkversions27extraslibpythontwistedinternetbasepy line 800 in rununtilcurrent callfunccallargs callkw file systemlibraryframeworkspythonframeworkversions27extraslibpythontwistedinternettaskpy line 602 in tick taskobj oneworkunit file systemlibraryframeworkspythonframeworkversions27extraslibpythontwistedinternettaskpy line 479 in oneworkunit result self iteratornext file librarypython27sitepackagesscrapyutilsdeferpy line 57 in genexpr work callableelem args named for elem in iterable exception caught here file librarypython27sitepackagesscrapyutilsdeferpy line 96 in iter errback yield nextit file librarypython27sitepackagesscrapycontribspidermiddlewareoffsitepy line 26 in process spider output for x in result file librarypython27sitepackagesscrapycontribspidermiddlewarerefererpy line 22 in genexpr return set refererr for r in result or file librarypython27sitepackagesscrapycontribspidermiddlewareurllengthpy line 33 in genexpr return r for r in result or if filterr file librarypython27sitepackagesscrapycontribspidermiddlewaredepthpy line 50 in genexpr return r for r in result or if filterr file librarypython27sitepackagesscrapycontribspiderscrawlpy line 73 in parse response for request or item in self requests to followresponse file librarypython27sitepackagesscrapycontribspiderscrawlpy line 52 in requests to follow links l for l in rulelink extractorextract linksresponse if l not in seen file librarypython27sitepackagesscrapycontriblinkextractorslxmlhtmlpy line 107 in extract links links self extract linksdoc responseurl responseencoding base url file librarypython27sitepackagesscrapylinkextractorpy line 94 in extract links return selflink extractor extract linksargs kwargs file librarypython27sitepackagesscrapycontriblinkextractorslxmlhtmlpy line 50 in extract links for el attr attr val in self iter linksselector root file librarypython27sitepackagesscrapycontriblinkextractorslxmlhtmlpy line 38 in iter links for el in documentiteretrelement exceptionsattributeerror str object has no attribute iteri cannot understand why this error is happeninghere is my short spiderimport scrapyfrom tutorialitems import dmozitemfrom scrapycontribspiders import crawlspider rulefrom scrapycontriblinkextractors import linkextractorclass tsrspidercrawlspider name tsr allowed domains thestudentroomcouk start urls download delay 4 user agent mozilla50 macintosh intel mac os x 109 rv350 gecko20100101 firefox350 rules rule linkextractor allowforumthisplayphpf143paged restrict xpathsliclasspagerpage numbersahref rule linkextractor allowshowthreadphptdpaged restrict xpathsliclasspagerpage numbersahref callbackparse link rule linkextractor allowshowthreadphptd restrict xpathstrclassthread unread callbackparse link def parse linkself response iterate over posts for sel in responsexpathliclasspost threadpost old rating selxpath divclasspostfooterspanclascoretextextract if not rating rating 0 else rating rating0 item dmozitem itempost selxpath divclasspostcontentblockquoteclasspostcontent restoretextextract itemlink responseurl itemtopic responsexpath divclassforumheader sectionheaderh1spantextextract itemrating rating yield itemsource can someone help me out where is the mistake i have been searching for days,['python'] +867258,make fails trying to install mongo php driver on centos 6 i have tried two different ways to install the mongodb php drivercompiling it based on directions from issuing as root pecl install mongothe server is centos 66 32bit that was originally a 65 virtualbox image that following an update now calls itself 66the error seems to start herein file included from vartmpmongoio streamc34vartmpmongocontribphpsslh3325 error opensslevph no such file or directoryvartmpmongocontribphpsslh3426 error opensslx509h no such file or directoryvartmpmongocontribphpsslh3528 error opensslx509v3h no such file or directoryin file included from vartmpmongoio streamc34vartmpmongocontribphpsslh38 error expected aa before aa tokenvartmpmongocontribphpsslh39 error expected aa before aa tokenvartmpmongocontribphpsslh40 error expected aa before aa tokenvartmpmongoio streamc in function aphp mongo io stream connectavartmpmongoio streamc189 error ax509a undeclared first use in this functionvartmpmongoio streamc189 error each undeclared identifier is reported only oncevartmpmongoio streamc189 error for each function it appears invartmpmongoio streamc189 error acerta undeclared first use in this functionvartmpmongoio streamc194 error expected expression before aa tokenmake io streamlo error 1error make failedother items of notephp vphp 566 cli built feb 19 2015 101959copyright c 19972015 the php groupzend engine v260 copyright c 19982015 zend technologiesmongo versionmongodb shell version 268openssl is installed 101e30e16 6 65i686i have checked other seemingly related stack posts such as mongodb php driver cant installed centos 6 cloud server but it did not seem to help or applyany ideas thanks,['php'] +867259,why can not i assign method reference directly to variable of object type simple question about java8 syntax why does jls8 restrict such expressions likeobject of ref streamof compiletime errorand allow only something likejavautilfunctionfunction of ref streamofobject obj of ref compiles ok,['java'] +867572,auto numbering of angularjs ngrepeat list i am creating student report list with angularjs ngrepeat my issue if how i can dynamically appending numbering like orderedlist to the generated list in viewi want to achieve something like this name of student student id 1 samuel addo 346578 2 grace asumani 965433 3 zein akill 123455 4 david addoteye 678543the column should be auto generate when rendering the model in view through ngrepeat honestly i do not know where to start cos i do not know how to do it i will be glad if anyone can help me or point me to the right source thank you,['javascript'] +867649,configure karmajs to work with react and es6 im try to develop a react module with es6 and could not find any generator for that so i had to make it from a basic one i was able to config almost everything but im have a lot of problems try to configure karma to test my module this is my karmaconfjs karma configuration generated on 20150317 using generatorkarma 090moduleexports functionconfig use strict configset enable thisable watching file and executing tests whenever any file changes autowatch true base path that will be used to resolve files and exclude basepath testing framework to use jasminemochaqunit frameworks commonjs mocha chai list of files patterns to load in the browser files node moduleskarmababelpreprocessornode modulesbabelcorebrowserpolyfilljs node modulesreactreactjs libjs testjs preprocessors libcjsx cjsx testcjsx cjsx libjs babel commonjs testjs babel commonjs babelpreprocessor options sourcemap inline filename function file return fileoriginalpathreplacejs es5js sourcefilename function file return fileoriginalpath list of files patterns to exclude exclude web server port port 8080 start these browsers currently available chrome chromecanary firefox opera safari only mac phantomjs ie only windows browsers chrome phantomjs which plugins to enable plugins karmacommonjs karmacjsxpreprocessor karmababelpreprocessor karmaphantomjslauncher karmachromelauncher karmamocha karmachai continuous integration mode if true it capture browsers run tests and exit singlerun false colors true level of logging possible values log thisable log error log warn log info log debug loglevel configlog info uncomment the following lines if you are using grunts server to run the tests proxies httplocalhost90 url root prevent conflicts with the site root urlroot karma at this point i have the following errorchrome 4202311 mac os x 10102 error uncaught referenceerror module is not defined at usersadminworkspaceopen sourcereactcomponentinspectornode modulesreactreactjs1and if i remove the react ref from files section i get this other errorphantomjs 198 mac os x error uncaught error could not find module react from usersadminworkspaceopen sourcereactcomponentinspectorlibindexes5js at usersadminworkspaceopen sourcereactcomponentinspectornode moduleskarmacommonjsclientcommonjs bridgejs85and if i remove the commonjs i getphantomjs 198 mac os x error referenceerror cannot find variable exports at usersadminworkspaceopen sourcereactcomponentinspectorlibindexes5js5or al least can anyone recommend me a yo generator with karma es6 jsx to build a module not a web app thanks for the help,['javascript'] +867885,custom table view cell iboutlet label is nil consider the following simple view controllerclass viewcontroller uiviewcontroller uitableviewdatasource iboutlet weak var tableview uitableview var items one two three override func viewdidload superviewdidload selftableviewregisterclasscustomtableviewcellself forcellreuseidentifier customcell selftableviewdatasource self func tableviewtableview uitableview numberofrowsinsection section int int return selfitemscount func tableviewtableview uitableview cellforrowatindexpath indexpath nsindexpath uitableviewcell let cell selftableviewdequeuereusablecellwithidentifiercustomcell as customtableviewcell celltitlelabeltext selfitemsindexpathrow return cell and custom cell viewclass customtableviewcell uitableviewcell iboutlet weak var titlelabel uilabel this code causes the following errorfatal error unexpectedly found nil while unwrapping an optional valuetitlelabel is nil aa it is not clear why setting default properties of uitableviewcell like textlabel work just finei am using a nib for the custom cellboth the labels and table views are correctly connected to their iboutletsboth the prototype cell and the custom nib view are marked as having a customtableviewcell classi am new to ios development am i missing something obvioussample xcode project available,['ios'] +868115,ios swift local persistence with cloudkit i am using cloudkit to fetchstore data but would also like to have a local persistence layer does cloudkit offer any kind of local storage capabilities or should i use nsuserdefaults nskeyedarchivernskeyedunarchiver,['ios'] +868227,using flag activity reorder to front to switch among persistently running ui activities leads to no window focus error my objective is to keep two ui activities alive and to switch back and forth between them at will without having to killrestart either of them but there is a serious side effect of using flag activity reorder to front to do this a loss of window focus when i resume a previous activity that is currently running in the backgroundi proved this issue by spending 5 minutes creating a simple application with two hello world activitiesthe app starts with activity a which simply shows a button nothing else called launch bpress this button this executes startactivityflag activity reorder to front activitybclassactivity b becomes active which shows simply shows a button called launch apress this button this executes startactivityflag activity reorder to front activityaclassactivity as onresume is called as expected and everything looks fine i can see activity a content againpress the devices back key and this set of errors will occur 100 of the timeeactivitymanager 513 reason input thispatching timed out waiting because no window has focus but there is a focused application that may eventually add a window when it finishes starting upiwindowstate 513 win death window5294687c u0 comandroidlaunchercomandroidlauncher2launcherwviewrootimpl 8066 dropping event due to no window focus keyevent actionaction down keycodekeycode back scancode0 metastate0 flags0xc8 repeatcount1 eventtime14965546 downtime14965045 deviceid1 source0x101 the practical result of the window death is essentially a crash from the users point of view android throws the user out of the app back to the home screen though technically the application remains running in the backgroundi debugged this and found that the reason activity a is visible but does not have focus is because activity as onwindowfocuschanged is not called like it normally does even though onresume is called this has something to do with the fact with activity b is still active in the background even though clearly b has lost focus onwindowfocuschangedfalse was called for b as well as onstop i know this because after step 4 above if i immediately call finish on activity b activity as onwindowfocuschangedtrue will be called and everything is normal the fact that activity b is still active but not focused somehow interferes with activity a regaining focus like it should is this an android bug or am i missing somethingnote that if activity a had multiple views in it and i were to touch one of those views after step 6 above i would get the same dropping event due to no window focus error though not 100 of the time for some reason,['android'] +868343,how to do multiple views with angular to support header and sidebar i am using angularjs for the first time i have successfully implemented a single ngview in my indexhtml page which contains a headerhtml template so it looks like belowbut now i am creating a dashboard dashboardhtml so i have a left side menu inaddition to headerhtml so it looks like thismy indexhtml is similar to thisdiv ngincludetemplatesheaderhtmldivdiv classmain idmainnospace div idmainpage div idwrapper classcontainer div classcontainer div ngviewdiv div div divdiv ngincludetemplatesfooterhtmlmy dashboardhtml is similar to this div classcollapse navbarcollapse navbarex1collapse ul classnav navbarnav sidenav li classactive a nghreflink1link 1a li li a nghreflink2link 2a li li a nghreflink3link 3a li ul div,['javascript'] +868546,instruments allocations not showing app classesobjects in previous versions of instruments i had no problem but now v62 for some reason allocations would not list any of my apps objects i have tried debug and release modenote the filter vc should catch all the viewcontrollers and without the filterany ideas,"['ios', 'objective-c']" +868665,prediction in caffe exception input blob arguments do not match net inputs i am using caffe for classifying nonimage data using a quite simple cnn structure i have had no problems training my network on my hdf5data with dimensions and x 1 x 156 x 12 however i am having difficulties classifying new datahow do i do a simple forward pass without any preprocessing my data has been normalized and have correct dimensions for caffe it is already been used to train the net below is my code and the cnn structureedit i have isolated the problem to the function net forward in pycaffepy and found that the issue arises as the selfinput dict is empty can anyone explain why that is the set is supposed to be equal to the set coming from the new test dataif setkwargskeys setselfinputs raise exceptioninput blob arguments do not match net inputsmy code has changed a bit as i now use the io methods for converting the data into datum see below in that way i have filled the kwargs variable with the correct dataeven small hints would be greatly appreciated import numpy as np import matplotlib import matplotlibpyplot as plt make sure that caffe is on the python path caffe root this file is expected to be run from caffe root import sys syspathinsert0 caffe root python import caffe import os import subprocess import h5py import shutil import tempfile import sklearn import sklearndatasets import sklearnlinear model import skimageio def loadfromhdf5datasettest reducedh5 pathbjarkehdf5 classificationdata f h5pyfilepath dataset r dat fdata fclose return dat def runmodelpython model file bjarkehdf5 classificationconv v2 simpleprototxt pretrained bjarkehdf5 classificationdatatrain iter 10caffemodel test data loadfromhdf5 net caffenetmodel file pretrained caffeset mode cpu caffeset phase test user test data0 datum caffeioarray to datumuserastypenpuint8 user dat caffeiodatum to arraydatum user dat user datastypenpuint8 out netforward alldatanpasarrayuser datif name main runmodelpythoncnn prototextname cdrcnnlayers name data type hdf5 data top data top label hdf5 data param source bjarkehdf5 classificationdatatraintxt batch size 10 include phase train layers name data type hdf5 data top data top label hdf5 data param source bjarkehdf5 classificationdatatesttxt batch size 10 include phase test layers name feature conv type convolution bottom data top feature conv blobs lr 1 blobs lr 2 convolution param num output 10 kernel w 12 kernel h 1 stride w 1 stride h 1 weight filler type gaussian std 001 bias filler type constant layers name conv1 type convolution bottom feature conv top conv1 blobs lr 1 blobs lr 2 convolution param num output 14 kernel w 1 kernel h 4 stride w 1 stride h 1 weight filler type gaussian std 001 bias filler type constant layers name pool1 type pooling bottom conv1 top pool1 pooling param pool max kernel w 1 kernel h 3 stride w 1 stride h 3 layers name conv2 type convolution bottom pool1 top conv2 blobs lr 1 blobs lr 2 convolution param num output 120 kernel w 1 kernel h 5 stride w 1 stride h 1 weight filler type gaussian std 001 bias filler type constant layers name fc1 type inner product bottom conv2 top fc1 blobs lr 1 blobs lr 2 weight decay 1 weight decay 0 inner product param num output 84 weight filler type gaussian std 001 bias filler type constant value 0 layers name accuracy type accuracy bottom fc1 bottom label top accuracy include phase test layers name loss type softmax loss bottom fc1 bottom label top loss,['python'] +868761,why doesnt byebugpry stop at the breakpoint in rspec actionmailer i try to debug my user mailerrb within my test environment but i dont know why the debugger doesnst stop where it suppose toso the code i roughly have isuser mailer specrbdescribe usermailer do describe send notification letters do bunch of code omitted here it should record itself to the database expect usermailersend notification lettersuser to changesentmailcountby1 end endendin user mailerrbclass usermailer actionmailerbase def send notification lettersuser byebug should break here but doesnt also tried bindingpry here also doesnt work buggy code buggy code buggy code sentmailcreate never reached mailto from endendthe question is why is byebugpry not stopping in the user mailrb when i run the test rspec specmaileruser mailer specrband whyhow to make it stop at that break pointis there a bug in the debugger,['ruby-on-rails'] +868819,java is volatile final required for reference to synchronized object this seems a pretty basic issue but i cannot find a clear confirmationlet us say i have a class properly synchronized in itselfpublic class syncclass private int field public synchronized void dosomething field field 2 public synchronized void dosomethingelse field field 3 if i need to have a reference to an instance of that class shared between threads i do still need to declare that instance volatile or final am i right as inpublic class mainclass previously outerclass public static void mainstring args final syncclass mysharedobject new syncclass new threadnew runnable public void run mysharedobjectdosomething start new threadnew runnable public void run mysharedobjectdosomethingelse start or if mysharedobject cannot be final because its instantiation depends on some other conditions interaction with gui info from socket etc not known beforehandpublic class mainclass previously outerclass public static void mainstring args volatile syncclass mysharedobject thread initthread new threadnew runnable public void run just to represent that there are cases in which mysharedobject cannot be final interaction with gui info from socket etc on which instantation of mysharedobject depends ifwhateverinfo mysharedobject new syncclass else mysharedobject new syncclass public void someotherthing initthreadstart this guarantees mysharedobject has been instantied in the past but that still happened in another thread initthreadjoin new threadnew runnable public void run mysharedobjectdosomething start new threadnew runnable public void run mysharedobjectdosomethingelse start final or volatile are mandatory the fact that myclass synchronizes the access to its own members does not exempt to take care in ensuring that the reference is shared among threads is that rightdifferences with difference between volatile and synchronized in java1 the referred question is about synchronized and volatile as alternatives for the same fieldvariable my question is about how to correctly use an already properly synchronized class ie synchronized has been choosen considering implications needed to be considered by the caller possibly using volatilefinal on a reference of an already synchronized class2 in other words the referred questionanswers are about lockingvolatile the same object my question is how can i be sure different threads actually see the same object before lockingaccessing itwhen the first answer of referred question refers explicitly to a volatile reference it is about an immutable object without synchronization the second answer limits itself to primitive types i did find them useful see below but not complete enough to shed any doubts on the case i am giving here3 the referred answers are very abstract and scholarly explanations to a very open question with quite no code at all as i stated in the introduction i need to a clear confirmation to actual code referring a specific while quite common issue they are related sure but just as a text book is related to a specific problem i actually read it before opening this question and find it useful yet i still need to thiscuss a specific application if text books resolved all problemsdoubts people may have applying them we probably wouldnt need stackoverflow at allconsider that in multithreading you cannot just try it out you need a proper understanding and be sure of details because race conditions can go right a thousand times and then go horribly wrong the thousand 1 time,['java'] +868925,c stackbased object allocation in c there are two ways one can declare an object for example the first wayvectorint nums new vectorint the second wayvectorint numspeople say that the first declaration allocates the object in the heap and the second on the stack i can imagine how it works if the vector object is in the heap the compiler would just find a free block in the heap to store the vector but what would happen if the object is allocated on the stack as i keep pushing new elements to the vector will there be enough memory space if not how would the compiler find a sufficiently big memory block on the stack to store the vector when the size of the vector can change,['c++'] +869025,error cannot initialize module treewalker unable to instantiate junittestcase after importing a maven project to eclipse luna the following error is thisplayed in a popup when saving after modifying a methodcannot initialize module treewalker unable to instantiate junittestcasejunittestcase is referring to a module in the checkstyle xml filemodule namejunittestcasei have the checkstyle configuration plugin for m2eclipse and checkstyle plugin 640 installed the plugin definition for mavencheckstyleplugin in my pom file specifies version 210note i realise this is similar to some other questions with the same error but a different module specified however i am yet to find a satisfying solution i believe that i could remove the module entry in the checkstyle config file but i require it to work as designed so that is not the preferable option,['java'] +869173,php local server invalid request unexpected eof after every execution regardless of said execution when using chrome web browser the php local server throws this errorinvalid request unexpected eof nit is not causing any visible issues however as it is a persistent issue i was wondering if something may bite me laterany ideasnote it happens roughly 10 seconds after any page is executedfurther note this happens after all executions even when the files are ended correctlyphp echo hey would still throw the aforementioned error thu mar 19 093955 2015 12700153923 200 admin thu mar 19 094005 2015 12700153924 invalid request unexpected eofthis is the full error,['php'] +869194,how to make a uiselect field as required i want to make the following field settings in my form as a required field in how can i do itdiv classformgroup label classcolxs5 controllabel settingslabel div classcolxs7 uiselect multiple taggingadpreferredemaildomainpatterntransform idemaildomainpatternlistinput taggingtokensspace themebootstrap ngthisabledsettingsenableauthentication false ngmodelsettingsemaildomainpatternlist uiselectmatchitemthisplayformatuiselectmatch uiselectchoices repeatitem in emaildomainpatterns itemthisplayformat uiselectchoices uiselect divdiv,['html'] +869265,java 8 datetime get start of day from zoneddatetime is there any difference between thesezoneddatetimetruncatedtochronounitdayszoneddatetimetolocaldateatstartofdayzoneddatetimegetzoneany reason to prefer one against the otherthanks,['java'] +869308,docker initialize mysql database with schema i am trying to create a container with a mysql database and add a to these databasemy current dockerfile isfrom mysqlmaintainer me email copy the database schema to the data directorycopy filesepcis schemasql dataepcis schemasql change the working directoryworkdir datacmd mysql u mysql user p mysql password mysql database epcis schemasqlin order to create the container i am following the documentation provided on docker and executing this commanddocker run name container name e mysql root passworddb root password e mysql userdb user e mysql passworddb user password e mysql databasedb name d mvpgomesepcisdbbut when i execute this command the container is not created and in the container status it is possible to see that the cmd was not executed successfully in fact only the mysql command is executedanyway is there a way to initialize the database with the schema or do i need to perform these operations manually,['mysql'] +869312,how is nth element implemented there are a lot of claims on stackoverflow and elsewhere that nth element is on and that it is typically implemented with introselect elementi want to know how this can be achieved i looked at wikipedias explanation of introselect and that just left me more confused how can an algorithm switch between qsort and medianofmediansi found the introsort paper here reprep1typepdf but that saysin this paper we concentrate on the sorting problem and return to the selection problem only briefly in a later sectioni have tried to read through the stl itself to understand how nth element is implemented but that gets hairy real fastcould someone show me pseudocode for how introselect is implemented or even better actual c code other than the stl of course,['c++'] +869344,why is or is not setting fields in a constructor threadsafe let us say you have a simple class like thisclass myclass private readonly int a private int b public myclassint a int b thisa a thisb b public int a get return a public int b get return b i could use this class in a multithreaded mannermyclass value nulltaskrun while true value new myclass1 1 threadsleep10 while true myclass result value if result null resulta 1 resultb 1 throw new exception threadsleep10my question is will i ever see this or other similar multithreaded code throw an exception i often see reference to the fact that nonvolatile writes might not immediately be seen by other threads thus it seems like this could fail because the write to the value field might happen before the writes to a and b is this possible or is there something in the memory model that makes this quite common pattern safe if so what is it does readonly matter for this purpose would it matter if a and b were a type that cannot be atomically written e g a custom struct,['c#'] +869445,ios8swift uicollectionreusableview missing return in a function i had a weird problem running into considering a header of a uicollectionviewi basically used the coded fromfunc collectionviewcollectionview uicollectionview viewforsupplementaryelementofkind kind string atindexpath indexpath nsindexpath uicollectionreusableview let dateformatter nsdateformatter dateformatterdateformat ddmmy hhmm 1 switch kind 2 case uicollectionelementkindsectionheader 3 let h collectionviewdequeuereusablesupplementaryviewofkindkind withreuseidentifier eventheaderview forindexpath indexpath as eventheader heventfirstlinetext first line heventsecondlinetext thiseventeventname heventdatetext dateformatterstringfromdatethiseventstartdate heventdescriptiontext thiseventshortdescription return h default 4 assertfalse unexpected element kind all that works perfectly fine when instantly deploying to either the simulator or a real device but oddly when i wanna build an adhoc package for testing purposes it tells me missing return in a function expected to return uicollectionreusableviewok so far so good ther is nothing outside the switchcase so it could return nothing but why does it not give any warnings on hot deploy only when i try to build a package,['ios'] +869538,adding photos to gallery in google play newsstand helo fellas ia m trying to add several pictures in a gallery of my articles in google play newsstand with no success i tried adding 3 pictures with the right size but cana t be thisplayed into the articlea s gallerymediacontent urlurl image typeimagepng expressionfull width538 height190mediadescription typeplaindescriptionmediadescriptionmediacredit roleauthor schemeurnebuauthormediacreditmediacontentthis is an example of my element item titlecdataarquean a cafeteraatitle linkcdatahttpgooglewebacdkelink contentencodedcdatatoday weare introducing a new agebased rating system for apps and games on google play we know that people in different countries have different ideas about what content is appropriate for kids teens and adults so todayas announcement will help developers better label their apps for the right audience consistent with industry best practices this change will give developers an easy way to communicate familiar and locally relevant content ratings to their users and help improve app thiscovery and engagement by letting people choose content that is right for themstarting now developers can complete a content rating questionnaire for each of their apps and games to receive objective content ratings google playas new rating system includes official ratings from the international age rating coalition iarc and its participating bodies including the entertainment software rating board esrb paneuropean game information pegi australian classification board unterhaltungssoftware selbstkontrolle usk and classificao indicativa classind territories not covered by a specific ratings authority will thisplay an agebased generic rating the process is quick automated and free to developers in the coming weeks consumers worldwide will begin to see these new ratings in their local marketscontentencoded authorgrupo jorgesysauthor mediacontent url typeimagepng expressionfull width538 height190mediadescription typeplaincdataandroidmediadescriptionmediacredit roleauthor schemeurnebucdatagrupo jorgesys staffmediacreditmediacontent mediacontent url mediumaudiomediatitlecdataarquean a cafeteraamediatitlemediadescriptioncdataarquean a cafeteraamediacreditmediacontent mediacontent url typeimagepng expressionfull width538 height190mediadescription typeplaincdataandroid0mediadescriptionmediacredit roleauthor schemeurnebucdatagrupo jorgesys staffmediacreditmediacontent mediacontent url typeimagepng expressionfull width538 height190mediadescription typeplaincdataandroid1mediadescriptionmediacredit roleauthor schemeurnebucdatagrupo jorgesys staffmediacreditmediacontent mediacontent url typeimagepng expressionfull width538 height190mediadescription typeplaincdataandroid2mediadescriptionmediacredit roleauthor schemeurnebucdatagrupo jorgesys staffmediacreditmediacontent mediacontent url typeimagepng expressionfull width538 height190mediadescription typeplaincdataarquean a cafeteraamediadescriptionmediacredit roleauthor schemeurnebucdatagrupo jorgesys staffmediacreditmediacontent item,"['java', 'android']" +869560,what is the difference between mockpatchobject and mockpatch i am trying to understand the difference between these two approaches of mocking a method could someone please help thistinguish them for this example i use the passlib libraryfrom passlibcontext import cryptcontextfrom unittest import mockwith mockpatchobjectcryptcontext verify return valuetrue as foo1 mycc cryptcontextschemesbcrypt sha256 mypass myccencrypttest assert myccverifytest mypasswith mockpatchpasslibcontextcryptcontextverify return valuetrue as foo2 mycc cryptcontextschemesbcrypt sha256 mypass myccencrypttest assert myccverifytest mypass,['python'] +869691,is there a way to avoid loops when adding to a list i was wondering a code like this liststring list new arrayliststringforcustomobject co objects listaddcogetactualtextcan it be written differently i mean of course at some point there will be a loop but i am wondering if there is an api usage i am ignoring,['java'] +869773,tkinter understanding mainloop till now i used to end my tkiter programs with tkmainloop or nothing would show up see examplefrom tkinter import import randomimport timetk tktktitle gametkresizable00tkwm attributestopmost 1canvas canvastk width500 height400 bd0 highlightthickness0canvaspackclass ball def init self canvas color selfcanvas canvas selfid canvascreate oval10 10 25 25 fillcolor selfcanvasmoveselfid 245 100 def drawself passball ballcanvas redtkmainloophowever when tried the next step in this programmaking the ball move by time the book am reading from says to do the following change the draw function todef drawself selfcanvasmoveselfid 0 1and add the following code to my programwhile 1 balldraw tkupdate idletasks tkupdate timesleep001but i noticed that adding this block of code made the use of tkmainloop useless since everything would show up even without itat this moment i should mention that my book never talks about tkmainloop maybe because it uses python 3 but i learned about it searching the web since my programs did not work by copying books codeso i tried doing the following that would not workwhile 1 balldraw tkmainloop timesleep001whats going on what does tkmainloop what does tkupdate idletasks and tkupdate do and how that differs from tkmainloop should i use the above looptkmainloop or both in my programsthanks,['python'] +869845,which way is better to get lower 32 bits of a 64 bits integer i found that in some answers they recommended using lower some var 32 32but i tested and found the following is fasterlower some var 0xfso which is better is the former safer in some cases or faster after compiler optimized,['c++'] +869878,reactjs ignores labels for attribute i know that for class we must use classname but how do i get react to preserve for attributethe followinglabel forrecipientname classnamecontrollabelrecipientlabelis rendered aslabel classcontrollabelrecipientlabelon an unrelated note i find it annoying that i can not change attributes using chromes console when using react is there a way around that for example if i inspect the rendered element and add the for attribute manually it thisappears when i click away from that control presumably because react rerenders the control i am guessing,['javascript'] +869921,const reference to temporary reference include iostreamusing namespace stdstruct cl cl coutclendl clconst cl coutclconst clendl cl coutclendl cl clcl fnc return clint main coutstartendl const cl refstatic castconst clfnc is ref valid here coutendendl return 0whats lifetime of temporary object returned by fnc is it lifetime of ref or of temporary reference static castfnc which destroyed at end of statementoutput of gcc lifetime of fnc is lifetime of refcl global object clstartclconst clendclcl global object cloutput of vs2013 lifetime of fnc is lifetime of temporary referencecl global object clstartclconst clclendcl global object clwhats correct by standard,['c++'] +869928,how to create javadoc using android studio without r and buildconfig i want to generate the javadoc for my library excluding r and buildconfig the generate javadoc functionality from the tools menu does not have the option to exclude fileshow to create javadoc using android studio without r and and buildconfig,['android'] +869994,remove spacing or padding in android spinner i am using android spinner and edittext from support lib v21 i would like to align text to left the same like edittext as shown in figure but deafult spinner include spacing or padding so i would like to remove it to align text to left please help how to remove it,['android'] +870013,how to join three table by laravel eloquent model i have three tablearticles table id title body categories id user idcategories table id category nameuser table id user name user typei want to show articles with their category name instead of category id and user name instead of user idi try like these query it is workarticles dbtablearticles joincategories articlesid categoriesid joinusers usersid articlesuser id selectarticlesidarticlestitlearticlesbodyusersusername categoryname getbut i want to do by eloquent way please how could i do,"['php', 'mysql']" +870018,ios swift is it possible to change the font style of a certain word in a string i am extracting from a db contents as strings with a method i extract the longest word out of this string now i would like to print out the entire string to a text label but would like to highlight the longest word in a different color and text style within the stringhow can i do thatdo i need to cut the string into pieces set the formatting and put them all together again before giving it to the label or is there any other better way,['ios'] +870086,spring boot autowire into an unmanaged class using configurable and load time weaving i have a collection of unmanaged classes that i are instantiated outside of spring i have been attempting to use spring aop with load time weaving to autowire a bean into these classes but have so far not had any luck i have been testing using tomcat 8 and spring boot 120my configuration where i attempt to set up class looks like thisconfigurationpropertysourceclasspathapplicationpropertiesenablespringconfiguredenableloadtimeweavingpublic class configinside config i define the bean i want to auotwire into my unmanaged classesbeanpublic stateprovider stateprovider setup bean return new dynamostateproviderimpl the unmanaged bean looks like thisconfigurableautowire autowireby type dependencycheck true preconstruction truepublic class stateoutput implements unifiedoutput autowiredprivate stateprovider stateproviderand i have the following deps inside my pom dependency groupidorgspringframeworkgroupid artifactidspringagentartifactid version256sec03version dependency dependency groupidorgspringframeworkgroupid artifactidspringtxartifactid dependency dependency groupidorgspringframeworkgroupid artifactidspringaopartifactid dependency dependency groupidorgspringframeworkgroupid artifactidspringaspectsartifactid dependency dependency groupidjavaxelgroupid artifactidjavaxelapiartifactid version300version dependencyso far i have not been able to see anything injected into stateprovider or been able to pull any info from the logs i have also attempted setter style injection using autowiredpublic void setstateproviderstateprovider stateprovider thisstateprovider stateproviderthanks,['java'] +870177,java home error with upgrade to spark 130 iam trying to upgrade a spark project written in scala from spark 121 to 130 so i changed my buildsbt like solibrarydependencies orgapachespark sparkcore 121 providedlibrarydependencies orgapachespark sparkcore 130 providedthen make an assembly jar and submit ithadoop conf diretchadoopconf sparksubmit driverclasspathetchbaseconf conf sparkhadoopvalidateoutputspecsfalse conf sparkyarnjarhdfsappslocalsparkassembly130hadoop240jar conf sparkserializerorgapachesparkserializerkryoserializer deploymodecluster masteryarn classtestobject numexecutors54 targetscala211myappassembly12jarthe job fails to submit with the following exception in the terminal150319 103007 info yarnclient 150319 102003 info yarnclient client token na diagnostics application application 1420225286501 4698 failed 2 times due to am container for appattempt 1420225286501 4698 02 exited with exitcode 127 due to exception from containerlaunch orgapachehadooputilshellexitcodeexception at orgapachehadooputilshellruncommandshelljava464 at orgapachehadooputilshellrunshelljava379 at orgapachehadooputilshellshellcommandexecutorexecuteshelljava589 at orgapachehadoopyarnservernodemanagerdefaultcontainerexecutorlaunchcontainerdefaultcontainerexecutorjava195 at orgapachehadoopyarnservernodemanagercontainermanagerlaunchercontainerlaunchcallcontainerlaunchjava283 at orgapachehadoopyarnservernodemanagercontainermanagerlaunchercontainerlaunchcallcontainerlaunchjava79 at javautilconcurrentfuturetasksyncinnerrunfuturetaskjava303 at javautilconcurrentfuturetaskrunfuturetaskjava138 at javautilconcurrentthreadpoolexecutorworkerruntaskthreadpoolexecutorjava886 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava908 at javalangthreadrunthreadjava662finally i go and check the yarn app masteras web interface since the job is there i know it at least made it that far and the only logs it shows are these log type stderr log length 61 binbash java homebinjava no such file or directory log type stdout log length 0iam not sure how to interpret that a is java home a literal including the brackets thatas somehow making it into a script is this coming from the worker nodes or the driver anything i can do to experiment troubleshooti do have java home set in the hadoop config files on all the nodes of the cluster grep java home etchadoopconfshetchadoopconfhadoopenvshexport java homeusrjdk64jdk160 31etchadoopconfyarnenvshexport java homeusrjdk64jdk160 31has this behavior changed in 130 since 121 using 121 and making no other changes the job completes finenote i originally posted this on the spark mailing list i will update both places ifwhen i find a solution,['java'] +870405,how do you kill futures once they have started i am using the new concurrentfutures module which also has a python 2 backport to do some simple multithreaded io i am having trouble understanding how to cleanly kill tasks started using this modulecheck out the following python 23 script which reproduces the behavior i am seeingusrbinenv pythonfrom future import print functionimport concurrentfuturesimport timedef control c this with concurrentfuturesthreadpoolexecutormax workers5 as executor future1 executorsubmitwait a bit namejack future2 executorsubmitwait a bit namejill for future in concurrentfuturesas completedfuture1 future2 futureresult printall donedef wait a bitname printn is waitingformatnname timesleep100if name main control c thiswhile this script is running it appears impossible to kill cleanly using the regular controlc keyboard interrupt i am running on os xon python 27 i have to resort to kill from the command line to kill the script controlc is just ignoredon python 34 controlc works if you hit it twice but then a lot of strange stack traces are dumpedmost documentation i have found online talks about how to cleanly kill threads with the old threading module none of it seems to apply hereand all the methods provided within the concurrentfutures module to stop stuff like executorshutdown and futurecancel only work when the futures have not started yet or are complete which is pointless in this case i want to interrupt the future immediatelymy use case is simple when the user hits controlc the script should exit immediately like any wellbehaved script does that is all i wantso whats the proper way to get this behavior when using concurrentfutures,['python'] +870814,what is grunt for i am trying to get into grunt which i am new to but i do not understand its utilityi understand that it is a taskrunner i understand that it can be used to do things like bundle uglify jshint minify etc etc etc anything that can be turned into a scripted taskbut i do not see what advantage this gives nearly all of these can be run from the command line anyway which is to say you could just combine them using a simple shell script it seems to me that setting up grunt gruntfiles and writing tasks is more work than writing a shell script rather than lesscould someone help me to understand what i am missing about this,['javascript'] +870840,jquery datatables getting selected row values i am using jquery datatablei done it using rowhtmlnow i want to get selected row values idsscript documentreadyfunction var table exampledatatable example tbodyon click tr function thistoggleclaselected buttonclick function alert tablerowsselecteddatalength rows selected and html code table idexample classthisplay cellspacing0 width100 thead tr thidth thpositionth thofficeth thageth thstart dateth thsalaryth tr thead tfoot tr thidth thpositionth thofficeth thageth thstart dateth thsalaryth tr tfoot tbody tr td1td tdsystem architecttd tdedinburghtd td61td td20110425td td320800td tr tr td2td tdaccountanttd tdtokyotd td63td td20110725td td170750td tr tablenow i am able to get selected noofrowsnow i want to get selected row idscan anyone guide me to achieve it,['jquery'] +870848,what is the difference between binrake and bundle exec rake what is the difference between using binrake and bundle exec rakeand which is one preferred stylebinrake dbmigratebundle exec rake dbmigrate,['ruby-on-rails'] +871006,qt drawing a filled rounded rectangle with border i want to draw a rectangle with rounded corners border radius same for all 4 corners with a specific color filling the entire rectangle and a separate border color say border is 1 px widefrom my observation qt provides three methods fillrect and drawrect and drawroundedrect i have tried them they do not work like i want to there is no method like fillroundedrect which means that i can draw a rounded rectangle but it would not be filled with the color i wanthow do i do it and also i read that due to some aliasing problems the corners are often rendered equal how do i set it as equal for all four will paintersetrenderhintqpainterantialiasing suffice or do i have to do anything else,['c++'] +871050,does seeking an html5 video require loading the whole file i want to randomly seek to different points in a 30 minute video every 30 seconds the filesize will be 100mb when i seek does the player start loading from that point or does it have to load the entire file and then find that time within it,"['javascript', 'html']" +871077,how do i inject code into an ios process questionlooking at i see a screenshot of the framework being used on the apple springboard with a caption that readsthe code injection is left as an exercise for the reader i 12i i am not directly interested in injecting it into the springboard but if i did want to inject the framework into another process like the calculator app for instance how would i go about doing soas a sidenote i am willing to jailbreak my device if that is the only way of doing something like thiswhat i have triedi have tried using to inject apps that i had the source to but i could not run it on my device and i also could not run it on apps i did not have the source toi have also tried using but i kept getting provisioning errors during the injecting process,"['ios', 'objective-c']" +871497,how can i use html5 geolocation in c application i am developing an antitheft software to get computers exact location notebooks with builtin gps are very rare in my country so i have to use html5 geolocation in my applicationfor internet explorer 9 there is a registry key that you can add urls to allow a url without needing user verification if you add an reg dwordvalue named domaincom under hkcusoftwaremicrosoftinternet explorergeolocationhostconsent path browser will allow geolocation request automatically however i cannot run internet explorer hidden so thats not working for me since thief should not realize and see whats going oni need to run internet explorer hidden somehowor i need to embed webkit or something to my application but i do not know how can i use it or how can i allow this request programmaticallyi prefer second way because internet explorer is now terminated by microsoft and i think next version will have different structurehow can i embed and use webkit or geckofx to my application how can i allow a geolocation request programmatically in this application,['c#'] +871685,iterate over two arrays i am new to swift i have been doing java programming i have a scenario to code for in swiftthe following code is in java i need to code in swift for the following scenario with string array strarr1string strarr1 some1some2string strarr2 somethingelse1somethingelse2for int i0i strarr1lengthi systemoutprintlnstrarr1i strarr2ii have a couple of arrays in swiftvar strarr1 string some1some2var strarr2 string somethingelse1somethingelse2for data in strarr1 printlndatafor data in strarr2 printlndata i need to loop over in single for loop based on indexcould you please provide your help on the syntaxes for looping over based on index,['ios'] +871851,webviewwebkit not working as expected this is my first time posting here so please bear with me i am using webkit to thisplay some content from youtube in a webviewbackgroundos os x 10102sdk os x 1010problemas i stated before i am using a webview to thisplay content from youtube but i ran into some problems which i have outlined belowwhen attempting to use the youtubes fullscreen action this is what happens test one using flashobservations what wrong i did when using the flash player on youtubeas website when i attempt to play a video everything worked fineadditionally when i clicked the youtube videoas full screen button the window did appear in full screen however it is not completely fullscreen the menu bar is still visiblewhat i expected i expected that the video would have entered fullscreen entirely in safari everything works finetest two using html5observations what i did when using the html5 player on youtubeas website when i attempted to play a video everything worked fine however when i clicked the youtube videoas full screen button nothing happenedwhat i expected i expected that the video would have entered full screen i did noticed when doing this ins safari everything worked as expectedcan someone please help me with this matter i have searched everywhere and found nothinghere is a sample of the test app i did to illustrate this problem voidapplicationdidfinishlaunchingnsnotification anotification insert code here to initialize your application nsurl url nsurl urlwithstring nsurlrequest urlrequest nsurlrequest requestwithurlurl self webview mainframe loadrequesturlrequest selfwindow setcontentviewselfwebview when yes webview will use flash if available else will use html5 bool shoulduseplugin yes if shoulduseplugin yes self webview preferences setpluginsenabledyes test 1 using flash else self webviewpreferencessetpluginsenabledno test 2 using html5,['objective-c'] +871926,why cannot a class extend a static nested class occurring within it this classpublic class outerchild extends outerchildinnerparent public static class innerparent fails to compile javac outerchildjavaouterchildjava1 error cyclic inheritance involving outerchildpublic class outerchild extends outerchildinnerparent 1 errorbecause outerchild would depend on itself because per 814 superclasses and subclasses of the java language specification java se 8 edition a class directly depends on any type that is mentioned in its extends or implements clause as a qualifier in the fully qualified form of a superclass or superinterface namebut i do not really understand the motivation here what is the problematic dependency is it just for consistency with the case where innerparent were nonstatic and would therefore end up with a lexically enclosing instance of itself,['java'] +871963,what is the spark dataframe method topandas actually doing i am a beginner of sparkdataframe api i use this code to load csv tabseparated into spark dataframelines sctextfiletail5csvparts linesmaplambda l lstripsplittfnames some name listschemadata structtypestructfieldfname stringtype true for fname in fnamesddf sqlcontextcreatedataframepartsschemadatasuppose i create dataframe with spark from new files and convert it to pandas using builtin method topandasdoes it store the pandas object to local memorydoes pandas lowlevel computation handled all by sparkdoes it exposed all pandas dataframe functionalityi guess yescan i convert it topandas and just be done with it without so much touching dataframe api,['python'] +872025,ios swift core data examples with a complex data relationship i am trying to understand how to model complex data relationships with core data with my app i currently have an entity of recipe ingredient and recipeingredient which bind ingredients to a recipei have not come across any example of fetching data out of this joint entity i would appreciate it if someone could give an example of an entity like my recipeingredient in swift,['ios'] +872294,what is the type of in java 8 in java8 what is the type of the following lambda that is a function that takes no arguments and returns nothingstated differentlypublic class a static void a static void mainstring args a aa what should i replace the question marks within scala this would be a function0unit i think but i do not find anything alike in java,['java'] +872333,how to create hashmap with streams overriding duplicates i am creating a hashmap using java8 stream api as followsmapinteger string map daofindallstream collectcollectorstomapentitygettype entitygetvaluenow if an element is added to the collection where the key already exists i just want to keep the existing element in the list and skip the additional element how can i achieve this probably i have to make use of binaryoperationu of tomap but could anyone provide an example of my specific case,['java'] +872339,reinterpret cast an array from string to int i would like to reinterpret a string in a array of int where every int take charge of 4 or 8 chars based on processor architectureis there a way to achieve this in a relatively inexpensive wayi tried out this but does not seem to reinterpret 4 chars in one intstring text abcdabcdefghefghunsafe fixed char charpointer text int32 intpointer int32charpointer for int index 0 index textlength 4 index consolewriteline intpointer index solution change int64 or int32 based on your needsstring text abcdabcdefghefghunsafe fixed char charpointer text int64 intpointer int64charpointer int conversionfactor sizeof int64 sizeof char int index 0 forindex 0 index textlength conversionfactor index consolewriteline intpointer index if textlength conversionfactor 0 intpointer index sizeof int64 intpointer index sizeof int64 consolewriteline intpointer index,['c#'] +872457,error unable to run mksdcard sdk tool keep getting an error in the setup wizard while trying to install android studio on ubuntuunable to run mksdcard sdk toolalso in the terminal i get this 115528 error trunwizardsetupprogrestep1 android studio 110 build ai1351740770 115531 error trunwizardsetupprogrestep1 jdk 180 40 115531 error trunwizardsetupprogrestep1 vm java hotspottm 64bit server vm 115531 error trunwizardsetupprogrestep1 vendor oracle corporation 115531 error trunwizardsetupprogrestep1 os linux 115532 error trunwizardsetupprogrestep1 last action,"['java', 'android']" +872477,stored procedure sometimes returns short sometimes returns int i am working with a legacy codebase and need to call a stored procedure that i am not allowed to modify this stored procedure returns a row or multiple rows of validation data example of result set two columns code and text0 successor 3 short error4 detailed errorin the procedure itself the message is selected simply as select 0 as code success as textproblemi am using entity framework to map the result of this stored procedure to a custom classpublic class validationresult public int code get set public string text get set the call itselfvar result contextdatabasesqlqueryvalidationresultold sproctolisti have written some integration tests and have noticed that when the procedure returns the success message the 0 comes across as a short when it returns a nonzero message it comes across as an int i assumed that setting code as an int the short would fit in unfortunately i get the following exception for my success testthe specified cast from a materialized systemint16 type to the systemint32 type is not validwhen i switch code to a short to make my success test pass my failure test fails with the following exceptionthe specified cast from a materialized systemint32 type to the systemint16 type is not validadonet is an answerone solution is to fall back to adonets sqldatareader object so i have that as a fallback solution i am wondering if there is something i can do on the ef side to get this working though,"['c#', '.net']" +872506,trying to convert firebase timestamp to nsdate in swift i am trying to use firebase timestamps in a swift app i would like to store them in my firebase and use them as native nsdate objects in my appthe docs say they are unix epoch time so i have triednsdatetimeintervalsince1970firebaseservervaluetimestampwith no luckthisfirebaseservervaluetimestampreturns0x01199298a0according to the debugger what is the best way to pass these timestamps around,['ios'] +872587,why my lambdas do not work i struggle with making lambdas work the code here is example but it shows my problem welambdas listfor i in range5 lambdasappendlambda xiixprint lambdas01print lambdas21this give me 16 but i expect to have different value for different lambda why is happening,['python'] +872716,android enable tlsv12 in okhttp i am using okhttp for my project i want to enable tlsv12 for my service call can any body tell me how to enable it,['android'] +872760,why is 00 syntactically valid why is this line valid in javascript var a 00after that a is undefined,['javascript'] +872966,flyway and spring boot integration i trying to integrate flyway for migrations in a spring boot project with hibernate and spring jpa i am getting the following exceptionorgspringframeworkbeansfactorybeancreationexception error creating bean with name flyway defined in class path resource orgspringframeworkbootautoconfigureflywayflywayautoconfigurationflywayconfigurationclass invocation of init method failed nested exception is orgflywaydbcoreapiflywayexception found nonempty schema public without metadata table use init or set initonmigrate to true to initialize the metadata tablemy pomxml is looking like this dependency groupidorgflywaydbgroupid artifactidflywaycoreartifactid version32versiondependencyi am using hibernate and a config java file for postgres dev stage and h2 local the signatures are looking like this beaninitmethod migrate public flyway flyway flyway fly new flyway flyclean flyinit flywaysetinitonmigratetrue flysetschemassba dialog flywaysetlocationsfilesystemsrcmainresourcesdbmigration flysetdatasourcethisdatasource flymigrate return fly beanname sbaentitymanagerfactory dependsonflyway public localcontainerentitymanagerfactorybean entitymanagerfactory i cannot find anything about my problem described in this question can anybody help,['java'] +873027,is there a beter way to catch only specific causes of an exception given this stacktrace javalangruntimeexceptioncaused by commypackagespecificexceptionand this trycatchtry tsinit catch runtimeexception e if egetcause instanceof specificexception do something else throw e i cannot modify the code for specificexception nor the method that wraps this exception into a runtimeexceptionis there a better way to catch only specificexception,['java'] +873226,angularjs directive twoway data binding not working when observing boolean i have a twoway data binding that is not altering the value of the variable sent to the directivemy directive watches for a trigger and gives focus to the associates element based on code found here at soappdirectivefocusme function timeout return scope trigger focusme link function scope element attrs scopewatchtrigger functionvalue consolelogdirective value value consolelogdirective start scopetrigger if value true timeoutfunction element0focus scopetrigger false consolelogdirective end scopetrigger in the html i call it as followsinput typetext ngmodelitemvalue focusmefocusinput when i trigger it for the first time it works because the focusinput variable switches its value but focusinput in the controllers scope outside the directive does not switch back to false when the directive completesthis switch back to false should happen when i call scopetrigger false assuming i understand what should be happeningwhat is missing that would cause the twoway binding to not push the value back to the variable passed into the directiveupdate 01for posting the question i removed a small bit of code the html actually looks like thisinput typetext ngmodelitemvalue focusmefocusinput ngifitemcondition matches itemcondition does not match if the input fields hides and then is reshown based on the ngif the directive will properly give focus the first time focusinput changes it will stop working again after that unless the hideshow process is repeated,['javascript'] +873230,xcode provisioning profile apple id not matching bundle identifier i am getting an error no matching provisioning profiles where it says the appleid has to be the same as the bundle identifier the problem is that it is the same but when i create my project it adds tests to the end of the bundle identifier for example appid is comcompanyapp i create a project with the product name app and the organization identifier comcompany the bundle identifier is then set to comcompanyapp when i try to run it on my device it says that the appid is comcompanyapp but the bundle identifier is comcompanyapptests,['ios'] +873245,intelij idea can i have automatically incremented build version number can i set somehow intelij building process to preprocess java source codes and give me ever incrementing build number something likeint mybuildnumber intelli j idea magic which will increment every build,['java'] +873369,how to properly create and run concurrent tasks using pythons asyncio module i am trying to properly understand and implement two concurrently running task objects using python 3s relatively new asyncio modulein a nutshell asyncio seems designed to handle asynchronous processes and concurrent task execution over an event loop it promotes the use of await applied in async functions as a callbackfree way to wait for and use a result without blocking the event loop futures and callbacks are still a viable alternativeit also provides the asynciotask class a specialized subclass of future designed to wrap coroutines preferably invoked by using the asyncioensure future method the intended use of asyncio tasks is to allow independently running tasks to run concurrently with other tasks within the same event loop my understanding is that tasks are connected to the event loop which then automatically keeps driving the coroutine between await statementsi like the idea of being able to use concurrent tasks without needing to use one of the executor classes but i have not found much elaboration on implementation this is how i am currently doing itimport asyncioprintrunning async testasync def say boo i 0 while true await asynciosleep0 printboo 0formati i 1async def say baa i 0 while true await asynciosleep0 printbaa 0formati i 1 option 1 wrap in task object automatically attaches to event loop and executesboo asyncioensure futuresay boobaa asyncioensure futuresay baaloop asyncioget event looplooprun foreverin the case of trying to concurrently run two looping tasks i have noticed that unless the task has an internal await expression it will get stuck in the while loop effectively blocking other tasks from running much like a normal while loop however as soon the tasks have to waiteven for just a fraction of a secondthey seem to run concurrently without an issue thus the await statements seem to provide the event loop with a foothold for switching back and forth between the tasks giving the effect of concurrencyexample output with internal awaitrunning async testboo 0baa 0boo 1baa 1boo 2baa 2example output without internal awaitboo 0boo 1boo 2boo 3boo 4questionsdoes this implementation pass for a proper example of concurrent looping tasks in asyncio is it correct that the only way this works is for a task to provide a blocking point await expression in order for the event loop to juggle multiple tasks,['python'] +873667,animating uivisualeffectview blur radius as the title says it is there a way to animate a uivisualeffectviews blur radius i have a dynamic background behind the view so the imageeffects addition cannot be used the only thing that can do this as far as i know is to animate the opacity but ios complains saying that doing that breaks the effectview so it definitely seems like a bad idea any help would be gladly appreciated,['objective-c'] +873779,numpy individual element access slower than for lists i just started using numpy and noticed that iterating through each element in a numpy array is 4x slower than doing the same but with a list of lists i know now that this defeats the purpose of numpy and i should vectorize the function if possible my question is though why is it 4x slower that seems like quite a large amounti ran the tests below using timeitimport numpy as npb npeye10a btolisttimeit b100100 10 loops best of 3 692 ns per looptimeit a100100 10 loops best of 3 707 ns per looptimeit b100100 10 loops best of 3 343 ns per looptimeit bitem100100 10 loops best of 3 297 ns per loopi tried to use thisthis to see what was going on under the hood but gottypeerror do not know how to thisassemble methodwrapper objectsthen i tried to look at the numpy source code but could not figure out which file corresponded to array element access i am curious what accounts for the extra overhead and more importantly how to figure this out for myself in the future it seems like python cannot be easily compiled to c code so that i can see the difference but is there a way to see what byte code is generated for each line to get a sense of the differences,['python'] +873793,websockets energy consumption on a mobile device iphoneandroid what is the impact on battery consumption by implementing websockets vs httpsuppose i am building an instant messaging app and have two optionsrely on push notifications to notify the device of a new message and then fetch that message via a rest apiestablish a websocket connection when the user launches the app and maintain that connection while the app is active the server forwards all messages directly to the device rather than using push notificationssomeone told me that maintaining a persistent websocket connection would be a huge battery hog because it requires the antenna to be constantly active rather than powering down after each request but is that really truethis answer suggests that on ios each device maintains a persistent connection with the push notification service at all times similar to websockets i suppose so does not that suggest that the devices antenna is running 247 anywaythe extra overhead of http requests would be pretty insignificant for an instant messaging app but in an application where a large number of items need to be downloaded constantly a persistent websocket connection would be very useful any insight about maintaining longterm websocket connections on mobile devices especially concerning battery consumption would be extremely helpful,"['android', 'ios']" +873795,where is requestisajaxrequest in aspnet core mvc to learn more about the new exciting aspnet5 framework i am trying to build a web application using the newly released visual studio 2015 ctp6most things looks really promising but i cannot seem to find requestisajaxrequest a functionality i have been using quite frequently on older mvc projectsis there a better way to do this that made them remove this method or is it hidden somewhere elsethanks for any advice on where to find it or what to do instead,['c#'] +873918,swift objectivec project generated swifth error cannot find interface declaration for uiviewcontroller i have got a project using the swift generated bridging header and have the project set up correctly no spaces in names uses modules predeclaring swift classes in my mm file deleting derived data doing a clean rebuild etc the bridging header is being generated fine but the automatically generated swifth has errors in it whats even worse those errors are on the generated in project creation swift versions of appdelegate and viewcontroller which would normally compile fine the errors in the swifth areinterface appdelegate uiresponder uiapplicationdelegate cannot find interface declaration for uiresponder superclassof appdelegate cannot find protocol declaration for uiapplicationdelegateinterface viewcontroller uiviewcontroller cannot find interface declaration for uiviewcontroller superclassof viewcontrolleri have searched stack overflow and the net and cannot find any answer that addresses this particular issue has anyone else had this or is there a way i can mark my appdelegate and viewcontroller classes so xcode does not try and create objectivec stubs for those swift classes as i do not actually need them,"['ios', 'objective-c']" +874114,excel vba to c i am converting some codes from excel vba to c and run into this problem i am not sure the equivalent of this code in c intellisence was not very helpful selectionshaperangeadjustmentsitem1 90i managed to get as far as adjustment in c but there is no item property,['c#'] +874213,what is the right way to implement sync and async methods in a library i need to make a library in which i will have synchronous and asynchronous featureexecutesynchronous waits until i have a result returns the resultexecuteasynchronous returns a future immediately which can be processed after other things are done if neededcore logic of my librarythe customer will use our library and they will call it by passing datakey builder object we will then construct a url by using that datakey object and make a http client call to that url by executing it and after we get the response back as a json string we will send that json string back to our customer as it is by creating dataresponse object some customer will call executesynchronous and some might call executeasynchronous method so that is why i need to provide two method separately in my libraryinterfacepublic interface client for synchronous public dataresponse executesynchronousdatakey key for asynchronous public futuredataresponse executeasynchronousdatakey keyand then i have my dataclient which implements the above client interfacepublic class dataclient implements client private resttemplate resttemplate new resttemplate private executorservice executor executorsnewfixedthreadpool10 for synchronous call override public dataresponse executesynchronousdatakey key dataresponse dataresponse null futuredataresponse future null try future executeasynchronouskey dataresponse futuregetkeygettimeout timeunitmilliseconds catch timeoutexception ex potologginglogerrorsex dataerrorenumtimeout on client key dataresponse new dataresponsenull dataerrorenumtimeout on client datastatusenumerror catch exception ex potologginglogerrorsex dataerrorenumclient error key dataresponse new dataresponsenull dataerrorenumclient error datastatusenumerror return dataresponse for asynchronous call override public futuredataresponse executeasynchronousdatakey key futuredataresponse future null try task task new taskkey resttemplate future executorsubmittask catch exception ex potologginglogerrorsex dataerrorenumclient error key return future simple class which will perform the actual taskpublic class task implements callabledataresponse private datakey key private resttemplate resttemplate public taskdatakey key resttemplate resttemplate thiskey key thisresttemplate resttemplate override public dataresponse call dataresponse dataresponse null string response null try string url createurl response resttemplategetforobjecturl stringclass it is a successful response dataresponse new dataresponseresponse dataerrorenumnone datastatusenumsuccess catch restclientexception ex potologginglogerrorsex dataerrorenumserver down key dataresponse new dataresponsenull dataerrorenumserver down datastatusenumerror catch exception ex potologginglogerrorsex dataerrorenumclient error key dataresponse new dataresponsenull dataerrorenumclient error datastatusenumerror return dataresponse create a url by using key object private string createurl string url somecode return url customer within our company will use my library like this as shown below by using my factory in their code base if they are calling executesynchronous methoddataresponse response dataclientfactorygetinstanceexecutesynchronousdatakey and if they want to call executeasynchronous methodfuturedataresponse response dataclientfactorygetinstanceexecuteasynchronousdatakeywhat is the best way to implement sync and async method for my library does implementing sync call as async waiting is a bad idea because it will consume one thread from the thread pool per a call with my curent setup if yes then can anyone explain why it is a bad idea and will it have any performance issuehow will you implement sync and async method given the above criteria what is the best way to do this this library will be used under very heavy load and it has to be fast meaning it should take time whatever my server is taking to respondshould i use asyncresttemplate in my code base which will be async nonblocking architecture,['java'] +874276,android with gradle java finished with nonzero exit value 2 this is my gradle fileapply plugin comandroidapplicationandroid compilesdkversion 21 buildtoolsversion 2112 defaultconfig applicationid comtesttest minsdkversion 15 targetsdkversion 21 versioncode 1 versionname 10 buildtypes release minifyenabled false proguardfiles getdefaultproguardfileproguardandroidtxt proguardrulespro packagingoptions exclude metainflicensetxt exclude metainflicense exclude metainfnoticetxt exclude metainfnotice dependencies compile filetreedir libs include jar compile comandroidsupportappcompatv72103 compile commcxiaokevolleylibrary1015 compile orgglassfishjerseymediajerseymediajsonjackson217when i try to run my android app i get the next errorerrorexecution failed for task appdexdebugcomandroididecommonprocessprocessexception orggradleprocessinternalexecexception process command usrlibjvmjava8oraclebinjava finished with nonzero exit value 2i get this error when i add to gradle file the jackson library googling some time i have found that jackson library is compatible with android apps and it is faster than other libraries as gsonhow i can solve iti am an android beginner,['android'] +874331,jquery validation addmethod not working i have a div in jsp as follows input typetext idyear placeholder year classyear name year valuei want to calculate the difference between current year and entered year i have to show the error if the value does not lie within some range this is my custome jquery validator functionjqueryvalidatoraddmethodvalidage function value element params alertinside add method var currentyear new dategetfullyear var range currentyear elementval ifrange 10 range 70 return true return falsebut it is showing error at elementvali have defined the rule as signup formvalidate initialize the plugin rules year validage true messages year invalid year,"['javascript', 'jquery']" +874353,match a class by parameter type in a c templategenerated class hierarchy introi am working on a custom memory allocator and need to add some bookkeeping info to the header of each allocated chunk there are several different chunk types and the bookkeeping info differs as well for instance for chunks shared between threads there is a need to add a reference counter for chunks used by single thread there is no such need for chunks taken from a memory pool there is a need to keep a reference to the originating pool for chunks taken from the free store there is no such needproblemso i would like to have a generic interface to add and get certain data types for a given chunk layout experimenting with this idea i came to a solution that is similar to stdtuple however unlike tuples every type i add to the header is going to be unique i just started to learn template metaprogramming and other intricacies of c however the part with adding a type was straightforward for methe problem i came across is implementing a method similar to c14 stdget by type template function for tuples i figured there is no need to write much code for this as the compiler is able to match the correct base class in a method call at first i put the get method right into templategenerated layout class however the compiler fails to match the correct class in this case the problem was solved by moving the get method to another manually added level of class hierarchythe code below demonstrates the problem defining have get in layout to 0 produces a working solution while defining it to 1 produces a broken solution at least with clang 35 and 36the question is what is broken in this caseinclude cstddefinclude iostreamifndef have get in layoutdefine have get in layout 0endifconstexpr stdsize t alignstdsize t size stdsize t offset return size 0x8 offset 0x3 0x3 size 0x10 offset 0x7 0x7 offset 0xf 0xftemplate stdsize t start typename ts struct layout static constexpr stdsize t size 0 static constexpr stdsize t offset start static constexpr stdsize t totalsize starttemplate stdsize t start typename t typename tsstruct layoutstart t ts public layoutalignsizeoft start sizeoft ts using type t static constexpr stdsize t size sizeoftype static constexpr stdsize t offset alignsize start static constexpr stdsize t totalsize layoutoffset size tstotalsize type value offset start no particular meaning just for testingif have get in layout template typename u stdsize t x typename us you helperlayoutx u us c return cvalue template typename u you get return helperuthis endiftemplate typename ts struct result public layout0 ts if have get in layout template typename u stdsize t x typename us you helperlayoutx u us c return cvalue template typename u you get return helperuthis endifint main stdcout layout size layout0totalsize stdendl stdcout layout size int layout0 inttotalsize stdendl stdcout layout size long layout0 longtotalsize stdendl stdcout layout size intint layout0 int inttotalsize stdendl stdcout layout size intlong layout0 int longtotalsize stdendl stdcout layout size longint layout0 long inttotalsize stdendl stdcout layout size longlong layout0 long longtotalsize stdendl stdcout get resultint long long doublegetlong stdendl return 0,['c++'] +874398,android alarmmanager sometimes triggers late if phone runs on battery updated the issue has likely been resolved please refer directly to the update below as alarmmanager was only partially to blame i am currently developing an android app with alarm clock functionality unfortunately it turned out that there seem to be rather specific cases for which alarmmanager does not seem to work as expected when i initially tested the app i did so by means of the android studio emulator nexus 5 api 21 as well as an old phone of mine galaxy s2 api 16 with the result that all alarms were delivered in time as soon as i switchedto my xperia z1 compact api 19 though alarms suddenly triggered minutes late occasionally interestingly this seems to be the case especially when the phone is currently running on battery ie not connected to the pc or an outlet it kind of feels like alarmmanager would suddenly act super sluggish in a desperate attempt to spare the battery completely oblivious to the fact that it was utilized by means of setexact if the device is not asleep delivery is always in timeeither way the behaviour that results from my code does not seem to be deterministic at all which is what really boggles my mindsimplified version of my codefirst i schedule alarmmanager depending on the api according to the logs calendar is set to the correct date and timepublic abstract class alarmscheduler private static void schedulealarmmanager am pendingintent pi calendar calendar if androidosbuildversionsdk int androidosbuildversion codeskitkat amsetexactalarmmanagerrtc wakeup calendargettimeinmillis pi else amsetalarmmanagerrtc wakeup calendargettimeinmillis pi the pending intent that is scheduled is a wakefulbroadcastreceiver according to the logs every time the alarm is late the call ofonreceive is as well at least as far as i have seen so it seems likely that the problem is located herepublic class alarmreceiver extends wakefulbroadcastreceiver override public void onreceivecontext context intent intent intent service new intentcontext alarmserviceclass serviceputextrasintent startwakefulservicecontext service for completeness this is the service that is started by the broadcastreceiver the activity that the service starts acquires its own wakelock in onresume i have also tried to forcefully delay the release of the receiver wakelock up to 10 ms in order to guarantee that one is active at all times but that did not yield different resultspublic class alarmservice extends service override public ibinder onbindintent intent return null override public int onstartcommandintent intent int flags int startid intent alarmthisplay new intentgetbasecontext alarmactivityclass alarmthisplayaddflagsintentflag activity new task alarmthisplayputextrasintent getapplicationstartactivityalarmthisplay some simple database operations here alarmreceivercompletewakefulintentintent return superonstartcommandintent flags startid i am honestly kind of lost where i did go wrong here but since an alarm clock that might trigger minutes late on some devices is not acceptable of course i wouldreally appreciate any input thanks in advanceupdatealright so first of all alarmmanagersetexact does indeed seem to deliver late occasionally but only for seconds not minutes according to the documentation this seems to be intended as it states the alarm will be delivered as nearly as possible to the requested trigger timeunfortunately this does sound like a matter of milliseconds rather than seconds which is why i did assume that alarmmanager was behaving faultily in the first place if it was evidently delivering seconds late i thought it capable of delivering minutes late as well still my mistake ultimatelysecondly the issue described initially was a wakelock issue that at least in my case did only show on my api 19 phone when it was currently running on battery while api 19 apparently introduced very aggressive power management for the sake of battery life the management appears to be even more aggressive if the phone is running on battery this seems also to be the reason why on the emulator everything was behaving normal per default it is always in the process of being charged if the icons are to be believedthe problem with the code initially posted is that the receiver wakelock is released before the activity acquires its own wakelock in onresume just a matter of milliseconds but still sufficient for the cpu to be pushed back to sleep apparently as i did state in my original post i already thought of this as a potential source of the problem which is why i did try to forcefully delay the release of the wakelock in order to guarantee that at least one would be active at all times for testing purposes i did this quick dirty by means of wait though which the os seemingly was not very fond of and thus forcefully shut down my service at some point which was something that did not show in regular logcat output from this point on subsequent alarms tended to be faulty although i am not sufficiently knowledgeable in terms of android to actually explain whyeither way the issue could be resolved by acquiring and releasing only one single wakelock instead of two separate ones please mind that due to the very nature of the problem there is no absolute certainty but testing results are looking fine,['android'] +874485,meteor collection document ids randomid or meteorcollectionobjectid when i insert documents into my meteor collections they have an id with the form of randomidrandomid wjqyq6sgjzvnmdlijwhen i insert documents into those same collections directly from mongodb they have an id in the form of meteorcollectionobjectidnew meteorcollectionobjectid localcollection objectid str b105582bc495617542af18e9awhy does my app use randomid is this a legacy settingmeteor versions when i created my app,['javascript'] +874619,laravel 5 mutators only work when i create a record and not when i update a record hi i have created a mutator to only store digits on my phone numbers here is my code in my profile modelpublic function setphoneattributephone thisattributesphone preg replace09phonethis works when i create a new record but if i update the record it does not work my question is how do i execute the mutator on both create and updatehere is how i update and create in my controllernamespace apphttpcontrollersuse apphttprequestsuse apphttprequestsprofilerequestuse apphttpcontrollerscontrolleruse illuminatehttprequestuse authuse aprofileclass profilecontroller extends controller public function createprofilerequest request check if the user does not have a profile yet ifauthuserprofilefirst save to database savetodatabase authuserprofilecreaterequestall return savetodatabase public function updateprofile profile profilerequest request save to database savetodatabase authuserprofileupdaterequestall return savetodatabase,['php'] +874635,how to transition smoothly from translucent to opaque uinavigationbar ios i am running into problems reconfiguring the uinavigationbar on ios 7 and 8 when transitioning between viewsmy application currently contains the following uiviewcontroller flowvc1 vc2 vc3in this flowvc1 is the home screen and has an opaque uinavigationbarvc2 has a translucent uinavigationbarvc3 goes back to having an opaque uinavigationbarthe problem i have been running into is that the transitions between these views are all very sloppy looking to start with i tried the followingin vc2 voidviewwillappearboolanimated super viewwillappearanimated configure appearance selfnavigationcontrollernavigationbar configuretranslucentappearanceand in vc1 and vc3 voidviewwillappearboolanimated super viewwillappearanimated configure appearance selfnavigationcontrollernavigationbar restoredefaultappearancehere are the implementations of the two helper functions listed above voidrestoredefaultappearance uiapplication sharedapplication setstatusbarstyleuistatusbarstylelightcontent self settitletextattributesnsforegroundcolorattributename uicolor jttextnavbar self settintcoloruicolor jttextnavbar self setbartintcoloruicolor jtbackgroundnavbarwithalpha10 self setbackgroundimagenil forbarmetricsuibarmetricsdefault self setbackgroundcoloruicolor jtbackgroundnavbarwithalpha10 self setshadowimageuiimage navigationbarshadowimage self settranslucentno voidconfiguretranslucentappearance uiapplication sharedapplication setstatusbarstyleuistatusbarstylelightcontent self setbackgroundimageuiimage new forbarmetricsuibarmetricsdefault self setbackgroundcoloruicolor clearcolor self setshadowimageuiimage new self settranslucentyesthis is the most basic way of handling this transition it has the following visual artefactswhen going from vc1 vc2 the moment you begin the transition the navigation bar turns black the animation completes normally when going from vc2 vc1 the nav bar instantly changes to the application default colour before the segue has time to complete when going from vc2 vc3 the navigation bar instantly goes from translucent to the app nav bar color and then menu items and vc body animate in when going from vc3 vc2 the nav bar instantly turns black and remains this way until the segue is complete none of these transitions look good at all ideally i would like the views to transition smoothly along with their new uinavigationbar but the only way i have seen to do this successfully is to manually add a toolbar to each xibany suggestions apologies if this description is confusing edit added cropped images of the uinavigationbar and top portion of uiviewcontroller for each of the listed transitions,"['ios', 'objective-c']" +874654,sailsjs get many to many association count i have a model user that has an association with another model phone this association is many to many the following call is built in to sails and allows me to get all the phone records for a particular userget useruseridphonesi would like to be able to implement pagination on that call but cannot figure out how to get the total number of results i have tried overwriting the blueprints findjs andor findonejs in order to return the count but the call above does not seem to run through that logic,['javascript'] +874690,is there any larger significance to this piece of translated assembly code for a short homework assignment in cs architecture we were made to translate the following ia32 assembly into c i have translated it properly as far as i know but the code does not appear to do anything particularly useful my professor typically gives us problems like this which end up doing something our last assignment like this was a bit pop count looking at the c code below does this function do anything useful some algorithm maybethe code appears below i have added comments to each asm line the following variables x y z are located at ebp 8 12 16 respectively x y and z are scanned from the terminal and passed into the function movl 12ebp edx moves long y to register edx subl 16ebp edx subtracts longs y y z movl edx eax moves long y to register eax sall 31 eax left shift all bits in long y by 31 places sarl 31 eax arithmetic right shift long y by 31 places imull 8ebp edx multiply longs unshifted y y x xorl edx eax xor operation shifted y shifted y unshifted y the returned value is stored in register eaxthe effective takeaway is we subtract z from y then populate every bit with the least significant bit to form either zero or max uint this is xord with the product of y z x and returnedmy translation into creturn y z 31 31 y z x in more words int f y z f y 31 these two lines populate all bits with the lsb f f 31 effectively if yz is odd f is 0 else f is 0 y x return y f or using people logic y z if y 2 0 return y x return y x 1 if the yz is odd the result will be 1 y z x 1 if the yz is even the result will be y z xfor clarification this is not part of the hw assignment i have completed the assignment by translating the code but i am interested in knowing why he gave us this code to begin with,['c'] +874721,django rest framework 3 serializers on nonmodel objects i am doing an upgrade to drf311 from 24 i was using a custom serializer to create an instance of an object that is not a modelin 24 it was easy enough to do this because in the serializer i would create the object in restore object in the view i would call serializeris valid and then pop the instance of the object out of the serializer with serializerobject then i could do whatever i wantwith the 3x changes it is harder to get the instance out of the object because the create and update methods are supposed to do the saving and serializerobject is not available anymoreas an example i used to have this for my userregistration object this is not a model because it is a convenience object that the server parses up and stores data in a number of other objectsdb tablesclass userregistrationobject def init self full name stage name password email localeen us selffull name full name selfpassword password selflocale locale selfemail email selfstage name stage nameheres the associated drf24 serializerclass userregistrationserializerserializersserializer full name serializerscharfieldmax length128 requiredfalse stage name serializerscharfieldmax length128 password serializerscharfieldmax length128 requiredfalse locale serializerscharfieldmax length10 requiredfalse use charfield instead of emailfield for email we do our own validation later to make for a better error msg email serializerscharfieldmax length254 requiredfalse def restore objectself attrs instancenone if instance is not none instancefull name attrsgetfull name instancefull name instancepassword attrsgetpassword instancepassword instancelocale attrsgetlocale instancelocale instanceemail attrsgetemail instanceemail instancestage name attrsgetstage name instancestage name return instance return userregistrationattrsthen in my view i do something like thisclass userregistrationapiview throttle classes serializer class userregistrationserializer def postself request formatnone event type user registration serializer userregistrationserializerdatarequestdata contextrequest request try if serializeris valid user registration serializerobject save user registration pieces in various placeshowever in drf3 i serializerobject is gone the docs say to do validation using serializervalidated data but that is just a hash and not the real object is there a way to get the object the whole thing seems more married to db objects which in this particular case is exactly what i am trying to avoidam i just missing some new drf3 concept,['python'] +874724,why does a conditional variable fix our power consumption we were working on our audio player project on mac and noticed that the power usage was so high about 7x that of google chrome doing the same workloadi used xcodes energy profiling tool one of the problems was we had too much cpuwake overheadaccording to xcodeeach time the cpu wakes from idle there is an incurred energy penalty if the wakes are high and the cpu utilization per wake is low then you should consider batching workwe had narrowed down the problem to a usleep function callin our code the audio decoder is a producer that produces audio data and inserts them into the consumer the audio player our audio player is base on openal which has a buffer for the audio databecause the audio player can be slower than the producer we always check the buffer availability before giving a new audio data to the audio player if no buffer is available we usleep for a while and try again so the code looks likevoid playaudiobufferdata data whileno buffer is available usleep process dataknowing that usleep is a problem the first thing we did was simply removing usleep because openal does not seem to provide callback or any other way polling seems to be the only option we successfully reduced the power usage by half after doing this then yesterday we tried forint i 0 iattempts i stdunique lockstdmutex lkm cvwait forlk 3 available checkbufferavailable return available if available process buf this is an experiment we tried by accident it does not really make sense to us as logically it performs the same wait and the use of the conditional variable is not correct because the variable available is only accessed by one thread but it actually reduced our energy consumption by 90 the cpu usage of the thread dropped a lot now we are better than chrome but how is conditional variable implemented differently than the following code why does it save us powermutex lockwhilecondition is false mutex unlock usleep mutex lockmutex unlockwe use macs activity monitor energy number and cpu usage profiling tool to measure the energy consumption,['c++'] +874737,get the class name of es6 class instance are there any harmonious ways to get the class name from es6 class instance other thansomeclassinstanceconstructornamecurrently i am counting on traceur implementation and it seems that babel has a polyfill for functionname while traceur does notto sum it all up there was no other way in es6es2015harmony and nothing is expected atm in esnextit may provide useful patterns for unminified serverside applications but is unwanted in applications meant for browserdesktopmobilebabel uses corejs to polyfill functionname it should be loaded manually for traceur and typescript applications as appropriate,['javascript'] +874797,android studio not deploying changes to app sometimes this scenario occurs when developing i would make a change in my source code hit save all and then run but the change wouldnt be apparently not reflected in the app i am using a device for testing i can even uninstall the app on my device and hit run again and the newly installed app still has not reflected the change in the source code when this happens i have to edit the source hit run and maybe then a new version with the changes i expected will be on the device i also tried the solution here but it does not seem to work often android studio deploys my app without new changes,['android'] +874803,i entered mvn command in windows but the command line return a java hint i have maven 331 and java 17 installed on my machine windows 81maven homecprogram filesapacheapachemaven331java homecprogram filesjavajdk170 75pathjava homebinjava homejrebinmaven homebini have tried to access mvn command line under cusersmyusername it works wellcusersmyusernamejava versionjava version 170 75javatm se runtime environment build 170 75b13java hotspottm 64bit server vm build 2475b04 mixed modecusersmyusernamemvn versionapache maven 331 cab6659f9874fa96462afef40fcf6bc033d58c1c 20150313t1310270700maven home cprogram filesapacheapachemaven331binjava version 170 75 vendor oracle corporationjava home cprogram filesjavajdk170 75jredefault locale en us platform encoding gbkos name windows 81 version 63 arch amd64 family windowsbut when i change the command path to d another thisk in my machine the output becomesdmvn versionusage java options class args to execute a class or java options jar jarfile args to execute a jar filewhere options include d32 use a 32bit data model if available d64 use a 64bit data model if available server to select the server vm hotspot is a synonym for the server vm deprecated the default vm is server cp class search path of directories and zipjar files classpath class search path of directories and zipjar files a separated list of directories jar archives and zip archives to search for class files dnamevalue set a system property verboseclassgcjni enable verbose output version print product version and exit versionvalue require the specified version to run showversion print product version and continue jrerestrictsearch nojrerestrictsearch includeexclude user private jres in the version search help print this help message x print help on nonstandard options eapackagenameclassname enableassertionspackagenameclassname enable assertions with specified granularity dapackagenameclassname thisableassertionspackagenameclassname thisable assertions with specified granularity esa enablesystemassertions enable system assertions dsa thisablesystemassertions thisable system assertions agentliblibnameoptions load native agent library libname eg agentlibhprof see also agentlibjdwphelp and agentlibhprofhelp agentpathpathnameoptions load native agent library by full pathname javaagentjarpathoptions load java programming language agent see javalanginstrument splashimagepath show splash screen with specified imagesee for more detailsdjava versionjava version 170 75javatm se runtime environment build 170 75b13java hotspottm 64bit server vm build 2475b04 mixed modebesides when i use intellij to create maven project just like quickstart the similar error happeneddmavenmultimoduleprojectdirectory system propery is not set check m2 home environment variable and mvn script matcherror maven execution terminated abnormally exit code 1i have tried like mvn version mvn d but they still do not workcould anyone please help thanksupdatednow my environment variables is set tojava homecprogram filesjavajdk170 75classpathjava homelibdtjarjava homelibtoolsjarm2 homecprogram filesapacheapachemaven331maven homecprogram filesapacheapachemaven331pathjava homebinm2 homebinothersand the problem still existsupdatedwhenever i type after mvn command in d path the command line will just return java hint it seems all the things after mvn are ignoredjust like thisdmvn fewadsfeusage java options class args to execute a class or java options jar jarfile args to execute a jar filewhere options include d32 use a 32bit data model if available d64 use a 64bit data model if available server to select the server vm hotspot is a synonym for the server vm deprecated the default vm is server cp class search path of directories and zipjar files classpath class search path of directories and zipjar files a separated list of directories jar archives and zip archives to search for class files dnamevalue set a system property verboseclassgcjni enable verbose output version print product version and exit versionvalue require the specified version to run showversion print product version and continue jrerestrictsearch nojrerestrictsearch includeexclude user private jres in the version search help print this help message x print help on nonstandard options eapackagenameclassname enableassertionspackagenameclassname enable assertions with specified granularity dapackagenameclassname thisableassertionspackagenameclassname thisable assertions with specified granularity esa enablesystemassertions enable system assertions dsa thisablesystemassertions thisable system assertions agentliblibnameoptions load native agent library libname eg agentlibhprof see also agentlibjdwphelp and agentlibhprofhelp agentpathpathnameoptions load native agent library by full pathname javaagentjarpathoptions load java programming language agent see javalanginstrument splashimagepath show splash screen with specified imagesee for more details,['java'] +874869,spring data facet does not work in intelij 14 right now i am in progress of setup rest api template i want to use spring boot with spring data integration everyting works nice but i would like to take an advantages in intelij 14 spring data plugin and enable autocompletion on ie findbyfirstname i try to achieve something like in this intelij 11 demo any suggestion how to enable spring data plugin in existing projectmy current configurationspringbootapplicationpublic class application public static void mainstring args springapplicationrunapplicationclass args configurationenabletransactionmanagementenablejparepositoriescomtestrepositorypublic class testdatabaseconfiguration bean public datasource datasource return new embeddeddatabasebuildersettypeembeddeddatabasetypeh2build bean public localcontainerentitymanagerfactorybean entitymanagerfactory localcontainerentitymanagerfactorybean entitymanagerfactorybean new localcontainerentitymanagerfactorybean entitymanagerfactorybeansetdatasourcedatasource entitymanagerfactorybeansetjpavendoradapternew hibernatejpavendoradapter entitymanagerfactorybeansetpackagestoscancomtestentities entitymanagerfactorybeansetjpapropertiesjpaproperties return entitymanagerfactorybean private properties jpaproperties properties properties new properties propertiessetpropertyhibernatehbm2ddlauto createdrop propertiessetpropertyhibernatedialect orghibernatedialecth2dialect propertiessetpropertyhibernateshow sql false propertiessetpropertyhibernateformat sql false return properties bean public jpatransactionmanager transactionmanager jpatransactionmanager transactionmanager new jpatransactionmanager transactionmanagersetentitymanagerfactoryentitymanagerfactorygetobject transactionmanagersetdatasourcedatasource return transactionmanager,['java'] +874943,gem install rails fails on ubuntu the error messagebuilding native extensions this could take a whileerror error installing rails error failed to build gem native extension usrbinruby21 r siteconf201503281540hff2f0rb extconfrbchecking if the c compiler accepts extconfrb failed could not create makefile due to some reason probably lack of necessarylibraries andor headers check the mkmflog file for more details you mayneed configuration optionsprovided configuration options withoptdir withoutoptdir withoptinclude withoutoptincludeoptdirinclude withoptlib withoutoptliboptdirlib withmakeprog withoutmakeprog srcdir curdir rubyusrbinruby21 help cleanusrlibruby210mkmfrb456in try do the compiler failed to generate an executable file runtimeerroryou have to install development tools first from usrlibruby210mkmfrb571in block in try compile from usrlibruby210mkmfrb522in with werror from usrlibruby210mkmfrb571in try compile from extconfrb80in nokogiri try compile from extconfrb87in block in add cflags from usrlibruby210mkmfrb621in with cflags from extconfrb86in add cflags from extconfrb337in mainextconf failed exit code 1gem files will remain installed in varlibgems210gemsnokogiri1662 for inspectionresults logged to varlibgems210extensionsx86 64linux210nokogiri1662gem makeoutconfigurationsubuntu 1410 gnulinux 316023generic x86 64gcc ubuntu 49116ubuntu6 491ruby 212p95 20140508 x86 64linuxgnu,"['ruby-on-rails', 'ruby']" +875023,are names in the c standard library meant to be in british english or american english after a quick search in draft n4296 i could not find any example of a name in the c standard library for which two possible spellings exists bre vs amewhile this may even be intentional i can imagine that at some point if a graphics library will be standardized and there seems to be some effort going in this direction the choice between colour and color will have to be madeare there normative regulations or perhaps even informal criteria that are being used to decide which spelling to pick for names in the c standard library,['c++'] +875122,reference to method is ambiguous when using lambdas and generics i am getting an error on the following code which i believe should not be there using jdk 8u40 to compile this codepublic class ambiguous public static void mainstring args consumerintfunctiontestdata arrayssortdata intnew consumerintfunctiontestarrayssort intnew private static t void consumerintfunctiontestfinal consumert consumer final intfunctiont generator private static t void consumerintfunctiontestfinal functiont consumer final intfunctiont generator the error is the followingerror17 9 java reference to consumerintfunctiontest is ambiguous both method consumerintfunctiontestjavautilfunctionconsumerjavautilfunctionintfunction in nettuisubenchambiguous and method consumerintfunctiontestjavautilfunctionfunctionjavautilfunctionintfunction in nettuisubenchambiguous matchthe error occurs on the following lineconsumerintfunctiontestarrayssort intnewi believe there should be no error as all arrayssort references are of type void and none of them return a value as you can observe it does work when i explicitly expand the consumert lambdais this really a bug in javac or does the jls state that the lambda cannot automatically be expanded in this case if it is the latter i would still think it is weird as consumerintfunctiontest with as first argument functiont should not match,['java'] +875176,creating a favorite feature on a list of questions that get randomized i am having a hard time correctly implementing a favorites feature for my app moving through a list of objects the user should be able to checkuncheck something as a favorite once the activity moves into the onpause state it should save the list of favorites rather the complete list of boolean markers that signal whether something is a favorite or not true for favorite false for not a favorite obviously upon moving into the onresume state the list should be loaded so they can view the favorites that they have previously markedmy issue i think truly comes from the fact that the list is randomized upon initialization i am sure my algorithm is off but i have tried various ways to the point where i can hardly bare to look at it anymoremain activity javapublic class mainactivity extends actionbaractivity global global mainoverrideprotected void oncreatebundle savedinstancestate global main globalgetinstancealloverrideprotected void onresume superonresume sharedpreferences settings getsharedpreferencesfile favorites 0 forint index 0 index total questions index boolean favfromfile settingsgetbooleansavedfavorite stringvalueofindex false global mainsetfavindex favfromfile overrideprotected void onpause superonpause sharedpreferences settings getsharedpreferencesfile favorites 0 sharedpreferenceseditor editor settingsedit forint index 0 index total questions index editorputbooleansavedfavorite stringvalueofindex global maingetfavindex commit the edits editorcommit practice javaoverrideprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate intent intent getintent selectedsection intentgetstringextrachoosesectionchosensection global globalgetinstanceselectedsectionglobal classpublic class global private static global global nullcurrent total of questions which the user has chosenex if multiplication was chosen and has 10 questions in the arraythen this equals 10int current totalthis is the position that the first question of the users choice starts withex if user chooses multiplication and the multiplication questions start at questions19then this equals 19int current startthis is the position that the last question of the users choice ends withex if user chooses multiplication and the multiplication questions end at questions24then this equals 24int current endbasic question structureclass questionstruct string q string a int position original position in the array boolean favoritearray of question structuresquestionstruct questions new questionstructtotal questionsuserchoice is the choice of question type that the user has selectedex multiplication division addition subtraction or alldefaultpublic static global getinstancestring userchoice ifglobal null global new global globalinitialize globalgetchoiceuserchoice globalsetquestionsdefault globalrandomize return globalpublic void initialize for int i 0 i total questions i questionsi new questionstruct questions0q question 1 text questions0a answer questions0position 0 questions1q question 2 text questions1a answer questions1position 1 questions2q question 3 text questions2a answer questions2position 2 etc etc etcpublic void setquestionsdefault questionstruct temp new questionstruct forint index 0 index total questions index int count questionsindexposition temp questionscount questionscount questionsindex questionsindex temp temp null randomize the questions only within the range of the categorywhich the user has chosenpublic void randomize forint index current end index current start index generate random number to switch with random block random rand new random int currentq randnextintcurrent end current start 1 current start switch two question blocks questionstruct temp questionscurrentq questionscurrentq questionsindex questionsindex temp public void setfavint q boolean b questionsqfavorite bpublic boolean getfavint q return questionsqfavoritethat might be everything pertinent to my issues i apologize if i left anything out or if something does not make sense feel free to ask questions i am still currently in the middle of altering everything to get it to work so i might have copied over something that does not quite add upedit i will also add the code for the favorite button click to turn a favorite into a nonfavorite and vise versa even though it is critical to having this work it is not something i was worried about functioning properly because it is so simple but if someone feels they would like to see it and in turn help me out then here it isthis is also in the practice questions java filepublic void setfavoritebutton ifglobalgetfavtempqq favoritesetbackgroundcolorcoloryellow else favoritesetbackgroundcolorgetresourcesgetcolorrcolorprimary overridepublic void onclickview v switchvgetid case ridfavorite updatefavorite break public void updatefavorite ifglobalgetfavtempqq globalsetfavtempqq false else globalsetfavtempqq true setfavoritebuttonedit i might should add that i believe the issue is algorithmic if i did not have the randomize feature in conjunction with the favorites i would be fine i think but i think both are important for my app to be very useful so that is where my focus is at trying to implement a favorites feature at the same time while keeping the randomization each time the global is called,"['java', 'android']" +875448,specifying locale for string interpolation in c6 roslyn ctp6 string interpolation in c6 lets me writedecimal m 420mstring x the value is mhowever a very common use case for string formatting is to specify the locale used for formatting the values let us say i need to use invariantculture for the formatting operation above what is the syntax for that this thiscussion suggests that i should be able to do thisstring x invthe value is mwhere inv is defined aspublic static string inviformattable formattable return formattabletostringnull systemglobalizationcultureinfoinvariantculturehowever this does not work it compiles but it leaves my program hanging at in cmdexe at startup as if klrexe that i assume is being invoked hangs compiler bugthis is an aspnet 5 console project in vs15 ctp 6,['c#'] +875606,using byte short and other primitive types why is it that i do not see them quite frequently i only see them mostly for networking where size really does matter but for example i have a variable that only uses numbers from the range 110 should not i use byte i am used to coding cc using as small memory as possible why is not it like this in java,['java'] +875670,android l 5x turn onoff mobile data programmatically i need to turn onoff mobile data programmatically below code is not working for 5x can you please help me thanks in advanceprivate void setmobiledataenabledcontext context boolean enabled throws classnotfoundexception nosuchfieldexception illegalaccessexception nosuchmethodexception invocationtargetexception final connectivitymanager conman connectivitymanager contextgetsystemservicecontextconnectivity service final class conmanclass classfornameconmangetclassgetname final field connectivitymanagerfield conmanclassgetdeclaredfieldmservice connectivitymanagerfieldsetaccessibletrue final object connectivitymanager connectivitymanagerfieldgetconman final class connectivitymanagerclass classfornameconnectivitymanagergetclassgetname final method setmobiledataenabledmethod connectivitymanagerclassgetdeclaredmethodsetmobiledataenabled booleantype setmobiledataenabledmethodsetaccessibletrue setmobiledataenabledmethodinvokeconnectivitymanager enabled 0330 124229466 wsystemerr5966 javalangnosuchmethodexception setmobiledataenabled boolean 0330 124229466 wsystemerr5966 at javalangclassgetmethodclassjava664 0330 124229466 wsystemerr5966 at javalangclassgetdeclaredmethodclassjava626javalangnosuchmethodexception setmobiledataenabled boolean below linefinal method setmobiledataenabledmethod connectivitymanagerclassgetdeclaredmethodsetmobiledataenabled booleantype,['android'] +875768,cant set host in curl php i am unable to set the host in curl it still shows as localhost if i use the following codefunction wgeturl agent mozilla50 windows nt 63 wow64 rv350 gecko20100101 firefox3501 curlheaders array accept texthtmlapplicationxhtmlxmlapplicationxmlq09q08 acceptencoding gzip deflate acceptlanguage enusenq05 useragent mozilla50 windows nt 63 wow64 rv350 gecko20100101 firefox3501 connection keepalive pragma nocache referer host hostname cachecontrol nocache cookie visid incap 1859899v1q8ar0tosoja48brmb8nn1gfuaquipabcrwagbdifmln9ntrcvrct incap ses 108 185989z1ory6bd0z3ngye2lbjaxn1gfuamb41mjmlfcjb1rtif28mg gaga136374689271427699070 gat1 frontendrqg7g9hp2ht788l309m7gk8qi7 gat ua1279175121 utma2339114376374689271427699070142769907814276990781 utmb2339114372101427699078 utmc233911437 utmz233911437142769907811utmcsrdirectutmccndirectutmcmdnone utmt ua127917511 cb ls1 chartbeat2s0wvxdwmwncfbgqp142769908132214276992327861 prum episodess1427699568560rhttp3aexamplecom ch curl init curl setopt ch curlopt httpheader curlheaders curl setopt ch curlopt header true curl setoptch curlopt returntransfer true curl setoptch curlopt useragent agent curl setoptch curlopt urlurl resultcurl execch return result i use fiddler to track the network requests where i found the host is still as localhostif i load this same link in browser i get as following in fiddleri need my specified domain to be accessed how can i achieve thisnote i am aware that host name should not contain the protocolalternativelyalso i would like to know is it possible to get the source code of a website the could be seen in browser through terminal,['php'] +875886,template nontype arguments for reference type and odrused is the variable v in the sample code below odrusedextern void vtemplatevoidvoid f int main fvi found this pattern in boost mlcf it says that the boostenabler is never defined but clang rejects it as a linkage error if g option is providedcf the sample code above is reduced version of the boost mls code and clang rejects it toocf i think but i am not sure that template nontype arguments for reference type are odrused even if they are not referred in their template body so the boost mls pattern is illformedis my understanding correct,['c++'] +875999,why is stdseed seq noncopyable according to c11 and why does not gclang conform consider the following minimal example maincppinclude randomint mainint char stdseed seq seed11337 42 stdseed seq seed2seed1 stdseed seq seed3 seed2 return 0according to the c standard this should not compile as stdseed seq is neither copy constructible nor copy assignablehowever this compiles fine with both g 49 and clang 34g49 stdc11 wall maincppclang stdc11 wall maincppthe android ndks llvmlibc implementation seems to follow the not copyable property of seed seq which can be confirmed in the source at androidndkr10dsourcescxxstlvmlibclibcxxincluderandom3553or by compiling the minimal example using ndk hometoolchainsarmlinuxandroideabi49prebuiltlinuxx86 64binarmlinuxandroideabig stdc11 c wall indk homesourcescxxstlvmlibclibcxxinclude indk homesourcescxxstlvmlibcllvmlibcabilibcxxabiinclude indk homesourcescxxstlvmlibcandroidsupportinclude isystem ndk homeplatformsandroid18archarmusrinclude maincppi have previously used this without being aware of my nonconforming code to store a copy of the seed for logging purposesi am left wonderingwhy it is that seed seq is not copyablethis is the first time i have encountered g and clang to not conform to the standard is it a conscious decision to deviate from the standard or is this an implementation bug how prevalent is this i would like to learn more i realized that i was thinking of seed seq wrong and that if i am only interested in the seed seqparam values the seed seeqs initial seed values that i should instead keep my copy in a vectort instead of a type that is meant to generate integers,['c++'] +876101,very strange windbg output for windows store 81 app i have got a debug dump available at which gives me very strange output i tried doing standard windbg stuff and got nothing useful so i tried pdedll and got the following pde v95 copyright 2014 andrew richardsstart memory scan 0x0552e634 cspend memory scan 0x05530 user stack base0x0552e648 0x066dd578 dse combasestowed exception information v10x0552e650 0x066dd578 dse combasestowed exception information v10x0552e694 0x066dd578 dse combasestowed exception information v10x0552e6ec 0x066dd578 dse combasestowed exception information v1 warning unable to verify checksum for systemcorenidll04 pdedsestowed exception array 0x066dd578stowed exception 1 0x06728600 0x804003 facility null default e pointer pointer that is not valid stack 0xb9505d4 61e7f228 windows ui xamldirectuibuttonbaseexecutecommand0x103 61e7f469 windows ui xamldirectuibuttonbaseonclick0xc9 621d87db windows ui xamldirectuibuttononclick0x9b 61e8033b windows ui xamldirectuibuttonbaseperformpointerupaction0x60 61e80162 windows ui xamldirectuibuttonbaseonpointerreleased0x292 620290be windows ui xamldirectuicontrolgeneratedonpointerreleasedprotected0x7e 61d5e28a windows ui xamldirectuicontrolfireevent0x648bd5 617159e4 windows ui xamldirectuidxamlcorefireevent0x2cf 617145c0 windows ui xamlagcorecallbacksfireevent0x40 617144f7 windows ui xamlccoreservicesclr fireevent0xe7 617143f5 windows ui xamlcommonbrowserhostclr fireevent0x35 617126b0 windows ui xamlccontrolbasescriptcallback0xe0 61712a48 windows ui xamlcxcpthispatcheronscriptcallback0x21c 617124c5 windows ui xamlcxcpthispatcherwindowproc0x186 75108e71 user32 internalcallwinproc0x2b 751090d1 user32usercallwinproccheckwow0x18e 7510932c user32thispatchclientmessage0xdc 75109529 user32 fndword0x49 77620996 ntdllkiusercallbackthispatcher0x36 7510e4a9 user32sendmessagew0x139 61ace38b windows ui xamlcxcpbrowserhostsyncscriptcallbackrequest0x11b 617159ba windows ui xamlceventmanagerraise0x4ba 61acd396 windows ui xamlceventmanagerraiseroutedevent0xd9 61f070c7 windows ui xamlcinputmanagerraisedelayedpointerupevent0x21c 61f05419 windows ui xamlcinputmanagerprocessgestureinput0x279 61f06e63 windows ui xamlcinputmanagerprocesstouchinteractioncallback0xc3 61e2075b windows ui xamlccoreservicesprocesstouchinteractioncallback0x4b 61ec80f5 windows ui xamlcuielementtouchinteractioncallback0x29 61d8febe windows ui xamlctouchinteractionhelperinteractionenginecallback0x5d5 61d8ffb4 windows ui xamlctouchinteractionhelperstaticinteractionenginecallback0x14 6ae9a1ad ninputcoutputconverterprocess0x1ec 6ae99fa0 ninputcinteractioncontextimploutputcallback0x7c 6ae99c09 ninputcinteractiongroupingfilter sendoutput0x29 6ae99d4c ninputcinteractiongroupingfilterinput0x2d 6ae99cc5 ninputcoutputcoalescingfilterflush0x49 6ae99c64 ninputcinteractionengineimpldigitizerinput0x4e4 6ae97c21 ninputprocessinputinteraction0x57 6ae99605 ninputcinteractioncontextimplprocessframehistory0x998 6aea08a4 ninputprocesspointerframesinteractioncontext0x54 61a013bb windows ui xamlctouchinteractionhelperprocesspointerinformation0x1e3 61a011c6 windows ui xamlctouchinteractionhelperprocesspointermessage0x66 61a01696 windows ui xamlcinputmanagerprocesspointermessageswithinteractionengine0x160 61a05f08 windows ui xamlcinputmanagerprocessinteractionpointermessages0x87 61a05e65 windows ui xamlcinputmanagerprocesspointerinput0x771 619ed303 windows ui xamlcinputmanagerprocessinput0xe5 61acd81e windows ui xamlccoreservicesprocessinput0x3e 61acd7a0 windows ui xamlcxcpbrowserhosthandleinputmessage0x14a 619ed5c4 windows ui xamlcjupitercontrolhandlepointermessage0x62 61bb7207 windows ui xamlcjupitercontrolhandlewindowmessage0x582fc3 6163410f windows ui xamlcjupiterwindowwindowproc0x114 6163403b windows ui xamlcjupiterwindowstaticwindowproc0x27 75108e71 user32 internalcallwinproc0x2b 751090d1 user32usercallwinproccheckwow0x18e 7510a66f user32thispatchmessageworker0x208 7510a6e0 user32thispatchmessagew0x10 6aee3b6d windows uiwindowsuicorecthispatcherwaitandprocessmessages0x16f 6aee3c94 windows uiwindowsuicorecthispatcherprocessevents0x7a 617d1348 windows ui xamldirectuiframeworkviewrun0x87 6b7b66ed twinapi appcorewindowsapplicationmodelcorecoreapplicationviewrun0x3d 6b7b6505 twinapi appcorewindowsfoundationcollectionsinternalhashmapunsigned intwindowsuicoreicorewindow windowsfoundationcollectionsinternaldefaulthashunsigned intwindowsfoundationcollectionsinternaldefaultequalitypredicateunsigned intwindowsfoundationcollectionsinternaldefaultlifetimetraitsunsigned intwindowsapplicationmodelcoredetailssmugglableinterfacelifetimetraitswindowsfoundationcollectionsinternalhashmapoptionsunsigned intwindowsuicoreicorewindow windowsfoundationcollectionsinternaldefaultlifetimetraitsunsigned int010 remove0x215 74674b16 shcorestringcchprintfw0x146 77197c04 kernel32basethreadinitthunk0x24 7763b54f ntdll rtluserthreadstart0x2f 7763b51a ntdll rtluserthreadstart0x1bstowed exception 2 0x06728628 0x804005 facility null default e fail unspecified failure stack 0xb6d5dec 61d36064 windows ui xamlcdependencyobjectseteffectivevalue0x429027 6190d5fb windows ui xamlcdependencyobjectupdateeffectivevalue0xd1 6190d579 windows ui xamlcdependencyobjectsetvalue0x55 61716141 windows ui xamlcuielementsetvalue0x61 61716288 windows ui xamlcframeworkelementsetvalue0x78 6171cf47 windows ui xamlccontrolsetvalue0x53 6171d00b windows ui xamlccontentcontrolsetvalue0x77 6194e9b0 windows ui xamlcdependencyobjectsetthemeresourcebinding0xba 6184d3f2 windows ui xamlcdependencyobjectupdateeffectivevalue0xb72 61867ff9 windows ui xamlcframeworkelementonstylechanged0x16b 6186834e windows ui xamlccontrolapplybuiltinstyle0x48 61895bee windows ui xamlccontrolcreationcomplete0x7f 61895b63 windows ui xamlxamlmanagedruntimeinitializationguard0x12c 6186220d windows ui xamlxamlwriterwritenode0x2e13 61871bc3 windows ui xamlcparserloadxamlcore0x404 618e31b0 windows ui xamlccoreservicesparsexamlwithexistingframeworkroot0xa0 618e301d windows ui xamlcapplicationloadcomponent0x21c 618e2dba windows ui xamlapplication loadcomponent0x95 618e2ccb windows ui xamldirectuiapplicationloadcomponent0xbb 618e367d windows ui xamldirectuiapplicationfactoryloadcomponentwithresourcelocationimpl0x5d 618e3608 windows ui xamldirectuiapplicationfactoryloadcomponentwithresourcelocation0x28unable to load image windowsuixamlnidll win32 error 0n2 warning unable to verify checksum for windowsuixamlnidll error module load completed but symbols could not be loaded for windowsuixamlnidll 6273101d windows ui xaml ni0x29101dstowed exception 3 0x06728650 0x804005 facility null default e fail unspecified failure stack 0x7e5b6d4 61d36064 windows ui xamlcdependencyobjectseteffectivevalue0x429027 6190d5fb windows ui xamlcdependencyobjectupdateeffectivevalue0xd1 6190d579 windows ui xamlcdependencyobjectsetvalue0x55 61716141 windows ui xamlcuielementsetvalue0x61 61716288 windows ui xamlcframeworkelementsetvalue0x78 6171cf47 windows ui xamlccontrolsetvalue0x53 6171d00b windows ui xamlccontentcontrolsetvalue0x77 6194e9b0 windows ui xamlcdependencyobjectsetthemeresourcebinding0xba 6184d3f2 windows ui xamlcdependencyobjectupdateeffectivevalue0xb72 61867ff9 windows ui xamlcframeworkelementonstylechanged0x16b 6186834e windows ui xamlccontrolapplybuiltinstyle0x48 61895bee windows ui xamlccontrolcreationcomplete0x7f 61895b63 windows ui xamlxamlmanagedruntimeinitializationguard0x12c 6186220d windows ui xamlxamlwriterwritenode0x2e13 61871bc3 windows ui xamlcparserloadxamlcore0x404 618e31b0 windows ui xamlccoreservicesparsexamlwithexistingframeworkroot0xa0 618e301d windows ui xamlcapplicationloadcomponent0x21c 618e2dba windows ui xamlapplication loadcomponent0x95 618e2ccb windows ui xamldirectuiapplicationloadcomponent0xbb 618e367d windows ui xamldirectuiapplicationfactoryloadcomponentwithresourcelocationimpl0x5d 618e3608 windows ui xamldirectuiapplicationfactoryloadcomponentwithresourcelocation0x28 6273101d windows ui xaml ni0x29101dstowed exception 4 0x06728678 0x804005 facility null default e fail unspecified failure stack 0x7e4fe5c 61d36064 windows ui xamlcdependencyobjectseteffectivevalue0x429027 6190d5fb windows ui xamlcdependencyobjectupdateeffectivevalue0xd1 6190d579 windows ui xamlcdependencyobjectsetvalue0x55 61716141 windows ui xamlcuielementsetvalue0x61 61716288 windows ui xamlcframeworkelementsetvalue0x78 6171cf47 windows ui xamlccontrolsetvalue0x53 6171d00b windows ui xamlccontentcontrolsetvalue0x77 6194e9b0 windows ui xamlcdependencyobjectsetthemeresourcebinding0xba 6184d3f2 windows ui xamlcdependencyobjectupdateeffectivevalue0xb72 61867ff9 windows ui xamlcframeworkelementonstylechanged0x16b 6186834e windows ui xamlccontrolapplybuiltinstyle0x48 61895bee windows ui xamlccontrolcreationcomplete0x7f 61895b63 windows ui xamlxamlmanagedruntimeinitializationguard0x12c 6186220d windows ui xamlxamlwriterwritenode0x2e13 61871bc3 windows ui xamlcparserloadxamlcore0x404 618e31b0 windows ui xamlccoreservicesparsexamlwithexistingframeworkroot0xa0 618e301d windows ui xamlcapplicationloadcomponent0x21c 618e2dba windows ui xamlapplication loadcomponent0x95 618e2ccb windows ui xamldirectuiapplicationloadcomponent0xbb 618e367d windows ui xamldirectuiapplicationfactoryloadcomponentwithresourcelocationimpl0x5d 618e3608 windows ui xamldirectuiapplicationfactoryloadcomponentwithresourcelocation0x28 6273101d windows ui xaml ni0x29101dstowed exception 5 0x067286a0 0x804005 facility null default e fail unspecified failure stack 0x7dfa064 61d36064 windows ui xamlcdependencyobjectseteffectivevalue0x429027 6190d5fb windows ui xamlcdependencyobjectupdateeffectivevalue0xd1 6190d579 windows ui xamlcdependencyobjectsetvalue0x55 61716141 windows ui xamlcuielementsetvalue0x61 61716288 windows ui xamlcframeworkelementsetvalue0x78 6171cf47 windows ui xamlccontrolsetvalue0x53 6171d00b windows ui xamlccontentcontrolsetvalue0x77 6194e9b0 windows ui xamlcdependencyobjectsetthemeresourcebinding0xba 6184d3f2 windows ui xamlcdependencyobjectupdateeffectivevalue0xb72 61867ff9 windows ui xamlcframeworkelementonstylechanged0x16b 6186834e windows ui xamlccontrolapplybuiltinstyle0x48 61895bee windows ui xamlccontrolcreationcomplete0x7f 61895b63 windows ui xamlxamlmanagedruntimeinitializationguard0x12c 6186220d windows ui xamlxamlwriterwritenode0x2e13 61871bc3 windows ui xamlcparserloadxamlcore0x404 618e31b0 windows ui xamlccoreservicesparsexamlwithexistingframeworkroot0xa0 618e301d windows ui xamlcapplicationloadcomponent0x21c 618e2dba windows ui xamlapplication loadcomponent0x95 618e2ccb windows ui xamldirectuiapplicationloadcomponent0xbb 618e367d windows ui xamldirectuiapplicationfactoryloadcomponentwithresourcelocationimpl0x5d 618e3608 windows ui xamldirectuiapplicationfactoryloadcomponentwithresourcelocation0x28 6273101d windows ui xaml ni0x29101di might be interpreting the stacktrace wrong but it looks to me like it is failing inside windowsuixaml when trying to call executecommand it does not look like it is my actual command that is failing but not even managing to get thereit is a standard store app that passed wack it is live on the store and i have not done anything weird it is a combination of c and f but the entire uixaml stuff is ccompletely stumped at this point not sure what to do,['c#'] +876162,ios watchkit how to determine if your code is running in watch extension or the app with watchkit you have your app that runs on the phone and the watch app that runs as an extensionif you create a library that contains common code to be used in both the phone app and the watch extension is there a way to tell if the code is running in the phone app or the watch extensionieif self isrunninginwatchextension nslogthis is running on watch else nslogthis is running on phone app boolisrunninginwatchextension,['ios'] +876233,android how to hide progress circle in facebook login i am using this method to perform a facebook login without using the fb button facebook authentication without login buttonit is working fine but a progress bar with black background is shown during fb login i guess from activity comfacebookloginactivityhow can i avoid thisplaying that activity i just want to show my own progress from my app activity during login in comfacebookloginactivity,['android'] +876288,how to test a jersey rest web service i have written a restful web service and have to test it using junit4 i have already written a client using jersey client but want to know if i can test my service only with junit4 can someone help me with sample at least my rest service has authenticate method that takes user name password and returns a token i have written test case for authenticate method but i am not sure how to test using urlpublic class testauthenticate service service new service string username user string password password string token testexpected exceptionclass public final void testauthenticateinputs password pass serviceauthenticateusername password testexpected exceptionclass public final void testauthenticateexception username null string token serviceauthenticateusername password assertnotnulltoken test public final void testauthenticateresult string token serviceauthenticateusername password assertnotnulltoken,['java'] +876426,fbsdkloginmanager loginwithreadpermissions i am using fbsdkloginbutton to allow to user login using facebook and using fbsdkloginbuttonreadpermissions public profileemailuser likesemailuser birthday to ask for permissions but i need one more permission which is publish actions i should use fbsdkloginmanager with loginwithreadpermissionspublic profileuser likesuser birthday loginwithpublishpermissionspublish actionsbut this for some reason affect on my permission some of my permission are missing check image codefbsdkloginmanager login fbsdkloginmanager alloc init login loginwithpublishpermissionspublish actions handlerfbsdkloginmanagerloginresult result nserror error if error process error else if resultiscancelled handle cancellations else if you ask for multiple permissions at once you should check if specific permissions missing if resultgrantedpermissions containsobjectpublish actions do work login loginwithreadpermissionspublic profileuser likesuser birthday handlerfbsdkloginmanagerloginresult result nserror error if error process error else if resultiscancelled handle cancellations else if you ask for multiple permissions at once you should check if specific permissions missing if resultgrantedpermissions containsobjectemail do work resultit take long time to redirect the user to the permission view and not all my permission appear to user notei know that warning mean that i need to submit my app to review but this not what i am asking about right now updatewhen i tried dheeraj singh solution but in this case user will be redirect twice to the facebook first time to get publish action then to get email and birthday permission which is bad,"['ios', 'objective-c']" +876431,fbsdk new facebook sdk 40 implementation is not working for login with facebook i am using this following block which is mentioned in facebook developer but when my app callbacks from browser then it is always returning cancelled resultfbsdkloginmanager login fbsdkloginmanager alloc initlogin loginwithreadpermissionsemail handlerfbsdkloginmanagerloginresult result nserror error if error process error else if resultiscancelled handle cancellations else if you ask for multiple permissions at once you should check if specific permissions missing if resultgrantedpermissions containsobjectemail do work this update comes on 25 march 15if anyone used this then please share it with mereference,"['ios', 'objective-c']" +876501,can i create an empty range iterator pair without an underlying container object i have a class akin to the followingstruct config using bindingcontainer stdmapid stdvectorbinding using bindingiterator bindingcontainermapped typeconst iterator boostiterator rangebindingiterator bindingsid id constprivate bindingcontainer m bindingssince the id passed to bindings might not exist i need to be able to represent a no bindings value in the return type domaini do not need to differentiate an unknown id from an id mapped to an empty vector so i was hoping to be able to achieve this with the interface as above and return an empty range with defaultconstructed iterators unfortunately although a forwarditerator is defaultconstructible c11 24251 the result of comparing a singular iterator is undefined 24215 so without a container it seems this is not possiblei could change the interface to eg wrap the iterator range in a boostoptional or return a vector value instead the former is a little more clunky for the caller though and the latter has undesirable copy overheadsanother option is to keep a staticallyallocated empty vector and return its iterators the overhead wouldnt be problematic in this instance but i would like to avoid it if i canadapting the map iterator to yield comparable defaultconstructed iterators is a possibility though seems overcomplexare there any other options here that would support returning an empty range when there is no underlying container incidentally i am sure a while back i read a working paper or article about producing empty ranges for standard container type when there is no container object but cannot find anything nownote i am limited to c11 features though i would be interested if there is any different approach requiring later features,['c++'] +876502,swift attempt to present uialertcontroller whose view is not in the window hierarchy presented after twtrshareemailviewcontroller i am using the twitter login in the signup process of my app and i am asking for the users email once i get it i would like to present a uialertcontroller heres my codefunc askfortwmail if twittersharedinstancesession nil let sharemailvctwtrshareemailviewcontrollercompletion mailstring errornserror in if mail nil printgot mail mail selfgotmail else printmail vc error error printlnpresent mail vc selfpresentviewcontrollersharemailvc animated true completion nil else printlnuser not logged in func gotmail var alertcontrolleruialertcontrollertitle some title message some message preferredstyle uialertcontrollerstylealert var okactionuialertactiontitleyes style uialertactionstyledefault uialertaction in some action var cancelactionuialertactiontitleno style uialertactionstylecancel uialertaction in some action alertcontrolleraddactionokaction alertcontrolleraddactioncancelaction selfpresentviewcontrolleralertcontroller animated true completion nil but i get this error i guess because the twtrshareemailviewcontroller is not thismissed warning attempt to present uialertcontroller on xviewcontroller whose view is not in the window hierarchyany idea of how i should write this how can i know when the twtrshareemailviewcontroller is thismissed to continue the signup process and be able to present my uialertcontroller i am not aware of a delegate method related to twtrshareemailviewcontrollerany help is appreciated thanks,['ios'] +876561,component wont render within navigatorios react native i cant get this simple navigatorios test to work the console log in my view triggeres and i can get it to render if i skip the navigatorios component and render myview directly however when myview is triggered from a component within the navigatorios component it wont render anything else than my navigatorios testvar react requirereactnativevar appregistry stylesheet navigatorios text view react var navigation reactcreateclass render function return navigatorios initialroute component myview title my navigatorios test passprops myprop foo var myview reactcreateclass render function consolelogmy view render triggered return view stylestylescontainer text stylestyleswelcome hello there welcome to my view text view var styles stylesheetcreate container flex 1 justifycontent center alignitems center backgroundcolor f5fcff welcome fontsize 20 textalign center margin 10 appregistryregistercomponentnavigation navigation,['ios'] +876736,thisplaying activity indicator on wkwebview using swift i am working on the following code and trying to show an activity indicator in the view whilst the page is loading i tried to implement the wknavigationdelegate methods but i am failing as nothing shows any suggestions on how to fix thisi am not setting the supportwebview view delegate anywhere but i wouldnt know how to do it in swiftimport uikitimport webkitclass supportwebview uiviewcontroller wknavigationdelegate iboutlet var containerview uiview nil var webview wkwebview override func loadview superloadview selfwebview wkwebview selfview selfwebview override func viewdidload superviewdidload var datamanager datamanagershareddatamanager var url datamanagermyvalidurl var req nsurlrequesturlurl selfwebviewloadrequestreq override func didreceivememorywarning superdidreceivememorywarning thispose of any resources that can be recreated func webviewwebview wkwebview didstartprovisionalnavigation navigation wknavigation uiapplicationsharedapplicationnetworkactivityindicatorvisible true func webviewwebview wkwebview didfinishnavigation navigation wknavigation uiapplicationsharedapplicationnetworkactivityindicatorvisible false,['ios'] +876807,while loop using bluebird promises i am trying to implement a while loop using promisesthe method outlined here seems to workit uses a function like thisvar promise requirebluebirdvar promisewhile functioncondition action var resolver promisedefer var loop function if condition return resolverresolve return promisecastaction thenloop catchresolverreject processnexttickloop return resolverpromisethis seems to use antipatterns and deprecated methods like cast and deferdoes anyone know a better or more modern way to accomplish thisthanks,['javascript'] +876956,android facebook sdk 4 in eclipse are there some way to import the new facebook sdk for android to eclipse without gradle or maven something like the past way i have been watching some pages but i do not find a the waythanks,['android'] +877146,downloading large file in python error compressed file ended before the endofstream marker was reached i am downloading a compressed file from the internetwith lzmaopenurllibrequesturlopenurl as file for line in file after having downloaded and processed a a large part of the file i eventually get the errorfile usrlibpython34lzmapy line 225 in fill buffer raise eoferrorcompressed file ended before the eoferror compressed file ended before the endofstream marker was reachedi am thinking that it might be caused by an internet connection that drops or the server not responding for some time if that is the case is there anyway to make it keep trying until connection is reestablished instead of throwing an exceptioni do not think it is a problem with the file as i have manually downloaded many files like it from the same website manually and decompressed it i have also been able to download and decompress some smaller files with python the file i am trying to download has a compressed size of about 20 gb,['python'] +877522,how can i get the current url using protractor i am testing a website using protractor and jasmine i would like to know the current url in order to verify a testi have triedfunction waitforurltochangetourlregex var currenturl return browsergetcurrenturlthenfunction storecurrenturlurl currenturl url thenfunction waitforurltochangeto return browserwaitfunction waitforurltochangeto return browsergetcurrenturlthenfunction comparecurrenturlurl return urlregextesturl and i am using this function in this wayitshould log function elementbymodeluserusernamesendkeysasd elementbymodeluserpasswordsendkeysasd elementbylinktextaccederclick waitforurltochangetohttplocalhost90solicitudes,['javascript'] +877585,uniform and valueinitialization i try to use valueinitialization for members with valueinitialization for constructors i do not know if i really use the good termsso when i definestruct a int a i am able to usea a5assertma 5 however if i want to use the member brace initializer and an initializationlist constructorstruct b int b 1this does not compile c14 b b2here is the errorprogcpp197 error no matching function for call to braceenclosed initializer list b b2 progcpp197 note candidates areprogcpp108 note constexpr bb struct b progcpp108 note candidate expects 0 arguments 1 providedprogcpp108 note constexpr bbconst bprogcpp108 note no known conversion for argument 1 from int to const bprogcpp108 note constexpr bprogcpp108 note no known conversion for argument 1 from int to bwhat is the difference conceptwisemany thanks,['c++'] +877608,dramatic speed drop for access to static ram over cache c backgroundi have been looking into potentially using the mpc5200 static ram space as scratch pad memory we have 16kb of unused memory that appears on the processor bus source now some important implementation notes arethis memory is used by the bestcomm dma controller under rtems this will essentially set up a task table at the start of sram with a set of 16 tasks that can run as buffers for peripheral interface i2c ethernet etc in order to use this space without conflict and knowing that our system only uses a about 2kb of ethernet driver buffers i offset the start of sram by 8kb so now we have 8kb of memory that we know wont be used by the systemrtems defines an array that points to static memory as follows sourcetypedef struct volatile uint8 t sram0x40 mpc5200 t extern volatile mpc5200 t mpc5200and i know that the sram array points to static memory because when i edit the first section and print out the memory block mbar 0x80 sourceso from here i can say the following i have the rtems defined access to the sram via mpc5200sram0 0x20 this means i can start doing some testing on the speed i can get out of ittestin order to evaluate the speed i set up the following testint a global that is separate from the test test set up the dataconst unsigned int listsize 0x10uint8 t data1listsizefor int k 0 k listsize k data1k k mpc5200sramk k test 1 data on regular stackclock t start clockfor int x 0 x 50 x for int y 0 y 0x20 y a data1y double elapsedtime static castdoubleclock start clocks per secprintfelapsed dynamic fn elapsedtime test 2 get data from the static memorystart clockfor int x 0 x 50 x for int y 0 y 0x20 y a mpc5200sramy elapsedtime static castdoubleclock start clocks per secprintfelapsed static fn elapsedtime pretty simple the concept is that we are iterating over the available space and setting a global we should expect that the static memory should have the same approximate timeresultso we get the followingelapseddynamic 1415elapsedstatic 6348so there is something going on here because the static is almost 6x slower than the cache hypothesisso i had 3 ideas about why this is cache misses i thought maybe the fact that we are mixing dynamic and static ram that something strange is happening so i tried this test some pointers to use as incrementersuint8 t i reinterpret castuint8 t0xf0x80x101uint8 t j reinterpret castuint8 t0xf0x80x102uint8 t b reinterpret castuint8 t0xf0x80x103 i replaced all of the potential memory accesses with the static ram variables that way the tests have no interaction in terms of memory locations start clock test 2 get data from the static memoryfor i 0 i 240 i for j 0 j 240 j b mpc5200sramj elapsedtime static castdoubleclock start clocks per secprintfelapsed static fn elapsedtimewe have the following resultselapseddynamic 010elapsedstatic 02010so now it is 200 times slower so i guess it is not to do with thatstatic memory different to normal the next thing i thought was that maybe it does not interact how i thought it would because of this linempc5200 contains 16kbytes of onchip sram this memory is directly accessible by the bestcomm dma unit it is used primarily as storage for task table and buffer descriptors used by bestcomm dma to move peripheral data to and from sdram or other locations these descriptors must be downloaded to the sram at boot this sram resides in the mpc5200 internal register space and is also accessible by the processor core as such it can be used for other purposes such as scratch pad storage the 16kbytes sram starts at location mbar 0x80sourcei am not sure how to confirm or deny thisslower static clock perhaps the static memory runs on a slower clock like in some systemsthis can be thisproved by looking in the manualsourcethe sram and the processor were on the same clock the xlb clk runs at the processor fundamental frequency sourcequestionwhat could be causing this are there reasons in general not to use sram for scratch pad storage i know on modern processors this would not even be considered but this is an older embedded processor and we are struggling for speed and space extra testsso after the comments below i performed some extra tests add volatile to the stack member to see if the speeds are more equalelapseddynamic 098elapsedstatic 597so still much faster and not really any change with the volatilethisassemble the code to see what is happening original codeint a 0uint8 t data50x20void assemblyfunctionvoid int test int 0xf080 mpc5200sram0 a data50 a test0 avoid assemblyfunctionvoid i think this is to load up a0 3d 20 00 00 lis r908 80 09 00 00 lwz r00r9 14 54 0a 06 3e clrlwi r10r024 mpc5200sram0 a 1c 3d 60 00 00 lis r110 20 39 6b 00 00 addi r11r110 28 3d 6b 00 01 adthis r11r1 where do these come from 2c 99 4b 80 00 stb r1032768r11test0 a c 3d 20 f0 00 lis r94096 this should be the same as above 10 61 29 80 00 ori r9r932768 24 90 09 00 00 stw r00r9 data50 a 4 3d 60 00 00 lis r110 18 99 4b 00 00 stb r100r11i am not particularly good at interpenetrating assembler but perhaps we have a problem here accessing and setting the memory from a global does seem to take more instructions for the sram from the above test it seems that there are less instructions for the pointer so i added thisuint8 t p uint8 t0xf080 test 3 get data from static with direct pointerfor int x 0 x 50 x for int y 0 y 0x20 y a py and i get the following resultelapsed dynamic 0952750elapsed static 5160250elapsed pointer 5642125so the pointer takes even longer i would have thought it would be exactly the same this is just getting stranger,['c++'] +877881,social framework for watchkit i want to create an app for apple watch that gives the user a simple possibility to share things right from his wristnow my question is whether there is a social framework for apple watch like the social framework on ios,['objective-c'] +877971,how to pass parameters to template event in meteor how to pass values to template eventshtmltemplate nameheader div classtestclasstext1div pass a 1 div classtestclasstext2div pass a 2templatejavascripttemplateheadereventsclick testclassfunctionevent template consoleloga print a values,['javascript'] +878213,how to configure jackson deserializer for nested entites with spring boot consider the following entitiespackage brcominvestorsdomainenderecoimport comgooglecommonbaseobjectsimport comgooglecommonbasestringsimport comgooglecommoncollectcomparisonchainimport orghibernatevalidatorconstraintsnotblankimport javaxpersistenceimport javaioserializableimport static comgooglecommonbasepreconditionscheckargumentimport static javaxpersistencegenerationtypesequenceentitypublic class regiao implements serializable comparableregiao id generatedvaluestrategy sequence private long id version private long version notblank columnlength 100 unique true private string nome regiao public regiaostring nome checkargumentstringsisnulloremptynome nome nao pode ser vazio thisnome nome override public boolean equalsobject obj if obj instanceof regiao regiao o regiao obj return objectsequalthisnome onome return false override public int hashcode return objectshashcodenome override public int comparetoregiao o return comparisonchainstart comparethisnome onome result override public string tostring return objectstostringhelpergetclassaddnome nometostring public long getid return id public long getversion return version public string getnome return nome and package brcominvestorsdomainenderecoimport comgooglecommonbaseobjectsimport comgooglecommonbasestringsimport comgooglecommoncollectcomparisonchainimport orghibernatevalidatorconstraintsnotblankimport javaxpersistenceimport javaxvalidationconstraintsnotnullimport javaioserializableimport static comgooglecommonbasepreconditionscheckargumentimport static comgooglecommonbasepreconditionschecknotnullimport static javaxpersistencegenerationtypesequenceentitypublic class cidade implements serializable comparablecidade id generatedvaluestrategy sequence private long id version private long version notblank columnlength 100 unique true private string nome notnull manytoone private regiao regiao notnull manytoone private estado estado cidade public cidadestring nome regiao regiao estado estado checkargumentstringsisnulloremptynome nome nao pode ser vazio checknotnullregiao regiao nao pode ser nulo checknotnullestado estado nao pode ser nulo thisnome nome thisregiao regiao thisestado estado override public boolean equalsobject obj if obj instanceof cidade cidade o cidade obj return objectsequalthisnome onome objectsequalthisestado oestado objectsequalthisregiao oregiao return false override public int hashcode return objectshashcodenome regiao estado override public int comparetocidade o return comparisonchainstart comparethisestado oestado comparethisregiao oregiao comparethisnome onome result override public string tostring return objectstostringhelpergetclassaddnome nomeaddregiao regiaoaddestado estadotostring public long getid return id public long getversion return version public string getnome return nome public regiao getregiao return regiao public estado getestado return estado i am trying to post a json to a restcontrollerrequestmappingvalue cidades method post consumes application json valuevoid inserirrequestbody cidade cidade repositorysavecidadei am using default configurations of spring boot to serialize and deserialize objectsif i post a json like this it works fine nome cidade regiao 10but i need to post a json like this nome cidade regiao id 10 version 0 nome regiao if i do so i get the error timestamp 20150402 status 400 error bad request exception orgspringframeworkhttpconverterhttpmessagenotreadableexception message could not read json template must not be null or empty through reference chain brcominvestorsdomainenderecocidaderegiao nested exception is comfasterxmljacksondatabindjsonmappingexception template must not be null or empty through reference chain brcominvestorsdomainenderecocidaderegiao path cidadesdoing some debug i found that jackson tries to create a uri from the regiao property of the posted object waiting for a string template like id i am googling it but cannot find a properly answer for thisi saw some related issues on stackoverflow but none worked for mecan you guys say what is the matter of thisi think that is just a configuration but do not know how or wherei am also trying to avoid custom serializers and deserializerseditif i post a json with only the ids of the nested entities like this nome cidade estado 10 regiao 10i get this message timestamp 20150407 status 400 error bad request exception orgspringframeworkhttpconverterhttpmessagenotreadableexception message could not read json failed to convert from type javaneturi to type brcominvestorsdomainenderecoestado for value 10 nested exception is javalangillegalargumentexception cannot resolve uri 10 is it local or remote only local uris are resolvable through reference chain brcominvestorsdomainenderecocidadeestado nested exception is comfasterxmljacksondatabindjsonmappingexception failed to convert from type javaneturi to type brcominvestorsdomainenderecoestado for value 10 nested exception is javalangillegalargumentexception cannot resolve uri 10 is it local or remote only local uris are resolvable through reference chain brcominvestorsdomainenderecocidadeestado path cidadesas i see that the correct way of send the nested entity is like regiao 10 i am hardcoding this in my javascript to workaroundfunctionitem itemregiao itemregiaoid omg itemestado itemestadoid omg if itemid return httpputcidades itemid item else return httppostcidades item it works but it suckshow can i fix this in javascript or configuring jacksonreading some docs there is something to do with uritoentityconverter but still do not know the correct way of configure thisthanks,['java'] +878257,could not find comandroidsupportsupportv42200 after sdk update after the sdk update im not able to create a hello world applicationmy buildgradle looks like this apply plugin comandroidapplicationandroid compilesdkversion 22 buildtoolsversion 2201 defaultconfig applicationid comcodersyo minsdkversion 11 targetsdkversion 22 versioncode 1 versionname 10 buildtypes release runproguard false proguardfiles getdefaultproguardfileproguardandroidtxt proguardrulespro dependencies compile filetreedir libs include jar compile comandroidsupportappcompatv72200but build got failed and shows errora problem occurred configuring project app could not resolve all dependencies for configuration app debugcompile could not find comandroidsupportsupportv42200 required by yoappunspecified comandroidsupportappcompatv72200so i added compile comandroidsupportsupportv42200 and now i geterrorfailed to find comandroidsupportsupportv42200a hrefopenfileopen fileabra hrefopendependencyinprojectstructureopen in project structure dialogai have updated the android sdk and the support libraries i have been stuck in it for the past few hours can some one please help me identify the issue,['android'] +878416,alias the angularjs scope object in a controller without getting into the details of why i need to provide an alias for scope in my controllers instead of injecting and decorating scope i would like for the users to instead be able to inject view and have it have the same effectbased on my understanding of angular scope is created by a scopeprovider which is a factory registered at configuration time of the angular app i am assuming that i need to register a viewprovider and set it equal to the scopeprovider but i have not had luck with what i have been trying any ideasfyi i am not looking for something like scope functionview the ideal solution would work with view functionview the view object would act exactly like scope two way binding etc,['javascript'] +878461,elegant way to find contiguous subarray within an array in javascript i wanted to write a function to find a contiguous subarray within a given array from a given starting index and return the index of the subarray within the array if it is found and 1 if it is not found this is similar to stringindexof but for arrays and subarrays instead of strings and substringsthis is my working codevar find csa function arr subarr from index if typeof from index undefined from index 0 var i found j for i from index i 1 arrlength subarrlength i found true for j 0 j subarrlength j if arri j subarrj found false break if found return i return 1and these are my tests and their expected valuesconsolelogfind csa1 2 3 4 5 2 3 4 1consolelogfind csa1 2 3 4 5 5 4consolelogfind csa1 2 3 4 5 1 3 1consolelogfind csa1 2 3 4 5 42 1consolelogfind csa1 2 3 4 5 0consolelogfind csa3 4 3 4 3 4 3 4 3 1 2consolelogfind csa6 6 6 7 6 6 7 1consolelogfind csa12 9 16 42 7 866 3 16 42 7 866 2my code passes the tests but as you can see it uses a boolean value found in the inner loop which is just my messy adhoc way of continuing an outer loop from a nested loop is there a cleaner way of writing it i looked into arrayprototypefindindex but it is an experimental technology at the moment so i cannot use it i want a method that works in most browsers i know there is a polyfill code snippet written on the mozilla page but that is even longer than my current code and it will be slower due to the function calls so i would rather avoid itmy primary goal for this function is performance the subarrays will be very small so i believe that using boyermoore string search algorithm or tries is a tad overkill and then my secondary goal is elegance of my implementation with those two goals in mind i would like to know if there is a better way of writing this code or if there are any javascript features or functions that i am missing that could help me avoid the found booleanjsfiddle if it helps anyone,['javascript'] +878499,how to run gradle test when all tests are uptodate i have my grade script set upwhen i exec the gradle build everything is working and it perform the junit testsafter that when i run the gradle test im getting the followingcusersprojectgradle testcompilejava uptodateprocessresources uptodateclasses uptodatecompiletestjava uptodateprocesstestresources uptodatetestclasses uptodatetest uptodatewhen i preform gradle clean and then gradle build it working of coursei want to be able to reset the test only and not building the whole project how should i do it,['java'] +878502,transferring data using emscripten worker api without copying is there a way to get emscripten to transfer and not copy data between web workers and the main ui threademscripten has an api that manages communication between web workers which i believes just uses the postmessage onmessage mechanism under the hood looking in the source for the emscripten worker api it appears that it does not use the transferlist option when it calls postmessage and so the data gets copied actually i think it gets copied at least twice first by the browser between the threads and then a second time by emscripten to get it into the emscriptenmanaged heapspace and if you want the data to continue to survive on the receiving end after the callback it would have to be copied a third time as according to the docs the data passed to the callback is only guaranteed to exist during the callbackrepeating my question from the top is there a way to get emscripten to avoid all this copying by transferring and not copying data between web workers and the main ui thread,"['javascript', 'c++', 'c']" +878586,sfinae away a copy constructor under certain conditions i would like to sfinae away the copy constructor and copy assignment operator of a class template but if i do so a default copy constructor and a default assignment operator are generated the sfinae is done based on tags i pass as class template parameters the problem is that sfinae only works on templates and a copy constructorassignment operator cannot be a template does there exist a workaround,['c++'] +878605,outofmemoryerror while decoding and encoding base64 string into bitmap i am trying to decode and encode a bitmap image on some devices it runs perfectly while on others it is not i am uploading base64 string to the server and getting base64 string from the server i have found various solutions but still am not able to solve my issue heres my codeencodingbutton1setonclicklistenernew onclicklistener override public void onclickview v todo autogenerated method stub intent i new intent intentaction pick androidprovidermediastoreimagesmediaexternal content uri getactivitystartactivityforresulti result load image image loading from galleryoverridepublic void onactivityresultint requestcode int resultcode intent data superonactivityresultrequestcode resultcode data if requestcode result load image resultcode result ok null data uri selectedimage datagetdata string filepathcolumn mediastoreimagesmediadata cursor cursor getcontentresolverqueryselectedimage filepathcolumn null null null cursormovetofirst int columnindex cursorgetcolumnindexfilepathcolumn0 picturepath cursorgetstringcolumnindex cursorclose imageview1setimagebitmapbitmapfactorydecodefilepicturepath if picturepath null textutilsisemptypicturepath bitmapfactoryoptions options new bitmapfactoryoptions optionsinpreferredconfig bitmapconfigargb 8 bitmap bitmap bitmapfactorydecodefilepicturepath options base64imagesend imagebase64encodetobase64bitmap logibase 64 image base64imagesend else base64imagesend decodingprivate string base64stringreceive 9j4aaqskzjrgabaqaqabaad2wbdaaebaqebaqebaqebaqebaqebaqebaqebaqebaqebaqeb aqebaqebaqebaqebaqebaqebaqebaqebaqebaqebaqh2wbdaqebaqebaqebaqebaqebaqebaqeb aqebaqebaqebaqebaqebaqebaqebaqebaqebaqebaqebaqebaqebaqebaqhwaarcadhaoedasia ahebaxeb8qahwaqubaqebaqeaecawqfbgcicqol8qatragedawieawufbaqa aaf9aqidaaqrbrihmuege1fhbyjxfdkbkaeii0kxwrvs0fakm2jyggkkfhcygroljicokso0nty3 odk6q0rfrkthisuptvfvwv1hzwmnkzwznaglqc3r1dnd4exqdhiwgh4ijipktljwwl5izmqkjpkwm p6ipqrkztlw2t7i5usldxmxgx8jjytlt1nxw19jz2uhi4tl5ufo6erx8vp09fb3pn68qahwea awebaqebaqebaqaecawqfbgcicqol8qatreaagecbaqdbacfbaqaaqj3aaecaxeebsex bhjbuqdhcrmimoeifekrobhbcsmzuvavynlrchyknoel8rcygromjygpkju2nzg5okneruzhselk u1rvvldywvpjzgvmz2hpann0dxz3ehl6gooehyahiimkkpoulzaxmjmaoqokpaanqkmqsro0tba3 ulm6wspexcbhymnk0tpu1dbx2nna4upk5ebn6onq8vp09fb3pn69oadambaairaxeapwdi igaoakacigaooriphxb8gfc7wd4iipj3xbhw54t8j6epine1bilnyaerfwkdgc8n htoarkebyac9qus6t4e0vvne13urhrde020n7qwo392lhy2npew828v9rldfjvqno3mfa6ssaxf p9plgsz8oci1lwwds0ahbe7xrax2fcfk59t0v4ypjudt2l6bbkvilxqxicpgkvhq1ickem sgqtwh7a7fxxua91y8owr1dwl8fnnvr5fd3gkxvpm8q7dsyax4kizyza3rrwp8ainxledc axud2j8ch4a9stg9um4ww3ddzkbtz06dnnfk2e8ek7yhzklzt12upxtq7jj7ppznsuz9i4f4d5 teieecvvdvt01q0k3evuuydlqmrz3xdb9bgmfqi1342lpdn34axw98m7vhabdtrluk hhidnqsffbpgcc4j8os4fepicoo64g17xbf8aqr17wdr1duocrzgce54hqbmvnpcukrn5u ntgjaywock9cxji5619jehnpocqeqcmhei7wyo2eosrn4nyrh41t5m3dveyv0nkzvr31wyunj 6o8jhmvwclhk4pkntfe28r317rutsu2lr0ng58zhsr4r8xelfd4jgdohifxd4fpbynjrcnv 36djjbr7egh7a7ww8vtvj4eprlgcxjninesassm2ot4x10kangjym5ycwnegegddlknonv auur3z6ebnu3s1l4gppn19sbscd8qftocelethcvj8bylnzaddx703zpuokm23rtbqrnk4nb5 fjb0tzaw085xs76oyv2mpxsrtt3wd4eftdd4n3gmghtvl8mfgn6wnna6lfjffdtvlla jsessig344xxet2byvcoh3foigca46epynsstysfzrxf4l8dznbydjodjjr0x6gc19ff smtt33ws1g0ghxo19r3wi5sw0pxhrd8bfbgubusnz1nzsbweqio38hwpgsmerneqkv3wqcyjy eazdsaasmlpa7strnnwst2t2m2j4tod3tjlmmt1guvoo0r3knzuv20tzj3j2k7k7suvhf svinxguafabrqauafabrqauafabrqbsqyy9px8xhqt3h5u1l zwvqa5vvif8unagcfawubfhz8n75pe2nkqx8wez98yxeqdj6n4tz5zkcb28xjrcujscgj6 onanmufwbz0k3xczet94t8jx8gpchcjvfoponi8lwmi4izbjxlae6krshilnh2p8knip xg2m6bqfihx7vr8y1dunqv8ajqgo3qm3abmsnona6knknnk4r8y46zs0f7oxvk97nyaezc du17tw1y4gyv2lseynk1plul2n875te3ekcbpe8px0izo7kk0ppxhptdnpqji6qwnl4h bsh9odb09x9tnqd69scfs5wagp2sf2x2pnopjlwhywhwwdaph9nifft4dptd5m5bol7t r2tcd19epbb9a8xapbo39ur4e6edr0aevjdpheu0hwtpv8abycnwr64zz1i3do3p5vdwai wdawfqn1v8axf12cf4fzp2onahtz7zbvz1ncc53eqhs4p5e3b1pxj68n0r4mlkvilwd r58oe3whr3gx9pxxl9f0bunp1dgsemenanj1pnfuxgjxz4n8qaef7p8aeh9n9p5sb33sdud k4iigo4vcmq9fp9o49zzthxmvofrvfxx8dz68pzpuc18pabff2ggweinb1adgd9t9ypx3v tum138f94i0onp7d19whv8ax2boocrxohnnv3ipxno1dp8anoc2c3tr7ckcvnjxtpnpf7vvz2 9xjp9ovoc4mov4f8asq557hn0jzxxe3fjhrh16v79c9we5oaclgmd063jdqtrapjju je64qsu1hwfqf6vuap4bw8z8pbtfiwm8leo8riyt4tv4irtj0g5d16vaoi6g49exuf1rmdwx 8wrapznnwsmnlk8ijr9jfah1b1dw98kektn64hel1tvoevjyk1zlpoo2op6zz6jymt3 z3lly3tk6gfpzagxmbjipymmbydzt3jnijp6dwbmixuaotawss7wvopno1cy9bu6apyik1gmw nis1eet0srtpyvpo3dswruves1ytvpak6plwoakacigaoakacigao akapxy4lyel77qf2wfaphlt9qwybxf8af7qf1zgm3h7w74a8xa00y64xhmifcl5ydxibg rx84p7lpwg4akal07wractd4xhaisdxj14mhjglehmhkjxrrwfrnxcmllof3swcc5so 4rh9m6x7t4v8flj2tw4yxjn0f36dnjgpz24jqaxxlv2mpea5chcyedtpbzamw8adq2rdof x689tfhhgkf9s5vhf3yweq1xnvddxg3fvxbvz9b4lsjkvsy3cppzvukvxs01utu007n7g6ly6d p9jzadyafyafpn6eunafp9hzmw0t9pzjntevsv45ayvjr0fsyplb8bwcpdof5hvquj0wabn aoan094nhz83qonwzvip9n9gf39r2z1pue18blfwxxwpom03qell0qoesgx9mb4dalqf h8hvi74b0hxb0s7ufsrttw4mwlarhtf0b3gfu8kej8yfinwaeppgonadqzzmfhygo y4p7x6nrsnq0lzp0dm60onsor3yf6giuba3hzo4xrcgrueo57jabr7eftrefgswdk zdpwfwrlo3zf8jf8atbeevd4wpqdyeiffodwbh8lnsvfqbotmvswpwsl8ohtp0wdt wdaslxidkf2idbsnp0dtzgvzctyxxtgyh8uonxwec298n47vdhnj64tjhjoajbbrlptnd7 upxjix9fqeegrymj96waxwbpy3b8vmfl3rhbmf4vksdojxasnqbgdqtrwf38f8hn wc8ntx0bbjzx54ftkfsgfft4fadqpiht9q4wd4aspqh4hsnfon6ogngtwahbssf8gxspezp pwv6obmfslwngp9oz49fc8cazjbhniswsltma0wc35xnttq54l4ly7knofrybzzxmyjd x2dplrnttw5p3t69brztjtdnqypfx0b193q7tv52tvqmrax807u6lkrcx3aakhg1vofjstzvp ofp742g9djvfgn94kvff37fh7omo36klqyghhvw86aybbww8hk1kpvipdodjzlisedop8ox wda3cjpi58vfhzyf8aiatdttq8pf6b9vhcp6np76rpwmjjv02nkkfqp14jxx4v2gfhb6 2cektp8awj8b63r3yepyc8e19xwbf69uxrbq4nff1dzwopiqws0x1jj2dle16ikrvwzu7ryv 721r2iv2algoakacigaoakacigaoakapwxwcc5mixxf7pni rcdp9l8qff3h7uaoadq8sgpnu0rqtjjwpqrhi7jjwtxxdws60nzahxkv2bkifdwp3tgf7 l8ndeuqadu6dmqccfrtgod4gip7uwnempgcugai58iepfegh1i0j2oowbveg9p1zwsm6qs q3cuan4s1qocp3sny0cqxq4x7i3wx1d4obhw9ogvafzv6hqfwcmpeon39mdp1cw1xodia0 3vtlizbx9jaxpnh3odamgs8njjntjdncdjcbnsy9pztbsa02cle1d1200tvpzsf7fwphmdgc gex473ysvjaqtaljyv1u3el9doz80t7p0xh6facrxo9namtpwrgnfhnyrxpfn92t6iubl d6nff8apvqm05espahia9v3ao2ftstodv9twzb98atn7urtg7u17h4b0uhqqhus9 gifhsvwt4wapalwzzdh85pfvxnnjbgsb19g5zbl1bfvpqpk4rvf8afddrlq2qf hsvxwrfewc68bebz9hwclvd0sn7cfh9wu9hitwcfnxjsdzqgn6h8pveaxy6xqetek9 k1lqpgpqh5oc6z4dgqrz33blaesadw18er3v9m8t6iwwetfofeewxzxgkp6jjpfbnfb37y fww8rfgp4qn4o8jfydr7elbidtvt97zn6f8a2wdb0nvoh6a2qfl1ovgfbpcdhhi8adhi3 xvd3h7unr4rlwh4d07wfbqgsdq1bdtfs9m1dvdzalruq6tqeshuvmta9hww3hhgvnpqeeyja91 yaxwicm973sk7reljsdmn0cz4b63kmzqxlyzjov05c6tuhyt3urydk3dj91k5yvfv5ohrr rqauafabrqauafabrqauafjb1t4zwcemaxdxevh7xiutgld2k apz2wniz6n1vwsr81vitpuj1gpzxhf8ajr6yboho8rea9oifhzqds8bx7pql4vtj4u1pj vaoaw5tuau4y4igtro4szv8q6zro1z7alrpn4wmbvmoegbnueh5bznyeocswdzvojq7u oxnd7ts5wy2tq7pxdmr2td2grffxmi5egfi9huljrvd7pnxwm6u7ts9r0j7ohr0uz8nbs vktnnwoh18aqm7y7kevrzgfj6zpsgav8a7n2x3i9fxnaleyj7pgz2zp8uv8abd04b0p3wi vuqdqazlfvansalwfppqpzhffthigv8ztoef521u0nep8a3yth2hv7x75wuv6 98ayz55deebtvxk56rh074dhfppe6zouetxoerdeoonqza3nxxsqagxwfm569c3yn0psa4 jx5s2ewhfjjkfqorgrk9k8reyqz1fd2d7yv132010v1rbp2mj9u3ur3fw1qi87x76t6axuzwn xf2fp2pbvgf8an19w28an4oh9ysrmvpt9gwq3h74bipgfn7f4719tg3lyfqdom0rtuu shchxu73vyt93bimhiy181a4f1x7ewxhdwpyi91zxlwshzmwum6cdidv1pvyseui4jayqsvcj p6sebcmlabgeenfaxt9a0sw0uwrvlwcmh7qjzvo12hqqaeaa7pdjknjc7qcrapolinro20 tg1vy20wycvkzimp4zvyxblkezffcplwuqlnpsc1dlfvqwraud3rx7sfk4uafabr rrqauafabrqauafagbfabpuqade6bqfnz3tjfry76yvluxdpewz8xtasqudg6 lwpyurqgaqmhjzx5rfj4mad8hrzth4uf9wiwu399vsby7atqr9gwwxrxjdnebuhz2qkgulh9 osqkwaooeo59cpovjfi74jt4hafeogoqf2ht36kwk5tgwcpfjaqp3wlas2vlbzqtknje4 vyceezfjcsp7xjghs5qsu5xkuvpj7zplad7t311fu8mz7ljm6jvjfltiplr65nx1u7x3913avn k7sf546vfalygz04wffgcn69ffoea9h0y9zubpp8j9ewjyaemdj5j3oeet4rps2c4ocmfzyhgnum drxxyturv7gjukdnawm8hlhyf8agjidaoef59wmk5b7nnly2c9orv1ti0uuye8thbqseuytd 7nxnzp2btt33eku7pqt9cgvde3rngt798d3htfoepum3fcbzx3xpr73p1gehrbgvsbv a9envuepd1ypvehpve2xdfdlmxruwcub5i6lzu98avpqpnt3aomra0lcu8axvvp b9ch5fyy46vgjgz9mhod16vrlmnpamsf9xhkvapuhqxuoftwh3qet35ygyzz1uzvodxr zfx735mhoewocfeb3i6dpostgzju1pahqu7fjhg31gd4oaehudc9sovzv5nfqgv3tjy2bffa hfgwscf4b5c5jji9mnuea8zmsu1pg2u1995lme97263vkle95p1cjhbczbuvfattoy95yljt6n9 xeyxnq0fxh7lvh2tzfenjg8ael5flowm5cnqdmauamacx6wroxayp7pjgcbifrgcdah4z68nu sfun8ce9ch4y8o2xhhqng8p2pr02wwxujgw2yzcnofmzlysmd5ydymhrst8p3dmpx35paoufx 5zqfdwljmiynlv5vfnj6kn3bajvf0s0s2wjo81ec53ngyn3dspvzxs1kub6vvjr3dexr3l dfsnefabrqauafabrqauafabrqauafmr8epabefhj121odg8 ubry1bawbc1ianu7fqcclku2rrnpjv2ryyvurz2geegfvjorz9c85waxwbsp7wz58 yemldtv7tv8awgni8ytziph2yw0nvid4jissnkynqw1rgdyqacwjlh89dpitteem2hidqnrgow goaenr0ucf8wc2mc98d15pug4ryoosijkec8fgmlk6vse28r8th6wlrjtkwc78eznlocg lccm3skoc1lew8otvt3nfxuns25s5k20ewwv2wdcencf7fvjqep7dzkvuqxbfnwe3fngt798d3ht f5xbffeb2bwchg4bgx9r3anbcf9w3t9cwaqhfp8ppc5gsetxytl3x3szpofq1pubwcs pqvth9dzxrmlu25gpudr6sb0p1zxgd1ch9uhvwcpf41wl1xggdvzpld8dn0gosrmj2y7r7p f5h9wp1zf8ayrsxn8azmf7httpc9e344r1wdzbsto17x4y1delaiqow09vujh2hufew1sa dj6jrtk3ypuam3urkffxtjunfczwfqpjlx148ap7p07dxmnf8qasnj8n6ssepz4yosnxp2l ame1fd2u6f8aapuid4xwjh4updf8aggvxy4kcaenl8kabpkxzzolegi9fbqi15ikmqyhmevs djk1ngeyzkixndjo9no9ld6k16u0kmz5bjzm3gshs1buudxbbnlfvunyp26cyb5xbmp0mo rld8qcigaoakacigaoakacigaoakacigdyn4uahyeiphb8qta 1ebrlufcovjibkbvxtp8ec44iz9c3pbrdrwef8m1eptr8gltrs4yinqgoeheopjf4a1 vn4zq3ofek8uazooegjzzx9ivjzfkp8zdpmv61zj00yyevzn8favzrjvwk8oltps7unp4 huxptdhh1ppknaimoo8jlmi1jsqkt16j2v09e17c1lh3m20sdmx9snvs1ryrfpav2t9xt otg01dvzwan4jwdqw2hyahpn6jpnq0unpy3ij1tsb2hqzioovgvyapz433gep8af vfpwvmpwngpf8ksji7wfp40hhrc8buna6t00rvxypo3j5ooevgfmbxt8cf2dpvzp3c bpaaghghszgf8ambz7eoddobkjf8aqvhuvxamsruz9q1qn5af8abp1536namfwd ap8a9hwhruswhg7wqxihxfqfh4f0dtvqhqnef2f3ipuo2pxgqoaintpjt39qgdovjj2hn pvh99v6nqa9usvorw1exdvgb8rfilr9h4hnvxc8wedzsdttp167h2cwzsf2tpwf7bpgcc 4powbv4fzv7pfacr0wbvl790f8a5wbcmil9qt4naf4gssphj4q1dijtnv86f8a2jgt avjbvjgx8gcojopg5rlh9nvrlpw98fph7plib5z0fb9sou3vbfv23enqdqq98hqes35ucv a2nadp9nafyy7avjyowhc8evrknp6cvdfdfwvnpwjwicfswj9xtmv2xghclbxmrj3s03 1jlv7vxvbv9gfkggkuytur33t1f8aeubqy7u1tngk9lnpnfpx8wfabrqauaf fabrqauafabrqauaffujllbnc12w2kjdazhvh0jgohxqtkwa38yfcgnfl08xe vxqvqn9mgyv4851mio6y9nj4ujjaoh8e6kmnehr08fr0fyvrbwx9udjv04bijpyxqbabhqop wzapr21s8fxo6hfn7dfacbz9hzxl7aszhj5ix5y9csc9a4tvls1tg4pgwx15bgmkjn ufpysqb8jxnhxgk7t7k91pvjo1lsnz7a32aumoofstpk1r2vdxva8lezxztbnr3undsbbpilx 5p8ah7ur82fhuhabmzduxlpwdrm5hsvvr4s6r85dunf6dfzytx5ekjwdiyyf8b6ac 9ff2n6cnff4anag56vupush0wavp3ivpdkhnthr6tpr6nj5gtx2l8powcffemkz6e fbj8t7n274z3bjx9gdy4ptt6y9pxv6dfxhwqo3gfqfsunn8pbgchem4xzjjkdnpxrx096qb4 fa0nr8a2omyeg90ez6btbi22atyno7kqfml6sysdomhceatffhqdudr1httpsgpsad0ywotnp8a hot9iegdchgt9psxxainab9ornkdhy8djxyccjnfdcg4pgyxk8c0ncsuzxb1i5vivezatv22 vcc4nxkwb1wqabaum7cwb71bk9lepxmu6k4wektprg2rewdcyhn4v8wfuq56yxxjlsjpxorg sl5wnlepeduq24dlv8azxhbt6dxkox8qanfabrqauafabrqauafaerc9 up1plemfej4yecfhhgqa3ete61egf2fonk4elo1gcwji09hajmkvze7sfyfmr5o1b4zelx8oww j8hwbxk2jzfnbcajva20dpwuacsapve6ytlcbjbpltzvl9rzdtvra8xeot0cx1l66emq13629o7 7ayhipx34o8ih013xbnlwabjdd6g5jczttoppmgb1of4iyssa8w1r466lfq48kag1itt4mf q318ac2aulicgyzwzmeplig7plggebecdqpgrjgfnhndfj8oh15z65puh6dpmchbooma9ce4jho c3tosa9oodwgdi1jutsk1stnnrvfezcnfsuxv66o1rju95attyvom9ltaj6px8uubnxdr6m12 916c4wowaagomdgamywptgaccacgpdtt39ndrafd159n2oxz1p6dc17lbar83h45pqwzk9cfp kjknnbuclg8dj3p9761ostzwsas0ssjay20r5mendar5id73xfig2oacno8azppt0ly6naz g55j6dkge9dqgkadrnkilhz78dscecdrnrn35hfd17eua2nud9sf731y3zzgynn1bmtaz 6a8n36dpfjjk9cg1xyplgp81la219ln7x1fyv7ov20nfxcf7emuvvt8o15jrrpbw0wqtv2vdkzh iv7nfjdxagpgxbod5cb92n93a6j16dahuetfgofsbtdfbypepsnq67alb4m0d1yry gorwr0pqcsstx7oye9pionyt2prgdffhioyl8kqs2dqvj0wcez6577j68a6jmrwzkwnum pdffw91esvft9hayjl3xf6jcct57qn6nb6xlqlay1t3tprd1lhpzsvtcmr4f0gw6zn4nsbz kgcaov1ddnnmvqv4dsjeitp8zais7xhyac3y8acdxgnmk6ytyr16446kviz8kwbgtqfj13 l64u5znasxhpw62sm6geox55yc5phbpbbxzjndwd4myla31b89vtzpxur7l70r3bupect5573 bsys7wvpdjt2vfxel3pd638g8hedfd3h4htta086hqa5ijrj0mm57cg4ne2anof8az4budq51 djt05bp5gd6eupvauegnafuwf17bxz6drn157jjtecfukp8ajpakssgafwuv2jp5z6zgelzs uk8nqp8azeplwcjhjtdibxk8h0vjajrc84pif41v88omf4uantpenykvodqhgptxk6g oxb6mocaoaor97oac9dp2t6fqio04ixjot3yhoftb0hnjripv4vb1ms9gif8aoulxbwj6f 5l8nmtwnbsvx796263pz6k8is9c1htwqceempdz3h09sbtkiuz0zxfpohgxpgcrlkk5omd cg8hdd1ot0ra3oqoakacigaoaiiwob68hfx0zmvnv47gcxd3gatvcq32vair yeh9pqaezesjmx0w3krpsrvwdqvzevmajh0gtknnjtngvywkl2piwdfvub9sbp2nlta0abc brptnkaryctgvizo3xlj1ogrsyrbxcalfsks9d1dv535e99vdbu74csvtl8x8tdlxemrvf3jy 3wlopidxr2omvft9fxt5fx631fxogfublcgdhqogxwasmdhp3zohh7ttp07twb8316ylyosao qprgn0ncp4w0toswbwrxj9m95nja5obxrejxagba8k9ocohyenvnpnoe5nevimvy3it1fwdtf zyilowvpdjxaaffghv9fzr5uvxt7977vxq1a7d91voldjzwoa30h04z1p9rjgvm6nyyz9ap8a 0l9ob7deudxf2falz1k8wszrew6l32sf8a1446zodl7ofqfkpiqioopyi5v4vb1cqnb 98atn7uqsgcxrveigcxrveigcxrveigcxrveigcoblgdykvrvonakfjwwtddgzdqbvmq v5tn2vv6qeefufmp8kdxz1zwzrv8aabnhqb09qsqr1adzwtkg8h6hoedz2b9vxr5z0vf7p1 lh4hhme3utxvttml6zddnwkk8djx3p8aiousa468uua2zsdvpmndplx3vvnr9x5kpz1ml93 lf8a7efvnvtormyuafahjfxh8xnwd4b8r6lzyta2rsdohpabaizhoxjf1zktwcev 8debtjwomfl9eevjx65655r2t9phxelxno8odhafbz0y49d2ue2epznpihydp2n9vypqe30 uhj4ffqykchg3bewsvw81vrp7qa7a73kehixfmv0qnfje0tx4s7kh7rfrk6trpx9vpptpyf7zd0 ypxzgygtwa5k3n93769ivn3geqn2m81pwu8axmcppxl9sthptpp3q6dqj7ew6l3anrh wbfuoomtm7tif8akan9u8aqqw7k9hrngt755xkemhkmvha36kz6kancisigdqorpooa0k kz6kancisigdqorpooa0kpxf3fwwdjlmqcxo30t0ksgdi7vrps0lrvs1gfrh4e98hpg eorm82t7kug6c48zfn688v7knooe5gm4a59r8c6qlyft88egwbu55bgc9m9evjpjjnebsf exppsu1h99zibxyrqoafcybhb3prz9n1cj15vn0vs593dv09xhxlrh0hwcllz8lgrt r9i0uuv556ouav6y9auxpuianqa5h2m6hqofvcync9tnqi9moeca1k82mo8a4vf8vfsw z7zwr7x15ftdu4rvws54ft255z05zwwg2fqvaepfl912sv4x8tti9funn53ajqo8ylt s1dnjyfh0pqenczppunqffqozpplpa67rnw74mar4d8yg6hogof2h0tdt8f8tcw1dlapeu 1bsicft1ppxkivpu6vgnh1odj9ew4pfj9ktrw5f19o8kyktwux8puzxkfx39uopxvaxo30t anckpkapqpwdpahh85x0h8zgfr2psk4mcgnlts07oiy9bewzntnv2xnwfhhfaa6dx7fgt nfucnbjwa5l4ptapcpelvdiiyxaa0uonizjjv09oeu7jzivh5jtt7p9f8aps9xoqccfhsf 55p075x364jgtsugzyoqvrqbyoqvrqbyoqvrqbyoqvrqbyoqvrqbyqc7n4i9mev3755x0z3oets vi6vp97apvz09zh1zqbxv3pwr6y9f9v3zzjpnuc8mq3n36fagvvpzufbb4zgymepjjq cug6cewfrn2mum4gppnqssa0tan08h9erduppzz1aiyutwsbh734dprzwdwyfosa27u8o dtp1pxd4v8qafoggadj0nrv73t9p07zypxuafy5jkkealtmvf1ht7kh8qbp4mrsevoqnn1pu kkx68ye3ittff3w90dxdpun3emwoqy61f2njqgwxrwr8tauix0pyke3iwpv1pl5mqllgcfta8ku tjlzwxaah80t02d8phxovwdrf1b3lfajcsu8tytrtlwvsfzlxwswbwzk4dw7fxfhjjpix ycc6lfah5rfhd9idubdxwixws8qah4n1jai8bts9xzwvb64wed8xizxhwmfthfhb4wbvdnx9 gvrn6bjhihwly6fpohljwagrdyi6hv4bpjb9yycovcfjn3rknb8hehabane02yv9 uac1pk8sqc4zjybwsteepnexhm8cvbmpewm7vl7s7wvthevqzbbxd9vts7fjb9ov8aw176n53e fpjapbr4gg2b4wsnp1djintezohidqfjxrb7nhhb5rnbjr1hy978rvqof2gfg34xbp 2dzniawbodz3ipv79d3hc37dfxc8g5hwykpi3trda4l51gjt8zignlxycdop5gmvtjih5l tl2v04yt6rby133wt02cpljv5pfc8apu59ma78as7xac84wnvp17gnrthrji5jle9n8cvdh 8qehylhajcawcqftfm3ca4xj8tnibbz8yj4bagybyhapcxjhhq3ijt9qpzmf8ameajhb5 z07nktovx8a2h9n3dxd8il8tkc2gtafqgovqccjibycdooc1zlk19dlzqwsvzrw6vkqxn210v etgsurp3pawvrsrvx427bxv21s7tu31b4o1fin7d0jp8aiycfw3wbpbjgfxbjz0rrf7xwcm n6fafqg5f2s10kpaau8w6fjqehpz4g9snysdkh7wxwp536br2n46lvxj79v7b9uov b5ioglsvgyw5ib9bfef3l5i4vt8a01xal5tr9v6ar3zwdwr4e4ardhpabpb t8ywcp01htmrzbggjpt3xxkk8tmxf7s3wp5hce2hyf8huw9zoxb26fxomkesvgyw5 acafw33n9yspvb0fvlrwakp7qx8v5hcvzcu2pfh6m8vh5oad37zz0hipbpjiapny twedurwmoe3b1f39fxbydyk3shh9odpaoqf9zvvpvaptz9sf7zx9pwpv8aac3li 4vvwdw1z4fwchxzdauh7uvg75gpgfgcymf9rttoo495yop7r6famgh1n9uao3p 083wdtvf8avn61otfppn1qowxao8fnwav7opbhe7so5yhv6de2qosqtwkp2lvh1z wav9ng2o6he6a7h1o45o41hzenlh9z8akbw33n9y8akj7ap7wh98f98jaapp7e0 v5fxr4bgawhqdf8t7xtq6dpdxjltu9nb6j68jmid9oftnrzzg7x5qhtajltu5bpmwf 7a49ep4xrzenlh9zqd628uxyr96yitowfk9p4vqvj6475xhoses1fw7qz8ncfxzvd ofzoyrgzs4pin8vnqzyhwn148ddev9psnp6spx6z9ioogztqat1v4wylhw94r8haf8vw11dx tq0lx38qhqet1kc9hmpexjk7ceu7vlvzby7el29qtj7nvalf9fnvlfz3gm6hfxvn wcvxeekfi98khadwn3xd0ht9q4h9nm73iocf8aiv6of7e9db64riip2qpjh4xo3x8xff n2ejp9nadf8a9gwbwzf9ac5x3yt2xzivyfan7bwy8giznthf32adzhjgsm8gezyum54x6mjha8 n00uxrrbzo23x73zj2795tpkzup2vvih4w3ehf2dphbf6gbjd4x8ewf8aznaplujyfc2jn k84xz4a6nobk998mf2spil8qdd04hftomb7xhqfirf6b4epev8p6exph9kf9ii0lscwhiysr jksfqfbpgw8gog6dywgduflqjoxaogl6cyzxykqpb069v88a665i56rssrxwvlev7j t2uuvapxszbi2dkwqkm8fabvtlvo5xtsn66rrtwvlozpwladowmwwnws7bkxvvs1zkghzu4og4i iih8q4wmnbooryt0qoakacigaoazput9pjlexejvphtsiitcltl0wdbhdfl wc3hzd4u5l9u9gsv8wjwn1t2prrx0ufbz5b86ie30htsvits7fh7uoor6whsr lhj1wchlvthi3xrv8ap8nytffd554vtwfqh6djrrqb2oifed2wsvvtailffcei3f lvd11vl0h6vupopwndwadr6g8gff0iivmcz1hhwc7b3yprjxuqkpdh3v8agl16nbfd p0flyjziwdsqh7s3l6qwdsqhs0uuvkmkacigaoaz button2setonclicklistenernew onclicklistener override public void onclickview v todo autogenerated method stub bitmap bitmap imagebase64decodebase64base64stringreceivemainactivitythis imageview2setimagebitmapbitmap imagebase64javaimport javaiobytearrayoutputstreamimport androidgraphicsbitmapimport androidgraphicsbitmapfactoryimport androidutilbase64import androidutillogpublic static string encodetobase64bitmap image bytearrayoutputstream baosnew bytearrayoutputstream imagecompressbitmapcompressformatjpeg100 baos byte bbaostobytearray string tempnull try systemgc tempbase64encodetostringb base64default catchexception e eprintstacktrace catchoutofmemoryerror e baosnew bytearrayoutputstream imagecompressbitmapcompressformatjpeg50 baos bbaostobytearray tempbase64encodetostringb base64default logeewn out of memory error catched return temppublic static bitmap decodebase64string inputcontext context byte decodedbyte base64decodeinput 0 boolean issdpresent androidosenvironment getexternalstoragestateequals androidosenvironmentmedia mounted file sdcarddirectory if issdpresent yes sdcard is present sdcarddirectory new file environment getexternalstoragepublicdirectoryenvironmentdirectory pictures myfile if sdcarddirectoryexists if sdcarddirectorymkdirs logdmysnaps failed to create directory else sorry sdcarddirectory new filecontextgetcachedir string timestamp new simpledateformatymmdd hhmmss formatnew date random rand new random nextint is normally exclusive of the top value so add 1 to make it inclusive int randomnum randnextint10 0 1 0 string nw img timestamp randomnumjpg also tried txt as file extension file image new filesdcarddirectory nw encode the file as a png image fileoutputstream outstream try outstream new fileoutputstreamimage outstreamwriteinputgetbytes outstreamflush outstreamclose catch filenotfoundexception e eprintstacktrace catch ioexception e eprintstacktrace logicompress bitmap path imagegetpath return decodefileimage bitmapfactorydecodebytearraydecodedbyte 0 decodedbytelengthprivate static bitmap decodefilefile f try decode image size bitmapfactoryoptions o new bitmapfactoryoptions oinjustdecodebounds true bitmapfactorydecodestreamnew fileinputstreamfnullo the new size we want to scale to final int required size70 find the correct scale value it should be the power of 2 int scale1 whileooutwidthscalerequired size ooutheightscalerequired size scale2 decode with insamplesize bitmapfactoryoptions o2 new bitmapfactoryoptions o2insamplesizescale return bitmapfactorydecodestreamnew fileinputstreamf null o2 catch filenotfoundexception e return nullerror stackjavalangoutofmemoryerrorat androidgraphicsbitmapfactorynativedecodebytearraynative methodat androidgraphicsbitmapfactorydecodebytearraybitmapfactoryjava510at androidgraphicsbitmapfactorydecodebytearraybitmapfactoryjava533at comutilityimagebase64decodebase64imagebase64java32at comactivityhomefragmentoncreateviewhomefragmentjava138at androidappfragmentperformcreateviewfragmentjava1700at androidappfragmentmanagerimplmovetostatefragmentmanagerjava890at androidappfragmentmanagerimplmovetostatefragmentmanagerjava1062at androidappbackstackrecordpopfrombackstackbackstackrecordjava773at androidappfragmentmanagerimplpopbackstackstatefragmentmanagerjava1498at androidappfragmentmanagerimplpopbackstackimmediatefragmentmanagerjava495at androidappactivityonbackpressedactivityjava2232at comactivitymainactivityonbackpressedmainactivityjava534at androidappactivityonkeyupactivityjava2210at androidviewkeyeventthispatchkeyeventjava2664at androidappactivitythispatchkeyeventactivityjava2440at comandroidinternalpolicyimplphonewindowdecorviewthispatchkeyeventphonewindowjava1962at androidviewviewrootimplviewpostimeinputstageprocesskeyeventviewrootimpljava3884at androidviewviewrootimplviewpostimeinputstageonprocessviewrootimpljava3858at androidviewviewrootimplinputstagedeliverviewrootimpljava3426at androidviewviewrootimplinputstageondelivertonextviewrootimpljava3476at androidviewviewrootimplinputstageforwardviewrootimpljava3445at androidviewviewrootimplasyncinputstageforwardviewrootimpljava3552at androidviewviewrootimplinputstageapplyviewrootimpljava3453at androidviewviewrootimplasyncinputstageapplyviewrootimpljava3609at androidviewviewrootimplinputstagedeliverviewrootimpljava3426at androidviewviewrootimplinputstageondelivertonextviewrootimpljava3476at androidviewviewrootimplinputstageforwardviewrootimpljava3445at androidviewviewrootimplinputstageapplyviewrootimpljava3453at androidviewviewrootimplinputstagedeliverviewrootimpljava3426at androidviewviewrootimplinputstageondelivertonextviewrootimpljava3476at androidviewviewrootimplinputstageforwardviewrootimpljava3445at androidviewviewrootimplasyncinputstageforwardviewrootimpljava3585at androidviewviewrootimplimeinputstageonfinishedinputeventviewrootimpljava3750at androidviewinputmethodinputmethodmanagerpendingeventruninputmethodmanagerjava2027at androidviewinputmethodinputmethodmanagerinvokefinishedinputeventcallbackinputmethodmanagerjava1721at androidviewinputmethodinputmethodmanagerfinishedinputeventinputmethodmanagerjava1712at androidviewinputmethodinputmethodmanagerimeinputeventsenderoninputeventfinishedinputmethodmanagerjava2004at androidviewinputeventsenderthispatchinputeventfinishedinputeventsenderjava141at androidosmessagequeuenativepolloncenative methodat androidosmessagequeuenextmessagequeuejava138at androidoslooperlooplooperjava123at androidappactivitythreadmainactivitythreadjava5050at javalangreflectmethodinvokenativenative methodat javalangreflectmethodinvokemethodjava515at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava806at comandroidinternaloszygoteinitmainzygoteinitjava622at dalviksystemnativestartmainnative methodi am also getting this error too in some devicesjavalangoutofmemoryerror failed to allocate a 38340876 byte allocation with 994361 free bytes and 971kb until oomat dalviksystemvmruntimenewnonmovablearraynative methodat androidgraphicsbitmapfactorynativedecodebytearraynative methodat androidgraphicsbitmapfactorydecodebytearraybitmapfactoryjava655at androidgraphicsbitmapfactorydecodebytearraybitmapfactoryjava678at commyapputilityimagebase64decodebase64imagebase64java53at commyappactivitydetailprofilefragmentoncreateviewdetailprofilefragmentjava103at androidappfragmentperformcreateviewfragmentjava2114at androidappfragmentmanagerimplmovetostatefragmentmanagerjava904at androidappfragmentmanagerimplmovetostatefragmentmanagerjava1082at androidappbackstackrecordrunbackstackrecordjava833at androidappfragmentmanagerimplexecpendingactionsfragmentmanagerjava1467at androidappfragmentmanagerimpl1runfragmentmanagerjava452at androidoshandlerhandlecallbackhandlerjava739at androidoshandlerthispatchmessagehandlerjava95at androidoslooperlooplooperjava145at androidappactivitythreadmainactivitythreadjava5944at javalangreflectmethodinvokenative methodat javalangreflectmethodinvokemethodjava372at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava1389at comandroidinternaloszygoteinitmainzygoteinitjava1184solutions that i have already tried arestrange out of memory issue while loading an image to a bitmap objecthow to convert a image into base64 stringout of memory error imageview issueout of memory error androidimage encoding and decoding using base64 in android application,"['java', 'android']" +878655,codeigniter cannot load libraries initially i thought i had a problem with loading libraries due to using modular extensions inside codeigniterhowever i have thiscovered even with a clean install of codeigniter i am unable to load libraries such as the session library or even the migration libraryi always get similar error messages usually to do with loading fileshere is my error message i have when using the session library note if i do not use libraries everything works fineerror a php error was encountered severity warning message mkdir functionmkdir invalid argument filename driverssession files driverphp line number 117 backtrace file indexphp line 301 function require once an uncaught exception was encountered type exception message session configured save path is not a directory does not exist or cannot be created filename systemlibrariessessiondriverssession files driverphp line number 119 backtrace file indexphp line 301 function require oncei feel like this is some form of permissions issue but whether i am using ampps mamp windows or xamp i always get this problemdoes anyone have any ideasos windows 81webserver amppsmampwindowsxamp all have the problemcodeigniter v300configconfigsess driver filesconfigsess cookie name ci sessionconfigsess expiration 7200configsess save path nullconfigsess match ip falseconfigsess time to update 300configsess regenerate destroy falseeditresolvedit is important now that you use the ci3 documentation when using the database method for sessions please ensure you use the updated sql to create the tablecreate table if not exists ci sessions id varchar40 not null ip address varchar45 not null timestamp int10 unsigned default 0 not null data blob not null primary key id key ci sessions timestamp timestampas found here i hope this helps anyone out with similar problemsalso for the initial problem if you are using the files driver please ensure you set the configsess save path to something like ci sessions or wherever you wish to store please see tpojka answer for more information,['php'] +878746,use of constexpr function before definition fails i am having some trouble with constexpr the book c primer shows a line of code constexpr int sz size only size is a constexpr function this code is righthowever the book does not give a specific example so i try the following code by myselfinclude iostreamconstexpr int funint main constexpr int f fun stdcout f stdendlconstexpr int fun return 3but my compiler said fun is undefinedif i change constexpr into const it works well and if i change my code to define the constexpr function before useinclude iostreamconstexpr int fun return 3int main constexpr int f fun stdcout f stdendlit also works well can someone tell me why,['c++'] +878761,bokeh plotting enable tooltips for only some glyphs i have a figure with some glyphs but only want tooltips to thisplay for certain glyphs is there currently a way to accomplish this in bokehalternatively is there a way to plot two figures on top of each other it seems like that would let me accomplish what i want to do,['python'] +878775,xcodestoryboard cannot drag bar button to toolbar at top i have a view controller that is the detail view of a table when you click on the row of the table it takes you to the detail view the detail view is embedded in a navigation controller such that there is a button at the upper left of the navigation bar that sends you back to the table so far so goodi now want to add an edit button to the right side of the navigation bar so that you can edit the detail view my plan is this will add another view controller modally that lets you edit the details of the item standard stuffhowever when i try to drag a bar button item from the list of objects to the navigation bar it would not take instead when i let go off the mouse button it leaves the bar button on the tab bar controller at the bottom my navigation scheme includes different tabs and for each tab a table detail view etcanyone run across this before and can suggest what i am doing wrong or some sort of workaround to add the bar button item to the right side of the navigation screen do i have to add it in codethanks for any suggestions,['ios'] +878919,systemnumericsvectorsvector is missing i am studying examples of simd operations in c and want to try some exapmles i downloaded nuget package systemnumericsvectors v40 and want to reproduce examples from the internet but they does not work because this library does not contain class needed target framework is 46 but there is no vectort for some reason and i do not know whymaybe it was removed from api but i did not found any correlated info why they did it,"['c#', '.net']" +879226,clion auto documenting functions classes is there any shortcut or something like this to add eg documentation of a function or class similar to in visual studio and cthanks,"['c++', 'c']" +879288,wrongautogenerated provisioning profile when submitting build to app store i am attempting to upload my ios app build after clicking submit from the organizerarchives window in xcode it seems to select the wrong provisioning profile to submit it is also not editable i have the correct iphone thistribution signing identities and app store provisioning profile in both the project and target under build settings i am skeptical about submitting the app with this autoselected provisioning profile xc rajibtho instead of my parse push app store profile am i doing something wrong here my app uses push notifications so i want to make sure the provisioning profile is set up correctly before submitting screenshot here of what i see,['ios'] +879434,is it possible to create extension methods like in c using macro in c i would like to extend the stdstring and to add equalsso i did the following define equalsstr1 comparestr1 0and used the following code if strequalshl which i assume compiles to if strcomparehl 0 and everything compiles greatnow i want to improve my macro add brackets to compile to if strcomparehl 0 i have tried something like define strequalsstr1 strcomparestr1 0but it would not compile the macro simply does not fithow can i achieve it,['c++'] +879471,unicode string equivalent of contain i have an error when trying to use contain in python s usome utf8 wordsk uone utf8 wordif scontainsk print contains how do i achieve the same resultexample with normal ascii strings haha i am going homek hahaif scontainsk print containsi am using python 27x,['python'] +879499,compiling wxlua crossplatform static i am planning to create a new c project write some c functions in it embed a lua engine with wxlua into it make my cc functions available to a lua side and then write my main program including the gui in luamy idecompiler are codeblocksgcc on windows i want to compile it for windows linux and osx my issuescompiling wxwidgets and luabuilding wxluacreating a crossplatform project that knows which libs to use for which osi read a lot of documentation on wxlua and found that you should probably use wxwidgets 2812 and lua 523 as they are the two latest stable and supported versionsif possible i would like the program to be a standalone executable in the endso i guess i need to compile lua and wxwidgets as lib libraries windows and a libraries linuxosx is that correct how would i do that once that is done what kind of project do i need to create and how would i embed wxlua into that project i could not find a lot of information on that and finally how would i tell my ideprojectmakefile which libraries to use for which os,['c++'] +879532,does google play ask to accept custom permission as like in built permissions in case of auto update i am working on an app where i am using a custom permission as defined by another developer in their sdkaccording to google if we add a predefined permission such as usespermission androidnameandroidpermissioninternet then when a user updates the app they will be prompted to approve this new permission this happens before the app is updated if the user does not accept the app is not updatednow we want to add in this custom permission will the play store still ask users to accept this new permission prior to updating the app when we release the new version on the play store,['android'] +879550,how to properly write a dfp out of page ad unit i am developing a javascriptrendered mobile web interstitial the layout is fully responsive hence it will take 100 of the provided screeniframei now wish to thisplay the interstitial through dfp at first i created a sized ad unit 320x480 and it worked just fine but the interstitial was limited to the boundaries of the iframei founf a new line item type called outofpage the documentation states thatthey may include popups and floating line items and are sometimes called interstitialsbut when i try to embed the interstitial in a test site what happens is that the iframe stays 1x1 making the interstitial invisible if i manually enlarge it with a debugger i see itmy settingsline item with inventory sizes of 1x1 and out of pagecreative with my code snippetad unit is defined as size 1x1 i read in the documentation that if youre using a doubleclick tag creative you must ensure that the creative code trafficked on the other end of the doubleclick tag ie another dfp network is properly coded for an outofpage ad unitwhat does it mean in terms of dfp outofpage interstitial that the ad is properly coded how do i force the interstitial to take all the size of the screen,['javascript'] +879562,placeautocomplete got unknown status code 90 i reused the code from google placeautocomplete sample project by android teami used different key for each project also enabled google places for android in google consolewhen i build and run the sample project it was working without problemhowever when i run it from my app sometimes it is working other times i got unknown status code 90 from statustostringi got this on the console0408 011539331 1614810791 wplacesi1 fa633 glocreplyelement unsuccessful status 10408 011539332 1614810791 wplacesi1 fa660 gplacequeryresult unsuccessful responsecode 260408 011539339 1055811608comtravelappkaret wkareti1 error getting autocomplete prediction api call statusstatuscodeunknown status code 90 resolutionnullit is very strange so when i type si start suggesting placesng so when i reached the fourth letter i occasionally got this errorso the only part that was different was only the int value clientid that i passed to mgoogleapiclientenableautomanagethe sample project use 0 while my project use 93938838939 random number i am not sure what value should i put here it rejected number that is already used by other appother than that the codes was no different only that i put the googleclient variable on activity but the actual autocomplete implementation on a fragmentplease help,['android'] +879845,flexbox row how to stretch children to fill crossaxis i have a leftright flexboxwrapper thisplay flex flexdirection row alignitems stretch width 100 height 70vh minheight 325px maxheight570px div classwrapper div classleftleftdiv div classrightrightdivdivthe problem is that the right child is not behaving responsively to be specific i want it to fill the height of the wrapper how to accomplish this thanksdebbie,['css'] +880113,mysql forcing query to use indices with local variable in where clause contexti have an application that selects a weighted random entry from a table for which prefix summation of weights is a crucial part the simplified table definition looks like thiscreate table entries id int not null primary key auto increment weight decimal9 3 fenwick decimal9 3 enginememorywhere fenwick stores the values within the fenwick tree representation of weights let the range of each entry spans between its prefix sum and its prefix sum its weight the application must generate a random number r between 0 and sumweight and finds the entry whose range encompasses r like thisthe fenwick tree combined with the memory engine and a binary search should allow me to find the appropriate entry in olg2n time as opposed to on time with the naive queryselect aid1 from select xxweight as counter from entries cross join select x0 a having counterr limit 1 aresearchi have been trying to condense the prefix sum operation into one query as opposed to several array accesses seen in scripting languages due to the overhead of multiple queries in the process i have realized that the traditional method of summation which involves accessing elements in descending key order would only sum the first element i was suspicious that mysql runs through tables linearly when variables are present in the where clause heres the queryselectsum1 into garbagefrom entries cross join select sum0 nentryid awhere idn and n0 and n and sumsumentriesfenwickselect sumwhere entryid is the id of the entry whose prefix sum we are computing i did create a query that did work alongside a function lft that returns the leftmost bit of an integerset nlftentryidset sum0select sum1 into garbage from entries where idn and nentryid and nnlftentryidn and sumsumentriesfenwickselect sumbut it only confirmed my suspicion of a linear search so too does the explain query id select type table type possible keys key key len ref rows extra 1 simple entries all null null null null 752544 using where 1 row in set 0 secthe indexesshow indexes from entries table non unique key name seq in index column name collation cardinality sub part packed null index type comment index comment entries 0 primary 1 id null 752544 null null hash 1 row in set 0 secnow i have seen many a question asking how to eliminate variables in the where clause so that the optimizer can work on the query however i cannot think of a way this query can do without idn i have contemplated putting the key values of entries i want to sum into a table and using joins but i believe that i will get undesirable effects either a plethora of tables or a linear search by evaluating against entryid anyways questionis there any way to force mysql to use the indices for this query i will even try a different dbms if they offer this functionality,['mysql'] +880114,how to find if a mounted drive really exists on mac what i actually was trying to achieve is to find out when a drive which i had mounted from network is thisconnectedfor which i started with a very simple approach i usedboostfilesystemexistson the mounted path of the drive which we can find in volumes eg for a drive on computer smbxyzdriveafter mounting i can see it likevolumesdriveand the later was the drive on which i was using boostfilesystemexistsso i was hoping as soon as i will thisconnect the network the mounted volume inside volumes will be cleared immediately and everything will work simplybutlater i realize that on network thisconnection osx takes like forever to clear drive from volumes directoryis there an apple api which can tell whether the amounted volume which appears in volumes is a valid one or notthanks in advance,['c++'] +880143,legitimate uses for static initializer i remember a couple years ago i was using static initializers to call classlevel setup operations i remember it having very bizarre behaviors and i just decided to steer clear from them maybe it was because i was messing up the topbottom order or being a newbie but i am encountering a need to revisit them and i want to make sure there is not a better way that is just as concise i know it is not fashionable but i often have datadriven classes that maintain a static list of instances imported from a database public class stratband private static volatile immutableliststratband stratbands importfromdb private final int minrange private final int maxrange private static immutableliststratband importfromdb construct list from database here constructors methods etcwhen i have dozens of tabledriven classes like this one this pattern is very concise yes i know it tightly couples the class with one source of datainstances however when i thiscovered the goodness of google guava i want to use the eventbus to update the static list when a certain event posted i would create a static final boolean variable just to call a static method that initialized the registration public class stratband private static volatile immutableliststratband stratbands importfromdb private static final boolean subscribed subscribe private final int minrange private final int maxrange private static immutableliststratband importfromdb construct list from database here constructors methods etc private static boolean subscribe myeventbusgetregisternew object subscribe public void refreshparameterrefreshevent e stratbands importfromdb return true this got annoying very quickly because the compiler would throw warnings over the subscribed variable never being used also it just added clutter so i am wondering if it is kosher to use the static initializer and there really is no better way if i do not decouple this into two or more classes thoughts public class stratband private static volatile immutableliststratband stratbands importfromdb static myeventbusgetregisternew object subscribe public void refreshparameterrefreshevent e stratbands importfromdb private final int minrange private final int maxrange private static immutableliststratband importfromdb construct list from database here constructors methods etc,['java'] +880156,how to throw an exception from callback in wcf async using iasyncresult i am using wcf async calls in my project and i am using client side asynchronous methods i have a scenario like below code in business layer and this method is called from web layer private void getgeneralnews clientbegingetgeneralnewsfeedgeneralnewscallback null call back method private static void generalnewscallbackiasyncresult asyncresult string response stringempty try response clientendgetgeneralnewsfeedasyncresult catchexception ex throw ex here is the problem it does not throw the exception to the web layer instead it will suppress the error so as shown in the above code snippet it does not throw the exception from business layer to web layer as it will be suppressed here in business layer itselfi checked in some of the blogs and sites they are suggesting to go for async and await approach as i have net 40 framework and i am seeing generate taskbased operations option thisabled so if there are any options using iasyncresult begin end in client side please let me know if there are any other approaches also welcome kindly someone help methanks,['c#'] +880195,upload video to youtube via android studio i am a new programmer in android studioi am trying to create a button that gets a file location and uploads it to my youtube accounti succeeded to get a video files directory in my android codefile mediafile new fileenvironmentgetexternalstoragedirectorygetabsolutepathi added a button that calls uploadtoyoutube functionnow i would like to upload it to my youtube account through the file path i havecan someone direct meany help appreciated,['android'] +880205,there is no south database module southdbpostgresql psycopg2 for your database i new to django and i am getting this error from south but i do not know what i am missing i search for answers but i cannot found anythingthere is no south database module southdbpostgresql psycopg2 for your database please either choose a supported database check for south database adapters settings or remove south from installed appsthis is my base settingsfrom unipath import pathbase dir path file ancestor3secret key ppiz7bc711usf7o er2o3zjsen6bwhem96django apps djangocontribadmin djangocontribauth djangocontribcontenttypes djangocontribsessions djangocontribmessages djangocontribstaticfilesthird party apps southlocal apps installed apps django apps third party apps local appsmiddleware classes djangocontribsessionsmiddlewaresessionmiddleware djangomiddlewarecommoncommonmiddleware djangomiddlewarecsrfcsrfviewmiddleware djangocontribauthmiddlewareauthenticationmiddleware djangocontribauthmiddlewaresessionauthenticationmiddleware djangocontribmessagesmiddlewaremessagemiddleware djangomiddlewareclickjackingxframeoptionsmiddleware djangomiddlewaresecuritysecuritymiddlewareroot urlconf misiteurlswsgi application misitewsgiapplicationlanguage code enustime zone utcuse i18n trueuse l10n trueuse tz truelocal settingsfrom base import template debug trueallowed hosts debug truedefault from email postgresqldatabases default engine djangodbbackendspostgresql psycopg2 name misite user fernandoperez password admin hostlocalhost port5432 south database adapters default southdbpostgresql psycopg2 static url staticcan someone help me thanks a lot,['python'] +880280,when to save data to database onpause or onstop i know this question has been asked a million times i myself though that i already knew the answer and that the correct one was that the only guaranteed call is to onpause so you should save your data therehowever in many places of android documentation they always suggest not doing heavy work such as writing data in database in the onpause method as it will delay the transition between the activitiesaccording to android developer guide in table 1onpause this method is typically used to commit unsaved changes to persistent data stop animations and other things that may be consuming cpu and so on it should do whatever it does very quickly because the next activity will not be resumed until it returnskillable yesthen according to android developer reference guide in the similar tableit says the same thing butkillable prehoneycomband they add a little note that saysbe aware that these semantics will change slightly between applications targeting platforms starting with honeycomb vs those targeting prior platforms starting with honeycomb an application is not in the killable state until its onstop has returned this impacts when onsaveinstancestatebundle may be called it may be safely called after onpause and allows and application to safely wait until onstop to save persistent statekillablenote the killable column in the above table for those methods that are marked as being killable after that method returns the process hosting the activity may killed by the system at any time without another line of its code being executedfor posthoneycomb i dont care about earlier versionsso is it ok to assume that any android device including different roms will ensure a call to onstop on the activity and this is the best place to make any time consuming storage writing of the appnote this is extremely confusing as most answers here sites books and even online android tests take as a correct answer that you should save it in onpause and not in onstop,['android'] +880350,program with noexcept constructor accepted by gcc rejected by clang the code struct t t struct s t t s noexcept defaultint main s sg 492 accepts this with no errors or warnings however clang 36 and 37 report for line 7error exception specification of explicitly defaulted default constructor does not match the calculated onehowever if the line s s is not commented out g 492 now reportsnoexcc in function int mainnoexcc127 error use of deleted function ss s s noexcc75 note ss noexcept is implicitly deleted because its exceptionspecification does not match the implicit exceptionspecification s noexcept default which compiler is right for the original codebackgroundg even allows the following to be added to mainstdcout stdis constructiblesvalue nwhich outputs 0 i encountered this problem when using clang to compile some complicated code that made heavy use of templates sfinae and noexcept in that code s and t are template classes so the behaviour depends on which types s was instantiated with clang rejects it with this error for some types whereas g permits it and the sfinae works based on is constructible and similar traits,['c++'] +880421,how to calculate formula from string to int i have a table that contains formula example of the formula gp1gp1 gp2100in my code using jquery i will replace gp1 with textbox1 value gp2 with textbox2 value and remove the i try to get the result by doing thisvar repl1 gp1gp1 gp2100var repl2 repl1replacegp1giparseinttxtbox1valvar repl3 repl2replacegp2giparseinttxtbox2valvar repl4 repl3replacegi so the last result will be var repl4 10100100i try to convert it to be int by doing thisvar result parseintrepl4but i get the result nancan anybody help me on how to calculate the formulathank you,"['javascript', 'jquery']" +880423,sharing callback doesnt work wiith facebook sdk 4 android i have recently moved my app to fb sdk 40 and i got some weird troubles with sharing the sharing dialog works great i am able to share with both facebook app and webdialog however after successfulfailure sharing my callback does not work at all so i cannot even show a toast or log anythingheres how i dosharedialogregistercallbackfbmanager new facebookcallbacksharerresult override public void onsuccesharerresult result this does not work toastmaketextfgetactivity you shared this post toastlength shortshow override public void oncancel override public void onerrorfacebookexception e this does not work eprintstacktrace i have even tried debugging the app no effect this code was not even calledso could you point me at what am i doing wrong or what am i missingupdatesince i am using special class for working with fb sdk heres the part of itprivate static callbackmanager fbmanagerpublic static callbackmanager initactivity c if facebooksdkisinitialized facebooksdksdkinitializec return fbmanager callbackmanagerfactorycreate public static void sharefinal fragment f final string title final string description final string link sharedialog sharedialog new sharedialogf sharedialogregistercallbackfbmanager new facebookcallbacksharerresult override public void onsuccesharerresult result toastmaketextfgetactivity you shared this post toastlength shortshow override public void oncancel override public void onerrorfacebookexception e eprintstacktrace sharedialogshowf composecontenttitle description linkand here how it looks like in fragment private callbackmanager callbackmanageroverridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate callbackmanager facebookhelperinitgetactivity overridepublic void onactivityresultint requestcode int resultcode intent data callbackmanageronactivityresultrequestcode resultcode data private void publishstory facebookhelpersharethis title getresourcesgetstringrstringsharing text sharinglink,['android'] +880432,javascript jquery save location in epub i am trying to build an epub reader for android every thing is fine and working as expected but the problem i cannot solve is saving last seen page or save position for bookmarka little backgroundi use css multi column to show epub columnwidth is set to windowwidth and columnheight is set to windowheightto ensure each column will fill the entire screencurrently for saving position i pre process the html and wrap each element with a div including a specific id that represents the section number and tag position for example a p tag after process would be like thisdiv idid 1 8psome textpdivthe id 1 8 represents that this text belongs to section 1 and it is the 8th element in that bodyi have a full list of these ids and for saving position i use jquery to compare left of the current column with left of every id so the nearest id will be found and i know that this page belongs to where in epubthe next step is to find offset suppose a p tag that fills 7 pages with offset i know that i must load the 8th element of section 1 and go to page 5look at the function in jquery for finding nearest element and offsetjqgetlastposition functionids var tempcolumn column column is current page that is showing iftempcolumn 0 tempcolumn 1 tempcolumn var realids idssplit var columnleft tempcolumn windowwidth columngap var currentleft var currid realids0 var nearestid realids0 0 var minthistance 10 var tempthistance 0 var exactcolumn 0 fori0 irealidslength i try currid realidsi currentleft curridpositionleft ifcurrentleft 0 currentleft 1 currentleft tempthistance columnleft currentleft iftempthistance 0 this id is after this page continue else iftempthistance minthistance minthistance tempthistance exactcolumn mathfloorminthistance windowwidth columngap this must compute the offset pages after nearest element nearestid realidsi exactcolumn catche jssavelastlocationnearestid this code works fine for most of situations where page offset is zero like id 1 8 0the problem arises when there is offset the offset page cannot be computed correctly i can see that there is one page offset but this code gives me0 offset or when there is 9 page offset it gives me 4so what is the problem with this codeor am i wrong doing this for saving locationis there any better methodupdateif i add div before any tag like div idid 1 8divpsome textp the result will be accurate in 90 of the time so the updated question will be how achieve this goal saving position in epub with 100 accuracyupdate 2i am putting the div for every elements eg head p link img is there any possibility that this makes the problem update 3i finally find what is causing the problem consider a situation where the nearest element to the current page start at the middle of the previous page i save the id of this element and the offset would be 1 when i want to load the saved location the element load at top of the page so a little shift in text would happen in the below image i show what is happeningany idea would be appreciatedupdate 4csscontainer width 100 height 98 overflow hidden content position relative height 98 mozcolumnwidth 200px webkitcolumnwidth 200px columnwidth 200px mozcolumngap 1px webkitcolumngap 1px columngap 1px img maxwidth 100 maxheight 100 thisplayinlineblock webkitcolumnbreakinside avoid the span idendmarkerspan will add to the end of body so i have a marker at the end of html contentthe jqueryvar column 0var columncount 0var windowwidthvar windowheightvar rtl 0function columnwidth containerwidth windowwidth containerwidth windowheight containerheight contentcsswebkitcolumnwidth windowwidth contentcssmozcolumnwidth windowwidth contentcsscolumnwidth windowwidth documentreadyfunction windowloadfunction columncount mathfloorendmarkerpositionleft windowwidth columngap if columncount 0 rtl 1 columncount columncount 1 2 informrtlrtl inform the java part that this doc is right to left else informrtlrtl reportnumberofpage columncount this will report to java part setcolumn functioni ifrtl 1 column i 1 else column i contentcsswebkittransformtranslate 1 column windowwidth columngap px0px setcolumn0 set the showing column to first nextpage function if column columncount 1 1 column columncount 1 informendpage else ifrtl 1 column column1 contentcsswebkittransformtranslate 1 column windowwidth columngap px0px else column column1 contentcsswebkittransformtranslate 1 column windowwidth columngap px0px prevpage function if 0 column informstartpage else ifrtl 1 column column1 contentcsswebkittransformtranslate 1 column windowwidth columngap px0px updatecurrentpagetext column 1 else column column1 contentcsswebkittransformtranslate 1 column windowwidth columngap px0px updatecurrentpagetext column this function add more html content to the end of current body addstring functions sinsertbeforeendmarker windowloadaddstringreport addstringreport function columncount mathfloorendmarkerpositionleft windowwidth columngap if columncount 0 requestmorepage if columncount 0 rtl 1 columncount columncount 1 nextpage reportnumberofpage columncount this function add more html content to the first of body addstringtofirst functions contentprepends windowloadaddstringtofirstreport addstringtofirstreport function maxcolumn mathfloorendmarkerpositionleft windowwidth columngap ifmaxcolumn 0 rtl 1 maxcolumn maxcolumn 1 column maxcolumn columncount column else column maxcolumn columncount column columncount maxcolumn setcolumn column reportnumberofpage columncount this is almost all of my code if you need more please let me know,"['javascript', 'jquery', 'html', 'css']" +880463,detect if wifi is turned on is there a way to detect if wifi is enabled on an iphoneipadi am not interested to see if i can reach the internet for that i use the reachability class i just need to know if wifi has been enabled on the devicegrateful for any tips,"['ios', 'iphone']" +880467,gcc 49 bug in structures initialization i have the codestruct a int astruct b int b const a a2struct c int c const b b2const c test 0 int main return testci have gcc 482 and 492 it can be compiled just fine withg49 wall testcpp o testg48 stdc11 wall testcpp o testg48 wall testcpp o testhowever it cannot be compiled withg49 stdc11 wall testcpp o testand the compiler output istestcpp1522 error uninitialized const member abaa const c test 0 testcpp1522 error uninitialized const member abaais this a bug or i just do not understand something,['c++'] +880680,how to thisplay common era ce in java8 following code does not print ce or current erasystemoutprintlnisoeracegetthisplaynametextstyleshort localeuk output adsystemoutprintlnisoeracegetthisplaynametextstylefull localeuk output anno dominiof course isoeracename helps but not if the full thisplay name like common era or current era is required i consider this a little bit strange because the javadoc of isoera explicitly mentions the term current era in its class description it does not even work for root locale the usecase here is to serve clients with a nonreligious backgroundthis does not help toolocaldate date localdatenowstring year dateformatdatetimeformatterofpatterng y localeuk ad 2015systemoutprintlnyearthe only way i found wastextstyle style maplongstring eras new hashmaplong bce long isoerabcegetvalue 0llong ce long isoeracegetvalue 1lif style textstylefull erasputbce before current era erasputce current era else erasputbce bce erasputce cedatetimeformatter dtf new datetimeformatterbuilder appendtextchronofieldera eras appendpattern ytoformattersystemoutprintlnlocaldatenowformatdtf ce 2015is there any better or shorter way,['java'] +880692,trying to assign vector of base from vector of derived this seems like a pretty basic problem but i cannot figure it out i have a stdvector of raw pointers to derived objects and i just want to copy it to another vector of base pointers using the assignment operator with vc i get error c2679 binary no operator found btw i do not want a deep copy of the objects i just want to copy the pointers sample codeinclude vectorusing namespace stdstruct base struct derived public base int main int argc char argv vectorderived v1 vectorbase v2 v2 v1 compiler error here return 0what confuses me is that i can copy the vector by looping through it and using push back like thisfor derived p derived v1 v2push backp derivedso my question is why does the assignment fail while push back works seems like the same thing to me,['c++'] +880698,do not understand the source code of arrayscopyof i have trouble understanding the source code of arrayscopyofpublic static tu t copyofu original int newlength class extends t newtype t copy objectnewtype objectobjectclass t new objectnewlength t arraynewinstancenewtypegetcomponenttype newlength systemarraycopyoriginal 0 copy 0 mathminoriginallength newlength return copywhat is this line checkingobjectnewtype objectobjectclasswhat are the differences between t new objectnewlength and t arraynewinstancenewtypegetcomponenttype newlength why arraynewinstance not good enough for both casesthis following line compiles but crashes at run time as expected when should i use this methodinteger nums arrayscopyofnew stringa b 2 integerclass,['java'] +880729,odd behavior in linq to sql with anonymous objects and constant columns my colleague was getting an error with a more complex query using linq to sql in net 40 but it seems to be easily reproducible in more simpler circumstances consider a table named transferjob with a synthetic id and a bit fieldif we make the following queryusing var ctx dbdatacontextcreate var withoutconstant ctxtransferjobsselectx new id xtransferjobid isauto xisfromautorebalance var withconstant ctxtransferjobsselectx new id xtransferjobid isauto true note were putting a constant value in this one var typea withoutconstantgettype var typeb withconstantgettype bool same typea typeb this is true var together withoutconstantconcatwithconstant var realized togethertolistinvalid cast exceptionan invalid cast exception is thrown where noted but strangely we have type equality when viewing in a debuggersimply changing the second to last line to move from iqueryables to using linqtoobjectsvar together withoutconstanttolistconcatwithconstanttolistvar realized togethertolistno problem herethen everything work fine as expectedafter some initial digging i see that it looks like the programmers of linq to sql were considering performance and are not actually having the generated sql pull the constant value in the case with the explicit setting of true in the withconstant version finally if i switch order everything seems to workvar together withconstantconcatwithoutconstant no problem this wayhowever i would still like to know if better detail what is really going on i find it rather odd that these would be considered equal types but cause an invalid cast exception whats actually happening under the covers how could i go about proving it to myselfstack traceat systemdatasqlclientsqlbufferget boolean at read f anonymoustype22objectmaterializer1 at systemdatalinqsqlclientobjectreadercompilerobjectreader2movenext at systemcollectionsgenericlist1ctorienumerable1 collection at systemlinqenumerabletolisttsourceienumerable1 source at kbagenerictestrunnerprogrammainstring args in cusersnicksourceworkspaceskbamainkbackbagenerictestrunnerprogramcsline 59 at systemappdomain nexecuteassemblyruntimeassembly assembly string args at microsoftvisualstudiohostingprocesshostprocrunusersassembly at systemthreadingexecutioncontextruninternalexecutioncontext executioncontext contextcallback callback object state boolean preservesyncctx at systemthreadingexecutioncontextrunexecutioncontext executioncontext contextcallback callback object state boolean preservesyncctx at systemthreadingexecutioncontextrunexecutioncontext executioncontext contextcallback callback object state at systemthreadingthreadhelperthreadstartgenerated sql is the followingselect t2transferjobid as id t2isfromautorebalance as isautofrom select t0transferjobid t0isfromautorebalance from dbotransferjob as t0 union all select t1transferjobid p0 as value from dbotransferjob as t1 as t2 p0 input int size 1 prec 0 scale 0 1 context sqlprovidersql2008 model attributedmetamodel build 403031934209with the order reversed which does not crash the sql isselect t2transferjobid as id t2value as isautofrom select t0transferjobid p0 as value from dbotransferjob as t0 union all select t1transferjobid t1isfromautorebalance from dbotransferjob as t1 as t2 p0 input int size 1 prec 0 scale 0 1 context sqlprovidersql2008 model attributedmetamodel build 403031934209to my earlier comment the constant is not pulled when doingwithconstanttolistselect t0transferjobid as idfrom dbotransferjob as t0 context sqlprovidersql2008 model attributedmetamodel build 403031934209,['c#'] +880785,using function written in c in c code i am working on a project in which some people have already written code in c and we have to use it in our code in c so i have tried following test to write a test program which demonstrates the samethe header file is ifndef h files n define h files n includeiostream ifdef cplusplus extern c endif void add funcint int ifdef cplusplus endif endifcpp file is includeh fileshvoid add funcint num int nums std cout the addition of numbers is numnums std endlthe c file is includestdiohincludeh fileshint main printfwe are calling the c function form c filen add func1015 return 0makefile is cc gccinc i includevpath c srcvpath cpp srcvpath o objall addprefix objfunctionso maino runrun maino functionso cc o bin objo cpp cxx c inc o libstdcobjo c cc c inc o phony cleanclean rm f obj bini am getting the following errorg c i include srcfunctionscpp o objfunctionsogcc c i include srcmainc o objmainogcc o binrun objmaino objfunctionsoobjfunctionso in function add funcfunctionscpptext0x1e undefined reference to stdcoutfunctionscpptext0x23 undefined reference to stdbasic ostreamchar stdchar traitschar stdoperator stdchar traitschar stdbasic ostreamchar stdchar traitschar char constfunctionscpptext0x2d undefined reference to stdostreamoperatorintfunctionscpptext0x32 undefined reference to stdbasic ostreamchar stdchar traitschar stdendlchar stdchar traitschar stdbasic ostreamchar stdchar traitschar functionscpptext0x3a undefined reference to stdostreamoperatorstdostream stdostreamobjfunctionso in function static initialization and destruction 0int intfunctionscpptext0x68 undefined reference to stdios baseinitinitfunctionscpptext0x77 undefined reference to stdios baseinitinitcollect2 error ld returned 1 exit statusmake run error 1if i use g as linker then it works fine but gcc linker gives methe problemas i think of the problem is the function name mangling by g andgcc does not mangles the functions namesymbolsso is there any compiler flag that would avoid name mangling if possiblethe reason for avoiding g linker is it treats the linking as c style but the base code is in c so it may introduce some bug in calling codeplease somebody suggest the solution,"['c++', 'c']" +880792,to thispose or not to thispose elements in an array of ithisposable objects there are lots of examples of arrays or lists of ithisposable objects being returned from functions in net for example processgetprocesses if i call that method is it my responsibility to thispose of all the members of the array as i iterate through them why should it be my responsibility since i never created the objects and the array that i was given is just pointers to the objects which were created outside of my code i always thought it was the creators burden to thisposeso what is the proper rule here,"['c#', '.net']" +880848,jquery ajax https call gives err insecure response i am trying to make a https cors ajax call from jquery to a nodejs process however when ever the call is made chrome complains in the console options httpslocalhost neterr insecure responselooking at a similar stack overflow question cross domain request from http to https aborts immediately i should be able to make cross origin https ajax calls if i import the self signed cert i made so i imported the cert into chrome i can see the certificate in chromes manage certificates tab under authorities but it still fails when i try the ajax callthis is how i made the private keyopenssl genrsa out domainkey 4096now the certopenssl req x509 sha512 nodes newkey rsa4096 keyout domainkey out domaincrtfor common name i put the ip address of the computer so chrome would not complain about a url mismatchhere is the html pagedoctype htmlhtml titleblackboxtitle head meta charsetutf8 script srcjquery12minjsscript script srcbootstrap334thistjsbootstrapminjsscript script srcloginjsscript head body div classcontainerfluid div classrow div classcolmd4 h2 welcome to blackboxh2 labelusernamelabel input typetext nameusername idusername labelpasswordlabel input type text namepassword idpassword input typebutton idloginbtn valuelogin div classcontainer div classrow div classoutdiv div div div div div body htmlthis is the javascript that goes along with the html documentreadyfunction loginbtnclickclicklogin function clicklogin var username usernameval var password passwordval ifpassword username outhtmlempty username or password else ajax type put url httpslocalhost contenttype applicationjson data jsonstringify username username password password datatype text and finally here is the node process that both serves the html and javascript and is suppose to receive the ajax callsconst fs requirefsconst http requirehttpconst https requirehttpsvar loginpage fsreadfilesyncloginhtmlvar loginpagejs fsreadfilesyncloginjsvar jquery fsreadfilesyncjquery12jsvar bootstrap fsreadfilesyncbootstrap334thistjsbootstrapminjsvar options key fsreadfilesyncdomainkey cert fsreadfilesyncdomaincrthttpcreateserverfunctionreq res reswritehead301 location https192168158 resendlisten80httpscreateserveroptions functionreq res ifreqmethod get requrl reswritehead200 ok contenttype texthtml reswriteloginpage resend else ifreqmethod get requrl loginjs reswritehead200 ok contenttype applicationjavascript reswriteloginpagejs resend else ifreqmethod get requrl jquery12js reswritehead200 ok contenttype applicationjavascript reswritejquery resend else ifreqmethod get requrl bootstrap334 thistjsbootstrapminjs reswritehead200 ok contenttype applicationjavascript reswritebootstrap resend else ifreqmethod options requrl reswritehead204 no content accesscontrolalloworigin origin accesscontrolallowmethods get post put delete options accesscontrolallowheaders contenttype accept accesscontrolmaxage 10 contentlength 0 var requestbodybuffer reqondata functionchunk requestbodybufferpushchunk reqonend function var requestbody requestbodybufferjoin var obj jsonparserequestbody ifobjhasownpropertyusername objhasownpropertypassword consolelogobjusername consolelogobjpassword listen443,"['javascript', 'jquery']" +880987,laravel 5 testing environment not getting set in codeception unit tests i am using laravel 5 and codeception and i would like to use an inmemory sqlite database for my unit tests however i cannot seem to get my environment set to testing in codeception i am using the laravel5 module and have the following defined in my unitsuiteyml fileclass name unittestermodules enabled asserts unithelper laravel5 config laravel5 environment file envtestingi have a env file which defines all my local settings then a envtesting file that defines all the testingspecific settings however it never seems to actually set the environment correctly to test the environment i just didthisassertequalstesting appenvironmentand i always getfailed asserting that two strings are equal expected actual testinglocalanyone have any idea what i am doing wrong,['php'] +880993,can this be moved i would like to define a class for marshalling data when marshalling is finished i would like to move the marshalled data out from within it which will probably invalidate the marshalling objecti believe this is possible with the static function extractdata belowclass marshaller public static datatype extractdatamarshaller marshaller return stdmovemarshallerdata private datatype datathis is a bit inconvenient to call thoughmarshaller marshaller do some marshallingdatatype marshalled datamarshallerextractdatastdmovemarshallerso can i wrap it with a member functiondatatype marshallertodatatype return marshallerextractdatastdmovethisthis would of course be called usingdatatype marshalled datamarshallertodatatypewhich to me looks much nicer but that stdmovethis thing looks awfully suspicious in the context of the call to todatatype marshaller cannot be used again but i do not think the compiler can know that the body of the function could be outside the callers compilation unit so there is nothing to indicate that marshaller has had move applied to itis this undefined behavior is it perfectly fine or somewhere in between is there a nicer way to accomplish the same goal preferably without using a macro or requiring the caller to explicitly move marshalleredit with both g and clang i found that not only could i compile the above use case but i could actually continue to make modifications to the underlying data via the marshaller then reextract the modified data using the todatatype function i also found that the alreadyextracted data in marshalled data continued to be changed by marshaller which indicates that the marshalled data is shared between the marshaller and the calling context so i suspect that there is either a memoryleak or undefined behavior from doubledeletion hereedit 2 if i put a print statement in datatypes destructor it appears twice when the caller leaves scope if i include a data member in datatype that has an array in it with a corresponding new and delete i get a glibc double free or corruption error so i am not sure how this could be safe even though several answers have said that it is technically allowed a complete answer should explain what is required to use this technique correctly with a nontrivial datatype classedit 3 this is enough of a rabbitholecanofworms that i have opened up another question to address my remaining concerns,['c++'] +881048,how do you use an onclicklistener in a recycler view what i am basically trying to do is make the objects that show up in the recycler view clickable to a certain textview id because i am making a program that shows an album cover and its title next to it in a list i need to be able to click on each one of the boxes that the recycler view makes and have a textview pop up with the other information author published date hit songs etc when its clicked on and then a back button if possible to go back to the album list i have been looking at this for hours and cant figure out how to make an onclicklistener work for it if you know how or have any suggestions id be glad to hear them thank youpackage comalbumlistalbumlistimport androidcontentcontextimport androidcontentintentimport androidsupportv7widgetrecyclerviewimport androidviewlayoutinflaterimport androidviewviewimport androidviewviewgroupimport androidwidgetimageviewimport androidwidgettextviewimport androidwidgettoastpublic class myadapter extends recyclerviewadaptermyadapterviewholder private albumdata itemsdata public myadapteralbumdata itemsdata thisitemsdata itemsdata public static class viewholder extends recyclerviewviewholder implements viewonclicklistener private textview txtviewtitle private imageview imgviewicon public viewholderview itemlayoutview superitemlayoutview itemlayoutviewsetonclicklistenerthis txtviewtitle textview itemlayoutviewfindviewbyidridalbum title imgviewicon imageview itemlayoutviewfindviewbyidridalbum icon override public void onclickview v override public myadapterviewholder oncreateviewholderviewgroup parentint viewtype view itemlayoutview layoutinflaterfromparentgetcontext inflaterlayoutdata layout null viewholder viewholder new viewholderitemlayoutview return viewholder override public void onbindviewholderviewholder viewholder int position viewholdertxtviewtitlesettextitemsdatapositiongettitle viewholderimgviewiconsetimageresourceitemsdatapositiongetimageurl override public int getitemcount return itemsdatalength,"['java', 'android']" +881062,what exactly is java8s stream i have read java 8 in action therefore i know what is stream and how to use it but from the point of computer sciences view all data needs to be stored in a kind of data structure so how to store stream how can stream be able to perform so many operations for so many kinds of collectionseg array linked list mapor maybe stream is just an interface and all kinds of collections are required to implement these operations specified in this interfacethanks,['java'] +881064,why does the source code for the guid constructor contain the line this guidempty if you look a the source code for the constructor of guidstring in the net 452 source code it is as followspublic guidstring g if gnull throw new argumentnullexceptiong contractendcontractblock this guidempty guidresult result new guidresult resultinitguidparsethrowstyleall if tryparseguidg guidstylesany ref result this resultparsedguid else throw resultgetguidparseexception the question is what is the purpose of the line this guidemptyfrom what i can see if string g can successfully be parsed in the tryparseguid method then this will be assigned if it cannot then an exception will be thrownsuppose you wrotevar guid new guidinvalidguidthis would cause an exception and the value of guid would be undefined i would assume so why the need to assign this to guidempty,"['c#', '.net']" +881116,make class transient or serializable but the class is serializable sonarqube 51 marks a lot of critical issues after reviewing my code however the class itself and the referenced class in the field is also serializable the referenced class inherits the serializable interface through a classhere is my examplepublic class a implements serializable private b b sonarcube markes this field as not serialzableand the class b is defined as followspublic class b extends c and the class c is defined as followspublic abstract class c extends d and the class d is definedpublic abstract class d implements serializable running findbugs on the same project does not see these problemsi am not sure if it is a bug in sonarcube or is my code has some other problems other fields in the classes cd or something elsedoes anybody has a clue,['java'] +881255,dagger2 does not generate dagger files im using dagger 2 since a while but today trying to compile got this errorerror13 31 error cannot find symbol class dagger globalcomponenterror38 21 error cannot find symbol variable dagger globalcomponentso here is the codepublic class myappapplication extends application private static globalcomponent componentoverridepublic void oncreate superoncreate component dagger globalcomponentbuilder busmodulenew busmodule syncmodulenew syncmodule servicemodulenew servicemodule contextmodulenew contextmodulethis persistencemodulenew persistencemodulethis buildand gradle dependenciescompile comgoogledaggerdagger20snapshotapt comgoogledaggerdaggercompiler20snapshotprovided orgglassfishjavaxannotation100b28any solutions already tried to clean rebuild change dependecy versions also deleting the gradle cache and reinstalling android studioif it helps also got the same error with this sample projects,['android'] +881276,sql limit min and max value in database create table tbl cdcdnr int identity11cdtitel nvarchar80 not nullcdduur intcdprijs smallmoneyso i am creating this table is there any way i can limit the value of cdprijs to be between 0 and 100,['sql'] +881314,how to import zxing to android studio i use android studioi want to import zxing in my application i find many articles and found the following sitei downloaded the zip and unzip and find some tutorialsbut it does not seem to be too detailed about the details what i need to import to achieve qrcode scani still have no idea how to do it414i tried lennon url providedzxingandroidminimaland import the gradlewrapperjarbut when i wrotenew intentintegrator this initiatescan still appear can not resolve symbol intentintegrator messagei do have a right jar select add as librarybut when an error occurs he does not seem to be added410finally no longer appear can not resolve symbol intentintegratorthis is the codewhat do i wrongi removed the new intentintegrator this initiatescan applications normal operation overrideprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main new intentintegratorthisinitiatescanmy buildgreadle repositories jcenter maven url,"['java', 'android']" +881332,node webkit catch iframe mouse events from parent window i am trying to create a draggable iframe in my app when the iframe is focused all mouse events are triggered within the inner window objecti cannot listen to those events within the iframe and trigger them myself because it can be blocked by the iframe content jsi cannot create an unvisible layer above the iframe that will catch all the events and move them forward to the iframe because bultin events cannot be triggered by script like css hovercan i catch those events in node layer without using webkit dom,['javascript'] +881355,how does whatsapp authentication work i want to develop a mobile app and use a whatsapp like user registration now i remember the security problems that were thiscussed some years ago whatsapp used to authenticate users simply by their phone number and imei now of course this is not really safe but i do not really know how to do it more securenow i did not hear something about whatsapp authentication problems anymore for a long time so i guess they have secure method now do you know how whatsapp does it today,['android'] +881390,how to access the value of a promise i am looking at this example from angulars docs for q but i think this probably applies to promises in general they have this examplepromiseb promiseathenfunctionresult return result 1 promiseb will be resolved immediately after promisea is resolved and its value will be the result of promisea incremented by 1but i am not clear how this works if i could write then on the result of the first then chaining them which i know i can then promiseb is a promise object of type object it is not a number so what do they mean by its value will be the result of promisea incremented by 1 am i supposed to access that as promisebvalue or something like that how can the success callback return a promise and return result 1 i am missing something,['javascript'] +881435,error while following tumblelog application with flask and mongoengine i am following tumbleblog application heremy init pyfrom flask import flaskfrom flaskextmongoengine import mongoengineapp flask name appconfigmongodb settings db sencha web service username username password passwordappconfigsecret key keepthiss3cr3tdb mongoengineappif name main appruni get the errormongoengineconnectionconnectionerror cannot connect to database default false is not a read preferencei tried passing in aliasdefault in appconfigmongodb settings but still getting the same error,['python'] +881551,enable template function if class has specific member function i wrote the following template function which checks whether an arbitary container contains a specific elementtemplatetemplateclass class class container t class item t class rest tbool containsconst container titem t rest t container const item t item forconst item t otheritem container ifotheritem item return true return falsethis works well for most containers however for all kinds of sets and maps it is sub optimal since there we could usetemplatetemplateclass class class set t class item t class rest tbool containsconst set titem t rest t set const item t item return setcount item 0obviously we cannot use both templates simultaneously because of ambiguity now i am looking for a way to use stdenable if to enable the to first template if container t does not provide a count member function and the second template if it does however i cannot figure out how to check for a specif member function using c11,['c++'] +881602,is it possible to obtain the address of a implicit instantiation of a function template i would like to know if there is any way to obtain the address of the instantiation of a function template produced by a specific set of argumentsinclude iostreamtemplate typename tclass a template typename t typename t2int helloat a at2 b int c return 69 int main aint a afloat b stdcout helloa b 3 n return 0this code prints the value returned by the function call how can i print the address of the version of hello instantiated for a and b parameters i would like the types to be inferred by the compiler,['c++'] +881681,how to use videotoolbox to decompress h264 video stream i had a lot of trouble figuring out how to use apples hardware accelerated video framework to decompress an h264 video stream after a few weeks i figured it out and wanted to share an extensive example since i could not find onemy goal is to give a thorough instructive example of video toolbox introduced in wwdc 14 session 513 my code will not compile or run since it needs to be integrated with an elementary h264 stream like a video read from a file or streamed from online etc and needs to be tweaked depending on the specific case i should mention that i have very little experience with video endecoding except what i learned while googling the subject i do not know all the details about video formats parameter structure etc so i have only included what i think you need to knowi am using xcode 62 and have deployed to ios devices that are running ios 81 and 82,['objective-c'] +881842,in c what is the best way to parse this wiki markup i need to take data that i am reading in from a wiki markup page and store it as a table structure i am trying to figure out how to properly parse the below markup syntax into some table data structure in chere is an example table owner action status comments bill fix the lobby in progress this is easy joe fix the bathroom in progress plumbing electric painting scott fix the roof complete this is expensive and here is how it comes in directly owner action status comments bill fix the lobby in progress this is eary joe fix the bathroom in progress plumbing electric painting scott fix the roof complete this is expensive so as you can seethe column headers have as the separatora row columns have a separator or a row might span multiple lines as in the second data row example above so i would have to keep reading until i hit the same number of cols that i have in the header rowi tried reading in line by line and then concatenating lines that had in between then but that seemed a bit hackyi also tried to simply read in as a full string and then just parse by first and then keep reading until i hit the same number of and then go to the next row this seemed to work but it feel like there might be a more elegant way using regular expressions or something similarcan anyone suggest the correct way to parse this data,['c#'] +881849,laravel 5 codeception not routing correctly i am trying to write an api test case for a controller function using codeception and i am hitting an issue where the route to the controller function does not appear to be evaluated correctly and the evaluation seems to be different depending on what i have in my test casehere is a code sample from my test caseuse apitesterclass customerregistercest tests public function testgetregisterapitester i isendgetregister iseeresponsecodeis200 public function testpostregisterapitester i isendpostregister set the data in here iseeresponsecodeis200 i have a routesphp file containing these routesrouteget as home uses homecontrollergetindexroutegetregister as getregister uses registrationcontrollergetregisterroutepostregister as postregister uses registrationcontrollerpostregisteri have inserted some debug statements into my controller classes so that i can see what routes get run like this logdebugget register or get index or post register etcat the moment i have stripped down everything from my controller classes so that only the debug statements are includedwhen i run the test case as above i get the following debug outputget registerget index so it appears that sendpostregister actually routes to the get route for instead of the post route for register outside of the test case everything works normally i can post to the register routes fine routing appears to work ok the problem only appears inside a codeception test caseif i change the test case so that i am doing the sendget and the sendpost inside the same function call for example like this tests public function testpostregisterapitester i isendgetregister iseeresponsecodeis200 isendpostregister set the data in here iseeresponsecodeis200 then i see this debug outputget registerget register so that by inserting the sendget into the same function as the sendpost it has changed the sendpost behaviour so that it now routes to the get route for register instead of the get route for index but still would not route to the correct post routei have tried turning xdebug on and do not have any clues from the xdebug output as to whats going on either,['php'] +881936,percent color in android for material design in googles spec for material design i see colors specified as percentagesto convey a hierarchy of information you can use different shades for text the standard alpha value for text on a white background is 87 0 secondary text which is lower in the visual hierarchy should have an alpha value of 54 0i do not understand how these percentages work for example if the background color is white what is the color of the textwhat if my background were say 607d8b what would my text color be is it just the background color with the opacity alpha set to the percentage,['android'] +881965,what do the nullrelated property attributes in xcode do with xcode 63 i noticed some property attributes namelynonnullnull resettablenullablecould someone explain what they do when applied,['objective-c'] +882161,number is out of range for activerecordtypeinteger with limit 4 i am using sqlite activerecord in my ruby app and heres the error i get while trying to write a big number to the integer field1428584647765 is out of range for activerecordtypeinteger with limit 4but according to sqlite docsthe value is a signed integer stored in 1 2 3 4 6 or 8 bytes depending on the magnitude of the value8 bytes is a plenty of space to store 1428584647765 number so why does activerecord give me an error why does it think that this is a 4byte field,['ruby'] +882173,why cannot change all the characters from full width character into half width character i want to change all the characters from full width characters into half width characters write the following codes to do the jobfor example to change all full width characters in i14i12i12i12i12i12i12i12i12 i14 eaac234aac into half width characters into codebitcn eaac234aac there are two methods to acheive the goalbut all of them failedall the php file were saved as utf8 formatmethod 1php function fulltohalfstr arrarray i14 0 i14 1 i14 2 i14 3 i14 4 i14 5 i14 6 i14 7 i14 8 i14 9 i14 a i14 b i14 c i14 d i14 e i14 f i14 g i14 h i14 i i14a j i14 k i14 l i14 m i14 n i14 o i14 p i14 q i142 r i143 s i14 t i14 u i14 v i14 w i14 x i141 y i14o z i12 a i12 b i12 c i12 d i12 e i12 f i12 g i12 h i12 i i12 j i12 k i12 l i12 m i12 n i12 o i12 p i12 q i12 r i12 s i12 t i12 u i12 v i12 w i12 x i12 y i12 z i14 new foreach str as char if isset arrchar new arrchar else new arr return new stri14i12i12i12i12i12i12i12i12 i14 eaac234aac echo fulltohalfstrerror messagemethod 2 phpfunction fulltohalfstr queue array i14 0 i14 1 i14 2 i14 3 i14 4 i14 5 i14 6 i14 7 i14 8 i14 9 i14 a i14 b i14 c i14 d i14 e i14 f i14 g i14 h i14 i i14a j i14 k i14 l i14 m i14 n i14 o i14 p i14 q i142 r i143 s i14 t i14 u i14 v i14 w i14 x i141 y i14o z i12 a i12 b i12 c i12 d i12 e i12 f i12 g i12 h i12 i i12 j i12 k i12 l i12 m i12 n i12 o i12 p i12 q i12 r i12 s i12 t i12 u i12 v i12 w i12 x i12 y i12 z i14 return preg replacexa3xb0xb9xc1xdaxe1xfaequeue1 str str i14i12i12i12i12i12i12i12i12 i14 eaac234aac echo str echo br echo fulltohalfstr error messagehow to fix two of themi solved the method 1 problem the fixed codes are as the followingphpfunction fulltohalfstrarrarray i14 0 i14 1 i14 2 i14 3 i14 4 i14 5 i14 6 i14 7 i14 8 i14 9 i14 a i14 b i14 c i14 d i14 e i14 f i14 g i14 h i14 i i14a j i14 k i14 l i14 m i14 n i14 o i14 p i14 q i142 r i143 s i14 t i14 u i14 v i14 w i14 x i141 y i14o z i12 a i12 b i12 c i12 d i12 e i12 f i12 g i12 h i12 i i12 j i12 k i12 l i12 m i12 n i12 o i12 p i12 q i12 r i12 s i12 t i12 u i12 v i12 w i12 x i12 y i12 z i14 new preg match allu str resultsstrresults0 foreach str as char if isset arrchar new arrchar else new char return newecho fulltohalfi14i12i12i12i12i12i12i12i12 i14 eaac234aac,['php'] +882352,why do linked lists use pointers instead of storing nodes inside of nodes i have worked with linked lists before extensively in java but i am very new to c i was using this node class that was given to me in a project just fineclass node public nodeint data int m data node m nextbut i had one question that was not answered very well why is it necessary to usenode m nextto point to the next node in the list instead ofnode m nexti understand that it is better to use the pointer version i am not going to argue facts but i do not know why it is better i got a not so clear answer about how the pointer is better for memory allocation and i was wondering if anyone here could help me understand that better,['c++'] +882407,how to avoid bitmap out of memory when working on very large image for ie 10 pixel and above currently i am working on a system that load a very large image with minimum width x heigh 10 pixelbut the ratio of the users upload image usually do not match our requirement ratio so i have to crop it to proper ratio but when using systemdrawing bitmap to crop it i always got sytemoutofmemory exceptioni have try bitmapclone and graphicdrawimage with correct rectanglef but no luckis there anyways to do this without getting the outofmemory exception or are there any alternatives to systemdrawing library to get this task done easily my code to load the image from user upload file var filebinary new bytestreamlength streamreadfilebinary 0 filebinarylength streamposition 0 var fileextension pathgetextensionfilename using image image imagefromstreamstream false false validation and check ratio cropimageimage portrait ratio fileextension and the cropimage functioncrop image from center with predefine ratio private byte cropimageimage sourceimg float ratio string fileextension var height sourceimgheight var width sourceimgwidth var isportrait width height rectanglef croppingrec new rectanglef float positionx 0 float positiony 0 float cropheight floatheight float cropwidth cropheight portrait ratio positiony 0 positionx width cropwidth 2 if cropwidth width cropwidth width cropheight cropwidth 1 portrait ratio positionx 0 positiony height cropheight 2 croppingrecwidth cropwidth croppingrecheight cropheight croppingrecx positionx croppingrecy positiony bitmap bmpimage sourceimg as bitmap bitmap bmpcrop bmpimageclonecroppingrec bmpimagepixelformat bmpcropsavedtest fileextension imageformatjpeg imageconverter converter new imageconverter return byteconverterconverttobmpcrop typeofbyte,['c#'] +882442,how to force a flex box to thisplay 4 items per row i am using a flex box to thisplay 8 items that will dynamically resize with my page how do i force it to split the items into two rows 4 per rowhere is a relevant snipor if you prefer jsfiddle parentwrapper height 100 width 100 border 1px solid blackparent thisplay flex fontsize 0 flexwrap wrap margin 10px 0 0 10pxchild thisplay inlineblock background blue margin 10px 0 0 10px flexgrow 1 height 100pxbody div classparentwrapper div classparent div classchilddiv div classchilddiv div classchilddiv div classchilddiv div classchilddiv div classchilddiv div classchilddiv div classchilddiv div divbody,"['html', 'css']" +882446,how to use qprogressdialog along with qdomdocument save function to make a long story short i have a program that uses the qdomdocument class to create an xml file and then uses the save function to save it to a text stream object so basically itsqdomdocument somedoccreate the xml file elements etc qfile iofilenameqtextstream outiodocsaveout4ioclosei want to be able to show the progress of the save using the qprogressdialog class but i am having a hard time figuring it out is there a way i can incrementally check to see if the file is through processing and just update the progress any suggestions thanks,['c++'] +882536,how to change the linewidth of hatch in matplotlib is there a way to increase the width of hatch in matplotlibfor example the following code by specifying linewidth only changes the width of the edge i want to change the linewidth of the line used for hatchimport matplotlibpyplot as pltimport numpy as npx nprandomrandn100fig pltfigureax figadd subplot1axhistx fillfalse hatch linewidth2pltshow,['python'] +882649,thisable and enabling tooltip not working i am trying to turn off and turnon the bootstrap tooltip on toggle using jquery but it doesnt seem to be working correctly i am noticing once the bootstrap tooltip is turned off its not turning back the tooltip to on againhow do i enable the tooltip back on appreciate your help fa3x backgroundcolor yellowfalg backgroundcolor bluetogglebuttonon color greentogglebuttonoff color red documentreadyfunction ulnav li clickfunction thistoggleclasstogglebuttononfindfa3xremoveclassfa3xaddclassfalgcssborder 3px solid red navonclick togglebuttonon function togglebuttonontoggleclasstogglebuttonon togglebuttonoffnav fa3xtoggleclassfa3x falgdatatoggletooltiptooltip navonclick togglebuttonoff function togglebuttonofftoggleclasstogglebuttonoff togglebuttononnav falgtoggleclassfalg fa3x datatoggletooltiptooltipthisable reltooltiptooltipthisable hide and destroy tooltips latest compiled and minified css link relstylesheet hrefscript srcscript latest compiled and minified javascript script srcscriptdiv ngcontroller ngclick ul classnavli a classtogglebuttononi classfa faexchangetoggleialili a uisrefhome ngclass datatoggletooltip dataplacementtop dataoriginaltitledefault tooltip i classfa fahome fa3xfa i spanhomespan alili a ngclass i classfa fabarcharto fa3x datatoggletooltip dataplacementtop dataoriginaltitledefault tooltipfa i spanwork span alili a uisrefmusic ngclass datatoggletooltip dataplacementtop dataoriginaltitledefault tooltip i classfa fatable fa3xfa i spanscenario brmusicspan alili a uisreffaq datatoggletooltip dataplacementtop dataoriginaltitledefault tooltip i classfa fafaq fa3xfa i spanfaqspan ali uldiv,['jquery'] +882698,angularjs design guide previously when i was writing angular apps i used to doangularmodulengapp all required ng dependenciesin my appjs and then inside services and controllers i could simply doangularmodulengappi have a repo to demonstrate thatbut then i saw the angularseed the way implemented was in controllersangularmoduleappcontrollers dependenciesin servicesangularmoduleappservices dependenciesin appjsangularmodulengapp ng appcontrollers appsrvicesi had no issue with design infact i thought it was good since evrything was dependency injected as well as modulari have a situation where i have a servicesmoviejs that hasangularmodulemyappservices ngresourcefactoryand servicesconfigjsangularmodulemyappservicesfactorybut while writing tests with karma and jasmine in the karmaconfjsi had files usual bower componentsangularjs appservicesjs but the problem was configjs got loaded before moviejs and there were errors myappservices is not loaded or misspeltthe way i fixed it was i didfiles appservicesmoviejs appservicesconfigjsi have set up a github repo for this too here is the controller test file and here is the karmaconfi want to know what can be the possible approaches to take such modular approach without having to specify the order in which the files are to be loaded for my testsand this is my first unit test and its failingerror unexpected request get key2e329c927ed8be07944ae447c9426fexpected get ratedapi key2e329c927ed8be07944ae447c9426fit would be helpful if i could get some help in fixing that too the testdescribecontrollers function beforeeachmodulemyapp beforeeachmodulemyappservices describemoviesctrl function var scope ctrl httpbackend beforeeachinjectfunctionhttpbackend rootscope controller movie config httpbackend httpbackend ctrl controller scope rootscopenew itshould return a list of movies function var data results name abc name def httpbackend expectget ratedapi key2e329c927ed8be07944ae447c9426f responddata ctrlmoviesctrl scope scope httpbackendflush expectscopeimagetoequal conf filemoduleexports functionconfig configset basepath frameworks jasmine files appbower componentsangularangularjs appbower componentsangularmocksangularmocksjs appbower componentsangularresourceangularresourcejs appbower componentsangularrouteangularroutejs appservicesmoviejs appservicesconfigjs appcontrollersjs appappjs unittestsjs exclude appminjs preprocessors reporters progress port 9876 colors true loglevel configlog info autowatch true browsers chrome singlerun false updatei have figured out the error in test i had to mock the other http request for the configuration thanks to philthis is my test nowdescribecontrollers function beforeeachmodulemyapp beforeeachmodulemyappservices describemoviesctrl function var scope httpbackend var config data images base url backdrop sizes w300 w500 movie data results name abc name def beforeeachinjectfunctionhttpbackend rootscope controller httpbackend httpbackend scope rootscopenew httpbackend expectget key2e329c927ed8be07944ae447c9426f respondconfig data httpbackend expectget ratedapi key2e329c927ed8be07944ae447c9426f respondmovie data controllermoviesctrl scope scope itshould return a list of movies function expectscopeimagetoequal httpbackendflush expectscopeimagebackdrop sizetoequalw300 although i am not sure if this is the right test to do p something like a vcr would be helpful,['javascript'] +882744,random unresolved external symbols that should not be there i am used to compiling for linux so this lib stuff is a bit weird for me with my program under visual studio i keep getting random unresolved external symbol for other libs and even microsoft runtimes1glfw3libinitcobj error lnk2019 unresolved external symbol imp vsnprintf referenced in function glfwinputerror1msvcrtdlibvsnprintfobj error lnk2001 unresolved external symbol imp vsnprintf1glfw3libcontextcobj error lnk2019 unresolved external symbol imp sscanf referenced in function parseversionstring1msvcrtdlibvsnprintfobj error lnk2001 unresolved external symbol imp vsnprintf1cprogram files x86microsoft visual studio 140vcliboldnameslib warning lnk4272 library machine type unknown conflicts with target machine type x86i am only including these libraries and i can confirm they are being foundx86glew32slibx86glfw3libx86glfw3dlibopengl32libwith their inherited valueskernel32libuser32libgdi32libwinspoollibcomdlg32libi can confirm that this is the exact order i have tried installing and reinstalling windows 7 sdk and visual studio i am also on windows 7any help regarding this issue would be appreciated and i am happy to give out more information if requiredthanks boncey,['c++'] +882765,iphone running ios 83 shows up as ineligible in xcode 62 current setupiphone 6 updated to ios 82imac running mavericks 109 with xcode 62deployment target set to 82when i connect the iphone it shows up as ineligiblealso it shows this warningi have triedto reboot both iphone imac not solvedto manually select iphone from product destination ineligible devicesmany other answers in this question but all for problems using xcode 63 not 62i know i can solve thisupgrading to yosemite installing xcode 63using an iphone running 82but is there any possibility that mounting the xcode 63 dmg and copying some libs symlinking something it will work,"['ios', 'iphone']" +882813,how to get bluetooth outbound transfer list i want to get the bluetooth outbound transfer list i referred following link and have looked many posts here related to this issue but could not found solutionlinkis there a any way that i can use to get the list,['android'] +882830,fabric release xcode 63 codesign xcodeselect i am trying to upload a release to fabric i am getting errors as follows i am using the xcode 63 recently updatedxcode 63 fabric 113 osx 10103what should i do to resolve above error continue uploading the release via fabric desktop toolis there any other way to upload binary to fabric,['ios'] +882836,open settings warning issue in xcode 63 comparison of address of uiapplicationopensettingsurlstring not equal to a null pointer is always true i am not inventing the wheel in ios8 to open settings from inside the app i am using this codebool canopensettings uiapplicationopensettingsurlstring nullif canopensettings nsurl url nsurl urlwithstringuiapplicationopensettingsurlstring uiapplication sharedapplication openurlurlthe code is in a lot of answers and questions in stackoverflowthe problem came out with xcode 63 i have got a warning sayingcomparison of address of uiapplicationopensettingsurlstring not equal to a null pointer is always truewhat is interesting is that apple is using it in their example code mhtmlsome idea about how to avoid the warning and still checking if i can open settings,"['ios', 'objective-c']" +882853,thisabling a dropdown list item jquery not working i want to thisable the dropdown list item using jquerythe index value is 1 and the value is internal i tried below syntaxes one by onethe solutions were the answers for similar questions none of them are working iam using ie8 var value internal idchildorganizationdropdownlist optionvalue value propthisabledthisabled childorganizationdropdownlist optionvalue value propthisabledthisabled idchildorganizationdropdownlistoption internal propthisabledtrue idchildorganizationdropdownlist optionvalue internal propthisabledthisabled idchildorganizationdropdownlistoptionvalue internal propthisabled trueidchildorganizationdropdownlistattrthisabled thiscustomernamedropdownlistfindoptionvalue internal designer aspxdiv claselectioncontrols aspcheckbox idchksubcontracting runatserver textsubcontracting enabledtrue asphiddenfield idsubcontractinghiddenfield runatserver div clasubselectioncontrol idallowsubcotractingselection stylethisplay none div clasubcontractingcontrols parent bu span div clasubcontractingcontrols supplier em classmandatoryindicatorem span aspdropdownlist idchildorganizationdropdownlist runatserver width200px asphiddenfield idixchildorganizationhiddenfield runatserver span div div divaspxcspublic dictionaryint string childorganizations set var result value resultadd0 select supplier childorganizationdropdownlistdatasource result childorganizationdropdownlistdatatextfield value childorganizationdropdownlistdatavaluefield key childorganizationdropdownlistdatabind childorganizationdropdownlistselectedvalue 0,"['jquery', 'asp.net']" +882886,misbehaviour of backstack of activity when activity destroyed i have two activities let us say a and b in activity a there is a broadcast receiver registered that listens for a particular event which will finish activity a i am registering the broadcast receiver in oncreate and destroying it in ondestroy of activity afor simplicity there is one button in activity b named destroy activity a when a user clicks on button activity a should be destroyednormally all of this is running smoothly without any issuesbut the problem occurs in following scenarios1 suppose i am in activity b and i press the home key to move the application to the background then if i use other resourceheavy applications android system will kill my application to free memory then if i open my application from recent tasks activity b will be resumed and it is oncreate onresume etc method will be called now i press button to destroy activity a but activity a has already been destroyed so activity as oncreate onresume etc methods will not be called until and unless i go to activity a by pressing the back button thus broadcast receiver is not registered to listen for the event2 the same problem will arise when user has selected do not keep activities from developer options in the devices settingsi have been looking to solve this issue for a long time but i am unable to find a proper answer what is the best way to handle this scenario is this an android bug there should be some solution for this issueplease help me,['android'] +882897,transparent font on transparent background i am currently working on a scrollbar which looks just like this if this text is to long for you just skip to the examplethere will be arrows at the left and right side to scroll either left or right the color of the scrollbar is not grey as it seems but rgba06 so its a transparent black which will be used in front of images now i want the last few letters in the line to fade out like in this example to accomplish that i am using a div overlay withbackgroundimage lineargradientto right rgba2552552550 blackbut if i would do that with a transparent scrollmenu it would mess up the backgroundcolor of the scrollmenu if you dona t know what i mean look here so i found a solution by combining two divs with lineargradients on the very right which if you lay them over each other create exactly the background color of the scrollmenu one of these lays behind the font one of them overlays the font that way i can achieve some transparency on the font here is an example for you guysrightpart leftpart width200px height50px positionabsolute top0left0 color whiterightpart zindex1 backgroundlineargradient to right rgba0 0 0 05 rgba0 0 0 0 leftpart backgroundlineargradient to left rgba0 0 0 05 rgba0 0 0 0 div idrightpart slight transparency effect on this divdiv idleftpartdivthe problem is that the transparency effect is limited to the background transparency of 05 therefore the transparency effect cana t get as strong as i want it to benow i am asking for a solution with which i could achieve a stronger transparency effect i would appreciate your suggestions please remember that i cana t just make a specific word in the end transparent since there is always a different word in the end of the scrollbar consequently i would need to make the font itself in a specific area transparent and i personally dona t know how to do that especially if it is supposed to work on all of the newest browser versions including ie9,['css'] +882929,how to suppress the deprecation warnings in django every time i am using the djangoadmin command a even on tabacompletion a it throws a removedindjango19warning and a lot more if i use the test command how can i suppress those warningsi am using django 18 with python 34 in a virtual environmentas far as i can tell all those warnings come from libraries not from my code here are some examplesalibpython34importlib bootstrappy321 removedindjango19warning djangocontribcontenttypesgeneric is deprecated and will be removed in django 19 its contents have been moved to the fields forms and admin submodules of djangocontribcontenttypesreturn fargs kwdsalibpython34sitepackagesdjangocontribadminutilpy7 removedindjango19warning the djangocontribadminutil module has been renamed use djangocontribadminutils insteaduse djangocontribadminutils instead removedindjango19warningalibpython34sitepackagesdjangotemplatetagsfuturepy25 removedindjango19warning loading the url tag from the future library is deprecated and will be removed in django 19 use the default url tag insteadremovedindjango19warning,['python'] +882941,conditional mocking call original function if condition does match how can i conditionally call the orignal method in a mockin this example i only want to fake a return value if barx otherwise i want to call the original methoddef mocked some methodbar if barx return fake return some how call original methodbarwith mockpatchmylibfoosome method mocked some method do some stuffi know that it is a bit strange if i want to fake mylibfoosome method in side do some stuff it should be conditionless all not some calls to some method should be mockedin my case it is an integration test not a s tiny unittest and mylibfoosome method is a kind of thispatcher which gets used very often and in one case i need to fake the result,['python'] +882958,add a new row to the top of a jquery datatable i need to add a new row into a datatable which should be placed in the top of the table and i have used sorting plugin but it failed can anyone please help me to fix this issue,['jquery'] +882990,fighting with frp i have read about frp and was very excitedit looks great so you can write more highlevel code and everything is more composable and etcthen i have tried to rewrite my own little game with a few hundreds sloc from plain js to baconand i found that instead of writing highlevel logiconly code i actually beating with baconjs and its adherence to principlesi run into some headache that mostly interfere clean codetake1instead of getting value i should create ugly constructionscircular dependenciessometimes they should be by logic but implementing it in frp is scaryactive stateeven creator of baconjs have troubles with itas example here is the peace of code to demonstrate the problemtask is to not allow two players stay at same placeimplemented with baconjsfunction adda return functionbreturn a bfunction neqa return functionbreturn a bfunction eqa return functionbreturn a bfunction alwaysval return functionreturn valfunction idareturn avar player functionplayers movement initpos var me meposition movement flatmapfunctionval return meposition take1 mapaddval flatmapfunctionposfuture var otherplayerpositions players filterneqme mapfunctionplayerreturn playerpositiontake1 return bacon combineasarrayotherplayerpositions mapfunctionpositions return positionssomeeqposfuture filterid mapalwaysposfuture logplayer initpos topropertyinitpos return mevar movea new baconbusvar moveb new baconbusvar players playerspushnew playerplayers movea 0playerspushnew playerplayers moveb 10moveapush4movebpush4moveapush1movebpush1movebpush1movebpush1moveapush1moveapush1movebpush1what i want to demonstrate ismepositions have dependency on its ownit is not easy to understand this code here is imperative implementation and it looks much easier to understand i spent much more time with bacon implementation and in result i am not sure that it will works as expectedmy questionprobably i miss something fundamental maybe my implementation is not so in frp stylemaybe this code looks ok and it just unaccustomed with new coding styleor this wellknown problems and i should choose best of all evil so troubles with frp like described or troubles with oop,['javascript'] +882997,is it possible to structure a generic method so t is optional hard question to phrase but if i havepublic class bunnymanager public bunnyt getbunnytstring somejson return new bunnytsomejson public class bunnyt t parsedjson get set public bunnytstring somejson if stringisnulloremptysomejson parsedjson convertjsonstringtoobjecttsomejson in some cases i want to get a bunny object without any json because the json string is null so i do not care what t isin this case can i create an overload or something to ignore t completely or can i call getbunnynull or getbunnyobject i am wondering what the correct way to solve this might be,['c#'] +883006,throwing copyable class deriving from noncopyable i have a framework which defines exception as a noncopyable class from which we derived a copyable class defining a copy constructor calling a noncopy base class constructorthis works under g but not under msvc 2013the following code will reproduce the probleminclude iostreamusing namespace stdif defined msc verdefine pretty function function endifclass you uconst u delete const u operatorconst u delete the library we use defines it as const u public u cout pretty function def endl protected explicit uint i cout pretty function int i endl class e public you public e cout pretty function def endl econst e e u1 cout pretty function cpy endl e operatorconst e e cout pretty function endl return this int foo e e throw e return 0int main try foo catchconst e e cout in catch e endl catch cout in catch endl if defined msc ver cout press enter to exit endl cingetendif return 0msvc complains about error 1 error c2280 uuconst you attempting to reference a deleted function at the end of function foog and clang both compile the code and they do not use the copy constructor at all the e object is moved but neither will compile if e is not copyconstructableedit i have edited the code to force a copybtw if the u copy functions are not deleted nor defined prec11 noncopyable msvc fails at link phase during uuconst u lookup unresolved externalis there a flaw in my code or is this bug in msvc,['c++'] +883030,why is there difference between template and auto type deduction for stdinitializer list edge case basically there are three types of type deduction in c11templatesautodecltypefor most cases type deduction of auto and templates seems to act in the same way but there is one case when were setting auto variable to value produced by braceenclosed initialiser we get compilation errorno match for call to stdinitializer listint braceenclosed initializer list foo0 1 2 3here is a link to live sample of the codefoos type would be deduced as stdinitializer listintauto foo 0 1 2 3 templatetypename t void bart tcompiles finebar foo next line gives compiler errorbar0 1 2 3decltype is a whole other story and is beside the point of this question but auto and templates should do the same stuff at least that is what seems to be sensible when deducing the type but they evidently do not and it is confusing as to why,['c++'] +883060,gruntinjector ignore css file from bower dependency i am using gruntinjector in a new projets it set up to add all bower dependency to the indexhtml filei have ionic in my dependencies and i use it only for the javascript file and not the css so i would like that gruntinjector do not add the ionic css file in my project heres my configurationinjector options addrootslash false ignorepath app bowerprefix bower bowerdependencies files appindexhtml bowerjson i could do it by modifying ionicbowerjsonmain cssioniccss fonts jsionicjs jsionicangularjsbut of course i would prefer not to do that,['javascript'] +883081,avoiding code repetition in default arguments in python consider a typical function with default argumentsdef faccuracy1e3 nstep10 this is compact and easy to understand but what if we have another function g that will call f and we want to pass on some arguments of g to f a natural way of doing this isdef gaccuracy1e3 nstep10 faccuracy nstep the problem with this way of doing things is that the default values of the optional arguments get repeated usually when propagating default arguments like this one wants the same default in the upper function g as in the lower function f and hence any time the default changes in f one needs to go through all the functions that call it and update the defaults of any of their arguments they would propagate to fanother way of doing this is to use a placeholder argument and fill in its value inside the functiondef faccuracynone nstepnone if accuracy is none accuracy 1e3 if nstep is none nstep10 def gaccuracynone nstepnone faccuracy nstep now the calling function does not need to know what fs defaults are but the f interface is now a bit more cumbersome and less clear this is the typical approach in languages without explicit default argument support like fortran or javascript but if one does everything this way in python one is throwing away most of the languages default argument supportis there a better approach than these two what is the standard pythonic way of doing this,['python'] +883095,blue holo colors appear green on device i am facing a weird issue where i am setting the background of a textview to androidcolorholo blue bright expecting it to be bright blue only to find that it is some kind of bright green on a devicexmltextview androidididtv text androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentendtrue androidlayout alignparentrighttrue androidlayout marginleft5dp androidlayout marginright5dp androidbackgrounddrawablechat bubble androidmaxwidth300dp androidpadding5dp androidsinglelinefalse androidtextsize16sp drawablechat bubblexml version10 encodingutf8shape xmlnsandroid solid androidcolorcolorchat bubble background corners androidradius5dp shapecolorsxml just the relevant linecolor namechat bubble backgroundandroidcolorholo blue brightcolorabove settings produce this each message is a textviewi thought maybe it was because my device thisplays colors differently or something so i tried some more holo colors but they all look exactly as they shouldandroidcolorholo green light givesandroidcolorholo green dark giveseven androidcolorholo orange light and androidcolorholo purple look okexcept for the blue onesandroidcolorholo blue light givesandroidcolorholo blue dark givesall blue appear as similar but not exactly the same tints of green also not the same tint of green as holo green light or holo green darki thought what is this everything looks good but not blue and went to check what the hex of holo blue bright is and i found it here it is ff00ddffso i tried to use that hex values directly instead of using the predefined holo colorandroid studio v12 tells me they are exactly the same color as i expectedhowever when i then changedsolid androidcolorcolorchat bubble background to solid androidcolorcolorchat bubble background2 to use ff00ddff as color i got thiswhich is exactly what i expected to see when i was using holo blue bright which should makes sense considering they are the same colori am stumped what is going on here what am i missing why do 2 supposedly equal color codes produce different results and why are all the other holo colors looking normaldevice infooneplus onemodel a01running cyanogen os v110xnph05q kernel 340cyanogenmodgc73a4ec build 04running android 4,['android'] +883101,anyone used specflow with xunit 20 successfully the current version of specflowxunit is not compatible with xunit 20 i cannot rollback to xunit 190 as all other unit tests are written for xunit 20 the current verions of specflowxunit uses iusefixture which is obsolete in xunit 20 so i would like to ask if anyone is using specflowxunit with xunit 20 how you do it,['c#'] +883127,error itms90086 submitting app i need to submit my app and i retrieve this errorand the configuration is on 64 bitsi do not know how to dothanks in advance,['ios'] +883245,google map error invalidkeyorunauthorizedurlmaperror i am developing in javascripthtmlcss an app that uses google maps i am getting the following alert dialog boxthis page was unable to thisplay a google maps element the provided google api key is invalid or this site is not authorized to use it error code invalidkeyorunauthorizedurlmaperrorthe app does actually thisplay the map element the alert is not a problem except it should not appear at all the map thisplays properlyi have gone in to the google developers console and in the credentials section have edited allowed referrers to be mydomaincomi have also gone in to the google developers console in the apis section and enabled 11 google maps apis,['javascript'] +883248,is there any way to limit repetitive boilerplate when using the pimpl idiom i have something like the following foohclass foo public foo foo note the param type repetition here is only incidental assume the functions cannot easily be made to share type signatures void bara b c d void baza b c d e f g h i j void quuxa b c d e f g h i jprivate class impl impl m pimplthen foocppclass fooimpl public void bara b c d void baza b c d e f g h i j void quuxa b c d e f g h i jprivate lots of private state helper functions etc void fooimplbara b c d void fooimplbaza b c d e f g h i j void fooimplquuxa b c d e f g h i j foofoo m pimplnew impl foofoo delete m pimpl m pimpl null void foobara b c d return m pimplbarb dvoid foobaza b c d e f g h i j return m pimplbazb d f h jvoid fooquuxa b c d e f g h i j return m pimplquuxb d f h jthere is a lot of repetition of bar baz and quux hereonce in foos declarationonce in fooimpls declarationonce in fooimpls definitionstwice in foos definitions once for foos function param list and again to call the corresponding fooimpl functionsfor each of these except the last i have to write out the entire parameter list whose types can be more involved whats the best way if any to reduce the repetition here one easy one is to inline the definition of the fooimpl public functions but is there anything besides that outside of designing the classes differently to have fewer public functions,['c++'] +883279,after pseudo element not appearing in code i am trying to use the after pseudo element to add some effects to a site div classproductshow styleshow ul li div class div classreadmore lessdiv a href3 classreadmorelink onclickreturn falseread morea div li uldivand stylesheetsproductshow readmoreless maxheight 200px height 100 overflow hiddenproductshow readmorelessafter background rgba255 255 255 0 thisplay block position absolute bottom 0 left 0 width 100 height 30px i see the styling for productshow readmoreless being applied but i do not see a after notation in the html blocks when i am examining the site from chrome latest versionmacos i read that there are sometimes issues with older browsers but i assumed that i should be able to see at least the after pseudo element notation if i was defining the style correctly what am i doing wrong,"['html', 'css']" +883326,getting a nullpointerexception while parsing json everything looks correct to me get results object get series array get object at index and get data arrayprivate void downloadalldata throws jsonexception queryapi jsonobject results mjsonresponsegetjsonobjectresults nullpointerexception here jsonarray seriesarray resultsgetjsonarrayseries jsonobject dataseries1 seriesarraygetjsonobject0 jsonarray dataarray1 dataseriesgetjsonarraydata jsonobject dataseries2 seriesarraygetjsonobject1 jsonarray dataarray2 dataseriesgetjsonarraydatajson feedstatusrequest succeededresponsetime36messageresultsseriesseriesid431432datayear1977periodm12periodnamedecembervalue1607footnotesyear1977periodm11periodnamenovembervalue1613footnotesyear1977periodm10periodnameoctobervalue1622footnotesyear1977periodm09periodnameseptembervalue1625footnotesyear1977periodm08periodnameaugustvalue1634footnotesyear1977periodm07periodnamejulyvalue1640footnotesyear1977periodm06periodnamejunevalue1646footnotesyear1977periodm05periodnamemayvalue1658footnotesyear1977periodm04periodnameaprilvalue1667footnotesyear1977periodm03periodnamemarchvalue1679footnotesyear1977periodm02periodnamefebruaryvalue1691footnotesyear1977periodm01periodnamejanuaryvalue1706footnotesseriesid321432datayear1977periodm12periodnamedecembervalue505footnotesyear1977periodm11periodnamenovembervalue504footnotesyear1977periodm10periodnameoctobervalue505footnotesyear1977periodm09periodnameseptembervalue506footnotesyear1977periodm08periodnameaugustvalue506footnotesyear1977periodm07periodnamejulyvalue506footnotesyear1977periodm06periodnamejunevalue505footnotesyear1977periodm05periodnamemayvalue501footnotesyear1977periodm04periodnameaprilvalue494footnotesyear1977periodm03periodnamemarchvalue488footnotesyear1977periodm02periodnamefebruaryvalue483footnotesyear1977periodm01periodnamejanuaryvalue476footnoteslogcat0410 221659519 1091010937comlearnkentmojito eandroidruntimei1 fatal exception intentservicedownloadservice process comlearnkentmojito pid 10910 javalangnullpointerexception at comlearnkentmojitoservicedownloadservicedownloadalldatadownloadservicejava151 at comlearnkentmojitoservicedownloadserviceonhandleintentdownloadservicejava83 at androidappintentserviceservicehandlerhandlemessageintentservicejava65 at androidoshandlerthispatchmessagehandlerjava102 at androidoslooperlooplooperjava212 at androidoshandlerthreadrunhandlerthreadjava610410 221659659 1091010910comlearnkentmojito dopenglrendereri1 enabling debug mode 00410 221659729 1091010910comlearnkentmojito iactivitymanageri1 timeline activity idle id androidosbinderproxy42db38a8 time595584590410 221700369 1091010910comlearnkentmojito ddownloadservicei1 resultsseriesdatavalue505year1977periodm12footnotesperiodnamedecembervalue504year1977periodm11footnotesperiodnamenovembervalue505year1977periodm10footnotesperiodnameoctobervalue506year1977periodm09footnotesperiodnameseptembervalue506year1977periodm08footnotesperiodnameaugustvalue506year1977periodm07footnotesperiodnamejulyvalue505year1977periodm06footnotesperiodnamejunevalue501year1977periodm05footnotesperiodnamemayvalue494year1977periodm04footnotesperiodnameaprilvalue488year1977periodm03footnotesperiodnamemarchvalue483year1977periodm02footnotesperiodnamefebruaryvalue476year1977periodm01footnotesperiodnamejanuaryseriesid21432datavalue621year1977periodm12footnotesperiodnamedecembervalue619year1977periodm11footnotesperiodnamenovembervalue616year1977periodm10footnotesperiodnameoctobervalue614year1977periodm09footnotesperiodnameseptembervalue612year1977periodm08footnotesperiodnameaugustvalue610year1977periodm07footnotesperiodnamejulyvalue607year1977periodm06footnotesperiodnamejunevalue603year1977periodm05footnotesperiodnamemayvalue600year1977periodm04footnotesperiodnameaprilvalue595year1977periodm03footnotesperiodnamemarchvalue591year1977periodm02footnotesperiodnamefebruaryvalue585year1977periodm01footnotesperiodnamejanuaryseriesid431432messagestatusrequest succeededresponsetime440410 221701489 1091010937comlearnkentmojito iprocessi1 sending signal pid 10910 sig 9the json response in the logcat represents logdtag mjsonresponsetostringinitializing mjsonresponse using volleyprivate void queryapi throws jsonexception try jsonobjectqueryputseriesid seriesid jsonobjectqueryputstartyear startyear jsonobjectqueryputendyear endyear catch jsonexception e eprintstacktrace jsonobjectrequest jsonobjrequest new jsonobjectrequestrequestmethodpost url jsonobjectquery new responselistenerjsonobject override public void onresponsejsonobject response mjsonresponse response logdtag mjsonresponsetostring new responseerrorlistener override public void onerrorresponsevolleyerror error override public mapstring string getheaders throws authfailureerror hashmapstring string headers new hashmapstring string headersputcontenttype applicationjson charsetutf8 return headers queueaddjsonobjrequest,"['java', 'android']" +883337,string length in swift 12 and swift 20 in the previous version of swift i had the following codefunc myfuncmystr string if mystrutf16count 3 with the latest release of swift 12 i now get the following errorutf16count is unavailable take the count of a utf16 view instead ie countstrutf16ok so i change my code as followsfunc myfuncmystr string if countmystrutf16 3 but that does not work i now get the following error message insteadstringutf16view is not identical to int16what is the correct way to get the length of a string with swift 12,['ios'] +883373,unknown provider ngdialogprovider in my appjs i have var app angularmoduleatlas ngroute ngdialogfor my controller i have appcontrollernodecontroller function scope http ngdialogthe ngdialog makes the error error injectorunpr unknown provider ngdialogprovider ngdialog nodecontrolleralso i used refrenced css and js fileslink relstylesheet hrefcontentngdialogcustomwidthcss link relstylesheet hrefcontentngdialogthemedefaultmincss link relstylesheet hrefcontentngdialogthemeplainmincss link relstylesheet hrefcontentngdialogcss script srcscriptsjquery213minjsscriptscript srcscriptsangularjsscriptscript srcscriptsangularroutejsscriptscript srcscriptsngdialogjsscripti tried all answers on stackoverflow and none of them work for me,['javascript'] +883382,shuffle dataframe rows i have the following dataframe col1 col2 col3 type0 1 2 3 11 4 5 6 120 7 8 9 221 10 11 12 245 13 14 15 346 16 17 18 3the dataframe is read from a csv file all rows which have type 1 are on top followed by the rows with type 2 followed by the rows with type 3 etci would like to shuffle the dataframes rows so that all types are mixed a possible result could be col1 col2 col3 type0 7 8 9 21 13 14 15 320 1 2 3 121 10 11 12 245 4 5 6 146 16 17 18 3as can be seen from the result the order of the rows is shuffled but the columns remain the same i do not know if i am explaining this clearly let me know if i do nothow can i achieve this,['python'] +883523,twitter screen name returning a null in parse logging in via twitter and trying to get the users screen name the screen name produces a null value each time any ideaspfuser currentuser pfuser currentuser pftwitterutils loginwithblockpfuser user nserror error if user nsloguh oh the user cancelled the twitter login return else if userisnew twitterscreenname pftwitterutils twitterscreenname nslogpftwitterutils twitterscreenname nsstring requeststring nsstring stringwithformat name twitterscreenname nsurl verify nsurl urlwithstringrequeststring nsmutableurlrequest request nsmutableurlrequest requestwithurlverify pftwitterutils twitter signrequestrequest nsurlconnection sendasynchronousrequestrequest queuensoperationqueue mainqueue completionhandlernsurlresponse response nsdata data nserror connectionerror nserror error nsdictionary result nsjsonserialization jsonobjectwithdatadata optionsnsjsonreadingallowfragments errorerror if error userusername twitterscreenname username resultname userprofiledescription resultdescription userimageurl resultprofile image url https stringbyreplacingoccurrencesofstring normal withstring bigger user saveeventually self performseguewithidentifier username sender self,"['ios', 'objective-c']" +883563,how do i get the views inside a container in swift i have a container view that i popped into my storyboard there is a wonderful little arrow that represents the embed segue to another scene that scenes top level object is controlled by a custom uiviewcontroller i want to call a method that is implemented in my custom class if i have access to the container how do i get a reference to whats inside,['ios'] +883589,how to write a select query or serverside function that will generate a neat timeflow graph from many data points note i am using a graph database orientdb to be specific this gives me the freedom to write a serverside function in javascript or groovy rather than limit myself to sql for this issuenote 2 since this is a graph database the arrows below are simply describing the flow of data i do not literally need the arrows to be returned in the query the arrows represent relationshipsi have data that is represented in a timeflow manner ie eventc occurs after eventb which occurs after eventa etc this data is coming from multiple sources so it is not completely linear it needs to be congregated together which is where i am having the issuecurrently the data looks something like this event next120 eventa 121121 eventb 122122 eventc 123 eventa 124124 eventd where next is the out edge to the event that comes next in the timeflow on a graph this comes out to look likeeventaeventbeventceventaeventdsince this data needs to be congregated together i need to merge duplicate events but preserve their edges in other words i need a select query that will result in eventbeventceventa eventdin this example since eventb and eventd both occurred after eventa just at different times the select query will show two branches off eventa as opposed to two separate timeflowsedit 2if an additional set of data were to be added to the data above with eventbevente the resulting datagraph would look like event next120 eventa 121121 eventb 122122 eventc 123 eventa 124124 eventd 125 eventb 126126 evente eventaeventbeventceventaeventdeventbeventei need a query to produce a tree like eventc eventb eventeeventa eventdedit 3 and 4here is the data with edges shown as opposed to the next column above i also added a couple additional columns here to hopefully clear up any confusion about the data event ip address timestamp in out 120 eventa 12315618918 20150417 124801 130 121 eventb 12315618918 20150417 124832 130 131 122 eventc 12315618918 20150417 124849 131 123 eventa 10314518722 20150417 140308 132 124 eventd 10314518722 20150417 140523 132 125 eventb 96109199184 20150417 215300 133 126 evente 96109199184 20150417 215307 133 the data is saved like this to preserve each individual event and the flow of a session labeled by the ip addresstldrgot lots of events some duplicates and need them all organized into one neat timeflow graph,['sql'] +883731,spring boot nesting configurationproperties spring boot comes with many cool features my favourite one is a typesafe configuration mechanism through configurationproperties and corresponding ymlproperties files i am writing a library that configures cassandra connection via datastax java driver i want to allow developers to configure cluster and session objects by simply editing yml file this is easy in springboot but i want to allow herhim configure multiple connections this way in php framework symfony it is as easy asdoctrine dbal default connection default connections default driver database driver host database host port database port dbname database name user database user password database password charset utf8 customer driver database driver2 host database host2 port database port2 dbname database name2 user database user2 password database password2 charset utf8this snippet comes from symfony documentationis it possible in springboot using configurationproperties should i nest them,['java'] +883797,how to deal with relations in flux imagine something like quora type question answers type answer upvotes type upvote more upvotes comments type comment more comments more answers more questions i would surely have something like a questionsstore but for all child entities i am unsure what to do with them coming from backbone i am thinking every answer should have a upvotesstore and a commentsstore and components would get their data from these stores and subscribe to updates from them as far as i understand flux childrelational stores are somewhat uncommonwhen every component subscribes to updates from questionsstore that leads to something like in commentscomponent onupdate function thissetstate comments questionsstoregetcommentsquestionid 1 answerid 1 or more extreme in commentcomponent onupdate function thissetstatequestionsstoregetcommentquestionid 1 answerid 1 commentid 1since the relational data lives in a tree structure every component needs to know all parent ids in order to be able to query their data from questionsstore i find this somehow weirdso what is the best flux pattern to deal with relational onetomany data structure,['javascript'] +883846,google analytics not working with swift 12 and xcode 63 i tried to use google analytics with my swift 12 app using xcode 63beta my bridging header works fine and containsimport gaihimport gaidictionarybuilderhimport gaiecommercefieldshimport gaiecommerceproducthimport gaiecommerceproductactionhimport gaiecommercepromotionhimport gaifieldshimport gailoggerhimport gaitrackedviewcontrollerhimport gaitrackerhi tried the following swift code to track a page var tracker2gaitracker gaisharedinstancedefaulttracker as gaitracker tracker2setkgaiscreenname valuehome screen tracker2sendgaidictionarybuildercreatescreenviewbuildbut the last line above raises the following error cannot invoke send with an argument list of type nsmutabledictionaryi found similar questions like google analytics not initialising in swift using google analytics with swift on ioswhat do i have to change to make the code above working with swift 12,"['objective-c', 'iphone']" +883874,ability to abort asynchronous call i am using babeljs with es7 style asyncawait methods i have a main script that will call a async method on an array of objects that all return promises i use promiseall to wait for all of those to return however these tasks could take a long time and if they exceed a threshold i would like to abort all of them and the task handle that in an appropriate wayis there anyway to accomplish such a thing currently the only way that i can think of is by spawning a process that does the work of calling these methods and waiting for them to all resolve and if the time limit is reach it can kill the process and do whatever handling it needsupdate some clarification about these methods that the main script is waiting on they might be doing a long series of operations calling external systems streaming files somewhere etc and not performing one single action that could be canceled independently update 2 some untested semipsuedo codeclass foo1 async dosomething call some external system copy some files put those files somewhere else s3 class foo2 async dosomething do some long computations update some systems class foohandler constructor thisfoolist async start await promiseallthisfoolistmapasync foo return await foodosomething let handler new foohandlerhandlerfoolistpushnew foo1handlerfoolistpushnew foo2 if this call takes too long because of slow connections errors whatever abort start handle it in whatever meaningful way and continue onawait handlerstart,['javascript'] +883969,no route in the route table matches the supplied values when using areas i know this error has popped up for people before but this seems to be a bit of a special casei have been working on setting up a spa with reactjs on top of aspnet mvc 4 i have had no problem getting things working on my machine however the weird issue i am seeing is that it is not working on any other machines for other devs as far as i have seen i do not have any files that are not checked in under source control i have made use of the routedebugger and i see the proper route being caught the route i am using for this spa is v2home so i have an area called v2 an mvc controller in the area called homecontroller and it has a view called index i setup a catchall in the v2arearegistrationpublic override void registerareaarearegistrationcontext context contextmaproute v2 default v2url new area v2 controller home action index heres application start in globalasaxcsprotected void application start arearegistrationregisterallareas globalconfigurationconfigurewebapiconfigregister filterconfigregisterglobalfiltersglobalfiltersfilters routeconfigregisterroutesroutetableroutes bundleconfigregisterbundlesbundletablebundles authconfigregisterauth automapperconfigurationconfigure loggerinfoapplication started globalconfigurationconfigurationensureinitialized i have gotten absolutely nowhere with this i would love to get this solved feel free to ask for anything missing,['asp.net'] +883981,how to uninstall mini conda python i have install the conda package as such wget bash miniconda conda install numpy pandas scipy matplotlib scikitlearn nltk ipythonnotebook seaborni want to uninstall it because it is messing up my pips and environmenthow do i uninstall conda totallywill it uninstall also my pip managed packages if so is there a way to uninstall conda safely without uninstalling packages managed by pip,['python'] +883996,dompdf does not render table nicely i am trying to get pdf using dompdf but i come cross a strange problem all the data and other things are fine but when it renders in pdf the first line of the table is always out of style firstly i though may be table is going to the next page which cause style out of context but i tried to limit table to one page and found out that the problem still exists so the first row of table on every page goes crazy following is my code and screen shots of pdfcontrollerdompdf new dompdfdompdfload htmllistingdompdfset papera4 landscapedompdfrenderdompdfstreamsamplepdfviewtable classtable tablebordered tr th width150client th tdclient name td tr tr thsite th tdphp print sitetitle td tr tr thaddress th td php print siteunit sitestreet sitesuburb sitestate sitelocation td tr tr thpost code th tdphp print sitepostcode td tr tr th colspan2 site informationth tr tr td colspan2 height150 php print sitesite information td tr tr th colspan2work instructionth tr tr td colspan2 height200 php print sitework instruction td tr tr th colspan2equipment on siteth tr tr td colspan2 php print sitesite equipment td tr tr th colspan2special instructionsth tr tr td colspan2 height100 php print sitespecial instruction td tr tr thcontact person th tdphp print sitecontact person td tr tr thcontact number th tdphp print sitecontact no td trtablepage 1page 2any help will be highly appreciatedthanks,['php'] +884059,how to expose existing property on objc class using an extension protocol in swift in swift 11 we were able to have code like below compile and work where we exposed existing objectivec properties through a protocol added by an extension we also had a few where the property is handled by the extensionobjc protocol enableable class var enabled bool get set let thisabledalpha cgfloat 05let enabledalpha cgfloat 10extension uibutton enableable extension uiimageview enableable var enabled bool get return alpha thisabledalpha setenabled alpha enabled enabledalpha thisabledalpha when trying to compile this code using xcode 63 and swift 12 we get the following error type uibutton does not conform to the protocol enableable the uiimageview extension seems to compile fineis there any way to expose these sort of existing properties from an objectivec type or do we have to implement a proxying property with a different name,"['ios', 'objective-c']" +884078,podofo for ios catalog object not found after writing a pdf file i have built podofo 093 for ios along with all the other needed libraries to support amrv7 arm64 and simulator my project runs fine but my problem is loading a document for the second time i always get the error catalog object not found in podofo if i open the document using preview app on mac and save it podofo can open it againheres the code i am using to open the document and save itselfdoc new podofopdfmemdocumentpath utf8stringnsstring tmppath self createcopyforfileselfpdfpathselfdocwritetmppath utf8stringnsdata myfile nsdata datawithcontentsoffiletmppathmyfile writetofiletmppath atomicallyyesnsfilemanager filemanager nsfilemanager defaultmanagernserror errorif filemanager fileexistsatpathselfpdfpath yes filemanager removeitematpathselfpdfpath errorerrorfilemanager copyitematpathtmppath topathselfpdfpath errorerrorthe error is herevoid pdfmemdocumentinitfromparser pdfparser pparser pdfobject pcatalog ptrailergetindirectkey root if pcatalog podofo raise error info epdferror noobject catalog object not found have you guys built podofo for ios lately any idea why is this happening,"['ios', 'objective-c']" +884139,itextsharp replace text in existing pdf without loosing formation i ve been searching the internet for 2 weeks and found some interesting solutions for my problem but nothing seems to give me the answermy goal is to do the folowingi want to find a text in a static pdffile and replace this text with another text i would like to keep the design of the content is it really that hardi found a way but i lost the whole information using pdfreader reader new pdfreaderpath stringbuilder text new stringbuilder for int i 1 i readernumberofpages i textappendpdftextextractorgettextfrompagereader i textreplacetxt suchennachtext txt ersetzenmittext return texttostring the second try i had was way better but needs fields where i can change the text inside string filenameexisting path string filenamenew ctestpdf using filestream existingfilestream new filestreamfilenameexisting filemodeopen using filestream newfilestream new filestreamfilenamenew filemodecreate pdf affnen pdfreader pdfreader new pdfreaderexistingfilestream pdfstamper stamper new pdfstamperpdfreader newfilestream var form stamperacrofields var fieldkeys formfieldskeys foreach string fieldkey in fieldkeys var value pdfreaderacrofieldsgetfieldfieldkey formsetfieldfieldkey valuereplacetxt suchennachtext txt ersetzenmittext textfeld unbearbeitbar machen sieht aus wie normaler text stamperformflattening true stamperclose pdfreaderclose this keeps the formatation of the rest of text and does only change my searched text i need a solution for text which is not in a textfieldthanks for all your answers and your help,['c#'] +884222,detect when wkwebview has finished loading every time i have a wkwebview app running on ios8 on ipad standard ipad useragent mozilla50 ipad cpu os 8 1 1 like mac os x applewebkit60014 khtml like gecko version80 mobile12b436 safari60014 i have tried all delegates and listeners i can think of to try and detect when a page has finished loading every time here is the problemopen your wkwebview and go to google the following are called decidepolicyfornavigationaction didstartprovisionalnavigation didfinishnavigationtype ayoutubea into google only decidepolicyfornavigationaction is called no didstartprovisionalnavigation or didfinishnavigationclick on youtube within google the following are called didstartprovisionalnavigation decidepolicyfornavigationaction didfinishnavigationfrom now on within youtube nothing is called click on a youtube video and no didstartprovisionalnavigation or didfinishnavigation also webviewloading observer is no longer called even decidepolicyfornavigationaction is only called every now and then howevera the webviewbackforwardlistcurrentitem is updated after every click so this must be detecting when the page has finished loading somehowthis behavior happens on a lot of other sites too vimeo for example i know this type of site is not updating the main frame every time but is this lack of a capability to detect when loading has startedfinished a alimitationa of wkwebview in its current statewhat i want to achieve is is there another way to detect when navigation has completed every time within java mobile websites like youtubevimeousing nsurlprotocol or similar or maybe a way to detect whenwebviewbackforwardlistcurrentitem is updatedthanks for any help,['ios'] +884272,how i will detect motion sensor in broadcast receiver i had written one receiver to detect device motion is changed or not like this in manifestxml receiver androidnamecomhanumansensorreceiversensorreceiver intentfilter androidenabledtrue androidexportedfalse action androidnameandroidintentactionuser present intentfilter receiverand inside receiver onreceive method code isstring action intentgetaction if actionequalsintentaction user present systemoutprintlnuser is present intent s new intentcontext mainactivityclass saddflagsintentflag activity new task contextstartactivitys else systemoutprintlnuser is not present finally my question is is not detecting the sensor when it is motioned it is detecting when my device in unlocked then it is calling my mainactivity but i want to detect when my device motion is changed then i want to detect in receiver how can i do that,['android'] +884329,authentication with spring security spring data mongodb i want to use spring security with mongodb using spring data and retrieve the users from my own database for spring security however i can not do that since my userservice type does not seem to be supported this is my userservice classpublic class userservice private applicationcontext applicationcontext private mongooperations mongooperations public userservice applicationcontext new annotationconfigapplicationcontextmongoconfigclass mongooperations mongooperations applicationcontextgetbeanmongotemplate public user findstring username return mongooperationsfindonequeryquerycriteriawhereusernameisusername userclass and my securityconfig classconfigurationenablewebsecuritypublic class securityconfig extends websecurityconfigureradapter autowired userservice userservice autowired public void configauthbuilderauthenticationmanagerbuilder builder throws exception builderuserdetailsserviceuserservice this does not work builderinmemoryauthenticationwithuserusernamepasswordpasswordrolesuser the line i commented saysthe inferred type userservice is not a valid substitute for the bounded parameter t extends userdetailsservicehow can i fix it so i can retrieve the users from my own database,['java'] +884402,ngrepeat with track by and filter and orderby not working i have this codejavascriptvar myapp angularmodulemyappfunction myctrlscope scopenamefilter scopecontacts name ghi name def name abc name jkl viewdiv ngcontrollermyctrl divinput typetext ngmodelnamefilter placeholdersearch div p ngrepeatcontact in contacts track by index filter namefilter orderby name contactname pdivi do not know why the order not working and why the filter is not workingat another question i have readed about something that objects cannot be filtered or ordered but i have an array with the objects above also it should workwhats the problemthanks in advance,['javascript'] +884622,autogenerated move constructors causing illegal behavior i asked a question about move constructors for which i have not accepted an answer yet because i am feeling more confused about certain aspects of the question even as i am starting to get a grip on others in particular i have found a surprising case in which both g and clang generate incorrect moveconstructorsquestion summaryg and clang apparently violate the rule that moveconstructors are not generated when destructors are explicitly defined why is this a bug or am i misunderstanding whats going onfor correctness these possiblyillegal move constructors should invalidate rhs pointer members but they do not why notit appears that the only way to avoid the unwanted behavior is to explicitly define a correct move constructor for every class that uses delete in its destructor does the qt library version 54 do thispart 1 illegally autogenerated constructorsconsider the following codeclass nomove public nomove int main stdcout nomove moveconstructible stdis move constructiblenomovevalue stdendlcompiled with both g 492 and clang 351 this code printsnomove moveconstructible 1but since nomove has an explicitly defined destructor i would expect that neither a move constructor nor a copy constructor should be autogenerated note that the unexpected constructor generation is not due to the fact that the destructor is trivial i get the same behavior when the destructor deletes an array and i am even able to compile code that requires a valid move constructor see example below whats going on here is it legal to autogenerate a move constructor here and if so whypart 2 possibly illegal autogenerated constructors causing undefined behaviorit appears that providing safe move constructors when delete is involved is fairly simple but i just want to make sure i understand when a class contains a pointer member and owns the underlying data is there any case in which it wouldnt be correct and sufficient for the move constructor to invalidate the rhs pointer after setting the destination pointer to the old valueconsider the following example which is similar to the nomove example above and is based on my original questionclass datatype public datatype val new int35 datatype delete val private int valclass marshaller public marshallerdefault datatype todatatype return stdmovedata private datatype datavoid domarshalling marshaller marshaller do some marshalling datatype marshalled datastdmovemarshallertodatatypethis compiles just fineshowing that yes datatype has an autogenerated move constructor and of course when run it causes a doubledeletion errornow this would be okay if the autogenerated move constructor invalidated the rhs pointer so if it is okay to autogenerate a move constructor here why is not that done safely the move constructor that makes this work is simplydatatypedatatype rhs valrhsval rhsval nullptrright am i missing anything should it perhaps be valstdmoverhsvalthis seems like it would be a perfectly safe function to autogenerate the compiler knows that rhs is an rvalue because the function prototype says so and therefore it is entirely acceptable to modify it so even if datatypes destructor did not delete val it seems like there wouldnt be any reason not to invalidate rhs in the autogenerated version except i suppose for the fact that this leads to a trivial performance hitso if the compiler is autogenerating this methodwhich again it should not especially since we can just as easily get this exact behavior from standard library code using unique ptr why is it autogenerating it incorrectlypart 3 avoiding this behavior in qt especially qbytearray in qt 54finally a hopefully easy question do qt 54s heapallocating classes such as qbytearray which is what i am actually using as the datatype in my original question have correctly implemented move constructors invalidating any movedfrom owning pointersi wouldnt even bother to ask because qt seems pretty solid and i have not seen any doubledeletion errors yet but given that i was taken off guard by these incorrect compilergenerated move constructors i am concerned that it is quite easy to end up with incorrect move constructors in an otherwisewellimplemented libraryrelatedly what about qt libraries written before c11 that do not have explicit moveconstructors if i can accidentally coerce an autogenerated move constructor that behaves erroneously in this case does anyone know if compiling say qt 3 with a c11compliant compiler causes undefined destruction behavior in usecases like this,['c++'] +884765,change status bar color when entering contextual action mode i have an application that uses theme attribute colorprimarydark to color the status bar on android v21this is working fine now when user longpresses a list item and enters the contextual action mode i am able to color the cab bar using attribute actionmodebackground so it looks like thisso the action bar is gray which is what i want but the status bar is still colored using the theme dark color i do not want that i want to change it to dark gray or black how can i do this i do not see any theme attribute that would work here,['android'] +884780,create a rectangle with just two rounded corners in swift i need to create a rectangle that have just two rounded corners in swift objective c code also okat the moment my code is creating two rectangles with cgpathcreatewithroundedrectcgrectmake0 0 30 60 5 5 niland cgpathcreatewithroundedrectcgrectmake0 0 30 60 0 0 niland merging them to have two right angle corners and two rounded ones but i am not happy with the code and i am pretty sure there should be much better ways to do iti am new to ios and graphical development and swift,['ios'] +884910,what are thisadvantages to using immutable state in react i have built my first react application with stateful stores the normal way and now i am looking into using an immutable global state like used in the este starterkitthe state of all stores is kept together in a single immutable data structurecomponents have no state but access data in their render based on a store getter function stores are also stateless but mutate the global application state for their domain using a cursorthe top level app component listens for state changes and rerenders the whole component treecomponents are implemented as pure meaning they use shouldcomponentupdate to efficiently figure out of they can be skipped in the rerendering it simplifies the application structure in a few wayscomponents do not listen to stores and also do not copy store data to their local state they simply grab their store state on each renderthe global state is always a snapshot of the whole application making it easier to debug and adding features like undo trivial the global state seems to simplify isomorphic renderingi only read positive things about using immutable data with react and it is recommended to avoid state in components so i wonder if there are any thisadvantages i figured there must be because otherwise i do not see why it is not recommended as the way to structure react appsimmutability is new to me so are there any caveats i should be aware of if i start using this approach in a complex real world app the only minor thing i can think of is the use of forceupdate as este is using it as i have read that it is a synchronous function morearty for example seems to defer the updates to the next animation frame in order to batch them but i consider this an implementation detail optimization and not some inherit downside of the immutable single state approach,['javascript'] +885197,pass self as argument within init method in swift 12 the following class has a let property declared as implicitly unwrapped variable this previously worked with xcode 62class subview uiview let pandgesturerecognizer uipangesturerecognizer required initcoder adecoder nscoder superinitcoder adecoder selfpandgesturerecognizer uipangesturerecognizertarget self action panaction func panactiongesture uipangesturerecognizer after updating to xcode 63 with swift 12 the following compilation errors occurproperty selfpangesturerecognizer not initialized at superinit callimmutable value selfpangesturerecognizer may only be initialized oncemoving the following line before the superinit callselfpandgesturerecognizer uipangesturerecognizertarget self action panactiongives the following errorself is used before superinit callthe property pangesturerecognizer requires no mutation therefore it has to be declared as constant let since it is a constant it has to have an initial value upon declaration or initialize it within the init method to initialize it it requires to pass self in the target parameterother thread suggested to declare it as implicitly unwrapped optional and initialize it after the superinit call this previously worked until i updated to xcode 63does anybody know a proper implementation or a workaround for this case,['ios'] +885291,facebook sdk 401 login without login button i am trying to log in without using login buttoni followed facebook tutorial but i can not get it work always give me nullpointerexceptionmy manifestxml version10 encodingutf8manifest xmlnsandroid packagecomexamplehematestfcaebooksdk usespermission androidnameandroidpermissioninternet application androidallowbackuptrue androidiconmipmapic launcher androidlabelstringapp name androidthemestyleapptheme metadata androidnamecomfacebooksdkapplicationid androidvaluestringfacebook app id activity androidnamecomfacebookfacebookactivity androidconfigchanges keyboardkeyboardhiddenscreenlayoutscreensizeorientation androidthemeandroidstylethemetranslucentnotitlebar androidlabelstringapp name provider androidauthoritiescomfacebookappfacebookcontentprovider androidnamecomfacebookfacebookcontentprovider androidexportedtrue activity androidnamemainactivity androidlabelstringapp name intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity applicationmanifestmy activity that i use it to login facebookpublic class mainactivity extends actionbaractivity callbackmanager callbackmanager loginmanager loginmanager override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main facebooksdksdkinitializegetapplicationcontext callbackmanager callbackmanagerfactorycreate loginmanager loginmanagergetinstance loginmanagerregistercallbackcallbackmanager new facebookcallbackloginresult override public void onsuccessloginresult loginresult app code toastmaketextgetapplicationcontext loginresultgetaccesstokentostring toastlength shortshow override public void oncancel app code override public void onerrorfacebookexception exception app code collectionstring permissions arraysaslistpublic profile user friends loginmanagerloginwithreadpermissionsthis permissions null pointer exception here override public boolean oncreateoptionsmenumenu menu inflate the menu this adds items to the action bar if it is present getmenuinflaterinflatermenumenu main menu return true override public boolean onoptionsitemselectedmenuitem item handle action bar item clicks here the action bar will automatically handle clicks on the homeup button so long as you specify a parent activity in androidmanifestxml int id itemgetitemid noinspection simplifiableifstatement if id ridaction settings return true return superonoptionsitemselecteditem override protected void onactivityresultint requestcode int resultcode intent data superonactivityresultrequestcode resultcode data callbackmanageronactivityresultrequestcode resultcode data my log cat0414 200346840 80758075comexamplehematestfacebooksdk eandroidruntimei1 fatal exception main process comexamplehematestfacebooksdk pid 8075 javalangruntimeexception unable to start activity componentinfocomexamplehematestfacebooksdkcomexamplehematestfacebooksdkmainactivity javalangnullpointerexception at androidappactivitythreadperformlaunchactivityactivitythreadjava2413 at androidappactivitythreadhandlelaunchactivityactivitythreadjava2471 at androidappactivitythreadaccess900activitythreadjava175 at androidappactivitythreadhhandlemessageactivitythreadjava1308 at androidoshandlerthispatchmessagehandlerjava102 at androidoslooperlooplooperjava146 at androidappactivitythreadmainactivitythreadjava5602 at javalangreflectmethodinvokenativenative method at javalangreflectmethodinvokemethodjava515 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava1283 at comandroidinternaloszygoteinitmainzygoteinitjava1099 at dalviksystemnativestartmainnative method caused by javalangnullpointerexception at comfacebookloginloginmanagergetloggerloginmanagerjava391 at comfacebookloginloginmanagerlogcompleteloginloginmanagerjava414 at comfacebookloginloginmanagerstartloginloginmanagerjava384 at comfacebookloginloginmanagerloginwithreadpermissionsloginmanagerjava262 at comexamplehematestfacebooksdkmainactivityoncreatemainactivityjava59 at androidappactivityperformcreateactivityjava5451 at androidappinstrumentationcallactivityoncreateinstrumentationjava1093 at androidappactivitythreadperformlaunchactivityactivitythreadjava2377a a a a a a a a a a a a at androidappactivitythreadhandlelaunchactivityactivitythreadjava2471a a a a a a a a a a a a at androidappactivitythreadaccess900activitythreadjava175a a a a a a a a a a a a at androidappactivitythreadhhandlemessageactivitythreadjava1308a a a a a a a a a a a a at androidoshandlerthispatchmessagehandlerjava102a a a a a a a a a a a a at androidoslooperlooplooperjava146a a a a a a a a a a a a at androidappactivitythreadmainactivitythreadjava5602a a a a a a a a a a a a at javalangreflectmethodinvokenativenative methoda a a a a a a a a a a a at javalangreflectmethodinvokemethodjava515a a a a a a a a a a a a at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava1283a a a a a a a a a a a a at comandroidinternaloszygoteinitmainzygoteinitjava1099a a a a a a a a a a a a at dalviksystemnativestartmainnative methodi tried every thing but ended up with nullpointerexceptionplease help me,['android'] +885297,how do i send webview content body via email currently in my app i am using a webview for my html content to be thisplayedwhich is coming via assets folder as expectedjust to clarify however i have integrated send via email functionality and i see the subject body and title as null instead of content in focus in the selected email of choice say i pick gmail when i select my send via email option i see the content body as null instead of the content in the webviewany one has done this or has an idea how to go about the sameheres my codemy emailutils classpublic class emailutils public static string feedback email public static void sharenewsviaemailfinal fragment fragment final string emailsubject final string emailbody sharenewsviaemailexfragmentgetactivity emailsubject emailbody public static void sharenewsviaemailexfinal context context final string emailsubject final string emailbody final intent emailintent new intentintentaction send emailintentsettypetexthtml final string subjectappendtext contextgetresourcesgetstringrstringemail subject append emailintentputextraintentextra subject emailsubject subjectappendtext emailintentputextraintentextra text emailbody contextstartactivityintentcreatechooseremailintent send email part my fragment class the button where it is calledoverride public void onmenuitemclickedfinal int position moptionsmenuhelperhidemenu menubuttonsetselectedfalse switch position case optionmenuitemsemail story position emailarticle break private void emailarticle final fragment fragment marticleadaptergetfragmentmarticlepagergetcurrentitem if fragment instanceof articlefragmentwebview final string emailsubject articlefragmentwebviewfragmentgetheadline final string articlebody articlefragmentwebviewfragmentgetarticlebody final string newline getresourcesgetstringrstringnew line final string thisclamer getresourcesgetstringrstringintellectual property info final string emailbody articlebody newline thisclamer emailutilssharenewsviaemailthis emailsubject emailbody how do i go about the samethanksheres the articlefragmentwebviewpublic class articlefragmentwebview extends absbasearticlefragment public static final string tag article fragment articlefragment public static final string article position article position public static final string category code article code private int mpositioninpager private articlewebviewclient articlewebviewclient override public void onactivitycreatedfinal bundle savedinstancestate superonactivitycreatedsavedinstancestate mpositioninpager getargumentsgetintarticle position override public view oncreateviewfinal layoutinflater inflater final viewgroup container final bundle savedinstancestate final view view superoncreateviewinflater container savedinstancestate articlewebviewclient new technicarticlewebviewclientgetactivity view return view override public void onloading final view fragmentview getview if fragmentview null layoututilsshowloadingfragmentview override public void showloadingview view layoututilsshowloadingview override public void showresultsfinal uri uri layoututilsshowresultsgetview ridnews body override public void settextsizetextsize textsize articlewebviewclientincreasefontsize override public void shownoresultsfinal uri uri layoututilsshownoresultgetview riddetails container override public void showrelateddivider override protected void getrelatedquotes override public uri oncreatecontenturi final string articlecode getargumentsgetstringarticle code return uriwithappendedpathnewscontentproviderarticle mynews uri articlecode override public void onstart superonstart public int getpositioninpager return mpositioninpager override protected int getfragmentlayoutid return rlayoutfragment article briefcase override protected int getarticletextviewid return ridnews body override protected int getflowtextviewid return ridtv override protected int getheadertextviewid return ridheadline override protected int getmetadatatextviewid return ridtimestamp and source override public void onmenuitemclickedfinal int position do nothing override public boolean setviewvaluefinal view view final cursor cursor final int columnindex if viewgetid ridnews body paranoia return true string article cursorgetstringcolumnindex string storyid cursorgetstringcursorgetcolumnindexbriefcasecolumnsid return articlewebviewclientsetarticlearticle storyid and heres the model class for getarticlebodypublic class briefcase public static final string text type text public static final string html type html public static final string pdf type pdf public static class columns public static final string id id public static final string name name public static final string saved date saveddate public static final string type documenttype public static final string document date documentdate public static final string source documentsource public static final string document link documentlink public static final string document id documentid public static final string is read isread public static final string article body articlebody primaryric public briefcasestring id string articleid string name string docdate string source string doctype mid id mdocumentid articleid mname name mpnacdate docdate mdocumentsource source mdocumenttype doctype misread false msaveddate new date serializednamecolumnsid private string mid serializednamecolumnsname private string mname serializednamecolumnssaved date private date msaveddate serializednamecolumnstype private string mdocumenttype serializednamecolumnsdocument date private string mpnacdate serializednamecolumnssource private string mdocumentsource serializednamecolumnsdocument id private string mdocumentid serializednamecolumnsis read private string misread public string getid return mid public string getname return mname public date getsaveddate return msaveddate public string getdocumenttype return mdocumenttype public string getpnacdate return mpnacdate public string getdocumentsource return mdocumentsource public string getdocumentlink string doclink null ifstringutilsisemptymdocumentsource return doclink return mdocumentid public string getisread return misread public contentvalues tocontentvalues if hasvaliddata final contentvalues values new contentvalues valuesputcolumnsid mid valuesputcolumnsname decodeheadline valuesputcolumnssaved date msaveddategettime valuesputcolumnsdocument link getdocumentlink valuesputcolumnsdocument date dateutilsconvertfromutcstringtolongmpnacdate valuesputcolumnssource mdocumentsource valuesputcolumnsis read misread valuesputcolumnstype mdocumenttype valuesputgenericcolumnsuser id sharedpreferencesmanagergetinstancegetloginusername return values return null private string decodeheadline string decodedheadline mname try decodedheadline urldecoderdecodemname networkutilsvaluesutf 8 catch final exception e eprintstacktrace return decodedheadline public contentvalues tocontentfordatabaseupdatevalues if hasvaliddata final contentvalues values tocontentvalues valuesputcolumnsarticle body getarticlebody return values return null private string getarticlebody string body final contentresolver resolver applicationgetappcontextgetcontentresolver final string projection new string columnsarticle body final uri uri uriwithappendedpathbriefcasecontentproviderbriefcase article story uri mid final cursor cursor resolverqueryuri projection null null null ifcursorgetcount0 cursormovetofirst body cursorgetstringcursorgetcolumnindexcolumnsarticle body return body private boolean hasvaliddata boolean isvalid false if stringutilsisnotemptymid stringutilsisnotemptymname isvalid true return isvalid,['android'] +885309,how do i fix this annoying syntastic rails error i have the following code in rails posterrorsfull messageseach do msg li msg li end syntasticcheck vim plug in keeps thisplaying this errorappviewspostsnewhtmlerbsyntax line12 1 1 appviewspostsnewhtmlerb12 warning possibly useless use of a variable in void context,"['ruby-on-rails', 'ruby']" +885381,scatterplot without linear fit in seaborn i am wondering if there is a way to turn of the linear fit in seaborns lmplot or if there is an equivalent function that just produces the scatterplot sure i could also use matplotlib however i find the syntax and aesthetics in seaborn quite appealing eg i want to plot the following plotimport seaborn as snssnssetstyleticksdf snsload datasetanscombesnslmplotx y datadf huedatasetwithout the linear fit like sofrom itertools import cycleimport numpy as npimport matplotlibpyplot as pltcolor gen cycleblue lightgreen red purple gray cyanfor lab in npuniquedfdataset pltscatterdflocdfdataset lab x dflocdfdataset lab y cnextcolor gen labellabpltlegendlocbest,['python'] +885443,warning method override for designated initializer i programmatically create several tables and the code has worked fine for years it did not generate any warnings two weeks ago when i last ran it iave since updated to ios 83 and i now get three warnings for each uitableviewcontrollermethod override for the designated initializer of the superclass initwithstyle not found method override for the designated initializer of the superclass initwithcoder not found method override for the designated initializer of the superclass initwithnibnamebundle not foundthe code to initialize the table is similar for all of my tables instancetypeinitinmanagedobjectcontextnsmanagedobjectcontext context withscorekeeperscorekeeper scorer withwordlistwordlist wordlist self super initwithstyleuitableviewstylegrouped if self mobjcontext context scorekeeper scorer wordlist wordlist return selfand the h looks like thisinterface settingstableviewcontroller uitableviewcontroller uipopovercontroller popover instancetypeinitinmanagedobjectcontextnsmanagedobjectcontext context withscorekeeperscorekeeper scorer withwordlistwordlist wordlist ns designated initializeri thought that i was overriding a designated initializer by invoking self super initwithstyleuitableviewstylegrouped but i guess the compiler now has other ideasso how do i override the designated initializer,"['ios', 'objective-c']" +885487,d3 histogram number of occurrences of date from time stamp newb here i have a csv with this datadate lat lon01012015 093814 am379734248757542301012015 094827 pm373852181221141301012015 101734 am390817127655460301022015 012717 pm4021620474619533i want to have a histogram where the x axis is by date and the y axis is by number of occurrencesso jan 1 would have a column height of 3 and jan 2 would have a column height of 1 the time of day is irrelevantdo i need to parse the dates or set a time interval of day somehow or create an array it seems there are two steps filter the data into chunks and count the chunks but i am not sure how to do iti found this example but the dates are already rounded nicely to dates and the data is in the file not externalthanks for any help,['javascript'] +885569,how to speed up aggregation queries following is the aggregation query match userid in 5 workflowstarttime gte isodate20150409t0z lte isodate20150416t0z group id task taskid workflowid workflowinstanceid taskname first task starttime first starttime endtime last endtime lastexecutiontime last starttime workflowname first workflowname project id 1 lastexecutiontime 1 taskname 1 averageexecutiontime subtract endtime starttime workflowname 1 group id idtask lastexecutiontime last lastexecutiontime averageexecutiontime avg averageexecutiontime taskname first taskname totalinstancecount sum 1 workflowname first workflowname project id id id 0 name taskname lastexecutiondate substr lastexecutiontime 0 30 averageexecutiontimeinmilliseconds averageexecutiontime totalinstancecount totalinstancecount workflowname 1 my collection documents are as follows id objectid550ff07ce4b09bf056df4ac1 outputdata xyz inputdata null location null channelname xyz userid 5 taskid 95 channelid 5 status success tasktypeid 7 workflowid 37 task xyz workflowstarttime isodate20150323t050926z endtime isodate20150323t052244z starttime isodate20150323t052244z tasktype trigger workflowinstanceid 233201595d17f1725804fe3b62712e862af08ce stacktrace null workflowname xyz data workflowi have a index on workflowstarttime1userid1 starttime1their are hardly 90 records in collection and as it is i am using a subset of data while quering using date range still it taking around 15 to 17 seconds i have used aggregation framework with other collections with huge data and the performance is very good do not know what is wrong with this query as its showing very slow output i expect it to be in mills as its a real time analytics queryany pointer on it appreciatedoutput when explain true added to aggregation query stages cursor query userid in 5 workflowstarttime gte isodate20150409t0z lte isodate20150416t0z fields endtime 1 starttime 1 task 1 taskid 1 workflowinstanceid 1 workflowname 1 id 0 plan cursor btreecursor ismultikey false scanandorder false indexbounds workflowstarttime isodate20150416t0z isodate20150409t0z userid 5 5 allplans cursor btreecursor ismultikey false scanandorder false indexbounds workflowstarttime isodate20150416t0z isodate20150409t0z userid 5 5 group id task taskid workflowid workflowinstanceid taskname first task starttime first starttime endtime last endtime lastexecutiontime last starttime workflowname first workflowname project id true lastexecutiontime true taskname true averageexecutiontime subtract endtime starttime workflowname true group id idtask lastexecutiontime last lastexecutiontime averageexecutiontime avg averageexecutiontime taskname first taskname totalinstancecount sum const 1 workflowname first workflowname project id false id id name taskname lastexecutiondate substr lastexecutiontime const 0 const 30 averageexecutiontimeinmilliseconds averageexecutiontime totalinstancecount totalinstancecount workflowname true ok 1,['java'] +885616,angularjs custom select2 directive i have created simple custom angularjs directive for this awesome jquery plugin jqueryselect2 as followsdirectiveappdirectiveselect2functiontimeoutparse return restrict ac link functionscope element attrs timeoutfunction elementselect2 200 usage in html templatesselect classformcontrol select2 namecountrydatangmodelclientprimary addresscountryngoptionscname as cname for c in clientcountries option valueselect countryoptionselectit is working as expected and my normal select element is replaced by select2 plugins however there is one issue though sometimes it is showing default value ie select country here although in dropdown proper model value is auto selectednow if i increase timeout interval from 200 to some high value say 1500 it is working but delays the the rendering of directive also i think this is not proper solution for it as my data is getting loaded via ajaxi have also tried to update directive as follows but no luck in that eitherappdirectiveselect2functiontimeoutparse return restrict ac require ngmodel link functionscope element attrs var modelaccessor parseattrsngmodel timeoutfunction elementselect2 scopewatchmodelaccessor function val ifval elementselect2valval ps i know that there is similar module present uiselect but it requires some different markup in form of uiselectuiselect and my app is already fully developed and i just want to replace normal select box with select2so can you please guide me how can i resolve this issue and make sure that directive keeps in sync with latest behaviour,"['javascript', 'jquery']" +885736,differences and similarities between lumen and laravel i read the documentation and it seems lumen is laravel with less features i must be missing somethingi am looking for a comparison table of the components and features of both laravel and lumen does anyone know the differences,['php'] +885809,can docker help build executable that work in different platform i am new to docker and so my question could be very naivestupid the application that we use presently need to be compiled in different platform to make it work in desired platform ie linux and window mainly so we need to compile source codecc in different platform and give different executable to customer as per their os my question is 1 is it possible with docker that i have one executable which work in all platform ie i compile my source code in one platform eg in linux and ship executable with docker to run in window platform thanks in advance,['c++'] +885934,selecting single row with no unique key i have a table like sofld1 fld2 fld30 1234 abc0 1235 def1 1236 ghi2 1236 jkl3 1236 mno4 1237 pqr5 1237 stu6 1237 vwxnote that neither column is unique there may be many rows with fld1 0 but for all other values fld1 will be unique and there may be many rows with the same value for fld2i need to select a single row for each value of fld2 with the highest value in fld 1 so the result based on the above data would befld1 fld2 fl40 1234 abc0 1235 def3 1236 mno 6 1237 vwx,['sql'] +886000,how to properly handle onerror inside rxjava android i am getting a list of installed apps on the device it is a costly operation so i am using rx for that observablelist observable observablecreatesubscriber list result getuserapps subscriberonnextresult subscriberonerrornew throwable subscriberoncompleted observable maps arrayliststring list new arraylist arraylistapplication applist new arraylist for application p arraylistapplication s listaddpgetappname applistaddp return applist subscribeonschedulersnewthread observeonandroidschedulersmainthread doonerrorthrowable letag throwable throwablegetmessage subscribes createlistviews viewhowever my problem is with handling errorsnormally user launches this screen waits for apps to load selects what is best and goes to next page however when user quickly changes the ui app crashes with nullpointerokay so i implemented this onerror however it still does not work and with above usecase it throws me this 0415 181242530 2238822388pldigitalvirgosafemob eandroidruntimei1 fatal exception main javalangillegalstateexception exception thrown on schedulerworker thread add onerror handling at rxinternalschedulersscheduledactionrunscheduledactionjava52 at androidoshandlerhandlecallbackhandlerjava730 at androidoshandlerthispatchmessagehandlerjava92 at androidoslooperlooplooperjava176 at androidappactivitythreadmainactivitythreadjava5419 at javalangreflectmethodinvokenativenative method at javalangreflectmethodinvokemethodjava525 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava1046 at comandroidinternaloszygoteinitmainzygoteinitjava862 at dalviksystemnativestartmainnative method caused by rxexceptionsonerrornotimplementedexception at rxobservable31onerrorobservablejava7134 at rxobserverssafesubscriber onerrorsafesubscriberjava154 at rxobserverssafesubscriberonerrorsafesubscriberjava1 at rxinternaloperatorsoperatordooneach1onerroroperatordooneachjava70 at rxinternaloperatorsnotificationliteacceptnotificationlitejava147 at rxinternaloperatorsoperatorobserveonobserveonsubscriberpollqueueoperatorobserveonjava177 at rxinternaloperatorsoperatorobserveonobserveonsubscriberaccess0operatorobserveonjava65 at rxinternaloperatorsoperatorobserveonobserveonsubscriber2calloperatorobserveonjava153 at rxinternalschedulersscheduledactionrunscheduledactionjava47 a a a a a a a a a a a a at androidoshandlerhandlecallbackhandlerjava730 a a a a a a a a a a a a at androidoshandlerthispatchmessagehandlerjava92 a a a a a a a a a a a a at androidoslooperlooplooperjava176 a a a a a a a a a a a a at androidappactivitythreadmainactivitythreadjava5419 a a a a a a a a a a a a at javalangreflectmethodinvokenativenative method a a a a a a a a a a a a at javalangreflectmethodinvokemethodjava525 a a a a a a a a a a a a at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava1046 a a a a a a a a a a a a at comandroidinternaloszygoteinitmainzygoteinitjava862 a a a a a a a a a a a a at dalviksystemnativestartmainnative method caused by javalangthrowable at pldigitalvirgosafemobfragmentswizardapplicationsfragmentlambdagetapplist25applicationsfragmentjava267 at pldigitalvirgosafemobfragmentswizardapplicationsfragmentaccesslambda2applicationsfragmentjava at pldigitalvirgosafemobfragmentswizardapplicationsfragmentlambda3callunknown source at rxobservable1callobservablejava145 at rxobservable1callobservablejava137 at rxobservableunsafesubscribeobservablejava7304 at rxinternaloperatorsoperatorsubscribeon11calloperatorsubscribeonjava62 at rxinternalschedulersscheduledactionrunscheduledactionjava47 at javautilconcurrentexecutorsrunnableadaptercallexecutorsjava390 at javautilconcurrentfuturetaskrunfuturetaskjava234 at javautilconcurrentscheduledthreadpoolexecutorscheduledfuturetaskaccess201scheduledthreadpoolexecutorjava153 at javautilconcurrentscheduledthreadpoolexecutorscheduledfuturetaskrunscheduledthreadpoolexecutorjava267 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava1080 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava573 at javalangthreadrunthreadjava841how should i properly handle this problem,['android'] +886074,springboot jersey allow jersey to serve static content the application uses jdk 8 spring boot spring boot jersey starter and is packaged as a war although it is locally run via spring boot maven pluginwhat i would like to do is to get the documentation i generate on the fly at build time as a welcome pagei tried several approachesletting jersey serving the static contents by configuring in applicationproperties the proper init parameter as described hereintroduce a metadatacompletefalse webxml in order to list the generated html document as a welcomefilenone of that worked outi would like to avoid having to enable spring mvc or creating a jersey resource just for serving a static fileany ideahere is the jersey configuration class i unsuccessfully tried to add a servletpropertiesfilter static content regex thereapplicationpathexposedapplicationcomponentpublic class resourceconfiguration extends resourceconfig public resourceconfiguration packagesxapi packagesxconfig propertyserverpropertiesbv thisable validate on executable override check true propertyserverpropertiesbv send error in response true and here is spring boot application class i tried adding an applicationproperties with springjerseyinitjerseyconfigservletfilterstaticcontentregexhtml but it did not work i am not exactly sure what the property key should be herespringbootapplicationcomponentscanimportdataconfigurationclasspublic class application extends springbootservletinitializer override protected springapplicationbuilder configurespringapplicationbuilder application return applicationsourcesapplicationclass public static void mainstring args springapplicationrunapplicationclass args,['java'] +886142,javascript new datedatestring handling would someone explain why formatting the same datestring differently gives a different date new date04081984a sun apr 08 1984 0 gmt0600 mountain daylight time new date19840408a sat apr 07 1984 180 gmt0600 mountain daylight time,['javascript'] +886300,jquery link for bootstrap i have noticed that the bootstrap provides a jquery link that you can use to run the javascript files what i would like to know is if it matters what jquery link you usecurrently the code provided by the bootstrap site isscript srcscriptwould it hurt if i used these links below to replace the above linkscript srcscriptscript srcscript,"['javascript', 'jquery', 'html']" +886312,not understanding median of medians algorithm to find kth element below is my code for trying to understand the median of medians algorithm using blocks of size 5 i understand how to get medians of the input but i am not sure how to code the block to keep recursing the input until i just have the median then after getting that median i am not sure how to use it as a pivot to throw away the useless information to partition the input getmediansarray returns an array of size ceilinputlength5 and getmedians just returns the median from an array only used on arrays of length 5public static int findkthelementint input int k int numofmedians int mathceilinputlength50 int medians new intnumofmedians medians getmediansarrayinput medians 1 this only gets the first iteration of medians of the input how do i recurse on this until i just have one median 2 how should i partition about the pivot once i get itpublic static int getmediansarrayint input int medians int numofmedians int mathceilinputlength50 int five new int5 for int i 0 i numofmedians i if i numofmedians 1 for int j 0 j 5 j fivej inputi5j mediansi getmedianfive else int numofremainders inputlength 5 int remainder new intnumofremainders for int j 0 j numofremainders j remainderj inputi5j mediansi getmedianfive return medianspublic static int getmedianint input arrayssortinput if inputlength 2 0 return inputinputlength2 inputinputlength2 1 2 return inputinputlength2,['java'] +886433,microservice service registry api gateway and data sharing i m actually reading tones of articles concerning microservices architecture but it seems that they are dealing the things the easiest way possible without going deeper in explanationsto explain you my questions i will show you my actual little architecture so heres what i want to use before making anything technically i need more theorical informationsdescription of my domaini have some mobile and browser based customers able to connect themselves on an application getting their user informations and able to consult billing informations about what they bought on a monolithic application i would use this architecture presentation layer with mobile angularember business layer with a rest api with nginx in front of that dal with a standard mysql database scalability would be applied only on xaxisi want to use a microservice architecture in this case because it is domain scalable and really flexible and to learn a bit more about it of courseon the schema in each service there is the only http url exposed by the api concernedquestionsa in the 1 flux mobile send an http request on in my mind the apigateway is able to ask a standard service registry eureka zookeeper or something else is able to find if a authsrv is accessible and can retrieve his network adress then the apigateway can request the authsrv and respond to the serveris that a good way to make it work is not there a latency problem when dealing with x machines to access a data b the flux 2 consults the service registry how can the service registry understand that every requests on auth even on children url like authother if it was exposed are related to this service on this address ipport c the flux 3 is showing that the service registry has an available authsrv the 3 bis show the other no authsrv is available in a little application we can admit that we lose sometime of thisponibility but in a big system where hundred of services are linked how can we handle service defficience d in an other post i was asking how to store a billing information because it is related to a user from another service and another databasein a standard architecture i would have billinginformations billinguserobjectiduseridin a microservice architecture somebody recommended to use billinginformations billinguseruser12365 url corresponding the the user ressource in the other serviceis this the best way to handle service data sharing and not couple the services e when should i prefer using amqp protocol instead of http protocol in this specific case thanks for advance,['java'] +886447,parse and xcode blocks would not autocomplete the last version of parse 171 and xcode 63 i cannot autocomplete blocks for parse api this is really annoying does anyone else have this problem before like every other blocks you can tab to highlight it and then hit enter query findobjectsinbackgroundwithblocknsarray objects nserror error now when i hit enter this happensquery findobjectsinbackgroundwithblocknullable pfarrayresultblocknullable block,['ios'] +886464,wrap text outside bezier curve in android i want to wrap text in the shape of bezier curve outside the curve in androidwhat i have tried path path new pathpathaddcirclex y radius pathdirectioncwmycanvasdrawtextonpathmytext path offset 0 mypaintwhat i am trying to achieve but this code draws text on curvei do not want to write text on curvei want to wrap text according to the curve and write it on next lineto understand it clearly please refer baconformecomi want to create this jquery like behaviour in android without using webbrowserand saw this link on android how do i wrapping text inside in a bezier pathquestion is it possible to achieve this if yesthen please guide me,['android'] +886475,es 6 difference between symboliterator and iterator i was wondering if there was a specific difference in implementing an iterator using the iterator function versus the symboliterator oneon mdn there is a page on arrayprototypeiterator yet in the examples itself symboliterator is used as the function name is this just the updated version and iterator is not valid anymore or are both of them valid,['javascript'] +886478,service in windows 7 operating system not using the hosts file as local service i have programmed a windows service that is calling another service over the network the other services ip is defined in the hosts filethe windows service is running as local systemon windows server 2008 this works fine the ip from the hosts file is usedon windows 7 the ip from the hosts file is not used instead it uses normal dns if i use a normal user instead of local system the behaviour is correct the same as on windows server 2008 the host file is used i can reliably switch between local system and a normal user for the same service binary without touching the hosts file the error is reproducable so it is not about caching anything anywhere or having a wrong hosts file is there anything in windows 7 i missed why would a service running as local system not use the hosts file,['c#'] +886651,admintokenaction fatal error cannot obtain application sso token i was trying to install openam 12 war with apache tomcat agent as configured ssobut tried more than fifty times but am getting only errorif i change below property value as amadmin from webagentwhile calling the protected application in tomcat second instance it countinously redirecting to same page again and again but did not get any exception amadmin is my admin user of openam consoleopenssoagentbootstrappropertiescomsunidentityagentsappusername exception in tomcat logapr 16 2015 54110 pm orgapachetomcatutildigesterdigester startelementsevere begin event threw errorjavalangexceptionininitializererror at comsunidentityagentsarchagentconfigurationbootstrapclientconfigurationagentconfigurationjava727 at comsunidentityagentsarchagentconfigurationinitializeconfigurationagentconfigurationjava1140 at comsunidentityagentsarchagentconfigurationclinitagentconfigurationjava1579 at comsunidentityagentsarchmanagerclinitmanagerjava675 at comsunidentityagentstomcatv6amtomcatrealmclinitamtomcatrealmjava67 at sunreflectnativeconstructoraccessorimplnewinstance0native method at sunreflectnativeconstructoraccessorimplnewinstancenativeconstructoraccessorimpljava57 at sunreflectdelegatingconstructoraccessorimplnewinstancedelegatingconstructoraccessorimpljava45 at javalangreflectconstructornewinstanceconstructorjava526 at javalangclassnewinstanceclassjava374 at orgapachetomcatutildigesterobjectcreaterulebeginobjectcreaterulejava145 at orgapachetomcatutildigesterdigesterstartelementdigesterjava1288 at comsunorgapachexercesinternalparsersabstractsaxparserstartelementabstractsaxparserjava509 at comsunorgapachexercesinternalparsersabstractxmldocumentparseremptyelementabstractxmldocumentparserjava182 at comsunorgapachexercesinternalimplxmldocumentfragmentscannerimplscanstartelementxmldocumentfragmentscannerimpljava1342 at comsunorgapachexercesinternalimplxmldocumentfragmentscannerimplfragmentcontentdrivernextxmldocumentfragmentscannerimpljava2770 at comsunorgapachexercesinternalimplxmldocumentscannerimplnextxmldocumentscannerimpljava606 at comsunorgapachexercesinternalimplxmldocumentfragmentscannerimplscandocumentxmldocumentfragmentscannerimpljava510 at comsunorgapachexercesinternalparsersxml11configurationparsexml11configurationjava848 at comsunorgapachexercesinternalparsersxml11configurationparsexml11configurationjava7 at comsunorgapachexercesinternalparsersxmlparserparsexmlparserjava141 at comsunorgapachexercesinternalparsersabstractsaxparserparseabstractsaxparserjava1213 at comsunorgapachexercesinternaljaxpsaxparserimpljaxpsaxparserparsesaxparserimpljava649 at orgapachetomcatutildigesterdigesterparsedigesterjava1561 at orgapachecatalinastartupcatalinaloadcatalinajava615 at orgapachecatalinastartupcatalinaloadcatalinajava663 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava57 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43 at javalangreflectmethodinvokemethodjava606 at orgapachecatalinastartupbootstraploadbootstrapjava280 at orgapachecatalinastartupbootstrapmainbootstrapjava454caused by comsunidentitysecurityamsecuritypropertiesexception admintokenaction fatal error cannot obtain application sso tokencheck amconfigproperties for the following properties comsunidentityagentsappusername comiplanetamservicepassword at comsunidentitysecurityadmintokenactionrunadmintokenactionjava272 at comsunidentitysecurityadmintokenactionrunadmintokenactionjava76 at javasecurityaccesscontrollerdoprivilegednative method at comsunidentitycommonconfigurationconfigurationobserverregisterlistenersconfigurationobserverjava89 at comsunidentitycommonconfigurationconfigurationobservergetinstanceconfigurationobserverjava114 at comsunidentitycommondebugpropertiesobserverclinitdebugpropertiesobserverjava49 32 morehost entry 127001 orgssocom testopenamcomtomcat two instances from apachetomcat70571 one for openam120war running in port 80802 another one for webagentopenamtomcatv67agent330zip with my protected application running in port 7070openam configuration 1 default configuration amadmin with password password and policyagent with passwordpassword1 created2 login as amadmin access control openamidprealmcreated3 access control openamidprealmsubjectidpuserpasswordpasswordcreated4 access control openamidprealmagentj2eenamewebagentpasswordpasswordlocalagenturlcreated5 federation create circle of trust openamidpcot select realm openamidprealm created6 common tasks create hosted identity provider select realm openamidprealm select circle of trust openamidpcot createdweb agent configuration dstudiesoopenamsp2idpwebagentj2ee agentstomcat v6 agentbinagentadmin installplease read the following license agreement carefullypress enter to continue or enter and to finishwelcome to the openam policy agent for apache tomcat 60 servletjspcontainerenter the complete path to the directory which is used by tomcat server tostore its configuration files this directory uniquely identifies thetomcat server instance that is secured by this agent help exit enter the tomcat server config directory path cprogram filesapachesoftware foundationtomcat 60conf dstudiesoopenamsp2idpapachetomcatspapachetomcat7057confenter the url where the openam server is running please include thedeployment uri also as shown below help back exit openam server url catalina home environment variable is the root of the tomcatinstallation help back exit enter the catalina home environment variable dstudiesoopenamsp2idpapachetomcatspapachetomcat7057choose yes to deploy the policy agent in the global webxml file help back exit install agent filter in global webxml true trueenter the agent url please include the deployment uri also as shown below help back exit agent url enter the agent profile name help back exit enter the agent profile name webagententer the path to a file that contains the password to be used for identifyingthe agent help back exit enter the path to the password file dstudiesoopenamsp2idppasswordtxtwarningagent profileuser webagent does not exist in openam server either hitthe back button and reenter the correct agent profile nameuser name orcreate this agent profile when askedavailable only in custominstallor continue without validating it because agent profile is in sub realm orcontinue without validatingcreating it and manually validatecreateit in openam server after installationsummary of your responsestomcat server config directory dstudiesoopenamsp2idpapachetomcatspapachetomcat7057confopenam server url catalina home environment variable dstudiesoopenamsp2idpapachetomcatspapachetomcat7057tomcat global webxml filter install trueagent url agent profile name webagentagent profile password file name dstudiesoopenamsp2idppasswordtxtverify your settings above and decide from the choices below1 continue with installation2 back to the last interaction3 start over4 exitplease make your selection 1 1updating thedstudiesoopenamsp2idpapachetomcatspapachetomcat7057binsetenvbatscript with the agent configuration jvm option donedonecreating directory layout and configuring agent file for agent 001instance donereading data from file dstudiesoopenamsp2idppasswordtxt andencrypting it donegenerating audit log file name donecreating tag swapped openssoagentbootstrapproperties file for instanceagent 001 donecreating a backup for filedstudiesoopenamsp2idpapachetomcatspapachetomcat7057confserverxmldonecreating a backup for filedstudiesoopenamsp2idpapachetomcatspapachetomcat7057confwebxmldoneadding openam tomcat agent realm to server xml file dstudiesoopenamsp2idpapachetomcatspapachetomcat7057confserverxmldoneadding filter to global deployment descriptor file dstudiesoopenamsp2idpapachetomcatspapachetomcat7057confwebxmldoneadding openam tomcat agent filter and form login authentication to selectedweb applications donesummary of agent installationagent instance name agent 001agent bootstrap file locationdstudiesoopenamsp2idpwebagentj2ee agentstomcat v6 agentagent 001configopenssoagentbootstrappropertiesagent configuration file locationdstudiesoopenamsp2idpwebagentj2ee agentstomcat v6 agentagent 001configopenssoagentconfigurationpropertiesagent audit directory locationdstudiesoopenamsp2idpwebagentj2ee agentstomcat v6 agentagent 001logsauditagent debug directory locationdstudiesoopenamsp2idpwebagentj2ee agentstomcat v6 agentagent 001logsdebuginstall log file locationdstudiesoopenamsp2idpwebagentj2ee agentstomcat v6 agentinstallerlogsauditinstalogthank you for using openam policy agentopenssoagentbootstrappropertiescomiplanetamnamingurlcomsunidentityagentsconfigserviceresolver comsunidentityagentstomcatv6amtomcatagentserviceresolvercomsunidentityagentsappusername webagentcomiplanetamservicesecret aqic91zdxfnlewliwrjdohp4vdraq7vpmblamencryptionpwd lzco703977uem52kt4zdyijlm2pmw3dcomiplanetservicesdebuglevelerrorcomiplanetservicesdebugdirectorydstudiesoopenamsp2idpwebagentj2ee agentstomcat v6 agentagent 001logsdebugcomsunservicesdebugmergealloncomsunidentityagentsconfiglocallogfile dstudiesoopenamsp2idpwebagentj2ee agentstomcat v6 agentagent 001logsauditamagent org sso com 7070logcomsunidentityagentsconfigorganizationname comsunidentityagentsconfiglockenable falsecomsunidentityagentsconfigprofilename webagentcomiplanetamservicesdeploymentdescriptoropenamopenamwebinfclassesamconfigpropertiescomiplanetamserverhostserver hostcomiplanetsecuritysslsocketfactoryimplcomsunidentitysharedldapfactoryjssesocketfactorycomsunidentitysmsms object class namecomsunidentitysmsms object classcomiplanetservicesconfigpathbase dircomiplanetamservermodetruecomiplanetamldapconnectionldaperrorcodesretries808191comiplanetamlocaleplatform localecomsunidentityurlconnectionusecachefalseopenssoprotocolhandlerpkgscomiplanetamserverprotocolserver protocomiplanetamserverportserver portcomiplanetservicesdebuglevelerrorcomsunembeddedreplicationportcomsunidentitycommonsystemtimerpoolsize3comsunidentityoverrideamctruecomsunembeddedsyncserversoncomiplanetamservicesecretencldapuserpasswdamencryptionpwdam enc keycomsunidentitysmenabledatastorenotificationdatastore notificationcomsunservicesdebugmergealloffcomiplanetamservicesdeploymentdescriptorserver uricomsunameventconnectionthisablelistthisable persistent searchagent 001confopenssoagentconfigurationproperties comsunidentityagentsconfigfiltermodemanagerj2ee policycomsunidentityagentsconfigfiltermodehostmanagerj2ee policycomsunidentityagentsconfigfiltermode allcomsunidentityagentsconfigusermappingmode user idcomsunidentityagentsconfiguserattributename employeenumbercomsunidentityagentsconfiguserprincipal falsecomsunidentityagentsconfigusertoken usertokencomsunidentityagentsconfigclientipheader comsunidentityagentsconfigclienthostnameheader comsunidentityagentsconfigloadinterval 0comsunidentityagentsconfiglocalelanguage encomsunidentityagentsconfiglocalecountry uscomsunidentityagentsconfigauditaccesstype log nonecomsunidentityagentsconfiglogthisposition remotecomsunidentityagentsconfigremotelogfile amagent org sso com 7070logcomsunidentityagentsconfiglocallogrotate falsecomsunidentityagentsconfiglocallogsize 52428800comsunidentityagentsconfigwebserviceenable falsecomsunidentityagentsconfigwebserviceendpoint0 comsunidentityagentsconfigwebserviceprocessgetenable truecomsunidentityagentsconfigwebserviceauthenticator comsunidentityagentsconfigwebserviceinternalerrorcontent wsinternalerrorcontenttxtcomsunidentityagentsconfigwebserviceautherrorcontent wsautherrorcontenttxtcomsunidentityagentsconfigwebserviceresponseprocessor comsunidentityagentsconfigaccessdenieduri comsunidentityagentsconfigloginform0 hostmanageramloginhtmlcomsunidentityagentsconfigloginform1 manageramloginhtmlcomsunidentityagentsconfigloginerroruri0 hostmanageramerrorhtmlcomsunidentityagentsconfigloginerroruri1 manageramerrorhtmlcomsunidentityagentsconfigloginuseinternal truecomsunidentityagentsconfiglogincontentfile formlogincontenttxtcomsunidentityagentsconfigauthhandler comsunidentityagentsconfiglogouthandler comsunidentityagentsconfigverificationhandler comsunidentityagentsconfighttpsessionbinding truecomsunidentityagentsconfigredirectparam gotocomsunidentityagentsconfigloginurl0 comsunidentityagentsconfiglogouturl0 comsunidentityagentsconfigloginurlprioritized truecomsunidentityagentsconfigloginurlprobeenabled truecomsunidentityagentsconfigloginurlprobetimeout 20comsunidentityagentsconfiglogouturlprioritized truecomsunidentityagentsconfiglogouturlprobeenabled truecomsunidentityagentsconfiglogouturlprobetimeout 20comsunidentityagentsconfigagenthost comsunidentityagentsconfigagentport comsunidentityagentsconfigagentprotocol comsunidentityagentsconfigloginattemptlimit 0comsunidentityagentsconfigamssocacheenable truecomsunidentityagentsconfigcookieresetenable falsecomsunidentityagentsconfigcookieresetname0 comsunidentityagentsconfigcookieresetdomain comsunidentityagentsconfigcookieresetpath comsunidentityagentsconfigcdssoenable falsecomsunidentityagentsconfigcdssoredirecturi agentappsunwcdssoredirecturicomsunidentityagentsconfigcdssocdcservleturl0 comsunidentityagentsconfigcdssoclockskew 0comsunidentityagentsconfigcdssotrustedidprovider0 comsunidentityagentsconfigcdssosecureenable falsecomsunidentityagentsconfiglogoutapplicationhandler comsunidentityagentsconfiglogouturi comsunidentityagentsconfiglogoutrequestparam comsunidentityagentsconfiglogoutintrospectenabled falsecomsunidentityagentsconfiglogoutentryuri comsunidentityagentsconfigfqdncheckenable truecomsunidentityagentsconfigfqdndefault orgssocomcomsunidentityagentsconfigfqdnmapping comsunidentityagentsconfiglegacysupportenable falsecomsunidentityagentsconfiglegacyuseragent0 mozilla47comsunidentityagentsconfiglegacyredirecturi agentappsunwlegacysupporturicomsunidentityagentsconfigresponseheader comsunidentityagentsconfigredirectattemptlimit 0comsunidentityagentsconfigportcheckenable falsecomsunidentityagentsconfigportcheckfile portcheckcontenttxtcomsunidentityagentsconfigportchecksetting7070 httpcomsunidentityagentsconfignotenforceduri0 comsunidentityagentsconfignotenforceduriinvert falsecomsunidentityagentsconfignotenforceduricacheenable truecomsunidentityagentsconfignotenforceduricachesize 10comsunidentityagentsconfignotenforcedrefreshsessionidletime falsecomsunidentityagentsconfignotenforcedip0 comsunidentityagentsconfignotenforcedipinvert falsecomsunidentityagentsconfignotenforcedipcacheenable truecomsunidentityagentsconfignotenforcedipcachesize 10comsunidentityagentsconfigattributecookieseparator comsunidentityagentsconfigattributedateformat e d m y hhmmss zcomsunidentityagentsconfigattributecookieencode truecomsunidentityagentsconfigprofileattributefetchmode nonecomsunidentityagentsconfigprofileattributemapping comsunidentityagentsconfigsessionattributefetchmode nonecomsunidentityagentsconfigsessionattributemapping comsunidentityagentsconfigresponseattributefetchmode nonecomsunidentityagentsconfigresponseattributemapping comsunidentityagentsconfigbypassprincipal0 comsunidentityagentsconfigdefaultprivilegedattribute0 authenticated userscomsunidentityagentsconfigprivilegedattributetype0 groupcomsunidentityagentsconfigprivilegedattributetype1 rolecomsunidentityagentsconfigprivilegedattributetolowercasegroup falsecomsunidentityagentsconfigprivilegedattributetolowercaserole falsecomsunidentityagentsconfigprivilegedsessionattribute0 comsunidentityagentsconfigprivilegedattributemappingenable truecomsunidentityagentsconfigprivilegedattributemapping comiplanetamcookienameiplanetdirectoryprocomiplanetamsessionclientpollingenablefalsecomiplanetamsessionclientpollingperiod180comiplanetsecurityencryptorcomiplanetservicesutiljceencryptioncomsunidentityidmremotenotificationenabledtruecomiplanetamsdkremotepollingtime1comsunidentitysmnotificationenabledtruecomsunidentitysmcachetime1comiplanetamserverprotocolhttpcomiplanetamserverhosttestopenamcomcomiplanetamserverport8080comsunidentityagentsnotificationenabledtruecomsunidentityagentspollinginterval3comsunidentitypolicyclientcachemodesubtreecomsunidentitypolicyclientbooleanactionvaluesiplanetamwebagentservicegetallowdenyiplanetamwebagentservicepostallowdenycomsunidentitypolicyclientresourcecomparatorsservicetypeiplanetamwebagentserviceclasscomsunidentitypolicypluginshttpurlresourcenamewildcarddelimitercasesensitivefalsecomsunidentitypolicyclientclockskew10comsunidentityagentsconfigpolicyenvgetparam0comsunidentityagentsconfigpolicyenvpostparam0comsunidentityagentsconfigpolicyenvjsessionparam0comsunidentityclientnotificationurlcomiplanetservicesdebuglevelerrorcomsunidentityagentsconfigignorepathinfo falseplease help me to solve this issuethanks in advance,['java'] +886661,static library and swift so i am working on an ios project in swift and i wanted to create a static library with some useful stuff in itmy problem is when i try to build my lib in xcode version 63 i have a build failed followed by applicationsxcodeappcontentsdevelopertoolchainsxcodedefaultxctoolchainusrbinlibtool unknown option character x in xlinkeri have never saw this and it is not my first static lib so i was thinking i may be linked to the fact that i am using exclusively swift classwhat do you guys think thank you in advance,"['ios', 'iphone']" +886682,how we can get android phones manufacturing date refurbished check by programmatically i am developing an app which is about showing android phones hardware and software information such as internal storage screen size imei rootes etci got stuck in getting some information such as manufacturing date refurbished check phone color headset connect counter charger connect counter and also some sensor health information such as infrared ant radio transmitteris there any way to get above all things informationi have find one application similar to my requirement below is that is app link which is available on playstore phone info asamsunga,['android'] +886710,how would that regular expression be i have an expression that follows some rulesthe character must be first and last characterthere can be zeroormore spaces inside there can be zeroormore inside there can be zeroormore words letters and numbers inside expressioniqpzsplpnkqnow i need another expression to replace all and in a string for test for example but only when they are not surrounded by the trick is that when or are surrounded by but these characters belong to a different pair of it should not passexample of results pass pass pass pass content here pass content here another content does not passnote that the first content has its and the second as well any or should not pass if its in between themi am not a pro with regular expressions so if you do not know how it would be any documentation or tutorial related would be of great help,['c#'] +886719,convert 21 equirectangular panorama to cube map i am currently working on a simple 3d panorama viewer for a website for mobile performance reasons i am using the threejs css3 renderer this requires a cube map split up into 6 single imagesi am recording the images on the iphone with the google photosphere app or similar apps that create 21 equirectangular panoramas i then resize and convert these to a cubemap with this website flashpreferrably i would like to do the conversion myself either on the fly in threejs if that is possible or in photoshop i found andrew hazeldens photoshop actions and they seem kind of close but no direct conversion is available is there a mathematical way to convert these or some sort of script that does it i would like to avoid going through a 3d app like blender if possiblemaybe this is a long shot but i thought i would ask i have okay experience with javascript but i am pretty new to threejs i am also hesitant to rely on the webgl functionality since it seems either slow or buggy on mobile devices support is also still spotty,['javascript'] +886813,check if entity is in list of mapped entities i have the following hibernate code which i believe should be working but it throws an errororgspringframeworkwebutilnestedservletexception request processing failed nested exception is orghibernateexceptionsqlgrammarexception error syntax error at or near position 503the relevant code is the followingoverridepublic listrepositorylink getrepositorylinksfinal dugauser user query query sessionfactorygetcurrentsession createqueryfrom repositorylink link where user in linkdugausers querysetparameteruser user return querylistwhere repositorylink is the followingentitytablename repository linkspublic class repositorylink id generatedvalue private integer id onetoone jointablename repository links github repositories joincolumns joincolumnname github repository id referencedcolumnname id inversejoincolumns joincolumnname repository link id referencedcolumnname id private githubrepository githubrepository onetomany jointablename repository links duga users joincolumns joincolumnname duga user id referencedcolumnname id inversejoincolumns joincolumnname repository link id referencedcolumnname id private listdugauser dugausers new arraylist public integer getid return id public githubrepository getgithubrepository return githubrepository public void setgithubrepositoryfinal githubrepository githubrepository thisgithubrepository githubrepository public listdugauser getdugausers return dugausers public void setdugausersfinal listdugauser dugausers thisdugausers dugausers i could probably get it working with some joins but i thought it would be nicer if i could get the in syntax to work why does not it work like this,['java'] +886880,reactnative push notifications parse i am currently working on a small app project to learn and try out reactnative on ios i have some experience with parse parsecom and would love to integreate parse in the new app currently i have no problems including parse js into reactnative i am able to log in with accounts etc now i need to send push notifications to a certain number of users not all userswhat i do not understand is how push notifications should work with reactnative and parse usually i would connect a device installation with a user id and then send a push to a certain number of users which means to the devices with the corresponding installation the reactnative guide does not mention anything like that and even though it gives the parse guide as a reference i fail to see how i should be able to send pushes via parse the guide leaves a lot of information to be desired too to what source do these listeners subscribe to from which server am i going to send notifications etcas i understand parse js is not able to read the current installation i hesitate to add parse ios to the project too this feels unnatural and should not be a required thing to do although it would allow me to read the current installation but still parse js is not able to register that installation in order to subscribe to push notificationsat this point i feel a little bit lost this piece of information tells me that it should be possible somehow i just cannot figure out how hope someone can help me with that some advice would be truely appreciated,['ios'] +887133,reviews in google api i am using below code to find google reviews for property what i am trying to do is i am fetching review for property then i will compare it with old review of that property which is in the db if it is greater than the systems property then it sends emailthis file is run for every houras a cron file and i enable the billing in google api so max limit is 150 but for some reason api does not return the exact count of reviews for examplei run this file for the one property which has 4 reviews but api returns 0 for 2 or 3 times then after some time it returns 4 reviewsi do not know the reason behind it i also noticed that we can see the reviews on google search page and in google same you can write reviews in multiple places like in google and in google mapand to check reviews i am using google plus url so is it possible that the review does exist but in another arealike in google search page but not in google call api to get review count of google url params array placeid google place id key google api keyurl http build queryparamsresjson file get contentsurlmsg resjsonyiilogmsginfo applicationresjson json decoderesjsontruereview count resjsonresultuser ratings total 0 resjsonresultuser ratings total if review is greater than 0 then check old review and if it is not same then send email ifreview count0 ifsizeofressql0 if google plus review is greater then systems google review then send email ifreview counttrimressql0google plus review thissend googleplusmailprop id msg google review for property id mail sentprop id new reviewreview count old review ressql0google plus review yiilogmsginfo application sql insert into tbl review alert propertyid google plus review values sqlprop idreview countsql on duplicate key update propertyid prop idgoogle plus review review countthisinsert reviewsqlmy question is1 is it possible that the review does exist but in another arealike in google search page but not in google if yes then in this case can i obtain the url where review is posted2 are all of the reviews are sync in google3 or i am doing something wrong in my code,['php'] +887149,making an object x such that x in x returns false if we make a pathological potato like this class potato def eq self other return false def hash self return randomrandint1 10 p potato p pfalsewe can break sets and dicts this way note it is the same even if eq returns true it is mucking with the hash that broke them p in pfalse p in p 0falsealso lenp 0 p 0 2 and p 0p raises keyerror basically all mapping related stuff goes out the window as expected but what i did not expect is that we cannot break lists p in ptruewhy is that it seems that list contains iterates but it is first checking identity before checking equality since it is not the case that identity implies equality see for example nan object what is the reason for lists shortcircuiting on identity comparisons,['python'] +887161,use index and match on another fulltext index gives error cannot find fulltext index matching the column list working now on a vbulletin board which runs on mysql 5621 with innodb table engine there is a default query in vbulletin which uses index hint on one column and the same time uses fulltext index on another two columns the query looks likeselect postid postdateline from post as post use index threadid inner join thread as thread onthreadthreadid postthreadid where matchposttitle postpagetext against atlantic blue tang in boolean mode and threadthreadid 170467this gives error1191 cannot find fulltext index matching the column listremoving use index resolves the problemthis was not happening on myisam implementation of fulltext index for sure as this is the default query on vbulletin and it runs fine on all boardsis it possible this is some configuration for innodb that causes this issue we do not have control over the query itself so looking for a way to resolve the issue on server configuration leveledit included show create table postcreate table post postid int10 unsigned not null auto increment threadid int10 unsigned not null default 0 parentid int10 unsigned not null default 0 username varchar100 not null default userid int10 unsigned not null default 0 title varchar250 not null default dateline int10 unsigned not null default 0 lastedit int10 unsigned not null default 0 pagetext longtext not null allowsmilie smallint6 not null default 0 showsignature smallint6 not null default 0 ipaddress varchar15 not null default iconid smallint5 unsigned not null default 0 visible smallint6 not null default 0 attach smallint5 unsigned not null default 0 infraction smallint5 unsigned not null default 0 reportthreadid int10 unsigned not null default 0 primary key postid key userid userid key threadid threadiduserid key dateline dateline fulltext key title titlepagetext engineinnodb auto increment1634030 default charsetutf8,['mysql'] +887183,installing tizen in windows 7 i am trying to install tizen wearable sdk in windows 7 64bit i have donwload the exe however when i am trying to isntall it i am getting the following errorerror cannot execute java even if it was installed check environment variable or java versionover 16 pleasei have installed in my computer java 170 80 i have put to the path of the system cprogram filesjavajre7bin and in java home cprogram filesjavajdk170 80i have tried to follow the instructions from here here however i did not mange to solve my issuesedit i followed the instructions from that link i went to cdusersappdatalocaltemp and i run from there the command in console java jar installmanagerjar the installation began normally however during the installation i got several errors,['java'] +887218,uploading files with flowjs ngflow to webapi 2 i am trying to use flowjs via its angular wrapper to upload files to an aspnet webapi 2 server anyway when i select a file to upload my webapi just gets the first chunk get request and then nothing happens no post is done and it seems that flowjs did not start the uploadthe initial get fired when i select a file isget httplocalhost49330apiuploadflowchunknumber1flowchunksize1048576flowcurrentchunksize4751flowtotalsize4751flowidentifier4751elmahmysqlsqlflowfilenameelmahmysqlsqlflowrelativepathelmahmysqlsqlflowtotalchunks1 http11host localhost49330connection keepaliveuseragent mozilla50 windows nt 63 wow64 applewebkit53736 khtml like gecko chrome420231190 safari53736accept referer httplocalhost49330acceptencoding gzip deflate sdchacceptlanguage enusenq08itq06and the response ishttp11 202 acceptedcachecontrol nocachepragma nocacheexpires 1server microsoftiis80xaspnetversion 4030319xsourcefiles utf8bqzpcuhjvamvjdhncndvixfrlc3rcvxbuzxn0xfvwvgvzdfxhcglcdxbsb2fkxpoweredby aspnetdate fri 17 apr 2015 080256 gmtcontentlength 0then no more requests are issuedas it seems there is no uptodate webapi example but only scattered posts i created for newbies like me a dummy repro solution you can download from it is an aspnet webapi 2 solution where i placed the upload code in the home view after adding the corresponding api controller just hit f5 and try uploading a file you can find the api controller in uploadcontrollercsthe relevant code parts area client side a page similar to the quickstart example of the ngflow pagediv classrow div classcolmd12 div flowinittarget apiupload flowfilessubmittedflowupload flowfilesuccessfilemsg message input typefile flowbtn ol li ngrepeatfile in flowfilesfilename filemsgli ol div divdivthe corresponding code is essentially an empty ts skeleton with the module initializationmodule up export interface imainscope export class maincontroller public static inject scope constructorprivate scope imainscope var app angularmoduleapp flow appcontrollermaincontroller maincontrollerb server side i added some bunding for the required scripts and the following controller modified from the sample code i found at how to upload file in chunks in aspnet using ngflow note that in the get upload method i changed the signature using a binding model otherwise we would get a 404 as the route was not matched and when the chunk is not found i return a 202 accepted code rather than 404 as flowjs documentation says that 200 corresponds to the chunk was accepted and correct no need to reupload while a 404 cancels the entire upload and any other code like 202 here tells the uploader to retryrouteprefixapipublic class uploadcontroller apicontroller private readonly string sroot public uploadcontroller sroot hostingenvironmentmappathapp datauploads routeupload acceptverbsget public ihttpactionresult uploadfromuri uploadbindingmodel model if ischunkheremodelflowchunknumber modelflowidentifier return ok return responsemessagenew httpresponsemessagehttpstatuscodeaccepted routeupload acceptverbspost public async taskihttpactionresult upload ensure that the request contains multipartformdata if requestcontentismimemultipartcontent throw new httpresponseexceptionhttpstatuscodeunsupportedmediatype if directoryexists sroot directorycreatedirectory sroot multipartformdatastreamprovider provider new multipartformdatastreamprovider sroot try await requestcontentreadasmultipartasyncprovider int nchunknumber converttoint32providerformdataflowchunknumber int ntotalchunks converttoint32providerformdataflowtotalchunks string sidentifier providerformdataflowidentifier string sfilename providerformdataflowfilename rename the generated file multipartfiledata chunk providerfiledata0 only one file in multipart message renamechunkchunk nchunknumber sidentifier assemble chunks into single file if they are all here tryassemblefilesidentifier ntotalchunks sfilename return ok catch exception ex return internalservererrorex private string getchunkfilenameint chunknumber string identifier return pathcombine sroot stringformatcultureinfoinvariantculture 0 1 identifier chunknumber private void renamechunkmultipartfiledata chunk int chunknumber string identifier string sgeneratedfilename chunklocalfilename string schunkfilename getchunkfilenamechunknumber identifier if fileexistsschunkfilename filedeleteschunkfilename filemovesgeneratedfilename schunkfilename private string getfilenamestring identifier return pathcombine sroot identifier private bool ischunkhereint chunknumber string identifier string sfilename getchunkfilenamechunknumber identifier return fileexistssfilename private bool areallchunksherestring identifier int totalchunks for int nchunknumber 1 nchunknumber totalchunks nchunknumber if ischunkherenchunknumber identifier return false return true private void tryassemblefilestring identifier int totalchunks string filename if areallchunkshereidentifier totalchunks return create a single file string sconsolidatedfilename getfilenameidentifier using stream deststream filecreatesconsolidatedfilename 150 for int nchunknumber 1 nchunknumber totalchunks nchunknumber string schunkfilename getchunkfilenamenchunknumber identifier using stream sourcestream fileopenreadschunkfilename sourcestreamcopytodeststream efor deststreamclose rename consolidated with original name of upload strip to filename if directory is specified avoid crossdirectory attack filename pathgetfilenamefilename debugassertfilename null string srealfilename pathcombine sroot filename if fileexistsfilename filedeletesrealfilename filemovesconsolidatedfilename srealfilename delete chunk files for int nchunknumber 1 nchunknumber totalchunks nchunknumber string schunkfilename getchunkfilenamenchunknumber identifier filedeleteschunkfilename efor,['javascript'] +887237,find the number of strings in 2d array of strings given an array of strings i need to find out the number of strings in iti followed thisbut this does not work if i am passing this into a functionheres the code i triedincludestringincludeiostreamincludecstdioincludecstringusing namespace stdint f1char input1 string s coutsizeofinput1endl print 4 coutsizeofcharendl print 4 int lsizeofinput1 sizeofchar giving l1 here but should be 8int main char str2babasfdfvffbfebgergrgafvdfvfvwekkhhffl int lsizeofstr2 sizeofchar coutlendl print 8 coutsizeofstr2endl print 32 coutsizeofcharendl print 4 f1str2,['c++'] +887265,parse login hang since facebook 40x with pffacebookutils initializefacebookwithapplicationlaunchoptionslaunchoptions semaphore wait slow trap since updating facebook to v40x and the latest parse libraries my app is hanging seemingly when trying to log in the user my stack trace looks like this i had a very similar problem previously answered here parse crash when calling pffacebookutils initializefacebook semaphore wait trap however that solution no longer works since it seems pfuser currentuser has been replaced with pfuserprivate getcurrentuserwithoptions and bftaskprivate waitforresultwithmainthreadwarning where it gets stuckin my app i have subclassed pfuser to a class called mpluser and overridden the user method not sure if this might be something to do with the issue mpluser user return mpluser pfuser useronce this starts occurring it becomes impossible to launch the app however i usually manage to launch the app a few times before the lock starts happening it usually happens after a crashi am using pod parsefacebookutilsv4 and have updates all libraries to latest versions update heres more stack trace from another thread that is seemingly trying to log on i initialise parse and facebook in the following order if i reverse the calls it crashes boolapplicationuiapplication application didfinishlaunchingwithoptionsnsdictionary launchoptions self initdefaults self initialiseapplicationspecifics self setupparsewithoptionslaunchoptions self enablecrashreporting self setupiaps etc voidinitialiseapplicationspecifics flurry setcrashreportingenabledyes self registerparsesubclasses parsecrashreporting enable parse enablelocaldatastoreifdef mpl parse setapplicationidxy clientkeyxy flurry startsessionxyelif mgm parse setapplicationidyx clientkeyx flurry startsessionyxendif voidsetupparsewithoptionsnsdictionary launchoptions pffacebookutils initializefacebookwithapplicationlaunchoptionslaunchoptions pftwitterutils initializewithconsumerkeyab consumersecretba pfanalytics trackappopenedwithlaunchoptionslaunchoptions,['objective-c'] +887285,sqoop import passwordfile function not working properly in sqoop 144 i am using hadoop121 and sqoop version is 144i am trying to run the following querysqoop import connect jdbcmysqlip3306database name table clients targetdir dataclients username root passwordfile sqooppassword m 1sqooppassword is a file which is kept on hdfs in path sqooppassword with permission 400 it is giving me an erroraccess denied for user rootip using password yescan anyone provide solution for this thanks in advance,['mysql'] +887416,why is mocking with di better than mocking objects in objectivec this blog article says thatwhile there are sometimes sensible ways to mock out objects without di typically by mocking out class methods as seen in the ocmock example above itas often flat out not possible even when it is possible the complexity of the test setup might outweigh the benefits if youare using dependency injection consistently youall find writing tests using stubs and mocks will be much easierbut it does not explain why what are possible scenarios where di injecting an id object conforming to protocol will serve better for mocking in objectivec than simple ocmockitogivenmockarray objectatindex0 willreturnfirst verifycountmockarray times1 objectatindex,"['ios', 'objective-c']" +887446,custom service exceptions are being thrown as axisfault we have an axis2 client reading from a soap web service an issue occurred when new client stub classes were generated using wsdl2java and their packages were renamed the generation tool itself is not causing the issue but wsdl2java is not renaming packages for all classes so i am having to do this myselfany idea about the best way to rename packages for these classes without having issues such as doing a string replacement in a smart way the web service throws business exceptions in some cases and they are caught directly by the calling code however this is not happening anymore and instead of specialexception the client now catches axisfaultyou can see the xml response belowxml version10 encodingutf8soapenvenvelope xmlnssoapenv soapenvbody soapenvfault faultcodesoapenvserverfaultcode faultstringexception message due to business errorfaultstring detail ns2specialexception xmlnsns2 ns2code7ns2code ns2messageexception message due to business errorns2message ns2specialexception detail soapenvfault soapenvbodysoapenvenvelopechecking this in more detail the difference are probably due to method populatefaults in the generated blaservicestub class where class names are set as strings for later use through reflection,['java'] +887482,implicitly constructed variables in c i am getting to grips with c and there is one language feature i am having particular trouble getting my head aroundi am used to declaring and initialising a variable explicitly but in c we sometimes seem to declare and implicitly construct a variablefor example in this snippet rdev seems to be implicitly constructed as it is subsequently used to construct a default random enginerandom device rdevdefault random engine genrdevcan someone explain whats going on here how can i tell this apart from a simple declaration such as int myint,['c++'] +887514,dagger 2 and android studio working but cannot see generated classes i am trying to use dagger 2 in an android studio project i have used the coffeemaker example i have managed to make the app build and working however i do not success in seeing the generated code if i debug i cannot see it neither moreover daggercoffeeapp coffee as marked as reed cannot resolve symbolmy gradle files are toplevel build file where you can add configuration options common to all subprojectsmodulesbuildscript repositories jcenter dependencies classpath comandroidtoolsbuildgradle113 note do not place your application dependencies here they belong in the individual module buildgradle files allprojects repositories jcenter andapply plugin comandroidapplicationandroid compilesdkversion 22 buildtoolsversion 2112 defaultconfig applicationid commateuyabarandroiddagger2test minsdkversion 22 targetsdkversion 22 versioncode 1 versionname 10 buildtypes release minifyenabled false proguardfiles getdefaultproguardfileproguardandroidtxt proguardrulespro lintoptions abortonerror false ignoring some references from daggercompiler dependencies compile filetreedir libs include jar compile comandroidsupportappcompatv72200 compile javaxinjectjavaxinject1 compile javaxannotationjavaxannotationapi12 compile comgoogledaggerdagger20 provided comgoogledaggerdaggercompiler20 provided orgglassfishjavaxannotation100b28thanks,['android'] +887521,asyncio event loop per python process aioprocessing multiple event loops i have two processes a main process and a subprocess the main process is running an asyncio event loop and starts the subprocess i want to start another asyncio event loop in the subprocess i am using the aioprocessing module to launch the subprocessthe subprocess function isdef subprocess code loop asyncioget event loop asynciocoroutine def f for i in range10 printi yield from asynciosleep1 looprun until completefbut i get an error looprun until completef file usrlibpython34asynciobase eventspy line 271 in run until complete selfrun forever file usrlibpython34asynciobase eventspy line 239 in run forever raise runtimeerrorevent loop is runningruntimeerror event loop is runningis it possible to start a new or restart the existing asyncio event loop in the subprocess if so how,['python'] +887568,reading a progressively encoded 90x90 jpeg in java takes 1 minute when using javaximageioimageio to load a largeresolution 90x90 jpeg from thisk it takes more than 1 minute in my scala application i tried creating a javaonly project but it still takes too long around 30 secondsthis is how i load the imagefile file new fileusersthe21stslow2jpgbufferedimage image imageioreadfileis there any way to improve performance on reading progressively encoded largeres jpegs in javathe image in question is this one moderators please do not reupload to other hosting site again so that encoding quality does not change,['java'] +887689,why parallel stream get collected sequentially in java 8 why foreach prints numbers in random order while collect always collects elements in original order even from parallel streaminteger intarray 1 2 3 4 5 6 7 8listinteger listofintegers new arraylistarraysaslistintarraysystemoutprintlnparallel stream listofintegers stream parallel foreache systemoutprinte systemoutprintln collectors listinteger l listofintegers stream parallel collectcollectorstolistsystemoutprintlnloutputparallel stream 8 1 6 2 7 4 5 3 1 2 3 4 5 6 7 8,['java'] +887694,loading multiple youtube videos iframe api i am having an issue with the following code but i am not sure where the problem ison my master page in javascript i have an array defined to hold a list of youtubeplayer objects that i create i also load the youtube api herei also have sometime several youtube user controls that contains the youtube div in a bootstrap modal it also contains a javascript for pushing a new youtubeplayer object to the array in the master page js lastly on the user control i define methods for autostarting and stopping the video on the shown and hide events of the bootstrap modalfinally to hopefully solve the race condition between the document being loaded and the youtube api being loaded i set two bool variables one for document one for api and check both for true before calling an initvideos function which iterates through the array of youtubeplayer objects and initializes them setting the ytplayer object in the window part of the issue i think is that i cannot statically set windowplayer1 etc because i never know how many youtube user controls will be loadedthe problem is whenever the bootstrap modal events fire the ytplayer object i retrieve from the window does not contain the methods for playvideo and pausevideoon my master pagedocumentreadyfunction windowdocready true if windowapiready initvideosfunction onyoutubeiframeapiready windowapiready true if windowdocready initvideos initvideosfunction initvideos if typeof ytplayerlist undefined return for var i 0 i ytplayerlistlength i var player ytplayerlisti var pl new ytplayerplayerdivid playervars autoplay 0 controls 1 autohide 2 modestbranding 1 playsinline 1 rel 0 wmode opaque videoid playervideoid events onstatechange playerstatechangehandler windowplayerid pl and on the user controlwindowytplayerlistpush id clientidplayer divid clientidplayer videoid videoid statechangehandler hideclientidplayerfunction hideclientid playerstate if statedata 0 hideclientid video function showclientid video clientid videomodalmodalshowfunction hideclientid video clientid videomodalmodalhidedocumentreadyfunction clientidvideoclickfunction showclientidvideo clientid videomodalonshown function windowclientidplayerplayvideo clientid videomodalonhide function windowclientidplayerpausevideo this may be a lack of js expertise but i am absolutely stuck any help would be greatly appreciated also for reference the exception i get is uncaught typeerror windowctl100 phcontent ctl100playerplayvideo is not a function,['javascript'] +887802,an extra parentheses in a call to a nested function in python i am studying the module of mark pilgrims dive into python book in chapter 6 and i am kind of stuck with what this line of code return getfileinfoclassff for f in filelist does getfileinfo is a nested function and i was wondering whats the duplicate f the extra parentheses is for i was hoping someone can help me out heres the complete functiondef listdirectorydirectory fileextlist get list of file info objects for files of particular extensions filelist ospathnormcasef for f in oslistdirdirectory filelist ospathjoindirectory f for f in filelist if ospathsplitextf1 in fileextlist def getfileinfoclassfilename modulesysmodulesfileinfo module get file info class from filename extension subclass sfileinfo ospathsplitextfilename1upper1 return hasattrmodule subclass and getattrmodule subclass or fileinfo return getfileinfoclassff for f in filelist,['python'] +887891,google play services v23 proguard configuration after upgrading to google play services v23 i see this message when trying to export signed application in eclipseproguard returned with error code 1 see consolewarning comgoogleandroidgmscommongoogleplayservicesutil cannot find referenced class androidcontentpmpackageinstallerwarning comgoogleandroidgmscommongoogleplayservicesutil cannot find referenced class androidcontentpmpackageinstallersessioninfowarning comgoogleandroidgmscommongoogleplayservicesutil cannot find referenced class androidcontentpmpackageinstallerwarning comgoogleandroidgmscommongoogleplayservicesutil cannot find referenced class androidcontentpmpackageinstallersessioninfowarning comgoogleandroidgmscommongoogleplayservicesutil cannot find referenced method androidcontentpmpackageinstaller getpackageinstaller in class androidcontentpmpackagemanagerwarning comgoogleandroidgmsinternalzzif cannot find referenced method void setmixedcontentmodeint in class androidwebkitwebsettings you should check if you need to specify additional program jarswarning there were 4 unresolved references to classes or interfaces you may need to specify additional library jars using libraryjarswarning there were 2 unresolved references to program class members your input classes appear to be inconsistent you may need to recompile them and try again alternatively you may have to specify the option dontskipnonpubliclibraryclassmembersjavaioioexception please correct the above warnings first at proguardinitializerexecuteinitializerjava321 at proguardproguardinitializeproguardjava211 at proguardproguardexecuteproguardjava86 at proguardproguardmainproguardjava492i added this as specified in documentationkeep class extends javautillistresourcebundle protected object getcontentskeep public class comgoogleandroidgmscommoninternalsafeparcelsafeparcelable public static final nullkeepnames comgoogleandroidgmscommonannotationkeepname class keepclassmembernames class comgoogleandroidgmscommonannotationkeepname keepnames class implements androidosparcelable public static final creatorand tried adding keep class androidcontentpmpackageinstallerto proguardprojecttxt but this didnt helpwhat am i missing,['android'] +887909,youtubeplayer not load ad video with cuevideo i am using youtubeplayer to play youtube video and use cuevideovideoid to load video which is working fine if video not contain ad but video contain ad then cuevideovideoid will not load videoalso seen some thiscussion regards such problem which are suggested use loadvideovideoid instead of cuevideovideoid but as per my requirement i shown image until video not buffer and when video buffered hide image and show youtubeplayer so have to use cuevideovideoid instead of loadvideovideoiddoes any one having such issue thanks in advance for any suggestion or helpbelow is my code to load video youtubeplayercuevideovideoid,['android'] +887947,when should i compare an optional value to nil quite often you need to write code such as the followingif someoptional nil do something with the unwrapped someoptional eg somefunctionsomeoptionalthis seems a bit verbose and also i hear that using the force unwrap operator can be unsafe and best avoided is there a better way to handle this,['ios'] +887949,how to auto stretch detail band when print order is set to horizontal in jasperreport i have a main report which is printed horizontally it has 5 columnson every column i want to put a sub report so i created thisand the subreport just like thisthe problem is when i run i get the following exceptionnetsfjasperreportsenginejrruntimeexception subreport overflowed on a band that does not support overflowlooks like jasper reports cannot stretch the detail band vertically when there is a subreport in it and the print order is set to horizontalwhat can i do to avoid this error and achieve what i want,['java'] +887967,whats the purpose of function with only unspecified number of parameters in other words when function declared like this with t being some typealiast will be ever usefulif you do not know such declaration specifies a function with unknown number of parameters it is allowed by the c standard but it does not provide us with a standard way of accessing passed arguments there is cstdarg library but it require named parameter before the ellipsis in order to work it look like this with another typealias named t1t t1 normally t1 is of type int and sepcifies the number of variadic argumentshowever the fact that the ellipsis can be the only function parameter means that such construct have some purpose and i am curios what is itan actual example of such function will look like thisvoid func,['c++'] +888076,contextnotactiveexception while calling asynchronous method of stateless bean i am injecting a stateless bean in a asynchronous servlet and calling asynchronous method from the serrvlet in the server logs of the jboss i am not able to see any of the exception but whhile starting the java mission control flight recorder i can see contextnotactiveexcetion whenever servlet makes a call to the asyncrhonous methodservlet webservleturlpatterns asyncservice asyncsupported truepublic class asyncserviceservlet extends httpservlet injectprivate service serviceprotected void dopostfinal httpservletrequest request final httpservletresponse response throws servletexception ioexception final asynccontext asynccontext requeststartasyncrequest response asynccontextstartnew runnable override public void run try serviceserviceasynccontext catch contextnotactiveexception ioexception e eprintstacktrace service class statelesspublic class service asynchronouspublic void servicefinal asynccontext asynccontext throws ioexception httpservletresponse res httpservletresponse asynccontextgetresponse ressetstatus200 asynccontextcomplete the stack trace i can see in the flight recorder javalangthrowableinit 4 javalangexceptioninit 4 javalangruntimeexceptioninit 4 javaxenterprisecontextcontextexceptioninit 4 javaxenterprisecontextcontextnotactiveexceptioninit 4 orgjbossweldcontextcontextnotactiveexceptioninitenumobject 4 orgjbossweldmanagerbeanmanagerimplgetcontextclass 4 orgjbossasweldejbejbrequestscopeactivationinterceptorprocessinvocationinterceptorcontext 4 orgjbossinvocationinterceptorcontextproceed 4 orgjbossinvocationinitialinterceptorprocessinvocationinterceptorcontext 4 orgjbossinvocationinterceptorcontextproceed 4 orgjbossinvocationchainedinterceptorprocessinvocationinterceptorcontext 4 orgjbossaseecomponentinterceptorscomponentthispatcherinterceptorprocessinvocationinterceptorcontext 4 orgjbossinvocationinterceptorcontextproceed 4 orgjbossasejb3componentpoolpooledinstanceinterceptorprocessinvocationinterceptorcontext 4 orgjbossinvocationinterceptorcontextproceed 4 orgjbossasejb3txcmttxinterceptorinvokeinourtxinterceptorcontexttransactionmanagerejbcomponent 4 orgjbossasejb3txcmttxinterceptorrequiredinterceptorcontextejbcomponentint 4 orgjbossasejb3txcmttxinterceptorprocessinvocationinterceptorcontexti have been going through many posts but still the issue remain the same please help me out,['java'] +888116,import modules from files in directory with es6 i can import several exports from a file like thisimport thinga thingb thingc from libthingshowever i like the organization of having one module per file i end up with imports like thisimport thinga from libthingsthingaimport thingb from libthingsthingbimport thingc from libthingsthingci would love to be able to do thisimport thinga thingb thingc from libthingsor something similar with the understood convention that each file contains one default export and each module is named the same as its fileis this possible,['javascript'] +888167,how to open a webview inside a frame in ionic what i need is to load html code inside a frame in a page in an ionic app without opening a new window or covering the rest of the pagethe idea is to have a frame that opens a web page without covering or thisrupting the rest of the page like the header buttons etcbasically what i want to do is the equivalent to an android webview in an ionic framework appis this possiblethere is no much code is a simple message details page for a messaging app is just that the messages have to be thisplayed as a web pageionview viewtitledetalles de mensaje classthiscoverpage ionnavbuttons sideright button classbutton buttonicon icon ionnaviconround ngclickopenpopoverevent button ionnavbuttons ionnavbuttons sideleft button classbutton buttonicon icon ionios7arrowback ngclickgoback button ionnavbuttons ioncontent scrollfalse ioncontentionviewi need to show the header with the top buttons and the webview below them,['javascript'] +888217,jquery search filter show the list item header i have following listul idfromlist li classheaderabcli li classitem123li li classitem258li li classitem189li li classitem545li li classheadercdeli li classitem789li li classitem215li li classitem897li li classitem9li li classheaderefgli li classitem701li li classitem566li li classitem511li ulwhen searching the item it should show the list item headerfor example when i am searching 9it should show abc 189cde 789 897 9now i am getting search list onlyfunction filterelement var value elementval fromlist lieachfunction if thistextsearchnew regexpvalue i 1 thisshow else thishide script srcscriptinput typetext idtxtlist onkeyupfilterthis ul idfromlist li classheaderabcli li classitem123li li classitem258li li classitem189li li classitem545li li classheadercdeli li classitem789li li classitem215li li classitem897li li classitem9li li classheadereli li classitem701li li classitem566li li classitem511liul,"['javascript', 'jquery']" +888234,c implementing fast push of many elements to the end of array i have a simple struct to hold an arraystruct array of a type size t allocated size size t elements 1index based a type arrayi want to write a simple function something like thisbool simple functionstruct array of a type my array int a int b int c int d a type new chunk a b ab d c c c cd bd a ac bc cd cd c size t size sizeofnew chunk sizeofa type return push to arraymy array new chunk sizethe my array is a static global variable below is an implementation of push to arraystatic bool push to arraystruct array of a type a a type new chunk size t size const size t new size aelements size const size t old size aelements if new size aallocated size the allocated size is most of the time big enough iave stripped this part of code to minimum a type tmp reallocaarray new size sizeofa type if tmp return true else aarray tmp aallocated size new size aelements new size memcpyaarray old size new chunk size sizeofa type return falsemy questionhow can i rewrite asimple functiona to make more compilers generate code that will write directly to the destination i would like the code to stay quite short and flexiblemy code works unfortunately the gcc and an old clang create temporary data on the stack and then copy it to destination below if a fragment of generated x86 64 assemblermovq 8rsp rdxmovq rdx 8raxmovq 16rsp rdxmovq rdx 16raxmovq 24rsp rdxmovq rdx 24raxmovq 32rsp rdxmovq rdx 32raxfor amd the assembler have thisrep movsqthe new clang works fine i have compiled with o3i have tried with code that added one element a time there was a lot of conditional jumps to call realloc unfortunately,['c'] +888352,how would i make this java 7 compatible i have an interface that basically looks like thispublic interface isettingt public t getdefault public t value public void sett value public string getname public default string getvaluename object obj value if obj instanceof boolean return booleanobj yes no return objtostring and then in another class i have a list of isettingprivate listisetting settings arraysaslist new classmode new endmode new playerlives new joinmidgame new scoreboardthisplay new lifeperkill new explosivebullets new reloadtimeand this all works perfectly however the platform where i use my code does not support java 8 so i have to use java 7 and heres where the problems comeif i set the maven target to 17 like this in my pomxmlconfiguration source18source target17targetconfigurationthen the code compiles perfectly with no errors or anything however when i try to run the code it gives me this errorjavalangclassformaterror method getvaluename in class netuniqraftmurdermatchsettingsisetting has illegal modifiers 0x1i tried to google it but could not find anything that i understood or seemed to be applicable in my caseso i thought i will just make the entire codebase into java 7configuration source17source target17targetconfigurationthe first error i see isdefault methods are allowed only at source level 18 or abovewhich is incredibly annoying and i do not know how to bypass that a lot of my code is dependent on default implementations i guess i just have to use abstract classes insteadbut the more problematic error i see is on the listsetting i havetype mismatch cannot convert from listisetting extends objectcomparableserializable to listisettingi have no idea what that means or how to fix it the quickfix eclipse offers are of no helpin case the you need to see the full nonstripped isetting class or the full stacktrace i put them externally as they are rather spaceyisettingjava stacktrace,['java'] +888374,errors with setting up an ionic app i have just started to get my hands on the ionic framework to code my first android app i can set up the project but when i want to add the android platform via ionic platform add it says error reading config file error enoent open dprojectsandroid2configxmlerror happened undefinedwhen i want to build the app via ionic build android it sayscurrent working directory is not a cordovabased projectwhen i run the fix from the ionic faq cordova create it saysat least the dir must be provided to create new project see cordova helpdoes anyone know why this errors happenedit tried on multiple computer windows 7 64 got the same error,['android'] +888399,php type hinting difference between closure and callable i noticed that i can use either of closure or callable as type hint if we expected some callback function to run for examplefunction callfunc1closure closure closurefunction callfunc2callable callback callbackfunction function echo hello worldcallfunc1function hello worldcallfunc2function hello worldquestionwhats the difference here in other words when to use closure and when to use callable or they serve the same purpose,['php'] +888497,placepicker does not pick up material theme i am using a placepicker library from google play services which starts up a new activity the new activitypicker has a toolbar actionbar which is not styled by default placepicker documentation states thatif you set custom colors in your application using the material theme the place picker inherits the colorprimary and colorprimarydark attributes from the themei have a theme in my stylexml filestyle nameapptheme parentthemeappcompatlight item namecolorprimary5665bbitem item nameandroidcolorprimary5665bbitem item namecolorprimarydark41456bitem item nameandroidcolorprimarydark41456bitemstyleand i have set the theme to be used in my android manifesto fileapplication androidallowbackuptrue androidicondrawableic launcher androidlabelstringapp name androidthemestyleapptheme the placepicker is created by the following codetry placepickerintentbuilder intentbuilder new placepickerintentbuilder intent intent intentbuilderbuildmainthis start the intent by requesting a result identified by a request code startactivityforresultintent request place picker catch googleplayservicesrepairableexception googleplayservicesnotavailableexception e loge error with google play libhowever the toolbar does not get styled as before it has a white background and black textit is interesting to note that my own toolbar actionbar does get styledhow do i force the placepicker activity to adopt my theme,['android'] +888541,python numpy keep a list of indices of a sorted 2d array i have a 2d numpy array and i want to create a new 1d array where it is indices of numbers in the first array if they are sorted in an ascending order for the following arraya 102 030i want this to be likeb 1102011012any idea how it can be done in python using predefined functionsthanks,['python'] +888606,jersey parsing java 8 date time this is my user class and i to save iso compliant date time in my databasepublic class user id private string id private string email datetimeformatiso datetimeformatisodate time private localdatetime logindate here is my jersey controllerpostconsumesapplicationjsonproducesapplicationjsonpublic response create user user mapobject object apiresponse new hashmapobject object mapobject object response new hashmapobject object user user userservicecreateuserhow can can i consume a datetime format like this one in jersey is it possible to send a datatime string and create java 8 date time object automatically email logindate 20150417t060651465z update i was using spring boot jersey and had other jsr packages dependency groupidorgspringframeworkbootgroupid artifactidspringbootstarterjerseyartifactid dependencyso i removed all the packages except from springbootjersey package use this annotation for localdatetime jsondeserializeusing localdatetimedeserializerclassthis way i can consume isodate and save isodate to mongodb and produce full formated mongodb localdatetime to frontend problem solved,['java'] +888659,toolbar overlapping below status bar i want to have appcompat v21 toolbar in my activity but the toolbar i am implementing is overlapping below status bar how can i fix ithere is the activity layout xmllinearlayout xmlnsandroid androidlayout widthfill parent androidlayout heightwrap content androidorientationvertical include androidididtoolbar layoutlayouttoolbar framelayout androidididcontainer androidlayout widthfill parent androidlayout height0dp androidlayout weight1 linearlayouttoolbar viewxml version10 encodingutf8androidsupportv7widgettoolbar xmlnsandroid androidididtoolbar androidlayout widthmatch parent androidlayout heightwrap content androidminheightattractionbarsize androidbackgroundattrcolorprimary theme stylestyle nameapptheme parentmaterialnavigationdrawerthemelightdarkactionbar item namecolorprimarycolorprimaryitem item namecolorprimarydarkcolorprimary darkitem item namecoloraccentcoloraccentitemstyle,['android'] +888737,what does this javascript snippet does start of jquery migration file i have found this piece of code in jquery migrate v1jquerymigratemutevoid 0jquerymigratemute0functionetn anything and i really wonder about 2 things1 what does void 0 mean2 why these conditions are followed by a comma my tests showed me it will always get executedits just not i really need to knowbut i am really interested because i thought i knew everything about js,"['javascript', 'jquery']" +888750,uifont fontwithname return nil this code return me nil in fonti add the open sans ttf file to project folderwhat am i missinguifont font uifont fontwithnameopensansbold sizefontsize if font str addattributensfontattributename valueuifont fontwithnamefont sizefontsize rangensmakerangelocation length labelattributedtext str,['objective-c'] +888761,universal 2d game assets and absolute node positioning i have a question regarding universal game assets and absolute positioning of a sknodes in sprite kit ios 8i will try to present my problem through an example as followsimagine a 2d top down game with a skspritenode which represents a house a house has multiple child skspritenodes which represent chairs desk sofa etci have 3 versions of house asset1x 200 x 200px nonretina ipads2x 400 x 400px retina iphones and ipads3x 600 x 600px iphone 6 plusimportantchild nodes chairs desk etc positions are defined in a plist file something like this json representationchildren position 2020 since the position is defined in points and not in pixels everything gets positioned like expected according to device screen scale for 1x devices the position stays 2020 for 2x position is 4040 and for 3x the position is 6060problemthe problem is that 200x200px and 400x400px assets are way to small for ipad devices in order to achieve similar look and feel on all devicesquestionhow to successfully presentimport assets in a way that would enable me to achieve similar if not the same look and feel on all devicesscreen sizes without breaking child nodes positioningmy takestake 1i could simply use the existing 400x400px assets on nonretina ipad devices and 600x600px assets on retina ipad devices for the house node but the positioning of a child nodes would become broken this is because the child position value wouldnt change and would still be 2020 and 4040 for ipad devices respectively while the assets would be bigger this would yield inaccurate child positions relative to the house nodetake 2i could also scale the skscene size zoom effect while using the normal 200x200px and 400x400px sized assets for ipad devices respectively this works and it keeps the child nodes positioning working but the rendered quality of the sceneassets is not good as it should be also this feels like a hack and we do not want thattake 3i could also use twice as big assets for ipad devices and double the child nodes position at the runtime in this case i would use a 400x400px asset for nonretina ipad devices and a new 800x800px asset for retina ipad devices while this looks great and keeps the child nodes positioning working it seems like a really big hack fixing child node position during runtime with thisif ui user interface idiom uiuserinterfaceidiompad positionx 20f positiony 20fthank you for taking the time to read the question,"['ios', 'objective-c', 'iphone']" +888791,adding values from a class in java there was a question in my book that said this there are no answerssuppose we have a class beta declared with the headerclass beta extends alphaso beta is a subclass of alpha and in class alpha there is a method with headerpublic int valuegamma gam throws valueexceptionwrite a static method called addvalues which takes an object which could be of type arraylistalpha or arraylistbeta and also an object of type gamma a call to the method addvalues must return the sum obtained by adding the result of a call of value on each of the objects in the arraylist argument with the gamma argument as the argument to each call of value any call of value which causes an exception of type valueexception to be thrown should be ignored in calculating the summy attemptpublic static int addvaluesarraylist extends alpha arr gamma gam int sum 0 for int i 0 i arrsize i try sum arrgeti gam catch exception e i return sumalthough i know for starters that the line sum arrgeti gam is going to give me an error because they are not straight forward ints that can be added the book provides no more information on the question so what i have written here is everything required for the question,['java'] +888799,spritekit physic different on ios 7x and ios 8x why would the sprite kit physic be different on ios 7x vs ios 8xi have a simple spritekit scene i have 2 static pins and in between i have sprites which are connected by a spring joint dropping an object on this elastic rope would behave like a trampoline everything was looking ok on ios 7x until i started testing on ios 8x i have tested on similar devices 2 iphones 5s and 2 ipod touch 5th gen with each 7 8 i am getting the same fps having the same number of nodesi have tried all kind of joint factors gravity speed and every time i run this simple piece of code on different devices on 7x i get a similar behavior but if i run it on 8x devices the elasticity is different of the spring joint is different stiffer on 7x the elastic will bend more on 8x without anything on it but if you add several balls on it you can even see a greater effect on the 8x devices before i am asked here the skcene codedefine kfrequency 300fdefine kdamping 00fdefine knodes 20typedef ns optionsuint32 t categorymask categorymaskball 1 0 categorymaskpin 1 1 categorymaskelastic 1 2 categorymaskborder 1 3implementation simplegamescenevoiddidmovetoviewskview view selfbackgroundcolor skcolor blackcolor selfphysicsworldgravity cgvectormake00 49 nsmutablearray nodesnsmutablearray arraywithcapacityknodes2 skspritenode pin self addpincgpointmakeselfsizewidth2 selfsizeheight4 self addchildpin nodes addobjectpin for int i 1 iknodes i skspritenode elastic self addelasticcgpointmakeselfsizewidth2ipinsizewidth1 selfsizeheight4 self addchildelastic nodes addobjectelastic skspritenode pin2 self addpincgpointmakeselfsizewidth2knodes1pinsizewidth1 selfsizeheight4 self addchildpin2 nodes addobjectpin2 for int i 1 iknodes1 i skspritenode nodea nodes objectatindexi1 skspritenode nodeb nodes objectatindexi self addspringjointfromnodea tonodeb voidtouchesbegannsset touches witheventuievent event for uitouch touch in touches skspritenode ball self spawnballattouch locationinnodeself self addchildball skspritenode spawnballatcgpointlocation skspritenode ball skspritenode spritenodewithtexturesktextureatlas atlasnamedgame texturenamedcircle ballposition cgpointmake locationx locationy ballphysicsbody skphysicsbody bodywithcircleofradiusballsizewidth2 ballphysicsbodydynamic yes ballphysicsbodyaffectedbygravity yes ballphysicsbodymass 400f ballphysicsbodycategorybitmask categorymaskball ballphysicsbodycollisionbitmask categorymaskelastic ballphysicsbodycontacttestbitmask 0 ballname ball return ballskspritenode addpincgpoint location skspritenode pin skspritenode spritenodewithtexturesktextureatlas atlasnamedgame texturenamedpin pinposition location pinzposition 1 cgfloat offsetx pinsizewidth pinanchorpointx cgfloat offsety pinsizeheight pinanchorpointy cgmutablepathref path cgpathcreatemutable cgfloat side pinsizewidth cgpathmovetopointpath null 0 offsetx side offsety cgpathaddlinetopointpath null side offsetx side offsety cgpathaddlinetopointpath null side offsetx 0 offsety cgpathaddlinetopointpath null 0 offsetx 0 offsety cgpathclosesubpathpath pinphysicsbody skphysicsbody bodywithpolygonfrompathpath pinphysicsbodyaffectedbygravity no pinphysicsbodydynamic no pinphysicsbodycategorybitmask categorymaskpin pinphysicsbodycollisionbitmask 0 pinphysicsbodycontacttestbitmask 0 cgpathreleasepath return pinskspritenode addelasticcgpoint location skspritenode elastic skspritenode spritenodewithtexturesktextureatlas atlasnamedgame texturenamedelastic elasticposition location elasticzposition 1 cgfloat offsetx elasticframesizewidth elasticanchorpointx cgfloat offsety elasticframesizeheight elasticanchorpointy cgmutablepathref path cgpathcreatemutable cgfloat side elasticsizewidth cgpathmovetopointpath null 0 offsetx side offsety cgpathaddlinetopointpath null side offsetx side offsety cgpathaddlinetopointpath null side offsetx 0 offsety cgpathaddlinetopointpath null 0 offsetx 0 offsety cgpathclosesubpathpath elasticphysicsbody skphysicsbody bodywithpolygonfrompathpath elasticphysicsbodyaffectedbygravity yes elasticphysicsbodyallowsrotation no elasticphysicsbodydynamic yes elasticphysicsbodymass 10f elasticphysicsbodycategorybitmask categorymaskelastic elasticphysicsbodycollisionbitmask categorymaskball elasticphysicsbodycontacttestbitmask 0 cgpathreleasepath return elastic void addspringjointfromskspritenode nodea toskspritenode nodeb skphysicsjointspring joint skphysicsjointspring jointwithbodyanodeaphysicsbody bodybnodebphysicsbody anchoranodeaposition anchorbnodebposition jointfrequency kfrequency gives the joint some elasticity jointdamping kdamping 00f will remove damping to create the pendulum selfphysicsworld addjointjointend,"['ios', 'objective-c']" +888810,how exactly works the spring bean post processor i am studying for the spring core certification an i have some doubts about how spring handle the beans lifecycle and in particular about the bean post processorso i have this schemait is pretty clear for me what it meansinto the load bean definitions phase happens thatthe configuration classes are processed andor components arescanned for andor xml files are parsedbean definitions added to beanfactory each indexed under its idspecial beanfactorypostprocessor beans invoked it can modify the definition of any bean for example for the propertyplaceholder values replacementsthen inthe beans creation phase happens thateach bean is eagerly instantiated by default created in right order with its dependencies injectedafter dependency injection each bean goes through a postprocessingphase in which further configuration and initialization may occurafter post processing the bean is fully initialized and ready for use tracked by its id until the context is destroyedok this is pretty clear for me and i also know that there are two types of bean post processors that areinitializers initialize the bean if instructed ie postconstructall the rest that allow for additional configuration and that may run before or after the initialize stepand i post this slideso it is very clear for me what does the initializers bean post processors they are the methods annoted with postcontruct annotation and that are automatically called immediately after the setter methods so after the dependecy injection and i know that i can use to perform some initialization batch as populate a cache as in the previous examplebut what exactly represents the other bean post processor what means that these are performed before or after the initialization phaseso my bean are instantiated and it is performed the dependency unjection so then the initialization phase is perfromed by the execution of a postcontruct annoted method what means that an bean post processor is performed before the initialization phase it means that it happen before the postcontruct annoted method execution so int means that it could happen before the dependency injection before that the setter methods are calledand what exactly means that it is performed after the initiazalization step it means that it happens after that the exectuon of a postcontruct annoted method or whati can easily figure into my head why i need a postcontruct annoted method but i cannot figure some typical example of the other kind of bean post processor can you show me some typical example of when are usedtnx,['java'] +888821,meaning of javascript i found some code about authentication with angular and i cannot understand this trick authserviceisauthenticated function return sessionuseridwhat does mean different of userid whenever true true true etc it do not understand thissomebody can help me for the source part the authservice,['javascript'] +888847,carrierwave save nil if the image is not uploaded i am trying to migrate images from local file system to dropbox so i am using carrierwave dropbox gem to move all images to dropbox i am able to store new images which is uploaded from my application i am trying to move the existing imagesi am using articlefirstavatar method to check whether the image exists or not i have used this method in many places for different sizes of images in my applicationwhen i use the above method to find out whether the image exists or not it says true always when the image is not present in dropbox look at my console output2 my uploaderclass avatar carrierwaveuploaderbaseinclude carrierwaveminimagickstorage filedef store dir if model uploadsmodelclassto sunderscoremodelidmounted as else uploadsmounted as end end endconsole output 1articlefirstavatarfalseavataruploader0x007f9813f1fe70 file carrierwavesanitizedfile0x007f9813f1e688 content typenil fileusersworkprojectapp1publicuploads370avataravatarpng original filenamenil model article model mounted asavatar storagecarrierwavestoragefile0x007f9813f1fad8 uploaderavataruploader0x007f9813f1fe70 versionsi changed uploader as followsclass avatar carrierwaveuploaderbase include carrierwaveminimagick storage dropbox def store dir if model uploadsmodelclassto sunderscoremodelidmounted as else uploadsmounted as end end endconsole output2articlefirstavatartrue avataruploader0x007f8574143ee8file carrierwavestoragedropboxfile0x007f8574143308 client dropboxclient0x007f8574143420 rootdropbox session dropboxsession0x007f8574143498 access tokenoauthtoken0x007f8574143470 key123453 secret2 consumer keyabcdeafs consumer secretasdfasfj localenil request tokennil configapp keyasdfasfasf app secretasdfkasfksf access tokenadfkjasfkhs access token secretaksdfkhsfksf access typedropbox user id292929292 pathuploadsimages370avatarpng uploaderavataruploader0x007f8574143ee8 model artcle model mounted asimage storage carrierwavestoragedropbox0x007f8574143c90 config app keyasdfasfasf app secretasdfkasfksf access tokenadfkjasfkhs access token secretaksdfkhsfksf access typedropbox user id292929292 dropbox client dropboxclient0x007f8574143420 rootdropbox sessionwhy does it show true when the image is not presenthow can i get false when the image is not present in dropbox,"['ruby-on-rails', 'ruby']" +888873,thisplay qstring qt5 content in visual studio 2013 debugging i used to google a lot about iti enabled debugging edit and continue in native only optionsi was trying to add visualizers to visual studio 2013visualizersvstools project on codeplex is not for 2013 seems likebut so far nothing helps,['c++'] +888889,widening exception of overriden method in java assume we have 2 classesclass aimport javaioioexception public class a public void test throws ioexception systemoutprintlntest in a class b import javaioioexception public class b extends a override public void test throws exception systemoutprintlntest in b this gives a compiler error and i would like to know the reason for iti can get the answer by myself but this is not fully scientific but partly logicallyi wrote a blog in azerbaijani when i write blog i stucked in loading processplease be carefull in quotesi think that when compiler read b classit loads method headers of a and method headers of band when you call test of a jvm calls test of a but as body calls test of band at that time we will have this method public void test throws ioexceptionheader of a systemoutprintlntest in bbody of b here i can throw wide exception from ioexception because here is body of test in btest method in b can throws exception so compiler does not approve this version of code my question is that really the process is going on as what i wrote aboveloading headers issue i stucked exactly herecan you explain me linking process i cannot figure out background of a a new b when compiler converts this line into bytecodedoes it loads of method headers of a and method bodys of batestcalls test of b class i know logically but cannot figure out at compiler level linking process thanks,['java'] +888943,difference between momenttostring and momenttoisostring i have reading momentjs document there have a momenttoisostring function for helps to formats a string to the iso8601 standard also there have a another one reason for why we use momenttoisostringmomenttoisostring function using for performance reasonsi do not know toisostring the performance best than momenttostringbut only the result was difference while using momenttostring and momenttoisostring so my question iswhy we should use momenttoisostring for performance reasons and what is the difference between momenttoisostring and momenttostring,['javascript'] +889031,angular js script5007 object expected error in ie9 and ie10 upon loading the angular library i am developing an angularjs application that should run on firefox and ie 9 and ie 10i use the latest version of angularjs library now it is 1315the serverside is written in java in javaee platform and server runs on glassfish and our computers run windows 7everything works fine when i am running the server locally on my computer and access my application using the httplocalhost8080 urlbut in ie9 and ie10 when i try to load the application from my server by using my ip address something like then angularjs library fails to load it gives an error saying script5007 object expected angularminjs line 7 character 218can this be an issue with the security settings of ie or the networki looked for similar issues but none was talking about this problem please help me if have an idea how can this be resolved,['javascript'] +889118,how to rendering partials within a partials in middleman i have some haml partials many of which contain the boilerplatecontainer row collg12when i try to abstract that out ala partial site section i getsyntax error unexpected keyword end expecting endofinput endendendendi am using ruby 2how do i render a haml partial within a haml partial in middlemanthanksupdatethis is apparently some kind of special case dealing with my partial above i have other partialswithinpartials rendering just fineupdatewith respect to this this repo the layout would actually be site sectioncontainer row collg12 nested section partial site section moar nested hamlindexhamlpartial nested section,['ruby'] +889128,how to convert numpy datetime64 into datetime i basically face the same problem posted hereconverting between datetime timestamp and datetime64but i could not find satisfying answer from it my question how to extract datetime from numpydatetime64 typeif i trynpdatetime6420120618t02054530400astypedatetimedatetimeit gave me 13392054530lmy current solution is convert datetime64 into a string and then turn to datetime again but it seems quite a silly method,['python'] +889161,numpyscipy deprecation warning for rank i have some python code which uses numpy and have run this successfully for a year or more i suddenly got the following error last weekusrlocallibpython27thistpackagesnumpycorefromnumericpy2507 visibledeprecationwarning rank is deprecated use the ndim attribute or function instead to find the rank of a matrix see numpylinalgmatrix rank visibledeprecationwarningi cannot find much on this online but i found a suggestion that this was due to a bug in old versions of scipy although my code does not actually use scipy directly i have upgraded to python 279 with numpy 192 and scipy 0151 however i am still getting the same error i am not sure whats causing this or how i fix this,['python'] +889172,flipping an array using pointers include iostreamusing namespace stdint fliparrayint input int n int outputn int pos 0 for int i n1 i 0 i outputpos inputi int p output for int k 0 k n k cout pk endl endl return pint main const int size 5 int firstarraysize for int and 0 and size n firstarrayn n1 int a a fliparrayfirstarray size for int j 0 j size j cout aj endl cout endl cout a t a1 t a2 return 0i am attempting to flip firstarray using a function that returns a pointer but i am struggling to understand how accessing an index using a pointer workshere is why i am confusedwithin the function fliparray the following forloopfor int k 0 k n k cout pk prints 5 4 3 2 1 to the console it was my understanding that i should be accessing an element of a vector with pk not pk if i print pk 5 6 7 8 9 is printed to the console if i print the array without pointers and using k as the index location 5 4 3 2 1 is printed to the consolewithin my main function however the values of a which is assigned pointer p from the fliparray function i do not get the same resultsfor int j 0 j size j cout aj endlprints 50123 to the console and for int j 0 j size j cout aj endlprints 52345 to the console further i thought that the pointer location of p and the pointer of location of a should be the same but when i print the address p in the function i get the location of 0x28fde0 and when i print the address of a in the main i get the location 0x28fedc of course these were done during the same runcould someone tell me where i have gone astray thanksthanks to everyone for the informative answersi have updated my solution and it is now returning what i would expect it to i have a new question about memory leaks and when pointers need to be deletedint fliparrayint input int n int output new intn int pos 0 for int i n1 i 0 i outputpos inputi return outputint main const int size 5 int firstarraysize for int and 0 and size n firstarrayn n1 int a a fliparrayfirstarray size for int j 0 j size j cout aj can also be written as aj which is more prone to bugs delete a return 0will the pointer output be deleted when the function fliparray returns if not how should i delete output while also returning it is deleting the pointer a in my main function the same thing as deleting output because they point to the same location,"['c++', 'c']" +889174,oclint astmatcher rule matching ns enum i am trying to create an oclint rule that matches both typedef enum and typedef ns enum declarations with little successi have an objectivec file testclassm with the following enum declarations in ittypedef ns enumnsinteger testenum testenumnone testenumsome testenumalltypedef enum othertestvalue 0 othertestvalue1 othertestvalue2 othertestenumdumping the ast with this commandclang xclang astdump fsyntaxonly classestestclassm grep enumgives me this output containing thistypedefdecl 0x7f9d3accd630 col1 col28 col28 testenum enum testenumenum testenumenumdecl 0x7f9d3accd6a8 prev 0x7f9d3accd530 systemlibraryframeworkscorefoundationframeworkheaderscfavailabilityh17157 classestestclassm711 line6728 testenum nsintegerlong enumconstantdecl 0x7f9d3accd738 line685 col5 testenumnone nsintegerlong enumconstantdecl 0x7f9d3accd788 line695 col5 testenumsome nsintegerlong enumconstantdecl 0x7f9d3accd7d8 line705 col5 testenumall nsintegerlongenumdecl 0x7f9d3accd828 line739 line771 line739 enumconstantdecl 0x7f9d3accd900 line745 col22 col5 othertestvalue int enumconstantdecl 0x7f9d3accd950 line755 col5 othertestvalue1 int enumconstantdecl 0x7f9d3accd9a0 line765 col5 othertestvalue2 inttypedefdecl 0x7f9d3accda40 line731 line773 col3 othertestenum enum othertestenumothertestenumi have an astmatcherrule objcnsenumrule where i am trying to match both typedef enum as well as typedef ns enum here is the code for thatinclude oclintabstractastmatcherrulehinclude oclintrulesethusing namespace stdusing namespace clangusing namespace clangast matchersusing namespace oclintclass objcnsenumrulerule public abstractastmatcherrulepublicvirtual const string name const override return obj c ns enum rulevirtual int priority const override return 3virtual void callbackconst matchfindermatchresult result override const enumdecl enumdecl resultnodesgetnodeasenumdeclenum if enumdecl addviolationenumdecl this found enum virtual void setupmatcher override addmatcherenumdeclbindenumstatic ruleset rulesnew objcnsenumrulerulehowever when i run this rule i only get the output for the typedef enum declarationclassestestclassm739 obj c ns enum rule p3 found enumwhat am i doing wrong here both enums show up in the ast dump but only one matches in the oclint ruleediti think this may have to do with the ast dump showing the enumdecl for the ns enum as defined in a different source file probably because of the ns enum macro as i can match the typedef but not the enumdecl,['c++'] +889270,c deleting a list member while iterating standard solution is not working heres my problem i have read many previous questions about how to delete a member of a list while iterating over it and i tried the various solutions that the answers proposed it happens that they seem not to work i have a list of classes of this kindclass walker public walkerint walker double x double y double z double weight int molteplicity the constructor and destructor are the followingwalkerwalkerint particle num x new doubleparticle num y new doubleparticle num z new doubleparticle numwalkerwalker delete x delete y delete znow the listlistwalker populationis defined as a member of another class now if the element molteplicity is null calculated via another function i have to dinamically remove the member from the class and this is how i do itfor it populationbegin it populationend if itmolteplicity 0 it populationeraseit else it getting the following error at runtime prog22332 malloc error for object 0x7f838ac03a60 pointer being freed was not allocated set a breakpoint in malloc error break to debug abort trap 6do you see the error thank you very much for your help if you need some more code just let me know,['c++'] +889271,validating google openid connect jwt id token i am trying to upgrade my mvc website to use the new openid connect standard the owin middleware seems to be pretty robust but unfortunately only supports the form post response type this means that google is not compatible as it returns all the tokens in a the url after a so they never reach the server and never trigger the middlewarei have tried to trigger the response handlers in the middleware myself but that does not seem to work at all so i have got a simply javascript file that parses out the returned claims and posts them to a controller action for processingproblem is even when i get them on the server side i cannot parse them correctly the error i get looks like thisidx10500 signature validation failed unable to resolve securitykeyidentifier securitykeyidentifier isreadonly false count 1 clause0 systemidentitymodeltokensnamedkeysecuritykeyidentifierclausetoken algrs256 kid073a3204ec09d050f5fd26460d7ddaf4b4ec7561 issaccountsgooglecom sub100330116539301590598 azp10618809501b47blhmmeprkvhcsnqmhfc7t20gvlgflappsgoogleusercontentcom nonce7c8c3656118e4273a397c7d58e108eb1 email verifiedtrue aud10618809501b47blhmmeprkvhcsnqmhfc7t20gvlgflappsgoogleusercontentcom iat1429556543exp1429560143 my token verification code follows the example outlined by the good people developing identityserver private async taskienumerableclaim validateidentitytokenasyncstring idtoken string state new stuff var token new jwtsecuritytokenidtoken var jwthandler new jwtsecuritytokenhandler byte certbytes getgooglecertbytes for int i 0 i certbyteslength i var certificate new x509certificate2certbytesi var certtoken new x509securitytokencertificate set up token validation var tokenvalidationparameters new tokenvalidationparameters tokenvalidationparametersvalidaudience googleclientid tokenvalidationparametersissuersigningtoken certtoken tokenvalidationparametersvalithissuer accountsgooglecom try validate securitytoken jwt var claimsprincipal jwthandlervalidatetokenidtoken tokenvalidationparameters out jwt if claimsprincipal null valid idtokenstatus valid catch exception e if idtokenstatus valid invalid return tokenclaims private byte getgooglecertbytes the request will be made to the authentication server webrequest request webrequestcreate streamreader reader new streamreaderrequestgetresponsegetresponsestream string responsefromserver readerreadtoend string split responsefromserversplit there are two certificates returned from google byte certbytes new byte2 int index 0 utf8encoding utf8 new utf8encoding for int i 0 i splitlength i if splitiindexofbegincert 0 int startsub splitiindexofbegincert int endsub splitiindexofendcert endcertlength certbytesindex utf8getbytessplitisubstringstartsub endsubreplacen n index return certbytes i know that signature validation is not completely necessary for jwts but i have not the slightest idea how to turn it off any ideas,"['c#', '.net']" +889274,pdf document does not thisplay when creating control dynamically i have an application that i want to thisplay multiple pdf documents if i define the control at design time i can load a document and thisplay it but when i dynamically create the control during run time i cannot get it to thisplay the document is being thisplayed in a tabhere is my codeaxacropdf newpdf new axacropdfnewpdfcreatecontrolnewpdfwidth selectedtabwidthnewpdfheight selectedtabheightnewpdfloadfilefilepathselectedtabcontrolsaddnewpdfnewpdfshownewpdfvisible truehow do i get the pdf to thisplay,['c#'] +889282,nodejs returning garbage json i am trying to write a simple piece of code using nodejs to get the json back from the stack exchange apithis is the api i am targetting sortreputationinnamedonal20raffertysitestackoverflowand here is my codevar https requirehttps use nodejs https modulefunction getuserdatabynameusername callbackvar stackoverflowuserurl sortreputationinnameencodeuricomponentusernamesitestackoverflowhttpsgetstackoverflowuserurl functionresponse consolelogheaders responseheaders if responsestatuscode 200 var jsonstring responseondata function chunk jsonstring chunk responseonend function consolelogjsonstring callbackjsonstringifyjsonstring else error consolelogerror however when i run this the data always comes back in a state of garbage like text like the followingu001fi12bu0u0u0u0u0u04u0uri12ni120fi12i12bi12i12i12uu0013i122u0010i12ri12mi12uu0018u04uu001di12i12jri12ei12vsu04u05i12i12i12i12i12i12hi12i12i12i12ci12i127oi12qi12ni12i12u0012u0014gi12i12i12i12i12i12i12zvu001fi12i12i12i12vi12i12ai12ni12qui12oi12u0eu0012i12n u05i12i12u03u00130au06bi12i12si12o i12i12i12i12i12ci12i12bwi12iu0bci12i12bi12u0017ei12u0013i12qi12di12i12loi12i12i12nqu0017i12i12i12oi12i12i12i12i12i12i12pfzi12ii12ru0fi12i12pui12xi12bki12i12luvi12i12u0012u00194i12lu0ei12urwi12i12u001ci12i12i12i12u001ai129i12u001ei12qi12qi12i12i12i12i12oi12i12abtii12bi12i12 u07i12cki2i12i12i12u0i12ju i12i12i12i12u03gi12u03i12u02u0u0i am assuming there is something wrong with my encodingdecoding but i cannot figure out what to do to fix this,['javascript'] +889324,youtube v3 api upload to channel i have to migrate my php scripts using youtubes v2 api to v3i am trying this example to upload a video samplesphpresumable uploadsi can authenticate my google account for my app the only problem is that the video is being uploaded to my google youtube channel and not to my original channel they both belong to the same google accounti was not able to solve this problem with the v2 api but selecting the default channel in channel switcher switcher did helphow can i tell the v3 api which channel to upload to,['php'] +889327,bluetooth gatt callback not working with new api for lollipop i currently have a method which writes to the ble devices to beep it my bluetooth callback goes as follows readcharacteristic rc new readcharacteristiccontext dsgetmacaddress serviceuuid uuidfromstringmyuuid override public void onread logwtag calldevice onread trythreadsleep10catchinterruptedexception ex writecharacteristic wc new writecharacteristicactivity context getmacaddress serviceuuid uuidfromstringmyuuid override public void onwrite logwtag calldevice onwrite override public void onerror logwtag calldevice onwriteonerror store data in writebuffer wcwritecharacteristicwritebuffer override public void onerror logwtag calldevice onreadonerror rcreadcharacteristicmy readcharacteristic implementation is as follows public class readcharacteristic extends bluetoothgattcallback public readcharacteristiccontext context string macaddress uuid service uuid characteristic object tag mmacaddress macaddress mservice service mcharacteristic characteristic mtag tag mcontext context thisactivity activity final bluetoothmanager bluetoothmanager bluetoothmanager mcontextgetsystemservicecontextbluetooth service mbluetoothadapter bluetoothmanagergetadapter final private static string tag readcharacteristic private object mtag private string mmacaddress private uuid mservice private uuid mcharacteristic private byte mvalue private activity activity private bluetoothadapter mbluetoothadapter private context mcontext private int retry 5 public string getmacaddress return mmacaddress public uuid getservice return mservice public uuid getcharacteristic return mcharacteristic public byte getvalue return mvalue public void onread logwtag onread getdatahexgetvalue public void onerror logwtag onerror public void readcharacteristic if retry 0 onerror return retry final bluetoothdevice device mbluetoothadaptergetremotedevicegetmacaddress if device null logwtag starting read getservice getcharacteristic final readcharacteristic rc readcharacteristicthis deviceconnectgattmcontext false rc override public void onconnectionstatechangebluetoothgatt gatt int status int newstate logwtagonconnectionstatechange status newstate if newstate 2status 0 gathiscoverservices else logwtag status gathisconnect gattclose try threadsleep20 catchexception e readcharacteristic override public void onservicesthiscoveredbluetoothgatt gatt int status logwtagonservicesthiscovered status bluetoothgattservice bgs gattgetservicegetservice if bgs null bluetoothgattcharacteristic bgc bgsgetcharacteristicgetcharacteristic gattreadcharacteristicbgc override public void oncharacteristicreadbluetoothgatt gatt bluetoothgattcharacteristic characteristic int status logwtagoncharacteristicread status if status bluetoothgattgatt success mvalue characteristicgetvalue logwtagoncharacteristicread mvalue gathisconnect gattclose onread else gathisconnect gattclose this current method works perfectly fine for devices running kitkat and below but when i run the same function on lollipop it beeps the device a couple of times and then stops working from then on wards whenever i try to connect it says the device is thisconnected and gives me an error code of 257 in onconnectionstatechanged method i also get this error whenever i call this method 0420 141423503 1232912384comwebblexy wbluetoothgatti1 unhandled exception in callback javalangnullpointerexception attempt to invoke virtual method void androidbluetoothbluetoothgattcallbackonconnectionstatechangeandroidbluetoothbluetoothgatt int int on a null object reference at androidbluetoothbluetoothgatt1onclientconnectionstatebluetoothgattjava181 at androidbluetoothibluetoothgattcallbackstubontransactibluetoothgattcallbackjava70 at androidosbinderexectransactbinderjava446is there anyone who has faced the same problem i never encountered the object to be null when ever i tried debugging,['android'] +889345,how to customize object equality for javascript set new es 6 harmony introduces new set object identity algorithm used by set is similar to operator and so not much suitable for comparing objectsvar set new setsetadda1setadda1consolelogsetvalues array object object how to customize equality for set objects in order to do deep object comparison is there anything like java equalsobject,['javascript'] +889369,what is the proper way to print a nested list with the highest value in python i have a a nested list and i am trying to get the sum and print the list that has the highest numerical value when the individual numbers are summed togetherx 123456789highest listfor i in x highestappendsumifor ind a in enumeratehighest if a maxhighest printxindi have been able to print out the results but i think there should be a simple and more pythonic way of doing this maybe using a list comprehension how would i do this,['python'] +889372,why is the callable abc in the collections abc module the python collectionsabc module contains many handy abcs for checking various features of objects but one that does not appear to belong is callable no standard collection is callable and pep 3119 does not provide any reasoning or even mention the callable abc so why is it in this package instead of somewhere elsecontexti am writing a pythonjava compiler for fun and i just wanted to see if there was any reasoning behind the decision so i could list that reasoning in my code,['python'] +889431,joining elements in a list without the join command i need to join the elements in a list without using the join command so if for example i have the list1241511the output should be1241511here is my code so fardef listslist1 answer 0 h lenlist1 while list1 answer answer list10 10 h h h 1 list1pop0 printanswerbut in the end the answer ends up being 125610 which is clearly wrongi think the logic is ok but i cannot find the problem,['python'] +889437,how to prevent constructor misuse in c class i have been trying to implement a loosely coupled application in an aspnet mvc5 app i have a controllerpublic class headercontroller controller private imenuservice menuservice public headercontrollerimenuservice menuservice this menuservice menuservice get header public actionresult index return view public actionresult getmenu menuitem menu this menuservicegetmenu return viewmenu menu and service being used in this controller ispublic class menuservice imenuservice private imenurespository menurepository public menuserviceimenurespository menurepository this menurepository menurepository public menuitem getmenu return this menurepositorygetmenu and the repository being used in the service class ispublic class menurepository imenurespository public menuitem getmenu return the menu items the interfaces used for the service and repository are as such public interface imenuservice menuitem getmenu public interface imenurespository menuitem getmenu the constructor for headercontroller takes in the menuservice using constructor injection and i have ninject as the di container handling thisit all works great except in my controller i can still do thismenuitem menu new menuservicenew menurepositorywhich breaks the architecture how can i prevent the new being used in this way,"['c#', 'asp.net']" +889475,parsing nested records in immutablejs suppose i have the following records defined using immutablejsvar address immutablerecordstreet city zip var user immutablerecordname address new addresshow do i convert plain javascript object into the user record i tried the following but it does not produce the expected outputvar user new username foo address street bar city baz record name foo address object object i am aware that it is possible to explicitly create the address recordvar user new username foo address new addrestreet bar city baz record name foo address record street bar city baz zip but that is not solution i am looking for imagine you have records nested several levels deep and want to storeretrieve the data as json eg in database i would like to use the actual user record structure as a schema information for recreating the nested records or is there a better way to represent nested and structured immutable data,['javascript'] +889488,how to select all columns except one column in pandas using ix i have a dataframe look like this import pandas import numpy as np df dataframenprandomrand44 columns listabcd df a b c d 0 0418762 0042369 0869203 0972314 1 0991058 0510228 0594784 0534366 2 0407472 0259811 03964 0894202 3 0726168 0139531 0324932 0906575how i can get all columns except column b using dfix,['python'] +889583,execution failed for task appcompiledebugaidl aidl is missing i installed android studio on my computer i created a new project but that got me the error below what can i doerrorexecution failed for task appcompiledebugaidl aidl is missingmy android studio version is 110this is my buildgradle filebuildscript repositories jcenter dependencies classpath comandroidtoolsbuildgradle110 note do not place your application dependencies here they belong in the individual module buildgradle files allprojects repositories jcenter and apply plugin comandroidapplicationandroid compilesdkversion 21 buildtoolsversion 2412 defaultconfig applicationid comexamplejocloning a login screen minsdkversion 13 targetsdkversion 21 versioncode 1 versionname 10 buildtypes release minifyenabled false proguardfiles getdefaultproguardfileproguardandroidtxt proguardrulespro dependencies compile filetreedir libs include jar compile comandroidsupportappcompatv72200,['android'] +889602,change background color of active list item in bootstrap i have item group list div idmainmenu div classlistgroup panel a hrefwhy classlistgroupitem datatogglecollapse dataparentmainmenumenu 1a div classcollapse idwhy a href classlistgroupitem datatogglecollapse dataparentsubmenu1menu 1 aa a href classlistgroupitemmenu 1 ba a href classlistgroupitemmenu 1 ca a href classlistgroupitemmenu 1 da a href classlistgroupitemmenu 1 ea a href classlistgroupitemmenu 1 fa div a hrefjoinus classlistgroupitem datatogglecollapse dataparentmainmenumenu 2a div classcollapse idjoinus a href classlistgroupitemmenu 2 aa a href classlistgroupitemmenu 2 ba a href classlistgroupitemmenu 2 ca a href classlistgroupitemmenu 2 da a href classlistgroupitemmenu 2 ea div divdivi want to change background of active list item i know how to change background but i am unable to get which list is active or inactive by javascript tried lots of solution given on others but did not wojrkjsfiddleupdate,"['javascript', 'html', 'css']" +889678,alternating colours per row per div using only css i want to know if this is possible using only cssblack whitewhite blackblack whitewhite blackthe name represents the colour background i want in this jsfiddle i have hardcoded it to show exactly what it is that i want but the amount of divs will be dynamic so i do not know how many there will behow do i achieve this,['css'] +889741,how to guarantee get of concurrenthashmap to always return the latest actual value introductionsuppose i have a concurrenthashmap singletonpublic class recordsmapsingleton private static final concurrenthashmapstringrecord payments new concurrenthashmap public static concurrenthashmapstring record getinstance return payments then i have three subsequent requests all processed by different threads from different sourcesthe first service makes a request that gets the singleton creates record instance generates unique id and places it into map then sends this id to another servicethen the second service makes another request with that id it gets the singleton finds record instance and modifies itfinally probably after half an hour the second service makes another request in order to modify record furtherproblemin some really rare cases i am experiencing heisenbug in logs i can see that first request successfully placed record into map second request found it by id and modified it and then third request tried to find record by id but found nothing get returned nullthe single thing that i found about concurrenthashmap guarantees is actions in a thread prior to placing an object into any concurrent collection happenbefore actions subsequent to the access or removal of that element from the collection in another threadfrom here if i got it right it literally means that get could return any value that actually was sometime into map as far as it does not ruin happensbefore relationship between actions in different threadsin my case it applies like this if third request does not care about what happened during processing of first and second then it could read null from mapit does not suit me because i really need to get from map the latest actual recordwhat have i triedso i started to think how to form happensbefore relationship between subsequent map modifications and came with idea jls says in 1744 that a write to a volatile variable v a8314 synchronizeswith all subsequent reads of v by any thread where subsequent is defined according to the synchronization orderso let us suppose i will modify my singleton like thispublic class recordsmapsingleton private static final concurrenthashmapstringrecord payments new concurrenthashmap private static volatile long revision 0 public static concurrenthashmapstring record getinstance return payments public static void incrementrevision revision public static long getrevision return revision then after each modification of map or record inside i will call incrementrevision and before any read from map i will call getrevisionquestiondue to nature of heisenbugs no amount of tests is enough to tell that this solution is correct and i am not an expert in concurrency so could not verify it formallycan someone approve that following this approach guarantees that i am always going to get the latest actual value from concurrenthashmap if this approach is incorrect or appears to be inefficient could you recommend me something else,['java'] +889764,list raw sensor data in memo i want to list all available raw sensor data in a memo for androidfollowing code worked over the past years but it does not work with xe8 there is probably an internal compiler bug is there anything i can do to make it work again or is there an alternative solutionuses typinfotype torientationsensoraccessor classtcustomorientationsensor tlocationsensoraccessor classtcustomlocationsensorprocedure tform2button1clicksender tobjectvar p location tcustomlocationsensortproperty p orientation tcustomorientationsensortproperty n v stringbegin memo1linesclear if assignedorientationsensor1sensor then begin if not orientationsensor1sensorstarted then orientationsensor1sensorstart error only in xe8 incompatible types tcustomlocationsensortproperty and tcustomorientationsensortproperty in xe7 it works for p orientation in orientationsensor1sensoravailableproperties do begin and orientationsensorgetenumnametypeinfotcustomorientationsensortproperty integerp orientation v floattostrtorientationsensoraccessororientationsensor1sensorgetdoublepropertyp orientation memo1linesvaluesn v end end if assignedlocationsensor1sensor then begin if not locationsensor1sensorstarted then locationsensor1sensorstart for p location in locationsensor1sensoravailableproperties do begin and locationsensorgetenumnametypeinfotcustomlocationsensortproperty integerp location v floattostrtlocationsensoraccessorlocationsensor1sensorgetdoublepropertyp location memo1linesvaluesn v end endendupdatesome experiments1 when i comment out the first for it will compile for p orientation in orientationsensor1sensoravailableproperties do begin and orientationsensorgetenumnametypeinfotcustomorientationsensortproperty integerp orientation v floattostrtorientationsensoraccessororientationsensor1sensorgetdoublepropertyp orientation memo1linesvaluesn v end end2 when i comment out the assigning of n and v it will compile too for p orientation in orientationsensor1sensoravailableproperties do begin and orientationsensorgetenumnametypeinfotcustomorientationsensortproperty integerp orientation v floattostrtorientationsensoraccessororientationsensor1sensorgetdoublepropertyp orientation memo1linesvaluesn v end endsince neither for nor n and v is the bad region where is the error then3 when i comment out the second forloop it will compile again if i comment out the first forloop it will compile too each forloop works but in combination they will not workit looks like the error is only happening if 5 factors are combinedtypinfoaccessorsfor loopusage of typinfo getenumnameboth forloops are usedupdate 2here is the smallest reproducible code i could find if any line is commented out it compilesprogram projectcompilerbugapptype consoleuses systemsensors systemsensorscomponentsvar p location tcustomlocationsensortproperty p orientation tcustomorientationsensortpropertybegin compilation error only in xe8 incompatible types tcustomlocationsensortproperty and tcustomorientationsensortproperty in xe7 it compiles for p orientation in torientationsensorcreatenilsensoravailableproperties do begin floattostr123 end for p location in tlocationsensorcreatenilsensoravailableproperties do begin endend,['android'] +889786,nodegyp link library dependencies at build time my nodejs addon uses cares library and my bindinggyp has dependencies attribute which is pointing to this now whenever i have to run addon i have to export ld library path variableis there a way i can configure this in bindinggyp so that every time i do not have to set ld library path linking at build timedependency setting in bindinggyp dependencies depscarescaresgypcares ex export export ld library pathbuildrelease,['c++'] +889808,change ad user terminal server properties with c i am using systemdirectoryservicesdirectoryentry to create ad user and everything work fine except for some remote desktop specifics propertiesexemple newuserpropertiesmstsconnectclientdrivesvalue falsenewuserpropertiesmstsconnectprinterdrivesvalue falsenewuserpropertiesmstsdefaulttomainprintervalue falsethis does not throw any exception so i guess the properties are found in the object but they do not have any effect when i go into the property window of that user under environment tab these 3 checkbox are still checked onam i missing something particular for these properties thank for your helpedit sorry i have been really busy here is a code sample private string createnewadaccountstring accountname string accountpassword try principalcontext context new principalcontextcontexttypedomain svlite litex y userprincipal newuser new userprincipalcontext newusersamaccountname accountname newuseruserprincipalname accountname newusername liteuser2015 accountname newuserthisplayname liteuser2015 accountname newusersetpasswordaccountpassword newuserpasswordneverexpires true newuserusercannotchangepassword true newusersave set advanced properties if newusergetunderlyingobjecttype typeofdirectoryentry directoryentry entry directoryentrynewusergetunderlyingobject entrypropertiesmstsconnectclientdrivesvalue false entrypropertiesmstsconnectprinterdrivesvalue false entrypropertiesmstsdefaulttomainprintervalue false entrypropertiesmstsinitialprogramvalue test entrycommitchanges return newuserguidtostring catch exception e messageboxshowfailed to create principalcontext exception e return null,['c#'] +889839,why is my application starting up in more than 2 minutes i am running a graphical java application made with swing on my windows 7 64 bits computermy application is a runnable jar file that i launch from my command prompt by using the following commandcpathtojrejavaexe jar myprogjarmy problem is that i get huge performance performance issues when i am using jre8 32bits while not when using jre7 32bits or jre8 64bitsnote that the application is runned with the same jar file the only difference is that it is being ran by different jresi tried different jre8 version and the problems persistswhen i compare both output when using the verbose argument i see that i get more than 1500 outputs with text loaded x from shared objects file for the jre7 while i get none for jre8mayby it may be somehow linked does anyone have an idea on what the problem could be here are some outputs from the jre7loaded mainframemainframextrfilefilter from rsrcloaded javaawteventhierarchylistener from shared objects fileloaded javalanginterruptedexception from shared objects fileloaded javaiofilewriter from shared objects fileloaded javaxswingcelleditor from shared objects fileloaded javaxswingtabletablecelleditor from shared objects fileloaded javaawtimagerenderedimage from shared objects fileloaded javaawtimagewritablerenderedimage from shared objects fileloaded javaawtimagebufferedimage from shared objects fileloaded sunawtutilidentityarraylist from cprogram files x86javajdk170 45jrelibrtjarloaded javaawtwindowtype from cprogram files x86javajdk170 45jrelibrtjarloaded javautilconcurrentatomicatomicboolean from shared objects fileloaded sunawtawtaccessorwindowaccessor from cprogram files x86javajdk170 45jrelibrtjarloaded javaawtwindow1 from cprogram files x86javajdk170 45jrelibrtjarloaded sunawtawtaccessorframeaccessor from cprogram files x86javajdk170 45jrelibrtjarloaded javaawtframe1 from cprogram files x86javajdk170 45jrelibrtjarloaded javaawtcomponentorientation from shared objects fileloaded javaawtcomponent3 from cprogram files x86javajdk170 45jrelibrtjarloaded javaxswingimageicon from shared objects fileloaded mainframesimulationsimulation from rsrcloaded mainframeoptimizationoptimization from rsrcloaded mainframeconvergenceconvergence from rsrcloaded javaawteventwindowevent from shared objects fileloaded mainframemenu from rsrchere are some jre8 outputsloaded mainframemainframe from rsrcloaded javautileventlistener from cprogram files x86javajre180 45librtjarloaded javaawteventactionlistener from cprogram files x86javajre180 45librtjarloaded javaxswingaction from cprogram files x86javajre180 45librtjarloaded sunreflectnativemethodaccessorimpl from cprogram files x86javajre180 45librtjarloaded sunreflectdelegatingmethodaccessorimpl from cprogram files x86javajre180 45librtjarloaded javaxswinguimanager from cprogram files x86javajre180 45librtjarloaded javaxswinguimanagerlookandfeelinfo from cprogram files x86javajre180 45librtjarloaded sunawtosinfo from cprogram files x86javajre180 45librtjarloaded sunawtosinfowindowsversion from cprogram files x86javajre180 45librtjarloaded sunawtosinfo1 from cprogram files x86javajre180 45librtjarloaded sunawtosinfoostype from cprogram files x86javajre180 45librtjarloaded javaawttoolkit from cprogram files x86javajre180 45librtjarloaded sunawtawtaccessortoolkitaccessor from cprogram files x86javajre180 45librtjarloaded javaawttoolkit4 from cprogram files x86javajre180 45librtjarloaded sunawtawtaccessor from cprogram files x86javajre180 45librtjarloaded javaawttoolkit5 from cprogram files x86javajre180 45librtjarloaded javautilresourcebundlecontrol from cprogram files x86javajre180 45librtjarloaded sunutilcoreresourcebundlecontrol from cprogram files x86javajre180 45librtjari runned a xsharedump for both jre7 and jre8 and i got the following resultsjre7loading classes to share donerewriting and unlinking classes donecalculating hash values for string objects donecalculating fingerprints doneremoving unshareable information donemoving common symbols to metadata section at 0x3a033570 donemoving vmsymbols to metadata section at 0x3a1d2170 donemoving the remaining symbols to metadata section at 0x3a1d3478 donemoved 44361 symbols 1703760 bytesmoving preordered readonly objects to shared space at 0x38a30 donemoving readonly objects to shared space at 0x38e129b0 donemoving string char arrays to shared space at 0x38e20cd8 donemoving preordered readwrite objects to shared space at 0x39430 donemoving readwrite objects to shared space at 0x399e8fb0 donemoving string objects to shared space at 0x39a3e920 donereadwrite space ends at 0x39a7dd28 6610216 bytesupdating references to shared objects donean error has occurred while processing the shared archive fileunable to create shared archive file cprogram files x86javajdk170 45jrebinclientclassesjsaerror occurred during initialization of vmunable to use shared archivejre8allocated shared space 27394048 bytes at 0x14a0loading classes to share preload warning cannot find javaxswingjcomponent2preload warning cannot find javaxswingrepaintmanager11preload warning cannot find javaxswingplafmetalmetallookandfeelmetallazyvaluepreload warning cannot find javaxswingplafmetalmetallookandfeelmetallazyvalue1preload warning cannot find javaxswingtextabstractdocumentinsertstringresultpreload warning cannot find sunawtwindowswtoolkit31preload warning cannot find sunjava2dthisposer2preload warning cannot find sunjava2dd3dd3dscreenupdatemanager1preload warning cannot find sunjava2dd3dd3dscreenupdatemanager11loading classes to share donerewriting and linking classes rewriting and linking classes donenumber of classes 2383 instance classes 2369 obj array classes 6 type array classes 8calculating fingerprints doneremoving unshareable information doneshared lookup cache table buckets 4108 bytesshared lookup cache table body 50352 bytesro space 5650016 477 of total out of 12582912 bytes 449 used at 0x14a0rw space 5396096 456 of total out of 12582912 bytes 429 used at 0x1560md space 753892 64 of total out of 2097152 bytes 359 used at 0x1620mc space 34032 03 of total out of 131072 bytes 260 used at 0x1640total 11834036 10 of total out of 27394048 bytes 432 used,['java'] +889856,how to exclude a file from an aar android library archive with gradle i am trying to create an aar file for a library android project using android studio and gradle i want to exclude from this archive specific folders and files but i cannot find a working solution the project has 2 flavoursapplibssrc flavour1 java a1 class file1java flavour2 java a1 class file1java main java res raw commentstxt androidmanifestxmland i use a buildgradle file like this oneapply plugin comandroidlibraryandroid compilesdkversion 21buildtoolsversion 2112defaultconfig minsdkversion 10 targetsdkversion 21packagingoptions exclude assets exclude commentstxtsourcesets flavour1 resources exclude commentstxt flavour2 buildtypes release minifyenabled true shrinkresources true proguardfiles getdefaultproguardfileproguardandroidtxt proguardrulestxt productflavors flavour1 packagingoptions exclude assets exclude resrawcommentstxt flavour2 dependencies compile comgoogleandroidgmsplayservicesgenerally speaking i have experimented a lot i have tried packagingoptions exclusion in sourcesets but nothing seems to work what i am trying to achieve is not include for example in the aar archive the file commentstxt and the folder assets which is an optional folder i examine each time the aar file by renaming it to zip and looking into the files includedi have also looked into the documentation here where maybe configurations could be a solution but i am not sure how to use it or how to move forward any help will be appreciated,['android'] +889902,failed to apply plugin android studio i am trying to import exoplayer library into my android studio project i have tryed few times with several methods importing direct with gradle import as module copy paste it i get the same errorerror15 a problem occurred evaluating project exoplayerlibrary failed to apply plugin id bintrayrelease plugin with id bintrayrelease not foundin library gradle i found the apply plugin lineapply plugin bintrayreleaseafter searching the library and apply it to dependencies i still got the errordependencies compile comnovodabintrayrelease0210any ideea how can i solve this problem,['android'] +889909,clang error on late default template parameter declaration the following code compiles fine with g but not with clang 36 forward declarationtemplate class s class tstruct basetemplate class tstruct basefriend friend struct baseint t actual declarationtemplate class s class t intstruct base void foo struct derivedfriend basefriendint struct derived baseint void fooint baseintfoo error occurs in the derivedfoo definitionerror too few template arguments for class template base baseintfoo testcpp38 note template is declared herestruct base error goes away after few minor fixes likeif default template parameter is defined in forward declaration instead of actual declarationor if derivedfriend is not usedbut what is wrong with the original code,['c++'] +890029,trying to parse requestbody from post in django for some reason i cannot figure out why django is not handling my requestbody content correctlyit is being sent in json format and looking at the network tab in dev tools shows this as the request payloadcreator creatorname content postcontent date 04212015which is exactly how i want it to be sent to my apiin django i have a view that accepts this request as a parameter and just for my testing purposes should print requestbodycontent to the console of course nothing is being printed out but when i print requestbody i get thisbcreatorcreatornamecontentpostcontentdate04212015so i know that i do have a body being senti have tried using json jsonloadsrequestbody to no avail either printing json after setting that variable also returns nothing,['python'] +890047,ignore a project in visual studio while debugging in visual studio if you have a solution with many projects is it possible to instruct the debugger to ignore some of the projects to treat them as external dlls in that sensewe have a lot of helper code that i would like to debug around for example if i am at a function call and i step into it i would like to skip over ioc code and base class framework code and step into the meat of the classes i am working on most of the stuff i would like to step over are in support assembliesi would like to avoid unloading projects since other team members are actively working on those parts and i want to pick up their changes when i get latest from source control similarly i do not want to set up an alternate solution for the same reason it is also not practical to put debugger attributes on other peoples codeif there is a way to instruct vs that i am only interested in particular assemblies that would be ideal,['.net'] +890064,iphone 6 mobile safari ios 8 landscape with tabs open and bootstrap navbarfixedtop will not close when open i have run into a bug with bootstraps navbarfixedtop with the iphone 6s mobile safari in landscape on ios 8 the bug only happens with other tabs openhere is how to replicate it1 go to on your iphone 6 in landscape a be sure you have one other tab open2 scroll down the page without opening the collapse3 once safaris status bar the url and tabs goes away open the navbar4 scroll back up so that safaris status bar with tabs comes back up5 try to close the navbar i had this bug in ios 7 but was able to fix it by adding the viewport minimalui meta i have tested my iphone 6 and the 6 iphone simulator with the latest version of ios 8 it appears the tabs are to blame since the regular iphone 6 does not have this problem because the tabs do not show on the status bar i would imagine this bug goes beyond just bootstrap though but applies to any fixed element on the topscript srcscriptlink href relstylesheet div classtosticky navbarfixedtop div classnavcontainer div classnavbar div classnavbarheader a typebutton classnavbartoggle btnsecondary btn datatogglecollapse datatargetnavbarex1collapse main menu a div div classcollapse navbarcollapse navbarex1collapse ul classnav navbarnav rolemenubar unless submenu li classactive navhome firstli a href rolemenuitemhomea li li classnavdot navhome img src alt rolepresentation li if submenu li classdropdown a href datatoggledropdown classdropdowntoggle rolebutton ariaexpandedfalseaboutb classcaretba ul classdropdownmenu rolemenu li class a hrefabout rolemenuitemchairs welcomea li li class a hrefabouthistory rolemenuitemhistorya li li class a hrefaboutcampbellhall rolemenuitemcampbell halla li li class a hrefaboutfaqs rolemenuitemfaqsa li li class a hrefaboutjobsandfellowships rolemenuitemjobs amp fellowshipsa li li class a hrefaboutintegritystatement rolemenuitemintegrity statementa li li class a hrefaboutcontact rolemenuitemcontacta li ul li li classnavdot img src alt rolepresentation li if submenu li classdropdown a href datatoggledropdown classdropdowntoggle rolebutton ariaexpandedfalsepeopleb classcaretba ul classdropdownmenu rolemenu li classhiddenxs dropdownsubmenu a hrefpeoplefaculty rolemenuitemfacultyb classcaretba li if submenu repeats previous code but this will show only on mobile to expose third tier navigation li classvisiblexs dropdownsubmenu a href classtriggerfacultyb classcaretba ul classdropdownmenu submenu rolemenu li class a hrefpeoplefacultycurrent rolemenuitemcurrenta li li class a hrefpeoplefacultyemeriti rolemenuitememeritia li ul li li class a hrefpeopleresearchers rolemenuitemresearchersa li li class a hrefpeoplepostdocs rolemenuitempostdocsa li li class a hrefpeoplevisitingscholars rolemenuitemvisiting scholarsa li li classhiddenxs dropdownsubmenu a hrefpeoplegraduatestudents rolemenuitemgraduate studentsb classcaretba li if submenu repeats previous code but this will show only on mobile to expose third tier navigation li classvisiblexs dropdownsubmenu a href classtriggergraduate studentsb classcaretba ul classdropdownmenu submenu rolemenu li classa hrefpeoplegraduatestudentscurrent rolemenuitemcurrenta li li classa hrefpeoplegraduatestudentsalumni rolemenuitemalumnia li ul li li class a hrefpeoplestaff rolemenuitemstaffa li ul li li classnavdot img src alt rolepresentation li if submenu li classdropdown a href datatoggledropdown classdropdowntoggle rolebutton ariaexpandedfalsenews amp eventsb classcaretba ul classdropdownmenu rolemenu li class a hrefnews rolemenuitemdepartment newsa li li class a hrefnewsevents rolemenuitemdepartment eventsa li li class a href rolemenuitem classexternal target blankcampus calendara li li class a hrefnewsnewsletters rolemenuitemnewslettersa li ul li li classnavdot img src alt rolepresentation li if submenu li classdropdown a href datatoggledropdown classdropdowntoggle rolebutton ariaexpandedfalseacademic programsb classcaretba ul classdropdownmenu rolemenu li classhiddenxs dropdownsubmenu a hrefprogramsundergraduateprogram rolemenuitemundergraduateb classcaretba li if submenu repeats previous code but this will show only on mobile to expose third tier navigation li classvisiblexs dropdownsubmenu a href classtriggerundergraduateb classcaretba ul classdropdownmenu submenu rolemenu li classa hrefprogramsundergraduateprogram rolemenuitemundergraduate overviewa li li classa hrefprogramsundergraduateprogramastrophysicsmajor rolemenuitemrequirements of the astrophysics majora li li classa hrefprogramsundergraduateprogramastrophysicsdeclaration rolemenuitemdeclaring the majora li li classa href rolemenuitem classexternal target blankhow to applya li li classa hrefprogramsundergraduateprogramundergraduateresources rolemenuitemundergraduate resourcesa li li classa hrefprogramsundergraduateprogramundergraduatestudentlearninginitiative rolemenuitemundergraduate student learning initiativea li li classa hrefprogramsundergraduateprogrampolicyonacademicmisconduct rolemenuitempolicy on academic misconducta li ul li li classhiddenxs dropdownsubmenu a hrefprogramsgraduateprogram rolemenuitemgraduateb classcaretba li if submenu repeats previous code but this will show only on mobile to expose third tier navigation li classvisiblexs dropdownsubmenu a href classtriggergraduateb classcaretba ul classdropdownmenu submenu rolemenu li classa hrefprogramsgraduateprogram rolemenuitemgraduate overviewa li li classa hrefprogramsgraduateprogramgraduaterequirements rolemenuitemdegree requirementsa li li classa hrefprogramsgraduateprogramgraduateapply rolemenuitemhow to applya li li classa hrefprogramsgraduateprogramgraduateresources rolemenuitemgraduate resourcesa li li classa hrefprogramsgraduateprogramteachingopportunities rolemenuitemteaching opportunitiesa li li classa hrefprogramsgraduateprogramstudentservices rolemenuitemstudent servicesa li ul li li classhiddenxs dropdownsubmenu a hrefcourses rolemenuitemcoursesb classcaretba li if submenu repeats previous code but this will show only on mobile to expose third tier navigation li classvisiblexs dropdownsubmenu a href classtriggercoursesb classcaretba ul classdropdownmenu submenu rolemenu li class active 3 a hrefcoursesundergraduate2015su rolemenuitem summer 2015 a undergraduate a li li class a hrefcoursesundergraduate2015sp rolemenuitem spring 2015 a undergraduate a li li class active 3 a hrefcoursesgraduate2015su rolemenuitem summer 2015 a graduate a li li class a hrefcoursesgraduate2015sp rolemenuitem spring 2015 a graduate a li ul li li class a hrefprogramsfinancialaid rolemenuitemfinancial aida li li class a hrefprogramsstudentawards rolemenuitemstudent prizes and awardsa li ul li li classnavdot img src alt rolepresentation li if submenu li classdropdown a href datatoggledropdown classdropdowntoggle rolebutton ariaexpandedfalseprospective studentsb classcaretba ul classdropdownmenu rolemenu li class a hrefprospectivestudents rolemenuitemwhy berkeley astronomya li li class a hrefprospectivestudentstuition rolemenuitemtuitiona li li class a hrefprospectivestudentsunexandsummersessions rolemenuitemunex and summer sessionsa li li class a hrefprospectivestudentsaboutberkeley rolemenuitemabout berkeleya li li class a hrefprospectivestudentsdiversitystatement rolemenuitemstatement on diversitya li ul li li classnavdot img src alt rolepresentation li if submenu li classdropdown a href datatoggledropdown classdropdowntoggle rolebutton ariaexpandedfalseresearch amp facilitiesb classcaretba ul classdropdownmenu rolemenu li class a hrefresearchfacilities rolemenuitemfacilitiesa li li class a hrefresearchfacilitiesorganizedresearchunits rolemenuitemorganized research unitsa li li class a hrefresearchfacilitiesresearchopportunities rolemenuitemresearch opportunitiesa li li class a hrefresearchfacilitiesprojects rolemenuitemprojectsa li li class a hrefresearchfacilitieslabs rolemenuitemlabsa li li class a hrefresearchfacilitieslibraries rolemenuitemlibrariesa li ul li li classnavdot img src alt rolepresentation li if submenu li classdropdown a href datatoggledropdown classdropdowntoggle rolebutton ariaexpandedfalsedepartment resourcesb classcaretba ul classdropdownmenu rolemenu li class a hrefdepartmentresources rolemenuitemforms and documentsa li li class a hrefdepartmentresourcesastronomycomputingservices rolemenuitemcomputing at berkeley astronomya li li class a hrefdepartmentresourcescampusservices rolemenuitemcampus shared servicesa li li class a hrefdepartmentresourcesaccessandbuilding rolemenuitemaccess amp buildinga li li class a hrefdepartmentresourceshostingvisitors rolemenuitemhosting speakers amp visitorsa li li class a hrefdepartmentresourcesbuildingprocedures rolemenuitembuilding proceduresa li li class a hrefdepartmentresourcescampusresources rolemenuitemcampus resourcesa li ul li li classnavdot img src alt rolepresentation li if submenu li classdropdown lastli a href datatoggledropdown classdropdowntoggle rolebutton ariaexpandedfalsefriends amp fansb classcaretba ul classdropdownmenu rolemenu li class a hrefastronomyfans rolemenuitemoutreacha li li class a hrefastronomyfansmakeagift rolemenuitemmake a gifta li li class a hrefastronomyfansaskanastronomer rolemenuitemask an astronomera li li class a hrefastronomyfanslocalresources rolemenuitemlocal resourcesa li li class a hrefastronomyfansmerchanthise rolemenuitemdepartment merchanthisea li ul li ul form actionsearch clasearch form visiblexs navbarform navbarright methodpost rolesearch div classinputgroup input classformcontrol inputsm search text namesearch text typetext placeholder span classinputgroupbtn button typesubmit classbtn btncolor btnsmspan classglyphicon glyphiconsearchspanspan clasronlysearchspan button span div form div div divdivi have yet to find a work around any ideas,"['html', 'css']" +890135,nsuserdefaults initwithsuitename persisting after deleting app i have an issue where if i store any data using nsuserdefaults alloc initwithsuitenamesuite name the data persists even after deleting the app is this supposed to happen,"['ios', 'objective-c']" +890205,mystery console error with iohidfamily for one of my projects this error message in xcodes console happens every time i run a build in the ios simulator it is been happening for over a year and i thought it would eventually go away with an update to xcode i have dereferenced and relinked all the frameworks and i am not explicitly calling anything from the iohidfamily whatever that is it does not seem to affect my program execution but i would really like to figure out why it dumps all this every time20150421 182013997 vectorz beta123701453236 error loading systemlibraryextensionsiohidfamilykextcontentspluginsiohidlibplugincontentsmacosiohidlib dlopensystemlibraryextensionsiohidfamilykextcontentspluginsiohidlibplugincontentsmacosiohidlib 262 no suitable image found did find systemlibraryextensionsiohidfamilykextcontentspluginsiohidlibplugincontentsmacosiohidlib macho but not built for ios simulator20150421 182013997 vectorz beta123701453236 cannot find function pointer iohidlibfactory for factory 13aa9c446f1b11d4907c05028f18d5 in cfbundlecfplugin 0x78da9a80 systemlibraryextensionsiohidfamilykextcontentspluginsiohidlibplugin bundle not loaded20150421 182013997 vectorz beta123701453236 error loading systemlibraryextensionsiohidfamilykextcontentspluginsiohidlibplugincontentsmacosiohidlib dlopensystemlibraryextensionsiohidfamilykextcontentspluginsiohidlibplugincontentsmacosiohidlib 262 no suitable image found did find systemlibraryextensionsiohidfamilykextcontentspluginsiohidlibplugincontentsmacosiohidlib macho but not built for ios simulator20150421 182013997 vectorz beta123701453236 cannot find function pointer iohidlibfactory for factory 13aa9c446f1b11d4907c05028f18d5 in cfbundlecfplugin 0x78da9a80 systemlibraryextensionsiohidfamilykextcontentspluginsiohidlibplugin bundle not loaded20150421 182013998 vectorz beta123701453236 error loading systemlibraryextensionsiohidfamilykextcontentspluginsiohidlibplugincontentsmacosiohidlib dlopensystemlibraryextensionsiohidfamilykextcontentspluginsiohidlibplugincontentsmacosiohidlib 262 no suitable image found did find systemlibraryextensionsiohidfamilykextcontentspluginsiohidlibplugincontentsmacosiohidlib macho but not built for ios simulator20150421 182013998 vectorz beta123701453236 cannot find function pointer iohidlibfactory for factory 13aa9c446f1b11d4907c05028f18d5 in cfbundlecfplugin 0x78da9a80 systemlibraryextensionsiohidfamilykextcontentspluginsiohidlibplugin bundle not loaded20150421 182013998 vectorz beta123701453236 error loading systemlibraryextensionsiohidfamilykextcontentspluginsiohidlibplugincontentsmacosiohidlib dlopensystemlibraryextensionsiohidfamilykextcontentspluginsiohidlibplugincontentsmacosiohidlib 262 no suitable image found did find systemlibraryextensionsiohidfamilykextcontentspluginsiohidlibplugincontentsmacosiohidlib macho but not built for ios simulator20150421 182013998 vectorz beta123701453236 cannot find function pointer iohidlibfactory for factory 13aa9c446f1b11d4907c05028f18d5 in cfbundlecfplugin 0x78da9a80 systemlibraryextensionsiohidfamilykextcontentspluginsiohidlibplugin bundle not loaded,"['ios', 'objective-c']" +890212,cannot find symbol class generated for dagger 2 i just started doing dependency injection using dagger 2 when i spun up my modules components and tried to build my application gradle threw the error error4 24 error cannot find symbol class generatedi dug into it and found that the error is in one of the classes dagger generates to do di the particular class that is missing was javaxannotationgenerated and the line throwing the error is the line that anntotates a dagger generated class as generateddaggerinternalcodegencomponentprocessorthis question helped in finding the solution which is to add the javax package as a dependency by adding the line compile orgglassfishjavaxannotation100b28 to my gradle build file this led to a successful buildmy question is why is that not added as a transitive dependency for dagger or why has not anyone else faced this particular issue i assume so since i could not find any question here regarding this,"['java', 'android']" +890272,fragment back stack does not work when extending appcompatactivity i am using the new appcompatactivity introduced in the appcompat library version 221when i extend this activity the hardware back button no longer pops the back stack of my fragments it closes the activity insteadhere is how i am changing fragments in my activity public void changefragmentfragment f fragmenttransaction ft getfragmentmanagerbegintransaction ftreplaceridfragment holder f ftaddtobackstacknull ftcommitif i change mainactivity extends appcompatactivity to mainactivity extends activity the problem goes away and i am able to go backwards through my fragmentschanging calls to getfragmentmanager to getsupportfragmentmanager results in devices running android 50 losing the material theme which was the main reason for implementing appcompatactivity in the first placethe style referenced in my manifest application androidthemestyleappthemestyle nameapptheme parentthemeappcompatlight item namecolorprimarycolorprimary material lightitem item namecolorprimarydarkcolorprimary dark material lightitem item namecoloraccentcoloraccent material lightitemstyle,['android'] +890273,does pow work for int data type in c i was simply writing a program to calculate the power of an integer but the output was not as expected it worked for all the integer numbers except for the power of 5my code isinclude stdiohinclude mathhint mainvoid int ab printfenter the number scanfnda bpowa2 printfndbthe output is something like thisenter the number 2 4enter the number 5 24enter the number 4 16enter the number 10 99cannot we use pow function for int data type,['c'] +890365,upgraded to appcompat v2210 and now getting illegalargumentexception appcompat does not support the current theme features i have just upgraded my app to use the newly released v2210 appcompat and i am now getting the following exception when i open my appcaused by javalangillegalargumentexception appcompat does not support the current theme features at androidsupportv7appappcompatdelegateimplv7ensuresubdecorappcompatdelegateimplv7java360 at androidsupportv7appappcompatdelegateimplv7setcontentviewappcompatdelegateimplv7java246 at androidsupportv7appappcompatactivitysetcontentviewappcompatactivityjava106how do i fix it,['android'] +890386,should i use the initializeondemand idiom and if so how i have the following code mytype x do something dangerous if some condition barx else if another condition which may depend on previous if else bazx the idea is that in some cases which are perhaps difficultinconvenient to determine in advance i need to use x but in the cases i do not need to use it trying to initialize it may be bad say could crash my processnow it seems like what i need to be using is an initializeondemand holder the link focuses on java so heres a sketch some kind of wrappermytype or wrappermytype do something dangerous with a get method such that the first get calls do something dangerous and later gets just pass the value the first call obtainedis this indeed an appropriate approach hereis there some standardish implementation of this idiom or a variant of itnotesi could use boostoptional but that would be a bit cumbersome and also twist the intended use it is recommended to use optionalt in situations where there is exactly one clear to all parties reason for having no value of type t and where the lack of value is as natural as having any regular value of t,['c++'] +890415,proper wordbreaking with css and js now i am working on project where users can create their own time lines each timeline has events there is a problem with event titleuser can create event with very long title for example12312312312312312312312313211233123213133gsfsfsfsdfserwerwerwerwesdfsdfor 12n 34 n no341 nno nn 34 o341412 34212 14 no342 12 no341 nno n341 n 14nn 12 ntitle thisplays with h3 and wordbreakbreakallexamplesi suppose that for the first example it works well enough but the second example violates the rules of hyphenationis there any plugin that will help or maybe proper css rules,"['javascript', 'jquery', 'html', 'css']" +890507,how to get date in proper format in symfony2 writing own console command how to get date in proper format in symfony2 writing own console commandplantype alldbnamegetplantypeplanendon alldbnamegetnextpaymentdatep planendonformathis on ymdcurrentdate new datetimedate date modifyp 5 dayoutputwritelndategetting error in console,['php'] +890534,usage of signed vs unsigned variables for flags in c is there any good practice or habit of using signed variables vs unsigned variables for flags personally i would use unsigned variable but i can see even signed variable used for flags in some code i mean especially in library interface where it mattersudpatei cannot accept answer use enum because it is implementation dependent and this it cannot be used in library interface,['c++'] +890623,update jquery variable on ajax complete im still a beginner with jsi use ajax for filtering content in wordpress so i need to send 2 variables to php but the problem is once i have navigated further one of the variables needs to change in html the data gets changed but jquery which runs on documentready uses the initial variable how can i make the variable refresh on ajax completehere is my codejquerydocumentreadyfunction taxfilterclick functionevent if eventpreventdefault eventpreventdefault else eventreturnvalue false var selecetd taxonomy thisattrid var persondata contentdataid data action filter posts afp nonce afp varsafp nonce taxonomy selecetd taxonomy person persondata ajax type post datatype json url afp varsafp ajax url data data success function data textstatus xmlhttprequest showcontenthtml dataresponse error function mlhttprequest textstatus errorthrown projectshtml error 404 from another function the dataid in html gets a new value but i need the jquery to get the new value aswelledit i need the persondata to be updated in my click function the dataid value of content gets updated on ajaxcomplete it is done by another click function which gets the value from php,"['javascript', 'php', 'jquery']" +890654,render new element onclick in reactjs i am new to react and am trying to render a new element onclick var loginbutton reactcreateclass clickhandle function thisrememberme active localforagegetitemrememberme function err key return key if thisremembermeactive true thisremembermeactive checked documentgetelementbyidloginformsubmit else reactrenderwanttoremember documentgetelementbyidloginbuttonhere return thisremembermeactive this is the element that should appearvar wanttoremember reactcreateclass getinitialstate function return position absolute thisplay block top 20px width 100px height 100px render function return div classnamerememberpopup stylethisstate div classnamerow div classnamestaylogin div classnamecolmd4 label forcheckboxangemeldet bleibenlabel div div classnamecolmd1 input typecheckbox idcheckbox nameremember div div div div but it does not appear instead react renders this htmlwanttoremember datareactid1wanttorememberi am pretty sure i am doing some pretty basic stuff wrong but cannot figure out what is not it possible to call different elements like this,['javascript'] +890690,can someone comprehensively explain the webrtc stats api i am finishing a webrtc project for a graduate course in video communications it is essentially a video conference chat room everyone that connects to the server is added to the conference i need to use the stats api in webrtc to show some relevant performance statistics for each rtcpeerconnection packets lost per second jitter retransmission etc this helps to observe performance cost as more peers are added to the conversation however the api seems to not be fully fleshed out yet it is apparently gone through some refreshes and does not quite match up to some w3c specs i have seen though perhaps it is out of date or i just do not understand nuances of reading the spec neither would surprise memy invocation of the api is similar to this one but interpreting the data is not straightforward for instance when looping through all items in rtcstatsreportresults many of them have duplicate names and confusing values i cannot seem to find any information about their meaning if anyone can assist me in understanding some of the important ones or point me to the lost city of gold eg proper documentation i would be grateful,['javascript'] +890800,an algorithm for iterating over a rectangular area inside a 1 dimensional array bitmapping this is an odd question which i had a tough time writing a title fori am working with pixels bitmaps more specifically and cannot figure out the simple maths for pragmatically accessing each array cellmy canvas is n16 x 16 pixels and is always 1 or greaterheres a photo of a basic and 2 canvaswhat i want my magical algorithm to do is run from 0 to 495 without touching that lighter grey area then go from 16 to 512 which is actually cell 511 my bad without touching the dark grey areaso 0 to 15 skip 16 to 31 followed by 32 to 47 etcand for and 3in this case it would be 0735 skipping the lighter grey areas 16751 skipping the areas on each side and 32767 skipping the darker grey areaswhat i triedheres an extract from my code hopefully it is useful and shows what i tried already it is the part that figures out the value for idxpos let us say length 3 for nowfor int character 0 character length character in case youre wondering it grabs 16x16 characters from an ascii spritesheet charpos stringcharacter 16 16 runs through the spritesheet character map this is a huge 16x1520 bitmap for int pixel 0 pixel 16 16 pixel ignore this just me messing around with pixel tinting r charmapcharpos pixel 0 0xff 255 u g charmapcharpos pixel 8 0xff 255 v b charmapcharpos pixel 16 0xff 255 w newcolour rgbr g b this is the part i am stuck on idxpos pixel character 16 16 bitmapidxpos charmapcharpos j you probably get the idea it sounds dead simple to me but i cannot figure it outoh and i am not interested in some magical library that can handle all my bitmap stuff for me i am not in a position where i can use one,['c++'] +890874,how to solve this exception could not find a setter for property productcode in class i am getting the following exceptioncould not find a setter for property productcodein class orderitemclass the property productcode is one of my table keyssee how is the property declaration in the classpublic class orderitem entitybase public virtual short company get set public virtual int order get set public virtual string seri get set public virtual string productcode get set public virtual string crop get set below this my mappingpublic maporderitem tableiped compositeid keypropertyc ccompany c emp keypropertyc corder p ped keypropertyc cseri s ped keypropertyc cproductcode c psv mapc cc cfonotnullable mapc canothercurrencycolumnv ipe checked doubts similar to mine but the solutions do not solve my problemalready tried to perform the mapping usingc cproductcodeaccessreadonlyc cproductcodeaccessfieldc cproductcodereadonlyto run the query directly in the database does not show me any error only the correct data,['c#'] +890900,why use rematch when research can do the same thing from the documentation it is very clear thatmatch apply pattern match at the beginning of the stringsearch search through the string and return first matchand search with and without rem flag would work the same as matchthen why does python have match is not it redundantare there any performance benefits to keeping match in python,['python'] +890901,what is the right combination of prefixes for css transitions and transforms what would be the right way to prefix this css in order to cover the widest range of browsers and versionsversion 1 webkittransition webkittransform 3s easeinout moztransition moztransform 3s easeinout mstransition mstransform 3s easeinout otransition otransform 3s easeinout transition transform 3s easeinout webkittransform rotatex30deg moztransform rotatex30deg mstransform rotatex30deg otransform rotatex30deg transform rotatex30degor version 2 webkittransition transform 3s easeinout moztransition transform 3s easeinout mstransition transform 3s easeinout otransition transform 3s easeinout transition transform 3s easeinout webkittransform rotatex30deg moztransform rotatex30deg mstransform rotatex30deg otransform rotatex30deg transform rotatex30degit appears to me that when using vendor prefixes on a transition property i should also target the vendor prefixed attribute i want to transitioni cannot really find any closure to this,['css'] +891109,possible to modify cookie values in a jquery ajax request i am working on a chrome extension that would allow users to record all http requests for a site modify pieces of the request and then resend iti am hoping to use jquerys ajax method to construct and send the modified request i have been able to construct the other parts of the request but as far as i can tell there is no way to include cookie values in the request just to be clear i am not trying to create a cookie on the browser i am trying to modify the cookie value that will be sent along as part of the http request using jquerys ajax methodcan this be done with jquerys ajax if not is there anyway to do it in javascript,"['javascript', 'jquery']" +891136,hibernate sql in clause making cpu usage to 100 in my java application i am using sql server and hibernate3 with ejb when i tried to execute a select query with in clause the db server cpu usage reaches to 100 but when i tried to run the same query in sql management studio the query is running without any cpu spikes application server and db server are two different machines my table has the following schemacreate table student table student id bigint not null identity class id bigint not null student first name varchar100 not null student last name varchar100 roll no varchar100 not null primary key student id constraint uk studentunique 1 unique class id roll nothe table contains around 10k records my query is select student id from student table where roll no in a101a102a103a250in clause contains 250 values when i tried to run above query in sql management studio the result is retrieved within 1 seconds and without any cpu spikes but when i tried to run the same query through hibernate the cpu spikes reaches to 100 for around 60 seconds and result is retrieved around 60 seconds the hibernate query iscriteria studentcriteria sessioncreatecriteriastudenttoclastudentcriteriaaddrestrictionsinrollno rollnolists rollnolists is an arraylist contains 250 stringsstudentcriteriasetprojectionprojectionsprojectionlistaddprojectionspropertystudentidlistlong studentids new arraylistlonglistlong results arraylistlong studentcriterialistif results null resultssize 0 studentidsaddallresultsreturn studentidswhat is the problem why it is so if the same query is running through management studio the result is retrieved without any spikes and result is retrieved within 1 seconds any solutionedit1my hibernate generated query isselect this student id as y0 from student table this where this roll no in edit2my execution planthis was after indexing roll nocreate index i student roll no on student table roll no,['java'] +891148,android inapp purchase v3 error authentication is required i am implementing google inapp purchase v3 and followed all steps stated over here as well in official documentation here i have uploaded my app in google playstore for alpha testing and i have downloaded that from playstore url into my real device but it giving me errorerrorauthentication is required you need to sign into your google accountmy code for inapp purchase is herepublic class buypointsfragment extends fragmentin app billing variable start debug tag for logging static final string tag commyapp does the user have the premium upgrade boolean mispremium false does the user have an active subscription to the infinite gas plan boolean msubscribedtoinfinitegas false skus for our products the premium upgrade nonconsumable and gas consumable static final string sku premium premium static final string sku gas gas sku for our subscription infinite gas static final string sku infinite gas infinite gas arbitrary request code for the purchase flow static final int rc request 101 graphics for the gas gauge static int tank res ids how many units 14 tank is our unit fill in the tank static final int tank max 4 current amount of gas in tank in units int mtank the helper object iabhelper mhelper in app billing variable endoverride public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate inapp load game data loaddata string base64encodedpublickey base64key from publisher account some sanity checks to see if the developer that is you really followed the instructions to run this sample do not put these checks on your app if base64encodedpublickeycontainsconstruct your throw new runtimeexception please put your apps public key in mainactivityjava see readme if getactivitygetpackagenamestartswithcommyappactivity throw new runtimeexception please change the samples package name see readme create the helper passing it our context and the public key to verify signatures with logdtag creating iab helper mhelper new iabhelpergetactivity base64encodedpublickey enable debug logging for a production application you should set this to false mhelperenabledebugloggingtrue start setup this is asynchronous and the specified listener will be called once setup completes logdtag starting setup mhelperstartsetupnew iabhelperoniabsetupfinishedlistener public void oniabsetupfinishediabresult result logdtag setup finished if resultissuccess oh noes there was a problem complaingetstringrstringproblem setting inapp billing result return have we been thisposed of in the meantime if so quit if mhelper null return iab is fully set up now let us get an inventory of stuff we own logdtag setup successful querying inventory mhelperqueryinventoryasyncmgotinventorylistener in app billing code end here in app billing methods start herepublic void inappcall setwaitscreentrue logdtag launching purchase flow for gas todo for security generate your payload here for verification see the comments on verifydeveloperpayload for more info since this is a sample we just use an empty string but on a production app you should carefully generate this string payload mhelperlaunchpurchaseflowgetactivity sku gas rc request mpurchasefinishedlistener payload updates ui to reflect model public void updateui update the car color to reflect premium status or lack thereof imageviewfindviewbyidridfree or premiumsetimageresourcemispremium rdrawablepremium rdrawablefree upgrade button is only visible if the user is not premium findviewbyidridupgrade buttonsetvisibilitymispremium viewgone viewvisible get infinite gas button is only visible if the user is not subscribed yet ridinfinite gas buttonsetvisibilitymsubscribedtoinfinitegas viewgone viewvisible update gas gauge to reflect tank status if msubscribedtoinfinitegas imageviewfindviewbyidridgas gaugesetimageresourcerdrawablegas inf else int index mtank tank res idslength tank res idslength 1 mtank imageviewfindviewbyidridgas gaugesetimageresourcetank res idsindex enables or thisables the please wait screen void setwaitscreenboolean set findviewbyidridscreen mainsetvisibilityset viewgone viewvisible findviewbyidridscreen waitsetvisibilityset viewvisible viewgone void complainstring message logetag trivialdrive error message alerterror message void alertstring message alertdialogbuilder bld new alertdialogbuildergetactivity bldsetmessagemessage bldsetneutralbuttonok null logdtag showing alert dialog message bldcreateshow void savedata warning on a real application we recommend you save data in a secure way to prevent tampering for simplicity in this sample we simply store the data using a sharedpreferences sharedpreferenceseditor spe getactivitygetpreferencesgetactivitymode privateedit speputinttank mtank specommit logdtag saved data tank stringvalueofmtank void loaddata sharedpreferences sp getactivitygetpreferencesgetactivitymode private mtank spgetinttank 2 logdtag loaded data tank stringvalueofmtank were being destroyed it is important to thispose of the helper here override public void ondestroy superondestroy very important logdtag destroying helper if mhelper null mhelperthispose mhelper null listener that is called when we finish querying the items and subscriptions we own iabhelperqueryinventoryfinishedlistener mgotinventorylistener new iabhelperqueryinventoryfinishedlistener public void onqueryinventoryfinishediabresult result inventory inventory logdtag query inventory finished have we been thisposed of in the meantime if so quit if mhelper null return is it a failure if resultisfailure complaingetstringrstringfailed to query inventory result return logdtag query inventory was successful check for items we own notice that for each purchase we check the developer payload to see if it is correct see verifydeveloperpayload do we have the premium upgrade purchase premiumpurchase inventorygetpurchasesku premium mispremium premiumpurchase null verifydeveloperpayloadpremiumpurchase logdtag user is mispremium premium not premium do we have the infinite gas plan purchase infinitegaspurchase inventory getpurchasesku infinite gas msubscribedtoinfinitegas infinitegaspurchase null verifydeveloperpayloadinfinitegaspurchase logdtag user msubscribedtoinfinitegas has does not have infinite gas subscription if msubscribedtoinfinitegas mtank tank max check for gas delivery if we own gas we should fill up the tank immediately purchase gaspurchase inventorygetpurchasesku gas if gaspurchase null verifydeveloperpayloadgaspurchase logdtag we have gas consuming it mhelperconsumeasyncinventorygetpurchasesku gas mconsumefinishedlistener return updateui setwaitscreenfalse logdtag initial inventory query finished enabling main ui verifies the developer payload of a purchase boolean verifydeveloperpayloadpurchase p string payload pgetdeveloperpayload todo verify that the developer payload of the purchase is correct it will be the same one that you sent when initiating the purchase warning locally generating a random string when starting a purchase and verifying it here might seem like a good approach but this will fail in the case where the user purchases an item on one device and then uses your app on a different device because on the other device you will not have access to the random string you originally generated so a good developer payload has these characteristics 1 if two different users purchase an item the payload is different between them so that one users purchase cannot be replayed to another user 2 the payload must be such that you can verify it even when the app was not the one who initiated the purchase flow so that items purchased by the user on one device work on other devices owned by the user using your own server to store and verify developer payloads across app installations is recommended return true callback for when a purchase is finished iabhelperoniabpurchasefinishedlistener mpurchasefinishedlistener new iabhelperoniabpurchasefinishedlistener public void oniabpurchasefinishediabresult result purchase purchase logdtag purchase finished result purchase purchase if we were thisposed of in the meantime quit if mhelper null return if resultisfailure complaingetstringrstringerror purchase result setwaitscreenfalse return if verifydeveloperpayloadpurchase complaingetstringrstringerror purchase authenitcity failed setwaitscreenfalse return logdtag purchase successful if purchasegetskuequalssku gas bought 14 tank of gas so consume it logdtag purchase is gas starting gas consumption mhelperconsumeasyncpurchase mconsumefinishedlistener else if purchasegetskuequalssku premium bought the premium upgrade logdtag purchase is premium upgrade congratulating user alertgetstringrstringthank you updgraing premium mispremium true updateui setwaitscreenfalse else if purchasegetskuequalssku infinite gas bought the infinite gas subscription logdtag infinite gas subscription purchased alertthank you for subscribing to infinite gas msubscribedtoinfinitegas true mtank tank max updateui setwaitscreenfalse called when consumption is complete iabhelperonconsumefinishedlistener mconsumefinishedlistener new iabhelperonconsumefinishedlistener public void onconsumefinishedpurchase purchase iabresult result logdtag consumption finished purchase purchase result result if we were thisposed of in the meantime quit if mhelper null return we know this is the gas sku because it is the only one we consume so we do not check which sku was consumed if you have more than one sku you probably should check if resultissuccess successfully consumed so we apply the effects of the item in our game worlds logic which in our case means filling the gas tank a bit logdtag consumption successful provisioning mtank mtank tank max tank max mtank 1 savedata alertyou filled 14 tank your tank is now stringvalueofmtank 4 full else complainerror while consuming result updateui setwaitscreenfalse logdtag end consumption flow override public void onactivityresultint requestcode int resultcode intent data logdtag onactivityresult requestcode resultcode data if mhelper null return pass on the activity result to the helper for handling if mhelperhandleactivityresultrequestcode resultcode data not handled so handle it ourselves heres where youd perform any handling of activity results not related to inapp billing superonactivityresultrequestcode resultcode data else logdtag onactivityresult handled by iabutil in app billing method end heremy products are managed products in developer account inapp productseditwhen i use androidtestpurchased as a sku then it works fine and as i change my sku with my product id then it giving me error authentication is required you need to sign into your google account,['android'] +891378,how to get mouse position on screen in wpf it works within a specific control but it does not work out the specific controlhow to get mouse position and use mouse events independently of any control just directly from screen without platform invoke2 needed pointsmouse events when mouse is not within a control but on a screenmouse position when mouse is not within a control but on a screenit should be solved without using platform invokenext two do not worksystemwindowsinputmousegetpositionthisdoes not get mouse position out a specific controlsystemwindowsformscursorpositionxsystemwindowsformscursorposition does not work because it has no types in a wpf app but it works in a windows forms appintellisense gets systemwindowsformscursorposition but it does not get any type of position hence i cannot getpositionx positionyandpoint pointtowindow mousegetpositionthispoint pointtoscreen pointtoscreenpointtowindowdoes not get mouse position out a specific control,"['c#', '.net']" +891411,android studio how to debug older version of android sdk stepbystep i have an android project targetting the android sdk v21 now i need to debug it on a device with android 44 ie sdk v20 how do i tell android studio to attach an older version of the source to the internal classes so that i can step through them,['android'] +891430,make image file visible in android gallery on lollipop i am trying to make some pictures that are taken in the app visible in the gallery so they can be shared and looked at outside of the app but i want to keep the images themselves inside the data directory of the app so when the app is deleted they get removed so they are stored in sdcardandroiddataappidpicturessubfolderi have looked at a lot of answers and for older versions of android both of the following solutions work but they do not seem to work in lollipopmediascannerconnectionscanfilethis new stringfiletostring new string imagejpeg new mediascannerconnectiononscancompletedlistener public void onscancompletedstring path uri uri logiexternalstorage scanned path logiexternalstorage uri uri uri contenturi urifromfilefileintent mediascanintent new intentintentaction media scanner scan filecontenturisendbroadcastmediascanintenti have tested this in a nexus 4 android 501 and a nexus 6 android 51 and it does not work in a nexus 7 android 422 it does work all 3 devices have a onmedia file in the sdcardandroiddata folder so no normal media scan should pick them updoes anyone know a work around to get this to work on all devicesandroid versions should this because of the nomedia file not work in the first place and is lollipop the only version that does this correctlyedit note that even a restart of the phone which should also trigger a rescan of files does not work and for good reason as the files are in a subfolder of a nomedia directory so any solution containing a media mounted broadcast is kind of useless i assume,['android'] +891432,what is wrong with this piece of code html php i have a simple function which has two parameters one for the image url and other for the attributes for the imagefunction image foundurlattributes ifgetimagesizeurl echo img srcurl attributes else echo img srcbase urlsite imagesimage not foundsvg attributes now what i am trying to do is create a clickable image if the image is found now this is the html codeecho div classpanelbodyecho div classcolmd12 collg12 colsm12 textcenterurl base urlproduct imagesresultproduct imageresultimage typeattributes height200px width100echo a hrefproductcomfullurlimage foundurlattributesaecho divecho divand this is the output i am gettingdiv classpanelbody div classcolmd12 collg12 colsm12 textcenter img srchttplocalhostnscproduct images7908076366784972032090jpg height200px width100 a hrefa divdivi do not know what is wrong here i am using bootstrap,"['php', 'html']" +891458,segfault in stdatomic load on linux using gcc 484 compiled with stdc11 mcx16include atomicstruct node tstruct pointer t node t ptr unsigned int count pointer t noexcept ptrnullptr count0 struct empty struct node t empty value stdatomicpointer t next node t nextpointer t int main node tnextload return 0gives a segfault when load is called how am i meant to initialize an atomic value,['c++'] +891467,using nuget package to deploy single file i want to createa nuget package with a single file is there a way to package a single file and then instruct the file as to where it should be placed within a visual studio project i was able to make a nuspec file and package a nuget package which contains the file in question however it is not possible to be installed inside of a packagemore specifically i have a configuration file which should be the same across many projects i want to be able to install a nuget package which can them be installed to place the configuration file in the correct locationthe nuspec file right now just specifies the basics about the metadata i then run nuget pack with that nuspec file and the configuration file in the directory this results in a nuget package with the configuration file in it which is uninstallablehere is what i have in the nuget package nowand the nuspec filexml version10package xmlns metadata idstylecopsettingsid version101version titlestylecopsettingstitle authorsclearspanauthors ownersclearspanowners descriptionstylecopsettingsdescription metadatapackage,['.net'] +891498,how to design filters for a generic pluggable collection i am developing a web application that features a timeline much like a facebook timeline the timeline itself is completely generic and pluggable it is just a generic collection of items anything with the proper interface dateable can be added to the collection and thisplayed on the timelineother components symfony bundles define models that implement the dateable interface and set up a provider that can find and return these models the code is much like thisclass timeline private providers filled by di public function find result foreach thisproviders as provider result array mergeresult providerfind return result the problem is that there needs to be a set of filters next to the timeline some filter options like date apply to all providers but most options do not for example most providers will be able to use the author filter option but not all some notification item are dynamically generated and do not have an authorsome filter options just apply to a single provider for example only event items have a location propertyi cannot figure out how to design a filter form that is just as modular as the timeline itself where should the available filter options be defined bundlespecific filter options could probably come from the bundle itself but how about filter options like user that can be used by multiple bundles and what if some filter options later become usable by multiple bundles for example only events have a location now but what if another module is added that also has items with a locationand how will each provider determine if the submitted filter form only contains options it understands if i set a location in the filter then the blogpostprovider should not return any messages because blog posts have no location but i cannot check for location in the filter because the blogpostbundle should not know about other providers and their filtering optionsany ideas on how i can design such a filter form,['php'] +891515,unclosed quote in a css block this snippet is red on firefox and blue on chrome who is right background red background blue a416 blocks sayssingle and double quotes must also occur in matching pairs and characters between them are parsed as a stringbut if or do not occur in matching pairs how should the syntax error be handled,['css'] +891569,is empty java file name working i started to learn java couple days ago and i have this burning question is empty java file name a valid source file name java,['java'] +891695,why does stringstartswithu2d2d always return true i was fiddling around with parsing in c and found that for every string i tried stringstartswithu2d2d will return true why is thatit seems it works with every char tried this code with net 45 the debugger did not breakfor char i charminvalue i charmaxvalue i ifitostringstartswithu2d2d debuggerbreak,['c#'] +891850,c type check in functions ignored required double provided int i have the following codeinclude iostreamusing namespace stdint dmultint a int b return 2abint mainvoid double a 33 double b 2 int c dmultab cout c endl return 0it compiles with mingw without problems the result is as i thought false is it a problem of the compiler that there is no warning that a function expecting integers but fed with doubles can compile without warning even if the input type is wrong does it mean that c ignores the input type of a function should not it realize that the function arguments have the wrong type,['c++'] +891881,bootstrap breakpoints need some clarification xs sm md lg so looking online i see some recent articles stating that the xs breakpoint is 480px and below others state 767 and below i had the understanding probably not correct that xs was for phones 480px and below colsm is for tablets 480 px to 767px etc however when i apply hiddenxs it seems to hide where i would expect my tablet view in the 480px to 767 range what am i doing wrong herethe columns snap to stacking at 480px but the hidden features and colxs do not seem to change at that screen width i am working with some crazy legacy code but i am fairly certain i have upgraded to the latest version of bootstrap,['css'] +891915,how to animate css top in jquery at a certain scroll location or when an element is visible i have a scrolltotop icon that appears when the window is scrolled down a bit the thing is when the window is scrolled to the bottom of the page it overlaps a div which i do not wanti would like to make it so the top position of scrolltotop gets animated upwards just a bit to avoid colliding with the div when the window is scrolled all the way to the bottomheres what i have so far jquery scroll to top animate inwindowscrollfunction if thisscrolltop 300 scrolltotopfadeout10cssright70 else scrolltotopfadein10cssright20 click event to scroll to topscrolltotopclickfunction html bodyanimatescrolltop 010 return false,['jquery'] +891983,switch control is not working on dialog in android version 50 i have used below switch in my application switch androidlayout widthwrap content androidlayout heightwrap content androidlayout centerhorizontaltrue androidtext androidthumbdrawabletoggle button color androidtextoffstringtext estimate androidtextonstringtext accurate androidtextcolorcolorwhite in above switch i am using toggle button colorxml to change the thumb color to green and red when switch is on and off respectivelyselector xmlnsandroid item androidstate checkedfalse androiddrawablecolorred item androidstate checkedtrue androiddrawablecolorgreen selectorif i add this switch to an activity layout and then its wokring perfectly as below image but if i add this switch on dialog using m dialogsetcontentviewrlayoutmylayout then switch looks like belownote that here mylayoutxml is a layout file in which i have added switchfor android version below 50 lollipop switch is working fine as i want note that for some reasons i am using themehololight in my application so i cannot use switchcompati know that a similar question has been asked here switch crashes when clicked on android 50and also it is reported here i have also tried the work around which is mentioned in above link to add drawable image for thumb and track but i do not understand why same switch is working on activity layout but not on dialogcan anybody please help me out with this,['android'] +892051,add index to jar file referencing external jar file i am trying a simple index creation on a jar file however it fails with jar i tmpvtkdicombinlibvtkdicomjarjavaiofilenotfoundexception tmpvtkdicombinlibvtkjar no such file or directory at javautilzipzipfileopennative method at javautilzipzipfileinitzipfilejava215 at javautilzipzipfileinitzipfilejava145 at javautiljarjarfileinitjarfilejava154 at javautiljarjarfileinitjarfilejava91 at suntoolsjarmaingetjarpathmainjava1052 at suntoolsjarmaingetjarpathmainjava1068 at suntoolsjarmaingenindexmainjava1084 at suntoolsjarmainrunmainjava269 at suntoolsjarmainmainmainjava1177on obvious workaround is simply cp usrsharejavavtkjar tmpvtkdicombinlibhowever it is ugly and errorprone is there any other way i can tell jar i where to search for a different vtkjar location i will need a portable solution which works on windowslinuxmacosxfor information the manifest is set to cat sourcejavamanifesttxtclasspath vtkjarfor information if i change it to cat sourcejavamanifesttxtclasspath usrsharejavavtkjarit gives a slightly different error jar i tmpvtkdicombinlibvtkdicomjarjavaiofilenotfoundexception tmpvtkdicombinlibusrsharejavavtkjar no such file or directory at javautilzipzipfileopennative method at javautilzipzipfileinitzipfilejava215 at javautilzipzipfileinitzipfilejava145 at javautiljarjarfileinitjarfilejava154 at javautiljarjarfileinitjarfilejava91 at suntoolsjarmaingetjarpathmainjava1052 at suntoolsjarmaingetjarpathmainjava1068 at suntoolsjarmaingenindexmainjava1084 at suntoolsjarmainrunmainjava269 at suntoolsjarmainmainmainjava1177for reference java versionjava version 170 75openjdk runtime environment icedtea 254 7u752542openjdk 64bit server vm build 2475b04 mixed mode,['java'] +892073,laravel auth to validate only adminsuperuser i am using laravel 5 on a windows dev machine i want to customize and use the auth middleware throughout my application to maintain authentication my use case is a standard one there are two or three classes of users admin and regular regular would be all users that are not admin the admin has the obvious role of backend management and hence has a separate routing group admin which should redirect an unlogged user to adminlogin i have set it up like soroutegroupmiddlewareauth prefix admin function routegetloginappauthcontrollergetlogin routepostloginappauthcontrollerpostloginwhen the login form is posted how do i ask auth to add a filter either that only validate from among those users where is admin is trueor ask it to first join a user and a userroles table to identify only users with an admin role,['php'] +892100,java synchronised list between threads best practice i am making a database logging engine when certain changes have happened these changes get pushed to a queue in a thread that processes 25 logobjects in the queue every 50msi was thinking of using a collectionssynchronizedlist to hold the objects i still need to process in the threadthe main application thread pushesses logobjects into the list via threadobjinstanceloglistaddnew logobjectsomething to log and in the thread i do logobject x loglistshift to process ithowever i feel like there might be better ways to do it or is this a perfectly acceptable approach or should i use arrayblockingqueue for his situation or another synchronised list object there are so many choicesthis is my first time working with threads so i am trying to figure out what the best approach is for a job queue and which objects to use to maintain itcan i just add things directly to the threaded lists or do i need to use a synchronised method for that in the threadthe questions are basicallywhere do i store a synchronised list of objects to process between two threads in the processing thread or the main thread what is the best practise to addremove items from the list via synchronised function or directly on the list objectwhat are my choices for list objects when building a job queue,['java'] +892103,responsive on mobile device with tables not working within iframe i am having an issue where my website looks off on an actual mobile device but when i resize the screen on my computer it looks just fine this is within an iframe also and looks fine outside of the iframe on a mobile device below is the actual url click on search for a player and you wills see the pageupdatelooks like someone else has this issue responsivetable width does not fit the container inside iframe on ios safaridesktop resizedgoogle chrome on iphone,['css'] +892175,lumen unpredictable output recently i installed lumen 504 mfw and ran into an issue with page load on default configuration i have unpredictable behavior of page load process sometimes it loads okay but sometimes instead of loading i am getting a download dialog with zero size unnamed file or it throws an exception likenotfoundhttpexception in applicationphp line 1109at first i want to say that other non lumenlaravel sites work fine server configuration apache 2412php 5671zend engine v260 with zend opcache v704devi think the problem is with php working through phpfpm because with fcgi configuration it seems to work welli tried notfoundhttpexception with lumen but that did not help me,['php'] +892381,how to update the timestamp on a photo or add the time zone on google photos using picasa web api i retrieve a photo from my google photo album and attempt to change the timestamp the time was wrong on my phone so trying to fix itvar service new picasaserviceexamplecoexampleapp1servicesetusercredentialsuid pwdalbumquery query new albumquerypicasaquerycreatepicasauridefaultpicasafeed feed servicequeryqueryvar entry picasaentryfeedentriessingleordefaultf ftitletext trip to italy allvar ac new albumaccessorentryvar photoquery new photoquerypicasaquerycreatepicasauridefault acidpicasafeed photofeed servicequeryphotoquerypicasaentry picasaentry photofeedentries0ulong timestamp converttouint64picasaentrygetphotoextensionvaluetimestamp deduct 9 hoursdatetime dt fromunixtimepatimestampaddhours9picasaentrysetphotoextensionvaluetimestamp converttostringtounixtimedtvar updatedentry picasaentry picasaentryupdateunfortunately while the update method succeeds the timestamp does not change i have also tried to change the timezone of the photo eg same thing user does manually like this am i missing something simpleis there another way to accomplish the same thing i would also settle for changing the timezone of the photo,['c#'] +892385,change build output directory of webapi application i am part of a team working on a large application i am a new addition to this team and am building a new piece of the app as part of this process i have created a webapi application that will expose some http endpoints through which i will retrieve information about the appdue to conditions it would take far too long to explain i would like to get the webapi project to build in another directory specifically binserverdebug as this is where most of the other portions of the app build to i would not bother except that the app tried to use files that are found based on the working directory which is currently wrong for my webapi appi tried changing it in the project settings and now i get this errormy googling has turned up little help thus far anyone know how to resolve this,['c#'] +892448,is there any smart way to combine overlapping paths in python let us say i have two path names head and tail they can overlap with any number of segments if they do not i would like to just join them normally if they overlap i would like to detect the common part and combine them accordingly to be more specific if there are repetitions in names i would like to find as long overlapping part as possible examplerootd1d2d1d2 d2d1d2filetxt rootd1d2d1d2filetxtand not rootd1d2d1d2d1d2filetxtis there any readytouse library function for such case or i have to implement one,['python'] +892565,backbonejs modeldestroy custom transitions when i use backbones modeldestroy it seems to automatically remove that view from the domis there a way for me to use destroy to send the delete request but remove the view from the dom myself something likethismodeldestroy wait true success function myelementanimate height 0 10 functionmyelementremove,"['javascript', 'jquery']" +892619,google polymer for android native app google polymer looks like a simple way to make material designed web pages i am developing a native android application and would like to make it material designed my question is can i use polymer for native android applications,['android'] +892630,locationservicessettingsapi reset settings change unavailable flag updating to google play services v70 and based in this sample for locationupdates in android i have the following code to connect to the locationservicessettingsapi and check if user has everything ok for the application receive the location updates locationsettingsrequestbuilder builder new locationsettingsrequestbuilder builderaddlocationrequestmlocationrequest mlocationsettingsrequest builderbuild pendingresultlocationsettingsresult result locationservicessettingsapichecklocationsettings mlocationclient mlocationsettingsrequest resultsetresultcallbackthiswhere this is the following callback override public void onresultlocationsettingsresult locationsettingsresult final status status locationsettingsresultgetstatus intent resolutionintent switch statusgetstatuscode case locationsettingsstatuscodessuccess everything is ok starting request location updates break case locationsettingsstatuscodesresolution required seems the user need to change setting to enable locations updates call startresolutionforresultactivity request code break case locationsettingsstatuscodessettings change unavailable error cannot retrieve location updates break the success it ok to reproduce just keep gps enabledthe resolution required is also ok to reproduce only thisable gpsthe settings change unavailable is the deal if user select never when the step resolution required is executed the result will come with this status alwaysdid the google play services has a option to reset programmatically the flag when user select the never option i know that never seems to be really do not ask me again but i thinking to create a option in case the user change his mind of course if this can be possiblein this case i will be able to receive the status resolution required again and ask to user to accept the locationupdates when the app is executed next time,['android'] +892635,bootstrap 3 tabs chartjs charts not loading on tabs i am using bootstrap 3 tabs for a page layouts and chartjs to create donut graphs for a projecthowever the charts do not load when changing to a tab with a chart on it sometimes they load when you start inspecting elements in google chrome thoughthey only seem to render if they are loaded on the first visible tabthere is one known error with the chartjs javascript in the chrome consoleuncaught indexsizeerror failed to execute arc on canvasrenderingcontext2d the radius provided 05 is negativeand i think this is because bootstrap has the tabs visibility set to none and therefore the chart does not render properly or somethingit should be looking like thishas anyone else had this problem if so is there a workaround or should i look for another charting script that will play nicely with bootstrap tabsthank you in advance,['javascript'] +892684,conda virtual envinment not changing under windows i have installed anaconda 220 for windows and created a virtual environment via conda create n myenv anacondathe environment is sucessfully created and i see it in my list of envinronments and indeed the directory is there in anacondaenvs conda info e conda environmentsmyenv danacondaenvsmyenvroot danacondahowever when running the activatebat script to switch envinronment although it appears to be successful the switch is not actually made activatebat myenvactivating environment astropydev conda list e conda environmentsmyenv danacondaenvsmyenvroot danacondawith the indicating the active environmenti have seen some issues with conda activate on windows but have not found this sepecific issuefor further info i am looking to copy the whole anaconda package thistribution and then install a dev version over one packagethanks,['python'] +892708,why on safari the transform translate does not work correctly i often use this code to center a div in viewcentered position fixed top 50 left 50 bring your own prefixes transform translate50 50it works great on firefox internet explorer and chrome however not in safariwhats a workaround to center an image in safari web browser,['css'] +892883,doctrine 2 migrations workflow i am developing a web application using zend framework 2 and doctrine 2 i am new to doctrine 2 in general and migrations in particular i was wondering if there are any recommended best practices in using this some specific things i am looking for a recommended workflow from development to deployment do you include prepopulating data in migrations how to handle reverting to a previous version if migration fails many thanks,['php'] +893011,react lifecycle methods understanding i am a newbie to reactjs and i am trying hard to understand several methods in react lifecycle methodsso far i still have something that confuses me1 as far as my understanding the difference between componentwillupdate and componentwillreceivepropsis that componentwillreceiveprops will called when parent change the props and we can use setstate setstate of this child inside componentwillreceivepropsfor examplevar app reactcreateclass getinitialstate function return source limit 200 source source1 handlesourcechange functionsource thissetstatesource source render function return div datasourceselectors onsourcechangethishandlesourcechange sourcethisstatesource tablesorter datasourceurlfordatasourcethisstatesource configconfig headerrepeat5 div in tablesorter we havecomponentwillreceiveprops functionnextprops load new data when the datasource property changes if nextpropsdatasource thispropsdatasource thisloaddatanextpropsdatasource meaning when we change thisstatesource we will expect componentwillreceiveprops be called in tablesorterhowever i do not quite understand how to use componentwillupdate in this case the definition of componentwillupdate is componentwillupdateobject nextprops object nextstatehow can we pass nextstate from parent into child or maybe i am wrong is the nextstate passed from the parent element 2method componentwillmount confuses me because in the official document it says that invoked once both on the client and server immediately before the initial rendering occursin this case if i use setstate in this method it will overrides the getinitialstate since it will called once only on initial in this case what the reason to set the parameters in the getinitialstate method in this particular case we have getinitialstate function return items thispropsinitialitems sort thispropsconfigsort column order columns thispropsconfigcolumns componentwillmount function thisloaddatathispropsdatasource loaddata functiondatasource if datasource return getdatasourcedonefunctiondata consolelogreceived data thissetstateitems data bindthisfailfunctionerror a b consolelogerror loading json items will be overrode initially and why we still need items thispropsinitialitems int the getinitialstate methodhope you can understand my explanation and please give me some hints if you have any many thanks for that,['javascript'] +893016,virtualalloc failing i am trying to use virtualalloc to reserve and commit a block of memory and then again to extend that block unfortunately it is returning null with error error invalid address despite virtualquery saying that the address range requested is free heres my codevoid allocation virtualallocnull 4096 mem reserve mem commit page readwritevoid desirednextallocation charallocation 4096memory basic information infosize t memory info virtualquerydesirednextallocation info sizeofinfovoid extended virtualallocdesirednextallocation 4096 mem reserve mem commit page readwritethe first allocation returns 0x0d0 the call to virtualquery results in the following data in info baseaddress 0x0d10 void allocationbase 0x0 void allocationprotect 0x0 unsigned long regionsize 0x0ff0 unsigned int64 state 0x010 unsigned long protect 0x01 unsigned long type 0x0 unsigned longi interpret that to mean that there are 0xff available pages beginning at 0xd10 which are in the mem free state so why does my attempt to commit the page at 0xd10 faili am running windows 7 and this is a 64 bit buildi have read several stackoverflow posts about virtualalloc but they all seem to imply that this code should work as does my understanding of the documentation,['c++'] +893096,setting width of seekbar to make swipe to unlock effect i am attempting to make a swipe to unlock feature using a seekbar the look i am aiming for is shown herethis is composed of two images a background and a button i put both the background and the seekbar in a framelayout so that the seekbar should sit on top of the backgroundlike solinearlayout androidlayout widthmatch parent androidlayout heightwrap content androidlayout gravitycenter vertical textview androidididtextview1 androidlayout widthwrap content androidlayout heightwrap content androidlayout gravitycenter vertical androidtexttesting 123 framelayout androidlayout heightwrap content androidlayout widthwrap content imageview androidididimageview01 androidlayout widthwrap content androidlayout heightwrap content androidscaletypecenter androidsrcdrawableunlockback seekbar androidididmyseek androidlayout widthmatch parent androidlayout heightwrap content androidclickablefalse androidmax100 androidprogressdrawableandroidcolortransparent androidthumbdrawableunlockbut framelayoutlinearlayoutunfortunately the end result looks like this in eclipsei seem to be unable to make the seekbar match the size of the framelayout you can see the size of the seekbar represented by a thin blue frame in the image above the frame has two small solid blue squares which you can grab with the mouse pointer for resizing but if i use my mouse pointer to drag the little blue square to match the full width of the frameview then as soon as i let go of the mouse the square pings back to its original too small sizewhat can i do to fix this if i can achieve swipe to unlock in a fundamentally different way then i am interested in that too,"['java', 'android']" +893136,handling status bar notification before it is thisplayed i am using notificationlistenerservice to handle device notificationsoverridepublic void onnotificationpostedstatusbarnotification sbn logdtagonnotificationposted posted id sbngetid t sbngetnotificationtickertext t sbngetpackagename the onnotificationposted method is called after the notification has been posted on the device is there a way to catch it before it is presentedi saw that reading notifications can also be achieved using the accessibilitymanager but again it is read after the notification poppedis there a way to delay the device notifications popups until some momenti know i can delete a notification using the notificationlistenerservice as it come after it popped to the user and save it and try to relaunch it later but i am having issues with the relaunching and again this is happening after the status bar notification is already shown,['android'] +893179,first run of android studio unable to access android sdk addon list after trying to reinstall android studio everything was fine until the first run while it was fetching android sdk component information it gave me an error sayingunable to access android sdk addon listi clicked on setup proxy clicked on autodetect proxy settings checked my connection it said connection successful then pressed ok after that it just came up with the same error no progressany ideas on what i can do next i have no experience with proxy so i only used autodetect proxy settings to stay simpleps i have searched but all i can find is to go behind the proxy but i do not have the permissions to edit ideaproperties i am using windows 81 32 bit,['android'] +893190,is there a multitransport logger that preserves place of call in original file when reporting to console preamblea known library winston has the same issue as many other different libraries that serve the purpose of multitransport logging when one of the transports is console the reported message in debugger console browser or any environment for nodejs misses very powerful information the place where the initial call was initiated developers file and instead the place of call inside the library is thisplayed in this case multiple calls from different filesplaces are all reported as if logged from one same placesolutions triedi have research two approaches one was trick on browsernode when they infer the place of call to consolelog the only way i found it can be done is via source maps this is a technology that allows to map minified js sources to original sources and debug it while looking at the full source however this assumes that there is one transition from real minified source to original and in case of substituting source for consolelog in potential library mylogger should be dynamic and reflect the multiple places where myloggerlog is called i have not found a way to do this dynamically since browser loads the map file just onceanother one was to substitute the call of consolelog and inside of custom function call all other transports this can be the same winston however if we do a simple replace like belowvar originallog consolelogconsole proto log functionmessage message new datetoisostring messagejoin originallogcallconsole messagehere send via other transports bodyinnerhtml bodyinnerhtml message brthe place of call to originallog will always be the same and it will be reported accordingly in console output so i thought of intercepting the call to consolelog but leaving the original native function in place but i failed to get the parameters of callfunction interceptgettinglog var originallog consolelog objectdefinepropertiesconsole proto log get functionarguments is always empty here which is not a big surprise originallogcallconsole log accessed jsonstringifyarguments return originallog question in shortdoes anybody know a different approach to logging or a way to trick on browsernodejs when calling consolelog the goal is to have a multilevel multitransport logger which would allow to switch verbosity and transports in configuration which will be different for development and production have full power of consolelog and at the same time neat syntax ie a single function call at a place where developer needs to log something thanks for reading,['javascript'] +893216,android art crash with error jni detected error in application jarray is an invalid stack indirect reference table or invalid reference i am writing an android application that processes a picture from the native c ndk r10d the code was working well until recent art introduction that is more strict with jni so the code is working fine with dalvik eg on prelolipop devices but ii creates a sigenv on the newest phonesi now get the error0426 161834169 eart21443 0xb4a2dd00 spacetypemallocspace begin0x12c0end0x12e010limit0x32c0size2mbcapacity192mbnon growth limit capacity512mbnamemain rosalloc space0426 161834170 eart21443 0xb4ae5640 allocspace main rosalloc space livebitmap 3begin0x12c0end0x32c0426 161834170 eart21443 0xb4ae5660 allocspace main rosalloc space markbitmap 3begin0x12c0end0x32c0426 161834170 eart21443 0xb4874120 spacetypeimagespace begin0x6f5ab0end0x6ff21e58size9mbnamedatadalvikcachearmsystem0426 161834170 eart21443 0xb4875220 imagespace datadalvikcachearmsystem livebitmap 0begin0x6f5ab0end0x6ff21f0426 161834170 eart21443 0xb4875220 imagespace datadalvikcachearmsystem livebitmap 0begin0x6f5ab0end0x6ff21f0426 161834170 eart21443 0xb49d9dd0 spacetypezygotespace begin0x72f090end0x740c70size17mbnamezygote space0426 161834170 eart21443 0xb4875440 allocspace zygote non moving space livebitmap 0begin0x72f090end0x740c70426 161834170 eart21443 0xb4875460 allocspace zygote non moving space markbitmap 0begin0x72f090end0x740c70426 161834170 eart21443 0xb4a2dc80 spacetypemallocspace begin0x740c70end0x740d60limit0x76f090size60kbcapacity46mbnon growth limit capacity46mbnamenon moving space0426 161834170 eart21443 0xb4ae5460 allocspace non moving space livebitmap 4begin0x740c70end0x76f090426 161834170 eart21443 0xb4ae53c0 allocspace non moving space markbitmap 4begin0x740c70end0x76f090426 161834170 eart21443 0xb486d340 large object spacegcretentionpolicyalwayscollect0426 161834263 aart21443 artruntimecheck jnicc65 jni detected error in application jarray is an invalid stack indirect reference table or invalid reference 0x740c9268 0xdead43210426 161834263 aart21443 artruntimecheck jnicc65 in call to getbytearrayelements0426 161834263 aart21443 artruntimecheck jnicc65 from boolean comgooglecodeleptonicaandroidpixnativegetdataint byte0426 161834263 aart21443 artruntimecheck jnicc65 main prio5 tid1 runnable0426 161834263 aart21443 artruntimecheck jnicc65 groupmain scount0 dscount0 obj0x72f090 self0xb482780426 161834263 aart21443 artruntimecheck jnicc65 systid21443 nice0 cgrpdefault sched00 handle0xb6f6abec0426 161834263 aart21443 artruntimecheck jnicc65 stater schedstat 427402282 63106827 397 utm28 stm14 core3 hz10426 161834263 aart21443 artruntimecheck jnicc65 stack0xbe5e30xbe5e50 stacksize8mb0426 161834263 aart21443 artruntimecheck jnicc65 held mutexes mutator lockshared held0426 161834263 aart21443 artruntimecheck jnicc65 native 00 pc 04e64 systemliblibbacktrace libcso unwindcurrentunwindunsigned int ucontext230426 161834263 aart21443 artruntimecheck jnicc65 native 01 pc 03665 systemliblibbacktrace libcso backtraceunwindunsigned int ucontext80426 161834263 aart21443 artruntimecheck jnicc65 native 02 pc 00256429 systemliblibartso artdumpnativestackstd 1basic ostreamchar std 1char traitschar int char const artmirrorartmethod840426 161834263 aart21443 artruntimecheck jnicc65 native 03 pc 00238fe7 systemliblibartso artthreaddumpstd 1basic ostreamchar std 1char traitschar const1580426 161834263 aart21443 artruntimecheck jnicc65 native 04 pc 0b191b systemliblibartso artjniabortchar const char const6100426 161834263 aart21443 artruntimecheck jnicc65 native 05 pc 0b2055 systemliblibartso artjniabortfchar const char const 680426 161834263 aart21443 artruntimecheck jnicc65 native 06 pc 0b4455 systemliblibartso artscopedcheckcheckbool char const constprop1294800426 161834263 aart21443 artruntimecheck jnicc65 native 07 pc 0bee03 systemliblibartso artcheckjnigetbytearrayelements jnienv jbytearray unsigned char620426 161834263 aart21443 artruntimecheck jnicc65 native 08 pc 00239478 dataappcombill2bincorelibdemo1libarmlibleptso jnienvgetbytearrayelements jbytearray unsigned char480426 161834263 aart21443 artruntimecheck jnicc65 native 09 pc 0023992c dataappcombill2bincorelibdemo1libarmlibleptso java com googlecode leptonica android pix nativegetdata5400426 161834263 aart21443 artruntimecheck jnicc65 native 10 pc 08d3b5 datadalvikcachearmdata java com googlecode leptonica android pix nativegetdata i 3b1040426 161834264 aart21443 artruntimecheck jnicc65 at comgooglecodeleptonicaandroidpixnativegetdatanative method0426 161834264 aart21443 artruntimecheck jnicc65 at comgooglecodeleptonicaandroidpixgetdatapixjava940426 161834264 aart21443 artruntimecheck jnicc65 at combill2bincorelibdemovideopipedebugtestdojnidebugvideopipedebugjava4490426 161834264 aart21443 artruntimecheck jnicc65 at combill2bincorelibdemocameraactivityruntest1cameraactivityjava133the code i run in java is return the raw bytes of the native pix object you can reconstruct the pix from this data using createfrompix return a copy of this pix objects raw data public byte getdata int size nativegetdatasizemnativepix size is usually quite big since i work on pictures 1mo300ko byte buffer new bytesize if nativegetdatamnativepix buffer throw new runtimeexceptionnative getdata failed return buffer private static native boolean nativegetdatalong nativepix byte datathe corresponding native code isjboolean java com googlecode leptonica android pix nativegetdatajnienv env jclass clazz jlong nativepix jbytearray data pix pix pix nativepix jbyte data buffer envgetbytearrayelementsdata null l uint8 byte buffer l uint8 data buffer size t size 4 pixgetwplpix pixgetheightpix memcpybyte buffer pixgetdatapix size envreleasebytearrayelementsdata data buffer 0 return jni trueit seems that getbytearrayelements is the source of the error but the jnienv reference and the jbytearray are provided by android and i do not store nor modify them since the buffer array is always allocated in the same java thread i do not see how it can be corruptedi am quite puzzled what can be the source of this issue is the heap too small or is it an art issue i really doubt it though thanks for you help,"['java', 'android']" +893374,trouble installing scipy via pycharm windows 8 no lapack blas resources found i am currently having trouble installing scipy via pycharms package manager i have installed numpy successfully and do have the microsoft visual studio cc compiler in the system variableshowever when it is time to install scipy in pycharm the following error occursexecuted command pip install scipyerror occured numpythistutilssystem infonotfounderror no lapackblas resources foundi have seen other resources on installing blas lapack on windows but i am unsure if it will work with pycharms installationsif anybody has the solution resources to redirect me to please let me know,['python'] +893381,boosthash combine vs simple xoring when using the boost library the fuction boosthash combine works like thisseed hash valuev 0x9e3779b9 seed 6 seed 2 46 1dochtmlhashreferencehtmlboosthash combinewhat is the advantage of this approach vs simply xoringwith xoring one can even use the hash function to use unordered containers as keys while this one is order dependent,['c++'] +893382,mvc controller cannot execute async method i have a very basic mvc controller with one actionpublic class homecontroller controller public actionresult index openconnectionwait return view private async task openconnection var synchronizationcontext synchronizationcontextcurrent debugassertsynchronizationcontext null using var connection new sqlconnection data sourcelocaldbprojectsv12initial catalogdatabase1integrated securitytrue await connectionopenasync this always hangs up the problem is that regular action not async version cannot execute async methods in my case openconnection method always hangs up at await connectionopenasync lineafter sometime i found two ways to make this code workingmake controllers action asynchronouspublic async taskactionresult index await openconnection return viewor allow async execution without capturing original sychronizationcontext for thatawait connectionopenasyncreplace withawait connectionopenasyncconfigureawaitfalseso my guess is that my initial problem was somewhere around synchronizationcontext but synchronizationcontextcurrent is not null and that makes me wonder if my guess is correctso could anybody explain why not async action in mvc controller cannot syncronously execute async methods,['c#'] +893415,dart equivalent of arrayprototypemap i try to get the ids from list of maps in dartin javascript it would be something like thisvar list id3 namethird id4 namefourthvar result listmapfunctionxreturn xidthis should give the result3 4is there a simple way of doing this in dartso far i was able to do this in dartvar list id3 namethirdid4 namefourthvar result listmapx xidthe result is a mappedlistiterable not sure what that is and you cannot use result0 like you can with a normal list how can i make a list of this,['javascript'] +893422,using objects in for of loops why is not is possible to use objects in for of loops or is this a browser bug this code does not work in chrome 42 saying undefined is not a functiontest first oneforvar item of test consolelogitem,['javascript'] +893459,standards compliant way to compare float to integral let us say i have two objects i and f of respective types i and f i know that stdis integralivalue is true and stdis floating pointfvalue is trueis there a fully standardscompliant way to find out if the value of i is smaller than the value of f note the emphasis on fully standardscompliant for this question i am only interested in answers that are backed up by guarantees from the c standardthe trivial implementation i if does not work because the value of f may not fit inside i the trivial implementation fi f does not work either because the precision of f may not be enough to represent i causing i to get rounded to a value equal to f if you have ie754 floats 167219 167220f failsbut here comes the real dilemma if you want to use stdnumeric limitsmax to alleviate these problems your back to the original problem of comparing floats and integers this is because the type of stdnumeric limitsmax is equal to the original type,['c++'] +893582,alternatives to static and global in c i have a class instance that needs to be accessed by some other classesit would be quite cumbersome to pass the instance always down the construction chaini tried to avoid global variable since people tend to advise against thisi thought i declare this instance a static member of a class and then include this class in order to access the instance but this does not work either error calling a private constructor of class footo specify the problem further in the context of the qgraphicsview frameworki want to add qgraphicsitems which are instantiated by a controller class managing the items to the qgraphicsscene which is but i do not insist on that detail a member of my qmainwindow classi spend a considerable amount of time searching the internet but i am fairly new and am kind of stuck here i appreciate any incentive on what the best way to solve the dilemma would be,['c++'] +893601,actionbaractivity is deprecated android studio actually there is no problem project compiles and runs but i cannot understand what is mean strikeout class name android studio tells that there is deprecated code is used can anybody explain,['android'] +893639,match smiley followed by word boundary i am trying to match smileys followed by a word boundary blet us say i wanna match p and followed by bpb is working fine but why is b behaving the opposite,['javascript'] +893653,after executing filedelete the file remains in delete pending how is it possible that after calling filedelete the file still exists sometimes i used simple code to reproduce the issue using fileopen the expected exception is filenotfoundexception i checked the operation in process monitor v305 and the result for the file is delete pending and throwns unauthorizedaccessexception does anyone have an explanation for itpublic class program private const string dummyfilename dummytxt private static void mainstring args int attempt 0 while true using filecreatedummyfilename filedeletedummyfilename try attempt using fileopendummyfilename filemodeopen fileaccessreadwrite filesharenone catch filenotfoundexception catch unauthorizedaccessexception ex consolewritelinefile exists0 fileexistsdummyfilename consolewritelinefile remains in delete pending state in attempt 0 attempt consolewritelineex consolereadkey,['c#'] +893795,what is the best practice for returing a error in aspnet mvc this is my action methodvar model dbpagedatafirstordefaultif modelnull return errorreutrn viewmodelwhat is the best practice for returning this error in a userfriendly way and in a way that i could identity this error when it occursthanks,['c#'] +893872,vs2013 does not seem to attach correctly a debugger is attached to but not configured to debug this unhandled exception while coding a console app i am using an sap dlli am getting the following error when trying to add an sap objecta debugger is attached to but not configured to debug this unhandled exception to debug this exception detach the current debuggercodesapbobscomgeneralservice ogeneralservice ocmpsrvgetgeneralserviceweppagesapbobscomgeneraldata ogeneraldata sapbobscomgeneraldataogeneralservicegetdatainterfacedigeneralservicedatainterfacesgsgeneraldataogeneraldatasetpropertyu webid 1try ogeneralserviceaddogeneraldatacatch exception e loggerwritelogerror add object emessagealthough the code is wrapped with trycatch the ide crashesafter many searches and suggestions around the web which did not helped i came across this post and applied the suggested solution and enabled native code debugging under the project properties debug tabthe result of ticking this option was that instead of letting me debug the unknown error the exception just thisappeared and the code runs with no interference questionswhy does the exception thisappears and not debuggedis it possible to have a different workaround for this problem since enabling the native code debugging is slowing down the app by 10x and not a real solution this problem,['c#'] +893889,search a json array in oracle i am trying to use the new json features introduced in oracle 12102however i cannot seem to find a way to look for a specific value in an array inside my json document consider the following table and datacreate table orders id integer not null primary key details clob not null check details is json strictinsert into orders id details values 1 products product 1 quantity 5 product 2 quantity 1 delivery address my hometowninsert into orders id details values 2 products product 42 quantity 1 product 10 quantity 2 comment your website is too slowinsert into orders id details values 3 products product 543 quantity 1 thiscount 15insert into orders id details values 4 products product 738 quantity 12 thiscount 32now i am trying to write a sql query that returns all orders where product 2 was ordered i cannot use json exists because it does not allow array expressions and i wouldnt know how to specify the value anywayjson value only returns a single value so i cannot iterate over the array values i tried select from orders owhere json valuedetails productsproduct 2but that did not return anything i also tried json table but that also seems to only take the first element from the arrayselect from orders o json tableodetails columns product id integer path productsproduct twhere tproduct id 2but that did not show anything apparently the star expansion in the array step does not expand the values in the json tableso my question is how can i based on the above sample data retrieve all orders where the product with the number 2 has been orderedi am essentially looking for the equivalent to this postgres queryselect from orderswhere details products product 2,['sql'] +893918,does the swift compiler ignore unused functions does the swift compiler compile unused functions or does it ignore them,['ios'] +894033,why is my computation so much faster in c than python below is a simple piece of process coded in c and python respectively for those of you curious about the process it is the solution for problem no 5 of project eulermy question is the c code below takes only 9 seconds to iterate while completion of python code takes 283 seconds to be exact 283 seconds on python 343 64 bits and 329 seconds on python 279 32 bitsso far i have coded similar processes both in c and python and the execution time differences were comparable this time however there is an extreme difference between the elapsed timesi think some part of this difference arise from the flexible variable type of python language i suspect python converts some part of variables into double but this much is still hard to explainwhat am i doing wrongmy system windows7 64 bitsc vs express 2012 9 secondspython 343 64 bits 283 secondspython 279 32 bits 329 secondscsharp codeusing systemnamespace bug vcs class program public static void mainstring args datetime t0 datetimenow int maxnumber 20 bool found false long start maxnumber while found found true int i 2 while i maxnumber 1 found if start i 0 found false i start consolewriteline0d start 1 consolewritelinetime elapsed 0f sec datetimenow t0seconds consolereadline and python codefrom datetime import datetimet0 datetimenowmax number 20found falsestart max numberwhile not found found true i 2 while i max number 1 and found if start i 0 found false i 1 start 1printnumber 0dnformatstart 1printtime elapsed 0f secnformatdatetimenow t0seconds,"['c#', 'python']" +894128,why no memory leak for propertycopy nsstring name when i do not release it in dealloc i turned arc offi have a property in a class declared like thispropertycopy nsstring namei set name with a constant stringgreeter setnamejanei implemented dealloc for my class like thisvoiddealloc super dealloci expected there would be a memory leak because i did not release name i am using xcode 62 and productanalyze does not identify any leaks and neither does instruments productprofile choose leaks hit the red record buttonhere is the relevant code greeterh flashlight2import foundationfoundationhinterface greeter nsobjectpropertycopy nsstring name nsstringdescriptionvoiddeallocend greeterm flashlight2import greeterhimplementation greeternsstringdescription nsstring msg nsstring alloc initwithstringi am a greeter return msg autoreleasevoiddealloc super deallocendimplementation appdelegate boolapplicationuiapplication application didfinishlaunchingwithoptionsnsdictionary launchoptions override point for customization after application launch greeter greeter greeter alloc init greeter setnamejane constant string in memory for life of program nslog greeter greeter release return yesafter thinking about it for awhile the only explanation that i can come up with is that the name setter does not actually copy the constant string it seems like objc does a type check on the string being assigned to the property and because it is a constant string objc just assigns thepointertotheconstantstring to the namepointer is something like that going on,['objective-c'] +894182,factory pattern to build many derived classes i have a factory object challengemanager to generate instances of a challenge object for a game i am building there are many challenges the constructors for each challenge class derivation are different however there is a common interface among them defined in the base classwhen i call managercreatechallenge it returns an instance of challenge which is one of the derived typesideally i would like to keep the code for the object construction inside the derived class itself so all the code related to that object is colocated exampleclass challenge class challengea challenge public static challenge makechallenge return new challengea class challengeb challenge public static challenge makechallenge return new challengeb now my challengemanagercreatechallenge call only needs to decide the class to call makechallenge on the implementation of the construction is contained by the class itselfusing this paradigm every derived class must define a static makechallenge method however since the method is a static one i am not able to make use of an interface here requiring it it is not a big deal since i can easily remember to add the correct method signature to each derived class however i am wondering if there is a more elegant design i should consider,['c#'] +894248,microsoft visual c compiler for python 34 i know that there is a microsoft visual c compiler for python 27 but is there currently or planned a microsoft visual c compiler for python 34 or eve microsoft visual c compiler for python 3x for that matter it would be supremely beneficial if i did not have to install a different version of visual studio on my entire lab,['python'] +894297,why is this code vulnerable to buffer overflow attacks int funcchar str char buffer100 unsigned short len strlenstr iflen 100 return 1 strncpybufferstrstrlenstr return 0this code is vulnerable to a buffer overflow attack and i am trying to figure out why i am thinking it has to do with len being declared a short instead of an int but i am not really sureany ideas,['c'] +894321,alternative to uiview autolayout methods which are to be deprecated according to the uiviewh header file the methods below are to be deprecated what is the alternative way of working with autolayout in code i do not see how the methods recommended in the code comment replace their existing counterparts as they work on the actual constraint and not on the relation between the uiview and the constraintinterface uiview uiconstraintbasedlayoutinstallingconstraints nsarray constraints ns available ios6 0 voidaddconstraintnslayoutconstraint constraint ns available ios6 0 this method will be deprecated in a future release and should be avoideda instead set nslayoutconstraints active property to yes voidaddconstraintsnsarray constraints ns available ios6 0 this method will be deprecated in a future release and should be avoideda instead use nslayoutconstraint activateconstraints voidremoveconstraintnslayoutconstraint constraint ns available ios6 0 this method will be deprecated in a future release and should be avoideda instead set nslayoutconstraints active property to no voidremoveconstraintsnsarray constraints ns available ios6 0 this method will be deprecated in a future release and should be avoideda instead use nslayoutconstraint deactivateconstraintsend,['ios'] +894342,multiple level of inheritance i have the following java class with multiple level of inheritance with certain type parameters i want to use the type parameter t in class b class b extends c class ct extends d class d however he following does not compileclass b extends c t tclass ct extends d class d although i can define the variable t in class c but it is not a good coding practice how can i define the following this does not compile as wellclass b extends ct extends d thanks,['java'] +894343,android appcompat 2211 default text color and actionmode style i am updating my application to use the version 2211 of the android support library my application theme inherits from themeappcompatlightdarkactionbarit works fine except that all texts are white if the textview style is set to one of the predefined style so i end up with white texts on light background default background color with version 2200 i had no issuei tried the follow in my theme but it does not seem to workitem nameandroidtextcolorcolorblackitemitem nameandroidtextcolorprimarycolorblackitemitem nameandroidtextcolorprimaryinversecolorblackitemmoreover the actionmode now has a black background instead of white as it used to be with 2200any idea on how to change this,['android'] +894375,inserting multiple value in table with string input i am passing one string to store procedure 120230450 it contains id and appropriate value for ithow can i add value as shown in below table in databaseid value1 202 304 50i have already stringsplit function which works perfectly and gives out put in row value some think like this 120230450can anyone please help me to insert data into table with any solutioni already try this solutioninsert table colname select yitemfrom dbosplitstringteststring xcross applydbosplitstringxitem ybut this will return duplicate value as more as id valuemy store procedure iscreate procedure dbotemp result insertdatastring varcharmaxasinsert into temptableidmarksselect xitemyitemfrom dbosplitstringvarcahrdatastring xcross applydbosplitstringvarcahrxitem yreturn 0,['sql'] +894447,dynamically scale object stacked over another one i am making a project with threejs where the user can dynamically change the dimensions of the model the question is very similar to this one that i posted but i am afraid it is not working since this time i am working with an extrusion of a planar shape the snippet of the code where i am having problems is the followingcubeyonchangefunctionvalue cubescaley value cubepositiony cubeheight value 2 roofpositiony roofheight roofscaley 2 cubepositiony 2 roofheightroofyonchangefunctionvalue roofscaley value roofpositiony roofheight value cubepositiony 2 value roofheightas you can observe when i change roofscaley also the object is moving but it should stay fixed to the upper part of the cube do you know what am i doing wrong this is a jsfiddle with the complete code thanks in advance for your answers,['javascript'] +894570,why does sql server convert varchar to datetime using an invalid style i cannot make out from the documentation why sql server parses a text in a format other than the specified styleregardless of whether i provide text in the expected formatselect convertdatetime n20150601 112or incorrect format for style 113select convertdatetime n20150601 113the results are the same 20150601 0 i would expect the latter to fail to convert the date correctlywhat rules does it employ when trying to convert a varchar to datetime ie why does the latter incorrect format style still correctly parse the dateedit it seems i have not been clear enough style 113 should expect dd mon y hhmissm24h but it happily converts values in the format ymmdd for some reason,['sql'] +894588,read a tab separated file with first column as key and the rest as values i have a tab separated file with 1 billion lines of these imagine 200 columns instead of 3abc 0123 06524 0325foo 09808 0874 02341 bar 023123 0123124 01232i want to create a dictionary where the string in the first column is the key and the rest are the values i have been doing it like this but it is computationally expensiveimport iodictionary with ioopenbigfile r as fin for line in fin kv linestripsplit k v kv0 kv1 dictionaryk listmapfloat vhow else can i do get the desired dictionary actually a numpy array would be more appropriate than a list of floats for the value,['python'] +894725,skype api message output how can i receive and output message from skype to my application textbox1texti was looking for it in skype4com documentation but did not find anything,['c#'] +894735,c find static array size preventing mistakes finding the size of a static array is a common operation see c find static array size sizeofa sizeofa0this can be wrapped into a macro egdefine array sizea sizeofa sizeofa0however its possible to accidentally pass in a regular pointereg void funcsomearray foo int i array sizefoo while its valid c but often ends up being a logical errorits possible to prevent this mistake taking advantage of perprocessor to fail on a zero length bitfielddefine array sizea sizeofstruct int isnt array const void a a0 0 sizeofa sizeofai have found this macro works with gcc but fails with clang for indirectly referenced members with error expression is not an integer constant expressionegchar word8 int i array sizeword okstruct bar word8 void funcstruct bar foo int i array sizefooword failsis there a more portable way to to implement this working with clang is good of course though im interested in general portability other compilers toothis seems such a common task that it would be good to have a reusable portable macro,['c'] +894767,slservicetypefacebook setinitialtext is not working i am trying to share a text on facebook with slservicetypefacebook on ios 83 but the popup text box thisplayed empty i want it to be thisplayed with text in it below you can see the code i use for that ifslcomposeviewcontroller isavailableforservicetypeslservicetypefacebook slcomposeviewcontroller controller slcomposeviewcontroller composeviewcontrollerforservicetypeslservicetypefacebook controller setinitialtextfirst post from my iphone app self presentviewcontrollercontroller animatedyes completionnil,['ios'] +894799,creating a partial sas proc summary replacement in pythonpandas we are working to get off of sas and onto pythonpandas however one thing we are having trouble with is creating a replacement for proc summary aka proc means that has the sas routines flexibility for nonsas users proc summary is just a routine that produces a table containing descriptive statistics for variables across all observations or within groups of observations in a dataset to paraphrase the sas documentation our requirements are just a small subset of the full functionality outputting a table where we haveability to apply different stats to different columns for now just count sum mean weighted meanability to handle zero to many grouping variablesability to specify a weight variable for weighted meanwe are not trying to do anything else anything graphical etc here is what we have so fardef wmean ungrouped dw return ddotwsum wsumdef wmean grouped group var name in var name weight d groupvar name in w groupvar name weight return d wsum wsumfuncs mean npmean sum npsum count npcount nonzerodef my summary data var names in var names out var functions var name weight none var names group none result dataframe if var names group is not none grouped datagroupby var names group for var name in var name out var function in zipvar names invar names outvar functions if var function wmean func lambda x wmean grouped x var name in var name weight resultvar name out seriesgroupedapplyfunc else func funcsvar function resultvar name out groupedvar name inapplyfunc else for var name in var name out var function in zipvar names invar names outvar functions if var function wmean resultvar name out serieswmean ungroupeddatavar name in datavar name weight else func funcsvar function resultvar name out seriesfuncdatavar name in return resulthere is a sample call to the my summary function my summary datadf var names inx 1x 1x 1x 1 var names out x 1 cx 1 sx 1 mx 1 wm var functionscountsummeanwmean var name weightval 1 var names groupregioncategorymy summary works but as you can see its implementation is not the prettiest here are the main issuestwo different code paths depending on grouped or ungrouped this stems completely from the fact that dataframe and dataframegroupby have different ways for applying a programmaticallyselected reducing function to a single column for dataframe the only way i have found is directly invoking funcdatavar name in datavar name inapplyfunc does not work because apply on a series does not reduce unlike apply on a dataframe on the other hand for dataframegroupby i have to use that very approach groupedvar name inapplyfunc that is because something like funcgroupedvar name in will not work no reason it shouldspecial treatment for weighted mean this is because it operates on two columns unlike all the other calculations which operate on just one i do not know if this can be helpedtwo different weighted mean functions this is a consequence of the first issue the ungrouped function has seriestype parameters and needs dot to multiply and reduce them the grouped function eventually deals with seriesgroupby objects and has to use the operator acknowledgements to the answer to this so post for the weighted average function codeso my questions areis there something native to pandas that can do all of this ie throw out the above and use that insteadif not are there any fixes to any of the issues mentioned aboveby any chance is there some way to group by nothing that is to obtain a dataframegroupby object from a dataframe without grouping on any variable then the code paths would be reduced as we would be dealing with the dataframegroupby interface exclusivelyupdate current solutionjohnes answer provides a way to group by nothing groupbylambda x true this is a workaround that he spotted in this so post which incidentally features an answer from wes himself speaking of the need for a dataframeagg which would serve the same purpose johnes excellent solution allows us to deal exclusively with objects of type dataframegroupby and instantly reduces most of the code paths i was able to reduce further using some functional gimmickry that is now possible because we have only dataframegroupby instances basically all functions are generated as needed the generators in quotes here so as to not be confused with python generator expressions take two parameters value column name and weight column name the second of which is ignored in all cases except wmean the generated functions are always applied over the entire dataframegroupby as was originally the case just with wmean with the parameters being the correct column names to use i also replaced all the np implementations with pandas calculations to better deal with nan values unless there is something native to pandas that can do this this is our solutionfunc gens mean lambda yz lambda x xymean sum lambda yz lambda x xysum count lambda yz lambda x xycount wmean lambda yz lambda x xy xzsum xzsumdef my summary data var names in var names out var functions var name weight none var names group none result pddataframe if var names group is none grouped datagroupby lambda x true else grouped datagroupby var names group for var name in var name out var function in zipvar names invar names outvar functions func gen func gensvar function func func gen var name in var name weight resultvar name out groupedapplyfunc return result,['python'] +894860,java lambda expression for nested loops with conditional i am new to lambda expressions and am trying to use them to reduce the following code to the lambda equivalent i have looked into reduce and flatmap and foreach as well as several other things but i am obviously missing something because everything that i try is either syntactically incorrect or i do not have a reference for what i needi need to perform an analysis of each element against all other elements in a collection i coded that as nested loops with a conditional once nonmatching elements have been identified a computation is done using both elements finally i want a collection of results for each comparative computationso heres the original codefinal listelement updated new arraylistelementssizefor final element first elements attribute newattribute firstgetattribute for final element second elements if firstequalssecond newattribute newattributeaddcomputechangefirst second final element newelement new elementfirstgetentry newattribute firstgetvalue updatedaddnewelementthen i tried many variations of lambda expressions the simplest of which iselementsparallelstream mapfirst new elementfirstgetentry firstgetattributeadd computechangefirst second first getvaluecollectcollectorstolistobviously this is wrong as there is no reference to second available to me and no conditionfilter for second being not equal to firsthow do i reduce this nested loop with conditional returning a collection to a lambda expressionany help here is greatly appreciated,['java'] +894904,calculating the averages for each key in a pairwise kv rdd in spark with python i want to share this particular apache spark with python solution because documentation for it is quite poori wanted to calculate the average value of kv pairs stored in a pairwise rdd by key here is what the sample data looks like rdd1take10 show a small sampleu20131009 760117302052786u20131010 9322709163346612u20131010 28264462809917358u20131007 9664429530201343u20131007 12461538461538463u20131009 2076923076923077u20131008 11842105263157894u20131013 3232514177693762u20131013 262496u20131013 10693069306930692now the following code sequence is a less than optimal way to do it but it does work it is what i was doing before i figured out a better solution it is not terrible but as youll see in the answer section there is a more concise efficient way import operator countsbykey scbroadcastrdd1countbykey sample output of countsbykeyvalue u20130909 215 u20130908 69 snip rdd1 rdd1reducebykeyoperatoradd calculate the numerators ie the sums rdd1 rdd1maplambda x x0 x1countsbykeyvaluex0 divide each sum by it is denominator ie count printrdd1collect u20131009 11235365503035176 u20131007 2339500642456595 snip,['python'] +894912,declaration under interface in objective c i am studying big nerd ranchs objective c programming booki saw a code like belowinterface bnremployee bnrperson nsmutablearray assetsproperty nonatomic unsigned int employeeidproperty nonatomic unsigned int officealarmcodeproperty nonatomic nsdate hiredateproperty nonatomic copy nsarray assetsdoubleyearsofemploymentvoidaddassetbnrasset aunsigned intvalueofassetsin this code why do you declare nsmutablearray assets under the interface how is this different than declaring it as a property and what purpose does it servelastly i see there is a nsarray assets in a property is this basically same as nsmutablearray assets,"['ios', 'objective-c']" +894913,force resizement when reading text from file the duplicate suggested is the question where i got the basis for this question so it is not a duplicate as a matter of fact i already have linked to that question from the startgood editi made a jsfiddle my first time notice how the textarea does not expand as one would wish type something inside the textarea and it will get resized immediatelyif we can automatically send a keypress event it may work this relevant question did not help the answers had no effecti am using the textarea as is from here then i read from a file and i am putting the content inside the textbox but it does not get resized as it shouldi update the textbox like thisfunction updatetextboxtext cagetextboxvaltextany ideasi am on firefox 340 canonical at ubuntu 1204 if that plays some role which i hope is not the case since some of my users use chromeeditan attempt would be to write something like thiscagetextboxattrrows how many rows does the new text containnote that if we try to find out how many lines of text the textarea contains we will get 1 as an answeredit 2maybe something like widthlength of line font size for a few tests it seems to be correct if i subtracted 1 by keeping only the integer part of the result of course,"['javascript', 'css']" +894914,want to plot pandas dataframe as multiple histograms with log10 scale xaxis i have floating point data in a pandas dataframe each column represents a variable they have string names and each row a set of values the rows have integer names which are not important print data0 kppawr23 kppaspyd1 3312387 132660402 2775202 0103 10 104 10 394374205 17017150 33019040i want to plot a histogram for each column the best result i have achieved is with the hist method of dataframedatahistbins20but i want the xaxis of each histogram to be on a log10 scale and the bins to be on log10 scale too but that is easy enough with binsnplogspace20a workaround might be to log10 transform the data before plotting but the approaches i have trieddataapplymathlog10anddataapplylambda x mathlog10xgive me a floating point error cannot convert the series to 0formatstrconvertertypeerror cannot convert the series to type float uoccurred at index kppawr23,['python'] +895182,generic method to find the median of 3 values i needed a method to get the median of 3 values i thought it a good opportunity to write a generic method since i do not really have that practiced i wrote this and it seems pretty straightforward though i get a warning but it seems to work fine according to my testsi am aware i could use an inherently sorted set or collectionssort but this approach is for the sake of understandingi want to pinpoint a few thingsi noticed this does not work if i tried to declare medianhelper with arraysaslista b c why is this trying to search this gives me unrelated results and it is otherwise elusive since i am not sure what is happening i get an unsupportedoperationexception but this is not present the way i have it belowwhy am i getting a warning what is wrongmissingthe method followsprivate static t extends comparable t mediant a t b t c listt medianhelper new arraylist t max t min medianhelperadda medianhelperaddb medianhelperaddc if acomparetob 0 max a min b else max b min a if maxcomparetoc 1 max c if mincomparetoc 0 min c medianhelperremovemax medianhelperremovemin return medianhelperget0,['java'] +895197,how to upgrade existing aspnet application to aspnet vnext i have not been able to find any proper documentation on how to upgrade an aspnet application to aspnet vnext i would like to switch hosting servers and from what i have learnt you can host aspnet vnext not only on windows but also on linux mac etci found this article upgrade to net vnext but it did not really help to achieve my goalso my question is what are the important steps to take when upgrading an existing aspnet application to aspnet vnext,['asp.net'] +895339,convert func to delegate i have the following delegate definedpublic delegate object mydelegatedynamic targetand i have a funcdynamic object objectfuncdynamic object myfunchow can i convert myfunc to mydelegatei have tried these instructions none of them workedmydelegate mydeleg myfuncmydelegate mydeleg mydelegate myfuncmydelegate mydeleg myfunc as mydelegate,"['c#', '.net']" +895404,whats the use of a circular reference in python you can append a list to itself and it will accept the assignment l 01 lappendl l0 1 l10 1 my question is whypython allows this rather than throwing an error is that because there is a potential use for it or is it just because it was not seen as necessary to explicitly forbid this behaviour,['python'] +895508,how merge two objects array in angularjs i want to append following object array with existing one in angulajs for implementing load more feature ieappending ajax response with existing one each timei have one variable scopeactions which contains following json data total 13 per page 2 current page 1 last page 7 next page url prev page url null from 1 to 2 data id 2108 action type id 202 user id 1 id 2108 action type id 202 user id 1 i want to append following json response each time this variable data id 2108 action type id 202 user id 1 id 2108 action type id 202 user id 1 i have tried with scopeactionsdataconcatdatadatabut it is not working and getting following error messagescopeactionsdataconcat is not a function,"['javascript', 'jquery']" +895557,what is the relationship between virtualenv and pyenv i recently learned how to use virtualenv and virtualenvwrapper in my workflow but i have seen pyenv mentioned in a few guides but i cannot seem to get an understanding of what pyenv is and how it is differentsimilar to virtualenv is pyenv a betternewer replacement for virtualenv or a complimentary tool if the latter what does it do differently and how do the two and virtualenvwrapper if applicable work together,['python'] +895628,how to get the dnu command working on os x just downloaded and installed visual studio code on os x 10103i have managed to partially follow the installation instructions for aspnet 5what i fail with is when the instruction tells me to calldnu restorewhen doing this in my terminal it saysbash dnu command not foundi have found a somewhat similar question here on so which unfortunately did not help memy questionhow can i make the dnu command work on os xupdatesomeone marked my questions as the duplicate of the so question i linked to by myselfnow so forces me to edit my question to proof that it is not a duplicate so basically that is me right nowi hope this satisfies the needs of so to not close my question as a duplicate since my understanding is that it is no duplicate,['.net'] +895657,swift compiler error acannot invoke map with an argument list of type a i have a range that i am trying to map on but i am getting the error acannot invoke map with an argument list of type aheres what the code looks like let patterns 05map versenum in let versenumberstartpattern versenumversenumspansspan let chapterstartpattern chapternumsparsedversechapterstartsspan if versenum 1 return chapterstartpattern else return chapterstartpattern versenumberstartpattern if i take out everything inside the closure and just return then the compiler does not complain however even if i add one line other than the return empty string then the compiler complains such as for let patterns 05map versenum in let versenumberstartpattern versenumversenumspansspan return am i missing something here,['ios'] +895658,missing secret token and secret key base rails 420 with rvm recently i pulled one of my repos from git after launching the server i am receiving the the following missing secret token and secret key basethis may be happening because i have included the secretsyml in my gitignoremy current setupubuntu 1404ruby 220p0rails 420rvm 12611local server not remotedevelopment environmentmany online resources state that i must gen a new key using rake secret and add it to the secretsyml placing the key inside the secretsyml and restarting the rails server does not workedited added contents of secretsyml below 043015 904 am estdevelopment secret key base long key heretest secret key base long key here do not keep production secrets in the repository instead read values from the environmentproduction secret key base envsecret key base please know this is set as a development environment on a local server in my place of residence not herokuother resources state i need to add an entry inside my secret tokenrb but this file does not exist in my projectthe only way my application will run is if i were to create a secret tokenrb file and add either one of the following inside of itmyappapplicationconfigsecret token if railsenvdevelopment or railsenvtest x 30 meets minimum requirement of 30 chars longelse envsecret tokenendor myappapplicationconfigsecret token the secret keywhy is this file required when the rails docs states to remove it33 configsecretsymlthe secret tokenrb is not required in order to run for new generated projects only the ones from my git repoplease advise on why my application needs secret tokenrb though the rails docs state otherwise or my application will not run without itedited 043015 927 am estanother strange behavior is i can rename secretsyml while the secret tokenrb remains in place and the application will still runi attempted to rename the secret tokenrb added envsecret key base to development and i am still experiencing the missing secret token issueedited added git repo below 050815 250 am estgit repo macsomething strange is if i were to modify any one of the 32 characters save the secret tokenrb reload the servermy app will run is the 32 character string in the secret tokenrb something i can makeup on my own if so what is the real purpose for rake secret,"['ruby-on-rails', 'ruby']" +895723,concurrent requests with mri ruby i put together a simple example trying to prove concurrent requests in rails using a basic example note that i am using mri ruby2 and rails 42 def api call sleep10 render json done endi then go to 4 different tabs in chrome on my mac i7 4 core and see if they get run in series or parallel really concurrent which is close but not the same thing ie httplocalhost30api calli cannot get this to work using puma thin or unicorn the requests each come by in series first tab after 10 seconds second after 20 since it had to wait for the first to complete third after thatfrom what i have read i believe the following to be true please correct me and were my resultsunicorn is multiprocess and my example should have worked after defining the number of workers in a unicornrb config file but it did not i can see 4 workers starting but everything works in series i am using the unicornrails gem starting rails with unicorn c configunicornrb and in my unicornrb i have unicornrbworker processes 4preload app truetimeout 30listen 30after fork do server worker activerecordbaseestablish connectionendthin and puma are multithreaded although puma at least has a clustered mode where you can start workers with a w parameter and should not work anyways in multithreaded mode with mri ruby20 because there is a global interpreter lock gil that ensures only one thread can be run at a time sodo i have a valid example or is using sleep just wrongare my statements above about multiprocess and multithreaded with respect to mri rails 2 correctany ideas on why i cannot get it working with unicorn or any server for that matterthere is a very similar question to mine but i cannot get it working as answered and it does not answer all of my questions about concurrent requests using mri rubygithub project note project is looking at more than this question of multiprocessthreading on the server,"['ruby-on-rails', 'ruby']" +895851,nsdictionary in swiftcannot subscript a value of type anyobject with a index of type int so i am trying to parse some data in json using swift below is my codevar jsonresultnsdictionary nsjsonserializationjsonobjectwithdatadata options nsjsonreadingoptionsmutablecontainers error nil as nsdictionaryprintlnjsonresult the above code will return something like this count 100 subjects alt name alt name then i try to access all the subjects with jsonresultsubjects so far so goodbut when i try to access the individual subject for example jsonresultsubjects0 xcode gives me errorcannot subscript a value of type anyobject with an index of type intcan someone help me with this,['ios'] +895854,object reference not set to an instance of an object when opening cshtml files in visual studio 2013 when i try to open cshtml files in visual studio 2013 i get this errorobject reference not set to an instance of an objecti have tried the solution given here but it did not workhere is my appsettings section in the webconfig appsettings add keyport value25 add keywebpagesversion value30 add keywebpagesenabled valuefalse add keyclientvalidationenabled valuetrue add keyunobtrusivejavascriptenabled valuetrue appsettingsi do not think that the problem is about this particular project because all my other mvc projects have same problem,['asp.net'] +895915,c function match priority i have simple question about the c function match priority suppose i have such codeinclude iostreamvoid funcconst char stdcout const char stdendltemplateint nvoid funcconst char n stdcout const char n stdendlint mainint argc char argv funchello world return 0the result of the code is with apple llvm version 610 clang602049 based on llvm 360svnconst chari think the literal type of the hello world should be const char why the const char version has a higher priority than the const char version,['c++'] +895962,understanding defer and obstruct macros i created a small macro metaprogramming library that implements basic useful constructs such as repeattimes x ifvalue true false tuples and moremost of my implementations work by overloading macros based upon their variadic argument count or through a counter exampledefine repeat 0x define repeat 1x x repeat 0x define repeat 2x x repeat 1xdefine repeat 3x x repeat 2x these defines are generated using an external script define repeatcount x catrepeat countxthis works fine but i have recently come across an extremely interesting implementation of macro recursion by paul fultzup until the deferred expression section i had no trouble understanding his articlei am however having a lot of trouble understanding the use of defer and obstruct properlypaul implements a very elegant version of repeat that does not require scriptgenerated defines like thisdefine eatdefine expand va args define whenc ifcexpand eatdefine repeatcount macro whencount obstructrepeat indirect deccount macro va args obstructmacro deccount va args define repeat indirect repeatan example of using this macrodefine mi ievalrepeat8 m 0 1 2 3 4 5 6 7defer obstruct and other utilities are implemented as suchdefine emptydefine deferid id emptydefine obstruct va args deferemptydefine expand va args define a 123a expands to 123defera expands to a because it requires one more scan to fully expandexpanddefera expands to 123 because the expand macro forces another scanwhen the preprocessor expands a macro the result is painted until the next scan it will not expand recursively unless an additional scan occurs is this correctdoes the expand macro force an additional scan if so does this scan allow macros to expand recursively whats the difference btween expand and deferiddoes defer force two additional scanswhat about the obstruct macro does it force two additional scansnow why is obstruct required in the recursive implementation of repeat why wouldnt defer or expand work here,['c++'] +895978,bootstrap dropdowntoggle close on click i have a dropdown button with a list of things that are anchored to different parts of the page this dropdown is only for mobilehowever the problem is the dropdown would not close after i click on it is there anyway i can make it close on click i have tried looking around but it wouldnt work on minediv idmobiledropdown classnav2 w dataspyaffix dataoffsettop350 div classcontainer div classpuleft stylemargintop3px marginright3pxjump to div div classpuleft div classbtngroup mobfl button typebutton classbtn btndefault btnsm dropdowntoggle datatoggledropdown ariaexpandedfalse categories span classcaretspan button ul classdropdownmenu rolemenu lia href1oneali lia href2twoali lia href3threeali lia href4fourali ul div div div divi also took a look at bootstraps js itself and caught this lineif ontouchstart in documentdocumentelement parentclosestnavbarnavlength if mobile we use a backdrop because click events do not delegate div classdropdownbackdropinsertafterthisonclick clearmenus is this be the reason why it would not close are there any workaround to make it workeditso with some help i got this scriptdocumentreadyfunction adropdowntoggleclickfunctionev adropdowntoggledropdowntoggle return false uldropdownmenu aclickfunctionev adropdowntoggledropdowntoggle return false my javascript is pretty weak how do i actually edit this to make it work only in my mobiledropdown id divalright so far i have updated my script to thisdocumentreadyfunction subject cat mob dropdowntoggleclickfunctionev subject cat mob dropdowntoggledropdowntoggle return false subject cat mob uldropdownmenu aclickfunctionev subject cat mob dropdowntoggledropdowntoggle return false it works like how i want it to be but the dropdown would not open again after the first time,"['javascript', 'jquery', 'html']" +896010,make an element as wide as the grandparent i have the following markup where content is 80 wide and contains slide elements i want the slides to be as wide as their grandparent ie body in this example this is the markup i have and it cannot be changedbody margin 0 font medium monospace background lightgraycontent margin auto width 80 background whitecontentbeforecontentafter content thisplay tableslide height 6em background indianreddiv idcontent plorem ipsum dolor sit amet consectetur adipiscing elitp blockquote pphasellus euismod dolor imperdietp blockquote div claslidedonec mauris tellusdiv ppellentesque sit amet venenatis diam at interdum tortorp ul liquisque ornare mi in pharetra porttitorli linulla ultrices quam nec vehicula portali uldivi have triedrelativeabsolute positioning which requires height of slides to be fixed the slides contain variable length textsetting 80 width on paragraphs instead of content but this is not elegant content contains elements that cannot have 80 width or 10 left margin,"['html', 'css']" +896203,can gcc o and s be used together can i use for example gcc o s outputs abscto generate an assembly file with name outputs it seems like i cannot when i try to do that i got following error message undefined symbols for architecture x86 64 main referenced from implicit entrystart for main executable ld symbols not found for architecture x86 64 clang error linker command failed with exit code 1 use v to see invocationi do not intend to use the linker just try to examine the assembly code,['c'] +896246,is it definitely illegal to refer to a reserved name on the stdproposals list the following code was giveninclude vectorinclude algorithmvoid fooconst stdvectorint v ifndef algorithm stdfor eachvbegin vend int istdcout i endiflet us ignore for the purposes of this question why that code was given and why it was written that way as there was a good reason but it is irrelevant here it supposes that algorithm is a header guard inside the standard header algorithm as shipped with some known standard library implementation there is no inherent intention of portability herenow algorithm would of course be a reserved name perc11 2113 in addition some identifiers are reserved for use by c implementations and standard libraries 176432 and shall not be used otherwise no diagnostic is requiredc11 1764321 certain sets of names and function signatures are always reserved to the implementationeach name that contains a double underscore or begins with an underscore followed by an uppercase letter 212 is reserved to the implementation for any useeach name that begins with an underscore is reserved to the implementation for use as a name in the global namespacei was always under the impression that the intent of this passage was to prevent programmers from definingmutatingundefining names that fall under the above criteria so that the standard library implementors may use such names without any fear of conflicts with client codebut on the stdproposals list it was claimed that this code is itself illformed for merely referring to such a reserved name i can now see how the use of the phrase shall not be used otherwise from c11 2113 may indeed suggest thatone practical rationale given was that the macro algorithm could expand to some code that wipes your hard drive for example however taking into account the likely intention of the rule i would say that such an eventuality has more to do with the obvious implementationdefined nature of the algorithm name and less to do with it being outright illegal to refer to it implementationdefined in its english language sense not the c standard sense of the phrasei would say that as long as were happy that we are going to have implementationdefined results and that we should investigate what that macro means on our implementation if it exists at all it should not be inherently illegal to refer to such a macro provided we do not attempt to modify itfor example code such as the following is used all over the place to thistinguish between code compiled as c and code compiled as cifdef cplusplusextern c endifand i have never heard a complaint about thatso what do you think does shall not be used otherwise include simply writing such a name or is it probably not intended to be so strict which may point to an opportunity to adjust the standard wording,['c++'] +896251,why my selection between two dates in the same table does not work i use sql server 2014 i try the following query to select between two dates in the same table the datatype is nvarchar i executed the following query it just shows me three rows such300320153004201530042015but in reality there is2902201530032015310420153004201530042015select registereddatefrom studentwhere studentregistereddate between convertnvarchar 30012014 103 and convertnvarchar 30042015 103,['sql'] +896273,android studio and visual studio emulator for android debugging is it possible to connect the shiny visual studio emulator for android installed with visual studio 2015 rc to android studioit is not showing in rundebugsolvedfound the address of the emulatorthen connected to it using adb connectand voila,['android'] +896297,google timeline chart color each bar individually when multiple on same line the google timeline charts seem to suggest coloring individual blocks on the timeline per the documentationbut there seems to be a problem when two bars overlap on the same line as you can see in this fiddlehere is the key codedatatableaddrows redgreenblue name of bar should be red ff0 new date1789 3 29 new date1797 2 3 redgreenblue name of bar should be green 00ff00 new date1796 2 3 new date1801 2 3 redgreenblue name of bar should be blue 0ff new date1801 2 3 new date1809 2 3 var options colors ff0 00ff00 0ffi tried playing with the accepted answer from this question by adding a 5th column the color to my data rowsgoogle charts api add blank row to timelinespecifically here is the function i thought i might be able to hijack to build my hackfunction anonymous self calling function to prevent variable name conficts var elcontainergetelementsbytagnamerect get all the descendant rect element inside the container var width10 set a large initial value to width var eltorem element would be added to this array for removal forvar i0iellengthi looping over all the rect element of container var cwidthparseinteligetattributewidthgetting the width of ith element ifcwidthwidth if current element width is less than previous width then this is min width and ith element should be removed eltoremeli widthcwidth setting the width with min width else ifcwidthwidth if current element width is equal to previous width then more that one element would be removed eltorempusheli forvar i0ieltoremlengthi eltoremisetattributefillnone make invisible all the rect element which has minimum widththe hope was to grab each rect skipping the bounding ones and filling them with a third loop at the end with their appropriate colors but i could not figure out how to get their associated color which was in the row objects from the rect objects themselves,"['javascript', 'jquery', 'css']" +896344,ionic emulate ios only works with livereload i have a simple ionic app that i am building and when i test with ionic serve lab everything looks great however when i try to emulate on the simulators with ionic emulate ios or ionic emulate android the app does not load seems like all the js is not coming through i am able to attach the debugger and there are not any console errorsbut when i do try and run the app with ionic emulate ios livereload everything seems to work fine i tried another sample app from scratch to rule out my machine env and it worked fine any ideas on how i can get the emulate to work without livereload,"['android', 'ios']" +896356,sharing swift code and maintaining the code in one place frameworklibrary i would like to create a swift framework and import it into my other projects obviously i would like to share my code by using the framework in question i was only able to find one related question herecreate and import swift frameworkand some tutorials on the internet which did not seem to produce anything useful for me so here is what i have an xcode project with a xcworkspace workspace generated bycocoapods that is the actual application that should use theframework a cocoa touch framework xcode project that is theframeworkwhat are the steps to include the framework 2 into the application 1 i tried using the method described in the linked question above but upon building it says it does not find the actual source files unknown 0 error no such file or directory pathtoprojectmyframeworksomeclaswiftwhere pathtoproject is obviously just a placeholder bounty goal propose a viable option how i could share a set of classes in an efficient way i need to be able to reuse code from one project easily and be able to maintain this code in one place it also needs to be compatible with ios7 so dynamic libraries probably would not do it for me any workflow that would allow me to do what i described above will be a winner thanks,['ios'] +896372,delete user but keep records foreign keys i have a table users with user accounts user id username the user id is related to multiple other tables eg a table with his last actions profile details his products his interests etcsometimes a user wants to be deleted and then i set a field deleted to 1 the records in most of the tables should be deleted but the records in 2 tables reports and messages should keep the reference to the user reason for example a message partner still wants to see the username of the account he recently talked to what is the best way to do this1 in php store the ids of the records in reports and messages that should be kept in an array then delete the user automatically all the tables related to users delete their records with a reference to the deleted account the reference in reports and messages should be on update set null so their records still exists after user delete the database is clean now then reinsert the user with the same user id with the field deleted to 1 then update the data in the array to the user id so the reference is set again2 remove the references to the user in reports and messages so there are no foreign keys3 is there a better optionthanks,"['php', 'mysql']" +896389,slicing a list and group for example if our source list isinput 1 2 3 4 5 6 7 8 9 and i need something like thisoutput 11 223 3456 4789 i try like this but this not work correctlygroups n 1group 1 2 3 4 5 6 7 8 9 10for i in range0 lengroup1 groupsupdatengroupiin n1,['python'] +896465,where to change minsdkversion setting in phonegap app i am having a strange issue when trying to build a basic phonegap app on os x the app is setup with just the android platform i am getting the following error when i enter phonegap buildprocessdebugmanifestvolumesdatatestsmyaplatformsandroidandroidmanifestxml155 errorusessdkminsdkversion 7 cannot be smaller than version 10 declared in library volumesdatatestsmyaplatformsandroidbuildintermediatesexplodedaarandroidcordovalibunspecifieddebugandroidmanifestxmlsuggestion use toolsoverridelibraryorgapachecordova to force usagewhen i then edit the indicated file and set the line tousessdk androidminsdkversiona10a androidtargetsdkversion22 and build again the error does not change does this setting exist somewhere else or is there something else going on here,['android'] +896533,gpuimage and gpuimageview app terminated due to memory error i am using a gpuimage and many gpuimageview instances the purpose is to thisplay the original image layer several slices of filtered images on top and finally animate the slice filters slowly across the original image imagine an image with some sepia bars rolling across to show the normal image and sepia image in sectionsi wrapped this functionality in a subclass of uiview as seen belowimport foundationimport quartzcoreclass filteredimagemaskview uiview initframe cgrect image uiimage superinitframe frame let imageviewframe cgrectmakeframeoriginx 00 framesizewidth framesizeheight let origimage gpuimagepictureimage image origimageforceprocessingatsizerespectingaspectratioimageviewframesize thisplay the original image without a filter let imageview gpuimageviewframe imageviewframe origimageaddtargetimageview origimageprocessimagewithcompletionhandler origimageremovealltargets var contentmode uiviewcontentmodescaleaspectfit imageviewcontentmode contentmode width of the unfiltered region let regularwidth cgfloat 300 width of filtered region let filterwidth cgfloat 300 how much we are moving each bar let totalxmovement regularwidth filterwidth 2 the start x position var currentxforfilter cgfloat totalxmovement the filter being applied to an image let filter gpuimagesepiafilter filterintensity 05 add the filter to the originalimage origimageaddtargetfilter let filteredviewcollection filteredviewcollectionfilteredviews gpuimageview iterate over the x positions until the whole image is covered whilecurrentxforfilter imageviewframewidth totalxmovement let frame cgrectmakecurrentxforfilter imageviewframeoriginy imageviewframewidth imageviewframeheight var filteredview gpuimageviewframe frame filteredviewclipstobounds true filteredviewlayercontentsgravity kcagravitytopleft this is the slice of the overall image that we are going to thisplay as filtered filteredviewlayercontentsrect cgrectmakecurrentxforfilter imageviewframewidth 00 filterwidth imageviewframewidth 10 filteredviewfillmode kgpuimagefillmodepreserveaspectratio filteraddtargetfilteredview add the filteredview to the super view selfaddsubviewfilteredview add the filteredview to the collection so we can animate it later filteredviewcollectionfilteredviewsappendfilteredview increment the x position currentxforfilter regularwidth filterwidth origimageprocessimagewithcompletionhandler filterremovealltargets move to the ui thread threadutilityrunonmainthread add the unfiltered image selfaddsubviewimageview and move it behind the filtered slices selfsendsubviewtobackimageview animate the slices slowly across the image uiviewanimatewithduration200 delay 00 options uiviewanimationoptionsrepeat animations weak filteredviewcollection in if let strongfilteredviewcollection filteredviewcollection ifstrongfilteredviewcollectionfilteredviews nil forvar i 0 i strongfilteredviewcollectionfilteredviewscount i strongfilteredviewcollectionfilteredviewsiframeoriginx totalxmovement strongfilteredviewcollectionfilteredviewsilayercontentsrectoriginx totalxmovement imageviewframewidth completion nil required initcoder adecoder nscoder superinitcoder adecoderclass filteredviewcollection var filteredviews gpuimageview gpuimageview initfilteredviews gpuimageview selffilteredviews filteredviews an instance of filteredimagemaskview is added programmatically to a view in a viewcontroller when that viewcontroller is thismissed the assumption is that the resources will be thisposed i was careful to avoid retain cycles when i watch the memory consumption in the debugger on a real device the memory does drop appropriately when the viewcontroller is thismissed however if i repeatedly load that viewcontroller to look at the image then thismiss it then reload it again i will eventually encounter app terminated due to memory errorif i wait a while after thismissing the viewcontroller the memory errors seem less frequent which leads me to believe the memory is still being released after the viewcontroller is thismissed but i have also seen the error after only a couple times of not so rapid opening and closing of the viewcontrolleri must be using the gpuimage andor gpuimageview inefficiently and i am looking for guidancethanksedit see below for the view controller implementationimport uikitclass viewimageviewcontroller uiviewcontroller fetchimagedelegate var imagemanager imagemanager iboutlet var mainview uiview override func viewdidload superviewdidload imagemanagerfetchimageasyncdelegate self this callback is thispatched on the ui thread func imagefetchcompletedimagedata uint8 let imageview filteredimagemaskviewframe selfmainviewframe image uiimagedata imagedata mainviewaddsubviewimageview var timer nstimerscheduledtimerwithtimeintervalnstimeinterval100 target self selector selectorthisplayreminder userinfo nil repeats false func thisplayreminder show an alert or message here class imagemanager func fetchimageasyncdelegate fetchimagedelegate this thispatches a high priority background thread threadutilityrunonhighprioritybackgroundthread weak delegate in get the image this part could take a while in the real implementation var imagedata uint8 move to the ui thread threadutilityrunonmainthread if let strongdelegate delegate strongdelegateimagefetchcompletedimagedata now that i am looking through this stripped down version does passing self to the imagemanager create a retain cycle even though i reference it weakly to the background thread can i pass that as a weak reference right from the viewimageviewcontroller it is certainly possible that the viewimageviewcontroller is thismissed before the fetchimageasync method completes and the callback is callededit i think i found the issue if you look at the viewimageviewcontroller in the callback i create an nstimer and pass self my suspicion is that is creating a retain cycle if the viewcontroller is thismissed before the timer executes that would explain why if i wait a few extra seconds i do not get the memory error because the timer fires and the viewcontroller thisposes properly here is the fix i think this is on the viewimageviewcontrollervar timer nstimer then instead of creating a new variable assign the timer to the class variableselftimer nstimerscheduledtimerwithtimeintervalnstimeinterval100 target self selector selectorthisplayreminder userinfo nil repeats false and finally on thismiss of the viewcontroller viewwillthisappear or back button click event or bothfunc canceltimer ifselftimer nil selftimerinvalidate selftimer nil,['ios'] +896540,why is php not recognizing a program in the windows system path when i use it with apache in my local development environment i have apache and php installed on windows 7 i am calling 7zip from my php program with exec i tried at first withexec7z a examplezip examplepdfbut it did not create the zip file after checking the apache error log i found7z is not recognized as an internal or external command operable program or batch fileafter changing the exec to include the full path to 7zipexe it workedexeccprogram files7zip7z a examplezip examplepdfbut cprogram files7zip is included in my windows system path the same php code works from the command line without using the full pathphp r exec7z a examplezip examplepdfwhy is it requiring the full path when i use it with apachean important point which i neglected to include when i originally posted this question is that i am already able to use exec to call other programs included in the windows system path without referring to them by their full pathsanother point which i did not mention originally because i did not realize its relevance was that 7zip had been added to the path only recently and i had restarted the apache service after adding it,['php'] +896671,visual studio during debugging the function evaluation requires all threads to run i am getting suddenly a strange error while debugging up to now the variable in the watch windows has been shown correctly now i am getting always the error message in the watch windows the function evaluation requires all threads to run i am not able to check any variable anymore i am not explicit working with threads what can i do to get it working againi thisabled aready as mentioned in some forums the function enable property evaluation and other implicit function calls in the option window of the debugger but without success then i am getting the error error implicit function evaluation thisabled by the usercan somebody help me and get it sorted outthankscheersmaik,['c#'] +896708,what is causing calibri to lose cleartype between 9 and 14 pt what exactly is it that makes gdi switch to binary aliasing when using default microsoft office font calibri between 9pt and 14pt with cleartypegridfit specifiedit is somewhat thisconcerting how many other fonts are also affected by whatever is behind this and at what sizes is there a workaroundexcluding gdi which does not have the same text layout featuresheres the code i used to generate the imageprivate void form1 paintobject sender painteventargs e egraphicstextrenderinghint textrenderinghintcleartypegridfit var height 0 for var i 1 i 17 i using var font new fontcalibri i var text cleartypegridfit i pt egraphicsdrawstringtext font systembrushescontroltext 0 height height integraphicsmeasurestringtext fontheight,['c#'] +896748,how to execute python code from within visual studio code visual studio code was recently released and i liked the look of it and the features it offered so i figured i would give it a go i downloaded the application from the downloads page fired it up messed around a bit with some of the features and then realized i had no idea how to actually execute any of my python codei really like the look and feelusabilityfeatures of visual studio code but i cannot seem to find out how to run my python code a real killer because that is what i program primarily indoes anyone know if there is a way to execute python code in visual studio code,['python'] +896755,specify eml file name using systemnetmailmailaddress or other library i need to file an email when requestedmy code below workssends emailfiles the email when requestedbut does not allow me to specify the file name uses a guid as file nameexample carchiveemail1003d05d11ca45e2a5f4cf2da29c39d9emlpotential solutionssave the file to a temporary folder rename file and then copy to final destinationsave the file using another method better performancepros and conssolution 1 is ugly and has bad performancequestiondoes anyone know how to file an email to myspecifiedfilenameeml without having to rename and then copyexisting codepublic shared sub sendbyval emailfrom as string byval emailto as string byval subject as string byval htmlbody as string optional savetofile as boolean false optional savefilepath as string dim mymsg as mailmessage new mailmessage dim recipients as string recipients splitemailto with mymsg from new systemnetmailmailaddressemailfrom for i 0 to recipientscount 1 if recipientsitostring then toaddnew systemnetmailmailaddressrecipientsi end if next sender new systemnetmailmailaddressemailfrom subject subject body htmlbody bodyencoding systemtextencodingutf8 isbodyhtml true priority mailpriorityhigh end with dim smtpserver as new smtpclientmysettingssmtpserver smtpserversendmymsg rem rem save email when requested rem if savetofile true then dim client as new smtpclientmysettingssmtpserver clientdeliverymethod smtpdeliverymethodspecifiedpickupdirectory clientpickupdirectorylocation savefilepath clientsendmymsg client nothing end if mymsg nothing smtpserver nothingend sub,['c#'] +896827,xcode 631 lost connection to attached device frequently when running my app i will get this occur 3 out of 4 attempts to run the app from xcode hitting enter cmdr will sometimes generate the error again and sometimes rarely actually run debug the code this happens with both an iphone 6 device 83 and a iphone 5 device 82while it is not a show stopper its adding to the development cycle time anyone out there suffering the same issue or anyone have a solutioni have had this happen both with and without a watch extension but it is more pronounced when working on an app with a watch extension,['ios'] +896903,how to optimize my code for finding the count of all integral medians for all possible integral triangles with a b c 10 i am doing the solution for this problem from euler project problem 513 integral medianabc is an integral sided triangle with sides aabac mc is the median connecting c and the midpoint of ab fn is the number of such triangles with can for which mc has integral length as well f103 and f50165find f10analysea b c and 10abc is a triangle so it should absab c abmc sqrt2 a2 2 b2 c2 2 wikipediamc is integer so 2 a2 2 b2 c2 should be a perfect square and divisible by 4codeinclude stdiohinclude mathhdefine and 10define maxab ababvoid main unsigned long int count 0 unsigned long int abc double mc for a 1 a n a printflun a for b a b n b for c maxb absba c n c ab c mc sqrt2 a a 2 b b c c20 if mcunsigned longmc 0 count printfncpt lun countissuesit works fine for small n but the complexity of the solution is too high i assume it is on3am i wrong which will take days for n 10 how could i improve this whether with a mathematical or algorithmic wayupdatesi got those suggestionscalculating power of a outside the bc loops and power of b outside c loop this improved slightly the performancec cannot be odd then a and b must have same parity this improved the performance 4 timesusing threads to divide the work on many cores it may improve by a factor close to number of cores a mathematical solution posted in mathstackexchange it claims on52 for a basic solution and can achieve on2 by using on2 of memory i did not test it yet,['c'] +896914,debugging digest already in progress error i am building a complex hybrid app and have been testing on a real device occasionally i am getting the dreaded digest already in progress error from angular especially it appears to be after a somewhat long digest cycle from the stack trace it appears to be initiated from an angular defer function that updates the locationhref which then triggers fastclick to send a touchend that in turn triggers a second digest leading to the error has anyone experienced this same error and if so how did you go about resolving itfor those interested here is what i am seeing in the stacktraceerror rootscopeinprog digest already in progressrootscopeinprogp024digestfileprivatevarmobilecontainersbundleapplication4040564a56314a1ab2fd6e53f9a574f2testappwjs3rdpartyangularangularjs8032beginphasefileprivatevarmobilecontainersbundleapplication4040564a56314a1ab2fd6e53f9a574f2testappwjs3rdpartyangularangularjs1447331applyfileprivatevarmobilecontainersbundleapplication4040564a56314a1ab2fd6e53f9a574f2testappwjs3rdpartyangularangularjs1422021fileprivatevarmobilecontainersbundleapplication4040564a56314a1ab2fd6e53f9a574f2testappwjs3rdpartyangularangularjs2252329eventhandlerfileprivatevarmobilecontainersbundleapplication4040564a56314a1ab2fd6e53f9a574f2testappwjs3rdpartyangularangularjs301325thispatcheventsendclickfileprivatevarmobilecontainersbundleapplication4040564a56314a1ab2fd6e53f9a574f2testappwjs3rdpartyfastclickfastclickjs29530ontouchendfileprivatevarmobilecontainersbundleapplication4040564a56314a1ab2fd6e53f9a574f2testappwjs3rdpartyfastclickfastclickjs58918fileprivatevarmobilecontainersbundleapplication4040564a56314a1ab2fd6e53f9a574f2testappwjs3rdpartyfastclickfastclickjs10543urlfileprivatevarmobilecontainersbundleapplication4040564a56314a1ab2fd6e53f9a574f2testappwjs3rdpartyangularangularjs502219setbrowserurlwithfallbackfileprivatevarmobilecontainersbundleapplication4040564a56314a1ab2fd6e53f9a574f2testappwjs3rdpartyangularangularjs1108021fileprivatevarmobilecontainersbundleapplication4040564a56314a1ab2fd6e53f9a574f2testappwjs3rdpartyangularangularjs18640evalfileprivatevarmobilecontainersbundleapplication4040564a56314a1ab2fd6e53f9a574f2testappwjs3rdpartyangularangularjs1412328digestfileprivatevarmobilecontainersbundleapplication4040564a56314a1ab2fd6e53f9a574f2testappwjs3rdpartyangularangularjs1393936fileprivatevarmobilecontainersbundleapplication4040564a56314a1ab2fd6e53f9a574f2testappwjs3rdpartyangularangularjs1416133completeoutstandingrequestfileprivatevarmobilecontainersbundleapplication4040564a56314a1ab2fd6e53f9a574f2testappwjs3rdpartyangularangularjs487715fileprivatevarmobilecontainersbundleapplication4040564a56314a1ab2fd6e53f9a574f2testappwjs3rdpartyangularangularjs525033,['javascript'] +897026,how to create msdeploy package using msbuild for all files in this project folder i am trying to create a web deploy package using msbuild through command line i have been searching all over and found the following command msbuild myprojectcsproj tpackagethough it works for me but it gives me only what visual studio gives us back when we create web deploy package through packgepublish web tab with only files needed to run this application option selected from the drop down menu but i want my web deploy package to look exactly the same as what i get when i select all files in this project folder option from the drop down menu i have gone through links like this but i wonder that do i really need to customize my csproj file the way its been described in that post since all i want is a command line apparently more elaborate than the one i mentioned above for msbuild that can imitate the all files in this project folder option that populates the bin folder of web deploy package with all the dlls that are there in the original bin folder of my project and generate me a more comprehensive package,['asp.net'] +897074,remove object from array of objects i am have array of objectsvalue14label7value14label7value18label7how i can delete this item value14label7 and resulting in the new array value14label7value18label7,['javascript'] +897101,ensure that a certain script loads before another script i cannot get how the scripts in a page are loaded i have jquery plugins that depend on other scripts i am using the timeago jquery plugin i have loaded this script in head in order script srcphp echo base urlcontentscriptsjqueryenginejqueryjs typetextjavascriptscript jquery library script srcphp echo base urlcontentscriptstimeagojs typetextjavascriptscript timeago script srcphp echo base urlcontentscriptsmyscriptjs typetextjavascriptscript custom scripts that contains ajaxand in document ready i am initializing timeago but this is not working for me in the console the browser shows timeago is not functioning what i want is to ensure that timeago has already loaded before any other script runs my scripts also contains multiple ajax calls that rely on timeago,"['javascript', 'jquery']" +897104,how to have a relationship based on a nonkey field i have two entities as following when i try to add items to my car table it shows following error messagetherefore it does not allow me to have more than one car with auto transmissionerror 1062 duplicate entry auto for key uk bca5dfkfd4fjdhfh4ddirfhdhesr entitiescarentitypublic class car implements javaioserializable id generatedvalue long id columnnametransmission nullable false string transmission onetomanyfetch fetchtypelazy mappedby car setcarfactory factories sample values for car table10 auto12 auto43 manual54 manual65 normal68 standard90 normal99 nogearcarfactoryentitypublic class carfactory implements javaioserializable id joincolumnnametransmissionreferencedcolumnname transmission manytoone car car id joincolumnnamefactory id referencedcolumnname id manytoone factory factory expected values for carfactory tableauto fac1auto fac2manual fac1auto fac5standard fac6normal fac3nogear fac1ive followed answer of this question as well but it did not worklong story short i need to have a table with two foreign keys from other tables with combined primary key it should not force unique foreign key in participating tables,['java'] +897123,android facebook sdk 40 login without facebook app i am having issues with the webview login for facebook on android i have followed the tutorials and login works perfectly when the user has the facebook app installed when the facebook app is not installed the webview for facebook login pops up however after logging in and accepting the permissions the webview simply redirects back to the login screen it never goes back to my apphas anyone else encountered this problem facebooksdksdkinitializethis profiletracker new profiletracker override protected void oncurrentprofilechangedprofile profile profile profile2 if profile2 null loggedinprofile2 else loggedout accesstokentracker new accesstokentracker override protected void oncurrentaccesstokenchangedaccesstoken accesstoken accesstoken accesstoken2 profilefetchprofileforcurrentaccesstoken callbackmanager callbackmanagerfactorycreate loginmanagergetinstanceregistercallbackcallbackmanager new facebookcallbackloginresult override public void onsuccessloginresult loginresult app code getprofileinfo override public void oncancel app code logefacebook login login cancelled loggedout override public void onerrorfacebookexception exception app code logefacebook login failed to login exceptiontostring loggedout looking at the logs without filters while the login takes place i see a couple of possibly relevant logsichromiumi1 infoconsole0 eventreturnvalue is deprecated please use the standard eventpreventdefault instead source 0iauthcorei1 tokencache missing snowballing token no granted scopes set,['android'] +897129,image upload with ajax i know there are many tutorials but i cannot figure out how to make them worki have an input form for file uploadinput onchangeuserpreviewimagethis typefile acceptimage stylethisplaynonethere is my javascript codefunction userpreviewimage fileinput save true var files fileinputfiles var file files0 current file var imagetype image var img documentcreateelementimg imgclasslistaddobj imgclasslistaddpreview imgfile file var reader new filereader readeronload functionaimg return functione aimgsrc etargetresult img readerreadasdataurlfileas a result i have img which is an object img srcdataimagepngbase64 which i can print outi have been using this for a while but now i need to change the workflowmy goal now is instead of printing the image send its source to the server the server code is working finei cannot figure out how to get the image source from what i have just the dataimagepngbase64 part can someone give me a tip,"['javascript', 'jquery']" +897148,cpu andor ram productivity when working with big integers yesterday i was solving one exam problem when found something very interesting at least for me the program is for factorials very big ones and the result is how much zeroes there are on the end of the number in some cases 2500 zeros so i did what i could but found that when enter number like 100 0 it takes exactly 130 133min to output the result i thought its because of my cpu it is not very fast i have sent the exe to some of my friends to try it because they have very good pcs when we are talking about performance exactly the same result 133min my question is why is the time to solve the task the same i know there are better ways to write my core so it wouldnt take so long but this is very important for me to understand as a beginner programmerso here is my codestatic void main int num intparseconsolereadline zerocounter 0 biginteger fact 1 var starttime datetimenow consolewriteline for int i 1 i num i fact i consolewriter0 datetimenow starttime biginteger facttarget fact while facttarget 10 0 facttarget 10 zerocounter consolewriter0 datetimenow starttime consolewriteline consolewritelineresult is number with 0 zeros zerocounter consolewriteline consolewritelinefinished for 0 datetimenow starttime consolewriteline consolewritelinenpres any key to exit consolereadkey i am very sorry if this is the wrong place to ask i did my best to find what i was looking for before i post this,['c#'] +897157,does freeing an int which was assigned to a char allocated by malloc invoke undefined behavior the title maybe confusing suppose str is a pointer allocated by malloc ptr of type int is assigned to it and is freed as shown by the code snippet belowchar str malloc64int ptr strfreeptri have tried to compile the above code it just gives a warningsource filec in function amainasource filec1016 warning initialization from incompatible pointer type int ptr str does the above code invoke undefined behaviordoes the above code snippet free the memory allocated by malloc for str,['c'] +897179,documenting javascript code in vscode for intellisense i am trying to get proper intellisense suggestions for my javascript code in visual studio code in particular i have the following angluarjs service reference pathdefinitelytypedangularjsangulardts var module angularmodule testapp modulefactory backend function http return getcomments function hoverheretoseetype post summaryretrieves comments from the backendsummary param namepost typestringpost to retrieve comments forparam return httpget rest post i thought i should be using xml documentation comments but they do not seem to work when i hover over hoverheretoseetype the parameter is shown as any while the return value is properly inferred using angulardts so the first part of the question is how do i annotate types in my functionsthe second part of the question comes up when actually trying to use the servicemodulecontroller myctrl function backend backendgetcomments test i get that intellisense does not understand angulars dependency injection so i will need to annotate backends type but how do i reference that typein short how do i get proper intellisense for the backendgetcomments call in the second snippet ie the information that the parameter has to be a string and the returned value will be an ngihttppromise,['javascript'] +897213,ajax function is not working by scroll using ajax for endless scroll content loads only first time but doest load by scroll what is wrongjqueryfunction loadfeed ajax url loadmorephp datatype html success function data postsappenddiv classhavanagiladiv postshtmldata loadfeedwindowscrollfunction var windowscroll windowscrolltop var windowheight windowheight var documentheight documentheight if windowscroll windowheight documentheight loadfeed loadmorephpphp session startif isset sessionlogin login sessionlogin id sessionid usernameroot passwordroot hostname localhost dbname kotik function testdb connect hostname username password dbh new pdomysqlhosthostnamedbnamekotik username password return dbh try dbh testdb connect hostname username password catchpdoexception e echo egetmessage php title select query dbh prepareselect title from books where id id order by date desctitle select query executearrayid idtitle select query result title select queryfetchcolumn echotitle select query resulttitle select query result title select queryfetchcolumn echotitle select query resulttitle select query result title select queryfetchcolumn echotitle select query resulttitle select query result title select queryfetchcolumn echotitle select query resulttitle select query result title select queryfetchcolumn echotitle select query result,"['javascript', 'php', 'jquery']" +897230,why are java 8 lambdas invoked using invokedynamic invokedynamic instruction is used to help the vm determine the method reference at runtime instead hardwiring it at compile time this is useful with dynamic languages where the exact method and argument types is not known until runtime but that is not the case with java lambdas they are translated to a static method with well defined arguments and this method can be invoked using invokestaticso then what is the need of invokedynamic for lambdas specially when there is a performance hit,['java'] +897323,how does gson typetoken work i understand that in java contrary to for example c generics are compiletime feature and is removed via type erasure so how does gsons typetoken really work how does it get the generic type of an object,['java'] +897371,gridview inside expandablelistview with multiple choice on android in my app i need to show images inside a expandablelistview and it has to be a gridview of images and these images can be selectable so i have an expandablelistadapter and inside of it i am implementing a gridview adapterthe images are showing fine as you can see in the picture 1 now what i am trying to achieve is the picture 2 how can i pass the groupposition and the childposition to the gridadapter and whe i click on the image make it highlight picture 2 public class expandlistadapter extends baseexpandablelistadapter public static final int choice mode multiple abslistviewchoice mode multiple public static final int choice mode multiple modal abslistviewchoice mode multiple modal no child could be selected public static final int choice mode none abslistviewchoice mode none one single choice per group public static final int choice mode single per group abslistviewchoice mode single one single choice for all the groups public static final int choice mode single absolute 101 private context context private arraylistgroup groups private arraylistarraylistchild child new arraylist private arraylistchild listchild private gridadapter adapter private customgridview gridview private sparsearraysparsebooleanarray checkedpositions private static final string log tag expandlistadapterclassgetsimplename private int choicemode choice mode multiple public expandlistadaptercontext context arraylistgroup groups thiscontext context thisgroups groups checkedpositions new sparsearraysparsebooleanarray child new arraylist for int i 0 i groupssize i childaddi groupsgetigetitems public expandlistadaptercontext context arraylistgroup children int choicemode thiscontext children for now the choice mode choice mode multiple modal is not implemented if choicemode choice mode multiple modal throw new runtimeexceptionthe choice mode choice mode multiple modal has not implemented yet thischoicemode choicemode override public object getchildint groupposition int childposition return childgetchildposition override public long getchildidint groupposition int childposition return childposition override public view getchildviewfinal int groupposition final int childposition boolean islastchild view convertview viewgroup parent if convertview null layoutinflater infalinflater layoutinflater context getsystemservicecontextlayout inflater service convertview infalinflaterinflaterlayoutgridview null listchild new arraylistchild for int j 0 j groupsgetgrouppositiongetitemssize j listchildaddchildgetgrouppositiongetj gridview customgridview convertviewfindviewbyidridgridview toolbar gridviewsetexpandedtrue adapter new gridadaptercontext listchild checkedpositions groupposition childposition gridviewsetadapteradapter adapter gridviewsetchoicemodecustomgridviewchoice mode multiple gridviewsetonitemclicklistenernew adapterviewonitemclicklistener override public void onitemclickadapterview parent view view int position long id setclickedgroupposition childposition systemoutprintlnposition checkedpositionsgetgroupposition if checkedpositionsgetgroupposition null boolean ischecked checkedpositionsgetgrouppositiongetchildposition ifischecked else systemoutprintlnfalse return convertview public void setclickedint groupposition int childposition switch choicemode case choice mode multiple sparsebooleanarray checkedchildpositionsmultiple checkedpositionsgetgroupposition if in the group there was not any child checked if checkedchildpositionsmultiple null checkedchildpositionsmultiple new sparsebooleanarray by default the status of a child is not checked so a click will enable it checkedchildpositionsmultipleputchildposition true checkedpositionsputgroupposition checkedchildpositionsmultiple else boolean oldstate checkedchildpositionsmultiplegetchildposition checkedchildpositionsmultipleputchildposition oldstate break todo implement it case choice mode multiple modal throw new runtimeexceptionthe choice mode choice mode multiple modal has not implemented yet case choice mode none checkedpositionsclear break case choice mode single per group sparsebooleanarray checkedchildpositionssingle checkedpositionsgetgroupposition if in the group there was not any child checked if checkedchildpositionssingle null checkedchildpositionssingle new sparsebooleanarray by default the status of a child is not checked checkedchildpositionssingleputchildposition true checkedpositionsputgroupposition checkedchildpositionssingle else boolean oldstate checkedchildpositionssinglegetchildposition if the old state was false set it as the unique one which is true if oldstate checkedchildpositionssingleclear checkedchildpositionssingleputchildposition oldstate else does not allow the user to uncheck it break this mode will remove all the checked positions from other groups and enable just one from the selected group case choice mode single absolute checkedpositionsclear sparsebooleanarray checkedchildpositionssingleabsolute new sparsebooleanarray checkedchildpositionssingleabsoluteputchildposition true checkedpositionsputgroupposition checkedchildpositionssingleabsolute break notify that some data has been changed notifydatasetchanged logvlog tag list position updated logvlog tag printsparsearrayssparsearraytostringcheckedpositions public void setchoicemodeint choicemode thischoicemode choicemode for now the choice mode choice model multiple modal is not implemented if choicemode choice mode multiple modal throw new runtimeexceptionthe choice mode choice mode multiple modal has not implemented yet checkedpositionsclear logvlog tag the choice mode has been changed now it is thischoicemode override public int getchildrencountint ngroup return 1 override public object getgroupint groupposition return groupsgetgroupposition override public int getgroupcount return groupssize override public long getgroupidint groupposition return groupposition override public view getgroupviewint groupposition boolean isexpanded view convertview viewgroup parent group group group getgroupgroupposition if convertview null layoutinflater inf layoutinflater context getsystemservicecontextlayout inflater service convertview infinflaterlayoutgroup item null expandablelistview mexpandablelistview expandablelistview parent mexpandablelistviewexpandgroupgroupposition textview tv textview convertviewfindviewbyidridgroup name tvsettextgroupgetname return convertview override public boolean hasstableids return true override public boolean ischildselectableint groupposition int childposition return true gridadapterpublic class gridadapter extends baseadapter private context mcontext private arraylistchild child imageloader imageloader appcontrollergetinstancegetimageloader private sparsearraysparsebooleanarray checkedpositions int groupposition childposition public gridadaptercontext context arraylistchild childvalues sparsearraysparsebooleanarray checkedpositions int groupposition int childposition mcontext context child childvalues thischeckedpositions checkedpositions thischildposition childposition thisgroupposition groupposition override public int getcount return childsize override public object getitemint position return position override public long getitemidint arg0 return 0 override public view getviewint position view convertview viewgroup parent viewholder holder null networkimageview i childposition position if convertview null layoutinflater inflater layoutinflater mcontext getsystemservicecontextlayout inflater service convertview inflaterinflaterlayoutchild item null holder new viewholder if imageloader null imageloader appcontrollergetinstancegetimageloader i networkimageview convertview findviewbyidridflag isetimageurlstringvalueofchildgetchildpositiongetimage imageloader convertviewsettagholder systemoutprintlnposition checkedpositionsgetgroupposition if checkedpositionsgetgroupposition null boolean ischecked checkedpositionsgetgrouppositiongetchildposition isetbackgroundresourcercolorbg ifischecked else systemoutprintlnfalse else holder viewholder convertviewgettag holdertext textview convertviewfindviewbyidridlabel holdertextsettextchildgetpositiongetname return convertview static class viewholder textview text,"['java', 'android']" +897372,cannot find embedded resource using getmanifestresourcestream i am currently working on a card dll in which i would need the image files for each card as an embedded resource the current project looks like thisnote the card images png are in the resources folderthe code i have been trying is pretty much the only code i can find is thisassembly assemblystream imagestreamprivate image imgpublic image img get return img public kaart this5 spades public kaartint val string s thiskaartwaarde val thisfiguur s this imagestream imgs thisimg new image imagestreamprivate stream imgs try assembly assemblygetexecutingassembly stream s assemblygetmanifestresourcestreamstringformat01png thiskaartwaarde thisfiguursubstring0 1 if s null return s else return null catch throw new exceptionkaart kan niet geladen worden the only exception i seem to get is an exception in the creation of the kaart object for which the code is herekaart k nulltry k new kaartcatch exception ex messageboxshowexmessage this messagebox is being shownimagesourceconverter c new imagesourceconvertertestboxsource imagesourcecconvertfromkimgthe exception being caught shown by use of messagebox is as followsvalue of null is not valid for streamwhile watching my variables during code execution i noticed somehow the linestream s assemblygetmanifestresourcestreamstringformat01png thiskaartwaarde thisfiguursubstring0 1fails to find the image even when using the format kaarten01pngthis simply makes me wonder if i am doing something wrong here or if i am using the wrong syntax any ideaseditimages are now being loaded properly however the imagesourceconverter is still throwing a nullreferenceexceptioncard creation loading the stream objects and unloading them into an image object are working fine now as far as i can tell however when trying to actually show the images in my wpf image control using the code below the nullrefexception is thrownkaartspel kaarten new kaartspelkaart k kaartenkaarten7imagesourceconverter c new imagesourceconvertertestboxsource imagesourcecconvertfromkimg exception here,['c#'] +897374,basic java float and integer multiplication casting i have the following codefloat f 15fint i 3i fi receive no warning but if i doi ifi receive an incompatible type warning why does java automatically cast the first multiplication but not the second what is the reasoning behind this,['java'] +897404,why does not java allow me to access private method through method of the same class i have code that looks like thispublic class at extends a private t one return t this protected t two return t this protected void three twoone and intellij tells me that one has private access in a but hey why cannot i call the private member of the same class,['java'] +897551,the template thisambiguator for dependent names this issue is based on section c reference dependent name the template thisambiguator for dependent name i have understood when invoking the template member function in a template class the keyword template is necessary to make the compiler know the following bracket is used for indicating template argumentjust like the used example in this sectiontemplatetypename tstruct s templatetypename u void footemplatetypename tvoid bar st s sfoot error parsed as less than operator stemplate foot okhowever in the consequent part it describes when a template name appears in a member access expression after or after the thisambiguator is unnecessary if there is a template with the same name found by ordinary lookup in the context of the expressionthen it comes with the following code comparing with previous example it defines set function whose name exists in standard library as well at the meanwhile using stdset is set up to make set template visible in template functionin this condition even if keyword template is not provided it still works wellinclude setusing stdset makes set visible to lookup from bartemplatetypename t struct s templatetypename u void settemplatetypename tvoid bar st s ssett not an error if set is visible and since c11 this is wellformed stemplate sett works with and without setbased on my understanding i tried my own version include iostreamtemplate typename t struct s template typename u void func stdcout in sfuncn in order to make member template function is visible in function test defining a global template function func whose name is same with one member template function in struct stemplate typename mvoid func stdcout from ordinary funcntemplate typename mvoid test sm s funcm test func template function is visible in test function sfuncm int main testintthe detail error message is listed as follows171750ryuc test g g typename2cpp typename2cpp617 error use template keyword to treat func as a dependent template name sfuncm template 1 error generatedany advice is appreciated on how to make my own code works well without keyword template,['c++'] +897557,efficiently moving dataframes from pandas to r with rpy or other means i have a dataframe in pandas and i want to do some statistics on it using r functions no problem rpy makes it easy to send a dataframe from pandas into rimport pandas as pddf pddataframeindexrange10columnsrange100from rpy2 import robjects as roroglobalenvdf dfand if were in ipythonload ext rmagicr i dffor some reason the roglobalenv route is slightly slower than the rmagic route but no matter what matters is this the dataframe i will ultimately be using is 100gb this presents a few problemseven with just 1gb of data the transfer is rather slowif i understand correctly this creates two copies of the dataframe in memory one in python and one in r that means i will have just doubled my memory requirements and i have not even gotten to running statistical testsis there any way totransfer a large dataframe between python and r more quicklyaccess the same object in memory i suspect this asking for the moon,['python'] +897572,device token not received when registering for remote notifications in swift i somehow can not receive the device token when registering for remote notifications i get the modal saying do you want to allow app x to be able to send you notificaitons but when i accept it the didregisterforremotenotifications function is not called when i register for remote notifications in ios 8swift using this code uiapplicationsharedapplicationregisterforremotenotifications let settings uiusernotificationsettingsfortypes uiusernotificationtypebadge uiusernotificationtypealert uiusernotificationtypesound categories nil uiapplicationsharedapplicationregisterusernotificationsettingssettings uiapplicationsharedapplicationregisterforremotenotificationsthese functions are not triggered at all func applicationapplication uiapplication didregisterforremotenotificationswithdevicetoken devicetoken nsdata andfunc applicationapplication uiapplication didfailtoregisterforremotenotificationswitherror error nserror however when i log this printlncurrent settings uiapplicationsharedapplicationcurrentusernotificationsettings and uiapplicationsharedapplicationisregisteredforremotenotificationsi receive current settings uiusernotificationsettings 0x170437120 types uiusernotificationtypealert uiusernotificationtypebadge uiusernotificationtypesound and true my provisioning profile and certificates ar all in order has someone else had this problem,['ios'] +897623,why does lambda translation need generation of a static method lambda translation is a two step process one desugaring the lambda into a static method in same classpublic class main public static void mainstring args runnable r systemoutprintlnhello systemoutprintlnarraysaslistmainclassgetdeclaredmethods private static void mainlambdamain0 public static void mainmainjavalangstringtwo generation of a class that implements the functional interfacesystemoutprintlna class has been generated rgetclasystemoutprintlnthat implements a functional interface arraysaslistrgetclassgetinterfacesa class has been generated class mainlambda1149928006 that implements a functional interface interface javalangrunnablequestion what is the need of this static method why cannot the lambda body be put directly into the interface method something like class mainlambda1 public void run lambda body here,['java'] +897683,viewpager setcurrentitem slide i have an activity contains viewpager first fragment in this viewpager contains listview and when i click on any item it replaces this fragment with selected one i use setcurrentitemselecteditemtruefor smooth scroll but viewpager slides over all fragments before selected fragment i want it to slide to selected fragment only not over all fragmentsi tried to use pagetransfromtransformpage like that overridepublic void transformpageview page float position int currentitem viewpagergetcurrentitem if currentitem selecteditem pagesetvisibilityviewgonebut with no luck,['android'] +897765,inject css to a site with webview in android for example i want to change the backgroundcolor of wgooglecomto redi have used webview and my stylecssfile is in assest folder i want to inject this stylecss file to wgooglecom what is wrong with my codes please write the correct codes for me thanksmy mainactitviyjava file package comexamplemysinaimport androidsupportv7appactionbaractivityimport androidosbundleimport androidviewmenuimport androidviewmenuitemimport androidwebkitwebviewpublic class mainactivity extends actionbaractivity override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main webview webview new webviewthis setcontentviewwebview string html htmlheadstyle src urlfileandroid assetstylecstyleheadhtml webviewloaddatahtml texthtml utf8 webviewloadurl override public boolean oncreateoptionsmenumenu menu inflate the menu this adds items to the action bar if it is present getmenuinflaterinflatermenumain menu return true override public boolean onoptionsitemselectedmenuitem item handle action bar item clicks here the action bar will automatically handle clicks on the homeup button so long as you specify a parent activity in androidmanifestxml int id itemgetitemid if id ridaction settings return true return superonoptionsitemselecteditem,"['android', 'css']" +897785,create hexagon imageview shape in ios i want above hexagon shape for my imageview but after implementing below code i am getting this image uibezierpath roundedpolygonpathwithrectcgrectsquare linewidthcgfloatlinewidth sidesnsintegersides cornerradiuscgfloatcornerradius uibezierpath path uibezierpath bezierpath cgfloat theta 20 m pi sides how much to turn at every corner cgfloat offset cornerradius tanftheta 20 offset from which to start rounding corners cgfloat squarewidth minsquaresizewidth squaresizeheight width of the square calculate the length of the sides of the polygon cgfloat length squarewidth linewidth if sides 4 0 if not dealing with polygon which will be square with all sides length length cosftheta 20 offset20 offset it inside a circle inside the square cgfloat sidelength length tanftheta 20 start drawing at point in lower right corner cgfloat calc squarewidth 20 sidelength 20 offset cgpoint point cgpointmakecalc squarewidth squarewidth length 20 cgfloat angle m pi path movetopointpoint draw the sides and rounded corners of the polygon for nsinteger side 0 side sides side point cgpointmakepointx sidelength offset 20 cosfangle pointy sidelength offset 20 sinfangle path addlinetopointpoint cgpoint center cgpointmakepointx cornerradius cosfangle m pi 2 pointy cornerradius sinfangle m pi 2 path addarcwithcentercenter radiuscornerradius startangleangle m pi 2 endangleangle theta m pi 2 clockwiseyes point pathcurrentpoint we do not have to calculate where the arc ended uibezierpath did that for us angle theta path closepath return path cgfloat linewidth 50 uibezierpath path self roundedpolygonpathwithrectcelleventimageviewbounds linewidthlinewidth sides6 cornerradius10 cashapelayer mask cashapelayer layer maskpath pathcgpath masklinewidth linewidth maskstrokecolor uicolor clearcolorcgcolor maskfillcolor uicolor whitecolorcgcolor celleventimageviewlayermask mask cashapelayer border cashapelayer layer borderpath pathcgpath borderlinewidth linewidth borderstrokecolor uicolor blackcolorcgcolor borderfillcolor uicolor clearcolorcgcolor celleventimageviewlayer addsublayerborderplease help me how can i implement this and i have never used bezier paths beforethanks in advance,['ios'] +897905,uibarbuttonitem in navigation bar programmatically i have been looking around for this solution for a while but have not got any eg one solution is selfnavigationitemsetrightbarbuttonitemuibarbuttonitembarbuttonsystemitem stop target self action nil animated truethis code will add a button with stop image just like this there are other solutions with search refresh etc but what if i want to add a button programmatically with the image i want,['ios'] +897911,google appengine datastore is extremely slow i need help in understanding why the below code is taking 3 to 4 secondsupdate use case for my application is to get the activity feed of a person since last login this feed could contain updates from friends or some new items outside of his network that he may find interesting the activity table stores all such activities and when a user logs in i run a query on the gaedatastore to return above activities my application supports infinite scrolling too hence i need the cursor feature of gae at a given time i get around 32 items but the activities table could have millions of rows as it contains data from all the userscurrently the activity table is small and contains 25 records only and the below java code reads only 3 records from the same tableeach record in the activity table has 4 uuid fieldsi cannot imagine how the query would behave if the table contained millions of rows and result contained 100s of rowsis there something wrong with the below code i have belowi am using objectify and appengine cursorsfilter filter new filterpredicatecreatorid filteroperatorequal useridqueryactivity query ofyloadtypeactivityclassfilterfilterquery querystartatcursorfromwebsafestringpreviouscursorstringqueryresultiteratoractivity itr queryiteratorwhile itrhasnext activity a itrnext systemoutprintln ai have gone through google app engine application extremely slow and verified that response time improves if i keep on refreshing my page which calls the above code however the improvement is only 30compare this with any other database and the response time for such tiny data is in milliseconds not even 100s of millisecondsam i wrong in expecting a regular database kind of performance from the gae datastorei do not want to turn on memcache just yet as i want to improve this layer without caching first,['java'] +897980,android studio 12 gradle is very slow it is been a while that i am using android studio and up until now i was using 101 gradle was a bit slow around 15 minute for assembledebug my project is really bigbut today i updated my as to 12 and now same process takes about 7 to 10 minutes and sometimes even with no resultis there any setting i have to change to make it faster honestly taking 10 minute for every debug run is a nightmare also most of the time my cpu usage is arround 10 percent it is actually idlecause before when gradle was working it was on 100 almost all the time,['android'] +898014,java inputstream to bytebuffer i am reading dds textures but since once built the jar i cannot access those textures through url and file and have to use inputstream insteadso i would need to know how i can obtain a javaaniobytebuffer from an javaioinputstreamps no matter through 3rd part libraries i just need it working,['java'] +898028,semitransparent slanted background i want to create an html element eg a div which is styled as followssemitransparent backgroundcolorrounded borders on all edgesleft side of the div draws a straight lineright side of the div draws a skewed linei would like to create this in css only and wonder if this is possible so far i came up with two different approaches which have their own drawbacks and are not fully sufficient you can have a look at those in this fiddleonesideskew1onesideskew2 fontsize 20px padding 2 backgroundcolor rgba220 50 255 06 position relative thisplay block borderradius 4px zindex 2 color f margintop 30pxonesideskew2 bordertoprightradius 0pxonesideskew1after height 100 width 20 position absolute top 0 left 85 thisplay inlineblock content backgroundcolor rgba220 50 255 06 moztransform skewx10deg webkittransform skewx10deg mstransform skewx10deg otransform skewx10deg transform skewx10deg zindex 1 borderradius 4pxonesideskew2after bordertop 1em solid rgba220 50 255 06 borderleft 025em solid rgba220 50 255 06 borderright 025em solid transparent borderbottom 1em solid transparent bordertoprightradius 4px left 100 thisplay inlineblock position absolute content top 0container width 500pxdiv classcontainer div classonesideskew1 span classinnertextone side skew with pseudo element skewedspan div div classonesideskew2 span classinnertextone side skew with pseudo element borderspan divdivapproach 1 onesideskew1 uses a div element with round borders and a skewed roundbordered pseudo element to create a oneside skewed element in sum this works great as long as the backgroundcolor is solid for semitransparent backgrounds you will see an ugly color overlap where the element and its pseudoelement meetapproach 2 onesideskew2 uses a div element with a pseudo behind it that consists of borders only it is somewhat hacky but gets close to my desired result still the right does not look nearly as smooth as in the first approach does someone else have a good solution for this problem in css only or will i have to use a fallback solution with a semitransparent backgroundimage to solve this,['css'] +898113,zing feed plotting multiple series in 1 chart i am trying to plot 2 line series data in zingchart feedbelow is my script codescriptvar chartdata typeline refresh type feed transport js url feed interval 10 series values values windowonload function zingchartrender id chartdiv data chartdata height 600 width 100 windowfeed functioncallback ajax type get datatype json headers accept applicationjson accesscontrolalloworigin url performancemonitorshowprocessusageprocessname success function data var mem datamemsize10 var tick plot0 parseintmem callbackjsonstringifytick var tick2 plot1parseintmem10 callbackjsonstringifytick2 it gets thisplayed but looses the line nature of the graphis this the right way is there a better method later i am planning to let user decide how many plots to be allowed in chart at runtimeis there something in zingchart that i can make use of thanks in advance,['javascript'] +898242,initialize char array in c i am not sure what will be in the char array after initialization in the following waychar buf50is that equivalent to char buf50,['c'] +898289,cannot find nor install mysql config i get this error from inspircdcannot exec mysql config no such file or directory at homealphainspircd2019makeutilitiespm line 392 flags line 37make sure you have pkgconfig installedin the case of gnutls configuration errors on debianubuntu etc you should ensure that you have installedgnutlsbin as well as libgnutlsdev and libgnutlsi have been looking all over the internet trying to find out how to remove the errorsi have read multiple threads but no luck i know i need the libmysqlclientdev package but i cannot for the life of me get it installedi runsudo aptget install libmysqlclientdevalso tried cleaning f and so on but i still get the errorthe following packages have unmet dependencieslibmysqlclientdev depends libmysqlclient18 55400ubuntu1 but 55410ubuntu014041 is to be installede unable to correct problems you have held broken packages,['mysql'] +898315,what are the differences between conda and anaconda i first installed anaconda on my ubuntu at anaconda when i was trying to update my anaconda according to the documentation from continuum analytics i should use the following commandsconda update condaconda update anacondathen i realized that i did not have conda installed so i installed it using the documentation from hereafter conda is installed when i run conda update anaconda i got the following errorerror package anaconda is not installed in homexiangminicondait appears conda is assuming my anaconda is installed under homexiangminiconda which is not truemy questions arewhat is the differences between conda and anacondahow can i tell conda where my anaconda is installed,['python'] +898340,scale div to fit background image i have a div with a background image that i want to expand 100 width and auto scale the div to fit the required height of the image at the moment it is not scaling the div height unless i set the height of the div to 100 but then it just stretches to the full height of the screen whereas i want it to scale to the height of the image here is the htmldiv idmainheaderwrapperdivend mainheaderwrapperbr classclear here is the css mainheaderwrapper background urlhttplocalhostsitegallerybg1jpg width 100 height auto webkitbackgroundsize cover mozbackgroundsize cover obackgroundsize cover backgroundsize cover backgroundsize 100 100 backgroundrepeat norepeat backgroundposition center center clear clear both thanks for any and all help,"['html', 'css']" +898430,calculations of the path of the sun i am writing several methods necessary to calculate the path of the sun across a specific point i have written the code using two different sources for my calculations and neither is producing the desired result the sources are andnote degrees to arcminutes is deg 60 minlocalsolartime i have converted the longitude to minutes the local standard time meridianlstm derived from the localstandardtimemeridian method returns a value that is in minutes and the equationoftime which is also returned in minutes using the equation from pveducation i have calculated the time correction which accounts for the small time variations within a given time zone when i apply this result and the localtime each in minutes to the local solar time lst equation the result is 676515 at this moment which does not make any sense to me the local solar time as i understand it represents the time with respect to the sun and when it is at its highest point in the sky locally is considered solar noon 676515 does not make sense does anybody understand what might be causing this hourangle i am hoping that once i fix the localsolartime method this will not need to be corrected i have chosen washington dc for the latitude and longitude both the zenith and azimuth readings should be positive values and for my region at this moment are 66 and 201 respectively public class pathofsun static localtime localtime localtimenowstatic double dclat 3883static double dclong 7702static decimalformat df new decimalformat0public static void mainstring args int day dayofyear double equationoftime equationoftimeday double lstm localtimemeridian double lst localsolartimeequationoftime dclong lstm double declination declinationday double hourangle houranglelst double zenith zenithdclat declination hourangle double azimuth azimuthdclong declination zenith hourangle longitude of timezone meridianpublic static double localtimemeridian timezone gmt timezonegettimezonegmt timezone est timezonegettimezoneest int td gmtgetrawoffset estgetrawoffset double localstandardtimemeridian 15 td106060 convert td to hours systemoutprintlnlocal time meridian localstandardtimemeridian return localstandardtimemeridianget the number of days since jan 1public static int dayofyear calendar localcalendar calendargetinstancetimezonegetdefault int dayofyear localcalendargetcalendarday of year systemoutprintlnday dayofyear return dayofyearemperical equation to correct the eccentricity of earths orbit and axial tiltpublic static double equationoftime double day double d 36003650day 81 d mathtoradiansd double equationtime 987sin2d753cosd154sind systemoutprintlnequation of time equationtime return equationtimethe angle between the equator and a line drawn from the center of the sundegreespublic static double declinationint dayofyear double declination 235sinmathtoradians36003650dayofyear 81 systemoutprintlndeclination dfformatdeclination return declinationadd the number of minutes past midnight localtimepublic static double hourangledouble localsolartime double hourangle 15 localsolartime 13 systemoutprintlnhour angle dfformathourangle degrees return hourangleaccount for the variation within timezone increases accuracypublic static double localsolartimedouble equationoftime double longitude double lstm localsolartime 4min longitude localstandardtimemeridian equationoftime time correction is time variation within given time zone minutes longitude longitude60 convert degrees to arcminutes double localstandardtimemeridian lstm double timecorrection 4 longitude localstandardtimemeridian equationoftime systemoutprintlntime correction timecorrection in minutes localsolartime represents solar time where noon represents suns is highest position in sky and the hour angle is 0 hour angle is negative in morning and positive after solar noon double localsolartime localtimetosecondofday timecorrection60 seconds localsolartime localsolartime6060 convert from seconds to hours convert double to time hhmmss for console output int hours int mathfloorlocalsolartime int minutes int localsolartime hours 60 1 for the daylight savings time solartime new timehours1 minutes 0 systemoutprintlnlocal solar time solartime hours return localsolartimepublic static double azimuthdouble lat double declination double zenith double hourangle double azimuthdegree 0 double elevation 90 zenith elevation mathtoradianselevation zenith mathtoradianszenith lat mathtoradianslat declination mathtoradiansdeclination hourangle mathroundhourangle hourangle mathtoradianshourangle double azimuthradian sinhouranglecosdeclination coselevation double azimuthradian sindeclinationcoslat coshouranglecosdeclination sinlatcoselevation account for time quadrants calendar cal calendargetinstance int hour calgetcalendarhour of day ifhour 0 hour 6 azimuthdegree mathtodegreesacosazimuthradian else ifhour 6 hour 12 azimuthdegree mathtodegreesacosazimuthradian azimuthdegree 180 azimuthdegree else if hour 12 hour 18 azimuthdegree mathtodegreesacosazimuthradian azimuthdegree azimuthdegree 180 else if hour 18 hour 24 azimuthdegree mathtodegreesacosazimuthradian azimuthdegree 360 azimuthdegree systemoutprintlnazimuth dfformatazimuthdegree return azimuthdegreepublic static double zenithdouble lat double declination double hourangle lat mathtoradianslat declination mathtoradiansdeclination hourangle mathroundhourangle hourangle mathtoradianshourangle solar zenith angle double zenith mathtodegreesacossinlatsindeclination coslatcosdeclinationcoshourangle solar elevation angle double elevation mathtodegreesasinsinlatsindeclination coslatcosdeclinationcoshourangle systemoutprintlnelevation dfformatelevation systemoutprintlnzenith dfformatzenith return zenithjust to reiterate the day local time meridian are exactly correct and the equation of time and declination are accurate but not exact update outputupdateused the scatterchart to thisplay the suns elevationazimuth throughout day i am still having trouble figuring out the azimuth output it is correct for long time but then it will change from increasing and start to decrease 2700 i will be sure to update the code once i finally get the output right,['java'] +898597,not understanding c type mismatch const foo to foo const having this set of objects and statementsqsetfoo setiterator qsetinsertconst t value type of the function i want to callconst foo get const type of the function i use to get the argumentsetinsertget the line showing up as errori get the error no known conversion for argument 1 from const foo to foo const i guess i have trouble reading these types because i have no idea what i should do to make this workfrom what i have read the const keyword applies to the type to its left with the exception of a toplevel const which can be written to the left of the type it applies to my guess would be that i have to convert get to a reference but i am unsure how to do that,['c++'] +898620,splitview for ipad and menu drawer for iphone im developing one universal app for iphone and ipad bothfollowing is the requirement of app requirement 1there should be a menu master on the left and detail on the right2for iphone menu or masterviewcontroller should be on drawer or on slide out menu3for ipad menu should be on rootviewcontroller of splitviewi have already tried i tried to implement it using spiltviewcontroller for ipad it is working fine masterviewcontroller is coming on left of the screen and detailviewcontroller is on right side of the screen but for iphone it is simply working as uinavigationcontroller masterviewcontroller controller as rootviewcontroller of uinavigationcontrollerwhat approach should i use to implement it,"['ios', 'iphone']" +898646,what is element in csproj file i have just opened my existing application in vs 2015 rc and after some automatic upgradations check it added the following lines in the csproj file of the projectmvcprojectupgradecheckedtruemvcprojectupgradecheckedfileupgradeflagsfileupgradeflagsupgradebackuplocationupgradebackuplocationoldtoolsversion40oldtoolsversioni was wondering what does these line do can i check them in safely to the source control assuming that anyone else opening the solution can open it in some previous versions of visual studio i was unable to find anything on msdn for this tagupdatei just opened the solution after csproj modifications in visual studio 2013 and it opened without any issue so this seems to be just a flag but nonetheless can anybody share some definition for this,['.net'] +898760,react native v xamarin forms choosing cross platform app environment i have been looking at xamarin forms for building a cross platform app we would like a framework which targets ios android and windows phone it seems like a nice product but the license cost may cause us a problem with our business model and also licensing for windows phone development is uncleari have come across another framework called react native which claims to be able to build cross platform apps i wondered if anyone could give me an idea of its strengths and weaknesses in particular relative to xamarin forms if possible one thing is that it uses javascript which may not scale well either in terms of code maintenance or execution performance but i would be grateful for input from anyone who has looked closer at react and has formed some objective opinions about its usefulnessthanks,"['android', 'ios']" +898773,recover file in android studio i create a project in android studio version 12 and after working on that project for a few weeks my pc suddenly shut down android studio was open at that timeafter starting the pc again i found that one of my file was completely erasedhere is the snapshot of the workspace as you can see nothing is left on that fileis there any way to recover that file i am using ubuntu 1404thanks in advance,"['java', 'android']" +898873,how to use the request route parameter in laravel 5 form request i am new to laravel 5 and i am trying to use the new form request to validate all forms in my applicationnow i am stuck at a point where i need to delete a resource and i created a deleteresourcerequest for just to use the authorize methodthe problem is that i need to find what id is being requested in the route parameter but i cannot see how to get that in to the authorize methodi can use the id in the controller method like sopublic function destroyid deletepivotrequest request resourcefindorfailidbut how to get this to work in the authorize method of the form request,['php'] +898932,best way to update data with a recyclerview adapter when i have to use a classic adapter with a listview i update my data in the listview like thismyadapterswaparraydatapublic swaparraylistdata data clear addalldata notifydatasetchangedi would like to know what is the best practice for a recyclerview because in a recyclerview adapter you cannot do a clear and addall as in listviewso i tried just with a notifydatasetchanged but it did not work then i tried with a swapadapter on my viewlistdata data newdatamyrecycleradapter adapter new myrecycleradapterdata swapadapter on my recyclerview instead of a setadapter like with a classic listviewrecyclerviewlistswapadapteradapter falsebut with this last solution i still have to create a new instance of my adapter and i feel like it is not the best solution i should be able just to change my data without a new myrecycleradapter,['android'] +898940,android spinner reveal animation material design i just need something pretty simplecannot find any guideresource online that will help me to achieve the following behaviourso there are 3 thingsa ripple that appears to be bounded to the viewscale up animation of the popup cannot find a way to customize itthe text is carried over from the spinner field to the actual popupany help is appreciated editthe ripple is actually a straight forward thing that can be found in the docs the scale up animation of the popup dropdown is what interesting me the most if i only could get a reference to that popup i could animate it however i want ideas anybody,['android'] +898991,compilation error with ldjson script and razor views i m trying to add some schemaorg stuff to my site and the razor view engine is giving me troubles here is what i am trying to add to my main layout script typeapplicationldjson context type organization url logo scriptthe context is the issue here how do i get around this,['asp.net'] +898997,pythonic way to merge two overlapping lists preserving order alright so i have two lists as suchthey can and will have overlapping items for example 1 2 3 4 5 4 5 6 7there will not be additional items in the overlap for example this will not happen 1 2 3 4 5 35 4 5 6 7the lists are not necessarily ordered nor unique 9 1 1 8 7 8 6 7i want to merge the lists such that existing order is preserved and to merge at the last possible valid position and such that no data is lost additionally the first list might be huge my current working code is as suchmaster 1398345addition 34578def mergemaster addition and 1 while and lenmaster if mastern additionn return master additionn and 1 return master additionwhat i would like to know is is there a more efficient way of doing this it works but i am slightly leery of this because it can run into large runtimes in my application i am merging large lists of stringsedit i would expect the merge of 1398345 34578 to be 139834578 for clarity i have highlighted the overlapping portion9 1 1 8 7 8 6 7 should merge to 9 1 1 8 7 8 6 7,['python'] +899007,swagger w aspnet v5 azure api app i am attempting to set up a api app azure with swagger swashbuckle as demonstrated by scott hanselman at the build conference here i have installed using nuget the packages swaggerapi and swashbucklecore it has not added any controller or settings that i would expect in order to have a swagger page when i navigate to baseurlswagger i get a 404 error i would think that since it has a ui it would require a web app in addition to the api app but i have rewatched the demo and scott clearly says you can add swagger swashbuckle to any api app in a 2nd app though i would think there may be issues with api thiscovery has anyone set this up yet successfully,['asp.net'] +899052,can powermockito be used with android studio 12 i am using android studio 12 and the comandroidtoolsbuildgradle122 pluginattempt 1i include the following in my appbuildgradleandroidtestcompile comgoogledexmakerdexmakermockito12androidtestcompile orgpowermockpowermockmockitoreleasefull162but then the powermockito package in not available for importerror cannot find symbol powermockitomockstaticdatastorefactoryclass attempt 2i include the following in my appbuildgradleandroidtestcompile orgpowermockpowermockapimockito162 exclude module hamcrestcore exclude module objenesisandroidtestcompile orgpowermockpowermockmodulejunit4162 exclude module hamcrestcore exclude module objenesiswhich is a trialanderror offshoot of this qa here androidstudiogradle with powermockthis compiles but when run mockito gives a runtime errorjavalangverifyerror orgmockitocglibcorereflectutils at orgmockitocglibcorekeyfactorygeneratorgenerateclasskeyfactoryjava167 at orgmockitocglibcoredefaultgeneratorstrategygeneratedefaultgeneratorstrategyjava25 at orgmockitocglibcoreabstractclassgeneratorcreateabstractclassgeneratorjava217 at orgmockitocglibcorekeyfactorygeneratorcreatekeyfactoryjava145 at orgmockitocglibcorekeyfactorycreatekeyfactoryjava117 at orgmockitocglibcorekeyfactorycreatekeyfactoryjava109 at orgmockitocglibcorekeyfactorycreatekeyfactoryjava105 at orgmockitocglibproxyenhancerclinitenhancerjava70 at orgpowermockapimockitorepackagedclassimposterizercreateproxyclassclassimposterizerjava95 at orgpowermockapimockitorepackagedclassimposterizerimposteriseclassimposterizerjava57 at orgpowermockapimockitorepackagedclassimposterizerimposteriseclassimposterizerjava49 at orgpowermockapimockitorepackagedcglibmockmakercreatemockcglibmockmakerjava24 at orgpowermockapimockitointernalmockmakerpowermockmakercreatemockpowermockmakerjava45 at orgmockitointernalutilmockutilcreatemockmockutiljava33 at orgmockitointernalmockitocoremockmockitocorejava59 at orgmockitomockitomockmockitojava1285 at orgmockitomockitomockmockitojava1163 at commdsolnagaformpushertestsetupformpushertestjava40 at androidtestandroidtestrunnerruntestandroidtestrunnerjava191 at androidtestandroidtestrunnerruntestandroidtestrunnerjava176 at androidtestinstrumentationtestrunneronstartinstrumentationtestrunnerjava554 at androidappinstrumentationinstrumentationthreadruninstrumentationjava1701is anyone using powermock successfully with android studio 12 please share your buildgradle thanks,['android'] +899072,are all c fixedpoint operations deterministic i am writing a small rts engine in c and want to use lockstep synchronisationas floating point determinism is something i cannot even hope to achieve i have to use fixed point mathhow deterministically over different compilers and cpus are typical operations on unsigned ints definedi am especially interested in division as that would incur rounding,['c++'] +899080,php fails loading xcacheso after recompile i recompiled php 5439 on my raspbian to include support for pthreadseverything works nice even the pthreads but every time i run a php script from commandline and i guess it is the same if apache uses php it says it is failing loading xcachesofailed loading usrlibphp520100525lfsxcacheso usrlibphp520100525lfsxcacheso undefined symbol compiler globalsi recompiled php using this information although php is running fine i would like to know what this message means and i would like to solve it if possible,['php'] +899215,how polymer hero transition works first off i am having a tough time understanding the fundamentals of the herotransition within polymer i am attempting to build a hero transition card like the one in the example provided by them which can be found herebelow i have built the mini card and i am just trying to understand the transition and how the larger card works with the smaller one my specific question is how does the transition bind to each element do i need to complete the css for both before i can begin playing with the coreanimatedpages does having an embedded template matter any guidance would be extremely helpful script srccomponentswebcomponentsjswebcomponentsjsscriptlink relimport hrefcomponentscoreanimatedpagescoreanimatedpageshtmllink relimport hrefcomponentscoreanimatedpagestransitionsherotransitionhtmllink relimport hrefcomponentspaperbuttonpaperbuttonhtmllink relimport hrefcomponentscoreimagecoreimagehtmllink relimport hrefcomponentspapershadowpapershadowhtmlpolymerelement namechipcard template style page2 width 100 height 100 paper shadow position relative thisplay inlineblock fontfamilyroboto sansserif fontsize 12px color white chip body height 400px width 300px backgroundcolor aqua color black chip top backgroundcolor deeppink backgroundimage url backgroundsize cover backgroundposition center center width 100 position relative chip bottom backgroundcolor fbfbfb width 100 height 20 position relative fontsize 12em wordwrap breakword text paddingleft 5 paddingright 25 overflow hidden coreimage thisplay block card container width 70 height 600px backgroundcolor aqua color black card right height 100 width 30 card left backgroundcolor darkblue height 100 width 70 card left top paddingright 20px paddingtop 20px backgroundcolor skyblue circle width 30px height 30px borderradius 50 backgroundcolor red header text card content width100 backgroundcolor lightcoral style coreanimatedpages transitionsherotransition selectedpage section papershadow z1 idpaper shadow onmouseoverraise onmouseoutlower animatedtrue herop ontaptransition div idchip body heroidchip body vertical layout center justified div idchip top flex div idcoreimage content selectcoreimagecontent div div div idchip bottom vertical layout startjustified div idtext content selectchip bottomcontent div div div papershadow section section idpage2 div idcard container heroidchip body ontaptransition herodiv section coreanimatedpages template script polymerchipcard page 0 raise function thispaper shadowsetz2 lower function thispaper shadowsetz1 transition functione if thispage 0 thispaper shadow ecurrenttarget thispage 1 else thispage 0 scriptpolymerelement,"['html', 'css']" +899251,is armadillo solve thread safe in my code i have loop in which i construct and over determined linear system and try to solve itpragma omp parallel forfor int i 0 i n01 i for int j 0 j n11 j for int k 0 k n21 k armamat amax points 2 armamat ymax points 1 initialize a and y armavec solution solveay sometimes quite randomly the program hangs or the results in the solution vector are nan and if i put do thisarmavec solutionpragma omp critical solution solveweightsaweightsythen these problem do not seem to happen anymorewhen it hangs it does so because some threads are waiting at the openmp barrierthread 2 thread 0x7fe4325a5700 lwp 398390 0x07fe44d3c2084 in gomp team barrier wait end from usrlib64gcc492lib64gccx86 64redhatlinuxgnu492libgompso11 0x07fe44d3bf8c2 in gomp thread start at libgompteamc1182 0x03f64607851 in start thread from lib64libpthreadso03 0x03f642e890d in clone from lib64libcso6and the other threads are stuck inside armadillo thread 1 thread 0x7fe44afe2e60 lwp 3980 0x03ee541f748 in dscal from usrlib64libblasso31 0x07fe44c0d36 in dlarfp from usrlib64atlasliblapackso32 0x07fe44c058736 in dgelq2 from usrlib64atlasliblapackso33 0x07fe44c058ad9 in dgelqf from usrlib64atlasliblapackso34 0x07fe44c059a32 in dgels from usrlib64atlasliblapackso35 0x07fe44f09fb3d in bool armaauxlibsolve uddouble armagluearmamatdouble armamatdouble armaglue times armamatdouble armamatdouble armabasedouble armagluearmamatdouble armamatdouble armaglue times const at usrincludearmadillo bitslapack wrapperhpp6776 0x07fe44f0a0f87 in armacoldoublecolarmagluearmagluearmamatdouble armamatdouble armaglue times armagluearmamatdouble armamatdouble armaglue times armaglue solve armabasedouble armagluearmagluearmamatdouble armamatdouble armaglue times armagluearmamatdouble armamatdouble armaglue times armaglue solve const at usrincludearmadillo bitsglue solve meathpp39as you can see from the stacktrace my version of armadillo uses atlas and according to this documentation atlas seems to be thread safe update 9112015i finally got some time to run more tests based on the suggestions of vladimir fwhen i compile armadillo with atlass blas i am still able to reproduce then hangs and the nans when it hangs the only thing that changes in the stacktrace is the call to blas0 0x03fa8054718 in atl dscal xp1yp0axbxplt from usrlib64atlaslibatlasso31 0x03fb05e76 in dlarfp from usrlib64atlasliblapackso32 0x03fb0576a61 in dgeqr2 from usrlib64atlasliblapackso33 0x03fb0576e06 in dgeqrf from usrlib64atlasliblapackso34 0x03fb056d7d1 in dgels from usrlib64atlasliblapackso35 0x07ff8f3de4c34 in void armalapackgelsdoublechar int int int double int double int double int int at usrincludearmadillo bitslapack wrapperhpp6776 0x07ff8f3de1787 in bool armaauxlibsolve oddouble armagluearmamatdouble armamatdouble armaglue times armamatdouble armamatdouble armabasedouble armagluearmamatdouble armamatdouble armaglue times const at usrincludearmadillo bitsauxlib meathpp3434compiling without atlas only with netlib blas and lapack i was able to reproduce the nans but not the hangsin both cases surrounding solve with pragma omp critical i have no problems at all,['c++'] +899254,angularjs orderby does not work when orderbyproperty is edited i have a list of objects in my scope and want to iterate over them show some of their properties in orderedbysomeproperty way and change themngrepeat is used to thisplay textboxes binded to each object of my list and orderby filter which takes position as a parameter is appliedonce again position is also editablenow we change position of certain object onceangular reorders the list as expected and then change twice angular does not reorder the listcould anyone explain how it is possible to fix this reorderonlyonce situation and what are the reasons for such a behaviourhere is fiddle jsfiddlehtmldiv ngcontrollermyctrl plist of activitiesp div ngrepeatactivity in modelactivities orderby position textarea typetext ngmodelactivityname textarea activityname input typetext ngmodelactivityposition divdivjsvar myapp angularmodulemyappfunction myctrlscope scopemodel activities name activity 1 position 1 name activity 2 position 2 name activity 3 position 3 name activity 4 position 4 name activity 5 position 5,['javascript'] +899309,stdstringstream and the str method i noticed something when trying to use the stringstream object here is a useless example to explain thisstringstream ss ss my string cout str endl is not equivalent tocout stringstream my stringstr endl this leads to a compilation error complaining that aclass stdbasic ostreama has no member named astrai cannot easily explain this this is not critical for my application but i am pretty sure this is hiding a c trick interesting to be understoodnote i am using gcc with c14,['c++'] +899361,internet explorer 10 and 11 remove placeholder text when the input is focused when using internet explorer 10 and 11 input placeholder text is removed if the input is focused using the autofocus attribute for exampleinput typetextbox value placeholderexample text autofocusdemo how can i ensure the placeholder text is not removedref,"['javascript', 'html']" +899384,android place picker closes immediately after launch i am developing an android application as part of a project and am using google places api to thisplay places of interest based on location i am using the placepicker inentbuilder to accomplish thishowever when the app is run the place picker launches and then closes immediately about 12 seconds i have already implemented the below suggestions that i got from other answersi have generated the public api key for android applications and am including this in the metadata tag in the app manifest i have enabled the google places api for android api on the developers consolei have included the latest play services version in dependencies in buildgradlei have included my code and the logcat below do let me know if i need to include anything elsemanifestxmlxml version10 encodingutf8manifest xmlnsandroidpackagecomsampathprojectproject v2 usespermission androidnameandroidpermissioninternet usespermission androidnameandroidpermissionaccess fine location application androidallowbackuptrue androidiconmipmapic launcher androidlabelstringapp name androidthemestyleapptheme activity androidnamemainactivity androidlabelstringapp name intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity metadata androidnamecomgoogleandroidgmsversion androidvalueintegergoogle play services version metadata androidnamecomgoogleandroidgeoapi key androidvaluestringgoogle api key metadata androidnamecomgoogleandroidmapsv2api key androidvaluestringgoogle api key activity androidnameloginactivity androidlabelstringtitle activity login activity activity androidnameplacessample androidlabelstringtitle activity places sample metadata androidnamecomgoogleandroidgeoapi key androidvaluestringgoogle api key activityapplicationmanifestbuildgradle app module this is the only moduleapply plugin comandroidapplicationandroid compilesdkversion 22 buildtoolsversion 2201 defaultconfig applicationid comsampathprojectproject v2 minsdkversion 16 targetsdkversion 21 versioncode 1 versionname 10 buildtypes release minifyenabled false proguardfiles getdefaultproguardfileproguardandroidtxt proguardrulespro dependencies compile filetreeinclude jar dir libs compile comandroidsupportappcompatv72211 compile comandroidsupportappcompatv72211 compile comandroidsupportcardviewv72211 compile comandroidsupportrecyclerviewv72211 compile comgoogleandroidgmsplayservices730placessample activity that is using google places apipackage comsampathprojectproject v2import androidcontentcontextimport androidcontentintentimport androidosbundleimport androidsupportv7appappcompatactivityimport androidviewmenuimport androidviewmenuitemimport androidviewviewimport androidwidgettextviewimport androidwidgettoastimport comgoogleandroidgmscommongoogleplayservicesnotavailableexceptionimport comgoogleandroidgmscommongoogleplayservicesrepairableexceptionimport comgoogleandroidgmslocationplacesplaceimport comgoogleandroidgmslocationplacesuiplacepickerpublic class placessample extends appcompatactivity textview getlocation int place picker request 1 override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity places sample getlocation textviewfindviewbyidridgetloctv getlocationsetclickabletrue getlocationsetonclicklistenernew viewonclicklistener override public void onclickview v placepickerintentbuilder builder new placepickerintentbuilder intent intent try intent builderbuildgetapplicationcontext startactivityforresultintent place picker request systemoutprintlnstart activity for result catch googleplayservicesrepairableexception e eprintstacktrace catch googleplayservicesnotavailableexception e eprintstacktrace override public boolean oncreateoptionsmenumenu menu getmenuinflaterinflatermenumenu places sample menu return true override public boolean onoptionsitemselectedmenuitem item handle action bar item clicks here the action bar will automatically handle clicks on the homeup button so long as you specify a parent activity in androidmanifestxml int id itemgetitemid noinspection simplifiableifstatement if id ridaction settings return true return superonoptionsitemselecteditem protected void onactivityresultint requestcode int resultcode intent data systemoutprintlnonactivityresult if requestcode place picker request if resultcode result ok place place placepickergetplacedata this string toastmsg stringformatplace s placegetname toastmaketextthis toastmsg toastlength longshow logcat0505 233830593 2140821408comsampathprojectproject v2 itimelinei1 timeline activity idle id androidosbinderproxy17e945c6 time6287729430505 233830598 2140821408comsampathprojectproject v2 itimelinei1 timeline activity idle id androidosbinderproxy17e945c6 time6287729480505 233831517 2140821408comsampathprojectproject v2 itimelinei1 timeline activity launch request idcomsampathprojectproject v2 time6287738670505 233831527 2140821408comsampathprojectproject v2 wresourcetypei1 for resource 0x01030224 entry index548 is beyond type entrycount90505 233831527 2140821408comsampathprojectproject v2 wresourcetypei1 for resource 0x01030224 entry index548 is beyond type entrycount90505 233831636 2140821408comsampathprojectproject v2 itimelinei1 timeline activity idle id androidosbinderproxy2daadb0a time6287739860505 233833869 2140821408comsampathprojectproject v2 isystemouti1 start activity for result0505 233834227 2140821408comsampathprojectproject v2 isystemouti1 onactivityresult0505 233834235 2140821408comsampathprojectproject v2 itimelinei1 timeline activity idle id androidosbinderproxy2daadb0a time628776586,['android'] +899394,how to store indices in a list i want to find certain segments of a string and store them however i will need to store a large number of these strings and i was thinking that it might be more elegant to store them as indices of the master string rather than as a list of strings i am having trouble retrieving the indices for use for exampleindex1 03 48 invalid syntaxindex2 0356s abcdefghijklmnprintsindex20 typeerror string indices must be integersam i thinking about this the wrong way,['python'] +899488,how do i view the explain plan in oracle sql developer i have few sql queries which has very low query running performance and i want to check the query execution plan for this query i am trying to execute the below query but its not showing any query execution plan its only thisplay message plan for succeeded i dont know is there any settings that we have to do in oracle sql developer to vies explain plan for query explain plan for select sop option id fromsimsim join p type pt on ptkeysimp type key join p config pc on pcidptproduct config idjoin p option po on pooption keypcdefault product options join s option so on soservice idsimassigned to service idjoin avv no an on simassigned anumber id anid where sostatus id in 2040 and soid to charsysdate numtodsinterval 1minute ymmddhh24miss0 and soid to charsysdate numtodsinterval 1 hour ymmddhh24miss0and not existsselect id from temp bpl t where tid soid,['sql'] +899520,ios how to publish action on custom object graph api facebook i need to publish actioni got success in publishing liking the link from graph apieg abc likes wabccomnow i am stuck at liking custom object eg abc likes toy1and also to get total number of likesthis is sample code which is not working nsdictionary properties ogtype toy ogtitle toy1 ogdescription this is a sample course fbsdkshareopengraphobject object fbsdkshareopengraphobject objectwithpropertiesproperties fbsdkshareopengraphaction action fbsdkshareopengraphaction alloc init actionactiontype oglikes action setobjectobject forkeytoy fbsdkshareopengraphcontent content fbsdkshareopengraphcontent alloc init contentaction action contentpreviewpropertyname toy fbsdkshareapi shareapi fbsdkshareapi alloc init optionally set the delegate shareapidelegate self shareapisharecontent content shareapi shareedit my code is working by changingtoytoappnamespacetoyand action setobjectobject forkeytoy to action setobjectobject forkeyobjectnow i want to fetch total number of likes on this custom object,['ios'] +899614,why cannot i create an array of a type parameter in java well i have read a lot of answers to this question but i have a more specific one take the following snippet of code as an examplepublic class genericarraye e s new e5after type erasure it becomespublic class genericarray object s new object5this snippet of code seems to work well why does it cause a compiletime errorin addition i have known from other answers that the following codes work well for the same purposepublic class genericarraye e s enew object5i have read some comments saying that the piece of code above is unsafe but why is it unsafe could anyone provide me with a specific example where the above piece of code causes an errorin addition the following code is wrong as well but why it seems to work well after erasure toopublic class genericarraye e s new e,['java'] +899682,why is there a loop in getandset of atomicinteger and similar classes for what purpose a loop is used in this code public final int getandsetint newvalue for int current get if compareandsetcurrent newvalue return current,['java'] +899686,matrixanimationusingpath animate on surroundings outline of path i have a path data that i coppy it from syncfusion programi have a path with that data in my page and want to animate my object exact on path way in mid of path line but the problem is the object move on outline surroundings of path here is code canvas cliptoboundsfalse margin43558279445 width70 height70 path namepp datam29073618550c291124091148376114091796875e05 2915156173706050176620483398438 29190903106690532913208007813 29810998916626005332946734375 3031199884414670530315399169922 303919982910156114829635620117l305836410522461265130615234375 312817029953003812605285644531 3485699835419653616630583649 386119983196259114410037994385c386989989280701108670196533203 391539988517761104180335998535 397279987335205103390350341797 403039989471436102600383758545 408659987449646105700283050537 4110399866104131109901428266l4452392141724186847972869873 6268891760254186847972869873c634129981994629186847972869873 63980926514192727813720703 639809265141957599639893 6398092651420720739364624 6341299819946292130772390234 62688917602542130772390234l4367799854278562130772390234c431629986763213077239023442694998741149921004732131958424809985160828205357456207275l405379986763162248687744141 3604092933273458410243988037c3594399881362924648200654983523539299884438514695599317550663474592468357469559926986694l347298499155469559926986694c34074998859084694799327850343352799880504614645900726318363349987411499458100252151489l285969982147217971076965332 1977987792969385482323169708c1961199855804391362158469856 1906969482423952048461437 1844591455078394962055683136 178359985351563394622065722942 173289985656738390092194601893 1722692828369384062369465828l13657903869631726883824463 1077193591309233446655273438c1059755859423801651954650910094931335452409364414215099587934387207240936441421509l131099700927734240936441421509c0587997436523438240936441421509 0235056610107422 0227826805114746 02205770108398 0587997436523438214717178344727 131099700927734214717178344727l8757942016602214717178344727 1307499885908123859767913818c133196948242118689918518066 138698931884811572050354 144389176025411649771816 1500599861145021172957275391 154579982757568121669826507568 1519981384277127309665679932l188509979248047322744116783142 2783199882507320952301025390625c2799137401580810391693115234375284917645454407017166137695312529073618550z stretchuniform fillwhite width70 height70 strokethickness0 rectangle fillf4600 rendertransformorigin0505 width4 height4 canvastop4 rectanglerendertransform transformgroup matrixtransform xnamett matrixtransformmatrix matrix matrixtransformmatrix matrixtransform transformgroup rectanglerendertransform rectangletriggers eventtrigger routedeventframeworkelementloaded beginstoryboard storyboard matrixanimationusingpath duration0010 storyboardtargetnamett storyboardtargetpropertymatrix autoreversetrue doesrotatewithtangenttrue matrixanimationusingpathpathgeometry pathgeometry figuresm29073618550c291124091148376114091796875e05 2915156173706050176620483398438 29190903106690532913208007813 29810998916626005332946734375 3031199884414670530315399169922 303919982910156114829635620117l305836410522461265130615234375 312817029953003812605285644531 3485699835419653616630583649 386119983196259114410037994385c386989989280701108670196533203 391539988517761104180335998535 397279987335205103390350341797 403039989471436102600383758545 408659987449646105700283050537 4110399866104131109901428266l4452392141724186847972869873 6268891760254186847972869873c634129981994629186847972869873 63980926514192727813720703 639809265141957599639893 6398092651420720739364624 6341299819946292130772390234 62688917602542130772390234l4367799854278562130772390234c431629986763213077239023442694998741149921004732131958424809985160828205357456207275l405379986763162248687744141 3604092933273458410243988037c3594399881362924648200654983523539299884438514695599317550663474592468357469559926986694l347298499155469559926986694c34074998859084694799327850343352799880504614645900726318363349987411499458100252151489l285969982147217971076965332 1977987792969385482323169708c1961199855804391362158469856 1906969482423952048461437 1844591455078394962055683136 178359985351563394622065722942 173289985656738390092194601893 1722692828369384062369465828l13657903869631726883824463 1077193591309233446655273438c1059755859423801651954650910094931335452409364414215099587934387207240936441421509l131099700927734240936441421509c0587997436523438240936441421509 0235056610107422 0227826805114746 02205770108398 0587997436523438214717178344727 131099700927734214717178344727l8757942016602214717178344727 1307499885908123859767913818c133196948242118689918518066 138698931884811572050354 144389176025411649771816 1500599861145021172957275391 154579982757568121669826507568 1519981384277127309665679932l188509979248047322744116783142 2783199882507320952301025390625c2799137401580810391693115234375284917645454407017166137695312529073618550z pathgeometry matrixanimationusingpathpathgeometry matrixanimationusingpath storyboard beginstoryboard eventtrigger rectangletriggers rectangle canvasedit 1 my animation go wrong way i want my rectangle move exact inside and in middle of path line see code in your pc you will see the problem my question is how fix that problem edit 2 i change the animation with doubleanimationusingpath same resultedit 3,['c#'] +899690,changing numbers from standard form without clicking every cell excel i have imported a csv file from mysql documenting part numbers and descriptions some of these part numbers have values like 1234567890987654321 which is then shortened by excel to 123e18 problem is i cannot query a part with this formatted data now i cannot feasibly go through every cell as there are just over 280 of them i have converted the row to text however this does not change the data in the cell the closest thing i have to a solution is deleting the cells and then undoing which gets the number in a textual format but then gives me a number in text field error also some parts have part numbers like 12e345 which is then changed to 120 you get the picturevery annoyingi would like a batch process to change all the values to text format thanks in advance,['mysql'] +899724,proguard removing annotations in android application i have included a project using gradle in my appcompile group orgbytedeco name javacv version 011which builds fine but whenever i run the app with proguard enabled it apparently removes the platform annotation from the jars that get included theni tried using the following based on keepattributes annotationkeep orgbytedecojavacppannotation interface i also tried the following based on keep interface but that does not work either what else can i try to prevent proguard from removed these annotations i was thinking about using injars or libraryjars but i believe gradle handles that for youthe solutionso the solution is as followsi have included the following in my proguard rules javacvkeep orgbytedecojavacppannotation interface keep orgbytedecojavacppannotationplatform public class keepclasseswithmembernames class orgbytedeco fieldskeepclasseswithmembernames class orgbytedeco methodskeepattributes enclosingmethodkeep interface orgbytedecojavacppannotationjavaxinjectkeepattributes annotation exceptions signature deprecated sourcefile sourcedir linenumbertable localvariabletable localvariabletypetable synthetic enclosingmethod runtimevisibleannotations runtimeinvisibleannotations runtimevisibleparameterannotations runtimeinvisibleparameterannotations annotationdefault innerclasseskeep class orgbytedecojavacpp dontwarn javaawtdontwarn orgbytedecojavacvdontwarn orgbytedecojavacpp end javacvand the following lines in my gradle these are the most recent versions at date 752015 ddmmycompile group orgbytedeco name javacv version 011compile group orgbytedecojavacpresets name opencv version 2411011 classifier androidarmcompile group orgbytedecojavacpresets name opencv version 2411011 classifier androidx86compile group orgbytedecojavacpresets name ffmpeg version 261011 classifier androidarmcompile group orgbytedecojavacpresets name ffmpeg version 261011 classifier androidx86i am quite sure that some proguard rules are a bit overkill but i have not yet tested which are redundant you may want to figure this out yourself if you run into this issue,"['java', 'android']" +899746,do java atomics only require atomicity with respect to the vm i was looking at the java source code for the atomicinteger class found here to see which atomic primitives are required to implement a jvm i noticed they use the undocumented unsafe api to implement their atomic integer operations and that the only two primitives they use seem to be the compare and swap and compare and set operations and the unsafe class implements these instructions as native methods which leads me to believe they are using the native instructions which perform these primitive operations in the general case however not every processorthough most modern ones do has an instruction set which supports these primitives natively now even without native processor support those primitives could be implemented by the vm in a way that guarantees atomicity with other vm threads but not necessarily with other native threads so does java require these primitives on the native architecture to have a valid jvm and thus all jvm implementations would support atomicity with native threads or is the atomicity in java only guaranteed between java threads,['java'] +899832,how to compare two strings when both can be null i am aware that it is better to call the equals method over using the operator see this question i want two strings to compare as equal if they are both null or if they represent the same string unfortunately the equals method will throw an npe if the strings are null my code is currentlyboolean equalsstring s1 string s2 if s1 null s2 null return true if s1 null s2 null return false return s1equalss2this is inelegant what is the correct way to perform this test,['java'] +899837,performing raw sql queries in yii2 i have written the below queries as i migrate my php website to the yii2 framework i want to add them to my controller so as to thisplay the top 10 bets won i have tried going through many yii2 database classes but i cannot get it to workmy tables areusersid user name user status other columnsbetsid user id date time other columns balance returnthe queries i want to get in yii2 arequery all dbhquery select sumbetsbalance return as total win betsuser id usersuser name usersuser status from bets inner join users on betsuser id usersid where usersuser status verified and betsdate time start date group by betsuser id order by total win descthe variable start date is a period of 6 months which i calculate according to time also please note that balance return is every win a user got so its sum determines the rankingthe second query isqwi dbhquery select sumbetsbalance return as total win betsuser id usersuser name usersuser status from bets inner join users on betsuser id usersid where usersuser status verified and betsdate time start date group by betsuser id order by total win desc limit 010,"['php', 'mysql']" +899916,android bug in slide activity transition so in trying to use the slide activity transition but with a different gravity the app crashes on using gravitystart using thisgetwindowsetexittransitionnew slidegravitystartand i get this errorillegalargumentexception invalid slide directionbut yet if you look in the source code that specific constructor above calls setslideedge in which case that method goes through a switch statement to set the gravity you specified earlier switch slideedge case gravityleft mslidecalculator scalculateleft break case gravitytop mslidecalculator scalculatetop break case gravityright mslidecalculator scalculateright break case gravitybottom mslidecalculator scalculatebottom break case gravitystart mslidecalculator scalculatestart break case gravityend mslidecalculator scalculateend break default throw new illegalargumentexceptioninvalid slide direction gravityleft works just fine but because i want rtl support it only makes sense to instead use gravitystart i am confused as to why the default case is executed in this switch statement and the only explanation for it is it is a bug i would report it to google but they do not have public ways of reporting api bugs like this and in this case the bug is not exactly obvious to fix so psa to anyone that wants to use the slide animation with a gravity of start,['android'] +899935,best way of implementing a scrolling navigation drawer i have been adding a navigation drawer to one of my apps and i started to wonder whether or not it would be better to switch from using a listview to multiple textviews for the navigation drawer list items looking at the google design guidelines on navigation drawer content specifically the section on scrolling i noticed that it may look nicer with multiple textviewsat the moment i am using a listview and imageview in my navigation drawer it looks a little like this however when i scroll in my navigation drawer i do this by turning my device landscape as there are not enough items in my list yet only the listview scrolls and the imageview stays as it is i want it to be able to scoll more like this where the imageview is also scrolled with the listviewadditionally i found that my listview in my navigation drawer does not have the ripple effects as shown in this image although other listviews in my other activitys and fragments dowhat are the issues i am facing and how could i go about resolving theseupdatein googles io app 2014 there seems to be a linearlayout at the bottom of the navigation drawer layout which i think is responsible for the list of items shown could someone explain how this would work,['android'] +900170,padding does not work on some devices i had a strange problems during the set padding to edittext xml looks like thisedittext androidlayout width270dp androidlayout height55dp androidems10 androidididetemail androidtextstylebold androidlayout gravitycenter vertical androidtextcolorf androidhintor use your email androidinputtypetextemailaddress androidlayout alignleftidtextview6 androidlayout alignstartidtextview6 androidtextcolorhintf androidbackgrounddrawableline white androidpaddingleft165dp androidlayout margintop10dp androidpaddingright2dp here is the screenshot from samsung note 2 android 501 and lg g3 android 442as you can see androidpaddingleft does not work for lgwhat could be the reasonthanksupdlayout bounds lg,['android'] +900180,facebook logout is not working in new sdk v410 in ios friends i want to integrate facebook in my app so that i am download new facebook sdk v410 for facebook login button use the class of fbsdkloginbutton as below code in swiftif fbsdkaccesstokencurrentaccesstoken nil user is already logged in do work such as go to next view controller or show logout button let loginview fbsdkloginbutton fbsdkloginbutton selfviewaddsubviewloginview loginviewcenter selfviewcenter loginviewreadpermissions public profile email user friends loginviewdelegate self selfreturnuserdataelse let loginview fbsdkloginbutton fbsdkloginbutton selfloginbuttondidlogoutloginview selfviewaddsubviewloginview loginviewcenter selfviewcenter loginviewreadpermissions public profile email user friends loginviewdelegate self as above code there is thisplay log in with facebook button after successfully login thare is thisplay logout button when i click on logout button then its delegate is called delegate class fbsdkloginbuttondelegatedelegate method of logout func loginbuttondidlogoutloginbutton fbsdkloginbutton printlnuser logged out fbsdkaccesstokensetcurrentaccesstokennil fbsdkprofilesetcurrentprofilenil let manager fbsdkloginmanager managerlogoutin delegate i am clear token and also called function of logout inside class of fbsdkloginmanager but each time get authorized screen of usernot get login screen so that another user cannot login with facebook each time i have to clear browser historywithout clear browser history there is not thisplay login page so that another user cannot loginqusetion facebook bug each time thisplay screen after logout,['ios'] +900192,how do i restrict access to my rest api to only authorized clients questioni am designed rest api that is going to be used for ios and android apps and possibly web and other mobile clients in the futurehow do i restrict my entire api to only the clients apps that i want to have access i want to prevent 3rd parties from accessing my api to register users or even login without going through an authorized application mobile or web clientcurrent ideasi could give each client that i want to have authorization a secret key but how do i prevent this key from being extracted from my applications source code especially easy if my app was a web app also if the key needs to be changed in the future due to a compromise this would be difficult as all my clients would need to be updated and old clients would fail to function there has to be a better solutioni am using jwt for user authentication but i fail to see how i can apply this to my problem i really like how jwt are easily implemented so it would be great if i could apply a jwt implementation to solve this problem,"['android', 'ios']" +900294,how to use code from one class in another java i am making a tank game and to avoid redundancy i am making classes to extendmy menupanel looks like this atmi have only written the code that matters for the questionknop dutch for buttonpublic class menupanel extends jpanel implements actionlistener private jbutton playknop highscoreknop quitknop htpknop private imageicon play hs quit htp private tanks mainvenster public menupaneltanks mainvenster thismainvenster mainvenster thissetlayoutnull int x 95 int width 200 int height 50 play new imageiconplaypanelclassgetresourcebuttonsplaypng playknop new jbuttonplay playknopsetboundsx y width height playknopaddactionlistenerthis hs new imageiconplaypanelclassgetresourcebuttonshspng highscoreknop new jbuttonhs highscoreknopsetboundsx 460 width height highscoreknopaddactionlistenerthis htp new imageiconplaypanelclassgetresourcebuttonshtppng htpknop new jbuttonhtp htpknopsetboundsx 515 width height htpknopaddactionlistenerthis quit new imageiconplaypanelclassgetresourcebuttonsquitpng quitknop new jbuttonquit quitknopsetboundsx 570 width height quitknopaddactionlistenerthis thisaddplayknop thisaddquitknop thisaddhtpknop thisaddhighscoreknop validate because the code to make the buttons is exactly the same except for the backgroundpath and the ycoordinate i made a class buttonpackage menuimport javaawtimageimport javaawteventactionlistenerimport javaxswingimageiconimport javaxswingjbuttonpublic class button public jbutton button public imageicon buttonimage public int x 95 public int width 200 public int height 50 public string backgroundpath public int y public buttonstring backgroundpath int y thisbackgroundpath backgroundpath thisy y buttonimage new imageiconplaypanelclassgetresourcebackgroundpath button new jbutton buttonsetboundsx y width height buttonaddactionlistenerthis that way my menupanel could look like this package menu suppresswarningsserial public class menupanel extends jpanel implements actionlistener private button playknop highscoreknop quitknop htpknop private jtextfield naam private tanks mainvenster public menupaneltanks mainvenster thismainvenster mainvenster thissetlayoutnull playknop new buttonbuttonsplaypng 350 highscoreknop new buttonbuttonshspng 460 quitknop new buttonbuttonsquitpng 515 htpknop new buttonbuttonshtppng 570 thisaddplayknop thisaddquitknop thisaddhtpknop thisaddhighscoreknop validate i do not know why but when i do this the buttons would not appear although the code from the button class is correct bc when i use the code in the menupanel itself it worksi do not know how to fix this problem and i have multiple problems like this in my whole javaproject but if someone could explain me how to fix this i could get rid of all the redundancy in my projectthanks in advancelolathank you all so much a combination of your answers helped me to let the buttons appear but for some kind of reason the images do not load with them my code now looks likepublic class menupanel extends jpanel implements actionlistenerprivate button playknop highscoreknop quitknop htpknopprivate tanks mainvensterint x 95 width 200 height 50public menupaneltanks mainvenster thismainvenster mainvenster thissetlayoutnull playknop new buttonbuttonsplaypng 350 this highscoreknop new buttonbuttonshspng 460 this quitknop new buttonbuttonsquitpng 515 this htpknop new buttonbuttonshtppng 570 this thisaddplayknop thisaddquitknop thisaddhtpknop thisaddhighscoreknop validatepublic class button extends jbutton jbutton button imageicon buttonimage string backgroundpath int y public buttonstring backgroundpath int y menupanel menupanel super thisbackgroundpath backgroundpath thisy y buttonimage new imageiconplaypanelclassgetresourcebackgroundpath thissetboundsx y width height thisaddactionlistenermenupanel all the buttons do work,['java'] +900355,application loader warning resulting api analysis file is too large i am getting a strange error when i submit my application via application loader toolthe resulting api analysis file is too large we were unable to validate your api usage prior to delivery this is just an informational messagethe application gets submitted to itunes connect and i am able to test it via testflight what is the reason behind this error also is there a risk of my app getting rejected because of this copy of the error message is below,"['ios', 'iphone']" +900501,java systemgetenv environment names starting with i have noticed that the environment in java on windows as obtained by a systemgetenv call includes some variables that do not exist in the real environment these begin with and equalssign and include exitcode which maps to the exit code of the process that ran just before this java invokation and the default directories of various drive letters such as c d this seems to be the case with all of suns java versions running on all windows versions is this documented anywhere or is it purely for suns internal onlyeditheres a simple example application to show what i mean compile and run this on the command lineimport javautilmapclass showenv public static void mainstring args for mapentry v systemgetenventryset systemoutprintf23s 54sn vgetkey vgetvalue then compare the variables with the set command from cmdexe or with similar commandline program written in c youll find the variables beginning with do not exist in thoseexitcode 0 c ctempthese variables are obviously added during execution of the jvm,['java'] +900557,c deep lazy comparison with elegant syntax i have a c class for which i need to define a comparator that should consider the result of several potentially expensive methods i do not want to cache the result of these methods for all the objects in my set because the criteria with the highest priority are cheaper and i expect the very expensive ones at the bottom to trigger only in rare casesif i had a cmp function that returned respectively 1 0 or 1 when the first argument is lesser equal or greater to the second and with shortcut logical operators that preserve integers i could easily writeint compareconst class rhs const return cmpexpensive method a rhsexpensive method b cmpexpensive method b rhsexpensive method b unfortunately i need to work with the operator so it becomes ugly costly and errorpronebool operatorconst class rhs const return expensive method a rhsexpensive method a expensive method a rhsexpensive method a expensive method b rhsexpensive method b expensive method b rhsexpensive method b or alternatively less costly but still pretty uglybool operatorconst class rhs const auto al expensive method a ar rhsexpensive method a if al ar return al ar auto bl expensive method b br rhsexpensive method b if bl br return bl bri have read about stdtie at this other question but if i understand correctly the tie would evaluate all my methods before starting the comparaison and i want these arguments to be lazily evaluatedi thought about defining a preprocessor macro such as thisdefine cut compareab auto x a auto y b if x y return x y that i would use likebool operatorconst class rhs const cut compareexpensive method a rhsexpensive method a cut compareexpensive method b rhsexpensive method b hoping that the braces would enclose my x and y in a private scope but alas clang complains of multiple definitions of x and yis there a prettier way around this,['c++'] +900581,impersonation only works when a user is specificed i am having an issue accessing a webservice with impersonate without a specified userworks identity impersonatetrue usernamedomainusername passwordmypassword does not work identity impersonatetrue while debugging i used the code below to verifiy the correct domain and username were being used they aresystemsecurityprincipalwindowsidentitygetcurrentnamehere is more of my webconfigauthentication modewindows identity impersonatetrue authorization allow users deny usersauthorizationi am logging into the prompt image belowany ideas why it will only work when i specify a user in the webconfig i am logging in with the same domainusername and password that i put into the identity impersonatetrue usernamedomainusername passwordmypassword i have tried with multiple accounts and they all work when i put their credentials in the webconfig but none work with identity set asidentity impersonatetrue and logging ineditthe remote server returned an error 403 forbidden edit 2everything works fine while debugging and while hitting the service on the server that contains the iis it is hosted on i have tried with multiple accounts and they all work everything is on the same domain,['c#'] +900602,mvc mixed auth owin windows auth i need to have both windows authentication and owin forms authentication but i cannot get it to workprobably the best option is to have two sites that have different authentication methodsi found a project that does what i want mvc5mixedauth but it uses iisexpress and i cannot get it to work with local iisthe error that occurs is request filtering is configured on the web server to deny the request because the query string is too longif i remove all my configureauth method inside startupauthcs it does not throw the error but i cannot login because it is needed to do cookieauthenticationstartupauthcspublic void configureauthiappbuilder app appcreateperowincontextdbemployeeportalcreate appcreateperowincontextapplicationusermanagerapplicationusermanagercreate appcreateperowincontextapplicationsigninmanagerapplicationsigninmanagercreate appusecookieauthenticationnew cookieauthenticationoptions authenticationtype defaultauthenticationtypesapplicationcookie loginpath new pathstringaccountlogin provider new cookieauthenticationprovider onvalidateidentity securitystampvalidatoronvalidateidentityapplicationusermanager usermaster int validateinterval timespanfromminutes30 regenerateidentitycallback manager user usergenerateuseridentityasyncmanager getuseridcallback id int32parseidgetuserid appuseexternalsignincookiedefaultauthenticationtypesexternalcookie appusetwofactorsignincookiedefaultauthenticationtypestwofactorcookie timespanfromminutes5 appusetwofactorrememberbrowsercookiedefaultauthenticationtypestwofactorrememberbrowsercookieany ideaupdate 1the errorrequest filtering is configured on the web server to deny the request because the query string is too longappears because occurs a login loop when it tries to reach the login page,['c#'] +900640,uitableview powered by fetchedresultscontroller with uitableviewautomaticdimension cells move when table is reloaded current set uptableview with automatically calculated heightsselftableviewsectionheaderheight uitableviewautomaticdimensionselftableviewrowheight uitableviewautomaticdimensionselftableviewestimatedrowheight 1520selftableviewestimatedsectionheaderheight 500whenever the fetched results controller updates its data the tableview is reloaded voidcontrollerdidchangecontentnsfetchedresultscontroller controller selftableview reloaddata the cell is configured using a xib the first label is pinned to the top of the cell each following label is pinned to the top of the label above it and the label at the bottom is pinned to the bottom of the cellthe issueeach time i set a favourite property on an item in the table view the fetched results controller is fired to reload the table and the scroll position is changed it is this change in the scroll position that i am trying to fixadditional infoif i use fixed cell heights it resolves the issue but i require uitableviewautomaticdimension because the first label can wrap over two lines and the remaining labels may or may not be presentexamplenote as i select the fav button it sets the fav property in core data and reloads the table why is the table jumping around,"['ios', 'objective-c']" +900652,looking for idiomatic way to evaluate to false if argument is false in python 3 i have a chain of functions all defined elsewhere in the classfusrohdahinpwhere inp is either a dictionary or boolfalsethe desired result is that if inp or any of the functions evaluate to false false is returned by the function stacki attempted to use ternary operators but they do not evaluate correctlydef funcinp return intinpvalue 1 if inp else falsethrows a typeerror bool not subscriptable if i false because inpvalue is evaluated before the conditionali know i can do it explicitlydef funcinp if inp false return false else return inpvalue 1but there are a ton of functions and this will nearly quadruple the length of my code it is also rewriting the exact same lines of code again and again which suggests to me that it is the wrong way to do thingsi suspect that a decorator with arguments is the answer but the more i play around with it the less sure i am about thatdef validate inpinp def decoratorfunc def wrapperargs return funcinp if inp else false return wrapper return decoratorvalidate inpinpdef funcinp return intinpvalue 1unfortunately the decorator call throws a nameerror inp not defined but i am not sure if i am using the decorator incorrectly or the decorator is the wrong solutionlooking for comment criticism suggestion andor sanity checkif you found this trying to solve your own problemyou probably want to be using empty dictionaries instead of boolean false props to chepnerin my application using false was okay bur offered no advantages and caused some chunky blocks of codei have found everything is simpler using an empty dictionary instead i am wrapping the functions that use the dict with a decorator that catches the keyerror thrown by referencing dictvalue where dict is empty,['python'] +900684,lambda that does absolutely nothing i needed to have a lambda expression of the functional interface runnable that did nothing i used to have a methodprivate void donothing do nothingand then use thisdonothing but i have found an even shorter way to do this,['java'] +900705,how does strlist work why does strlist returns how we see list on the console how does strlist work any reference to the cpython code for strlist x abc def ghi strxabc def ghito get the original list back from the strlist i have to from ast import literal eval x abc def ghi strxabc def ghi liststrx a b c d e f g h i literal evalstrxabc def ghiwhy does not liststrlist turns the strlist back to the original listor i could use evalstrxabc def ghiis literal eval the same as eval is eval safe to usehow many times can i do the following does the code break if it keep on doing strliststrlist eg x abc listxa b c strlistxa b c liststrlistx a b c strliststrlistx a b c liststrliststrlistx a b c strliststrliststrlistx a b c liststrliststrliststrlistx a b c,['python'] +900714,check if ionic app is in dev serve modebrowser i use ionic serve to run my app on localhosthow can i know when i am in browser and not in androidi triednavigatorplatform macintelnavigatorplatforms undefinedionicplatformisbrowser falsenavigatoruseragent iphone i am in chrome device modethank you,['javascript'] +900776,must the c standard library support classes that are picky about who their friends are this question is easiest to illustrate with an example so here goesis code like the following guaranteed to be valid and compile run correctlynot all implementations actually compile it correctly but i am wondering if that is a buginclude algorithmclass picky friend picky stdcopypicky const picky picky const picky const picky picky operator picky const return this public picky int main picky const a picky b stdcopypicky const picky a a 1 b return 0,['c++'] +900790,dynamic database connection in sails js how i can set a database connection from a controller i need to specify in the controller the type of database user password port database name and set this in connectionsjs,['javascript'] +900859,configurable sensitive data masking via log4net i am looking at using log4net as my logging framework of choice for a new project starting shortly one issue that i have run into during prototyping that i cannot find a definitive answer for is how you can clean or mask message content in a configurable and tidy wayhypothetically let us say i want several cleaners to be put in action but i also want to follow the single responsibility principle some cleaner examplescardnumberpan cleaner password cleaner private data cleaneri know that you should never be logging this sort of information in plain text and the code executing the logs will never knowingly be doing this i want to have a last level of protection however in case data becomes malformed and sensitive data somehow slips into somewhere it should not logs being the worst case scenariooption 1i have found this stackoverflow article which details a possible solution however it involves the use of reflection this is not desirable for performance but it also seems hacky to manipulate internal storage mechanismseditinglog4netmessagesbeforetheyreachtheappendersoption 2the suggested answer on the same question suggests the use of a patternlayoutconverter this is fine for a single cleaner operation but you are unable to use multiple operations such as the belowpublic class cardnumbercleanerlayoutconverter patternlayoutconverter protected override void converttextwriter writer loggingevent loggingevent string message loggingeventrenderedmessage todo replace with real card number detection and masking writerwritemessagereplace9 layout typelog4netlayoutpatternlayout converter name valuecleanedmessage type valuelog4netprototypecardnumbercleanerlayoutconverter log4netprototype converter converter name valuecleanedmessage type valuelog4netprototypepasswordcleanerlayoutconverter log4netprototype converter conversionpattern valuecleanedmessage layoutin the case of a naming collision as demonstrated above the converter loaded last will be the one which is actioned using the above example this means that passwords will be cleaned but not card numbersoption 3a third option which i have tried is the use of chained forwarderappender instances but this quickly complicates the configuration and i wouldnt consider it an ideal solution because the loggingevent class has an immutable renderedmessage property we are unable to change it without creating a new instance of the loggingevent class and passing it through as demonstrated belowpublic class cardnumbercleanerforwarder forwardingappender protected override void appendloggingevent loggingevent todo replace this with real card number detection and masking string newmessage loggingeventrenderedmessagereplace9 what context data are we losing by doing this loggingeventdata eventdata new loggingeventdata domain loggingeventdomain identity loggingeventidentity level loggingeventlevel locationinfo loggingeventlocationinformation loggername loggingeventloggername exceptionstring loggingeventgetexceptionstring timestamp loggingeventtimestamp message newmessage properties loggingeventproperties threadname loggingeventthreadname username loggingeventusername baseappendnew loggingeventeventdata public class passwordcleanerforwarder forwardingappender protected override void appendloggingevent loggingevent todo replace this with real password detection and masking string newmessage loggingeventrenderedmessagereplace4 what context data are we losing by doing this loggingeventdata eventdata new loggingeventdata domain loggingeventdomain identity loggingeventidentity level loggingeventlevel locationinfo loggingeventlocationinformation loggername loggingeventloggername exceptionstring loggingeventgetexceptionstring timestamp loggingeventtimestamp message newmessage properties loggingeventproperties threadname loggingeventthreadname username loggingeventusername baseappendnew loggingeventeventdata matching configuration very hard to followlog4net appender namelocatedasyncforwardingappender typelog4netprototypelocatedasyncforwardingappender log4netprototype appenderref refcardnumbercleanerforwarder appender appender namecardnumbercleanerforwarder typelog4netprototypecardnumbercleanerforwarder log4netprototype appenderref refpasswordcleanerforwarder appender appender namepasswordcleanerforwarder typelog4netprototypepasswordcleanerforwarder log4netprototype appenderref reflogfileappender appender appender namelogfileappender typelog4netprototypelogfileappender log4netprototype layout typelog4netlayoutpatternlayout conversionpattern valuem layout appender root level valuedebug appenderref reflocatedasyncforwardingappender rootlog4netdoes anyone have another suggestion for how this could be implemented where theoretically and number of cleaners could be configured at the cost of performance,"['c#', '.net']" +900887,how to use appcompatpreferenceactivity i am trying to add toolbars to the appcompatpreferenceactivity but i do not know how to do socan you tell me how,['android'] +900943,duplicating parent child and grandchild records i have a parent table that represents a document ofsorts with each record in the table having n children records in a child table each child record can have n grandchild records these records are in a published state when the user wants to modify a published document we need to clone the parent and all of its children and grandchildrenthe table structure looks like thisparentcreate table qlquantlist quantlistid int identity 1 1 not null stateid int not null title varchar 500 not null constraint pk quantlist primary key clustered quantlistid asc constraint fk quantlist state foreign key stateid references qlstate stateidchildcreate table qlquantlistattribute quantlistattributeid int identity 1 1 quantlistid int not null narrative varchar 500 not null constraint pk quantlistattribute primary key quantlistattributeid constraint fk quantlistattribute quantlistid foreign key quantlistid references qlquantlistquantlistidgrandchildcreate table qlattributereference attributereferenceid int identity 1 1 quantlistattributeid int not null reference varchar 250 not null constraint pk quantlistreference primary key attributereferenceid constraint fk quantlistreference quantlistattribute foreign key quantlistattributeid references qlquantlistattributequantlistattributeidin my stored procedure i pass in the quantlistid i want to clone as quantlistid since the quantlistattribute table has a foreignkey i can easily clone that as well insert into qlquantlist stateid title select 1 title from qlquantlist where quantlistid quantlistidset clonedid scope identityinsert into qlquantlistattribute quantlistid narrative select clonedid narrative from qlquantlistattribute where quantlistid quantlistidthe trouble comes down to the attributereference if i cloned 30 quantlistattribute records how do i clone the records in the reference table and match them up with the new records i just inserted in to the quantlistattribute table insert into qlattributereference quantlistattributeid reference select quantlistattributeid reference from qlquantlistreference where i do not have a key to go off of for thisi thought i could do this with some temporary linking tables that holds the old attribute ids along with the new attribute ids i do not know how to go about inserting the old attribute ids in to a temp table along with their new ones inserting the existing attributes by quantlistid is easy enough but i cannot figure out how to make sure i link the correct new and old ids together in some way so that the attributereference table can be cloned right if i could get the quantlistattribute new and old ids linked i could join on that temp table and figure out how to restore the relationship of the newly cloned references to the newly cloned attributesany help on this would be awesome i have spent the last day and a half trying to figure this out with no luck please excuse some of the sql inconsistencies i rewrote up the sql real quick trimming out a lot of additional columns relatedtables and constraints that werent needed for this questioneditafter doing a little digging around i found that output might be useful for this is there a way to use output to map the quantlistattributeid records i just inserted to the quantlistattributeid they originated from,['sql'] +901001,file was built for arm64 which is not the architecture being linked x86 64 i am building a framework first to use in my ios simulator however i get this error when importing it into the main projectfile was built for arm64 which is not the architecture being linked x86 64here is the build info of my frameworkupdatei created a universal framework using this technique but i am still getting the errorupdate results from running file on the binaryhunterp file dinkle dinkle macho universal binary with 2 architecturesdinkle for architecture x86 64 macho 64bit dynamically linked shared library x86 64dinkle for architecture arm64 macho 64bit dynamically linked shared library,"['ios', 'objective-c']" +901078,how to suppress variable type within value attribute using ngoptions running angularjs 140rc1 the value within a ngoptions loop contains the type of the variablesee the following codescript srcscriptscript angularmoduleselectoptionstest controllerselectoptionscontroller scope functionscope scopeoptions id 1 label item 1 id 2 label item 2 id 3 label item 3 scriptdiv ngappselectoptionstest ngcontrollerselectoptionscontroller select ngmodelopt ngoptionsoptionid as optionlabel for option in options selectdivthis generates html code which looks like thisselect ngoptionsoptionid as optionlabel for option in options ngmodeloption classngpristine ngvalid ngtouched option value selectedselectedoption option valuenumber1 labelitem 1item 1option option valuenumber2 labelitem 2item 2option option valuenumber3 labelitem 3item 3optionselectwhy is the value prefixed by the type of the variable ie number in previous versions of angularjs eg the current stable 1315 the value attributes are filled with the expected values of 1 2 and 3so is this a bug in 140rc1 or do those cases need to be handled differently now,['javascript'] +901155,is this code really undefined as clang seems to indicate i switched on fsanitizeundefined on my project which uses catch the unit testing library one line from catch was signalled as causing undefined behaviour by this flag i managed to make an isolated exampleinclude iomanipinclude sstreamint main stdostringstream os os 0x stdsetfill0 stdhexcompiled withclang fsanitizeundefined maincppif i run this the following print is givenusrbinlib64gccx86 64unknownlinuxgnu492includec492bitsios baseh9624 runtime error load of value 4294967221 which is not a valid value for type std ios fmtflagsusrbinlib64gccx86 64unknownlinuxgnu492includec492bitsios baseh7667 runtime error load of value 4294967221 which is not a valid value for type std ios fmtflagsthis happens for me on clang 360 and for a friend with clang 341ubuntu3 it does not happen for me on gcc version 492so what is up here is this code actually bad or is there something fishy going on on clangs end,['c++'] +901166,ionic angular post request return state 404 i just updated on the new version on the angular ionic and method for processing remote request stopped working and returns always 404 responserequest is followingrequest methodpoststatus code404 not found from cacherequest headersview sourceacceptapplicationjson textplain contenttypetextplainoriginfileuseragentmozilla50 linux android 442 lenovo buildkot49h applewebkit53736 khtml like gecko version40 chrome30 mobile safari53736request payloadview sourceacode of the method which is processing remote request is following set transfer credentials http method post url scoperemoteurl data img base64 9j4aaqskz headers applicationjson timeout 10 success response successfunctiondata status headers config suces else processing error error response errorfunctiondata status headers config error i tried to solve it using this topicangularjs httppost does not send dataand angular ionic post request getting 404 not foundbut without luckserver side is processing request by this wayinputjson file get contentsphpinput input json decode inputjson true convert json into arrayif i am trying to send request using postman or curl everything seems to be working ionic infonode version v0122cordova cli 500ionic cli version 1322xcode version xcode 631 build version 6d1002 iossim version not installediosdeploy version not installedangularjs versionversion 1313how can i solve it pleasemany thanks for any advice,['javascript'] +901233,background image dimension for navigation drawer header basically i liked the background used by mr jonathan lee for navigation drawer header back ground in google official link so i wanted to reproduce something similar inspired by that i believe i need to make similar design in photoshop and set as background but the question is what should be the dimensions and pixels so that it matches different kind of devicesth above link has guideline for icons and margins but have not seen any dimension mentioned for that backgroundanybody has any idea or link that can help,['android'] +901251,strange for infinite loop in java how is this useful though i have some experience in java the following code looks a bit strange to mepublic class forlooptest public static void mainstring args for this code compiles fine although the initializationtestincrement part is empty unlike a usual for loop forint i0 i10 isince the code compiles fine it is valid syntax is there any practical use of this type of for loop where there is no initializationtestincrement part,['java'] +901257,typeaheadjs and bloodhound showing an odd number of results i have a typeaheadbloodhound implementation in my frontend that fetches jsondata from a playscalaserver typeaheadversion is 01 the implementation is as followshtmldiv idtypeahead classcolmd8 input classtypeahead formcontrol typetext placeholderselect the userdivjavascriptvar engine new bloodhound datumtokenizer function datum var fullname fullnamedatum return bloodhoundtokenizerswhitespacefullname querytokenizer bloodhoundtokenizerswhitespace identify functionobj return objid remote url routescontrollersusersindexurl cache false replace function url query if isemptyquery url encodeuricomponentquery return url filter function data consolelogdata return mapdata function user return id userid fullname viewmodelfullnameuser instantiate the typeahead uitypeahead typeaheadtypeahead hint true highlight true minlength 1 name engine thisplaykey fullname source enginefunction fullnamedata if data undefined return else var fname datafirstname undefined datafirstname var lname datalastname undefined datalastname return fname lname jsonresponse the server givesfirstnametestlastnameuser id1 the server pages the result so that it gives maximum of 5 results which is supposed to be the default limit for typeaheadbloodhound as wellthe problem is that when the server returns 5 results typeahead shows 0 results in the overlay if the server gives 4 results typeahead shows 1 in the overlay if the server gives 3 results typeahead shows 2 results for 2 and 1 results it shows the correct number of elements in the overlay if i remove the page length and the server returns over 10 results then typeahead shows 5 results the limit consolelog inside the filter shows the correct number of dataresults so they go to bloodhound at leastwhat might be the issue with this code this typeaheadfield is the only typeaheadfield present in this page i checked the dom and typeahead generates wrong amount of resultset fields so it is not a problem with css tried to remove all custom css as well thanks for any replies,"['javascript', 'jquery']" +901273,how to move bootstrap 3 carousel caption below images i have this html that shows slideshow images using bootstrap 3 div classcolsm8 div idmycarousel classcarousel slide dataridecarousel indicators ol classcarouselindicators li datatargetmycarousel dataslideto0 classactiveli li datatargetmycarousel dataslideto1li li datatargetmycarousel dataslideto2li li datatargetmycarousel dataslideto3li li datatargetmycarousel dataslideto4li li datatargetmycarousel dataslideto5li ol wrapper for slides div classcarouselinner rolelistbox for p in posts if forloopcounter 1 div classitem active else div classitem endif if pheadimage img src pheadimageurl altimage width460 height345 endif div classcarouselcaption h3 ptitle h3 p pteaser p div div endfor div left and right controls a classleft carouselcontrol hrefmycarousel rolebutton dataslideprev span classglyphicon glyphiconchevronleft ariahiddentruespan span clasronlypreviousspan a a classright carouselcontrol hrefmycarousel rolebutton dataslidenext span classglyphicon glyphiconchevronright ariahiddentruespan span clasronlynextspan a divdivi want caption to be shown below the image not over iti tried to manipulate the html and css but could not achieve this so appreciate your helpupdate apart from native bootstrap i have tried these custom css directives which did not helpcarouselinner paddingbottom95px carouselcaption bottom95px,['css'] +901402,how to compress a sequence of nonrepeated number size and bits im trying to compress a sequence of nonnegative numbers wherethe value range of each number is from 0 to 2n1each number appears once only it means there is total 2n numbers example for and 414 1 8 2 12 6 0 10 4 13 5 7 15 9 3 11so normally each number will cost 4 bits and for 16 numbers we will have to use 16x4 64 bits to store themcurrently i have just thought of compressing them as belowfor the first 8 numbers use 4 bits to store each of themfor the next 4 numbers only 3 bitseachfor the next 2 numbers only 2 bitseachfor the next 1 numbers only 1 bit for itfor the last one actually its not necesary to be stored obviously we should know what the last number is if we know all other 15 numbers so the compressed data size will bez 8 4 4 3 2 2 1 1 1 0 49 bits the compression ratio is about 76 which is pretty good i thinkbut for larger values of n the ratio seems to be decreased for and 2048 the ratio is only 91 so i would like to hear your suggestions for better compressingthank you,['c++'] +901416,how do i get my rails assets to be served by cloudflare instead of my server i am running a rails app on heroku and recently switched to cloudflare for cdn for asset serving my understanding was that once i use cloudflare my assets ie jscssimages would be served from cloudflare and not from my own server but in my heroku logs i still see the requests for assets do i need to configure something in my rails app like setting the asset host or something thanks,['ruby-on-rails'] +901442,method overload ambiguity with java 8 ternary conditional and unboxed primitives the following is code compiles in java 7 but not openjdk1804531b13fc21static void fobject o1 int i static void fobject o1 object o2 static void testboolean b string s string double d 10 the supremum of types string and double is object object o b s d double boxeddouble d int i 1 fo i fine fb s boxeddouble i fine fb s d i error ambiguousthe compiler claims the last method call ambiguousif we change the type of the second parameter of f from int to integer then the code compiles on both platforms why does not the posted code compile in java 8,['java'] +901450,is there a compiler hint for gcc to force branch prediction to always go a certain way for the intel architectures is there a way to instruct the gcc compiler to generate code that always forces branch prediction a particular way in my code does the intel hardware even support this what about other compilers or hardwaresi would use this in c code where i know the case i wish to run fast and do not care about the slow down when the other branch needs to be taken even when it has recently taken that branchfor if normal how to tell compiler to always branch predict true value dosomethingnormal else exceptionalcase as a follow on question for evdzhan mustafa can the hint just specify a hint for the first time the processor encounters the instruction all subsequent branch prediction functioning normally,['c++'] +901608,android identify whether webview playing sound or not the web page loading inside webview is auto playing in background i would like to detect when sound stops and than thisplay toast messagethanks,['android'] +901706,java call stack inspection and manipulation my question is is it possible in any way to analyze and modify call stack both content of frames and stack content in runtimei am looking for any possibility lowlevel unsafe or internal api possibility to write c extension etc only constraint it should be usable in standard runtime without debugging or profiling mode this is the point where i am doing research is it possible at all not is it good ideai would like to gather all local data from a frame store it somewhere and then remove that frame from stack with possibility of restoring it later effectively that gives us continuations in jvm and they will allow fast async frameworks like gevents from python and generator constructs like those from python to come upthis may look like repeated question but i have only found questions that were answered with use threadcurrentthreadgetstacktrace or that should be done with debugging tools there was similiar question to mine but it was only answered in context of what asking guy wanted to do work on async computations while i need more general javastack oriented answer this question is similiar too but as before it is focused on parallelization and answers are focused on that tooi repeat this is research step in process of coming up with new language feature proposal i do not wanna risk corrupting anything in jvm i am looking for possibility then i am gonna analyse possible risks and look out for them i know that manipulating stack by hand is ugly but so is creating instances with ommiting consrtuctor and it is basis for objenesis dirty hacks may be dirty but they may help introducing something coolps i know that quasar and lightwolf exist but as above those are concurrencyfocused frameworkseditlittle clarification i am looking for something that will be compatible with future jvm and libraries versions preferably were talking about something that is considered stable public api but if the solution lies in something internal yet almost standard or becoming standard after being internal like sunmiscunsafe that will do too if it is doable by cextension using only c jvm api that is ok if that is doable with bytecode manipulation that is ok too i think that may be possible with asm,['java'] +901810,rubymine rails server launcher was not found in the project after importing an existing project into rubymine i encountered rails server launcher was not found in the project when i runedit configuration i have checked this cannot start the debugger in rubymine rails server launcher wasnt found in project but deleting the idea directory and reopen is not helpful i can rails server in the terminal successfully and the rails server runs so i guess it is likely a rubymine related thingthanksallen,"['ruby-on-rails', 'ruby']" +901842,c lambda capture private class member here is a part of my class bool dump dvars fstream refvar output file for each array start array start array size refvarconst void dvar void work with output file return true private void array start unsigned int array size fstream output file i want to access the private member variable output file of my lambda which is in the public member function dump dvars when i capture the this pointer i can not access the variable because it is private i also do not want to make it public though i already read this question how to make the lambda a friend of a class but i do not want to create another function so my current fix for the problem is creating a reference to the private member and pass that variable via reference capture list to my lambdais that a good solution and good style or is there a better solution,['c++'] +901844,reserved keyword is used in protobuf in python in general i have a protobuf definition which used a python keyword from it works in javacc but when comes to python i could not assign value to ithere is the detail of my problemi have a protobuf definition like belowmessage foo required int64 from 10 since the field from is a keyword in python after i generated the python code i could not compile the code as belowfoo foofoofrom 1234then i tried to use setattr to set the attributesetattrfoo from 1234that gives me a protobuf exceptionattributeerror assignment not allowed to composite field from in protocol message objecti could not change the definition at this moment because it has been used widely in the system any help would be appreciated if i can workaround to use the from attribute in pythonbelow is the protobuf generated codeimport sys foo descriptordescriptor namefoo full namecomkerneljoyfoo filenamenone filedescriptor containing typenone fields descriptorfielddescriptor namefrom full namecomkerneljoyfoofrom index0 number10 type3 cpp type2 label2 has default valuefalse default value0 message typenone enum typenone containing typenone is extensionfalse extension scopenone optionsnone extensions nested types enum types optionsnone is extendablefalse extension ranges oneofs serialized start28 serialized end47descriptormessage types by namefoo foofoo reflectiongeneratedprotocolmessagetypefoo messagemessage dict descriptor foo module foo pb2 protoc insertion pointclass scopecomkerneljoyfoo sym dbregistermessagefoo,['python'] +901867,proper use of hkobserverquerys background update completionhandler hkobserverquery has the following method that supports receiving updates in the background initwithsampletypepredicateupdatehandlerthe updatehandler has a completionhandler which has the following documentationthis block is passed to the update handler you must call this block as soon as you are done processing the incoming data calling this block tells healthkit that you have successfully received the background data if you do not call this block healthkit continues to attempt to launch your app using a back off algorithm if your app fails to respond three times healthkit assumes that your app cannot receive data and stops sending you background updatesfrom looking at other posts it seems like there is a lot of confusion revolving around this handler below are some questions that i have about itwhen should the handler be called if called too late then hk might think that the app never received the query update causing you to hit the background update 3strikes backoff algorithm the documentation states that it should be called after handling other queries depending on how long it would take to run those queries it sounds like you could get dangerously close to hitting the background update strikeswhy is this needed should not the system know that the app has been launched and has received the background update when using corebluetooth in the background it just wakes your app up in the background for 10 seconds no need to call any handler or deal with the background update 3strikesif you hit the background update 3strikes and hk stops sending updates is that permanent does hk ever start sending the background updates again what if there is a bug that prevented the handler to be called and now youve fixed it is the app stuck never receiving the updates or will it reset when the app is relaunched or updateddoes hk keep your app running in the background until the handler is called is that part of its purpose or just a side effect if it is part of its purpose how long can we run before needing to stop and hit the first background update strike,['ios'] +901899,are there any advantages of using fusedlocationproviderapi over locationmanager earlier to get user current location i have used locationmanagerlocationmanager locationmanager locationmanager getactivitygetsystemservicecontextlocation serviceif locationmanagerisproviderenabledlocationmanagergps provider location locationmanagergetlastknownlocationlocationmanagergps provider else if locationmanagerisproviderenabledlocationmanagernetwork provider location locationmanagergetlastknownlocationlocationmanagernetwork providerit is easy to read and very straightforward codebut i have noticed that google recently released new client api model in google play services and suggests to use fusedlocationproviderapi which looks like much more complicated it is async it requires to handle callbacks etcare there any advantages of using fusedlocationproviderapi over locationmanager,['android'] +901946,are variables local to a class that are not declared as pointers created on the heap or stack take the followinga aclass b no content for brevityclass apublic a bsettitlehi private b bint main return 0the question here is if b which is declared inside a is declared on the heap or on the stackif on the heap does this mean it is automatically deleted or must i also delete this tooside questionthis is what i was originally doing but thought i was being a bit stupid as i had to keep declaring everything as new everywhere if the above is on the stack i guess it was not so stupid righta aclass b no content for brevityclass apublic a thisb new b i do not have c 14 so i cannot do make unique bsettitlehi private unique ptrb bint main return 0,['c++'] +902044,separating a string in c i am trying to separate a string into multiple strings to make a customized terminal so far i have been separating control signals using strtok however i do not understand how to separate specific instances of a character for examplestring input false echo hello world grep hellowhen trying to strtok this input and trying to separate using the output would befalse echo hello world grep helloinstead i would like the output to befalse echo hello world grep hellohow can i have strtok treat and differently rather than having it saying they are the same,['c++'] +902081,cordova hello world app would not thisplay i am new to apache cordova and i cannot get the cordova hello world application to thisplay on android i am talking about the default application obtained from the cordova create command from the clii read the documentation and installed everything as required nodejs npm cordova 500 i already had an android sdk so i just needed to update the pathcordova tells me the build is a successit then says the application is launched but the only thing that changes on deviceemulator screen is that a menu is opened like on the following picture i tried on an emulator and on a real device results are the samei checked the api version and it seems to be high enough 403i am under windows 7 with an oracle jdk i thought maybe a plugin was missing and installed cordovaplugindevice but it did change nothingis this a bug or do i miss somethingis there some mean to get an error report nothing unusual appears with the cordova run android command,['android'] +902122,how to stop mbprogresshud and add a subview when the server is not returning data in my app i have this class to get data from my serverclass apifunc loadofferscompletionoffers void offer id string offerstatusstring let myurl nsurlstring let request nsmutableurlrequesturl myurl requesthttpmethod post let poststring offer idoffer idofferstatusdealstatusactionshow requesthttpbody poststringdatausingencodingnsutf8stringencoding allowlossyconversion true let task nsurlsessionsharedsessiondatataskwithrequestrequest data response error in if error nil printlnerrorerror else var errnserror let jsonobject anyobject nsjsonserializationjsonobjectwithdatadata options nsjsonreadingoptionsmutablecontainers error nil if let dict jsonobject as string anyobject if let myoffers dictoffers as anyobject var offers offers for offer in myoffers let offer offersdictionary offer as nsdictionary offersappendoffer let priority thispatch queue priority default thispatch asyncthispatch get global queuepriority 0 thispatch asyncthispatch get main queue completionoffers taskresume then in my view controller i load the model class myviewcontroller uiviewcontroller uitableviewdatasource uitableviewdelegate var offers offers func loadmodel let loadingnotification mbprogresshudshowhudaddedtoselfview animated true loadingnotificationmode mbprogresshudmodeindeterminate loadingnotificationlabeltext updating your offers offers offers let api api apiloadoffersdidloadoffers offer id dealident offerstatus open func didloadoffersoffersoffers selfoffers offers selftableviewreloaddata mbprogresshudhideallhudsforviewselfview animated true selfrefreshcontrolendrefreshing override func viewwillappearanimated bool loadmodel everything works except that when the json dictionary is empty meaning that there no offers the mbprogresshud keep spinningi would like stop the activity indicator adding a subview instead which says that there are no offers any suggestion would be greatly appreciated i triedif offersisempty mbprogresshudhideallhudsforviewselfview animated true and also if offers 0 mbprogresshudhideallhudsforviewselfview animated true but it is not working thanks,['ios'] +902131,how play video on videoview inside viewpager from server i try to develop an app that retrieve videos from server and play on videoview inside viewpager video from raw folder is worked fine but their are 2 issues1 some video is not played or black activity show2 video is not stop when page is scrolledso how to use url instead of androidresourcemypackagenamevideo1mp4and how to pausestop when pageischanged any tutorial or any hits i will be thankful for that here my code is source codeviewpageradapterjavaimport androidcontentcontextimport androidmediamediaplayerimport androidmediamediaplayeronpreparedlistenerimport androidneturiimport androidsupportv4viewpageradapterimport androidsupportv4viewviewpagerimport androidviewlayoutinflaterimport androidviewviewimport androidviewviewgroupimport androidwidgetimageviewimport androidwidgetlinearlayoutimport androidwidgetmediacontrollerimport androidwidgettextviewimport androidwidgetvideoviewpublic class viewpageradapter extends pageradapter context context string rank string country string population int flag layoutinflater inflater static int arrayvid private videoview mvideoview public viewpageradaptercontext context string rank string country string population int flag int arrayvid thiscontext context thisrank rank thiscountry country thispopulation population thisflag flag thisarrayvid arrayvid override public int getcount return ranklength override public boolean isviewfromobjectview view object object return view linearlayout object override public object instantiateitemviewgroup container final int position declare variables textview txtrank textview txtcountry textview txtpopulation imageview imgflag inflater layoutinflater context getsystemservicecontextlayout inflater service view itemview inflaterinflaterlayoutviewpager item container false locate the textviews in viewpager itemxml txtrank textview itemviewfindviewbyidridrank txtcountry textview itemviewfindviewbyidridcountry txtpopulation textview itemviewfindviewbyidridpopulation imgflag imageview itemviewfindviewbyidridflag mvideoview videoview itemviewfindviewbyidridvvexe txtranksettextrankposition txtcountrysettextcountryposition txtpopulationsettextpopulationposition imgflagsetimageresourceflagposition mvideoviewsetonpreparedlistenernew onpreparedlistener override public void onpreparedmediaplayer mp mpsetloopingtrue mediacontroller mediacontroller new mediacontrollercontext false mediacontrollersetanchorviewmvideoview mvideoviewsetmediacontrollermediacontroller viewpager containeraddviewitemview return itemview override public void destroyitemviewgroup container int position object object remove viewpager itemxml from viewpager viewpager containerremoveviewlinearlayout object public void pausevideo mvideoviewstopplayback public void playint position mvideoviewsetvideouriuri parseandroidresourcemypackagename arrayvidposition mvideoviewrequestfocus mvideoviewstart mainactivityjavaimport androidappactivityimport androidosbundleimport androidsupportv4viewpageradapterimport androidsupportv4viewviewpagerimport androidsupportv4viewviewpageronpagechangelistenerimport androidviewviewimport androidwidgetimagebuttonpublic class mainactivity extends activity declare variables viewpager viewpager pageradapter adapter string rank private imagebutton play string country string population int flag public int position int arrayvid boolean isrunning true override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate get the view from viewpager mainxml setcontentviewrlayoutviewpager main play imagebutton findviewbyidridbtnplayab generate sample data rank new string 1 2 3 4 5 6 7 8 9 10 country new string china india united states indonesia brazil pakistan nigeria bangladesh russia japan population new string 1354040 1210193422 3157610 237641326 193946886 1829120 1709010 152518015 143369806 127360 flag new int rdrawablechina rdrawableindia rdrawableunitedstates rdrawableindonesia rdrawablebrazil rdrawablepakistan rdrawablenigeria rdrawablebangladesh rdrawablerussia rdrawablejapan arrayvid new int rrawbasiccrunch rrawbicyclecrunch rrawreversecrunch rrawlongarmcrunch rrawcrossovercrunch rrawrightobliquecrunch rrawleftobliquecrunch rrawhalfcurl rrawverticallegcrunch rrawplank locate the viewpager in viewpager mainxml viewpager viewpager findviewbyidridpager pass results to viewpageradapter class adapter new viewpageradaptermainactivitythis rank country population flag arrayvid binds the adapter to the viewpager viewpagersetadapteradapter playsetonclicklistenernew viewonclicklistener override public void onclickview v if isrunning viewpageradapter adapterplayposition isrunning false playsetbackgroundresourcerdrawablepausee else viewpageradapter adapterpausevideo isrunning true playsetbackgroundresourcerdrawableplayy viewpager itemxmlxml version10 encodingutf8linearlayout xmlnsandroid androidididlinearlayout1 androidlayout widthfill parent androidlayout heightfill parent androidgravitycenter androidorientationvertical androidpadding10dp androidweightsum10 linearlayout androidlayout widthfill parent androidlayout height0dip androidlayout weight16 androidorientationhorizontal linearlayout androidlayout width0dip androidlayout heightfill parent androidlayout weight3 androidorientationvertical linearlayout androidlayout widthwrap content androidlayout heightwrap content androidorientationhorizontal textview androidididranklabel androidlayout widthwrap content androidlayout heightwrap content androidtextstringranklabel textview androidididrank androidlayout widthwrap content androidlayout heightwrap content linearlayout linearlayout androidlayout widthwrap content androidlayout heightwrap content androidorientationhorizontal textview androidididcountrylabel androidlayout widthwrap content androidlayout heightwrap content androidtextstringcountrylabel textview androidididcountry androidlayout widthwrap content androidlayout heightwrap content linearlayout linearlayout androidlayout widthwrap content androidlayout heightwrap content androidorientationhorizontal textview androidididpopulationlabel androidlayout widthwrap content androidlayout heightwrap content androidtextstringpopulationlabel textview androidididpopulation androidlayout widthwrap content androidlayout heightwrap content linearlayout linearlayout imageview androidididflag androidlayout width0dip androidlayout heightfill parent androidlayout weight1 androidbackground0 androidpadding1dp linearlayout videoview androidididvvexe androidlayout widthwrap content androidlayout height0dip androidlayout margintop5dp androidlayout weight79 androidgravitycenter linearlayoutviewpager mainxml xml version10 encodingutf8 linearlayout xmlnsandroid androidididlinearlayout1 androidlayout widthfill parent androidlayout heightfill parent androidorientationvertical androidweightsum10 androidsupportv4viewviewpager androidididpager androidlayout widthwrap content androidlayout height0dip androidlayout weight86 linearlayout androidlayout widthfill parent androidlayout height0dip androidlayout weight14 androidgravitycenter androidpadding10dp linearlayout androidlayout widthmatch parent androidlayout heightmatch parent androidlayout gravitycenter androidbackground696969 androidgravitycenter androidorientationhorizontal androidweightsum10 linearlayout androidlayout width0dp androidlayout heightmatch parent androidlayout weight1 linearlayout imagebutton androidididbtnprevab androidlayout width0dp androidlayout heightwrap content androidlayout weight2 androidbackgrounddrawableprevsel linearlayout androidlayout width0dp androidlayout heightmatch parent androidlayout weight1 linearlayout imagebutton androidididbtnplayab androidlayout width0dp androidlayout heightwrap content androidlayout weight2 androidbackgrounddrawableplaysel linearlayout androidlayout width0dp androidlayout heightmatch parent androidlayout weight1 linearlayout imagebutton androidididbtnnextab androidlayout width0dp androidlayout heightwrap content androidlayout weight2 androidbackgrounddrawablenextsel linearlayout androidlayout width0dp androidlayout heightmatch parent androidlayout weight1 linearlayout linearlayout linearlayout,['android'] +902136,page not found when a user clicks on a facebook invite from my application i am not sure if this is a programming related problem or not but as i have no experience with the facebook sdk i am just assuming that i did something wrong somewhere even though i have followed the documentation to the ti am using the unity sdk for anybody that is curious and i am using the fbapprequest to send the invite to the application the code in my application looks exactly like that in the documentation public void invitefriends fbapprequest message come play this great game callback logcallback void logcallbackfbresult result debuglogcallback was called resulttextthis brings up the box as expected and allows me to invite a friend and the friend does get the invite however once they click on the invite they are redirected to a page that looks like thiswhich is causing quite a bit of problems for me i have checked everything in the application panel and it seems like everything checks out my google play identifier is correct aswell as my class name my key hashes are all correct i do not know what else i can do if youd like to look up my bundle identifier on the play store it is buzzqualify and i am sure that youll find it with easei should also add that i have an application page which can be found here this page is linked to the facebook application in the developer console aswellwhat can i do to resolve this issue is it in the code please help this has been a 4 day long setback and were losing progress rapidly because of itit is been a few days now were now paying someone for a fix through paypal,['android'] +902145,add jar to doclet classpath using mavenjavadocplugin i wrote a doclet that collects some data and passes it to a reporter i want this reporter to be exchangeable i tried to add a reporter implementation to the doclet classpath using an additionaldependency andor a plugindependency i cannot load the reporter implementation with the java 6 service loader and it also does not work to get the class using the doclets class loader or the threads context class loaderhow can i get the testtestreporterimpl into the testdoclet classpathin the docletapireporterserviceloader serviceloaderloadtestreporterclass testtestreporterapireporterserviceloaderiteratorhasnext falsethreadcurrentthreadgetcontextclassloaderloadclasstesttestreporterimpl classnotfoundexceptiongetclassgetclassloaderloadclasstesttestreporterimpl classnotfoundexceptionin the pom executing the docletplugin groupidorgapachemavenpluginsgroupid artifactidmavenjavadocpluginartifactid version2103version executions execution idrunmydocletid goals goaljavadocgoal goals phasegenerateresourcesphase execution executions dependencies dependency groupidtestgroupid artifactidtestdoclettestreporterartifactid versionprojectversionversion dependency dependencies configuration doclettesttestdocletdoclet docletartifact groupidtestgroupid artifactidtestdocletartifactid versionprojectversionversion docletartifact additionaldependencies additionaldependency groupidtestgroupid artifactidtestdoclettestreporterartifactid versionprojectversionversion additionaldependency additionaldependencies usestandarddocletoptionsfalseusestandarddocletoptions configurationplugintestdoclettestreportersrcmainresourcesmetainfservicestesttestreportertesttestreporterimpl,['java'] +902268,d3 gauge chart with growing arc i want to achieve something like a growing arc which indicates 5 levels see picture my data has only an integer value which is between 15 you can ignore the icon in the middle for now is there any possibility to achieve something like that in d3 i could not find any example for this moreover i tried it with a cut off pie donut chart approach but i could not make the growing arc i would appreciate any help thanks for that,['javascript'] +902417,nullpointerexception on return new i have a very strange problem with nullpointerexception code example is as follows public string getparams 143 return new string 144 getuserfullname145 stringutilformatdatesent tiltu stringutilinitcapusergetname vuositostring asiatyyppi0 lisatiedot0 asiatyyppi1 lisatiedot1 alaviitteet0152 alaviitteet1153 now i have got an issue from production having a stack tracejavalangnullpointerexception at packageemailservicegetparamsemailservicejava143i am unable to produce that kind of stack trace myself it maybe some environment issue that for some reason line numbers do not match if i have null references on any variable stack trace points to that specific line but never to line 143but what i want to ask is is it possible to produce nullpointerexception at line 143 specifically,['java'] +902493,what is the maximum length of concatenated sms in smpp i am working on an smsc service which is supposed to join the messages if it finds the pdu header and then pass that message to the next service which uses different protocols not just smpp to actually deliver the message now i am a little puzzled about the max length of the messagei have been searching and the only thing i found about it is this where they mention thatnote in theory it is possible to utilize 255 messages 39015 characters for a concatenated sms however 3 sms or 459 characters is generally considered to be the longest length message that will be thisplayed on the majority of mobile handsets cardboardfish limit concatenated sms to 459 characters to ensure maximum compatibilityis there any official documentation speaking of this maximum limit of 3 sms what kind of limits mobile oses actually have and finally what maximum length should i allow in my service,"['android', 'ios']" +902498,new applicationdbcontext vs httpcontextgetowincontextget i am a little confused about which way is better and which one to use surely if you can always get httpcontextgetowincontextget then why even create a new applicationdbcontext and risk doubling objects etcnote i am specifically talking about a web application here,"['c#', 'asp.net']" +902560,how to implement aspnet identity 20 in existing database i am currently having existing membership implemented in aspnet 45 web forms project the application uses entityframework 613 version with dbcontext and currently in database first approach i want to migrate the old membership to use the new aspnet identity 20 system i have followed this article for performing the migration but never succeeded i got the errors as mentioned in the property claims on type aspnetuser is not a navigation propertyit confirms that i am missing something basic in the migration processcan someone provide me the step by step guide to perform the success migrationi want to address the following points1 in identity i have some extra user data other than what default identity is providing i see there is a identitycontext which does these identity operations i have a different context which inherits from dbcontext do i need to use both the contexts in other words identitycontext is compulsory for identity operation cannot these two contexts be merged into one2 i am not restricted to database first approach since the identity uses the code first approach i am okay to go ahead with the codefirst approach but needs the correct steps to follow up3 since i have extra user data so i need to extend the identityuser to add new properties if i will extend the identityuser will the identity code work seamlessly4 i followed video tutorial which adds the migration in the applicationdbcontext the applicationdbcontext inherits identitycontext it worked for me but i want to add migration for my own context which inherits from dbcontext it is because the applicationdbcontext does not include the other tablesnonidentity tables5 i tried applying the migration in my custom contextcs file which contains all the identity and nonidentity tables i created this class using the reverse engineering approach by entityframework power tools as suggested in this articleafter the poco classes are created i added migration and updated the database the main errors i got areidentityuserlogins entitytype entityset identityuserlogins is based on type identityuserlogin that has no keys defined identityuserroles entitytype entityset identityuserroles is based on type identityuserrole that has no keys definedas per this solution i added the configuration but ended up with creating new tables for identityuserlogin identityrole etc which are duplicate identity tables6 even if i am keeping duplicate identity tables eg aspnetuserroles and identityuserrole i am not able fetch data using the identity codevar user usermanagerfindasyncusernametext passwordtext and getting exceptioninvalid column name userid,"['c#', 'asp.net']" +902566,why cannot functionalinterfaces have default methods why cannot i create a functionalinterface with a default method implementationfunctionalinterfacepublic myinterface default boolean authorizestring value return true,['java'] +902593,why use immutablelist over readonlycollection net 45 has a new namespace systemcollectionsimmutablethis package provides collections that are thread safe and guaranteed to never change their contents also known as immutable collectionsi am confused is not the thread safety problem already solved by the readonlycollection class why use immutablelist insteadi know there is also an ireadonlylist interface that does not solve the thread safety problem implicitly because other threads may edit the object by another interface,"['c#', '.net']" +902680,rotate frame layout which contains dynamic buttons i have a framelayout which add four imageview at runtime as well in center it contains main image with which user can perform different action but i face the problem with rotate layout view currently on touch of rotate button i am doing thispublic void setrotatelistener mrotateimagesetontouchlistenernew ontouchlistener override public boolean ontouchview v motionevent event float x eventgetx0 float y eventgety0 float theta getthetax y switch eventgetaction motioneventaction mask case motioneventaction pointer down theta old theta break case motioneventaction move float delta theta theta theta old theta old theta int direction delta theta 0 1 1 angle 3 direction logdtag rotate angle objgetheight objsetrotationangle notifylistenerdirection break return true private float getthetafloat x float y float sx x objgetwidth 20f float sy y objgetheight 20f float length float mathsqrtsx sx sy sy float nx sx length float ny sy length float theta float mathatan2ny nx final float rad2deg float 1800 mathpi float thetadeg theta rad2deg return thetadeg 0 thetadeg 3600f thetadegbut i cannot get the expected result i already refer this link as well as well as try to rotate with gesture and animation too but it seems not working as per my move on the screen,['android'] +902706,avfoundation reverse an avasset and output video file i have seen this question asked a few times but none of them seem to have any working answers the requirement is to reverse and output a video file not just play it in reverse keeping the same compression format and frame rate as the source videoideally the solution would be able to do this all in memory or buffer and avoid generating the frames into image files for ex using avassetimagegenerator and then recompiling it resource intensive unreliable timing results changes in frameimage quality from original etc my contribution this is still not working but the best i have tried so farread in the sample frames into an array of cmsamplebufferref using avassetreaderwrite it back in reverse order using avassetwriterproblem seems like timing for each frame is saved in the cmsamplebufferref so even appending them backwards will not worknext i tried swapping the timing information of each frame with reversemirror frame problem this causes an unknown error with avassetwriternext step i am going to look into avassetwriterinputpixelbufferadaptor avasset assetbyreversingassetavasset asset nsurl tmpfileurl nsurl urlwithstringtmptestmp4 nserror error initialize the avassetreader that will read the input asset track avassetreader reader avassetreader alloc initwithassetasset errorerror avassettrack videotrack asset trackswithmediatypeavmediatypevideo lastobject avassetreadertrackoutput readeroutput avassetreadertrackoutput assetreadertrackoutputwithtrackvideotrack outputsettingsnil reader addoutputreaderoutput reader startreading read in the samples into an array nsmutablearray samples nsmutablearray alloc init while1 cmsamplebufferref sample readeroutput copynextsamplebuffer if sample null break samples addobject bridge idsample cfreleasesample initialize the the writer that will save to our temporary file cmformatdescriptionref formatdescription cfbridgingretainvideotrackformatdescriptions lastobject avassetwriterinput writerinput avassetwriterinput alloc initwithmediatypeavmediatypevideo outputsettingsnil sourceformathintformatdescription cfreleaseformatdescription avassetwriter writer avassetwriter alloc initwithurltmpfileurl filetypeavfiletypempeg4 errorerror writerinput setexpectsmediadatainrealtimeno writer addinputwriterinput writer startsessionatsourcetimecmsamplebuffergetpresentationtimestamp bridge cmsamplebufferrefsamples0 writer startwriting traverse the sample frames in reverse order fornsinteger i samplescount1 i 0 i cmsamplebufferref sample bridge cmsamplebufferrefsamplesi since the timing information is built into the cmsamplebufferref we will need to make a copy of it with new timing info will copy the timing data from the mirror frame at samplessamplescount i 1 cmitemcount numsampletimingentries cmsamplebuffergetsampletiminginfoarray bridge cmsamplebufferrefsamplessamplescount i 1 0 nil numsampletimingentries cmsampletiminginfo timinginfo mallocsizeofcmsampletiminginfo numsampletimingentries cmsamplebuffergetsampletiminginfoarray bridge cmsamplebufferrefsample numsampletimingentries timinginfo numsampletimingentries cmsamplebufferref samplewithcorrecttiming cmsamplebuffercreatecopywithnewtiming kcfallocatordefault sample numsampletimingentries timinginfo samplewithcorrecttiming if writerinputreadyformoremediadata writerinput appendsamplebuffersamplewithcorrecttiming cfreleasesamplewithcorrecttiming freetiminginfo writer finishwriting return avasset assetwithurltmpfileurl,"['ios', 'objective-c']" +902764,thissettitle title name not working in cakephp 3x basically in defaultctp i have this for my titletitle thisfetchtitle titleand inside of the controller i have this linethissettitle testtitlebut it does nothing it still thisplays controllers namejobs controllers full name os jobscontrollerctpbut if i put this inside of my view filethisassigntitle testtitleit changes the title so what is wrong with thissettitle title,['php'] +902775,onerror do not work in ie i am trying to attach an event handler for the onerror event 404 error to a link element i have something like this on my pagelink relstylesheet typetextcss hrefdeadlinkcss onerrorhandle404error it works fine on chrome and opera but it should work on ie9 too i found this but i cannot find a solution myselfis there a way to do that without writing an extra method to load styles dynamically note i did not tag this question with jquery so please do not use it in your answers,"['javascript', 'html']" +902958,etoforms and sqlite crossplatform development for windowsosx i really like etoforms i think they will be boost the crossplatform developments in the futurebut after creating my first uiheavy application both windows and osx i realized that i need a database engine toomy fav for that project is sqlite but i cannot find a corresponding package on nuget for thathas anyone experiences with it,"['c#', '.net']" +903031,styling facebookactivity to avoid terrible progress bar i just implemented logging in through facebook using their sdk in conjunction with parsefacebookutilsv4in my manifest i had to declare a facebookactivity that gets launched when i try to sign in and that works great activity androidnamecomfacebookfacebookactivity androidconfigchangeskeyboardkeyboardhiddenscreenlayoutscreensizeorientation androidthemeandroidstylethemetranslucentnotitlebar androidlabelstringapp name this snippet comes from official docs so i did not choose anything what i found really weird is its styling on my emulator api 22 it has a progressbar that seems to be coming from the 90s is there a way to style it i have tried changing the androidtheme attribute but with no successi thought of extending comfacebookfacebookactivity but after digging through source code i found out it inflates a comfacebookloginfragment which is then responsible of the progress bar actually any ideas,['android'] +903148,use of iframe causing thisability of links i have an side navigation bar which toggles to hide and show on each click in the sidebarcontains a list links and a iframe where i am thisplaying a website when i click on a link it will hide the side bar and redirects it to corresponding url within the iframe area the problem is in when i am thisplaying some websites inside iframe the links of that redirected websites will only work in top half portion of iframe and remaining in remaining half portion of iframe links are thisabled when i scroll inside iframe ie when link in bottom half comes to top portion the links are enabled need help menu sample position absolute top 0 bottom 0 left 0 width 100px border solid 1px transition transform 01s easeout content position absolute top 0 bottom 0 right 0 left 0 padding 10px transition left 1s easeout marginleft 15 margintop 150 transition top mar margintop 25 on toggle contentpushed left 225px hide transformtranslatex 100px div classmenu sample top mar div classcolsm3 colmd2 sidebar ul classnav navsidebar lispan stylecolorblue fontweightbolddashboardsspanli for dashboard in dashboards lia href dashboardd url dashboardd name ali endfor ul div div div classcontent pushed top mar button onclicktogglemenuspan idmenubuttonspan classglyphicon glyphiconchevronleft idglymphi stylemarginleft24spanspanbuttondivdiv stylemarginleft1 margintop35 height 625px iframe width100 height95 nameiframe a frameborder0iframediv,"['html', 'css']" +903207,add server certificate information to trust manager android programmatically i am new to this ssl and x509certificate concepts what all i need is is there any way to get the certificate information from a given urlfor example if user has typed then i need the certificate information for that programmatically editfinally i got the certificate information from server now my questions are1 how can i check certificate is trusted or not 2 how can i add the certificate to the trust manager 3 even if it is untrusted certificate if the user wants to continue with that then i need to add the certificate to the trust manager how can i achieve this4 is it that inorder to check a certificate is trusted or not do we really need to have another certificate to compare i am very much new to these x509 certificateany help will be really appreciated editthis is what i have tried but none of them is helping me i need to get the certificate is trusted or notx509trustmanager trustmanager new x509trustmanager override public void checkclienttrustedx509certificate chain string authtype throws certificateexception for trustmanager tm managers if tm instanceof x509trustmanager x509trustmanager tmcheckclienttrusted chain authtype override public void checkservertrustedx509certificate chain string authtype for x509certificate cert chain final string mcertificatinotype certgettype date afterdate certgetnotafter date beforedate certgetnotbefore date currentdate new date try certcheckvaliditynew date catch certificateexpiredexception e loginactivityisexpired true eprintstacktrace catch certificatenotyetvalidexception e loginactivityisinvalid true eprintstacktrace try certverifytrustedrootgetpublickey catch invalidkeyexception e eprintstacktrace catch certificateexception e eprintstacktrace catch nosuchalgorithmexception e eprintstacktrace catch nosuchproviderexception e eprintstacktrace catch signatureexception e eprintstacktrace try if certgetissuerx500principalequals trustedrootgetissuerx500principal certverifytrustedhostgetpublickey catch invalidkeyexception e eprintstacktrace catch certificateexception e eprintstacktrace catch nosuchalgorithmexception e eprintstacktrace catch nosuchproviderexception e eprintstacktrace catch signatureexception e eprintstacktrace if afterdatecomparetocurrentdate currentdatecomparetobeforedate 0 else if certgetissuerx500principalequals trustedrootgetissuerx500principal return for x509certificate cert chain url url string host if basehoststringequalsignorecase final settings settings mapplication getsettings try url new url settingsserveraddresstostring host urlgetauthority catch malformedurlexception e eprintstacktrace else string dn certgetsubjectdngetname string cn getvalbyattributetypefromissuerdndn cn if cnequalsignorecasehost if certgetissuerx500principalequals trustedrootgetissuerx500principal return else else for trustmanager tm managers if tm instanceof x509trustmanager try x509trustmanager tmcheckservertrusted chain authtype catch certificateexception e eprintstacktrace override public x509certificate getacceptethissuers arraylistx509certificate issuers new arraylist for trustmanager tm managers if tm instanceof x509trustmanager issuersaddallarrays aslistx509trustmanager tm getacceptethissuers return issuerstoarraynew x509certificateissuers size,['android'] +903342,ibinspectable and floating point values is it possible to set floating point value in attributes inspector i have this property in my uiviewibinspectablevar scale cgfloat 090 didset setneedsthisplay as you can see default value is 09 and i would like to change it in attributes inspector but it looks like thatand i am only able to set integer values in there am i missing something,['ios'] +903377,the best performant way to push items into array in my website i have many arrays with datafor example vertices array colors array sizes arrayi am working with big amounts of items up to tens of millionsbefore adding the data into the arrays i need to process ituntil now i did it in the main thread and this made my website freeze for x secondsit froze because of the processing and because of adding the processed data into the arraystoday i moved did a lot of work the processing into web workers but the processed data is being added in the main thread i managed to save the freezing time of the processing but not of the addingthe adding is simply done by arraypush or arraysplice i have read some articles about how array works and found out when we add item to an array the array is being fully copied to a new place in the memory with arraylength 1 size and there adding the value this makes my data pushing slow i also read that typed array are much faster but for this i would need to know the size of the array which i do not know and for creating a big typed array with extra counter and managing adding items in the middleand not the end of the array would be a lot of code change which i do not want to do at this timeso for my questioni have typedarray that return from the web worker and this i need to put into regular array what is the best performant way to do it today i am running in a loop and pushing one after the othereditexample how the website workthe client add count of items lets say 10the items raw data is being collected and send to the workerthe worker is processing all the information and sending back the processed data as typedarray for using as transferable objects in the main thread we are adding the processed data to arrays to the end or in some specific index2nd round the client add another 10 items sending to the worker and the result being added to the main thread arrays3nd round can be 10 items 4nd round 10 5nd round can remove indices 1020,['javascript'] +903387,table2excel plugin does not work i am working on a dashboard app and i would like to implement download table as xls featureon this link you can see how the table looks likedashboardi have found a library which also includes the tutorial that explains the set up as you can see in the code below i have done more or less everything like it was explained however it does not work and for some reason the table will not be exportedas you can see i have included jquerytable2exceljs in the resources together with all other resources which are used for this page i have also checked if the js file is available after the page is loaded and it also looks goodi have also tried this function documentgetelementbyidbtnexportaddeventlistenerclick function documentgetelementbyidmytabletable2excel exclude noexl name excel document name filename myfilename but it also does not look well and when i execute the function i get this message in the debugg console typeerror documentgetelementbyidtable2excel is not a functionthis is how my indexjsp looks like at the momentpage contenttypetexthtml pageencodingutf8taglib prefixc uritaglib uri prefixformdoctype html public w3cdtd html 401 transitionalenhtml langenhead meta charsetutf8 meta httpequivxuacompatible contentieedge meta nameviewport contentwidthdevicewidth initialscale1 titlekpi admintitle link hrefcurl valueresourcescssbootstrapmincss relstylesheet link hrefcurl valueresourcescssadditioncss relstylesheet link relstylesheet href script srccurl value script script srccurl value script script srccurl valueresourcesjsbootstrapjs script script srccurl valueresourcesjsadditionjs script script srccurl valueresourcesjsjquerytable2exceljs script script function documentgetelementbyidbtnexportaddeventlistenerclick function table2exceltable2excel exclude noexl name excel document name filename myfilename scriptheadbodynav classnavbar navbarinverse navbarfixedtop nav navdiv classcontainer div clastartertemplate ul classnav navtabs tabs ul tab panes div classtabcontent div classtabpane fade in active ida formform actionkpiadminkpis methodget div classrow forminline div classformgroup label fordatedatelabel input idstartdatepicker typetext classformcontrol namedate valuedate div button typesubmit classbtn btndefaultsubmitbutton div br div classtableresponsive table idmytable classtable tablebordered table2excel thead tr tdnametd tdlast importtd tdlast valuetd td colspan4valuestd td colspan3targetstd td colspan3scoretd tdactiontd tr thead tr tdtd tdtd tdtd td classtextcenter stylefontweight 700dtdtd td classtextcenter stylefontweight 700wtdtd td classtextcenter stylefontweight 700mtdtd td classtextcenter stylefontweight 700ytdtd td classtextcenter stylefontweight 70td td classtextcenter stylefontweight 700100td td classtextcenter stylefontweight 700150td td classtextcenter stylefontweight 700wtdtd td classtextcenter stylefontweight 700mtdtd td classtextcenter stylefontweight 700ytdtd tdtd tr cforeach varrow itemsrows varstatusloop loop that creates the table cforeach tr last row mean tr table div formform button idbtnexport classbtn btndefaultexport as xlsbutton div div classtabpane fade idb content inside tab b div div classtabpane fade idc content inside tab c div div div div container i am realy not sure what could cause this problem or do i have an error in the jquery syntax it could be also that the lib is not inportet correctly within jsp page but this is the way which was working for me in the past i guess that i am using right jquery version since jquery datepicker works fineif you are able to see what could case this issue please help me to fix it if you have any better idea how to export a table as an excel file please suggestthx in advanceedit 1i have changed the function and it looks like the code i have posted below if i execute consolelogexporting before or after table2exceltable2excel exporing will be printed out in the console obviously that excludes jquery as a potential cause of the problemscript function btnexportclickfunction consolelogexporting table2exceltable2excel exclude noexl name excel document name filename myfilename scriptedit 2since i was not able to fix this i have tried to try something new i have found this solutions and it works but still not as i would really like to so i hope that you can help me to improve itmy table looks like thisand this is what i get as a resultfirst of all it really looks strange without excel grid do you have an idea why the file is exported without it and how can i add itsecond i would like to remove the column after ytd where the additional infos are presented is it somehow possible to adjust the tab textreplace below in order to achive thisin html it looks like thistdtd width20px a classinfobox href img srcimginfojpg altinfo width18 height18 span service engineer br datasource span atrjavascript function looks like thisfunction exportexcelreporttblid var tab text table border2pxtr var table documentgetelementbyidtblid var style for var j 0 j tablerowslength j style tablerowsjclassnamesplit if stylelength 2 tab text tab text tablerowsjinnerhtml tr tab text tab text table tab text tab textreplaceaag tab text tab textreplaceimggi tab text tab textreplaceinputinputgi return windowopendataapplicationvndmsexcel encodeuricomponenttab textthx,"['javascript', 'jquery', 'html']" +903400,access violation when calling delphi dll from c in a multithreaded environment i am calling a dll function written in delphi xe2 from c using pinvoke it appears to be working when calls are made sequentially from a single thread however when multiple threads are calling the function the c host application throws systemaccessviolationexception seemingly at randomwhy does the code below trigger an access violation and how do i fix thisminimum delphi library code for reproducing the problemlibrary pinvokeproblemr resuses windows sysutilsprocedure testconst testbyte byte stdcallbegin outputdebugstringpwidecharinttostrtestbyteendexports testendminimum c host application code to reproduce the problemdllimport pinvokeproblemdll callingconvention callingconventionstdcall entrypoint testprivate static extern void testbyte testbytepublic static void mainstring args for int i 1 i 10 i more iterations better chance to fail int threadcount 10 parallelfor1 threadcount new paralleloptions maxdegreeofparallelism threadcount test byte byteargument 42 testbyteargument consolewritelinestringformatiteration 0 1 test byteargument additional information platform is x64 windows 7 c host application built for x86 in net 40 delphi dll compiled for 32bitthe library appears to be working ok when used in a multithreaded delphi host applicationan msvc version of the dll with the function signature extern declspecdllexport void stdcall testchar testbyte works fine with the c host which suggests this is somehow specific to delphithe code will not fail if the library function has no return value void and argumentschanging the calling convention in both code to cdecl did not helpany ideas would be much appreciated,"['c#', '.net']" +903431,jquery contains does not work on chrome i have one problem with jquery contains it work perfect on firefoxthis is my codeinputdataheightcmblurfunction var text thisval ifthisvallength 0 ifthisvalcontainscm thisvaltext cm on chrome it give error uncaught typeerror valcontains is not a functionhow can i fix it please helpthank you,"['javascript', 'jquery']" +903444,how do i assemble gas assembly and link it with the open watcom c library i am trying to produce 16bit dos executables but using the gcc compiler so i am using the ancient gcc43 ia16 port i made a docker image of my build heres what i am tryinghost mkdir resultshost docker run v pwdresultsresults it ysangkokia16gccraskcontainer cd resultsi do not include the header cause gcc cannot use openwatcoms libc headerscontainer echo main printflol testci do not link cause i do not have 16bit binutils available if i build an object file it is not correctly marked as 16bitcontainer trunkbuildia16masterprefixbinia16unknownelfgcc s testcnow i have this assembly file arch i8086jumps code16 att syntax prefixno app section rodatalc0 string lol text p2align 1 global main type main functionmain pushw bp movw sp bp subw 4 sp call main movw lc0 ax pushw ax call printf addw 2 sp movw bp sp popw bp ret size main main ident gcc gnu 430 20070829 experimentaloutside the container in the host i try to assemble it with yasm yasm m x86 p gas f elf o testo tests tests1 warning directive arch not recognizedtests3 error junk at end of line first unrecognized character is pi comment out the syntax line since yasm does not understand it and try again this time it succeedsi test the relocation symbols objdump r testotesto file format elf32i386relocation records for textoffset type value 07 r 386 pc16 main0a r 386 16 rodata0e r 386 pc16 printfsadly they are 32bit when i try and link anyway in the container it does not workroot1341f35c4590 cd owbinlroot1341f35c4590owbinl watcomow owbinlwlink open watcom linker version 19portions copyright c 19852002 sybase inc all rights reservedsource code is available under the sybase open watcom public licensesee for detailspress ctrld to finishwlinksystem doswlinkfile resultstesto comment i press controld on the next line wlinkloading object fileswarning w1080 file resultstesto is a 32bit object fileerror e2015 file resultstestotests bad relocation type specifiederror e2015 file resultstestotests bad relocation type specifiederror e2015 file resultstestotests bad relocation type specifiedif i try and make a coff instead of an elf yasm cannot even assembleroot1341f35c4590 cd owbinlroot1341f35c4590owbinl watcomow owbinlwlink open watcom linker version 19portions copyright c 19852002 sybase inc all rights reservedsource code is available under the sybase open watcom public licensesee for detailspress ctrld to finishwlinksystem doswlinkfile resultstestowlinkloading object fileswarning w1080 file resultstesto is a 32bit object fileerror e2015 file resultstestotests bad relocation type specifiederror e2015 file resultstestotests bad relocation type specifiederror e2015 file resultstestotests bad relocation type specifiedi know yasm does not support 16bit but maybe there is a workaround is there a gascompatible 16bit assembler the gastointel converters are not working,['c'] +903453,outputcache varybyparam is varying by parameter that is not supposed to be included i am using outputcache in mvc 5 to cache a view on the serveri only want to cache a view based on two parameters in the query stringaction methodhttpgetoutputcachelocation outputcachelocationserver duration 6010 varybyparam idquoteidpublic actionresult myactionint id productcategorytype category return contentdatetimenowtostringroutecontextmaproutemycustomroutemyareacontrolleractionidcategorynamequoteidnew controller mycontroller name urlparameteroptional quoteid urlparameteroptional new mynamespaceareasmyareacontrollers the urlhttplocalhost17191myareamycontrollermyaction21aholidayaquoteidthis works and binds the data correctly however if i change any part of the name part of the url it still generates a new cache item even though in my action method i have speficied varybyparamidquoteidfor examplehttplocalhost17191myareamycontrollermyaction21aholidaysomequoteidandhttplocalhost17191myareamycontrollermyaction21anotherholidaysomequoteidare generating different datetime outputs but they should not they should be identicalwhat have i done wrong and how can i achieve the desired behavioureditjust to be clear productcategorytype is an enum that is being bound via it is int value the binding for this is correct when i debug the actionresultedit 2since i have been asked to show productcategorytype i have added it below this does bind correctly when i debug though i do not think it has anything to do with the problempublic enum productcategorytype touractivity 1 accommodation 2 buspass 3 selfdrive 4edit 3changing the url tohttplocalhost17191aproductsview21nametest1quoteid123and the cache now works as expected but how can i achieve this with the prettier url via routing,['c#'] +903489,how are object dependencies between static blocks resolved i recently came across this at work while i am not sure it is really a good idea i do not understand how static blocks are handled by the compilerhere is an exampleconsider that you have classes a and bpublic class a public final static listinteger list static list new arraylist public class b public final static int dependsona static dependsona alistsize and a main class that just reads bdependsonathe static block in b is dependent of the one in a since it uses the list static variablenow the code executes properly and no nullpointerexception is raised at runtime but what is the mechanism that ensures that list is initialized before it is potentially used elsewhere,['java'] +903559,oracle text escaping with curly braces and wildcards i want to be able to escape the search criteria in an oracle text query using contains and combine the escaped criteria with wildcards to have doubly truncated criteria i know my indexes may not be setup for ideal performance but that is superfluous i want to be able to use the curly braces syntax for best readability but this does not work according to the top answer on this related but not duplicate question curly braces define complete tokens is there any way to thisable or work around this behavior oracle text how to sanitize user inputi would rather avoid having to escape every single character in my search criteria as per the last select in my code or try to search the string for special characters since reserved words are also considered special note that i have no stop words the following demonstrates my problem unfortunately sqlfiddle does not appear to support oracle textcreate table my tablemy col varchar220insert into my tablemy col values abcinsert into my tablemy col values abcdinsert into my tablemy col values abcdeinsert into my tablemy col values bcdinsert into my tablemy col values bcdecreate index ftix on my table my colindextype is ctxsyscontextparameters stoplist ctxsysempty stoplist sync on commitselect from my table where containsmy col bcd 0 expected resultsselect from my table where containsmy col bcd 0 no resultsselect from my table where containsmy col bcd 0 returns bcdselect from my table where containsmy col bcd 0 returns bcdselect from my table where containsmy col bcd 0 expected results,['sql'] +903635,why does stdshared ptr stdunique ptr compile while stdshared ptr stdunique ptr does not i explored this topic in coliru with the following input commandg stdc14 o2 wall pedantic pthread maincpp aoutthe test can be found here but i have posted the code below i used int in my example as it is a basic typeinclude iostreaminclude memorystruct foo foo a 0 b 1 c 1 combination 05 int a b c double combination int main int unmanagedarray new int16 stdunique ptrint uniquearrayorigin stdmake uniqueint16 stdshared ptrint works but needs call to new sharedsingletestunmanagedarray stddefault deleteint works does not require call to new sharedsingleunique stdmake uniqueint16 compilation error conversion to nonscalar type sharedsinglederived uniquearrayorigin stdshared ptrint compilation errors sharedarraytestunmanagedarray stddefault deleteint compilation error conversion to nonscalar type sharedarrayunique stdmake uniqueint16 compilation error conversion to nonscalar type sharedarrayderived uniquearrayorigin stdshared ptrfoo works specified overload of operator for shared ptr nonarraytest stdmake uniquefoo stdcout doneni have looked around on so for answers but only turned up references to the implementation of stdshared ptr not having a specialization and that this largely was because no one bothered to give a proper proposal to the standards committee on the subjecti am curious because i would interpret 4th overload of operator stdshared ptrtoperatorstdunique ptrt deleter on cppreference to indicate that such syntax is legal t and t are the same type regardless of the state of specializations for array types for stdshared ptr after all furthermore this syntax only appears to work on the product of stdmake uniquet and not a unique pointer object which goes against my understanding of the topicshould not the calls be effectively the same though one moves an existing object and the other well moves an object that is just been created i would expect the only difference between them would be the invalid stdunique ptrt after the function call in the first case as a side note i assume that since there is a way of constructing a dynamicallyallocated array into a shared ptr that does not require the use of new i should prefer it to the messier and exceptionunsafe call to new tntldroperator does not work at all between stdshared ptrt and stdunique ptrt though i would expect it to work whyif anything i would expect the type conversion from t to t to be a source of compilation errors between the unique and shared pointers why does this workoperator works between stdshared ptrt and stdmake uniquet but not stdunique ptrt whyam i correct to assume in cases which require a dynamically allocated shared array but where i do not want to use either boost or a vector reasons below i should call operator stdmake uniquetnwhy are not i usingboost is not approved for use yet in my company and i do not know when or if i will get approval to use itarrays i have to determine the size of this array at runtimevectors i am working on a realtime signal processing system and would prefer to avoid the extra pointer dereference i was also attempting to avoid including extraneous libraries in my header files this was for communications between reading and writing subsystems however i eventually chose to optimize this later if it matters premature optimization and bite the bullet the question remains though,['c++'] +903701,java game hitbox detection rounded corners i am working on a simple 2d game with java swing and no framework i have a rectangular player that the user can move around on the map are few obstacles which the player should not be able to go through i did this by making a new rectangle object for the player and each obstacle with their bounds but iam not really sure if this is the right way to do it it works but the movements of the player are not really user friendly if the player wants to pass two obstacles they must be on the perfect coordinates to passis it even a good idea to check for intersections between the player and the obstacle with a rectangle object or should i do it another waynow for my 2nd questioniad like to replace the rectangular hitboxes with the same hitbox but with rounded corners so the player could pass more easilythis is what the game looks like with hitboxes enabledthe code that checks if the player and the obstacles have yet intersectedfor player p thisgetplayerarray rectangle recplayer pplayerbounds for obstacle kiste obstaclearray rectangle reckiste kisteobstbounds if recplayerintersectsreckiste psetx100 not actual code here the function that returns the hitbox of the player obstaclepublic rectangle obstbounds return new rectanglethisgetx thisgety imagegetimagegetwidthnull imagegetimagegetheightnull,['java'] +903715,different result for ymmdd and ymmdd in javascript when passed to new date i was executing below statement under nodejs repl and i was getting two different result for same datevar datestr1 20150331var datestr2 20150331var date1 new datedatestr1gives tue mar 31 2015 0 gmt0530 istvar date2 new datedatestr2gives tue mar 31 2015 0530 gmt0530 istin the 1st one hourminseconds are all zeros while in the 2nd one by default hourmin is getting set to as a timezone hourmin which is 530,['javascript'] +903727,assembledebug not working with gradle24 in android studio i recently updated gradlewrapperproperties file to use gradle24here is my new updated gradlewrapperproperties filesun dec 21 212827 gmt0530 2014thistributionbasegradle user homethistributionpathwrapperthistszipstorebasegradle user homezipstorepathwrapperthiststhistributionurlafter this update i ran the clean command so that it used 24 and 221 the older versionnow if i use gradlew assembledebug command in android studio it throws the following error failure build failed with an exception what went wrongexecution failed for task activeandroidcompiledebugtestaidl executor singleton not started tryrun with stacktrace option to get the stack trace run with info or debug option to get more log outputbut if i run the same command on command line it worksany idea what could be wrong,['android'] +903737,how to make n equal to n why is not b equal to true if you run this code on windowssystemsetpropertylineseparator nstring sstringformatnboolean bnequalssi want s to be n and not rn even on windows,['java'] +903744,what is the recommendedcorrect way to access fields in an inner class suppose we have this class and its inner class outerjava public class outer private static class inner private final object foo public innerobject foo thisfoo foo public object getfoo return foo inner inner parse somemistery question to access foo which is recommended object bar innergetfoo object baz innerfooi am surprised that innerfoo works since foo is private it can be accessed only through getfoo right,['java'] +903785,how to include a proguard configuration in my android library aar android libraries per the aar file speca includes a proguardtxt file my understanding is that this file declares how the library correctly can be obfuscated and minified in my case i need to preserve some apiclasseshow can i declare the librarys proguardtxt file in the librarys buildgradle and will this file be automatically read when creating an application apk that uses my libraryi did not find this information in androids gradle plugin user guide,['android'] +903803,objectivec issues with uiwebview to pdf i have this method here that takes my uiwebview and convert into a pdf and its working well but when i print off this pdf or email it its cut off its like its only generating what the size of the uiwebview that i set which is width 688 height 577 if i increase the size of the uiwebview to lets say 900 or 1024 my pdf is empty my uiwebview is bigger than 577 but in my app i am able to scrollhere is methodvoidwebviewdidfinishloaduiwebview webviewpdf cgrect origframe webviewpdfframe nsstring heightstr webviewpdf stringbyevaluatingjavascriptfromstringdocumentbodyscrollheight get the height of our webview int height heightstr intvalue cgfloat maxheight kdefaultpageheight 2kmargin int pages floorheight maxheight nsarray paths nssearchpathfordirectoriesindomainsnsdocumentdirectory nsuserdomainmask yes nsstring path paths objectatindex0 selfpdfpath path stringbyappendingpathcomponentnsstring stringwithformatpurchase orderpdf uigraphicsbeginpdfcontexttofileselfpdfpath cgrectzero nil for int i 0 i pages i if maxheight i1 height cgrect f webviewpdf frame fsizeheight i1 maxheight height webviewpdf setframe f uigraphicsbeginpdfpagewithinfocgrectmake0 0 kdefaultpagewidth kdefaultpageheight nil cgcontextref currentcontext uigraphicsgetcurrentcontext cgcontexttranslatectmcurrentcontext kmargin kmargin webviewpdflayer renderincontextcurrentcontext uigraphicsendpdfcontext webviewpdf setframeorigframe webviewpdf subviews lastobject setcontentoffsetcgpointmake0 0 animatednoi hope this makes sensedoes anyone have any suggestions on how to fix this so the pdf is not cut offi forgot to mention these variablesdefine kdefaultpageheight 850define kdefaultpagewidth 850define kmargin 50here is my share button ibactionshareidsender nsdata pdfdata nsdata datawithcontentsoffileselfpdfpath uiactivityviewcontroller activitycontroller uiactivityviewcontroller alloc initwithactivityitemspdfdata applicationactivitiesnil uipopovercontroller popup uipopovercontroller alloc initwithcontentviewcontrolleractivitycontroller popup presentpopoverfromrectcgrectmakeselfviewframesizewidth 36 60 0 0inviewselfview permittedarrowdirectionsuipopoverarrowdirectionup animatedyes,"['ios', 'objective-c']" +903975,why i am getting this line in green colour in timeline activity idle id androidosbinderproxy41d2b6d8 time1933928 since i have updated my phone version from 43 to 4 it started showing this line and it annoying me very muchtimeline activity idle id androidosbinderproxy41d2b6d8 time1933928please help how to solve his problem and why i am getting this error,['android'] +904015,new keyword and method hiding the new keyword is used to hide the base class implementation of the same but i am not sure why the following code produces the output as baseclassclass baseclass public void fun consolewritebase class class derived1 baseclass new void fun consolewritederived1 class class derived2 derived1 new void fun consolewritederived2 class class program public static void mainstring args derived2 d new derived2 dfun we are hiding the implementation of fun in derived2 but still base class is called why so am i missing something,['c#'] +904029,xmpp ios framework detect internet thisconnection issue with openfire server i have implemented chatting application using xmpp ios framework with openfire serverfortunately application is running successfully but i am facing one issue of internet thisconnection in applicationwhen user is getting logout or went in offline mode manually then it sends stanza to hisher rosters so hisher rosters knows that user went in offline modenow when internet will thisconnect from users device at that time application is not able to send presence stanza to server due to internet thisconnection so hisher rosters would not get information about that offline user and user will be shown in online mode onlyi thought something like openfire server might be able to check connected users and whenever any user gets thisconnected it should send presence stanza with offline status to his rosters so they can know that this user is on offline modecan anybody please help me if there is any way through which i can implement this featureit will be very helpful for me to solve this issuethanks in advance,['ios'] +904081,mongrel rails programatically report which port it is running on on my local machine i run rails with mongrel i have some stuff which runs when it starts via a file in configinitializers which uses puts to tell me which database it is using what is being used to send emails and a few other bits of infowhen i run a cluster of mongrels on ports 30 3001 and 3002 i only want to do this reporting stuff for the mongrel on port 30 so i need to wrap it in an if block which tests which port the currently running mongrel is using can anyone tell me how i can get this in my code,['ruby-on-rails'] +904138,laravel middleware return variable to controller i feel i might be off base with this excuse me if i am essentially i am carrying out a permissions check on a user to determine whether they can view a page or not this involves passing the request through some middleware firstthe problem i have is i am duplicating the same database query in the middleware and in the controller before returning the data to the view itself here is an example of the setup routesphproutegetpagesid as pages middleware pageuser uses pagescontrollerview pageusermiddlewarephp class pageusermiddlewarepublic function handlerequest closure next get the page pageid requestrouteid find the page with users page pagewithuserswhereid pageidfirst check if the logged in user exists for the page ifpageuserswherepivotuser id authuseridexists redirect them if they do not exist return redirectrouteredirectroute return nextrequest pagescontrollerphppublic function viewid page pagewithuserswhereid idfirst return viewpagesview page pageas you can see the pagewithuserswhereid idfirst is repeated in both the middleware and controller i need to pass the data through from one to the other so an not to duplicate hope this is clear enough of my end goal and i appreciate the help,['php'] +904230,calling base and derived static methods of a type variable i have the following exampleclass ideone public static void main string args throws javalangexception aconcreteerrorhandler a new aconcreteerrorhandler am exception here public static class abstracterrorhandler public static void handle throw new unsupportedoperationexceptionnot implemented public static class concreteerrorhandler extends abstracterrorhandler public static void handle systemoutprintlnconcrete handler public static class at extends abstracterrorhandler public void m thandle ideonewhy the method of the base class is called but not of the derived the signatures of the handle methods are perfectly the same i know that static methods do not inherit but should not a compiletime error be thrown in my case thencould someone explain that behavior,['java'] +904247,django save behavior with autocommit transactions i have a following setupseveral data processing workers get configuration from django view get conf by http configuration is stored in django model using mysql innodb backendconfiguration model has overridden save method which tells workers to reload configurationi have noticed that sometimes the workers do not receive the changed configuration correctly in particular when the conf reload time was shorter than usual the workers got old configuration from get conf missing the most recent change the transaction model used in django is the default autocommiti have come up with the following possible scenario that could cause the behaviornew configuration is savedsave returns but mysql innodb is still processing the autocommitworkers are booted and make http request for new configurationmysql autocommit finishesis the step 2 in the above scenario possible that is can django model save return before the data is actually committed in the db if the autocommit transactional method is being used or to go one layer down can mysql autocommitting insert or update operation finish before the commit is complete update insert visible to other transactions,['mysql'] +904252,css lint ignore all ie6 and ie7 based errors i am using sublime text 3 and css linter in my settings i have put the ignore rule and currently there is only the outlinenone rule i would like to include all the rules which refer to ie6 and ie7 based errors is there a list what are the ie6 and ie7 rules so that i can put them in the ignore array my csslintsublimesettings look like this csslint rules you wish to ignore must be an array leave blank to include all default rules ignore outlinenone,['css'] +904254,why is faster than list i recently compared the processing speeds of and list and was surprised to thiscover that runs more than three times faster than list i ran the same test with and dict and the results were practically identical and both took around 0128sec million cycles while list and dict took roughly 0428sec million cycles eachwhy is this do and probably and too immediately pass back a copies of some empty stock literal while their explicitlynamed counterparts list dict tuple str fully go about creating an object whether or not they actually have elementsi have no idea how these two methods differ but i would love to find outi could not find an answer in the docs or on so and searching for empty brackets turned out to be more complicated than i would expectedi got my timing results by calling timeittimeit and timeittimeitlist and timeittimeit and timeittimeitdict to compare lists and dictionaries respectively i am running python 279i recently thiscovered why is if true slower than if 1 that compares the performance of if true to if 1 and seems to touch on a similar literalversusglobal scenario perhaps it is worth considering as well,['python'] +904261,how a uitabbarcontroller fit into the viper architecture i am writing an application which has a tabbar based navigation i am adopting the viper architecture but i am really confused with the topic of how a uitabbarcontrollers tab changing should be implemented,['ios'] +904281,error calling stored procedures from entityframework i am trying to access a store procedure from entityframeworki have followed these stepsfirst of all i have created the stored procedure in the azure databasethen i have updated the edmx model from database selecting only the storedprocedure i wantonce done in the function import i see the storedprocedure added but not in the section of storedprocedureswhat can i do so that it appears herein the function import section all the parameters are set as input whereas maxreference should be marked as outputhow can i change italthough these two issues i have executed the codeand i got the following exceptionentitycommandcompilationexceptionan error occurred while preparing command definition see the inner exception for detailsand the innerexceptionthe function import datamodelentitiesassignmaxsalesref cannot be executed because it is not assigned to a storage function,['c#'] +904300,is there a way to find out which file used require once let us say i have the following situationfile1phpphprequire onceinitphpfile2phpphprequire onceinitphpinitphpphpmagic function which tells me which file parsed this filei know this is a longshot but is there a way to know from within initphp which file included initphp it in the current execution,['php'] +904411,difference between new hashmapint and guava mapsnewhashmapwithexpectedsizeint in java you can create a new hashmap to hold a specific number of items like somap m new hashmap100guava provides a mapsnewhashmapwithexpectedsizeint method which i would expect to simply call hashmapint but it does not do this instead it calculates its own capacity and uses thatwhy does newhashmapwithexpectedsize do its own thing and why would i want to use it over calling new hashmapint directly,['java'] +904448,thisable scrolling in child recyclerview android i have a layout consists of a parent recyclerview with a sub recyclerview in iti know that it is not good to put a list inside another list but i have to so that i can use the sub list features like swiping and drag and drop my issue is that the child recyclerview gain focus and stops the parent from scrolling if the touch point was on it simply i want if the touch was vertically on the child recyclerviewthe parent scrolls up and down and if the touch was horizontal or a click then the child recyclerview list item swipes left and right any help to achieve this,['android'] +904570,strange assignment textview to bundle after decompiling why i created a simple application a counter app that upon pressing a button increments a integer by one and updates a textview the code can be seen belowpublic class mainactivity extends activity public static int count 0 override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main final textview textview textview findviewbyidridcount textviewsettextintegertostringcount final button button button findviewbyidridbutton buttonsetonclicklistenernew viewonclicklistener override public void onclickview v count textviewsettextintegertostringcount after decompiling the same app with dex2jar and jdgui i received the following code backpublic class mainactivity extends activity public static int count 0 protected void oncreatefinal bundle parambundle superoncreateparambundle setcontentview2130903040 parambundle textviewfindviewbyid2131296257 parambundlesettextintegertostringcount buttonfindviewbyid2131296256setonclicklistenernew viewonclicklistener public void onclickview paramanonymousview mainactivitycount 1 parambundlesettextintegertostringmainactivitycount on the following line parambundle textviewfindviewbyid2131296257 parambundlesettextintegertostringcounthow is it possible for the system to set the textview to the parambundle and why is this happening parambundle is of type bundle and textview is not a subclass of bundle further more bundle is final according to the decompiled version did something go wrong upon decompiling is the information from the decompiler wrong or why do we get this resultedit virtual methodsmethod protected oncreatelandroidosbundlev locals 3 param p1 savedinstancestate landroidosbundle prologue line 17 invokesuper p0 p1 landroidappactivityoncreatelandroidosbundlev line 18 consthigh16 v2 0x7f030 invokevirtual p0 v2 lcomexamplerawahelloworldmainactivitysetcontentviewiv line 20 const v2 0x7f0901 invokevirtual p0 v2 lcomexamplerawahelloworldmainactivityfindviewbyidilandroidviewview moveresultobject v1 checkcast v1 landroidwidgettextview line 21 local v1 textviewlandroidwidgettextview sget v2 lcomexamplerawahelloworldmainactivitycounti invokestatic v2 ljavalangintegertostringiljavalangstring moveresultobject v2 invokevirtual v1 v2 landroidwidgettextviewsettextljavalangcharsequencev line 22 consthigh16 v2 0x7f090 invokevirtual p0 v2 lcomexamplerawahelloworldmainactivityfindviewbyidilandroidviewview moveresultobject v0 checkcast v0 landroidwidgetbutton line 23 local v0 buttonlandroidwidgetbutton newinstance v2 lcomexamplerawahelloworldmainactivity1 invokedirect v2 p0 v1 lcomexamplerawahelloworldmainactivity1initlcomexamplerawahelloworldmainactivitylandroidwidgettextviewv invokevirtual v0 v2 landroidwidgetbuttonsetonclicklistenerlandroidviewviewonclicklistenerv line 30 returnvoidend methodi am definitely no smali expert only a novice but i decoded the application using apktool as well and received the smali code above from my understanding the savedinstance parambundle is loaded in to p1v3 and used in oncreate and it is not used in any way in line 20 or 21 to me this point towards a decompling error keep in mind that apktool allows for building the application again and thus no data may be lost when decompiling,"['java', 'android']" +904576,android image picker select multiple images from gallery with a maximum limit of 5 i have an app where the user needs to be able to choose multiple pictures to send them somewhere however they can only send five images at a time i need to be able to limit the number of images that they can pick from the gallery through the image picker to put it in a single sentence i want to limit the number of imagesphotos that the user can select in the default image selector from the galleryhere is the code that i am using for my image pickerintent chooseintent new intentintentaction pick mediastoreimagesmediaexternal content urichooseintentputextraintentextra allow multiple truestartactivityforresultchooseintent 2it already keeps track of how many images are selected at the top by defaultis there a way to set a maximum limit like to have a user only be able to select up to 5 images,['android'] +904577,realm swift 0923 run script phase not working trying to use the new realmswift0923 i cannot get this arun script phasea to work i follow the instructions from heremy runscript entry according to the the instructions is see image belowunfortunately i still get the following error message while trying to compile see below what could still be wrong bash usersxlibrarydeveloperxcodederiveddatamyappglnkfueqyjbdhurfurfkipbuildproductsdebugiphonesimulatormyappappframeworksrealmswiftframeworkstripframeworkssh no such file or directorymy frameworksearchpaths is also set as followsusersxmyappframeworksrealmswiftframeworkframeworksi appreciate any help on this,['ios'] +904711,django custom command error unrecognized arguments i am trying to create a command similar to createsuperuser which will take two arguments username and passwordits working fine in django 17 but not in 18 i am also using python34this is the code i wrotemyappmanagementcommandscreatemysuperuserpyfrom djangocoremanagementbase import basecommand commanderrorfrom djangocontribauthmodels import userclass commandbasecommand help create a super user def handleself args options if lenargs 2 raise commanderrorneed exactly two arguments for username and password username password args u created userobjectsget or createusernameusername if created uis superuser true uis staff true uset passwordpassword usave else raise commanderroruser s already exist username return password changed successfully for user s uusernameand when i try to run this command python managepy createmysuperuser myuser mypasswordi get this errorusage managepy createmysuperuser h version v 0123 settings settings pythonpath pythonpath traceback nocolormanagepy createmysuperuser error unrecognized arguments myuser mypasswordbut when i dont pass any arguments it raises commanderror which is expectedcommanderror need exactly two arguments for username and password,['python'] +904733,how to update the list whenever the tabs are changing in view pager in my app i am using navigation tab using view pager i have able to successfully drawn the tabs using the code posted on guideswikislidingtabswithpagerslidingtabstriphere i have used the sliding tab and view pager both to get the navigation tabseverything is working fine but the list are not getting updated when i am moving to the other tab onresume is getting called even the object list variable is also getting updated while debugging but visually list is not getting updated here i am some snippets of the codefor tab1 which in my case is active tab override public void onresume superonresume ifinternetutilisconnectedtointernetgetactivity mswiperefreshlayoutsetenabledfalse else mswiperefreshlayoutsetenabledtrue new getusersfromservertaskexecute here i am making the network calls on tab2 which is archive tab override public void onresume superonresume new getusersarchivedfromservertaskexecute network calls in mainactivitypublic class materialtab extends fragmentactivity override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutmaterial main sample viewpager viewpager viewpager findviewbyidridviewpager viewpagersetadapternew samplefragmentpageradaptergetsupportfragmentmanager pagerslidingtabstrip tabsstrip pagerslidingtabstrip findviewbyidridtabs tabsstripsetviewpagerviewpager tabsstripsetonpagechangelistenernew viewpagersimpleonpagechangelistener override public void onpageselectedint position ifposition 0 activefragment activefragment new activefragment final fragmenttransaction ft getsupportfragmentmanagerbegintransaction ftdetachactivefragment ftattachactivefragment ftcommit ifposition 1 archivefragment archivefragment new archivefragment final fragmenttransaction ft getsupportfragmentmanagerbegintransaction ftdetacharchivefragment ftattacharchivefragment ftcommit also the thing is when i am doing swiperefresh then the list is getting updated i am now totally confused why this behaviour when i am swiping the tab the same methods are getting called and thelist is not getting updated but when i am doing swiperefresh it is getting updatedthis is the active fragmentpublic class activefragment extends fragment public void updatefragment new getusersarchivedfromservertaskexecute public class getusersarchivedfromservertask extends asynctaskuser void string override protected string doinbackgroundshipment parmas logdtag stringvalueofshipmentdbhandlergetallactiveshipmentssize userlist1 userdbhandlergetallactiveuserbytodaydatetimeutilgetcurrenttime return override protected void onpreexecute superonpreexecute override protected void onpostexecutestring str set the refresh listener to false after the list has been loaded with new set of data if mswiperefreshlayoutisrefreshing mswiperefreshlayoutsetrefreshingfalse if userlist1size 0 viewgroup parentone viewgroup viewonegetparent ifparentone null parentoneremoveviewviewone if shipmentlist1size 0 mshipmentadapter new shipmentadaptergetactivity userlist11 shipmentlistview1setadaptermshipmentadapter setlistviewheightbasedonchildrenshipmentlistview1 viewgroup parentone viewgroup viewonegetparent ifparentone null mainlayoutoneaddviewviewone mshipmentadapternotifydatasetchanged mswiperefreshlayoutsetclickabletrue,['android'] +905198,google play url messes up facebooks share dialog i am trying to share an image with title and description on facebook but it looks like when i set a google play url as the contenturl then the title and description are not thisplayedthis is my codeif sharedialogcanshowsharelinkcontentclass sharelinkcontent linkcontent new sharelinkcontentbuilder setcontenttitlei want this car setcontenturluriparse setimageurluriparseoptionaljpg build sharedialogshowlinkcontentthe resultbut when i set a google play url as contenturlif sharedialogcanshowsharelinkcontentclass sharelinkcontent linkcontent new sharelinkcontentbuilder setcontenttitlei want this car setcontentdescriptionthis description should be thisplayed below the image but somehow it depends on the link setcontenturluriparse setimageurluriparseoptionaljpg build sharedialogshowlinkcontentthe resulti tried this with other general and google play links and i always got the same resultwhats wrongediti submitted this question to the facebook team and even though they admitted that this is a bug i was told that they would not fix it any time soon,['android'] +905209,how to merge two geometries or meshes using threejs r71 here i bumped to the problem since i need to merge two geometries or meshes to one using the earlier versions of threejs there was a nice functionthreegeometryutilsmergependulum ballhowever it is not on the new version anymorei tried to merge pendulum and ball with the following codeball is a meshvar ballgeo new threespheregeometry243535var ballmat new threemeshphongmaterialcolor 0xf7fe2e var ball new threemeshballgeo ballmat ballpositionset0var pendulum new threecylindergeometry1 1 20 16ballupdatematrixpendulummergeballgeometry ballmatrixsceneaddpendulumafter all i got the following errorthreeobject3dadd object not an instance of threeobject3d threecylindergeometry uuid 688b0eb170f74c5186db5b1b90a8a24c name type cylindergeometry vertices array1332 colors array0athrerror three r71js35threeobject3dadd three r71js70anonymous function pendulumjs20,['javascript'] +905210,bitshifting on littleendian and bigendian will this0x10203040 24 0xff 0x10always be true on both littleendian and bigendian machines,['c++'] +905292,kefirjs how to stream events from a callback function the mousetrapjs library lets you bind a callback function to keys like somousetrapbindspace function keydownwhats the best way to attach a stream to this without using the bus of doom should i use emitter or pooli am trying to get arrow keys hooked up in this fiddle jsfiddlenetvzafq25w,['javascript'] +905320,how do i use devise and activeadmin for the same user model i have activeadmin and devise working with users i would like to use devise to log in regular nonadmin users with the same user model how can i do this i want to have an admin flag in the user model for only admins i tried adding the 2nd line to routesrbdevise for users activeadmindeviseconfigdevise for usersbut it gave an error when i tried to list the routesrake routesdl is deprecated please use fiddlerake abortedargumenterror invalid route name already in use new user sessionyou may have defined two routes with the same name using the as option or you may be overriding a route already defined by a resource with the same naming for the latter you can restrict the routes created with resources as explained herei have created an authorization adapter which just checks useradmin true and that is working ok for activeadmin,['ruby-on-rails'] +905358,sql query in proc fails with error02115 i am getting some weird behavior of proc procedure as shown belowdefine bghcpy to oradest source voidstrcpyvoiddestarr voidsource destlen strlenconst char destarr define bghcpy from oradest source voidmemcpyvoiddest voidsourcearr size tsourcelen destsourcelen 0 long fnsqlmarkprocessed char pszrowid char pszmarker bghcpy to ora o rowid stack pszrowid bghcpy to ora o cust processed pszmarker exec sql update document all set processed by bgh o cust processed where rowid o rowid stack return sqlcasqlcodethe input arguments values passed to above function is pszrowid af1laaiaabooraab pszmarkerxthe query return the error code02115 with following messagesql error02115 code interpretation problem check common name usagei am using oracle as the backend databasecan anyone provide me information on what are the possible causes for this failed queryany help is highly appreciatedflags used during proc compilation is defined belowu01apporacleproduct816oracle homebinproc echo dbscs5 dsun5 iexporthomebscsobwbscs6srccoredumpissuefinal code fix 004641 dndebug dsunos53 d posix 4sources iusrgenericgeneric25364 bitinclude dfeature 212298 dbscs config iexporthomebscsobwbscs6srcbatinclude dfeature 00203808 gmd dfeature 00241737 doracle db brand iu01apporacleproduct816oracle homerdbmsdemo iu01apporacleproduct816oracle homeprecomppublic iexporthomebscsobwbscs6srccoredumpissuefinal code fix 004641include ibatinclude dfeature61717 dfeature52824 dfeature56178 dd236312 d dsdp g sed e siincludeg e sd g e sd define1g select errorno definefeature61717 definefeature52824 definefeature56178 linesyes inamebgh esqlpc onamebgh esqlc lnamebgh esqllis,"['sql', 'c']" +905428,getting error in jpa query with springboot from the server log i am getting the below error oswsmmahttpentitymethodprocessor written timestampfri may 15 013947 edt 2015 status500 errorinternal server error exceptionorgspringframeworktransactiontransactionsystemexception messagecould not roll back jpa transaction nested exception is javaxpersistencepersistenceexception unexpected error when rollbacking pathapiact as applicationjsoncharsetutf8 using orgspringframeworkhttpconverterjsonmappingjackson2httpmessageconverter6dc2f5d0edit at commysqljdbcutilhandlenewinstanceutiljava377 at commysqljdbcsqlerrorcreatecommunicationsexceptionsqlerrorjava1036 at commysqljdbcmysqliosendmysqliojava3661 at commysqljdbcmysqliosendcommandmysqliojava2417 at commysqljdbcmysqliosqlquerydirectmysqliojava2582 at commysqljdbcconnectionimplexecsqlconnectionimpljava2526 at commysqljdbcconnectionimplsetautocommitconnectionimpljava4846 at sunreflectgeneratedmethodaccessor45invokeunknown source at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43 at javalangreflectmethodinvokemethodjava497 at orgapachetomcatjdbcpoolproxyconnectioninvokeproxyconnectionjava126 at orgapachetomcatjdbcpooljdbcinterceptorinvokejdbcinterceptorjava108 at orgapachetomcatjdbcpoolthisposableconnectionfacadeinvokethisposableconnectionfacadejava81 at comsunproxyproxy60setautocommitunknown source at orghibernateenginetransactioninternaljdbcjdbctransactiondobeginjdbctransactionjava72 at orghibernateenginetransactionspiabstracttransactionimplbeginabstracttransactionimpljava162 at orghibernateinternalsessionimplbegintransactionsessionimpljava1435 at orghibernatejpainternaltransactionimplbegintransactionimpljava61 at orgspringframeworkormjpavendorhibernatejpadialectbegintransactionhibernatejpadialectjava159 at orgspringframeworkormjpajpatransactionmanagerdobeginjpatransactionmanagerjava380 at orgspringframeworktransactionsupportabstractplatformtransactionmanagergettransactionabstractplatformtransactionmanagerjava373 at orgspringframeworktransactioninterceptortransactionaspectsupportcreatetransactionifnecessarytransactionaspectsupportjava439 at orgspringframeworktransactioninterceptortransactionaspectsupportinvokewithintransactiontransactionaspectsupportjava262 51 common frames omittedcaused by javanetsocketexception broken pipe at javanetsocketoutputstreamsocketwrite0native method at javanetsocketoutputstreamsocketwritesocketoutputstreamjava109 at javanetsocketoutputstreamwritesocketoutputstreamjava153 at javaiobufferedoutputstreamflushbufferbufferedoutputstreamjava82 at javaiobufferedoutputstreamflushbufferedoutputstreamjava140 at commysqljdbcmysqliosendmysqliojava3643 71 common frames omitted20150516 050211546 error nio8080exec6 oacthispatcherservlet servletservice for servlet thispatcherservlet in context with path threw exception request processing failed nested exception is orgspringframeworktransactiontransactionsystemexception could not roll back jpa transaction nested exception is javaxpersistencepersistenceexception unexpected error when rollbacking with root causejavanetsocketexception broken pipe at javanetsocketoutputstreamsocketwrite0native method at javanetsocketoutputstreamsocketwritesocketoutputstreamjava109 at javanetsocketoutputstreamwritesocketoutputstreamjava153 at javaiobufferedoutputstreamflushbufferbufferedoutputstreamjava82 at javaiobufferedoutputstreamflushbufferedoutputstreamjava140 at commysqljdbcmysqliosendmysqliojava3643 at commysqljdbcmysqliosendcommandmysqliojava2417 at commysqljdbcmysqliosqlquerydirectmysqliojava2582 at commysqljdbcconnectionimplexecsqlconnectionimpljava2526 at commysqljdbcconnectionimplsetautocommitconnectionimpljava4846 at sunreflectgeneratedmethodaccessor45invokeunknown source at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43 at javalangreflectmethodinvokemethodjava497 at orgapachetomcatjdbcpoolproxyconnectioninvokeproxyconnectionjava126 at orgapachetomcatjdbcpooljdbcinterceptorinvokejdbcinterceptorjava108 at orgapachetomcatjdbcpoolthisposableconnectionfacadeinvokethisposableconnectionfacadejava81 at comsunproxyproxy60setautocommitunknown source at orghibernateenginetransactioninternaljdbcjdbctransactiondobeginjdbctransactionjava72 at orghibernateenginetransactionspiabstracttransactionimplbeginabstracttransactionimpljava162 at orghibernateinternalsessionimplbegintransactionsessionimpljava1435 at orghibernatejpainternaltransactionimplbegintransactionimpljava61 at orgspringframeworkormjpavendorhibernatejpadialectbegintransactionhibernatejpadialectjava159 at orgspringframeworkormjpajpatransactionmanagerdobeginjpatransactionmanagerjava380 at orgspringframeworktransactionsupportabstractplatformtransactionmanagergettransactionabstractplatformtransactionmanagerjava373 at orgspringframeworktransactioninterceptortransactionaspectsupportcreatetransactionifnecessarytransactionaspectsupportjava439 at orgspringframeworktransactioninterceptortransactionaspectsupportinvokewithintransactiontransactionaspectsupportjava262 at orgspringframeworktransactioninterceptortransactioninterceptorinvoketransactioninterceptorjava96 at orgspringframeworkaopframeworkreflectivemethodinvocationproceedreflectivemethodinvocationjava179 at orgspringframeworkaopframeworkjdkdynamicaopproxyinvokejdkdynamicaopproxyjava207 at comsunproxyproxy83findbyuseridunknown source at comaerodsocialapiscontrolleruseractivitycontollercreateordeletefeeduseractivitycontollerjava52 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava62 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43 at javalangreflectmethodinvokemethodjava497 at orgspringframeworkwebmethodsupportinvocablehandlermethoddoinvokeinvocablehandlermethodjava221 at orgspringframeworkwebmethodsupportinvocablehandlermethodinvokeforrequestinvocablehandlermethodjava137 at orgspringframeworkwebservletmvcmethodannotationservletinvocablehandlermethodinvokeandhandleservletinvocablehandlermethodjava110 at orgspringframeworkwebservletmvcmethodannotationrequestmappinghandleradapterinvokehandlemethodrequestmappinghandleradapterjava7 at orgspringframeworkwebservletmvcmethodannotationrequestmappinghandleradapterhandleinternalrequestmappinghandleradapterjava706 at orgspringframeworkwebservletmvcmethodabstracthandlermethodadapterhandleabstracthandlermethodadapterjava85 at orgspringframeworkwebservletthispatcherservletdothispatchthispatcherservletjava943 at orgspringframeworkwebservletthispatcherservletdoservicethispatcherservletjava877 at orgspringframeworkwebservletframeworkservletprocessrequestframeworkservletjava966 at orgspringframeworkwebservletframeworkservletdopostframeworkservletjava868 at javaxservlethttphttpservletservicehttpservletjava644 at orgspringframeworkwebservletframeworkservletserviceframeworkservletjava842 at javaxservlethttphttpservletservicehttpservletjava725 at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava291 at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava206 at orgspringframeworkwebfilterhiddenhttpmethodfilterdofilterinternalhiddenhttpmethodfilterjava77 at orgspringframeworkwebfilteronceperrequestfilterdofilteronceperrequestfilterjava107 at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava239 at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava206 at orgspringframeworkwebfiltercharacterencodingfilterdofilterinternalcharacterencodingfilterjava88 at orgspringframeworkwebfilteronceperrequestfilterdofilteronceperrequestfilterjava107 at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava239 at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava206 at comaerodsocialapisservicecorsfilterdofiltercorsfilterjava22 at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava239 at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava206 at orgapachecatalinacorestandardwrappervalveinvokestandardwrappervalvejava219 at orgapachecatalinacorestandardcontextvalveinvokestandardcontextvalvejava106 at orgapachecatalinaauthenticatorauthenticatorbaseinvokeauthenticatorbasejava501 at orgapachecatalinacorestandardhostvalveinvokestandardhostvalvejava142 at orgapachecatalinavalveserrorreportvalveinvokeerrorreportvalvejava79 at orgapachecatalinacorestandardenginevalveinvokestandardenginevalvejava88 at orgapachecatalinaconnectorcoyoteadapterservicecoyoteadapterjava537 at orgapachecoyotehttp11abstracthttp11processorprocessabstracthttp11processorjava1085 at orgapachecoyoteabstractprotocolabstractconnectionhandlerprocessabstractprotocoljava658 at orgapachecoyotehttp11http11nioprotocolhttp11connectionhandlerprocesshttp11nioprotocoljava2 at orgapachetomcatutilnetnioendpointsocketprocessordorunnioendpointjava1556 at orgapachetomcatutilnetnioendpointsocketprocessorrunnioendpointjava1513 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava1142 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava617 at orgapachetomcatutilthreadstaskthreadwrappingrunnableruntaskthreadjava61 at javalangthreadrunthreadjava745and when i am calling the api i am getting response liketimestamp 1431668344518status 500error internal server errorexception orgspringframeworktransactioncannotcreatetransactionexceptionmessage could not open jpa entitymanager for transaction nested exception is javaxpersistencepersistenceexception orghibernatetransactionexception jdbc begin transaction failed path apiacthere is my applicationproperty datasource settings set here configurations for the database connectionspringdatasourceurl jdbcmysqllocalhost3306apispringdatasourceusername rootspringdatasourcepassword rootspringdatasourcedriverclassname commysqljdbcdriver specify the dbmsspringjpadatabase mysql show or not log for each sql queryspringjpashowsql true hibernate settings are prefixed with springjpahibernatespringjpahibernateddlauto updatespringjpahibernatedialect orghibernatedialectmysql5dialectspringjpahibernatenaming strategy orghibernatecfgimprovednamingstrategyhere is my application claspringbootapplicationpublic class application public static void mainstring args springapplicationrunapplicationclass args bean public application websecurityconfigureradapter return new application bean public filter characterencodingfilter characterencodingfilter characterencodingfilter new characterencodingfilter characterencodingfiltersetencodingutf8 characterencodingfiltersetforceencodingtrue return characterencodingfilter edithere is my controller code requestmappingvalue method requestmethodpost responsebody public string createuser requestbody user user userdaosaveuser return done here is my daotransactionalpublic interface userdao extends crudrepositoryuser long can anyone tell me what is the actual problem and how to solve thisif more information needed feel free to ask,"['java', 'mysql']" +905432,is it possible to generate an inner class of a class to compile with an annotation processor i am wondering if it would be possible to generate a class via an annotation processor that would be an inner class of a class to be compiledfor instance while compiling class a generate class afoo i wonder if there is a trick that could be used or not i got the feeling that it might be possible to generate some source that will be compiled in the same byte code as an inner class would and at compileruntime the jvm would take it for an inner class and allow accessing outer class private fieldsthe idea behind that question which is not a noobie question though it may look more or less technical is to be able to use the private visibility modifier for annotated fields like dagger butterknife etc the private modifier allowing to detect unused fields more easily whereas package private protection hides themor is there any workaround any way to get the best of both words,"['java', 'android']" +905437,what does attempting to upgrade input file specified using deprecated transformation parameters mean i am currently trying to train my first net with caffe i get the following outputcaffe train solverfirst net solverprototxti0515 0901065710 15331 caffecpp117 use cpui0515 090106578014 15331 caffecpp121 starting optimizationi0515 090106578097 15331 solvercpp32 initializing solver from parameters test iter 1test interval 1base lr 001thisplay 1max iter 2lr policy invgamma 01power 075momentum 09weight decay 0snapshot 1snapshot prefix first netsolver mode cpunet first netprototxti0515 090106578203 15331 solvercpp70 creating training net from net file first netprototxte0515 090106578348 15331 upgrade protocpp609 attempting to upgrade input file specified using deprecated transformation parameters first netprototxti0515 090106578533 15331 upgrade protocpp612 successfully upgraded file specified using deprecated data transformation parameterse0515 090106578549 15331 upgrade protocpp614 note that future caffe releases will only support transform param messages for transformation fieldse0515 090106578574 15331 upgrade protocpp618 attempting to upgrade input file specified using deprecated v1layerparameter first netprototxti0515 090106578635 15331 upgrade protocpp626 successfully upgraded file specified using deprecated v1layerparameteri0515 090106578729 15331 netcpp42 initializing net from parameters name first netinput datainput dim 1input dim 5input dim 41input dim 41state phase trainlayer name data type imagedata top data2 top dataidx transform param mirror false crop size 41 image data param source homemoosegithubfirstnetdataimagestxt layer name labelmask type imagedata top labelmask top labelidx transform param mirror false crop size 41 image data param source homemoosegithubfirstnetlabelsimagestxt layer name assertidx type euclideanloss bottom dataidx top losswhat does attempting to upgrade input file specified using deprecated transform parameters v1layerparameter mean where exactly did i use something deprecated what should i use instead,['c++'] +905463,cocoa touch framework fails to debug on simulator in embedding project i have got a cocoa touch framework built with xcode 6 targetted towards ios ios8this frameworks target architecture settings are default meaning that i have not changed anything the architectures are set to standard which does not include x86 64 more on that laterthe framework itself contains both swift and objectivec code so building it using the static library workaround from ray wenderlich would not worknow if i create a new project and add the framework project to it the project builds for both the device and simulator which is finehowever if i take the framework file and add it to a different project just like youd add any other framework the project would not build for the simulator well it does build but it crashes because it cannot find the relevant classes it works fine on the device and archiving works just as expected as wellthe framework project itself already gives me a warning apple macho linker warning directory not found for option debugophoneosany help would be highly appreciated,"['ios', 'objective-c']" +905510,acceptable use of instanceof i am new to java and struggling with a design problem i know use of instanceof may indicate a design flaw and i understand the often given animaldogcat classes as example replacing bark and meow with makenoise etcmy question is what is a sensible design if i need to call methods which do not have a corresponding method depending on the type of subclass for example what if i want to call a new method biteleash if the class is a dog but do nothing at all if it is a cati did consider having biteleash in animal which does nothing and overriding it in dog but there are methods many like this so it seems a clunky solution in a similar vein what if the caller needs to do something different depending on which subclass it has hold of eg terminate if subclass is a cat is instanceof acceptable here or is there a better waypublic class animal string name public animalstring name thisname name public string getname return name public void makenoise systemoutprintlnsome noise for a generic animal public class cat extends animal public catstring name supername override public void makenoise systemoutprintlnmeow public class dog extends animal public dogstring name supername override public void makenoise systemoutprintlnwoof public void biteleash systemoutprintlnleash snapped import javautilrandompublic class codeexample public static void mainstring args animal animal getsomeanimal systemoutprintlnmy pet is called animalgetname animalmakenoise if animal instanceof dog dog dog dog animal dogbiteleash do lots of other things because animal is a dog eg sign up for puppy training lessons private static animal getsomeanimal animal animal random randomgenerator new random int randomint randomgeneratornextint100 if randomint 50 animal new dogrover else animal new cattiddles return animal,['java'] +905512,bean thiscovery problems when using weldse with gradle application plugin i am building a gradlebased java se application built on top of hibernate as my orm of choice my plan is to use weldse to be able to use cdi annotations for injections of entitymanagers throughout the applicationbased on the common hibernateutil helper class found in the hibernate documentation i moved towards jpa interfaces and added produces annotations to provide producer methods i have added an empty metainfbeansxml as wellpackage daoimport javaxenterpriseinjectthisposesimport javaxenterpriseinjectproducesimport javaxpersistenceentitymanagerimport javaxpersistenceentitymanagerfactoryimport javaxpersistencepersistencepublic class hibernateutil private static final entitymanagerfactory emf buildentitymanagerfactory private static entitymanagerfactory buildentitymanagerfactory try return persistencecreateentitymanagerfactorypersistenceunit catch throwable ex systemerrprintlninitial entitymanagerfactory creation failed ex throw new exceptionininitializererrorex produces public static entitymanager createentitymanager return emfcreateentitymanager public static void closeentitymanagerthisposes entitymanager em systemoutprintlnclosing em try emclose catch throwable t tprintstacktrace when i try to use the inject annotation on a field however weld fails to resolve the correct producer method and produces an exception insteadexception in thread main orgjbossweldexceptionsunsatisfiedresolutionexception weld001308 unable to resolve any beans for type class appdemoapplication qualifiers javaxenterpriseinjectany at orgjbossweldbeanbuiltininstanceimplgetinstanceimpljava101 at appmainmainmainjava14the offending code is instantiated through the weld container for cdi support and is incredibly basicpackage appimport javaxinjectinjectimport javaxpersistenceentitymanagerpublic class demoapplication inject private entitymanager em public void run try emgettransactionbegin systemoutprintlninside transaction catch throwable t tprintstacktrace finally emgettransactionrollback emclose am i missing an obvious point here how can i get weld to thiscover the producer method for injecting my dependenciesi have put together a minimal project reproducing my problem on github thanks for any helpful suggestions update 20150518seems like i misunderstood the error message in fact weld does not even resolve the demoapplication bean which leads me to believe that somethings wrong with the bean thiscovery process after updating my weldse dependency to the freshly released 300alpha8 version see the linked github repo i was able to get the application to work by manually telling weld about my beans in mainjavafinal weld weld new weld enablethiscovery addpackagefalse hibernateutilclass addpackagefalse demoapplicationclastill any suggestions as to why the beans are not automatically thiscovered despite having an empty metainfbeansxml in place are highly appreciatedupdate 20150519the mystery is unraveled see my own answer below i changed the question title in order to reflect the actual nature of the issue,['java'] +905577,using startup class in aspnet5 console application is it possible for an aspnet 5beta4 console application built from the aspnet console project template in vs2015 to use the startup class to handle registering services and setting up configuration detailsi have tried to create a typical startup class but it never seems to be called when running the console application via dnx run or inside visual studio 2015startupcs is pretty muchpublic class startup public startupihostingenvironment env configuration configuration new configuration configurationaddjsonfileconfigjson configurationaddjsonfileconfigenvenvironmentnametolowerjson optional true configurationaddenvironmentvariables thisconfiguration configuration public void configureservicesiservicecollection services servicesconfiguresettingsconfigurationgetsubkeysettings servicesaddentityframework addsqlserver adbcontextapplicationcontextoptions optionsusesqlserverthisconfigurationdatadefaultconnectionconnectionstring public void configureiapplicationbuilder app ihostingenvironment env iloggerfactory loggerfactory loggerfactoryaddconsoleminlevel loglevelwarning i have tried to manually create the startup class in my main method but this does not seem like the right solution and has not so far allowed me to configure the services i am assuming there is some way for me to create a hostingcontext that does not start up a web server but will keep the console application alive something along the lines ofhostingcontext context new hostingcontext applicationname appnameusing new hostingenginestartcontext console codehowever so far the only way i can get this to work is if i set the hostingcontextserverfactorylocation to microsoftaspnetserverweblistener which starts up the web server,['c#'] +905687,check if a string contains a list of substrings and save the matching ones this is my situation i have a string representing a textstring mytext text to analyze for words bar foo and a list of words to search for in itliststring words new liststring foo bar xyzi would want to know the most efficient method if exists to get the list of the words contained in the text something like thatliststring matches mytextfindwordswords,['c#'] +905697,how do you define node modules as externs in closure compiler i have a nodejs project that i want to compile with closure compiler i do not want it to run in the browseruse browserify i mainly want the utility of type checking i originally got the compiler to work correctly using the followingjava jar compilerjar w verbose language in ecmascript5 strict externs closureexternsjs jslibjswhere closureexternsjs manually defined variables and functions which i was using from nodejs in a rather crude way closureexternsjs constructor function buffersomethingfunction requirepathvar process it turns out that this worked only through sheer luck there is no dependency tracking between files so you can have cases where you return a type foo and the compiler will complain that it does not exist depending on the machine depending on the compile order i then found out i was doing it all wrong and should be using process common js modules so the compiler will do dependency tracking where i requirefoo i am currently invoking the compiler like sojava jar compilerjar w verbose language in ecmascript5 strict externs externsfsjs jslibjs process common js modules common js entry module appjsbut this is failing with error required entry point modulecrypto never provided error required entry point moduledgram never provided error required entry point moduleextend never provided error required entry point modulefs never provided error required entry point modulenet never provided error required entry point moduleq never providedsome of these modules are native to nodejs eg fs whereas others are contained in node modules like q i do not want to run these external modules through the compiler so i know i need to set up externs files for them i know there is for common nodejs externs and i know how to invoke them on the compiler but for some reason when i do something like externs externsfsjs the error for modulefs remains what am i doing wrongi know there is other flags like module and common js module path prefix but i am not sure if i need to use them to get this to work or not my googlefu has failed to come up with any answers on the correct incantation here,['javascript'] +905798,expression tree data structure i want to implement a simple arithmetic expression tree data structure in c such that an expression tree object is initialised by exprtreeoperator expression1 expression2 here is an example of how it should workdouble x 1 y 2 z 05expr1 exprtree x y expr1 1 2 2expr2 exprtree expr1 z expr2 1 2 05 15cout expr2str endl 1 2 05cout expr2eval endl 15here is how my code looks so fartemplateclass operand typeclass exprtreepublic exprtreeconst char op operand type operand1 operand type operand2 op op operand1 operand1 operand2 operand2 double eval const stdstring str constprivate char op typename operand type operand1 operand2templateclass operand typestdstring exprtreeoperand typestr const stdostringstream os stdstring op1 op2 if typeidoperand1 typeidexprtree op1 operand1str else op1 stdstringoperand1 if typeidoperand2 typeidexprtree op2 operand1str else op2 stdstringoperand2 os op1 op op2 return osstrhowever i get this error when i compile the code left of write must point to clastructuniongeneric typei would appreciate it if someone would help me with this error and possibly provide some tips as to how i should implement this data structure btw i am very new to c,['c++'] +905839,oracle performance query executing multiple identical function calls is it possible for oracle to reuse the result of a function when it is called in the same query transaction without the use of the function result cachethe application i am working with is heavily reliant on oracle functions many queries end up executing the exact same functions multiple timesa typical example would beselect my packagemy functionmy id my packagemy functionmy id 24 my packagefunction also calling my functionmy id from my table where my tableid my idi have noticed that oracle always executes each of these functions not realizing that the same function was called just a second ago in the same query it is possible that some elements in the function get cached resulting in a slightly faster return this is not relevant to my question as i want to avoid the entire second or third executionassume that the functions are fairly resourceconsuming and that these functions may call more functions basing their result on tables that are reasonably large and with frequent updates a million records updates with say 10 updates per hour for this reason it is not possible to use oracles function result cacheeven though the data is changing frequently i expect the result of these functions to be the same when they are called from the same queryis it possible for oracle to reuse the result of these functions and how i am using oracle11g and oracle12cbelow is an example just a random nonsense function to illustrate the problem takes 200 msselect test packagetestspeedstandard regexp count from dual takes 400msselect test packagetestspeedstandard regexp count test packagetestspeedstandard regexp count from dualused functionscreate or replace package test package isfunction testspeed p package name varchar2 p object name varchar2return numberendcreate or replace package body test package isfunction testspeed p package name varchar2 p object name varchar2return numberis ln total numberbegin select sumposition into ln total from all arguments where package name standard and object name regexp count return ln totalend testspeedend,['sql'] +905882,what is the term used to describe a complete call frame cycle thing in javascript in javascript there is the concept of the execution pathway beginning at a certain point such as an event handler with the control being relinquished back to the browser at some pointis there a proper name for this processoriginally i thought you could refer to this as the current stack frame but after reading wikipedia i see that refers to something else it is not the call stack that is the breadcrumb of where weve been apologies for the awkward title i am open to suggestions,['javascript'] +905958,github push event signature do not match i am coding a webhook for github and implemented secure verification in koajs asfunction signtok blob var hmac hmac crypto createhmacsha1 tok updateblob digesthex return sha1 hmackey thisrequestheadersxhubsignatureblob jsonstringifythisrequestbodyif key blob thisstatus 400 thisbody bad requestlock signsettingsapi secret blobif lock key consolelogsymbolswarning unauthorized thisstatus 403 thisbody unauthorized returnfor pull requests and create events this works ok even pushing new branches works but for push commits events the xhubsignature and the computed hash from the payload do not match so it always get 403 unauthorizedupdatei have noticed that for this kind of push payloads the commits and head commit are added to the payload i have tried removing the commits and the head commit from the body but it did not workupdatefor more information please review these example payloads i have also included url for the test repo and token info,['javascript'] +906008,project euler 14 why is my treemap algorithm slower than brute force background i first learned c and java in school a number of years ago but i have not done much programming over the past 9 or so years as my previous career did not require iti decided to look into project euler to brush up on my programming and solved problem 14 which asks to find the integer between one and one million with the longest collatz sequence the collatz sequence proceeds by given a starting number multiplying the number by 3 and adding 1 if it is odd or halving the number if it is even the process continues until the number reaches 1 i first solved the problem using brute force as illustrated in the code belowint nlong temp long is necessary since some collatz sequences go outside scope of intint and length new int10 forn 0 and 10 n temp and 1 and lengthn 1 while temp 1 and lengthn if temp 2 0 temp temp2 else temp 3temp 1 int max 0 int max index 0 for int i 0 i 10 i if n lengthi max max and lengthi max index i systemoutprintlnthe number with the longest collatz sequence is max index 1i thought this approach would be inefficient since it runs the algorithm significantly more often than necessary any number that is part of a previous numbers collatz sequence will effectively have its sequence determined already and so you end up calculating the sequence of every single number every single time it comes up in a collatz sequencei decided it would be better to store each number in a map as soon as it comes up in a collatz sequence so you would only have to calculate it once to do this i used a treemap with the numbers used as keys and the associate collatz sequence length as the value and used a recursive function to insert each number into the map as soon as it comes up in a collatz sequence see the code belowpublic static treemaplong integer tm new treemaplong integerpublic static void mainstring args tmputlong1 1 int maxval 1 long keywithmaxval 1 int maybemax for long i 2 i 10 i iftmcontainskeyi maybemax addkeyi if maybemax maxval maxval maybemax keywithmaxval i systemoutprintlnthe number with the longest collatz sequence is keywithmaxval with length maxvalpublic static int addkeylong key while tmcontainskeykey if key 2 0 tmputkey 1 addkeykey2 else tmputkey 1 addkey3key 1 return tmgetkeyi used a treemap since it automatically sorts the keys on entry so as i iterate through the for loop i can quickly check whether the keys have already been inserted and avoid calling the addkey method to add the keys unless i have to i thought that this algorithm would be much much fasterhowever when i actually ran the code i was surprised to find that the brute force algorithm came up with the answer instantaneously while recursive treemap algorithm took much longer around 6 seconds when i modified my programs to go up to 5 million rather than one million the difference became even more pronounced i added some code to each program to make sure that the second program was doing less work than the first and indeed i determined that the addkey method was only being called once for each key while the number of times the while loop needed to iterate in the first program was equal to the sum of the lengths of all numbers collatz sequences ie much more often than the number of method calls in the second algorithmso why is the first algorithm so much faster than the second is it because the array of primitives in the first algorithm requires fewer resources than the treemap of wrapper objects in the second is searching the map to check if a key already exists slower than i anticipated should not it be log time are recursive methods that require large numbers of method calls inherently slower or is there something else i am overlooking,['java'] +906065,java array initialization with zero size while declaring an array in java we have to dynamically allocate the memory using new keyword class array public static void mainstring ars int a new int10 systemoutprintlnalength above code will create a 1d array containing 10 elements 4 byte eachand the output will be 10but when you run same code as followingclass array public static void mainstring ars int a new int0 systemoutprintlnalength output is 0 i want to know that when you write new int0 then do java allocate some memory for the array or not if yes how much,['java'] +906221,invite users with appinvitedialog i am glad that facebook finally let users invite their friends with the sdk version 4 but i do not know how to do it the documentation is clear at least for a whileif appinvitedialogcanshow appinvitecontent content new appinvitecontentbuilder setapplinkurl setpreviewimageurl build appinvitedialogshowmainactivitythis contentso far this could not be simpler but once i select a user to invite i get missing app link url errori understand i need to create an app link url but i do not really know how according to the documentation i should put meta tags between the headhead sections on the website associated with my facebook app in the developer consoles settingssite url sectionso i put these on my websitemeta propertyalandroidurl content meta propertyalandroidapp name contentmyapp meta propertyalandroidpackage contentcommyappandroid meta propertyalweburl content the is created with the app link generatorthis part is totally obscure in the example the url is sharesamplestory1234 and sharesample is defined as a scheme in an intent filter but then what is story1234in the app link generatori added the intent filter to androidmanifest with the scheme data androidschemecommyappandroid i set deep linking in the launcher class asuri targeturl applinksgettargeturlfrominboundintentthis getintentif targeturl null logiactivity app link target url targeturltostringi set the app link name as app link url for myappi set the url as the google play urli set the app name as myappi set the package name as commyappandroidthen i set the generated app link url on the website asmeta propertyalandroidurl content for now all i need is to be able to send app invites and when users click on them they should be taken to the google play url of the app it is like i am one step from finishing this thing but i cannot figure out what i am missing,['android'] +906274,what is the difference between this getcontext and getactivity i am very confused with the usage of all these that where should we use them,['android'] +906339,how does content security policy work i am getting a bunch of errors in the developer consolerefused to evaluate a stringrefused to execute inline script because it violates the following content security policy directiverefused to load the scriptrefused to load the stylesheetwhats this all about how does content security policy work how do i use the contentsecuritypolicy http headerspecifically how toallow multiple sourcesuse different directivesuse multiple directiveshandle portshandle different protocolsallow file protocoluse inline styles scripts and tags style and scriptallow evaland finallywhat exactly does self mean,"['javascript', 'html']" +906372,first rspec test ensure value is 1 or 1 new programmer here i am a student working on my project that is a reddit clone currently i have been introduced to rspec i have to start writing my own model tests to be used in further exercises the model in question is not created it will be in the next assignment can someone please check if i have done this correctlyin the next checkpoint well add a vote model this model will feature an inclusion validation inclusion validation ensures that a votes value attribute is either 1 or 1 if a vote is initialized with any other value it will not savecreate votespecspecmodelsvote specrbdescribe vote do describe validations do describe value validation do it only allows 1 or 1 as values do your expectations here end end endendwrite a spec that asserts the validations work as expected use rspecs expectto eq syntax as you may recall from the specs in the ruby exercises you can assert that something should equal false or true you would not be able to run the tests because we have not generated the model were testingbelow is my implementationdescribe vote do describe validations do before do 2times votecreatevalue 1 3times votecreatevalue 1 2times votecreatevalue 3 end describe value validation do it only allows 1 or 1 as values do expect votevalue to eq1 end it only allows 1 or 1 as values do expect votevalue to eq1 end end endendbest regardsedit here is a revisiondescribe vote do describe validations do before do 2times votecreatevalue 1 3times votecreatevalue 0 2times votecreatevalue 3 end describe value validation do it only allows 1 as value do expect votevalue to eq1 end it only allows 1 as value do expect votevalue to eq1 end it it prohibits other values do expect votevalue to not be valid end end endendi have also tried with this code which worked at first but now fails in the next assignmentrequire rails helper describe vote do describe value validation do it allows 1 do value votecreatevalue 1 expectvalueto be valid end it allows 1 do value votecreatevalue 1 expectvalueto be valid end it prohibits other values do value votecreatevalue 0 expectvalueto not be valid end endenda rspec specfailures 1 vote value validation allows 1 failureerror value votecreatevalue 1 nomethoderror undefined method update rank for nilnilclass appmodelsvoterb12in update post specmodelsvote specrb7in block 3 levels in top required 2 vote value validation allows 1 failureerror value votecreatevalue 1 nomethoderror undefined method update rank for nilnilclass appmodelsvoterb12in update post specmodelsvote specrb12in block 3 levels in top required 3 vote value validation prohibits other values failureerror expectvalueto eqfalse expected false got vote id nil value 0 user id nil post id nil created at nil updated at nil compared using specmodelsvote specrb18in block 3 levels in top requiredfinished in 030485 seconds files took 328 seconds to load6 examples 3 failuresfailed examplesrspec specmodelsvote specrb6 vote value validation allows 1rspec specmodelsvote specrb11 vote value validation allows 1rspec specmodelsvote specrb16 vote value validation prohibits other values,"['ruby-on-rails', 'ruby']" +906422,java 8 stream map and count thistinct my first attempt with java 8 streamsi have an object bid which represents a bid of a user for an item in an auction i have a list of bids and i want to make a map that counts in how many thistinct auctions the user made a bidthis is my take on itbidsstream collect collectorsgroupingby bid bidgetbidderuserid mappingbidgetauctionid collectorstoset entrysetstreamcollectcollectorstomap e egetkeye egetvaluesize it works but i feel like i am cheating cause i stream the entry sets of the map instead of doing a manipulation on the initial stream must be a more correct way of doing this but i could not figure it out thanks,['java'] +906522,how mpandroidchart thisplay all xaxis values i am developing some chart features using mpandroidchart libraryis there any way to thisplay all the xaxis values i addedseems that the library will auto calculate on xaxis some of values will be hiddenex thisplay date 0517 0517 0515 the same day 0517 will not shownthanks,['android'] +906568,detect when odoo interface is fully loaded i need to run some javascript code to check when odoo has ended loadingi know that querying jqueryactive 0 does the trick in version 7 but that does not work in odoo because it always keep one connection open for the longpollingdoes anybody know which web element can i use to check for sure when the interface is fully loaded if i can query the url of the active jquery connections that would also do the trick,"['javascript', 'jquery']" +906569,angularjs html5mode support on github pages the question is does github pages support angularjs html5modei have found a w resource which states that it is possible to do that with 404 fallback page well it seems like an erroneous solution since each call will return 404 error this would not be seofriendly for sure html5mode is supposed to need serverside support to return the html entry point for each callso is that possible to serve angularjs html5mode on github pages the right way,['javascript'] +906697,how do i build gcc with c concepts concepts lite support the c standards committee is working on a ts technical specification for concepts extension programming languages c extensions for concepts n4377 is the latest version of this document for inclusion into the c standard features are asked to be implemented ideally for a publicly accessible systemi am aware of conceptgcc but the concepts proposal above colloquially referred to as concepts lite is different i heard that there is a concepts branch and i have tried the originasuttoncconcepts from gccs git mirror but that did not compile how do i build and use a version of gcc supporting concepts as specified in the above draft ts,['c++'] +906704,why does javas sort implementation convert a list to an array before sorting in jdk 18 the first statement of the javautillistsortcomparator method is the followingobject a thistoarrayit is expensive to copy the list into an array sort it and reset every node of the list to the sorted value from the arrayit seems like it is possible not to copy values to a temporary array when sorting an arraylist am i right if not what guided the creators of the method,['java'] +906707,adding custom roles to azure mobile services user google twitter facebook microsoft i have an net azure mobile services project with some controllers i want to secure with the typical authorize attribute i can create a roles table and a userprofiles table and associate the various users authenticated through google facebook etc with roles in my roles table my question is how do a add the roles claims to the serviceusers after the authentication is complete but before the authorize filters onauthorize method runs is this even possibleexample of what i want to doauthorizeroles adminpublic async taskihttpactionresult putint id mydto dtorough table examplesrolesid name1 user2 adminuserprofilesid externalloginid favoritecolor1 googleserviceuserid blueuserroles linking tableroleid userid2 1editone option might be to create my own action filter overriding the authorize filter attribute and in the onauthorize method i could query the userprofiles and roles tables to get the roles for the current user then check against the roles specified in the authorize objects roles property to determine if the user has access but somehow it feels like there should be a place earlier in the pipeline that i can intercept to just add the roles claims to the current user,['.net'] +906717,how can i make my ionic button refresh all ionviews preferable in most just revaluate a ngswitch in my view i have a ngswitch likediv ngswitch onteamisfavorite button classbutton buttonenergized snbutton ngswitchwhenfalse ngclickmaketeamfavorite show team on dashboard button p clasnmsg ngswitchdefault this team is shown on the dashboard pdivhow can i make my ionic button refresh all ionviewspreferable in most just reevaluate a ngswitch in 1 reload everythingwhat i tried in my controllercontrollerlistpeoplectrl functionionichistory state scope stateparams teams scopemaketeamfavorite function teamssetfavoriteidstateparamsteamid ionichistoryclearcache stategostatecurrent scopeteam teamsgetstateparamsteamid scopeteamisfavorite teamsgetfavoriteidstateparamsteamid scopepeople teamsmembersstateparamsteamidit would invalidate all caches i guess but it did not work anyway dnotei searched but did not find anything to do this i do not want to mark my ion view with cachefalse and opt out of all cachingi think this is ionic specific but it could be my general lack of knowledge concerning angularjs dthe point is it works without clearing the cache when i next open the view again just that it is not reloaded while looking at itediti also tried with ionichistoryclearcache stategostatecurrent reload true or just stategostatecurrent reload true no luck,"['javascript', 'html']" +906752,how can i thisable mongodb log messages in console i have this little test scriptrequire mongomongo client mongoclientnew12700127017 database testmongo clientcollectioninsert onea 1an this is the console output ruby testrbd 20150517t211205504986 25257 debug mongodb adding 12700127017 to the cluster runtime 00212msd 20150517t211205531238 25257 debug mongodb command namespaceadmincmd selectorismaster1 flags limit1 skip0 projectnil runtime 245481msd 20150517t2112054532 25257 debug mongodb command namespacetestcmd selectorinsertcollection documentsa1 idbsonobjectid0x21935660 data58e80553657262a90 writeconcernw1 orderedtrue flags limit1 skip0 projectnil runtime 211718msi want to thisable those log messages i do not want a dirty stdout i did not found any option for this in the ruby driver and also i have tried to edit etcmongodconf with these directives but it did not fix itverbose falsediaglog 0any idea i do not know what else i can try,['ruby'] +906861,javalangunsatisfiedlinkerror ndk in android studio gradle folder structure app main java jni androidmk applicationmk hellojnic resin buildgradleapply plugin comandroidapplicationandroid compilesdkversion 21buildtoolsversion 2201defaultconfig applicationid comexamplehellojni minsdkversion 17 targetsdkversion 21 sourcesetsmain jnisrcdirs jnilibssrcdir srcmainlibs ndk modulename hellojni cflags stdc11 fexceptions ldlibs log stl gnustl shared abifilter armeabiv7a task nativelibstojartype zip description create a jar archive of the native libs destinationdir filebuilddirnativelibs basename nativelibs extension jar from filetreedir libs include so into lib taskswithtypejavacompile compiletask compiletaskdependsonnativelibstojar testapplicationid comexamplehellojnitests testinstrumentationrunner androidtestinstrumentationtestrunnerbuildtypes release minifyenabled false proguardfiles getdefaultproguardfileproguardandroidtxt proguardrulestxt dependencies compile filetreedir builddirnativelibs include nativelibsjarin androidmk local path call mydir include clear vars local module hellojnilocal src files hellojnicinclude build shared libraryin hellojnicincludecomexamplehellojnihellojnihinclude stringh include jnih jstring java com example hellojni hellojni stringfromjni jnienv env jobject thiz if defined arm if defined arm arch 7a if defined arm neon if defined arm pcs vfp define abi armeabiv7aneon hardfloat else define abi armeabiv7aneon endif else if defined arm pcs vfp define abi armeabiv7a hardfloat else define abi armeabiv7a endif endif else define abi armeabi endif elif defined i386 define abi x86 elif defined x86 64 define abi x86 64 elif defined mips64 mips64el toolchain defines mips too define abi mips64 elif defined mips define abi mips elif defined aarch64 define abi arm64v8aelse define abi unknown endif return envnewstringutfenv hello from jni compiled with abi abi in java public class hellojni extends activity called when the activity is first created override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate textview tv new textviewthis tvsettext stringfromjni setcontentviewtvpublic native string stringfromjnipublic native string unimplementedstringfromjnistatic systemloadlibraryhellojnii am getting unsatisfied error javalangunsatisfiedlinkerror dalviksystempathclassloaderdexpathlistzip file dataappcomexamplehellojni2baseapknativelibrarydirectoriesvendorlib systemlib could not find libhellojniso at javalangruntimeloadlibraryruntimejava366 at javalangsystemloadlibrarysystemjava989 at comexamplehellojnihellojniclinithellojnijava64 at javalangreflectconstructornewinstancenative method at javalangclassnewinstanceclassjava1572 at androidappinstrumentationnewactivityinstrumentationjava1088 at androidappactivitythreadperformlaunchactivityactivitythreadjava2215 at androidappactivitythreadhandlelaunchactivityactivitythreadjava2388 at androidappactivitythreadaccess800activitythreadjava148 at androidappactivitythreadhhandlemessageactivitythreadjava1292 at androidoshandlerthispatchmessagehandlerjava102 at androidoslooperlooplooperjava135 at androidappactivitythreadmainactivitythreadjava5312 at javalangreflectmethodinvokenative method at javalangreflectmethodinvokemethodjava372 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava901 at comandroidinternaloszygoteinitmainzygoteinitjava696my localpropertiessdkdirfsdkndkdircndkits not generating so files,"['java', 'android']" +906885,why does java 8 apply annotations differently to derived classes if i have the following two classes basejavapublic abstract class baset abstract void methodt tand derivedjavapublic class derived extends basenumber deprecated void methodnumber n i then compile them with javac basejava derivedjava and then use javap v derived if i use java 7 i getpublic class derived extends basejavalangnumber signature 17 lbaseljavalangnumber sourcefile derivedjava minor version 0 major version 51 flags acc public acc superconstant pool 1 methodref 520 baseinitv 2 class 21 javalangnumber 3 methodref 422 derivedmethodljavalangnumberv 4 class 23 derived 5 class 24 base 6 utf8 init 7 utf8 v 8 utf8 code 9 utf8 linenumbertable 10 utf8 method 11 utf8 ljavalangnumberv 12 utf8 deprecated 13 utf8 runtimevisibleannotations 14 utf8 ljavalangdeprecated 15 utf8 ljavalangobjectv 16 utf8 signature 17 utf8 lbaseljavalangnumber 18 utf8 sourcefile 19 utf8 derivedjava 20 nameandtype 67 initv 21 utf8 javalangnumber 22 nameandtype 1011 methodljavalangnumberv 23 utf8 derived 24 utf8 base public derived flags acc public code stack1 locals1 args size1 0 aload 0 1 invokespecial 1 method baseinitv 4 return linenumbertable line 1 0 void methodjavalangnumber flags code stack0 locals2 args size2 0 return linenumbertable line 7 0 deprecated true runtimevisibleannotations 0 14 void methodjavalangobject flags acc bridge acc synthetic code stack2 locals2 args size2 0 aload 0 1 aload 1 2 checkcast 2 class javalangnumber 5 invokevirtual 3 method methodljavalangnumberv 8 return linenumbertable line 1 0if i do the same thing with java 8 i instead get public class derived extends basejavalangnumber minor version 0 major version 52 flags acc public acc superconstant pool 1 methodref 520 baseinitv 2 class 21 javalangnumber 3 methodref 422 derivedmethodljavalangnumberv 4 class 23 derived 5 class 24 base 6 utf8 init 7 utf8 v 8 utf8 code 9 utf8 linenumbertable 10 utf8 method 11 utf8 ljavalangnumberv 12 utf8 deprecated 13 utf8 runtimevisibleannotations 14 utf8 ljavalangdeprecated 15 utf8 ljavalangobjectv 16 utf8 signature 17 utf8 lbaseljavalangnumber 18 utf8 sourcefile 19 utf8 derivedjava 20 nameandtype 67 initv 21 utf8 javalangnumber 22 nameandtype 1011 methodljavalangnumberv 23 utf8 derived 24 utf8 base public derived descriptor v flags acc public code stack1 locals1 args size1 0 aload 0 1 invokespecial 1 method baseinitv 4 return linenumbertable line 1 0 void methodjavalangnumber descriptor ljavalangnumberv flags code stack0 locals2 args size2 0 return linenumbertable line 5 0 deprecated true runtimevisibleannotations 0 14 void methodjavalangobject descriptor ljavalangobjectv flags acc bridge acc synthetic code stack2 locals2 args size2 0 aload 0 1 aload 1 2 checkcast 2 class javalangnumber 5 invokevirtual 3 method methodljavalangnumberv 8 return linenumbertable line 1 0 runtimevisibleannotations 0 14signature 17 lbaseljavalangnumbersourcefile derivedjavathe thing to note here is that there is an annotation visible on the void methodjavalangobject stub in the java 8 version that is not present in the java 7 version it is not just javap making a mistake if you use reflection to check the annotations present at runtime the java 7 version only has an annotation on void methodjavalangnumber and the java 8 version has it on both whats going on,['java'] +906908,is it possible to change value of range key in dynamodb table i know it may be a very silly question but i am new to dynamodbmy doubt is is it possible to update the value of a range key in dynamodbsuppose my table is testid pkhkdate rkname gsi add lsii want to modify date attributeinitial values in table wasid 344date 5656name abcrunning this code below i am able to change the name attribute which is gsimapstringattributevalue item new hashmapstringattributevalueitemputid new attributevalue344itemputdate new attributevalue5656mapstringattributevalueupdate item1 new hashmapstringattributevalueupdateattributevalueupdate update new attributevalueupdatewithvaluenew attributevalueamitwithactionputitem1putname updateupdateitemrequest updateitemreq new updateitemrequesttestitemitem1updateitemresult updateitemres dynamodbuseastupdateitemupdateitemreqbut when i change this lineitem1putname updatewith item1putdate updatei am getting some error asexception in thread main comamazonawsamazonserviceexception one or more parameter values were invalid cannot update attribute date this attribute is part of the key service amazondynamodbv2 status code 400 error code validationexception request id hrrp24q7c48amd8asai992l6mbvv4kqnso5aemvjf66q9asuaajg at comamazonawshttpamazonhttpclienthandleerrorresponseamazonhttpclientjava820 at comamazonawshttpamazonhttpclientexecutehelperamazonhttpclientjava439 at comamazonawshttpamazonhttpclientexecuteamazonhttpclientjava245 at comamazonawsservicesdynamodbv2amazondynamodbclientinvokeamazondynamodbclientjava2908 at comamazonawsservicesdynamodbv2amazondynamodbclientupdateitemamazondynamodbclientjava1256so is it possible to change the range key value,['java'] +906937,understanding python closures i always thought that python 27 functions refer to the scope they were defined in consider the following code why is the second output not calculating sinis there any way to modify the code so it is working as expectedimport mathmymath dictfor fun in sin cos def implval print calculating s fun return getattrmath funval mymathfun impl calculating cosprint mymathcosmathpi calculating cos whyprint mymathsinmathpi,['python'] +906973,how to apply a limit just for joining table in mysql query i have two table named category and content each category can have many contents and this is my queryselect from categories ca left join content co on cocat idcaidi want to apply limit on it that query fetch 10 content for each categoryhow should i query for this,"['php', 'mysql', 'sql']" +906982,sorting a stream of doubles by absolute magnitude i have a series of double values which i want to sum up and get the maximum valuethe doublestreamsummarystatistics sounds perfect for thatthe getsum method has an api note reminding me of what i learned during one of my computer science courses the stability of the summation problem tends to be better if the values are sorted by their absolute values however doublestream does not let me specify the comparator to use it will just use doublecompareto if i call sorted on the streamthus i gathered the values into a final streambuilderdouble values streambuilder and callvaluesbuild sortedcomparatorcomparingdoublemathabs maptodoublea asummarystatisticsyet this looks somewhat lengthy and i would have preferred to use the doublestreambuilder instead of the generic builderdid i miss something or do i really have to use the boxed version of the stream just to be able to specify the comparator,['java'] +907162,does the following chained assignment cause undefined behavior does the following code invoke undefined behavior in cint a 1 b 2a b a 1i know that the following does invoke uba b athe reason is that it violates the following clause from the standardbetween the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression furthermore the prior value shall be accessed only to determine the value to be storedhowever the first snippet does not violate this clause a coworker says that statement a b a1 can mean eithera a 1b a 1or b a 1a bi think that due to the righttoleft associativity of it always must mean a b a1 nota a 1b a 1i am not positive though is it ub,['c'] +907201,performance of javalangreflectarray since i am making heavy use of reflective access to arrays in a project i decided to compare the performance of arrayindex vs javalangreflectarraygetarray index while i anticipated that reflective calls are quite a bit slower i was surprised to see that they are between 1016 times slowerso i decided to write a simple utility method that does about the same as arrayget but receives the array at the given index by casting the object instead of using a native method as does arraygetpublic static object getobject array int index class c arraygetclass if intclass c return intarrayindex else if floatclass c return floatarrayindex else if booleanclass c return booleanarrayindex else if charclass c return chararrayindex else if doubleclass c return doublearrayindex else if longclass c return longarrayindex else if shortclass c return shortarrayindex else if byteclass c return bytearrayindex return objectarrayindexi believe that this method provides the same functionality as arrayget with the notable difference of the thrown exceptions eg a classcastexception gets thrown instead of an illegalargumentexception if one calls the method with an object that is no arrayto my surprise this utility method performs much better than arraygetthree questionsdo others here experience the same performance issues with arrayget or is this perhaps a hardwareplatformjavaversion issue i tested with java 8 on a dual core windows 7 laptopdo i miss something concerning the functionality of the method arrayget ie is there some functionality that must necessarily be implemented using a native callis there a specific reason why arrayget was implemented using native methods when the same functionality could have been implemented in pure java with a much higher performancetest classes and resultsthe tests have been done using caliper latest caliper from git necessary to compile the code but for your convenience i also included a main method that performs a simplified test you need to remove the caliper annotations to make it compiletestclassimport javalangreflectarrayimport comgooglecaliperbeforeexperimentimport comgooglecaliperbenchmarkpublic class arrayatbenchmark public static final class arrayutil public static object getobject array int index class c arraygetclass if intclass c return intarrayindex else if floatclass c return floatarrayindex else if booleanclass c return booleanarrayindex else if charclass c return chararrayindex else if doubleclass c return doublearrayindex else if longclass c return longarrayindex else if shortclass c return shortarrayindex else if byteclass c return bytearrayindex return objectarrayindex private static final int element size 100 private object objectarray beforeexperiment public void setup objectarray new objectelement size for int i 0 i objectarraylength i objectarrayi new object benchmark public int objectarray atint reps int dummy 0 for int i 0 i reps i for int j 0 j element size j dummy objectarrayjhashcode return dummy benchmark public int objectarray array getint reps int dummy 0 for int i 0 i reps i for int j 0 j element size j dummy arraygetobjectarray jhashcode return dummy benchmark public int objectarray arrayutil getint reps int dummy 0 for int i 0 i reps i for int j 0 j element size j dummy arrayutilgetobjectarray jhashcode return dummy test method to use without cailper public static void mainstring args arrayatbenchmark benchmark new arrayatbenchmark benchmarksetup int warmup 10 warm up benchmarkobjectarray atwarmup benchmarkobjectarray array getwarmup benchmarkobjectarray arrayutil getwarmup int reps 10 long start systemnanotime int temp benchmarkobjectarray atreps long end systemnanotime long time endstartreps systemoutprintlntime for objectarray at time ns start systemnanotime temp benchmarkobjectarray array getreps end systemnanotime time endstartreps systemoutprintlntime for objectarray array get time ns start systemnanotime temp benchmarkobjectarray arrayutil getreps end systemnanotime time endstartreps systemoutprintlntime for objectarray arrayutil get time ns if temp 0 sanity check to prevent jit to optimize the test methods away systemoutprintlnresult result the caliper results can be viewed herethe results of the simplified main method look like this on my machinetime for objectarray at 620 nstime for objectarray array get 10525 nstime for objectarray arrayutil get 1287 nsadditional informationthe results are similar when running the jvm with serverthe other array methods eg arraygetint arraygetlength arrayset etc also perform much slower than similarly implemented utility methodsthis question is somewhat related to what is the purpose of javalangreflectarrays getter and setter methods,['java'] +907232,how to find if i have a memory leak i wrote a number crunching algorithm the idea is thata small main programs needs very few memory starts at 2 mbthen in a loop it calls a function that needs quite some memory around 100 mb which should be released when the function end in order to understand whats going on the function is now always called with the same parametersit seems that the program slowly eats memory so i suspect a memory leak i have tried address sanitizer from clang and pointer checker from intel but they do not find anythingnow i am looking at the memory consumption in my activity monitor i am running osx but i get the same memory usage from the unix command top and just before the big function is called the program takes 2 mb when running the function the program takes 120 mb what is strange is that when the program ends up the big function and comes back inside the loop it now takes 37 mb then when it goes back into the big function it takes 130 mb again coming back in the loop it takes 36 mb then in the big function it takes 140 mbso it is slowly drifting away but not with a regular pattern how should i trust the memory usage in topcan memory fragmentation increase the memory usage without memory leaki let the program run overnight and here is the data i getin the first loop the program takes 150 mb2 hours later after 68 loops the program takes 220 mbafter one night and 394 loops the program takes 480 mbso it seems that the function that allocates and deallocates memory about 120 mb seems to leak 1 mb each time it is called,['c++'] +907261,deactivate conflict in virtualenvwapper and anaconda i am using virtualenv to switch my python dev env but when i run workon my env i meet such error messageerror deactivate must be sourced run source deactivateinstead of deactivateusage source deactivateremoves the bin directory of the environment activated with sourceactivate from pathafter some searches on google it seems that workon which is defined in usrlocalbinvirtualenvwrappersh calls deactivate and there is a script with the same name is present in anacondas bin so it gets called by workon by mistakeany suggestion for working around this conflict,['python'] +907275,jni wrapper for c function using swig what should be the typemap i am trying to create the jni wrapper for the following functions in cint err new instanceconst char name instance t instancename input instance outputint err get valueconst instance t instance int valinstance input val outputwhere instance t is defined as typedef void instance ti am all lost in the swig manual for java since it does not simply support input parameters as the output type i had no problems whatsoever with the python wrapper shown belowwhat is the correct way of using typemap in the case of java instance t argouttypemapin numinputs0 instance t instance instance t temp 0 1 temptypemapargout instance t instance append outputpylong fromlonglonglong long 1 instance t intypemapin instance t instance 1 instance t pylong aslonglonginput,"['java', 'c']" +907277,tools to create installers or setup programs in visual studio 2015 after i built a good wpf application in c and willing to work with that technology i knew that my software development tools with visual studio community 2015 rc are not enough without a tool for creating setup programsso i would tried to install microsoft visual studio 2015 installer projects but unfortunately microsoft visual studio professional which is not free is required to be able to install that extensioni have also tried to install the release version of wix toolset v39 r2 but it is not compatible with visual studio 2015,['c#'] +907327,external source maps for minified transpiled es6 code with webpack and gulp i am writing es6 code and transpile it to es5 with babel then minify with uglify all run with webpack via gulp i would like to use external source maps to keep filesize as small as possiblethe gulp task is pretty basic all the funky stuff is in the webpack configvar gulp requiregulpvar webpack requiregulpwebpackgulptaskjses6 function return gulpsrcpathjoin dirname pth to src indexjs pipewebpackrequirewebpackconfigjs pipegulpdestpathjoin dirname pth to destwebpackconfigjsvar path requirepathvar webpack requirewebpackmoduleexports output filename mainjs sourcemapfilename mainjsmap devtool inlinesourcemap module loaders test pathjoin dirname pth to src loader babelloader plugins new webpackoptimizeuglifyjsplugin compress warnings false output comments false semicolons true sourcemap true the above works and it creates working source maps but they are inline if i change webpackconfigjs so that it says devtool sourcemap the source map is created as a separate file using sourcemapfilename as filename but it is not usable chrome dev tools does not seem to understand it if i remove the webpackoptimizeuglifyjsplugin the source map is usable but the code is not minified so source map works for the two individual steps but not when they are run in sequencei suspect the uglify step ignores the external sourcemap from the previous transpiler step so the sourcemap it generates is based on the stream which of course does not exist outside of gulp hence the unusable source mapi am pretty new to webpack so i may be missing something obviouswhat i am trying to do is similar to this question but with webpack instead of browserify gulp browserify 6to5 source mapsthanks in advance,['javascript'] +907449,why does my 8m l3 cache not provide any benefit for arrays larger than 1m i was inspired by this question to write a simple program to test my machines memory bandwidth in each cache levelwhy vectorizing the loop does not have performance improvementmy code uses memset to write to a buffer or buffers over and over and measures the speed it also saves the address of every buffer to print at the end heres the listinginclude stdiohinclude stdlibhinclude stringhinclude systimehdefine size kb 8 16 24 28 32 36 40 48 64 128 256 384 512 768 1024 1025 2048 4096 8192 16384 20define testmem 10 approximate in bytesdefine buffers 1double timervoid struct timeval ts double ans gettimeofdayts null ans tstv sec tstv usec10e6 return ansint mainint argc char argv double xbuffers double t1 t2 int kbsizes size kb double bandwidthsizeofkbsizessizeofint int iterationssizeofkbsizessizeofint double addresizeofkbsizessizeofintbuffers int i j k for k 0 k sizeofkbsizessizeofint k iterationsk testmemkbsizesk1024 for k 0 k sizeofkbsizessizeofint k allocate for j 0 j buffers j xj double mallockbsizesk1024 addresskj xj memsetxj 0 kbsizesk1024 measure t1 timer for i 0 i iterationsk i for j 0 j buffers j memsetxj 0xff kbsizesk1024 t2 timer bandwidthk bufferskbsizeskiterationsk1024010240t2t1 free for j 0 j buffers j freexj printftestmem ldn testmem printfbuffers dn buffers printfsize kbtbandwidth gbstiterationstaddressesn for k 0 k sizeofkbsizessizeofint k printf7dtt2ftdttx kbsizesk bandwidthk iterationsk addressk0 for j 1 j buffers j printf x addresskj printfn return 0and the results with buffers 1testmem 10buffers 1size kb bandwidth gbs iterations addresses 8 5279 1220703 90b010 16 5648 610351 90b010 24 5701 406901 90b010 28 5713 348772 90b010 32 4540 305175 90b010 36 3811 271267 90b010 40 3802 244140 90b010 48 3812 203450 90b010 64 3751 152587 90b010 128 3689 76293 90b010 256 3558 38146 d760f010 384 3101 25431 d75ef010 512 2679 19073 d75cf010 768 2620 12715 d758f010 1024 2620 9536 d754f010 1025 1830 9527 90b010 2048 1829 4768 d744f010 4096 1829 2384 d724f010 8192 1831 1192 d6e4f010 16384 1831 596 d664f010 20 1832 48 cb2ff010i can easily see the effect of the 32k l1 cache and 256k l2 cache what i do not understand is why performance drops suddenly after the size of the memset buffer exceeds 1m my l3 cache is supposed to be 8m it happens so suddenly too not tapered at all like when the l1 and l2 cache size was exceededmy processor is the intel i7 3700 the details of the l3 cache from sysdevicessystemcpucpu0cache arelevel 3coherency line size 64number of sets 8192physical line partition 1shared cpu list 07shared cpu map ffsize 8192ktype unifiedways of associativity 16i thought i would try using multiple buffers call memset on 2 buffers of 1m each and see if performance would drop with buffers 2 i gettestmem 10buffers 2size kb bandwidth gbs iterations addresses 8 5415 1220703 e59010 e5b020 16 5152 610351 e59010 e5d020 24 3894 406901 e59010 e5f020 28 3853 348772 e59010 e60020 32 3831 305175 e59010 e61020 36 3829 271267 e59010 e62020 40 3829 244140 e59010 e63020 48 3746 203450 e59010 e65020 64 3693 152587 e59010 e69020 128 3567 76293 e59010 63769010 256 2721 38146 63724010 636e3010 384 2626 25431 63704010 636a3010 512 2619 19073 636e4010 63663010 768 2620 12715 636a4010 635e3010 1024 2616 9536 63664010 63563010 1025 1829 9527 e59010 f59420 2048 1823 4768 63564010 63363010 4096 1827 2384 63364010 62f63010 8192 1829 1192 62f64010 62763010 16384 1831 596 62764010 61763010 20 1831 48 57414010 4b0c3010it appears that both 1m buffers stay in the l3 cache but try to increase the size of either buffer ever so slightly and the performance dropsi have been compiling with o3 it does not make much difference except possibly unrolling the loops over buffers i tried with o0 and it is the same except for the l1 speeds gcc version is 491to summarize i have a 2part questionwhy does my 8 mb l3 cache not provide any benefit on blocks of memory larger than 1mwhy is the drop in performance so suddeneditas suggested by gabriel southern i ran my code with perf using buffers1 with only one buffer size at a time this was the full commandperf stat e dtlbloadsdtlbloadmissesdtlbstoresdtlbstoremisses r 100 aout 2 perfouttxtthe r means that perf will run aout 100 times and return the average statisticsthe output of perf with define size kb 1024 performance counter stats for aout 100 runs 1508798 dtlbloads 002 0 dtlbloadmisses 0 of all dtlb cache hits 625967550 dtlbstores 0 1503 dtlbstoremisses 079 0360471583 seconds time elapsed 079 and with define size kb 1025 performance counter stats for aout 100 runs 1670402 dtlbloads 009 0 dtlbloadmisses 0 of all dtlb cache hits 626099850 dtlbstores 0 2115 dtlbstoremisses 219 0503913416 seconds time elapsed 006 so there does seem to be more tlb misses with the 1025k buffer however with this size buffer the program does about 9500 calls of memset so it is still less than 1 miss per memset call,"['c++', 'c']" +907492,how to pass data to another page using jquery ajax i have a problem on ajax callhere is my code regarding the ajaxsubjectsclickfunction ajax type post url portalcurriculumphp data studentnumberstudentidval success functiondata curriculumhtmldata when i echo studentnumber on another page the studentnumber is undefined why is that,"['javascript', 'php', 'jquery']" +907665,appending the elements within div using appendchild attribute i have a div as div iddiv1 width100px height100pxdivnow within this div i want to place 20 elements but dynamically it can grow upto 50 elementsimages also i am using the following code to append these elements in a divvar i documentcreateelementimgvar d documentgetelementbyiddiv1dappendchildinow the issue is as the number of elements increase the elements are going out of div and if i use the maxwidth and maxheight on images the result doesnt changeisetattributemaxwidth 100isetattributemaxheight 100is there anything which i am missingeditthe images need to shrink as the div size is fixed,"['javascript', 'html', 'css']" +907746,android app with gps voice directions i am trying to create a tourism app for androidi need the user be guided by voice i have been looking at the googlemaps android api but there is nothing about voice directions do you know any workaround for this is there any other apisdk that i could use to implement thisthanks in advance,['android'] +907769,why do some cells not move entirely i have set up this jsfiddle var movecell functiondirection var celltobemoved pickrandomcellvar currentx celltobemovedxbasevalvalue var currenty celltobemovedybasevalvaluevar change getplusorminus cellsize 1 var newx currentx changevar newy currenty changevar selectedcell d3selectcelltobemovedif direction x selectedcelltransitionduration1500 attrx newx else selectedcelltransitionduration1500 attry newy in the movecell function i pick a random cell request its current x and y coordinates and then add or subtract its width or height to move it to an adjacent cellwhat i am wondering about if you watch the cells move some will only move partially to the next cell can anoyne tell me why this is so,['javascript'] +908099,bug in chrome with ckeditor editing links so basically i have this problem in chromeworking fine in firefox when i edit a content and i have the following situation a link and some text and when i click at the end of the link to change some link text to some link to website it does the following before editing some link text some contenta hrefsome link text a some contentsome link to website some contenta hrefsome linka to website some content,"['javascript', 'jquery']" +908121,memory heap allocator library that keeps separate structures heres my problem i need to manage memory in a remote contiguous buffer that my program cannot read or write to it needs to have mallocfree semantics and support setting minimum alignment and fragmentation avoidance whenever possible since i cannot read or write to this buffer directly i need to use local structures to manage all the allocationsi am already using boost so if something inside boost can be massaged to do this that would be great however i am not averse to using a c library or anything like that as an example i need a nonipc version ofboostinterprocessbasic managed external buffer char boostinterprocessrbtree best fit boostinterprocessmutex family boostinterprocessoffset ptrvoid some alignment boostinterprocessiset indexpreferably with mallocfree semantics instead of newdeletebut without it ever actually reading or writing to the underlying buffer and keeping all the allocation informationdata structures in a separate bufferany ideasps i do not want the boostinterprocess example to be misleading i am just familiar with the interface so using it as an example the application is not really interprocess and the allocator would only be used from my applicationspecifically i would like to be able to manage a 16gb external buffer with allocation sizes from 128 bytes all the way to 512mb this is strictly 64bit code but even then i would prefer the pointer type to be a template parameter so i can use uint64 t explicitly,['c++'] +908259,xcode fetching list of team time out member center dead any ideas it was working an hour ago now everything is dead and the status page says all is good,['ios'] +908333,thistinguish read char from read integer i am implementing rle algorithm in c and i am having a great problem i am using as an identifier for the compressiondecompression let me use examples0 0 0 0 1 2 0 0 0 0 0 4 1 2 0 4kind of x y repeat x y times and the numbers vary from 0 to 255 unsigned char but the number 64 is screwing me because it is the same as the program reads 64 0 5i expect 64 0 5 no decompression is neededwhat i get 0 0 0 0 0 64 is stored in a char variable and then the program uses it as if var decompress,['c'] +908359,videoviewsetonpreparedlistener videoviewsetoncompletionlistener and videoviewsetonerrorlistener not getting called here is my code snippet where i want to play a video coming from serverprivate void playvideo try getwindowsetformatpixelformattranslucent mediacontroller mediacontroller new mediacontrollervideoactivitythis mediacontrollersetanchorviewvideoview uri video uriparsevideopath videoviewsetmediacontrollermediacontroller videoviewsetvideourivideo videoviewrequestfocus videoplayerremoveallviews videoplayersetvisibilityviewgone videoviewsetvisibilityviewvisible videoviewsetonpreparedlistenernew onpreparedlistener override public void onpreparedmediaplayer mp thismissprogressdialog videoviewbringtofront videoviewsetfocusabletrue videoviewstart contentstarted true videoviewsetoncompletionlistenernew oncompletionlistener override public void oncompletionmediaplayer mp contentstarted false videoviewsetonerrorlistenernew onerrorlistener override public boolean onerrormediaplayer mp int what int extra thismissprogressdialog intent in new intent setresult1 in finish return false catch exception e thismissprogressdialog finish the progressdialog is thismissed only in videoviewsetonpreparedlistener and videoviewsetonerrorlistener but the progressdialog is not getting thismissed and video is not getting played i tried to put logs and see logs are printed upto just before videoviewsetonpreparedlistener and after that no logs are thisplayed listeners are not getting registered i guess any help is appreciatedthanks in advanceeditm trying to stream a live video if video is availbale it should go to videoviewsetonpreparedlistener and should play the video if live is not availableie video will be live after some time then it should go to videoviewsetonerrorlistener and return to previous activity with result 1andvideo is streamed over rtsp,['android'] +908388,getting error while decryptition of saml token i am getting error while decryption of saml token however this issue is not consistent it works after restarting server it was working properly till last night debug decrypter631 attempt to decrypt encryptedkey using credential from kek keyinfo resolver failed orgopensamlxmlencryptiondecryptionexception probable runtime exception on decryptionunknown parameter type at orgopensamlxmlencryptiondecrypterdecryptkeydecrypterjava705 at orgopensamlxmlencryptiondecrypterdecryptkeydecrypterjava628 at orgopensamlxmlencryptiondecrypterdecryptusingresolvedencryptedkeydecrypterjava783 at orgopensamlxmlencryptiondecrypterdecryptdatatodomdecrypterjava524 at orgopensamlxmlencryptiondecrypterdecryptdatatolistdecrypterjava442 at orgopensamlxmlencryptiondecrypterdecryptdatadecrypterjava403 at orgopensamlsaml2encryptiondecrypterdecryptdatadecrypterjava141 at orgopensamlsaml2encryptiondecrypterdecryptdecrypterjava69 at orgspringframeworksecuritysamlwebssowebssoprofileconsumerimplprocessauthenticationresponsewebssoprofileconsumerimpljava199 at orgspringframeworksecuritysamlsamlauthenticationproviderauthenticatesamlauthenticationproviderjava82 at orgspringframeworksecurityauthenticationprovidermanagerauthenticateprovidermanagerjava156 at orgspringframeworksecuritysamlsamlprocessingfilterattemptauthenticationsamlprocessingfilterjava84 at orgspringframeworksecuritywebauthenticationabstractauthenticationprocessingfilterdofilterabstractauthenticationprocessingfilterjava195 at orgspringframeworksecuritywebfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava342 at orgspringframeworksecuritywebfilterchainproxydofilterinternalfilterchainproxyjava192 at orgspringframeworksecuritywebfilterchainproxydofilterfilterchainproxyjava166 at orgspringframeworksecuritywebfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava342 at orgspringframeworksecuritywebcontextsecuritycontextpersistencefilterdofiltersecuritycontextpersistencefilterjava87 at orgspringframeworksecuritywebfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava342 at orgspringframeworksecuritysamlmetadatametadatageneratorfilterdofiltermetadatageneratorfilterjava87 at orgspringframeworksecuritywebfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava342 at orgspringframeworksecuritywebfilterchainproxydofilterinternalfilterchainproxyjava192 at orgspringframeworksecuritywebfilterchainproxydofilterfilterchainproxyjava160 at orgspringframeworkwebfilterdelegatingfilterproxyinvokedelegatedelegatingfilterproxyjava346 at orgspringframeworkwebfilterdelegatingfilterproxydofilterdelegatingfilterproxyjava259 at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava241 at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava208 at orgapachecatalinacorestandardwrappervalveinvokestandardwrappervalvejava220 at orgapachecatalinacorestandardcontextvalveinvokestandardcontextvalvejava122 at orgapachecatalinaauthenticatorauthenticatorbaseinvokeauthenticatorbasejava503 at orgapachecatalinacorestandardhostvalveinvokestandardhostvalvejava170 at orgapachecatalinavalveserrorreportvalveinvokeerrorreportvalvejava103 at orgapachecatalinavalvesaccesslogvalveinvokeaccesslogvalvejava950 at orgapachecatalinacorestandardenginevalveinvokestandardenginevalvejava116 at orgapachecatalinaconnectorcoyoteadapterservicecoyoteadapterjava421 at orgapachecoyotehttp11abstracthttp11processorprocessabstracthttp11processorjava1070 at orgapachecoyoteabstractprotocolabstractconnectionhandlerprocessabstractprotocoljava611 at orgapachetomcatutilnetjioendpointsocketprocessorrunjioendpointjava314 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava1145 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava615 at orgapachetomcatutilthreadstaskthreadwrappingrunnableruntaskthreadjava61 at javalangthreadrunthreadjava745 caused by javalangillegalargumentexception unknown parameter type at orgbouncycastlejceproviderjcersacipherengineinitunknown source at javaxcryptocipherimplinitcipherjava791 at javaxcryptocipherchooseprovidercipherjava849 at javaxcryptocipherinitcipherjava1348 at javaxcryptocipherinitcipherjava1282 at orgapachexmlsecurityencryptionxmlcipherdecryptkeyxmlcipherjava1475 at orgopensamlxmlencryptiondecrypterdecryptkeydecrypterjava697 41 more 092151120 error decrypter639 failed to decrypt encryptedkey valid decryption key could not be resolved 092151120 debug decrypter787 attempt to decrypt encrypteddata using key extracted from encryptedkey faileearlier i was getting invalide key size error which i fixed with the help of spring saml adfs javasecurityinvalidkeyexception however i am not sure whether it will have any impact on us security policy lawbut this decrypt exception is not getting resolved and its not consistent some time it starts working after restarting serveri tried each and everything in last 23 days i thought issue occurs after metadata refresh so i tried adding below property to resourcebackedmetadataprovider bean but no luckproperty nameparserpool refparserpoolproperty nameminrefreshdelay value120property namemaxrefreshdelay value30then i debug webssoprofileconsumerimpljava code thought this mught be the issue related to jira so i checkout the latest code and create new jar and added to my project but no luck,['java'] +908406,animate a cashapelayer circle into a roundedcorner triangle i would like to animate a shape as it transitions from a circle to a roundedcorner triangletldr how do i animate a cashapelayers path between two cgpath shapes i know that they need to have the same number of control points but i think i am doing that whats wrong with this codethe beginning and end states would look something like thisheres what i have tried so far i am using a cashapelayer and animating a change in its path propertyaccording to the documentation emphasis minethe path object may be animated using any of the concrete subclasses of capropertyanimation paths will interpolate as a linear blend of the online points offline points may be interpolated nonlinearly eg to preserve continuity of the curves derivative if the two paths have a different number of control points or segments the results are undefinedin an attempt to get the circle and triangle to have the same number of control points i made them both fourpointed shapes the circle is a heavilyrounded rectangle and the triangle is hiding a fourth control point on one sideheres my codeselfviewbackgroundcolor bluecolorcreate a cashapelayerlet shape cashapelayershapeframe cgrectx 50 y 50 width 200 height 200shapefillcolor uicolorredcolorcgcolorselfviewlayeraddsublayershapelet bounds shapeboundscreate the squirclelet squareradius cgfloat cgrectgetwidthshapebounds2let topcorner cgpointmakeboundsmidx boundsminylet rightcorner cgpointmakeboundsmaxx boundsmidylet bottomcorner cgpointmakeboundsmidx boundsmaxylet leftcorner cgpointmakeboundsminx boundsmidylet squarepath cgpathcreatemutablelet squarestartingpoint midpointleftcorner point2 topcornercgpathmovetopointsquarepath nil squarestartingpointx squarestartingpointyaddarctopointsquarepath aroundpoint topcorner onwaytopoint rightcorner radius squareradiusaddarctopointsquarepath aroundpoint rightcorner onwaytopoint bottomcorner radius squareradiusaddarctopointsquarepath aroundpoint bottomcorner onwaytopoint leftcorner radius squareradiusaddarctopointsquarepath aroundpoint leftcorner onwaytopoint topcorner radius squareradiuscgpathclosesubpathsquarepathlet square uibezierpathcgpath squarepathcreate the faked trianglelet triangleradius cgfloat 250let trianglepath cgpathcreatemutablelet trianglestartingpoint midpointtopcorner point2 rightcornerlet startingpoint midpointtopcorner point2 leftcornercgpathmovetopointtrianglepath nil startingpointx startingpointylet cheatpoint midpointtopcorner point2bottomcorneraddarctopointtrianglepath aroundpoint topcorner onwaytopoint cheatpoint radius triangleradiusaddarctopointtrianglepath aroundpoint cheatpoint onwaytopoint bottomcorner radius triangleradiusaddarctopointtrianglepath aroundpoint bottomcorner onwaytopoint leftcorner radius triangleradiusaddarctopointtrianglepath aroundpoint leftcorner onwaytopoint topcorner radius triangleradiuscgpathclosesubpathtrianglepathlet triangle uibezierpathcgpath trianglepathshapepath squarecgpathand later on in viewdidappearlet animation cabasicanimationkeypath pathanimationfromvalue selfsquarecgpathanimationtovalue selftrianglecgpathanimationduration 3selfshapepath selftrianglecgpathselfshapeaddanimationanimation forkey animationkeyi have two quick little functions for making the code more legiblefunc addarctopointpath cgmutablepath aroundpoint cgpoint onwaytopoint cgpoint radius cgfloat cgpathaddarctopointpath nil aroundpointx aroundpointy onwaytopointx onwaytopointy radiusfunc midpointpoint1 cgpoint point2 cgpoint cgpoint return cgpointmakepoint1x point2x2 point1y point2y2my current result looks like thisnote i am trying to build the circle out of a veryrounded square in an attempt to get the same number of control points in the vector shape in the above gif the corner radius has been reduced to make the transformation more visiblewhat do you think is going on how else might i achieve this effect,['ios'] +908851,following html knit rmarkdown including block of white space i have working on journaling the visualization of some spatial data using raster and rmarkdown but am having a problem with there being a bunch of negative space above each figure here is the rmarkdown code somewhat simplifiedr global options includefalseknitropts chunksetfigwidth12 figheight8 echofalse warningfalse messagefalser rpackageslibrarymaptoolslibraryrasterlibraryrgdaldescription of datadata are taken from the national land cover database 2011 and represent land cover at a 30m x 30m resolutionlocation of data national land cover database 2011fnamenlcd 2006 landcover 2011 edition 2014 10 10zipimport raster file for us landcover and shapefile for state borders and countiesr import raster file for us landcoverrfile documentsdatanlcd 2006 landcover 2011 edition 2014 10 10nlcd 2006 landcover 2011 edition 2014 10 10img location of raster datar1 rasterrfileimport shapefile for state bordersstatepath documentsdatasetwdstatepathshp1 readogr statestransform shapefile to fit raster projectionshp1 sptransformshp1 r1crsremove hawaii and alasks which are not in raster imageshp1sub chawaiialaskastatessub shp1ascharactershp1state name in shp1sub import county datadata source 2011 us countyzipcountypath documentsdatatl 2011 us countysetwdcountypathshp2 readogr tl 2011 us countytransform shapefile to fit raster projectioncounties sptransformshp2 r1crscountiessub countiesascharactercountiesstatefp in statessubstate fips raster plot of us with state and county border overlaysr plot landcover with state bordersplot state borders over rasterplotr1plotcountiessub border darkgreylwd65addtplotstatessubborder darkblueaddtraster cropped and masked to extent of californiar crop raster to a single state californiashpsub ccaliforniashpca statessubascharacterstatessubstate name in shpsub r1crop cropr1 extentshpcaplotr1everything runs fine but when the markdown is output to html a bunch of white space is included as well heres the published rpub now solved i think this is a raster problem as i have not had this issue with figures for example in ggploti have been able to temporarily fix this by shrinking the image down but anytime i enlarge the picture to anything reasonable the extra space is added if anyone knows how to fix this it would be greatly appreciated,['html'] +908860,are older simdversions available when using newer ones when i can use sse3 or avx are then older sse versions as sse2 or mmx available or do i still need to check for them separately,"['c++', 'c']" +908861,define buildconfigfield for an specific flavor and buildtype i have 2 flavors lets say vanilla and chocolate i also have debug and release build types and i need vanilla release to have a field true while the other 3 combinations should be falsedef boolean booleandef variable variabledef true truedef false false vanilla debug buildconfigfield boolean variable false release buildconfigfield boolean variable true chocolate buildconfigfield boolean variable false i am having an error so i guess the debug and release trick doesnt work it is possible to do this,['android'] +908918,how to avoid thispatching in the middle of a thispatch within my flux architected react application i am retrieving data from a store and would like to create an action to request that information if it does not exist however i am running into an error where the thispatcher is already thispatching my desired code is something likegetall functionoptions options options var key jsonstringifyoptions var ratings dataratingskey if ratings ratingactionsfetchalloptions return ratings however intermittently fails when the thispatcher is already thispatching an action with the message invariant violation thispatchthispatch cannot thispatch in the middle of a thispatch i am often making requests in response to a change in application state eg date range my component where i make the request in response to a change event from the appstore has the followinggetstatefromstores function var dateoptions startdate appstoregetstartisostring enddate appstoregetenthisostring return ratings ratingstoregetalldateoptions i am aware that event chaining is a flux antipattern but i am unsure what architecture is better for retrieving data when it does not yet exist currently i am using this terrible hackgetall functionoptions options options var key jsonstringifyoptions var ratings dataratingskey if ratings settimeoutfunction if ratingactionsthispatcheristhispatching ratingactionsfetchalloptions 0 return ratings what would be a better architecture that avoids event chaining or the thispatcher error is this really event chaining i just want to change the data based on the parameters the application has setthanks,['javascript'] +909101,did boostoptionals implicit cast to bool go away i started porting a vc10boost 148 codebase to vc12boost 157 and i am getting an error that boostoptional cannot convert to bool i thought this was a feature of boostoptional did it get removedexamplebool fizz boostoptionalint32 t buzz return buzzgiveserror 21 error c2440 return cannot convert from boostoptionalint32 t to bool,['c++'] +909116,is it possible to use angular with the jinja2 template engine i have a flask site and i want to use the angular javascript framework unfortunately it seems as if the delimiters overlap how do i use angular with jinja2 if both rely on double curly braces expr is it even possible,['python'] +909294,why does 0 cause a syntax error this is weird this is what happens at the javascript console in chrome version 42023135 64bit 0 0 00 0 00 0 0x uncaught syntaxerror unexpected numberfirefox 3702 does the same although its error message issyntaxerror missing before statementthere is probably some technical explanation regarding the way javascript parses numbers and perhaps it can only happen when tinkering at the console prompt but it still seems wrongwhy does it do that,['javascript'] +909311,ios coreplot scroll does not work well using coreplot version 16running ios 83i am using coreplot with scatterplot for to represent multiples lineswhen i scroll the graph moves to jumps and it locks i do not know what happens can you help mehere my codeimport uikituikithimport coreplotcocoatouchhinterface temporallineviewcontrolleruiviewcontrollercptplotdatasourcecptscatterplotdelegateproperty strong nonatomic iboutlet cptgraphhostingview hostingviewendinterface temporallineviewcontroller nsmutabledictionary datesproperty nonatomic readwrite strong nsarray plotdataendimplementation temporallineviewcontrollercptgraph creategraph initwithframecgrectmakeviewgraphframeoriginx viewgraphframeoriginy 500 viewgraphframesizeheight cptgraph graph cptxygraph alloc initwithframehostingviewbounds graph applythemecpttheme themenamedkcptslatetheme hostingviewhostedgraphgraph axes cptxyaxisset axisset cptxyaxisset graphaxisset cptxyaxis x axissetxaxis xmajorintervallength cptdecimalfromdoubleoneday xorthogonalcoordinatedecimal cptdecimalfromdouble00 xminorticksperinterval 0 nsdateformatter dateformatter nsdateformatter alloc init dateformatter setdateformatddmmy cpttimeformatter timeformatter cpttimeformatter alloc initwithdateformatterdateformatter timeformatterreferencedate nsdate allocinit xlabelformatter timeformatter xlabelrotation cptfloatm pi 4 cptxyaxis y axissetyaxis yhiddenyes yorthogonalcoordinatedecimal cptdecimalfromint0 return graphvoidcreatescatterplot cptgraph graph self creategraph cptxyplotspace plotspace cptxyplotspace graphdefaultplotspace nstimeinterval xlow 00 plotspacexrange cptplotrange plotrangewithlocationcptdecimalfromdoublexlow lengthcptdecimalfromdoubleoneday 100 plotspaceyrange cptplotrange plotrangewithlocationcptdecimalfromdouble1 lengthcptdecimalfromdouble50 plotspaceallowsuserinteraction yes plotspaceallowsmomentum yes cptscatterplot diagnosticplot self createscatterplotwithidentifierdiagnostic plot withlinecolorcptcolor greencolor withfillcolorcptcolor greencolor cptscatterplot vaccineplot self createscatterplotwithidentifiervaccine plot withlinecolorcptcolor blackcolor withfillcolorcptcolor blackcolor cptscatterplot interventionplot self createscatterplotwithidentifierintervention plot withlinecolorcptcolor bluecolor withfillcolorcptcolor bluecolor cptscatterplot smokinghabitplot self createscatterplotwithidentifiersmoking habit plot withlinecolorcptcolor yellowcolor withfillcolorcptcolor yellowcolor cptscatterplot menstrualplot self createscatterplotwithidentifiermenstrual plot withlinecolorcptcolor redcolor withfillcolorcptcolor redcolor cptscatterplot menstrualtreatmentplot self createscatterplotwithidentifiermenstrual treatment plot withlinecolorcptcolor orangecolor withfillcolorcptcolor orangecolor cptscatterplot psychomotormilestoneplot self createscatterplotwithidentifierpsychomotor milestone plot withlinecolorcptcolor purplecolor withfillcolorcptcolor purplecolor graph addplotvaccineplot toplotspaceplotspace graph addplotdiagnosticplot toplotspaceplotspace graph addplotinterventionplot toplotspaceplotspace graph addplotsmokinghabitplot toplotspaceplotspace graph addplotmenstrualplot toplotspaceplotspace graph addplotmenstrualtreatmentplot toplotspaceplotspace graph addplotpsychomotormilestoneplot toplotspaceplotspace cptscatterplot createscatterplotwithidentifiernsstring identifier withlinecolorcptcolor linecolor withfillcolorcptcolor fillcolor cptscatterplot datasourcelineplot cptscatterplot alloc init datasourcelineplotidentifier identifier cptmutablelinestyle linestyle datasourcelineplotdatalinestyle mutablecopy linestylelinewidth 30 linestylelinecolor linecolor datasourcelineplotdatalinestyle linestyle cptplotsymbol plotsymbol2 cptplotsymbol ellipseplotsymbol plotsymbol2fill cptfill fillwithcolorfillcolor plotsymbol2size cgsizemake100 100 datasourcelineplotplotsymbol plotsymbol2 return datasourcelineplotvoidgeneratedata nsmutablearray data nsmutablearray array data addobjectself creatediagnosticdata data addobjectself createvaccinedata data addobjectself createinterventiondata data addobjectself createsmokinghabitdata data addobjectself createmenstrualdata data addobjectself createmenstrualtreatmentdata data addobjectself createpsychomotormilestonedata selfplotdata datapragma mark pragma mark plot data source methodsnsuintegernumberofrecordsforplotcptplot plot nslognumberofrecordsforplot if plotidentifier isequaldiagnostic plot nsmutablearray data selfplotdata0 return datacount else ifplotidentifier isequalvaccine plot nsmutablearray data selfplotdata1 return datacount else ifplotidentifier isequalintervention plot nsmutablearray data selfplotdata2 return datacount else ifplotidentifier isequalsmoking habit plot nsmutablearray data selfplotdata3 return datacount else ifplotidentifier isequalmenstrual plot nsmutablearray data selfplotdata4 return datacount else ifplotidentifier isequalmenstrual treatment plot nsmutablearray data selfplotdata5 return datacount else ifplotidentifier isequalpsychomotor milestone plot nsmutablearray data selfplotdata6 return datacount return 0idnumberforplotcptplot plot fieldnsuintegerfieldenum recordindexnsuintegerindex nslognumberforplot if plotidentifier isequaldiagnostic plot nsmutablearray data selfplotdata0 nsstring str nsstring stringwithformatdataindexfieldenum if str intvalue0 return nil return dataindexfieldenum else ifplotidentifier isequalvaccine plot nsmutablearray data selfplotdata1 nsstring str nsstring stringwithformatdataindexfieldenum return dataindexfieldenum else ifplotidentifier isequalintervention plot nsmutablearray data selfplotdata2 nsstring str nsstring stringwithformatdataindexfieldenum return dataindexfieldenum else if plotidentifier isequalsmoking habit plot nsmutablearray data selfplotdata3 nsstring str nsstring stringwithformatdataindexfieldenum if str intvalue0 return nil return dataindexfieldenum else if plotidentifier isequalmenstrual plot nsmutablearray data selfplotdata4 nsstring str nsstring stringwithformatdataindexfieldenum if str intvalue0 return nil return dataindexfieldenum else if plotidentifier isequalmenstrual treatment plot nsmutablearray data selfplotdata5 nsstring str nsstring stringwithformatdataindexfieldenum if str intvalue0 return nil return dataindexfieldenum else ifplotidentifier isequalpsychomotor milestone plot nsmutablearray data selfplotdata6 nsstring str nsstring stringwithformatdataindexfieldenum return dataindexfieldenum return nil,['ios'] +909376,blank frame on merging videos using avmutablecomposition this question has been asked many times before but nothing helped me i am merging multiple videos using avmutablecomposition after merging videos i get blank frames in between 30 40 of the videos others merge fine i just play the composition directly using avplayer as an avplayeritem code is belowavmutablecomposition mutablecomposition avmutablecomposition composition avmutablecompositiontrack videocompositiontrack mutablecomposition addmutabletrackwithmediatypeavmediatypevideo preferredtrackidkcmpersistenttrackid invalid avmutablecompositiontrack audiocompositiontrack mutablecomposition addmutabletrackwithmediatypeavmediatypeaudio preferredtrackidkcmpersistenttrackid invalid nsmutablearray instructions nsmutablearray new cgsize size cgsizezero cmtime time kcmtimezero for avurlasset asset in assets avassettrack assettrack assettrack asset trackswithmediatypeavmediatypevideo objectatindex0 avassettrack audioassettrack asset trackswithmediatypeavmediatypeaudiofirstobject nserror error videocompositiontrack inserttimerangecmtimerangemakekcmtimezero assettracktimerangeduration oftrackassettrack attimetime errorerror if error nslogasset url assettrackasset nslogerror errordebugdescription audiocompositiontrack inserttimerangecmtimerangemakekcmtimezero assettracktimerangeduration oftrackaudioassettrack attimetime errorerror if error nslogerror errordebugdescription avmutablevideocompositioninstruction videocompositioninstruction avmutablevideocompositioninstruction videocompositioninstruction videocompositioninstructiontimerange cmtimerangemaketime assettracktimerangeduration videocompositioninstructionlayerinstructions avmutablevideocompositionlayerinstruction videocompositionlayerinstructionwithassettrackvideocompositiontrack instructions addobjectvideocompositioninstruction time cmtimeaddtime assettracktimerangeduration if cgsizeequaltosizesize cgsizezero size assettracknaturalsize avmutablevideocomposition mutablevideocomposition avmutablevideocomposition videocomposition mutablevideocompositioninstructions instructions mutablevideocompositionframeduration cmtimemake1 30 mutablevideocompositionrendersize size playeritem avplayeritem playeritemwithassetmutablecomposition playeritemvideocomposition mutablevideocomposition,"['ios', 'objective-c']" +909385,phpmailer generates php warning stream socket enable crypto peer certificate did not match expected i am using phpmailer on php 56 the increased security around certificated in php 56 is certainly funi am trying to send a test message to a domain hosted on dreamhost the error that comes back from phpmailer is could not connect to smtp hostthat error is not right though i have logging enabled and here is what is actually going onconnection opening to mx1sub4homiemaildreamhostcom25 timeout30 optionsarray connection opened s 220 homiemailmx32gdreamhostcom esmtpc ehlo s81aikbbcoms 250homiemailmx32gdreamhostcom 250pipelining 250size 40960 250etrn 250starttls 250enhancedstatuscodes 250 8bitmimec starttlss 220 200 ready to start tlsc quits smtp error quit command failed connection closedi could not understand why phpmailer just gives up issuing a quit command when it should start sending the message i got another clue from another logphp warning stream socket enable crypto peer certificate cnmaildreamhostcom did not match expected cnmx1sub4homiemaildreamhostcom in homeikbbdomainsdevikbbcompublic htmlincludesphpmailer5210clasmtpphpif i use some custom options to prevent validation of the cert they are using i can get it to continue here is what i have mailsmtpoptions array ssl array verify peer false verify peer name false allow self signed trueif i put the smtpoptions in there and skip the peer verification message goes ok with no warning in php at allhow can i trap that error so i know there is an issue but still send the message,['php'] +909397,is abpeoplepickernavigationcontroller slow when using abpeoplepickernavigationcontroller it takes a moment 05 sec to load and thisplay the control which is slower than the normal reaction time of other popupsi came with the solution set the controller as a variable and access this preloaded object viaself presentviewcontrollerselfpeoplepicker animatedyes completionniljust out of curiosity is there another way to fire up the picker without preloading it,['ios'] +909471,function template receiving any standard map i am writing a function that should receive one of stdmap stdmultimap stdunordered map or stdunordered multimap my code is as followtemplatetemplate class class class map typename coord inline typename stdenable ifstdis arithmeticcoordvaluetype filtermapcoord coord map coord step 2 for auto it stdbeginmap it stdendmap if itsecond itfirst step it maperaseit else it the template template parameter map does not generalize for all types of maps the stdmap and stdmultimap receive four template parameters and stdunordered map and stdunordered multimap receive five template parameters this implies that i can not solve the problem with a template template parameter is there any way to solve this with the constraint that all maps must have keytype valetype coord i would not like to specify explicitly the parameters types in a call to filter,['c++'] +909549,on linux is tls set up by the kernel or by libc or other language runtime i am just studying how tls threadlocal storage is implemented on linux systems the document elf handling for threadlocal storage explains how a programs requirements for threadlocal variables can be encoded in an elf binary and how the runtime should handle such binarieshowever it is not clear to me whether in practice the runtime which sets up the tls areas will be the linux kernel and its code for loading elf binaries or some initialization code in libc could someone explain brieflybackground i am trying to staticallylink and run an application but it segfaults on start in gdb i can see the segfaulting code is some init code from libc it is trying to read a static variable using an address relative to gs but gs is zero,['c'] +909579,what does it mean when one language is a parallel superset of another i am reading a journal article about realtime concurrent c and it mentions in the abstract so any of you can see the context through that link as well that concurrent c is a parallel superset of c and of c now i know what a superset is but what do they mean by a parallel superset when referring to programming languages,"['c++', 'c']" +909670,visual studio 2015 autocollapse regions and inactive code in every version of visual studio up to 2013 code wrapped in regions and inactive code in if statements are automatically collapsed when you open a c code file for the first time when enter outlining mode when files open is enabledi am trying to figure out how to enable this in visual studio 2015 rc but even turning on enter outlining mode when files open does not seem to have any effect if anything it seems that the file opens and then vs activates outlining mode a split second later without checking to see if anything needs to be collapsed,['c#'] +909701,caesar cipher in javascript using shiftchar function and arraymap method i am attempting to learn javascript by reading through a lot of online tutorials and am practicing by working through the challenges on coderbyte i am having trouble with the caesarcipher challenge the function needs to take a string and an offset parameter and then return the string with each alpha character shifted by whatever offset was provided leaving any nonalpha characters intact i have got my shiftchar function working which will take the char and the offset and will apply the shift only for alpha characters and will return the new character now that that is complete i thought i would be able to just take the original string split it into an array and then map that array of chars to a new array using my shiftchar function however i cannot get it to work and i cannot seem to figure out why is there something i am missing about the map method my understanding is that the map method will automatically pass each element in the array it is called on as the first argument then i am just passing my offset value as an additional argument can someone please shed some light as to why this is not working and suggest a more workable approachusing the javascript language have the function caesarcipherstrnum take the str parameter and perform a caesar cipher shift on it using the num parameter as the shifting number a caesar cipher works by shifting each letter in the string and places down in the alphabet in this case and will be num punctuation spaces and capitalization should remain intact for example if the string is caesar cipher and num is 2 the output should be ecguct ekrjgt var str caesar cipherfunction caesarcipherstr offset var chararray strsplit var result chararraymap shiftchar char offset join function shiftcharchar offset var isalpha az ifisalphatestchar char stringfromcharcodecharcharcodeat0 offset ifchar z char a char z char stringfromcharcodecharcharcodeat0 26 return char return resultconsolelogcaesarcipher str 2,['javascript'] +909711,could not cast value of type nsarraym 0x34df0900 to nsdictionary swift when decoding json response from webservice i get an error sayingcould not cast value of type nsarraym 0x34df0900 to nsdictionaryi tried out so many solutions found in stackoverflow too but nothing worksmy code let jsondatansdictionary nsjsonserializationjsonobjectwithdataurldata optionsnsjsonreadingoptionsmutablecontainers error error as nsdictionarylet successnsinteger jsondatavalueforkeysuccess as nsintegerresponse from the web service id 1 title bmw price 50 description 330 addeddate 20150518 0 user id 1 user name canovas user zipcode 32767 category id 1 category label vehicules subcategory id 2 subcategory label motos bdd thank you for your help,['ios'] +909853,position imagesbackground images relative to mouse i would like to know what an efficient way is to animate positions of images or background images in relation to the mouse take github for examplethis is one hella sexy 404 pagei want to make an impact on my users and this surely does so in my opinionquestions1 how can this be done2 just css css js3 lastly any libraries for stuff like this,"['javascript', 'css']" +909894,codeigniter htaccess giving 404 page not found files are in a subfolder when i uploaded my file i uploaded them in shared hosting the thing is that the files and folders for my codeigniter are in one of those website name foldersit gives me a 404 error when i visit the sitemy htacces fileifmodule mod rewritec rewriteengine on rewritebase removes access to the system folder by users additionally this will allow you to create a systemphp controller previously this would not have been possible system can be replaced if you have renamed your system folder rewritecond request uri system rewriterule indexphp1 l when your application folder is not in the system folder this snippet prevents user access to the application folder submitted by fabdrol rename application to your applications folder name rewritecond request uri application rewriterule indexphp1 l checks to see if the user is attempting to access a valid file such as an image or css document if this is not true it sends the request to indexphp rewritecond request filename f rewritecond request filename d rewriterule indexphp1 lifmoduleifmodule mod rewritec errordocument 404 indexphpifmodulei really do not know what to do any help is appreicated thanksedit when i edit the indexphp file and just put something like echo hey and delete the htaccess file it works fine,['php'] +909918,sending a c array to python and back extending c with numpy i am going to send a c array to a python function as numpy array and get back another numpy array after consulting with numpy documentation and some other threads and tweaking the code finally the code is working but i would like to know if this code is written optimally considering theunnecessary copying of the array between c and numpy pythoncorrect dereferencing of the variableseasy straightforward approachc code python embedcpp defines the entry point for the console applicationinclude stdafxhdefine npy no deprecated api npy 1 7 api versioninclude pythonhinclude numpyarrayobjecthincludeiostreamusing namespace stdint tmainint argc tchar argv py setprogramnameargv0 py initialize import array build the 2d array pyobject pargs preturn pmodule pfunc pyarrayobject np ret np arg const int size 10 npy intp dims2size size const int nd 2 long doublec arrsize new long doublesizesize long double c out for int i i size i for int j j size j c arrij i size j np arg reinterpret castpyarrayobjectpyarray simplenewfromdatand dims npy longdouble reinterpret castvoidc arr calling array tutorial from mymodule pyobject pname pyunicode fromstringmymodule pmodule pyimport importpname py decrefpname if pmodule cout mymodule can not be imported endl py decrefnp arg delete c arr return 1 pfunc pyobject getattrstringpmodule array tutorial if pfunc pycallable checkpfunc py decrefpmodule py xdecrefpfunc py decrefnp arg delete c arr cout array tutorial is null or not callable endl return 1 pargs pytuple new1 pytuple setitempargs 0 reinterpret castpyobjectnp arg preturn pyobject callobjectpfunc pargs np ret reinterpret castpyarrayobjectpreturn if pyarray ndimnp ret nd 1 row0 is returned cout function returned with wrong dimension endl py decrefpfunc py decrefpmodule py decrefnp arg py decrefnp ret delete c arr return 1 int len pyarray shapenp ret0 c out reinterpret castlong doublepyarray datanp ret cout printing output array endl for int i i len i cout c outi cout endl finalizing py decrefpfunc py decrefpmodule py decrefnp arg py decrefnp ret delete c arr py finalize return 0in codereview there is a fantastic answer link,"['python', 'c++']" +909948,facebook oncompleted email javalangnullpointerexception i am able to get all those things as shown in my code below but unable to retrieve email from the user profilewhat can i do for thisany kind of help will be appreciatedearlier i was using this source to get details of facebook user and was fetching data including email without any troublepublic class mainactivity extends activity private sessionstatuscallback sessionstatuscallback private session currentsession private button login private button logout private button publishbutton private textview textview override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main textview textview findviewbyidridtextview create instace for sessionstatuscallback sessionstatuscallback new sessionstatuscallback override public void callsession session sessionstate state exception exception onsessionstatechangesession state exception login button findviewbyidridloginbutton loginsetonclicklistenernew onclicklistener override public void onclickview v connecttofb logout button findviewbyidridlogoutbutton logoutsetonclicklistenernew onclicklistener override public void onclickview v if currentsession null currentsessioncloseandcleartokeninformation publish button publishbutton button findviewbyidridpublishbutton publishbuttonsetonclicklistenernew onclicklistener override public void onclickview v publishstory public void connecttofb liststring permissions new arrayliststring permissionsaddpublish actions currentsession new sessionbuilderthisbuild currentsessionaddcallbacksessionstatuscallback sessionopenrequest openrequest new sessionopenrequest mainactivitythis openrequestsetloginbehaviorsessionloginbehaviorsuppress sso openrequestsetrequestcodesessiondefault authorize activity code openrequestsetpermissionspermissions currentsessionopenforpublishopenrequest override public void onactivityresultint requestcode int resultcode intent data superonactivityresultrequestcode resultcode data if currentsession null currentsession onactivityresultthis requestcode resultcode data private void onsessionstatechangesession session sessionstate state exception exception if session currentsession return if stateisopened log in just happened toastmaketextgetapplicationcontext session opened toastlength shortshow requestexecutemerequestasyncsession new requestgraphusercallback override public void oncompletedgraphuser user response response string fbid usergetid string fbname usergetname string gender userasmapgetgendertostring string email userasmapgetemailtostring string first userasmapgetfirst nametostring string last userasmapgetlast nametostring textviewsettextid fbid name fbname gender gender emailid email first first last last else if stateisclosed log out just happened update the ui toastmaketextgetapplicationcontext session closed toastlength shortshow public void publishstory and now i am using same code in one of my project but always getting eandroidruntimei1 fatal exception mainjavalangnullpointerexception at commainactivity5oncompletedmainactivityjava262at comfacebookrequest1oncompletedrequestjava303at comfacebookrequest4runrequestjava1726at androidoshandlerhandlecallbackhandlerjava615at androidoshandlerthispatchmessagehandlerjava92at androidoslooperlooplooperjava137at androidappactivitythreadmainactivitythreadjava4921at javalangreflectmethodinvokenativenative methodat javalangreflectmethodinvokemethodjava511at this line i am getting npe string email userasmapgetemailtostringcodepublic class mainactivity extends activity button btnfblogin btngplogin private sessionstatuscallback sessionstatuscallback private session currentsession override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutscreen layout sessionstatuscallback new sessionstatuscallback override public void callsession session sessionstate state exception exception onsessionstatechangesession state exception btnfblogin button findviewbyidridloginfb btnfbloginsetonclicklistenernew onclicklistener override public void onclickview arg0 todo autogenerated method stub connecttofb public void connecttofb liststring permissions new arrayliststring permissionsaddpublish actions currentsession new sessionbuilderthisbuild currentsessionaddcallbacksessionstatuscallback sessionopenrequest openrequest new sessionopenrequest mainactivitythis openrequestsetloginbehaviorsessionloginbehaviorsuppress sso openrequestsetrequestcodesessiondefault authorize activity code openrequestsetpermissionspermissions currentsessionopenforpublishopenrequest override public void onactivityresultint requestcode int resultcode intent data superonactivityresultrequestcode resultcode data if currentsession null currentsession onactivityresultthis requestcode resultcode data private void onsessionstatechangesession session sessionstate state exception exception if session currentsession return if stateisopened log in just happened toastmaketextgetapplicationcontext session opened toastlength shortshow requestexecutemerequestasyncsession new requestgraphusercallback override public void oncompletedgraphuser user response response string fbid usergetid string fbname usergetname string gender userasmapgetgendertostring string email userasmapgetemailtostring string first userasmapgetfirst nametostring string last userasmapgetlast nametostring toastmaketextmainactivitythis emailid email toastlength longshow else if stateisclosed log out just happened update the ui toastmaketextgetapplicationcontext session closed toastlength shortshow what could be the reason why its happening,['android'] +909963,can i use gamepads with nodewebkit nwjs i am building a nwjs nodewebkit dashboard app which i want to be able to control with a game controller for example xbox 360 controller or logitech controller i am calling the following onready but when i debug its not recognizing any gamepadsangularelementdocumentreadyfunction ifcangame var prompt to begin using your gamepad connect it and press any button gamepadprompttextprompt windowongamepadconnected function gamepadprompthtmlgamepad connected consolelogconnection event windowongamepadthisconnected function consolelogthisconnection event gamepadprompttextprompt function cangame return getgamepads in navigatorwhen i debug the code it does not appear to be detecting any gamepads i also try navigatorwebkitgetgamepadsbut it does not show any gamepads being detected either has anyone successfully used gamepads with a nwjs app i would greatly appreciate some help getting this to work,['javascript'] +910010,wkwebview fails to load css styles when html code contains unicode chars i found a strange behavior in the wkwebview i use to load the html text from a file in the bundle and i also use a css file also in the bundlewhile this approach always works with uiwebview with the new wkwebview class it only works if the html text does not contain unicode chars like a u2013i have created a test project for that that demonstrates the issue attached a screenshot from thereas it is visible in the screenshot the webview2 in the middle of the device when the html text contains the a sign the thisplayed text is not styled as it should webview1 on the top if we load the same html from a remote server using the loadrequest call it works indeed webview3 on the bottomusing the uiwebview objects everything works fine insteadthe html used is this onestoryhtmlhtmlmeta charsetutf8link relstylesheet typetextcss hrefstylescss bodydiv123123divbodyhtmlstory failinghtmlhtmlmeta charsetutf8link relstylesheet typetextcss hrefstylescss body123a123bodyhtmlstylescssbody fontsize80pxcolor ff0,['ios'] +910036,how to declare generic multitype collection of generic handlers i always have hard time using generics with collections and wildcardsso here is the following map i want to keep collection of handlers for a specific type of packet classprivate concurrenthashmapclass extends packet listpacketlistener extends packet listeners new concurrenthashmapand the packetlistenerpublic interface packetlistenert extends packet public void onoutgoingpacketstreamer streamer t packet public void onincomingpacketstreamer streamer t packetnow what i would like to do is to get listeners depending on incoming packet class like thispublic t extends packet void addpacketlistenerclasst clazz packetlistenert listener if listenerscontainskeyclazz false listenersputifabsentclazz new linkedlistpacketlistenert error listpacketlistener extends packet list listenersgetclazz listaddlistenerpublic t extends packet listpacketlistenert getpacketlistenersclasst clazz listpacketlistenert list listenersgetclazz error if list null listisempty return null else return new arraylistlist and finally i would like to perform such invocationprivate t extends packet void notifylistenerst packet listpacketlistenert listeners streamergetpacketlistenerspacketgetclass if listeners null for packetlistener extends packet packetlistener listeners packetlisteneronincomingpacketstreamer packet all i am getting are just lot of errors is it because of wildcards in collection declaration is it possible to achieve such solution,['java'] +910078,unable to install apk using adb on device upgraded to android lollipop iave recently upgraded one of my android devices to android lollipop 50 and now i canat debug my application and even install apk on the device using adb i receive the following errorjavalangunsatisfiedlinkerror no implementation found for javalangstring androidossystempropertiesnative getjavalangstring javalangstring tried java android os systemproperties native 1get and java android os systemproperties native 1get ljava lang string 2ljava lang string 2 at androidossystempropertiesnative getnative method at androidossystempropertiesgetsystempropertiesjava64 at androidosenvironmentclinitenvironmentjava354 at androidosenvironmentgetlegacyexternalstoragedirectoryenvironmentjava488 at androidosdebugclinitdebugjava96 at androidmddmhandlehellohandleheloddmhandlehellojava164 at androidmddmhandlehellohandlechunkddmhandlehellojava91 at orgapacheharmonydalvikddmcddmserverthispatchddmserverjava171javalangunsatisfiedlinkerror androidosdebug at androidmddmhandlehellohandlefeatddmhandlehellojava176 at androidmddmhandlehellohandlechunkddmhandlehellojava93 at orgapacheharmonydalvikddmcddmserverthispatchddmserverjava171javalangunsatisfiedlinkerror androidosdebug at androidmddmhandleprofilinghandlemprqddmhandleprofilingjava187 at androidmddmhandleprofilinghandlechunkddmhandleprofilingjava88 at orgapacheharmonydalvikddmcddmserverthispatchddmserverjava171my device is asus fonepad 7 me175cg or k00zkernel version31020i386 cptandroidmec91mon apr 20 133008 cst 2015is there any solution for this problemupdatedfirst of all thanks to those guys who pay attention to this very specific question really thanksfor further clarificationwhen i received this error i googled the entire universe for the phrase javalangunsatisfiedlinkerror and gave a try to any solutions that seemed to be applicable as well as the solution that suggested by kushal and others most of the questions were and still are for htc m8 and devices other than asus if you visit this post you may see an answer by me which is deleted by so guards and i admit it that it was not really an answer and i post the answer while i was really thisappointed of resolving the issueanyway what i have done up to now which may be helpful for others arefirst i upgraded my android sdk tools to the latest version 242 after that when i tried adb install demoapk in some cases it was successful and sometimes not i killed all running apps on the device as suggested by some guys but it sometimes works and sometimes notthen i gave a try to other solution specifically the one that suggested by this post in fact when i try to debug the app using intellij idea the ide itself does as the suggested procedure and the result isyou can see that the ide itself does as the procedure by kushal suggestsafter that i found several records referring a few as here and here and in latter someone has said that this was a bug in some htc devices that was fixed with lmr1therefore i came up with the idea that there may be a fix by asus team which you guys know about it and kindly provide me with thatthanks,['android'] +910082,what causes long spin and sync times in java in java 8 update 45 adding these options to the java callxxprintgcapplicationstoppedtimexxprintsafepointstatisticsxxprintsafepointstatisticscount1shows me statistics like thesevmop threads total initially running wait to block time spin block sync cleanup vmop page trap count3679229 no vm operation 72 1 2 6016 0 6016 0 0 120150522t1125275190200 total time for which application threads were stopped 60168551 seconds stopping threads took 60164099 secondsthe problem here is the long time for stopping threads in this example it is 6 seconds which is already a problem for our application but i have seen even larger times in one instance without full logging though amounting to almost a minutethe vm operation here no vm operation is varying i have also seen eg revokebias g1inccollectionpause or gcg operation also the page trap count seems to be irrelevant i have seen examples where it was 0 and others where it was 2 consistent though is that the time always is reflected in the values of spin and synci am looking for an indepth explanation of those timing values spin and sync but mostly i am interested in why this is happening and what i can do against it i am not aware of anything evil in our configuration there are plenty of bored cores and unused memory on the machine we are running pure java no jni and we are not aware of any excessive synchronization in our code,['java'] +910199,listview overlay another layout when scroll actually i do not know how it properly called overlay parallax or slideup whatever i have an activity called cafe details which presents a containerlinearlayout with header information name min price delivery time min etc and other container viewpager which contains a expandablelistview with something information menusthishes and all i want to do is slide up my viewpager when scrolls listview to scpecific y position to coveror overlay header informationa similar effect but with parallax that i do not need to use looks like thisi can detect when user scrolling listview down or up but how i can move container with viewpager to overlay other container please give me ideas regardsupdi have tried a huge number of ways how to implement it and all of them unfortunately are not suitable so now i have come to next variant add scroll listener to listview calculate scrolly position of view and then based on that move the viewpager on y axis by calling settranslationy here is some code1 viewpagers fragment mlistviewsetonscrolistenernew abslistviewonscrolistener override public void onscrollstatechangedabslistview abslistview int i override public void onscrollabslistview abslistview int i int i1 int i2 if getactivity null mainactivity getactivityresizepagercontainerabslistview 2 mainactivityobject fieldsint previouspos private float mintranslationprivate float minheightsomewhere in oncreatemintranslation llvendordescheadersgetmeasuredheightllvendordescnotegetmeasuredheightllvendordescheaders is linearlayout with headers that should be hiddenlvendordescnote is a textview on green backgroundminheight llvendordescriptionpagercontainergetmeasuredheightllvendordescriptionpagercontainer is a container which contains viewpagerpublic void resizepagercontainerabslistview abslistview final int scrolly getscrollyabslistview if scrolly previouspos final float translationy mathmaxscrolly mintranslation llvendordescriptionpagercontainersettranslationytranslationy previouspos scrolly private int getscrollyabslistview view view child viewgetchildat0 if child null return 0 int firstvisibleposition viewgetfirstvisibleposition int top childgettop return top firstvisibleposition childgetheight this simple solution unfortunately has a problem it is blinking and twitching i do not know how to call it right when scrolls slowly so instead settranslationy i have used an objectanimatorpublic void resizepagercontainerabslistview abslistview objectanimator moveanim objectanimatoroffloatllvendordescriptionpagercontainer translationy translationy moveanimstart i do not like this solution because 1 anyway it does resize viewpager with delay not instantly 2 i do not think that is good idea to create many objectanimators objects every time when i scroll my listviewneed your help and fresh ideas regards,['android'] +910209,opengl water waves with noise i am currently in the process of making water waves so basically i am starting from the beginning i have created a mesh which is basically a flat square and have animated it in the vertex shader below is the code which achieves thatvtxy sin20 vtxx a time10 cos15 vtxy a time10 02basically just moving the y position based on a sin and cos function the results of this can be observed herei then tried adding some perlin noise as per the perlin noise functions by ian mcewan available here githubcomashimawebglnoise as followsvtxy vtxy 01cnoisea time50a vertexyzthe results of this can be observed hereas you can plainly observe there is no real random effect that i was looking for simulate some basic random roughness of an ocean i was wondering how it would be possible for me to achieve this also any suggestions on how to improve either of the functions that change y would also be appreciated,['c++'] +910266,laravel 5 charset not working correctly on the views but it working well when i dump it from controller i am facing a charset problem here i am developing an app that uses a sql server database the database was not created for this app it exists before it and works very well i cannot change anything on the database because its too large and its used by many other appsi have been finished the auth of my laravel 5 app so i will create a view and show in this view the name of logged user the name is administrador da acentuao it use some special charactersin my viewsauthusername it shows administrador da acentuai12i12obut in my controller before i return the view i diddieauthusernameand it shows me administrador da acentuaoi try now do it in my view file authusernamephp dieand this works fine it shows meadministrador da acentuaoit makes me believe the error occours for something laravel does after the views are parsedi do not know why it works well when i die the user name on the controller but not works when i echo its name on the viewmay anyone help me plzpsmy view file is using utf8 charseti tried to echo with and without html tags and charset meta the problem occours on both casesi tried to delete my view file and create a new one with utf8 charset it does not worki tried to use php echo authusername instead blade tags it does not work,['php'] +910418,how can i change the dots to another character on password field in ios swift i have a text field and i would like to replace the default dot character to something else when the password is hidden is there any way to do this easily,['ios'] +910484,android studio how can i make an avd with arm instead of haxm i am new to android studio using version 1211 my computer does not support haxm so it would not let me install that to use for virtualization in some similar questions on this website people mention setting up a virtual device with an arm instead of haxm how can i do this in the avd manager all of the premade hardware profiles use haxm and when i click new hardware profile i do not see any option to use arm i looked in the sdk manager and for api 22 i have installed arm eabi v7a system image and google apis arm eabi v7a system image are those what i need how can i create a custom virtual phone with arm or is there a way i can use one of the preexisting hardware devices with arm instead of haxm,['android'] +910620,angular uirouter dynamic routing based on slug from api ajax call load view based on slug examples slugs in server database accessible through apislug johnsmithtype userslug microsofttechnologiestype companyscenario 1 user view controller httplocalhostjohnsmithstateuser url user templateurl partialuserhtml controller userctrlscenario 2 company view controller httplocalhostmicrosofttechnologiesstatecompany url company templateurl partialcompanyhtml controller companyctrlnow i want to make make a dynamic state based the slug getting from api call to the serveri written a imaginary code but i am not getting way to achieve example url httplocalhostjohnsmithstatehybrid johnsmith url slug templateurl function return partialtypehtml controllerprovider function rt return typecontroller resolove type function http stateparams httpget method get url httplocalhostapi stateparamsslug successfunctionresponse status headers config response slug johnsmithtype user return responsetype return,['javascript'] +910680,how to search json data in mysql i am inserting my data in a database with json encodednow i want to search in feature but i cannotmysql queryselect id attribs json from products where attribs json regexp 1value3this query shows me all rows with key 1 and value is any thing not value is 3my data isfeature1value23 2value1 5value 3value1 9value 4valueu0633u0627u062au0646 6value 7value 8value show counter0show counter thiscount,"['php', 'mysql']" +910709,rails uniq public activity t publicactivityactivityarel tableactivities publicactivityactivitywhere ttrackable typeeqlessonandttrackable idinmy lessons ids orttrackable typeeqpostandttrackable idinmy posts ids orttrackable typeeqwallpostandttrackable idinmy wallposts ids orttrackable typeeqcommentandttrackable idinmy comments ids orttrackable typeeqcourseandttrackable idinmy courses ids orttrackable typeeqgroupandttrackable idinmy groups idsorderid descuniqa atrackable typeatrackable idin my database i have duplicate entries for trackable typetrackable id because if a user click on update many times i get many entriesso i want only to get one of these i tried with uniqa atrackable typeatrackable idbut nothing happensreturned sql queryselect thistinct activities from activities where activitiestrackable type lesson and activitiestrackable id in 11 39 40 16 5 3 12 9 13 19 18 37 15 23 24 29 20 10 25 26 27 17 28 22 21 30 33 35 34 36 32 31 or activitiestrackable type post and activitiestrackable id in 50 49 48 47 46 45 44 43 42 41 40 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 14 13 12 10 5 or activitiestrackable type wallpost and activitiestrackable id in 158 157 155 154 153 152 151 132 131 130 129 128 127 126 125 124 119 118 117 116 115 114 113 1 110 109 108 107 106 105 104 103 102 101 100 99 98 93 92 91 90 87 85 84 83 82 81 80 79 78 77 76 75 74 73 72 71 70 69 68 67 66 65 64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 39 38 37 36 35 34 33 31 30 29 28 27 26 25 24 22 20 19 17 16 15 14 13 10 7 6 5 4 or activitiestrackable type comment and activitiestrackable id in 100 99 98 95 83 82 81 79 78 71 70 69 68 67 65 63 62 61 60 59 58 57 56 55 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 or activitiestrackable type course and activitiestrackable id in 8 1 5 7 or activitiestrackable type group and activitiestrackable id in 14 11 4 5 6 3 2 1 order by id descupdateif i tryactivities publicactivityactivityselectthistinct trackable type trackable idwhere ttrackable typeeqlessonandttrackable idinmy lessons ids orttrackable typeeqpostandttrackable idinmy posts ids orttrackable typeeqwallpostandttrackable idinmy wallposts ids orttrackable typeeqcommentandttrackable idinmy comments ids orttrackable typeeqcourseandttrackable idinmy courses ids orttrackable typeeqgroupandttrackable idinmy groups ids orderid desci get thisupdate 2if i tryactivities publicactivityactivityselectthistinct ontrackable type trackable id i get pgsyntaxerror error syntax error at or near on line 1 select countthistinct ontrackable type trackable id fr select countthistinct ontrackable type trackable id from activities,['ruby-on-rails'] +910730,why is css calc100250px not working i have tested it in the most recent versions of firefox chrome ie 11 in none of those browsers it works when you use the css calc function to calculate eg width as far as i can see i have applied it properly for reference you might want to check why is this not workingdiv backgroundcolor blue height 50px width calc100250pxdivdivdemosedityes this question developed to become a duplicate in the course of many edits but i still think this should remain here because it illustrates the problem better than for example css calc not working also imho the answer is much better,['css'] +910769,how to join multiple tables using cakephp 3 i am using cakephp 3xwhat i want is to be able to call thiscategoriesfind and then join topics on topicscat id categoriesid and then join posts on poststopic id topicsidi do not get any errors but the only data i am getting back is the categories data i have tried left and inner join with no success any help would be greatly appreciatedthe table relationships arecategoriestablethishasmanytopicstopicstablethisbelongstocategoriesthishasmanypostspoststablethisbelongstotopicsalso the query i havequery thiscategoriesfindall ordercategoriesname asc join topics table topics type left conditions topicscat id categoriesid posts table posts type left conditions poststopic id topicsid tried using the containable behavior but now i am getting the error categories is not associated with posts using this queryquery thiscategoriesfindall ordercategoriesname asc containtopics posts functionq return qwherepoststopic id topicsid,"['php', 'mysql']" +910819,reactnative cannot access parse data i am trying to use parse as the data provider for a listview in a reactive native app i have followed the parse guide regarding subscribing to a query but for some unknown reason the the data source is empty i have verified and writing a test object to parse works fineit seems that observe should be called before getinitialstate or am i missing somethinguse strictvar react requirereactnativevar strings requirelocalizedstringsvar parse requireparseparsevar parsereact requireparsereactparseinitializeapi key here api key herevar testobject parseobjectextendtestobjectvar testobject new testobjecttestobjectsavefoo barthenfunctionobject alertyay it workedvar view text listview stylesheet reactvar styles stylesheetcreate maincontainer flex 1 padding 30 margintop 65 flexdirection column justifycontent center backgroundcolor f title marginbottom 20 fontsize 22 textalign center color 0 var ds new listviewdatasourcerowhaschanged r1 r2 r1 r2 assumes immutable objectsvar workoutlist reactcreateclass mixins parsereactmixin observe function return workouts new parsequeryworkoutdescendingcreatedat getinitialstate function return datasource dsclonewithrowsthisdataworkouts renderrow function return viewtexttestingtextview render function return view style flex 1 flexdirection column stringsworkoutstabtitle listview ref listview datasource thisstatedatasource renderrow thisrenderrow automaticallyadjustcontentinsets false keyboardthismissmode ondrag keyboardshouldpersisttaps true showsverticalscrollindicator true style stylesmaincontainer view moduleexports workoutlist,['ios'] +910917,clang bug namespaced template class friend the following code which does not compile under clang but does under gcc and vstemplatetypename t class barnamespace ns templatetypename t class foo foo templatetypename u friend class bar templatetypename rclass barpublic bar nsfooint f int mainint char barint b return 0it fails withmaincpp2022 error calling a private constructor of class nsfooint nsfooint f maincpp89 note implicitly declared private here foo bar should have access to foos private constructor but it looks like it does not if i remove namespace ns it compilescode looks fine to me but maybe i am misunderstanding the c standard which compiler is correct,['c++'] +910931,how does the gmail app achieve it is flat view hierarchy i am attempting to optimize my listitems when i go into my developer options and turn on show layout bounds i noticed that the gmail app has a completely flat view hierarchy how is this black magic achieved,['android'] +910934,replacement for fbfriendpickerviewcontroller for facebook ios sdk 4 according to facebook v4 changelog all fbviewcontroller were deprecated and we should build our own table view controller to show friends listnow before i put myself working on it does anyone knows an alternative for fbfriendpickerviewcontroller on facebook v4thanks,['ios'] +911136,find all numbers in a string with a nsscanner i used the below code to extract numbers from inputstring using nsscannernsstring inputstring dhoni7 notout at183runs in 145andhehit15fours and10sixers100nsstring numberstringnsarray elements inputstring componentsseparatedbystring for int i0 ielements counti nsscanner scanner nsscanner scannerwithstringelements objectatindexi nscharacterset numbers nscharacterset charactersetwithcharactersinstring1234567890 throw away characters before the first number scanner scanuptocharactersfromsetnumbers intostringnull collect numbers scanner scancharactersfromsetnumbers intostringnumberstring result int number numberstring integervalue if number 0 nslogdnnumber numberstring nil my expected output is 71831451510100but the output i am getting is 718314510it just extracts first occurrence of a number from each word eg if its dho7ni89 it just detects the 7 and does not detect 89 i would be really happy if someone helps me figure out a way to fix this,['objective-c'] +911232,why does basic eventargs class exist this is more theoretical question i know that every event in c has to have 2 parameters object and eventargs it is clear but why does the basic eventargs class even exist when it is impossible to pass any data with it of course i can make new eventargs class that inherits from the basic one but i just miss the point of the class that cannot carry any data,['c#'] +911287,campaigntrackingreceiver is not registered google analytics v4 i am using google analytics v4 in my android app the install tracking was working fine for some days and all of a sudden my broadcast receiver is not registeredlogcat says campaigntrackingreceiver is not registered not exported or is thisabled installation campaign tracking is not possible see for instructionsthis is what i have done within my manifest application tag service androidnamecomgoogleandroidgmsanalyticscampaigntrackingservice androidenabledtrue androidexportedfalse receiver androidnamemypackagecustomcampaigntrackingreceiver androidexportedtrue intentfilter action androidnamecomandroidvendinginstall referrer intentfilter receiverand my custom campaign tracking receiver looks like thispublic class customcampaigntrackingreceiver extends broadcastreceiver override public void onreceivecontext context intent intent when youre done pass the intent to the google analytics receiver new campaigntrackingreceiveronreceivecontext intent logvreferralreceiver intentgetaction logvreferralreceiver intentgetdatastring logvreferralreceiver intenttostring logvreferralreceiver intentgetstringextrareferrer call to other referrers i am not able to figure out where things are going out of hand i am using only one install referrer filter in my manifest,['android'] +911322,how to create an empty array in swift i am a newbie with swift programming language and i really confuse with the ways we create array in swift could you please tell me how many ways to create an empty array with some detail thank you,['ios'] +911385,receive url in ionic for ios i am using ionic framework i am trying to set up a way to receive a url from another app like you are in browser click share and send the link to another app my app i found this cordova plugin and have integrated it in my app but this is pulgin for android i need same functionality in ios any idea which plugin i need to use for ios steps taken by me for android1 cordova plugin add gitgithubcominitsogarcordovawebintentgit2 checked configxml file and found code for webintent intentfilter action androidnameandroidintentactionsend category androidnameandroidintentcategorydefault data androidmimetypetextplain intentfilterand appjs code if windowplugins windowpluginswebintent windowpluginswebintentgeturifunctionurl alertgeturi urlurl any suggestions for the same functionally in ios thank you,['ios'] +911440,decorator to time specific lines of the code instead of whole method lets assume a simple method def test method a 1 b 10 c 20 sum1 sumrangeab sum2 sumrangebc return sum1sum2to time this method using a decorator a simple decorator would be from functools import wrapsdef timed decoratorf wrapsf def wrapperargs kwds start timetime result fargs kwds elapsed timetime start10 loggerdebugf0 t102f msformatf name elapsed return result return wrappernow if i want to time specific lines of test method say line 4 sum1 sumrangeab the current implementation involves inline coding like def test method a 1 b 10 c 20 start timetime sum1 sumrangeab timing specific line or lines elapsed timetime start10 loggerdebugthis part took102f msformatelapsed sum2 sumrangebc return sum1sum2the intention is to use the decorator to time lines m to and of a specific method without modifying the code in the methodis it possible to inject such logic using a decorator,['python'] +911543,what makes microsoftwordgenerated html documents so large in code below is a simple w3cvalidated code to print hello worlddoctype htmlhtmlheadmeta charset utf8titlehellotitleheadhello worldhtml but when i do the same thing with ms word the code generated is of 449 lines why do all these extra lines appear in the code,['html'] +911550,separation of validator and service with external api calls i am currently building a web application and attempting to design it following good mvc and serviceoriented architecture i have however hit a bit of a wall in connecting the presentation layer ie my controllers and the backend services while still maintaining good errorvalidation reporting back to the useri read a really good so post here about how to separate validation logic from the service layer and for the most part it all made sense however there was one flaw if you can call it that in this model that niggled at me how do you avoid duplicating effort when looking up objects that are required by both the validator and the servicei think it would be easier to explain with a reasonably simple examplelet us say i have an application that allows users to share code snippets around now i have decided to add a new feature which allows a user to attach their github account to their account on my site ie to build up a profile for the purpose of this example i am going to simply assume that all my users are trustworthy and would only attempt to add their own github accounts not anyone elses following the aforementioned so article i have set up a basic github service for retrieving github user infointerface igithubuserservice githubuser findbyusernamestring usernamethe concrete implementation of githubuserservice makes an expensive call to 0 in order to pull user informationagain following the articles model i implemented the following command to link a user account to a github user command for linking a github account to an internal user accountpublic class githublinkcommand public int userid get set public string githubusername get set my validator needs to validate that the username entered by the user is a valid github account this is very straightforward call findbyusername on the githubuserservice and make sure that the result is not nullpublic sealed class githublinkcommandvalidator validatorgithublinkcommand private readonly igithubuserservice userservice public githublinkcommandvalidatorigithubuserservice userservice this userservice userservice protected override ienumerablevalidationresult validategithublinkcommand command try var user this userservicefindbyusernamecommandgithubusername if user null yield return new validationresultusername stringformatno user with the name 0 found on githubs servers catchexception e yield return new validationresultusername there was an error contacting githubs api okay that is great the validator is really straightforward and makes sense now it is time to make the githublinkcommandhandlerpublic class githublinkcommandhandler icommandhandlergithublinkcommand private readonly igithubuserservice userservice public githublinkcommandhandlerigithubuserservice userservice this userservice userservice public void handlegithublinkcommand command get the user details from github var user this userservicefindbyusernamecommandgithubusername implementation of this entity is not really relevant just assume it is a persistent entity to be stored in a backing database var entity new githubuserentity name userlogin avatarurl useravatarurl etc store the entity this somerepositorysaveentity again this looks really neat and straightforward however there is one glaring issue the duplicate calls to igithubuserservicefindbyusername one from the validator and one from the service on a bad day such a call can take 12 seconds without serverside caching making duplication far too expensive to use this architectural modelhas anyone else encountered such an issue when writing validatorsservices around external apis and how did you reduce the duplication of effort outside of implementing a cache in your concrete class,['c#'] +911585,converting typeof to string is there a way to convert gccs typeof extension to a string for exampledefine printtypea printfs typeofaso that i can doint a 4printftype of a is printtypeaand get the output oftype of a is inta possible use of this would be as followsinclude stdiohdefine indirect printa print typeofaavoid print intint i printfd ivoid print charchar c printfc cint mainvoid char c c int i 100 char a c indirect printa int a i indirect printa return 0if possible it should work for all types including structures and unions without relying on adding every type to a list manually,['c'] +911731,laravel 5 validate multiple request is it possible in laravel 5 to validate multiple requests in order to insert related models after a form submissioni know how to validate multiple model by using validators but i want to do it with the request classlaravel 4 validateuser validatormakeinputall userrulesvalidaterole validatormakeinputall rolerulesif validateuserfails validaterolefails validationmessages array merge recursive validateusermessagestoarray validaterolemessagestoarray laravel 5 request one class createuserrequest extends request public function rules request two class createrolerequest extends request public function rules controller model call public function storecreateuserrequest request createrolerequest request2 how can i validate the user input values and the role input values using the request approach and have a specific feedback if validation fails,['php'] +911924,how to properly align a 5x10 2d array with random data in console first time poster here but i have been using stackoverflow this entire quarter to help me along in my intro to c class generally i can find what i am looking for if i look hard enough but i have been unable to find anyone that has already answered my questioni have an assignment that wants me to thisplay random numbers in a 5x10 arrayi then need to calculate the sum of the numbers and the average but i will worry about that laterrandomized numbers should be 0 and 100 the console output should look something like thisx x x x xx x x x xx x x x xx x x x xx x x x xjust with 10 rows instead of 5however my current code is listing the random numbers next to each other and wrapping lines once it reaches the end of the line like thisx x x x x x x x x x x x x x x x xx x x x x x x x x x x x x x x x xx x x x etcwhat can i do to get it to align correctly i have pretty much exhausted my ability to use format modifiers so when you see 0 5 that is just my most recent attempt but far from my only i am extremely new to c so any advanced techniques would be out of the question as i wouldnt understand how to properly use them any thoughts sousing systemnamespace dilleyhw7 class array2d static void main const int rows 10 const int cols 5 const int max 100 int numbers new int10 5 random rand new random for int i 0 i rows i for int j 0 j cols j numbersi j randnext0 101 consolewrite 0 5 numbersi j hopefully this does not screw with the code snippet i know i could do some crap like this int numbers randomnext1100 randomnext0100 randomnext0100 randomnext0100 randomnext1100 randomnext0100 randomnext0100 randomnext0100 randomnext1100 randomnext0100 randomnext0100 randomnext0100 randomnext1100 randomnext0100 randomnext0100 randomnext0100 randomnext1100 randomnext0100 randomnext0100 randomnext0100 but that would get me a very poor score on the assignment,['c#'] +911964,how remove some special words from a string content i have some strings containing code for emoji icons like grinning kissing heart or bouquet i would like to process them to remove the emoji codesfor example givenhellogrinning how are youkissing heart are you finebouqueti want to get thishello how are you are you finei know i can use this coderichtextbox2text richtextbox1textreplacekissing heart replacebouquet replacegrinning tostringhowever there are 856 different emoji icons i have to remove which using this method would take 856 calls to replace is there any other way to accomplish this,['c#'] +911998,how to use authenticated proxy in selenium chromedriver after searching for many hours i am starting to think this is impossiblei need to run chrome through selenium using different authenticated not public proxys for each runproxy ip some ip addressuid the user idpwd the passwordoptions webdriverchromeoptionsoptionsadd argumentproxyservers uidpwdproxy ipdriver webdriverchromeexecutable pathdriverchromedriverexe chrome optionsoptionsdrivergetsite urlchrome will fireup and thisplay the errorthis webpage is not availableerr no supported proxiesif i use a public proxy requiring no authentication like thisproxy ip public proxy ip addressoptions webdriverchromeoptionsoptionsadd argumentproxyservers proxy ipdriver webdriverchromeexecutable pathdriverchromedriverexe chrome optionsoptionsdrivergetsite urlit runs just fine and thisplays the site while using the proxyi also tried a variant with http in front of the user idoptionsadd argumentproxyserverhttps uidpwdproxy ipthe fact that i have searched far and wide and have not found a solution leads me to believe none might existi did find this but i cannot make sense out of itselenium chromedriver authentication proxynot sure what browswermobproxy is or is supposed to do or how to implement and test in python i hate piling up bandaid solutions unless they are absolutely necessary,['python'] +912004,connection to db dies after 424 in springboot jpa hibernate i have an app that uses springbootjpahiberanate with mysqli am getting this error logcaused by commysqljdbcexceptionsjdbc4communicationsexception the last packet successfully received from the server was 56006037 milliseconds ago the last packet sent successfully to the server was 56006037 milliseconds ago is longer than the server configured value of wait timeout you should consider either expiring andor testing connection validity before use in your application increasing the server configured values for client timeouts or using the connectorj connection property autoreconnecttrue to avoid this problemhere is my applicationproperties datasource settings set here configurations for the database connectionspringdatasourceurl jdbcmysqllocalhost3306testspringdatasourceusername testspringdatasourcepassword testspringdatasourcedriverclassname commysqljdbcdriver specify the dbmsspringjpadatabase mysql show or not log for each sql queryspringjpashowsql true hibernate settings are prefixed with springjpahibernatespringjpahibernateddlauto updatespringjpahibernatedialect orghibernatedialectmysql5dialectspringjpahibernatenaming strategy orghibernatecfgimprovednamingstrategyto solve this issue i can usespringdatasourcetestonborrowtruespringdatasourcevalidationqueryselect 1but i checked that it is not recommended so can anyone suggest me what should i do to overcome this error,"['java', 'mysql']" +912032,check decimal and total length of number using regex i can check if it is decimal or notddbut what i want to control is total length of those digitdd110but i still cannot control itafter 2 days later my final solution isdd110debuggex demo,['c#'] +912051,signalr and websockets on mono i have done hours of scouring trying to figure out why the websockets transport does not work through signalr on my c 45 application running on linux via mono 401references in my projectmicrosoftowinhosthttplistenermicrosoftowinhostsystemwebright now i am trying to figure out where the bottleneck is that is preventing websockets from working the way i understand it is systemweb is basically a self running server that utilizes the httplistener to listen on a port for an http connection which then processes them up to systemweb am i getting this part correctcan someone point me in the right direction to an open issue or a bug tracker where this is currently in development from what i can tell there are some core functions in httpsys from this answer which are required and present in windows 8 are there plans on implementing this in mono i would prefer not to get some third party library and to get this working in signalr,"['c#', '.net']" +912080,get all documents from mongodb collection i need to retrieve all the documents that are in my collection in mongodb but i cannot figure out how i have declared my collection like thisprivate static imongocollectionproject specollection dbgetcollectionprojectcollection projectand i followed what is explained in this mongodb tutorial i adjusted it for my needs like var documents await specollectionfindnew projecttolistasynchowever i keep having the following errormongodbdriverimongocollection does not have a definition for find and the best override of the extension method superlong stuff find contains non valid arguments,"['c#', '.net']" +912177,received memory warning then crash i want to thisplay multiple images in scrollview when images are more than 70 application will crash and thisplay received memory errori have get the images from document directoryi have tried uiscrollview myscrolluiscrollview allocinitwithframecgrectmake0 0 320 480 int x5y15 for int i 0 i imgarrcount i ifx211 uiimage imagepath uiimage imagewithcontentsoffilepath array objectatindexi imgviewuiimageview allocinitwithframecgrectmakex y 77 75 imgviewimageimagepath imgebtnuibutton buttonwithtypeuibuttontypecustom imgebtnframecgrectmakex y 93 110 imgebtn addtargetself actionselectorbtnclick forcontroleventsuicontroleventtouchupinside imgebtntagi x103 else x5 y130 uiimage imagepath uiimage imagewithcontentsoffilepath array objectatindexi imgviewuiimageview allocinitwithframecgrectmakex y 77 75 imgviewimageimagepath imgebtnuibutton buttonwithtypeuibuttontypecustom imgebtnframecgrectmakex y 93 110 imgebtn addtargetself actionselectorbtnclick forcontroleventsuicontroleventtouchupinside imgebtntagi x103 myscroll addsubviewimgebtn myscroll addsubviewimgview myscrollcontentsizecgsizemake320 y120how can i thisplay multiple images in scrollview,"['ios', 'objective-c', 'iphone']" +912229,reordering with bootstrap 3 can someone help me with the html to reorder columns below using bootstrap 3 1 2 3 to this 2 1 3 i know this has something to do with pushpull i just cant to seem to get it righteditand som code that i cannot get to workdiv classrow div classcolmd8 colxs122div div classcolmd2 colxs12 colmdpush21div div classcolmd8 colxs12 colmdpull23divdivon mobile it looks good but not on desktopsolutiondiv classrow div classcolmd8 colxs12 colmdpush22div div classcolmd2 colxs12 colmdpull81div div classcolmd8 colxs123divdiv,['css'] +912260,command line doctrine orm with silex you are missing a cliconfigphp or configcliconfigphp file in your project i am trying to use doctrine orm with silex and finding it an altogether frustrating experience due to the lack of consistent documentationwhen i run vendorbindoctrine at the console i get the following outputoutputyou are missing a cliconfigphp or configcliconfigphp file in yourproject which is required to get the doctrine console working you can use thefollowing sample as a templatephpuse doctrineormtoolsconsoleconsolerunner replace with file to your own project bootstraprequire once bootstrapphp replace with mechanism to retrieve entitymanager in your appentitymanager getentitymanagerreturn consolerunnercreatehelpersetentitymanagerthis is my composerjson file require silexsilex 20dev symfonyyaml 267 doctrinedbal 22 dflydevdoctrineormserviceprovider 20dev khepinyamlfixturesbundle 081 config bindir bin this is the php code that registers the doctrine service etcphpuse doctrinecommoncacheapccacheuse doctrinecommoncachearraycacheuse silexproviderdoctrineserviceprovideruse dflydevproviderdoctrineormdoctrineormserviceproviderappregisternew doctrineserviceprovider array dboptions array driver pdo mysql dbname foobar host localhost user root password root charset utf8 appregisternew doctrineormserviceprovider array dbormproxies dir dir cachedoctrineproxy dbormproxies namespace doctrineproxy dbormcache appdebug extension loadedapc new apccache new arraycache dbormauto generate proxies true dbormentities arrayarray type simple yaml path dir srcresourcesconfigdoctrine namespace foobarentity this is my configuration file bincliconfigphpphp retrieve entitymanageruse doctrineormtoolssetupuse doctrineormentitymanageruse doctrineormtoolsconsoleconsolerunnerapp require once dir appsrcaphpisdevmode appdebugpaths appdbormentitiespathconfig setupcreateyamlmetadataconfigurationpaths isdevmodeentitymanager entitymanagercreateappdboptions configreturn consolerunnercreatehelpersetentitymanagerwhat am i doing wrong,['php'] +912285,how to insert tabs inside ion content in ionic always using the awesome framework ionic for developing my mobile application everything seems to work finei want to add something particular to my app i want to have apps inside a ioncontenti am using button bar tabs i am not sure if this is the right solution or noi want to also let you know that i am using already tabs tool in my app so in my appjs i do have some code for nagigating tabs so i do not know how i would be able to add another one for another pagemy code codepenhere is what i want here some of my code bodydiv ionheaderbar classbarstable button classbutton buttonclear buttonpositive hrefindexhtmlretourbutton h1 classtitledatailsh1 ionheaderbarioncontent div classitem itemdivider styleheight45px div stylethisplayinlineblock left10px positionabsolute h5competitonh5 h514th journeyh5 div div stylethisplayinlineblock right10px positionabsolute h525 mai 2015h5 h51800h5 div div div classitem itemtextwrap styleheight100px img src football club logo 90png stylewidth55px height55px positionabsolute left10px top12px img src football club logo 90png stylewidth55px height55px positionabsolute right10px top12px h4 stylepositionabsolute left10px top70pxasromeh4 h4 stylepositionabsolute right10px top70pxlazioh4 h4 stylepositionabsolute left150px top35px3h4 h4 stylepositionabsolute right150px top35px2h4 divdiv classbuttonbara classbutton tabstate uisrefhomerasumaa a classbutton tabstate uisrefcontactcompositionadiv div body,"['javascript', 'css']" +912311,how do i thisable c 6 support in visual studio 2015 backgroundwe have a project that were developing in vs 2015 with c6 enabled that occasionally needs to be opened by developers using vs 2013 without c6 we have no intention to use c 6 within this particular solution as much as i would like toproblemvisual studio and resharper suggest helpful c 6 language constructs that render the solution inoperable in earlier versions of visual studio without c6 supporti have thisabled the resharper c6 support but i cannot seem to thisable limit c features across the whole solutionquestionhow do i limit c to c5 capabilities within a solution or within visual studio 2015,['c#'] +912322,objectivec search for streets based on userentered query i want to allow the users to search for a street name and have the results thisplayed in a uitableview for the moment the region is not important it can be from any regioni could not find any relevant example in my searches and i do not know if i should use cllocation or mklocalsearchbased on docs i should use mklocalsearchalthough local search and geocoding are similar they support different use cases use geocoding when you want to convert between map coordinates and a structured address such as an address book address use local search when you want to find a set of locations that match the useras inputbut i have tried both methods and it gives me only 1 result eventhough there is an nsarray returnedthis is the clgeocoder approachclgeocoder geocoding clgeocoder alloc initgeocoding geocodeaddrestringthetextfieldtext completionhandlernsarray placemarks nserror error if error nslog error else nslogi placemarks count forclplacemark mystr in placemarks nslog mystr and this is my mklocalsearch trymklocalsearchrequest request mklocalsearchrequest alloc initrequestnaturallanguagequery thetextfieldtextrequestregion selfregionlocalsearch mklocalsearch alloc initwithrequestrequestlocalsearch startwithcompletionhandlermklocalsearchresponse response nserror error if error nil uialertview alloc initwithtitlenslocalizedstringmap errornil messageerror localizeddescription delegatenil cancelbuttontitlenslocalizedstringoknil otherbuttontitlesnil show return if responsemapitems count 0 uialertview alloc initwithtitlenslocalizedstringno resultsnil messagenil delegatenil cancelbuttontitlenslocalizedstringoknil otherbuttontitlesnil show return selfstreets response selfstreetstableview reloaddatamklocalsearch seems to return more than 1 response in some cases but these are related to places not street names searchesthanks in advance,['objective-c'] +912419,chartjs line chart set background color i am working with chartjs and i wanted to convert the a line chart to png but the problem is that the image always downloaded with transparent background which is not what i need i tried many options nothing really workedif someone have ever faced this problem please suggest something worked for you,['javascript'] +912529,monitoring location settings in a library i am working on a library that can be used to monitor geofences on android devices i have noticed that the geofences i register with google play location services geofencingapi class are lost after i turn location services off and back on in the device settingsi have seen folks suggesting that i need to register for the androidlocationproviders changed broadcast receiver in my androidmanifestxml file i have done that but this broadcast receiver only gets called when i add and remove test providers in my test application i do not receive it at all when toggling location services in the device settingsam i doing something wrong does anyone know how to reliably determine when the user toggles location services in the device settings i would like to be able to see these events in the background even if my app is not runningi figure i could set up an repeating task that runs in the background and periodically checks to see if location services has been toggled but it sounds gross and inefficientif it helps i am testing on an moto g running android 442 everything i have done with geofences has worked fine until nowedit after doing more research i have found that the behaviour of the providers changed broadcast is highly variable depending on phone version and model my nexus 5 running android 51 seems to work fine actually i am able to get the providers changed broadcast very regularly i also have a moto g and moto x phone running 44x and they never produced the providers changed broadcast for me a samsung galaxy s3 on android 42 would produce the broadcast for me but stop doing it after i used my map activity with test location providersanyways i have decide to stop pursuing this problem for now i think android is just being buggy,['android'] +912630,how do i implement advanced search with operators with pg search i have implemented pgsearch on my node model like soinclude pgsearchpg search scope node search against name user id circa using tsearch any word true associated against comments message user first name last name email memberships relation and in my controller i have thisif paramssearch nodes nodenode searchparamssearchendideally what i would like to be able to do though is have someone be able to type in the text representation a flag of one of the associations and have the search filter just on that flageg say name bouncing ball where the search would take place just on the column called name on the nodes model akait would look for all the nodes with the name bouncing ball and not search other columns or models or even any of the associationsnaturally i would like to be able to do searches likeowner john brown which searches for all nodes whose owneruser first name and last name are john brown comment manhattan which searches for all nodes that have a comment with the text manhattan in the copy and so onhow do i achieve this with pgsearch,['ruby-on-rails'] +912688,filter elements in a dom with common class name and apply css on it jquery in a dom i could filter out elements having class names starting with a particular word here it is answer list two cpts and the result is given belowclassanswer list two cpts div classaanswer list two cpts 1 19234adiva div classaanswer list two cpts 2 19234adiva div classaanswer list two cpts 3 19234adiva div classaanswer list two cpts 4 19234adiva div classaanswer list two cpts 5 19234adiva div classaanswer list two cpts 1 19234adiva div classaanswer list two cpts 2 19234adiva div classaanswer list two cpts 3 19234adiva div classaanswer list two cpts 4 19234adiva div classaanswer list two cpts 5 19234adiva div classaanswer list two cpts 1 19235adiva div classaanswer list two cpts 2 19235adiva div classaanswer list two cpts 3 19235adiva div classaanswer list two cpts 1 19235adiva div classaanswer list two cpts 2 19235adiva div classaanswer list two cpts 3 19235adivafrom this i would like to take an element find its class name find another element having same class name compare the height of both the div elements and apply the larger height value to both the div elements please help me with the jquery code for implementing the same thank you,"['javascript', 'jquery', 'html', 'css']" +912693,converting string to datetime from jqueryui datepicker using strtotime i am using jqueryui datepicker and here is the codelink relstylesheet hrefcodejquerycomui14themessmoothnessjqueryuicss script srccodejquerycomjquery1102jsscript script srccodejquerycomui14jqueryuijsscript link relstylesheet hrefresourcesdemosstylecss script function from datepicker defaultdate 1w changemonth true numberofmonths 3 onclose function selecteddate to datepicker option mindate selecteddate to datepicker defaultdate 1w changemonth true numberofmonths 3 onclose function selecteddate from datepicker option maxdate selecteddate script form actionlinkto export methodpost h1export csvh1 label forfromfromlabel input typetext idfrom namefrom label fortotolabel input typetext idto nameto input typesubmit valueexport text formwhen i post the from and tofromstr postfromtostr posttofrom dateymd hisstrtotimefromstr 020to dateymd hisstrtotimetostr 020the to has been converted properly ie 20150613 020 but the from has not it returned 612015 200 instead to make sure i am fetching the correct values i echoed the fromstr and tostr fromstr returned 612015tostr returned 06132015why was the from returned mdy while to did mmddy how do i convert a mdy string to timestamp then please help thank you,"['php', 'jquery']" +912752,nsarray does not have a member named append i just got into swift coding and i am trying to follow a tutorial but it seems as if the coder i am following may have an older version or i am doing something wrong i am trying to make a sound object to make a soundboard but when i try to add the sound file to the array using append it says that the method append is not a member of the nsarray can someone tell me what is the right way to do solve this1,"['ios', 'objective-c']" +912764,transparent background of css for those who cannot wait fiddlei have this problem in css the structure of the html and css code looks like thishtmldiv classone div classtwo div classthree div divdivcssone width 500px height 500px background url moonfpomegranatesontree85361jpg backgroundsize cover backgroundrepeat norepeat padding 20pxtwo width 300px height 300px background blue padding 20pxthree width 200px height 200px background transparent padding 20px border 5px solid yellowmy problem is how do i make the background of div classthreediv that it would be transparent and would blend to the background of the div classonediv i want my desired output to be like the attached image is this possible,"['html', 'css']" +912846,athinking in reactjs if i have a angularjs background i am familiar with developing clientside applications in angularjs but now i would like to start using reactjsi also have an eye on the reactnative which i think will revolutionize mobile apps what is the way of thinking and how the structure of a react application differs from angular what is the biggest difference,['javascript'] +912892,android lollipop 501 sqlitelog posix error 11 sqlite error 3850 i am having an issue while upgrading an app to support android lollipopthe app implements a syncadapter that writes on a db through a content providerat the same time it can happen that the user is browsing the frontend of the app where loaders read the same data from the databaseloaders also listen to data changesnow if i run the program on a prelollipop device everything works without any error outputon lollipop instead i receive the following logcat message112059344 2234122376comexamplecom esqlitelogi1 10 posix error 11 sqlite error 3850112059364 2234122376comexamplecom esqlitelogi1 10 posix error 11 sqlite error 3850112059364 2234122376comexamplecom esqlitelogi1 10 posix error 11 sqlite error 3850112059364 2234122376comexamplecom esqlitelogi1 10 posix error 11 sqlite error 3850now from sqlite docs3850 sqlite ioerr lockthe sqlite ioerr lock error code is an extended error code for sqlite ioerr indicating an io error in the advisory file locking logic usually an sqlite ioerr lock error indicates a problem obtaining a pending lock however it can also indicate miscellaneous locking errors on some of the specialized vfses used on macs everything seems to work properly on a high level that is both reads and writes are performedanda pending lock means that the process holding the lock wants to write to the database as soon as possible and is just waiting on all current shared locks to clear so that it can get an exclusive lock no new shared locks are permitted against the database if a pending lock is active though existing shared locks are allowed to continuei know that the sqlite version has been updated by few major releases in lollipop so i am prone to think that the error is due to some new behaviour of sqlite that i cannot isolatehowever everything seems to work fine from a higher level point of view app does not crash both reads and writes are performed framerate does not drop at least to human eyes but i wouldnt want to ignore the issue to release the app until i am sure it would not cause data corruption or troublesperhaps i am missing on some important changes to lollipop regarding locks and multiprocess database access but i feel it is an issue that lies on a lower level with respect to the artdalvik domain and so has to be fixed in an ndk contextis there a way to fix this possibly without thistributing an app specific version of sqlite is there any manifestsqlite option to avoid the errorthanks in advance,['android'] +912958,jquery add class on hover on certain width if bootstrap dropdown is showing i am using bootstrap with dropdown my anchor has a background color on hover but when the dropdown is showing i want the parent containing the dropdown to lose the background color my html is nav classnavbar navbardefault avnav rolenavigation div classcontainer div classnavbarheader button typebutton classnavbartoggle collapsed datatogglecollapse datatargetbsexamplenavbarcollapse1 span clasronlyspan span classiconbarspan span classiconbarspan span classiconbarspan button div div classcollapse navbarcollapse idbsexamplenavbarcollapse1 ul classnav navbarnav nav navtabs li classlia li1a hrefhomeali li classdropdown li2a classdropdowntoggle datatoggledropdownaboutaspan classnavarrowspan div classdropdownmenu ul lia hrefdrop 1ali lia hrefdrop 2ali lia hrefdrop 3ali ul div li ul div navbarcollapse div container nav my attempt at this document readyfunction var section avnav nav li ahover var width sectionwidth if width 768 sectionaddclassnobg the cssnobg background noneimportantwhat am i doing wrong that my code is not working,"['javascript', 'jquery', 'css']" +912985,scheme is not configured for the test action ios xcode project i am trying to run an xcode unit test for my ios application i am willing to do it on an ipad connected via usb to a mac machine i am trying to run the test from the command line in order to trigger it from jenkins later onbelow is what i am currently typing into the command line and the error i am getting please helpthe codexcodebuild test scheme myapplication destination platformiosnameipadthe errorscheme myapplication is not currently configured for the test action,['ios'] +913076,python fill cells with colors using openpyxl i am currently using openpyxl v2 for python 27 and i wanted to set colors to cells i have used the following importsimport openpyxlfrom openpyxl import workbookfrom openpyxlstyles import color patternfill font borderfrom openpyxlstyles import colorsfrom openpyxlcell import celland the following is the code i tried usingwb openpyxlworkbookws wbactiveredfill patternfillstart colorf0 end colorf0 fill typesolidwsa1style redfillbut i get the following errortraceback most recent call last selffont valuefontcopyattributeerror patternfill object has no attribute fontany idea on how to set cell a1 or any other cells with colors using openpyxl,['python'] +913097,calling begininvoke from a destructor i have some code in a wpf application that looks like thispublic class mytextbox systemwindowscontrolstextbox ithisposable public void thispose thisposetrue gcsuppressfinalizethis protected virtual void thisposebool thisposing thispatcherbegininvokeaction delegate do work on member variables on the ui thread mytextbox thisposefalse the thispose method is never getting explicitly called so the destructor calls it it seems like in this case the object would be destroyed before the delegate in the begininvoke fires on the ui thread it appears to be working though what is happening here is this safe,"['c#', '.net']" +913170,remove ad user from security group using python i am trying to remove a user from a security group using python and pywin32 but so far have not been successful however i am able to add a user to a security group from win32comclient import getobjectgrp getobjectldapcngroupnameougroupsdcblahdclocalgrpaddldapcnusernameouusersdcblahdclocal successfully adds a user to the groupgrpremoveldapcnusernameouusersdcblahdclocal returns an errorthe error is belowtraceback most recent call last file stdin line 1 in module file comobject ldapcngroupnameougroupsdcblahdclocal line 2 in removepywintypescom error 2147352567 exception occurred 0 none none none 0 2147024891 nonei have also tried adding using getobject to get the user and remove it that way however i get the same error usr getobjectldapcnuserouusersdcblahdclocalgrpremoveusrany help would be much appreciated as i have hit a deadend hereediti have also now tried using tim goldens active directory module to try and remove the group memberimport active directory as adgrp adfind groupgroupnameusr adfind userusernamegrpremoveusrpathhowever this also does not work and i encounter the below errortraceback most recent call last file cpython33libsitepackagesactive directorypy line 799 in getattr attr getattrselfcom object nameattributeerror pyiads object has no attribute groupduring handling of the above exception another exception occurredtraceback most recent call last file cpython33libsitepackagesactive directorypy line 802 in getattr attr selfcom objectgetnamepywintypescom error 2147463155 ole error 0x80500d 0 active directory the directory property cannot be found in the cachern none 0 2147463155 noneduring handling of the above exception another exception occurredtraceback most recent call last file stdin line 1 in module file cpython33libsitepackagesactive directorypy line 1081 in remove selfgroupremovedn file cpython33libsitepackagesactive directorypy line 804 in getattr raise attributeerrorattributeerroreditwherby suggested that i change to python 27 and give that a go i have just tried thisimport active directory as aduser adfind userusernamegroup adfind groupgroupnamegroupremoveuserpath but i am still getting an errortraceback most recent call last file stdin line 1 in module file comobject ldapcngroupnameougroupsdcblahdclocal line 2 in removepywintypescom error 2147352567 exception occurred 0 none none none 0 2147024891 nonethe user and group are definitely found correctly as i can print their ldap paths using print userpath and print grouppathare there any other active directory libraries for python 33 that anyone can recommend,['python'] +913181,entity framework suggest invalid field name i have two tables in my database bunts which contains information about pieces of steelcreate table bunts buntcode integer not null buntname varchar20 buntsteel integer and poll weight bunts which contains information about operations that had been performed on each buntcreate table poll weight bunts pwbcode integer not null pwbbuntcode integer pwbdepartmentfrom integer pwbdepartmentto integer the relationship is onetomany i mapped those tables to models everything worked just finerecently i have decided to add a field to table bunts which would reference to the last operation that had been performed on buntbuntlastoper integernow my models look like thistablebuntspublic class bunt key columnbuntcode public int code set get columnbuntname public string name set get columnbuntsteel public int steelcode set get columnbuntlastoper public int lastoperationid set get foreignkeylastoperationid public buntoperation lastoperation set get public virtual icollectionbuntoperation operations set get tablepoll weight buntspublic class buntoperation key columnpwbcode public int code set get columnpwbbuntcode public int buntcode set get foreignkeybuntcode public bunt bunt set get columnpwbdepartmentfrom public int departmentfromcode set get after i have made this when i try to query operations like thisreturn contextoperationsit generates an sqlstatement with new incorrect field bunt codeselect bpwbcode as pwbcode bpwbbuntcode as pwbbuntcode bpwbdepartmentfrom as pwbdepartmentfrom bbunt code as bunt codefrom poll weight bunts as bi assume that now ef looks for a field that is a foreign key for bunts table and cant find it so it generates bunt code field which is missing in my database but i already have a property bunt in buntoperation class which references to bunts table what am i missingupdateseems like this solves my problemprotected override void onmodelcreatingdbmodelbuilder modelbuilder modelbuilderentitybunthasoptionalb blastoperationwithmany modelbuilderentitybunthasmanyb boperationswithrequiredop opbunt,"['c#', '.net']" +913198,why strcmp returns int but not char as far as i know the only difference between variable types such as char int etc is the amount of memory they occupy i guess that they have no role in regulating what the variable they are holding represents if that is true in here i have seen the following for strcmpthe strcmp function compares the string s1 against s2 returning a value that has the same sign as the difference between the first differing pair of characters interpreted as unsigned char objects then promoted to inti want to ask why is the result promoted to int since chars are being compared their difference fits into a char in all cases so is not promoting the result to int simply appending bunch of 0s at the end of the result so why is this done,"['c++', 'c']" +913467,referenceerror cannot find variable jquery with poltergeistcapybara what i am trying to doi am trying to use capybara with poltergeist to log into amazon at this urlsimple enough except that when i try to submit the form i get the error referenceerror cannot find variable jquery however the source for jquery is in the page and should have been loadedthe code i am using to log in is this visit fill inap email with user fill inap password with password click onsigninsubmitinputsubmit triggers a javascript call to validate input this uses jquery and when it does the error is thrownwhat i expectedi expected that when i visited the login page that jquery would have been loaded with the other javascripts on that pagei have no idea why jquery would not be loaded at this point phantomjs would have loaded the page and loaded the jquery referenced in the page nothings i have triedtiming issue added sleep after visitconfiguration issuemy current configuration include capybaradslcapybaradefault driver poltergeistcapybararegister driver poltergeist do app capybarapoltergeistdrivernewapp phantomjs phantomjspathendcapybaraignore hidden elements falseattempting to force jquery to loadcapybarapoltergeistdrivernewapp phantomjs phantomjspath extensions handlersjqueryjsi have tried quite a few things in an attempt to get my head around whats going on but i am coming up empty any thoughts on where i might look or what may be going on would be greatly appreciated,"['javascript', 'jquery']" +913483,what is surrogate prototype swapping in javascript in the underscorejs code the comments state naked function reference for surrogateprototypeswappingvar ctor functionwhat is surrogateprototypeswappingorwhere can i find an articleclear documentation on surrogateprototypeswapping,['javascript'] +913490,the way c represents negative integers in memory and casts them unchecked c has various value types and each serves their own purpose int32 ranges from 0x7f 1 to 0x7f and from every machine i have ever run it it seems that uncheckedint0xf always got me a resulting value of 1 is this always the case furthermore does net always represent 1 as 0xf in memory on any system is the leading bit always the sign bit does it always use the twos complement signed binary representation for integers,"['c#', '.net']" +913527,method routecollectionget appendtrailingslash not found when using razor url helpers in aspnet mvc 5 mono i am creating an aspnet mvc 5 application in mono ubuntu 144 monodevelop 59 mono jit compiler version 401i see that some of the razor components are not recognized egurlactionwhen i add thisa titlenotifications hrefurlaction listinghome home ai get this errorsystemmissingmethodexceptionmethod routecollectionget appendtrailingslash not foundsystemwebmvc is referenced from the packages is there anything else which is requiredupdate i tried these solutions so fardoes the razor view engine work for monois it possible to use razor 20 view engine under monoit seems like it is a known issue but i strongly believe there shall be some hack for this to work i tried using aspx engine also but no gain,['c#'] +913532,is list a subtype of list extends number and why here is what i knowdouble is a subtype of number and listdouble is not a subtype of listnumberlistdog is not a subtype of listanimal because you can add cat to listanimal but you cannot do that with listdoglist extends number means this list can store variables of type number and variables of subtype of number listdouble means this list can store variables of type doubleplease correct me if anything above is wrong and then is listdouble a subtype of list extends number and why,['java'] +913541,how to pass django template variables to a webpack module i am just learning about webpack module and i am thinking of moving the entire js infrastructure of my django app to modules it seems that a straightforward way of doing this is to create a webpack module for each django template or view and have a single script tag on each pagehowever i am trying to find a way of passing the content of django template variables to these webpack modules previously i could have these variables inlinedscriptsample codevar arr for s in vars arrpushs endfor scriptnow i only havescript srctempjsscriptone potential solution i found is to define the webpack module to be a library that exports a single root function to the global namespace in the browser then use an inline script tag to put the django variables into a js variable and pass this as arguments to the exported functionthis somehow feels like a clumsy way of doing things any ideas as to how i can handle this betterthanks,"['javascript', 'python']" +913544,turning string with embedded brackets into a dictionary whats the best way to build a dictionary from a string like the one belowkey1 value1 key2 value2 key3 value with spacesso the key is always a string with no spaces but the value is either a string or a string in curly brackets it has spaceshow would you dict it intokey1 value1 key2 value2 key3 value with spaces,['python'] +913659,jquery backstretch image automoving and back i use backstretch on my website now trying to move the backgroudn automatically from left to right and back but til now it just moves in one direction i am lookig for a continous loop of that moving imagehow can i reset move back the imagebackstretchjs some more javascript for movingeffect initialisationvar images fileadmintemplategfxbackground0203jpg jquerybackstretch imagesmathfloormathrandom imageslength jqueryfunction function swoopelement element animatemarginleft5px 100 function settimeoutfunction swoopelement 0 backstretch img resulting this html outputdiv idbackstretch styleleft 0px top 0px position fixed overflow hidden zindex 9 margin 0px padding 0px height 100 width 100img srcfileadmintemplategfxbackground0203jpg styleposition absolute margin 0px 0px 0px 340498890491151px padding 0px border none zindex 9 width 3006px height 835px left 5515px top 0pxdivsorry for posting the html code a littlt bit ugly do not know to do it righteditthanks a lot but i think that is not what i needi think i need a calculation about imagewidth and marginleft to switch from movingleft to movingright and backso i tried to calculate width of my image butiwidth jquerybackstretch imgwidthis always nullandiwidth backstretch imgwidthbreaks the whole javascripti thought it could be a solution to write a second function called backswoop for counting up the marginleft and then do a condition about marginleft and imagewidthiwidth jquerybackstretch imgwidthjqueryfunction function swoopelement elementanimatemarginleft5px 50 function settimeoutfunction ifelementcssmarginleft1 iwidth swoopelement else backswoopelement 0 backstretch img function backswoopelement elementanimatemarginleft5px 50 function settimeoutfunction ifelementcssmarginleft 0 swoopelement else backswoopelement 0 backstretch imgbut because i am not great with javascript it does not work,"['javascript', 'jquery', 'css']" +913802,parse notifications on android would not work i am trying to set up parse push notifications on android for some time nowi followed different tutorials and i am trying to send the notifications from their web platform but nothing seems to work here is what i have tried so farhere is the oncreate method of my application classoverride public void oncreate superoncreate logipushnotificationsparse initialize parseinitializethis parseinstallationgetcurrentinstallationsaveinbackground parsepushsubscribeinbackground new savecallback override public void doneparseexception e if e null logipushnotificationscomparsepush successfully subscribed to the broadcast channel else logipushnotificationscomparsepush failed to subscribe for push this is called successfully as i get the logsuccessfully subscribed to the broadcast channelalso here is some relevant content of my manifest fileusespermission androidnameandroidpermissioninternetusespermission androidnamecomgoogleandroidprovidersgsfpermissionread gservices permission androidnamecommyapermissionc2d message androidprotectionlevelsignature usespermission androidnamecommyapermissionc2d message usespermission androidnamecomgoogleandroidc2dmpermissionreceive usespermission androidnameandroidpermissionvibrate usespermission androidnameandroidpermissionaccess network state usespermission androidnameandroidpermissionwake lock usespermission androidnameandroidpermissionreceive boot completed usespermission androidnameandroidpermissionget accounts usespermission androidnameandroidpermissionwrite internal storage usespermission androidnameandroidpermissionwrite internal storage usespermission androidnameandroidpermissionwrite external storage usespermission androidnameandroidpermissionread external storage usespermission androidnameandroidpermissionread phone state usespermission androidnameandroidpermissionread contactsusespermission androidnameandroidpermissionsend sms usespermission androidnameandroidpermissioncamera usesfeature androidnameandroidhardwarecamera application androidallowbackuptrue androidicondrawableic launcher androidlabelstringapp name androidnameapp androidthemestyleapptheme activity androidnameactivitiesmainactivity androidlaunchmodestandard androidscreenorientationsensorportrait intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity metadata androidnamecomparsepushgcm sender id androidvalueid123456789 metadata androidnamecomparsepushnotification icon androidresourcedrawableic launcher service androidnamecomparsepushservice receiver androidnamecomparseparsebroadcastreceiver intentfilter action androidnameandroidintentactionboot completed action androidnameandroidintentactionuser present intentfilter receiver receiver androidnamecomparseparsepushbroadcastreceiver androidexportedfalse intentfilter action androidnamecomparsepushintentreceive action androidnamecomparsepushintentdelete action androidnamecomparsepushintentopen intentfilter receiver comparsegcmbroadcastreceiver receiver androidnamecomparsegcmbroadcastreceiver androidpermissioncomgoogleandroidc2dmpermissionsend intentfilter action androidnamecomgoogleandroidc2dmintentreceive action androidnamecomgoogleandroidc2dmintentregistration category androidnamecommyapp intentfilter receiverapplicationwhen i try sending push from parse website nothing happensas this is not working i tried implementing my own gcmbroadcastreceiver and changing it in the manifest receiver androidnamereceiversmycustomreceiver androidpermissioncomgoogleandroidc2dmpermissionsend intentfilter action androidnamecomgoogleandroidc2dmintentreceive action androidnamecomgoogleandroidc2dmintentregistration category androidnamecommyapp intentfilterreceiverandpublic class mycustomreceiver extends broadcastreceiver override public void onreceivecontext context intent intent logipushnotificationsmycustomreceiver without success then i also tried creating my own parsepushbroadcastreceiver by inheriting from parsepushbroadcastreceiver receiver androidnamereceiverscustomparsereceiver androidexportedfalse intentfilter action androidnamecomparsepushintentreceive action androidnamecomparsepushintentdelete action androidnamecomparsepushintentopen intentfilter receiverand public class customparsereceiver extends parsepushbroadcastreceiver override protected notification getnotificationcontext context intent intent logipushnotificationsparse getnotification return null override protected void onpushopencontext context intent intent logipushnotificationsparse onpushopen override protected void onpushreceivecontext context intent intent logipushnotificationsparse onpushreceive private jsonobject getdatafromintentintent intent logipushnotificationsparse getdatafromintent it did not work eitherthe thing is when i create my own gcm broadcastreceiver and i send a notification from my own server with some small php script the notification is successfully receivedi really wonder whats wrong with my implementation of the client side parse notifications system any hint on where the problem might come from,['android'] +913806,does the keyword final have any impact on the jvm now i recently ran into a recommendation that you should use the keyword final as wide as possible this is good in order to prevent a programmer from shooting his own leg that is reassign the variable that should not be reassignedbut does it serve any other goal that is can jvm use information about the final variables in order to optimize the bytecode somehow so it would ran faster build a better pipelining or use it in a multithreaded environment or is just a syntactic sugar that minimizes the possibility of errors during code development,['java'] +913826,connecting to sql azure database fails due to missing ssl encryption i am learning aspnet 5 vnext on my mac for the last day i have been stuck trying to connect to my sql azure database in that attempt i have been using the following codevar servername protectedvar dbname protectedvar userid protectedvar password protectedvar sql select from customerusing var database new sqlconnectionservertcp servername databasewindowsnet1433database dbname user id userid password password trusted connectionfalseencrypttruemax pool size25 databaseopen return await databasequeryasynctsql when this code gets executed an exception is thrown the exception details looks like thistype systemnotimplementedexception message ssl encryption for data sent between client and server is not implementedupdatei learned that encryption is not supported in the framework running on mac os x at this time for that reason i updated my connection string to looks like the followingvar connectionstring persist security infofalseintegrated securitytrueinitial catalog dbname server servername user id userid password passwordstill when i use the connection string above i get the following errortype systemdatasqlclientsqlexceptionmessage server does not exist or connection refusedi have confirmed that my ip address is not blocked by azure i did this by logging into the azure portal and managing the sql server database from the silverlight app yet i am still not sure why i am getting this errorif i am understanding this correctly there is not a way to connect to a sql azure database at this time from aspnet 5 running on a mac is that true if it is not true what am i doing wrong,"['c#', 'asp.net']" +913828,avoiding duplicate symbol when compiling to multiple instruction sets i am in the process of using cpu thispatch based on processor features to switch implementation of a complicated numerical algorithm i want to include the two versions an sse2 and sse3 version for arguments sake i am compiling in the same dynamic librarythe approach taken so far is to wrap all architecture specific code into a namespace eg namespace sse2 and namespace sse3 and thus avoiding duplicate symbol names when linking into the final dynamic libraryhowever what happens if i use some code outside my control eg a stdvectorint in both the sse2 and ss3 version as far as i can see the stdvector implementation will be present in both the sse2 and sse3 object files but could in theory contain different instructions depending on the optimizations performed by the compiler when i link these object files into the dynamic library one of them will be used and i risk potentially trying to run an sse3 instruction on a cpu only supporting sse2aside from compiling to two separate dynamic libraries what can be done to get around this problem i need a solution working with both visual studio and clang on windows mac os x and linux,['c++'] +913879,laravel get microtime from database in a mysql database i have a datetime field stored like this 20150512 1358250508but when i execute this query for example query sdkeventwithsdkeventstack if issetparamsco id paramsco id querywhereco id paramsco id if issetparamsapp id paramsapp id querywhereapp id paramsapp id if issetparamsapp ip paramsapp ip querywheresdkevent ip like paramsapp ip if issetparamsplace id paramsplace id querywhereplacement id paramsplace id sdks querygeti get the datetime like this 20150512 135825why am i not getting the microseconds,"['php', 'mysql']" +913925,activerecord alternative to find in batches i have a query that loads thousands of objects and i want to tame it by using find in batchescarincludesmemberwhereengine 123find in batchesbatch size 500 according to the docs i cannot have a custom sorting order in batcheshowever i need a custom sort order of created at desc is there another method to run this query in chunks like it does in find in batches so that not so many objects live on the heap at once,['ruby-on-rails'] +913946,android studio preview this jvm does not support constant tag 15 i am attempting to look at a preview of an xml layout that contains a couple custom views nothing complicated mostly wrappers i am getting the following errorthe following classes could not be instantiateda comappviewwidgetslidingswiperefreshlayout open class show exception clear cachea comappviewwidgetbetterviewanimator open class show exception clear cachejavalangclassformaterror this jvm does not support constant tag 15 in class file unknown at javalangclassloaderdefineclass1native method at javalangclassloaderdefineclasscondclassloaderjava637 at javalangclassloaderdefineclassclassloaderjava621 at javalangclassloaderdefineclassclassloaderjava471 at comandroidtoolsidearenderingrenderclassloaderloadclassrenderclassloaderjava150 at comandroidtoolsidearenderingrenderclassloaderloadclassfilerenderclassloaderjava125 at orgjetbrainsandroiduipreviewmoduleclassloaderloadclassfilemoduleclassloaderjava287 at comandroidtoolsidearenderingrenderclassloaderloadclassfromclasspathrenderclassloaderjava118 at orgjetbrainsandroiduipreviewmoduleclassloaderloadclassfrommodulemoduleclassloaderjava202 at orgjetbrainsandroiduipreviewmoduleclassloaderloadclassfrommoduleordependencymoduleclassloaderjava136 at orgjetbrainsandroiduipreviewmoduleclassloaderloadmoduleclassloaderjava122 at comandroidtoolsidearenderingrenderclassloaderfindclassrenderclassloaderjava53 at orgjetbrainsandroiduipreviewmoduleclassloaderfindclassmoduleclassloaderjava84 at javalangclassloaderloadclassclassloaderjava306 at javalangclassloaderloadclassclassloaderjava247 at orgjetbrainsandroiduipreviewviewloaderloadclassviewloaderjava182 at orgjetbrainsandroiduipreviewviewloaderloadviewviewloaderjava101 at comandroidtoolsidearenderinglayoutlibcallbackloadviewlayoutlibcallbackjava177 at androidviewbridgeinflaterloadcustomviewbridgeinflaterjava207 at androidviewbridgeinflatercreateviewfromtagbridgeinflaterjava132 at androidviewlayoutinflaterinflatelayoutinflaterjava482 at androidviewlayoutinflaterinflatelayoutinflaterjava385 at comandroidlayoutlibbridgeimplrendersessionimplinflaterendersessionimpljava400 at comandroidlayoutlibbridgebridgecreatesessionbridgejava332 at comandroididecommonrenderinglayoutlibrarycreatesessionlayoutlibraryjava350 at comandroidtoolsidearenderingrendertask2computerendertaskjava497 at comandroidtoolsidearenderingrendertask2computerendertaskjava485 at comintellijopenapiapplicationimplapplicationimplrunreadactionapplicationimpljava894 at comandroidtoolsidearenderingrendertaskcreaterendersessionrendertaskjava485 at comandroidtoolsidearenderingrendertaskrenderrendertaskjava590 at orgjetbrainsandroiduipreviewandroidlayoutpreviewtoolwindowmanagerdorenderandroidlayoutpreviewtoolwindowmanagerjava644 at orgjetbrainsandroiduipreviewandroidlayoutpreviewtoolwindowmanageraccess1700androidlayoutpreviewtoolwindowmanagerjava79 at orgjetbrainsandroiduipreviewandroidlayoutpreviewtoolwindowmanager71runandroidlayoutpreviewtoolwindowmanagerjava586 at comintellijopenapiprogressimplcoreprogressmanager2runcoreprogressmanagerjava152 at comintellijopenapiprogressimplcoreprogressmanagerregisterindicatorandruncoreprogressmanagerjava452 at comintellijopenapiprogressimplcoreprogressmanagerexecuteprocessunderprogresscoreprogressmanagerjava402 at comintellijopenapiprogressimplprogressmanagerimplexecuteprocessunderprogressprogressmanagerimpljava54 at comintellijopenapiprogressimplcoreprogressmanagerrunprocesscoreprogressmanagerjava137 at orgjetbrainsandroiduipreviewandroidlayoutpreviewtoolwindowmanager7runandroidlayoutpreviewtoolwindowmanagerjava581 at comintellijutiluiupdatemergingupdatequeueexecutemergingupdatequeuejava320 at comintellijutiluiupdatemergingupdatequeueexecutemergingupdatequeuejava310 at comintellijutiluiupdatemergingupdatequeue2runmergingupdatequeuejava254 at comintellijutiluiupdatemergingupdatequeueflushmergingupdatequeuejava269 at comintellijutiluiupdatemergingupdatequeueflushmergingupdatequeuejava227 at comintellijutiluiupdatemergingupdatequeuerunmergingupdatequeuejava217 at comintellijutilconcurrencyqueueprocessorrunsafelyqueueprocessorjava238 at comintellijutilalarmrequest1runalarmjava351 at javautilconcurrentexecutorsrunnableadaptercallexecutorsjava439 at javautilconcurrentfuturetasksyncinnerrunfuturetaskjava303 at javautilconcurrentfuturetaskrunfuturetaskjava138 at javautilconcurrentthreadpoolexecutorworkerruntaskthreadpoolexecutorjava895 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava918 at javalangthreadrunthreadjava695is there a suggested fix for it i have tried the typical cleaningrebuilding and restarting android studio,"['java', 'android']" +914062,correct image and font scale on different devices i have a simple view with a text and an image i ran this app on iphone6plus and iphone5 then i made a screenshot of both and enlarged the iphone5 screenshot such that it matches the size of the screenshot from iphone6plus here is the result as you can se the size of the text the size of the image and there positions are not identical but they should be to look the same on different screen sized here is an example of a weather app running on different screensas you can see the sizes and the positions of text and image are identical the image is loaded from asset catalog imageviewimage uiimagenamed shower3selfviewaddsubviewimageviewimageviewcenter selfviewcenteri have only created a 128x128 image and put it into the 1x version in the asset catalogelet me rephrase this i run the wether app on iphone5 make ascreenshot and iphone6 make a screenshot then i resize both screenshots to the same size then i see that both fontsize as well as images dimension are exactly equal on both screenshots this means that on each device font and image must have different dimensions how can i do that how can i achieve that text and image have identical proportions on different screen sizes how does the weather app do it,"['ios', 'objective-c', 'iphone']" +914067,directivefactory not working in production i have a directive that prints out flash messages for users everything works fine on my localhost but as soon as i test it out on heroku the flash message does not appear here is the controllerangularmodulealertscontrolleralertscontroller alertcontrolleralertcontrollerinject flashfunction alertcontrollerflash var vm this vmflash flashthe directiveangularmodulealertsdirectiveflash flashflashinject timeoutfunction flash timeout return restrict e replace true scope text type template div idflash message classnotification ngclasstype text hello div link functionscope element attrs timeoutfunction elementremove 50 and the factory that handles storing the flash messagesangularmodulealertsfactoryflash flashfunction flash var messages var results messages messages printmessage printmessage addmessage addmessage return results function printmessage return resultsmessages function addmessagemessage resultsmessagespushmessage my html codediv ngcontrolleralertscontroller as alerts div ngrepeatmessage in alertsflashmessages flash typemessagetype textmessagetextflash divdivno error appears on the console the funny thing is the flash message is presented in the html does not loadthis is what is shown in localhostdiv ngrepeatmessage in alertsflashmessages classngscope div idflash message classnotification ngbinding ngisolatescope success ngclasstype typemessagetype textmessagetext your link has been copied hello divdivbut on heroku productiondiv ngrepeatmessage in alertsflashmessages classngscopedivi am creating the flash in my code viaflashaddmessagetype success text your link has been copiedmy question is why does this not appear on my production code but it appears on my localhost and how do i fix it,['javascript'] +914159,how do parameterized methods resolve if it is not an input parameter how are references to t handled by the compiler in the following code since the method takes no parameters that would allow inference of t are any restrictions being placed on what type of object can be placed into the list is a cast even taking place on the line where i add the string to the list my first thought is that without anything to infer t from t becomes an object type thanks in advancepublic class app private t void parameterizedmethod listt list new arraylist forint i 0 i 10 i listaddtnew string is a cast actually occurring here public app parameterizedmethodpublic static void mainstring args new app,['java'] +914200,recursive function that tells if a tree is a binary search tree bst modified code i was working on the exercises here i wrote a function that decides if a tree is a bstreturn 1 or notreturn 0 but i am not sure if my code is totally good i tested it for a bst and a nonbst tree and it seems to work correctly i want to know the opinion of the community updated code consider the tree not a bst 5 2 7 1 6my idea is to compare 2 with 5 if it is good then 1 with 5 and if it is good then 6 with 5 if it is good then 1 with 2 if it is good then 6 with 2 if it is good then 5 with 7 if it is good isbst returns 1 this code is supposed to do it recursively the node structure struct node int data struct node left struct node rightthe code int lisgoodstruct node n1struct node n2 ifn2 null return 1 else int r lisgoodn1n2leftlisgoodn1n2right ifr ifn1data n2data return r else return 0 else return r int risgoodstruct node n1struct node n2 ifn2 null return 1 else int r risgoodn1n2rightrisgoodn1n2left ifr ifn1data n2data return r else return 0 else return r int isbststruct node node ifnode null return 1 else iflisgoodnodenodeleftrisgoodnodenoderight return isbstnodeleftisbstnoderight else return 0,['c'] +914241,android studio execution failed for task appcompiledebugaidl failed i installed android studio 1211 with gradle version 221 and android plugin version 123 i tried to create a simple hello world project and it give me a build failure of appcompiledebugaidl failed am i missing something or have some incompatible issue with version as this should be a simple application thanks for any helpthis is the compilation errors i am gettinginformationgradle tasks appassembledebugaprebuild uptodateapredebugbuild uptodateappcheckdebugmanifestaprereleasebuild uptodateapreparecomandroidsupportappcompatv720library uptodateapreparecomandroidsupportsupportv420library uptodateapreparedebugdependenciesappcompiledebugaidl failederrorexecution failed for task appcompiledebugaidl aidl is missinginformationbuild failed,['android'] +914305,autosuggestion is not working using canjs i am trying to to create auto suggest element manually i am using canjs for this pruposefollowing code i have tried so farlistfilter function item index list ifitemincludessearchtext searchtext css hide and show classes for match else css show for unmatched results in above code i am facing two problemsincludes does not work in all browsers for that i have tried matchcontains and substring but they could not help meincludes working in chrome but when i entered the string whose substring is not contained by the last element of list it will notwork because filter will keep searching from all the elementsis there any mistake i am doingi want to it to run in all the browserthank you,['javascript'] +914332,hashmap contains and get methods should not be used together i got the following question from an interviewi was given a character array like thischar characters u a u i o f ui needed to get the thistinct characters and counts of each characteru 3a 1i 1o 1f 1so i answered in java with the following codehashmapcharacter integer map new hashmapcharacter integerint i 1for char c characters if mapcontainskeyc int val mapgetc mapputc val else mapputc ithe interviewer was a solution architect he asked me why i was using both containskey and get methods here and noted that it was redundant to use both methods what is his point what was i doing wrong here will my code cause a performance issue etc,['java'] +914385,jekyll generate an include once and include it to all pages tldr can i say somehow to generate the content for a include once and just stamp it out in multiple places without having to regenerate it in every locationi am building a fairly big documentation site with jekyll which has right now a bit over 50 articles on it it has a sidebar where all articles are listed the sidebar is built in a separate sidebarhtml and then it is included into every page on the site with include sidebarhtml in defaulthtmlthe problem i have is that every single article runs the generation of sidebarhtml separately so i have over 50 generation passes on that piece of code every article i add adds another pass to this and make all the passes a bit slower as generating the sidebar has to parse every single article in the project build time has gone up from basically zero to over 100 seconds already and if i remove the include sidebarhtml then it drops down to 5 seconds when i get all the articles in i would estimate to have around 100200 of them then i should have versioning in the future for all articles which means that there can easily be 10 articles in the long run at that point i wouldnt be suprised if changing one letter in one file would take something like an hour to regenerate files in jekyll serveand jekyll buildwhat i would like to do is to build sidebarhtml once in the beginning of the build process and just stamp it out to every page when i generate said pages is this possible,['html'] +914435,how to upload files to another users google drive without asking permission every time is there any way to upload files to another users google drive without asking for login or verification code each time except the first timeuntil now i used pydrive but it asks to login each time is there anyway other than this such that a key or something to use to skip the login of the user,['python'] +914575,slide to delete with rotation i need to remove view with rotation using on touch event my view is not lightweight it contain a web browser and other elementsi implemented slide to delete without rotation and it works not very fast but it works after adding the rotation very very slowlyi looking for fast method to remove with rotation as i understand i can to read bitmap from the screen hide my view and paint this bitmap on canvas i think that this method should works finemy question iswhat library can i use what about screen rotation i must to clear canvas remove mybitmap restore my view and reset touch events maybe i can use analog of internal drag and drop hm this is good idea but how to make fullsize shadow and animate action moving out of the screenhow do you solve such problemsupdate for mohammed alii can to read bitmap of my view and draw it on canvas opaque shadow for drag and drop shadow size,['android'] +914600,measurement of tlb effects on a cortexa9 after reading the following paper what every programmer should know about memory i wanted to try one of the authors test that is measuring the effects of tlb on the final execution timei am working on a samsung galaxy s3 that embeds a cortexa9according to the documentationwe have two micro tlbs for instruction and data cache in l1 the main tlb is located in l2 data micro tlb has 32 entries instruction micro tlb has either 32 or 64 entriesl1 size 32 kbytesl1 cache line 32 bytesl2 size 1mbi wrote a small program that allocates an array of structs with and entries each entrys size is 32 bytes so it fits in a cache linei perform several read access and i measure the execution timetypedef struct int elmt sizeofint 4 bytes char padding28 4 28 32b cache line sizeentryvolatile entry entries nullallocate memory and init to 0entries callocnb entries sizeofentry ifentries null perrorcalloc failed exit1fori 0 i nb entries i entriesi mmapnull 4096 prot read prot write map private map anonymous 0 0 ifentriesi map failed perrormmap failed exit1entrieslast elementelmt 1randomly access and init with random valuesn 1i 0whilen nb entries 1 init with random value entriesielmt rand nb entries loop till we reach the last element whileentriesentriesielmtelmt 1 entriesielmt ifentriesielmt nb entries entriesielmt 0 i entriesielmtgettimeofdaytstart nullfori 0 i nb loops i j 0 whilej 1 j entriesjelmt gettimeofdaytend nulltime tendtv sec tstarttv sectime 10time tendtv usec tstarttv usectime 10time nb entries nbloopsfprintfstdout d 3lld02lldn nb entries time 100 time 100i have an outer loop that makes nb entries vary from 4 to 1024 as one can see in the figure below while nb entries 256 entries executing time is longerwhen nb entries 404 i get an out of memory why micro tlbs exceeded main tlbs exceeded page tables exceeded virtual memory for the process exceededcan someone explain me please what is really going on from 4 to 256 entries then from 257 to 404 entriesedit 1as it has been suggested i ran membench src code and below the resultsedit 2in the following paper page 3 they ran i suppose the same benchmark but the different steps are clearly visible from their plots which is not my caseright now according to their results and explanations i only can identify few thingsplots confirm that l1 cache line size is 32 bytes because as they said once the array size exceeds the size of the data cache 32kb the reads begin to generate misses an inflection point occurs when every read generates a missein my case the very first inflection point appears when stride 32 bytes the graph shows that we have a secondlevel l2 cache i think it is depicted by the yellow line 1mb l2 size therefore the two last plots above the latter probably reflects the latency while accessing main memory tlbhowever from this benchmark i am not able to identifythe cache associativity normally dcache and icache are 4way associative cortexa9 trm the tlb effects as they said in most systems a secondary increase in latency is indicative of the tlb which caches a limited number of virtual to physical translations the absence of a rise in latency attributable to tlb indicates that large page sizes have probably been usedimplementededit 3this link explains the tlb effects from another membench graph one can actually retrieve the same effects on my graphon a 4kb page system as you grow your strides while they are still 4k youll enjoy less and less utilization of each page youll have to access the 2nd level tlb on each access the cortexa9 supports 4kb pages modeindeed as one can see in my graph up to strides 4k latencies are increasing then when it reachs 4k you suddenly start benefiting again since youre actually skipping whole pages,['c'] +914641,how regular expression or operator is evaluated in tsql i have generated uniqueidentifier using newid function for example723952a796c6421f961f80e66a4f29d2then all dashes are removed and it looks like this723952a796c6421f961f80e66a4f29d2now i need to turn the string above to a valid uniqueidentifier using the following format x and setting the dashes againto achieve this i am using sql clr implementation of the c regexmatches function with this 8124 regular expression which gives me thisselect from dboregexmatches 723952a796c6421f961f80e66a4f29d2 8124using the above i can easily build again a correct uniqueidentifier but i am wondering how the or operator is evaluated in the regular expression for example the following will not workselect from dboregexmatches 723952a796c6421f961f80e66a4f29d2 8412is it sure that the first regular expression will first match the start and the end of the string then the other values and is always returning the matches in this order i will have issues if for example 96c6 is matched after 421f,"['c#', '.net']" +914677,swift nshttpcookie is nil i am trying to write a couple cookies in swift so that when i thisplay a webview it will be able to read those cookies and react appropriately i found many examples of how to create the cookie and read the apple docs but i can not seem to get a valid nshttpcookie object it is always nilheres my codelet basehost domaincomlet oneyearinseconds nstimeinterval60 60 24 365func setcookiekey string value anyobject var cookieprops nshttpcookieoriginurl basehost nshttpcookiepath nshttpcookiename key nshttpcookievalue value nshttpcookiesecure true nshttpcookieexpires nsdatetimeintervalsincenow oneyearinseconds var cookie nshttpcookieproperties cookieprops this line fails due to the nil cookie nshttpcookiestoragesharedhttpcookiestoragesetcookiecookiemy cookie variable is nil i have tried many combinations of the properties including having both nshttpcookieoriginurl and nshttpcookiedomain with and without nshttpcookiesecure and even without nshttpcookieexpires always nildoes anyone have any ideas what i am doing wrong,['ios'] +914740,activatorcreateinstance creates value of type t instead of nullable look at the sample code belowvar genericnullabletype typeofnullablevar nullabletype genericnullabletypemakegenerictypetypeofboolvar returnvalue activatorcreateinstancenullabletype objectfalsefor some reason returnvalue variable will be of type bool and not bool why is that and how could it be avoidedupd here is a screenshot from my vs,['c#'] +914744,how to close asynchttpclient with netty for an asynchronous http request using the asynchttpclient with netty provider will prevent the main program to terminate when we execute an asynchronous requestfor instance the following program terminates after the println or not depending on whether the provider is jdkasynchttpprovider or nettyasynchttpproviderpublic class program public static completablefutureresponse getdataasyncstring uri final asynchttpclient asynchttpclient new asynchttpclient final completablefutureresponse promise new completablefuture asynchttpclient preparegeturi executenew asynccompletionhandlerresponse override public response oncompletedresponse resp throws exception promisecompleteresp asynchttpclientclose is this correct return resp return promise public static void mainstring args throws exception final string uri a systemoutprintlngetdataasyncuriget about the asynhttpclient the documentation states ahc is an abstraction layer that can work on top of the bare jdk netty and grizzly note that the jdk implementation is very limited and you should really use the other real providersto use asynchttpclient with netty we just need to include the corresponding library in the java class path so we may run the previous program with one of the following class path configurations to use netty or not cp asynchttpclient1924jarnetty3103finaljarslf4japi1712jar will use nettyasynchttpprovidercp asynchttpclient1924jarslf4japi1712jar will use jdkasynchttpproviderwhat else should we do to use netty provider correctly for instance i am closing the asynchttpclient in asynccompletionhandler is that correctis there any configuration to change the observed behavior,['java'] +914750,ionic app image upload from camera photo library i am working on a ionic chat app where the user can upload a photo as part of their message i am looking for a way to upload the image to my webhost server so i can retrieve it later via a urlthe problem is that i am not able to get it to upload to my web serveri am using these two pluginsorgapachecordovafiletransfercordovaplugincamerawhen i run the app in xcode simulator and select a picture from the device photolibrary the console gives me the following messagesfile transfer finished with response code 200void senddelegatemessagensinvocation delegate webviewrunjavascriptalertpanelwithmessageinitiatedbyframe failed to return after waiting 10 seconds main run loop mode kcfrunloopdefaultmodesuccess this is the code i currently useappcontrollerhomecontroller functionrootscope scope cordovacamera ionicactionsheet cordovafiletransfer open photolibrary scopeopenphotolibrary function var options quality 100 destinationtype cameradestinationtypefile uri sourcetype camerapicturesourcetypephotolibrary allowedit true encodingtype cameraencodingtypejpeg popoveroptions camerapopoveroptions savetophotoalbum false cordovacameragetpictureoptionsthenfunctionimagedata consolelogimagedata consolelogoptions var url target path may be local or url var targetpath imagedata var filename targetpathsplitpop var options filekey file filename filename chunkedmode false mimetype imagejpg cordovafiletransferuploadurl targetpath optionsthenfunctionresult consolelogsuccess jsonstringifyresultresponse alertsuccess alertjsonstringifyresultresponse functionerr consolelogerror jsonstringifyerr alertjsonstringifyerr function progress constant progress updates timeoutfunction scopedownloadprogress progressloaded progresstotal 100 functionerr error consolelogerr this is my uploadphp filephp move uploaded file filesfiletmp name cwd filesimagesmove uploaded file filesfiletmp name filesimages,['ios'] +914752,prevent interface builder from auto creating constraints i created a demo project here i have a view where i created a scrollview in a xib file in interface builder i did not set any constraints in my viewdidload method i set constraints with snapkitscrollviewsnp makeconstraints make void in makeedgesequaltoselfviewwhen i run the code i get the following console output unable to simultaneously satisfy constraints probably at least one of the constraints in the following list is one you do not want try this 1 look at each constraint and try to figure out which you do not expect 2 find the code that added the unwanted constraint or constraints and fix it note if youre seeing nsautoresizingmasklayoutconstraints that you do not understand refer to the documentation for the uiview property translatesautoresizingmaskintoconstraints nsibprototypinglayoutconstraint0x7b74e280 ib auto generated at build time for view with fixed frame v1uiscrollview0x7b74c430 names uiview0x7b74dd10 deviceimagestestlayoutconstraint0x7baa2760 uiscrollview0x7b6608d0top uiview0x7b64d800topwill attempt to recover by breaking constraint nsibprototypinglayoutconstraint0x7b74e280 ib auto generated at build time for view with fixed frame v1uiscrollview0x7b74c430 names uiview0x7b74dd10 break on objc exception throw to catch this in the debuggerthe methods in the uiconstraintbasedlayoutdebugging category on uiview listed in uikituiviewh may also be helpful20150529 183714368 deviceimagestest36462607 unable to simultaneously satisfy constraints probably at least one of the constraints in the following list is one you do not want try this 1 look at each constraint and try to figure out which you do not expect 2 find the code that added the unwanted constraint or constraints and fix it note if youre seeing nsautoresizingmasklayoutconstraints that you do not understand refer to the documentation for the uiview property translatesautoresizingmaskintoconstraints nsibprototypinglayoutconstraint0x7b74e080 ib auto generated at build time for view with fixed frame h0uiscrollview0x7b74c430ltr names uiview0x7b74dd10 nsibprototypinglayoutconstraint0x7b74e330 ib auto generated at build time for view with fixed frame huiscrollview0x7b74c430600 deviceimagestestlayoutconstraint0x7baa7170 uiscrollview0x7baa7b30right uiview0x7baa79a0right nsautoresizingmasklayoutconstraint0x7baa4800 h v uiview0x7b74dd10width uiviewcontrollerwrapperview0x7ba9f060width nsautoresizingmasklayoutconstraint0x7baa5180 h v uiviewcontrollerwrapperview0x7ba9f060width uinavigationtransitionview0x7bc769b0width nsautoresizingmasklayoutconstraint0x7baa58e0 h v uinavigationtransitionview0x7bc769b0width uilayoutcontainerview0x7bc75140width nsautoresizingmasklayoutconstraint0x7baa61a0 h v uilayoutcontainerview0x7bc75140width uiwindow0x7bc71870width nsautoresizingmasklayoutconstraint0x7baa69a0 h v huiwindow0x7bc71870320will attempt to recover by breaking constraint deviceimagestestlayoutconstraint0x7baa95b0 uiscrollview0x7baa9610right uiview0x7baa96b0rightbreak on objc exception throw to catch this in the debuggerthe methods in the uiconstraintbasedlayoutdebugging category on uiview listed in uikituiviewh may also be helpful20150529 183714496 deviceimagestest36462607 unable to simultaneously satisfy constraints probably at least one of the constraints in the following list is one you do not want try this 1 look at each constraint and try to figure out which you do not expect 2 find the code that added the unwanted constraint or constraints and fix it note if youre seeing nsautoresizingmasklayoutconstraints that you do not understand refer to the documentation for the uiview property translatesautoresizingmaskintoconstraints nsibprototypinglayoutconstraint0x7b74e360 ib auto generated at build time for view with fixed frame vuiscrollview0x7b74c430600 deviceimagestestlayoutconstraint0x7bc77e40 uiscrollview0x7bc7f6a0top uiview0x7bc52180top deviceimagestestlayoutconstraint0x7bc49420 uiscrollview0x7bc74b00bottom uiview0x7bc7b970bottom nsautoresizingmasklayoutconstraint0x7baa4960 h v uiview0x7b74dd10height uiviewcontrollerwrapperview0x7ba9f060height nsautoresizingmasklayoutconstraint0x7baa51e0 h v uiviewcontrollerwrapperview0x7ba9f060height uinavigationtransitionview0x7bc769b0height nsautoresizingmasklayoutconstraint0x7baa5940 h v uinavigationtransitionview0x7bc769b0height uilayoutcontainerview0x7bc75140height nsautoresizingmasklayoutconstraint0x7baa6200 h v uilayoutcontainerview0x7bc75140height uiwindow0x7bc71870height nsautoresizingmasklayoutconstraint0x7baa69d0 h v vuiwindow0x7bc71870568will attempt to recover by breaking constraint deviceimagestestlayoutconstraint0x7bc84790 uiscrollview0x7bc848b0bottom uiview0x7bc84860bottombreak on objc exception throw to catch this in the debuggerthe methods in the uiconstraintbasedlayoutdebugging category on uiview listed in uikituiviewh may also be helpfulit seems that interface builder is generating constraints for me even if i did not set any this leads to a conflict with my constraints i set in code i also set settranslatesautoresizingmasksfalsehow can i prevent interface builder from auto generating constraints,['ios'] +914801,react components render correctly in browser but jest test errors when rendering only a reactowner can have refs i have two components in react that render just fine and produce expected behavior in the browser but cannot seem to be rendered when running a test via jestdescriptionsjsvar react requirereactaddonsvar requirejqueryvar description requiredescriptionjsvar descriptions reactcreateclass getinitialstate function container always starts with at least one description field that is empty or whatever is contained in props var descriptions if thispropsinfo null descriptionspushnum 0 data else eachthispropsinfo function i string descriptionspushnum i data string if descriptionslength 0 we want at least one description field at all times descriptionspushnum 0 data return descriptions descriptions focus 1 componentwillreceiveprops function nextprops props are updated var descriptions we do not care about previous values so we will make a new list eachnextpropsinfo function i string descriptionspushnum i data string if descriptionslength 0 we want at least one description field at all times descriptionspushnum 0 data thissetstatedescriptions descriptions adescription function pos adds a new description underneath the last one in the container var descriptions thisstatedescriptions var max 0 eachdescriptions function i item if itemnum max max itemnum descriptionssplicepos 1 0 num max 1 data thissetstatedescriptions descriptions focus pos 1 focus the new description removedescription function pos remove a description from the array given its array position var descriptions thisstatedescriptions if descriptionslength 1 descriptionssplicepos 1 thissetstatedescriptions descriptions focus pos 0 0 pos 1 render function var items thisstatedescriptionsmapfunction item i add one description for every item in the array return description keyitemnum adescriptionthisadescription removedescriptionthisremovedescription descriptionnumi focusi thisstatefocus dataitemdata bindthis return div classnamedescriptions items div moduleexports descriptionsessentially this component is a container for one or more child description components and the amount of description components that need to be rendered depends on the passed info prop which holds an array of stringsdescriptionjsvar react requirereactaddonsvar description reactcreateclass mixins reactaddonslinkedstatemixin componentdidmount function focus the input if it was added after page load if thispropsfocus thisrefsdescinputgetdomnodefocus componentwillreceiveprops function nextprops if nextpropsfocus thisrefsdescinputgetdomnodefocus thissetstatedescription nextpropsdata getinitialstate function returndescription thispropsdata handlekeydown function e var key ekeycode if key 13 enter is pressed we need to add a new line underneath this one epreventdefault thispropsadescriptionthispropsdescriptionnum else if key 8 backspace was pressed check to see if line is empty and remove if so var value thisrefsdescinputgetdomnodevalue if value null value epreventdefault thispropsremovedescriptionthispropsdescriptionnum render function return div classnamedescription input typetext onkeydownthishandlekeydown valuelinkthislinkstatedescription refdescinput div moduleexports descriptionthis component receives a string or nothing sets its state to contain that string and uses the linkedstatemixin to update the state whenever the value of the input changes and viceversai thought i had no issues with these components but the following jest testdescriptionstestjsjestdontmockjsdescriptionsjsvar react requirereactaddonsvar testutils reactaddonstestutilsdescribedescriptions function itcreates exactly two description components when given a string array of length 2 function jestdontmockjsdescriptionjs var description requirejsdescriptionjs var info foobar var descriptions requirejsdescriptionsjs var descriptions testutilsrenderintodocumentdescriptions infoinfo var array testutilsscryrenderedcomponentswithtypedescriptions description expectarraylengthtoequal2 fails with the following errora descriptions ao it mocks description exactly twice when given info array of length 2 error invariant violation addcomponentasrefto only a reactowner can have refs this usually means that youre trying to add a ref to a component that does not have an owner that is was not created inside of another components render method try rendering this component inside of a new toplevel component which will hold the refon this linevar descriptions testutilsrenderintodocumentdescriptions infoinfothis makes no sense to me as the components render fine in the browser without any issues it seems to only break when reacts testutils attempts to do ithere are my dependenciespackagejsondependencies jquery 214 react 0133 reacttools 0133devdependencies browserify 1021 gulp 3811 gulpreact 301 gulpshell 041 gulpstreamify 005 gulpuglify 110 jestcli 045 nodelibsbrowser 052 reactify 1 vinylsourcestream 110 watchify 321 webpack 1910does anyone know what might be causing this error,['javascript'] +914818,integration tests with spring security i need to send a get request to the api but despite having placed the administrator annotation get error withmockuserrolesadministrador how do i send a requestapi requestmappingvalue id method requestmethodget postauthorizereturnobjectinstancia principalinstanciainstancia public validacao retrievepathvariableid string id return validacaoserviceretrieveid test test withmockuserroles administrador public void testcretrieve throws exception thismockmvc performgetapivalidacao idwithuser andexpectstatusisok andreturn logorgspringframeworkwebutilnestedservletexception request processing failed nested exception is orgspringframeworksecurityauthenticationauthenticationcredentialsnotfoundexception an authentication object was not found in the securitycontexttest classfixmethodordermethodsortersname ascendingrunwithspringjunit4classrunnerclasscontextconfigurationclasses validacaoapitesttestconfigurationclass withsecurityconfigclasswebappconfigurationpublic class validacaoapitest enablewebmvc configuration public static class testconfiguration fongo fongo new fongonew server 1 db db fongogetdboknok bean validacaoapi getvalidacaoapi return new validacaoapi bean activeuser getactiveuser activeuser mock mockitomockactiveuserclass whenmockgetuserthenreturnnew usersetemail whenmockgetinstanciathenreturnnew instanciasetinstanciainstancia return mock bean validacaoservice getvalidacaoservice return new validacaoservice bean matchservice getmatchservice return new matchservice bean planilhareader getplanilhareader return new planilhareader bean atributoreader getatributoreader return new atributoreader bean atributodao getatributodao return new atributodao bean uploadservice getuploadservice return new uploadservice bean validacaoresultadodao getvalidacaoresultadodao return new validacaoresultadodaodb bean mapper getmapper return new mapperdb bean uploaddao getuploaddao return new uploaddaodb bean matchdao getmatchdao return new matchdaodb bean validacaodao getvalidacaodao return new validacaodaodb bean uploadoriginalsdao getuploadoriginalsdao return new uploadoriginalsdaodb bean atributovalidator getatributovalidator return new atributovalidator autowired matchservice matchservice autowired private webapplicationcontext context private mockmvc mockmvc private static string id before public void setup mockmvc mockmvcbuilderswebappcontextsetupcontextbuild test public void testacreatevalidation throws exception mvcresult result thismockmvc performpostapivalidacao andexpectstatusisok andexpectjsonpathid notnullvalue andreturn thisid basicdbobject jsonparseresultgetresponsegetcontentasstringgetstringid test public void testbretrieveall throws exception mvcresult result thismockmvc performgetapivalidacao andexpectstatusisok andexpectjsonpath0id notnullvalue andreturn basicdblist list basicdblist jsonparseresultgetresponsegetcontentasstring thisid string basicdbobject jsonparselistget0tostringgetid fixme test withmockuserroles administrador public void testcretrieve throws exception thismockmvc performgetapivalidacao idwithuser andexpectstatusisok andreturn,['java'] +914837,pass char to method expecting unsigned char i am working on some embedded device which has sdk it has a method likemessageboxu8 u8 u8 is typedefed unsigned char when i checkedbut i have seen in their examples calling code likemessageboxhihellopassing char pointer without cast can this be well defined i am asking because i ran some tool over the code and it was complaining about above mismatchmessageboxstatus error calculating rhashdiyc 89 error 64 type mismatch arg no 1 ptrs to signedunsigneddiyc 89 error 64 type mismatch arg no 2 ptrs to signedunsignedsometimes i get different opinions on this answer and this confuses me even more so to sum up by using their api the way described above is this problem will it crash the programand also it would be nice to hear what is the correct way then to pass string to sdk methods expecting unsigned char without causing constraint violation,['c'] +914885,javaxnetsslsslexception read error ssl0x9524b800 io error during system call connection reset by peer our clients are starting to see 100s of these sslexception error connection reset by peer over the last couple of weeks and i cannot figure out whywere using retrofit with okhttp no special configurationpublic class okhttpclientprovider implements iokhttpclientprovider okhttpclient okhttpclient public okhttpclientprovider thisokhttpclient createclient public okhttpclient getokhttpclient return thisokhttpclient private okhttpclient createclient return new okhttpclient the above client provider is a singleton the restadapter is built using this injected client we use dagger restadapterbuilder restadapterbuilder new restadapterbuilder setconverterconverter setendpointnetworkrequestdetailsgetserverurl setclientnew okclientokhttpclientprovidergetokhttpclient seterrorhandlernew networksynchronouserrorhandlereventbus based on stack overflow solutions what i have found out the keep alive duration on the server is 180 seconds okhttp has a default of 300 secondsthe server returns connection close in its header but the client request sends connection keepalivethe server supports tls 10 11 12 and uses open sslour servers have moved to another hosting provider recently in another geography so i do not know if these are dns failures or notweve tried tweaking things like keepalive reconfigured openssl on the server but for some reason the android client keeps getting this errorit happens immediately without any delay when you try to use the app to post something or pull to refresh it does not even go to network or have a delay before this exception happens which would imply the connection is already broken but trying it multiple times somehow fixes it and we get a success it happens again laterweve invalidated our dns entries on the server to see if this what caused it but that has not helpedit mostly happens on lte but i have seen it on wifi as welli do not want to thisable keep alive because most modern clients do not do that also were using okhttp 24 and this is a problem on post ice cream sandwich devices so i am hoping it should take care of these underlying networking issues the ios client also gets these exceptions but close to a 100 times less ios client uses afnetworking 20 i am struggling to find new things to try at this point any help ideasupdate adding full stack trace through okhttp retrofitretrofiterror read error ssl0x9dd07200 io error during system call connection reset by peer at retrofitrestadapterresthandlerinvokerequestrestadapterjava390 at retrofitrestadapterresthandlerinvokerestadapterjava240 at javalangreflectproxyinvokeproxyjava397 at proxy15getaccesstokenusingresourceownerpasswordcredentialsunknown source at comcompanydroidrepositorynetworknetworkrepositorygetaccesstokenusingresourceownerpasswordcredentialsnetworkrepositoryjava76 at comcompanydroiduiloginlogintaskdoinbackgroundlogintaskjava88 at comcompanydroiduiloginlogintaskdoinbackgroundlogintaskjava23 at androidosasynctask2callasynctaskjava292 at javautilconcurrentfuturetaskrunfuturetaskjava237 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava12 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava587 at javalangthreadrunthreadjava818 caused by javaxnetsslsslexception read error ssl0x9dd07200 io error during system call connection reset by peer at comandroidorgconscryptnativecryptossl readnative method at comandroidorgconscryptopensslsocketimplsslinputstreamreadopensslsocketimpljava699 at okiookio2readokiojava137 at okioasynctimeout2readasynctimeoutjava211 at okiorealbufferedsourceindexofrealbufferedsourcejava306 at okiorealbufferedsourceindexofrealbufferedsourcejava300 at okiorealbufferedsourcereadutf8linestrictrealbufferedsourcejava196 at comsquareupokhttpinternalhttphttpconnectionreadresponsehttpconnectionjava191 at comsquareupokhttpinternalhttphttptransportreadresponseheadershttptransportjava80 at comsquareupokhttpinternalhttphttpenginereadnetworkresponsehttpenginejava917 at comsquareupokhttpinternalhttphttpenginereadresponsehttpenginejava793 at comsquareupokhttpinternalhuchttpurlconnectionimplexecutehttpurlconnectionimpljava439 at comsquareupokhttpinternalhuchttpurlconnectionimplgetresponsehttpurlconnectionimpljava384 at comsquareupokhttpinternalhuchttpurlconnectionimplgetresponsecodehttpurlconnectionimpljava497 at comsquareupokhttpinternalhucdelegatinghttpsurlconnectiongetresponsecodedelegatinghttpsurlconnectionjava105 at comsquareupokhttpinternalhuchttpsurlconnectionimplgetresponsecodehttpsurlconnectionimpljava25 at retrofitclienturlconnectionclientreadresponseurlconnectionclientjava73 at retrofitclienturlconnectionclientexecuteurlconnectionclientjava38 at retrofitrestadapterresthandlerinvokerequestrestadapterjava321 a a a a a a a a a a a a at retrofitrestadapterresthandlerinvokerestadapterjava240 a a a a a a a a a a a a at javalangreflectproxyinvokeproxyjava397 a a a a a a a a a a a a at proxy15getaccesstokenusingresourceownerpasswordcredentialsunknown source a a a a a a a a a a a a at comcompanydroidrepositorynetworknetworkrepositorygetaccesstokenusingresourceownerpasswordcredentialsnetworkrepositoryjava76 a a a a a a a a a a a a at comcompanydroiduiloginlogintaskdoinbackgroundlogintaskjava88 a a a a a a a a a a a a at comcompanydroiduiloginlogintaskdoinbackgroundlogintaskjava23 a a a a a a a a a a a a at androidosasynctask2callasynctaskjava292 a a a a a a a a a a a a at javautilconcurrentfuturetaskrunfuturetaskjava237 a a a a a a a a a a a a at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava12 a a a a a a a a a a a a at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava587 a a a a a a a a a a a a at javalangthreadrunthreadjava818,['android'] +914898,img dir cannot be stored in db but viewed from the same variables used in query i am trying to upload an image to my server using the following form by sanwebecan be found herehowever when i am pressing upload the new thumb loads perfectly fine however my image cannot be uploaded to the database using the exact same variables from which the image is being viewed how comei tried putting the db information just infront of the query like thisecho div aligncenterecho img srcimagesprofilepicturesthumb prefix new file name altthumbnailecho divprofile pic temp imagesprofilepictures thumb prefix new file nameprofile pic full temp imagesprofilepictures new file namesession user sessionuser confirmrequire databasephpprofile pic db upload dbprepareupdate login set profile picture temp profile pic temp profile picture full temp profile pic full temp where user session session userprofile pic db uploadbindparamsession user session user pdoparam strprofile pic db uploadbindparamprofile pic temp profile picture temp pdoparam strprofile pic db uploadbindparamprofile pic full temp profile picture full temp pdoparam strprofile pic db uploadexecuteconfirm upload db profile pic db uploadrowcountifconfirm upload db 0 popup message profile picture has been uploaded echo popup messageelse popup message profile picture could not be uploaded echo popup messageedit twothe query now runs however i get the feedback profile picture could not be uploaded how come the query does not run properlyedit fouri have tried changing the user session session user to id 1 instead i then get upload successfull however the value is only inserted into profile picture temp and is set to 0 somehow the bindparam changes the value whyedit threei have now tried using mysqli aswell same results here returning could not be uploaded however does not change value in dbsql update login set profile picture temp and profile picture full temp where user session stmt mysqlipreparesql or die database errorbr sql brberror messageb mysqlierrorstmtbind params profile picture temp profile picture full temp session userstmtexecute or diesomething went wrongifstmtfetch popup message profile picture has been uploaded echo popup messageelse popup message profile picture could not be uploaded echo popup messagestmtfree resultstmtclose,"['php', 'jquery', 'mysql', 'sql']" +914978,npms guidelines on callback errors i was reading through npmas coding style guidelines and came across the following very cryptic suggestionbe very careful never to ever ever throw anything itas worse than useless just send the error message back as the first argument to the callbackwhat exactly do they mean and how does one implement this behavior do they suggest calling the callback function within itselfhereas what i could think of using the async fsreaddir methodfsreaddir function callbackerr files if err throw err npm says do not do this callbackerr wouldnat this cause an infinite loop else normal stuff,['javascript'] +915009,is it possible to hide python function arguments in sphinx suppose i have the following function that is documented in the numpydoc style and the documentation is autogenerated with the sphinx autofunction directivedef foox y hidden argumentnone foo a bar parameters x str the first argument to foo y str the second argument to foo returns the barred foo if hidden argument end users shouldnt call this functionx y return x yi do not want to advertise the hidden argument as part of my public api but it shows up in my autogenerated documentation is there any way to tell sphinx to ignore a specific argument to a function or even better make it autoignore arguments with a leading underscore,['python'] +915021,objectis vs i stumbled upon a code example which was using this comparisonvar somevar 0objectisfalse somevar returns false i know false 0 will be true that is why we have how is objectis different from,['javascript'] +915028,java wildcard generic as return warning in eclipse and sonarqube private list gridmodelpublic list getgridmodel return gridmodeleclipse shows a warninglist is a raw type references to generic type list should be parameterizedchanging the code to below will remove the warningprivate list gridmodelpublic list getgridmodel return gridmodelhowever the above code shows a major pitfall error in sonarqube which saysremove usage of generic wildcard type generic wildcard types should not be used in return parametersso how can i fix this warningi see a similar question here but could not find the solution using class extends object did not remove sonar warning,['java'] +915054,using genymotion emulator with ionic framework i have downloaded and installed genymotion and created and built my ionic applicationwhen i try to run the genymotion emulator using the following commandionic run androidi get the following responseno target specified deploying to emulator no emulator specified defaulting to nexus 5 api 21 x86 waiting for emulator emulator error x86 emulation currently requires hardware acceleration please ensure intel haxm is properly installed and usable cpu acceleration status hax kernel module is not installed the emulator is not working any ideas,['android'] +915123,how to change the floating label color of textinputlayout with reference to the new textinputlayout released by google how do i change the floating label text colorsetting colorcontrolnormal colorcontrolactivated colorcontrolhighlight in styles does not helpthis is what i have now,['android'] +915142,dynamically resize a bufferedimage in java i tried resizing the buffered image using affinetransform as well as scalrresizehere are my codes for both of themusing scalrresize bufferedimage buff robotcreatescreencapturenew rectanglebufxbufybufwidthbufheight xcoord ycoord width height bufferedimage scrcapt scalrresizebuff methodbalanced scrwidth scrheightusing affinetransformbufferedimage buff robotcreatescreencapturenew rectanglebufxbufybufwidthbufheight xcoord ycoord width heightbufferedimage scrcapt new bufferedimagebufwidthbufheightbufferedimagetype int argbaffinetransform atscr new affinetransformatscrscaleaspectratiowidthaspectratioheightaffinetransformop scaleop new affinetransformopatscr affinetransformoptype bilinearscrcapt scaleopfilterbuff scrcaptthe variables have been declared in the beginning inside clastatic int bufx 0static int bufy 0static int bufwidth 1static int bufheight 1static int scrwidth 0static int scrheight 0static float aspectratiowidth 0static float aspectratioheight 0i am getting the values for for all the variables dynamically inside a different methodaspectratiowidth bufwidthscrwidthaspectratioheight bufheightscrheighthowever when i run this code i get an error in both the functions affinetransform as well as scalrresizescalrresizeexception in thread thread2 javalangillegalargumentexception width 0 and height 0 cannot be 0at javaawtimagedirectcolormodelcreatecompatiblewritablerasterdirectcolormodeljava1016at javaawtimagebufferedimageinitbufferedimagejava331at orgimgscalrscalrcreateoptimalimagescalrjava2006at orgimgscalrscalrscaleimagescalrjava2133at orgimgscalrscalrresizescalrjava1667at orgimgscalrscalrresizescalrjava1415affinetransformexception in thread thread2 javaawtimageimagingopexception unable to invert transform affinetransform00 00 00 00 10 00at javaawtimageaffinetransformopvalidatetransformaffinetransformopjava558at javaawtimageaffinetransformopinitaffinetransformopjava151how do i go about thisi understand that this is happening because i am changing the variable in a different method and accessing them in another onebut those two methods cannot be combinedis there any way i can make this work editi changed the method of resizingheres what i did nowpublic static bufferedimage resizeimagebufferedimage image double scalewidth double scaleheight bufferedimage img new bufferedimageimagegetwidth imagegetheightbufferedimagescale fast graphics2d g imgcreategraphics gscalescalewidth scaleheight gdrawimageimage null 0 0 gthispose return imageedit2for a clearer idea of what is happening exactlythis is a method which returns scrwidth and scrheightpublic static void showonscreen int screen jframe framenew graphicsenvironment ge graphicsenvironment getlocalgraphicsenvironment graphicsdevice gs gegetscreendevices for int i 0 i gslength i screenwidthaddgsigetthisplaymodegetwidth screenheightaddgsigetthisplaymodegetheightscrwidth screenwidthgetscreenwidthsize1scrheight screenheightgetscreenheightsize1 systemoutprintge systemoutprintgs if screen 1 screen gslength gsscreensetfullscreenwindow framenew else if gslength 0 gs0setfullscreenwindow framenew else throw new runtimeexception no screens found and this is the actionlistener which returns bufwidth and bufheight btnnewbuttonaddactionlistenernew actionlistener public void actionperformedactionevent e execute when button is pressed systemoutprintlnyou clicked the button int ind cgetselectedindex bufx capxgetind bufy capygetind bufwidth capwidthgetind bufheight capheightgetind framesetvisiblefalse framenewsetvisibletrue showonscreen1framenew aspectratiowidth double bufwidthscrwidth aspectratioheight double bufheightscrheight systemoutprintaspectratiowidth systemoutprintlnaspectratiowidth systemoutprintaspectratioheight systemoutprintlnaspectratioheight and aspectratios are used inside runpublic void run systemoutprintaspectratiowidth systemoutprintlnaspectratiowidthsystemoutprintaspectratioheight systemoutprintlnaspectratioheightwhiletrue bufferedimage buff robotcreatescreencapturenew rectanglebufxbufybufwidthbufheight xcoord ycoord width height bufferedimage resizedbuff resizeimagebuff aspectratiowidth aspectratioheight,['java'] +915188,reactively changing colour of an infobox upon a click or hover over i would like to use the reactivevalue observe observeevent framework in shiny and shinydashboard to be able to reactively change the colour of an infobox when clickedi would also like it to thisplay an image with some text in a popup box when hovering over the infoboxas a basis of code as a reproducible example please see thisbut the code is availible below libraryshinydashboard ui dashboardpage dashboardheadertitle info boxes dashboardsidebar dashboardbody infoboxes with fillfalse fluidrow a static infobox infoboxnew orders 10 2 icon iconcreditcard dynamic infoboxes infoboxoutputprogressbox infoboxoutputapprovalbox infoboxes with filltrue fluidrow infoboxnew orders 10 2 icon iconcreditcard fill true infoboxoutputprogressbox2 infoboxoutputapprovalbox2 fluidrow clicking this will increment the progress amount boxwidth 4 actionbuttoncount increment progress server functioninput output outputprogressbox renderinfobox infobox progress paste025 inputcount icon iconlist color purple outputapprovalbox renderinfobox infobox approval 80 icon iconthumbsup lib glyphicon color yellow same as above but with filltrue outputprogressbox2 renderinfobox infobox progress paste025 inputcount icon iconlist color purple fill true outputapprovalbox2 renderinfobox infobox approval 80 icon iconthumbsup lib glyphicon color yellow fill true shinyappui serveris that possible,"['javascript', 'html']" +915197,central login with saml and making site to work as identity provider so my scenario goes like i have two sites acom and site bcom and one authentication server cauthcomwhat client wants is when user lands on acom or bcom user fills in the login form on respective site but the action of form will be on cauthcom cauthcomauthenticate when user is authenticated on cauth he is loggined on the both sitesi am thinking to implement saml to achieve the same and flow is likeafter authentication idpcauthcom will send saml response to the both the service providers and user will be given access to both the sites i am novice in saml and unable to get proper documentation and comprehension for the samewhat i want to know is is my solution to the problem worth implementation is it possible to make site cauthcom as identity provideri have looked at thread making your php website into saml identity provider but not able to get proper solution,['php'] +915301,getting autofac to work with mvc6 beta5 i am trying to get autofac working with an mvc6 application i am working on i found this blog article however it seems to be a little dated it looks like its using the beta3 bits i am using this clr version100beta511911my project has these 2 referencesautofac 400alpha2autofacdnx 400alpha2within the article is talks about how to modify the startupcs create the autofac container builder var builder new autofaccontainerbuilder add any autofac modules or registrations builderregistermodulenew autofacmodule populate the services builderpopulateservices build the container var container builderbuild return containerresolveiserviceproviderthe above code complains about builderpopulateservices giving me an errorthe type iservicedescriptor is defined in an assembly that is not referenced you must add a reference to assembly microsoftframeworkdependencyinjectioniservicedescriptor version0 cultureneutral publickeytokennullfrom me research it looks like in beta4 dependencyinjectioniservicedescriptor was removed has anyone else managed to get autofac working with the latest beta5 bits,"['c#', 'asp.net']" +915418,building an animation using python gizeh i am able to create a simple diagram with shapes and numbersi am using the following codeimport gizeh as gzw h 500 300surface gzsurfacewh bg color1071for a in range19 rect gzrectanglelx 10 ly 10 xywaha fill 0107 rectdrawsurface txt gztextstra fontfamilydancing script fontsize15 fill0xywaha txtdrawsurfacesurfaceipython thisplayi have also created a version using moviepyimport numpy as npimport gizeh as gzimport moviepyeditor as mpyw h 500 300duration 5figpath tmpfps 1def make framet surface gzsurfacewh bg color1 rect gzrectanglelx 10 ly 10 xywt1h2 fill 0107 rectdrawsurface txt gztextstrt1 fontfamilydancing script fontsize15 fill0xywt1h2 txtdrawsurface return surfaceget npimageclip mpyvideoclipmake frame durationdurationclipwrite videofilefigpath trax 0mp4 fpsfpsclipipython thisplayfpsfps widthw autoplay0 loop0i would like to be able to create animated gif using a time delay between each step of the cycle,['python'] +915421,ef db first refresh is not detecting fks to a particular table not sure whats happened to my setup but of late when i update my database with new fields or new tables that have a foreign key to a particular table person my database refresh picks up the new fields but does not recognize the fk relationships to person foreign keys to most other tables work finewhat setting might be missingperhaps a clue person acts as the base type for several other tables eg manager customer etc which all share the basic characteristics of having name birth date gender etc and the descendant tables have a primary key that also acts as foreign key to person fk relationships to the descendant tables are also not being recognized,['c#'] +915439,oracle sql date greater than statement as the title says i want to find a way to check which of my data sets are past 6 months from sysdate via queryselect from orderarchivewhere orderdate 31 dec 2014i have tried the following but it returns an error saying my date format is wrong however inserting the data i used that date format as requestedintended and had no issueserror at command line 10 column 25blockquoteerror report sql error ora01861 literal does not match format string 01861 0 literal does not match format stringcause literals in the input must be the same length as literals in the format string with the exception of leading whitespace if the fx modifier has been toggled on the literal must match exactly with no extra whitespaceaction correct the format string to match the literal,['sql'] +915440,attribute insetforeground has already be defined after updating to the new comandroidsupportdesign20i got this error attribute insetforeground has already be definedkeep in mind that i am using romannurik scriminsetsframelayoutjava,['android'] +915451,rippledrawable mask color what is it for in referring to the rippledrawable for android l there is a way to mask away to contain the ripple effect within the view the masking is done asripple androidcolorff0ff item androiddrawabledrawablewhite ripplewe could also mask it usingripple androidcolorff0ff item androiddrawabledrawableblack rippleas mentioned in the document the mask layer is not drawn on the screen but just masking away the ripple effect i am curious why should one set a color white or black or anything there is there any significant of us setting a color as the mask or it is indeed any value will dohopes someone enlighten thanks,['android'] +915506,do parentheses make a difference when determining the size of an array the following program prints the same number twice on gcc 482include stdiohint main char a13 printfsizeof a is zun sizeof a printfsizeofa is zun sizeofaaccording to this reddit post gcc is not standardconformant in this respect because a parenthesized expression is not on the list of exceptions for when arraytopointer decay does not happenis this guy correct here is the relevant standard quoteexcept when it is the operand of the sizeof operator or the unary operator or is a character string literal used to initialize an array of character type or is a wide string literal used to initialize an array with element type compatible with wchar t an lvalue that has type array of type is converted to an expression that has type pointer to type that points to the initial member of the array object and is not an lvaluejust to be clear he argues that a should trigger arraytopointer decay because parentheses are not covered in the list above sizeof operator unary operator string literal as initializer,['c'] +915565,sys platform is not defined x64 windows this has been bugging me for a little while i recently upgraded to x64 python and i started getting this error example pip installcusersunamethistribute0635pip install pythonqtcollecting pythonqt downloading pythonqt050targzbuilding wheels for collected packages pythonqt running setuppy bthist wheel for pythonqt complete output from command cpython27pythonexe c import setuptools file cusersunameappdatalocaltemppipbuildvonat7pythonqtsetuppyexeccompileopen file readreplacern n file exec bdist wheel d cusersunameappdatalocaltemptmpghy5gtpipwheel traceback most recent call last file string line 1 in module file cusersunameappdatalocaltemppipbuildvonat7pythonqtsetuppy line 11 in module packagesqt file cpython27libthistutilscorepy line 137 in setup ok thistparse command line file cpython27libsitepackagesthistribute0635py27eggsetuptoolsthistpy line 232 in parse command line result thistributionparse command lineself file cpython27libthistutilsthistpy line 467 in parse command line args self parse command optsparser args file cpython27libsitepackagesthistribute0635py27eggsetuptoolsthistpy line 558 in parse command opts nargs thistribution parse command optsself parser args file cpython27libthistutilsthistpy line 523 in parse command opts cmd class selfget command classcommand file cpython27libsitepackagesthistribute0635py27eggsetuptoolsthistpy line 362 in get command class eprequireinstallerselffetch build egg file cpython27libsitepackagesthistribute0635py27eggpkg resourcespy line 2027 in require working setresolveselfthistrequiresselfextrasenvinstaller file cpython27libsitepackagesthistribute0635py27eggpkg resourcespy line 2237 in requires dm self dep map file cpython27libsitepackagesthistribute0635py27eggpkg resourcespy line 2466 in dep map self dep map self compute dependencies file cpython27libsitepackagesthistribute0635py27eggpkg resourcespy line 2499 in compute dependencies common frozensetreqs for extranone file cpython27libsitepackagesthistribute0635py27eggpkg resourcespy line 2496 in reqs for extra if reqmarker fnoverrideextraextra file cpython27libsitepackagesthistribute0635py27egg markerlibmarkerspy line 109 in marker fn return evalcompiled marker environment file environment marker line 1 in module nameerror name sys platform is not defined failed building wheel for pythonqtfailed to build pythonqtinstalling collected packages pythonqt running setuppy install for pythonqtsuccessfully installed pythonqt050the package was installed fine but i cannot build wheels i tried reinstalling thistribute manually by downloading a zip and running python setuppy install that installed wonderfuly without a hitch but i still have the above problemhow can i redefine sys platformalright i rolled back to x86 good ole 32 bit python and i still have the problem this is really concerning because i cannot reset this after reinstalling i looked at markerlib which looks promising but i do not know how to use it safely currently i am unable to install pretty much anything from pypi so i am giving points to increase interestany help i really want to be able to use pypi againi chose the selected answer as it is the most likely to solve the problem i myself have moved back to x86 python so i cannot test this myself therefore i encourage future visitors to try this answer but i have not myself been able to test it,['python'] +915662,using appcompat layout behavior with stringappbar scrolling view behavior throws exception i have a strange probem using the appcompat lib 2 with the new introduced layout behaviorif i use it with the value stringappbar scrolling view behavior as described here android design support lib the application terminates with the following exceptioncould not inflate behavior subclass androidsupportdesignwidgetsettings caused by javalangruntimeexception could not inflate behavior subclass androidsupportdesignwidgetsettings caused by javalangclassnotfoundexception androidsupportdesignwidgetsettings caused by javalangnoclassdeffounderror androidsupportdesignwidgetsettings caused by javalangclassnotfoundexception androidsupportdesignwidgetsettingsif i change to applayout behaviorandroidsupportdesignwidgetappbarlayoutscrollingviewbehavioreverything works finewhat i am missing,"['java', 'android']" +915751,image cannot be thisplay after uploading previously when i tried uploading image into the database the image would not thisplay when i check the path in the db and in the folder it is correctcorrect path in db and folderand then when i tried to view the image that has been uploaded it says that i do not have the permission to view it i have also tried uploaded different photo extension and different photo viewer application and i still cannot view the image apart from that i have tried w3school php5 file upload again same thing happen i cannot view my imagethis is my code if isset filesimagetmp name echo else file filesimagetmp name location serverdocument root eharsphoto filesimagename move uploaded file filesimagetmp name serverdocument root eharsphoto filesimagename mysql queryinsert into photo locationemp id values locationemp id why cannot i view my image is it because of the document root or is it something else please help me thank youupdated based on the image below my code as shown above is inside the admin folder the reason why i would like to save my images in eharsphotos so that every level of user admin admin2 and user can view the same photo that has been uploaded if you could advice me what is the best way to do in order to achieve my objective above thanks again,['php'] +915757,how to read and write map fromto parquet file in java or scala looking for a concise example on how to read and write mapstring object fromto parquet file in java or scalahere is expected structure using comfasterxmljacksondatabindobjectmapper as serializer in java ie looking for equivalent using parquetpublic static mapstring object readinputstream inputstream throws ioexception objectmapper objectmapper new objectmapper return objectmapperreadvalueinputstream new typereferencemapstring object public static void writeoutputstream outputstream mapstring object map throws ioexception objectmapper objectmapper new objectmapper objectmapperwritevalueoutputstream map,['java'] +915803,fast algorithm mapping int to monotonically increasing int subset i have encountered variations of this problem multiple times and most recently it became a bottleneck in my arithmetic coder implementation given and 256 segments of known nonnegative size si laid out in order starting from the origin and for a given x i want to find and such that s0 s1 sn1 x s0 s1 snthe catch is that lookups and updates are done at about the same frequency and almost every update is in the form of increasing the size of a segment by 1 also the bigger a segment the higher the probability it will be looked up or updated again obviously some sort of tree seems like the obvious approach but i have been unable to come up with any tree implementation that satisfactorily takes advantage of the known domain specific details given the relatively small size of n i also tried linear approaches but they turned out to be considerably slower than a naive binary tree even after some optimization like starting from the back of the list for numbers above half the totalsimilarly i tested introducing an intermediate step that remaps values in such a way as to keep segments ordered by size to make access faster for the most frequently used but the added overhead exceeded gainssorry for the unclear title despite it being a fairly basic problem i am not aware of any specific names for it,['c'] +915888,entity framework 4 loading reference exception i am having troubles loading the reference to a parent object in entity framework 4 due to lazy loading the reference to the parent object condition is not loaded on the child object thiscountlevel so i try to load it withifthisconditionreferenceisloaded thisconditionreferenceloadbut this throws the following exception the entity reference could not be loaded because it is not attached to an objectcontextso if i try to attach the existing child object thiscountlevel to the object context and then load the parent reference afterwardscontextattachtotblthiscountlevel thisi get the following exceptionan object with the same key already exists in the objectstatemanager the existing object is in the detached state an object can only be added to the objectstatemanager again if it is in the added statei feel like i am doing something wrong in the first place but i cannot figure out what so every help on this topic is very appreciated let me know if you need additional information,['c#'] +915911,what is the difference between void and voidargument type cast void funcptrint aint main int k1 void funcptr2int funcptr2 voidfuncptr funcptr2 voidintfuncptr funcptr2k return 0void funcptrint a printfd awhat is the difference between void and voidargument type in function pointer type castingas a result it does not occur warningis this wrong about void type casting,"['c++', 'c']" +916052,require js files dynamically on runtime using webpack i am trying to port a library from gruntrequirejs to webpack and stumbled upon a problem that might be a gamebreaker for this endeavorthe library i try to port has a function that loads and evaluates multiple modules based on their filenames that we get from a config file into our app the code looks like this coffeeloadmodules arrayoffilepaths new promise resolve require arrayoffilepaths ms for module in ms module moduleapi resolvethe require here needs to be called on runtime and behave like it did with requirejs webpack seems to only care about what happens in the buildprocessis this something that webpack fundamentally does not care about if so can i still use requirejs with it what is a good solution to load assets dynamically during runtimeedit loadmodule can load modules that are not present on the buildtime of this library they will be provided by the app that implements my library,['javascript'] +916056,rxjava retrofit make multiple calls i have a solid grasp of retrofit when using sync and async calls however i encountered a small problem when creating some complex task which i have tomake a request in order to get list of idsabout 2030 idsafter fetching ids list i would like to make async calls in order to get information about each object defined by id i want to make 2030 request in pararrel i desire to observe it in order to update the ui after i manage to receive all the data from async callsi read about that issue and i realized that rxjava would solve my problem but frankly i have found it really hard so far to understand the whole processit would be great if i read some correct example in order to immerse into rxjavarxandroid issue,"['java', 'android']" +916102,floatingactionbutton example with support library recently i read these postsandroid design support libraryandroid support library revision 20floatingactionbuttonbut none of them give me a detail example about creating a new floatingactionbutton so hard to understand i ask this questioncan anyone give me an example about itany help much be appreciated thanks in advanceediti just found some issues on floatingactionbutton fab and i want to improve another answer see my answer below,['android'] +916179,configure spring xml configuration namespaces to avoid idea warnings i have the following spring xml configuration headerbeans xmlns xmlnsp xmlnscontext xmlnstx xmlnsxsi xmlnstask xsischemalocation txannotationdriven transactionmanagertransactionmanager when i open file in idea i see red errors1xmlnsp uri is not registered errors in idea for beans tagbut it is working goodhow to avoid red errors psi have the following fragment in my xml configuration bean idsessionfactory classorgspringframeworkormhibernate4localsessionfactorybean property namedatasource refdatasource property nameconfiglocation valueclasspathhibernatecfgxmlvalue property property namehibernateproperties props prop keyhibernateshow sqltrueprop prop keyhibernatedialectjdbcdialectprop prop keyhibernateconnectioncharsetutf8prop prop keyhibernateshow sqltrueprop prop keyhibernateformat sqltrueprop prop keyhbm2ddlautovalidateprop props property bean,['java'] +916246,installing aws php sdk unexpected variables i am trying to use the aws php sdk and having some issues getting set up i am getting this error when i run my php script that requires the autoloader parse error syntax error unexpected value t variable in directory pathawsfunctionsphp on line 36i looked in that document and line 36 is the one that begins with if predvaluefunction filteriterable callable pred foreach iterable as value if predvalue yield value not really sure how to work around this so any tips would be greatly appreciated things i have tried installing with composer installing with zip followed these steps,['php'] +916276,what is the difference between soap and rest webservices can soap be restful from msdn magazine and i understand thatwhen restful endpoints are asked for data using http the http verb used is get using rest means that you can take advantage of http caching and other features like conditional get that aid in scaling services many of these techniques cannot be used with soap because soap uses post only over httpfrom the wikipedia page state transferrestful systems typically but not always communicate over the hypertext transfer protocol with the same http verbs get post put delete etc used by web browsers to retrieve web pages and send data to remote serversbut will it be a violation of rest architecture to use http post to get data from a resource in other words can a soap based webservice be restfulare there any other differences between restful and soap based webservice,['c#'] +916309,laravel generate slug before save im trying to learn laravel 5 with help of this wondefull websitefor my activity model i want to generate slugs before i save one to my database so i have created the following modelphp namespace appuse illuminatedatabaseeloquentmodelclass activity extends model protected table activitys protected fillable title text subtitle here i want to auto generate slug based on the title public function setslugattribute thisattributesslug str slugthistitle but when i save an object with help of the activity model slug is not filled i tried changing it to thisattributestitle test for testing but it didnt run also i tried adding parameters title slug to setslugattribute but it didnt helpwhat am i doing wrong and could someone explain the parameter that is used in some examples for setsomeattributewhyparameterherenote there is a slug field in my databaseas suggested by user3158900 i have tried public function settitleattributetitle thistitle title thisattributesslug str slugthistitle this makes my title field empty but saves the slug the way i want it why is thistitle empty then if i remove thistitle title both title and slug are empty,['php'] +916332,prevent converting uint64 t to uint16 t why does the following code compile in clang are there any c flags to prevent this from happening i would like the compiler to throw an error because i am passing a stduint64 t as an argument to a function that accepts stduint16 tinclude cstdintusing namespace stdvoid foouint16 t x int main uint64 t x 10 foox return 0,['c++'] +916413,shorthand for empty function in nodejs in js there is shorthand for an empty object which is is there shorthand for an empty function in jsthe reason being as functions are firstclass objects we use them as arguments more often but passing in an empty function is at best uglyvar foo bazfunctionin order to declare a function at somepoint we have to declare function i would like more nodejs apis to require a callback function to be passed so the api does not deceivingly look synchronous perhaps one step in that direction would be to create shorthand for empty placeholder functions,['javascript'] +916417,how do i change an android snackbars initial alignment from bottom to top the recent android library came out just a few days ago but i would like to have the snackbar appear on top of the screen preferably within a relativelayout as it is parent viewhow does one change the snackbars initial alignment which i presume to be layout alignparentbottom to layout alignparenttop,['android'] +916431,how to set system time in windows 10 iot is there a way to set system time from my app running on a raspberry pi 2 in windows 10 iot core insider preview this does not work for lack of kernel32dll dllimportkernel32dll entrypoint setsystemtime setlasterror true extern static bool win32setsystemtimeref systemtime systime,['c#'] +916567,npe when calling mockitoannotationsinitmocks in androidtestcase trying to use mockito in my androidtestcase i added the dependencies to the buildgradlefinal dexmaker version 12dependencies androidtestcompile comgoogledexmakerdexmakerdexmaker version androidtestcompile comgoogledexmakerdexmakermockitodexmaker version androidtestcompile orgmockitomockitocore11019the testcase with the mockito initializationpublic class userslistpresentertest extends androidtestcase public void setup throws exception mockitoannotationsinitmocksthis public void testinitialize throws exception but as soon as i add any attribute to the class even before adding any annotation the test start to crashpublic class userslistpresentertest extends androidtestcase string mockstring public void setup throws exception mockitoannotationsinitmocksthis public void testinitialize throws exception with the following stacktracejavalangnullpointerexception attempt to invoke virtual method javalangclass javalangobjectgetclass on a null object referenceat comgoogledexmakermockitodexmakermockmakergetinvocationhandleradapterdexmakermockmakerjava80at comgoogledexmakermockitodexmakermockmakergethandlerdexmakermockmakerjava75at orgmockitointernalutilmockutilismockitomockmockutiljava74at orgmockitointernalutilmockutilismockmockutiljava66at orgmockitointernalconfigurationinjectionscannermockscannerismockorspymockscannerjava86at orgmockitointernalconfigurationinjectionscannermockscannerpreparedmockmockscannerjava72at orgmockitointernalconfigurationinjectionscannermockscannerscanmockscannerjava61at orgmockitointernalconfigurationinjectionscannermockscanneraddpreparedmocksmockscannerjava47at orgmockitointernalconfigurationinjectingannotationengineinjectmocksinjectingannotationenginejava96at orgmockitointernalconfigurationinjectingannotationengineprocessinjectmocksinjectingannotationenginejava62at orgmockitointernalconfigurationinjectingannotationengineprocessinjectingannotationenginejava56at orgmockitomockitoannotationsinitmocksmockitoannotationsjava108at commyprojectpresentationuserslistpresentertestsetupuserslistpresentertestjava28at androidtestandroidtestrunnerruntestandroidtestrunnerjava191at androidtestandroidtestrunnerruntestandroidtestrunnerjava176at androidtestinstrumentationtestrunneronstartinstrumentationtestrunnerjava5at androidappinstrumentationinstrumentationthreadruninstrumentationjava1853what am i doing wrong,"['java', 'android']" +916653,how to convert an instant to a date format i can convert a javautildate to a javatimeinstant java 8 and later this way calendar cal calendargetinstancecalsetcalendarhour of day 8calsetcalendarminute 30date starttime calgettimeinstant i starttimetoinstantcan anybody let me know about the convert that instant to date with a specific date time format ie 20150602 830i have gone through api but could not find a satisfactory answer,['java'] +916713,how to url encode expressions of template variable with interpolate i have a variable x abbthis variable is then used in a ngsrcxtherefore it is important for me to url encode the variables a and bwhat i do currently isvar func interpolatescopex var url funcscope return scetrustasresourceurlurlmy problem is that when a or b contains spaces they are not url encodedhow can i tell the interpolate function to url encode the variables a and b,['javascript'] +916724,how to increase the execution speed and reduce execution time of a social website like facebook developed in phpfox i have an already developed and running social website like facebook this website has been developed using phpfox v307which is a social networking platform created in phpthe website functions are working well no issues with them the main major and serious issue i am facing with the website is the slow execution speed for any kind of operation it takes too much time and user has to wait for that much time this really irritates the user and is affecting the performance of a websiteso i did research on facebook the worlds largest social networking website developed in php if facebook can execute at rapid speed in spite of heavy user load and continuous operations why cannot my sitefirst thing is the site is developed using a framework called phpfox so the entire database design caching and all other things have been managed by the framework itself i cannot change the frameworks settings but ultimately i want to increase the execution speed of my website so how should i achieve it if you have any best in class solution please provide me the guidance for it any kind of help would be highly appreciatedplease feel free to ask me any of the queries you have regarding the issue i am facingthanks,['php'] +916853,python requests send certificate as string i cant seem to get the handshake working properlycert pathtocert filepemurl requestsgeturl certcert verifytruethis is fine when i use it locally where i have the file physically we host our application on heroku and use environvariablesthe requests module doesnt seem to accept certificates as strings eg export certificatelonglistofcharactersrequestsgeturl certget envcertificate verifytruei have also tried something like thiscert tempfilenamedtemporaryfilecertwritecertificatecertseek0requestsgeturl certcertname verifytruefirst of all it works locally but not on heroku anyways it doesnt feel like a solid solutioni get a ssl handshake errorany suggestions,['python'] +916860,how to get appdelegate with urban airship swift after integrating urban airship when i calet appdelegate uiapplicationsharedapplicationdelegate as appdelegatei always get nil when i tried to get class of uiapplicationsharedapplicationdelegate it tells me that it is uaappdelegateproxy nowbut let appdelegate uiapplicationsharedapplicationdelegate as uaappdelegateproxyalso returns nilhow can i get my appdelegateediti figured up that this happens only when uaconfig parameter automaticsetupenabled is set to true when automaticsetupenabled is false i get appdelegate as usual but i am losing advantages of urban airship automatic configuration,['ios'] +916944,library not found for lpodsafnetworking i am getting the following error when using afnetworkinglibrary not found for lpodsafnetworkinglinker command failed with exit code 1 use v to see invocationi checked for all missing frameworksand they are all present additionally this project works for other peoplewe pulled it from github and i am the only person for whom it does not workits a joint projectwe all use xcode 62 i do not understand what could be wrong or what went missing i tried pulling using the command linesourcetree and even from xcode git source controli also tried different versions of xcode but all the other teamates are using xcode 62 which i am using nowit used to work before it suddenly stopped working any ideas are welcomethank youfollowing is the detailed errorsld warning directory not found for option lusersramapriyasridharandocumentsrama3062015iosmapbox ld warning directory not found for option lusersramapriyasridharandocumentsrama3062015iospodsbuilddebugiphoneos ld library not found for lpodsafnetworking clang error linker command failed with exit code 1 use v to see invocationeditafter opening the workspace file i did not get the mach o linker error any more but i am getting the following errorcommand volumesxcode 1xcodeappcontentsdeveloperplatformsiphonesimulatorplatformdeveloperusrbinmomc failed with exit code 1i asked my team mates who said that it still works fineso it is still a problem only on my computer,['ios'] +916967,zoomable circle packing with automatic text sizing in d3js i am trying to merge two of mikes examples zoomable circle packing automatic text sizingit works when initially thisplayed at the toplevel however if you zoom in to the next level the fonts are not sized correctlyi am not sure if i need to modify the transform or modify the part which calculates the font sizeheres my codepen var circlefill functiond if dcolor return dcolor else return dchildren colorddepth f var calculatetextfontsize functiond return mathmin2 dr 2 dr 8 thisgetcomputedtextlength 11 pxvar margin 20 diameter 960var color d3scalelinear domain1 18 rangehsl00100 hsl2283040 interpolated3interpolatehclvar pack d3layoutpack padding2 sizediameter margin diameter margin valuefunctiond return dsize var svg d3selectbodyappendsvg attrwidth windowinnerwidth attrheight windowinnerheight appendg attrtransform translate diameter 2 diameter 2 var focus root nodes packnodesroot viewvar circle svgselectallcircle datanodes enterappendcircle attrclass functiond return dparent dchildren node node nodeleaf node noderoot stylefill circlefill onclick functiond if focus d zoomd d3eventstoppropagation circleappendsvgtitle textfunctiond return dname var text svgselectalltext datanodes enterappendtext attrclass label stylefillopacity functiond return dparent root 1 0 stylethisplay functiond return dparent root null none textfunctiond return dname stylefontsize calculatetextfontsize attrdy 35emvar node svgselectallcircletextd3selectbody stylebackground color1 onclick function zoomroot zoomtorootx rooty rootr 2 marginfunction zoomd var focus0 focus focus d var transition d3transition durationd3eventaltkey 7500 750 tweenzoom functiond var i d3interpolatezoomview focusx focusy focusr 2 margin return functiont zoomtoit transitionselectalltext filterfunctiond return dparent focus thisstylethisplay inline stylefillopacity functiond return dparent focus 1 0 eachstart functiond if dparent focus thisstylethisplay inline eachend functiond if dparent focus thisstylethisplay none function zoomtov var k diameter v2 view v nodeattrtransform functiond return translate dx v0 k dy v1 k circleattrr functiond return dr k d3selectselfframeelementstyleheight diameter pxclicking the largest subcircle in the vis circle illustrates the problem,['javascript'] +916970,how to generate valid apns certificate p12 for use in gcm for ios i am trying google cloud messaging sample app for ios platform to generate googleservicesinfoplist apns development and production certificates are needed pkcs12 file formati have created p12 file in mac keychain access bundling both apns dev certificate and private key but when uploading the p12 file it says it is not in valid formatthe certificate must be a valid pkcs12 file,['ios'] +916982,error using android design support library attr backgroundtint not found trying to use the new design support library in my project aapt throws the following errordescription error no resource found that matches the given name attr backgroundtintresource designresvaluesstylesxmllocation line 21 this is the affected entry in stylesxmlstyle namewidgetdesignfloatingactionbutton parentandroidwidget item nameandroidbackgrounddrawablefab backgrounditem item namebackgroundtintattrcoloraccentitem item namefabsizenormalitem item nameelevationdimenfab elevationitem item namepressedtranslationzdimenfab translation z presseditem item nameripplecolorattrcolorcontrolhighlightitem item nameborderwidthdimenfab border widthitemstylei am targeting my project to use sdk 21 with min sdk set to 17edit i have all sdk tools up to date,['android'] +917001,polymer 10 multiple calls to send method of ironrequest i have a component that uses an instance of ironajax to retrieve data from the backend and i would like to use ironrequest to send updates such as postdelete requestseverything works perfectly the first time around however if the request is invoked again i get an erroruncaught typeerror cannot read property then of undefinedmy template definition looks like thisironajax idajax auto verbose urlcartapi lastresponseajaxresponse handleasjsonironajaxironrequest idxhrironrequestin my component script i use the send method of ironrequest to send a postvar me thisthisxhrsend url cartapi method post body jsonstringifyentrythenfunction me refresh function consoleerrorpost failedthe error message indicates that send has returned undefined rather than a valid promise objectso my question is this is an ironrequest element actually reusable do i need to do anything to refresh or reinitialize itupdatethanks to zikes i have updated my code as followsironajax idajaxget auto urlcartapi lastresponseajaxresponse handleasjsonironajaxironajax idajaxpost urlcartapi methodpost onresponse refreshironajaxironajax idajaxdelete methoddelete onresponse refreshironajaxinsertentry functionentry thisajaxpostbody jsonstringifyentry thisajaxpostgeneraterequest handleremove functione var entry ecurrenttargetentry thisajaxdeleteurl cartapi entryid thisajaxdeletegeneraterequest refresh function thisajaxgetgeneraterequest,['javascript'] +917009,client ecc ssl certificate contains unknown named curve question precontexti am working in an existing library that uses ssl with the netty framework on a remote server i am running into an ssltls handshake error the error is as follows javaxnetsslsslprotocolexception javaioioexception unknown named curve 1284010045311 at sunsecuritysslhandshakercheckthrownhandshakerjava1345 na170 79 at sunsecuritysslsslengineimplchecktaskthrownsslengineimpljava519 na170 79 at sunsecuritysslsslengineimplreadnetrecordsslengineimpljava799 na170 79 at sunsecuritysslsslengineimplunwrapsslengineimpljava767 na170 79 at javaxnetsslsslengineunwrapsslenginejava624 na170 79 at ionettyhandlersslsslhandlerunwrapsslhandlerjava982 nettyall4023finaljar4023final at ionettyhandlersslsslhandlerunwrapsslhandlerjava908 nettyall4023finaljar4023final at ionettyhandlersslsslhandlerdecodesslhandlerjava854 nettyall4023finaljar4023final at ionettyhandlercodecbytetomessagedecodercalldecodebytetomessagedecoderjava249 nettyall4023finaljar4023final at ionettyhandlercodecbytetomessagedecoderchannelreadbytetomessagedecoderjava149 nettyall4023finaljar4023final at ionettychannelabstractchannelhandlercontextinvokechannelreadabstractchannelhandlercontextjava3 nettyall4023finaljar4023final at ionettychannelabstractchannelhandlercontextfirechannelreadabstractchannelhandlercontextjava319 nettyall4023finaljar4023final at ionettychanneldefaultchannelpipelinefirechannelreaddefaultchannelpipelinejava787 nettyall4023finaljar4023final at ionettychannelnioabstractniobytechannelniobyteunsafereadabstractniobytechanneljava130 nettyall4023finaljar4023final at ionettychannelnionioeventloopproceselectedkeynioeventloopjava511 nettyall4023finaljar4023final at ionettychannelnionioeventloopproceselectedkeysoptimizednioeventloopjava468 nettyall4023finaljar4023final at ionettychannelnionioeventloopproceselectedkeysnioeventloopjava382 nettyall4023finaljar4023final at ionettychannelnionioeventlooprunnioeventloopjava354 nettyall4023finaljar4023final at ionettyutilconcurrentsinglethreadeventexecutor2runsinglethreadeventexecutorjava116 nettyall4023finaljar4023final at ionettyutilconcurrentdefaultthreadfactorydefaultrunnabledecoratorrundefaultthreadfactoryjava137 nettyall4023finaljar4023final at javalangthreadrunthreadjava745 na170 79caused by javaxnetsslsslprotocolexception javaioioexception unknown named curve 1284010045311 at sunsecuritysslhandshakemessagecertificatemsginithandshakemessagejava451 na170 79 at sunsecuritysslserverhandshakerprocessmessageserverhandshakerjava2 na170 79 at sunsecuritysslhandshakerprocessloophandshakerjava901 na170 79 at sunsecuritysslhandshaker1runhandshakerjava841 na170 79 at sunsecuritysslhandshaker1runhandshakerjava839 na170 79 at javasecurityaccesscontrollerdoprivilegednative method na170 79 at sunsecuritysslhandshakerdelegatedtaskrunhandshakerjava1273 na170 79 at ionettyhandlersslsslhandlerrundelegatedtaskslhandlerjava1015 nettyall4023finaljar4023final at ionettyhandlersslsslhandlerunwrapsslhandlerjava927 nettyall4023finaljar4023final 14 common frames omittedcaused by javasecuritycertcertificateparsingexception javaioioexception unknown named curve 1284010045311 at sunsecurityx509x509certinfoinitx509certinfojava171 na170 79 at sunsecurityx509x509certimplparsex509certimpljava1781 na170 79 at sunsecurityx509x509certimplinitx509certimpljava196 na170 79 at sunsecurityproviderx509factoryenginegeneratecertificatex509factoryjava97 na170 79 at javasecuritycertcertificatefactorygeneratecertificatecertificatefactoryjava339 na170 79 at sunsecuritysslhandshakemessagecertificatemsginithandshakemessagejava449 na170 79 22 common frames omittedcaused by javaioioexception unknown named curve 1284010045311 at sunsecurityececparametersdecodeparametersecparametersjava197 na170 79 at sunsecurityececparametersengineinitecparametersjava319 na170 79 at javasecurityalgorithmparametersinitalgorithmparametersjava293 na170 79 at sunsecurityx509algorithmiddecodeparamsalgorithmidjava139 na170 79 at sunsecurityx509algorithmidinitalgorithmidjava114 na170 79 at sunsecurityx509algorithmidparsealgorithmidjava382 na170 79 at sunsecurityx509x509keyparsex509keyjava168 na170 79 at sunsecurityx509certificatex509keyinitcertificatex509keyjava75 na170 79 at sunsecurityx509x509certinfoparsex509certinfojava705 na170 79 at sunsecurityx509x509certinfoinitx509certinfojava169 na170 79 27 common frames omittednow here was my approach to try solving this issue at hand this remote server requires client authentication and that certificate is the one that uses elliptic curves using a client certificate with different public key algorithms and signature algorithms does not cause the error meaning that the client certificate is at fault here i ranopenssl x509 in client cert text nooutthe client certificate is as followscertificate data version 3 0x2 serial number 35850396155650225 0x31c09e8937746e21 signature algorithm ecdsawithsha1 issuer issuer validity not before dec 1 230126 2014 gmt not after nov 26 230126 2034 gmt subject 1361414138718b4304c627b subject public key info public key algorithm idecpublickey publickey 192 bit pub 04dcca0776de2891b8941608120185 24a5a55e4884aa2bf83afa87f13070 f37b01686af62956c7176071feb7c0 d1d51cad asn1 oid prime192v1 nist curve p192 x509v3 extensions x509v3 basic constraints critical cafalse x509v3 key usage critical digital signature key encipherment x509v3 extended key usage critical tls web client authentication tls web server authentication x509v3 subject key identifier subject key identifier x509v3 authority key identifier keyid key id signature algorithm ecdsawithsha1 signature goes herethis leaves me under the impression that the nist p192 curve is not being recognized by jdk ssl library the jdk version i am running is 170 79 i do not know how to proceed fixing this any ideas,['java'] +917016,vertical alignment of a div using semanticui i cannot seem to find it anywhere in the docsis there a way to vertically center a div on the page using semanticui semantics here is what i am trying to dodiv classui centered grid div classeight column wide divi want to be centered vertically on a pagediv divdiv,"['html', 'css']" +917067,jersey rest client treat custom mediatype as mediatypeapplication json i am writing a rest client using jersey with jacksonfeature enabled for a webservice that forces me to specify their customnamed content type even though it is just regular json in other words when i do thisrequest request buildmysamplerequestpojoresponse response requestbuilderpost entityentityrequest mediatypeapplication jsonthe service complains that i am using an invalid content type i can get around this by specifying their customnamed media type in place of the mediatypeapplication json constantresponse response requestbuilderpost entityentityrequest vndstupidnamethatreallyisjustjsonjsonhowever when i do that i getsevere messagebodywriter not found for media typestupidnamethatreallyisjustjsonis there a way i can have jersey treat this customized media type name as if it were regular json without writing a customized messagebodywriter,['java'] +917078,is there xml xslt and xpath support in the new microsoft edge browser does anyone have information about xml xslt or xpath support in the new microsoft edge browserin specific when i use the javascript function transformtodocument it ends with the following error message aerror in transformnode invalid argumentathe same code is working with ie 10 ie 11 chrome safari etc but unfortunately is not working with the new browser,['javascript'] +917185,java 8 extract first key from matching value in a map suppose i have a map of given name surname pairs and i want to find the given name of the first entry in that map that has the surname matching a certain valuehow would we do this in a java 8 fashionin my test case example below i put two ways that would do ithowever the first one looking for the given name of the first person with a surname of donkey will throw javautilnosuchelementexception no value present so it is not safethe second one works but it is not only harder to read but it it is a bit not quite functionaljust wondering if someone here would suggest me an easier clearer way of achieving this using either stream or foreach or bothtestpublic void shouldbeabletoreturnthekeyofthefirstmatchingvalue throws exception mapstring string names new linkedhashmap namesputjohn doe namesputfred flintstone namesputjane doe string keyofthefirst namesentrysetstreamfiltere egetvalueequalsdoefindfirstgetgetkey assertequalsjohn keyofthefirst try namesentrysetstreamfiltere egetvalueequalsdonkeyfindfirstget catch nosuchelementexception e expected optionalmapentrystring string optionalentry namesentrysetstreamfiltere egetvalueequalsdonkeyfindfirst keyofthefirst optionalentryispresent optionalentrygetgetkey null assertnullkeyofthefirstthank you in advance,['java'] +917306,how i can get list from some class properties with java 8 stream good day i have a list of person i need get a list from property of person for example i have a person classclass person private string name private string birthdate public string getname return name public string getbirthdate return birthdate personstring name thisname name listperson personlist new arraylistpersonlistaddnew persondavidpersonlistaddnew personjoepersonlistaddnew personmichelpersonlistaddnew personbaraki want to get list of names with stream api like thisliststring names personliststreamsomecodecollectcollectorstolistnamesstreamforeachsystemoutprintlndavidjoemichelbarakhow can i get lists from property with stream api this code do not workpublic class main public static void mainstring args listperson personlist new arraylist person person new person212 persongetfriendsaddallarraysaslistnn3 1 nn3 2 nn3 3 personlistaddperson person new person 34n persongetfriendsaddallarraysaslistnn3 4 nn3 5 nn3 6 personlistaddperson person new personon1 persongetfriendsaddallarraysaslistnn3 7 nn3 8 nn3 9 personlistaddperson person new person3412nn12n 12 persongetfriendsaddallarraysaslistnn3 10 nn3 11 nn3 12 liststring friens personliststreammapeegetfriendscollectcollectorstolist friendsstreamforeachsystemoutprintln nn3 1 nn3 2 nn3 3 nn3 4 class person string name liststring friends personstring name thisname name public string getname return name public liststring getfriends return friends,['java'] +917316,android nestedscrollview has wrong size after applayout behavior since google has published the design support library for android there are many nice things that can be done without implementing custom code while i have tested the custom views in this lib i have found a worse thing and i did not know if this is a bug or noti have found the cheesesquare project on github in the activity detailxmllayout file there are 3 cardviews inside the nestedscrollview if you delete 2 of them you can see that the nestedscrollview does not have the full size of the parentmatch parent the nestedscrollview is bound to the bottom of the parent view the nestedscrollview gets his full size when i remove the applayout behaviorstringappbar scrolling view behavior but when i remove the layout behavior the toolbar is not collapsingis there any fix for this example layout file can be found here detailxmlyou can build the cheesesquare apk from my github branch stackoverflow,['android'] +917332,how to nil a object in swift how to assign nil to an object in swift i am getting error if assigned directly,['ios'] +917336,left outer join of two collections the question is pretty much in the title i am looking for an algorithm more efficient than full search through the collectionsi have two collectionslistmaptypeid object col1listentity col2where public enum typeid player partner platform amountandpublic class entity private int player id private int platform id private bigdecimal amount get setthe col1 collection which is of the type listmaptypeid object contains only player partner platform typeids i need to write a methodpublic listmaptypeid object mergelistmaptypeid object col1 listentity col2 implwhich is going to produce listmaptypeid object each the entry entry of the map contains additional keyvalue amount amounts value where amounts value is the value of the amount field of the instance e of entity if eplayer id entrygetplayer eplatform id entrygetplatform and null otherwisein fact the operation would be the same ascol1 left outer join col2 on eplayer id entrygetplayer eplatform id entrygetplatformsamplecol1platform 1 partner 1 player 1 platform 1 partner 3 player 1 platform 2 partner 1 player 2 platform 3 partner 4 player 5col2entityplatform id 1 player id 1 amount 100entityplatform id 2 player id 2 amount 200entityplatform id 3 player id 4 amount 300resultplatform 1 partner 1 player 1 amount 100 platform 1 partner 3 player 1 amount 100 platform 2 partner 1 player 2 amount 200 platform 3 partner 4 player 5 amount null,['java'] +917342,can a java method return value depending upon condition i have a icoreclient interface and aclient and bclient classes implements thisicoreclient is exposed for users i need to add a new method in icoreclient interface so it needs to be implemented in both clients i can not make this method generic as it has completely different signature but similar functionalities i have 2 interfaces xx and yyclienta implements xx and clientb implements yyso i decided to add a new testmethod in icoreclient that will provide me the instance of xx or yy depending upon clientsi want to return the instance of these interfaces from a single method depending upon condition in clientapublic xx testmethod return instanceof xxin clientbpublic yy testmethod return instanceof yywhat should i write in icoreclient interfacepublic zz testmethodi tried putting a dummy interface zz acting as a common supertype both xx and yy are implementing this but still not able to expose methods of xx and yy in their respective clients as finally it got typecasted in zzis there any known approach for this kind of scenario edit if i make return type object method of these interfaces are not exposed although object contains the instance of xx or yy user still needs to cast it to xx or yy how will user know for using the methods in the interface i want to expose the methods of the clientx without having to cast to clienta or clientb,['java'] +917415,android recyclerviewadapter oncreateviewholder working i am using recyclerviewadapter but i am little confused regarding working of its method oncreateviewholder overridepublic recyclerviewviewholder oncreateviewholderviewgroup viewgroup int viewtype ifviewtypetype item view mview layoutinflaterfromviewgroupgetcontextinflaterlayoutinflate common item viewgroup false viewholder vh new viewholdermview return vh else view mview layoutinflaterfromviewgroupgetcontextinflaterlayoutinflate uncommon item viewgroup false viewholderfooter vh new viewholderfootermview return vh so incase i have 10 items in my list so for each item this method will be called and every time a new viewholder will be created of course it will one time for each view but now my question is when we were using listview and baseadapter with them we store viewholder in tag and use that we do not create viewholder for each item override public view getviewint position view convertview viewgroup parent myviewholder mviewholder ifconvertview null convertview inflaterinflaterlayoutlayout list item null mviewholder new myviewholder convertviewsettagmviewholder else mviewholder myviewholder convertviewgettag mviewholdertvtitle detailconvertview ridtvtitle mylistgetpositiongettitle mviewholdertvdesc detailconvertview ridtvdesc mylistgetpositiongetdescription mviewholderivicon detailconvertview ridivicon mylistgetpositiongetimgresid return convertview so are we not creating extra viewholders object please help me understand the pros and consthanks,['android'] +917534,angularjs how to clear query text in input of uiselect multiple options i am using uiselectversion 0112 my html code followsuiselect ngmodelstaffselected ngthisabledthisabled resetsearchinputfalse multiple uiselectmatch placeholderstaffitemnameuiselectmatch uiselectchoices repeatstaff in staffs refreshrefreshstaffselectsearch refreshdelay0 div ngbindhtmlname highlight selectsearchdiv uiselectchoicesuiselecthere i am using multiple to select multi options after i searched for query on type it is remains showing how can i should not show thatjs codescoperefreshstaff functionname staffsqueryscopequerycriteriathenfunctionresponse return responsedata,['html'] +917554,why can i use gets in gcc stdc11 the gets function has been removed from the c language no such function exists in the standardyet i compile the following codeinclude stdiohint main void void gets nullusinggcc stdc11 pedanticerrors wall wextraand it compiles without giving any errors or warnings similarlyinclude stdiohint getsint main voidwill not compile error gets redeclared as different kind of symbolin the standard 4 conformance a6 we can reada conforming implementation may have extensions including additional library functions provided they do not alter the behavior of any strictly conforming programgiven the above i do not think gcc is standardcompliant even in pedantic mode is there a reason for this is this intentional or is it a buggcc version 491edit gcc versiongcc x86 64win32sehrev1 built by mingww64 project 491,['c'] +917609,how to ignore the avoid nondefault constructors in fragments error i got this error while trying to generate the signed apk the thing is my app is able to run and debug normally on my device i do not know why when i try to generate apk this error came out how to ignore this error and generate the signed apk i am using android studio 1211 for mac,['android'] +917699,advantage of telling the swift compiler an objects type instead of inferring i have been doing swift programming for a few months now and i have always been curious about thisis there an advantage to telling the swift compiler the type of an object in its declarationielet image uiimage uiimagecompared to not telling the compiler and having it infer the type at runtime ie let image uiimagei would think it would be more efficient to tell the compiler the object type instead of having it infer the type i know this question appeals to objectivec syntax as well so i will add that in the tags,['ios'] +917703,which linq statements force entity framework to return from the db i know of several linq statements that will cause ef to evaluate and return results form the db to memory tolist is one does anyone have a comprehensive list of the statements that do thisnot sure ofsingleordefaultunionedit wish i could accept all these answers great info from everyone,['c#'] +917720,how to create a simple divider in the new navigationview google introduced the navigationview in the design support library version 20 with which you can create a drawer very easily using a menu resourcehow can i create a simple divider line between two items grouping the items did not work creating a sub items section does create a divider line but it requires a title which i do not wantany help would be appreciated,['android'] +917747,shallowclone an es6 map or set how do you shallowclone an es6 map or set objecti want to get a new map or set that has the same keys and values,['javascript'] +917766,server side rendering with react reactrouter and express i am trying to set up serverside rendering for my react app and i am trying to use the great reactrouter module to allow it to handle nonjs situations some crawlers when a user had js turned off for some reason however i am running into trouble i have been using the great response here as a guide of sorts but i am getting strange errors thrown at me i get a persistent syntax error when trying to use reactrendertostring am i setting up the serverside rendering incorrectly missing something obvious or anything elsemy setupreally basic express serverrequirebabelregistervar app express misc express configvar router requirereactrouter routes requirejsxapproutes react requirereactappusefunctionreq res next var router routercreatelocation requrl routes routes routerrunfunctionhandler state consoleloghandler var html reactrendertostringhandler return resrenderreact page html html toplevel react app component shimsrequireintlrequirees5shimvar react requirereactaddons router requirereactrouter nav requirenav injecttapeventplugin requirereacttapeventplugin windowreact react export for intlvar reactintl requirereactintl intlmixin reactintlintlmixinvar route routerroute defaultroute routerdefaultroute notfoundroute routernotfoundroute routehandler routerroutehandlervar app reactcreateclass mixins intlmixin getinitialstate function return connected false loaded false user true render function return div classnamecontainerfluid nav routehandler footer div var routes route namehome path handlerapp defaultroute namewelcome handlerwelcome route namebar pathbar handlerbar route namefoo pathfoo handlerfooroute routerouterrunroutes routerhistorylocation functionhandler reactrenderhandler documentgetelementbyidappmoduleroutes routesoutput flo012 err div classnameprogressbarcontainer flo012 err flo012 err syntaxerror unexpected token flo012 err at exportsruninthiscontext vmjs7316flo012 err at module compile modulejs44325flo012 err at module extensionsjs modulejs47810flo012 err at objectrequireextensionsanonymous function as js usersusercodefoobarappsflonode modulesbabelnode modulesbabelcorelibbabelapiregisternodejs1617flo012 err at moduleload modulejs35532flo012 err at functionmodule load modulejs31012flo012 err at functionanonymous usersusernvmversionsnodev0124libnode modulespm2node modulespmxlibtransactionjs6221flo012 err at functioncls wrapmethod usersusercodefoobarappsbarnode modulesnewreliclibshimmerjs23038flo012 err at functionanonymous usersusercodefoobarappsbarnode modulespmxlibtransactionjs6221flo012 err at modulerequire modulejs36517flo012 err at require modulejs38417,['javascript'] +917797,c openmp reduction scalability i am testing the performance speedup of some algorithms when using openmp and one of then is not scaling am i doing something wrongpc detailsmemory 77 gibprocessor intela corea i74770 cpu 340ghz a 8 os ubuntu 1504 64bitgcc gcc ubuntu 48219ubuntu1 482codeinclude stdiohinclude stdlibhinclude mathhinclude omphint mainint argc char argv int test size i double vector mean stddeviation start time duration if argc 2 printfusage s test sizen argv0 return 1 srandint omp get wtime test size atoiargv1 printftest size dn test size vector double malloctest size sizeofdouble for i 0 i test size i vectori rand start time omp get wtime mean 0 stddeviation 0pragma omp parallel defaultshared privatei pragma omp for reductionmean for i 0 i test size i mean vectori pragma omp single mean test sizepragma omp for reductionstddeviation for i 0 i test size i stddeviation vectori meanvectori mean stddeviation sqrtstddeviation test size duration omp get wtime start time printfstd deviation lfn stddeviation printfduration fmsn duration10 return 0compilation linegcc c o maino mainc fopenmp lm o3gcc o dp maino fopenmp lm o3results omp num threads1 dp 10166224199ms omp num threads2 dp 10157924034ms omp num threads4 dp 10159056189ms,['c'] +917887,correct way to convert method to async in c i am attempting to convert the following method simplified example to be asynchronous as the cachemissresolver call may be expensive in terms of time database lookup network call synchronous versionpublic class thingcache private static readonly object lockobj other stuff public thing getstring key functhing cachemissresolver if cachecontainskey return cachekey thing item lock lockobj if cachecontainskey return cachekey item cachemissresolver cacheaddkey item return item there are plenty of materials online about consuming async methods but the advice i have found on producing them seems less clearcut given that this is intended to be part of a library are either of my attempts below correct asynchronous attemptspublic class thingcache private static readonly semaphoreslim lockobj new semaphoreslim1 other stuff attempt 1 public async taskthing getstring key functhing cachemissresolver if cachecontainskey return await taskfromresultcachekey thing item await lockobjwaitasync try if cachecontainskey return await taskfromresultcachekey item await taskruncachemissresolverconfigureawaitfalse cacheaddkey item finally lockobjrelease return item attempt 2 public async taskthing getstring key functaskthing cachemissresolver if cachecontainskey return await taskfromresultcachekey thing item await lockobjwaitasync try if cachecontainskey return await taskfromresultcachekey item await cachemissresolverconfigureawaitfalse cacheaddkey item finally lockobjrelease return item is using semaphoreslim the correct way to replace a lock statement in an async method i cannot await in the body of a lock statementshould i make the cachemissresolver argument of type functaskthing instead although this puts the burden of making sure the resolver func is async on the caller wrapping in taskrun i know it will be offloaded to a background thread if it takes a long timethanks,['c#'] +917925,2 names for a same attribute i would like to know if there is a way to link two attributes of a class or to give 2 names to a same attribute for example i am actually working on a script which create triangle from data given by users my triangle is abc sides of this triangle are ab bc and ca so the triangle has got these 3 attributes selfab selfbc selfca but ab ba so i would like to allow users to do print myinstanceba instead of print myinstanceab so i thought to create the attribute selfab and the property ba which return selfab that work fine when i try to do print myinstanceba instead of print myinstanceab but i am greedy i also would like to allow users to do myinstanceba 5 instead of myinstanceab 5 and when doing this also edit the attribute abis there is a way to do this,['python'] +917962,how to check if collection is not empty using java stream i am new to java 8 i am not able to understand what is wrong in the following piece of code the idea is to sent collectionuser if its not empty but if the collection is empty than sent httpstatusnot found entity responserequestmappingvalue findpks method requestmethodget produces mediatypeapplication json valuepublic responseentitycollectionuser getusersrequestbody final collectionstring pks return streamsupportstreamuserrepositoryfindallpksspliterator false maplist new responseentitylist httpstatusok orelsenew responseentityhttpstatusnot foundeclipse shows me error in the following point orelsethe method orelsenew responseentityhttpstatusnot found is undefined for the type streamresponseentityusermy base interface method looks like followingiterablet findalliterablepk pks,['java'] +917992,how to test google app invites i am currently implementing googles app invites and i am wondering what the best way to test fresh installs i can broadcast an install referrer event with the appropriate deep link like so adb shell am broadcast a comandroidvendinginstall referrer n yourpackagepathupuntilyourbroadcastreceiver es referrer test referrertestbut this would send a generic broadcast out with referral data is there currently a way to broadcast a install referral which also contains the appropriate appinvitereferral data digging into the source reveals that there is a comgoogleandroidgmsappinvitereferral bundle included as a part of the intent but i am unsure how to construct that as a part of the broadcastediti have created a separate more general question regarding the use of bundle extras when testing broadcasts here,['android'] +918122,why does the jquery selector idid selects all elements with duplicate ids i came across some year old code written by a good developer yes i knew him personally to access all elements having the same idchoicechoiceit returns all elements having the id but if we use the belowchoiceit returns only the first match as expectedafter searching for some time i am unable to figure out any official links pointing to his technique as to how it selected all elements with duplicate idcan anyone please explain how is this working updateplease see the question is not about what alternative to use i am aware of claselectors and attributeselectors and know having duplicate ids is not recommended but sometimes you just have to live with years old code the way it is if you know what i mean,"['javascript', 'jquery', 'html']" +918132,thisable web page navigation on swipeback and forward on a windows phone in ie users can go back and forward by swiping on the screen if the swipe is coming from the edge this os level functionality is hampering my webpages uxis there any js or css which can thisable that some hack would also doa snapshot from windowsphones websitehere is the link to the reference page please note that i still need touchaction enabled for horizontal scrolling,"['javascript', 'css']" +918215,snackbar in support library does not include onthismisslistener i would like to implement the new snackbar included in the latest design support library but the way it is offered seems counterintuitive for my and i assume many others usewhen the user does an important action i want to allow them to undo it via the snackbar but there seems to be no way to detect when it is thismissed to do the action it makes sense to me to do it the following wayuser does actionshow snackbar and update ui as if the action has been completed ie it appears that data is sent to the database but actually is not yetif user pressed undo revert the ui changes if not when the snackbar is thismissed it will then send the databut because i do not see any accessable onthismisslistener i would therefore have touser does actionsend info to database immediately and update uiif user presses undo send another call to the database to remove the justadded data and revert the ui changesi would really like to avoid having to make the two calls to the database and just send one when the app knows that it is safe the user has avoided pressing undo i notice there is some implementation of this in a thirdparty library via an eventlistener but i would really like to stick to the google library,['android'] +918329,shaky scale animation i am doing little mosaic if i can call it like that i am changing scale and opacity based on position mouse and the center of the picturedivi am calculating the thistance via vektors with function calculatethistanceelem mousex mousey return mathfloormathsqrtmathpowmousex elemoffsetleft elemoffsetwidth 2 2 mathpowmousey elemoffsettop elemoffsetheight 2 2 and im looping throught the divspictures and if the thistance is smaller than 100 it calculates its opacityscalebut i came to a problem where animation of changing opacityscale is little bit shakky it seems like its hesitating if it should do somethingdemo is there any way or shortcut how to fix that as i called it shakking or hesitating,"['javascript', 'css']" +918376,to check if ajax call is synchronous or asynchronous in browser dev tools is there a way to confirm whether a particular ajax request in async or sync in browser dev tools like chrome developer tools or firebug for ajax request http request header does not indicate whether its sync or asyncxrequestedwithxmlhttprequest,['javascript'] +918393,account onlogin hook meteor loop i am building an application using meteor i want to create a new cart id to act as a cart where i can store items each time a user logs into my application however every time i open a new page in the application a new cart id is created does this mean that the application logs in every single time i click on a new page in the app heres my code accountsonloginfunctionuser var newcartid uuidnew meteorusersupdate id useruser id set profilecartid newcartid consolelogjust created a new cart id at date,['javascript'] +918430,ionic build android failure execution failed for task processdebugresources i am using mac yosemite getting the following failure on running a build for android platform failure build failed with an exception what went wrongexecution failed for task processdebugresources comandroididecommoninternalloggederrorexception failed to run command userssairamkdevelopmentandroidsdkmacosxbuildtools2201aapt package f nocrunch i userssairamkdevelopmentandroidsdkmacosxplatformsandroid22androidjar m userssairamkprojectsdummy aplatformsandroidbuildintermediatesmanifestsfulldebugandroidmanifestxml s userssairamkprojectsdummy aplatformsandroidbuildintermediatesresdebug a userssairamkprojectsdummy aplatformsandroidbuildintermediatesassetsdebug m j userssairamkprojectsdummy aplatformsandroidbuildgeneratedsourcerdebug f userssairamkprojectsdummy aplatformsandroidbuildintermediatesresresourcesdebugap debugmode custompackage comionicframeworkbcgsandbox553389 0 apk outputtextsymbols userssairamkprojectsdummy aplatformsandroidbuildintermediatessymbolsdebug error code 1 output userssairamkprojectsdummy aplatformsandroidbuildintermediatesresdebugxmlconfigxml59 error error parsing xml unbound prefixthe build runs perfectly fine for ios i have installed android sdk and configured android home and android sdk root system variables also tried removing the platform and adding it again to have a clean platform folder using ionic platform remove androidionic platform add androidbut no goodandroid sdk build tool versions that i have installed 191202112 and 2201androidmanifestxml preference usessdk androidminsdkversion16 androidtargetsdkversion22,['android'] +918620,how to use polymer 10 with rails 4 now that polymer 10 is production ready which is the best way to use it on rails 4 i read a lot and i saw that all the solutions are deprecated for example using gems like likepolymerrails emcee etci am lost trying to create a good structure for the project and the way to include all the polymer components also i do not know if sprocket could help or not,['ruby-on-rails'] +918645,what is authorizedentity cannot find gcm defaultsenderid in own app i am trying to get my app running with google cloud messaging i am following the google cloud messaging quickstart app which can be found here on githubin their quickstart app at some point we ask the google cloud messaging service for a registration token so that this instance of our app can talk to the cloud i find this line of coderegistrationintentservicejavaonhandleintentintent intent instanceid instanceid instanceidgetinstancethisstring gcmregistrationtoken instanceidgettokengetstringrstringgcm defaultsenderid googlecloudmessaginginstance id scope nullthe part that is confusing me is this value rstringgcm defaultsenderid it is defined in their quickstart app but it is automatically generated how am i supposed to get my app to generate that valuei look up the docs for instanceidgettoken which is here gettokenjavalangstring javalangstringinstanceidgetoken returns a token that authorizes an entity example cloud service to perform an action on behalf of the application identified by instance id this is similar to an oauth2 token except it applies to the application instance instead of a userthe function header looks like public string gettoken string authorizedentity string scopei see that the first arg that gettoken wants is string authorizedentityso what is this authorizedentity string supposed to beit clearly identifies the instance of the app making the request but how am i supposed to generate it in the quickstart app i cannot find it defined in resvaluestringsxml i can only find it defined in rjava and appbuildgeneratedresgoogleservicesdebugvaluesvaluesxmlit looks like resourcesstring namegcm defaultsenderid175643285stringresourcesthere is just that one string in that file and that file is buried way deep in the project structure i cannot find anywhere in the code where this gcm defaultsenderid is being generated programmaticallyi am confused because how was i supposed to know that string was there i never defined that string and googling for cannot resolve gcm defaultsenderid gives no results i am trying to implement google cloud messaging in my own app so of course my own app is not going to automatically know to generate that string how am i supposed to make that id number this is why i think it is important that i understand what this authorizedentity string that instanceidgettoken wants so that i can properly generate one to give to gettoken perhaps my idea is completely wrong perhaps i am not supposed to generate gcm defaultsenderid but i know that i am not supposed to alter rjava and the valuesxml file is also under a generated folderhelp please if i find the answer in my searches i will happily post the answer any help much appreciated note my project was exported to gradle from eclipse so it will still have the eclipse projectfolder structure that should not cause any problems but the valuesxml file is in a different place,"['java', 'android']" +918681,how can characters body be continuously rotated when its head is already turned by 60a after some experimenting i parented an empty headcam to the characters neckthis snippet allow rotation of the head synchronously to the cardboardheadcamera void lateupdate neckbonetransformrotation cameratransformrotation quaternioneuler 0090 cameratransformposition headcamtransformpositionthe characters arms should not move when only the head rotates as long in the range 60a to 60a after that i would like to move the whole character with the arms still visible the following method works as long the character is not rotated by more than 180a after that the characters flips by 180a how could i achieve constant rotationvoid lateupdate quaternion camrot cameratransformrotation quaternioneuler 0090 neckbonetransformrotation camrot float yrot camroteuleranglesy float ydelta 0 if yrot 300f yrot 180 ydelta yrot 300f if yrot 60f yrot 180 ydelta yrot 60 playerobjtransformrotation quaternioneuler0 ydelta 0 cameratransformposition headcamtransformpositiona java applet for testing the algorithm standalone,"['java', 'c#']" +918742,adding doubles and complex numbers in c consider this bit of code include iostreaminclude complexint main stdcomplexdouble z1 5 stdcout z1 1 n must change to z1 10 to compile stdcomplexint z2 5 stdcout z2 10 n must change to z2 1 to compilethis produces a compilation error as no operator is found for types in the expressions z1 1 or z2 10 on the other hand changing these expressions so that the base types match works finenaively for z1 1 i would expect the int 1 to be promoted to a double and expected the z2 with base type int in z2 10 to be promoted to a complexdouble whats going on,['c++'] +918752,keyframe animation appears fuzzy when moving frames i use jazzhands to create a key frame based animation in a uiscrollviewhere is an example look at the view at the top when you move from page to page while the animation is running the view at the top is slightly moving from left to right the animation appears a bit fuzzyhere is the code taken from the example here iftframeanimation titleview1frameanimation iftframeanimation new titleview1frameanimationview selftitleview1 selfanimator addanimationtitleview1frameanimation titleview1frameanimation addkeyframeiftanimationkeyframe alloc initwithtimetimeforpage1 andframeselftitleview1frame titleview1frameanimation addkeyframeiftanimationkeyframe alloc initwithtimetimeforpage2 andframecgrectoffsetselftitleview1frame timeforpage2 0 titleview1frameanimation addkeyframeiftanimationkeyframe alloc initwithtimetimeforpage3 andframecgrectoffsetselftitleview1frame timeforpage3 0 titleview1frameanimation addkeyframeiftanimationkeyframe alloc initwithtimetimeforpage4 andframecgrectoffsetselftitleview1frame timeforpage4 0when running the demo take a look at the part marked with red in the following screenshot edit here is the code containing this problem how can i make the animation running smooth and less fuzzy,"['ios', 'objective-c']" +918770,python insert into list faster than on i have a sorted list l and i have a binary search for determining where in the list to insert an element such that the resulting list will still be in order however linsertindexobject needs on time complexityis there another data structure for l that will serve the same purpose but allows for a faster insertion,['python'] +918773,optimization algorithm for calculating multiplier and divisor values i am trying to optimize an algorithm and i cannot think of a better way to do itthere is one input a clock frequency value that will go through a combination of multipliers and divisorsthe goal is to find the set of multiplier and divisor values that will produce the desired output value given the inputoutclk inclk mult1 mult2 mult3 mult4 div1 div2my current naive implementation isdefine pre min 10define pre max 20 available values of the multipliers and divisorsuint8 t mult1 vals 1 2uint8 t mult2 vals 1 2 4 8uint8 t mult3 vals 3 5 7uint8 t div1 vals 1 2 4uint8 t div2 vals 1 2 4 8bool exists mults divsuint32 t in val uint32 t out val uint8 t i m1 i m2 i m3 i d1 i d2 uint32 t calc val for i m1 0 i m1 sizeofmult1 vals i m1 for i m2 0 i m2 sizeofmult2 vals i m2 for i m3 0 i m3 sizeofmult3 vals i m3 for i div1 0 i div1 sizeofdiv1 vals i div1 calc val in val mult1 valsi m1 mult2 valsi m2 mult3 valsi m3 div1 valsi div1 if calc val pre min calc val pre max continue can this be refactored for i div2 0 i div2 sizeofdiv2 vals i div2 calc val div2 valsi div2 if calc val out val return true no multiplierdivisor values found to produce the desired out val return falseis there any way to optimize this or use some algorithmic approachi am using c but any type of pseudo code is ok with meeditsome examples for clarification this will return trueexists mults divs20 70 in20 out70 iterating over the values internally 1 in 1 1 3 1 60 60 is not within pre minmax range of 1020 2 in 1 1 5 1 10 is within range try varying div2 2a div21 10 1 10 70 not desired out 2b div22 10 2 50 70 etc 3 in 1 1 7 1 70 not within range etc 4 in 1 2 7 1 140 is within range try varying div2 4a div21 140 1 70 4b div22 140 2 70 is desired out return result true since a 20 in can generate a 70 out with mult11 mult22 mult37 div11 div22this will return falseexists mults divs20 9because there is no combination of divisor and multiplier with the available values that will result in getting the 9,['c++'] +918919,how does firefox reader view operate ff version 3805 summaryi am looking for the criteria by which i can create a webpage and be fairly sure it will appear in the firefox reader view if user desiredsome sites have this option some do not some with more text do not have this option than others with much less text stack overflow for instance thisplays only the question rather than any answers in reader viewquestioni have had my firefox upgraded from 3801 to 3805 and have found a new feature called readerview which is a sort of overlay which removes page clutter and makes text easier to readreaderview is found in the right hand side of the address bar as a clickable icon on certain pagesthis is fine but from the programming point of view i want to know how reader view works which criteria of which pages it applies to i have done some exploration of the mozilla firefox website with no clear answers sod all programming answers of any sort i found i have of course googled binged this and this only came back with references to firefox addons this is not an addon but a staple part of the new firefox version i made an assumption that readerview used html5 and would extract article contents but this is not the case as it works on wikipedia which does not appear to use article or similar html5 tags instead the readview extracts certain divs and thisplays them alone this feature works on some html5 pages such as wikipedia but then not othersif anyone has any ideas how firefox readerview actually operates and how this operation can be used by website developers can you share or if you can find where this information can be located can you point me in the right direction as i have not been able to find thisany help is much appreciated please note further information in my answer below,['javascript'] +919008,how to resolve assuming assembly reference systemwebmvc with reference to questions26393157windowsupdatecausedmvc3andmvc4stopworking the quickest way to resolve the warning belowassuming assembly reference systemwebmvc version40 cultureneutral publickeytoken31bf3856ad364e35 matches systemwebmvc version4001 cultureneutral publickeytoken31bf3856ad364e35 you may need to supply runtime policy,"['c#', '.net']" +919111,why is my buffer length ignored i am developing a receiver for a small hardware project i am working on a small board that uses uart to transfer datathe receiver code is shown in full below i will explain the problematic bits separately shortlydefine tty devttys002include stdiohinclude stringhinclude unistdh unix standard functionsinclude fcntlh file controlsinclude errnoh error numbersinclude asserthinclude termiosh posix terminalint open portconst char tty int fd fd opentty o rdwr o noctty o ndelay assert failed to open port fd 1 block until read fcntlfd f setfl 0 return fdvoid configure portint fd struct termios options get current options tcgetattrfd options 9600 baud cfsetispeedoptions b9600 cfsetospeedoptions b9600 receive local mode optionsc cflag clocal cread raw output optionsc oflag opost no hardware flow control optionsc cflag crtscts no parity 1 stop bit optionsc cflag parenb optionsc cflag cstopb 8 data bits optionsc cflag csize optionsc cflag cs8 write options back set them immediately tcsetattrfd tcsanow optionsint mainint argc const char argv int fd open porty const size t count 8 char bufcount 1 ssize t n configure portfd while 1 and readfd buf count bufcount 0 if n 0 printfsn buf return 0since i do not have my hardware at hand currently i decided to test my receiver over a regular tty define tty devttys002 to test it i simply compiled and ran the above code and then opened a separate terminal andecho text devttys002all this works fine and well and i get all the data i am echoing into the ttyhowever the problem arises when i input a long message into the ttyecho this is a longer test message devttys002i receive the whole message as a single string in my program output why is this so i would have expected the text to be split up into blocks of 8 chars const size t count 8if it is of importance i am using this guide as my goto for the configurationedit please see the comments for further thiscussion on the issue,['c'] +919123,the standard way to get sizeofpromotedx is there a standard way to get the size of the type a variable would be promoted to when passed as a variadic argumentauto x auto y sizeofpromotedxthe results should bechar sizeofintint sizeofintfloat sizeofdouble,['c++'] +919143,how can i debug my docker container with phpstorm under the following ip my container run successful in my webbrowseri have also create a volume to share files between my container and my filesystemdocker run name lampf d p 3277580 v userssjasiteslamkepf2varwhtml linklampf dbdb codinglimoapache php540 gs imgmck pdflib9now i install also xdebug successful in my container with the following xdebuginizend extensionusrlocallibphpextensionsnodebugnonzts20100525xdebugsoxdebugremote enableonxdebugremote host127001xdebugremote port90xdebugremote handlerdbgpxdebugprofiler enable0xdebugprofiler output dirtempprofiledirphpstorm is also configuredbut my breakpoints in my indexphp are ignoredwhat is my mistakeproblem is solve with help from sergeymy new xdebuginizend extensionusrlocallibphpextensionsnodebugnonzts20100525xdebugsoxdebugremote enableonxdebugremote host127001xdebugremote port90xdebugremote connect backonxdebugremote handlerdbgpxdebugprofiler enable0xdebugprofiler output dirtempprofiledir,['php'] +919286,share same jpa persistencexml accross multiple ejb jars inside ear our project has multiple ejb modules and we want to share a single persistencexml file between themwe put the persistencexml file inside ears metainf directory but the persistence unit is not available at runtime it seems like the file is never read since we forced incorrect classes and jar files but nothing happenswhy is weblogic not reading the persistencexml file inside the earwe get the following error when running the code no pu is found available persistence units caused by javalangillegalargumentexception no persistence unit named em is available in scope ejb1modulejar available persistence units persistencexmlxml version10 encodingutf8persistence version10 xmlns persistenceunit namesystemunit transactiontypejta jtadatasourcesysmtemdsjtadatasource jarfileejb1modulejarjarfile classclass classclass classclass persistenceunitpersistencestructure persistence unit is placed inside the earear metainf persistencexml ejb1modulejar ejb2modulejar ejb3modulejarwe are using weblogic 1036 which uses jpa 10 and toplinkeclipselink that shipts with it,['java'] +919311,find digits in file names and cross reference them with others first i will quickly describe my motivation for this and the actual problemi deal with large batches of files constantly and more specifically i find myself having to rename them according to the following rulethey may all contain words and digits but only one set of digits is incrementing and not constant i need to extract those and only those digits and rename the files accordingly for example foo 1 bar 2015jpgfoo 2 bar 2015jpgfoo 03 bar 2015jpgfoo 4 bar 2015jpgwill be renamed 1jpg2jpg3jpg or 03jpg the leading zero can stay or go4jpgso what we start with is a vector with stdwstring objects for all the filenames in the specified directory i urge you to stop reading for 3 minutes and think about how to approach this before i continue with my attempts and questions i do not want my ideas to nudge you in one direction or another and i have always found fresh ideas are the bestnow here are two ways that i can think of1 old style c string manipulation and comparisonsin my mind this entails parsing each filename and remembering each digit sequence position and length this is easily stored in a vector or whatnot for each file this works well basically uses string searches with increasing offsetswhileoffset filename find first ofl0123456789 offset filenamenpos size filenamefind first not ofl0123456789 offset offset digit locations vecemplace backoffset size offset sizewhat i have after this is a vector of location size pairs for all the digits in the filename constant by using the definition in the motivation or notafter this chaos ensues as you need to cross reference the strings and find out which digits are the ones that need to be extracted this will grow exponentially with the number of files which tends to be huge not to mentioned multiplied by the number of digit sequences in each string also not very readable maintainable or elegant no go2 regular expressionsif there was ever a use for regexs it is this create a regex object out of the first filename and try to match it with what comes next success instant ability to extract the required number failure add the offending filename as a new regex object and try to match against the two existing regexs rinse and repeat the regexs would look something like thisfoo d bar djpgor create a regex for each digit sequence separatelyfoo d bar 2015jpgfoo 1 bar djpgthe rest is cake just keep on matching as you go and in the best case it might require only one pass question iswhat i need to know1 can you think of any other superior way to achieve this i have been banging my head against the wall for days2 although the cost of string manipulation and vector constructingdestructing may be substantial in the first method perhaps it pales in comparison to the cost of regex objects second method worst case as many regex objects as files would this be thisastrous with potentially thousands of files3 the second method can be adjusted for one of two possibilities few stdregex object constructions many regex match calls or the other way around which is more expensive the construction of the regex object or trying to match a string with it,['c++'] +919323,parallelismperformance problems with scrapyd and single spider contexti am running scrapyd 11 scrapy 0246 with a single seleniumscrapy hybrid spider that crawls over many domains according to parameters the development machine that host scrapyds instances is an osx yosemite with 4 cores and this is my current configurationscrapydmax proc per cpu 75debug onoutput when scrapyd starts20150605 1338100500 log opened20150605 1338100500 twistd 1500 libraryframeworkspythonframeworkversions27resourcespythonappcontentsmacospython 279 starting up20150605 1338100500 reactor class twistedinternetselectreactorselectreactor20150605 1338100500 site starting on 680020150605 1338100500 starting factory twistedwebserversite instance at 0x104b91f3820150605 1338100500 launcher scrapyd 101 started max proc300 runnerscrapydrunnereditnumber of corespython c import multiprocessing printmultiprocessingcpu count 4problemi would like a setup to process 300 jobs simultaneously for a single spider but scrapyd is processing 1 to 4 at a time regardless of how many jobs are pendingeditcpu usage is not overwhelming tested on ubuntui have also tested this scenario on a ubuntu 1404 vm results are more or less the same a maximum of 5 jobs running was reached while execution no overwhelming cpu consumption more or less the same time was taken to execute the same amount of tasks,['python'] +919432,ie 11 and ff 38 issue printing from iframe over 1 page in length i have run into an issue where printing a page that contains numerous iframes runs into an issue when the contents of an iframe is longer than the printed pagehere is a super boiled down version of what i am seeing open this link hit print preview you should see 7 pages of lorem ipsum fillnext open this link in ie 10 11 or ff 38 and hit print previewyou can see only the 1st page is printed you can see the iframe run off the bottom of the page but it does not continue on to page 2 or beyondinterestingly chrome has no problems with this and prints perfectly fine unfortunately the organization only supports ie and fire fox anyone ever run into this before or have any ideas with how to resolve it,['html'] +919442,javafx tab order in scenebuilder how can i set tab order focus order for elements for example text field in scenebuilder,['java'] +919481,why use reflection to access class members when methodhandle is faster with the release of java 7 came the methodhandle which allows a user to invoke a method as if using its underlying bytecode in particular the methodhandleslookup class provides factory methods to create method handles to access class membersthe factory methods on a lookup object correspond to all major use cases for methods constructors and fields each method handle created by a factory method is the functional equivalent of a particular bytecode behaviorfunctionally this is more or less equivalent to using reflection to access these same class members yet method handles are faster than reflectionso is there any reason to still use reflection functionalities like fieldgetmethodinvoke or are these methods effectively obsolete with the introduction of the faster method handlesnote that while method handles were introduced in java 7 my question primarily pertains to java 8 in which they were optimized to supposedly reach performance approximately equal to direct fieldmethod calls surpassing reflections ability,['java'] +919525,androidviewinflateexception binary xml file line 33 error inflating class i am using custom adapter class to work with recyclerview here is my codepublic class cardadapter extends recyclerviewadaptercardadapterviewholder listnatureitem mitems public cardadapter super mitems new arraylistnatureitem natureitem nature new natureitem naturesetnamethe great barrier reef naturesetthumbnailrdrawablegreat barrier reef mitemsaddnature nature new natureitem naturesetnamegrand canyon naturesetthumbnailrdrawablegrand canyon mitemsaddnature override public viewholder oncreateviewholderviewgroup viewgroup int i view v layoutinflaterfromviewgroupgetcontext inflaterlayoutrecycler view card item viewgroup false viewholder viewholder new viewholderv return viewholder override public void onbindviewholderviewholder viewholder int i natureitem nature mitemsgeti viewholdertvnaturesettextnaturegetname viewholderimgthumbnailsetimageresourcenaturegetthumbnail override public int getitemcount return mitemssize class viewholder extends recyclerviewviewholder public imageview imgthumbnail public textview tvnature public viewholderview itemview superitemview imgthumbnail imageviewitemviewfindviewbyidridimg thumbnail tvnature textviewitemviewfindviewbyidridtv nature and here is the complete logandroidviewinflateexception binary xml file line 33 error inflating class unknown at androidviewlayoutinflatercreateviewlayoutinflaterjava613 at comandroidinternalpolicyimplphonelayoutinflateroncreateviewphonelayoutinflaterjava56 at androidviewlayoutinflateroncreateviewlayoutinflaterjava660 at androidviewlayoutinflatercreateviewfromtaglayoutinflaterjava685 at androidviewlayoutinflaterrinflatelayoutinflaterjava746 at androidviewlayoutinflaterrinflatelayoutinflaterjava749 at androidviewlayoutinflaterrinflatelayoutinflaterjava749 at androidviewlayoutinflaterinflatelayoutinflaterjava489 at androidviewlayoutinflaterinflatelayoutinflaterjava396 at comgithubflorent37materialviewpagersamplecardadapteroncreateviewholdercardadapterjava53 at comgithubflorent37materialviewpagersamplecardadapteroncreateviewholdercardadapterjava18 at androidsupportv7widgetrecyclerviewadaptercreateviewholderrecyclerviewjava4385 at androidsupportv7widgetrecyclerviewrecyclergetviewforpositionrecyclerviewjava3700 at androidsupportv7widgetrecyclerviewrecyclergetviewforpositionrecyclerviewjava3609 at androidsupportv7widgetlinearlayoutmanagerlayoutstatenextlinearlayoutmanagerjava1859 at androidsupportv7widgetlinearlayoutmanagerlayoutchunklinearlayoutmanagerjava1311 at androidsupportv7widgetlinearlayoutmanagerfilinearlayoutmanagerjava1274 at androidsupportv7widgetlinearlayoutmanageronlayoutchildrenlinearlayoutmanagerjava525 at androidsupportv7widgetrecyclerviewthispatchlayoutrecyclerviewjava2118 at androidsupportv7widgetrecyclerviewonlayoutrecyclerviewjava2415 at androidviewviewlayoutviewjava14063 at androidviewviewgrouplayoutviewgroupjava4607 at androidsupportv4viewviewpageronlayoutviewpagerjava1594 at androidviewviewlayoutviewjava14063 at androidviewviewgrouplayoutviewgroupjava4607 at androidwidgetrelativelayoutonlayoutrelativelayoutjava948 at androidviewviewlayoutviewjava14063 at androidviewviewgrouplayoutviewgroupjava4607 at androidwidgetframelayoutonlayoutframelayoutjava448 at androidviewviewlayoutviewjava14063 at androidviewviewgrouplayoutviewgroupjava4607 at androidsupportv4widgetdrawerlayoutonlayoutdrawerlayoutjava907 at androidviewviewlayoutviewjava14063 at androidviewviewgrouplayoutviewgroupjava4607 at androidwidgetframelayoutonlayoutframelayoutjava448 at androidviewviewlayoutviewjava14063 at androidviewviewgrouplayoutviewgroupjava4607 at androidwidgetlinearlayoutsetchildframelinearlayoutjava1655 at androidwidgetlinearlayoutlayoutverticallinearlayoutjava1513 at androidwidgetlinearlayoutonlayoutlinearlayoutjava1426 at androidviewviewlayoutviewjava14063 at androidviewviewgrouplayoutviewgroupjava4607 at androidwidgetframelayoutonlayoutframelayoutjava448 at androidviewviewlayoutviewjava14063 at androidviewviewgrouplayoutviewgroupjava4607 at androidwidgetlinearlayoutsetchildframelinearlayoutjava1655 at androidwidgetlinearlayoutlayoutverticallinearlayoutjava1513 at androidwidgetlinearlayoutonlayoutlinearlayoutjava1426 at androidviewviewlayoutviewjava14063 at androidviewviewgrouplayoutviewgroupjava4607 at androidwidgetframelayoutonlayoutframelayoutjava448 at androidviewviewlayoutviewjava14063 at androidviewviewgrouplayoutviewgroupjava4607 at androidviewviewrootimplperformlayoutviewrootimpljava1996 at androidviewviewrootimplperformtraversalsviewrootimpljava1817 at androidviewviewrootimpldotraversalviewrootimpljava14 at androidviewviewrootimpltraversalrunnablerunviewrootimpljava4520 at androidviewchoreographercallbackrecordrunchoreographerjava725 at androidviewchoreographerdocallbackschoreograpcartadapter line number 53 view v layoutinflaterfromviewgroupgetcontextcartadapter line number 18 public class cardadapter extends recyclerviewadaptercardadapterviewholder what could be the reason why i am facing this issue is there something else where i have to make change solution provided by abhishek and shvet it resolved the exception but still getting something like this recyclerview over materialviewpager by default which is not okedited againpublic void onviewcreatedview view bundle savedinstancestate superonviewcreatedview savedinstancestate mrecyclerview recyclerview viewfindviewbyidridrecycler view mrecyclerviewsethasfixedsizetrue mlayoutmanager new gridlayoutmanagergetactivity 2 mrecyclerviewsetlayoutmanagermlayoutmanager madapter new cardadapter madapter new recyclerviewmaterialadapternew cardadapter mrecyclerviewsetadaptermadapter materialviewpagerhelperregisterrecyclerviewgetactivity mrecyclerview null mrecyclerviewaddonitemtouchlistener new recycleritemclicklistenergetactivity new recycleritemclicklisteneronitemclicklistener override public void onitemclickview view int position toastmaketextgetactivity stringvalueofposition toastlength longshow,['android'] +919543,swift uibutton with two lines of text i was wondering if it is possible to create a uibutton with two lines of text i need each line to have a different font size the first line will be 17 point and the second will be 11 point i have tried messing with putting two labels inside of a uibutton but i cannot get them to stay inside the bounds of the buttoni am attempting to do all of this in the ui builder and not programmaticallythanks,['ios'] +919578,javafx button border and hover i am using java 8 i have toolbar and buttons on iti want to implement the followingin usual state without mouse hover at toolbar only button label must be seen no background nor borderswhen the user mouse hovers over the button then the usual button must be seenhow to do it via css,"['java', 'css']" +919662,when we typecast the int to double does the actual address where int is stored is get changed i want to know that when we typecast the int to double does the actual result where int is stored is get changed or increased because int is of 4 byteslets assume and when we it get typecast to double which is of 8 bytesassumption then does the size also increased now to store the value of doubleand please go easy on me if it is a stupid question,['c'] +919663,android fused locationsettingsrequest remove never option from startresolutionforresult aaccording to thisyou can check if location requirements are met and show a dialog if not using startresolutionforresultin that dialog you can choose ok not this time or neveris it possible to thisable that never optiongoogle maps official app has that option thisabled,['android'] +919761,running c code from c application android ndk for free i have a c game engine that currently supports windows linux and android ndk it is built on top of sdl and uses opengl for renderingone of the design constraints of this game engine is that the cost of development must be 0 building the engine should come at no cost to me other than man hours i must be allowed to freely rethistribute the engines code and binaries and users should be able to sell games created using the engine with no restrictionsright now i am using a very slow interpreted scripting language for game logic it actually works well for writing glue code and simple responses to ui events but not much elsei would like to replace this system with a c solution have the user compile a c class library dll containing their game logic and have the c side consume this dll and call the appropriate hooksit is been rather difficult to find information on how to achieve this in a crossplatform way each platform has a different way of hosting the needed runtimes also most articles i have found suggest the use of fullfledged frameworks that provide platform abstractions that are already implemented in my engineis there currently a way to run code from a c dll from an android ndkbased c application without using an entirely different sdk and without having to shell out hundreds of dollars for a licensein particular i am eyeing some of microsofts recent open source net initiatives anything there i could useedit to clarify windows and linux have welldocumented ways of running net code for free this question pertains specifically to calling managed code from an android ndk application without paying licensing fees to xamarin or another vendor,"['c#', 'c++', '.net']" +919785,laravel firstornew how to check if it is first or new i am using laravels function firstornew to create a new user or find and update an existing onehow can i know after the object is created if it existed before or if it is a new objectthe idea is something like thisuser appuserfirstornew email userdatagetemail name userdatagetnameif usernew some way to check user was created now else user already existed,['php'] +919846,using xpath to select the href attribute of the followingsibling i am attempting to scrape the following site i am trying to select the href next to the web address text the following xpath selector gets the tag i am afterxthcontainstext web addressfollowingsiblingtdareturns a hrefwcosullivannyusahowever when i specifically try to extract the href using href the return value is an empty arrayxthcontainstext web addressfollowingsiblingtdahrefreturns this is the html of the row i am looking attr valigntop td classprofile view lefttd th alignleft classprofile view centerweb addressth td classprofile view right ahrefwcosullivannyusa td tdtdtr,['html'] +919853,error inflating class android support design what i am trying to do is use the new android support design library mentioned here i have attempted to use the floating action button as follows in my xml layout this is where the below error is coming fromandroidsupportdesignwidgetfloatingactionbutton androidididfab androidlayout widthwrap content androidlayout heightwrap content androidlayout aligntopidadview androidlayout margintop500dp when my app is launched this is the error0606 205643186 64056405comnickapp eandroidruntimei1 fatal exception mainprocess comnickapp pid 6405javalangruntimeexception unable to start activity componentinfocomnickappcomnickappmainactivity androidviewinflateexception binary xml file line 7 error inflating class androidsupportdesignwidgetfloatingactionbutton at androidappactivitythreadperformlaunchactivityactivitythreadjava2306 at androidappactivitythreadhandlelaunchactivityactivitythreadjava2366 at androidappactivitythreadaccess800activitythreadjava149 at androidappactivitythreadhhandlemessageactivitythreadjava1284 at androidoshandlerthispatchmessagehandlerjava102 at androidoslooperlooplooperjava135 at androidappactivitythreadmainactivitythreadjava5290 at javalangreflectmethodinvokenative method at javalangreflectmethodinvokemethodjava372 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava908 at comandroidinternaloszygoteinitmainzygoteinitjava703 caused by androidviewinflateexception binary xml file line 7 error inflating class androidsupportdesignwidgetfloatingactionbutton at androidviewlayoutinflatercreateviewlayoutinflaterjava633 at androidviewlayoutinflatercreateviewfromtaglayoutinflaterjava743 at androidviewlayoutinflaterrinflatelayoutinflaterjava806 at androidviewlayoutinflaterinflatelayoutinflaterjava504 at androidviewlayoutinflaterinflatelayoutinflaterjava414 at androidviewlayoutinflaterinflatelayoutinflaterjava365 at comandroidinternalpolicyimplphonewindowsetcontentviewphonewindowjava401 at androidappactivitysetcontentviewactivityjava2197 at comnickappmainactivityoncreatemainactivityjava94 at androidappactivityperformcreateactivityjava6020 at androidappinstrumentationcallactivityoncreateinstrumentationjava1105 at androidappactivitythreadperformlaunchactivityactivitythreadjava2259a a a a a a a a a a a a at androidappactivitythreadhandlelaunchactivityactivitythreadjava2366a a a a a a a a a a a a at androidappactivitythreadaccess800activitythreadjava149a a a a a a a a a a a a at androidappactivitythreadhhandlemessageactivitythreadjava1284a a a a a a a a a a a a at androidoshandlerthispatchmessagehandlerjava102a a a a a a a a a a a a at androidoslooperlooplooperjava135a a a a a a a a a a a a at androidappactivitythreadmainactivitythreadjava5290a a a a a a a a a a a a at javalangreflectmethodinvokenative methoda a a a a a a a a a a a at javalangreflectmethodinvokemethodjava372a a a a a a a a a a a a at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava908a a a a a a a a a a a a at comandroidinternaloszygoteinitmainzygoteinitjava703in my buildgradle file for the app module i have compile comandroidsupportdesign20 as requiredalso other relevant parts from the buildgradle file compilesdkversion 21buildtoolsversion 21defaultconfig minsdkversion 16 targetsdkversion 21 i should also note that when i go to project structuredependencies and i try to add a library dependency i cannot find comandroidsupportdesign20 when searching i am not sure if this is required in addition to adding the dependency in buildgradle filefinally in my sdk manager i have confirmed android support repository and android support library are up to date at versions 15 and 2 respectivelyare there any suggestions for what else i might tryi have found this answer and tried the solution however it did not solve my issue,['android'] +919859,removing block quote from post text wordpress i have a wordpress site and i want to remove the block quotes from the post and put just the regular text also want to remove any images that are in the text i just want the regular textthis code does the opposite of what i want takes out the block quotes and posts that i want it to post the other text and not the block quotephp get the content block get the content check and retrieve blockquote ifpreg matchblockquotessblockquote block matches output blockquote echo matches1,"['php', 'html']" +919897,why jvm is designed in a way that it does not allow force garbage collection as far as i know we cannot force for garbage collection in java the best we can do is to send a request by calling systemgc or runtimegc doing so will send request of garbage collection to jvm but itas not guaranteed that garbage collection will happen so my question is are there any particular reasons why jvm is designed in a way that it does not support force garbage collection,['java'] +919919,match parent width does not work in recyclerview my recyclerview and item has match parent width but the result is view classandroidsupportv7widgetrecyclerview androidlayout widthmatch parentand itemslinearlayout xmlnsandroidxmlnstoolsxmlnsfabandroidididll itmandroidorientationhorizontalandroidlayout widthmatch parentfullxml version10 encodingutf8linearlayout xmlnsandroidxmlnstoolsxmlnsfabandroidididll itmandroidorientationhorizontalandroidlayout widthmatch parentandroidlayout heightwrap contentandroidweightsum100androidgravityrightbutton androidlayout width0dp androidlayout weight15 androidlayout heightfill parent androidtextuu a androidididbutton linearlayout androidlayout width0dp androidlayout heightfill parent androidlayout weight20 androidgravitycenter linearlayout androidlayout widthwrap content androidlayout heightwrap content androidorientationhorizontal comgetbasefloatingactionbuttonfloatingactionbutton androidlayout widthfill parent androidlayout heightfill parent fabfab plusiconcolorff56ff83 fabfab colornormalcolord red fabfab colorpressedff5c86ff fabfab sizemini fabfab icondrawableic remove white androidididfab rmv esfanduneirelmikarbordiardakanothercustomtxtview androidlayout weight25 androidlayout width0dp androidlayout heightfill parent androidtextappearanceandroidattrtextappearancelarge androidtext0 androidgravityrightcenter vertical androidididtxt takhir itm comgetbasefloatingactionbuttonfloatingactionbutton androidlayout widthfill parent androidlayout heightfill parent fabfab plusiconcolorcolorcolorprimarylight fabfab colornormalcolorcolorprimarydark fabfab colorpressedcolorcolorprimary fabfab sizemini fabfab icondrawableic add white androidididfab add linearlayoutlinearlayout spinner androidlayout width0dp androidlayout heightfill parent androidlayout weight10 androidididsp nomre itm androidentriesarraydegreeslinearlayout androidlayout width0dp androidlayout heightfill parent androidlayout weight10 androidgravitycenter linearlayout baraye ine ke nameshod fab ro weight behosh dad comgetbasefloatingactionbuttonfloatingactionbutton androidlayout widthfill parent androidlayout heightfill parent fabfab plusiconcolorff56ff83 fabfab colornormalcolord green fabfab colorpressedcolord orange fabfab sizenormal fabfab icondrawableic done white androidididfab hazr linearlayoutesfanduneirelmikarbordiardakanothercustomtxtview androidlayout weight5 androidlayout width0dp androidlayout heightfill parent androidtextappearanceandroidattrtextappearancelarge androidtext100 androidgravityrightcenter vertical androidididtxt ghybtnumber itm esfanduneirelmikarbordiardakanothercustomtxtview androidlayout weight30 androidlayout width0dp androidlayout heightfill parent androidtextappearanceandroidattrtextappearancelarge androidtext1 31uu uu3u u androidgravityrightcenter vertical androidididtxt title itm androidlayout marginright10dp view androidlayout width0dp androidlayout heightfill parent androidlayout weight10 classdehdodenhofcircleimageviewcircleimageview androidididview androidsrcdrawablemmrdf linearlayout,['android'] +920035,spurious copies in c03 libstdc vs c11 consider this codeinclude iostreaminclude stringinclude mapusing namespace stdclass foopublic foo x0 cout default endl fooint a xa cout param endl foofoo const foo xfoo x cout copy endl foo operatorfoo const foo cout assignment endl x foo x return this int getvoid return x private int xint mainint argc char argv stdmapint foo foos foo a foo10 foos100 a foo return 0compiled in gcc with stdc11 and you get the outputparamdefaultassignmentremove stdc11 then you getparamdefaultcopycopyassignmentwith c11withoutlibc example producing the superior output in c03 modewhere are the two extra copies coming from they are related to calling the subscript operator not the assignment they remain if you remove the assignment to me they do not seem to be needed even in a prec11 world as the libc example showsthis was originally motivated by looking at this question,['c++'] +920255,converting owinhttprequestcontext to httpcontext ihttphandler and websockets i am trying to implement web sockets in my application that currently implements a restful web api i want certain pieces of information to be able to be exposed by a web socket connection so i am trying to figure out how to upgrade a normal http request to a web socket connectioni am trying to follow this tutorial the problem i am having is my controller that handles the get request inherits from apicontroller and i am trying to do this if httpcontextcurrentiswebsocketrequest httpcontextcurrentacceptwebsocketrequestsomefunction return new httpresponsemessagehttpstatuscodeswitchingprotocolsthe problem is my httpcontextcurrent is always null and i do not know why it seems like there is no such thing as a httpcontext i do see however from the request that comes in that their is a httprequestcontext that comes in with the request are these two objects related at all and is there any way i can get access to the iswebsocketrequest method so i can try and upgrade the request to a web socket connectionmy controller and what i am trying to do httpget public httpresponsemessage getsomething if httpcontextcurrentiswebsocketrequest consolewritelineweb socket request httpcontextcurrent is always null my controller inherits solely from apicontroller,"['c#', '.net']" +920403,how can i fetch the row of next in rank to the rank of last id create tablecreate table goal implement id int percent int insert into goal implement values 110 215 320 440 550 620queryselect id percent find in set percent select group concat percentorder by percent desc from goal implement as rank from goal implement order by id descresultid percent rank6 20 35 50 14 40 23 20 32 15 51 10 6i do not know how to fetch the rowrank that is next on the last id for example last ids rank is 3want resultid percent rank4 40 2,"['php', 'mysql']" +920466,collapsingtoolbarlayout imageview is not scrollable using cheesesquare android support library example is it possible to make the header imageview scrollable androidsupportdesignwidgetappbarlayout androidididappbar androidlayout widthmatch parent androidlayout heightdimendetail backdrop height androidthemestylethemeoverlayappcompatdarkactionbar androidfitssystemwindowstrue androidsupportdesignwidgetcollapsingtoolbarlayout androidididcollapsing toolbar androidlayout widthmatch parent androidlayout heightmatch parent applayout scrollflagsscrollexituntilcollapsed androidfitssystemwindowstrue appcontentscrimattrcolorprimary appexpandedtitlemarginstart48dp appexpandedtitlemarginend64dp imageview androidididbackdrop androidlayout widthmatch parent androidlayout heightmatch parent androidscaletypecentercrop androidfitssystemwindowstrue applayout scrollflagsscroll applayout collapsemodeparallax androidsupportdesignwidgetcollapsingtoolbarlayoutandroidsupportv4widgetnestedscrollview androidlayout widthmatch parent androidlayout heightmatch parent androidfillviewporttrue applayout behaviorstringappbar scrolling view behavior notice that i have added added androidfillviewporttrue to nestedscrollview and also added applayout scrollflagsscroll to the imageview but when trying to scroll from the imageview nothing happens,['android'] +920526,how do hashmapvalues and hashmapkeyset return values and keys the source code of hashmapvalues is shown as followspublic collectionv values collectionv vs values return vs null vs values new valuesas you can see when the values method first called it just returns a values object the values object is a subclass of abstractcollection with no constructor and of course contains no element but when i called the method it returned a collection rapidlycollectionstring values mapvaluessystemoutprintlnvaluesthat is so weird not only values but also keyset and entryset method return such empty objects so here is my question when and how do these methods return objects with elements we need,['java'] +920548,how to open ios app when push notification custom button clicked i added some button into the ios push notification eg i customized the push notification banneralerts with some custom buttons which i would like to open the appcurrently when i click the banneropen button of alert dialog the app runs successfullyi want to add opening app event programmaticallyps it is about the interactive push notification and on my research there is not answer relevant to this question,['ios'] +920670,how to programmatically copy asynchronous dependent content to the clipboard following a click i am trying to programmatically use the execcommand in chrome build 43 to copy the result of an asynchronous jsonp request to the clipboard here is a snippet of the logic loadcontentfunction loadcontentcallback getjsoncallbackmyfuncfunctionresult consolelogresultresulttext out containerhtmlresulttext out if callback callback function copyajax loadcontentcopyfunction copy var copydivtext containertext consolelogcopydivtextcopydivtext executecopycopydivtextdocumentaddeventlistenerdomcontentloaded function documentgetelementbyidcopyonclick copy documentaddeventlistenerdomcontentloaded function documentgetelementbyidcopyajaxonclick copyajax copy text as textfunction executecopytext var input documentcreateelementtextarea documentbodyappendchildinput inputvalue text inputfocus inputselect documentexeccommandcopy inputremovei know that starting build 43 of chrome you code use the execcommand with clipboard the problem however is that you need to do it in within the execution of a user originated event in which the permissions are elevatedthis is a similar restriction that zeroclipboard flash based solution hasexcept from getting an answer that it is not possible which is what i ponder about now these are the other options i thought of doing as last resortwarning they are all hail mary passessince jsonp cannot be synchronous turn it to something that uses regular ajax call and make sure that ajax call is synchronous within the execution context of the user event this goes against my deeply rooted belief we should not do synchronous xhr calls since it degrades user experienceas the user approaches with the mouse to the copy button we preemptively send the server request and hope it is fast enough before the user clicks the button this is an obvious race condition which might not part of the time and will not work for certain when the use wants to do a ctrlcommandc instead of clicking the copy buttonperform a two step process one click to trigger the call when the content is available show a message the content is available and press another click on the msg area to copy to clipboard it does not seem like the best ux interaction ever i have created this example with this alternativetriggering a click programmatically does not constitute a user issues eventthere might be a way to create a simple chrome extension and let the user set the permission for that extension to copy to the clipboard this involves but the end user having to install and extension and change local browser settings not sure that many users will be capablewilling to do so i have already looked into stackoverflow questions such as this but they do not address an asynchronous scenarioplease let me know if you can find any other workable solution or a tweak on the existing one,['javascript'] +920688,c using stdvector across boundaries assuming that exe and dll use the same compiler and stl version if i use a stdvector in my exe and use reserve to reserve memory then i pass it as reference to a dll i do a push back in the dll to add an element to my vector if i do not exceed actual capacity is the memory of the new element allocated in the dll or in the exe,['c++'] +920810,how to combine ckeditor in my app code using requirejs grunt and uglify here is my commonjs filerequirejsconfigpaths domready vendorrequirejsdomreadydomready jquery libjquery datatables vendordatatablesmediajsjquerydatatablesmin tabletools vendordatatablesextensionstabletoolsjsdatatablestabletools fixedheader vendordatatablesextensionsfixedheaderjsdatatablesfixedheadermin datatablesbootstrap vendordatatablesbootstrap3pluginmediajsdatatablesbootstrap3min jeditable vendorjeditablejeditable routing bundlesfosjsroutingjsrouter routes vendorfosjsroutingfos js routes ckeditorcorevendorckeditorckeditor ckeditorjqueryvendorckeditoradaptersjquery selectize vendorselectizethistjsselectizemin sifter vendorsiftersiftermin microplugin vendormicropluginsrcmicroplugin datepicker vendorzebradatepickerpublicjavascriptzebra datepicker bootstrap vendorbootstrapthistjsbootstrapminshim bootstrap deps jquery jeditable deps jquery routing exports routing routes deps routing ckeditorjquery depsjqueryckeditorcore selectize deps jquery sifter microplugin tabletools deps datatables fixedheader deps datatables and here is the relevant part of my gruntfilejsrequirejs main options mainconfigfile appdir jscommonjs appdir appdir baseurl js dir builtdir optimizecss none optimize none modules name common include jquery domready bootstrap ckeditorjquery selectize jeditable datepicker routing routes name appmycode exclude common other appmycode entries that exclue common as above uglify options banner pkgname grunttemplatetodaymmdd n compress drop console true remove consolelog statements build files function var files jsfilepathsforeachfunctionval filespush expand true cwd builtdir src val dest builtdir return files and this is how i instantiate ckeditor in my codeckeditorckeditor customconfig toolbargroups name basicstyles groups basicstyles name links groups links name paragraph groups list blocks name document groups mode name insert groups insert name styles groups styles name about groups about removebuttons underlinestrikesubscriptsuperscriptanchorstylesspecialcharaboutsource removeplugins magicline finally these are the errors i get in firebug when i try to load ckeditor using my uglified code on production it works perfectly before optimising in my dev environment networkerror 404 not found geckocsstf0rfeditor tf0rfnetworkerror 404 not found engbjstf0rftypeerror da is undefined isdetectbavar dthisbfunction dadirdrtlartlltrcadai have tried to set the path inside the ckeditor instantiation code using skins pathtockeditorcssfiles but that does not work either incidentally i have also tried downloading ckeditor from the website and installing it fresh with boswer install ckeditor but cannot get it work once uglified and combined into my code using gruntcan anyone see what i am doing wrong does anyone else have this working i am sure folks out there must have it working and it is just my ignorance holding me back,['javascript'] +920826,the generated class for component of dagger 2 is not found in compiletestjava of gradles java plugin well i am migrating my android project to use the clean architecurethis means that part of my code is within the domain module pure java no dependency with android for this project i am using dagger 2 that generates source using the annotation processor during compile timei have the following gradles configuration for my projectapply plugin javasourcecompatibility 17targetcompatibility 17configurations providedsourcesets main compileclasspath configurationsprovided runtimeclasspath configurationsprovided test compileclasspath configurationsprovided runtimeclasspath configurationsprovided dependencies def domaindependencies rootprojectextdomaindependencies def domaintestdependencies rootprojectextdomaintestdependencies provided domaindependenciesdaggercompiler provided domaindependenciesjavaxannotation compile domaindependenciesdagger compile domaindependenciesrxjava compile domaindependenciesjoda testcompile domaintestdependenciesjunit testcompile domaintestdependenciesassertj testcompile domaintestdependenciesmockito testcompile domaintestdependenciesjmocklegacy testcompile domaintestdependenciescommonscsvin my test source i created the interface testcomponent and the dagger is suposed to generate the daggertestcomponent when i try to build my project either through command line or android studio i receive compilation errors of cannot find symbol and then execution failed for task domaincompiletestjavai tried to change the provided with compile and testcompile it is still not workingwhat is strange is that after the failure of the compiletestjava i can find the generated daggertestcomponentjava in domainbuildclassestest so if it is being generated why am i receiving this compile errorit is important to note that this problem only happens in the test source i have generated source of dagger 2 being used in the main sourceupdatei commented every place that was trying to use the daggertestcomponent and tried to build again in the domainbuildclassestest now i can find not only the daggertestcomponentjava but also the class resulted of the compilation so it is generating the source file and compiling it why is the compilation of files using it not working it seems like some order problem like the generated source is not ready yet at the time of the compile of the other sources,"['java', 'android']" +920835,lombok exclude property from builder i have a class called as xyzclientwrapper which have following structurebuilderxyzclientwrapperstring namestring domainxyzclient clientwhat i want no build function generated for property xyzclient client does lombok supports such use case,['java'] +920853,using ngrepeat and filter how to tell which items are visible i have an array of objects that i am thisplaying in my angular app using ngrepeat i am filtering out items using filter and the value of a search input it works as expected but i have a select all deselect all option and i only want to select the visibile items in the list the ones that meet the current search criteriawithout performing the same logic in my controller ie using indexof the search value on each of my objects how can i tell which items are currently filtered out by ngrepeatfiltermy viewinput typetext ngmodelsearchvalueinput typecheckbox ngmodelcheckall ngchangetogglealltr ngrepeatitem in items filtersearchvalue tditemidtd tditemnametdtra function in my controllerscopetoggleall forvar i in scopeitems how can i tell if this item is filtered out in the view i have significantly simplified my code samples here for simplicity since this question does not need much more detail is there a way to do what i am thinking or do i need to perform the search again,"['javascript', 'html']" +920919,android m requesting permissions with permission groups the android m preview docs shows us how to check and request permissions with the new permissions model in the chart below that it shows us a group of permission groups and their associated permissions when i try to to checkselfpermission with a permission group ie manifestpermission groupcamera on first start predictably i get packagemanagerpermission denied then try to requestpermissions for that same permission group and i do not get any type of dialog to pop up onrequestpermissionsresult returns immediately with 1 when i try the same sequence with manifestpermissioncamera things seem to work as normal but for a simple app that i am making i need to record video with audio and requesting the two separate permissions camera and microphone aka record audio seems like poor designthe question is checkselfpermission and requestpermission supposed to work with manifestpermission and manifestpermission group but there is a bug that i should file since it would not show request or was this intentional designnote i understand that i can create a requestpermissionsstring int string array with multiple permissions in it myself but id still have plenty of if statements to check the combinations of permissions i need and to request them as a group when i should only need to request a permission group,['android'] +920949,are these two python statements the same i have these two statementsreturn selfgetdata if selfgetdata else andreturn selfgetdata or i want to know are they same or there is any difference,['python'] +920994,stream audio from microphone via bluetooth to another iphone i am trying to take incoming microphone audio and stream it to another iphone basically a phone call but via bluetooth i have the audio coming in via avaudiorecorderfunc startrecording audiorecorder nil let audiosessionavaudiosession avaudiosessionsharedinstance audiosessionsetcategoryavaudiosessioncategoryrecord error nil var recordsettingsnsmutabledictionary nsmutabledictionarycapacity 10 recordsettingssetobjectnsnumberintegerliteral kaudioformatlinearpcm forkey avformatidkey recordsettingssetobjectnsnumberfloat 4410 forkey avsampleratekey recordsettingssetobjectnsnumberint 2 forkey avnumberofchannelskey recordsettingssetobjectnsnumberint 16 forkey avlinearpcmbitdepthkey recordsettingssetobjectnsnumberbool false forkey avlinearpcmisbigendiankey recordsettingssetobjectnsnumberbool false forkey avlinearpcmisfloatkey soundpath documentsdirectorystringbyappendingpathcomponentrecordcaf refurl nsurlfileurlwithpath soundpath as string var errornserror audiorecorder avaudiorecorderurl refurl settings recordsettings as nsobject anyobject error error if audiorecorderpreparetorecord true audiorecordermeteringenabled true audiorecorderrecord else printlnerrorlocalizeddescription then i tried using streamreader from here streamreader from martinrusingif let astreamreader streamreaderpath documentsdirectorystringbyappendingpathcomponentrecordcaf while let line astreamreadernextline let dataz linedatausingencodingnsutf8stringencoding println linethen send the data to another device usingselfappdelegatempcdelegatesessionsenddatadata nsdata topeers anyobject withmode mcsessionsenddatamode error nserrorpointer i convert line to nsdata then using a thispatch after 05 seconds running constantly i send it to another device via bluetoothit does not seem to work and i do not think this is a practical way of doing it i have done numerous searches and have not seen much on streaming data via bluetooth the key word streaming understandably sends me to pages about server streamingmy question is how can i take audio from a microphone and send it to another iphone via bluetooth i have the bluetooth part all set up and it works great my question is very similar to this except with iphones and swift i want to have a phone call via bluetooththank you in advance,"['ios', 'iphone']" +921110,php days difference calculation error i have a php code to calculate the number of days between two specific dates the difference should not count sundays and saturdays also i have an array of dates which includes holidays which also need to be skippedi gave the starting date as 01052015 and ending date as 01062015 i gave the entire days in the month of may as array thus the difference should be 1 day but i am getting the output as 7 what is the problem here is the codefunction daterangefirst last dates array current strtotimefirst now current last strtotimelast while current last if datew current 0 dates datedmy current current strtotime1 day current unsetdates0 return datesdatea 01052015date 01062015hdsarray array1052015205201540520155052015705201580520159052015110520151205201514052015150520151605201518052015190520152105201522052015230520152505201526052015280520152905201530052015datesarray daterangedatea dateresult array diffhdsarraydatesarraydate diff sizeofresultecho date diffthanks in advance,['php'] +921115,how to filter keys of an object with lodash i have an object with some keys and i want to only keep some of the keys with their valuei tried with filtervar data a1 abb2 b3var result filterdata functionvalue key return keystartswithaconsolelogresultbut it prints an array1 2which is not what i want how to do it with lodash or something else if lodash is not workinglive demo,['javascript'] +921125,how can i integrate resharpers dotsettings file in sonarqube i have a c project with a resharper dotsettings file i want to configure sonar so that it uses my dotsettings file in my dottsettings file i thisabled many rules how can i integrate this file in sonarqubethis is my sonarprojectproperties file just the reshaper partresharpersonarresharpermodesonarresharperdotsettingspathmyprojectresharper7codingstyledotsettingsi also have the same problem with stylecopthis is my sonarprojectproperties file just the stylecop part stylecop sonarstylecopmodesonarstylecopprojectfilepathmyprojectsettingsstylecopfyi i run the sonarqube analysis with bamboo,['c#'] +921257,css way of looping a background image with cover or contain sizing say you are trying to animate a tilable background like thiscontainer width 160px height 91pxbg width 100 height 100 background url repeatx left center backgroundsize contain webkitanimation thisplace 2s linear infinite animation thisplace 2s linear infinitewebkitkeyframes thisplace from backgroundposition 0 center to backgroundposition 160px center keyframes thisplace from backgroundposition 0 center to backgroundposition 160px center div classcontainer textarea classbgtextareadivas soon as you change the dimensions of the container the looping animation breaksis there any way to make this responsive without js,['css'] +921428,reposition legal label mkattributionlabel i would want to move the legal label to the right side on ios 6 and 7 the below solution was working fine however on ios 83 it seems to not worki get the label then with a timer 01 sec in viewdidlayoutsubviews i call this method voidmovelegallabel uiview legallink self attributionview legallinkframe cgrectmakeselfmapviewframesizewidth legallinkframesizewidth 10 selfmapviewframesizeheight legallinkframesizeheight 10 legallinkframesizewidth legallinkframesizeheight legallinkautoresizingmask uiviewautoresizingflexibleleftmargin uiviewautoresizingflexibletopmarginwhich works nicely for rotation etcbut as soon as i scroll the map the label jumps back to the lefttried to call this method in the regiondidchangeanimated but the label jumps back first to the left then to right it is really annoying how could i force that stupid label to stay on the right side solution as suggested by christian subclass the mkmapviewmove the movelegallabel code therecall it in layoutsubviewsvoidlayoutsubviews super layoutsubviews self movelegallabel,"['ios', 'iphone']" +921603,is it possible to detect links within an nsstring that have spaces in them with nsdatadetector first off i have no control over the text i am getting just wanted to put that out there so you know that i cannot change the linksthe text i am trying to find links in using nsdatadetector contains the followingh1my main itemh1img src first image herejpgh2some extra datah2the detection code i am using is this but it will not find this linknsdatadetector linkdetector nsdatadetector datadetectorwithtypesnstextcheckingtypelink errornilnsarray matches linkdetector matchesinstringmyhtml options0 rangensmakerange0 myhtml lengthfor nstextcheckingresult match in matches if match resulttype nstextcheckingtypelink nsurl url match url does some stuff is this a bug with apples link detection here where it cannot detect links with spaces or am i doing something wrongdoes anyone have a more reliable way to detect links regardless of whether they have spaces or special characters or whatever in them,"['ios', 'objective-c']" +921666,capture keys typed on android virtual keyboard using javascript i have a web page with a textarea and i need to capture the keys typed by the user so that i can substitute different unicode characters for the keys typed my current code is as followsmytextareabindkeypress functionevent var keyinput eventwhich call other functionsthis above code works on pcs and iphonesafari however it fails when using chrome on an android samsung tablet for some reason when i type on the android virtual soft keyboard the keypress event is not triggered the android version is 502if i try using keyup or keydown it always returns 229 for all characters except for return key space backspace etc even though the keycode is always 229 the textarea thisplays the correct characters typed by the user which means the device knows which key was entered but somehow i am unable to get a handle on this event and the key code using javascripthere are the alternatives that i have tried so far and their outcomesmaintextareaonkeydown keyup functionevent eventwhich and eventkeycode both return 229documentonkeypress functionevent function is not triggeredmytextareabindinput keypress functionevent comes inside function but keycode and which are undefinedany help regarding this issue is appreciated,"['javascript', 'android', 'jquery']" +921717,programmatic access to apple watch crown i know it has been available for literally less than 48 hours but i was wondering if anyone has figured out how to programmatically access the digital crown on the apple watch in watchos 2 is there not an objectivec method such as voidcrownmovedwithtimestampfloattimestamp that i can override the implementation of my thinking was that this method could be a method of wkinterfacecontroller and would be called at a set interval like every time the digital crown is spun an angle of 1 degree like what is done to receive touches in an uiview using the methods such as voidtouchesbegannsset touches witheventuievent event any help would be greatly appreciated thanks,['objective-c'] +921723,path reconstruction with hashing i have been trying to figure out how to find a on time complexity algorithm to solve the following in javawe are given an input pair with a start point and end point and we have to construct a path such that the start of one input matches the end of another input in this case alphabeticallyex if i have a list p b b mo pm zwhere pb or bm are pairs p being the start point and b being the endi should create as outputo pp bb mm zand naturally i want to check for cycles in this case i will just report if there is a cyclethe first time i tried to do this i used a swapping algorithm that was on2 by basically swapping two entries if there was a match and moving down the list there is a definitely a faster way to do this and i understand semiintuitively how to do it but i was wondering if someone could clear it up a littlebasically i am assuming you need to make some sort of hashkey type of structure where you can reference the value of the object itself by a keyfor example you would keep two collections one of starts and one of ends you could take each input and create an object that has a start and end field and then add all of the starts and ends to two arrays then you would have to find basically endstart for each start and add its respective object to a list after finding themmy only thing is i cannot figure out exactly how to implement this in java using a hash table or some similar data structure do i have to add the starts and ends to separate hash tables and then use the start points as lookup keyspseudocode from looking at someone who solved it in python on githubfor inputs parse input add parse1 to starts add parse2 to endsfor starts find origin a start not in ends requires hashif no origin cycle existsfor inputs find endsorigin requires hash origin endsorigin so we can find the next onewondering if someone could help me translate this to an algorithm in java other efficient solutions very welcome since i am interested in this type of problem solving or understanding it more generally from a data structures perspective,['java'] +921724,portfolio rebalancing with bandwidth method in python we need to calculate a continuously rebalanced portfolio of 2 stocks lets call them a and b they shall both have an equal part of the portfolio so if i have 100 in my portfolio 50 get invested in a and 50 in b as both stocks perform very differently they will not keep their equal weights after 3 month already a may be worth 70 while b dropped to 45 the problem is that they have to keep their share of the portfolio within a certain bandwidth of tolerance this bandwidth is 5 so i need a function that does if a b105 or a105 b then rebalance this first part serves only to get the fastest way some data to have a common basis of thiscussion and to make results comparable so you can just copy and paste this whole code and it works for youimport pandas as pdfrom datetime import datetimeimport numpy as npdf1 pdiodataget data yahooibm startdatetime1970 1 1 enddatetimetodaydf1renamecolumnsadj close ibm inplacetruedf2 pdiodataget data yahoof startdatetime1970 1 1 enddatetimetodaydf2renamecolumnsadj close ford inplacetruedf df1joindf2ford howinnerdel dfopendel dfhighdel dflowdel dfclosedel dfvolumenowe start to calculate the relative performance of each stock with the formula dfibmdfibm0 the problem is that as soon as we break the first bandwidth we need to reset the 0 in our formula dfibmdfibm0 since we rebalance and need to start calculating from that point on so we use dfd for this placeholder function and set it equal to dft as soon as a bandwidth gets broken dft basically just counts the length of the dataframe and can tell us therefore always awhere we area so here the actual calculation startstol 005 settintg the bandwidth tolerancedfd 0 dft nparangelendftol 03def flex relativex if dfibmdfibmilocdfdvalues dfforddffordilocdfdvalues 1tol return dfilocdfindexget locxname 1d dft elif dfibmdfibmilocdfdvalues dfforddffordilocdfdvalues 1tol return dfilocdfindexget locxname 1d dft else return dfibmdfibmilocdfdvalues dfforddffordilocdfdvaluesdfibm performance dfford performance dfapplyflex relative axis 1the problem is that i am getting this error form the last line of code where i try to apply the function with dfapplyflex relative axis 1valueerror the truth value of a series is ambiguous use aempty abool aitem aany or aall uoccurred at index 19720601 0 the problem is that none of the given options of the error statement solves my problem so i really do not know what to dothe only thing i found so far was the link below but calling a r function would not work for me because i need to apply that to quite big datasets and i may also implement an optimization in this function so it definitely needs to be built in python here is the link anyway finance lib with portfolio optimization method in pythonmanually what is not a good way to handle big data i calculated that the first date for a rebalancing would be 031972 0the output of the dataframe at the first rebalancing should look like this ibm ford d t ibm performance ford performance19721101 0 6505655 0387415 0 107 1021009107 095955241819721102 0 6530709 0398136 0 108 1017092172 093371360519721103 0 6478513 0411718 0 109 10252867 0902911702 this is the day the rebalancing was detected19721106 0 6363683 0416007 109 110 1043787536 0893602752 this is the day the day the rebalancing is implemented therefore dfd gets set dft 10919721108 0 6310883 0413861 109 1 1052520384 089823636419721109 0 6227073 0422439 109 112 10686226 08796875thanks a lot for your supportalexander yes the rebalancing will take place the following daymaxymoo if you implement this code after yours you get the portfolio weights of each stock and they do not rest between 45 and 55 it is rather between 75 and 25 dfford weight dfford propdfforddfford propdfforddfibm propdfibm calculating the actual portfolio weightsdfibm weight dfibm propdfibmdfford propdfforddfibm propdfibmprint dfprint dfibm weightminprint dfibm weightmaxprint dfford weightminprint dfford weightmaxi tried no for an hour or so to fix but did not find itcan i do anything to make this question clearer,['python'] +921805,controlling thistance of shuffling i have tried to ask this question before but have never been able to word it correctly i hope i have it right this timei have a list of unique elements i want to shuffle this list to produce a new list however i would like to constrain the shuffle such that each elements new position is at most d away from its original position in the listso for examplel 1234d 2answer magicfunctionl dnow one possible outcome could be printanswer3124notice that 3 has moved two indices 1 and 2 have moved one index and 4 has not moved at all thus this is a valid shuffle per my previous definition the following snippet of code can be used to validate thisold ei for ie in enumeratelnew ei for ie in enumerateanswervalid allabsinewed for ei in olditemsnow i could easily just generate all possible permutations of l filter for the valid ones and pick one at random but that does not seem very elegant does anyone have any other ideas about how to accomplish this,['python'] +921833,swift get devices ip address i need to get ip address of ios device in swift this is not a duplicate of other questions about this i need to get only wifi ip address if there is no wifi ip address i need to handle it there are a few questions about it on stack overflow but there are only functions that return ip addresses for example from how to get ip address in swiftfunc getifaddresses string var addresses string get list of all interfaces on the local machine var ifaddr unsafemutablepointerifaddrs nil if getifaddrsifaddr 0 for each interface for var ptr ifaddr ptr nil ptr ptrmemoryifa next let flags int32ptrmemoryifa flags var addr ptrmemoryifa addrmemory check for running ipv4 ipv6 interfaces skip the loopback interface if flags iff upiff runningiff loopback iff upiff running if addrsa family uint8af inet addrsa family uint8af inet6 convert interface address to a human readable string var hostname ccharcount intni maxhost repeatedvalue 0 if getnameinfoaddr socklen taddrsa len hostname socklen thostnamecount nil socklen t0 ni numerichost 0 if let address stringfromcstringhostname addressesappendaddress freeifaddrsifaddr return addresseshere i get 2 values address from mobile interneti think and wifi address i need is there any other way to get only wifi ip address,['ios'] +921904,tfs version control does not show conflicts currently i have migrated the tfs from one hardware to another hardware and since then whenever some one check in the code and other gets that version it just replace the code with showing any alert of conflicts it is not merging the code just replacing it with other versioni dont know why it is happening please provide your suggestion,['asp.net'] +921919,google maps 1101 ios with cocoapods giving duplicate symbol error i am trying to integrate the new googlemaps sdk 1101 and i followed the quick start from but i am getting the following error and i got stuck with duplicate symbol error googlemapsresourcecontextoduplicate symbol zn7gmscore8renderer14depthmaskstatec1eb in usersklouddatadocumentssvn rilrtss ios b200podsgooglemapsframeworksgooglemapsframeworkgooglemapsdepthmaskstateoduplicate symbol zn7gmscore8renderer14depthmaskstatec2eb in usersklouddatadocumentssvn rilrtss ios b200podsgooglemapsframeworksgooglemapsframeworkgooglemapsdepthmaskstateoduplicate symbol zn7gmscore8renderer14depthmaskstated0ev in usersklouddatadocumentssvn rilrtss ios b200podsgooglemapsframeworksgooglemapsframeworkgooglemapsdepthmaskstateoduplicate symbol zn7gmscore8renderer14depthmaskstated1ev in usersklouddatadocumentssvn rilrtss ios b200podsgooglemapsframeworksgooglemapsframeworkgooglemapsdepthmaskstateoduplicate symbol zn7gmscore8renderer14depthmaskstated2ev in usersklouddatadocumentssvn rilrtss ios b200podsgooglemapsframeworksgooglemapsframeworkgooglemapsdepthmaskstateoduplicate symbol znk7gmscore8renderer14depthmaskstate11stringvalueev in usersklouddatadocumentssvn rilrtss ios b200podsgooglemapsframeworksgooglemapsframeworkgooglemapsdepthmaskstateoduplicate symbol znk7gmscore8renderer14depthmaskstate7predrawepns0 14entityrenderererkns 4base10reffed ptrins0 11entitystate in usersklouddatadocumentssvn rilrtss ios b200podsgooglemapsframeworksgooglemapsframeworkgooglemapsdepthmaskstateoduplicate symbol znk7gmscore8renderer14depthmaskstate8postdrawepns0 14entityrenderererkns 4base10reffed ptrins0 11entitystate in usersklouddatadocumentssvn rilrtss ios b200podsgooglemapsframeworksgooglemapsframeworkgooglemapsdepthmaskstateoduplicate symbol ztvn7gmscore8renderer14depthmaskstatee in usersklouddatadocumentssvn rilrtss ios b200podsgooglemapsframeworksgooglemapsframeworkgooglemapsdepthmaskstateoduplicate symbol zn7gmscore8renderer15glscopedcontextc1ep15gmsiosglcontext in usersklouddatadocumentssvn rilrtss ios b200podsgooglemapsframeworksgooglemapsframeworkgooglemapsglscopedcontextoduplicate symbol zn7gmscore8renderer15glscopedcontextc2ep15gmsiosglcontext in usersklouddatadocumentssvn rilrtss ios b200podsgooglemapsframeworksgooglemapsframeworkgooglemapsglscopedcontextoduplicate symbol zn7gmscore8renderer15glscopedcontextd1ev in usersklouddatadocumentssvn rilrtss ios b200podsgooglemapsframeworksgooglemapsframeworkgooglemapsglscopedcontextoduplicate symbol zn7gmscore8renderer15glscopedcontextd2ev in usersklouddatadocumentssvn rilrtss ios b200podsgooglemapsframeworksgooglemapsframeworkgooglemapsglscopedcontextold 706 duplicate symbols for architecture i386clang error linker command failed with exit code 1 use v to see invocation,['ios'] +921942,array of random numbers with sum in given range in c how do i get an array of n numbers each 0x0xff in my case of which the sum is within a given range 0kthe almost duplicate c multiple random numbers adding up to equal a certain number targets a specific sum but in my case the sum can be anything between 0k,['c'] +921968,ios workaround for manually focusing on an inputtextarea so i have seen a lot of threads about the ios issue with focusing on an inputtextarea element see here and here it seems that ios will not let you manually focus on one of these elements and requires it to be a genuine tapclick to focus on the elementi have tried simulating a click triggering a click simply doing click straight awayall sorts of thingshere is my current workaround that i am trying to implementscopegotoelement functioneid call anchorscroll scopesmoothscrolltoeidthenfunction clickelementtextarea function clickelemente eontouchstart function evaltouchstart efocus etriggertouchstartyou do not need to worry about the scrolling function i know this works and i have tested that enough the commented out evaltouchstart works with no issues to change the text of the textarea but the focus does not work on ios i have tested this on an android device and it works fine but on ios it just does not bring up the keyboard sometimes it will start to bring up the keyboard for half a second and then thisappear againi have looked at other threads as i mentioned above and i cannot seem to figure out just how to write a workaround for this any ideas,"['javascript', 'jquery', 'ios']" +921986,add two sections in recyclerview android in my application i am using recyclerview to thisplay all contact listi want two section in recyclerviewlike one section is my application contact list and second section is my phone contact listlike thisis there any method to do itdoes anybody know how to do it,['android'] +922028,php split or explode string on tag i would like to split a string on a tag into different parts string text img srchellopng other textthe next function doesnt work yet on the right wayarray preg splitimg i stringthe output should be array 0 text 1 img srchellopng 3 other textwhat kind of pattern should i use to get it doneeditwhat if there are multiple tagsstring text img srchellopng hello img srcbyepng other textarray preg splitimg i string 1 preg split delim captureand the output should bearray 0 text 1 img srchellopng 3 hello 4 img srcbyepng 5 other text,['php'] +922090,mysql udf function to return xml situationi want to create a mysql function named xmlify that takes in a string and an expression that will return a setxmlifystring exprthe function should wrap each returned field of each returned row in the set into its own xml tag the name of the tag should be the field namesmall exampleselect xmlifyfoo select 1 as a 2 as b union select 3 as a 4 as bshould returnfooa1ab2bfoofooa3ab4bfooi want to have this because it will enable me to run a complex query with many joins andor dependant subqueries without having to return redundant data to the clienti already have a workaround without the function i want to build but this involves writing difficult queries that are not easily maintainedsee my examples belowmaking sure the field names are legal xml node name is for a later worry once the function stands i will think of some algorithm that will take the field name and turn it into some legal xml node namealso escaping the xml data is for a later worry this will be done with a different function named cdataify that will simply wrap all data into cdata and and will escape any prior occurance of in the data into cdatai have not been able to accomplish this using stored functions in mysql because these do not take in resultsets also even if you were to pass in sql as a string and then prepare statement and execute it you cannot access the fields if you do not already know the field namesso now i am wondering if the trick can be done with user defined functions udf this is something i have not yet worked with and i would like your advise here before enbarqueingquestionsso my questions now areto recap i would like to have a mysql function that i can pass an expression or result set and where i can also use the field names of the result setam i assuming correct that this will not be possible in stored functionswill udf take in expessions their result set as an argumentwill udf allow me to to access field names of the result set so i can use them as the xml tag nameswill it work on windows as well i read that udf have some limitationsis there a better way i have not thought of yetwill i be able to have a udf dll that i can create on my own development computer and then copy the dll file to my server and use it therehow do i get this show on a roll please be thorough and take into account that i have mysql 55 64bit on a windows computerexampleimagine having the following 3 tablesusers grades toys id name userid grade userid toy 1 bart 1 e 1 slingshot 2 lisa 1 e 1 krusty 2 a 2 malibu stacy 2 b 2 calculator my desired result would be limited to bart and lisausers user idcdata1id namecdatabartname grades gradecdataegrade gradecdataegrade grades toys toycdataslingshottoy toycdatakrustytoy toys user user idcdata1id namecdatalisaname grades gradecdataagrade gradecdatabgrade grades toys toycdatamalibu staceytoy toycdatacalculatortoy toys userusersconsiderationi do not want in php or c to have to first query the user table and then per user run two additional queries for the grades and toys because for 10 users i would be be running 2001 queriesi also do not want to run a query with all joins and go through the result set in php or c because the user name would be sent as many times as the number of grades times the number of toys imagine having a user field containing a huge blobi cannot simply use group concat on joined tables as the gradestoys would still appear doubleand if i would use group concat with thistinct i will lose the grades with are the same such as barts two esso currently i would use the following statement to get this result involving two dependant subqueries this works greatselect concat users ifnull group concat user idcdata replaceuidcdata id namecdata replaceunamecdata name grades select ifnull group concat gradecdata replaceggradecdata grade separator from grades g where guserid uid grades toys select ifnull group concat toyscdata replacettoycdata toys separator from toys t where tuserid uid toys user separator users from users uwhere uname bart or uname lisanow as you might notice it is a rather big and ugly query which hurts the eyes when readingmaintaining such a query is hardif i would have my functions xmlify and cdataify i could simply write this insteadselect xmlifyusers xmlifyuser select cdataifyuid as id cdataifyuname as name xmlifygrade select cdataifyggrade as grade from grades g where guserid uid as grades xmlifytoys select cdataifyttoy as toy from toys t where tuserid uid as grades from users u where uname bart or uname lisa editas mentioned in the comments by nb there is a repository on github possibly holding all i need i have however spent several days now just trying to get this to work on my system without success any answer that holds a stepbystep howto on how to install this on my mysql 55 64bit server running on windows is also acceptableplease take into account that i have no experience with makes makefiles etc so please be thorough in explaining,['mysql'] +922120,why does instagrams pagination return the same page over and over the codei have created a php class to communicate with instagrams api i am using a private function called api request shown below to communicate with instagrams apiprivate function api request request null if is null request request thisrequesthttprequest body wp remote retrieve body wp remote get request array timeout 10 contenttype applicationjson try response json decode body true thisdatapagination responsepaginationnext url thisdataresponse responsedata thissetup data thisdata catch exception ex thisdata null these two lines of codethisdatapagination responsepaginationnext urlthisdataresponse responsedatasets up my data within this arrayprivate data array response null pagination null photos arraythe problemwhenever i request the next page with the following functionpublic function pagination query thisapi request thisdatapagination output json encode thisdataphotos return outputinstagram gives me the first page over and over and over gain any idea what the problem is hereupdate 1i realized that because my setup data function used in api request function pushes my photo objects onto the end of my thisdataphotos arrayprivate function setup data data foreach dataresponse as obj code that parses the api goes here pushes new object onto photo stack array push thisdataphotos new obj it is necessary to create an empty array when requesting a new pagepublic function pagination query thisdataphotos array kicks out old photo objects thisapi request thisdatapagination output json encode thisdataphotos return outputi am able to retrieve the second page but all subsequent pagination query calls only return the second page any ideas what could be wrongupdate 2i thiscovered that using a while statement to make the api request function call itself allows to me retrieve page after page just fineprivate function api request request null if is null request request thisrequesthttprequest body wp remote retrieve body wp remote get request array timeout 18 contenttype applicationjson try response json decode body true thisdataresponse responsedata thisdatanext page responsepaginationnext url thissetup data thisdata while state returns page after page just fine while count thisdataphotos 80 this api request thisdatanext page catch exception ex thisdata null however this does not fix my pagination query function and it appears as if my trycatch block is creating a closure and i am not really sure what to make of this,['php'] +922154,jquery file upload in angularjs i am trying to upload a file with jquery file upload in combination with angularjs i have a multistep form this are 2 steps of my multistep formdiv ngswitchstep div ngswitchwhen1 h1identityh1 form namesteponeform datafileuploadoptions enctypemultipartformdata novalidate autocompleteoff input typesubmit ngclicknextsteponeformvalid valuenext br span classbutton fileinputbutton ngclassthisabled thisabled input typefile idfileupload namefiles multiple span button typebutton classbtn btnprimary start datangclicksubmit spanstart uploadspan button input ngmodelapplicationlastname stringpattern required typetext placeholder last nametranslate nameappname idappname div ngshowsteponeformsubmitted steponeformappnametouched div classerror ngshowsteponeformappnameerrorrequiredlast name is requireddiv div classerror ngshowsteponeformappnameerrorstringpatterndoes not look like a textdiv div input typesubmit ngclicknextsteponeformvalid valuenext form div div ngswitchwhen2 h1studiesh1 form namesteptwoform novalidate autocompleteoff input typesubmit ngclickprevious valueprevious input typesubmit ngclicknextsteptwoformvalid valuenext fieldset classinputgroup legend translatelower secondary studieslegend emlast obtained degrem input ngmodelapplicationlowersecondarystudiesdegreetitle typetext placeholderdegree title namemorelowersecondarystudiesdegreetitle idlwsappdegreetitle input ngmodelapplicationlowersecondarystudieseducationauthority typetext placeholdereducation authority namemorelowersecondarystudieseducationauthority idlwsappeducationauthority input ngmodelapplicationlowersecondarystudiesgraduationyear stylepadding 05278em width 100 typenumber min1960 max2015 value2015 placeholdergraduation year namemorelowersecondarystudiesgraduationyear idlwsappgraduationyear div ngshowsteptwoformsubmitted steptwoformmorelowersecondarystudiesgraduationyeartouched div classerror ngshowsteptwoformmorelowersecondarystudiesgraduationyearerrornumbermust be valid yeardiv div fieldset input typesubmit ngclickprevious valueprevious input typesubmit ngclicknextsteptwoformvalid valuenext form divdivin my custom js file i havejqueryfileuploadfileupload datatype jsonin my controller angularjs i havescopeoptions maxfilesize 50 type post acceptfiletypes gifjpegpngias you can see i call the submit function on start upload but that does not trigger anything i am also not getting any errors in my browser console what am i missing updatei do not have a submission function in my controllerjs i thought this was standard added with jqueryfileuploadangularjs they also did not specify a submit function here in the example jquery fileupload angularjsthe declaration of my module in appjsvar app angularmoduledxsvkgroupapp ngroute gettextconfigfunctionrouteprovider httpprovider locationprovider send all requests payload as query string httpproviderdefaultstransformrequest functiondata if data undefined return data return jqueryparamdata set all post requests content type httpproviderdefaultsheaderspostcontenttype applicationxwformurlencoded charsetutf8 all routes routeprovider wheneditphpsubmissions templateurl viewspathviews submissionshtml controller submissionoverviewcontroller wheneditphpsubmissionshowfid templateurl viewspathviews submissionhtml controller showsubmissioncontroller wheneditphpsubmissiondeletefid templateurl viewspathviews deletesubmissionhtml controller deletesubmissioncontroller whenwpadmin controller routedecidercontroller template div ngincludegettemplateurldiv whenlsubmissionnewjid templateurl viewspathviews newsubmissionhtml controller stepcontroller whenlprojects templateurl viewspathviews projectshtml controller projectsoverviewcontroller otherwise controller routedecidercontroller template div ngincludegettemplateurldiv locationproviderhtml5modetruerunfunction gettextcatalog location var curr path locationpath var result curr pathsplit var language result1 gettextcatalogsetcurrentlanguagelanguage gettextcatalogdebug truein my controllerjs i have amongst other things deals with advancing going back or finishing the multi step form param scope param http param routeparams constructor function stepcontrollerscope http routeparams inits scopeapplication scopeapplicationchildren counters scopechildcounter 0 scopemorelowersecondarystudiescounter 0 scopemorehighersecondarystudiescounter 0 scopemorehighershorttermeducationcounter 0 scopemorehigherlongtermeducationcounter 0 scopemoreadditionalstudiesspecialtycounter 0 scopemoreadditionalstudiesthesiscounter 0 scopelanguagecounter 0 scopeexperiencecounter 0 select options scopelanguageoptions select very good good notions no notion languages todo make the default list dynamic instead of hardcoded problem is the variable expressions wont get accepted in the select attributes scopelanguages dutch french english german scopejob id routeparamsjid scopestep 1 scopenoneselected function type switchtype case appcontact ifscopeapplicationcontact return true else return scopeapplicationcontactrelations scopeapplicationcontactemployees scopeapplicationcontactjobad scopeapplicationcontactwebsite scopeapplicationcontactother break case appworklocation ifscopeapplicationworklocation return true else return scopeapplicationworklocationroeselare scopeapplicationworklocationbrussel scopeapplicationworklocationmerelbeke break scopenext functionvalid ifvalid scopestep scopestep else ifscopestep 2 scopeinputgrouperror false special check for 6 input groups input fields ifcheck scopestep 1 else scopeinputgrouperror true scopestep scopestep else scopestep 1 windowscrollto00 scopeprevious function scopestep 1 windowscrollto00 scopefinish functionvalid ifvalid scopestep scopestep else httppostnewsubmission id scopejob id application scopeapplication successfunctiondata status headers config windowlocationhref dataredirect url function check var check false jqueryeachjqueryfieldsetinputgroup function loops through all fieldsets if check are there no fieldsets with 3 filled input elements then check is false so far check jquerythisfindinputtexttypenumberfilterfunction checks whether inputs are filled return thisvalue length 2 if filled inputs 2 check true return checkangularmoduledxsvkgroupapp controllerstepcontroller stepcontroller,"['javascript', 'jquery']" +922191,order by depending on parameter results in error i have a stored procedure that initiates an order by depending on a parameterdrop procedure dbogetusersbyclusterandusername gocreate procedure dbogetusersbyclusterandusername sortfield nvarchar 256 username sortorder int 0as select from user order by case when sortorder 0 then case when sortfield username then user username when sortfield lastlogindate then user lastlogindate when sortfield creationdate then user creationdate end end asc case when sortorder 1 then case when sortfield username then user username when sortfield lastlogindate then user lastlogindate when sortfield creationdate then user creationdate end end descreturn 0gohowever if i call the procedure like thisexec dbogetusersbyclusterandusername sortorder1 sortfieldusernamei get the following errormsg 241 level 16 state 1 procedure getusersbyclusterandusername line 7conversion failed when converting date andor time from character stringwhy would it try to convert something to datetime can anyone please help,['sql'] +922241,roslyn importadderservice does not visit trivia the microsoftcodeanalysiseditingimportadderserviceaddimportsasync method only visits nontrivia syntax nodes and therefore does not add namespace imports for them this leads to the results that crefs in xml documentation comments cannot be simplified to their short names when using the microsoftcodeanalysissimplificationsimplifierthe biggest problem that i have with this is that the simplification can lead to inconsistent results assume that you have multiple crefs and for one cref you have a namespace import introduced due to another type that is actually used in a nontrivia node then this one crefs gets shortened and the others do notfor clarificationbefore applying importadderservice and simplifiernamespace namespace summary see crefsystemcollectionsienumerable see crefsystemcollectionsgenericienumerablet summary internal class mydeclaration systemcollectionsienumerable field after applying importadderservice and simplifierusing systemcollectionsnamespace namespace summary see crefienumerable see crefsystemcollectionsgenericienumerablet summary internal class mydeclaration ienumerable field questioncan i work around this issue we definitely want to add usings for all types referenced in cref tagsor is this even by designi guess it is indeed a missing feature to tell the importadderservice to visit trivia syntax nodes,['c#'] +922295,search for zero in 2d array and make a corresponding row and col 0 this is my code which works but it is too big i want to refactor itreq row 1req col 1aeach with index do row index roweach with index do col i if col 0 req row index req col i break end endendif req col 1 and req row 1 aeach with index do rowindex roweach with index do col i print req row index or i req col 0 col print end puts r endendinput 2d array1 2 3 4 5 6 7 89 10 0 12 13 14 15 required output 1 2 0 4 5 6 0 80 0 0 012 13 0 15,['ruby'] +922298,laravel5 like equivalent eloquent i am using the below code to pull some results from the database with laravel 5bookingdateswhereemail inputgetemailorwherename like inputgetnamegethowever the orwherelike does not seem to be matching any results what does that code produce in terms of mysql statementsi am trying to achieve something like the followingselect from booking dates where email or name like johnthanks in advance,"['php', 'mysql']" +922474,difference between bower browserify requirejs webpack i am used to simple and small js projects where the js dependencies are concatenated and minified as part of the build process using something like gulp and the script tag in the html contains the hardcoded path to that minified js file it is not elegant and probably has several thisadvantages but conceptually it is a simple approachbut with bigger projects i understand it is good to look at packaging systems like bower browserify requirejs webpack etc whats the benefit to using them as opposed to the way i am used to doing it what are the main ways it helps the development processare these technologies i mentioned competitors to each other or are some of them fulfilling different purposes and can be used together what is the difference between themalso i looked into webpack and it is described in some places as though it is a replacement for gulp i thought gulp is a build system and different from these packaging toolsedit how do these concepts relate to amd or commonjs,['javascript'] +922496,okhttpretrofit default timeout i was wondering how many seconds should i set to my retrofit client how many seconds should i use as default timeoutwhat is the default timeout for okhttpretrofit should we let default values,['android'] +922555,bottom align floating action button i want to align to bottom right my fabi tried with androidgravitybottomrightwhen i try androidlayout alignparentbottomtrue fab thisappearwhen i try androidlayout alignbottomidlista tiendas fab thisappearit does not seems complicated but i just cannot do it any ideaxml version10 encodingutf8relativelayout xmlnsandroidxmlnsappandroidlayout widthmatch parentandroidlayout heightmatch parentlistview androidididlista tiendas androidlayout widthmatch parent androidlayout heightwrap content androidlayout margin5dp androiddividerandroidcolortransparent androiddividerheight40spandroidsupportdesignwidgetfloatingactionbutton androidididfab androidlayout widthwrap content androidlayout heightwrap content androidsrcdrawableic add white 48dp appbackgroundtintcolorspg rosa appborderwidth0dp appelevation8dp appfabsizenormal androidlayout alignparentrighttrue androidlayout alignparentbottomidlista tiendas relativelayout,['android'] +922685,can it is possible to allow user for multiple selection of file in storage access framework after clicking on a button i am getting the content from provider intent i new intentintentaction open document iaddcategoryintentcategory openable isettypeimage startactivityforresulti requestcodenow i want to allow user for multiple selection is it possible,['android'] +922797,java 32bit fp implementation of mathsqrt the standard mathsqrt method seems pretty fast in java already but it has the inherent drawback that it is always going to involve 64bit operations which does nothing but reduce speed when dealing with 32bit float values is it possible to do better with a custom method that uses a float as a parameter performs 32bit operations only and returns a float as a resulti sawfast sqrt in java at the expense of accuracyand it did little more than reinforce the notion that mathsqrt is generally hardtobeat i also sawwhich showed me a bunch of interesting casm hacks that i am simply too ignorant to port directly to java though sqrt14 might be interesting as a part of a jni call i also looked at apache commons fastmath but it looks like that library defaults to the standard mathsqrt so no help there and then there is yepbut i have not bothered with that yet,['java'] +922827,watchify does not always detect changes in javascript files i created a gulp task for bundling modules with browserify and i am using watchify to watch for changes here is my gulp task for watchifygulptaskwatchbrowserify function var opts assign watchifyargs entries jsappjs debug true basedir app paths lib var b watchifybrowserifyopts bonupdate function bundle function bundle gutilloggutilcolorsbluestarting browserify var time datenow return bbundle onerror gutillogbindgutil gutilcolorsredbrowserify error pipesourcebundlejs pipebuffer pipesourcemapsinitloadmaps true pipesourcemapswrite pipegulpdestapp onend function var duration datenow time gutilloggutilcolorsbluefinished browserify dms duration bundleif i edit main js file jsappjs the change is always detected but when i edit some other files that the main file requires the change is detected roughly every other time but not always am i doing something wrong herehere is the full github repo so maybe you get the complete idea how i planned this to work,['javascript'] +922930,apply a list of functions to a java streams map method i map a stream of namevaluepairs with a lookupfunction which returns a function like thislistnamevaluepair parampairs getparampairslistnamevaluepair newparampairs parampairsstream mapnamevaluepair nvp lookupfunctionnvpgetnameapplynvp flatmapcollectionstream collecttolistbut what if lookupfunction returned a collectionfunction instead and i wanted to perform a map with each of the returned functions how would i do that,['java'] +923050,why are two click events registered in this htmlcssjquery i am trying to style a checkbox list i have added my styles and they appear correctly when rendered i want to add a class when the label for the checkbox is clicked this is my markup and here is the same in a jsfiddle you can see from my fiddle that two click events are registered with just one click whyhtmlul li label fortest 0 class input idtest 0 nameoffering cycle typecheckbox value1 fall label li li label fortest 1 class input idtest 1 nameoffering cycle typecheckbox value2 spring label li li label fortest 2 class input idtest 2 nameoffering cycle typecheckbox value3 summer label li li label fortest 3 class input idtest 3 nameoffering cycle typecheckbox value4 other label liulcssul liststyletypenonelabel positionrelative thisplayinlineblock paddingleft27px height25pxlabelbefore thisplayblock positionabsolute top2px marginleft28px width18px height18px backgroundcolorf borderradius5px border1px solid c textalign center colorf fontsize18px contentainput width1px height1px border0 opacity0 floatrightjquerylabelfortest onclickfunction thistoggleclasstesting,"['javascript', 'jquery', 'html', 'css']" +923097,why is not a final variable always a constant expression in the below codefinal int aa2byte ba error possible loss of precisionwhy do i get this error is not a final variable compile time constant expression and hence implicitly narrowed to byte during the assignmentin other words is not the above code equivalent tofinal int a2byte ba,['java'] +923107,collapsingtoolbar not working with notsotall content i am pretty sure this is a bug so i am asking for a workaround my layout is likecoordinatorlayout appbarlayout collapsingtoolbarlayout imageview toolbar collapsingtoolbarlayout appbarlayout androidsupportv4widgetnestedscrollview content here coordinatorlayouti am retrieving content from the web and i do not know how tall it will be might be few lines might be very longhowever i thiscovered that collapsingtoolbar does not work well when content is not big enough to cover the entire screen casescontentheight screenheight works swiping topbottom expands and collapses the toolbar as well as scrolling contentcontentheight screenheight does not that is not good because most of the times contentheight expandedtoolbarheight screenheightin other words when content is not tall enough even if contentexpandedtoolbar is much taller than the whole screen it does not react to scroll gestures and shows some bugs it might take ten gestures to collapse the toolbar a little bit so you can hardly reach the bottom part of the content which is hidden at the bottom because the toolbar is expandedany workaroundif you want to try just take the cheesesquare sample project and delete or reduce the content inside nestedscrollview in activity detailxml api17 here,['android'] +923197,testing postmessage with jasmine async does not work i am trying to use jasmine 20 to write unit tests for some logic in an angularjs app but the logic is inside an event listener from the controller windowaddeventlistenermessage functione if edata sendmessage scopesubmit falseand from the test file describepost message function beforeeachfunctiondone var controller createcontrollercontrollerparams spyonscope submit windowpostmessagesendmessage done itshould submit on a sent message function done expectscopesubmittohavebeencalled done but the test fails the spy never being hit extra info from putting in console debug statementswindowaddeventlistener in the controller is getting calledthe beforeeach and it block are both getting calledthe above message handler in the controller is not getting called during the testthe message sent in this test is eventually being receievd by the message handler several times but not until after the test endswhat is my test missing here,['javascript'] +923238,junit tests pass but pit says the suite is not green while trying to run a pit mutation test i get the following errormutationcoverage failed all tests did not pass without mutation when calculating line coverage mutation testing requires a green suitethe tests run just fine when i do a normal test build but while running the mutation tests phase they supposedly fail but no details are provided as to why i have gone through the reasons listed on the pit testing faq but i still have no clue what could be wrongi triedadding the dthreads1 option to rule of any multi threading issuecould not find any system properties unique the couple tests that are failingthe tests are not ignored under normal runswhat are some other things i should try or other ways to debug what could be going on here,['java'] +923281,how to get dividers in navigationview menu without titles i am using the new navigationview to create my navigation drawer menu from xml i need to place a divider between the section menu items which switch between the sections of my app and the settings and help support links at the bottomin all the examples i have seen i see how this can be done by putting another menu within an item but the item requires to have the androidtitle attribute so the best i can do is make the title blank which leaves an empty space before the settings and help feedbackmenu xmlnsandroid group androidcheckablebehaviorsingle item androidididnav section 1 androidicondrawableic dashboard androidtitlestringsection 1 androidcheckedtrue default selection item androidididnav section 2 androidicondrawableic dashboard androidtitlestringsection 2 item androidididnav section 3 androidicondrawableic dashboard androidtitlestringsection 3 group item androidtitlenull i do not want a title or space here menu item androidididnav settings androidicondrawableic settings androidtitlestringsettings item androidididnav help feedback androidicondrawableic help androidtitlestringhelp feedback menu itemmenui have tried various combinations of menu item and group tags but have not found anything that will work this for example has the issue of using the last item in the previous group as the group titlemenu xmlnsandroid group androidcheckablebehaviorsingle item androidididnav section 1 androidicondrawableic dashboard androidtitlestringsection 1 androidcheckedtrue default selection item androidididnav section 2 androidicondrawableic dashboard androidtitlestringsection 2 item androidididnav section 3 androidicondrawableic dashboard androidtitlestringsection 3 group group this puts stringsection 3 as the group title menu item androidididnav settings androidicondrawableic settings androidtitlestringsettings item androidididnav help feedback androidicondrawableic help androidtitlestringhelp feedback menu itemmenuthere just has to be an easy way to do this using just the menu xml description google has this very behavior in their material design specedityet another close attemptmenu xmlnsandroid item androidtitlenull still a space here though menu group androidcheckablebehaviorsingle and this checkable behavior behaves strangely for some reason item androidididnav section 1 androidicondrawableic dashboard androidtitlestringsection 1 androidcheckedtrue default selection item androidididnav section 2 androidicondrawableic dashboard androidtitlestringsection 2 item androidididnav section 3 androidicondrawableic dashboard androidtitlestringsection 3 group menu item group finally no space or title here item androidididnav settings androidicondrawableic settings androidtitlestringsettings item androidididnav help feedback androidicondrawableic help androidtitlestringhelp feedback itemmenuthis leaves no space between the items above and below the divider but there is still the space at the top now also the androidcheckablebehaviorsingle behaves strangely items are not selected when selected the first time and items are not unselected once others do become selected,['android'] +923348,in xcode i see no paired apple watch even though the watch is paired and the watchs udid is registered my phone is listed as an ineligible target in xcode and out to the side it says no paired apple watch my apple watch is registered under ios devices i can see the udid the watch has watchos 20 installed and my iphone 6 has ios 9 installed the iphone pairs just fine with the watch and i can install apps i have tried rebooting both the watch and the phone i have tried rebooting xcode i tried creating a new scheme in xcode but it still shows no paired apple watch i can choose productdestination and the app will show up on the phone it just would not install the watch appjust sits there saying installing,"['ios', 'iphone']" +923398,system occasionally returns 2 i have coded a function using system library function as belowint executeconst char cmd int ret systemcmd if ret 1 if wifexitedret ret wexitstatusret else ret 1 linfo execute s ret d cmd ret logging return retthen i called it with a shell script as belowbinshpathpathusrlocalsbinusrsbinsbinusrlocalbinusrbinbincd dirname 0agent namegrep agent name etcconfigini awk print 3 pypython26binpythoncheck alive statusps ef grep agent name grep v grep wc l if status ne 0 then process exist echo agent name already exist exit 1 fi check aliveeval py binagentpy dstatusps ef grep agent name grep v grep wc lif status lt 1 then echo run failed exit 1else echo run succ exit 0fibut sometimes there was a odd return code of 2 as belowinfoexecute admintrystartsh ret 1infoexecute admintrystartsh ret 1infoexecute admintrystartsh ret 2infoexecute admintrystartsh ret 2infoexecute admintrystartsh ret 1infoexecute admintrystartsh ret 1infoexecute admintrystartsh ret 1infoexecute admintrystartsh ret 1infoexecute admintrystartsh ret 1infoexecute admintrystartsh ret 2i would like to understand why there was a return code of 2new 20150612 1354i have found that when the system returns 2 there was a error message of bash as belowbash xmalloc localec73 cannot allocate 2 bytes 0 bytes allocated,['c'] +923458,how to integrate apache spark with spring mvc web application for interactive user sessions i am trying to build a movie recommender system using apache spark mllibi have written a code for recommender in java and its working fine when run using sparksubmit commandmy run command looks like thisbinsparksubmit jars optpocspark131binhadoop26mllibsparkmllib 210100jar class comrecommendermovielensalsextended master local4 homesarveshdesktopsparktestrecommenderjar homesarveshdesktopsparktestmllatestsmallratingscsv homesarveshdesktopsparktestmllatestsmallmoviescsvnow i want to use my recommender in real world scenario as a web application in which i can query recommender to give some resulti want to build a spring mvc web application which can interact with apache spark context and give me results when askedmy question is that how i can build an application which interacts with apache spark which is running on a cluster so that when a request comes to controller it should take user query and fetch the same result as the sparksubmit command outputs on consoleas far as i have searched i found that we can use spark sql integrate with jdbc but i did not find any good examplethanks in advance,['java'] +923469,android sdk folder taking a lot of thisk space do we need to keep all of the system images there are a lot of system images piling up on my thisk in the android sdk folder i hardly use the emulator may be once in 6 months most of my development is directly on device what i wanted to check was will removing the system images at least for the old apis ie 22 impact the developmentalso the google apis folder seen below should i keep it for all versions or just the one in the latest suffice,['android'] +923478,tablayout tab selection how to select tab in tablayout programmatically tablayout tablayout tablayout findviewbyidridtabs tablayoutsetupwithviewpagerviewpager,['android'] +923636,how to match a character in middle or at the end of string but only once i am trying to match a string in java with stringmatchesaccepted values are abc321 abc321other8 or abc321 but abc321 or abc321other8 should not match so may be in middle or at the end of the string but not at the beginning and it should appear only oncethis is the closest regexp i have managed to domystringmatchesazaz09azaz09but the problem is that may appear multiple times so how can i improve the regex to allow only once,['java'] +923653,where exactly is net runtime clr jit compiler located this question might look a bit foolish or odd but i have heard a lot of about net clr jit compiler and how it works blah blah blah but now i am wondering where exactly it is located or hosted is it hosted as a part of windows operating system when we actually install net frameworkorit is a part of some exe which we can see in task manageri am looking for the detailed answer on this someone might frame this question as how windows operating system triggersexecutes net executable inside net runtime,"['c#', '.net']" +923670,java generics type erasure of other fields in generic class if i compile the code below with javac testjava xlintunchecked the assignment to the variable c4 produces a warning due to type erasurethe types here are insignificant just exampleswhy does the object reference g3 lose the type information about the member variable comparatorstring strcmp and why does not c1 issue the same warning as the only difference is that the class is not genericimport javautilcomparatorpublic class test normalclass and new normalclass comparatorstring c1 nstrcmp genericclasslong g1 new genericclasslong comparatorstring c2 g1strcmp genericclass g2 new genericclasslong comparatorstring c3 g2strcmp genericclass g3 new genericclasslong comparatorstring c4 g3strcmpclass normalclass public object t public comparatorstring strcmpclass genericclasst public t t public comparatorstring strcmp,['java'] +923681,delayed rendering of react components i have a react component with a number of child components in it i want to render the child components not at once but after some delay uniform or different for each of the childreni was wondering is there a way how to do this,['javascript'] +923688,java how to only create an object with valid attributes i am doing a basic java course and i came to a problem how do i create an object only if i have passed valid parameters to the constructor should i make an alternate class and call the constructor from there after the validation is realized or shouldcould i use a static method in the class for the validation what is the best practice in this case,['java'] +923714,what is stored in this 26kb executable compiling this code with o3include iostreamint mainstdcouthello worldstdendlresults in a file with a length of 25890 bytes compiled with gcc 481cannot the compiler just store two calls to writestdout fileno strlen store writes contents store the string and boom write it to the thisk it should result in a exe with a length under 1024 bytes to my estimatecompiling a hello world program in assembly results in 17 bytes file hello world in less than 20 bytes means actual code is 5bytes long the string is hello world0what that exe stores except the actual main and the functions it callsnote this question applies to msvc tooedita lot of users pointed at iostream as being the culprit so i tested this hypothesis and compiled this program with the same parametersint main and got 23815 bytes the hypothesis has been thisproved,['c++'] +923751,wpf controls should code behind be avoided at all costs i have a wpf project and need to create a control that is specific to the domain but will be reused in multiple views the control must thisplay a decimal value in 3 parts the integral part and the decimal part split into 2 with different font sizes i have a dependency property for the amount and then split the amount in 3 parts in the code behind so i can show them in the specific labels i also use the decimal amount to decide whether the amount is going up or down and subsequently change the background color of the control all of this is done in the code behind i know that some say that code behind is evil and i agree in most cases however how would you implement this otherwise,['c#'] +923787,ios9 hangtracer interval is 0 forcing to 1s while using contact framework i was working with contact framework just adding a contact and it was saved without any problem i double checked in contact list but recently i notice that this message appears on console 20150612 095739723 addingcontacttoaddressbook819291346 hangtracer interval is 0 forcing to 1s 20150612 095739725 addingcontacttoaddressbook819291346 made new hangtracer connection0x332e10i googled it and i only found a mention in twitter about awhat new wizardry is thisaactually i donat know if my code is the cause of this problem voidverifyuserauthorizationinios9andlowercncontactstore contactstore cncontactstore allocinitif cncontactstore authorizationstatusforentitytypecnentitytypecontacts cnauthorizationstatusnotdetermined contactstore requestaccessforentitytypecnentitytypecontacts completionhandlerbool granted nserror nullable error if grantedyes self addcontactinios9andlower if self addcontactinios9andlower nslogerror else nslogerror else nslogerror else if cncontactstore authorizationstatusforentitytypecnentitytypecontacts cnauthorizationstatusauthorized self addcontactinios9andlowerelse nslogerrorbooladdcontactinios9andlowercncontactstore contactstore cncontactstore allocinitcnmutablecontact mutablecontact cnmutablecontact allocinitmutablecontactgivenname namemutablecontactfamilyname lastnamemutablecontactphonenumbers nsarray allocinitwithobjectscnlabeledvalue labeledvaluewithlabelcnlabelphonenumberiphone valuecnphonenumber phonenumberwithstringvaluephone nilcnsaverequest saverequest cnsaverequest allocinitsaverequest addcontactmutablecontact tocontainerwithidentifiernilnserror error nilif contactstore executesaverequestsaverequest errorerror return noelse return yes,['ios'] +923829,android viewpager tinder like ui with 3d card stack appearance i am trying to create a tinderlike ui in android using the viewpageri have looked at this library but i would like to be able to see the previous card once i swipe right hence the preference for a viewpagerthe specific ui detail i am looking for isstacking of images with the outline of the next view underneath the current view i have been able to achieve the stacking of views through the viewpagerpagetransformer interface but i am unable to get the outline of the stack of the subsequent views inside the pager the part that gives it a 3d look like over here card stacked on top of another card here is my pagetransform methodpublic void transformpageview view float position int pagewidth viewgetwidth if position 1 infinity1 this page is way offscreen to the left viewsetalpha0 else if position 0 10 use the default slide transition when moving to the left page viewsetalpha1 viewsettranslationx0 viewsetscalex1 viewsetscaley1 viewsetrotation90position else if position 1 01 fade the page out viewsetalpha1 counteract the default slide transition viewsettranslationxpagewidth position viewsetscalex1 viewsetscaley1 else if position1 viewsetalpha1 viewsetpadding01500 else 1infinity this page is way offscreen to the right viewsetalpha0 is this possible with the viewpager,['android'] +923840,angular uirouter resolve value as string with uirouter i add all resolve logic in state function like this myctrljs var myctrl functionscope customers scopecustomers customers routingjs stateproviderstatecustomersshow url customersid template template controller myctrl resolve i feel this must define as like controller customers functioncustomer stateparams return customergetstateparamsid however imo resolve object must belong to a controller and it is easy to read and maintain if it is defined within a controller file myctrljs var myctrl functionscope customers scopecustomers customers myctrlresolve customers functioncustomer stateparams return customergetstateparamsid routingjs stateproviderstatecustomersshow url customersid template template controller myctrl resolve myctrlresolve error invocables must be an object however when i define it as myctrlresolve because of iife i get the following errorfailed to instantiate module due to referenceerror myctrl is not definedwhen i define that one as string myctrlresolve i get thiserror invocables must be an objecti see that controller is defined as string so i think it is also possible to provide the value as string by using a decorator or somethinghas anyone done this approach so that i can keep my routingsjs clean and putting relevant info in a relevant file,['javascript'] +923851,toolbar search suggestions theming iam trying to change search suggestions to alight themeaiam using appcompatv720 library and read about new feature for customizing search view widget androidsupportv7widgetsearchviewfirst try sectiontoolbarandroidsupportv7widgettoolbar xmlnsandroid xmlnsapp androidlayout widthmatch parent androidlayout heightwrap content androidbackgroundattrcolorprimary androidminheightattractionbarsize apopupthemestylethemeoverlayappcompatlight appthemestylethemeoverlayappcompatdarkactionbar main themestyle namemaintheme parentthemeappcompatlightnoactionbar item namecolorprimarycolorreditem item namecolorprimarydarkcolorred darkitem item namesearchviewstylestylemainthemesearchviewitemstylesearchview themestyle namemainthemesearchview parentwidgetappcompatlightsearchview item namevoiceiconmipmaptest iconitemstylethis way i am not able to affect the search view to test it i am changing the voice icon in the search view and it does not change from defaultsecond try sectionthe second try was to override the overlay theme in toolbaroverlay themestyle namemainthemeoverlay parentthemeoverlayappcompatdarkactionbar item namesearchviewstylestylemainthemesearchviewitemstylethis way i have some feedback but i lose material design in particular i have the old hint icon and it is underlinedmy final aim is to change the search suggestion row backgroundsuggestion row layoutitem namesuggestionrowlayoutlayoutmy custom layoutitemi think that i am far away to accomplish thiscan you help me,['android'] +923866,how to select columns from dataframe by regex i have a dataframe in python pandas the structure of the dataframe is as the following a b c d1 d2 d3 10 14 12 44 45 78i would like to select the columns which begin with d is there a simple way to achieve this in python,['python'] +923889,accessing scala nested classes from java let us say we have the following class structure in scalaobject foo class barwe can easily construct bar in java with new foobar but everything changes when we add an extra level of nested classesobject foo object bar class baz somehow it is no longer possible to construct the most inner class baz in java looking at the javap output i cannot see any significant difference between first 2 levels and second cases 3 levels generated code looks pretty reasonable to me2 levelspublic class foobar 3 levelspublic class foobarbaz with that said whats the difference between 2level vs 3level nested scala classes when they accessed from java,['java'] +923891,how to handle a huge stream of json dictionaries i have a file that contains a stream of json dictionaries like thismenu ac d 3 2e it also includes nested dictionaries and it looks like i cannot rely on a newline being a separator i need a parser that could be used like thisfor d in getobjectsf handle dictdthe point is that it would be perfect if the iteration only happened at the root level is there a python parser that would handle all jsons quirks i am interested in a solution that would work on files that wouldnt fit into ram,['python'] +923975,python testing ncurses i am developing terminal app and i am wondering how can onetest the terminal user interface made with ncurses does any one have some experience with this kind of testingso far my best shot will be to test app with capturing stdout and compare it with what it should be but i am concerned that i could never create the comparable case for every terminal size text colors codes for 256bit24bit etcone way to test would be to simulate the keyboard but how could i test the visual behaivouri am clueless obout this problem,['python'] +924003,ant jar error execute failed javaioioexception cannot run programaapt error2 no such file or directory i am trying to compile a simple java library for unity and after running ant jar i get the following messageapplicationsadtbundlemacx86 6420140702sdktoolsantbuildxml649 the following error occurred while executing this lineapplicationsadtbundlemacx86 6420140702sdktoolsantbuildxml694 execute failed javaioioexception cannot run program usersunityprojectsjavatestpluginaapt error2 no such file or directorythis is strange because i have compiled this class before successfully and i have everything i would think i need namely android studio and related packages tools android 45 etc i noticed that aapt is not located in my adtbundlesdkplatformtools directory but it is in one of the buildtools directories even including the latter in my path did not helpanyway i am running mac os 10103 with the most uptodate version of android studio this class compiled before upgrading to yosemite i have seen suggestions on how to fix this issue but all of those suggestions apply to linux as opposed to mac os,"['java', 'android']" +924153,php ratchet class memcache not found i am following ratchets tutorials for sessionprovider page the code is like thisphp your shell scriptuse ratchetsessionsessionprovideruse symfonycomponenthttpfoundationsessionstoragehandleruse ratchetappmemcache new memcache class not found on line 7memcacheconnectlocalhost 11211session new sessionprovider new myapp new handlermemcachesessionhandlermemcacheserver new applocalhostserverroutesessdemo sessionserverrunphp throws a fatal error when i run the script in the commandlineclass memcache not found in on line 7this code is placed in binchatserverphpwierd stuffthe class is not available only for chatserverphp script,['php'] +924249,intermittent failure to load images err content length mismatch the problemmy website fails to load random images at random times intermittent failure to load image with the following error in consoleget examplecomimagejpg neterr content length mismatchimage either does not load at all and gives the broken image icon with alt tag or it loads halfway and the rest is corrupted eg colors all screwed up or half the image will be greyed out setuplitespeed server phpmysql website with html css javascript and jquery important notes problem occurs on all major web browsers intermittently and with various imagesi am forcing utf8 encoding and https on all pages via htaccesshosting provider states that all permissions are set correctly in my access log when an image fails to load it gives a 200 ok response for the image and lists the bytes transferred as 0 zero it is almost always images that fail to load but maybe 5 of the time it will be a css file or javascript file problem occurred immediately after moving servers from apache to litespeed and has been persistent over several weeks gzip and caching enabled,"['javascript', 'php', 'html']" +924269,android overflow menu and back button not showing in collapsing toolbar i am trying to implement features from the new design support library to create a parallax scrolling toolbar which looks similar to the new material design whatsapp profile pages however i cannot get the overflow menu and back button to show in the top cornersi have tried using the following methods to thisplay the back button but none of them works getsupportactionbarsetthisplayhomeasupenabledtrue getsupportactionbarsethomebuttonenabledtrue getsupportactionbarsetthisplayshowhomeenabledtrueand overwriting the oncreateoptionsmenu method for the overflow menu also did not workdoes anyone know how to add these toolbar icons to a collapsingtoolbar from the design support library below is my layout xml for the activity thanks androidsupportdesignwidgetcoordinatorlayoutxmlnsandroidxmlnsappandroidididmain contentandroidlayout widthmatch parentandroidlayout heightmatch parentandroidfitssystemwindowstrueandroidsupportdesignwidgetappbarlayout androidididappbar androidlayout widthmatch parent androidlayout height256dp androidthemestylethemeoverlayappcompatdarkactionbar androidfitssystemwindowstrue androidsupportdesignwidgetcollapsingtoolbarlayout androidididcollapsing toolbar androidlayout widthmatch parent androidlayout heightmatch parent applayout scrollflagsscrollexituntilcollapsed androidfitssystemwindowstrue appcontentscrimcolorprimary appexpandedtitlemarginstart48dp appexpandedtitlemarginend64dp imageview androidididbackdrop androidlayout widthmatch parent androidlayout heightmatch parent androidsrcdrawableheaderbg androidscaletypecentercrop androidfitssystemwindowstrue applayout collapsemodeparallax androidsupportv7widgettoolbar androidididtoolbar androidlayout widthmatch parent androidlayout heightattractionbarsize apopupthemestylethemeappcompatlightdarkactionbar applayout collapsemodepin androidsupportdesignwidgetcollapsingtoolbarlayoutandroidsupportdesignwidgetappbarlayoutandroidsupportv4widgetnestedscrollview androidlayout widthmatch parent androidlayout heightmatch parent androidlayout gravityfill vertical androidlayout marginbottomattractionbarsize applayout behaviorstringappbar scrolling view behaviorandroidsupportv4widgetnestedscrollview,['android'] +924362,java infinite loop performance i have a thread that only has to work when a certain circumstance comes in otherwise it just iterates over an empty infinite looppublic void run whiletrue ifball null do some calculations does it affect the performance when the loop actually does nothing but it has to check if it has to do the calculation every iterationonly creating a this thread when needed is not an option for me because my class which implements runnable is a visual object which has be shown all the timeedit so is the following a good solution or is it better to use a different method concerning performanceprivate final object standby new objectpublic void run whiletrue synchronized standby whileball null should i use while or if here try standbywait catch interruptedexception ie ifball null do some calculations public void handlecollisionball b some more code ball b synchronized standby standbynotify,['java'] +924485,xcode 7 exception breakpoint firing in mainm but app runs normally i have set an all exceptions exception breakpoint for my project in xcode 7 it mysteriously fires on launch in mainm but there does not seem to be anything obviously wrong on continuing the app runs normallyeven running the project in xcode 6 now causes this breakpoint to fire i cannot figure out what is causing this the threads do not indicate anything specific to what the cause ismaybe it is some sort of font issue in the storyboard or something does anyone know a fixnote it is a c exception not objectivec perhaps due to missing fonts xcode throws an exception in main in ios 8 with all exceptions breakpoint,"['ios', 'objective-c']" +924523,calculate how a value differs from the average of values using the gaussian kernel density python i use this code to calculate a gaussian kernel density on this valuesfrom random import randintx gridfor i in range10 x gridappendrandint04print x gridthis is the code to calculate the gaussian kernel densityfrom statsmodelsnonparametrickde import kdeunivariateimport matplotlibpyplot as pltdef kde statsmodels ux x grid bandwidth02 kwargs univariate kernel density estimation with statsmodels kde kdeunivariatex kdefitbwbandwidth kwargs return kdeevaluatex gridimport numpy as npfrom scipystatsthistributions import norm the grid well use for plottingfrom random import randintx gridfor i in range10 x gridappendrandint04print x grid draw points from a bimodal thistribution in 1dnprandomseed0x npconcatenatenorm1 1rvs400 norm1 03rvs100pdf true 08 norm1 1pdfx grid 02 norm1 03pdfx grid plot the three kernel density estimatesfig ax pltsubplots1 2 shareytrue figsize13 8figsubplots adjustwspace0pdfkde statsmodels ux x grid bandwidth02ax0plotx grid pdf colorblue alpha05 lw3ax0fillx grid pdf true ecgray fcgray alpha04ax0set titlekde statsmodels uax0set xlim45 35pltshowall the values in the grid are between 0 e 4 if i receive a new value of 5 i want to calculate how that value differs from the average values and assign to it a score between 0 and 1 setting a thresholdso if i receive as a new value 5 its score must be close to 090 while if i receive as a new value 500 its score must be close to 00how can i do that is my function to calculate the gaussian kernel density correct or is there a better waylibrary to do that update i read an example in a paperthe weight of a washing machine is typically of 100 kg usually vendors use the kg unit to also refer its capacity example 9 kg for a human is easy to understand that 9 gk is the capacity and not the total weight of the washing machine we can afakea this form of intelligence without deep language understanding by insteadmodeling a thistribution of values over training data for eachattributefor a given attribute a weight of a washing machine for example let va va1 va2 van va n be the set of values of attribute a corresponding to productsin the training data if i found a new value v intuitively it is aclosea to thethistribution estimated from va then we should feel more confident assigning this value to a example weight of a washing machinean idea could be to measure the number of standard deviations bywhich the new value v differs from the average of values in va but a better one could be to model a gaussian kernel density on va and then express the support at new value v as the density at that pointwhere where i2ak is the variance of the kth gaussian and z isa constant to make sure scsv va a 0 1 how can i obtain it in python using the statsmodels library updated 2 example of data but i think that is not very importantgenerated by this code from random import randintx gridfor i in range10 x gridappendrandint13print x grid2 2 1 2 2 3 1 1 1 2 2 2 1 1 3 3 1 2 1 3 2 3 3 1 2 3 1 1 3 2 2 1 1 1 2 3 2 1 2 3 3 2 2 3 3 2 2 1 2 1 2 2 3 3 1 1 2 3 3 2 1 2 3 3 3 3 2 1 3 2 2 1 3 3 1 2 1 3 2 3 3 1 2 3 3 2 1 2 3 2 1 1 2 1 1 2 3 2 1 2 2 2 3 2 3 3 1 1 3 2 1 1 3 3 3 2 1 2 2 1 3 2 3 1 3 1 2 3 1 3 2 2 1 1 2 2 3 1 1 3 2 2 1 2 1 2 3 1 3 3 1 2 1 2 1 3 1 3 3 2 1 1 3 2 2 2 3 2 1 3 2 1 1 3 3 3 2 1 1 3 2 1 2 2 2 1 3 1 3 2 3 1 2 1 1 2 2 2 3 3 3 3 2 2 2 3 1 1 2 2 1 1 1 3 3 3 3 1 3 1 3 1 1 1 2 1 2 1 1 2 1 3 1 2 3 1 3 2 2 2 2 2 1 1 2 3 1 1 1 3 1 3 2 2 3 1 3 3 2 2 3 2 1 2 1 1 1 2 2 3 2 1 1 3 1 2 1 3 3 3 1 2 2 2 1 1 2 2 1 2 3 1 3 2 2 2 2 2 2 1 3 1 3 3 2 3 2 1 3 3 3 3 3 1 2 2 2 1 1 3 2 3 1 2 3 2 3 2 1 1 3 3 1 1 2 3 2 3 3 2 3 3 2 3 3 3 3 3 3 3 2 1 1 2 3 2 3 1 1 1 1 2 2 2 2 1 1 2 2 1 3 1 1 2 3 1 1 2 3 1 2 3 1 2 1 3 3 2 2 3 3 3 2 1 1 2 2 3 2 3 2 1 1 1 1 2 3 1 3 3 3 2 1 2 3 1 2 1 1 2 3 3 1 1 3 2 1 3 3 2 1 1 3 1 3 1 2 2 1 3 3 2 3 1 1 3 1 2 2 1 3 2 3 1 1 3 1 3 1 2 1 3 2 2 2 2 1 3 2 1 3 3 2 3 2 1 3 1 2 1 2 3 2 3 2 3 3 2 3 3 1 1 3 2 3 2 2 2 3 1 3 2 2 3 3 2 3 2 2 2 3 3 1 3 2 3 1 1 2 1 3 1 2 2 3 3 1 3 1 1 2 2 1 3 3 3 1 2 2 2 1 3 1 2 2 2 3 3 3 1 1 2 3 3 1 1 2 3 2 3 3 2 2 1 3 3 3 3 2 3 1 3 3 2 1 3 2 1 1 3 3 2 2 2 2 1 1 1 1 2 3 3 3 2 1 3 1 1 1 1 3 1 2 3 3 3 2 3 1 2 2 2 3 2 1 2 3 3 2 3 3 1 2 3 3 3 3 2 3 3 2 1 1 1 2 3 1 3 3 2 1 3 3 3 2 2 1 2 3 2 3 3 3 3 2 3 2 1 2 1 1 3 3 3 2 2 3 1 3 2 1 3 1 1 3 3 1 2 2 2 3 3 1 2 1 2 1 3 2 3 3 3 3 3 3 3 1 2 3 1 3 3 2 2 1 3 1 1 3 2 1 2 3 2 1 3 3 3 2 3 1 2 3 3 1 2 2 2 3 1 2 1 1 1 3 1 3 1 3 3 2 3 1 3 2 3 3 1 2 1 3 2 2 2 2 2 2 1 2 2 3 2 2 3 2 2 2 3 1 1 3 3 1 3 1 2 1 2 1 3 2 2 1 3 1 3 3 1 3 1 1 1 1 3 2 1 2 3 1 1 3 1 1 3 1 3 3 3 1 1 3 1 3 2 2 2 1 1 2 3 3 2 3 3 1 2 3 2 2 3 1 2 2 2 1 1 3 1 2 2 2 1 1 2 3 1 3 1 1 3 2 2 3 2 2 3 3 1 1 2 2 3 1 1 2 3 2 2 3 1 2 2 1 1 3 2 3 1 1 3 1 3 2 3 3 3 3 3 2 2 3 2 1 1 1 3 3 1 2 1 3 2 3 2 2 1 2 3 3 1 1 1 1 3 3 1 3 3 1 1 3 1 3 1 3 2 3 1 3 3 3 1 1 2 2 3 2 3 2 2 1 2 1 2 1 2 2 3 1 1 3 2 2 3 2 3 3 2 2 2 2 2 2 3 2 3 1 2 2 1 1 2 3 3 1 3 3 1 3 3 1 3 2 2 2 1 1 2 1 3 1 1 1 2 3 3 2 3 1 3this array represents the ram of new smartphones in the market usually they have 123 gb of ramthat is the kernel density updatei try the code with this values1024 1 1024 10 1024 128 1536 16 192 2048 20 2048 24 250 256 278 288 290 3072 3 30 3072 32 384 4096 4 4096 448 45 512 576 64 768 8 96the values are all in mb do you think that is working well i think that i must set a threshold 100 cdfv kdev1 42 0210097 04997341024 96 0479597 0498350 0 0359 049852048 36 0181609 04997003048 8 0040299 0499424 update 3 256 256 256 256 256 256 256 256 256 256 256 256 256 256 256 256 256 256 256 256 256 256 256 256 512 512 512 256 256 256 512 512 512 128 128 128 512 512 512 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 2048 2048 2048 1024 1024 1024 512 512 512 512 512 512 1024 1024 1024 2048 2048 2048 512 512 512 512 512 512 512 512 512 512 512 512 512 512 512 1024 1024 1024 1024 1024 1024 1024 1024 1024 512 512 512 128 128 128 512 512 512 256 256 256 256 256 256 1024 1024 1024 512 512 512 128 128 128 512 512 512 512 512 512 1024 1024 1024 1024 1024 1024 4 4 4 3 3 3 24 24 24 8 8 8 16 16 16 16 16 16 256 256 256 512 512 512 512 512 512 512 512 512 512 512 512 512 512 512 512 512 512 512 512 512 512 512 512 1024 1024 1024 1024 1024 1024 512 512 512 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 2048 2048 2048 512 512 512 1024 1024 1024 512 512 512 1024 1024 1024 2048 2048 2048 2048 2048 2048 512 512 512 512 512 512 256 256 256 256 256 256 256 256 256 512 512 512 512 512 512 1024 1024 1024 512 512 512 512 512 512 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 2048 2048 2048 2048 2048 2048 4096 4096 4096 2048 2048 2048 1024 1024 1024 1024 1024 1024 1024 1024 1024 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 512 512 512 512 512 512 512 512 512 512 512 512 512 512 512 768 768 768 768 768 768 2048 2048 2048 2048 2048 2048 3072 3072 3072 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 1024 1024 1024 512 512 512 256 256 256 512 512 512 1024 1024 1024 1024 1024 1024 1024 1024 1024 2048 2048 2048 1024 1024 1024 1024 1024 1024 2048 2048 2048 1024 1024 1024 3072 3072 3072 1024 1024 1024 512 512 512 1024 1024 1024 1024 1024 1024 512 512 512 2048 2048 2048 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 2048 2048 2048 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 2048 2048 2048 1024 1024 1024 2048 2048 2048 1024 1024 1024 1024 1024 1024 1024 1024 1024 512 512 512 1024 1024 1024 512 512 512 512 512 512 512 512 512 1024 1024 1024 1024 1024 1024 512 512 512 1024 1024 1024 512 512 512 1024 1024 1024 512 512 512 512 512 512 512 512 512 256 256 256 1024 1024 1024 2048 2048 2048 1024 1024 1024 1024 1024 1024 512 512 512 512 512 512 1024 1024 1024 1024 1024 1024 1024 1024 1024 2048 2048 2048 1024 1024 1024 2048 2048 2048 1024 1024 1024 512 512 512 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 1024 1024 1024 1024 1024 1024 1024 1024 1024 2048 2048 2048 2048 2048 2048 2048 2048 2048 1024 1024 1024 2048 2048 2048 512 512 512 512 512 512 1024 1024 1024 1024 1024 1024 512 512 512 64 64 64 1024 1024 1024 1024 1024 1024 256 256 256 512 512 512 512 512 512 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 64 64 64 64 64 64 128 128 128 128 128 128 128 128 128 128 128 128 64 64 64 64 64 64 64 64 64 64 64 64 128 128 128 576 576 576 512 512 512 1024 1024 1024 512 512 512 576 576 576 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 2048 2048 2048 512 512 512 2048 2048 2048 768 768 768 768 768 768 768 768 768 512 512 512 192 192 192 1024 1024 1024 512 512 512 512 512 512 384 384 384 448 448 448 576 576 576 384 384 384 288 288 288 768 768 768 384 384 384 288 288 288 64 64 64 2048 2048 2048 2048 2048 2048 2048 2048 2048 3072 3072 3072 2048 2048 2048 2048 2048 2048 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 512 512 512 1024 1024 1024 64 64 64 128 128 128 128 128 128 128 128 128 64 64 64 64 64 64 64 64 64 64 64 64 256 256 256 768 768 768 768 768 768 768 768 768 256 256 256 192 192 192 256 256 256 64 64 64 256 256 256 192 192 192 128 128 128 256 256 256 192 192 192 288 288 288 288 288 288 288 288 288 288 288 288 128 128 128 128 128 128 384 384 384 512 512 512 1024 1024 1024 1024 1024 1024 1024 1024 1024 2048 2048 2048 2048 2048 2048 2048 2048 2048 3072 3072 3072 1024 1024 1024 2048 2048 2048 2048 2048 2048 3072 3072 3072 512 512 512 512 512 512 512 512 512 1024 1024 1024 1024 1024 1024 512 512 512 1024 1024 1024 512 512 512 512 512 512 512 512 512 1024 1024 1024 1024 1024 1024 32 32 32 768 768 768 1024 1024 1024 1024 1024 1024 1024 1024 1024 2048 2048 2048 1024 1024 1024 2048 2048 2048 3072 3072 3072 2048 2048 2048 1024 1024 1024 2048 2048 2048 1024 1024 1024 2048 2048 2048 256 256 256 256 256 256 256 256 256 256 256 256 512 512 512 512 512 512 256 256 256 512 512 512 512 512 512 512 512 512 64 64 64 64 64 64 64 64 64 64 64 64 128 128 128 128 128 128 1024 1024 1024 1024 1024 1024 128 128 128 1024 1024 1024 2048 2048 2048 1024 1024 1024 1024 1024 1024 2048 2048 2048 3072 3072 3072 1024 1024 1024 1024 1024 1024 512 512 512 512 512 512 512 512 512 512 512 512 2048 2048 2048 1024 1024 1024 2048 2048 2048 1024 1024 1024 1024 1024 1024 512 512 512 512 512 512 1024 1024 1024 512 512 512 1024 1024 1024 512 512 512 512 512 512 512 512 512 1024 1024 1024 2048 2048 2048 2048 2048 2048 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 2048 2048 2048 2048 2048 2048 512 512 512 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 256 256 256 256 256 256 512 512 512 512 512 512 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 2048 2048 2048 2048 2048 2048 2048 2048 2048 3072 3072 3072 2048 2048 2048 384 384 384 512 512 512 512 512 512 512 512 512 512 512 512 512 512 512 512 512 512 512 512 512 512 512 512 2048 2048 2048 2048 2048 2048 2048 2048 2048 1024 1024 1024 2048 2048 2048 1024 1024 1024 3072 3072 3072 3072 3072 3072 3072 3072 3072 128 128 128 256 256 256 1024 1024 1024 1024 1024 1024 1024 1024 1024 2048 2048 2048 512 512 512 1024 1024 1024 1024 1024 1024 2048 2048 2048 512 512 512 512 512 512 512 512 512 512 512 512 768 768 768 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 512 512 512 1024 1024 1024 128 128 128 512 512 512 1024 1024 1024 512 512 512 1024 1024 1024 512 512 512 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 2048 2048 2048 1024 1024 1024 1024 1024 1024 1024 1024 1024 2048 2048 2048 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 512 512 512 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 64 64 64 64 64 64 256 256 256 512 512 512 512 512 512 512 512 512 16 16 16 3072 3072 3072 3072 3072 3072 256 256 256 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 2048 2048 2048 2048 2048 2048 2048 2048 2048 512 512 512 32 32 32 1024 1024 1024 1024 1024 1024 256 256 256 256 256 256 512 512 512 512 512 512 512 512 512 512 512 512 512 512 512 512 512 512 1024 1024 1024 1024 1024 1024 512 512 512 512 512 512 512 512 512 512 512 512 512 512 512 1024 1024 1024 512 512 512 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 32 32 32 2048 2048 2048 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 2048 2048 2048 512 512 512 1 1 1 1024 1024 1024 32 32 32 32 32 32 45 45 45 8 8 8 512 512 512 256 256 256 512 512 512 512 512 512 512 512 512 512 512 512 1024 1024 1024 512 512 512 512 512 512 512 512 512 512 512 512 512 512 512 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 512 512 512 16 16 16 4 4 4 4 4 4 4 4 4 16 16 16 16 16 16 16 16 16 64 64 64 8 8 8 8 8 8 8 8 8 64 64 64 64 64 64 256 256 256 64 64 64 64 64 64 512 512 512 512 512 512 512 512 512 32 32 32 32 32 32 32 32 32 128 128 128 128 128 128 128 128 128 32 32 32 128 128 128 64 64 64 64 64 64 16 16 16 256 256 256 2048 2048 2048 1024 1024 1024 2048 2048 2048 256 256 256 512 512 512 1024 1024 1024 512 512 512 256 256 256 512 512 512 512 512 512 512 512 512 512 512 512 1024 1024 1024 512 512 512 512 512 512 1024 1024 1024 1024 1024 1024 512 512 512 1024 1024 1024 1024 1024 1024 512 512 512 1024 1024 1024 1024 1024 1024 2048 2048 2048 256 256 256 256 256 256 1024 1024 1024 1024 1024 1024 256 256 256 3072 3072 3072 3072 3072 3072 128 128 128 1024 1024 1024 512 512 512 512 512 512 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 128 128 128 128 128 128 64 64 64 256 256 256 256 256 256 512 512 512 768 768 768 768 768 768 16 16 16 32 32 32 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 2048 2048 2048 2048 2048 2048 1024 1024 1024 2048 2048 2048 1024 1024 1024 512 512 512 2048 2048 2048 1024 1024 1024 3072 3072 3072 3072 3072 3072 2048 2048 2048 1024 1024 1024 1024 1024 1024 3072 3072 3072 3072 3072 3072 3072 3072 3072 3072 3072 3072 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 512 512 512 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 2048 2048 2048 1024 1024 1024 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 3072 3072 3072 3072 3072 3072 512 512 512 512 512 512 512 512 512 512 512 512 512 512 512 1024 1024 1024 512 512 512 64 64 64 96 96 96 512 512 512 64 64 64 64 64 64 512 512 512 512 512 512 512 512 512 512 512 512 512 512 512 512 512 512 1024 1024 1024 512 512 512 512 512 512 1024 1024 1024 512 512 512 512 512 512 1024 1024 1024 1024 1024 1024 1024 1024 1024 512 512 512 512 512 512 1024 1024 1024 1024 1024 1024 512 512 512 512 512 512 1024 1024 1024 512 512 512 1024 1024 1024 1024 1024 1024 512 512 512 512 512 512 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 512 512 512 512 512 512 1024 1024 1024 2048 2048 2048 2048 2048 2048 2048 2048 2048 3072 3072 3072 3072 3072 3072 2048 2048 2048 2048 2048 2048 2048 2048 2048 512 512 512 1024 1024 1024 2048 2048 2048 1024 1024 1024 1024 1024 1024 512 512 512 1024 1024 1024 1024 1024 1024 512 512 512 1024 1024 1024 512 512 512 1024 1024 1024 1024 1024 1024 2048 2048 2048 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 2048 2048 2048 64 64 64 64 64 64 256 256 256 1024 1024 1024 512 512 512 256 256 256 512 512 512 1024 1024 1024 512 512 512 512 512 512 1024 1024 1024 1024 1024 1024 2048 2048 2048 2048 2048 2048 512 512 512 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 2048 3072 3072 3072 3072 3072 3072 2048 2048 2048 1024 1024 1024 1024 1024 1024 1024 1024 1024 2048 2048 2048 2048 2048 2048 1024 1024 1024 2048 2048 2048 3072 3072 3072 2048 2048 2048with this data if i try as new value this number new valuesx npasarray1285121024204830722800something goes wrong with the 3072 all values are in mb this is the result 100 cdfv kdev128 26 0129688 0499376512 55 0275874 04996711024 91 0454159 049362048 12 0062298 04991503072 0 01556 04983642800 1 04954 0498573i cannot understand why this happens the 3072 value appears a lot of time in the data this is the histogram of my datas this is very strange because there are some values for 3072 and also for 4096,['python'] +924566,why does variable initialization of to an assignment expression string x x y compile how does this compiles without error as my understanding the compiler checks the type of the variable in this case string then sees if the type of the expression on the right side corresponds to the variables type or at least a subtype but let us stick to the simple case with the string class since it is final public class initclass public static void mainstring args string str str hello systemoutprintlnstr my question is how does str hello compile is the compiler already aware that str should be of type string,['java'] +924720,attributeerror fileinput instance has no attribute exit i am trying to read from multiple input files and print the second row from each file next to each other as a tableimport sysimport fileinputwith fileinputinputfilescutflow ttjets 1ltxt cutflow ttjets 1ltxt as f for line in f proclinedef procline parts linesplit split line into parts if in line if at least 2 partscolumns print parts1 print column 2 but i get a attributeerror fileinput instance has no attribute exit,['python'] +924887,jquery selector using value but unknown attribute how can i use jquery to search for elements that have a specific attribute value regardless of the attribute taglikemyvalueshould finda hreftargethtml targetmyvaluetr changemyvaluethe first one because of the target attribute the second one for the change attributeis there a better solution than just iterate over all attributes,"['javascript', 'jquery']" +924911,calabashandroid attach to running app i have calabashandroid set up working perfectly with a default scenario using cucumber to run tests or calabashandroid console to enter repl modehowever under some scenarios it turns out to be pretty useful to be able to attach to an app that is already running for instance i would start an app in debug mode and start the tests to be able to set breakpoints and check why certain features do not work as expected in my scenarios when it comes to calabash on ios this task is really straightforward no additional preparation needed as the app starts with a test server bundled in and i can attach calabash to it at any time however calabash android seems to be forcequitting the app every time i try to start calabash having the app runningis there any way around itedit looks like the below answers did not help much but i still hope someone calabash devs where are you will stumble upon this one day i have spent some time thiscovering the issue myself and that is what the specific issue isstart the app in debug mode using xamarin for instancestart calabashandroid console path to apktry issuing any commands eg query a it fails with a message keepalivethisconnectedtry running start test server in background a the app is killed and debug session is terminateddigging deeper into details i found out that start test server in background in fact runs shell am instrument with shcalabainstrumentationbackendcalabashinstrumentationtestrunner being instrumentation backend and a bunch of other flags describing which app to instrument what port to use etc thus being said the following would help a lot is it possible for shell am instrument to attach to a running app,['android'] +925015,import on class instanciation i am creating a module with several classes in it my problem is that some of these classes need to import very specific modules that needs to be manually compiled or need specific hardware to workthere is no interest in importing every specific module up front and as some modules need specific hardware to work it could even raise errorsi would like to know if it is possible to import these module only when needed that is on instantiation of a precise class like so class specificclassthatneedrandommoduleobject import randommodulealso i am not sure that this would be a good pythonic way of doing the trick so i am open to suggestion for a proper way,['python'] +925039,swift protocol extension self reference issues with init i am looking for a way to add a default initializer to a protocol via protocol extensionsmy protocol isprotocol testprotocol var myvar double get set initvalue double initexistingstruct testprotocoli have implemented a struct using this protocol asstruct teststruct testprotocol var myvar double initvalue double myvar value init existingstruct testprotocol myvar existingstructmyvar however if i try via extension to make a default initializer for this protocol i run into self issuesextension testprotocol initvalue double myvar value initexistingstruct testprotocol myvar existingstructmyvar where both assignment lines issue the error variable self passed by reference before being initializedis there a way to make this work or am i limited to using classes,['ios'] +925113,prevent nouislider tooltips from overlapping the nouislider is a great working plugin however i would like the tooltips to not overlap each other i have the following which works except for the overlapping tooltipsslidernouisliderrange min 0 max 100 step 5connect truestart 20 50 sliderlinklowertoinlinediv classtooltipdiv functionvaluethistext from value sliderlinkuppertoinlinediv classtooltipdiv functionvaluethistext from value i am thinking something like this would be nice anyone got a clue,"['javascript', 'jquery']" +925127,huge unusable font size in android studio as the title states i have inadvertently set the font size to something gargantuan in android studio and it is now totally unusable at most i see the tops of a few letters once the program loads so i cannot even get back into the options to reduce the font size looking through the config files has given me no joy so i am looking for some way of adjusting the settings from outside the program itself or deleting all user customised settings and starting again without completely deleting everything i had tried to uninstall and reinstall which worked for a short while then the font went back from normal to huge edit i have managed to fix it for now at least by moving the androidstudio12 file from my users folder and starting android studio again allowing it to reset,['android'] +925280,convert column collation to tabledatabase default every single post on so that i have seen to accomplish this suggests running the following sqlalter table tablename convert to character set utf8 collate utf8 unicode cithe problem with this unless i am mistaken is that it explicitly specifies the column collations so you end up with something like this when you mysqldump the database address varchar150 collate utf8 unicode ci default null city varchar100 collate utf8 unicode ci default null state varchar2 collate utf8 unicode ci default null zipcode varchar10 collate utf8 unicode ci default nullmy question is is there no way to convert the column collations to the table or database default without doing thisfor example i have tables that might look like this address varchar150 default null city varchar100 default null state varchar2 collate utf8 general ci default null zipcode varchar10 collate utf8 unicode ci default nullwhat i want is to convert all columns to utf8 unicode ci the tabledatabase default but not have each column explicitly set to that collation so that when i mysqldump the converted table it just looks like this address varchar150 default null city varchar100 default null state varchar2 default null zipcode varchar10 default nullwith a line at the end of the table creation statement that defines the default character set and collation engineinnodb default charsetutf8 collateutf8 unicode ci,['mysql'] +925291,python set interpetation of 1 and true in ipython 3 interactive shellin 53 set2 1 2 true helloin 54 lenset2out54 3in 55 set2out55 hello true 2is that because 1 and true get the same interpetation so given that set eliminates duplicates only one of them true gets to stayhow can we keep both,['python'] +925327,thisplaying a stock ios notification banner when your app is open and in the foreground when apples official ios messages app is open and in the foreground new messages from other contacts trigger a stock ios notification alert banner see image belowis this possible in 3rd party apps on the app store local andor push notifications for your app while your app is open and in the foregroundwhen testing my app notifications are received but no ios alert ui is shownbut this behavior is seen in apples official messages appthe local and remote notification programming guide sayswhen the operating system delivers a local notification or remote notification and the target app is not running in the foreground it can present the notification to the user through an alert icon badge number or soundif the app is running in the foreground when the notification is delivered the app delegate receives a local or remote notificationso yes we can receive the notification while in the foreground but i see no way to present the stock ios notification alert uivoidapplicationuiapplication application didreceiveremotenotificationnsdictionary userinfo i know we still receive the notification in the foreground this question is about thisplaying the stock ios notification alert ui yes one could use a 3rd party toast alert framework self use3rdpartytoastalertframeworkfromgithubis messages then using a private api to thisplay the alert while in the foregroundfor the purpose of this question please do not suggest any 3rd party toast popup alerts on github or etc i am only interested if this can be done using the stock ios local or push notification alerts while your application is open and in the foreground,['ios'] +925389,how to get monospaced numbers in uilabel on ios 9 at wwdc 2015 there was a session about the new asan franciscoa system font in ios 9 it uses proportional number rendering instead of monospaced numbers by default when linked against the ios 9 sdk there is a convenient initializer on nsfont called nsfontmonospaceddigitssystemfontofsizemysize weight that can be used to explicitly enable monospaced number thisplayhowever i could not find the uikit equivalent for this on uifont,['ios'] +925396,css animations delay and playstate behavior i am trying to capture a specific moment in elements animation meaning i want the animation to start and stop at point x lets say start and stop on second 5 of 100s animationhere is my shot at itjsfiddlewebkitkeyframes background from background yellow 100 background blue div webkitanimationname background webkitanimationduration 100s webkitanimationfillmode forwards webkitanimationdelay 40s webkitanimationplaystate pausedthis seems to work great in chrome and firefox but doesnt seem to work in safari and ieno way rightnote i left the prefix in on purpose to test it on safari specificallyunlike in chrome it seems like the animation never starts in safari and remains on the initial stepis this a known issue is there a workaround or another way to implement thisupdateclarificationwhat i need is to be able to capture a specific frame of the animation open my fiddle in chrome and play around animationdelay attribute in my fiddle make sure it remains negative what you will see is that you are able to catch 1 specific frame of the animation thats exactly what i need my problem is that this doesnt work in safari,['css'] +925398,javafx undo facility i recently started learning the javafx api after i already experience in swingi noticed that even a lot of classes were already well implemented in awt and swing they were effectively reimplemented in javafx this includes javafxscenepaintcolorjavafxeventactioneventvsjavaawtcolorjavaawteventactioneventand much more even though it could have easily require to use them i assume that this is so to decouple javafx the most possible from the other libraries so new developers should not even know of their existents okif my assumption is true why did not they include a new implementation ofjavaxswingundopackagealthough i understand that undo has really nothing to do with the user interface so it has nothing to do with swing too if for any reason they decided to include it in the javaxswing package so could they include it in javafx,['java'] +925444,ios app thisplaying incorrect date in mac itunes i built an ionic app and have noticed that the ipa installed into itunes is thisplaying a date of 123103 where would i change that date or set it dynamicallyhere is a screenshot screenshotthanks,['ios'] +925473,sending extra to requestlocationupdates intentservice breaks location updates i am having trouble sending a string extra with my pendingintent that i pass to locationservicesfusedlocationapirequestlocationupdatesgoogleapiclient client locationrequest request pendingintent callbackintent it appears that the username extra i am putting onto the intent is mangling the location that requestlocationupdates is trying to hand off to my intentservice as intentgetparcelableextrafusedlocationproviderapikey location changed returns nulledit i have tried making a user class that implements parcelable and putting it as an extra mrequestlocationupdatesintentputextrausername new userusernameand i have also tried to put the parcelable user inside a bundle as suggested via comment in this bug report bundle userbundle new bundleuserbundleputparcelableuser new userusernamemrequestlocationupdatesintentputextrauser userbundlein my service bundle userbundle intentgetbundleextrauseruser user userbundlegetparcelableuserstring username usergetusernamehowever neither of these approaches has made any difference whenever i put any extra onto my intent the location is never added to the intent when the updates occuri setup this intentservice to handle location updatespublic class locationupdateservice extends intentservice private final string tag locationupdateservice public locationupdateservice superlocationupdateservice override protected void onhandleintentintent intent logdtag onhandleintent bundle extras intentgetextras logdtag keys found inside intent textutilsjoin extraskeyset string username intentgetstringextrausername if username null logdtag username username else logdtag username null if intenthasextrafusedlocationproviderapikey location changed logdtag intent does not have location location location intentgetparcelableextrafusedlocationproviderapikey location changed if location null logdtag location null logdtag latitude stringvalueoflocationgetlatitude logdtag longitude stringvalueoflocationgetlongitude when the user clicks a button the startlocationupdates is called in my main activitymain activity classboolean mlocationupdatesenabled falseprotected void createlocationrequest mlocationrequest new locationrequest mlocationrequestsetintervallocation update interval mlocationrequestsetfastestintervallocation update fastest interval mlocationrequestsetprioritylocationrequestpriority high accuracyprotected void startlocationupdates logdtag startng location updates mlocationupdatesenabled true if mlocationrequest null createlocationrequest create the intent to use webviewactivity to handle results intent mrequestlocationupdatesintent new intentthis locationupdateserviceclass create a pendingintent mrequestlocationupdatespendingintent pendingintentgetservicegetapplicationcontext 0 mrequestlocationupdatesintent pendingintentflag cancel current request location updates locationservicesfusedlocationapirequestlocationupdatesmgoogleapiclient mlocationrequest mrequestlocationupdatespendingintent logdtag location updates startedprotected void stoplocationupdates logdtag stopping location updates mlocationupdatesenabled false locationservicesfusedlocationapiremovelocationupdates mgoogleapiclient mrequestlocationupdatespendingintent logdtag location updates stoppedthis all works well and good when the user presses the button togglelocationupdates is called which calls locationservicesfusedlocationapirequestlocationupdates which calls my locationupdateservice where i am able to get the locationthe trouble comes when i tried to put a string extra onto my intent using intentputextrastring stringmain activity classprotected void startlocationupdatesstring username create the intent to use webviewactivity to handle results intent mrequestlocationupdatesintent new intentthis locationupdateserviceclass when i put this extra intentservice sees my username extra but the parcelableextra location null mrequestlocationupdatesintentputextrausername username edit i had started the next sentence as a statement rather than a question i am usingam i using the correct approach to sending some extra data to this location update handling intentservice or is there a moresane way to go about this is this a bug or just poor documentation,['android'] +925541,dereferencing a temporary unique ptr unique ptra myfun unique ptra panew a return paconst a ra myfunthis code compiles but ra contains garbage can someone explain to me why is this code invalidnote if i assign the return of myfun to a named unique ptr variable before dereferencing it it works fine,['c++'] +925543,how to use httpclient to post with authentication i am trying to do the following curl which works for me in c using httpclientcurl x post u clientidclientsecret d grant typepassword d usernameemail d passwordpassword d scopeallthe c codehttpclienthandler handler new httpclienthandler credentials new systemnetnetworkcredential my client id my client secret try usingvar httpclient new httpclienthandler var activationurl wsomehosturlcom var postdata grant typepasswordusernamepasswordmypascopeall var content new stringcontentpostdata encodingutf8 applicationxwformurlencoded var response await httpclientpostasyncactivationurl content ifresponseissuccestatuscode return null var result await responsecontentreadasstringasync return result catchexception return null when executed just crashes out doesnt even catch the exceptionnormally i am able to get and post perfectly fine but whats throwing me off is how to set the auth stuff clientid and clientsecret,"['c#', '.net']" +925731,change ndkbuild output locations my app has the following structureandroid app build 1 src main assets java jni androidmk applicationmk jnilibs armeabi armeabiv7a res androidmanifestxml build 2i am building my so libraries with ndkbuild command in a linux machine i use it likemy ndk location pathndkbuild c my project location pathandroidappsrcmainthe build process works fine and output files are produced with no errorsmy problem is that the result files are not directed to the proper positionthe libs generated at appsrcmainlibsarmeabiv7alibmygeneratedlibrarysoappsrcmainlibsarmeabilibmygeneratedlibrarysoand the obj files at appsrcmainobjlocalarmeabiv7alibmygeneratedlibrarysoappsrcmainobjlocalarmeabilibmygeneratedlibrarysoi would like the output to produced in different locationsthe libs at jnilibsie appsrcmainjnilibsarmeabi the obj under one of the build folders ie build1 or build2is there any possible way to achieve that by changing some parameter to the mk files or to the build commandedittarget out does not seem to work in ndk r6bexecuting command ndkbuild c androidappsrcmain target outandroidappsrcmainjnilibstarget arch abi warnings as the following appear for each generated fileandroidndkr6bbuildcorebuildbinarymk217 warning overriding commands for target androidappsrcmainjnilibsobjsoandroidndkr6bbuildcorebuildbinarymk217 warning ignoring old commands for target androidappsrcmainjnilibsobjso,['android'] +925749,why does failing to recognise equality mess up c list sort this is a somewhat obscure question but after wasting an hour tracking down the bug i though it worth askingi wrote a custom ordering for a struct and made one mistakemy struct has a special state let us call this minif the struct is in the min state then it is smaller than any other structmy compareto method made one mistake acomparetob would return 1 whenever a was min but of course if b is also min it should return 0now this mistake completely messed up a listmystruct sort method the whole list would sometimes come out in a random ordermy list contained exactly one object in min stateit seems my mistake could only affect things if the one min object was compared to itselfwhy would this even happen when sortingand even if it did how can it cause the relative order of two nonmin objects to be wrongusing the linq orderby method can cause an infinite loopsmall complete test examplestruct mystruct icomparablemystruct public int state public mystructint s state s public int comparetomystruct rhs 10 is the min state otherwise order as usual if state 10 return 1 incorrect if state 10 correct version if rhsstate 10 return 0 return 1 if rhsstate 10 return 1 return thisstate rhsstate public override string tostring return stringformatmystruct0 state class program static int main var list new listmystruct var rnd new random for int i 0 i 20 i int x rndnext15 if x 10 x listaddnew mystructx listaddnew mystruct10 listsort never returns list listorderbyitem itemtolist consolewritelinelist foreach var x in list consolewritelinex for int i 1 i listcount i consolewrite0 listicomparetolisti 1 return 0,['c#'] +925811,python pandas to sql how to create a table with a primary key i would like to create a mysql table with pandas to sql function which has a primary key it is usually kind of good to have a primary key in a mysql table as sogroup exportto sqlcon db name configtable group export if exists replace flavor mysql index falsebut this creates a table without any primary key or even without any indexthe documentation mentions the parameter indel label which could be used to create an index but does not mention any option for primary keysdocumentation,"['python', 'mysql']" +925882,ng if with angular for string contains i have the following angular codeli ngrepeatselect in items foo ngrepeatnewin selectvaluesnewlabelfoohow can i use an ngif condition to look for a specific characterngifselectname to only thisplay the code when the character is here the value i have is like 8877 and the numbers are dynamic but the question mark is always there i cannot seem to filter based on that,"['javascript', 'jquery', 'css']" +925925,how do i generate sourcemaps when using babel and webpack i am new to webpack and i need a hand in setting up to generate sourcemaps i am running webpack serve from the command line which compiles successfully but i really need sourcemaps this is my webpackconfigjsvar webpack requirewebpackmoduleexports output filename mainjs publicpath assets cache true debug true devtool true entry webpackhotonlydevserver srccomponentsmainjs stats colors true reasons true resolve extensions js jsx alias styles dirname srcstyles mixins dirname srcmixins components dirname srccomponents stores dirname srcstores actions dirname srcactions module preloaders test jsjsx exclude node modules loader jsxhint loaders test jsjsx exclude node modules loader reacthotbabelloader test sass loader styleloadercssloadersassloaderoutputstyleexpandedindentedsyntax test scss loader styleloadercsass test pngjpgwoffwoff2 loader urlloaderlimit8192 plugins new webpackhotmodulereplacementplugin new webpacknoerrorsplugin i am really new to webpack and looking though the docs has not really helped as i am not sure what this problem is specific to,['javascript'] +925959,xcode 64 could not download and install ios 83 simulator i have been trying to install ios simulators 83 84 on xcode 632 an 64 beta respectively in the first case is not even an option to download this simulator while in xcode 64 it shows an error could not download and install ios 83 simulator authorization is required to install the packages i have searched the web but i could not find anything so i tries reinstalling xcode from apple developer website as well as from the app store with no change at all the only simulator i can use is 82 i cannot install any other version any help would be really appreciatedthis is the error on xcode 64 with no additional option of ios 84 simulatorthese are the simulator options for me to download which result in that errorthese are my options in xcode 632 with no option for ios 83,"['ios', 'iphone']" +926201,could not initialize class androidsupportdesignwidgetcoordinatorlayout i am trying to use the coordinatorlayout from the new android design library i added the package to gradle then i try to use the layout i get this errorjavalangnoclassdeffounderror could not initialize class androidsupportdesignwidgetcoordinatorlayoutat sunreflectnativeconstructoraccessorimplnewinstance0native methodat sunreflectnativeconstructoraccessorimplnewinstancenativeconstructoraccessorimpljava39at sunreflectdelegatingconstructoraccessorimplnewinstancedelegatingconstructoraccessorimpljava27at javalangreflectconstructornewinstanceconstructorjava513at orgjetbrainsandroiduipreviewviewloadercreatenewinstanceviewloaderjava413at orgjetbrainsandroiduipreviewviewloaderloadviewviewloaderjava105at comandroidtoolsidearenderinglayoutlibcallbackloadviewlayoutlibcallbackjava177at androidviewbridgeinflaterloadcustomviewbridgeinflaterjava207at androidviewbridgeinflatercreateviewfromtagbridgeinflaterjava132at androidviewlayoutinflaterinflatelayoutinflaterjava482at androidviewlayoutinflaterinflatelayoutinflaterjava385at comandroidlayoutlibbridgeimplrendersessionimplinflaterendersessionimpljava400at comandroidlayoutlibbridgebridgecreatesessionbridgejava332at comandroididecommonrenderinglayoutlibrarycreatesessionlayoutlibraryjava350at comandroidtoolsidearenderingrendertask2computerendertaskjava497at comandroidtoolsidearenderingrendertask2computerendertaskjava485at comintellijopenapiapplicationimplapplicationimplrunreadactionapplicationimpljava894at comandroidtoolsidearenderingrendertaskcreaterendersessionrendertaskjava485at comandroidtoolsidearenderingrendertaskrenderrendertaskjava590at orgjetbrainsandroiduipreviewandroidlayoutpreviewtoolwindowmanagerdorenderandroidlayoutpreviewtoolwindowmanagerjava644at orgjetbrainsandroiduipreviewandroidlayoutpreviewtoolwindowmanageraccess1700androidlayoutpreviewtoolwindowmanagerjava79at orgjetbrainsandroiduipreviewandroidlayoutpreviewtoolwindowmanager71runandroidlayoutpreviewtoolwindowmanagerjava586at comintellijopenapiprogressimplcoreprogressmanager2runcoreprogressmanagerjava152at comintellijopenapiprogressimplcoreprogressmanagerregisterindicatorandruncoreprogressmanagerjava452at comintellijopenapiprogressimplcoreprogressmanagerexecuteprocessunderprogresscoreprogressmanagerjava402at comintellijopenapiprogressimplprogressmanagerimplexecuteprocessunderprogressprogressmanagerimpljava54at comintellijopenapiprogressimplcoreprogressmanagerrunprocesscoreprogressmanagerjava137at orgjetbrainsandroiduipreviewandroidlayoutpreviewtoolwindowmanager7runandroidlayoutpreviewtoolwindowmanagerjava581at comintellijutiluiupdatemergingupdatequeueexecutemergingupdatequeuejava320at comintellijutiluiupdatemergingupdatequeueexecutemergingupdatequeuejava310at comintellijutiluiupdatemergingupdatequeue2runmergingupdatequeuejava254at comintellijutiluiupdatemergingupdatequeueflushmergingupdatequeuejava269at comintellijutiluiupdatemergingupdatequeueflushmergingupdatequeuejava227at comintellijutiluiupdatemergingupdatequeuerunmergingupdatequeuejava217at comintellijutilconcurrencyqueueprocessorrunsafelyqueueprocessorjava238at comintellijutilalarmrequest1runalarmjava351at javautilconcurrentexecutorsrunnableadaptercallexecutorsjava439at javautilconcurrentfuturetasksyncinnerrunfuturetaskjava303at javautilconcurrentfuturetaskrunfuturetaskjava138at javautilconcurrentthreadpoolexecutorworkerruntaskthreadpoolexecutorjava895at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava918at javalangthreadrunthreadjava695anybody have a fix for this thank you,['android'] +926287,how to configure log4j 2x purely programmatically how do i configure log4j 23 with console appender pure programmatically no configuration files of any formatbasically i am looking for 2x version of this 1x code in my classes i would then useprivate static final logger logger logmanagergetlogger some method loggerdebugsomestringwithout any configuration i am as expected facing error statuslogger no log4j2 configuration file found using default configuration logging only errors to the consolewhile usage of configuration files seems to be properly documented i could not find a good example of a barebone codeonly casethe closest i got is this article that still uses a dummy fileheres my best though completely unsuccessful shotprivate static void configurelog4j patternlayout layout patternlayoutcreatedefaultlayout consoleappender appender consoleappendercreatedefaultappenderforlayoutlayout loggerconfig loggerconfig new loggerconfig loggerconfigaddappenderappender debug nullhave i missed something if it is still a rtfm case please point me into the right direction,['java'] +926345,video streaming issue i am using mpmovieplayercontroller for playing hls ie video streaming it works fine on good and average network wifi3g but not working properly on slow network 2g below is the piece of code for the same also on slow network seekbar is causing an issue it moves upwards and player shows blank screenmpmovieplayercontroller player mpmovieplayercontroller alloc initplayerallowsairplay yesselfview addsubviewplayerviewplayerviewframe cgrectmake50 640 uiscreen mainscreen boundssizewidth 100 viwvideoframesizeheight 100playercontrolstyle mpmoviecontrolstyledefaultplayermoviesourcetype mpmoviesourcetypefileplayer setcontenturlnsurl urlwithstringformatm3u8aaplplayer play,['ios'] +926468,error with php mail multiple or malformed newlines found in additional header suddenly have started receiving the above error without any changes having been made to the scripthost is 1and1 i knowthe script still works fine on a different server and so my suspicion is that there must have been some server config change that has lead to this although the hosts plead ignorancethere is no information on the above error at all in google that i can find does anybody have any ideas server is running apache if that helps,['php'] +926693,android cookies reward for invites i am trying to integrate reward for invites logic what i am trying to do for this is i generate a unique url for every user when a friend clicks on the url he is directed to a page and then to the playstore on the page a cookie with the unique id is stored on the devicenote user may open the link in any browserwhen the app on the device starts i fetch for the cookies that was saved using above and if available send the same to the server where the user is easily identified and rewardedthis looked pretty straight forward however i am stuck at the point where i have to read the cookie and extract the idi read this which says it is not possible i also tried the belowlistcookie cookies new defaulthttpclientgetcookiestore getcookies if cookiesisempty systemoutprintlnnone cookies else for int i 0 i cookiessize i systemoutprintlncookie cookiesgetitostring but no luck i keep getting none cookiesmy questionsis it possible to read the cookie that was created if yes howif no any alternative on how i can achieve the above functionalitythanks for stopping by,['android'] +926710,client secretjson is empty upon download from google developer site i am trying to download the client secretjson from google api i am following the steps listed in use this wizard to create or select a project in the google developers console and automatically enable the apiin the sidebar on the left select consent screen select an email address and enter a product name if not already set and click the save buttonin the sidebar on the left select credentials and click create new client idselect the application type installed application the installed application type other and click the create client id buttonclick the download json button under your new client id move this file to your working directory and rename it client secretjsonthe client secretjson file does download but it is empty the title of the file looks like it must be the client id ending in appsgoogleusercontentcom however there is no data stored inside the file,['ruby'] +926744,fileprovider crash npe attempting to invoke xmlresourceparser on a null string this is a part of my manifestxml version10 encodingutf8manifest xmlnsandroid packagecomexampleasd androidversioncode118 androidversionname118 usessdk androidminsdkversion14 androidtargetsdkversion19 application androidnamecomexampleasdasdapplication androidallowbackuptrue androidallowtaskreparentingtrue androidthemestyleasdtheme provider androidnamecomexampleasddatabasehqcontentproviderdb androidauthoritiesourcontentproviderauthorities provider provider androidnameandroidsupportv4contentfileprovider androidauthoritiescomexampleasdfileprovider androidexportedfalse androidgranturipermissionstrue metadata androidnameandroidsupportfile provider paths androidresourcexmlfilepaths provider applicationmanifestthis is the filepaths file in rawxmlfilepathsxmlxml version10 encodingutf8paths xmlnsandroid filespath namemediapathsi download a video from internet and save it to internal storage this waypublic static boolean saveinputstreamtointernalstoragefilecontext context string filename byte datatowrite context ctx fileoutputstream fos try fos new fileoutputstreamcontextgetfilesdir fileseparator filename objectoutputstream oos new objectoutputstreamfos ooswriteobjectdatatowrite oosclose return true catch filenotfoundexception e eprintstacktrace return false catch ioexception e eprintstacktrace return false i try to use it like soprivate void playvideofromdevicewithworkaroundstring filename file newfile new filegetfilesdir filename uri contenturi fileprovidergeturiforfilegetapplicationcontext comexampleasd newfile try videofullscreensetvideouricontenturi showmediacontrols true playvideo catch exception e playvideofromnetwork at this lineuri contenturi fileprovidergeturiforfilegetapplicationcontext comexampleasd newfile i get the following errorjavalangnullpointerexception attempt to invoke virtual method androidcontentresxmlresourceparser androidcontentpmproviderinfoloadxmlmetadataandroidcontentpmpackagemanager javalangstring on a null object referenceat androidsupportv4contentfileproviderparsepathstrategyfileproviderjava560at androidsupportv4contentfileprovidergetpathstrategyfileproviderjava534at androidsupportv4contentfileprovidergeturiforfilefileproviderjava376,['android'] +926761,linker error with variable templates consider the code belowinclude iostreamtemplatetypename tt nint main nint 42 stdcout nint stdendlit compiles and links with g51 and it thisplays 42 however clang fails to link itundefined reference to nintif i initialize the template variable liketemplatetypename t t nthen clang links it too any idea whats going on is clang correct in failing to link the program and why does it work if i initialize the template variable as far as i know template variables are just syntactic sugar for template wrappers around static members so nint 42 is effectively specializing the int instance imo the code should link,['c++'] +926776,does string interpolation evaluate duplicated usage if i have a format string that utilizes the same place holder multiple times likeemailbody good morning persongetfullname blah blah blah persongetfullname would you like to play a gamedoes persongetfullname get evaluated twice or is the compiler smart enough to know these are the same value and should be evaluated once,['c#'] +926864,popover does not thisplay when opened i set up a basic example with ionic popover however when i open the popover the opacity stays at zero preventing the popover from showing i know the method openpopover is called because i receive the opened console log in my web console if i remove the opacity property from the console the popover thisplaysmy controllerangularmodulesearchcontrollersearchresultscontroller searchresultscontrollersearchresultscontrollerinject ionicpopover scopefunction searchresultscontrollerionicpopover scope var vm this vmopenpopover openpopover activate function activate ionicpopoverfromtemplateurltemplatessearchfilterpopoverhtml scope scope thenfunctionpopover consolelogpopover vmpopover popover function openpopover event consolelogopened vmpopovershowevent my view pageionview hidenavbartrue signedinheadersignedinheader ioncontent classpadding hasheader div classrow div classcol col75 textleft div4 results for 263355div div div classcol col25 textright div ngclicksearchresultsopenpopover i classicon ionarrowdownbi filter div div div ioncontent ionfooterbar ad here 1 ionfooterbarionviewmy popover templateionpopoverview ionheaderbar h1 classtitlemy popover titleh1 ionheaderbar ioncontent hello ioncontentionpopoverviewwhy does the popover not show and how can i fix this,"['javascript', 'css']" +927014,c wpf entity framework 6 synchronization databases scenarioi have two mysql databasesbig master databasesmall client database example tablesbig database usertext usernameint idvarchar loginvarchar password a lot more fieldsclient database userint idint unique api id id from mastervarchar loginvarchar passwordproblemi need to synchronize databases but i do not know how to do that in the best way i read this question but it is quite old and not cover my casei communicate with master database via rest api direct connection is not the option my synchronization algorithmdownload and deserialize data from rest api for example apiusers to list of apiuser objects public class apiuser int id string login string password public class user int id int api id string login string password iterate over list of apiusersif entity with apiuserid exist overwrite all fieldselse create new entitysave changesmy codepublic void syncuserslist apiuser apiusers using var db new dbentities apiusersforeachapiuser var dbuser dbclient wherec capi id apiuserid singleordefault if dbuser null var userobj new user api id apiuserid login apiuserlogin password apiuserpassword dbclientadduserobj else dbuserapi id apiuserid dbuserlogin apiuserlogin dbuserpassword apiuserpassword dbsavechanges questionhow to do it better i have problem with deleted entities from master database my algorithm does not cover cover this case,['c#'] +927088,anonymous method staticness different between 2013 and 2015 debug compilations i am hoping someone can identify the language feature or bug that resulted in the change in behaviour of the program below it is reproduced from a much larger scenario that was intended to log a message if the delegate supplied to orchardgo was not staticusing systemnamespace sample public static class program public static void main new apple public sealed class apple public apple orchardgo internal static class orchard public static void goaction action consolewritelineactionmethodisstatic the scenario isif i compile and run a debug build produced with visual studio 2013 the output is trueif i compile and run a debug build produced with visual studio 2015 the output is falsein both cases the target net framework is 45if i compile and run a release build produced with visual studio 2015 the output is true and thus consistent with visual studio 2013visual studio 2015 is the rc version if that mattersi can see from ildasm the 2013 generated code mod csampleexe m a and i f e s t nsp sample cls sampleapple class public auto ansi sealed beforefieldinit stf cs9 cachedanonymousmethoddelegate1 private static class mscorlibsystemaction met ctor void b 0 void cls sampleorchard class private abstract auto ansi sealed beforefieldinit stm go voidclass mscorlibsystemaction cls sampleprogram class public abstract auto ansi sealed beforefieldinit stm main void is clearly different to the 2015 generated code mod csampleexe m a and i f e s t nsp sample cls sampleapple class public auto ansi sealed beforefieldinit cls c class nested private auto ansi serializable sealed beforefieldinit custom instance void mscorlibsystemruntimecompilerservicescompilergeneratedattributector 01 00 00 00 stf 9 public static initonly class sampleapplec stf 9 0 0 public static class mscorlibsystemaction stm cctor void met ctor void b 0 0 void met ctor void cls sampleorchard class private abstract auto ansi sealed beforefieldinit stm go voidclass mscorlibsystemaction cls sampleprogram class public abstract auto ansi sealed beforefieldinit stm main void but my knowledge of il and compiler changes is not sufficient to determine whether this is a new feature or an unintended bug i can produce the full il dumps on request but can anyone tell me from the information i have supplied what is going on here and whether it is intentional why is the anonymous method considered static in 2013 but nonstatic in 2015,['c#'] +927091,in this code why do foo and thisfoo refer to different things heres the codefor var i 0 i 10 i settimeoutfunction consolelogi prints 9 10 times consolelogthisi prints 0 1 29 bindii i 10why do i and thisi refer to different thingscontrast this to a bit of code executed on the global scopevar x 5consolelogxconsolelogthisxboth will print 5here the scope was global and so was the context a variable declaration set a property of the same name on the global context on the other hand within a function scope this does not happenvar a function var x 5 consolelogx 5 consolelogthisx undefined consolelogi undefined consolelogthisi 10bindi 10aeven if we pass the global context into the local scope declaring a variable within the function does not set it as a property of the global contextvar a function var x 5 consolelogx 5 consolelogthisx undefinedbindwindowaconsolelogx undefinedconsolelogthisx undefinedwhat i am trying to say is this in the global scope a variable declaration modifies the global context but in a function scope a variable declaration does not modify the functions context no matter what the context is why,['javascript'] +927107,how to thisable sleep mode of apple watch programmatically i am developing one application for apple watch what problem i am facing is watch goes in sleeping mode after some time i want to thisable the sleep mode programmatically any solution for this thanks in advance,['objective-c'] +927240,tablayout update tab content with a custom view i am using tablayout of the new material design and i have a problem i cannot update tab content of a custom view once the tab is createdi can simplify my method inside my pageradapter withpublic view settabviewint position boolean selected view v layoutinflaterfromcontextinflaterlayoutdefault tab view null tv textview vfindviewbyidridtabtextview ifselected tvsettextselected else tvsettextunselected return vand in activity i can simplify my code withtablayout tablayout tablayout findviewbyidridtabsviewpager pager viewpager findviewbyidridviewpagerpageradapter adapter new pageradaptergetsupportfragmentmanagerpagersetadapteradaptertablayoutsetupwithviewpagerpagerfor int i 0 i tablayoutgettabcount i tablayouttab tab tablayoutgettabati view v if i 0 v adaptersettabviewi true vsetselectedtrue else v adaptersettabviewi false tabsetcustomviewvtablayoutsetontabselectedlistenernew tablayoutontabselectedlistener override public void ontabselectedtablayouttab tab adaptersettabviewtabgetposition true override public void ontabunselectedtablayouttab tab adaptersettabviewtabgetposition false override public void ontabreselectedtablayouttab tab the tabs titles are set right when the app starts but when i change tab the content still remains the same,['android'] +927294,tabhost thisplays content once oncreate i have a tabhost inside a navigationdrawer and i am facing this weird problem which occurs when ever i go from tabhost which exist as a navigation drawer item to another navigation drawer item and get back to tabhost it would not thisplay its content the first time it works perfectly but when ever i change the item and get back to it it would not thisplay the content in other word it would not load child fragments unless i closed the app and relaunch it or change the orientation recreate fragmenthow it looks first time i open it with contentafter going to another navdrawer item and return to tabhosttabhost fragmentimport androidcontentcontextimport androidosbundleimport androidsupportv4appfragmentimport androidsupportv4appfragmentactivityimport androidsupportv4appfragmentpageradapterimport androidsupportv4viewviewpagerimport androidviewlayoutinflaterimport androidviewviewimport androidviewviewgroupimport androidwidgettabhostimport androidwidgettabwidgetimport javautilarraylistimport infofdsemiratesrpublic class myfragment extends fragment private tabhost mtabhost private viewpager mviewpager private tabsadapter mtabsadapter public myfragment override public void oncreatebundle instance superoncreateinstance override public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate view v inflaterinflaterlayoutfragment main container false mtabhost tabhost vfindviewbyidandroidridtabhost mtabhostsetup mviewpager viewpager vfindviewbyidridpager mtabsadapter new tabsadaptergetactivity mtabhost mviewpager return v override public void onresume superonresume here we load the content for each tab mtabsadapteraddtabmtabhostnewtabspecincidentsetindicatorincident pageonefragmentclass null mtabsadapteraddtabmtabhostnewtabspecservice requestsetindicatorservice request pagetwofragmentclass null public static class tabsadapter extends fragmentpageradapter implements tabhostontabchangelistener viewpageronpagechangelistener private final context mcontext private final tabhost mtabhost private final viewpager mviewpager private final arraylisttabinfo mtabs new arraylisttabinfo static final class tabinfo private final string tag private final class clss private final bundle args tabinfostring tag class class bundle args tag tag clss class args args static class dummytabfactory implements tabhosttabcontentfactory private final context mcontext public dummytabfactorycontext context mcontext context public view createtabcontentstring tag view v new viewmcontext vsetminimumwidth0 vsetminimumheight0 return v public tabsadapterfragmentactivity activity tabhost tabhost viewpager pager superactivitygetsupportfragmentmanager mcontext activity mtabhost tabhost mviewpager pager mtabhostsetontabchangedlistenerthis mviewpagersetadapterthis mviewpagersetonpagechangelistenerthis public void addtabtabhosttabspec tabspec class clss bundle args tabspecsetcontentnew dummytabfactorymcontext string tag tabspecgettag tabinfo info new tabinfotag clss args mtabsaddinfo mtabhostaddtabtabspec notifydatasetchanged override public int getcount return mtabssize override public fragment getitemint position tabinfo info mtabsgetposition return fragmentinstantiatemcontext infoclssgetname infoargs public void ontabchangedstring tabid int position mtabhostgetcurrenttab mviewpagersetcurrentitemposition public void onpagescrolledint position float positionoffset int positionoffsetpixels public void onpageselectedint position unfortunately when tabhost changes the current tab it kindly also takes care of putting focus on it when not in touch mode the jerk this hack tries to prevent this from pulling focus out of our viewpager tabwidget widget mtabhostgettabwidget int oldfocusability widgetgetdescendantfocusability widgetsetdescendantfocusabilityviewgroupfocus block descendants mtabhostsetcurrenttabposition widgetsetdescendantfocusabilityoldfocusability public void onpagescrollstatechangedint state pageonefragmentpublic class pageonefragment extends fragment override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate override public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate return inflaterinflaterlayoutpageone fragment container false override public void onactivitycreatedbundle savedinstancestate superonactivitycreatedsavedinstancestate override public void onattachactivity activity superonattachactivity override public void onstart superonstart override public void onresume superonresume pagetwofragmentpublic class pagetwofragment extends fragment override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate override public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate return inflaterinflaterlayoutpagetwo fragment container false override public void onactivitycreatedbundle savedinstancestate superonactivitycreatedsavedinstancestate override public void onattachactivity activity superonattachactivity override public void onstart superonstart override public void onresume superonresume note after debugging i notice that oncreateview in pageonefragment and pagetwofragment is not executedso what is happening and why the tabhost does not load its content after navigating to another itemeditafter hours of painful debugging i found that my code never execute the fallowing method on the second call which isoverride public fragment getitemint positionnever get executed after the second call tabinfo info mtabsgetposition return fragmentinstantiatemcontext infoclssgetname infoargs how could i solve thisany help is truly appreciatedthanks in advance,"['java', 'android']" +927347,how to update the httpconfiguration after the owin testserver creation the http configuration is setup in te startup class usually which is bound to the create methodbut what if i want to start an owin server one time for all tests but update its http configuration depending on each test needsthis is not possible the server object has nothing usefulusing var server testservercreatestartup var data serverhttpclientgetasyncapidatawhat i want to do for crud integration tests is stub the service methods do it one time fall all testswebapiconfigregisterconfigwebservicesconfigregisterconfig do it individually for each test update di registerations with fake components per test methodvar builder new containerbuildervar mockcontext new mocktgbcontextvar mockservice new mockschoolyearservicemockcontextobject mockservicesetuptaskienumerableschoolyeardtoc cgetschoolyearsasyncreturnstaskfromresultenumerableemptyschoolyeardto builderregisterinstancetgbcontext no need for this it works without registering the ctor parameter dependency builderregisterinstanceschoolyearservicemockserviceobjectbuilderupdateautofacwebapidependencyresolverconfigdependencyresolvercontainer as icontainerat the moment i am forced to create a testserver per test methodthats a total overhead in timesolutionmake the httpconfiguration static and this code should workvar builder new containerbuildervar mockcontext new mocktgbcontextvar mockservice new mockschoolyearservicemockcontextobjectmockservicesetuptaskienumerableschoolyeardtoc cgetschoolyearsasyncreturnstaskfromresultenumerableemptyschoolyeardto builderregisterinstanceschoolyearservicemockserviceobjectbuilderupdateautofacwebapidependencyresolverconfigurationdependencyresolvercontainer as icontainer,['c#'] +927357,how to do error handling with easynetq rabbitmq i am using rabbitmq in c with the easynetq library i am using a pubsub pattern here i still have a few issues that i hope anyone can help me withwhen there is an error while consuming a message it is automatically moved to an error queue how can i implement retries so that it is placed back on the originating queue and when it fails to process x times it is moved to a dead letter queueas far as i can see there is always 1 error queue that is used to dump messages from all other queues how can i have 1 error queue per type so that each queue has its own associated error queuehow can i easily retry messages that are in an error queue i tried hosepipe but it justs republishes the messages to the error queue instead of the originating queue i do not really like this option either because i do not want to be fiddling around in a console preferably i would just program against the error queueanyone,['c#'] +927582,gcc emits vastly different code using marchnative on similar architectures i am working on writing an opencl benchmark in c currently it measures the fused multiplyaccumulate performance of both a cl device and the systems processor using c code the results are then cross checked for accuracyi wrote the native code to take advantage of gccs auto vectorizer and it works however i have noticed that gcc has some odd behavior with the marchnative flagthis is my loopdefine buffer size sqrt 4096define squaren n ndefine rounds per iteration 48static float cpu result matrixconst float a const float b const float c float res aligned alloc16 squarebuffer size sqrt sizeoffloat const unsigned buff size squarebuffer size sqrt const unsigned round cnt rounds per iteration float lres forunsigned i 0 i buff size i lres 0 forunsigned j 0 j round cnt j lres ai bi ci bi lres bi ci ai ci lres ci ai bi ai resi lres return reswhen i compile with marchnative ofast on a broadwell system i get nice vectorized avx codel19 vmovups ymm0 ymmword ptr rcxrdx mov eax 48 vmovups ymm2 ymmword ptr rdirdx vaddps ymm1 ymm0 ymm5 vmovups ymm3 ymmword ptr rsirdx vaddps ymm4 ymm2 ymm5 vmulps ymm1 ymm1 ymm2 vfmadd132ps ymm4 ymm1 ymm0 vaddps ymm1 ymm3 ymm5 vmulps ymm0 ymm2 ymm0 vmulps ymm0 ymm0 ymm1 vfmadd132ps ymm4 ymm0 ymm3 vmovaps ymm1 ymm4 vxorps xmm0 xmm0 xmm0 p2align 410 p2align 3compiling with the same flags on a piledriver system emits sse2 instructions but no avx instructions even though the architecture supports it i will clarify my title here by saying that broadwell and piledriver are nothing alike but they both support similar vector instruction set extensions so the emitted code should be similarl19 mov eax 48 movups xmm0 xmmword ptr rcxrdx movups xmm2 xmmword ptr r130rdx movaps xmm4 xmm0 movaps xmm1 xmm2 movups xmm3 xmmword ptr rsirdx addps xmm4 xmm5 addps xmm1 xmm5 mulps xmm4 xmm2 mulps xmm1 xmm0 mulps xmm0 xmm2 addps xmm1 xmm4 movaps xmm4 xmm1 mulps xmm4 xmm3 addps xmm3 xmm5 mulps xmm0 xmm3 addps xmm4 xmm0 pxor xmm0 xmm0 movaps xmm1 xmm4 p2align 410 p2align 3i can even compile the whole project with marchbroadwell and run it on the piledriver system and it works with a 100 performance gaini am compiling with gcc 510 and ftreevectorizerverbose does not seem to work anymore so the compilers behavior is quite opaque i have not found any information about the flag being deprecated so i am not sure why it does not work anymore and i would really like to figure out what gcc is doingthe whole project is here,['c'] +927706,when to use a mock v stub or neither i have been reading up on mocks and stubs their differences and uses i am still a bit confused but i think i have got the jist of it now i am wondering about applications i can see the use in creating fake objects in testing scenarios where the actual objects are too complicated to haul around to test one aspect but let us consider my application i am working on a computational geometry library our library defines points lines linesegments vectors polygons and polyhedra along with a bunch of other objects and all the usual geometric operations any given object is stored as a list of points or directions or lower level objects but none of these objects takes more than a few milliseconds to generatewhen i am testing this library does it make sense to use mocksstubs anywhereright now we just use particular test cases were calling them stubs but i do not think they meet the technical definition of a stub what do you think better vocab for that would be testcases examplessourcecode edit note that were striving for immutability in all our geometry objects so it only makes sense to test the results of operations but not state changes to the initial objects,['c#'] +927710,rails 4 no manifestjson after assets precompile on production server here is the appassets for a rails 42 appthere are 3 bootstraps js and css files after deploying to production ubuntu 121 assets precompile was done on server deployed under suburirails envproduction bundle exec rake assetsprecompile rails relative url rootmysuburihere is the productionrb configcache classes true configeager load true configconsider all requests local false configaction controllerperform caching true configserve static files false envrails serve static filespresent configassetscompress true configassetsjs compressor uglifier configassetscompile false configassetsdigest true configlog level debug configi18nfallbacks true configactive supportdeprecation notify configlog formatter loggerformatternew configactive recorddump schema after migration falsehere is the head of applicationcscssimport bootstrapmincssimport bootstrapthememincssimport simple formcscssimport user menuscscssin applicationjs it has require bootstrapminhere is the output of ls for publicassets on production serverapplication05cf37813d76c2bd659271403789374cc118f1a4e616ec220969577b79ff6514cssapplication375b4b5d8fc285716f4fdca966aa960912efe8292242df8f1a60b99d5caa4b02jsauthentifybanquet coursexbanquetxbiz workflowxcommonxglyphiconshalflingsregular5d234508037dc13a419ef6ce48f3fc73dbb477f1a162c052b872182b494e626esvgglyphiconshalflingsregularbd18efd3efd70fec8ad09611a20cdbf99440b2c1d40085c29be036f891d65358ttfglyphiconshalflingsregularf495f34e4f177cf0115af995bfeb3fcabc88502876e76fc51a4ab439bc8431eotglyphiconshalflingsregularfc969dc1c6ff531abcf368089dcbaf5775133b0626ff56b52301a059fc0f9e1ewoffjqueryuisearchxstate machine logxuser manualxuser menus7c46e17f4172c2a954eeaf85e80b4e030d1ed0fb3927288bbe07eeb4fb8cbfc5cssby comparing with other rails app it is missing manifestjson under assets we tried various config options in configenvironmentproductionrb with no avail the only option works on production server is live compilation of configassetscompile true not recommended what is wrong with our code to cause assets precompile failingupdate we have rebuilt the rails app from ground up and the assets problem remains the same this assets precompile issue may have nothing to do with setup in configproductionrb and configinitializersaseetsrb as we suspect rolling back version of bundler and rake did not help the same bootstrap css and js files have been used in another rails 42 app running on the same production server without the problem,['ruby-on-rails'] +927744,how can i be notified when a snackbar has thismissed itself i am using a snackbar from the comandroidsupportdesign20 library i am using it to undo deletions to make my life easier i am going to make the ui look like things are actually deleted from the data source and if the undo button in the snack bar is not pressed actually perform the deletions from the data source so i want to know when the snackbar is no longer visible so it is safe to delete the items i can call getview on the snackbar but i am not sure what listener i should be using i tried setonsystemuivisibilitychangelistener but that did not work i believe it is only for the system status bar additionally snackbar can not be extended as it has a private constructor,['android'] +927753,pandas add multiple empty columns to dataframe this may be a stupid question but how do i add multiple empty columns to a dataframe from a listi can dodfb nonedfc nonedfd nonebut i cannot dodfb c d nonekeyerror b c d not in index,['python'] +927892,choosing a tsdb for oneoff smarthome installation i am building a oneoff smarthome data collection box it is expected to run on a raspberrypiclass machine 1g ram handling about 200k data points per day each a 64bit int weve been working with vanilla mysql but performance is starting to crumble especially for queries on the number of entries in a given time intervalas i understand it this is basically exactly what timeseries databases are designed for if anything the unusual thing about my situation is that the volume is relatively low and so is the amount of ram availablea quick look at wikipedia suggests opentsdb influxdb and possibly blueflood opentsdb suggests 4g of ram though that may be for highvolume settings influxdb actually mentions sensor readings but i cannot find a lot of information on what kind of resources are requiredokay so heres my actual question are there obvious red flags that would make any of these systems inappropriate for the project i describei realize that this is an invitation to flame so i am counting on folks to keep it on the bright and helpful side many thanks in advance,['mysql'] +927896,scope in javascript acting weird object are passed with their reference in javascript meaning change in that object from any where should be reflectedin this case the expected output was for consolelogafunction changeab ax added a bassigning a as to babchangeabconsoleloga expected but output xaddedconsolelogbwhat is happening here it should not be because of functional scope as far as i knowthank you,['javascript'] +927913,php session is randomly lost and cant understand why i paid a programmer to make a shop basket script to work with spreadshirt api everything is working perfectly except that the basket keeps emptying itself i think the session is lost at some point so the script creates another basketidi tried to find if there was a specific reason it was happening without any success i cannot reproduce the bug it just happens randomly without any reason closing the browser resetting apache or even the whole webserver would not provoke session losti have got two different scripts working with cookies on the same domain and they do not have any problem one is a cookie for the admin login session and the other cookie is to save the users last viewed articles on the shopi tried all solutions found on google without any success editing phpini forcing ini settings through php tried the htaccess way heres the sessions part of my phpinfo shopajaxphp session handling line 18ini setsessioncookie domain mywebsitecom headerpragma nocacheheadercachecontrol nostore nocache maxage0 mustrevalidatelanguage addslashes getlshopid addslashes getshop if serverhttp x requested with xmlhttprequest dieno direct access allowed ifsession id lifetime60 60 24 365 domain mywebsitecom session set cookie paramslifetimedomain session start configurationconfigshopsource comconfigshopid shopidconfigshopkey configshopsecret add an article to the basketif isset postsize isset postappearance isset postquantity create an new basket if not exist if isset sessionbasketurl get shop xml stringapiurl configshopsourceapiv1shops configshopid stringxmlshop oldhttprequeststringapiurl null get if stringxmlshop0 diestringxmlshop objshop new simplexmlelementstringxmlshop if is objectobjshop diebasket not loaded create the basket namespaces objshopgetnamespacestrue basketurl createbasketnet objshop namespaces sessionbasketurl basketurl sessionnamespaces namespaces get the checkout url checkouturl checkout sessionbasketurl sessionnamespaces basket language workaround if languagefr if strstrcheckouturlfr checkouturl str replacespreadshirtcomspreadshirtcomfrcheckouturl sessioncheckouturl checkouturl workaround for not having the appearance id if postappearance0 stringapiarticleurl configshopsourceapiv1shops configshopidarticlesintval postarticlefulldatatrue stringxmlarticle oldhttprequeststringapiarticleurl null get if stringxmlarticle0 diestringxmlarticle objarticleshop new simplexmlelementstringxmlarticle if is objectobjarticleshop diearticle not loaded postappearance intvalobjarticleshopproductappearanceid article data to be sent to the basket resource data array articleid intval postarticle size intval postsize appearance intval postappearance quantity intval postquantity shopid configshopid add to basket addbasketitem sessionbasketurl sessionnamespaces data basketdata preparebasket echo json encodearrayc arrayu sessioncheckouturlq basketdata0l basketdata1 no call just read basket if not emptyif isset getbasket if array key existsbasketurl session empty sessionbasketurl basketdata preparebasket echo json encodearrayc arrayu sessioncheckouturlq basketdata0l basketdata1 else echo json encodearrayc arrayu q 0l function preparebasket intinbasket0 if isset sessionbasketurl basketitemsgetbasket sessionbasketurl ifemptybasketitems foreachbasketitemsbasketitemsbasketitem as item intinbasket itemquantity l pq parse url sessioncheckouturl if preg matchbasketid09afi pqquery l pqquery return arrayintinbasketl additional functionsfunction addbasketitembasketurl namespaces data global config basketitemsurl basketurl items basketitem new simplexmlelementxml version10 encodingutf8 standaloneyes basketitem xmlnsxlink xmlns quantity dataquantity quantity element id dataarticleid typesprdarticle xlinkhrefconfigshopsourceapiv1shops datashopid articles dataarticleid properties property keyappearance dataappearance property property keysize datasize property properties element links link typeedit xlinkhrefhttp datashopid spreadshirt configshopsourcea dataarticleid link typecontinueshopping xlinkhrefhttp datashopidspreadshirtconfigshopsource links basketitem header array header createauthheaderpost basketitemsurl header contenttype applicationxml result oldhttprequestbasketitemsurl header post basketitemasxmlfunction createbasketplatform shop namespaces basket new simplexmlelementbasket xmlnsxlink xmlns shop id shopid basket attributes shopbasketsattributesnamespacesxlink basketsurl attributeshref header array header createauthheaderpost basketsurl header contenttype applicationxml result oldhttprequestbasketsurl header post basketasxml basketurl parsehttpheadersresult location return basketurlfunction checkoutbasketurl namespaces basketcheckouturl basketurl checkout header array header createauthheaderget basketcheckouturl header contenttype applicationxml result oldhttprequestbasketcheckouturl header get checkoutref new simplexmlelementresult refattributes checkoutrefattributesnamespacesxlink checkouturl stringrefattributeshref return checkouturl functions to build headersfunction createauthheadermethod url global config time time 10 data method url time sig sha1data configshopsecret return authorization sprdauth apikeyconfigshopkey datadata sigsigfunction parsehttpheadersheader headername retval array fields explodern preg replacex0dx0ax09x20 header foreachfields as field if preg match headername m field match return match2 return retvalfunction getbasketbasketurl header array basket if emptybasketurl header createauthheaderget basketurl header contenttype applicationxml result oldhttprequestbasketurl header get basket new simplexmlelementresult return basketfunction oldhttprequesturl header null method get data null len null switch method case get ch curl initurl curl setoptch curlopt http version curl http version 1 1 curl setoptch curlopt returntransfer true curl setoptch curlopt header false if is nullheader curl setoptch curlopt httpheader header break case post ch curl initurl curl setoptch curlopt http version curl http version 1 1 curl setoptch curlopt returntransfer true curl setoptch curlopt header true curl setoptch curlopt httpheader header curl setoptch curlopt post true not createbasket but addbasketitem curl setoptch curlopt postfields data break result curl execch curl closech return resultthere is also 2 other parts of the script a form to add a sample tshirt to the basket examplephp and a script to call the ajax shopcontrollerjs can post it if needed but there is no session handling stuffupdate maybe the problem is not related to sessions the basketid is lost but phpsessid stays the same in the browser cookiesi did the following tests for the last 3 days tested with diferent computers and browsersempty browser cookies then start a new session during the afternoonadd 1 item to basket i write down the basketid and check the browsers cookies to write down the phpsessidusually always around midnight the basket empty itselfphpsessid stays the same in my browser cookies even after basket empty itselfhowever the basketid is not the same the one used during the afternoon is lost and a new one is regeneratedserver is centos 59 php version 529 from ovh dedicated server on a dedicated ip,"['javascript', 'php']" +927924,cgaffinetransforms performance is really slow on ios 7 at the moment i am creating some transitions and transform via cgaffinetransform for a panning view and i am running in troubles because of the transform performance under ios 7 and an iphone 4i dived in istruments and logged the stuff and the heavy lifting is done when i am applying my transforms to the viewcurrent implementationfunc handlepanrecognizer uipangesturerecognizer let drawerlocation recognizerlocationinviewdrawerview let locationinview recognizerlocationinviewcontainerview let progressmax containerviewframeheight 40 20 ifrecognizerstate changed let offsetdrag dragstartpositiony locationinviewy let progress floatoffsetdrag progressmax ifoffsetdrag 0 let positiontransform cgaffinetransformmaketranslation0 containerviewboundsheight 40 20 cgfloatnormalizedprogress viewwithtransformtransform positiontransform really bad performance here else reset the transition workaround for ios 7func handlepanrecognizer uipangesturerecognizer let drawerlocation recognizerlocationinviewdrawerview let locationinview recognizerlocationinviewcontainerview let progressmax containerviewframeheight 40 20 ifrecognizerstate changed let offsetdrag dragstartpositiony locationinviewy let progress floatoffsetdrag progressmax ifoffsetdrag 0 if uidevicecurrentdevicesystemmajorversion 7 let positiontransform cgaffinetransformmaketranslation0 containerviewboundsheight 40 20 cgfloatprogress viewwithtransformtransform positiontransform really bad performance here else viewwithtransformframe cgrectmake0 containerviewboundsheight 40 20 cgfloatprogress drawerviewframesizewidth drawerviewframesizeheight works like a charm on ios 7 else reset the transition questionwhy is the performance so bad on ios 7 and my iphone 4 with cgaffinetransforms because it is doing the same thing with the offset then the frame setting in the workaround when i use uiviewanimatewithduration with transform it is performing on 60fps what can i do not to rewrite the whole implementation on my ios 7 basisupdate 28th julyfound out that autolayout is possible involved in this issue here is a timeprofiler stack from my current callsnow i am facing a big problem in my current implementation because i rely on autolayout whats the easiest solution to solve this hassle on ios 7,"['ios', 'objective-c']" +927928,warn if another typedefd name of a type is used in an argument list consider a large project where many types are typedefd egtypedef int agetypedef int heightand some functions getting arguments of those typesvoid printpersonage a height h printfage d height dn a his there a way to warn at compile time if those arguments are of the wrong type egage a 30height h 180printpersonh a no warning because a and h are both integers does gcc or some static code analysis tool have an option to warn in such cases,['c'] +927954,why does not javascript get its own thread in common browsers not enough that javascript is not multithreaded apparently javascript does not even get its own but shares a thread with a load of other stuff even in most modern browsers javascript is typically in the same queue as painting updating styles and handling user actionswhy is thatfrom my experience an immensely improved user experience could be gained if javascript ran on its own thread alone by js not blocking ui rendering or the liberation of intricate or limited message queue optimization boilerplate yes also you webworkers which the developer has to write themselves to keep the ui responsive all over the place when it really comes down to iti am interested in understanding the motivation which governs such a seemingly unfortunate design decision is there a convincing reason from a software architecture perspective,['javascript'] +927959,aspnetsession layout renderer not working i am using nlog for logging in my aspnet 45 website i have used nlog 40 now i need to use session variables in my logs so i tries to use aspnetsession layout renderer this layout renderer is included in nlogweb i have added this dll and also under the extensions tag in nlog config file but it gives the following errorargumentexception layoutrenderer cannot be found aspnetsessioni have also added nlogextended dll and also under the extensions tag in nlog config file but it also did not helpplease let me know what should i do,['asp.net'] +927994,save functions order in phpdoc i am running phpdoc on my project and there is a file the only meaningful file in which the order of methods is important for grouping methods how can i have the same order of functions in the generated documentation as in the source fileactually i am ready to change doc framework if it helps,['php'] +928041,resizing with gd outputs black images what can cause php gd to produce a black image after resizing the following code always outputs a black image for every valid jpeg filephpfilename testjpgpercent 05headercontenttype imagejpeglistwidth height getimagesizefilenamenewwidth width percentnewheight height percentthumb imagecreatetruecolornewwidth newheightsource imagecreatefromjpegfilenameimagecopyresizedthumb source 0 0 0 0 newwidth newheight width heightimagejpegthumbimagedestroythumboutput of gd info array gd version bundled 210 compatible freetype support 1 freetype linkage with freetype t1lib support gif read support 1 gif create support 1 jpeg support 1 png support 1 wbmp support 1 xpm support xbm support 1 jismapped japanese font support the code appeared working in other environments probably it is related to os installed packages libraries etc,['php'] +928046,getting facebook session on wordpress backgroundwe have a wordpress site that requires a special kind of facebook authentication the wp site needs to authenticate a user with a different app and then log the user into the app the web app is built by us and it has an api that the wp site uses to interact with it before we all get rowdy this whole authentication process works using a normal login form using the api we can easily see that the user is or is not logged into the app and thisplay that on the wp siteproblemas stated we need facebook authentication i am using facebooks php sdk v4 and have it built into a custom plugin so as to keep the code seperate from the theme when a user clicks on the fb icon it shows the popup with the correct redirect url after a while this popup closes but there is nothing in the result a few well placed var dumps reveal that i am not getting anything back from facebookredirectloginhelper this means i cannot get the session which in turns means no user infocodeas stated i have created a plugin nssocialphp which handles everything here is that file plugin name ns social plugin require once nssocialinitphprequire once nscallbackfunctionsphprequire once nsfacebookphp fb nulladd actionplugins loadedload fbfunction load fb global fb fb new wp facebook social login check function get fb url global fb return fblogin urlnssocialinitphp starts a session that fb can use any functions that are required during initialisation of wordpress or this plugin add actionplugins loaded start sessionfunction start session if session id session start nscallbackfunctionsphp contains all the callback functions for the redirects these are all shortcodes that are placed in pages so the url will be wsitecomfacebookcallback and that page will only have facebookcallback in it which will handle the requestadd shortcodefacebook callback facebook callbackfunction facebook callback global fb if isset geterror if geterror access denied echo script ifwindowopener null windowclose script exit session fbget session userarr fbget user username userarrfirst name usersurname userarrlast name useremail userarremail userverified userarrverified sessionregisteruser user sessionregistertype facebook action dievar dump sessiontrue if user existsuseremail action login wp redirecthome urlsocialregister actionand last but not least my nsfacebookphp fileuse facebookfacebookredirectloginhelperuse facebookfacebooksessionuse facebookfacebookrequestclass wp facebook var helper var session var permissions var loginurl public function construct initialize the sdk facebooksessionsetdefaultapplication0appid145 00hahaitsmysecret23523 thispermissions public profile email thishelper new facebookredirectloginhelperhome urlfacebookcallback thisloginurl thishelpergetloginurlthispermissions returns the login url return string public function login url return thisloginurl returns the current users info as an array public function get usersession null ifemptysession session thissession ifsession retrieve users profile information graph api to request user data request new facebookrequestsession get me response requestexecute get response as an array user responsegetgraphobjectasarray return user return false public function get session try thissession thishelpergetsessionfromredirect catchfacebookrequestexception ex when facebook returns an error catchexception ex when validation fails or other local issues if thissession return thissession what have i triedi have gone through quite a few questions on so what i have noticed is when i first run the page my fbrlh state in my session is abcdef for example but when i get a response after clicking the login button my fbrlh state is xyz i do not know if this has an effect on the outcome if it could how would i use this state i do not set it i am assuming that the fb sdk doestldrfb php sdk v4 is not sending back anything when i use facebookredirectloginhelper why would it do this and how do i fix it,['php'] +928052,does the c standard specify stl implementation details for the compiler while writing an answer to this question i faced an interesting situation the question demonstrates the scenario where one would want to put a class in an stl container but fails to do so because of a missing copy constructormove constructorassignment operator in this particular case the error is triggered by stdvectorresize i made a quick snippet as a solution and saw another answer that had provided a move constructor instead of an assignment operator and copy constructor as i had what was interresting that the other answer did not compile in vs 2012 while clanggcc were happy with both approachesfirst clang and gcc are happy with this one vs 2012 is notinclude memoryinclude vectorclass fooimpl class foo stdunique ptrfooimpl myimplpublic foo foo f myimpl stdmove fmyimpl foo fooint main stdvectorfoo testvec testvecresize10 return 0second clanggccvs2012 are all happy with thisinclude memoryinclude vectorusing namespace stdclass fooimpl class foo unique ptrfooimpl myimplpublic foo foo fooconst foo foo what to do with the pointer foo operator const foo foo if this foo what to do with the pointer return this int mainint argc char argv vectorfoo testvec testvecresize10 return 0to understand what was happening i looked at the stl sources in vs 2012 and saw that it really was invoking the move assignment operator so that is why my sample worked i do not have a linux machine accessible to understand what is going on in clanggcc and the other did not since it had only the move copy constructorso this created the following question can the compiler freely decide how to implement stl methods in this case stdvectorresize since radically different implementations could cause nonportable code or is this simply a vs 2012 bug,['c++'] +928136,android button drawable tint is it possible to tint the drawableleft in an android button i have a black drawable i would like to tint white i know how to achieve this with an image view image on the left but i want to do this with the default android buttonmy source codebutton androidlayout heightwrap content androidlayout width0dp androidlayout weight1 androidtextstringdrawer quizzes androidbackgroundtintcolormd light green 500 androidstatelistanimatornull androidtextcolorf androidtextsize12dp androidfontfamilysansserif androiddrawableleftdrawableic action landscape androidgravityleftcenter vertical androiddrawablepadding8dp is there any way to tint the button or is there a custom view method to achieve this effect,['android'] +928139,how can i show verbose pytest diffs without verbose test progress pytests verbose option is required to show full diffs on assertion failures but this also thisplays the full name of each test during execution which is noisyi would like full diffs to show when an assertion fails but i only want single s to appear when the tests are running is there a way to do this,['python'] +928144,caches of all versions of a webapp deployed in parallel are shutdowned i use ehcache in a webapp whose versions are deployed in parallel on a tomcat instance this is a handy way to deploy new versions without stopping an applicationi however have a problem with this way to proceed even if i give the cache and thisk store different names depending on the versions of the webapp all caches are stopped when stopping one instancemy config is xml version10 encodingutf8ehcache xmlnsxsi xsinonamespaceschemalocationehcachexsd namemywebaprojectversion build buildnumberdefaultcache maxelementsinmemory10 maxelementsonthisk10 eternalfalse timetoliveseconds300 timetoidleseconds300 overflowtothisktrue thiskpersistentfalse memorystoreevictionpolicylru statisticstruecache maxelementsinmemory10 maxelementsonthisk10 nameorghibernatecacheinternalstandardquerycache eternalfalse timetoliveseconds300 timetoidleseconds300 overflowtothisktrue thiskpersistentfalse statisticstruecache nameorghibernatecachespiupdatetimestampscache maxelementsinmemory10 maxelementsonthisk10 timetoliveseconds300 timetoidleseconds300 eternalfalse overflowtothisktrue thiskpersistentfalse statisticstruecache namequerypresences maxelementsinmemory100 maxelementsonthisk10 eternalfalse timetoliveseconds300 timetoidleseconds300 overflowtothisktrue thiskpersistentfalse statisticstruethiskstore pathjavaiotmpdirmywebaprojectversion build buildnumber ehcacheprojectversion and buildnumberbeing replaced by maven during the build processdoes someone know how to avoid this unwanted behaviour i am using ehcachecore243 and hibernateehcache438,['java'] +928181,changing timezone on azure web apps does not work for datetimeoffsetnow according to multiple postings microsoft enabled the ability to use an application setting website time zone to control the timezone of the web server to try this i set this value to eastern standard time which is my local time zoneon an aspnet mvc razor page i added the following codedatetimenow datetimenowdatetimeoffsetnow datetimeoffsetnowdatetimeutcnow datetimeoffsetutcnowwhen i ran this last night at 51007pm eastern standard time it gave the following outputdatetimenow 6182015 51007 pmdatetimeoffsetnow 6182015 51007 pm 0datetimeutcnow 6182015 91007 pmas you can see the setting correctly allowed datetimenow to return the correct value in my timezone rather than utc like azure websitesweb apps usually do datetimeutcnow has always returned the correct value for obvious reasonshowever datetimeoffsetnow returns the local time but with an offset of 0 almost as if the clock was changed rather than the timezone this occurs even though the documentation says emphasis minegets a datetimeoffset object that is set to the current date and time on the current computer with the offset set to the local times offset from coordinated universal time utcso what is happening that the website time zone setting impacts datetimenow but it does not impact datetimeoffsetnow and is there any way i can get around thatas a point of clarification i do not really want to change the time zone on the server we are working on a proper timezone independent solution but i am still curious why this happens the way it does,"['c#', 'asp.net']" +928330,is there any way to detect ios 9 low power mode programmatically i know the user can detect low power mode by observing the colour of the battery icon but is there an api call that allows a program to detect low power mode,['ios'] +928353,flasksecurity user registered signal not received in python 33 but works in 27 i am trying to use the user registered signal in order to set up default roles for users when they register using flasksecurity as in the following link setting default role in flask securityin my searches i can see that there was a bug that was already addressed for this in flasksecurity not getting signal from flasksecurity fix user registered signal problemi have tried the following to prove if the signal is received by the handler without any luckuser registeredconnect viaappdef user registered sighandlersender extra printprintuser registered sighandler extrathis however never gets called even though the user gets registered and the signal should be sent if it helps i have set the flasksecurity configuration as followsappconfigsecurity registerable trueappconfigsecurity confirmable falseappconfigsecurity send register email falseappconfigsecurity changeable trueappconfigsecurity send password change email falsesignals from flasklogin and flaskprincipal are working for me as i managed to confirm that the following code snippets successfully print when the signals are sentuser logged outconnect viaappdef on user logged outsender user printuser log out made it inuseridentity changedconnect viaappdef identity changed oksenderidentity printidentity changedidentityfor my setup i am using python 33 anaconda and using the followingflask0101flasklogin0211flaskprincipal040flasksecurity174blinker13 having looked at the signals in both flasklogin and flasksecurity i am not sure why the flasksecurity signals would not be workingeditif i add printuser registeredreceivers to a route in my app it will show that i have a receiver 139923381372400 function user registered sighandler at 0x7f42737145f0 if i put this same print statement within the registerablepy of flasksecurity just before the user registeredsendapp get current objectuseruser confirm tokentoken then it lists no receivers edit2problem appears to be related to using python 33 i created a python 27 environment and the user registered code worked as expectedfull code to reproducefrom flask import flaskrender templatefrom playhouseflask utils import flaskdbimport osfrom flaskextsecurity import security peeweeuserdatastorefrom flaskextsecuritysignals import user registeredfrom flaskextlogin import user logged outfrom peewee import from playhousesignals import modelfrom flaskextsecurity import usermixinrolemixinapp flask name appconfigadmin passwordsecretappconfigapp dirospathdirnameospathrealpath file appconfigdatabasesqliteexts ospathjoinappconfigapp dir blogdbappconfigsecret key sh secretappconfigsecurity registerable trueappconfigsecurity confirmable falseappconfigsecurity send register email falseflask db flaskdbflask dbinit appappdatabase flask dbdatabaseclass basemodelmodel class meta databaseflask dbdatabaseclass userbasemodel usermixin emailcharfield passwordcharfield active booleanfielddefaulttrue confirmed at datetimefieldnulltrue def is activeself return true def is anonymousself return false def is authenticatedself return trueclass rolebasemodel rolemixin name charfielduniquetrue description textfieldnulltrueclass userrolesbasemodel user foreignkeyfielduser related nameroles role foreignkeyfieldrole related nameusers name propertylambda self selfrolename description propertylambda self selfroledescriptionuser datastore peeweeuserdatastoredatabase user role userrolessecurity securityapp user datastoreuser registeredconnect viaappdef user registered sighandlersenderextra printprintuser registered sighandleruser logged outconnect viaappdef on user logged outsender user printuser log out made it inuserapproutedef index printuser registeredreceivers return render templatebasehtmldatabasecreate tablesuserroleuserroles safetrueapprundebugtruebasehtml templatedoctype htmlhtml head titleblogtitle head body ul if current useris authenticated lia href url forsecuritylogoutnext log outali lia href url forsecurityregister registerali else lia href url forsecurityloginnext loginali lia href url forsecurityregister registerali endif block extra header endblock ul bodyhtml,['python'] +928358,selenium webdriver firefox dynamically thisable javascript i know i can use firefox profiles to thisable javascript for example see enablethisable javascript using selenium webdriverhowever i have a case where i need javascript to be enabled in order for me to log in to a page but then i want javascript to be thisabled after i am logged in so that when i do page source it returns the dom as if javascript has not run the key is that the login page requires javascript is it possible to dynamically control whether javascript is on or off in selenium webdriver,['javascript'] +928707,what is the proper way to validate requests with resteasy i use resteasy in combination with google guice using resteasyguice i have been looking for ways to validate my request bodies i want to do for examplepublic static class mypojo notempty private string contentsand then use in my resourcepostvalidaterequestpublic void dopostvalid mypojo mypojo use mypojo only if validi have been working with the resteasyhibernatevalidatorprovider but since i switched to newer versions this introduced the unwanted dependency to ejb see also resteasy1056 in the comments is stated that you should switch to the newer validator11 insteadswitch to resteasyvalidatorprovider11 which implements the newer bean validation 11 specificationthe docs sayvalidation is turned on by default assuming resteasyvalidatorprovider11jar is available though parameter and return value validation can be turned off or modified in the validationxml configuration file see the hibernate validator documentation for the detailsi however do not manage to get this working to my configuration because i find myself including dependencies like hibernatevalidator javaxelapi javaxel and hibernatevalidatorcdi and annotations like validateonexecution i however do not find any of this being instantiated or invalid requests being rejectedwhat is the preferred lightweight and working way to do validation with resteasy,['java'] +928763,hardware acceleration for android studio not working i am on a hp dm4 intel core i5 machine with windows 7 my android studio gives me the following error when i compile my applicationafter some googling i found that i have to install intel hardware accelerated executed manager that comes with android sdk but when i try to do that i get this errordoes this somehow relate to hardware virtualization i already have it enabled from the biosi do not understand what the problem is please helpedit i downloaded the windows hardwareassisted virtualization detection toolfrom the microsoft website and it says everything is fine this is crazy,['android'] +928798,apply material design touch ripple to imagebutton i have an imagebutton that does not respond with a touch animation when it is clicked because it is a static image unlike regular buttons on lollipop which come with the built in ripple effect i would like to add the material design ripple touch effect to the image but cannot seem to find a way to implement it i can set a color filter over the image but that is not the ripple effect an example of what i am trying to do is when you hold an album cover image in google play music and a shadow ripple moves across the image,['android'] +928865,size of boundingboxroi to track object keeps on increasing despite fixed initial size i am trying to track my hand based on the area using media flow tracker but the bounding box keeps increasing after some time it works properly for the first 10 seconds or soheres a code snippetdef mainthisplay simplecvthisplaycam kinectts bb noneimg camgetdepthfliphorizontalwhile thisplayisnotdone depth camgetdepthfliphorizontal filtered depthstretch0 180binarizedilate1 if bb is none blobs filteredfindblobs if blobs hand blobsfilterabs70 blobsarea 500 print hand if hand bb hand0boundingbox print bb if bb is not none ts filteredtrackmftrack ts img bb if ts tsdrawbb tsshowpixelvelocityrt tsdrawpath filteredshow,"['python', 'c++']" +928931,how do i get the perceived styling of a text node windowgetcomputedstyle method accepts only element nodes is there any way to reliably get the style that determines the visual representation of a text nodei realize that nodes cannot have style attributes but they certainly are styled since they inherit the parent elements styles is there perhaps a way to get all computed styles from the parent element that are relevant to the text nodes visual representationnote that wrapping the node in a span is out of the question this would affect css rules such as spannthchild or span span etc,"['javascript', 'html', 'css']" +928967,how to thisable cookies in laravel 5 i am having singlepage app made on laravel 51 i use localstorage to keep api key and i do not need cookies laravel creates two cookies for mexsrftokenlaravel sessionif i set session driver to array in my environment config laravel session cookie is no longer generatedbut i think there might be a problem with xsrftoken cookie because i found out this piece of code in verifycsrftoken middleware classpublic function handlerequest closure next if thisisreadingrequest thisshouldpassthroughrequest thistokensmatchrequest return thisaddcookietoresponserequest nextrequest throw new tokenmismatchexceptionand addcookietoresponse method looks like thisprotected function addcookietoresponserequest response config configsession responseheaderssetcookie new cookie xsrftoken requestsessiontoken time 60 120 configpath configdomain false false return responseit seems like it sets this cookie no matter what i could thisable this middleware but i want to use it to verify csrf token with http headers can i thisable cookies completely,['php'] +929004,deprecated smil svg animation replaced with css or web animations effects hover click in accordance with this topicfirefox 3840 smil problems very slow speed resolved in ff version 41 from 220915and this topicintent to deprecate smilsvg tag animatetransform does not work well it would be nice to replace smil animate tag with css or css transitionsconsole warning please use css animations or web animations insteadwhich would work fast on the latest versions of firefox and chromethe next google chrome warningconsole warning svgs smil animations animate set etc are deprecated and will be removed please use css animations or web animations insteadrevision 196823 add smil deprecation warningfor a start i need to implement three things1 hover effect on mouse overthe easiesthow it wasrect x05 y05 width1 height1 fillwhite it makes halfvisible selecting effect set attributenamestrokeopacity beginmouseover endmouseout to05 explicitly reverse the opacity animation on mouseout set attributenamestrokeopacity beginmouseout endmouseover to1recti removed the set tags added classes to the rect tag and added to this to the css hover pseudoclasselement tplhover strokeopacity 052 it scales a few times after change committed to this element pageloadhow it wasanimationit scales a few times after change committed to this element animatetransform attributetypexml attributenametransform typescale dur05s keytimes005051 values121121 repeatcount6 fillfreezehow to organize without the animate tag 3 it animates scale up and scale down onclickhow it wasit animates scale up and scale down onclick animatetransform attributenametransform attributetypexml typescale from1 to115 repeatcount1 beginmousedown02s dur 02s fillfreeze animatetransform attributenametransform attributetypexml typescale from115 to1 repeatcount1 beginmouseup04s dur 02s fillfreezehow to organize without animate tag tried to use active but there are differences in the behaviorelement tplactive transform scale11 this is the entire code of my template elementg idswitcher cursorpointer strokewidth015 g transformscale11375 g rect x05 y05 width1 height1 strokewhite pointereventsnone rect x05 y05 width1 height1 fillwhite it makes halfvisible selecting effect set attributenamestrokeopacity beginmouseover endmouseout to05 explicitly reverse the opacity animation on mouseout set attributenamestrokeopacity beginmouseout endmouseover to1 rect line x10 y1025 x20 y2025 strokewidth017 strokelinecapround pointereventsnone vertical on animation it scales a few times after change committed to this element animatetransform attributetypexml attributenametransform typescale dur05s keytimes005051 values121121 repeatcount6 fillfreeze it animates scale up and scale down onclick animatetransform attributenametransform attributetypexml typescale from1 to115 repeatcount1 beginmousedown02s dur 02s fillfreeze animatetransform attributenametransform attributetypexml typescale from115 to1 repeatcount1 beginmouseup04s dur 02s fillfreeze g ggworking version from my current working project looks like previously only used by a browser ff because pay attention hover works here with 2 figures cause chrome support smil and use together firefox does not currently support smil and use together according to robert longsonin my attempt to make the equivalent css it looks like in ff in chromeor the same for other element working versionthanksedit 1i found that this combination variant will work fine for hover and mousedown in firefox but only the hover effect works in chromei am also interested in how could i save some of these animations by transfering them to css web animations,['css'] +929101,viewpostimeinputstage action down as i am trying to debug my program i cannot figure out the error i have initialized two buttons and used setonclicklistener on them when the user clicks the buttons they are supposed to see a debug messageon logcat however i keep seeing this message appear instead whenever i click the button or if i click anywhere at all on the screen viewpostimeinputstage action down does anyone know what that message signifies or if they a solution to my problem thanks so much,['android'] +929178,php telnetssh dynamic login i have an issue that is stumped mei am trying to automate a cli login to a router and run some commands obtained via a webpage however i do not know if the router has telnet or ssh enabled might be onethe other or both and i have a list of possible usernamepassword combos that i need to try to gain accessoh and i cannot change either the protocol type or the credentials on the device so that is not really an option i was able to figure out how to login to a router with a known protocol and login credentials and run the necessary commandsincluded below but i do not know if i should use an ifelse block to work through the telnetssh decisions or if a switch statement might be better would using expect inside php be an easier way to go function tunnelruncommandsuserpass yubi cpeip 1234 commands explode exploden commands screenout ssh new net ssh2router jumphost if sshloginuser pass yubi exitlogin failed sshsettimeout2 sshwritessh l username cpeipn sshreadassword sshwritepasswordn sshread sshwriten cpeprompt sshread net ssh2 read regex cpeprompt str replacen trimcpeprompt sshwriteconfig tn foreach commands explode as i sshwritein note the n sshsettimeout2 screenout sshread sshwriteendn sshreadcpeprompt sshwriteexitn echo router update completed results belowbrbr echo div idtext outtextarea style bordernone width 700px rows20screenouttextareadivupdatethe solution i went with was a whileswitch loop i would of gone the expect route but i kept running into issues on getting the expect module integrated into php on my server windows box if i had been using a unixlinux server expect would of been the simplest way to achieve thisi just made it into a working demo for now so there are a lot of variations missing from the case statements still and errorhandling still needs to bef figured out but the basic idea is there i still want to move the preg match statements around a bit more to do the matching at the top of the while loop so i do not spam the whole case section with different preg match lines but that may prove to be more work than i want for now hope this might help someone else trying to do the same php includenetssh2php definenet ssh2 logging net ssh2 log complex ini setthisplay errors 1conn new net ssh2somewhereouttherecomif connloginuser pass yubi exitlogin failedprompt testingconnsettimeout2connwriteps1promptconnreadconnwritenscreenout connreadecho screenout is set on the shellbrbrecho login db30 login db31logged in falsestatus sshstatus prev login counter 0while logged in login counter 3 switch status case telnet break case ssh connwriten connwritessh l login dblogin counter0 cpeipn status prev status status connreadn net ssh2 read regex break case preg matchpermission denied status true false connwritechr3 sends ctrlc status connread if strstrstatus testing status ssh login counter break else break 2 case preg matchppassword status true false connwritelogin dblogin counter1 n status prev status status connreadn net ssh2 read regex break case preg matchyesno status true false connwriteyesn status prev status status connreadn net ssh2 read regex break case preg matchazaz09 statusmatches true false connwriteshow versionn status connread ifpreg matchadtranadtrancisco status truefalse logged in true break default echo brsomething done messed up exiting break 2 echo pre conngetlog preif logged in true echo br made it out of the while loop cleanly else echo br made it out of the while loop but not cleanlyecho pre conngetlog preconnthisconnectecho thisconnected cleanly,['php'] +929347,how to verify if a file is readable by humans how i can make sure that a file is readable by humansby that i essentially want to check if the file is a txt a yml a doc a json file and so on the issue is that in the case i want to perform this check file extensions are misleading and by that i mean that a plain text file that should be txt has an extension of d and various others what is the best way to verify that a file can be read by humansso far i have tried my luck with extensions as followsprivate boolean humanscanreadstring extention switch extentiontolowercase case txt case doc case json case yml case html case htm case java case docx return true default return false but as i said extensions are not as expectededit to clarify i am looking for a solution that is platform independed and without using external libraries and to narrow down what i mean human readable i mean plain text files that contain characters of any language also i dont really mind if the text in the file makes sense like if it is encoded i dont really care at this point thanks so far for all the responses d,['java'] +929349,code coverage result is not accurate to real coverage in xcode 7 i am running test cases in application with enabled code coverage data xcode 7 beta 2 but i am able to get only few files coverage data while my all test cases are running successfully some files has covered all codes by unit test cases but still showing 3 code coverage for examplethis is the result of code coverage as you can see on the right side there is an info how many times these lines of code was called during tests in this case 0buthere is a place in tests where we can see that this function was called indeed how many times oh at least once this number is delivered by info on the right sideso the code above should be marked as called and not be grayed outcan anyone explain this why does this happen,['ios'] +929388,playing video using textureview in recyclerview i am trying to implement a list with videos like vine or instagram app where they play video plays when list item is shown or fully visible and video pauses when list item gets hided i am using textureview with media player to play a video from url and added it as list item in recyclerview following is my codevideosadapter classpublic class videosadapter extends recyclerviewadaptervideosadapterviewholder context contextprivate arrayliststring urlspublic static class viewholder extends recyclerviewviewholder public linearlayout layout public textview textview public viewholderview v superv layout linearlayout vfindviewbyidridlinearlayout textview textview vfindviewbyidridtextview public videosadaptercontext context arrayliststring urls thiscontext context thisurls urls create new views invoked by the layout manageroverridepublic videosadapterviewholder oncreateviewholderviewgroup parent int viewtype create a new view view v layoutinflaterfromparentgetcontextinflaterlayoutview main parent false viewholder viewholder new viewholderv return viewholder replace the contents of a view invoked by the layout manageroverridepublic void onbindviewholderviewholder holder int position string url urlsgetposition holdertextviewsettexturl playvideoholder urloverridepublic int getitemcount return urlssizeprivate void playvideoviewholder holder string url final customvideoplayer vid new customvideoplayerstringvalueofurl context holderlayoutaddviewvid holderlayoutsetonclicklistenernew viewonclicklistener override public void onclickview v vidchangeplaystate customvideoplayer classpublic class customvideoplayer extends textureview implements textureviewsurfacetexturelistenercontext contextstring urlmediaplayer mpsurface surfacesurfacetexture spublic customvideoplayercontext context attributeset attrs supercontext attrs thiscontext contextpublic customvideoplayerstring ur context context supercontext thissetsurfacetexturelistenerthis thisurl ur thiscontext contextoverridepublic void onsurfacetextureavailablefinal surfacetexture surface int arg1 int arg2 thiss surface logdurl thisurl startvideosurfaceoverridepublic boolean onsurfacetexturedestroyedsurfacetexture arg0 return trueoverridepublic void onsurfacetexturesizechangedsurfacetexture arg0 int arg1int arg2 overridepublic void onsurfacetextureupdatedsurfacetexture arg0 public void setvideostring url thisurl urlpublic void startvideosurfacetexture t thissurface new surfacet thismp new mediaplayer thismpsetsurfacethissurface try uri uri uriparsethisurl thismpsetdatasourceurl thismpprepareasync thismpsetonpreparedlistenernew mediaplayeronpreparedlistener public void onpreparedmediaplayer mp mpsetloopingtrue mpstart catch illegalargumentexception e1 e1printstacktrace catch securityexception e1 e1printstacktrace catch illegalstateexception e1 e1printstacktrace catch ioexception e1 e1printstacktrace try catch illegalargumentexception e eprintstacktrace catch securityexception e eprintstacktrace catch illegalstateexception e eprintstacktrace try catch illegalstateexception e eprintstacktrace public void changeplaystate ifthismpisplaying thismppause else thismpstartwhen i run this code there are multiple issues in it1 first two itemsvideos buffers and play fine but when i scroll it does not load third video and first video also gets removed from the list 2 on scroll videoslist items starts buffering again for the item that was already buffered3 on fast scroll list gets too laggy and get stuck and crashesattached is the image of logcat that i get while list scroll and video playingcan anyone guide me through this what is the right way to create a list like vine app,['android'] +929452,jquerys change of isnumeric in latest versions until recent version jquery used to check if numeric via return isnan parsefloatobj isfinite obj the first part is for parsefloatd nanisnan parsefloatinfinity true but not a numberthe second part is for isfinite2 truebut in recent version they changed it and changed it to return jqueryisarrayobj obj parsefloatobj 1 0questionwhat was not good enough in the previous version that they changed it to the new one and why do they check if array,"['javascript', 'jquery']" +929459,change default aspnet identity twofactor remember cookie expire time i have been using aspnet identity 221 following is the code in post method of verifycode actionvar result await signinmanagertwofactorsigninasyncmodelprovider modelcode ispersistent modelrememberme rememberbrowser modelrememberbrowserswitch result case signinstatussuccess return redirecttoactiondashboardindex case signinstatuslockedout return viewlockout case signinstatusfailure default modelstateaddmodelerror invalid code return viewmodelwhen both modelrememberme and modelrememberbrowser is true browser remembers identity and two factor cookie for 2 weeks this is the default implementation but i only need to remember tfa for 8 hours how can i do that i have been searching for the solution since last 10 days but i have not found the solution any help would be much appreciatedfollowing is the code in my startup class it just does not take effectpublic partial class startup for more information on configuring authentication please visit public void configureauthiappbuilder app configure the db context user manager and signin manager to use a single instance per request appcreateperowincontextapplicationdbcontextcreate appcreateperowincontextapplicationusermanagerapplicationusermanagercreate appcreateperowincontextapplicationsigninmanagerapplicationsigninmanagercreate appcreateperowincontextapplicationrolemanagerapplicationrolemanagercreate string domainname stringisnulloremptyconfigdomainname configdomainname string cookiename aspnet domainname enable the application to use a cookie to store information for the signed in user and to use a cookie to temporarily store information about a user logging in with a third party login provider configure the sign in cookie appusecookieauthenticationnew cookieauthenticationoptions authenticationtype defaultauthenticationtypesapplicationcookie loginpath new pathstringaccountlogin slidingexpiration true expiretimespan timespanfromhours9 cookiedomain domainname cookiename cookiename provider new cookieauthenticationprovider enables the application to validate the security stamp when the user logs in this is a security feature which is used when you change a password or add an external login to your account onvalidateidentity securitystampvalidatoronvalidateidentityapplicationusermanager progenyuser long validateinterval timespanfromminutes30 regenerateidentitycallback manager user usergenerateuseridentityasyncmanager getuseridcallback id idgetuseridlong use a cookie to temporarily store information about a user logging in with a third party login provider appuseexternalsignincookiedefaultauthenticationtypesexternalcookie enables the application to temporarily store user information when they are verifying the second factor in the twofactor authentication process appusetwofactorsignincookiedefaultauthenticationtypestwofactorcookie timespanfromminutes5 enables the application to remember the second login verification factor such as phone or email once you check this option your second step of verification during the login process will be remembered on the device where you logged in from this is similar to the rememberme option when you log in appusetwofactorrememberbrowsercookiedefaultauthenticationtypestwofactorrememberbrowsercookie uncomment the following lines to enable logging in with third party login providers appusemicrosoftaccountauthentication clientid clientsecret appusetwitterauthentication consumerkey consumersecret appusefacebookauthentication appid appsecret appusegoogleauthentication,['c#'] +929485,jquery droppable zone in droppable zone i have a droppable unordered list named ul classdroppable inside the unordered list i have dynamicly generated list items named li classplaceholderli which are also droppablewhen dropping a draggable item between a placeholder all works fine but when dropping a draggable item on the li classplaceholderli itself the draggable item gets appended to the placeholder and the unordered listso i get a double clone of itheres a jsfiddle to have a visual example i am aware that it is logical that i get a double clone on my page but i do not know how to thisable it any help is greatly appreciatedupdate if you drag a draggable item verticaly over a droppable element they append automatically how is that possible,"['javascript', 'jquery']" +929487,phpoop how to avoid instances of the same class to access private propertiesmethods from other objects i know that private visibility in most of the oop based lenguages if not all define that privacy in a class basis meaning that instances of the same class can access private propertiesmethods of eachother now i want to prevent this and i want to know what is the best designimplementation in order to do this without having a negative performance impact for example i know that i could implement an aop and use notations but this would lead to a performance decrease since the languange engine would have to create the reflection of the class and check the annotation so basically my question is what is the best way to avoid instances of the same class to access eachother private methodspropertiesexampleclass product private prize public function constructprize this prize prize public function calculatethiscountproduct extraproduct extraproduct prize 0 how to avoid this producta new product10productb new product25productacalculatethiscountproductb,['php'] +929593,mailer error missing template hello i have problem with actionmailer when i try to execute actionrake send emaili get a error rake abortedactionviewmissingtemplate missing template user mailermailer with mailer searched in user mailerheres mymailersuser mailerrbclass usermailer actionmailerbase default from def maileruser user user mailto useremail subject test endendviewsuser mailermailerhtmlerbdoctype htmlhtml head meta contenttexthtml charsetutf8 httpequivcontenttype head body p sample mail p bodyhtmlviewsuser mailermailertexterbsample maillibtasksemails taskrakedesc send emailtask send email environment do usermailermaileruserlastdeliverendconfigenvironmentsdevelopmentrb i recommend using this line to show error configaction mailerraise delivery errors true actionmailer config configaction mailerdelivery method letter opener configaction mailerdefault url options host localhost30 configaction mailerdelivery method smtp smtp settings for gmailconfigaction mailersmtp settings address smtpgmailcom port 587 user name envgmail username password envgmail password authentication plainenable starttls auto true send email in development modeconfigaction mailerperform deliveries truei searched for the solution on stackoverflow and i tried many of the answers for the similar problem but unfortunately none of them worked for mei found solution when i add body to mailer method like def maileruser user user mailto useremail subject test body somethingendthen it does work but i would like to have a body in separate files and make it more complex with user name and other thingsif someone have a idea how to solve this problem then i would be very thankful,"['ruby-on-rails', 'ruby']" +929695,best way to read from a big csv file without loading everything to memory using javascript i am using atomelectron for building an app that has visualisations over video based on data each video has a corresponding csv file with information for each frame the videos are about 100 minutes so the files has plenty of datathe problem i am having is that it takes a couple of seconds to load and parse the file most of the time this is not a problem but i need to make playlist of parts of videos and loading the whole csv file each time a video is changed is not a viable option i been looking to file streaming options as fastcsv but i did not manage to start reading for an arbitrary part of the file edit from the fs documentation in this case the question is how can i know which byte correspond with the position i want in the fileoptions can include start and end values to read a range of bytes from the file instead of the entire file both start and end are inclusive and start at 0what do you think would be the better and most performant approach to this situationin concreteis there a way of start to read a stream from any part of a csv filedo you consider there is another storage method that would allow me to solve this problem better,['javascript'] +929709,ib designables gives strange warning when using a custom class i am trying to subclass my uibutton on my storyboard with a custom swift class that should show the button as a custom hamburger buttoni am getting this warning and not seeing the hamburger button being rendered in interface builder although it will intermittently workthe custom class is called nthamburgerbutton i do not know why the string on characters is appearing before the class nameib designables using class uibutton for object with custom class because the class ttc6cprojectname17nthamburgerbutton does not exist,['ios'] +929720,creating a wear avd i have several comments in my android wear applications which says that my app does not look good on two deviceszenwatch and sony smartwatch3 i have gathered dpi and resolution of bothzenwatch 320x320 round 278dpi 163 inchessmartwatch3 320x320 square 283dpi 16 inchesnow i am trying to run the app further than the basic emulator however there are just two configurations i can usei have tried editing it is config files with no luckin config files i could not manage to find screen size just dpi and looks like any configuration changed is ignoredthe following is all the configuration i have found interestinghwlcddensity240no screen size no resolution just lcd density which for me looks like dpi but now i am not sure so i cannot mimic any of the two above mentioned devicesany tips about thisedit 6 june 2015i cannot run the device i configuratedas you can see a yellow warning is shown which says the followingso i am not able to run any device i created,['android'] +929757,is the c compiler optimizing nullable types can anybody shed any light on why this unit test is failing in visual studio 2013testmethodpublic void inconceivable int x 0 assertareequaltypeofint xgettype,['c#'] +929867,how can i create a phpdoc for magic properties outside of the class definition phpdoc provides the var tag which should work even for variables declared outside of a classhowever this does not seem to work if i define the variable as a magic member of an object var apptranslator fortressmessagetranslator apptranslator new fortressmessagetranslatorwhere app is a slim object that supports arbitrary property assignment via magic setters and gettersi know that i could add it to slim itself via the property tag but then i would need to change the core slim code every time i create a new propertydoes phpdoc support this kind of dynamic property documenting,['php'] +929884,bootstrap 3 hide the main menu when item with sub menu is click and show sub menu i would like to have a sub menu thisplay only and hide the main menu after you click an item in the main menu that has a sub menu the tricky part is that this will only activate only in mobile but not in bigger screen i have tried only a plugin or implemented a library from below link and it had a conflict somewhere that menu does not show up i hope you could give me a new way of doing thismy menu looks like thismain menu thisplaying and when click an item with sub menu it hides the main menu and show only the sub menu div classnavbar navbardefault div classcontainer div classnavbarheader button typebutton classnavbartoggle datatogglecollapse datatargetnavbarcollapse span classiconbarspan span classiconbarspan span classiconbarspan button a classnavbarbrand href img srcassetsimgvivaldilogopng alt classimgresponsive a div div classnavbarcollapse collapse ul classnav navbarnav dlmenu li a hrefindexhtml classhomehomea li li classdropdown open a idwhoweare href datatoggledropdown classdropdowntoggle ariaexpandedtruewho we area ul classdropdownmenu img srcassetsimgmenutripng stylemargintop 18px marginleft 20px lia hrefpatient formsali li classdividerli lia hreffree consultationali li classdividerli lia hrefinsuranceali li classdividerli lia hrefour storyali li classdividerli lia hrefphysiciansali li classdividerli lia hrefstaffali li classdividerli lia hreftestimonialsali li classdividerli lia href styleborderbottomwidth 0pxthe osteopathic wayali ul li li a hrefbloghtmlservicesa li li a hrefcontacthtmlwellness centera li li a hrefcontacthtmlnews 38 eventsa li li a hrefcontacthtmlcontacta li ul div divdiv,"['jquery', 'html', 'css']" +930063,variable width height of uicollectionviewcell using autolayout with storyboard without xib here is an design issue in the app that uses autolayout uicollectionview and uicollectionviewcell that has automatically resizable width height depending on autolayout constraints and its content some textit is a uitableview list like with each cell that has it is own width height calculated separately for each row dependant on its content it is more like ios messages build in app or whatsupit is obvious that app should make use of func collectionviewcollectionview uicollectionview layout collectionviewlayout uicollectionviewlayout sizeforitematindexpath indexpath nsindexpath cgsizeissue is that within that method app cannot call func collectionviewcollectionview uicollectionview cellforitematindexpath indexpath nsindexpath uicollectionviewcell nor dequeuereusablecellwithreuseidentifieridentifier string forindexpath indexpath nsindexpath anyobject to instantiate cell populate it with specific content and calculate its width height trying to do that will result in an indefinite recursion calls or some other type of app crash at least in ios 83the closest way to fix this situation seems to copy definition of the cell into view hierarchy to let autolayout resize cell automatically like cell to have the same width as parent collection view so app can configure cell with specific content and calculate its size this should definitely not be the only way to fix it because of duplicated resourcesall of that is connected with setting uilabelpreferredmaxlayoutwidth to some value that should be autolayout controllable not hardcoded that could depend on screen width height or at least setup by autolayout constraint definition so app can get multiline uilabel intrinsic size calculatedi would not like to instantiate cells from xib file since storyboards should be todays industry standard and i would like to have as less intervention in codeeditthe basic code that cannot be run is listed bellow so only instantiating variable cellprobe not used crashes the app without that call app runs smoothlyvar oncetoken thispatch once t 0class viewcontroller uicollectionviewcontroller uicollectionviewdelegateflowlayout override func collectionviewcollectionview uicollectionview numberofitemsinsection section int int return 1 func collectionviewcollectionview uicollectionview layout collectionviewlayout uicollectionviewlayout sizeforitematindexpath indexpath nsindexpath cgsize thispatch onceoncetoken let cellprobe collectionviewdequeuereusablecellwithreuseidentifierfirst forindexpath nsindexpathforrow 0 insection 0 as uicollectionviewcell return cgsizewidth 200height 50 override func collectionviewcollectionview uicollectionview cellforitematindexpath indexpath nsindexpath uicollectionviewcell let cell collectionviewdequeuereusablecellwithreuseidentifierfirst forindexpath nsindexpathforrow 0 insection 0 as uicollectionviewcell return cell,['ios'] +930066,understanding equals method j bloch in his effective java provides a several rules for the implementation for equals method here they area reflexive for any nonnull reference value x xequalsx must return true a symmetric for any nonnull reference values x and y xequalsy must return true if and only if yequalsx returns truea transitive for any nonnull reference values x y z if xequalsy returns true and yequalsz returns true then xequalsz must return true a consistent for any nonnull reference values x and y multiple invocations of xequalsy consistently return true or consistently return false provided no information used in equals comparisons on the objects is modified a for any nonnull reference value x xequalsnull must return falsebut later in the book he mentioned socalled liskov substitution principlethe liskov substitution principle says that any important property of a type should also hold for its subtypes so that any method written for the type should work equally well on its subtypesi do not see how it ties to the equals contracts should we actually adhere to it while writing the equals implementationthe question is about implementing the method for subclasses here is the example from the bookprivate static final setpoint unitcirclestatic unitcircle new hashsetpoint unitcircleaddnew point1 0 unitcircleaddnew point0 1 unitcircleaddnew point1 0 unitcircleaddnew point0 1public static boolean onunitcirclepoint p return unitcirclecontainsppublic class counterpoint extends point private static final atomicinteger counter new atomicinteger public counterpointint x int y superx y counterincrementandget public int numbercreated return counterget and the following implementation broken violates liskov substitution principle page 40override public boolean equalsobject o if o null ogetclass getclass return false point p point o return px x py yok violates and what then i do not understand,['java'] +930248,i implemented editactionsforrowatindexpath and commiteditingstyle but no edit actions appear on the tableviewcell when swiping the cell i implemented editactionsforrowatindexpath and commiteditingstyle the swipe is working but no edit actions appear on the uitableviewcellmy implementation for editactionsforrowatindexpath and commiteditingstyle as followfunc tableviewtableview uitableview commiteditingstyle editingstyle uitableviewcelleditingstyle forrowatindexpath indexpath nsindexpath if editingstyle uitableviewcelleditingstyledelete i did some work here tableviewdeleterowsatindexpathsindexpath withrowanimation uitableviewrowanimationautomatic func tableviewtableview uitableview editactionsforrowatindexpath indexpath nsindexpath anyobject let deleteaction uitableviewrowactionstyle uitableviewrowactionstylenormal title delete handler actionuitableviewrowaction indexpathnsindexpath void in i did some work here tableviewreloaddata return deleteactionany help will be appreciated,['ios'] +930290,friend lookup exception from templateid consider the following clause in namespacememdef3if the name in a friend declaration is neither qualified nor a templateid and the declaration is a function or an elaboratedtypespecifier the lookup to determine whether the entity has been previously declared shall not consider any scopes outside the innermost enclosing namespaceis there a reason for the exception for templateid along with the qualified name for that matter is there a reason for the lookup of an unqualified name that is not a templateid to be restricted to the innermost enclosing namespace is there a specific problem or usecase that this clause solves,['c++'] +930319,random invalid viewstate error i know there are a lot of questions on this topic and i have read them alli am using iis8 net 45users randomly get an invalid viewstate error i cannot figure it out once this happens the only way they can get back into the site is to clear browser cachein my webconfig i havesystemwebmachinekey validationkeykey here decryptionkeydecrypt key is valid here validationsha1 hostingenvironment shadowcopybinassembliesfalse authentication modenone compilation targetframework451 httpruntime targetframework451 systemwebi am running on a virtual private server and i have yet to find a viewstate larger than 9kbmy application pool is set to restart at 300am once per daymy page uses update panels maybe the user is clicking back but i have seen it happen just visiting the page with no clicking backone thing i noticed is i have 3 different sites using the same application pool identity but the application pools are seperate there is no machine keys in machinexml but only in my webconfig,"['c#', 'asp.net']" +930405,background processes in nodejs what is a good aproach to handle background processes in a nodejs application scenario after a user posts something to an app i want to crunch the data request additional data from external resources etc all of this is quite time consuming so i want it out of the reqres loop ideal would be to just have a queue of jobs where you can quickly dump a job on and a daemon or task runner will always take the oldest one and process itin ror i would have done it with something like delayed job what is the node equivalent of this api,['javascript'] +930469,net core does not depend on any installation i have been reading about net core and it seems really coolthere is just one thing that is making me think and i have not read it anywhere when i set my aspnet 5 web app to target net core and deploy it this app does not depend at all on the net framework installed on the machine that is going to host iti mean the assemblies deployed already contain the clr the bcl and the project dependencies so i can have mutiple web apps hosted in one single machine with different versions of net core rightthank you,"['c#', '.net']" +930631,preventing ui flicker when loading async data in reactjs i have some data in indexeddb which can only be accessed asynchronously i want to build a reactjs ui using that data the general idea is that i will have multiple react components that load data from indexeddb and thisplay some ui based on that data and the user will be able to switch between which component is currently thisplayedmy concern is that i do not know how to elegantly accomplish this without some superfluous ui flickering i can do my asynchronous data loading in componentdidmount and put the data in thisstate but then render will be called before it is finished forcing me to either thisplay nothing or thisplay some placeholder data for a tiny fraction of a second while the data from indexeddb is retrievedi would rather have it not render until after my data from indexeddb is loaded i know it would not take long to load and i would rather the previous component continue to thisplay while the new data loads so there is just one flicker old new rather than two old blankplaceholder new this is more like how a normal web page works when you click a link from one website to another your browser does not instantly show a blankplaceholder screen while it waits for the server from the linked website to respondi am thinking i could do my data loading outside of the react component before calling reactrender and then passing it in via thisprops but that seems messy because nesting components would become tricky and some of my components will be updating over time and pulling new data from indexeddb through the exact same code that initializes them so it seems like an ideal use case for storing data in thisstate because then i could update it within the component itself when i get a signal that new data is available initialization and updating would be as easy as calling a thisloaddata function that sets some values in thisstate but then i have the aforementioned extra flickerdoes anyone have any better ideas whats the canonical solution to this problem is it really to just have millisecond blankplaceholder flickers all over the place,['javascript'] +930647,why does this for loop exit on some platforms and not on others i have recently started to learn c and i am taking a class with c as the subject i am currently playing around with loops and i am running into some odd behaviour which i do not know how to explain include stdiohint main int array10i for i 0 i 10 i arrayi0 code should never terminate printftest n printfd n sizeofarraysizeofint return 0on my laptop running ubuntu 1404 this code does not break it runs to completion on my schools computer running centos 66 it also runs fine on windows 81 the loop never terminates whats even more strange is that when i edit the condition of the for loop to i 11 the code only terminates on my laptop running ubuntu it never terminates in centos and windows can anyone explain whats happening in the memory and why the different oses running the same code give different outcomes edit i know the for loop goes out of bounds i am doing it intentionally i just cannot figure out how the behaviour can be different across different oses and computers,['c'] +930739,how to create dynamic drag and drop templates i have a requirement of developing a functionality where user can dynamically define a template labels textboxes labels rows columns parent child relationships among above elements etc these elementssuch as combo boxes may be bound to different database tablesfor example the user may define a template t1 for a specific use case u1 but this template is not restricted to u1 only it may be needed to be used in another use case u2 where it is a sub part of a bigger templateonce the templates are defined another user may load the templates html form and enter data into it at a later stage i need to reuse this data and template to generate pdf reports since pdf reports may sometimes need to have a different layout than the html form i would need parent child relationships between elements as wellas of now we are achieving by generating an xml from a user interface where a user can select elements from a dropdown and specify properties at run time these xml are transformed to html using xslt another xslt is used for generating pdfs the limitation of this scheme is that it is very tedious to incorporate any user requests such as multiple columns add tables into forms etci was wondering how other people achieve this and is there an apilibrary for doing the same i have looked at html5 and jquery drag and drop features but it would require me to add everything from scratch such as dynamically add columnsrows etc,"['java', 'html']" +930850,full list of default java system properties is there a reference or full documentation for all system properties a specific jre setsi am not referring to system properties that can be set by the user of the java command this would be an unlimited list but to the properties the runtime sets itself such as userdir or sunarchdatamodela prefix of sun suggests that this is a kind of private property of the oracle jre implementation while it is less clear for osarch is there some kind of standard that defines which properties with what values i can expect to be set on all jres and which not,['java'] +930851,division an integer into k parts i am programming in java and i need to formulate an algorithm the requirements of the algorithm are we have 3 integer variables n m kwe want to divide n into k parts so that the sum of the kpartsare equal to n and each part is an integer between 1 and mwe want all possible combinations with the allowed integersfor example with input setn 7 m 3 k 4we have two different combinations that we can formulate7 2 2 2 1and7 3 2 1 1thank you all,['java'] +930883,does newmalloc or deletefree occupy or invalidate cache lines i am curious about the cache behavior here are some questions related to the cache below does write operation bring the data into the cacheconsidering an assignment like ai bi will ai be loaded into the cachesince i just write something into ai instead of reading its valuewhen allocating large memory the memory may come from the os and the os will initialize the data to zero for safety reason reference if assignments will bring data into cachequestion 1 will this mechanism occupy the cache assume that there is an allocated array b and the entire b is now in the cache will the cache lines occupied by b become invalidavailable right after i free array bcould somebody gives me a hint,"['c++', 'c']" +930941,logback smtpappender send only one email at a particular time with all the exceptions is there a way to configure the smtpappender in logback to meet the following criteria group all the exceptions into one messageonly send the daily log report if exceptions occurredsend the report only once grouped in one email at a particular time of the daymy current implementation is far from doing the above but currently it sends 3 emails when an exception occurs the exception message the stacktrace and a flush of the buffer filter duplicate log messages very important for email reports turbofilter classchqoslogbackclassicturboduplicatemessagefilter allowedrepetitions1allowedrepetitions cachesize10cachesizeturbofilter basic appender appender nameconsole classchqoslogbackcoreconsoleappender encoder classchqoslogbackclassicencoderpatternlayoutencoder patterndhhmms 55xuser level thread logger20 msgnpattern encoderappender email appender statuslistener classchqoslogbackcorestatusonconsolestatuslistener appender nameemail classchqoslogbackclassicnetsmtpappender smtphostserversmtphost smtpportportsmtpport asynchronoussendingfalseasynchronoussending fromsenderfrom torecipientto subjectsubjectsubject layout classchqoslogbackclassicpatternlayout patterndhhmms 55xuser level thread logger20 msgnpattern layoutappender other root levelinfo appenderref refconsole appenderref refrollingfile appenderref refemailroot,['java'] +931028,will my compiler ignore useless code i have been through a few questions over the network about this subject but i did not find any answer for my question or it is for another language or it does not answer totally dead code is not useless code so heres my questionis explicit or not useless code ignored by the compilerfor example in this codedouble testruntime somefunctionthatreturndoubles a bit of code skippedint i 0for int j 0 j testruntimelength jdouble prevspec oilcons 0will the for loop be removedi use net45 and vs2013the background is that i maintain a lot of code that i did not write and i was wondering if useless code should be a target or if i could let the compiler take care of that,"['c#', '.net']" +931118,plotting categorical data with pandas and matplotlib i have a data frame with categorical data colour direction1 red up2 blue up3 green down4 red left5 red right6 yellow down7 blue downand now i want to generate some graphs like pie charts and histograns based on the categories is it possible without creating dummy numeric variables something likedfplotkindhist,['python'] +931121,android read preferences set in authenticator xml i want to read in my code preferences i have set via the authenticator xml file i found cant access preferences set in accountauthenticator in android and how can access preferences set in accountauthenticator in android one is completely unanswered and the other says i need to create my own activity this really sounds odd since that would mean that the preferences i can configure via xml are useless because i never can read them again that cannot be does someone know more about it if i really have to create an own activity how would i do this in the case of the authenticator,['android'] +931130,could not find or load main class orgapachecatalinastartupbootstrap when i run apache tomcat7056 in eclipse i get an errorerror could not find or load main class orgapachecatalinastartupbootstraphow can i fix the problem,['java'] +931191,python not properly reading in text file i am trying to read in a text file that looks something like thisdate starttime endtime 6814 1832 19036814 1912 19186914 1703 17086914 1713 1750and this is what i haveg openobserved closure infotxt rclosure dateclosure starttimeclosure endtimefile data1 greadlinesfor line in file data11 data1linesplit closure dateappendstrdata10 closure starttimeappendstrdata11 closure endtimeappendstrdata12i did it this way for a previous file that was very similar to this one and everything worked fine however this file is not being read in properly first it gives me an error list index out of range for closure starttimeappendstrdata11 and when i ask for it to print what it has for data1 or closure date it gives me something like x006x00x008x00x001x004x00x00 x001x008x003x002x00x00 x001x009x0x003x00rx00ni have tried rewriting the text file in case there was something corrupt about that particular file and it still does the same thing i am not sure why because last time this worked fineany suggestionsthanks,['python'] +931228,javascript intercepted ctrlo does not open my file dialog i have an input typefile idbrowsebutton filebrowser input in my htmli have another button with id choosefilebutton that when clicked calls documentgetelementbyidbrowsebuttonclick when this button is clicked it correctly clicks browsebutton and the file dialog opensnow i took code from this answer to intercept a ctrlo keypress and open my file dialog so i have thiswindowbindkeydown functione if ectrlkey emetakey switch stringfromcharcodeewhichtolowercase case s epreventdefault does not matter for this question return false case o epreventdefault documentgetelementbyidchoosefilebuttonclick return false return trueas you can see when i intercept ctrlo i click on my choosefilebutton button which calls documentgetelementbyidbrowsebutton in its onclick handler i have put a breakpoint in this click handler and when i press ctrlo it does arrive at this breakpoint however the file dialog never shows upthrough debugging i found out that if i put an alert after the choosefilebutton click line then the alert shows up and the normal page open file dialog shows up not my file dialog if i do not have this alert however nothing shows up at allis this a bug how can i fix it and make my file dialog show up via the intercepted ctrloedit i just tested in chrome and it works perfectly however it still does not work in firefox,"['javascript', 'jquery', 'html']" +931244,how does the standards committee indicate the status of a paper under consideration does the c standards committee provide on the open standard site or elsewhere any indicatation of the status of the papers under consideration and indexed on the openstandards site i am referring to the individual papers indicating potential changes to the standard with associated thiscussion as per the example below i am not referring to the published or draft standard as a wholefor instance how can i determine whether n3922 has been accepted or rejected,['c++'] +931284,app engine instances spikes i am using automatic scaling with gae running php55 this also happened with php5 settingsautomatic scaling min idle instances 0 max idle instances 2 default value min pending latency 500ms max pending latency 70msi am having trouble understanding why these spikes are happening typically my application requires no more than 5 instances running at once occasionally this will jump to 1200 for no apparent reason the logs surrounding this time show 500 timeout errors for all nonstatic content the only dependency on these pages is a simple database insert i am using google cloud sql there are no errors reported in the cloud sql logs eitherany ideas on how to further troubleshoot this as you can see from the image this problem is very sporadic but extremely costly,['php'] +931323,cordova splash screen plugin ipad landscape mode issue i am using the cordova splash screen plugin in my hybrid mobile app targeted for ios i have all the splash screen images added to my project as belowthe reason for using this plugin is to elongate the time for which the splash screen is shown and i manually hide it later in the app so my configxml has the following declarationspreference nameautohidesplashscreen valuefalse preference nameshowsplashscreenspinner valuefalsethis plugin works fine in the portrait mode on iphone and ipad but on the ipad in landscape mode the plugin shows the splash image in portrait mode and consequently my first app view also shows in the portrait mode even though the device is in landscape mode below screenshot shows the splash screen and the black blank portion below it when the ipad is in landscape modeany advise on how to resolve this issue,['ios'] +931338,determining cause of deoptimisation first the questionhow can i determine the cause of deoptimisation of my functionfor example here is a deoptimisation entry for one of my functionsdeoptimizing deopt eager begin 0x3ca09e9f4d1 mergeobjects opt 50 12 fp to sp delta 96 jump table entry 8 deoptimization bailout 12 translating mergeobjects node43 height64 0x7f5fbfecd0 top 128 0xcd2904121 sp 144 0xcd2904121 undefined 0x7f5fbfecc8 top 120 0x3ca09e9ca19 sp 136 0x3ca09e9ca19 an object with map 0x4c8d818621 0x7f5fbfecc0 top 112 0x2c9b8b1b95a9 sp 128 0x2c9b8b1b95a9 an object with map 0x7e33a207821 0x7f5fbfecb8 top 104 0x2c9b8b1b9229 rax 0x2c9b8b1b9229 js array0 0x7f5fbfecb0 top 96 0xcd2904181 sp 112 0xcd2904181 false 0x7f5fbfeca8 top 88 0x2481f54fb4b6 callers pc 0x7f5fbfeca0 top 80 0x7f5fbfed40 callers fp 0x7f5fbfec98 top 72 0x3ca09e8eae1 context 0x7f5fbfec90 top 64 0x3ca09e9f4d1 function 0x7f5fbfec88 top 56 0x70a69429aa1 sp 32 0x70a69429aa1 string3 key 0x7f5fbfec80 top 48 0xcd2904121 undefined literal 0x7f5fbfec78 top 40 0xcd2904121 undefined literal 0x7f5fbfec70 top 32 0x3ca09e9ca19 sp 136 0x3ca09e9ca19 an object with map 0x4c8d818621 0x7f5fbfec68 top 24 0x4c8d818621 sp 64 0x4c8d818621 mapelements3 0x7f5fbfec60 top 16 0x2c9b8b014341 sp 56 0x2c9b8b014341 fixedarray3 0x7f5fbfec58 top 8 0x30 sp 48 3 0x7f5fbfec50 top 0 0 sp 40 smideoptimizing eager end 0x3ca09e9f4d1 mergeobjects 12 node43 pc0x2481f54ecd00 stateno registers alignmentno padding took 0060 msremoving optimized code for mergeobjectsi suspect that the reason albeit not very telling is thisjump table entry 8 deoptimization bailout 12where can i find more information about this and other reasons for deoptimisation and more importantly how can i determine what part of my js code caused this deoptimisationhere are some other deoptimisation reasons i see for other functionsdeoptimize insufficient type feedback for generic named accessdeoptimize insufficient type feedback for rhs of binary operationjump table entry x deoptimization bailout y lots of these with different numbersin laymans terms i would like to be able to look at this log and say okay my function got deoptimised because v8 predicted i will only use strings as its function parameter and here i called it with an integer or something similari would also love to learn more about the other information i can see in these logs for example what do the various deoptimisations mean eager soft etc what do the numbers in the first line mean what else should be of interest to me in this log while improving performanceif it is in any way relevant the code being deoptimised in the log above is here and to generate the logs by running the librarys benchmark execute in the projects rootnode trace deopt code comments bench,['javascript'] +931390,android alarmmanager stops when activity die i start alarmmanager with pendingintent and on few phones alarm is not responding on some devices is working ok on others it fails i have made a few tests on different phones nexus works ok also samsung galaxy s4 zoom 42 works oksamsung note 2 43 works okoppo 4 alarm diesi have also implemented broadcast receivers which are working as they should on all devices logvtag start alarm intent intentalarm new intentcontext alarmreceiverclass pendingintent pendingintent pendingintentgetbroadcastcontextgetapplicationcontext 0 intentalarm pendingintentflag update current alarmmanager alarmmanager alarmmanager contextgetsystemservicecontextalarm service alarmmanagersetinexactrepeatingalarmmanagerelapsed realtime 10 50 pendingintent,['android'] +931410,setting active profile and config location from command line in spring boot i have a spring boot applicationi have three profiles in my application development staging and production so i have 3 files applicationdevelopmentymlapplicationstagingymlapplicationproductionymlmy applicationyml resides inside srcmainresources i have set the active profile in applicationyml as spring profilesactive developmentthe other 3 profile specific config files are present in cconfig folder i am using gradle plugin for eclipse when i try to do a bootrun i am setting the command line arguments in my gradle configuration in eclipse as dspringprofilesactivestaging dspringconfiglocationcconfighowever the command line property is not getting reflected and my active profile is always getting set as developmentwhich is the one that i have mentioned in the applicationsyml file also cconfig folder is not searched for profile specific config filesi think i am missing something here i have been trying to figure it out for the past 2 days but no luck i would really appreciate any help,['java'] +931412,why is there no execution time difference between multithreading and singlethreading i am trying to learn python language and it is concept i wrote some code to play with multithreading but i notice that there is no execution time difference between multi and single threadingthe machine which is to run script has 4 corethread def get tokensfile namemap printfile name counter 0 with openfile namerencodingutf8sig as f for line in f item jsonloadslineencodingutf8 if spot in item and itemsid 4663 counter1 if counter 500 break tokens nltkword tokenizeitemspotlanguageenglish for token in tokens if token not in map maptoken 1 else maptoken maptoken 1 start time timetime map dict with threadpoolexecutormax workers3 as executor for file in fileprocessingget files in directorydraw data future executorsubmitfileprocessingget tokens file map end time timetime printelapsed time was g seconds end time start timeeach files size in the raw data is bigger than 25 mb so i think must be difference between them but there is not why am i doing a mistake in code or multihreading concept,['python'] +931441,font for collapsingtoolbarlayout is there a way to set the font for a collapsingtoolbarlayouti am using calligraphy but my default font is not appliedi think the problem is the collapsingtexthelper class is using canvasdrawtext instead of a textviewhow can i change the default font that is used for canvasdrawtext,['android'] +931467,in java what does such enum type compile to below is the code that defines enum typeenum company ebay30 paypal10 google15 yahoo20 att25 private int value private companyint value superthisname thisvalue value public int getvalue return value that gets internally compiled tofinal class company extends enumcompany public final static company ebay new company30 public final static company paypal new company10 public final static company google new company15 public final static company yahoo new company20 public final static company att new company25 private int value private companyint value superthisnameenumvalueofcompanyclass thisname thisvalue value public int getvalue return value is my understanding correct,['java'] +931503,how to resolve this warning watlasi1pointer 0x0 not in getpreloadeddrawables every time when i run my app i am getting this weird warningi do not have any idea about resolving it can some one please explain me thishere is the logcat0625 093424997 17211721 iarti1 lateenabling xcheckjni0625 093425957 17211748comaitrgaitqc dopenglrendereri1 render dirty regions requested true0625 093425970 17211721comaitrgaitqc di1 hostconnectionget new host connection established 0xa4942590 tid 17210625 093425975 17211721comaitrgaitqc datlasi1 validating map0625 093425979 17211721comaitrgaitqc watlasi1 pointer 0x0 not in getpreloadeddrawables0625 093425979 17211721comaitrgaitqc watlasi1 pointer 0x0 not in getpreloadeddrawables0625 093425979 17211721comaitrgaitqc watlasi1 pointer 0x0 not in getpreloadeddrawables0625 093425979 17211721comaitrgaitqc watlasi1 pointer 0x0 not in getpreloadeddrawables0625 093425979 17211721comaitrgaitqc watlasi1 pointer 0x0 not in getpreloadeddrawables0625 093425979 17211721comaitrgaitqc watlasi1 pointer 0x0 not in getpreloadeddrawables0625 093425979 17211721comaitrgaitqc watlasi1 pointer 0x0 not in getpreloadeddrawables0625 093425979 17211721comaitrgaitqc watlasi1 pointer 0x0 not in getpreloadeddrawablesand it goes up to this so i skipped some lines 0625 093426019 17211721comaitrgaitqc watlasi1 pointer 0x0 not in getpreloadeddrawables0625 093426019 17211721comaitrgaitqc watlasi1 pointer 0x0 not in getpreloadeddrawables0625 093426019 17211721comaitrgaitqc watlasi1 pointer 0x0 not in getpreloadeddrawables0625 093426019 17211721comaitrgaitqc watlasi1 pointer 0x0 not in getpreloadeddrawables0625 093426019 17211721comaitrgaitqc watlasi1 pointer 0x0 not in getpreloadeddrawables0625 093426019 17211721comaitrgaitqc watlasi1 pointer 0x0 not in getpreloadeddrawables0625 093426019 17211721comaitrgaitqc watlasi1 pointer 0x0 not in getpreloadeddrawables0625 093426019 17211721comaitrgaitqc watlasi1 pointer 0x0 not in getpreloadeddrawables0625 093426019 17211721comaitrgaitqc watlasi1 pointer 0x0 not in getpreloadeddrawables0625 093426019 17211721comaitrgaitqc watlasi1 pointer 0x0 not in getpreloadeddrawables0625 093426025 17211721comaitrgaitqc watlasi1 pointer 0x0 not in getpreloadeddrawables0625 093426025 17211721comaitrgaitqc watlasi1 pointer 0x0 not in getpreloadeddrawables0625 093426087 17211748comaitrgaitqc dlibegli1 loaded systemlibegllibegl emulationso0625 093426088 17211748comaitrgaitqc dlibegli1 loaded systemlibegllibglesv1 cm emulationso0625 093426100 17211748comaitrgaitqc dlibegli1 loaded systemlibegllibglesv2 emulationso0625 093426115 17211748comaitrgaitqc di1 hostconnectionget new host connection established 0xa4942b30 tid 17480625 093426125 17211748comaitrgaitqc iopenglrendereri1 initialized egl version 140625 093426160 17211748comaitrgaitqc dopenglrendereri1 enabling debug mode 00625 093426183 17211748comaitrgaitqc wegl emulationi1 eglsurfaceattrib not implemented0625 093426183 17211748comaitrgaitqc wopenglrendereri1 failed to set egl swap behavior on surface 0xa4938f80 erroregl success,['android'] +931599,protecting twitter keys on android when adding twitter authentication to my android app going to twitter dev i was flabbergasted at finding that i have to initialize twitters fabric like thisimport iofabricsdkandroidfabricimport comtwittersdkandroidtwitterimport comtwittersdkandroidcoretwitterauthconfigoverridepublic void oncreate superoncreate twitterauthconfig authconfig new twitterauthconfigconsumerkey consumersecret fabricwiththis new twitterauthconfigthey are officialy recommending that i put both api key and api secret in my app as plaintext even in this official sample the keys are stored in buildconfigi am using proguard but even then i cannot guarantee that a determined hacker wouldnt be able to exploit my api secret do established apps like quora also expose these keyscan somebody post an example for overcoming this vulnerability or give a convincing argument as to why twitter is doing thisin contrast google and facebook only required me to add an appid and i had to hash my signing certificates and link the hashes to respective apps this is levels of magnitude more secure than above,['android'] +931603,reduce menu items widthheight and textview size i had done a menu overflow itemsi need to reduce menu items widthheight and textview sizei referred this postbut it is not working for mei am posted the code and screenshot related to thatmenu xmlnsandroid item androidididadd androidicondrawabledown androidtitleread androidshowasactionnever item androidididadd2 androidicondrawabledown androidtitlewrite androidshowasactionnever item androidididadd3 androidicondrawabledown androidtitlebold androidshowasactionnever menumenu item screenshotstylesxml style nameappbasetheme parentandroidthemelight style application theme style nameapptheme parentappbasetheme item nameandroidactionoverflowbuttonstylestylemyactionbuttonoverflowitem style style namemyactionbuttonoverflow parentandroidstylewidgetholoactionbuttonoverflow item nameandroidsrcdrawabledownitem stylemy only problem isi need to reduce the widthheight and textview size in menu items,['android'] +931709,c template functions priority include iostreamtemplate class u class tvoid foou t stdcout firsttemplate class tvoid fooint const t stdcout secondint main int a double g 2 fooa g prints first return 0to call the second foo overload the compiler needs to perform only one template type deduction but for the first overload it needs to perform two can you please explain why the first overload is called,['c++'] +931715,how to force the eclipse mars 45 formatter not to join already wrapped lines i have just moved from eclipse kepler to eclipse mars and my java formatter seems not to behave the same way anymorei used to be able to do the followingobject method1 method2 method3the formatter would keep my code like that however since i changed to eclipse mars everything is wrapped to one linei have verified the formatter and i still have the option never join already wrapped lines checked my project does not use specific settings regarding the eclipse formatter i tried recreating a formatter from scratch and the result is the samehow can i force eclipse not to join those lines thanks,['java'] +931720,default value for gradle buildconfigfield boolean used across flavors i have a number of flavors in my app and i want to set a boolean buildconfigfield for a subset of them is there a way to avoid having to add the field to every flavor ideally my buildgradle would look like the followingproductflavors flavor1 flavor4 buildconfigfield boolean thisable something true flavor5 buildconfigfield boolean thisable something true flavor8 so in my app i can just goif buildconfigthisable something thisable stuffhowever compilation fails when i try to build with for example flavor1 as it cannot find the field i do not want to have to remember to add this to every new flavor i create are there any ways around this,['android'] +931772,initialization with string in scientific format in java biginteger i have a need to work with large numbers something in range 1e100 1e200 however the biginteger class which seems to be suitable in general does not recognize strings in scientific format during initialization as well as does not support the conversion to a string in the formatbigdecimal d new bigdecimal1e10 worksbiginteger i1 new biginteger10 worksbiginteger i2 new biginteger1e10 throws numberformatexceptionsystemoutprintlndtoengineeringstring workssystemoutprintlni1toengineeringstring method is undefinedis there a way around i cannot imagine that such class was designed with assumption that users must type hundreds of zeros in input,['java'] +931825,why does typescript wrap class in anonymous function let us have for example a dog classclass dog static food private static static var 123 constructorprivate name speak consolelogthisname i eat dogfood dogstatic var compiled to jsvar dog function function dogname thisname name dogprototypespeak function consolelogthisname i eat dogfood dogstatic var dogstatic var 123 return dogthis works equally well and is less complicatedfunction dogname thisname namedogprototypespeak function consolelogthisname i eat dogfood dogstatic vardogstatic var 123is there any other than aesthetic reason for using the anonymous function wrapper,['javascript'] +931940,get functions methods of a class i have to dynamically fetch the properties and functions of a es6 class is this even possible using a forin loop i only get to loop through the properties of a class instanceclass foo constructor thisbar hi somefunc consolelogthisbar var foo new foofor var idx in foo consolelogidxoutputbar,['javascript'] +932010,ios 8 self sizing cells with accessory view using ios 83 simulator and xcode 632i am using the self sizing cells technique in ios 8 and it works terrifically when the cell has no accessory view but breaks when the cell has an accessory view i set constraints on the label inside the cellthen i use an estimatedrowheight and set the rowheight to uitableviewautomaticdimension i am omitting tableviewnumberofrowsinsection here but it just returns 3 for this exampleimplementation mytableviewcontroller voidviewdidload super viewdidload selftableviewestimatedrowheight 440f selftableviewrowheight uitableviewautomaticdimension uitableviewcell tableviewuitableview tableview cellforrowatindexpathnsindexpath indexpath mycell cell mycell tableview dequeuereusablecellwithidentifiermycell forindexpathindexpath celltitlelabeltext test comment test comment test comment test comment test comment test comment test comment test comment test comment test comment test comment return cellendand bam everything looks greatbut when i add an accessory view in the storyboard without changing any of the codethe first cell goes to hell xcodes view debugger tells me the label height is 1785 points and i had to use a gif to show it herei do notice that the other two cells are sized fine i also note that when i rotate the simulator the first cell gets resized properly including after it is rotated back to portraitdoes anyone know why the accessory view messes this up so badly and what i can do to fix it a sample project is available at,"['ios', 'iphone']" +932049,pdb file is mising after postsharp i am using postsharp version 2164 also tried latest version 21735 and sometimes pdb file is missing and there is a pssym file in it is place xml version10 encodingutf8symbols xmlns class class1tcrosscuttingloggingcrosscuttingloggingattributeslogmethodcallstatsattribute limitedlicensetrue class class2trequestlimiterrequestlimiterrequestcounterattribute limitedlicensetrue symbolsi ran procmon on the build process and as far as i can tell the postsharpsrv40x86exe process moves both dll and pdb files from objdebug folder to objdebugbeforepostsharp folder and later on generates a new dll in objdebug folder but a new pdb file is not generatedthis happens for some of my dlls seemingly at random and does not seem to be reliable because on other machine all pdb files are generated correctly,['c#'] +932074,how to merge xml streams i have multiple xml streams with this formatxml1xml version10 encodingutf8node nodeatest1nodea nodebtest2nodeb nodec atest4att value110value1 nodecnodenode nodeatest1nodea nodebtest7nodeb nodec atest8att value120value1 nodecnodexmlnxml version10 encodingutf8node nodeatest1nodea nodebtest2nodeb nodec atest4att valuen50valuen nodecnodenode nodeatest1nodea nodebtest7nodeb nodec atest8att valuen60valuen nodecnodenode nodeatest9nodea nodebtest8nodeb nodec atest8att valuen60valuen nodecnodei want the merged xml to look like thisxml version10 encodingutf8node nodeatest1nodea nodebtest2nodeb nodenewtest4att value110value1 valuen50valuennodenode nodeatest1nodea nodebtest7nodeb nodenewtest8nodenew value120value1 valuen60valuennodenode nodeatest9nodea nodebtest8nodeb nodenewtest8nodenew value1value1 valuen60valuennodeso i create unique keys nodeanodebnodenew with different value1 valuen which are assigned nothing if this unique key does not appear in its respective xmlwhat would be the most efficient way to do this,['c#'] +932235,is there an example code for corespotlight search feature ios 9 api is there an example code for corespotlight search feature ios 9 api really appreciate if can look at sample code to implementtest,['objective-c'] +932329,adding uitableview inside uitableviewcell i am working on custom uitableviewcell where i want to add uitableview inside uitableviewcell so is there any controller available to do the samethis is the image of what i want to add in my projectthis is expandable uitableview where after clicking first row inside table and buttons are expandedso if any similar controller is available please suggest methanks in advance,['ios'] +932368,prevent categoryaxis labels from overlapping in linechart using the below options does not help me prevent my categoryaxislabels from overlapping in linechart when my browser is resizedcategoryaxisautogridcount truecategoryaxisminhorizontalgap 100categoryaxisgridposition startcategoryaxisequalspacing falsecategoryaxisparsedates falsechartvalidatenowi trigger these functions on the wndowonresize function event please note i also have a custom labelfunction to format the axislabelsmy result it autogridcounts from 476px to lower but above it all the categoryaxis label values appear on xaxis and overlap upon each other in a most thisgraceful way can someone please help me out really stuck,['jquery'] +932395,why is accessing a variable using windowvariable slower multiple sources for js performance tips encourage developers to reduce scope chain lookup for example iifes are touted as having a bonus benefit of reducing scope chain lookup when you access global variables this sounds quite logical perhaps even taken for granted so i did not question the wisdom like many others i have been happily using iifes thinking that on top of avoiding global namespace pollution there is gonna be a performance boost over any global codewhat we expect todayfunction window undefined apparently variable access here is faster than outside the iifejquery windowsimplifying extending this to a generalized case one would expectvar x 0functionwindow accessing windowx here should be fasterwindowbased on my understanding of js there is no difference between x 1 and windowx 1 in the global scope therefore it is logical to expect them to be equally performant right wrong i ran some tests and thiscovered that there is a significant difference in access timesok maybe if i place the windowx 1 inside an iife it should run even faster even if just slightly right wrong againok maybe it is firefox let us try chrome instead v8 is the benchmark for js speed yea it should beat firefox for simple stuff like accessing a global variable directly right wrong yet againso i set out to find out exactly which method of access is fastest in each of the two browsers so let us say we start with one line of code var x 0 after x has been declared and happily attached to window which of these methods of access would be fastest and whydirectly in global scopex x 1directly in global scope but prefixed with windowwindowx windowx 1inside a function unqualifiedfunction accessunqualified x x 1inside a function with window prefixfunction accesswindowprefix windowx windowx 1inside a function cache window as variable prefixed access simulate local param of an iifefunction accesscachewindow var global window globalx globalx 1inside an iife window as param prefixed access functionglobal globalx globalx 1 windowinside an iife window as param unqualified access functionglobal x x 1 windowplease assume browser context ie window is the global variablei wrote a quick time test to loop the increment operation a million times and was surprised by the results what i found firefox chrome 1 direct access 848ms 1757ms2 direct windowx 2352ms 2377ms3 in function x 338ms 3ms4 in function windowx 1752ms 835ms5 simulate iife globalx 786ms 10ms6 iife globalx 791ms 11ms7 iife x 331ms 655msi repeated the test a few times and the numbers appear to be indicative but they are confusing to me as they seem to suggestprefixing with window is much slower 2 vs 1 4 vs 3 but whyaccessing a global in a function supposedly extra scope lookup is faster 3 vs 1 whywhy are the 567 results so different across the two browsersi understand there are some who think such tests are pointless for performance tuning and that may well be true but please for the sake of knowledge just humor me and help improve my understanding of these simple concepts like variable access and scope chainif you have read this far thank you for your patience apologies for the long post and for possibly lumping multiple questions into one i think they are all somewhat relatededit sharing my benchmark code as requestedvar x starttime endtime time test 1 xx 0starttime datenowfor var i0 i10 i x x 1endtime datenowtime endtime starttimeconsolelogaccess x directly completed in time ms test 2 windowxx 0starttime datenowfor var i0 i10 i windowx windowx 1endtime datenowtime endtime starttimeconsolelogaccess windowx completed in time ms test 3 inside function xx 0starttime datenowaccessunqualifiedendtime datenowtime endtime starttimeconsolelogaccessunqualified completed in time ms test 4 inside function windowxx 0starttime datenowaccesswindowprefixendtime datenowtime endtime starttimeconsolelogaccesswindowprefix completed in time ms test 5 function cache window simulte iife globalxx 0starttime datenowaccesscachewindowendtime datenowtime endtime starttimeconsolelogaccesscachewindow completed in time ms test 6 iife windowxx 0starttime datenowfunctionwindow for var i0 i10 i windowx windowx1 windowendtime datenowtime endtime starttimeconsolelogaccess iife window completed in time ms test 7 iife xx 0starttime datenowfunctionglobal for var i0 i10 i x x1 windowendtime datenowtime endtime starttimeconsolelogaccess iife x completed in time msfunction accessunqualified for var i0 i10 i x x1 function accesswindowprefix for var i0 i10 i windowx windowx1 function accesscachewindow var global window for var i0 i10 i globalx globalx1,['javascript'] +932438,unsupportedclassversionerror on running play application with jdk 17 just now started learning play framework for my project requirement and my project only build on jdk 17 so i have downloaded play 239 version and created a sample project by typing activator new then moved into the sample project directory and executed activator run then i see jdk incompatible exceptions where i have to make the changes to handle thisloginfo loading project definition from eworkspaceplayfirstaprojectinfo set current project to firstapp in build fileeworkspaceplayfirstappjavalangunsupportedclassversionerror comtypesafeconfigconfigexception unsupported majorminor version 520 at javalangclassloaderdefineclass1native method at javalangclassloaderdefineclassclassloaderjava800 at javasecuritysecureclassloaderdefineclasecureclassloaderjava142 at javaneturlclassloaderdefineclassurlclassloaderjava449 at javaneturlclassloaderaccess100urlclassloaderjava71 at javaneturlclassloader1runurlclassloaderjava361 at javaneturlclassloader1runurlclassloaderjava355 at javasecurityaccesscontrollerdoprivilegednative method at javaneturlclassloaderfindclassurlclassloaderjava354 at javalangclassloaderloadclassclassloaderjava425 at javalangclassloaderloadclassclassloaderjava358 at comtypesafesbtwebsbtwebanonfuncomtypesafesbtwebsbtwebload1applysbtwebscala535 at comtypesafesbtwebsbtwebanonfuncomtypesafesbtwebsbtwebload1applysbtwebscala535 at scalaoptionfoldoptionscala157 at comtypesafesbtwebsbtwebcomtypesafesbtwebsbtwebloadsbtwebscala549 at comtypesafesbtwebsbtwebanonfunglobalsettings1anonfunapply1applysbtwebscala143 at comtypesafesbtwebsbtwebanonfunglobalsettings1anonfunapply1applysbtwebscala143 at scalafunction1anonfunandthen1applyfunction1scala55 at sbtprojectsetprojectprojectscala319 at sbtbuiltincommandsdoloadprojectmainscala484 at sbtbuiltincommandsanonfunloadprojectimpl2applymainscala475 at sbtbuiltincommandsanonfunloadprojectimpl2applymainscala475 at sbtcommandanonfunapplyeffect1anonfunapply2applycommandscala58 at sbtcommandanonfunapplyeffect1anonfunapply2applycommandscala58 at sbtcommandanonfunapplyeffect2anonfunapply3applycommandscala60 at sbtcommandanonfunapplyeffect2anonfunapply3applycommandscala60 at sbtcommandprocesscommandscala92 at sbtmainloopanonfun1anonfunapply1applymainloopscala98 at sbtmainloopanonfun1anonfunapply1applymainloopscala98 at sbtstateanon1procestatescala184 at sbtmainloopanonfun1applymainloopscala98 at sbtmainloopanonfun1applymainloopscala98 at sbterrorhandlingwideconverterrorhandlingscala17 at sbtmainloopnextmainloopscala98 at sbtmainlooprunmainloopscala91 at sbtmainloopanonfunrunwithnewlog1applymainloopscala70 at sbtmainloopanonfunrunwithnewlog1applymainloopscala65 at sbtusingapplyusingscala24 at sbtmainlooprunwithnewlogmainloopscala65 at sbtmainlooprunandclearlastmainloopscala48 at sbtmainlooprunloggedloopmainloopscala32 at sbtmainlooprunloggedmainloopscala24 at sbtstandardmainrunmanagedmainscala53 at sbtxmainrunmainscala28 at xsbtbootlaunchanonfunrun1applylaunchscala109 at xsbtbootlaunchwithcontextloaderlaunchscala128 at xsbtbootlaunchrunlaunchscala109 at xsbtbootlaunchanonfunapply1applylaunchscala35 at xsbtbootlaunchlaunchlaunchscala117 at xsbtbootlaunchapplylaunchscala18 at xsbtbootbootrunimplbootscala41 at xsbtbootbootmainbootscala17 at xsbtbootbootmainbootscalaerror javalangunsupportedclassversionerror comtypesafeconfigconfigexception unsupported majorminor version 520,['java'] +932520,identifying the logged in user from different browser tab in aspnet i have a website with login option in aspnetif i open website in two browser tabs and logged in with same user account and navigated to homescreen in both tabs now i am logged out from one tab and again logged in same tabafter that i clicked on the second tabhow can i thiscriminate that i am sending request from first tab or second tab from code behindif the request is from second tab i need to navigate the application to login screenhow can i do thisin my home page i had added the logic likeif sessionuserid null responseredirectloginaspxbut the problem is that when i logout from first tab and login in again there and after that second tab refreshed sessionuserid is not null so it will stay therebut i need to redirect login page how can i achieve this,"['c#', 'asp.net', '.net']" +932548,extremely slow object instantiation in python 27 i recently had to complete an assignment that used a lot of coordinate operations thinking to save time and simplify my code i defined a class to encapsulate the behaviour of a coordinate pair the class looked like thisclass vector tuple def init self value tuple init self value def add self other return vector self 0 other 0 self 1 other 1this allowed me to write code like this for exampledef translate pointlist thisplacement return point thisplacement for point in pointlistbut my application was terribly slow much slower than other assignments i could not locate any inefficiency in my implementation of the algorithm so i did a simple test to see what the overhead was of the vector class i expected somewhere between 5 and 15my test of the vector class looked like thisv vector 0 0d vector 1 1loopidx 30while loopidx 0 v v d loopidx 1print vthis runs typically in this kind of timereal 0m8440suser 0m8367ssys 0m0016sfor comparison i ran this codev 0 0dx 1dy 1loopidx 30while loopidx 0 v v 0 dx v 1 dy loopidx 1print vrun time for this code isreal 0m1004suser 0m0995ssys 0m06shave i done something seriously wrong or does using class objects in python really mean your application will take over 8 times as long to run,['python'] +932619,how can i use a cursorloader in a viewpager i have a cursorloader which is working finethe problem is i am not using it like i am supposed to i load the data from the cursorloader into arraylists and then use the lists i found this tutorial which shows how to use a cursorloader with a viewpager but i do not understand how to actually make it happen i have a fragment which looks like this public class firstfragment extends fragment mapview mapview googlemap map store instance variables private string emailaboutimagepathlatitudelongitude button getdirections newinstance constructor for creating fragment with arguments public static firstfragment newinstancestring emailstring aboutstring imagepath string latitude string longitude firstfragment fragmentfirst new firstfragment bundle args new bundle argsputstringemail email argsputstringabout about argsputstringimagepath imagepath argsputstringlatitude latitude argsputstringlongitude longitude fragmentfirstsetargumentsargs return fragmentfirst store instance variables based on arguments passed override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate email getargumentsgetstringemail about getargumentsgetstringabout imagepath getargumentsgetstringimagepath latitude getargumentsgetstringlatitude longitude getargumentsgetstringlongitude inflate the view for the fragment based on layout xml override public view oncreateviewlayoutinflater inflater viewgroup container final bundle savedinstancestate view view inflaterinflaterlayoutzzfragment pager items container false imageview imageview imageview viewfindviewbyidridlistpager imageview textview about textview viewfindviewbyidridlistpager text textview emaill textview viewfindviewbyidridlistpager title aboutsettextthisabout emaillsettextthisemail imageloader imageloader imageloadergetinstance thisplayimageoptions options new thisplayimageoptionsbuildercacheinmemorytrue cacheonthisctrueresetviewbeforeloadingtrue considerexifparamstrue build imageloadergetinstancethisplayimageimagepath imageview options getdirections button viewfindviewbyidridgetdirections getdirectionssetonclicklistenernew viewonclicklistener override public void onclickview v string struri latitude longitude email intent mapintent new intentandroidcontentintentaction view uriparsestruri mapintentsetclassnamecomgoogleandroidappsmaps comgoogleandroidmapsmapsactivity getactivitystartactivitymapintent view v inflaterinflaterlayoutlistviewtopager container false gets the mapview from the xml layout and creates it mapview mapview viewfindviewbyidridmapview mapviewoncreatesavedinstancestate gets to googlemap from the mapview and does initialization stuff map mapviewgetmap mapgetuisettingssetmylocationbuttonenabledfalse mapsetmylocationenabledtrue needs to call mapsinitializer before doing any cameraupdatefactory calls mapsinitializerinitializethisgetactivity updates the location and zoom of the mapview cameraupdate cameraupdate cameraupdatefactorynewlatlngzoomnew latlngdoubleparsedoublelatitude doubleparsedoublelongitude 10 mapanimatecameracameraupdate return view override public void onresume mapviewonresume superonresume override public void ondestroy superondestroy mapviewondestroy override public void onlowmemory superonlowmemory mapviewonlowmemory and i was calling it in this class public class viewpagerfragment extends fragmentactivity implements loadermanagerloadercallbackscursor arrayliststring email new arrayliststringarrayliststring about new arrayliststringarrayliststring imagepath new arrayliststringarrayliststring latitude new arrayliststringarrayliststring longitude new arrayliststringoverrideprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity view pager fragment getloadermanagerinitloader1 null thisprivate smartfragmentstatepageradapter adapterviewpager extend from smartfragmentstatepageradapter now instead for more dynamic viewpager itemspublic static class mypageradapter extends smartfragmentstatepageradapter private final arrayliststring email private final arrayliststring about private final arrayliststring imagepath private final arrayliststring latitude private final arrayliststring longitude private int listposition public mypageradapterfragmentmanager fragmentmanagerarrayliststring emailarrayliststring about arrayliststring imagepatharrayliststring latitudearrayliststring longitudeint lposition superfragmentmanager thisimagepathimagepath thisemailemail thisabout about thislatitude latitude thislongitude longitude listposition lposition returns total number of pagesoverridepublic int getcount return emailsize returns the fragment to thisplay for that page override public fragment getitemint position return firstfragmentnewinstancelistpositionposition emailgetlistpositionposition return firstfragmentnewinstanceemailgetposition aboutgetpositionimagepathgetpositionlatitudegetpositionlongitudegetposition returns the page title for the top indicator override public charsequence getpagetitleint position return page position overridepublic loadercursor oncreateloaderint id bundle args string projection activitiestablekey email activitiestablekey about activitiestablekey imagepath activitiestablekey latitude activitiestablekey longitutde cursorloader cursorloader new cursorloaderthis namecontentprovidername activities uri projection null null null return cursorloaderoverridepublic void onloadfinishedandroidcontentloadercursor loader cursor cursor if cursor null cursorgetcount 0 cursormovetofirst do emailaddcursorgetstringcursor getcolumnindexorthrowemail aboutaddcursorgetstringcursor getcolumnindexorthrowabout imagepathaddcursorgetstringcursor getcolumnindexorthrowimagepath latitudeaddcursorgetstringcursor getcolumnindexorthrowserverlatitude longitudeaddcursorgetstringcursor getcolumnindexorthrowserverlongitude while cursormovetonext int listposition getintentgetextrasgetintposition viewpager vppager viewpager findviewbyidridvppager adapterviewpager new mypageradaptergetsupportfragmentmanageremailaboutimagepathlatitudelongitudelistposition vppagersetadapteradapterviewpager vppagersetcurrentitemlistpositionoverridepublic void onloaderresetandroidcontentloadercursor loader how can i modify the code to use the viewpager with the loader directly by using that tutorial instead of storing everything in lists and then using the lists,['android'] +932670,provided gradle dependency is aar not jar i have an issue where i am trying to include a library in my project called the parseloginui the issue is it uses the provided tag instead of compile i believe the provided tag means that the project needs to supply this dependency in order for the library to work rather than this library compiling the libraries itselfso in my android library it references the facebook sdk like so provided comfacebookandroidfacebookandroidsdk401then in my mobilebuildgradle which is my main module i compile the facebook sdks like socompile comfacebookandroidfacebookandroidsdk401i have been following the guide for installing this library and this is how youre meant to do it here is the warning i get that stops me from compiling thrown by the parseloginuibuildgradle file the one providing itwarningproject parseloginui provided dependencies can only be jars comfacebookandroidfacebookandroidsdkaar401 is an android librarythe documentation for this library has a fix which isif you are using gradle 110 or above you may encounter warningproject parseloginui provided dependencies can only be jars comfacebookandroidfacebookandroidsdkaar401 is an android library it is an open issue of android gradle build tool currently the workround is using gradle 100fair enough but i do not want to downgrade my gradle currently running v123 just to solve this issue there must be a way round this or a better way of doing itmy questionhow can i include the facebook sdk in both the library module and my main module,['android'] +932672,vec4 x mat4x4 product using simd and improvements i am writing a complex simulation program and it apprears that the most time consumming routine is the one for multiplying a fourvector float4 with a 4x4 matrix i need to run this program on several computers which are more or less old that is why i tried to check simd capabilities of such operations in the following code include xmmintrinh sseinclude pmmintrinh sse3include nmmintrinh sse42 include immintrinh avxinclude iostreaminclude ctimeinclude stringusing namespace std 4vectortypedef struct float x float y float z float wfloat4 typedef to simplify the pointer of function notationtypedef voidfunctionfloat4const float4const float4float dot const float4 in a const float4 in x return in axin xx in ayin xy in azin xz in awin xw 7 flopsvoid a times x float4 out y const float4 in a const float4 in x out yx dotin a0 in x 7 flops out yy dotin a1 in x 7 flops out yz dotin a2 in x 7 flops out yw dotin a3 in x 7 flopsvoid a times x sse float4 out y const float4 in a const float4 in x load matrix a and vector x into sse registers m128 x mm load psconst floatin x loadstore are almost 0 flops m128 a0 mm load psconst floatin a 0 m128 a1 mm load psconst floatin a 1 m128 a2 mm load psconst floatin a 2 m128 a3 mm load psconst floatin a 3 transpose the matrix and reorder the vector mm transpose4 ps a0a1a2a3 m128 u1 mm shuffle psxx mm shuffle0 m128 u2 mm shuffle psxx mm shuffle1 m128 u3 mm shuffle psxx mm shuffle2 m128 u4 mm shuffle psxx mm shuffle3 multiply each matrix row with the vector x m128 m0 mm mul psa0 u1 4 flops m128 m1 mm mul psa1 u2 4 flops m128 m2 mm mul psa2 u3 4 flops m128 m3 mm mul psa3 u4 4 flops using hadd we add four floats at a time m128 sum 01 mm add psm0 m1 4 flops m128 sum 23 mm add psm2 m3 4 flops m128 result mm add pssum 01 sum 23 4 flops finally store the result mm store psfloatout y resultvoid a times x sse3 float4 out y const float4 in a const float4 in x should be 4 sse x 4 alu 16 times faster than scalar load matrix a and vector x into sse registers m128 x mm load psconst floatin x loadstore are almost 0 flops m128 a0 mm load psconst floatin a 0 m128 a1 mm load psconst floatin a 1 m128 a2 mm load psconst floatin a 2 m128 a3 mm load psconst floatin a 3 multiply each matrix row with the vector x m128 m0 mm mul psa0 x 4 flops m128 m1 mm mul psa1 x 4 flops m128 m2 mm mul psa2 x 4 flops m128 m3 mm mul psa3 x 4 flops using hadd we add four floats at a time m128 sum 01 mm hadd psm0 m1 4 flops m128 sum 23 mm hadd psm2 m3 4 flops m128 result mm hadd pssum 01 sum 23 4 flops finally store the result mm store psfloatout y resultvoid a times x sse4 float4 out y const float4 in a const float4 in x 28 flops should be 4 sse x 4 alu 16 times faster than scalar load matrix a and vector x into sse registers m128 x mm load psconst floatin x loadstore are almost 0 flops m128 a0 mm load psconst floatin a 0 m128 a1 mm load psconst floatin a 1 m128 a2 mm load psconst floatin a 2 m128 a3 mm load psconst floatin a 3 multiply each matrix row with the vector x m128 m0 mm dp psa0 x 0xff 4 flops m128 m1 mm dp psa1 x 0xff 4 flops m128 m2 mm dp psa2 x 0xff 4 flops m128 m3 mm dp psa3 x 0xff 4 flops using hadd we add four floats at a time m128 mov 01 mm movelh psm0 m1 4 flops m128 mov 23 mm movelh psm2 m3 4 flops m128 result mm shuffle psmov 01 mov 23 mm shuffle2 0 2 0 4 flops finally store the result mm store psfloatout y resultvoid a times x avx float4 out y const float4 in a const float4 in x load matrix a and vector x into sse registers m128 x mm load psconst floatin x loadstore are almost 0 flops m256 xx mm256 castps128 ps256x xx mm256 insertf128 psx1 m256 a0 mm256 load psconst floatin a 0 m256 a2 mm256 load psconst floatin a 2 multiply each matrix row with the vector x m256 m0 mm256 mul psa0 xx 4 flops m256 m2 mm256 mul psa2 xx 4 flops using hadd we add four floats at a time m256 sum 00 mm256 hadd psm0 m2 4 flops m128 sum 10 mm256 extractf128 pssum 0 m128 sum 01 mm256 extractf128 pssum 001 m128 result mm hadd pssum 10 sum 01 4 flops finally store the result mm store psfloatout y result finally store the result no temp variable direct hadd this avoid to copy from alu128 to alu256 mm store psfloatout y mm hadd ps mm256 extractf128 pssum 0 mm256 extractf128 pssum 001void test function function f string simd unsigned int imax float4 y float4 x1 0510207 float4 x2 0710205 float4 x3 0502107 float4 x4 1070205 float4 a4 0510207 06040108 03080205 1040609 clock t tstart clock for unsigned int i0 iimax i for unsigned long int j0 j250 j avoid for loop over long long it is 2 times slower function pointer give a real call whether the direct call is inlined and thus results are overestimated f yax1 f yax2 f yax3 f yax4 clock t tend clock double diff static castdoubletend tstart 1e3 cout time simd diff s endl cout nops simd double imax 109 endl cout power simd double imax 28 diff gflops endl 28 flops for std cout endlint main int argc char argv test function a times x std 1 test function a times x sse sse 2 test function a times x sse3sse3 3 test function a times x sse4sse4 1 test function a times x avx avx 3 return 0i have some troubles about the improvements for such problem when running the code i obtain the following results intel core i5 4670k 34ghz haswell codeblockmingw compiler using o2 marchcorei7avx time std 6287 snops std 1109power std 445363 gflopstime sse 61 snops sse 2109power sse 840715 gflopstime sse3 8361 snops sse3 3109power sse3 100466 gflopstime sse4 6131 snops sse4 1109power sse4 456695 gflopstime avx 8767 snops avx 3109power avx 958138 gflopsmy questions are the following is this possible to improve more the performancesspeed up it should bex4 maximum for sse and x8 for avxwhy the avx is not faster than sse3 for those who say stop using your stuff use intel math kernel library i reply i would not because i want a small executable file and i only need to use simd for this specific case not elsewhere,['c++'] +932704,is there any better way to calculate n 8 3 5 i need to take a size t volume and calculate this result in a size tsize t next volume 8 3 5if this result would overflow a size t then next should be zero the problem is of course that volume 8 3 can overflow while the entire result fits in a size tat the moment i am splitting out the last 4 bits of volume and performing the multiplication addition and division separately my question is can i do better than what i have so far if there is no type larger than size tsize t next volumesize t volume check if the numerator will overflow size t if volume size max 3 8 size t lower upper multiply lower 4 bits by 8 and add 3 lower volume 0xf 8 3 downshift the rest and multiply by 8 upper volume 4 8 divide upper remainder and lower by 5 lower upper 5 4 lower 5 divide upper by 5 upper upper 5 ensure the sum will not overflow size t if upper lower 4 size max 4 return 0 return upper 4 lower else return volume 8 3 5there might be some errors in that code i have not put it through extensive testing yet but i believe all the main ideas are there,['c'] +932710,restore exact innerhtml to dom i would like to save the html string of the dom and later restore it to be exactly the same the code looks something like thisvar stringified documentdocumentelementinnerhtml later after serializing and deserializingdocumentdocumentelementinnerhtml stringifiedthis works when everything is perfect but when the dom is not w3ccomliant there is a problem the first line works fine stringified matches the dom exactly but when i restore from the nonw3ccompliant stringified the browser does some magic and the resulting dom is not the same as it was originallyfor example if my original dom looks likepdivdivpthen the final dom will look likeppdivdivppsince div elements are not allowed to be inside p elements is there some way i can get the browser to use the same html parsing that it does on page load and accept broken html asiswhy is the html broken in the first place the dom is not controlled by meheres a jsfiddle to show the behavior open your consolebody div idasdfp idouterpdiv script typetextjavascript var insert documentcreateelementdiv var text documentcreatetextnodeladygaga insertappendchildtext documentgetelementbyidouterappendchildinsert var e documentgetelementbyidasdf consolelogeinnerhtml einnerhtml einnerhtml consolelogeinnerhtml this is different than 2 lines above scriptbody,"['javascript', 'jquery', 'html']" +932771,java jar memory usage vs class file memory usage i recently changed my large java application to be delivered in jars instead of individual class files i have 405 jars which hold 50 class files my problem is that when i run my programs as jars classpath is a wildcard to get all jars java will continually use more and more memory i have seen the memory go 2gb and it seems like java is not doing stoptheworld garbage collections to keep the memory lower if i run the exact same program against the exploded jars only class files javas memory usage stays much lower 256mb and stays there this is happening in oracles java 8 on windows 7 x64 and windows server x64 why would packaging my application as jars change the memory profile also i have run the program for a long time as jars with the memory maximum limited to 128mb with no problems so i do not have a memory leakwith jar files in classpathwith class files in classpath edit i accepted the answer from k erlandsson because i think it is the best explanation and this is just an ugly quirk of java thanks every one and especially k erlandsson for your help,['java'] +932875,optimize performance of loop i have been profiling a bottleneck in my code a function shown below that gets called several million times i could use tips on increasing the performance the xs numbers were taken from sleepy compiled with visual studio 2013 o2 and other typical release settingsindicies is typically 0 to 20 values and other parameters are the same size bsize indiciessize tempssize tempsksize1 double objectgradientconst size t j 2 const stdvectordouble b 3 const stdvectorsize t indices 4 const stdvectorstdvectordouble temps const5 2327s 6 double sum 07 19216s for size t k indices8 3205s if k j9 21953s sum tempskjbk10 11 32021s return boostmathisfinitesum sum 013 2286s any ideasthanks for the tips guys here were the results i got from the suggestionsi found it interesting that switching to cbegin and cend had such a large impact i guess the compiler is not being as smart as it could there i am happy with the bump but still curious if there is more room here through unrolling or vectorization for those interested here my benchmark for isfinitexboostisfinitexspeed 761164 per mstime 01314 ms 023 msstdisfinitexspeed 266835 per mstime 03748 ms 065 ms,['c++'] +932883,show gif file with glide image loading and caching library i try to show a gif image as loading placeholder in image view with glide library glidewithcontext loadimageurl placeholderrdrawableloading2 asgif crossfade intoimagei try to show this file loading2gifbut get this error error54 86 error cannot find symbol method asgifhow can i show gif file with glide in a imageview,['android'] +932949,branchio link for ios not passing data postinstall but does work for cold launch i have several branch links that are meant to deeplink into my ios app and preload an image into a uiimageview they work properly when the app is installed regardless of whether it is simply in the background or has been terminated however they do not work if the app is not already installed they do properly link to the app store but once the app is installed the parameters do not seem to flow through correctly i say the parameters do not seem to flow through because i cannot find a way to test this since i do not think there is any way to simulate a fresh app install via deeplink in xcode i know i can build from xcode to my phone without the app automatically launching then click the deeplink but by that point the app is already installed on my phone so it defeats the purpose of the test if anyone knows of a way to test app installs via deeplink i would gladly take that information and run with it for a whileheres an example of a deep link that should load a graphic into a shirt design qwdoes anyone know of any known issues with branch not sending data correctly postinstalledit heres what i have got in my appdelegate branch code now i cannot prove that the url is not getting set but homeviewcontroller is not downloading the linked image like it does for nonpostinstall launches and like i mentioned before i do not know how to simulate this situation since the xcode simulator always installs first so i have no opportunity to simulate clicking the link preinstalet branch branch branchgetinstance branchinitsessionwithlaunchoptionslaunchoptions andregisterdeeplinkhandler params error in if error nil if let url paramsproduct picture url as string let url nsurlstring url homeviewcontrollerinjectedimageurl url,['ios'] +933006,is not this switch statement a nonsense i found this weird switch statement in laravel 5 coreswitch countargs case 0 return instancemethod case 1 return instancemethodargs0 case 2 return instancemethodargs0 args1 case 3 return instancemethodargs0 args1 args2 case 4 return instancemethodargs0 args1 args2 args3 default return call user func arrayinstance method argsis there any reason why they possibly decided to build such a thing instead of just using thisreturn call user func arrayinstance method argsany benefits,['php'] +933015,importerror no module named concurrentfuturesprocess i have followed the procedure given in how to use valgrind with python for checking memory leaks in my python code i have my python source under the pathroottestacdatechi have given above path in pythonpath everything is working fine if i run the code with default python binary located under usrbin i need to run the code with the python binary i have build manually which is located underhomeabcdworkspacepyhonbinpythonthen i am getting the following error from concurrentfuturesprocess import processpoolexecutorimporterror no module named concurrentfuturesprocesshow can i solve this,['python'] +933076,get pitch and roll from matrix without singularities i am working on motion simulator with 2 dof pitch roll i am reading transformation matrix from game and i need to get the angles and send to hardware to drive motorssince euler angles have singularities i cannot really use them it behaves like thiswhen it should like thisi prepared online example to better show the issue get euler angles from model matrixvar mat modelmatrixmattransposevar e new threuleresetfromrotationmatrixmat xzyvar v etovector3var pitch vzvar roll vxas far as i understand there are two problems herethere is no yaw axis on simulatoreven if there were yaw axis motors just do not behave like computer graphics ie they need time to get to target positioni have read about gimbal lock and even implemented euler filter but that did not work as expectedmost advices about gimbal lock were to use quaternions but i cannot drive physical motor with quaternion or can iaxis order does not really matter here because changing it will only move singularity from one axis to anotheri need to handle this some other wayi tried multiplying axis vectors by matrix and then using cross and dot product to get angles but that failed too i think there should be also axis reprojection involved to get this right but i could not figure it out but something tells me that this is the right way to do this it was something like this then i came up with different idea i know previous position so maybe do the followingconvert matrix to quaternioncompute difference between current and previous quaternionconvert resulting quaternion to euler anglesadd those angles to static pitch roll and yaw variablesso i tried that and it worked no singularities in any of the directions perfect 360 degree rotation in pitch roll and yaw the perfect solution except it is not the frames did not synchronize so after a while angles were way off from what they should be i have been thinking about some sort of synchronization mechanism but i figured this is not the right wayit looked like this and the same logic but directly with matrices i have searched web high and low i have read dozens of papers and other questionsposts and i just cannot believe nothing really works for my casei might not understand or miss something so here is everything i found and triedlinks code i have put it all together so it is messyi must be missing something or i am looking at this from the wrong angle,['c++'] +933098,how to maintain fragment state without backstack in tab i am trying to save fragment state in onsaveinstancestate but when i go back to fragment it always reloaded again instead of starting from last statei looked into oncreateview and onactivitycreated and it always have onsaveinstancestate as nullpublic void navigatefragmentstring tag fragment fragment boolean shouldadd fragmentmanager manager getsupportfragmentmanager fragmenttransaction ft managerbegintransaction if shouldadd mstacksgettagpushfragment push fragment on stack ftreplaceandroidridtabcontent fragment if shouldadd ftaddtobackstacktag ftcommit as i am unable to use backstack because in tabs back stack is not useful any help would be highly appreciated,['android'] +933109,in cssjavascript how is this iconfont plugin implemented demo at jsfiddlelink href relstylesheetlink relstylesheet hrefscript srcscriptscript srcscripti classmaterialiconsaddii classmaterialiconsreplayiwhat confused me the most is the icons are not implemented by class attribute like i classiconaddi or i classiconreplyi but by the inner text of the i nodewhen i view the i node in the developer tool of chrome they look almost the same and seem inthistinguishable for css selectorif the icon is set by the inner text how could css asign different icons for these i nodesanother thing that i could not understand is how these icons are implemented icon font png or svg it seems that they are implemented by icon font but i cannot find any css declaration likefaflagbefore content f024if the icons is not implemented by the before selector and content attribute how are they implemented,"['javascript', 'jquery', 'html', 'css']" +933146,arraycollection collection of forms index collision in symfony 2 i am using symfony2 to build up my pagewhen i try to update a collection of forms like described in the cookbook entry how to embed a collection of forms i get a collision of the indexes of the frontend and the indexes of the arraycollection in the backendi have got the relation user address onetomany a user wants to createupdatedelete his addresses therefore he can add delete in the frontend with the help of the javascript part new address elements he does the following1 adds new address has index 02 adds new address has index 1 and instantly removes this address again3 adds new address has index 2when he clicks on save button the following code savesupdates the user and its addresses thisempersistuser thisemflushnew addresses for example are then correctly persisted to the databasenow the user wants to update the address eg with index 0when he now clicks on the save button it updates the adress with index 0 but at the same time it adds again the address with index 2 to the database object to better understand the problem i have drawn a small illustration handmade sorry for my bad art skillsnow i have got two times the address with index 1 within my object databasei know why this happens it is because the first index 1 address gets mapped to the arraycollection element number 1 and the second gets mapped to number 2 because of the frontend name index 2 you can say it just fills up the addresses until it reaches the frontend index in the backendbut how can i fix this behaviour site notethis behaviour occurs using ajax requests because if you would reload the page after clicking save button it would reindex the addresses in the frontend correctly with the indexes in the backendmy suggestion to handle that situationreindexing the frontend indexes after clicking save with the server sideindexes is this a clear the only solution for my problem,"['javascript', 'php']" +933193,compile error when using assemblycopyrightattribute or assemblycompanyattribute via codedomprovider i figure something silly is going on as the remaining assembly level attributes can be included just fine but whenever assemblycopywriteattribute or assemblycompanyattribute is declared it results in cs0116 and cs1730 errors given that the code does not contain any method declarations i do not see how cs0116 is applicable and there are no type definitions interspersed so not sure how cs1730 is applicable errorserror number cs0116error text a namespace cannot directly contain members such as fields or methodserror number cs1730error text assembly and module attributes must precede all other elements defined in a file except using clauses and extern alias declarationssource fileusing systemusing systemreflectionusing systemruntimeinteropservicesassembly comvisiblefalseassembly clscompliantfalseassembly assemblycompanymy company this results in a compile time errorassembly guid9d8271d9957f46dcbcc61055137b4fadassembly assemblytitleccda mapassembly assemblydescriptionthe mapping logic to source a cxd and populate a ccdaassembly assemblycopyrightmy company 2015 this results in a compile time errorassembly assemblycultureenusassembly assemblyversion220assembly assemblyfileversion220123assembly assemblyconfigurationdebugassembly assemblymetadataattributebuilt06272015assembly assemblymetadataattributehostjormungandrassembly assemblymetadataattributethe answer42assembly assemblymetadataattributedocument typeccdaassembly assemblymetadataattributedocument spec version20compilation logiccodedomprovider provider codedomprovidercreateprovidercvar source directorygetfilespathcombineenvironmentgetfolderpathenvironmentspecialfolderdesktopcodedomcstolistdumpmap sourceselectifilereadalltextitoarrayvar parameters new compilerparameters generateinmemory true outputassembly stringformatmapdllcounttreatwarningsaserrors true warninglevel 4parametersreferencedassembliesaddmscorlibdllvar results providercompileassemblyfromsourceparameters source,['.net'] +933305,alamofire does not respect timeout interval class apiclient var user user let alamofiremanager alamofiremanager let center nsnotificationcenterdefaultcenter init let configuration nsurlsessionconfigurationdefaultsessionconfiguration configurationtimeoutintervalforrequest 4 seconds configurationtimeoutintervalforresource 4 selfalamofiremanager alamofiremanagerconfiguration configuration func test this does not respect the 4 second time out why selfalamofiremanagerrequestpost constantsapiendpointtest parameters parametersresponsejson req res json error in if let json selfhandleapiresponsereq res res json data json error error,['ios'] +933337,how to json stringify a javascript date and preserve timezone i have a date object that is created by the user with the timezone filled in by the browser like sovar date new date2011 05 07 04 0 0 tue jun 07 2011 040 gmt10 e australia standard timewhen i stringify it though the timezone goes byebyejsonstringifydate 20110606t180zthe best way i can get a iso8601 string while preserving the browsers timezone is by using momentjs and using momentformat but of course that would not work if i am serializing a whole command via something that uses jsonstringify internally in this case angularjsvar command time date contents foo httppostnotesadd commandfor completeness my domain does need both the local time and the offset,['javascript'] +933347,android listview does not refresh by filter in my application i have three fragment with viewpager one of this fragments i have simple arraylist as listview from phones contact list and i am trying to filter that after typing into edittext but does not refresh until softkeyboard is visible and i must have to hide keyboard to refresh list view by filtered stringsfor examplefilter listview by aadaptergetfilterfilteramy adapter public class adaptercontacts extends baseadapter implements filterable private layoutinflater inflater private context context private listcontactlists categoryarraylist private final arraylistcontactlists originallist new arraylistcontactlists private namefilter filter public adaptercontactsarraylistcontactlists array categoryarraylist array public adaptercontactscontext context listcontactlists array thiscontext context inflater layoutinflaterfromthiscontext categoryarraylist array originallistaddallarray override public int getcount return categoryarraylistsize override public contactlists getitemint position return categoryarraylistgetposition override public long getitemidint position return 0 override public view getviewint position view convertview viewgroup parent viewholder mviewholder if convertview null convertview inflaterinflaterlayoutlayout contacts list item null mviewholder new viewholderconvertview convertviewsettagmviewholder else mviewholder viewholder convertviewgettag contactlists item getitemposition mviewholderfillitemsthis item position return convertview private static class ui extends helperui public textview tv person nickname mobile number public textview btn invite message public imageview img contact image public imageview imgv user rank public textview tv contact name public linearlayout ll root public uiview view parseuiview private class viewholder private ui ui public viewholderview view ui new uiview public void fillitemsfinal adaptercontacts adapter final contactlists item final int position uitv contact namesettextitemgetcontact name if itemgetstatus 1 uibtn invite messagesetvisibilityviewgone uiimgv user ranksetvisibilityviewvisible if itemgetrank null textutilsisemptyitemgetrank picassowithgcontextloaditemgetrankintouiimgv user rank uitv person nickname mobile numbersettextitemgetnick name uill rootsetbackgrounddrawablegcontextgetresourcesgetdrawablerdrawableselector button actions if itemgetcontact image null textutilsisemptyitemgetcontact image bitmap bitmap ucgetcontactphotoitemgetmobile number gcontextgetcontentresolver if bitmap null uiimg contact imagesetimagebitmapbitmap else uiimg contact imagesetimagedrawablegcontextgetresourcesgetdrawablerdrawableno avatar else show user avatar from web picassowithgcontextloaditemgetcontact imageintouiimg contact image uiimg contact imagesetimagebitmapbitmapfactorydecodefilegdir image itemgetcontact image else uill rootsetbackgrounddrawablegcontextgetresourcesgetdrawablerdrawableselector invite actions uibtn invite messagesetvisibilityviewvisible uiimgv user ranksetvisibilityviewgone uibtn invite messagesettextucgetstringrstringinvite person uibtn invite messagesetbackgrounddrawablegcontextgetresourcesgetdrawablerdrawableshape invite button default uitv person nickname mobile numbersettextitemgetmobile number bitmap bitmap ucgetcontactphotoitemgetmobile number gcontextgetcontentresolver if bitmap null uiimg contact imagesetimagebitmapbitmap else uiimg contact imagesetimagedrawablegcontextgetresourcesgetdrawablerdrawableno avatar override public filter getfilter if filter null filter new namefilter return filter public class namefilter extends filter override protected filterresults performfilteringcharsequence constraint filterresults results new filterresults string searchtext constrainttostringtolowercase arraylistcontactlists newlist filterlistbasedonsearchtextsearchtext resultsvalues newlist resultscount newlistsize return results private arraylistcontactlists filterlistbasedonsearchtextstring constraint arraylistcontactlists newlist new arraylistcontactlists int l originallistsize for int i 0 i l i contactlists namelist originallistgeti if namelistgetcontact nametostringcontainsconstraint newlistaddnamelist return newlist suppresswarningsunchecked override protected void publishresultscharsequence constraint filterresults results categoryarraylist arraylistcontactlists resultsvalues notifydatasetchanged softkeyboard status status in manifest for activitymain this class have view pager with three fragment activity androidnameactivitiesactivitybootstrap androidwindowsoftinputmodeadjustpan androidscreenorientationportraitother way to do filter in fragment without adapters abilityedt sampleaddtextchangedlistenernew textwatcher override public void ontextchangedcharsequence s int start int before int count override public void beforetextchangedcharsequence s int start int count int after override public void aftertextchangededitable s string text edt samplegettexttostring filtertext public void filterstring chartext drinksclear if chartextlength 0 drinksaddallcontact list else for contactlists wp contact list if wpgetcontact namecontainschartext drinksaddwp contact listclear contact listaddalldrinks adapternotifydatasetchangedlistview succesful filtered by when i close or hide softkeyboard that refresh with nw items,['android'] +933424,javascript strict mode not working as expected var test function use strict var mapnames name city name coordlat latitute for var key in mapnames var names if mapnameskey name mapnameskey else name key consolelognametestin the code above i made a mistake by declaring variable names and using name instead i thought strict mode would catch it but it did not should not this throw an error in this case,['javascript'] +933425,why is there a separate instance of vmdalvikart for every app on android as the title stateswhy is there a separate instance of vmdalvikart for every app on androidthe need for itand what would have happened if the android os had chosen a model where a single vm runs all the apps,['android'] +933597,on navigation drawer item click new list view in navigation drawer i am trying to get the following functionality in navigation drawer but i am not able to break it scenarioi am having a navigation drawer on clicking any item in the navigation drawer i need a list view to open with multiple item in it which could be further selected for some kind of functionalityi am also attaching the image which will define my need in appropriate manner please have a kind reference of the image to get what i basically and actually needany help would be appreciated,['android'] +933711,js how to create a random picker that would not pick the same item twice i am making a random hero picker for a game and this tool will randomly pick heroes for the player i want to add a feature where it picks the heroes for the whole team of 3 but i do not know how to make it so that the same hero would not be pick more than once here is a sample of my code for picking a random hero for a player thank you in advancescript languagejavascriptfunction pickherovar imagenumber 16 var randomnumber mathrandom var rand1 mathround imagenumber1 randomnumber 1images new arrayimages1 images2 images3 images4 images5 images6 images7 images8 images9 images10 images11 images12 images13 images14 images15 images16 var image imagesrand1documentteam1hero1src imagescript,['javascript'] +933870,why cannot i goto default or goto case x within a switch selection structure section 681 of c11 or c99 or section 361 of c89 all seem to indicate that default and case x where x is some constantexpression are examples of labeled statements alongside identifierstyle labels that are suitable for use with gotoi am aware that i could simply place an identifierstyle label directly following the default or case x labels that is not what this question is about i am more curious as to whether there is any actual rationale behind prohibiting this kind of behaviourif it were possible to declare default labels outside of a switch selection structure then i would understand as there would be some conflict between where the goto inside of the switch selection structure is intended to aim however section 641 of c11 or c99 or 311 of c89 prohibits the use of default as anything other than a keyword and 681 restricts its use further to switch structures only or generic structures in c11 which are irrelevant herei would also understand if multiple possibly nested switch structures each with default or case x labels introduced ambiguity however the scope of those labels seems to be restricted to within their innermost surrounding switch structures and referring to any identifier outside of its scope is clearly an error requiring a diagnostic at compiletimehas this been thiscussed in any standard documents eg the rationale is there any kind of explanation for this behaviour other than it is because it is or because the spec says so if so what is that explanation,['c'] +933882,download an object url in a lollipop web view in an android lollipop web view i want to let the user download a generated txt file store some text in a data urlvar dataurl windowurl windowwebkiturlcreateobjecturl new blobhello world create a link that lets the user download the text file as hellotxtvar downloadlink documentcreateelementadownloadlinksetattributehref dataurldownloadlinkinnerhtml click to download working with david on this i did the same thing fyi setting the download attribute just makes hitting the link nop ie do nothing at all in the web view so i omitted it john thisplay the linkdocumentgetelementbyidcontainerappendchilddownloadlinkon the android java side i wrote a downloadlistener that tries to use downloadmanager to download the filepackage comsomesideprojectsimport androidwebkitdownloadlistener a download listener that lets users download files from the web view public class customdownloadlistener implements downloadlistener private mainactivity currentactivity override public void ondownloadstart string url string useragent string contentthisposition string mimetype long contentlength androidutillogdlogger url url useragent useragent contentthisposition contentthisposition mimetype mimetype contentlength contentlength androidneturi source androidneturiparseurl make a new request androidappdownloadmanagerrequest request new androidappdownloadmanagerrequestsource appears the same in notification bar while downloading string filename getfilenamecontentthisposition requestsetdescription this project will be saved in your downloads folder as filename requestsettitlefilename add cookie on request header for authenticated web app string cookiecontent getcookiefromappcookiemanagersourcegethost requestaddrequestheadercookie cookiecontent if androidosbuildversionsdk int androidosbuildversion codeshoneycomb requestallowscanningbymediascanner requestsetnotificationvisibility androidappdownloadmanagerrequestvisibility visible notify completed save the file in the downloads folder of sdcard requestsetdestinationinexternalpublicdir androidosenvironmentdirectory downloads filename get the download service and enqueue the file androidappdownloadmanager manager androidappdownloadmanager thiscurrentactivitygetapplication getsystemserviceandroidcontentcontextdownload service managerenqueuerequest public string getfilenamestring contentthisposition string filename contentthispositionsplitfilename return filename1replacefilename replace trim public string getcookiefromappcookiemanagerstring url androidwebkitcookiemanager cookiemanager androidwebkitcookiemanagergetinstance if cookiemanager null return null string rawcookieheader null extract setcookie header value from android app cookiemanager for this url rawcookieheader cookiemanagergetcookieurl if rawcookieheader null return null return rawcookieheader public void setcurrentactivitymainactivity currentactivity thiscurrentactivity currentactivity this java error surfaces when i click on the link in the web view javalangillegalargumentexception can only download httphttps uris blobfile3af566c1cfb0b24382ba1690bab359fcc5 at androidappdownloadmanagerrequestinitdownloadmanagerjava429i got the same error when i hosted my page on an http server so the error seems to stem from the blob portionwhat are my options now how can i download the data stored at the object url ultimately i want to download a much larger blob 50mbi could pass the data to an object injected into addjavascriptinterface but i would have to base64 encode my blob and decode on the java side since only primitives and simple types can be passed encoding into base64 via javascript crashes chromium for 50mb blobs i get out of memory errors upon calling readasdataurlhow else could i download the 50mb blob from the web view or transfer the 50mb binary data from javascript to android java details on use case i am using javascript to generate a 50mb video file blob with mime type videoxmswmv this generations completely clientside i am confident that step works since i can download the file on a desktop browser as well as through the normal chrome app via an object url i then want to somehow let the user store that file on hisher external storage maybe in dcim or downloadson an unrelated note i would like also to do the same thing with audio wav files for say generating ring tones to store in ringtones,['android'] +933901,how to change hint text color of textinputlayout hi i am using textinputlayout in my app i want to set hint text color and floating label colorboth focused and unfocused to white i have tried below code androidsupportdesignwidgettextinputlayout androidlayout widthfill parent androidlayout heightwrap content androidthemestyletextlabelandroidsupportv7widgetappcompatedittext androidlayout widthfill parent androidlayout heightwrap content androidhinthiandroidididedit id androidsupportv7widgetappcompatedittextandroidsupportdesignwidgettextinputlayoutstyle nametextlabel parenttextappearanceappcompathint color and label color in false stateitem nameandroidtextcolorhintcolorcolor nameitem item nameandroidtextsize20spitemlabel color in true state and bar color false and true stateitem namecoloraccentcolorcolor nameitemitem namecolorcontrolnormalcolorcolor nameitemitem namecolorcontrolactivatedcolorcolor nameitemstyleit is working properly for lollipop but not for lower versionshow can i achieve the same in lower versions as well,['android'] +933921,setstatusbarhidden is deprecated in ios 90 i am upgrading my code from ios 8 to ios 9 i have a code snippet in my programuiapplication applicationname setstatusbarhiddenyesi am getting the warning setstatusbarhidden is deprecated in ios 90 use uiviewcontroller prefersstatusbarhidden if i just replace setstatusbarhidden with prefersstatusbarhidden i get instance method not foundcan someone please suggest me how to solve this problem,['objective-c'] +933968,can detect system proxy settings in java application but not in junit windows 7java 180 45eclipse marsif you have system proxy set up to http the below will print http only if it runs from main method of java applicationhowever if it is called from junit 4 test in eclipse it always prints directit is also noted that defining djavanetusesystemproxiestrue in eclipse run configurations arguments vm arguments the test simply hangsany idea what is going onthanks a lotpublic void printsystemproxy systemsetpropertyjavanetusesystemproxies true try final listproxy list proxyselectorgetdefaultselectnew urihttpfoobar for final proxy proxy list systemoutprintlnproxytype catch final urisyntaxexception e throw new illegalstateexceptione,['java'] +933974,viewflipper animation does not work on first swipe on my main activity i have a viewflipper with three child views after the app is first started when i do the first right to left swipe the view changes but it does not have the slide animation after the first swipe the animation works as expected when swiping in either direction i am following this tutorial the code i use is public boolean ontoucheventmotionevent touchevent switch toucheventgetaction when user first touches the screen case motioneventaction down lastx toucheventgetx break case motioneventaction up float currentx toucheventgetx left to right swipe if lastx currentx if mviewflippergetthisplayedchild 0 break mviewflippersetinanimationthis ranimin from left mviewflippersetoutanimationthis ranimout to right mviewflippershowprevious right to left swipe if lastx currentx if mviewflippergetthisplayedchild mviewflippergetchildcount 1 break mviewflippersetinanimationthis ranimin from right mviewflippersetoutanimationthis ranimout to left mviewflippershownext break return falsewhen i debug the code i do not see any differences between when the animation is working and when it is not also i see this behavior on an actual device and the emulator what did i miss i can post the animation xml files and the view xml if they are needededitthe only way i am able to get this to work as expected is to set the following in the oncreate method mviewflippersetinanimationthis ranimin from right mviewflippersetoutanimationthis ranimout to left mviewflippersetflipinterval10 mviewflipperstartflippingi then call stopflipping on the first swipe the interesting thing to me is that the animation works on the first swipe with these changes even if the first autoflip has not occurred however if i simply set the animation in the oncreate method without calling the startflipping method it still does not have the animation on the first swipe can someone offer an explanation as to why this behavior occurs,['android'] +933988,java 8 find index of minimum value from a list say i have a list with elements 34 11 98 56 43using java 8 streams how do i find the index of the minimum element of the list eg 1 in this casei know this can be done easily in java using listindexofcollectionsminlist however i am looking at a scala like solution where we can simply say list34 11 98 56 43zipwithindexmin 2 to get the index of minimum value is there anything that can be done using streams or lambda expressions say java 8 specific features to achieve the same resultnote this is just for learning purpose i do not have any problem in using collections utility methods,['java'] +933991,es6 call static method within a class i have this class which does an internal call to a static methodexport class generalhelper extends basehelper static isenv return configgetenvname env static isprod return generalhelperisprod are there any keywords i can use to replace the class name in the line belowgeneralhelperisprodin php we have self static etc does es6 provide anything similar to thesety,['javascript'] +934035,stop collapsingtoolbar from collapsing after nestedscrollview runs out of content to scroll in android how can i get the collapsingtoolbar to stop collapsing if the nestedscrollview runs out of content to scroll this functionality currently exists in the contacts app on android 511 however in my code when the nestedscrollview stops scrolling the toolbar continues to collapse leaving gap between the twoxml version10 encodingutf8androidsupportdesignwidgetcoordinatorlayout xmlnsandroid xmlnsapp xmlnstools androidididmain content androidlayout widthmatch parent androidlayout heightmatch parent androidsupportdesignwidgetappbarlayout androidididappbar androidlayout widthmatch parent androidlayout height256dp androidthemestylethemeoverlayappcompatdarkactionbar androidsupportdesignwidgetcollapsingtoolbarlayout androidididcollapsing toolbar androidlayout widthmatch parent androidlayout heightmatch parent applayout scrollflagsscrollexituntilcollapsed appcontentscrimattrcolorprimary appexpandedtitlemarginstartdimencontent padding normal appexpandedtitlemarginend64dp androidsupportv7widgettoolbar androidididtoolbar androidlayout widthmatch parent androidlayout heightattractionbarsize apptitletextappearancestyleactionbartitletext applayout collapsemodepin androidsupportdesignwidgetcollapsingtoolbarlayout androidsupportdesignwidgetappbarlayout androidsupportv4widgetnestedscrollview androidlayout widthmatch parent androidlayout heightmatch parent applayout behaviorstringappbar scrolling view behavior androidscrollbarsnone linearlayout androidlayout widthmatch parent androidlayout heightwrap content androidorientationvertical androidpaddingbottomdimenkeyline 2 androidsupportv7widgetcardview androidlayout widthmatch parent androidlayout heightwrap content androidlayout margindimenelement spacing normal include layoutlayoutviewloadingindeterminate linearlayout androidididprogress status container stylestyleconnectionfieldcontainer androidlayout widthmatch parent androidlayout heightwrap content androidlayout gravitycenter vertical androidorientationvertical androidvisibilityvisible spinner androidididprogress status androidlayout widthmatch parent stylestyletextconnectionfield textview stylestyletextconnectionlabel androidtextstringmobilecustomerconnectprogrestatus linearlayout androidsupportv7widgetcardview androidsupportv7widgetcardview androidlayout widthmatch parent androidlayout heightwrap content androidlayout margindimenelement spacing normal linearlayout androidlayout widthmatch parent androidlayout heightwrap content androidorientationvertical linearlayout androidididemail1 container stylestyleconnectionfieldcontainer androidorientationhorizontal toolsvisibilityvisible linearlayout androidlayout width0dp androidlayout heightwrap content androidlayout gravitycenter vertical androidlayout weight1 androidorientationvertical textview androidididemail1 stylestyletextconnectionfield toolstext textview stylestyletextconnectionlabel androidtextstringmobilecustomerconnectemail1 linearlayout imagebutton androidididaction email1 stylestylebuttonconnectionaction androidsrcdrawableic email black 24dp linearlayout linearlayout androidididemail2 container stylestyleconnectionfieldcontainer androidorientationhorizontal toolsvisibilityvisible linearlayout androidlayout width0dp androidlayout heightwrap content androidlayout gravitycenter vertical androidlayout weight1 androidorientationvertical textview androidididemail2 stylestyletextconnectionfield toolstext textview stylestyletextconnectionlabel androidtextstringmobilecustomerconnectemail2 linearlayout imagebutton androidididaction email2 stylestylebuttonconnectionaction androidsrcdrawableic email black 24dp linearlayout linearlayout androidididphone day container stylestyleconnectionfieldcontainer androidorientationhorizontal toolsvisibilityvisible linearlayout androidlayout width0dp androidlayout heightwrap content androidlayout gravitycenter vertical androidlayout weight1 androidorientationvertical textview androidididphone day stylestyletextconnectionfield toolstext80151234 textview stylestyletextconnectionlabel androidtextstringmobilecustomerconnectphoneday linearlayout imagebutton androidididaction call phone day stylestylebuttonconnectionaction androidsrcdrawableic call black 24dp imagebutton androidididaction text phone day stylestylebuttonconnectionaction androidsrcdrawableic textsms black 24dp linearlayout linearlayout androidsupportv4widgetnestedscrollview androidsupportdesignwidgetfloatingactionbutton androidididcreate reminder androidlayout widthwrap content androidlayout heightwrap content applayout anchoridcollapsing toolbar applayout anchorgravitybottomrightend appborderwidth0dp appelevationdimenshadow size androidlayout marginbottomdimenkeyline 1 androidlayout marginrightdimenkeyline 1 androidsrcdrawableic alarm add white 24dp appbackgroundtintattrcoloraccent androidsupportdesignwidgetcoordinatorlayout,['android'] +934101,how to tell jsonnet to deserialize jarray to a list when object type is provided let us have the following classclass foo public object anythis class accepts anything in the field anywhen i calljsonconvertdeserializeobjectfooany 5any contains systemint64however when i calljsonconvertdeserializeobjectfooany 5any contains newtonsoftjsonlinqjarrayhow to configure jsonnet so that in this case any would contain listobjectclarification there could be anything i can calljsonconvertdeserializeobjectfooany cor jsonconvertdeserializeobjectfooany c 5more clarificationi would like to tell somehow to jsonnet maybe using jsonserializersettingswhen you encounter object and json contains an array deserialize that to for instance listobject,"['c#', '.net']" +934107,ie11 object does not support property or method includes javascript windowlocationhash i am checking the url to see if it contains or includes a in it to control the hash pop state in the window all other browsers are not having an issue only iethe debugger gives me this error when i try to load in this way object does not support property or method includesi get no error when i load the page in tghrough the popstate documentreadyfunctione ifwindowlocationhash var hash ifwindowlocationhashincludes alerti have a hash windowlocationhashsubstringwindowlocationhashindexof 0windowlocationhashindexof else hash windowlocationhash if hashdrs hashdrp hashdffi hashdci hashdcp hashdrp hashdrma hasheics hashorg hashcontentaddclasspageonremoveclasspageoff else homecontentaddclasspageonremoveclasspageoff else homecontentaddclasspageonremoveclasspageoff windowonpopstate function var hash ifwindowlocationhashincludes hash windowlocationhashsubstringwindowlocationhashindexof 0windowlocationhashindexof else hash windowlocationhash if hashdrs hashdrp hashdffi hashdci hashdcp hashdrp hashdrma hasheics hashorg thisnavigatetarget hashcontent ifwindowlocationhashincludes else locationhref locationhref else thisnavigatetarget homecontent,['javascript'] +934129,count occurences of digit x in range 0n so i am trying to write a python function that takes in two arguments and and num and counts the occurrences of n between 0 and num for example countoccurrences155 should be 2countoccurrences1005 should be 20i made a simple iterative solution to this problemdef countoccurrencesnumn count0 for x in range0num1 count counthelperstrxn return countdef counthelpernumbern count0 for digit in number if digitn count 1 return countthis ran into obvious problems if i tried to call countoccurrences105what my question is is how can i make this more efficient i want to be able to handle the problem fairly fast and avoid out of memory errors here is my first pass at a recursive solution trying to do thisdef countoccurencenum n if num0n return 1 else if lennum 1 return countoccurencenum1n countoccurencestrintnum1n else return 0,['python'] +934258,extends a would not accept as child classes i am working with android studio and i keep getting a problem i do not know how to solve i do not know whether it is a problem with android studio with java or a mistake a makei have a class whose constructor is the followingpublic makequerycallablearraylist extends a i try to create an object of that class with the following linescallablearraylistb callable new callablearraylistb makequery makequery new makequerycallableof course class b extends a double checkedbut when i call the constructor the ide tells me that it expects another type of argumentwhat mistake am i making thanks for all the help,"['java', 'android']" +934279,how to programmatically count the number of files in an archive using python in the program i maintain it is done as in count the files in the archivelength 0command urs l slt s upathto7zexe srcfileins err popencommand stdoutpipe stdinpipe startupinfostartupinfocommunicateins stringiostringioinsfor line in ins length 1inscloseis it really the only way i cannot seem to find any other command but it seems a bit odd that i cannot just ask for the number of fileswhat about error checking would it be enough to modify this toproc popencommand stdoutpipe stdinpipe startupinfostartupinfoout procstdout countreturncode procwaitif returncode raise exceptionufailed reading number of files from srcfileor should i actually parse the output of popen edit interested in 7z rar zip archives that are supported by 7zexe but 7z and zip would be enough for starters,['python'] +934301,what is the use for buckets interface in stdunordered map i have been watching this video from cppcon 2014 and thiscovered that there is an interface to access buckets underneath stdunordered map now i have a couple of questionsare there any reasonable examples of the usage of this interfacewhy did the committee decide to define this interface why typical stl container interface was not enough,['c++'] +934303,dnx web command throwing unable to resolve project error after publishing from vs2015 this is about an obsolete prerelease version of net corei have created a basic project in prerelease aspnet 5 later on was renamed to aspnet core using a betapreview of visual studio 2015 i have published the project to a file system and am trying to run it from there using the command dnx webthe error that results is unable to resolve project i have checked that dnvm is using the default framework my published directory has web webcmd wroot and approot folders is there anything else i should be checkingi am using aspnet core 100beta4 clr,['asp.net'] +934406,what is jstcache and why it is being added to my html tags while using firebug i have noticed an attribute name jstcache is added to some of my html tags while it is not visible in the source of the page in firebug i see following html langen jstcache0 head body jstcache0 div classmydiv jstcache0 i google result shows it is related to jstemplate i am not using it and i do not know why it is being added to my code,"['javascript', 'html']" +934410,does calling randomnormal on an array of values add noise i saw this pattern in someones codeimport numpy as np create arrayxx nplinspace00 10 num100 add noisexx nprandomnormalxxand it seems to add some noise to each value of the array but i cannot find any documentation for this whats happening what determines the properties ie scaling of the noise is the given value being treated as the mean ie the loc parameter of each sampling from the normal thistributioni would also be very curious to know why this behavior does not seem to be covered in the documentation,['python'] +934421,how to find gradle lintoptions document for android i got is not translated in missingtranslationerror in my android project i searched by google find something works as abortonerror false and a document about lintoptions but i do not want to ignore all lint errors so i copied xml created by eclipse as lintconfig filedefaultlintxml and it worksi want to know where can i find the full document about all lint options that can set in the lintxmlthanks for any help,['android'] +934521,how to subscribe to an event on a service in angular2 i know how to raise an event with the eventemitter i can also attach a method to be called if i have a component like thiscomponentwithevent myeventmymethodevent when i have a component like this everything works great i moved some logic into a service and i need to raise an event from inside the service what i did was thisexport class myservice myevent eventemitter new eventemitter somemethodthatwillraiseevent thismyeventnextdata fun i have a component that needs to update some value based on this event but i cannot seem to make it work what i tried was thisannotationsexport class mycomponent constructormyservice myservice myservice is injected properly and i already use methodsshared data on this myservicemyeventon on is not a method not working myservicemyeventsubscribe subscribe is not a method not working how do i make mycomponent subscribe to the event when the service that raises it is not a componenti am on on 200alpha28edit modified my working example to actually work so focus can be put on the notworking part example code,['javascript'] +934526,android java binder failed binder transaction i am trying to download an image from service and thisplay it in activity but i keep getting java binder failed binder transactionthis is my service codepublic class downloadimageservice extends service overridepublic int onstartcommandintent intent int flags int startid new loadimageasyncexecuteintentgetstringextratype return servicestart not stickyoverridepublic ibinder onbindintent intent return nullprivate class loadimageasync extends asynctaskstring void string byte compressedimage bitmap bmp string img override protected void onpreexecute superonpreexecute override protected string doinbackgroundstring params try url url new urlimgurl bmp bitmapfactorydecodestreamurlopenconnectiongetinputstream compressedimage compressbitmapcompresimagebmp img base64encodetostringcompressedimage base64default catch ioexception e compressedimage null bmp null eprintstacktrace return null override protected void onpostexecutestring s superonpostexecutes if compressedimage null intent i new intentgetapplicationcontext othercampaignactivityclass isetflagsintentflag activity new task iputextraimage byte img startactivityi stopservicenew intentgetapplicationcontext downloadimageserviceclass compress functionpublic static byte compresimagebitmap b bytearrayoutputstream stream new bytearrayoutputstream bcompressbitmapcompressformatpng 100 stream byte compressedbytearray streamtobytearray return compressedbytearraymy activitypublic class otheractivity extends appcompatactivity private imageview ivoverrideprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity other iv imageview findviewbyidridimageviewcam byte bytearray base64decodegetintentgetstringextraimage byte base64default byte bytearray getintentgetextrasgetbytearrayimage byte bitmap bitmap bitmapfactorydecodebytearraybytearray 0 bytearraylength ivsetimagebitmapbitmapoverridepublic void onbackpressed superonbackpressed finishwhat is the issue in the code the activity is not startingthe app is not crashing i only get this in logcat 0630 123836800 292292comvtenit ejavabinderi1 failed binder transaction it is probably due to large bitmap i guess,['android'] +934529,browser notifications invoked website so lately on some websites i have seen these browser level invoked notifications that popup even if you did not open that certain website you have to allow those notifications to be thisplayed and then they are pretty much everywhere even when you first open a browser without tabsi do not know how to use for these browser level notifications invoked by my website a name and some code examples would be appreciated i do not even know what programming language it is written in assuming javascriptthis is a screenshot of what i am talking about top right corneras you see they still appear even though the browser is minimized,['javascript'] +934545,set sqlite as database for unit testing in laravel 51 i am trying to setup unit testing in laravel 51 following the documentation i see thislaravel is built with testing in mind in fact support for testing with phpunit is included out of the boxandwhen running tests laravel will automatically set the configuration environment to testing laravel automatically configures the session and cache to the array driver while testing meaning no session or cache data will be persisted while testingwhich is awesome but how do i tell laravel to use sqlite database connection when tests are ranonly thing there is in configdatabasephp is this commented code we might use this connection for unit testssqlite driver sqlite database storage pathdatabasesqlite prefix we might use this is there a way to set this globally for all test do i need to set the connecton in every test caseany help appreciated,['php'] +934560,virtualenv command not found i could not get virtualenv to work despite various attempts i installed virtualenv on mac os x usingpip install virtualenvand have also added the path into my bash profile every time i try to run the virtualenv command it returnsbash virtualenv command not foundevery time i run pip install virtualenv it returnsrequirement already satisfied use upgrade to upgrade virtualenv in libraryframeworkspythonframeworkversions27libpython27sitepackagesi understand that in mac the virtualenv should be correctly installed in usrlocalbinthe virtualenv is indeed installed in usrlocalbin but whenever i try to run the virtualenv command the command is not found i have also tried to run the virtualenv command in the directory usrlocalbin and it gives me the same result bash virtualenv command not foundthese are the paths i added to my bash profileexport pathpathusrlocalbinexport pathpathusrlocalbinpythonexport pathpathlibraryframeworkpythonframeworkversion27libsitepackagesany workarounds for this why is this the case,['python'] +934597,authentication no longer works after get to post change i used the php code below to successfully get the timeline of a twitter user rest api oauth 10anow i would like to follow a user on twitter i needed to change the get to a post request for it and now the code no longer workserrorcode 32 message could not authenticate youwhat needs to be changed to make it work php x i removed the valuestoken xtoken secret x consumer key xconsumer secret xhost apitwittercom not workingmethod postpath 11friendshipscreatejson api call path worksmethod get path 11statusesuser timelinejson api call pathquery array query parameters screen name twitter count 2oauth array oauth consumer key consumer key oauth token token oauth nonce stringmt rand a stronger nonce is recommended oauth timestamp time oauth signature method hmacsha1 oauth version 10oauth array maprawurlencode oauth must be encoded before sortingquery array maprawurlencode queryarr array mergeoauth query combine the values then sortasortarr secondary sort valueksortarr primary sort key http build query automatically encodes but our parameters are already encoded and must be by this point so we undo the encoding stepquerystring urldecodehttp build queryarr url httpshostpath mash everything together for the text to hashbase string methodrawurlencodeurlrawurlencodequerystring same with the keykey rawurlencodeconsumer secretrawurlencodetoken secret generate the hashsignature rawurlencodebase64 encodehash hmacsha1 base string key true this time were using a normal get query and were only encoding the query params without the oauth paramsurl http build queryqueryoauthoauth signature signature do not want to abandon all that workksortoauth probably not necessary but twitters demo does it also not necessary but twitters demo does this toofunction add quotesstr return str oauth array mapadd quotes oauth this is the full value of the authorization lineauth oauth urldecodehttp build queryoauth if youre doing post you need to skip the get building above and instead supply query parameters to curlopt postfieldsoptions array curlopt httpheader arrayauthorization auth curlopt postfields postfields curlopt header false curlopt url url curlopt returntransfer true curlopt ssl verifypeer false do our businessfeed curl initcurl setopt arrayfeed optionsjson curl execfeedcurl closefeedtwitter data json decodejsonprint rtwitter data,['php'] +934599,intdef android support annontation with jackson deserializing using jacksonannotations along with android support annotations my pojo isjsonignorepropertiesignoreunknown truepublic class schedule public static final int sunday 0 public static final int monday 1 public static final int tuesday 2 public static final int wednesday 3 public static final int thursday 4 public static final int friday 5 public static final int saturday 6 private integer weekday public schedule weekday public integer getweekday return weekday public void setweekdayweekday integer weekday thisweekday weekday retentionretentionpolicyruntime intdefsunday monday tuesday wednesday thursday friday saturday public interface weekday from backed i get objectscheduleweekdaymondaywhat i want is to map weekday to it is integer value defined in constants is there any way i can achieve this update the main purpose is optimization you should strictly avoid using enums on android like it said here,['android'] +934605,where does my embedded python stdout go consider the following mweinclude pythonhinclude stdiohint mainvoid printftest 1n py initialize printftest 2n pyrun simplestringprinttest 3 printftest 4n return 0when i compile and run this as normal i get the expected output testtest 1test 2test 3test 4but when i redirect the output i get nothing from the python code test cattest 1test 2test 4what is happening and more importantly how do i get my python output written to stdout like expected,['python'] +934654,flexflow column wrap how to set containers width equal to content i have a container and several inner divs container thisplay inlineflex flexflow column wrap maxheight 500pxelement width 200px height 200px margin 10px background 0now i have 3 flex columnswhat i expectedcontainers width becomes equal to the sum of columns width 660pxwhat i gotcontainers width becomes equal to the first columns widththe penwhy when i change flexdirection to row and maxheight to maxwidth everything goes just as expected is there a way to make my containers width equal to content width,['css'] +934664,exact quran font with thajweed ios i have an ios quran app project i have tested several arabic fonts for my quran app text contents but it have some difference in thajweed marks other than the original quran text with thajweed marks please check the images i want to know which font is the correct one for quranic text with complete thajweed marksedit i have tried so many fonts like alquranalkareemttfuthmanichafsttfetc i do not think it will be usefull if iam listing all here i want the quran font with complete and exact thajweed marksit show like this in my appit should be like this as it is the correct onenote for persons who do not know arabic it is not two different font styles its thajweed rule shows different,['ios'] +934689,scroll does not work in nestedscrollview when try to scroll from views with click events i am using a nestedscrollview in a layout and am attempting to use the new coordinatorlayout from the design support library for collapsingtoolbarlayoutmy layout file looks like thisxml version10 encodingutf8androidsupportdesignwidgetcoordinatorlayout xmlnsandroid xmlnsapp androidlayout widthmatch parent androidlayout heightmatch parent androidsupportdesignwidgetappbarlayout androidididappbar androidlayout widthmatch parent androidlayout height200dp androidfitssystemwindowstrue androidthemestylethemeoverlayappcompatdarkactionbar androidsupportdesignwidgetcollapsingtoolbarlayout androidididcollapsing toolbar androidlayout widthmatch parent androidlayout heightwrap content androidfitssystemwindowstrue appcontentscrimattrcolorprimary appexpandedtitlemarginstart48dp applayout scrollflagsscrollexituntilcollapsed appexpandedtitlemarginend64dp imageview androidlayout widthmatch parent androidlayout height200dp androidscaletypecentercrop androidsrcdrawableimage load default big androidsupportv7widgettoolbar androidididanim toolbar androidlayout widthmatch parent androidlayout heightattractionbarsize applayout collapsemodepin apopupthemestylethemeoverlayappcompatlight androidsupportv7widgettoolbar androidsupportdesignwidgetcollapsingtoolbarlayout androidsupportdesignwidgetappbarlayout androidsupportv4widgetnestedscrollview androidididnestedscrollvw androidlayout widthmatch parent androidlayout heightmatch parent applayout scrollflagsscrollenteralways androidfitssystemwindowstrue applayout behaviorstringappbar scrolling view behavior relativelayout androidlayout widthmatch parent androidlayout heightmatch parent androidclickablefalse androidfitssystemwindowstrue linearlayout androidididchangepasswordbuttoncontainer androidlayout widthmatch parent androidlayout heightwrap content androidorientationvertical button androidididchangepasswordexpand androidlayout widthmatch parent androidlayout height55dp androidbackgrounddrawableback img androidtextchange your password androidtextcolorcolorwhite androidtextstylebold linearlayout linearlayout androidididchangepasswordcontainer androidlayout widthmatch parent androidlayout heightwrap content androidlayout belowidchangepasswordbuttoncontainer androidlayout centerinparenttrue androidorientationvertical androidpadding10dp textview androidlayout widthwrap content androidlayout heightwrap content androidlayout gravitycenter horizontal androidtextedit your password androidtextcolorcolororange edittext androidididetusername androidlayout widthmatch parent androidlayout heightwrap content androidlayout margintop10dp androidbackgrounddrawableedittext default bg androiddrawableleftdrawablepassword icon androiddrawablerightdrawabletick androidhint old password androidpadding12dp androidpasswordtrue androidtextcolorhintb5b5b5 edittext androidididetpass androidlayout widthmatch parent androidlayout heightwrap content androidlayout margintop10dp androidbackgrounddrawableedittext default bg androiddrawableleftdrawablepassword icon androiddrawablerightdrawablecross androidhint new password androidpadding12dp androidpasswordtrue androidtextcolorhintb5b5b5 radiobutton androidlayout widthwrap content androidlayout heightwrap content androidpaddingbottom20dp androidpaddingtop20dp androidtextshow password button androidididbtnsingin androidlayout widthmatch parent androidlayout heightwrap content androidlayout margin4dp androidbackgrounddrawablelogin button background androidpaddingbottom8dp androidpaddingtop8dp androidtextdone androidtextcolorcolorwhite androidtextstylebold linearlayout linearlayout androidididdealertodealercontainer androidlayout widthmatch parent androidlayout heightwrap content androidlayout belowidchangepasswordcontainer androidorientationvertical button androidididdealertodealerexpand androidlayout widthmatch parent androidlayout height55dp androidbackgrounddrawableback img androidtextdealer to dealer platform no androidtextcolorcolorwhite androidtextstylebold linearlayout linearlayout androidlayout widthmatch parent androidlayout heightwrap content androidlayout belowiddealertodealercontainer androidlayout centerinparenttrue androidorientationvertical androidpadding10dp textview androidlayout widthwrap content androidlayout heightwrap content androidlayout gravitycenter horizontal androidtextedit number androidtextcolorcolororange edittext androidididdealertodealerno androidlayout widthmatch parent androidlayout heightwrap content androidlayout margintop10dp androidbackgrounddrawableedittext default bg androiddrawableleftdrawablepassword icon androiddrawablerightdrawabletick androidhint 56546789 androidpadding12dp androidpasswordtrue androidtextcolorhintb5b5b5 button androidididdealertodealernodone androidlayout widthmatch parent androidlayout heightwrap content androidlayout margin4dp androidbackgrounddrawablelogin button background androidpaddingbottom8dp androidpaddingtop8dp androidtextdone androidtextcolorcolorwhite androidtextstylebold linearlayout relativelayout androidsupportv4widgetnestedscrollviewandroidsupportdesignwidgetcoordinatorlayoutwhen i try to scroll sometimes it does not workreason for this is other elements of layout with click events are consuming the touch eventbasically edittext radiobutton button are consuming touch eventsany suggestions to solve this problem,['android'] +934698,error in executing oracle stored procedure using c i am trying to execute an oracle stored procedure 1 input and 2 out parameters using c my table contain 3 columns an integer id and 2 varchar2 type columnsthis is table definition create table testtable id int not null fname varchar2200 lname varchar2200 constraint pk primary key idthis is my stored procedurecreate or replace procedure testp tempid in testtableidtype tempname out testtablenametype templname out testtablelnametype as begin select name lname into tempname templname from testtable where id tempidendhere is the code to execute this procedure from ctry int32 id 1 string fname lname using oragetoracleconnection oracledataaccessclientoraclecommand cmd new oracledataaccessclientoraclecommandtestp oragetoracleconnection cmdcommandtype commandtypestoredprocedure cmdparametersaddtempid oracledataaccessclientoracledbtypeint32parameterdirectioninputvalue id cmdparametersaddtempname oracledataaccessclientoracledbtypevarchar2200parameterdirectionoutputvalue fname cmdparametersaddtemplname oracledataaccessclientoracledbtypevarchar2200parameterdirectionoutputvalue lname cmdexecutenonquery catch exception ex messageboxshowextostring this is the exception generatedoracledataaccessclientoracleexception ora06502 plsql numeric or value error ora06512 at usmandbatestp line 9can anyone help me,['c#'] +934701,implementation of dynamic initialization for global variables and static member variables in c i have some questions about the implementation of variable initialization in c in regards to the linking and executable module loading process my main concern is with dynamic initialization of global variables and static member variables wherein the initialization process involves the execution of code i am looking for the answer to address my questions for both windows and linuxi already understand that in the case of static initializationthe initial value is placed into its own section during compilation the sections are mapped into memory by the os module loaderthe variable is assigned the location of the initial values memory address with the application of a dir32 type relocationhere are my questionswhat information does the compiler place into a generated object file relating to dynamic initialization of global variables for the linker to use please go into as much detail as possible about related sections and generated symbols what differences are there for static member variables compared to nonstatic global variableswhat information does the linker place into the final linked module during the linking process so that the os module loader is able to correctly initialize all variables including dynamically initialized globalstatic member variables that make calls to functions as part of initialization how is the function that needs to be executed during dynamic variable initialization mapped to the particular variable that needs to be initialized with that codewhen an executable or dynamically linked module is loaded how is dynamic initialization of variables performed does the implementation of c11 constant expressions marked by the constexpr specifier involve any special considerations compared to the implementation of regular static member variables and functions i have a specific example case i am hoping the answer could refer to within the framework of the above questions since i felt that having a concrete example of taking an object file identifying the relevant sectionssymbols and how this particular code would be linked and loaded so that successful initialization of the static variable could be carried out would make the answer easier to understand this example is for windows using msvc as the compiler please mention specific differences for gcclinux wherever they exist here is a simple example of c code involving a regular variable and a static member variable which from my understanding needs to be dynamically initialized by the os loader before main because it makes a call to a function as part of its initializationclass testpublic static int testfunction return 10 static int membervarint testmembervar testtestfunctionint foo return 5int var fooint mainint argc char argv var testmembervar return 0and here is a dump of the sections and symbols for the object file produced by msvc using the above code compiled in debug mode the dump was created with llvmreadobj a utility which comes with llvmclangfile sourceobjformat coffi386arch i386addresize 32bitsections section number 1 name drectve 2e 64 72 65 63 74 76 65 virtualsize 0x0 virtualaddress 0x0 rawdatasize 65 pointertorawdata 0x2bc pointertorelocations 0x0 pointertolinenumbers 0x0 relocationcount 0 linenumbercount 0 characteristics 0x100a00 image scn align 1bytes 0x10 image scn lnk info 0x200 image scn lnk remove 0x800 section number 2 name debugs 2e 64 65 62 75 67 24 53 virtualsize 0x0 virtualaddress 0x0 rawdatasize 3380 pointertorawdata 0x2fd pointertorelocations 0x1031 pointertolinenumbers 0x0 relocationcount 8 linenumbercount 0 characteristics 0x421040 image scn align 1bytes 0x10 image scn cnt initialized data 0x40 image scn mem thiscardable 0x20 image scn mem read 0x40 section number 3 name debugt 2e 64 65 62 75 67 24 54 virtualsize 0x0 virtualaddress 0x0 rawdatasize 136 pointertorawdata 0x1081 pointertorelocations 0x0 pointertolinenumbers 0x0 relocationcount 0 linenumbercount 0 characteristics 0x421040 image scn align 1bytes 0x10 image scn cnt initialized data 0x40 image scn mem thiscardable 0x20 image scn mem read 0x40 section number 4 name textdi 2e 74 65 78 74 24 64 69 virtualsize 0x0 virtualaddress 0x0 rawdatasize 60 pointertorawdata 0x1109 pointertorelocations 0x1145 pointertolinenumbers 0x0 relocationcount 3 linenumbercount 0 characteristics 0x60501020 image scn align 16bytes 0x50 image scn cnt code 0x20 image scn lnk comdat 0x10 image scn mem execute 0x20 image scn mem read 0x40 section number 5 name debugs 2e 64 65 62 75 67 24 53 virtualsize 0x0 virtualaddress 0x0 rawdatasize 216 pointertorawdata 0x1163 pointertorelocations 0x123b pointertolinenumbers 0x0 relocationcount 5 linenumbercount 0 characteristics 0x42101040 image scn align 1bytes 0x10 image scn cnt initialized data 0x40 image scn lnk comdat 0x10 image scn mem thiscardable 0x20 image scn mem read 0x40 section number 6 name textdi 2e 74 65 78 74 24 64 69 virtualsize 0x0 virtualaddress 0x0 rawdatasize 60 pointertorawdata 0x126d pointertorelocations 0x12a9 pointertolinenumbers 0x0 relocationcount 3 linenumbercount 0 characteristics 0x60501020 image scn align 16bytes 0x50 image scn cnt code 0x20 image scn lnk comdat 0x10 image scn mem execute 0x20 image scn mem read 0x40 section number 7 name debugs 2e 64 65 62 75 67 24 53 virtualsize 0x0 virtualaddress 0x0 rawdatasize 204 pointertorawdata 0x12c7 pointertorelocations 0x1393 pointertolinenumbers 0x0 relocationcount 5 linenumbercount 0 characteristics 0x42101040 image scn align 1bytes 0x10 image scn cnt initialized data 0x40 image scn lnk comdat 0x10 image scn mem thiscardable 0x20 image scn mem read 0x40 section number 8 name textmn 2e 74 65 78 74 24 6d 6e virtualsize 0x0 virtualaddress 0x0 rawdatasize 42 pointertorawdata 0x13c5 pointertorelocations 0x0 pointertolinenumbers 0x0 relocationcount 0 linenumbercount 0 characteristics 0x60501020 image scn align 16bytes 0x50 image scn cnt code 0x20 image scn lnk comdat 0x10 image scn mem execute 0x20 image scn mem read 0x40 section number 9 name debugs 2e 64 65 62 75 67 24 53 virtualsize 0x0 virtualaddress 0x0 rawdatasize 192 pointertorawdata 0x13ef pointertorelocations 0x14af pointertolinenumbers 0x0 relocationcount 5 linenumbercount 0 characteristics 0x42101040 image scn align 1bytes 0x10 image scn cnt initialized data 0x40 image scn lnk comdat 0x10 image scn mem thiscardable 0x20 image scn mem read 0x40 section number 10 name textmn 2e 74 65 78 74 24 6d 6e virtualsize 0x0 virtualaddress 0x0 rawdatasize 42 pointertorawdata 0x14e1 pointertorelocations 0x0 pointertolinenumbers 0x0 relocationcount 0 linenumbercount 0 characteristics 0x60501020 image scn align 16bytes 0x50 image scn cnt code 0x20 image scn lnk comdat 0x10 image scn mem execute 0x20 image scn mem read 0x40 section number 11 name debugs 2e 64 65 62 75 67 24 53 virtualsize 0x0 virtualaddress 0x0 rawdatasize 204 pointertorawdata 0x150b pointertorelocations 0x15d7 pointertolinenumbers 0x0 relocationcount 5 linenumbercount 0 characteristics 0x42101040 image scn align 1bytes 0x10 image scn cnt initialized data 0x40 image scn lnk comdat 0x10 image scn mem thiscardable 0x20 image scn mem read 0x40 section number 12 name textmn 2e 74 65 78 74 24 6d 6e virtualsize 0x0 virtualaddress 0x0 rawdatasize 39 pointertorawdata 0x1609 pointertorelocations 0x0 pointertolinenumbers 0x0 relocationcount 0 linenumbercount 0 characteristics 0x60501020 image scn align 16bytes 0x50 image scn cnt code 0x20 image scn lnk comdat 0x10 image scn mem execute 0x20 image scn mem read 0x40 section number 13 name debugs 2e 64 65 62 75 67 24 53 virtualsize 0x0 virtualaddress 0x0 rawdatasize 224 pointertorawdata 0x1630 pointertorelocations 0x1710 pointertolinenumbers 0x0 relocationcount 5 linenumbercount 0 characteristics 0x42101040 image scn align 1bytes 0x10 image scn cnt initialized data 0x40 image scn lnk comdat 0x10 image scn mem thiscardable 0x20 image scn mem read 0x40 section number 14 name bss 2e 62 73 73 00 00 00 00 virtualsize 0x0 virtualaddress 0x0 rawdatasize 8 pointertorawdata 0x0 pointertorelocations 0x0 pointertolinenumbers 0x0 relocationcount 0 linenumbercount 0 characteristics 0xc03080 image scn align 4bytes 0x30 image scn cnt uninitialized data 0x80 image scn mem read 0x40 image scn mem write 0x80 section number 15 name rtcimz 2e 72 74 63 24 49 4d 5a virtualsize 0x0 virtualaddress 0x0 rawdatasize 4 pointertorawdata 0x1742 pointertorelocations 0x1746 pointertolinenumbers 0x0 relocationcount 1 linenumbercount 0 characteristics 0x40301040 image scn align 4bytes 0x30 image scn cnt initialized data 0x40 image scn lnk comdat 0x10 image scn mem read 0x40 section number 16 name rtctmz 2e 72 74 63 24 54 4d 5a virtualsize 0x0 virtualaddress 0x0 rawdatasize 4 pointertorawdata 0x1750 pointertorelocations 0x1754 pointertolinenumbers 0x0 relocationcount 1 linenumbercount 0 characteristics 0x40301040 image scn align 4bytes 0x30 image scn cnt initialized data 0x40 image scn lnk comdat 0x10 image scn mem read 0x40 section number 17 name crtxcu 2e 43 52 54 24 58 43 55 virtualsize 0x0 virtualaddress 0x0 rawdatasize 8 pointertorawdata 0x175e pointertorelocations 0x1766 pointertolinenumbers 0x0 relocationcount 2 linenumbercount 0 characteristics 0x403040 image scn align 4bytes 0x30 image scn cnt initialized data 0x40 image scn mem read 0x40 symbols symbol name compid value 14776701 section image sym absolute 1 basetype null 0x0 complextype null 0x0 storageclass static 0x3 auxsymbolcount 0 symbol name feat00 value 2147484049 section image sym absolute 1 basetype null 0x0 complextype null 0x0 storageclass static 0x3 auxsymbolcount 0 symbol name drectve value 0 section drectve 1 basetype null 0x0 complextype null 0x0 storageclass static 0x3 auxsymbolcount 2 auxsectiondef length 65 relocationcount 0 linenumbercount 0 checksum 0x0 number 0 selection 0x0 auxsectiondef length 0 relocationcount 0 linenumbercount 0 checksum 0x0 number 0 selection 0x0 symbol name debugs value 0 section debugs 2 basetype null 0x0 complextype null 0x0 storageclass static 0x3 auxsymbolcount 2 auxsectiondef length 3380 relocationcount 8 linenumbercount 0 checksum 0x0 number 0 selection 0x0 auxsectiondef length 112874624 relocationcount 0 linenumbercount 0 checksum 0x0 number 0 selection 0x0 symbol name debugt value 0 section debugt 3 basetype null 0x0 complextype null 0x0 storageclass static 0x3 auxsymbolcount 2 auxsectiondef length 136 relocationcount 0 linenumbercount 0 checksum 0x0 number 0 selection 0x0 auxsectiondef length 0 relocationcount 0 linenumbercount 0 checksum 0x0 number 0 selection 0x0 symbol name textdi value 0 section textdi 4 basetype null 0x0 complextype null 0x0 storageclass static 0x3 auxsymbolcount 2 auxsectiondef length 60 relocationcount 3 linenumbercount 0 checksum 0x46c8586b number 0 selection any 0x2 auxsectiondef length 2651074843 relocationcount 0 linenumbercount 0 checksum 0x0 number 0 selection 0x0 symbol name debugs value 0 section debugs 5 basetype null 0x0 complextype null 0x0 storageclass static 0x3 auxsymbolcount 2 auxsectiondef length 216 relocationcount 5 linenumbercount 0 checksum 0x0 number 4 selection associative 0x5 assocsection textdi 4 auxsectiondef length 726561912 relocationcount 0 linenumbercount 0 checksum 0x0 number 0 selection 0x0 symbol name textdi value 0 section textdi 6 basetype null 0x0 complextype null 0x0 storageclass static 0x3 auxsymbolcount 2 auxsectiondef length 60 relocationcount 3 linenumbercount 0 checksum 0x46c8586b number 0 selection any 0x2 auxsectiondef length 1313174712 relocationcount 0 linenumbercount 0 checksum 0x0 number 0 selection 0x0 symbol name debugs value 0 section debugs 7 basetype null 0x0 complextype null 0x0 storageclass static 0x3 auxsymbolcount 2 auxsectiondef length 204 relocationcount 5 linenumbercount 0 checksum 0x0 number 6 selection associative 0x5 assocsection textdi 6 auxsectiondef length 3135640214 relocationcount 0 linenumbercount 0 checksum 0x0 number 0 selection 0x0 symbol name textmn value 0 section textmn 8 basetype null 0x0 complextype null 0x0 storageclass static 0x3 auxsymbolcount 2 auxsectiondef length 42 relocationcount 0 linenumbercount 0 checksum 0xb9575122 number 0 selection noduplicates 0x1 auxsectiondef length 936864182 relocationcount 0 linenumbercount 0 checksum 0x0 number 0 selection 0x0 symbol name debugs value 0 section debugs 9 basetype null 0x0 complextype null 0x0 storageclass static 0x3 auxsymbolcount 2 auxsectiondef length 192 relocationcount 5 linenumbercount 0 checksum 0x0 number 8 selection associative 0x5 assocsection textmn 8 auxsectiondef length 3843792410 relocationcount 0 linenumbercount 0 checksum 0x0 number 0 selection 0x0 symbol name textmn value 0 section textmn 10 basetype null 0x0 complextype null 0x0 storageclass static 0x3 auxsymbolcount 2 auxsectiondef length 42 relocationcount 0 linenumbercount 0 checksum 0x2aafa5e4 number 0 selection any 0x2 auxsectiondef length 919462443 relocationcount 0 linenumbercount 0 checksum 0x0 number 0 selection 0x0 symbol name debugs value 0 section debugs 11 basetype null 0x0 complextype null 0x0 storageclass static 0x3 auxsymbolcount 2 auxsectiondef length 204 relocationcount 5 linenumbercount 0 checksum 0x0 number 10 selection associative 0x5 assocsection textmn 10 auxsectiondef length 1658743834 relocationcount 0 linenumbercount 0 checksum 0x0 number 0 selection 0x0 symbol name textmn value 0 section textmn 12 basetype null 0x0 complextype null 0x0 storageclass static 0x3 auxsymbolcount 2 auxsectiondef length 39 relocationcount 0 linenumbercount 0 checksum 0x9f9044f9 number 0 selection noduplicates 0x1 auxsectiondef length 607079010 relocationcount 0 linenumbercount 0 checksum 0x0 number 0 selection 0x0 symbol name debugs value 0 section debugs 13 basetype null 0x0 complextype null 0x0 storageclass static 0x3 auxsymbolcount 2 auxsectiondef length 224 relocationcount 5 linenumbercount 0 checksum 0x0 number 12 selection associative 0x5 assocsection textmn 12 auxsectiondef length 3159278302 relocationcount 0 linenumbercount 0 checksum 0x0 number 0 selection 0x0 symbol name testfunctiontestsahxz value 0 section textmn 10 basetype null 0x0 complextype function 0x2 storageclass external 0x2 auxsymbolcount 0 symbol name emembervartest2hayaxxz value 0 section textdi 4 basetype null 0x0 complextype function 0x2 storageclass static 0x3 auxsymbolcount 0 symbol name fooyahxz value 0 section textmn 8 basetype null 0x0 complextype function 0x2 storageclass external 0x2 auxsymbolcount 0 symbol name evaryaxxz value 0 section textdi 6 basetype null 0x0 complextype function 0x2 storageclass static 0x3 auxsymbolcount 0 symbol name main value 0 section textmn 12 basetype null 0x0 complextype function 0x2 storageclass external 0x2 auxsymbolcount 0 symbol name rtc checkesp value 0 section image sym undefined 0 basetype null 0x0 complextype function 0x2 storageclass external 0x2 auxsymbolcount 0 symbol name rtc initbase value 0 section image sym undefined 0 basetype null 0x0 complextype function 0x2 storageclass external 0x2 auxsymbolcount 0 symbol name rtc shutdown value 0 section image sym undefined 0 basetype null 0x0 complextype function 0x2 storageclass external 0x2 auxsymbolcount 0 symbol name bss value 0 section bss 14 basetype null 0x0 complextype null 0x0 storageclass static 0x3 auxsymbolcount 2 auxsectiondef length 8 relocationcount 0 linenumbercount 0 checksum 0x0 number 0 selection 0x0 auxsectiondef length 0 relocationcount 0 linenumbercount 0 checksum 0x0 number 0 selection 0x0 symbol name membervartest2ha value 4 section bss 14 basetype null 0x0 complextype null 0x0 storageclass external 0x2 auxsymbolcount 0 symbol name var3ha value 0 section bss 14 basetype null 0x0 complextype null 0x0 storageclass external 0x2 auxsymbolcount 0 symbol name rtcimz value 0 section rtcimz 15 basetype null 0x0 complextype null 0x0 storageclass static 0x3 auxsymbolcount 2 auxsectiondef length 4 relocationcount 1 linenumbercount 0 checksum 0x0 number 0 selection any 0x2 auxsectiondef length 1569749662 relocationcount 0 linenumbercount 0 checksum 0x0 number 0 selection 0x0 symbol name rtc initbasertcimz value 0 section rtcimz 15 basetype null 0x0 complextype null 0x0 storageclass static 0x3 auxsymbolcount 0 symbol name rtctmz value 0 section rtctmz 16 basetype null 0x0 complextype null 0x0 storageclass static 0x3 auxsymbolcount 2 auxsectiondef length 4 relocationcount 1 linenumbercount 0 checksum 0x0 number 0 selection any 0x2 auxsectiondef length 1278087628 relocationcount 0 linenumbercount 0 checksum 0x0 number 0 selection 0x0 symbol name rtc shutdownrtctmz value 0 section rtctmz 16 basetype null 0x0 complextype null 0x0 storageclass static 0x3 auxsymbolcount 0 symbol name crtxcu value 0 section crtxcu 17 basetype null 0x0 complextype null 0x0 storageclass static 0x3 auxsymbolcount 2 auxsectiondef length 8 relocationcount 2 linenumbercount 0 checksum 0x0 number 0 selection 0x0 auxsectiondef length 3724741121 relocationcount 0 linenumbercount 0 checksum 0x0 number 0 selection 0x0 symbol name membervarinitializertest2p6axxza value 0 section crtxcu 17 basetype null 0x0 complextype null 0x0 storageclass static 0x3 auxsymbolcount 0 symbol name varinitializer value 4 section crtxcu 17 basetype null 0x0 complextype null 0x0 storageclass static 0x3 auxsymbolcount 0 thank you very much for considering my question a thorough answer would be greatly appreciated,['c++'] +934704,flawless way of preventing element from being affected by external css i am doing a script that will be implemented in multiple pages and i am trying to prevent the elements it generates from being styled by the pages css some people have the great idea of writing css like thisbodyminheight200pxso i found this new css propertyelem all initial and it seems to work quite well but i have already experienced some problems and i bet there may be many that i do not know aboutfor example for internet explorer even ie11 to reset minheight you cannot use initial you must use 0 therefore allinitial does not override minheightdo you know of a better way to do this or at least a list of properties i should take care of individuallyedit to better explain what i want i will do this in js i mentioned before it is a script and i am not only interested in solutions i would like to know why that solution works and why is better than the one i offer also i am aware of performance so i would rather like to use the minimun amount of rules if posible i would like to know for example which are the most dangerous ones,['css'] +934722,rails 4 integrating you tube youtube it gem i am trying to incorporate you tube in my rails 4 appi want users to be able to upload a video file which will then be posted on my you tube channeli am using rails 4 with youtube it gem i have been trying to follow this tutorial my file structure has project model and a video model the associations areprojectrbhas one video accepts nested attributes for videovideorb belongs to projectmy video table has a boolean attribute called include video fcollection radio buttons include video true yes false no first last item wrapper class fixradio class radioinline createproject responseproject if it is true then i want to reveal the field where users add a link to the video attribute is called link ffile field link the video form in which i ask these questions is a partial the partial is inside the project form which has other questions i also have a partial view which has the container for the you tube clip as shown in the tutorialthe view partial is included in my project show page as if projectvideoinclude video render videosparticulars end my project controller hasdef new project projectnew projectvideo videonewend def show authorise project project projectfindparamsid creator userfindprojectcreator id creator profile creatorprofile projectvideo videonew endmy project controller also has white labelled attributes from my video table as does my video controller def project params paramsrequireprojectpermit video attributes include video linkmy video controller has def show respond withvideo end def create video videonewvideo params videoproject id video paramsproject id end def video params paramsvideopermitinclude video link project id endmy videorb hasclass video activerecordbase associations belongs to project belongs to program belongs to proposal belongs to profile belongs to user scopes validations yt link format ayoutubevuwembedwatchvvzi validates link presence true format yt link format class methods callbacks before create do uid linkmatchyt link format selfuid uid2 if uid uid2 if selfuidto slength 11 selferrorsaddlink is invalid false elsif videowhereuid selfuidany selferrorsaddlink is not unique false else get additional info end end instance methods private methods def get additional info begin client youtubeitoauth2clientnewdev key envyt developer key video clientvideo byuid selftitle videotitle selfduration parse durationvideoduration selfauthor videoauthorname selflikes videoratinglikes rescue selftitle selfduration 0 selfauthor selflikes 0 selfthislikes 0 end end def parse durationd hr d 3600floor min d hr 3600 60floor sec d hr 3600 min 60floor hr 0 hrto s if hrto i 10 min 0 minto s if minto i 10 sec 0 secto s if secto i 10 hrto s minto s secto s endendi had a related problem and got help from this post rails 4 with you tubehowever it is created a new problem and i do not know if it is advancing my progress toward a solutionthe bit that is new from a suggestion made by a user on the other posted question is to add a show line to my projects controller for the video when i try this i get this errorfailed to save the new associated videowhen i try to make an entirely new project which has the video form partial within it i get an error saving the form it says the video link is not valid i am selecting a mov file from my hard drivei then changed the validation in my videorb to validates link format yt link format allow blank true allow nil trueie removing presence true and adding blank and nil but i still get that errorhow do i approach figuring this out,['ruby-on-rails'] +934723,should i put log4jproperties file into library i have a library project this project uses log4j for loggingshould i put log4jproperties into generated jarif it is not a good practice could you tell me why,['java'] +934778,how to fire event after 3 sec of hovering i have a div and i want to fire an event only after user continuous hovers his mouse for 3 sec my code does not work well because it fires right after hover and does not waitcode inner picmouseenterfunction settimeoutfunction alerttesting 30mouseleavefunction alertfinish,"['javascript', 'jquery', 'html']" +934809,test if method in classa has been called from another method in classa it is possible to test if a method has been called using moq and dependency injection however is it possible to test if one method in a class calls another within the same class for example i want to test that if i log a certain exception that an information message is logged as wellthe method ispublic void errorstring message exception exception long logid 0 var int32 intlogid infoid was converted to an int so that it would fit in the log logid int32 errormessage exception int32this was my attempt at unit testing it the test fails is there any way that it can it be donevoid logging an error with a long id also logs info var mock new mockilogger var testedclass new logger var counter 0 testedclasserrortest counter new exceptiontest counter int64maxvalue mockverifym minfoitisanystring itisanyintsince the info and error methods are in the same class classa i do not believe i can pass classa as a dependency into classa so does it not need tested,['c#'] +934818,how to use another class as a class template specialization i have a hybridlock class that spin tries a lock for a compile time fixed number of spins before falling back to blocking on a stdmutex until the lock becomes availablesimplifiedinclude mutextemplateunsigned spin limitclass hybrid lock public void lock forunsigned i0ispin limiti ifthismmutextry lock return thismmutexlock void unlock thismmutexunlock private stdmutex mmutexin the special case of spin limit0 this falls back to being a plain stdmutex ie no visible spinsso i have specialized that totemplateclass hybrid lock0 public stdmutex it works fine but is that the approved way of specializing class templates to be another preexisting template,['c++'] +934855,angularjs performance issue with timer fired i am building a pretty huge angular app my problem is the memory leaks resulting in page freezeon clicking a button my app opens up a popupwith help of custom directive the content of this popup is dynamically appended and the popup is called with http from the local fileit works fine i have used chrome developer tools to come up with the following as per what timeline gave meas you can see the timer is fired for a long time before the render happens and the time of this gets more and more when the user do it multiple timesclosing popup and reopen again unless he goes to some other page and come back or refresh the pageso how can i destroy all the previous timers or what has to be done to collect the garbageor is it something else that has to be done,['javascript'] +934918,how to implement material design in java gui swingswt i have seen lots technologies are implementing googles material design into guis and some great frameworks are also came into being for web using jscss i seen libs for implementing material design for c forms and even for ios but i wonder is there any lib or resource to implement material design in java gui swingswt that will be a great thing to know about it,['java'] +934925,mingww64s gcc and address sanitizer installing mingww64 51 i find fsanitizeaddress is available it compiles fine and when it starts linking i get thousands ofundefined reference to asan report load1undefined reference to asan report load4i googled and found libasan referenced various places but also comments that when you include fsanitizeaddress it automatically includes that library for linking i searched the mingww64 51 install dirctory for asan and it was not found anywherewhat do i need to add on to use address sanitizing features in mingww64 thank you,['c++'] +934986,java assignments query case 1byte b 7 why do not i need to cast 7 to byte in this case byte b byte7systemoutprintlnboutput 7case 2static void funbyte b systemoutprintlnbpublic static void mainstring args fun7 compiler gives error because a cast is missing hereoutputcompilation error method funbyte is not applicable for the argument intmy question is how come in case 1 7 is implicitly cast to byte from an int while in case 2 it is forcing the programmer to cast it explicitly7 is still in the range of byteplease suggest,['java'] +935081,is module guaranteed to be defined during class creation i was reading some code that looked basically like thisclass fobject class name module replace to me that looked really weird module what is that so i went and looked at the python datamodel a quick search shows that module is a property of class objects and of function objects however there is no module available in the global namespace as can easily be verified by just trying to look at it and observing the nameerror that results i decided to chalk this up to implementation specific behavior but as a last check i decided to test with other implementations i have handy it turns out that this code executes with1cpython 276cpython 340jython 253pypy 221 python 273my question is whether this behavior is actually defined anywhere in the language reference i am not sure why i would want to but could i safely rely on module being in the class creation namespace or did all the implementors just decide to do this the same way1all linux but i doubt that matters,['python'] +935129,android studio is not generating zip aligned apk i am using android studio 122my sdk is well updated and buildtools version installed is 2201build generate signed apki only get appreleaseunalignedapk in appbuildoutputsapki have already googled and triedcopy pasting zipalignexe from buildtools folder to i sdktools ii sdkplatformtoolsadding zipalignenabled true under buildtypes in buildgradlegradle zipalign task not workingplease help solve this issue i want to zipalign using android studiothis is my first app i am trying to publish,['android'] +935163,javascript checking surrounding table cells im making the game called dots and boxesthere are a bunch of dots on a gridtable tr td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd tr tr td classgaptd td classhline onclickaddlinethistd td classgaptd td classhline onclickaddlinethistd td classgaptd td classhline onclickaddlinethistd td classgaptd td classhline onclickaddlinethistd td classgaptd td classhline onclickaddlinethistd td classgaptd td classhline onclickaddlinethistd td classgaptd trtablewhen you click on one side of the box it turns blackfunction addlineobj consolelogcalled if objstylebackgroundcolor black objstylebackgroundcolor black changeturn once you click on the fourth side closing the box the box turns the color of the player who clicked the fourth sidecurrently the players have to manually click the box to change its color however i would like it to automatically fill the box with the color when all four sides are black around the boxhow can i use a function in javascript to check if a the line above below left and right of a box is filled in blackvar playerturn blue changeturn var number 0 function addlineobj consolelogcalled if objstylebackgroundcolor black objstylebackgroundcolor black changeturn function fillboxobj if playerturn blue objstylebackgroundcolor red else if playerturn red objstylebackgroundcolor blue function changeturn if playerturn red playerturn blue documentgetelementbyidturnstylecolor blue else if playerturn blue playerturn red documentgetelementbyidturnstylecolor red consolelogplayerturn documentgetelementbyidturninnerhtml playerturn s turn h3 fontfamily arialtable bordercollapse collapsevline width 10px height 60pxbox width 60px height 60pxhline width 60px height 10pxgap width 10px height 12px backgroundcolor blackvlinehover hlinehover backgroundcolor blackh3 idturnh3table tr td classgaptd td classhline onclickaddlinethistd td classgaptd td classhline onclickaddlinethistd td classgaptd td classhline onclickaddlinethistd td classgaptd td classhline onclickaddlinethistd td classgaptd td classhline onclickaddlinethistd td classgaptd td classhline onclickaddlinethistd td classgaptd tr tr td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd tr tr td classgaptd td classhline onclickaddlinethistd td classgaptd td classhline onclickaddlinethistd td classgaptd td classhline onclickaddlinethistd td classgaptd td classhline onclickaddlinethistd td classgaptd td classhline onclickaddlinethistd td classgaptd td classhline onclickaddlinethistd td classgaptd tr tr td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd tr tr td classgaptd td classhline onclickaddlinethistd td classgaptd td classhline onclickaddlinethistd td classgaptd td classhline onclickaddlinethistd td classgaptd td classhline onclickaddlinethistd td classgaptd td classhline onclickaddlinethistd td classgaptd td classhline onclickaddlinethistd td classgaptd tr tr td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd tr tr td classgaptd td classhline onclickaddlinethistd td classgaptd td classhline onclickaddlinethistd td classgaptd td classhline onclickaddlinethistd td classgaptd td classhline onclickaddlinethistd td classgaptd td classhline onclickaddlinethistd td classgaptd td classhline onclickaddlinethistd td classgaptd tr tr td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd tr tr td classgaptd td classhline onclickaddlinethistd td classgaptd td classhline onclickaddlinethistd td classgaptd td classhline onclickaddlinethistd td classgaptd td classhline onclickaddlinethistd td classgaptd td classhline onclickaddlinethistd td classgaptd td classhline onclickaddlinethistd td classgaptd tr tr td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd tr tr td classgaptd td classhline onclickaddlinethistd td classgaptd td classhline onclickaddlinethistd td classgaptd td classhline onclickaddlinethistd td classgaptd td classhline onclickaddlinethistd td classgaptd td classhline onclickaddlinethistd td classgaptd td classhline onclickaddlinethistd td classgaptd tr tr td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd td classbox onclickfillboxthistd td classvline onclickaddlinethistd tr tr td classgaptd td classhline onclickaddlinethistd td classgaptd td classhline onclickaddlinethistd td classgaptd td classhline onclickaddlinethistd td classgaptd td classhline onclickaddlinethistd td classgaptd td classhline onclickaddlinethistd td classgaptd td classhline onclickaddlinethistd td classgaptd trtable,"['javascript', 'html', 'css']" +935165,material tablayout elevation not working for some reason the elevation attribute does not seem to be working on the new tablayout in the material design support library any ideasxmlxml version10 encodingutf8linearlayout xmlnsandroidandroidlayout widthmatch parentandroidlayout heightmatch parentandroidorientationverticalandroidsupportdesignwidgettablayout androidididtab layout androidlayout widthmatch parent androidlayout heightattractionbarsize androidelevation6dp androidsupportv4viewviewpager androidididview pager androidlayout widthmatch parent androidlayout height0dp androidlayout weight1 linearlayouthooked up like this in a parent fragmentviewpager viewpager viewpager viewfindviewbyidridview pagertablayout tablayout tablayout viewfindviewbyidridtab layoutapageradapter apageradapter new apageradaptergetchildfragmentmanagerviewpagersetadapterapageradaptertablayoutsetupwithviewpagerviewpagerimagethe activity has a toolbar but this is outside of the fragment and should not affect the tablayouts ability to have a shadowrelevant activity xmllinearlayout xmlnsandroidxmlnstoolsandroidlayout widthmatch parentandroidlayout heightmatch parentandroidorientationverticaltoolscontextcombluckappsappinfomanageruimainactivityandroidsupportv7widgettoolbar androidididtoolbar androidlayout widthmatch parent androidlayout heightwrap content androidbackgroundattrcolorprimary androidelevation6dp androidminheightattractionbarsize toolsignoreunusedattribute framelayout androidididcontainer androidlayout widthmatch parent androidlayout height0dp androidlayout weight1 linearlayout,['android'] +935362,is the jpa embedded annotation mandatory i have tried omitting the embedded annotation and still the fields have been embedded in the table i cannot find anything which would say that the embedded annotation is optional is it or is it not optionalthe following codeembeddablepublic class address string city string streetentitypublic class person string name embedded it seems that it works even if this annotation is missing address addressgenerates always the same tableperson name city streeteven if i do not specify embeddedmy configurationjboss eap 640hibernatejpa20api101finalredhat3jarthe jpa specification saysjavaxpersistenceembeddedspecifies a persistent field or property of an entity whose value is an instance of an embeddable class the embeddable class must be annotated as embeddable javaxpersistenceembeddablespecifies a class whose instances are stored as an intrinsic part of an owning entity and share the identity of the entity each of the persistent properties or fields of the embedded object is mapped to the database table for the entity,['java'] +935394,hog features for blocks only i am trying to calculate hog features for block only i explored hogcpp listed under opencvmodulegpusrc below is the code that i change to computer the features of block onlyvoid cvgpuhogdescriptorgetdescriptorsconst gpumat img size win stride gpumat descriptors int descr format cv assertwin stridewidth block stridewidth 0 win strideheight block strideheight 0 computeblockhistogramsimg give block back const size t block hist size getblockhistogramsize size blocks per win numpartswithinwin size block size block stride size wins per img numpartswithinimgsize win size win stride descriptorscreatewins per imgarea static castintblocks per winarea block hist size cv 32f switch descr format case descr format row by row hogextract descrs by rowswin sizeheight win sizewidth block strideheight block stridewidth win strideheight win stridewidth imgrows imgcols block histsptrfloat descriptors break case descr format col by col hogextract descrs by colswin sizeheight win sizewidth block strideheight block stridewidth win strideheight win stridewidth imgrows imgcols block histsptrfloat descriptors break default cv errorcv stsbadarg unknown descriptor format here is the computeblockhistograms code as well void cvgpuhogdescriptorcomputeblockhistogramsconst gpumat img computegradientimg grad qangle size t block hist size getblockhistogramsize size blocks per img numpartswithinimgsize block size block stride block histscreate1 block hist size blocks per imgarea cv 32f block hists getbuffer1 static castintblock hist size blocks per imgarea cv 32f block hists buf hogcompute histsnbins block stridewidth block strideheight imgrows imgcols grad qangle floatgetwinsigma block histsptrfloat hognormalize histsnbins block stridewidth block strideheight imgrows imgcols block histsptrfloat floatthreshold l2hysedit i am including getdescriptor function as well from hogcppvoid cvgpuhogdescriptorgetdescriptorsconst gpumat img size win stride gpumat descriptors int descr format cv assertwin stridewidth block stridewidth 0 win strideheight block strideheight 0 computeblockhistogramsimg const size t block hist size getblockhistogramsize size blocks per win numpartswithinwin size block size block stride size wins per img numpartswithinimgsize win size win stride descriptorscreatewins per imgarea static castintblocks per winarea block hist size cv 32f switch descr format case descr format row by row hogextract descrs by rowswin sizeheight win sizewidth block strideheight block stridewidth win strideheight win stridewidth imgrows imgcols block histsptrfloat descriptors break case descr format col by col hogextract descrs by colswin sizeheight win sizewidth block strideheight block stridewidth win strideheight win stridewidth imgrows imgcols block histsptrfloat descriptors break default cv errorcv stsbadarg unknown descriptor format can someone help me to get the hog features for block only edited i am only interested to calculat hog features for different window size keeping features for cell and block same,['c++'] +935471,get width and height of one row in recycleview android i am creating recycleview with some items so i need to get the width and height of the one row of recycleviewhere i am creating recycleview recyclerview rvsmetki recyclerview findviewbyidridrvartikli rvsmetkisetlayoutmanagernew gridlayoutmanagerthis 3 rvsmetkisetadapternew artikliadapterthis here i want to get width and heightand this is my artikliadapterpublic class artikliadapter extends recyclerviewadapterartikliadapterviewholder private static context context private layoutinflater inflater private arraylistartikl artiklilist public artikliadaptercontext context thiscontext context inflater layoutinflaterfromcontext artiklilist loginactivitygetartikllist override public artikliadapterviewholder oncreateviewholderviewgroup parent int viewtype view row inflaterinflaterlayoutartikli row parent false return new artikliadapterviewholderrow override public void onbindviewholderartikliadapterviewholder holder int position artikl currentartikl artiklilistgetposition holdertvnazivsettextcurrentartiklgetnaziv holdertvcenasettext12 currentartiklgetprodaznacena override public int getitemcount return artiklilistsize static class viewholder extends recyclerviewviewholder private relativelayout rlartikl private textview tvnaziv private textview tvcena public viewholderview itemview superitemview rlartikl relativelayout itemviewfindviewbyidridrlartikl tvnaziv textview itemviewfindviewbyidridtvnaziv tvcena textview itemviewfindviewbyidridtvcena how can i get width and height of one rowhow can i get width and height of one row,"['java', 'android']" +935541,why does the session id change when requesting through ajax in php i am logged in on bananacom banana has a api link on appajax loggedinmy website is monkey monkey runs a simple get json to bananas appajax loggedin which returns a loggedin value either 1 or 0why is it always returning 0 when it is through ajax even though i really am logged in on banana and also when accessing the link directly gives me 1how can the developer at banana fix iti would have understood it if it is a server side call but i do not understand why it wont tell me if im logged in if banana makes the request running session id check it generates a new one each call through ajax and when accessing directly it works just fine and keeps the sameis there any fix or another way to do this,['php'] +935657,mpmovieplayercontroller initialplaybacktime property not working in ios 84 after setting initialplaybacktime property the videohttp streaming still plays from the beginningthe same code works well in ios 83 selfmovieplayerinitialplaybacktime selflastplaybacktimeselfmovieplayer play,"['ios', 'objective-c']" +935714,collapsingtoolbarlayout sometimes leaves white space below i have a problem here are the screenshotsand here is the codexml version10 encodingutf8androidsupportdesignwidgetcoordinatorlayout androidididrootlayout androidlayout widthmatch parent androidlayout heightmatch parent androidsupportdesignwidgetappbarlayout androidlayout widthmatch parent androidlayout height256dp androidthemestylethemeoverlayappcompatdarkactionbar androidsupportdesignwidgetcollapsingtoolbarlayout androidididcollapsingtoolbarlayout androidlayout widthmatch parent androidlayout heightmatch parent appexpandedtitlemarginstart64dp applayout scrollflagsscrollexituntilcollapsed androidsupportv7widgettoolbar androidididtoolbar androidlayout widthmatch parent androidlayout heightattractionbarsize androidbackgroundattrcolorprimary androidminheightattractionbarsize applayout collapsemodepin apopupthemestylethemeoverlayappcompatlight appthemestylethemeoverlayappcompatdarkactionbar androidsupportdesignwidgetcollapsingtoolbarlayout androidsupportdesignwidgetappbarlayout androidsupportv4widgetnestedscrollview androidlayout widthmatch parent androidlayout heightmatch parent androidfillviewporttrue applayout behaviorstringappbar scrolling view behavior linearlayout androidlayout widthmatch parent androidlayout heightmatch parent androidorientationvertical button androidlayout widthwrap content androidlayout heightwrap content androidtextyo yo button androidlayout widthwrap content androidlayout heightwrap content androidtextyo yo button androidlayout widthwrap content androidlayout heightwrap content androidtextyo yo button androidlayout widthwrap content androidlayout heightwrap content androidtextyo yo button androidlayout widthwrap content androidlayout heightwrap content androidtextyo yo button androidlayout widthwrap content androidlayout heightwrap content androidtextyo yo button androidlayout widthwrap content androidlayout heightwrap content androidtextyo yo button androidlayout widthwrap content androidlayout heightwrap content androidtextyo yo button androidlayout widthwrap content androidlayout heightwrap content androidtextyo yo button androidlayout widthwrap content androidlayout heightwrap content androidtextyo yo button androidlayout widthwrap content androidlayout heightwrap content androidtextyo yo button androidlayout widthwrap content androidlayout heightwrap content androidtextyo yo button androidlayout widthwrap content androidlayout heightwrap content androidtextyo yo button androidlayout widthwrap content androidlayout heightwrap content androidtextyo yo button androidlayout widthwrap content androidlayout heightwrap content androidtextyo yo button androidlayout widthwrap content androidlayout heightwrap content androidtextyo yo button androidlayout widthwrap content androidlayout heightwrap content androidtextyo yo button androidlayout widthwrap content androidlayout heightwrap content androidtextyo yo button androidlayout widthwrap content androidlayout heightwrap content androidtextyo yo button androidlayout widthwrap content androidlayout heightwrap content androidtextyo yo button androidlayout widthwrap content androidlayout heightwrap content androidtextyo yo button androidlayout widthwrap content androidlayout heightwrap content androidtextyo yo button androidlayout widthwrap content androidlayout heightwrap content androidtextyo yo button androidlayout widthwrap content androidlayout heightwrap content androidtextyo yo linearlayout androidsupportv4widgetnestedscrollview androidsupportdesignwidgetfloatingactionbutton androidididfabbtn2 androidlayout widthwrap content androidlayout heightwrap content androidlayout gravitybottomright androidlayout marginbottomdimencodelab fab margin bottom androidlayout marginrightdimencodelab fab margin right appborderwidth0dp appfabsizenormal androidsupportdesignwidgetcoordinatorlayoutandroidsupportdesignwidgetnavigationview androidididnavigation androidlayout widthwrap content androidlayout heightmatch parent androidlayout gravitystart appheaderlayoutlayoutnav header appitemicontintcolorcolorprimarydark appitemtextcolorcolorcolorprimary appmenumenunavigation drawer items you can see sometimes a white space appears below the toolbar but sometimes nodou yo have any idea of whats wrong because i really do not know how to fix thisthanks in advanceedit i can only reproduce this with android 511 in the nexus 7,['android'] +935741,center glyphicon content i using google chrome inspector and if you select the before pseudo of the glyphicon you will see that there is empty space at the right how i can center the glyphiconi tried to set text align but it does not workspan classglyphicon glyphiconplusspanstyleglyphicon fontsize 120px stylejsfiddleupdated link jsfiddle 2,['css'] +935800,bind poses joint transforms in collada i am trying to export a custom 3d model format to collada i have built the collada data classes through xsd and now problems come when i try to fill them with data especially for what concerns matricesmy skeleton class is basically an array of joint classes that i read from the binary file and every joint looks like this values of traslation and rotation are relative to the parent joint or root if there is no parent alwaysclass joint listjoint children quaternion rotation joint parent string name uint32 id vector3 traslationthe first thing i do is to build the joint nodes in the library visual scenes section of the file which is quite simple and i get correct resultsforeach joint joint in hierarchicaljoints writejointnodesjointprivate void writejointnodesjoint joint vector3 rotationeulers quaterniontoeulersjointrotation eulersorderzyx writestartelementnode writeattributestringid stringconcatjointname id writeattributestringtype joint writeattributestringname jointname writeelementstringtranslate bonetraslation writeelementstringattributesrotate stringconcat00 00 10 rotationztodegrees sid rotatez writeelementstringattributesrotate stringconcat00 10 00 rotationytodegrees sid rotatey writeelementstringattributesrotate stringconcat10 00 00 rotationxtodegrees sid rotatex writeelementstringscale 10 10 10 joint children jointgetchildren for int32 i 0 i childrenlength i writejointnodeschildreni writeendelementhere is an example of the outputnode idbn head id typejoint namebn head translate00732510 0 0translate rotate sidrotatez10 00 10 00rotate rotate sidrotatey00 10 00 90rotate rotate sidrotatex10 00 00 00rotate scale10 10 10scalenow comes the tricky part since i also have to export weights skinning data into the library controllers section which looks like thisskin sourcegeometry1 id bind shape matrix1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1bind shape matrix source idskinu3d1 idjoints name array idskinu3d1 idjointsarray count4bn head id bn jaw id bn lefteye id bn righteye idname array technique common accessor sourceskinu3d1 idjointsarray count4 stride1 param namejoint typename accessor technique common source source idskinu3d1 idbind poses float array idskinu3d1 idbind posesarray count640 09831 0018391 158086 1 0 0 0 0 0018391 09831 0041763 0 0 0 1 011 0374834 0927092 0564468 1 0506 0323 0808 059 0927092 0374834 145633 0 0 0 1 0 036 1 0074606 1 0 0 0032523 0 1 036 1638 0 0 0 1 04 036 1 0074607 1 0302 04 0032021 0302 1 036 163774 0 0 0 1float array technique common accessor sourceskinu3d1 idbind posesarray count4 stride16 param nametransform typefloat4x4 accessor technique common source weights source here joints input semanticjoint sourceskinu3d1 idjoints input semanticinv bind matrix sourceskinu3d1 idbind poses joints vertex weights hereskinhere the first 16 values of skinu3d1 idbind posesarray should represent the inverse bind pose of bn head of my examplei can build the joints array properly and i can handle vertices weights without problems but i really do not understand how to obtain the matrices being used inside the skin controller i need to output a collada model with y up orientation and all i know is that collada matrices are columnmajorstarting from the data i have my questions basically arehow do i calculate the bind shape matrix in this example it is an identity matrix but i have also seen other collada files in which it is differenthow do i calculate inverse bind matrices for every joint,['.net'] +935801,how to get visual studio to stay within 4gb virtual address space the visual studio devenvexe process is 32bit even when run on a 64bit os so it cannot use more than 4gb of virtual memoryunfortunately when i am debugging my c application with visual studio i frequently run out of memory due to this 4gb limit for example using vmmap below shows progression of my typical visual studio usage over a few hours leading to a crashhow can i get visual studio to use less memory so i stop wasting time with it crashingis it typical for visual studio to use more than 35 gb virtual address spacei am using visual studio 2012 but i assume this problem spans different vs versions since visual studio 2015 still does not have a 64bit versionnote that vmmap reports afreea as the remaining memory in the address space up to 4gb for 32 bit processes and 8tb for 64 bit processes on windowsthings i have already triedstarting in safe moderemoving all plugins and extensions so that nothing shows in tools addin manager nor tools extensions is helpful for thisdeleting my suosdf filesdeleting my appdatamicrosoftvisualstudio foldersusing funnel and filtering out all but 3 projectsremoved all my symbol file pdb locations selections and chose automatically load symbols for only specified modulesselected enable just my code for debuggingthisabling intellisense tools options text editor cc advanced thisable intellisense,['c++'] +935953,how to rotate an array i have the following problem to testrotate an array of and elements to the right by k steps for instance with and 7 and k 3 the array 1234567 is rotated to 5671234 how many different ways do you know to solve this problemmy solution in intermediate arraywith space is on and time is on i can create a new array and then copy elements to the new array then change the original array by using systemarraycopypublic void rotateint nums int k ifk numslength kknumslength int result new intnumslength forint i0 i k i resulti numsnumslengthki int j0 forint ik inumslength i resulti numsj j systemarraycopy result 0 nums 0 numslength but is there a better way we can do it with bubble rotatelike bubble sort in o1 space,['java'] +935976,thisable initial automatic ajax call datatable server side paging i have a datatable initialized with server side paging and it is working fine this table triggers ajax pulls data and renders onto the table during initialization however i need empty table initially and load table data on click of a button using load or reload likemytableapiajaxreloadhere is my table initializationfunction inittesttable mytable testtabledatatable processing true serverside true ajax url testtabledatahtml type get columns data code data description there should be a way to restrict the loading of table during initialization i read the documentation but could not find please suggest,['jquery'] +936016,how to use jquery ui components in aurelia getting started app navigation app i am able to run the aurelia app by following the steps provided in getting started tutorial they have used bootstrap navbar in the skeleton application is it possible to use jquery ui components in the aurelia app if yes please explain me how to achieve thisthanks in advance,"['javascript', 'jquery']" +936034,unable to login with symfony i am currently doing a project with symfony version 2510 everythings working fine until we changed our database and update its entities i already tried different ways yet still i cannot log in to the system whenever i run on either prod or dev environment it gives me this errorauthentication request could not be processed due to a system problemi already tried clearing the cache manually or even through command prompt even tried running these commandsphp appconsole doctrineschemaupdate dumpsqlphp appconsole doctrineschemaupdate forceand even tried creating a new user using thisphp appconsole fosusercreate testuser pssw0rdand it successfully saved in the databaseheres the log file20150702 082406 eventdebug notified event kernelresponse to listener symfonycomponenthttpkerneleventlistenerresponselisteneronkernelresponse 20150702 082406 eventdebug notified event kernelresponse to listener symfonycomponentsecurityhttpremembermeresponselisteneronkernelresponse 20150702 082406 eventdebug notified event kernelresponse to listener sensiobundleframeworkextrabundleeventlistenerhttpcachelisteneronkernelresponse 20150702 082406 eventdebug notified event kernelresponse to listener symfonycomponenthttpkerneleventlistenerprofilerlisteneronkernelresponse 20150702 082406 eventdebug notified event kernelresponse to listener symfonybundlewebprofilerbundleeventlistenerwebdebugtoolbarlisteneronkernelresponse 20150702 082406 eventdebug notified event kernelresponse to listener symfonycomponenthttpkerneleventlistenersavesessionlisteneronkernelresponse 20150702 082406 eventdebug notified event kernelresponse to listener symfonycomponenthttpkerneleventlistenerstreamedresponselisteneronkernelresponse 20150702 082406 eventdebug notified event kernelfinish request to listener symfonycomponenthttpkerneleventlistenerlocalelisteneronkernelfinishrequest 20150702 082406 eventdebug notified event kernelfinish request to listener symfonycomponenthttpkerneleventlistenerrouterlisteneronkernelfinishrequest 20150702 082406 eventdebug notified event kernelfinish request to listener symfonycomponentsecurityhttpfirewallonkernelfinishrequest 20150702 082406 eventdebug notified event kernelterminate to listener symfonybundleswiftmailerbundleeventlisteneremailsenderlisteneronterminate 20150702 082406 eventdebug notified event kernelterminate to listener symfonycomponenthttpkerneleventlistenerprofilerlisteneronkernelterminate 20150702 082406 eventdebug notified event kernelresponse to listener symfonycomponenthttpkerneleventlistenerresponselisteneronkernelresponse 20150702 082406 eventdebug notified event kernelresponse to listener symfonycomponentsecurityhttpremembermeresponselisteneronkernelresponse 20150702 082406 eventdebug notified event kernelresponse to listener sensiobundleframeworkextrabundleeventlistenerhttpcachelisteneronkernelresponse 20150702 082406 eventdebug notified event kernelresponse to listener symfonycomponenthttpkerneleventlistenerprofilerlisteneronkernelresponse 20150702 082406 eventdebug notified event kernelresponse to listener symfonybundlewebprofilerbundleeventlistenerwebdebugtoolbarlisteneronkernelresponse 20150702 082406 eventdebug notified event kernelresponse to listener symfonycomponenthttpkerneleventlistenersavesessionlisteneronkernelresponse 20150702 082406 eventdebug notified event kernelresponse to listener symfonycomponenthttpkerneleventlistenerstreamedresponselisteneronkernelresponse 20150702 082406 eventdebug notified event kernelfinish request to listener symfonycomponenthttpkerneleventlistenerlocalelisteneronkernelfinishrequest 20150702 082406 eventdebug notified event kernelfinish request to listener symfonycomponenthttpkerneleventlistenerrouterlisteneronkernelfinishrequest 20150702 082406 eventdebug notified event kernelfinish request to listener symfonycomponentsecurityhttpfirewallonkernelfinishrequest 20150702 082406 eventdebug notified event kernelresponse to listener symfonycomponenthttpkerneleventlistenerresponselisteneronkernelresponse 20150702 082406 eventdebug notified event kernelresponse to listener symfonycomponentsecurityhttpremembermeresponselisteneronkernelresponse 20150702 082406 eventdebug notified event kernelresponse to listener sensiobundleframeworkextrabundleeventlistenerhttpcachelisteneronkernelresponse 20150702 082406 eventdebug notified event kernelresponse to listener symfonycomponenthttpkerneleventlistenerprofilerlisteneronkernelresponse 20150702 082406 eventdebug notified event kernelresponse to listener symfonybundlewebprofilerbundleeventlistenerwebdebugtoolbarlisteneronkernelresponse 20150702 082406 eventdebug notified event kernelterminate to listener symfonybundleswiftmailerbundleeventlisteneremailsenderlisteneronterminate 20150702 082406 eventdebug notified event kernelresponse to listener symfonycomponenthttpkerneleventlistenersavesessionlisteneronkernelresponse 20150702 082406 eventdebug notified event kernelterminate to listener symfonycomponenthttpkerneleventlistenerprofilerlisteneronkernelterminate 20150702 082406 eventdebug notified event kernelresponse to listener symfonycomponenthttpkerneleventlistenerstreamedresponselisteneronkernelresponse 20150702 082406 eventdebug notified event kernelfinish request to listener symfonycomponenthttpkerneleventlistenerlocalelisteneronkernelfinishrequest 20150702 082406 eventdebug notified event kernelfinish request to listener symfonycomponenthttpkerneleventlistenerrouterlisteneronkernelfinishrequest 20150702 082406 eventdebug notified event kernelfinish request to listener symfonycomponentsecurityhttpfirewallonkernelfinishrequest 20150702 082406 eventdebug notified event kernelterminate to listener symfonybundleswiftmailerbundleeventlisteneremailsenderlisteneronterminate 20150702 082406 eventdebug notified event kernelterminate to listener symfonycomponenthttpkerneleventlistenerprofilerlisteneronkernelterminate 20150702 082406 eventdebug notified event kernelresponse to listener symfonycomponenthttpkerneleventlistenerresponselisteneronkernelresponse 20150702 082406 eventdebug notified event kernelresponse to listener symfonycomponentsecurityhttpremembermeresponselisteneronkernelresponse 20150702 082406 eventdebug notified event kernelresponse to listener sensiobundleframeworkextrabundleeventlistenerhttpcachelisteneronkernelresponse 20150702 082406 eventdebug notified event kernelresponse to listener symfonycomponenthttpkerneleventlistenerprofilerlisteneronkernelresponse 20150702 082406 eventdebug notified event kernelresponse to listener symfonybundlewebprofilerbundleeventlistenerwebdebugtoolbarlisteneronkernelresponse 20150702 082406 eventdebug notified event kernelresponse to listener symfonycomponenthttpkerneleventlistenersavesessionlisteneronkernelresponse 20150702 082406 eventdebug notified event kernelresponse to listener symfonycomponenthttpkerneleventlistenerstreamedresponselisteneronkernelresponse 20150702 082406 eventdebug notified event kernelfinish request to listener symfonycomponenthttpkerneleventlistenerlocalelisteneronkernelfinishrequest 20150702 082406 eventdebug notified event kernelfinish request to listener symfonycomponenthttpkerneleventlistenerrouterlisteneronkernelfinishrequest 20150702 082406 eventdebug notified event kernelfinish request to listener symfonycomponentsecurityhttpfirewallonkernelfinishrequest 20150702 082406 eventdebug notified event kernelterminate to listener symfonybundleswiftmailerbundleeventlisteneremailsenderlisteneronterminate 20150702 082406 eventdebug notified event kernelterminate to listener symfonycomponenthttpkerneleventlistenerprofilerlisteneronkernelterminate 20150702 082406 requestinfo matched route wdt parameters controller web profilercontrollerprofilertoolbaraction token d950df route wdt 20150702 082406 eventdebug notified event kernelrequest to listener symfonycomponenthttpkerneleventlistenererrorsloggerlistenerinjectlogger 20150702 082406 eventdebug notified event kernelrequest to listener symfonycomponenthttpkerneleventlistenererrorsloggerlistenerinjectlogger 20150702 082406 eventdebug notified event kernelrequest to listener symfonycomponenthttpkerneleventlistenererrorsloggerlistenerinjectlogger 20150702 082406 eventdebug notified event kernelrequest to listener symfonycomponenthttpkerneleventlistenerdebughandlerslistenerconfigure 20150702 082406 eventdebug notified event kernelrequest to listener symfonycomponenthttpkerneleventlistenerprofilerlisteneronkernelrequest 20150702 082406 eventdebug notified event kernelrequest to listener symfonybundleframeworkbundleeventlistenersessionlisteneronkernelrequest 20150702 082406 eventdebug notified event kernelrequest to listener symfonycomponenthttpkerneleventlistenerfragmentlisteneronkernelrequest 20150702 082406 eventdebug notified event kernelrequest to listener symfonycomponenthttpkerneleventlistenerrouterlisteneronkernelrequest 20150702 082406 eventdebug notified event kernelrequest to listener symfonycomponenthttpkerneleventlistenerlocalelisteneronkernelrequest 20150702 082406 eventdebug notified event kernelrequest to listener symfonycomponentsecurityhttpfirewallonkernelrequest 20150702 082406 eventdebug notified event kernelrequest to listener symfonybundleasseticbundleeventlistenerrequestlisteneronkernelrequest 20150702 082406 eventdebug notified event kernelcontroller to listener symfonybundleframeworkbundledatacollectorrouterdatacollectoronkernelcontroller 20150702 082406 eventdebug notified event kernelcontroller to listener symfonycomponenthttpkerneldatacollectorrequestdatacollectoronkernelcontroller 20150702 082406 eventdebug notified event kernelcontroller to listener sensiobundleframeworkextrabundleeventlistenercontrollerlisteneronkernelcontroller 20150702 082406 eventdebug notified event kernelcontroller to listener sensiobundleframeworkextrabundleeventlistenerparamconverterlisteneronkernelcontroller 20150702 082406 eventdebug notified event kernelcontroller to listener sensiobundleframeworkextrabundleeventlistenerhttpcachelisteneronkernelcontroller 20150702 082406 eventdebug notified event kernelcontroller to listener sensiobundleframeworkextrabundleeventlistenersecuritylisteneronkernelcontroller 20150702 082406 eventdebug notified event kernelcontroller to listener sensiobundleframeworkextrabundleeventlistenertemplatelisteneronkernelcontroller 20150702 082406 eventdebug notified event kernelresponse to listener symfonycomponenthttpkerneleventlistenerresponselisteneronkernelresponse 20150702 082406 eventdebug notified event kernelresponse to listener symfonycomponentsecurityhttpremembermeresponselisteneronkernelresponse 20150702 082406 eventdebug notified event kernelresponse to listener sensiobundleframeworkextrabundleeventlistenerhttpcachelisteneronkernelresponse 20150702 082406 eventdebug notified event kernelresponse to listener symfonycomponenthttpkerneleventlistenerprofilerlisteneronkernelresponse 20150702 082406 eventdebug notified event kernelresponse to listener symfonybundlewebprofilerbundleeventlistenerwebdebugtoolbarlisteneronkernelresponse 20150702 082406 eventdebug notified event kernelresponse to listener symfonycomponenthttpkerneleventlistenersavesessionlisteneronkernelresponse 20150702 082406 eventdebug notified event kernelresponse to listener symfonycomponenthttpkerneleventlistenerstreamedresponselisteneronkernelresponse 20150702 082406 eventdebug notified event kernelfinish request to listener symfonycomponenthttpkerneleventlistenerlocalelisteneronkernelfinishrequest 20150702 082406 eventdebug notified event kernelfinish request to listener symfonycomponenthttpkerneleventlistenerrouterlisteneronkernelfinishrequest 20150702 082406 eventdebug notified event kernelfinish request to listener symfonycomponentsecurityhttpfirewallonkernelfinishrequest 20150702 082406 eventdebug notified event kernelterminate to listener symfonybundleswiftmailerbundleeventlisteneremailsenderlisteneronterminate 20150702 082406 eventdebug notified event kernelterminate to listener symfonycomponenthttpkerneleventlistenerprofilerlisteneronkernelterminate could you please tell me whats wrong with what i am doing thanksediti tried clearing the cookies and run the application again and found this on the logs20150703 042734 requestinfo matched route fos user security check parameters controller fosuserbundlecontrollersecuritycontrollercheckaction route fos user security check 20150703 042734 doctrinedebug select t0username as username1 t0username canonical as username canonical2 t0email as email3 t0email canonical as email canonical4 t0enabled as enabled5 t0salt as salt6 t0password as password7 t0last login as last login8 t0locked as locked9 t0expired as expired10 t0expires at as expires at11 t0confirmation token as confirmation token12 t0password requested at as password requested at13 t0roles as roles14 t0credentials expired as credentials expired15 t0credentials expire at as credentials expire at16 t0ediuserid as ediuserid17 from edi user t0 where t0username canonical limit 1 erosales 20150703 042734 securityinfo authentication request failed an exception occurred while executing select t0username as username1 t0username canonical as username canonical2 t0email as email3 t0email canonical as email canonical4 t0enabled as enabled5 t0salt as salt6 t0password as password7 t0last login as last login8 t0locked as locked9 t0expired as expired10 t0expires at as expires at11 t0confirmation token as confirmation token12 t0password requested at as password requested at13 t0roles as roles14 t0credentials expired as credentials expired15 t0credentials expire at as credentials expire at16 t0ediuserid as ediuserid17 from edi user t0 where t0username canonical limit 1 with params erosales sqlstate42s22 column not found 1054 unknown column t0ediuserid in field list 20150703 042734 securitydebug redirecting to login i already rendered a couple of hours trying to fix this but still i cannot i hope someone can help me thanks,['php'] +936133,webpack can not load font file unexpected token i have a stylecss file that makes use of a font file and i am having trouble getting the font file loaded using webpack here is my loader configuration loaders test jsjsx exclude node modules loader reacthotbabelloader test styl loader styleloadercssloaderstylusloader test css loader styleloadercssloader test pngjpg loader urlloaderlimit8192 test ttfeotsvgwoff2az09 loader fileloader test woff2v090909 loader urlloaderlimit10minetypeapplicationfontwoff the errors that i receive is error in srcfontsiconfontsmffontwofflt4gttmodule parse failed pathsrcfontsiconfontsmffontwofflt4gtt line 1 unexpected token illegalyou may need an appropriate loader to handle this file typesource code omitted for this binary file cssloadersrcfontsiconstylecss 22931it looks to me that webpack is taking it as a css file when it is not but i am pretty sure the test expression passes for the font file,['css'] +936157,android compute right bbox for wms getfeatureinfo i am trying to make a request to my geoserver to retrieve the features near the tap of a user on the mapthe map takes all the space therefore i computed the bbox in this wayregion mmapgetprojectiongetvisibleregionlatlngboundsdouble left regionsouthwestlongitudedouble top regionnortheastlatitudedouble right regionnortheastlongitudedouble bottom regionsouthwestlatitudeand the width and height are taken as belowsmmapfragmentgetviewgetwidthmmapfragmentgetviewgetheightwhile the x and y parameter are calculated in the following waypoint click mmapgetprojectiontoscreenlocationlatlngwhere latlng is the point that came from the event onmapclicklatlng reference here the resulting url that i obtain ishttplocalhostgeoserversindotwmsservicewmsrequestgetfeatureinfoinfo formatapplication2fjsonversion1srsepsg3a3857bbox1217374033505640344084121741135650564037028query layerssindotverticalelayerssindotverticalefeature count3stylestabletb3labwidth2048height1262x1441y503the problem is that the server returns always an empty response even if i know that there are features there because i can see the spots on the map what could it bethanks in advance,['android'] +936189,what is the reason for the overhead in memory usage for arrays in java in java the character data type char is represented with 2 bytes the array of n characters char is represented with 2n24 bytes in general there is an overhead of 24 bytes for storing an array of n objects at least if the objects are of primitive typewhy do we need these additional 24 bytes how are they usededit july 2nd 2015 it was brought to my attention in a comment that an answer to this question is offered here on the programmers stackexchange,['java'] +936190,realm primary key migration i want to migrate my realm schema to a new version therefor the removal of my primary key is neededold schemaclass studystate object dynamic var name dynamic var x dynamic var y override static func primarykey string return name new schemaclass studystate object dynamic var name dynamic var x dynamic var y without migration realm will fail withrlmexception reason migration is required for object type studystate due to the following errors property name is no longer a primary keyi tried this migration block which failed toomigrationenumeratestudystateclassname oldobject newobject in newobjectdeleted false newobjectprimarykeyproperty rlmexception reason invalid property nameis there a way to remove the primary key when migrating realm to a new schema version,['ios'] +936244,making a bootstrap table column fit to content i am using bootstrap and drawing a table the rightmost column has a button in it and i want it to drop down to the minimum size it needs to fit said buttontable classtable tableresponsive tbody tr thnameth thpayment methodth thth tr tr tdbart footd tdvisatd tda rolebutton classbtn btndefault btnxs hrefpaymentsviewnnrn 8tmb0ckvxt06nkrygviewatd tr tbodytablethis renders like thiswith some firebug highlighting the column width has come out this widethat column scales with the page while the page is in the larger dynamic width modes i have some idea how i would go about fixing this in pure css but most of those approaches will probably cause issues with the low width versions of the sitehow would i make that column drop down to the width of it is contentsas ever existing bootstrap classes pure css javascript,"['html', 'css']" +936284,how to convert color names to its equivalent hex code i want to thisplay the textviews text at particular color in which i am getting from server from server colors are coming in string format like yellow blue red purple etc how can we set this color to textviews textcan anybody have any idea about thisthanks,['android'] +936293,saving objectsserialization i am trying to make the transition from c to c and i have a few questions about saving objects to files and serializationin c if you want to save a data structure i have been taught that saving it in a text format as a string is often unnecessary and a binary file that exist as a memory snapshot is often better because it does not need encodingdecoding and matching strings to fieldsin c the approach appears to be different it converts object fields separately to a string or some other format and then it reconstructs the object when necessary i am not sure how binary serialization works but i think it sill converts the data to some format and does not exist as a pure nonformatted memory snapshot why is the memory snapshot method without any encodingdecoding not used in c the only reason i can think is compatibility with other code and environments and maybe it has to do with the complexity of objects vs regular structures,['c#'] +936335,canceling drag because exception nsinvalidargumentexception attempt to insert nil object when i try to drag drop an object from a nsoutlineview to another it usually works but sometimes it fails for some objects i get the message canceling drag because exception nsinvalidargumentexception reason nsplaceholderarray initwithobjectscount attempt to insert nil object from objects0 was raised during a dragging sessioni have found out that this happens when i first drag the item over another row of the same table without releasing it and then drag to the new tablethis is the content of the draggeditems in the last function i can check during the dragging id nspasteboardwritingoutlineviewnsoutlineview outlineview pasteboardwriterforitemiditem cbcollectible collectible item representedobject return collectible uniqueid stringvalue voidoutlineviewnsoutlineview outlineview draggingsessionnsdraggingsession session endedatpointnspointscreenpoint operationnsdragoperationoperation cbdebugend draggingleaderindex i sessiondraggingleaderindex voidoutlineviewnsoutlineview outlineview draggingsessionnsdraggingsession session willbeginatpointnspointscreenpoint foritemsnsarray draggeditems freeandnilthedraggeditems thedraggeditems nsarray alloc initwitharraydraggeditems sessiondraggingpasteboard setdatansdata data fortypemain view pasteboard type voidoutlineviewnsoutlineview outlineviewupdatedraggingitemsfordragidnsdragginginfodragginginfooutput lognslogdraggeditems draggeditems nsarraym 0x31fa0f0nstreecontrollertreenode 0x1d23750 child nodes update dragging registrationoutlineview1 registerfordraggedtypesmain view pasteboard type nsstringpboardtype nsfilenamespboardtypeoutlineview2 registerfordraggedtypesmain view pasteboard type nsstringpboardtype nsfilenamespboardtype,['objective-c'] +936411,is nullchecking on linq queries idiomatic using linqtosql i wonder which is more idiomatic of the following threefooswherefoo foobarhasvalue foobarvalue 42fooswherefoo foobarvalue 42fooswherefoo foobar 42the first option generates an extra bar is not null predicate that is probably being optimized away in most dbmses if one queried objects instead of a database the nullcheck would be mandatory but since one can create generic iqueriablefoo queries that might fail on objects but not on databases the first option would always work although both the linq and sql code is a little longer than the second option the third option provided by michael liu seems to be the best of both worlds but will not work in the case foobar has type bool fooswherefoo foobar results in a type error as implicit conversion is not made hereshould one strive to write generic queries that will not fail if used outside of the context they were initially designed for,"['c#', 'sql']" +936420,angularjs filter is not working for multiple words from 2 different keys this is some of sample json datascopeproducts variants subcategoryid 66 productimagepath imagesbritannia887png subcategoryname butter brandname britannia productid 887 brandid 76 productname butter variants subcategoryid 71 productimagepath imagesamul886png subcategoryname cheese brandname amul productid 886 brandid 47 productname cheese variants subcategoryid 106 productimagepath imagesamul885png subcategoryname curd brandname amul productid 885 brandid 47 productname curdand this is how i am rendering to webpagediv ngifsearchtext classbox ngrepeatproduct in products filterfilterexpr orderbyproductname nginclude srccommontemplatehtmlngincludedivthere is a search text box in page when user start typing in serach text box i assigns value to filterexpr like thisscopeonsearchtextchanged functionevent searchtext if searchtextlength 3 scopefilterexpr searchtext when user type amul or cheese or butter it is able to filter the products problem is when user types amul curd or curd amul or butter britannia no products are thisplaying on the pagehow to make it work what change i need to do to so it is able to filter for multiple words,['javascript'] +936583,collapsingtoolbarlayout subtitle i am able to set the title of a collapsingtoolbarlayout via the settitle method is there a way to set also a subtitlethanks,['android'] +936587,building a geolocation photo index crawling the web or relying on an existing api i am developing a geolocation service which requires a photo per poi and i am trying to figure out how to match the right photo to a given locationi am looking for an image that will give an overview for the location rather than some arbitrary image from a given coordinatefor example when searching for nyc in google you get the following image filtered out from of course google is google however i have found this similar approach on other sites for example lng12269478z11a2p5 q for an index like poi name overview image url what would be your approach crawling an api etc please add your thoughts,['javascript'] +936633,simulating device screen on web page i am creating a web app that generates and serves web pages for mobile devices for instance the user configures which data to show and uses a velocity template to generate the final htmlcssjs fileswhen the template and the information to include is configured the clients connect to the server to show the generated pageshowever i am now creating a preview screen for this so let us say i want to see how it will looks like on a let us say nexus 5my goal is to create something like google has on chrome the mobile device emulation the problem is that i am not being able to understand how they are able to do that kind of emulationit is true that the content must be zoomed out in order to show everything this is pretty easy to understand as if the screen is not big enough we need to make it fitso i know the devices screen diagonal size it is resolution and ppi points por inch what i need to know is how to get some proper measurements for my web site to emulate the device when i go to the chrome emulation tool i see that the nexus 5 is shown asresolution 360 x 640pixel aspect ratio 3i know how they calculate the pixel aspect ratio it is the devices ppi divided by 160 base ppi so 445 160 3 445 is the pixel density of nexus 5 that is how they got to the 360 x 640 they divide the resolution by the pixel aspect ratio 3on my web site i have an iframe and load the generated page into it then i know i must apply a zoom level and this is where the problem is at i do not really know which value of the zooming should beone of the attempts was1 screensize diagonalpixel aspect ratio 1 4953 0606060applying this zoom makes it look fine if i follow the same approach with an amazon kindle hdx it also workshowever if i go with the lg l70 i get the following1 45125 027the problem is that applying this zoom things will be a lot smaller because of so much zoom out compared to nexus 5 and in chrome emulation mode they seem so alikeplease let me know if there is any information left that could help solving this puzzle,['html'] +936664,how to remove an empty list from a list java i have searched for this but it is in other languages like python or r i have lists inside a list and i would like to remove the empty listfor example abcdef ghi jkl mnoi would like abcdef ghi jkl mnohow do i remove empty list from a listthanks,['java'] +936684,can i use an es62015 module import to set a reference in global scope i have this situation where i am trying to import an existing library which i will call troublesome using webpackbabel fwiw and it has a global reference to jquery in it which i am trying to resolve using module syntaxi have successfully imported jquery into the local scope of a module viaimport jquery from jqueryso i triedimport jquery from jquery import troublesomebut perhaps not surprisingly i get something like jquery is not a function kicked back from troublesomejsi have tried this as wellsystemimportjquerythenjquery windowjquery jqueryimport troublesomebut it turns out that systemimport is part of the socalled moduleloader spec which was pulled from the es62015 spec so it is not provided by babel there is a polyfill but webpack wouldnt be able to manage dynamic imports accomplished via calls to systemimport anywaybut if i call out the script files in indexhtml like soscript srcscriptscript srcscriptscript srctherestofmyjsjsscriptthe reference to jquery is resolved in troublesomejs and things are goodbut i would prefer to avoid the script tag route as webpack does not manage thosecan anyone recommend a decent strategy for dealing with scenarios like thisupdatewith some guidance from tn1ck i was eventually able to identify one webpackcentric solution using the importsloaderthe configuration for this solution looks something like this module loaders test requireresolvetroublesome loader importsjqueryjqueryjquery,['javascript'] +936740,how do you use css transform with jquery and address window maximise inconsistency documentation of attempts and pictures of the described problemi am trying to resize a table responsively within bootstrap bootstrap is working just fine and even my table is working mostly fine the problem i am having is that when the view port is resized whether it be a desktop window or the rendering of the page via a cell phone screen the table will not resize in any kind of sensible manner it does resize but not relative to its original position it shrinks in place and loses its margin placement with the other elements on the pageas you cans see i have tried a number of different methods represented by the commented sections i have poured over at least 40 browser tabs searching for a viable solution to this there is some little something i am missing and a good push in the right direction would be greatly appreciatedwhat do i need to do to alleviate that margin so the table will remain top and left against the content above it and the view port left wallsee my answer below for the solution for both transformation and maximise issuethe incomplete jquery code i am usingwindowresizefunction var ww windowwidth var hh windowheight var tt gametablewidth var scle 00parsefloat parsefloatww if ww 688 scle parsefloatww parsefloat gametablecsstransform scale scletostringsubstr0 4 gametablecss webkittransform scale scletostringsubstr0 4 moztransform scale scletostringsubstr0 4 mstransform scale scletostringsubstr0 4 otransform scale scletostringsubstr0 4 transform scale scletostringsubstr0 4 loghtmlloghtml scletostringsubstr0 4 br gametablewidthgamerowcsswidth gametableheightgamerowcsswidth gametablecsstransform scale075 gametablecssposition relative gametablecsstop 0 gametablecssleft 0 gametablecsspadding 0 gamedivcssposition relative gamedivcsstop 0px gamedivcssleft 0px gamedivcsspadding 0pxa precise depiction of the stated behavior can be found in the pictures belowthe table is on the left of the screen when both the window and the board are the same width 688pxbut when using the code above the table shrinks but it does not maintain position this is my question how to i make it not make that marginlets reiterate when i shrink the table using the transform method above it creates an undesirable margin top and left of the table what do i need to do to alleviate that margin so the table will remain top and left against the content above it and the view port left wall,"['jquery', 'html', 'css']" +936808,how are these methods ambiguous one takes array another takes varargs how are these append methods ambiguouspublic class try multiplearguments public static void mainstring args int array1 new int 1 2 3 int array2 new int 4 5 6 appendarray1 array2 appendarray1 4 5 6 public static int appendint array1 int array2 int ans new intarray1length array2length forint i0 iarray1length i ansi array1i forint i0 iarray2length i ansiarray1length array2i return ans public static int appendint array1 int array2 return appendarray1array2 updatevarargs is equivalent to an array but this is from inside of the method from outside of the method it should not be equivalent to itupdate 2i see now that i can pass an array to vararg i did not knew that was always workarounding this need hm was this from the very beginning of java varargs,['java'] +936874,ioniccordova make phone call in ios i have found a thread in ionic on this topic it mentions the whitelist pluginso i try to add these code in the configxml but it still can not workaccess origintel launchexternalyes access originmailto launchexternalyes allowintent hreftel htmla hreftel 110callaerror20150703 002116231 myparking271671006045 failed to load webpage with error the url canat be showni try to use another plugin but it still can not work htmlspan ngclickondailindexcallspanjsvar onsuccess function consolelogsuccessvar onerror function consolelogfailscopeondail functionindex windowpluginscallnumbercallnumberonsuccess onerror scopeparkingrecordsindexnumbererror20150703 002409620 myparking273081007392 failso how can i make this workionic version 143cordova version 500,['ios'] +936881,why does my javascript only fire when the code is repeated i am having an issue where i can only get my code to fire if i repeat it see the below example while the code is nearly identical if i take either of the two scripts out the code does not function with just one yet if i run both the script fires fine but only one instead of two give it a gothis works but only one script firesscript typetextjavascriptvar url windowlocationhref documentwritescript typeapplicationjavascript srcmik21 url scriptscript typetextjavascriptvar url windowlocationhref documentwritescript typeapplicationjavascript srcmik url scriptthis does not workscript typetextjavascriptvar url windowlocationhref documentwritescript typeapplicationjavascript srcmik21 url scriptor thisscript typetextjavascriptvar url windowlocationhref documentwritescript typeapplicationjavascript srcmik url scriptdoes anyone have any ideas this is definitely the weirdest thing i have seen in a whilethanks,"['javascript', 'html']" +936920,how can i change the navigationviews item text size google recently released the androidsupportdesignwidgetnavigationview widget as part of the comandroidsupportdesign20 library which greatly simplified and standarthises the process of creating a navigationdrawerhowever according to the design specs the list item should be roboto medium 14sp 87 0 the navigationview exposes no textsize or textstyle to customise thiswhat are my options if i am pedantic about maintaining the correct design specifications using the google provided navigationview or customising it in any other way,['android'] +936969,two floating action buttons next to each other the material design documentation has an example of google maps showing two floating action buttons next to one another actually one above the otherhow is this done i have two fabs in a coordinator layout but they end up on top of one another so you only see one buttonxml version10 encodingutf8androidsupportdesignwidgetcoordinatorlayout xmlnsandroid xmlnsapp androidlayout widthmatch parent androidlayout heightmatch parent use themeoverlay to make the toolbar and tablayout text white androidsupportdesignwidgetappbarlayout androidididabl top androidlayout heightwrap content androidlayout widthmatch parent androidthemestylethemeoverlayappcompatdarkactionbar androidsupportv7widgettoolbar androidididtoolbar androidfitssystemwindowstrue androidlayout widthmatch parent androidlayout heightattractionbarsize apopupthemestylethemeoverlayappcompatdarkactionbar androidsupportdesignwidgetappbarlayout linearlayout androidlayout widthmatch parent androidlayout heightmatch parent androidorientationvertical imageview androidididimg photo androidlayout widthmatch parent androidlayout height256dp androidbackgroundc5c5c5 edittext androidididtext name androidlayout widthmatch parent androidlayout heightwrap content androidlayout belowidimg baby androidlayout alignparentstarttrue androidlayout alignparentlefttrue androidhintname androiddrawableleftdrawableic account androiddrawablepadding20dp androidtextappearanceandroidattrtextappearancesmall textview androidididtext dob androidlayout widthmatch parent androidlayout heightwrap content androidlayout belowidtext name androidlayout alignparentstarttrue androidlayout alignparentlefttrue androidhintdate of birth androiddrawableleftdrawableic cake androiddrawablepadding20dp styleandroidstylewidgetholospinner linearlayout androidsupportdesignwidgetfloatingactionbutton androidididfab camera androidlayout widthwrap content androidlayout heightwrap content androidlayout margin16dp androidsrcdrawableic camera androidclickabletrue appfabsizemini applayout anchoridimg photo applayout anchorgravitybottomrightend androidsupportdesignwidgetfloatingactionbutton androidididfab gallery androidlayout widthwrap content androidlayout heightwrap content androidlayout margin16dp androidsrcdrawableic image androidclickabletrue appfabsizemini applayout anchoridimg photo applayout anchorgravitybottomrightendandroidsupportdesignwidgetcoordinatorlayout,['android'] +937002,is 10 a constant expression in java as far as i understand the java 8 jls the expression 10 is considered a constant expression but when i try to compile the following program with openjdk 8 i get an errorpublic class switch public static void mainstring args switch42 case 10 return default return the error says 10 is not a constant expressionswitchjava4 error constant expression required case 10 1 erroram i missing something or is it a bug in openjdk 8,['java'] +937012,how to allow users to login protected flaskrestapi in angularjs using http authentication guys if my question is not clear please comment below basic http authentication for rest api in flaskangularjsi just want to login to the flaskrestapi in angularjs i do not know how to send the login info username and passwordto flaskrestapi in this app there is one table after successfully login and it will load the data here we are not using any database but username and password is hardcoded in restserver code and usernameadmin and password1234 when can modify update addnewdata i took this from this blog here they are using in knockout i am trying to in angularjslogin formdiv idlogin classmodal hide fade tabindex1 roledialog arialabelledbyloginlabel ariahiddentrue div classmodalheader h3 idloginlabelsign inh3 div div classmodalbody form classformhorizontal div classcontrolgroup label classcontrollabel forinputusernameusernamelabel div classcontrols input ngmodelusername typetext idinputusername placeholderusername div div div classcontrolgroup label classcontrollabel forinputpasswordpasswordlabel div classcontrols input ngmodelpassword typepassword idinputpassword placeholderpassword div div form div div classmodalfooter button ngclicksubmitdatausername password classbtn btnprimary datathismissmodal ariahiddentruesign inbutton div divhtml code which call login modeldiv classnavbar div classnavbarinner a classbtn datatogglemodal datatargetloginlogina divdivangulurjs codescript var app angularmodulemyapp appcontrollertasksctrl functionscope http scopesubmitdatafunctionusername password var config params usernameusername passwordpassword httpgetdatajson httpgettodoapiv10tasks successfunctionresponse consolelogresponsetasks scopetasks responsetasks scopeedittask functiontask scopeselectedtask task scoperemoverow functiontask scopetaskssplicetask 1 scopeaddnewtask function scopetaskspushtitle scopetask1description scopedescription1 scopetaskspushtitle scopetask1 description scopedescription1 scopetask1 scopedescription1 scopetaskspushdhsh scriptrestapiserverimport sixfrom flask import flask jsonify abort request make response url for render template from flaskexthttpauth import httpbasicauthapp flask name static url pathauth httpbasicauthauthget passworddef get passwordusername if username admin return 1234 return noneautherror handlerdef unauthorized return make responsejsonifyerror unauthorized access 403apperrorhandler400def bad requesterror return make responsejsonifyerror bad request 400apperrorhandler404def not founderror return make responsejsonifyerror not found 404tasks id 1 title ubuy groceries description umilk cheese pizza fruit tylenol done false id 2 title ulearn python description uneed to find a good python tutorial on the web done false def make public tasktask new task for field in task if field id new taskuri url forget task task idtaskid externaltrue else new taskfield taskfield return new taskapprouteauthlogin requireddef index return render templateindexhtmlapproutetodoapiv10tasks methodsgetauthlogin requireddef get tasks return jsonifytasks make public tasktask for task in tasksapproutetodoapiv10tasksinttask id methodsgetauthlogin requireddef get tasktask id task task for task in tasks if taskid task id if lentask 0 abort404 return jsonifytask make public tasktask0approutetodoapiv10tasks methodspostauthlogin requireddef create task if not requestjson or title not in requestjson abort400 task id tasks1id 1 title requestjsontitle description requestjsongetdescription done false tasksappendtask return jsonifytask make public tasktask 201approutetodoapiv10tasksinttask id methodsputauthlogin requireddef update tasktask id task task for task in tasks if taskid task id if lentask 0 abort404 if not requestjson abort400 if title in requestjson and not isinstancerequestjsontitle sixstring types abort400 if description in requestjson and not isinstancerequestjsondescription sixstring types abort400 if done in requestjson and typerequestjsondone is not bool abort400 task0title requestjsongettitle task0title task0description requestjsongetdescription task0description task0done requestjsongetdone task0done return jsonifytask make public tasktask0approutetodoapiv10tasksinttask id methodsdeleteauthlogin requireddef delete tasktask id task task for task in tasks if taskid task id if lentask 0 abort404 tasksremovetask0 return jsonifyresult trueif name main apprundebugtrue,['python'] +937040,how to reproduce application not responding anr from activity and from broadcastreceiver i need to reproduce application not responding anr dialogs from activity and from broadcastreceiveri tried to create a simple button click public void makeanrclickview view while truewith this code i reproduced anr on emulator with android 237 same code does not work on real device with the newest android versions 4another attempt was as followspublic void onmakeanrclickview view try threadsleep150 catch interruptedexception e eprintstacktrace this does not help alsoany suggestions,['android'] +937055,how can i split and pipe multiple naudio stream i have a c project working with input audio stream from kinect 1 kinect 2 microphone or anything elsewaveindataavailable object sender waveineventargs e lockbuffer var pos bufferposition bufferwriteebuffer 0 ebytesrecorded bufferposition pos the buffer variable is a stream from component a that will be processed by a speechrecognition component b working on streamsi will add new components c d e working on streams to compute pitch detect sound do finger printing or anything else how can i duplicate that stream for components c d e component a send an event i have a stream do what you want i do not want to reverse the logic by an event give me your streamsi am looking for a multistream that could give me a stream instance and will handle the jobcomponent avar multistream buffer new multistreamsendmyeventwithbuffercomponent b c d epublic void handlemyeventmultistream buffer var stream buffergetnewstream var engine new enginecomponentb enginesetstreamstreamthe multistream must be a stream to wrap write method because stream do not have data available mechanics if a stream is thispose by component b the multistream should remove it from it is array the multistream must throw an exception on read to require use of getnewstreamedit kinect 1 provide a stream itself should i use a thread to pumpit into the multistream did anybody have that kind of multistream class thanks,['c#'] +937071,chinese localization not worked with php gettext extension as it works with english i am already localized a website from russian to english with php and gettext just with wrapping all strings into string functionit worksheres the gists but it do not work with chinese translation i just added compiled mo and source po into localezh cnlc messages visit indexphplocalezh cn and do not see it translated at allwhat it wrong with chinesehave i to use other language code or somethingi use zh cn to map on chinese like it done in wordpressi cannot understand whyupdatethe problem was in html meta tag and charset going from server in windows1251 chop russian php serverafter i set meta charsetgbk and turned off adefaultcharset in htaccess chinese localization finally started to workafter all i added these modificationshtaccess adefaultcharset utf8 adefaultcharset off rewriterule cn indexphplocalezh cncharsetgbk lfunctionsphp included before doctype html charset getcharset ifissetcharset charsetutf8 headphp the head tag content meta charsetcharsetso if i does not set charset into get request it becomes utf8 otherwise it goes from get request for chiense i set it to gbk like on taobaocom and browser sets up right charsetbut after all i just has cyrillic characters encoded in chinese glyphs character by characterlike this n2 n n3 becomes this e eif you paste these chinese characters into decoder app chose gb2312 on left one from chinese charsets and utf8 on right you will have 2 3 a some cyrillic characters corrupted but this is obviously an original string because in translation i have more shorten a for this phrasehelp me pleaseupdate 2i just forgot to set bind textdomain codeset to domain it was messagesall works on unicode charset all normal,['php'] +937110,google play api returning error 401 i am using gradleplaypublisher library to upload my app to google play but i get error 401 unauthorized when executing the publishing taskmy dev account at google play and service account at dev console are set up play api is enabled as i see from build logs the first request sent ispost i get 200 ok and the following json access token some value here token type bearer expires in 3600then the next request is sentpost my apps package name hereeditsfirst of all i noticed this header among others authorization not loggedand second i get this error as a response401 unauthorizedwauthenticate bearer realm errorinvalid tokenhas anyone faced the same issue everything seems to be set up correctly so i have no idea what went wrong thank you,['android'] +937193,avaudioplayer preloaded sound leaks from memory i have an avaudioplayer instance that loads sound in memory with audioplayerpreparetoplay and then after a few start playing it i have a problem that in approximately ten minutes after entering background it leaks from memory and i is not being prepared after that fed hours i do not have an ability to run preparetoplay again how to leave that preloaded sound in memory for a long term i am preparing sound to play in applicationdidfinishlaunchingwithoptionsmethodlet thispatchqueue thispatch get global queuethispatch queue priority default 0 thispatch asyncthispatchqueue weak self in var audiosessionerror nserror let audiosession avaudiosessionsharedinstance nsnotificationcenterdefaultcenteraddobserverself selector handleinterruption name avaudiosessioninterruptionnotification object nil audiosessionsetactivetrue error nil if audiosessionsetcategoryavaudiosessioncategoryplayback error audiosessionerror printlnsuccessfully set the audio session else printlncould not set the audio session let filepath nsbundlemainbundlepathforresourcesound oftypemp3 let filedata nsdatacontentsoffile filepath options datareadingmappedifsafe error nil var errornserror selfaudioplayer avaudioplayerdata filedata error error selfaudioplayernumberofloops 1 selfaudioplayerdelegate self if selfaudioplayerpreparetoplay false printlnsuccessfully prepared for playing else printlnfailed to prepare for playing then in didreceiveremotenotification i am trying to play it in background selfaudioplayerplay it returns true probably it works but after about 10 20 minutes it does not work and note that play now returns falseis there a sense to thisable arc automatic reference counting to release and dealloc audioplayer manuallymaybe i need to use lower level apis such as openal however i would not use it since it is deprecated in ios 9 and later i will need to rewrite it without openalany more ideas maybe i need to use audio units with remoteio if it will work provide some examples pleasemaybe there are third party frameworks like objectal an easy implementation of openal as i know it is available in ios 9these methods are just my assumptions but them main question remains the same will those methods work from background,['ios'] +937416,are variables declared with let or const not hoisted in es6 i have been playing with es6 for a while and i noticed that while variables declared with var are hoisted as expectedconsolelogtypeof name undefinedvar name johnvariables declared with let or const seem to have some problems with hoistingconsolelogtypeof name referenceerrorlet name johnandconsolelogtypeof name referenceerrorconst name johndoes this mean that variables declared with let or const are not hoisted what is really going on here is there any difference between let and const in this matter,['javascript'] +937480,fibers vs async await i am joining a c project in which the developers are heavily using fibers before this project i have not even heard of them and previously used async await and threads and backgroundworkers to my multitasking operations today i was asking them why they used fibers and the main developer said that it is easier for him to debug meaning he knows which thread a particular function has come from and even could access the variables higher in the stacki was wondering what are the advantages and thisadvantages of using fibers vs using the new async await and using threadsps were using net 45,['c#'] +937506,javascript how to acess rowdatapacket i am currently developing a desktop application with nodewebkit during that process i need to get some data from a local mysqldatabasethe querying works fine but i cannot figure out how to access the results i store all of them in an array that is then passed to a function in the console they look like thisrowdatapacket user id 101 actionsperformed 20rowdatapacket user id 102 actionsperformed 110rowdatapacket user id 104 actionsperformed 3and here is the query structurevar ret connquerysqlquery functionerr rows fields if err alert else for var i of rows retpushi dostuffwiththeresultrethow do i retrieve this in the dostuffwiththeresult function the values are more important but if i could get the keys as well that would be great,"['javascript', 'mysql']" +937507,a usingdeclaration can not be repeated in function scope why is that in namespaceudecl10 you have the following examplenamespace a int inamespace a1 using ai using ai ok double declarationvoid f using ai using ai error double declarationthis snippet compiles in clang,['c++'] +937537,how to add postgresql datasource to wildfly 90 i have tried tutorial at masterthebosscomjbossclishmodule add nameorgpostgres resourcestmppostgresql931101jdbc41jar dependenciesjavaxapijavaxtransactionapisubsystemdatasourcesjdbcdriverpostgresadrivernamepostgresdrivermodulenameorgpostgresdriverclassnameorgpostgresqldriverdatasource add jndinamejavapostgreds namepostgrepool connectionurljdbcpostgresqllocalhostpostgres drivernamepostgres usernamepostgres passwordpostgresthis tutorial works with wildfly 82 but it does not work with wildfly 90 3rd step fails with error messageoutcome failedfailuredescription wflyjca0041 failed to load module for driver orgportgresrolledback truehow to add postgres datasource to wildfly 90,['java'] +937676,laravel class guzzlehttpclient not found i am trying to use mandrill to send emails via my laravel framework however i am receiving the following errorfatalerrorexception in mandrilltransportphp line 114 class guzzlehttpclient not foundi have installed guzzle using the following command in terminalguzzlehttpguzzle 40according to laravels documentation i need to add guzzlehttpguzzle 40 to my composerjson file but i am not sure if where i have placed it is correct as i still see the error name laravellaravel description the laravel framework keywords framework laravel license mit type project require laravelframework 50 illuminatehtml 50 guzzlehttpguzzle 40 requiredev phpunitphpunit 40 phpspecphpspec 21 autoload classmap database psr4 app app autoloaddev classmap teststestcasephp scripts postinstallcmd php artisan clearcompiled php artisan optimize postupdatecmd php artisan clearcompiled php artisan optimize postcreateprojectcmd php r copyenvexample env php artisan keygenerate config preferredinstall thist here is the list of packages my application has notice that guzzle has a different version 423 which i have also tried updating to but still get the same error,['php'] +937716,set imageview after orientation change i have the following code which is working perectly fine till i rotate my phone then i have to click again to load an image i understand that when we rotate the activity restarts and we have some methods to store the state and restore it but in my case as you can see that the img file is in a string as it is generated at randomso how can i make use of onconfigurationchanged which seems easy to understand to restore the previous image before rotationpublic class homescreen extends activity protected imageview imgview protected string str override protected void oncreatefinal bundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity home screen final random rnd new random actionbar actionbar getactionbar actionbarhide imgview imageview findviewbyidridimgrandom if savedinstancestate null str savedinstancestategetstringparam imgviewsetimagedrawable getresourcesgetdrawablegetresourceidstr drawable getapplicationcontext imgviewsetonclicklistenernew viewonclicklistener override public void onclickview view final imageview img imageview findviewbyidridimgrandom i have 3 images named img 0 to img 2 so str img rndnextint9 imgviewsetimagedrawable getresourcesgetdrawablegetresourceidstr drawable getapplicationcontext protected void onsaveinstancestatebundle savedinstancestat superonsaveinstancestatesavedinstancestat savedinstancestatputstringparam str when i rotate it is crashing and also on load or onclick no images are loading 0707 2132950 iinputreader468 device reconfigured id1 namegenymotion virtual input size 1080x1920 orientation 0 mode 1 thisplay id 0 0707 2132950 iactivitymanager468 config changes480 10 310mcc260mnc en us layoutdir sw360dp w360dp h567dp 480dpi nrml port finger qwertyvv dpadv s14 0707 2133081 wresourcetype1861 too many attribute references stopped at 0x01010034 0707 2133081 wresourcetype1861 too many attribute references stopped at 0x01010034 0707 2133082 dandroidruntime1861 shutting down vm 0707 2133083 eandroidruntime1861 fatal exception main 0707 2133083 eandroidruntime1861 process appmotivationtechiequickieypbmotivation pid 1861 0707 2133083 eandroidruntime1861 javalangruntimeexception unable to start activity componentinfoappmotivationtechiequickieypbmotivationappmotivationtechiequickieypbmotivationhomescreen javalangnullpointerexception name is null 0707 2133083 eandroidruntime1861 at androidappactivitythreadperformlaunchactivityactivitythreadjava2325 0707 2133083 eandroidruntime1861 at androidappactivitythreadhandlelaunchactivityactivitythreadjava2387 0707 2133083 eandroidruntime1861 at androidappactivitythreadhandlerelaunchactivityactivitythreadjava3947 0707 2133083 eandroidruntime1861 at androidappactivitythreadaccess900activitythreadjava151 0707 2133083 eandroidruntime1861 at androidappactivitythreadhhandlemessageactivitythreadjava1309 0707 2133083 eandroidruntime1861 at androidoshandlerthispatchmessagehandlerjava102 0707 2133083 eandroidruntime1861 at androidoslooperlooplooperjava135 0707 2133083 eandroidruntime1861 at androidappactivitythreadmainactivitythreadjava5254 0707 2133083 eandroidruntime1861 at javalangreflectmethodinvokenative method 0707 2133083 eandroidruntime1861 at javalangreflectmethodinvokemethodjava372 0707 2133083 eandroidruntime1861 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava903 0707 2133083 eandroidruntime1861 at comandroidinternaloszygoteinitmainzygoteinitjava698 0707 2133083 eandroidruntime1861 caused by javalangnullpointerexception name is null 0707 2133083 eandroidruntime1861 at androidcontentresresourcesgetidentifierresourcesjava2034 0707 2133083 eandroidruntime1861 at appmotivationtechiequickieypbmotivationhomescreengetresourceidhomescreenjava148 0707 2133083 eandroidruntime1861 at appmotivationtechiequickieypbmotivationhomescreenoncreatehomescreenjava35 0707 2133083 eandroidruntime1861 at androidappactivityperformcreateactivityjava5990 0707 2133083 eandroidruntime1861 at androidappinstrumentationcallactivityoncreateinstrumentationjava1106 0707 2133083 eandroidruntime1861 at androidappactivitythreadperformlaunchactivityactivitythreadjava2278 0707 2133083 eandroidruntime1861 11 more 0707 2133084 wactivitymanager468 force finishing activity 1 appmotivationtechiequickieypbmotivationhomescreen,['android'] +937825,how can a parameter in a generic method be assigned to an integer and a character class at the same time why this code is not showing any compilation errorpublic class generic public static void mainstring args character arr3abcdefg integer a97 systemoutprintlnnon genregenmethodaarr3 class non genre statict boolean genmethodt xt y int flag0 fort ry ifrx flag ifflag0 return false return true if we write a normal code like thisshown belowpublic class hello public static void mainstring args character arr65 integer aa ifarra compilation errorshows incompatible types integer and character systemoutprintlntrue then why the above above is running finehow can t be of integer class and array of t be of character class at the same timeand if its running then why its not printing trueascii vaue of a is 97so it should print true,['java'] +937969,fragment vs custom view in android the fragment and custom view can achieve the similar function i know that fragment is more reusable comparing with custom view any other benefitsenhancements for using fragment is fragment supposed to replace custom view or just a enhancement for some specific purpose for instance the code below is fragment public class testfragment extends fragment private textview tv name private button btn play private button btn delete override public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate return inflaterinflaterlayouttestfragment container false override public void onstart superonstart tv name textviewgetviewfindviewbyidridtv name btn play buttongetviewfindviewbyidridbtn play btn delete buttongetviewfindviewbyidridbtn delete the code for custom view public class testcustomview extends linearlayout private textview tv name private button btn play private button btn delete public testcustomviewcontext context attributeset attrs supercontext attrs setorientationlinearlayouthorizontal setlayoutparamsnew layoutparamslayoutparamsmatch parent layoutparamsmatch parent tv name new textviewcontext addviewtv name btn play new buttoncontext addviewbtn play btn delete new buttoncontext addviewbtn delete public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate return inflaterinflaterlayouttestfragment container false both testfragment testcustomview can create a view consisting of textview buttons and use tags of framelayoutfragment and compackagenametestcustomview to declare in the activitys xml layout file but whats the advantages to use fragment thanks in advance,['android'] +938040,flasklogin does not work on local machine but fine on hosting i have a flask app and i use flasklogin following tutorials nothing fancy hereworks fine on hostingworks fine on my local mac computer at homedoes not work on my local linux computer at office which may be behind a firewall but i am able to do portforwarding and connect to the databasefrom flaskextlogin import loginmanager login manager loginmanagerlogin managersession protection stronglogin managerinit appapplogin managerlogin view logindef login error none form loginform if requestmethod post user dbusersfind oneusername formusernamedata pass hash generate password hashformpassworddata if user and uservalidate login pass hash userpassword user obj useruserusername sessionlogged in true login useruser objremembertrue flashlogged in successfully categorysuccess print logged in ok return redirectrequestargsgetnext or url forindex return redirect url forindex error invalid credentials return render templateloginhtml titlelogin localswell when i enter my password wrong it gives the invalid credentials error when i enter my password correctly i do not see logged in successfully flash but on console i see logged in ok so there is no problem with db connection however i am not logged in for exampleguseris authenticatedgives false in the template this occurs only on my local linux on the other hand hosting and mac successfully logs in the user,['python'] +938099,django manytomany field how to get check for 80 subset match i have a django db with cooking recipes i want to query all users who have at least 80 ingredients to make a recipe how do i achieve thisor how do i query for users who are missing only 1 ingredient for the recipemodelspyclass ingredientmodelsmodel id modelsautofieldidmax length 100 primary keytrue namemodelscharfieldingredient max length100 def unicode self return selfnameclass usermodelsmodel id modelsautofieldidmax length 100 primary keytrue ingredient modelsmanytomanyfieldingredientblanktrue def unicode self return strselfidclass recipemodelsmodel id modelsautofieldid max length100 primary keytrue recipe ingredient modelsmanytomanyfieldingredientrelated namerecipe ingredientblanktrue def unicode self return selfid,['python'] +938179,why some int from 0x0 to 0xf is not a defined unicode character i read from the java doc of character that the set of characters from u0 to uf is sometimes referred to as the basic multilingual plane bmpbut i tried the following code and found there is 2492 int is not defined is there any thing wrong or i have some misunderstanding thankspublic static void main string args int count0 forint i 0x0 i0xfi ifcharacterisdefinedi count systemoutprintlncountoutput 2492,['java'] +938280,how do i check if an iterator is actually an iterator container i have a dummy example of an iterator container below the real one reads a file too large to fit in memoryclass dummyiterator def init self max value selfmax value max value def iter self for i in rangeselfmax value yield idef regular dummy iteratormax value for i in rangemax value yield ithis allows me to iterate over the value more than once so that i can implement something like thisdef normalisedata total sumi for i in data for val in data yield val total this works when i call nextnormalisedummyiterator100 this does not work when i call nextnormaliseregular dummy iterator100how do i check in the normalise function that i am being passed an iterator container rather than a normal generator,['python'] +938309,systemruntimeinteropservicescomexception when launching a pdf file on windows phone i am trying to open a pdf file using the below working code i previously used on another appbut this time i am getting systemruntimeinteropservicescomexception when the flow hits this line windowssystemlauncherlaunchfileasyncpdffile what is the meaning of this exception and how to get rid of itplease note that without caring about this exception thisabling it the file still cannot be openedplease note the file exists in my isolated folder checked with wpowertooli tried with 2 different files so it shouldnt be a matter of file corruption public void openfilestring options systemdiagnosticsdebugwritelineoptions options string optval jsonhelperdeserializestringoptions0 asyncopenoptval public async task asyncopenstring filename filename filenamesubstring2 filenamelength 2 filename filenamereplace replace windowsstoragestoragefolder local windowsstorageapplicationdatacurrentlocalfolder debugwritelinelocal localpath windowsstoragestoragefile pdffile await localgetfileasyncfilename debugwritelinepdffile pdffilename launch the pdf file windowssystemlauncherlaunchfileasyncpdffile this msdn post belongs to me yes the file is installed and i have acrobat readerplease note that this c code is a phonegapcordova plugin which is called via javascript in my hybrid application,['c#'] +938355,circle loading animation i am trying to create apples os x circle loading animationwhat i have tried so faranimationwrapper width 200px height 200px border 1px solid black borderradius 50 position relative overflow hidden filter brightness08 webkitfilter brightness08piepiece1 position absolute width 50 height 50 bottom 0 left 0 background lineargradientto right rgba255 0 0 1 0 rgba255 255 0 1 100piepiece2 position absolute width 50 height 50 bottom 0 right 0 background lineargradientto right rgba255 255 0 1 0 rgba0 255 0 1 100piepiece3 position absolute width 50 height 50 top 0 left 0 background lineargradientto right rgba255 0 0 1 0 rgba255 0 255 1 100piepiece4 position absolute width 50 height 50 top 0 right 0 background lineargradientto right rgba255 0 255 1 0 rgba0 0 255 1 100rotatingspinners position absolutespike fill rgba22 22 22 05figure classanimationwrapper div classpiepiece1div div classpiepiece2div div classpiepiece3div div classpiepiece4div svg classrotatingspinners width100 height100 viewbox0 0 100 100 xmlns xmlnsxlink defs path idspinpart claspike dm 6540 c 6540 8020 5050 6040 5040 5040z defs use x0 y0 xlinkhrefspinpart use x0 y0 xlinkhrefspinpart transformrotate60 50 50 use x0 y0 xlinkhrefspinpart transformrotate120 50 50 use x0 y0 xlinkhrefspinpart transformrotate180 50 50 use x0 y0 xlinkhrefspinpart transformrotate240 50 50 use x0 y0 xlinkhrefspinpart transformrotate300 50 50 svgfigurethe linear gradients do not seem to line up correctly since i could not find a way to make the gradients go in two directionsis there a way to create this using only css or svg without mixing them like i have done or are there other solutions i can use like canvas or some kind of image magic,"['html', 'css']" +938717,linkedin sdk duplicate symbol i downloaded latest linkedin sdk and added to my project but building failedduplicate symbol objc metaclass podsdummy pods in linkedinsdkframeworklinkedinsdkpodsdummyo buildproductsdebugiphonesimulatorlibpodsapodsdummyo duplicate symbol objc class podsdummy pods in linkedinsdkframeworklinkedinsdkpodsdummyo buildproductsdebugiphonesimulatorlibpodsapodsdummyo ld 2 duplicate symbols for architecture x86 64 clang error linker command failed with exit code 1 use v to see invocationdoes anyone know how to fix it,['ios'] +938724,java convert int to smallest representation as ranges given an array of int values how could one parse the series into counting sequence notationexamples1 2 3 4 5 9 13 14 15 15913154 6 8 10 11 12 15 17 46810121517i am looking for a method that would produce these results this is what i have so far but i am very much stumped at this pointtest codeimport javautilarrayspublic class testsequencing public static void mainstring args int numbers1 1 2 3 4 5 9 13 14 15 string numbers1s 1591315 systemoutprintlnarraystostringnumbers1 systemoutprintlnexpectedt numbers1s systemoutprintlnproducedt sequencenumsnumbers1 n int numbers2 3 5 6 9 12 string numbers2s 356912 systemoutprintlnarraystostringnumbers2 systemoutprintlnexpectedt numbers2s systemoutprintlnproducedt sequencenumsnumbers2 n int numbers3 1 2 3 4 5 6 7 string numbers3s 17 systemoutprintlnarraystostringnumbers3 systemoutprintlnexpectedt numbers3s systemoutprintlnproducedt sequencenumsnumbers3 n public static string sequencenumsint nums stringbuilder sb new stringbuilder int rangestart nums0 int previous nums0 int current int expected previous 1 for int i 1 i numslength i current numsi expected previous 1 if current expected i numslength 1 if current rangestart sbappendprevious else sbappendrangestart previous rangestart current previous current if sbcharatsblength 1 sbdeletecharatsblength 1 return sbtostring output1 2 3 4 5 9 13 14 15expected 1591315produced 159913143 5 6 9 12expected 356912produced 3356991 2 3 4 5 6 7expected 17produced 16,['java'] +938818,finish all asynchronous requests before loading data i have run into an issue where i have multiple asynchronous requests occuring which grab images and information from the facebook api and my firebase database i want to perform all my asynchronous requests then store all that data that i grabbed from the facebook apifirebase database into one entire object which i can quickly load i have set up completion handlers for every asynchronous request which i thought forces the program to wait until the request is complete and then have the program continue but that does not seem to work for me below is my attemptfunc setupeventscompletion result bool event event void get a reference to events eventsreference firebaseurldb name eventattendeesref firebaseurldb name read the data at our posts reference printlnevent references eventsreference eventsreferenceobserveeventtypefeventtypechildadded withblock snapshot void in let eventname snapshotvalueeventname as string let eventlocation snapshotvalueeventlocation as string let eventcreator snapshotvalueeventcreator as string var attendees nsmutabledictionary var attendeesimages uiimage let attendee nsmutabledictionary let group thispatch group create get attendees first thispatch group entergroup selfgetattendeessnapshotkey as string completion result name objectid void in ifresult true printlnfinished grabbing name objectid attendeesaddentriesfromdictionaryattendee as nsobject anyobject else printlnfalse thispatch group leavegroup get attendees photos thispatch group entergroup selfgetattendeespicturesattendee completion result image void in if result true printlnfinished getting attendee photos now to store into event object attendeesimagesappendimage else printlnfalse thispatch group leavegroup thispatch group notifygroup thispatch get main queue printlnboth requests done maintain array snapshot keys selfeventidsappendsnapshotkey if snapshot nil let event eventeventname eventname eventlocationeventlocation eventphotoeventphoto fromdatefromdate fromtimefromtime todatetodate totimetotime attendees attendees attendeesimagesattendeesimages attendeesimagestest attendeesimagestest privacyprivacy eventcreator eventcreator eventcreatorid eventcreatorid printlnevent event completionresult true event event error void in printlnerrordescription i know i have my completion handlers set correctly as i have tested in my program however what i want is that only after both the getattendees and getattendeespictures function completes i then want to store all the information i grabbed the snapshot getattendees and getattendeespictures function and store them into an event object any ideas on how to accomplish this i have tried to look into thispatch groups to help me handle this via this link checking for multiple asynchronous responses from alamofire and swift but my program seems to only execute the getattendees function but not the getattendeespictures function below are also the getattendees and getattendeespictures functionsfunc getattendeeschild string completion result bool name string objectid string void get event attendees of particular event var attendeesreference selfeventattendeesrefchildbyappendingpathchild printlnloading event attendees get all event attendees attendeesreferenceobserveeventtypefeventtypechildadded withblock snapshot void in let name snapshotvalueobjectforkeyname as string let objectid snapshotvalueobjectforkeyobjectid as string printlnname name object id objectid completionresult true name name objectid objectid error void in printlnerrordescription func getattendeespicturesattendees nsmutabledictionary completion result bool image uiimage void printlnattendees count attendeescount for key value in attendees let url nsurlstring keypicturetypelarge printlnurl url let urlrequest nsurlrequesturl url asynchronous request to thisplay image nsurlconnectionsendasynchronousrequesturlrequest queue nsoperationqueuemainqueue responsensurlresponse datansdata errornserror void in if error nil printlnerror error thisplay the image let image uiimagedata data ifimage nil completionresult true image image,['ios'] +938894,get type from stdstring c once i was asked a question during the interviewhence i have a function void fstdstring and i call a function as this fint so that my function must create a local int x in its body is there a way to get the type from const char i know that boostmplvector does solve this kind of problem can anyone tell me the technique,['c++'] +938939,can individual composer dependencies be suppressed from autoloading i have a project containing amongst others the following composerjson dependenciespropelpropel1 devmasterhalleck45phpmetrics devmasteri recently did a composer update and found that a new version of a library required by phpmetrics called hoa introduces a new class engineexception to emulate a new php7 class unfortunately propel 1 also defines engineexception and so a conflict resultsthe correct fix for this would be to upgrade to propel 2 which uses namespaces however this is still in alpha and is subject to bc breaks so is not really workable for memy present fix is to lock hoa to a specific version that does not have the new classhoacore 21504that is not a bad solution but it is not entirely satisfying to lock a library to an old versionin the hoa code the only way for the new class not to be loaded is to be running php 7 which is again not feasible however it also occurs to me that hoa only needs to be required when phpmetrics runs this is a standalone code analysis tool and only sits in the root of the project for convenience the rest of the project does not use this librarythus it would be great if i could call something in composer to ask that this class is not autoloaded or perhaps something to do the same in the composerjson it is being needlessly loaded at present i do not know whether it is being autoloaded incorrectly or whether it is being required manually by composerit may help to know that hoa classes have been added by composer to the autogenerated autoload psr4php script as far as i can understand the docs this means it is autoloaded and there is nothing in my project that would require any of the hoa classes,['php'] +938957,android how to create circle view with android i am creating a view as below design here like apple music pic 1pic 2 the pink circle with physical interaction and fly can you suggest ways to make them,['android'] +938959,how can i get menu item in navigationview androidsupportdesignwidgetnavigationview androidididdrawer nav androidlayout widthwrap content androidlayout heightmatch parent androidlayout gravitystart androidthemestylethemeappcompatlightnoactionbar appheaderlayoutlayoutdrawer header appmenumenumenu drawer i am using androidsupportdesignlibrary for material design what i want is to hide some menu items when the user is not loggedin now i have trouble to get the menu item in navigationviewi have triedmenuitem logoutitem menuitem mnavigationviewfindviewbyidridmenu logoutlogoutitemsetvisiblefalsebut it is not workinghow can i do thisthanks,['android'] +939103,draw splines by using direct2d i have the data of a spline curvedegreeknotscontrol pointsfit pointsand i need to draw this curve by using direct2d at the moment i am using the id2d1geometrysink interface to draw geometries but it seems it does not implements a possible addspline methodis there a way to draw spline by means of direct2d even a directx implementation that can be used in a direct2d application will be fine,"['c++', 'c']" +939115,picasso library does not load images from sd card on adroid i take a file from path from image gallery and try to load it a image view as follows file path is storagesdcard0dcimcamera1436267579864jpg i also tried passing uri i also have read privileges to sd cardit ends up in onerror method however similar method works fine for web urls how can i resolve thisprivate void getimagefile file iffileexists picassowithactivity loadfile errorrdrawablenoimage intoimgpreview new callback override public void onsuccess if progressbar null imgpreview null imgpreviewsetvisibilityviewvisible imgpreviewsettagloaded progressbarsetvisibilityviewgone override public void onerror if progressbar null imgpreview null imgpreviewsetvisibilityviewvisible progressbarsetvisibilityviewgone usespermission androidnameandroidpermissionwrite external storageusespermission androidnameandroidpermissionread external storageusespermission androidnameandroidpermissioninternetusespermission androidnameandroidpermissionaccess network state,['android'] +939154,aspnet 5 identity custom signinmanager i have a mvc 6 project vnext and i am playing around with the aspnet identity in my case i do not want to use the buildin stuff which uses the ef signinmanager usermanager userstore i have an external database and i just want to make a usernamepassword lookup and return a valid cookie so i started writing my own classes public class myuser public string id get set public string username get set public string password get set public string passwordhash get set public class myuserstore iuserstoremyuser iuserpasswordstoremyuser in the myuserstore class i am using hardcoded list of users as my store only for test purposes and i overrode some methods just to return the data from the hardcoded storepublic class myusermanager usermanagermyuser public myusermanager iuserstoremyuser store ioptionsidentityoptions optionsaccessor ipasswordhashermyuser passwordhasher ienumerableiuservalidatormyuser uservalidators ienumerableipasswordvalidatormyuser passwordvalidators ilookupnormalizer keynormalizer identityerrordescriber errors ienumerableiusertokenprovidermyuser tokenproviders iloggerfactory logger ihttpcontextaccessor contextaccessor basestore optionsaccessor passwordhasher uservalidators passwordvalidators keynormalizer errors tokenproviders logger contextaccessor here i made the methods checkpasswordasync and verifypasswordasync to return true and passwordverificationresultsuccess respectively just for the testpublic class myclaimsprinciplefactory iuserclaimsprincipalfactorymyuser public taskclaimsprincipal createasyncmyuser user return taskfactorystartnew var identity new claimsidentity identityaddclaimnew claimclaimtypesname userusername var principle new claimsprincipalidentity return principle public class mysigninmanager signinmanagermyuser public mysigninmanagermyusermanager usermanager ihttpcontextaccessor contextaccessor iuserclaimsprincipalfactorymyuser claimsfactory ioptionsidentityoptions optionsaccessor null iloggerfactory logger null baseusermanager contextaccessor claimsfactory optionsaccessor logger public override tasksigninresult passwordsigninasyncstring username string password bool ispersistent bool shouldlockout here goes the external username and password look up if usernametolower username passwordtolower password return basepasswordsigninasyncusername password ispersistent shouldlockout else return taskfromresultsigninresultfailed and everything is hooked up in the startup class as followsservicesaddidentitymyuser myrole adduserstoremyuserstore addusermanagermyusermanager adefaulttokenprovidersand because i did not manage to create the mysigninmanager object in the startup code in order to add it into the di for later injection in the controllers and views i am creating it in the myaccountcontrollerpublic myaccountcontrollerihttpcontextaccessor httpcontextaccessor usermanagermyuser usermanager ioptionsidentityoptions optionsaccessor iloggerfactory logger signinmanager new mysigninmanagerusermanager as myusermanager httpcontextaccessor new myclaimsprinciplefactory optionsaccessor loggerin my mylogin action in the myaccount controller i am calling passwordsigninasync and i can see that i am getting the cookie with the encoded claims in it from the myclaimsprinciplefactorywhen i try to call some other action with the authorizeattribute on it i can see that the cookie is in the request header but i am unauthorized more precisely because i did not remove the builtin default aspnet identity authentication from the visual studio sample template i am redirected to the accountlogin insteadis this the right way of customizing aspnet identity and what am i missing here,['c#'] +939188,what is this format for seconds x win32 networkloginprofile querying a wmi object on the colitems getwmiobject win32 networkloginprofile namespace rootcimv2 whereobject name match name selectobject namepasswordageaccording to msdnpasswordagedata type datetime access type readonly length of time a password has been in effect this value is measured from the number of seconds elapsed since the password was last changed example 012010230 0i am getting 0682352230so i have tried casting this to timespanand datetime no luckwhat does the colon represent how to get number hours it representthanks adding the wmi class name to title for the next poor soul that get confused by documentation wordinghere is what worksthat worked perfectly str 0682352230ts systemmanagementmanagementdatetimeconvertertotimespanstrdays 68hours 23minutes 52seconds 23milliseconds 0ticks 59611430totaldays 689947106481481totalhours 1655873056totalminutes 99352383totalseconds 5961143totalmilliseconds 59611430,"['c#', '.net']" +939204,how to split a string while maintaining whitespace how do you split a string of words and retain whitespaceshere is the code string words ssplit string s contains hello worldafter the code runs words contains hello worldideally it should not be an empty string in the middle but contain both whitespaces words should be hello worldhow do i get it to have this result,['java'] +939236,integrating smack with android studio project for chat application i am trying to implement a chat messenger using ejabberd server and smack library but having a hard time to integrate all the jars and dependencies of smack i am using android studiomy buildgradlemodule apply plugin comandroidapplication android compilesdkversion 22 buildtoolsversion 2201 defaultconfig applicationid comexamplenitxmppclient minsdkversion 18 targetsdkversion 22 versioncode 1 versionname 10 buildtypes release minifyenabled false proguardfiles getdefaultproguardfileproguardandroidtxt proguardrulespro dependencies compile filetreedir libs include jar compile comandroidsupportappcompatv720 compile orgigniterealtimesmacksmackandroid410 compile orgigniterealtimesmacksmacktcp410 compile orgigniterealtimesmacksmackandroidextensions410 compile orgogcexpp3116 firstly i was getting xmlpullparser error then i added xpp3 but after i added xpp3 i am getting errorgradle execution failed for task apredexdebug comandroididecommonprocessprocessexception orggradleprocessinternalexecexception process command usrlibjvmjava7openjdkamd64binjava finished with nonzero exit value 1buildgradleproject toplevel build file where you can add configuration options common to all subprojectsmodulesbuildscript repositories jcenter dependencies classpath comandroidtoolsbuildgradle122 note do not place your application dependencies here they belong in the individual module buildgradle files allprojects repositories jcenter maven url mavencentral questions how to remove the error or what can be the cause of error i might be missing some dependency using smock will increase the appsize can i acheive im without using any library and writing server side code instead like using ejabberd library for nodejs and the android app talking to nodejs instead of ejabberdand yes i more thing public class xmppclient private static int port 52 private static string host myip private static string service mycom static xmpptcpconnectionconfiguration conf xmpptcpconnectionconfigurationbuilder setservicenameservice setportport sethosthost setcompressionenabledfalsebuild static xmpptcpconnection connection new xmpptcpconnectionconf public static void registerstring username string password throws smackexceptionnotconnectedexception xmppexceptionxmpperrorexception smackexceptionnoresponseexception accountmanager accountmanager accountmanagergetinstanceconnection accountmanagercreateaccountusernamepassword public static void main string args throws smackexceptionnotconnectedexception xmppexceptionxmpperrorexception smackexceptionnoresponseexception registeruser password i am getting the error when i am running the xmppclient class,['android'] +939316,cors header accesscontrolalloworigin missing i am calling this function from my aspnet form and getting following error on firebug console while calling ajaxcrossorigin request blocked the same origin policy thisallows reading the remote resource at httpanotherdomaintestjson reason cors header accesscontrolalloworigin missingvar url httpanotherdomaintestjson ajax url url crossorigin true type get xhrfields withcredentials true accept applicationjson donefunction data alertdata failfunction xhr textstatus error var title message switch xhrstatus case 403 title xhrresponsejsonerrorsummary message please login to your server before running the test break default title invalid url or crossorigin request blocked message you must explictly add this site windowlocationorigin to the list of allowed websites in your server break i have done alternate way but still unable to find the solutionnote i have no server rights to make server sideapiurl changes,['jquery'] +939347,atomic shared ptr for lockfree singly linked list i am wondering if it is possible to create a lockfree threadsafe shared pointer for any of the common architectures like x64 or armv7 armv8in a talk about lockfree programming at cppcon2014 herb sutter presented a partial implementation of a lockfree singly linked list the implementation looks quite simple but it relies on an atomic shared ptr implementation that does not exist in the standard library yet or on using the specialized stdatomic functions this is especially important as single pushpop calls potentially invoke multiple atomic loadsstores and compare exchange operations the problem i see and i think some of the questions in the talk went into the same direction is that for this to be an actual lockfree data structure those atomic operations would have to be lockfree themselves i do not know of any standard library implementation for the stdatomic functions that is lockfree and at least with a short google so search i also did not find a suggestion of how to implement a lockfree specialization for stdatomicstdshared ptr now before i am wasting my time on this i wanted to ask do you know if it is possible to write an lockfree atomic shared pointer at allare there already any implementations that i have overlooked and ideally are even compatible with what you would expect from a stdatomicstdshared ptr for the mentioned queue it would especially require a casoperationif there is no way to implement this on current architectures do you see any other benefit in herbs implementation compared to a normal linked list that is protected by a lockfor reference here is the code from herb sutter might contain typos from metemplateclass t class slist struct node t t stdshared ptrnode next stdatomicstdshared ptrnode head public class reference stdshared ptrnode p public referencestdshared ptrnode p t operator return pt t operator return pt auto findt t const auto p headload while p p t p p next return referencemovep void push frontt t auto p stdmake sharednode pt t pnext head while headcompare exchange weakpnext p void pop front auto p headload while p headcompare exchange weakp p next note that in this implementation single instances of a shared ptr can be accessed modified by multiple different threads it can be readcopied reset and even deleted as part of a node so this not about whether multiple different shared ptr objects that manage the same object can be used by multiple threads without a race condition this that is already true for current implementations and required by the standard but it is about concurrent access to a single pointer instance which is for standard shared pointers no more threadsafe than the same operations on raw pointers would beto explain my motivationthis is mainly an academic question i have no intention of implementing my own lock free list in production code but i find the topic interesting and at first glance herbs presentation seemed to be a good introduction however while thinking about this question and sehe is comment on my answer i remembered this talk had another look at it and realized that it does not make much sense to call herbs implementation lockfree if it is primitive operations require locks which they currently do so i was wondering whether this is just a limitation of the current implementations or a fundamental flaw in the design,['c++'] +939423,documenting a wrapped rest response using swagger ui i have a widgetdto that i have annotated with swagger ui annotations the final response wraps a list of widgetdtos with a layer of metadata per page 21 of this restful best practices document for example data id 1234 prop1 val1 id 5678 prop1 val2 my java code looks like thisgetproducesmediatypeapplication jsonapioperation value get all widgets response widgetdtoclassapiresponsesvalue apiresponsecode 200 message returns the list of widgetspublic response getwidgets listwidgetdto widgets mapstring object responsebody new hashmap responsebodyputdata widgets return responseokresponsebodybuildi would like to reuse this pattern on multiple resources and i do not want to create list dtos for every response type is there an elegant way to use swagger to document these types of response bodies,['java'] +939478,how to limit one session from any browser for a username in flask i am using a gunicorn server in which i am trying to figure out a way to limit only one session per username ie if user a is logged in to the app from chrome he should not be able to login through firefox unless he logs out of chrome or shouldnt be able to open another tab in chrome itselfhow can i generate a unique id for the browser and store it in a db so that until the user logs out or session expires the user cant login through any other browser,['python'] +939534,are htmlcollection and nodelist iterables in es6 an iterable is an object that allows for of and has a symboliterator key arrays are iterables as are sets and maps the question is are htmlcollection and nodelist iterables are they supposed to bemdn documentation seems to suggest a nodelist is an iterableforof loops will loop over nodelist objects correctly in browsers that support forof like firefox 13 and laterthis appears to corroborate firefoxs behaviouri tested the following code in both chrome and firefox and was surprised to find that firefox seem to think they are iterables but chrome does not in addition firefox thinks that the iterators returned by htmlcollection and nodelist are one and the samevar col documentgetelementsbyclassnametest should get htmlcollection of 2 elemsvar nod documentqueryselectoralltest should get nodelist of 2 elemsvar arr slicecallcol should get array of 2 elemsconsolelogcolsymboliterator firefox iterator function chrome undefinedconsolelognodsymboliterator firefox iterator function chrome undefinedconsolelogarrsymboliterator firefox chrome iterator functionconsolelogcolsymboliterator nodsymboliterator firefox trueconsolelogcolsymboliterator arrsymboliterator firefox falsediv classtest1divdiv classtest2divone really weird confusing thing running the code snippet produces a different result from copying it and running in an actual fileconsole in firefox particularly last comparison any enlightenment on this weird behaviour here would be appreciated too,['javascript'] +939648,mvc controller return a bad request i was wondering if it was possible to return a bad request with content from an mvc controller the only way i have been able to do this is to throw httpexception however here i cannot set any content tried this approach to but for some odd reason i am always getting an ok back is it possible to do thispublic class somecontroller controller httppost public async taskhttpresponsemessage foo var response new httpresponsemessagehttpstatuscodebadrequest responsecontent new stringcontentnaughty return response,['c#'] +939676,is there a significantly better way to find the most common word in a list python only considering a trivial implementation of the problem i am looking for a significantly faster way to find the most common word in a python list as part of python interview i received feedback that this implementation is so inefficient that it is basically failure later i tried many algorithms i found and only some heapsearch based solutions are a bit faster but not overwhelmingly when scaled to tens of millions of items heapsearch is about 30 faster on trivial lengths like thousand it is almost the same using timeitdef stupidwords freqs for w in words freqsw freqsgetw 0 1 return maxfreqs keyfreqsgetas this is a simple problem and i have some experience although i am nowhere algorithms guru or competitive coder i was surprisedof course i would like to improve my skills and learn that so much better way of solving the problem so your input will be appreciatedclarification for duplicate status my point is to find out if there is actually much asymptotically better solution and other similar questions have picked an answer that is not much better if this is not enough to make the question unique close this question of courseupdatethank you all for the input regarding the interview situation i remain with the impression that hand written search algorithm was expected that may be somewhat more efficient andor the reviewer was assessing code from the point of view of another language with different constant factors of course everyone can have own standards what was important for me was to validate if i am totally clueless i had the impression that i am not or just usually write not the best possible code it is still possible that even better algorithm exists but if it remained hidden for the community here for a few days i am fine with thati am picking the most upvoted answer it seems fair to do so even though more than one people privided usefull feedbackminor updateit seems that using defaultdict has a noticeable advantage over using the get method even if it is statically aliased,['python'] +939781,why is printf with a single argument without conversion specifiers deprecated in a book that i am reading it is written that printf with a single argument without conversion specifiers is deprecated it recommends to substituteprintfhello worldwithputshello worldorprintfs hello worldcan someone tell me why printfhello world is wrong it is written in the book that it contains vulnerabilities what are these vulnerabilities,['c'] +939883,textinputlayout not showing when view added programmatically i noticed some strange behaviour of textinputlayout when i add the following to my layout androidsupportdesignwidgettextinputlayout androidlayout widthmatch parent androidlayout heightwrap content edittext androidididtxtfirstname stylestyleedittextstyle androidlayout widthmatch parent androidlayout heightmatch parent androidhintin layout androidsinglelinetrue androidsupportdesignwidgettextinputlayouteverything works as expected when i inflate a similar layout like view v layoutinflaterfromthisinflaterlayoutedittext w surrounding textinputlayout null edittext edittext edittext vfindviewbyidridedittext edittextsethintadded programmatically viewgroup root viewgroup findviewbyidridroot rootaddviewvthe textinputlayout does not appear and the edittext behaves the standard way any ideas what the reason could be,['android'] +939902,is it safe to delete from an array inside each is it possible to safely delete elements from an array while iterating over it via each a first test looks promisinga 14to aaeach i adeletei if i 2 1 3 4 however i could not find hard facts onwhether it is safe by designsince which ruby version it is safeat some points in the past it seems that it was not possible to doit is not working because ruby exits the each loop when attempting to delete somethingthe documentation does not state anything about deletability during iterationi am not looking for reject or delete if i want to do things with the elements of an array and sometimes also remove an element from the array after i have done other things with said elementupdate 1 i was not very clear on my definition of safe what i meant wasdo not raise any exceptionsdo not skip any element in the array,['ruby'] +939920,c get most common string in a model list i want to get the most common string from a model list using linq but i do not really know howhere is some example codepublic modelclass public string name get set public int num get set imagine a huge listof modelclass is stored in the database in some controllervar model from s in dbsomeclass select sstring mostcommonname how would i find the most common name from this list using linq,['c#'] +940668,bind array of strings in the butterknife i am trying to bind array of strings using butterknife but seems that there is no way but in processor there is a method to bind arrayhere is my codestringsxmlstringarray nametest strings itemvkitem itemfacebookitem itemtwitteritem iteminstagramitem itemgoogle plusitem itemgoogle mailitemstringarraymainactivitybindrstringtest stringsprotected string mstrings,"['java', 'android']" +940725,internal mechanism of sizeof in c i use sizeof to get size of a struct in c but the result i got is unexpectedstruct sdshdr int len int free char bufint main printfstruct lendnsizeofstruct sdshdr return 0 struct len8 with or without bufmy question is why does buf not occupy any space and why is the size of the int type still 4 on a 64bit cpuhere is the output from gcc vconfigured with prefixapplicationsxcodeappcontentsdeveloperusr withgxxincludedirusrincludec421apple llvm version 610 clang602053 based on llvm 360svntarget x86 64appledarwin1440thread model posix,['c'] +940845,nspointerarray weird compaction i have a weak nspointerarray with some nsobject that has been released before calling compact what i see islldb po currentarray count1lldb po currentarray pointeratindex0nildb po currentarray allobjects nsarraym 0x16f04f00that makes sense but what is really weird is that when i call compact on that array i see the same values count still returns 1 and pointeratindex0 is nilwhy the nil has not been removededitheres the full code yeah it is xctesting framework voidtestcompaction weak id testingpointer nil nspointerarray weakarray nspointerarray weakobjectspointerarray autoreleasepool nsobject someobj nsobject alloc init testingpointer someobj weakarray addpointer bridge voidtestingpointer nslogbefore compaction inside autorelease testingpointer count d allobjects pointeratindex0 pointeratindex0 class testingpointer weakarray count weakarray allobjects weakarray pointeratindex0 idweakarray pointeratindex0 class someobj nil nslogbefore compaction outside autorelease testingpointer count d allobjects pointeratindex0 pointeratindex0 class testingpointer weakarray count weakarray allobjects weakarray pointeratindex0 idweakarray pointeratindex0 class weakarray compact nslogafter compaction outside autorelease testingpointer count d allobjects pointeratindex0 pointeratindex0 class testingpointer weakarray count weakarray allobjects weakarray pointeratindex0 idweakarray pointeratindex0 classand logs before compaction inside autorelease testingpointer nsobject 0x7de7ff80 count 1 allobjects nsobject 0x7de7ff80 pointeratindex0 nsobject 0x7de7ff80 pointeratindex0 class nsobject20150720 142714062 appetizesuite copy541449019054 before compaction outside autorelease testingpointer null count 1 allobjects pointeratindex0 null pointeratindex0 class null20150720 142722615 appetizesuite copy541449019054 after compaction outside autorelease testingpointer null count 1 allobjects pointeratindex0 null pointeratindex0 class null why the compact method does not delete the first pointer it is clearly a nil before calling compact,['objective-c'] +940866,sharing a mongoid model between 2 applications using engine vs plugin i want to share a model between 2 maybe more in the future of my rails apps i could not find any clear suggestions but i picked up some of the questions and answers i have read and came to a conclusion that it has to be done with a gemmed plugin engine i decide to go with an plugin because i read that engine is simply a kind of a full pluginso i created a plugin using rails plugin new my models skipactiverecord skiptestunit dummypathspecdummy the options are for skipping activerecord as an orm and using rspec for testingafter i created the plugin i got the following filesmy modelsgemspec gemfile gemfilelock lib mitlicense rakefile readmerdoc speci tried to include the model using the following methodsjust creating an appmodels directory and put my model insideas suggested in this tutorial and i could see in devises github i created a generator in an attempt to generate the modelboth of them failed and then i decided to go with the engine suggestion by just adding mountable to the options list of the rails new command i got the full rails app structure with app bin db and the rest of the directories put my model in the appmodels dir and it worked like a magic as i believe i am a programmer and not i magician i do not to do such magics so can you tell me whats wrong with both of my thin plugin solutions using generatorcreating a model moreover what are the advantages of using those generatorsi am attaching my generators code maybe i miss somethingrequire railsgeneratorsnamed baserequire mongoidmodule mongoid module attackgenerator def generate model invoke mongoidmodel name unless model exists behavior invoke end def inject field types inject into file model path migration data after include mongoiddocumentn if model exists end def migration data field link url type string field token type string end def model exists fileexistsfilejoindestination root model path end def model path model path filejoinapp models file pathrb end endend,['ruby-on-rails'] +940914,why does the promise constructor require a function that calls resolve when complete but then does not it returns a value instead as i plunge into studying promises my understanding has halted on the following question that i do not find thiscussed all i find are specific thiscussions of the promise constructor and the promise then function but not a thiscussion that compares their design patterns1 the promise constructorfrom the ecmascript 6 documentation we have this use of the promise constructor with my comment addednew promisefunctionresolve reject call this stage 1function object with two arguments resolve and reject the first argument fulfills the promise the second argument rejects it we can call these functions once our operation is completed2 the then functionmoving on to the then function that can be called on a promise object which returns a new promise object we have the following function signature as described by the documentation with my comments addedpthenonfulfilled onrejectedchainingbecause the then method returns a promise you can easily chain then callsvar p2 new promisefunctionresolve reject resolve1 stage 1 againp2thenfunctionvalue consolelogvalue 1 return value 1 call this stage 2thenfunctionvalue consolelogvalue 2my questionfrom the above code snippet it seems clear to me that the value passed to the resolve function in stage 1 is passed on to the next stage the first then function there is no return value at stage 1 however it is the return value at stage 2 that is passed on to the next stage after that the second then functionis this lack of correspondence between the design pattern for the creation of a promise and the use of the then function on an existing promise which also returns a promise just a historical fluke one requires calling a callback but returns nothing and the other returns a value but does not call a callbackor am i missing an underlying reason why the promise constructor utilizes a different design pattern than the then functionthanks,['javascript'] +940926,installing pygobject via pip in virtualenv i am actually upgrading an old django app from python27 to python34 while installing pygobject via pip i got this errorcollecting pygobject using cached pygobject2283tarbz2 complete output from command python setuppy egg info traceback most recent call last file string line 20 in module file tmppipbuild9dp0wn96pygobjectsetuppy line 272 raise systemexit error nothing to do gio could not be found and is essential syntaxerror invalid syntax command python setuppy egg info failed with error code 1 in tmppipbuild9dp0wn96pygobjecti am trying to install it in a virtualenv systemwide installation does not work either i am working on arch linux with python34i have installed the arch package named pygobjectdevel 31621 but i still cannot import gobject python modulewhat is this damned missing gioany help is welcomedthanx in advance,['python'] +940970,symfony dependencyinjection how to represent closure in yaml service definitions i have a service which requires a closure when trying to setup it using calls in symfony di yaml fileilluminatequeuequeuemanager arguments app app calls addconnector illuminatequeueconnectornullconnector i am wondering if i can enclose a service into a closure as the library code would not let me insert anything elsepublic function addconnectordriver closure resolver thisconnectorsdriver resolveris there a way i can create closure or an anonymous function in symfony di container yaml definition file i guess it could be done with some compiler pass but i wonder whether there possibly is an existing solution to this problem,['php'] +940982,sailsjs node server reqsession is always empty using passportlocal strategy have ember app running on httplocalhost4200sails app is running on httplocalhost1337i have a policy set on a presignup survey so on the sails side inapicontrollersprocesurveycontrollerjs i have thismoduleexports process survey functionreq res ifreqbody reqbody null resstatus400 return ressenderr something bad happened var params reqbody reqsessionuser ifparamsp 1 1 paramsp 2 1 paramsp 3 0 paramsp 4 bad param reqsessionuserqualifies true resstatus200 return ressendmessage user qualifies status good else reqsessionuserqualifies false resstatus200 return ressendmessage user fails to qualify status bad i then have this policy in apipoliciesqualifiesjsmoduleexports functionreq res next ifreqsessionuserqualifies return next else resstatus400 return ressendstatus 400 message user does not qualify which i apply to my apiusercontrollerjsonly thing is that whenever i post from ember to my usercontrollercreate method i get an error from that policy saying cannot read property qualifies of undefinedand if i sailslogverbosereqsession it is always empty at this point no matter what i doi have enabled cors on my server and my configcorsjs has these options moduleexportscors allroutes true origin httplocalhost4200 credentials true methods get post put delete options head headers xrequestedwith xhttpmethodoverride contenttype acceptin my ember adapter i have this export default dsrestadapterextend host httplocalhost1337 ajax functionurl method hash hashcrossdomain true hashxhrfields withcredentials true return this superurl method hash clearly i am missing something important but i just do not know what and i have run out of ideas for google queries why is my reqsession always emptyedit these were asked for in commentscontents of confighttpjsmoduleexportshttp middleware passportinit requirepassportinitialize passportsession requirepassportsession order startrequesttimer cookieparser session passportinit passportsession myrequestlogger bodyparser handlebodyparsererror compress methodoverride poweredby custom router w favicon 404 500 and configsessionjsmoduleexportssession secret a cookie maxage 48 60 60 10,['javascript'] +940986,xcode 7 error trying to integrate parse using cocoapods swift i am using xcode 7 beta and i have been trying to integrate parse ios sdk using cocoapodsi already created the bridgingheaderh i alreade imported parse import parseparseh i already called parse in my appdelegateswiftthe error happends when i try to use any classobject related to parse actually i am just calling parse with parsesetapplicationidparseapiappid clientkey parseapiclientkeyi am getting the following errorundefined symbols for architecture x86 64 objc class parse referenced from type metadata accessor for objectivecparse in appdelegateold symbols not found for architecture x86 64clang error linker command failed with exit code 1 use v to see invocationi have cleaned the project many times even a complete clean build,['ios'] +941224,fetching array data of php in angular js and not able to update data in php i am new to angular js and i want to update the data of registration form in which i am not able to update data and also how to print array values of php in script file of angular jsplease look forward above the code and give required solutionsfetchdataphpphp include oncedbphp ifisset getaction if getactionadd data add data else if getactionget data get data else if getactiondelete data delete data else if getactionedit data edit data else if getactionupdate data update data insert data function add data data json decodefile get contentsphpinput print rdata fname datafname lname datalname gender datagender state datastate queryinsert into registration reg fname reg lname reg gender reg state reg id values fname lname gender state null result mysql queryquery echo query if result arr arraymsg data added successfully error jsn json encodearr print rjsn else arr arraymsg error error in inserting records jsn json encodearr print rjsn view data function get data querymysql queryselect from registration data array whilerowmysql fetch arrayquery data array userid rowreg id fname rowreg fname lname rowreg lname gender rowreg gender state rowreg state print rrow print rjson encodedata return json encodedata delete data function delete data data json decodefile get contentsphpinput index datauserid print rdata del mysql querydelete from registration where reg id index ifdel return true return false edit data function edit data data json decodefile get contentsphpinput index datauserid qry mysql queryselect from registration where reg id index data array whilerowmysql fetch arrayqry dataarray userid rowreg id fname rowreg fname lname rowreg lname gender rowreg gender state rowreg state print rjson encodedata return json encodedata update data function update data datajson decodefile get contentsphpinput index datauserid fname datafname lname datalname gender datagender state datastate querymysql queryupdate registration set reg fnamefnamereg lnamelname reg gendergenderreg statestate where reg idindex if query arr arraymsg product updated successfully error jsn json encodearr print rjsn else arr arraymsg error error in updating record jsn json encodearr print rjsn controllerjsvar regform angularmoduleregformregformcontrollerformcontrollerfunctionscopehttp scopesubmittrue scoperesettrue scopestates id1namegujarat id2nameharyana id3namemp scopeget data function httpgetfetchdataphpactionget datasuccessfunctiondata scopefields data return scope scopesave function httppostfetchdataphpactionadd data userid scopeuserid fname scopefname lname scopelname gender scopegender state scopeselectedstate successfunction data status headers config alertjsonstringifydata consolelogdata added successfully scopeget data alertdata added successfully scopedelete id functionindex httppostfetchdataphpactiondelete data userid index successfunction data status headers config scopeget data edit data scopeedit id functionindex scopeupdatetrue scopecanceltrue scopesubmitfalse scoperesetfalse httppostfetchdataphpactionedit data userid index successfunction data status headers config alertdata0userid alertjsonstringifydata scopeuserid data0userid scopefname data0fname scopelname data0lname scopegender data0gender scopeselectedstate parseintdata0state errorfunctiondata status headers config scopeupdate function httppostdbphpactionupdate data userid scopeuserid fname scopefname lname scopelname gender scopegender state scopeselectedstate successfunction data status headers config alertjsonstringifydata scopeget data return scope errorfunctiondata status headers config formhtmlhtml ngappregform head titleregistration formtitle script srcangularminjsscript script srccontrollerjs var regform angularmoduleregform regformcontrollerformcontrollerfunctionscope scopestates id1namegujarat id2nameharyana id3namemp scopeformfields scopesave functionform scopeformfieldspushfname scopefnamelname scopelnamegender scopegender statescopestate script head body ngcontrollerformcontroller form nameuserform table tr td firstname td td input typehidden ngmodeluserid nameuserid input ngmodelfname typetext required ngminlength4 span ngshowuserformfnameerrorrequired this is a required field span td tr tr td lastname td td input ngmodellname typetext td tr tr td gender td td input typeradio ngmodelgender valuemale idmale checkedcheckedmale input typeradio ngmodelgender valuefemale idfemalefemale td tr tr td state td td select idstateform ngmodelselectedstate ngoptionsstateid as statename for state in states option value make selection option select td tr tr td input namecheck idcheck typecheckbox ngmodelaccept required accept td tr tr td button ngshowsubmit ngclicksavesavebutton button ngshowupdate ngclickupdateupdatebutton td td button ngshowreset ngclickreset typeresetresetbutton button ngshowcancel ngclickclearcancelbutton td tr table br br table border1 thead thuseridth thfirstnameth thlastnameth thgenderth thstateth thactionth thead tbody nginitget data tr ngrepeatfield in fields tdfielduserid td tdfieldfname uppercasetd tdfieldlnametd tdfieldgendertd tdfieldstatetd tda idedit href ngclickedit idfielduseridedita nbspa iddelete href ngclickdelete idfielduserid ngconfirmare you suredeleteatd tr tbody table form bodyhtml,['php'] +941250,c property value does not get modified within javascript jquery i initialize a property within the controllers constructorpublic bookcontroller sessionprovidersessionloadsceanrio falsei have an action method which reset the property again on a button click eventpublic actionresult loadscenarioint bookid sessionprovidersessionloadsceanrio true remaining code return jsonscenarioid jsonrequestbehaviorallowgetfollowing javascript code is in my view which is called when the button is clickedvar bookhandler btnloadscenclickfunction e ajax url urlactionloadscenario book datatype json type post data bookid bookhandlergetbookid success function response var scenarioid response var isloadscenario portalpresentationwebplanningmvcapp startsessionprovidersessionloadsceanrio otherproperties windowopenurlactionindex bookscenario new loadscenario loadscenarioreplace loadscenario isloadscenario tabid error function my problem is when i click the button value of property changes in the controller but it does not change in my javascript codeplease see the screen capture of the developer tooldoes anyone has a clue on this,"['javascript', 'c#', 'jquery']" +941263,apn fails with authentication failed because the remote party has closed the transport stream i am trying to send apn from c using sslstreamauthenticateasclient method by passing server ip sslprotocolstls and x509certificate2collection but i am getting an error messageauthentication failed because remote party has closed the transport streami have tried every solution thiscussed here but nothing works please help below is the code x509certificate2collection certs new x509certificate2collectionx509certificate2 xcert new x509certificate2xcertimportdcertifyp12 password x509keystorageflagsuserkeysetcertsaddxcert apple development server addrestring apshostif xcerttostringcontainsproductionkeyfriendname apshost gatewaypushapplecomelse apshost gatewaysandboxpushapplecom create a tcp socket connection to the apple server on port 2195tcpclient tcpclient new tcpclienttcpclientconnectapshost 2195 create a new ssl stream over the connectionsslstream new sslstreamtcpclientgetstream authenticate using the apple certservicepointmanagersecurityprotocol securityprotocoltypetlslstreamauthenticateasclientapshost certs systemsecurityauthenticationsslprotocolstls falsereturn true,['.net'] +941483,how to specify large integer literals in a readable way i want to specify a sequence of large integers with many zeros likea 1e13 1e14 1e19 my intuition is to use scientific notation but in python it is a float instead of integer is there a easy way in python to write these integer literals without writing all the zeros because making sure the number of zeros correct is a nightmarei believe i can cast the floats back to integer using int but just wonder if there is a better way,['python'] +941587,how to cancel ongoing http request in swift my code does get request like thisthispatch asyncthispatch get global queuethispatch queue priority default 0 void in let task nsurlsessionsharedsessiondatataskwithrequestrequest data response error in if error nil printlnerror error return if let httpresponse response as nshttpurlresponse if httpresponsestatuscode 200 successfully got response var err nserror if let json nsjsonserializationjsonobjectwithdatadata options nil error err as string anyobject success decoding json else failed stop activity indicator thispatch asyncthispatch get main queue void in selfactivityindicatorstopanimating taskresume if viewwillthisappear gets called before the request finishes i want to stop the requestright now it seems like the view does not thisappear before the request finishes is there a way to cancel the ongoing getpost request,['ios'] +941637,jquery draggable containment array values for scaled container if anyone could help me figure out how to make the draggable elements contained in a div that changes scale based on window size i would really appreciate any guidanceif i doelementdraggable cursor move containment containerwhat will happen is it gives me the containment for the regular size of the container so if i have a transform scale15 there will be space in the container that the draggable element can not goi have also tried containment parent but that gets very glitchyediti have found out how to get the top and left containment but i cannot figure out how to get the right and bottomvar containmentarea containercontainment containmentareaoffsetleft containmentareaoffsettop i have tried width and height from containmentarea0getboundingclientrect but that does not seem to be the right move eitherhere is a jsfiddle of some example code,"['javascript', 'jquery']" +941739,laravel 51 class html does not exist i am upgrading from 42 directly to 51 and run into problems with the html and form classesi followed the upgrade notes and didadd laravelcollectivehtml 50 to composerjsoncomposer updateadd collectivehtmlhtmlserviceproviderclass to providers in aphpadd form collectivehtmlformfacadeclass html collectivehtmlhtmlfacadeclass to aliases in aphpbut my views do not work i get either class html does not exist when using htmlrouter or get class html does not exist when using link to routei also tried illuminatehtml instead of laravelcollective i did a composer dumpautoloadthe complete errorserrorexception in containerphp line 736 class html does not exist view cdevwadminresourcesviewsclubsindexbladephpreflectionexception in containerphp line 736 class html does not existwhat am i missing,"['php', 'html']" +941867,how to send request to url that is set to loginadmin in google app engine in my appyaml a url is defined to be url api script mainapp login admin secure alwaysi tried to the following code to talk to the apiimport requestsdef main r requestsget data auth password print rstatus code rtextif name main mainbut authentication has failed and judging from the output i am redirect to a login pagehow can i use python to authenticate and access the url,['python'] +941938,position 0 is not getting selected in spinner in android i have created a spinner that has three itemsdailyweeklymonthlyi did the following in my java filenavspinner new arraylistspinnernavitem navspinneraddnew spinnernavitemgetresourcesgetstringrstringdailyview navspinneraddnew spinnernavitemgetresourcesgetstringrstringweekview navspinneraddnew spinnernavitemgetresourcesgetstringrstringmonthview adapter new titlenavigationadaptergetactivitygetapplicationcontext navspinner mspinner spinner rootviewfindviewbyidridspinner mspinnersetadapteradapter mspinnersetonitemselectedlistenerthisonitemselected method implements adapterviewonitemselectedlistenerpublic void onitemselectedadapterview parentview view v int position long id logeposition position if mnavifirsthit mnavifirsthit false else fragment fragment null switch position case 0 logeweek position break case 1 backspace 1 logeweek position break case 2 backspace 1 logeweek position break default break public void onnothingselectedadapterview parentview adapterpublic class titlenavigationadapter extends baseadapter private textview txttitle private arraylistspinnernavitem spinnernavitem private context context private textview txtheading private sharedpreferences pref public titlenavigationadaptercontext context arraylistspinnernavitem spinnernavitem thisspinnernavitem spinnernavitem thiscontext context override public int getcount return spinnernavitemsize override public object getitemint index return spinnernavitemgetindex override public long getitemidint position return position override public view getviewint position view convertview viewgroup parent if convertview null layoutinflater minflater layoutinflater contextgetsystemserviceactivitylayout inflater service convertview minflaterinflaterlayoutlist item title null txttitle textview convertviewfindviewbyidridtxttitle txttitlesettextspinnernavitemgetpositiongettitle txttitlesettextcolorcontextgetresourcesgetcolorrcolororangetext txttitlesettextsizetypedvaluecomplex unit sp 12 pref contextgetsharedpreferencesmypref contextmode private string text prefgetstringselecteditem contextgetresourcesgetstringrstringtransaction main gridview if textequalsignorecaseconvertviewgetresourcesgetstringrstringtransaction main gridview txttitlesettextconvertviewgetresourcesgetstringrstringtransaction main gridview text else if textequalsignorecaseconvertviewgetresourcesgetstringrstringtransaction main weekview txttitlesettextconvertviewgetresourcesgetstringrstringtransaction main weekly text else if textequalsignorecaseconvertviewgetresourcesgetstringrstringtransaction main monthview txttitlesettextconvertviewgetresourcesgetstringrstringtransaction main monthly text return convertview override public view getdropdownviewint position view convertview viewgroup parent if convertview null layoutinflater minflater layoutinflater contextgetsystemserviceactivitylayout inflater service convertview minflaterinflaterlayoutlist item title null txttitle textview convertviewfindviewbyidridtxttitle txttitlesetpadding20 20 0 20 txtheading textview convertviewfindviewbyidridtxtheading txtheadingsetvisibilityviewgone txttitlesettextspinnernavitemgetpositiongettitle return convertview the above code works fine when i select position 1 or 2 i get the logs properly then from position 1 or 2 if i select position 0 the log is not printed at all position does not get called even just the position log is not getting printedthis is really strange i am not sure why this happening can somebody help me with thisthanks,['android'] +942014,how can i generate an image that will be similar to snapchats snapcode and will be used in the same way i am building an app that uses a qr code to connect users similar to how snapchat allows users to add each other on snapchati was hoping to use a more aesthetically pleasing alternative to the qr code something similar to snapchats snapcode any idea as to how it can be done in an ios application,['ios'] +942049,does c 60s string interpolation rely on reflection short and simple does the new string interpolation in c 60 rely on reflection ie doesstring mystr hi name how are youuse reflection at runtime to find the variable name and its value,['c#'] +942071,memory efficient sort of massive numpy array in python i need to sort a very large genomic dataset using numpy i have an array of 26 billion floats dimensions 868940742 3 which takes up about 20gb of memory on my machine once loaded and just sitting there i have an early 2015 13 macbook pro with 16gb of ram 500gb solid state hd and an 31 ghz intel i7 processor just loading the array overflows to virtual memory but not to the point where my machine suffers or i have to stop everything else i am doingi build this very large array step by step from 22 smaller n 2 subarrays function fun 1 generates 2 new n 1 arrays using each of the 22 subarrays which i call sub arr the first output of fun 1 is generated by interpolating values from sub arr0 on array b arrayx fx and the second output is generated by placing sub arr 0 into bins using array r arrayx binx i call these outputs b arr and rate arr respectively the function returns a 3tuple of n 1 arraysimport numpy as npdef fun 1sub arr interpolate b values and rates based on position in sub arr b nploadbfile r nploadrfile b arr npinterpsub arr0 b0 b1 rate arr npsearchsortedr0 sub arr0 huge efficiency gain over npdigitize return rrate r 1 b arr sub arr1 i call the function 22 times in a forloop and fill a preallocated array of zeros full arr numpyzeros868940742 3 with the valuesfull arr0 full arr1 full arr2 fun 1in terms of saving memory at this step i think this is the best i can do but i am open to suggestions either way i do not run into problems up through this point and it only takes about 2 minuteshere is the sorting routine there are two consecutive sortsfor idx in range2 sort idx numpyargsortfull arridx full arr full arrsort idx additional processing return small 10 3 array of statsnow this sort had been working albeit slowly takes about 10 minutes however i recently started using a larger more fine resolution table of x fx values for the interpolation step above in fun 1 that returns b arr and now the sort really slows down although everything else remains the same interestingly i am not even sorting on the interpolated values at the step where the sort is now lagging here are some snippets of the different interpolation files the smaller one is about 30 smaller in each case and far more uniform in terms of values in the second column the slower one has a higher resolution and many more unique values so the results of interpolation are likely more unique but i am not sure if this should have any kind of effect bigger slower file17399307 99417493652 98817570460 98217575180 97617577127 9717578255 96417580576 95817583028 95217583699 94617584172 94smaller more uniform regular file1 24 1001 24 2001 24 3001 24 4001 24 5001 246001 247001 24i am not sure what could be causing this issue and i would be interested in any suggestions or just general input about sorting in this type of memory limiting case,['python'] +942137,explain behaviors in mapping auto incremented composite id sequence with hibernate i have a tablecreate table someentity id int11 not null auto increment subid int11 not null default 0 primary key idsubidi have a entity class with an auto increment field in iti want to read auto increment id assigned to it when it gets persisted annotations on getter are as below private long id private int subid id generatedvalue how do i correct this to have multiple rows with same id and different subid columnname id public long getid return id id columnname subid public int getsubid return subid i want to have entities as id 1 subid 0 id 1 subid 1id 1 subid 2id 2 subid 0subid is default 0 in database and i am incrementing it programmatically on updates to that row i tried the solution as in this so post jpa returning an auto generated id after persist transactional override public void daosaveentitysomeentity entity entitymanagerpersistentity now outside this transaction i am trying to get the auto increment id assigned override public long servicesaveentitysomeentity entity daodaosaveentityentity return entitygetid i am calling this from a web service post producesmediatypeapplication json consumesmediatypeapplication json public response createentitysomeentity entity the update method is as below transactional public void updatereportjobsomeentity someentity query query entitymanagercreatequeryupdate someentity set statenewstate where id id querysetparameternewstatepassive querysetparameterid id queryexecuteupdate double rand mathrandom int i int rand 300 try threadsleepi only to simulate concurrency issues catch interruptedexception e eprintstacktrace listinteger reslist entitymanagercreatequeryselect maxsubid from someentity where id id setparameterid jobidgetresultlist increment old subid by 1 int subid reslistget0 someentitysetsubidsubid 1 someentitysetstateactive entitymanagermergesomeentity entitymanagerpersistsomeentity i send and concurrent updates from and threads for entity with id 1 and few other properties as belowsomeenity entity new someentity entitysetid1 long num threadcurrentthreadgetid entitysetfieldonefieldone num entitysetfieldtwo i entitysetfieldthree j i jcase 1 with with id on id and id annotation on subid and entitymanagerpersist in updatewhen i ran with 300 threads some failed with connection exception too many connections the databse state is id 1 subid 0 id 1 subid 1 id 1 subid 2 id 1 subid 150the subid is always incremental the race condition is only that which one will be active is undefined because of race conditioncase 2 with with id on id and id annotation on subid and entitymanagermerge in updateid 1 subid 0 id 1 subid 0 id 2 subid 0 id 151 subid 0 perhaps just a coincidence that one more thread than case 1 was successful case 3 with generatedvalue and id on id and no id annotation on subid and entitymanagerpersist in update exception detached entity passed to persist case 3 with generatedvalue and id on id and no id annotation on subid and entitymanagermerge in update if update is run sequentially the database state is id 1 subid 0after next update id 1 subid 1after each update same row is updated leading to only one row at a timeid 1 subid 2case 4 same as case 3 with concurrent updates if run concurrentlywith 300 threads i get the below exception orghibernatehibernateexception more than one row with the given identifier was found 1database state is id 1 subid 2 only one thread would have been successful but because of race condition updated subid from 0 to 2 case 5 with generatedvalue and id on id and id annotation on subidcreate also fails with subid orghibernatepropertyaccessexception illegalargumentexception occurred while calling setter of someentityidplease explain the causesfrom the javadoc of methods i know thatpersist make an instance managed and persistent merge merge the state of the given entity into the current persistence contextmy question is more towards how hibernate manages the annotationswhy is there be a detached entity exception in case 3 when the session is not closed yetwhy is there a illegalargumentexception in case 5 i am using hibernate 36 mysql 5 and spring 4also please suggest a way achieve such incremental id and subidusing custom selectgenerator with a demo implementation or any other way without doing a column concat,"['java', 'mysql']" +942234,jasmine how to spyon instance methods i have a functionvar data var myfunc function datastuff new classnamedoadobdoci would like to test that doa dob and doc were all calledi tried spying on the instance methods like thisbeforeeachfunction spyonclassname doaitshould call doa function myfunc expectclassnamedoatohavebeencalledbut that just gives me a doa method does not exist errorany ideas,['javascript'] +942242,cakephp 3 routing with language parameter i am trying to convert cakephp 2x to 3x i was using routerconnect rules but i try to convert them to scope versionregarding to myold routing rule in configroutesphp i added this routerdefaultrouteclassroute routerscope function routes routesconnectlanguagecontrolleraction language ardeenfr routesconnectlanguagecontroller action index language ardeenfr routesconnectlanguage controller mydefault action index language ardeenfr routesredirectgohere controller mycontroller action myaction persist arrayusername routesconnect controller mydefault action index routesfallbacksinflectedroutebut this fails in examplecomenworks i get this error error workscontroller could not be found because my controller file is workscontrollerphpdoes controller name part hanged to sentence casein cakephp 3 also examplecomfoobar gives this error error barcontroller could not be found but foo is controller and bar is actionhow can i fix this routing problem editchanging routedefaultrouteclassroute to routedefaultrouteclassinflectedroute solved problem 1 but problem 2 exists,['php'] +942310,android selectableitembackground no glow effect on long press i am trying to use the recyclerview in an android appi imported the recyclerview sample project into android studio and it works finei want to make the items in the recycler view to react visually when the user long presses them in order to do that i set the background of the view to selectableitembackground i made these modificationsinside text row itemxml i added this line on the framelayout tagandroidbackgroundandroidattrselectableitembackgroundinside customadapterjava i added a long click listener on the framelayoutvsetonlongclicklistenernew viewonlongclicklistener override public boolean onlongclickview view logdtag element getposition long clicked return true if i run the modified sample on a lollipop emulator i get the nice ripple effect when i long press the items in the recycler viewbut if i run the app on a kitkat emulator i do not get the glow effect that comes with kitkat the item in the list gets darker when i longpress it and the long click listener does run but i expected the color to glow as the long press was happeninghere is a gif of what i am seingwhy does selectableitembackground not run the glow effect on kitkat how can i get it to work on both kitkat and lollipop,['android'] +942348,jointjs add custom ports with path class for custom elements what i am trying to do is make a element with custom class for ports and path so that i can add an element with custom path and my own markup for portsthis way when i create an element i will pass dynamic path for its shape just like elements of path class behave and as i have also extended from portsmodelinterface i will also have my own markup for portsthis whole effort is to make svg scalable for zomming previously i was using html custom element with my custom ports which was working fine but html of custom elements was not scaling on zoomingvar graph new jointdiavar paper new jointdiapaper el paper width 800 height 600 gridsize 1 model graph snaplinks true embeddingmode truejointshapescustom1 jointshapescustom1element jointshapesbasicgenericextend extend jointshapesbasicportsmodelinterface markup g classrotatableg clascalablerect class myrectgg classinportsg classoutportsg portmarkup g classport id circle classportbodyg defaults jointutildeepsupplement type htmlelement size width 200 height 110 inports outports attrs magnet true rect stroke none fillopacity 0 width 300 height 210 circle r 6 circle radius magnet true left0 stroke gray inports circle fill gray magnet passive type input y 0 outports circle fill gray type output jointshapesbasicgenericprototypedefaults getportattrs function portname index total selector type var attrs var portclass port index var portselector selector portclass var portcircleselector portselector circle attrsportcircleselector port id portname uniqueidtype type type attrsportselector ref rect refx index 1 055 total if selector outports attrsportselectorrefdy 15 return attrs jointshapescustom1atomic jointshapescustom1elementextend markup g classrotatableg clascalablepathgtextg defaults jointutildeepsupplement type basicpath size width 60 height 60 attrs path fill f stroke black text fontsize 14 text textanchor middle refx 5 refdy 20 ref path yalignment middle fill black fontfamily arial helvetica sansserif jointshapesbasicgenericprototypedefaultsvar a2 new jointshapescustom1atomic position x 50 y 260 size width 100 height 100 attrs path d m 30 0 l 60 30 30 60 0 30 z text text diamond refy 5 basicpath text is originally positioned under the element inports in outports outgraphaddcellsa2the element is added in graph but some how the ports do not show upi do not have proper concept of adding classes so please any help will be greatly appreciated thanksfiddle example,['javascript'] +942500,can i change a thistribution parameters there is uniform int thistribution in random when i creating that i define an intervalcan i change this interval after the creationfor example stduniform int thistribution thistr0 10 can i change an interval here,['c++'] +942511,apple music genre selection screen does anybody have an idea how the genre selection bubbles in apple music were made the movement seems to be done with uikit dynamics i definitely see collision behaviors but cannot seem to reproduce the fluidity of the drag movement and the gravity towards the center of the view i tried using uipushbehavior and uisnapbehavior but no luck,['ios'] +942680,how to commit code to svn from xcode 64 can anyone please tell me if any possibility to commit every update to svn from xcode 64 or mac os x 1010 via terminal codes or if any reference links for configuration of xcode64 project with svncurrently i am using this to commit or check out from svn but is i am facing bit complicated to get update via svn co path username name from svn if anyone are using svn with graphical user interfaceplease tell me the procedure or if any reference links,['ios'] +942684,c11 unordered set with stdowner lesslike hashing i am using external networking library which returns some magic structures representing opened sockets and the docs say that when inserting them into stl containers they should be compared using stdowner lestdmapmagicstructure stdshared ptrclient stdowner lessmagicstructure socketshowever i would like to use unordered map instead how can i do it stdowner less is a comparator and it is useless for a hash map digging in the source code magicstructure appears to be a typedef for stdshared ptr,['c++'] +942762,return custom 404 error when resource not found in django rest framework i am learning django rest framework and also new to django i want to return a custom 404 error in json when a client will access a resource which was not foundmy urlspy looks liks thisurlpatterns urlrmailer viewsmaileras view namesendemailtoadminin which i have only one resource which can be accessed through uri httplocalhost80mailernow when a client access any other uri like httplocalhost80 api should return a 404not found error like this status code 404 error the resource was not foundplease suggest some answer with proper code snippets if suitable,['python'] +942890,how to change bootstrap datepicker month view to thisplay quarters i have an application where i have to submit monthly reports and quarterly reports i am using the bootstrapdatepicker for the monthly report and i want to keep the same standarts in my application therefore it would be great if i avoid using a select box to thisplay quartersthis is what bootstrap offers when you are in month view mode and this is what i want to dowhen it is selected all 3 months of the quarter will be selected i checked the bootstrapdatepickerjs file and i only saw the table generation code which wasdpglobaltemplate div classdatepicker div classdatepickerdays table class tablecondensed dpglobalheadtemplate tbodytbody dpglobalfoottemplate table div div classdatepickermonths table classtablecondensed dpglobalheadtemplate dpglobalconttemplate dpglobalfoottemplate table div div classdatepickeryears table classtablecondensed dpglobalheadtemplate dpglobalconttemplate dpglobalfoottemplate table div divand in the dpglobal variable were the templatesheadtemplate thead tr th classprev171th th colspan5 classdatepickerswitchth th classnext187th tr thead conttemplate tbodytrtd colspan9tdtrtbody foottemplate tfoot tr th colspan7 classtodayth tr tr th colspan7 classclearth tr tfootall the help is appreciated,['javascript'] +942891,ios 9 attempt to delete and reload the same index path this is an errorcoredata error serious application error an exception was caught from the delegate of nsfetchedresultscontroller during a call to controllerdidchangecontent attempt to delete and reload the same index path length 2 path 0 0 with userinfo nullthis is my typical nsfetchedresultscontrollerdelegatefunc controllerwillchangecontentcontroller nsfetchedresultscontroller tableviewbeginupdatesfunc controllercontroller nsfetchedresultscontroller didchangesection sectioninfo nsfetchedresultssectioninfo atindex sectionindex int forchangetype type nsfetchedresultschangetype let indexset nsindexsetindex sectionindex switch type case insert tableviewinsertsectionsindexset withrowanimation fade case delete tableviewdeletesectionsindexset withrowanimation fade case update fallthrough case move tableviewreloadsectionsindexset withrowanimation fade func controllercontroller nsfetchedresultscontroller didchangeobject anobject nsmanagedobject atindexpath indexpath nsindexpath forchangetype type nsfetchedresultschangetype newindexpath nsindexpath switch type case insert if let newindexpath newindexpath tableviewinsertrowsatindexpathsnewindexpath withrowanimation fade case delete if let indexpath indexpath tableviewdeleterowsatindexpathsindexpath withrowanimation fade case update if let indexpath indexpath tableviewreloadrowsatindexpathsindexpath withrowanimation none case move if let indexpath indexpath if let newindexpath newindexpath tableviewdeleterowsatindexpathsindexpath withrowanimation fade tableviewinsertrowsatindexpathsnewindexpath withrowanimation fade func controllerdidchangecontentcontroller nsfetchedresultscontroller tableviewendupdatesin viewdidloadprivate func setuponcefetchedresultscontroller if fetchedresultscontroller nil let context nsmanagedobjectcontextmr defaultcontext let fetchreguest nsfetchrequestentityname dborder let datedescriptor nssortdescriptorkey date ascending false fetchreguestpredicate nspredicateformat useridentifier dbappsettingscurrentuseridentifier fetchreguestsortdescriptors datedescriptor fetchreguestfetchlimit 10 fetchedresultscontroller nsfetchedresultscontrollerfetchrequest fetchreguest managedobjectcontext context sectionnamekeypath identifier cachename nil fetchedresultscontrollerdelegate self try fetchedresultscontrollerperformfetch,['ios'] +942950,trying to print top view of a tree using two if statements problem statementyou are given a pointer to the root of a binary tree print the top view of the binary tree you only have to complete the function my code void top viewnode root node r root ifrleftnull top viewrleft systemoutprintrdata ifrrightnull systemoutprintrdata top viewrright the two if statements are executed every time the function is called but i need only one of them to execute i tried switch but its giving constant expression error i have already found a different solution for this problem so i only want to know if we can make only one if execute at a time ie is there a way to fix my code without changing the approach problem link,['java'] +942971,android viewpager not calling ondetachondestroyondestroyview for when being replaced in a container i have a framelayout container in which i use the replace method to put a fragment when an item is selected from the navigation drawergetsupportfragmentmanagerbegintransactionreplaceridcontainer fragment fragmentgetfragmenttagcommiti have a fragment which has a viewpager within it i have 3 fragments which are thisplayed in a tab layout with the viewpager when i select another item from the navigation drawer the fragment with the viewpager is replaced but the fragments within are not detached the system calls only the fragment with the viewpager ondetachondestroy etc methods but not the methods of the fragments it containsi am using fragmentpageradapter and i tried with the fragmentstatepager adapter nothing changes i am using the default setoffscreenpagelimit1how can i get my viewpager fragments methods ondetachondestroy calledthanks,['android'] +943027,is it possible to do a simple image view parallax with coordinator layout without the collpsing toolbar layout hello lets say i have a layout which contains the following scrollview androidididscroll androidlayout belowidtoolbar androidlayout widthmatch parent androidlayout heightmatch parent androidlayout aboveidbutton relativelayout androidlayout widthmatch parent androidlayout heightmatch parent imageview androidididimage androidlayout widthmatch parent androidlayout height240dp androidscaletypecentercrop androidsrcdrawableandroid view androidididanchor androidlayout widthmatch parent androidlayout height240dp textview androidididbody androidlayout belowidanchor androidlayout widthmatch parent androidlayout heightwrap content androidbackgroundandroidcolorwhite androidtextcolorandroidcolorblack androidpaddingbottomdimenactivity vertical margin androidpaddingleftdimenactivity horizontal margin androidpaddingrightdimenactivity horizontal margin androidpaddingtopdimenactivity vertical margin androidtextstringsample relativelayout scrollviewis it possible to use coordinator layout to make the image view move with half the speed of the scroll view as it scrolls up or down,['android'] +943036,better understand sqlalchemys yield per problems to cite sqlalchemy documentationthe queryyield per method is not compatible with most eager loading schemes including subqueryload and joinedload with collectionswarninguse this method with caution if the same instance is present in more than one batch of rows enduser changes to attributes will be overwrittenin particular itas usually impossible to use this setting with eagerly loaded collections ie any lazyajoineda or asubquerya since those collections will be cleared for a new load when encountered in a subsequent result batch in the case of asubquerya loading the full result for all rows is fetched which generally defeats the purpose of yield peralso note that while yield per will set the stream results execution option to true currently this is only understood by psycopg2 dialect which will stream results using server side cursors instead of prebuffer all rows for this query other dbapis prebuffer all rows before making them available the memory use of raw database rows is much less than that of an ormmapped object but should still be taken into consideration when benchmarkingi really have a problem understanding how yield per works and what exactly is the problem on using this method also what is the right way to workaround these problems and keep using this function for iterating over a huge amount of rowsi am interested in all constructive information you have but here are some hint questionshow can there be multiple instances of the same row only through relationships if two rows of the iterating table have an fk to the same row in another table is there a problem if you do not know that it happens or you only read attributes on the relationshipslazyajoineda or asubquerya are not possible but why exactly both of them are simply parts of your query on which you call yield perif they are cleared in a subsequent result batch then simply load it again so where is the problem or is the only problem that you loose the changes of youre relationships if have made changesin the case of a asubquerya loading why all rows are fetched the sql server may have to save a big table but then why not simply return the result in batches one after the other for the entire queryin an example in the yield per doc q sessqueryobjectyield per100optionslazyload joinedloadobjectsome related they deactivate eagerload with lazyload but keep a single joined load is there a way to still use yield per with eagerload what are the conditionsthey say psycopg2 is the only dbapi which support stream results so is that the only dbapi which you can use with yield per as far as i understand yield per uses the cursorfetchmany example function of dbapi which support many of them and as far as i understand cursorfetchmany supports fetching only parts of the result and does not fetch everything if it would fetch everything why the function existsi have the feeling that yield per is entirely safe even with eagerload if you only do read access for example for statistics is that correct,"['python', 'mysql']" +943084,g compilation error is protected from within this context while there is no error with clang i have the following codeinclude iostreamclass baseclass protected static int xint baseclassxclass deriveda public baseclass public deriveda x 3 class derivedb public baseclass public derivedb stdcout derivedax int mainint argc char argv derivedb bcompiling with g g classtestcpp i receive the following errorclasstestcpp in constructor aderivedbderivedba classtestcpp95 error aint baseclassxa is protected int baseclassx classtestcpp2532 error within this context stdcout derivedaxwhen i am compiling with clang clang classtestcpp there is no errorwhy is g returning the compilation errori use g version 510 and clang version 361,['c++'] +943120,exc bad access using gmaps sdk 190 xcode 64 runing on 83 device i have 2 projects working with google maps sdk they are currently in the appstorethings to have in mindgmaps sdk version 190 installed via cocoapodsxcode version 64deployment target 71device iphone 4s with 830today i have opened xcode as usual with the first project tried to compile and debug on the iphone and i sometimes get a exc bad access code1 crash on the app and sometime get exc bad access codeexc arm da aling no stack trace in here but always on mainmreturn uiapplicationmainargc argv nil nsstringfromclasstgpappdelegate claseeing the first thread i have thiscovered that this is error is related to google mapstried the followingupdating the pod did not workreplaced my code with the sample code on gmaps sdk page did not worki have read something about auto layout thisabled did not workthe weird part is that i alsotried in an iphone 6 with 84 did worktried in an iphone 6 with 83 did workboth project are in an early beta state so i do not if the are any real user have this problem but i am worried that some users wont be able to use the apps because of thisi could not find too much information over the internet and i do not even know where to look is there any reported known error regarding this anyone else with the same issuehere is the sample code i am usingvoidviewdidload super viewdidload gmscameraposition camera gmscameraposition camerawithlatitude3780948 longitude5965699 zoom2 gmsmapview mapview gmsmapview mapwithframecgrectzero cameracamera selfview mapviewedit 1doing more tests found out that the problem appears only when debugging attaching the debugger when running the app if you run the app from the iphone and after that you attach the debugger to the process everything runs ok i mean if the map tries to render when the debugger is attached then you will get the exc bad access it is a debugger error then i am confusededit 2this in answered in here thanks dave,"['ios', 'objective-c', 'iphone']" +943156,use strict needed in a typescript file i have seen posts regarding where to put the use strict line in a typescript code file my question is why have it at allsince typescript is already a strongly typed language what does use strict add,['javascript'] +943163,taking the address of an overloaded function template is possible sometimes on gcc 490include iostreaminclude mapstruct a typedef int typetemplatetypename t void foot stdcout a stdendl templatetypename t void footypename ttype stdcout b stdendl templatetypename tstruct identity typedef t typetemplatetypename t void bart stdcout a stdendl templatetypename t void bartypename identityttype stdcout b stdendl int main auto f fooa ambiguous fooa0 prints b as the second overload is more specific auto b bara fine bara0 prints b as the second overload is more specific b0 prints b return 0any clue on why the address can be taken in the second case,['c++'] +943213,weird nested class partial specialization results on both gcc and clang while writing a small template metaprogramming library for personal use i came across an interesting problem since i was reusing a few partial specializations for some metafunctions i decided i would put them under a common template class and use tags along with nested partial specialization to provide the differences in behaviour the problem is i am getting nonsensical to me results here is a minimal example that showcases what i am trying to doinclude iostreaminclude cxxabihinclude typeinfotemplate typename tconst char type name return abi cxa demangletypeidtname nullptr nullptr nullptrtemplate typename argsstruct vargs namespace details template typename k struct outer template typename arg struct inner using result arg struct tag namespace details template template typename arg typename args struct outertaginnervargsarg args using result typename outertaginnerargresult template typename tusing test t typename detailsoutertaginnertresultint main using t test tvargschar int stdcout type namet n return 0i am getting vargschar int as output when using the 510 version of gcc and tag when using the 360 version of clang my intention was for the above piece of code to print char so i am pretty baffled by these resultsis the above piece of code legal or does it exhibit undefined behaviorif it is legal what is the expected behavior according to the standard,['c++'] +943240,template partial ordering why does partial deduction succeed here consider the following simple to the extent that template questions ever are exampleinclude iostreamtemplate typename tstruct identitytemplate struct identityint using type inttemplatetypename t void bart t stdcout an templatetypename t void bart typename identityttype stdcout bn int main bar0 0both clang and gcc print a there according to the rules in tempdeductpartial and tempfuncorder to determine partial ordering we need to synthesize some unique types so we have two attempts at deduction parameters arguments a t typename identityttype uniquea uniquea b t t uniqueb typename identityuniquebtype for deduction on b according to richard cordens answer the expression typename identityuniquebtype is treated as a type and is not evaluated that is this will be synthesized as if it were parameters arguments a t typename identityttype uniquea uniquea b t t uniqueb uniqueb 2 it is clear that deduction on b fails those are two different types so you cannot deduce t to both of themhowever it seems to me that the deduction on a should fail for the first argument youd match t uniquea the second argument is a nondeduced context so wouldnt that deduction succeed iff uniquea were convertible to identityuniqueatype the latter is a substitution failure so i do not see how this deduction could succeed either how and why do gcc and clang prefer the a overload in this scenario,['c++'] +943264,module is not available misspelled or forgot to load but i didnt i am fairly new to angular and using it with json api files to test i am trying to use the free github api my names for functions are for a different json api that i will be working with later i just wanted to see if my functions were working with the consolelogs but i receive this error in the consoleuncaught error injectormodulerr failed to instantiate module mesaviewer due toerror injectornomod module mesaviewer is not available you either misspelled the module name or forgot to load it if registering a module ensure that you specify the dependencies as the second argumenti have spelled mesaviewer the exact same in both and dependencies are seen in the second linevar app angularmodulemesaviewervar maincontroller functionscope location http routeparams what did i do wronghere is my plunk,['javascript'] +943278,polymorphic association on uuid and integer fields given tables with integer and uuid primary keys what is the best way to integrate a polymorphic join has many for exampleclass interest activerecordbase id is an integer has many likes as likeableendclass post activerecordbase id is a uuid has many likes as likeableendclass user activerecordbase has many likes has many posts through likes source likeable source type post has many interests through likes source likeable source type interestendclass like activerecordbase likeable id and likeable type are strings belongs to likeable polymorphic true belongs to userendmany queries workinterestlikespostlikesuserlikeshoweveruserinterestsgivespgundefinedfunction error operator does not exist integer character varying line 1 interests inner join likes on interestsid likes hint no operator matches the given name and argument types you might need to add explicit type casts select interests from interests inner join likes on interestsid likeslikeable id where likesuser id 1 and likeslikeable type 2whats the best way to include ensure the proper casting happens,['ruby-on-rails'] +943373,calligraphy library by chrisjenx is not working i did what his documentation has instructed upon setting up the default font override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setupdefaultfont setcontentviewrlayoutactivity main setuptoolbarandnavigationdrawer public void setupdefaultfont calligraphyconfiginitdefaultnew calligraphyconfigbuilder setdefaultfontpathfontsopensansregularttf setfontattridrattrfontpath build i also placed the fonts in assetsfonts but to no availroboto still shows up as default font and not open sans i tried applying it manually one by one to each textview but still it does not workany ideas on why this does not workmore info in case it is usefulmy minisdkversion is 15 and targetsdkversion is 22these are my dependenciesdependencies compile filetreedir libs include jar compile comandroidsupportappcompatv720 compile comandroidsupportdesign20 compile comandroidsupportrecyclerviewv72103 compile comandroidsupportcardviewv72103 compile dehdodenhofcircleimageview121 compile ukcochrisjenxcalligraphy210and this is the custom theme that i am usingresources style namemyiit theme parentthemeappcompat item namecolorprimarydarkcolorprimary darkitem item namecolorprimarycolorprimaryitem item nameandroidtextcolorprimarycolorwhiteitem item nameandroidwindowbackgroundcolortertiary darkitem item nameandroidactivatedbackgroundindicatordrawableselected draweritem item namewindowactionbarfalseitem item namewindownotitletrueitem styleresources,['android'] +943383,codeigniter batch insert into specific columns i have a codeigniter application and a mysql table with the following structuretable shortlisted candidatesid int primary key auto incrementcandidate no int not nullwritten marks intviva marks inti want to do insert batch into this table but data will only be inserted in id and candidate no columns i know codeigniter active records class provides the thisdbinsert batch function for batch insert but it actually inserts data in the entire table whereas i want data to be inserted only into specific columns how can i achieve this in codeigniternote that id is an auto increment primary key columnmy controller codeclass shortlisted candidates extends my controller function construct parent construct thisloaddatabase thisloadmodelshortlisted candidate thisloadhelperurl thisloadhelperhtml thisloadhelperform thisoutputenable profilerfalse function add data array if post datacandidate no thisinputpostcandidate no thisshortlisted candidateadd candidate to shortlistdata thissessionset flashdatamessage data successfully added redirectshortlisted candidatesadd my model codeclass shortlisted candidate extends ci model function construct call the model constructor parent construct function add candidate to shortlistdata following code inserts data in all columns thisdbinsert batchshortlisted candidates data how to write active record batch insert query for inserting data in only id and candidate no column,"['php', 'mysql']" +943456,how to use clang static analyzer in qt creator see this manual using clang static analyzer in qt creator manualcan someone tell me for to set up thisi do not see this tab in analyzer settings in qtcreator and do not see the plugin in the list which can be used for thisupdate sorry i see this is a commercial version only,['c++'] +943591,lifetime of rvalue bound to static const reference consider this stdstring foovoid bar const stdstring r1 foo static const stdstring r2 fooi know that the lifetime of the string resulting from the first call to foo will be extended to the lifetime of r1 what about the temporary bound to r2 though will it live until the end of the scope or will it still be there when bar is reentered note i am not interested whether a particular compiler does so i am interested in the one we use and i can test easily with that i want to know what the standard has to say on this,['c++'] +943637,modal window with angular uirouter directive i have spent some time now looking into a generic way of controlling a modal window with angularjs and none of the proposed options are anywhere near good solutionthe directive solutioni found this demo however the downside of that is you have to manually manage and store the state of the modal and croscope update itscopeparentattrsvisible truealso if you had to add more functionality like actually adding an item with a popup that would involve even more ugly code on the parent page scopethe uirouter solutionthis is the official guide on how to use modals with ui routerthis however is using uibootstrapmodal my question is is there any simple and elegant solution to what is quite frankly a very simple problemsomething like this for examplestatepopup url itemadd views popupview templateurl mypopuphtml controller mypopupcontroller type modal and things like close redirect submit all are handled in the mypopupcontrolleri am not seeking an explanation of why the examples are above are as they are or how i should be using them i am simply looking if anyone has come up with a better solution,['javascript'] +943704,no matching function for call to stdvector push back i have a sample program containing 6 timepoints using high resolution clocknow from standard chrono header i take differences bw each of them resulting in 3 differences and caste them as auto duration1 stdchronoduration caststdchronomicroseconds t2 t1 count to microsecondsi have another variable named durations which is assigned as follows auto durations stdmake tupleduration1duration2duration3 containing previous timepoint differencesi have to push this tuple into an vector so i have introduced stdvectorstdtuplestdchronomicrosecondsstdchronomicrosecondsstdchronomicroseconds list however on using listpush backdurations i get an error as progcpp in function int mainprogcpp3629 error no matching function for call to stdvectorstdtuplestdchronodurationlong long int stdratio1ll 10ll stdchronodurationlong long int stdratio1ll 10ll stdchronodurationlong long int stdratio1ll 10ll push backstdtuplelong long int long long int long long int listpush backdurationsi tried to search about stdchronomicroseconds and other stdchronoduration stuff here but was not successful in rectifying the problemi know this has something to do with my negligence of type system but i am unable to locate that error any help would be appreciated here is ideone linkinclude iostreaminclude chronoinclude vectorinclude tupleusing namespace stdusing namespace stdchronovoid function long long number 0 for long long i 0 i 20 i number 5 int main high resolution clocktime point t1 high resolution clocknow high resolution clocktime point t3 high resolution clocknow high resolution clocktime point t5 high resolution clocknow function high resolution clocktime point t2 high resolution clocknow high resolution clocktime point t4 high resolution clocknow high resolution clocktime point t6 high resolution clocknow auto duration1 stdchronoduration caststdchronomicroseconds t2 t1 count auto duration2 stdchronoduration caststdchronomicroseconds t4 t3 count auto duration3 stdchronoduration caststdchronomicroseconds t6 t5 count auto durations stdmake tupleduration1duration2duration3 stdvectorstdtuplestdchronomicrosecondsstdchronomicrosecondsstdchronomicroseconds list listpush backdurations cout duration1 duration2 duration3 return 0,['c++'] +943737,visual studio android emulator thisplay keyboard how can i thisplay keyboard on vs android emulatorin avd i can setup it from emulator configurator but there is no way in vs,['android'] +943834,using lodash and underscore simulatenously in requirejs environment in a requirejs environment whats the best way to allow some amd modules to use lodash while others simultaneously use underscore,['javascript'] +943872,what is the difference between browserpause and browserenterrepl in protractor there is the browserpause functionbeta unstable pause function for debugging webdriver tests use browserpause in your test to enter the protractor debugger from that point in the control flowelementbyidfooclickbrowserpause execution will stop before the next click actionelementbyidbarclickand also there is a lessknown one browserenterreplbeta unstable enterrepl function for entering the repl loop from any point in the control flow use browserenterrepl in your test does not require changes to the command line no need to add debugelementbyidfooclickbrowserenterrepl execution will stop before the next click actionelementbyidbarclickfrom the provided documentation and examples it is clear that they both are used for debugging the tests but it is not clear what is the difference between the two when should we use pause and when enterrepl,['javascript'] +944006,djangodbutilsprogrammingerror relation app user does not exist during managepy test my setupdjango 183 python 2710 ubuntu 1404djangotwofactorauth120i get the following error when i run python managepy testtraceback most recent call last file srcvenvbindjangoadminpy line 5 in module managementexecute from command line file srcvenvlibpython27sitepackagesdjangocoremanagement init py line 338 in execute from command line utilityexecute file srcvenvlibpython27sitepackagesdjangocoremanagement init py line 330 in execute selffetch commandsubcommandrun from argvselfargv file srcvenvlibpython27sitepackagesdjangocoremanagementcommandstestpy line 30 in run from argv supercommand selfrun from argvargv file srcvenvlibpython27sitepackagesdjangocoremanagementbasepy line 393 in run from argv selfexecuteargs cmd options file srcvenvlibpython27sitepackagesdjangocoremanagementcommandstestpy line 74 in execute supercommand selfexecuteargs options file srcvenvlibpython27sitepackagesdjangocoremanagementbasepy line 4 in execute output selfhandleargs options file srcvenvlibpython27sitepackagesdjangocoremanagementcommandstestpy line 90 in handle failures test runnerrun teststest labels file srcvenvlibpython27sitepackagesdjangotestrunnerpy line 210 in run tests old config selfsetup databases file srcvenvlibpython27sitepackagesdjangotestrunnerpy line 166 in setup databases kwargs file srcvenvlibpython27sitepackagesdjangotestrunnerpy line 370 in setup databases serializeconnectionsettings dictgettest getserialize true file srcvenvlibpython27sitepackagesdjangodbbackendsbasecreationpy line 368 in create test db test flushnot keepdb file srcvenvlibpython27sitepackagesdjangocoremanagement init py line 120 in call command return commandexecuteargs defaults file srcvenvlibpython27sitepackagesdjangocoremanagementbasepy line 4 in execute output selfhandleargs options file srcvenvlibpython27sitepackagesdjangocoremanagementcommandsmigratepy line 179 in handle created models selfsync appsconnection executorloaderunmigrated apps file srcvenvlibpython27sitepackagesdjangocoremanagementcommandsmigratepy line 317 in sync apps cursorexecutestatement file srcvenvlibpython27sitepackagesdjangodbbackendsutilspy line 65 in execute return selfcursorexecutesql params file srcvenvlibpython27sitepackagesdjangodbutilspy line 97 in exit sixreraisedj exc type dj exc value traceback file srcvenvlibpython27sitepackagesdjangodbbackendsutilspy line 63 in execute return selfcursorexecutesqldjangodbutilsprogrammingerror relation app user does not existwhen i drop a printsql statement on line 62 in djangodbbackendsutilspy i get following outputcreate database test dev select crelname crelkind from pg catalogpg class c left join pg catalogpg namespace and on noid crelnamespace where crelkind in r v and nnspname not in pg catalog pg toast and pg catalogpg table is visiblecoidcreate table django migrations id serial not null primary key app varchar255 not null name varchar255 not null applied timestamp with time zone not null select crelname crelkind from pg catalogpg class c left join pg catalogpg namespace and on noid crelnamespace where crelkind in r v and nnspname not in pg catalog pg toast and pg catalogpg table is visiblecoidsavepoint s140275211773760 x1create table thistributedlock lock id serial not null primary key key varchar255 not null value varchar255 not null timestamp timestamp with time zone nullrelease savepoint s140275211773760 x1savepoint s140275211773760 x2create table djkombu queue id serial not null primary key name varchar200 not null uniquerelease savepoint s140275211773760 x2savepoint s140275211773760 x3create table djkombu message id serial not null primary key visible boolean not null sent at timestamp with time zone null payload text not null queue id integer not nullrelease savepoint s140275211773760 x3savepoint s140275211773760 x4create table otp static staticdevice id serial not null primary key user id integer not null name varchar64 not null confirmed boolean not nullrelease savepoint s140275211773760 x4savepoint s140275211773760 x5create table otp static statictoken id serial not null primary key device id integer not null token varchar16 not nullrelease savepoint s140275211773760 x5savepoint s140275211773760 x6create table otp totp totpdevice id serial not null primary key user id integer not null name varchar64 not null confirmed boolean not null key varchar80 not null step smallint not null check step 0 t0 bigint not null digits smallint not null check digits 0 tolerance smallint not null check tolerance 0 drift smallint not null last t bigint not nullrelease savepoint s140275211773760 x6create index djkombu queue name 1c24e49fd475ad53 like on djkombu queue name varchar pattern opsalter table djkombu message add constraint djkombu message queue id 12778caea7843dd fk djkombu queue id foreign key queue id references djkombu queue id deferrable initially deferredcreate index djkombu message 46cf0e59 on djkombu message visiblecreate index djkombu message df2f2974 on djkombu message sent atcreate index djkombu message 75249aa1 on djkombu message queue idalter table otp static staticdevice add constraint otp static staticdevice user id 39a61f1bd3ec970d fk app user id foreign key user id references ff user id deferrable initially deferredso it is clear to me that my tests blow up while the test database is being setup specifically the attempt to create a foreign key constraint between the otp static staticdevice table and my apps app user table failsmy immediate question is why does django create the otp table before my apps table my assumption is that the otp app is listed first in my installed apps but this is not the caseinstalled apps djangocontribauth djangocontribcontenttypes djangocontribsessions djangocontribsites djangocontribmessages djangocontribstaticfiles djangocontribadmin djangocontribhumanize app django otp django otppluginsotp static django otppluginsotp totp two factor next i look at djangocoremanagementcommandsmigratepy trying to find out how django determines its order for migrating appsplopping a pdbset trace statement on line 264 and looking to see what app labels contains i getsetdjangosaml2 django ace recurly staticfiles thistributedlock app overrides messages django otp kombu transport django otp totp compressor otp static humanize ajax select django extensions import export raven compat crispy forms emojithis is as far as i have gotten before i decided to ask for help does anyone know how django might end up not creating all the projects apps in the correct order so that decency conflicts do not occur,['python'] +944058,vimeo iframe stealing mouse wheel event on firefox i made this example here you can test in firefox that scroll event is fired except when over vimeo iframe and i guess any iframe is there any solution to fire event on iframe ps i want to use this in a custom scrollbar,['javascript'] +944087,flexbox force new column i want to achieve this layout below 600pxand this layout above 600pxthe height of the text and image is variable and unknownflexbox works great for the source reordering but i am having trouble forcing the new column to work cross browserusing pagebreakbefore always on the div with the image forces a new column but this technique only works in firefox 39this js fiddle shows an example of what i have so far test in firefox to see working examplehow can i make this layout work in chrome and ie11 using position absolute on the image to move it out the document flow is not an option as i need it to push the content below downwhilst i am using flexbox i would accept any css only method that could achieve the desired layout,"['html', 'css']" +944126,limit 1 is very slow for specific records using different keys i am diagnosing an intermittent slow query and have found a strange behaviour in mysql i cannot explain it is choosing a different nonoptimal key strategy for one specific case only when doing a limit 1table some unreferenced data columns removed for brevitycreate table ch log cl id bigint20 not null auto increment cl unit id int11 not null default 0 cl date datetime not null default 0 0 cl type char1 not null default cl data text not null cl event varchar255 null default null cl timestamp timestamp not null default current timestamp on update current timestamp cl record status char1 not null default a primary key cl id index cl type cl type index cl date cl date index cl event cl event index cl unit id cl unit id index log type unit id cl unit id cl type index unique user cl user number cl unit idengineinnodbauto increment419582094this is the query which only runs slow for one specific cl unit idexplainselect from ch logwhere ch log type i and ch log event g and cl unit id1234order by cl date desc limit 1idselect typetable type possible keys key key lenrefrowsextra1 simple ch logindexcl typecl eventcl unit idlog type unit idcl date8 n 5295using wherefor all other values of cl unit id it uses the log type unit id key which is much fasteridselect typetable typepossible keys key key lenref rowsextra1 simple ch logref ch log typech log eventch log unit idlog type unit idlog type unit id5 constconst3804using where using filesortall queries take about 001 seconds the slow unit query takes 1015 minutesi cannot see anything strange about the data for this unitunit 1234 only has 6 records of type i and event gother units have many moreunit 1234 only has 320 logs in total which is typicalthe data itself is normal no bigger or olderthere are around 30 units in the database which represent devices logging stuff the cl unit id is their unique pk although no constraintgeneral infothere are 30m records in total around 12gbmysql 5169logcentos 64bitthe data is gradually changing 30m 3months of logs but i do not know if this has happened beforethings i have tried and can solve the problem withremoving the limit 1 the query runs in milliseconds and returns the datachanging to limit 2 or other combinations eg 23 runs in millisecondsadding a index hint solves itfrom ch log use index log type unit idbut i do not want to hardcode this into the applicationadding a second order by on the primary key also solves itorder by cl id cl date desc giving explainidselect typetable typepossible keys key key lenref rowsextra1 simple ch logref ch log typech log eventch log unit idlog type unit idlog type unit id5 constconst6870using wherewhich is slightly different to the type hinted one with more records examined 60 but still runs in 10s of millisecondsagain i could do this but i do not like using sideeffects i do not understandso i think my main question are a why does it only happen for limit 1b how can the data itself affect the keystrategy so much and what aspect of the data seeing as the quantity and spread in the indexes seems typical,"['mysql', 'sql']" +944162,plotting 3d graphics in python 3 i want do some 3d plotting to visualize some date i am using matplotlib but the 3d feature of matplotlib is not as powerful as 2d plotting i found mayavi very powerful even matplotlib recommand it in toolkitsmplot3dfaqhtmlhowever most of my previous work are done in python 3 but mayavi do not support python3 yet how could i plot 3d graphics in python 3,['python'] +944397,simulating adts in java an application may operate in two modes real time where it looks at every update to the state of the world or sampled where it only looks at the state of the world every t millisecondsif i were writing haskell or any language with adts i would model this asdata mode realtime sampled intwhich can be used as follows in a typesafe waycase mode of realtime do realtime stuff sampled interval do sample stuff with intervali say that it is typesafe because if you are running in realtime mode you are prevented from trying to access the interval field which is provided at just the time you need it if you are operating in sampled modehow can i model the same thing in java in a typesafe way that is i wantto define a class or enum that thistinguishes between the two modes andto prohibit access to the interval field when in realtime mode andto have all of this checked by the compileris this possible in java if not what is the idiomatic way to achieve this kind of typesafety,['java'] +944623,why are there 2 stack frames for a lambda invocation the following codepublic static void mainstring args collectionssingleton1streamforeachi new exceptionprintstacktraceprintsjavalangexception at printlambdastacktracelambdamain0printlambdastacktracejava6 at printlambdastacktracelambda11831932724acceptunknown source at javautilcollections2tryadvancecollectionsjava4717 at javautilcollections2foreachremainingcollectionsjava4725 at javautilstreamreferencepipelineheadforeachreferencepipelinejava580 at printlambdastacktracemainprintlambdastacktracejava6how is the lambda invocation implemented why are there 2 stack frames,['java'] +944625,intent to open a chat with a specific user on snapchat app i am trying to find if there is any app schemato open the snapchat app via intent with a specific userid that i want to chat withbtw to find the userid,['android'] +944646,what is the correct way to allocate and use an untyped memory block in c the answers i got for this question until now has two exactly the opposite kinds of answers it is safe and it is undefined behaviour i decided to rewrite the question in whole to get some better clarifying answers for me and for anyone who might arrive here via googlealso i removed the c tag and now this question is c specifici am making an 8bytealigned memory heap that will be used in my virtual machine the most obvious approach that i can think of is by allocating an array of stduint64 tstdunique ptrstduint64 t blocknew stduint64 t100let us assume sizeoffloat 4 and sizeofdouble 8 i want to store a float and a double in block and print the valuefloat pf reinterpret castfloatblock0double pd reinterpret castdoubleblock1pf 11pd 22stdcout pf stdendlstdcout pd stdendli would also like to store a cstring saying hellochar pc reinterpret castcharblock2stdstrcpypc hellonstdcout pcnow i want to store hello world which goes over 8 bytes but i still can use 2 consecutive cellschar pc2 reinterpret castcharblock3stdstrcpypc2 hello worldnstdcout pc2for integers i do not need a reinterpret castblock5 1stdcout block5 stdendli am allocating block as an array of stduint64 t for the sole purpose of memory alignment i also do not expect anything larger than 8 bytes by its own to be stored in there the type of the block can be anything if the starting address is guaranteed to be 8bytealignedsome people already answered that what i am doing is totally safe but some others said that i am definitely invoking undefined behaviouram i writing correct code to do what i intend if not what is the appropriate way,['c++'] +944695,how to implement the hashable protocol in swift for an int array a custom string struct i am making a structure that acts like a string except that it only deals with unicode utf32 scalar values thus it is an array of uint32 see this question for more backgroundwhat i want to doi want to be able to use my custom scalarstring struct as a key in a dictionary for examplevar suffixdictionary scalarstring scalarstring unicode key rendered glyph value populate dictionarysuffixdictionarykeyscalarstring valuescalarstring check if dictionary contains unicode scalar string keyif let renderedsuffix suffixdictionaryunicodescalarstring do something with valueproblemin order to do that scalarstring needs to implement the hashable protocol i thought i would be able to do something like thisstruct scalarstring hashable private var scalararray uint32 var hashvalue int get return selfscalararrayhashvalue error func left scalarstring right scalarstring bool return lefthashvalue righthashvaluebut then i thiscovered that swift arrays do not have a hashvalue what i readthe article strategies for implementing the hashable protocol in swift had a lot of great ideas but i did not see any that seemed like they would work well in this case specificallyobject property array is does not have hashvalueid property not sure how this could be implemented wellformula seems like any formula for a string of 32 bit integers would be processor heavy and have lots of integer overflowobjectidentifier i am using a struct not a classinheriting from nsobject i am using a struct not a classhere are some other things i readimplementing swifts hashable protocolswift comparison protocolsperfect hash functionmembership of custom objects in swift arrays and dictionarieshow to implement hashable for your custom classwriting a good hashable implementation in swiftquestionswift strings have a hashvalue property so i know it is possible to dohow would i create a hashvalue for my custom structureupdatesupdate 1 i would like to do something that does not involve converting to string and then using strings hashvalue my whole point for making my own structure was so that i could avoid doing lots of string conversions string gets it is hashvalue from somewhere it seems like i could get it using the same methodupdate 2 i have been looking into the implementation of string hash codes algorithms from other contexts i am having a little difficulty knowing which is best and expressing them in swift thoughjava hashcode algorithmc algorithms hash function for string so question and answers in chashing tutorial virginia tech algorithm visualization research groupgeneral purpose hash function algorithmsupdate 3i would prefer not to import any external frameworks unless that is the recommended way to go for these thingsi submitted a possible solution using the djb hash function,['ios'] +944785,ipad safari improper scrolling in rtl with wide content the condition is as followsusing ipad safaripage is in rtl right to left mode arabic localepage dynamically loads some content which is wider than the screenstrange scrolling behavior occursthe page starts out seemingly scrolled too far to the left see the screenshot so the righthand side what is normally the left in ltr mode is towards the middle and what seems like negative space is thisplayed insteadyou can touchdrag to right to scroll left to see some contents that start offscreen but i can only scroll part way which leaves some content far off to the left that is impossible to get tohere is a screenshot from defect i am working onhere is a simple html that could reproduce the problemdoctype htmlhtml dirrtlheadmeta nameviewport contentminimumscale025 maximumscale40 userscalableyes headbody stylebackgroundcolorgreyscript srcscriptscript settimeoutfunction div stylewidth20pxbackgroundcolorredtestdivappendtobody 10scriptbodyhtmlsteps you can follow to reproduce the problemcopy this html to a local fileopen the document in chrome using f12 you can turn on ipad emulationpress the button to emulate then you will notice that the right edge of the red box is near the middle of the page however that should not be the case that red box should be the only content and nothing is to the right of it so it should aligned with the right edgethis issue also only happens when you dynamically insert the wide content after the page has loaded so if the page starts out with wide content the scroll behavior seems normal hence the settimeout in the codeany adviceworkaround to fix this problemedityou can also directly try this link to reproduce the problem,['html'] +944790,what exactly is an idexpression i am having a problem clearly understanding exactly what an idexpression is i will start off by following what i found in the most recent working draft of the c standard starting off withventuring to the definition of an identifieran identifier is an arbitrarily long sequence of letters and digitsso it seems like any arbitrary long sequence of letters and digits can be an idexpression but waitso the identifier must be declared first in order for it to be an idexpression well lets head over to clause 7continuingcontinuing againwe arrive herei interpret this to mean an idexpression requires an identifier to be declared which requires an idexpression this seems like a circular definition can someone tell me where i went wronganyway my interpretation is that the identifier must be declared first in order for it to be considered an idexpression but is not that really just a name the standard states thatevery name that denotes an entity is introduced by a declarationso why not just call it a nameexpression instead,['c++'] +944856,why is not and independent calculations and times faster on and threads i have an and core processor 4 in my case why is not and totally independent function calls on and threads roughly and times faster of course there is an overhead of creating threads but read further look at the the following codenamespace ch stdchrononamespace mp boostmultiprecisionconstexpr static unsigned long long int num 35 mp factorial uses boostmultiprecisioncpp int so i get legit results chsteady clocktime point s1 chsteady clocknow auto fu1 stdasyncstdlaunchasync mp factorial num auto fu2 stdasyncstdlaunchasync mp factorial num auto fu3 stdasyncstdlaunchasync mp factorial num auto fu4 stdasyncstdlaunchasync mp factorial num fu1get fu2get fu3get fu4get chsteady clocktime point e1 chsteady clocknow chsteady clocktime point s2 chsteady clocknow mp factorialnum mp factorialnum mp factorialnum mp factorialnum chsteady clocktime point e2 chsteady clocknow auto t1 chduration castchmicrosecondse1 s1count auto t2 chduration castchmicrosecondse2 s2count cout t1 t2 endli get results like11756 20317thats roughly 2 times faster i have also tried this with huge numbers like num 35 i got really similar results177462588 346575062why is this the case i am perfectly aware of amdahls law and that a multicored processor is not always number of cores times faster but when i have independent operations i would expect better results at least something near number of coresupdateas you can see all threads are working as expected so this is not the issue,['c++'] +944860,java generics bound mismatch i have a generic class with this definitionpublic class acoproblemsolverc e extends environment a extends antcolonye antc e where antcolony goes this waypublic abstract class antcolonye extends environment a extends ant e and ant goes like thispublic abstract class antc e extends environment i was hoping to extend antcolony in this fashionpublic class flowshopproblemsolver extends acoproblemsolverinteger flowshopenvironment flowshopantcolony but eclipse is showing an error on the flowshopantcolony parameter classbound mismatch the type flowshopantcolony is not a valid substitute for the bounded parameter a extends antcolonyeantce of the type acoproblemsolverceawhich confuses me since flowshopantcolony is defined this waypublic class flowshopantcolony extends antcolonyflowshopenvironment antforflowshop and antforflowshop goes like thispublic class antforflowshop extends antinteger flowshopenvironment why is not flowshopantcolony accepted as a valid parameter,['java'] +944911,is it possible write a gulpfile in es6 question how can i write my gulp file in es6 so i can use import instead of require and use syntax over function i can use iojs or node any versiongulpfilejsimport gulp from node modulesgulpindexjsgulptaskhelloworld consoleloghello worlderrorsimport gulp from node modulesgulpindexjssyntaxerror unexpected reserved wordgulptaskhelloworld syntaxerror unexpected token inside the node modulesgulpbingulpjs i have changed the first line to usrbinenv node harmony as asked in this stack,['javascript'] +944918,why does windowwidth change while the page is loading i noticed that my scripts were setting widths incorrectly so i tried the following snippetvar prevsetintervalfunction ifwindowwidthprev consolelogprevwindowwidth1this printed 2 different values 1464 and 1481 since these are 17px apart i am almost certain this is caused by scrollbars the second value is the correct valuewhy does windowwidth change without resizing the window should not it return the browser windows width which should be constant,"['javascript', 'jquery']" +944973,how to open sub menu after click on menuitem in navigation drawer i implemented a navigation drawer with navigation view and i am adding value in navigation view through a menuxml fileandroidsupportdesignwidgetnavigationviewandroidididnvviewandroidlayout widthwrap contentandroidlayout heightmatch parentandroidlayout gravitystartappitemtextcolorandroidcolorwhiteandroidbackgroundattrcoloraccentappmenumenudrawer viewappheaderlayoutlayoutnav headerandroidsupportdesignwidgetnavigationviewevery thing is working fine but i am facing a problem i want to thisplay submenus after click on menui tried many things likei add submenu in menuxml inside itemsomthing like thismenu xmlnsandroidgroup androidcheckablebehaviorsingleitem androidididnav changeoutlet fragment androidicondrawablehome icon androidtitlestringchangeoutlet androidcheckedtrue menu group item androidtitleoneitem item androidtitletwoitem item androidtitlethreeitem group menuthen it return me output like thisoutput click on this link to see outputnow problem is that in this way i am not able to click on menu only sub menu are clickable herei want here to show sub menu only after click on menu otherwise sub menu does shown to other or say it is in invisible state,['android'] +945044,android how to open last activity when tapping notification i have observed several similar questions but they couldnt help me i need to thisplay last activity when user click notification here is my codenotificationcompatbuilder notificationbuilder new notificationcompatbuilderyourservicethis setcontenttitlegetresourcesgettextrstringapp name setcontenttextgetservicestatedescriptionyourservicethis setsmalliconiconid setwhensystemcurrenttimemillisintent nintent getpreviousintenttaskstackbuilder stackbuilder taskstackbuildercreatethis adds the back stackstackbuilderaddparentstackmainactivity clastackbuilderaddnextintentnintentpendingintent pendingintent stackbuildergetpendingintent0 pendingintentflag update currentnotificationbuildersetcontentintentpendingintentstartforegroundcontextconstantslauncher service note id notificationbuilderbuildprivate intent getpreviousintent intent newintent nullfinal activitymanager activitymanager activitymanager getsystemservicecontextactivity serviceif buildversionsdk int buildversion codeslollipop final listactivitymanagerapptask recenttaskinfos activitymanagergetapptasks if recenttaskinfosisempty for activitymanagerapptask apptasktaskinfo recenttaskinfos if apptasktaskinfogettaskinfobaseintentgetcomponentgetpackagenameequalscontextconstantspackage name newintent apptasktaskinfogettaskinfobaseintent newintentsetflagsintentflag activity new task else final listactivitymanagerrecenttaskinfo recenttaskinfos activitymanagergetrecenttasks1024 0 if recenttaskinfosisempty for activitymanagerrecenttaskinfo recenttaskinfo recenttaskinfos if recenttaskinfobaseintentgetcomponentgetpackagenameequalscontextconstantspackage name newintent recenttaskinfobaseintent newintentsetflagsintentflag activity new task if newintent null newintent new intentreturn newintentsecond point is that if i used deprecated metods in order to build notification thisplaying last activity works great as i wanted here is codenotification note new notificationiconid getresourcesgettextrstringservicestarted systemcurrenttimemillis noteflags notificationflag ongoing event noteflags notificationflag no clear intent nintent new intent nintent getpreviousintentnintent pendingintent pi pendingintentgetactivitythis 0 nintent 0 notesetlatesteventinfothis getresourcesgettextrstringapp name getservicestatedescriptionyourservicethis pi startforegroundcontextconstantslauncher service note id notebut i do not want use deprecated metods anymore that is why i am here explaining thanks in advanceand i have seen this doc as wellhere is my manifestxml version10 encodingutf8permission androidnamecommypackagepermissionc2d message androidprotectionlevelsignature usespermission androidnameandroidpermissionreceive boot completedusespermission androidnameandroidpermissioninternetusespermission androidnameandroidpermissionwrite external storageusespermission androidnameandroidpermissionread external storageusespermission androidnameandroidpermissionaccess network stateusespermission androidnameandroidpermissionaccess wifi stateusespermission androidnameandroidpermissionread phone stateusespermission androidnameandroidpermissionvibrateusespermission androidnameandroidpermissionwake lockusespermission androidnameandroidpermissionread contactsusespermission androidnamecomgoogleandroidc2dmpermissionreceive usespermission androidnamecommypackagepermissionc2d message usespermission androidnameandroidpermissionget tasksapplication androidnamemyapplication androidicondrawableic launcher androidlabelstringapp name androidthemestylethemeappcompatlight activity androidnameactivitystartingactivity androidlabelstringapp name intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity activity androidnameactivitymainactivity androidconfigchangesorientationscreensize activity activity androidnameactivitycomposeemailactivity androidconfigchangesorientationscreensize androidparentactivitynameactivitymainactivity metadata androidnameandroidsupportparent activity androidvalueactivitymainactivity activity activity androidnameactivityeditaccountactivity androidconfigchangesorientationscreensize androidparentactivitynameactivitymainactivity metadata androidnameandroidsupportparent activity androidvalueactivitymainactivity activity androidprocessremote is for working in background service androidenabledtrue androidnameserviceyourservice application,['android'] +945092,why xcode 7 shows tbd instead of dylib xcode 7in target buildphases link binary with libraries tap buttonwhen choosing frameworks to add you cannot find dylib youll see tbd instead what is the reason for this for people who need dylib follow from this postchoose add otheronce in the file selection window do cmdshiftg go to folder type usrlibfrom userlib you can find the dylib files,['ios'] +945103,xpath of element on another websitecross domian i want to get the xpath of an element on a website my own domain which i got it using javascript code as mentioned in this answer now what i want to click on button which will open a url cross domain window and when user click on an element on that window it is xpath is capturedi tried doing the same using iframe with no lucknow my question is there a way to get the xpath of an element of another website cross domainany help will be appreciatedthanks,['javascript'] +945241,slow antlr4 generated parser in python but fast in java i am trying to convert ant antlr3 grammar to an antlr4 grammar in order to use it with the antlr4python2runtimethis grammar is a cc fuzzy parserafter converting it basically removing tree operators and semanticsyntactic predicates i generated the python2 files usingjava jar antlr45completejar dlanguagepython2 cppgrammarg4and the code is generated without any error so i import it in my python project i am using pycharm to make some tests import sys timefrom antlr4 import from parsercppgrammarlexer import cppgrammarlexerfrom parsercppgrammarparser import cppgrammarparsercurrenttimemillis lambda introundtimetime 10def is stringobject return isinstanceobjectstrdef parsecommandstringlineargv if2lenargv raise indexerrorinvalid args size ifis stringargv1 return true else raise typeerrorargument must be str typedef doparsingargv if parsecommandstringlineargv printarguments ok 0formatargv1 input filestreamargv1 lexer cppgrammarlexerinput stream commontokenstreamlexer parser cppgrammarparserstream print parser start start currenttimemillis tree parsercode print parser end 0 msformatcurrenttimemillisstart passdef mainargv tree doparsingargv passif name main mainsysargvthe problem is that the parsing is very slow with a file containing 200 lines it takes more than 5 minutes to complete while the parsing of the same file in antlrworks only takes 12 secondsanalyzing the antlrworks tree i noticed that the expra rule and all of its descendants are called very often and i think that i need to simplifychange these rules to make the parser operate fasteris my assumption correct or did i make some mistake while converting the grammar what can be done to make parsing as fast as on antlrworksupdatei exported the same grammar to java and it only took 795ms to complete the parsing the problem seems more related to python implementation than to the grammar itself is there anything that can be done to speed up python parsingi have read here that python can be 2030 times slower than java but in my case python is 400 times slower,"['java', 'python']" +945251,how can i move a scrollbar from inside to outside a table i have this scrollable table and notice that it only move its tbody not its thead and that is how it should be but the scrollbar is inside the table which makes the thead and the tbody thisarrange so i had an idea to move the scrolbar to outside the table but i do not know how to do it to a scrollbar can you tell me how i can do itlive long and prosperfrom thisto thisfunction removeclassnameelem classname elemclassname elemclassnamereplaceclassname trimfunction addcssclasselem classname removeclassnameelem classname elemclassname elemclassname classnametrimstringprototypetrim function return thisreplacess function stripedtable if documentgetelementbyid documentgetelementsbytagname var alltables documentgetelementsbytagnametable if alltables return for var i 0 i alltableslength i if alltablesiclassnamematchws scrolltablews var trs alltablesigetelementsbytagnametr for var j 0 j trslength j removeclassnametrsj alternaterow addcssclasstrsj normalrow for var k 0 k trslength k 2 removeclassnametrsk normalrow addcssclasstrsk alternaterow function calcth var table documentgetelementsbytagnametable for var i 0 i tablelength i tableiwidth 100 tablelength function calc var table documentgetelementbyidstable var w tableoffsetwidth total width of the table for var y 0 y tablerowslength y cycle through rows var row tablerowsy for var x 0 x rowcellslength x cycle through cells var cell rowcellsx cellstylewidth w rowcellslength px add px for a unit windowonload function stripedtable calcwindowonresize function stripedtable calcth calcth wordbreak breakallhtml width 100 height 100 overflow hiddenbody background f color 0 font normal normal 12px verdana geneva arial helvetica sansserif margin 10px padding 0tabletda color 0 font normal normal 12px verdana geneva arial helvetica sansserifh1 font normal normal 18px verdana geneva arial helvetica sansserif margin 0 0 5px 0divtablecontainer clear both border 1px solid 963 height 285px overflow auto width 100htmlbody divtablecontainer overflow hidden width 100 height 100divtablecontainer table float left width 100htmlbody divtablecontainer table width 100theadfixedheader tr position relativehtmlbody theadfixedheader tr thisplay blocktheadfixedheader th background c96 borderleft 1px solid eb8 borderright 1px solid b74 bordertop 1px solid eb8 fontweight normal padding 4px 3px textalign lefttheadfixedheader atheadfixedheader alinktheadfixedheader avisited color f thisplay block textdecoration none width 100theadfixedheader ahover color f thisplay block textdecoration underline width 100htmlbody tbodyscrollcontent thisplay block height 262px overflow auto width 100 make td elements pretty provide alternating classes for striping the table tbodyscrollcontent tdtbodyscrollcontent trnormalrow td background f borderbottom none borderleft none borderright 1px solid c bordertop 1px solid d padding 2px 3px 3px 4pxtbodyscrollcontent tralternaterow td background e borderbottom none borderleft none borderright 1px solid c bordertop 1px solid d padding 2px 3px 3px 4pxhtml xmlns xmllangen langenhead titlepure css scrollable table with fixed headertitle meta httpequivcontenttype contenttexthtml charsetutf8 meta httpequivlanguage contentenus style typetextcstyleheadbody h1pure css scrollable table with fixed headerh1 div idtablecontainer classtablecontainer table border0 cellpadding0 cellspacing0 width100 clascrolltable idstable thead classfixedheader tr classalternaterow tha hrefheader 1ahjsgdhjagsdhjgahjsdghjasgdhjagshjdgahjsdghjagsdhja th tha hrefheader 2a th tha hrefheader 3a th tr thead tbody clascrollcontent tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tr classnormalrow tdcell content 1td tdcell content 2td tdcell content 3td tr tr classalternaterow tdmore cell content 1td tdmore cell content 2td tdmore cell content 3td tr tbody table div div br divbodyspan classgr tooltipspan classgr tooltipcontentspani classgr tooltiplogoispan classgr trianglespanspanhtml,"['javascript', 'jquery', 'css']" +945274,how to avoid class selfuse i have the following classpublic class myclass public void deleteorganizationorganization organization delete organization delete related users for user user organizationgetusers deleteuseruser public void deleteuseruser user delete user logic this class represents a selfuse in that its public method deleteorganization uses its other public method deleteuser in my case this class is a legacy code against which i started adding unit tests so i started by adding a unit test against the first method deleteorganization and ended up figuring out that this test has been extended to also test the deleteuser methodproblemthe problem is that this test is not isolated anymore it should only test the deleteorganization method i was obliged to treat the different conditions related to deleteuser method in order to pass it so to pass the test which has hugely increased the complexity of the testsolutionthe solution was to spy the class under test and stub deleteusera methodtestpublic void shoulddeleteorganization myclass spy spynew myclass avoid invoking the method donothingwhenspydeleteuseranyuserclass invoke method under test spydeleteorganizationnew organizationnew problemthough the previous solution solves the problem it is not recommended as the javadoc of the spy method statesas usual you are going to read the partial mock warning object oriented programming is more less tackling complexity by dividing the complexity into separate specific srpy objects how does partial mock fit into this paradigm well it just does not partial mock usually means that the complexity has been moved to a different method on the same object in most cases this is not the way you want to design your applicationthe complexity of the deleteorganization method has been moved to deleteuser method and this is caused by the class selfuse the fact that this solution is not recommended in addition to the in most cases this is not the way you want to design your application statement suggests that there is a code smell and refactoring is indeed needed to improve this codehow to remove this selfuse is there a design pattern or a refactoring technique that can be applied,['java'] +945276,fileoutputstream does the close method calls also flush i am really confused about flush and close methodin my code i always close my fileoutputstream object but i want to know that if i have to use flush method here and where can i use iti will write a project that download 4 or 5 files repeatedly i will write a methodfor download files and my method will be in a loop and download files repeatedlymy method will have a code like thisdoes the close method calls flush or do i have to use flush before closingtry inputstream inputstream congetinputstream fileoutputstream outputstream new fileoutputstreamcprogramstryfilecsv int bytesread 1 byte buffer new byte4096 while bytesread inputstreamreadbuffer 1 outputstreamwritebuffer 0 bytesread catchexception e finally outputstreamclose inputstreamclose note that the code works well it download the file successfully but i am not sure about using flush,['java'] +945315,rcharts nvd3 2d zoom possible is there a zooming function in nvd3 that i can directly type in my r source code does not matter if it requires javascript as long as i do not have to change nvd3 source code i tried the linewithfocuschart but that only zooms along the xaxis whereas i would like to ideally draw a box around the zoom section and it will zoom to where i drew the box even if that is not possible if nvd3 supports any kind of 2d zoom that would be awesome i have provided a reproducible example of what i have so far but i have not found a feature for the zoom i am looking for yet thank you libraryrcharts temp dataframex 1100 y 1100 z crep150 rep050 g nploty x group z data temp type linechart gtemplatesscript nvd3 templateschartwithtitle styledhtml gsettitle example gcharttransitionduration 1 tooltipcontent functionkey x y return z key br x x br y y showlegend false margin listleft 200 right 100 bottom 100 top 100 gxaxisaxislabel x gyaxisaxislabel y width 40 g,['javascript'] +945383,how to test decorated react component with shallow rendering i am following this tutorial trying to learn how shallow rendering worksi have a higher order componentimport react from reactfunction withmuicomposedcomponent return class withmui render return composedcomponent thisprops and a componentwithmuiclass playerprofile extends reactcomponent render const name avatar thisprops return div classnameplayerprofile div classnameprofilenamenamediv div avatar srcavatar div div and a testdescribeplayerprofile component testing with shallow rendering beforeeachfunction let testutils reactaddons thistestutils testutils thisrenderer testutilscreaterenderer thisrendererrenderplayerprofile nameuser avataravatar itrenders an avatar function let result thisrenderergetrenderoutput consolelogresult expectresulttypetoequalplayerprofile the result variable holds thisrenderergetrenderoutputin the tutorial the resulttype is tested likeexpectresulttypetoequaldivin my case if i log the result it islog objecttype function playerprofile so i changed my test likeexpectresulttypetoequalplayerprofilenow it gives me this errorassertion error expected function playerprofile to equal function withmuiso playerprofiles type is the higher order function withmuiplayerprofile decorated with withmui using shallow rendering only the playerprofile component is rendered and not it is children so shallow rendering wouldnt work with decorated components i assumemy question iswhy in the tutorial resulttype is expected to be a div but in my case is nothow can i test a react component decorated with higher order component using shallow rendering,['javascript'] +945428,bucketing in r or sql i am completely stumped on a problem and would like some guidance i am picking random sets of 8 numbers from the set of 1 to 8 for example 56813427 and trying to bucket those numbers as subsets of sequential numbers according to the order they appear for the example above the first bucket would start with a 5 then the 6 would be added upon hitting the 8 a new bucket would be started whenever we get to a number that belongs in an existing bucket eg when we reach 2 it can be added to 1s bucket we add it there in this example after all 8 numbers wed arrive at56781234for a total of 4 buckets i am not actually concerned with the contents of the buckets i just want to count how many buckets there are for a given random set of 8 digits i plan on looping through a set of 10 of these 8 digit sequences,['sql'] +945430,clojurescript without java is it possible to compile clojurescript without javai read the clojurescript nodejs quickstart but i see they still use java to compilei checked cljsbootstrap but they also depend on javais there any way to just use npm install and start using clojurescript,['java'] +945454,beautifulsoup get text is not specific enough for my html parsing given the html code below i want output just the text of the h1 but not the details about which is the text of the span which is encapsulated by the h1 my current output gives details about a new mens genuine leather bifold id credit card money holder wallet blacki would likenew mens genuine leather bifold id credit card money holder wallet blackhere is the html i am working withh1 classitl itempropname iditemtitlespan classghdndetails about nbspspannew men039s genuine leather bifold id credit card money holder wallet blackh1here is my current codefor line in soupfind allh1attrsitempropname print lineget textnote i do not want to just truncate the string because i would like this code to have some reusabilitywhat would be best is some code that crops out any text that is bounded by the span,"['python', 'html']" +945544,getting server data for the apple watch i am wondering how to go about designing a watchos app that depends on getting the latest feed from a server would you need to use application context and just have the iphone push it over in the background using the watchconnectivity framework or would you use nsurlsession on the apple watch itself keep in mind this is for watchos 2,['ios'] +945617,double exclamation mark in swift i know the definition for a single exclamation mark but twoi was coding today and the compiler force me to add one more to my sentencemysignalsubscribenext value anyobject in let list racsequence valuemyobjectrac sequence if i use only one mark the project does not compile giving me the error value of optional type anyobject not unwrapped did you mean to use or then i add one more and everything workswhats the meaning for two exclamation marks in swift,['ios'] +945697,jquery change selectbox value based on radio button value or other way round i have a site that allows users to guess predict the result of a sports matchto give you an idea what i am trying to achieve have a look at the following image the selected teams gets thisplayed at the bottom of the page along with their scores as you can see on the bottom circle of the imagewhat im trying to doas you can see in 1st circle the selected score is 0 zero thus i would like the radio button selected to automatically jump to draw in the second circle the user selected draw by 12 points in that case i would like the selectbox value to automatically default to zero or thisp appropriate message my problemmy script below thisplays the selected team and selected score inside a div at the bottom of page i can get the above described problem to work but that in turn affects the primary working of my script explained aboveany idea how i can solve above problem without affecting the primary working of my script explained aboveplease play around with my code snippet to get an idea of my problemmy codedocumentreadyfunction radio selectchangefunction e clear the div thisppickshtml update the div radiocheckedeachfunction ind ele var selectboxval thisclosestdivteamfindselectval selectboxval selectboxval by selectboxvalselectboxval thisppicksappendeleval selectboxval br script srcscriptdiv classteaminput typeradio namefoo valueshaks input typeradio namefoo valuehurricanes input typeradio namefoo valuedraw select option value0option option value11option option value22option option value33option option value44option option value55option option value66option option value77option option value88option option value99option option value1010optionselectbrdivdiv classteaminput typeradio namebar valuecrusaders input typeradio namebar valuepioneers input typeradio namebar valuedraw select option value0option option value11option option value22option option value33option option value44option option value55option option value66option option value77option option value88option option value99option option value1010optionselectbrdivdiv classteaminput typeradio namewow valuechelsea input typeradio namewow valueliverpool input typeradio namewow valuedraw select option value0option option value11option option value22option option value33option option value44option option value55option option value66option option value77option option value88option option value99option option value1010optionselectdivdiv idthisppicksdiv,"['javascript', 'jquery', 'html', 'css']" +945745,why does spinner control still thisplay prompt information even if the event setonitemselectedlistener is after setselection i write the event setonitemselectedlistener of spinner after spinnerrangersetselectioni think toastmaketext will not launch when i run the app for the first time but prompt information is still thisplayed whyoverridepublic view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate view rootview inflaterinflaterlayoutcleanup delete fragment old container false mview rootview mcontext rootviewgetcontext initvalueofcontrols return rootviewprivate void initvalueofcontrols spinnerranger spinnermviewfindviewbyidridspinner publicparfunfillrangespinnermview spinnerranger spinnerrangersetselectionpublicparfungetindexofrangedeleteoldmcontext spinnerrangersetonitemselectedlistenernew adapterviewonitemselectedlistener override public void onitemselectedadapterview parent view view int position long id toastmaketextmcontext my position toastlength longshow override public void onnothingselectedadapterview parent to trevor carothersif i insert a dolongtimeoperation before selection listener event will it still thisplay the toastprivate void initvalueofcontrols spinnerranger spinnermviewfindviewbyidridspinner publicparfunfillrangespinnermview spinnerranger spinnerrangersetselectionpublicparfungetindexofrangedeleteoldmcontext dolongtimeoperation spinnerrangersetonitemselectedlistenernew adapterviewonitemselectedlistener override public void onitemselectedadapterview parent view view int position long id toastmaketextmcontext my position toastlength longshow override public void onnothingselectedadapterview parent code aprivate void initvalueofcontrols spinnerranger spinnermviewfindviewbyidridspinner publicparfunfillrangespinnermview spinnerranger spinnerrangersetselectionpublicparfungetindexofrangedeleteoldmcontext dolongtimeoperation spinnerrangerpostnew runnable override public void run spinnerrangersetonitemselectedlistenernew adapterviewonitemselectedlistener override public void onitemselectedadapterview parent view view int position long id toastmaketextmcontext my position toastlength longshow override public void onnothingselectedadapterview parent code bprivate void initvalueofcontrols spinnerranger spinnermviewfindviewbyidridspinner publicparfunfillrangespinnermview spinnerranger spinnerrangersetselectionpublicparfungetindexofrangedeleteoldmcontext spinnerrangerpostnew runnable override public void run spinnerrangersetonitemselectedlistenernew adapterviewonitemselectedlistener code cprivate void initvalueofcontrols spinnerranger spinnermviewfindviewbyidridspinner publicparfunfillrangespinnermview spinnerranger spinnerrangersetselectionpublicparfungetindexofrangedeleteoldmcontext spinnerrangersetonitemselectedlistenernew adapterviewonitemselectedlistener,['android'] +945934,audioqueuethispose delay according to documentation here refcfuncaudioqueuethispose err audioqueuethisposequeue truei use true so thispose of audioqueue happens immediately although it does thispose queue immediately sometimes other times it has delay 34 seconds up to 13 seconds on the device err audioqueuestopqueue true has the same problem as well my understanding is that both functions try to flushrelease buffers already and about to be enqueuedso i even help my callback function to flush the buffers if audioqueuethispose is going to be calledstatic void myaqoutputcallbackvoid inuserdata audioqueueref inaq audioqueuebufferref incompleteaqbuffer if playershouldthispose printfplayer shouldthispose n osstatus thispose audioqueueflush inaq return since i am going to record something using audioqueues after playing a track i need this functions returned without delays couple hundred milliseconds is okay but 34 seconds that is unacceptable other audioqueue functions also being called on the same thread and they seem working fine i have also tried to call this on main thread to make sure if it is going to change anything or notself performselectoronmainthreadselectortryonmain withobjectnil waituntildoneno or thispatch syncthispatch get main queue didnt do any differenceany idea what might be happening,"['ios', 'objective-c']" +946019,spacing between rows i have divs that are set to specific thisplays to mimic a table so basically i want to achieve the style that is shown in the image when a row is selected i have tried padding and margins but it does not seem to work anyone has any idea how i can do thistable thisplay tableheader thisplay tableheadergroup fontweight boldrow thisplay tablerowgroupcell thisplay tablecell border 1px solid black padding 5pxselected background red margin 20px border 1px solid red borderradius 10pxdiv classtable div classheader div classcellheader 1div div classcellheader 2div div div classrow selected div classcellrow 1 cell 1div div classcellrow 1 cell 2div div div classrow div classcellrow 2 cell 1div div classcellrow 2 cell 2div div div classrow div classcellrow 3 cell 1div div classcellrow 3 cell 2div divdiv,"['html', 'css']" +946133,building a swift framework with xcode 7 beta 3 to use as an embedded binary ever since embedded binaries were introduced in ios 8 i have been wanting to port a lot of my common code into frameworks i decided to wait one year before doing it and this year with xcode 7 beta and ios 9 i am starting to do that just thati have started a cocoa touch framework project in xcode 7 and i want to compile it into a usable framework i can get it to compile my project into a framework but there is a few issues namely the framework does not appear to be importable into new projects i will describe the steps i did for that shortly because of that i am not sure if my framework has any visible symbolsthis is what i have done to create the frameworkcreated my framework as a cocoa touch frameworkwent to my targets build phases went to headers and added all my swift files to the public section in hopes that will export all my simbols without having to mark them as publici tried to archive my project as a framework currently it looks like xcode 7 beta 3 has a bug going to report it later today in which it generates corrupted archive files for this reason i could not get my framework from the organizer window to work around this i changed the schema of the run action in xcode from debug to release built it and grabbed it is generated framework from my projects buildiphoneosrelease directory this was a quick test so i did not need the frameworks generated for emulatorsand this is what i did to try to add the framework to a new projectcreated a frameworks group for organizational purposes and dragged the framework there selecting yes when it asked me if i want to copy the file to my projects directorywent to my targets settings removed my framework from linked libraries it was added there automatically added it to embedded binaries instead this added the framework to linked libraries again so i had to remove it from there twice leaving the framework in linked libraries causes a linker error cannot find the framework no idea why but i think it is irrelevant to my problem and something i should report to apple as well but once you remove it from there it seems to compile fine when you add it to embedded binariestried to import my framework in a file xcode complains there is no such moduleunfortunately despite the fact that embedded frameworks have been around for around a year i cannot find much writing on the topicso my question is am i creating the framework correctly making it possible that my frameworkanything else is failing due to an xcode 7 beta bug or is there a different procedure to create a framework that i want to use as an embedded binary i should probably mention that i want to make this library open source and i think thistributing a plain framework file to the people who want to use it would be neat,['ios'] +946272,how to handle a file as string generated by prawn so that it is accepted by carrierwave i am using prawn to generate a pdf from the controller of a rails apprespond to do format formatpdf do pdf generatereportpdfnewobject view context send data pdfrender filename report type applicationpdf thisposition inline endendthis works fine but i now want to move generatereportpdf into a background task and pass the resulting object to carrierwave to upload directly to s3the worker looks like thisdef perform pdf generatereportpdfnewobject filestring document documentnew object id objectid file filestring file is field used by carrierwave endhow do i handle the object returned by prawn to ensure it is a format that can be read by carrierwavefilestring pdfrender file filename writes the object to the root directory of the app as i am on heroku this is not possible file pdfrender returns argumenterror string contains null bytefilestring stringionew pdfrender file filename returns typeerror no implicit conversion of nil into stringfilestring stringionew pdfrender returns activerecordrecordinvalid validation failed file you are not allowed to upload nil files allowed types jpg jpeg gif png pdf doc docx xls xlsxfilestring fileopen pdfrender returns argumenterror string contains null byteand so onwhat am i missing stringionew pdfrender seems like it should work but i am unclear why its generating this error,['ruby-on-rails'] +946349,javalangnosuchmethoderror when it is clearly there general info i am using the bukkitspigot api in version gitspigot1d14d5fba32592 mc 183 implementing api version 183r01snapshot intellij idea 1413 and compile with its default compiler the java jdk version is 180 25so when i try to call this clas constructor it throws the runtime exception from the titleinventory menu classpackage melakanutilinventoryimport orgbukkitbukkitimport orgbukkitentityplayerimport orgbukkiteventeventhandlerimport orgbukkiteventeventpriorityimport orgbukkiteventlistenerimport orgbukkiteventinventoryinventoryclickeventimport orgbukkiteventinventoryinventorytypeimport orgbukkitinventoryinventoryimport orgbukkitinventoryitemstackimport orgbukkitpluginjavajavapluginimport javautilhashmapimport javautilmapsuppresswarningsunused util functionality is not always usedpublic class inventorymenu implements listener private inventorytype type private string title private mapinteger menuoption options constructors public inventorymenuinventorytype type string title javaplugin plugin thisoptions new hashmapinteger menuoption thistype type thistitle title plugingetservergetpluginmanagerregistereventsthis plugin public boolean addoptionint position menuoption option boolean res isposemptyposition thisoptionsputposition option return res public void addoptionstring name int position itemstack icon addoptionposition new menuoptionicon name public boolean isposemptyint position return thisoptionscontainskeyposition public void openforplayer p create a new inventory inventory inv bukkitcreateinventoryp thistype thistitle fill all icons at their positions for mapentryinteger menuoption key thisoptionsentryset invsetitemkeygetkey keygetvaluegeticon if the inventory is a player inventory update the players if invgettype inventorytypeplayer pgetinventorysetcontentsinvgetcontents for any openable inventory just open it up else popeninventoryinv listens for inventory clicks if the inventory is a menu cancel movement push event close inventory if it should param e the actual event eventhandlerpriority eventpriorityhighest public void oninventoryclickinventoryclickevent e prevent clicking if this inventory was clicked if egetclickedinventorygetnameequalsthistitle esetcancelledtrue check for option if thisoptionscontainskeyegetrawslot get the option for this slot menuoption option thisoptionsgetegetrawslot fill out an event and push it menuclickevent event new menuclickeventplayer egetwhoclicked true optiongetname egetrawslot bukkitgetservergetpluginmanagercalleventevent now close inventory if not cancelled if eventwillclose egetwhoclickedcloseinventory suppresswarningsunused public interface optionclickeventhandler public void onoptionclickmenuclickevent event the item menu classpackage melakantestimport melakanutilinventoryinventorymenuimport melakanutilinventorymenuclickeventimport melakanutilinventorymenuoptionimport melakanutilitemitembuilderimport orgapachecommonslangvalidateimport orgbukkitchatcolorimport orgbukkitmaterialimport orgbukkitentityplayerimport orgbukkiteventeventhandlerimport orgbukkiteventeventpriorityimport orgbukkiteventlistenerimport orgbukkiteventinventoryinventorytypepublic class itemmenu implements listener private pluginentry plugin private inventorymenu menu commands private testcommand testcmd public itemmenupluginentry plugin validatenotnullthisplugin the plugin reference may not be null thisplugin plugin thismenu new inventorymenuinventorytypechest chatcolordark gray abilities thisplugin test thismenuaddoption1 new menuoption new itembuilder amount1 materialmaterialraw fish namechatcolorlight purple test lorechatcolorwhite click me build testidentifier thistestcmd new testcmdthisplugin public void openforplayer p thismenuopenforp eventhandlerpriority eventprioritynormal public void onoptionclickmenuclickevent e test if egetnameequalstestidentifier thistestcmdexecuteforegetwhoclicked exception stack trace124825 server threaderror error occurred while enabling test v10 is it up to date javalangnosuchmethoderror melakanutilinventoryinventorymenulorgbukkiteventinventoryinventorytypeljavalangstringlorgbukkitpluginjavajavapluginvat melakantestitemmenuitemmenujava33 at melakantestcommandparsercommandparserjava20 at melakantestpluginentryonenablepluginentryjava21 at orgbukkitpluginjavajavapluginsetenabledjavapluginjava321 spigot serverjargitspigot1d14d5fba32592 at orgbukkitpluginjavajavapluginloaderenablepluginjavapluginloaderjava335 spigot serverjargitspigot1d14d5fba32592 at orgbukkitpluginsimplepluginmanagerenablepluginsimplepluginmanagerjava405 spigot serverjargitspigot1d14d5fba32592 at orgbukkitcraftbukkitv1 8 r2craftserverloadplugincraftserverjava356 spigot serverjargitspigot1d14d5fba32592 at orgbukkitcraftbukkitv1 8 r2craftserverenablepluginscraftserverjava316 spigot serverjargitspigot1d14d5fba32592 at netminecraftserverv1 8 r2minecraftserverrminecraftserverjava416 spigot serverjargitspigot1d14d5fba32592 at netminecraftserverv1 8 r2minecraftserverkminecraftserverjava382 spigot serverjargitspigot1d14d5fba32592 at netminecraftserverv1 8 r2minecraftserveraminecraftserverjava337 spigot serverjargitspigot1d14d5fba32592 at netminecraftserverv1 8 r2dedicatedserverinitdedicatedserverjava257 spigot serverjargitspigot1d14d5fba32592 at netminecraftserverv1 8 r2minecraftserverrunminecraftserverjava522 spigot serverjargitspigot1d14d5fba32592 at javalangthreadrununknown source 180 31as you can see the constructor is there and is to my knowledge properly called so is this error a mistake in my project setup an api thing or something entirely differentthe utility classes are in a seperate module and everything works if i paste them into my test plugin module but not inside the other module however any other constructor in any other class inside melakanutilinventory can be called normally,['java'] +946388,proxy node request to new port and act like reverse proxy i need to create an application that proxies a request from port a to port bfor instance if a user connects on port 30 he will be routed under the hood to port 3001 therefore the original application will run on port 3001 but in the client browser the user will put port 30not redirect a new server will be created which listens to port 3001 and all the call are actually to port 30 running with the new server and new portsince port 30 is actually occupiedby my reverse proxy app how should i test itis there a way to test this to verify that this is workingeg by unit testingi have found this module which might be able to help,['javascript'] +946391,snackbar and fitssystemwindow i have an app that uses fitssystemwindows to be able to draw an background behind navigation and statusbar unfortunately the snackbar seems to ignore the fitssystemwindowstrue from the container i boiled the problem down to this minimal appthe styleresources style nameapptheme parentthemeappcompatlight item nameandroidwindowbackgroundcoloraccent material darkitem item nameandroidfitssystemwindowsfalseitem item nameandroidwindowtranslucentstatustrueitem item nameandroidwindowtranslucentnavigationtrueitem styleresourcesthe layoutrelativelayout xmlnsandroid xmlnstools androidlayout widthmatch parent androidlayout heightmatch parent androidfitssystemwindowstrue toolscontextmainactivity button androidididbutton androidtextstringhello world androidlayout widthmatch parent androidlayout heightmatch parentrelativelayoutthe activitypublic class mainactivity extends appcompatactivity override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main findviewbyidridbuttonsetonclicklistenernew viewonclicklistener override public void onclickfinal view v snackbarmakevthis snackbar should fitsystemwindowssnackbarlength indefiniteshow anyone knows some workaroundi published the minimal app to show the problem here,['android'] +946443,execute script on server by user action i did not really know how to describe my problem on the title so i did my besti have a function that reset my website i also have a time stamp in which that function should execute the time stamp is changing every reset so i need to find a way to activate that function on quemy best soultion so far was to write time to reset function and if it is true run the script but the script is heavy and i am afraid it would not be possible to run it on some random user the reset is happening only once computer he could exit the website before the script executed completlyalso i affraid in some situations the script will execute twice or more due of a few users logging in togather this is another problem i will be happy to get help solvei am sorry for my bad english and for the none code question i hate it tooi will gladly explain again if you did not understand me thank youediti do not have to use the users it was only an idea i hadi have an admin panel written in php code in which you can edit the date of the time for reset there is a way to change cj dates with php code or any other way to make the reset happen without using the users,"['php', 'mysql']" +946513,moving to uninitialized memory or how raw storage iterator works i want to move a range of objects into uninitialized memory using moveconstruction since there is no movecounterpart to stduninitialized copy i came up with two options either use stdmove with raw storage iterator or resort to the manual loopt dest get memory option onestdmovefirst last stdraw storage iteratort tdest option twofor auto ifirst i last i dest newdest tstdmoveiwill the first option do the moveconstruction thus being equivalent to the second or copy construction or default construction followed by move assignment are there other considerations to prefer one option or another,['c++'] +946616,loading genymotion library genymotion directory applicationsgenymotionappcontentsmacos trying to initialize engine initialize engine failed the problem is same as topicloading genymotion librarygenymotion directory applicationsgenymotionappcontentsmacostrying to initialize engineinitialize engine failedi have installed virtualbox 500 and successfully executedif i directly run the genymotion app it also workshowever i clicked the icon pluged in eclipse then it appears the error messagei have searched the solution on the website and then i have relocated the directory of genymotionapp but it still did not work are there any people have the same experience likes minei will thank you if you guys have some method,['android'] +946625,uiactivityviewcontroller plugin netwhatsappwhatsappshareextension invalidated i am using uiactivityviewcontroller and after sending an image via whatsapp i am getting this message in the console plugin netwhatsappwhatsappshareextension invalidatedwhy is this message showing in logjaba edited i am using ios 92 swift xcode 72but i oz was using xcode 64 objectivec ios 8,"['ios', 'iphone']" +946733,url bar hiding when scrolling on phone messes 100 height up i have this following demo website pieces of content as well as navigation are set to 100 height when i am on my phone there is this url bar up top that hides when i scroll up however this effect messes the 100 height up because it adjusts to the new browser size creating an unpleasing effect the same goes for vh and vw unitsi have tried the followingfunction windowdimensions if htmlhasclasstouch height windowscreenheight width windowscreenwidth else height winheight width winwidth function screenfix if htmlhasclasstouch touch true navcssheight height px homecssheight height px headercssheight height2 px contentcssminheight height px this however creates a problem because at the very top there is this bar with battery wifi signal info that is also accounted to the screen height making the 100 and vh elements a tad biggeri could not believe i did not find any other question about this as i assumed this is a pretty common problem for 100100 sitesdo you guys know any fix for this,"['javascript', 'jquery', 'html', 'css']" +946740,android m request permission non activity my widget makes calls to secure permissions outside of an activity scope is it possible to request permissions for android m outside of an activity,['android'] +946847,cannot change navigation drawer icon color in android ok i know this is a trivial issue but for some reason it is not working for me i have done a lot of things suggested in other answers but in vain my drawable folder has white color icons i even tried to change it from stylesxml but that does not work either i am testing it on my lollipop device any help will be appreciated thanks in advancethis is a portion of my manifest file application androidallowbackuptrue androidicondrawableic drawer androidlabelstringapp name metadata androidnamecomgoogleandroidgmsversion androidvalueintegergoogle play services version toolsreplaceandroidvalue activity androidnameactivity splash androidlabelstringapp name intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity activity androidnameactivity test androidlaunchmodesingleinstance androidthemestyleappthemebase androidwindowsoftinputmodestatehidden and finally this is my stylexml similar is for v21style nameappthemebase parentthemeappcompatlightnoactionbar item nameandroidwindowcontenttransitionstrueitem item nameandroidwindowallowentertransitionoverlaptrueitem item nameandroidwindowallowreturntransitionoverlaptrueitem item nameandroidactionmenutextcolorfitem item namecolorprimarycolorcolorprimaryitem item namecolorprimarydarkcolorcolorprimarydarkitem item namedrawerarrowstylestylemydrawerarrowtoggleitem item namewindowactionbarfalseitem item namecoloraccentfitem item nameandroidwindowsharedelemententertransitionandroidtransitionmoveitem item nameandroidwindowsharedelementexittransitionandroidtransitionmoveitemstyle,['android'] +946919,why proguard does not obfuscate method body i am using proguard to obfuscate my jar program everything works fine except for the fact that proguard does not obfuscate local variables in method bodies here is an examplerawobfuscatedthe variable names that are highlighted in yellow should be obfuscated but they are not how can i obfuscate them too make them renamed to a b c etchere is my proguard config the above method is not from one of the excluded classes,['java'] +946990,aysncio cannot read stdin on windows i am trying to read stdin asynchronously on windows 7 64bit and python 343i tried this inspired by an so answerimport asyncioimport sysdef reader printreceived sysstdinreadlineloop asyncioget event looptask loopadd readersysstdinfileno readerlooprun foreverloopclosehowever it raises an oserror winerror 100381 an operation was attempted on something that is not a socket could a filelike object like stdin be wrapped in a class to give it the api of a socket i have asked this question separately but if the solution is simple please answer hereassuming that i cannot wrap a filelike object to make it a socket i tried using streams as inspired by this gistimport asyncioimport sysasynciocoroutinedef stdioloop reader asynciostreamreaderlooploop reader protocol asynciostreamreaderprotocolreader yield from loopconnect read pipelambda reader protocol sysstdinasynciocoroutinedef async inputloop reader yield from stdioloop line yield from readerreadline return linedecodereplacer replacen asynciocoroutinedef mainloop name yield from async inputloop printhello nameloop asyncioget event looplooprun until completemainlooploopcloseand that raises a notimplementederror in asynciobase events make read pipe transportplease advise how to read stdin using asyncio on windows,['python'] +946995,how to efficiently create a multirow photo collage from an array of images in swift problemi am building a collage of photos from an array of images that i am placing onto a tableview i want to make the images wrap when the number of images reaches the boundary of the tableview cells width this would allow me to thisplay rows of images in the collage currently i get a single row please feel free to advise if additional information is required i am most likely not approaching this in the most efficient way since there is a delay as the number of images used in the array begins to increase any feedback on this would be very much appreciatednota benei am creating a collage image it is actually one image i want to arrange the collage by creating an efficent matrix of columns and rows in memory i then fill these rects with images finally i snapshot the resulting image and use it when needed the algorithm is not efficient as written and produces only a single row of images i need a lightweight alternative to the algorithm used below i do not believe uicollectionview will be a useful alternative in this casepseudo codegiven an array of images and a target rectangle representing thetarget viewget the number of images in the array compared to max number allowed per rowdefine a smaller rectangle of appropriate size to hold the image sothat each row fills the target rectangle ie if one image then that should fill the row if 9 images then that should fill the row completely if 10 images with a max of 9 images per row then the 10th begins the second rowiterate over the collectionplace each rectangle at the correct location from left to rightuntil either last image or a max number per row is reached continue on next row until all images fit within the target rectanglewhen reaching a max number of images per row place the image andsetup the next rectangle to appear on the successive rowusing swift 20class func collageimage rectcgrect imagesuiimage uiimage let maxside maxrectwidth cgfloatimagescount rectheight cgfloatimagescount uigraphicsbeginimagecontextwithoptionsrectsize false uiscreenmainscreenscale var xtransformcgfloat 00 for img in images let smallrectcgrect cgrectmakextransform 00maxside maxside let rnd arc4random uniform270 15 draw in rect imgdrawinrectsmallrect rotate img using random angle uiimagerotateimageimg radian cgfloatrnd xtransform cgfloatmaxside 08 let outputimage uigraphicsgetimagefromcurrentimagecontext uigraphicsendimagecontext return outputimage class func rotateimagesrc uiimage radiancgfloat uiimage calculate the size of the rotated views containing box for our drawing space let rotatedviewbox uiviewframe cgrectmake00 srcsizewidth srcsizeheight let t cgaffinetransform cgaffinetransformmakerotationradian rotatedviewboxtransform t let rotatedsize rotatedviewboxframesize create the bitmap context uigraphicsbeginimagecontextrotatedsize let bitmapcgcontextref uigraphicsgetcurrentcontext move the origin to the middle of the image so we will rotate and scale around the center cgcontexttranslatectmbitmap rotatedsizewidth2 rotatedsizeheight2 rotate the image context cgcontextrotatectmbitmap radian now draw the rotatedscaled image into the context cgcontextscalectmbitmap 10 10 cgcontextdrawimagebitmap cgrectmakesrcsizewidth 2 srcsizeheight 2 srcsizewidth srcsizeheight srccgimage let newimage uigraphicsgetimagefromcurrentimagecontext uigraphicsendimagecontext return newimage alternative 1i have refined my solution to this a bit this one does stack the images in columns and rows however as stated my interest is in making this as efficient as possible whats presented is my attempt at producing the simplest possible thing that workscaveatthe image produced using this is skewed rather than evenly thistributed across the entire tableview cell efficient even thistribution across the tableview cell would be optimalclass func collageimage rectcgrect imagesuiimage uiimage let maxside maxrectwidth cgfloatimagescount rectheight cgfloatimagescount 080 let rowheight rectheight cgfloatimagescount 08 let maximagesperrow 9 var index 0 var currentrow 1 var xtransformcgfloat 00 var ytransformcgfloat 00 var smallrectcgrect cgrectzero uigraphicsbeginimagecontextwithoptionsrectsize false uiscreenmainscreenscale for img in images let x index maximagesperrow row should change when modulus is 0 row changes when modulus of counter returns zero maximagesperrow if x 0 last column of current row xtransform cgfloatmaxside smallrect cgrectmakextransform ytransform maxside maxside reset for new row currentrow xtransform 00 ytransform maxside cgfloatcurrentrow 1 else not a new row if xtransform 0 this is first column draw rect at 0ytransform smallrect cgrectmakextransform ytransform maxside maxside xtransform cgfloatmaxside else not the first column so translate x ytransform to be reset for new rows only smallrect cgrectmakextransform ytransform maxside maxside xtransform cgfloatmaxside draw in rect imgdrawinrectsmallrect let outputimage uigraphicsgetimagefromcurrentimagecontext uigraphicsendimagecontext return outputimage alternative 2the alternative presented below scales the images so that they always fill the rectangle in my case the tableview cell as more images are added they are scaled to fit the width of the rectangle when the images meet the maximum number of images per row they wrap this is the desired behavior happens in memory is relatively fast and is contained in a simple class function that i extend on the uiimage class i am still interested in any algorithm that can deliver the same functionality only faster nota bene i do not believe adding more ui is useful to achieve the effects as noted above therefore a more efficient coding algorithm is what i am seeking class func collageimage rectcgrect imagesuiimage uiimage let maximagesperrow 9 var maxside cgfloat 00 if imagescount maximagesperrow maxside maxrectwidth cgfloatmaximagesperrow rectheight cgfloatmaximagesperrow else maxside maxrectwidth cgfloatimagescount rectheight cgfloatimagescount var index 0 var currentrow 1 var xtransformcgfloat 00 var ytransformcgfloat 00 var smallrectcgrect cgrectzero uigraphicsbeginimagecontextwithoptionsrectsize false uiscreenmainscreenscale for img in images let x index maximagesperrow row should change when modulus is 0 row changes when modulus of counter returns zero maximagesperrow if x 0 last column of current row smallrect cgrectmakextransform ytransform maxside maxside reset for new row currentrow xtransform 00 ytransform maxside cgfloatcurrentrow 1 else not a new row smallrect cgrectmakextransform ytransform maxside maxside xtransform cgfloatmaxside draw in rect imgdrawinrectsmallrect let outputimage uigraphicsgetimagefromcurrentimagecontext uigraphicsendimagecontext return outputimage efficiency testingreda lemeden gives some procedural insight into how to test these cg calls within instruments on this blog post he also points out some interesting notes from andy matuschak of the uikit team about some of the peculiarities of offscreen rendering i am probably still not leveraging the ciimage solution properly because initial results show the solution getting slower when attempting to force gpu utilization,['ios'] +947046,detecting microsofts edge or spartan with javascript is the user agent for edge or spartan browsers known already can anyone tell me how to detect this browser and diferentiate it from ie in advance of its release,['javascript'] +947078,laravel no supported encrypter found the cipher and or key length are invalid i am building a project using laravel it was working fine on localhost but when i upload it to the server the server has comodo ssl installed i receive the following errorruntimeexception in encryptionserviceproviderphp line 29no supported encrypter found the cipher and or key length are invalidin encryptionserviceproviderphp line 29at encryptionserviceproviderilluminateencryptionclosureobjectapplication array in containerphp line 733at containerbuildobjectclosure array in containerphp line 626at containermakeencrypter array in applicationphp line 674at applicationmakeilluminatecontractsencryptionencrypter in containerphp line 837at containerresolveclassobjectreflectionparameter in containerphp line 800at containergetdependenciesarrayobjectreflectionparameter array in containerphp line 771at containerbuildsahrasalonhttpmiddlewareencryptcookies array in containerphp line 626at containermakesahrasalonhttpmiddlewareencryptcookies array in applicationphp line 674at applicationmakesahrasalonhttpmiddlewareencryptcookies in pipelinephp line 123at pipelineilluminatepipelineclosureobjectrequest in checkformaintenancemodephp line 42at checkformaintenancemodehandleobjectrequest objectclosureat call user func arrayarrayobjectcheckformaintenancemode handle arrayobjectrequest objectclosure in pipelinephp line 124at pipelineilluminatepipelineclosureobjectrequestat call user funcobjectclosure objectrequest in pipelinephp line 103at pipelinethenobjectclosure in kernelphp line 118at kernelsendrequestthroughrouterobjectrequest in kernelphp line 86at kernelhandleobjectrequest in indexphp line 54can anyone help solve this error,['php'] +947098,wcf service stops handling calls for 15 seconds i faced a strange behavior in one of my wcf services this service worked fine for around 15 years but since a few weeks it shows some kind of outages unfortunately i cannot post images cause i am new herethe callssecond drop to 0 although there are still incoming calls the outage is always 15 seconds long after these 15 seconds the queued calls are processed it could not be network related because 90 of all calls come from another wcf service on the same server and no other service 10 in total are affected by this behavior the service itself does continue working like calculating internal stuff doing db updates etc no increase in execution times of the internal work this occurs around 18 25 minutes but the outage is always 15 secondsoswindows server 2012wcf running as windows servicewcf configurationinstancecontextmode instancecontextmodepercallconcurrencymode concurrencymodemultipleusesynchronizationcontext falseincludeexceptiondetailinfaults truebinding webhttpbindingconcurrency throttle settingsmaxconcurrentcalls 384maxconcurrentinstances 2784maxconcurrentsessions 2400i already did some investigatingwcf throttle settingsi made a full dump of the service in the exact time when it happened neither the concurrentcalls nor the concurrentsessions are exhausted the dump did not show any exception which could be cause of the problemmax tcp conenctionmonitoring of active tcp connection is far from it is limitsport trunking in the switchas no calls are coming in even from the local services using localhost i am pretty sure it is not network relatedload problemthis behavior occurs with low load see below and also with high load 5 times as much of incoming calls the frequency of this is not changing based on the load i also tried to reproduce the behavior on my staging system with around 60010 calls second i managed to bring the service into a state where i sent more incoming calls second as the service could handle the outstanding calls increased and at some point the service crashed of course but this behavior never showed upthread pool exhaustionthe problem occurs when the service is running with 50 threads and also with 200 threads although with no more available threads there would be an error message about thati am running out of possible things which would cause such behavior i think it could be the gc blocking threads as the service is using around 10gb in the ram it is a kind of memory cache service or it could be the os windows server 2012or something related to the windows service itselfhas anyone faced something like this on your own or does someone has another idea what could cause that edit now i can post imagesedit gc heap dump thanks to usri see that nearly 50 in total 70 including the associated references are caused by one big dictionary with approx 27 million entries based on memory dump heap i will focus on that to refactor it there are lots of unused items in it maybe this will helpadditionally i will add gcwaitforfullgcapproach method from msdn to see if the gc is running while the service stops handling incoming requestsi will keep you posted when i know moreedit gc stats 14 seconds of the outage includedaclr startup flags concurrent gcatotal cpu time 42662 msecatotal gc cpu time 2748 msecatotal allocs 1524637 mbamsecmb alloc 1802 msecmbatotal gc pause 29772 mseca time paused for garbage collection 194a cpu time spent garbage collecting 64amax gc heap size 116103 mbapeak process working set 14917915 mbapeak virtual memory usage 15326974 mbthat is just 3 seconds of pausing anyway that should not be that high and i am gonna refactor the memory store but it does not explain the 15 seconds at all edit during the weekend i did the followinginstalled latest windows updates last update was 2 month agorestarted the windows serverrefactored the inmem store of the 27 million objects i managed to reduce the used memory from 11gb to 68gb which is quite a lot very old code in there the problem is not reoccurring so far approx 17h running now that leads me to the assumption that the gc caused the pausing of the service or some os related issue was causing that behaviori guess the problem is not solved at all and will reoccur at some point cause the data will increase over time thanks to everyone spend time on this i will continue investigate the dumps and try to find out what happened in detail i will keep you posted,['c#'] +947141,declaration difference and scope in question declaration difference it was asked what the difference is betweenint ifor i0 i100 i some loopandfor int i0 i100 i some loopthe answers are clear the 2nd is c99 and the scope of i is limited to the loop i do not have c99 so i cannot test and hence ask it as a question what would be the resolution in the following caseint i 32for int ii i100 i some loopwould the new i be initialized with the old i or would the old i already be inaccessible becaus a new i has already been declared,['c'] +947162,implicitly convert to reference i havestruct vec m128 m128 inline vec m128 m128 m128m128 so now m128 can implicitly convert to vec but when i use it as invoid dostuffvec v stuff be doing dostuff mm set1 ps10f mm set ps returns m128i get an error sayingcannot convert from m128 to vecso whats the problem and how to fix it,['c++'] +947178,xamarin android player cannot play this video i am using androids videoview to play an embedded video in my app it works fine on my device but i keep getting a cannot play this video message and a black screen in the xamarin android playerthe corresponding error log looks like thisunable to play videomediaplayer error 138videoview error 138i found a few posts regarding this error but none of them helped me solving this issue and i am not able to find a proper description for this status codemy c code looks like thisvideoview new videoview contextbasesetnativecontrol videoviewvideoviewsetonerrorlistener new errorlistener string filename enewelementfilesourcefilename filenametolower substring 0 filenamelastindexof int resourceid contextresourcesgetidentifier filename raw contextpackagenamevar fullpath stringformat androidresource01 contextpackagename resourceidvideoviewsetvideopath fullpathvideoviewrequestfocus videoviewstart,['android'] +947200,javascript enter event does not work on google i am trying to simulate an enter keypress with javascript for automationvar script documentcreateelementscriptscriptsrc scripttype textjavascriptdocumentbodyappendchildscriptvar e jqueryeventkeypressewhich 13 choose the one you wantekeycode 13this is the code used to setup the key event i have tried keydown and keyup as wellthis does not seem to work when searching google if i type some text and trigger the event on the input field nameqtriggere nothing happens i am using google to test simulating a proper enter event i hope to use js to automate skype web clientdoes anyone know if it is possible to simulate an actual enter keypress using javascript i have seen that selenides pressenter works but it uses webdriver so maybe it is not relevanti have also tried native js event triggeringvar thispatchkeyboardevent functiontarget initkeyboradevent args var e documentcreateeventkeyboardevents einitkeyboardeventapplye arrayprototypeslicecallarguments 1 targetthispatcheventethispatchkeyboardeventnameq keypress true true null h 13 sidenote i am aware that query can be submitted by calling submit on the element but that is not what i am after,"['javascript', 'jquery']" +947204,why is a generic repository considered an antipattern it seems to me that a lot of specialised repository classes share similar characteristics and it would make sense to have these classes implement an interface that outlines these characteristics creating a generic repositoryto illustrate my point say we have this codepublic class ientity public int id public interface irepositoryt where t ientity ienumerablet list get void addt entity void deletet entity void updatet entity t findbyidint idtableauthorpublic partial class author ientity public int id get set required public string authorname get set and then we go onto implement these interfaces to create our specific repositoriespublic class authorrepository irepositoryauthor model1 authorcontext public authorrepository authorcontext new model1 public ienumerableauthor list get return authorcontextauthors public void addauthor entity authorcontextauthorsaddentity authorcontextsavechanges public void deleteauthor entity authorcontextauthorsremoveentity authorcontextsavechanges public void updateauthor entity authorcontextentryentitystate systemdataentityentitystatemodified authorcontextsavechanges public author findbyidint id var result from r in authorcontextauthors where rid id select rfirstordefault return result before i implemented this i went out a did a bit of research about whether it was a good idea or not and all the information i could find we statements calling it an antipattern but without explaining whywhy is a generic repository considered an antipattern,['c#'] +947225,continue when one future task has expected result i have 3 futuretaskt objects i want that they are processed asynchronously however as soon as one of the futuretasks get methods does not return null i want to continue ie my method wrapper returns and does not wait until the other two futuretasks are processedi thought about something like private file wrapperfinal file file executorservice executors executorsnewcachedthreadpool file returnfile futuretaskfile normal futuretaskfile medium futuretaskfile huge executorsexecutenormal executorsexecutemedium executorsexecutehuge try ifreturnfilenormalget null returnfilemediumget null returnfilehugeget null return returnfile catchexecutionexception interruptedexception e i am not sure how to capture the exceptions thrown by the get in a proper way because i assume they will be thrown since i just return without waiting for the other two tasks to be completed moreover i have doubts that the code will work like intended i feel that i am close to the solution but missing something,['java'] +947313,java while loop dramatically slows down over time after a large number of iterations my program reads a text file line by line in a while loop it then processes each line and extracts some information to be written in the output everything it does inside the while loop is o1 except two arraylist indexof method calls which i suppose are on the program runs at a reasonable pace 1m lines per 100 seconds in the beginning but over time it slows down dramatically i have 70 m lines in the input file so the loop iterates 70 million times in theory this should take about 2 hours but in practice it takes 13 hours where is the problemhere is the code snippetbufferedreader corpus new bufferedreader new inputstreamreader new fileinputstreammycorpustxtutf8writer outputfile new bufferedwriternew outputstreamwriter new fileoutputstreamoutputtxt utf8liststring words new arraylistwords is being updated with relevant values here linkedhashmapstringinteger dic new linkedhashmapdic is being updated with relevant keyvalue pairs here string line while line corpusreadline null string parts linesplit if diccontainskeyparts0 diccontainskeyparts1 int firstindexplusone wordsindexofparts0 1 int secondindexplusone wordsindexofparts1 1 outputfilewritefirstindexplusone secondindexplusone parts2n else notfound outputfilewritenulln outputfileclose,['java'] +947323,instabug for android build warning we have a gradle project that contains 4 modules 1 library module and 3 android apps to build our apps we use circleci we have also thisabled predexing for the circleci builds following this guideeverything was great until i added instabug to one of our projects we have been reaching the circleci 4gb limit ever since on top of that the project that has instabug as a dependency will start the predex gradle task no matter what to start a new build we use the following command gradlew assembledebug ppredexenablefalse the project that uses instabug gets some warnings during build time like this ignoring innerclasses attribute for an anonymous inner class cominstabuglibraryb that does not come with an associated enclosingmethod attribute this class was probably produced by a compiler that did not target the modern class file format the recommended solution is to recompile the class from source using an uptodate compiler and without specifying any target type options the consequence of ignoring this warning is that reflective operations on this class will incorrectly indicate that it is not an inner classi assume that we are reaching the 4 gb limit due to the predex task that is started for the instabug projectdoes anyone has any idea on whats going onedit gradle filesroot buildgradle toplevel build file where you can add configuration options common to all subprojectsmodulesbuildscript repositories jcenter dependencies classpath comandroidtoolsbuildgradle123 classpath dehannesstrussgodot02 classpath comgithubbenmanesgradleversionsplugin0113 note do not place your application dependencies here they belong in the individual module buildgradle files apply plugin dehannesstrussgodotapply plugin comgithubbenmanesversionsapply from dependenciesgradledef ciserver cidef executingonci trueequalssystemgetenvciserverext predexenable property will come from the command line when circleci is building the project if projecthaspropertypredexenable projectextpredexlibs projectpropertiespredexenableequalstrue else projectextpredexlibs true pre dexing should be true by default buildtime new dateformatymmddthhmmz timezonegettimezoneutc developmentflavor applicationid projectextappidname versionname projectextvernamename minsdkversion 15 buildconfigfield string api type name resvalue string tray authority applicationidtray defaultlibraryflavorconfig targetsdkversion 22 versioncode projectextvercode versionname projectextvername multidexenabled true buildconfigfield string git sha projectextgitsha buildconfigfield string build time buildtime defaultflavorconfig defaultlibraryflavorconfig applicationid projectextappid resvalue string tray authority applicationidtray defaultandroidconfig compilesdkversion 22 buildtoolsversion 2201 compileoptions sourcecompatibility javaversionversion 1 7 targetcompatibility javaversionversion 1 7 dexoptions javamaxheapsize executingonci 2048m 4g jumbomode true packagingoptions exclude metainfdependenciestxt exclude metainflicensetxt exclude metainfnoticetxt exclude metainfnotice exclude metainflicense exclude metainfdependencies exclude metainfnoticetxt exclude metainflicensetxt exclude metainfdependenciestxt exclude metainflgpl21 exclude metainfservicesjavaxannotationprocessingprocessor lintoptions checkreleasebuilds false or if you prefer you can continue to check for errors in release builds but continue the build even when errors are found abortonerror false subprojects repositories maven url jcenter projectextgitsha git revparse short headexecute projectprojectdirtexttrim projectpluginswhenpluginadded plugin if comandroidbuildgradleapluginequalspluginclassname projectandroiddexoptionspredexlibraries rootprojectextpredexlibs else if comandroidbuildgradlelibrarypluginequalspluginclassname projectandroiddexoptionspredexlibraries rootprojectextpredexlibs dependenciesgradleext kiosk dependencies compile projectcommon compile librariesmultidex compile librariesviewpagerindicator compile librariesrecyclerview compile librariesvolley compile librariesinstabug compile librariesmixpanel compile librariesloadtoast compilelibrariescrashlytics transitive true compile librariesdagger apt librariesdaggercompiler provided librariesjavaxannotations kiosk module buildgradlebuildscript repositories maven url jcenter dependencies classpath comneenbedanktgradlepluginsandroidapt16 classpath iofabrictoolsgradle1 repositories maven url maven url maven url apply plugin comandroidapplicationapply plugin comneenbedanktandroidaptapply plugin iofabric manifest version informationdef versionmajor 1def versionminor 0def versionpatch 0def versionbuild 0 bump for dogfood builds public betas etcextvercode versionmajor 10 versionminor 10 versionpatch 100 versionbuildextvername versionmajorversionminorversionpatchextappid caresmartandroidkioskandroid defaultandroidconfig defaultconfig defaultflavorconfig minsdkversion 21 buildconfigfield string app name androidkiosk productflavors realproduction buildconfigfield string api type prod dev developmentflavor dependencies kioskdependencies,['android'] +947360,scikitlearn train test split with indices how do i get the original indices of the data when using train test splitwhat i have is the followingfrom sklearncross validation import train test splitimport numpy as npdata npreshapenprandn20102 10 training exampleslabels nprandomrandint2 size10 10 labelsx1 x2 y1 y2 train test splitdata labels size02but this does not give the indices of the original data one workaround is to add indices to data eg data i d for i d in enumeratedata and then pass them inside train test split and then expand again is there any cleaner solution,['python'] +947399,find the year with the most number of people alive in python given a list of people with their birth and end years all between 1900 and 20 find the year with the most number of people alivehere is my somewhat bruteforce solutiondef most populatedpopulation singletrue years dict for person in population for year in xrangeperson0 person1 if year in years yearsyear 1 else yearsyear 0 return maxyears keyyearsget if single else key for key val in yearsiteritems if val maxyearsvaluesprint most populated1920 1939 1911 1944 1920 1955 1938 1939print most populated1920 1939 1911 1944 1920 1955 1938 1939 1937 1940 falsei am trying to find a more efficient way to solve this problem in python both readability and efficiency counts moreover for some reason my code would not print 1938 1939 while it shouldupdateinput is a list of tuples where first element of a tuple is a year when person was born and second element of a tuple is the year of deathupdate 2end year 2nd part of tuple counts as well as a year of the person being alive so if the person dies in sept 1939 we do not care about the month he is actually alive in 1939 at least part of it that should fix the 1939 missing in resultsbest solutionwhile readability counts in favor of joranbeasley for bigger input most efficient algorithm was provided by njzk2 thanks hannesovran for providing analysis in ipython notebook on gist,['python'] +947443,how to assert map contains map with entry i have a unit test that needs to check for a nested map value i can get my assertion to work by pulling out the entry and matching the underlying map but i was looking for a clear way to show what the assertion is doing here is a very simplified testimport static orghamcrestmatcherassertassertthatimport static orghamcrestmatchershasentryimport javautilhashmapimport javautilmapimport orgjunittestpublic class mapcontainsmaptest test public void testmaphasmap mapstring object outermap new hashmapstring object mapstring object nestedmap new hashmapstring object nestedmapputfoo bar outermapputnested nestedmap works but murky assertthatmapstring object outermapgetnested hasentryfoo bar fails but clear assertthatoutermap hasentrynested hasentryfoo bar it seems the problem is the outer map is being compared using hasentryk key v value while what i want to use is hasentrymatcher super k keymatcher matcher super v valuematcher i am not sure how to coerce the assertion to use the second formthanks in advance,['java'] +947450,mobile app avoiding or securing cors i am wondering if there is an industry standard for better securing ajax calls on mobilemy mobile app consists of my websites html js css files but installs them locally on the mobile device for performance the mobile devices local indexhtml then calls my web server for data tomcat in this casethe only way i have found this to work is to enable cors in my servletresponsesetcontenttypetexthtmlresponseaddheaderaccesscontrolalloworigin responseaddheaderaccesscontrolallowmethods get put post options deleteresponseaddheaderaccesscontrolallowheaders contenttyperesponseaddheaderaccesscontrolmaxage 86400but quite honestly i dont like that for a variety of reasons but mainly anything can now query my webserver from any domain and get a responsehow can i achieve the same ajax call to my webserver from a mobile device using cors but in a more secure manner so that only my app is allowed access or is cors incorrect altogether in this case of mobile and there is a more standarddesirable solution,['java'] +947551,laravel 5 controller sending json integer as string on my development server the json response from the laravel 5 controller shows the data in the correct typesegimdb rating 76imdb votes 6271but on the production server the json response is sent back as stringsimdb rating 760imdb votes 6271both development and production have the same version of php installed 561any ideas on what may be causing this behaviour,['php'] +947571,firebase reauthentication required we are working on an ios app that is using google to authenticate with firebase according to firebase says that auth tokens expire every 24 hourswe are wondering if the following scenario is something we need to consideruser authenticates with google and firebaseour app gets a firebase auth token that expires in 24 hoursuser closes our ios app1 minute before the firebase auth token expires the user reopens the appa minute later we make a request to firebase the auth token has expiredit seems we have to reauthenticate with firebase by observing authentication changes per but will we have to reissue the same request to firebase from 5 abovealso it seems we could reauthenticate in the cancelblockref observeeventtypefeventtypevalue withblockfdatasnapshot snapshot nslog snapshotvalue withcancelblocknserror error nslog errordescription reauthenticate and then reissue requestthis would not be ideal because we would have to write this code everywhere that we make a requestwhat are the best practices to deal with this scenariodoes firebase automatically refresh the auth token when it is close to expiry,['ios'] +947603,uicollectionviewcell expandcollapse with intrinsic size i have a collection view with a custom flow layout and many different cells of different height the width of the collection view changes on device rotation so the width of cells must change accordingly for this to work i implemented asizeforitematindexa method and return different sizes depending on current interface orientationmost of the cells do not change their height however there is one cell that i want to expand and collapse whenever the user taps on it you can assume that the cell only has one uilabel with one or more lines of text when the cell appear for the first time the number of lines is set to 1 and when user taps on the cell the number of lines is set to 0 and here the cell should use the intrinsic size of the label to change itas height automatically how can i achieve this effecthere is an example of what it should look like,['ios'] +947765,how are class attributesfields stored i know that an instance of this c class class a char c int i short ss would look kind of like this in memory c iss this 42 letter annotation has no sense but i think that my point is clear1 byte for char 3 bytes of padding 4 bytes of int 2 bytes for the short and 2 bytes of tail padding platform dependant but it would not change the logicfrom c standards compilers wouldnt change the order of the fields in my examplenonstatic data members of a nonunion class with the same access control clause 11 are allocated so that later members have higher addresses within a class object the order of allocation of nonstatic data members with different access control is unspecified clause 11 implementation alignment requirements might cause two adjacent members not to be allocated immediately after each other so might requirements for space for managing virtual functions 103 and virtual base classes 101so i would like to know if it is the same for java classes can the compiler change the order to reduce the padding,"['java', 'c++']" +947830,xlib and firefox behavior i am trying to create a small window manager just for fun but i am having problems in handling windows created by firefox only with that application other apps works fine the problem is after i launch firefox and add my decoration it seems to work fine but if for example i try to click on the menu button the subwindow does not appear what seems to happen is that after the click a clientmessage event is fired with the following valuesdata nulldata net wm state hiddendata nulldata nulldata nullnow the problem is that i do not know how to show the window which window i tried with xraisewindowxmapwindowi tried to get the transient window and show itbut without success what i do not understand is that if this client message is generated by the menu subwindow or not how should i show a window that is in net wm state hiddenanother strange problem is that after receiving the clientmessage i always receive 2 unmapnotify events i also have another question if i want to show the file edit mena1 in firefox it appears if i remember correctly when you press the alt button maybe firefox creates a tree of windowsthis is the loop where i handle the events while1 xnexteventthisplay local event switchlocal eventtype case configurenotify configure notify handlerlocal event thisplay break case motionnotify motion handlerlocal event thisplay break case createnotify cur win local eventxcreatewindowwindow char window name xfetchnamethisplay cur win window name printfwindow name sn window name ifwindow namenull ifstrcmpwindow name parent printfadding bordersn xsetwindowborderwidththisplay cur win border width xfreewindow name break case mapnotify map notify handlerlocal eventthisplay infos break case unmapnotify printfunmapnotifyn break case destroynotify printfdestroy eventn destroy notify handlerlocal eventthisplay break case buttonpress printfevent button pressedn button handlerlocal event thisplay infos break case keypress printfkeyboard key pressedn keyboard handlerlocal event thisplay break case clientmessage printfclientmessagen printftmessage sn xgetatomnamethisplaylocal eventxclientmessage type printftformat dn local eventxclientformat atom atoms atom local eventxclientdatal int i 0 fori0 i5 i printfttdata d sn i xgetatomnamethisplay atomsi int nchild window child windows window parent window window root window xquerytreethisplay local eventxclientwindow root window parent window child windows nchild printftnumber of childs dn nchild break now in the clientmessage actually i am just trying to see collect some information to understand what is happening and what i can see from the code above is that the window that raised the event contains one child again is that the menu or notthe code for the mapnotify event where i add the decoration is the following void map notify handlerxevent local event thisplay thisplay screeninfos infos printfmap notifyn xwindowattributes win attr char child name xgetwindowattributesthisplay local eventxmapwindow win attr xfetchnamethisplay local eventxmapwindow child name printftattributes w d h d name s id lun win attrwidth win attrheight child name local eventxmapwindow window trans none xgettransientforhintthisplay local eventxmapwindow trans printftis transient ldn trans ifchild namenull ifstrcmpchild name parent local eventxmapoverride redirect false window new win draw window with namethisplay rootwindowthisplay infosscreen num parent infosscreen num win attrx win attry win attrwidth win attrheightdecoration height 0 blackpixelthisplay infosscreen num xmapwindowthisplay new win xreparentwindowthisplaylocal eventxmapwindow new win0 decoration height set window itemlocal eventxmapwindow new win xselectinputthisplay local eventxmapwindow structurenotifymask printftparent window id lun new win put textthisplay new win child name 9x15 10 10 blackpixelthisplayinfosscreen num whitepixelthisplay infosscreen num xfreechild namenow can someone help me with these problems unfortunately i already googled many times but without success to sum up my issues are two 1 how to show subwindows from firefox2 how to show the file edit menu updatei noticed something strange testing firefox with xev to understand what events are fired in order to show an application i saw that using firefox in unity and using firefox in another window manger the events fired are completely different in unity i have only clientmessageunmapnotifyinstead using firefox for example with xfce4 the xevents generated are morevisiblitynotify more than oneexpose event more than onebut if i try to enable visibilitychangemask in my wm i receive the following eventsconfigurenotifyclientmessagemapnotify2 unmapnotifyupdate 2i tried to read the xwmhints properties in the clientmessage window probably the mena1 window and the values are for the flags 67 inputhint statehint windowgrouphintfor the initial state normalstateupdate 3i tried to look how another window manager works and i was looking at the source code of calmwm what is my understanding is that when the clientmessage event arrives with a net wm state message it updates these properties and in the case of net wm state hidden it clears this property and the result will be that the property will be deleted so i tried to update my code to delete that property but it is still not working anyway the relevant updated code in client message handler now looks like thisatom atoms atom local eventxclientdatalint i 0fori0 i5 i printfttdata d sn i xgetatomnamethisplay atomsi ifi1 printft deleting property net wm state hidden n xdeletepropertythisplay cur window atomsi it is only a test and i am sure that i1 in my case is the net wm state hidden property here a link to calmwm source code so i am still stuck at that point update 4really i do not know if it helps but i tried to read the window attributes in the mapnotify event and the window map state is isviewable 2update 5i found a similar problem here in so using xlib with python xlib python cannot map firefox menusthe solution suggests to use xsetinputfocus i tried that on my xmapnotify handler xsetinputfocusthisplay local eventxmapwindow reverttoparent currenttimebut it still does not help the firefox menu still does not appearand i have the same problem with rightclickupdate 6playing with xconfigurenotify event and unmap event i found that thexconfigure request has 2 window fields window and above and when the the xconfigurerequestwindow value is the same of xunmapwindow valueand also that the xconfigurerequestabove is always changing but xconfigurerequestwindow is always the same in all eventsit seems that the xconfigurerequestabove is related to what menu i am trying to open for example if rightclick on a page i get an id always the same for every subsequent clickif i rightclik on a tab the above value is another oneand the same happen if i leftclick the firefox main menustill do not know if that helpsreally do not know anyone got any idea,['c'] +947831,stop propagation does not work i have the below jquery eventhandler i want to stop all navigations on a web pagedocumentclickfunctionevent eventstoppropagation eventpreventdefault eventcancelbubble true eventstopimmediatepropagation documentcssbordercolor documentcssbackgroundcolor eventtargetcssbordercoloryellow eventtargetcssbackgroundcolor6bff70 return false when i use this on facebook login page it stops all navigations but in google home page i am feeling lucky button still navigates to next page how do i avoid iti am using javafx browser by the way it is similar to safari browser,"['javascript', 'jquery']" +947837,which scenes keyword volatile is needed to declare in objectivec as i know volatile is usually used to prevent unexpected compile optimization during some hardware operations but which scenes volatile should be declared in property definition puzzles me please give some representative examples thx,"['ios', 'objective-c']" +947909,strange error when execute httpclient i have created an http request in my project i sat it but did not work so simplified that part to test it this is ithttpclient cl new defaulthttpclient try httpresponse httpresponse clexecutenew httpget systemoutprintlnhttpresponsegetentitygetcontentlength catch exception e systemoutprintlndid not work systemoutprintlnegetmessage but when i run it i get these0721 155736203 2685126851comakgradevupbman wi1 unable to open systemframeworkqcomfmradiojar no such file or directory0721 155736203 2685126851comakgradevupbman warti1 failed to open zip archive systemframeworkqcomfmradiojar io errorand of course a did not work and a null for prints i appreciate your tips tnx,"['java', 'android']" +947966,why there is no addrangeremoverange method in idbset interface in entity 6 in entity framework 6 addrange method has been introduced it is great for big inserts because dbsetadd method always trigger detectchanges which extremely slows down the process i have just wanted to use some existing code based on idbset interface when realized that it does not have addrange method it exists only in dbset classi googled a little bit and found this thiscussion but there is no clear conclusion about the reason why actually addrange method does not exist in idbset interfaceis it a bug or is there some good reason for it not to be there any ideasupdatehere microsoft gave me an answerthis is by design the interface approach was not a good one for dbset because adding members breaks any existing applications that implement the interfacegiven we want to be able to add members to dbset we swapped to a base class approach where dbset is a base class that you can directly mock or inherithere are some links that show how to use dbset rather than idbset,['c#'] +948016,visual studio 2015 c 6 roslyn cannot compile xml comments in pcl project i just installed the fresh released community edition of visual studio 2015 rtm and i am trying to get my open source project working under vs2015 and c 60 some of my cs are shared across projects this way i am able to build both a pcl version with limited functionality and a full version of the core libraryfor some reason however some code files build properly in the full project but fail when built in the pcl project where everything compiles under c 5 and visual studio 2013 the compiler seems to be unable to resolve a cref in an xml comment when building the pcl version here is a simplified code example that fails on my machine summarysummarypublic class a compile error on next line summarysee crefytypesummary public void x summarysummary param namexparam public void ytype x summarysummary param nameiparam public void yint i the compile error i am getting iscs1580 invalid type for parameter type in xml comment cref attribute ytype simpleinjectorpclweird thing is though that the intellisense support in the xml comments wow we have intellisense in xml comments now actually works and the method ytype is selectable through the drop down list but after selecting this a compile error is generated in pcl onlymy question of course is how to fix this is this a common problem could projects configuration have anything to do with this is this a known bug,['c#'] +948017,mod closest to zero i have an angle and i need to return a representative angle in the range 180180i have written a function to do this but it seems such a simple process i was wondering if there was an operator or function that already did thisint funcint angle angle 360 ifangle 180 angle 360 else ifangle 180 angle 360 return anglei have made a live example for testing expected functionality,"['c++', 'c']" +948237,how to record screen with android studio i connect my phone to android studio and code i want to record my phone screen i saw this but that button is thisabled in my android studio i can capture screens but cannot record can someone help me with thisupdatethis is how it is there in my android studio the button is thisabled,['android'] +948266,accessing nested urls when using for loop to generate the list items on feed tab notei am using ionic framework and angularshort explanationi have a json file with information each object from the file has an id category title etc using a for loop i am filling the feed tab with every object as an item like a quick post with an option to click to read more the for loop is used because of an infinitescrollingproblemnow when i am using the infinitescrolling and the for loop everything messed up and the link to the nested page with all the info about every object from the json file does not work in order to take the full info about an item i am using it is idgoali want to be able when on the feed tab to click on an item and see the nested page with all the info about it edithere is a link demo in the plunkeri will post the main code here in the post too in case it catches someones eye appjsvar starter angularmodulestarter ionicstarterrunfunctionionicplatform ionicplatformreadyfunction ifwindowcordova windowcordovapluginskeyboard cordovapluginskeyboardhidekeyboardaccessorybartrue ifwindowstatusbar statusbarstyledefault starterconfigfunctionstateprovider urlrouterprovider stateprovider statetabs url tab abstract true templateurl templatestabshtml statetabshome url home views hometab templateurl templateshomehtml statetabslist url list views listtab templateurl templateslisthtml controller listcontroller statetabsdetail url listaid views listtab templateurl templatesdetailhtml controller listcontroller urlrouterproviderotherwisetabhomestartercontrollerlistcontroller scope http state functionscope http state scopeposts var startingpoint 0 var limit 1 scopeloadfunctionstartingpoint limit httpgetjsdatajsonsuccessfunctiondata forvar i startingpoint ilimit i1 scopepostspushdatapostsi scopewhichpoststateparamsaid finallyfunction scopebroadcastscrollrefreshcomplete scopebroadcastscrollinfinitescrollcomplete scopeget more function scopeloadstartingpoint limit limit2 startingpoint2 scopenomore function return scopepostslength 50 false true the page showing all the info ionheaderbar classbarpositive h2 classtitleh2ionheaderbarionview viewtitlefull article ioncontent ionlist classlistinset ionitem classitemtextwrap ngrepeatpost in posts filter idwhichpost true div classtextwrap h2 classarticleauth posttitle h2 div p classarticledateby postauthor on postdate about span classcategory postcategory spanp div div img classimagephoto ngsrcpostphoto alt p classtextwrap postdescription p ionitemionlistdatajson exampleid1 categorylife titlelorem ipsum is simply dummy text author stoyangenchev date november 05 1955 photo imgtest1jpg description lorem ipsum is simply dummy text of the printing and typesetting industry lorem ipsum has been the industrys standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book it has survived not only five centuries but also the leap into electronic typesetting remaining essentially unchanged it was popularised in the 1960s with the release of letraset sheets containing lorem ipsum passages and more recently with desktop publishing software like aldus pagemaker including versions of lorem ipsummain pageionview viewtitlenewest postsdiv classbar barsubheader iteminputinset barlight label classiteminputwrapper i classicon ionsearch placeholdericoni input typesearch ngmodelquery placeholdersearch for post labeldivioncontent classhassubheader ionrefresher onrefreshload ionrefresher ionlist ionitem ngrepeatpost in posts track by postid filter query classitemthumbnailleft itemtextwrap hreftablistpostid img ngsrcpostphoto div p clashorttext titlearticle posttitle limitto 33 posttitlelength 33 hellip p img classarticleauthimg srcimgstoyangenchevjpg altstoyangenchevauthor div div classarticleinfo h2postauthorh2 h4postdateh4 h4 classcategorypostcategoryh4 div div classcleardiv p clashorttext postdescription limitto 200 postdescriptionlength 200 hellip p ionitem ionlist ioninfinitescroll ngifnomore oninfiniteget more thistance15 ioninfinitescrollioncontentionview,"['javascript', 'jquery']" +948277,why is python 3 is considerably slower than python 2 i have been trying to understand why python 3 is actually taking much time compared with python 2 in certain situations below are few cases i have verified from python 34 to python 27note i have gone through some of the questions like why is there no xrange function in python3 and loop in python3 much slower than python2 and same code slower in python3 as compared to python2 but i feel that i did not get the actual reason behind this issuei have tried this piece of code to show how it is making differencemax num 3107 this is to make compatible with py34try xrangeexcept xrange rangedef foo i max num while i 0 i 1def foo for for i in xrangemax num passwhen i have tried running this programme with py34 and py27 i have got below resultsnote these stats came through a 64 bit machine with 26ghz processor and calculated the time using timetime in single loopoutput python 342639208316802978509724123477935791output python 27151315212250475143909454i really do not think that there has been changes applied to while or xrange from 27 to 34 i know range has been started acting as to xrange in py34 but as documentation saysrange now behaves like xrange used to behave except it works with values of arbitrary size the latter no longer existsthis means change from xrange to range is very much equal to a name change but working with arbitrary valuesi have verified thisassembled byte code as wellbelow is the thisassembled byte code for function foopython 34 13 0 load global 0 max num 3 store fast 0 i 14 6 setup loop 26 to 35 9 load fast 0 i 12 load const 1 0 15 compare op 4 18 pop jump if false 34 15 21 load fast 0 i 24 load const 2 1 27 inplace subtract 28 store fast 0 i 31 jump absolute 9 34 pop block 35 load const 0 none 38 return valuepython 27 13 0 load global 0 max num 3 store fast 0 i 14 6 setup loop 26 to 35 9 load fast 0 i 12 load const 1 0 15 compare op 4 18 pop jump if false 34 15 21 load fast 0 i 24 load const 2 1 27 inplace subtract 28 store fast 0 i 31 jump absolute 9 34 pop block 35 load const 0 none 38 return value and below is the thisassembled byte code for function foo forpython 34 19 0 setup loop 20 to 23 3 load global 0 xrange 6 load global 1 max num 9 call function 1 1 positional 0 keyword pair 12 get iter 13 for iter 6 to 22 16 store fast 0 i 20 19 jump absolute 13 22 pop block 23 load const 0 none 26 return valuepython 27 19 0 setup loop 20 to 23 3 load global 0 xrange 6 load global 1 max num 9 call function 1 12 get iter 13 for iter 6 to 22 16 store fast 0 i 20 19 jump absolute 13 22 pop block 23 load const 0 none 26 return value if we compare both the byte codes they have produced the same thisassembled byte codenow i am wondering what change from 27 to 34 is really causing this huge change in execution time in the given piece of code,['python'] +948288,visual studio 2015 break on unhandled exceptions not working visual studio used to have a specific checkbox to break on unhandled exception in 2015 this has been removed or moved somewhere i cannot find it so now my converted projects no longer break if i fail to provide a userlevel exception handler i do not want to break on all thrown exceptions because i handle specific ones just where i fail to provide a specific handler right now my code simply exits the current procedure and continues execution at the next call stack location not goodanyone know how to get this back in visual studio 2015 i just upgraded to the community edition yesterdaycheers ted,['c#'] +948418,infinite panel in wpf for an internal tool i need to create something akin to blenders node editor see image below or ue4s blueprint editor with wpfthe backend and individual blocks are not a problem but i am not sure how to go about an arbitrary sized and expanding canvas i thought about using a canvas inside a scrollviewer but i think that would be difficult to scroll left ie if the user had to add nodes to the left of what the scrollviewer thinks is the edge i am relatively new to wpf so could someone point me in the right direction,['c#'] +948495,android how to send and receive image and location using map in group chat using xmppsmack i developing group chat app using androidxmpp in that i do not know how to send and recive picsimage or location using mapso any one one can please give me way to do thesecurrently i got text message and add to list view like following message msg new messageto messagetypegroupchatmsgsetbodytextif constantsconnection null try constantsconnectionsendpacketmsg logdsend to room name to logdstore store data to db dbadapteradduserdatanew userdatatext 1 beam id catch exception e logdo msg exception egetmessage messagesaddtext runonuithreadnew runnable public void run set to listview setmychatadapter and receive using stanzatypefilter so how for image and location sharing i try following code for image using filetransfermanager using smackextensions413sourcesjar private void sendimage filetransfermanager mgnew filetransfermanagerconstantsconnection outgoingfiletransfer transfer mgcreateoutgoingfiletransferbeam idconstantsconference name constantsresources file file new fileselectedimagepath try transfersendfilefile test file catch exception e eprintstacktrace whiletransferisdone iftransfergetstatusequalsfiletransferstatuserror systemoutprintlnerror transfergeterror else if transfergetstatusequalsfiletransferstatuscancelled transfergetstatusequalsfiletransferstatusrefused systemoutprintlncancelled transfergeterror try threadsleep10l catch interruptedexception e eprintstacktrace iftransfergetstatusequalsfiletransferstatusrefused transfergetstatusequalsfiletransferstatuserror transfergetstatusequalsfiletransferstatuscancelled systemoutprintlnrefused cancelled error transfergeterror else systemoutprintlnsuccess but when i access that file using following filetransfermanager mgnew filetransfermanagerconstantsconnectionit give me error has a private access of so i find constructor of that file is private this is jar file so i can not change it to public so how can i access that fileclass into my class so how can i sharesendreceive image and location message in chat please help me as soon as possiblethanks in advance,['android'] +948523,how to get wifi ssid in ios9 after captivenetwork is depracted and calls for wifi name are already blocked until today i used the captivenetwork interface to thisplay the name of the currently connected wifithe ios 9 prerelease reference already stated that the captivenetwork methods are depracted now but they still worked at the beginningwith the newest version apple seems to have blocked this calls already maybe due to privacy concernsis there any other way to get the name of the current wifithis is how i obtained the ssid until today but you only get nil nowimport systemconfigurationcaptivenetworkhnsstring wifiname nil nsarray interfacenames bridge transfer idcncopysupportedinterfaces for nsstring name in interfacenames nsdictionary info bridge transfer idcncopycurrentnetworkinfo bridge cfstringrefname if infossid wifiname infossid,"['ios', 'objective-c']" +948543,what is mounting in react js i am hearing this term this term mount too many times while learning reactjs and there seem to be lifecycle methods and errors while regarding to this term what exactly does react mean by mountingexamples componentdidmount and componentwillmount,['javascript'] +948621,adding a tooltip to cmenu items a while ago i have tried to add a tooltip for testing purposes on a cmenu item now i would need it and i am facing the same issue againthis question and answersmfc how to add tooltip in cmenu itemsdoes not help me at all as this newline magic is simply not workingalso it seems like i am not the only one having problems with itmfc cmenu tooltip not being thisplayedvoid ctextlistctrlcreatemenuvoid m menucreatemenu cmenu submenu submenucreatepopupmenu submenuappendmenuwmf string idc resend popup lresendnshow me the tooltip other menu items m menuappendmenuwmf popup reinterpret castuint ptrsubmenum hmenu l submenudetachthe result is thishowever increasing the letters of the text results in a bigger popup menu not a menu tooltipi have seen the other links in this answer and checked them and the projects but these are not what i wantdoes someone know what i did wrong or is there another solutionsource which could be helpful edit as i have mentioned before in a comment here is a sample solution with minimum requirements to reproduce the problem see cmenulistctrlcpp100tested with vs2010 vs2015 same result,['c++'] +948674,jackson not populating all properties i am working on a simple example using jackson library to convert a json string back to java object but i see only few properties are being set on my java object instead of all propertieshere is my codeimport javaiobufferedreaderimport javaiofilenotfoundexceptionimport javaiofilereaderimport javaioioexceptionimport orgcodehausjacksonmapobjectmapperpublic class jsontest public static void mainstring args throws filenotfoundexception ioexception stringbuffer buffer new stringbuffer string data bufferedreader reader null try reader new bufferedreadernew filereaderpathtosamplejson while data readerreadline null bufferappenddata finally if reader null readerclose systemoutprintlnbuffertostring objectmapper mapper new objectmapper sample obj mapperreadvaluebuffertostring sampleclass systemoutprintlnobj the samplejava program looks like thisimport orgcodehausjacksonannotatejsonignorepropertiesimport comfasterxmljacksonannotationjsonpropertyjsonignorepropertiesignoreunknown truepublic class sample jsonpropertyprop 1 private string prop1 private string prop2 jsonpropertyprop 3 private string prop3 private string prop4 setters getters for the properties override public string tostring return sample prop1 prop1 prop2 prop2 prop3 prop3 prop4 prop4 input json string in my file is prop 1 1 prop2 2 prop 3 3 prop4 4the output of this program is sample prop1null prop22 prop3null prop44as per my program the prop1 and prop3 should not be null i am not clear where i made mistakeupdateif i remove the jsonproperty annotation then i am getting the exception as exception in thread main orgcodehausjacksonmapexcunrecognizedpropertyexception unrecognized field prop 1 class sample not marked as ignorablethis is my pomxml file dependenciesdependency groupidcomfasterxmljacksoncoregroupid artifactidjacksoncoreartifactid version260versiondependencydependency groupidcomfasterxmljacksoncoregroupid artifactidjacksonannotationsartifactid version260versiondependencydependency groupidorgcodehausjacksongroupid artifactidjacksonmapperaslartifactid version1913versiondependency,['java'] +948679,how to render raw html code in phoenix framework i am storing raw html from a contenteditable tag in my rethinkdb databasenow i want to thisplay the content after retrieving ithtmleexdiv idcontenteditabletext for contenttext contenttext contenttextdata do div contenttext div end divi can sucessfully retrieve it but it is thisplaying the raw html itself,['html'] +948864,force locale for android flavor with resconfig i am trying to use the resconfig and resconfigs from the android build systemandroid studio version 122 gradle build version 123osx 10103i was having problem with these 2 options with my project so i started a new blank project with android studio i attached my buildgradle where i only added resconfigs en fr under android defaultconfig resconfigs en fr and defined 2 basic flavorsproductflavors fr resconfig fr en resconfig en i then created a 2 stringsxml files and translated the hello world default labelsrcmainresvaluesstringsxml default srcmainresvaluesenstringsxml srcmainresvaluesfrstringsxml with this i would expect to see only 3 values folders in myapplicationappbuildsintermediatesresendebug since i defined in the resconfigs to only use en and fr and filter anything elsevalues valuesen valuesfralthough all languages values folder are still in there so the resconfigs is not filtering anything apparentlyi would also expect to see the label hello world from valuesen when running endebug flavor variant since i specified that the flavor en would use resconfig en although when i run the test app i see the label from valuesfrstringsxml instead of valuesenstringsxml since the language on the tablet is configured as french canadaam i misunderstanding the purpose behind resconfig if so how am i supposed to force a flavor to only run in only language and not be dependant on the os locale setting this solution must be compatible with flavordimensions too since i use them in the real app i am trying to configurenote i also filed a bug since i think there really is a problem with this resconfig behavior thanks,['android'] +948865,print range images get by query in mysql aspnet i require to print a range of images that bring in a query the range can be very large but when printing mean to choose whether you want to print a certain range by nose images if this has to do with javascript or with asp net button nameprintbutton idprintbutton typebutton classbtn btndefault onclick printdivprintablearea runatserver span classglyphicon glyphiconprintspan button div div div div classpanelbody div classpanzoom div idprintablearea img srcimgdescargajpg altvisualizacia3n del original de la forma migratoria classimgresponsive runatserver div div div div section div divdivscript typetextjavascript function printdivdivname var printcontents documentgetelementbyiddivnameinnerhtml var originalcontents documentbodyinnerhtml documentbodyinnerhtml printcontents windowprint documentbodyinnerhtml originalcontents windowonfocus function windowclose var section sectionfirst sectionfindpanzoompanzoom zoomin sectionfindzoomin zoomout sectionfindzoomout zoomrange sectionfindzoomrange reset sectionfindreset scriptas you can see only the image that is inside the div is printed what i try to do is that when you send print ask if i want to print all that were obtained through a query that rank to rank or pagesin this image show the resultsthe image show in other paneland the user can print this imagebut i want that the user can choose to print a range of images that were found with the inquiry ie the results,"['javascript', 'mysql', 'asp.net']" +949022,how can i remove all nil elements in a swift array basic way does not workfor index in 0 listcount if listindex nil listremoveatindexindex this will cause array index out of range,['ios'] +949126,optional framework not working coreaudiokit not on simulator to get midi over bluetooth working i need to use the coreaudiokit framework this works perfectly but i am not able to compile on the simulator making the framework optional does not help error is ld framework not found coreaudiokiti think it should work according to the docsdeleting the framework allows my code to compilei have got this in code which is why i can delete the framework without issues if target iphone simulatorimport coreaudiokitcoreaudiokithendifhow can i get this optional compilation to work,['ios'] +949152,do any implementations of operator new return a pointer to a guard page for zerosize arrays related to c new int0 will it allocate memorythe standard says in 5347when the value of the expression in a directnewdeclarator is zero the allocation function is called to allocate an array with no elementsand in 37312the effect of dereferencing a pointer returned as a request for zero size is undefinedyet the pointer cannot be a null pointersince actually dereferencing the pointer is undefined behavior does any implementation return a pointer to a guard page i imagine that it would be easy and help detect bugsimprove security,['c++'] +949194,develop for 4k resolution on desktop or let browsers handle the scaling i have got a general web design question recently our office acquired a couple of very large 4k television screens first thing people did was plug up a surface pro 3 to iti loaded up our company website on it it is not great it is very very very thin it was developed to be responsive up to resolutions around 1080pnow that was ie11 on windows 81 i do not know what edge has in store with windows 10 however i know that chrome has a hidpi mode that i believe sets a device screen size and scales everything up and they are actively improving the featureif the screen were treated as if it were 1080p and everything was scaled by 2x i am in the clear for all my websitesmy question is should i count on browser scaling will that become the norm or is that simply a necessary evil they must implement for backwards compatibility with the current majority of the entire internetshould i continue to add more responsive design and ensure it looks good al the way up to 4k resolutions are there any meta tags to be aware of to ensure i take advantage of browser scaling when possiblesorry for the barrage of questions to keep this short and sweet i will simply ask thisshould i start focusing on ensuring my responsive websites look good all the way up to 4k resolutions or keep developing for 1080p and pray browser scaling becomes the norm for 4k thisplays,"['html', 'css']" +949208,strange behavior in dowhile statement on galaxy s5 and android 511 i face strange behavior of dowhile statement on galaxy s5 and android 511 if you have any information let me knowint i 0int j 0do logdtag test dowhile 1 i i j j i 0 logdtag test dowhile 2 i i j j i logdtag test dowhile 3 i i j j i logdtag test dowhile 4 i i j j j logdtag test dowhile 5 i i j j while j 5if i will run the program on galaxy s5 with android 511 output log is as followsdmainactivity 9856 test dowhile 1 i 2 j 0dmainactivity 9856 test dowhile 2 i 2 j 0dmainactivity 9856 test dowhile 3 i 2 j 0dmainactivity 9856 test dowhile 4 i 2 j 0dmainactivity 9856 test dowhile 5 i 2 j 1dmainactivity 9856 test dowhile 1 i 2 j 1dmainactivity 9856 test dowhile 2 i 2 j 1dmainactivity 9856 test dowhile 3 i 2 j 1dmainactivity 9856 test dowhile 4 i 2 j 1dmainactivity 9856 test dowhile 5 i 2 j 2dmainactivity 9856 test dowhile 1 i 2 j 2dmainactivity 9856 test dowhile 2 i 2 j 2dmainactivity 9856 test dowhile 3 i 2 j 2dmainactivity 9856 test dowhile 4 i 2 j 2dmainactivity 9856 test dowhile 5 i 2 j 3dmainactivity 9856 test dowhile 1 i 2 j 3dmainactivity 9856 test dowhile 2 i 2 j 3dmainactivity 9856 test dowhile 3 i 2 j 3dmainactivity 9856 test dowhile 4 i 2 j 3dmainactivity 9856 test dowhile 5 i 2 j 4dmainactivity 9856 test dowhile 1 i 2 j 4dmainactivity 9856 test dowhile 2 i 2 j 4dmainactivity 9856 test dowhile 3 i 2 j 4dmainactivity 9856 test dowhile 4 i 2 j 4dmainactivity 9856 test dowhile 5 i 2 j 5if i will run the same program on other device or other os version output is as followsdmainactivity 9515 test dowhile 1 i 0 j 0dmainactivity 9515 test dowhile 2 i 0 j 0dmainactivity 9515 test dowhile 3 i 1 j 0dmainactivity 9515 test dowhile 4 i 2 j 0dmainactivity 9515 test dowhile 5 i 2 j 1dmainactivity 9515 test dowhile 1 i 2 j 1dmainactivity 9515 test dowhile 2 i 0 j 1dmainactivity 9515 test dowhile 3 i 1 j 1dmainactivity 9515 test dowhile 4 i 2 j 1dmainactivity 9515 test dowhile 5 i 2 j 2dmainactivity 9515 test dowhile 1 i 2 j 2dmainactivity 9515 test dowhile 2 i 0 j 2dmainactivity 9515 test dowhile 3 i 1 j 2dmainactivity 9515 test dowhile 4 i 2 j 2dmainactivity 9515 test dowhile 5 i 2 j 3dmainactivity 9515 test dowhile 1 i 2 j 3dmainactivity 9515 test dowhile 2 i 0 j 3dmainactivity 9515 test dowhile 3 i 1 j 3dmainactivity 9515 test dowhile 4 i 2 j 3dmainactivity 9515 test dowhile 5 i 2 j 4dmainactivity 9515 test dowhile 1 i 2 j 4dmainactivity 9515 test dowhile 2 i 0 j 4dmainactivity 9515 test dowhile 3 i 1 j 4dmainactivity 9515 test dowhile 4 i 2 j 4dmainactivity 9515 test dowhile 5 i 2 j 5if we convert the code to while or for statement the issue does not occurif we make a own log library with sync file io the issue occurdoes not occur on galaxy s4 and s6 or android 502,"['java', 'android']" +949219,uialertcontroller is crashed ipad i am using xcode 6 to develop an ios applicationwhen i used uialertcontroller it can be worked well on iphone 6 simulator but crashes on ipad simulatormy problem while clicking share then it could be crashedhow could i solve ithere is my codeoverride func tableviewtableview uitableview editactionsforrowatindexpath indexpath nsindexpath anyobject var shareaction uitableviewrowactionstyle uitableviewrowactionstyledefault title share handler actionuitableviewrowaction indexpathnsindexpath void in let sharemenu uialertcontrollertitle nil message share using preferredstyle actionsheet let twitteraction uialertactiontitle twitter style uialertactionstyledefault handler nil let facebookaction uialertactiontitle facebook style uialertactionstyledefault handler nil let emailaction uialertactiontitle email style uialertactionstyledefault handler nil let cancelaction uialertactiontitle cancel style uialertactionstylecancel handler nil sharemenuaddactiontwitteraction sharemenuaddactionfacebookaction sharemenuaddactionemailaction sharemenuaddactioncancelaction selfpresentviewcontrollersharemenu animated true completion nil xcode showed this messageterminating app due to uncaught exception nsgenericexception reason your application has presented a uialertcontroller uialertcontroller 0xaf71c80 of style uialertcontrollerstyleactionsheet the modalpresentationstyle of a uialertcontroller with this style is uimodalpresentationpopover you must provide location information for this popover through the alert controllers popoverpresentationcontroller you must provide either a sourceview and sourcerect or a barbuttonitem if this information is not known when youenter image description here11 present the alert controller you may provide it in the uipopoverpresentationcontrollerdelegate method prepareforpopoverpresentation first throw call stack 0 corefoundation 0x0023c746 exceptionpreprocess 182 1 libobjcadylib 0x01c7aa97 objc exception throw 44 2 uikit 0x012c4062 uipopoverpresentationcontroller presentationtransitionwillbegin 3086 3 uikit 0x00bda174 71uipresentationcontroller initviewhierarchyforpresentationsuperview block invoke 1549 4 uikit 0x00bd8247 56uipresentationcontroller runtransitionforcurrentstate block invoke 198 5 uikit 0x00c0d31b 40uiviewcontroller scheduletransition block invoke 18 6 uikit 0x00ac6862 aftercacommithandler block invoke 15 7 uikit 0x00ac680d applyblocktocfarraycopiedtostack 415 8 uikit 0x00ac6622 aftercacommithandler 549 9 corefoundation 0x0015d86e cfrunloop is calling out to an observer callback function 30 10 corefoundation 0x0015d7b0 cfrunloopdoobservers 400 11 corefoundation 0x001531ea cfrunlooprun 1226 12 corefoundation 0x00152a5b cfrunlooprunspecific 443 13 corefoundation 0x0015288b cfrunloopruninmode 123 14 graphicsservices 0x047b82c9 gseventrunmodal 192 15 graphicsservices 0x047b8106 gseventrun 104 16 uikit 0x00a9c106 uiapplicationmain 1526 17 mars i 0x01c724 main 180 18 libdylddylib 0x02392ac9 start 1 19 0x01 0x0 1libcabidylib terminating with uncaught exception of type nsexception,['ios'] +949288,change xcrun developer path for android studio i am using git and am trying to push my code and getting the following error when using the terminal i do not use xcode im using android studiothe command i tried using was git branch networkingerrorxcrun error invalid active developer path librarydevelopercommandlinetools missing xcrun at librarydevelopercommandlinetoolsusrbinxcruni am running on el capitan beta 4 update if that helps in anyway,['android'] +949294,implementing google analytics 750 play services in android 44 and below crashes after i implemented google analytics my app crashes instantly on devices older than lollipop 0722 154243831 wdalvikvm1815 vfy unable to resolve virtual method 16407 lcomgoogleandroidgmsanalyticsinternalzzggetapplicationcontext landroidcontentcontext0722 154243831 ddalvikvm1815 vfy replacing opcode 0x6e at 0x030722 154243831 idalvikvm1815 could not find method comgoogleandroidgmsinternalzzldzzoq referenced from method comgoogleandroidgmsanalyticsinternalzzfzzv0722 154243831 wdalvikvm1815 vfy unable to resolve static method 27402 lcomgoogleandroidgmsinternalzzldzzoq lcomgoogleandroidgmsinternalzzlb0722 154243831 ddalvikvm1815 vfy replacing opcode 0x71 at 0x0e0722 154243831 wdalvikvm1815 vfy unable to find class referenced in signature lcomgoogleandroidgmsinternalzzlb0722 154243831 wdalvikvm1815 vfy ljavalangobject is not instance of lcomgoogleandroidgmsanalyticsinternalzzd0722 154243831 wdalvikvm1815 vfy bad arg 1 into lcomgoogleandroidgmsanalyticsinternalzzd0722 154243831 wdalvikvm1815 vfy rejecting call to lcomgoogleandroidgmsanalyticsinternalzzfzza lcomgoogleandroidgmsanalyticsinternalzzdv0722 154243831 wdalvikvm1815 vfy rejecting opcode 0x70 at 0x020722 154243831 wdalvikvm1815 vfy rejected lcomgoogleandroidgmsanalyticsinternalzzfzzht lcomgoogleandroidgmsanalyticsinternalzzv0722 154243831 wdalvikvm1815 verifier rejected class lcomgoogleandroidgmsanalyticsinternalzzf0722 154243831 dandroidruntime1815 shutting down vm0722 154243831 wdalvikvm1815 threadid1 thread exiting with uncaught exception group0xb0ce1b200722 154243831 eandroidruntime1815 fatal exception main0722 154243831 eandroidruntime1815 process pid 18150722 154243831 eandroidruntime1815 javalangverifyerror comgoogleandroidgmsanalyticsinternalzzf0722 154243831 eandroidruntime1815 at comgoogleandroidgmsanalyticsgoogleanalyticsgetinstanceunknown source0722 154243831 eandroidruntime1815 at comxoncreatexjava220722 154243831 eandroidruntime1815 at androidappinstrumentationcallapplicationoncreateinstrumentationjava10070722 154243831 eandroidruntime1815 at androidappactivitythreadhandlebindapplicationactivitythreadjava43280722 154243831 eandroidruntime1815 at androidappactivitythreadaccess1500activitythreadjava1350722 154243831 eandroidruntime1815 at androidappactivitythreadhhandlemessageactivitythreadjava12560722 154243831 eandroidruntime1815 at androidoshandlerthispatchmessagehandlerjava1020722 154243831 eandroidruntime1815 at androidoslooperlooplooperjava1360722 154243831 eandroidruntime1815 at androidappactivitythreadmainactivitythreadjava50010722 154243831 eandroidruntime1815 at javalangreflectmethodinvokenativenative method0722 154243831 eandroidruntime1815 at javalangreflectmethodinvokemethodjava5150722 154243831 eandroidruntime1815 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava7850722 154243831 eandroidruntime1815 at comandroidinternaloszygoteinitmainzygoteinitjava6010722 154243831 eandroidruntime1815 at dalviksystemnativestartmainnative methodmy gradle file inside android blockcompilesdkversion 22buildtoolsversion 2201defaultconfig applicationid x minsdkversion 14 targetsdkversion 22 versioncode 6 versionname 05 multidexenabled truebuildtypes release minifyenabled false proguardfiles getdefaultproguardfileproguardandroidtxt proguardrulespro i use this version of google play services compile comgoogleandroidgmsplayservicesanalytics750i searched a lot on the web already on this subject but could not find anything that solved the issue closest one was this answer on so unfortunately it did not worked out for me,['android'] +949346,numpy why the need to explicitly copy a value arr nparange011slice of arr arr06slice of arr99 slice of arr returnsarray99 99 99 99 99 99 arr returnsarray99 99 99 99 99 99 6 7 8 9 10as the example shown above you cannot directly change the value of the slice of arr because it is a view of arr not a new variablemy questions arewhy does numpy design like this wouldnt it be tedious every time you need to copy and then assign valueis there anything i can do to get rid of the copy how can i change this default behavior of numpy,['python'] +949376,autofac registerinstance vs singleinstance iproductrepositoryproxy productdataserviceproviderinstance new serviceproductdataproviderbuilderregisterinstanceproductdataserviceproviderinstanceasiproductrepositoryproxyvsbuilderregistertypeserviceproductdataproviderasiproductrepositoryproxyinstanceperrequesti saw this code from an exemployee here and wonder if the guy wanted to register a singleinstance behaviorbuilderregistertypeserviceproductdataproviderasiproductrepositoryproxysingleinstanceis the manual newingup of the serviceproductdataprovider with registerinstance not the same as the register singleinstance,['c#'] +949392,nonscrolling fragment in a viewpager inside coordinatorlayout i am using a viewpager in a coordinatorlayout from latest version of design library in an activitysome fragments for this viewpager have layouts such as recyclerview or nestedscrollview but some just cannot scroll given their small content androidsupportdesignwidgetappbarlayout androidididtabanim appbar androidlayout widthmatch parent androidlayout heightwrap content androidthemestylemytheme androidsupportv7widgettoolbar androidididtabanim toolbar androidlayout widthmatch parent androidlayout heightattractionbarsize androidbackgroundattrcolorprimary applayout scrollflagsscrollenteralways apopupthemestylethemeoverlayappcompatlight androidsupportdesignwidgettablayout androidididtabanim tabs androidlayout widthmatch parent androidlayout heightwrap content androidsupportdesignwidgetappbarlayout androidsupportv4viewviewpager androidididtabanim viewpager androidlayout widthmatch parent androidlayout heightmatch parent applayout behaviorstringappbar scrolling view behavior androidsupportdesignwidgetcoordinatorlayoutbut in one fragment with a framelayout as the root view i need to have a button that is anchored to the bottom but it appears to be drawn offscreento be able to see it i need to add a bottom padding equals to the height of the toolbar framelayout xmlnsandroid xmlnsapp androidlayout widthmatch parent androidlayout heightmatch parent androidbackgroundandroidcolorwhite textview androidididtextview androidlayout widthwrap content androidlayout heightwrap content androidlayout gravitycenter androidtexthome screen androidtextappearanceandroidattrtextappearancelarge textview androidlayout widthmatch parent androidlayout height70dp androidlayout gravitybottom androidgravitycenter androidtextstringbrand androidtextcolorcolorbrandcolor androidtextsize20sp framelayoutlikewise a layout gravity set to center on an element does not appear to be in the center of the visible area for this fragmentmy understanding is that coordinatorlayout is only intented to work with scrolling contents is that correct so that using only regular viewgroup such as framelayout relativelayout linearlayout for the viewpager fragments will have their bottom part drawn offscreen in that case do i need to remove this button from this fragment layout and move it to the activity layout containing the coordinatorlayout it needs to be shown only on the first fragment,['android'] +949477,how can i fire a zoom out event in browser resize i am using leafletjs for my test app i need to fire the zoomout event when the browser is resizedhere is my browser resize codefunction windowonresize resize function resize use strict ifwindowwidth 765 mapoptionszoom 5 consolelogmapoptionszoom this code if to show the mapltopojson lgeojsonextend adata functionjsondata if jsondatatype topology for key in jsondataobjects geojson topojsonfeaturejsondata jsondataobjectskey lgeojsonprototypeadatacallthis geojson else lgeojsonprototypeadatacallthis jsondata var tiles ltilelayerhttpstileopenstreetmaporgzxypngvar latlng new llatlng2840 8415mapoptions dragging false zoomcontrol true scrollwheelzoom false doubleclickzoom false touchzoom false attributioncontrol false center latlng zoom 7 layers tilesconsolelogmapoptionszoom firstmap lmapmapnepal mapoptionsmapinvalidatesizevar topolayer new ltopojsongetjsonjsmapthistrictstopojsondoneaddtopodatawhat i have done is create a global variable called mapoptions first the map is initialized with mapoptionszoom 7 and when the browser is resized then i have changed the value of the mapoptionszoom to 6 the value has changed but there is no effect in zoom of the map,"['javascript', 'jquery']" +949547,load more posts ajax button in wordpress i have had a look through the old questions and tried many of the different methods that there seems to be to do this the closest i have got to working is this one here how to implement pagination on a custom wp query ajax i have tried everything and it just doesnt work absolutely nothing changes on the page if you inspect the load more button and click it the jquery is making the load more button action as it changes from a idmore postsload morea to a idmore posts thisablesthisabledload morea which even that doesnt seem right to me anyway it is not adding the posts i think i am missing something simple but for the life of me i cannot work it outthe code in my template file is div idajaxposts classrow php postsperpage 3 args array post type post posts per page postsperpage cat 1 loop new wp queryargs while loophave posts loopthe post div clasmall12 large4 columns h1php the title h1 pphp the content p div php endwhile echo a idmore postsload morea wp reset postdata divthe code in my functions file isfunction more post ajax offset postoffset p postp headercontenttype texthtmlargs array suppress filters true post type post posts per page p cat 1 offset offsetloop new wp queryargswhile loophave posts loopthe post the contentexit add actionwp ajax nopriv more post ajax more post ajax add actionwp ajax more post ajax more post ajaxand my jquery in the footer is script typetextjavascript jquerydocumentready function var ajaxurl php echo admin urladminajaxphp var page 5 what page we are on var p 3 post per page more postsonclickfunction when btn is pressed more postsattrthisabledtrue thisable the button temp postajaxurl actionmore post ajax offset page p 1 p p successfunctionposts page ajaxpostsappendposts change this more postsattrthisabledfalse scriptcan anybody see something i am missing or able to help,"['javascript', 'php', 'jquery']" +949619,javascript pushstate on a subdomain throws exception in my js filewindowhistorypushstateslugi know about security restrictions for the pushstate methodthe new url must be of the same origin as the current url otherwise pushstate will throw an exceptionhowever in my website i use a domain wmydomaincom where pushstate works fine but when i call the method on my subdomain subdomainmydomaincom it throws a weird exceptionuncaught securityerror failed to execute pushstate on history a history state object with url cannot be created in a document with origin i do call the ip 007210 as something internal but i get this exception on development live environmenti do resolve my subdomains via route53 by the way maybe it has to do with that,['javascript'] +949648,how do you see which exceptions are thrown with intellisense in vs2015 this was addressed and fixed in vs2015 update 1is there any way to show the exceptions in vs2015vs2015vs2013,['c#'] +949752,java constructor chain direction i realize there are special classes for which this general question does not apply but for the simple ones when we have multiple constructors and the parameters of one are a clean subset of another is it better to call the constructor with the longer list from the one with the shorter list or vice versa whypublic class a int x int y int z public a this0 public aint x this x 0 public aint x int y thisx y 0 public aint x int y int z thisx x thisy y thisz z some setup stuff needed for all a orpublic class a int x int y int z public aint x int y int z thisx y thisz z public aint x int y thisx thisy y public aint x this thisx x public a some setup stuff needed for all a,['java'] +949775,scrapy spider memory leak my spider have a serious memory leak after 15 min of run its memory 5gb and scrapy tells using prefs that there 900k requests objects and thats all what can be the reason for this high number of living requests objects request only goes up and doesnt goes down all other objects are close to zeromy spider looks like thisclass externallinkspidercrawlspider name external link spider allowed domains start urls rules rulelxmllinkextractorallow callbackparse obj followtrue def parse objself response if not isinstanceresponse htmlresponse return for link in lxmllinkextractorallow denyselfallowed domainsextract linksresponse if not linknofollow yield linkcrawlitemdomainlinkurlhere output of prefshtmlresponse 2 oldest 0s ago externallinkspider 1 oldest 3285s agolinkcrawlitem 2 oldest 0s agorequest 1663405 oldest 3284s agomemory for 100k scraped pages can hit 40gb mark on some sites for example at victorinoxcom it reach 35gb of memory at 100k scraped pages mark on other its much lesserupd,['python'] +949856,fab animation with viewpagertabslider i am trying to find way to achieve such effect v 4material ext publish0b6okdz75tqqsvlhxngjcnteznfucomponentsbuttonsfabbehavior 04 xhdpi 009webmi am using androidsupportv4viewviewpageri appreciate any hints and help,['android'] +949875,implementing data structure using levels of abstraction lets assume i am to implement stack using dynamic array allocationi have the following classes and their functionsdatahclass datapublic datastdstring fname int age namefname ageage private stdstring name int agestackarrayhinclude datahclass stackarraypublic stackarrayint ssize sizessize top1 dataarray new datasize stackarray delete dataarray stackarray operatorstackarray stackarrayobj use copyswap here stackconst stackarray stackarrayobj bool isfull bool isempty void pushdata dataobj void popprivate data dataarray int top int sizeif i implement something like the above it works quite well but of recent i have been asked to implement the above two as it is then have a separate implementation for core stack functionalitiesso now if i move push pop isfull isempty to the new stack definition what exactly will be the purpose of class stackarray implemtationthe two solution i have tried are as followsnew class implemtation class stackadt public stackadt virtual stackadt 0 virtual bool isfull 0 virtual bool isempty 0 virtual void pushdata dataobj 0 virtual void pop 0then by extending this class from stackarray class thereby forcing it to implement all the pure virtual functionthe second but not so elegantmy opinion way i have done it is thati have a complete definition and implementation of the stack in stackadt and then calling the corresponding methods in equivalent methods in stackarray like thisstackadt pushbool stackadtpushconst data dataobj ifisfull return false else top dataarraytop dataobj return truethen inside stackarray push i will do something like thisbool stackarraypushconst data dataobj stackadt dopush dopushpushdataobjnot too sure both methods of combining all three classes data container and stack are what they are suppose to behow can i solve this design problem or at least align it with best practice if there is any for such,['c++'] +949994,compilation error stddefh no such file or directory whenever i try to compile this code it always ends up with this error in file included from usrincludewcharh60 from usrlibgcci686pccygwin492includeccwchar44 from usrlibgcci686pccygwin492includecbitspostypesh40 from usrlibgcci686pccygwin492includeciosfwd40 from usrlibgcci686pccygwin492includecios38 from usrlibgcci686pccygwin492includecostream38 from usrlibgcci686pccygwin492includeciostream39 from testcpp1 usrincludesysreenth1420 fatal error stddefh no such file or directory include stddefh compilation terminatedthe code i was trying to compile isinclude iostreamusing namespace stdint main cout hello world d return 0,['c++'] +950018,annoying lag when avqueueplayer jumps from asset to another i have an avqueueplayer that is supposed to play sequentially an array of avurlasset representing consecutive fragments of one continuous videowhenever a fragment ends and another starts there is a small glitch that can be well noticed frame hold for approx 02sec and sound gets mutedi tried researching how to get around that issue but have not found anything i tried solving it by having 2 avqueueplayers and switch between both around 02sec before the end of every fragment issue not solvedany idea on how to solve thatnote when joining the mp4 fragments together using an mp4 joiner software the output is a single smooth video without any glitch,['ios'] +950068,why final variable does not require initialization in main method in java when i am just trying to do some program in javai try to use final variablei know that final variable must be initialized at the time of declaration but inside the main method it accepts the final variable with out initialization i do not know whats the reasoncan any one tell me the reason thank youcodeclass name final int b here shows error public static void mainstring args final int a here no error why systemoutprintlnhai,['java'] +950099,show label in tooltip but not in x axis for chartjs line chart i currently am using a line chart with chartjs and have a label set that looks like this january 2015 february 2015 march 2015 april 2015 may 2015 june 2015 i want the relevant label to show up in the tooltip for the chart but only want every alternating label to show up on the x axis of the chart to prevent crowding is there a way i can achieve this i am currently replacing every second value from my array with but while that removes the crowding from my x axis it does not meet my requirement to show the label in the tooltip,['javascript'] +950143,how to simulate multiple tag with css i was spending some time on a question when i came up with a funny solution but not really finalizedsee the fiddle and try to erase the br tag the idea is too get the same effect red div thisplayed but without using this solution relatively horribleso here is my question how do i simulate br tags with css or eventually js just some more difficulty you cannot touch the wrapperheres the html codediv classwrapper psome text and descriptionsp div classwidget boxwrap div classboxbrbrbrbrbrbrbrbrbrbrbrbrbrdiv div psome more text and description and some more offcourse and a bit more and just a tiny bit morepdivheres the csswrapper width300px thisplayblock positionrelative overflowhidden backgroundcolorgraywidget width300px height300px thisplayblock positionrelative backgroundcolorgreenbox backgroundcolorred visibilityvisibleboxwrap overflow hidden height 0 paddingbottom 60boxwrap div maxwidth 100,"['javascript', 'html', 'css']" +950200,qt c library in android eclipse project qsqlite driver not loaded i have created a qt dynamic lib that uses qt sql to open an sqlite database but i am getting this errorqsqldatabase qsqlite driver not loadedqsqldatabase available drivers the dll was working fine as part of a qt android application however i need to use it through jni from an existing java application developed in eclipsethis is the shortest example code that reproduces the problem i load the library from java and call its init methodsystemloadlibraryplugins sqldrivers libqsqlitesystemloadlibraryqt5sqlsystemloadlibrarymyqtlibmyqtlibinitand inside the qt library i just call qsqldatabaseadatabasejniexport void jnicall java test myqtlib foojnienv jclass manually create a qcoreapplication instance int argc 1 static char arg static char arg2 arg app new qcoreapplicationargc arg2 try to add an sqlite db connection qsqldatabaseadatabaseqsqlitesince the error is qsqlite driver not loaded and the qt library was working inside a qt application i assume that qt is doing some initialization that i am missingbut this did not remove the error so it must be something else normally the qt application will use qtapplicationjava and qtactivityjava to perform some initialization so they must be doing something more there that i am not doing,"['android', 'c++']" +950211,casting pointer types on different architectures i have the following structure and getter function that returns a cast to an unsigned integerstruct s uint32 t avoid get astruct s st unsigned ret ret unsignedstathe following code is runstruct s stuint16 t xsta 1get ast unsigned xand for x86 64 i686 armv7hl ppc64le and other architectures x 1 but for ppc64 x 0 why is this little vs bigendian,['c'] +950229,analyticsreceiver is not registered or is thisabled i have just started upgrading my android app from the old deprecated analytics sdk to v4 i followed the documentation and as far as i can tell i did everything righton my device which has google play services installed data seems to be sent just finewhat worries me is that in the logs i see this message every time my app starts analyticsservice not registered in the app manifest hits might not be delivered reliably see for instructions and of course i would prefer to get accurate statisticsthe message seems quite clear add this stuff to your androidmanifextxml file the problem is that it is already therethis is in my androidmanifestxml file inside the application tag beneath the activity and service tags that are required by the rest of my app google analytics metadata androidnamecomgoogleandroidgmsversion androidvalueintegergoogle play services version receiver androidnamecomgoogleandroidgmsanalyticsanalyticsreceiver androidenabledtrue intentfilter action androidnamecomgoogleandroidgmsanalyticsanalytics thispatch intentfilter receiver service androidnamecomgoogleandroidgmsanalyticsanalyticsservice androidenabledtrue androidexportedfalse is this a known issue am i missing something elsei went for the extend application and have the tracker as a static property approach that is also used in the getting started part of the documentation,"['java', 'android']" +950233,where are string objects when created using tostring methods stored in memory in java i was doing one assignment and i got this following questionwhere are the string objects created with the tostring method stored in memorystring a integertostring10in the constant poolon the heap the area of new operator object,['java'] +950279,which third party imageview class should i used my requirement is need to show image in imageview from server url save it for offline use alsobut there may be chances that same url image can be updatedi tried egoimageviewasyncimageviewfximageviewhaneke thsese all classes i triedmy first part of requirement is achieved but not secondie if x link image is shown for first timeif on that same link image is upadated app shows old image only,['objective-c'] +950282,jupyter ipython notebook not plotting i installed anaconda to use pandas and scipy i reading and watching pandas tutorials and they all say to open the ipython notebook using ipython notebook pylabinlinebut when i do that i get a message sayingsupport for specifying pylab on the command line has been removed please use pylab inline or matplotlib inline in the notebook itselfbut that does not work then when i try plotarange10 i get a message saying name plot is not defined i trying plotting data from a csv file and gotmatplotlibaxes subplotsaxessubplot at 0xebf8b70what should i do,['python'] +950335,count appearance of each character i am currently working on a password strength calculator and then i need to know if a character appears more than oncei know i must use regex like this occurance passwordmatchaglength to get ho many times a occurs but i want to do that with each character letter number symbolis there a way to do that using js jquery maybe regex other than working with an array which contains all characters i want to test,"['javascript', 'jquery']" +950444,how to confine animated div to a webpage section hi i am currently working on a parallax website i would like to add an image that moves down as the user scrollsbut only within a section of a website so 4 sections downthe image is thereit moves as the user scrolls downthen thisappears behind 5th section and we see it no morei am trying to do a similar effect to this website websitewhen you scroll downyou see about move between divs i want to achieve that when i do itit appears on top of first section and stays on screen all the way downheres a sample jsfiddle it only shows a part of the website fiddlei know it is to do with positioning but i want it to stay within the div rather than positioned within the whole page create cross browser requestanimationframe methodwindowrequestanimationframe windowrequestanimationframe windowmozrequestanimationframe windowwebkitrequestanimationframe windowmsrequestanimationframe functionfsettimeoutf 1060var bubble1 documentgetelementbyidbubbles1var bubble2 documentgetelementbyidbubbles2var fish documentgetelementbyidfishvar scrollheight documentbodyscrollheight height of entire documentvar windowheight windowinnerheight height of browser windowfunction parallaxbubblesvar scrolltop windowpageyoffset get number of pixels document has scrolled verticallyvar scrollamount scrolltop scrollheightwindowheight 100 get amount scrolled in bubble1styletop scrolltop 2 px move bubble1 at 20 of scroll speedbubble2styletop scrolltop 5 px move bubble2 at 50 of scroll speedfishstyleleft 100 scrollamount windowaddeventlistenerscroll function on page scrollrequestanimationframeparallaxbubbles call parallaxbubbles on next available screen repaint falsewindowaddeventlistenerresize function on window resizevar scrollamount scrolltop scrollheightwindowheight 100 get amount scrolled in fishstyleleft 100 scrollamount falsecdmaincontent i need to assign a minheight to the main content so that the children can inherit it height 60 position relative zindex 1cdfixedbg position relative minheight 100 backgroundsize cover backgroundrepeat norepeat backgroundposition center center zindex 1cdfixedbg h1 cdfixedbg h2 position absolute left 50 top 50 bottom auto right auto webkittransform translatex50 translatey50 moztransform translatex50 translatey50 mstransform translatex50 translatey50 otransform translatex50 translatey50 transform translatex50 translatey50 width 90 maxwidth 1170px textalign center fontsize 30px fontsize 1875rem textshadow 0 1px 3px rgba0 0 0 03 color whitecdfixedbgcdbg1 backgroundimage urlimagescontentgreypngcdfixedbgcdbg2 backgroundimage urlimagescontentcdbackground2jpgmedia only screen and minwidth 768px cdfixedbg h1 cdfixedbg h2 fontsize 36px media only screen and minwidth 1170px cdfixedbg backgroundattachment fixed cdfixedbg h1 cdfixedbg h2 fontsize 48px fontweight 300 cdscrollingbg position relative minheight 50 padding 4em 0 lineheight 16 boxshadow 0 0 50px rgba0 0 0 05 zindex 2cdscrollingbgcdcolor1 backgroundcolor f color 0cdscrollingbgcdcolor2 backgroundcolor 1c1c1c background rgba4848481background mozradialgradientcenter ellipse cover rgba4848481 0 rgba5656561 0 rgba2828281 46 rgba1010101 100background webkitgradientradial center center 0px center center 100 colorstop0 rgba4848481 colorstop0 rgba5656561 colorstop46 rgba2828281 colorstop100 rgba1010101background webkitradialgradientcenter ellipse cover rgba4848481 0 rgba5656561 0 rgba2828281 46 rgba1010101 100background oradialgradientcenter ellipse cover rgba4848481 0 rgba5656561 0 rgba2828281 46 rgba1010101 100background msradialgradientcenter ellipse cover rgba4848481 0 rgba5656561 0 rgba2828281 46 rgba1010101 100background radialgradientellipse at center rgba4848481 0 rgba5656561 0 rgba2828281 46 rgba1010101 100filter progiddximagetransformmicrosoftgradient startcolorstr303030 endcolorstr0a0a0a gradienttype1 cdscrollingbgcdcolor3 backgroundcolor 00161b color 3d3536media only screen and minwidth 768px cdscrollingbg padding 8em 0 fontsize 20px fontsize 125rem lineheight 2 fontweight 300 bubbles1width 100height 100bottom 0left 0position absolutezindex 1background url 5 80 norepeatbubbles2background urlbubbles3png 95 90 norepeatscript srcscriptmain classcdmaincontent parallaxdiv classcdscrollingbg cdcolor2 parallaxdiv classcdcontainerplorem ipsum dolor sit amet consectetur adipisicing elit dolore incidunt suscipit similique dolor corrupti cumque qui consectetur autem laborum fuga quas ipsam doloribus sequi mollitia repellendus sapiente repudiandae labore rerum amet culpa inventore modi non quo nisi veritatis vitae nam labore fugit inventore culpa iusto officia exercitationem voluptates quibusdam odit odio incidunt consequatur consectetur aspernatur optio vitae molestias quas repellendus fugit ullam culpa eligendi et dignissimos voluptatibus illum molestias aliquam nostrum quasi ipsa culpa iusto explicabo ut error consequuntur enim temporibus adipisci tempora voluptate id consequatur mollitia eveniet blanditiis illo quod repellendus alias cum rem doloremque adipisci accusantium saepe necessitatibuspdiv cdcontainer div cdscrollingbg div classcdscrollingbg cdcolor3 div idbubbles1divh2lorem ipsum dolor sit ameth2div cdfixedbg div classcdscrollingbg cdcolor3 div classcontainer this is the bubble image div classrowfluid div claspan3 div classtextwidget widget h4about meh4 plorem ipsum dolor nonus amet consectetur ex adipisicing elit sed do eiusmod incididunt ut labore et dolore magna aliqua ut enim ad ex minim veniam quis nostrud lorem exercitation ullamco laboris nisi ut aliquip nesciunt aliquap div div div claspan3 div div claspan3 div div claspan3 div div divdiv,"['javascript', 'html', 'css']" +950460,how can i identify usage of hardware vs soft keyboard in a hybrid tablet problemi have a small group of roughly 90 users which is extremely important so when one or two of these business customers desire the ui changed in their web app they usually get development resources dedicated however it is important for us to understand exactly how the application is being used by the group as a whole because this group tends to have strong personal views on how their ui should look and they all use the app differently i am having the most trouble with identification of their usage of hardware vs soft keyboard optimally i am looking for an answer as simple as use the new windowtabletmode true i do not think that simple answer existsresearchso question detect virtual keyboard vs hardware keyboard is the only significantly similar question i see but it focuses half of its time on using a javascript keyboard to replace the soft keyboard so the answers talk about how to make the keyboard specific to numbers dates etc additionally he is looking for crossbrowser solutions where i need only ie11 support finally i can depend on the hardware keyboard being docked and a specific brand dell finally i can depend upon windowsie11 so there could be other avenues of approach compared to this 3yearold question my use of a hybrid tablet also makes the approaches of capability checks useless since i already knwo all the capabilities touch etc are already available on the devicei could check the registry for the ui setting but i really need to stick to javascript or something similarandroid has undocumented but known events which indicate showing and hiding of the keyboard however none of the users will be using androidie should receive a wm settingchange message when the change occurs but i am unable to determine if this is made available to a javascript api i am thinking it would be a message far more specific if any so i cannot find anything with this search term and javascriptcodefrom w3schools the windoworientation property returns 0 for portrait and 90 or 90 for landscape viewcombined with windowinnerheight i could use something likevar portraitwindowonorientationchangefunctionevent if eventorientation 0 portrait true else if not it is landscape portrait false then i would use windowinnerheight in combination with the value of portrait to determine if the width to height ratio looks like i have a keyboard open this approach really might work in fullscreen considering my fairly narrow constraints but what if the browser is not fullscreen i am sure there are plenty of other reasons to not write a hacky ratio calculation for this additionally my greatest desire would of course be to do this with any browser and any screen sizethese things i can handle i would need to set variables on the loading of the document and work out a way to determine when the typing becomes relevant i might need to check for some browser capabilities perhaps i would increment counters for typing with and without a hardware keyboard once i hit a certain number let us say 5 keystrokes i would send a post request to my data tracking endpoint to let it know that session 12345 used the soft keyboard or hard keyboard afterwards i would unsubscribe from the event handler however i work this part is of less concern because i do not think i will get stuck on anything but i did not want anyone to spend time on beautification or development of a huge exampleenvironmenthardware should all be dell tabletlaptop hybrids specific model tbd with ie11 i hate to make something ie specific but if it runs on ie11 it is totally acceptablei should be able to pull in any sort of javascript libraries suggested but keep in mind that jquery 22 and knockout 21 are already present so little weight is added for a solution with jquery usagei probably cannot get approval to write an application that uses activex or some other heavy handed customized approach that would require installation of a local application because my company has roughly 50 users and a deployment like that for 90 users would be overly complex to maintainthe screen sizes should all be 11 inches but i would be sad to resort to using specific size and resolution because an answer like that would be extremely limited in application for me or future readersimpact for readersi am seeing a move away from ipads in the medical kiosk emr space because ipads limit a lot of the ui choices in favor of a cohesive experience physicians especially will often get attention of high ranking it leaders if they desire a very specific ui change microsoft has tended to allow a lot of nonstandard intervention and more recently more standard types of intervention in how the browser works i think a lot of this movement is going to windows tablets for this reason and also for the reason that many medical groups are heavy on net development capability,['javascript'] +950544,how to add a dropdown menu to the navigation bar title in ios i want to make something similar to the dropdown menu in these screenshots how would i go about doing thatwhen you tap the title the arrow points up and a menu drops down the app is college menus,"['ios', 'objective-c']" +950570,how to wake up iphone app from watchos 2 i have an app that has a very rich network layer and my apple watch app depends on all the models unfortunately the app is not modular enough to make this layer available in the watch appi solved this problem by using openparentapplication to wake up the iphone app perform the request and give back the resultsin watchos 2 this method is gone and i should use watchconnectivity the best way to use this would be by sending userinfo dictionaries but how can i wake up the iphone app to handle my requests to get notifications about new userinfos i have to use the wcsessiondelegate and for that i need a wcsession object but when should i create that and how to wake up the app,['ios'] +950697,show parent 1st level child category in a drop down list wordpress i currently have this code that shows all the parent categories in a drop down listhtmlphp codeul php args array orderby name hierarchical 1 taxonomy category hide empty 0 parent 0 categories get categoriesargs foreachcategories as category echo lia href get category linkcategorycat id title categoryname categoryname ali ulthere is no problem with the code below actually it works perfectly you can see it here at my wordpress website wbendaggerscomwhat i want to achieve now is how can i add the 1st level child of the parent just what it shown in image 1 below with the same effectimage 1 sample this is what i want to achieve whenever the user hovers on the listed parent category it will thisplay its 1st level child category as show in the image belowimage 2 sample parentcategory hierarchy by the way i need a working code php html and css alsoi really appreciate you help and efforts thank you very muchsome additional information that might be usefulthe website is a wordpress websiteall post are properly categorize parents 1st level child categoryis properly categorized,['php'] +950770,how to manage services in angular2 angular 2 200alpha31 typescript 15currently i manage my service as a simple class then i inject this class into an other component exampleexport class playerservice http http players constructor injecthttp http thishttp http getallcallback thishttpgetdataplayersjson torx mapres resjson subscribedata thisplayers data callbackdata addplayer call webservice to save user thisplayerspushplayer only if save has work deleteplayer not implemented yet getid not implemented yet i think i am doing it the wrong wayi am using httpgettorxsubscribe i thought i saw that some people return the observable directly from torxif two components ask for players getall at the same time two queries will be executed do i have to manage flag or is there another way i am working here with a callback what do i have to do if i want the data immediately no asyncwill components be automatically informed about players addremove do i have to use some kind of event to handle this any example so my question is is there a common way to manage services in angular2,['javascript'] +950793,floating label spinner after using the android design support librarys textinputlayout to place a floating label above an edittext component i was wondering if there is a way to add a floating label to the spinner component not necessarily using the design libraryby this i mean something like a textview placed above the spinner obviously no animations like the textinputlayout but i want the text size font and colour to match that of the textinputlayouts floating labelfor example it would look something like this see the labels above the spinnersas i mentioned before my main aim is to have a label above the spinner just as in the textinputlayout so text size font colour and thistances between the label and the component would be the sameon the google design page about floating label text fields there is a diagram showing dimensions of the label relative to the component but there is no indication of the label text colour or sizeso to summarise i am asking if there is a special component to achieve what i am asking or a custom view i can use what would it be and how can i use it if not what is the floating label text size colour and font so that i can place a textview above my spinner with the layout dimensions shown in the above imageeditfrom the google design guidelines for text fields it has the following for floating labelshint and input font roboto regular 16sp label font roboto regular 12sp tile height 72dp text top and bottom padding 16dp text field divider padding 8dp as well as the images shown above so the floating label font is roboto regular 12sp you can therefore use a textview to thisplay the spinner label as i do not know of any custom views or special components you could usehowever after trying it out it does not look quite as good as the example shown in the image a custom view may be better for this as it could look nicer but the solution above is just one way of achieving something close to what i originally wanted,['android'] +950986,vs2015 internal compiler error when using inheriting constructors heres a 10line c11 program vastly simplified from a program i am working ontemplate typename t class base public template typename s bases x template typename t class child public baset public using basetbasetemplate class childint public baseint public using baseintbaseint main childint child80fmsvc 2015 outputs1 build started project myproject configuration debug win32 1 filenamecpp1pathtofilename10 fatal error c1001 an internal error has occurred in the compiler1 compiler file msc1cpp line 13931 to work around this problem try simplifying or changing the program near the locations listed above1 please choose the technical support command on the visual c1 help menu or open the technical support help file for more informationnb msvc 2015 support for inheriting constructors is new with that versioni have already submitted a bug report on this since at the very least the compiler should not crash however can i have confirmation that this is correct c usagea workaroundbug report here,['c++'] +951216,are search engines going to see my dynamically created content in bootstrap tabs i have a page indexphp with 3 bootstrap tabs in it and for each tab i am generating its content after user clicks on itfor examplewhen page is loaded i will execute sql query that will get data from database only for first tab when user clicks on the second tab i am executing a query that will take data and thisplay it in selected tab is this good approach is google going too see all that data when it index the page containing all this tabs i do not want to pull all data at once because of performance issueshere is my sample code so please tell me if this is a good approachindexphp filedoctype htmlhtmlhead titletabs demotitle latest compiled and minified css link relstylesheet hrefheadbody div classcontainer ul classnav navtabs li classactivea datatoggletab hrefhomehomeali lia datatoggletab hrefmenu1menu 1ali lia datatoggletab hrefmenu2menu 2ali ul div classtabcontent div idhome classtabpane fade in active h3homeh3 psome contentp div div idmenu1 classtabpane fade php model 0 title first item content some first content 1 title second item content some second content php foreach model as data h3 datatitle h3 p datacontent p php endforeach div div idmenu2 classtabpane fade h3menu 2h3 psome content in menu 2p div div div jquery library script srccodejquerycomjquery214minjsscript latest compiled and minified javascript script srcscriptbodyhtmli am afraid that search engines will not see second and third tabs contents or at least they will not relate them with indexphp page am i wrong,['javascript'] +951231,test if array contains value using phpunit i created this array of objectsad 1 new adunitarrayid 1 name ad 1 description great ad code alpha widget id 123ad 2 new adunitarrayid 2 name ad 2 description good ad code delta widget id 456ad 3 new adunitarrayid 3 name ad 3 description bad ad code sigma widget id 789adunitarr arrayad 1 ad 2 ad 3and i want to check that a random ad i got from a function exists in the array the code to get the ad looks like this fixture new adgroupfixturesetadsadunitarandad fixturegetrandomadnow i want to check if the array contains the random ad i received what i was able to do like thisthisassertequalsin arrayrandad adunitarr 1 check if ad in arraybut my question is is there an assert or some other way to check this thing better than the way i did it i tried using assertarrayhaskey but i got the following errorphpunit framework exception argument 1 no value of phpunit framework assertassertarrayhaskey must be a integer or stringany idea please thx,['php'] +951353,why is negative margin not working when you click resume some text comes in from the left this is because i gave negative margin to the text initiallybut negative margin of intro page gives no effectwhat i want is thatwhen i click resume page text of resume should come in from left this works and text of intro page should go out to the right this does not work negative margin of intro page does not seem to be working why is thatinitially page should be empty except the two links currently intro page page is shown resume page is hidden properly as desiredin short everything about resume page works perfectly i want the exact same things to happen to intro pagefunction clicked resumeonscreen var resume documentgetelementbyidresume page ifonscreen 1 resumeclassname clicked about0 else ifonscreen 0 resumeclassname unseen function clicked aboutonscreen var about documentgetelementbyidintro page ifonscreen 1 aboutclassname clicked resume0 else ifonscreen 0 aboutclassname unseen intro pageunseenthisplay blockmarginright 200pxintro pagemarginright 0pxthisplay blockwebkittransition marginright 15s easeintransition marginright 15s easeinresume pageunseenthisplay blockmarginleft 600pxresume pagemarginleft 0pxthisplay blockwebkittransition marginleft 10s easeintransition marginleft 10s easein h2 classtitle barullispan onclick clicked about1aboutspanlilispan onclickclicked resume1resumespanliulh2 div idintro page classunseenp idintro main text i enjoy reading swimming jogging painting and exploring pfigure classintro pic1 img srcimgawardjpg altreceiving award height50 figcaptionaward 2015figcaptionfiguredivdiv idresume page classunseenpmy resumepdiv,"['javascript', 'html', 'css']" +951371,concat data binding and static text in c so i have a textbox with a data binding to it but i want to add static text in my xaml codetextblock textbinding preptimetextblockthis will only show the number of minutes i want it to be thisplayed as preparation time 55 minutes public string preparation get return preparation time preptime minutes i know i can use a getter for this which would be a clean solution but there has to be a way to write this directly into my xamlthanks in advance,['c#'] +951452,is it possible to make an inputtext to require either an email or a tel i made an input typetext placeholderphone or email requiredrequired and i was just wondering if i can make it so that it would require either a valid email or a number,"['javascript', 'html']" +951583,how find package in cmake with a custom path for opencv framework in ios i have cmake 30 and my own ios project in c that use opencv as dependency that project generate a group of libraries loaded by and application projectin my cmake i try to look for opencv dependency it automatically in windows and linux but in android ios i have to set the correct package with android setting opencv dirsdknativejni works property with this codesetopencv dir not found cache path path to use opencvifopencv dir strequal not found find package opencv paths opencv dir messagefatal error warning install and configure path to prebuilt opencvconfigcmakeendifin ios this doesnt work i usually create project xcode project without find opencv and then i drag and drop the framework and configure manually variable framework search path with a custom path in userspiperomanlibrariesopencv249iosbut using the cmake code doesnt find itwhat is the problem locating the framework,"['c++', 'ios']" +951586,what is an alternative to pch in swift i was wondering what could be used instead of pch in swiftis there any alternative to pch or way to get rid of import in swift so that we do not need to do this for all classesi do not want to carry aroundimport all the time what could be the best substitute of pch in swift,['ios'] +951611,detect button click in table view ios xcode for multiple row and section i want to detect the button click on table view with multiple row and section i was able to acheive it on case of single row but i got trouble that it didnt detect correct section i got trouble to detect which section button has user clicked below is the updated code after problem is being solved property strongnonatomic nsmutablearray quantityarray property strongnonatomic nsmutablearray rows synthesize quantityarrayrows voidviewdidload super viewdidload quantityarray nsmutablearray alloc init self pluminusfunction uitableviewcell tableviewuitableview tableview cellforrowatindexpathnsindexpath indexpath if addbtnclicked minusbtnclicked celblcounttext quantityarray objectatindexindexpathsection1objectatindexindexpathrow addbtnclicked no minusbtnclicked no else celblcounttext quantityarray objectatindexindexpathsection1objectatindexindexpathrow cellbtnminustag indexpathrow cellbtnplustag indexpathrow celblcounttag indexpathrow cellbtnplus addtargetself actionselectoradditem forcontroleventsuicontroleventtouchupinside if celblcounttext integervalue0 cellbtnminus addtargetself actionselectordeleteitem forcontroleventsuicontroleventtouchupinside return cell pragma mark pluys minus buttonvoid pluminusfunction for int j0 j itemarr count j rows nsmutablearray alloc init for int i0 i itemarr objectatindexj objectforkeyitemlistcount i rows insertobject0 atindexi quantityarray insertobjectrows atindexj self sumpragma mark uibutton selectorvoidadditemuibuttonbutton cgpoint touchpoint button convertpointcgpointzero toviewselftableview nsindexpath clickedbuttonindexpath selftableview indexpathforrowatpointtouchpoint nsinteger row clickedbuttonindexpathrow nsinteger section clickedbuttonindexpathsection nsinteger labeltext quantityarray objectatindexsection1objectatindexrowintegervalue1 nsmutablearray subarray quantityarray objectatindexsection1 subarray replaceobjectatindexrow withobject nsstring stringwithformatldlonglabeltext quantityarray replaceobjectatindexsection1 withobject subarray addbtnclicked yes nsindexpath rowtoreload nsindexpath indexpathforrowrow insectionsection nsarray rowstoreload nsarray arraywithobjectsrowtoreload nil selftableview reloadrowsatindexpathsrowstoreload withrowanimationuitableviewrowanimationnonevoiddeleteitemuibuttonbutton cgpoint touchpoint button convertpointcgpointzero toviewselftableview nsindexpath clickedbuttonindexpath selftableview indexpathforrowatpointtouchpoint nsinteger row clickedbuttonindexpathrow nsinteger section clickedbuttonindexpathsection nsinteger labelvalue quantityarray objectatindexsection1objectatindexrowintegervalue if labelvalue1 nsinteger labeltext quantityarray objectatindexsection1objectatindexrowintegervalue1 nsmutablearray subarray quantityarray objectatindexsection1 subarray replaceobjectatindexrow withobject nsstring stringwithformatldlonglabeltext quantityarray replaceobjectatindexsection1 withobject subarray addbtnclicked yes nsindexpath rowtoreload nsindexpath indexpathforrowrow insectionsection nsarray rowstoreload nsarray arraywithobjectsrowtoreload nil selftableview reloadrowsatindexpathsrowstoreload withrowanimationuitableviewrowanimationnone i want to acheive as image belowbelow link give solution to my problem toodetecting which uibutton was pressed in a uitableview,"['ios', 'objective-c']" +951617,python requests ssl handshake failure every time i try to dorequestsgethttpsurl i got this messageimport requests requestsget traceback most recent call last file stdin line 1 in module file usrlibpython27thistpackagesrequestsapipy line 55 in get return requestget url kwargs file usrlibpython27thistpackagesrequestsapipy line 44 in request return sessionrequestmethodmethod urlurl kwargs file usrlibpython27thistpackagesrequestssessionspy line 455 in request resp selfsendprep send kwargs file usrlibpython27thistpackagesrequestssessionspy line 558 in send r adaptersendrequest kwargs file usrlibpython27thistpackagesrequestsadapterspy line 385 in send raise sslerrore requestsexceptionslerror errno 1 sslc510 error14077410ssl routinesl23 get server hellosslv3 alert handshake failurei tried everythingupdate my requestsupdate my ssl but nothing changesi am using python 276 cannot change this,['python'] +951735,plot two ranges yaxis in a morrisjs line chart i have two series with different range and i am trying to plot it in two ranges with different scale on two yaxis of line chart morrisjs is that possible i only can see one serie1 because serie 2 is plotted in value 0 because the numbers are smaller than serie 1 new morrisline element dest datadata xkey date ykeys serie 1serie 2 labels labels,"['javascript', 'jquery', 'html']" +951816,where is the visual studio html designer where is the visual studio html designer i see that there are options for the html designer but i cannot open itso i just want to ask why i cannot find the designer and how do i open it when i create an html file it just goes to the html code,['html'] +951873,c enumerabletake with default value what is the best way to get exactly x values from an enumerable in cif i use enumerable take like thisvar mylist enumerablerange010var result mylisttake20the result will only have 10 elementsi want to fill the missing entries with a default valuesomething like thisvar mylist enumerablerange010var result mylisttakeordefault20 defaultint is there anything like thisis there such a function in c and if not what would be the best way to achieve this,"['c#', '.net']" +952012,aspnet identity using password and azure active directory authentication i am building an aspnet mvc 5 web site using aspnet identity owin and want to support both traditional usernamepassword authentication as well as authentication against azure active directory this app does not need to authenticate against microsoft ids live ids facebook twitter or any of the other external providers the closest so question i found is this one how to do both azure active directory single sign on and forms authentications on aspnet mvci have looked at the samples that get created when you create a project using the individual user accounts option as well as the work and school accounts option in vs 2015 i have authentication working well individually it is only when i try to combine them that i am running into problemsin my startup authcs file i am configuring owin like this public void configureauthiappbuilder app appsetdefaultsigninasauthenticationtypecookieauthenticationdefaultsauthenticationtype appusecookieauthenticationnew cookieauthenticationoptions appusecookieauthenticationnew cookieauthenticationoptions authenticationtype defaultauthenticationtypesexternalcookie loginpath new pathstringaccountsignin appuseopenidconnectauthentication new openidconnectauthenticationoptions clientid clientid authority authority tokenvalidationparameters new systemidentitymodeltokenstokenvalidationparameters validateissuer false notifications new openidconnectauthenticationnotifications securitytokenvalidated context return taskfromresult0 authorizationcodereceived context return taskfromresult0 authenticationfailed context contextowincontextresponseredirecthomeerror contexthandleresponse suppress the exception return taskfromresult0 this configuration works for password authentication but does not work for aad authentication to enable aad authentication i need to either comment out the line setting the authenticationtypeauthenticationtype defaultauthenticationtypesexternalcookieor just set cookieauthentication with no valuesappusecookieauthenticationnew cookieauthenticationoptions i would guess that there is a relatively simple approach to this and would appreciate some ideas on where to start looking,['c#'] +952139,is a function hoisted if it is defined within an if condition so suppose i have something like thisvar x 1 if function f x typeof f xthis outputs 1undefined i thought it should have output 1function because function f should have been hoisted above the if this is clearly not the case why i thought function declarations and bodies were always hoisted to the top of the scope,['javascript'] +952164,bottom layout on a navigation drawer android trying to add a footer to a navigation drawer that consists of two lists i am not doing this right i understood that anything that i want in the navigation drawer should be encapsulated in the linearlayout androidididleft drawer layouti would like to add a bottom layout that does not depend on listview scroll i tried different versions of where to add the bottom layout code but nothing happens i need an extra eye please thank youandroidsupportv4widgetdrawerlayout xmlnsandroid androidididdrawer layout androidlayout widthfill parent androidlayout heightmatch parent androidbackgroundandroidcolorwhite linearlayout androidlayout widthmatch parent androidlayout heightfill parent androidorientationvertical include androidididtoolbar layoutlayouttoolbara framelayout to thisplay fragments framelayout androidididframe container androidlayout widthmatch parent androidlayout height0dp androidlayout weight1 linearlayout listview to thisplay slider menu linearlayout androidididleft drawer layout androidlayout widthdimennavigation drawer max width androidlayout heightmatch parent androidlayout gravitystart androidorientationvertical framelayout androidlayout widthmatch parent androidlayout height48dp androidbackgroundcolorlist background button androidididrefreshbtn androidlayout widthmatch parent androidlayout height48dp androidtextstringrefresh androidvisibilitygone edittext androidididsearchmenutxt androidlayout widthmatch parent androidlayout height48dp androidbackgroundcolorlist background pressed androiddrawableleftdrawablesearch web androiddrawablepaddingdimenactivity horizontal margin androiddrawablestartdrawablesearch web androidfocusablefalse androidfocusableintouchmodetrue androidhintstringsearch androidpaddingleft8dp androidsinglelinetrue androidtextcolorhintandroidcolordarker gray androidtextsizedimentext size 14edittext button androidididclearbtn androidlayout width24dp androidlayout height24dp androidlayout gravityrightcenter androidbackgrounddrawablemob clear androidpaddingright8dp androidvisibilityinvisible framelayout linearlayout androidididleft drawer androidlayout widthmatch parent androidlayout heightmatch parent androidorientationvertical listview androidididactivechatslist androidlayout widthdimennavigation drawer max width androidlayout heightwrap content androidlayout gravitystart androidbackgroundcolorlist background pressed androidchoicemodesinglechoice androiddividerdrawablelist divider androiddividerheight1dp androidfadescrollbarsfalse androidfastscrollenabledfalse listview androidididdrawerlistview androidlayout widthdimennavigation drawer max width androidlayout heightmatch parent androidlayout gravitystart androidbackgrounddrawablelist selector androidchoicemodesinglechoice androiddividerdrawablelist divider androiddividerheight1dp androiddrawselectorontoptrue androidfastscrollenabledfalse androidminheight250dp linearlayout androidlayout widthfill parent androidlayout heightwrap content androidlayout weight1 androidlayout alignparentbottomtrue button androidididcancelbutton androidlayout widthwrap content androidlayout heightwrap content androidtextaprofile linearlayout linearlayout linearlayoutandroidsupportv4widgetdrawerlayout,['android'] +952189,is jacksons jsonsubtypes still necessary for polymorphic deserialization i am able to serialize and deserialize a class hierarchy where the abstract base class is annotated with jsontypeinfo use jsontypeinfoidminimal class include jsontypeinfoasproperty property classbut no jsonsubtypes listing the subclasses and the subclasses themselves are relatively unannotated having only a jsoncreator on the constructor the objectmapper is vanilla and i am not using a mixinjackson documentation on polymorphicdeserialization and type ids suggests strongly i need the jsonsubtypes annotation on the abstract base class or use it on a mixin or that i need to register the subtypes with the objectmapper and there are plenty of so questions andor blog posts that agree yet it works this is jackson 260so am i the beneficiary of an asyetundocumented feature or am i relying on undocumented behavior that may change or is something else going on i am asking because i really do not want it to be either of the latter two but i gots to knowedit adding code and one comment the comment is i should have mentioned that all the subclasses i am deserializing are in the same package and same jar as the base abstract classabstract base classpackage soimport comfasterxmljacksonannotationjsontypeinfojsontypeinfo use jsontypeinfoidminimal class include jsontypeinfoasproperty property classpublic abstract class polybase public polybase override public abstract boolean equalsobject obja subclass of itpackage soimport orgapachecommonslang3builderequalsbuilderimport comfasterxmljacksonannotationjsoncreatorimport comfasterxmljacksonannotationjsonpropertypublic final class suba extends polybase private final int a jsoncreator public subajsonpropertya int a thisa a public int geta return a override public boolean equalsobject obj if null obj return false if this obj return true if thisgetclass objgetclass return false suba rhs suba obj return new equalsbuilderappendthisa rhsaisequals subclasses subb and subc are the same except that field a is declared string not int in subb and boolean not int in subc and the method geta is modified accordinglytest classpackage so import javaioioexceptionimport orgapachecommonslang3builderequalsbuilderimport orgtestngannotationstestimport static orgassertjcoreapiassertionsimport comfasterxmljacksonannotationjsoncreatorimport comfasterxmljacksonannotationjsonpropertyimport comfasterxmljacksondatabindobjectmapperpublic class testpoly public static class testclass public polybase pb1 pb2 pb3 jsoncreator public testclassjsonpropertypb1 polybase pb1 jsonpropertypb2 polybase pb2 jsonpropertypb3 polybase pb3 thispb1 pb1 thispb2 pb2 thispb3 pb3 override public boolean equalsobject obj if null obj return false if this obj return true if thisgetclass objgetclass return false testclass rhs testclass obj return new equalsbuilderappendpb1 rhspb1 appendpb2 rhspb2 appendpb3 rhspb3 isequals test public void jackson should or should not deserialize without jsonsubtypes arrange polybase pb1 new suba5 pb2 new subbfoobar pb3 new subctrue testclass sut new testclasspb1 pb2 pb3 objectmapper mapper new objectmapper act string actual1 null testclass actual2 null try actual1 mapperwritevalueasstringsut catch ioexception e faildid not serialize e try actual2 mapperreadvalueactual1 testclassclass catch ioexception e faildid not deserialize e assert assertthatactual2isequaltosut this test passes and if you break at the second try line you can inspect actual1 and seepb1clasubaa5 pb2clasubbafoobar pb3clasubcatrueso the three subclasses got properly serialized each with their class name as id and then deserialized and the result compared equal each subclass has a value type equals,['java'] +952303,how to get the browser border to lock to a div when resizing i am looking at this 3 fixedcolumn css layout on i want to use this layout however i would like to change the way it behaves when i resize the browserwhen the browser is open nice and wide the columns are centered nicely on the pagethen we reduce the width of the browser and it locks to the left side of the leftmost column like thiswhat i would like to do is change the css or javascript if necessary so that the browser locks to the left side of the middle column instead when the browser becomes too narrowi am not sure how to achieve this though can anyone suggest how to change the code and most importantly why your solution worksedit for those reading this question i marked salem ouerdanis answer as the correct one because he was the first to answer with a solution that worked the particular way i wanted however it became clear that people were interpreting the question in slightly different ways so it is worth reading through because there are some really great answers which might suit your situation better please upvote them as such,"['javascript', 'jquery', 'html', 'css']" +952318,is it possible for uistackview to scroll let us say i have added more views in uistackview which can be thisplayed how i can make the uistackview to scroll,['ios'] +952366,mysql select multiple rows within a row i want something like this not sure if my syntax is correct thoughi will be executing this with phpselect acolumn1 acolumn2 bcolumn1 ccolumn1 if acolumn3 not null then select ccolumn1 ccolumn2 ccolumn3 dcolumn1 from table d d inner join table c c on dcolumn1 ccolumn1 and ccolumn4 1 where dcolumn2 acolumn3 end iffrom table a a inner join table b b on acolumn1 bcolumn1 and bcolumn2 1 inner join table c c on acolumn1 ccolumn1 and ccolumn2 1where acolumn1 10 and bcolumn3 1 and ccolumn3 0order by acolumn1 ascso the output will be something like thisit would be ok if it has multiple rows with the same data on the first few columns something like thisgrey area is from the outer select and white area is from the inner selectnote that both outer and inner select statement has table c if without the if statement can i do thisselect acolumn1 acolumn2 bcolumn1 ccolumn1 column1 column2 column3 dcolumn1 from table a a inner join table b b on acolumn1 bcolumn1 and bcolumn2 1 inner join table c c on acolumn1 ccolumn1 and ccolumn2 1 left join table d d on acolumn3 dcolumn2 inner join table c cc on dcolumn1 column1 and column4 1where acolumn1 10 and bcolumn3 1 and ccolumn3 0order by acolumn1 ascit kinda feels wrong to mewhat if i use fetch associs it even possible to do this in one query,"['php', 'mysql', 'sql']" +952405,put new rows at the specific position of the jquery datatable defaulti create ajax datatable which rows are sometimes filled by json in the end of table jsfiddle and sometimes in the top of table it depends of time of ajax responserecommended outputi have two input jsons from two different sources and output is this tabletable trtd1tdtd2tdtd3tdtr trtd1tdtd2tdtd3tdtr trtd1tdtd2tdtd3tdtr trtd1tdtd2tdtd3tdtr trtd1tdtd2tdtd3tdtr trtd8tdtd7tdtd6tdtr inserted row trtd8tdtd7tdtd6tdtr inserted row trtd8tdtd7tdtd6tdtr inserted row trtd8tdtd7tdtd6tdtr inserted row trtd1tdtd2tdtd3tdtr trtd1tdtd2tdtd3tdtr trtd1tdtd2tdtd3tdtrtablerows from 2 json are inserted in table created from 1 json to specific position this position is constant lengths of 1 and 2 json data are constantfirst solutioni have to add first column containing a number and sort the datatable descending by it jsfiddle i can hide first column jsfiddle but i rather use custom function because it does not work in ie8var t tab1datatable ajax data1json columndefs classname hide targets 0 columns data id data cat1 data cat2 data cat3 ajax type get url data2json contenttype applicationjson charsetutf8 datatype json success function response trowsaddresponsedata tdraw idea custom functioni try to create custom function rowsaddinpositionrows position but it works as function rowsaddi copied and modified function rowsadd found in jquerydatatablesjs at line 7879 i changed outpush to outsplice splice docs i know it is not recommended better is extend datatables api api register rowsaddinposition function rows position var newrows thisiterator table function settings var row i ien var out for i0 ienrowslength iien i row rowsi if rownodename rownodenametouppercase tr rowsadd use outpush outpush fnaddtr settings row 0 changed to outsplice outsplice position 0 fnaddtr settings row 0 else outsplice position 0 fnadata settings row consolelogout return out 1 return an apirows extended instance so rowsnodes etc can be used var modrows thisrows 1 modrowspop modrowspushapply modrows newrowstoarray return modrows it would be great if you could help mei found similar questions so link function fnadata in version 19 datatablesso link add multiply rows to end of datatableso link no answerdatatables forum link old version no answer i thinkeditthank you davidkonrad but i test it in jsfiddle and i found 2 problems ordering is wrong 21 not 12 i think easy problemsometimes this added rows are on the top of table sometimes in right position randomly maybe big problemi debug it in jsfiddle and its behaviour is very strangeconsolelogrowcount rowcountif rows are on the top bad position returnrowcount 0rowcount 1and for did not loop because firebug does not show var iif they are in good position returnrowcount 5rowcount 6and for looped and var i returned in this example1 loop i 5 i 4 i 32loopi 6 i 5 i 4 i 3did i missed something why order is strange,"['javascript', 'jquery']" +952515,android justify spanable textview that support rtl languages i need to create a custom textview in android first of all it should be justified then it should support spans and although it should support rtl right to left languages for ex farsi persian i am working on this issue for a week but in fact i stuck in a bad condition because non of available libraries support all these conditions justify spanable rtl do you have any ideai although checked lots of libraries for ex link,['android'] +952748,can you pass a variable into the c compiler code heres my current situation i have an application that compiles c code taken in as a string using codedom i have a securestring that stores a password and i was wondering if there would be any way to pass that securestring variable into the compiled code as a securestringhere is some example codesecurestring securepassword getsecurepastring codestring using system using systemsecurity namespace someprogram class myclass static void mainstring args securestring securepass new securestring somehow set this equal to the securepassword variable compiler codecodedomprovider codeprovider codedomprovidercreateprovidercsharpstring outfile outputexe systemcodedomcompilercompilerparameters parameters new compilerparametersparametersgenerateexecutable trueparametersoutputassembly outfilecompilerresults results codeprovidercompileassemblyfromsourceparameters codestringi cannot find a way to do this and i imagine that this is not actually possible and instead i should possibly just store the password in an encrypted file and read it from that,['c#'] +952756,android collapsingtoolbarlayout collapse listener i am using collapsingtoolbarlayout alongside with appbarlayout and coordinatorlayout and they are working fine alltogether i set my toobar to be fixed when i scroll up i want to know if there is a way to change the title text of the toolbar when collapsingtoolbarlayout it is collapsed wrapping up i want two different titles when scrolled and when expandedthank you all in advance,['android'] +952919,nosuchmethoderror writing avro object to hdfs using builder i am getting this exception when writing an object to hdfsexception in thread main javalangnosuchmethoderror orgapacheavroschemaparserparseljavalangstringljavalangstringlorgapacheavroschema at comblahsometypeclinitsometypejava10the line it is referencing in the generated code is thispublic class sometype extends orgapacheavrospecificspecificrecordbase implements orgapacheavrospecificspecificrecord public static final orgapacheavroschema schema new orgapacheavroschemaparserparse and the call in my code is thisval sometypebuilder sometypenewbuilder setsomefieldsome value set a whole load of other fieldscalling newbuilder in test code causes no issues at allthe jar is being run on an hdfs node using the hadoop jar commandany ideas what might be going wrong here,['java'] +952956,is it possible to send a reason for jasmine 2 specs skipped with xit or pending when we find a bug with one of our protractor jasmine2 specs we usually want to skip the test until the bug has been resolved i know how to do this with xit or pending and jasminereporters terminalreporter is doing a nice job of color highlighting and listing pending specshowever the pending tests always report no reason given which implies it is possible to give a reason for the skipped test i currently comment the spec with an issue number but it would be really nice to report the reason the test was thisabled and the issue number updateas requested adding example terminal output fdescribe on an example so reporting most of the suite thisabled versionsprotractor 210 and jasmine 231using xit skipped will thisplay the platform if available success 85 specs 0 failures 1 skipped 72 thisabled in 34734spending1 will thisplay the platform if availableno reason givenusing pendingthis appears to have started marking it failed probably related to failures1 will thisplay the platform if availablemessagefailed marked pendingstackerror failed marked pendingupdated related feature requests and issues for this functionalitythere is currently a feature request to support pendingmessage outstanding for protractorjasminewd if you want to follow progress,['javascript'] +953065,c standard container and stl container in c recently i am working on a c project that i am not allowed to use standard template library or any other templatesi am kinds of confused after i did some research what are the containers belongs to standard library while others belongs to standard template library or we do not say container for standard library do weis vector a container or not is vector a class for standard library or it belongs to stli am hoping to implement a list of some structure in standard library can i use list or vector,['c++'] +953139,how to get inline function definitions back in chromes javascript console chromes javascript console used to have a very helpful feature where if you entered the name of any function visible in the current scope it would print the complete definition of that function essentially as described in this answer heresome time ago i think at least a couple of months could be more it stopped doing this however and entering a function name now gives a very unhelpful response likei know i can click on that line or rightclick and choose show function definition to be shown the functiondefinition in the sources tab but that is very clunky compared to the previous inline function definitions for a workflow that is typically along the lines of get the function definition copypaste into the console change a few things then overwrite the original function definitionanother trick is to add a after the function name as in jobclicked instead of jobclicked which shows the code in the console but loses all of the syntax highlighting is there any way to get the javascript console to go back to its previous behavior of thisplaying the complete function definition inline inside of the javascript console with the syntaxhighlighting intact,['javascript'] +953211,what is the purpose of nameof version 60 got a new feature of nameof but i cannot understand the purpose of it as it just takes the variable name and changes it to a string on compilationi thought it might have some purpose when using t but when i try to nameoft it just prints me a t instead of the used typeany idea on the purpose,"['c#', '.net']" +953340,php unpack as unsigned int how do i convert a binary string to an unsigned inti am doingid unpackv substrdir mid 12 41echo id brwhere v according to documentation isunsigned long always 32 bit little endian byte orderand it prints 992455690 how is this possibleupdate found this in the documentationnote that php internally stores integral values as signed if you unpack a large unsigned long and it is of the same size as php internally stored values the result will be a negative number even though unsigned unpacking was specifiedso now the question is whats the point of the v format if its identical to the signed version other than to create confusion,['php'] +953638,how to use coordinator layout with fragment as scrolling view i am trying to use a coordinator layout with an appbar layout that hosts a fragment as the scrolling view the fragment consists of a recyclerview and a bottom aligned layout holding a button like sohowever the bottom section is hidden by defaultand only shows up after i scrollfrom my activity class overrideprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main testfragment fragment testfragment getfragmentmanagerfindfragmentbytagtest if fragment null fragment new testfragment getfragmentmanagerpopbackstack fragmenttransaction fragmenttransaction getfragmentmanagerbegintransaction fragmenttransactionreplaceridfragment container fragment test fragmenttransactioncommitactivity layoutrelativelayout xmlnsandroid xmlnsapp androidlayout widthmatch parent androidlayout heightmatch parent androidsupportdesignwidgetcoordinatorlayout androidididmain content androidlayout widthmatch parent androidlayout heightwrap content androidorientationvertical framelayout androidididfragment container androidlayout widthmatch parent androidlayout heightmatch parent applayout behaviorstringappbar scrolling view behavior androidsupportdesignwidgetappbarlayout androidididappbar androidlayout widthmatch parent androidlayout heightwrap content androidthemestylethemeoverlayappcompatdarkactionbar androidsupportdesignwidgettablayout androidididtabs androidlayout widthmatch parent androidlayout heightattractionbarsize applayout scrollflagsenteralwaysscroll apptabgravityfill apptabmodefixed androidsupportdesignwidgetappbarlayout androidsupportdesignwidgetcoordinatorlayoutrelativelayoutfragment layoutrelativelayout xmlnsandroid xmlnsapp androidlayout widthmatch parent androidlayout heightmatch parent androidsupportv7widgetrecyclerview androidididrecyclerview androidlayout widthmatch parent androidlayout heightwrap content androidlayout aboveidbottomview androidscrollbarsvertical androidvisibilityvisible relativelayout androidididbottomview androidlayout widthmatch parent androidlayout heightwrap content androidlayout alignparentbottomtrue androidbackgroundd4285d applayout scrollflagsenteralways button androidididbutton androidlayout widthwrap content androidlayout heightwrap content androidtextdo something androidtextsize14sp relativelayoutrelativelayoutthe end goal here is for the fragment to have the bottom bar always on screen and the recycler view scrolling the appbar awayis this possiblethanks all,['android'] +953679,build opencv with contrib modules and java wrapper i try to build opencv on my windows 7 machine to include the contrib modules i add the opencv extra modules path in cmakegui the opencv300jar and opencv300dll are created but i can not find the java classes to use the extra modules am i missing an option in the make configuration is it possible at all to use the extra modules from java,['java'] +953681,send local notification when download completes through nsurlsession nsurlsessiondownloadtask i am using nsurlsessiondownloadtask objects on an nsurlsession to allow users to download documentsa while the app is in the background device locked i also want to inform the user that individual downloads have finished through a local notificationto that end i am triggering a local notification in the urlsessiondownloadtaskdidfinishdownloadingtourl download task delegate method however i am wondering if there might be a better place to add the code triggering a notification since the way apple explains it the download task will be passed to the system and from that i am deriving that those delegates will not be called anymore on the download tasks delegate oncea or shortly after the app is backgroundedmy question what is the best place to add the code for triggering the local notifications has anybody had any previous experience in adding this sort of a functionality to their application,"['ios', 'objective-c']" +953832,c14 initializing constexpr variables from parameter values say i have a class that that can return a constant expression through a constexpr functiontemplateint nstruct foo constexpr int bar const return n if i wanted to initialize constexpr values from foobar how should i pass a parameter of type foo i have tried these two with an example constexpr variable inside of each to test that it can be initializedtemplateint nconstexpr int byvaluefoon f constexpr int i fbar return fbartemplateint nconstexpr int byreferenceconst foon f constexpr int i fbar return fbarconstexpr int a byvaluefoo1constexpr int b byreferencefoo1but clang 37 raises an error on byreference while gcc 51 does not live demomaincpp1525 error constexpr variable i must be initialized by a constant expression constexpr int i fbar maincpp25 note in instantiation of function template specialization byreference1 requested here constexpr int b byreferencefoo1whats the difference between taking a const foo or a plain foo when bar is constexpr either way and returns a valid constant expressionwhich is right and why gcc or clang if available references to the standard would be appreciated,['c++'] +953924,how to test plpython postgresql procedures with travis ci i am trying to set up ci for some plpython postgresql procedures in travis cii have tried several ways1 with the legacy infrastructure i have tried to just assume that plpython is already installed but it had not succeedthe command psql u postgres c create extension plpythonu exited with 1001s psql u postgres d test c create language plpythonuerror could not access file libdirplpython2 no such file or directory 2 have tried to add sudo aptget update sudo aptget y install postgresqlplpython94 commands in the beginning and it was also failed because this command initiated replacement of postgressql 94 that comes already installed in the travis environment travis build3 also tried to use containerbased infrastructure with this lines in the config addons postgresql 94 apt packages postgresqlplpython94no success toowhat is the good way to test plpython procedure in travis ci,['python'] +953931,cannot unsafebitcast between types of different sizes in swift when i try to find duplicates in array i get the error cannot unsafebitcast between types of different sizes i find the duplicates following method func uniqs sequencetype t hashable where sgeneratorelement tsource s t var buffer t var added sett for elem in source if addedcontainselem bufferappendelem addedinsertelem return bufferfunc filter var arrayforsearch mp3files as string var filteredarray uniqarrayforsearch printlnfiltered array filteredarraythe method of find duplicates i knew on this link enter link description here i use xcode 6 and swift 12there is the array in this codevar mp3files arraystringfunc exportdata var generalurl anyobject var arrayfiles arraynsurl var directory filemanagerurlsfordirectorynssearchpathdirectorydocumentdirectory indomains nssearchpathdomainmaskuserdomainmask var urlfromdirectory directoryfirst as nsurl var file filemanagercontentsofdirectoryaturlurlfromdirectory includingpropertiesforkeys nil options nsdirectoryenumerationoptionsskipshiddenfiles error nil printlnfile file mp3files filemap 0lastpathcomponent filter 0pathextension mp3 printlnmp3 files mp3fileswhen i wrote this code in playground it works an example var array apple mac iphone ipad air apple air airvar filteredarray arraysetarrayprintlnfilteredarrayhow can i use it in my project,['ios'] +953975,xcode reference a framework instead of link binary with libraries when developing cocoa touch framework how can i use code from third party framework by referencing it other then including it in the link binary with libraries optioni dont want to link to binary in order to prevent symbol conflicts between hosting project and the framework project which will use the frameworkadditionally i will need the framework code to use the hosting project reference to the third party framework how can it be doneor should i take different approach for example static framework i am not familiar with the small differences of the two,['ios'] +954170,is there any equivalent for the wear remoteinputsetchoices but for the phone what i would like to achieve is quite simple to explaini want the user to pick an item by voice from a list and get the result in the app exactly like the remoteinputsetchoices which is unfortunately made for watch onlybelow is the code need to speak to the watch but i would like to achieve this feature on a phoneany idea,['android'] +954177,linq slowness materializing complex queries i have often found that if i have too many joins in a linq query whether using entity framework or nhibernate andor the shape of the resulting anonymous class is too complex linq takes a very long time to materialize the result set into objectsthis is a generic question but heres a specific example using nhibernatevar librarybookidswithshelfandbooktagquery from shelf in sessionqueryshelf join sbttref in sessionqueryshelfbooktagtypecrossreference on shelfshelfid equals sbttrefshelfid join booktag in sessionquerybooktag on sbttrefbooktagtypeid equals bytebooktagbooktagtype join btbref in sessionquerybooktagbookcrossreference on booktagbooktagid equals btbrefbooktagid join book in sessionquerybook on btbrefbookid equals bookbookid join librarybook in sessionquerylibrarybook on bookbookid equals librarybookbookid join library in sessionquerylibrarycredential on librarybooklibrarycredentialid equals librarylibrarycredentialid join lcsg in session querylibrarycredentialsalesforcegroupcrossreference on librarylibrarycredentialid equals lcsglibrarycredentialid join usergroup in sessionqueryusergroup on lcsgusergrouporganizationid equals usergroupusergrouporganizationid where shelfshelfid shelfid usergroupusergroupid usergroupid bookisdeleted bookisdrm null bookbookformattypeid null select new book book librarybook librarybook booktag booktag add a couple of where clauses thenvar result librarybookidswithshelfandbooktagquerytolisti know it is not the query execution because i put a sniffer on the database and i can see that the query is taking 0ms yet the code is taking about a second to execute that query and bring back all of 11 records so yeah this is an overly complex query having 8 joins between 9 tables and i could probably restructure it into several smaller queries or i could turn it into a stored procedure but would that helpwhat i am trying to understand is where is that red line crossed between a query that is performant and one that starts to struggle with materialization whats going on under the hood and would it help if this were a sp whose flat results i subsequently manipulate in memory into the right shapeedit in response to a request in the comments heres the sql emittedselect thistinct book4 bookid as bookid12 0 libraryboo5 librarybookid as libraryb1 35 1 booktag2 booktagid as booktagid15 2 book4 title as title12 0 book4 isbn as isbn12 0 book4 publicationdate as publicat4 12 0 book4 classificationtypeid as classifi5 12 0 book4 synopsis as synopsis12 0 book4 thumbnailurl as thumbnai7 12 0 book4 retinathumbnailurl as retinath8 12 0 book4 totalpages as totalpages12 0 book4 lastpage as lastpage12 0 book4 lastpagelocation as lastpag11 12 0 book4 lexilerating as lexiler12 12 0 book4 lastpageposition as lastpag13 12 0 book4 hidden as hidden12 0 book4 teacherhidden as teacher15 12 0 book4 modifieddatetime as modifie16 12 0 book4 isdeleted as isdeleted12 0 book4 importedwithlexile as importe18 12 0 book4 bookformattypeid as bookfor19 12 0 book4 isdrm as isdrm12 0 book4 lightsailready as lightsa21 12 0 libraryboo5 bookid as bookid35 1 libraryboo5 libraryid as libraryid35 1 libraryboo5 externalid as externalid35 1 libraryboo5 totalcopies as totalcop5 35 1 libraryboo5 availablecopies as availabl6 35 1 libraryboo5 statuschangedate as statusch7 35 1 booktag2 booktagtypeid as booktagt2 15 2 booktag2 booktagvalue as booktagv3 15 2 from shelf shelf0 shelfbooktagtypecrossreference shelfbookt1 booktag booktag2 booktagbookcrossreference booktagboo3 book book4 librarybook libraryboo5 library librarycre6 librarycredentialsalesforcegroupcrossreference librarycre7 usergroup usergroup8 where shelfbookt1 shelfid shelf0 shelfid and booktag2 booktagtypeid shelfbookt1 booktagtypeid and booktagboo3 booktagid booktag2 booktagid and book4 bookid booktagboo3 bookid and libraryboo5 bookid book4 bookid and librarycre6 libraryid libraryboo5 libraryid and librarycre7 librarycredentialid librarycre6 libraryid and usergroup8 usergrouporganizationid librarycre7 usergrouporganizationid and shelf0 shelfid p0 and usergroup8 usergroupid p1 and not book4 isdeleted 1 and book4 isdrm is not null and book4 bookformattypeid is not null and book4 lightsailready 1 edit 2 heres the performance analysis from ants performance profiler,['c#'] +954207,how to break out of twitter inapp browser in android i have a typical modern webapp regularly shared on twitteri recently noticed that when opening our webapp in the twitter internal browser localstorage is deactivated which breaks our apphow could i break out of the twitter internal browser and open the page in the default android browser,"['javascript', 'android']" +954209,resize image to certain size while retaining aspect ratio crop image if necessary ios i am using uiimagepickercontroller to choose an image from my camera roll and resizing it before uploading it to parsei want to resize an image to certain size let us say 750x10 while retaining the aspect ratio of the original image if necessary i want to crop the image i also want it to be easy to have different versions of the image full size thumbnail size right now i am resizing only the height of the image how can i achieve what i am looking forthanksnewproductviewcontrollerhinterface newproductviewcontroller uiviewcontroller uinavigationcontrollerdelegate uiimagepickercontrollerdelegate uitextfielddelegateproperty nonatomic strong uiimage imageproperty nonatomic strong uiimagepickercontroller imagepickerproperty nonatomic weak iboutlet uiimageview imageview uiimage imagewithimageuiimage sourceimage scaledtoheightfloat i heightendnewproductviewcontrollerm ibactionaddimageidsender selfimagepicker uiimagepickercontroller alloc init selfimagepickersourcetype uiimagepickercontrollersourcetypephotolibrary selfimagepickerdelegate self selfimagepickerallowsediting no self presentviewcontrollerselfimagepicker animatedno completionnil voidimagepickercontrolleruiimagepickercontroller picker didfinishpickingmediawithinfonsdictionary info nsstring mediatype info objectforkeyuiimagepickercontrollermediatype if mediatype isequaltostringnsstring kuttypeimage a photo was selected selfimage info objectforkeyuiimagepickercontrolleroriginalimage if selfimagepickersourcetype uiimagepickercontrollersourcetypecamera save the image uiimagewritetosavedphotosalbumselfimage nil nil nil selfimageview setimageselfimage self thismissviewcontrolleranimatedyes completionnil uiimage imagewithimageuiimage sourceimage scaledtoheightfloat i height float oldheight sourceimagesizeheight float scalefactor i height oldheight float newwidth sourceimagesizewidth scalefactor float newheight oldheight scalefactor uigraphicsbeginimagecontextcgsizemakenewwidth newheight sourceimage drawinrectcgrectmake0 0 newwidth newheight uiimage newimage uigraphicsgetimagefromcurrentimagecontext uigraphicsendimagecontext return newimage ibactioncreateproductidsender pfobject newproduct pfobject objectwithclassnameproduct uiimage newimage self imagewithimageselfimage scaledtoheight10f uiimage thumbnailimage self imagewithimageselfimage scaledtoheight410f nsdata imagedata uiimagejpegrepresentationnewimage 08f nsdata thumbnaildata uiimagejpegrepresentationthumbnailimage 08f pffile imagefile pffile filewithnameimagejpg dataimagedata pffile thumbnailfile pffile filewithnamethumbnailjpg datathumbnaildata newproductimagefile imagefile newproductthumbnailfile thumbnailfile newproduct setobjectpfuser currentuser forkeyuser,['ios'] +954293,how to make an uipickerview with a done button swift i am having difficulties to make an uipickerview with a done button to appear when the users taps a uitextfield this is my code so far everything builds fine but when i tap the text field the keyboard appears not the pickerclass viewcontroller uiviewcontroller uipickerviewdatasource uipickerviewdelegate iboutlet var textfield1 uitextfieldlet pickerdata 11 12 13ibaction func textbuttonsender anyobject let picker uipickerview picker uipickerviewframe cgrectmake0 200 viewframewidth 300 pickerbackgroundcolor whitecolor pickershowsselectionindicator true pickerdelegate self pickerdatasource self let toolbar uitoolbar toolbarbarstyle uibarstyledefault toolbartranslucent true toolbartintcolor uicolorred 76255 green 217255 blue 100255 alpha 1 toolbarsizetofit let donebutton uibarbuttonitemtitle done style uibarbuttonitemstyleplain target self action donepicker let spacebutton uibarbuttonitembarbuttonsystemitem uibarbuttonsystemitemflexiblespace target nil action nil let cancelbutton uibarbuttonitemtitle cancel style uibarbuttonitemstyleplain target self action donepicker toolbarsetitemscancelbutton spacebutton donebutton animated false toolbaruserinteractionenabled true textfield1inputview picker textfield1inputaccessoryview toolbaroverride func viewdidload superviewdidload do any additional setup after loading the view typically from a niboverride func didreceivememorywarning superdidreceivememorywarning thispose of any resources that can be recreatedfunc numberofcomponentsinpickerviewpickerview uipickerview int return 1func pickerviewpickerview uipickerview numberofrowsincomponent component int int return pickerdatacountfunc pickerviewpickerview uipickerview titleforrow row int forcomponent component int string return pickerdatarowfunc pickerviewpickerview uipickerview didselectrow row int incomponent component int textfield1text pickerdatarowfunc donepicker textfield1resignfirstresponder,['ios'] +954348,nosetoolseq vs assertequal the problemweve been using nose test runner for quite a whilefrom time to time i see our tests having eq callseq actual expectedinstead of the commonselfassertequalactual expectedthe questionis there any benefit of using nosetoolseq as opposed to the standard unittest frameworks assertequal are they actually equivalentthoughtswell for one eq is shorter but it has to be imported from nosetools which makes the tests dependent on the test runner library which can make it more difficult to switch to a different test runner say pytest on the other hand we are also using istest nottest and attr nose decorators a lot,['python'] +954361,do the point collections on net charts have an upper limit i am new to the charting functions in nets systemwindowsformsdatavisualizationcharting library during my exploratory prototyping i created a chart to which i can add random points change the chart type etc but i noticed that every time i add more than 34998 points to the chart regardless of which type of chart type i use the entire chart thisappears and is replaced with a big x no exception is thrown and it does not appear to be a limitation of the point collection itself if i step through the code when adding the 349th point it gets added to the collecion just fine but as soon as the chart gets repainted it immediately gets replaced with the xi realize that this is a large number of points to have on a chart in the first place and i plan to look at some decimation techniques to downsample my input data but i was just wondering if there is a hard limit at this number and which module in the system is the actual constraint dataset drawing canvas etc i could not find any mention of it in the documentation does anyone know of such a limit,"['c#', '.net']" +954516,bordereffect binding leak memory but borderbackground does not using updated net 40 i found a strange memory leak that can be reproduced by following sample code appxml has some application wide resources that bind to properties in appxmlcs the resource that create leak is a dropshadoweffect whose color dependency property is bound to a property in app objectthe main window has a button to launch a leakwindow in which resources defined in appxml are usedwhen the leak window is closed it is not garbage collected thisonly happen if the leak window use above mentioned dropshadoweffect resource does not happen on a solidcolorbrush whose color is also bound to the same sourcereally appreciate if someone can tell me why this leak happens on the dropshadoweffect but not on the solidcolorbrushappxmlapplication xclasswpfsimpleapp xmlns xmlnsx applicationresources this one make gc unable to collect leakwindow dropshadoweffect xkeyappdropshadowcolor colorbinding sourcexstatic applicationcurrent pathdropshadowcolor modeoneway this one does not leak solidcolorbrush xkeyappbackground colorbinding sourcexstatic applicationcurrent pathdropshadowcolor modeoneway applicationresourcesapplicationappxmlcs start mainwindow and implements inotifypropertychanged for the property dropshadowcolor public partial class app application inotifypropertychanged protected override void onstartupstartupeventargs e baseonstartupe start main window var mainwindow new mainwindow mainwindowshow private color dropshadowcolor colorsblue public color dropshadowcolor get return dropshadowcolor set dropshadowcolor value onpropertychangeddropshadowcolor public event propertychangedeventhandler propertychanged protected virtual void onpropertychangedstring propertyname propertychangedeventhandler handler propertychanged if handler null handlerthis new propertychangedeventargspropertyname mainwindowxml and mainwindowxmlcs has a button to create a leakwindow shown belowvar win new leakwindow owner thiswinshowthere is also another button to do gccollectleakwindowxmlwindow xclasswpfsimpleleakwindow xmlns xmlnsx titleleak height300 width300 grid leak border width200 height200 borderthickness1 borderbrushblack effectstaticresource appdropshadowcolor no leak if comment out above and uncomment below border width200 height200 borderthickness1 borderbrushblack backgroundstaticresource appbackground gridwindowleakwindowxmlcs public partial class leakwindow window public leakwindow initializecomponent leakwindow debugwritelineleakwindow finalized updatemy search show this might be related todynamicresourcestaticresource cause memory leaks but that one is patched early in net 35kb967328 also tried the walkdictionary method mentioned in that thread but no helpchange binding mode to onetime does not help eitherswitch to net 45 also patched to date and using dynamicresource does not helpfurther investigation shows the leak is caused by a eventhandler reference from dropshadoweffect to bordereffect probably a change notification due to the binding in dropshadoweffectstill what weird is why this only occurs on bordereffect but not on borderbackground workgroundadding xsharedfalse to dropshadoweffect in appxml can workaround this i can now have applicationwide defined resources but lose the memory efficiency,['c#'] +954561,index of an element in an array using java the following code in java return 1 i thought that it should return 3int array 123456 systemoutprintlnarraysaslistarrayindexof4can you help me understand how this function worksthanks,['java'] +954567,visual studio 2015 mvc 6 scaffolding switched to using iactionresult intead of actionresult i have just installed vs 2015 and i noticed a few changes in the autoscaffolding of mvc6 i am curious why microsoft made those changes as i think if they decided to do some there might be some benefits that i may not know of in vs 2013 the mvc 5 autoscaffolding always used actionresultin vs 2015 the mvc 6 autoscaffolding switched to using iactionresultin vs 2015 i notice that the microsoft team prefer not to do this anymore public class test private int i public test int i thisi i while in all generated classes i saw that they did public class test private int i public test int i i i if it is just the matter of coding style it is fine i will immediately lose my interests in known why they changed this but if there is any logical explanation behind this i cannot wait to know what that is,['c#'] +954838,micorosft edge embedded pdf how to print our site has pdfs embedded into our pages which allow the user to print them we have this working across all browsersplatforms using various techniques pdfjspdfobjectiframes etchowever when it comes to the edge none of these techniques print properly using the an iframe which i assume is using the native pdf viewer there is no print option only save as if i print using the edge toolbar i get all the html content around it i appreciate that i could hide the rest of the content using css for the print but i was hoping there would be a cleaner way using pdfjs prints the whole page not just the pdf pdf object just tells me i do not have adobe installed preumably because there is no activex supportso my questions are has anyone else worked out how to print out an embedded pdf in edge yet and if you have how,"['javascript', 'html']" +955178,swift dyld library not loaded using cocoapods i apologize for what may seem like an overly asked question but no matter how many answers to related questions i am asking none of them seem to work see in order here here here and herei am running xcode 64 with ios 8 iphone only using cocoapods many of other answers provided there seems to be a build setting or general setting that does not exist in my version of xcode yielding many conclusions not helpfulas a matter of reference i followed this cocoapods tutorial which worked with ease but it is only when i attempt to load the app onto my phone yes i have valid certificates and my other apps work just fine without using other dependencies the app immediately crashes just as it is about to loaddyld library not loaded rpathpods examplepodsframeworkpods examplepodsreferenced from privatevarmobilecontainersbundleapplicationf109a3773ea448c29042cb6c384c9f30examplepodsappexamplepodsreason image not foundlldb see here where i named my app examplepodsand then here is my folder structure opened in workspace mode note that there is only 3 dependenciesthen see general settings and build settingsi am at a complete loss help is much appreciated,"['ios', 'iphone']" +955217,python 3xs dictionary view objects and matplotlib in python 3x keys values and items return views now while views certainly have advantages they also seem to cause some compatibility issues for example with matplotlib ultimately it is with numpy as an example this and this answers on stackexchange questions work just fine with python 2x but raise an exception when executing them in python 34a minimal example would beimport matplotlibpyplot as pltd 1 2 2 10pltscatterdkeys dvalueswhich raises typeerror float argument must be a string or a number not dict values with python 34 while for the minimal example the exception is quite clear this question arises because of the same problem and here the exception is a lot less clear typeerror ufunc isfinite not supported for the input types and the inputs could not be safely coerced to any supported types according to the casting rule safewhat is the best practice to deal with this issue can we hope that in a new release of matplotlib or ultimately numpy this issue will be dealt with or should we just start to write things like listdictvalues when using matplotlib just to be sure not to run into trouble with python 3x,['python'] +955368,what to do if classes with same interface having similar but different method signature what to do if classes with same interface having similar but different method signaturelet us say i have a project to calculate different costs to get a total cost at lastin my program there is several calculator classes namely acostcalculator bcostcalculator and so on when a calculate method is invoked to calculate a cost a cost container is passed to those cost calculators too in a good scenario i can make a costcalculator interface for every cost calculatorshowever the calculation for different cost required different resources in my current program it make be likegetresource are costly method while several costs need this so do it outside calculate methodresourcea resourcea getresourcea resourceb resourceb getresourcebcostcontainer costcontainer new costcontainercostcalculator acostcalculator new acostcalculatorcostcalculator ecostcalculator new ecostcalculatoracostcalculatorcalculatecostcontainerbcostcalculatorcalculatecostcontainerccostcalculatorcalculatecostcontainer resourceadcostcalculatorcalculatecostcontainer resourceaecostcalculatorcalculatecostcontainer resourcea resourcebif the signature is exactly the same i may make a loop conveniently to do it at once however since they are similar but different i cannot even make a good interfacei am not sure if there is good ways to do so what i can think of is generalizing all calculate method to intocalculatecostcontainer costcontainer listobject resourcesany ideas thanks for answering,['java'] +955371,how do nontype template parameters get compiled i have a fair understanding of how typetemplate parameters get compiled but do nontype templates get compiled the same way for instance with a typetemplate like thistemplatetypename tclass templatedclass do something with ttemplatedclassint intclasstemplatedclasschar charclassthe above would get compiled to separate class definitions for int and charclass templatedclassint do something with intclass templatedclasschar do something with charwhen templating nontype parameters does the compiler do it the same way for instancetemplateint nclass numericclass int arrayn do something else with nnumericclass3 class3numericclass5 class5would this generate separate class definitions for each of the numeric values as belowclass numericclass3 int array3 do something else with 3class numericclass5 int array5 do something else with 5if so could not that lead to a ton of bloated compiled code if there are a significantly large number of numeric possibilities for the template parameter i could have a static array class defined with a numeric template in my core api then every time i declared an instance with a unique length value it would have to compile a new class definition for it this could lead a ridiculously large number of compiled definitions assuming my code is openendedas far as i know this is still encouraged practice does the compiler have some other way of dealing with nontype templates then or are the overheads from having it compiled this way not all that significant,['c++'] +955467,new object instantiation when using java 8 streams is there a differnce in using the following contstructs other than slightly better readability in the lattersomeliststreammapitem new newclassitemcollectcollectorstolistsomeliststreammapnewclassnewcollectcollectorstolist,['java'] +955486,binary tree genetic programming i have just got started with genetic programming and i am having issues initializing my populationi am needing a tree to represent each candidate solution the problem being i am unfamiliar with trees there are two ways of initializing that i need namely grow tree of variable size and full balanced same shape and size tree full grow 5 12 34 6 7i have initialized my tree class however i do not know how to proceed from here onwards to populate the tree either full or growpublic class tree object value tree left right public treeobject value thisvaluevalue public tree object value tree left tree right thisvalue value thisleft left thisright right getter setter for the value public object getvalue return value public void setvalueobject value thisvalue value getters setters for left right nodes public tree getleft return left public tree getright return right public void setlefttree ln left ln public void setrighttree rn right rncould anyone kindly tell me how this can be done or even just a nudge in the right directioni am trying to randomly populate the trees till a predefined depthoperators are inserted everywhere apart from leaf nodesoperands 1100 are inserted only on the leaf nodesthanks,['java'] +955488,why does hello world hello47world for this c atruebool a hello world helloworldand for this c btruebool b hello world hello47worldi am wondering how this can be and more importantly why did the c language architects choose this behavior,"['c#', '.net']" +955525,error errorsgrailsexceptionresolver concurrentmodificationexception occurred when processing request i have a grails 245 gsp page which loads two iframe iframe scrollingno srccreatelinkcontrolleradmin actionpage1 id servicecardidiframeiframe scrollingno srccreatelinkcontrolleradmin actionpage2 id servicecardidiframeafter every second reload or so i have the following problem note that this does not occur all the time on my gsp i see error 500 the console shows the following error 20150801 2141530 httpnio8080exec3 error errorsgrailsexceptionresolver concurrentmodificationexception occurred when processing request get testadminservicecardpreviewcard4b6dc4730fd3acd80astacktrace followsmessage error processing groovypageview error executing tag assetstylesheet null line method 527 dofilter in grailsappviewsadminservicecardpreviewcardgsp caused by grailstagexception error executing tag assetstylesheet null 6 docall in grailsappviewsadminservicecardpreviewcardgsp caused by concurrentmodificationexception null 1456 sort in javautilarraylist 175 sort in javautilcollections 145 filenamewithoutextensionfromartefact in assetpipelineassethelper 99 loadrequiresfortree in assetpipelinedirectiveprocessor 76 getflattenedrequirelist in 83 getdependencylist in assetpipelineassetpipeline 79 docall in assetpipelinegrailsassetstaglib closure2 6 docall in users mg documents grails ggts3 6 3 test grails app views adminservicecard previewcard gsp run closure1 10 run in users mg documents grails ggts3 6 3 test grails app views adminservicecard previewcard gsp 198 dofilter in grailsplugincachewebfilterpagefragmentcachingfilter 63 dofilter in grailsplugincachewebfilterabstractfilter 53 dofilter in grailspluginspringsecuritywebfiltergrailsanonymousauthenticationfilter 62 dofilter in grailspluginspringsecuritywebauthenticationlogoutmutablelogoutfilter 46 dofilterinternal in orggrailsjaxrswebjaxrsfilter 1142 runworker in javautilconcurrentthreadpoolexecutor 617 run in javautilconcurrentthreadpoolexecutorworker 745 run in javalangthreadedit here is the content of adminservicecardpreview gspgroovygsp import orgcodehausgroovygrailspluginsmetadatagrailspluginimport orgcodehausgroovygrailswebpagesgroovypageimport orgcodehausgroovygrailswebtaglibimport orgcodehausgroovygrailswebtaglibexceptionsgrailstagexceptionimport orgspringframeworkwebutilimport grailsutilgrailsutilclass gsp majestella adminservicecardpreview gsp extends groovypage public string getgroovypagefilename webinfgrailsappviewsadminservicecardpreviewgsp public object run writer out getoutwriter expressionout getexpressionoutregistersitemeshpreprocessmodeprinthtmlpart0createtagbody1 printhtmlpart1invoketagjavascriptg5libraryjquerypluginjquery1printhtmlpart1invoketagstylesheetasset7srcperfectscrollbarperfectscrollbarmincss1printhtmlpart2invoketagjavascriptasset8srcperfectscrollbarperfectscrollbarjqueryminjs1printhtmlpart2invoketagjavascriptasset9srcjquerycyclealljs1printhtmlpart1invoketagstylesheetasset11srcpreviewcss1printhtmlpart3invoketagcaptureheadsitemesh131printhtmlpart4createtagbody1 printhtmlpart5iftrue showcard true printhtmlpart6iftrue servicecardimageitems printhtmlpart7expressionoutprintcreatelinkcontrollerimage actiongetimage idservicecardimageitems0id absolutetrueprinthtmlpart8printhtmlpart9expressionoutprintservicecardtitleprinthtmlpart10expressionoutprintservicecardcompanynameprinthtmlpart11printhtmlpart12iftrue showdetail true printhtmlpart13loopint i 0for imageitem in servicecardimageitems printhtmlpart14expressionoutprintcreatelinkcontrollerimage actiongetimage idimageitemid absolutetrueprinthtmlpart15iprinthtmlpart16expressionoutprintrawservicecarddescriptionprinthtmlpart17printhtmlpart18invoketagcapturebodysitemesh1161printhtmlpart19public static final map jsp tags new hashmapprotected void init thisjsptags jsp tagspublic static final string content type texthtmlcharsetutf8public static final long last modified 1438521220lpublic static final string expression codec htmlpublic static final string static codec nonepublic static final string out codec nonepublic static final string taglib codec nonehow can i solve this problem,['html'] +955569,why does asmjs deteriorate performance just to see how it performs i wrote a very short asmjs module by hand which simulates the 2d wave equation using 32bit integer math and typed arrays int32array i have three versions of it all as similar as possibleordinary ie legible albeit cstyle javascriptsame as 1 with asmjs annotations added so that it passes the validator according to firefox and other toolssame as 2 except with no use asm directive at the topi left a demo at which lets you switch between modules to see the effects of using each one all three work but at different speeds this is the hotspot with asmjs annotationsfor i 0 i h i 1 i0 for j 0 j w j 1 j0 if i 0 index 1 index 0 continue if i 1 h index 1 index 0 continue if j 0 index 1 index 0 continue if j 1 w index 1 index 0 continue ucen signedheap u0 offset index 2 2 0 unorth signedheapu0 offset index w 2 2 0 usouth signedheapu0 offset index w 2 2 0 uwest signedheap u0 offset index 1 2 2 0 ueast signedheap u0 offset index 1 2 2 0 uxx uwest ueast 1 ucen 0 uyy unorth usouth 1 ucen 0 vel signedheapvel offset index 2 2 0 vel vel uxx 1 0 vel applycapvel 0 vel vel uyy 1 0 vel applycapvel 0 force signedheapforce offset index 2 2 0 signedheapu1 offset index 2 2 applycapapplycapucen vel 0 0 force 0 0 force force force forcedampingbitshift 0 signedheapforce offset index 2 2 force vel vel vel velocitydampingbitshift 0 signedheapvel offset index 2 2 vel index index 10 the ordinary javascript version is structured as above but without the bitwise operators that asmjs requires eg x0 x arrx22 etcthese are the results for all three modules on my machine using firefox developer edition v 41 and chrome version 44 in milliseconds per iterationfirefox version 41 20 ms 35 ms 60 mschrome version 44 25 ms 150 ms 75 msso ordinary javascript wins in both browsers the presence of asmjsrequired annotations deteriorates performance by a factor of 3 in both furthermore the presence of the use asm directive has an obvious effect it helps firefox a bit and brings chrome to its kneesit seems strange that merely adding bitwise operators should introduce a threefold performance degradation that cannot be overcome by telling the browser to use asmjs also why does telling the browser to use asmjs only help marginally in firefox and completely backfire in chrome,['javascript'] +955611,why does my transform snap back am trying to make my element stay in spot after the transition right now the translated location is where i want it but then my name snaps back onto the quote am i missing a piece of code or is there a piece of code that is making this snap back happenblockquote fontfamily open sans verdana arial sansserif fontsize 30px lineheight 60px width 100 backgroundcolor rgba0 0 0 016 rgba192 241 247 015 height 100px textalign center paddingtop 40px color white fontweight 300 fontstyle italic transition all 250ms easeinoutblockquote blockquote2 transition all 250ms easeinout fontsize 25px lineheight 35px width 90blockquote author thisplay inline marginleft 150px transition all 250ms easeinout fontfamily roboto sansserif color 838eca texttransform uppercase fontsize 20px letterspacing 2px lineheight 35px opacity 0blockquotehover blockquote2 transform translatex20px transition all 250ms easeinoutblockquotehover author opacity 1 fontweight 900 color rgb25 137 228 transform translatex200px transition all 250ms easeinoutdiv classblockquote div classblockquote2 beabeaace p classauthor jason zhangp divdiv,['css'] +955626,are there any thisadvantages using preparedstatement compared to statement i was going through differences between statement and preparedstatement in jdbc and saw so many advantages here and here with preparedstatement in comparison with statementsome of my colleague was asking why we still need statement and why it is not deprecated looking at the advantages of preparedstatementso is there any reason why we still have the statement in jdbc api,['java'] +955639,how to import my app module into myappuitests file this is my simple test caseimport xctesttestable import myapp it does not workbecause of thisclass tabbarcontrollertests xctestcase override func setup supersetup let defaults nsuserdefaultsstandarduserdefaults defaultssetobject forkey dbtabbarorderedindexeskey key is undefined because of lack of my app module defaultssynchronize continueafterfailure false xcuiapplicationlaunch func testisorderoftabssaved xcuiapplicationtabbarsbuttonscateringtap what next once i tap uitabbaritem i change the value of dbappsettingsmode so here i would like to have an access to my dbappsettingsmode property to check if it is really changed i noticed that there is one weird thing when i build my app and check what was built there is no build for my uitest target is it important,['ios'] +955712,transform the string aabsd to be 2ab3sd please help me i want to transfrom the string aabsd to be 2ab3sd someone called it was encryptionthis is how i resolve itpublic class transformstring public static void mainstring args string str aabsd stringbuilder newstr new stringbuilder char temp strcharat0 int count 0 for int i 0 i strlength i if temp strcharati count else newstrappendcount newstrappendtemp count 0 temp strcharati ifi strlength 1 newstrappendstrcharati string x stringvalueofnewstr x xreplace0 systemoutprintx but the output is2ab2sdthis result is not exactly look like i want please help me transform aabsd to 2ab3sd,['java'] +955746,convert php array from xml that contains duplicate elements up until now i have been using the snippet below to convert an xml tree to an arraya json decodejson encodearray simplexml load stringxml1however i am now working with an xml that has duplicate key values so the array is breaking when it loops through the xml for exampleusers userxuser useryuser userzuserusersis there a better method to do this that allows for duplicate keys or perhaps a way to add an incremented value to each key when it spits out the array like thisarray array users array user 1 x user 2 y user 3 z i am stumped so any help would be very appreciated,['php'] +955845,app implementing parse unity plugin crashes on android device but works fine in editor i am trying to use parse in my unity game in order to implement high scores my problem is that when i try to put the game on my android device to test it the name of the app comes up different it comes up as parseunitypushsample even though i have not changed anything besides adding the files that parse gives me to use it the build settings have not changed and it even shows that my package name is the same yet testing it on a device has this result testing it in unity 5 works fine the game loads as it should this only happens when i try to put it on a device for testingalong with it changing the app name it also crashes when opening i get a prompt that says parseunitypushsample has failed anytime i try to open it on an android deviceeditokay so i figured out a way to view some errors that occur when testing on a device i get this error unable to find unity activity in manifest you need to make sure orientation attribute is set to sensorlandscape manuallyunityeditorbuildplayerwindowbuildplayerandrun i have no idea what the issue is though since i have manually set the orientation for the activity to sensorlandscape in the android manifestxml version10 encodingutf8manifest xmlnsandroid packagecomlaserdeflectorsab androidversionname101 androidversioncode1 androidinstalocationpreferexternalusessdk androidminsdkversion10 androidtargetsdkversion22 usespermission androidnameandroidpermissioninternet usespermission androidnameandroidpermissionaccess network state usespermission androidnameandroidpermissionwake lock usespermission androidnameandroidpermissionvibrate usespermission androidnameandroidpermissionget accounts usespermission androidnamecomgoogleandroidc2dmpermissionreceive permission androidprotectionlevelsignature androidnamecomlaserdeflectorsabpermissionc2d message usespermission androidnamecomlaserdeflectorsabpermissionc2d message usespermission androidnamecomandroidvendingbilling application androidlabellaser deflector androidicondrawableapp icon androidscreenorientationsensorlandscape androidnamecomsoomlasoomlaapp androiddebuggablefalse androidisgametrueactivity androidnameunityplayeractivity intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher category androidnameandroidintentcategoryleanback launcher intentfilteractivityreceiver androidnamecomparseparsepushbroadcastreceiver androidpermissioncomgoogleandroidc2dmpermissionsend intentfilter action androidnamecomgoogleandroidc2dmintentreceive action androidnamecomgoogleandroidc2dmintentregistration category androidnamecomlaserdeflectorsab intentfilterreceiverservice androidnamecomparseparsepushservice activity androidnamecomsoomlastorebillinggooglegoogleplayiabserviceiabactivity androidthemeandroidstylethemetranslucentnotitlebarfullscreen metadata androidnamebillingservice androidvaluegooglegoogleplayiabservice applicationusesfeature androidglesversion0x020 usespermission androidnameandroidpermissionread phone state usesfeature androidnameandroidhardwaretouchscreen androidrequiredfalse usesfeature androidnameandroidhardwaretouchscreenmultitouch androidrequiredfalse usesfeature androidnameandroidhardwaretouchscreenmultitouchthistinct androidrequiredfalse manifest81015i have come to learn that this may be an issue with parse v152 although changing to v132 did not help with the issue i am facing either i will update as soon as i learn anything more815updating to v154 did not fix the issue either still having problems with the android manifest with the same error message if anyone has any idea please let me know,"['c#', 'android']" +955934,read a text file line by line in swift just started learning swift i have got my code to read from the text file and the app thisplays the content of the entire text file how can i thisplay line by line and call upon that line multiple timestextfiletxt contains the followingbanana applepearstrawberryblueberryblackcurrentthe following is what currently have if let path nsbundlemainbundlepathforresourcetextfile oftype txt var data stringcontentsoffilepath encoding nsutf8stringencoding error nil if let content data textviewtext content also if there is another way of doing this please let me know much appreciated,['ios'] +955955,short circuit evaluation of a statement with operator in c i have executed the following code in codeblocks 1005 on windows 7 int a0b0ccabprintfnadnbdncdnnabcthe output i obtained is given belowa1b0c0this makes perfect sense because of short circuit evaluationthe expression a is post increment and 0 is returned to the logical and hence the part b is not evaluated since both 0 0 and 0 1 evaluates to 0 but here arises my doubt the precedence value of operators clearly states that is having higher precedence over so my understanding was like this both a and b are evaluated and then only checks the result of expression a to come to a decision but this has not happened only a is evaluated here what is the reason for this behavior does being a sequence point has something to do with this behavior if so why we say that is having lower precedence than,['c'] +956053,reactjs animate replace how to wait for fade out before adding content to fade in i am trying to use reactcsstransitiongroup to replace content by fading out some content waiting for it to thisappear completely and then fading in new content i am using key props which was the solution to this related question so the content is being swapped out and animated the problem though is that the new content is added to the dom and takes up space in the flow from the start rather that waiting until the old content has faded out ie i can delay fading in with a transition delay but the gap where the content will fade in is there from the start since css visibilityhidden still adds space for the element in the flow using that with opacity does not help either my question is there a way to achieve the desired outcome using only css if not i presume my component will have to detect the end of the fadeout transition and only then add the new element what is the recommended react way for detecting and reacting to transitionend eventsmy code thus far jsxlet key thisstateadding addform addplaceholderreactcsstransitiongroup transitionnamefade div keykey thisstateadding thisrenderform thisrenderplaceholder divreactcsstransitiongroup cssfadeenter overflow hidden opacity 001fadeenterfadeenteractive opacity 1 transition opacity 3s easein 3sfadeleave opacity 1fadeleavefadeleaveactive opacity 001 transition opacity 3s easein,"['javascript', 'css']" +956081,viewpager swipe does not work with recyclerview i want to implement a simple swipe navigation using a viewpager with fragments that hold and manage a recyclerviewthe fragments are created and can be switched using setcurrentitem but you cannot swipe left or right to switch pages the viewpager seems to ignore any swipe gesturemy activity layoutframelayout xmlnsandroid xmlnsapp androidlayout widthmatch parent androidlayout heightmatch parent androidsupportv4viewviewpager androidididviewpager androidlayout widthmatch parent androidlayout heightmatch parent androidlayout margintopattractionbarsize androidsupportv7widgettoolbar framelayouti populate the viewpager using a fragmentpageradapter in my oncreate like soviewpager viewpager findviewbyidridviewpagerviewpageraddonpagechangelistenerthisviewpagersetadapternew fragmentpageradaptergetsupportfragmentmanager override public fragment getitemint position switch position case 0 return new dummy2fragment case 1 return new dummy2fragment default return null override public int getcount return 2 override public charsequence getpagetitleint position return dataset position 1 the fragment layout is a simple framelayout which wraps a recyclerviewframelayout xmlnsandroid androidlayout widthmatch parent androidlayout heightmatch parent androidsupportv7widgetrecyclerview androidididrecyclerview androidlayout widthmatch parent androidlayout heightmatch parent androidbackgroundcolorbackground material lightframelayoutthe adapter and the layout manager are set in the fragments oncreateviewrecyclerview recyclerview viewfindviewbyidridrecyclerviewrecyclerviewsethasfixedsizetruerecyclerviewsetadapteradapterrecyclerviewsetlayoutmanagernew gridlayoutmanagergetactivity 6 linearlayoutmanagervertical falseedit 1 i think i did not ask my question clear enoughi have a working pager with a working tablayout that is populated by a fragmentpageradapter meaning that fragments are properly created and the tab layout thisplays a clickable tab for each item every fragment in this viewpager thisplays a recyclerview with a gridlayoutmanagerhowever the viewpager does not seem to receive any swipe gesture you can change the current selected position via the tablayout but not by swiping for example from left to rightit looks like the recyclerview consumes all swipe events regardless of the layout direction which is set to verticalany ideas,['android'] +956165,how to improve performance of ucollectionview containing lots of small images in my ios app i have uicollectionview that thisplays around 1200 small 35x35 points images the images are stored in application bundlei am correctly reusing uicollectionviewcells but still have performance problems that vary depending on how i address image loadingmy app is application extension and those have limited memory 40 mb in this case putting all 1200 images to assets catalog and loading them using uiimagenamed imagename resulted in memory crashes system cached images which filled up the memory at some point the app needs to allocate bigger portions of memory but these were not available because of cached images instead of triggering memory warning and cleaning the cache operating system just killed the appi changed the approach to avoid images caching i put images to my project not to asets catalog as png files and i am loading them using nsbundlemainbundlepathforresourceimagename oftype png now the app no longer crashes due to memory error but loading of single image takes much longer and fast scrolling is lagging even on the newest iphones i have full controll over the images and can transform them for example to jpeg or optimize them i already tried imageoptim and some other options without successhow can i resolve both these performance problems at once edit 1i also tried loading images in background thread this is code from my subclass of uicollectionviewcellprivate func loadimagenamedname string thispatch asyncthispatch get global queuethispatch queue priority default 0 weak self in let image bundlepathforresourcename oftype pngcgimage if name selfthisplayedimagename thispatch asyncthispatch get main queue if name selfthisplayedimagename selfcontentviewlayercontents image this makes scrolling smooth without consuming additional memory for caching but when scrolling to some location programatically for example when uicollectionview scrolls to top it causes another problem during scrolling animation the images do not update scroll is too fast for them to load and after scrolling is finished it takes wrong images are thisplayed for fraction of second and one after another replaced with correct ones this is very thisturbing visuallyedit 2i cannot group small images into bigger composed images and thisplay those as suggested by this answerreasons consider different screen sizes and orientations there would have to be precomposed images for each of them which would make the app download huge the small images can by thisplayed in different order some of them might be hidden in some situation i surrely cannot have precomposed images for each possible combinations and orders,['ios'] +956260,stop django from creating migrations if the list of choices of a field changes i have a django core app called foocorethere are several optional pluginglike apps for example superfooin my case every plugin adds a new choice in a model charfield which belongs to foocoredjango migrations detect changes if the list of choices get changedi think this is not necessary at least one other developer thinks the sameclass activepluginmodelsmodel plugin name modelscharfieldmax length32 choicesget active pluginsthe code to get the choicesclass get active pluginsobject def iter self for item in yield itemthe core foocore gets used in several projects and every installation has a different set of plugins django tries to create useless migrations is there a way to work around this,['python'] +956405,assigning members of a pair to variables is it possible to assign the members of a pair without creating a temporary objectinclude tupleusing namespace stdpair bool int foo return make pair false 3 int main int x bool y auto z foo x zsecond y zfirst return 0in the above code the object auto z is needed to hold the pair before thissecting it but its creation might be expensive in the actual code,['c++'] +956529,how does python know what to do with the in keyword i am a bit bewildered by the in keyword in pythonif i take a sample list of tuplesdata 5 1 98385465 10 1 82087544 15 1 78788187 20 1 75751283i can do two different for in loops and get different resultsfor gwv in data print gwvthis prints each set of values on a line eg 5 1 98385465for i in data print ithis prints the whole tuple eg 5 1 98385465how does python know that by providing one variable i want to assign the tuple to a variable and that by providing three variables i want to assign each value from the tuple to one of those variables,['python'] +956776,android shared element transition between two activities does not work in my app i am trying to use the newly introduced element sharing between activities everything works like a charm if the shared element is with fixed position eg androidlayout gravitytop but the problem comes when the view is anchored my first activity looks like thisandroidsupportdesignwidgetcoordinatorlayout xmlnsandroid xmlnsapp xmlnsauto androidlayout widthmatch parent androidlayout heightmatch parent androidsupportv4viewviewpager androidididpager androidlayout widthmatch parent androidlayout heightmatch parent androidsupportdesignwidgetappbarlayout androidididappbar androidlayout widthmatch parent androidlayout heightwrap content androidsupportdesignwidgetappbarlayout androidsupportdesignwidgetfloatingactionbutton androidididplay all androidlayout widthwrap content androidlayout heightwrap content androidlayout gravitybottomright androidlayout margin24dpandroidsupportdesignwidgetcoordinatorlayoutmy second activity looks like thisandroidsupportdesignwidgetcoordinatorlayout xmlnsandroid xmlnsauto androidlayout widthmatch parent androidlayout heightmatch parent androidsupportv7widgetrecyclerview androidididlist androidlayout widthmatch parent androidlayout heightmatch parent androidsupportdesignwidgetfloatingactionbutton androidididplay androidlayout widthwrap content androidlayout heightwrap content androidlayout margin16dp androidelevation10dp androidsrcdrawableic action play autolayout anchoridappbar androidtransitionnamefab button autolayout anchorgravitybottomright androidsupportdesignwidgetappbarlayout androidididappbar androidlayout widthmatch parent androidlayout height192dp androidsupportdesignwidgetappbarlayout androidsupportdesignwidgetcoordinatorlayoutthe code i use is as followsintent intent activityoptions options activityoptionsmakescenetransitionanimationthis view fab buttonstartactivityintent optionstobundleif i use the layout anchor and layout anchorgravity attributes the transition between the two fabs is done with no animation if the second fab is with fixed position it works perfectly what am i doing wrong,['android'] +956837,vs2015 add reference for class library i have created a project in vs2015 structure as belowsolution1bookstoreclasslibrary1 class library packagebookstoreclasslibrary2 class librarybookstoreweb mvc5in bookstoreweb i can reference bookstoreclasslibrary2 but fail to reference bookstoreclasslibrary1it shows an error a reference to classlibrary1 could not be addedmy question is how to reference a class library package in vs2015 thank you so much,['asp.net'] +956875,swing jbutton is not rendering properly on solaris with java 8 i have connected to solaris 11 from my windows machine i have set thisplay to my machine and i am using java 8note this worked fine when using java 6when i am launching dialog then its button and other swing components are not getting rendered observed that it works on o windows 7 enterpriseo windows server 2012 enterprisei tried changing the lf but that did not work when i used gtklookandfeel then buttons appeared but without textlabel any help is greatly appreciated kindly let me know if any elaboration needed thankscode for my dialog is as followspackage comuiimport javaxswingswingutilitiespublic class simpledialog extends javaawtdialog private static final long serialversionuid 8298472889742780386l public simpledialogjavaawtframe parent boolean modal superparent modal initcomponents this method is called from within the constructor to initialize the form warning do not modify this code the content of this method is always regenerated by the form editor editorfold defaultstatecollapsed descgenerated codegenbegininitcomponents private void initcomponents btnskip new javaxswingjbutton btnretry new javaxswingjbutton btnabort new javaxswingjbutton jscrollpane1 new javaxswingjscrollpane lblmessage new javaxswingjtextarea btnviewlog new javaxswingjbutton setlocationrelativetonull setminimumsizenew javaawtdimension600 200 setmodalitytypejavaawtdialogmodalitytypeapplication modal setnameform noi18n setresizablefalse settitlesimple dialog addwindowlistenernew javaawteventwindowadapter public void windowclosingjavaawteventwindowevent evt closedialogevt btnskipsettextskip this step noi18n btnskipsetnamebtnskip noi18n btnskipaddactionlistenernew javaawteventactionlistener public void actionperformedjavaawteventactionevent evt btnskip clickevt btnretrysettextretry noi18n btnretrysetnamebtnretry noi18n btnretryaddactionlistenernew javaawteventactionlistener public void actionperformedjavaawteventactionevent evt btnretry clickevt btnabortsettextabort noi18n btnabortsetnamebtnabort noi18n btnabortaddactionlistenernew javaawteventactionlistener public void actionperformedjavaawteventactionevent evt btnabort clickevt jscrollpane1setnamejscrollpane1 noi18n lblmessagesetcolumns20 lblmessageseteditablefalse noi18n lblmessagesetlinewraptrue lblmessagesetrows5 lblmessagesetnamelblmessage noi18n jscrollpane1setviewportviewlblmessage btnviewlogsettextview log noi18n btnviewlogsetnamebtnviewlog noi18n btnviewlogaddactionlistenernew javaawteventactionlistener public void actionperformedjavaawteventactionevent evt open some log file javaxswinggrouplayout layout new javaxswinggrouplayoutthis thissetlayoutlayout layoutsethorizontalgroup layoutcreateparallelgroupjavaxswinggrouplayoutalignmentleading addgroupjavaxswinggrouplayoutalignmenttrailing layoutcreatesequentialgroup addcontainergap addgrouplayoutcreateparallelgroupjavaxswinggrouplayoutalignmenttrailing addcomponentjscrollpane1 javaxswinggrouplayoutalignmentleading javaxswinggrouplayoutdefault size 580 shortmax value addgrouplayoutcreatesequentialgroup addcomponentbtnskip addpreferredgapjavaxswinglayoutstylecomponentplacementunrelated addcomponentbtnretry addpreferredgapjavaxswinglayoutstylecomponentplacementrelated 87 shortmax value addcomponentbtnviewlog addgap79 79 79 addcomponentbtnabort addcontainergap layoutsetverticalgroup layoutcreateparallelgroupjavaxswinggrouplayoutalignmentleading addgroupjavaxswinggrouplayoutalignmenttrailing layoutcreatesequentialgroup addcontainergap addcomponentjscrollpane1 javaxswinggrouplayoutdefault size 149 shortmax value addpreferredgapjavaxswinglayoutstylecomponentplacementrelated addgrouplayoutcreateparallelgroupjavaxswinggrouplayoutalignmentbaseline addcomponentbtnskip addcomponentbtnabort addcomponentbtnretry addcomponentbtnviewlog addcontainergap pack editorfoldgenendinitcomponents closes the dialog private void closedialogjavaawteventwindowevent evt genfirstevent closedialog setvisiblefalse thispose genlastevent closedialog private void btnabort clickjavaawteventactionevent evt genfirstevent btnabort click thissetvisiblefalse genlastevent btnabort click private void btnretry clickjavaawteventactionevent evt genfirstevent btnretry click thissetvisiblefalse genlastevent btnretry click private void btnskip clickjavaawteventactionevent evt genfirstevent btnskip click thissetvisiblefalse genlastevent btnskip click public static void mainstring args swingutilitiesinvokelaternew runnable public void run simpledialog dialog new simpledialognew javaawtframe true dialogaddwindowlistenernew javaawteventwindowadapter public void windowclosingjavaawteventwindowevent e systemexit0 dialogsetvisibletrue variables declaration do not modifygenbeginvariables private javaxswingjbutton btnabort private javaxswingjbutton btnretry private javaxswingjbutton btnskip private javaxswingjbutton btnviewlog private javaxswingjscrollpane jscrollpane1 private javaxswingjtextarea lblmessage end of variables declarationgenendvariables,['java'] +956990,should classes with public nonvirtual destructors be marked final to close voters please help me improve the question so it gets reopened how can i improve this question so that it gets reopenedherb sutter wrote a base class destructor should be either public and virtual or protected and nonvirtualaccording to that guideline if you have a class with a public nonvirtual destructor then that class should not be used as a base class why not mark it final to enforce thatbut sutter also wrote the following implying that final need not be used re uses of final are rarer well they sort of are i donat know of many and during standardization bjarne repeatedly asked for examples of problems it solved and patterns where it should be used and i donat recall any major ones that stood outanother relevant quote implying that final should be used now that it is available is from scott meyers effective c item 7if youre ever tempted to inherit from a standard container or any other class with a nonvirtual destructor resist the temptation unfortunately c offers no derivationprevention mechanism akin to javas final classes or cs sealed classesanother data point is that the standard library has no types marked final but the reason for that seems to be to avoid breaking codethere is a similar question here but not exactly a duplicate as it misses the protected nonvirtual option default to making classes either final or give them a virtual destructor,['c++'] +957042,woocommerce shows cart is empty in firefoxafter adding the products to cart woocommerce shows cart is empty when products are addedin firefox browser after redirecting to cart page but works well in other browsers like internet explorer and chrome and thisplays the number of items in the cart in all browsersbefore redirecting to the cart pageglobal woocommercedataexplode postproductidstryfori0isizeofdatai ifdatai0 wccartadd to cartdatai1 my cart count wccartget cart contents countecho my cart countcatchexception eecho e echo script typetextjavascriptwindowlocationwccartget cart urlscriptand further if i login and do the same process everything works correctly,['php'] +957091,partially updating an entity in ef6 i am trying to figure out how to smoothly do a partial update basically a http patch of an entity using entity framework 60 but i am stumped at the number of examples out there that do not seem to work for me even those that are not obviously for another version of efwhat i would like to accomplishthe entity is updated without having to load it first ie there is only one trip to the databaseonly the properties that i touch are updated others are left as isthe closest i have gotten is neatly described by this answer to a very similar question and illustrated by the following codepublic async task updatemyentityint id int updatedproperty string otherproperty using var context new mydbcontext var entity new myentity id id contextmyentitiesattachentity if updatedproperty null entityproperty updatedpropertyvalue if stringisnulloremptyotherproperty entityotherproperty otherproperty await contextsavechangesasync now this works for simple entities but i am getting entity validation errors because i have a couple of required properties and relations that are not updated and therefore not present in the attached entity as noted i would just like to ignore thosei have debugged and verified that contextentryentitypropertye epropertyismodified changes to true when that line is run and that all the properties i never touch still return false for similar checks so i thought ef would be able to handle thisis it possible to resolve this under the two constraints above howupdatewith lsunets answer i understand somewhat what i have to do but it does not work fully the logic fails for referential propertiesconsider the following domain modelpublic class myentity public int id get set public int property get set required public string otherproperty get set required public otherentity related get set public class otherentity public int id get set public string someproperty get set now if i try to update a myentity i do the followingvar entity new myentity id 123 an entity with this id exists in dbcontextmyentitiesattachentityif updatedproperty null entityproperty updatedpropertyvalue await contextsavechangesasyncin my custom validation method overridden as in the answer below the validation error on the required property otherproperty is correctly removed since it is not modified however i still get a validation error on the related property because entityentrymemberrelated is dbreferenceentry not dbpropertyentry and thus the validation error is not marked as a false errori tried adding a separate analogous clause for handling reference properties but the entityentry does not seem to mark those as changed with relation member as dbreferenceentry relation does not have anything to indicate that the relationship is changedwhat can i check against for false errors in this case are there any other cases i need to handle specially onetomany relationships for example,['c#'] +957227,how to thisable css warning unknown property in eclipse mars i get many unknown property warnings in my css files this might be due to the fact that i have efxclipse 20 and the eclipse web developer tools installed if i open the css files with the efxclipse css editor and add suppresswarnings the warning icon changes its color see figure below howeverthe problems view still shows the warning and the default css editor shows the warning tooi do not want to add suppresswarnings since the css files are automatically generated with winless how can i thisable the unknown property warnings for specific files or at allmy css files are not located under src but under a folder help that help folder contains html files for my eclipse plugin and corresponding css files those files are not used for javafxefxclipse here is a related article that did not really help me but might give you further informationscreenshot that shows the warnings and the problem view click to enlarge,['css'] +957239,python 27 round number to nearest integer i have been trying to round long float numbers like3226890756332268907563312396694215336206896552with no success so far i tried mathceilx mathfloorx although that would round up or down which is not what i am looking for and roundx which did not work either still float numberswhat could i doedit codefor i in widthrange for j in heightrange r g b rgb imgetpixeli j h s v colorsysrgb to hsvr2550 g2550 b2550 h h 360 introundh print h debug,['python'] +957249,howto pass funcptr from c class to a c api how can i pass a dynamic generated c function as funcprt to a c apithe api exports thisdllimport void api register funcchar func name void funcptrchar char i have to create the function while runtime because i do not know about it beforeso i used a classclass jsfunc public char jsfuncname char jsparameter void runfuncchar val1 char val2 printfnjsfuncrunfunc executed jsparameters passednjsparameter and call it like thisjsfunc jsm new jsfunc jsmjsfuncname external parameter1 jsmjsparameter external parameter2 api register funcexternal parameter1 jsmrunfuncbut visualstudio 2015 tells meerror c3867 jsfuncrunfunc nonstandard syntax use to create a pointer to member vjcs cusersastrausourcereposvcjsvcjsvcjscpp 54sorry if the code is bad i am not a cc programmer but need to get this running for my daily workthanks,"['c++', 'c']" +957333,testing rake in rails multiple error raises silenced in test i have a rake task that guards against dangerous rails rake rasks based on the environment it works fine when i test each individual dangerous method in rspec the test passes when i test multiple in a row for multiple environments the test fails after the first one even if i run the test multiple times for the same dangerous action rake dbsetup for example it will only pass the first time if i run the tests as individual it statements one for each dangerous action only the first two will pass there are 4how can i get rspec to behave correctly here and pass all the tests when run in a suitethe rake task guard dangerous tasksrakeclass invalidtaskerror standarderror endtask guard dangerous tasks environment do unless railsenv development raise invalidtaskerror endendw dbsetup dbreset each do task raketasktaskenhance guard dangerous tasksendthe rspec testrequire spec helperrequire rakeload rakefiledescribe dangerous tasks do context given a production environment do it prevents dangerous tasks do allowrailsto receiveenvand returnproduction w dbsetup dbreset each do task name expect raketasktask nameinvoke to raise errorinvalidtaskerror end end end context given a test environment do it prevents dangerous tasks do allowrailsto receiveenvand returntest w dbsetup dbreset each do task name expect raketasktask nameinvoke to raise errorinvalidtaskerror end end endendrspec output we know the guard task did its job because the rake task did not actually runfailureerror expect raketasktask nameinvoke to raise errorinvalidtaskerror expected invalidtaskerror but nothing was raised,['ruby-on-rails'] +957362,how does the timeouttimelimit decorator work i found this decorator that times out a function here on stack overflow and i am wondering if someone could explain in detail how it works as the code is very elegant but not clear at all usage is timeouttimelimitfrom functools import wrapsimport errnoimport osimport signalclass timeouterrorexception passdef timeoutseconds100 error messageosstrerrorerrnoetime def decoratorfunc def handle timeoutsignum frame raise timeouterrorerror message def wrapperargs kwargs signalsignalsignalsigalrm handle timeout signalalarmseconds try result funcargs kwargs finally signalalarm0 return result return wrapsfuncwrapper return decorator,['python'] +957391,aspnet mvc 5 and webapi 2 authentication i recently built an mvc 5 web site as a front end protoype and used individual accounts for authentication i now need to build a webapi2 backend that will serve this website as well as an iphone app and multiple other clients i am confused regarding authentication with the mvc site and webapii want all user management to take place through the webapi which will use tokens so that it is client agnostic however i do not know how cookie authentication on the website side will work without my identity classes it seems like i will be duplicating code with the mvc site and webapi i want to use cookies for the mvc site and oauth tokens for the webapi do i need create another project like an identityprovider to manage this or is there a clean way to implement this using just the mvc and webapi projects thanksedit i am mainly confused about how to manage user identity with users being able to login through both the mvc site and through a webapi request i need to be able to generate the useridentity and claims in a unified way and i am confused when i have both the mvc individual accounts template and the webapi2 individual account authentication template to work with i want to store users claims etc in an aws hosted mongodb instance,['c#'] +957563,first nonnull value per row from a list of pandas columns if i have got a dataframe in pandas which looks something like a b c0 1 nan 21 nan 3 nan2 nan 4 53 nan nan nanhow can i get the first nonnull value from each row eg for the above i would like to get 1 3 4 none or equivalent series,['python'] +957576,why do the tablayouts tabs iconstexts blink when swiping between pages backgroundi have used the pagerslidingtabstrip library for a long time to show tabs above a viewpagerrecently i was tasked to set icons using selectors with selectedvsunselected states instead of texts for the tabs and so i did however it seems that the library could not handle it well showing empty tabs sometimes so i have moved to tablayout which is a part of the design library by googlethe problemi have noticed a few solutions of how to add icons to the tablayout but each of them has one or more of those issues no icons are shownicons are shown but can blink from time to time especially when using a selector for them with exitfadeduration being set or when swiping fastclicking on tabs does not change the current page of the viewpagerthe codethe code i have used is from cheesesquare sample in the mainactivityjava file it is quite basic final tablayout tablayout tablayout findviewbyidridtabs viewpager viewpager viewpager findviewbyidridviewpager tablayoutsetupwithviewpagerviewpagerthe solutions i have tried aresetting an icon for each tab and remove getpagetitle code of the adapter for int i 0 i tablayoutgettabcount i tablayoutgettabatiseticonalso tried adding setontabselectedlistener for when i did not use a selectorthis solution results in blinking effect issue 2extending tablayout to support icons or implementing tabviewprovider as shown here extending tablayout does not show icons at all issue 1 and implementing tabviewprovider has the issue of blinking icons quite rare thoughfor getpagetitle return a spannablestring that has the icon in it as shown here this did not show the icons at all for me i remember i tried other solutions too but they also had issues as i have mentionedthe questionwhat is the correct way to set icons for the tabsis there an official way to achieve this i would like to at least have a selectedunselected images for each tab the transition of when selecting is a good bonus which i have hoped to achieve as it looks nicer this waywhy do the icons blink anyway i have noticed that it occurs even for textsis there maybe a workaround,['android'] +957639,inheriting constructors w wo their default arguments c primer 5th edition on page 629 statesif a base class constructor has default arguments those arguments are not inherited i tried this for myself and to me it seems that the derived constructor generated by the compiler also has the same default arguments as the base constructorheres a little testinclude iostreamstruct base base default baseint x int y 88 int z 99 xx yy zz virtual void debug const stdcout nx x y y z z n private int x y zstruct derived base using basebaseint main base b1 bdebug x 1 y 88 z 99 derived d5 ddebug x 5 y 88 z 99 return 0 you can run this here so are we inheriting also the default arguments for a inherited constructor or notif not how come i am not getting junk for the last 2 members but the same exact values as the default argumuments for the constructor inherited from basealso searched on the internet for a clear response about this but found none,['c++'] +957883,paginating text in android i am writing a simple textebook viewer for android so i have used a textview to show the html formatted text to the users so they can browse the text in pages by going back and forth but my problem is that i can not paginate the text in androidi can not or i do not know how to get appropriate feedback from the linebreaking and pagebreaking algorithms in which textview uses to break text into lines and pages thus i can not understand where the content ends in the actual thisplay so that i continue from the remaining in the next page i want to find way to overcome this problemif i know what is the last character painted on the screen i can easily put enough characters to fill a screen and knowing where tha actual painting was finished i can continue at the next page is this possible howsimilar questions have been asked several times on stackoverflow but no satisfactory answer was provided these are just a few of themhow to paginate long text into pages in androidebook reader pagination issue in androidpaginate text based on rendered text sizethere was a single answer which seems to work but it is slow it adds characters and lines until the page is filled i do not think this is a good way to do page breakinghow to break styled text into pages in androidrather than this question it happens that pageturner ebook reader does it mostly right although it is somehow slowps i am not confined to textview and i know line breaking and page breaking algorithms can be quite complex as in tex so i am not looking for an optimal answer but rather a reasonably fast solution that can be usable by the usersupdate this seems to be a good start for getting the right answeris there a way of retrieving a textviews visible line count or rangeanswer after completing text layout it is possible to find out the visible textviewtreeobserver vto txtviewexgetviewtreeobserver vtoaddongloballayoutlistenernew ongloballayoutlistener override public void ongloballayout viewtreeobserver obs txtviewexgetviewtreeobserver obsremoveongloballayoutlistenerthis height txtviewexgetheight scrolly txtviewexgetscrolly layout layout txtviewexgetlayout firstvisiblelinenumber layoutgetlineforverticalscrolly lastvisiblelinenumber layoutgetlineforverticalheightscrolly,"['java', 'android']" +957939,aspnet 5 semantic versioning it seems that versioning works differently than in previous versions of net the projectjson seems to use semantic versioning from what i have seen online with the format majorminorpatchspecial does this replace the assembly version idea or add to it or does it just get used with nugethow does one access the version during runtime i came across nugetsemanticversion object online in the microsoftframeworkruntime package but i cannot find out how to retrieve it in codeis there a programmatic way to update this value on a build or just custom scripts,"['c#', 'asp.net']" +957947,angularuibootstrap accordion and collapse animation not working on the angularuibootstrap demodocs page the accordion and collapse directives are both animated when clicking on an itemhowever the animations do not work in the plunker demos also found on that page is some dependency missing or is it a possible bugtested in chrome firefox updatei updated to version 0143 on 20151029 and everything works great now thank you to the angularui team for all the hard work,"['javascript', 'css']" +958073,xcode 7 warnings object file was built for newer ios version than being linked i recently integrated google cloud messaging into an app targeting ios 7 and ios 8 just grabbed xcode 7 beta 4 to get started on ios 9 support and now i am getting an error from the linkerld warning object file podsgoogleinterchangeutilitieslibrarieslibprotocolbuffersadescriptorpbo was built for newer ios version 83than being linked 70and a handful more like that all for parts of libprotocolbuffersadoes this mean that ios 83 is required to use the gcm library if so why did xcode 6 happily spit out code that by all appearances in my testing with ios 7 devices delivered push notifications to ios 73 without issuegiven that they are just warnings i can still compile fine however i prefer not to ship code that is wrongedit i emailed google and they said top people will look into it in the mean time if youre reading this and bothered by the warning maybe also email so they will be encouraged to deal with it,"['ios', 'objective-c']" +958118,why requestwheninuseauthorization does not prompt the user for access to the location in my viewdidload method i have locationmanager cllocationmanager allocinit initializing locationmanager locationmanagerdelegate self we set the delegate of locationmanager to self locationmanagerdesiredaccuracy kcllocationaccuracybest locationmanager startupdatinglocation ifuidevice currentdevice systemversion floatvalue 80 locationmanager requestwheninuseauthorization and the request is called but the user is not prompted why,['objective-c'] +958174,is there a clojure equivalent of rubys tap method ruby provides the tap method which allows you to take in a variable and run code on it but then return the original variable rather than the result of your expression iedef number 5tap x print x prints 5 and returns 5endis there any function built into clojure that can provide this functionality,['ruby'] +958196,does size t foo 0 need a cast looking at this answer and knowing that 0 is an octal constantfor hexadecimal constants and octal according to the comments it is the first type the value can fit in int unsigned int long unsigned long long long unsigned long longtherefore i deduce this does not need a castsize t foo 0however due to a strict misrac lint tool i get back a message about an illegal implicit type conversion misrac2004 rule 101is my understanding wrong or is the tool in errornb i have changed to size t foo 0u as that is a lot simpler than arguing with qa but i would like to satisfy my own curiosity,['c'] +958204,ffmpeg and php to get an image out of a video and convert video to ogg i have a video hosting site and have successfully installed ffmpeg on my local server things work overall but i cannot get the video duration and do not know how to convert videos to the ogg format i can convert videos to mp4 but am unsure if the same code can also convert to oggone more thing is that i can get a thumbnail out of the video at the start of the video but i want it after 50 seconds base basenameuploadfile safe fileext new file basemp4 new image basejpg new image path live imgnew image new flv live dirnew file equire vendorautoloadphp ececute ffmpeg generate mp4 execffmpeg i uploadfile f mp4 s 896x504 new flv execute ffmpeg and create thumb execffmpeg i uploadfile f mjpeg vframes 71 s 768x432 an new image path,['php'] +958262,no http response when direct stream uploading to amazon s3 i currently have a function that grabs an mp3 file from a remote url and uploads it to an amazon s3 bucketthe function seems to work fine in that the file appears in s3 however i am concerned that while testing this on my local server using a tunnel ngrok the page does not seem to be returning any http statusit does return 200 when i download the file locally first then upload it as were dealing with large audio files i am trying to make the first idea work in that it is more efficient i thinkis there a way to make the page return a http status code and should i be concerned that it currently does nothere is the code snippet using the v2 amazon sdk in phpconfig arraykey amazon s3 keysecret amazon s3 secretregion uswest2 s3 awsfactoryconfiggets3registerstreamwrappers3putobjectarray bucket mybucket key filenamemp3 contentlength size body fopenurl r,['php'] +958367,azure publish or package fails without errors i am trying to publish or package our webrole into azure after migrating from sdk 25 to 27 25 was working fine even though i am not sure if it is relatedthis is the error i have from the build in the output window 3 build started project myprojectazure configuration production any cpu 4 publish started project myprojectazure configuration production any cpu 4cprogram files x86msbuild120binmicrosoftcommoncurrentversiontargets16975 warning msb3270 there was a mismatch between the processor architecture of the project being built msil and the processor architecture of the reference msshrtmi version2500 cultureneutral publickeytoken31bf3856ad364e35 processorarchitectureamd64 amd64 this mismatch may cause runtime failures please consider changing the targeted processor architecture of your project through the configuration manager so as to align the processor architectures between your project and references or take a dependency on references with a processor architecture that matches the targeted processor architecture of your project4 transformed webconfig using elegacymainazuremyprojectfrontwebproductionconfig into objproductiontransformwebconfigtransformedwebconfig4done building project myprojectazureccproj failed44build failed build 3 succeeded 0 failed 25 uptodate 0 skipped publish 0 succeeded 1 failed 0 skipped i have searched for an anwer and came up with this link where they state that it could be due to an outofmemoryexception and the fix is to build on a high end x64 system i am building on a core i7 16gig of ram really good computer so i do not think it comes from this i also installed the windows 7 hotfix that fixes the emulator issue from largeaddressaware switch just in case but it did not helpthank you,['c#'] +958418,get reference of cell under heightforrowatindexpath in ios 8 i am currently working on a project where i have embedded a uitableview inside uitableviewcellwhat i need to do is to thisable the uitableviews scroll and make the uitableview to fit size of all rows but as the uitableview inherits from uiscrollview the use of autolayout does not force uitableview to make the height of cell depending on its contentsize not frame when returning uitableviewautomaticdimensionios 7 solutionthis was easy achievable until ios 7 as i get the reference of the cell under heightforrowatindexpath using the code belowuitableviewcell cell tableview cellforrowatindexpathindexpathint height celltableviewcontentsizeheightreturn heightbut in ios 8 it gives bad access as ios 8 calls the heightforrowatindexpath before the cellforrowatindexpath has been calledios 8 approachdeclare a property to keep reference of the cellproperty strong nonatomic uitableviewcell prototypecelluse a method to save the current cell reference to the property in order to use it idprototypecellatindexpathnsindexpath indexpath nsstring cellid mycell if prototypecell prototypecell selftableview dequeuereusablecellwithidentifiercellid return prototypecellget uitableview of the uitableviewcell from the prototype and from its contentsize i get the height and i return it under heighforrowatindexpath from the method belowintheightforthreadatindexpathnsindexpath indexpath prototypecell self prototypecellatindexpathindexpath prototypecellcontentview setneedslayout prototypecellcontentview layoutifneeded int footer prototypecelltableview numberofsections prototypecelltableviewsectionfooterheight int header prototypecelltableview numberofsections prototypecelltableviewsectionheaderheight int height ceilf prototypecelltableviewcontentsizeheight prototypecelltableviewcontentoffsety prototypecelltableviewcontentinsetbottom prototypecelltableviewcontentinsettop header footer nslogi i intceilf prototypecelltableviewcontentsizeheight height return heightcgfloattableviewuitableview tableview heightforrowatindexpathnsindexpath indexpath return self heightforthreadatindexpathindexpathproblemthe contentsizeheight that i get back from the prototypecell is wrong and it does not match the real contentsize of the uitableview but when i log the real contentsize under customcell class it shows the correct contentsize which differs from the one under prototypecell this makes me wondering that maybe i should try to dequeue the cell at a specific state in order to get the correct contentsize but logs shows the same valuesi have been researching a lot and trying different ideas but none worked so far i do not know if anyone has tried to achieve a similar thing as me and solved this it will be really nice if you provide me an idea or something,['ios'] +958427,what happens with timers when pc wakes from sleep i have a com addin for office apps that performs an operation in the background every 30 minutes using asystemtimerstimerthis background operation performs user authentication over an internet connection and i have reports from some users that authentication fails when their pcs wake from sleep i cannot reproduce this behavior myself so my theory is that when the pc wakes the background operation executes before a connection to the internet is restored presumably the connection was closed by windows when the pc went to sleepin general if a pc goes to sleep after a period of inactivity what happens when the pc wakes in terms of timers for example is the timer paused while sleeping and then resumes at its set interval when the pc wakes eg if the timer was 10 min into the interval when the pc went to sleep the timerelapsed event would not fire until 20 min after the pc wakes is the timerelapsed event queued so that it fires immediately upon the pc waking does windows stop the timer when the pc goes to sleep or does the timer keep running while the pc sleeps but since the internet connection is broken presumably the background operation cannot perform user authentication,['c#'] +958474,what is the meaning of the operator looking into some code of a colleague of mine i came accross the followingfriend bool operatorvalueitertype const rhs valueitertype const lhsit is declared in a template classtemplatetypename typeclass valueiter public stditeratorstdbidirectional iterator tag typecan someone tell me what the symbol indicates i expect it has something to with the operator,['c++'] +958475,thisplaying markers on google map from mysql database using phpjavascript in my database i have latlng values and i am trying to thisplay markers on a google map i have my map coming up ok but cannot get the markers going selects all the rows in the tester tablequery select from tester where 1result mysql queryqueryif result dieinvalid query mysql error while row mysql fetch assocresult var marker new googlemapsmarker position php rowlat php rowlng map map titlehello world any help would be great thanks,"['javascript', 'php', 'mysql']" +958683,do caseinsensitive ordering with djangofilter is it possible to do caseinsensitive ordering by first name with djangorestframeworkhere is the codeimport django filterclass personfilterdjango filtersfilterset class meta model person fields first name lower order by first name lowerclass personviewsetbasemodelviewset queryset personobjectsall permission classes permissionsisauthenticated filter backends filtersdjangofilterbackend filter class personfilteris there an easy way to do caseinsensitive ordering with djangofilterhere djangofilter has docs for caseinsensitive search but nothing for orderingin the django docs the code is somewhat obtuse for this which makes me wonder if it exists for djangofilter or not heres the django docs code snippet on how to do it with the django orm from djangodbmodelsfunctions import lower mymodelobjectsorder bylowermyfield,['python'] +958721,static struct initialization in c99 i have encountered a strange behaviour when using compound literals for static struct initialization in gcc in c99gnu99 modesapparently this is finestruct test int astatic struct test tt 1 1 however this is notstatic struct test tt struct test 1 2 this triggers following error initializer element is not constantalso this does not help eitherstatic struct test tt const struct test 1 3 i do understand that initializer value for a static struct should be a compiletime constant but i do not understand why this simplest initializer expression is not considered constant anymore is this defined by the standard the reason i am asking is that i have encountered some legacy code written in gcc in gnu90 mode that used such compound literal construct for static struct initialization 2 apparently this was a gnu extension at the time which was later adopted by c99 and now it results in that the code that successfully compiled with gnu90 cannot be compiled with neither c99 nor even gnu99why would they do this to me,['c'] +958724,retrieve the wpa2 enterprise username in ios i have an interesting requirement that i am not sure is even possible currently i am developing an ipad app for a fleet of tablets the tablets connected to a wpa2 enterprise wifi network is it possible using objectivec or swift or c magic or whatever is necessary to get the identityusername that is connected to the wireless networki have poked around captivenetwork but it does not seem to be what i want i am not sure if there is something to cwnetwork but that seems to be mac only you can do this on android i know because i am currently doing it with the key androidnetwifiwificonfigurationenterprisefieldcan anybody help,"['ios', 'objective-c']" +958811,how do i get the right this in an arraymap i assume there is some application of call or apply here but i am not sure how to implement ita foo bar things 1 2 3 showfooforeach function thisthingsmapfunctionthing consolelogthisfoo thing ashowfooforeachsay i want to map an array but in the function i need access to the this to which foo belongs the function of map creates a new this context so i obviously need to coerse that context back in somehow but how do i do that while still having access to thing,['javascript'] +958843,xcode message from debugger got unexpected response to k packet ok i got this message when testing my app on simulatormessage from debugger got unexpected response to k packet okwhat does it mean and is my app in any sort of dangerusing xcode 64 72,['ios'] +958873,why do not cython compile logic or to expression for example here is an or expressionc f1 0 or f1 f0 thhere is the compiled c code pyx t 24 pyx v f1 0if pyx t 24 else pyx t 23 pyx t 24 goto pyx l5 bool binop done pyx t 24 pyx v f1 pyx v f0 pyx v th pyx t 23 pyx t 24 pyx l5 bool binop done pyx v c pyx t 23why not output this pyx v c pyx v f1 0 pyx v f1 pyx v f0 pyx v this the goto version faster than,"['python', 'c']" +958988,how to create renderscript scripts on android studio and make them run backgroundi want to research about creating renderscript scripts on android and renderscript in general and over the past year androidstudio became the only ide that google supports for android apps development the problemfor this i have found multiple websites as suchhow to use the renderscript support library with gradlething is all the tutorials and samples i have seen are for eclipse and they say that all i need to do is create an rs file inside the raw folder also tried in the src folder in the same folder of the mainactivityjava file and it will autogenerate the needed java files for me having a prefix of scriptc but it does not work for mewhat i have triedi have created a file from some sample i have found for eclipse called juliars heres the codepragma version1pragma rs java package namelbcommyapplicationfloat cxfloat cyfloat widthfloat heightfloat zoomint precisionuchar colorvoid rootconst uchar4 in uchar4 out uint32 t x uint32 t y float fx x 05f width 4f zoom 2f zoom float fy y 05f height 4f zoom 2f zoom float t 0 int k 0 whilek precision 1 t fx fx fy fy cx fy 2 fx fy cy fx t if fx fx fy fy 4 break k outb colork30 outg colork31 outr colork32in the java file i wanted to access the newly created file so i started to write scriptc and expected it to fill the needed extra characters but it does not i cannot for example use this piece of codemscriptnew scriptc juliamrsgetresourcesrrawjuliai have also tried to add renderscript support for older android versions but this of course did not helpdefaultconfig renderscripttargetapi 22 renderscriptsupportmodeenabled true another thing i have tried is to use newfolderrenderscript folder via the context menu of the app but then i got this errorerrorexecution failed for task appcompiledebugrenderscript comandroididecommonprocessprocessexception orggradleprocessinternalexecexception process command dappdatalocalandroidsdkbuildtools2300previewllvmrsccexe finished with nonzero exit value 1073741515the questionwhats the correct way to create and run a renderscript script on androidstudioedit sadly i have the exact same issue again and this time setting renderscripttargetapi to 18 does not help i have also tried another projects with renderscript here and here but both have the same issueserrorexecution failed for task renderscriptcompilearmdebugrenderscript comandroididecommonprocessprocessexception orggradleprocessinternalexecexception process command dandroidsdkbuildtools2301llvmrsccexe finished with nonzero exit value 1073741515i have now added a bounty to solve this issue once and for all,['android'] +959005,how can i set cg context show backtrace environmental variable i have three buttons in my view after setting the cornerradus in the viewdidload buttonlayercornerradius 20 i get the following error message in the log error cgcontextsavegstate invalid context 0x0 if you want to see the backtrace please set cg context show backtrace environmental variablequestions how can i set cg context show backtrace environmental variableor how can i fix this warningokay i have the backtrace now from the message it does not make any sense to me some help pleaseaug 7 142700 error cgcontextsavegstate invalid context 0x0 backtrace uistatusbaritemview updatecontentsandwidth33 uistatusbaritemview initwithitemdataactionsstyle477 uistatusbaritemview createviewforitemwithdataactionsforegroundstyle134 uistatusbarlayoutmanager createviewforitemwithdataactions163 uistatusbarlayoutmanager prepareenableditemtypewithenableditemswithdataactionsitemappearingitemthisappearing36 uistatusbarlayoutmanager prepareenableditemswithdataactions92 uistatusbarforegroundview setstatusbardataactionsanimated797 uistatusbarforegroundview setstatusbardataactionsanimated332 51uistatusbar preparetosetstyleanimationforced block invoke360 uiviewanimation performwithoutanimation65 uistatusbar preparetosetstyleanimationforced866 uistatusbar requeststyleattributesanimationparametersforced391 uistatusbar requeststyleanimationparametersforced437 uistatusbar requeststyleanimatedforced90 uistatusbar evaluateserverregistration250 45uiviewhierarchy postmovedfromsuperview block invoke590 uiviewhierarchy postmovedfromsuperview544 uiviewinternal addsubviewpositionedrelativeto1967 uistatusbarwindow setstatusbar288 uiapplication createstatusbarwithrequestedstyleorientationhidden340 uiapplication runwithmainscenetransitioncontextcompletion950 uiapplication workspacedidendtransaction188 fbsserialqueue performnext192 fbsserialqueue performnextfromrunloopsource45 cfrunloop is calling out to a source0 perform function 17 cfrunloopdosources0556 cfrunlooprun867 cfrunlooprunspecific488 uiapplication run402 uiapplicationmain171 main117aug 7 142700 error cgcontexttranslatectm invalid context 0x0 backtrace uistatusbaritemview updatecontentsandwidth33 uistatusbaritemview initwithitemdataactionsstyle477 uistatusbaritemview createviewforitemwithdataactionsforegroundstyle134 uistatusbarlayoutmanager createviewforitemwithdataactions163 uistatusbarlayoutmanager prepareenableditemtypewithenableditemswithdataactionsitemappearingitemthisappearing36 uistatusbarlayoutmanager prepareenableditemswithdataactions92 uistatusbarforegroundview setstatusbardataactionsanimated797 uistatusbarforegroundview setstatusbardataactionsanimated332 51uistatusbar preparetosetstyleanimationforced block invoke360 uiviewanimation performwithoutanimation65 uistatusbar preparetosetstyleanimationforced866 uistatusbar requeststyleattributesanimationparametersforced391 uistatusbar requeststyleanimationparametersforced437 uistatusbar requeststyleanimatedforced90 uistatusbar evaluateserverregistration250 45uiviewhierarchy postmovedfromsuperview block invoke590 uiviewhierarchy postmovedfromsuperview544 uiviewinternal addsubviewpositionedrelativeto1967 uistatusbarwindow setstatusbar288 uiapplication createstatusbarwithrequestedstyleorientationhidden340 uiapplication runwithmainscenetransitioncontextcompletion950 uiapplication workspacedidendtransaction188 fbsserialqueue performnext192 fbsserialqueue performnextfromrunloopsource45 cfrunloop is calling out to a source0 perform function 17 cfrunloopdosources0556 cfrunlooprun867 cfrunlooprunspecific488 uiapplication run402 uiapplicationmain171 main117aug 7 142700 error cgcontextrestoregstate invalid context 0x0 backtrace uistatusbaritemview updatecontentsandwidth33 uistatusbaritemview initwithitemdataactionsstyle477 uistatusbaritemview createviewforitemwithdataactionsforegroundstyle134 uistatusbarlayoutmanager createviewforitemwithdataactions163 uistatusbarlayoutmanager prepareenableditemtypewithenableditemswithdataactionsitemappearingitemthisappearing36 uistatusbarlayoutmanager prepareenableditemswithdataactions92 uistatusbarforegroundview setstatusbardataactionsanimated797 uistatusbarforegroundview setstatusbardataactionsanimated332 51uistatusbar preparetosetstyleanimationforced block invoke360 uiviewanimation performwithoutanimation65 uistatusbar preparetosetstyleanimationforced866 uistatusbar requeststyleattributesanimationparametersforced391 uistatusbar requeststyleanimationparametersforced437 uistatusbar requeststyleanimatedforced90 uistatusbar evaluateserverregistration250 45uiviewhierarchy postmovedfromsuperview block invoke590 uiviewhierarchy postmovedfromsuperview544 uiviewinternal addsubviewpositionedrelativeto1967 uistatusbarwindow setstatusbar288 uiapplication createstatusbarwithrequestedstyleorientationhidden340 uiapplication runwithmainscenetransitioncontextcompletion950 uiapplication workspacedidendtransaction188 fbsserialqueue performnext192 fbsserialqueue performnextfromrunloopsource45 cfrunloop is calling out to a source0 perform function 17 cfrunloopdosources0556 cfrunlooprun867 cfrunlooprunspecific488 uiapplication run402 uiapplicationmain171 main117,['ios'] +959086,async task android execute this was asked in one of the android interviews i was asked whether it is possible to start another async task let it be task2 from doinbackground method of async task 1let it be task1 i had gone through the docs which say the followingthe task instance must be created on the ui thread executeparams must be invoked on the ui threadas per these statements i think that it should not be possible to start a task from background method of another task also async task has ui methods which cannot be used on a background thread so that strengthened my argument and i answered it as not possible on checking on a simple demo app i saw that it is indeed possible to do sosome demo code override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main mcontext this init logv gaurav thread is threadcurrentthreadgetname task1 task new task1 taskexecute class task1 extends asynctask override protected object doinbackgroundobject params todo autogenerated method stub logv gaurav thread task 1 is threadcurrentthreadgetname task2 task new task2 taskexecute return null class task2 extends asynctask override protected object doinbackgroundobject params todo autogenerated method stub logv gaurav thread task 2 is threadcurrentthreadgetname logv gaurav task 2 started return null i get following logs indicating successful execution 0807 094625564 vgaurav2100 thread is main 0807 094625564 vgaurav2100 thread task 1 is asynctask 3 0807 094625564 vgaurav2100 thread task 2 is asynctask 4 0807 094625564 vgaurav2100 task 2 startedi have checked this on ics kk and l device and it works fine for allone reason i could think of is that i am not overriding any ui methods and doing any ui updation in my second task hence it does not cause any problems but i am not sure even if that is the case it violates the threading rules mentioned in the developer guideas a reference i checked out this link too start asynctask from another asynctask doinbackground but the answer states to start the second task using runonuithread method inside doinbackground i would like some help on whats going on here thanks,['android'] +959110,c method naming conventions tosomething vs assomething as i was writing some extension methods for my business logic objects i came to the question of renaming the conversion methods someobjecttoanotherobject would go fine with the widely used objecttostringhowever linq for example mixes up both variants and i cannot find a difference between them todictionary tolist asparallel asqueryable what are the differences between these two naming conventions and what should i know to decide whether to use for my own classes,['c#'] +959153,hiding copypastereturn panel in ios 9 shortcuts panel iam testing my application on ios 9 beta apple added a new panel with copypastereturn functionsi know i can thisable it in general settings of my devicecan i detect it in code using notifications and can i tell my textfields and textviews do not show it when they are editingif i turn off the predictive view the panel will thisplayi have not found it in xcode 7 beta 4 if you know how to fix this issue please let me know it too,"['ios', 'objective-c']" +959267,how to prepare a dataset for keras motivationto run a set of labeled vectors through keras neural networkexamplelooking at keras dataset example mnistkerasdatasets import mnistx tr y tr x te y te mnistload dataprint x trshapeit seem to be a 3 dimensional numpy array60 28 281st dimension is for the samples2nd and 3rd for each sample featuresattemptbuilding the labeled vectorsx train numpyarray1 128 10 4 0 128 10 4x test numpyarray1 128 10 2 0 128 10 2y train numpyarraytrue 10 4 false 10 4y test numpyarraytrue 10 2 false 10 2x train x trainastypefloat32x test x testastypefloat32y train y trainastypebooly test y testastypeboolthe training codemodel sequentialmodeladense128 50modeladdactivationrelumodeladropout02modeladense50 50modeladdactivationrelumodeladropout02modeladense50 1modeladdactivationsoftmaxrms rmspropmodelcompilelossbinary crossentropy optimizerrmsmodelfitx train y train batch sizebatch size nb epochnb epoch show accuracytrue verbose2 validation datax test y testscore modelevaluatex test y test show accuracytrue verbose0printtest score score0printtest accuracy score1resulttest score 139705320154test accuracy 10why do i get such a bad result for such a simple datasetis my dataset malformedthanks,['python'] +959282,wrap horizontal based on height i am using layout horizontal wrap to locate some items based on its size and the container these items have different sizes so sometimes i am losing a lot of space below thembetter if i show you a sketch with the situationmy relevant code looks likestyle high height 200px low height 50px object minwidth 200px stylediv classlayout horizontal wrap styleheightauto idcontainer div classobject high p1p div div classobject low p2p div div classobject low p3p div div classobject low p4p divdivscript typetextjavascript function containersortable cursor move scriptthose elements are sortable so the user can move them a solution with fixed positions is not possibleis it possible to resolve it using polymershadowany ideai did a plnkr where you can reproduce itupdateas ia m getting some suggestions to use float and i am getting some difficulties to explain the problem i am having with it i am adding a new sketch to show a possible goal notice how the user could move the small items at both sides of the big one,"['html', 'css']" +959309,why is the version property not set with spring data jpa wanted to know how is version annotation in spring data rest put to use for etags i do not see the etags populated for some reasonentityentitylistenersauditingentitylistenerclasspublic class venue implements serializable private static final long serialversionuid 5516160437873476233l private long id other properties private long version private date lastmodifieddate getters setters jsonignore lastmodifieddate public date getlastmodifieddate return lastmodifieddate version column public long getversion return version going by the docs this should give me an etag value as seen in the snippet from the libraryprotected httpheaders prepareheaderspersistententity entity object value add etag httpheaders headers etagfromentity valueaddtonew httpheaders add lastmodified auditablebeanwrapper wrapper getauditablebeanwrappervaluehowever given the entity following configuration i still get a null for versionmy application has the following springbootapplicationenableentitylinksenablejpaauditingpublic class gabbarsinghapplicationand the rest repository is as followsrepositoryrestresourcecollectionresourcerel venue path venuespublic interface venuerepository extends jparepositoryvenue long while i have not got to test these methods yet with the headers etc a simple post request on httplocalhost8080workshops gives a 500 because of null pointer exception at getting etag header value from value of version propertyupdatemoved to javaxpersistenceversion for the entities i still do not get an etag header in the response headersheres a failing unit test before public void setup throws exception xstream xstream new xstream objectinputstream in xstreamcreateobjectinputstreamvenuesxmlgetinputstream leela venue inreadobject paul venue inreadobject taj venue inreadobject loggerdebuginitialised venues from xml file venuesxmlgetfilename test public void testetagheaderisautogeneratedonresourcecreation final httpentityvenue httpentity new httpentityvenuetaj headers responseentityresourcesupport response resttemplateexchangebase location venues endpoint httpmethodpost httpentity new parameterizedtypereferenceresourcesupport asserttrueresponse should contain etag header null responsegetheadersgetetagthis assertion fails,['java'] +959377,cordova ionic enable android emoji soft keyboard with cordova ionic android you can call for the search keyboard with input typesearchi am trying to access the emoji keyboard with input typetextshortmessagebut it is not workingtextshortmessage is based off this so question android keyboard with emoji which is for direct android development,['android'] +959552,how can i create a horizontal gradient background for my ios nav bar i know how to set a navigation bar background color with bartintcolor but now i am working on an ios app that calls for a horizontal gradient not the typical vertical gradienthow can i create a navigation bar with a horizontal gradient background,"['ios', 'objective-c']" +959582,how can i prevent jquery prepend removing the html when i click on the anchor tag the image shifts from divleft to divright i want the image to be copied is this the default behaviour of prepend how can i avoid this problemthe image is just a placeholder for a big div with many childrendoctype htmlhtml xmlnshead titletitle script srcscriptsjquery210minjsscript script typetextjavascript srcscriptsjavascriptjsscriptheadbody div idleft stylefloatleft img srcimagesroomsk1jpg altalternate text height200 width200 div div idright stylefloatrightdiv a idaddimagetoright hrefadd image torightabodyhtmlthe jquery isdocumentreadyfunction addimagetorightclickfunction var image left img var imgcopy image divrightprependimgcopy,"['javascript', 'jquery', 'html', 'css']" +959652,how can i create this particular shape is there an easier or better way to create this particular shapecombination of shapes in css3 than what am i currently doing i have tried a few different things alreadythe downward facing triangle should be sitting just below the three lines but i cannot seem to get it therei want it to look like this trianglecontainer top 0 width 30px height 40px position relative borderbottom 2px solid e74c3ctriangle position relative margin auto top 30px left 0 right 0 width 21px height 21px transform rotate45deg webkittransform rotate45deg moztransform rotate45deg otransform rotate45deg mstransform rotate45deg borderright 2px solid e74c3c borderbottom 2px solid e74c3cline width 30px position relative borderbottom 2px solid e74c3c margintop 3pxa href classopen div classlinediv div classlinediv div classlinediv div classtrianglecontainer div classtrianglediv diva,['css'] +959697,c tcp server for simple chat i am writing my first tcp server using microsofts supplied async examplesvvs110aspxi have everything working from the example i am extending it as a simple chat program but i am having trouble following the steps of this program probably because of its async nature when a message is received it echoes back to the client and closes the socket i do not see where it goes back to reopen the socketpublic static void startlistening data buffer for incoming data byte bytes new byte1024 establish the local endpoint for the socket the dns name of the computer running the listener is hostcontosocom iphostentry iphostinfo dnsresolvednsgethostname ipaddress ipaddress iphostinfoaddresslist0 ipendpoint localendpoint new ipendpointipaddress 110 create a tcpip socket socket listener new socketaddressfamilyinternetwork sockettypestream protocoltypetcp bind the socket to the local endpoint and listen for incoming connections try listenerbindlocalendpoint listenerlisten100 while true set the event to nonsignaled state alldonereset start an asynchronous socket to listen for connections consolewritelinewaiting for a connection listenerbeginaccept new asynccallbackacceptcallback listener wait until a connection is made before continuing alldonewaitone catch exception e consolewritelineetostring consolewritelinenpress enter to continue consoleread private static void sendcallbackiasyncresult ar try retrieve the socket from the state object socket handler socket arasyncstate complete sending the data to the remote device int bytessent handlerendsendar consolewritelinesent 0 bytes to client bytessent handlershutdownsocketshutdownboth handlerclose catch exception e consolewritelineetostring also is it not normal to leave the socket open,['c#'] +959703,simple injector perwebapirequest dependency in signalr hub according to this post it should be possible to inject perwebrequest dependencies into signalr hubs although with some limitations like problem with onthisconnected method in my case it is asp web api not mvc and it does not work for some reasonhere are relevant partscontainerregisterwebapicontrollershttpconfigurationcontainerregisterwebapirequestdbcontext mydbcontextcontainerregisterwebapirequestisamplerepository samplerepository dbcontext injected to samplerepositoryenable injections to signalr hubsvar activator new simpleinjectorhubactivatorcontainerglobalhostdependencyresolverregistertypeofihubactivator activatorthis class makes possible to inject into hubspublic class simpleinjectorhubactivator ihubactivator private readonly container container public simpleinjectorhubactivatorcontainer container container container public ihub createhubdescriptor descriptor return ihub containergetinstancedescriptorhubtype and hub itself hubnamesample public class samplehub hub public activebetshubisamplerepository repository irrelevant methods here onthisconnected not implemented with this setup i get exceptionno registration for type samplehub could be found andan implicit registration could not be made the isamplerepository is registered as web api request lifestyle but the instance is requested outside the context of a web api requestwhich is expected as i understand however i get exactly same exception when i change lifestyle of repository to transient var transienthybrid lifestylecreatehybrid httpcontextcurrent null new webapirequestlifestyle lifestyletransient containerregisterisamplerepository samplerepositorytransienthybridi suspect the problem could lie in httpcontextcurrent null check that is not working for web api the same way as for mvcsignalr 22simple injector 283what do i missupdatethis is stack trace on how signalr creates hubsat simpleinjectorinstanceproducergetinstance at simpleinjectorcontainergetinstancetype servicetype at mywebabiwebapiapplicationsimpleinjectorhubactivatorcreatehubdescriptor descriptor in globalasaxcsline 108 at microsoftaspnetsignalrhubsdefaulthubmanagerresolvehubstring hubname at microsoftaspnetsignalrhubshubthispatchercreatehubirequest request hubdescriptor descriptor string connectionid statechangetracker tracker boolean throwiffailedtocreateso the proper solution would be to use executioncontextscope for a hubs but this scope needs to be explicitly closed which makes things more complicated,"['c#', '.net']" +959711,convert nsdata byte array to string i have an nsdata object i need to convert its bytes to a string and send as json description returns hex and is unreliable according to various so posters so i am looking at code like thisnsuinteger len imagedata lengthbyte bytedata bytemalloclenimagedata getbytesbytedata lengthlenhow do i then send bytedata as json i want to send the raw bytescodensstring jsonbase64 imagedata base64encodedstringnslogbase 64 fingerprint jsonbase64nsdata b64 nsdata datafrombase64stringjsonbase64nslogequal d imagedata isequaltodatab64nslogb64 b64nslogoriginal imagedatansstring decoded nsstring alloc initwithdatab64 encodingnsutf8stringencodingnslogdecoded decodedi get values for everything except for the last line decodedwhich would indicate to me that the raw bytes are not formatted in nsutf8encoding,['objective-c'] +959721,angularjs angularuirouter always redirects to urlrouterproviderotherwise location i am trying to create an spa where you have to be logged in to access almost everything so naturally the default screen you see is the login screen however after a user has logged in no matter what the uisref is uirouter redirects to the login page even when the user is authenticated here is my uirouter codefunction use strictangular moduleapp uirouter satellizer configfunction stateprovider urlrouterprovider authprovider httpprovider provide httpproviderinterceptorspushq injector functionq injector return responseerror function rejection var state injectorgetstate var rejectionreasons token not provided token expired token absent token invalid angularforeachrejectionreasons function value key if rejectiondataerror value localstorageremoveitemuser stategoauth return qrejectrejection response functionresponse var authorization responseheadersauthorization ifauthorization null authorization authorizationsubstr7trim consolelogauthorization var auth injectorgetauth authsettokenauthorization return response authproviderloginurl mingdaograderapiauthenticate stateprovider stateusers url users templateurl viewsuserviewhtml controller usercontroller as user statesubjects url usersuser idsubjects templateurl viewssubjectsviewhtml controller subjectsctrl as subjectsctrl statesubject url usersuser idsubjectssubject id templateurl viewssubjectviewhtml controller subjectctrl as subjectctrl stateauth url auth templateurl viewsauthviewhtml controller authcontroller as auth stateotherwise url path templateurl viewsauthviewhtml controller authcontroller as auth urlrouterproviderotherwiseauth urlrouterproviderotherwisefunctioninjector location consolelogcould not find location locationpathauth runfunction rootscope state log rootscopeonstatechangestart function event tostate consolelogtostatename var user jsonparselocalstoragegetitemuser if user rootscopeauthenticated true rootscopecurrentuser user anytime i try to use stategoany state name here or even type the address into the address bar i am always redirected to the auth state on the console the message is could not find httplocalhost for every single route i can type in httplocalhostusers5subjects and i get the same messagehere is one of my controllers doing a redirectfunction use strict angular moduleapp controllerauthcontroller authcontroller function authcontrollerauth state http rootscope log var vm this vmloginerror false vmloginerrortext vmlogin function var credentials username vmusername password vmpassword authlogincredentialsthenfunction return httpgetapiauthenticateuser function error vmloginerror true vmloginerrortext errordataerror thenfunction response var user jsonstringifyresponsedatauser localstoragesetitemuser user rootscopeauthenticated true rootscopecurrentuser responsedatauser loginfofrom authctrl rootscopecurrentuserid stategosubjects user idrootscopecurrentuserid any ideas what i am doing wrong thanks a lot for your timeupdate ok i have not found a way to fix it but i think i may have found a possible cause it seems to only happen for the routes with parameters for example if i go to the users state whose path is users there is no redirect however if i go to the subjects state whose path is usersuser idsubjects it does redirect it is like the url matching service cannot recognize that users5subjects matches usersuser idsubjects so redirects any ideas how to work around this,['javascript'] +959725,openlayers 3 movestart event on map openlayers3 api has a maponmoveend however i cannot find a movestart any one know how i can achieve this is there a equivalent event openlayers 2 had a movestart event on map i am looking an exact parallel in openlayers3heres a basic jsfiddle if someone wants to play around i did add a movestart event there to show what i want but it does not actually exist i think use case one might ask i have stops on maps that have nearly fullscreen infowindows users can switch to next marker from infowindow i make the windows translucent to show the map panning underneath so users get a context of where next location is this works great in openlayers2 with movestart and moveend events but in the new ol3 version of the map i cannot get the movestart event update i did answer the question my self but i am still offering bounty if anyone would like to propose a better solution,['javascript'] +959858,why is the box shadow only visible after scrolling i have been trying for ages to figure out why the box shadow on my top menu is not visible when you first navigate to each page but appears once you start scrollingthis is the site the class with the shadow is navbarwrappernavbarwrapper backgroundcolor fwidth 100margin autowebkitboxshadow 0px 5px 5px 2px rgba0 0 0 05 hoffset voffset blur radius color red green blue opacity mozboxshadow 0px 5px 5px 2px rgba0 0 0 05boxshadow 0px 5px 5px 2px rgba0 0 0 05it is worth mentioning that i am also using stickup to get the menu to stick to the top of the page perhaps some kind of conflict with that script,"['jquery', 'html', 'css']" +959963,strange bug with xcode 7 ios 9 b5 with datawithcontentsofurl i have a part of code who works as expected on all ios versions but not on ios 9nsdata response nsdata datawithcontentsofurl nsurl urlwithstring url optionsnsdatareadinguncached errorerrorit is a simple json texti got this errorerror domainnscocoaerrordomain code256 the file axphpa couldnat be opened userinfonsurlhow this url can be intepreted as a file response nil thanks,['ios'] +959979,uitableview background color ios 9 i have a uitableview that i want to set its background color to transparent background color for the table view and all subviews at interface builder is set to transparent it works fine for ios 8 7 but not ios 9 any ideacellforrowatindexpath methodcell setselectedbackgroundviewuiview alloc initcellselectedbackgroundview setbackgroundcoloruicolor clearcolorcell setbackgroundcoloruicolor clearcolorcellcontentview setbackgroundcoloruicolor clearcolorcell setbackgroundviewuiview alloc initcellbackgroundview setbackgroundcoloruicolor clearcolor,"['ios', 'objective-c']" +960061,how to completely colorize uipopoverpresentationcontroller background color i am working with a day and night mode for an appthe problem is when just setting the background color of a view and then using it as presenting as popover there are little white artifacts see the pictureis there an easy way to fix thisdo i may have to write my own uiview,['ios'] +960286,http request from a c desktop application to a siteminderprotected server i have developed a c desktop application which makes https requests to the customers servers usually documentumsharepointalfresconemakiwareetc httpsbased serversseveral customers have asked us to support their servers which are protected by ca sso new name of siteminderquestion what do i need to do to allow my application to send https requests and receive responses with ca ssoprotected serversi have developed ntlmsso support for our c desktop application and it works well but i am not sure about how to proceed for ca ssoi have asked the same question on the ca forum but like most questions there it remains unanswered,['c#'] +960316,proxy request to new port with httpproxy i use this code i want to create proxy that all the application calls to port 30 will be routed under the hood to port 3002var http requirehttp httpproxy requirehttpproxy var proxy httpproxycreateproxyserver httpcreateserverfunction req res proxywebreq res target httplocalhost3002 listen30 create target serverhttpcreateserverfunction req res reswritehead200 contenttype textplain reswriterequest successfully proxied to requrl n jsonstringifyreqheaders true 2 resendlisten3002now when i run the application with original port30 i see in the browser request successfully proxied to 3002 when i change the port in the browser to 3002 i still get thesame messagewhy is it okwhat should i put in production inside the second createserver i mean instead of thereswritehead200 contenttype textplain reswriterequest successfully proxied to requrl n jsonstringifyreqheaders true 2resenddoes the resend should also be there i use the code from,['javascript'] +960464,associativity of function call operator in c i was going through the topic of associativity of c operatorsthere i came across this fact that the function call operator has a left to right associativity but associativity only comes to play when multiple operators of the same precedence occur in an expression but i could not find any example involving function call operator where associativity plays a crucial rolefor example in the statement a fx gx the result depends on the evaluation order and not on the associativity of the two function callssimilarly the call fgx will evaluate function g first and then the function f here we have a nested function call and again associativity does not play any rolethe other c operators in this priority group are array subscript postfix and postfix but i could not find any examples involving a combination of these operators with where associativity plays a part in expression evaluation so my question is does the associativity of function call being defined as left to right affect any expression in c can anyone provide an example where the associativity of function call operator does matter in expression evaluation,['c'] +960505,boto3 to download all files from a s3 bucket i am using boto3 to get files from s3 bucket i need a similar functionality like aws s3 syncmy current code isusrbinpythonimport boto3s3boto3clients3lists3list objectsbucketmy bucket namecontentsfor key in list s3download filemy bucket name keykey keykeythis is working fine as long as the bucket has only filesif a folder is present inside the bucket its throwing an errortraceback most recent call last file test line 6 in module s3download filemy bucket name keykey keykey file usrlocallibpython27thistpackagesboto3s3injectpy line 58 in download file extra argsextraargs callbackcallback file usrlocallibpython27thistpackagesboto3s3transferpy line 651 in download file extra args callback file usrlocallibpython27thistpackagesboto3s3transferpy line 6 in download file self get objectbucket key filename extra args callback file usrlocallibpython27thistpackagesboto3s3transferpy line 690 in get object extra args callback file usrlocallibpython27thistpackagesboto3s3transferpy line 707 in do get object with self osutilopenfilename wb as f file usrlocallibpython27thistpackagesboto3s3transferpy line 323 in open return openfilename modeioerror errno 2 no such file or directory my folder8df54234is this a proper way to download a complete s3 bucket using boto3 how to download folders,['python'] +960514,g would not allow generalized capture of const object by reference in lambda this is rejected by g 493 and 520 but is accepted by clang 350int main const int ci 0 auto lambda cap ci g gives error binding aconst inta to reference of type ainta thiscards qualifiers it appears that g refuses to allow nonconst references to be captured except of course using plain old c11 capture ci that seems a very strange constraint perhaps a bug in g,['c++'] +960537,splitting values by commas that are outside parentheses i have the following stringa b 10 functionc string expression functiondce functionc x 100and want to split it by commas that are outside parentheses to thisa b 10 functionc string expression functiondcefunctionc x100i was not able to do this alone or using any of the similar answers herefor example s regular expression works well but only if not nested parentheses are used which is my casecould anyone tell me how to split the values using or not regular expression,"['c#', '.net']" +960562,paginated api request how to know if there is another page i am creating a php class that use a 3rd party api the api has a method with this request url structurewhere x is the page numbereach page return 50 sales and i need to return an undefined number of pages for each user depending on the user sales and store some data from each salei have already created some methods that get the data from the url decode and create a new array with the desired data but only with the first page requestnow i want to create a method that check if is there another page and if there is get it and make the check againhow can i check if there is another page and how to create a loop that get another page if there is onei have already this code but it create an infinite looprequireclassesclassexample apiphpmy class new example apipage 1sales url my clasales url page url my classget datasales urlwhile emptyurl page sales url my clasales url page url my classget datasales urli do not use curl i use file get content when i request a page out of range i get this resultstring2 and this other after json decodearray0,['php'] +960612,how to ignore a json element in android retrofit i am developing an android app which is sending a json using android retrofit it converts a pojo class in a json it is working fine but i need to ignore in the sending of json one element from the pojo class does anyone know any android retrofit annotationexamplepojo classpublic class sendingpojo long id string text1 string text2 i want to ignore that in the json getidreturn id setidlong id thisid id gettext1return text1 settext1string text1 thistext1 text1 gettext2return text2 settext2string text2 thistext2 text2 interface sender apiclass public interface svcapi postsendingpojo svc path public sendingpojo addsendingpojobody sendingpojo spany idea how to ignore text2,['android'] +960765,how to insert into multiple tables on user registration and edit the registration from how would i insert rows in multiple tables default user table and parents table when registering a new useri know i need to edit models authcontroller and viewmy user modelnamespace jcfkmodelsuserclass user extends model implements authenticatablecontract canresetpasswordcontract use authenticatable canresetpassword the database table used by the model var string protected table user var string protected primarykey user id var bool public timestamps false the attributes that are mass assignable var array protected fillable email password the attributes excluded from the models json form var array protected hidden password remember token public function parents return thishasoneappmodelsparents is the current user an admin return bool public function isadmin return thisrole id roleadmin public function isparents return thisrole id roleparent parents modelnamespace jcfkmodelsparentsclass parents extends model protected table parent public timestamps false public primarykey user id protected fillable name phone address city id region postalcode public function user return thisbelongstoappuser the auth controllernamespace jcfkhttpcontrollersauthuse illuminatecontractsauthguarduse illuminatecontractsroutingregistraruse jcfkmodelsuseruse jcfkmodelsparentsuse validatoruse jcfkhttpcontrollerscontrolleruse illuminatefoundationauthauthenticatesandregistersusersclass authcontroller extends controller use authenticatesandregistersusers create a new authentication controller instance return void public function constructguard auth registrar registrar thisauth auth thisregistrar registrar thismiddlewareguest except getlogout get a validator for an incoming registration request param array data return illuminatecontractsvalidationvalidator protected function validatorarray data return validatormakedata name requiredmax255 email requiredemailmax255uniqueuser password requiredconfirmedmin6 create a new user instance after a valid registration param array data return user protected function createarray data user new userdata parents new parentsdata usersave userparentssaveparents the database fields of parents are user id name phone address the database fields of user are user id email password i need help with my registerbladephp file as wellform classformhorizontal roleform methodpost action urlauthregister input typehidden name token value csrf token div classformgroup label classcolmd4 controllabelnamelabel div classcolmd6 input typetext classformcontrol namename value olduser id div div div classformgroup label classcolmd4 controllabelemail addresslabel div classcolmd6 input typeemail classformcontrol nameemail value oldemail div div div classformgroup label classcolmd4 controllabelpasswordlabel div classcolmd6 input typepassword classformcontrol namepassword div div div classformgroup label classcolmd4 controllabelconfirm passwordlabel div classcolmd6 input typepassword classformcontrol namepassword confirmation div div div classformgroup div classcolmd6 colmdoffset4 button typesubmit classbtn btnprimary register button div divform,"['php', 'html']" +960776,is it possible to use a java 8 style method references in scala i am developing a javafx8 application in scala but i could not figure out how to pass a method reference to an event handler to clarify i am not using scalafx library but build my application directly on top of javafxheres the related code snippetinputcontrollerjava i wrote this test class in java to isolate the issue to consume a method reference onlypublic class inputcontroller public void handlefileselectionactionevent actionevent event handling code public inputcontroller init controller this works javainputcontroller inputcontroller new inputcontrollerfilebuttonsetonactioninputcontrollerhandlefileselectionthis does not work scalaval inputcontroller new inputcontrollerfilebuttonsetonactioninputcontrollerhandlefileselectionheres the error message from the compiler scala 2116error125 45 missing arguments for method handlefileselection in class mainfollow this method with if you want to treat it as a partially applied function filebuttonsetonactioninputcontrollerhandlefileselection if i use scala 2120m2 instead i get a different error messageerror125 45 missing argument list for method handlefileselection in class mainunapplied methods are only converted to functions when a function type is expectedyou can make this conversion explicit by writing handlefileselection or handlefileselection instead of handlefileselection filebuttonsetonactioninputcontrollerhandlefileselection is there a native way which scala can leverage method references introduced in java 8 i am aware of the implicit conversions approach to use a lambda expression but i want to know if there is a way to use a method reference similar to java 8 without needing to use the lambda decleration,['java'] +960852,ios swift share on instagram with captions i am able to successfully share an image on instagram using the uidocumentinteractioncontroller but the instagramcaption key would not work this is my codeselfcontroller uidocumentinteractioncontroller controllerdelegate selfselfcontrollerurl fileuri here the caption would not appearselfcontrollerannotation nsdictionaryobjectsandkeys my caption instagramcaptionselfcontrolleruti cominstagramexclusivegramselfcontrollerpresentopeninmenufromrectcgrectzero inview selfview animated truewhat am i doing wrong,['ios'] +960859,android interrupt thread contained in a method in android studio i have a thread contained in a method like soseen below because i would like to restart the thread whenever it is called1 recreating the thread rather than restartingpublic void callthread final thread mythread new threadnew runnable override public void run for int x0 x750threadinterrupted x using this and thread sleep for repeated timed code within a thread try threadsleep4 runonuithreadnew runnable override public void run some code if condition mythreadinterrupt catch interruptedexception e my problem is that it wont let me use mythreadinterrupt in the desired location in my code giving me an error saying variable mythread may not have been initialized and will not compile because of this however it works when the entire thread is contained in class but i do not have a way of restarting it in other words i need a way to interrupt the thread while it is contained in a method2accepted solutions 1 a solution where the thread can be restarted 2 a solution where the thread can be interrupted while the thread is contained in a methodps if its unclear i have edited my code above for easy readability but i have not removed things like the for loop or the threadsleep as i assume they could be part of the problem so if theres too many or too little of a certain curly bracket then thats not the problemedit searched around and apparently you cant restart a thread,"['java', 'android']" +960943,ios 9 beta language id syntax change i am quite confusing why in ios 9 beta the return value of language code is different from ios 84functionnsuserdefaultsstandarduserdefaultsobjectforkeyapplelanguages just set language to simple chinese and region to china in ios 84 return zhhanz but in ios 9 beta 4 return zhhanzcn the language id syntax is much more like language designatorscript designatorregion designatoris different with apple documentis it a new rule in ios 9 can someone help me to confirm thisthank you for your help,"['ios', 'objective-c', 'iphone']" +961027,splitting digits and latin letters from a string currently i have an array something like this 0 is001 eeaae12ac aa1 cafrom this i would like to extract only the is001 part and leave the japanese character behind to something like this 0 eeaae12ac aa1 canormal preg split i am using currently only for white space but it seems like having some issue on the ca character to fall into next array so i decided if only i can split those non japanese characters out,['php'] +961123,customise android talkback in alert dialogue i have checked with all default alert dialogue box via android talkback default android talkback behaviour is that it reads all contentsnon stop in dialogue box is there any way i can customise it according to my need for example alertdialog alertdialog new alertdialogbuilderalertdialogactivitythiscreatealertdialogsettitlealert dialogalertdialogsetmessagethis is my alert dialogalertdialogsetbuttonok new dialoginterfaceonclicklistener public void onclickdialoginterface dialog int which toastmaketextgetapplicationcontext you clicked on ok toastlength shortshow alertdialogshowwhen dialog appears it reads automatically alert dialogue this is my alert dialogue ok but i want to control it like it should read only alert dialogue or this is my alert dialogue etcand while tapping on ok it reads only ok instead ok button,['android'] +961209,i need to thisplay only one part of a json encoded object hi i am new to php but have managed to get this far in my requirementsi am trying to thisplay only one part of a json decoded object i have called the object resultsi can successfully use var dump results and then get the full results as followsobjectstdclass2 public 0 objectstdclass3 public forename 1 string james length5 public middle1 1 string length0 public middle2 1 string length0 public middle3 1 string length0 public surname 1 string turner length7 public status int 100i then insert this into a table using the following codehtmlform idclientdetails actiondetailsphp methodpost table thead tr thfirst nameth thsurnameth thsearchth tr theadphp foreachresults as otr td idforename oforename 1 td td idsurname osurname 1 td tdbutton typesubmit more infobuttontdtrphp endforeach tableformhtmlheres the problemwhen i thisplay the results i get the following errornotice trying to get property of nonobjectthis seems to be because i am trying to run the public status int 100 part of the objectso my question ishow do i either stop the table from trying to populate that status or how do i ignore it completelyeditif i wanted to i could get the results from the json decode as an associative array instead of as objects would this help me to ignore the status arrayobject,['php'] +961222,require using amd pattern gives error for jquery ui events in my code testjs is dependent on jqueryui which does not uses require amd pattern and testspecjs dependent on jqueryui testjs which uses amd pattern can we load dependency of jqueryui in testjs dynamically when running testspecjsrequireconfig baseurl demo paths jquery libraryjquery1 jqueryui libraryjqueryui14 shim jquery exports jquery jqueryui deps jquery librarysrcjstest deps libraryjquery1 libraryjqueryui14 jscollapse exports test callback window karma startin testjs draggable of jqueryui draggable event is written after evaluating paneliddraggablerevert true got error typeerror undefined is not a function evaluating paneliddraggablerevert truehow to load jqueryui for testjs in requireconfig as i am using this to run my jasmine test casesin real environment it is working as expected but in jasmine test case not able to find jqueryui eventtestjs is not using requirejs but testspecjs uses the require amd patternin testspecjs code after executing this got error of jqueryui draggable undefineddefinejqueryuilibrarysrcjstest function i am able to access jquery ui in testspecjs using not in testjs where jqueryui event is written as testjs does not uses amd require pattern do not know what is missing any help will be appriciated,['javascript'] +961327,wordpress admin menu thisplay glitch in google chrome a recent update to google chrome seems to be causing issues with my wordpress admin menus this is happening on all sites whether in local development or on the web the sites are thisplaying fine on other browsers firefox and safarideactivating all plugins and changing to the default twentyfifteen theme had no effect on this thisplay glitchis there a known issue with chrome can this be fixed,['css'] +961488,how to limit python traceback to specific files i write a lot of python code that uses external libraries frequently i will write a bug and when i run the code i get a big long traceback in the python console 9 of the time it is due to a coding error in my code not because of a bug in the package but the traceback goes all the way to the line of error in the package code and either it takes a lot of scrolling through the traceback to find the code i wrote or the traceback is so deep into the package that my own code does not even appear in the tracebackis there a way to blackbox the package code or somehow only show traceback lines from my code i would like the ability to specify to the system which directories or files i want to see traceback from,['python'] +961580,python bandpass filter of an image i have a data image with an imaging artifact that comes out as a sinusoidal background which i want to remove since it is a single frequency sine wave it seems natural to fourier transform and either bandpass filter or notch filter where i think i would use a gaussian filter at omega in trying to do this i notice two things 1 simply by performing the fft and back i have reduced the sine wave component shown below there seems to be some highpass filtering of the data just by going there and backimport numpy as npf npfftfft2img do the fourier transformfshift1 npfftfftshiftf shift the zero to the centerf ishift npfftifftshiftfshift1 inverse shiftimg back npfftifft2f ishift inverse fourier transformimg back npabsimg backthis is an image of img backmaybe the filtering here is good enough for me but i am not that confident in it since i do not have a good understanding of the background suppression2 to be more sure of the suppression at the unwanted frequencies i made a boolean bandpass mask and applied it to the data but the fourier transform ignores the mask a shapefshift10b shapefshift11ro 8ri 5yx npogrida2a2 b2b2 m1 xx yy roro m2 xx yy ririm3npdstackm1m2 maskcomb for r in m3 maskcombappendanyc for c in r probably not pythonic sorrynewma npinvertmaskcombfiltdat maarrayfshift1masknewma imshowabsfiltdatf ishift npfftifftshiftfiltdat img back2 npfftifft2f ishift img back2 npabsimg back2here the result is the same as before because npfft ignores masks the fix to that was simple filtdat2 filtdatfilledfiltdatmeanunfortunately but upon reflection also unsurprisingly the result is shown here the left plot is of the amplitude of the fft with the bandpass filter applied it is the dark ring around the central dc component the phase is not shownclearly the brickwall filter is not the right solution the phenomenon of making rings from this filter is well explained here what happens when you apply a brickwall filter to a 1d datasetso now i am stuck perhaps it would be better to use one of the built in scipy methods but they seem to be for 1d data as in this implementation of a butterworth filter possibly the right thing to do involves using fftconvolve as is done here to blur an image my question about fftconvolve is this does it require both images the image and the filter to be in real space i think yes but in the example they use a gaussian so it is ambiguous fftgaussiangaussian if so then it seems wrong to try to make a real space bandpass filter maybe the right strategy uses convolve2d with the fourier space image and a homemade filter if so do you know how to make a good 2d filter,['python'] +961693,how to select a particular tile when clicked and inflate a bitmap on it in tileview android i am showing a big image using tileview using tileview librarynow i want to show a circle in a rect boundary when cliked on particular tileshow to get on which tile clicked and how to show bitmmap above that tilepublic class largeimagetileviewactivity extends tileviewactivity tileview tileview override public void oncreate bundle savedinstancestate superoncreate savedinstancestate multiple references tileview gettileview by thisabling transitions we would not see a flicker of background color when moving between tile sets tileviewsettransitionsenabled false size of original image at 100 scale tileviewsetsize 2835 4289 detail levels tileviewadetaillevel 10f tilespainting10col rowjpg tileviewadetaillevel 0500f tilespainting500col rowjpg tileviewadetaillevel 0250f tilespainting250col rowjpg tileviewadetaillevel 0125f tilespainting125col rowjpg set scale to 0 but keep scaletofit true so it will be as small as possible but still match the container tileviewsetscale 0 let us use 01 positioning tileviewdefinerelativebounds 0 0 1 1 frame to center frameto 05 05 tileviewaddtilevieweventlistener listener private tilevieweventlistenerimplementation listener new tilevieweventlistenerimplementation public void ontap int x int y samplecallout callout new samplecalloutlargeimagetileviewactivitythis tileviewslidetoandcenterx y toastmaketextmcontext center tempstoregetcenterx tempstoregetcentery toastlength shortshow tileviewaddcalloutcallout x y 05f 10f callouttransitionin,['android'] +961762,why php function str word count returns different count from js equivalent i have this js code which i think is equivalent to the php str word count function but still they return different words countsmy js codeelement f9 value isyes for all people asking their selfs have you ever dreamed to visite world travel market 2015 we can confirm that now it is a great time to go to london for world travel market 2015yes for all people asking their selfs have you ever dreamed to visite world travel market 2015 we can confirm that now it is a great time to go to london for world travel market 2015yes for all people asking their selfs have you ever dreamed to visite world travel market 2015 we can confirm that now it is a great time to go to london for world 2015yes for all people asking their selfs have you ever dreamed to visite world 2015 we can confirm that now it is a great time to go to london for world travel market 2015yes for all people asking their selfs have you ever dreamed to visite world travel market 2015 we can confirm that now it is a great time to go to london for world 2015yes for all people asking their selfs have you ever dreamed to visite world travel market 2015 we can confirm that now it is a great time to go to london for world travel market 2015yes for all people asking their selfs have you ever dreamed to visite world 2015 we can confirm that now it is a great time to go to london for world 2015yes for all people asking their selfs have you ever dreamed to visite world travel market 2015 we can confirm that now it is a great time to go to london for world 2015yes for all people asking their selfs have you ever dreamed to visite world 2015 we can confirm that now it is a great time to go to london for world 2015var words documentgetelementbyidf9valuereplaceg words wordsreplacessgiwords wordsreplace 2gi words wordsreplacen nwords wordssplit lengthoutputs 300my php codestr word countyes for all people asking their selfs have you ever dreamed to visite world travel market 2015 we can confirm that now it is a great time to go to london for world travel market 2015yes for all people asking their selfs have you ever dreamed to visite world travel market 2015 we can confirm that now it is a great time to go to london for world travel market 2015yes for all people asking their selfs have you ever dreamed to visite world travel market 2015 we can confirm that now it is a great time to go to london for world 2015yes for all people asking their selfs have you ever dreamed to visite world 2015 we can confirm that now it is a great time to go to london for world travel market 2015yes for all people asking their selfs have you ever dreamed to visite world travel market 2015 we can confirm that now it is a great time to go to london for world 2015yes for all people asking their selfs have you ever dreamed to visite world travel market 2015 we can confirm that now it is a great time to go to london for world travel market 2015yes for all people asking their selfs have you ever dreamed to visite world 2015 we can confirm that now it is a great time to go to london for world 2015yes for all people asking their selfs have you ever dreamed to visite world travel market 2015 we can confirm that now it is a great time to go to london for world 2015yes for all people asking their selfs have you ever dreamed to visite world 2015 we can confirm that now it is a great time to go to london for world 2015 outputs 290what does the php str word count does not count as word which my js code does also can you suggest what to change so i can get same count for js and php code,"['javascript', 'php']" +961965,xcode 7 beta 5 can not download simulator after installing xcode7 beta5 i ran a simple project on simulator but simulator showed an errorthe comapplecoresimulatorsimruntimeios90 simulator runtime is not availabledownload the comapplecoresimulatorsimruntimeios90 simulator runtime from the downloads section in xcodes preferencesbut when i go to the preference download folder it is empty in components after check and install,['ios'] +961982,python string formatting with percent sign i am trying to do exactly the following x 12 y hello dds x0 x1 y12hellohowever i have a long x more than two items so i tried dds x ybut it is syntax error what would be the proper way of doing this without indexing like the first example,['python'] +962045,count number of times app has been launched using swift i would like to count the number of times my ios application has been launched using swifti would then like to take the number and thisplay it using nslog each time,['ios'] +962055,is it safe to assume floating point is represented using ie754 floats in c floating point is implementation defined in the c so there is not any guaranteesour code needs to be portable we are thiscussing whether or not acceptable to use ie754 floats in our protocol for performance reasons it would be nice if we do not have to convert back and forth between a fixed point format when sending or receiving datawhile i know that there can be differences between platforms and architectures regarding the size of long or wchar t but i cannot seem to find any specific about the float and double what i found so far that the byte order maybe reversed on big endian platforms while there are platforms without floating point support where a code containing float and double wouldnt even link otherwise platforms seem to stick to ie754 single and double precisionso is it safe to assume that floating point is in ie754 when availableedit in response to a commentwhat is your definition of safeby safe i mean the bit pattern on one system means the same on the another after the byte rotation to deal with endianness,['c'] +962060,how to structure a program to work with minesweeper configurations i am trying to write a program to calculate probabilities for the game minesweeper and have had some difficulty working out how best to structure it while it may seem quite simple at first with the example below i would like to know the best way to allow for more complex configurations note i am not looking for help with how to calculate probabilities i know the method i just need to implement itto make it clear what i am trying to calculate i will work through a simple example which can be done by hand consider a minesweeper configuration 1 2 where represents an unclicked cell the 1 tells us there is exactly 1 mine in the leftmost 7 unclicked cells the 2 tells us there are exactly 2 in the rightmost 7 to calculate the probability of each individual cell containing a mine we need to determine all the different cases only 2 in this simple case1 mine in leftmost 3 cells 2 mines in rightmost 3 cells total of 3 mines 3x39 combinations1 mine in center 4 cells 1 mine in rightmost 3 cells total of 2 mines 4x312 combinationsgiven the probability of a mine being in a random cell is about 02 it is in a random selection of cells about 4 times more likely there is a total of 2 mines rather than a total of 3 so the total number of mines in a configuration matters as well as the number of combinations of each configuration so in this case the probability of case 1 is 994x120158 and the probability of there being a mine in a given leftmost cell is therefore about 01583005 as those cells are effectively equivalent they share exactly the same revealed neighboursi have created a gui with tkinter which allows me to easily enter configurations such as the one in the example which stores the grid as a numpy array i then made a numbergroup class which isolates each of the clickednumbered cells storing the number and a set of the coordinates of its unclicked neighbours these can be subtracted to get equivalence groups although this would not be as straightforward if there were three or more numbers instead of just two but i am unsure how to go from here to getting the different configurations i toyed with making a configuration class but am not hugely familiar with how different classes should work together see working code below numpy requirednote i am aware i could have attempted to use a brute force approach but if possible i would like to avoid that keeping the equivalent groups separate in the above example there are 3 equivalence groups the leftmost 3 the middle 4 the rightmost 3 i would like to hear your thoughts on thisimport numpy as npgrid nparray 0 0 0 0 0 2 1 0 0 0 0 0 dims 3 4 dimensions of the gridclass numbergroupobject def init self mines coords dimsnone takes a number of mines and a set of coordinates if dims selfdims dims selfmines mines selfcoords coords def repr self return group of cells with minesformat lenselfcoords selfmines def str self if hasattrself dims dims selfdims else dims maxc0 for c in selfcoords 1 maxc1 for c in selfcoords 1 grid npzerosdims int for coord in selfcoords gridcoord 1 return strgridreplace0 replace1 def sub self other if typeother is numbergroup return selfcoords othercoords elif typeother is set return selfcoords othercoords else raise typeerrorcan only subtract a group or a set from anotherdef get neighbourscoord dims x y coord row u for you in rangex1 x2 if you in rangedims0 col v for v in rangey1 y2 if v in rangedims1 return u v for you in row for v in colgroups all coords i j for i in rangedims0 for j in rangedims1for coord nr in c gridc for c in all coords if gridc 0 empty neighbours c for c in get neighbourscoord dims if gridc 0 if nr lenempty neighbours print error number in cell is too highformatnr coord break groupsappendnumbergroupnr empty neighbours dimsprint groupsfor g in groups print gprint groups0 groups1updatei have added a couple of other classes and restructured a bit see below for working code and it is now capable of creating and thisplaying the equivalence groups which is a step in the right direction however i still need to work out how to iterate through all the possible mineconfigurations by assigning a number of mines to each group in a way that creates a valid configuration any help is appreciatedfor example 2 1 there are three equivalence groups g1 the left 3 g2 the middle 4 g3 the right 3 i want the code to loop through assigning groups with mines in the following wayg12 max the first group g20 g31 this is all configs with g12g11 decrease by one g21 g30 this is all with g11g10 g22 invalidso we arrive at both configurations this needs to work for more complicated setupsimport numpy as npdef get neighbourscoord dims x y coord row u for you in rangex1 x2 if you in rangedims0 col v for v in rangey1 y2 if v in rangedims1 return u v for you in row for v in colclass nrconfigobject def init self grid selfgrid grid selfdims gridshape dimensions of grid selfall coords i j for i in rangeselfdims0 for j in rangeselfdims1 selfnumbers dict selfgroups selfconfigs selfget numbers selfget groups selfget configs def str self return strselfgridreplace0 def get numbersself for coord nr in c selfgridc for c in selfall coords if selfgridc 0 empty neighbours c for c in get neighbours coord selfdims if selfgridc 0 if nr lenempty neighbours print error number in cell is too highformat nr coord return selfnumberscoord numbernr coord empty neighbours selfdims def get groupsself coord neighbours dict for coord in c for c in selfall coords if selfgridc 0 must be a set so that order does not matter coord neighbourscoord selfnumbersc for c in get neighbourscoord selfdims if c in selfnumbers while coord neighbours coord neighbours coord neighbourspopitem equiv coords coord c for c ns in coord neighboursitems if ns neighbours for c in equiv coords if c in coord neighbours delcoord neighboursc selfgroupsappendequivgroupequiv coords neighbours selfdims def get configsself pass what goes hereclass numberobject contains information about the group of cells around a number def init self nr coord neighbours dims takes a number of mines and a set of coordinates selfnr nr selfcoord coord a list of the available neighbouring cells coords selfneighbours neighbours selfdims dims def repr self return number with empty neighboursformat intself lenselfneighbours def str self grid npzerosselfdims int gridselfcoord intself for coord in selfneighbours gridcoord 9 return strgridreplace0 replace9 def int self return selfnrclass equivgroupobject a group of cells which are effectively equivalent def init self coords nrs dims selfcoords coords a list of the neighbouring number objects selfnr neighbours nrs selfdims dims if selfnr neighbours selfmax mines minlenselfcoords maxmapint selfnr neighbours else selfmax mines lencoords def repr self return equivalence group containing cellsformat lenselfcoords def str self grid npzerosselfdims int for coord in selfcoords gridcoord 9 for number in selfnr neighbours gridnumbercoord intnumber return strgridreplace0 replace9 grid nparray 0 0 0 0 0 2 1 0 0 0 0 0 config nrconfiggridprint configprint number groupsfor and in confignumbersvalues print nprint equivalence groupsfor g in configgroups print g,['python'] +962069,is detecting unsigned wraparound via cast to signed undefined behavior i am using a uint16 t as a sequence counter in a network protocol this counter commonly wraps around as expected when a receiver gets a packet it checks this counter against the most recently received to see whether it is a new packet or an out of order packetwraparound needs to be taken into account when comparing sequence numbers so if for example the last sequence number was 0x40 then a sequence number from 0x4001 to 0xbf is newer and a sequence number from 0xc0 to 0xf and from 0x0 to 0x3f is smallerthe way i am currently doing this is as followsuint16 t lastuint16 t current read in values for last and currentif int16 tcurrent last 0 printfcurrent is newern else printfcurrent is older or samenby subtracting the two and treating the result as a int16 t i can easily see which is greater and by how much so for example if the current sequence number is at least 5 less that the last ie int16 tcurrent last 5 i can assume this is not due to normal packet reordering and drop the packeti realize that signed wraparound is undefined however in this case i am treating an unsigned value as signed for the sake of doing comparisons does this invoke undefined behavior and if so what would be a better way to do this type of comparison,['c'] +962142,analyzing android project with lint and sonarqube i really got an overflow trying to make these things to work together i followed instruction from here and finally got a sonarqube 511 server with android lint plugin 11 installed then i configured my multimodule gradle build to work with sonarqube plugin see code fragment from root config belowplugins id orgsonarqube version 10sonarqube properties property sonarhosturl sonarqubeserver90 property sonarjdbcurl jdbcmysqlsonarqubedb3306sonaruseunicodetrueampcharacterencodingutf8 property sonarjdbcdriverclassname commysqljdbcdriver property sonarjdbcusername sonar property sonarjdbcpassword sonar property sonarsourceencoding utf8 property sonarlogin admin property sonarpassword admin property sonarprofile android lint property sonarimport unknown files true property sonarandroidlintreport buildoutputslintresultsxml and after that i ran lint sonarqubetask to execute the analysis as a result i got a bulk of lint errors regarding retrolambda project javalangunsupportedoperationexception unknown astnode child lambdaexpression which is quite normal and lintresultsxml accompanied with html version files per each module containing descriptions of issues thiscovered the report said that there were 8 errors and 434 warnings found but things went wrong when sonarqube plugin tried to upload the results to sonarqube server the log was full of unable to find file and unable to find rule messages and when the processing was over then there were no issues reported for my project on sonarqube serverand i am wondering what did went wrong i checked the paths and all files were there i looked through all thiscussions i could reach and it seems like my config is correct and i do everything right does anybody have any clue what i missed and what needs to be checked any suggestions or ideas are welcomei will be also happy if there is a way to import lint data using external sonarqube runner since this tool seems to be more predictable and stable then a gradle plugin,"['java', 'android']" +962196,how to enable cookie in phantomjsdriver selenium c heres my codecase browsertypephantomjs var service phantomjsdriverservicecreatedefaultservicepathcombine rootpath packages var cookiefilepathpathcombine rootpath packagescookietxt if fileexistscookiefilepath filecreatecookiefilepath var phantomjsoptions new phantomjsoptions driver new phantomjsdriverservicephantomjsoptions var cookiejar drivermanagecookies drivernavigategotourlseleniumconfigurationcurrentbaseurl cookiejaraddcookienew cookiex 12345 return driverbasically the issue is that i am not able to login into my test application because i get an error saying your browser is set to block cookies i have tried everything but i just cannot seem to get the solution for thiswhat should i do please help me out herelet me know if there is some detail missing,['c#'] +962265,is it good to use exit instead of fcloseall for closing multiple files the man page of exit says all open stdio streams are flushed and closed files created by tmpfile are removedparameters of exit ie exit success and exit failure are slightly more portable to nonunix environments than the use of 0 and some nonzero value like 1 or 1 in particular vms uses a different convention the man page of fcloseall saysthe standard streams stdin stdout and stderr are also closedthe fcloseall function does not lock the streams so it is not threadsafemany online tutorials say that deallocating all resources of a given type is a programming error they should be deallocated individually by the code that owns them or not at allso is it good to use exit instead of fcloseall,['c'] +962269,increasing speed of a pure numpyscipy convolutional neural network implementation backgroundi have trained up a convolutional neural network which i would like others to be able to use without requiring hard to install libraries such as theano which i have found trivial to install on linux but very hard on windowsi have written an implementation using numpyscipy that is almost fast enough but would be even better if it was two or three times fasterwhat i have tried90 of the time is spent in the following lineconv out npsumscipysignalconvolve2dxiwfimodevalid for i in rangenum in axis0this line gets called 32 times once for each feature map and num in is 16 the number of features in the previous layer so overall this line is slow as it results in 3216512 calls to the convolve2d routinexi is only 2525 and wfi is 22questionis there a better way of expressing this type of convolutional layer in numpyscipy that would execute fasteri am only using this code for applying a learnt network so i do not have lots of images to be done in parallelcodethe full code for doing a timing experiment isimport numpy as npimport scipysignalfrom time import timedef max poolx return maximum in groups of 2x2 for a nhw image nhw xshape return npamaxxi112i12 for i in range4axis0def conv layerparamsx applies a convolutional layer wb followed by 22 pool followed by relu on x wbiases params num in wshape1 a for fbias in enumeratebiases conv out npsumscipysignalconvolve2dxiwfimodevalid for i in rangenum in axis0 aappendconv out bias x nparraya x max poolx return npmaximumx0w nprandomrandn321622astypenpfloat32b nprandomrandn32astypenpfloat32i nprandomrandn162525astypenpfloat32t0 timeo conv layerwbiprint timet0this prints 0084 seconds at the momentupdateusing mplfs suggestiond x11c x11b x11a x11for fbias in enumeratebiases conv out npsumaiwfi00biwfi01ciwfi10diwfi11 for i in rangenum in axis0i get 0075s which is slightly faster,['python'] +962314,how to execute nested asyncawait code in parallel while maintaining the same thread on await continuations this might be the worst stackoverflow title i have ever written what i am actually trying to do is execute an asynchronous method that uses the asyncawait convention and itself contains additional await calls from within a synchronous method multiple times in parallel while maintaining the same thread throughout the execution of each branch of the parallel execution including for all await continuations to put it another way i want to execute some async code synchronously but i want to do it multiple times in parallel now you can see why the title was so bad perhaps this is best illustrated with some codeassume i have the followingpublic class myasynccode async task methoda do some stuff await methodb some other stuff async task methodb do some stuff await methodc some other stuff async task methodc do some stuff the caller is synchronous from a console application let me try illustrating what i am trying to do with an attempt to use taskwaitall and wrapper taskspublic void mycallingmethod listtask tasks new listtask forint c 0 c 4 c myasynccode asynccode new myasynccode tasksaddtaskrun asynccodemethoda taskwaitalltaskstoarraythe desired behavior is for methoda methodb and methodc to all be run on the same thread both before and after the continuation and for this to happen 4 times in parallel on 4 different threads to put it yet another way i want to remove the asynchronous behavior of my await calls since i am making the calls parallel from the callernow before i go any further i do understand that there is a difference between asynchronous code and parallelmultithreaded code and that the former does not imply or suggest the latter i am also aware the easiest way to achieve this behavior is to remove the asyncawait declarations unfortunately i do not have the option to do this it is in a library and there are reasons why i need the continuations to all be on the same thread having to do with poor design of said library but even more than that this has piqued my interest and now i want to know from an academic perspectivei have attempted to run this using plinq and immediate task execution with asparallelselectx xmethodaresult i have also attempted to use the asynchelper class found here and there which really just uses unwrapgetawaitergetresult i have also tried some other stuff and i cannot seem to get the desired behavior i either end up with all the calls on the same thread which obviously is not parallel or end up with the continuations executing on different threadsis what i am trying to do even possible or are asyncawait and the tpl just too different despite both being based on tasks,['c#'] +962401,returning jintarray from jni i am trying to return a jintarray from c to java but the application seems to hang in the jni call i have stripped the problem down to the creation and population of the jintarray although i am not receiving any errors any help is appreciatedtest project to make sure everything worksinclude stdafxhinclude windowshinclude vectorinclude iostreaminclude jnihusing namespace stdstdvectorjint childwindowsbool callback enumchildprochwnd hwnd lparam lparam childwindowspush backjint hwnd return truejint getchildwindowshwnd hwnd childwindowsclear enumchildwindowshwnd enumchildproc null int len static castintchildwindowssize jint values100 stdcopychildwindowsbegin childwindowsend values for stdvectorjintconst iterator i childwindowsbegin i childwindowsend i stdcout hwndi envsetintarrayregionchilderen 0 len values return valuesint tmainint argc tchar argv getchildwindowshwnd1377258 stdcout windows count childwindowssize return 0output0d0550 0b04f2 001c047a 02055e 020558 010564 07054e 050570 060512 0c04e0 windows count 10java code systemoutprintlnget child windows systemoutprintlnmain handle gethandle final int handles getchildwindows systemoutprintlndone getting childsjava outputstarting test child windowsget child windowsmain handle 525978jni codejniexport jintarray jnicall java main getchildwindowsjnienv env jclass c childwindowsclear enumchildwindowshwnd enumchildproc null int len static castintchildwindowssize jintarray childeren envnewintarraylen jint values100 stdcopychildwindowsbegin childwindowsend values envsetintarrayregionchilderen jsize0 jsizelen values envreleaseintarrayelementschilderen values 0 return childeren,"['java', 'c++']" +962631,different initialization of base class attribute consider a base class that has an attributeclass base protected attributebase elementptr and a derived classclass derived public base also i have a class attributederived which derives from attributebasewhen i create an object of the class base i would like elementptr to be initialized in this wayelementptr new attributebasebut when i create an object of the class derived i would like elementptr to be initialized in this wayelementptr new attributederivedwhat is the cleanest way to do that,['c++'] +962634,creating an instance for class looking at source code of integer class just stumble at this below line classinteger type classinteger classgetprimitiveclassintand getprimitiveclass is a native method static native class getprimitiveclastring namewhy it became a native method really want to know how one can create an instance for class does that differs with normal way of creating instance for ex ex e new ex,['java'] +962670,how can i mark a message as read in mailkit i use mailkit to read some messages from a gmail account works great but when my application has read a message i want to mark the message as read and save that state to gmail is this possible with mailkit i have not found anything about it yetbest regardsrena,['c#'] +962718,why calling superfinalize is preferred when overriding finalize method i am getting sonarqube error that calling the superfinalize at the end of this method implementation is highly recommended in case parent implementations must also thispose some system resources but i found that object class has no implementation for finalize methodprotected void finalize throws throwable so why need to call superfinalize,['java'] +962730,xamarin vs ionic frameworks pros and cons i want to develop a new android application in c and i need to know which one is better for android development xamarin or ionic frameworkswhat are these ides pros and cons,['android'] +962811,ios uitableview whats the different between cellforrowatindexpath and willthisplaycell forrowatindexpath just as the questions title mentionswhats the difference between cellforrowatindexpath and willthisplaycell forrowatindexpathi think cell configuration can be done either in cellforrowatindexpath or willthisplaycell forrowatindexpath,['ios'] +962827,autocompletetextview float hint i have tried a lot but cannot make work an autocompletetextview float hint using the textinputlayout from supportit is possible or i need to use an external library,['android'] +962969,difference between memory order consume and memory order acquire i have a question regarding a gccwiki article under the headline overall summary the following code example is giventhread 1ystore 20xstore 10thread 2if xload 10 assert yload 20 ystore 10it is said that if all stores are release and all loads are acquire the assert in thread 2 cannot fail this is clear to me because the store to x in thread 1 synchronizes with the load from x in thread 2but now comes the part that i do not understand it is also said that if all stores are release and all loads are consume the results are the same wouldnt it be possible that the load from y is hoisted before the load from x because there is no dependency between these variables that would mean that the assert in thread 2 actually can fail,['c'] +963023,bindthis not working on ajax success function i use react and jquery heres a part of my codebefore react component mounts i perform ajax request to know if user is logged init is supposed to set state when a response returns status code 200am i incorrectly using bindthis componentwillmount function ajax url is signed in method get datatype json successfunctionresponse thissetstate signedin responsesigned in currentuser parsejsonresponsecurrent user bindthiscomponentdidmount function consolelogthisstatesignedinedit 01when i do consolelogthis in successfunctionresponse callbackthis was the belowrascasconstructor props object context object state object refs object reactinternalinstance reactcompositecomponentwrapper reactinternalinstance reactcompositecomponentwrapper context object currentelement reactelement instance reactclasscreateclassconstructor isownernecessary false istoplevel false mountimage null mountindex 0 mountorder 2 pendingcallbacks null pendingelement null pendingforceupdate false pendingreplacestate false pendingstatequeue null renderedcomponent reactcompositecomponentwrapper rootnodeid 0 warnedaboutrefsinrender false proto reactcompositecomponentwrappercontext object proto object definegetter definegetter definesetter definesetter lookupgetter lookupgetter lookupsetter lookupsetter constructor objecthasownproperty hasownpropertyisprototypeof isprototypeofpropertyisenumerable propertyisenumerabletolocalestring tolocalestringtostring tostringvalueof valueofget proto get proto set proto set proto getdomnode reactboundarguments null reactboundcontext reactclasscreateclassconstructor reactboundmethod arguments bind newthis caller length 0name proto targetfunction boundthis reactclasscreateclassconstructorboundargs array0props objectrefs object proto objectrenderbuttonset setsignedin reactboundarguments null reactboundcontext reactclasscreateclassconstructor reactboundmethod setsignedinresponsearguments caller length 1name setsignedinprototype setsignedin proto function scopearguments bind newthis arguments caller length 1name prototype boundmethodbind proto function scopecaller length 1name proto targetfunction setsignedinresponseboundthis reactclasscreateclassconstructorboundargs array0state objectcurrentuser objectcreated at 20150724t1830387720900email facebook account url nullfirstname i igithub account url nullgoogleplus account url nullid 1lastname ilinkedin account url nullsns avatar nulltwitter account url nullupdated at 20150814t0214210910900 proto objectsignedin true proto object proto reactclasscomponentsolutionsmy code above was antipatternfollow one of the methods suggested by answer i adopted plus react documentation already provided very useful solution about my case load initial data via ajaxalso setstate is asynchronousthat is why i thought setstate not working when i log it on consoleafter all i checked inside render and pass as props to child components,"['javascript', 'jquery']" +963213,why are the results of of str strintern for these strings different public static void mainstring args string str1 new stringbuilderecoappende12 atostring systemoutprintlnstr1intern str1 string str2 new stringbufferjaappendvatostring systemoutprintlnstr2intern str2results true false first one prints true and the second prints false why are the results different,['java'] +963241,why can int today i found strange syntax like int 0in some old code but in fact the code is not commented there seems to be no report of compile errors for this line i tested it separately and it can compile tooint main int 0 return 0why can it compile,['c'] +963276,usemin and multiple build configurations following is the sample usemin build configuration in my indexhtml file buildjs jsonejs script srcappmodulesoneonejsscriptscript srcappmodulesonetwojsscriptscript srcappmodulesonethreejsscript endbuild buildjs jstwojs script srcappmodulestwoonejsscriptscript srcappmodulestwotwojsscriptscript srcappmodulestwothreejsscript endbuild for development version i dont want to minify the scripts and i want each module into its own js file so the indexhtml after running would bescript srcjsonejsscriptscript srcjstwojsscriptfor production versioni want to minify the scripts and concat them into a single fileso the indexhtml would bescript srcjsmyappjsscripti tried the following but it is not working buildmyapp jsmyappjs buildjs jsonejs script srcappmodulesoneonejsscriptscript srcappmodulesonetwojsscriptscript srcappmodulesonethreejsscript endbuild buildjs jstwojs script srcappmodulestwoonejsscriptscript srcappmodulestwotwojsscriptscript srcappmodulestwothreejsscript endbuild endbuild and run the usemin task like this prod would be set to true in the prod task and false in dev task usemin myapp produglifymangletrue js produglifymanglefalse i can keep two indexhtml files and manage thisbut i was wondering can this be achieved with a single indexhtmlthanks in advance for any help,['javascript'] +963333,associativity math a b c a b c recently i was going through an old blog post by eric lippert in which while writing about associativity he mentions that in c a b c is not equivalent to a b c for certain values of a b c i am not able to figure out for what types and range of arithmetic values might that hold true and why,"['c#', '.net']" +963345,php syntax surprise with conditional operator and or today i was openmouthed by the followingasdf 1 or true asdf fdsavar dumpasdf print asdfasdf 1 or true asdf fdsavar dumpasdf print asdfasdf 1 or true asdf fdsavar dumpasdf print trueasdf 1 or true asdf fdsavar dumpasdf print 1ok the last does not surprise me much but the thirdcan anyone explain,['php'] +963596,matplotlib legend vertical rotation does someone perhaps know if it is possible to rotate a legend on a plot in matplotlib i made a simple plot with the below code and edited the graph in paint to show what i wantpltplot456 label testax pltgcaaxlegendpltshow,['python'] +963605,how to download csv file from function in wordpress plugin i have built a plugin for a client so that they can download data as a csv file it is been set up so that when the user clicks on a link in the menu the csv should just automatically download however it does not quite work like that and just loads the function as a page in the wordpress backendthis is the code i have for the functionfunction download payment csv include libconnectionphp csv output values dbqueryselect from tbpayments order by date desc i0 while rowr mysql fetch rowvalues for j0jij csv output rowrj csv output n headerpragma public headerexpires 0 headercachecontrol mustrevalidate postcheck0 precheck0 headercachecontrol private false headercontenttype applicationoctetstream headercontentthisposition attachment filenamereportcsv headercontenttransferencoding binary echo csv outputand as i said it just returns a blank screen any help would be appreciatededitso this is the code i am now working with taking bits from whats been said alreadyfunction download payment csv include libconnectionphp csv output values load payment csv fp fopenphpoutput w file test export filename file dateymd hitime headercontenttype textcsv headercontentthisposition attachment filenamefilenamecsv thisable caching headercachecontrol nocache nostore mustrevalidate http 11 headerpragma nocache http 10 headerexpires 0 proxies headercontenttransferencoding utf8 ifcountvalues 0 foreachvalues as result fputcsvfp result fclosefpthis generates a csv but there is a problem with itthe problem is that when viewing the page it does not download it as a csv it just outputs the contents of the csv in to the page however adding this function to the top of the pluginadd actionadmin initdownload payment csvthis then triggers a download when the menu link is clicked which is fine but it triggers it for every menu item in the plugin which is wrong it should only trigger when the download link is clicked,['php'] +963758,webkit browsers showing blue text as slightly purple i cannot find any info on this issue in google because every result is about the default purple avisited color that is not the issue here the issue is with chromes default antialiasing on some systems blue text shows up as blueishpurple if i change the antialiasing to webkitfontsmoothing antialiased it keeps the correct color but then the fonts are radically different between chrome and firefox the blue color i am using is the clients color so it cannot change to purple like this i am hoping somebody has a fix for thishere are screenshots from tests i have doneedit just to clarify this has nothing to do with the default avisited link color my blue color is being inherited but chromes antialiasing is causing the text to appear purple heres an example,['css'] +963840,breaking a reactnative appliction into plugable modules i am looking to write a reactnative application i want to be able to download new modules at runtime on the device to extend functionality there would be some core logic that knows how to request new modules based on some form input like a dbs i do not want to bundle everything into a single monolithic bundle which is what i believe happens now with the built in packager this would something similar to how requirejs works in browser what i need to know ishow do i build independent modules reactnative bundle does not seem to allow me to select which root modules to begin with and only works on root projecthow can i at runtime request new functionality be injected into the current javascript environment,['javascript'] +963917,c should you size t with a regular array i am confused about size t i know it is an unsigned typerightmy question is when should it be used is there a reason why it should be used with a regular array i mean one would have to declare the array size to be really huge so huge that a regular unsigned or signed wouldnt be able to handle it and then a size t would be able to deal with it right can someone give me an example,['c++'] +963994,android google maps v2 inside scrollview shows gray tiles on some devices there is android google maps v2 inside scrollviewit works on many devices but shows gray tiles on some devicesapi key is correct to use google maps v2 inside scrollview should to use custom class extends supportmapfragment like this public class workaroundmapfragment extends supportmapfragment private ontouchlistener mlistener override public view oncreateviewlayoutinflater layoutinflater viewgroup viewgroup bundle savedinstance view layout superoncreateviewlayoutinflater viewgroup savedinstance touchablewrapper framelayout new touchablewrappergetactivity framelayoutsetbackgroundcolorgetresourcesgetcolorandroidrcolortransparent viewgroup layoutaddviewframelayout new viewgrouplayoutparamsviewgrouplayoutparamsmatch parent viewgrouplayoutparamsmatch parent return layout public void setlistenerontouchlistener listener mlistener listener public interface ontouchlistener public abstract void ontouch public class touchablewrapper extends framelayout public touchablewrappercontext context supercontext override public boolean thispatchtoucheventmotionevent event switch eventgetaction case motioneventaction down mlistenerontouch break case motioneventaction up mlistenerontouch break return superthispatchtoucheventevent and also set workaroundmapfragment getsupportfragmentmanagerfindfragmentbyidridmapsetlistenernew workaroundmapfragmentontouchlistener override public void ontouch mscrollviewdarequestthisallowintercepttoucheventtrue the image bellow taken by users android version 422 device samsung grand 2app tested on samsung galaxy tab 2 101 403 and asus fonepad 7 tablet 501 and works wellandroidminsdkversion10,['android'] +964032,grizzly pipe leak what am i doing wrong i have written the following test codetestpublic void testleakwithgrizzly throws throwable executorservice executor executorsnewfixedthreadpooln threads setfuturevoid futures new hashset inetsocketaddress inetsocketaddress new inetsocketaddresslocalhostaddress 1 for int i 0 i and threads i futurevoid future executorsubmitnew grizzlyconnecttaskinetsocketaddress requests bindfailures successfulopens failedopens successfulcloses failedcloses futuresaddfuture for futurevoid future futures futureget block threadsleep10 let everything calm down reporterreport throw causeofdeath private static class grizzlyconnecttask implements callablevoid private final inetsocketaddress address private final meter requests private final meter bindfailures private final counter successfulopens private final counter failedopens private final counter successfulcloses private final counter failedcloses public grizzlyconnecttaskinetsocketaddress address meter requests meter bindfailures counter successfulopens counter failedopens counter successfulcloses counter failedcloses thisaddress address thisrequests requests thisbindfailures bindfailures thissuccessfulopens successfulopens thisfailedopens failedopens thissuccessfulcloses successfulcloses thisfailedcloses failedcloses override public void call throws exception while die tcpniotransport transport null boolean opened false try transport tcpniotransportbuildernewinstancebuild transportstart transportconnectaddressget block opened true successfulopensinc successful open requestsmark catch throwable t noinspection throwableresultofmethodcallignored throwable root getrootcauset if root instanceof bindexception bindfailuresmark ephemeral port exhaustion continue causeofdeath t die true finally if opened failedopensinc if transport null try transportshutdownget block successfulclosesinc successful close catch throwable t failedclosesinc systemerrprintlnwhile trying to close transport tprintstacktrace else no transport successful close successfulclosesinc return null on my linux laptop this crashes in 5 minutes with the following exceptionjavaioioexception too many open files at sunniochepollarraywrapperepollcreatenative method at sunniochepollarraywrapperinitepollarraywrapperjava130 at sunniochepollselectorimplinitepollselectorimpljava68 at sunniochepollselectorprovideropenselectorepollselectorproviderjava36 at orgglassfishgrizzlynioselectorsnewselectorselectorsjava62 at orgglassfishgrizzlynioselectorrunnercreateselectorrunnerjava109 at orgglassfishgrizzlynioniotransportstartselectorrunnersniotransportjava256 at orgglassfishgrizzlynioniotransportstartniotransportjava475 at netradaileaktestgrizzlyconnecttaskcaleaktestjava137 at netradaileaktestgrizzlyconnecttaskcaleaktestjava1 at javautilconcurrentfuturetaskrunfuturetaskjava266 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava1142 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava617 at javalangthreadrunthreadjava745the successfail counters look like this counters failedcloses count 0failedopens count 409successfulcloses count 177177successfulopens count 136178 meters bindfailures count 40998 mean rate 15310 eventssecond 1minute rate 14461 eventssecond 5minute rate 9112 eventssecond 15minute rate 3956 eventssecondrequests count 136178 mean rate 50854 eventssecond 1minute rate 54738 eventssecond 5minute rate 44276 eventssecond 15minute rate 39153 eventssecondwhich tells me thatthere were no close failuresall connections either failed to create or were successfully closed 136178 409 177177all failures to open were ephemeral port exhaustion except for the last one 409 40998 1the complete code is up on github here so am i somehow misusing the grizzly api or is this a real leaknote im using grizzly 2312 which i know is not the latest upgrading would require convincing people which is why i want to be positive this is not user error on my endedit this thing leaks even when nothing is thrown cutting back to a single thread and putting a 2ms sleep in there still leaks 800 pipes over 50 minutes,['java'] +964235,async download inside didreceiveremotenotification my app is configured to support silent push contentavailable and also supports background fetch want i need to achieve is upon receiving a silent push i need to send an ajax request to the server get back the data and save it persist it with coredata of course all this happens without the user ever opening the app when he do opens up the app a fresh data will be waiting this is the silent push call back func applicationapplication uiapplication didreceiveremotenotification userinfo nsobject anyobject fetchcompletionhandler completionhandler uibackgroundfetchresult void use alamofire to make an ajax call let mutableurlrequest nsmutableurlrequesturl url let requestbodydata nsmutabledata nsmutabledata mutableurlrequesthttpbody body mutableurlrequesthttpmethod post mutableurlrequestsetvaluebearer accesstoken forhttpheaderfield authorization mutableurlrequestsetvalueapplicationjson forhttpheaderfield contenttype requestmutableurlrequest responsejson req res data error in we do not reach this code block save the incoming data to coredata completionhandleruibackgroundfetchresultnewdata now the problem is that when a notification arrives and the delegate is called the ajax code executes make the call to the server and then exits the code inside the ajax callback will not run but when i open the app and brings it to the foreground suddenly this code section wakes up and continues to run this is not the desirable behaviour because when i open the app i still need to wait 12 seconds for the those operations to run updating the ui etc what am i doing wrong here should i open a new background thread for this operationupdatei moved completionhandleruibackgroundfetchresultnewdata into the ajax callback but still this dose not fix the original problem which is that this ajax callback code block would not execute update 2it seems like it is an issue with alamofire and that i will have to use nsurlsession to make this ajax call trying to put some code together,['ios'] +964324,memory leak with large core data batch insert in swift i am inserting tens of thousands of objects into my core data entity i have a single nsmanagedobjectcontext and i am calling save on the managed object context every time i add an object it works but while it is running the memory keeps increasing from about 27m to 400m and it stays at 400m even after the import is finishedthere are a number of so questions about batch insert and everyone says to read efficiently importing data but it is in objectivec and i am having trouble finding real examples in swift that solve this problem,['ios'] +964371,how to scan two images for differences i am trying to scan 2 images 32bppargb format identify when there is a difference and store the difference blocks bounds in a list of rectanglessuppose these are the imagessecondi want to get the different rectangle bounds the opened directory window in our casethis is what i have doneprivate unsafe listrectangle codeimagebitmap bmpbitmap bmp2 listrectangle rec new listrectangle bmdata bmplockbitsnew systemdrawingrectangle0 0 1920 1080 systemdrawingimagingimagelockmodereadonly bmppixelformat bmdata2 bmp2lockbitsnew systemdrawingrectangle0 0 1920 1080 systemdrawingimagingimagelockmodereadonly bmp2pixelformat intptr scan0 bmdatascan0 intptr scan02 bmdata2scan0 int stride bmdatastride int stride2 bmdata2stride int nwidth bmpwidth int nheight bmpheight int minx intmaxvalue int miny intmaxvalue int maxx 0 bool found false for int y 0 y nheight y byte p bytescan0topointer p y stride byte p2 bytescan02topointer p2 y stride2 for int x 0 x nwidth x if p0 p20 p1 p21 p2 p22 p3 p23found differencesbegan to store positions found true if x minx minx x if x maxx maxx x if y miny miny y else if found int height getblockheightstride scan0 maxx minyscan02stride2 found false rectangle temp new rectangleminx miny maxx minx height recaddtemp x minx y height minx intmaxvalue miny intmaxvalue maxx 0 p 4 p2 4 return rec public unsafe int getblockheightint stride intptr scan int x int y1intptr scan02int stride2a function to get an existing block height int height 0 for int y y1 y 1080 yonly for example in our case its 1080 height byte p bytescantopointer p y stride x 4set the pointer to a specific potential point byte p2 bytescan02topointer p2 y stride2 x 4 set the pointer to a specific potential point if p0 p20 p1 p21 p2 p22 p3 p23still change on the height in the increasing y of the block height return height this is actually how i call the method bitmap a imagefromfilecusersitapidesktop1png as bitmapgenerates a 32bpprgba bitmap bitmap b imagefromfilecusersitapidesktop2png as bitmap listrectangle l1 codeimagea b int i 0 foreach rectangle rec in l1 i bitmap tmp bclonerec apixelformat tmpsaveitostring png but i am not getting the exact rectangle i am getting only half of that and sometimes even worse i think something in the codes logic is wrongcode for nico private unsafe listrectangle codeimagebitmap bmp bitmap bmp2 listrectangle rec new listrectangle var bmdata1 bmplockbitsnew systemdrawingrectangle0 0 bmpwidth bmpheight systemdrawingimagingimagelockmodereadonly bmppixelformat var bmdata2 bmp2lockbitsnew systemdrawingrectangle0 0 bmpwidth bmpheight systemdrawingimagingimagelockmodereadonly bmp2pixelformat int bytesperpixel 3 intptr scan01 bmdata1scan0 intptr scan02 bmdata2scan0 int stride1 bmdata1stride int stride2 bmdata2stride int nwidth bmpwidth int nheight bmpheight bool visited new boolnwidth nheight byte base1 bytescan01topointer byte base2 bytescan02topointer for int y 0 y nheight y5 byte p1 base1 byte p2 base2 for int x 0 x nwidth x5 if arepixelsequalp1 p2 bytesperpixel visitedx nwidth y fill the different area int minx x int maxx x int miny y int maxy y var pt new pointx y stackpoint tobeprocessed new stackpoint visitedx nwidth y true tobeprocessedpushpt while tobeprocessedcount 0 var process tobeprocessedpop var ptr1 bytescan01topointer processy stride1 processx bytesperpixel var ptr2 bytescan02topointer processy stride2 processx bytesperpixel check pixel equality if arepixelsequalptr1 ptr2 bytesperpixel continue this pixel is different update the rectangle if processx minx minx processx if processx maxx maxx processx if processy miny miny processy if processy maxy maxy processy point n int idx put neighbors in stack if processx 1 0 and new pointprocessx 1 processy idx nx nwidth ny if visitedidx visitedidx true tobeprocessedpushn if processx 1 nwidth and new pointprocessx 1 processy idx nx nwidth ny if visitedidx visitedidx true tobeprocessedpushn if processy 1 0 and new pointprocessx processy 1 idx nx nwidth ny if visitedidx visitedidx true tobeprocessedpushn if processy 1 nheight and new pointprocessx processy 1 idx nx nwidth ny if visitedidx visitedidx true tobeprocessedpushn if maxx minx 1 5 maxy miny 15 recaddnew rectangleminx miny maxx minx 1 maxy miny 1 p1 5 bytesperpixel p2 5 bytesperpixel base1 5 stride1 base2 5 stride2 bmpunlockbitsbmdata1 bmp2unlockbitsbmdata2 return rec,['c#'] +964429,flat ui radiocheck plugin radio buttons do not toggle anymore with ios 841 i am using the latest version of flat ui pro 132 and there seems to be a problem with the jquery plugin flatuiradiocheck v010 and ios devicesyou can see the problem when you load their demo page go to the section with the radio buttons and click on the two buttons radio is on and radio is off to toggle the radio button this toggling toggling the state visually as well as the state of the radio element in the dom works fine in all major desktop browsers ie ff safari windowshowever there is a problem with safari on ios i am running the latest ios version on an iphone 4s 841 clicking the two radio buttons does not toggle their state anymoreit seems to be related to possibly the new version of mobile safari on ios since it works fine on desktop browsersany idea or help on how to debug this error is greatly appreciated,"['jquery', 'ios']" +964430,how to add rectangles on top of existing rectangle in canvas i am trying to add some red rectangles within my existing canvas on top of specific boxes exactly like the expected result image but they do not appear at all as my code shows the current undesired outcome when i deploy my app my code is to create 4 rectangles on the top row and 4 rectangles on the bottom row but i only want this to be added on top of boxes 26 but i know extra code needs to be added for the red rectangles on top of boxes 1 7 does anyone know what i am doing wrong and how to fix this all help would be appreciatedpublic class rectangletextview extends view private final paint mblackpaint new paint private final paint mredpaint new paint private final textpaint mtextpaint public rectangletextviewcontext context attributeset attrs supercontext attrs int valueindp int typedvalueapplydimensiontypedvaluecomplex unit dip 1 getresourcesgetthisplaymetrics int valueinsp int typedvalueapplydimensiontypedvaluecomplex unit sp 20 getresourcesgetthisplaymetrics mredpaintsetcolorcolorparsecolorcc3 mblackpaintsetantialiasfalse mblackpaintsetcolorcolorblack mblackpaintsetstrokewidthvalueindp mblackpaintsetstylepaintstylestroke mtextpaint new textpainttextpaintanti alias flag mtextpaintsetcolorcolorblack mtextpaintsettextalignpaintaligncenter mtextpaintsettextsizevalueinsp mwindowpaint new paint mwindowpaintsetcolorcolorparsecolorcc3 mwindowpaintsetstrokewidthvalueindp private paint mwindowpaint override protected void ondrawcanvas canvas superondrawcanvas if getwidth 0 return initialise red rectangles int w canvasgetwidth int h canvasgetheight int rectwidth w 5 int space w 15 int toprectheight getpaddingtop int bottomrectheight getpaddingbottom draw end rectangles int msiderectwidth 10 canvasdrawrect0 0 msiderectwidth getheight mredpaint draw left end rectangle canvasdrawrectgetwidth msiderectwidth 0 getwidth getheight mredpaint draw right end rectangle draw grey boxes setbackgroundcolorcolorparsecolor808080 int boxwidth getwidth msiderectwidth 7 draw text views for int i 0 i 7 i canvasdrawtextintegertostringi 1 i boxwidth 10 boxwidth 2 canvasgetheight 2 mtextpaintdescent mtextpaintascent 2 mtextpaint draw black lines for int i 1 i 7 i canvasdrawlinemsiderectwidth boxwidth i 0 msiderectwidth boxwidth i getheight mblackpaint draw red windows for int i 0 i 4 i mwindowpaintsetstylepaintstylestrokeadd this int left i rectwidth space int right left rectwidth if i 1 mwindowpaintsetstylepaintstylefill change to this rect rect new rectleft 0 right toprectheight canvasdrawrectrect mwindowpaint rect rect2 new rectleft h bottomrectheight right h canvasdrawrectrect2 mwindowpaint expected resultcurrent undesired outcomeactivity mainxmlrelativelayout xmlnsandroid xmlnstools androidlayout widthmatch parent androidlayout heightmatch parent androidpaddingleftdimenactivity horizontal margin androidpaddingrightdimenactivity horizontal margin androidpaddingtopdimenactivity vertical margin androidpaddingbottomdimenactivity vertical margin toolscontextmainactivity comapptacularappscarrectangletextview androidlayout width100dp androidlayout height45dp androidpaddingtop10dp androidpaddingbottom10dp androidbackground808080 androidgravitycenterrelativelayoutmainactivityjavaimport androidosbundleimport androidsupportv7appappcompatactivitypublic class mainactivity extends appcompatactivity override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main,"['java', 'android']" +964508,why are generator methods constructors methods when declared as methods using es6 enhanced object literals or classes are not constructors does not have a prototype chainbut generators when declared via the method syntax do have a prototype chain and are constructorstake the following example requires v8use strictclass x a thisb b printclass method let i new xiaprototypeb function printgenerator method ianextnew ianextoutputsclass methodgenerator methodwhile adding prototypes to ib and calling new ib will throw an error because ib is not a constructori am able to do new ia and this inside a gets a different contextwhy does this difference existwhat is the use case for having prototype in generators defined as methods,['javascript'] +964578,cropping image with swift and put it on center position in swift programming how do you crop an image and put it on the center afterwardsthis is what i have got so far i have successfully crop the image but i want to put it on the center after imgviewimage origimage var masklayer cashapelayer masklayerframe imgviewframe masklayerpath pathcgpath masklayerfillcolor uicolorwhitecolorcgcolor masklayerbackgroundcolor uicolorclearcolorcgcolor imgviewlayermask masklayer uigraphicsbeginimagecontextimgviewboundssize imgviewlayerrenderincontextuigraphicsgetcurrentcontext var image uigraphicsgetimagefromcurrentimagecontext imgviewimage image uigraphicsendimagecontextupdate let rect cgrect cgrectmakepathboundsminx pathboundsminy pathboundswidth pathboundsheight create bitmap image from context using the rect let imageref cgimageref cgimagecreatewithimageinrectimagecgimage rect imgviewbounds rect imgviewimage uiimagecgimage imagerefi was able to center it by getting the pathbound and size and change the bounds of my imageview,['ios'] +964636,is there a way to group or temporarily thisable the undo history for a richtextbox i am currently wrestling with tables inside richtextboxs in wpf in wpf tables do not have rows and columns they just have rows each having a certain number of cells when a user presses the add column button my program adds a new cell to each row the problem with using this method is after a user adds a column if they press undo it removes each cell one by one obviously not what the user would expectdoes anyone know a way to temporarily thisable the addition of actions to the undo queue or a way to group undo actions or any other solution to my problem,['c#'] +964838,android studio errorandroidstudiogradlegradle24libpluginsgradlediagnostics24jar no such file or directory i have just installed android studio 13 into my ubuntu 1404 64bit i created a new project and after finishing the process android studio shows gradle myapplication project refresh failedi found same type of questions in stackoverflow but any of the solution did not fit for me i could not figure out the problemhere are some screenshotsafter creating a new project it shows the following messagewhen i opened the gradlewrapperproperties filei found as followingwhen i checked the directory androidstudiogradlegradle24libplugins i found the file gradlediagnostics24jarhere is the log file please help me to solve the problem,"['java', 'android']" +964886,zoomablescrollable html window in mobile browsers i am trying to create a div window with inner elements to be able to scrollzoom on mobile with its contents like herei would like to be able to do followingon page load scale scrollable zoomable background to fit the windowto be able to zoom with two finger gestures scroll with touchstart touchendthe rest of the page must not zoom nor scroll horizontally with meta nameviewport contentwidthdevicewidthinitialscale1maximumscale1the window must not be an iframe it needs to be part of the document structure,"['javascript', 'html', 'css']" +964921,issue with robolectric with new version of google play services i use robolectric for unit tests i have google play services in my project this worked fine until yesterday when google play services updated to a new version i get this errorjavalangnullpointerexceptionat comgoogleandroidgmscommongoogleplayservicesutilzzhunknown sourceat comgoogleandroidgmscommongoogleplayservicesutilzzdunknown sourceat comgoogleandroidgmscommongoogleapiavailabilityisgoogleplayservicesavailableunknown sourceat comgoogleandroidgmscommonapizzgzzezznnunknown sourceat comgoogleandroidgmscommonapizzgzzirununknown sourceat javautilconcurrentexecutorsrunnableadaptercallexecutorsjava511at javautilconcurrentfuturetaskrunfuturetaskjava266at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava1142at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava617at javalangthreadrunthreadjava745process finished with exit code 255it seems the shadow class is not called googleplayservicesutil is called giving the nullpointerexception has anyone seen thisi do not even use google play services in the tests,['android'] +964943,c 6 autoproperties read once or every time i follow a pattern when setting certain properties whereby i check to see if the corresponding field is empty returning the field if not and setting it if so i frequently use this for reading configuration settings for example so that the setting is read lazily and so that it is only read once here is an exampleprivate string databaseid get if stringisnulloremptydatabaseid databaseid cloudconfigurationmanagergetsettingdatabase return databaseid i have started to use c 6 autoproperty initialization as it really cleans up and makes my code more concise i would like to do something like thisprivate string databaseid get cloudconfigurationmanagergetsettingdatabasebut i am not sure how the compiler interprets it in this case will this have the same effect as my first block of code setting the automatically implemented field once and thereafter reading from the field or will this call the cloudconfigurationmanager every time i get databaseid,['c#'] +965012,firefox thisable the add on i am developing i am developing an firefox addon with it is latest jpm sdkafter i done the major code i use jpm run command to run the extensionbut the addon is thisabled it says addon name could not be verified for use in firefox version and has been thisabledlike in the pictureanyone know how to turn off this firefox feature,['javascript'] +965037,httpshandler error while installing pip with python 279 hi i am trying to install pip with python 279 but keep getting following error i want to create python virtual env python getpippy traceback most recent call last file getpippy line 17767 in module main file getpippy line 162 in main bootstraptmpdirtmpdir file getpippy line 82 in bootstrap import pip file tmptmp tfw2vpipzippip init py line 15 in module file tmptmp tfw2vpipzippipvcssubversionpy line 9 in module file tmptmp tfw2vpipzippipindexpy line 30 in module file tmptmp tfw2vpipzippipwheelpy line 35 in module file tmptmp tfw2vpipzippip vendorthistlibscriptspy line 14 in module file tmptmp tfw2vpipzippip vendorthistlibcompatpy line 31 in module importerror cannot import name httpshandleri guess this is something related to openssl libraries since i do not have sudo access i would like to install it in home folder from source any idea how to do it,['python'] +965052,why only the last menu item has icon in wpf i am programmatically adding a context menu to a control var contextmenu new contextmenu contextmenuitemsaddnew menuitem header copy all icon findresourcecopyimage contextmenuitemsaddnew menuitem header copy all with headers icon findresourcecopyimage contextmenuitemsaddnew menuitem header copy selected icon findresourcecopyimage contextmenuitemsaddnew menuitem header copy selected with headers icon findresourcecopyimage copyimage is defined in my application resource image xkeycopyimage sourceimagescopypngat runtime only the last menu item shows the icon the other three menu items do not does anyone have an explanation for this behavior,['c#'] +965073,smallest multiple having only 0 and 4 as its digits given a number a find the smallest number b such that a b contains digits 4 and 0 only and zeroes should only be in the end ie numbers like 404 are not validfor example a b ab 1 4 4 2 2 4 3 148 4 4 1 4 5 8 40 well i attempted the question in this manner maintain a queue of integers the smallest possible number is 4 pop the number ie the front element of the queue and push the numbers that can be derived from this popped number that is when we pop 4 we push 410 40 and 410 4 44 with the constraint that the popped number is not divisible by 10 if it is push only its next multiple of 10so my queue will be like 4404004404 as i am popping elements from the queue i will check if it is divisible the given number a if yes just break and the number popped is my desired resultbecause my number can be really large i maintained a queue of pairstringint where string corresponds to the number and int corresponds to the remainder thus remainder of the next stage can be computed easilyex queue 44 pop current result is string 4 and remainder is lets say prev 4check if the last digit is 0 or not for checking if its a multiple of 10 or notif not then append 0 to this string and remainder as prev10a and push this pair in the queue also append 4 to this string with remainder as prev10 4a and push if the last digits is 0 append 0not 4 and corresponding remainder push this pair in the queuequeue 40prev10a 44 prev10 4a and so ontill the pair in the front of the queue has remainder 0 well continue doing thisthough this improvement seemed to be a bit good but not correct and did not pass all the test cases can someone please throw some light on how this should be solved in an optimal manner the range of a is 1010,['c++'] +965290,android appcompat v723 today google released sdk 6 api 23i tried to create a project with the api 23 but i am having the following problemfailed to resolve comandroidsupportappcompatv7230heres my gradle fileandroid compilesdkversion 23 buildtoolsversion 2300 defaultconfig applicationid mypackage minsdkversion 17 targetsdkversion 23 versioncode 1 versionname 10 buildtypes release minifyenabled false proguardfiles getdefaultproguardfileproguardandroidtxt proguardrulespro dependencies compile filetreedir libs include jar wearapp projectwear compile comandroidsupportappcompatv7230 compile comgoogleandroidgmsplayservices780in the sdk manager the version 23 is not listed to updatehow can i solve this,['android'] +965311,mdilxapcompileexe failed with error code 2001 releasedebug arm deploy to device is not possible but the build succeedsi get following exceptionseverity code description project file line error error dep6810 mdilxapcompileexe failed with error code 2001 see log file cusersobjarmdebugmdilmdilxapcompilelogtxt for more detailsmdilxapcompilelogtxtcrossgen failed error processing assembly cusersobjarmdebugmsilmicrosoftbanddll raw error code 2148733978google lead me to following solutionclose visual studionavigate to yoursolutionpackages delete everything except packagesconfig reopen the solution in visual studio right click on solution and select manage nuget packagesclick the restore button that appears at the top of the dialogwindowdoes not work for me any other suggestionsthanks in advance,['c#'] +965387,method floatmathsqrt not found i am using the new android marshmallow sdk and the method floatmathsqrt is gone what should i use now,['android'] +965461,java regex how to find the parent match any page from wikipediaabas asdn asf asfs aftemplate1a name surnameb jhsdf sdfc template2d e f and gh asd asdasfgasgasg asgas jygh trdx dftf xcthi 73j template2abc123j template3aakbbtemplate4ccuuasd wetd gdsgwew gothertemplatesdf 213how can i find template1s content start is a end is with java regexesi tried string pattern stemplate1spattern p patterncompilepattern patterncase insensitive patternmultiline patterndotallmatcher m pmatchercontentwhile mfind if mgroupequals systemoutprintlnmgroup systemoutprintln but in here the regex is finding the first which is template2 then stopsi want to pass is any is open then i want to find top parent matchi want to get top template1 content between top and editplease keep in mind that i am parsing content after removing white spacescontentreplacealls think of content as writing a single line,['java'] +965475,why this chain of promises immediately resolves can someone explain to me why the resulting promise d from the code below is resolved immediatelypromises that are never resolved nor rejectedvar a new promisefunctionrrevar b new promisefunctionrrevar c new promisefunctionrrevar d a b creducefunction previouspromise promise return previouspromisethenpromise promiseresolvei am creating an array of promises that are pending forever so the resulting promise should also be pending forever as it waits for all subsequent promises to finish as presented here i have been using promises for a while now but i am clearly missing something here,['javascript'] +965514,handling java exceptions caught in constructors with final members i have some ugly code and want to refactor itpublic class udptransport extends abstractlayerbyte private final datagramsocket socket private final inetaddress address private final int port boolean dead is provided by superclass public udptransportstring host int port thisport port inetaddress tmp address null try tmp address inetaddressgetbynamehost catch unknownhostexception e eprintstacktrace dead true socket null address null return address tmp address datagramsocket tmp socket null try tmp socket new datagramsocket catch socketexception e eprintstacktrace dead true socket null return socket tmp socket the issue causing the ugliness is the interaction between final members and caught exceptions i would like to keep the members final if possiblei would like to form the code as follows but the java compiler cannot analyse the control flow there is no way that address could be assigned a second time as the first attempted assignment must have thrown for control to have reached the catch clausepublic udptransportstring host int port thisport port try address inetaddressgetbynamehost catch unknownhostexception e eprintstacktrace dead true address null can only have reached here if exception was thrown socket null return error27 13 error variable address might already have been assignedany adviceps i have a constraint which is that the constructors do not throw otherwise this would all be easy,['java'] +965526,is negative index for operator well defined i know it would be very bad codingstyle but the following code runs perfectly on my machine but is the behavior well defined portableint main int p new int3 int q p2 q1 41 stdcout p1 delete p,['c++'] +965570,preferencefragmentcompat requires preferencetheme to be set with the new preferencefragmentcompat from the v7 preference support library i get this errore javalangillegalstateexception must specify preferencetheme in themee at androidsupportv7preferencepreferencefragmentcompatoncreatepreferencefragmentcompatjava202what theme should be setupdate i have tried usingitem namepreferencethemestylepreferencethemeoverlayitemas suggested by bogato but it does not look right and looks very holo even on lollipopsupport librarynative preferences,['android'] +965638,work out values from loaded information i need to be able to show a dynamic return for each bet that the user has in place but for some reason none of them work i have previously asked this question before but with no lucki am hoping that the extra detail in this will be sufficient to help with getting an answer to this at lasti have hard coded one of the scripts in so to use odds1 stake1etc and this worked but the others have notif anybody can help with this it would be greatly appreciatedjavascript var count div 0 diveachfunction count div consolelogcounter count div for var i 0 i count div i stake ionkeyup function var newval parsefloatstake ival 10 parsefloat odds ival 10 parsefloatstake ival 10 0 showdynamicreturn ivalparsefloatnewvaltofixed2 phpfunction readbets link id currentpage loggedin true idcount 0 querybase select from bets where user id s ifloggedin true querybase2 sprintfquerybase id else querybase2 sprintfquerybase id selectquery linkqueryquerybase2 return div stylemaxheight 680px overflow auto whileresult mysqli fetch arrayselectquery idcount ifresultodds sp odds sp else odds explode resultodds odds odds0 odds1 return div styleborder 1pt solid black width 99 return h2 stripslashesresulttitle h2 return form action methodpost return table classtable tablecondensed return trtd stylewidth50sport tdtd resultsport tdtr return trtd stylewidth50participant tdtd stripslashesresultparticipant tdtr return trtdmarket tdtd stripslashesresultmarket tdtr return trtdtime tdtd datehi strtotimeresultbet till time tdtr return trtdodds tdtd resultodds input typehidden value odds id odds idcount tdtr return trtdstake tdtddiv classinputgroupspan classinputgroupaddon idbasicaddon1poundspaninput stylewidth100 typetext namestake idstake idcount ariadescribedbybasicaddon1 placeholderstake divtdtr return tr iddynamic returntd colspan10centerdiv classinputgroupspan classinputgroupaddon idbasicaddon2estimated return poundspaninput stylewidth100 typetext idshowdynamicreturn idcount ariadescribedbybasicaddon2 placeholder0 readonly divcentertdtr ifresultew available true return trtdcenterlabeleach way betnbspnbspinput typecheckbox ideachwaychk nameeachwaychk labelcentertd tdcenterinput typesubmit namesubmitto openbets valueplace bet centertdtr else return trtd colspan10centerinput typesubmit namesubmitto openbets valueplace bet centertdtr return hidden fields for the horses information return input typehidden namebetslip id value resultbet id return input typehidden namesport value currentpage return input typehidden nameeachway ideachway value return input typehidden nameodds value resultodds return input typehidden nameew odds value resultew odds return input typehidden namesport value resultsport return input typehidden namebettilldate value resultbettilldate return input typehidden namebettilltime value resultbettilltime return area to submit a delete and remove an item from the bet slip return trtd colspan100centerinput typesubmit namedelete betslip item valuedelete this bet onclickreturn confirmare you sure you want to delete this centertdtr return table return form return divbr return div return returngenerated htmldiv styleborder 1pt solid black width 99 borderradius 25pt h2cyprus v wales match bettingh2 form action methodpost table classtable tablecondensed tr td stylewidth 50sport td tdfootballtd tr tr td stylewidth 50participant td tdcyprustd tr tr tdmarket td tdeuro 2016td tr tr tdtime td td1945td tr tr tdodds td td195input typehidden value38 id odds3 td tr tr tdstake td td div classinputgroupspan classinputgroupaddon idbasicaddon1poundspaninput stylewidth 100 typetext namestake idstake3 ariadescribedbybasicaddon1 placeholderstake div td tr tr iddynamic return td colspan10 centerdiv classinputgroupspan classinputgroupaddon idbasicaddon2estimated return poundspaninput stylewidth100 typetext idshowdynamicreturn4 ariadescribedbybasicaddon2 placeholder0 readonly divcenter td tr tr td colspan10 centerinput typesubmit namesubmitto openbets valueplace bet center td tr hidden fields for the horses information input typehidden namebetslip id value13 input typehidden namesport value input typehidden nameeachway ideachway value input typehidden nameodds value195 input typehidden nameew odds value input typehidden namesport valuefootball input typehidden namebettilldate value input typehidden namebettilltime value area to submit a delete and remove an item from the bet slip tr td colspan100 centerinput typesubmit namedelete betslip item valuedelete this bet onclickreturn confirm are you sure you want to delete this center td tr table formdiv,"['javascript', 'php', 'jquery', 'html']" +965671,issue in sorting email values using angularjs custom sort function i have a column in which i am thisplaying email of user i have added sort functionality to it but the resultant array is not sorted properlysample code is hereany help will be appreciatedul ngrepeatuser in users orderbyemailfalsein the example code output of sorting ascending isbut expected output is,['javascript'] +965698,header files without explicitly writing namespace in a c implementation file i have the option to write something likenamespaceclassnamesomefunctionint param implinstead ofnamespace name namespace space classnamesomefunctionint param impl which i find very convenient and more readable can this somehow be used in header files too something like thisclass namespaceclassname declarationsinstead ofnamespace name namespace space class classname declarations if something like this is possible then under which conditions i could imagine that one would need to forward declare the namespace forward declare the classes within the namespace like thisnamespace name namespace space class classname before being able to use thisclass namespaceclassname declarationsin a header filebut somehow i am not able to get this to work 1 is it even possible what bothers me is that with nested namespaces i have to indent 2 tabs until i can actually declare my class i would like to use that space in my header files but i do not want to omit the tabs since this would be against the everything in curly brackets needs to be tabbed oncerule i do not know if there is an actual name for this if there is excuse my ignorance i do not know any s1 the problem i faced was not related to the question the approach actually works but it has drawbacks see accepted answer,['c++'] +965747,can you use css transitions on svg attributes like y2 on a line i want to change the attributes of an svg line and animate the transition to the new coordinatesi am using reactjs to change the value of y2 in this exampleline strokegreen x10 y150 x2100 y225toline strokegreen x10 y150 x2100 y275with css likemystuff transition all 1sis it possible for a css transition to work on the y2 attribute or is there a way to set the attributes of the line in css likemystuff line y2 25which i know does not worki have considered using javascript but that adds complexityi have considered using smil but i would have to store the old and new y2 states and i do not think reactjs allows the animate elementi have considered using a transform on my line element and will go down this path if i cannot find a better solution i want to avoid the math and complexity,['css'] +965847,why baseline of inlineblock element with overflowhidden is set to its bottom margin after reading two great answers explaining the behaviour of inlineblock elements why is this inlineblock element pushed downward and why the spans lineheight is useless i still have two unexplained questions 1 what the reason to change baseline of inlineblock element from baseline of its line box to bottom margin edgethe baseline of an inlineblock is the baseline of its last line box in the normal flow unless it has either no inflow line boxes or if its overflow property has a computed value other than visible in which case the baseline is the bottom margin edge2 how to calculate this shiftimportant i do not try to find a solution how to fix it i try to understand what was the reason to change positioning behaviour of inlineblock element when it is applied overflow hidden so please do not post answers for dummiesupdateunfortunately i did not get what i want although i accepted the answer i think the problem in the questions itself regarding the first question i wanted to understand why inlineblock cannot preserve baseline of its line box even if it has overflowhidden despite of w3c specification of course i wanted to hear the design decisions not just it must be set to something because w3c it mandates the second one i want to get a formula where we can paste fontsize and lineheight of an element and get the correct resultanyway thanks to anybody update 2fortunately and subjectively the answer is found see the first reaccepted answer thank you pallxk,"['html', 'css']" +965901,viewpager fragments are not recreated after fragmenttransactionreplace followed by back button i am trying to implement saving and restoring state but i am running into problems when replacing the main fragment with a preferencefragment and then hitting the back button my main fragment consists of a viewpager with a fragmentpageradapter with 3 fragments to swipe through none of the fragmentoncreateview callbacks for my 3 fragments are invoked after hitting the back button i have tried all the solutions i have come over here on so but i have not been able to resolve the issueanother possibly important thing to note is that the data for my 3 viewpager fragments are stored in separate classes which are instanced and accessible through the activity the 3 fragments all contain recyclerviews for listing a fair amount of data this is done for cleanliness but also so that these data persist in the activity this is probably not an issue since it works fine when starting the app but also since the main issue is that my fragments are not recreatedunexpected behavioron application creation everything works fine but when i replace my main fragment containing a viewpager with a fragmentpageradapter with another one and then pressing the back button the fragments in the viewpager are not recreated the oncreateview of my main fragment is calledquestionswhat am i missing is there some other callbacks that should be created where and how should i recreate the fragmentswhat have i triedchanged the fragmentadapter in use but i should really use getsupportfragmentmanager as was the solution hereedit use of erroneous fragmentmanager actually was the source of my troubles see my answer below addoverride public int getitempositionobject object return position none to the fragmentpageradapter as suggested herechange from fragmentpageradapter to fragmentstatepageradapter which should not matter here as far as i understand the internals of fragmentstatepageradapter actually keeps the fragments but they are not rendered anewadd the main fragment back using a fragmenttransaction when its oncreateview is called and in several of the other callbacks of that fragment see mainfragment belowvarious other thingsmy mainfragment class with corresponding xml layoutpublic class mainfragment extends fragment private mmviewpager mviewpager null nullable override public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate note that this method is called when the back button is pressed i have tried setting the content back to this instance in several places view view inflaterinflaterlayoutmm main fragment container false setup viewpager mviewpager mmviewpager viewfindviewbyidridmm pager tablayout tablayout tablayout viewfindviewbyidridmm tablayout tablayoutsetupwithviewpagermviewpager return view public mmviewpager getmmviewpager return mviewpager mm main fragmentxmlxml version10 encodingutf8linearlayout xmlnsandroid xmlnsapp androidorientationvertical androidlayout widthmatch parent androidlayout heightmatch parent androidsupportdesignwidgettablayout androidididmm tablayout androidlayout widthmatch parent androidlayout heightwrap content apptabmodescrollable commycompanymyappguimmpagermmviewpager androidididmm pager androidlayout widthmatch parent androidlayout heightmatch parent androidlayout weight1 linearlayoutthen in activityoncreate i simply do insert main fragmentfragmentmanager fragmentmanager getsupportfragmentmanagerfragmentmanagerbegintransaction replaceridmm content frame new mainfragment commitwhere mm content frame is a framelayout where i replace and remove fragments then when a button to view the preferences are pushed i run the following snippet below in the activity i add this fragment to the backstack to be able to use the back buttonpublic void showsettingsfragment getsupportactionbarsettitlegetstringrstringmm drawer settings getsupportfragmentmanagerbegintransaction replaceridmm content frame new mmpreferencesfragment fragmentconstantssettings fragment tag addtobackstacknull committhe mmviewpager claspublic class mmviewpager extends viewpager private mmactivity mactivity private mmpageradapter mpageradapter public mmviewpagercontext context attributeset attrs supercontext attrs mactivity mmactivity context mpageradapter new mmpageradaptermactivitygetsupportfragmentmanager mactivity thissetoffscreenpagelimitpagerconstantsoffscreen page limit thissetadaptermpageradapter thissetcurrentitempagerconstantspage filter recipes the mmpageradapter class currently a fragmentstatepageradapterpublic class mmpageradapter extends fragmentstatepageradapter private mmactivity mactivity public mmpageradapterfragmentmanager fragmentmanager mmactivity mmactivity superfragmentmanager mactivity mmactivity override public fragment getitemint position switch position case pagerconstantspage filter recipes return new filteredrecipesfragment case pagerconstantspage selected recipes return new selectedrecipesfragment case pagerconstantspage shopping list return new shoppinglistfragment default return null override public int getcount return pagerconstantsnumber of pages 3 override public charsequence getpagetitleint position switch position case pagerconstantspage filter recipes return mactivitygetresourcesgetstringrstringmm title recipe filter fragment case pagerconstantspage selected recipes return mactivitygetresourcesgetstringrstringmm title selected recipes fragment case pagerconstantspage shopping list return mactivitygetresourcesgetstringrstringmm title shopping list fragment default return tab for reference here is also the main layout of the activityxml version10 encodingutf8androidsupportv4widgetdrawerlayout xmlnsandroid xmlnsapp androidididmm drawer layout androidlayout widthmatch parent androidlayout heightmatch parent source the main content view relativelayout androidlayout widthmatch parent androidlayout heightmatch parent source androidsupportv7widgettoolbar xmlnsandroid androidididmm toolbar androidlayout widthmatch parent androidlayout heightwrap content androidminheightattractionbarsize androidlayout alignparenttoptrue stylestylemmactionbar appthemestylethemeoverlayappcompatdarkactionbar apopupthemestylethemeoverlayappcompatlight the framelayout where i replace fragments framelayout androidididmm content frame androidlayout widthmatch parent androidlayout heightmatch parent androidlayout belowidmm toolbar relativelayout listview androidididmm drawer listview androidlayout width260dp androidlayout heightmatch parent androidpaddingleft16dp androidpaddingright16dp androidpaddingstart16dp androidlayout gravitystart androidchoicemodesinglechoice androiddividerandroidcolortransparent androiddividerheight0dp androidbackgroundcolormm white androidsupportv4widgetdrawerlayout,['android'] +965966,defer compiling from one php script to another what i would like to achievemy phpscript is running on while running i would like to get content also scripts from another website without execution compiling but defer the executionnow i would like to execute the content from on it is a bit like grabbing global script snippets and compile after putting them together on a different serverfilesmainphp phpvar mainphpfile put contentslocal subphp file get contents include local subphpecho varsubphp subphp line 1 notcompiledbrphp var subphp line 2 compiled laterbr subphp line 3 notcompiledbrresult after running mainphpsubphp line 1 notcompiledsubphp line 3 notcompiledmainphpwanted resultsubphp line 1 notcompiledsubphp line 3 notcompiledline 2 compiled latermy own workaroundmy own workaround is to simply switch the extension from subphp to subwhatever and rename it on the flyfilesmainphp the sourcecode is the same but changedfile get contentsphp tofile get contentsdontcompileasphpphpvar mainphpfile put contentslocal subphp file get contentsinclude local subphpecho varsubdontcompileasphp the sourcecode is the same but without php extension it will not be compiled as php as wellsubphp line 1 notcompiledbrphp var subphp line 2 compiled laterbr subphp line 3 notcompiledbrresult after running mainphp matches exactly my needssubphp line 1 notcompiledsubphp line 3 notcompiledline 2 compiled laterwhy am i not satisfied with my workaroundi want to have a clean way to defer the compiling without playing around with extensionsthings i also tried halt compiler ob start any help is very welcome thanx in advance btw it is my very first question,['php'] +966001,cannot get write settings permission when i have a target api of 23 on android m preview 3 i cannot seem to acquire the manifestpermissionwrite setings permission requestpermissionsnew stringmanifestpermissionwrite settings 101request permission does not bring up the dialog i would expect but if i make the following call without this permission ringtonemanagersetactualdefaultringtoneuriactivity ringtonemanagertype ringtone ringurithe call will except because i do not have the permissioni am not sure where to go from here is there a new ringtone api for 23 or did this permission change just make it impossible for any nonsystem apps to change the ringtone,['android'] +966056,d3js transforming nested group images i am working on this1 d3 project basically i am trying to create a sql like query builder i can drop boxes to the drawing area other operators inside the box then i should be able to connect them all i am trying to translate 2 images which are nested in groups i want to move the small items inside the big box i can transform the big box and small operators separately problem happens when i try to move the small operators first i want to move the small operators then big boxes meanwhile i want to keep the relative position of small operators and big box same but when i try to move the large box after moving one of the small box it resets its location here is a demo of my work in jsfiddleg iddraw rect classcontainer height400 width400 x0 y0 stylefillgrayrect g classqbox idqbox line iddummyline x10 x20 y10 y20 visibilityhidden stylestrokered strokewidth4pxline image x10 y10 classcontainer initialx10 initialy10 xlinkhref width110 height110image circle classleft idqboxleft initialcx10 initialcy65 cx10 cy65 r5 stylefillredcircle circle classright idqboxright initialcx120 initialcy65 cx120 cy65 r5 stylefillredcircle g idop1 classop image classopim x10 y10 classcontainer initialx10 initialy10 xlinkhref width50 height50image circle idop1left classleft initialcx10 initialcy35 cx10 cy35 r5 stylefillredcircle circle idop1right classright initialcx60 initialcy35 cx60 cy35 r5 stylefillredcircle g g idop2 classop image classopim x60 y60 initialx60 initialy60 xlinkhref width50 height50image circle idop2left classleft initialcx60 initialcy85 cx60 cy85 r5 stylefillredcircle circle idop2right classright initialcx110 initialcy85 cx110 cy85 r5 stylefillredcircle g g g classqbox idqbox2 line iddummyline x10 x20 y10 y20 visibilityhidden stylestrokered strokewidth4pxline image x110 y110 classcontainer initialx110 initialy110 xlinkhref width110 height110image circle classleft idqboxleft initialcx110 initialcy165 cx110 cy165 r5 stylefillredcircle circle classright idqboxright initialcx220 initialcy265 cx220 cy165 r5 stylefillredcircle g idop3 classop image classopim x110 y110 classcontainer initialx110 initialy110 xlinkhref width50 height50image circle idop1left classleft initialcx110 initialcy135 cx110 cy135 r5 stylefillredcircle circle idop1right classright initialcx160 initialcy135 cx160 cy135 r5 stylefillredcircle g g idop4 classop image classopim x160 y160 initialx160 initialy160 xlinkhref width50 height50image circle idop2left classleft initialcx160 initialcy185 cx160 cy185 r5 stylefillredcircle circle idop2right classright initialcx210 initialcy185 cx210 cy185 r5 stylefillredcircle g gg var qbox d3selectallqbox ondblclick function var g d3selectthis var scale scale1212 gattrtransform gattrtransform scale var opbox d3selectallop var circles d3selectallcircle var cdrag d3behaviordrag ondragstart function d3eventsourceeventstoppropagation ondrag function var dummyline d3selectdummyline var me d3selectthis var transform menodegetctm var t2 meselectfunction return thisparentnode selectfunction return thisparentnode selectcirclenodegetctm var tc d3transformd3selectthisattrtransformtranslate var tp d3transformd3selectthisselectfunction return thisparentnode attrtransformtranslate consolelogtransform var mex t2e var mey t2f dummyline stylevisibility visible attrtx1 numbermeattrcx attrx1 numbermeattrcx numbertransforme numbermex attrty1 numbermeattrcy attry1 numbermeattrcy numbertransformf numbermey attrx2 numberd3eventx attrtx2 numberd3eventx numbertp0 numbertc0 attry2 numberd3eventy attrty2 numberd3eventy numbertp1 numbertc0 attrstart meattrid ondragend function var g d3selectthisselectfunction return thisparentnode selectfunction return thisparentnode var dummyline d3selectdummyline dummylinestylevisibility hidden d3selectqbox appendline attrid function return dummylineattrstart circleid attrx1 dummylineattrx1 attrix1 dummylineattrtx1 attrx2 dummylineattrx2 attrix2 d3select circleidattrcx attry1 dummylineattry1 attriy1 dummylineattrty1 attry2 dummylineattry2 attriy2 d3select circleidattrcy attrstart dummylineattrstart attrend circleid stylestroke green stylestrokewidth 2px var svg d3selectsvgnode var drag d3behaviordrag originfunction var t d3transformd3selectthisattrtransformtranslate return x t0 y t1 ondragstart function d3eventsourceeventstoppropagation ondrag function var g d3selectthis var mouse dx d3eventx dy d3eventy var currentobj x gselectimageattrx y gselectimageattry width gselectimageattrwidth height gselectimageattrheight var parentobj x numbergselectfunction return thisparentnode selectcontainerattrx numberd3transformparentattrtransformtranslate0 y numbergselectfunction return thisparentnode selectcontainerattry numberd3transformparentattrtransformtranslate1 width gselectfunction return thisparentnode selectcontainerattrwidth height gselectfunction return thisparentnode selectcontainerattrheight var loc getxymouse currentobj parentobj d3selectthisattrtransform translate locx locy d3selectthisattrtransform translate d3eventx d3eventy var groupid d3selectthisattrid var groupclass d3selectthisattrclass d3selectaline0foreachfunction e1 var line d3selecte1 consoleloggroupid groupid if lineattrid dummyline groupclass qbox consolelog consoleloglineid lineattrid var linestart lineattrstartsplit0 var lineend lineattrendsplit0 consoleloglinestatr linestart consoleloglineend lineend var t d3transformd3select groupidattrtransformtranslate var t2 d3transformd3select groupidselectfunction return thisparentnode attrtransformtranslate consoleloggroupid groupid if linestart groupid var t d3transformd3select linestartattrtransformtranslate lineattrx1 numberlineattrix1 numbert0 lineattry1 numberlineattriy1 numbert1 lineattrx1 numberlineattrix1 numbert0numbert20 lineattry1 numberlineattriy1 numbert1numbert21 if lineend groupid var t d3transformd3select lineendattrtransformtranslate lineattrx2 numberlineattrix2 numbert0 lineattry2 numberlineattriy2 numbert1 lineattrx2 numberlineattrix2 numbert0 lineattry2 numberlineattriy2 numbert1 lineattrx2 numberlineattrix2 numbert0numbert20 lineattry2 numberlineattriy2 numbert1numbert21 opboxcalldrag qboxcalldrag circlescallcdrag var circleid circlesonmouseover function circleid d3selectthisattrid onmouseout function circleid null ps i connect two elements by dragging the circles and dropping into another circle can anyone point out my mistake,['javascript'] +966169,adaptivetrigger and datatemplate will adaptivetrigger work in a datatemplate that is my code i am using to customize my shellnavigation it is working fine except the visual states they will not trigger anything shellshellheadview xkeyshellheadview 01 shellshellheadviewcontenttemplate datatemplate grid margin200 visualstatemanagervisualstategroups visualstategroup visualstate xnamegreenbackgroundvisualstate visualstatesetters setter targetheadviewleftbackground valuegreen visualstatesetters visualstatestatetriggers adaptivetrigger minwindowwidth10 visualstatestatetriggers visualstate visualstate xnameorangebackgroundvisualstate visualstatesetters setter targetheadviewleftbackground valueorange visualstatesetters visualstatestatetriggers adaptivetrigger minwindowwidth20 visualstatestatetriggers visualstate visualstate xnameredbackgroundvisualstate visualstatesetters setter targetheadviewleftbackground valuered visualstatesetters visualstatestatetriggers adaptivetrigger minwindowwidth30 visualstatestatetriggers visualstate visualstategroup visualstatemanagervisualstategroups gridcolumndefinitions columndefinition widthauto columndefinition gridcolumndefinitions grid gridcolumn0 xnameheadviewleft width100 height90 grid,['c#'] +966238,does sourcemaps in style tags work i am having problems with css within a tag and sourcemapsin order to improve the load time of my project i have changed the way i put the css in my html turning thishtml head link relstylesheet hrefcstylescss head body h1sourcemaps working wonderfullyh1 bodyhtmlinto thishtml head style h1 color red more css sourcemappingurlcstylecssmap style head body h1sourcemaps not working h1 bodyhtmlbasically during the building process the original css file generated with sassc with sourcemaps flag is dumped into the html that will be servedi am having troubles because it does not recognise the sourcemaps when the css is inside a tag but it does it perfectly when i use the tag am i missing an extra annotation or it is not supportedi am using chrome,['css'] +966305,why does not the function get data from php in android i want to get response after post data but it fails i want to create a login system i have successfully submited data to php file everything is working fine now i want to get response from same function but i am unable to know where the issue is here is the java functionpublic class postdatagetres extends asynctaskstring string string protected void onpreexecute superonpreexecute override protected string doinbackgroundstring strings try postrdata catch nullpointerexception e eprintstacktrace catch exception e eprintstacktrace return null override protected void onpostexecutestring lenghtoffile do stuff after posting data public void postrdata string result inputstream isr null final string email editemailgettexttostring final string pass editpassgettexttostring create a new httpclient and post header httpclient httpclient new defaulthttpclient httppost httppost new httppost try add your data listnamevaluepair namevaluepairs new arraylistnamevaluepair2 namevaluepairsaddnew basicnamevaluepairid email namevaluepairsaddnew basicnamevaluepairstringdata pass httppostsetentitynew urlencodedformentitynamevaluepairs execute http post request httpresponse response httpclientexecutehttppost resultviewsettextinserted httpentity entity responsegetentity isr entitygetcontent convert response to string try bufferedreader reader new bufferedreadernew inputstreamreaderisriso885918 stringbuilder sb new stringbuilder string line null while line readerreadline null sbappendline n isrclose resultsbtostring catchexception e logelog tag error converting result etostring parse json data try string s jsonarray jarray new jsonarrayresult forint i0 ijarraylengthi jsonobject json jarraygetjsonobjecti s s name jsongetstringfirst namenn user id jsongetintuser idn name jsongetstringfirst namen email jsongetstringemailnn resultviewsettexts catch exception e todo handle exception logelog tag error parsing data etostring catch clientprotocolexception e todo autogenerated catch block catch ioexception e todo autogenerated catch block resultviewsettextdone and here is php codeifid query mysql queryselect first name from users where email id whilerowmysql fetch assocquery selecteddatarow printjson encodeselecteddata please help me i have tried so far but could not achieve any results please help me how can i get response from php file after query execution,"['java', 'php', 'android']" +966335,mysql group by column with 2 rows for each group i need 2 id for each groupselect id categorycat name from infoleft join category on infocat id categorycat idwhere categorycat name is not nullgroup by categorycat nameorder by categorycat name asc how to do thissample dataid cat name1 cat12 cat13 cat24 cat15 cat26 cat17 cat2output will beid cat name6 cat14 cat17 cat25 cat2,"['mysql', 'sql']" +966415,unexpected cfbundleexecutable key after spending some time googling something tells me that the issue is newwe had a fully functional project supporting ios78 of course it was multiple times successfully submitted to appstore we use pods lots of tracking and monitoring like ga and instabug now we decided to submit a version of the app built on xcode 7 on ios 9 to testflightwe thisabled bitcode since many pods like flurry and other prebuilt libraries does not include itthe build was successful after the submission to itunesconnect we get thiswe had same for googleappindexing library in pods too but we removed it just to make it work now instabug it is going too far so i am trying to understand what is going on in ios 9 and what are the changes that made a fully working project to start throwing such errorsany thoughts and ideas are welcomed please share your experience and if i missed something i will gladly share my steps,['ios'] +966526,google vision barcode library not found i am trying to use the new feature in google play services vision to add qr code scanning to my application but when i run my app i get thisivisioni1 supported abis armeabiv7a armeabidvisioni1 library not found datadatacomgoogleandroidgmsfilescomgoogleandroidgmsvisionbarcodelibsarmeabiv7alibbarhoppersoivisioni1 requesting barcode detector downloadi have declared barcode dependency as per tutorial metadata androidnamecomgoogleandroidgmsvisiondependencies androidvaluebarcode i tried reinstalling the app and restarting the phone nothing helpsusing google play services 78 version installed on the device is 7811compile comgoogleandroidgmsplayservicesvision780code used for creating the barcode detectorboolean initbarcodedetector final barcodetrackerfactory barcodetrackerfactory new barcodetrackerfactorythis final multiprocessorbarcode multiprocessor new multiprocessorbuilderbarcodetrackerfactory build barcodedetector new barcodedetectorbuilderthis build barcodedetectorsetprocessormultiprocessor if barcodedetectorisoperational false toastmaketextthis rstringbarcode not operational toastlength longshow finish return false return truethe above close returns false and finishes activity because barcodedetectorisoperational returns false,['android'] +966724,systemsecuritycryptography vs pclcrypto we are in the process of gutting a lot of shared functionality in our system and porting it to pcl libraries i am having an issue using pclcrypto i am taking some existing data in our database and trying to decrypt it with the same algorithm i get the value back but there are 16 extra bytes at the end that are just garbagesee code belowold algorithm using systemsecuritycryptographypublic static string symmetricencryptthis string plaintext string key symmetricalgorithm algorithm byte keybuffer convertfrombase64stringkeyhashhashalgorithmmd5 byte plaintextbuffer encodingutf8getbytesplaintext var symmetricalgorithm new aescryptoserviceprovider symmetricalgorithmkey keybuffer symmetricalgorithmmode ciphermodeecb var encryptor symmetricalgorithmcreateencryptor byte cipherbuffer encryptortransformfinalblockplaintextbuffer 0 plaintextbufferlength symmetricalgorithmclear return converttobase64stringcipherbuffer public static string symmetricdecryptthis string ciphertext string key symmetricalgorithm algorithm byte keybuffer convertfrombase64stringkeyhashhashalgorithmmd5 byte ciphertextbuffer convertfrombase64stringciphertext var symmetricalgorithm new aescryptoserviceprovider symmetricalgorithmkey keybuffer symmetricalgorithmmode ciphermodeecb var decryptor symmetricalgorithmcreatedecryptor byte plaintextbuffer decryptortransformfinalblockciphertextbuffer 0 ciphertextbufferlength symmetricalgorithmclear return encodingdefaultgetstringplaintextbuffer decryption using pclcryptopublic static string symmetricdecryptthis string ciphertext string key symmetricalgorithm algorithm byte keybuffer convertfrombase64stringkeyhashhashalgorithmmd5 byte ciphertextbuffer convertfrombase64stringciphertext isymmetrickeyalgorithmprovider symmetricalgorithm winrtcryptosymmetrickeyalgorithmprovideropenalgorithmpclcryptosymmetricalgorithmaesecb var symmetrickey symmetricalgorithmcreatesymmetrickeykeybuffer var decryptor winrtcryptocryptographicenginecreatedecryptorsymmetrickey byte plaintextbuffer decryptortransformfinalblockciphertextbuffer 0 ciphertextbufferlength return utf8encodingutf8getstringplaintextbuffer 0 plaintextbufferlengthusing the old version plaintextbuffer is 16 bytes new version it is 32 bytes help,['c#'] +966741,why is initialization of a constant dependent type in a template parameter list thisallowed by the standard in the answer to this post partially specializing a nontype template parameter of dependent type it statesthe type of a template parameter corresponding to a specialized nontype argument shall not be dependent on a parameter of the specialization exampletemplate class t t t struct c template class t struct ct 1 errortemplate int x int array ptrx class a int array5template int x class axarray erroraend example my question is why is this restriction here there is at least one use case where i find that this restriction interferes with writing clean code egtemplate typename t tstruct testtemplate typename tstruct testt nullptr or struct testt tnullptrtemplate typename r typenameargs rfnargsstruct testrargs fnthough i am unsure if there are other cases that stating a constant based on a type is a problem beyond not making any senseanyone have a reason for why this is so,['c++'] +966981,how to specialize classes for all reference types c03 please notice c03 is what i really need but for knoledge sake i would like to see some more pretty implementations in c11 as welli need a template classtemplate typename tclass a private t m memberpublic at member more stuff void foot parami need1 if a is compiled with a value type including pointers which by themselves are passed by valuethen i need a to look like this exactly like aboveclass a private t m memberpublic at member more stuff void foot param2 if a is compiled with a reference type for example intthen i need a to look like thisclass aprivate t m memberpublic at member more stuff void foot paramstill the same t not tif i knew a received only ints then i would be able to use specializationbut any type can be used by as usermaincppaint a11st versionaint a22nd versionab a31st versionab a42nd versionac a51st version,['c++'] +967012,how to escape character in java how to escape character while using split function call in javasplit declarationstring splitstring regularexpressionthats what i didservicessplit says dongling metacharacterservicessplit illegal escape character in string literalbut it allows to do something like thisstring regexpr,['java'] +967021,visual studio 2015 profiler not showing anything from my code i am trying to use profiler from visual studio 2015 community for cpu usage and all i get is just my exe and external code nothing elsethere is a generated pdb file and i tried to clean and rebuild my project thisabled just my code could someone help me thanks,['c++'] +967127,default advice for using cstyle string literals vs constructing unnamed stdstring objects so c 14 introduced a number of userdefined literals to use one of which is the s literal suffix for creating stdstring objects according to the documentation its behavior is exactly the same as constructing an stdstring object like soauto str hello worlds rhs is equivalent to stdstring hello world of course constructing an unnamed stdstring object could be done prior to c 14 but because the c 14 way is so much simpler i think way more people will actually consider constructing stdstring objects on the spot than before that is why i thought it makes sense to ask thisso my question is simple in what cases it is a good or bad idea construct an unnamed stdstring object instead of simply using a cstyle string literalexample 1consider the followingvoid foostdstring argfoobar option 1foobars option 2if i am correct the first method will call the appropriate constructor overload of stdstring to create an object inside foos scope and the second method will construct an unnamed string object first and then moveconstruct foos argument from that although i am sure that compilers are very good at optimizing stuff like this but still the second version seems like it involves an extra move as opposed to the first alternative not like a move is expensive of course but again after compiling this with a reasonable compiler the end results are most likely to be highly optimized and free of redundand movescopies anywayalso what if foo is overloaded to accept rvalue references in that case i think it would make sense to call foobars but i could be wrongexample 2consider the followingstdcout hello world stdendl option 1stdcout hello worlds stdendl option 2in this case the stdstring object is probably passed to couts operator via rvalue reference and the first option passes a pointer probably so both are very cheap operations but the second one has the extra cost of constructing an object first it is probably a safer way to go though in all cases of course constructing an stdstring object could result in a heap allocation which could throw so exception safety should be taken into consideration as well this is more of an issue in the second example though as in the first example an stdstring object will be constructed in both cases anyway in practice getting an exception from constructing a string object is very unlikely but still could be a valid argument in certain casesif you can think of more examples to consider please include them in your answer i am interested in a general advice regarding the usage of unnamed stdstring objects not just these two particular cases i only included these to point out some of my thoughts regarding this topicalso if i got something wrong feel free to correct me as i am not by any means a c expert the behaviors i described are only my guesses on how things work and i did not base them on actual research or experimenting really,['c++'] +967290,why do i get the error your ruby version is 200 but your gemfile specified 2 although i have 2 installed i am using rbenv and i get the error your ruby version is 200 but your gemfile specified 2 when i run the bundle install command in my project the strange thing is that i have actually got the 2 version installed as my gemfile specifies and not the 200 version see image belowi tried the solution offered in this thread your ruby version is 200 but your gemfile specified 210 but it had no effecti am on an macbook air with yosemite if that makes any differenceupdatewhich ruby usersmyuserrbenvshimsrubyruby v ruby 2p95 20150413 revision 50295 x86 64darwin14 rbenv global 2 and rbenv rehash has no effectwhich bundle usrbinbundlegem env gem pathsusersmyuserrbenvversions2librubygems220usersmyusergemruby220,['ruby-on-rails'] +967356,spring exceptionhandler and httpmediatypenotacceptableexception i have a class annotated with controlleradvice and this method in itexceptionhandlerresourcenotfoundexceptionclassresponsestatushttpstatusnot foundresponsebodypublic exceptioninfo resourcenotfoundhandlerresourcenotfoundexception ex listerrorcontent errors new arraylist errorsaddnew errorcontentexceptionscodesnot found code null test return fillexceptioninfohttpstatusnot found errors exhere is fillexceptioninfopublic exceptioninfo fillexceptioninfohttpstatus status listerrorcontent errors exception ex string msg exgetmessage return new exceptioninfostatustostring errors msg null msgequals exgetmessage exceptionutilsgetfullstacktraceexwhen a webclient send a request for some json data which cannot be found this method works ok but when server receives a request to image instead of my exception a httpmediatypenotacceptableexception is thrown i understand that it happens because of wrong content type but how can i fix this problemupdmy goal is to throw resourcenotfoundexception in both cases for json data and for fileexception that i get so it is thrown from abstractmessageconvertermethodprocessorerror oswsmmaexceptionhandlerexceptionresolver doresolvehandlermethodexception failed to invoke exceptionhandler method public comliautilsglobalexceptionhandlerexceptioninfo comliautilsglobalexceptionhandlerresourcenotfoundhandlercomliaappcontrollersexceptionsresourcenotfoundexception orgspringframeworkwebhttpmediatypenotacceptableexception could not find acceptable representation at orgspringframeworkwebservletmvcmethodannotationabstractmessageconvertermethodprocessorwritewithmessageconvertersabstractmessageconvertermethodprocessorjava168 springwebmvc411releasejar411release at orgspringframeworkwebservletmvcmethodannotationabstractmessageconvertermethodprocessorwritewithmessageconvertersabstractmessageconvertermethodprocessorjava101 springwebmvc411releasejar411release at orgspringframeworkwebservletmvcmethodannotationrequestresponsebodymethodprocessorhandlereturnvaluerequestresponsebodymethodprocessorjava198 springwebmvc411releasejar411release at orgspringframeworkwebmethodsupporthandlermethodreturnvaluehandlercompositehandlereturnvaluehandlermethodreturnvaluehandlercompositejava71 springweb411releasejar411release at orgspringframeworkwebservletmvcmethodannotationservletinvocablehandlermethodinvokeandhandleservletinvocablehandlermethodjava122 springwebmvc411releasejar411release at orgspringframeworkwebservletmvcmethodannotationexceptionhandlerexceptionresolverdoresolvehandlermethodexceptionexceptionhandlerexceptionresolverjava362 springwebmvc411releasejar411release at orgspringframeworkwebservlethandlerabstracthandlermethodexceptionresolverdoresolveexceptionabstracthandlermethodexceptionresolverjava60 springwebmvc411releasejar411release at orgspringframeworkwebservlethandlerabstracthandlerexceptionresolverresolveexceptionabstracthandlerexceptionresolverjava138 springwebmvc411releasejar411release at orgspringframeworkwebservletthispatcherservletprocesshandlerexceptionthispatcherservletjava1167 springwebmvc411releasejar411release at orgspringframeworkwebservletthispatcherservletprocessthispatchresultthispatcherservletjava1004 springwebmvc411releasejar411release at orgspringframeworkwebservletthispatcherservletdothispatchthispatcherservletjava955 springwebmvc411releasejar411release at orgspringframeworkwebservletthispatcherservletdoservicethispatcherservletjava877 springwebmvc411releasejar411release at orgspringframeworkwebservletframeworkservletprocessrequestframeworkservletjava966 springwebmvc411releasejar411release at orgspringframeworkwebservletframeworkservletdogetframeworkservletjava857 springwebmvc411releasejar411release at javaxservlethttphttpservletservicehttpservletjava687 javaxservletapi310jar310 at orgspringframeworkwebservletframeworkservletserviceframeworkservletjava842 springwebmvc411releasejar411release at javaxservlethttphttpservletservicehttpservletjava790 javaxservletapi310jar310 at orgeclipsejettyservletservletholderhandleservletholderjava717 jettyservlet911v20140108jar911v20140108 at orgeclipsejettyservletservlethandlercachedchaindofilterservlethandlerjava1644 jettyservlet911v20140108jar911v20140108,['java'] +967573,backbone models change url query params depending on rest action inside a backbone model we have the url and urlroot attributes url function return jobs urlroot function return jobs however i want to add params or query params to the url depending on what type of request it is get post put delete etcso i want to do something like this url functiontype opts type and opts arguments are not available in backbone i just made them up for this example var url jobs switch type case get break case post break case put url url optimisticdelete optsoptimisticdelete break case delete url url upsert optsupsert break default throw new errorno match return url is there a good way to accomplish something like this,['javascript'] +967713,why cannot i select cells in my wpf datagrid i have a wpf datagrid that looks like the followingdatagrid xnamedatagridorderitems margin3690451 verticalalignmentbottom height405 gridrow1 verticalgridlinesbrushlightgray horizontalgridlinesbrushlightgray alternatingrowbackgroundbeige alternationcount2 selectionmodesingle selectionchangeddatagridoutstandingorders selectionchanged autogeneratecolumnsfalse isreadonlytrue gridcolumnspan2 datagridcolumns datagridtextcolumn headerresource name bindingbinding resourcename datagridtextcolumn headerquantity ordered bindingbinding quantity datagridtextcolumn headerorder date bindingbinding orderdate stringformat0d datagridcheckboxcolumn headerthispatched resource bindingbinding ischecked datagridtextcolumn datagridcolumnsdatagrideven though the datagrid is enabled and i have specified a selection mode i cannot click into any of the cells what else am i missingin case it is relevant heres the full xaml for the windowwindow xclassorderprocessormainwindow xmlns xmlnsx xmlnsd xmlnsmc xmlnslocalclrnamespaceorderprocessor mcignorabled titleorder processing height727625 width1088 icon14383970 deliveryico grid margin0020 gridcolumndefinitions columndefinition width9 columndefinition width14 gridcolumndefinitions gridrowdefinitions rowdefinition height94 rowdefinition height315 gridrowdefinitions button xnamebuttonrefreshorders contentloadrefresh orders list margin036100 rendertransformorigin072265 tooltipclick to refresh the orders list with the latest orders from sharepoint gridcolumn1 horizontalalignmentright width140 height36 verticalalignmenttop clickbuttonrefreshorders click datagrid xnamedatagridoutstandingorders margin117156470 rendertransformorigin0505 gridrowspan2 gridcolumnspan2 verticalgridlinesbrushlightgray horizontalgridlinesbrushlightgray alternatingrowbackgroundbeige alternationcount2 selectionmodesingle selectionunitfullrow selectionchangeddatagridoutstandingorders selectionchanged autogeneratecolumnsfalse isreadonlytrue datagridcolumns datagridtextcolumn headerpersona bindingbinding persona datagridtextcolumn headercustomer name bindingbinding customername datagridtextcolumn headerorganization bindingbinding organization datagridtextcolumn headeremail bindingbinding email datagridtextcolumn headerphone bindingbinding phonenumber datagridtextcolumn headerstreet bindingbinding street datagridtextcolumn headersuburb bindingbinding suburb datagridtextcolumn headerpostcode bindingbinding postcode datagridtextcolumn headerorder date bindingbinding orderdate stringformat0d datagridcolumns datagrid button xnamebutton thispatch current item contentset selected resources to be thispatched margin001010 rendertransformorigin072265 tooltip horizontalalignmentright width462 gridrow1 gridcolumn1 height36 verticalalignmentbottom groupbox xnamegroupboxcustomerdetails headercustomer details margin110010 gridrow1 gridcolumn0 verticalalignmentbottom height455 horizontalalignmentleft width353 stackpanel label xnamelabelcustomername content horizontalalignmentleft verticalalignmenttop fontsize16 fontweightbold label xnamelabelcustomerorganization content horizontalalignmentleft verticalalignmenttop fontsize16 label xnamelabelcustomerstreet content horizontalalignmentleft verticalalignmenttop fontsize16 label xnamelabelcustomersuburb content horizontalalignmentleft verticalalignmenttop fontsize16 label xnamelabelcustomerpostcode content horizontalalignmentleft verticalalignmenttop fontsize16 stackpanel groupbox datagrid xnamedatagridorderitems margin3690451 verticalalignmentbottom height405 rendertransformorigin0505 gridrow1 verticalgridlinesbrushlightgray horizontalgridlinesbrushlightgray alternatingrowbackgroundbeige alternationcount2 selectionmodesingle selectionchangeddatagridoutstandingorders selectionchanged autogeneratecolumnsfalse isreadonlytrue gridcolumnspan2 datagridrendertransform transformgroup scaletransform skewtransform angley0146 rotatetransform translatetransform y0497 transformgroup datagridrendertransform datagridcolumns datagridtextcolumn headerresource name bindingbinding resourcename datagridtextcolumn headerquantity ordered bindingbinding quantity datagridtextcolumn headerorder date bindingbinding orderdate stringformat0d datagridcheckboxcolumn headerthispatched resource bindingbinding ischecked datagridtextcolumn datagridcolumns datagrid gridwindow,['c#'] +967885,how do i create intstream from set i currently do thissetinteger integers sourced from elsewhere in codeintstream intstream integersstreammaptointvalue valueit seems redundant to have to map value to value to convert the streaminteger to intstream is there a way to do this without that redundant maptoint section,['java'] +968073,how to watch linq expressions in vs 2015 i am trying to debug a linq expression in visual studio 2015 when i add it to the watch window i get the following error in the value columnfielddomainvalueswhered dactive error cs1061 list does not contain a definition for where and no extension method where accepting a first argument of type list could be found are you missing a using directive or an assembly referencewhen i try to execute in the immediate window i get the same errorerror cs1061 list does not contain a definition for where and no extension method where accepting a first argument of type list could be found are you missing a using directive or an assembly referencei thought that support was added for this in visual studio 2015 based on this article i found this article that outlines some limitations but none apply to my x86 wpf applicationi have an x86 net 45 wpf appin my output window i see that systemcore has been loaded loaded cwindowsmicrosoftnetassemblygac msilsystemcorev40 40 b77a5c561934e089systemcoredllmy method is static and not async i do have the using systemlinq statement at the top of my classusing infragisticswindowseditorsusing microsoftpracticesservicelocationusing systemusing systemcollectionsgenericusing systemlinqusing systemwindowspublic static valueeditor selecteditorcolumnconfig config tableinfo info object value null do some stuff fieldfiltereddomainvalues fielddomainvalueswhered dactivetolist do some other stuff i am not using dynamic typesi have visual studio 2012 and visual studio 2013 also installedi am using resharper anything else i could check in vs options,"['c#', '.net']" +968157,dimple js plot not scaling correctly in firefox i made a few charts with dimple and they look ok in chromium v 43 but in firefox v 40 they are rendered incorrectlyi inspected the page in the debugger and i can see that under the svg tag there is a g tag the inspector shows the g tag in chrome as 720x556 and in firefox as 730x97 which obviously results in a thistorted plotthe same problem occurs on a number of plots bubble line and bar chartsi am using dimple 216 and d3 356here is an example of my codelink functionscope element attrs var svg dimplenewsvgelement0 800 600 svgtextcharttitle var mychart new dimplechartsvg data mychartaddcategoryaxisx column1 mychartaddcategoryaxisy column2 mychartaddcategoryaxisz column3 mychartaddseriescolumn1 dimpleplotbubble mychartdrawdiv ngview classngscope div classcolmd12 ngscope ngcontrollermycontroller trafficplot valp2ptraffic loaddataloaddataip classngisolatescope svg width800 height600 g the rest of the dimple generated code g svg trafficplot divdivany suggestions how to fix thisedit after doing some research i found that the g is a container element used for grouping graphic elements that allows the group elements in this case svg to be handled as one elementin the element inspector the svg appears to have the correct size but the top level gdoes not i suspect that chrome default renders it with 100 height width while firefox renders it depending on the sizes of the elements in it,['javascript'] +968225,androidstudio sdk directory does not exists i am using android studio for a project on svn usually on windows pcslately i want to run this on a mac it keep giving the below errorerrorthe sdk directory usersahmadmusadesktopproject pathdandroidsdk does not exist please fix the sdkdir property in the localproperties filei already put the sdk on localproperties file assdkdirusersahmadmusalibraryandroidsdki do not know why it keep adding the dandroidsdk automatically this is my windows pc sdk directory but why it is here now nothing on code mention any dandroidsdk,['android'] +968377,how to render inkcanvas to an image in uwp windows 10 application the rendertargetbitmap class worked with simple canvas inkmanager in windows 81 to render ink strokes to an imageuwp introduced inkcanvas and a new inking api however it seems like the rendertargetbitmap does not work with that when i try to capture ink strokes with renderasync method no ink strokes get rendered only other objects like rectangle and so onis it a bug or this new api is not meant to be used this way if not then how can i render an image out of inkcanvasthanks,['c#'] +968576,builder design pattern accessingpassing model data toin concrete classes here is my builder interfacepublic interface icontainerbuilder void setsections void setsides void setarea webcontrol getcontainerand this is my concretebuilderpublic class singlecontainerbuilderbaseproperties icontainerbuilder panel panel new panel public void setsections panelheight value coming from model panelwidth value coming from model public void setsides panelsomeproperty value coming from model panelsomeotherproperty value coming from model public void setarea throw new notimplementedexception public systemwebuiwebcontrolswebcontrol getcontainer return panel and the director is herepublic class containerbuilder private readonly icontainerbuilder objbuilder public buildericontainerbuilder conbuilder objbuilder conbuilder public void buildcontainer objbuildersetarea objbuildersetsections objbuildersetsides public webcontrol getcontainer return thisobjbuildergetcontainer and that is how i am calling it from default pagevar conbuilder new containerbuildernew singlecontainerbuilderconbuilderbuildcontainervar container conbuildergetcontainernow the problem confusion i am having is how do i pass the model data to the concrete classes the reason i am confusedstuck is there could be number of different containers could be more than 2030 does each different type of container has to go and grab data from the model or is there a better approach for itthe second thing i am confused with is my model is in a different library do i need to create a copy of the model in my web project and populate my local model from that master model or should i directly query the master model for concrete class properties as you can see my singlecontainer contains baseproperties which are local declaration of the properties that are already in the master model i do not see or understand the point of local model and i am not sure i am right here or notsorry i am new to design patterns any help will be really appreciated thanks,"['c#', 'asp.net']" +968609,how to make orgapachehttplegacy work with proguard azure mobile services the problemi am using android mobile services which relies on androidhttpclientreferencing orgapachehttplegacy resolves all the problems and the app runs just fine however with proguard on i keep running into issuesthe problem plays out in two scenarios if i keep the export checkbox checked in jave build path i get a stub exception as expected see thiscussion belowsee screenshot for which checkbox i am talking aboutthe runtime crash of type stubjavalangruntimeexception unable to start activity componentinfocomstuffdcomstuffdmainactivity javalangruntimeexception stub at androidappactivitythreadperformlaunchactivityactivitythreadjava2345 at androidappactivitythreadhandlelaunchactivityactivitythreadjava2405 at androidappactivitythreadaccess800activitythreadjava149 at androidappactivitythreadhhandlemessageactivitythreadjava1324 at androidoshandlerthispatchmessagehandlerjava102 at androidoslooperlooplooperjava211 at androidappactivitythreadmainactivitythreadjava5317 at javalangreflectmethodinvokemethodjava at javalangreflectmethodinvokemethodjava372 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava1016 at comandroidinternaloszygoteinitmainzygoteinitjava811caused by javalangruntimeexception stub at orgapachehttpmessageabstracthttpmessageabstracthttpmessagejava7 at orgapachehttpclientmethodshttprequestbasehttprequestbasejava7 at orgapachehttpclientmethodshttpgethttpgetjava8 at commicrosoftwindowsazuremobileservicestablemobileservicejsontableexecutegetrecordsmobileservicejsontablejava952 at commicrosoftwindowsazuremobileservicestablemobileservicejsontableexecuteurlquerymobileservicejsontablejava183 at commicrosoftwindowsazuremobileservicestablemobileservicejsontableexecutemobileservicejsontablejava160 at commicrosoftwindowsazuremobileservicestablemobileservicetableexecutemobileservicetablejava158 at commicrosoftwindowsazuremobileservicestablemobileservicetableexecutemobileservicetablejava249 at commicrosoftwindowsazuremobileservicestablequeryexecutablequeryexecuteexecutablequeryjava101if however i keep the checkbox unchecked as suggested see thiscussion below i get and abstractmethoderror exceptionjavalangruntimeexception an error occured while executing doinbackground at androidosasynctask3doneasynctaskjava300 at javautilconcurrentfuturetaskfinishcompletionfuturetaskjava355 at javautilconcurrentfuturetasksetexceptionfuturetaskjava2 at javautilconcurrentfuturetaskrunfuturetaskjava242 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava12 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava587 at javalangthreadrunthreadjava811caused by javalangabstractmethoderror abstract method javalangstring orgapachehttpclientmethodshttprequestbasegetmethod at androidnethttpandroidhttpclientgetmethodandroidhttpclientjava283 at androidnethttpandroidhttpclientexecuteandroidhttpclientjava301proguard config useddontwarn orgapachehttpdontwarn androidnethttpdontwarn commicrosoftwindowsazuremobileserviceshas anyone else run into this and has figured it out,['android'] +968657,what can cause crypt to produce false validations i encountered a problem with a portal i am building and decided to investigate further with a small stress test this test produced 401050 different salts for one specified password the code follows incline 0max 40 auth new authentication falsecounter 0 truecounter 0while incline max passwordstring 1 encrypted pass authhash passwordpasswordstring check cryptpasswordstringencrypted pasalt if check encrypted passpassword truecounter else falsecounter if incline max break inclineecho of max checks falsecounter false returns truecounter true returnswith authhash password being public salt nullpublic function setsalt bytesize mcrypt get iv sizemcrypt cast 256 mcrypt mode cfb salt mcrypt create ivbytesize mcrypt dev random thissalt salt if is nullthissalt return true return falsepublic function hash passwordpassword thissetsalt return array array return arraysalt thissalt return arraypassword cryptpasswordthissalt return return arraynow after showing the code my output is as follows on multiple refreshes of 40 checks 22 false returns 3978 true returnsof 40 checks 15 false returns 3985 true returnsof 40 checks 15 false returns 3985 true returnsof 40 checks 10 false returns 3990 true returnsof 40 checks 6 false returns 3994 true returnsof 10 checks 40 false returns 9960 true returnsof 10 checks 43 false returns 9957 true returnsof 50 checks 196 false returns 49804 true returnsdespite being a minute fail rate the problem is still there regarding password encryption should this not be 100 for all password comparisonsso overall question is what could cause this type of affect could it possibly be my coding or a flaw within the completely flawless php,['php'] +968773,confused about gcm token updation process trying to implement googles latest gcm services i have read gcm documentation i have also downloaded analysed googles sample implementation from all the above i understood the followinginstanceid services provide apis to generate gcm registration tokens you send store this generated token in your app serverthese tokens can be changed once in a while from client side as well as instanceid service side as mentioned here to handle this you have to implement instanceidlistenerservice and the instanceid provider will call ontokenrefresh where you just write your logic to get a new token and sending it to server googles sample app there is something called canonical id as mentioned here which is the last registration id send from a device that gcm server sends your device if your app server sends an older registration id you have to replace your existing token in server with this canonical idnow following are my questionsinstanceidgettoken seems to return same token if the app is not uninstalled and it returns pretty fast if the token has not changed so can i call the registrationintentservice every time i start the app this way i am guaranteed to get to work with the latest token all the timehow does the ontokenrefresh if refresh happens while your app is not connected to the play store no internet or something does instanceid provider retry is this documented somewhere what happens if at the same time a push notification is sent what exactly is a canonical id is it the latest token generated for a device initiated by instanceidgettoken at client or at instanceid provider end if canonical id is indeed the latest gcm token what is the need of ontokenrefresh implementation as you can anyway analyse the push notification data and update your app server if you find a canonical id provided,['android'] +968833,imgsrc was not explicitly set so defaultsrc is used as a fallback here is my contentsecuritypolicy in indexhtmlmeta httpequivcontentsecuritypolicy contentdefaultsrc self now i am dynamically setting img src of img idupdateprofilepicpreview classprofilpicpreview src as var smallimage documentgetelementbyidupdateprofilepicpreview smallimagestylethisplay block smallimagesrc dataimagejpegbase64 imagedatait showsrefused to load the image dataimagejpegbase649j4aaqskzjrgabaqaqabaad2wbdacgchimegsgjismtkygwaptbyakkaii2tsfjrrvcjfoyik96re5nffdggoqbhrqa9elidg5oopgiclfah2q because it violates the following content security policy directive defaultsrc self note that imgsrc was not explicitly set so defaultsrc is used as a fallbackso how can i enable setting img src dynamically i was following this example from cordova pagevar picturesource picture sourcevar destinationtype sets the format of returned value wait for device api libraries to loaddocumentaddeventlistenerdevicereadyondevicereadyfalse device apis are availablefunction ondeviceready picturesourcenavigatorcamerapicturesourcetype destinationtypenavigatorcameradestinationtype called when a photo is successfully retrievedfunction onphotodatasuccessimagedata uncomment to view the base64encoded image data consolelogimagedata get image handle var smallimage documentgetelementbyidsmallimage unhide image elements smallimagestylethisplay block show the captured photo the inline css rules are used to resize the image smallimagesrc dataimagejpegbase64 imagedata called when a photo is successfully retrievedfunction onphotourisuccessimageuri uncomment to view the image file uri consolelogimageuri get image handle var largeimage documentgetelementbyidlargeimage unhide image elements largeimagestylethisplay block show the captured photo the inline css rules are used to resize the image largeimagesrc imageuri a button will call this functionfunction capturephoto take picture using device camera and retrieve image as base64encoded string navigatorcameragetpictureonphotodatasuccess onfail quality 50 destinationtype destinationtypedata url a button will call this functionfunction capturephotoedit take picture using device camera allow edit and retrieve image as base64encoded string navigatorcameragetpictureonphotodatasuccess onfail quality 20 allowedit true destinationtype destinationtypedata url a button will call this functionfunction getphotosource retrieve image file location from specified source navigatorcameragetpictureonphotourisuccess onfail quality 50 destinationtype destinationtypefile uri sourcetype source called if something bad happensfunction onfailmessage alertfailed because message,"['javascript', 'html']" +968844,promise join add new function call to the chain i am trying to load and parse a file but am having some trouble calling two functions and returning the result for the promise i am using bluebird promises the following code works as expectedrun function filepath return promisejoin fsreadfileasyncfilepath utf8 thenparsefileparsebindnull userkey usersgetusersasyncusersobj thenusersmodifyrecbindnull processenvusers thenfunction args return runprocrun args0 args1i have divided the parsefileparse function into two methods parsefileparse and parsefilegetprop parsefilegetprop should take the output from parsefileparse and return what parsefileparse returned before the method was split up here is my attempt to use both functionsrun function filepath return promisejoin fsreadfileasyncfilepath utf8 thenparsefileparsebindnull userkey thenparsefilegetpropbindnullkey usersgetusersasyncusersobj thenusersmodifyrecbindnull processenvusers thenfunction args return runprocrun args0 args1but it is not working what am i doing wrong hereupdatevar ymlparser requireyamljsvar ymlobjparse function data use strict if ymlobj ymlobj ymlparserparsedata return ymlobjgetprocweb function return ymlobjpropwebmoduleexports parse parse getprop getprop,['javascript'] +968864,wait for task to complete without blocking ui thread i have a fairly complex wpf application that much like vs2013 has idocuments and itools docked within the main shell of the application one of these tools needs to be shutdown safely when the main window is closed to avoid getting into a bad state so i use caliburn micros public override void cancloseactionbool callback method to perform some database updates etc the problem i have is all of the update code in this method uses mongodb driver 20 and this stuff is async some code currently i am attempting to perform public override void cancloseactionbool callback if backtestcollectionanybt btteststatus teststatusrunning using manualreseteventslim taredowncompleted new manualreseteventslimfalse update running test taskrunasync statusmessage stopping running backtest await savebacktesteventsasyncselectedbacktest logtracestringformat shutdown requested saved backtest 0 with events selectedbacktestname thissource new cancellationtokensource thistoken thissourcetoken var filter buildersbsondocumentfiltereq backtestfieldsid docidserializerwriteselectedbacktestid var update buildersbsondocumentupdatesetbacktestfieldsstatus teststatuscancelled imongodatabase database clientgetdatabaseconstantsdatabasemappingsdatabasebacktests await mongodataserviceupdateasyncbsondocument database constantsbacktests filter update token logtracestringformat shutdown requested updated backtest 0 status to cancelled selectedbacktestname continuewithant statusmessage thisposing backtest engine if engine null enginethispose logtraceshutdown requested thisposed backtest engine successfully callbacktrue taredowncompletedset taredowncompletedwait now to start with i did not have the manualreseteventslim and this would obviously return to the canclose caller before i updated my database on the background threadpool thread in an attempt to prevent the return until i have finished my updates i tried to block the return but this freezes the ui thread and prevents anything from happening how can i get my cleanup code to run without returning to the caller too earlythank for your timenote i cannot override the onclose method using async signature as the calling code would not await it i have no control over this,['c#'] +968869,visual studio 2015 diagnostics tool does not support current debugging configuration after using vs2015 snapshot and profiling tools i cannot seem to get the diagnostics tools to work again every project even new ones just say the following the diagnostic tools window does not support the current debugging configurationtried creating new and different type projects running as administrator deleting program data app data repairing and reinstalling from uninstallanyone experienced this shame as they have improved this tool a lot in this versionthanks,['c#'] +969021,uitableview auto resizing row constraint breaking mysteriously on iphone 6plus i have a custom uitableviewcell which has a thumbnail and bunch of text the row height is configured to be calculated automatically using tableviewestimatedrowheight 129tableviewrowheight uitableviewautomaticdimensionthe row height should be calculated as exactly 138 points everything looks great on the iphone 5 however on iphone 6 plus the auto row height fails intermittently for random rows with the following log nslayoutconstraint0x17009d0 v20scoopthumbnailimage0x124d2a5a0 names uitableviewcellcontentview0x124e23200 nslayoutconstraint0x17009de70 uitableviewcellcontentview0x124e23200bottommargin scoopthumbnailimage0x124d2a5a0bottom 20 nslayoutconstraint0x17009e780 vscoopthumbnailimage0x124d2a5a090 nslayoutconstraint0x17009ef00 uiviewencapsulatedlayoutheight vuitableviewcellcontentview0x124e232001383the last line of the log seems to say that for some reason the row height was calculated as 1383 instead of 138 i have been banging my head for a while now but i am unable to figure out why this is happening can some one please helpupdate this is how my table view cell looks likeupdate i could not get the code out of the main repo since its a part of a bigger project but i have managed to reproduce the issue with a very simple sane project please find it here on github,['ios'] +969140,english us language code changed google speech api v2 not returning the correct result just noticed the english us words no longer thisplay the correct spelling this previously was ok now it thisplays the english uk spelling below is a list of some words that i found for example if i say center and set the language code as enus i am getting the result as centre which is english uki am using google api v2 langenuskeymy keywords ending in arebritish english words that end in re often end in er in american englishbritish and us centre center fibre fiber litre liter theatre theater or theatre even though i am giving the language code as enus the result returned will be in british englishis this a common issue or us english code is no longer working any help will be appreciatedediti just noticed this issue is with ok google also even though my input is in english us the answers i am getting is in english ukthese are some other wordswords ending in ourbritish english words ending in our usually end in or in american englishbritish and uscolour colorflavour flavorhumour humorlabour laborneighbour neighborverbs in british english that can be spelled with either ize or ise at the end are always spelled with ize at the end in american englishbritish and usapologize or apologise apologizeorganize or organise organizerecognize or recognise recognizewords ending in yseverbs in british english that end in yse are always spelled yze in american englishbritish and usanalyse analyzebreathalyse breathalyzeparalyse paralyze,['android'] +969148,android m user permission error read and write i just started off with android m and i am unable to access the external storage i get the following errorcaused by javalangsecurityexception permission denial reading comandroidprovidersmediamediaprovider uri contentmediaexternalimagesmedia from pid15355 uid10053 requires androidpermissionread external storage or granturipermission i am adding userpermission in manifest like usespermission androidnameandroidpermissionwrite external storage and my build file is with following settings compilesdkversion 23buildtoolsversion 2201minsdkversion 16targetsdkversion 23how to read and write from external storage in android m,['android'] +969163,indexoutofboundsexception after repopulating arraylist marshmallow only my setup is as follows inside my oncreate i initialize an arraylist as follows textlist new arraylisthashmapstring string unrelated code if isconnected new thisplaytexttaskexecutesectionidand the asynctask fetches text via httpurlconnection parses the json using jsonreader and adds each line of text to the textlist all of this happens inside the asynctasks doinbackground i have a custom adapter that thisplays the strings in textlisti also have a function gotonextsection that gets triggered when the user wants to navigate to the next page where i do something likegotonextsection if isconnected new thisplaytexttaskexecutesectionid1 however since i do not want the stale text from the previous page to remain on screen i do the following in my asynctaskprivate class thisplaytexttask extends asynctaskstring void string override protected void onpreexecute superonpreexecute textlistclear override protected string doinbackgroundstring urls json parsing is called in getdata try return getdataurls0 catch ioexception e return could not load text so that the arraylist is empty and ready to be repopulated all of this works fine in all other supported android versions but when i tried it in a marshmallow emulator gotonextsection results in an indexoutofboundsexception this occurs after the new content is added to the freshly cleared arraylist verified via logging so i do not think it is a race condition note that not clearing the list prevents the exception and since this is the only arraylist used in the activity i am positive that clear is the problem i have tried nulling and reinitializing it before launching the asynctask as an alternative as well to no avail again this happens exclusively on android 60 thoughtseditheres the logcat stacktrace note that the size of index that it is attempting to access and where in the code this occurs is irrelevant because i have tried to log the arraylist after the task is executed in gotonextsection and it just gives me an exception for whatever index i have tried to access in the logjavalangindexoutofboundsexception invalid index 0 size is 0 at javautilarraylistthrowindexoutofboundsexceptionarraylistjava255 at javautilarraylistgetarraylistjava308 at androidwidgetheaderviewlistadapterisenabledheaderviewlistadapterjava164 at androidwidgetlistviewthispatchdrawlistviewjava3329 at androidviewviewdrawviewjava16181 at androidwidgetabslistviewdrawabslistviewjava4142 at androidviewviewupdatethisplaylistifdirtyviewjava15174 at androidviewviewgrouprecreatechildthisplaylistviewgroupjava3593 at androidviewviewgroupthispatchgetthisplaylistviewgroupjava3573 at androidviewviewupdatethisplaylistifdirtyviewjava15134 at androidviewviewgrouprecreatechildthisplaylistviewgroupjava3593 at androidviewviewgroupthispatchgetthisplaylistviewgroupjava3573 at androidviewviewupdatethisplaylistifdirtyviewjava15134 at androidviewviewgrouprecreatechildthisplaylistviewgroupjava3593 at androidviewviewgroupthispatchgetthisplaylistviewgroupjava3573 at androidviewviewupdatethisplaylistifdirtyviewjava15134 at androidviewviewgrouprecreatechildthisplaylistviewgroupjava3593 at androidviewviewgroupthispatchgetthisplaylistviewgroupjava3573 at androidviewviewupdatethisplaylistifdirtyviewjava15134 at androidviewviewgrouprecreatechildthisplaylistviewgroupjava3593 at androidviewviewgroupthispatchgetthisplaylistviewgroupjava3573 at androidviewviewupdatethisplaylistifdirtyviewjava15134 at androidviewviewgrouprecreatechildthisplaylistviewgroupjava3593 at androidviewviewgroupthispatchgetthisplaylistviewgroupjava3573 at androidviewviewupdatethisplaylistifdirtyviewjava15134 at androidviewthreadedrendererupdateviewtreethisplaylistthreadedrendererjava281 at androidviewthreadedrendererupdaterootthisplaylistthreadedrendererjava287 at androidviewthreadedrendererdrawthreadedrendererjava322 at androidviewviewrootimpldrawviewrootimpljava2615 at androidviewviewrootimplperformdrawviewrootimpljava2434 at androidviewviewrootimplperformtraversalsviewrootimpljava2067 at androidviewviewrootimpldotraversalviewrootimpljava1107 at androidviewviewrootimpltraversalrunnablerunviewrootimpljava6013 at androidviewchoreographercallbackrecordrunchoreographerjava858 at androidviewchoreographerdocallbackschoreographerjava670 at androidviewchoreographerdoframechoreographerjava606 at androidviewchoreographerframethisplayeventreceiverrunchoreographerjava844 at androidoshandlerhandlecallbackhandlerjava739 at androidoshandlerthispatchmessagehandlerjava95 at androidoslooperlooplooperjava148 at androidappactivitythreadmainactivitythreadjava5417 at javalangreflectmethodinvokenative method at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava726 at comandroidinternaloszygoteinitmainzygoteinitjava616,"['java', 'android']" +969185,cakephp 3 redirect in beforefilter of parent class in our cakephp 3 application we found a different behaviour were sure that it worked well in cakephp 2 so i suppose something changed in new versionwhen user visits this url b2controllermymethod these methods run appcontrollerbeforefilter bcontrollerbeforefilter b2controllerbeforefilter b2controllermymethod b2controllermymethod2 then user is redirected to this url ccontrollermymethod10 but we need this when user visits b2controllermymethod and isok condition is true then redirect user to ccontrollermymethod10 without running bcontrollerbeforefilter b2controllerbeforefilter b2controllermymethod and bcontrollermymethod2our minimal code is like thisclass appcontroller function beforefilterevent event set isok variable if isok true return thisredirectccontrollermymethod10 aa1 ab2 class bcontroller extends appcontroller function beforefilterevent event parentbeforefilterevent a1 b2 function myothermethod myothermethod2 function myothermethod2 class b2controller extends bcontroller function beforefilterevent event parentbeforefilterevent m11 m22 function mymethod mymethod2 function mymethod2 class ccontroller extends appcontroller function beforefilterevent event parentbeforefilterevent function mymethod10 how can i make user to redirect to another controller action from the beforefilter of main class note that redirect occurs but user is redirected after calling mymethod and mymethod2also note that there is other controllers like ccontroller that uses beforefilter redirect behaviour,['php'] +969369,getting javalangreflectinvocationtargetexception when trying to register broadcast receiver of embedded apk my app has an embedded apk i need to register a broadcastreceiver in the inner apk from my main apkthe inner apk is not to be installed on the system i must load it dynamically so i am using reflection to call a method in the inner apk which has code to register the broadcastreceiver this receiver of inner apk should invoke for related broadcast i am getting an error while trying to register the broadcastreceiver is it even possible for a broadcastreceiver to be registered in this way and be fully functional exception and code are given belowerror related log0824 083126915 dmainapp1957 invoke method0824 083126955 dinnerapp1957 register receiver0824 083126955 wsystemerr1957 javalangreflectinvocationtargetexception0824 083126965 wsystemerr1957 at javalangreflectmethodinvokenativenative method0824 083126965 wsystemerr1957 at javalangreflectmethodinvokemethodjava5150824 083126965 wsystemerr1957 at comexampleea mainappmainappinvokeservicemainappjava1050824 083126965 wsystemerr1957 at comexampleea mainappmainapponcreatemainappjava400824 083126965 wsystemerr1957 at androidappactivityperformcreateactivityjava52310824 083126975 wsystemerr1957 at androidappinstrumentationcallactivityoncreateinstrumentationjava10870824 083126975 wsystemerr1957 at androidappactivitythreadperformlaunchactivityactivitythreadjava21590824 083126975 wsystemerr1957 at androidappactivitythreadhandlelaunchactivityactivitythreadjava22450824 083126975 wsystemerr1957 at androidappactivitythreadaccess800activitythreadjava1350824 083126975 wsystemerr1957 at androidappactivitythreadhhandlemessageactivitythreadjava11960824 083126975 wsystemerr1957 at androidoshandlerthispatchmessagehandlerjava1020824 083126975 wsystemerr1957 at androidoslooperlooplooperjava1360824 083126975 wsystemerr1957 at androidappactivitythreadmainactivitythreadjava50170824 083126975 wsystemerr1957 at javalangreflectmethodinvokenativenative method0824 083126975 wsystemerr1957 at javalangreflectmethodinvokemethodjava5150824 083126975 wsystemerr1957 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava7790824 083126975 wsystemerr1957 at comandroidinternaloszygoteinitmainzygoteinitjava5950824 083126975 wsystemerr1957 at dalviksystemnativestartmainnative method0824 083126985 wsystemerr1957 caused by javalangnullpointerexception0824 083126985 wsystemerr1957 at androidcontentcontextwrapperregisterreceivercontextwrapperjava4670824 083126985 wsystemerr1957 at comexampleea innerappinnerappregisterinnerappjava500824 083126985 wsystemerr1957 18 morerelated code from main app invoke methodlogdtaginvoke methodfinal string apkfile target base pathea innerappapkstring classname comexampleea innerappinnerappstring methodtoinvoke register final file optimizeddexoutputpath getdiroutdex 0dexclassloader dloader new dexclassloaderapkfileoptimizeddexoutputpathgetabsolutepath nullclassloadergetsystemclassloadergetparenttry class loadedclass dloaderloadclassclassname object obj objectloadedclassnewinstance suppresswarningsrawtypes class noparams method m loadedclassgetmethodmethodtoinvoke noparams object onoparams minvokeobj onoparams catch classnotfoundexception e catch invocationtargetexception e todo autogenerated catch block eprintstacktracecode of invoked method comexampleea innerappinnerappregisterlogdtag register receiverintentfilter filternew intentfilter filteraddactioncomexampleea mainappiregisterreceiverobj innerreceiverfilter,"['java', 'android']" +969438,post byte array to web api server using httpclient i want to post this data to web api serverpublic sealed class somepostrequest public int id get set public byte content get set using this code for serverrouteincomingvalidatemodelpublic async taskihttpactionresult postincomingdatasomepostrequest requestdata post logic hereand this for clientvar client new httpclientclientbaseaddress new urihttplocalhost25001clientdefaultrequestheadersacceptclearclientdefaultrequestheadersacceptadd new mediatypewithqualityheadervalueapplicationjsonvar content new formurlencodedcontentnew dictionarystring string id 1 content 123 var result await clientpostasyncapisomedataincoming contentresultensuresuccestatuscodeeverything works fine at least debugger stops at breakpoint in postincomingdata since there is a byte array i do not want to serialize it as json and want to post it as binary data to decrease network traffic something like applicationoctetstreamhow this can be achieved i have tried to play with multipartformdatacontent but looks like i just cannot understand how multipartformdatacontent will match signature of controllers methodeg replacing content to thisvar content new multipartformdatacontentcontentaddnew formurlencodedcontentnew dictionarystring string id 1 var binarycontent new bytearraycontentnew byte 1 2 3 binarycontentheaderscontenttype new mediatypeheadervalueapplicationoctetstreamcontentaddbinarycontent contentvar result await clientpostasyncapisomedataincoming contentresultensuresuccestatuscodeleads to error 415 unsupported media type,['c#'] +969442,making python run a few lines before my script i need to run a script foopy but i need to also insert some debugging lines to run before the code in foopy currently i just put those lines in foopy and i am careful not to commit that to git but i do not like this solutionwhat i want is a separate file barpy that i do not commit to git then i want to runpython somewherebarpy somewhere elsefoopywhat i want this to do is first run some lines of code in barpy and then run foopy as main it should be in the same process that the barpy lines ran in otherwise the debugging lines would not helpis there a way to make barpy do this someone suggested this import impimport sys debugging code herefp pathname description impfind modulesysargv1impload module main fp pathname descriptionthe problem with that is that because it uses import machinery i need to be on the same folder as foopy to run that i do not want that i want to simply put in the full path to foopyalso the solution needs to work with pyc files as well,['python'] +969522,alpha sort plugin how to add shuffle animation i have implemented a jquery plugin to identify and sort a collection of child elements wrapped in a parent the plugin also has a grouping capabilityi am sort of lost on how to add in animations to the dom change i was able to add in a basic show animation that brings in the elements but i want to create a sweet shuffle visual effectfunction fnalphasort function options defaults changing the keys will kill someone close to you so do not do it var settings extend child div collection of child elements within the parent target span the target element within a single child order asc the sort order existing options asc desc group truegroup alphabetically or not titlecss rowthe css class styling the header group options var data dataname developer must set the values being compared to a data attribute dataname var parent this var children thisfindsettingschild var container letters read the dom each childs target element has a data attribute dataname read the data attribute and prepare a list of first letters a key value pair is inserted into the container key will be the first letter the value will be a sublist containing child elements the child elements represent institutes which starts with the letter denoted by the key childreneachfunction var elem thisfindsettingstarget var name elemattrdata var l namesubstring01touppercase if l in container containerl containerletterspushl containerlpushthis sort the list of first letters stored containerletterssort ifsettingsorder asc containerlettersreverse clear the parent element get ready for dom manipulation parentempty iterate through the firt letter list sort each sublist each sublist is identified by a first letter key eachcontainerletters functioniletter var list containerletter listsortfunctionab var aelem afindsettingstarget var aname aelemattrdata var belem bfindsettingstarget var bname belemattrdata returns 1 str1 is sorted before str2 1 str1 is sorted after str2 0 two strings are equal return anametouppercaselocalecomparebnametouppercase if the init script set group to true then group else skip ifsettingsgroup parentappenddiv class containerfluiddiv clasettingstitlecssh3 class institutegrouph3letterh3divdiv append to dom foreach in list parentappendlisteach jquery,['jquery'] +969562,from matplotlibbackends import tkagg importerror cannot import name tkagg while trying to run this example to test how matplotlib works with tkinter i am getting the errorenvfieldsofgoldfieldsofgoldvirtualboxnew python testpytraceback most recent call last file testpy line 7 in module from matplotlibbackendsbackend tkagg import figurecanvastkagg navigationtoolbar2tkagg file homefieldsofgoldnewenvlocallibpython27sitepackagesmatplotlibbackendsbackend tkaggpy line 13 in module import matplotlibbackendstkagg as tkagg file homefieldsofgoldnewenvlocallibpython27sitepackagesmatplotlibbackendstkaggpy line 7 in module from matplotlibbackends import tkaggimporterror cannot import name tkaggusing the solution provided here i have tried to uninstall matplotlib and install the tk and tkdev packages by using these commands sudo aptget install tk85sudo aptget install tkdevand then reinstalling matplotlib again by pip install matplotlibbut i am still getting the same error any help would be appreciated i am using ubuntu 1404 on virtualbox and working inside a virtualenv environmentthanks so much,['python'] +969703,serve imagesassests using slim framework i need to serve images which are common in multiple modules to the resources folder us outside of public folder i am using slim framework app classes vendor resources images admin styles scripts indexphp initphp public styles scripts indexphp initphpcurrently i have created a subdomain staticpro1local to serve local images but now i am in search for some other wayon slim i am trying to make a route to dynamically create and serve images as requiredappgetassetsheightwidthidtype function use app headercontenttype imagejpeg dir dirname dir resourcesimages image new imagickdiridsvg code to create images based on height width and change its format svg to png as required appresponseheadercontenttype contenttype imagetype echo image resbodyimagei intent to use it as img srcassets200400testpng but i keep getting 404 error i already triedphp how to use a rest controller to serve imagesand few other i also found but i need to use svg conversions and few other stuffs which it does not have,['php'] +969737,events other than place changed for google maps autocomplete i have an app that currently fires correctly on place changedhowever i want to branch search to behave differently when a user has selected an autocomplete entry and when they have entered text on their own without the assistance of autocompletewhat kind of event listener should i use to make the thistinction i cannot find any documentation on other events for google maps autocompletewhat i have nowvar gmaps new googlemapsplacesautocompletesearchpropertiesget0 types geocode componentrestrictions country us googlemapseventaddlistenergmaps place changed function fire search,"['javascript', 'jquery']" +969821,angularjs dependencyinjection i have say two modules fooafooband an application module angularmodulefoo fooafoobi have a service in module foob say angularmodulefoob angularmodulefoobfactoryhelperhelperfnwhich i want to use in one of my controllers in fooawhat i have done is simple dependency injection angularmodulefooa angularmodulefooa controllermycontrollerhelpermycontrollerfnwhich is workingmy questions are how am i getting the helper service from module foob even though it is not declared as a dependency for module awill it break at a later stageif it is correct is this a good practice,['javascript'] +969879,how does the web version of whatsapp work on ios devices considering the os shuts apps in 30 seconds now for those who do not know can go to and sync your whatsapp chats by exchanging a qr code and chat via the web extension of the appi am not interested in how they have an initial handshake might be communicating with whatsapp servers nor how they sync data so fast for chatting might be using open sockets directly from device to clienti am curious as to how the app works in background on ios afaik running a background intent service is pretty simple but not for ios ios allows only up to 30 seconds after the app is shut down normally 1 i tried crashing the appswipe up still the web version was running normally2 i thisabled background app refresh the web version did not stop3 even thisable notifications still the web version worked normally4 as well they do not have a blue bar the likes when google maps is giving you directions that indicates the app is running in bg5 are they using dummy geo fencing to keep them alive but that d require bg app refresh toois it some new feature on ios 8 that was introduced and i am not aware of,"['ios', 'objective-c']" +969937,best practices for global resources in c when we want to make our application for all usersspeak different languageswe need a global technologyin c we use resourcemanager as followusing systemusing systemreflectionusing systemresourcespublic class example public static void main retrieve the resource resourcemanager rm new resourcemanagerexampleresources typeofexampleassembly string greeting rmgetstringgreeting consolewriteenter your name string name consolereadline consolewriteline0 1 greeting name the example produces output similar to the following enter your name john hello johnthe assembly have two or more language resourcesassembly assemblyenusresx assemblyzhcnresx then we archive to change the resource by changing thread cultureinfo to use different resourceif the application have a lot of dllassembly filesi want to have a single pointone resource file for one language for the applicationis there a good solution for my ideabefore i just change the viewegwinform or usercontrols language to implement different ui for corresponding language,['c#'] +970213,using the twitter streaming api i need to notify my app of new tweets in real time from a selected few users afaik to do this i need to use the twitter streaming api i have come across twitter4j but i am not quite sure how to use this with the streaming api does anyone know of any concrete up to date examples on using thisalso i came across this exerpt in the streaming api documentation hereeach account may create only one standing connection to the public endpoints and connecting to a public stream more than once with the same account credentials will cause the oldest connection to be thisconnected clients which make excessive connection attempts both successful and unsuccessful run the risk of having their ip automatically bannedthe app will need to update for all users when a new tweet is received would that break this rule do i need to create a backend instead to receive the stream and then push the new tweets down from there,['android'] +970216,c sqrt guaranteed precision upperlower bound i have to check an inequality containing square roots to avoid incorrect results due to floating point inaccuracy and rounding i use stdnextafter to get an upperlower boundinclude cfloat dbl maxinclude cmath stdnextafter stdsqrtdouble x 420 just an example numberdouble y stdnextafterstdsqrtx dbl maxa is yy x guaranteed using gcc compilerb will this work for other operations like or even stdcos and stdacosc are there better ways to get upperlower boundsupdatei read this is not guaranteed by the c standard but should work according to ie754 will this work with the gcc compiler,['c++'] +970217,android build with retrolambda ignores source code changes in our project we use gradle retrolambda proguardretrolambda incremental build is set to falsesometimes build passes without error but source code changes does not apply in appto solve this problem we clean and rebuild project withgradlew clean assembledebugbut in our case it takes about 230 m that is too longhow we can solve this issue,['android'] +970226,query c list to limit children but return parents i have a nested list structure with customers orders orderitems i am trying to find a linq or other query that will return the customers and their nested items where the orderitem quantity 1 however it should not return any orders or orderitems where the quantity 1i have tried thisvar customers2 customerswherec cordersanyo oorderitemsexistsoi oiquantity 1it correctly returns only customers with order items quantity 1 but it also returns all other orders and order items as welli can get the desired results with a couple of foreach loops but i would like to find something more elegant foreach var customer in customers2 customerorders customerorderswhereo oorderitemsexistsoi oiquantity 1tolist foreach var order in customerorders orderorderitems orderorderitemswhereoi oiquantity 1tolist here is the object structure and some sample datapublic class customer public int customerid get set public string name get set public string address get set public listorder orders get set public class order public int orderid get set public int customerid get set public datetime orderdate get set public bool shipped get set public listorderitem orderitems get set public class orderitem public int orderitemid get set public int orderid get set public string itemname get set public int quantity get set var customers new listcustomer new customer customerid 1 name shawn address 123 main street orders new listorder new order orderid 100 customerid 1 orderdate datetimenow shipped true orderitems new listorderitem new orderitem orderitemid 200 orderid 100 itemname computer quantity 1 new orderitem orderitemid 206 orderid 100 itemname hard drive quantity 2 new order orderid 106 customerid 1 orderdate datetimenow shipped true orderitems new listorderitem new orderitem orderitemid 207 orderid 106 itemname monitor quantity 3 new orderitem orderitemid 208 orderid 106 itemname dvd burner quantity 2 new customer customerid 2 name arianna address 456 main street orders new listorder new order orderid 101 customerid 2 orderdate datetimenowadays10 shipped true orderitems new listorderitem new orderitem orderitemid 201 orderid 101 itemname barbie quantity 2 new customer customerid 3 name ryan address 789 main street orders new listorder new order orderid 102 customerid 3 orderdate datetimenowadays5 shipped true orderitems new listorderitem new orderitem orderitemid 203 orderid 103 itemname minecraft quantity 2,['c#'] +970497,ibdesignable never finishes updating uitableviewcell in storyboard this is a similar question to this but not quite the samei have created a subclass of uitableviewcell which references a custom nib and marked it as ibdesignable changes that are made both in code and from the xib file thisplay correctly in the simulator and on a device but not in the storyboardimport uikitibdesignable class textfieldtableviewcell uitableviewcell var view uiview required initcoder adecoder nscoder superinitcoder adecoder setup override initstyle uitableviewcellstyle reuseidentifier string superinitstyle style reuseidentifier reuseidentifier setup func setup view loadviewfromnib viewframe bounds viewautoresizingmask uiviewautoresizingflexiblewidth uiviewautoresizingflexibleheight contentviewaddsubviewview func loadviewfromnib uiview let bundle nsbundleforclass selfdynamictype let nib uinibnibname textfieldtableview bundle bundle let view nibinstantiatewithownerself options nil0 as uiview return view the storyboard thisplays a permanent designables updatingbreaking the problem down into a less complex test of only subclassing a uitableviewcell and marking it as ibdesignable results in the same permanent designables updatingimport uikitibdesignable class textfieldtableviewcell uitableviewcell required initcoder adecoder nscoder superinitcoder adecoder override initstyle uitableviewcellstyle reuseidentifier string superinitstyle style reuseidentifier reuseidentifier has anyone had success with creating a ibdesignable uitableviewcell subclass this is happening in xcode 7 beta 6 and beta 5,['ios'] +970539,rake spec does not run with custom rails env but rspec and bundle exec rspec do so i am having a bit of a bizarre issue i have a custom rails environment setup for my ci server which is running linux the environment gets loaded properly and the tests do run on the ci server but only if i run them with bundle exec rspec instead of bundle exec rake spec or bundle exec rakewhen the tests do not run they still return an exit code of 0 and the ci server assumes the build was successful even if theoretically the build may be brokenidentical behavior occurs on my machine which is running os xheres a console session with all the different test cases to better illustrate whats happeningno rails env specifiedmyapp rakeusersiorvmrubiesruby220binruby iusersiorvmgemsruby220gemsrspeccore332libusersiorvmgemsruby220gemsrspecsupport330lib usersiorvmgemsruby220gemsrspeccore332exerspec pattern spec specrbfinished in 434 seconds files took 31 seconds to load47 examples 0 failures myapp rake specusersiorvmrubiesruby220binruby iusersiorvmgemsruby220gemsrspeccore332libusersiorvmgemsruby220gemsrspecsupport330lib usersiorvmgemsruby220gemsrspeccore332exerspec pattern spec specrbfinished in 38 seconds files took 336 seconds to load47 examples 0 failures myapp rspecfinished in 387 seconds files took 298 seconds to load47 examples 0 failures myapp bundle exec rakeusersiorvmrubiesruby220binruby iusersiorvmgemsruby220gemsrspeccore332libusersiorvmgemsruby220gemsrspecsupport330lib usersiorvmgemsruby220gemsrspeccore332exerspec pattern spec specrbfinished in 39 seconds files took 303 seconds to load47 examples 0 failures myapp bundle exec rake specusersiorvmrubiesruby220binruby iusersiorvmgemsruby220gemsrspeccore332libusersiorvmgemsruby220gemsrspecsupport330lib usersiorvmgemsruby220gemsrspeccore332exerspec pattern spec specrbfinished in 364 seconds files took 297 seconds to load47 examples 0 failures myapp bundle exec rspecfinished in 375 seconds files took 295 seconds to load47 examples 0 failureseverything is working as expectedwith a standard rails envresults are identical with test development or productionmyapp rails envtest rakeusersiorvmrubiesruby220binruby iusersiorvmgemsruby220gemsrspeccore332libusersiorvmgemsruby220gemsrspecsupport330lib usersiorvmgemsruby220gemsrspeccore332exerspec pattern spec specrbfinished in 386 seconds files took 307 seconds to load47 examples 0 failures myapp rails envtest rake specusersiorvmrubiesruby220binruby iusersiorvmgemsruby220gemsrspeccore332libusersiorvmgemsruby220gemsrspecsupport330lib usersiorvmgemsruby220gemsrspeccore332exerspec pattern spec specrbfinished in 39 seconds files took 302 seconds to load47 examples 0 failures myapp rails envtest rspec finished in 382 seconds files took 298 seconds to load47 examples 0 failures myapp rails envtest bundle exec rakeusersiorvmrubiesruby220binruby iusersiorvmgemsruby220gemsrspeccore332libusersiorvmgemsruby220gemsrspecsupport330lib usersiorvmgemsruby220gemsrspeccore332exerspec pattern spec specrbfinished in 376 seconds files took 291 seconds to load47 examples 0 failures myapp rails envtest bundle exec rake specusersiorvmrubiesruby220binruby iusersiorvmgemsruby220gemsrspeccore332libusersiorvmgemsruby220gemsrspecsupport330lib usersiorvmgemsruby220gemsrspeccore332exerspec pattern spec specrbfinished in 383 seconds files took 299 seconds to load47 examples 0 failures myapp rails envtest bundle exec rspec finished in 383 seconds files took 311 seconds to load47 examples 0 failuresonce again everything is fine and dandywith a custom rails envmyapp rails envci rakeusersiorvmrubiesruby220binruby iusersiorvmgemsruby220gemsrspeccore332libusersiorvmgemsruby220gemsrspecsupport330lib usersiorvmgemsruby220gemsrspeccore332exerspec pattern spec specrbfinished in 373 seconds files took 303 seconds to load47 examples 0 failures myapp rails envci rake spec no output just a brief pause and back to shell promptmyapp rails envci rspec finished in 782 seconds files took 296 seconds to load47 examples 0 failures myapp rails envci bundle exec rake no output just a brief pause and back to shell promptmyapp rails envci bundle exec rake spec no output just a brief pause and back to shell promptmyapp rails envci bundle exec rspec finished in 7 seconds files took 28 seconds to load47 examples 0 failuresdue to the nature of the ci servers setup i have to run the tests within bundle exec but what i find mind boggling is that on my machine rails envci rake works flawlessly while rails envci rake spec does not runbut when i wrap them in a bundle exec neither rake nor rake spec run in rails envci but bundle exec rspec works finecan someone explain what is going on here i cannot find a way for this to make any logical sense have i stumbled upon a bug in rails rake tasksedit in response to haradwaiths answeryou bring up some really good points and the first point is spot on it runs the rspec executable directly but i cannot say your answer adequately explains whats happeningthis behavior is not specific to my machine the behavior is identical on a clean ruby22 docker container which runs bundle install before every test as it loads a clean container each time there is no way for old versions of gems to creep into further replicate the clean slate of the docker container i just did a test on my machine with an empty gemset to rule out gem version conflicts and got identical results my gemfile does indeed have no mention of a ci group if the rspecrails gem is not being loaded then rails envci rake with no arguments wouldnt run rspec as the default rake task but it clearly does we can also see that it has different behavior depending on whether or not its being ran with bundle exec i do not believe that running with bundle exec would unload rspecrails if running it without bundler somehow manages to load it automaticallyif rspec andor rspecrails werent being loaded the rake would fail with an exit code other than 0 and spit out something likenotmyapp touch rakefilenotmyapp rake specrake aborteddo not know how to build task specsee full trace by running task with trace,"['ruby-on-rails', 'ruby']" +970751,cannot resolve overloaded method with generic lambda this codepublic static void fstring args public static void finteger args public static void mainstring args fstreamofxtoarrayi new stringicompiles success with jdk8u45 but jdk8u60 prints the following errorerror17 9 java reference to f is ambiguous both method fjavalangstring in type infertest and method fjavalanginteger in type infertest matchdoes it follow the jsl why compiler can not resolve overloaded methods was it a fixed bug in jdk8u45,['java'] +970806,google drive api files search i need to create a file and share it for all user in the same domain within a js applicationheres the creation request body title documentname mimetype applicationvndgoogleappsspreadsheetthan i add domain permissions for created filepermissions insert request body role writertype domainvalue domainresult in driveeverything works fine for the user that created the file i can find the file with qtitledocumentname and trashedfalsebut i cannot find that file with another useri tried to look in sharedwithme folder qtitlethat documentname and trashedfalse and sharedwithmetrue no resultsi basically need to search like but i cannot find anything related to sourcedomain in drive apis,['javascript'] +970904,how to prevent my snackbar text from being truncated on android i am thisplaying a snackbar with a fairly long text message and on the phone in portrait mode it looks finebut on the tablet it seems to only allow 1 line of text so it gets ellipsisedis there anyway i can get it to be 2 line in tablet landscape,['android'] +970955,extjs using remotely loaded singleton values for store definition i am having some trouble trying to figure out how to do this if it is even possiblei have an app which uses parsecom to store it is data the thing is i want each user to have a different parsecom account so their data sets do not intersect whatsoever so i created a singleton settings which stores the users appid and apikey which are loaded from a general parsecom account which is managed by me and contains each users email appid and apikey so when they log into the app it gets the users appid and apikeythe thing is i need to use those settings appid and apikey in the definitions of my stores as i need to send them in the headers i have done some testing trying to set my singletons globals when the app launchs but at the time of the stores definition both of those globals are null as the app has not launched yetheres some of my code so i can make myself a little clearer as i know this is not the easiest thing to understandapplicationjsextdefinesettings singleton true appid null apikey nullextdefinemyappapplication extend extappapplication name myapp stores launch function extcreatemyappstoresettingsload params where email email is supposed to be a user input but for the sakes of testing i just made it static callback functionrecords var s records0 settingsappid sgetappid settingsapikey sgetapikey parseinitializesettingsappid settingsapikey onappupdate function extmsgconfirmapplication update this application has an update reload function choice if choice yes windowlocationreload storeextdefinemyappstorethings extend extdatastore model myappmodelthing proxy type rest api read create reader type json rootproperty results usedefaultxhrheader false withcredentials false headers xparseapplicationid settingsappid this is null at the time of definition but i want it to be the newly fetched value at the time of app launch xparserestapikey settingsapikey this is obviously null as well contenttype applicationjson autoload true autosync truewhats the way around thisby the way if someone can think of a proper name for this thread please feel free to change it or suggest,['javascript'] +970956,how to thisable all whitespace autoformatting in visual studio 2015 i really like the new visual studio 2015 but the auto formatting is a bit too much extensive for my liking especially i like to have control over whitespacepublic class tipstats public int points get set public int position get set public decimal percentage get set i only see three autoformat settings in my settings and i have ticked them all off still visual studio is autoformatting my whitespace are there any other hidden settings that i need to know for thisabling all whitespace autoformattingupdateas saragis notes ignore spaces in declaration statements works sometimes for this specific example but still there all kind of autoformat forces working against what i wantmost options seem to only define how you want your autoformatting i am looking for the setting that defines if you want autoformattingps i am having only problems with autoformatting i still use ctrlk f to manual format parts of my code now and thenupdate added feature request on uservoice,['c#'] +971062,how to detect if the page is slow due to 3rd party javascripts for those of us who run content websites and deal with ad networks combating malicious or malfunctioning rogue ads can be frustrating i own a site that embeds a lot of youtube dailymotion videos once in awhile a bad ad will turn up and make the video playback stutter i always dealt with these on a casebycase basis but is there a way to detect using javascript whether or not the page is slowin my head a very crude way is to have a setinterval running at 100ms and if it detects a big delay in one interval act accordinglyare there other more elegant approaches,['javascript'] +971086,suggestions for an ios mobile apps writing platform i recently began studying mobile apps development and wonder if anyone has a good suggestion for an ios compiler software,['ios'] +971103,how can i set a hook to run code at the end of a ruby class definition i am building a plugin that will allow a developer to add various features to a class with a simple declaration in the class definition following the normal acts as patternfor example code consuming the plugin might look likeclass yourclass consumes my plugin option1 value1 specific method to use your methodendmy question arises because i want to error check that the value provided for the specific method to use parameter exists as a method but the way code is typically organized and loaded the method does not exist yetthe code in my plugin tentatively looks like thismodule myplugin extend activesupportconcern module classmethods def consumes my pluginoptions raise argumenterrornewoptionsspecific method to use is not defined if optionsspecific method to usepresent selfrespond tooptionsspecific method to use end endendthis would workclass yourclass def your method true end consumes my plugin option1 value1 specific method to use your methodendbut this is how most people write code and it would notclass yourclass consumes my plugin option1 value1 specific method to use your method def your method true endendhow can i fail at yourclass load time i want it to error then not at run time with a nomethoderror can i defer execution of the line that raises the argumenterror until the entire class is loaded or do something else clever to achieve that,['ruby'] +971440,multiple assignment on one line not working as expected i am trying to swap two ints x and y in the example and do it in one line without a library functionso i started with thisint x 4int y 3systemoutprintlnxsystemoutprintlnyx ysystemoutprintlnxsystemoutprintlnyy xsystemoutprintlnxsystemoutprintlnyx ysystemoutprintlnxsystemoutprintlnythe output was 4 3 7 3 7 4 3 4 as expected all good so farnext up was this int x 4int y 3systemoutprintlnxsystemoutprintlnyy x ysystemoutprintlnxsystemoutprintlnyx ysystemoutprintlnxsystemoutprintlnythe output was 4 3 7 4 3 4 as expected once again still good so farthen finally thisint x 4int y 3systemoutprintlnxsystemoutprintlnyx y x ysystemoutprintlnxsystemoutprintlnyat this stage the output became 4 3 0 4 now i know that the 0 is a result of 4 4 because the x assignment was not complete at that time why is this happening why does not the x y actually assign 7 to the x variable so that it becomes 7 4 for the last assignment,['java'] +971447,why does equals result in an assertion error when comparing two objectsbut only sometimes i am working on unit testing for a project at code school and equals is giving me some trouble in my project save is saving into an sql database this code passes the unit testtestpublic void save assignsnametoobject restaurant testrestaurant new restaurantpokpok5034 testrestaurantsave restaurant savedrestaurant restaurantallget0 assertequalssavedrestaurantgetname pokpokbut if i change the final line to the following it will result in an assertion errorasserttruesavedrestaurantequalstestrestauranti debugged using systemoutprintln to verify that both values in testrestaurant do equal the corresponding values in savedrestaurant the following unit test for an object of another very similar class passes using the equals methodtestpublic void save assignsidtoobject true cuisine testcuisine new cuisinemexican testcuisinesave cuisine savedcuisine cuisineallget0 asserttruesavedcuisineequalstestcuisineedit here is my source code for equalsoverridepublic boolean equalsobject otherrestaurant if otherrestaurant instanceof restaurant return false else restaurant newrestaurant restaurant otherrestaurant return thisgetid new restaurantgetid thisgetnameequalsnewrestaurantgetname thisgetphoneequalsnewrestaurantgetphone why can equals compare some objects and not others in my code example the only difference i am seeing is that one object takes one parameter and the other takes twothank you,['java'] +971488,how to get view from drawer header layout with binding in activity so this is my activity mainxmlxml version10 encodingutf8layout xmlnsandroid xmlnsapp xmlnstools toolscontextcomnjiukobalrogbalrogcomnjiukobalrogbalrogactivitiesmainactivity a drawerlayout is intended to be used as the toplevel content view using match parent for both width and height to consume the full space available androidsupportv4widgetdrawerlayout androidididdrawer layout androidlayout widthmatch parent androidlayout heightmatch parent as the main content view the view below consumes the entire space available using match parent in both dimensions relativelayout androidlayout widthmatch parent androidlayout heightmatch parent linearlayout androidididll container androidlayout widthmatch parent androidlayout heightmatch parent androidorientationvertical androidsupportv7widgettoolbar androidididmy awesome toolbar androidlayout widthmatch parent androidlayout heightwrap content androidbackgroundandroidcolorblack androidfitssystemwindowstrue textview androidididtoolbar title androidlayout widthwrap content androidlayout heightwrap content androidlayout marginleft10dp androidlayout marginstart10dp androidtextcolorandroidcolorwhite androidtextsizedimenabc text size title material toolbar toolstextstringdefault toolbar title androidsupportv7widgettoolbar framelayout androidididcontainer androidlayout widthmatch parent androidlayout heightmatch parent framelayout linearlayout androidsupportdesignwidgetfloatingactionbutton androidididfab fuf androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentbottomtrue androidlayout alignparentendtrue androidlayout alignparentrighttrue androidlayout marginbottom20dp androidlayout marginend20dp androidlayout marginright20dp androidsrcdrawableflamme appfabsizenormal relativelayout androidsupportdesignwidgetnavigationview androidididnavigation view androidlayout widthwrap content androidlayout heightmatch parent androidlayout gravitystart androidbackgroundandroidcolorblack appheaderlayoutlayoutdrawer header appitemtextcolorcolordrawer item color selector appmenumenumenu drawer androidsupportv4widgetdrawerlayoutlayoutand i am using binding for the activity so i do not have to use the findviewbyid and cast it etc like this activitymainbinding binding databindingutilsetcontentviewthis rlayoutactivity main toolbar toolbar bindingmyawesometoolbar toolbartitle bindingtoolbartitle balrogfontshelpersetkhandboldtoviewtoolbartitle setsupportactionbartoolbar final actionbar actionbar getsupportactionbar if actionbar null actionbarsethomeasupindicatorrdrawableic dehaze white 24 actionbarsetthisplayhomeasupenabledtrue actionbarsetnavigationmodeactionbarnavigation mode standard actionbarsetthisplayshowtitleenabledfalse drawerlayout bindingdrawerlayout tvloggeduseremail textview findviewbyidridtv logged user email balrogfontshelpersetkhandboldtoviewtvloggeduseremailas you can see i can get the views that are directly in the activity mainxml layout by binding but when the view i am trying to get is not there i cannot see the variable in the binding objectdrawer headerxml xml version10 encodingutf8relativelayout xmlnsandroid androidlayout widthmatch parent androidlayout height96dp xmlnstools androidbackgroundandroidcolorblack androidthemestylethemeoverlayappcompatdark textview androidididtv logged user email androidlayout widthwrap content androidlayout heightwrap content androidlayout centerverticaltrue androidlayout marginleft16dp toolstextstringlogin placeholder email androidtextallcapstrue androidtextappearancestyletextappearanceappcompatbody2 androidtextsize20sprelativelayouthow could i get this tv logged user email textview in a binding way so i havetvloggeduseremail bindingtvloggeduseremail,['android'] +971640,bug caused by use of function instead of sub in single line lambda expression i have just come across a situation where a colleague wrote a bug and we did not understand why it happened despite the fact we know how to fix it i have been using lamda expressions for years but am much more experienced with c than vb and i obviously have a fundamental misunderstanding of somethingthe following is observed in visual studio 2010 with net 35i have simplified this down to the following simple test code that reproduced a similar scenarioon a windows form i put the following to simply execute a lambda and then print the value of a test object to a textboxprivate sub executeactionbyval action as actionof testclass dim testobj as new testclass actiontestobj textbox1text testobjmyintegerend subpublic class testclass public myinteger as integerend classand then i run some code to call it using a lambdain the following case the output in the textbox is 15 as i would expect executeactionsubobj objmyinteger 15in the following case the output is also 15 as i would expect it does generate a warning because no return value is specified which i understand and is fine because it does what is expected executeactionfunctionobj objmyinteger 15 end functionin the following case the output is 0 and i do not understand whyexecuteactionfunctionobj objmyinteger 15why in the final scenario does the value of the object not change to 15 i need to understand this difference between single line function lambdas and multi line function lambdas to see if i need to check across all our products for similar bugs it compiles fine and does not generate warnings making it extremely dangerous for our usesi tried the following to see if it made any difference forcing the execution before any implicit return but it did notexecuteactionfunctionobj objmyinteger 15,['.net'] +971723,how to interactively thisplay and hide lines in a bokeh plot it would be nice to be able to interactively thisplay and hide lines in a bokeh plot say i have created my plot something like thisfrom bokehplotting import output file figure showfrom numpyrandom import normal uniformmeas data 1 normal0 1 100meas data 2 uniform05 05 100output filemyplothtml titlemy plotfig figurewidth500 plot height500figlinexrange0 lenmeas data 1 ymeas data 1figlinexrange0 lenmeas data 2 ymeas data 2showfighow can i add the possibility to interactively enablethisable one of the two linesi know that this is on the wish list see this feature request but that does not sound like it would be implemented too soon i have the impression that this should be possible using a checkboxgroup and a selfdefined callback but unfortunately this callback has to be written in javascript which i have absolutely no experience in,"['javascript', 'python']" +971829,how do i handle async operations in startupconfigure in my aspnet 5 app i want to load some data from azure into a cache inside my startupconfigure method the azure sdk exposes async methods exclusively typically calling an async method is done via await inside an async method like thispublic async task configureiapplicationbuilder app imemorycache cache data datatocache await datasourceloaddataasync cachesetsomekey datatocache remainder of configure method omitted for clarityhowever aspnet 5 requires that the configure method returns void i could use an async void method but my understanding is that async void methods are only supposed to be used for event handlers as per among many othersi was thinking that a better way to do this would be to call the async function without await call wait on the returned task then cache the results via the taskresults property like thispublic void configureiapplicationbuilder app imemorycache cache taskdata loaddatatask datasourceloaddataasync loaddatataskwait cachesetsomekey loaddatataskresult remainder of configure method omitted for claritystephen walther used a similar approach in a blog post earlier this year however it is unclear from that post if this is considered an acceptable practice is itif this is considered an acceptable practice what if any error handling do i need my understanding is that taskwait will rethrow any exceptions thrown by the async operation and i have not provided any mechanism to cancel the async operation is simply calling taskwait sufficient,"['c#', 'asp.net']" +971835,properly terminating program using exceptions question is using exceptions the proper way to terminate my program if all i want is to thisplay an error message and close accounting that i may be deep in the program can i just explicitly call something like exit insteadwhat i am currently doingi am working on a game project and am trying to figure out the best way to terminate the program in the case of an error that calls for such an action for example in the case the textures cannot be loaded i thisplay an error message and terminate the programi am currently doing this with exceptions like soint main game game try gamerun catch badresolutionexception e notificationshowerrormessageewhat error resolution return 1 catch badassetexception e notificationshowerrormessageewhat error assets return 1 catch stdbad alloc e notificationshowerrormessageewhat error memory return 1 return 0all but bad alloc are my own defined exceptions derived from runtime errori do not need any manual resource cleanup and i am using stdunique ptr for any dynamic allocation i just need to thisplay the error message and close the programresearchalternatives to exceptionsi have looked up a lot of posts on so and other places and have seen others say anything from do not use exceptions to use exceptions but your using them wrong i have also looked up explicitly calling something like exitusing exit sounds nice but i read it would not go back through the call stack up to main cleaning everything up if i can find this again i will post the link additionally according to this should not be used if multiple threads are active i do expect to be creating a second thread for a short time at least once and an error could occur in that threadnot using exceptions was mentioned in some replies here in relation to games use exceptions was thiscussed here there are a number of other sources i have read but those were the most recent i looked atpersonal conclusiondue to my limited experience of working with error handling and using exceptions i am not sure if i am on the right track i have chosen the route of using exceptions based on the code i posted above if you agree that i should tackle those cases with exceptions am i using it correctly,['c++'] +971853,afnetworking problems with tls verification of a self signed server root ca this is a question that tries to both find solutions for my particular use case and to document what i have tried to do for anyone else who is following this processwe have a restful server and an ios app we have our own certificate authority and the server has a root certificate authority and a self signed certificate we followed this process to generate the following filesrootcapemrootcakeyservercrtserverkeyonly the server certificates are stored on our server and as part of the ssl process the public keys are sent with the api calls for verificationi have followed this process to use afnetworking to use certificate pinning as well as public key pinning to verify our self signed certificateswe convert the crt file to a cer file in der format according to this guideand include the cer file servercer in the ios app bundle this successfully allows our app to make getpost requests to our server however because our server certificate might expire or get reissued we want to instead use the root ca as done by people in this thread on afnetworkingcurrently weve updated to afnetworking 260 so our networking libraries should definitely include all the updates include ones in this thiscussionthe code used to create our security policy var manager afhttprequestoperationmanager afhttprequestoperationmanager managerrequestserializer afjsonrequestserializer force serializer to use json encoding let policy afsecuritypolicy afsecuritypolicypinningmode afsslpinningmodepublickey var data nsdata nsdata for name string in rootca server let path string nsbundlemainbundlepathforresourcename oftype cer let keydata nsdata nsdatacontentsoffile path dataappendkeydata policypinnedcertificates data policyallowinvalidcertificates true policyvalidatesdomainname false managersecuritypolicy policywith servercer included were able to trust our server by pinning the public key also tried afsecuritypolicypinningmodecertificate this worked because the exact certificate is included however because we might change up the servercrt file that the server has so we want to be able to do it with just rootcacerhowever with just the rootca included in the app bundle this does not seem to work is it that the rootca does not have enough information about the public key to verify the server certificate which was signed with the root ca the servercrt file may also have a changing commonnamealso since my fluency in ssl terminology is pretty raw if anyone has can clarify whether i am asking the correct questions that would be great the specific questions aream i generating the certificates correctly so that the server can prove its identity using the self signed servercrt fileis it possible to include only the rootcacer file into the bundle and be able to verify the leaf certificate servercrt will it be able to verify another server2crt file signed by the same rootca or should we include an intermediate cert between the rootca and the leafis public key pinning or certificate pinning the right solution for this every forum and blog post i have read says yes but even with the most updated afnetworking library we have not had any luckdoes the server need to somehow send both the servercrt and the roomcapem signatures over,['ios'] +971957,efficiently find every combination of assigning smaller bins to larger bins let us say i have 7 small bins each bin has the following number of marbles in itvar smallbins 1 5 10 20 30 4 10i assign these small bins to 2 large bins each with the following maximum capacityvar largebins 40 50i want to find every combination of how the small bins can be thistributed across the big bins without exceeding capacity eg put small bins 45 in large bin 2 the rest in 1 constraintseach small bin must be assigned to a large bin a large bin can be left emptythis problem is easy to solve in onm o2n time see below just try every combination and if capacity is not exceeded save the solution i would like something faster that can handle a variable number of bins what obscure graph theory algorithm can i use to reduce the search spacebrute forcevar smallbins 1 5 10 20 30 4 10var largebins 40 50function getlegitcombossmallbins largebins var legitcombos var assignmentarr new uint32arraysmallbinslength var i smallbinslength1 while true var isvalid validateassignmentarr smallbins largebins if isvalid legitcombospushnew uint32arrayassignmentarr var alldone incrementassignmentarr largebinslengthi if alldone true break return legitcombosfunction incrementassignmentarr max i while i 0 if assignmentarri max assignmentarri 0 i else return i return truefunction validateassignmentarr smallbins largebins var totals new uint32arraylargebinslength for var i 0 i smallbinslength i var assignedbin assignmentarri totalsassignedbin smallbinsi if totalsassignedbin largebinsassignedbin return false return truegetlegitcombossmallbins largebins,['javascript'] +971966,issues relating to type parameters in java method calls the java language specification for java 8 provides an example of a method call with a type argument in example 41 usage of a types void loops s thissloops s is the the type argument for the method callin that example the supplied type argument is meaningful but apparently type arguments for method calls can also be redundant and completely meaningless and generics need not even be involved for examplevoid m void test m thism thisintegerm compiles and runs ok thisstring byte stringbuilder thread throwablem compiles and runs ok integerm would not compile illegal start of expressioni have a couple of questions arisingcan anyone suggest a valid reason for java allowing these redundant type parameters accepting that they do no harm it still seems to me like something that the compiler could and should catchthat code only compiles if the method calls with type arguments are prefixed with this otherwise you get illegal start of expression errors is that a bug should not any unambiguous method call that works with this also work without thisthe catalyst for these questions is oracles response to a bug report i created for an interesting java problem someone raised here on soupdate sep 18 2015i raised bug jdk8098556 for this issue with oracle here is their responsethis is not an issue method references are checked using same rules as plain methods note that for ordinary methods you can always supply redundant typeargumentsvoid m thisstringm legalmethod and constructor references simply inherit this behavior as per 1513if the method reference expression has the form referencetype typearguments identifier the potentially applicable methods are the member methods of the type to search that have an appropriate name given by identifier accessibility arity n or n1 and type argument arity derived from typearguments as specified in a151221since that response confirms the information task had already provided below including citing the relevant section of jls i have accepted that answer,['java'] +972006,comparing two variables with is operator which are declared in one line in python according to the documentationthe current implementation keeps an array of integer objects for all integers between 5 and 256 when you create an int in that range you actually just get back a reference to the existing object so it should be possible to change the value of 1 i suspect the behaviour of python in this case is undefined so the following behaviors are normal a 256 b 256 a is btrue c 257 d 257 c is dfalsebut when i declare two variables like these i am getting true e 258 f258 e is ftruei have checked the identity of the objects referenced by e and f ide43054020 idf43054020they are same my question is what is happening when we are declaring e and f by separating with semicolons why are they referencing to the same object though the values are out of the range of pythons array of integer objects it would be better if you please explain it like you are explaining it to a beginner,['python'] +972017,errorinvalid comparator when sorting using custom comparison function i am trying to sort some integers and make odd integers followed by even ones i am using visual studio 2015heres my codeint w123456sortww6const inticonst intjbool return i1j1when both are odd or even the order is oki1if one is odd and one is evencheck if the first one is oddwhen executed it encounters an error says expression invalid comparator i do not know why it would cause this error how to modify it,['c++'] +972042,css controlling cascade i have built an editor for users to use it has a pallette of styles to choose from for this example well call these p1 and p2 the problem i have is that they are overriding each other depending on what order they appear in the style sheeti cant find a way that is going to solve this because i do not know how these panels may be nestedthis example is significantly simplified and i cannot control exactly where things like the a tag will be they could be nested in tables lists paragraphs or any other tags at any depth this would also apply to headings and any other child elements that need there style customized eg h1 ul to look good in the context that it is shown inp1 a color redp2 a color greendiv classpl p2 a hrefhello 2a div classpl p1 a hrefhello 21a div classpl p2 a hrefhello 212a div divdivdiv classpl p1 a hrefhello 1a div classpl p2 a hrefhello 12a div classpl p1 a hrefhello 121a div divdivi have played around with not selector and also using alldefault on children but have had no luck,"['html', 'css']" +972303,design redux actions and reducers for a react reusable component i am developing a large application with redux and react and i decided to make some reusable components like custom checkboxes and radio buttonsas i want to store this information into the redux store to be able to debug state of the application easily and the same component have the same functionality everywhere it seems a good idea to create reducers and actions for each component however redux reducers return a new state and save it in the store with the name of the reducer as a key and this forbids having more than one component of the same type in the same page using the same actions and reducers but keeping different statesi think there are two solutions to this problemcreate different actions and reducers for each component that i use even thought the component and it is functionalities are the same this solutions does not seem a good solution because there will be a lot of redundant codecreate actions with sufficient parameters to be able to differentiate each one in the reducer and that way change only the part of the state that is specifiedi went forward with the second optionactions file for the checkbox componentimport createaction from reduxactions actions export const change checkbox state change checkbox state action creators export const changecheckboxstate createactionchange checkbox state block name state return block name state checked state reducers file for the checkbox componentimport handleactions from reduxactionsimport change checkbox state from checkboxactionsexport const checkboxcomponent handleactions change checkbox state state action actionpayloadblock actionpayloadname actionpayloadstate i use block to specify the page name to specify the name of the specific component eg gender and state as and object with the new statebut this solution has some problems toocannot specify initial state of each component because the keys of the state are dynamiccomplicates to much the store structure with a lot of nested statesaggregates data by component and not by form which will complicate debugging and it is logically incorrecti do not have enough experience with redux and react to think of a better solution to this problem but it seems to me that i am missing something important about reactredux relationship and this raises some questionsis it a good idea to store state of this reusable components into the redux stoream i wrong in binding together react components with redux actions and reducers,['javascript'] +972364,can i integrate microsoft lens into my application i like office lenss ability to automatically crop focus and align a picture mainly for receipt and expense processing i want to have an app flow that goes like thisuser opens my app and clicks photograph receiptlens opens android intent or similar in iosuser takes picturepicture is returned to my application for processingi am having trouble making that flow happen and to make the data transfer photo between the camera and my app seamless what options do i have,"['android', 'ios']" +972409,jumping markers on android maps api v2 i am seeing markers jump around on the map on android maps api v2 even when nothing is happening in the app heres a video of the behaviorwhat i expect markers should remain stationary at their originally added latlongwhat steps will reproduce the problem 1a download the apk from redesignonebusawayandroidobagoogledebugapkor1b build install and run the v206 tag of onebusawaya git clone b git checkout v206c gradlew installobagoogledebugd adb shell am start n comjoulespersecondseattlebusbotorgonebusawayandroiduihomeactivitybrowse to any supported city eg seattle or tampa and watch the green bus stop markers jump around on the mapi should add that i cannot always reproduce this it seems like everything works fine for a time but then when the markers start jumping around they do not stopmarker implementation detailsthe code that loads the icons used for the 9 marker types 8 directions no direction is herei am using this drawable stop iconxmlwhich is a number of shapes this creates the main green circle with the white outline and the drop shadoes then i am drawing the direction arrow on top of this drawable for each of the 8 directions code for drawing directions is herein the code to load the icons i am caching the bitmapdescriptor returned from bitmapdescriptorfactoryfrombitmap for each of the 9 icon types on first load so this is not done each time a marker is put on the mapi also saw the app crash to unfortunately onebusaway has stopped and saw this exception in logcat after letting the app sit on the map screen for a few minutes0810 164002422 1584315929comjoulespersecondseattlebusbot eandroidruntimei1 fatal exception glthread 8614 process comjoulespersecondseattlebusbot pid 15843 javalangillegalargumentexception comparison method violates its general contract at javautilcomparabletimsortmergehicomparabletimsortjava831 at javautilcomparabletimsortmergeatcomparabletimsortjava449 at javautilcomparabletimsortmergecollapsecomparabletimsortjava372 at javautilcomparabletimsortsortcomparabletimsortjava178 at javautilcomparabletimsortsortcomparabletimsortjava142 at javautilarrayssortarraysjava1957 at javautilcollectionssortcollectionsjava1864 at comgooglemapsapiandroidlib6gmm6nblaunknown source at comgooglemapsapiandroidlib6gmm6nlaunknown source at comgooglemapsapiandroidlib6gmm6nlbunknown source at comgooglemapsapiandroidlib6gmm6ncvfunknown source at comgooglemapsapiandroidlib6gmm6ncvrununknown sourcei have seen this on an lg g4 and nexus 6 more details on lg device is belowlg g4 ls991 with android 51 ls991zv4google play services client library version compile comgoogleandroidgmsplayservicesmaps750 and compile comgoogleandroidgmsplayservicesmaps780google play services version on the device google play services 7899 21342440android sdk version compilesdkversion 21 buildtoolsversion 2112this issue has not always existed which makes me believe it was introduced during an update to android google play servicesmaps at some pointi have opened an issue for this on gmapsapiissues as well but no response as of this posthas anyone else seen this any ideas for fixesediti should add that i cannot always reproduce this it seems like everything works fine for a time but then when the markers start jumping around they do not stopedit 2i have created a smaller demo project here on github that uses the same marker implementationhowever i have not yet seen the same problem thereedit 3i have changed to caching bitmaps instead of bitmapdescriptors in well see if this fixes the problem it is intermittent so the only way i will know is if i do not see the problem again for some period of timeedit 4i am still seeing the problem so looks like switching from caching bitmapdescriptors to bitmaps and changing to using contextcompatgetdrawable did not have any effectedit 5not sure if this is related but i am also seeing the following output in logcat when this happens0901 104600339 92789278 elibegli1 validate thisplay255 error 3008 egl bad thisplay 0901 104600339 92789278 elibegli1 validate thisplay255 error 3008 egl bad thisplayand901 1046069 92789278 wresourcesmanageri1 asset path systemframeworkcomgoogleandroidmapsjar does not exist or contains no resourcesand0901 104616019 11374311 wactivitymanageri1 scheduling restart of crashed service comgoogleandroidgmsusagereportingserviceusagereportingservice in 10ms 0901 104616019 11374311 wactivitymanageri1 scheduling restart of crashed service comgoogleandroidgmsicingserviceindexservice in 110msand0901 104838609 540226676 esqlitedatabasei1 error inserting context name8 end time14418918490 context family7 module idcomgoogleandroidcontextmanagermodulepowerconnectionmodule version1 sync state mod time millis14418918532 start time14418643058 sync state0 context id9680c4f4789a4d86acbf43d2098e89b8 time type3 proto blobb28265a3 androiddatabasesqlitesqliteconstraintexception unique constraint failed contextcontext id code 2067 at androiddatabasesqlitesqliteconnectionnativeexecuteforlastinsertedrowidnative method at androiddatabasesqlitesqliteconnectionexecuteforlastinsertedrowidsqliteconnectionjava790 at androiddatabasesqlitesqlitesessionexecuteforlastinsertedrowidsqlitesessionjava926 at androiddatabasesqlitesqlitestatementexecuteinsertsqlitestatementjava86 at androiddatabasesqlitesqlitedatabaseinsertwithonconflictsqlitedatabasejava1581 at androiddatabasesqlitesqlitedatabaseinsertsqlitedatabasejava1451 at comgoogleandroidcontextmanagerqakasourcefile405 at comgoogleandroidcontextmanagerqakbsourcefile380 at comgoogleandroidcontextmanagerqakasourcefile346 at comgoogleandroidcontextmanagerqakbsourcefile373 at comgoogleandroidcontextmanagergajasourcefile58 at comgoogleandroidcontextmanagergaarunsourcefile52 at comgoogleandroidcontextmanagergihandlemessagesourcefile214 at androidoshandlerthispatchmessagehandlerjava102 at androidoslooperlooplooperjava135 at androidoshandlerthreadrunhandlerthreadjava61edit 6i have not seen this issue lately and i noticed that google play services on the lg g4 device was bumped to 8115 2250156240 so maybe it was fixed with an update of google play services i will report back again lateredit 7i have seen this again in 8115 2250156240 and 8118 2272748240 although it does not seem nearly as bad as it used to be ie fewer markers jump around and the jumping is less noticeable it seems to be triggered mainly when resuming the app when its been in the background for a while if i kill the app and then start it fresh the problem thisappearsedit 8i found a way to consistently reproduce this seefrom above issuebuild install and run the v206 tag of onebusawaya git clone b git checkout v206c gradlew installobagoogledebugd adb shell am start n comjoulespersecondseattlebusbotorgonebusawayandroiduihomeactivityhold the device in a portrait orientationif youre not physically located in seattle or tampa or any of the supported regions youll need to go to settingsyour region and manually set the region after doing this scroll the map to the region or select take me there when promptedtap on a bus stop on the maptap on the 3 dots more button next to arrival time or tap on arrival in list in sliding paneltap on option show route on mapafter the route loads on the map change the device orientation to landscapewatch the markers jump around after the map reloadsfull video capture on lg g4 that shows new steps to produce and issue,['android'] +972412,how to unit test static resources served by spring resourcehandlerregistry i am trying to unit test a new spring mvc project i have a passing test for the home controller serving indexjsp i am trying to test serving static resources served by the resourcehandlerregistry in my webconfigany tips on how to do this correctly below is my coderunwithspringjunit4classrunnerclasswebappconfigurationcontextconfigurationclasses webconfigclasspublic class homecontrollertest private mockmvc mockmvcautowiredprivate webapplicationcontext webapplicationcontextbeforepublic void setup throws exception mockmvc mockmvcbuilderswebappcontextsetupwebapplicationcontext buildtestpublic void testgethomepage throws exception passing thismockmvcperformget andexpectstatusisok andexpectviewnameindex andexpectforwardedurlwebinfpagesindexjsptestpublic void testgetresources throws exception test fails with 404 thismockmvcperformgetresourcescsstestcss anddoprint andexpectstatusisok andexpectforwardedurlresourcescsstestcssoutput from print 20150828 125309 warn pagenotfound1136 no mapping found for http request with uri resourcescsstestcss in thispatcherservlet with name mockhttpservletrequest http method get request uri resourcescsstestcss parameters headers handler type null async async started false async result null resolved exception type null modelandview view name null view null model null flashmapmockhttpservletresponse status 404 error message null headers content type null body forwarded url null redirected url null cookies,['java'] +972611,in java why can a protected member be accessed from outside the class within the same package in his book herbert schildt says in page 172 3rd paragraph that protected applies only when inheritance is involvedin page 228 table 91 shows that a protected member can be accessed from a nonsub class within the same packagethe following code works and supports the information in table 91class1javapackage mypackpublic class class1 protected pro1 public class1 systemoutprintlnpro class2javapackage mypackclass class2 extends class1 class2 systemoutprintlnpro class3javapackage mypackclass class3 class3 class1 class1new class1 systemoutprintlnclass1pro it is alright that the variable pro can be accessed from the derived class class2 but how can it be accessed from the nonderived class class3 through a reference to an object of class1 it contradicts the statement on page 172 if it is so then i find no difference between the public and protected specifiers in this situation,['java'] +972637,how can i set up a wildcard subdomain i need to serve any of my subdomainssub1foocomsub2foocomanysubfoocomfrom foocomi have successfully added a a record with the value in websitepanelshould i make an edit at webconfig in my project to enable this feature alsoif i visit for example anysubfoocom i get the error messagethe connection to anysubfoocom was interruptedwhich i suppose means that something is blocking the responsehow can i fix that should i edit the webconfig somehow or whatupdatethe site hosted in a shared hosting environment,['asp.net'] +972662,how to change a dataframe column from string type to double type in pyspark i have a dataframe with column as stringi wanted to change the column type to double type in pysparkfollowing is the way i didtodoublefunc userdefinedfunctionlambda x xdoubletypechangedtypedf joindfwithcolumnlabeltodoublefuncjoindfshowjust wanted to know is this the right way to do it as while running through logistic regression i am getting some error so i wonder is this the reason for the trouble,['python'] +972823,alternative to nested ternary operator in js i personally love ternary operators and in my humble opinion they make complicated expressions very easy to digest take this one word resthistance 0 a resthistance 1 resdifference 3 b resthistance 2 resdifference 5 stringreskeylength 5 c dhowever in our projects eslint rules nested ternary operators are forbidden so i have to get rid of the abovei am trying to find out alternatives to this approach i really do not want to turn it into a huge if else statement but do not know if there is any other options,['javascript'] +972828,what does the chrome javascript cpu profiler do that could affect a programs performance during the profile i have recently managed to introduce a bug into my script which causes the physics frame rate to drop from 100fps to 10fps every now and then it is a physics simulation type appi have been trying to find the cause for quite a while now and have stumbled upon a wierd phenomena when the frame rate drops to 10fps if i run chromes cpu profiler it jumps back up to 100fps and stays there even after i stop the profilerso i have been playing around with the profiler and it seems like it thisables conditional breakpoints while it is running which speed up performance after making sure to remove all breakpoints clear my cache and restart the chrome process i am sure that breakpoints have nothing to do with itso what i would like to know is does chrome do anything else which could be affecting especially increasing the performance of my app while the profiler is runningi want to keep this question general so that it can help people who have similar but not identical problems but i should note that i am running my physics in a webworker thread and this worker thread is the one which experiences the wierd frame rate issuesthanksedit i am pretty sure this has something to do with the communication between the threads not sompletely sure though,['javascript'] +972887,where can i get sos for windows 10 iot i have a dump of a net universal app running on raspberry pi 2 windows 10 iot0 vertargetwindows 10 version 10240 mp 4 procs free arm nt thumb2product winnt suite singleusertsbuilt by 1001024016384 th11507091700i see it uses coreclr like silverlight did before0 lm vm coreclrstart end module name6e430 6e7fd0 coreclr export symbols coreclrdll loaded symbol image file coreclrdll timestamp thu jul 16 213739 2015 55a88693 file version 46231170 product version 40231170doing an analyze v does not download sos automaticallyloading the silverlight version of sos i found on my pc indicates the wrong version0 load cprogram filesmicrosoft silverlight51205130sosdll0 threadsthe version of sos does not match the version of clr you are debugging pleaseload the matching version of sos for the version of clr you are debuggingclr version 46231170sos version 51205130failed to load data access dll 0x804005it seems that sos was implemented on github but i could not find a binary downloadon my pc with visual studio 2015 community i could find a file called mrt100sosdll in the folder cprogram filesmsbuildmicrosoftnetnativex86 which turns out to be a debugging extension and says0 help mrt100sos is a debugger extension dll designed to aid in debugging net nativeprogramswhich sounded great but running any commands results in the following error message0 threadsfailed to find runtime dll mrt100 appdll 0x804005extension commands need mrt100 appdll in order to have something to doi am running out of ideas how do i debug a net universal app dump in a way that i can see the net callstack which imho results in the question where can i get sos for windows 10 iot,['c#'] +972946,swift performseguewithidentifier not working i am trying to switch view controllers after a user successfully logs in to their account but it is not working correctly i cant use a segue directly because if the login button is clicked it will go to that view controller regardless if the information is correct or not i have tried everything that i know of with no success this is the code i am trying ibaction func logintappedsender anyobject let username usernamefieldtext let password passwordfieldtext if usernameisempty passwordisempty var emptyfieldserroruialertview uialertviewtitle please try again message please fill in all the fields we can get you logged in to your account delegate self cancelbuttontitle try again emptyfieldserrorshow pfuserloginwithusernameinbackgroundusername passwordpassword user pfuser error nserror void in if user nil selfperformseguewithidentifierklikur sender self else if let errorstring erroruserinfoerror as string selferrormessage errorstring selfalertviewplease try again message the username password combiation you have given us does not match our records please try again buttonname try again i have the storyboard id set to test and it is not switching view controller when the correct information is entered can somebody help me resolve my problem,['ios'] +972958,find how many times each number between and and m can be expressed as a sum of a pair of primes consider this methodpublic static int countpairsint min int max int lastindex primessize 1 int i 0 int howmanypairs new intmaxmin1 forint outer primes forint inner primessublisti lastindex int sum outer inner ifsum max break ifsum min sum max howmanypairssum min i return howmanypairsas you can see i have to count how many times each number between min and max can be expressed as a sum of two primesprimes is an arraylist with all primes between 2 and 20 in this case min is 10 and max is 20 that is why primes goes until 20my method works fine but the goal here is to do something fastermy method takes two loops one inside the other and it makes my algorithm an ona2 it sucks like bubblesorthow can i rewrite my code to accomplish the same result with a better complexity like onlognone last thing i am coding in java but your reply can be in also python vbnet c ruby c or even just a explanation in english,['java'] +972992,simulating the rangebased for loops beginend behavior consider the specification of the rangebased for loops beginexpr and endexpr n4140 stmtrangedp1 given a range range of type rangetbeginexpr and endexpr are determined as followsif ranget is an array type beginexpr and endexpr are range and range bound respectively where bound is the array bound if ranget is an array of unknown size or an array of incomplete type the program is illformedif ranget is a class type the unqualifiedids begin and end are looked up in the scope of class ranget as if by class member access lookup 345 and if either or both finds at least one declaration beginexpr and endexpr are rangebegin and rangeend respectivelyotherwise beginexpr and endexpr are begin range and end range respectively where begin and end are looked up in the associated namespaces 342 note ordinary unqualified lookup 341 is not performed aend note is it possible to simulate this exact behavior in ordinary c code ie can we write a magic begin and a magic end function template such thatforauto p range init statements and auto my range range init forauto b magic beginmy range e magic endmy range b e b auto p b statements always have the exact same behaviornonanswers include qualified calls to stdbeginstdend does not handle the third bullet among other things and using stdbegin beginrange because among other things that is ambiguous if adl for begin finds an overload that is equally good as stdbeginfor illustration givennamespace foo struct a int begin struct b using end int class c int begin int end inaccessible struct d int beginint int end struct e templateclass t int begint return nullptr templateclass t int endt return nullptr fooa a foob b fooc c food d fooe ei want magic beginamagic beginbmagic begincmagic begind to be a compile error and magic begine to return intnullptr,['c++'] +973000,java 8 reference to method is ambiguous does anybody understand why the following code will compile fine in java 7 and below but fails with java 8public static void mainstring args throws exception putgethellopublic static r r getstring d return rdpublic static void putobject o systemerrprintlnobject opublic static void putcharsequence c systemerrprintlncharsequence cpublic static void putchar c systemerrprintlnchar cthe get method has a generic return type in jdk 7 and below this compiles fine and the put method with the object parameter is chosen in jdk 8 this cannot be compiled indicating the put method is ambiguousapparently jdk 8 is skipping over the objectparameter method and finding the last two subobjectparameter methods and complaining about them ie if you add another put method with some other parameter type the compiler will switch and complain about the new last two methodsthis seems like a bug,['java'] +973225,moving react classes into separate files after doing the react tutorial this is my indexhtml file indexhtml doctype htmlhtml head meta charsetutf8 titlehello reacttitle script srcscript script srcscript script srcscript script srcscript head body div idcontentdiv script srclibmainjsscript bodyhtmland this is my srcmainjsx filevar commentbox reactcreateclass getinitialstate function return data loadcommentsfromserver function ajax url thispropsurl datatype json cache false success functiondata thissetstatedata data bindthis error functionxhr status err consoleerrorthispropsurl status errtostring bindthis handlecommentsubmit functioncomment var comments thisstatedata var newcomments commentsconcatcomment thissetstatedata newcomments ajax url thispropsurl datatype json type post data comment success functiondata thissetstatedata data bindthis error functionxhr status err consoleerrorthispropsurl status errtostring bindthis componentdidmount function thisloadcommentsfromserver setintervalthisloadcommentsfromserver thispropspollinterval render function return div classnamecommentbox h1comments yoh1 commentform oncommentsubmitthishandlecommentsubmit commentlist datathisstatedata div var commentform reactcreateclass handlesubmit functione epreventdefault var author reactfinddomnodethisrefsauthorvaluetrim var text reactfinddomnodethisrefstextvaluetrim if text author return send request to the server thispropsoncommentsubmitauthor author text text reactfinddomnodethisrefsauthorvalue reactfinddomnodethisrefstextvalue return render function return form classnamecommentform onsubmitthishandlesubmit input typetext placeholderyour name refauthor input typetext placeholdersay something reftext input typesubmit valuepost form var commentlist reactcreateclass render function var commentnodes thispropsdatamapfunction comment return comment authorcommentauthor commenttext comment commentnodesreverse return div classnamecommentlist commentnodes div var comment reactcreateclass render function var rawmarkup markedthispropschildrentostring sanitize true return div classnamecomment h2 classnamecommentauthor thispropsauthor h2 span dangerouslysetinnerhtml html rawmarkup hr div reactrender commentbox urlcommentsjson pollinterval20 documentgetelementbyidcontentadditionally i am running this command to turn my jsx into jsbabel watch src outdir libi would like to move each react class into its own file for example i would like to create the following four files note each map to a top level var declaration in my mainjsx file and pull all of these classes into my mainjsx filecommentjsxcommentlistjsxcommentformjsxcommentboxjsxhow do i do thisafter banging my head on require and es6 for a while here i still do not have a good intuition of how to separate all these apart or if something like require es6 is even the right way to approach thisthanks for the help,['javascript'] +973408,if not null java 8 style java 8 presents optional classbefore java 7order order orderbeangetorderidif order null ordersetstatustrue pmpersistorder else loggerwarningorder is nullso on java 8 styleoptionalorder optional optionalofnullableorderbeangetorderidoptionalifpresent s ssetstatustrue pmpersists can we return from method in this place not from lambda so if return take place above we can avoid if optionalispresent checkif optionalispresent loggerwarningorder is null is it correct to use optional in this case can anyone propose a more convenient way in java 8 style,['java'] +973766,group by in mongoengine embeddeddocumentlistfield hi so i have this test data in mongo for mongoengine that i use for storing users cart id objectid55e492ac516ddc17a8b07d2a user objectid55e3f236516ddc78296968be items item objectid55e24cd6516ddcbdc081842b quantity 2 added date isodate20150831t1749023z item objectid55e24cd6516ddcbdc0818425 quantity 3 added date isodate20150831t1749025z item objectid55e24cd6516ddcbdc0818420 quantity 3 added date isodate20150831t1749026z here the modelsclass cartitemmongoengineembeddeddocument item mongoenginereferencefielditem quantity mongoengineintfield added date mongoenginedatetimefielddefaultdatetimenowclass cartmongoenginedocument user mongoenginereferencefielduser items mongoengineembeddeddocumentlistfieldcartitemhere i store items in users cart now i would like to get all the unique items in the items list field because there will be duplicate items i perform the following queries to get the itemscart cartobjectsfilteruseruserfirstqueryset cartitemsin this case i think i would have to group the items i tried using raw query in filter cartitemsfilter raw but this just does not work because raw is not supported in this case can someone please help me in how i can do this thank you,['python'] +973777,avoid cost of stdmutex when not multithreading suppose i have an application that may or may not have spawned multiple threadsis it worth it to protect operations that need synchronization conditionally with a stdmutex as shown below or is the lock so cheap that it does not matter when singlethreadinginclude atomicinclude mutexstdatomicbool more than one thread activefalsevoid operation requiring synchronization void call operation requiring synchronization if more than one thread active static stdmutex mutex stdlock guardstdmutex lockmutex operation requiring synchronization else operation requiring synchronization editthanks to all who have answered and commented very interesting thiscussiona couple of clarificationsthe application processes chunks of input and for each chunk decides if it will be processed in a singlethreaded or parallel or otherwise concurrent fashion it is not unlikely that no multithreading will be neededthe operation requiring synchronization will typically consist of a few inserts into global standard containersprofiling is of course difficult when the application is platformindependent and should perform well under a variety of platforms and compilers past present and futurebased on the thiscussion so far i tend to think that the optimization is worth iti also think the stdatomicbool more than one thread active should probably be changed to a nonatomic bool multithreading has been initialized the original idea was to be able to turn the flag off again when all threads other than the main one are dormant but i see how this could be errorproneabstracting the explicit conditional away into a customized lock guard is a good idea and facilitates future changes of the design including simply reverting back to stdlock guard if the optimization is not deemed worth it,['c++'] +973780,doctrine isdeletable method in entity i have a entity in my database say member which has many relationships with other tables 6 relationships to be exact some of them i do not want mapped with the orm i mean linked to this entity because they may have many records like memberaccesslogs for example and some other load many other entitiesnow i want this member entity to have an isdeletable method so i can thisable exclude button in administration page if i where to do this the traditional way i would have to declare the associations with all the other tables in the entity class including memberaccesslogs and i would put the method in it so i could test if these associations are emptybut afaiu i would have to make a fetch or at least a count to the associations tables in order check for emptyanother way would be to fetch the members i want shown and then make a separate query to check for empty with a low cost existsselect from table limit 1 in these subtables and then populate the isdeletable method in member programmatically before pass it to twigbut i found this solution cumbersome anyone has a better way to do this just for the record some people may think this is premature optimization i maintain contrary to some that you should think ahead when you are programming and do not this this is bad but i really think this is not the place to thiscuss it please let us focus on the question asked ok editto easily prove that limit 1 is increadibly faster than count i did a small test in a table in my database that has more than 20 million lines here are the resultsselect count from loga 20 million table206784731 rows fetched 27023msselect existsselect null from loga limit 1 true1 rows fetched 2msi guess 135115 times faster is conclusive enough d,['php'] +973827,android studio undo ctrlz redo ctrly not working i have just moved from eclipse to android studio and am finding really weird behaviour when i try to do ctrlz ctrly to undoredo code changesit hard to describe what happens exactly but the end result is that i usually end up just losing my code and having to type it back in from memorythe undo and redo buttons in the ide do seem to work fine so maybe something is wrong with my shortcut keys which would be surprising as i should just have a standard installation setupcan anyone advise what to do so ctrlz and ctrly will work in the expected manner,['android'] +973908,edittext cursor resetting to left after android data binding update i am trying out the new android data binding library 10rc1 and i have made a user object with three string fields name email and age and linked them to 3 edittexts in my layout on the first field name i placed a textwatcher everything seems to work well i prevented the notifypropertychanged loop in the name field by checking to see if the text is different before allowing it to call setname the problem is every time i type in the name field the cursor resets to the left of the edittext after each character i googled around for a solution but most fix suggestions for a cursor issue say to grab a reference to the edittext and adjust the cursor position manually but i would like to avoid doing that since i then need to findviewbyid to the edittext and the point of data binding was to try to avoid doing that thank you for your helpmy layout looks like thislayoutdata variable nameuser typecomcarlpooledatabindingstestuserdatarelativelayout xmlnsandroid xmlnsbind xmlnstools androidlayout widthmatch parent androidlayout heightmatch parent androidpaddingleftdimenactivity horizontal margin androidpaddingrightdimenactivity horizontal margin androidpaddingtopdimenactivity vertical margin androidpaddingbottomdimenactivity vertical margin toolscontextmainactivity edittext androidlayout width200dp androidlayout heightwrap content androidididname androidtextusername bindaddtextchangedlistenerusernamechanged edittext androidlayout width200dp androidlayout heightwrap content androidididemail androidlayout belowidname androidtextuseremail edittext androidlayout width200dp androidlayout heightwrap content androidididage androidlayout belowidemail androidtextuserage textview androidlayout widthwrap content androidlayout heightwrap content androidlayout belowidage androidtextusernamerelativelayoutmy user object looks like thisimport androiddatabindingbaseobservableimport androiddatabindingbindableimport androidtexteditableimport androidtexttextwatcherpublic class user extends baseobservable private string name private string email private string age public userstring name string email string age thisname name thisemail email thisage age public user bindable public string getname return name bindable public string getemail return email bindable public string getage return age public final textwatcher namechanged new textwatcher override public void aftertextchangededitable s ifstostringequalsignorecasename setnamestostring override public void beforetextchangedcharsequence s int start int count int after override public void ontextchangedcharsequence s int start int before int count public void setnamestring name thisname name notifypropertychangedcomcarlpooledatabindingstestbrname public void setemailstring email thisemail email public void setagestring age thisage age my activity looks like thisimport androiddatabindingdatabindingutilimport androidosbundleimport androidsupportv7appappcompatactivityimport comcarlpooledatabindingstestdatabindingactivitymainbindingpublic class mainactivity extends appcompatactivity override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate activitymainbinding binding databindingutilsetcontentviewthis rlayoutactivity main user user new usercarl poole 26 bindingsetuseruser,['android'] +973937,should i define the primary key for each entity in realm i have noticed that setting pk is not obligatory in realm and simply can be omitted but in documentation is stated that indexes are created automatically for primary key propertiesand i would like to clear up some questions1 what is the default value for pk is defined by realm if i do not assign it by myself is it hash or whatever if i do not set pk and call myrealmobject primarykey it returns nil2 if this implicit pk is indexed by default should i worry about it because if it is not indexed does it mean that it affects the general performance of this entity for examplefetching objects 3 is it a good practice to define pk every time for each rlmobject subclass or it is not necessary for realm and simply may rely on it is internal realization defined by realm itself,['ios'] +973945,getting error inflating class androidsupportdesignwidgetnavigationview i was following a tutorial on implementing the navigationview from the design support library and i just cannot get away from this error below i have read the other solutions posted on this site but none of them worked for me please helpcaused by androidviewinflateexception binary xml file line 28 error inflating class androidsupportdesignwidgetnavigationviewactivity mainxmlandroidsupportv4widgetdrawerlayout xmlnsandroidxmlnsappxmlnstoolsandroidididdrawerandroidlayout widthmatch parentandroidlayout heightmatch parentandroidfitssystemwindowstruetoolscontextmainactivitylinearlayout androidlayout widthmatch parent androidlayout heightmatch parent androidorientationvertical include androidididtool bar layoutlayouttool bar framelayout androidididframe androidlayout widthmatch parent androidlayout heightmatch parent framelayoutlinearlayoutandroidsupportdesignwidgetnavigationview androidididnavigation view androidlayout widthwrap content androidlayout heightmatch parent androidlayout gravitystart appheaderlayoutlayoutheader appmenumenudrawer androidsupportv4widgetdrawerlayoutmainactiviyjavaimport androidsupportdesignwidgetnavigationviewimport androidsupportv4widgetdrawerlayoutimport androidsupportv7appactionbardrawertoggleimport androidsupportv7appappcompatactivityimport androidosbundleimport androidsupportv7widgettoolbarimport androidviewmenuimport androidviewmenuitemimport androidviewviewimport androidwidgettoastpublic class mainactivity extends appcompatactivity defining variablesprivate toolbar toolbarprivate navigationview navigationviewprivate drawerlayout drawerlayoutoverrideprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main initializing toolbar and setting it as the actionbar toolbar toolbar findviewbyidridtool bar setsupportactionbartoolbar initializing navigationview navigationview navigationview findviewbyidridnavigation view setting navigation view item selected listener to handle the item click of the navigation menu navigationviewsetnavigationitemselectedlistenernew navigationviewonnavigationitemselectedlistener this method will trigger on item click of navigation menu override public boolean onnavigationitemselectedmenuitem menuitem checking if the item is in checked state or not if not make it in checked state if menuitemischecked menuitemsetcheckedfalse else menuitemsetcheckedtrue closing drawer on item click drawerlayoutclosedrawers check to see which item was being clicked and perform appropriate action switch menuitemgetitemid replacing the main content with contentfragment which is our inbox view case ridinbox toastmaketextgetapplicationcontext inbox selected toastlength shortshow contentfragment fragment new contentfragment androidsupportv4appfragmenttransaction fragmenttransaction getsupportfragmentmanagerbegintransaction fragmenttransactionreplaceridframe fragment fragmenttransactioncommit return true for rest of the options we just show a toast on click case ridstarred toastmaketextgetapplicationcontext stared selected toastlength shortshow return true case ridsent mail toastmaketextgetapplicationcontext send selected toastlength shortshow return true case riddrafts toastmaketextgetapplicationcontext drafts selected toastlength shortshow return true case ridallmail toastmaketextgetapplicationcontext all mail selected toastlength shortshow return true case ridtrash toastmaketextgetapplicationcontext trash selected toastlength shortshow return true case ridspam toastmaketextgetapplicationcontext spam selected toastlength shortshow return true default toastmaketextgetapplicationcontext somethings wrong toastlength shortshow return true initializing drawer layout and actionbartoggle drawerlayout drawerlayout findviewbyidriddrawer actionbardrawertoggle actionbardrawertoggle new actionbardrawertogglethis drawerlayout toolbar rstringopendrawer rstringclosedrawer override public void ondrawerclosedview drawerview code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank superondrawercloseddrawerview override public void ondraweropenedview drawerview code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank superondraweropeneddrawerview setting the actionbartoggle to drawer layout drawerlayoutsetdrawerlisteneractionbardrawertoggle calling sync state is necessay or else your hamburger icon wont show up actionbardrawertogglesyncstateoverridepublic boolean oncreateoptionsmenumenu menu inflate the menu this adds items to the action bar if it is present getmenuinflaterinflatermenumenu main menu return trueoverridepublic boolean onoptionsitemselectedmenuitem item handle action bar item clicks here the action bar will automatically handle clicks on the homeup button so long as you specify a parent activity in androidmanifestxml int id itemgetitemid noinspection simplifiableifstatement if id ridaction settings return true return superonoptionsitemselecteditembuildgradle apply plugin comandroidapplicationandroid compilesdkversion 23buildtoolsversion 2300defaultconfig applicationid comexamplemobinamanzaiprojectalpha minsdkversion 17 targetsdkversion 23 versioncode 1 versionname 10buildtypes release minifyenabled false proguardfiles getdefaultproguardfileproguardandroidtxt proguardrulespro debug debuggable true dependencies compile filetreedir libs include jarcompile comandroidsupportsupportv42300compile comandroidsupportappcompatv72300compile comandroidsupportdesign2300compile dehdodenhofcircleimageview130edit stack trace caused by androidviewinflateexception binary xml file line 28 error inflating class androidsupportdesignwidgetnavigationview caused by javalangreflectinvocationtargetexception caused by androidviewinflateexception binary xml file line 2 error inflating class androidwidgetrelativelayout caused by javalangreflectinvocationtargetexception caused by javalangoutofmemoryerror failed to allocate a 276203532 byte allocation with 12108696 free bytes and 174mb until oomedit 2 the problem seems to be in the headerxml,"['java', 'android']" +973974,viewpager title does not appear until i swipe it i am learning to use viewpager and pagertabstrip to implement navigation bar i have implemented it my problem is every time i open the app fresh the titles do not show but after i swipe it once the titles all appear again and then everything is normalcode shown belowcustomised adapterpublic class mypageradapter extends pageradapter private listview viewlist private liststring titlelist public mypageradapterlistview viewlist liststring titlelist thisviewlist viewlist thistitlelist titlelist override public int getcount return viewlistsize override public boolean isviewfromobjectview view object o return view o override public object instantiateitemviewgroup container int position containeraddviewviewlistgetposition return viewlistgetposition override public void destroyitemviewgroup container int position object object containerremoveviewviewlistgetposition override public charsequence getpagetitleint position return titlelistgetposition xml fileandroidsupportv4viewviewpager androidididviewpager androidlayout widthwrap content androidlayout heightwrap content androidlayout gravitycenter androidsupportv4viewpagertabstrip androidididtab androidlayout widthwrap content androidlayout heightwrap content androidlayout gravitybottom androidsupportv4viewviewpagerthis is the screenshot of just clicked the app iconand this is after i swiped to the second pagei am really frustrated thanks,"['java', 'android']" +974146,read random line from a large text file i have a file with 50 lines i want to find the most efficient way to choose one of those lines each time i run my program i had originally intended to use the random method to choose one that was before i knew there were 50 lines thought that might be inefficient so i thought i would look at reading the first line then deleting it from the top and appending it to the bottom but it seems that i have to read the whole file and create a new file to delete from the topwhat is the most efficient way the random method or the new file methodthe program will be run every 5 mins and i am using c 45,['c#'] +974158,linking a c program with spidermonkey i successfully compiled spidermonkey on windows how can i link against it now to embed itjsconfig is not properly installed and i do not understand this workaround linking to the static library should be easier but i do not even know which file it is i have mozgluelib mozjs43a1lib nspr4lib plc4lib plds4lib in thistsdklib and nspr4lib plc4lib plds4lib in thistlib updatejsconfig was not working because i had this problem bash r command not found because of windowsunix newline characters problem i ran dos2unix jsconfig and i could run ithowever the output does not help on windows jsconfig cflagsstdgnu0x include usrlocalincludemozjs43a1jsrequireddefinesh iusrlocalincludemozjs43a1 icusersyvaindocumentsmozillacentraljssrcbuild optobjthistincludenspr jsconfig libslibdirjs library namelib cusersyvaindocumentsmozillacentraljssrcbuild optobjthistlibnspr4lib cusersyvaindocumentsmozillacentraljssrcbuild optobjthistlibplc4lib cusersyvaindocumentsmozillacentraljssrcbuild optobjthistlibplds4lib kernel32lib user32lib gdi32lib winmmlib wsock32lib advapi32lib psapilibnotesi used the following command to compileg stdc11 iobjdirthistinclude lobjdirthistlib helloworldcpp o helloworld lmozjs31 lz lpthread ldl i know it is not the correct way to compile it since those libraries are not in objdirthistlib it returns the following errorsjscpucfgh1213 erreurerror cannot determine endianness of your platform please add support to jscpucfgherreur ajs evaluatescripta was not declared in this scopethis question seems to draw some attention note that i asked the same question for v8,['c++'] +974286,efficiently load a large mat into memory in opencv is there a more efficient way to load a large mat object into memory than the filestorage method in opencvi have a large mat with 192 columns and 1 million rows i want to store locally in a file and load into memory then my application starts there is no problem using the filestorage but i was wondering if there exists a more efficient method to do this at the moment it takes about 5 minutes to load the mat into memory using the debug mode in visual studio and around 3 minutes in the release mode and the size of the data file is around 12gbis the filestorage method the only method available to do this task,['c++'] +974331,libcurl stops working ssl connect error i am working on a program for personal use that scrapes a few webpages periodically one of them requires the use of ssl and its main url actually is a load balancer that redirects to a different domain each time out of a list of a handful not sure if this is relevant i am quite new to libcurl and ssl in particular so i may be missing something obvious but i do not think sothe program works fine for a while so far never longer than an hour but once it gets the ssl connect error for the first time it will keep giving the same error every time it is always a different amount of time and a different amount of successful requests before it starts failingthe error buffer always contains the following schannel next initializesecuritycontext failed sec e illegal message 0x80090326 this error usually occurs when a fatal ssltls alert is received eg handshake failed more detail may be available in the windows system event logthere is nothing useful in eventvwr searches on that error code return results about issues with self signed certificates on earlier versions of windows server but little else i do not control the server i am connecting to but i doubt it is a windows boxi have run out of ideas here so i am just going to give any details that may be relevant i cannot really post any actual source code because i have abstracted all the curl calls away in several classes so i would have to paste a lot of boilerplate code before others could make sense of it i have confirmed with the visual studio debugger that this is what the actual calls boil down to thoughi initialize libcurl in the main thread before any others are created like so curl global initcurl global win32 curl global sslthen i create and initialize the actual curl handle in a second thread and only in that thread like som handle curl easy initcurl easy setoptm handle curlopt writedata thiscurl easy setoptm handle curlopt writefunction writecurl easy setoptm handle curlopt debugdata thiscurl easy setoptm handle curlopt debugfunction debugcurl easy setoptm handle curlopt verbose 1curl easy setoptm handle curlopt errorbuffer m errormsg0curl easy setoptm handle curlopt followlocation 1curl easy setoptm handle curlopt cookiefile i have experimented with setting both curlopt ssl verifyhost and curlopt ssl verifypeer to 0 but that did not helpi built libcurl from curl7430targz with nmake f makefilevc modestatic vc12 enable winsslyes enable sspiyes machinex64 debugyes on visual studio 2013whats going on here and how can i fix it,['c++'] +974359,namespace thisappears when building release but present on debug the systemwindowsinteractivity namespace vanishes when i swap from debug build to release build my project fails to build naturally and gives the error and warning visible in the images below the namespace simply thisappears from the object browser as soon as i switch build modes even though the reference is still present in the solution explorerwhats going on here and how do i fix it,['c#'] +974534,optimizing opportunities with java streams i was looking through some code and came across this method that takes an html header value ie contentthispositioninlinefilenamefoobar and parses it into a map separated by the semicolons into keyvalue pairs at first it looked like a good candidate for optimization using a stream but after i implemented it the fact that i cannot reuse the computed stringindexof value means the string must be scanned 3 times which is actually less optimal than the original i am perfectly aware that there are many instances where streams are not the right tool for the job but i was wondering if i had just missed some technique that could allow the stream to be as performantmore performant than the initial code convert a header value string into a map param value the header value return the data map private static mapstringstring headermap string value int eq mapstringstring map new hashmap forstring entry valuesplit ifeq entryindexof 1 mapputentrysubstring0eqentrysubstringeq 1 return map return streamofvaluesplitfilterentry entryindexof 1collectcollectors headermapmy attempt at streaming it convert a header value string into a map param value the header value return the data map private static mapstringstring headermap string value return streamofvaluesplitfilterentry entryindexof 1collectcollectorstomapentry entrysubstring0entryindexofentry entrysubstringentrysubstringentryindexof 1 headermap,['java'] +974573,uploading pdf from jspdf with ajax using binary data i am attempting to pass a pdf i have generated on frontend javascript using jspdf to a spring framework mvc backend below is the front end code i have writtenvar filename thefilevar constructurl daasrestservicesdashboardpdfprintupload filenamevar url restservicegeturlconstructurlvar filebytes btoapdfoutputhttpposturl filebytessuccessfunctiondata consolelogdata errorfunctione a consoleloge consoleloga the pdf variable has been generated properly and can confirm is opens correctly when calling pdfsavefilename below is the java code which has been written on the spring mvc backend for this callrequestmappingmethod requestmethodpost value pdfprintuploaddocumentnamepublic responsebody string postprintdocumentpathvariable string documentname requestparam byte filebytes string methodname postprintdocument ifloggerisloggablelevelfiner loggerenteringclass name methodname string check iffilebytes null check not null else check null decoding the bytestream save to file location return file location string returnvalue hi documentname check if loggerisloggablelevelfiner loggerexitingclass name methodname return returnvalueeach time i make a request i am getting 400 errors telling me error 400 required byte parameter filebytes is not presenti can confirm in the request payload that a large amount of data is being transmitted however the backend does not seem to want to accept the parameterthe purpose of doing this is that i want to be able to get the data from the pdf and then decode it on the backend so i can later publish the pdf to a location on the server is there something i am missing in my code for these requests to keep failing and is there an easier more efficient way to achieve this functionality,"['javascript', 'java', 'jquery']" +974636,how to set android m default usb config to mtp rather than charging only whenever my device nexus 5 android m preview 3 connects via usb the usb config always defaults to charging only this is quite problematic because the usb port on my device is faulty and sometimes thisconnects and reconnects when bumped and so i have to manually change the mode to mtp media transfer protocol from the notification drawer each timedebugging mode is enableddevelop settings usb configuration is set to mtp,['android'] +974764,print specific nodes at a every level calculated by a given function i recently attended an interview and i was given a functionfn squarefn1 squarefn2 for n2f1 1f2 2here and is the level of an narray tree fn123516for every level n of a given narray tree an narray tree where every node has atmost n children i have to print the fn node at every level for exampleat level 1 print node number 1 ie root at level 2 print node number 2 from leftat level 3 print node number 3 from leftat level 4 print node number 5 and so onif the number of nodessay nl at any level n is less than fn then have to print node number nlfn counting from the lefti did a basic level order traversal using a queue but i was stuck at how to count nodes at every level and handle the condition when number of nodes at any level n is less than fni just need a way how to proceed the above problem,['java'] +974781,oop in c implicitly pass self as parameter i have been working on an example to learn oop in c currently i have come up with this code which is working however i am interested in making the methods implicitly pass self as a parameterinclude stdiohinclude stdboolhinclude stdlibhinclude stopwatchhtypedef struct stopwatch s unsigned int milliseconds unsigned int seconds unsigned int minutes unsigned int hours bool is enabled void tick struct stopwatch s void start struct stopwatch s void stop struct stopwatch s void reset struct stopwatch s stopwatch tstatic void tick stopwatch t self stopwatch t self self if selfis enabled selfmilliseconds if selfmilliseconds 10 selfmilliseconds 0 selfseconds if selfseconds 60 selfseconds 0 selfminutes if selfminutes 60 selfminutes 0 selfhours static void start stopwatch t self stopwatch t self self selfis enabled truestatic void stop stopwatch t self stopwatch t self self selfis enabled falsestatic void reset stopwatch t self stopwatch t self self selfis enabled false selfmilliseconds 0 selfseconds 0 selfminutes 0 selfhours 0void new stopwatch stopwatch t newinstance stopwatch t calloc1 sizeofstopwatch t newinstanceis enabled false newinstancemilliseconds 0 newinstanceseconds 0 newinstanceminutes 0 newinstancehours 0 newinstancetick tick newinstancestart start newinstancestop stop newinstancereset reset return newinstancevoid main struct stopwatch s stopwatch new stopwatch printf initial dn stopwatchmilliseconds stopwatchstart stopwatch stopwatchtick stopwatch stopwatchtick stopwatch stopwatchtick stopwatch printf started dn stopwatchmilliseconds stopwatchstop stopwatch stopwatchtick stopwatch printf stopped dn stopwatchmilliseconds stopwatchreset stopwatch printf reset dn stopwatchmilliseconds i have tried reading and following object oriented programming with ansic but cannot wrap my head around how to structure my object so instead of stopwatchtickstopwatchi can writestopwatchtick,['c'] +974815,split an string value i have a string value 12233 i want to split this string and separate it to 3 different valueval 1 1val 2 22 val 3 33i searched a lot its possible with characters like or other symbolssomething else my number is always different so i cant split it by enter the exact stringi want to do something like thisvar myval 12233var lastval myvalsplit0 3 split from index 0 till index 3how i can do itthanks,['javascript'] +974919,cannot build signed android package through visual studio cordova i am trying to build a signed release package for my android application using visual studio 2015 cordova toolsi am using cordova 511 which requires that i supply the build process with a buildjson file telling the application where the keystore are and what password is usinghowever when i add the buildjson file i am not able to make a successful build to releasei followed this guide and got this error with path edited out1 android homecprogram files x86androidandroidsdk taskid1 java homecprogram files x86javajdk170 55 taskid1 buildjson taskid1 reading build config file buildjson taskid1 platformsandroidcordovanode modulesqqjs126 taskid1 throw e taskid1 taskid1 syntaxerror unexpected token i taskid1 at objectparse native taskid1 at parseopts platformsandroidcordovalibbuildjs47527 taskid1 at objectmoduleexportsrun platformsandroidcordovalibbuildjs52916 taskid1 at platformsandroidcordovabuild3622 taskid1 at fulfilled platformsandroidcordovanode modulesqqjs79854 taskid1 at selfpromisethispatchdone platformsandroidcordovanode modulesqqjs82730 taskid1 at promisepromisepromisethispatch platformsandroidcordovanode modulesqqjs76013 taskid1 at platformsandroidcordovanode modulesqqjs574 taskid1 at flush platformsandroidcordovanode modulesqqjs10817 taskid1 at process tickcallback nodejs35511 taskid1 command finished with error code 1 cmd s c platformsandroidcordovabuildbat release buildconfigbuildjson taskid1error building one of the platforms error cmd command failed with exit code 11 you may not have the required environment or os to build this project taskid1mdavscli error cmd command failed with exit code 11done executing task mdavscli failed taskid11what am i doing wrong it seems like it cant parse the json,['android'] +975037,alamofire invalid value around character 0 alamofirerequestget urlauthenticateuser password responsejson request response json error in printlnerror printlnjsonthis is my request with alamofire for a certain request it sometime works but sometimes i getoptionalerror domainnscocoaerrordomain code3840 the operation couldnat be completed cocoa error 3840 invalid value around character 0 userinfo0x78e74b80 nsdebugdescriptioninvalid value around character 0i have read that this can be due to invalid json but the response is a static json string that i have validated in json validator as valid it does contain a a a characters and some htmlwhy am i getting this error sometimes,['ios'] +975052,java 8 convert file name array to file array i have an array of string file names and i want to convert them into file array i am wandering whether there is a more elegant way of doing it rather than this onestring names file1 file2 file3file files new stringnameslengthfor int i 0 i nameslength i filesi new filenamesi editthanks for noting in comments i am using java 8,['java'] +975401,run async code before entire mocha test i am looking for a way to run async code before the entire mocha testheres an example of a test that uses an array of arguments expectations and loops over all of the items in this array to produce function assertionsvar assert requireassert global describe itvar fn function value return value pancakevar tests arg kitty expect kitty pancake arg doggy expect doggy pancake describeexample function testsforeachfunction test itshould return testexpect function var value fntestarg assertequalvalue testexpect now my question is how would this work if the tests value came from a promise like thisvar assert requireassertvar promise requirebluebird global describe itvar fn function value return value pancakefunction gettests return promiseresolvekitty pancake delay500 thenfunction value return arg kitty expect value arg doggy expect doggy pancake getteststhenfunction tests describeexample function testsforeachfunction test itshould return testexpect function var value fntestarg assertequalvalue testexpect also trieddescribeexample function getteststhenfunction tests testsforeachfunction test itshould return testexpect function var value fntestarg assertequalvalue testexpect however in this example none of the tests run because mocha does not recognize the describe statement because it is within a promisebefore beforeeach would not do anything to help with a test in the format anyway unless the was a beforetest hook that would supply mocha with the knowledge that there is an async operation that needs to be run before the entire test,['javascript'] +975620,no realize class procedure defined i just want to share how i found the solution to the errorno realize class procedure definedwhen running a xmotif c application i am posting this because i only found one reference to this problem while searching online and it contained no solutions i managed to solve the problem and wanted to share my findings if you do come across this problem again notice i am not saying my solution will always solve this type of errorproblemi found this problem while running a simple c program that used the motif and x intrinsics toolkits gcc wall c pushc gcc wall o push pusho lxt lxm pusherror no realize class procedure definedthe c source code was the followinginclude stdiohinclude xmxmhinclude xmpushbh prototype callback function void pushed fnwidget xtpointer xmpushbuttoncallbackstruct int mainint argc char argv widget top wid button xtappcontext app thisplay thisplay xttoolkitinitialize app xtcreateapplicationcontext thisplay xtopenthisplayapp localhost100pushpush null0 argcargv top wid xtappcreateshellnull form applicationshellwidgetclass thisplay null 0 button xmcreatepushbuttontop wid push me null 0 tell xt to manage button xtmanagechildbutton attach fn to widget xtaddcallbackbutton xmnactivatecallback xtcallbackproc pushed fn null xtrealizewidgettop wid thisplay widget hierarchy xtappmainloopapp enter processing loop return 0void pushed fnwidget w xtpointer client data xmpushbuttoncallbackstruct cbs printfdo not push men,['c'] +975803,how can we workaround the blank title in pagertitlestrip and pagertabstrip there is an issue with pagertitlestrip and pagertabstrip with supportv4 version 2300the title views of a viewpager when using pagertitlestrip or pagertabstrip and the version 2300 for marshmallowandroid 60 support of the supportv4 library does not render correctlyissue is tracked and scheduled for future release onupdate this have now been resolved in 2310,['android'] +975911,why is this generator expression function slower than the loop version i have been operating under the theory that generator expressions tend to be more efficient than normal loops but then i ran into the following example write a function which given a number n and some factors ps returns the sum of all the numbers under n that are a multiple of at least one factorhere is a loop version and a shorter generator expression versiondef loopsn ps total sum 0 for i in xrangen for p in ps if ip 0 total sum i break return total sumdef genexpn ps return sumi for i in xrangen if anyip 0 for p in psi would expect the two to perform roughly equal with maybe the comprehension version a little faster but what i did not expect was thisfor func in loops genexp print func timeittimeits10 357 func number100 setupfrom main import s funcloops 282878184319genexp 1016631007194x slower is not even close why what am i misunderstanding,['python'] +975997,lodash foreach with function i am trying to use the lodash foreach method with a nested function that calls a mongo database var jobs foreachids functionid jobrequestfindbyjobidid functionerr result iferr callbackerr jobspushresult callbacknull jobsi am having problems because the foreach and callbacks will run through before the inner function is ever called how can i resolve thisi want the callback to be called after the for each and inner function have completed,['javascript'] +976049,android release build failing due to shrinkreleasemultidexcomponents i am having real difficulties building a release version of my appthis is part of the output i get when running gradlew assemblerelease stacktrace debugin android studio it spits out the same thing and i have crawled the net but have not found a solution for this175741664 info orggradleapiinternaltasksexecutionskipuptodatetaskexecuter executing task appshrinkreleasemultidexcomponents uptodate check took 02 secs due to no history is available175741665 debug orggradleapiinternaltasksexecutionexecuteactionstaskexecuter executing actions for task appshrinkreleasemultidexcomponents175741717 info systemout proguard version 521175741745 debug orggradleapiinternaltasksexecutionexecuteatmostoncetaskexecuter finished executing task appshrinkreleasemultidexcomponents175741745 lifecycle class orggradletaskexecutionlogger appshrinkreleasemultidexcomponents failed175741746 info orggradleexecutiontaskgraphabstracttaskplanexecutor appshrinkreleasemultidexcomponents threadmain5main completed took 0091 secs175741747 debug orggradleexecutiontaskgraphabstracttaskplanexecutor task worker threadmain5main finished busy 8329 secs idle 0049 secs175741771 error orggradlebuildexceptionreporter 175741774 error orggradlebuildexceptionreporter failure build failed with an exception175741774 error orggradlebuildexceptionreporter 175741775 error orggradlebuildexceptionreporter what went wrong175741775 error orggradlebuildexceptionreporter execution failed for task appshrinkreleasemultidexcomponents175741782 error orggradlebuildexceptionreporter javaioioexception the output jar usersjacobdocumentsmyappappbuildintermediatesmultidexreleasecomponentclassesjar must be specified after an input jar or it will be empty175741783 error orggradlebuildexceptionreporter 175741795 error orggradlebuildexceptionreporter exception is175741797 error orggradlebuildexceptionreporter orggradleapitaskstaskexecutionexception execution failed for task appshrinkreleasemultidexcomponents175741797 error orggradlebuildexceptionreporter at orggradleapiinternaltasksexecutionexecuteactionstaskexecuterexecuteactionsexecuteactionstaskexecuterjava69175741797 error orggradlebuildexceptionreporter at orggradleapiinternaltasksexecutionexecuteactionstaskexecuterexecuteexecuteactionstaskexecuterjava46175741798 error orggradlebuildexceptionreporter at orggradleapiinternaltasksexecutionpostexecutionanalysistaskexecuterexecutepostexecutionanalysistaskexecuterjava35175741798 error orggradlebuildexceptionreporter at orggradleapiinternaltasksexecutionskipuptodatetaskexecuterexecuteskipuptodatetaskexecuterjava64175741798 error orggradlebuildexceptionreporter at orggradleapiinternaltasksexecutionvalidatingtaskexecuterexecutevalidatingtaskexecuterjava58175741799 error orggradlebuildexceptionreporter at orggradleapiinternaltasksexecutionskipemptysourcefilestaskexecuterexecuteskipemptysourcefilestaskexecuterjava42175741799 error orggradlebuildexceptionreporter at orggradleapiinternaltasksexecutionskiptaskwithnoactionsexecuterexecuteskiptaskwithnoactionsexecuterjava52175741799 error orggradlebuildexceptionreporter at orggradleapiinternaltasksexecutionskiponlyiftaskexecuterexecuteskiponlyiftaskexecuterjava53175741799 error orggradlebuildexceptionreporter at orggradleapiinternaltasksexecutionexecuteatmostoncetaskexecuterexecuteexecuteatmostoncetaskexecuterjava43175741800 error orggradlebuildexceptionreporter at orggradleapiinternalabstracttaskexecutewithoutthrowingtaskfailureabstracttaskjava305175741800 error orggradlebuildexceptionreporter at orggradleexecutiontaskgraphabstracttaskplanexecutortaskexecutorworkerexecutetaskabstracttaskplanexecutorjava79175741800 error orggradlebuildexceptionreporter at orggradleexecutiontaskgraphabstracttaskplanexecutortaskexecutorworkerprocesstaskabstracttaskplanexecutorjava63175741800 error orggradlebuildexceptionreporter at orggradleexecutiontaskgraphabstracttaskplanexecutortaskexecutorworkerrunabstracttaskplanexecutorjava51175741800 error orggradlebuildexceptionreporter at orggradleexecutiontaskgraphdefaulttaskplanexecutorprocessdefaulttaskplanexecutorjava23175741801 error orggradlebuildexceptionreporter at orggradleexecutiontaskgraphdefaulttaskgraphexecuterexecutedefaulttaskgraphexecuterjava88175741801 error orggradlebuildexceptionreporter at orggradleexecutionselectedtaskexecutionactionexecuteselectedtaskexecutionactionjava29175741801 error orggradlebuildexceptionreporter at orggradleexecutiondefaultbuildexecuterexecutedefaultbuildexecuterjava62175741801 error orggradlebuildexceptionreporter at orggradleexecutiondefaultbuildexecuteraccess200defaultbuildexecuterjava23175741802 error orggradlebuildexceptionreporter at orggradleexecutiondefaultbuildexecuter2proceeddefaultbuildexecuterjava68175741802 error orggradlebuildexceptionreporter at orggradleexecutiondryrunbuildexecutionactionexecutedryrunbuildexecutionactionjava32175741802 error orggradlebuildexceptionreporter at orggradleexecutiondefaultbuildexecuterexecutedefaultbuildexecuterjava62175741802 error orggradlebuildexceptionreporter at orggradleexecutiondefaultbuildexecuterexecutedefaultbuildexecuterjava55175741802 error orggradlebuildexceptionreporter at orggradleinitializationdefaultgradlelauncherdobuildstagesdefaultgradlelauncherjava149175741803 error orggradlebuildexceptionreporter at orggradleinitializationdefaultgradlelauncherdobuilddefaultgradlelauncherjava106175741803 error orggradlebuildexceptionreporter at orggradleinitializationdefaultgradlelauncherrundefaultgradlelauncherjava86175741803 error orggradlebuildexceptionreporter at orggradlelauncherexecinprocessbuildactionexecuterdefaultbuildcontrollerruninprocessbuildactionexecuterjava80175741804 error orggradlebuildexceptionreporter at orggradlelaunchercliexecutebuildactionrunexecutebuildactionjava33175741804 error orggradlebuildexceptionreporter at orggradlelaunchercliexecutebuildactionrunexecutebuildactionjava24175741804 error orggradlebuildexceptionreporter at orggradlelauncherexecinprocessbuildactionexecuterexecuteinprocessbuildactionexecuterjava36175741804 error orggradlebuildexceptionreporter at orggradlelauncherexecinprocessbuildactionexecuterexecuteinprocessbuildactionexecuterjava26175741805 error orggradlebuildexceptionreporter at orggradlelauncherclirunbuildactionrunrunbuildactionjava51175741807 error orggradlebuildexceptionreporter at orggradleinternalactionsrunnableactionadapterexecuteactionsjava171175741807 error orggradlebuildexceptionreporter at orggradlelauncherclicommandlineactionfactoryparseandbuildactionexecutecommandlineactionfactoryjava237175741809 error orggradlebuildexceptionreporter at orggradlelauncherclicommandlineactionfactoryparseandbuildactionexecutecommandlineactionfactoryjava210175741810 error orggradlebuildexceptionreporter at orggradlelauncherclijavaruntimevalidationactionexecutejavaruntimevalidationactionjava35175741810 error orggradlebuildexceptionreporter at orggradlelauncherclijavaruntimevalidationactionexecutejavaruntimevalidationactionjava24175741811 error orggradlebuildexceptionreporter at orggradlelauncherclicommandlineactionfactorywithloggingexecutecommandlineactionfactoryjava206175741812 error orggradlebuildexceptionreporter at orggradlelauncherclicommandlineactionfactorywithloggingexecutecommandlineactionfactoryjava169175741813 error orggradlebuildexceptionreporter at orggradlelaunchercliexceptionreportingactionexecuteexceptionreportingactionjava33175741814 error orggradlebuildexceptionreporter at orggradlelaunchercliexceptionreportingactionexecuteexceptionreportingactionjava22175741814 error orggradlebuildexceptionreporter at orggradlelaunchermaindoactionmainjava33175741815 error orggradlebuildexceptionreporter at orggradlelauncherbootstrapentrypointrunentrypointjava45175741815 error orggradlebuildexceptionreporter at orggradlelauncherbootstrapprocessbootstraprunnoexitprocessbootstrapjava54175741816 error orggradlebuildexceptionreporter at orggradlelauncherbootstrapprocessbootstraprunprocessbootstrapjava35175741816 error orggradlebuildexceptionreporter at orggradlelaunchergradlemainmaingradlemainjava23175741817 error orggradlebuildexceptionreporter at orggradlewrapperbootstrapmainstarterstartbootstrapmainstarterjava33175741818 error orggradlebuildexceptionreporter at orggradlewrapperwrapperexecutorexecutewrapperexecutorjava130175741819 error orggradlebuildexceptionreporter at orggradlewrappergradlewrappermainmaingradlewrappermainjava48175741819 error orggradlebuildexceptionreporter caused by orggradleinternaluncheckedexception javaioioexception the output jar usersjacobdocumentsmyappappbuildintermediatesmultidexreleasecomponentclassesjar must be specified after an input jar or it will be empty175741819 error orggradlebuildexceptionreporter at orggradleinternaluncheckedexceptionthrowasuncheckedexceptionuncheckedexceptionjava39175741819 error orggradlebuildexceptionreporter at orggradleinternalreflectjavamethodinvokejavamethodjava66175741820 error orggradlebuildexceptionreporter at orggradleapiinternalprojecttaskfactoryannotationprocessingtaskfactorystandardtaskactiondoexecuteannotationprocessingtaskfactoryjava218175741820 error orggradlebuildexceptionreporter at orggradleapiinternalprojecttaskfactoryannotationprocessingtaskfactorystandardtaskactionexecuteannotationprocessingtaskfactoryjava2175741820 error orggradlebuildexceptionreporter at orggradleapiinternalprojecttaskfactoryannotationprocessingtaskfactorystandardtaskactionexecuteannotationprocessingtaskfactoryjava200175741820 error orggradlebuildexceptionreporter at orggradleapiinternalabstracttasktaskactionwrapperexecuteabstracttaskjava579175741821 error orggradlebuildexceptionreporter at orggradleapiinternalabstracttasktaskactionwrapperexecuteabstracttaskjava562175741821 error orggradlebuildexceptionreporter at orggradleapiinternaltasksexecutionexecuteactionstaskexecuterexecuteactionexecuteactionstaskexecuterjava80175741821 error orggradlebuildexceptionreporter at orggradleapiinternaltasksexecutionexecuteactionstaskexecuterexecuteactionsexecuteactionstaskexecuterjava61175741821 error orggradlebuildexceptionreporter 47 more175741821 error orggradlebuildexceptionreporter caused by javaioioexception the output jar usersjacobdocumentsmyappappbuildintermediatesmultidexreleasecomponentclassesjar must be specified after an input jar or it will be empty175741822 error orggradlebuildexceptionreporter at proguardconfigurationcheckercheckconfigurationcheckerjava64175741822 error orggradlebuildexceptionreporter at proguardproguardexecuteproguardjava73175741822 error orggradlebuildexceptionreporter at proguardgradleproguardtaskproguardproguardtaskjava1074175741822 error orggradlebuildexceptionreporter at orggradleinternalreflectjavamethodinvokejavamethodjava63175741822 error orggradlebuildexceptionreporter 54 more175741823 error orggradlebuildexceptionreporter 175741823 lifecycle orggradlebuildresultlogger 175741823 lifecycle orggradlebuildresultlogger build failed175741823 lifecycle orggradlebuildresultlogger 175741823 lifecycle orggradlebuildresultlogger total time 25463 secsthis is my configbuildscript repositories maven url dependencies classpath iofabrictoolsgradle1 apply plugin comandroidapplicationapply plugin iofabricrepositories maven url android compilesdkversion 23 buildtoolsversion 2301 defaultconfig applicationid commyapp minsdkversion 16 targetsdkversion 23 versioncode 9 versionname 093 multidexenabled true packagingoptions exclude metainfnotice exclude metainfdependenciestxt exclude metainflicensetxt exclude metainfnoticetxt exclude metainfnotice exclude metainflicense exclude metainfdependencies exclude metainfnoticetxt exclude metainflicensetxt exclude metainfdependenciestxt exclude metainflgpl21 uselibrary orgapachehttplegacy buildtypes release minifyenabled true proguardfiles getdefaultproguardfileproguardandroidtxt proguardandroidoptimizetxt dependencies compile fileslibsorgapachehttplegacyjar compile orgapachehttpcomponentshttpclientandroid435 compileorgapachehttpcomponentshttpmime435 exclude module orgapachehttpcomponentshttpclient compile comandroidsupportappcompatv72301 compile comgoogleandroidgmsplayservices750 compile commixpanelandroidmixpanelandroid462 compile comandroidsupportrecyclerviewv72301 compile comfacebookandroidfacebookandroidsdk410 compile comsoundcloudandroidandroidcrop100aar compile comandroidsupportsupportv42301 compilecomcrashlyticssdkandroidcrashlytics251aar transitive true thanks in advance,['android'] +976238,mouse hover using jquery keeps bouncing i am trying to make a show content on mouseover and make it stay visible while the mouse is hovered on the list since i am planning to put a button there but when i do hover hidden content kept bouncing for some reasonjquery codeliemployersmouseoverfunction employer contentshowslow thisaddclassbluehoverliemployersmouseoutfunction employer contenthidefast thisremoveclassbluehoverhtmlli classemployers divemployerdiv div classemployer contentsome contentdivlili classcourt divcourtdiv div classcourt contentsome contentdivli,"['javascript', 'jquery', 'html', 'css']" +976253,why is onattach activity activity deprecated after updating the sdk to api level 23 i found that onattach activity activity is deprecated and the new method is onattach context context can any one enlighten me on why this change was made,['android'] +976392,socket shutdown when should i use socketshutdownboth i believe the shutdown sequence is as follows as described herethe msdn documentation remarks section readswhen using a connectionoriented socket always call the shutdown method before closing the socket this ensures that all data is sent and received on the connected socket before it is closedthis seems to imply that if i use shutdownsocketshutdownboth any data that has not yet been received may still be consumed to test thisi continuously send data to the client via send in a separate threadthe client executed shutdownsocketshutdownboththe beginreceive callback on the server executes however endreceive throws an exception an existing connection was forcibly closed by the remote host this means that i am unable to receive the 0 return value and in turn call shutdownas requested i have posted the server side code below it is wrapped in a windows form and it was created just as an experiment in my test scenario i did not see the close wait state in tcpview as i normally did without sending the continuous data so potentially i have done something wrong and i am interrupting the consequences incorrectly in another experimentclient connects to serverclient executes shutdownsocketshutdownbothserver receives shutdown acknowledgement and sends some data in response server also executes shutdownclient receives data from server but the next beginreceive is not allowed a request to send or receive data was thisallowed because the socket had already been shut down in that direction with a previous shutdown callin this scenario i was still expecting a 0 return value from endreceive to close the socket does this mean that i should use shutdownsocketshutdownsend instead if so when should one use shutdownsocketshutdownbothcode from first experimentprivate tcplistener socketlistener get set private socket connectedclient get set private bool servershutdownrequestedprivate object shutdownlock new objectprivate struct socketstate public socket socket public byte bytesprivate void processincomingiasyncresult ar var state socketstatearasyncstate exception thrown here when client executes shutdown var dataread statesocketendreceivear if dataread 0 statesocketbeginreceivestatebytes 0 statebyteslength socketflagsnone processincoming state else lock shutdownlock servershutdownrequested true statesocketshutdownsocketshutdownboth statesocketclose statesocketthispose private void spam int i 0 while true lock shutdownlock if servershutdownrequested try connectedclientsendencodingdefaultgetbytesitostring catch break i else break private void listen while true connectedclient socketlisteneracceptsocket var data new socketstate databytes new byte1024 datasocket connectedclient connectedclientbeginreceivedatabytes 0 databyteslength socketflagsnone processincoming data servershutdownrequested false new threadspamstart public serverform initializecomponent var hostentry dnsgethostentrylocalhost var endpoint new ipendpointhostentryaddresslist0 110 socketlistener new tcplistenerendpoint socketlistenerstart new threadlistenstart,"['c#', '.net']" +976400,how to test if json path does not include a specific element or if the element is present it is null i have been writing some simple unit testing routines for a simple spring web application when i add jsonignore annotation on a getter method of a resource the resulting json object does not include the corresponding json element so when my unit test routine tries to test if this is null which is the expected behavior for my case i do not want the password to be available in json object test routine runs into an exceptionjavalangassertionerror no value for json path password exception no results for path passwordthis is the unit test method i wrote testing the password field with isnullvalue methodtestpublic void getuserthatexists throws exception user user new user usersetid1l usersetusernamezobayer usersetpassword123456 whenuserservicegetuserbyid1lthenreturnuser mockmvcperformgetusers1 andexpectjsonpathusername isusergetusername andexpectjsonpathpassword isnullvalue andexpectjsonpathlinkshref hasitemendswithusers1 andexpectstatusisok anddoprinti have also tried it with jsonpathexists which gets similar exception stating that the path does not exist i am sharing some more code snippets so that the whole situation becomes more readablethe controller method i am testing looks something like thisrequestmappingvalueusersuserid method requestmethodgetpublic responseentityuserresource getuserpathvariable long userid loggerinforequest arrived for getuser with params userid user user userservicegetuserbyiduserid ifuser null userresource userresource new userresourceasmtoresourceuser return new responseentityuserresource httpstatusok else return new responseentityhttpstatusnot found i am using spring hateos resource assembler for converting entity to resource objects and this is my resource classpublic class userresource extends resourcesupport private long userid private string username private string password public long getuserid return userid public void setuseridlong userid thisuserid userid public string getusername return username public void setusernamestring username thisusername username jsonignore public string getpassword return password public void setpasswordstring password thispassword password i understand why this is getting an exception also in a way the test is successful that it could not find the password field but what i want to do is run this test to ensure that the field is not present or if present it contains null value how can i achieve thisthere is a similar post in stack overflowhamcrest with mockmvc check that key exists but value may be nullin my case the field may be non existent as wellfor the record these are the versions of test packages i am using dependency groupidcomfasterxmljacksoncoregroupid artifactidjacksoncoreartifactid version261version dependency dependency groupidcomfasterxmljacksoncoregroupid artifactidjacksonannotationsartifactid version261version dependency dependency groupidcomfasterxmljacksoncoregroupid artifactidjacksondatabindartifactid version261version dependency dependency groupidcomjaywayjsonpathgroupid artifactidjsonpathartifactid version200version scopetestscope dependency dependency groupidcomjaywayjsonpathgroupid artifactidjsonpathassertartifactid version200version scopetestscope dependency dependency groupidjunitgroupid artifactidjunitartifactid version412version scopetestscope dependency dependency groupidorgmockitogroupid artifactidmockitoallartifactid version11019version scopetestscope dependencythanks in advanceeditto be more precise say you have to write a test for an entity where you know some of the fields need to be null or empty or should not even exists and you do not actually go through the code to see if there is a jsonignore added on top of the property and you want your tests to pass how can i do thisplease feel free to tell me that this is not practical at all but still would be nice to knoweditthe above test succeeds with the following older jsonpath dependencies dependency groupidcomjaywayjsonpathgroupid artifactidjsonpathartifactid version091version scopetestscope dependency dependency groupidcomjaywayjsonpathgroupid artifactidjsonpathassertartifactid version091version scopetestscope dependencyedit found a quickfix that works with latest version of jaywayjasonpath after reading the documentation of springs json path matcherandexpectjsonpathpassworddoesnotexist,['java'] +976413,passport allow sign up with name and email address local strategy is there any way to allow a user to register on the local strategy with his password email and nameevery example i could find online only use namepassword or emailpassword i also searched through the the whole passport documentation but that documentation is not helpful at all it is just one bloated site full of examplesi just need an list of functions classes and variables passport uses with explanations what they and every parameter of them do every good library has something like that why cannot i find it for passporthere are the key parts of my codepassportuselocalsignup new localstrategy usernamefield email passwordfield password are there other options emailfield did not seem to do anything passreqtocallback true allows us to pass in the req from our route lets us check if a user is logged in or notfunctionreq email password done check if email not already in database create new user using email and password i want an additional parameter here nameso is passport really that limited there has to be a way to do this right,['javascript'] +976427,toolbar in appbarlayout is scrollable although recyclerview has not enough content to scroll is it really intended that the toolbar in a appbarlayout is scrollable although the main container with the appbar scrolling view behavior has not enough content to really scrollwhat i have tested so farwhen i use a nestedscrollview with wrap content attribute as main container and a textview as child the appbarlayout works properly and does not scrollhowever when i use a recyclerview with only a few entries and the wrap content attribute so that there is no need to scroll the toolbar in the appbarlayout is scrollable even though the recyclerview never receives a scroll event tested with a onscrollchangelistenerheres my layout codeandroidsupportdesignwidgetcoordinatorlayout xmlnsandroid xmlnsapp androidididcoordinatorlayout androidlayout widthmatch parent androidlayout heightmatch parent androidsupportdesignwidgetappbarlayout androidididappbarlayout androidlayout widthmatch parent androidlayout heightwrap content androidsupportv7widgettoolbar androidididtoolbar androidlayout widthmatch parent androidlayout heightattractionbarsize androidbackgroundattrcolorprimary applayout scrollflagsscrollenteralways appthemestyletoolbarstyle androidsupportdesignwidgetappbarlayout androidsupportv7widgetrecyclerview androidididrecycler androidlayout widthwrap content androidlayout heightwrap content applayout behaviorstringappbar scrolling view behavior androidsupportdesignwidgetcoordinatorlayoutwith the following effect that the toolbar is scrollable although it is not necessaryi have also found a way to deal with this by checking if all recyclerview items are visible and using the setnestedscrollingenabled method of the recyclerviewnevertheless it does seem more like a bug as intended to me any opinions dedit 1for people who are might be interested in my current solution i had to put the setnestedscrollingenabled logic in the postdelayed method of a handler with 5 ms delay due to the layoutmanager which always returned 1 when calling the methods to find out whether the first and the last item is visiblei use this code in the onstart method after my recyclerview has been initialized and every time after a content change of the recyclerview occursfinal linearlayoutmanager layoutmanager linearlayoutmanager mrecyclerviewgetlayoutmanagernew handlerpostdelayednew runnable override public void run no items in the recyclerview if mrecyclerviewgetadaptergetitemcount 0 mrecyclerviewsetnestedscrollingenabledfalse if the first and the last item is visible else if layoutmanagerfindfirstcompletelyvisibleitemposition 0 layoutmanagerfindlastcompletelyvisibleitemposition mrecyclerviewgetadaptergetitemcount 1 mrecyclerviewsetnestedscrollingenabledfalse else mrecyclerviewsetnestedscrollingenabledtrue 5edit 2i just played around with a new app and it seems that this unintended behavior has been fixed in support library version 2330 or even earlier thus there is no need for workarounds anymore,['android'] +976441,rails clockwork not running code i am using the gem clockwork in a rails 32 app the app is running on heroku the clock job runs at 1am but it is not executing the codehere is the clockrb code clockworkevery1day dailyjob at 0100 statsmailerstats emaildeliver forecastwhererun date datetodayeach do forecast woschedules run jobplans pathid forecastwoschedule id end the log showssep 04 05 ndeavorstaging appclock1 nomethoderror undefined method woschedules run jobplans path for clockworkmoduleif i rake routes i getwoschedules run jobplans get woschedulesrun jobplansformat woschedulesrun jobplans,"['ruby-on-rails', 'ruby']" +976466,default arguments as nonstatic member variables i want to create a class which has two integer member variables and a function which has two optional arguments if these arguments are supplied the function returns the sum of them if these arguments are not supplied the function returns the sum of its two member variableshere is the codeclass fooprivate int x int y public fooint x int y x x y y int barint a x int b y int z a b return z however i get the following compilation errorinvalid use of nonstatic data member foox int x invalid use of nonstatic data member fooy int y this suggests that the member variables have to be static to use them in as default arguments in a function but i do not want them to be staticwhat is the solution,['c++'] +976527,data bindings with custom listeners on custom view i am trying to bind an event on a custom view with the new android databinding library but run into an issueheres the relevant part of my custom viewpublic class supercustomview extends framelayout private ontogglelistener mtogglelistener public interface ontogglelistener void ontoggleboolean switchposition public void setontogglelistenerontogglelistener listener mtogglelistener listener i am trying to use this custom view and bind the ontoggle event with the followingdata variable namecontroller typecomxblopcontrollerdatacomcompanyviewssupercustomview androidlayout widthmatch parent androidlayout heightwrap content appontogglecontrollertogglestrokelimitation appcustom titleblah appcustom summarybloh appcustom widgettogglewhere togglestrokelimitation is a method on the controllerpublic void togglestrokelimitationboolean switchposition maxstrokeenabledsetswitchpositioni get this error when compiling javalangruntimeexception found data binding errors data binding error msgcannot find the setter for attribute appontoggle with parameter type javalangobject filepathtoandroidappappsrcmainreslayoutfragment strokexml loc3635 3667 data binding error i have tried to use androidontoggle instead of appontoggle but get the same errorwhen reading the binding events section of the doc i feel like i can wire any method off the controller to the ontoggle eventdoes the framework wrap the controllertogglestrokelimitation methods into a supercustomviewontogglelistener any hint on the kind of magic that is behind the existing onclick provided by the framework,['android'] +976644,how to make backgroundimage scroll continuously horizontally without a break in animation i am trying to make a banner that scrolls sideways infinitely with css3 animation the problem is that after the animation is over it has a harsh cut when it is restarting i am trying to figure out how to prevent that harsh animationi have put my code here keyframes slideleft frombackgroundposition rightto backgroundposition leftwebkitkeyframes slideleft frombackgroundposition rightto backgroundposition leftmasthead backgroundimage urlanimation slideleft 5s infinite easeinoutwebkitanimation slideleft 5s infinite easeinoutwidth 100height 1200pxdiv idmastheaddiv,"['html', 'css']" +976689,memory leak detected in chrome custom tabs i am attempting to implement chrome custom tabs and detecting a memory leak through leakcanarythe demo application does not appear to leak unless we add another activity layer ie mainactivity launches activity2 which bindsunbinds to the custom tab service and launches the url everything the mainactivity does in the demo app mainactivity looks like thispublic class mainactivity extends activity implements onclicklistener private button mlaunchbutton override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate leakcanaryinstallgetapplication setcontentviewrlayoutmain mlaunchbutton button findviewbyidridlaunch button mlaunchbuttonsetonclicklistenerthis override public void onclickview v int viewid vgetid if viewid ridlaunch button intent intent new intentgetapplicationcontext activity2class startactivityintent returning from activity2 to mainactivity will cause this leak0904 134926783 1045612161orgchromiumcustomtabsclientexample dleakcanaryi1 in orgchromiumcustomtabsclientexample1010904 134926783 1045612161orgchromiumcustomtabsclientexample dleakcanaryi1 orgchromiumcustomtabsclientactivity2 has leaked0904 134926783 1045612161orgchromiumcustomtabsclientexample dleakcanaryi1 gc root androidsupportcustomtabscustomtabsclient1valcallback anonymous class extends androidsupportcustomtabsicustomtabscallbackstub0904 134926783 1045612161orgchromiumcustomtabsclientexample dleakcanaryi1 references orgchromiumcustomtabsclientactivity22this0 anonymous class extends androidsupportcustomtabscustomtabscallback0904 134926783 1045612161orgchromiumcustomtabsclientexample dleakcanaryi1 leaks orgchromiumcustomtabsclientactivity2 instancemy question is is this a bug in the demo application maybe unbindcustomtabsservice is missing some needed teardown or is this a bug in the chrome custom tabs library itselfthank you,['android'] +976706,using a generic swift class in objectivec let us say i define a generic class in swift similar to the followingclass myarrayt func addobjectobject t do something hopefully i know there is a slightly better implementation of array this is merely an examplein swift i can now use this class very easilylet a myarraystringaaddobjectabcwith xcode 7 we now have generics in objectivec so i would assume that i could use this class in objectivecmyarraynsstring a myarraynsstring alloc inita addobjectabchowever myarray is never added to my projectswifth file even if i change it to inherit from nsobject it still does not appear in my swifth fileis there any way to create a generic swift class and then use it in objectivecupdate if i try to inherit from nsobject and annotate with objcobjcmyarrayclass myarrayt nsobject func addobjectobject t do something hopefully i get the following compiler errorgeneric subclasses of objc classes cannot have an explicit objc attribute because they are not directly visible from objectivecdoes this mean there is no way to use a generic swift class in objectivec how does one indirectly reference the class,"['ios', 'objective-c']" +976823,run unit tests on save with android studio has anyone managed to make a reasonably comfortable setup for their project where unit tests run on every savei currently have a split project an android application project and a java project that the android application depends upon i write unit tests for the java project and run them manually every now and thenin my understanding to make this happen as expected i also want to have incremental builds for the java project i am not sure that this is feasibly possible while using gradle with its current state of affairs,"['java', 'android']" +976825,this jmh benchmark is inconsistent across machines why i am trying to write a method like thisstatic boolean fitsindoublelong x return true if x can be represented as a numericallyequivalent doubleand i am trying to find the most efficient implementation i settled on one but then a coworker ran the benchmarks and got different relative results the fastest implementation for me is not the fastest for himis there something wrong with these benchmarkspackage rndimport orgopenjdkjmhannotationsbenchmarkimport orgopenjdkjmhannotationsbenchmarkmodeimport orgopenjdkjmhannotationsforkimport orgopenjdkjmhannotationsmeasurementimport orgopenjdkjmhannotationsmodeimport orgopenjdkjmhannotationsoutputtimeunitimport orgopenjdkjmhannotationsscopeimport orgopenjdkjmhannotationsstateimport orgopenjdkjmhannotationswarmupimport orgopenjdkjmhinfrablackholeimport orgopenjdkjmhrunnerrunnerimport orgopenjdkjmhrunneroptionsoptionsimport orgopenjdkjmhrunneroptionsoptionsbuilderimport javamathbigdecimalimport javautilconcurrenttimeunitstatescopethreadbenchmarkmodemodeaveragetimeoutputtimeunittimeunitnanosecondsfork1measurementiterations 5warmupiterations 5public class benchmarks public static void mainstring args throws exception options options new optionsbuilder includebenchmarksclassgetname build new runneroptionsrun benchmark public void bigdecimalblackhole bh for long x numbers bhconsumebigdecimalx benchmark public void castblackhole bh for long x numbers bhconsumecastx benchmark public void zerosblackhole bh for long x numbers bhconsumezerosx public static boolean bigdecimallong x bigdecimal a new bigdecimalx bigdecimal b new bigdecimaldouble x return acomparetob 0 public static boolean castlong x return x long double x x longmax value public static boolean zeroslong x long a mathabsx int z longnumberofleadingzerosa return z 10 longnumberoftrailingzerosa 10 z private static final long numbers 0 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 123 456 789 123 456 789 1012 131415 161718 1012 131415 161718 11l 2l 3l 4l 5l 6l 7l 8l 9l 1l 2l 3l 4l 5l 6l 7l 8l 9l 1 2 3l 4l 5l 6l 7l 8l 9l longmax value longmax value 1 longmin value longmin value 1 1l 53 1l 53 1 1l 53 2 1l 60 1l 60 1 1l 60 8 1l 60 32 1l 60 64 1l 60 128 1l 60 256 1l 53 1l 53 1 1l 53 2 1l 60 1l 60 1 1l 60 8 1l 60 32 1l 60 64 1l 60 128 1l 60 256 there are small differences in our environmentsme windows 10 jdk 180 45 zeros is the fastesthim windows 7 jdk 180 20 cast is the fastestour results are selfconsistent from run to run whether running in an ide or from the command line were using jmh 1105what is happening here the benchmark seems untrustworthy and i do not know how to fix it,['java'] +976897,how is memory managed for nondeclared entities in the c language for example in the following code how and where is the number 10 used for the comparison storedincludestdiohincludeconiohint main int x 5 if x 10 printfx is greater than 10 else if x 10 printfx is lesser than 10 else printfx 10 getch return 0pardon me for not giving enough details instead of initializing x directly with 5 if we scan and get it from the user we know how memory is allocated for x but how memory is allocated for the literal number 10 which is not stored in any variable,['c'] +976907,assigning a string literal to stdstring i am aware that the following code will create an array of characters and remain in memory until the program endschar str this is a stringas for this statement creates a local array of characters and will be freed when str goes out of scopechar str this is a stringwhat i am curious is what happens when i write it like thisstdstring str this is a stringstr should make a copy of the string in it is own memory local but what about the string literal itself will it have the lifetime of the program or will it be freed when str goes out of scope,['c++'] +976917,how to change the default app icon in the facebook login authentication screen plain and simple i need to change the default app icon that is presented to the user when in the authentication screen when logging into the app using the facebook sdkwhat i have triedwdeveloperfacebookcom my apps app details iconsany help is appreciated thank you for your time,"['android', 'ios', 'iphone']" +977095,how to get reproducible results in keras i get different results test accuracy every time i run the imdb lstmpy example from keras framework lstmpythe code contains nprandomseed1337 in the top before any keras imports it should prevent it from generating different numbers for every run what am i missing update how to repro install keras execute lstmpy a few times it will train the model and output test accuracyexpected result test accuracy is the same on every runactual result test accuracy is different on every runupdate2 i am running it on windows 81 with mingwmsys module versionstheano 070numpy 181scipy 0140c1update3 i narrowed the problem down a bit if i run the example with gpu set theano flag devicegpu0 then i get different test accuracy every time but if i run it on cpu then everything works as expected my graphics card nvidia geforce gt 635,['python'] +977134,use recyclerview inside scrollview with flexible recycler item height i want to know is there any possible way to use recyclerviewbefore this i use recyclerview with fix height inside a scrollview but this time i do not know height of the item hint i read all question and solution of stack question before ask this question since 4 days agoupdate some solution learn how to scroll recyclerview on his own but i want to show this expanded,['android'] +977352,app transport security xcode 7 beta 6 i am currently working on xcode 7 beta 6 i am trying to send a delete request to the error i receive isapp transport security has blocked a cleartext http http resource load since it is insecure temporary exceptions can be configured via your apps infoplist file error making api call error domainnsurlerrordomain code1022 the resource could not be loaded because the app transport security policy requires the use of a secure connection nslocalizeddescriptionthe resource could not be loaded because the app transport security policy requires the use of a secure connection nsunderlyingerror0x796f7ef0 error domainkcferrordomaincfnetwork code1022 nullin my actual api call i put https instead of http and that actually worked for my post requests but the delete request throws the above errori have seen solutions on here that involve the plist file but none of them have worked for me i have listed my attempts belowfirst attemptkeynsapptransportsecuritykeydict keynsallowsarbitraryloadskey truedictsecond trykeynsapptransportsecuritykeydict keynsexceptiondomainskey dict keyherokuappcomkey dict keynsincludessubdomainskey true keynsexceptionallowsinsecurehttploadskey true keynsexceptionrequiresforwardsecrecykey false keynsexceptionminimumtlsversionkey stringtlsv12string keynsthirdpartyexceptionallowsinsecurehttploadskey true keynsthirdpartyexceptionrequiresforwardsecrecykey false keynsthirdpartyexceptionminimumtlsversionkey stringtlsv12string keynsrequirescertificatetransparencykey false dict dictdictand finally i even put all these temporary keys in like sokeynsapptransportsecuritykey dict keynsexceptiondomainskey dict keyherokuappcomkey dict keynsincludessubdomainskey true keynstemporaryincludessubdomainskey true keynsexceptionallowsinsecurehttploadskey true keynstemporaryexceptionallowsinsecurehttploadskey true keynsexceptionrequiresforwardsecrecykey false keynstemporaryexceptionrequiresforwardsecrecykey false keynsexceptionminimumtlsversionkey stringtlsv12string keynstemporaryexceptionminimumtlsversionkey stringtlsv12string keynsthirdpartyexceptionallowsinsecurehttploadskey true keynstemporarythirdpartyexceptionallowsinsecurehttploadskey true keynsthirdpartyexceptionrequiresforwardsecrecykey false keynstemporarythirdpartyexceptionrequiresforwardsecrecykey false keynsthirdpartyexceptionminimumtlsversionkey stringtlsv12string keynstemporarythirdpartyexceptionminimumtlsversionkey stringtlsv12string keynsrequirescertificatetransparencykey false keynstemporaryrequirescertificatetransparencykey false dict dict dictall with no luck i always get the same error the delete request is formatted correctly because when i manually do it from postman i get the desired result here is what my actual api call method looks like just in case there could be an issue hereclass func makedeleteallrequestcompletion errorbool void let session nsurlsessionsharedsession let url nsurlstring let request nsmutableurlrequesturl url requesthttpmethod delete let task sessiondatataskwithrequestrequest data response error void in if error nil printerror making api call error completionerror true else let httpresponse response as nshttpurlresponse let statuscode httpresponsestatuscode if statuscode 200 printsuccessfully deleted completionerror false else printdifferent status code statuscode completionerror true taskresume once again i am using xcode 7 beta 6 about my selected answerthe answer i selected as correct was right for me because i made all these changes to the wrong plist file in my project and that answer was the only one that addressed the possibility the solutions offered by the other answers are not wrong so any other people experiencing this issue should give them a try since they are valid i hope this helps anyone having similar issues,['ios'] +977372,html css automatically adjust height i am trying to thisplay outbound and inbound flight by visualising it using cssless the problem is that when outbound flight has more airport changes then inbound then line stays at the level of first flight i want line adjust height dynamically based on the longest route could you please help me to figure out how do achieve required resultsupdate prepared plunker example make a screen wider in order to see it properly this is what i have gotthis is what i am trying achivelesstimeslice position relative thisplay webkitbox thisplay webkitflex thisplay msflexbox thisplay flex webkitboxalign stretch webkitalignitems stretch msflexalign stretch alignitems stretch marginleft 20pxtimeslice padding 20pxcircle width 16px height 16px boxsizing contentbox bordercolor 29a8bb background f borderradius 32px thisplay block border 2px solid bluecirclewrap position absolute top 0px left 91px zindex 2circlewrap circle position relative left 20pxdatetime boxsizing contentbox webkitflexshrink 0 msflexnegative 0 flexshrink 0 webkitflexbasis 100px msflexpreferredsize 100px flexbasis 100px textalign center margintop 5pxdatetime maxwidth 90px color 9 fontsize 13px margintop 0px marginbottom 10px marginleft 20pxtimeslicerownotlastchild pointtitle borderleft 2px solid blue paddingleft 15px paddingtop 0 position relative top 20pxduration marginleft 50px maxwidth 90px color 9 fontsize 13px marginbottom 10pxstoptransit borderwidth 2px color red paddingleft 5px marginleft 20px marginbottom 10px tablelayout fixedstoptransit transitpath waittime paddingright 10px paddingleft 20pxtransitpath borderrightstyledotted width 140pxwaitreason textalign centersearchresult padding 0px 15pxhtmldiv idticketid stylethisplaynone div classcolmd6 line h3outboundh3 div ngrepeatdepartureflight in ticketroutedepartureflights div classtimeline div classtimeslice row div classdatetime p classdatedepartureflightdeparturetime date d mp p classtimedepartureflightdeparturetime datehmmap div div classcirclewrap div classcirclediv div div classpointtitle span bdepartureflightcityfrom departureflightflyfromb span div div div classtimeslice row div classdatetime p classtime durationdepartureflightarrivaltimedepartureflightdeparturetime datehmmhp div div classpointtitle div div div classtimeslice row div classdatetime p classdatedepartureflightarrivaltime date d mp p classtimedepartureflightarrivaltime datehmmap div div classcirclewrap div classcirclediv div div classpointtitle span bdepartureflightcityto departureflightflytob span div div div div ngifdepartureflighttransferflight table clastoptransit tr td classtransitpath div classwaitreasonconnection changebr long wait nbspspan classglyphicons glyphiconsairplaneaspandiv td td classwaittimedepartureflightdeparturetime datehmm hourstd tr table div div div div classcolmd6 h3inboundh3 div ngrepeatreturnflight in ticketroutereturnflights div classtimeline div classtimeslice row div classdatetime p classdatereturnflightdeparturetime date d mp p classtimereturnflightdeparturetime datehmmap div div classcirclewrap div classcirclediv div div classpointtitle span breturnflightcityfrom returnflightflyfromb span div div div classtimeslice row div classdatetime p classtime durationreturnflightarrivaltimereturnflightdeparturetime datehmmhp div div classpointtitle div div div classtimeslice row div classdatetime p classdatereturnflightarrivaltime date d mp p classtimereturnflightarrivaltime datehmmap div div classcirclewrap div classcirclediv div div classpointtitle span breturnflightcityto returnflightflytob span div div div div ngifreturnflighttransferflight table clastoptransit tr td classtransitpath div classwaitreasonconnection changebr long wait nbspspan classglyphicons glyphiconsairplaneaspandiv td td classwaittimereturnflightdeparturetime datehmm hourstd tr table div div div div,"['html', 'css']" +977385,uistackview unable to simultaneously satisfy constraints on squished hidden views when my uistackview rows are squished they throw autolayout warnings however they thisplay fine and nothing else is wrong besides these sorts of loggingsunable to simultaneously satisfy constraints probably at least one of the constraints in the following list is one you do not want try this 1 look at each constraint and try to figure out which you do not expect 2 find the code that added the unwanted constraint or constraints and fix it note if youre seeing nsautoresizingmasklayoutconstraints that you do not understand refer to the documentation for the uiview property translatesautoresizingmaskintoconstraints so i am not sure how to fix this yet but it does not seem to break anything besides just being annoyingdoes anyone know how to solve it interestingly the layout constraints are tagged quite often with uisvhiding indicating that perhaps it should ignore the height minimums for subviews or something in this instance,['ios'] +977402,status bar turns white and does not show content behind it i am trying out appcompat on marshmallow and i want to have a transparent status bar however it turns white i have tried a couple solutions but they did not work for me transparent status bar not working with windowtranslucentnavigationfalse lollipop draw behind statusbar with its color set to transparent heres related codemy stylesxml style namebacon parentthemebaconstyle namethemebacon parentthemeappcompatlightnoactionbar item namecolorprimarycolortheme primaryitem item namecolorprimarydarkcolortheme primary darkitem item namecoloraccentcolortheme accentitem item namewindowactionbarfalseitem item namewindowactionbaroverlaytrueitem item namewindownotitletrueitem item nameandroidwindowbackgroundcolorbackground material lightitem stylestyle namethemebacondetail parentbaconv21style namebacon parentthemebacon item nameandroidwindowdrawssystembarbackgroundstrueitemstylestyle namethemebacondetail parentbacon item nameandroidstatusbarcolorandroidcolortransparentitemstyleactivityframelayout xmlnsandroidandroidlayout widthmatch parentandroidlayout heightmatch parentandroidfitssystemwindowstrueandroidsupportv4viewviewpager androidididpager androidlayout widthmatch parent androidlayout heightmatch parent androidfitssystemwindowstrue framelayoutfragmentandroidsupportdesignwidgetcoordinatorlayout xmlnsandroidxmlnsappandroidlayout widthmatch parentandroidlayout heightmatch parentandroidfitssystemwindowstrueandroidsupportdesignwidgetappbarlayout androidididappbar androidlayout widthmatch parent androidlayout height192dp androidfitssystemwindowstrue androidthemestylethemeoverlayappcompatdarkactionbar androidsupportdesignwidgetcollapsingtoolbarlayout androidididcollapsing toolbar androidlayout widthmatch parent androidlayout heightmatch parent androidfitssystemwindowstrue appcontentscrimattrcolorprimary appexpandedtitlemarginbottom32dp appexpandedtitlemarginend64dp appexpandedtitlemarginstart48dp applayout scrollflagsscrollexituntilcollapsed appstatusbarscrimcolorblack trans80 imageview androidididphoto androidlayout widthmatch parent androidlayout heightmatch parent androidcontentdescriptionstringphoto androidfitssystemwindowstrue androidscaletypecentercrop applayout collapsemodeparallax androidsupportv7widgettoolbar androidididanim toolbar androidlayout widthmatch parent androidlayout heightattractionbarsize applayout collapsemodepin apopupthemestylethemeoverlayappcompatlight androidsupportdesignwidgetcollapsingtoolbarlayoutandroidsupportdesignwidgetappbarlayout,['android'] +977414,linkedin android sdk unable to connect to api invalid request i am having some trouble connecting to the linkedin apii am following this and this yet i am getting this error codeerrorcode invalid requesterrormessage either bundle id or package name hash are invalid unknown malformedmy implementation so far is pretty simplepublic void shareonlinkedin authlistener authlistener new authlistener override public void onauthsuccess logdtag success override public void onautherrorliautherror error logdtag errortostring lisessionmanager getinstancegetapplicationcontext initcolectiondetailactivitythis buildscope authlistener trueprivate static scope buildscope return scopebuildscoper basicprofile scopew shareoverrideprotected void onactivityresultint requestcode int resultcode intent data try lisessionmanagergetinstancegetapplicationcontext onactivityresultthis requestcode resultcode data catch exception e eprintstacktrace,"['java', 'android']" +977429,read binary qr code with avfoundation is it possible to read a binary encoded qr code with avfoundationi can get a avmetadatamachinereadablecodeobject object of type avmetadataobjecttypeqrcode however this only has a stringvalue property which would not work because the data contained in the qr code cannot be converted to a string friendly representationshould i use zxing insteadthanks,['ios'] +977557,is sequential file io with systemiofile helper methods safe i just saw this question is it safe to use static methods on file class in c to summarize op has an ioexception because file is in use in this aspnet code snippetvar text filereadalltextpathtofiletxt do something with textfilewritealltextpathtofiletxtmy first thought has been it is a simple concurrent access issue because of multiple aspnet overlapping requests something i would solve centralizing io into a synchronized threadsafe class or dropping files in favor of something else i read both answers and when i was about to downvote one of them then i saw who those users are and i thought what the h and stoppedi will cite them both then please refer to original answers for more contextfor this op paragraphi am guessing that the file read operation sometimes is not closing the file before the write operation happens an answer sayscorrect file systems do not support atomic updates well using filestream does not help file has no magic inside it just uses filestream wrapped for your conveniencehowever i do not see any expectancy for an atomic operation read subsequent write and parallel because of partially overlapping multithreaded requests may cause concurrent accesses even an atomic io operation read write will have exactly same issue ok filestream may be asynchronous but it is not how filereadalltext and filewritealltext use itthe other answer made me much more perplex it saysalthough according to the documentation the file handle is guaranteed to be closed by this method even if exceptions are raised the timing of the closing is not guaranteed to happen before the method returns the closing could be done asynchronouslywhat msdn says method will open read and close file also in case of exceptions is it ever possible that such method will close file asynchronously will os defer closehandle in which cases whyin short is it just a misunderstanding or closehandle is asynchronous i am missing something extremely important,"['c#', '.net']" +977676,java 8 whats the difference between instant and localdatetime i know thatinstant is rather a technical timestamp representation nanoseconds for computinglocaldatetime is rather dateclock representation including timezones for humansstill in the end imo both can be taken as type for most application usecases as example currently i am running a batch job where i need to calculate a next run based on dates and i am struggling to find a proscons between these two types apart from the nanosecond precision advantage of instant and the timezone part of localdatetimecan you name some application examples where only instant or localdatetime should be usededit beware misread documentations for localdatetime regarding precision and timezone,['java'] +977695,gwt logger no control over debug output i am having the following in my clientgwtxml filexml version10 encodingutf8doctype module public google incdtd google web toolkit 251en module renametoclient inherits namecommzclientapp source pathclient inherits namecomgooglegwtlogginglogging setproperty namegwtloggingloglevel valuefiner setproperty namegwtloggingenabled valuetrue setproperty namegwtloggingconsolehandler valueenabledmoduleand i am trying to log the following loggerinfoinfo loggerfinefine loggerwarningwarning loggersevereseverebut the only thing that shows up in my firebug console is the severe messagemon sep 07 134409 gmt200 2015 commzclientapp severe severewhy am i not getting the other log messagesi have already set the javautilloggingconsolehandlerlevel in loggingproperties to fine limit the message that are printed on the console to info and abovejavautilloggingconsolehandlerlevel finejavautilloggingconsolehandlerformatter javautilloggingsimpleformattereditright now it is working even without one of those lines setproperty namegwtloggingloglevel valuefiner setproperty namegwtloggingenabled valuetrue setproperty namegwtloggingconsolehandler valueenabled i removed those lines cleaned my project and launched the apache server and for whatever magical reason i am receiving debug outputchanging setproperty namegwtloggingloglevel valuefiner to setproperty namegwtloggingloglevel valueinfo does not change the output i am getting all messages down to finer settingsetproperty namegwtloggingenabled valuefalse now does not remove the debug output still getting everythingi want to have control over my debug output,['java'] +977707,python merging two lists with all possible permutations i am trying to figure out the best way to merge two lists into all possible combinations so if i start with two lists like thislist1 1 2list2 3 4the resulting list will look like this13 24 14 23that is it basically produces a list of lists with all the potential combinations between the twoi have been working through itertools which i am pretty sure holds the answer but i cannot come up with a way to make it act this way the closest i came waslist1 1 2 3 4list2 5 6 7 8print listitertoolsproductlist1 list2which produced1 5 1 6 1 7 1 8 2 5 2 6 2 7 2 8 3 5 3 6 3 7 3 8 4 5 4 6 4 7 4 8so it does all the possible combinations of items in each list but not all the possible resulting lists how do i get that to happenedit the end goal is to be able to individually process each list to determine efficiency the actual data i am working with is more complex so in the original example above it would work something like thislist1 1 2list2 3 4get first merged list 13 2 4 do stuff with this listget second merged list 14 2 3 do stuff with this listif i got the list of lists of lists output i described above then i could put it into a for loop and process on other forms of output would work but it seems the simplest to work with,['python'] +977747,retrieve two equal dates from simpledateformat in java i made this snippet to show my problemimport javatextsimpledateformatpublic class foo public static void mainstring args simpledateformat formatter new simpledateformatmm hh dd mm y string date1 1412293500 string date2 1412336700 string datestring1 formatterformatlongparselongdate1 0 string datestring2 formatterformatlongparselongdate2 0 systemoutprintlndatestring1 datestring2 date1 and date2 are expressed in seconds so i am expecting two different dates in output but the dates are printed the same i checked inside this online tool and as you can see the dates are related to two different dayshow can i solve this,['java'] +977801,attribute barlength has already been defined i have just updated material design support lib to v2301 and now my code does not compile anymoreattribute barlength has already been definedusersadmindocumentsworkspacemyappappbuildintermediatesexplodedaarcomandroidsupportappcompatv72301resvaluesv23valuesv23xmlerror retrieving parent for item no resource found that matches the given name androidtextappearancematerialwidgetbuttoninverseerror retrieving parent for item no resource found that matches the given name androidwidgetmaterialbuttoncoloredwhat should i doeditthe 2 libs that gives me the error arecompile comandroidsupportdesign20compile comandroidsupportappcompatv720,['android'] +977995,nodejs nodemailer gmail error im trying to send a email using nodejs nodemailer module my whole code looks likevar httprequirehttpvar nodemailerrequirenodemailerhttpcreateserverfunctionreqres reswritehead200 contenttype textplain var transporter nodemailercreatetransportsmtp service gmail auth user my mail pass mypassword var mailoptions from fred foo a sender address to the same mail want to send it to myself subject hello a subject line text hello world a plaintext body html bhello world ab html body transportersendmailmailoptions functionerror info iferror return consolelogerror consolelogmessage sent inforesponse resendhllolisten40but when i run it it throws login error altought my namepass are correct the whole error looks like this autherror invalid login 5345714 gninsarp1scc1pltakgnsbtwv5345714 fhw6fqlxkg3niqw7atso7o0r4etd7ettnrghexxeulyquthjrntb9r647mlr7gy9z4lsz5345714 wuzyynnwnbjiyrjnzhko9siv visbjgf5hsfptjl5s0dsf3eyncx e8tq z6s4z1mue5i5345714 p8y5yagzdn5rskjpb1ytu3tfwhstlisczizphhlfhlzv86tab8mx4jrqa51hfjyy0kof5345714 qytmeibs1kuzejzpiabmjri87dik please log in via your web browser and5345714 then try again5345714 learn more at534 5714 cx1sm17733852wib0 gsmtp name autherror data 5345714 scc1pltakgnsbtwvrn5345714 fhw6fqlxkg3niqw7atso7o0r4etd7ettnrghexxeulyquthjrntb9r647mlr7gy9z4lszr5345714 wuzyynnwnbjiyrjnzhko9siv visbjgf5hsfptjl5s0dsf3eyncx e8tq z6s4z1mue5irn5345714 p8y5yagzdn5rskjpb1ytu3tfwhstlisczizphhlfhlzv86tab8mx4jrqa51hfjyy0kofrn5345714 qytmeibs1kuzejzpiabmjri87dik please log in via your web browser andrn5345714 then try againrn5345714 learnmore atrn534 5714 cx1sm17733852wib0 gsmtp stage auth is there something i have to set in my gmail acc to allow this to send email from that or how can i fix it,['javascript'] +978132,arguments http post c i am making an http post method to get data i have an idea to create a method to get a specific arguments but when i do not have idea to get the arguments taken in http get arguments are in the url and is more easy to get the arguments how do i create a method to take all the data in http post in php for example when you show the var post you show all data in the body post how can i do this in cmy method is thishttppostallowanonymouspublic ihttpactionresult test get url args for example is var args requestrequesturiquery but if the arguments are in the body i do not have idea,['c#'] +978213,nsuseractivity missing contentattributeset property i am implementing the ios9 search index using nsuseractivitiesaccording to the documentation nsuseractivity there should be a property called contentattributeset that is used to add more content to the search item however looking at the nsuseractivity class in xcode 7 shows no property with this name i am using xcode 7 beta 6,['ios'] +978404,resolving instances in aspnet 5 mvc 6 di how do i manually resolve a type using the aspnet 5 mvc 6 builtin dependency injection frameworksetting up the container is easy enoughpublic void configureservicesiservicecollection services servicesaddtransientisomeservice someconcreteservicebut how can i resolve isomeservice without performing injection for example i want to do thisisomeservice service servicesresolveisomeservicethere are no such methods in iservicecollection,['c#'] +978416,how to return the previous text after an onclick js function my code is function changetext documentgetelementbyidbuttoninnerhtml downloadingthe buttonbutton id button onclickchangetext valuechange textdownload file as csvbuttoni want the button to change to downloading then return to download as csv a few seconds after is this possible in js,['javascript'] +978430,hibernate not releasing connections from connection pool i am creating an application with hibernate jpa and i use c3p0 for connection pooling with mysql i have an issue with the number of connections to the mysql database as it hits the 152 opened connections this is not wanted since i define in my c3p0 config file the max pool size to 20 and of course i close every entity manager i get from the entitymanagerfactory after committing every transactionfor every time a controller is executed i notice more than 7 connections are opened and if i refresh then 7 connections are opened again without the past idle connections being closed and in every dao function i call the emclose is executed i admit here that the issue is in my code but i do not know what i am doing wrong herethis is the sondagejava entityentitynamedquerynamesondagefindall queryselect s from sondage spublic class sondage implements serializable private static final long serialversionuid 1l public sondage id generatedvaluestrategy generationtypeidentity private int id private string name private byte needlocation bidirectional manytoone association to resultatsondage onetomanymappedby sondage cascade cascadetypeall orderbysondage asc private listresultatsondage resultatsondages bidirectional manytoone association to sondagesection onetomanymappedby sondage cascade cascadetypeall private listsondagesection sondagesectionsand heres my dao clasuppresswarningsuncheckedpublic static listsondage getallsondage entitymanager em persistencemanagergetentitymanager listsondage allsondages new arraylist try emgettransactionbegin query query emcreatequeryselect s from sondage s allsondages querygetresultlist emgettransactioncommit catch exception ex if emgettransactionisactive emgettransactionrollback allsondages null finally emclose return allsondagesas you see em is closed in my jsp i do this i know this is not the good way of doing thing in the view sidebody div classheader include fileincludesheaderjsp div h2 stylecolor green textalign centeru3auah2 div idallsurveys classpuremenu customrestrictedwidth listsondage allsondages listsondage requestgetattributesondages for int i 0 i allsondagessize i a hrefpagecontextrequestcontextpath authdosurveyid allsondagesgetigetid allsondagesgetigetnamea nbsp if requestgetsessiongetattributeuser null utilisateur user utilisateur requestgetsessiongetattributeuser if usergettypeequalsadmin a hrefpagecontextrequestcontextpath aautheditsurveyid allsondagesgetigetida1 uua br divbodyi am guessing that every time i call usergettype a request is established if so how can i prevent thisfor c4p0 config file i included it in persistencexml i saw several posts saying that i need to put the c3p0 config file in c3p0configxml but with my setup the c3p0 is initialized with the values i pass in the persistencexml file also the mysql connections are reaching 152 connections but the maxpoolsize is at 20 heres the persistencexml filepersistence version21 xmlns xmlnsxsi xsischemalocation 2 1xsd persistenceunit namecaoe transactiontyperesource local classcomcaoemodelschoixquestionclass classcomcaoemodelsquestionclass classcomcaoemodelsreponseclass classcomcaoemodelsresultatsondageclass classcomcaoemodelssectionclass classcomcaoemodelssondageclass classcomcaoemodelssondagesectionclass classcomcaoemodelssousquestionclass classcomcaoemodelsutilisateurclass properties property namehibernateconnectionprovider class value orghibernateservicejdbcconnectionsinternalc3p0connectionprovider property namehibernateconnectiondriver class valuecommysqljdbcdriver property namehibernateconnectionpassword value property namehibernateconnectionurl valuejdbcmysqllocalhost3306caoeuseunicodeyesampcharacterencodingutf8 property namehibernateconnectionusername valueroot property namehibernatedialect valueorghibernatedialectmysqldialect property namehibernateshow sql valuetrue property namehibernatec3p0max size value50 property namehibernatec3p0min size value3 property namehibernatec3p0max statements value20 property namehibernatec3p0acquire increment value1 property namehibernatec3p0idle test period value30 property namehibernatec3p0timeout value35 property namehibernatec3p0checkouttimeout value60 property namehibernateconnectionrelease mode valueafter statement property namedebugunreturnedconnectionstacktraces valuetrue properties persistenceunitpersistenceedit i am deploying the application to a red hat server with tomcat and mysql installed i am just wondering why hibernate is opening too much connections to mysql with all entity managers closed no connection will remain open but this is not the case i am guessing and correct me if i am true that the connections are opened when i do something like this listsondage allsondages sondagedaogetallsondagesfor sondage sondage allsondages listquestion questions sondagegetquestions code to thisplay questions for examplehere when i use sondagegetquestions does hibernate open a connection to the database and does not close it after am i missing something in the configuration file that close or return connection to pool when it is done with it thanks in advance for any helpedit2 since people are asking for versions here they are java jre 180 25apache tomcat v70hibernatecore4310hibernate c3p0 4310finalhibernatejpa 21thanks in advancethe mysql version is mysql 5617 if that can helpedit 4 as people are getting confused about witch version of the code i posted is buggy let me edit this so youll know what happens exactlyfirst i will start by showing whats the buggy code as you guys do not care about whats workingsuppresswarningsuncheckedpublic static listsondage getallsondage entitymanager em persistencemanagergetentitymanager listsondage allsondages new arraylist try emgettransactionbegin query query emcreatequeryselect s from sondage s allsondages querygetresultlist emgettransactioncommit catch exception ex if emgettransactionisactive emgettransactionrollback allsondages null finally emclose return allsondages so this is basically what i did for all my dao functions i know transaction is not needed here since i saw questions pointing that transactions are important for connection to close beside this i getentitymanager from persistencemanager class that has an entitymanagerfactory singleton object so getentitymanager creates an entitymanager from the entitymanagerfactory singleton object code is better than 10 word pesistencemanagerjavaimport javaxpersistenceentitymanager import javaxpersistenceentitymanagerfactory import javaxpersistencepersistence public class persistencemanager private static entitymanagerfactory emf null public static entitymanager getentitymanager return getentitymanagerfactorycreateentitymanager public static entitymanagerfactory getentitymanagerfactory ifemf null emf persistencecreateentitymanagerfactorycaoe return emf else return emf yes this is cool and all good but wheres the problemthe problem here is that this version opens the connections and never close them the emclose have no effect it keeps the connection open to the databasethe noob fixwhat i did to fix this issue is create an entitymanagerfactory for every request it mean that the dao looks something like this suppresswarningsuncheckedpublic static listsondage getallsondage this is the method that return the entitymanagerfactory singleton object entitymanagerfactory emf persistencemanagergetentitmanagerfactory entitymanager em emfcreateentitymanager listsondage allsondages new arraylist try emgettransactionbegin query query emcreatequeryselect s from sondage s allsondages querygetresultlist emgettransactioncommit catch exception ex if emgettransactionisactive emgettransactionrollback allsondages null finally emclose emfclose return allsondagesnow this is bad and i will just keep it while i do not have answer for this question it seems like forver d so with this code basically all connections gets closed after hibernate does not need them thanks in advance for any efforts you put in this question,"['java', 'mysql']" +978451,undeclared struct causes no warnings the following code compiles fine without any warnings on gccnote that there is no forward declaration for the struct is this valid c andor c codestruct foobar fstruct foobar fun return 0 int main f 0 fun return 0,"['c++', 'c']" +978549,sorting a hashmap by date in a java class i have a method to reorder an existing hashmap by date the hashmap is of a type string object where the object contains a field called exppaydate and the key string is a sequential number turned into a string so i need to loop through the items in the sourcemap and find the item with the newest date then copy it to a tempmap in the correct order my issue is what is the best way to determine the item with the newest date,['java'] +978577,how can my variable declarations affect execution time i am a circuit designer not a software wizard and have been working on a numerical algorithm for the past 9 months as a way to evaluate the effectiveness of my algorithms i monitor the amount of time needed to converge on a solutionabout 6 months ago i thiscovered that the way i declare my variables can have a dramatic effect on the time needed for the program to run for example simply rearranging the declarations as shown below can double the time needed to run the code simply changing the lengths of the arrays also affects the problem similarlyint n j iterlong double realzero realerr quaditererr quadxlong double tuv3 quadqp102 realqp102bool updatedint n j iterlong double realzero realerr quaditererr quadxlong double quadqp102 realqp102bool updatedlong double tuv3i initially assumed i had some sort of bug but i cannot find it other than speed i do not see any other anomalies and i get the same results whether the code runs slow or fasti found some thiscussions on problems associated with packing long doubles but i did not understand any of it and they never said how to fix the problem they were thiscussingcan someone give me some insight as to what might be going on here and how to fix it i need consistency more than i need the speed i am not using any speed optimizers default compiler settings and i am using c builder xe3 i am not using a pragma pack as someone askedbased on the comments i setup the declarations for slow and fast execution and compared the base addresses on all the long double variables whether slow or fast the addresses end with a 0 4 8 or c,['c++'] +978654,wxpython threads blocking this is in the phoenix fork of wxpythoni am trying to run a couple threads in the interests of not blocking the guitwo of my threads work fine but the other one never seem to hit its bound result function i can tell that it is running it just does not seem to properly post the eventheres the result function for the main calculation threadsdef on status resultself event if not selfpanelprogress bargetrange selfpanelprogress barsetrangeeventdataparcel count selfpanelprogress barsetvalueeventdatacurrent parcel selfpanelstatus labelsetlabeleventdatamessageheres how i am binding themfrom wxlibpubsubcore import publisherpub publisherheres how i am binding the methoddef post eventmessage data wxcallafterlambda a publishersendmessagemessage datadataand here are the threads the first one does not work but the second two doclass preparethreadthreadingthread def init self notify window threadingthread init self self notify window notify window self want abort false def runself while not self want abort for status in prepare collectiondatabase self previous id self current id self year self col type self lock post eventpreparerunning status post eventpreparecomplete none return none def abortself self want abort trueclass setupthreadthreadingthread def init self notify window threadingthread init self self notify window notify window self want abort false def runself while not self want abort do more stuff with the database return none def abortself self want abort trueclass latestcollectionsthreadthreadingthread def init self notify window threadingthread init self self notify window notify window self want abort false def runself while not self want abort do stuff with my database return none def abortself self want abort trueprepare collection is a function that yields status objects that looks like thisclass status def init self parcel count current parcel total message selfparcel count parcel count selfcurrent parcel current parcel selftotal total selfmessage messageheres how i am creatingstartingsubscribing the preparethreadmainformwxform prepare thread preparethreadself prepare threadstart selfpub publisher selfpubsubscribeselfon status result preparerunning selfpubsubscribeselfon status result preparecomplete def on status resultself event if not selfpanelprogress bargetrange selfpanelprogress barsetrangeeventdataparcel count selfpanelprogress barsetvalueeventdatacurrent parcel selfpanelstatus labelsetlabeleventdatamessagei have tried stubbing out prepare collection with range10 but i still do not ever hit the event handler,['python'] +978677,why can you instantiate a class from a string variable but not a string in php how come in php this worksmyclass appmyclassobject new myclassbut this results in an errormyclass myclassobject new appmyclassin the second example an unexpected t constant encapsed string is thrownas it turns out the above example is due to operator precedence since new takes highest precedence butsimilarly i can try instantiating with just a string as inobject new appmyclassand the same error is thrown why is this,['php'] +978694,slickjs remove blue highlight around image i am using slickjs to build a carousel inside a modal everything works perfectly until i click on an image a blue border shows up and i unfortunately cannot figure out how to make it stop doing so i have tried outline none and border none and have had no success here is my codehtmldiv idopenmodal classmodaldialog div id background a hrefclose titleclose classclosexa div idlogo img srcmedia gallerylogo altsmiley face height100 width150 div div classmultipleitems divimg srcmedia galleryimage1 height200 width300div divimg srcmedia galleryimage2 height200 width300div divimg srcmedia galleryimage3 height200 width300div divimg srcmedia galleryimage4 height200 width300div divimg srcmedia galleryimage5 height200 width300div divimg srcmedia galleryimage6 height200 width300div div divdivcss slider slickslider margin 110px 35px 0 0 position relative thisplay block mozboxsizing borderbox boxsizing borderbox webkituserselect none mozuserselect none msuserselect none userselect none webkittouchcallout none khtmluserselect none mstouchaction pany touchaction pany webkittaphighlightcolor transparentslicklist position relative thisplay block overflow hidden margin 0 padding 0slicklistfocus outline noneslicklistdragging cursor pointer cursor handslickslider slicktrack slickslider slicklist webkittransform translate3d0 0 0 moztransform translate3d0 0 0 mstransform translate3d0 0 0 otransform translate3d0 0 0 transform translate3d0 0 0slicktrack position relative top 0 left 0 thisplay blockslicktrackbefore slicktrackafter thisplay table contentslicktrackafter clear bothslickloading slicktrack visibility hiddenslickslide thisplay none float left height 100 minheight 1pxdirrtl slickslide float rightslickslide img thisplay blockslickslideslickloading img thisplay noneslickslidedragging img pointerevents noneslickinitialized slickslide thisplay block backgroundcolor green border noneslickloading slickslide visibility hiddenslickvertical slickslide thisplay block height auto border 1px solid transparentslickarrowslickhidden thisplay noneslider width 80 margin 40px 0 0 100pxlower margintop 100pxslickslide color white padding 30px fontsize 30px fontfamilyarial margin 0 50px 0 0slickprevbefore slicknextbefore color blackslickslidenthchild1 slickslidenthchild3 slickslidenthchild5 slickslidenthchild7 slickslidenthchild9 slickslidenthchild11 slickslide slickcurrent slickactive thisplay none color redslickslide slickactive thisplay noneslickactive img outline 0 important border0 none importantmultipleitems img outline 0 important border0 none importantjquerydocumentreadyfunction multipleitemsslick infinite false arrows false slidestoshow 3 slidestoscroll 1 edit here is a link to the jsfiddle when you open the modal you will see the images inside once you click on an image a blue box appears around the image that is what i am trying to remove,"['javascript', 'jquery', 'css']" +978734,how can i insert new linern in reactnative text component i want to insert a new line like rn br to text component in reactnativewhen i writetexthithis is a test messagetextbut reactnative shows to me hi this is a test messageis there possible print like thishithis is a test message,"['javascript', 'ios']" +978786,super class method and interface default method conflict resolution consider the below examplepublic class testing extends supcls implements intf public static void mainstring args new testingtest class supcls public void test systemoutprintlnfrom supcls interface intf public default void test systemoutprintlnfrom intf as you can see there is no connection between supcls class and intf interface but both are defining a common methodand testing class is extending supcls and implementing intfso when i call test method on testing the output isfrom supclswhich i think makes sense because extending from a class should take higher priority than implementing from an interfacebut eclipse reports otherwise as shown in the below screen capturei strongly believe this is a bug in eclipsebut before assuming is this behavior defined documented in the jls or is there something else which defines this behavioredit eclipse version is mars release 450 if it matters,['java'] +978917,migrating project to new experimental gradle plugin i try to migrate my android project to new experimental gradle plugin i followed instructions at this page i made changes in required files but i have an error when i trying to sync project with gradle fileserrorunable to load class comandroidbuildgradlemanagedproductflavor impl possible causes for this unexpected error includegradles dependency cache may be corrupt this sometimes occurs after a network connection timeout redownload dependencies and sync project requires networkthe state of a gradle build process daemon may be corrupt stopping all gradle daemons may solve this problem stop gradle build processes requires restartyour project may be using a thirdparty plugin which is not compatible with the other plugins in the project or the version of gradle requested by the projectin the case of corrupt gradle processes you can also try closing the ide and then killing all java processesbuildgradle in my app folder is very similar to thisapply plugin comandroidmodelapplicationapply plugin mavenrepositories maven url getbaserepository credentials username nexus username password nexus password mavencentraldef int cache limit cache changing modules for secondstointegerconfigurationsall resolutionstrategycachechangingmodulesfor cache limit secondsmodel android compilesdkversion 23 buildtoolsversion 2300 defaultconfigwith applicationid myrealappithishere minsdkversionapilevel 14 targetsdkversionapilevel 18 multidexenabled true androidbuildtypes debug buildconfigfieldwith create type boolean name debug build value rootprojectextdebugbuild release minifyenabled false proguardfiles proguardrulespro buildconfigfieldwith create type boolean name debug build value rootprojectextreleasebuild dependencies my dependencies are heredoes anybody know where the problem is i do not know why error message contains problem about productflavor because my project has no flavorsupdatei tried to clean my project clean was not successful but the error message during clean is more specificerror10 1 a problem occurred configuring project app exception thrown while executing model rule comandroidbuildgradlemodelbasecomponentmodelpluginrulescreatevariantdataorggradlemodelmodelmap orggradlemodelmodelmap comandroidbuildgradleinternaltaskmanager aftereach could not resolve all dependencies for configuration app debugcompile exception thrown while executing model rule modelandroid cannot set readonly property minsdkversion for class comandroidbuildgradlemanagedproductflavor implbut still i do not know how can i fix it,['android'] +979023,realm fetching objects on background thread and pass to main thread i want to fetch large amount of objects on the background thread however i cannot pass them to the main thread as i get terminating app due to uncaught exception rlmexception reason realm accessed from incorrect threadfetch codethispatch asyncthispatch get global queuethispatch queue priority default 0 void background thread rlmrealm realm rlmrealm defaultrealm selfallobjectsrlmresult myclass allobjectsinrealmrealm thispatch asyncthispatch get main queue void use selfallobjects and do stuff on main thread how to perform a fetch on the background and pass the object to the main thread so there is minimal performance impacti could get the primary keys and then refetch on the main thread but this will be the same performance possibly even slower as fetching them directly,"['ios', 'objective-c']" +979113,failed to execute replacestate on history cannot be created in a document with origin null i am creating a page for the transitionclicking on the page to navigate to another page works on firefox but it does not on chromeerror is showing uncaught securityerror failed to execute replacestate on history a history state object with url filecusersathitedesktopdemopagehtml cannot be created in a document with origin nullhere is my codedoctype htmlhtmlheadmeta nameviewport contentwidthdevicewidth initialscale1link relstylesheet hrefscript srcscript script srcscriptheadbodydiv datarolepage idpageone div dataroleheader h1welcome to my homepageh1 div div datarolemain classuicontent pclick on the link to see the slide effectp a hrefpagetwo datatransitionslideslide to page twoa div div datarolefooter h1footer texth1 divdiv div datarolepage idpagetwo div dataroleheader h1welcome to my homepageh1 div div datarolemain classuicontent pclick on the link to go back p a hrefpageone datatransitionslide datadirectionreversego to page onea div div datarolefooter h1footer texth1 divdiv bodyhtml,"['javascript', 'jquery', 'html']" +979173,how to create populated mysql docker image on build time i would like to create a mysql docker image with data already populatedi want to create 3 layers like this layer 3 customer 1 database customer 2 database layer 2 database image with tables but no data layer 1 mysql5626 my question is now how to create a correct dockerfile for layer 2 and 3where my empty with tablessql file is loaded into layer 2 and customer1sql and customer2sql is loaded into two images in layer 3 i read something about putting sql files into dockerentrypointinitdbd but this would result in the data being when the image is started for the first time this not what i want i want the data to be ready in the image for example to be quickly available in testingi could start the mysql image load the data from commandline and do a commit but this is not reproducible requiring doing that again when data in the sql files are changedhow can this be donebest regardsmorten green hermansen,['mysql'] +979231,comparing sorting array of hashes in ruby i have two arrays they have different attributesarray1 name apple quantity 2 name grape quantity 10 name pear quantity 3array2 name grape freshness 9 name apple freshness 7 name pear freshness 10i would like to sort array1 based on array2s order by name the result would bearray1 name grape quantity 10 name apple quantity 2 name pear quantity 3,['ruby'] +979388,scrollview with embedded tableview i am building an ios app in swift with xcode 6i am trying to embed a view controller with a table view in a scrollview when the user drags in the table view it is suppose to move the table not the the scrollview that it is embedded ini have made this illustration to clearify my view and view controller hierachythe red area is the content size area of the scrollviewthe green and blue areas are different view controllers embedded in the scrollviewthe yellow area is a text field in the blue view controllerthe orange area is a table view in the blue view controlleri have enabled paging in the scrollview so that it snaps to either the green or blue view controller how can i pop the table view to the top of the view hierachy so that the only way to scroll the scrollview will be to drag in the text fieldimport uikitclass rootviewcontroller uiviewcontroller uiscrollviewdelegate var scrollview uiscrollviewvar greenviewcontroller greenviewcontrollervar blueviewcontroller blueviewcontrolleroverride func viewdidload superviewdidload scrollview uiscrollviewframe cgrectmake0 0 selfviewframewidth selfviewframeheight scrollviewdelegate self scrollviewpagingenabled true selfgreenviewcontroller selfstoryboardinstantiateviewcontrollerwithidentifiergreen view controller as greenviewcontroller selfblueviewcontroller selfstoryboardinstantiateviewcontrollerwithidentifierblue view controller as blueviewcontroller greenviewcontrollerviewframe cgrectmake0 0 viewboundswidth viewboundsheight blueviewcontroller cgrectmake0 viewboundsheight viewboundswidth viewboundsheight scrollviewaddsubviewgreenviewcontrollerview scrollviewaddsubviewblueviewcontrollerview scrollviewcontentsize cgsizemakeviewboundswidth viewboundsheight2 selfviewaddsubviewscrollviewi hope that i have expressed myself clearlyediti have tried changing the size of the scrollview when it scrolls the idea was to change the height of the frame so it matches the height of the textfield when it is scrolled all the way down but it seems that it also changes the visible part of whats embedded in the scrollview func scrollviewdidscrollscrollview uiscrollview if selfscrollviewcontentoffsety textfieldviewboundsheight selfscrollviewframesizeheight viewboundsheight scrollviewcontentoffsety textfieldviewboundsheight printlnselfscrollviewframe,['ios'] +979470,android check permission for locationmanager i am trying to get the gps coordinates to thisplay when i click a button in my activity layout the following is the method that gets called when i click the buttonpublic void getlocationview view textview tv textview findviewbyidridgps coord view locationmanager lm locationmanager getsystemservicelocation service location loc lmgetlastknownlocationlocationmanagergps provider tvsettextlatitude locgetlatitude nlongitude locgetlongitudei am getting an error that says call requires permission which may be rejected by user code should explicitly check to see if permission is availablei have already granted these permissions in my androidmanifest the error is taken care of and the app compiles when i add the following before calling lmgetlastknownlocationif checkselfpermissionmanifestpermissionaccess fine location packagemanagerpermission granted checkselfpermissionmanifestpermissionaccess coarse location packagemanagerpermission granted returnhowever the app crashes when i press the button that calls getlocation when it is clicked what is going on is there bettersimpler way to grab the gps coordinates of the device,['android'] +979486,javafx rendering glitch in jre 180 60 i have a javafx 8 application that works perfectly well in jre 180 45 but today a user came to me with a problem after some investigation i realised that it was related to him having a more recent release of the jre specifically 180 60im reading a gis shapefile and drawing several paths to a group like 30 or more in my version it was a bit slow but it worked fine in the latest version the image appeared thistorted the paths where drawn out of place and out of scale in chunkscorrect image generated under jre 180 45thistorted image generated under jre 180 60so i decided to make a little test application to separate the problem from anything else i might be doing in doing so i found out that the problem was not only when drawing paths on group but also in drawing to a canvas also if somehow i managed to redraw the screen the image would appear fine for example i have a checkbox binded with the visible property of the group containing the paths so if i set it to false and then true it takes some time drawing the scene but then it appears fine the test app is very simple if you press a button you generate a canvas with some squares 10px10p if you press the other you generate more squares and thus the rendering glitch appearspackage gisuiimport javafxapplicationapplicationimport javafxapplicationplatformimport javafxscenegroupimport javafxscenenodeimport javafxscenesceneimport javafxscenecanvascanvasimport javafxscenecanvasgraphicscontextimport javafxscenecontrolbuttonimport javafxscenelayouthboximport javafxscenelayoutpaneimport javafxscenelayoutvboximport javafxscenepaintcolorimport javafxscenepaintpaintimport javafxsceneshapelinetoimport javafxsceneshapemovetoimport javafxsceneshapepathimport javafxstagestagepublic class path2dtestapplication extends application private static final int width 10 group content new group override public void startstage stage throws exception stagesettitlejavafx 180 60 rendering test button button new buttoncanvas 100 x 30 buttonsetonactionadogeneratecanvas10030 button button2 new buttoncanvas 100 x 400 button2setonactionadogeneratecanvas100400 button button3 new buttonpaths 100 x 30 button3setonactionadogeneratepaths10030 vbox vbox new vbox vboxgetchildrenaddallnew hboxbuttonbutton2button3content group root new group rootgetchildrenaddvbox scene scene new sceneroot80width60width 1500 800 colorwhite stagesetscenescene stageshow private void dogeneratepathsint maxxint maxy pane paths new pane contentgetchildrenclear platformrunlater forint i 0imaxxi forint j0jmaxyj pathsgetchildrenaddgetpathij contentgetchildrenaddpaths private void dogeneratecanvasint maxxint maxy contentgetchildrenclear platformrunlater canvas canvas new canvasmaxxwidth maxywidth graphicscontext gc canvasgetgraphicscontext2d int counter 0 forint i 0imaxxi forint j0jmaxyj gcsetfillcolor rgb255int mathrandom255191 double xcoords new doubleiwidth i1width i1width iwidth double ycoords new doublejwidthjwidthj1widthj1width gcfillpolygonxcoordsycoordsxcoordslength counter systemoutprintlncounter polygons added contentgetchildrenaddcanvas protected node getpathint iint j path path new path pathgetelementsaddnew movetoiwidth jwidth pathgetelementsaddnew linetoi1width jwidth pathgetelementsaddnew linetoi1width j1width pathgetelementsaddnew linetoiwidth j1width pathgetelementsaddnew linetoiwidth jwidth paint currentcolor color rgb255int mathrandom255191 pathsetfillcurrentcolor pathsetstrokewidth01 return path public static void mainstring args applicationlaunchpath2dtestapplicationclass args test 1 press button canvas 100 x 30 30 squares are drawn correctly and fast test 2 press button canvas 100 x 400 40 squares are drawn showing the glitchtest 3 press button canvas 100 x 400 again 40 squares are drawn correctly and fast test 4 press button paths 100 x 30 30 squares are drawn showing the glitchtest 5 press button paths 100 x 30 again 30 squares are drawn correctlythis is my first question to stakoverflow so apologies if i was not clear enoughif anyone knows if this is a jre error or there is some problem with my code i would be grateful also any workarounds would be helpful tks,['java'] +979495,celluloid async inside ruby blocks does not work trying to implement celluloid async on my working example seem to exhibit weird behaviorhere my code looks class indefinite include celluloid def run loop do 1each do i asyncon background end end end def on background puts running in background end end indefinitenewrunbut when i run the above code i never see the puts running in backgroundbut if i put a sleep the code seem to workclass indefinite include celluloid def run loop do 1each do i asyncon background end sleep 05 end end def on background puts running in background end end indefinitenewrunany idea why such a difference in the above two scenariothanks,['ruby'] +979500,how to make alarm manager work when android 60 in doze mode i am a developer of two alarm clock apps on google play i am trying to get them to work with android 60 however doze mode makes it so they do not ring i put them on the white list i put a foreground notification icon up i am not sure what else i can do when in doze mode the the alarm manager alarms are still ignored the clock app which is a google play rather than aosp app however is different when the alarm is enabled on the clock app adb deviceidle step will always read active and never idle idle pending or anything elseis android cheating here giving its own app more power aka pulling an apple are all alarm clock apps on google play about to become nonfunctional kind of worried here these are quality apps that each took a year of parttime development time and are big income sources for me any clues on how i could get these to work would be a huge helpsetting the alarmmanager intent intent intent new intentcontext receiveralarmclass if androidosbuildversionsdk int 16 intentaddflagsintentflag receiver foreground amsender pendingintentgetbroadcastcontext 1 intent pendingintentflag cancel current flag cancel current seems to be required to prevent a bug where the intent does not fire after app reinstall in kitkat am alarmmanager contextgetsystemservicecontextalarm service amsetalarmmanagerrtc wakeup scheduletotime1 amsenderand the receiveralarm classpublic class receiveralarm extends broadcastreceiveroverridepublic void onreceivecontext context intent intent if wakelock null powermanager pm powermanager contextgetsystemservicecontextpower service wakelock pmnewwakelockpowermanagerpartial wake lock themeapptitle wakelockacquire xalarmmasterstartringingalarmtrueand the relevant parts of the xalarmmasterstartringingalarm method if wakelock null powermanager pm powermanager contextgetsystemservicecontextpower service wakelock pmnewwakelockpowermanagerpartial wake lock themeapptitle wakelockacquire if screenwakelock null powermanager pm powermanager contextgetsystemservicecontextpower service screenwakelock pmnewwakelockpowermanagerfull wake lock powermanageracquire causes wakeup powermanageron after release themeapptitle scr screenwakelockacquire intent alarmintent new intentintentaction view alarmintentaddflagsintentflag activity new task alarmintentaddflagsintentflag activity clear top alarmintentsetclasscontext activityalarmalarmclass contextstartactivityalarmintentsome of the methods have been pasted inline for easier readability,['android'] +979520,random array generator java i need to initialize an array of characters with 10 random characters between az and azi donat want do this by first generating only characters between az and then only characters in az but treat all 52 characters equallyi know one way to do this is to generate a random number between 0 and 51 and assign it one of the character valueshow would i approach this problem or assign values to the random numbers between 0 and 51,['java'] +979572,c generics interfaces and inheritance i have two interfacespublic interface iamapublic interface iambt where t iamaand two classes implementing these interfaces like thispublic class classa iamapublic class classb iambclassawhen trying to use these classes as shownpublic class foo public void bar var list new listiambiama listaddnew classb i get this compiler errorcannot convert from classb to iambiamai know i can make the compiler happy usingpublic class classb iambiamabut i need to be able to be the type parameter for iamb in classb an implementation of iama,['c#'] +979688,android fake gps location apps do not work anymore i used to work with this applicationhlenand before this with this onehlenam working on a lg g3 and a nexus 5 but in the last couple of days the fake location does not work as it shouldit does not always modify my location and sets in where i want or many times it sets my location where i want for a couple of seconds and then resets to my real location i am working on a travel app and this made it very simple to simulate trips and locationsis there any other fake location app that actually works how it shouldor is there any other way to set the location of my phone while the app is runningedit yes mock locations is onlike i said it does change my location to the mock location i want but it jumps back to my real location after a couple of seconds depending sometimes it stays for minutes on the mock location but then jumps for 1 second on my real location and then goes back now i know this cause i log all the locations that i find even more draws the path and i have lines that jump back to my real location and then continuepicture pink how it should begreen locations that i get and the path as you can see each a couple of locations that i get it jumps back to my location,['android'] +979754,undefined reference to cocos2duserdefault i have this cocos 2dx game for ios and i want to port it to android i understand i have to write all my classes in the androidmk and i did but still i have this problem classesscenesitemshopitemshopcpp144 error undefined reference to cocos2duserdefaultgetvalueforkeyplistthis is just horrible i do not understand why i have this error i have userdefault class declared in androidmkedithere is some codeccuserdefaulth copyright c 20102012 cocos2dxorg copyright c 20132014 chukong technologies inc permission is hereby granted free of charge to any person obtaining a copy of this software and associated documentation files the software to deal in the software without restriction including without limitation the rights to use copy modify merge publish thistribute sublicense andor sell copies of the software and to permit persons to whom the software is furnished to do so subject to the following conditions the above copyright notice and this permission notice shall be included in all copies or substantial portions of the software the software is provided as is without warranty of any kind express or implied including but not limited to the warranties of merchantability fitness for a particular purpose and noninfringement in no event shall the authors or copyright holders be liable for any claim damages or other liability whether in an action of contract tort or otherwise arising from out of or in connection with the software or the use or other dealings in the software ifndef support ccuserdefault h define support ccuserdefault h include baseccplatformmacrosh include string include baseccdatah ns cc begin addtogroup data storage userdefault acts as a tiny database you can save and get base type values by it for example setboolforkeyplayed true will add a bool value true into the database its key is played you can get the value of the key by getboolforkeyplayed it supports the following base types bool int float double string class cc dll userdefault public get value methods brief get bool value by key if the key does not exist a default value will return you can set the default value or it is false js na bool getboolforkeyconst char pkey js na bool getboolforkeyconst char pkey bool defaultvalue brief get integer value by key if the key does not exist a default value will return you can set the default value or it is 0 js na int getintegerforkeyconst char pkey js na int getintegerforkeyconst char pkey int defaultvalue brief get float value by key if the key does not exist a default value will return you can set the default value or it is 00f js na float getfloatforkeyconst char pkey js na float getfloatforkeyconst char pkey float defaultvalue brief get double value by key if the key does not exist a default value will return you can set the default value or it is 00 js na double getdoubleforkeyconst char pkey js na double getdoubleforkeyconst char pkey double defaultvalue brief get string value by key if the key does not exist a default value will return you can set the default value or it is js na stdstring getstringforkeyconst char pkey js na stdstring getstringforkeyconst char pkey const stdstring defaultvalue brief get binary data value by key if the key does not exist a default value will return you can set the default value or it is null js na lua na data getdataforkeyconst char pkey js na lua na data getdataforkeyconst char pkey const data defaultvalue set value methods brief set bool value by key js na void setboolforkeyconst char pkey bool value brief set integer value by key js na void setintegerforkeyconst char pkey int value brief set float value by key js na void setfloatforkeyconst char pkey float value brief set double value by key js na void setdoubleforkeyconst char pkey double value brief set string value by key js na void setstringforkeyconst char pkey const stdstring value brief set binary data value by key js na lua na void setdataforkeyconst char pkey const data value brief save content to xml file js na void flush returns the singleton js na lua na static userdefault getinstance js na static void destroyinstance deprecated use getinstace instead js na lua na cc deprecated attribute static userdefault shareduserdefault js na cc deprecated attribute static void purgeshareduserdefault js na static const stdstring getxmlfilepath js na static bool isxmlfileexist stdstring getvalueforkeypliststdstring key bool searchtextinpliststdstring text private userdefault userdefault static bool createxmlfile static void initxmlfilepath static userdefault userdefault static stdstring filepath static bool isfilepathinitialized end of data storage group ns cc end endif support ccuserdefault h ccuserdefaultcppcopyright c 20102012 cocos2dxorgcopyright c 20132014 chukong technologies incpermission is hereby granted free of charge to any person obtaining a copyof this software and associated documentation files the software to dealin the software without restriction including without limitation the rightsto use copy modify merge publish thistribute sublicense andor sellcopies of the software and to permit persons to whom the software isfurnished to do so subject to the following conditionsthe above copyright notice and this permission notice shall be included inall copies or substantial portions of the softwarethe software is provided as is without warranty of any kind express orimplied including but not limited to the warranties of merchantabilityfitness for a particular purpose and noninfringement in no event shall theauthors or copyright holders be liable for any claim damages or otherliability whether in an action of contract tort or otherwise arising fromout of or in connection with the software or the use or other dealings inthe softwareinclude baseccuserdefaulthinclude platformcommonhinclude platformccfileutilshinclude tinyxml2hinclude basebase64hinclude baseccutilshif cc target platform cc platform ios cc target platform cc platform mac cc target platform cc platform android root name of xmldefine userdefault root name userdefaultrootdefine xml file name userdefaultxmlusing namespace stdns cc begin define the functions here because we do not want to export xmlnodeptr and other types in ccuserdefaulth static tinyxml2xmlelement getxmlnodeforkeyconst char pkey tinyxml2xmlelement rootnode tinyxml2xmldocument doc tinyxml2xmlelement curnode nullptr check the key value if pkey return nullptr do tinyxml2xmldocument xmldoc new tinyxml2xmldocument doc xmldoc stdstring xmlbuffer fileutilsgetinstancegetstringfromfileuserdefaultgetinstancegetxmlfilepath if xmlbufferempty cclogcan not read xml file break xmldocparsexmlbufferc str xmlbuffersize get root node rootnode xmldocrootelement if nullptr rootnode cclogread root node error break find the node curnode rootnodefirstchildelement while nullptr curnode const char nodename curnodevalue if strcmpnodename pkey break curnode curnodenextsiblingelement while 0 return curnodestatic void setvalueforkeyconst char pkey const char pvalue tinyxml2xmlelement rootnode tinyxml2xmldocument doc tinyxml2xmlelement node check the params if pkey pvalue return find the node node getxmlnodeforkeypkey rootnode doc if node exist change the content if node if nodefirstchild nodefirstchildsetvaluepvalue else tinyxml2xmltext content docnewtextpvalue nodelinkendchildcontent else if rootnode tinyxml2xmlelement tmpnode docnewelementpkeynew tinyxml2xmlelementpkey rootnodelinkendchildtmpnode tinyxml2xmltext content docnewtextpvaluenew tinyxml2xmltextpvalue tmpnodelinkendchildcontent save file and free doc if doc docsavefileuserdefaultgetinstancegetxmlfilepathc str delete doc implements of userdefault userdefault userdefault userdefault nullptrstring userdefault filepath stringbool userdefault isfilepathinitialized falseuserdefaultuserdefaultuserdefaultuserdefaultbool userdefaultgetboolforkeyconst char pkey return getboolforkeypkey falsebool userdefaultgetboolforkeyconst char pkey bool defaultvalue const char value nullptr tinyxml2xmlelement rootnode tinyxml2xmldocument doc tinyxml2xmlelement node node getxmlnodeforkeypkey rootnode doc find the node if node nodefirstchild value const charnodefirstchildvalue bool ret defaultvalue if value ret strcmpvalue true if doc delete doc return retint userdefaultgetintegerforkeyconst char pkey return getintegerforkeypkey 0int userdefaultgetintegerforkeyconst char pkey int defaultvalue const char value nullptr tinyxml2xmlelement rootnode tinyxml2xmldocument doc tinyxml2xmlelement node node getxmlnodeforkeypkey rootnode doc find the node if node nodefirstchild value const charnodefirstchildvalue int ret defaultvalue if value ret atoivalue ifdoc delete doc return retfloat userdefaultgetfloatforkeyconst char pkey return getfloatforkeypkey 00ffloat userdefaultgetfloatforkeyconst char pkey float defaultvalue float ret floatgetdoubleforkeypkey doubledefaultvalue return retdouble userdefaultgetdoubleforkeyconst char pkey return getdoubleforkeypkey 00double userdefaultgetdoubleforkeyconst char pkey double defaultvalue const char value nullptr tinyxml2xmlelement rootnode tinyxml2xmldocument doc tinyxml2xmlelement node node getxmlnodeforkeypkey rootnode doc find the node if node nodefirstchild value const charnodefirstchildvalue double ret defaultvalue if value ret utilsatofvalue if doc delete doc return retstdstring userdefaultgetstringforkeyconst char pkey return getstringforkeypkey string userdefaultgetstringforkeyconst char pkey const stdstring defaultvalue const char value nullptr tinyxml2xmlelement rootnode tinyxml2xmldocument doc tinyxml2xmlelement node node getxmlnodeforkeypkey rootnode doc find the node if node nodefirstchild value const charnodefirstchildvalue string ret defaultvalue if value ret stringvalue if doc delete doc return retdata userdefaultgetdataforkeyconst char pkey return getdataforkeypkey datanulldata userdefaultgetdataforkeyconst char pkey const data defaultvalue const char encodeddata nullptr tinyxml2xmlelement rootnode tinyxml2xmldocument doc tinyxml2xmlelement node node getxmlnodeforkeypkey rootnode doc find the node if node nodefirstchild encodeddata const charnodefirstchildvalue data ret defaultvalue if encodeddata unsigned char decodeddata nullptr int decodeddatalen base64decodeunsigned charencodeddata unsigned intstrlenencodeddata decodeddata if decodeddata retfastsetdecodeddata decodeddatalen if doc delete doc return ret void userdefaultsetboolforkeyconst char pkey bool value save bool value as string if true value setstringforkeypkey true else setstringforkeypkey false void userdefaultsetintegerforkeyconst char pkey int value check key if pkey return format the value char tmp50 memsettmp 0 50 sprintftmp d value setvalueforkeypkey tmpvoid userdefaultsetfloatforkeyconst char pkey float value setdoubleforkeypkey valuevoid userdefaultsetdoubleforkeyconst char pkey double value check key if pkey return format the value char tmp50 memsettmp 0 50 sprintftmp f value setvalueforkeypkey tmpvoid userdefaultsetstringforkeyconst char pkey const stdstring value check key if pkey return setvalueforkeypkey valuec strvoid userdefaultsetdataforkeyconst char pkey const data value check key if pkey return char encodeddata 0 base64encodevaluegetbytes static castunsigned intvaluegetsize encodeddata setvalueforkeypkey encodeddata if encodeddata frencodeddatauserdefault userdefaultgetinstance initxmlfilepath only create xml file one time the file exists after the program exit if isxmlfileexist createxmlfile return nullptr if userdefault userdefault new userdefault return userdefaultvoid userdefaultdestroyinstance cc safe delete userdefault x deprecateduserdefault userdefaultshareduserdefault return userdefaultgetinstance x deprecatedvoid userdefaultpurgeshareduserdefault return userdefaultdestroyinstancebool userdefaultisxmlfileexist file fp fopen filepathc str r bool bret false if fp bret true fclosefp return bretstdstring userdefaultgetvalueforkeypliststdstring key return testvoid userdefaultinitxmlfilepath if isfilepathinitialized filepath fileutilsgetinstancegetwritablepath xml file name isfilepathinitialized true create new xml filebool userdefaultcreatexmlfile bool bret false tinyxml2xmldocument pdoc new tinyxml2xmldocument if nullptrpdoc return false tinyxml2xmldeclaration pdeclaration pdocnewdeclarationnullptr if nullptrpdeclaration return false pdoclinkendchildpdeclaration tinyxml2xmlelement prootele pdocnewelementuserdefault root name if nullptrprootele return false pdoclinkendchildprootele bret tinyxml2xml success pdocsavefile filepathc str ifpdoc delete pdoc return bretconst string userdefaultgetxmlfilepath return filepathvoid userdefaultflushns cc endendif cc target platform cc platform ios cc platform cc platform androidend here are some calls i makestdstring textid itemname namestdstring word userdefaultgetinstancegetvalueforkeyplisttextid stdstring word userdefaultgetinstancegetvalueforkeyplistnodechild desc attribute value as stringstdstring word userdefaultgetinstancegetvalueforkeyplistitemname descat each of this lines i get undefined reference to cocos2duserdefaultgetvalueforkeypliststdstringmy cocos2dx game structure of code is like thismygameclassesmygamecocos2dcocosmygamemli have an androidmk file in the jni folder and in the mygamecocos2dcocos maybe it is a linkin problem but if it was a linking problem why i do not get undefined reference when calling other functions from userdefaults class editproblem solved there was an if in the top of the class so this class would compile only on ios platform now my method works,"['android', 'c++', 'ios']" +979902,how to change the base date for parsing two letter years with java 8 datetimeformatter if i use a pattern like dmyy for creating a java 8 datetimeformatter eg using datetimeformatterofpatternpattern which i will only use for parsing not formatting it will interpret all twoletter years as 20xx eg parsing a string like 13599 to be interpreted as 20990513 which in my case is wrong it was meant to be in the year 19in my application i am trying to parse dates from ocrd documents which could eg still be from the 90ies so having the old simpledateformat behavior of interpreting the date to be within 80 years before and 20 years after the current date fits me quite well but for various reasons i am still looking to switch the whole date parsing logic to the new java 8 datetimeformatterslooking through the java source code i see that this is all interpreted relative to the constant reducedprinterparserbase date but i see no way to change the value used when building my own formatter from a pattern is this simply not possible or have i missed some possibility of specifying the behavior for parsing twoletter years,['java'] +980020,font issue on ubuntu machine in parsing pdf file i have an application on my ubuntu 1404x machine this application does text mining on pdf files i suspect that it is using apache tika etcthe problem is that during its reading process i get the following warning 20150910 141535 warn fontmanager font not found couriernewpsmt20150910 141536 warn fontmanager font not found couriernewpsmt20150910 141933 warn fontmanager font not found helvetica20150910 141934 warn fontmanager font not found esqwsfhelvetica20150910 141934 warn fontmanager font not found esqwsfhelvetica20150910 141934 warn fontmanager font not found esqwsfhelveticahow can i get those fonts on my machine or is it some java lib that i am missing for fonts,['java'] +980074,how to thisable crossdevice action mirroring functionality of browsersync ghostmode our team used the gulpangular generator with yeoman to scaffold out our web app it uses browsersync to handle live reloads which we want however we just deployed to our development server and now when two developers are using the gulp serve command at the same time they both are shown the same window ie one developer types on one window it shows up in the other developers window as well i believe this is due to browsersyncs crossdevice testing capabilities however i am at a loss for how to thisable this feature if anyone knows how to do this preferably without thisabling our livereload functionality please let me knowbelow is the code for my serverjs file in the gulp folder which is the same as the one that comes with the gulpangular generator so hopefully this will help some peopleuse strictvar path requirepathvar gulp requiregulpvar conf requireconfvar browsersync requirebrowsersyncvar browsersyncspa requirebrowsersyncspavar util requireutilvar proxymiddleware requirehttpproxymiddlewarefunction browsersyncinitbasedir browser browser browser undefined default browser var routes null ifbasedir confpathssrc utilisarraybasedir basedirindexofconfpathssrc 1 routes bower components bower components var server basedir basedir routes routes you can add a proxy to your backend by uncommenting the line bellow you just have to configure a context which will we redirected and the target url example httpgetusers requests will be automatically proxified for more details and option servermiddleware proxymiddlewareusers target proxyhost jsonplaceholdertypicodecom browsersyncinstance browsersyncinit startpath server server browser browser browsersyncusebrowsersyncspa selector ngapp only needed for angular appsgulptaskserve watch function browsersyncinitpathjoinconfpathstmp serve confpathssrcgulptaskservethist build function browsersyncinitconfpathsthistgulptaskservee2e inject function browsersyncinitconfpathstmp serve confpathssrc gulptaskservee2ethist build function browsersyncinitconfpathsthist,['javascript'] +980181,logging with retrofit 2 i am trying to get the exact json that is being sent in the request here is my codeokhttpclient client new okhttpclientclientinterceptorsaddnew interceptor override public comsquareupokhttpresponse interceptchain chain throws ioexception request request chainrequest logestringformatnrequestnsnheadersns requestbodytostring requestheaders comsquareupokhttpresponse response chainproceedrequest return response retrofit retrofit new retrofitbuilder baseurlapi url addconverterfactorygsonconverterfactorycreate clientclientbuildbut i only see this in the logsrequestcomsquareupokhttprequestbody13ff4074dheaderscontenttype applicationvndlleventlistjsonhow am i supposed to do proper logging given the removal of setlog and setloglevel which we used to use with retrofit 1,['java'] +980240,procedural and data abstraction in ruby i am new to ruby i am learning abstraction principle in rubyas i understood procedural abstraction is hiding the implementation details from the user or simply concentrating on the essentials and ignoring the detailsmy concern is how to implement it1 is it a simple function calling just like this function to sort array params arrayarray to be sortdef my sortarray return array if arraysize 1 swapped false while swapped swapped false 0uptoarraysize2 do i if arrayi arrayi1 arrayi arrayi1 arrayi1 arrayi swapped true end end end arrayendand calling like this sorted array my sort1234123439012 how does data abstraction differs from encapsulationas i understood data abstraction is just hiding some member data from other classes,['ruby'] +980260,embedded dylibsframeworks are only supported on ios 80 and later for architecture armv7 i just upgraded from xcode 64 to xcode 7gm and am now getting the following warning when running my old projectembedded dylibsframeworks are only supported on ios 80 and later rpathxframeworkx for architecture armv7this problem only happens in xcode 7but when i run the project in xcode 64it has never happened,['ios'] +980342,c 60 null propagation operator property assignment this question has been completely overhauled in the interest of being thorough in explanationi have noticed what appears to be quite a poor limitation of the null propagation operator in c 60 in that you cannot call property setters against an object that has been null propagated though you can call property getters against an object that has been null propagated as you will see from the generated il which i have reflected into c there is nothing that should limit the ability to call property setters using null propagationto start with i have created a simple class with both java style getset methods and a property with public gettersetter accesspublic class person public personstring name datetime birthday name name public string name get set public void setnamestring name name name public string getname return name i have tested the ability of null propagation in the following test classpublic class program public static void mainstring args person person new personjoe bloggs datetimeparse01011991 this line does not work see documented error below personname john smith personsetnamejohn smith string name personname the lefthand side of an assignment must be a variable property or indexeryou may notice from this however that the java way of setting the name by calling setname works and you may also notice getting the value of a null propagated property also workslet us take a look at the c that was generated from this codepublic static void mainstring args person person new personjoe bloggs datetimeparse01011991 if person null personsetnamejohn smith string arg 33 0 person null personname nullnotice that when used against the setname method null propagation transforms to a straightforward if statement and that when used against the name property getter a ternary operator is used to either get the value of name or nullone thing i have noticed here is the behavior difference between using an if statement and using the ternary operator when using a setter using an if statement would work whereas using a ternary operator wouldntpublic static void mainstring args person person null if person null personname john smith personname person null john smith nullin this example i am using both an if statement and the ternary operator to check whether person is null before attempting to assign to its name property the if statement works as expected the statement using the ternary operator fails as expectedobject reference not set to an instance of an objectin my opinion the limitation comes from c 60s ability to transform null propagation into either an if statement or a ternary expression had it been designed to use only if statements property assignment would work via null propagationso far i have not seen one compelling argument as to why this should not be possible therefore i am still looking for answers,['c#'] +980423,generator as function argument can anyone explain why passing a generator as the only positional argument to a function seems to have special rulesif we have def fargs print success print argsthis works as expected f1 2success1 2this does not work as expected f2 1 file stdin line 1syntaxerror only named arguments may follow expressionthis works as expected f1 for x in 1 2success generator object genexpr at 0x7effe06bdcd0 2this works but i do not understand why should not it fail in the same way as 2 f2 1 for x in 1 successgenerator object genexpr at 0x7effe06bdcd0 2,['python'] +980476,influencing how entity classes are created in ef 6 codefirst from database weve been using ef 40 with a databasefirst approach using an edmx modelwere now upgrading to ef 613 and were investigating whether to go with or without that edmx model we definitely still want to be in control of our database schema so well be creating new tables etc with sql script and then generating the ef model either edmx or just code classes from the existing databaseduring my trials with visual studio 2013 i noticed an annoying point when ef 6 creates the classes from the existing database i have a customer class which links to a contact class three times once for the designcontact once for the salescontact and a third time for the supportcontact those are stored as designcontactid int etc columns in the customer tableyou can create those classes using this tsqlcreate table dbocontact contactid int not null constraint pk contact primary key clustered name varchar200 address varchar200 zipcode varchar20 city varchar100 phone varchar100create table dbocustomer customerid int not null constraint pk customer primary key clustered name varchar200 other properties designcontactid int constraint fk customer designcontact foreign key references dbocontactcontactid salescontactid int constraint fk customer salescontact foreign key references dbocontactcontactid supportcontactid int constraint fk customer supportcontact foreign key references dbocontactcontactidwhen creating the classes from the database i see thisthe customer class has my three xcontactid columns as fields that is as expectedef also generates three navigation properties of type contact but it calls them contact contact1 contact2 ughi am trying to find a way to get around those horribly bad named navigation properties these are bad becausetheir not intuitive which one points to which contact now are the stable or could they change over time if a fourth relationship to contact is introduced not sure cannot find any docs on thisjust their names are absolutely horrible why are not they called designcontact based on designcontactid salescontact based on salescontactid etcin ef 41 and up you were able to add t4 templates to the edmx and influence the generation process is that still possible somehow with ef6 if youre doing generate codefirst from existing database approach i could not find any blog post or article on that topic anymoreor is there another way to influence how ef generates the classes most notably the navigation properties can i define some kind of custom convention or something to influence this,['c#'] +980516,cannot find manifest defined receiver 1 of the time i have an aar that requires an entry in the consuming applications manifest during the bootstrapping of my library i inspect the androidmanifestxml for the required receiver and if i cannot find it i throw a runtimeexception as my library will not function properly this works on 99 of the installations but there are a small number of installations that throw this runtimeexception when the receiver clearly existsandroid v44 v511 are all included in the crash reports samsung lenovo nexus 4 nexus 5 etc are all affected devicesthe most interesting clue is that 75 of the crashes are on rooted devices speculation has been that this is a result of some custom rom or some other application that is interfering with the receivers detectioni have tested with a rooted nexus 5 w4 and it works fine i have tested with a stock nexus 5 w511 and it works fine i have tested with a nexus 5 running cyanogenmod 121 latest release and it works fine i applied all the privacy guard options available and it still works finereally at a loss and do not want to abandon the affected usersandroidmanifestxmlxml version10 encodingutf8manifest xmlnsandroid permission androidnameapplicationidpermissionc2d message androidprotectionlevelsignature usespermission androidnameapplicationidpermissionc2d message usespermission androidnamecomgoogleandroidc2dmpermissionreceive application receiver androidnamecomexamplemybroadcastreceiver androidexportedtrue androidpermissioncomgoogleandroidc2dmpermissionsend intentfilter action androidnamecomgoogleandroidc2dmintentreceive action androidnamecomgoogleandroidc2dmintentregistration category androidnameapplicationid intentfilter receiver activities etc removed for brevity applicationmanifestclasspublic class checksetup other methods removed for brevity public void checkmanifest listresolveinfo receiversinfo intent checkintent new intentapplicationcontext mybroadcastreceiverclass receiversinfo packagemanagerquerybroadcastreceiverscheckintent 0 boolean receiverfound false if receiversinfo null for resolveinfo resolveinfo receiversinfo if resolveinfoactivityinfo null resolveinfoactivityinfonameequalsmybroadcastreceiverclassgetname resolveinfoactivityinfopackagenameequalspackagename receiverfound true if receiverfound throw new runtimeexceptionstringformats definition not found in androidmanifestxml mybroadcastreceiverclassgetname,['android'] +980605,magnific popup facebook share button works just on second click i have a gallery with magnific popup with a share button as titlesrc this is called on button clickfunction callfacebookitem consolelogitem fbui method feed link item caption die besten partypics bei partynewsde functionresponse consolelogresponse this is the magnific popup callgallerymagnificpopup delegate a child items selector by clicking on it popup will open type image gallery enabledtrue tcounter curr von total preloadfalse image verticalfitfalse titlesrcfunctionitem var image itemelattrhref return a clasharefacebook onclickcallfacebookimage target blanki classfa fafacebookofficialinbspfoto teilena tclose schliessen tloading lade bild other optionsia m getting the href of the clicked image and pass it to the callfacebook function the first time i click the share button it just shows the standard ogtags when i close this window and click the share button again a it works the image shows up at the share dialog any ideas why,['javascript'] +980722,unexpected error while processing hprof file null i am having a massive memory issue on specific devices where a ton of memory is allocated out of nowhere i am trying to do a heapdump to figure out what is allocating the memory but when i attempt to open the heapdump file i get an error in android studiohprofview unexpected error while processing hprof file nulli have done some web searching but there are not any references to this error as far as i can tell i just need help getting the heap dump i can fix my app from thereedit i tried converting the dump file but it gave me another errorconvert android java heap dump unexpected error while converting heap dump error read 16710959 of 33177623 bytes,['android'] +980756,polymer swipepages create by repeat i try to use swipepages by template repeat swipepages template isdomrepeat itemsvalues swipepage div text to swipe div swipepage template swipepagesin the polymer i wrotecreated function consolelogthis thisvalues 123 it give me the error uncaught typeerror cannot set property values of undefined polymercreated polymerbase addfeature invokebehavior polymerbase addfeature dobehavior polymerbasecreatedcallback windowpolymer anonymous function polymerdomapidomapi addnodei cant get it work also use readyfunctionthisvalues123does not work in this case it throws exception that their is 0 pagesi think that the the swipepages does not receive the input after the template repeat runif i write it not by template it works okupdatethis is all the polymerelementdommodule idelementelement template swipepages template isdomrepeat itemsvalues swipepage div text div swipepage template swipepages template script polymer iselementelement created function thisvalues 123 ready function thisvalues123 scriptdommoduleif their is another swipe page element for polymer that can dynamically change i will be happy to knowif their is a hack solution like load all the element dynamically it will be also okthanks,['javascript'] +980910,what are the differences if any between es6 arrow functions and functions bound with functionprototypebind it seems to me that in es6 the following two functions are very nearly identicalfunction return thisbindthis return thisthe end result seems the same arrow functions produce a javascript function object with their this context bound to the same value as the this where they are createdobviously in the general sense functionprototypebind is more flexible than arrow functions it can bind to values other than the local this and it can bind any functions this at any point in time potentially long after it is initially created however i am not asking how bind itself is different from arrow functions i am asking how arrow functions differ from immediately calling bind with thisare there any differences between the two constructs in es6,['javascript'] +980945,why is not the c standard library already preincluded in any c source in c the standard library is wrapped in the std namespace and the programmer is not supposed to define anything inside that namespace of course the standard include files do not step on each other names inside the standard library so it is never a problem to include a standard headerthen why is not the whole standard library included by default instead of forcing programmers to write for example include vector each time this would also speed up compilation as the compilers could start with a prebuilt symbol table for all the standard headerspreincluding everything would also solve some portability problems for example when you include map it is defined what symbols are taken into std namespace but it is not guaranteed that other standard symbols are not loaded into it and for example you could end up in theory with stdvector also becoming availableit happens sometimes that a programmer forgets to include a standard header but the program compiles anyway because of an include dependence of the specific implementation when moving the program to another environment or just another version of the same compiler the same source code could however stop compilingfrom a technical point of view i can image a compiler just preloading with mmap an optimal perfecthash symbol table for the standard librarythis should be faster to do than loading and doing a c parse of even a single standard include file and should be able to provide faster lookup for std names this data would also be readonly thus probably allowing a more compact representation and also shareable between multiple instances of the compilerthese are however just shoulds as i never implemented thisthe only downside i see is that we c programmers would lose compilation coffee breaks and stack overflow visits editjust to clarify the main advantage i see is for the programmers that today despite the c standard library being a single monolithic namespace are required to know which subpart include file contains which functionclass to add insult to injury when they make a mistake and forget an include file still the code may compile or not depending on the implementation thus leading to nonportable programs,['c++'] +980995,send output of popen through websockets i am using popen with fgets to read the output of tcpdump asynchronouslythe below code should be run in the command line not with apache and viewing it in your browserhandle popentcpdump nnx rwhile true output fgetshandle print output nthe problem arises when i try to output this information via websocketswebsockets also use an infinite loop for managing its sockets ticks and messagesit looks something likewhile true socket selectreadwriteexcept1 foreach read as socket if socket thismaster client socket acceptsocketi send data through the websocket with websocketsendtoallmessagei cannot put the while loops one after the other because it will only run whichever loop i put first while true a while true b b will never be calledi cannot merge the while loops because the websockets slows down the reading of popen and vise versa while true a b if b is taking a long time to finish a will be slow to runwhat can i do in this situation i am open to the idea of threads communication between forked scripts or anything else,['php'] +981028,why does this java 8 method reference compile i am currently diving deeper into java 8 features like lambdas and method references playing around a bit brought me to the following examplepublic class consumertest private static final string names tony bruce steve thor public static void mainstring args arraysaslistnamesforeachobjectsrequirenonnull my question is why does the line inside the main method compile if i understood the thing correctly the referenced methods signature has to correspond to the functional interfaces sam signature in this case the consumer requires the following signaturevoid acceptt thowever the requirenonnull method returns t instead of void public static t t requirenonnullt obj,['java'] +981053,telnet gets empty output and loginpassword absent i try to write swift snippets to send commands to telnet but i need to log in firston osx i generated a telnet service launchctl load f systemlibrarylaunchdaemonstelnetplist after that i able to connect from other computers to ip x port 23for example from windows 7 telnet x 23darwinbsd fesslocal ttys009login snaggspasswordxsnaggs lurin the command line telnet asks me for the user and password after that i can run any linux commands so far so goodi wrote telnet module for android so osx telnet service works properly this means that i see login and password outputs so i am able to handle itnow i am stuck with ios swift i googled and found pretty good solution that should work in my casereceivingdatafromnsinputstreaminswiftusingsocketsinswiftlikeinjavaso i wrote my home workclass telnetclient nsobject nsstreamdelegate private var inputstream nsinputstream private var outputstream nsoutputstreamfunc initnetworkcommunication let host cfstring x let port uint32 23 var readstream unmanagedcfreadstream var writestream unmanagedcfwritestream cfstreamcreatepairwithsockettohostkcfallocatordefault host port readstream writestream var inputstream nsinputstream var outputstream nsoutputstream nsstreamgetstreamstohostwithnamex port 23 inputstream inputstream outputstream outputstream selfinputstream inputstream selfoutputstream outputstream selfinputstream readstreamtakeretainedvalue selfoutputstream writestreamtakeretainedvalue selfinputstreamdelegate self selfoutputstreamdelegate self selfinputstreamscheduleinrunloopnsrunloopcurrentrunloop formode nsdefaultrunloopmode selfoutputstreamscheduleinrunloopnsrunloopcurrentrunloop formode nsdefaultrunloopmode selfinputstreamopen selfoutputstreamopen func sendmessagemessagestring let data nsdata messagedatausingencodingnsasciistringencoding allowlossyconversion true nsutf8stringencoding let stream nsinputstream nsinputstreamdata data var buffer uint8count 8 repeatedvalue 0 streamopen if streamhasbytesavailable let result int streamreadbuffer maxlength buffercount selfoutputstreamwritebuffer maxlength buffercount printlnwrote to server message stream callback override method from nsstreamdelegatefunc streamastream nsstream handleevent eventcode nsstreamevent switch eventcode case nsstreameventerroroccurred nslogerroroccurred break case nsstreameventendencountered nslogendencountered break case nsstreameventnone nslognone break case nsstreameventhasbytesavailable nsloghasbytesavaible never enters here var buffer uint8count 4096 repeatedvalue 0 if astream selfinputstream while selfinputstreamhasbytesavailable var len selfinputstreamreadbuffer maxlength buffercount iflen 0 var output nsstringbytes buffer length buffercount encoding nsutf8stringencoding if output nslogserver said output break case nsstreameventallzeros nslogallzeros break case nsstreameventopencompleted nslogopencompleted called on initialisation break case nsstreameventhasspaceavailable nsloghasspaceavailable break default nslogdefault break first of all nothing happens when i try to call initnetworkcommunication i expect calling of func stream or i am wrong it should be nsstreameventhasbytesavailable state or i am wrongwhen i call sendmessagesnags i get response in stream that falls on case nsstreameventhasspaceavailable what does it meanmy expected results on connect i should get login output but get nothing,['ios'] +981083,is it possible to parse dates with both textstyleshort and textstylefull for the month a java 8 datetimeformatter created from a pattern like d m u can only parse dates with the month written in the style defined by textstyleshort eg 13 feb 2015 a datetimeformatter created from d m u can only parse dates with the month written in the style defined by textstylefull eg 13 february 2015in the old simpledateformat the difference between m and m was only important for formatting not for parsing so it was easily possible to create a parser that understood both the full and the short form of month namesis it possible to create a java 8 datetimeformatter that can also do this or do i always have to create two parsers one with the full and one with the short pattern,['java'] +981116,getting cpu usage of a specific service in c i want to know the cpu usage of a specific service in c performancecounter works fine with processperformancecounter counter new performancecounterprocess processor time myprocess true double result counternextvaluebut not with services performancecounter counter new performancecounterservice processor time myservice true double result counternextvalue,"['c#', '.net']" +981221,swift compiler error cannot invoke lockforconfiguration with an argument list of type i cannot seem to find anything on this i am getting the error cannot invoke lockforconfiguration with an argument list of type on the second line hereif let device capturedevice devicelockforconfiguration devicevideozoomfactor 10 cgfloatratiovalue deviceunlockforconfiguration printratiovalue,['ios'] +981313,python pandas how to move one row to the first row of a dataframe given an existing dataframe that is indexed df pddataframenprandomrandn10 5columnsa b c d e df a b c d e0 01316 0315019 0306728 06424 02945621 0769310 1277065 0735549 0900214 18263202 1561325 01571 0544697 0275880 04515643 0612561 0540457 2390871 2699741 05348074 1504476 2113726 0785208 1037256 02929595 0467429 1327839 1649 1144189 03228966 0306556 1668364 0036508 0596452 00667557 1689779 1469891 0068087 13231 03822358 0028250 2145618 05973 0473131 06380569 0633408 0791857 0933033 1485575 0021429 dfset indexa b c d ea 01316 0315019 0306728 06424 0294562 0769310 1277065 0735549 0900214 18263201561325 01571 0544697 0275880 0451564 0612561 0540457 2390871 2699741 05348071504476 2113726 0785208 1037256 0292959 0467429 1327839 1649 1144189 03228960306556 1668364 0036508 0596452 00667551689779 1469891 0068087 13231 0382235 0028250 2145618 05973 0473131 0638056 0633408 0791857 0933033 1485575 0021429how to move the 3rd row to the first row that says expected result b c d ea 1561325 01571 0544697 0275880 045156401316 0315019 0306728 06424 0294562 0769310 1277065 0735549 0900214 1826320 0612561 0540457 2390871 2699741 05348071504476 2113726 0785208 1037256 0292959 0467429 1327839 1649 1144189 03228960306556 1668364 0036508 0596452 00667551689779 1469891 0068087 13231 0382235 0028250 2145618 05973 0473131 0638056 0633408 0791857 0933033 1485575 0021429now the original first row should become the second row,['python'] +981355,why does android studio want me to use for each instead of for loop this question has been struggling me for time why sometimes does android studio want me to use for each instead of for loop because when i use for loop i get a warning that i could be using for each and with altenter it suggests me the autofixfor example let us suppose we have this codestring a string array abcforint i 0 i arraylength i a arrayi a i get a warning and this is the fix suggested by android studiofor string anarray array a anarray a is it more performant there is a reason i should get a warning for actually using just for loopor when it is better for loop or for each,['java'] +981371,cannot update buildgradle to use support library 2301 so i have updated my buildgradle filecompile comandroidsupportappcompatv72301compile comandroidsupportrecyclerviewv72301compile comandroidsupportcardviewv72301compile comandroidsupportdesign2301but when i try to sync the project this pops uperror25 13 failed to resolve comandroidsupportrecyclerviewv72301install repository and sync projectshow in fileshow in project structure dialogand the same for the other two repositoriesthen i try to click install repository and sync project and this error occursignoring unknown package filter extraandroidm2repositorywarning the package filter removed all packages there is nothing to install please consider trying to update again without a package filterand install failsi have installed build tools 2301 and everything for android m in sdk managertried rolling back to 2300 but it is the same whats wrong where did this package filter came from i dont think i changed anything except for buildgradle before this error occurededit i tried to delete build tools and install them again and while installing sdk manager log popped up with thispreparing to install archivesdownloading android sdk platformtools revision 2301installing android sdk platformtools revision 2301 stopping adb server failed code 1installed android sdk platformtools revision 2301downloading android sdk buildtools revision 2301installing android sdk buildtools revision 2301installed android sdk buildtools revision 2301stopping adb server succeededstarting adb server succeededdone 2 packages installeddone loading packages,['android'] +981461,how to add leading padding to view added inside an uistackview this is my setup i have an uiscrollview with leadingtop trialing edge set to 0 inside this i add an uistackview with this constraintsstackviewcenteryanchorconstraintequaltoanchorselectedcontactsscrollviewcenteryanchoractive true stackviewleadinganchorconstraintequaltoanchorselectedcontactsscrollviewleadinganchoractive trueinside the stack view i add some viewsmy issue is that because of the constraints the first view added to stack view will also have leading edge 0 what are the ways that i could add some padding to the first view without adjusting the scroll view constraints,['ios'] +981480,laravel how to log info to separate file how to specify a separate file for logging info in laravel 51any immediate help will be highly appreciable thanks,['php'] +981624,determine os newline in javascript i am generating a file for the user to download and i want to insert the correct newline characters for their platform n r or rni am aware of the following solutions but none solve my problem exactlyquerying navigatorplatform or navigatorappversion these properties are deprecated so i would prefer not to rely on themthere are specific approaches for firefox and nodejs these do not apply as i am creating a website and i would prefer if it worked on all browsersthere are ways to find the browsers newline characters but i am interested in the users platform these are different firefox always uses n regardless of the os,['javascript'] +981654,what are type hints in python 35 one of the talked about features in python 35 is said to be type hintsan example of type hints is mentioned in this article and this while also mentioning to use type hints responsibly can someone explain more about it and when it should be used and when not,['python'] +981700,optimization for newest ipad pro simulator i have installed the newest xcode 71 beta and trying to run my project on the ipad pro simulator everything is right and all of the features work correct but i have an issue with the screen sizeon the main screen of application i run the next lognslogf selfviewboundssizewidthi have 1024 for landscape orientation but when i create a new application in xcode 71 and run the same code on the main screen i get another value 1366today i plan to find diffs between project files created in old xcode 64 and newest beta 71 using araxis mergedo you now how to fix this issue for the my old project,"['ios', 'objective-c']" +981782,export html table to ppt on client side i want to know whether we have any jquery or javascript solution to convert html table to powerpointonly solution i got is html table export here we have all the export options but i want solution only for powerpoint i can use html table export but my concern is for one export i should use whole plugin is there a sample code only for ppt,"['javascript', 'jquery']" +981821,how to set unread notification count in navigationview of drawerlayout i have created one navigationview inside drawerlayout using android design support library androidsupportv4widgetdrawerlayout xmlnsandroid xmlnsapp androidididdrawer layout androidlayout widthmatch parent androidlayout heightmatch parent androidfitssystemwindowstrue other views androidsupportdesignwidgetnavigationview androidididnavigation androidlayout widthwrap content androidlayout heightmatch parent androidlayout gravitystart appmenumenumy navigation items androidsupportv4widgetdrawerlayoutmy navigation itemsxmlmenu xmlnsandroid group androidcheckablebehaviorsingle item androidididbookmarks drawer androidicondrawableic drawer bookmarks androidtitlestringbookmarks item androidididalerts drawer androidicondrawableic drawer alerts androidtitlestringalerts item androidididsettings drawer androidicondrawableic drawer settings androidtitlestringsettings group menunow i want to set unread notification counter for each item of navigationview like below image how to set unread notification counter on item of navigationview,['android'] +981884,collection to doublestream i am looking for most elegant way to create doublestream for using sum average etc from a listdouble at the moment i have such codelistdouble doubles getlistofdoublesdouble sum doublesstream maptodoubled d summaybe anyone could suggest a shorter way,['java'] +981910,can capturebyreference in expression templates coexist with type deduction expression templates are often used as an optimization technique to avoid the creation of temporary objects they defer constructing the complete object until the template is used in an assignment or initialization this finds use in string builders linear algebra packages etcto avoid expensive copies the expression template class can capture the bigger arguments by reference i will use qts qstringbuilder as an exampleit works when the references outlive the expression templateqstring foo qstringa qstringb qstringbuilderqconcatenableqstring qconcatenableqstringthe conversion and resolving of the expression template happens at the assignment the string temporaries outlive the assignmentalas we run into trouble as soon as the expression template type is inferred instead of the target type worksqstring foo qstring return qstringa qstringb failsqstring foo return qstringa qstringb and alsoauto foo qstringa qstringb foo holds references to strings that do not exist anymoreqstring bar foo oopsone solution is for the builder to hold copies of objects since qstrings here are implicitly shared their copying is cheap although still more expensive than holding a reference suppose though that the arguments were stdstring youd definitely not want to copy them unless necessaryis there any technique that could be used to detect that a complete template expression is not immediately resolved and must copy the data is thus far only held a reference tonote i am not asking about any particular existing implementation of expression templates i only use qstringbuilder as a motivating example this is not a qt question or an eigen question etc the title is the question pretty much,['c++'] +981938,why would an outer join be slower than separate queries i have a query that basically looks like thisselect from usersearches usleft outer join quotes q on qusersearchid usid and qquotenumber is not nuleft outer join containerdetails cd on cdquoteid qidleft outer join surcharges s on scontainerdetailid cdidwhere ussearchdate between begindate and enddategiven certain values of begindate and enddate i have a search that takes 30 seconds to return around 100k rows the ultimate goal is to populate some objects that have parentchildchildchild relationships so after some experimentation i found that i could speed up the query dramatically with the followingselect from usersearches usleft outer join quotes q on qusersearchid usid and qquotenumber is not nuleft outer join containerdetails cd on cdquoteid qidwhere ussearchdate between begindate and enddateselect cdid into cdidsfrom usersearches usleft outer join quotes q on qusersearchid usid and qquotenumber is not nuleft outer join containerdetails cd on cdquoteid qidwhere ussearchdate between begindate and enddateselect from surcharges sinner join cdids on scontainerdetailid cdidsiddrop table cdidsthis runs in 10 seconds which makes no sense to me surely it should be faster just to join the surcharges in the first place the surcharge table has the following indexespkalter table dbosurcharges add constraint pk dbosurcharges primary key clustered id ascix1create nonclustered index ix surcharge containerdetailid on dbosurcharges containerdetailid ascinclude ideverysinglecolumnabouttwelveofthemix2create nonclustered index ix containerdetailid on dbosurcharges containerdetailid ascto sum up why is it faster to do a separate query for my surcharges than it is to join them in the first placeedit here are the execution plans these are sqlplan files that you can open in sql studioquery 1 combinedquery 2 seperate,['sql'] +981940,android studio robolectric androidcontentresresourcesnotfoundexception no such label commyappstringapp name this issue i cannot seem to get rid of i have gone through probably 3 or 4 dozen articles and threads trying to resolve it i have outlined everything belowbasically the question is is the issue i am having a flaw with robolectric or is there some small step iam missing or i have a weird combination of plugins any guidance on this would be greatly appreciatedwindows 7versionsgradle 27android studio 132robolectric 30roboguice 3project dependencies dependencies classpath comandroidtoolsbuildgradle130 classpath comnewrelicagentandroidagentgradleplugin42440 classpath comgithubtripletgradleplaypublisher112 classpath orgmoallemigradleadvancedbuildversiongradleplugin150app dependenciesimport orgmoallemigradleinternalversioncodetypeapply plugin comandroidapplicationapply plugin newrelicapply plugin comgithubtripletplayapply plugin orgmoallemiadvancedbuildversionandroid def service account aaccountadef p12 key filemykeyp12signingconfigs releaseconfig a compilesdkversion 22buildtoolsversion 2201advancedversioning nameoptions versionmajor 6 versionminor advancedversioningversioncode codeoptions versioncodetype versioncodetypeauto increment one step defaultconfig applicationid commyapp minsdkversion 15 targetsdkversion 22 versioncode advancedversioningversioncode versionname advancedversioningversionnamebuildtypes def string string def url url release minifyenabled true proguardfiles getdefaultproguardfileproguardandroidtxt proguardrulespro signingconfig signingconfigsreleaseconfig staging minifyenabled true proguardfiles getdefaultproguardfileproguardandroidtxt proguardrulespro development minifyenabled false debug minifyenabled false testoptions unittestsreturndefaultvalues truedependencies compile filetreeinclude jar dir libs compile comandroidsupportappcompatv720 compile comgoogleandroidgmsplayservices42 compilename libraryrelease ext aar compile comsquareupokhttpokhttp240 compile comgooglecodegsongson231 compile orgroboguiceroboguice3 provided orgroboguiceroboblender3 testcompile junitjunit412 testcompile orgmockitomockitocore11019 testcompile orgrobolectricrobolectric30repositories flatdir dirs libscustom gradle runnerpublic class m1stroboelectricgradletestrunner extends robolectrictestrunner public m1stroboelectricgradletestrunnerclass testclass throws initializationerror supertestclass string buildvariant buildconfigflavorisempty buildconfigflavor buildconfigbuild type string intermediatespath buildconfigclassgetresource tostringreplacefile intermediatespath intermediatespath substring0 intermediatespathindexofclasses systemsetpropertyandroidpackage buildconfigapplication id systemsetpropertyandroidmanifest intermediatespath manifestsfull buildvariant androidmanifestxml systemsetpropertyandroidresources intermediatespath resmerged buildvariant systemsetpropertyandroidassets intermediatespath assets buildvariantoverride protected androidmanifest getappmanifestconfig config string manifestproperty systemgetpropertyandroidmanifest string resproperty systemgetpropertyandroidresources string assetsproperty systemgetpropertyandroidassets androidmanifest manifest new androidmanifestfsfilefrompathmanifestproperty fsfilefrompathresproperty fsfilefrompathassetsproperty manifestsetpackagenamecommyapp return manifesttest classrunwithm1stroboelectricgradletestrunnerclasspublic class mainactivitytest private mainactivity mactivity private button mbutton private textview mtextviewbeforepublic void setup mactivity robolectricbuildactivity mainactivityclasscreateget mbutton button mactivityfindviewbyidridsigninbutton mtextview textview mactivityfindviewbyidridlinkcontactissuethe following line of code is what is throwing the error mactivity robolectricbuildactivity mainactivityclasscreategetinitially i attempted to use the default robolectricgradletestrunner but kept receiving the resourcenotfound commyappstringapp name not found after perusing a ridiculous amount of articles and blogs i came across this and was able to get past it by implementing a custom runner this solved the app name issue sort of if on the test class i put configsdk 21 i receive the error iwas receiving initiallyandroidcontentresresourcesnotfoundexception no such label commyappstringapp nameat orgrobolectricutilactivitycontrollergetactivitytitleactivitycontrollerjava104at orgrobolectricutilactivitycontrollerattachactivitycontrollerjava49at orgrobolectricutilactivitycontroller1runactivitycontrollerjava121at orgrobolectricshadowsshadowlooperrunpausedshadowlooperjava304at orgrobolectricshadowscoreshadowsadapter2runpausedcoreshadowsadapterjava45at orgrobolectricutilactivitycontrollercreateactivitycontrollerjava118at orgrobolectricutilactivitycontrollercreateactivitycontrollerjava129at orgmembers1stmobilemainactivitytestsetupmainactivitytestjava32at sunreflectnativemethodaccessorimplinvoke0native methodat sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava62at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43at orgjunitrunnersmodelframeworkmethod1runreflectivecallframeworkmethodjava50at orgjunitinternalrunnersmodelreflectivecallablerunreflectivecallablejava12at orgjunitrunnersmodelframeworkmethodinvokeexplosivelyframeworkmethodjava47at orgjunitinternalrunnersstatementsrunbeforesevaluaterunbeforesjava24at orgrobolectricrobolectrictestrunner2evaluaterobolectrictestrunnerjava251at orgrobolectricrobolectrictestrunnerrunchildrobolectrictestrunnerjava188at orgrobolectricrobolectrictestrunnerrunchildrobolectrictestrunnerjava54at orgjunitrunnersparentrunner3runparentrunnerjava290at orgjunitrunnersparentrunner1scheduleparentrunnerjava71at orgjunitrunnersparentrunnerrunchildrenparentrunnerjava288at orgjunitrunnersparentrunneraccess0parentrunnerjava58at orgjunitrunnersparentrunner2evaluateparentrunnerjava268at orgrobolectricrobolectrictestrunner1evaluaterobolectrictestrunnerjava152at orgjunitrunnersparentrunnerrunparentrunnerjava363at orgjunitrunnerjunitcorerunjunitcorejava137at comintellijjunit4junit4ideatestrunnerstartrunnerwithargsjunit4ideatestrunnerjava78at comintellijrtexecutionjunitjunitstarterpreparestreamsandstartjunitstarterjava212at comintellijrtexecutionjunitjunitstartermainjunitstarterjava68at sunreflectnativemethodaccessorimplinvoke0native methodat sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava62at comintellijrtexecutionapplicationappmainmainappmainjava140if i leave the sdk alone i get robolectric doesnat support api 22so far iave triedcreating a custom buildconfig and passing that in perrecommendations on this robolectric threadsetting the packagename in the config per recommendations on this thread overloading the new applicationmanifest to send back the api levelsetting the targetsdk to 21 in my gradle filepretty much every combination of the previous steps results in the same error verified that the app name is in the valuesxml resources file generated by the test buildiave tried using mactivity robolectricsetupactivitymainactivityclassinstead ofmactivity robolectricbuildactivity mainactivityclasscreateget8 regular unit tests are working when being run,['android'] +982044,checking if httpstatuscode represents success or failure let us suppose i have the following variablesystemnethttpstatuscode status systemnethttpstatuscodeokhow can i check if this is a success status code or a failure onefor instance i can do the followingint code intstatusifcode 200 code 300 successi can also have some kind of white listhttpstatuscode succestatus new httpstatuscode httpstatuscodeok httpstatuscodecreated httpstatuscodeaccepted httpstatuscodenonauthoritativeinformation httpstatuscodenocontent httpstatuscoderesetcontent httpstatuscodepartialcontentifsuccestatuscontainsstatus linq successnone of these alternatives convinces me and i was hoping for a net class or method that can do this work for me such asbool issuccess httputilitiesissuccestatus,"['c#', '.net']" +982108,overriding doctrine trait properties i know you can override a trait method by declaring it in your class i was curious if was possible to over ride a trait property the same way is this safe to do its not in the documentation so i am hesitant to implement thisfrom the documentationan inherited member from a base class is overridden by a member inserted by a trait the precedence order is that members from the current class override trait methods which in turn override inherited methods,['php'] +982116,no autocomplete on html and css files in vim youcompleteme for some reason i get no autocomplete on html and css files all works well with other languages for example js ruby or pythoni have spent close to 2h today trying to fix it but to no avail i use vundle and youcompleteme to do all of this you can have a look at my vimrc file here i am on os x 10105 and my vim version is 74 installed via homebrew i also use macvim but it does not matter it does not work in either of them,"['html', 'css']" +982339,uiimageview missing images in launch screen on device i have an app that supports ios8 and later built in xcode 7 and i am using a xib for a launch screen i do not have launch images the view contains a single uilabel with the app version and 2 uiimageviews with images that are both present in imagesxcassets a logo and a splash imagethe uilabel and the logo image appear correctly when i launch the application but the splash image does not if i run the app on an ipad air 2 with ios9 i have tested on an air and a mini running ios8 and ios9 simulators for ipad 2 ipad air and ipad air 2 and the image appears correctly in all of thosei ran some basic troubleshooting to see if i could figure out what is going on but i have not been able to solve it and the only difference i can see between the image that is working and the one that is failing is when i added it to the assetsheres a rundown of what i knowthe uiimageview for the splash image is in the correct place at the correct size i can tell this because i set its background color to green just to make sure the view is there but the image does not appear so i am assuming that the view is not to blamesetting the uiimageview for the splash image to also use the logo image makes the logo image appear in the correct place for the view this also leads me to assume that the view is not to blamethe uiimage that i am using in the splash image view is used elsewhere in the app and appears fine in those other views the logo image is also used elsewhere in the app and appears fine so i am assuming that the image is valid and having it appear in other views is not a problemi have confirmed that the settings of the uiimages for the logo and splash in the xcassets file are the same they are set to universal any width and height multiple scale factors rendered as default there is one difference the logo has 1x 2x and 3x scales while the splash image only has 1x and 2x but i have also tried using uiimages with only 1x and 1x and 2x values in the uiview and they work if they were added to the project some time agoadding another image of a different size or format png and jpg to my xcassets and using that uiimage in the uiimageview for the splash image also fails to thisplayadding another uiimageview to the xib file and allocating it a uiimage that was already in the xcassets works the image appears in the loading screencopying and renaming the image files used for the logo and adding them to the project then using that uiimage in the splash view also fails to thisplayi have tried cleaning the project restarting the development machine and deleting the app from the air 2 and reinstalling it just in case that was a problemthese last three steps lead me to believe that there is some issue with images added after a certain point in the project files lifetime while i updated to xcode 7 yesterday the splash image was originally added in xcode 6 but the logo image also added in xcode 6 was added some months beforei have looked over the json files for the logo image and splash image and they appear to have the same format i have also trawled through the pbxproj file looking for differences and i cannot see anyso i was wondering if anyone had any idea why the launch screen might not thisplay these new images i am adding on the air 2 specifically other questions i have been reading through relating to images not appearing all seem to relate either to launch images or to images in xib files that have associated classes neither of which seems relevant here,"['ios', 'objective-c']" +982433,undocumented windows builtin pdf renderer capabilities using the windowsdatapdf namespace i am able to render pdf as an image without using any third party libraryif im not mistaken microsofts edge browser uses the same library to render pdfs windowsdatapdfdll by looking at the official windowsdatapdf documentation here i can see it is only about converting a page in a portable document format pdf document to an image filebut edge browser has search text capability when rendering a pdf which i cannot find anywhere in the windowsdatapdf librarymy question is is there any undocumented hence unofficial capabilities available to use in the windowsdatapdf namespace or somewhere else builtin in windows specifically the search text function which i assume i must be able to a extract the text of pdf so i can search on it and b get the xy of the string occurence on the rendered page so i can highlight it somehow,['c#'] +982514,issue with css minwidth and maxwidth i have an unordered list like in the example demoli thisplay block border 1px solid lightcoral liststyle none padding 4px 6px margin 5px width 150px minwidth 120px maxwidth 250px lilastchild width 200pxul li first item li li second item very long content li li third item li li this is 200px wideliuli want the li items to be at least 120px wide and at most 250px if i do not set the width they automatically set it to maxwidth but if i set it to 150px like in the demo then why does not the second one get its maximum allowed width ie 250px even if its content does not fit into a single lineis there something i am missing can this be done with pure css,"['html', 'css']" +982515,how to programmatically create users in aspnet 5 using identity ia m trying to create some users in a seed method but no lucki had used this example how to add role and users in aspnet mvc 5 but the usermanager seams to be instantiate in a different waylooking in the accountcontroller this instance is loaded in the constructor public accountcontroller usermanagerapplicationuser usermanager signinmanagerapplicationuser signinmanager iemailsender emailsender ismssender smssender bennerclicontext applicationdbcontext usermanager usermanager signinmanager signinmanager emailsender emailsender smssender smssender applicationdbcontext applicationdbcontext but my seed method lies on the mydbcontext classhow can i access the usermanager instance from there there are another ways to create users in vnext updateafter vlathislav karamfilov suggestion,"['c#', 'asp.net']" +982524,facebook js sdks fbapime method does not return the fields i expect in graph api v24 i am trying to get some basic information using facebook api but so far i only get the users name and id as in name juan fuentes id 123456 i need to get mor einformation like email first name last name and birthdaythis is my js codefunction facebooklogin fbloginfunctionresponse var token responseauthresponseaccesstoken var uid responseauthresponseuserid if responseauthresponse fbapime get access token token functionresponse consolelogresponse fbapiuid get access token token functionresponse consolelogresponse scope public profile and this is the button that activates ita idfblogin href onclickfacebooklogina,['javascript'] +982567,how to check for an empty object in an angularjs view in the controllers scope i have something likescopecard in the view i must check if my object is still an empty literal or if it contains some data in some fieldsi tried thisngshowangularequals cardandngshowangularequals cardbut it did not workare there any better ways how do you check if an object is empty or if it contains some fields,['javascript'] +982666,simplest way of running same select on multiple data in mysql i have pretty simple select let us sayselect countadded from users where added 20150730can i run this select in some simple way not only for the given date but also for let us say 7 days each row showing count up to that specific dayeditheres my sql building a tablecreate table users id int6 unsigned auto increment primary key added dateinsert into users added values 20150730insert into users added values 20150729insert into users added values 20150728insert into users added values 20150721insert into users added values 20150726insert into users added values 20150725insert into users added values 20150724insert into users added values 20150723insert into users added values 20150729insert into users added values 20150722insert into users added values 20150720insert into users added values 20140210i expect result like that date count 20150730 12 20150729 11 20150728 10 20150727 9 20150726 9 20150725 8 20150724 7,"['mysql', 'sql']" +982848,generate all combinations of mathematical expressions that add to target java homeworkinterview i have tried to solve the problem below for a coding challenge but could not finish it in 1 hour i have an idea on how the algorithm works but i am not quite sure how to best implement it i have my code and problem belowthe first 12 digits of pi are 314159265358 we can make these digits into an expression evaluating to 27182 first 5 digits of e as follows3141 5 9 26 5 3 5 8 27182or3 1 415 92 65358 27182notice that the order of the input digits is not changed operators or are simply inserted to create the expressionwrite a function to take a list of numbers and a target and return all the ways that those numbers can be formed into expressions evaluating to the targetfor example f314159265358 27182 should print3 1 415 92 65358 271823 1 4 159 26535 8 271823 1 4 159 26535 8 271823 14 15 9 26535 8 271823141 5 9 26 5 3 5 8 27182this problem is difficult since you can have any combination of numbers and you do not consider one number at a time i was not sure how to do the combinations and recursion for that step notice that parentheses are not provided in the solution however order of operations is preservedmy goal is to start off with say3then31 31 31 31 31then314 314 314 314 314 314 314 etcthen look at the every value in the list each time and see if it is target value if it is add that string to result listhere is my codepublic static liststring combinationsstring nums int target liststring tempresultlist new arrayliststring liststring realresultlist new arrayliststring string originalnum charactertostringnumscharat0 for int i 0 i numslength i if i 0 originalnum numscharati start off with a new number to decompose tempresultlistaddoriginalnum char originalnumchararray originalnumtochararray for int j 0 j originalnumchararraylength j go through every character to find the combinations maybe recursion here instead of iterative would be easier for string s tempresultlist try to evaluate int temp 0 if scontains scontains scontains scontains evaluate expression else just a number if temp target realresultlistadds tempresultlistclear return realresultlist could someone help with this problem looking for an answer with coding in it since i need help with the generation of possibilities,['java'] +983331,textinputlayout how to give padding or margin to hint i have to use textinputlayout of design support library in my project i want to give space between hint and edittext in textinputlayout i set margin and padding in textinputlayout and even inside edittext but both are not workso how to solve this issue here i attach screen shot and my codingstylestyle nametexthint parentbasetextappearanceappcompat item nameandroidtextsize18spitem item nameandroidtextcolorcolorgreenitemstylexml androidsupportdesignwidgettextinputlayout androidlayout widthmatch parent apphinttextappearancestyletexthint androidlayout margintop10dp androidlayout marginleft30dp androidlayout marginright30dp androidlayout heightwrap contentedittext androidlayout widthmatch parent androidlayout height50dp androidididedttxtemailaddress androidsinglelinetrue androidhintstringenter valid email androidpaddingleft20dp androidtextsize20sp androidbackgrounddrawablerounded commonandroidsupportdesignwidgettextinputlayout,['android'] +983347,how to render partial view in mvc5 via ajax call to a controller and return html how can use ajax to load a complete partial view rendered in html so i just set the divhtmli need the ajax call to call controller action that will render a complete partial view red and append it at the end of the currently loaded one i know how to append to dom and how to make ajax calls i need to know what is the best plumbing approach for this what type of actionresult should the action return and if there is an already builtin mechanism for this so to avoid reinventing the wheel,"['jquery', 'html']" +983413,eliminating warnings from scikitlearn i would like to ignore warnings from all packages when i am teaching but scikitlearn seems to work around the use of the warnings package to control this for examplewith warningscatch warnings warningssimplefilterignore from sklearn import preprocessingusrlocallibpython35sitepackagessklearnutilsfixespy66 deprecationwarning inspectgetargspec is deprecated use inspectsignature instead if order in inspectgetargspecnpcopy0usrlocallibpython35sitepackagessklearnutilsfixespy358 deprecationwarning inspectgetargspec is deprecated use inspectsignature instead if exist ok in inspectgetargspecosmakedirsargsam i using this module incorrectly or is sklearn doing something its not supposed to,['python'] +983482,clarification on function pointers in c the following code comes from example abo3c from insecure programming a see also why cast extern puts to a function pointer voidcharputsint mainint argvchar argc extern systemputs void fncharvoidcharsystem char buf256 fnvoidcharputs strcpybufargc1 fnargc2 exit1specifically this linevoid fncharvoidcharsystemi think that void fnchar sounds like a lambda but i know that it is notthen maybe this is only a play with parentheses where void fnchar is a declaration of a function and this function is referencing system but why does the char parameter have no name is this permitted,['c'] +983609,how to get response as string using retrofit without using gson or any other library in android i am trying to get response from the following api but i do not know how to get response as string so that i can use the string to parse and get the jsonobjectretrofit version usedretrofit200beta1i have tried this until nowpublic interface githubservice getusersuser public string listrepospathuser string usercallbackstring callback retrieving githubservice service retrofitcreategithubserviceclass servicelistreposusername new callbackstring override public void onresponseresponse response systemoutprintlnresponsetostring override public void onfailurethrowable t exceptioncaused by javalangillegalargumentexception could not locate call adapter for class javalangstring tried retrofitexecutorcalladapterfactory at retrofitutilsresolvecalladapterutilsjava67 at retrofitmethodhandlercreatecalladaptermethodhandlerjava49any help would be really appreciated,['android'] +983681,ios9 this application is modifying the autolayout engine from a background thread which can lead to engine corruption and weird crashes i have just dowloaded the latest xcode 71 beta and have started playing around with ios9i had an app working perfectly with no errors in ios8 but now i get the following error from overriding the drawrect method in a uitableviewcell class this application is modifying the autolayout engine from a background thread which can lead to engine corruption and weird crashes this will cause an exception in a future releasehere is the backtrace stack0 corefoundation 0x010a749f65 exceptionpreprocess 1651 libobjcadylib 0x0109dcfdeb objc exception throw 482 corefoundation 0x010a749e9d nsexception raiseformat 2053 foundation 0x0109b442e5 assertautolayoutonmainthreadonly 794 foundation 0x01099a4ece nsisengine withbehaviorsperformmodifications 315 uikit 0x010b9d425b uiviewadditionallayoutsupport withautomaticengineoptimizationthisabledifengineexists 586 uikit 0x010b9d4d9e uiviewadditionallayoutsupport updateconstraintsifneeded 2547 uikit 0x010b702760 uitableviewcellcontentview updateconstraintsifneeded 1858 uikit 0x010b9d5ab3 uiviewadditionallayoutsupport updateconstraintsatenginelevelifneeded 2729 uikit 0x010b1e6274 uiviewhierarchy updateconstraintsasnecessaryandapplylayoutfromengine 15910 uikit 0x010b1f5d84 uiviewcalayerdelegate layoutsublayersoflayer 71011 quartzcore 0x010ae1059a calayer layoutsublayers 14612 quartzcore 0x010ae04e70 zn2ca5layer16layout if neededepns 11transactione 36613 quartzcore 0x010ae04cee zn2ca5layer28layout and thisplay if neededepns 11transactione 2414 quartzcore 0x010adf9475 zn2ca7context18commit transactionepns 11transactione 27715 quartzcore 0x010ae26c0a zn2ca11transaction6commitev 48616 quartzcore 0x010ae2737c zn2ca11transaction17observer callbackep19 cfrunloopobservermpv 9217 corefoundation 0x010a675967 cfrunloop is calling out to an observer callback function 2318 corefoundation 0x010a6758d7 cfrunloopdoobservers 39119 corefoundation 0x010a66ae4c cfrunlooprunspecific 52420 corefoundation 0x010a71e011 cfrunlooprun 9721 sdwebimage 0x010971773c sdwebimagedownloaderoperation start 186822 foundation 0x0109961e47 nsoqschedule f 19423 libthispatchdylib 0x010d93849b thispatch client callout 824 libthispatchdylib 0x010d91e8ec thispatch queue drain 221525 libthispatchdylib 0x010d91de0d thispatch queue invoke 60126 libthispatchdylib 0x010d920a56 thispatch root queue drain 142027 libthispatchdylib 0x010d9204c5 thispatch worker thread3 128 libsystem pthreaddylib 0x010dc80a9d pthread wqthread 72929 libsystem pthreaddylib 0x010dc7e3dd start wqthread 13here is the drawrect method override func drawrectrect cgrect superdrawrectrect let cellrect rect values let buttonboxx cell margin cell margin2 let buttonboxy cellrectheight buttonboxheight let buttonboxwidth rectwidth cell margin 3 set button box let buttonboxrect cgrectmakebuttonboxx buttonboxy buttonboxwidth buttonboxheight let buttonbox uibezierpathroundedrect buttonboxrect byroundingcorners bottomright bottomleft cornerradii cgsizewidth corner radius height corner radius create the path uicolorwhitecolorsetfill set the fill to be white buttonboxfillmy understanding cf this question is that complicated calculations etc should be done on a background thread and the the update of the ui on the main thread because ui is not thread safehowever if i use the following override func drawrectrect cgrect superdrawrectrect let cellrect rect values let buttonboxx cell margin cell margin2 let buttonboxy cellrectheight buttonboxheight let buttonboxwidth rectwidth cell margin 3 set button box let buttonboxrect cgrectmakebuttonboxx buttonboxy buttonboxwidth buttonboxheight let buttonbox uibezierpathroundedrect buttonboxrect byroundingcorners bottomright bottomleft cornerradii cgsizewidth corner radius height corner radius create the path uicolorwhitecolorsetfill set the fill to be white thispatch asyncthispatch get main queue buttonboxfill i now get a cgcontext erroraerror cgcontextsavegstate invalid context 0x0 if you want to see the backtrace please set cg context show backtrace environmental variableerror cgcontextsetflatness invalid context 0x0 if you want to see the backtrace please set cg context show backtrace environmental variableerror cgcontextaddpath invalid context 0x0 if you want to see the backtrace please set cg context show backtrace environmental variableerror cgcontextdrawpath invalid context 0x0 if you want to see the backtrace please set cg context show backtrace environmental variableerror cgcontextrestoregstate invalid context 0x0 if you want to see the backtrace please set cg context show backtrace environmental variableerror cgcontextsavegstate invalid context 0x0 if you want to see the backtrace please set cg context show backtrace environmental variableerror cgcontextsetflatness invalid context 0x0 if you want to see the backtrace please set cg context show backtrace environmental variableerror cgcontextaddpath invalid context 0x0 if you want to see the backtrace please set cg context show backtrace environmental variableerror cgcontextdrawpath invalid context 0x0 if you want to see the backtrace please set cg context show backtrace environmental variableerror cgcontextrestoregstate invalid context 0x0 if you want to see the backtrace please set cg context show backtrace environmental variableany suggestions solution ok here is the deal i was loading an image into a uiimageview asynchronously but not painting it in the ui on the main thread but on a background thread furthermore i was calling setneedsthisplay on the uitableviewcell after adding the image to the ui thus calling the drawrect method againa but this time on the background thread,['ios'] +983737,how to show the static blocks in magento 2 i am creating a magento 2 themei want to thisplay the custom blocks on the cms homepagehow can i dothank you very much,['php'] +983792,variable was written but never read im getting the following warning variable istaken was written to but never read on the following code func textfieldshouldendeditingtextfield uitextfield bool var istaken bool false if textfield usernametxt var query pfqueryclassname user query pfqueryclassname user querywherekeyusername equalto usernametxttext queryfindobjectsinbackgroundwithblock objects anyobject error nserror in if error nil if objectscount 0 istaken true else printusername is available else printerror return true why am i getting the warning and how do i do away with it,['ios'] +983804,xcode 7 linker command failed with exit code 1 use v to see invocation again im testing my app on ios simulator of xcode 7 and its all right o but when i try test in my iosdevice a iphone 5s with ios 9i updated the xcode 7 and ios9 today 09162015 and before that with ios 84 was working fineobs the ios deployment target on xcode project is ios 9i already try this like suggested in this postclang error linker command failed with exit code 1 use v to see invocation when doing unit test on xcode but does not workthe guy of this post just created a new projectxcode 7 linker command failed with exit code 1 use v to see invocation but is not a solution to me because my project is huge,['ios'] +983910,object refrence not set to an instance of an object when i create new android app visual studio in a visual studio 2015 xamarin android sdk jdk 17 and emulator are installed and xamarin has all green checked items in toolsoptionsxamarin but when i try to create blank app android vs shows an error object reference not set to an instance of an objectthen new project fail to create and solution explorer will be empty how could i solve it thanks a lot,['android'] +983943,pass a dictionary parameter in web api i am trying to pass a dictionarystringstring object as a parameter to my web api method but if i inspect the log file it always comes through with a count of 0web api methodhttppostactionnamesendpostpublic void sendpostfrombody dictionarystringstring values using var sw new streamwriterfposttesttxt true swwritelinenumber of items in the dictionary valuescount logic which calls the web apipublic httpresponsemessage sendstring uri string value httpresponsemessage responsemessage null using var client new httpclient clientbaseaddress new uriuri clientdefaultrequestheadersacceptclear clientdefaultrequestheadersacceptaddnew mediatypewithqualityheadervalueapplicationjson var content new formurlencodedcontent new dictionarystring string value value responsemessage clientpostasyncuri contentresult return responsemessage,"['c#', 'asp.net']" +983947,does webkitfilter grayscale100 cause bugs before you start readingapparently the bug has been fixed now i am not experiencing the error anymore in chrome 520274382 and presumably also in earlier versionsoriginal questioni am creating a extension for chrome and i made a context menu which has a few optionstechnically it works fine the problem is that every entry of the menu has an icon assigned to it styled with css normally the icons are grey until they are hovered this has worked fine for a long time and since yesterday it is broken and i dont know what i have changed that could have caused thisthe status now is that when i am opening the menu happens via jquery it is just a div which is hidden most of the time all icons are invisible until i hover them so if i move my mouse over call now it looks like thiswhen i unhover it the icon stays visible and looks like its supposed to so basically i can show all of the icons when i hover them oncenow there are three things which are giving me a complete brainfucki am sure persistent changes means something is in state a you hover it and it gets into state b and stays in state bor goes to state c when you unhover it again are impossible in css but thats exactly whats happening here andwhen i open the chrome developer tools and change anything in the css settingsbeforeafterevery icon is thisplayed correctly not in case of the changed css property of course but it stays visible when you turn it back on it is completely irrelevant which of the css properties you change whenever you change it the images pop upthe context menu is a div it gets hidden and shown through jquerys slideup and slidedown functions so it never gets reset just hidden and shown from time to time now when i hover all of the icons to make them visible close the menu clicking somewhere otuside it and open it again the icons are invisible now i experimented with the css properties in my css file and i found the following my icons are grayscaled when they are not hovered in css it looks like thiswebkitfilter grayscale100filter grayscale100filter grayfilter urldataimagesvgxmlutf8svg version11 xmlns height0filter idgreyscalefecolormatrix typematrix values03 03 03 0 0 03 03 03 0 0 03 03 03 0 0 0 0 0 1 0 filtersvggreyscalenow when i comment out webkitfilter grayscale100 the icons are not grayed out of course but they show up like they shouldso how the f does this work,"['javascript', 'html', 'css']" +983966,ruby each vs while loop performance trying to resolve a basic problem of algorithm in ruby and testing performance just in case the algorithm aims to find the smallest positive number that is evenly divisible by all of the numbers from 1 to 20heres the code def remaindernumber with while divisor 2 while divisor 21 return false unless number divisor 0 divisor 1 end trueenddef remaindernumber with each 220each do divisor return false unless number divisor 0 end trueendnumber 180 0 0while number 10 0 0 0 if remainder number puts number break end number 1endon my computer with while version ruby takes around 10 seconds with each version it takes between 70 and 80 seconds to resolve code does the exact same thing gives same result why such a difference in performance,['ruby'] +983973,sort array by the thistance to a number for example if you have a set of numbers 54321 and you want all numbers ordered by closest to 3 the result would be 32451i have tried using uasort and written a custom sort function to take the fixed digit3 in this case but it did not work i wrote the function to take the fixed digit away from the current two digits being compared and applied abs to themi need a way where i can compare which number of comparing how close the current number being accessed is and to slot it in the right place in the arrayany ideas can this be achieved using uasort,['php'] +984056,move up keyboard when editing uitextfield on ios9 for my keyboards to move up to uncover uitextfield in my ios app i used to implement this answer on ios7 and 8 and it has worked perfectly for now however on ios 91 it does not work anymoreto be more accurate even if the background view does move up the uitextfield does notany idea of what has changed so much since ios9 and ios 91,"['ios', 'objective-c']" +984070,why are operators in the expression new dategettime applied in strict lefttoright order the following expression seems to work as intended and return the current timestampnew dategettimehowever i cannot understand why operators are applied in strict lefttoright order heremdn says the member operator has higher priority than new this would mean that must be applied before new so the expression should be evaluated asnew dategettimebut in fact it is evaluated asnew dategettimei guess there has to be something i have overlooked but i cannot understand whatnote i do not actually use this expression i prefer datenow method it is just my curiosity,['javascript'] +984164,how to structure redux componentscontainers iam using redux and iam not sure about how to organize my components i think the best is to keep them in folders with the name of the main component as the name of the folder and all inner components inside components common things like links header titles etc form buttons inputs etc player all small components forming the player indexjs this one is the top layout component playbtnjs artistnamejs songnamejs episode another componentthen in the containers folder iave one container per page that are the only ones i am actually connecting to reduxcontainers homepageappjs episodepageappjs and then the actions are one per each top component instead of one per page so in the page container that i connect to redux i pass all the actions of the components used in that page for exampleactions playerjs episodejs am i doing this right i have not found much information about it googling and the ones i have found i think they are limited to small projectsthanks,['javascript'] +984225,is there a cost to entering and exiting a c checked block consider a loop like thisfor int i 0 i end i do somethingif i know that i would not overflow but i want a check against overflow truncation etc in the do something part am i better off with the checked block inside or outside the loopfor int i 0 i end i checked do something orchecked for int i 0 i end i do somethingmore generally is there a cost to switching between checked and unchecked mode,['c#'] +984409,ios 9 xcode 7 application appears with black bars on top and bottom installed the app on iphone 6 ios9 and here is what happened notice black bars on top and bottom it works just fine on ios8 how i can fix iti have tried building with xcode 64 7 same resultiphone 5 used to run iphone 4 apps like this,['ios'] +984432,using avaudioengine to schedule sounds for lowlatency metronome i am creating a metronome as part of a larger app and i have a few very short wav files to use as the individual sounds i would like to use avaudioengine because nstimer has significant latency problems and core audio seems rather daunting to implement in swift i am attempting the following but i am currently unable to implement the first 3 steps and i am wondering if there is a better waycode outline create an array of file urls according to the metronomes current settings number of beats per bar and subdivisions per beat file a for beats file b for subdivisionsprogrammatically create a wav file with the appropriate number of frames of silence based on the tempo and the length of the files and insert it into the array between each of the soundsread those files into a single audiobuffer or audiobufferlistaudioplayerschedulebufferbuffer attimenil optionsloops completionhandlernilso far i have been able to play a looping buffer step 4 of a single sound file but i have not been able to construct a buffer from an array of files or create silence programmatically nor have i found any answers on stackoverflow that address this so i am guessing that this is not the best approachmy question is is it possible to schedule a sequence of sounds with low latency using avaudioengine and then loop that sequence if not which frameworkapproach is best suited for scheduling sounds when coding in swift,['ios'] +984494,classpath issue between jettymavenplugin and tomcatjdbc 809 leading to serviceconfigurationerror i am working on an app using jettymavenplugin932v20150730tomcatjdbc808 which has tomcatjuli as dependencyafter trying to upgrade the tomcatjdbc jar to any version beyond 809 i get the following errorjavautilserviceconfigurationerror orgapachejulilogginglog provider orgeclipsejettyapachejspjulilog not a subtypelooking the changelog between those 2 versions i have found something that looks suspiciousadd a simple serviceloader based thiscovery mechanism to the juli logfactory to make it easier to use juli and tomcat components that depend on juli such as jasper independently from tomcat patch provided by greg wilkins marktalso i have found that a new system property was introduced in the apache tomcat jdbc connection poolorgapachetomcatjdbcpoolonlyattemptcurrentclassloadercontrols classloading of dynamic classes such as jdbc drivers interceptors and validators if set to false default value the pool will first attempt to load using the current loader ie the class loader that loaded the pool classes and if class loading fails attempt to load using the thread context loader set this value to true if you wish to remain backwards compatible with apache tomcat 808 and earlier and only attempt the current loader if not set then the default value is false unfortunately starting the plugin with jettyrun using this property did not resolve the issueany help would be appreciated thanksstack trace and dependencies tree caused by javautilserviceconfigurationerror orgapachejulilogginglog provider orgeclipsejettyapachejspjulilog not a subtype at javautilserviceloaderfailserviceloaderjava239 at javautilserviceloaderaccess300serviceloaderjava185 at javautilserviceloaderlazyiteratornextserviceserviceloaderjava376 at javautilserviceloaderlazyiteratornextserviceloaderjava404 at javautilserviceloader1nextserviceloaderjava480 at orgapachejulilogginglogfactorylogfactoryjava78 at orgapachejulilogginglogfactorylogfactoryjava66 at orgapachetomcatjdbcpooldatasourcefactorydatasourcefactoryjava58 at localristrettopersistencedatasourcemailmaildatasourceconfigurationdatasourcemaildatasourceconfigurationjava31 at localristrettopersistencedatasourcemailmaildatasourceconfigurationenhancerbyspringcglib497970ddcglibdatasource0 at localristrettopersistencedatasourcemailmaildatasourceconfigurationenhancerbyspringcglib497970ddfastclassbyspringcglib2ba2dde9invoke at orgspringframeworkcglibproxymethodproxyinvokesupermethodproxyjava228 at orgspringframeworkcontextannotationconfigurationclassenhancerbeanmethodinterceptorinterceptconfigurationclassenhancerjava309 at localristrettopersistencedatasourcemailmaildatasourceconfigurationenhancerbyspringcglib497970datasource at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava62 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43 at javalangreflectmethodinvokemethodjava497 at orgspringframeworkbeansfactorysupportsimpleinstantiationstrategyinstantiatesimpleinstantiationstrategyjava162 at orgspringframeworkbeansfactorysupportconstructorresolverinstantiateusingfactorymethodconstructorresolverjava588 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactoryinstantiateusingfactorymethodabstractautowirecapablebeanfactoryjava19 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorycreatebeaninstanceabstractautowirecapablebeanfactoryjava1014 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorydocreatebeanabstractautowirecapablebeanfactoryjava504 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorycreatebeanabstractautowirecapablebeanfactoryjava476 at orgspringframeworkbeansfactorysupportabstractbeanfactory1getobjectabstractbeanfactoryjava303 at orgspringframeworkbeansfactorysupportdefaultsingletonbeanregistrygetsingletondefaultsingletonbeanregistryjava230 at orgspringframeworkbeansfactorysupportabstractbeanfactorydogetbeanabstractbeanfactoryjava299 at orgspringframeworkbeansfactorysupportabstractbeanfactorygetbeanabstractbeanfactoryjava194 at orgspringframeworkbeansfactorysupportdefaultlistablebeanfactoryfindautowirecandidatesdefaultlistablebeanfactoryjava1120 at orgspringframeworkbeansfactorysupportdefaultlistablebeanfactorydoresolvedependencydefaultlistablebeanfactoryjava1044 at orgspringframeworkbeansfactorysupportdefaultlistablebeanfactoryresolvedependencydefaultlistablebeanfactoryjava942 at orgspringframeworkbeansfactorysupportconstructorresolverresolveautowiredargumentconstructorresolverjava813 at orgspringframeworkbeansfactorysupportconstructorresolvercreateargumentarrayconstructorresolverjava741 at orgspringframeworkbeansfactorysupportconstructorresolverinstantiateusingfactorymethodconstructorresolverjava464 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactoryinstantiateusingfactorymethodabstractautowirecapablebeanfactoryjava19 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorycreatebeaninstanceabstractautowirecapablebeanfactoryjava1014 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorydocreatebeanabstractautowirecapablebeanfactoryjava504 at orgspringframeworkbeansfactorysupportabstractautowirecapablebeanfactorycreatebeanabstractautowirecapablebeanfactoryjava476 at orgspringframeworkbeansfactorysupportabstractbeanfactory1getobjectabstractbeanfactoryjava303 at orgspringframeworkbeansfactorysupportdefaultsingletonbeanregistrygetsingletondefaultsingletonbeanregistryjava230 at orgspringframeworkbeansfactorysupportabstractbeanfactorydogetbeanabstractbeanfactoryjava299 at orgspringframeworkbeansfactorysupportabstractbeanfactorygetbeanabstractbeanfactoryjava194 at orgspringframeworkcontextsupportabstractapplicationcontextgetbeanabstractapplicationcontextjava956 at orgspringframeworkcontextsupportabstractapplicationcontextfinishbeanfactoryinitializationabstractapplicationcontextjava747 at orgspringframeworkcontextsupportabstractapplicationcontextrefreshabstractapplicationcontextjava480 at orgspringframeworkwebcontextcontextloaderconfigureandrefreshwebapplicationcontextcontextloaderjava434 at orgspringframeworkwebcontextcontextloaderinitwebapplicationcontextcontextloaderjava306 at orgspringframeworkwebcontextcontextloaderlistenercontextinitializedcontextloaderlistenerjava106 at orgeclipsejettyserverhandlercontexthandlercallcontextinitializedcontexthandlerjava798 at orgeclipsejettyservletservletcontexthandlercallcontextinitializedservletcontexthandlerjava530 at orgeclipsejettyserverhandlercontexthandlerstartcontextcontexthandlerjava771 at orgeclipsejettyservletservletcontexthandlerstartcontextservletcontexthandlerjava342 at orgeclipsejettywebappwebappcontextstartwebappwebappcontextjava1368 at orgeclipsejettymavenpluginjettywebappcontextstartwebappjettywebappcontextjava320 at orgeclipsejettywebappwebappcontextstartcontextwebappcontextjava1335 at orgeclipsejettyserverhandlercontexthandlerdostartcontexthandlerjava735 at orgeclipsejettyservletservletcontexthandlerdostartservletcontexthandlerjava259 at orgeclipsejettywebappwebappcontextdostartwebappcontextjava511 at orgeclipsejettymavenpluginjettywebappcontextdostartjettywebappcontextjava403 at orgeclipsejettyutilcomponentabstractlifecyclestartabstractlifecyclejava68 at orgeclipsejettyutilcomponentcontainerlifecyclestartcontainerlifecyclejava132 at orgeclipsejettyutilcomponentcontainerlifecycledostartcontainerlifecyclejava114 at orgeclipsejettyserverhandlerabstracthandlerdostartabstracthandlerjava61 at orgeclipsejettyserverhandlercontexthandlercollectiondostartcontexthandlercollectionjava161 at orgeclipsejettyutilcomponentabstractlifecyclestartabstractlifecyclejava68 at orgeclipsejettyutilcomponentcontainerlifecyclestartcontainerlifecyclejava132 at orgeclipsejettyutilcomponentcontainerlifecycledostartcontainerlifecyclejava114 at orgeclipsejettyserverhandlerabstracthandlerdostartabstracthandlerjava61 at orgeclipsejettyutilcomponentabstractlifecyclestartabstractlifecyclejava68 at orgeclipsejettyutilcomponentcontainerlifecyclestartcontainerlifecyclejava132 at orgeclipsejettyserverserverstartserverjava405 at orgeclipsejettyutilcomponentcontainerlifecycledostartcontainerlifecyclejava106 at orgeclipsejettyserverhandlerabstracthandlerdostartabstracthandlerjava61 at orgeclipsejettyserverserverdostartserverjava372 at orgeclipsejettyutilcomponentabstractlifecyclestartabstractlifecyclejava68 at orgeclipsejettymavenpluginabstractjettymojostartjettyabstractjettymojojava457 at orgeclipsejettymavenpluginabstractjettymojoexecuteabstractjettymojojava328 at orgeclipsejettymavenpluginjettyrunmojoexecutejettyrunmojojava170 at orgapachemavenplugindefaultbuildpluginmanagerexecutemojodefaultbuildpluginmanagerjava132 at orgapachemavenlifecycleinternalmojoexecutorexecutemojoexecutorjava208 at orgapachemavenlifecycleinternalmojoexecutorexecutemojoexecutorjava153 at orgapachemavenlifecycleinternalmojoexecutorexecutemojoexecutorjava145 at orgapachemavenlifecycleinternallifecyclemodulebuilderbuildprojectlifecyclemodulebuilderjava116 at orgapachemavenlifecycleinternallifecyclemodulebuilderbuildprojectlifecyclemodulebuilderjava80 at orgapachemavenlifecycleinternalbuildersinglethreadedsinglethreadedbuilderbuildsinglethreadedbuilderjava51 at orgapachemavenlifecycleinternallifecyclestarterexecutelifecyclestarterjava120 at orgapachemavendefaultmavendoexecutedefaultmavenjava347 at orgapachemavendefaultmavenexecutedefaultmavenjava154 at orgapachemavenclimavencliexecutemavenclijava582 at orgapachemavenclimavenclidomainmavenclijava214 at orgapachemavenclimavenclimainmavenclijava158 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava62 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43 at javalangreflectmethodinvokemethodjava497 at orgcodehausplexusclassworldslauncherlauncherlaunchenhancedlauncherjava289 at orgcodehausplexusclassworldslauncherlauncherlaunchlauncherjava229 at orgcodehausplexusclassworldslauncherlaunchermainwithexitcodelauncherjava415 at orgcodehausplexusclassworldslauncherlaunchermainlauncherjava356 at orgcodehausclassworldslaunchermainlauncherjava46 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava62 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43 at javalangreflectmethodinvokemethodjava497 at comintellijrtexecutionapplicationappmainmainappmainjava140info orgspringframeworkdataspringdatajpajar182releasecompile info orgspringframeworkdataspringdatacommonsjar1102releasecompile info orgspringframeworkspringormjar417releasecompile info orgspringframeworkspringjdbcjar417releasecompile info orgspringframeworkspringtxjar417releasecompile info orgaspectjaspectjrtjar186compile info orgpostgresqlpostgresqljar941202jdbc42compile info orgapachetomcattomcatjdbcjar809compile info orgapachetomcattomcatjulijar809compile info orghibernatehibernateentitymanagerjar501finalcompile info orgjbossloggingjbossloggingjar330finalcompile info orghibernatehibernatecorejar501finalcompile info antlrantlrjar277compile info orgjbossjandexjar122finalcompile info dom4jdom4jjar161compile info xmlapisxmlapisjar10b2compile info orghibernatecommonhibernatecommonsannotationsjar500finalcompile info orghibernatejavaxpersistencehibernatejpa21apijar100finalcompile info orgapachegeronimospecsgeronimojta 11 specjar1compile info orgjavassistjavassistjar3181gacompile info comfasterxmljacksoncorejacksondatabindjar261compile info comfasterxmljacksoncorejacksonannotationsjar261compile info comfasterxmljacksoncorejacksoncorejar261compile info orgslf4jjcloverslf4jjar1712compile info orgslf4jjultoslf4jjar1712compile info orgslf4jlog4joverslf4jjar1712compile info orgslf4jslf4japijar1712compile info chqoslogbacklogbackclassicjar113compile info chqoslogbacklogbackcorejar113compile info orgwicketstuffwicketstufflogbackjar6200compile info orgapachecommonscommonslang3jar34compile info orgapachecommonscommonscollections4jar40compile info commonsiocommonsiojar24compile info commonscodeccommonscodecjar110compile info commonsbeanutilscommonsbeanutilsjar192compile info commonscollectionscommonscollectionsjar321compile info comgoogleguavaguavajar180compile info junitjunitjar412test info orghamcresthamcrestcorejar13test info orgspringframeworkspringtestjar417releasetest info orgspringframeworkspringcorejar417releasecompile info orgspringframeworkspringwebjar417releasecompile info orgspringframeworkspringaopjar417releasecompile info aopallianceaopalliancejar10compile info orgspringframeworkspringbeansjar417releasecompile info orgspringframeworkspringcontextjar417releasecompile info orgspringframeworkspringexpressionjar417releasecompile info javaxjavaeewebapijar70provided,['java'] +984588,xcode 7 dropbox core api simply thisable bitcode i have been using dropbox core api in my ios app for quite a while now after updating to xcode 7 i received the following error when i try to compile my projectld frameworksdropboxiosdropboxsdkframeworkdropboxsdk does not contain bitcode you must rebuild it with bitcode enabled xcode setting enable bitcode obtain an updated library from the vendor or thisable bitcode for this target i know what bitcode is and what it is good for the error can be solved by simply setting the enable bitcode option to no in the targets build settings after this everything compiles without any error and the app runs without any problemso far so good but is this the right solution i checked the dropbox page for an updated version of the sdk but i already use the latest versionthe project contains some other target for an app widget watch extension etc which do not use the dropbox sdk what option for enable bitcode should be used here is is for some reason better use the same value noin my case for all targets does it make any sense to enable bitcode for watch and widget targets if the the main app target does not use bitcodewhat is the best practice here,"['ios', 'objective-c']" +984619,whats the at symbol in the redux connect decorator i am learning redux with react and stumbled upon this code i am not sure if it is redux specific or not but i have seen the following code snippet in one of the examplesconnectstate return key stateab while the functionality of connect is pretty straightforward but i do not understand the before connect it is not even a javascript operator if i am not wrongcan someone explain please what is this and why is it usedupdate it is in fact a part of reactredux which is used to connects a react component to a redux store,['javascript'] +984623,cannot find keyplane that supports type 4 for keyboard iphoneportraitnumberpad i recently upgraded to xcode 7 and today i noticed this warning in the log when i tapped a text field and the keyboard popped upcannot find keyplane that supports type 4 for keyboard iphoneportraitnumberpad using 563160167 portrait iphonesimplepad defaulti have a uitextfield that i set up in interface builder and configured it also in ib to thisplay a number pad keyboard i also noticed that for a normal type of keyboard this message does not appeari searched for a solution but none of what i found worked so farthe simulator settings under simulatorhardwarekeyboard arechecked for uses same layout as os xunchecked for the other twoany ideas,['ios'] +984680,how to set up cordova plugin project with ide support i have been struggling to set up my cordova plugin project mainly due the facts thatplugins need to be in a separate folder away from the main projectwhen i use for example cordova build android to build the project cordova copies the java file from my plugin folder and put it into platformsandroidsrc folderthus i should not modify my plugins java file in the android project manually i have to write my code in my plugin folderbut i cannot import plugin folder into the ide project thus i do not have code completionit is basically impossible to write javaobjectivec without ide supporthow can i set up an idefor example for android studio project with code completion for my plugin development,"['java', 'android']" +984699,android toolbar moves up when keyboard appears i am creating a chat based ui screen where i have toolbar and recyclerview for chat messages and reply msg layoutwhenever edittext get focus it moves up the toolbar instead i would like to resize the recyclerviewsome of the stackoverflow answers suggest to place a empty scrollview below the toolbar but it did not work activity androidnamepostmessageactivity androidlabelstringtitle activity post message androidwindowsoftinputmodestatevisibleadjustresize activityi am setting the windowsoftinputmode to statevisibleadjustpan in the manifest file relativelayout xmlnsandroidxmlnstoolsandroidlayout widthmatch parentandroidlayout heightmatch parenttoolscontextcompasonetyokibupostmessageactivityinclude androidididtoolbar home layoutlayouttoolbar home androidelevation5dp scrollview androidlayout widthmatch parent androidlayout heightmatch parentscrollviewlinearlayout androidlayout widthmatch parent androidlayout heightmatch parent androidlayout belowidtoolbar home androidorientationvertical androidlayout aboveidadd post layout androidsupportv7widgetrecyclerview androidlayout widthmatch parent androidlayout heightmatch parent androidididpost msg recyclerview androidsupportv7widgetrecyclerviewlinearlayoutlinearlayout androidorientationhorizontal androidlayout widthfill parent androidlayout heightwrap content androidlayout alignparentbottomtrue androidlayout centerhorizontaltrue androidpadding5dp androidididadd post layout androidbackgroundf androidlayout alignparentlefttrue androidlayout alignparentrighttrue androidelevation5dp androidlayout margin0pt edittext androidlayout width0dp androidlayout heightmatch parent androidididmessagetext androidlayout gravitybottom androidlayout weight1 androidmaxlines4 androidscrollbarsvertical androidbackgroundcolortrasnperant androidhinttype your message androidlayout marginbottom4dp imagebutton androidlayout widthwrap content androidlayout heightwrap content androidsrcdrawableic send black 36dp androidididsendbutton androidbackgrounddrawableabc btn default mtrl shape androidonclickaddpost linearlayout,['android'] +984712,prepareforsegue freezes after updating to ios9 strange issues that i have spent the last 24 hours trying to fixi have an app which was working perfectly fine i updated xcode for ios9 now one of 5 push segues wont perform the action i can breakpoint within prepareforsegue and everything appears to run correctly but soon as it exits the function the phone cpu maxes out and just sits there the gui does not do anythingi have tried many things from creating a new viewcontroller and using the same segue link and everything works its only this one viewcontroller i cannot perform a performseguewithidentifier to i have commented all code from this viewcontroller and still nothing theres nothing special about it compared to those that do worki am totally stuck now anyone have ideassorry if im being vague please ask for any details i have failed to note herethanksdean,"['ios', 'objective-c']" +984773,storage duration of underlying character data with userdefined string literal quick setup i want to pass strings around in my program as a pointer and a size i have a string class and a userdefined literal for constructing literal stringsstruct string const char ptr size t sz inline constexpr string operator stringconst char s size t sz return s szint main auto s hello string sptr0 is this access guaranteed to workdoes the standard specify that the argument passed to my userdefined literal operator has static duration ie is the above code actually equivalent to writingint main string shello 5or is the compilerlinker allowed to leave me with a dangling pointer when i use the userdefined literalsection 2138 of n4527 did not seem to say anything on the subject of storage class of the argument to the userdefined string literal operators any pointers into the appropriate sections of the standard would be appreciated,['c++'] +984826,feature detect if user gesture is needed is there a way to detect if calling play on a video element is allowed without a user gestureon android chrome this warning is givenfailed to execute play on htmlmediaelement api can only be initiated by a user gestureso on chrome android a user gesture is required to start the playback of a video while it is not on desktop chrome is there a way to detect which behavior i will geti want to have slightly different behavior in my app depending on if calling play programatically is allowed or noti have tried to use modernizrvideoautoplay but that checks if the autoplay property on the element which is not the same thing this gives false negatives for ie11 and edgeedit added an example the video will start playing automatically in chrome desktop and ie11 or edge with 3s delay on windows 8 or 10 for chromeandroid a user interaction is needed clicking the button and the error message can be seen in the console,['javascript'] +984894,c bitwise xor compared to java bitwise xor i am trying to convert some java code to c and it is been working flawlessly so far but i have encountered an issue with the operator in c consolewriteline127 0xf prints 4294967168 whereas in java systemoutprintln127 0xf prints 128 i have been looking around to see if there is something else that i need to use instead but i have not come across anything,"['java', 'c#']" +985030,upload to app store failed no version found for adamid platform i am trying to submit an app update for an ios app to support devices running ios 9 and in the process of uploading to the app store via xcode i am getting the following errorno version found for adamid platform 936823648mac os x app if this problem persists for more than 24 hours please contact your apple representativethis is an ios app not an os x app so i do not know why i am getting this error i have already submitted several versions of the app to the app store previouslyanyone know how to resolve this issue,['ios'] +985063,mfc cview cformview destruction crash as per this stackoverflow question what is the correct way to programmatically quit an mfc applicationi am using afxgetmainwndpostmessagewm close00 to exit an mfc program sdi cframewnd containing a csplitterwnd with two cformviewsas expected this calls destroywindowthe problem i am facing is that after the derived cformview destruction as per msdnafter calling destroywindow on a nonautocleanup object the c object will still be around but m hwnd will be null msdnnow the cview destructor is called and at the point it does the cdocumentremoveviewcdocumentupdateframecountsit fails on the following assert assertiswindowpviewm hwndi checked and the m hwnd is already set to null in the derived cview destructor called just beforewhat am i doing wrong edit here is a chart illustrating why i want to send a wm close message and not a wm quiti think the answer lays in this msdn technical note but i cannot figure it outedit 2the order that things get called1 afxgetmainwndpostmessagewm close002 derived cframewndonclose3 cframewndonclosewhich calls cwinappclosealldocumentsbool bendsessionwhich calls cdocmanagerclosealldocumentsbool bendsessionwhich calls cdoctemplateclosealldocumentsboolwhich calls cdocumentonclosedocumentnow in this functionwhile m viewlistisempty get frame attached to the view cview pview cviewm viewlistgethead assert validpview cframewnd pframe pviewensureparentframe and close it precloseframepframe pframedestroywindow will destroy the view as wellso we see that cwnddestroywindow is called so4 derived cformview destructor5 cscrollviewcscrollview6 cviewcviewwhich calls cdocumentremoveviewcview pviewwhich calls cdocumentonchangedviewlistwhich calls cdocumentupdateframecountswhich crashes here assertiswindowpviewm hwndbecause pviewm hwnd is nulledit 3i figured out what the problem wasthe destructor of the first view was deleting an uninitialized pointer which is ub this was making the destructor hang and never completeusually the destructor of the second view is only called upon completion of the first one but in this case it was still being executed although the first one never completedsince the first view base class destructors were never called this function was never called for the first viewvoid cdocumentremoveviewcview pview assert validpview assertpviewm pdocument this must be attached to us m viewlistremoveatm viewlistfindpview pviewm pdocument null onchangedviewlist must be the last thing done to the documentwhere we can see that the view is removed from the m viewlistthis means that when the second view destructor completes invoid cdocumentupdateframecounts assumes 1 doc per frame walk all frames of views mark and sweep approach position pos getfirstviewposition while pos null the pos is supposed to be null but it is not which lead to the crash,['c++'] +985274,comparing first element of the consecutive lists of tuples in python i have a list of tuples each containing two elements the first element of few sublists is common i want to compare the first element of these sublists and append the second element in one lists here is my listmylist1213141526272839310i would like to make a list of lists out of it which looks something like thisnewlist2345678910i hope if there is any efficient way,['python'] +985317,device will not run error ios 9 xcode 70 i recenlty upgraded my device to ios 9the device will not work in xcode 71 when tying to run get the erroran error was encountered while enabling development on this device please try rebooting and reconnecting the device 0xe8076so i updated itunes and dowloaded xcode 70 as suggested here cleaned and builtno luckany input appreciated,['ios'] +985447,how to get unicast dns and gateway address in uwp i am trying to find unicast dns and gateway address in windows iot normally i can access these values with networkinterfacegetallnetworkinterfaces methodbut in uwp that method is missingis there any alternative for getting these values,"['c#', '.net']" +985587,ignore spelling warning in android studio for specific files i want to ignore spellcheck warnings for specific files only in android studio i have tried this out but this seems to be equivalent to suppresslint instead of suppresswarning heres an example of something like what i want to doxml version10 encodingutf8lint issue idspellcheckinginspection severitytypo ignore pathappsrcmainresvalueslocal valuesxml ignore pathappsrcmainresvaluesstringsxml ignore pathappsrcmainandroidmanifestxml issuelintany ideas,['android'] +985626,how to change direction of android elevation shadow i have framelayout with androidelevation4dp shadow of this elevation directed down i want change direction of shadow to upframelayout androidididcontainer androidlayout widthmatch parent androidlayout height100dp androidelevation10dp androidlayout marginbottom100dp androidbackgroundcolorcolorprimary androidlayout alignparentbottomtrue androidlayout alignparentlefttrue androidlayout alignparentstarttrueframelayout,['android'] +985713,java 8 streams grouping a stream of tuples edit i am rephrasing the question so that its more cleari have written this code listimmutablepairinteger integer list new arraylistimmutablepairinteger integer listaddnew immutablepair1 1 listaddnew immutablepair1 1 listaddnew immutablepair1 1 listaddnew immutablepair2 2 listaddnew immutablepair2 2 listaddnew immutablepair2 2 listaddnew immutablepair3 3 listaddnew immutablepair3 3 listaddnew immutablepair3 3 streamimmutablepairinteger integer stream liststream mapinteger integer result streamcollectcollectorsgroupingby immutablepairgetleft collectorsmapping immutablepairgetright collectorssummingintcomparatorcomparingimmutablepairgetright i want to process this list using steams so that the output is a map which contains keys 1 3 2 6 3 9so basically we group on the left item of the tuple and then sum the right itemthis code does not compile and the compiler says that it cannot resolve getleft getright methodshere are the error messages from the compilerusersabhijavaprojectsmovielambda2srcmainjavacomabhimovielambda2java229 error method summingint in class collectors cannot be applied to given types collectorssummingintcomparatorcomparingimmutablepairgetright required tointfunction super t1 found comparatorobject reason no instances of type variables t2u exist so that comparatort2 conforms to tointfunction super t1 where t1t2u are typevariables t1 extends object declared in method t1summinginttointfunction super t1 t2 extends object declared in method t2ucomparingfunction super t2 extends u you extends comparable super u declared in method t2ucomparingfunction super t2 extends uusersabhijavaprojectsmovielambda2srcmainjavacomabhimovielambda2java229 error incompatible types cannot infer typevariables tu collectorssummingintcomparatorcomparingimmutablepairgetright argument mismatch invalid method reference no suitable method found for getrightobject method pairgetright is not applicable actual and formal argument lists differ in length method immutablepairgetright is not applicable actual and formal argument lists differ in length where tu are typevariables t extends object declared in method tucomparingfunction super t extends u you extends comparable super u declared in method tucomparingfunction super t extends uusersabhijavaprojectsmovielambda2srcmainjavacomabhimovielambda2java229 error invalid method reference collectorssummingintcomparatorcomparingimmutablepairgetright nonstatic method getright cannot be referenced from a static context where r is a typevariable r extends object declared in class immutablepairusersabhijavaprojectsmovielambda2srcmainjavacomabhimovielambda2java228 error invalid method reference immutablepairgetright nonstatic method getright cannot be referenced from a static context where r is a typevariable r extends object declared in class immutablepairusersabhijavaprojectsmovielambda2srcmainjavacomabhimovielambda2java226 error invalid method reference immutablepairgetleft nonstatic method getleft cannot be referenced from a static context where l is a typevariable l extends object declared in class immutablepair,['java'] +985816,handle webpack css imports when testing with mocha with webpack you can import styles in your code like this import pagespinnerstyl but when you try to test this code with mocha your tests will be crashed with syntaxerror because engine tries to handle styles like js codehow can i test code like this with mocha,['javascript'] +985857,android studio does not install latest application on device i am following some tutorials about building apps in android studio but for some reason it is not launchinginstalling the latest version of my app when i click run i have to manually uninstall the app on the phone and then click run after making changes in android studio for the app to get updated any ideashere is the console outputwaiting for devicetarget device htchtc one m8uploading file local path homebrandonandroidstudioprojectsjustjavaappbuildoutputsapkappdebugapk remote path datalocaltmpcomexampleandroidjustjavano apk changes detected skipping file upload force stopping package insteaddevice shell command am forcestop comexampleandroidjustjavalaunching application comexampleandroidjustjavacomexampleandroidjustjavamainactivitydevice shell command am start d n comexampleandroidjustjavacomexampleandroidjustjavamainactivity a androidintentactionmain c androidintentcategorylauncherstarting intent actandroidintentactionmain catandroidintentcategorylauncher cmpcomexampleandroidjustjavamainactivity waiting for process comexampleandroidjustjavaconnected to the target vm address localhost8638 transport socketthisconnected from the target vm address localhost8638 transport socket,['android'] +985892,c unordered map with pair as key not compiling i am trying to create an unordered map to map pairs with integers include unordered mapusing namespace stdusing vote pairstring stringusing unordered map unordered mapvote inti have a class where i have declared an unordered map as a private member however i am getting this error when i try to compileapplicationsxcodeappcontentsdevelopertoolchainsxcodedefaultxctoolchainusrincludecv1type traits94838 implicit instantiation of undefined template std 1hashstd 1pairstd 1basic stringchar std 1basic stringchar i am not getting this error if i use a regular map like mappairstring string int instead of an unordered mapis it not possible to use pair as key in unordered maps,['c++'] +985896,achieving stackless recursion in java 8 how do i achieve stackless recursion in javathe word that seems to come up the most is trampolining and i have no clue what that means could someone in detail explain how to achieve stackless recursion in java also what is trampolining if you cannot provide either of those could you please point me in the right direction ie a book to read about it or some tutorial that teaches all of these concepts,['java'] +985899,collapsible toolbar set how much the toolbar should be collapsed in oncreate i am creating a listview and its corresponding detailview applicationmy listview has items which if clicked take the user to the detailviewactivityon the detailviewactivity i have implemented a collapsible toolbarnow every time the detailviewactivity is opened a different image with different dimensions is set onto the imageview within the collapsible toolbari want that the toolbar should be open upto a certain height by default say 256dp but if the image height is greater than that the user should be able to pull down to view the rest of the image exactly like whatsappi have managed to programatically set the height of the toolbar each time i open the activity but the problem is the toolbar is always fully expanded so if the image is larger the tollbar by default is very big i want it to be collapsed to 256dp irrespective of the height of the imagethe code for my layout isrelativelayout xmlnsandroid xmlnsapp xmlnstools androidlayout widthmatch parent androidlayout heightmatch parent androidsupportdesignwidgetcoordinatorlayout androidididrootlayout androidlayout widthmatch parent androidlayout heightmatch parent androidsupportdesignwidgetappbarlayout androidididappbar androidlayout widthmatch parent androidlayout heightdimenapp bar height androidthemestylethemeoverlayappcompatdarkactionbar androidsupportdesignwidgetcollapsingtoolbarlayout androidididcollapsingtoolbarlayout androidlayout widthmatch parent androidlayout heightmatch parent appcontentscrimattrcolorprimary appexpandedtitlemarginstartdimenexpanded toolbar title margin start applayout scrollflagsscrollexituntilcollapsed imageview androidididimage androidlayout widthmatch parent androidlayout heightmatch parent androidscaletypecentercrop androidsrcdrawablebackground navdrawer applayout collapsemodeparallax applayout collapseparallaxmultiplier07 view androidlayout widthmatch parent androidlayout heightmatch parent androidlayout margintop130dp androidbackgrounddrawablegradient header background applayout collapsemodeparallax applayout collapseparallaxmultiplier01 androidsupportv7widgettoolbar androidididtoolbar androidlayout widthmatch parent androidlayout heightattractionbarsize applayout collapsemodepin apopupthemestylethemeoverlayappcompatlight appthemestylethemeoverlayappcompatdarkactionbar androidsupportdesignwidgetcollapsingtoolbarlayout androidsupportdesignwidgetappbarlayout androidsupportv4widgetnestedscrollview androidididdetail nested scroll view androidlayout widthmatch parent androidlayout heightmatch parent applayout behaviorstringappbar scrolling view behavior framelayout androidididdetail container androidlayout widthmatch parent androidlayout heightmatch parent toolsignoremergerootframe androidsupportv4widgetnestedscrollview linearlayout androidlayout widthmatch parent androidlayout height12dp androidorientationvertical applayout anchoridappbar applayout anchorgravitybottom view androidididtoolbar shadow transparent androidlayout widthmatch parent androidlayout heightdimentoolbar elevation androidbackgroundcolortransparent view androidididtoolbar shadow androidlayout widthmatch parent androidlayout heightdimentoolbar elevation androidbackgrounddrawabledropshadow linearlayout comgithubclansfabfloatingactionbutton androidididaction edit stylestylemenubuttonsstyle androidlayout widthwrap content androidlayout heightwrap content androidlayout marginright10dp androidsrcdrawableic edit applayout anchoridappbar applayout anchorgravitybottomrightend androidsupportdesignwidgetcoordinatorlayout imageview androidididdetail back arrow land androidlayout widthwrap content androidlayout heightwrap content androidvisibilitygone textview androidididcourse name textview androidlayout width0dp androidlayout height0dp androidvisibilitygonerelativelayoutand in my activity i have found the height and set it to the toolbar like thisappbar appbarlayout findviewbyidridappbarcoordinatorlayoutlayoutparams lp coordinatorlayoutlayoutparams appbargetlayoutparamslpheight my bitmapgetheightdetailactivityappbarsetlayoutparamslpdetailactivitymimageviewsetimagebitmapmy bitmapi am attaching screenshots to make my point clearerthis is exactly how tall i want my toolbar to be everytime the activity gets launchedand this is what i get from my codenow i could hardcode the height to 256dp in code but then the user will not be able to scroll down to see the rest of the image please suggestthank you for your responseany response could get me started,['android'] +985945,ios 9 searchbar thisappears from table header view when uisearchcontroller is active the structureview1 click a button present modally mymodalview uitableviewcontrollermymodalview has uisearchcontroller embedded the searchbar of uisearchcontroller is placed in mymodalviewtableviewtableheaderviewit is been working fine since ios 80 however on ios 9 the searchbar thisappear when the uisearchcontroller is active please take a look at theses pictures belowthe modal viewuisearchcontroller active on ios 8uisearchcontroller active on ios 9the very standard codeoverride func viewdidload superviewdidload dynamically create a search controller using anonymous function selfresultsearchcontroller let controller uisearchcontrollersearchresultscontroller nil controllersearchresultsupdater self controllerdimsbackgroundduringpresentation false controllersearchbarsizetofit controllersearchbardelegate self selftableviewtableheaderview controllersearchbar return controller auto sizing row cell height selftableviewestimatedrowheight 130 selftableviewrowheight uitableviewautomaticdimension selfdefinespresentationcontext true no footer for better presentation selftableviewtablefooterview uiviewinitframe cgrectzerothis issue also happens in ios 91 beta any idea pointer would be deeply appreciatedcheers,['ios'] +985992,java method executed prior to default constructor i am learning java and accidentally i came across following code where default constructor is executed after the methodpublic class chkcons int var getval chkcons systemoutprintlni am default constructor public int getval systemoutprintlni am in method return 10 public static void mainstring args chkcons c new chkcons output i am in methodi am default constructorcan anyone please explain me why this happenedthanks,['java'] +986050,facebook sdk is not a dylib error after update update xcode 7 i got some errors with facebook sdk after update xcode 7 when i tried to build the project like the code belowld warning autolinking supplied usersmanjarbdesktophubbalabslibfacebooksdkfbsdksharekitframeworkfbsdksharekit framework linker option at usersmanjarbdesktophubbalabslibfacebooksdkfbsdksharekitframeworkfbsdksharekit is not a dylibld warning autolinking supplied usersmanjarbdesktophubbalabslibfacebooksdkfbsdkcorekitframeworkfbsdkcorekit framework linker option at usersmanjarbdesktophubbalabslibfacebooksdkfbsdkcorekitframeworkfbsdkcorekit is not a dylibld warning autolinking supplied usersmanjarbdesktophubbalabslibfacebooksdkfbsdkloginkitframeworkfbsdkloginkit framework linker option at usersmanjarbdesktophubbalabslibfacebooksdkfbsdkloginkitframeworkfbsdkloginkit is not a dylibhow to fix thisthanks,['ios'] +986058,google cloud messaging showing success message but not sending ios so i have run into a very strange problem with google cloud messaging the problem i am having is that it is registering the devices successfully and when a message is sent i get a success message from google but the devices never receive any messagesthe message i get back from gcm isresult push notification sent successfully multicast id60083875307696640success1failure0canonical ids0resultsmessage id0144282484260752273fc535e73fc535eto make things even more confusing my implementation was working about 2 weeks ago and i have not changed anything to date the android version of the app is receiving messages with no problems it is only the ios implementation that is not workingany help would be much appreciatedthanks,['ios'] +986113,how to destroy a highland stream i have the following exampleconst input const output eachx consolelogout xinput pipeoutputinputwrite1outputdestroyinputwrite2 as far as i can read in the documentation destroying the stream should clean up the broken pipein stead i get the following errorout 1out 2node moduleshighlandlibindexjs14 throw new errorcan not call next after nil error can not call next after nildoes anyone have some insight into why this happends and what the correct way to destroy the stream is,['javascript'] +986122,whats wrong here instance member cannot be used on type i have the following code and i am confused about this error messageinstance member mydate cannot be used on type tableviewcontrollercodeclass tableviewcontroller uitableviewcontroller let mydate nsdate let items 1 9 7 a mydate 2 9 7 b mydate 3 9 7 c mydate 4 9 7 d mydate when i write the following i can build it but i do not know why the oder snippet is not workingclass tableviewcontroller uitableviewcontroller let mydate nsdate let items 1 9 7 a nil 2 9 7 b mydate 3 9 7 c mydate 4 9 7 d mydate,['ios'] +986187,visual studio 2015 strange keyboard shortcuts i just went over to vs 2015 from 2013 back in 2013 i was using alt shift for typing the character in vs 2015 the same command toggles the error thisplay for the scroll bar and wont let me type the opening curly bracket i have tried to track down this awful shortcut in tools options environment keyboard but without any success anyone know how to remove this or override it with my desired shortcut edit i am using resharper 92 ultimate and it is keyboard scheme resharper 2x or intellij idea over visual studios default scheme i have tried with both schemes and none of them seems to solve this issue so this should not be the cause of the problem unless i am missing something obvious regarding the keyboard layout i am using a swethish one sv and it looks like this and my physical keyboard looks like this mac note i am using the following vs setup microsoft visual studio professional 2015version 140231070 d14relmicrosoft net frameworkversion 46081installed version professionalto clarify even more notice the green little checkbox that indicates if there are any errors or warnings on picture two this is whats getting toggled while using the desired command inside vs,['c#'] +986206,navigation drawer menu items selected within different groups i have a working navigation drawer and having some issues with menuitemsetcheckedtrue when using groups and headers within the menu it is not highlighting menu items as expectedhere is my xmlmenu xmlnsandroid xmlnstools toolscontextactivitymap group androidcheckablebehaviorsingle item androidididnav welcome androidicondrawableabc btn check to on mtrl 0 androidtitlewelcome item androidididnav map showmap androidiconmipmapic map black 24dp androidtitleshow map item androidiconmipmapic list black 24dp androidtitleshow list item androidtitlesettings menu item androidididnav database check androidiconmipmapic cloud done black 24dp androidtitleupdate database item androidididnav map settings androidiconmipmapic settings black 24dp androidtitleapp preferences menu item item androidtitlegeneral menu item androidididnav general about androidiconmipmapic info black 24dp androidtitleabout item androidididnav general help androidiconmipmapic help black 24dp androidtitlehelp item androidididnav general report androidiconmipmapic email black 24dp androidtitlefeedback report error menu item groupmenuas you can see i have 3 menu items then a settings group with 2 menu items then a general group with 3 menu itemsnow with the first 3 menu items the menuitemsetcheckedtrue is working as expected and highlighting that menu item however none of the following menu items within the subset settings or general subsets are highlighting correctlyi read that the group androidcheckablebehavioursingle can encapsulate the whole block but that does not seem to be workingany thoughts cheersedit added screenshot of the menu structure,"['java', 'android']" +986221,how to use spring boot making a common library now i want to develop a common mail service for our systemsas we design we want to develop a rabbitmq producer and consumer on consumer side we could develop and deploy a spring boot or spring cloud application but on producer side we want to give a common mail client like the interface below and make a jar dependency for other systeminterface mailclient listentablefuture sendmessage message but i see spring boot and spring cloud using many declarative method and seems must use a application class but i just want a class reference and not need deploy i do not know how to implement it,['java'] +986273,android studio edalvikvmi1 could not find class databasehelper referenced from method databasemanager hello i am getting this error using android studio on runtime but only on devices with an sdk version 19 everything compiles ok but i get this error on my databasehelper classjavalangnoclassdeffounderrorhere is my app buildgradleapply plugin comandroidapplicationandroid compilesdkversion 23 buildtoolsversion 2301 uselibrary orgapachehttplegacy defaultconfig minsdkversion 11 targetsdkversion 23 versioncode 1 versionname 10 multidexenabled true buildtypes release minifyenabled true dependencies compile filetreeinclude jar dir libs compile comgoogleandroidgmsplayservices780 compile comandroidsupportappcompatv72301 compile comgithubjohnpersanosupertoasts134aar compile comreadystatesoftwaresystembartintsystembartint103 compile comnavercorppulltorefreshlibrary320aar compile comparseboltsboltsandroid121 compile comj256ormliteormliteandroid448 compile comj256ormliteormlitecore448my databasehelper class extends ormlitesqliteopenhelpereverything was working fine while my compilesdkversion was at 19here is what i updatedgradle classpath comandroidtoolsbuildgradle110 130sdk version compilesdkversion 19 23appcompat comandroidsupportappcompatv71901 23playservicesmy databasehelper class is in the same package than other classes which work fine thank you for your help,['android'] +986275,assemblygettypes returns strange type names eg c when using assemblygettypes i get types that have typename that begin with c i tried to google if this is anonymous types or something else but cannot get a really good answeris there a property on type that indicate what these types are i do not like having to do iftypenamestartswith,"['c#', '.net']" +986376,when i try to run the xcode simulator i get the error stop anulla i just updated to xcode 7 and ran an app on a live device now for some reason i get an error when i try to run an app in a simulator stop anulla an instance of anulla is already running choose astopa to terminate and launch a new instancewhen i press the stop button it grays out as in the screen shot but nothing happens i have tried resetting the content and settings on the simulator but that did not help,['ios'] +986636,jsx vs es6es2015 in my project i am using react and babel so i use some es6 features but mainly those used by react webstorm gives me the option to mark my syntax either as es6 or jsx harmony and i got confused i think i know what es6es2015 is and how to use it with a compiler eg babel the hard part id jsxjsx harmony i know that react uses jsx butis this the same jsx as here if not which jsx is meant by jsx harmony option in webstormi have seen the compatibility page mentioned here and know that jsx transformer supports only small part of es6 but also that apparently babel supports jsx as an addition to es6 support so jsx seems to be more than es6 subset if so what features of jsx react or jsx harmony are not part of es6 specs editas for question 1 i am getting sure these are two completely different things but what is jsx harmony then edit 2to answer my own question webstorm jsx harmony refers most probably to the syntax supported by react jsx compiler with harmony flag on adding a bit of es6 support,['javascript'] +986716,how to compile opencv ios with enable bitcode when i tried to compile my xcode project with opencv 24 ios using xcode 7 ios sdk 9 xcode complained thatld opencv2frameworkopencv2alloco does not contain bitcode you must rebuild it with bitcode enabled xcode setting enable bitcode obtain an updated library from the vendor or thisable bitcode for this target for architecture arm64clang error linker command failed with exit code 1 use v to see invocationand refused to link after some googling it turns out to be because apple added a new feature named bitcode for app optimization within app store while opencv ios binary has not been updated to include bitcode it cannot pass the link stagesome reference pointed out a temporary solution to thisable enable bitcode so the linking could be done without bitcode this will prevent the app being compiled for apple watches because bitcode is mandatory for watch apps therefore my question is are there some best easy ways to compile ios opencv with bitcode enabled better with a download link for compiled framework,['ios'] +986720,can i test screen record in emulator in android studio i try to test a sample code about screen record from below link i modified some code to thisable recording audioi test the code in android studio v13 but i get the following error and the file capturemp4 is blanki am not sure whether i must test the code in real mobile phone could you help me thankserror info0922 064150250 21672167 eandroidruntimei1 fatal exception main process screencapturetruitoncommyapplication pid 2167 javalangruntimeexception stop failed at androidmediamediarecorderstopnative method at screencapturetruitoncommyapplicationmainactivityontogglescreensharemainactivityjava93 at screencapturetruitoncommyapplicationmainactivity1onclickmainactivityjava55 at androidviewviewperformclickviewjava4780 at androidwidgetcompoundbuttonperformclickcompoundbuttonjava120 at androidviewviewperformclickrunviewjava19866 at androidoshandlerhandlecallbackhandlerjava739 at androidoshandlerthispatchmessagehandlerjava95 at androidoslooperlooplooperjava135 at androidappactivitythreadmainactivitythreadjava5257 at javalangreflectmethodinvokenative method at javalangreflectmethodinvokemethodjava372 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava903 at comandroidinternaloszygoteinitmainzygoteinitjava698source codepackage screencapturetruitoncommyapplicationpublic class mainactivity extends activity private static final string tag mainactivity private static final int permission code 1 private int mscreendensity private mediaprojectionmanager mprojectionmanager private static final int thisplay width 480 private static final int thisplay height 640 private mediaprojection mmediaprojection private virtualthisplay mvirtualthisplay private mediaprojectioncallback mmediaprojectioncallback private togglebutton mtogglebutton private mediarecorder mmediarecorder override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main thisplaymetrics metrics new thisplaymetrics getwindowmanagergetdefaultthisplaygetmetricsmetrics mscreendensity metricsdensitydpi mmediarecorder new mediarecorder initrecorder preparerecorder mprojectionmanager mediaprojectionmanager getsystemservice contextmedia projection service mtogglebutton togglebutton findviewbyidridtoggle mtogglebuttonsetonclicklistenernew viewonclicklistener override public void onclickview v ontogglescreensharev mmediaprojectioncallback new mediaprojectioncallback override public void ondestroy superondestroy if mmediaprojection null mmediaprojectionstop mmediaprojection null override public void onactivityresultint requestcode int resultcode intent data if requestcode permission code logetag unknown request code requestcode return if resultcode result ok toastmaketextthis screen cast permission denied toastlength shortshow mtogglebuttonsetcheckedfalse return mmediaprojection mprojectionmanagergetmediaprojectionresultcode data mmediaprojectionregistercallbackmmediaprojectioncallback null mvirtualthisplay createvirtualthisplay mmediarecorderstart public void ontogglescreenshareview view if togglebutton viewischecked sharescreen else mmediarecorderstop mmediarecorderreset logvtag recording stopped stopscreensharing initrecorder preparerecorder private void sharescreen if mmediaprojection null startactivityforresultmprojectionmanagercreatescreencaptureintent permission code return mvirtualthisplay createvirtualthisplay mmediarecorderstart private void stopscreensharing if mvirtualthisplay null return mvirtualthisplayrelease mmediarecorderrelease private virtualthisplay createvirtualthisplay return mmediaprojectioncreatevirtualthisplaymainactivity thisplay width thisplay height mscreendensity thisplaymanagervirtual thisplay flag auto mirror mmediarecordergetsurface null callbacks null handler private class mediaprojectioncallback extends mediaprojectioncallback override public void onstop if mtogglebuttonischecked mtogglebuttonsetcheckedfalse mmediarecorderstop mmediarecorderreset logvtag recording stopped initrecorder preparerecorder mmediaprojection null stopscreensharing logitag mediaprojection stopped private void preparerecorder try mmediarecorderprepare catch illegalstateexception e eprintstacktrace finish catch ioexception e eprintstacktrace finish private void initrecorder mmediarecordersetaudiosourcemediarecorderaudiosourcemic mmediarecordersetvideosourcemediarecordervideosourcesurface mmediarecordersetoutputformatmediarecorderoutputformatmpeg 4 mmediarecordersetvideoencodermediarecordervideoencoderh264 mmediarecordersetaudioencodermediarecorderaudioencoderamr nb mmediarecordersetvideoencodingbitrate512 10 mmediarecordersetvideoframerate30 mmediarecordersetvideosizethisplay width thisplay height mmediarecordersetoutputfileenvironmentgetexternalstoragedirectory capturemp4,['android'] +986857,class javacardframeworkservicecardremoteobject not found i am newer in java card platform so please be patient with me i am trying to develop an rmi application for the java card 3 platform my ide is eclipse and my os is windows 10 i start by creating a simple interface icontorjava responsible for increasing decreasing etc certain valueshere is my interfacepackage sidimport javarmiremoteimport javarmiremoteexceptionimport javacardframeworkuserexceptionpublic interface icontor extends remote public void incrementerthrows remoteexceptionuserexception public void decrementerthrows remoteexceptionuserexception public byte getvaluethrows remoteexceptionuserexception public void initbyte valuethrows remoteexceptionuserexceptionthen i provide an implementation for this interface which i named contorjavapackage sidimport javarmiremoteexceptionimport javacardframeworkuserexceptionimport javacardframeworkservicecardremoteobjectpublic class contor extends cardremoteobject implements icontor private byte contor 0 override public void incrementer throws remoteexception userexception contor override public void decrementer throws remoteexception userexception contor override public byte getvalue throws remoteexception userexception return contor override public void initbyte value throws remoteexception userexception contor value my test applet worked ok below i wrote that peace of codepackage sidimport javacardframeworkimport javacardframeworkservicethispatcherimport javacardframeworkservicermiservicepublic class test extends applet thispatcher thispatcher public static void installbyte barray short boffset byte blength new testregister protected test rmiservice rmiservice new rmiservicenew contor thispatcher new thispatchershort1 thispatcheraddservicermiservicethispatcherprocess command override public void processapdu apdu thispatcherprocessapdu this is a standard piece of code however i want to create a client which uses that interface which implements the interface remote so i create a java application in which i copied the icontorjava interface then i opened a command prompt and do the following thingsgo into the directory where the source files of the first project is located cd bla blacontorsrcgo a directory up cd go into bin directory cd binhere i have located the name of the package sid and into package sid i have those three files contorclass icontorclass and testclassthen i typed the following command on the command promptrmic v12 classpath jc classic homelibtoolsjar sidcontorbut i got the following errorclass javacardframeworkservicecardremoteobject not found in class sidcontori replace the toolsjar with api classicjar but i still get the same error the jc classic home contains the path to the java card 3 development kit toolsjar contains compiled implementations of packages javacardframework javacardsecurity javacardxbiometry javacardxexternal and javacardxframeworktlv my bout is to generate a client application in binsid directorymy jc classic home value is cprogram files x86oraclejava card development kit 305ga and i am using jdk 18here is my package explorer from eclipse,['java'] +986881,c change app language programmatically uwp realtime in my application for each language string resources are stored separately and are thisplayed depending of type of language environment i want to change the language in the application settings how do i realize that after the language selection instantly apply it in the user interface,['c#'] +986882,how to prevent an external js request i am using a service that automatically constructs and hosts launch pages in the body of their code they have a call to jquery script typetextjavascript srcajaxgoogleapiscomajaxlibsjquery211jqueryminjscache2015092209unfortunately since i am in china googleapiscom is blocked and the page has to wait for this code to timeout before it will render this portion is autogenerated as part of the template and i cannot change it however i can insert custom javascript in the head and the body are there any ways i can prevent this code from making the request to googleapiscom or to force it to abort after it has already made the requesteditheres a screen cap of the network tab when i try to load the page as you can see the call to googleapiscom hangs for 14 mins until it times out at which point domcontentloaded triggers and the entire page loads,['javascript'] +986983,failed to resolve comgithubphiljaympandroidchartv214 i am using mpandroidchart libarary in android studiobut when i am trying to sync gradle which given an error as below imagegradle text is here to compile mpandroidchart libararycompile comgithubphiljaympandroidchartv214please help to resolve this problem thanks in advance,['android'] +987023,why there is not stdis struct type trait i have seen that in order to check if a type t is a class i can usebool isclass stdis classtvalueit returns true for both classes and structs i know that in c they are almost the same thing but i would like to know why there is not a thistinction between them in the type trait it is always useless to check this difference or there is some more reason that i do not understand,['c++'] +987037,c 6 switch on nullable long goes to default for real values i have this simple program with a switch on a nullable longclass program static void mainstring args consolewritelinetest1 private static string testlong orderid switch orderid case 1 return 1 default return default after compiling in vs 2013 i always get 1 as outputafter compiling in vs 2015 i always get default as outputit only happens if the argument to test is a long not an inti have decompiled then ilcode and in my opinion there is an convi8 missing before comparing the values via beqs the vs 2013 compiler emits it method private hidebysig static string testvaluetype mscorlibsystemnullable1int64 orderid cil managed code size 46 0x2e maxstack 2 locals init 0 valuetype mscorlibsystemnullable1int64 v 0 1 valuetype mscorlibsystemnullable1int64 v 1 2 int64 v 2 3 string v 3011 private static string testlong orderid012 il 0 nop013 switch orderid il 01 ldarg0 il 02 stloc1014 015 case 1016 return 1017 default018 return default019 020 021 022 il 03 ldloc1 il 04 stloc0 il 05 ldlocas v 0 il 07 call instance bool valuetype mscorlibsystemnullable1int64get hasvalue il 0c brfalses il 0024 il 0e ldlocas v 0 il 0010 call instance 0 valuetype mscorlibsystemnullable1int64getvalueordefault il 0015 stloc2 il 0016 ldloc2 il 0017 ldci41 il jf17 convi8 added by me il 0018 beqs il 001c il 001a brs il 0024016 return 1 il 001c ldstr 1 il 0021 stloc3 il 0022 brs il 002c017 default018 return default il 0024 ldstr default il 0029 stloc3 il 002a brs il 002c019 020 il 002c ldloc3 il 002d ret end of method programtestcan anyone confirm thisif i change the switchstatement to switch orderidvalue everything works fine but i am not sure how many of those statements exists in our code base,"['c#', '.net']" +987088,xcode 7 build failed due to ld library not found for lgoogleanalyticsservices i have been struggling to get my xcode project to build for the last couple hours i keep getting the following errorld library not found for lgoogleanalyticsservices clang error linker command failed with exit code 1 use v to see invocationi have tried almost everything i saw that the google developers website said to use pod googleanalytics even after trying almost everything i could find on stackoverflow and google regarding the error i have had absolutely no lucki upgraded to xcode 7 yesterday everything seemed to work yesterday but today suddenly i started getting this errorif someone has anything i can do about this error please helppointing me in the right direction to get it fixed would be awesome toothanks in advance for your help,['ios'] +987093,why the response object from javascript fetch api is a promise when requesting from a server with javascript fetch api you have to do something likefetchapi thenresponse responsejson catcherr consolelogerrhere responsejson is resolving its promisethe thing is that if you want to catch 404s errors you have to resolve the response promise and then reject the fetch promise because youll only end in catch if there is been a network error so the fetch call becomes something likefetchapi thenresponse responseok responsejson responsejsonthenerr promiserejecterr catcherr consolelogerrthis is something much harder to read and reason about so my question is why is this needed whats the point of having a promise as a response value are there any better ways to handle this,['javascript'] +987270,whats the best way to get the duration of an api call using guzzle 6 currently with guzzle 6 it seems there is no out of the box way to get the duration of an api call whats the best way to get this stat with any ordinary call using the code belowi am using the following code from how do you log all api calls using guzzle 6use guzzlehttphandlerstackuse guzzlehttpmiddlewareuse guzzlehttpmessageformatteruse monologloggerstack handlerstackcreatestackpush middlewarelog new loggerlogger new messageformatterreq body res body client new guzzlehttpclient base uri handler stack echo string clientgetipgetbody,['php'] +987284,null coalescence and lambdas this answer to another question of mine did not compile though on the surface it seems it should this is not the same question i can rewrite the other answer to work for my other questiongiven private funcmyt bool segmentfilter get set public myconstructorfuncmyt bool segmentfilter null this does not compile type or namespace mas could not be found segmentfilter segmentfilter mas return true this equivalent form compiles just fine if segmentfilter null segmentfilter mas return true else segmentfilter segmentfilter why is the compiler running into trouble with the null coalescent operator but not with the syntaxsugarfree ifelse version,['c#'] +987287,the application is missing required entitlement comappledevelopericloudservices i am using a public icloud database in my app which works great and is up on the store on updating my app to a new version with xcode 7 on ios9 i get a crash on the line ckcontainer container ckcontainer containerwithidentifiericloudcomidentifier terminating app due to uncaught exception ckexception reason the application is missing required entitlement comappledevelopericloudservicesthis happens only the first launch of the app after updating and only on ios9 after that first update launch the app launches and icloud works as expected i can recreate the crash consistently by downloading the current store version of the app then running the updated app from xcode 7 if i do the same steps download production app and update using ios8 i do not have the same crash i am guessing this is an ios9 or xcode 7 bug any ideas edit this actually happens on the first launch of the app on ios9 regardless of whether i am updating or just first installing,['ios'] +987300,php 7 rc3 how to install missing mysql pdo i am trying to setup webserver with php 7 rc3 nginx on ubuntu 1404 for test purposesi installed ubuntu in vagrant using ubuntutrusty64 and php 7 rc 3 from ondaej sura12 i can not find the way to install mysql pdo php sees pdo class but not anything related to mysql like pdomysql attr direct query etclooks like there is no lib php70mysql by analogy with standard php5mysqlnd and php70fpm etc from ondaejsection pdo in phpinfopdo support enabledpdo drivers no valuehow can i get it,"['php', 'mysql']" +987302,how to create a handshake between php web server and socketio on nodejs server i have a websocket running on nodejs 40 on server 100418 at port 8020 i implemented my websocket using socketio v13 express and expresessionproject definitioni need to be able to create a session in socketio for every user that connects to it from a php application after the user send the first http request i will authenticate them using a token that will be passed from php to socketio along with the http request after the user is authenticated i need to save some personal data inside socketio session to reuse later every time the user refresh the php application socketio will need to know the session data that is already createdproblemevery time the user reloadsrefreshed the php page where heshe connected from the session data are lost the server fails to know that connection belong to session xyz which is previously created createdi am not sure how to create a handshake between php and nodejs where the two server can exchange a unique data to tie the socketio session tovery close look at the problemi opened this link in my browser this created a session for me directly from nodejs per the route codethen i connected to the websocket using php now i can see that the session sticks with no problem i was able to open multiple tabs in the browser and the same session is there as expectedthe reason it worked this time is because the url established a session and tied it between my browser and the session and from there i was able to readwrite my session from socketio using expresocketiosession package but if i do not create the session using the url manually the session will only be good for one page load only and every time the page is reloaded the session is destroyed like it never existedquestioni need to develop the same behavior when connection to the websocket via when connecting from the socketiohow can i establish a handshake between php server and socketio where the two servers can tie the session data to the correct user every time the php page is reloaded or a new browsers tab is openedhere is my websocket codevar app requireexpress https requirehttps fs requirefs session requireexpresession sharedsession requireexpresocketiosession filestore requiresessionfilestoresession base64url requirebase64url cookieparser requirecookieparser env requiremodulesconfigvar server httpscreateserver key fsreadfilesynccertskeypem cert fsreadfilesynccertscertpem applistenenvsocketport envsockethost function consolelog0332j consolelogwebsocket is running at https serveraddressaddress serveraddressportvar io requiresocketioservervar icwsreq requiremodulesicwsrequestjs icwsconn requiremodulesicwsconnectionjs icwsinter requiremodulesicwsinteractionsjs sessionvalidator requiremodulesvalidatorjsvar icwsrequest new icwsreqvar sessionchecker new sessionvalidatorvar sessionstorefile new filestorepath tmpsessionsvar clients var sessionoptions store sessionstorefile secret envsessionsecret name envsessionname rolling true saveuninitialized false resave true unset keep cookie maxage 60 60 10 var sessionmiddleware sessionsessionoptionsappusesessionmiddleware session support for the appset access control headers on every express routeappusefunction req res next ressetheaderaccesscontrolalloworigin ressetheaderaccesscontrolallowheaders xrequestedwith contenttype next use shared session middleware for socketioiousesharedsessionsessionmiddleware autosave true middleware for authorizing a user before establishing a connectioniousefunctionsocket next var myip socketrequestsocketremoteaddress var token sockethandshakequerytokenid var session sockethandshakesession ifsession token consoleloglog no session and no token return nextnew errorno tkensession found iftoken consoleloglog token was not found return nextnew errortoken not found sessionid should be defined on a page reload consolelogip address myip sessionid sockethandshakesessionid allow any user that is authorized ifsession sessionautherized token sessiontoken consoleloglog you are good to go return nextnew erroryou are good to go if the client changed their token client logged out terminate the open session before opening a new one if sessionautherized token sessiontoken var decodedtoken base64urldecodetoken sessioncheckervalidatedatadecodedtoken myip envsessionduration functionisvalid icws ifisvalid consoleloglog token could not be validated return nextnew errortoken could not be validated sessionauthorized true sessionicwsserver icwshost sessionicwsport icwsport sessiontoken token sessionicwssessionid null sessionicwstoken null icwsrequestsetconnectionicwshost icwsport var icwsconnection new icwsconnicwsrequest sessionsavefunction consoleloglog new connection to websocket return next ioonconnection function socket consolelogconnection is validated and ready for action var socketid socketid ifsockethandshakesessionid consolelogsessionid was not found return false var sessionid sockethandshakesessionid var usercons clientssessionid add this socket to the users connection ifuserconsindexofsocketid 1 userconspushsocketid clientssessionid usercons socketonchat functionmsg for var key in clientssessionid if clientssessionidhasownpropertykey var id clientssessionidkey consolelogclient said msg iotoidemitchat message server said msg socketonthisconnect functionmsg consolelogclosing sessionid sessionid var usercons clientssessionid var index userconsindexofsocketid ifindex 1 userconsspliceindex 1 consolelogremoved thisconnect message msg else consolelogthisconnect message msg socketonerror functionmsg consolelogerror message msg appget function req res ressendwelcome reqsessionidappgetread function req res ressendwelcome reqsessionnameappgetsetname function req res reqsessionname reqparamsname ressendwelcome reqsessionnamehere is how i connect to the websocket from php serverdoctype htmlhtml langenus head titlesocketio chattitle meta charsetutf8 style margin 0 padding 0 boxsizing borderbox body font 13px helvetica arial form background 0 padding 3px position fixed bottom 0 width 100 form input border 0 padding 10px width 90 marginright 5 form button width 9 background rgb130 224 255 border none padding 10px messages liststyletype none margin 0 padding 0 messages li padding 5px 10px messages linthchildodd background e style script srcscript script typetextjavascript srcjsjquery210minjsscript script function var socket ioconnect secure true port 8020 query php generated token that will be used to authenticate the user from nodejs when the send button is clicked fclickfunctione epreventdefault var message mvaltrim if message return false socketemitchat message mval socketonchat functionmsg messagesappendlitextmsgmessage script head body ul idmessagesul form action idf input idm autocompleteoff buttonsendbutton form bodyhtml,"['javascript', 'php']" +987337,pythons equivalent of rubys to check if a variable exist and if exits use the original value other wise use the new value assigned in ruby it isvar var newhow to write it in python psi do not know the name of i simply cannot search it in bing,"['python', 'ruby']" +987351,xcode validate failed a sealed resource is missing or invalid yesterday i received an email from apple apple suggest developers validate their xcode version here is the link validating your xcodecheck your xcode versionspctl assess verbose applicationsxcodeappnormally we should seeapplicationsxcodeapp acceptedsourcemac app storeapplicationsxcodeapp acceptedsourceappleorapplicationsxcodeapp acceptedsourceapple systembut my xcode downloaded from app store saidapplicationsxcodeapp a sealed resource is missing or invalid,['ios'] +987521,c thisk io write after read at the same offset of a file will make read throughput very low backgroundi am developing a database related program and i need to flush dirty metadata from memory to thisk sequentiallydevsda1 is volumn format so data on devsda1 will be accessed block by block and the blocks are adjacent physically if accessed sequentiallyand i use direct io so the io will bypass the caching mechanism of the file system and access directly the blocks on the thiskproblemsafter opening devsda1 i will read one block update the block and write the block back to the same offset from the beginning of devsda1 iterativelythe code are like below block size 256kbint file opendevsda1 o rdwro largefileo directforint i0 in i preadfile buffer block size iblock size update the buffer pwritefile buffer block size iblock sizei found that if i do not do pwrite read throughput is 125 mbsif i do pwrite read throughput will be 21 mbs and write throughput is 169 mbsif i do pread after pwrite write throughput is 115 mbs and read throughput is 208 mbsi also tried readwrite and aio readaio write but the problem remains i do not know why write after read at the same position of a file will make the read throughput so lowif accessing more blocks at a time like thispreadfile buffer num blocks block size iblock sizethe problem will mitigate please see the chart,['c'] +987605,constructing dependencies graph asynchronously in dagger 2 this is a more theoretical question please let me know if i am going in the wrong directionis there any way to load some of graph dependencies asynchronouslyin parallel in dagger 2 should it be even considered in a context of dagger my problem is mainly connected with app launch time a lot of external dependencies like mixpanel crashlyticsfabric retrofit restadapter cause that the app is warming up longer than 1 secondwhat helped me a lot is lazy interface but the final effect still does not satisfy me any ideasexampleapp has splashactivity which depends on splashactivitypresenter which depends on mixpanel restadapter and crashlytics libraries and a couple smaller objects each of them has init method which takes a lot of time mixpanel initialization takes about 200ms on nexus 5 android m so in result it will take about 2 seconds before user sees splash screenis there any way to construct those objects in parallel,['android'] +987607,racket as scripting language in a game engine i would like to add scripting capabilities to my c game enginei have engineexe physicsdll audiodll and i am adding scriptingdll which is a highlevel racket wrapperengineexe loads physicsdll and sets up physics world loads audiodll and sets up audio world it is supposed to load scriptingdll to set up bindings to physicsdll audiodll and to load game scriptsafaik there are two possible ways to embed racket into a c programas extensionas foreign interfaceusing foreign interface seems bizarre due to necessity to load physicsdll audiodll two times first from engineexe and then from the game scriptwriting extensions looks more appealing because it allows doing script bindings on c side on the other hand you have to build your extension with raco ctool link it with mzdyn object file a which looks awkward as well why not make mzdyn a static libraryi would like to implement a single method eg setupscriptbindings both in physicsdll and in audiodll and to call it from engineexe at the startupis there a straightforward way to do it,['c++'] +987614,selenium webdriver beautifulsoup web scraping error 416 i am doing web scraping using selenium webdriver in python with proxyi want to browse more than 10k pages of single site using this scrapingissue is using this proxy i am able to send request for single time only when i am sending another request on same link or another link of this site i am getting 416 error kind of block ip using firewall for 12 hoursnote i am able to do scraping all normal sites with this code but this site has kind of security which is prevent me for scrapinghere is codeprofile webdriverfirefoxprofileprofileset preferencenetworkproxytype 1profileset preference networkproxyhttp 747314842profileset preferencenetworkproxyhttp port 3128profileupdate preferencesbrowser webdriverfirefoxfirefox profileprofilebrowsergettimesleep5element browserfind elements by css selector wellsmnotmbn row colmd4 ul fssmall afor ele in element print eleget attributehrefbrowserquitany solution,['python'] +987651,how to resolve nuget dependency hell i develop a library with some functional named companynamesdk which must be integrated in company project companynamesomesolutioncompanynamesdkdll must be deployed via nuget packageand companynamesdk package has a dependency on 3rd party nuget packages for good example let us take unity current dependency is on v351405prerelease of unitycompanynamesomesolutionproject1 depends on unity v215052companynamesomesolutionproject2 depends on unity v3013041integrating companynamesdk into this solution adds dependency on unity v351405prereleaselet us take that companynamesomesolution has one runnable output project companynamesomesolutionapplication that depends on two above and on companynamesdkand here problems begin all unity assemblies has equal names in all packages without version specifier and in the target folder it will be only one version of unity assemblies v351405prerelease via bindingredirect in appconfighow can code in project1 project2 and sdk use exactly needed versions of dependent packages they were coded compiled and tested withnote1 unity is just an example real situation is 10 times worse with 3rdparty modules dependent on another 3rdparty modules which in turn has 34 versions simultaneouslynote2 i cannot upgrade all packages to their latest versions because there are packages that have dependency notonlatestversion of another packagesnote3 suppose dependent packages has breaking changes between versions it is the real problem why i am asking this questionnote4 i know about question about conflicts between different versions of the same dependent assembly but answers there does not solve the root of a problem they just hide itnote5 where the hell is that promised dll hell problem solution it is just reappearing from another positionnote6 if you think that using gac is somehow an option then write stepbystep guide please or give me some link,"['c#', '.net']" +987893,present of uninitialized color attachment issue when i run my opengl app i get the following errori googled but cannot get any useful informationherere a piece of source code voidrendercathisplaylinkthisplaylink selfcanvas clear glpixelstoreigl unpack alignment 1 glblendfuncgl one gl one minus src alpha glenablegl blend nsinteger mlength mparticlescount nsinteger drawcount 0 nsinteger drawindex 0 wqparticle drawparticle cgfloat drawxdrawydrawscaledrawangle glkmatrix4 changecolormatrix if mlength 0 glbindframebuffergl framebuffer fbo glviewport00widthheight drawcount 0 drawindex 1 while drawcount mlength drawparticle mparticlesdrawcount ifdrawparticleflg random 05 if drawindex drawparticletexindex glactivetexturegl texture0 glbindtexturegl texture 2d gluinttexturedrawparticletexindex gluniform1iglintunilocation1 0 drawindex drawparticletexindex ifdrawparticleflg drawx drawparticleposx random 1 05 drawparticlescale 006 drawy drawparticleposy random 1 05 drawparticlescale 006 drawscale drawparticlescale random 04 08 changecolormatrix self setchangecolorwithdpdrawparticle nrandom drawx drawx drawscale drawy drawy drawscale else drawx drawparticleposx drawparticlescale drawy drawparticleposy drawparticlescale drawscale drawparticlescale changecolormatrix self setchangecolorwithdpdrawparticle n1 gluniformmatrix4fvglintunilocation2 1 0 changecolormatrixm drawangle drawparticleangle cgfloat drawr sqrtdrawx drawx drawy drawy cgfloat oa 2 m pi acosdrawx drawr drawx cosoa drawangle drawr drawy sinoa drawangle drawr mmatrix glkmatrix4identity mmatrix glkmatrix4rotatemmatrix drawangle 0 0 1 mmatrix glkmatrix4scalemmatrix drawscale drawscale drawscale mmatrix glkmatrix4translatemmatrix drawx drawy 0 mvpmatrix glkmatrix4multiplyf tmpmatrix mmatrix gluniform1iglintunilocation3 yes gluniformmatrix4fvglintunilocation0 1 0 mvpmatrixm gldrawelementsgl triangles sizeofindices gl unsigned byte 0 if drawparticlelife 0 mvf getforcefromposwithpxdrawparticleposx pydrawparticleposy drawparticle setvfupdatewithoutxmvfoutx outymvfouty drawcount continue mparticles removeobjectatindexdrawcount mlength mlength 1 glbindframebuffergl framebuffer0 glbindtexturegl texture 2d fbotexture mmatrix glkmatrix4identity mvpmatrix glkmatrix4multiplytmpmatrix mmatrix gluniformmatrix4fvglintunilocation0 1 0 mvpmatrixm gluniform1iglintunilocation3 no gldrawelementsgl triangles sizeofindices gl unsigned byte 0 selfcanvasglcontext presentrenderbuffergl renderbufferhow can i solve this,['ios'] +987957,fast way to turn a labeled image into a dictionary of label coordinates say i have labeled an image with scipyndimagemeasurementslabel like so0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 3 0 2 2 0 0 0 0 2 2 0 0 0 0whats a fast way to collect the coordinates belonging to each label ie something like 1 0 1 1 1 2 1 2 4 0 4 1 5 0 5 1 3 3 4 i am working with images that are 150 x 50 pixels in size and roughly half of each images pixels are labeled ie nonzerorather than iterating through the entire image with nditer would it be faster to do something like npwhereimg label for each labeleditwhich algorithm is fastest depends on how big the labeled image is as compared to how many labels it has warren weckesser and salvador dali bhat irshads methods which are based on npnonzero and npwhere all seem to scale linearly with the number of labels whereas iterating through each image element with nditer obviously scales linearly with the size of labeled imagethe results of a small testsize 10 x 10 num labels 10weckesser 0214357852936s dali 0650229930878s nditer 653645992279s size 10 x 10 num labels 100weckesser 0936990022659s dali 133582305908s nditer 681486487389s size 10 x 10 num labels 10weckesser 843906402588s dali 981303452s nditer 747897100449s size 10 x 10 num labels 10weckesser 100405524015s dali 11817239809s nditer 914583897591sso the question becomes more specificfor labeled images in which the number of labels is on the order of sqrtsizeimage is there an algorithm to gather label coordinates that is faster than iterating through every image element ie with nditer,['python'] +987993,is there a way to change the android status bar color with react native i just got started with react native for android and i am trying to figure out if there is a way to change the status bar color for androidlike this,['android'] +988055,creating directory for okhttp cache on android on android how should i create the file parameter for the comsquareupokhttpcache constructor it seems like context gives you plenty of optionsnew filecontextgetcachedir httpresponsecachenew filecontextgetexternalcachedir httpresponsecachecontextgetdirhttpresponsecache contextmode privatejust wondering what best practice is thanks,['android'] +988107,webpack loading images from html templates i am trying to set up an angular project using webpack but i cannot figure out how to reference images from within html templates and have them included in the buildmy project tree is as followspackagejsonapp images foopng scripts styles templatesi am trying to user htmlloader along with urlloader and fileloader but it is just not happeningthis is an example template apptemplatesfoohtmlimg srcimagesfoopng problem 1 i would like to be able to reference images relative to app right now the paths need to be relative to the template file and this will get ugly very quickly imagesfoopngproblem 2 even if i specify the relative path as i have done above the build is successful but nothing really happens the paths are left asis and no images appear in thisthere is my webpack configvar path requirepathvar webpack requirewebpackvar ngminplugin requirengminwebpackpluginvar htmlwebpackplugin requirehtmlwebpackpluginvar extracttextplugin requireextracttextwebpackpluginvar ngannotateplugin requirengannotatewebpackpluginmoduleexports functionconfig env var approot pathjoin dirname app ifenv env development var webpackconfig cache true debug true contentbase approot entry app pathjoinapproot scriptsappcoffee output path pathjoin dirname thist publicpath librarytarget var filename scriptsnamehashjs chunkfilename namechunkhashjs module loaders test css loader extracttextpluginextractstyleloader cssloader test scss loader extracttextpluginextractstyleloader cssloadersassloaderoutputstyleexpandedincludepathsnode modulesfoundationscss test coffee loader coffeeloader loader ngtemplaterelativeto pathresolve dirname app html test png loader urlloaderlimit10mimetypeimagepngnamepathnamehashext test jpg loader fileloadernamepathnamehashext test woffwoff2 loader urlprefixfactoryntslimit50mimetypeapplicationfontwoff test ttf loader fileprefixfonts test eot loader fileprefixfonts test svg loader fileprefixfonts test json loader json resolve extensions js coffee scss css root approot singlerun true plugins new webpackcontextreplacementplugin a new webpackprovideplugin lodash new extracttextpluginstylesnamechunkhashcss allchunks true new htmlwebpackplugin template approot apphtml filename apphtml inject body chunks app devtool eval ifenv production webpackconfigplugins webpackconfigpluginsconcat new ngannotateplugin new webpackoptimizeuglifyjsplugin new webpackdefineplugin processenv node env jsonstringifyproduction new webpackoptimizededupeplugin new webpackoptimizeuglifyjsplugin webpackconfigdevtool false webpackconfigdebug false return webpackconfig,"['javascript', 'html']" +988119,parsefacebookutils android auth type reauthenticate i am using facebook sdk 3191 parse 180during login via facebook my app asks for basic permissions only public profile emailwhen using parsefacebookutilslogin method how to reask declined permissionsi did not find any param where i could specify auth type,['android'] +988238,when there is performance benefit for writing own swap function method suppose i have class like this onestruct a stdstring a stdstring b stdstring c stdstring dif i use stdswap it probably will do something like this pseudocodevoid stdswapa a a b a tmp stdmovea a stdmoveb b stdmovetmpit will construct empty object tmp using default ctor generally cheap operation then it hopefully move 3 times except in crazy cases when move decay to copyhowever if i do my own swapvoid swapa a a b stdswapaa ba stdswapab bb stdswapac bc stdswapad bdit definitely will use less memory but it still need to construct empty stdstring 4 times i could go wild and make it with single stdstringin all cases it does not look like big improvementonly proper case i could think of is if default ctor is ridiculously expensive am i correct,['c++'] +988276,how to avoid launching the android application twice running from eclipse to real device i am running the application from eclipse and it is being launched twice first time launching the app then again relaunching after few secondsmy app splash screen main activityboth opening twicei already tried adding androidlaunchmodesingleinstance in my manifest file but not successi have tried 3 different applications from my eclipse still opening twice in my kitkat lollipop real device created new project that one also opening twice edit 1 tried adding this line in manifest file but not successandroidlaunchmodesingletopplease let me know how to solve this issuemanifest fileapplication androidallowbackuptrue androidicondrawablelogo androidlabelstringapp name androidlargeheaptrue androidlaunchmodesingleinstance androidthemestyleapptheme2 activity androidnamestart androidlabelstringapp name androidscreenorientationportrait intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity activity androidnamemainactivity androidscreenorientationportrait intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorydefault intentfilter activityapplicationmy start activityjava public class start extends activity sessionmanagerfor signin session override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate session class instance session new sessionmanagerfor signingetapplicationcontext remove the title bar requestwindowfeaturewindowfeature no title setcontentviewrlayoutstart imageview image1imageviewfindviewbyidridimageview1 animation bottom to top translateanimation animation2 new translateanimation00f 00f40f 00f animation2setduration10 animation2setfillafterfalse image1startanimationanimation2 thread timer new thread override public void run try sleep30 catch interruptedexception e eprintstacktrace finally sessionchecklogin finish timerstart for full action bar color starts if buildversionsdk int buildversion codeskitkat settranslucentstatustrue systembartintmanager tintmanager new systembartintmanagerthis tintmanagersetstatusbartintenabledtrue tintmanagersetstatusbartintresourcercolorfullstartcolor for full action bar color ends here targetapi19 private void settranslucentstatusboolean on window win getwindow windowmanagerlayoutparams winparams wingetattributes final int bits windowmanagerlayoutparamsflag translucent status if on winparamsflags bits else winparamsflags bits winsetattributeswinparams,['android'] +988278,check chars in varchar how can i check that varchar contains all chars from another varchar where sequence of characters is irrelevantfor example i have varchar a abc and column col in table table where is row with col cbad i want to select this row because it contains all characters from a variable please for your helpi tried something like thatdeclare a varchar5 abcddeclare b varchar5 dcadeclare i int 0declare pat varchar30 while i lenb begin set i i 1 set pat pat a endselect patif b like pat select 1else select 0but i can not put this to where condition,['sql'] +988323,mpmovieplayer control style bar frame height i am using the mp movie player for playing a live channel feed i am also adding a tap gesture on a view for hiding and unhiding of a collection view this view is then added on the player view playershouldautoplayyes playercontrolstylempmoviecontrolstyledefault viewvideoframe cgrectmake0 0 selfviewframesizewidth selfviewframesizeheight viewvideo addsubviewplayerview uitapgesturerecognizer tapgesture uitapgesturerecognizer alloc initwithtargetself actionselectorhandletap tapgesturedelegateself cgrect aviewframe cgrectmake0 0 selfviewframesizewidth selfviewframesizeheight aview uiview alloc initwithframeaviewframe aview addgesturerecognizertapgesture playerview setuserinteractionenabledyes playerview addsubviewaviewnow the problem i am facing is that when the tap gesture is thisabled then i can use this control state buttons such as full screen and the pause play but if i keep the tap gesture enabled on the player view then i cannot use this control state baris there a way i can put bring the control state bar in front so that i can use this functionsand also what is the fixed height of this control state please specify dimensions for landscape and portrait both,"['ios', 'objective-c']" +988381,c move semantics wrapping legacy c apis i am working with a legacy c api under which acquiring some resource is expensive and freeing that resource is absolutely critical i am using c14 and i want to create a class to manage these resources here is the basic skeleton of the thingclass thingprivate void legacypublic void operation1 int operation2 string operation3private thingvoid legacy legacylegacy this is not really the singleton pattern nothing is static and there may be many thing instance all managing their own legacy resources furthermore this is not merely a smartpointer the wrapped pointer legacy is private and all operations are exposed via some public instance functions that hide the legacy api from consumersthe constructor is private because instances of thing will be returned from a static factory or namedconstructor that will actually acquire the resource here is a cheap imitation of that factory using malloc as a placeholder for the code that would invoke the legacy api public static thing acquire do many things to acquire the thing via the legacy api void legacy malloc16 return a constructed thing return thinglegacy here is the destructor which is responsible for freeing the legacy resource again free is just a placeholder thing noexcept if nullptr legacy do many things to free the thing via the legacy api but do not throw any exceptions free legacy legacy nullptr now i want to ensure that exactly one legacy resource is managed by exactly one instance of thing i did not want consumers of the thing class to pass instances around at will they must either be owned locally to the class or function either directly or via unique ptr or wrapped with a shared ptr that can be passed about to this end i deleted the assignment operator and copy constructorsprivate thingthing const delete void operatorthing const deletehowever this added an additional challenge either i had to change my factory method to return a unique ptrthing or a shared ptrthing or i had to implement move semantics i did not want to dictate the pattern under which thing should be used so i chose to add a moveconstructor and moveassignmentoperator as follows thingthing old noexcept legacyold legacy reset the old things state to reflect the move old legacy nullptr thing operator thing old noexcept if old this swap legacy old legacy return this with this all done i could use thing as a local and move it about thing one thingacquire thing two moveonei could not break the pattern by attempting to commit selfassignment thing one thingacquire one one build errori could also make a unique ptr to one auto three make uniquethingthingacquireor a shared ptr auto three make sharedthingthingacquireeverything worked as i had expected and my destructor ran at exactly the right moment in all my tests in fact the only irritation was that make unique and make shared both actually invoked the moveconstructor it was not optimized away like i had hopedfirst question have i implemented the moveconstructor and moveassignmentoperator correctly they are fairly new to me and this will be the first time i have used one in angersecond question please comment on this pattern is this a good way to wrap legacy resources in a c14 classfinally should i change anything to make the code better faster simpler or more readable,['c++'] +988387,net dictionary with two keys and one value is there a dictionary available in net that could hold 2 keys and one valuelikedictionaryof tkey of tkey tvaluei have a need to store two keys and at certain times look an item by the key 1 and at other times by the key 2my current solution is to maintain two dictionariesdictionarystring long dict1 new dictionarystring longdictionarylong long dict2 new dictionarylong longand when need to add item i will add it to both dictionariesdict1addabc 1dict2add345 1and then i will look up an item from either one of those dictionaries depending by which one of the keys i need to look bysame i will do when deleting or updating an itemi have thought about the composite key but i do not know how to set it up and i do not want to lose any speed of searching the itemis there some solution available in net to have dictionary that can hold multiple keys,"['c#', '.net']" +988398,ios 9 parse v 185 facebook v 46 login crash on fbsdkinternalutility checkregisteredcanopenurlscheme i am doing simple login with facebook using parse for ios 9 using swift 2 i use parsefacebookutilsv4framework from parse i have exactly followed instruction for ios 9 from this link also i am using parse v 185 facebook v 46 however when i try to login like this let permissions user about me user relationships user birthday user location pffacebookutilslogininbackgroundwithreadpermissionspermissions block user pfuser error nserror void in switched to if user nil nsloguh oh the user cancelled the facebook login else if userisnew inserted nsloguser signed up and logged in through facebook else nslog errorlocalizeddescription as string nsloguser logged in through facebook userusername it crash like this i also cannot trace how and why it crash how shall i solve fbsdkinternalutility checkregisteredcanopenurlscheme0x10014ec04 0 stp x22 x21 sp 480x10014ec08 4 stp x20 x19 sp 160x10014ec0c 8 stp x29 x30 sp 320x10014ec10 12 add x29 sp 320x10014ec14 16 sub sp sp 160x10014ec18 20 mov x20 x00x10014ec1c 24 mov x0 x20x10014ec20 28 bl 0x10020d6d0 symbol stub for objc retain0x10014ec24 32 mov x19 x00x10014ec28 36 adrp x8 3410x10014ec2c 40 ldr x8 x8 33200x10014ec30 44 cmn x8 10x10014ec34 48 bne 0x10014ec 200 inlined thispatch once at,['ios'] +988412,how can i force focus to change to a specific view in tvos i am implementing custom code to handle a click on the menu button on the siri remotehow can i force focus to change to my custom menu when pressing the menu button,['objective-c'] +988569,how to render a single page wordpress template with twig i have been trying to render a single page wordpress template with twig but so far everything has failed extends layoutsbasetwig block content for page in pages set up pagepage include contentcontent pagepost name twig endfor endblock what one of the templates looks like section idabout wppost class div classcontainer div classrow div classcollg12 textcenter h2 clasectionheading wpthe title h2 h3 clasectionsubheading textmuted wpget post metawpget the id st page subtitle true h3 to be changed to subtext for title div div div classrow div classcollg12 wpthe content div div divthe corresponding functions wpgetpages new twig simplefunctionpages function currentid get the id menu order wp get nav menu itemsheader menu items array foreachmenu order as item menu items itemid args arraypost type page status publish exclude currentid orderby menu order order asc pages get postsargs return pages wpsetpages new twig simplefunctionset up page functionarg setup postdataarg selftwig environmentaddfunctionwpposts selftwig environmentaddfunctionget theme options selftwig environmentaddfunctionwppostdata selftwig environmentaddfunctionwpgetpages selftwig environmentaddfunctionwpsetpages this brings out the templates but it sets the page title from the template as the title of the home pagewould really appreciate any help on fixing this,['php'] +988650,how to compile a c file with roslyn programmatically i read that you cannot compile c 60 with csharpcodeprovider and therefor trying to do with with roslyn but i cannot find a good example how to load a file and then compile it to a dllhow should i write something similar to this code with roslyn or is there some other way to do it now when i try to compile files that contain reference to projects with c 60 code it just say the type or namespace name x does not exist in the namespace y are you missing an assembly reference public string compilecode var provider new csharpcodeprovider var outputpath pathcombinepathgetdirectoryname path codedll var compilerparams new compilerparameters referencedassemblies outputpath compilerresults results providercompileassemblyfromfilecompilerparams path var dllpath resultspathtoassembly if resultserrorshaserrors return dllpath printerrorresultserrors return in summary i want to load a c filecompile it to a dll so i can load it later,['c#'] +988681,how to keep elements nonrefreshed the main goal is to keep nonrefreshed the logotext div clasmall7 medium4 columns logo and the menu nav classpagedmenu rolenavigationwithout clipping on page refresh or while the content is loading from a page to another also the menu state should be preserved from a page to another i have found here a possible solution that could solve the problem you could use ajax to fetch the updated content and use jquery to put the new content on the page and avoid the refresh entirely doing it that way the existing data in the page would remain untouched said jfriend00 so i have tried to use an ajax plugin called aws in the aws option page i suppose that i have done the right thing pointing wrapper as ajax container id and also pagedmenu as menu container class transition effect enabled no ajax container ids blank no loader selected having already a pulse loader implemented in the themeat this point all i got it is a menu sidemenu shiftnav pulse dot loader content loading malfunction generated perhaps by the wrong defined ajax container id andor menu container class or by a conflict with an existing js jquery code not so surealso in chrome console there is an erroruncaught syntaxerror unexpected token anonymous function ajaxifyjsver431175nextendeach jquery214minjsver2142nfnneach jquery214minjsver2142bindajaxsuccess ajaxifyjsver431169ncallbacksj jquery214minjsver2142ncallbackskfirewith jquery214minjsver2142x jquery214minjsver2144najaxtransportkcorsacrossdomainsendb jquery214minjsver2144everything is getting back to normal on page refresh but does not help at all being uselessi also have to mention that for the menu i have tried to keep the state using jquerystorageapi and storagejquerysessionstorage as you can see in mynewmenujs file but that will not solve the nonrefreshing elements problemthe menu jsfiddle only if this helps to have the whole picture here thanks to diego bettoyou can use this live link as example there is a similar situation with the above described ajax implementation right and regarding the appearance menu is kept nonrefreshed from one page to another if you browse books works etc menu sections youll see if there is a model that could be implemented here i will be glad to find itle meanwhile i have tried another ajaxify solution made by arvgta special thanks without succes yet but as far as i have found from the author the defined elements should be divs with ids not classes so i will try to find a way to modify somehow the code in order to have id instead on classesalso i will try to transform and implement in ajaxifyminjs file the pagecontainer element jquerypagecontainerajaxify i will come back with newsle2 i have tried to implement the solution using ids instead of classes but still the pages are not loading correctly at this point we have ajaxminjs file updated with these linesfunction jquerydocumentreadyfunction jquerypagecontainerajaxifyrequestdelay400formsfalse jquery also i have modified the theme file to have idpagecontainer instead if classpagecontainerin these conditions on menu click the links are changed like it should menu logotext elements seems to working almost fine sometimes get skippy changing position but the content is not loading correctly in all cases same here everything is getting back to normal on manual page refresh f5 but does not help le3 it looks like the conflict is at least between revolution slider plugin and ajaxify errormessagerevolution slider error you have some jqueryjs library include that comes after the revolution files js include this includes make eliminates the revolution slider libraries and make it not work spansite live link here any thoughts alternative in this area not interested in using other different platforms different wordpress themes etc just a workaround in this existing situationle4 as far as i can see there are many users that voted up the jake bown answer that could be indeed a solution but i cannot find the reason that did not work correctly implemented into my theme without errors live link here the elements logotext menu are still fading on refresh are not kept nonrefreshed any thoughts jake bown anyone le finalbuzinas thank you once again for your time and effort delivered the closest answer for my needs taking in consideration my site enviroment plugins installed etc i will come back with news as soon as i have the final solution implemented thank you all,"['javascript', 'jquery', 'html', 'css']" +988682,xcode 7 type arguments cannot be applied to nonparameterized class i am getting this error in my xcode project today i have never got it before the only change i have made since the last successful build is that i imported the iad framework i did that this morning before i tried to do a fresh build so i am not sure if it had anything to do with it i doubt it though all of the issues are with nssetnsarraynsdictionary and are all contained in uikit is uievent and coreimages ciimage if anyone has any idea what might be going on here i would appreciate the inputedit i forgot to mention the specific errors here they aretype arguments cannot be applied to nonparameterized class nssettype arguments canot be applied to nonparameterized class nsarraytype arguments canot be applied to nonparameterized class nsdictionaryedit 2 i did not realize that the app store automatically updated xcode from 64 to 70 so i changed to title to reflect the correct xcode versionheres where it is happening in uieventh lines 50 51 52 53 56 59 nullable nsset uitouch alltouches nullable nsset uitouch touchesforwindowuiwindow window nullable nsset uitouch touchesforviewuiview view nullable nsset uitouch touchesforgesturerecognizer uigesturerecognizer gesture ns available ios3 2 an array of auxiliary uitouchas for the touch events that did not get delivered for a given main touch this also includes an auxiliary version of the main touch itself nullable nsarray uitouch coalescedtouchesfortouchuitouch touch ns available ios9 0 an array of auxiliary uitouchas for touch events that are predicted to occur for a given main touch these predictions may not exactly match the real behavior of the touch as it moves so they should be interpreted as an estimateheres where it is happening in uiresponderh lines 3134 generally all responders which do custom touch handling should override all four of these methods your responder will receive either touchesendedwithevent or touchescancelledwithevent for each touch it is handling those touches it received in touchesbeganwithevent you must handle cancelled touches to ensure correct behavior in your application failure to do so is very likely to lead to incorrect behavior or crashes voidtouchesbegannssetuitouch touches witheventnullable uievent event voidtouchesmovednssetuitouch touches witheventnullable uievent event voidtouchesendednssetuitouch touches witheventnullable uievent event voidtouchescancellednullable nssetuitouch touches witheventnullable uievent eventalso happening in uiresponderh line 79interface uiresponder uiresponderkeycommandsproperty nullablenonatomicreadonly nsarrayuikeycommand keycommands ns available ios7 0 returns an array of uikeycommand objectsendheres where it is happening in ciimageh lines 97 and 102 creates a new image from the contents of image ciimage imagewithcgimagecgimagerefimage ciimage imagewithcgimagecgimagerefimage optionsnullable ci dictionarynsstringid options creates a new image from the contents of layer ciimage imagewithcglayercglayerreflayer ns deprecated mac10 410 11 ciimage imagewithcglayercglayerreflayer optionsnullable ci dictionarynsstringid options ns deprecated mac10 410 11,"['ios', 'objective-c']" +988727,compare image from file and image created from canvas i am testing with protractor and jasmine and i have also included imagediff and nodecanvas in my projecti need to compare two images and make sure they are the same one is saved in my file structure and the other is created from canvas i am able to convert the canvas to image and also load the image from the file heres what i have var imagediff requirenode modulesjsimagediffjsimagediffjsvar canvas requirecanvasvar fs requirefsvar path requirepathbeforeeachfunction jasmineaddmatchersimagediffjasminefunction loadimage url callback var image fsreadfileurl function error data if error throw error image new canvasimage imageonload function callbackimage imagesrc data return imageitshould work function executescript is needed to get the canvas element and convert it browserdriverexecutescriptfunction var can documentqueryselectorworkspacecanvas var ctx cangetcontext2d var data cantodataurlimagepng var img new image imgsrc data this code below shows that the image was converted properly var link documentcreateelementa linkhref imgsrc linkdownload image1png linkclick return data thenfunctionresult newdata result var imgpath pathjoin dirname imagesimage1png loadimageimgpath functionimage consolelogloadimage var canvas new canvas canvaswidth imagewidth canvasheight imageheight var ctx canvasgetcontext2d ctxdrawimageimage 0 0 var data canvastodataurlimagepng olddata data todo do a comparison here done my question is how do i compare the two images and make sure they are the same i thought comparing the data uri would work but it does not i would really like to use imagediff but i am not sure how to do that please help me,['javascript'] +988963,accessing variable values within a macro some time ago i made this beautiful assert macro for c and c programsdefine asserttruthy message if truthy cout message on line line in file file check was truthy endl scatter assert calls throughout your code and it will warn you whenever the truthy value is not truthy very handy during development to remind you of potential mistakesexassertfilesfound 0 could not find any files check your pathwhen filesfound is 0 the macro will print outcould not find any files check your path on line 27 in file openfilesc check was filesfound 0now what i want it to print to give me even more relevant information is the value of any variables passed into the truthy parameter like thiscould not find any files check your path on line 27 in file openfilesc check was filesfound 0 filesfound is 0this seems lisplike territory i wonder is there any black magic c preprocessing that i can use to evaluate variables and functions to their values without evaluating the truthy statementi assume to be thisappointed,['c++'] +988990,in which situations to delete a pointer my following question is on memory management i have for example an int variable not allocated dynamically in a class let us say invar1 and i am passing the memory address of this int to another classes constructor that class does thisclass ex1 ex1int p intvar1 ptoint p intvar1 int ptointshould i delete ptoint because it has the address of an undynamically allocated int i thought i do not need to delete itand again i declare an object to a class with new operatorobjtoclass new ex1and i pass this to another classclass ex2 ex2ex1 p obj obj p obj ex1 objshould i delete obj when i am already deleting objtoclassthanks,['c++'] +989007,in c what is the right way to post attachments to confluence rest api i am migrating from confluences soap api to using their rest api i see there is support for adding attachments to a page by doing a post but i am running into issues getting it to work i am getting a 403 forbidden error message i have other get items working fine through the rest api but doing an attachment post seems to keep failinghere is my current code given a specific filename byte rawdata filereadallbytesfilename var pageid 134 var url new uri pageid childattachment var requestcontent new multipartformdatacontent var imagecontent new bytearraycontentrawdata imagecontentheaderscontenttype mediatypeheadervalueparseattachementcontenttype requestcontentaddimagecontent file attachementfilename requestcontentheadersaddxatlassiantoken nocheckcan you see if i am doing anything wrong above,['c#'] +989019,css border colour into 4 colours is there any way that i can have 4 different colours on one side of a border in css i currently haveheaderbordercolor88a9ebi want to have a border of 4 solid colours with a 25 split on each is this something that is possiblei want to make a solid version of this without the white bits in between,"['html', 'css']" +989104,incorrect message with get accounts permission am trying to update my app with the new android m permissions which uses google login but when i do a checkselfpermissionmanifestpermissionget accounts the dialog that pops up says allow myapp to access your contacts with the deny and allow buttonsthis seems kind of weird for the get accounts permission should not it say something related to access your accounts instead is this a bug or should i be doing something differently,['android'] +989116,unable to play some youtube videos using youtube android player api for example this video cannot be played with youtube player api other videos from search response works oki get the following messages 0925 171850226 2428024280commypackagename wyoutubeandroidplayerapii1 cannot load modern controls ui upgrade to the latest version of the android youtube api0925 171905911 2428024280commypackagename eyoutubeplayerfragmenti1 video error internal erroryoutubeplayer api version 121 latestyoutube app on device is up to date and able to play this videovideo parameters videoembeddabletrue videosyndicatedtrue,['android'] +989146,testing angular emit and on events i am trying to write unit test for my events in controllerbelow is my controllermyappcontrollerparentctrl scope function scope scopemessage some text in parent scopeonupdate parent controller functionevent message scopemessage message controllerchildctrl scope function scope scopeclickfunction function scopemessage parent updated from child controller scopeemitupdate parent controller scopemessage and below is my test that i am trying to writedescribehello controller test function var ctrl scope beforeeachmodulemyapp beforeeachinjectfunction controller rootscope scope rootscopenew spyonscope on ctrl controllerparentctrl scope scope itshould change parentctrl message property from child ctrl function var new hero ralf ninja turtle sub scope scopenew sub scopeemitupdate parent controller new hero expectscopeontohavebeencalled expectscopemessagetoberalf ninja turtle getting err here i am expecting message in the parent controller to be updated but the test is failing at expectscopemessagetoberalf ninja turtle,['javascript'] +989154,methodnotallowedhttpexception in routecollectionphp line 219 when i storing a post i get this errormethodnotallowedhttpexception in routecollectionphp line 219what can cause this problem routesphproutegethome postscontrollerindexrouteget postscontrollerindexroutegetindex postscontrollerindexroutegetposts postscontrollerindexroutegetpostslugid postscontrollershowroutegetpostssukurtinaujastraipsni postscontrollercreateroutepatchpostsstorenewpost postscontrollerstoreroutegetpostslugidedit postscontrollereditroutepatchpostsslug postscontrollerupdateroutegettagstags tagscontrollershowroutegetcategoriescategories categoriescontrollershow authentication routesroutegetauthlogin authauthcontrollergetloginroutepostauthlogin authauthcontrollerpostloginroutegetauthlogout authauthcontrollergetlogout registration routesroutegetauthregister authauthcontrollergetregisterroutepostauthregister authauthcontrollerpostregisteri am using laravel 51 and i cannot figure this out for a day,['php'] +989244,combining columncount and thisplay table renders single column in firefox i am trying to work out an issue in firefox i am using 4003 where using mozcolumncount and thisplay table causes a list to thisplay as one column heres my example and a jsfiddlediv webkitcolumncount 2 chrome safari opera mozcolumncount 2 firefox columncount 2ul thisplay table margin 0 autodiv ul liabcdli libli licdefgli lidli uldivi am using thisplay table to center the columns in the div in edge ie10 and chrome the list is in two columns my question is how can i get two columns with thisplay table in firefox or how to properly center the list so that it works in all browsers,"['html', 'css']" +989275,ckreference deleteself attribute has no effect how does deleteself really work docs sayswhen the reference objectas action is set to ckreferenceactiondeleteself the target of the referenceathat is the record stored in the referenceas recordid propertyabecomes the owner of the source record deleting the target owner record deletes all its source recordsbut my impression is that deleting a target will not always delete source and it is quite annoying when it remains in the container client downloads it and expect that the reference point to somewhere but target does not exist when building up slice of the server data store on client how do you treat this case you ignore that sort of records or periodically you look up the cloudkit storage searching for corrupt records to delete themor instead of deleting a record is it better to set an attribute that it is in a deleted state but keep it in the database,['ios'] +989288,custom browser actions in protractor the problemin one of our tests we have a long clickclick and hold functionality that we solve by usingbrowseractionsmousedownelementperformbrowsersleep50browseractionsmouseupelementperformwhich we would like to ideally solve in one line by having sleep a part of the action chainbrowseractionsmousedownelementsleep50mouseupelementperformclearly this would not work since there is no sleep actionanother practical example could be the humanlike typing for instancebrowseractionsmousemoveelementclick sendkeystsleep50 we should randomize the delays strictly speaking sendkeysesleep10 sendkeysleep20 sendkeyst performnote that these are just examples the question is meant to be genericthe questionis it possible to extend browseractions action sequences and introduce custom actions,['javascript'] +989292,why does isinstance1 2 3 liststr evaluate to true i was playing around a bit with the new type hinting typing module with python35 trying to find a way to confirm if the hinted type is equal to the actual type of the variable and came across something that rather surprised me from typing import list somelist 1 2 3 isinstancesomelist liststrtruecontinuing my search for finding a way to compare a variable to it is hinted type i have also tried this anotherlist foo bar typeanotherlist is liststrfalsewould anyone be able to explain why exactly the former evaluates to trueand continuing onwards is there a sound way to check if a variables type is equal to a type coming from the typing module,['python'] +989325,how make browser update script file when manifest updates but allow caching i have tried two different ways and both do not work1 update the manifest so browser sees there is changes and updatesthis updates all files except javascript files the browser sees there is a difference downloads everything including javascript files but uses the cached version of the javascript files2 send nocache headers see code below to stop caching of script filesthis causes the browser to throw an error and no longer cache anything it says an applicationcache error occurredthe nocache codefilesmatch js fileetag none ifmodule mod headersc header unset etag header set cachecontrol maxage0 nocache nostore mustrevalidate header set pragma nocache header set expires wed 11 jan 1984 050 gmt ifmodulefilesmatchthe above makes all browsers not cache the app for offline useis there a way around this,['javascript'] +989364,how can i mock javatimelocaldatenow in my test case i need test time sensitive method in that method were using java 8 class localdate it is not jodawhat can i do to change time when i am running test,['java'] +989439,serialize javafx model with gson i am currently following a tutorial to help me learn how javafx works and in the tutorial they are building a small app to manage peoples information the tutorial is also using xml for loadingsaving but i do not want to use xml and would like to use json i have a person model that uses stringproperty integerproperty and objectproperty my issue is that i am not exactly sure what the best way to load and save this would be without it saving unnecessary fields and also loading without gson throwing an errorpersonimport javatimelocaldateimport javafxbeanspropertyintegerpropertyimport javafxbeanspropertyobjectpropertyimport javafxbeanspropertysimpleintegerpropertyimport javafxbeanspropertysimpleobjectpropertyimport javafxbeanspropertysimplestringpropertyimport javafxbeanspropertystringproperty model class for a person author marco jakob public class person private final stringproperty firstname private final stringproperty lastname private final stringproperty street private final integerproperty postalcode private final stringproperty city private final objectpropertylocaldate birthday default constructor public person thisnull null constructor with some initial data param firstname param lastname public personstring firstname string lastname thisfirstname new simplestringpropertyfirstname thislastname new simplestringpropertylastname some initial dummy data just for convenient testing thisstreet new simplestringpropertysome street thispostalcode new simpleintegerproperty1234 thiscity new simplestringpropertysome city thisbirthday new simpleobjectpropertylocaldatelocaldateof19 2 21 public string getfirstname return firstnameget public void setfirstnamestring firstname thisfirstnamesetfirstname public stringproperty firstnameproperty return firstname public string getlastname return lastnameget public void setlastnamestring lastname thislastnamesetlastname public stringproperty lastnameproperty return lastname public string getstreet return streetget public void setstreetstring street thisstreetsetstreet public stringproperty streetproperty return street public int getpostalcode return postalcodeget public void setpostalcodeint postalcode thispostalcodesetpostalcode public integerproperty postalcodeproperty return postalcode public string getcity return cityget public void setcitystring city thiscitysetcity public stringproperty cityproperty return city public localdate getbirthday return birthdayget public void setbirthdaylocaldate birthday thisbirthdaysetbirthday public objectpropertylocaldate birthdayproperty return birthday saving where persondata is an observablelist of personstry writer writer new filewriterfile new gsonbuildersetprettyprintingthisablehtmlescapingcreatetojsonpersondata writerthis way of saving currently produces a save with a lot of unnecessary fields like name value etc when it could be firstname hans firstname name value hans valid true helper observable lastname name value muster valid true helper observable street name value some street valid true postalcode name value 1234 valid true city name value some city valid true birthday now when even trying to load the string above with gson it produces an error failed to invoke public javafxbeanspropertystringproperty with no argsloaderperson personstry reader reader new filereaderfile persons gsonfromjsonreader personclasspersondataclearpersondataaddallpersonsi have googled to see if it was possible to use getters and setters with gson but it does not really seem possible so i am stuck on what to do,['java'] +989617,how to override stdhash for an enum defined inside a class i have got an enumeration type defined inside of a class and i want to create an unordered set of those objects as a member of the classinclude unordered setclass foo public enum bar some value error implicit instantiation of stdhash stdunordered setbar getvalues const return values private stdunordered setbar valuesnow i know the obvious answer is to add a custom hash function to the unordered setstdunordered setbar barhasherhowever what i am wondering is if there is a way to specialize stdhash for the bar enum so that anyone who uses unordered map gets the hashing behavior automaticallythis works with every other data type but not enums because enums cannot be forward declaredin order for this to work i would have to put the definition of stdhash after the enum definition but before the first use which means i would have to put it in the middle of the class body which would not work,['c++'] +989825,resttemplate unable to populate object i have following code to send request and receive a response it seems like everything is configured but the code is returning nullpointerexception i am not sure whats missing i printed out readyurl variable which has the correct url address the stacktrace does not offer muchcodetry final string apikey myapi final string url apikey string readyurl url what name resttemplate resttemplate new resttemplate eventsresponse eventresponse resttemplategetforobjectreadyurl eventsresponseclass systemerrprintlnseatwave eventresponsegeteventsgeteventsize line 245 catch nullpointerexception e eprintstacktracexmlrootelementxmlaccessortypexmlaccesstypefieldpublic class eventsresponse xmlelement private status status xmlelementname paging private page page xmlelement private events events public status getstatus return status public void setstatusstatus status thisstatus status public page getpage return page public void setpagepage page thispage page public events getevents return events public void seteventsevents events thisevents events xmlrootelementxmlaccessortypexmlaccesstypefieldpublic class status xmlelementname version private double version xmlelementname timestamputc private date timestamputc xmlelementname code private int code xmlelementname message private string message xmlelementname details private string details public double getversion return version public void setversiondouble version thisversion version public date gettimestamputc return timestamputc public void settimestamputcdate timestamputc thistimestamputc timestamputc public int getcode return code public void setcodeint code thiscode code public string getmessage return message public void setmessagestring message thismessage message public string getdetails return details public void setdetailsstring details thisdetails details xmlrootelementnamepagexmlaccessortypexmlaccesstypefieldpublic class page xmlelementnamepagenumber private int pagenumber xmlelementnamepagesize private int pagesize xmlelementnamepageresultcount private int pageresultcount xmlelementnametotalresultcount private int totalresultcount xmlelementnametotalpagecount private int totalpagecount public int getpagenumber return pagenumber public void setpagenumberint pagenumber thispagenumber pagenumber public int getpagesize return pagesize public void setpagesizeint pagesize thispagesize pagesize public int getpageresultcount return pageresultcount public void setpageresultcountint pageresultcount thispageresultcount pageresultcount public int gettotalresultcount return totalresultcount public void settotalresultcountint totalresultcount thistotalresultcount totalresultcount public int gettotalpagecount return totalpagecount public void settotalpagecountint totalpagecount thistotalpagecount totalpagecount xmlrootelementxmlaccessortypexmlaccesstypefieldpublic class events xmlelement private listevent event public listevent getevent return event public void seteventlistevent event thisevent event xmlrootelementxmlaccessortypexmlaccesstypefieldpublic class event xmlelementname id private int id xmlelementname date private date date xmlelementname eventgroupname private string eventgroupname xmlelementname venuename private string venuename xmlelementname town private string town xmlelementname country private string country xmlelementname ticketcount private int ticketcount xmlelementname currency private string currency xmlelementname minprice private double minprice xmlelementname swurl private string swurl xmlelementname eventgroupimageurl private string eventgroupimageurl xmlelementname layoutid private int layoutid xmlelementname eventgroupid private int eventgroupid xmlelementname venueid private int venueid xmlelementname swsellurl private string swsellurl public int getid return id public void setidint id thisid id public date getdate return date public void setdatedate date thisdate date public string geteventgroupname return eventgroupname public void seteventgroupnamestring eventgroupname thiseventgroupname eventgroupname public string getvenuename return venuename public void setvenuenamestring venuename thisvenuename venuename public string gettown return town public void settownstring town thistown town public string getcountry return country public void setcountrystring country thiscountry country public int getticketcount return ticketcount public void setticketcountint ticketcount thisticketcount ticketcount public string getcurrency return currency public void setcurrencystring currency thiscurrency currency public double getminprice return minprice public void setminpricedouble minprice thisminprice minprice public string getswurl return swurl public void setswurlstring swurl thisswurl swurl public string geteventgroupimageurl return eventgroupimageurl public void seteventgroupimageurlstring eventgroupimageurl thiseventgroupimageurl eventgroupimageurl public int getlayoutid return layoutid public void setlayoutidint layoutid thislayoutid layoutid public int geteventgroupid return eventgroupid public void seteventgroupidint eventgroupid thiseventgroupid eventgroupid public int getvenueid return venueid public void setvenueidint venueid thisvenueid venueid public string getswsellurl return swsellurl public void setswsellurlstring swsellurl thisswsellurl swsellurl exceptionjavalangnullpointerexception at commyprojectticketsserviceticketseviceimplseatwaveticketseviceimpljava245 at commyprojectticketsserviceticketseviceimplfindticketticketseviceimpljava45 at commyprojectwebticketcontrollerfindticketticketcontrollerjava29 at sunreflectnativemethodaccessorimplinvoke0native method at sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava57 at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43 at javalangreflectmethodinvokemethodjava606 at orgspringframeworkwebmethodsupportinvocablehandlermethoddoinvokeinvocablehandlermethodjava221 at orgspringframeworkwebmethodsupportinvocablehandlermethodinvokeforrequestinvocablehandlermethodjava137 at orgspringframeworkwebservletmvcmethodannotationservletinvocablehandlermethodinvokeandhandleservletinvocablehandlermethodjava110 at orgspringframeworkwebservletmvcmethodannotationrequestmappinghandleradapterinvokehandlemethodrequestmappinghandleradapterjava7 at orgspringframeworkwebservletmvcmethodannotationrequestmappinghandleradapterhandleinternalrequestmappinghandleradapterjava706 at orgspringframeworkwebservletmvcmethodabstracthandlermethodadapterhandleabstracthandlermethodadapterjava85 at orgspringframeworkwebservletthispatcherservletdothispatchthispatcherservletjava943 at orgspringframeworkwebservletthispatcherservletdoservicethispatcherservletjava877 at orgspringframeworkwebservletframeworkservletprocessrequestframeworkservletjava966 at orgspringframeworkwebservletframeworkservletdogetframeworkservletjava857 at javaxservlethttphttpservletservicehttpservletjava621 at orgspringframeworkwebservletframeworkservletserviceframeworkservletjava842 at javaxservlethttphttpservletservicehttpservletjava728 at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava305 at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava210 at orgspringframeworksecuritywebfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava369 at orgspringframeworksecuritywebaccessinterceptfiltersecurityinterceptorinvokefiltersecurityinterceptorjava109 at orgspringframeworksecuritywebaccessinterceptfiltersecurityinterceptordofilterfiltersecurityinterceptorjava83 at orgspringframeworksecuritywebfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava381 at orgspringframeworksecuritywebaccessexceptiontranslationfilterdofilterexceptiontranslationfilterjava97 at orgspringframeworksecuritywebfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava381 at orgspringframeworksecuritywebsessionsessionmanagementfilterdofiltersessionmanagementfilterjava100 at orgspringframeworksecuritywebfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava381 at orgspringframeworksecuritywebauthenticationanonymousauthenticationfilterdofilteranonymousauthenticationfilterjava78 at orgspringframeworksecuritywebfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava381 at orgspringframeworksecuritywebauthenticationremembermeremembermeauthenticationfilterdofilterremembermeauthenticationfilterjava112 at orgspringframeworksecuritywebfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava381 at orgspringframeworksecuritywebservletapisecuritycontextholderawarerequestfilterdofiltersecuritycontextholderawarerequestfilterjava54 at orgspringframeworksecuritywebfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava381 at orgspringframeworksecuritywebsavedrequestrequestcacheawarefilterdofilterrequestcacheawarefilterjava35 at orgspringframeworksecuritywebfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava381 at orgspringframeworksecuritywebauthenticationwbasicauthenticationfilterdofilterbasicauthenticationfilterjava177 at orgspringframeworksecuritywebfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava381 at orgspringframeworksecuritywebauthenticationabstractauthenticationprocessingfilterdofilterabstractauthenticationprocessingfilterjava187 at orgspringframeworksecuritywebfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava381 at orgspringframeworksecuritywebauthenticationlogoutlogoutfilterdofilterlogoutfilterjava105 at orgspringframeworksecuritywebfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava381 at orgspringframeworksecuritywebcontextsecuritycontextpersistencefilterdofiltersecuritycontextpersistencefilterjava79 at orgspringframeworksecuritywebfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava381 at orgspringframeworksecuritywebfilterchainproxydofilterfilterchainproxyjava168 at orgspringframeworkwebfilterdelegatingfilterproxyinvokedelegatedelegatingfilterproxyjava344 at orgspringframeworkwebfilterdelegatingfilterproxydofilterdelegatingfilterproxyjava261 at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava243 at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava210 at orgapachecatalinacorestandardwrappervalveinvokestandardwrappervalvejava2 at orgapachecatalinacorestandardcontextvalveinvokestandardcontextvalvejava123 at orgapachecatalinaauthenticatorauthenticatorbaseinvokeauthenticatorbasejava502 at orgapachecatalinacorestandardhostvalveinvokestandardhostvalvejava171 at orgapachecatalinavalveserrorreportvalveinvokeerrorreportvalvejava99 at orgapachecatalinavalvesaccesslogvalveinvokeaccesslogvalvejava953 at orgapachecatalinacorestandardenginevalveinvokestandardenginevalvejava118 at orgapachecatalinaconnectorcoyoteadapterservicecoyoteadapterjava408 at orgapachecoyotehttp11abstracthttp11processorprocessabstracthttp11processorjava1023 at orgapachecoyoteabstractprotocolabstractconnectionhandlerprocessabstractprotocoljava589 at orgapachetomcatutilnetjioendpointsocketprocessorrunjioendpointjava312 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava1145 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava615 at javalangthreadrunthreadjava744sample result xml version10 encodingutf8eventsresponse xmlnsi status version20version timestamputc20150927t084424timestamputc code0code messagesuccessmessage details status paging pagenumber1pagenumber pagesize50pagesize pageresultcount50pageresultcount totalresultcount7889totalresultcount totalpagecount158totalpagecount paging events event id948040id date20150927t1430date eventgroupnamethe lion king londoneventgroupname venuenamelyceum theatre londonvenuename townlondontown countryukcountry ticketcount183ticketcount currencygbpcurrency minprice2975minprice swurlampappid203710swurl eventgroupimageurl 0277 1 mainpicturejpgeventgroupimageurl layoutid232layoutid eventgroupid277eventgroupid venueid232venueid swsellurlampaffidampappid2037810swsellurl event event id987509id date20150927t150date eventgroupnameamerican idioteventgroupname venuenamearts theatre londonvenuename townlondontown countryukcountry ticketcount28ticketcount currencygbpcurrency minprice357minprice swurlampappid2037810swurl eventgroupimageurl 32152 1 1 201209091615jpgeventgroupimageurl layoutid4576layoutid eventgroupid32152eventgroupid venueid4207venueid swsellurlampaffidampappid2037810swsellurl event event id948273id date20150927t150date eventgroupnamematilda the musicaleventgroupname venuenamecambridge theatrevenuenameupdatei added this code right after resttemplategetforobject line but nothing will be shown on consoleifeventresponse null systemerrprintlnit is null else systemerrprintlnmessageeventresponsegetstatusgetmessage,['java'] +989829,branch prediction at no cost i have just stumbled upon this thing and i am really curious if maybe modern cpus current ones maybe mobile ones as well embedded do not actually have a branching cost in the situation below1let us say we have this x a let us assume they are both declared earlier as simple ints if flag do a let us assume a is not the same as b else do b and of course b is different than a 2compared to this if flag x a do a else x a do b assuming a and b are completely different in therms of pipeline instructions fetch decode execute etcis the 2nd approach going to be faster are cpus smart enough to tell that no matter what the flag is the next instruction is the same so they would not have to thiscard pipeline stages for it because of branch miss prediction notein the first case the cpu has no option but to thiscard the first few pipeline stages of the do a or do b if a branch miss prediction happened because they are different i see the 2nd example as a somehow delayed branching like i am going to check that flag even if i do not know the flag i can get on with the next instruction because it is the same no matter what the flag is i already have the next instruction and it is ok for me to use itediti did some research and i have some nice results how would you explain this behavior sorry for my latest edit but i had some cache problems as far as i could see these are more accurate results and code samples i hopehere is the code compiled with gcc version 482 ubuntu 48219ubuntu1 using o3case 1include stdiohextern int cacheextern bool bextern int xextern int aextern unsigned long loopextern void aextern void bint main for unsigned long i 0 i loop i cache x a if b a else b delete b delete x delete a delete loop delete cache return 0int cache new int0bool b new booltrueint x new int0int a new int0unsigned long loop new unsigned long0x0fevoid a x b false void b x b true case 2include stdiohextern int cacheextern bool bextern int xextern int aextern unsigned long loopextern void aextern void bint main for unsigned long i 0 i loop i cache if b x a a else x a b delete b delete x delete a delete loop delete cache return 0int cache new int0bool b new booltrueint x new int0int a new int0unsigned long loop new unsigned long0x0fevoid a x b false void b x b true there is pretty much unnoticeable difference between the o3 versions of both approaches but without o3 second case does run slightly faster at least on my machinei have tested without o3 and with the loop 0xfebest timesalinubuntudesktop time 1 real 0m20231suser 0m20224ssys 0m0020s alinubuntudesktop time 2 real 0m19932suser 0m19890ssys 0m0060s,"['c++', 'c']" +989851,generated javadoc pages unneccesarily wrap method arguments with annotations if i generate javadoc for a method the method parametersexceptions unnecessarily get wrapped into a new line like thisthere is plenty of horizontal space left on the page using oracle javadocexe 8u60how can i prevent these unnecessary line breaks without having to manually edit the html filesthis is the source code of the part shown in the screenshotul classblocklist li classblocklist a namemethoddetail a h3method detailh3 a namegetrootword a ul classblocklist li classblocklist h4getrootwordh4 prenotnullpublicnbspa href titleclass or interface in javalangstringanbspgetrootwordpre li ul a namesetrootwordjavalangstring a ul classblocklist li classblocklist h4setrootwordh4 prepublicnbspvoidnbspsetrootwordnotnull a href titleclass or interface in javalangstringanbsprootwordpre li ul a namegetadjectivedeclension a ul classblocklist li classblocklist h4getadjectivedeclensionh4 prenotnullpublicnbspa hrefcomkayoncoreadjectiveadjectivedeclensionhtml titleinterface in comkayoncoreadjectiveadjectivedeclensionanbspgetadjectivedeclension throws a hrefcomkayoncorenodeclensionexceptionhtml titleclass in comkayoncorenodeclensionexceptionapre dl dtspan classthrowslabelthrowsspandt ddcodea hrefcomkayoncorenodeclensionexceptionhtml titleclass in comkayoncorenodeclensionexceptionacodedd dl li ul a namesetadjectivedeclensioncomkayoncoreadjectiveadjectivedeclension a ul classblocklist li classblocklist h4setadjectivedeclensionh4 prepublicnbspvoidnbspsetadjectivedeclensionnullable a hrefcomkayoncoreadjectiveadjectivedeclensionhtml titleinterface in comkayoncoreadjectiveadjectivedeclensionanbspadjectivedeclensionpre li ul liulthe source code above is extracted condensed and processed by a html formatter for easier reading here is the very raw complete file,['java'] +989929,conditionally load polyfills i am building a website which my target group is very general ages 13oo so hello ie9 hello ancient android browser so i need polyfills for some stuff viewport calc etc before i used modernizr and some conditionals user agents to target ios 67 etc then with yepnopejs i was loading the specific polyfillsnow that modernizr 30 is out i noticed that the modernizrload is deprecated also the yepnopejs library is deprecated as they say on their websitethere are new best practices that you should likely follow insteadbut i cannot find any of them after googling for some time everyone recommend modernizr and yepnope but this issue is so fresh the deprecation the new version of modernizr and i cannot find any new alternative methodmaybe using of some module loader like requirejs will do the job and if yes how,['javascript'] +990080,where and when to get data for watch complication after working with complications for a few days i feel confident saying the following about the update process for updates that happen at a prescribed intervalthe system calls requestedupdatedidbeginthis is where you can determine if your data has changed if it has not your app does not have to do anything if your data has changed you need to call eitherreloadtimelineforcomplication if all your data needs to be resetextendtimelineforcomplication if you only need to add new items to the end of the complication timelinenote the system may actually call requestedupdatebudgetexhausted instead of requestedupdatedidbegin if youve spent too much of your complications time budget for the day this is the reason for this questionif you called reloadtimelineforcomplication the system will call getcurrenttimelineentryforcomplication along with the future and past variants that get arrays depending on your time travel settingsthis is conjecture as i have not tested it yet but i believe if you called extendtimelineforcomplication that only the gettimelineentriesforcomplication afterdate date nsdate would be calledthe system will then call getnextrequestedupdatedatewithhandler so you can specify how long until your complication requires a new updateapples documentation is quite clear that you should not ask for updates too often or conduct too much processing in the complication code or you will exhaust your time budget and your complication will stop updating so my question is where and when do you do the updatefor context my scenario is a url with return data that changes up to two times per hourthe most obvious place in which to put the url fetch code is func requestedupdatedidbegin fetch the data store it and if there is no change just return if there was a change then extend or reload the timelinehowever a url fetch can be costly alternativesput the code on the phone app and send it over with a wcsession but if the user closes that app then the updates will no longer happenuse push updates but this is not a web app so i have no place to send them fromobviously i will update all the data when the user interacts with the watch app but that now means it only gets updated when the user uses the app which negates the need for a complicationis there anywhere else can i have a periodic function in the watch app that is not part of the complication where is the right place to fetch the data for a complication update,['ios'] +990124,is componentdidmount of parent called after all componentdidmount of children i have the code below in my render of parentdiv thisstateosmdatamapfunctionitem index return chart keyindex featureitem refcharts divand code below in my child chartdiv classnameallcharts chartistgraph datachartdata typeline optionsoptions divi thought the componentdidmount of parent is called only after all childs are loaded but here the componentdidmount of parent is called before the componentdidmount of childis this how things work or am i doing something wrongif this is how things work how would i detect when all the child components are loaded from parent,['javascript'] +990611,hibernate creating wrong entity subtype in relationship i have a strange issue where hibernate does not create the expected entity type in a many to one relataionship we have the following entities with subclass hierarchy simplifiedentitytablename ainheritancestrategy inheritancetypesingle tablethiscriminatorcolumnname thiscriminator thiscriminatortype thiscriminatortypestring length 1public abstract class a id public long getid entitythiscriminatorvalue1public class a1 extends a entitythiscriminatorvalue2public class a2 extends a entitytablename binheritancestrategy inheritancetypesingle tablethiscriminatorcolumnname thiscriminator thiscriminatortype thiscriminatortypestring length 1public abstract class baclass extends a protected aclass a id public long getid public abstract aclass geta public void setaaclass a entitythiscriminatorvalue1public class b1 extends ba1 override manytoonefetch eager joincolumnname a id public a1 geta entitythiscriminatorvalue2public class b2 extends ba2 override manytoonefetch eager joincolumnname a id public a2 geta in persistencexml both entities are declared in the ordera2a1b2b1now i create instances of a1 and b1 in the dba1 a1 new a1entitymanagerpersista1b1 b1 new b1b1setaa1entitymanagerpersistb1i can see the instances are saved to the db correctly each have id 1 thiscriminator is also 1 a id in b is also 1when i now try to get the b in another hibernate sessionb b entitymanagerfindbclass 1li get the exceptionorghibernatepropertyaccessexception exception occurred inside getter of bcaused by javalangclasscastexception a2 cannot be cast to a1at b1getab1java61 108 more with debugging i found out that hibernate is creating the correct entity of type b1 and creates an incorrect entity of type a2 for the relationship to a the correct type a1 is created if the order in the persistencexml is changed it seems like hibernate does not take the thiscriminator column of a table into account in this case but always creates the first subtype declared in the configuration how can this be fixed is there something wrong with the annotationsi also had the concrete implementation of method geta with its annotations in the supertype b at first but this leads to similar problems,['java'] +990658,maximum recursion depth error in python when calling supers init i have a class hierarchy a b c in b i need some processing in the constructor so i came up with this code from this post understanding python super with init methodsusrbinpythonclass aobject def init self v v2 selfv v selfv2 v2class ba def init self v v2 do some processing superself class self init v v2class cb def hello print v v2b b3 5print bvprint bv2c c12print chowever i have an runtime error from maximum recursion exceeded file evenmorepy line 12 in init superself class self init v v2runtimeerror maximum recursion depth exceeded while calling a python objectwhat might be wrong,['python'] +990961,why does opentrue w print the text like sysstdoutwrite i have the following codewith opentrue w as f fwritehellowhy does this code print the text hello instead of raise an error,['python'] +990969,xcodebuild exportarchive exportoptionsplist error for key method expected one of i am using command line xcodebuild tool to export adhoc thistribution ipa file out of my archive like thisxcodebuild exportarchive archivepath patharchivexcarchive exportpath path exportoptionsplist pathoptionsplisthowever this command fails with errorexportarchive exportoptionsplist error for key method expected one of but found adhocno mater what method i provide in my export options plist it always fails with this error it also fails if i remove the method option from the plist file,['ios'] +990990,why do optional parameters get passed wrong values in visual studio 2015 i found a weird behavior in vs2015 here are the detailsi have a net 46 project referencing a 35 assembly this assembly defines in one of it is interfaces the following method that i was able to inspect using resharper decompilervoid writestringmarshalasunmanagedtypebstr in string data in bool flushandend truetake note of the last optional argument flushandend which has a default value of true the problem now is when i use this method in my project hovering over the method name shows the usual vs tooltip which details the method signature except that for me it shows a wrong default value of the optional argument flushandend heres a screenshotto make things even worse i have noticed that during runtime when calling the method writestringwith only the first parameter flushandend gets set to false and not its default value defined in the dll i am referencing the impact of this on our project was big because it rendered a big feature of our app useless and blocked a big part of our regression testsi was able to overcome this problem by forcing the value of the optional argument to true when calling the method but i am afraid there are other calls somewhere else in the project that suffer from the same problem so i will need a better solution for this or to at least understand whats the cause behind this behaviorweve just upgraded our environment weeks ago before we were using vs2013 and everything worked finei am aware of the confirmed net 46 bug which causes some arguments to be passed wrong values and i can relate it to my issue here but as it is said in the article the bug only occurs when compiling for x64 architecture my project is a wpf application and we compile it to be x32why is writestring called with wrong default argumenti will try later to isolate the problem in a small project and see if i can reproduce the problemedit i have managed to isolate the problem and found some interesting stuffi created a simple net 46 console application added a reference to my dll and wrote the following simple code that consist of sending a command to a device and reading the responseprivate static void mainstring args init managers resourcemanager iomgr new resourcemanagerclass formattedio488 instrument new formattedio488class connect to the usb device instrumentio imessageiomgropenusb00x09570x0909my463123580instr string cmd idn this is the problematic method from my dll instrumentwritestringcmd read the response string responsestring instrumentreadstring consolewritelineresponsestring consolereadkey what i did next is open this project from both vs 2013 and vs 2015 in both versions of vs i did rebuild the project and run it here are the resultsvs2013 writestring was called using the correct default value of flushandend which is true meaning flush the buffer and end the commandvs2015 writestring was called using the wrong default value of flushandend which gave a timeout exceptionfurther inspections between the two versions of visual studio shows that the object browser viewer in vs2013 shows the method signature asvoid writestringstring data bool flushandend truewhile the object browser in vs2015 shows the method signature asvoid writestringstring data bool flushandend falsethe only explanation of this behavior is that there is a problem with vs2015 compiler not reading correct default values from the assembly,"['c#', '.net']" +991045,how to change the hint size of textinputlayout this is my xmlandroidsupportdesignwidgettextinputlayout stylestylemain input text androidlayout margintopdimenactivity medium margin apphinttextappearancestyletextappearenceapptextinputlayout androidsupportv7widgetappcompatedittext stylestylemain edit text androidinputtypetext androidsupportdesignwidgettextinputlayoutand this is stylestyle namemain input text item nameandroidlayout widthmatch parentitem item nameandroidlayout heightdimenactivity edittext heightitem item nameandroidbackgrounddrawablemc shape border button transparentitem item nameandroidgravitycenter verticalitem item nameandroidpaddingtopdimenactivity extra small marginitem item nameandroidpaddingbottomdimenactivity extra small marginitem item nameandroidkeytextsize8spitem item nameandroidtextsize8spitemstylei do not find something like hintsize textsize and keytextsize not helping,['android'] +991178,receiving refresh token from windows live sdk in universal windows app i am developing an universal windows app windows 10 where i have a twolayered app on iotdevices eg raspberry pi 2 it just thisplays content but on all other devices pc notebook smartphone etc you have something like an controller for the thisplayed dataone of the features i want to realize is the windows live login in the controller part to get calendar information in the thisplayiotpart for that i give users the opportunity to login with windows live as shown belowliveauthclient auth new liveauthclientliveloginresult loginresult await authloginasyncnew string wlsignin wlcalendars wloffline access if loginresultstatus liveconnectsessionstatusconnected save the accesstoken from loginresultsessionaccesstoken tokenhandlersaveloginresultsessionaccesstoken accesstoken is quite accessable right here but as far as i know i should save the refreshtoken but the session has no field for itso my proplem is that i do not get a field from the liveconnectsession where the refreshtoken could be stored but all articles i read are telling that i just need to add wloffline access to the scopes for receiving an refreshtokeni am not very familiar with oauth20 and sdks apis are building on oauth so does someone knows anything what i am doing wrong or how i have to handle iti am really thankful for all well meant and helpful answersps i am using the live sdk 56 and not the new onedrive api because it has no access to calendar information,['c#'] +991207,dnx beta8 aspnet 5 and kestrel in azure as of aspnet announcement 69aspnet 5 applications run in iis have been hosted by a component named helios and in beta8 were thiscontinuing the helios iis hostalsohosting aspnet 5 applications in iis will now be achieved using the iis httpplatformhandler configured to forward through to the aspnet 5 kestrel server this native iis module manages the launching of an external application host process in this case dnxexe and the routing of requests from iis to the hosted processthe problem i have right now is that i have spent a few days stumbling through the internet looking how to host dnx application with httpplatformhandler in azure and achieved nothing workingwhat steps i should take to migrate from aspnet 5 beta7 to aspnet 5 beta 8,['asp.net'] +991234,how to compare a given date from today i want to compare a given date to today and here is the condition if provided date is greater than or equal to 6 months earlier from today return true else return falsecodestring strdate tbdatetext 20150329if datetimenowaddmonths6 datetimeparsestrdate if given date is equal to exactly 6 months past from today change to if date has to be less 6 months lblresulttext true this does not work with the entered date aboveelse otherwise give me the date which will be 6 months from a given date datetime dt2 converttodatetimestrdate lblresulttext 6 months from given date is dt2addmonths6 this works fineif 6 months or greater than 6 months is what i would like for oneconditionif less than 6 months is another condition,['c#'] +991321,how to remove special characters from string in swift 2 the answer inhow to strip special characters out of string is not workinghere is what i got and it gives me an error func removespecialcharsfromstringstr string string let chars setstring setarrayliteral abcdefghijklmnopqrstuvwxyz abcdefghijklkmnopqrstuvwxyz1234567890 return stringstrcharactersfilter charscontains0 error here at 0the error at 0 says elementaka character cannot be converted to expected argument type string,['ios'] +991491,retrofit 2 file downupload i am trying to downupload a file with retrofit 2 but cannot find any tutorials examples on how to do somy code for downloading isgetdocumentscheckoutpublic callfile checkoutqueryvalue documenturl string documenturl queryvalue accesstoken string accesstoken queryvalue readonly boolean readonlyandcallfile call retrofitsingletongetinstanceserveraddress checkoutdocumentgetcontenturl apitoken readonlyicallenqueuenew callbackfile override public void onresponseresponsefile response retrofit retrofit string filename documentgetfilename try systemoutprintlnresponsebody long filelength responsebodylength inputstream input new fileinputstreamresponsebody file path environmentgetexternalstoragedirectory file file new filepath filename bufferedoutputstream output new bufferedoutputstream new fileoutputstreamfile byte data new byte1024 long total 0 int count while count inputreaddata 1 total count outputwritedata 0 count outputflush outputclose catch ioexception e string logtag temptag logelogtag error while writing file logelogtag etostring override public void onfailurethrowable t todo error handling systemoutprintlnttostring i have tried with call and call but nothing seems to workthe serverside code writes the files bytes into httpservletresponses output stream after setting the headers and mime type correctlywhat am i doing wrongfinally the upload codemultipartpostdocumentscheckinpublic callstring checkinqueryvalue documentid string documentid queryvalue name string filename queryvalue accesstoken string accesstoken partfile requestbody fileandrequestbody requestbody requestbodycreatemediatypeparsedocumentgetmimetype file callstring call retrofitsingletongetinstanceserveraddresscheckindocumentid documentgetfilename apitoken requestbody callenqueuenew callbackstring override public void onresponseresponsestring response retrofit retrofit systemoutprintlnresponsebody override public void onfailurethrowable t systemoutprintlnttostring thanksedit after the answer downloading only yields a corrupted file without the streaming uploading does not as well when i use the above code the server returns a 400 error after changing it torequestbody requestbody requestbodycreatemediatypeparsedocumentgetmimetype file multipartbuilder multipartbuilder new multipartbuilder multipartbuilderaddformdatapartfile documentgetfilename requestbody callstring call retrofitsingletongetinstanceserveraddresscheckindocumentid documentgetfilename apitoken multipartbuilderbuild the request executes but the backend does not seem to receive a filebackend coderequestmappingvalue documentscheckin method requestmethodpostpublic void checkindocumentrequestparam string documentid requestparam string name requestparam multipartfile file requestparam string accesstoken httpservletresponse responsewhat am i doing wrong i was able to use the backend from plain java with the apache httpclient multipartentitybuilder builder multipartentitybuildercreate buildersetmodehttpmultipartmodebrowser compatible builderaddbinarybodyfile new fileetemptestjpg httpentity httpentity builderbuild systemoutprintlnhttpentity entityutilstostringhttpentity httppost httppost new httpposturi httppostsetentityhttpentityedit v2for anyone interested both up and downloading work now these are the solutionsservicegetdocumentscheckoutpublic callresponsebody checkoutqueryvalue documenturl string documenturl queryvalue accesstoken string accesstoken queryvalue readonly boolean readonlymultipartpostdocumentscheckinpublic callstring checkinqueryvalue documentid string documentid queryvalue name string filename queryvalue accesstoken string accesstoken partfile requestbody filedownload code callresponsebody call retrofitsingletongetinstanceserveraddress checkoutdocumentgetcontenturl apitoken readonlyi callenqueuenew callbackresponsebody override public void onresponseresponseresponsebody response retrofit retrofit string filename documentgetfilename try file path environmentgetexternalstoragedirectory file file new filepath filename fileoutputstream fileoutputstream new fileoutputstreamfile ioutilswriteresponsebodybytes fileoutputstream catch ioexception e logelogtag error while writing file logelogtag etostring override public void onfailurethrowable t todo error handling systemoutprintlnttostring upload code callstring call retrofitsingleton getinstanceserveraddresscheckindocumentid documentgetfilename apitoken multipartbuilderbuild callenqueuenew callbackstring override public void onresponseresponsestring response retrofit retrofit handle response here override public void onfailurethrowable t todo error handling systemoutprintlnerror systemoutprintlnttostring,['android'] +991815,trycatch block in the main function without brackets visual studio 2015 c languagei remember that i read somewhere about the entry point ie main method what it is possible to write thisinclude iostreamusing namespace stdint maintry return 0 i am herecatch cout i am catch endl this row was not called return 1 oops but the next f10 key pressing jumps from the try block into this rowie at this case the trycatch block is located not in the bracketsint main start bracket try return 0 catch return 1 end bracketboth cases are compiled successfully and work too but in the first variant when i am step by step pressing the f10 key after the try block i get into the catch block also for the second variant of code i have not such behaviourwhy does it happen,['c++'] +991817,creating daemon using python libtorrent for fetching meta data of 100k torrents i am trying to fetch meta data of around 10k torrents per day using python libtorrentthis is the current flow of codestart libtorrent sessionget total counts of torrents we need metadata for uploaded within last 1 dayget torrent hashes from db in chunks create magnet link using those hashes and add those magnet uris in the session by creating handle for each magnet urisleep for a second while meta data is fetched and keep checking whether meta data s found or notif meta data is received add it in db else check if we have been looking for meta data for around 10 minutes if yes then remove the handle ie dont look for metadata no more for nowdo above indefinitely and save session state for futureso far i have tried thisusrbinenv python this file will run as client or daemon and fetch torrent meta data ie torrent files from magnet uriimport libtorrent as lt libtorrent libraryimport tempfile for settings parameters while fetching metadata as temp dirimport sys getting arguiments from shell or exit scriptfrom time import sleep sleepimport shutil removing directory tree from temp directory import ospath for getting pwd and other thingsfrom pprint import pprint for debugging showing object dataimport mysqldb db connectivity import osfrom datetime import date timedeltasession ltsessionltfingerprintut 3 4 5 0 flags0sessionlisten on6881 6891sessionadd extensionut metadatasessionadd extensionut pexsessionadd extensionsmart bansessionadd extensionmetadata transfersession save filename magnet2torrentmagnet to torrent daemonsave stateifospathisfilesession save filename fileread opensession save filename rb sessionload stateltbdecodefilereadread filereadclose printsession loaded from fileelse printnew session startedsessionadd dht routerrouterutorrentcom 6881sessionadd dht routerrouterbittorrentcom 6881sessionadd dht routerdhttransmissionbtcom 6881sessionadd dht routerdhtaelitiscom 6881sessionstart dhtsessionstart lsdsessionstart upnpsessionstart natpmpalive truewhile alive db conn mysqldbconnect host user passwd db unix socketmysqlmysqlsock open database connection printreconnecting get all records where enabled 0 and uploaded within yesterday subset count 100 yesterday datetoday timedelta1 yesterday yesterdaystrftimeymd hms printyesterday total count query select count as total count from content where upload date yesterday and enabled 0 printtotal count query try total count cursor db conncursor prepare a cursor object using cursor method total count cursorexecutetotal count query execute the sql command total count results total count cursorfetchone fetch all the rows in a list of lists total count total count results0 printtotal count except print error unable to select data total pages total countsubset count printtotal pages current page 1 whilecurrent page total pages from count current page subset count subset count printcurrent page printfrom count hashes get mysql data query select hash from content where upload date yesterday and enabled 0 order by record num desc limit strfrom count strsubset count printget mysql data query try get mysql data cursor db conncursor prepare a cursor object using cursor method get mysql data cursorexecuteget mysql data query execute the sql command get mysql data results get mysql data cursorfetchall fetch all the rows in a list of lists for row in get mysql data results hashesappendrow0upper except print error unable to select data printhashes handles for hash in hashes tempdir tempfilemkdtemp add magnet uri params save path tempdir duplicate is error true storage mode ltstorage mode t2 paused false auto managed true duplicate is error true magnet uri magnetxturnbtih hashupper trudp3a2f2ftrackeropenbittorrentcom3a80trudp3a2f2ftrackerpublicbtcom3a80trudp3a2f2ftrackercde3a80 printmagnet uri handle ltadd magnet urisession magnet uri add magnet uri params handlesappendhandle push handle in handles list printhandles length is printlenhandles whilelenhandles 0 for h in handles printinside handles for each loop if hhas metadata torinfo hget torrent info final info hash strtorinfoinfo hash final info hash final info hashupper torfile ltcreate torrenttorinfo torcontent ltbencodetorfilegenerate tfile size lentorcontent try insert cursor db conncursor prepare a cursor object using cursor method insert cursorexecuteinsert into dht tfiles hash tdata values s s final info hash torcontent db conncommit print data inserted in db except mysqldberror e try print mysql error d s eargs0 eargs1 except indexerror print mysql error s stre shutilrmtreehsave path remove temp data directory sessionremove torrenth remove torrnt handle from session handlesremoveh remove handle from list else ifhstatusactive time 600 check if handle is more than 10 minutes old ie 600 seconds printremove torrent shutilrmtreehsave path remove temp data directory sessionremove torrenth remove torrnt handle from session handlesremoveh remove handle from list sleep1 printsleep1 printsleep10 sleep10 current page current page 1 save session state filewrite opensession save filename wb filewritewriteltbencodesessionsave state filewriteclose printsleep60 sleep60 save session state filewrite opensession save filename wb filewritewriteltbencodesessionsave state filewriteclosei tried kept above script running overnight and found only around 1200 torrents meta data is found in the overnight sessionso i am looking for improve the performance of the script i have even tried decoding the save state file and noticed there are 700 dht nodes i am connected to so its not like dht is not runningwhat i am planning to do is keep the handles active in session indefinitely while meta data is not fetched and not going to remove the handles after 10 minutes if no meta data is fetched in 10 minutes like i am currently doing iti have few questions regarding the libtorrent python bindingshow many handles can i keep running is there any limit for running handles will running 10k or 100k handles slow down my system or eat up resources if yes then which resources i mean ram network i am behind firewall can be a blocked incoming port causing the slow speed of metadata fetching can dht server like routerbittorrentcom or any other ban my ip address for sending too many requests can other peers ban my ip address if they find out i am making too many requests only fot fetching meta data can i run multiple instances of this script or may be multithreading will it give better performance if using multiple instances of the same script each script will get unique nodeid depending on the ip and port i am using is this viable solution is there any better approach for achieving what i am trying,['python'] +991924,update database values with same php values using doctrine type i am using a doctrine2 type to encrypt database values the type converts the php value internally to and from a database value by encrypting and decrypting it this works perfectly due to the doctrine2 types the encryption is stored as a base64 encoded string every encrypted string is prefixed by a fixed defined prefix this means the database field contains both encrypted and decrypted values this is required by external requirements recognized by the prefixmy wish is the followingassume i have an entity i want to force the encryption or decryption of all properties of an entity using doctrine i do this by forcing the database value within the type to be stored in the encrypted or decrypted formhowever when i call the method entitymanagercomputechangesets the none of the properties of the entity is marked as changed of course the actual data the php values are not changed however the database values do are supposed to changehow to accomplish thissome code of the doctrine typephpuse doctrinedbaltypestypeclass encryptedtype extends type private static forcedecrypt false encryption stuff like encrypt and decrypt public function converttophpvaluevalue abstractplatform platform if value null return null return this decryptvalue false public function converttodatabasevaluevalue abstractplatform platform if value null return null if selfforcedecrypt return string value return this encryptstring value false i have removed all unneeded code,['php'] +991940,relying on order of initialisation according to the c 14 standard nonstatic member variables are initialised in the order they are declared in a class the cut down code below relies on this rule to control a thread functionclass foo foo keep goingtrue my threadfoogothis void go whilekeep going check a stdcondition variable and do some work bool keep going stdthread my threadnote that keep going is declared before the thread object and should be set to true by the time the thread enters the go function this is fine and seems to work okhowever this is multithreaded code and it pays to be paranoid so i have two questions1 is it safe to rely on the order of initialisation like this my real object does not make sense without the processing thread so i want to set it going in the constructor2 is it unsafe to give code to others when it relies on relatively obscure things like the order of initialisation,['c++'] +992002,xcode 7 cannot run a test on the device fatal error occurs i try to run a simple testeverything is fine in the simulator when i run on the device emerge following errorthe log is dyld could not load inserted library privatevarmobilecontainersdataapplication7ee297485e864e9bb8e5882753654f87tmpidebundleinjectionframeworkidebundleinjection because no suitable image found did find privatevarmobilecontainersdataapplication7ee297485e864e9bb8e5882753654f87tmpidebundleinjectionframeworkidebundleinjection code signature invalid for privatevarmobilecontainersdataapplication7ee297485e864e9bb8e5882753654f87tmpidebundleinjectionframeworkidebundleinjectioni tried to make clean build and remove derived data it did not help mei appreciate any tips or helps,['objective-c'] +992083,test if two numpy arrays are close to equal including shape i want to test if two numpy arrays are close to equal so i have been using the npallclose function the only problem is it returns true if given a twodimensional matrix and a threedimensional matrix of equal elementsimport numpy as npx nparray314159265 01 01 01y nparraymathpi 01 01 01z1 nparray314159265 01 01 01 314159265 01 01 01z2 nparraymathpi 01 01 01 mathpi 01 01 01 npallclosexy returns true as expectednpallclosexz1 also returns true even though matrices are different shapes unwantednow i know about nparray equal which compares elements and shape but it does not allow me to test if the elements are close only if they are equal for instancenparray equalxyreturns falseis there a function i can use that will return true for xy and z1z2 but false for xz1 in this case,['python'] +992635,java parallelstream with custom pool with caller work stealing normally when one uses java 8s parallelstream the result is execution via the default common forkjoin pool ie forkjoinpoolcommonpoolthat is clearly undesirable however if one has work that is far from cpu bound eg may be waiting on io much of the time in such cases one will want to use a separate pool sized according to other criteria eg how much of the time the tasks are likely to be actually using the cputhere is no obvious means of getting parallelstream to use a different pool but there is a way as detailed hereunfortunately that approach entails invoking the terminal operation on the parallel stream from a forkjoin pool thread the downside of this is that if the targetfork join pool is completely busy with existing work the whole execution will wait on it while doing absolutely nothing thus the pool can become a bottleneck worse than single threaded execution by contrast when one uses parallelstream in the normal fashion forkjoinpoolcommonexternalhelpcomplete or forkjoinpoolcommontryexternalunpush are used to let the calling thread from outside the pool help in the processingdoes anyone know of a way to both get parallelstream to use a nondefault forkjoin pool and have a calling thread from outside the forkjoin pool help in the processing of this work but not the rest of the forkjoin pools work,['java'] +992643,why we use memory managers i have seen that lot of code bases specially server codes have basic sometimes advanced memory managers is the real purpose of memory manager is to reduce number of malloc calls or mainly for the purpose of memory analysis corruption check or may be other application centric purposes is the argument of saving malloc calls reasonable enough as malloc in itself is a memory manager the only performance gain i can reason is when we know that system always ask for same size memory or the reason for having memory manager is that free does not return memory to os but saves in the list so over the lifetime of the process the heap usage of the process may increase if we keep on doing mallocfree because of fragmentation,"['c++', 'c']" +992699,es6 classes and this with event handlers playing around with some es6 and ran into an issue i am not sure how to solve consider the followingclass foo constructor windowaddeventlistenerscroll thiswatch watch consolelogthis inside of watch this is the window object as expected but how do i refer to foo currently i get around this with bind thiswatchbindthis but i would love to know if there is a more proper es6 way to get this going,['javascript'] +992777,using a variable with the same name in different spaces this code compiles but i have a run time error in visual studioruntime check failure 3 the variable x is being used without being initializedint x 15int main int x x return 0i do not understand that behavior in the error box when i click continue the program resumes and x has a corrupted content like 8556328 instead of 15why does this code work without a problem and the int array is well declaredconst int x 5int main int xx 1234 return 0,"['c++', 'c']" +992843,build gradle system app as part of aosp build i have a custom rom based on aosp and i am working on a system app that is packaged during the rom build just like any other system appis it possible to switch this app to a gradle style app and build that specific app with gradle during the aosp build ie start the gradle build from a makefile,['android'] +992949,how to get entire linked group details using sql in have table called mygroup in database i thisplay this table data in tree format in gui as belowvishal groupvishal group1 vishal group11 vishal group1vishal group2 vishal group21 vishal group211vishal group3 vishal group4 vishal group41actually the requirement is i need to visit the lowest root for every group if that respective group is not used in other specific tables then i would delete that record from respective tablei need to get all the details only for the main group called vishal group please refer to both snaps one contains entire table data and the other snap snap which has tree format detailsshows expected data ie i need to get only those records as a result of a sql execution i tried with self join generally we do for mgr and employee column relationship but no success to get the records which falls under vishal group which is the base of all recordsi have added a table ddl and insert sql for reference as below and also attached a snap of how data looks in the tablecreate table mygroup pk group guid default newid not null description varchar255 linked to group guid primary key pk groupcommitinsert into mygroup pk group description linked to group values 1 my items nullinsert into mygroup pk group description linked to group values cd1e33d11649b983be067687e4d6 vishal group 1insert into mygroup pk group description linked to group values 4b42e7a5b14c451bacf583dd8a983a58 vishal group1 cd1e33d11649b983be067687e4d6insert into mygroup pk group description linked to group values a87e921d0468497d92c519ab63751ee8 vishal group11 4b42e7a5b14c451bacf583dd8a983a58insert into mygroup pk group description linked to group values 0fdc729a8fcc4d238619436a459835dd vishal group1 a87e921d0468497d92c519ab63751ee8insert into mygroup pk group description linked to group values 2e15a2a97e40422ea5d6c3f6c63f8591 vishal group2 cd1e33d11649b983be067687e4d6insert into mygroup pk group description linked to group values 5eac9866f4064bbdb7b35ceec3877c9b vishal group21 2e15a2a97e40422ea5d6c3f6c63f8591insert into mygroup pk group description linked to group values a326e6e3030e493baa0edc5d90db080f vishal group211 5eac9866f4064bbdb7b35ceec3877c9binsert into mygroup pk group description linked to group values 3cf1fe37eec04e79a3c5db78f6a9bc05 vishal group3 cd1e33d11649b983be067687e4d6insert into mygroup pk group description linked to group values 1ec302c80ab34f67b47acc43401df4ed vishal group4 cd1e33d11649b983be067687e4d6insert into mygroup pk group description linked to group values 2eb8176404fa4dda9aaba607bdc2756d vishal group41 1ec302c80ab34f67b47acc43401df4edinsert into mygroup pk group description linked to group values 7d93908113f0404c9f2f52c628fdcc sample boms 1insert into mygroup pk group description linked to group values c77d2255ac47461dbee57f3154c23af1 test1 1insert into mygroup pk group description linked to group values d054539aba4e3f97461522ff8a1e89 test2 1insert into mygroup pk group description linked to group values 71b4751c70964fb98d716bb19a3d9ed9 trailer assy 1insert into mygroup pk group description linked to group values f702babb73b04a49b4421c7c8a126335 wip 1insert into mygroup pk group description linked to group values fc74d59a94e34209bcea1b7606ea62f1 m 1insert into mygroup pk group description linked to group values 6e4354f9b29847379c1851b4acac0734 test1 1insert into mygroup pk group description linked to group values 42a48ee0d4ee4828bc11d7f0d1fe5bec test1 1insert into mygroup pk group description linked to group values 28afe8e112214f94bae337ea6b360494 test 2 1commitany idea how to get records which falls under vishal group,['sql'] +992965,why do i get php fatal error when i want to install an extension php composerphar require kartikvyii2password deverror msgcall to undefined method fxpcomposerassetpluginpackageversionversionparserparselinks in homejohncomposervendorfxpcomposerassetpluginrepositoryvcspackagefilterphp on line 272when i wanna add an extension in my project i got this error help me to solve it,['php'] +992977,angularjs file upload in put method not working i have a simple todos application in which i am trying to upload a photo along with a single todo now i have created this factory function that takes care of the creation of the todo todosfactoryinserttodo functiontodo return httppostbaseurl todo headers contenttype undefined transformrequest functiondata headersgetter var formdata new formdata angularforeachdata function value key formdataappendkey value return formdata and the factory update method looks like this todosfactoryupdatetodo functionid todo return httpputbaseurl id todo headers contenttype undefined transformrequest functiondata headersgetter var formdata new formdata angularforeachdata function value key formdataappendkey value return formdata the inserttodo is working as expected but the updatetodo is not posting data to the server i am using laravel for the api and the update api endpoint has this codeddinputall inputfilecover photothis shows that noting was posted in the request and if i change the put to post in the updatetodo factory method it starts working am i missing some extra headers or something updateif i remove both the transformrequest and headers form the updatetodo method the text data is successfully received on the server but the the file doesnat and if i just remove the headers nothing gets postedupdatei am using the php server that comes with laravel using this commandphp artisan serveupdatethanks to ricardos answer i was able to get the submitted data using this coderouterputtodosid functionid stream file get contentsphpinput echo stream diei am getting the stream in this format3643739756006088191021064137contentthisposition formdata nameid53643739756006088191021064137contentthisposition formdata namenameimage todo3643739756006088191021064137contentthisposition formdata namecomplete03643739756006088191021064137contentthisposition formdata namecreated at20151002 0628103643739756006088191021064137contentthisposition formdata nameupdated at20151002 0628103643739756006088191021064137contentthisposition formdata namecover photo filenamedragonfallsvenezuela5jpgcontenttype imagejpegi12i12i12i12i12jfifi12i12hi12hi12i12i12i12i12i12exifi12i12mmi12i12i12i12i12i12ii12i12i12i12i12i12i12i12i12i12i12i12i12i12i12i12i12i12zi12i12i12i12i12i12i12unicodei12i12ci12ri12ei12ai12ti12oi12ri12i12 i12gi12di12i12ji12pi12ei12gi12 i12vi121i12i120i12 i12i12ui12si12ii12ni12gi12 i12ii12ji12gi12 i12ji12pi12ei12gi12 i12vi126i122i12i12i12 i12qi12ui12ai12li12ii12ti12yi12 i12i12 i129i120i12now i need to parse this raw format i have found two php methods that other people have suggested and but both of them are not working properly and do not give an array like get or post,['javascript'] +993014,d3js json data array is binding the same array element to everything i am loading a geojson data file that contains an array of objects each object containing the vector information for a different countrys outline the same array element is being bound to every dom element i have come across this scope issue before in javascript but every change i made caused nothing to loadi attached a jsfiddle i use an example data file which seems to take a couple seconds to loadmy code from the jsfiddle looks likedocumentreadyfunction d3json functionerror data var mygeojson datafeatures for i 0 i mygeojsonlength i var path d3geopath var width 960 var height 600 var svg d3selectbodyappendsvg attrwidth width attrheight height svgselectallpath datadatafeatures enterappendpath attrdpath attrfill3e429a,['javascript'] +993084,intellij idea and gradle cannot be applied to groovylangclosure i have a gradle file which whenever i load open it in intellij idea 1415 shows ide errors for the entire file namely all the errors seem to be eitherjavalangstring errorsorgroovylangclosure errorsi have tried clearing the files contents and only writing the top linegroup commeblahbut even that results in an errorfor contexts sake this is an individual module in a larger springboot project this module is a set of simple static files with gradle for css compilation static analysis etc while the rest are java modules and are not having gradle issuescan anyone think why intellij would be struggling to understand this gradle file,['java'] +993117,unexpected behavior of substring in c the definition of substring method in net systemstring class is like thispublic string substringint startindexwhere startindex is the zerobased starting character position of a substring in this instance as per the method definition if i understand it correctly it means it will give me a part of the string starting at the given zerobased indexnow if i have a string abc and take substring with different indexes i get following resultsvar str abcvar chars strtoarray returns 3 char a b c as expectedvar sub2 strsubstring2 1 returns c as expectedvar sub3 strsubstring3 2 returns why no exceptionvar sub4 strsubstring4 3 throws argumentoutofrangeexception as expectedwhy it does not throw exception for case 2 the string has 3 characters so indexes are 0 1 2 and even toarray tochararray method returns 3 characters as expected should not it throw exception if i try to substring with starting index 3,"['c#', '.net']" +993129,variadic aggregates as core language feature stdtuple is highly templateloaded beast to access to nth member compiler must perform a plenty of template instantiations although its simple nature access to nth data member of corresponding imaginary struct it seems that stdtuple should be a core language feature something like this pseudocodetemplate typename types struct or class or even union v types v defines implicitly operator constant expression to access by index if more than one variadic parameter pack provided during expanding of parameter pack of template parameters in specializations then instead of v there can be specific datamember name say x but still with xoperator implicitly defined member functions and data members allowedtemplate typename types v stddecay t types make tupletypes args return stdforward types args template typename types v types forward as tupletypes args return stdforward types args template typename types v types tietypes args return args is there any proposal of something like language supported variadic datamembers definition syntax for classes,['c++'] +993151,how to mimic a use crc flag on hacked 1998 uncompress in 2013 zlib api interface i was updating a projects code from a 1998 version of zlib to a 2013 version of zlib one thing that seemed to change is that there used to be a use crc flag on the uncompress function which appeared to have gone missingint zexport uncompress dest destlen source sourcelen use crc bytef dest ulongf destlen const bytef source ulong sourcelen int use crc vanished update as pointed out by joe this is likely a thirdparty modification title updated accordingly the rest of the question is still applicable as in how should i best do this with todays stock zlibin the code i am studying uncompress is being called by something that deconstructs the binary format of a zip and passes in a payload of data the code had been passing the crc flag in as 1 if the flag was not used it would get a z data error 3 a zlib with no use crc flag gets z data error just as if the flag had been falsein experiments i found that very small files worked without use crc then that the small counting files crossed over to notworking between 12345678901234 and 123456789012345 reason was that is the first file which was deflated instead of stored uncompressed at what zip called a savings of 6 in floundering with options to get zlib to accept it i tried many things that included trying the 16 max wbits nothing seemed to process the payload out of zip testzip testtxt the way the old code hadif i was willing to subtract one out of my destination size i seemed to be able to suppress the erring checkat the loss of one byte heres the simple test program with the minimal zip payload hardcodedinclude stdiohinclude zlibhint mainint argc char argv char compressed 0x78 0x9c 0x33 0x34 0x32 0x36 0x31 0x35 0x33 0xb7 0xb0 0x34 0x30 0x04 0xb1 0xb8 0x00 0x31 0x30 0xb1 0x30 0x10 0x00 0x00 0x00 last 4 bytes are size 16 char uncompressed16 1 account for null terminator int ret z stream strm memsetuncompressed x 16 uncompressed16 0 strmzalloc strmzfree strmopaque z null strmtotal out 0 strmavail in 25 strmnext in compressed ret inflateinit2strm max wbits 16 it is z ok strmavail out 15 16 gives error 3 incorrect header check strmnext out uncompressed ret inflatestrm z no flush if ret z stream end z ok does not finish printfinflate error d sn ret strmmsg return 2 inflateendstrm printfsuccessful inflation sn uncompressed return 0the output issuccessful inflation 123456789012345xshowing the data is getting uncompressed but we need all 16 bytes there is a newline in there from the file that should be received 16 max wbits cannot even get thatany ideas whats going wrong no permutation of settings seems to get there without errors,['c'] +993208,fixed position inside scrolling div i have a div with let us say a height on 400px the content is much longer so the div can scroll yaxis in the right side of the div i need some buttons to have a fixed position inside that divhow would i do that jquery css whatever i do not mindi tried fixto but does not seem to work for this and a css solution that says use positionfixed but no leftright just margin it works ok but if the page itself scrolles the buttons scrolls too which they should not they should stay fixed inside the div at all timeexample codediv classcontainer stylewidth 960px height 400px position relative div classbuttons needtobefixeddiv div classalotofcontent stylewidth 20pxdivdiv,"['jquery', 'css']" +993336,cloudkit free public storage and data transfer i would like to understand the cloudkit free usage calculation but i cannot could anyone describe what 40 requests per seconds 10 per 10 users are i could not find any definition what a request is if i had 2 apps and every app would ping my cloudkit server at the same time would it result in two requests per second for the described moment how do i know how to limit the request in my apps and how to queue the requests so they can be done later when the time comes where the limit is not reached at the cloudkit serverwhat about the 2gb data transfer 50 mb per user how should i understand these 50 mb per second per day for the eternity what will happen if one user for one of my apps used 50 mb traffichow do i limit my app and still have a good clint server communication will i get an error when the limit is reached and would not automatically charged by applei do really like the programming ease of cloudkit but i am kinda scared that it could go all way wrong and i will get charged for misunderstandingit is really hard for me to imagine how it is calculated,['ios'] +993479,why does this program not receive the expected udp packets i am trying to receive a udp packet using boost asio my code is based off of this blocking udp client example from the asio documentationi am trying to receive a bootplike udp packet from a c6655 ti dsp which are being transmitted in 3 second intervals i have wireshark watching the same interface my program is listening on and it can see the packets arriving see below for the exact packet data exported from wireshark the packets are not really coming from the dsp i captured one with tcpdump and i am simulating it from a raspberry pi with packethhowever my program does not receive the packets it has a 4 second timeout since the dsp broadcasts every 3 seconds if it hits the timeout it prints a message to that effect otherwise it is supposed to print the number of bytes received the full compilable source code of the program follows about 100 linesthe command is being invoked with the parameters 1921685122 67 40 which means listen on 192168512267 with a 40 millisecond timeoutedit in addition to the code below i also tried this as my endpoint udpendpoint listen endpointboostasioipaddress v4any atoiargv2 as well as the ip address 0 as suggested by a search result somewherei also added the following to no availboostasiosocket basebroadcast optiontruesocket set optionoptioni do have a program that is able to properly receive this packet written using berkeley sockets it is not doing anything special that i can see beyond binding to inaddr anyhere is the complete program blocking udp clientcpp include boostasiodeadline timerhppinclude boostasioio servicehppinclude boostasioipudphppinclude boostbindhppinclude boostdate timeposix timeposix time typeshppinclude iostreamusing boostasiodeadline timerusing boostasioipudpclass listenerpublic listenerconst udpendpoint listen endpoint socket io service listen endpoint deadline io service deadline expires atboostposix timepos infin check deadline stdsize t receiveconst boostasiomutable buffer buffer boostposix timetime duration timeout boostsystemerror code ec deadline expires from nowtimeout ec boostasioerrorwould block stdsize t length 0 socket async receiveboostasiobufferbuffer boostbindlistenerhandle receive 1 2 ec length todo the following dowhile is hinky does run one need to happen before the comparison do io service run one while ec boostasioerrorwould block return length private void check deadline if deadline expires at deadline timertraits typenow cancel would not work on xp something about using close instead look it up i am doing this on win10 socket cancel deadline expires atboostposix timepos infin deadline async waitboostbindlistenercheck deadline this static void handle receiveconst boostsystemerror code ec stdsize t length boostsystemerror code out ec stdsize t out length out ec ec out length length private boostasioio service io service udpsocket socket deadline timer deadline int mainint argc char argv try if argc 4 stdcerr usage blocking udp timeout listen addr listen port timeout msn return 1 udpendpoint listen endpointboostasioipaddressfrom string0 atoiargv2 stdcout endpoint listen endpoint stdendl auto timeout atoiargv3 stdcout timeout timeout stdendl listener clisten endpoint for char data1024 boostsystemerror code ec auto and creceiveboostasiobufferdata boostposix timemillisecondstimeout ec if ec stdcout receive error ecmessage n else stdcout received and bytes stdendl catch stdexception e stdcerr exception ewhat n return 0here is the packet that i am trying to receive this includes the ethernet frame0 ff ff ff ff ff ff c4 ed ba aa 28 35 08 00 45 00 5e0010 01 48 00 01 00 00 10 11 a9 a5 00 00 00 00 00 00 h0020 00 00 00 44 00 43 01 34 00 00 01 01 06 00 12 34 dc440030 56 78 00 01 00 00 00 00 00 00 00 00 00 00 00 00 vx0040 00 00 00 00 00 00 c4 ed ba aa 28 35 00 00 00 00 50050 00 00 00 00 00 00 74 69 2d 62 6f 6f 74 2d 74 61 tibootta0060 62 6c 65 2d 73 76 72 00 00 00 00 00 00 00 00 00 blesvr0070 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0080 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0090 00 00 00 00 00 00 74 69 2d 62 6f 6f 74 2d 74 61 tibootta00a0 62 6c 65 2d 30 30 30 37 00 00 00 00 00 00 00 00 ble0700b0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00c0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00d0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00e0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0100 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0110 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0120 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0130 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0140 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0150 00 00 00 00 00 00 i do have a berkeley socket implementation that can receive this packet i have removed error handling and other misc code struct sockaddr in servaddr socklen t len char mesgrecv buffer length sockfd socketaf inet sock dgram 0 bzeroservaddr sizeofservaddr servaddrsin family af inet servaddrsin addrs addr htonlinaddr any servaddrsin port htons67 bindsockfd struct sockaddr servaddr sizeofservaddr and recvfromsockfd mesg recv buffer length 0 null len,['c++'] +993659,why does not this ruby program return off heap memory to the operating system i am trying to understand when memory allocated off the ruby heap gets returned to the operating system i understand that ruby never returns memory allocated to it is heap but i am still not sure about the behaviour of off heap memory ie those objects that do not fit into a 40 byte rvalueconsider the following program that allocates some large strings and then forces a major gcrequire objspacestring size 250def print statsmsg puts puts msg puts puts rss ps eo rsspid grep processpid grep v grep awk print 1kb puts heap size gcstatheap sorted length 408 401024 kb puts size of all objects objectspacememsize of all1024 kbenddef run print statsstart work data 600 0times do data string size end print statsend work datanilendrungcstartprint statsafter forced major gcrunning this program with ruby 223 on mri it produces the following output after a forced major gc the heap size is as expected but rss has not decreased significantlystart workrss 7036 kbheap size 1195 kbsize of all objects 3172 kbend workrss 205660 kbheap size 35046 kbsize of all objects 178423 kbafter forced major gcrss 164492 kbheap size 35046 kbsize of all objects 2484 kbcompare these results to the following results when we allocate one large object instead of many smaller objectsdef run print statsstart work data string size 600 0 print statsend work datanilendstart workrss 7072 kbheap size 1195 kbsize of all objects 3170 kbend workrss 153584 kbheap size 1195 kbsize of all objects 149064 kbafter forced major gcrss 7096 kbheap size 1195 kbsize of all objects 2483 kbnote the final rss value we seem to have freed all the memory we allocated for the big stringi am not sure why the second example releases the memory but the first example does not as they are both allocating memory off the ruby heap this is one reference that could provide an explanation but i would be interested in explanations from othersreleasing memory back to the kernel also has a cost user space memory allocators may hold onto that memory privately in the hope it can be reused within the same process and not give it back to the kernel for use in other processes,['ruby'] +993722,spread operator vs objectassign let us say i have an options variable and i want to set some default valuewhats is the benefit drawback of these two alternativesuse the spread operatoroptions optionsdefault optionsor use objectassignoptions objectassign optionsdefault optionsthis is the commit that made me wonder,['javascript'] +993727,matching algorithm i have a list of pencils and a list of erasers the goal it to check whether or not all the erasers can be put on pencils an eraser may fit on multiple different pencils pencils can have at most 1 eraser if i just loop through all the erasers and put them on pencils i end up with erasers that fit no unoccupied pencils even though there is a solution that has all the erasers on pencilswhat algorithm could i use to figure out a combination that fits all the erasers on pencilspublic class eraser public boolean matchespencil p unimportant public class pencilmy attemptpublic boolean domatchlisteraser erasers listpencil pencilsfor eraser e erasers boolean found false iterator it pencilsiterator while ithasnext pencil p pencil itnext if ematchesp found true itremove break if found return false return true,['java'] +993761,combine multiple simple jquery functions i have a form with several dropdown boxes if user choose other from the dropdown menu another div with an input field will slide down the problem is that i have 20 dropdown boxes like that can i create only 1 function to trigger the related onehere is my html div classcontainer div select idoption1 namecity option valueplease chooseoption option valueotherotheroption option valuelondonlondonoption select div div idbox1 input typetext namecityother divdivdiv classcontainer div select idoption2 namecolor option valueplease chooseoption option valueotherotheroption option valueredredoption select div div idbox2 input typetext namecolorother divdivand my jquery code box1hideoption1onchange function if thisvalue other box1slidedownslow else box1slideupslow box2hideoption2onchange function if thisvalue other box2slidedownslow else box2slideupslow,['jquery'] +993837,functionprototype is a function i am digging into the javascript prototype chainin order to document my findings i have drawn the following scheme although most of the concepts are clear i am left with just two related questions rather than splitting them up i guessed that centralising them in this question might be better is there a reason for functionprototype to be of type function instead of objecttypeof functionprototype functionis functionprototype a unique function in js since it does not have a prototype property of its own like other functions do is there a generally accepted name to refer to it,['javascript'] +993919,how to obey contract of equals when deriving from abstract class in his book effective java joshua bloch writes about the pitfalls that occur with the contract of equals when derived classes add additional fields to the check normally this would break the symmetry but bloch states that you can add a value component to a subclass of an abstract class without violating the equals contractobviously this is true because there can be no instances of the abstract class so there is no symmetry to violate but what about other subclasses i wrote this example intentionally omitting hashcode implementations and nullchecks to keep the code shortpublic abstract class vehicle private final string color public vehiclestring color thiscolor color public string getcolor return color override public boolean equalsobject o if this o return true if o instanceof vehicle return false vehicle that vehicle o return colorequalsthatcolor public class bicycle extends vehicle public bicyclestring color supercolor public class car extends vehicle private final string model public carstring color string model supercolor thismodel model override public boolean equalsobject o if this o return true if o instanceof car return false car that car o return getcolorequalsthatgetcolor modelequalsthatmodel when i create one instance of each class with the same color string the symmetry of equals is brokenbicycle bicycle new bicyclebluecar car new carblue mercedesbicycleequalscar truecarequalsbicycle falsei am unsure on how to handle this the best way declare equals as abstract in the abstract class to enforce an implementation in the subclasses but the same effect could be achieved by not declaring equals at all in the abstract class,['java'] +993961,typescript react and gulp defining react what i am trying to accomplish is a workflow where i can write react modules using typescript and automatic compiling to js via gulp i am using typescript 162 gulpreact and gulptypescriptmy tsx file looks like this now reference pathtypingsreactreactdts import react reactinterface helloworldprops name stringvar hellomessage reactcreateclasshelloworldprops any render function return divhello thispropsnamediv reactrenderhellomessage namehello documentgetelementbyidtestmy problem is this line import react reactwhen i leave it out i get the error error ts2304 cannot find name react when compiling tsx to js but it still compiles to jsx and i can use the output when i put it in i can compile without errors but when i try to use the file inside the browser i get an uncaught referenceerror react is not defined of coursethis is how my gulptask looks likegulptaskguitsx function var tsresult gulpsrcconfigguisrcpath tsxapptsx pipets jsx react return tsresultjspipegulpdestconfigguisrcpath jsxis there any workaround for this or am i missing something here,['javascript'] +994067,angular resource recursive query from the api i am working on i need to take 2 different lists and i need to take in chunks of 20 items to avoid server timeoutswhat i built actually is thisitems1querypromisethenfunction data scopeitems1 datalist return items2querypromisethenfunction data scopeitems2 datalistwith this code i am downloading the entire list of objectsboth the query return list next true limit 20 last 20basically it is a pagination systemboth services are like thisappfactoryitems1 resource functionresource return resourceitems1item1id storeid id query method get isarray false update method put i do not really know how to make recursive function with resource in order to push those items in chunks of 20,['javascript'] +994083,ienumerable repeats function i have faced a strange problem here i reproduced the problemrandom r new randomlistint x new listint 1 2 3 4 5 6var e xorderbyi rnextvar list1 etolistvar list2 etolistbool b list1sequenceequallist2consolewritelineb prints falseuntil now i thought that linq functions get executed when they are called but in this method it seems after i call tolist the linq function orderby executes again why is that so,['c#'] +994203,are scalar and strict types in php7 a performance enhancing feature since php7 we can now use scalar typehint and ask for strict types on a perfile basis are there any performance benefits from using these features if yes howaround the interwebs i have only found conceptual benefits such asmore precise errorsavoiding issues with unwanted type coercionmore semantic code avoiding misunderstandings when using others codebetter ide evaluation of code,['php'] +994322,laravel hasmanythrough but must return only one array i have these tablesentries table id blog id title 1 1 1st entry blogs table id name 1 1stblog field groups table id blog id name 1 1 group1 fields table id field group id name 1 1 field 1 values table id field id entry id value 1 1 1 hello world now on my models i have set up these relationshipsclass entry extends model public function blog return thisbelongstoblogclass class blog extends model public function entries return thishasmanyentryclass public field group return thishasonefieldgroupclass class fieldgroup extends model public function fields return thishasmanyentryclass public function blog return thisbelongstoblogclass class field extends model public function group return thisbelongstofieldgroupclass field group id public function values this method should get the values from the values table per entry id return thishasmanythroughvalueclass entryclass id entry id class value extends model public function field return thisbelongstofieldclass field id using this query i canentry entrywithblogfield groupfieldsfind1i can get the entry along with its blog field groups and fields i want to get the values associated with the entry tooentry entrywithblogfield groupfieldsvaluesfind1i am having trouble on which relationship to use any help is much appreciated i just started using laravel,"['php', 'mysql']" +994328,android floating action button options menu there are lots of custom libraries for achieving the fab menu thing but i want it to be done without using any custom libraries i want to achieve this fab menu nativelyplease do not suggest me any custom library,['android'] +994348,what is the rationale for not including strdup in the c standard most c programmers are familiar with the strdup function many of them will take it for granted yet it is not part of the c standard neither c89 c99 nor c11 it is part of posix and may not be available on all environments indeed microsoft insisted on renaming it strdup adding to confusionit is rather easy to define it this way in cinclude stringhchar strdupconst char s size t size strlens 1 char p mallocsize if p memcpyp s size return pbut even savvy programmers can easily get it wrongfurthermore redefining the function only on systems that do not have it proves a bit complicated as explained here strdup functionwhy not include such useful widely supported functions in revised editions of the c standard a lot of new functions have been included the c standard library in c99 what is the rationale for not including strdup,['c'] +994448,android data binding using include tag mainxmllayout xmlnsandr data data include layoutlayoutbuttonsincludebuttonsxmllayout xmlnsandr data data button androidididbutton myactivityjava binding databindingutilinflatebindingbutton cannot resolve symbol buttonhow to get buttonupdatethe above example is working properly because 10rc4 fixed the problem of needing the unnecessary variable,"['java', 'android']" +994477,catch too long form submission i am developing an html page which has simple html form nothing special being submitted by button there is a couple of situations when form submitted and response comes too long if whenever really comes back how can i organize the form the way it fires some callback when waiting a response is too long we could show up some notice for user indicating our server is overloaded in that situation here is request that being sent by formpost http11host examplecomproxyconnection keepalivecontentlength 83cachecontrol maxage0accept texthtmlapplicationxhtmlxmlapplicationxmlq09imagewebpq08origin upgradeinsecurerequests 1useragent mozilla50 windows nt 61 win64 x64 applewebkit53736 khtml like gecko chrome4502454101 safari53736contenttype applicationxwformurlencodedreferer acceptencoding gzip deflateacceptlanguage rururuq08enusq06enq04cookie cookie definition omittedform data omittedis proxyconnection keepalive influence the process somehow googling led me to plugin but it is for a little bit different purpose,"['javascript', 'html', 'asp.net']" +994486,ios 9 black keyboard broken layout in ios 9 if i show the camera with a keyboard showing when i thismiss the camera controller and the keyboard comes back the layout is broken like in the screenshot belowstep to reproducetap on a text field so the keyboard will showopen a controller that uses the camerathismiss camera controllerwhen the keyboard comes back it is broken,['ios'] +994563,is it always safe to unsubscribe from an event inside the handler lets say that i have this incomplete class in which i raise an event without first assigning it to a variable to make it threadsafepublic class test public event eventhandler someevent void onsomeeventeventargs e if someevent null someeventthis e would it be safe to unsubscribe an event handler from itself or could there be any problem similar to what would happen when removing items from a collection while enumerating itvoid someeventhandlerobject sender eventargs e testinstancesomeevent someeventhandler,['c#'] +994584,xcode 7 magical record unit tests fail after upgrading from xcode 64 to xcode 7 and now 701 my project crashes when starting unit tests my ios project is using magical record and the app crashes at this assertion nsmanagedobjectcontext mr defaultcontext synchronizedself nsassertmagicalrecorddefaultcontext nil default context is nil did you forget to initialize the core data stack return magicalrecorddefaultcontext i have commented out all of my previous tests and both of these tests show the same behaviorimport xctestxctesthinterface badtests xctestcaseendimplementation badtests voidsetup super setup voidteardown super teardown voidtestsanity xctassert1 1endandimport xctestxctesthimport magicalrecordmagicalrecordhinterface badtests xctestcaseendimplementation badtests voidsetup super setup nslog using in memory store magicalrecord setlogginglevelmagicalrecordloggingleveldebug magicalrecord setupcoredatastackwithinmemorystore voidteardown magicalrecord cleanup super teardown voidtestsanity xctassert1 1endreverting back to xcode 6 with the same tests resolves the issue,"['ios', 'objective-c']" +994671,deleting copy constructor breaks inherited constructors i am trying to use the constructor inheritance feature of c11 the following snippet copied from somewhere i do not remember whence works completely fineinclude iostreamstruct base base base0 baseint a basea 0 baseint a double b stdcout base a b stdendl struct derived base using basebase derivedconst derived that delete this line is the culpritint mainint argc char argv derived d1 derived d242 derived d342 314that is until the line marked by the comment is added because then all hell breaks loose g stdc11 o test testcpptestcpp in function aint mainint charatestcpp1811 error no matching function for call to aderivedderiveda derived d1 testcpp1811 note candidates aretestcpp1316 note derivedderivedint using basebase testcpp1316 note candidate expects 1 argument 0 providedtestcpp1316 note derivedderivedint doubletestcpp1316 note candidate expects 2 arguments 0 providedit seems as if deleting the copy constructor also somehow made the default constructor from base inaccessible googling the problem did not bring up anything useful so suggested this issue but as far as i understand i do not use copy initialization in this snippet could someone shed some light on what has happened herethe compiler that generated the message above is gcc 482 however clang returns a similar error message,['c++'] +994679,make images private in wordpress i am making a site that i would like to make private the most important part is that the images on the domain cannot be seen without the user logging in first so i would like all traffic to be redirected to wdomainnamecomwpadmin also for images if the user is not logged inheres what i have tried1 plugins i have tried both wordpress force login the plugin wprequirelogin and a coming soon page and maintenance mode2 adding a function from this answer which is this function is login page return in array globalspagenow array wploginphp wpregisterphp function wpse make blog private if is user logged in is admin is login page global wp query wp queryset 404 add action wp wpse make blog private non of these things redirects the traffic if i go to the direct url for the image such as can that be done edit 1 mevius pointed out that wordpress might not be loaded if you type in the direct url to an image so he suggests that it should be done on apachelevel end of edit 1,['php'] +994706,difference between 01 and 1 in a javascript date what is the difference between the dates 20151001 and 2015101 in javascriptnew date2015101this returns thu oct 01 2015 0 gmt0300new date20151001returns wed sep 30 2015 210 gmt0300,['javascript'] +994782,c variadic template constructor and common constructors code like c14struct s int a int b class c public cchar const size t 1 cs const 2 cs const 3 templatetypename t ct 4 cs 5 cs 6s s 1 2 c c1 s calls 4 and not 2c c2 abc 3 calls 4 and not 1c c3 char constabc size t3 calls 1 okc c4 s calls 5 if uncommentedc c5 s calls 6 if uncommenteds const s2 c c6 s2 calls 3simple constructor is called if it has exact the same signature as the passed parameteris there some trick to use common constructors as usual with a variadic template constructor without copying classes passed as parameters and overloading constructors likecs const cs and without additional tags in constructors,['c++'] +994858,invoking a method of an anonymous class i learned the other day that you can do thisnew object void hello systemoutprintlnhello world hellothis seems really weird to me surely the static type of the object created is object so there is not a method hello is not it almost completely pointless it is not possible to invoke hello twice for examplei have 2 questions about this can somebody point me to the part of the specification that addresses thisam i right in thinking that the only way you can invoke hello is immediately like this what about reflectionthanks,['java'] +994888,list index out of range whenever i change the list size im trying to rotate a list of list 90 degrees for example change this123 456 789 to741 852963 visually123 741 456 852 789 963whenever i change the list size to be more elements or less it always says the index is out of range what is going on def rotatelist1 biglist create a list that we will append on to for i in rangelenlist11 loop through the list looking at the indexes newlist for j in reversedrangelenlist1 reverse that list newlistappendlist1ji biglistappendnewlist append the elements to the biglist reversed return biglist,['python'] +995008,overload function for both arraysofconst and pointerstoconst i can capture an array along with its compiletime size using a template function like sotemplateint nvoid fooconst int n stdcout fooconst int nnhowever i would like to overload foo to also allow pointerstoconst so that the first overload is used when the function is called on an array type and the second one when it is called on a pointer directlyvoid fooconst int stdcout fooconst int nint main int a1 0 fooa const int b1 0 foobtry it on ideonehere the first overload is called for a the second one for bmy guess is that for a the compiler must perform a conversiontoconst which means that fooconst int is not a perfect match but i am lost to why this is not even an ambigous function callhow can i change the code so that the first overload is called in both cases,['c++'] +995036,how do you run a js file using npm scripts i cannot get npm to work my packagejson file hasscripts build buildjs and i have a buildjs file in the same folder that just consolelogswhen i run npm run buildi get the error the system cannot execute the specified programnpm err windows nt 617601npm err argv cprogram filesnodejsnodeexe cprogram filesnodejsnode modulesnpmbinnpmclijs run buildnpm err node v411npm err npm v335npm err code elifecycleand if i move the buildjs file and change my packagejson file to have a subfolderscripts build buildbuildjs then i get the errorbuild is not recognized as an internal or external command operable program or batch filewhats going wrong i am copying the example documentation,['javascript'] +995057,hide the status bar in ios 9 how do you hide the status bar in ios 9this is now deprecated uiapplication sharedapplication setstatusbarhiddenyes,"['ios', 'objective-c']" +995061,retrofit 20 how to print the full json response i am moving from volley to retrofit currently version 20how to print the the full json response code includescompile comsquareupretrofitconvertergson200beta2compile comsquareupretrofitretrofit200beta2restclientokhttpclient client new okhttpclient clientinterceptorsaddnew interceptor override public response interceptinterceptorchain chain throws ioexception response response chainproceedchainrequest return response gson gson new gsonbuilder setdateformatymmddthhmmsz create retrofit retrofit new retrofitbuilder baseurlroot addconverterfactorygsonconverterfactorycreategson clientclient build rest client retrofitcreateapiserviceclassapiservice getmyjson callmodel getfeedin activity calling apicallmodel call restclientgetgetfeedcallenqueuenew callbackmodel override public void onresponseresponsemodel response retrofit retrofit logw20 getfeed responseraw responserawtostringdont work logw20 getfeed retrofit retrofittostringdont work logw20 getfeed body responsebodytostring dont work logw20 getfeed getstatus responsebodygetstatus override public void onfailurethrowable t tprintstacktrace loge20 getfeed onfailure ttostring,"['java', 'android']" +995202,why setmap emplace hint does not return a boolean according to cppreference both stdset and stdmap emplace functions return a stdpairiteratorbool with a bool value to say if the insertion actually took placehowever emplace hint returns an iterator either to the inserted element or to the existing element in the set or map if the insertion did not happen there is no bool value here is there any reason for this difference in the interface of these similar functionsupdatefunction insert returns the bool value only when no hint is provided this is consistent with the behavior of emplace and emplace hint the question is then is there any reason to not return a bool when a hint is given i can only think that maybe there is some performance reason because the user usually provides a hint after a lower boundupper bound operation so it is sure the insertion will happen,['c++'] +995220,java read write construction can someone explain me why this construction wont work while fileinputstreamavailable0 fileoutputstreamwritefileinputstreamreadand this one works just finewhile fileinputstreamavailable0 int data fileinputstreamread fileoutputstreamwritedataas for me they are identical but 1st one wont write data correctly will write half of file lenght data,['java'] +995364,google analytics on android gives avg session duration 0 i am using google analytics on android and it gives me a lot of avg session duration 0please note that i am not using ga autoactivitytracking and i have more than one activityheres my codebuildgradle compile comgoogleandroidgmsplayservicesanalytics750application classtracker mtracker googleanalyticsgetinstancecontextnewtrackerrxmltrackertrackerxmlresources xmlnstools toolsignoretypographydashes replace placeholder ga tracking id with a real one string namega trackingidua1string bool namega reportuncaughtexceptionstruebool integer namega sessiontimeout300integer 1800 seconds is 30 minutes which is the default included explicitly for ease of tweaking integer namega thispatchinterval1800integer bool namega debugfalseboolresourcesi send screenviews on onstart function or onpageselected within a viewpagerpublic static void sendscreenviewstring screenname if cansend mtrackersetscreennamescreenname mtrackersendnew hitbuildersappviewbuilder setcustomdimensioncountry index getcountrycodebuild timberitag screen view recorded screenname else timberitag screen view not recorded analytics thisabled or not ready,['android'] +995508,is an iife required around class in ecmascript javascript 6 if i have class car do i need to wrap that with our function closure do vars get hoisted to window or just to the class what about when transpiled does traceurbabel turn it into a iife and let us into varsdo i need tofunction class car to be safe,['javascript'] +995655,running methods simultaneously i have a dog class with a method run which is supposed to move pictures across the screenpublic bool run point p pictureboxdoglocation whilepx 530 int movement randomizernext0 3 px movement pictureboxdoglocation p if location 4 incomplete section return true else return falsethis method is called from a button click event in which 4 dog objects are created and the each object calls the run methodprivate void button1 clickobject sender eventargs e dog dog1 new dogpicturedog1 dog dog2 new dogpicturedog2 dog dog3 new dogpicturedog3 dog dog4 new dogpicturedog4 dog1run dog2run dog3run dog4runthe problem is that each method executes one by one not simultaneously i want each method to run at the same time if i remove the while statement then all methods execute at the same time but with the while loop they execute one after another any suggestions on how to fix this problem are greatly appreciated run method without the while looppublic bool run dog1run point p pictureboxdoglocation int movement randomizernext0 30 location movement px movement pictureboxdoglocation p if location 4 incomplete code return true else return false,['c#'] +995732,using body parser to pass zip file i have node app which use express in the app i need to send via post message zip file eg from postman to the node server currently i use body parser like following but i wonder if this is okappusebodyparserurlencodedextended falseappusebodyparserjsonappusebodyparsertext type applicationtextenriched limit 10mbbtw this is working but i wonder if i use it right,['javascript'] +995779,how to queryrepresent 1tomany information in the list page how to queryrepresent 1tomany information in the list pagecreate users id name create user tags id user id tag nameuser has 1 to many user tagssample data i would like the table to be rendered as user1 tag1tag2user2 tag3user3 tag1user4user5 tag5tag6tag7in order to construct the above table i would have to do the following to construct each rowieselect from usersfor user user users select tag name from user tags where user id userid listtag tags fetchtagsuseris there a better way to fetch cache tags for an user so that it does not take a longer time to construct the above list of users,"['java', 'mysql']" +995879,how to create reuleaux triangle shape using css3 i need a help to make reuleaux triangle shape using css3 like below the image the shape has a white border around how is it possible,['css'] +996034,mongoid default scope overrides default value why mongoid 402i have test classclass test include mongoiddocument include mongoidtimestamps include mongoidparanoia field successful type boolean default false default scope wheresuccessful true endthen i dottestnew tsuccessful trueso here is the question what is the reason behind this behaviourps i have fixed it resetting successful with the help of after initialize method,"['ruby-on-rails', 'ruby']" +996297,replace activator for middleware in aspnet core i am trying to instruct my aspnet core mvc application to use a 3rd party di container rather than writing an adapter i am trying to just plug in the the library following the advice in this postthis works pretty well i can replace the built in icontrolleractivator with my own that uses the di container however i am running into a roadblock when trying to instantiate custom middleware that also relies on injected dependencies aspnet cannot resolve these dependencies because it is not using my 3rd party di container is there an equivalent of icontrolleractivator for middleware or am i stuck using the builtin di or writing an adapter edit heres some more of my code i am actually trying to use ninject using the pattern above internal sealed class ninjectcontrolleractivator icontrolleractivator private readonly ikernel kernel public ninjectcontrolleractivatorikernel kernel kernel kernel debuggerstepthrough public object createactioncontext context type controllertype return kernelgetcontrollertype i have thiscovered i have two problemsi cannot inject standard aspnet components into my controllers because ninject is not aware of themmy middleware that uses application services cannot be instantiated because aspnet is not aware of ninjectfor an example of the first problem heres a controller that fails to instantiate because i am using iurlhelper also note the ilogger which also fails to instantiatepublic class systemcontroller controller public systemcontrollerilogger logger iurlhelper urlhelper heres an example of the second problem with a custom middlewarepublic class custommiddleware private requestdelegate next this is an application specific service registered via my ninject kernel private ipersonservice personservice public custommiddlewarerequestdelegate next ipersonservice personservice next next personservice personservice public async task invokehttpcontext context i realize that in theory aspnet components should be in their own pipeline and my application components should be in another but in practice i often need to use components in a crosscutting way as in the examples above,['c#'] +996521,android studio proguard unable to compute hash of classesjar it has been long years if ever since i have asked a question at stackoverflow although i use it almost of daily basisanyway here it goesrecently i have switched to api 23 that forced me to use uselibrary orgapachehttplegacyas they have thrown out an easy access to the apache librarymy project compiles fine and runs fine across all testdevices in debug modetoday i need to bring my project to production and proguard shouts with unable to compute hash of buildintermediatesclassesproguardreleaseclassesjarthere are no other errors or warning there used to be but i got rid of them like getting rid of duplicate copies of apache librarieshere is my gradle filebuildscript repositories mavencentral jcenter dependencies classpath comandroidtoolsbuildgradle131 apply plugin comandroidapplicationrepositories maven url mavencentral jcenterdependencies compile comgithublzyzsdcircleprogress110aar compilecomfasterxmljacksondatatypejacksondatatypejoda204 exclude module jodatime compile netdanlewandroidjoda281 compile commonsiocommonsio compile comgoogleandroidgmsplayserviceslocation780 compile comgoogleandroidgmsplayservicesnearby780 compile comgoogleapisgoogleapiservicestranslatev2rev411200 exclude artifacts that the android sdkruntime provides exclude group xpp3 module shared exclude group orgapachehttpcomponents module httpclient exclude group junit module junit exclude group comgoogleandroid module android compile comgooglehttpclientgooglehttpclientandroid1180rc exclude artifacts that the android sdkruntime provides exclude group xpp3 module shared exclude group orgapachehttpcomponents module httpclient exclude group junit module junit exclude group comgoogleandroid module android compile comtheartofdevedmodoandroidimagecropper10 compile comviewpagerindicatorlibrary241aar compile meleolinshortcutbadger1010aar compile comandroidsupportappcompatv7230 compile comandroidsupportsupportv4230 compile comandroidsupportgridlayoutv7230 compile comandroidsupportcardviewv7230 compile group comfasterxmljacksoncore name jacksoncore version 241 group comfasterxmljacksoncore name jacksonannotations version 241 group comfasterxmljacksoncore name jacksondatabind version 241 compile deundercouchbson4jackson240 the sample build uses multiple directories to keep boilerplate and common code separate from the main sample codeliststring dirs main main sample code look here for the interesting stuff common components that are reused by multiple samples template boilerplate code that is generated by the sample template processandroid compilesdkversion 23 buildtoolsversion 2300 uselibrary orgapachehttplegacy defaultconfig minsdkversion 10 targetsdkversion 23 buildtypes debug minifyenabled false proguardfiles getdefaultproguardfileproguardandroidtxt proguardrulestxt release minifyenabled true proguardfiles getdefaultproguardfileproguardandroidtxt proguardrulestxt sourcesets main dirseach dir javasrcdirs srcdirjava ressrcdirs srcdirres androidtestsetroottests androidtestjavasrcdirs testssrc packagingoptions exclude metainfnotice exclude metainfnoticetxt exclude metainflicense exclude metainflicensetxt and here goes the proguardrulestxt add project specific proguard rules here by default the flags in this file are appended to flags specified in candroidsdktoolsproguardproguardandroidtxt you can edit the include path and order by changing the proguardfiles directive in buildgradle for more details see only obfuscatedontshrink keep source file and line numbers for better crash logskeepattributes sourcefilelinenumbertable avoid throws declarations getting removed from retrofit service definitionskeepattributes exceptions allow obfuscation of androidsupportv7internalviewmenu to avoid problem on samsung 422 devices with appcompat v21 see keep class androidsupportv7internalviewmenu amazon iap library has some missing stuffdontwarn comamazon butterknife uses some annotations not available on androiddontwarn butterknifeinternal prevent butterknife annotations from getting renamedkeepnames class butterknifeinjectview eventbus methods can not be renamedkeepclassmembers class public void onevent gson uses generic type information stored in a class file when working with fields proguard removes such information by default so configure it to keep all of itkeepattributes signature gson specific classesdontwarn sunmiscunsafe jodatime has some annotations we do not care aboutdontwarn orgjodaconvert okhttp has some internal stuff not available on androiddontwarn comsquareupokhttpinternal okio has some stuff not available on androiddontwarn javaniofiledontwarn orgcodehausmojoanimal snifferignorejrerequirement oltu has some stuff not available on android javaxservlet we do not use slf4j and not included because it is available on android jsondontwarn javaxservlethttpdontwarn orgslf4jdontwarn orgjsondontwarn comfasterxml retrofit has some optional dependencies we do not usedontwarn rxdontwarn retrofitappenginei have cleaned my project restarted android stuio even wiped out the whole builds directoryresultinformationgradle tasks applicationassemblereleaseapplicationprebuild uptodateapplicationprereleasebuild uptodateapplicationcheckreleasemanifestapplicationpredebugbuild uptodateapplicationpreparecomandroidsupportappcompatv72300library uptodateapplicationpreparecomandroidsupportcardviewv72300library uptodateapplicationpreparecomandroidsupportgridlayoutv72300library uptodateapplicationpreparecomandroidsupportsupportv42300library uptodateapplicationpreparecomgithublzyzsdcircleprogress110library uptodateapplicationpreparecomgoogleandroidgmsplayservicesbase780library uptodateapplicationpreparecomgoogleandroidgmsplayserviceslocation780library uptodateapplicationpreparecomgoogleandroidgmsplayservicesmaps780library uptodateapplicationpreparecomgoogleandroidgmsplayservicesnearby780library uptodateapplicationpreparecomtheartofdevedmodoandroidimagecropper104library uptodateapplicationpreparecomviewpagerindicatorlibrary241library uptodateapplicationpreparemeleolinshortcutbadger1010library uptodateapplicationpreparenetdanlewandroidjoda281library uptodateapplicationpreparereleasedependenciesapplicationcompilereleaseaidl uptodateapplicationcompilereleaserenderscript uptodateapplicationgeneratereleasebuildconfig uptodateapplicationgeneratereleaseassets uptodateapplicationmergereleaseassets uptodateapplicationgeneratereleaseresvalues uptodateapplicationgeneratereleaseresources uptodateapplicationmergereleaseresources uptodateapplicationprocessreleasemanifest uptodateapplicationprocessreleaseresources uptodateapplicationgeneratereleasesources uptodateapplicationprocessreleasejavares uptodateapplicationcompilereleasejavawithjavac uptodateapplicationcompilereleasendk uptodateapplicationcompilereleasesources uptodateapplicationlintvitalreleaseapplicationproguardrelease uptodateapplicationdexrelease uptodateapplicationvalidateexternaloverridesigningapplicationpackagerelease failederrorexecution failed for task applicationpackagerelease unable to compute hash of cusersrafal 0projektyapplicationbuildintermediatesclassesproguardreleaseclassesjarinformationbuild failedinformationtotal time 6694 secsinformation1 errorinformation0 warningsinformationsee complete output in console,"['java', 'android']" +996543,uiimagepickercontroller not asking for permissions on ios 9 i have an ios app where i present an image picker the selfpicker uiimagepickercontroller alloc initselfpickerdelegate selfselfpickersourcetype uiimagepickercontrollersourcetypephotolibraryselfpopover uipopovercontroller alloc initwithcontentviewcontrollerselfpickerselfpopover presentpopoverfromrectcgrectmake100 100 1 1 inviewselfview permittedarrowdirectionsuipopoverarrowdirectionany animatedyesthe app however does not ask for permissions at all it just thisplays the error message this app does not have access to your photos or videosany ideas on what might cause thisthanks in advance,"['ios', 'objective-c']" +996569,how to generate random 64bit unsigned integer in c i need generate random 64bit unsigned integers using c i mean the range should be 0 to 18446744073709551615 rand max is 1073741823i found some solutions in the links which might be possible duplicates but the answers mostly concatenates some rand results or making some incremental arithmetic operations so results are always 18 digits or 20 digits i also want outcomes like 5 11 387 not just 3771778641802345472by the way i really do not have so much experience with the c but any approach code samples and idea could be beneficial,['c'] +996661,memory usage with pointers please look at the below image after changing the value of p1 now it points to the b2 memory location what happened to the shaded memory segment as i know it will remain until code block finished its execution can those garbaged memory segments be reused again for program execution char p1 stringchar p2 anotherp1 p2question title may be misleading i was unable to find a qood title for this question,['c++'] +996749,classes without constructor in f i am not sure why f seems to allow the definition of a class without any constructors i mean it would be impossible to instantiate an object of the class should not the language spec treat this as illegal behaviorfor example i can define the classtype myclass class member thisx 0 endmyclass seems to have the typetype myclass member x intbut it would not be instantiable,['.net'] +996769,foreach on collection cast to ienumerable work slower than without cast today i found something that i do not quite understand i got the following code in linqpad version 5void main const int size 50 listthing things enumerablerange1 50selectx new thing id xtolist var sw1 stopwatchstartnew foreach var t in things iftid size break sw1elapsedmillisecondsdump var sw2 stopwatchstartnew ienumerablething ienthings things foreach var t in ienthings if tid size break sw2elapsedmillisecondsdumpclass thing public long id get set it appears that second loop takes twice as long as the first one why would this simple cast cause such an effect i am sure that there is something simple happening under the hood that i am somehow missing,['c#'] +996907,spark rdd mapping with extra arguments is it possible to pass extra arguments to the mapping function in pysparkspecifically i have the following code recipe raw data rdd sctextfiledatajson use unicodetruejson data rdd raw data rddmaplambda line jsonloadslinemapped rdd json data rddflatmapprocessdatalinethe function processdataline takes extra arguments in addition to the json object asdef processdatalinedataline arg1 arg2how can i pass the extra arguments arg1 and arg2 to the flamap function,['python'] +997007,swift make protocol extension a notification observer let us consider the following codeprotocol a func doaextension a func registerfornotification nsnotificationcenterdefaultcenteraddobserverself selector selectorkeyboarddidshow name uikeyboarddidshownotification object nil func keyboarddidshownotification nsnotification now look at a uiviewcontroller subclass that implements aclass acontroller uiviewcontroller a override func viewdidload superviewdidload selfregisterfornotification triggerkeyboard func triggerkeyboard some code that make key board appear func doa but surprisingly this crashes with an error keyboarddidshow unrecognized selector sent to instance 0x7fc97adc3c60so should i implement the observer in the view controller itself cannot it stay in the extension following things already triedmaking a a class protocoladding keyboarddidshow to protocol itself as signatureprotocol aclass func doa func keyboarddidshownotification nsnotification,['ios'] +997218,authentication with jwt laravel 5 without password i am trying to learn laravel and my goal is to be able to build a restful api no use of views or blade only json results later an angularjs web app and a cordova hybrid mobile app will consume this api after some research i am inclining to choose jwtauth library for completely stateless benefit my problem is i have 2 main types of users customers and moderators customers are not required to have a password i need to be able to generate a token for access with the provided email only if that email exists in the database and it belongs to a customer it will generate and return the tokenif it exists and belongs to a moderator it will return false so the interface can request a password if the email does not exist it throws an invalid parameter errori read the docs here and it says it is possible to use custom claims but the docs does not explain what are claims and what it means the array being passed as custom claims i would like some input on how to go about achieving what i explain above phpnamespace apphttpcontrollersuse illuminatehttprequestuse apphttprequestsuse apphttpcontrollerscontrolleruse jwtauthuse tymonjwtauthexceptionsjwtexceptionclass authenticatecontroller extends controller public function authenticaterequest request credentials requestonlyemail password try verify the credentials and create a token for the user if token jwtauthattemptcredentials return responsejsonerror invalid credentials 401 catch jwtexception e something went wrong return responsejsonerror could not create token 500 if no errors are encountered we can return a jwt return responsejsoncompacttoken thanks youupdatebountys codepublic function authenticaterequest request email requestinputemail user userwhereemail emailfirst try verify the credentials and create a token for the user if token jwtauthfromuseruser return responsejsonerror invalid credentials 401 catch jwtexception e something went wrong return responsejsonerror could not create token 500 if no errors are encountered we can return a jwt return responsejsoncompacttoken,['php'] +997251,xcode 7 warnings with google signin lib when building project i got this issue warnings on xcode 7 could not resolve external type i google it and did all found solutions but did not solve the issuethe google signin lib was added via pods pod googlesigninsee following image link for detail warnings infowarnings on xcode 7 with google signin lib,['ios'] +997297,image not uploaded from angular to laravel i am created a form for save items details with the imagei am using laravel 51 and angularjs the items information will be saved succesfully but the image not uploaded to server and also image details not saved in databasei need help to upload image into laravel using angularjsits my html code div ngcontrolleritemcontrollerform ngsubmitadditem labelnamelabelinput typetext namename value ngmodelnewitemname placeholderitem name labelmodel nolabelinput typetext namemodel value ngmodelnewitemmodel placeholdermodel number labelsizelabelinput typetext namesize value ngmodelnewitemsize placeholderitem size labelcolourlabelinput typetext namecolor value ngmodelnewitemcolor placeholderitem colour br labeldescriptionlabeltextarea cols30 rows5 ngmodelnewitemdescription placeholderdescriptiontextarea br labelphotolabelinput typefile acceptimagworks ngfselect ngfmultipletrue classformcontrol idimg nameimg placeholderimage ngmodelnewitemphoto multiple br button typesubmitsavebuttonformdiv ngshowsendmessage item saved successfullydivdivangularjs codeappcontrolleritemcontrollerfunctionscopehttpitem scopeitemsscopenewitemscopecuritem scopesendmessagefalseloaddatato send message to site adminscopeadditemfunction ifscopecuritemid todo error thisplay scopenewitemupdatefunction angularextendscopecuritemscopecuritem scopenewitem scopesendmessagetrue else scopenewitemsavefunction item todo error thisplay scopeitemspushitem scopesendmessagetrue scopesendmessagetrue scopecuritem scopenewitem scopenewitemnew item loaddatafunction loaddata var items itemqueryfunction scopeitems items scopenewitemnew item angularmoduleitemservicefactoryitemresourcefunctionresource return resourceapiitemsitemid itemidid update methodput itemcontrollerphp is given below php namespace apphttpcontrollersauth use appfile use appitem use illuminatehttprequest as request use apphttprequests use apphttpcontrollerscontroller use illuminatehttpresponse use validator use input class itemcontroller extends controller validates given data for account param array data return validator protected function validatorarray data loan account is not validated return validatormakedata name required size requiredmax255 store a newly created resource in storage param illuminatehttprequest request return illuminatehttpresponse public function storerequest request validator thisvalidatorrequestall ifvalidatorfails return responsejson validatorerrors 400 itemnew itemrequestall ifitemsave iditemid if requesthasfilephoto file requestfilephoto imagenew file imagename thisuploadimagefile imagefile idid imagesave return responsejsonerror server is down 500 to strore images public function uploadimagefile storedfilename ifemptyfile extensionfilegetclientoriginalextension filename rand19extension storedfilenamebase pathimgworks filename filemove base pathimgworks filename return storedfilename,['php'] +997316,android sugar orm no such table exception i am getting the no such table exception when i am using sugar orm with gpu image android library i am using gradle and android studio once i remove gpu image this issue is solved so i do not know whats causing this exception details about this exception are also being thiscussed in this git issueand it seems a lot of people are still facing itmy crash log is posted below 1009 113021511 43264831comexampleapp esqlitelog 10 failed to do file read got 0 amt 100 last errno 2 1009 113026506 43264831comexampleapp esqlitelog 1 no such table image 1009 113026516 43264831comexampleapp eandroidruntime fatal exception asynctask 1 1009 113026516 43264831comexampleapp eandroidruntime javalangruntimeexception an error occured while executing doinbackground 1009 113026516 43264831comexampleapp eandroidruntime at androidosasynctask3doneasynctaskjava299 1009 113026516 43264831comexampleapp eandroidruntime at javautilconcurrentfuturetaskfinishcompletionfuturetaskjava352 1009 113026516 43264831comexampleapp eandroidruntime at javautilconcurrentfuturetasksetexceptionfuturetaskjava219 1009 113026516 43264831comexampleapp eandroidruntime at javautilconcurrentfuturetaskrunfuturetaskjava239 1009 113026516 43264831comexampleapp eandroidruntime at androidosasynctaskserialexecutor1runasynctaskjava230 1009 113026516 43264831comexampleapp eandroidruntime at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava1080 1009 113026516 43264831comexampleapp eandroidruntime at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava573 1009 113026516 43264831comexampleapp eandroidruntime at javalangthreadrunthreadjava838 1009 113026516 43264831comexampleapp eandroidruntime caused by androiddatabasesqlitesqliteexception no such table image code 1 while compiling select from image 1009 113026516 43264831comexampleapp eandroidruntime at androiddatabasesqlitesqliteconnectionnativepreparestatementnative method 1009 113026516 43264831comexampleapp eandroidruntime at androiddatabasesqlitesqliteconnectionacquirepreparedstatementsqliteconnectionjava886 1009 113026516 43264831comexampleapp eandroidruntime at androiddatabasesqlitesqliteconnectionpreparesqliteconnectionjava497 1009 113026516 43264831comexampleapp eandroidruntime at androiddatabasesqlitesqlitesessionpreparesqlitesessionjava588 1009 113026516 43264831comexampleapp eandroidruntime at androiddatabasesqlitesqliteprograminitsqliteprogramjava58 1009 113026516 43264831comexampleapp eandroidruntime at androiddatabasesqlitesqlitequeryinitsqlitequeryjava37 1009 113026516 43264831comexampleapp eandroidruntime at androiddatabasesqlitesqlitedirectcursordriverquerysqlitedirectcursordriverjava44 1009 113026516 43264831comexampleapp eandroidruntime at androiddatabasesqlitesqlitedatabaserawquerywithfactorysqlitedatabasejava1314 1009 113026516 43264831comexampleapp eandroidruntime at androiddatabasesqlitesqlitedatabasequerywithfactorysqlitedatabasejava1161 1009 113026516 43264831comexampleapp eandroidruntime at androiddatabasesqlitesqlitedatabasequerysqlitedatabasejava1032 1009 113026516 43264831comexampleapp eandroidruntime at androiddatabasesqlitesqlitedatabasequerysqlitedatabasejava1238,['android'] +997373,c metaprogramming a template parameter which must inherit an abstract class i have an abstract class for comparablehashable valuesclass keypublic virtual bool operator const key const 0 virtual bool operator const key const 0 virtual u32 hashcode const 0and some concrete class c which inherits thisclass c public keyprivate u32 a bpublic static const c null a prototype for representing a no value c some reasonable implementation it is just a pair and i would like to implement a templated hashset classtemplateclass t inherits key const t proto class hashset t is the type of values stored in these sets proto should be an instance of t which is used as the null value of type t for the purposes of set inclusion i am reasonably experienced with c but not especially with tmp and although it seems like something which should be embarrassingly simple to pull off i cannot seem to figure out how something like my pseudocode class t inherits key is actually done in c i want to be able to create a hashset of instances of c likehashsetc cnull mysetcan somebody please tell me what the proper and idiomatic way to handle this situation in c would be thank you,['c++'] +997530,difference between stdstring and stdstring in one function of my code i found a bug it was written stdstring const stdstring currentdatetime time t now time0 struct tm tstruct char buf80 tstruct localtimenow strftimebuf sizeofbuf ymdx tstruct strftimebuf sizeofbuf ymdx tstruct stdstring str buf strerasestdremovestrbegin strend strend return strthe code compiles without errors why does it compile what does stdstring mean then,['c++'] +997611,are arithmetic operations on literals calculated at compile time or run time i have the followingdouble timeinminutes double timeinmilliseconds 10 60is the operation 10 60 done at compile time or at run time in other words are there performance differences during run time between the code snippet above anddouble timeinminutes double timeinmilliseconds 60edit my question is different from will the java compiler precalculate sums of literals as i am mixing the use of variables and literals in the arithmetic operations it is a small difference but as tagirvaleev noted in the comments are arithmetic operations on literals calculated at compile time or run time there are instances where some literals are not precompiled even though they could be,['java'] +997650,in what cases does the procestart method return false from msdnthe return value true indicates that a new process resource was started if the process resource specified by the filename member of the startinfo property is already running on the computer no additional process resource is started instead the running process resource is reused and false is returnedtrying something like thisvar info new procestartinfo filename cmdvar p1 new process startinfo infovar result p1start trueresult p1start truevar p2 new process startinfo inforesult p2start truehave the same result if i am using filepath cmyappexe instead of cmdin what cases does it return false,"['c#', '.net']" +997696,in webpack how can i have different output directories for multiple entry points i have the following webpack configuration with multiple entry pointsmoduleexports entry somepage scriptssomedirsomepagejs anotherpage scriptssomedirsomesubdiranotherpagejs output path pathresolve dirname out filename namejs is it possible to set a different output path for each entry instead of getting an output of outsomepagejsoutanotherpagejs i want outsomedirsomepagejsoutsomedirsomesubdiranotherpagejsthe ideal solution for me would be for outputpath to accept a function for exampleoutput path function name hash return pathresolve dirname mymapoffilenamestodirsname filename namejsdoes anyone know if this is possible or if there is an existing plugin that can accomplish thisedit i do not want to use multiple config entries multicompiler because i would not be able to create a shared file among the entry points with commonschunkplugin anymore,['javascript'] +997709,why and when to use angularcopy deep copy i have been saving all the data received from services direct to local variable controller or scope what i suppose would be considered a shallow copy is that correctexampledataservicecallfunctionthenfunctionresponse scopeexample responsedatarecently i was told to use angularcopy in order to create a deep copyscopeexample angularcopyresponsedatahowever the deep copy information seems to be working in the same way when used by my angular application are there specific benefits to using a deep copy angularcopy and can you please explain them to me,['javascript'] +997725,create multiple columns in pandas dataframe from one function i am a python newbie so i hope my two questions are clear and complete i posted the actual code and a test data set in csv format belowi have been able to construct the following code mostly with the help from the stackoverflow contributors to calculate the implied volatility of an option contract using newtonraphson method the process calculates vega when determining the implied volatility although i am able to create a new dataframe column for implied volatility using the pandas dataframe apply method i am unable to create a second column for vega is there a way create two separate dataframe columns when the function to returns iv vega togetheri triedreturn iv vega from functiondfmyiv vega dfapplynewtonrap axis1got valueerror shape of passed values is 56 2 indices imply 56 13also triedreturn iv vega from functiondfmyiv dfvega dfapplynewtonrap axis1got valueerror shape of passed values is 56 2 indices imply 56 13additionally the calculation process is slow i imported numba and implemented the jitnogiltrue decorator but i only see a performance improvement of 25 the test data set is the performance test has almost 90 records the run time is 2 hours and 9 minutes without numba or with numba but witout nogiltrue the run time when using numba and jitnogiltrue is 1 hour and 32 minutes can i do betterfrom datetime import datetimefrom math import sqrt pi log exp isnanfrom scipystats import normfrom numba import jit dff daily fed funds posted rate is usually one day behinddff pdread csv parse dates0 index coldaterf float4f dffvalue10 100 rf 0015 get fed funds rate tradingminutesday 450 75 hours per day 60 minutes per hourtradingminutesannum 113400 trading minutes per day 252 trading days per yearcal usfederalholidaycalendar load us federal holiday calendarjitnogiltrue nogiltrue arg improves performance by 25def newtonraprow estimate implied volatility iv using newtonraphson method param row dataframe options contract params for function timestamp datetime close date expiry datetime option contract expiration date strike float option strike opttype object c for call p for put rootprice float underlying close price bid float option contact closing bid ask float option contact closing ask return float estimated implied volatility if rowbid 00 or rowask 00 or rowrootprice 00 or rowstrike 00 or rowtimestamp rowexpiry iv vega 00 00 set iv and vega to zero if option contract is invalid or expired else dte days to expiration uses pandas bdate range method to determine the number of business days to expiration minus usfederalholidays minus constant of 1 for the timestamp date dte floatlenpdbdate rangerowtimestamp rowexpiry lencalholidaysrowtimestamp rowexpiryto pydatetime 1 mark rowbid rowask 2 cp 1 if rowopttype c else 1 s rowrootprice k rowstrike t the number of trading minutes to expiration divided by the number of trading minutes in year t dte tradingminutesday tradingminutesannum todo get dividend value d 0 iv sqrt2 pi t mark s closed form estimate of iv brenner and subrahmanyam 1988 vega 00 for i in range1 100 d1 logs k t rf d iv 2 2 iv sqrtt d2 d1 iv sqrtt vega s normpdfd1 sqrtt model cp s normcdfcp d1 cp k exprf t normcdfcp d2 iv model mark vega if absmodel mark 10e9 break if isnaniv or isnanvega iv vega 00 00 todo return vega with iv if addl pandas column possible return iv vega return ivif name main test function from baseline data get csv true if get csv csvheaderlist timestamp oprasymbol rootsymbol expiry strike opttype rootprice last bid ask volume openint iv filename ctmptest2015093056recordscsv df pdread csvfilename parse dates0 3 namescsvheaderlist else pass start datetimenow todo create addl pandas dataframe column if possible for vega dfmyiv vega dfapplynewtonrap axis1 dfmyiv dfvega dfapplynewtonrap axis1 dfmyiv dfapplynewtonrap axis1 end datetimenow print end starttest data ctmptest2015093056recordscsv20150930 160aapl151016c001090aapl20151016 160109c109953463637156512900349720150930 160aapl151016p001090aapl20151016 160109p1099524234242379030870314620150930 160aapl151016c00110aapl20151016 160110c109953286310217288500328820150930 160aapl151016p00110aapl20151016 160110p1099528127428121134270302920150930 160aapl151016c0010aapl20151016 1601c10995235244245667423180318720150930 160aapl151016p0010aapl20151016 1601p109953231325203137730292620150930 160aapl151120c00110aapl20151120 160110c1099559575955330171120363520150930 160aapl151120p00110aapl20151120 160110p10995615616337241570403842,['python'] +997930,implementing interface comparators say i have a simple interface that i wish to be comparable based on some featureinterface organism extends comparableorganism string getname int getcomplexity override default int comparetoorganism other return thisgetcomplexity othergetcomplexity each implementing class must return a unique complexity so any two instances of a class will have the same complexity and any two instance of a different class will have a different complexity the natural ordering will group all instances of classes together i now want to implement this interface in a class that overrides the default comparison specifically for comparing two instance of that class within that clas group of instances in the order i use the following patternclass bacteria implements organism enum shape rod round spiral private final shape shape override public int comparetoorganism other if other instanceof bacteria return thisshapecomparetobacteriaothershape else return organismsupercomparetoother i am not particularly happy with this pattern of code once the set of classes implementing the interface becomes large it becomes quite complex to maintain and requires lots of repeated code and depends on an implicit property of complexity i much prefer the comparator style of defining the order i would like to be able to implement the comparable in bacteria using something that looks likereturn comparator comparingintorganismgetcomplexity thencomparingbacteriagetshapeto be clear i realise that comparators do not work like this they are designed so that one comparator is used across a collection not a different comparator depending on each object i mention them here not because they are a potential solution but because the chaining style of comparators is elegant and transparent i am interested in whether there is a similarly elegant way to define compareto to allow different orderings within a collection depending on class,['java'] +997943,golangstyle defer in c i was reading about the go languages defer statement it allows you to specify an action to take when a function has ended for example if you have a file pointer or resource instead of writing freedelete with every possible return path you just need to specify the defer function onceit looks like an analogue might be coming to c eventually what is standard deferfinalizer implementation in c will there be standardization of scope guardscope exit idioms until then is there anything unforeseen about doing it with an object whose destructor makes a callback it looks like the destructor order for local variables is sane and that it also handles exceptions well though maybe not exiting on signalshere is a sample implementation is there anything troubling about itinclude iostreaminclude functionalusing namespace stdclass frameexittask stdfunctionvoid func public frameexittaskstdfunctionvoid func func func frameexittask func frameexittask operatorconst frameexittask delete frameexittaskconst frameexittask deleteint main frameexittask outer taskcout world frameexittask inner taskcout hello if 11 2 return 1 frameexittask skipped taskcout blamoutput hello world,['c++'] +998071,verify oauth1a signed request using twitter joauth with rsasha1 i have a use case to authenticate oauth1 request which is signed using rsa private key and verified at server end with rsa public keyi found this library from twitter which helps us authenticateverify the oauth signed requests i want to leverage this library for verifying the request from jersey or spring mvc action method the request from client would have been signed using private key at my end i would use the public key of the client to verify the request which means rsasha1 algotwitter joauth seem to be useful but i am missing the code that would transform httpservletrequest to oauthrequestthe library readme file suggests this as facility but i could not find a code that does javaxservlethttphttpservletrequest comtwitterjoauthoauthrequest transformationthe request verification happens in verify method which has following signaturepublic verifierresult verifyunpackedrequestoauth1request request string tokensecret string consumersecretsecondly i also want to know which is the most appropriate way to useread rsa public key with twitter joauth when verify method takes string parameter,['java'] +998287,how can i modify ripple color when using attrselectableitembackground as background i have seen some so questions and they gave some possible methods to achieve what i want for exampleuse colorcontrolhighlight attribute in stylesxmlhere is my stylesv21xmlstyle nameselectableitembackground item nameandroidcolorcontrolhighlight5677fcitem item nameandroidbackgroundattrselectableitembackgrounditemstyleand my widgettextview androidididtv take photo as bt androidlayout width280dp androidlayout height48dp androidtextstringact take photo stylestyleselectableitembackgroundand it does not work i also tried to add parentthemeappcompat to selectableitembackground style or change to colorcontrolhighlightno android prefix or change to androidattrselectableitembackground neither is usefuluse backgroundtint attribute in layoutso i add androidbackgroundtint5677fc to my textview still useless then i tried to change androidbackgroundtintmode to src in and src atop and they never make a differenceso how can i change ripple color when i use attrselectableitembackground as background i only focus on lollipop and above thank you in advance,['android'] +998338,android what audio mode should be set to send receive voice between devices i am trying to stream voiceaudio two way between two android devices tablet and mobile over java sockets the tablet can play received audiovoice clearly but the mobile plays received audio as noisethen i set this audio mode in the code on tabletaudiomanagersetmodeaudiomanagermode in callthis now results in mobile receiving clear voicebut the tablet goes silent it does not play the received audio or rather its not audiblei am not sure what combination if any of audiomanager mode i should use here,['android'] +998394,what are the qualifications for a class in c to become a container i am new to c programming and came across the term containers with examples such as vector deque map etcwhat should be the minimum requirements that a class should fulfill to be called a container in c,['c++'] +998426,why 2700 records 320kb each should take 30 seconds to be fetched i have 2700 records in mongodb each document has a size of approximately 320kb the engine i use is wiredtiger and the total size of collection is about 885mb my mongodb config is as below systemlog destination file path usrlocalvarlogmongodbmongolog logappend truestorage dbpath usrlocalvarmongodb engine wiredtiger wiredtiger engineconfig cachesizegb 1 statisticslogdelaysecs 0 journalcompressor snappy collectionconfig blockcompressor snappy indexconfig prefixcompression falsenet bindip 127001my connection is via socket mongo client mongoclienttmpmongodb27017sockand collection stats reveal this resultdbmycolstats ns bimycol count 2776 size 885388544 avgobjsize 318944 storagesize 972476416 capped false wiredtiger metadata formatversion 1 creationstring allocation size4kbapp metadataformatversion1block allocationbestblock compressorsnappycache resident0checkpointwiredtigercheckpoint9addr01e30275da81e4b9e99f78e30275db81e4c61d1e01e30275dc81e40fab67d5808080e439f6afc0e41e80bfc0order9time14566832size511762432write gen13289checkpoint lsn2452054144checksumuncompressedcollatorcolumnsdictionary0formatbtreehuffman keyhuffman valueid5internal item max0internal key max0internal key truncateinternal page max4kbkey formatqkey gap10leaf item max0leaf key max0leaf page max32kbleaf value max1mbmemory page max10mos cache dirty max0os cache max0prefix compression0prefix compression min4split deepen min child0split deepen per child0split pct90value formatuversionmajor1minor1 type file uri statisticstablecollection06630292038312816605 lsm bloom filters in the lsm tree 0 bloom filter false positives 0 bloom filter hits 0 bloom filter misses 0 bloom filter pages evicted from cache 0 bloom filter pages read into cache 0 total size of bloom filters 0 sleep for lsm checkpoint throttle 0 chunks in the lsm tree 0 highest merge generation in the lsm tree 0 queries that could have benefited from a bloom filter that did not exist 0 sleep for lsm merge throttle 0 blockmanager file allocation unit size 4096 blocks allocated 0 checkpoint size 511762432 allocations requiring file extension 0 blocks freed 0 file magic number 120897 file major version number 1 minor version number 0 file bytes available for reuse 460734464 file size in bytes 972476416 btree columnstore variablesize deleted values 0 columnstore fixedsize leaf pages 0 columnstore internal pages 0 columnstore variablesize leaf pages 0 pages rewritten by compaction 0 number of keyvalue pairs 0 fixedrecord size 0 maximum tree depth 4 maximum internal page key size 368 maximum internal page size 4096 maximum leaf page key size 3276 maximum leaf page size 32768 maximum leaf page value size 1048576 overflow pages 0 rowstore internal pages 0 rowstore leaf pages 0 cache bytes read into cache 3351066029 bytes written from cache 0 checkpoint blocked page eviction 0 unmodified pages evicted 8039 page split during eviction deepened the tree 0 modified pages evicted 0 data source pages selected for eviction unable to be evicted 1 hazard pointer blocked page eviction 1 internal pages evicted 0 pages split during eviction 0 inmemory page splits 0 overflow values cached in memory 0 pages read into cache 10519 overflow pages read into cache 0 pages written from cache 0 compression raw compression call failed no additional data available 0 raw compression call failed additional data available 0 raw compression call succeeded 0 compressed pages read 10505 compressed pages written 0 page written failed to compress 0 page written was too small to compress 0 cursor create calls 7 insert calls 0 bulkloaded cursorinsert calls 0 cursorinsert key and value bytes inserted 0 next calls 0 prev calls 27 remove calls 0 cursorremove key bytes removed 0 reset calls 16657 search calls 16656 search near calls 0 update calls 0 cursorupdate value bytes updated 0 reconciliation dictionary matches 0 internal page multiblock writes 0 leaf page multiblock writes 0 maximum blocks required for a page 0 internalpage overflow keys 0 leafpage overflow keys 0 overflow values written 0 pages deleted 0 page checksum matches 0 page reconciliation calls 0 page reconciliation calls for eviction 0 leaf page key bytes thiscarded using prefix compression 0 internal page key bytes thiscarded using suffix compression 0 session object compaction 0 open cursor count 7 transaction update conflicts 0 nindexes 2 totalindexsize 208896 indexsizes id 143360 date 1 65536 ok 1how can i understand that mongodb uses swap how to infer where exactly is the bottleneckeditthe way i fetch data in python is for doc in mycolfinddate lte 20161212 gte 20120909 id false docuids setdocuids recordsappenddocdate field is indexededit 2 these are the result when fetching data cpu core1 65cpu core2 65cpu core3 65cpu core4 65ram 71908190mbswap 11402048mbedit 3mongodb log is20151011t1725083170330 i network initandlisten connection accepted from anonymous unix socket 18 2 connections now open20151011t1725083210330 i network initandlisten connection accepted from anonymous unix socket 19 3 connections now open20151011t1725365010330 i query conn19 getmore bimycol cursorid10267473126 ntoreturn0 keyupdates0 writeconflicts0 numyields3 nreturned14 reslen4464998 locks 199ms20151011t1725376650330 i query conn19 getmore bimycol cursorid10267473126 ntoreturn0 keyupdates0 writeconflicts0 numyields5 nreturned14 reslen4464998 locks 281ms20151011t1725503310330 i network conn19 end connection anonymous unix socket 2 connections now open20151011t1725503630330 i network conn18 end connection anonymous unix socket 1 connection now openedit 4sample data is date 20120912 uids 123430nb i have 30k uids inside of uids fieldedit 5explaining query thisplay that it has used ixscan stage dbmycolfinddate lte 20181127 gte 20110423 id 0explainexecutionstats queryplanner plannerversion 1 namespace bimycol indexfilterset false parsedquery and date lte 20181127 date gte 20110423 winningplan stage projection transformby id 0 inputstage stage fetch inputstage stage ixscan keypattern date 1 indexname date 1 ismultikey false direction forward indexbounds date 20110423 20181127 rejectedplans executionstats executionsuccess true nreturned 2776 executiontimemillis 2312 totalkeysexamined 2776 totaldocsexamined 2776 executionstages stage projection nreturned 2776 executiontimemillisestimate 540 works 27 advanced 2776 needtime 0 needfetch 0 savestate 31 restorestate 31 iseof 1 invalidates 0 transformby id 0 inputstage stage fetch nreturned 2776 executiontimemillisestimate 470 works 27 advanced 2776 needtime 0 needfetch 0 savestate 31 restorestate 31 iseof 1 invalidates 0 docsexamined 2776 alreadyhasobj 0 inputstage stage ixscan nreturned 2776 executiontimemillisestimate 0 works 2776 advanced 2776 needtime 0 needfetch 0 savestate 31 restorestate 31 iseof 1 invalidates 0 keypattern date 1 indexname date 1 ismultikey false direction forward indexbounds date 20110423 20181127 keysexamined 2776 dupstested 0 dupsdropped 0 seeninvalidated 0 matchtested 0 serverinfo host mysyslocal port 27017 version 300 gitversion nogitversion ok 1edit 6os mac osx yosemitemongodb version 300total ram 8gfilesystem mac os extended journaled,['python'] +998439,visual studio 2015 no bower packages in intellisense i have just download the visual studio 2015 community edition and started to learn asp5i have seen on many blog posts and videos that when creating a new bowerjson file you should be able to drop a line under the dependencies and a list of packages should start filtering as you type in the intellisense i am however unable to see any of these packages listed its also unable to find any versions if i manually type in the package name showing the only option as i have confirmed that the correct json schema has been selected for bower i am running vs2015 on a windows 7 64bit machine and fully connected to the internetlooking forward to getting to the bottom of this issuestuart,"['c#', 'asp.net']" +998440,is there any difference between the different methods of clearing the contents of a string variable given a string variable set to some valuestring s hellois there any difference performance gotchas between the following methods to clear the contents s s stdstringscleari got the sample code from this answer to a question about clearing a variable,['c++'] +998516,expected identifier in function declaration objectivec to swift i am trying to convert over my objectivec to swift a little confused on the error here and how to take care of it i have been reading through the documentation but still confused this was generated from a converter anyone have any ideasobjectivec id init self super init if self return nil selfcmrequestsquery nsmutablearray alloc initwithcapacity5 selfcmqueryisruning no selfrequestcounter 0 selfserverofflineorbadresponse no selfuserwasloggedin no selfneedtosendpushnotitoken no selfnointernetconection no selfneedtoupdatetoken no reqoperationmanager sharedmanager setdelegateself return selfswiftfunc init anyobject self super if self return nil selfcmrequestsquery nsmutablearraycapacity 5 selfcmqueryisruning false selfrequestcounter 0 selfserverofflineorbadresponse false selfuserwasloggedin false selfneedtosendpushnotitoken false selfnointernetconection false selfneedtoupdatetoken false reqoperationmanagersharedmanagersetdelegateself return self,['objective-c'] +998678,when should i be using classes in python i have been programming in python for about two years mostly data stuff pandas mpl numpy but also automation scripts and small web apps i am trying to become a better programmer and increase my python knowledge and one of the things that bothers me is that i have never used a class outside of copying random flask code for small web apps i generally understand what they are but i cannot seem to wrap my head around why i would need them over a simple function to add specificity to my question i write tons of automated reports which always involve pulling data from multiple data sources mongo sql postgres apis performing a lot or a little data munging and formatting writing the data to csvexcelhtml send it out in an email the scripts range from 250 lines to 600 lines would there be any reason for me to use classes to do this and why,['python'] +998713,hw kbd failed to set null as keyboard focus ios in my ios app crash log i found this statementhw kbd failed to set null as keyboard focus iosdoes anyone know what this is and how to resolve it,['ios'] +998730,scala string vs i am new to scala and i have seen code for concatenating strings in scala like thistest 1and i have tested and it is also written in scala doctest 1so my understanding is that is like the java string but is more powerful can take in more types of parameters also seems to be universal to other things like list i want to know if my understanding is correct and any other differences when should one over another just for string concatenation,['java'] +998733,lambda scope for static members initializer my question is about lambda scope for the static member initializers consider the following testinclude functionalinclude iostreamstruct s static const stdfunctionvoidvoid s funcconst stdfunctionvoidvoid ss func stdcout hello from pretty function stdendlint mainvoid ss func return 0gcc starting from 48 defines the lambda in the scope of s so the program outputs something like thishello from slambdagcc482 has a different definition for function co macros but nevertheless the lambda is still defined within smeanwhile gcc47 defines the lambda in the global scope so the program outputshello from lambdaprobably newer gcc are more standardcompliant however i would like to ask if the standard actually specifies this aspect or it can be implementationdependentupdate as user5434961 suggested that all function alike macros are implementation dependent so it is better to avoid them in a standardcompliant test so here is the example which can be compiled if a compiler defines such lambdas within s scope and breaks the compilation otherwiseinclude functionalinclude iostreamstruct s static const stdfunctionvoidvoid s funcprivate static const int s fieldconst stdfunctionvoidvoid ss func stdcout hello from ss func ss field ss field stdendlconst int ss field 1int mainvoid ss func return 0,['c++'] +998755,why is windowname cached in a programming challenge i recently took part in i had to use the windowname property to store manipulate data i found out that when you change this property it persists through page refreshes although not when opening a new page with the same urlthe only information i could find was that this is known and even used by some frameworks as data storage but i would be interested in the why as in why is windowname persistent any historical reasons and the how which rules are there of when the windowname is kept between page changes and when it is thiscardedapparently my googlefu is not strong enough to find the answers to these questions there is not even a mention of it on the mdn page so i hope that maybe you could help methanks david,['javascript'] +998790,paperdialog in polymer does not close in iphone i use this example from the doc of polymer paperdialog h2headerh2 paperdialogscrollable lorem ipsum paperdialogscrollable div classbuttons paperbutton dialogthismisscancelpaperbutton paperbutton dialogconfirmacceptpaperbutton divpaperdialogin every browser the dialog closes when i click on place that is not the dialog but on iphone ios 84 it does not worki cannot close the dialoghow can i solve this problem,['javascript'] +998897,boostasio wrong local endpoint code exampleinclude stdafxhinclude boostasiohppinclude winsock2hinclude iostreaminclude stringint tmainint argc tchar argv boostasioio service service auto sock new boostasiobasic stream socket boostasioiptcp service ifsock try boostasioipaddress v4 ipa boostasioipaddress v4from stringargv1 boostasioipbasic endpoint boostasioiptcp addressipa unsigned short atoiargv2 sock connectaddress stdcoutconnected local addresock local endpoint remote addresock remote endpointstdendl catch const boostsystemsystem error e stdcouterrorewhat int dummy stdcindummy return 0i have 2 computers output from computer aconnected local addressx remoteaddressy where x and y real ipsips same to ping outputoutput from computer bconnected local address127001 remoteaddressy where y real ipips same to ping outputcomputer a and b have only 1 nicwhy i got 127001 i cant make real connection from ip 127001 to y how to fix itupdate even windows sockets return 127001 on problematic host see code belowwsadata wsadataauto iresult wsastartupmakeword2 2 wsadataif iresult no error return 1socket connectsocketconnectsocket socketaf inet sock stream ipproto tcpif connectsocket invalid socket wsacleanup return 1sockaddr in clientserviceclientservicesin family af inetclientservicesin addrs addr inet addrargv1clientservicesin port htonsunsigned short atoiargv2iresult connectconnectsocket sockaddr clientservice sizeof clientserviceif iresult socket error wsacleanup return 1struct sockaddr in sinint addrlen sizeofsinifgetsocknameconnectsocket struct sockaddr sin addrlen 0 sinsin family af inet addrlen sizeofsin char ip inet ntoasinsin addr stdcoutipstdendl,['c++'] +999045,atomically increment two integers with cas apparently it is possible to atomically increment two integers with compareandswap instructions this talk claims that such an algorithm exists but it does not detail what it looks likehow can this be donenote that the obvious solution of incrementing the integers one after the other is not atomic also stuffing multiple integers into one machine word does not count because it would restrict the possible range,['c'] +999200,convert a static library target into a framework target in an xcode project i have a an xcode project which produces a static library my team plans all new development in swift it is not possible to add swift files to the static library project we are dropping support for ios 7 so it is now possible to include frameworks in our ios app therefore i intend to convert my static library project to a framework projecti have looked but i cannot find any tools or advice for how to perform this conversion the static library is large more than 100 m filesi am hoping for a better answer than create a new parallel framework target i have attempted this twice the first time as a swift target but i was not able to easily import all the objective c files next as an objective c target but there is no pch anymore,['ios'] +999223,reactnative android fontfamily does not take effect question 1i add a fontfamily to indexandroidjss welcome style but it takes no effect does fontfamily actually work on androidwelcomefontsize20fontfamilyrobotothintextaligncentermargin10question 2if fontfamily works on android is there a way to load custom font from assets or is this some feature to be implemented by reactnative,['android'] +999224,session is null in acquirerequeststate when loading virtual directory name in browser but not null when loading defaultaspx i have an aspnet 40 webforms application i need to access httpcontextcurrentsession and set a value in the acquirerequeststate event or an event after it in globalasax and i have found a peculiar behaviorlet us say i have a virtual directory in iis version 7 in my case called foo in that i have defaultaspx as the home page a sample globalasax file is below application languagec script runatserver void application acquirerequeststateobject sender eventargs e httpcontextcurrentsessionkey value scriptwhen i visit httplocalhostfoodefaultaspx in my browser it works just fine when i visit httplocalhostfoo i get a nullreferenceexception where i set the value on the session the only change is the url in the browser they end up hitting the same page but the framework behaves differently based on whether or not the url contains just a folder name or if it contains an aspx filechecking if httpcontextcurrentsession null is not an option for me because i need to set a value on the session with every request which is non negotiableis there a config setting in iis that i am missing or is this a bugforgotten featurean answer for another question hinted at the fact iis does not load the session for every kind of request for example style sheets do not need a session maybe this behavior is happening because iis cannot tell ahead of time if that folder name will result in executing an aspx file or if it will deliver a static html fileupdate i even tried reordering the default documents that iis looks for so that defaultaspx was at the top of the list egdefaultaspxdefaultaspdefaulthtmand i am still getting the same problemupdatethe event handler is only getting fired once because it is resulting in a nullreferenceexception i have done some additional reading and i know aspnet triggers these events for every request even for css or javascript files additionally the session object is not loaded for static files because there is not code that accesses the session thus no need to load the object even so the very first request is the request for the web page which will need the session and the session is nulldmytroshevchenko askedfirst add a guard check if httpcontextcurrentsession null so that there is no nullreferenceexception thrown then try to see maybe the event will be fired a second time with a session availablemodified codevoid application acquirerequeststateobject sender eventargs e if httpcontextcurrentsession null httpcontextcurrentsessionkey value i set a break point at the if statement i saw this event fire 4 timessession is nullsession is nullsession not nullsession is nullwhen continuing to step through the code each time only when it started executing defaultaspx and its codebehind did i have a session available i actually had the web page open in firefox and was monitoring the network requests the first request was for httplocalhostfoonext i set a breakpoint in application beginrequest as well and got the following eventsbeginrequestacquirerequeststatebeginrequestacquirerequeststatebeginrequestacquirerequeststate session is not nullexecute defaultaspx foo returns a response to the browserbeginrequestacquirerequeststate session is null againat 9 the ajax request in the browser to httplocalhost548598fad4e71e57a4caebe1c6ed7af6f583aarterysignalrpolltransportlongpollingconnectiontokenmessageidrequesturlhttp3a2f2flocalhost2ffoo2fbrowsernamefirefoxuseragentmozilla2f50windowsnt613bwow643brv3a410gecko2f20100101firefox2f410tid4 1445346977956 is hanging waiting for a response,"['c#', 'asp.net']" +999501,reusing jax rs client in multithreaded environment with resteasy according to the documentation clients are heavyweight objects that manage the clientside communication infrastructure initialization as well as thisposal of a client instance may be a rather expensive operation it is therefore advised to construct only a small number of client instances in the application ok i am trying to cache client itself and webtarget instances in a static variable the somemethod is invoked in multithreaded environmentprivate static client client clientbuildernewclientprivate static webtarget webtarget clienttargetsomebaseurlpublic static string somemethodstring arg1 string arg2 webtarget target entrtargetqueryparamarg1 arg1queryparamarg2 arg2 response response targetrequestget final string result responsereadentitystringclass responseclose return resultbut sometimes not always i am get an exceptioninvalid use of basicclientconnmanager connection still allocated make sure to release the connection before allocating another onehow can clientwebtarget be reusedcached correctly is it possible with jax rs client api or i have to use some frameworkspecific features resteasyjersey could you provide some example or documentation,['java'] +999529,uiapplicationshortcutitem can i use an image downloaded from the web as uiapplicationshortcuticon i am setting up some 3d touch functionality and would like to use an image that has been downloaded from the web can access via sdwebimages cache as an audio cover image in a uiapplicationshortcutitem just like apples music app see screenshotis this possible it looks like it is not as i cannot put the image in to the apps bundle as far as i know i guess apple is doing something that devs cannot do yet uiapplicationshortcutitems docs only have the following create an icon using a systemdefined image instancetypeiconwithtypeuiapplicationshortcuticontypetype create an icon from a custom image the provided image named will be loaded from the apps bundle and will be masked to conform to the systemdefined icon style instancetypeiconwithtemplateimagenamensstring templateimagename,['ios'] +999562,tryfinally without catch and return value i have a program as followingpublic class main public static void mainstring argsthrows exception int res test systemoutprintlnafter call res res public static int testthrows exception try return 100 finally systemoutprintlnfinally after run above program following result saw in consolefinallyexception in thread main javalangarithmeticexception by zero at maintestmainjava17 at mainmainmainjava7this behavior is normal because exception thrown to main methodthen i change code as following public class main public static void mainstring argsthrows exception int res test systemoutprintlnafter call res res public static int testthrows exception try return 100 finally systemoutprintlnfinally return 20 when run above program i saw following result in consolefinallyafter call res 20my question related to second format why when return in finally block exception not thrown to main method,['java'] +999594,getting current time in java 8 i am exploring the new javatime api of java 8 i am particularly trying to retrieve the current time my current time zone of a different time zone and of a different offsetthe code ispublic static void getcurrentlocaltime localtime time localtimenow systemoutprintlnlocal time zone zoneidsystemdefaulttostring systemoutprintlncurrent local time timepublic static void getcurrenttimewithtimezone localdatetime localtdateandtime localdatetimenow zoneid zoneid zoneidofamericalos angeles zoneddatetime dateandtimeinla zoneddatetimeoflocaltdateandtime zoneid string currenttimewithtimezone dateandtimeinlagethourdateandtimeinlagetminute systemoutprintlncurrent time in los angeles currenttimewithtimezonepublic static void getcurrenttimewithzoneoffset localtime localttime localtimenow zoneoffset offset zoneoffsetof0800 offsettime offsettime offsettimeoflocalttime offset string currenttimewithzoneoffset offsettimegethouroffsettimegetminute systemoutprintlncurrent time with offset 0800 currenttimewithzoneoffsetbut when i call the methods i get the same timeofday my system time which is obviously not what i am expecting the output of the method callscurrent time in los angeles 1959local time zone asiacalcuttacurrent local time 195920477current time with offset 0800 1959even after setting a different time zone and offset why am i getting the same time,['java'] +999818,ipython autoreload changes in subdirectory i launch ipython from the main folder project now if i make changes in the file projecttestssome modulepy the changes fail to be autoreloaded in ipython also i get the following message after i save the changes and want to run some other script in the promptautoreload of some module failed traceback most recent call last file usrlibpython27thistpackagesipythonextensionsautoreloadpy line 229 in check superreloadm reload selfold objectsimporterror no module named some moduleit seems it detects changes were made inside folder tests but it cannot import it can someone help me with thiseditfor better clarification i launch ipython from the terminal in the main folder in this folder i have another folder tests inside tests i have two python filessome modulepydef hello world print hello worlduse some modulepyfrom some module import hello worldhello worldonce i launched ipython further changes in some modulepy would not be loaded in ipython for example if i add a second print hello earth in the definition of hello world and run run testsuse some modulepy i get the error message shown above and will only get the hello world printedit2 i would like a solution where i do not need to either change the working directory or adding any search paths manually i want it to be loaded automatically with autoreload,['python'] +999832,how to handle errors in celerys taskmap say i have two celery taskscelerytaskdef run flakey thingsargs kwargs return run flakey and synchronous thingmap xrange10 apply asynccelerytaskdef run flakey and synchronous thinga if a 5 return a raise runtimeerroraso when you go to run run flakey things it will fall over straight away because the first item in the sequence raises an exception what i would like is to run the task for all items in the sequence in order as map does but continue to run on exception raising a new exception once all of these have completedthe ideal would be if i could add an on failure to the xmap object before applying it but xmap does not appear to be a full task object,['python'] +999852,functional reference to objectclone does not compile compilingimport javautilconcurrentcallableclass ideone callable x supercloneusing oracle jdk givesmainjava6 error incompatible types invalid method reference callable x superclone clone has protected access in objectwhich makes no sense as a class should be able to access its parents protected methods this expression works fine in eclipses compileralso superclone compiles fineis this a bug,['java'] +999890,why can we not use default methods in lambda expressions i was reading this tutorial on java 8 where the writer showed the codeinterface formula double calculateint a default double sqrtint a return mathsqrta and then saiddefault methods cannot be accessed from within lambda expressions the following code does not compileformula formula a sqrt a 100but he did not explain why it is not possible i ran the code and it gave an errorincompatible types formula is not a functional interfaceso why is it not possible or what is the meaning of the error the interface fulfills the requirement of a functional interface having one abstract method,['java'] +999904,required casting using c ternary conditional operator i am trying to figure out why casts are required in the following examplesbool test new randomnextdouble 05short val 5 ex 1 must cast 0 to shortshort res test 5 0 fineshort res test val 0 errorshort res test val short0 ugly ex 2 must cast either short or null to shortshort nres test val null errorshort nres test shortval null uglyshort nres test val shortnull uglyshort nres test val defaultshort uglythe first example just seems crazy to me if short i 0 compiles why cannot the compiler implicitly treat the 0 or any other valid short value as a short in the above codethe second example makes more sense to me i understand that the compiler is unable to determine the type of the expression on the right side of the but imo it should take nullable types into account when doing soi would like to understand if there is actual reasoning behind these compiler errors,['c#'] +999922,script tag textbabel variable scope firstly i understand textbabel is not for use in production but i found it quite useful for development as when i make a change to my jsx file djangos dev webserver will reload without me having to do anything ie compile the jsx to js after every changei am not in control of the build environment eg django as this is a small plugin for a larger system that i am not developingthe problem is thisscript typetextbabel src static myappjsmainjsx scriptscript function consolelogmything scriptwhere mything is in mainjsx something as simple asvar mything helloif mainjsx is javascript and the type of the script tags is changed accordingly then this will work just fine as textbabel though it will not work because mything is not in scopeuncaught referenceerror mything is not definedthis makes sense to me as i wouldnt expect script tags of different types to share a scope but i am wondering if there is some clever way around this to aid developmenti previously had all the code in a single textbabel block but as it grows it would be nice to separate it out into several jsx files,['javascript'] +999980,why must thrown objects be copyinitialized exceptions use the statical type of an object to copyinitialize the thrown object for instancestruct foo foo default fooconst foo deleteint main throw fooclang stdc14 complains that the explicitlydeleted copy constructor cannot be used why cannot it be moveinitialized instead,['c++'] +1000160,latency when pressing headset button in iphone i am trying to trigger different actions inside only my own app using buttons of plugged headset something similar what pressy does i noticed however that no matter if i use mpremotecommandcenter or remotecontrolreceivedwithevent delegate i receive events with a noticable lag what makes matter worse is that if i try double press button fast i will only get one uieventtyperemotecontroldoes anyone experience similar issue know the reason of this or even better know some workaround tested under ios8 and ios9,"['ios', 'iphone']" +1000234,wsdl how to generate exception with errorcode and errormessage inlined i am trying to use wsdlfault but can not generate expected java class exception the class i get generated annotations and getterssetters removedpublic class projectexception extends exception private comhomeprojectgeneratedfault faultpublic class fault protected string errormessage protected long errorcodethe class i expect to get generatedpublic class projectexception extends exception protected string errormessage protected long errorcodemy wsdlxml version10 encodingutf8wsdldefinitions nameprojectsoapserviceimplservice targetnamespace 0project xmlnswsdl xmlnstns 0project xmlnssoap wsdltypes xsschema xmlnstns 0project xmlnsxs elementformdefaultunqualified targetnamespace 0project version10 xselement namecreateproject typetnsprojectrequest xselement nameprojectresponse typetnsprojectresponse xscomplextype nameprojectrequest xssequence xselement minoccurs0 nameprojectname typexsstring xssequence xscomplextype xscomplextype nameprojectresponse xssequence xselement minoccurs0 nameprojectid typexslong xssequence xscomplextype xselement namefault xscomplextype xssequence xselement nameerrormessage typexsstring xselement nameerrorcode typexslong xssequence xscomplextype xselement xsschema wsdltypes wsdlmessage namecreateproject wsdlpart nameparameters elementtnscreateproject wsdlmessage wsdlmessage namecreateprojectresponse wsdlpart nameparameters elementtnsprojectresponse wsdlpart wsdlmessage wsdlmessage nameprojectexception wsdlpart namefaultmessage elementtnsfault wsdlmessage wsdlporttype nameprojectport wsdloperation namecreateproject wsdlinput namecreateproject messagetnscreateproject wsdloutput namecreateprojectresponse messagetnscreateprojectresponse wsdlfault namefault messagetnsprojectexception wsdloperation wsdlporttype wsdlbinding nameprojectsoapserviceimplservicesoapbinding typetnsprojectport soapbinding styledocument transport wsdloperation namecreateproject soapoperation soapaction styledocument wsdlinput namecreateproject soapbody useliteral wsdlinput wsdloutput namecreateprojectresponse soapbody useliteral wsdloutput wsdlfault namefault soapfault namefault useliteral wsdlfault wsdloperation wsdlbinding wsdlservice nameprojectsoapserviceimplservice wsdlport nameprojectportport bindingtnsprojectsoapserviceimplservicesoapbinding soapaddress locationhttplocalhost9090projectportport wsdlport wsdlservicewsdldefinitionsany ideas how to inline properties in class directlythanks in advance,['java'] +1000241,how to set 135 years billing period in paypal express checkout php i am using paypal as payment gateway and want to create recurring profile like 1 year plan for 20 3 year plan for 40 5 year plan for 50but when i am adding billingperiodyearbillingfrequency3 as paramsgetting error from paypal api and getting error billing frequency must be 0 and be less than or equal to one yearerror message invalid billing frequencyerror code 11516error severity code error please help me here,['php'] +1000332,new android studio activity design pattern content mainxml i started learning android but in new android studio 14 using blank activity creates two xml files activity main and content main from what i read this is the new design pattern but no relatively new tutorial 1yr mentions this and operates with blank activity creating only activity mainis there any way around it is it possible to create your own activity template or just create activity main without content main learning android for beginner is already enough of a hassle without manually creating java and xml from empty activity every time or trying to translate files from tutorials into new design pattern while trying to learn,['android'] +1000353,recyclerview addonitemtouchlistener get whichsubview is clicked inside row i have implemented recyclerview onclicklistener from this stack overflow solution this solution works fine for the recycler item clicks but i cannot able to get which subviewex imageviewbutton is clicked from the row mattachmentrecyclerviewaddonitemtouchlistener new recycleritemclicklistenergetapplicationcontext new recycleritemclicklisteneronitemclicklistener override public void onitemclickview view int position if viewgetidridattachmnet remove attachmentslistremoveposition mattachmentadapternotifydatasetchanged attachmentcount onitemclickviewposition always returns view id as 1 how do i track whick view is clicked,"['java', 'android']" +1000397,resume vimeo video from last progress i have an embedded vimeo video on the homepage my site which is set to autoplay when the site loads i am also using the api and froogaloopjs for some custom controlswhat i need to do is save the time the video has got to when a visitor navigates to another page then resume playing from this point if and when they return to the homepagei know i can use playprogress to get the time elapsed but am not sure how to store this and how to use it when the visitor returns to the homepageediti now have the following code and am using jscookie to store the progress cookie how would i get the value of playprogress and set it as a cookie using beforeunload on window i am not great at javascript so help would be greatjavascript also including this library function var iframe player10 var player1 fiframe var status1 status1 when the player is ready add listener for playprogress player1addeventready function status1textready player1addeventplayprogress onplayprogress function onplayprogressdata id status1textdataseconds seconds played setting a cookie cookiessettimeelapsedsomethinghtmlscript srcscriptdiv classvideoholder h3player 1h3 iframe idplayer1 srcplayer idplayer1 width500 height281 frameborder0 webkitallowfullscreen mozallowfullscreen allowfullscreeniframe div pspan clastatus1hellipspanp divdiv,"['javascript', 'jquery']" +1000398,android 60 permissionget accounts i am using this to get permission if contextcompatcheckselfpermissioncontext manifestpermissionget accounts packagemanagerpermission granted should we show an explanation if activitycompatshouldshowrequestpermissionrationalecontext manifestpermissionget accounts else no explanation needed we can request the permission activitycompatrequestpermissionscontext new stringmanifestpermissionget accounts permissions request get accounts my permissions request read contacts is an appdefined int constant the callback method gets the result of the request but the pop up dialog for permission asks user for access contactsin pre 60 in play store with usespermission androidnameandroidpermissionget accountsrequest is named identity and explains i need it to get device account,['android'] +1000477,react unterminated jsx contents i am trying to set up a basic react example using jspmsystemjs and babel i have this code here to show a simple page and am getting an error import react from reactexport default reactcreateclassthisplayname maincomponentproptypes item reactproptypesobjectrender function render return div classbuilderconteiner div reactrendermaincomponent documentgetelementbyidappnothing is showing up and the console is erroring unterminated jsx contents and babel is pointing to the reactrender line like so 17 reactrendermaincomponent documentgetelementbyidapp still new to this so i am unsure what is going wrong here would appreciate any help thanks,['javascript'] +1000494,how to enablethisable toolbar scrolling programmatically when using design support library i use support design library to showhide toolbar when scrolling a recyclerview inside a fragment as mention here guideswikihandlingscrollswithcoordinatorlayoutxml version10 encodingutf8androidsupportv4widgetdrawerlayout xmlnsandroid xmlnsapp xmlnstools androidididdrawer layout androidlayout widthmatch parent androidlayout heightmatch parent androidfitssystemwindowstrue toolsopendrawerstart androidsupportdesignwidgetcoordinatorlayout androidididcoordinatorlayout androidlayout widthmatch parent androidlayout heightmatch parent toolscontextmainactivity androidsupportdesignwidgetappbarlayout androidididappbarlayout androidlayout widthmatch parent androidlayout heightwrap content androidthemestyleappthemeappbaroverlay androidsupportv7widgettoolbar androidididtoolbar androidlayout widthmatch parent androidlayout heightattractionbarsize androidbackgroundattrcolorprimary apopupthemestyleappthemepopupoverlay applayout scrollflagsscrollenteralways androidsupportdesignwidgetappbarlayout framelayout androidididflcontent androidlayout widthmatch parent androidlayout heightmatch parent applayout behaviorstringappbar scrolling view behavior androidsupportdesignwidgetfloatingactionbutton androidididfab androidlayout widthwrap content androidlayout heightwrap content androidlayout gravitybottomend androidlayout margindimenfab margin androidsrcandroiddrawableic dialog email androidsupportdesignwidgetcoordinatorlayout androidsupportdesignwidgetnavigationview androidididnav view androidlayout widthwrap content androidlayout heightmatch parent androidlayout gravitystart androidfitssystemwindowstrue appheaderlayoutlayoutnav header main appmenumenuactivity main drawer androidsupportv4widgetdrawerlayoutit works grate now i want to enablethisable toolbar scrolling programmatically because i use fragments and i need to stop this feature for some fragments,['android'] +1000511,casting pointer to void is there any difference in below two castings int a10int pavoidp does not give any warning or error or void p error statement with no effect werrorunusedvaluewhen complied with gcc wall werror stdc99 pedantic just saw that in this answer clearly i misunderstood something,['c'] +1000517,rails performance issue with joining of records i have the following setup with activerecord and mysqluser has many groups through membershipsgroup has many users through membershipsthere is also an index by group id and user id described in schemarbadd index memberships group id user id name uugj index using btree3 different queriesuserwhereid membershipuniqpluckuser id38ms select thistinct membershipsuser id from memberships user load 110ms select users from users where usersid in 1 2userwhereid membershipuniqselectuser iduser load 152ms select users from users where usersid in select thistinct membershipsuser id from membershipsuseruniqjoinsmembershipsuser load 1351ms select thistinct users from users inner join memberships on membershipsuser id usersidwhat is the best approach for doing this why the query with join is much slower,"['mysql', 'ruby-on-rails']" +1000569,setting a length height or width for one element minus the variable length of another ie calcx y where y is unknown i know we can use calc when lengths are definedflexbasis calc3 60pxleft calc50 25pxheight calc100em5but what if a length is variableheight calc100 header with variable heightorwidth calc100 50px box with variable widthis there a standard way to do this in cssi know the overall task is possible with flexbox and tables but i am wondering if css offers a simpler method flexbox tables and simple javascript are acceptable alternativesheight demowidth demo,"['javascript', 'jquery', 'css']" +1000749,limit panning amount in order to prevent image from wandering off of the window introductioni have exported svg as xaml and it turned into canvas with enormous amount of paths after making that canvas main content of the simple autogenerated window image was clipped since it was bigger than main windows client rectangle i have solved this problem by implementing panning since i plan on fiddling with the zooming later i have added dummy scaletransform in the xaml of the canvas and have changed its rendertransformorigin to 05 05 so i can zoom image around its centeri wanted image to be centered when window is loaded so i placed that canvas inside viewbox which seems to work just fine after adjusting few propertiesproblemsince i have changed the rendertransformorigin of the canvas i am unable to figure out math that will enable me to limit panning amounteven though the viewbox is the content of the main window i can not get dimensions of main windows client area viewbox resizes to fit its content this makes my task even more difficultmy efforts to solve thisthere seems no other way to get main windows client rectangle except with the usage of pinvoke and getclientrect winapi call there was another hack with querying systemparametersinfo for nonclient metrics such as borders and titlebar but that is an estimation that might fail due to applied themes and similari have not tried to use pinvoke because i simply refuse to do so at the moment there has to be better solution than this that path should be my last choice and the one i will make out of pure desperationi have tried to find alternative approach on my own but failed i have tried to use transformtoancestortransformtobounds for my calculations but that failed tooquestionhow to limit panning so image does not thisappear from the main window when user drags too much i will accept alternative solutions code that was submitted was a try of an inexperienced self taught beginner so i accept constructive critique and advicerelevant informationin order to keep this post as short as possible i am giving only relevant xaml and code behind snippets below full code is pasted on pastebin and can be found at the very bottom of this post relevant xaml snippetswindow xclasstestzamapumainwindow nameglavniprozor windowstartuplocationcenterscreen xmlns xmlnsx titlemainwindow height350 width525 mouseleftbuttondownglavniprozor mouseleftbuttondown mouseleftbuttonupglavniprozor mouseleftbuttonup mousemoveglavniprozor mousemove lostmousecaptureglavniprozor lostmousecapture viewbox namesurface stretchuniformtofill horizontalalignmentcenter verticalalignmentcenter canvas xmlns backgroundblue xnamesvg4306 width494705 height51055356 needed in the future for zooming around center rendertransformorigin05 05 unknown tag metadata canvasrendertransform transformgroup i intend to experiment with scaling in the future so i added the below part scaletransform scalex1 scaley1 i have used dependency properties for translation translatetransform xbinding translationfactorx elementnameglavniprozor modetwoway ybinding translationfactory elementnameglavniprozor modetwoway transformgroup canvasrendertransform bunch of path objects omitted for brevity canvas viewboxwindowrelevant code behind snippetsnamespace testzamapu summary interaction logic for mainwindowxaml summary public partial class mainwindow window public mainwindow initializecomponent translationfactorx 0 translationfactory 0 ispanning false panning variables private point ptoldposition private bool ispanning dependency properties for translation along x and y axes public static readonly dependencyproperty translatex dependencypropertyregistertranslationfactorx typeofdouble typeofmainwindow public static readonly dependencyproperty translatey dependencypropertyregistertranslationfactory typeofdouble typeofmainwindow public double translationfactorx get return doublegetvaluetranslatex set setvaluetranslatex value public double translationfactory get return doublegetvaluetranslatey set setvaluetranslatey value mouse event handlers for panning private void glavniprozor mouseleftbuttondownobject sender mousebuttoneventargs e baseonmouseleftbuttondowne if ispanning return ispanning thiscapturemouse ptoldposition egetpositionthis private void glavniprozor mouseleftbuttonupobject sender mousebuttoneventargs e baseonmouseleftbuttonupe if thisismousecaptured thisreleasemousecapture ispanning false private void glavniprozor mousemoveobject sender mouseeventargs e baseonmousemovee if ispanning point ptnewposition egetpositionthis if ptnewposition ptoldposition vector direction ptoldposition ptnewposition directionx translationfactorx directionx directiony translationfactory directiony translationfactorx directionx translationfactory directiony ptoldposition ptnewposition private void glavniprozor lostmousecaptureobject sender mouseeventargs e ispanning false thisonlostmousecapturee here is the full xaml and here is full code behind,['c#'] +1000862,how to wire up reduxform bindings to the forms inputs reduxform is a very compelling library for providing redux bindings for forms in a react application which should be superconvenient unfortunately using the librarys own examples i am failing to actually bind anything which is super inconvenienti am attempting to make use of the sample code on the project site and finding multiple obstacles despite attempting to reproduce it faithfully where am i misinterpreting this api has the api shifted since the demo code was written am i missing some critical and obvious piece of redux knowledgeproblem 1 the signature for the handlesubmit method should be handlesubmitdata but handlesubmit is currently receiving only the react syntheticevent from the submit action and no data in fact using the example aswritten was sending two separate events seemingly because of the stacked onsubmit action on the form and the onclick on the button where is that data supposed to be coming from and why am i failing to pass it to the handlerproblem 2 there is a critical fields object that must be defined on the form parent and supplied as prop to your form unfortunately the shape of that fields object is not explained in the docs nor its purpose really is it essentially the initial state object a simple object container for reduxform to use at runtime for errors etc i have gotten it to stop erroring by matching the props on fields to the field names in connectreduxform but because the data is not binding i am assuming it is not the right shapeproblem 3 the fields are supposed to be autobound to handlers for onblur and onchange so that they update the store appropriately that is never happening which we can see thanks to the redux devtools however handlesubmit is successfully thispatching the initialize action which suggests the store reducer and other basic plumbing are all working problem 4 validatecontact is firing once on init but never againthis is unfortunately too complex for a simple fiddle but the entire repo it is just the basic reduxstarterapp plus this form poc is available here and here is the outer componentimport react from reactimport connect from reactreduximport initialize from reduxformimport contactform from componentssimpleformsimpleformjsconst mapstatetoprops state counter statecounterexport class homeview extends reactcomponent static proptypes thispatch reactproptypesfuncisrequired counter reactproptypesnumber constructor super handlesubmitevent data eventpreventdefault consolelogevent this should be the data but is an event consolelogdata no data here either consolelogsubmission received data thispropsthispatchinitializecontact clear form this works return false increment thispropsthispatch type counter increment render const fields name address phone return div classnamecontainer textcenter h1welcome to the react redux starter kith1 h2sample counter thispropscounterh2 button classnamebtn btndefault onclickthis increment increment button contactform handlesubmitthishandlesubmitbindthis fieldsfields div export default connectmapstatetopropshomeviewand the inner form componentimport react component proptypes from reactimport connectreduxform from reduxformfunction validatecontactdata consolelogvalidating consolelogdata const errors if dataname errorsname required if dataaddress dataaddresslength 50 errorsaddress must be fewer than 50 characters if dataphone errorsphone required else if d3d3d4testdataphone errorsphone phone must match the form 9 return errorsclass contactform extends component static proptypes fields proptypesobjectisrequired handlesubmit proptypesfuncisrequired render const fields name address phone handlesubmit thisprops return form onsubmithandlesubmit labelnamelabel input typetext name will pass value onblur and onchange nameerror nametouched divnameerrordiv labeladdresslabel input typetext address will pass value onblur and onchange addresserror addresstouched divaddresserrordiv labelphonelabel input typetext phone will pass value onblur and onchange phoneerror phonetouched divphoneerrordiv button typesubmitsubmitbutton form apply connectreduxform and include synchronous validationcontactform connectreduxform form contact the name of your form and the key to where your forms state will be mounted fields name address phone a list of all your fields in your form validate validatecontact a synchronous validation functioncontactform export the wrapped componentexport default contactform,['javascript'] +1000865,zingchart target multiple series in a rule using tokens i am wondering whether it is possible to target multiple series in the same rule using tokens in essence what i am aiming for is if the value from series 1 is greater than the value in the same position in series 2 change some styleszingchart configvar config type area plot rules rule v from series 1 v from series 2 backgroundcolor c series text series 1 values 36 40 38 47 49 45 48 54 58 65 74 79 85 83 79 71 61 55 text series 2 values 40 40 40 50 50 50 50 60 60 80 80 80 80 80 80 80 60 60 if that is not possible is there another way to achieve the same outcome i am aiming to change the style of an individual point when the series 1 value is greater than the series 2 value,['javascript'] +1000879,can golang multiply strings like python can python can multiply strings like sopython 343 default mar 26 2015 220340gcc 492 on linuxtype help copyright credits or license for more information x my new text is this long y lenx ycan golang do the equivalent somehow,['python'] +1000970,bootstrap masonry add blank divs when grid have empty spaces at the bottom i am using masonry bootstrap and notice that when i have a 3column grid then i have 10 items it would thisplay a 3x4 grid having 2 blank spaces at the bottom how could i automatically add 2 empty divs at the bottom just to fill it up and not having those blank spaces so the total div would become 12 wherein the 2 divs are just blankthis is not supposed to be fixed to a 3column but should dynamically add empty divs whenever it detected that there are and number of empty divs that could be filled up should be applicable on load and on resizethere will be no problem with the item size since they will all have the same width and height boxsquare typei made a jsfiddle that could now add fillers on the empty spaces on the last row this is working on the on resize as well by using the layoutcomplete event but the problem is whenever i resize it keeps on appending new fillerstry resizing to different sizes and youll notice it keeps on adding fillersin case heres the code as wellhtmlinput typehidden namehftotalgriditems idhftotalgriditems value10 div classgrid div classitem divloremdiv div div classitem divloremdiv div div classitem divloremdiv div div classitem divloremdiv div div classitem divloremdiv div div classitem divloremdiv div div classitem divloremdiv div div classitem divloremdiv div div classitem divloremdiv div div classitem divloremdiv divdivdiv classresultdivcssgrid margin 0 autoitem marginbottom 20px border 1px solid red height 80px width 80px filler backgroundcolor 9 border 1px solid bluejqueryfunction function calculaterows var lisinrow 0 var item grid item var grid grid var itemwidth grid itemwidth var itemheight grid itemheight itemeachfunction if thisprevlength 0 if thispositiontop thisprevpositiontop return false lisinrow else lisinrow var lisinlastrow itemlength lisinrow if lisinlastrow 0 lisinlastrow lisinrow resulthtmlno of lis in a row lisinrow br no of lis in last row lisinlastrow if lisinlastrow lisinrow var cloneditem grid itemlastchildcloneemptycss width itemwidth height itemheight addclassfiller gridappendcloneditemmasonryappended cloneditem else if newtotal hftotalgriditemsval gridmasonryremove grid itemfiller gridmasonry var grid grid gridmasonry itemselector item isfitwidth true gutter 20 gridmasonryon layoutcomplete function event calculaterowseventlength gridmasonry,"['javascript', 'jquery', 'html', 'css']" +1001096,how to verify aspnet mvc outputcache works on server i am fixing a bug with aspnet outputcache and it is driving me insanewe want caching on the server but it does not appear to work it did a while ago in an older version of our app but we thiscovered the bug by accident recentlylocally i just cannot get the caching to work on the serverside using this attributeoutputcachecacheprofile myprofile location outputcachelocationserver does not worknow based on a few things i have read by googling around here is possibly relevant informationoutput caching is enabled in iis localhosti do use an authorizeattribute a custom one with inheritance i have debugged towards this specifically and i am 95 confident this is not the causei have fiddled around with various varybyparams values nothing workscaching does work clientsidei have opened a perfmon session and added some counters from the web service cache group all i see is that there are cached urls but the cache is missedthe bigger problembug were facing now is that outputcache is not working at all right now we were able to fix that by specifying varybyparams an empty string that did it for the client but it does not work serverside yeti am actually checking whether it works or not by placing a debug breakpoint in the action that should be cached it gets hit everytime which should mean the cache is not hit,['asp.net'] +1001250,align two uilabel texts i would like to align the start of the text of two uilabels i aligned the two uilabels with the yellow and grey background and used sizetofit to shrink the uilabels to the content but the text is not perfectly left aligned there is a gap on the left the gap is bigger or smaller depending on the first character i would like to align the red lines in the following picture there is even a small gap with the small font in the grey uilabel but it is barely visiblewith the z character the gap is smaller but still visible by the yellow area left to the za simple uilabel alignment does not help for my specific problem because the text content is dynamic and not static so there could be any combination depending on the data i get from the backend therefore i was hoping for a uifont or uilabel attribute that could return the size of the gap based on the current rendering of the texti know that there are great uifont related attributes like baseline capheight and ascender one can access to align text but there seems to be no attribute that would return the value of this gap on the left,['ios'] +1001324,ios 9 keyup event not firing is anybody else having problems with the keyup event in ios 9 not firingjust a simple test bed replicates the issue for meinput idtxtinput vanilla jsdocumentgetelementbyidtxtinputonkeyup function consolelogkeyup triggeredjquerytxtinputonkeyup function consolelogkeyup triggeredneither fire,"['javascript', 'jquery']" +1001332,how to create a retrofitresponse object during unit testing with retrofit 2 while using rxjava and retrofit 2 i am trying to create unit tests to cover when my app receives specific responsesthe issue i have is that with retrofit 2 i cannot see a nice way of creating a retrofitresponse object without the use of reflectiontestpublic void testlogin throwsloginbadrequestexceptionwhen403error requestbuilder requestbuilder new requestbuilder requestbuilderget requestbuilderurlhttplocalhost responsebuilder responsebuilder new responsebuilder responsebuildercode403 responsebuilderprotocolprotocolhttp 1 1 responsebuilderbodyresponsebodycreatemediatypeparseapplicationjson keysomestuff responsebuilderrequestrequestbuilderbuild retrofitresponseloginresponse aresponse null try constructorretrofitresponse constructor constructorretrofitresponse retrofitresponseclassgetdeclaredconstructors0 constructorsetaccessibletrue aresponse constructornewinstanceresponsebuilderbuild null null catch exception ex reflection error doreturnobservablejustaresponsewhenmockloginapiloginanyobject testsubscriber testsubscriber new testsubscriber loginapiserviceloginloginrequestsubscribetestsubscriber throwable resulterror throwable testsubscribergetonerroreventsget0 asserttrueresulterror instanceof loginbadrequestexceptioni have tried using the following but this creates an okhttp response vs a retrofit response requestbuilder requestbuilder new requestbuilder requestbuilderget requestbuilderurlhttplocalhost responsebuilder responsebuilder new responsebuilder responsebuildercode403 responsebuilderprotocolprotocolhttp 1 1,['android'] +1001337,how to thisable special naming convention inspection of pep 8 in pycharm i installed pycharm and enabled pep8 checks in inspectionsif i write such function def funcargone printargonethe ide shows me this warning argument name should be lowercasebut there is no option to ignore only such inspectioni cant find such error number to ignore herehere are all the naming inspectionshow to ignore only some of themwhy i need thisthe current project coding guidelines must be keptit s too hard to change the guidelines of the whole projectwhat exactly i wanti need to thisable only some naming inspections not all like by settings editor inspectionspep8 coding style violationeg class names should be still inspected with pep8 and function argument names not,['python'] +1001378,simple stdregex search code would not compile with apple clang stdc14 here is the mcveinclude iostreaminclude regexstdstring s return testint main static const stdregex regexrw stdsmatch smatch if stdregex searchs smatch regex stdcout smatch0 stdendl return 0it compiles fine with clang stdc11 maincppbut not with clang stdc14 maincpperror message in the later case with stdc14maincpp149 error call to deleted function regex search if stdregex searchs smatch regex applicationsxcodeappcontentsdevelopertoolchainsxcodedefaultxctoolchainusrbinincludecv1regex59981 note candidate function with st std 1char traitschar sa std 1allocatorchar ap std 1allocatorstd 1sub matchstd 1 wrap iterconst char cp char tp std 1regex traitschar has been explicitly deletedregex searchconst basic string cp st sa sapplicationsxcodeappcontentsdevelopertoolchainsxcodedefaultxctoolchainusrbinincludecv1regex28765 note candidate function with st std 1char traitschar sa std 1allocatorchar ap std 1allocatorstd 1sub matchstd 1 wrap iterconst char cp char tp std 1regex traitschar regex searchconst basic string cp st sa s applicationsxcodeappcontentsdevelopertoolchainsxcodedefaultxctoolchainusrbinincludecv1regex28515 note candidate template ignored deduced conflicting types for parameter bp std 1basic stringchar vs std 1match resultsstd 1 wrap iterconst char std 1allocatorstd 1sub matchstd 1 wrap iterconst char regex search bp bp const basic regex cp tp applicationsxcodeappcontentsdevelopertoolchainsxcodedefaultxctoolchainusrbinincludecv1regex28575 note candidate template ignored could not match const cp against stdstring aka basic stringchar char traitschar allocatorchar regex searchconst cp const cp applicationsxcodeappcontentsdevelopertoolchainsxcodedefaultxctoolchainusrbinincludecv1regex28635 note candidate template ignored could not match const cp against stdstring aka basic stringchar char traitschar allocatorchar regex searchconst cp match resultsconst cp ap const basic regex cp tp applicationsxcodeappcontentsdevelopertoolchainsxcodedefaultxctoolchainusrbinincludecv1regex28695 note candidate template ignored could not match basic regex against match results regex searchconst basic string cp st sa s applicationsxcodeappcontentsdevelopertoolchainsxcodedefaultxctoolchainusrbinincludecv1regex59631 note candidate template ignored could not match const chart against stdstring aka basic stringchar char traitschar allocatorchar regex searchconst chart str const basic regex chart traits eapplicationsxcodeappcontentsdevelopertoolchainsxcodedefaultxctoolchainusrbinincludecv1regex28395 note candidate function template not viable requires at least 4 arguments but 3 were provided regex search bp bp match results bp ap const basic regex cp tp applicationsxcodeappcontentsdevelopertoolchainsxcodedefaultxctoolchainusrbinincludecv1regex28455 note candidate function template not viable requires at least 4 arguments but 3 were provided regex searchconst cp const cp match resultsconst cp ap applicationsxcodeappcontentsdevelopertoolchainsxcodedefaultxctoolchainusrbinincludecv1regex28845 note candidate function template not viable requires at least 4 arguments but 3 were provided regex search wrap iter iter first 1 error generatedcompiler version information clang vapple llvm version 700 clang7072target x86 64appledarwin1500thread model posixso whats wrong,['c++'] +1001746,recursively concat colums in sql i have a table containing values as followsa b a l1 a l2 a l3 a l4 aa a a a b1 a c1 a d1 a e1 aa d a x1 a y1 a null a null athe output should be a ab1c1d1e1 aa ab1c1d1 aa ab1c1 aa ab1 aa dx1y1 aa dx1 ais it possible i see a pattern here but able to figure it out how to do itps rollup cannot be used as the server does not support itthanks a ton,"['mysql', 'sql']" +1001765,hibernate jta read db connection parameters per environment i am writing a javaee application using hibernate the application will be running on multiple environments dev qa prod etc will have separate dbss associated with each of them i would like to set the hibernate properties like jdbcurl username password etc separately for each of these environmentsmy current persistencexml looks like persistenceunit namepu transactiontypejta providerorghibernateejbhibernatepersistenceprovider validationmodecallbackvalidationmode properties property namehibernatedialect valueorghibernatedialectoracledialect property namehibernatehbm2ddlauto valuevalidate property namehibernatetempuse jdbc metadata defaults valuefalse property namehibernateeventmergeentity copy observer valueallow property namehibernateconnectiondriver class valueoraclejdbcoracledriver property namehibernateconnectionurl valuejdbcoraclethinhostschema property namehibernateconnectionusername valueabc property namehibernateconnectionpassword value properties persistenceuniti am using the persistence unit as follows in my java codepersistencecontextunitname puprivate entitymanager em is there a way that i can inject the hibernate properties which are stored in separate properties files into entitymanager for different environments please note that i am using jta and hence cannot use entitymanagerfactory also i am not do not want to use spring,['java'] +1001995,how to handle system alert window permission not being autogranted on some premarshmallow devices i have been getting reports of some xiaomi devices eg mi 2 running api level 21 not showing overlays my app targets api 23there are several posts out there regarding this it seems that miui devices do not enable this permission at install time unlike other premarshmallow devicesunfortunately settingscandrawoverlays only works on android 23what is the correct way to check whether this permission has not yet been enabled premarshmallowis there an intent to take the user to the relevant muiu settings page maybe new intentandroidsettingsactionmanage overlay permission packagename but i have no means to test this,['android'] +1002012,sfsafariviewcontroller status bar style my apps statusbar style is uistatusbarstylelightcontent and it is set in my rootviewcontroller as preferredstatusbarstylenow i have a problem that when opening sfsafariviewcontroller from within my app it has inherited statusbar style that is light and invisible on the white background of sfsafariviewcontrolleris there a way to set statusbar style for sfsafariviewcontrollerps i tried to subclass sfsafariviewcontroller and override this method but it does not help uistatusbarstylepreferredstatusbarstyle return uistatusbarstyledefaultupdateuiapplication sharedapplication setstatusbarstyle does the trick but this method is deprecated in ios 9,"['objective-c', 'iphone']" +1002366,no search results while publish and subscribe from single collection im using easysearch package and would like to search posts or comments to those posts the problem nothing gets shown when search is typed in no error messages shown on both consolelog and server updates i did consolelog on both the publish and subscribe so the subscribe returns the consolelog on the browser devtools but the publish does not return anything on the server terminal template html template namesearchposts esinput idmain indexindexes placeholdersearch eseach indexposts postitem eseach eseach indexcomments postitem eseachtemplatetemplate js client templatesearchpostsoncreatedfunction var self this instance instance easysearchgetcomponentinstance id main index posts id main index comments instanceonsearchingdone function searchingisdone searchingisdone consolelogi am done instanceoncurrentvalue function val consolelogthe user searches for val thissubscribealldocs templatesearchpostshelpers indexes function return posts comments posts function return postsfind,['javascript'] +1002485,changing property contentsgravity in transformonly layer will have no effect i started to create a very simple tictactoe gamethe main goal is to make the view proportional to all screen sizes of all ios devicesso i put the image on a viewcontroller make it full size of screen and then i put it into a stack view i have added constrains to this stack view 0 to all sidesand when i ran the simulator then everything looks good but i receive a message in console panel what does it mean screenshot,['ios'] +1002509,make one iap valid for different applications until now i thistributed my app on the play store with an inapp purchase to thisable adsi am redesigning the whole app and i would like to split it into two applications one for mobile devices like the original and one for android tv devices so i was thinking about releasing these two versions as two new apps and transforming the actual app into something like a purchase manager i want users who already paid to remove ads in the mobile version to not pay in order to remove ads in the tv one there are ways to check if an app was not installed from play store andor it has been tampered eg using apktoolsit is also possible to create a paid app as key for the other apps i was thinking to create three applicationspm the purchase manager will replace the actual appmb the mobile version of my apptv the tv version of my appall the three applications will be signed with the same key and will include tampering detection pm will have an exposed activitya that can be used by mb or tv to check if the user has purchased the remove ads featurebut i have two concernsis this design safe or can it be someway exploitedis there a more elegant way besides uploading multiple apks to do thisedit1there are two main reasons why i am splitting my appmy application currently supports api level 9 by adding leanback library i should increase the minimum sdk to level 17i do not want one large apk with both images and layouts for tv and mobile versions,['android'] +1002521,what the usefulness about java generics involving inheritance and generics extends self i find the generics whose generics params extends itselfhere i do not understand that welli suspect that it is wrong at the beginning but no one put forward i have some questions about thishow to use the variant generics can you give me a example what the benefit or effect of this generics stylehere is the generics style code which is picked from here abstract class baset extends baset class variantt extends variantt extends baset thanksi14,['java'] +1002597,all vagrant php cli scripts hang waiting on host resolution on mac os x i have been getting hangs when executing php commands on my homestead vagrant box running ubuntu there is a significant lag before the console even starts the php cli executionran strace vyt s time php artisan help from vagrant box everything gets stuck for several minutes on the first to last call to recvfrom3 but i have no idea whyopenetcresolvconf o rdonlyo cloexec 3 010fstat3runresolvconfresolvconf st devmakedev0 16 st ino7632 st modes ifreg0644 st nlink1 st uid0 st gid0 st blksize4096 st blocks8 st size171 st atime20151017045356 st mtime20151017045354 st ctime20151017045354 0 07mmapnull 4096 prot readprot write map privatemap anonymous 1 0 0x7fed9385c0 08read3runresolvconfresolvconf dynamic resolvconf5 file fo 4096 171 010read3runresolvconfresolvconf 4096 0 06close3runresolvconfresolvconf 0 08munmap0x7fed9385c0 4096 0 011unamesysnamelinux nodenamehomestead release313065generic version106ubuntu smp fri oct 2 220827 utc 2015 machinex86 64 domainnamenone 0 06statetcresolvconf st devmakedev0 16 st ino7632 st modes ifreg0644 st nlink1 st uid0 st gid0 st blksize4096 st blocks8 st size171 st atime20151017045356 st mtime20151017045354 st ctime20151017045354 0 08openetchosts o rdonlyo cloexec 3 09fstat3etchosts st devmakedev8 1 st ino1161 st modes ifreg0644 st nlink1 st uid0 st gid0 st blksize4096 st blocks8 st size251 st atime20151016185729 st mtime20141003011642 st ctime20141003011642 0 05mmapnull 4096 prot readprot write map privatemap anonymous 1 0 0x7fed9385c0 08read3etchosts 127001 localhostnn the follo 4096 251 09read3etchosts 4096 0 07close3etchosts 0 07munmap0x7fed9385c0 4096 0 010socketpf inet sock stream ipproto ip 3 012fcntl3socket78362 f setfl o rdonlyo nonblock 0 06connect3 sa familyaf inet sin porthtons90 sin addrinet addr127001 16 1 einprogress operation now in progress 094select4 3socket78362 3socket78362 3socket78362 0 20 1 out 3 left 0 197 010getpeername3 sa familyaf inet sin porthtons90 sin addrinet addr127001 16 0 07fcntl3socket78362 f setfl o rdonly 0 06setsockopt3 sol tcp tcp nodelay 10 8 0 08write3socket78362 4780xml version10 encoding 483 483 042brk0x2f930 0x2f930 0472recvfrom3 0x7ffc489b16d0 128 0 0 0 erestartsys to be restarted if sa restart is set 4940291 sigwinch si signosigwinch si codesi kernel recvfrom3 0x7ffc489b16d0 128 0 0 0 erestartsys to be restarted if sa restart is set 0072574 sigwinch si signosigwinch si codesi kernel recvfrom3 0x7ffc489b16d0 128 0 0 0 erestartsys to be restarted if sa restart is set 0033758 sigwinch si signosigwinch si codesi kernel recvfrom3 0x7ffc489b16d0 128 0 0 0 erestartsys to be restarted if sa restart is set 0038904 sigwinch si signosigwinch si codesi kernel recvfrom3 0x7ffc489b16d0 128 0 0 0 erestartsys to be restarted if sa restart is set 0026003 sigwinch si signosigwinch si codesi kernel recvfrom3 0x7ffc489b16d0 128 0 0 0 erestartsys to be restarted if sa restart is set 0024057 sigwinch si signosigwinch si codesi kernel recvfrom3 0x7ffc489b16d0 128 0 0 0 erestartsys to be restarted if sa restart is set 0055221 sigwinch si signosigwinch si codesi kernel recvfrom3 0x7ffc489b16d0 128 0 0 0 erestartsys to be restarted if sa restart is set 0058240 sigwinch si signosigwinch si codesi kernel recvfrom3 0x7ffc489b16d0 128 0 0 0 erestartsys to be restarted if sa restart is set 0027569 sigwinch si signosigwinch si codesi kernel recvfrom3 0x7ffc489b16d0 128 0 0 0 erestartsys to be restarted if sa restart is set 0056877 sigwinch si signosigwinch si codesi kernel recvfrom3 0x7ffc489b16d0 128 0 0 0 erestartsys to be restarted if sa restart is set 0025934 sigwinch si signosigwinch si codesi kernel recvfrom3 0x7ffc489b16d0 128 0 0 0 erestartsys to be restarted if sa restart is set 0076699 sigwinch si signosigwinch si codesi kernel recvfrom3 0x7ffc489b16d0 128 0 0 0 erestartsys to be restarted if sa restart is set 0089092 sigwinch si signosigwinch si codesi kernel recvfrom3 0x7ffc489b16d0 128 0 0 0 erestartsys to be restarted if sa restart is set 0254680 sigwinch si signosigwinch si codesi kernel recvfrom3 0x7ffc489b16d0 128 0 0 0 erestartsys to be restarted if sa restart is set 0131634 sigwinch si signosigwinch si codesi kernel recvfrom3 0x7ffc489b16d0 128 0 0 0 erestartsys to be restarted if sa restart is set 0065721 sigwinch si signosigwinch si codesi kernel recvfrom3 0x7ffc489b16d0 128 0 0 0 erestartsys to be restarted if sa restart is set 0042778 sigwinch si signosigwinch si codesi kernel recvfrom3 0x7ffc489b16d0 128 0 0 0 erestartsys to be restarted if sa restart is set 0072277 sigwinch si signosigwinch si codesi kernel recvfrom3 0x7ffc489b16d0 128 0 0 0 erestartsys to be restarted if sa restart is set 00424 sigwinch si signosigwinch si codesi kernel recvfrom3 0x7ffc489b16d0 128 0 0 0 erestartsys to be restarted if sa restart is set 0080704 sigwinch si signosigwinch si codesi kernel recvfrom3 0x7ffc489b16d0 128 0 0 0 1 econnreset connection reset by peer 113721here is the contents of etchosts127001 localhost the following lines are desirable for ipv6 capable hosts1 ip6localhost ip6loopbackfe0 ip6localnetff0 ip6mcastprefixff021 ip6allnodesff022 ip6allroutersff023 ip6allhosts127011 homestead homesteadthe contents of etcresolveconf dynamic resolvconf5 file for glibc resolver3 generated by resolvconf8 do not edit this file by hand your changes will be overwrittennameserver 10023the problem is now affecting every unrelated vagrant box i have not just the homestead box almost every php command on each box is stalled by 515 minutes for each cli execution if a chain of commands must be called it can take an hour to finish a process that should take 30 secondsthis started after the mac these boxes are run on was upgraded to el capitandepending on the vagrant box sometimes this strace lineconnect3 sa familyaf inet sin porthtons90 sin addrinet addr127001 16 0is replaced byconnect3 sa familyaf inet sin porthtons90 sin addrinet addr192168561 16 0the ip 192168561 appears to be the default router for virtualboxplease note all vagrant boxes are either standard config or those that work without issue on my other team members macwindows systemsvagrant 174 and virtualbox 4330in response to request route nkernel ip routing tabledestination gateway genmask flags metric ref use iface0 10022 0 ug 0 0 0 eth010020 0 2552552550 you 0 0 0 eth0192168100 0 2552552550 you 0 0 0 eth1results for sudo netstat tulnp grep 90tcp6 0 0 90 listen 1317hhvmwhy hhvm is showing up i do not know because the box is supposed to be using the standard php interpreter,['php'] +1002643,most efficient way to parse every fourth line from a very large file i have a file of the following format1 some basic info in this line2 lots of info in this line hundreds of chars3 some basic info in this line4 lots of info in this line hundreds of charsthat format repeats itself tens of thousands of times making files up to 50 gib i need an efficient way to process the only the line 2 of this format i am open to using c c11 stl or boost i have looked at various other questions regarding file streaming on so but i feel like my situation is unique because of the large file size and only needing one out of every four linesmemory mapping the file seems to be the most efficient from what i have read but mapping a 50 gb file will eat up most computers ram you can assume that this application will be used by average users say 48 gib ram also i will only need to process one of the lines at a time here is how i am currently doing this yes i am aware this is not efficient that is why i am redesigning itstdstring glgetreadifstream input stdstring str stdstring toss if inputgood getlineinput toss getlineinput str getlineinput toss getlineinput toss return stris breaking the mmap into blocks the answer for my situation is there anyway that i can leverage only needing 1 out of 4 lines thanks for the help,['c++'] +1002651,js how to track errors where there are many functions calls every function create new error object so how i can get the preivous errorsfor example this is my codefunction maincallback afunctionerr if err callbacknew errorcannot run main function return function acallback bfunctionerr if err callbacknew errorcannot run b function return function bcallback if 1 2 callbacknew errorerror in b functionwhen i run this i get only the last error cannot run main function but i want to get all the previous errors do you have any best practive for thatwhat i am doing is thisiferr errnew errorcannot run this functionr errmessagei am asking of you know about any other library or better way for doing that something that extend the error objectsomething likeerrpushnew error,['javascript'] +1003027,wcsession sendmessagereplyhandler error code 7014 wcerrorcodedeliveryfailed i have a watch os 2 application that communicates with the ios app via wcsession method sendmessagereplyhandlererrorhandlerthe ios application reply correctly but time to time i get the error with code 7014 of domain wcerrordomain payload could not be deliveredit happens more often when the ios application is not foregroundi do not find any solution of this problem i hope one of you know a solution to this problem,['ios'] +1003093,why does adding two string literals not use operatorconst string const string edit i have reformatted the post to be clearer why does this workstruct a struct b bavoid operatorconst b const b int main a a1 a2 a1 a2and this does notstruct b bconst charvoid operatorconst b const b error invalid operands of types const char 6 and const char 6 to binary operatorint main hello worldessentially in the first example a1 and a2 both convert to b objects through the implicit conversion and use the operatorconst b const b to add following from this example i would have expected hello and world to convert to b objects again through the implicit constructor and use operatorconst b const b to add to each other instead there is an error which indicates the cstyle strings do not attempt a userdefined conversion to b in order to add why is this is there a fundamental property that prevents this,['c++'] +1003201,how to detect a laser line in an image using python whats the quickest most reliable method of detecting a roughly horizontal red laser line in an image using python i am working on a small project related to 3d laser scanning and i need to be able to detect the laser in an image in order to calculate thistance from its thistortionto start i have two images a reference image a known to contain no laser line and an image b that definitely contains a laser line possibly thistorted egsample image asample image bsince these are rgb but the laser is red i remove some noise by stripping out the blue and green channels using this functionfrom pil import imageimport numpy as npdef only redim strips out everything except red data nparrayim red green blue alpha datat im2 imagefromarrayredt return im2that gets me these imagesnext i try and eliminate more noise by taking the difference of these two images using pilimagechopsdifference ideally the exposure between the two images would be identical causing the difference to contain nothing except the laser line unfortunately because the laser adds light the exposure and overall brightness of each image is significantly different resulting in a difference that still has considerable noise egmy final step is to make a best guess as to where the line is since i know the line will be roughly horizontal and the laser line should be the brightest thing in the image i scan each column and find the row with the brightest pixel which i assume to be the laser line the code for this isimport osfrom pil import image imageopsimport numpy as npx imageopenlaserdiffpng rx xconvertlout imagenewl xsize blackpix outloady npasarrayxgetdata dtypenpfloat64reshapexsize1 xsize0print yshapefor col i in xrangeyshape1 col max maxyrow icol i row i for row i in xrangeyshape0 col max brightness col max row col max print col i col max pixcol i col max row 255outsavelaserlinepngall i really need to perform my thistance calculation is the array of col max values but the laserlinepng helps me visualize the success and looks likeas you can see the estimate is pretty close but it still has some noise mostly on the lefthand side of the image where the laser line is absorbed by a matte black finishwhat can i do to improve my accuracy andor speed i am trying to run this on an arm platform like the raspberry pi so i am worried my code might to be too inefficient to run welli am not fully familiar with numpys matrix functions so i had to settle for a slow for loop to scan each column instead of something more efficient is there a fast way to find the row with the brightest pixel per column in numpyalso is there a reliable way to equalize the images prior to performing the difference without dimming the laser line,['python'] +1003452,menu burger animation toggle full page menu basically i need a menu burger that toggles on and off a full page menu but i cannot get the coding to work together so i created both the menu burger animation toggle and the full page menu separately which work fine now i dont know how to put them together i have tried for ages but cannot seem to make it work can anyone help pleasehere are the links to the codes1 menu burger fiddle cssbody padding 0pxborder position fixed background f9f8f3top bottom left 0 right 0 height 50pxtop top 0bottom bottom 0right left top 0 bottom 0 width 50pxright right 0left left 0 end of body border nav chamburger thisplay block position fixed left 0px bottom 0px overflow hidden margin 0 padding 0 width 50px height 50px fontsize 0 textindent 9px webkitappearance none mozappearance none appearance none boxshadow none borderradius none border none cursor pointer webkittransition background 03s transition background 03schamburgerfocus outline nonechamburger span thisplay block position absolute top 25px left 12px right 12px height 2px background 262626chamburger spanbeforechamburger spanafter position absolute thisplay block left 0 width 100 height 2px backgroundcolor 262626 content chamburger spanbefore top 7pxchamburger spanafter bottom 7pxchamburgerhtx backgroundcolor f9f8f3chamburgerhtx span webkittransition background 0s 03s transition background 0s 03schamburgerhtx spanbeforechamburgerhtx spanafter webkittransitionduration 03s 03s transitionduration 03s 03s webkittransitiondelay 03s 0s transitiondelay 03s 0schamburgerhtx spanbefore webkittransitionproperty top webkittransform transitionproperty top transformchamburgerhtx spanafter webkittransitionproperty bottom webkittransform transitionproperty bottom transform active state ie menu open chamburgerhtxisactive backgroundcolor fafd37chamburgerhtxisactive span background nonechamburgerhtxisactive spanbefore top 0 webkittransform rotate45deg mstransform rotate45deg transform rotate45degchamburgerhtxisactive spanafter bottom 0 webkittransform rotate45deg mstransform rotate45deg transform rotate45degchamburgerhtxisactive spanbeforechamburgerhtxisactive spanafter webkittransitiondelay 0s 03s transitiondelay 0s 03s2 full page menu fiddle cssul li liststyle noneyellowmenu background fafd37 fontsize 2em textalign center position absolute left 0 top 0 right 0 bottom 0 paddingtop 16yellowmenu a color black textdecoration none width 100 height 2em thisplay block lineheight 21 fontfamily ff super grotesk fontweight normal fontstyle normal transition backgroundcolor 2s easeyellowmenu ahover color e0e0d4 background rgba18218215707,"['jquery', 'html', 'css']" +1003491,sending email via spring boot springbootstartermail i am trying to send emails using spring boot but am gettingjavalangunsupportedoperationexception method not yet implemented at javaxmailinternetmimemessageinitmimemessagejava89 at orgspringframeworkmailjavamailsmartmimemessageinitsmartmimemessagejava52 at orgspringframeworkmailjavamailjavamailsenderimplcreatemimemessagejavamailsenderimpljava325i have used this maven entry parent groupidorgspringframeworkbootgroupid artifactidspringbootstarterparentartifactid version126releaseversion parentdependency groupidorgspringframeworkbootgroupid artifactidspringbootstarterwebartifactid version126releaseversion dependency dependency groupidorgspringframeworkbootgroupid artifactidspringbootstartermailartifactid version126releaseversion dependencyapplicationpropertiesspringmailhostsmtpgmailcomspringmailport 25springmailusername testspringmailpassword testand my codeautowired private javamailsender javamailsenderprivate void send mimemessage mail javamailsendercreatemimemessage try mimemessagehelper helper new mimemessagehelpermail true helpersetto helpersetreplytosomeonelocalhost helpersetfromsomeonelocalhost helpersetsubjectlorem ipsum helpersettextlorem ipsum dolor sit amet catch messagingexception e eprintstacktrace finally javamailsendersendmail return helper this appears to be a straight forward but do not what am i missing,['java'] +1003542,scroll position would not reset when go to other page after pressing back button i am having a problem with scrolling in angularjs appat the moment it has 2 pages the first page is a list of customers you can select one of them and see it is details the second one is a list of companies it works in the same wayi am using a panel to navigate between them using locationpath and the app also has a back button using windowhistorybackwhen you select one of the items in customers or companies list and after it when you pressed the button back youre returned to the previous pagecustomers or companies list with restoring the scroll position i am using standard windowhistoryback feature not implemented anything custombut here is where the problem occurs if without scrolling in any direction simply go to another pageto other list of items scroll position would not reset but if you scroll it even just a little bit it is position will reset also if you do not use the back button everything works fineso the question is how can we reset scroll position when go to another page after using windowhistorybacki am also using infinitescroll plugin if it matters but even when i turned it off nothing changed so i guess the problem is not with the plugin,['javascript'] +1003563,make custom html elements droppable in iframe i like to have a list which elements can be dropped in a list in an iframe similar to this example i found a working solution via this thread but in my case i need other elements than lisheres my setupdiv idcontainer ul lito drop 1li lito drop 2li uldiviframe idframe srciframeand the iframe contentul idsortable lielementli lielementli lielementliulthis works as you can see hereit even works when changing the ul and lis to div example and iframewhen i use custom tags it is working with foo and bar tags but what i really need is to get it working with modules and module tagsfoo idsortable works barelementbar barelementbar barelementbarfoomodules idsortable does not work moduleelementmodule moduleelementmodule moduleelementmodulemodulesheres the fiddle and the iframe of what i actually need to workso basically the draggable and sortable method is not working with my custom html tags whats so different between foo bar and modules moduleupdateit seems this is an issue on webkit browsers only since it is working fine on ff was not able to test on a windows machine yetwhen dragging the element it will create a helper which gets some inline stylepositionabsoluteleftxpxrightxpxwidthxpxheightxpxzindex10while on webkits it only get position left and rightpositionabsoluteleftxpxrightxpx,"['jquery', 'html']" +1003619,gem install rmagick fails on os x el capitan i upgraded to el capitan a couple of days ago and ran abrew update brew upgradeit updated imagemagick which caused rubys rmagick gem to stop workingno problem i thought i will just rungem install rmagickand it will recompileexcept it did not when i run it i see thisgem install rmagickbuilding native extensions this could take a whileerror error installing rmagick error failed to build gem native extension userssamrbenvversions223binruby r siteconf201510195734730ju1wrb extconfrbchecking for clang yeschecking for magickconfig yeschecking for outdated imagemagick version 649 nochecking for ruby version 185 yeschecking for stdinth extconfrb failed could not create makefile due to some reason probably lack of necessarylibraries andor headers check the mkmflog file for more details you mayneed configuration optionsprovided configuration options withoptdir withoutoptdir withoptinclude withoutoptincludeoptdirinclude withoptlib withoutoptliboptdirlib withmakeprog withoutmakeprog srcdir curdir rubyuserssamrbenvversions223binruby base nameuserssamrbenvversions223libruby220mkmfrb456in try do the compiler failed to generate an executable file runtimeerroryou have to install development tools first from userssamrbenvversions223libruby220mkmfrb587in try cpp from userssamrbenvversions223libruby220mkmfrb1060in block in have header from userssamrbenvversions223libruby220mkmfrb911in block in checking for from userssamrbenvversions223libruby220mkmfrb351in block 2 levels in postpone from userssamrbenvversions223libruby220mkmfrb321in open from userssamrbenvversions223libruby220mkmfrb351in block in postpone from userssamrbenvversions223libruby220mkmfrb321in open from userssamrbenvversions223libruby220mkmfrb347in postpone from userssamrbenvversions223libruby220mkmfrb910in checking for from userssamrbenvversions223libruby220mkmfrb1059in have header from extconfrb38in configure headers from extconfrb18in initialize from extconfrb517in new from extconfrb517in mainextconf failed exit code 1gem files will remain installed in userssamrbenvversions223librubygems220gemsrmagick2154 for inspectionresults logged to userssamrbenvversions223librubygems220extensionsx86 64darwin14220staticrmagick2154gem makeouthere is the contents of mkmflogfind executable checking for clang yesfind executable checking for magickconfig yesconfigure compile options checking for outdated imagemagick version 649 nodetected imagemagick version 692assert minimum ruby version checking for ruby version 185 yesclang o conftest iuserssamrbenvversions223includeruby220x86 64darwin14 iuserssamrbenvversions223includeruby220rubybackward iuserssamrbenvversions223includeruby220 i dmagickcore hdri enable0 dmagickcore quantum depth16 dmagickcore hdri enable0 dmagickcore quantum depth16 conftestc l luserssamrbenvversions223lib lusrlocalcellarimagemagick6924lib lmagickcore6q16 lusrlocalcellarimagemagick6924lib lmagickcore6q16 lrubystatic framework corefoundation lpthread lgmp ldl lobjc ld library not found for lgmpclang error linker command failed with exit code 1 use v to see invocationchecked program was begin 1 include rubyh23 int mainint argc char argv4 5 return 06 end any ideas,['ruby'] +1003626,multiple onetomany relations to one entity once upon a time in the dark abyss somewere deep in the lands of symfony there was a frustrated programmer he tried and tried but somehow the evil doctrine striked again and again also the villains joins associative tables and onetomanymanytoone were giving him a hard time then on a late afternoon stackoverflow and it is community came to the rescueenough fairytales my problem is that i have three tables that should all refer to the same table to get attachments mail order ticketeach of these three entities can have attachments so i made an attachment entitynow my database contains the followingtable mails id from to messagetable attachments id name pathtable orders id table tickets id name description table attachment associations id type parent id attachment idwhat i wold like to do is to be able to map orders tickets and mails to the same attachments tablehowever i am stuck on how to do this in doctrineupdatei tried using the following method this does seem to get the record i am looking for but i do not know how to automatically create update or delete the record in the associative table join table using this method ormmanytomanytargetentityentityattachment ormjointablenameattachment associations joincolumnsormjoincolumnnameparentid referencedcolumnnameid inversejoincolumns ormjoincolumnnameattachmentid referencedcolumnnameid protected attachmentsanother updateif i delete a mail order or ticket will all corresponding attachments be deleted as well,['php'] +1004034,duplicate id idimage in appcompat v7 abc activity chooser viewxml58 while creating the apk i got the following error duplicate id idimage already defined earlier in this layout abc activity chooser viewxml58 in layout appcompat v7so i cleaned it still the same there is indeed duplicate id idimage in this file xml version10 encodingutf8view xmlnsandroidclassandroidsupportv7internalwidgetactivitychooserviewinnerlayoutandroidididactivity chooser view contentandroidlayout widthwrap contentandroidlayout heightmatch parentandroidlayout gravitycenterstyleattractivitychooserviewstyleframelayout androidididexpand activities button androidlayout widthwrap content androidlayout heightmatch parent androidlayout gravitycenter androidfocusabletrue androidaddstatesfromchildrentrue androidbackgroundattractionbaritembackground imageview androidididimage androidlayout width32dip androidlayout height32dip androidlayout gravitycenter androidlayout margintop2dip androidlayout marginbottom2dip androidlayout marginleft12dip androidlayout marginright12dip androidscaletypefitcenter androidadjustviewboundstrue framelayoutframelayout androidididdefault activity button androidlayout widthwrap content androidlayout heightmatch parent androidlayout gravitycenter androidfocusabletrue androidaddstatesfromchildrentrue androidbackgroundattractionbaritembackground imageview androidididimage androidlayout width32dip androidlayout height32dip androidlayout gravitycenter androidlayout margintop2dip androidlayout marginbottom2dip androidlayout marginleft12dip androidlayout marginright12dip androidscaletypefitcenter androidadjustviewboundstrue framelayoutviewany ideas of how to deal with this obviously i cannot just rename iti can skip checking it in lint but the error still persists and i do not think this is the best solution any more reliable solutions,['android'] +1004047,using nginx as a reverse proxy to iis server i have multiple aspnet applications running on a single iis server with different ports for each applicationi have installed nginx on the same server so that my clients can access all my applications only using port 80nginx is running all right on port 80 my individual aspnet applications are also up and runningi made these changes in nginx conf file location students proxy set header xrealip remote addr proxy set header xforwardedfor remote addr proxy set header host host proxy pass location registration proxy set header xrealip remote addr proxy set header xforwardedfor remote addr proxy set header host host proxy pass then i restarted nginx and typed the url in my browser nginx served a 404 pagei made no other changes to the conf filewhat i am doing wrong,['asp.net'] +1004065,is it possible to have static type assertions in pycharm def somepropertyself value type value int assert isinstancevalue int other stuffi would like pycharm to assert when the user sets the value to something other than an int i am already using a type hint is there another way to get this functionality thanks in advance for any insight you can provide,['python'] +1004221,frameworks detected in android studio frameworks detected android framework is detected in the project configurei get the above message when i try to build a particular project in android studio 14the project is blank and not able to run this project i searched for the solution and did not find any proper solutioni came across this answer but according to this in my case android support repository is already been installed in sdk manager this solution does not help meany help is appreciatedthanks,['android'] +1004330,uitableview example for swift i have been working with swift and ios for a number of months now i am familiar with many of the ways things are done but i am not good enough that i can just write things up without looking i have appreciated stack overflow in the past for providing quick answers to get me back on track with topics i have gotten rusty on for example asynctask android exampleioss uitableview is in this category for me i have done them a few times but i forget what the details are i could not find another question on stackoverflow that just asks for a basic example and i am looking for something shorter than many of the tutorials that are online although this one is very goodi am providing an answer below for my future reference and yours,['ios'] +1004394,crash in ios xpc api misuse we have a crash in our ios app reported by crashlyticscrashed xpc api misuse attempt to send a message expecting a reply to comapplenetworkingconnection0x46bf35a0the stack trace isthread crashed xpc api misuse attempt to send a message expecting a reply to comapplenetworkingconnection0x46bf35a00 libxpcdylib 0x35cc534a xpc api misuse 411 libsystem cdylib 0x35ba49e5 strlcpy chk 482 libxpcdylib 0x35cb5f75 xpc serializer create 1583 libxpcdylib 0x35cb5ea1 xpc connection send message 60it happened under ios 902 on a iphone 5 we are not able to reproduce the crash and we have no idea how to start debuggingfixing it seems that we are not alone with thismaybe somebody here has any ideas,"['ios', 'iphone']" +1004584,trailing slash triggers 404 in flask path rule i want to redirect any path under users to a static app the following view should capture these paths and serve the appropriate file it just prints the path for this example this works for users users604511 and users604511action why does the path users cause a 404 errorbprouteusersbprouteuserspathpathdef serve client apathnone return path,['python'] +1004619,nsurlsession with background session configuration is not returning an error when there is no connection when i set up nsurlsessionalamofiremanager with a background session configuration if there is no internet connection i am expecting to receive the usual nserror error domainnsurlerrordomain code1009 the internet connection appears to be offline this happened regularly if i am not using a background configuration but if i do such configuration my callbackdelegate method will never be called it will eventually be called when i activate the wifi again i would prefer to receive an error straight away am i missing something,['ios'] +1004659,thisable entire uimenucontroller edit menu in wkwebview requirementi have a wkwebview and would like to remove the system menu items copy define share from the edit menu and present my owni am targeting ios 8 and 9 i am currently testing with the xcode 701 simulator ios 9 and my iphone 6 running ios 902standard method does not worki know the standard way of achieving this is by subclassing wkwebview and implementing canperformactionwithsender however i have found that with wkwebview canperformactionwithsender is not being called for the copy or define actions this appears to be a known bug wkwebview and uimenucontrollerexample app implementation mywkwebview boolcanperformactionselaction withsenderidsender nslogaction nsstringfromselectoraction if action selectordelete adding delete as test works return yes trying to remove everything else does not work for copy define share return no voiddeleteidsender nslogdelete menu item selectedendoutput note no copy or define action20151020 122832864 wkwebviewcustomeditmenubug4580421121480 action cut20151020 122832865 wkwebviewcustomeditmenubug4580421121480 action select20151020 122832865 wkwebviewcustomeditmenubug4580421121480 action selectall20151020 122832865 wkwebviewcustomeditmenubug4580421121480 action paste20151020 122832866 wkwebviewcustomeditmenubug4580421121480 action delete20151020 122832866 wkwebviewcustomeditmenubug4580421121480 action promptforreplace20151020 122832866 wkwebviewcustomeditmenubug4580421121480 action transliteratechinese20151020 122832867 wkwebviewcustomeditmenubug4580421121480 action showtextstyleoptions20151020 122832907 wkwebviewcustomeditmenubug4580421121480 action addshortcut20151020 122832908 wkwebviewcustomeditmenubug4580421121480 action accessibilityspeak20151020 122832908 wkwebviewcustomeditmenubug4580421121480 action accessibilityspeaklanguageselection20151020 122832908 wkwebviewcustomeditmenubug4580421121480 action accessibilitypausespeaking20151020 122832909 wkwebviewcustomeditmenubug4580421121480 action maketextwritingdirectionrighttoleft20151020 122832909 wkwebviewcustomeditmenubug4580421121480 action maketextwritingdirectionlefttorightplanned workaroundmy desire now is to completely hide the edit menu and replace it with a custom menu using qbpopupmenumy problem is that i have not been able to find a way to hide or thisable the standard edit menu i have found some suggestions to hide it with uimenucontroller sharedmenucontrollermenuvisible no on uimenucontrollerwillshowmenunotification but i have not been able to get this to work it has no affect with willshowmenu i can hide it in didshowmenu but by that point it is too late and i get a menu flashi have also tried to locate it outside the visible area using uimenucontroller sharedmenucontroller settargetrectcgrectmake0 0 1 1 inviewselfextraview but again doing so with willshowmenu has no affect and with didshowmenu it is too lateexperiments available here what am i missing is there another way to thisable or hide the standard editting menu for wkwebview,['ios'] +1004670,can you calculate the password hash used by active directory we currently store users of our web application in our database along with hashessalts of their passwords the hashes are calculated when the user is created and sets their password and stored in a user table in a databasesome time after the creation of the user account we may want to create a windows account in our domain and want to be able to set the domain users password so that it is the same as the one the user uses to log into the web app since we do not save the plain text version of the password we do not have a way to send it to ad when we created itone way i was thinking about getting around this issue would be to calculate all the different password hashes that ad uses when the user first sets their password and then somehow set the records in ad later when we create the userhow would you create the hashes i think they are md4 md5 and des using netcan you bypass the password creation on userprincpalsetpassword and make some other call in order to directly set the hashes stored by adit seems like there should be a way to do this since ms has tools for syncing passwords from ad to azure users,['.net'] +1004861,invalid parent folder error for appfolder in drive api i get an invalid parent folder error and i have seen the solutions to use resource id rather than drive id but it is a different scenario herei am trying to access the appfolder and this just uses the googleapiclient like sothisappfolder drivedriveapigetappfoldermgoogleapiclientwhen i later try to create a file in it i get the above errordrivefolderdrivefileresult fileresult appfoldercreatefilemgoogleapiclient changeset drivecontentsresultgetdrivecontentsawaitthen fileresultgetstatus gives me the errosthis used to work for me before whats different is that i have manually emptied my apps data on google drive delete hidden app databut i have not thisconnected the app so i would assume that appfolder will continue to work the same wayso far the only workaround is uninstalling the app but this way i lose my datathis is reproducible please help,['android'] +1005175,is there an umbrella term to group the fromscratch constructors thistinguishing them from the copy and move constructors this one is a jargon questionthere are several umbrella terms to group logical operations in c for examplefor the destructor copymove assignment and constructors the copy control operationsis there one term for all constructors that create an object without copying or moving from another object of the same class,['c++'] +1005379,error compiling android project after updating findbugs to 301 after updating findbugs plugin up to 301 version i cannot compile multi module project in android studio also i use comgooglecodefindbugsannotations301 dependency for using findbugs annotations eg suppressfbwarningsi get following error while assembling project execution failed for task presentationpackagealldevelopdebugclassesformultidex javautilzipzipexception duplicate entry javaxannotationcheckfornullclasshow can i fix it,['android'] +1005384,are static locals of function template specializations with t required to be unique we use the intel c compiler and detected that it miscompiles the following reduced from a use of boostfunctionponies funnamednamespacedfunctora1cctemplatetypename tint ft static int x tx return x namespace struct a static const int x 1 int f1 return faa2cctemplatetypename tint ft static int x tx return x namespace struct a static const int x 0 int f2 return famainccinclude cstdioint f1int f2int main stdprintfd dn f1 f2 command line icpc a1cc a2cc maincc o main main0 0my question is is this compliant does using static locals in such instantiations produce undefined behavior when inspecting the produced symbols i noted that while f is has local linkage as i suspected the x static variable receives weak linkage and therefore the two xes are merged and it becomes lottery which is chosen icpc a2cc a1cc maincc o main main1 1i would be grateful for help perhaps this is actually a compilerbug after all and it has already been reported,['c++'] +1005400,using increment in ternary operator in c for the example after i useint a 5 b 6x a b a bx gets the value of a which is 5 and a increments to 6 which is expectedwhen i usea a b a bafter this line a still remains 5buta a b a ba is now 6why is this happening and why is not increment operator executed in the first caseedit just to clarify i am asking why this happens when i am using these lines separately one by one not all three in the same time,['c'] +1005794,why does int compile fine in c but not in c consider the following program see live demo hereinclude stdiohint mainvoid int missing variable name putssurprisemy compiler gcc 481 gives the below warningwarning useless type name in empty declaration enabled by defaultwhy does it compile fine should not i get a compiler error g 481 gives the following error when i compile it as a c programerror declaration does not declare anything fpermissive,"['c++', 'c']" +1005840,css animation overflows the div i have next code the borders should be shown i do not know why they thissapeared in demo the screen is separated in 8 equal parts and on each part should be ripple effect all works fine in chrome mozzila opera safari but ripple overflows the element in ie how can i fix itdocumentreadyfunction button lineonclick menu button function e doripplethis e var parent ink d x yfunction dorippleparent e if parentfindinklength 0 parentprependspan classinkspan ink parentfindink inkremoveclassanimate if inkheight inkwidth d mathmaxparentouterwidth parentouterheight inkcss height d width d x epagex parentoffsetleft inkwidth 2 y epagey parentoffsettop inkheight 2 inkcss top y px left x px addclassanimate function removeanimationclass inkremoveclassanimate settimeout function inkremoveclassanimate 650html bodyheight100width100margin0padding0equal equal divclasscol thisplay webkitbox thisplay mozbox thisplay msflexbox thisplay webkitflex thisplay flex flex 1 0 autobutton line height 25 width 100amenu button width 50 height 100 float left backgroundcolor white thisplay table bordercollapse collapse textdecoration none color black positionrelative overflowhidden cursorpointer amenu button menu button content thisplay tablecell verticalalign middle amenu button border overlay height100 width100 positionabsolute borderright 1px solid e6f0f0 borderbottom 1px solid e6f0f0 amenu button menu button content h2 textalign center fontsize 11em fontfamily roboto sansserif fontweight 400 amenu button menu button content menu button color rectangle padding 0 width 40px height 3px top 0 bottom 0 left 0 right 0 margin auto amenu button menu button content menu button color rectangleresidence backgroundcolor 74dbce amenu button menu button content menu button color rectanglecitizenship backgroundcolor 509194 amenu button menu button content menu button color rectangleforillegals backgroundcolor ff7662 amenu button menu button content menu button color rectanglesoonillegals backgroundcolor ffd869 amenu button menu button content menu button color rectanglefastsearch backgroundcolor 7b8dd8 amenu button menu button content menu button color rectanglecooperation backgroundcolor bb5b91 amenu button menu button content menu button color rectangleaboutapp backgroundcolor a294 amenu button menu button content menu button color rectanglesettings backgroundcolor f47b50 ink thisplay block position absolute background 006064 borderradius 100 transform scale0 animation effect inkanimate animation ripple 065s linear keyframes ripple scale the element to 250 to safely cover the entire link and fade it out 100 opacity 0 transform scale25 script srcscriptdiv classbutton line a classolmd6 menu button idresidence div classborder overlaydiv div classmenu button content h2 idresidencetext aspliteral runatserver text resources strings residence h2 div classmenu button color rectangle idresidencediv div a a classolmd6 menu button id div classborder overlaydiv div classmenu button content h2 idcitizenshiptext aspliteral runatserver text resources strings citizenship h2 div classmenu button color rectangle idcitizenshipdiv div a a classolmd6 menu button id div classborder overlaydiv div classmenu button content h2 idfastsearchtext aspliteral runatserver text resources strings fastsearch h2 div classmenu button color rectangle idfastsearchdiv div a a classolmd6 menu button id div classborder overlaydiv div classmenu button content h2 idcooperationtext aspliteral runatserver text resources strings cooperation h2 div classmenu button color rectangle idcooperationdiv div a a classolmd6 menu button id div classborder overlaydiv div classmenu button content h2 idforillegalstext aspliteral runatserver text resources strings forillegals h2 div classmenu button color rectangle idforillegalsdiv div a a classolmd6 menu button id div classborder overlaydiv div classmenu button content h2 idsoonillegalstext aspliteral runatserver text resources strings soonillegals h2 div classmenu button color rectangle idsoonillegalsdiv div a a classolmd6 menu button id div classborder overlaydiv div classmenu button content h2 idaboutapptext aspliteral runatserver text resources strings aboutapp h2 div classmenu button color rectangle idaboutappdiv div a a classolmd6 menu button idsettings div classborder overlaydiv div classmenu button content h2 idsettingstext aspliteral runatserver text resources strings settings h2 div classmenu button color rectangle idsettingsdiv div a div,"['javascript', 'jquery', 'html', 'css']" +1005924,ifstatement in c with empty body is condition guaranteed to be evaluated given this statement which as a sidenote is not my preferred coding styleif dosomething does the c standard guarantee that the function is calledit is return value has no effect on the execution path so the compilermay follow the ideas of shortcut evaluation and optimize it away,['c++'] +1005944,how to convert string to date to string in swift ios am learning swift and am struck in converting the date string to nsdate to string am getting the date string in this format thu 22 oct 2015 074517 0 i need to show the date in the mmddy format i tried the following code but it returns nulet dateformatter nsdateformatterdateformatterdateformat mmddydateformatterdatestyle nsdateformatterstylemediumstylelet dateobj dateformatterdatefromstringdatestringprintdateobj dateobjcan anyone please help where am going wrong looking forward the help thanks in advance,['ios'] +1005963,promise then vs then catch is there any difference between the 2 followings codes mypromisethenfunction consolelogsuccesscatchfunction consolelogerrormypromisethenfunction consolelogsuccess function consolelogerrori know then and catch returns new promises resolved or rejected with the value returns in the callback but i see the 2 codes around the web and i am curious about the real differences between the 2 codes,['javascript'] +1005971,phasset afnetworking upload multiple videos currently i am using the following code to upload videos nsurlrequest urlrequest afhttprequestserializer serializer multipartformrequestwithmethodpost urlstringentity uploadurlabsolutestring parametersentityparams constructingbodywithblockidafmultipartformdata formdata uploadmodel getassetdataentityasset resulthandlernsdata filedata nsstring mimetype filehelper mimetypeforfileaturlentityfileurl nserror fileappenderror formdata appendpartwithfiledatafiledata namedata filename entityfilename mimetypemimetype errorurlrequesterrorgetassetdata methodvoidgetassetdata phassetmphasset resulthandlervoidnsdata imagedatadataresponse phvideorequestoptions options phvideorequestoptions alloc init optionsversion phvideorequestoptionsversionoriginal phimagemanager defaultmanager requestavassetforvideomphasset optionsoptions resulthandleravasset asset avaudiomix audiomix nsdictionary info if asset iskindofclassavurlasset class nsurl localvideourl avurlasset asset url nsdata videodata nsdata datawithcontentsofurllocalvideourl dataresponsevideodata the problem with this approach that an app simply runs out of memory whenever largemultiple video files are being uploaded i suppose it is due to requesting the nsdata aka filedata for uploading of a filesee in the method above i have tried to request the file path using method appendpartwithfileurl intead of appendpartwithfiledatait works on an emulator and fails on a real device with an error that it cannot read the file by the path specified i have described this issue herephasset afnetworking unable to upload files to the server on a real deviceupdate i have modified my code in order to test approach of uploading file by the local path on a new iphone 6s as follows nsurlrequest urlrequest afhttprequestserializer serializer multipartformrequestwithmethodpost urlstringentity uploadurlabsolutestring parametersentityparams constructingbodywithblockidafmultipartformdata formdata nsstring mimetype filehelper mimetypeforfileaturlentityfileurl nserror fileappenderror formdata appendpartwithfileurlentityfileurl namedata filenameentityfilename mimetypemimetype errorfileappenderror if fileappenderror sys mylog nsstring stringwithformatfailed to append fileappenderror localizeddescription errorurlrequesterrortesting on iphone 6s gives a more clear log warning it occurs as the result of invoking method appendpartwithfileurl warning my log failed to append file the operation couldnat be completed file url not reachabledeny1 filereadmetadata privatevarmobilemediadcim100appleimg 08mov 154125 iphone6s kernel0 notice sandbox my app396 deny1 filereadmetadata privatevarmobilemediadcim100appleimg 08mov 154125 iphone6s my app396 warning my log failed to append file the file aimg 08mova couldnat be opened because you donat have permission to view ithere is the code used to fetch the local file path from phassetif mphassetmediatype phassetmediatypeimage phcontenteditinginputrequestoptions options phcontenteditinginputrequestoptions allocinit optionscanhandleadjustmentdata boolphadjustmentdata adjustmeta return yes mphasset requestcontenteditinginputwithoptionsoptions completionhandlerphcontenteditinginput nullable contenteditinginput nsdictionary nonnull info dataresponsecontenteditinginputfullsizeimageurl else ifmphassetmediatype phassetmediatypevideo phvideorequestoptions options phvideorequestoptions alloc init optionsversion phvideorequestoptionsversionoriginal phimagemanager defaultmanager requestavassetforvideomphasset optionsoptions resulthandleravasset asset avaudiomix audiomix nsdictionary info if asset iskindofclassavurlasset class nsurl localvideourl avurlasset asset url dataresponselocalvideourl so the issue remains the same files uploaded to the server are empty,"['ios', 'objective-c', 'iphone']" +1006194,is this a proper usage of function interface i am trying to get familiar with lambda functions to start with i decided to write a handy class called ternaryoperator so the question is did i get the ideology right or am i missing something as it should be done in a different waypublic class ternaryoperatort u implements functiont u private final functiont u f public ternaryoperatorpredicate super t condition function super t extends u iftrue function super t extends u iffalse thisf t conditiontestt iftrueapplyt iffalseapplyt override public you applyt t return fapplyt i see usage of this class like thispredicateobject condition objectsisnullfunctionobject integer iftrue obj 0functioncharsequence integer iffalse charsequencelengthfunctionstring integer safestringlength new ternaryoperatorcondition iftrue iffalseand now i can calculate a length of any string even if it is a null with this onelinerso if you have any ideas how to write better ternaryoperator or if you think that it is useless please tell me,['java'] +1006282,elastic transport client on aws managed elasticsearch i am trying to use the aws managed elasticsearch for my projecti have followed and i am able to start an instance and which is successfull but i am unable to connect to the same instance from my service using elasticsearch transport clienti know transport client supposed to connect on to the 9300 port and that port i am unable to turn on through the aws console here is the code that i am using to connect which is successfully able to connect to my elastic search setup on an ec2 machine on the 9300 portimmutablesettingsbuilder settings immutablesettingssettingsbuilder settingsputclustername myclustername putclienttransportnodes sampler interval 15s putclienttransportping timeout 15s putclienttransportsniff true putclienttransportignore cluster name falsebuild client new transportclientsettings addtransportaddress new inetsockettransportaddress envgetpropertyelastichosturlprovidedbyaws80 i am getting the exceptionorgelasticsearchclienttransportnonodeavailableexception none of the configured nodes are available at orgelasticsearchclienttransporttransportclientnodesserviceensurenodesareavailabletransportclientnodesservicejava305 at orgelasticsearchclienttransporttransportclientnodesserviceexecutetransportclientnodesservicejava200 at orgelasticsearchclienttransportsupportinternaltransportclientexecuteinternaltransportclientjava106 at orgelasticsearchclientsupportabstractclientindexabstractclientjava98i suspect that this error is since i am connecting the transportclient over the http port but i dunno what is the tcp port for aws managed elastic search instance i searched in aws documents and i couldnt find any if some have used transportclient to connect with amazon es let me knownb i have verified that the elasticsearch java jar version that i am using is as same as same with the server and from my system i am able to access the kibana and the es http ports with out any issue,['java'] +1006616,real world example of events in yii2 i learn about events from yii2 doci know how it works but i do not know where to use it and how to use it in my developmentthere is example of send email notification but i want a solid example which clear the idea where to use and how to use it my code is belowin model i write const event new user newuserpublic function sendmailtoevent thissendmailarguments you code in controller use yiibasecomponentuse yiibaseeventpublic function someaction modelonsignupformevent new user modelsendmailtoauthmodel authuser detailsuser details modeltriggersignupformevent new user,['php'] +1006661,error while converting webp image file to jpg in python i have written small program to convert webp to jpg in pythonimport imghdrfrom pil import imageim imageopenunnamedwebpconvertrgbimsavetestjpgjpegwhen executing it gives me following errorno handlers could be found for logger pilimagefiletraceback most recent call last file webptopngpy line 3 in module im imageopenunnamedwebpconvertrgb file usrlocallibpython27thistpackagespilimagepy line 2286 in open filename if filename else fpioerror cannot identify image file unnamedwebpi have installed pillow with webp capability here is my pillow installation outputpil setup summaryversion pillow 300platform linux2 273 default jun 22 2015 193341 gcc 463 tkinter support available jpeg support available openjpeg jpeg20 support not available zlib pngzip support available libtiff support not available freetype2 support available littlecms2 support not available webp support available webpmux support not availableplease help me how to proceed,['python'] +1006970,retrofit 2 example tutorial but gsonconverterfactory thisplay error cannot resolve symbol i am trying to follow retrofit is 2 tutorial but on this part of the code there is a gsonconverterfactory that thisplays error cannot resolve symbolpublic class servicegenerator public static final string api base url private static okhttpclient httpclient new okhttpclient private static retrofitbuilder builder new retrofitbuilder baseurlapi base url this is the line with error addconverterfactorygsonconverterfactorycreate public static s s createserviceclas serviceclass retrofit retrofit builderclienthttpclientbuild return retrofitcreateserviceclass previously i added in my gradlebuild i am not sure if i should add gson since they say retrofit 19 has it but nothing is mentioned about retrofit 2dependencies retrofit okhttp compile comsquareupretrofitretrofit200beta2,['android'] +1006999,cannot create directory in external storage although permissions are apparently set correctly i have usespermission androidnameandroidpermissionwrite external storage in my manifest file however i fail when trying to create a directory logdlog string androidosenvironmentgetexternalstoragestate javaiofile folder new javaiofileenvironmentgetexternalstoragedirectory javaiofileseparator test boolean success true if folderexists success foldermkdir if success logdlog string created directory else logdlog string failed while creating directory the status of external storage is mounted but the test directory cannot be created and the output is failed while creating directorybrowsing in the phone to the app info the permission modify or delete the contents of your usb storage is marked to be activated for my applicationwhat could be the cause of this some special setting of the phone it is a samsung gti9506 with android 43 api18 to be noted is that the getexternalstoragedirectory is not on the sd card but on the internal storage storageemulated0updatespeaking with colleagues it seems that this device has undergone several tweaking after having been rooted to allow a specific application to directly write on the sd card it is probably not worth to investigate further i will simply switch to another device i will keep the device for a while and if anybody will show up with an answer i will quickly test if it solves the problemupdate 2 bounty endthe problem remains unsolved but as stated before it is most likely something very specific to this one device it is not possible to write on any path being it external or internal storage not even in the path returned by getexternalcachedir,"['java', 'android']" +1007023,difference between sha256withrsa and sha256 then rsa what is the difference between compute a signature with the following two methodscompute a signature with signaturegetinstancesha256withrsacompute sha256 with messagedigestgetinstancesha256 and compute the digest with signaturegetinstancersa to get the signatureif they are different is there a way to modify the method 2 so that both methods give the same outputi tried the following codepackage myshamyshaimport javasecuritymessagedigestimport javasecurityprivatekeyimport javasecuritysecurityimport javasecuritysignatureimport orgbouncycastlejceproviderbouncycastleproviderpublic class mysha256 public static void mainstring args throws exception compute sha256 first securityaddprovidernew bouncycastleprovider string s 1234 messagedigest messagedigest messagedigestgetinstancesha256 messagedigestupdatesgetbytes byte outputdigest messagedigestdigest sign sha256 with rsa privatekey privatekey shareloadpk8dkeypk8 signature rsasignature signaturegetinstancersa rsasignatureinitsignprivatekey rsasignatureupdateoutputdigest byte signed rsasignaturesign systemoutprintlnbytestohexsigned compute sha256withrsa as a single step signature rsasha256signature signaturegetinstancesha256withrsa rsasha256signatureinitsignprivatekey rsasha256signatureupdatesgetbytes byte signed2 rsasha256signaturesign systemoutprintlnbytestohexsigned2 public static string bytestohexbyte bytes final char hexarray 0123456789abcdeftochararray char hexchars new charbyteslength 2 for int j 0 j byteslength j int v bytesj 0xff hexcharsj 2 hexarrayv 4 hexcharsj 2 1 hexarrayv 0x0f return new stringhexchars nevertheless the outputs are not the samethe following is the sample output with my test keymethod 1 61427b2a2cf1902a4b15f80156aeb09d8096ba1271f89f1919c78b18d0baba08aa043a0037934b5ae3fc0eb7702898ac5ae96517afd93433df540353bcce72a470cfa4b765d5835e7ea743f3c4a0abb11414b0141ef7eccd2d5285a69728d0d0709c2537d6a772418a928b0e168f81c99b538fd25bda7496ae8e185ac46f39method 2 ba9039b75ca8a40dc9a7aed51e174e2b3365b2d6a1cf94df70a00d898074a51fdd9973672dde95cbac39ebe4f3ba529c538ed0ff9f0a3f9a8ce203f1dffa907dc508643906aa86da54dff8a90b00f5f116d13a53731384c1c5c9c4e75a3e41daf88f74d2f1bccf818764a4ab144a081b641c1c488ac8b194eb14bc9d1928e4eaupdate 1according to mkls answer i modify my code but still cannot get it right do i still miss somethingpackage myshamyshaimport javaiobytearrayoutputstreamimport javaioioexceptionimport javasecuritymessagedigestimport javasecurityprivatekeyimport javasecuritysecurityimport javasecuritysignatureimport orgbouncycastleasn1deroutputstreamimport orgbouncycastleasn1nistnistobjectidentifiersimport orgbouncycastleasn1x509algorithmidentifierimport orgbouncycastleasn1x509digestinfoimport orgbouncycastlejceproviderbouncycastleproviderpublic class mysha256 public static void mainstring args throws exception compute sha256 first securityaddprovidernew bouncycastleprovider string s 1234 messagedigest messagedigest messagedigestgetinstancesha256 messagedigestupdatesgetbytes byte outputdigest messagedigestdigest algorithmidentifier sha256aid new algorithmidentifiernistobjectidentifiersid sha256 null digestinfo di new digestinfosha256aid outputdigest sign sha256 with rsa privatekey privatekey shareloadpk8dkeypk8 signature rsasignature signaturegetinstancersa rsasignatureinitsignprivatekey rsasignatureupdateditoasn1primitivegetencoded byte signed rsasignaturesign systemoutprintlnmethod 1 bytestohexsigned compute sha256withrsa as a single step signature rsasha256signature signaturegetinstancesha256withrsa rsasha256signatureinitsignprivatekey rsasha256signatureupdatesgetbytes byte signed2 rsasha256signaturesign systemoutprintlnmethod 2 bytestohexsigned2 public static string bytestohexbyte bytes final char hexarray 0123456789abcdeftochararray char hexchars new charbyteslength 2 for int j 0 j byteslength j int v bytesj 0xff hexcharsj 2 hexarrayv 4 hexcharsj 2 1 hexarrayv 0x0f return new stringhexchars method 1 675d8685467c5a9b5e74988e0cd41a46a929c1d0890b32b1fbe34f12d68f1fdb56e623294db903f6ac60a2ada61976b27c66056a16f5790a78168803ad2c685f9b4cf983c939305a9819cba9d95441cd7214d40d06a98b4ddf9692a7d300dd51e808a6722a0d7c288dbd476df4deebb3daf41cfc0978f24424960f86f0284emethod 2 ba9039b75ca8a40dc9a7aed51e174e2b3365b2d6a1cf94df70a00d898074a51fdd9973672dde95cbac39ebe4f3ba529c538ed0ff9f0a3f9a8ce203f1dffa907dc508643906aa86da54dff8a90b00f5f116d13a53731384c1c5c9c4e75a3e41daf88f74d2f1bccf818764a4ab144a081b641c1c488ac8b194eb14bc9d1928e4ea,['java'] +1007033,searching for data by using part of the row i have this tableand i am using the following code to retrieve data from my tablethat returns all the english words that its kurthish word contains 2targettext 2try preparedstatement ps connpreparestatementselect englishkurthish from info where kurthish or regexp matcheskurthish or regexp matcheskurthish or regexp matcheskurthish pssetstring1 targettext pssetstring2 targettext pssetstring3 targettext pssetstring4 targettext try resultset rset psexecutequery while rsetnext systemoutprintlnrsetgetstringenglish systemoutprintlnrsetgetstringkurthish so it works fine it prints all the english words that i wantmy problem is that when i get the corresponded kurthish word it does not print the complete cell it just prints 2for example the output of the previous code should beaesthete 2 u3aaether2uu u3u 2 u2 3uaffair 2 but it printsaesthete 2 aether 2 affair 2 what can i do to get the output that i wantnote that i am using ucanaccess for my database connection,['java'] +1007080,postgresql on conflict in sqlalchemy i have read quite a few resources ao 1 2 but i am unable to get postgresqls on conflict ignore behaviour working in sqlalchemyi have used this accepted answer as a basis but it givessawarning cannot validate argument append string cannot locate any sqlalchemy dialect named appendi have tried adding the postgresql dialect to the compile clause renaming my object but it does not worki also tried to use the strinsert on confilct ignore without results not surprising btwhow can i get the on conflict ignore to get added to my inserts i like the proposed solution as i can see myself not wanting the ignore behaviour on each insertps using python 27 do not mind upgrading to 3435 latest sqlalchemy 1x,"['python', 'sql']" +1007126,visual studio debugger stops hitting breakpoints in mixed debugging mode i have a severe problem with mixed debugging in msvc2013 after a call to a com method from a native c dll debugger does not stop at breakpoints any morecode structurethe picture above presents the overall structure of the codei have a single solution with about ten c projects about fifty c native projects and one ccli project serving as a bridge between managed and native worlds startup project is a c wpf project gui application it calls ccli project bridge internally which in turn calls various native c dlls various libraries alternatively i can make a c console application service console app as startup project for testing purposes onlyi have implemented a library to import some information from autodesk inventor document files inventor apprentice com server inventor apprentice on picture is used to achieve it which was freely downloaded alongside with inventor view 2015 as a first step the import was implemented in a standalone native c console application and everything worked fine then it was adapted to be used in the whole infrastructure as a native c dll import library and the debugging hell startedsymptomsdebugging broken in a debug build after calling the following com method in import libraryauto pcomponentdefinitions pdocumentgetcomponentdefinitionsbreakpoints in c code are no longer hit even if i set a breakpoint in the code of another dll it is not hit breakpoints still visualize as full red circles so this is not related to pdb issuesthe application itself continues to execute and some time later i can see the correct results of data import visible in gui meaning that import library has executed correctly after that i can pause the gui application with break all button in which case the main thread is shown stuck deeply inside one of the inventors dlls rsedll which cannot be true because that thread has finished import and has even returned correct resultsin the output window i can see the following messages appearing during the problematic com method call access violations seem to be normal in apprenticefirstchance exception at 0x07fedd451f0c rsedll in guiapplicationexe 0xc05 access violation writing location 0x07fde3afccthe common language runtime cannot stop at this exception common causes include incorrect com interop marshalling and memory corruption to investigate further use nativeonly debuggingfirstchance exception at 0x07fedd455f6c rsedll in guiapplicationexe 0xc05 access violation writing location 0x07fde3ee6ci have tried to embed breakpoints into the code at the moment of compilation by inserting debugbreak before and after the problematic import code the first one is hit if debugging is not yet broken but the second one is not on the other hand debugger clearly notices it because it writes the following message to output windowthe process hit a breakpoint the common language runtime cannot continue fromthis may be caused by an embedded breakpoint in the native runtime or a breakpoint set in a cannotstop regionto investigate further use nativeonly debugginggoogle gives no results at all for this diagnostic message it sounds like msvc thinks it is debugging managed code which is actually nativecrashes in call in case of release build running the application in mixed debugging mode results in a crash inside rsedll during the problematic com call reproducibilityi use msvc 2013 update 4 project is built in x64 mode net framework v40 is used inventor apprentice from inventor 2015 is usedexperimentation shows thateverything is ok when no debugger is attachedeverything works correctly including debugging when nativeonly debugging is used either via service console app or after attaching to already running process in native only modein mixed ie native managed debugging mode the problem reproduces regardless of whether gui application was started with debugging or debugger was attached to a working processthere is a problem both in debug and release modes but it acts differently in debug build crazy debugging issues arise debugging broken but in release it simply crashes somewhere inside crashes insidefull list of runs performed can be seen herethe main questionhas anyone seen similar behavior before what may be the cause of such behavior is there a way to fix it,"['c#', 'c++']" +1007193,oauth suddenly not working on iphone with fs app installed only our iphone app allows for sign in via foursquare via oauth it was working fine and recently stopped working the error we get is connecting failure callback uri is not valid for this consumerhowever if the user does not have the foursquare app installed on their phone it works fine as before it seems as if fs is now doing a redirect to handle the oauth inside the fs app and this fails when attempting to return to the originating application via safari it seems to work this is on ios 9solutions thanks,"['ios', 'iphone']" +1007257,difference between bytearray and list in python i am curious to know how memory management differs between bytearray and list in pythoni have found a few questions like difference between bytearray and list but not exactly answering my question my question precisely from array import array x arrayb 1234 x sizeof 36 y bytearray1234 y sizeof 32 z 1234 z sizeof 36as we can see there is a difference in sizes between listarrayarray 36 bytes for 4 elements and a byte array 32 bytes for 4 elements can someone explain to me why is this it makes sense for byte array that it is occupying 32 bytes of memory for 4 elements 4 8 32 but how can this be interpreted for list and arrayarray lets take the case of bytearray which makes more sense to me at least pfor i in y printi idi1 49623202 4962336 diff is 16 units3 4962352 diff is 16 units4 4962368 diff is 16 unitswhy does the difference between two contiguous elements differ by 16 units here when each element occupies only 8 bytes does that mean each memory address pointer points to a nibblealso what is the criteria for memory allocation for an integer i read that python will assign more memory based on the value of the integer correct me if i am wrong like the larger the number the more memoryeg y 10 y sizeof 14 y 10 y sizeof 16 y 10 y sizeof 18what is the criteria that python allocates memoryand why python is occupying so much more memory while c only occupies 8 bytes mine is a 64 bit machine when they are perfectly under the range of integer 2 64 metadata python version 343 v3439b73f1c3e601 feb 24 2015 224306 msc v1600 32 bit intelmachine arch 64bitps kindly guide me to a good article where python memory management is explained better i had spent almost an hour to figure these things out and ended up asking this question in so,['python'] +1007629,jquery selectbox to textbox before changing countryafter changing countryas you saw on the pictures i want to replace selectbox with textbox for city and town depends on changing country i need selectbox only in my country for other countries i need textboxif the client change country i am replacing selectbox to textbox it is ok but if the client want to back old country selection i need to reload city and town as selectbox but it is not workingwhat should i do here is my jquery filescript typetextjavascript documentreadyfunction var city cityhtml var town townhtml countrychangefunctioncity town var country thisval ifcountry ta14rkiye cityreplacewithinput classformcontrol typetext namecity idcity townreplacewithinput classformcontrol typetext nametown idtown else cityreplacewithcity townreplacewithtown scriptupdate i am almost done i used rhumborl s methodbut there is a problem town depends on city selection normally when city changes i am loading new towns but in this issue it is not workingin this event code failsi changed countryi turned back turkeyi changed city to ankara new towns are loading from ankarawhen i changed any other country and turn back to turkey i can see city as ankara but towns are not ankaras towns are from origin city nevaehirhere is screenshotthis is conflict,"['javascript', 'jquery']" +1007756,why does the in keyword claim it needs an iterable object non iterable 1 5 in non iterabletraceback most recent call last file input line 1 in moduletypeerror int object is not iterable class also non iterable def contains selfthing return true 5 in also non iterabletrue isinstancealso non iterable iterablefalseis there a reason in keyword claims to want an iterable object when what it truly wants is an object that implements contains,['python'] +1007782,what could trigger a sigabrt on thispatch async in ios91 i am trying to debug a crashing bug reported by many of my users in the field all show me the same stackexception type exc crash sigabrtexception codes 0x0 0x0exception note exc corpse notifytriggered by thread 8os version ios 91 13b143code type arm native0 libsystem kerneldylib 0x392c84 0x392b80 851241 libsystem pthreaddylib 0x39370732 0x3936c0 182262 libsystem cdylib 0x39264f9a 0x3921a0 3070983 libsystem cdylib 0x39264f2c 0x3921a0 3069884 libsystem cdylib 0x392447ea 0x3921a0 1740585 myapp 0x0cb3e0 69mydatamanager mymethod block invoke mydatamanagerm2367line 2367 is simply2363 bool success db executeupdateinsert into table id content values messageremoteid messagecontent2364 assertsuccess2365 debuglogdb results d success2366 2367 thispatch asyncthispatch get main queue 2368 self cleanupmethodargs2369 while there certainly is code within that block it is only 1 line long and that code does not appear to be executed on this stack because otherwise i would see cleanupmethod above mymethodedit you can see that just before the thispatch async there is an assert i originally thought that this crash was due to the assert but the line numbers never matched up the assert was many lines higher up line 2364 not 2367 and when i tested it further i saw that if the assert is triggered my stack would not include the block invoke that you can see appended to the end of the call to mymethodcan anyone suggest how a thispatch async could trigger this behavior moreover is there any way for me to symbolicate apples code in libsystem cdylibbinary image of libsystem cdylib0x3921a0 0x3927ef libsystem cdylib armv7 0b5d65608e6f38448cd207fbd748d372 usrlibsystemlibsystem cdylibnote the object in question is a global singleton my data manager if you will it handles network requests and stores state that may need to be shared between uiviewcontrollers it is declared originally as follows mydatamanager mainstore static thispatch once t once static id sharedinstance thispatch onceonce sharedinstance self alloc init return sharedinstancei understand the consequences of the object being deallocated when my cleanupmethodargs method is calledbut i had thought my global singleton would always be around and thus always safe to call in the way i do in my code i am furthermore not concerned about retain cycles since again this is supposed to be a global singletonis this code sample below ok to dointerface mydatamanagerendimplementation mydatamanager mydatamanager mainstore static thispatch once t once static id sharedinstance thispatch onceonce sharedinstance self alloc init return sharedinstance voidmymethod nsdictionary args thispatch asyncthispatch get main queue self cleanupmethodargs voidcleanupmethodidargs endinterface myviewcontroller uiviewcontrollerendimplementation myviewcontroller voidviewdidload super viewdidload mydatamanager sharedinstance mymethodend,['ios'] +1007838,apache common simplexsolver objectivefunction for maximizing the sum of values in a matrix i am trying to solve the following linear problem by using the simplex solver from apachecommons orgapachecommonsmath3optimlinearsimplexsolvern is the number of rowsm is the number of columnsl is a global limit for the sum value of each rowthis is what i have so farlistlinearconstraint constraints new arraylistdouble a calculateavalues m count of columns constraint 1 the sum of values in all column must be 1forint i 0 i m i double v new doublen forint j0 j n j vj 1 constraintsaddnew linearconstraintv relationshipleq 1 and count of rows constraint 2 sum of a ij in all row must be l limitforint i 0 i n i double v new doublem forint j0 j m j vj aij constraintsaddnew linearconstraintv relationshipleq ldouble objectivecoefficients new doublen mforint i 0 i and m i objectivecoefficientsi 1linearobjectivefunction objective new linearobjectivefunctionobjectivecoefficients 0linearconstraintset constraintset new linearconstraintsetconstraintssimplexsolver solver new simplexsolverpointvaluepair solution solveroptimizeobjective constraintset goaltypemaximizereturn solutiongetvaluei have trouble getting the objective function right and also it might be some other things missing my every attempt so far resulted in unboundedsolutionexception,['java'] +1007864,custom view created with interface builder does not render when called in other views i have an xib for the main window and i created a custom view in the following stepscreate a new class which inherits from nsviewmyviewh import cocoacocoah ib designable interface myview nstablecellview endmyviewm import myviewh implementation myview voidawakefromnib nslogpost view awaking from nib endcreate a new xib and set the root views class to the class created above and design in that xibset outlets from the xib to the classand i tried to use this custom view in the main window in the following stepsdrag a custom view to the main windows xibset the class of that custom view to the class created abovebut nothing renders from the log i can see that code in awakefromnib from the custom view class is executed when i set the class to be ib designable the view gets empty in the main windows xib different from what i designedi tried to set the file owner of the custom views xib to the custom class but nothing changedi guess the problem is that the custom views xib file is not actually loaded when i googled it there seem to be few references on this exact topic so how should i actually achieve this goal ie design a view in ib implement its methods in a class associate these two and expose it just like a system view for use in other xibsupdate i found a tutorial and realized what i lack for correctly rendering the view when built i have to add an outlet from the view in the xib to the view classproperty nonatomic strong iboutlet nsview view and then load it in the idinitwithcodernscoder coder method nsbundle mainbundle loadnibnamedmyview ownerself toplevelobjectsnilself addsubviewselfviewbut the view still would not render in the interface builder,['objective-c'] +1008137,select the most recent 5 rows based on date i have not touched php in a while and trying to select the 5 most recent entries in my database and print them to screeni see mysql command is not recommended anymore and to use pdomysql insteadmy query is something like thisselect idtitledateauthor from table order by date desc limit 5i am assuming i would have to put the values into an array and create a loop and output the resultsphpdb new pdomysqldbhostdbhostdbnamedbname user passwhile printtitlei datei authori idb nulli am stuck filling in the gaps with the above codeupdate the db new pdo line is reporting an error messagephp fatal error uncaught exception pdoexception with message sqlstatehy0 cannot connect to local mysql server through socket in varpdo is confirmed to be installed and enabled my other web apps on the server can connect to the same remote mysql server fine,"['php', 'mysql']" +1008295,redirect if authenticated logic in laravels builtin auth this question has been asked before and i believe my code to be correct but i am getting strange behaviouri need to redirect the user to different routes after login depending on some database values i thought that in order to do this i simply had to place my logic in the handle method of apphttpmiddlewareredirectifauthenticatedphp my method currently looks like sopublic function handlerequest closure next if thisauthcheck ifthisauthusersign up complete 1 return redirect else ifthisauthuserstep one complete 0 return redirectregisterstep1 elseifthisauthuserstep two complete 0 return redirectregisterstep2 else return redirect return nextrequestthis does not work and upon login the user is redirected to home i have tried placing ddthisauthuser inside the thisauthcheck condition but it never gets run if i place it outside of that check then it is run on every request it looks like thisauthcheck is never runmy question if not here where should this logic goi have removed protected redirectto account from the authcontrollerphp controller too,['php'] +1008337,fast reading of console input i need for fast reading data from standard input stream of console input consist of 10 rows with 20 chars each 2 million chars user paste it from clipboard my procedure works for about 3 minutes very slowly the target is 10 seconds it is look likevar inputdata new string10 10 rows with 20 charsfor int i 0 i 10 i cycle duration is about 3 minutes inputdatai consolereadline some processingwhats i trieddirectly consoleread consolereadkey the same resultconsolein read readline readasync readlineasync readblockwith various block size readblockasync readtoend readtoendasync the same resultnew streamreaderconsoleopenstandardinputbuffer with various buffer and block size the same resulthide console window at start of reading and show it when reading is finished acceleration 10i tried get input data from file it is works perfectly and fast but i need read from consolestreami noticed while input reading in progress process conhostexe actively uses a processorhow can i speed up the reading of inputupdincreasingdecreasing consolebufferheight and consolebufferwidth has no effect readfile msdn is also slowly but i noticed an interesting factreadfilehandle buffer buffersize out bytescount null buffersize may be very big but buffer obtains no more than one row with rn so it seems that data passed into inputstream rowbyrow syncroniously,"['c#', '.net']" +1008351,where do you file bugs for androidios google products or services appinvites maps etc i have recently found a bug on the android sdk for appinvitesi searched the web looking for a bug tracker for appinvites and could not find anyso i posted on the classic bandroidcom receiving this response from a googlersorry this tracker is for issues with the android os only please use to obtain support for google products or serviceswhich was not useful at all the support google page just list support pages for end users not for developers and there is nothing there that can work as a bug tracking tool for appinviteso i tried to post in the google group to just thiscover a while later that group has been thiscontinued by google in favor of stackoverflow but since i cannot do a bug report on a google product here i just ask for the right place to report a bug to googleexample of google products or servicesgoogle play services androidios sdkgoogle appinvites androidios sdkgoogle maps androidios sdkgoogle analytics androidios sdketcso where do i file a bug to google about one of its android or ios sdk products for developersedit this question was closed because some people think this is off topic it is not this speaks about tools commonly used in development finding bug in sdk is part of programming filing bug on those instrument is either a good practice and sometimes the only option to have your bug fixed for this reason i think this is ontopic,"['android', 'ios']" +1008407,manipulating images with net core i have updated my project from net 45 to net core with aspnet core i had some very simple code in my previous version that used the bitmap object from systemdrawing to resize an imageas i understand systemdrawing cannot be used in net core because it is not cross platform but what can be used insteadi have googled this and cannot find anything the only thing i can find is this post which has no code on it what so ever,['c#'] +1008569,how to bring the custom view cell above table rows in nstableview when i use a custom view as the cell of a viewbased nstableview the custom view is somewhat below the table row when i click on it instead of affecting the elements eg text field custom view the table row was selected and highlighted i have to reclick to select the text field nsviewtableviewnstableview tableview viewfortablecolumnnstablecolumn tablecolumn rownsintegerrow nslogwe are creating views nstablecellview newview newview tableview makeviewwithidentifierpostcell ownerself nstextfield newtextfield nstextfield alloc init newview addsubviewnewtextfield return newviewwhen i thisable the row selection according to nstableview thisable row selection there was no selection boolselectionshouldchangeintableviewnstableview tableview return nobut i still cannot select directly the text field whats worse i cannot even select it using the mouse only tab on the keyboard worksthere seem to be something above it but is it the table column shown in interface builder or something elsehow can i fix this,['objective-c'] +1008636,php operator precedence bug the result ofvar dumpnull a 15var dumpaisbooltrueint15why is this script not triggering an errorsince not equal operator has a higher precedence than assignment operator a should be compared to null first,['php'] +1008708,static cells are showing empty in interface builder running xcode 71 i am running xcode 71 on os 101 i have several tableviews with static cells for cells that are below the size for the view controller the data labels text fields etc of the static cells do not appear the static cells will not show any saved data if i scroll or do anything else the static cells are all empty i can still see the static cells when i run the simulator i just cannot edit the cells in interface builderhas anyone found a workaround for this issue,['ios'] +1008783,appdomaincurrentdomainsetupinformationprivatebinpath is null when i start my application that only has one appdomain appdomaincurrentdomainsetupinformationprivatebinpath is null even though i have probing paths set in myappexeconfig as shown belowi would have expeceted that appdomaincurrentdomainsetupinformationprivatebinpath contains the string dir1dir2dir3how can i access the probing path as configured in the myappexeconfigxml version10 encodingutf8configuration appsettings add keyfoo valuebar appsettings startup supportedruntime versionv114322 startup runtime gcconcurrent enabledtrue assemblybinding xmlnsurnschemasmicrosoftcomasmv1 publisherpolicy applyyes please add your subdirectories to the probing path probing privatepathdir1dir2dir3 assemblybinding runtime systemwindowsforms jitdebuggingtrue configurationupdateas hans passant pointed out the comment below setupinformationprivatebinpath is not set for the primary appdomain so the above does not work what would be your suggestion to simulate the way fusion searches for assemblies in the probing path or at least take probing privatepath from the current application configuration into account the best thing i can come up with is to read probing privatepath from appconfig manually when the current domain is the primary appdomain appdomaincurrentdomainisdefaultappdomain is true is there a better wayupdate 2here some additional background information what this is needed for this problem occured in appdomainassemblytypescannergetassemblydirectories of the nancy framework nancy autothiscovers and loads 3rd party modules and other plugins by default this is supposed to be done same way as normally linked assemblies would be loaded ie as fusion would do it by looking through the probing paths assemblies are loaded using assemblyload as opposed to assemblyloadfrom so as i understand it all the dependent assemblies of the loaded assemblies must be reachable in the probing path of the applicationappdomain too,"['c#', '.net']" +1008934,is there a standard way to convert a class to a string in java the standard is to define the method tostring to return a string representation of a class other than overloading operator is there any such standard in c i know there are the stdto string methods to get a string representation of a number does the c standard speak of defining the method to string to serve similar purpose for a class or is there a common practice followed by c programmers,['c++'] +1008956,subtract blend mode using colormatrixfilter in android i have the following colormatrixfilter but i want to use it as a mask for subtractblend mode instead of using it directly how do i go about achieving this colormatrix colormatrix 0393 07689 01889 0 0 0349 06859 01679 0 0 0272 05339 01309 0 0 010,"['java', 'android']" +1008991,plugin comlinkedinlinkedinshareextension interrupted in ios i am using uiactivityviewcontroller to share text and link to linkedini got the errors plugin comlinkedinlinkedinshareextension interruptedplugin comlinkedinlinkedinshareextension invalidatedi installed linkedin app on my ios device how can i fix it,['ios'] +1009134,android failed to ensure directory i have been using environmentgetexternalstorage to store and manage files and there is no warning message from logcat with that method and works greatly finebut my project needs to use method contextgetexternalfilesdirstring type and there is a warning messagecontextimplfailed to ensure directory storageexternal sdandroiddatapackage namefilesfortunately that file object works finereading or write or making folder works too but i want to know how to resolve that warning message do i miss something,['android'] +1009180,how to use tls 12 in java 6 it seems that java 6 supports tls up to v10 is there any way to use tls 12 in java 6maybe a patch or a particular update of java 6 will have support for it,['java'] +1009196,debugging in sony xperia e2003 stopped working suddenly this is my environment os ubuntu 14043 ltslinuxandroid phone sony xperiae2003 android version 4ide android studio debugging on the sony phones used to work for me it suddenly is not working now when running in debug mode the execution does not stop at break points without any change debugging on samsung phones is working nowdebugging mode is enabled and i can see the device from adb devices commandadb devies command outputusb debugging connection statusthe problem is a bit weird i have many sony phones and all of them are not working now so i guessed the problem is with my system but my team mates are also facing same problem logcat is working i see logs from user interactionthe debugger tab shows this message and hangs foreverconnecting to the target vm address localhost8601 transport socketupdatei have checked the answer here but my devices do not have sdcards so not working for me i tried to connect to the target vm manually by clicking the ff icon but the debugger gets thisconnected immediately following the steps here i cant change usb connection mode the selected option is missing on my phone,['android'] +1009234,cannot resolve symbol c882c94be45f9d16a1cf845fc16ec5 i am a new developer exploring the world of android i am currently working through the udacity tutorials for creating the sunshine app in the fragment activity class in order to get data from openweathermap i must add the api key i got from my account to the end of the generated url there is a call to buildconfigjava in the fragment activity click to see the call to buildconfigjava which is on the 6th line as part of string apikeythe buildgradle file is as followsapply plugin comandroidapplicationandroid compilesdkversion 23 buildtoolsversion 2301 defaultconfig applicationid comexampleandroidsunshineapp minsdkversion 10 targetsdkversion 21 versioncode 1 versionname 10 buildtypes release minifyenabled false proguardfiles getdefaultproguardfileproguardandroidtxt proguardrulespro buildtypeseach itbuildconfigfield string open weather map api key c882c94be45f9d16a1cf845fc16ec5 dependencies compile filetreedir libs include jar compile comandroidsupportappcompatv72310in buildtypeseach itbuildconfigfield is called with string open weather map api key c882c94be45f9d16a1cf845fc16ec5 resulting in public static final string open weather map api key c882c94be45f9d16a1cf845fc16ec5being generated in buildconfigjava however i keep getting this errorcannot resolve symbol click to see error message and buildconfigjava filei do not understand why the string open weather map api key is automatically being created as just a group of letters and numbers without quotes around them but if i edit the code to readpublic static final string open weather map api key c882c94be45f9d16a1cf845fc16ec5or public static final string open weather map api key c882c94be45f9d16a1cf845fc16ec5the buildconfigjava automatically changes itselfi am not sure what i am doing wrong and i checked many of the udacity videos which did not have any information about this issue please let me know if you know how to fix thisregards,"['java', 'android']" +1009415,write a program to find sum of squares of all numbers given the following conditions given two numbers n1 and n2 such that n2n1 find sum of squares of all numbers from n1 to n2 including n1 and n2my approachi tried to solve the problem using a for loop iterated from n1 to n2 but i am getting wrong answerbelow is my function for the codepublic int computesumofsquares int n1 int n2 int sum0 ifn2n1 forint in1in2i sumsumn1n1 return sum write your code herefor the input parameters actual output expected output8 10 192 245,['java'] +1009851,angular need to reload page for fb share button to show up i am trying to get facebooks share plugin up and running the problem i have been running into is that i have to reload the page to actually get the share button to show up if i navigate to the page through link or url the facebook share button will not show up i have to reload the page and then the button will show up i am using angular so thought to use a directive but so far my efforts have not been successful here is where i have the directive in my template div classfbsharebutton fbshare datahreffburl datalayoutbutton idfbsharedivhere is my directive angularmoduleappdirectivefbshare function function createhtmlhref layout return div classfbsharebutton datahref href datalayout layout div return restrict a scope link function postlinkscope elem attrs attrsobservedatahref function newvalue var href newvalue var layout attrslayout button elemhtmlcreatehtmlhref layout fbxfbmlparseelem0 the facebook sdk code which is just after the opening body tag div idfbrootdiv scriptfunctiond s id var js fjs dgetelementsbytagnames0 if dgetelementbyidid return js dcreateelements jsid id jssrc connectfacebookneten ussdkjsxfbml1versionv25appidx fjsparentnodeinsertbeforejs fjs document script facebookjssdk script,['javascript'] +1009943,ios uilocalnotifications action button crashes and corrupts app data minor update to our app was released this version had also changed its app id from a unique id to our team id by apple support according to apple changing to the use of team id should only reset keychain access we do not use the keychain so it should not have any effect on our appbut since the update was released some of our users on production have been experiencing corruption of their app data this happens only when they respond to a local notification using an action button from the notification center or lock screen it may happen on all ios versions supportedusers experiencing this have another symptom they receive two local notifications instead of just one but the app only see one notification further more these notifications still would not go away after thisabling notifications and cancellation using uiapplication sharedapplication cancelalocalnotifications these duplicate notification were scheduled before the app was updated from the app store but after update app lost control over them for some users this issue is described in detail in this questionthe biggest clue may lay in crash reports received from apple incident identifier ed0e9c74b38ccrashreporter key ae05bdbc46hardware model iphone41process my app 4path privatevarmobilecontainersbundleapplication653248616my appappmy appidentifier commycompanymyappversion xxcode type arm nativeparent process launchd 1datetime 20151027 21452424 0500launch time 20151027 21452020 0500os version ios 91 13b143report version 104exception type exc crash sigabrtexception codes 0x0 0x0exception note exc corpse notifytriggered by thread 0last exception backtrace0 corefoundation 0x244b3676 exceptionpreprocess 122 nsexceptionm1621 libobjcadylib 0x3582ee12 objc exception throw 34 objcexceptionmm5312 corefoundation 0x244b354c nsexception raiseformatarguments 100 nsexceptionm1313 foundation 0x25240bc4 nsassertionhandler handlefailureinmethodobjectfilelinenumberdescription 88 nsexceptionm1524 uikit 0x28840754 uiapplication runwithmainscenetransitioncontextcompletion 2928 uiapplicationm32995 uikit 0x28853a48 84uiapplication handleapplicationactivationwithscenetransitioncontextcompletion block invoke3218 32 uiapplicationm119206 uikit 0x2883d71e uiapplication workspacedidendtransaction 130 uiapplicationm26487 frontboardservices 0x2c52dca2 fbsserialqueue performnext 226 fbsserialqueuem1578 frontboardservices 0x2c52df94 fbsserialqueue performnextfromrunloopsource 44 fbsserialqueuem2049 corefoundation 0x24476bfa cfrunloop is calling out to a source0 perform function 10 cfrunloopc176110 corefoundation 0x244767e8 cfrunloopdosources0 448 cfrunloopc180711 corefoundation 0x24474b56 cfrunlooprun 790 cfrunloopc253612 corefoundation 0x243c8114 cfrunlooprunspecific 516 cfrunloopc281413 corefoundation 0x243c7f00 cfrunloopruninmode 104 cfrunloopc284414 uikit 0x28610208 uiapplication run 520 uiapplicationm248915 uikit 0x2860af10 uiapplicationmain 140 uiapplicationm366516 my app 0xc4972 main 22 mainm1417 libdylddylib 0x35f9d86e tlv get addr 42 threadlocalhelperss310it has a stacktrace exactly the same as in this question which happens when users respond to a push notification crash during app load may explain the corrupted app dataas seen in the stacktrace this crash is not caused by our code we have not changed anything in the code it has been working well before the app id change and it happens to 2 of our users heres the code that handles action buttons of notifications voidapplicationuiapplication application handleactionwithidentifiernsstring identifier forlocalnotificationuilocalnotification notification completionhandlervoid completionhandler try if notification nsdate alarmtime notificationuserinfo notificationuserinfo objectforkeytime nil logic savealarmtimealarmtime takenatnsdate date catch nsexception exception nslogexception exception description finally completionhandler what causes this crashi know that it is thrown in uiapplication runwithmainscenetransitioncontextcompletion 2928 uiapplicationm3299 question is whats in there that causes this to crash,"['ios', 'objective-c']" +1010015,how to calculate method execution time in c while debugging in visual studio 2010 iave a c method written in visual studio 2010 where several loop is executing now i want to calculate the method execution time while debugging i know that it is possible to calculate time using stopwatch in my code but i am not authorized to change the code so is there any way to calculate the method execution time while debugging,['c#'] +1010046,unknown animation name decelerateinterpolator android studio 15device samsung 442i am trying to animate items loaded from a arraylist into a recyclerview i when the dropdown arrow is clicked the items should animate decelerate when expanded and should animate when collapsed however currently the list items just appearscode that calls the setanimation override public void onbindchildviewholderchatchildviewholder childviewholder int position object childlistitem chatchildtitles chatchildtitles chatchildtitleschildlistitem childviewholdertvchildtitlesettextchatchildtitlesgettitle setanimationchildviewholdercvchildrooms position code for setting the animation private void setanimationcardview viewtoanimate int position animation animation animationutilsloadanimationmcontext androidranimfade in animationsetinterpolatormcontext androidranimdecelerate interpolator viewtoanimatestartanimationanimation here is a couple of screenshotsin the collapsed stateafter the arrow has been clicked expland the listthis is my layout i am using that represents the rows that will be thisplayed in the recyclerviewxml version10 encodingutf8androidsupportv7widgetcardview androidididcvchildrooms xmlnscard xmlnsandroid androidlayout widthmatch parent androidlayout heightwrap content cardcardbackgroundcolorcolorchild header lighter grey cardcontentpadding4dp cardcardpreventcorneroverlaptrue dehdodenhofcircleimageviewcircleimageview androidididprofile image androidlayout width40dp androidlayout height40dp androidlayout gravitycenter verticalstart androidsrcdrawablephotorace textview androidididtvchildtitle androidlayout widthwrap content androidlayout heightwrap content androidlayout gravitycenter verticalcenter androidtextcoffee latte room androidfontfamilysansseriflight androidtextsize16sp androidtextcolorandroidcolorblackandroidsupportv7widgetcardviewi have a function that should start the animationprivate void setanimationcardview viewtoanimate int position animation animation animationutilsloadanimationmcontext androidranimdecelerate interpolator viewtoanimatestartanimationanimationi have tested using the following that works ok with slide in left however i do not want them to slide in from the left animation animation animationutilsloadanimationmcontext androidranimslide in leftviewtoanimatestartanimationanimationmany thanks for any suggestions,['android'] +1010227,getting spark python and mongodb to work together i am having difficulty getting these components to knit together properly i have spark installed and working succesfully i can run jobs locally standalone and also via yarn i have followed the steps advised to the best of my knowledge here and herei am working on ubuntu and the various component versions i have arespark spark151binhadoop26hadoop hadoop261mongo 2610mongohadoop connector cloned from python 2710i had some difficulty following the various steps such as which jars to add to which path so what i have added arein usrlocalsharehadoop261sharehadoopmapreduce i have added mongohadoopcore150snapshotjarthe following environment variablesexport hadoop homeusrlocalsharehadoop261export pathpathhadoop homebinexport spark homeusrlocalsharespark151binhadoop26export pythonpathusrlocalsharemongohadoopsparksrcmainpythonexport pathpathspark homebinmy python program is basicfrom pyspark import sparkcontext sparkconfimport pymongo sparkpymongo sparkactivatedef main conf sparkconfsetappnamepyspark test sc sparkcontextconfconf rdd scmongordd mongodbusernamepasswordlocalhost27017mydbmycollectionif name main maini am running it using the commandspark homebinsparksubmit driverclasspath usrlocalsharemongohadoopsparkbuildlibs master local4 sparkpythonexamplesparkpythonexamplepyand i am getting the following output as a resulttraceback most recent call last file homemesparkpythonexamplesparkpythonexamplepy line 24 in module main file homemesparkpythonexamplesparkpythonexamplepy line 17 in main rdd scmongorddmongodbusernamepasswordlocalhost27017mydbmycollection file usrlocalsharemongohadoopsparksrcmainpythonpymongo sparkpy line 161 in mongordd return selfmongopairrddconnection string configvalues file usrlocalsharemongohadoopsparksrcmainpythonpymongo sparkpy line 143 in mongopairrdd ensure picklesself file usrlocalsharemongohadoopsparksrcmainpythonpymongo sparkpy line 80 in ensure pickles orig tbpy4jprotocolpy4jerroraccording to here this exception is raised when an exception occurs in the java client code for example if you try to pop an element from an empty stack the instance of the java exception thrown is stored in the java exception memberlooking at the source code for pymongo sparkpy and the line throwing the error it sayserror while communicating with the jvm is the mongodb spark jar on sparks classpath so in response i have tried to be sure the right jars are being passed but i might be doing this all wrong see belowspark homebinsparksubmit jars usrlocalsharespark151binhadoop26libmongohadoopspark150snapshotjarusrlocalsharespark151binhadoop26libmongojavadriver304jar driverclasspath usrlocalsharespark151binhadoop26libmongojavadriver304jarusrlocalsharespark151binhadoop26libmongohadoopspark150snapshotjar master local4 sparkpythonexamplesparkpythonexamplepyi have imported pymongo to the same python program to verify that i can at least access mongodb using that and i can i know there are quite a few moving parts here so if i can provide any more useful information please let me know,['python'] +1010233,how to parametrize function by function template while implementing byte order conversion function for a structure i found out that implementation violates dry principlehere is the code snippet to show what i mean inline void fromhostbyteordertonetworkserverstatus ss ssfield0 qtobigendian int32ssfield0 ssfield1 qtobigendian int16ssfield1 20 more fields assigned in the same wayinline void fromnetworkbyteordertohostserverstatus ss ssfield0 qfrombigendian int32ssfield0 ssfield1 qfrombigendian int16ssfield1 20 more fields assigned in the same waywhat i want one routine where i can pass name of template function qtobigendianqfrombigendian with implementation like template typename byteconversionfunctiontinline void changebyteorderserverstatus ss ssfield0 byteconversionfunctiont int32ssfield0 ssfield1 byteconversionfunctiont int16ssfield1important informationalso notice that byteconversionfunctiont inside changebyteorder is instantiated with different type like int32 int16 in qt headers qfromto is a templatetemplate typename t inline t qfrombigendiant sourcecan you suggest the way to do it or maybe to obey kiss and duplicate code in order to avoid additional complexity,['c++'] +1010317,executing and number of threads in parallel and in a sequential manner i have an application where i have 10 small parts of 1 large filei have to upload maximum of 16 parts at a timei used thread parallel library of neti used parallelfor to divide in multiple parts and assigned 1 method which should be executed for each part and set degreeofparallelism to 16i need to execute 1 method with checksum values which are generated by different part uploads so i have to set certain mechanism where i have to wait for all parts upload say 10 to completein tpl library i am facing 1 issue is it is randomly executing any of the 16 threads from 10 i want some mechanism using which i can run first 16 threads initially if the 1st or 2nd or any of the 16 thread completes its task next 17th part should be startedhow can i achieve this,['c#'] +1010410,android logcat error ecliptrayutils hidecliptrayifneeded textview is focused hidecliptray i am new und unexperienced to android trying to develop apps in ubuntu 1404 with android studio 14 i use two activities and none of these activities layout or the like uses a cliptray however in logcat i see the following entry ecliptrayutils hidecliptrayifneeded textview is focused hidecliptrayand google does not really help here no luck to find anything even for just the phrase hidecliptrayifneeded although this is listed as an error the app seems to work without problems but i do not like to have unfixed errors i also see those lines randomly in my log filedcliptrayutils setinputtypeforcliptray 0any suggestions are welcomeaddition i just realized that this error probably only occurs when the app is running on the actual phone and i switch off the thisplay could that be the cause of this error then it has nothing to do with the actual app and i will be happy,['android'] +1010554,how do i convert lambda parameters to usable objects i am trying to stream a list of doubles into a mapdouble double where the keys are the doubles in the original list and the values are some computed valuethis is what my code looks like values is a listdouble that was passed inimmutablemapdouble double valuemap valuesparallelstream collectcollectorstomapp p p dothingvalues pprivate double dothinglistdouble double p double computedvalue 00 do math here with p return computedvaluehowever intellij is complaining that p p is not a valid lambda expression it is complaining about a cyclic inference i am also getting an error when i call dothing because p is a lambda parameter and not a doublewhen i try to cast p to a double in the call to dothing that fails to castam i missing something really obvious it seems like there is no way to actually do anything with my lambda parameters,['java'] +1010577,major performance loss in uiwebview on ios 9 i have boiled down my issue to a very simple scenario and it appears to be with ios 9 and uiwebview with a website that has lots of page loads like you would get from navigatingi followed this tutorial to build a simple ios app with a uiwebview i pointed the uiwebview at a static html that looks like what i have at the bottom i then refreshed the page with the button or the script that does it automaticly and eventually the app grows slower and slower usually around 5080 refreshes i have the list in the page for demonstration because it allows you to scroll which highlights the issue much soonerany help or direction for me to look into resolving this issuedoctype htmlhtml langenheadheadbodyforminput iddemo typebutton onclickhistorygo0 valuerefreshform ul datarolelistview lithis is an itemli lithis is an itemli lithis is an itemli lithis is an itemli lithis is an itemli lithis is an itemli lithis is an itemli lithis is an itemli lithis is an itemli lithis is an itemli lithis is an itemli lithis is an itemli lithis is an itemli lithis is an itemli lithis is an itemli lithis is an itemli lithis is an itemli lithis is an itemli lithis is an itemli lithis is an itemli lithis is an itemli lithis is an itemli lithis is an itemli lithis is an itemli lithis is an itemli lithis is an itemli lithis is an itemli lithis is an itemli lithis is an itemli lithis is an itemli lithis is an itemli lithis is an itemli lithis is an itemli lithis is an itemli lithis is an itemli lithis is an itemli lithis is an itemli ul script var elem documentgetelementbyiddemo elemvalue date locationreload script bodyhtml,"['ios', 'iphone']" +1010776,checkselfpermission method is not working in targetsdkversion 22 checkselfpermission method is not working as expected and it is always returning zero in android 60marshmallow because the target sdk is 22 and i am using http client for network connection following is the code snippet private void insertdummycontactwrapper list permissionsneeded new arraylist final liststring permissionslist new arrayliststring if addpermissionpermissionslist manifestpermissionaccess fine location permissionsneededaddgps if addpermissionpermissionslist manifestpermissionread contacts permissionsneededaddread contacts if addpermissionpermissionslist manifestpermissionwrite contacts permissionsneededaddwrite contacts if permissionslistsize 0 if permissionsneededsize 0 need rationale string message you need to grant access to permissionsneededget0 for int i 1 i permissionsneededsize i message message permissionsneededgeti showmessageokcancelmessage new dialoginterfaceonclicklistener override public void onclickdialoginterface dialog int which requestpermissionspermissionslisttoarraynew stringpermissionslistsize request code ask multiple permissions return requestpermissionspermissionslisttoarraynew stringpermissionslistsize request code ask multiple permissions return insertdummycontacttargetapibuildversion codesmprivate boolean addpermissionliststring permissionslist string permission if checkselfpermissionpermission packagemanagerpermission granted permissionslistaddpermission check for rationale option if shouldshowrequestpermissionrationalepermission return false return trueprivate void showmessageokcancelstring message dialoginterfaceonclicklistener oklistener new alertdialogbuildermainactivitythis setmessagemessage setpositivebuttonok oklistener setnegativebuttoncancel null create showoverridepublic void onrequestpermissionsresultint requestcode string permissions int grantresults switch requestcode case request code ask multiple permissions mapstring integer perms new hashmapstring integer initial permsputmanifestpermissionaccess fine location packagemanagerpermission granted permsputmanifestpermissionread contacts packagemanagerpermission granted permsputmanifestpermissionwrite contacts packagemanagerpermission granted fill with results for int i 0 i permissionslength i permsputpermissionsi grantresultsi check for access fine location if permsgetmanifestpermissionaccess fine location packagemanagerpermission granted permsgetmanifestpermissionread contacts packagemanagerpermission granted permsgetmanifestpermissionwrite contacts packagemanagerpermission granted all permissions granted insertdummycontact else permission denied toastmaketextmainactivitythis some permission is denied toastlength short show break default superonrequestpermissionsresultrequestcode permissions grantresults,['android'] +1011122,string constant pool and intern i have being trying to understand the concept of string constant pool and inter for last few days after reading a lot of articles i understood some portions of it but still confused about few things1string a abc this creates a object in the string constant poolbut does the following line of code creates the object xyz in string constant poolstring b xyztolowercase2string c qwe string d csubstring1 dintern string e we should the literal we be added to the string consant pool during class loading if so why does de result in true even when the d is not pointing to string constant pool,['java'] +1011168,why is parsimonious rejecting my input with an incompleteparseerror i have been trying to work out the basic skeleton for a language i have been designing and i am attempting to use parsimonious to do the parsing for me as of right now i have declared the following grammargrammar grammar program expr expr lvalue rvalue expr lvalue az09 rvalue ns when i try to output the resulting ast of a simple input string like dosomething someargument printgrammarparse dosomething someargument parsimonious decides to flatout reject it and then gives me this somewhat cryptic errortraceback most recent call last file testspy line 13 in module printgrammarparse dosomething someargument file usrlocallibpython27thistpackagesparsimoniousgrammarpy line 112 in parse return selfdefault ruleparsetext pospos file usrlocallibpython27thistpackagesparsimoniousexpressionspy line 109 in parse raise incompleteparseerrortext nodeend selfparsimoniousexceptionsincompleteparseerror rule program matched in its entirety but it did not consume all the text the nonmatching portion of the text begins with dosomething some line 1 column 1at first i thought this might be an issue related to my whitespace rule but after a few failed attempts at removing the whitespace rule in certain places i was still coming up with the same errori have tried searching online but all i have found that seems to be remotely related is this question which did not help me in any wayam i doing something wrong with my grammar am i not parsing the input in the correct way if anyone has a possible solution to this it would be greatly appreciated,['python'] +1011280,handle selection of custom calloutview swift i have created a custom calloutview which seem to work fine however i have problem with handling tap on the custom callout view i would like push to a specific viewcontroller when it is selected how can i achieve thisbelow i have added my fbsingleclusterview which is the custom mkannotationview and the bubbleview which is the custom calloutview beside this i ofcourse have an viewcontroller with a mapviewfbsingleclusterview variablesprivate var hitoutsidebool truevar preventdeselectionbool return hitoutsidefbsingleclusterview methodsoverride func setselectedselected bool animated bool let calloutviewadded bubbleviewsuperview nil if selected selected hitoutside supersetselectedselected animated animated selfsuperviewbringsubviewtofrontself if bubbleview nil bubbleview bubbleview if selfselected calloutviewadded bubbleviewclipstobounds true bubbleviewlayermaskstobounds true selfaddsubviewbubbleview let thiscview uiimageview thiscviewcontentmode uiviewcontentmodecenter thiscviewimage uiimage thiscviewimage uiimagenamed thisclosure bubbleviewcontentviewaddsubviewthiscview let namelabel uilabel namelabelautoresizingmask flexiblewidth flexibleheight namelabelfont uifontsystemfontofsize10 namelabeltextcolor uicolorwhitecolor namelabeltext companystringuppercasestring bubbleviewaddsubviewnamelabel thiscviewsnp makeconstraints make void in maketopequaltobubbleviewoffset0 makeheightequalto30 makewidthequalto20 makerightequaltobubbleviewoffset0 namelabelsnp makeconstraints make void in maketopequaltobubbleviewoffset0 makeleftequaltobubbleviewoffset10 makeheightequalto30 makerightequaltobubbleviewoffset20 let namelabelwidth namelabelrequiredwidthcompanystringuppercasestring font uifontsystemfontofsize10 35 let bubbleheight 35 as cgfloat bubbleviewframe cgrectmakeselfframewidth2namelabelwidth2 bubbleheight2 namelabelwidth bubbleheight if selfselected bubbleviewremovefromsuperview override func hittestpoint cgpoint withevent event uievent uiview var hitview superhittestpoint withevent event if let callout bubbleview if hitview nil selfselected hitview callouthittestpoint withevent event hitoutside hitview nil return hitviewbubbleview methods override public func hittestpoint cgpoint withevent event uievent uiview let viewpoint superviewconvertpointpoint toview self point let isinsideview pointinsideviewpoint withevent event let view superhittestviewpoint withevent event return view override public func pointinsidepoint cgpoint withevent event uievent bool return cgrectcontainspointbounds point,['ios'] +1011422,mark separate dimensions of an array with annotations in java 8 we can mark separate dimensions of array with annotationssee section 102 in jls 8for exampleint a aint a b avoid somemethodint a b y then we can parse such declarations with java reflection to implement some specific logicdo you know any practical applications of this feature in real java frameworks or java libraries,['java'] +1011493,can there be an algorithm faster than linear search i have heard that there is no faster algorithm faster than linear search for an unsorted array but when i run this algorithm linearpublic static void searchint arr int value forint i 0 i arrlength i ifarri value return with a random array of length 10the average time to find a value is 75nsbut with this algorithmpublic static void skipsearchint arr int value forint i 0 i arrlength i2 ifarri value return forint i 1 i arrlength i2 ifarri value return i get a shorter average 68nsedit a lot of you are saying that i did not do a proper benchmark and this was by fluke but i ran these functions 10 times and got the average and every time i ran the functions 10 times i got 7576ns for the first algorithm and 6769ns for the second algorithmi used javas systemnanotimeto measure thiscodeint arr new int10random r new randomforint i 0 i arrlength i arri rnextintint and 10long starttime systemnanotimeforint i 0 i n i searcharr arrint mathfloormathrandomarrlengthsystemoutprintlnaverage time systemnanotimestarttimefloatnnsstarttime systemnanotimeforint i 0 i n i skipsearcharr arrint mathfloormathrandomarrlengthsystemoutprintlnaverage skip search time systemnanotimestarttimefloatnns,['java'] +1011613,i want to explode a variable in a little different way i have this variablevar abcd123456efi want to explode it so that i get the following arrayarray0 a1 b2 c3 d4 1234565 e6 fi used explodevar but i am not getting my desired output any suggestions,['php'] +1011690,java spring security oauth token not returned with 404 page not found everyone i am aware that there is already a solution for similar kind of issue but this question is differenti also read the link present but the solution did not apply to memy question is that i am trying to secure my javaspringjersey webservice application using oauth20 and have been using springsecurityoauth2 library versionwhenever i make a call to the oauthtoken the application verifies the details provided under the header client secret client id and grant type the client is successfully authenticated but token data is not returned from the server rather a 404 page not found response is shownhere is the below configurationswebxmlxml version10 encodingutf8webapp xmlnsxsi xmlns xsischemalocation 2 5xsd version25 listener listenerclassorgspringframeworkwebcontextcontextloaderlistenerlistenerclass listener contextparam paramnamecontextconfiglocationparamname paramvaluewebinfspringthispatcherservletxmlparamvalue contextparam servlet servletnamejerseyservletservletname servletclasscomsunjerseyspispringcontainerservletspringservletservletclass initparam paramnamecomsunjerseyconfigpropertypackagesparamname paramvaluecomtprivitybabycenterwsparamvalue initparam initparam paramnamecomsunjerseyapijsonpojomappingfeatureparamname paramvaluetrueparamvalue initparam loadonstartup1loadonstartup servlet servletmapping servletnamejerseyservletservletname urlpatternurlpattern servletmapping filter filternamespringsecurityfilterchainfiltername filterclassorgspringframeworkwebfilterdelegatingfilterproxyfilterclass filter filtermapping filternamespringsecurityfilterchainfiltername urlpatternurlpattern filtermappingwebappthispatcherservletxmlxml version10 encodingutf8beans xmlns xmlnsxsi xmlnsaop xmlnscontext xmlnsjdbc xmlnsoauth2 xmlnsp xmlnssecurity xmlnstx xsischemalocation securityhttp patternoauthtoken createsessionstateless authenticationmanagerrefauthenticationmanager securityintercepturl patternoauthtoken accessis authenticated fully securityanonymous enabledfalse securityhttpbasic entrypointrefclientauthenticationentrypoint securitycustomfilter refclientcredentialstokenendpointfilter beforebasic auth filter securityaccessdeniedhandler refoauthaccessdeniedhandler securityhttp securityhttp patternws createsessionnever authenticationmanagerrefauthenticationmanager entrypointrefoauthauthenticationentrypoint securityanonymous enabledfalse securityintercepturl patternws methodget accessis authenticated fully securityintercepturl patternws methodpost accessis authenticated fully securitycustomfilter refresourceserverfilter beforepre auth filter securityaccessdeniedhandler refoauthaccessdeniedhandler securityhttp bean idoauthauthenticationentrypoint classorgspringframeworksecurityoauth2providererroroauth2authenticationentrypoint bean bean idclientauthenticationentrypoint classorgspringframeworksecurityoauth2providererroroauth2authenticationentrypoint property namerealmname valuespringsecclient property nametypename valuebasic bean bean idoauthaccessdeniedhandler classorgspringframeworksecurityoauth2providererroroauth2accessdeniedhandler bean idclientcredentialstokenendpointfilter classorgspringframeworksecurityoauth2providerclientclientcredentialstokenendpointfilter property nameauthenticationmanager refauthenticationmanager bean securityauthenticationmanager aliasauthenticationmanager securityauthenticationprovider userservicerefclientdetailsuserservice securityauthenticationmanager bean idclientdetailsuserservice classorgspringframeworksecurityoauth2providerclientclientdetailsuserdetailsservice constructorarg refclientdetails bean bean idclientdetails classorgspringframeworksecurityoauth2providerclientjdbcclientdetailsservice constructorarg index0 ref beandatasource constructorarg bean securityauthenticationmanager iduserauthenticationmanager securityauthenticationprovider refcustomuserauthenticationprovider securityauthenticationmanager bean idcustomuserauthenticationprovider classcomtprivitybabycenterwssecuritycustomuserauthenticationprovider bean authorization server configuration of the server is used to provide implementations of the client details service and token services and to enable or thisable certain aspects of the mechanism globally oauth2authorizationserver clientdetailsservicerefclientdetails tokenservicesreftokenservices userapprovalhandlerrefuserapprovalhandler oauth2authorizationcode oauth2implicit oauth2refreshtoken oauth2clientcredentials oauth2password authenticationmanagerrefuserauthenticationmanager oauth2authorizationserver oauth2resourceserver idresourceserverfilter resourceidspringsec tokenservicesreftokenservices bean idtokenstore classorgspringframeworksecurityoauth2providertokenstorejdbctokenstore constructorarg namedatasource refdatasourceconstructorarg bean configure authentication manager bean idpasswordencoder classorgspringframeworksecuritycryptobcryptbcryptpasswordencoder constructorarg namestrength value11 bean grants access if only grant or abstain votes were received we can protect rest resource methods with jsr250 annotations such as rolesallowed bean idaccessdecisionmanager classorgspringframeworksecurityaccessvoteunanimousbased property namedecisionvoters list bean classorgspringframeworksecurityaccessannotationjsr250voter list property bean bean idtokenservices classorgspringframeworksecurityoauth2providertokendefaulttokenservices property nametokenstore reftokenstore property namesupportrefreshtoken valuetrue property nameaccesstokenvalidityseconds value120property property nameclientdetailsservice refclientdetails bean a user approval handler that remembers approval decisions by consulting existing tokens bean idoauth2requestfactory classorgspringframeworksecurityoauth2providerrequestdefaultoauth2requestfactory constructorarg refclientdetails bean bean iduserapprovalhandler classorgspringframeworksecurityoauth2providerapprovaltokenstoreuserapprovalhandler property namerequestfactory refoauth2requestfactory property nametokenstore reftokenstore beanbeansbelow is the logs for the samedebug orgspringframeworksecuritywebutilmatcherantpathrequestmatcher checking match of request oauthtoken against oauthtokendebug orgspringframeworksecuritywebfilterchainproxy oauthtoken at position 1 of 7 in additional filter chain firing filter securitycontextpersistencefilterdebug orgspringframeworksecuritywebfilterchainproxy oauthtoken at position 2 of 7 in additional filter chain firing filter webasyncmanagerintegrationfilterdebug orgspringframeworksecuritywebfilterchainproxy oauthtoken at position 3 of 7 in additional filter chain firing filter clientcredentialstokenendpointfilterdebug orgspringframeworksecuritywebfilterchainproxy oauthtoken at position 4 of 7 in additional filter chain firing filter basicauthenticationfilterdebug orgspringframeworksecuritywebauthenticationwbasicauthenticationfilter basic authentication authorization header found for user bccwsdebug orgspringframeworksecurityauthenticationprovidermanager authentication attempt using orgspringframeworksecurityauthenticationdaodaoauthenticationproviderwarn orgspringframeworkcontextsupportresourcebundlemessagesource resourcebundle messages not found for messagesource cannot find bundle for base name messages locale en uswarn orgspringframeworkcontextsupportresourcebundlemessagesource resourcebundle labels not found for messagesource cannot find bundle for base name labels locale en uswarn orgspringframeworkcontextsupportresourcebundlemessagesource resourcebundle errors not found for messagesource cannot find bundle for base name errors locale en usdebug orgspringframeworkjdbccorejdbctemplate executing prepared sql querydebug orgspringframeworkjdbccorejdbctemplate executing prepared sql statement select client id client secret resource ids scope authorized grant types web server redirect uri authorities access token validity refresh token validity additional information autoapprove from oauth client details where client id debug orgspringframeworkjdbcdatasourcedatasourceutils fetching jdbc connection from datasourcedebug orgspringframeworkjdbcdatasourcedatasourceutils returning jdbc connection to datasourcedebug orgspringframeworksecuritywebauthenticationwbasicauthenticationfilter authentication success orgspringframeworksecurityauthenticationusernamepasswordauthenticationtokenf9d8c511 principal orgspringframeworksecuritycoreuserdetailsuser593829e username bccws password protected enabled true accountnonexpired true credentialsnonexpired true accountnonlocked true granted authorities admin credentials protected authenticated true details orgspringframeworksecuritywebauthenticationwebauthenticationdetailsb364 remoteipaddress 01 sessionid null granted authorities admindebug orgspringframeworksecuritywebfilterchainproxy oauthtoken at position 5 of 7 in additional filter chain firing filter securitycontextholderawarerequestfilterdebug orgspringframeworksecuritywebfilterchainproxy oauthtoken at position 6 of 7 in additional filter chain firing filter exceptiontranslationfilterdebug orgspringframeworksecuritywebfilterchainproxy oauthtoken at position 7 of 7 in additional filter chain firing filter filtersecurityinterceptordebug orgspringframeworksecuritywebutilmatcherantpathrequestmatcher checking match of request oauthtoken against oauthtokendebug orgspringframeworksecuritywebaccessinterceptfiltersecurityinterceptor secure object filterinvocation url oauthtoken attributes is authenticated fullydebug orgspringframeworksecuritywebaccessinterceptfiltersecurityinterceptor previously authenticated orgspringframeworksecurityauthenticationusernamepasswordauthenticationtokenf9d8c511 principal orgspringframeworksecuritycoreuserdetailsuser593829e username bccws password protected enabled true accountnonexpired true credentialsnonexpired true accountnonlocked true granted authorities admin credentials protected authenticated true details orgspringframeworksecuritywebauthenticationwebauthenticationdetailsb364 remoteipaddress 01 sessionid null granted authorities admindebug orgspringframeworksecurityaccessvoteaffirmativebased voter orgspringframeworksecurityaccessvoterolevoter6dbd30e2 returned 0debug orgspringframeworksecurityaccessvoteaffirmativebased voter orgspringframeworksecurityaccessvoteauthenticatedvoter19d7b3 returned 1debug orgspringframeworksecuritywebaccessinterceptfiltersecurityinterceptor authorization successfuldebug orgspringframeworksecuritywebaccessinterceptfiltersecurityinterceptor runasmanager did not change authentication objectdebug orgspringframeworksecuritywebfilterchainproxy oauthtoken reached end of additional filter chain proceeding with original chaindebug orgspringframeworksecuritywebaccessexceptiontranslationfilter chain processed normallydebug orgspringframeworksecuritywebcontextsecuritycontextpersistencefilter securitycontextholder now cleared as request processing completedi have still been looking at the problem but not heading to any solution any help would be appreciated,['java'] +1011860,closure default capture overhead is there any overhead in using a default capture mode foo foo bar bar writefoo foo foo bar bar foo writefoo to clarify is there any cost in using the former related to bar being capture even if not used,['c++'] +1012109,why is address of nonstatic member not allowed as template nontype parameter template int ip struct test struct q static int a int b constexpr qint b bb int iconstexpr q q02int main constexpr testi t1 works fine constexpr testqa t2 works constexpr testq0b t3 does not work address of nonstatic member return 0the declaration of t3 in the above piece of code fails despite the template argument q0b being known during compile time some googling revealed that this is thisallowed by the standard section 1432note addresses of array elements and names or addresses of nonstatic class members are not acceptable templateargumentsxsm x4 error address of nonstatic membeso why exactly is this explicitly thisallowed by the standard despite the addresses of nonstatic members of global variables being unique as well as known during compiletime,['c++'] +1012164,swift 21 error sorting in place only on release builds i started getting crash reports for the sort lamdba in the below code the third line in the grey box belowprivate func fixoverlapsinout blocks timeblock maxoverlaps int nil blockssortinplace ab in if astarttime bstarttime return true else if astarttime bstarttime aendtime bendtime return true return false note the crash does not occur on debug builds from xcode only the app store and ad hoc archives will crash and only when the length of the blocks list is in the hundredsi modified the code to this and the problem went awayprivate func fixoverlapsinout blocks timeblock maxoverlaps int nil blocks blockssort ab in if astarttime bstarttime return true else if astarttime bstarttime aendtime bendtime return true return false is there something i have missed about how to use inout or sortinplace i can try to do a demo of this it is on multiple versions of ios 89 and swift 21editok heres a minimal version that crashes turns out the inout was a red herring if you start a new single view project in xcode 71 you can replace the view controller with thisclass viewcontroller uiviewcontroller override func viewdidload superviewdidload do any additional setup after loading the view typically from a nib var blocks timeblock for var i in 020 works if you put in a small number like 8 let t timeblock tstart intarc4random uniform10 get some random numbers so the sort has to do some work tend intarc4random uniform10 blocksappendt blockssortinplace ab in if astart bstart return true return false printdone gets here on debug not releaseclass timeblock var start 0 var end 0override func didreceivememorywarning superdidreceivememorywarning thispose of any resources that can be recreatedso run it in release and you should see it prints done if you end the loop at around 17 but crashes with 20 exact number might be different for you,['ios'] +1012203,babel the cli has been moved into the package babelcli i was working on a js file at work where i had babel installed running babel filejs nodei sent the file home to work in the evening installed babel at home and i got the following error when i run the above commandthe cli has been moved into the package babelcliany ideas thank you in advance if i install the cli the following code fails to compilefunction sumarrayindexarray i separator return array mapx xsplitseparator mapc return parseintc mapx return xi reducex y return x y 0function mintosecm return m 60function secondstominutesandsecondss var min s 60 var sec s 60 minutes mathfloormin seconds secfunction outputtime return hours minutes seconds,['javascript'] +1012228,how to check if celerysupervisor is running using python how to write a script in python that outputs if celery is running on a machine ubuntumy usecase i have a simple python file with some tasks i am not using django or flask i use supervisor to run the task queue for exampletaskspyfrom celery import celery taskapp celerytasksapptaskdef add togethera b return a bsupervisorprogramcelery workerdirectory varappcommandcelery a tasks worker infothis all works i now want to have page which checks if celerysupervisor process is running ie something like this maybe using flask allowing me to host the page giving a 200 status allowing me to load balance for examplecheck statuspy from flask import flaskapp flask name approutedef status check check supervisor is running if supervisor return render templateuphtml else return render templatedownhtmlif name main apprun,['python'] +1012494,ipad pro device detection i am trying to detect ipad pro device trying to guess its height with nslogfselfviewframesizeheightbut it returns 1024 same as ipad non retina devices any advice i need to specify some codes exact for ipad pro with this line of code define ipadpro uidevice currentdevice userinterfaceidiom uiuserinterfaceidiompad uiscreen mainscreenboundssizeheight 2732and the codes must detect ipad pro even on ios simulator thanksedited some suggest use lunchscreen but when i use it this happens scaled down,"['ios', 'objective-c']" +1012534,retrofit default thread i use retrofit with rxjava in my android app and my codepublic void getconfignetworksubscriber subscriber observableconfig observable mapigetconfig observablesubscribeonschedulersnewthread observeonandroidschedulersmainthread subscribesubscriberpublic void getcodestring mobile int type networksubscriber subscriber observablebasemessageentity observable mapigetcodemobile type observablesubscribeonschedulersnewthread observeonandroidschedulersmainthread subscribesubscriberand i do not want to write subscribeonschedulersnewthread and observeonandroidschedulersmainthread every business methodhow can i do,['android'] +1012754,how to query relational data in parse javascript i am quite new to parsei have a database set up using this codevar class parseobjectextendclassvar team parseobjectextendteamvar student parseobjectextendstudentvar newclass new classnewclasetname classnamenewclasetcode classcodenewclasetcreator currentuservar classacl new parseaclcurrentuserclassaclsetpublicreadaccesstruenewclasetaclclassaclnewclasavefor var i 0 i teamnameslength i var team new team teamsetname teamnamesi var teamacl new parseaclcurrentuser teamaclsetpublicreadaccesstrue teamsetaclteamacl teamsave for var j 0 j studentnamesilength j if studentnamesij var student new student studentsetname studentnamesij studentsetparent team studentsave teamsetparent newclass teamsavenewclasavenull success functionnewclass success error functionnewclass error fail here class team and student are modeled as onetomany relationshipsnow when a student signs up for the class using his or her own user account the corresponding students user column is set to the current userthen i want to list all the classes whose creator or one of its students user column if exists equals to currentuserhow do i create such a query referencing multiple classes in parse or how can i optimize the database so that such a query can be made as efficient as possible without having to create two separate queriesany help is appreciatedclarificationi knew that i could do an or query as described in parse docs i should have stated this in the question however my question is about doing so on relational data defined by a pointer type property to parent here i need user be a property of a student instance which belongs to team and then to class and i would like to filter only class objects that has either its creator property or one of its grandchildrens an instance of student user property equal to the currentuser effectively listing only the classes that you created or are registered as a student,['javascript'] +1012758,how to import a swift framework globally i want to have a way to import my swift cocoapods globally in every class how can i achieve thisi tried a lot of things and they did not work here are some ways i have not tried and thought may be possible if found a way to work themhave a general import statement like uikit and put everything in there edit this failedsomehow put swift frameworks in the objc briding header and import the stuff in there,['ios'] +1012765,babelloader jsx syntaxerror unexpected token i am a beginner in react webpacki found a wired error in my hello world web appi am using babelloader in webpack to help me convert jsx into js but it seems like babel cannot understand jsx syntaxhere are my dependciesdevdependencies babelcore 6014 babelloader 600 webpack 1122 webpackdevserver 1121dependencies react 0141here are my webpackconfigjsvar path requirepathmoduleexports entry webpackhotdevserverpathresolve dirname appmainjs output path pathresolve dirname build filename bundlejs module loaders test js exclude node modules loader babelloader here are my appmainjsvar react requirereactreactrenderh1hello worldh1documentgetelementbyidappand this is the error messageerror in appmainjsmodule build failed syntaxerror appmainjs unexpected token 213 1 var react requirereact 2 reactrenderh1hello worldh1documentgetelementbyidapp at parserppraise node modulesbabylonlibparserlocationjs2413thanks for you guys,['javascript'] +1012808,how to extend the information that provides intellisense using the visual studio sdk in c or vbnet using the visual studio 2013 sdk how i could add an additional element on intellisense when the info of a member is shownmy intention is not to add a completionsuggestion element i would like to add custom additional info below the info that is shown for a member that can throw an exception like a method function or property gettersetter not a keywordi read a little bit the members of microsoftvisualstudiolanguageintellisense namespace but i did not take any clear idea about itmy goal with the help i could get here is to find the answer to develop a simple extension that will add documentedexception information for members something like thisi wonder to bring back this useful feature in visual studio for c and add it also for vbnet then if successful i will share it for free with all yours like i did in the past with this useful extensionsnippet tool visual studio galleryjust i comment that because any help could be rewarded for all of us in that wayadditionally to my question and only additionally if someone could start guiding me about how to figure out the way to retrieve the xml documentation of the members exception crefexception name to do this or maybe a simple way i would be very gratefuleditabout the xml documentation i get the idea to use the visual studio object browser to inspect the exceptions of the member that will be listed by intellisense instead of messing with reflection to get exception info that could be a better and viable way to do it once i can figure out how to automate the object browser from sdk but i am just commenting this maybe that will be a new question once this question could be solved because firstly i need to solve this step i hope so,"['c#', '.net']" +1012877,overriding len in init py python i would like to assign an another function to len in init py file of my package the following wayllen lenlen lambda x llenx 1it works fine but only in the init py file how can i make it affect other modules in my package,['python'] +1013056,apache storm bolt task is not receiving message after some time we have a storm topology in which we configured one spout and two bolts spout queries data from db continuously and send tuples it to first bolt for some processing first bolt does some processing and send tuples it to second bolt which calls third party web service and sends data so what is happening after some time last bolt is not getting any tuples and if we restart the topology it works fine only last bolt is in problem here other spout and first bolt are running fine and i am not using acking framework i have configured only one worker in this casetopologybuilder builder new topologybuilder buildersetspoutmessagelistenrspout new messagelistenerspout 1 buildersetboltprocessorbolt new processorbolt 20shufflegroupingmessagelistenrspout buildersetboltnotifierbolt new notifierbolt40shufflegroupingprocessorbolt config conf new config confputconfigtopology sleep spout wait strategy time ms 10 confsetmessagetimeoutsecs600 confsetdebugtrue stormsubmittersubmittopologytopology conf buildercreatetopology,['java'] +1013064,objectmapper initialize object ios simple thing that is giving me a headache how to initialize an object that conforms to mappable protocol without any json yetwhat i would like to do is simply initialise empty user object in code like thislet user userhowever that gives me errormissing argument for parameter 1 in calli was able to do it in version 014 with swift 12 but now it doesnt work do you guys know how to do it now in swift 2 and new object mapper i know how to initialize it with json etc i just want to initialize that object for other purposes and i cant figure out howclass user mappable var username stringvar age intvar weight doublevar array anyobjectvar dictionary string anyobject var bestfriend user nested user objectvar friends user array of usersvar birthday nsdaterequired init map map mappablefunc mappingmap map username mapusername age mapage weight mapweight array maparr dictionary mapdict bestfriend mapbest friend friends mapfriends birthday mapbirthday datetransformplease help,['ios'] +1013422,uistackview and truncated multiline uilabels i want to add several multiline labels to an uistackviewbut i always end up my labels being truncated as seen in this screenshotbut i like to have it more as shown here my faked screenshothere is my code first i create the parentmaster stackview put it into an scrollview which is tucked to the screen stackview uistackview stackviewaxis vertical stackviewthistribution fill stackviewspacing 2 stackviewtranslatesautoresizingmaskintoconstraints false scrollviewaddsubviewstackview nslayoutconstraintactivateconstraintsstackconstraints let s1 createheaderstackview stackviewinsertarrangedsubviews1 atindex 0 let lbl2 makelabel lbl2text second one stackviewinsertarrangedsubviewlbl2 atindex 1 scrollviewsetneedslayoutwhile makelabel and makebutton are just helper functions func makebutton uibutton let btn uibuttontype custom btnbackgroundcolor uicolorlightgraycolor return btnfunc makelabel uilabel let lbl uilabel lblfont uifontsystemfontofsize18 lblsetcontentcompressionresistancepriority10 foraxis vertical lblsetcontenthuggingpriority10 foraxis vertical lblpreferredmaxlayoutwidth scrollviewframewidth lblnumberoflines 0 lbltextcolor uicolorblackcolor lblbackgroundcolor uicolorredcolor return lblthe createheaderstackviewmethod is to configure my stackview to put inside a stackview with all my header stufunc createheaderstackview uistackview let lblheader makelabel lblheadertext uistackview lblheadertextalignment center let lblinfo makelabel lblinfotext this is a long text over several lines because why not and am able to to so unfortunaltey stackview thinks i am not allowed lblinfotextalignment natural lblinfolayoutifneeded let lblinfo2 makelabel lblinfo2text this is a seconds long text over several lines because why not and am able to to so unfortunaltey stackview thinks i am not allowed lblinfo2textalignment natural lblinfo2layoutifneeded let btnportal makebutton btnportalsettitlemy button forstate normal btnportaladdtargetself action gotopushwebportalaction forcontrolevents touchupinside let headerstackview uistackviewarrangedsubviews lblheader btnportal lblinfo lblinfo2 headerstackviewaxis vertical headerstackviewalignment center headerstackviewthistribution fill headerstackviewspacing 2 headerstackviewsetcontentcompressionresistancepriority10 foraxis vertical headerstackviewsetcontenthuggingpriority10 foraxis vertical headerstackviewsetneedsupdateconstraints headerstackviewsetneedslayout headerstackviewlayoutmarginsrelativearrangement true return headerstackviewso to make a long story short what is needed to adjust my stackviews so each stackview and therefore label is shown in full glorious size i tried to compress and hug everything but it did not seem to work and googling uistackview uilabel multiline truncated seems to be a dead end tooi appreciate any helpregards flori,['ios'] +1013475,can you share data on cloudkit between different apps i have a free and paid version of my app in the app store i am updating the app to share some public data using cloudkit i would like both the free and paid apps to share the same data firstly is it possible for two apps to share the same data with cloudkit if so how can i get this to work i have tried enabling cloudkit in the capabilities of both targets and selecting the same container in both apps the main app which has use default container selected works fine but the other app on which i have selected specify custom containers and selected the custom container from the first target gets an error back when i try to download anything,['ios'] +1013546,foreach loop vs foreach method differences edit this question can be marked as a duplicate of this questionis there any differences performance or otherwise between using a foreach loop or the foreach linq methodfor context this is part of one of my methodsforeach var property in typeofpersongetproperties validatepropertynamei can alternatively use this code to perform the same tasktypeofperson getproperties tolist foreachproperty validatepropertynamewhen would be using the loop structure be better than using method chainingheres another example where i have used the foreach method but could just have easily used a foreach loop and a variable linqprivatedatadatabaseusers castuser whereuser userlogintype logintypewindowsuser selectuser new name username login userlogin tolist foreachresult writeobjectresult loopvar users privatedatadatabaseusers castuser whereuser userlogintype logintypewindowsuser selectuser new name username login userlogin foreachvar user in users writeobjectuser,['c#'] +1013585,mathematical explanation why decimals conversion to double is broken and decimalgethashcode separates equal instances i am not sure if this nonstandard way of stating a stack overflow question is good or bad but here goeswhat is the best mathematical or otherwise technical explanation why the codestatic void main decimal arr 42m 420m 4200m 420m 420m 420m 420m 420m 420m 420m 420m 420m 420m 420m 420m 420m 420m 420m 420m 420m 420m 420m 420m 420m 420m 420m 420m 420m foreach var m in arr consolewritelinestringformatcultureinfoinvariantculture 032120r2x8 m doublem mgethashcode consolewritelinefunny consequences var h1 new hashsetdecimalarr consolewritelineh1count var h2 new hashsetdoublearrselectm doublem consolewritelineh2countgives the following funny apparently incorrect output42 42 40450420 42 404504200 42 40450420 42 40450420 42 40450420 42 40450420 42 40450420 42 40450420 42 40450420 42 40450420 42 40450420 42 40450420 42 40450420 42 40450420 42 40450420 42 40450420 42 40450420 42 40450420 42 40450420 42 40450420 42 40450420 4193 bfbb0f420 42 40450420 4207 40450420 42 40450420 42 40450420 42 40450420 42 40450funny consequences23tried this under net 452,"['c#', '.net']" +1013596,function parameter the same in button ngclick i have two buttons that are using the same ngclick with different paramslabel classitem iteminput button ngclicktakepicturetruesave settingsbutton button ngclicktakepicturefalsechoose from gallerybuttonlabelno matter what i do the buttons pass the same param as what is in the first function callwith a simple controller function for testing the same param gets logged in this case it is true for bothscopetakepicture functionmy param consolelogmy paramthese seems to happen only in ionic not with standard angular here is a codepen for a working exampleedit per the solution below i have included the source of the problem in the code excerpt above curse you label curse you to heck,['javascript'] +1013653,how to group a series by values in pandas i currently have a pandas series with dtype timestamp and i want to group it by date and have many rows with different times in each groupthe seemingly obvious way of doing this would be something similar togrouped sgroupbylambda x xdatehowever pandas groupby groups series by its index how can i make it group by value instead,['python'] +1013655,algorithm to find all primes from 2 to 10 not working heres a piece of code to compute all primes from 2 to 10 using the statement that a number and is a prime number iffin the first version i think that i implemented the algorithm correctlypublic class giuga public static void mainstring args int and 2 whilen10 int k 1 long sum 0 whilekn1 sum sumlongmathpowdoublekdoublen1 k ifsumnn1 systemoutprintlnn is a prime n but since the variable sum grows rapidly an overflow happens and after the prime number 17 there will be no output anymoreto prevent that i have to use thiswell i did that and here is my 2 versionpublic class giuga public static void mainstring args int and 2 whilen10 int k 1 long sum 0 whilekn1 sum sumlongmathpowdoublekndoublen1n here are the changes k ifsumnn1 systemoutprintlnn is a prime n i think i did it correctly but now the output stops after the prime number 13 i am trying to find my mistake for quite some time now what am i doing wrongthere must be 168 primes from 2 to 10,['java'] +1013659,getting currently selected text i am try to get the currently selected text in an input using windowgetselection but i am always getting an empty stringexpectbrowserexecutescriptreturn windowgetselectiontostringtoequaltestresults intoexpected to equal testthe complete reproducible test using angularjsorg as a target sitedescribemy test function beforeeachfunction browserget itshould select text in an input function var query elementbycssinputsearchquery querysendkeystest querysendkeysprotractorkeychordprotractorkeycommand a expectbrowserexecutescriptreturn windowgetselectiontostringtoequaltest note that i actually see the entered text being selected with command awhat am i doing wrongusing protractor 251 firefox 41,['javascript'] +1013994,how to send broadcast from one app to another app i have app a and app b in app a i want to send broadcast to app bthis is the code for app1 final intent intentnew intent intentsetactioncompkgperformruby intentputextrakeynamecode1id intentsetcomponentnew componentnamecompkgappbcompkgappbmainactivity sendbroadcastintentand in app b in mainactivity i have my broadcastreceiverclass public class mainactivity extends activity private mybroadcastreceiver myreceiver override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main receive broad cast fromn external app intentfilter intentfilternew myreceiver new mybroadcastreceiver intentfiltercompkgperformruby ifintentfilternull registerreceivermyreceiverintentfilter public class mybroadcastreceiver extends broadcastreceiver override public void onreceivecontext context intent intent todo autogenerated method stub toastmaketextmainactivitythisdata received from external apptoastlength shortshow override protected void ondestroy todo autogenerated method stub superondestroy ifmyreceiver null unregisterreceivermyreceiver i am getting the error receiver is not registered,['android'] +1014152,mysql connect to server access denied for user rootlocalhost edit9 is it a possibility that i am simply missing a few permissions on folders i would really really appreciate some more suggestionsedit3 as this post did not get enough replies and it is absolutely vital i get this going as soon as possible i reconstructed my post to thisplay what i think i have deducted so farnote logging in normally via numerous different commands simply did not workmy processremoved mysql running the following commands did i forget anythingsudo rm usrlocalmysqlsudo rm rf usrlocalmysqlsudo rm rf librarystartupitemsmysqlcomsudo rm rf librarypreferencepanesmysqlrm rf librarypreferencepanesmysqlsudo rm rf libraryreceiptsmysqlsudo rm rf libraryreceiptsmysqlsudo rm rf vardbreceiptscommysqldownloaded mysql579osx1010x86 64dmg from installed mysql579osx109x86 64pkg using a standard install on standard location why is the pkg 109 while i downloaded 1010 my os x version is 1010 yosemitei get a notification that a temporary password for rootlocalhost has been created i wrote this down perfectlyhere is where the problems startattempting to start mysql server via terminal with sudo usrlocalmysqlsupportfilesmysqlserver start returns starting mysql error the server quit without updating pid file varrunmysqldmysqldpidafter some research about this pid file i realized i needed to create mycnf in etc so i didcd usrlocalmysqlsupportfilessudo cp mydefaultcnf etcmycnfedited and saved mycnf cd etcsudo nano mycnf entered the line pidfile varrunmysqldmysqldpidcreated the directory sudo mkdir varrunmysqldsudo touch varrunmysqldmysqldpidsudo chown r mysqlmysql varrunmysqldassuming mycnf should be all set now including the pid file i tried to start the server again however nothing has changedokay so then i decided fine i will try to change the password that was temporarily set when i installed i stop the mysql server it should not be running but just in case sudo usrlocalmysqlsupportfilesmysqlserver stop this might be interesting because i end up in some sort of shell form in which i am not able to do anything whatsoever i have to restart terminal from heretrying to start mysql in safe mode with sudo mysql safe skipgranttables returns 1510 102810 mysqld safe logging to usrlocalvarmysqlrobsmacbookprolocalerr1510 102810 mysqld safe starting mysqld daemon with databases from usrlocalvarmysql1510 102810 mysqld safe mysqld from pid file usrlocalvarmysqlrobsmacbookprolocalpid endedso again it is all about this pid file i have no values set for basedirdatadirportserver idsocket here perhaps that is it if so what values should i set here other errors that regularly occur when i fiddle around with different suggestions on the internet include access denied for user rootlocalhost using password yesno orcant connect to mysql server through socket usrlocalvarmysqldatamysqldlocalerr last few lines201517t081355755115z 0 warning timestamp with implicit default value is deprecated please use explicit defaults for timestamp server option see documentation for more details201517t081355756291z 0 warning no zero date no zero in date and error for division by zero sql modes should be used with strict mode they will be merged with strict mode in a future release201517t081355756310z 0 warning no auto create user sql mode was not set201517t081355780792z 0 warning insecure configuration for securefilepriv current value does not restrict location of generated files consider setting it to a valid nonempty path201517t081355781750z 0 note usrlocalmysqlbinmysqld mysqld 579 starting as process 94 201517t081355796438z 0 warning setting lower case table names2 because file system for usrlocalmysqldata is case insensitive201517t081355802783z 0 note innodb mutexes and rw locks use gcc atomic builtins201517t081355802816z 0 note innodb uses event mutexes201517t081355802826z 0 note innodb gcc builtin atomic thread fence is used for memory barrier201517t081355802834z 0 note innodb compressed tables use zlib 123201517t081355804723z 0 note innodb number of pools 1201517t081355808009z 0 note innodb using cpu crc32 instructions201517t081355821713z 0 note innodb initializing buffer pool total size 128m instances 1 chunk size 128m201517t081355843514z 0 note innodb completed initialization of buffer pool201517t081355898365z 0 note innodb highest supported file format is barracuda201517t081355935027z 0 note innodb creating shared tablespace for temporary tables201517t0813559352z 0 note innodb setting file ibtmp1 size to 12 mb physically writing the file full please wait 201517t081355950640z 0 note innodb file ibtmp1 size is now 12 mb201517t081355952035z 0 note innodb 96 redo rollback segments found 96 redo rollback segments are active201517t081355952061z 0 note innodb 32 nonredo rollback segments are active201517t081355952538z 0 note innodb waiting for purge to start201517t081356070486z 0 note innodb 579 started log sequence number 2471474201517t081356070792z 0 note innodb loading buffer pools from usrlocalmysql579osx109x86 64dataib buffer pool201517t081356071268z 0 note innodb not started201517t081356072953z 0 note plugin federated is thisabled201517t081356075825z 0 note innodb buffer pools load completed at 1517 91356201517t081356086709z 0 warning failed to set up ssl because of the following ssl library error ssl context is not usable without certificate and private key201517t0813561126z 0 note server hostname bindaddress port 3306201517t081356112759z 0 note ipv6 is available201517t081356112804z 0 note resolves to 201517t081356113081z 0 note server socket created on ip 201517t081356180223z 0 note event scheduler loaded 0 events201517t081356180406z 0 note usrlocalmysqlbinmysqld ready for connectionsversion 579 socket tmpmysqlsock port 3306 mysql community server gploutcome to a nice suggestion from vasfedthen creating the txt file as described entered the command with my used directory and filename mysqld safe initfilehomemysqlinit which returns robsmacbookprohome leroyklotz 1518 092523 mysqld safe logging to usrlocalvarmysqlrobsmacbookprolocalerr1518 092523 mysqld safe starting mysqld daemon with databases from usrlocalvarmysqlusrlocalbinmysqld safe line 129 usrlocalvarmysqlrobsmacbookprolocalerr permission deniedrm tmpmysqlsock permission deniedusrlocalbinmysqld safe line 166 usrlocalvarmysqlrobsmacbookprolocalerr permission denied1518 092523 mysqld safe mysqld from pid file usrlocalvarmysqlrobsmacbookprolocalpid endedusrlocalbinmysqld safe line 129 usrlocalvarmysqlrobsmacbookprolocalerr permission deniedgranting permissions on robsmacbookprolocalerr and mysqlsock which is still called mysqlsocklock does this matterdoes not completely solve the issue error message now readsrobsmacbookpro leroyklotz mysqld safe initfilehomemysqlinit 1 747robsmacbookpro leroyklotz 1519 091351 mysqld safe logging to usrlocalvarmysqlrobsmacbookprolocalerr1519 091351 mysqld safe starting mysqld daemon with databases from usrlocalvarmysqlrm tmpmysqlsock permission denied1519 091353 mysqld safe mysqld from pid file usrlocalvarmysqlrobsmacbookprolocalpid ended,['mysql'] +1014526,using webpack with babel and babelpresetreact and babelpresetes2015 i am trying to transcompile my reactes6 code and am coming from browserify i am struggling to create a webpack build because of the new babel 6 release and the fact that most of the tutorials out there are now outdatedthis works in my babelrc presets reactbut when i change it to this presets es2015 reactit throws this cryptic error error in clientappjsmodule build failed error you gave us a visitor for the node type numericliteral but it is not a valid typethis is my webpackconfigjs if that helps at allmoduleexports entry clientappjs output filename publicbundlejs resolve extensions js jsx module loaders test jsx exclude node modulesbower components loader babel is there something obvious i am missing i have also swapped the order of the presets and it does not seem to make a difference i have babelcore babelloader babelpresetes2015 babelpresetreact and webpack in my node modules,['javascript'] +1014554,create and import helper functions in tests without creating packages in test directory using pytest questionhow can i import helper functions in test files without creating packages in the test directorycontexti would like to create a test helper function that i can import in several tests say something like this in common filepydef assert a general property betweenx y test a specific relationship between x and y assert in testmy testpydef test something withx some value some function of x assert a general property betweenx some valueusing python 35 with pytest 282 current solutioni am currently doing this via importing a module inside my projects test directory which is now a package but i would like to do it with some other mechanism if possible so that my test directory does not have packages but just tests and the tests can be run on an installed version of the package as is recommended here in the pytest documentation on good practices,['python'] +1014621,react babel webpack not parsing jsx code webpackconfigjsmoduleexports context dirname app entry javascript appjs html indexhtml resolve extensions js jsx output filename appjs path dirname thist module loaders test jsx exclude node modules loader babelloader test html loader filenamenameext packagejson name reactwebpackproject version 100 description main indexjs scripts test echo error no test specified exit 1 author license isc devdependencies babel 6015 babelcore 6020 babelloader 601 fileloader 084 webpack 1122 dependencies react 0142 appappjsimport react from reactimport greeting from greetingreactrender greeting nameworld documentbodyi have seen the exact same questions after searching around but none of the answers seemed to apply to me i am getting the following error when running webpack error in appjsmodule build failed syntaxerror pathtoprojectreactwebpackprojectappappjs unexpected token 52 reactrender greeting nameworld documentbodyi am not sure why i am getting this error still i am guessing it has something to do with my webpackconfigjs file but not 100 what the problem is,['javascript'] +1014791,how to draw a shape using a piece of image in php i need to create a frame image by using a piece of an imagefor exampleuser will upload a image piece from backendnow i need to create a frame on frontend as per the frontend users requirement user will choose the height and width of frame then he will choose this image piece like thisi am not getting any way to do this i have tried to do this by css and html canvas but no luckcan some one please suggest me how can i achieve this by using php or css or html or javascript or any howyou can see the working example here that actually i need to docreate your own frame,"['javascript', 'php', 'html', 'css']" +1014798,understanding the given calculation cast multiplication intfloat109 10is evaluated to 108 whyimo the intcast should be evaluated after the multiplication,"['c#', '.net']" +1014819,interop with nim return struct array containing a string char member interoping nim dll from c i could call and execute the code belowif i will add another function proc that calls getpacks and try to echo on each elements buffer i could see the output in the c console correctlybut i could not transfer the data as it is i tried everything but i could not accomplish the taskproc getpacksptrnimparsze int packarrinout var datapackarrstdcallexportcdynlib packarrinoutnewseqparsze var dummystr abcdefghij for i curdatapack in packarrinoutmpairs dummystr9 chari int80 curdatapack datapackbufferdummystr intval uint32 itype datapackarr seqdatapack datapack object buffer string intval uint32when i do same in cc the type i am using is either an intptr or charthat is happy to contain returned buffer member export api void cdecl c returndatapackunsigned int size datapack dparr unsigned int dumln indexdatapack curdp null char dummystrmax dparr datapackmalloc size sizeof datapack curdp dparr strncpydummy abcdefghij strmax dumln sizeofdummy for index 0 index size indexcurdp curdpival index dummydumln1 0 index 126 0 curdpsval char calloc dumlnsizeofdummy strcpycurdpsval dummy c signature for c code above dllimportcdllidll callingconvention callingconventioncdecl suppressunmanagedcodesecurity private static extern uint c returndatapackuint x datapackgtestc tcdparrc struct public unsafe static class datapackg structlayoutlayoutkindsequential public struct testc public uint id public intptr strval finally calling the function like so public static unsafe listdatapackgtestc populatelstpackcint arrl datapackgtestc packuarrout listdatapackgtestc rtlstpacku new listdatapackgtestcarrl c returndatapackuintarrl packuarrout datapackgtestc currentpack packuarrout for int i 0 i arrl i currentpack rtlstpackuaddnew datapackgtestc strval currentpackstrval id currentpackid consolewritelineres0 marshalptrtostringansiintptrrtlstpacku1strvalnew stringrtlstpacku0strval return rtlstpacku how could i produce similar c code as above from nim it does not have to be same code but same effect that in c i would be able to read the content of the string for now the int is readable but the string is not edit this is what i tried to make things simple struct array of int membersupdateit seem that the problem is to do with my settings of nim in my windows osi will be updating as soon as i thiscover what exactly is wrong,"['c#', 'c']" +1014881,what is overflow usub linus torvalds has recently made it to mainstream news with a rant over a pull request this pull request included a function overflow usub which is apparently nonstandard and uses some kind of compiler magic as a result of the widespread reporting of this rant it is nearimpossible to find any useful information about this function my question is what is overflow usub when should it be used and what kind of compiler magic does it require,['c'] +1014943,how do i make java hashtablecontainskey to work for array sorry to ask this question but i am new to javahashtablebytebyte map new hashtablebytebytebyte temp 1 1 0mapputtemp tempbyte temp2 1 1 0systemerrprintlnmapcontainskeytemp2does not work with containskey as the printed result is falsehashtableintegerinteger mapint new hashtableinteger integerint i 5mapintputi iint j 5systemerrprintlnmapintcontainskeyjworks the printed result is truei understand it has something to do with object reference but could not reach any solution after searchingis there anyway i can use hashtable to find key with array type i just want to test if a specific array is in hashtable as a keyany hits would be great thank,['java'] +1015002,indexnotfoundexception versus nullreferenceexception i have the following code that attempts to catch a null reference it then throws an exception with a clearer reason for the error specified in the message property what type of exception should it throw an indexoutofrangeexceptionvar existing thisgetbyitemidentityitemid int or longif existing null throw new indexoutofrangeexceptionthe specified item does not existvar price existingpriceor a nullreferenceexceptionvar existing thisgetbyitemidentityitemidif existing null throw new nullreferenceexceptionthe specified item does not existvar price existingpriceor should we have just let the exception run its coursevar existing thisgetbyitemidentityitemidvar price existingprice nullreferenceexception coming your waythe reason we tend not to do this last option is that the default nullreferenceexception is light on detail and just states object reference not set to an instance of an objectwhich to be honest could quite well be the most unhelpful error message in c,['c#'] +1015309,multiple keyboard layouts in an ios keyboard extension i am currently working on a keyboard extension for ios and am now wondering how to integrate multiple layouts support into the system settingsin the system settings the default en us keyboard has an additional menu indicated by a arrow to the right where you can choose from multiple keyboard layouts as you can see in the screenshot from the ios simulator below ios 91 13b137can this be achieved with a custom keyboard extension too i cannot find any documentation on it which may mean that it either is not possible using public apis or i am too stupid to use google i have searched quite a lot online but most of what i find is about setting the keyboard locale in the infoplist file or instructions on how to enable the system keyboard in different languages which are registered as different keyboards which i would like to avoidi can see an alternative if this does not work which would be to basically create multiple keyboard extensions in one wrapping app which include the same code base but define other layouts however this would look rather ugly clutter up the code and people will have to enable each layout individually which from my point of view is not the most userfriendly approach as stated above ios ships with different keyboards for different languages but i am trying to provide multiple keyboard layouts for the same language so this is not what i want,['ios'] +1015316,xctestcase ios ui tests dealing with uitableviews with many cells i am experimenting with the xcode 7 ui xctestcase testcases and i just stumbled onto an issue with one uiview in which i have a uitableview with many cells40when the app is running normally only the visible cells are rendered and there is no performance issue at allhowever if i run the app within the context of recording a xctestcase and i navigate to this screen the simulator freezes apparently because each single cell is rendered as if it were visible if i try to script the navigation manually and i run the xctestcase the testcase fails right after navigating to this screen exiting with a ui testing failure failed to get refreshed snapshot apparently again because all cells are being rendered and this does not finish in timei think this has to do with the fact that the testing framework builds an entire metamodel of the screen under thisplay adding each of the 40 cells into the view tree hierarchyi tried adding an expectation hoping this would give the testing container enough time to finish rendering all cells but this does not workis there a workaround for this is it somehow possible to skip building part of the ui tree hierarchy or somethingmy goal is being able to write ui tests for this screen,['ios'] +1015479,core data nsbatchdeleterequest appears to leave objects in context i have seen many questions regarding batch deletion in core data but none seem to address my issuei am creating an ios 9 swift app using core data at wwdc this year i attended the core data session and saw that i could use nsbatchdeleterequest to delete large numbers of objects directly from the persistent store this works for me for some objects but not others and i think it has something to do with my relationshipsi have an object graph consisting of subject and course where there is a onetomany relationship subjects may own as many courses as they wishthere is a courses relationship on subject with a delete rule of cascade as i want all courses associated with a subject to be deleted when a subject is deletedthe inverse is subject on course with a delete rule of nullify here i am a bit confused as to apples description of nullifyremove the relationship between the objects but do not delete either object this only makes sense if the department relationship for an employee is optional or if you ensure that you set a new department for each of the employees before the next save operationthat makes it pretty clear but why would the relationships be deleted but not either object if i delete a course i would like the course to be deleted and the relationship from the subject to the course to be deleted so that a fault to the deleted course will not appear in the nsset on subjects courses seti want to provide a way for all objects in an entity to be deleted when i try this by individually fetching and deleting each course courses are properly deleted and removed from the nsset of courses on a subjectsince i have no idea how many courses will be present and i want to ensure high performance in every situation i figured i would use batch deletion to delete all courses the problem is that while utilizing nsbatchdeleterequest to delete all subjects works fine deleting all courses along the way because of the cascade rule trying to delete all courses using this method appears to leave all objects in placei used nsbatchdeleterequest to delete all courses but then when i query the moc to see what subjects and courses still exist both courses are still returned and the subject owning them still has references to themin contrast when i fetch and delete each course individually my subsequent fetch properly thisplays an empty array for all courses and the courses relationship on the subject appears to have been properly modifiedyes i am saving the context after executing the request i suppose the context may not be notified of what the store does but then again deleting all subjects worked great what is going on here,['ios'] +1015616,cyclic dependency error after removing mathjaxrails so my gemfile currently looks likesource bundle edge rails instead gem rails github railsrailsgem rails 424 use sqlite3 as the database for active recordgem sqlite3 use scss for stylesheetsgem sassrails 50 use uglifier as compressor for javascript assetsgem uglifier 130 use coffeescript for coffee assets and viewsgem coffeerails 410 see for more supported runtimes gem therubyracer platforms ruby use jquery as the javascript librarygem jqueryrails turbolinks makes following links in your web application faster read more gem turbolinks build json apis with ease read more gem jbuilder 20 bundle exec rake docrails generates the api under docapigem sdoc 040 group docgem mathjaxrails 25 251gem bootstrapsass 33 3351 use activemodel has secure password gem bcrypt 317 use unicorn as the app server gem unicorn use capistrano for deployment gem capistranorails group developmentgroup development test do call byebug anywhere in the code to stop execution and get a debugger console gem byebugendgroup development do access an irb console on exception pages or by using console in views gem webconsole 20 spring speeds up development by keeping your application running in the background read more gem springendit works fine funny thing is as soon as i remove mathjaxrails and try to run in production mode i getusrlocalrvmgemsruby221gemsactionpack424libaction thispatchroutingurl forrb99in append features cyclic include detected argumenterror from usrlocalrvmgemsruby221gemsactionpack424libaction thispatchroutingurl forrb99in include from usrlocalrvmgemsruby221gemsactionpack424libaction thispatchroutingurl forrb99in block in moduleurlfor from usrlocalrvmgemsruby221gemsactivesupport424libactive supportconcernrb120in class eval from usrlocalrvmgemsruby221gemsactivesupport424libactive supportconcernrb120in append features from usrlocalrvmgemsruby221gemsactionview424libaction viewrailtierb41in include from usrlocalrvmgemsruby221gemsactionview424libaction viewrailtierb41in block 2 levels in classrailtie from usrlocalrvmgemsruby221gemsactivesupport424libactive supportlazy load hooksrb38in instance eval from usrlocalrvmgemsruby221gemsactivesupport424libactive supportlazy load hooksrb38in execute hook from usrlocalrvmgemsruby221gemsactivesupport424libactive supportlazy load hooksrb45in block in run load hooks from usrlocalrvmgemsruby221gemsactivesupport424libactive supportlazy load hooksrb44in each from usrlocalrvmgemsruby221gemsactivesupport424libactive supportlazy load hooksrb44in run load hooks from usrlocalrvmgemsruby221gemsactionpack424libaction controllerbaserb266in classbase from usrlocalrvmgemsruby221gemsactionpack424libaction controllerbaserb164in moduleactioncontroller from usrlocalrvmgemsruby221gemsactionpack424libaction controllerbaserb5in top required from rootstudysomeappcontrollersapplication controllerrb1in top required from usrlocalrvmgemsruby221gemsactivesupport424libactive supportdependenciesrb274in require from usrlocalrvmgemsruby221gemsactivesupport424libactive supportdependenciesrb274in block in require from usrlocalrvmgemsruby221gemsactivesupport424libactive supportdependenciesrb240in load dependency from usrlocalrvmgemsruby221gemsactivesupport424libactive supportdependenciesrb274in require from usrlocalrvmgemsruby221gemsactivesupport424libactive supportdependenciesrb360in require or load from usrlocalrvmgemsruby221gemsactivesupport424libactive supportdependenciesrb317in depend on from usrlocalrvmgemsruby221gemsactivesupport424libactive supportdependenciesrb233in require dependency from usrlocalrvmgemsruby221gemsrailties424librailsenginerb472in block 2 levels in eager load from usrlocalrvmgemsruby221gemsrailties424librailsenginerb471in each from usrlocalrvmgemsruby221gemsrailties424librailsenginerb471in block in eager load from usrlocalrvmgemsruby221gemsrailties424librailsenginerb469in each from usrlocalrvmgemsruby221gemsrailties424librailsenginerb469in eager load from usrlocalrvmgemsruby221gemsrailties424librailsenginerb346in eager load from usrlocalrvmgemsruby221gemsrailties424librailsapplicationfinisherrb56in each from usrlocalrvmgemsruby221gemsrailties424librailsapplicationfinisherrb56in block in modulefinisher from usrlocalrvmgemsruby221gemsrailties424librailsinitializablerb30in instance exec from usrlocalrvmgemsruby221gemsrailties424librailsinitializablerb30in run from usrlocalrvmgemsruby221gemsrailties424librailsinitializablerb55in block in run initializers from usrlocalrvmrubiesruby221libruby220tsortrb226in block in tsort each from usrlocalrvmrubiesruby221libruby220tsortrb348in block 2 levels in each strongly connected component from usrlocalrvmrubiesruby221libruby220tsortrb429in each strongly connected component from from usrlocalrvmrubiesruby221libruby220tsortrb347in block in each strongly connected component from usrlocalrvmrubiesruby221libruby220tsortrb345in each from usrlocalrvmrubiesruby221libruby220tsortrb345in call from usrlocalrvmrubiesruby221libruby220tsortrb345in each strongly connected component from usrlocalrvmrubiesruby221libruby220tsortrb224in tsort each from usrlocalrvmrubiesruby221libruby220tsortrb203in tsort each from usrlocalrvmgemsruby221gemsrailties424librailsinitializablerb54in run initializers from usrlocalrvmgemsruby221gemsrailties424librailsapplicationrb352in initialize from rootstudysomeconfigenvironmentrb5in top required from rootstudysomeconfigru3in require from rootstudysomeconfigru3in block in main from usrlocalrvmgemsruby221gemsrack164librackbuilderrb55in instance eval from usrlocalrvmgemsruby221gemsrack164librackbuilderrb55in initialize from rootstudysomeconfigruin new from rootstudysomeconfigruin main from usrlocalrvmgemsruby221gemsrack164librackbuilderrb49in eval from usrlocalrvmgemsruby221gemsrack164librackbuilderrb49in new from string from usrlocalrvmgemsruby221gemsrack164librackbuilderrb40in parse file from usrlocalrvmgemsruby221gemsrack164librackserverrb299in build app and options from config from usrlocalrvmgemsruby221gemsrack164librackserverrb208in app from usrlocalrvmgemsruby221gemsrailties424librailscommandsserverrb61in app from usrlocalrvmgemsruby221gemsrack164librackserverrb336in wrapped app from usrlocalrvmgemsruby221gemsrack164librackserverrb272in start from usrlocalrvmgemsruby221gemsrailties424librailscommandsserverrb80in start from usrlocalrvmgemsruby221gemsrailties424librailscommandscommands tasksrb80in block in server from usrlocalrvmgemsruby221gemsrailties424librailscommandscommands tasksrb75in tap from usrlocalrvmgemsruby221gemsrailties424librailscommandscommands tasksrb75in server from usrlocalrvmgemsruby221gemsrailties424librailscommandscommands tasksrb39in run command from usrlocalrvmgemsruby221gemsrailties424librailscommandsrb17in top required from binrails4in require from binrails4in main booting webrick rails 424 application starting in production on run rails server h for more startup options ctrlc to shutdown serverexitingwhy i just want to load mathjax from the mathjax cdn,['ruby-on-rails'] +1015812,merging sorted arrays of unequal length i have a project that requires me to merge two sorted arrays a and b and place the result in a new array of length alength blength i am tracking both the counter of my placement in all 3 arrays and the length of my arrays are unequal my convention is that if one array runs out before another the code will just dump the rest of the other array into the result arrayunfortunately the only way that i can check if the other array still contains elements is seen the for loop can anyone help me this should a relatively easy fix but i cannot think of a solutionpublic class two public static void mainstring args sample problem int var a 2355810171820 int var b 5678141517 final int a size 10 final int b size 7 final int c size 17 int var c new int17 int acount 0 int bcount 0 int ccount 0 for ccount 0 ccount c size ccount b runs out before a runs out if bcount b size acount a size dump rest of var a into var c var count var aacount acount problem bcount is equal to bsize and is triggering the break a runs out before b runs out else if acount a size bcount b size dump rest of var b into var c var count var bbcount bcount if acount a size bcount b size ccount c size break if var aacount var bbcount var count var aacount acount else if var aacount var bbcount var count var bbcount bcount else if var aacount var bbcount var count var aacount acount ccount var count var bbcount bcount for int i var c systemoutprinti,['java'] +1015887,color seaborn boxplot based in dataframe column name i would like to create a list of boxplots with the color of the box dependent on the name of the pandasdataframe column i use as inputthe column names contain strings that indicate an experimental condition based on which i want the box of the boxplot coloredi do this to make the boxplotssnsboxplotdata datadropna orienthpltshowthis creates a beautiful list of boxplots with correct names now i want to give every boxplot that has prog dmso in its name a red color leaving the rest as bluei tried creating a dictionary with column names as keys and colors as valuescolor for column in datacolumns if prog dmso in column colorcolumn red else colorcolumn blueand then using the dictionary as colorsnsboxplotdata datadropna orienth colorcolorcolumnpltshowthis does not work understandably there is no loop to go through the dictionary so i make a loopfor column in datacolumns snsboxplotdata datacolumn orienth colorcolorcolumnpltshowthis does make boxplots of different colors but all on top of each other and without the correct labels if i could somehow put these boxplot nicely in one plot below each other i would be almost at what i want or is there a better way,['python'] +1015900,how can i use azure file storage with web app service i have been struggling to find some resources that help explain how we use the file storage with web app servicethere are ways to use it with the old web roles check here however there is no onstart methods in azure web service,['c#'] +1016019,why xcode generated nsmanagedobject subclass contains always optional properties even if they are marked as nonoptional i have a core data entity named film and has a properties title and date i noticed that the generated nsmanagedobject subclass generate optional nsmanaged property even if i marked like non optional in core data inspectorcore data inspectornsmanagedobject subclassi can manually change it as nonoptional property or is a better choice to left it as optional why,['ios'] +1016050,memory allocation fails but why does it crash or does it i was experimenting with realloc giving it larger and larger sizes and checking whether the same block was reused or not int main void char newstr prevstr null size t newsize prevsize 0 printf we play with reallocn while 1 newsize prevsize 1 prevsize3 add 33 newstr reallocprevstr newsize if newstr null printf could not alloc newsizezu sorryn newsize break else printf newsizezu successfully allocedn newsize if newstr prevstr printf newstr prevstrtsame block reusedn else printf newstr prevstrtnew block allocedn prevstr newstr prevsize newsize return exit successas expected one eventually reaches a point where the size is too large and realloc cannot answer the request according to the manual realloc should return null and set errno enomem when it does not succeed this is not what happens when i run the above code on my machine a mac with darwin kernel version 1500instead of returning null the code crashes and saysmalloc mach vm mapsize153288611651584 failed error code3 error cannot allocate region set a breakpoint in malloc error break to debugcould not alloc newsize153288611651277 sorryis this normal something i did not understand when reading the man pagethis is not crucial for my code at the moment but i can imagine situations where i would like to test whether memory can be alloced without risking a crash is there a standard way of testing whether alloc will work without risking such crashadded after mystery is solved see answers below there is no crash just some system error message from malloc that gets in the way of the expected output see below on how to avoid that,['c'] +1016176,why is domain api deprecated in nodejs why is domain api deprecated in nodejs i found it handy to catch errors in context of a incoming web request rather than exception boiling up to the level of process also is there any alternative to domain apis that can be now be used,['javascript'] +1016192,why does search in gmail api return different result than search in gmail website i am using the gmail api to search emails from users i have created the following search queryticket after20151104 and fromme and intrashwhen i run this query in the browser interface of gmail i get 11 messages as expected when i run the same query in the api however i get only 10 messages the code i use to query the gmail api is written in python and looks like thissearchquery ticket after20151104 and fromme and intrashmessagesobj googlegetgmailv1usersmemessages dataq searchquery tokentokendataprint messagesobjresultsizeestimate 10i sent the same message on to another gmail address and tested it from that email address and to my surprise it does show up in an apisearch with that other email address so the trouble is not the email itselfafter endlessly emailing around through various testgmail accounts i think but not 100 sure that the browserinterface search function has a different definition of me it seems that in the apisearch it does not include emails which come from email addresses with the same name while these results are in fact included in the result of the browsersearch for example if pete kramer sends an email from to which both have their name set to pete kramer it will show in the browsersearch and it will not show in the apisearchcan anybody confirm that this is the problem and if so is there a way to circumvent this to get the same results as the browsersearch returns or does anybody else know why the results from the gmail browsersearch differ from the gmail apisearch al tips are welcome,['python'] +1016364,errorexecution failed for task aprocessdebuggoogleservices please fix the version conflict after updating my google play services to rev 28 i am getting this error im not sure why this is happening as it was working fine beforehere is my buildgradle fileapply plugin comandroidapplicationapply plugin comgooglegmsgoogleservicesandroid compilesdkversion 23 buildtoolsversion 2302defaultconfig applicationid commatsoltechpakistancurrentaffairs minsdkversion 10 targetsdkversion 23 versioncode 11 versionname 211buildtypes release multidexenabled true minifyenabled true proguardfiles getdefaultproguardfileproguardandroidtxt proguardrulespro dependencies compile filetreeinclude jar dir libs compile filessrcmainlibsuniversalimageloader193jar compile filessrcmainlibsnineoldandroids240jar compile comandroidsupportappcompatv72310 compile comandroidsupportsupportv42310 compile comandroidsupportcardviewv72310 compile comgithubksoichiroandroidobservablescrollview150 compile comgoogleandroidgmsplayservices830 compile commcxiaokevolleylibrary1018 compile comgoogleandroidgmsplayservicesanalytics830andbuildscript repositories jcenterdependencies classpath comandroidtoolsbuildgradle130 classpath comgooglegmsgoogleservices140beta3 note do not place your application dependencies here they belong in the individual module buildgradle filesallprojects repositories jcenterso can anyone please tell me where is the problem as the code was working fine before the update of googleplayservices,['android'] +1017051,compare array values with others values from the same array what iam trying to achieve is that it will loop trough the array then it will look if the items in the array are the same on three points product id the size value and the color valuei want to create a new array where the items are listed the only thing i donat want is the duplicated values i want that the duplicated values if they are the same on those three points that the quantity will be count together like if i have 3 items same product id same size and same color and both of the three i ordered 3 items in my new array this is just standing 1 time and the quantity will be 9 so there will be no duplicated values in my new arraycurrent loop foreachorders as key order foreachorderorderproducts as key value echo pre print rvalueattributes echo pre results in the the following arrayarray id 2 product id 4 order id 2 name swag3 description haha price 1995 proceeds 10 quantity 2 attributes id1namesizevaluexsactive1id8namecolorvaluewitactive1array id 3 product id 3 order id 3 name swag2 description lol price 1995 proceeds 10 quantity 2 attributes id2namesizevaluesactive1id7namecolorvaluezwartactive1array id 4 product id 3 order id 4 name swag2 description lol price 1995 proceeds 10 quantity 1 attributes id2namesizevaluesactive1id7namecolorvaluezwartactive1sort of what iam looking forarray id 2 product id 4 order id 2 name swag3 description haha price 1995 proceeds 10 quantity 2 attributes id1namesizevaluexsactive1id8namecolorvaluewitactive1array id 3 product id 3 order id 3 name swag2 description lol price 1995 proceeds 10 quantity 3 attributes id2namesizevaluesactive1id7namecolorvaluezwartactive1solutionnote it is blade php as frontendbackendorder is the array with productsitems foreachorders as key order foreachorderorderproducts as op i product productfindorfailopproduct idtoarray attributes opattributes quantityopquantity matchedresult false count countitems fora 0 a count a items with the same product id in the item array ifitemsaproductid iproductid check if the attributes are also the same ifitemsaattributes iattributes the attributes ar ethe same so up the quantity itemsaquantity iquantity matchedresult true continue if its right there are no other matches ifmatchedresult false only push item if there is not a match items i frontenddiv classtableresponsive table classtable tablestriped thead tr thproductth thquantityth tr thead tbody foreachitems as item tr tditemproductname ifcountitemattributes 0 small foreachitemattributes as att attname attvalue endforeach small endiftd tditemquantitytd tr endforeach tbody tablediv,['php'] +1017116,cache invalidation and synchronisation angularbackend too introi have got a complex and long lasting query on the backend feeding back the angular app on the frontendcurrently the angular app uses the cached data on the backend rather than reading directly from the complex query which would take few minutes the cache gets warm every morning and every nightas users make changes to the ui and save the data which is then passed onto the server side and saved to database at that time the ui is up to date until the user refreshes the page at the same time database is up to date but the cache is stale so when the user refreshes the page the stale cache values are thisplayed on the pagemore info i am now thinking of ways to refresh the cache and any advice from more experienced folks would be most welcomemy idea is to refresh the cache by a cache job one at a time which is queued as soon as user saves something the job will have the relevant info what changed and the whole cache would not have to be recalculated but rather just the bit which changedquestion part what technique can i use to keep the user up to date with the data even if the user refreshes the page should i save the deltas on the client side in a form of indexeddb or localstorage at the same when the data is sent to server so when the page refreshes the user reads the data from the localstorage or indexed dbi m still thinking this trough obviously i do not have much experience in this any comments on the directions i have taken so far basically i can change anything including backendfrontendcaching it is still in the poc phase i m just trying to be as informed as possible to what worked for other peopleupdatelittle more background i am working on a index like page so there are more than one records that can be edited inline also i am doing some transformation of the flat db records on the backend before dumping them into the map like structure and passing it to the frontend in a form of json,"['javascript', 'java']" +1017310,what is a difference between traditional loop and foreach loop i wonder if there is a difference between thesearraylistexample list new arraylistexample1forint i 0 i listsize i listgetidosomething2forexample example list exampledosomethingif there is not any difference which one is more common or efficient,['java'] +1017492,why does not lldb forward my environment variable anymore i am working on a patch for ffmpeg and need to debug my code i am loading an external library and in order to test different library versions i have them in different folders to select which one i want to use i have been using dyld library pathpathtolibdir ffmpeg and that works okay but when i try it within lldb it crashes saying dyld library not loaded and reason image not found this used to work prexcode 71 but i just recently upgraded and it stopped workingheres my mvceinclude stdiohinclude stdlibhint main char str getenvdyld library path if str putsstr else putsnull return 0running this program as follows produces the output aoutnull dyld library pathtmp aouttmpthat looks okay but when i try to use lldb it fails dyld library pathtmp lldb aoutlldb target create aoutcurrent executable set to aout x86 64lldb runprocess 54255 launched aout x86 64nullprocess 54255 exited with status 0 0x0trying to set the environment variable inside lldb workslldb aoutlldb target create aoutcurrent executable set to aout x86 64lldb env dyld library pathtmplldb runprocess 54331 launched aout x86 64tmpprocess 54331 exited with status 0 0x0 lldb version it is from xcode 71 lldb versionlldb3404110question is this an intended new feature or is this a new bug in lldb or am i totally crazy and this never used to work i am quite positive lldb used to forward the dyld library path environment variable so how come it is not anymoreedit this is on os x 101,['c'] +1017498,how to use a requires clause with lambda functor arguments is there any way to apply a general requires clause to the arguments of a lambda functor suppose i have two constraints c1 and c2 that i want checked against an argument i would have expected the following to work since a similar syntax is allowed for functionsauto x requires c1decltypex c2decltypex but this would not compile with gcc 6,['c++'] +1017695,pdo update syntax error or access violation i am new in pdo writing an update querysql update users setuname uname role role fname fname email email mobile1 mobile1 mobile2 mobile2 education education division division thistrict thistrict sub thistrict sub thistrict address address looking for looking where id id sql update users setunamerolefnameemailmobile1mobile2educationdivisionthistrictsub thistrictaddresslooking for where id st connpreparesql ressql stquerystring params array uname uname role role fname fname email email mobile1 mobile1 mobile2 mobile2 education edu division division thistrict thistrict sub thistrict sub thistrict address address looking looking id id resparams params r stexecuteparams and gettingsqlstate420 syntax error or access violation 1064 you have an error in your sql syntax check the manual that corresponds to your mariadb server version for the right syntax to use near uname role 2fname a full nameemail rahm at line 1can anybody tell me whats wrong in my codehere is my table structure,"['php', 'mysql', 'sql']" +1017729,3d touch shortcut load other url i have implemented three 3d touch actions lets name them apptouch1 apptouch2 and apptouch3this is the code in my appdelegate filefunc applicationapplication uiapplication performactionforshortcutitem shortcutitem uiapplicationshortcutitem completionhandler bool void ifshortcutitemtype apptouch1 myvariablesurl else ifshortcutitemtype apptouch2 myvariablesurl else ifshortcutitemtype apptouch3 myvariablesurl this is my myvariables class for nowstruct myvariables static var url this is the code of my viewcontroller classiboutlet var containerview uiviewvar webview uiwebviewvar loadedurl stringoverride func prefersstatusbarhidden bool return trueoverride func loadview superloadview selfwebview uiwebview selfview selfwebviewoverride func viewdidload superviewdidload loadfunc load let requesturl nsurlstring myvariablesurl let request nsurlrequesturl requesturl selfwebviewloadrequestrequest loadedurl myvariablesurloverride func didreceivememorywarning superdidreceivememorywarning thispose of any resources that can be recreatedhowever it always loads the default url even if the app was closed before i tried events like viewdidappear and viewwillappear also but this did not worki think this is very simple for an ios developer i tried to start with ios and have this problem,['ios'] +1017848,navigation bar moves when admob interstital showed when i show interstital ad status bar fades away and navigation bar moves up all content under navigation bar moves up to when i close the ad everything moves down it looks really strange and glitchyi am using navigation controller in storyboard with show navigation bar property oncode to show interstital ad in appdelegatem fileselfinterstitialad presentfromrootviewcontrollerselfwindowrootviewcontrollerbasically i need everything to stay in place without moving when i present interstital ad,['ios'] +1018304,what happened to the esprimasix npm module my npm project has the esprimasix npm module as a transitive dependency recently it has become impossible to download as seen in the following output from npm installnpm err 404 not foundnpm err 404 npm err 404 esprimasix is not in the npm registrynpm err 404 you should bug the author to publish itnpm err 404 it was specified as a dependency of syntaxerrornpm err 404 npm err 404 note that you can also install from anpm err 404 tarball folder or http url or git urlon the npm site esprimasix cannot be foundbut googles cache for the page shows that it used to exist cd1hlenctclnkglukclientubuntuso why did the module become unavailable and what is the best way to get my project building againedit in the end i updated the dependency which depended on esprimasix to a later version which did not need it,['javascript'] +1018514,is it normal that javascript can create otherwise invalid dom somewhat by accident i found out that a span inserted directly inside a tbody stays in place when done with javascript insertbefore where such invalid dom would if created with literal html lead to the span being placed before the entire tablei expected either the same behaviour as with literal html or some dom exception being throwneg this htmltable theadtrthtable headerthtdthead tbody spanfrom html rarr goes upspan trtdtable contentstdtr tbodytablewith this javascriptvar span documentcreateelementspan tbody documentqueryselectortbodyspaninnerhtml created with js rarr stays in placetbodyinsertbeforespan tbodyqueryselectortrrenders created with js a stays in place between the header and the first row the original literal span moves outside of the tableis this normal and canshould i count on this it behaves the same in ff chrome opera ie 9 not tested belowalso is there a way to query the dom whether content of a certain type would under normal circumstances be valid at a certain point in the dom this is actually what i wanted to do when i found out about this quirk which it is imhothe fiddle is here,"['javascript', 'html']" +1018598,rails and using gulpgrunt to inject code to views how would i use one of the gulpgrunt plugins that compile some type of asset and then replace a custom comment line in a view with either a set of script or link tags etc in rails so that the view file is not seen as changed everytime that happens by my version control system,['ruby-on-rails'] +1018843,wildfly 901 wflyctl0158 handler console is not found suddenly after working fine for some time wildfly 901 and also 902 seem to have somehow lost the console handler for loggingwhen trying to debug an application from netbeans 802 the console window showserror stderr default task14 handler javautilloggingconsolehandler is not definedas last entry and the web application seems to be stuck before actually startingin wildflys management console there seems to be a root logger using 2 handlers console and fileboth handlers seem to be existing in standalonefullxml subsystem xmlnsurnjbossdomainlogging30 consolehandler nameconsole level nameinfo formatter namedformatter namecolorpattern formatter consolehandler periodicrotatingfilehandler namefile autoflushtrue formatter namedformatter namepattern formatter file relativetojboserverlogdir pathserverlog suffix valueymmdd append valuetrue periodicrotatingfilehandler rootlogger level nameinfo handlers handler nameconsole handler namefile handlers rootlogger subsystem when changing config in the management console i can delete the handlers out of the root logger then i can save but taking them in again seems impossible since i get the wflyctl0158 telling that the handler would not be defined,['java'] +1018901,xctestcase wait for app to idle my uitest fails because the test waits endless until the app idles i can not see that there is anything happening in the background like a loading spinnerit just occurs on one tab all others tabs are tapable but the test fails on screen 3 i i click on another tab after the test is caught on screen 3 the test resumes and finishes successfullyany ideas voidtestexample xcuielementquery tabbarsquery selfapptabbars tabbarsquerybuttonsscreen2 tap tabbarsquerybuttonsscreen3 tap tabbarsquerybuttonsscreen1 tap tabbarsquerybuttonsscreen4 tap,['ios'] +1019136,execute scripts returned from each synchronously but without delay in order of completion the situation is that i am dynamically loading a set of scripts from an api that i then call via eval i do not care which order the scripts are called but i do not want any of them to be called at the same time that is scripts a b and c can be returned in order c b a and i want to begin evalc immediately when c is returned but i want evalb to wait until evalc is completedwithout getting into the fully hairy code here is the heart of it where instances is a string arrayeachinstances function index instance var apiurl instance getjsonapiurl functiondata except i do not want to eval here as evaluations may overlap evaldatascript from what i understand i could use when to wait until all were complete but that would waste time as i do not need to wait until all are downloaded in order to begin their execution,"['javascript', 'jquery']" +1019147,firebase and new google signin on android i am trying to add support for the new google signin announced as part of play services 830 i successfully configured the project and i am getting a token from the googleapiclient but firebase is returning an invalid credentials error when calling refauthwithoauthtokengoogle tokengoogle signin is working but that requires a separate permission which is a pain when developing for marshmallowfirebase android tutorial has a google signin sample and my feeling is that they dont have support for the new google signin yet has anyone tried the new google signin in connection with firebase and got it to work,['android'] +1019207,how to print the value of a tensor object in tensorflow i have been using the introductory example of matrix multiplication in tensorflowmatrix1 tfconstant3 3matrix2 tfconstant22product tfmatmulmatrix1 matrix2and when i print the product it is thisplaying it as a tensorobjectobviouslyproducttensorflowpythonframeworkopstensor object at 0x10470fcd0but how do i know the value of productthe following does not helpprint producttensormatmul0 shapetensorshapedimension1 dimension1 dtypefloat32i know that graphs run on sessions but is not there any way i can check the output of a tensorobject without running the graph in a session,['python'] +1019228,why is any running slower than using loops i have been working in a project that manage big lists and pass the lists trough a lot of tests in order to validate or not each word of the list the funny thing is that each time that i have used the faster tools or generators like the itertools module and i make some tests they seem to be slowerfinally i decided to ask the question because it is possible that i be doing something wrong the following code will try to test the performance of the any function vs loopsusrbinpython3import timefrom unicodedata import normalize import a large list of tests like 300mb the list contains words each one separated in a linepathtestsstarttimetimewith openpath encodingutf8 modert as f tests listfreadprintfile reading done in secondsformattimetime startstarttimetimetests listlinestrip for line in normalizenfctests listsplitlinesprintstring formalization and list strip done in secondsformattimetimestartprint stringsformatlentests list test to check if any is fasterprinttesting the performance of anyunallowed combinationsabacadaeafagahaiafaxaertrzbtduizipuyioikiliwpdef combination is validstring if anycombination in string for combination in unallowed combinations return false return truedef combination is valid2string for combination in unallowed combinations if combination in string return false return truestarttimetimefor string in tests list combination is validstringprintcombination is valid ended in secondsformattimetimestartstarttimetimefor string in tests list combination is valid2stringprintcombination is valid2 ended in secondsformattimetimestart the code i posted is pretty representative of the kind of tests i do with my program and if we take a look to the resultsfile reading done in 022988605499267578 secondsstring formalization and list strip done in 6803032875061035 seconds38709922 stringstesting the performance of anycombination is valid ended in 8074802565574646 secondscombination is valid2 ended in 4169514226913452 secondsfile reading done in 024268722534179688 secondsstring formalization and list strip done in 6720442771911621 seconds38709922 stringstesting the performance of anycombination is valid ended in 7905265760421753 secondscombination is valid2 ended in 42248007435303 secondsi find kinda amazing that using the function with loops its half faster than using any what would be the explanation to this am i doing something wrongi interpret the results as if any generated a list of all the results and check if they are true or false at the end in the other hand the function that uses loops after a result is created it is tested so it can exit earlier without generating unusefull testswhat do you think i used python34 under gnulinux,['python'] +1019266,debugger shows npos4294967295 when viewing string variables my problem is basically that whenever i debug using visual studio 2015 community edition on windows 10 machine and i try to hover over a variable or look at a variable in the locals or autos section of the debug view i do not see the actual data saved in the variable this is a problem i have seen with both strings and vectors for strings it will show npos4294967295and if you keep clicking the drop down arrows you will eventually get to the actual string saved in that variable only after digging into the internal structure of the variable like std string alloc and mypair and myval etc same for vectors has anyone ever experienced this problem or knows how to fix it,['c++'] +1019552,explicit qualification in c declaration the following namespace definition fails to compile when the first declaration is commented out if the first declaration of foo is uncommented then it compiles just finenamespace y void foo void yfoothe relevant part in the standard a83a1 sayswhen the declaratorid is qualified the declaration shall refer to a previously declared memberi understand that this rule prevents the introduction of names into other namespaces i wonder if that rule could be relaxed to allow for qualifiedids referring to the current namespace,['c++'] +1019699,how to avoid the specific feature versions in eclipse target definitions i have an osgi project that is split into 3 repositories each repository has its own build into p2 repository with tychorepo1 p2 repo 1repo2 p2 repo 2repo3 p2 repo 3also each repository has a target definition file that includes the bundles from third party p2 repositories and from another project repositories p2 repo1 p2 repo 2 or p2 repo 3 above repo2 contains a dependency to repo1 bundles repo3 has dependencies to the repo1 and repo2 bundlesrepo1 target definition eclipse orbit p2repo2 target definition eclipse orbit p2 p2 repo1repo3 target definition eclipse orbit p2 p2 repo1 p2 repo2now i have the following problem after building the first repository the p2 repo1 repository updated and contains the feature with the new snapshot versions the target definitions of repo2 and repo3 depend on the previous snapshot version of repo1 bundles and building these repositories is impossible without updating the appropriate target definitions in eclipse there are update button in target editor location includeallplatformsfalse includeconfigurephasetrue includemodeplanner includesourcetrue typeinstallableunitunit idcommyproductfeatureapigamefeaturegroup version100201509251400unit idcommyproductfeatureimplgamefeaturegroup version100201509251400repository locationhttptargetrepositorylocationso it is impossible automatically build all 3 repos so the build process becomes too complicatedcommit the changes in the first repo and build it with jenkinsupdate the target definition of repo2 to point it to the new version of repo 1 featurecommit this update in repo2 and build it with jenkinsetci am thinking now to use git submodules for integrating these 3 repos to avoid the p2 repositories or move all in one repository,['java'] +1019808,can initializing expression use the variable itself consider the following codeinclude iostreamstruct data int x ydata filldata data datax3 datay6 return dataint main data dfilld stdcout x dx y dy nhere d is copyinitialized from the return value of fill but fill writes to d itself before returning its result what i am concerned about is that d is nontrivially used before being initialized and use of uninitialized variables in someall cases leads to undefined behaviorso is this code valid or does it have undefined behavior if it is valid will the behavior become undefined once data stops being pod or in some other case,['c++'] +1019859,why can this css snippet draw a triangle i saw the following code without any commentstriangle bordercolor transparent borderbottomcolor green borderstyle solid borderwidth 300px bordertopwidth0 height 0 width 0div classtriangledivthe result is a green triangle does anyone have ideas about why it works,['css'] +1019894,email address splitting so i have a string that i need to split by semicolonsemail address onetwohotmailcomsomethingexamplecomboth of the email addresses are validso i want to have a liststring of the followingonetwohotmailcomsomethingexamplecombut the way i am currently splitting the addresses is not workingvar addresses emailaddrestringsplitnew stringsplitoptionsremoveemptyentries selectx xtrimtolistbecause of the multiple characters i end up with invalid email addressesi have tried a few different ways even going down working out if the string contains quotes and then finding the index of the characters and working it out that way but it is a real paindoes anyone have any better suggestions,['c#'] +1019990,create pdf document for printing in qt from template i write an application when user inserts data in a dialog window document title sender name and address etc and then my application should generate a pdf file from this user datapdf file should have defined layout something like thisi tried to do this with qpdfwriter but have problems aligning text in pdf heres my codeinclude qapplicationinclude qtcoreinclude qprinterinclude qpdfwriterinclude qpainterqstring currdate qdate date qdatecurrentdate return datetostringddmmyvoid pdfqstring filename qpdfwriter writerfilename writersetpagesizeqpagedpaintdevicea4 writersetpagemarginsqmargins30 30 30 30 qpainter painterwriter paintersetpenqtblack paintersetfontqfonttimes 10 qrect r painterviewport qstring citydate city citydate currdate painterdrawtextr qtalignright citydateqstring sender company xyznsender random street 12314ansender 1231232 citynpainterdrawtextr qtalignleft sender painterendint mainint argc char argv qapplication aargc argv pdfexample1pdf return aexecdate printed to pdf is on the left buti have trouble with further text how to move painter todifferent locations to print also the sender name document titleand document content inside the page is the translate method of the painter enough or can it be done simpleri do not know how to handle page breaks in case the document content will be very long will spread on 2 or more pagesthanksediti also tried the qtextdocument approach but its hard to write any document with almost any example available on the web i came up only with thisvoid pdfqstring filename qprinter printerqprinterprinterresolution printersetoutputformatqprinterpdfformat printersetpapersizeqprintera4 printersetoutputfilenamefilename printersetpagemarginsqmarginsf30 30 30 30 qfont headerfonttimes new roman 8 qfont titlefonttimes new roman 14 qfontbold qtextcharformat txtformat qtextcharformat qtextdocument doc docsetpagesizeprinterpagerectsize qtextcursor cursor new qtextcursordoc txtformatsetfontheaderfont cursorinserttextcompany xyz txtformat cursormovepositionqtextcursorright qtextcursorendofline qtextcursorkeepanchor 10 cursorinserttextcurrdate txtformat docprintprinter,['c++'] +1020025,using flexbox with angular 2 components i want to update visual sidegrid colors of my angular 2 application old layout was build with bootstrap 4 which i do not really need anymore i decided to go for plain css3 and build grid with flexbox i made a preview of this grid on codepenhowever implementation in project is hard and i am now stuck let us consider an exampleimport component from angular2angular2component selector somecomponent template aside classcol4 mainasideaside section classmainsection centersection export class somecomponent if i bootstrap this component within for example container i may get this resultbody container is flex parent div classcontainer somecomponent mainaside and mainsection should be flex children aside classmainasideaside section classmainsection centersection somecomponent divbodyas you can see the flex chain parent child is broken because of component selector between them i menaged to fix this by adding styles thisplay flex width 100 to component selector from chrome dev tools however i do not know how to make this work from code perspective nor is it the best way to do soi would really appreciate any help because i have no idea how to fix this with the exception of not using flexboxi am using angular 200alpha44and yes i am aware of angulars alpha state,"['javascript', 'css']" +1020090,clangformat line breaks i am looking for a clangformat setting to prevent the tool from removing line breaksfor example i have my columnlimit set to 120 and heres what happens when i reformat some sample codebeforeinclude vectorinclude stringstdvectorstdstring get vec return stdvectorstdstring this is a test some of the lines are longer than other but i would like to keep them on separate lines int main auto vec get vecafterinclude vectorinclude stringstdvectorstdstring get vec return stdvectorstdstringthis is a test some of the lines are longer than other but i would like to keep them on separate linesint main auto vec get vecwhat i would like is that the tool breaks lines that are over 120 characters but does not decide to combine lines just because they are less than 120 charactersis there such an option nothing in the docs stood out to me,['c++'] +1020101,are end1 iterators for stdstring allowed is it valid to create an iterator to endstr1 for stdstringand if it is not why is not itthis question is restricted to c11 and later because while prec11 the data was already stored in a continuous block in any but rare poc toyimplementations the data did not have to be stored that wayand i think that might make all the differencethe significant difference between stdstring and any other standard container i speculate on is that it always contains one element more than its size the zeroterminator to fulfill the requirements of c str21471 basic string accessors stringaccessorsconst chart c str const noexceptconst chart data const noexcept1 returns a pointer p such that p i operatori for each i in 0size 2 complexity constant time 3 requires the program shall not alter any of the values stored in the character arraystill even though it should imho guarantee that said expression is valid for consistency and interoperability with zeroterminated strings if nothing else the only paragraph i found casts doubt on that2141 basic string general requirements stringrequire4 the charlike objects in a basic string object shall be stored contiguously that is for any basic string object s the identity sbegin n sbegin n shall hold for all values of n such that 0 and ssizeall quotes are from c14 final draft n3936related legal to overwrite stdstrings null terminator,['c++'] +1020222,flaskadmin form constrain value of field 2 depending on value of field 1 one feature i have been struggling to implement in flaskadmin is when the user edits a form to constrain the value of field 2 once field 1 has been setlet me give a simplified example in words the actual use case is more convoluted then i will show a full gist that implements that example minus the constrain featurelet us say we have a database that tracks some software recipes to output reports in various formats the recipe table of our sample database has two recipes serious report ascii artto implement each recipe we choose one among several methods the method table of our database has two methods tabulate results pretty printeach method has parameters the methodarg table has two parameter names for tabulate results rows thisplay total and two parameters for pretty print embellishment character lines to jumpnow for each of the recipes serious report ascii art we need to provide the value of the arguments of their respective methods tabulate results pretty printfor each record the recipearg table lets us select a recipe that is field 1 for instance serious report and an argument name that is field 2 the problem is that all possible argument names are shown whereas they need to be constrained based on the value of field 1 what filtering constraining mechanism can we implement such that once we select serious report we know we will be using the tabulate results method so that only the rows and thisplay total arguments are availablei am thinking some ajax wizardry that checks field 1 and sets a query for field 2 values but have no idea how to proceedyou can see this by playing with the gist click on the recipe arg tab in the first row serious report if you try to edit the methodarg value by clicking on it all four argument names are available instead of just two full gist please run thisfrom flask import flaskfrom flask admin import adminfrom flask admincontrib import sqlafrom flask sqlalchemy import sqlalchemyfrom sqlalchemy import column foreignkey integer stringfrom sqlalchemyorm import relationship create applicationapp flask name create dummy secrey key so we can use sessionsappconfigsecret key 123456790appconfigsqlalchemy database uri sqlitea sample databasesqliteappconfigsqlalchemy echo truedb sqlalchemyapp create admin appadmin adminapp nameconstrain values template modebootstrap3 flask viewsapproutedef index return a hrefadminclick me to get to adminaclass methoddbmodel tablename method mid columninteger primary keytrue method columnstring20 nullablefalse uniquetrue methodarg relationshipmethodarg backrefmethod recipe relationshiprecipe backrefmethod def str self return selfmethodclass methodargdbmodel tablename methodarg maid columninteger primary keytrue mid columnforeignkeymethodmid ondeletecascade onupdatecascade nullablefalse methodarg columnstring20 nullablefalse uniquetrue recipearg relationshiprecipearg backrefmethodarg inline models method def str self return selfmethodargclass recipedbmodel tablename recipe rid columninteger primary keytrue mid columnforeignkeymethodmid ondeletecascade onupdatecascade nullablefalse recipe columnstring20 nullablefalse indextrue recipearg relationshiprecipearg backrefrecipe inline models method def str self return selfrecipeclass recipeargdbmodel tablename recipearg raid columninteger primary keytrue rid columnforeignkeyreciperid ondeletecascade onupdatecascade nullablefalse maid columnforeignkeymethodargmaid ondeletecascade onupdatecascade nullablefalse strvalue columnstring80 nullablefalse inline models recipe methodarg def str self return selfstrvalueclass methodargadminsqlamodelview column list method methodarg column editable list column listclass recipeadminsqlamodelview column list recipe method column editable list column listclass recipeargadminsqlamodelview column list recipe methodarg strvalue column editable list column listadminadd viewrecipeargadminrecipearg dbsession more submenuadminadd viewsqlamodelviewmethod dbsession categorysee other tablesadminadd viewmethodargadminmethodarg dbsession categorysee other tablesadminadd viewrecipeadminrecipe dbsession categorysee other tablesif name main dbdrop all dbcreate all dbsessionaddmethodmid1 methodtabulate results dbsessionaddmethodmid2 methodpretty print dbsessioncommit dbsessionaddmethodargmaid1 mid1 methodargrows dbsessionaddmethodargmaid2 mid1 methodargthisplay total dbsessionaddmethodargmaid3 mid2 methodargembellishment character dbsessionaddmethodargmaid4 mid2 methodarglines to jump dbsessionaddreciperid1 mid1 recipeserious report dbsessionaddreciperid2 mid2 recipeascii art dbsessioncommit dbsessionaddrecipeargraid1 rid1 maid2 strvaluetrue dbsessionaddrecipeargraid2 rid1 maid1 strvalue12 dbsessionaddrecipeargraid3 rid2 maid4 strvalue3 dbsessioncommit start app apprundebugtrue,['python'] +1020406,publishing from visual studio 2015 i am trying to publish my aspnet 5 mvc6 application to godaddy server from visual studio 2015 i have imported publish profile from my server and i am able to validate the connection however when i publish my app i have the following errorerror user unauthorizedweb deployment task failed connected to the remote computer x using the web management service but could not authorize make sure that you are using the correct user name and password that the site you are connecting to exists and that the credentials represent a user who has permissions to access the sitethe credentials are valid i can publish vs2013 sample project from vs2015 but i can not publish vs2015 sample project as well as my app from vs2015 with the same credentialsthe user is an admin on the server,['asp.net'] +1020571,how is 0 thistinguished from other integers when initializing nullptr t as i understand stdnullptr t can be initialized from nullptr as well as from 0 but at the same time the third initialization below does not work despite 5 has the same type as 0include memoryint main stdnullptr t null10 stdnullptr t null2nullptr stdnullptr t null35 error cannot convert ainta to astdnullptr ta in initializationhow does this work ie how does the standard library thistinguish 0 from 5 at compilation time if these literals are not template argumentscan one create a custom class which would similarly thistinguish arguments of its constructor at compilation time not using stdnullptr t for this,['c++'] +1020629,why does sleep500 cost more than 500ms i used sleep500 in my code and i used gettickcount to test the timing i found that it has a cost of about 515ms more than 500 does somebody know why that is,['c++'] +1020689,how to publish aspnet core app to ftp server visual studio publish only supports importing web deployis there a workaround,['asp.net'] +1020695,index of longest run c i am trying to solve this questionwrite a function that finds the zerobased index of the longest run in a string a run is a consecutive sequence of the same character if there is more than one run with the same length return the index of the first onefor example indexoflongestrunabbcdcbba should return 6 as the longest run is d and it first appears on index 6following what i have doneprivate static int indexoflongestrunstring str char array1 strtochararray arraysortarray1 comparer comparer new comparer int counter 1 int maxcount 0 int idenxof 0 for int i 0 iarray1length1 i if comparercomparearray1iarray1i1 0 counter else ifmaxcount counter maxcount counter idenxof i counter 1 counter 1 return idenxof public class comparer icomparerchar public int comparechar firstchar char nextchar return firstcharcomparetonextchar the problem is that when i get to the last index for example abbccawhich is a in this case and when i14 taking this string as example and when iarray1length1 statment is false the for loop jumps directrly to return indexof and return the wrong index i am trying to find out how to push the forloop to continue the implementation so idenxof could be changed to the right index any help please,['c#'] +1020712,djangopyodbcazure rollback error with previously working configuration line 389 i have been using djangopyodbcazure for a while on linux along with pydobc freetds and unixodbc to connect django to sql server 2014 i ran into this problem with an application that had been working fine and am having trouble debugging it to reproduce the problem i started a brand new django app to keep things simple heres my virtualenvazuretestvagrantvagrant azuretest pip freezedjango186djangopyodbcazure1830pyodbc3010heres my database config to connect to sql serverdatabases default engine sql serverpyodbc host myservercom port 1433 name my db user my db user password mypw autocommit true options driver freetds autocommit true unicode results true host is server true extra params tds version72 and i created a simple modelspyclass testtempmodelsmodel tempdate modelsdatefieldthis set up has been working fine in a fairly complex django project which can still select to this same database however whenever i try to do an update or migration i have been getting this errorazuretestvagrantvagrant azuretest managepy migrate homeoperations to perform apply all migrations homerunning migrations rendering model states done applying home01 initialtraceback most recent call last file homevagrantvirtualenvsazuretestlibpython34sitepackagessql serverpyodbcbasepy line 389 in set autocommit selfconnectionrollbackpyodbcerror hy0 the driver did not supply an errorthe above exception was the direct cause of the following exceptiontraceback most recent call last file managepy line 10 in module execute from command linesysargv file homevagrantvirtualenvsazuretestlibpython34sitepackagesdjangocoremanagement init py line 354 in execute from command line utilityexecute file homevagrantvirtualenvsazuretestlibpython34sitepackagesdjangocoremanagement init py line 346 in execute selffetch commandsubcommandrun from argvselfargv file homevagrantvirtualenvsazuretestlibpython34sitepackagesdjangocoremanagementbasepy line 394 in run from argv selfexecuteargs cmd options file homevagrantvirtualenvsazuretestlibpython34sitepackagesdjangocoremanagementbasepy line 445 in execute output selfhandleargs options file homevagrantvirtualenvsazuretestlibpython34sitepackagesdjangocoremanagementcommandsmigratepy line 2 in handle executormigratetargets plan fakefake fake initialfake initial file homevagrantvirtualenvsazuretestlibpython34sitepackagesdjangodbmigrationsexecutorpy line 110 in migrate selfapply migrationstatesmigration migration fakefake fake initialfake initial file homevagrantvirtualenvsazuretestlibpython34sitepackagesdjangodbmigrationsexecutorpy line 154 in apply migration selfrecorderrecord appliedmigrationapp label migrationname file homevagrantvirtualenvsazuretestlibpython34sitepackagesdjangodbmigrationsrecorderpy line 67 in record applied selfmigration qscreateappapp namename file homevagrantvirtualenvsazuretestlibpython34sitepackagesdjangodbmodelsquerypy line 348 in create objsaveforce inserttrue usingselfdb file homevagrantvirtualenvsazuretestlibpython34sitepackagesdjangodbmodelsbasepy line 734 in save force updateforce update update fieldsupdate fields file homevagrantvirtualenvsazuretestlibpython34sitepackagesdjangodbmodelsbasepy line 759 in save base with transactionatomicusingusing savepointfalse file homevagrantvirtualenvsazuretestlibpython34sitepackagesdjangodbtransactionpy line 186 in enter connectionset autocommitfalse file homevagrantvirtualenvsazuretestlibpython34sitepackagesdjangodbbackendsbasebasepy line 295 in set autocommit self set autocommitautocommit file homevagrantvirtualenvsazuretestlibpython34sitepackagessql serverpyodbcbasepy line 390 in set autocommit selfconnectionautocommit autocommit file homevagrantvirtualenvsazuretestlibpython34sitepackagesdjangodbutilspy line 98 in exit sixreraisedj exc type dj exc value traceback file homevagrantvirtualenvsazuretestlibpython34sitepackagesdjangoutilssixpy line 658 in reraise raise valuewith tracebacktb file homevagrantvirtualenvsazuretestlibpython34sitepackagessql serverpyodbcbasepy line 389 in set autocommit selfconnectionrollbackdjangodbutilserror hy0 the driver did not supply an errorthe weird part is that it successfully creates the table in sql server home testtemp and seems to be erroring out on an unnecessary rollback any ideas on best ways to debug this further or fix the issue when i run the sql output by managepy sqlmigrate home directly against the database logged in with this username and password it works finethanks in advanceupdate 1 this is not a good fix but gets around what appears to be a problem with a rollback being called when it should not this change is made around line 389 of basepy in djangopyodbcazurethis is ugly and gets rid of a safeguard but makes things work in the meantime modifying basepy around line 389 in djangopyodbcazuredef set autocommitself autocommit selfconnectioncommit with selfwrap database errors if autocommit selfconnectioncommit else selfconnectionrollback selfconnectionautocommit autocommitobviously still looking for an actual fix rather than a hack and the root causeupdate 2 back out the change made in update 1 above to the original djangopyodbc then in the settings change the tds version to be either 70 or 71 it works if you change it to 72 or 73 it breaks could this be a problem with the new date fields available starting in sql server 2008 either way a temp solution is to revert to tds version 71 and this is clearly useful information towards a fix,['python'] +1020791,keeping vector of iterators of the data i have a function void get good itemsconst stdvectort datastdvectorx good itemsthis function should check all data and find items that satisfies a condition and return where they are in good itemswhat is best instead of xstdvectorsize t that contains all good indicesstdvectort that contain a pointers to the itemsstdvectorstdvectortiterator that contains iterators to the itemsother editwhat will i do with the good itemsmany things one of them is to delete them from the vector and save them in other place maybe something else lateredit 2one of the most important for me is how will accessing the items in data will be fast depending on the struct of good itemsedit 3i have just relized that my thought was wrong is not better to keep raw pointersor smart as items of the vector so i can keep the real values of the vector which are pointers and i do not afraid of heavy copy because they are just pointers,['c++'] +1020799,unable to get db connection after java 8 upgrade i have recently upgraded an application from java 17 to 18 rest of the libraries versions remains unchanged i am getting the following error after the upgradedebug 201512 095512 basicresourcepool an exception occurred while acquiring a poolable resource will retryjavalangnullpointerexception at oraclenetjndijndiattrsgetattrsjndiattrsjava207 at oraclenetresolveraddrresolutioninitaddrresolutionjava198 at oraclenetnsnsprotocolconnectnsprotocoljava219 at oraclejdbcdrivert4cconnectionconnectt4cconnectionjava1102 at oraclejdbcdrivert4cconnectionlogont4cconnectionjava320 at oraclejdbcdriverphysicalconnectioninitphysicalconnectionjava546 at oraclejdbcdrivert4cconnectioninitt4cconnectionjava236 at oraclejdbcdrivert4cdriverextensiongetconnectiont4cdriverextensionjava32 at oraclejdbcdriveroracledriverconnectoracledriverjava521 at commchangev2c3p0drivermanagerdatasourcegetconnectiondrivermanagerdatasourcejava134 at commchangev2c3p0wrapperconnectionpooldatasourcegetpooledconnectionwrapperconnectionpooldatasourcejava182 at commchangev2c3p0wrapperconnectionpooldatasourcegetpooledconnectionwrapperconnectionpooldatasourcejava171 at commchangev2c3p0implc3p0pooledconnectionpool1pooledconnectionresourcepoolmanageracquireresourcec3p0pooledconnectionpooljava137 at commchangev2resourcepoolbasicresourcepooldoacquirebasicresourcepooljava1014 at commchangev2resourcepoolbasicresourcepoolaccess800basicresourcepooljava32 at commchangev2resourcepoolbasicresourcepoolacquiretaskrunbasicresourcepooljava1810 at commchangev2asyncthreadpoolasynchronousrunnerpoolthreadrunthreadpoolasynchronousrunnerjava547hibernate configurationshibernateconfiguration sessionfactory property namehibernateconnectiondriver classoraclejdbcdriveroracledriverproperty property namehibernateconnectionurljdbcoraclethinldapsxcnodcwproperty property namehibernateconnectionusernameyproperty property namehibernatestatement cachesize0property property namehibernateconnectionpasswordzproperty property namehibernatec3p0min size5property property namehibernatec3p0max size20property property namehibernatec3p0timeout1800property property namehibernatec3p0max statements0property property namehibernatedefault schemayproperty property namehibernatedialectorghibernatedialectoracledialectproperty property namehibernateshow sqltrueproperty sessionfactoryhibernateconfigurationrelated libraries usedojdbc6 112030hibernate 31problemthe dependencies contained 2 hibernate version 31 and 30 and ojdbc6 and ojdbc7 used mvn dependencytree dverbose to got dependency treesolutionexcluded the other versions of hibernate and ojdbc from the dependencies dependency groupidgroupid artifactidartifactid versionversion exclusions exclusion groupidhibernategroupid artifactidhibernateartifactid exclusion exclusion groupidcomoraclegroupid artifactidojdbc6artifactid exclusion exclusions dependency,['java'] +1020908,converting c program into 32bit assembly code i am stuck with converting c code into assembly here is the code that i need to convertinclude stdiohdefine and 50 int xn yn z2 nvoid convolveint int int intint mainvoid int i n printfenter vector size d n scanfd n printfenter first vector d elementsn n for i 0 i n i scanfd xi printfenter second vector d elementsn n for i 0 i n i scanfd yi convolvex y z n printfconvolutionn for i 0 i n n 1 i printfd zi printfn return 0void convolveint x int y int z int n int i j for i 0 i n n 1 i zi 0 for i 0 i n i for j 0 j n j zi j xi yj returni am stuck at this linescanfd xihow do i insert into arrayhere is what i have so far data align 4state long 0 bss and 50 int xn yn z2n data equ n 50 comm i44 int b comm n44 int n comm j44 int j comm xn44 int xn where and is 50 comm yn44 int xn where and is 50 comm zn84 int xn where and is 100 section rodata to format stringsfmt0 string enter vector size d fmt1 string dfmt2 string enter first element d elementsnfmt3 string enter second element d elementsnfmt4 string convolutionnfmt5 string nfmt6 string d text globl mainmain pushl ebp prolog movl esp ebp pushl esi save calleesave registers esi edi and ebx onto stack pushl edi where esi at 4ebpedi at 8ebp and ebx at 12ebp pushl ebx pushl eax for array where eax at 16ebp allocate space for i and and on the stack subl 8 esp i is at address 20ebp and is at address 24ebp pushl fmt0 push fmt0 call printf printfenter vector size d addl 4 esp deallocate parm to printf leal 24ebp ebx ebx address of n pushl ebx push address of n pushl fmt1 push fmt1 d call scanf scanf d n addl 8 esp dealoccate parms for scanf pushl fmt2 push fmt2 call printf printfenter first element d elementsn addl 4 esp deallocate parm to printf movl 0 20ebp i0 movl 20ebp edi edii movl 24ebp esi esin cmpl esi edi compare in jg for done jump to for done if infor loop pushl edi push i pushl esi push n pushl eax push array pushl fmt1 push fmt1 d call scanf scanfd n addl 8 esp dealocate parms to scanf movl address of xedi4 eax incl edi edi i movl edi20ebp iedi compl esi edi compare in jle for loop jump to for loop if infor done addl 8 esp deallocate local vars from stack popl ebx restore ebx popl edi restore edi popl esi restore esinext loop for second vector pushl esi save calleesave registers esi edi and ebx onto stack pushl edi where esi at 4ebpedi at 8ebp and ebx at 12ebp pushl ebx pushl fmt3 push fmt3 call printf printfenter second element d elementsn addl 4 esp deallocate parm to printf movl 0 20ebp i0 movl 20ebp edi edii movl 24ebp esi esin cmpl esi edi compare in jg for done jump to for done if infor loop pushl edi push i pushl esi push n pushl eax push array pushl fmt1 push fmt1 d call scanf scanfd n addl 8 esp dealocate parms to scanf movl address of yedi4 eax incl edi edi i movl edi20ebp iedi compl esi edi compare in jle for loop jump to for loop if infor done addl 8 esp deallocate local vars from stack popl ebx restore ebx popl edi restore edi popl esi restore esi leave epilog retconvolve pushl ebp prolog movl esp ebp pushl esi save calleesave registers esi edi and ebx onto stack pushl edi where esi at 4ebpedi at 8ebp and ebx at 12ebp pushl ebx allocate space for x y z n i and j on the stack subl 24 esp x is at address 4ebp y is at address 8ebp z is at address 12ebp and is at address 16ebp i is at address 16ebp and is at address 20ebp movl 0 16ebp i0 movl 16ebp edi edii movl 20ebp esi esin addl esi esi 2 times n subl 1 esi 2n 1 cmpl esi edi compare in jg for done jump to for done if in,['c'] +1020957,how to extend python enum what is best practice for extending enum type in python 34 and is there even a possibility for do thisfor examplefrom enum import enumclass eventstatusenum success 0 failure 1class bookingstatuseventstatus duplicate 2 unknown 3traceback most recent call lasttypeerror cannot extend enumerationscurrently there is no possible way to create a base enum class with members and use it in other enum classes like in the example above is there any other way to implement inheritance for python enums,['python'] +1021057,mysql grouping is not respecting order by i am trying to do a mysql query to find the most recently active threads and the most recent comment on each thread in a web forum threads are stored in two tables forum topics and forum responses where each forum topic has many forum responseshere i do a search on forum reponses joined to forum topics with a descending sort on forum responseidselect tid ttitle rid rbody from forum responses r inner join forum topics t on rforum topic id tid order by rid desc id title id body 17 new topic 69 yes 19 test topic 1 68 this is a test 17 new topic 64 hey yo 19 test topic 1 63 test topic starter 18 test topic 62 test 18 test topic 61 test 17 new topic 60 another test response 17 new topic 59 test response 17 new topic 54 what should this topic be about ok so far so good but it is returning duplicates i just want to have the most recentlyrespondedto forum topics so i add a group by to my query so we can group by the topic idselect tid ttitle rid rbody from forum responses r inner join forum topics t on rforum topic id tid group by tid order by rid desc id title id body 19 test topic 1 63 test topic starter 18 test topic 61 test 17 new topic 54 what should this topic be about but now we have a problem it is grouping by the forum topic id but counterintuitively we are not getting our forum topics sorted by most recent activity and the associated forum responses are not the most recentwhats going wrong here is there a way to alter this query so that i get a list of the most recentlycontributedto forum topics along with their respective most recent comments,"['mysql', 'sql']" +1021305,why googlematerialicon does not have logout icon in android library although here contains an exit to app icon i cannot find it in its android library,['android'] +1021309,load data infile mysql error 280 i am having problems with the following sql query i want to executeload data infile thelocationofmyfilecsvinto table test import fields terminated by lines terminated by rnignore 1 lines artid artnamepharmlang artnamefr artnamenl pubprice percentagerebate rebateamount sellingprice localisation cnknr eannr soldqty minthd maxthd qtyinstock datelastsale vatrate suppliermanufname buyprice invcatcode arttype apbcatcode apblegcode pharmapbnr i want to load the data of an excel file into a table in my databasewhen i run this locally everything works but when i do this on the server i get the following erroruncaught exception pdoexception with message sqlstate280 invalid authorization specification 1045 access denied for user myuserlocalhost using password yesi am trying to do this in php in zend framework when i contacted the hosting they said i needed the file permission to do this but this is bad practice and not adviced i also tried to do this in a shell script like thisbinbashusrbinmysql hostlocalhost usertheuser passwordpassword databasedb databaseeofmysqlload data infile locationofmyfilecsvinto table test import fields terminated by lines terminated by rnignore 1 lines artid artnamepharmlang artnamefr artnamenl pubprice percentagerebate rebateamount sellingprice localisation cnknr eannr soldqty minthd maxthd qtyinstock datelastsale vatrate suppliermanufname buyprice invcatcode arttype apbcatcode apblegcode pharmapbnr eofmysqlbut i got the same errorerror 1045 280 at line 1 access denied for user userlocalhost using password yesupdatei have tried to add local like thisload data local infile thelocationofmyfilecsvbut then i get this errorerror 1148 420 at line 1 the used command is not allowed with this mysql versionalso tried to add localinfile1 like this but got same errorusrlocalbinmysql host127001 usertheuser localinfile1 passwordpassword databasedb databasesecond updatemy config file mycnf looks like thismysqldlocalinfile0max connections 50connect timeout 5wait timeout 300max allowed packet 16mthread cache size 128sort buffer size 4mbulk insert buffer size 16mtmp table size 16mmax heap table size 16mkey buffer size 32mopenfileslimit 20table cache 400myisam sort buffer size 8mconcurrent insert 2read buffer size 2mread rnd buffer size 1mquery cache limit 1mquery cache size 32minnodb log file size 48mmax allowed packet 32mthe location where my connection is established does not really matter because i am testing it with a shell script where i make the connection i do not get an error when i runusrbinmysql hostlocalhost usertheuser passwordpassword databasedb databaseeofmysqlshow tableseofmysqljust a list of all the tables in my databasewhen i run show grants i get grants for theuserlocalhost grant usage on to theuserlocalhost identified by password password grant all privileges on mydomain live to theuserlocalhost grant all privileges on mydomain staging to theuserlocalhost with grant option 3 rows in set 001 sec,"['php', 'mysql', 'sql']" +1021601,how to find whats in the inputstream i want to create a small program in which the user will provide me with the url and then heshe will get the images present in that webpage below is the code from which i have started url posturl new urlurl inputstream inputstream posturlopenstream bufferedreader br new bufferedreadernew inputstreamreader inputstream string line stringbuilder sb new stringbuilder while line brreadline null sbappendline loggerservicelogsbtostring return nullit will provide me with the html of the webpage and search for the img tags but what if the url provided to me is something like direct image link which contains the direct image as it will not contain html how to tackle this also i am eager to find out some apis that i could usethanks in advance,"['java', 'html']" +1021657,method iterator declared in javautilcollection and in javalangiterable its superinterface can somebody explain to me why is the method iteratore iterator defined in javautilcollection collection already extends javalangiterable this method is redundant is this for convenience,['java'] +1021675,use attribute and target matrices for tensorflow linear regression python i am trying to follow this tutorialtensorflow just came out and i am really trying to understand it i am familiar with penalized linear regression like lasso ridge and elasticnet and its usage in scikitlearn for scikitlearn lasso regression all i need to input into the regression algorithm is df x an m x and dimensional attribute matrix pddataframe and sr y an m dimensional target vector pdseries the variable structure in tensorflow is a bit new to me and i am not sure how to structure my input data into what it wants it seems as if softmax regression is for classification how can i restructure my df x m x and attribute matrix and sr y m dimensional target vector to input into tensorflow for linear regression my current method for doing a linear regression uses pandas numpy and sklearn and it is shown below i think this question will be really helpful for people getting familiar with tensorflowusrbinpythonimport pandas as pdimport numpy as npimport tensorflow as tffrom sklearnlinear model import lassocvcreate dataframes for attribute and target matricesdf x pddataframenparray001231451341columnsatt1att2att3indexs1s2s3s4sr y pdseriesnparray3258indexs1s2s3s4nametargetprint df xatt1 att2 att3s1 0 0 1s2 2 3 1s3 4 5 1s4 3 4 1print sr ys1 3s2 2s3 5s4 8name target dtype int64create linear model lasso regressionmodel lassocvmodelfitdf xsr yprint modellassocvalphasnone copy xtrue cvnone eps01 fit intercepttruemax iter10 and alphas100 and jobs1 normalizefalse positivefalseprecomputeauto random statenone selectioncyclic tol01verbosefalseprint modelcoef 0 038346 0,['python'] +1021728,flip nonzero values along each row of a lower triangular numpy array i have a lower triangular array like bb nparray10257500 12702341 barray 1 0 0 0 025 075 0 0 01 02 07 0 02 03 04 01 i want to flip it to look likearray 1 0 0 0 075 025 0 0 07 02 01 0 01 04 03 02 that is i want to take all the positive values and reverse within the positive values leaving the trailing zeros in place this is not what fliplr does npfliplrbarray 0 0 0 1 0 0 075 025 0 07 02 01 01 04 03 02 any tips also the actual array i am working with would be something like bshape 2002044 instead of 44 each 44 block looks like the above example with different numbers across the 200 20 different entries,['python'] +1021860,controlling poll frequency of browserwait fluent wait the storyin java selenium language bindings there is a fluentwait class that allows to tightly control how the expected condition would be checkedeach fluentwait instance defines the maximum amount of time to wait for a condition as well as the frequency with which to check the condition furthermore the user may configure the wait to ignore specific types of exceptions whilst waiting such as nosuchelementexceptions when searching for an element on the pagein other words it is possible to change the polling interval in which the expected condition check is applied which is by default 500ms plus it is possible to set exceptions to ignoreit is also possible in python there are relevant poll frequency and ignored exceptions arguments to webdriverwait classthe questionis it possible to control the poll frequency in which the expected condition is verified when using browserwait in protractorwebdriverjsaccording to the browserwait documentation there are only 3 possible arguments a function which is an expected condition a timeout value and an optional timeout error message i hope there is a different setting or way to change the poll frequency,['javascript'] +1021864,uisearchbar textdidchange creating error there are visible views left after reusing them all null null i am using a uitableviewcontroller with a uisearchbar everything seems to work fine except i am getting a strange warning in the textdidchange method that i have never seen beforethis is my code voidsearchbaruisearchbar searchbar textdidchangensstring searchtext selfsearchresults removeallobjects ifsearchtext isequaltostringsearchtextnil selftableview reloaddata return fornsarray monsterarray in selfmonsterarray nsstring name monsterarray0 nsrange r name lowercasestring rangeofstringsearchtext lowercasestring ifrlocation nsnotfound ifrlocation0 selfsearchresults addobjectmonsterarray selftableview reloaddataby stepping through the program i have found that the warning occurs right before the end of textdidchange as i mentioned in the title the warning is thisthere are visible views left after reusing them all null null does anyone know why this is happening and how to resolve it,['ios'] +1022030,what is the point of rubys method unbinding mechanism methodunbind returns an unboundmethod reference to the method which can later be bound to another object using unboundmethodbindclass foo attr reader baz def initializebaz baz baz endendclass bar def initializebaz baz baz endendf foonewtest1g foonewtest2h barnewtest3fmethodbazunbindbindgcall test2fmethodbazunbindbindhcall typeerror bind argument must be an instance of fooinitially i thought this is incredibly awesome because i expected it would work similarly to javascripts functionprototypecallfunctionprototypeapply however the object to which you want to bind the method must be of the same classthe only application i can think of is if you unbind a method lose the original implementation redefine the method in the original or singleton class and then rebind and call it,['ruby'] +1022077,firefox console throws no element found on http 204 response everything actually works but i cannot get rid of this error in the firefox consoleno element foundi am sending an http request to my apihttp url api location expenses objexpenseid method deletethenfunctionresponse ifresponsestatus 204 var params locationsearch paramsalertsuccess alertsexpense deleted locationsearchparams routereloadand my django rest framework api returns an http 204 no content status,['javascript'] +1022091,bring through previous 12 months count while grouping by period i am trying to use the below code to bring though a count of all lines in the last 12 month period for the period and plant please see the output belowso for example with the below output rather than the 12 months column currently containing the total for the period i want the count using a period between 201001201101 please note my example was only for the dataset below and the 12 months column needs to adapt for each periodperiod plant stock special monthtotal 12months201101 0ea0 27 0 27 27201101 0eb0 35 2 37 37the issue i am having is that rather than bring through the last 12 month count my code is merely bringing through the count for the current period please can someone assist select convertvarchar6dateaddmm0pdt112 as periodpplant sumcase when leftuppermaterial2 zz then 1 else 0 end as stock sumcase when leftuppermaterial2 zz then 1 else 0 end as special count as monthtotalsumcase when convertvarchar6dateaddmm0pdt112 between convertvarchar6dateaddmm12pdt112 and convertvarchar6dateaddmm0pdt112 then 1 else 0 end as 12months from iesaonlinedbods pos as p where plant in select client from metricsdboco 001 plants 090 final where custgrp hovis group by pplantconvertvarchar6dateaddmm0pdt112 order by convertvarchar6dateaddmm0dt112plant,['sql'] +1022164,choose a user of the list loop here i fetched all information of my users with a loop as you see my table is like thisand my code is this phpidfgmembersiteuserid echo id db host localhostdb name sitedb table tablesitedb user rootdb pass con mysql connectdb hostdb userdb pass or die au u u34uu u uselectedmysql select dbdb name con or die ua u34uu u umysql queryset character set utf8dbresultmysql queryselect tablesitename tablesitefamily tablesiteusername tablesitephone number tablesiteemail from db tablecon i 1 whileamchmysql fetch assocdbresult phpecho form namef1 idform i methodpost action serverphp self acceptcharsetutf8rnechodiv dirrtlecho uu ua uu u nbspnbspnbspamchname amchfamilynbspnbspnbsp uu au3 amchphone numbernbspnbspnbspu amchemailbrecho input typesubmit namesubmit valueua u auechohrechohrechodivecho formrn i phpifisset postsubmit for each user there is a button for choosing hemher for send himher information to another pagethis is a part of printing users information with button for each one of them i just do not know how to choose that buddy and send selected information to another page thanks,"['php', 'mysql', 'sql']" +1022209,retrofit 2 best practice for android asynchronous request or synchronous request in asynctask i am using the retrofit 2 library for an android rest client retrofit itself supports synchronous and asynchronous request cf here the reason for the latter being not to block a thread and thus not to get interrupted by androidin practice is it better to use synchronous calls in a native asynctask or asynchronous calls directly from retrofitif one is preferable over the other what are the technical reasons,['android'] +1022390,pythonrequests post with unicode filenames i have read through several related questions here on so but did not manage to find a working solutioni have a flask server with this simplified codeapp flask name api apiappclass sendmailapiresource def postself print requestfiles return responsestatus200apiadd resourcesendmailapi if name main apprunhost0 debugtruethen in the client codingutf8import requestseng file name atxtheb file name utxtrequestsposthttplocalhost50 filesfile0 openeng file name rbrequestsposthttplocalhost50 filesfile0 openheb file name rbwhen sending the first request with the nonutf8 filename the server receives the request with the file and prints immutablemultidictfile0 filestorage uatxt none but when sending the file with the utf8 filename the server does not seem to receive the file as it prints immutablemultidicti am using requests 230 but the problem does not resolve with the latest version as well 281 flask version is 0101 and flaskrestful version is 034i have done some digging in requests code and the request seems to be sent ok ie with the file and i printed the request right before it is being sent and see the file name was indeed encoded to rfc22316ea257530b254861b71626f10a801726contentthisposition formdata namefile0 filenameutf8d790txtto sum things up i am not entirely sure if the problem lies within requests that does not properly attach the file to the request or if flask is having issues with picking up files with file names that are encoded according to rfc2231 update came across this issue in requests github,['python'] +1022611,make google recaptcha work with special charachters in the domain name i was setting up an api key for a site with the swethish charachter a in the domain name httpsaljaio but it did not initialize the recaptchathen trying an api key for the equivalent url which worked when reaching the site from but not httpsaljaiothen i found the secure token which should work on all domains it initialized the recaptchas on all domains and was also working on all tested domains except the one with a in it tokenis there any way to get it working also with a in the domain name editsince an apikey for is working from android when accessing the site from httpsaljaio it might be how the browser interprets the domain eg firefox interprets httpsaljaio as domain httpsaljaio and cannot get a response from google servers that will not allow a in domain names android inteprets httpsaljaio as and will get a response since it is not containing a any thoughts about this is there any way to force the browser to interpret httpsaljaio as edit2code examples can be reached on saljaiotest 17862187163test and xnsljaloaiotestedit3as of today 25112015 it seems not to be possible to use recaptcha with a special charachter like a in the domain name since aishwat singh have been helping the most to coming to this conclusion within the time for the bounty he will be rewarded however an answer will be accepted when a solution can be provided for this problem,['javascript'] +1022842,how to check characters alternatively and replace it with y if it is x i have a string something like thisstr it is a test string for more clarification i t i s a t e s t s t r i and g 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20now i need to check all characters that are multiples of 4 plus first character like these1 i4 i8 space12 t16 r20 now i need to compare them with y y is a variable symbol for example y r in here so i want to replace y with x x is a variable symbol too for example x m in hereso i want this outputit is a test stminghere is my solution i can do that using some php functionstrlenstr to count the number of characters named sumsum 4 to find characters that are multiples of 4substrstr 41 to select specific character named char the problem is hereif char r to comparestr replacermchar to replaceand then combining all char to each otherbut my solution has two problemsubstr does not count space character as i mentioned abovecombining characters is complicated a bit it needs to some waste processingwell is there any solution i like to do that using regex is it possible,['php'] +1022984,remove an image that was not put in uploads folder via wp handle upload i am saving an image to uploads folder but i am using file put contents instead of wp handle upload because i get an image in base64 and not as a file in files image and certain post data are savedupdated as they should be using this functionswp insert attachmentwp update attachment metadatathe problem is when i want to remove an old image when saving a new one wp delete attachment does not remove the image it does seem to remove stuff in db though i am thinking the problem lies in not using wp handle upload when i upload an image via upload btn and receive it using files and then upload it with wp handle upload removing worksdoes anyone have an idea of what might be the right way to remove an image in my case perhaps i can save it properly using wp handle upload even if i have an image in base64 thanks for any info edit i also tried saving image with wp upload bits and wp delete attachment still did not work another thing i checked the code of wp handle upload function located in wpadminincludesfilephp i do not see an easy way to modify or copy the existing function and add a custom one which would accept base64 image instead of a file as in files someone has a base64 to files workaround perhaps,['php'] +1023022,wcf clientside errorhandling i am consuming a clunky wcf server that occasionally throws various exceptions and additionally returns some of its errors as string i have no access to the server code at alli want to override the inner wcfclient request invocation method and handle all inner exceptions and hardcoded errors returned by the server and raise the fault event if an error occurs pseudoclass myclient myservicesoapclient protected override oninvoke object result try result baseoninvoke ifresult error raise fault event catch raise fault event so that when i call myclientgethelloworld it goes thru my overridden methodhow can this be achievedi know i do not have to use the generated client but i do not want to reimplement all the contracts again and i want to use the generated clientbase subclass or at least its channelwhat i need is control over the inner request call methodupdatei read this answer and looks it is partially what i am looking for but i am wondering if there is a way to attach an ierrorhandler to the consumer client code only i want to add it to the clientbasetchannel instance somehowupdatethis article also looks very promising but it does not work the applied attribute does not seem to take effecti cannot find a way to add iservicebehavior to the client sideupdatei tried attaching an ierrorhandler via iendpointbehaviorapplyclientbehavior calling public void applyclientbehaviorserviceendpoint endpoint clientruntime clientruntime clientruntimecallbackthispatchruntimechannelthispatchererrorhandlers addnew errorhandlerclientruntime is a parameter but exceptions are still thrown directly skipping myerrorhandlerapplythispatchbehavior is not called at allconclusioni need to achieve two aspectswrap all exceptions that might occur during the lifetime of a baseclienttchannel and decide whether to handle them or throw them on this should take care of all operation the service i am consuming exposes few dozensparse all serverreplies and throw exceptions for some of them so they are forwarded as in statement 1,['c#'] +1023067,is creating two files for the same file descriptor welldefined posix specifies an fdopen function that creates a file for a file descriptor posix also specifies a fileno function that returns the file descriptor for a file together these two could be used to create a second file accessing the same underlying file descriptor as an existing filefile secondfilefile f const char mode int fd filenof return fd 0 fdopenfd mode nullis this a welldefined operation under posix what happens when i access both the original file and the second file i made for the same file descriptor is the interaction specified if yes howhistorically unices used a fixed table of file structures for the 20 files you could open calling fdopen on a file descriptor that has already been associated with a file would thus corrupt the existing file and yield undefined behaviour i am not sure if such an implementation of stdio is still allowed by posix which is why i am asking this question,['c'] +1023314,java finding leading zeros in a long by conversion to double prior to finding the method longnumberofleadingzeroslong i i was casting longs to doubles and using mathgetexponentdouble d the idea was to find the double representation of the long use the exponent to get the highest set bit and subtract it from 64 to get the number of leading zerosthis mostly worked but was occasionally off by 1 the following forloop was used to highlight the problemfor int i 0 i 64 i double max longmax value i double min longmin value i double neg 1l i systemoutformatmax 5d min 5d 1 5dn mathgetexponentdmax mathgetexponentdmin mathgetexponentdnegwith the significant portion of outputmax 55 min 55 1 56 max 54 min 54 1 55 max 52 min 53 1 54 max 51 min 52 1 52 max 50 min 51 1 51 the longs with all bits set are off by 1 above 252 as this post explains a loss of precision occurs due to the storage of 53 significant bits in the 52bit mantissa however i am struggling to understand why the exponent is affectedwhile i am no longer using this method i am still curious why and under what circumstances does this method of finding the leading zeros in a long fail,['java'] +1023356,what does from future import absolute import actually do i have answered a question regarding absolute imports in python which i thought i understood based on reading the python 25 changelog and accompanying pep however upon installing python 25 and attempting to craft an example of properly using from future import absolute import i realize things are not so clearstraight from the changelog linked above this statement accurately summarized my understanding of the absolute import changelet us say you have a package directory like thispkgpkg init pypkgmainpypkgstringpythis defines a package named pkg containing the pkgmain and pkgstring submodulesconsider the code in the mainpy module what happens if it executes the statement import string in python 24 and earlier it will first look in the packages directory to perform a relative import finds pkgstringpy imports the contents of that file as the pkgstring module and that module is bound to the name string in the pkgmain modules namespaceso i created this exact directory structure ls rpkgpkg init py mainpy stringpy init py and stringpy are empty mainpy contains the following codeimport stringprint stringascii uppercaseas expected running this with python 25 fails with an attributeerror python25 pkgmainpytraceback most recent call last file pkgmainpy line 2 in module print stringascii uppercaseattributeerror module object has no attribute ascii uppercasehowever further along in the 25 changelog we find this emphasis addedin python 25 you can switch imports behaviour to absolute imports using a from future import absolute import directive this absoluteimport behaviour will become the default in a future version probably python 27 once absolute imports are the default import string will always find the standard librarys versioni thus created pkgmain2py identical to mainpy but with the additional future import directive it now looks like thisfrom future import absolute importimport stringprint stringascii uppercaserunning this with python 25 however fails with an attributeerror python25 pkgmain2pytraceback most recent call last file pkgmain2py line 3 in module print stringascii uppercaseattributeerror module object has no attribute ascii uppercasethis pretty flatly contradicts the statement that import string will always find the stdlib version with absolute imports enabled whats more despite the warning that absolute imports are scheduled to become the new default behavior i hit this same problem using both python 27 with or without the future directive python27 pkgmainpytraceback most recent call last file pkgmainpy line 2 in module print stringascii uppercaseattributeerror module object has no attribute ascii uppercase python27 pkgmain2pytraceback most recent call last file pkgmain2py line 3 in module print stringascii uppercaseattributeerror module object has no attribute ascii uppercaseas well as python 35 with or without assuming the print statement is changed in both files python35 pkgmainpytraceback most recent call last file pkgmainpy line 2 in module printstringascii uppercaseattributeerror module string has no attribute ascii uppercase python35 pkgmain2pytraceback most recent call last file pkgmain2py line 3 in module printstringascii uppercaseattributeerror module string has no attribute ascii uppercasei have tested other variations of this instead of stringpy i have created an empty module a directory named string containing only an empty init py and instead of issuing imports from mainpy i have cdd to pkg and run imports directly from the repl neither of these variations nor a combination of them changed the results above i cannot reconcile this with what i have read about the future directive and absolute importsit seems to me that this is easily explicable by the following this is from the python 2 docs but this statement remains unchanged in the same docs for python 3syspathas initialized upon program startup the first item of this list path0 is the directory containing the script that was used to invoke the python interpreter if the script directory is not available eg if the interpreter is invoked interactively or if the script is read from standard input path0 is the empty string which directs python to search modules in the current directory firstso what am i missing why does the future statement seemingly not do what it says and what is the resolution of this contradiction between these two sections of documentation as well as between described and actual behavior,['python'] +1023489,cannot see nexus 6p for debugging i am using windows 10 a dell xps 13 and v141 of android studio i have sdk tools 2441 installed as well as google usb driver 11on the phone i have usb debugging enabled and can see the device in file explorer ie documents pictures etcbut the device never shows up using adb devices nor in android studioi have never had this much trouble getting an android device debugging before but i do not know if it is marshmallow or the nexus 6p that is to blame more importantly i have no idea what to do at this point to get it debuggingi am dead in the water until this is resolved so any help is most appreciatedthanks,['android'] +1023730,uitabbar item not showing storyboard reference i am trying to use the new storyboard references in a tabbar when i use the storyboard reference the uitabbaritem with customized image text set is not showing anything see setupstoryboard setuptabbaritem setupi fixed it for now by setting the images title in the initwithcoder function for the initial viewcontroller in the referenced storyboards like sostatic nsstring const contactsviewcontrollertabcontactimagename tabcontactstatic nsstring const contactsviewcontrollertabcontactactiveimagename tabcontactactive instancetypeinitwithcodernscoder adecoder self super initwithcoderadecoder if self selftitle nslocalizedstringcontacts nil selftabbaritemimage uiimage imagenamedcontactsviewcontrollertabcontactimagename selftabbaritemselectedimage uiimage imagenamedcontactsviewcontrollertabcontactactiveimagename return self,"['ios', 'objective-c']" +1023731,on window resize event javascript on object tag i have created jquery tabs and embedded a jsp page on the parent page i have called on window resize events on both pages but the inner page function does not get invoked for the inner page i have an svg element which needs to be resized every time the window is resized slinkpagetojunction base1 innertabbedpagejspintersectionname strintersectionname framename strframename ip serverip port serverport intercorridorname svgfilenameif documentgetelementbyidjnlive strintersectionname null var nexttab tabs lisize1 tabcount tabs lisize create the tab lia hreftab strintersectionname datatoggletab strintersectionname nbspnbsp button classclose closetab alignright typebuttonxbuttonaliappendtotabs create the tab content div classtabpane idtab strintersectionname div idjnlive strintersectionname classcolsm6 stylemargintop 1 divappendtotabcontent var heightvalue windowheight var widthvalue windowwidth alertheightvaluewidthvalue var url object idobj strintersectionname data slinkpagetojunction height heightvalue width widthvalue object jnlive strintersectionnamehtmlurl make the new tab active tabs alasttabshow openedtabbedjunctionnamestabcount 1 strintersectionname openedtabbedjunctionframenamestabcount 1 strframename registercloseeventso it creates a new tab if it does not already exist now my on windowresize event on the inner page is windowaddeventlistenerresize changeframesizejn on the outer page it iswindowaddeventlistenerresize changeframesize but when i resize the window with the tab selected changeframesizejn is not invoked how can i do that ps i dont know if i have put the information that is required for the question to be answered the fact is i am not sure how to ask this question,"['javascript', 'jquery', 'html']" +1023738,setting a windows variable to execute a java program i am setting this variableset srcdir cdeveloppementworkspaceseclipsemyauthenticationprovidersrcthen i exeecute this programjava dmjfmyauthenticationjar dfilessrcdir weblogicmanagementcommoweblogicmbeanmaker but i have this strange errorthe specified input files directory srcdir does not existi even tried using java dmjfmyauthenticationjar dfilessrcdir weblogicmanagementcommoweblogicmbeanmakerwith the same resultthe specified input files directory srcdir does not existanother testcdeveloppementworkspaceseclipsewlauthenticationproviderset atestcdeveloppementworkspaceseclipsewlauthenticationproviderecho aacdeveloppementworkspaceseclipsewlauthenticationprovider,['java'] +1023770,pushwoosh leaking my activity i am using pushwoosh inside my application to receive push notifications i am using the latest version of pushwoosh library 3114 i have a screen structure like thislogin activity main activity with multiple tabsso i am implementing my pushwoosh related logic inside mainactivity and i want to unregister from push on logout and go back to login activity my code is given below i have filtered out all other sections unrelated to pushwoosh to be frank this code is exactly similar to the code in pushwoosh documentation here the only difference is in the onlogout method where i try to unregister from pushwoosh and go back to loginactivitytabbaractivityjavaoverrideprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate pushwoosh registration registerreceivers pushmanager pushmanager pushmanagergetinstancethis pushmanagersetnotificationfactorynew pushnotificationfactory try pushmanageronstartupthis catchexception e register for push pushmanagerregisterforpushnotifications checkmessagegetintent override protected void onnewintentintent intent superonnewintentintent setintentintent checkmessageintentoverrideprotected void onresume superonresume registerreceiversoverrideprotected void onpause superonpause unregisterreceiversbroadcastreceiver mbroadcastreceiver new baseregistrationreceiver override public void onregisteractionreceivecontext context intent intent checkmessageintent private broadcastreceiver mreceiver new basepushmessagereceiver override protected void onmessagereceiveintent intent json data key contains json payload of push notification public void registerreceivers intentfilter intentfilter new intentfilter getpackagename actionpush message receive registerreceivermreceiver intentfilter getpackagename permissionc2d message null registerreceivermbroadcastreceiver new intentfilter getpackagename pushmanagerregister broad cast actionpublic void unregisterreceivers try unregisterreceivermreceiver catch exception e eprintstacktrace try unregisterreceivermbroadcastreceiver catch exception e eprintstacktrace private void checkmessageintent intent if null intent if intenthasextrapushmanagerregister event uploadpushtokentoserverpushmanagergetpushtokenthis a resetintentvalues private void resetintentvalues intent mainappintent getintent if mainappintenthasextrapushmanagerpush receive event mainappintentremoveextrapushmanagerpush receive event else if mainappintenthasextrapushmanagerregister event mainappintentremoveextrapushmanagerregister event else if mainappintenthasextrapushmanagerunregister event mainappintentremoveextrapushmanagerunregister event else if mainappintenthasextrapushmanagerregister error event mainappintentremoveextrapushmanagerregister error event else if mainappintenthasextrapushmanagerunregister error event mainappintentremoveextrapushmanagerunregister error event setintentmainappintentfinally on logoutprivate void onlogout other cleanup pushwoosh pushmanagergetinstancethisunregisterforpushnotifications goback to login activityi am getting pushes from server without any issue the only problem i face is after i logout and go back to loginactivity tabbaractivity remains in memory which in turns hold on to many other fragments and views i tried debugging using mat and this is what it shows upclass name ref objects shallow heap ref shallow heap retained heapcompushwooshinternalrequestrequestmanager1 0x12f89ce0 thread1737 thread 1 88 360 536 valcontext inmyprojectactivitiestabbaractivity 0x12d8ac40 1 360 360 18520i have also cross checked the same with leakcanary tool that also indicates that pushwoosh is holding on to my activity so my question is how can i cleanup pushwoosh to avoid my activity getting leaked,['android'] +1023841,regex validating csv strings i have a textfield in javafx where the background color changes accordingly to if the content is valid or notvalid987654321 1987654321 210101 9 11701 91 1 24101 917 1 0 430801 9 178 2 001 9 1 084 0invalid0101 9 1 0 1 031240314 9basically only digitsfirst group 4 or 9 digitsif first group 9 digits only two groups in totalif first group 4 digits three four or five groups in totalgroup two and three digits 19group four and five digits 09now think one of these valid lines as one identthe current regex is final string base dsddsdsdsdsddsdsddsdsdsddsdsdsdsdwich works great so far but now i want to include csv so i can type only one ident as i have used to or multiple idents separated by comma but not more than five idents in total my attempt final string pattern stringformatss15basethis enables me to input thisall the valid lines above0101 9 1 0101 9 2 0101 9 30101 9 1 987654321 21 0101 9 3 0101 9 4and if i input more than 5 idents it turns invalid correctlybut if i input the invalid ident 0101 9 1 1 1 1 1 1 1 1 1 it still turns validany suggestions edit this is the matching logic private final predicatestring typingpredicate new predicatestring override public boolean applystring input return inputmatchespattern textfieldtextpropertyaddlistenernew changelistenerstring override public void changedobservablevalue extends string observablevalue string previous string current if current null if stringutilsisemptycurrent typingpredicateapplycurrenttrim textfieldgetstyleclassremoveallinvalid else textfieldgetstyleclassaddinvalid,['java'] +1023878,difference between two dates with different years i want to calculate the difference between 2 dates with different years in seconds i do it like this public static int datedifferencedate d1 date d2 return int d2gettime d1gettimethe problem is that when i run this for example for these datesd1 tue nov 17 141820 gmt0100 2015d2 fri nov 28 153750 gmt0200 2016i get 169191300 as a resultbut when the years are the same i get the right result 954959013can someone explain what is happening here,['java'] +1023879,mqtt sample app is not keeping connection on android 511 i am trying to use mqtt in my app for realtime notificationsas a client library i am using eclipse pahohere is their sample android applicationon android 4 it works fine if i am connected and my device goes into sleep mode mqttclient is sending periodic pings and keeps connection alivebut on my android 511 connection is being torn after a short period when device goes to sleep modethe strange thing is that i still have wifi connection wifi is not thisconnected i have implemented a broadcastreceiver for this but for some reason mqttconnection is not persistedi have tested the sample app by eclipse implemented my own service with wakelocks and periodic pings same storydoes anyone know why is this happening any workaround for thisfor reference bugcgiid482442update found out that if i set keepalive timeout to 10 seconds connection is persisted if it is 20 seconds then connection is dropped same scenario happens when using 10 seconds pings connection is persisted 20 seconds pings connection is droppeddoes anyone know why,['android'] +1023901,why exception is null in threadpoolexecutors afterexecute i want to handle exeptions thrown by worker threads in threadpoolexecutorafterexecute method currently i have this codepublic class myexecutor extends threadpoolexecutor public static void mainstring args myexecutor threadpool new myexecutor taskobject task new task threadpoolsubmittask public myexecutor super4 20 60 timeunitseconds new linkedblockingqueue40 override protected void afterexecuterunnable r throwable t superafterexecuter t systemoutprintlnin afterexecute if t null systemoutprintlnexception thrown tgetmessage else systemoutprintlnt null private static class taskv implements callablev override public v call throws exception systemoutprintlnin call throw new sqlexceptiontesting if i run the code i get outputin callin afterexecutet nullwhy is parameter throwable t null in afterexecute should not it be the sqlexception instance,['java'] +1024014,how to get md5 iterated md5 sum of every chunk using blueimp jquery upload plugin i have to calculate and send a iterated md5hash to my uploadapibut i dona t know howia m usingwith included blueimp jquery upload pluginfor sending only one file filesize smaller than chunksizeeverything is working fine but if file is chunked then i have no idea how to catch the chunk to get md5 of itat the end i have to make the md5 iterately like described here hashinguploadfileupload this element will accept file dragdrop uploading dropzone drop type global form method method post type of datasendmethod datatype json type of data to recieve from apicall maxchunksize global chunk size multipart true this function is called when a file is added to the queue either via the browse button or via dragdrop add function e data var reader new filereader var file datafiles0 var jqxhr var tpl li classworkinginput typetext value0 datawidth48 dataheight48 datafgcolor0788a5 datareadonly1 databgcolor3e4043 ppdiv classmsgdivspanspanli append the file name and file size tplfindp text filename appendi formatfilesize filesize i add the html to the ul element datacontext tplappendtoul initialize the knob plugin tplfindinputknob listen for clicks on the cancel icon tplfindspanclickfunction if tplhasclassworking jqxhrabort tplfadeout function tplremove prevent xhr from sending data in multipartformdata datapostmessage datafiles0type datacontenttype datafiles0type var chunksize global chunk size filesize filesize global chunk size describe the filereaderdataloadevent readeronload function event var binary eventtargetresult var md5 cryptojsmd5binarytostring dataurl md5sum md5 d a t a s e and d jqxhr datasubmit add url to xhrobject dataurl global form action dataurl etf id global folder id dataurl file title filename if the file will be send in one piece if global chunk size filesize add urlparameter to xhrobject dataurl size chunk start 0 dataurl size chunk length chunksize this part for the chunks must be in beforesendcallback because the chunkrelated sizedata is undefined in this case but available there add urlparameter to xhrobject dataurl size final filesize read md5sum and send the file chunk on multipart file is a chunk readerreadasbinarystring file beforesend functione data var file datafiles0 thisfindmsghide if the file will be send as chunks if global chunk size filesize consolelog chunk data datauploadedbytes datachunksize filesize data add urlparameter to xhrobject dataurl size chunk start datauploadedbytes dataurl size chunk length datachunksize if typeof thisattrsession id undefined dataurl session id thisattr session id i hope you have a useful idea thanx,"['javascript', 'php', 'jquery']" +1024035,what is the notification when the number of monitors changes i am curious what is the win32 notification that is broadcast when the number of monitors in the system changes i thought it was wm thisplaychange but i was wrong,"['c++', 'c']" +1024156,place an image in the middle of a block of text without splitting the string and with css only is it possible to achieve the effect belowimg classimageintext srcwimgurlcomimgpngspan classtextaroundimage text goes herespan,"['html', 'css']" +1024387,spring batch readers cursor closed early in jta transaction managed step the working configuration for the step in question is the followingstep spring batch job repository and business repositories using various datasources all use a jta transaction managerstep mystep uses a jdbc paging item readerweblogic oracle xe andor eei wanted to analyze the performance of the jdbc cursor item reader in mystep however after the first commit the second chunks first read would fail with javasqlsqlexception result set already closedi suspected it might be jta xa driver closing the cursor for some reason so i gave mystep a simple datasource transaction manager on the datasource the reader was using and the step was able to complete successfully this is not a solution since this breaks transactionally integrity of the stepshould i be able to use a cursor reader inside of a jta managed step using the environment described below if so what might be configured incorrectly on my endenvironmenttransaction managerbean idmytransactionmanagerclassorgspringframeworktransactionjtajtatransactionmanagerdatasource driver oraclexadatasource jdbc 6 1070weblogic 121300oracle db 11g enterprise edition 112040os osx or linuxconfigbean idmytransactionmanager classorgspringframeworktransactionjtajtatransactionmanagerbean idmydatasource classorgspringframeworkjndijndiobjectfactorybean property namejndiname valuejdbcmydatasource property nameproxyinterface valuejavaxsqldatasourcebeanbatchstep idmystep jobrepositorymyjobrepositoryfactory batchtasklet transactionmanagermytransactionmanager batchchunk readermyreader processormyprocessor writermywriter commitinterval100 processortransactionalfalse batchlisteners batchlistener refmylistener batchlisteners batchtaskletbatchstepbean idmyreader classorgspringframeworkbatchitemdatabasejdbccursoritemreader scopestep property namedatasource refmydatasource property namesql valueselect from myhugetable order by mycolumn desc property namerowmapper bean classmyrowmapper propertybeancaught in the actbelow is the call stack of the result set being closed before the next chunks read notice xa connection closing all statements which causes jdbc to close all results setsjavalangthreadstate runnable at weblogicjdbcwrapperresultsetinternalcloseresultsetjava178 at weblogicjdbcwrapperstatementcloseallresultsetsstatementjava286 at weblogicjdbcwrapperstatementinternalclosestatementjava395 at weblogicjdbcwrapperstatementinternalclosestatementjava367 at weblogicjdbcwrapperxaconnectioncloseallstatementsxaconnectionjava393 at weblogicjdbcwrapperxaconnectioncleanupxaconnectionjava406 at weblogicjdbcwrapperxaconnectionreleasetopoolxaconnectionjava432 at weblogicjdbcjtadatasourceremovetxassocdatasourcejava1907 at weblogicjdbcjtadatasourcepreparedatasourcejava1090 at weblogictransactioninternalxaserverresourceinfopreparexaserverresourceinfojava1408 at weblogictransactioninternalxaserverresourceinfopreparexaserverresourceinfojava522 at weblogictransactioninternalserverscinfostartprepareserverscinfojava411 at weblogictransactioninternalservertransactionimpllocalprepareservertransactionimpljava2709 at weblogictransactioninternalservertransactionimplglobalprepareservertransactionimpljava2340 at weblogictransactioninternalservertransactionimplinternalcommitservertransactionimpljava300 at weblogictransactioninternalservertransactionimplcommitservertransactionimpljava260 at orgglassfishtransactiontransactionmanagerimplcommoncommittransactionmanagerimplcommonjava571 at orgspringframeworktransactionjtajtatransactionmanagerdocommitjtatransactionmanagerjava1021 at orgspringframeworktransactionsupportabstractplatformtransactionmanagerprocesscommitabstractplatformtransactionmanagerjava761 at orgspringframeworktransactionsupportabstractplatformtransactionmanagercommitabstractplatformtransactionmanagerjava730 at orgspringframeworktransactionsupporttransactiontemplateexecutetransactiontemplatejava150 at orgspringframeworkbatchcoresteptasklettaskletstep2doinchunkcontexttaskletstepjava271 at orgspringframeworkbatchcorescopecontextstepcontextrepeatcallbackdoiniterationstepcontextrepeatcallbackjava77 at orgspringframeworkbatchrepeatsupportrepeattemplategetnextresultrepeattemplatejava368 at orgspringframeworkbatchrepeatsupportrepeattemplateexecuteinternalrepeattemplatejava215 at orgspringframeworkbatchrepeatsupportrepeattemplateiteraterepeattemplatejava144 at orgspringframeworkbatchcoresteptasklettaskletstepdoexecutetaskletstepjava257 at orgspringframeworkbatchcorestepabstractstepexecuteabstractstepjava198 at orgspringframeworkbatchcorejobsimplestephandlerhandlestepsimplestephandlerjava148 at orgspringframeworkbatchcorejobflowjobflowexecutorexecutestepjobflowexecutorjava64 at orgspringframeworkbatchcorejobflowsupportstatestepstatehandlestepstatejava67 at orgspringframeworkbatchcorejobflowsupportsimpleflowresumesimpleflowjava165 at orgspringframeworkbatchcorejobflowsupportsimpleflowstartsimpleflowjava144 at orgspringframeworkbatchcorejobflowflowjobdoexecuteflowjobjava134 at orgspringframeworkbatchcorejobabstractjobexecuteabstractjobjava304 at orgspringframeworkbatchcorelaunchsupportsimplejoblauncher1runsimplejoblauncherjava135 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava1142 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava617 at javalangthreadrunthreadjava745,['java'] +1024430,millisecond in sql tsql select casta20150101 14483469a as datetime firstval casta20150101 14483469a as datetime secondvalwhen we look at the answer there is a difference between the milliseconds part in the result set whereas you can notice that in the select statement i have specified different milliseconds part the question is why there is a difference in the millisecond part even though i have different value selected,['sql'] +1024544,is it supported to call method on nil reference in delphi the following delphi program calls method upon nil reference and runs fine program project1apptype consoletype tx class function str string endfunction txstr stringbegin if self nil then begin result nil end else begin result not nil endendbegin writelntxnilstr readlnendhowever in a structurally similar c program systemnullreferenceexception will be raised which seems to be the right thing to donamespace consoleapplication1 class tx public string str if this null return null return not null class program static void mainstring args systemconsolewritelinetxnullstr systemconsolereadline because tobjectfree uses such style it seems to be supported to call method on nil reference in delphi is this true let us suppose that in the if self nil branch no instance field will be accessed,['c#'] +1024547,get response status code using retrofit 20 and rxjava i am trying to upgrade to retrofit 20 and add rxjava in my android project i am making an api call and want to retrieve the error code in case of an error response from the server observablemyresponseobject apicallbody bodyand in the rxjava callmyretrofitobjectapicallbodysubscribenew subscribermyresponseobject override public void oncompleted override public void onerrorthrowable e override public void onnextmyresponseobject myresponseobject on response from server in retrofit 19 the retrofiterror still existed and we could get the status by doingerrorgetresponsegetstatushow do you do this with retrofit 20 using rxjava,['android'] +1024773,my newly released app cannot be installed error code 504 i just released my app to the google play store and the signed apk was published successfully however and i have tried this on three different phones and tablets the app refuses to install when downloaded from the store after clicking the install button the app will download the status will change to installing and then the following dialog appearswhat can be donefacts about my app that could help troubleshootingthe app is targeting api22 with a minsdk of 17i am not using proguardthe app is using multidex via the multidex support libraryappbuildgradlebuildscript repositories maven url dependencies classpath iofabrictoolsgradle1 apply plugin comandroidapplicationapply plugin metatarkaretrolambdaapply plugin iofabricrepositories maven url jcenterandroid compileoptions sourcecompatibility javaversionversion 1 8 targetcompatibility javaversionversion 1 8 compilesdkversion 23 buildtoolsversion 2302 defaultconfig applicationid iogivenowapp minsdkversion 17 targetsdkversion 22 versioncode 1 versionname 10 enabling multidex support multidexenabled true signingconfigs debug storefile filedebugkeystore release productflavors define separate dev and prod product flavors dev dev utilizes minsdkversion 21 to allow the android gradle plugin to predex each module and produce an apk that can be tested on android lollipop without time consuming dex merging processes minsdkversion 17 prod the actual minsdkversion for the application minsdkversion 17 buildtypes debug minifyenabled false release signingconfig signingconfigsrelease minifyenabled false proguardfiles getdefaultproguardfileproguardandroidtxt proguardrulespro apply from dependencies compile comandroidsupportmultidex101 compile comgoogleguavaguava180 compile orgfunctionaljavafunctionaljava44 compile ioreactivexrxandroid101 because rxandroid releases are few and far between it is recommended you also explicitly depend on rxjavas latest version for bug fixes and new features compile ioreactivexrxjava1014 compile filetreeinclude jar dir libs compile comandroidsupportsupportv42311 compile comandroidsupportsupportv132311 compile comgoogleandroidgmsplayservicesmaps830 compile comgoogleandroidgmsplayserviceslocation830 compile comandroidsupportappcompatv72311 compile comandroidsupportdesign2311 compile comandroidsupportcardviewv72311 compile comandroidsupportpalettev72311 compile comjakewhartonbutterknife701 compile comgooglemapsandroidandroidmapsutils04 compile comgithubchrisbanesactionbarpulltorefreshlibrary099 compile comnhaarmanlistviewanimationslibrary260 compile comsquareuppicassopicasso252 compile dehdodenhofcircleimageview200 compile jpwasabeefrecyclerviewanimators201 compile combartoszlipinskiviewpropertyobjectanimator110 compile comandroidmapsextensionsandroidmapsextensions210 compile comparseboltsboltsandroid121 compile comparseparseandroid1103 compile comparseparseuiloginandroid001 compile comparseparseuiwidgetandroid001 uncomment if using facebook login optional maven dependency compile comfacebookandroidfacebookandroidsdk460 compile filetreedir libs include parsejar compile filetreedir libs include parsecrashreportingjar compiledekeyboardsurferandroidwidgetcrouton184aar maybe drop the aar later exclusion is not neccessary but generally a good idea exclude group comgoogleandroid module supportv4 compile projectstripe compile iocardandroidsdk501 compile comastuetzpagerslidingtabstrip101 fork of pager sliding tab strip that supports colorstatelists for tab text color compile projectpagerslidingtabstripmagicgoose1c26523library compile projectrecyclerviewanimators compile projectanimators compilecomcrashlyticssdkandroidcrashlytics253aar transitive true toplevel buildgradle toplevel build file where you can add configuration options common to all subprojectsmodulesbuildscript repositories mavencentral dependencies classpath comandroidtoolsbuildgradle150 classpath metatarkaretrolambdaprojectlomboklombokast023a2 plugins id metatarkaretrolambda version 323allprojects repositories mavencentral note this is very hard to google for because most answers deal with the clientside ie users getting this error when trying to download apps update 12installing the signed apk manually with adb install produces failure install failed dexopt and the following logcat stack traceit should be noted that running the debug version of the app with a minsdkversion of 21 on my phone via android studio works flawlesslythis could be related to multidex when i change my minsdkversion to 21 the app installs fine but if i change it to 17 it fails heres an expanded version of the above stacktrace19 155058474 1918619186 dandroidruntime start comandroidinternalosruntimeinit uid 20 19 155058477 1918619186 dandroidruntime checkjni is off19 155058642 1918619186 dandroidruntime calling main entry comandroidcommandspmpm19 155058706 39073907 dfinsky 1 packageverificationreceiveronreceive verification requested id 3719 155058713 39073907 dfinsky 1 workertaskonpreexecute verification requested for id 37 datafiledatalocaltmpiogivenowapp flags114 fromverificationactivityfalse19 155059860 39073934 iqtaguid failed write ctrlu 44 res1 errno2219 155059860 39073934 iqtaguid untagging socket 44 failed errno2219 155059860 39073934 wnetworkmanagementsockettagger untagsocket44 failed with errno 2219 155059863 39073907 dfinsky 1 2onresponse verification id37 response019 155059877 39073907 dfinsky 1 packageverificationreceiveronreceive verification requested id 3719 155059890 1901719033 ddefcontainer copying datalocaltmpiogivenowapp to baseapk19 155100633 809869 dpackagemanager renaming dataappvmdl171337004tmp to dataappiogivenowapp19 155100660 809869 ipackagemanager running dexopt on dataappiogivenowapp1baseapk pkgiogivenowapp isaarm vmsafemodefalse19 155100711 1920319203 idex2oat systembindex2oat zipfd6 ziplocationdataappiogivenowapp1baseapk oatfd7 oatlocationdatadalvikcachearmdata instructionsetarm instructionsetfeaturesdiv runtimearg xms64m runtimearg xmx512m swapfd2419 155101187 1920319203 idex2oat decided to run without swap19 155101560 1920319206 wdex2oat before android 41 method int androidsupportv7internalwidgetlistviewcompatlookforselectablepositionint boolean would have incorrectly overridden the packageprivate method in androidwidgetlistview19 155106063 1920319207 alibc fatal signal 11 sigsegv code 1 fault addr 0xd94e27a4 in tid 19207 compiler driver19 155106066 1920319203 alibc fatal signal 11 sigsegv code 1 fault addr 0xd94e27a4 in tid 19203 main19 155106102 1920319205 alibc fatal signal 11 sigsegv code 1 fault addr 0xd94e27a4 in tid 19205 compiler driver19 155106166 351351 idebug 19 155106166 351351 idebug build fingerprint googleshamushamu511lmy47z1860966userreleasekeys19 155106166 351351 idebug revision 3369619 155106167 351351 idebug abi arm19 155106167 351351 idebug pid 19203 tid 19207 name compiler driver systembindex2oat 19 155106167 351351 idebug signal 11 sigsegv code 1 segv maperr fault addr 0xd94e27a419 155106168 8091027 wnativecrashlistener could not find processrecord for pid 1920319 155106193 351351 idebug r0 b163600c r1 13f513f4 r2 b15af0 r3 08700c19 155106193 351351 edebug am write failure 32 broken pipe19 155106193 351351 idebug r4 013f4 r5 d94d87f4 r6 73406b18 r7 d94d880719 155106193 351351 idebug r8 b6f70a70 r9 d94d8804 sl b6a46df4 fp 019 155106194 351351 idebug ip 0 sp b0dffb20 lr b6d47065 pc b6d46e26 cpsr 8007003019 155106194 351351 idebug 00 pc 0dbe26 systemliblibartso artclasslinkerresolvemethodexceptionhandlertypesartdexfile const artmirrorartmethod819 155106194 351351 idebug 01 pc 0dc061 systemliblibartso artclasslinkerresolveclassexceptionhandlertypesartdexfile const arthandleartmirrorclass10819 155106194 351351 idebug 02 pc 0dc28b systemliblibartso artclasslinkerverifyclassarthandleartmirrorclass51819 155106194 351351 idebug 03 pc 00145be1 systemliblibartcompilerso19 155106194 351351 idebug 04 pc 0013f25d systemliblibartcompilerso19 155106194 351351 idebug 05 pc 002438ed systemliblibartso artthreadpoolworkerrun4419 155106194 351351 idebug 06 pc 002441ed systemliblibartso artthreadpoolworkercallbackvoid6019 155106194 351351 idebug 07 pc 016baf systemliblibcso pthread startvoid3019 155106194 351351 idebug 08 pc 014af3 systemliblibcso start thread619 155106403 809850 ibootreceiver copying datatombstonestombstone 03 to dropbox system tombstone19 155106452 351351 edebug unexpected waitpid response n19203 status0b19 155106452 351351 edebug tid exited before attach completed tid 1920319 155106453 355355 einstalld dexinv end dataappiogivenowapp1baseapk status0x0b process failed19 155106457 809869 wpackagemanager package could not be installed in dataappiogivenowapp1 comandroidserverpmpackagemanagerexception scanpackageli at comandroidserverpmpackagemanagerservicescanpackagedirtylipackagemanagerservicejava5955 at comandroidserverpmpackagemanagerservicescanpackagelipackagemanagerservicejava5267 at comandroidserverpmpackagemanagerserviceinstallnewpackagelipackagemanagerservicejava10177 at comandroidserverpmpackagemanagerserviceinstallpackagelipackagemanagerservicejava10707 at comandroidserverpmpackagemanagerserviceaccess2300packagemanagerservicejava234 at comandroidserverpmpackagemanagerservice6runpackagemanagerservicejava8627 at androidoshandlerhandlecallbackhandlerjava739 at androidoshandlerthispatchmessagehandlerjava95 at androidoslooperlooplooperjava135 at androidoshandlerthreadrunhandlerthreadjava61 at comandroidserverservicethreadrunservicethreadjava4619 155106572 809869 iart explicit concurrent mark sweep gc freed 1214595mb allocspace objects 344mb los objects 27 free 41mb57mb paused 1454ms total 81174ms19 155106584 1918619186 iart systemexit called status 19 155106584 1918619186 iandroidruntime vm exiting with result code 1the above gives more clues it looks like dex2oat is failing with a sigsegv in the compiler driver i am going to continue googling around so far this does not seem like the more common linearalloc limit that other people with failing package installs are running intoupdate 3i am now able to get a working prodrelease build installed by enabling proguard with the following rules file add project specific proguard rules heredontobfuscate if obfuscation is enabled we get javalangnosuchfieldexception producerindex wtfretrolambdadontwarn javalanginvokekeep class butterknife dontwarn butterknifeinternalkeep class viewbinder keepclasseswithmembernames class butterknife fieldskeepclasseswithmembernames class butterknife methodskeep class comparse dontwarn comparsedontwarn okiodontwarn fj guavadontwarn sunmiscunsafe picassodontwarn comsquareupokhttphowever devdebug builds still cannot be installedfor some reason i am seeing a more detailed stacktrace now note that the signal issued to dex2oat is now sigabrt rather than sigsegv,['android'] +1024791,select countid in linq is there any way to write a linq query to result in select countid from tbl1because tbl1selectqqidcountdoes not translate to the result that i wantupdate it returns select count from tbl1update after answer i tested the scenario with more than 210,['c#'] +1025005,android studio issue in buildgradle uncaught translation error executionexception outofmemory i am having a strange problem with my android app in android studio everything seemed to be working fine until today after adding some new files and making some updates to buildgradlethe error message i am seeing is the followinguncaught translation error javautilconcurrentexecutionexception javalangoutofmemoryerror gc overhead limit exceededuncaught translation error javautilconcurrentexecutionexception javalangoutofmemoryerror gc overhead limit exceededuncaught translation error javautilconcurrentexecutionexception javalangoutofmemoryerror gc overhead limit exceededuncaught translation error javautilconcurrentexecutionexception javalangoutofmemoryerror gc overhead limit exceededuncaught translation error javautilconcurrentexecutionexception javalangoutofmemoryerror gc overhead limit exceededuncaught translation error javautilconcurrentexecutionexception javalangoutofmemoryerror gc overhead limit exceeded6 errors abortingerrorexecution failed for task myapplicationdexdebug comandroididecommonprocessprocessexception orggradleprocessinternalexecexception process command cprogram filesjavajdk180 11binjavaexe finished with nonzero exit value 1do you know if there is any issue with my buildgradle below the new lines are under new dependencies added below this line i also set multidexenabled to trueapply plugin comandroidapplicationandroid compilesdkversion 23 buildtoolsversion 2301 uselibrary orgapachehttplegacy defaultconfig applicationid commyapp minsdkversion 14 targetsdkversion 21 multidexenabled true compileoptions sourcecompatibility javaversionversion 1 7 targetcompatibility javaversionversion 1 7 buildtypes release minifyenabled false proguardfiles getdefaultproguardfileproguardandroidtxt proguardrulestxt uselibrary orgapachehttplegacydependencies compile fileslibsaspectjrt182jar compile fileslibsisoparser10rc27jar compile fileslibsmultiscreenandroid1jar compile fileslibspicasso252jar compile fileslibsvolleyjar compile comfacebookandroidfacebookandroidsdk450 compile comandroidsupportappcompatv72301 compile comandroidsupportsupportv13 new dependencies below this line compile comandroidsupportdesign2301 compile comandroidsupportcardviewv72310 compile comgithubbumptechglideglide360 compile dehdodenhofcircleimageview130 used to optimize rendering of list views compile comandroidsupportrecyclerviewv72310 compile ukcochrisjenxcalligraphy210 compile comsquareuppicassopicasso252 compile comgoogleandroidgmsplayservices780 compile commcxiaokevolleylibraryaar100 compile comgoogleandroidgmsplayservicesplus780 compile comgoogleandroidgmsplayserviceswallet780,"['java', 'android']" +1025084,how does this 128 bit integer multiplication work in assembly x8664 i am reading computer systems a programmers perspective and the homework was to describe how this algorithm worksc functionvoid store prod int128 dest int64 t x int64 t y dest x int128yassemblymovq rdx raxcqtomovq rsi rcxsarq 63 rcximulq rax rcximulq rsi rdxaddq rdx rcxmulq rsiaddq rcx rdxmovq rax rdimovq rdx 8rdireti do not know why it performs xh yl yh xl value which we add after unsigned multiplication,['c'] +1025135,socketio unable to emit data to clients unique room i am using nodejs to create a media upload microservice this service works by taking in the binary data of the upload to a buffer and then using the s3 npm package to upload to an s3 bucket i am trying to use the eventemitter present in that package which shows the amount of data uploaded to s3 and send that back to the client which is doing the uploading so that they can see upload progress i am using socketio for this sending of progress data back to the clientthe problem i am having is that the emit event in socketio will send the upload progress data to all connected clients not just the client which initiated the upload as i understand it a socket connects to a default room on connection which is mirrored by the id on the client side according to the official docs using sockettoidemit should send the data scoped only to that client but this is not working for meupdated example codeserverjsvar http requirehttpusers requiredataapp requireappusersvar server httpcreateserverappserverlistenappgetport function consolelogexpress server listening on port appgetportvar io requiresocketjslistenserversocketjsvar socketio requiresocketiovar socketconnection exports moduleexports socketconnectionlisten function listenapp io socketiolistenapp exportssockets iosockets iosocketsonconnection function socket socketjoinsocketid socketonthisconnect function consolelogdevice socketid thisconnected socketconnectionupload function upload data sockettosocketidemitprogress progressdataprogressamountdataprogresstotal100 return io s3uploadjsvar config requireconfigawsjsonvar s3 requires3var path requirepathvar fs requirefsvar busboy requirebusboyvar inspect requireutilinspectvar io requiresocketjsvar s3upload exports moduleexports s3uploadupload function uploadparams start uploading to uploadervar uploader clientuploadfileparamsuploaderonerror functionerr consoleerrorthere was a problem uploading the file to bucket either the params are incorrect or there is an issue with the connection errstack resjsonresponsehtml spanthere was a problem uploading the file to bucket either the params are incorrect or there is an issue with the connection please refresh and try againspan throw new errorerruploaderonprogress function iouploaduploaderuploaderonend function s3uploaddeletefileparamslocalfilewhen using debug node myappjs i see the socketioparser taking in this information but it is not emitting it to the clientsocketioparser encoding packet type2dataprogressprogress9579421709825nsp 0mssocketioparser encoded type2dataprogressprogress9579421709825nsp as 2progressprogress9579421709825 0mshowever if i remove the to portion of this code it sends the data to the client albeit to all clients which will not help at alliosocketsonconnection functionsocket socketjoinsocketid socketemitprogress progress dataprogressamountdataprogresstotal100debug node myappjssocketioclient writing packet type2dataprogressprogress93823786632886nsp 1ms socketioparser encoding packet type2dataprogressprogress93823786632886nsp 1ms socketioparser encoded type2dataprogressprogress93823786632886nsp as 2progressprogress93823786632886 0ms enginesocket sending packet message 2progressprogress93823786632886 0ms enginesocket flushing buffer to transport 0ms enginews writing 42progressprogress9984186540937002 0ms enginews writing 42progressprogress93823786632886 0mswhat am i doing wrong here is there a different way to emit events from the server to only specific clients that i am missing,['javascript'] +1025274,skobbler callout tail imageview thisplayed incorrectly android sdk 251 i have code that adds a custom annotation callout view to be thisplayed whenever an annotation is selected my skobbler mapview overridepublic void onannotationselectedfinal skannotation annotation mappopup mapholdergetcalloutview set the callout viewas background color mappopupsetviewcolorcolorwhite view view getlayoutinflaterinflaterlayoutmap callout null mappopupsetcustomviewview setting 2nd parameter to true will cause tail to be thisplayed mappopupshowatlocationannotationgetlocation true i also request in the showatlocation call that the callout view be thisplayed with the tail imageview however when i test in the app i see that the tail appears at the top of my map surface holder relativelayout container instead of at the bottom of the framelayout container that thisplays the callout popup viewwhen i pan the map i can see that the tail view moves left and right relative to the movement of the callout view but it remains aligned to the top of the map surface holder container never moving up or down do i need to add some code somewhere to make the tail image view aware of where it should be placed in the yaxis direction of the relativelayout containeri did try adding a call to mappopupsetverticaloffsetoffset to see if that had any effect but the tail image remained locked to the top of the screenone other difference i could see between my custom callout view and the default one provided by the skobbler is that the standard view is a relativelayout container while my implementation is a framelayout however i am not sure that it should matter since the tail imageview here is being added to the parent of my callout view not as a childthank you in advance for any help in the matter and let me know if any additional details would be helpfulthanks,"['java', 'android']" +1025360,why cannot i pickle a typingnamedtuple while i can pickle a collectionsnamedtuple why cannot i pickle a typingnamedtuple while i can pickle a collectionsnamedtuple how can i manage to do pickle a namedtuplethis code shows what i have tried so farfrom collections import namedtuplefrom typing import namedtuplepersontyping namedtuplepersontyping firstnamestrlastnamestrpersoncollections namedtuplepersoncollections firstnamelastnamept persontypingjohnsmithpc personcollectionsjohnsmithimport pickleimport tracebacktry with openpersontypingpkl wb as f pickledumppt fexcept tracebackprint exctry with openpersoncollectionspkl wb as f pickledumppc fexcept tracebackprint excoutput on the shell python3 provapy traceback most recent call last file provapy line 16 in module pickledumppt f picklepicklingerror cannot pickle class typingpersontyping attribute lookup persontyping on typing failed,['python'] +1025431,depth page transform on uiviewswift how to create the depth page transform animation top to bottom bottom to top like this i searched in google but i am not get any idea for how to implement in iossample output like this,"['ios', 'objective-c']" +1025521,error webgl exceeded 16 live webgl contexts for this principal losing the least recently used one i have a javascript using the threejs package i made some changes saw the error and undid all of the changes i have made however the error remainederror webgl exceeded 16 live webgl contexts for this principal losing the least recently used onea googlesearch did not reveal something useful 16 hits anyone any idea what is going on maybe this error has nothing to do with my script but with the browser itself,['javascript'] +1025592,404 page on prestashop multistore i have just enabled multistore in my 161 prestashop and added a new shop besides of my default shopdefault shop address new multistore address it seems everything is fine in home page of new shop however refereing to pages like contactus bestsaled and other pages prestashop thisplays 404 error pagehow can this be fixedps url rewriting is also enabled on my shophere is the content of htaccess file start do not remove this comment prestashop will keep automatically the code outside this comment when htaccess will be generated again htaccess automaticaly generated by prestashop ecommerce opensource solution ifmodule mod rewritecifmodule mod envcsetenv http mod rewrite onifmodulerewriteengine ondomain laklakirrewritecond http host laklakirrewriterule erewritebaserewriterule api api lrewriterule api envrewritebasewebservicethispatcherphpurl1 qsal imagesrewritecond http host laklakirrewriterule 09 azaz0909jpg envrewritebaseimgp1123jpg lrewritecond http host laklakirrewriterule 0909 azaz0909jpg envrewritebaseimgp121234jpg lrewritecond http host laklakirrewriterule 090909 azaz0909jpg envrewritebaseimgp12312345jpg lrewritecond http host laklakirrewriterule 09090909 azaz0909jpg envrewritebaseimgp1234123456jpg lrewritecond http host laklakirrewriterule 0909090909 azaz0909jpg envrewritebaseimgp123451234567jpg lrewritecond http host laklakirrewriterule 090909090909 azaz0909jpg envrewritebaseimgp12345612345678jpg lrewritecond http host laklakirrewriterule 09090909090909 azaz0909jpg envrewritebaseimgp1234567123456789jpg lrewritecond http host laklakirrewriterule 0909090909090909 azaz0909jpg envrewritebaseimgp1234567812345678910jpg lrewritecond http host laklakirrewriterule c09 azaz0909jpg envrewritebaseimgc123jpg lrewritecond http host laklakirrewriterule cazaz 09jpg envrewritebaseimgc12jpg l alphaimageloader for ie and fancyboxrewritecond http host laklakirrewriterule images iejpegpnggif jsjquerypluginsfancyboximages12 ldomain laklakirrewritecond http host laklakirrewriterule erewritebaserewriterule api api lrewriterule api envrewritebasewebservicethispatcherphpurl1 qsalrewritecond http host laklakirrewriterule ghods ghods lrrewritecond http host laklakirrewriterule ghods 1 l imagesrewritecond http host laklakirrewriterule 09 azaz0909jpg envrewritebaseimgp1123jpg lrewritecond http host laklakirrewriterule 0909 azaz0909jpg envrewritebaseimgp121234jpg lrewritecond http host laklakirrewriterule 090909 azaz0909jpg envrewritebaseimgp12312345jpg lrewritecond http host laklakirrewriterule 09090909 azaz0909jpg envrewritebaseimgp1234123456jpg lrewritecond http host laklakirrewriterule 0909090909 azaz0909jpg envrewritebaseimgp123451234567jpg lrewritecond http host laklakirrewriterule 090909090909 azaz0909jpg envrewritebaseimgp12345612345678jpg lrewritecond http host laklakirrewriterule 09090909090909 azaz0909jpg envrewritebaseimgp1234567123456789jpg lrewritecond http host laklakirrewriterule 0909090909090909 azaz0909jpg envrewritebaseimgp1234567812345678910jpg lrewritecond http host laklakirrewriterule c09 azaz0909jpg envrewritebaseimgc123jpg lrewritecond http host laklakirrewriterule cazaz 09jpg envrewritebaseimgc12jpg l alphaimageloader for ie and fancyboxrewritecond http host laklakirrewriterule images iejpegpnggif jsjquerypluginsfancyboximages12 l thispatcherrewritecond request filename s orrewritecond request filename l orrewritecond request filename drewritecond http host laklakirrewriterule nclrewritecond http host laklakirrewriterule envrewritebaseindexphp nclifmoduleaddtype applicationvndmsfontobject eotaddtype fontf ttfaddtype fontotf otfaddtype applicationxfontwoff woffifmodule mod headersc filesmatch ttfttcotfeotwoffsvg header add accesscontrolalloworigin filesmatchifmoduleif rewrite mod is not enablederrordocument 404 indexphpcontroller404 end do not remove this comment prestashop will keep automatically the code outside this comment when htaccess will be generated again,['php'] +1025632,using auto in output parameter is there a way to use auto keyword in this scenariovoid foobar output output bar int main imaginary code auto a fooaof course it impossible to know what type of a so the solution should be to merge them in one sentence in a way or another is this available,['c++'] +1025695,visual studio professional 2015 and windows 10 all kinds of ide errors i have recently done the following on my macbook proinstalled vmware 8 and updated to latest versioninstalled visual studio 2015 from msdn licensed via subscription updated extensionsetc via the extensionsupdates menucloned my repositoryopened a solution originally created with vsnet 2013 4a allowed nuget to restore packages which it didattempted to get on and do workthe problem here is that it is regularly unusable for the following reasonsi regularly get object reference not set to an instance of an object when trying to close the ide i have to kill devenvexe from taskmgri regularly get value cannot be null parameter name compositionservice when trying to add references i simply cannot add referencesi see regular dialog prompts telling me that extensions have crashed and would i like to continue seeing this error messageit is incredibly slow to react by comparison with vs2013 which was relatively snappyi have a feeling that all are related to something and finding that something is my goali have so far removed everything from the componentmodelcache folder in the app data for the 140 folder which prompted a load of reloading of mef components whatever they are when i reloaded the solution this does not appear to have done a great deal but it was stated as a potential solution for the cant load package x problemit is random how long it is usable before these errors manifest themselves but it is very frequent throughout the day that i am killing the executable and reopeningi find it hard to believe that this software was shipped in this condition so i assume that there is something that i need to do to remedy this situation with my local environment solution projects or something elsei am going to try and create a new solution and add the projects one by one but all i am really doing is trial and errorclutching at strawsany advice on how to remedy my ide i have no hope of being remotely productive at present,['.net'] +1025884,localhost error with laravel 51 on ubuntu 1404 have had a look at previous articles here but with no luck i have just installed laravel 51 via composer i have been following the official documentation for installation located here i am not using homestead and i am neither using a virtual environment while everything works fine i am having trouble hosting the project up on my web server while regular php files are hosted easily and are accessible via my localhost accessing the public folder of laravel via my localhost is giving me a 500 internal server error following the tutorial my publichtaccess file has the following contentsoptions followsymlinksrewriteengine onrewritecond request filename drewritecond request filename frewriterule indexphp lmy error logs most recent entry is as followsthu nov 19 2510012710 2015 corealert pid 6461 client 12700143086 varwhtmlblogpublichtaccess options not allowed hereas for permissions i have given permissions to all files and folders within my laravel apps folder i am running apache247 ubuntu and php 5591ubuntu414 on my machine please do let me know if you need any other information any help will be highly appreciatededit solved the problem by adding the following in my apache2confdirectory allowoverride alldirectorythanks everyone,['php'] +1026128,intersection of two linestrings geopandas let us say i have the following to geodataframes of linestrings one of which represents roads and one of which represents contour lines import geopandas as gpd import geopandastools import shapely from shapelygeometry import r1linestring12325 r2linestring1430 roadsgpdgeodataframemain stspruce stgeometryr1r2 columnsname roads name geometry0 main st linestring 1 2 3 251 spruce st linestring 1 4 3 0 c1linestringpoint12buffer5exterior c2linestringpoint12buffer75exterior c3linestringpoint12buffer9exterior contoursgpdgeodataframe1009080geometryc1c2c3 columnselevation contours elevation geometry0 100 linestring 15 2 14975923636099 195099141 90 linestring 175 2 1746388545004148 19264872 80 linestring 19 2 18956254004977 19117845 if i plot these they look like thisthere are 3 contour line and 2 roads i want to find the elevation at each point along each road basically i want to intersect roads and contours which should give me 12 points and preserve the attributes from both geodataframes road name and elevation i can generate the 12 points as such by using an intersection of the unions of the two geodataframes intersectiongpdgeodataframegeometrylistroadsunary unionintersectioncontoursunary union intersection geometry0 point 018644118110415 2138983051476381 point 02674451642029509 21584306455253692 point 03636038969321072 26363961030678933 point 04696699141100895 25303300858899114 point 05385205980649126 21923150747581145 point 06464466094067262 23535533905932746 point 1353553390593274 16464466094067267 point 1399321982208571 2291524760728 point 1530330085889911 1469669914110099 point 1636396103067893 136360389693210710 point 1670759586114587 2384494826432411 point 1827239686607525 2353404960825941 however how do i now get the road name and elevation for each of those 12 points a spatial join does not behave as i would expect and only returns 4 points all 12 should intersect with the line files since they were created that way by definition gpdtoolssjoinintersection roads geometry index right name2 point 03636038969321072 2636396103067893 1 spruce st3 point 04696699141100895 2530330085889911 1 spruce st5 point 06464466094067262 2353553390593274 1 spruce st6 point 1353553390593274 1646446609406726 1 spruce st any suggestions as to how i can do thiseditit appears that the issue has to do with how the intersection points are created if i buffer the roads and contours by a very small amount the intersection works as expected see below roadsbuffgpdgeodataframeroads geometryroadsbuffer05 contoursbuffgpdgeodataframecontours geometrycontoursbuffer05 join1gpdtoolssjoinintersection roadsbuffdropindex right1sort index join2gpdtoolssjoinjoin1 contoursbuffdropindex right1sort index join2 geometry name elevation0 polygon 1636395933642091 1363596995290097 spruce st 801 polygon 1530329916464109 1469663012468079 spruce st 902 polygon 1353553221167472 1646439707764716 spruce st 1003 polygon 05385239436706243 2192310454047735 main st 1004 polygon 02674491823047923 2158426108877007 main st 905 polygon 018688004427904 2138978561144256 main st 806 polygon 06464467873602107 2353546141571978 spruce st 1007 polygon 04696700920635739 2530322836868614 spruce st 908 polygon 03636040748855915 26363854046597 spruce st 809 polygon 1399312865255344 22919147068011 main st 10010 polygon 1670752113626148 23849053114361 main st 9011 polygon 1827232214119086 2353409065675979 main st 80 the above is the desired output although i am not sure as to why i have to buffer the lines to get them to intersect the points that were created from the intersection of the lines,['python'] +1026201,how to get single characters from string in ios for gujrati languageother language i am trying to get single characters from nsstring like a1aa34aa a34a a i want output like 1a1aa34aa a 2 a34a 3 a but output is coming like this 1aa aa aa aa1 aa aa 2 a a aa aa aa34 aa aa 3aa a aa a aai have used code like belownsmutablearray array nsmutablearray allocinit for int i0 istrelementlength i nsstring str strelement substringwithrangensmakerangei 1 array addobjectstr nslogarraylet us take strelement as a then i got output like this aa a aa a aabut i need output like this ais there any way that i can get the desired output any method available directly in ios or need to create it by my self then any way or idea how to create itany help is appreciatedthanks in advanced,"['ios', 'objective-c']" +1026390,optimal sse unsigned 8 bit compare i am trying to find the most way of performing 8 bit unsigned compares using sse up to sse 42 the most common case i am working on is comparing for 0u eg mm cmpgt epu8v mm setzero si128 1which of course can also be considered to be a simple test for nonzerobut i am also somewhat interested in the more general case eg mm cmpgt epu8v1 v2 2the first case can be implemented with 2 instructions using various different methods eg compare with 0 and then invert the result the second case typically requires 3 instructions eg subtract 128 from both operands and perform signed compare see this question for various 3 instruction solutionswhat i am looking for ideally is a single instruction solution for 1 and a two instruction solution for 2 if neither of these are possible then i am also interested in thoughts as to which of the various possible 2 or 3 instruction implementations is most efficient on modern intel cpus sandy bridge ivy bridge haswellbest implementations for case 2 so farcompare equal with unsigned max and invert resultdefine mm cmpgt epu8v0 v1 mm andnot si128 mm cmpeq epi8 mm max epu8v0 v1 v1 mm set1 epi81two arithmetic instructions one bitwise 133 throughputinvert sign bits for both arguments subtract 128 and use signed comparedefine mm cmpgt epu8v0 v1 mm cmpgt epi8 mm xor si128v0 mm set1 epi8128 mm xor si128v1 mm set1 epi8128one arithmetic instruction two bitwise 116 throughputbest implementations for case 1 derived from case 2 implementations above1define mm cmpgtz epu8v0 mm andnot si128 mm cmpeq epi8v0 mm set1 epi80 mm set1 epi81one arithmetic instruction one bitwise 083 throughput2define mm cmpgtz epu8v0 mm cmpgt epi8 mm xor si128v0 mm set1 epi8128 mm set1 epi8128one arithmetic instruction one bitwise 083 throughput,['c'] +1026534,how to make segue animation horizontal without uinavigationcontroller i am using a uisplitviewcontroller with a masterviewcontroller and detailviewcontroller without uinavigationcontrollerscurrenly the segue animation for masterdetail triggered byperformseguewithidentifiershowdetail sender selfconsists in the detailviewcontroller showing up from the bottom upwardshow can i make that animation showing leftwards,['ios'] +1026582,springhateoas 080release compatibility with spring 4 i am using 080release version of springhateos which has spring libraries springcore and springwebmvc in version 323release as a compile time dependencieshowever in runtime i would like to use springcore and springwebmvc in version 422releasedoes anyone know if this version of springhateos is compatible with latest version of spring libraries,['java'] +1026701,how are net compilers able to construct o1 lookups for any t in a hashset i do not understand how a compiler can be smart enough to construct an o1 lookup for myobject where i can put anything insidepublic class myobject i understand how this can be done for a limited number of nonprimitives such as public class myobject int i get set char c get set but how can it possibly know how to do this for any implementation of myobject,"['c#', '.net']" +1026708,lasagnenolearn autoencoder how to get hidden layer output i have trained an autoencoder using lasagnenolearn suppose the network layers are 500 100 100 500 i have trained the neural net like sonetfitx xi want to do something like the followingnetpredictx layer2so i will get the suppressed representation of my data so if my initial data have a shape 10 500 the resulting data will be 10 100i searched but could not find how to do that is it possible with lasagnenolearn,['python'] +1026937,android studio 15 where put emulator options i cannot understand where i need to put emulator options to use kvm after update to version 15 rundebug configuration emulator tab thisappeared,['android'] +1026968,empirical complexity of my library sort implementation does not seem to match anything like on log n i recently heard about the library sort and since i have to make my students work on the insertion sort from which the library sort is derived i decided to build an exercise for them on this new topic the great thing is that this algorithm claims to have a on log n complexity see the title insertion sort is on log n or the text in the wikipedia page from the link abovei am aware that empirical measurements are not always reliable but i tried to do my best and i am a little thisappointed by the following plot blue is the library sort green is the inplace quicksort from rosetta code vertical axes is the average time computed as the mean of many different attempts horizontal axes is the size of the list random lists of size and have integer elements between 0 and 2n the shape of the curve does not really look as something related to on log nhere is my code including the test part did i miss something coding utf8 def library sortl initialization d lenl k noned1 m dbit length floorlog2n 1 for i in ranged k2i1 li main loop ab 12 for i in rangem because multiplication by 2 occurs at the beginning of the loop the first element will not be sorted at first pass wich is wanted because a single element does not need to be sorted a 1 b 1 for j in rangeaminbd1 p 2j1 s kp binary search x y 0 p while yx 1 c xy1 if kc none if kc s x c else y c else ef c1c1 while ke none e 1 while kf none f 1 if ke s y e elif kf s x f else x y e f break insertion if yx 1 k xy1 s else if kx none if kx s y x case may occur for 210 while s none ky s s ky y 1 else kx s kp none rebalancing if b d break if i m1 s p while s 0 if ks none in the following line the order is very important because s and p may be equal in which case we want ks which is kp to remain unchanged ks kp none ks p 2 s 1 return x for x in k if x none def quicksortl array listl quicksortarray 0 lenarray 1 return arraydef quicksortarray start stop if stop start 0 pivot left right arraystart start stop while left right while arrayleft pivot left 1 while arrayright pivot right 1 if left right arrayleft arrayright arrayright arrayleft left 1 right 1 quicksortarray start right quicksortarray left stopimport random timedef testf print testing f name randomseed42 x y for i in 25 50 100 200 300 500 10 50 10 150 250 40 50 10 and 10i 1 m 2i xappendi t timetime for j in rangen f randomrandrange0m for in rangei yappend timetimetn return xyimport matplotlibpyplot as pltx1 y1 testlibrary sortx2 y2 testquicksortpltplotx1y1pltplotx2y2pltshowedit i computed more values switched to the pypy interpreter in order to compute a little more in the same time here is another plot i also added reference curves it is difficult to be sure of it but it still looks a little more like ona2 than on log n,['python'] +1026988,angularjs httppost request using json i want to create a post request using json file it is working for httpget request but do not work for httppost my method for a get request is httpgetdatadata1jsonsuccessfunctionres scopemydataset res it is returning all the json data that i saved in json file now i want to create a post request that saved the data in this json file the method that i used for this var obj id scopeid name scopename http url datadata1json datatype json method post data obj headers contenttype applicationjson successfunctionresponse scopemydataset response errorfunctionerror scopeerror error the error shows in browser post httplocalhost30datadata1json 404 not foundremote address130request urlhttplocalhost30datadata1jsonrequest methodpoststatus code404 not foundresponse headersview sourceconnectionkeepalivecontentlength29contenttypetexthtml charsetutf8datesat 21 nov 2015 061047 gmtxcontenttypeoptionsnosniffxpoweredbyexpressrequest headersview sourceacceptapplicationjson textplain acceptencodinggzip deflateacceptlanguageenusenq08connectionkeepalivecontentlength13contenttypeapplicationjsoncookieconnectsids3allxaaoksigfyafjikxrrqdp2ydr4mqmd2by9r2fcoustykg4ut5yvleak6phz5kqvhcojuuy2bms2fs gaga1124289398014535433dnt1hostlocalhost30originhttplocalhost30refererhttplocalhost30useragentmozilla50 macintosh intel mac os x 10 10 2 applewebkit53736 khtml like gecko chrome460249086 safari53736how can i saved the object data in this json fileplease help me,['javascript'] +1027004,react native android transitions are really slow my react native transitions using the navigator are really slow dropping the javascript thread frames to 0 for a second or two when the animation first starts then picking up to 20 then pausing halfway through and then usually finishing relatively smoothly i am testing on a clean galaxy note 4 so it is not an emulator issuei am rendering empty views with interactionmanagerrunafterinteractions and then a 5element listview after the animation is complete i have compiled the app for production and turned dev mode offis this expectedthe current state of things hopefully to improve or am i probably doing something wrong if so whats the best way to hunt that down i have very little logic running if there is not an easy solution is there a way to thisable animations on navigator transitions,['android'] +1027019,pgp data encryption for use with yubico openpgp smart card i am trying to implement pgp encryption based on yubikey neo openpgp smart card applet in a java application it seems to be a dark art and is not easy to google this stuff but here is where i got so farthe card is initialized keys are generated using gpg tool it generally works i have my public key in asc format and managed to load it into orgbouncycastleopenpgpconnect to the smart card in the usb dongle using javaxsmartcardio apisselect the openpgp appletval pgpaid bytes0xd2 0x76 0x00 0x01 0x24 0x01val answer cardchanneltransmitcommandapdu0x00 0xa4 0x04 0x00 pgpaidsuccessfully present the right pin to the cardval pin 123456return bytes0x00 0x20 0x00 0x82 pinlength pintobytearraycharsetsutf 8send a quasisuccessful see below decipher commandbytes0x00 0x2a 0x80 0x86 datasize data bytes0x00when data xtobytearray the result is sw90 success but no data is returned it is a naive test because the openpgp applet documentation on page 52 mentions thatthe command input except padding indicator byte shall be formatted according to pkcs1 before encryptioni have no idea how to encrypt the data and get it into pkcs1 formati also tried reading through yubico openpgp card implementation tests but it only provides another failing example line 196 i tried running that but the result is different the test expects sw0050 indicating an exception and what i get is sw6f00 no precise diagnosis according to this documenti created a github repository with the entire code it is written in kotlin but should be easy to read,['java'] +1027077,validating check boxes in html i have a form there are 4 options they may be check boxes or radioi want to select multiple options but one is compulsoryi know it is possible in jsjquery but i want a htmlcss base solution,"['html', 'css']" +1027248,during dev how can i block page load until watchify finishes heres a typical workflowedit js filesave file watchify automatically starts rebuilding it for mealttab to browserctrlr to reload pagethat is great except if watchify takes longer than steps 3 and 4 it sucks because you either get the stale code or an erroris there an easy way to guarantee that does not ever happen like a way for watchify to signal to my server that it should wait another split second before trying to load the requested page if such a thing does not exist how do people deal with this problem in practicei must suck at googling because i cannot even find people talking about this problem except this which says add a simple nodebased server that will block on requests until the watch is done running this would avoid the alwaysfrustrating phenomenom of reloading the page only to find the watch has not quite run yet but unfortunately that is an entry in a todo list not something that exists in that repo,['javascript'] +1027272,how to show the google location services permission request dialog above through the lockscreen i am trying to show the google location services turn on gps network data etc dialog through lock screeni am using keyguardmanager to thisable lock screen this works fine as my mainactivity is able to thisable the lock screen however as soon as the google location services dialog shows up the lock screen is back to enable the screen is locked and i cannot get to my mainactivity unless i unlock the screeni have even tried flag show when locked but it did not helphere is my codeprivate keyguardlock thisablescreenlock overrideprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate getwindowaddflagswindowmanagerlayoutparamsflag keep screen on getwindowaddflagswindowmanagerlayoutparamsflag show when locked setcontentviewrmain layout keyguardmanager mykeyguard keyguardmanagergetsystemservicecontextkeyguard service thisablescreenlock mykeyguardnewkeyguardlockthisablekeyguard thisablescreenlockthisablekeyguardprotected synchronized void googleapiclient intialize logetag building googleapiclient googleapiclient new googleapiclientbuilderthis addconnectioncallbacksthis addonconnectionfailedlistenerthis addapilocationservicesapi buildprotected void locationrequest intialize locationrequest new locationrequest locationrequestsetintervalupdate interval in milliseconds locationrequestsetfastestintervalfastest update interval in milliseconds locationrequestsetprioritylocationrequestpriority high accuracyprotected void locationsettingsrequest builder locationsettingsrequestbuilder builder new locationsettingsrequestbuilder builderaddlocationrequestlocationrequest locationsettingsrequest builderbuildoverridepublic void onconnectedbundle connectionhint logetag googleapiclient is connected locationsettings check start protected void locationsettings check start pendingresultlocationsettingsresult result locationservicessettingsapichecklocationsettings googleapiclient locationsettingsrequest resultsetresultcallbackthisis there anyway i can show this google location services dialog through passwordpatternpin etc lock screenthank you very much for your help,['android'] +1027387,correct way to join two double linked list in the linux kernel source the list splice is implemented with list splicestatic inline void list spliceconst struct list head list struct list head prev struct list head next struct list head first listnext why struct list head last listprev firstprev prev prevnext first lastnext next nextprev lastis not the list already pointing to the head of a linked listwhy do we need to fetch listnext instead,['c'] +1027403,applying statelistanimator in recylerviews item will cause flickering effect when calling notifydatasetchanged i realize if i apply androidstatelistanimator on recylerviews item calling adapternotifydatasetchanged will cause undesired flickering effect on certain recylerviews items not all items strangelyheres my recylerviews itemlinearlayout xmlnsandroid androidstatelistanimatoranimlift up androidbackgrounddrawablewhite linearlayoutanimlift up is defined asxml version10 encodingutf8selector xmlnsandroid item androidstate enabledtrue androidstate pressedtrue objectanimator androiddurationandroidintegerconfig shortanimtime androidpropertynametranslationz androidvalueto8dip androidvaluetypefloattype item item objectanimator androiddurationandroidintegerconfig shortanimtime androidpropertynametranslationz androidvalueto4dip androidvaluetypefloattype itemselectorand drawablewhite is defined as drawable namewhitefdrawablewhen i call adapternotifydatasetchanged the following strange flickering effect happens at the last 5 items of recylerview there are total 10 visible items on screenthis problem only happen at api 21 and above because only api 21 supports androidstatelistanimatoris this a bug or i had missed out somethingthe complete minimal workable code can be downloaded from,['android'] +1027662,clicking on thisabled swing components i have a thisabled jtable that provides a popup menuimport javaawteventmouseadapterimport javaawteventmouseeventimport javaxswingjframeimport javaxswingjmenuitemimport javaxswingjpopupmenuimport javaxswingjtablepublic class thisabledtableframe extends jframe public thisabledtableframe setsize200 100 settitlegetclassgetcanonicalname setdefaultcloseoperationjframethispose on close jtable table new jtable addtable tableaddmouselistenernew mouseadapter override public void mousepressedmouseevent e mousereleasede override public void mousereleasedmouseevent e new popupmenu tablesetenabledfalse setvisibletrue public static void mainstring args new thisabledtableframe private class popupmenu extends jpopupmenu public popupmenu jmenuitem menuitem new jmenuitemtest addmenuitem setvisibletrue so when testing this function with assertj swing usingimport orgassertjswingedtguiactionrunnerimport orgassertjswingedtguiqueryimport orgassertjswingfixtureframefixtureimport orgassertjswingjunittestcaseassertjswingjunittestcaseimport orgjunittestpublic class popuptestcase extends assertjswingjunittestcase protected framefixture window override protected void onsetup thisabledtableframe mainframe guiactionrunner executenew guiquerythisabledtableframe protected thisabledtableframe executeinedt return new thisabledtableframe window new framefixturerobot mainframe test public void popupshouldbeopened windowtableshowpopupmenu pomxmlproject xmlns xmlnsxsi xsischemalocation modelversion400modelversion groupidassertjswinginactivetestgroupid artifactidassertjswinginactivetestartifactid version001snapshotversion dependencies dependency groupidorgassertjgroupid artifactidassertjswingjunit45artifactid version120version scopetestscope dependency dependencies build sourcedirectorysrcsourcedirectory plugins plugin artifactidmavencompilerpluginartifactid version33version configuration source17source target17target configuration plugin plugins buildprojectit works fine when the table is enabled but the popupshoudbeopened test on the thisabled table throws the following exception javalangillegalstateexception expecting component javaxswingjtablenamenull rowcount0 columncount0 enabledfalse visibletrue showingtrue to be enabledat orgassertjswingdrivercomponentpreconditionscheckenabledcomponentpreconditionsjava68at orgassertjswingdrivercomponentpreconditionscheckenabledandshowingcomponentpreconditionsjava48at orgassertjswingdrivercomponentdriver2executeinedtcomponentdriverjava5at orgassertjswingedtguitaskrunguitaskjava38at javaawteventinvocationeventthispatchinvocationeventjava312at javaawteventqueuethispatcheventimpleventqueuejava745at javaawteventqueueaccess300eventqueuejava103at javaawteventqueue3runeventqueuejava706at javaawteventqueue3runeventqueuejava704at javasecurityaccesscontrollerdoprivilegednative methodat javasecurityprotectiondomain1dointersectionprivilegeprotectiondomainjava76at javaawteventqueuethispatcheventeventqueuejava715at javaawteventthispatchthreadpumponeeventforfilterseventthispatchthreadjava242at javaawteventthispatchthreadpumpeventsforfiltereventthispatchthreadjava161at javaawteventthispatchthreadpumpeventsforhierarchyeventthispatchthreadjava150at javaawteventthispatchthreadpumpeventseventthispatchthreadjava146at javaawteventthispatchthreadpumpeventseventthispatchthreadjava138at javaawteventthispatchthreadruneventthispatchthreadjava91at orgassertjswingedtguiactionrunnerexecuteguiactionrunnerjava103at orgassertjswingdrivercomponentdrivercheckinedtenabledandshowingcomponentdriverjava552at orgassertjswingdrivercomponentdriverinvokepopupmenucomponentdriverjava519at orgassertjswingfixtureabstractjpopupmenuinvokerfixtureshowpopupmenuabstractjpopupmenuinvokerfixturejava95at guitestcasepopupshouldbeopenedguitestcasejava27at sunreflectnativemethodaccessorimplinvoke0native methodat sunreflectnativemethodaccessorimplinvokenativemethodaccessorimpljava57at sunreflectdelegatingmethodaccessorimplinvokedelegatingmethodaccessorimpljava43at javalangreflectmethodinvokemethodjava606at orgjunitrunnersmodelframeworkmethod1runreflectivecallframeworkmethodjava44at orgjunitinternalrunnersmodelreflectivecallablerunreflectivecallablejava15at orgjunitrunnersmodelframeworkmethodinvokeexplosivelyframeworkmethodjava41at orgjunitinternalrunnersstatementsinvokemethodevaluateinvokemethodjava20at orgjunitinternalrunnersstatementsrunbeforesevaluaterunbeforesjava28at orgjunitinternalrunnersstatementsrunaftersevaluaterunaftersjava31at orgjunitrunnersblockjunit4classrunnerrunchildblockjunit4classrunnerjava73at orgjunitrunnersblockjunit4classrunnerrunchildblockjunit4classrunnerjava46at orgjunitrunnersparentrunnerrunchildrenparentrunnerjava180at orgjunitrunnersparentrunneraccess0parentrunnerjava41at orgjunitrunnersparentrunner1evaluateparentrunnerjava173at orgjunitinternalrunnersstatementsrunbeforesevaluaterunbeforesjava28at orgjunitinternalrunnersstatementsrunaftersevaluaterunaftersjava31at orgjunitrunnersparentrunnerrunparentrunnerjava220at orgeclipsejdtinternaljunit4runnerjunit4testreferencerunjunit4testreferencejava50at orgeclipsejdtinternaljunitrunnertestexecutionruntestexecutionjava38at orgeclipsejdtinternaljunitrunnerremotetestrunnerruntestsremotetestrunnerjava459at orgeclipsejdtinternaljunitrunnerremotetestrunnerruntestsremotetestrunnerjava675at orgeclipsejdtinternaljunitrunnerremotetestrunnerrunremotetestrunnerjava382at orgeclipsejdtinternaljunitrunnerremotetestrunnermainremotetestrunnerjava192as the popup menu obviously works even on the thisabled table how can i get assertj to right click the thisabled table,['java'] +1027766,force ipad pro to full resolution without launch screen i want to use a launch image with my ios app not a launch screen launch images can target devices more precisely than launch screens there is no way to make a launch screen that behaves exactly like a launch imageif you do not have a launch screen in your ios app the ipad pro renders as if the screen resolution were 1024x768 points wide to see this create a new project delete its launch screen and start it in ipod pro simulatoris there a way to get ipad pro to render at native 1366x1024 points without using a launch screen,['ios'] +1027909,attempt to invoke virtual method int androidtextlayoutgetlinecount on a null object reference i am getting null pointer exception randomly usually it works and sometime it crashes i had searched a lot but did not get any help as it there is no proper line from where i get any helpi am also using handler with itmy logcat error is as follows and code is added below it javalangnullpointerexception attempt to invoke virtual method int androidtextlayoutgetlinecount on a null object reference at androidwidgettextviewonmeasuretextviewjava6703 at androidviewviewmeasureviewjava17547 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava5535 at androidwidgetlinearlayoutmeasurechildbeforelayoutlinearlayoutjava1436 at androidwidgetlinearlayoutmeasureverticallinearlayoutjava722 at androidwidgetlinearlayoutonmeasurelinearlayoutjava613 at androidviewviewmeasureviewjava17547 at androidwidgetrelativelayoutmeasurechildhorizontalrelativelayoutjava727 at androidwidgetrelativelayoutonmeasurerelativelayoutjava463 at androidviewviewmeasureviewjava17547 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava5535 at androidwidgetframelayoutonmeasureframelayoutjava436 at androidsupportv7internalwidgetcontentframelayoutonmeasurecontentframelayoutjava135 at androidviewviewmeasureviewjava17547 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava5535 at androidwidgetframelayoutonmeasureframelayoutjava436 at androidviewviewmeasureviewjava17547 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava5535 at androidwidgetframelayoutonmeasureframelayoutjava436 at androidviewviewmeasureviewjava17547 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava5535 at androidwidgetlinearlayoutmeasurechildbeforelayoutlinearlayoutjava1436 at androidwidgetlinearlayoutmeasureverticallinearlayoutjava722 at androidwidgetlinearlayoutonmeasurelinearlayoutjava613 at androidviewviewmeasureviewjava17547 at androidviewviewgroupmeasurechildwithmarginsviewgroupjava5535 at androidwidgetframelayoutonmeasureframelayoutjava436 at comandroidinternalpolicyimplphonewindowdecorviewonmeasurephonewindowjava2615 at androidviewviewmeasureviewjava17547 at androidviewviewrootimplperformmeasureviewrootimpljava2015 at androidviewviewrootimplmeasurehierarchyviewrootimpljava1173 at androidviewviewrootimplperformtraversalsviewrootimpljava1379 at androidviewviewrootimpldotraversalviewrootimpljava1061 at androidviewviewrootimpltraversalrunnablerunviewrootimpljava5885 at androidviewchoreographercallbackrecordrunchoreographerjava767 at androidviewchoreographerdocallbackschoreographerjava580 at androidviewchoreographerdoframechoreographerjava550 at androidviewchoreographerframethisplayeventreceiverrunchoreographerjava753 at androidoshandlerhandlecallbackhandlerjava739 at androidoshandlerthispatchmessagehandlerjava95 at androidoslooperlooplooperjava135 at androidappactivitythreadmainactivitythreadjava5254 at javalangreflectmethodinvokenative method at javalangreflectmethodinvokemethodjava372 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava903 at comandroidinternaloszygoteinitmainzygoteinitjava698this is my code as follows here it usually crash on click of register or forget button on first install and after that it usually works fine but sometime it gives me error public class login extends appcompatactivity implements viewonclicklistenerprocessedresult private handler uithreadhandler private context context private edittext ed passworded username override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity login storagemanager storagemanagernew storagemanagerthisabc string accesstokencheckstoragemanagergetvalueconstantssharedpreferenceslaccesstoken null ifaccesstokenchecknull generalfunctionsmovetonextactivitymainactivityclassthis uithreadhandler new uithreadhandler new threadnew runnable override public void run init start initialization part private final void init contextthis fontsmanagerinitformassetsthis fontslatoregularttf fontsmanagerchangefontsthis textview mytextview generalfunctionsfindviewbyidandcastthis ridlogin tv noaccount mytextviewsetmovementmethodnew linktouchmovementmethod mytextviewsethighlightcolorgetresourcesgetcolorandroidrcolortransparent spannablestring myspannable new spannablestringmytextviewgettexttostring touchablespan touchablespan new touchablespancolorparsecolor606060getresourcesgetcolorrcolorcolorbluecolortransparent override public void onclickview textview generalfunctionssimplemovetonextactivityregisterclass context myspannablesetspantouchablespan generalfunctionsgettextmytextviewindexofregister generalfunctionsgettextmytextviewlength 0 mytextviewsettextmyspannable textviewbuffertypespannable textview tv forgetpassword generalfunctionsfindviewbyidandcastthisridlogin tv foregetpassword generalfunctionssettextcolorselectorcolorparsecolor606060getresourcesgetcolorrcolorcolorbluetv forgetpassword tv forgetpasswordsetonclicklistenerthis ed password edittext findviewbyidridlogin ed password ed username edittext findviewbyidridlogin ed usrname ed passwordsettransformationmethodnew asteriskpasswordtransformationmethod button bt login generalfunctionsfindviewbyidandcastthisridlogin bt signin setselectorrdrawablebig green btn normal bt login button bt linkedind generalfunctionsfindviewbyidandcastthisridlogin bt linkedin setselectorrdrawablebig blue btn normal bt linkedind private final void setselectorfinal int resourceidfinal button button buttonsetonclicklistenerthis try string name getnameofresyrceactivityresourceid string newstringnamereplacenormalpressed statelistdrawable states new statelistdrawable statesaddstatenew int androidrattrstate pressed getdrawablebynameactivitynewstring statesaddstatenew int androidrattrstate focusedgetdrawablebynameactivity newstring statesaddstatenew int getdrawablebynameactivity name ifview instanceof button buttonviewsetbackgroundstates else ifview instanceof imageview imageviewviewsetimagedrawablestates catch exception e public static synchronized drawable getdrawablebynamecontext contextstring name resources resources contextgetresources final int resourceid resourcesgetidentifiername drawable contextgetpackagename return resourcesgetdrawableresourceid override public void onclickview v switch vgetid case ridlogin bt linkedin dwebview transparentdialog dwebviewnewinstance showprogressdialogtransparentdialog constantsdialogconstantsweb break case ridlogin bt signin uithreadhandlersendemptymessageconstantsactivitybasicscodevalidation break case ridlogin tv foregetpassword generalfunctionssimplemovetonextactivity without historyforgetpasswordclass context break listener part override public iresponse imethod void processedresultiresponse iresponse imethod imethod switch imethodtostring case back finish break case showprogress uithreadhandlersendemptymessageconstantsactivitybasicscodeshowdialog break case hideprogress uithreadhandlersendemptymessageconstantsactivitybasicscodehidedialog break handler part private class uithreadhandler extends handler override public void handlemessagemessage msg switch msgwhat case constantsactivitybasicscodeseterror customexception exceptioncustomexceptionmsgobj textview edittextexceptiongettextview edittextseterrorexceptiongetmessage edittextsetfocusabletrue edittextrequestfocus break case constantsactivitybasicscodehidedialog hideprogressdialogconstantsdialogconstantstransparent break case constantsactivitybasicscodeshowdialog dtdialog dtdialogdtdialognewinstance showprogressdialogdtdialogconstantsdialogconstantstransparent break case constantsactivitybasicscodevalidation here validation is done in separate thread new threadnew runnable override public void run try if validationvalidateloginthis generalfunctionsmovetonextactivitymainactivityclass context catch customexception e catch exception for validation is thrown here message message uithreadhandlerobtainmessageconstantsactivitybasicscodeseterror messageobje uithreadhandlersendmessagemessage finally uithreadhandlersendemptymessageconstantsactivitybasicscodehidedialog start break superhandlemessagemsg public finalt extends dialogfragment void showprogressdialogt currentdialogstring tagname fragmentmanager fragmentmanager getsupportfragmentmanager currentdialogshowfragmentmanager tagname public final void hideprogressdialogstring tagname fragmentmanager fragmentmanager getsupportfragmentmanager dialogfragment transparentdialog dialogfragmentfragmentmanagerfindfragmentbytagtagname if transparentdialog null return transparentdialogthismiss xml file xml version10 encodingutf8linearlayout androidlayout widthmatch parent androidlayout heightmatch parent androidorientationvertical androidlayout gravitycenter androidgravitycenter imageview stylestyleimageview androidlayout margintopdimen 7sdp androidsrcmipmapic launcher edittext androidtagstringlogin emailid phone androidlayout margintopdimen 12sdp stylestyleedittext androiddrawableleftdrawableuser icon androidididlogin ed emailphone androidinputtypetext edittext androidtagstringlogin password androidlayout margintopdimen 12sdp androiddrawableleftdrawablepassword icon androidididlogin ed password androidinputtypetextpassword androidhintstringlogin password stylestyleedittext textview androidlayout margintopdimen 11sdp androidididlogin tv foregetpassword androidtextstringlogin forgetpassword stylestyletextview androidtextcolor606060 androidtextstylenormal button androidlayout margintopdimen 30sdp androidididlogin bt signin stylestylebutton androidtextstringlogin singin androidbackgrounddrawablebig green btn normal cltempclickuicustom viewlinethroughtextview androidlayout margintopdimen 12sdp appandroid textcolor606060 androidgravitycenter androidlayout widthmatch parent androidlayout heightwrap content applineheightdimen 2sdp applinecolorcolorcolorgray appandroid textsizedimen 15sdp appandroid textstringlogin or apptextpaddingdimen 10sdp button androidlayout margintopdimen 12sdp androidididlogin bt linkedin stylestylebutton androidtextstringlogin linkedin androidbackgrounddrawablebig blue btn normal textview androidlayout margintopdimen 12sdp androidididlogin tv noaccount androidtextstringlogin noaccount stylestyletextview androidtextstylenormal androidtextcolor606060 androidlayout marginbottomdimen 7sdplinearlayoutviewstub androidididlogin vs empty androidlayout widthmatch parent androidlayout heightmatch parent androidlayout gravitycenter androidgravitycenter androidlayoutlayoutempty view,['android'] +1027971,signalr not working in asp net 5 rc1 i cannot seem to get signalr 3 working on asp net 5 rc1 upgrading from beta8 i tried the latest rc1 package for signalr but had the following problem i tried the microsoftaspnetsignalrserver 300rc115810 packageservicesaddsignalris causing the following errorthe type iservicecollection is defined in an assembly that is not referenced you must add a reference to assembly microsoftextensionsdependencyinjectionabstractions version10 cultureneutral publickeytokennulland appusesignalris causing this onethe type iapplicationbuilder is defined in an assembly that is not referenced you must add a reference to assembly microsoftaspnethttpabstractions version10 cultureneutral publickeytokennullwhen i switch to the microsoftaspnetsignalrserver 300rc215909 package i get a runtime erroran exception of type systemtypeloadexception occurred in mscorlibdll but was not handled in user codeadditional information could not load type microsoftaspnethttprequestdelegate from assembly microsoftaspnethttpabstractions version10 cultureneutral publickeytokenadb9793829ddae60,['c#'] +1028021,convert javascript string to php array i am scraping a website using php to get some data the data i get is a valid javascript array v42 2015 23428 30243 76993 v43 2015 24060 30401 73412 v44 2015 22855 29720 71573 v45 2015 24455 30757 78991 v46 2015 24275 30398 84424i now have this string in php but how can i convert it to a php array,"['javascript', 'php']" +1028026,how do i get the program files directory i am trying to get the program files directory in a 64bit os this code below returns the same answer program files x86consolewritelineenvironmentgetfolderpathenvironmentspecialfolderprogramfilesx86tostringconsolewritelineenvironmentgetfolderpathenvironmentspecialfolderprogramfilestostringany help,['c#'] +1028080,can adding extra const qualifications break functionality assuming compilation went fine as i try to apply constcorrectness for my own code i often have to add const qualifications to function definitions in other modules written by other programmers in order to use those functions in my own code see here on backpatching constcorrectnessi always thought that if everything compiles fine this could impossibly lead to broken functionality as const labels only matter at compile timeyet the other day one of my colleagues insisted that i should rerun all automated tests before i commit code with added const labels where i thought it was sufficient that such code compileddoes he have a point is there a way that applying constcorrectness could break existing functionality edit it is maybe important to note that generally i only have to do this for pointer parameters of functions eg something getsomethingobject pobj to something getsomethingconst object pobj i do not change return types or method constness as this is not a problem for client code,['c++'] +1028129,npm install cannot find module semver i cannot use npm install using command prompt in nodejs i am getting this errors when running npm installmodulejs339 throw err error cannot find module semver at functionmodule resolvefilename modulejs33715 at functionmodule load modulejs28725 at modulerequire modulejs36617 at require modulejs38517 at objectanonymous cusersadminappdataroamingnpmnode modulesnpmlibconfigdefaultsjs614 at module compile modulejs43526 at objectmodule extensionsjs modulejs44210 at moduleload modulejs35632 at functionmodule load modulejs312 at modulerequire modulejs36617please help me,['javascript'] +1028187,c offsetof char arithmetic in this answer int8 t is used for byte pointer arithmeticstdsize t offset offsetofthing bthing thing reinterpret castthingreinterpret castint8 tptr offseti have always used char in the past but the comments are really confusing and nobody responded so i posted this separate questionis char valid and the preferred way of doing these calculations,['c++'] +1028248,css media queries overriding each other thanks stack overflow for helping i have got some custom css i am using to tighten up a design i keep running into this issue where if i change something in one media query say for the iphone 6 that change then affects another device say the iphone 5 its becoming this issue were i am constantly adjusting with no end in sight here are my media break points i am using iphone 6 plus media only screen and mindevicewidth 414px and maxdevicewidth 736px and orientation portrait iphone 6 media only screen and mindevicewidth 375px and maxdevicewidth 667pxand orientation portrait iphone 5s media only screen and mindevicewidth 320px and maxdevicewidth 568px and orientation portrait ipad layouts media only screen and mindevicewidth 768px and maxdevicewidth 1024px ipad landscape media only screen and mindevicewidth 768px and maxdevicewidth 1024px and orientation landscape and webkitmindevicepixelratio 1 any help would be greatly appricated,"['html', 'css', 'iphone']" +1028256,is returning a task violating the cqsprinciple the cqsprinciple separation states that a command should return void the recommendation for async methods is to never return void but instead returning a taskso if i write an async command will that inevitably break the cqsprinciple,['c#'] +1028267,implement imageview rotation with screen limit in the below class i am developing an android application for image zoomingdragrotation to the outside of screen limit first i have to fit the image to the whole screen programmatically and perform the zoomingrotationdrag operation on image to the outside of screen boundary i used the following code everything is working fine what i need except that the rotation feature i confused that matrix calculation so please help anybody how to implement the rotate feature with this codejavacodeimport androidcontentcontextimport androidgraphicsbitmapimport androidgraphicsmatriximport androidgraphicspointfimport androidutilattributesetimport androidviewmotioneventimport androidviewscalegesturedetectorimport androidviewviewimport androidwidgetimageviewpublic class zoomableimageview extends imageview matrix matrix new matrix static final int none 0 static final int drag 1 static final int zoom 2 static final int click 3 int mode none pointf last new pointf pointf start new pointf float minscale 1f float maxscale 4f float m float redundantxspace redundantyspace float width height float savescale 1f float right bottom origwidth origheight bmwidth bmheight scalegesturedetector mscaledetector context context public zoomableimageviewcontext context attributeset attr supercontext attr supersetclickabletrue thiscontext context mscaledetector new scalegesturedetectorcontext new scalelistener matrixsettranslate1f 1f m new float9 setimagematrixmatrix setscaletypescaletypematrix setontouchlistenernew ontouchlistener override public boolean ontouchview v motionevent event mscaledetectorontoucheventevent matrixgetvaluesm float x mmatrixmtrans x float y mmatrixmtrans y pointf curr new pointfeventgetx eventgety switch eventgetaction when one finger is touching set the mode to drag case motioneventaction down lastseteventgetx eventgety startsetlast mode drag break when two fingers are touching set the mode to zoom case motioneventaction pointer down lastseteventgetx eventgety startsetlast mode zoom break when a finger moves if mode is applicable move image case motioneventaction move if the mode is zoom or if the mode is drag and already zoomed if mode zoom mode drag savescale minscale float deltax currx lastx x difference float deltay curry lasty y difference float scalewidth mathroundorigwidth savescale width after applying current scale float scaleheight mathroundorigheight savescale height after applying current scale if scalewidth is smaller than the views width in other words if the image width fits in the view limit left and right movement if scalewidth width deltax 0 if y deltay 0 deltay y else if y deltay bottom deltay y bottom if scaleheight is smaller than the views height in other words if the image height fits in the view limit up and down movement else if scaleheight height deltay 0 if x deltax 0 deltax x else if x deltax right deltax x right if the image doesnt fit in the width or height limit both up and down and left and right else if x deltax 0 deltax x else if x deltax right deltax x right if y deltay 0 deltay y else if y deltay bottom deltay y bottom move the image with the matrix matrixposttranslatedeltax deltay set the last touch location to the current lastsetcurrx curry break first finger is lifted case motioneventaction up mode none int xdiff int mathabscurrx startx int ydiff int mathabscurry starty if xdiff click ydiff click performclick break second finger is lifted case motioneventaction pointer up mode none break setimagematrixmatrix invalidate return true override public void setimagebitmapbitmap bm supersetimagebitmapbm bmwidth bmgetwidth bmheight bmgetheight public void setmaxzoomfloat x maxscale x private class scalelistener extends scalegesturedetectorsimpleonscalegesturelistener override public boolean onscalebeginscalegesturedetector detector mode zoom return true override public boolean onscalescalegesturedetector detector float mscalefactor detectorgetscalefactor float origscale savescale savescale mscalefactor if savescale maxscale savescale maxscale mscalefactor maxscale origscale else if savescale minscale savescale minscale mscalefactor minscale origscale right width savescale width 2 redundantxspace savescale bottom height savescale height 2 redundantyspace savescale if origwidth savescale width origheight savescale height matrixpostscalemscalefactor mscalefactor width 2 height 2 if mscalefactor 1 matrixgetvaluesm float x mmatrixmtrans x float y mmatrixmtrans y if mscalefactor 1 if mathroundorigwidth savescale width if y bottom matrixposttranslate0 y bottom else if y 0 matrixposttranslate0 y else if x right matrixposttranslatex right 0 else if x 0 matrixposttranslatex 0 else matrixpostscalemscalefactor mscalefactor detectorgetfocusx detectorgetfocusy matrixgetvaluesm float x mmatrixmtrans x float y mmatrixmtrans y if mscalefactor 1 if x right matrixposttranslatex right 0 else if x 0 matrixposttranslatex 0 if y bottom matrixposttranslate0 y bottom else if y 0 matrixposttranslate0 y return true override protected void onmeasure int widthmeasurespec int heightmeasurespec superonmeasurewidthmeasurespec heightmeasurespec width measurespecgetsizewidthmeasurespec height measurespecgetsizeheightmeasurespec fit to screen float scale float scalex width bmwidth float scaley height bmheight scale mathminscalex scaley matrixsetscalescale scale setimagematrixmatrix savescale 1f center the image redundantyspace height scale bmheight redundantxspace width scale bmwidth redundantyspace 2 redundantxspace 2 matrixposttranslateredundantxspace redundantyspace origwidth width 2 redundantxspace origheight height 2 redundantyspace right width savescale width 2 redundantxspace savescale bottom height savescale height 2 redundantyspace savescale setimagematrixmatrix,['android'] +1028271,secure javascript get request essentially i have a custom html chart that needs a value from an external secure proxy server right now i am inserting html blocks into the relevant areas on the page that include javascript to get the correct data through an xhttp get request it works wonderfully until we restrict access to our proxy server to be limited to our ssl from our c5 site which is also what we want this prevents the chart from getting the correct value because the html and the javascript get executed on the client side and not through c5 essentially what i need to do i think is to move the get request inside of c5 so that it can pass through with the ssl certificate i then need to take that value and plug it back into the chart below is some pseudocode based on the html code that i am currently dropping into the page this is the actual html block that i am creating div idhtmlblock455 classhtmlblockdiv clasomecustomchart heres the script currently running that gets the necessary data and calls the proper functions to populate the chart script typetextjavascript global var to store updating value var amount 0 open a new http requestvar xhr new xmlhttprequestxhropenget some elasticsearch server truexhronreadystatechange function if xhrreadystate 4 if xhrstatus 200 var person jsonparsexhrresponsetext amount person sourceage grabs the person age chart 328dataupdateto amount updates the above html data value documentgetelementbyidchart 328 textinnerhtml amount else consoleerrorxhrstatustext xhronerror function e consoleerrorxhrstatustextxhrsendnull this function executes on page load and prepares the chartdocumentreadyfunction,"['javascript', 'html']" +1028297,long delays in sending udp packets i have an application that receives processes and transmits udp packetseverything works fine if the port numbers for reception and transmission are differentif the port numbers are the same and the ip addresses are different it usually works fine except when the ip address are on the same subnet as the machine running the application in that last case the send to function requires several seconds to complete instead of a few milliseconds as is usualrx port tx ip tx port result5001 same 5002 ok delay 01 secs subnet 5001 different 5001 ok delay 01 secs subnet5001 same 5001 fails delay 2 secs subnethere is a short program that demonstrates the probleminclude ctimeinclude iostreaminclude stringinclude boostarrayhppinclude boostasiohppusing boostasioipudpusing stdcoutusing stdendlint test const stdstring output ip try unsigned short prev seq no boostasioio service io service build the input socket this is connected to a udp client that is running continuously sending messages that include an incrementing sequence number const int input port 5001 udpsocket input socketio service udpendpointudpv4 input port build the output socket const stdstring output port 5001 udpresolver resolverio service udpresolverquery queryudpv4 output ip output port udpendpoint output endpoint resolverresolvequery udpsocket output socket io service output socketopenudpv4 double output buffer size boostasiosocket basesend buffer size option 8192 2 output socketset optionoption cout tx to output endpointaddress output endpointport endl int count 0 for receive packet unsigned short recv buf 20 udpendpoint remote endpoint boostsystemerror code error int bytes received input socketreceive fromboostasiobufferrecv buf20 remote endpoint 0 error if error error boostasioerrormessage size throw boostsystemsystem errorerror start timer int64 timestart queryperformancecounter large integer timestart send onwards boostsystemerror code ignored error output socketsend to boostasiobufferrecv bufbytes received output endpoint 0 ignored error stop time and thisplay tx time int64 timeend queryperformancecounter large integer timeend int64 f queryperformancefrequency large integer f cout send time secs double timeend timestart double f endl stop after loops if count 10 break catch stdexception e stdcerr ewhat stdendl int main test 1931681200 test 1921681200 return 0the output from this program when running on a machine with address 1921681101tx to 19316812005001send time secs 00232749send time secs 0541566send time secs 0924535send time secs 0449014send time secs 0616714send time secs 00199299send time secs 0746081send time secs 0157972send time secs 0246775send time secs 0775578send time secs 0477618send time secs 00187321tx to 19216812005001send time secs 139485send time secs 3026send time secs 300104send time secs 025927send time secs 300163send time secs 299895send time secs 664908e005send time secs 299864send time secs 298798send time secs 301send time secs 300124send time secs 986207e005why is this happening is there any way i can reduce the delaynotesbuilt using codeblocks running under various flavours of windowspacket are 10 bytes longthe problem goes away if i connect the computer running the application to a second network for example a wwlan cellular network rocket stick as far as i can tell this is the situation we havethis works different ports same lan this also works same ports different lans this does not work same ports same lan this seems to work same ports same lan dual homed module2 host,['c++'] +1028385,do inline namespace variables have internal linkage if not why does the code below work this question is directly related to this one consider the codeinclude iostreaminline namespace n1 int x 42int x 10int main extern int x stdcout x thisplays 10it thisplays 10 if i remove the extern int x declaration then we get an ambiguity compiler time errorerror reference to x is ambiguousquestion why does the code work with the extern int x declaration work and why does it stop working when i remove it is it because inline namespace variables have internal linkage,['c++'] +1028472,how to avoid this forloop mess in c i need to program all possible sets of numbers from 1 to n for an arbitrary number m of integers without permutationsince i do not know how to explain it better here are some examplesfor m 2vectorvectorint box int and 5forint i 1 i n i forint j n j i j vectorint dummy dummypush backi dummypush backj boxpush backdummy for m 3vectorvectorint box int and 5 forint i 1 i n i forint j n j i j forint k n k j k vectorint dummy dummypush backi dummypush backj dummypush backk boxpush backdummy this works perfectly fine and the result is what i need but like already mentioned m can be arbitrary and i cannot be bothered to implement this for m 37 or what ever n and m are known values but change while the program is running there must be a better way to implement this than for the m 37 case to implement a row of 37forloops can someone help me i am kind a clueless edit to explain better what i am looking for here are some more exampleslet us say n 5 and m 4 than 1223 is a feasible solution for me 124 is not since it is to short let us say i already found 1223 as a solution than i do not need 2123 2213 or any other permutation of this numberedit2 or if you prefer a more visual mathematical problem formulation here you goconsider m the dimension with m been 2 you are left with a n size matrix i am looking for the upper or lower triangle of this matrix including the diagonal let us move to m 3 the matrix becomes a 3 dimensional cube or tensor if you so wish now i am looking for the upper or lower tetrahedron including the diagonalplain for higher dimensions than 3 i am looking for the hypertetrahedron of the hypercube including the hyperdiagonalplane,['c++'] +1028475,custom sort vector of pair based on their values i have the following vectorstdvector stdpairint int vectorofpairswith the following items0 10 21 42 33 44 55 6i would like to sort them in a way that the second component of every pair is equal to the first component of the nearest pair in the vector something like this0 11 44 55 60 22 33 4i do not know if this is clearly enough i will append an image that show what i am trying to doi feel that i should use sort with some kind of comparator but i am lost right herestdsortvectorofpairsbegin vectorofpairsend mycomparatorbool mycomparatorpairint int a pairint int b ifsome kind of comparison return true return falsei am newbie with c and if someone could help me with a pseudocode of how to do this i will be very grateful,['c++'] +1028558,android activityoptionscompat custom expand animation i am currently trying to figure out how to make a custom expand animation and using activityoptionscompat seems like the best method for this however i am not really sure on how to write a custom transition animation to do the effect i wanti have a button on top of a list open which when pressed will shift the listview below it down expanding and showing a screen with options i hope this image explains what i am trying to accomplishwhat i am trying to do isset the top open bar to the top bar in the second screen titlecalled filtersset a 0px height view that is directly under the open bar to theexpanded options list called frameset the viewpager to a 0px height view below the expanded optionscalled listbut the list does not get pushed away the new screen is just overlayed on top of itviewcompatsettransitionname filters filters viewcompatsettransitionname frame frame viewcompatsettransitionname viewpager list activityoptionscompat options activityoptionscompatmakescenetransitionanimation getactivity new pair filters filters new pair frame frame new pair viewviewpager list activitycompatstartactivity getactivity new intent getactivity filtersclass optionstobundle does anyone know how to accomplish this style of transition animation thanks for your time and help,['android'] +1028582,no registered handler for url scheme itmsapps rate button simulator i am making rate button for ipad pro when tapping on rate button the debug area showslaunchservices error there is no registered handler for url scheme itmsappsibactionratebuttonidsenderuiapplication sharedapplication openurlnsurl urlwithstringitmsappsitunesapplecomappid12345678why am i getting a no registered handler for url scheme error when i have a url present in code,['ios'] +1028601,how do i get a html5 file input to accept only certain file types consistently across browsers according to this answer on stack overflow we can set the accept attribute of an input typefile to filter accepted input as followsacceptapplicationvndopenxmlformatsofficedocumentspreadsheetmlsheet applicationvndmsexcelhowever as you can notice running the simple snippet below chrome 430something appears to simply thisregard this configuration while it is perfectly understood by firefox 390i considered switching to a more blunt approach usingacceptxls xlsx which works fine in chrome but makes firefox somewhat confused accepting only the files using the xlsx extensionconsidering that this is probably very common and basic i must be missing something where am i screwing up how do i get a html5 file input to suggest only xls and xlsx files consistently across browsersheres a code snippet illustrating my issue along with a jsfiddle link in case youd wanna fiddle with itaccepts applicationvndmsexcel and the likesbr label forfile1file inputlabelinput typefile namefile1 acceptapplicationvndopenxmlformatsofficedocumentspreadsheetmlsheet applicationvndmsexcelhr accepts xls and xlsxbr label forfile2file inputlabelinput typefile namefile2 acceptxls xlsx,['html'] +1028698,xcode 71 with ios 92 error could not find developer thisk image i have ios 92 13c71 installed on my iphone 5 and i am enrolled as an apple developeron my macbook pro i have xcode 71 and osx el capitanwhen i try to run a project on my phone is gives the error could not find developer thisk imagedoes anyone know whats wrong,['ios'] +1028720,merging numpy array elements using join in python want to convert the following numpy array a a arrayx y k d 2 z a 15 r dtypes2 arrayp 49 l n dtypes2 array5 y 33 u v z dtypes2 arrayf i c m u 98 dtypes2 into output b b xyd2a15 xkdzar p49ln 5y33uvz ficmu98consider each subarray like this x y k d 2 z a 15 r then merge 0 and 1 columns with and each row with then merge 0 and 2 column and so on here 01 and 02 columns are merged using and is used to merge the subarrays just merging the strings using i tried the following code couldnt get the result thoughtemp for c in a temp a0 b joinjoinvar1var2 for var1var2 in ziptempa for row in a print bprint,['python'] +1028786,exclude fileslines of code in xcode 7 code coverage how would you exclude a few methods or say the appdelegate file from being tested during code coverage in xcode 7i am not using gcov,"['ios', 'objective-c', 'iphone']" +1028925,is it possible to stretch a imageoverlay in leaflet i am making a leafletjs based application and i want the user to be able to draw a svg image on the map to accomplish this i am tracking the mousedown and mouseup events to define the imagebounds and using an imageoverlay to draw a svg image i want the svg image to be stretched so it completely fits the defined imagebounds but instead is it scaled so it fits within the imagebounds without thistorting the aspect ratiois there a way to enable imageoverlays to ignore their original aspect ratio and stretch to fit in the imageboundsimagebounds southwest northeast tempshape limageoverlay imageurl imagebounds tempshapeaddto mapedit tried to do the same thing with a bitmap image instead and it does stretch so it seams to be a svg specific thing,['javascript'] +1028992,uncaught referenceerror ionic is not defined for ionic push i am trying to add ionicio push to my application but its throwing ionic is not definedreferenceerror ionic is not definedvar push new ionicpusheverything is working fine except this undefined error i have run this command to update lib but nothing happen bundle version is ionic v110ionic lib updatemy appjsangularmoduletestapp ionicionicservicecore ionicservicepush lavoappcontrollers lavoappservicesngcordovarunfunctionionicplatformrootscopelocationtimeoutanchorscrollstateionichistorycordovapush ionicplatformreadyfunction var push new ionicpush debug true pushregisterfunctiontoken consolelogdevice tokentokentoken,['javascript'] +1028999,log caught exceptions from outside the method in which they were caught i have a method likepublic tresult dosomethingwithloggingtresultfunctresult someaction try return someactioninvoke catch exception ex logexceptionex throw this method is used as followsvar result dosomethingwithlogging fooi also want to log exceptions that were caught inside foo i cannot use throw in catch inside of foohow can i catch such exceptionsexample public static string foo try return foo catch exception i have to log this exception too without adding anything to foo return exception caught,['c#'] +1029015,correct way of absolute import in python 27 python 2710in virtualenvenable from future import absolute import in each modulethe directory tree looks likeproject prjt init py pkg1 init py module1py tests init py test module1py pkg2 init py module2py tests init py test module2py pkg3 init py module3py tests init py test module3py data logi tried to use the function compute of pkg2module2py in pkg1module1py by writing like in module1pyimport syssyspathappendpathtoprojectprjtfrom prjtpkg2module2 import computebut when i ran python module1py the interpreter raised an importerror that no module named prjtpkg2module2what is the correct way of absolute import do i have to add the path to project to syspathhow could i run test module1py in the interactive interpreter by python prjtpkg1teststest module1py or python m prjtpkg1teststest module1py,['python'] +1029066,method overrides and polymorphysm i am trying to create a program that allows the user to check into a hotel room the program should check if the room is free and then allocate one of the free rooms if any are available i have multiple rooms types such as a single room a double room a twin room and so on which all need to inherit from the base class roomhere is my code currentlypublic class room public static bool av false true false public bool availability bool a false foreach var roomav in av a a roomav return a public bool availabilityint room return avroom public int allocate if availability int room 0 while avroom room avroom false return room else return 1 public static void roomstatus for int i 0 i avlength 1 i consolewritelinei avitostring class singleroomthe functions i have defined in the room class need to be usable by all the different room types but each hold their own separate array stating whether they are available or not how can i do this how can i access those functions for each class but on there own separate array instead of performing them just on the av array like i have currently,['c#'] +1029242,where to fetch dnx appbase after the rc1 update been running a aspnet 5 console application that is published to multiple environments for a while nowhowever since the rc1 update the environmental variable dnx appbase that i relied on for the configenvironmentjson location has been removed here is the code in questionanyone know what happened to the dnx appbase environmental variable and where i can get this information fromalternatively what are other ways to achieve the same result,['c#'] +1029437,how to make stdmake unique a friend of my class i want to declare stdmake unique function as a friend of my class the reason is that i want to declare my constructor protected and provide an alternative method of creating the object using unique ptr here is a sample codeinclude memorytemplate typename tclass apublic somehow i want to declare make unique as a friend friend stdunique ptrat stdmake uniqueat static stdunique ptra createat x return stdunique ptranew ax works return stdmake uniqueax does not work protected at x voidx int main stdunique ptraint a aintcreatea5 voida return 0right now i get this errorstartin file included from progcc1usrlocallibcxxheadincludecv1memory315232 error calling a protected constructor of class aintreturn unique ptr tpnew tp vstdforward args args progcc1321 note in instantiation of function template specialization std 1make uniqueaint int requested here return stdmake uniqueax does not work progcc2241 note in instantiation of member function aintcreatea requested herestdunique ptraint a aintcreatea5 progcc175 note declared protected hereat x voidx 1 error generated1finishwhat is the correct way to declare stdmake unique as a friend of my class,['c++'] +1029603,nontrivial destructor make class nontriviallyconstructible consider following codeinclude type traitsstruct t static assertstdis trivially destructible t static assertstdis trivially default constructible t struct and n static assertstdis trivially destructible and static assertstdis trivially default constructible and it compiles fine using clang 370 live example but summarizing the standardthe default constructor for class t is trivial ie performs no action if all of the following is truethe constructor is not userprovided ie is implicitlydefined or defaultedt has no virtual member functionst has no virtual base classest has no nonstatic members with default initializers since c11every direct base of t has a trivial default constructorevery nonstatic member of class type has a trivial default constructoras i can see there is no dependence on triviality of the destructori missed something is it clang bugadditionali found a workaround is static assert has trivial constructor and builtin type trait there is support in clang gcc and msvcfor is noexcept constructible family of type traits there is workaround too,['c++'] +1029604,how to test facebook audience network ads over testflight i am trying to integrate audience network to my app ads work correctly on simulator and device when i deploy over xcodei want to thistribute the build over testflight to be sure it will work in release mode when i try to directly deploy from xcode to my device in release mode facebook returns no fill for the ads ads do not show up on testflight builds eitherhave any ideas about showing ads for devices in testflight builds,['ios'] +1029636,getting nested values in immutablejs according to the docs here i should be able to get the deeply nested value by providing an array for the keypath argument this is what i have done however i am getting undefined as the return valuevar obj immutablemapcategories 1 a 2 bvar output objgetincategories 1alertoutputwhat am i doing wrong,['javascript'] +1029771,long words do not float are they denser than short words i want some text to be thisplayed within a boxso i wrap my text with an article tag article phere is my text ready to be boxedparticleand style it as a fixed width block make long words to break and hide the text when overflowarticle thisplay inlineblock width160px overflow hidden wordwrap breakwordso far so good text wraps correctly and long words break and wrapproblem happens when i put a floating image in front of the textarticle img srcimgpngimg phere is my text now preceded by an imageparticleconveniently styled to float before the textimg width 32px float leftwhen text has only short words it floats and wraps correctly but long words do not float anymore they sink to the bottom of the image see this fiddle are long words denser than shortedit i am editing my question to include some complementary information to the answer i have accepted it seems that the only way to solve this problem is to break the long words with wbr tragshere is my code to insert wbr tags in long words insert word break hint tags in long words at num pos stringprototypewbr functionnum return thisreplace regexpw num w g functionmatchsubmatch1submatch2return submatch1 wbr submatch2,['css'] +1029789,map an array of json objects to a javautilmap and vice versa the question is how to map an array of json objects to a javautilmap where each key would be some specified property of an object and the value is the object itselfjsonitems field1 1 field2 hello field1 2 field2worldjava pojopublic class storage private mapinteger item itemspublic class item private integer field1 private string field2so is there a some way to specify to objectmapper that it should use field1 property of each json object as key when deserializing array of items to the map,['java'] +1029820,assigning properties to nonprototype with decorators i am building a simple mapping between frontendbackend data structure in order to do that i have created a decorator that looks like the followingfunction apifield apikey string setfn any any ret ret getfn any any ret ret return function target abstractmodel propertykey string targetapifieldsbag targetapifieldsbag assign targetapifieldsbag propertykey apikey apikey setfn setfn getfn getfn and this is how i use itclass abstractcar apifieldid public id string undefinedclass bmw extends abstractcar apifieldcylinders public cylindercount numberclass vw extends abstractcar apifieldyearcompanyfounded public yearestablished numberthe issue that i am seeing is that instead of the actual object being passed to the decorator it is always its prototype decorate apifieldyearcompanyfounded vwprototype yearestablished void 0which means that as i am assigning stuff to the instance in the decorator it is always attached to the prototype which in turn means that properties i want to be defined only the vw instance are also available on the abstractcar and the bmw class in this example this would be yearestablished this makes it impossible to have two properties with the same name but different api fields in two different classesis there any way to circumvent this behaviour,['javascript'] +1029840,how to load or retrieve a webpage in both online and offline mode in android application i need to load and retrieve a html webpage in internal or external memory of android device what i need is to download and retrieve a webpage in android using webviewthere is lot of repeated questions similar to downloading or saving the webpage but none of the answers helped me guide methanks in advance,"['android', 'html']" +1029843,redux managing preload state i am building an application where i need to preload people and planet data it is likely that in the future more preload requirements may be added on launch of the application i want to have value in the store that represents the global state of the app as loaded boolean the value would be true only then when the preload requirements peopleloaded true and planetloaded true are true the store would look something like thisstorea loaded booleana peoplea a loaded booleana a items a planetsa a loaded booleana a items separate action creators make the needed async requests and thispatch actions which are handled by the people and planets reducers as shown below uses reduxthunkactionsindexjsimport as types from constantsactiontypesimport getpeople getplanets from utilswapiexport function loadpeople return thispatch return getpeople thenpeople thispatchaddpeoplepeople export function loadplanets return thispatch return getplanets thenplanets thispatchaddpeopleplanets export function addpeople people return type typesadd people peopleexport function addplanets planets return type typesadd planets planetsexport function initapp return thispatch loadpeoplethispatch loadplanetsthispatch utilswapi handles fetching people and planet data either from localstorage or making a requestinitapp action creator calls other action creators within sitejs just before rendering to dom as shown belowsitejsimport react from reactimport render from reactdomimport root from containersrootimport configurestore from storeconfigurestoreimport initapp from actionsconst store configurestore preload datastorethispatchinitapprender root storestore documentqueryselectorroot1 what are the best practices for managing global preload state of the application in redux2 is having a global loaded state in the store necessary3 what would be a scalable way of checking app loaded state in multiple react components it does not seem right to include people and planet state for containers that just needs to know the global app state and does not handle rendering of people or planets also that would be painful to manage when the global loaded state would be needed in multiple containersquoting part of dans answer from redux multiple stores why not questionusing reducer composition makes it easy to implement dependent updates a la waitfor in flux by writing a reducer manually calling other reducers with additional information and in a specific order4 does dan by calling other reducers mean calling nested reducers,['javascript'] +1029961,adding targetaction in protocol extension fails i have a set of view controllers which will have a menu bar button i created a protocol for those viewcontrollers to adopt also i have extended the protocol to add default functionalities my protocol looks likeprotocol centerviewcontrollerprotocol class var containerdelegate containerviewcontrollerprotocol get set func setupmenubarbuttonand the extension looks like soextension centerviewcontrollerprotocol where self uiviewcontroller func setupmenubarbutton let barbutton uibarbuttonitemtitle menu style done target self action menutapped navigationitemleftbarbuttonitem barbutton func menutapped containerdelegatetogglesidemenu my viewcontroller adopts the protocol class mapviewcontroller uiviewcontroller centerviewcontrollerprotocol weak var containerdelegate containerviewcontrollerprotocol override func viewdidload superviewdidload setupmenubarbutton i got the button to thisplay nicely but when i click on it the app crashes with appnamemapviewcontroller menutapped unrecognized selector sent to instance 0x7fb8fb6ae650if i implement the method inside the viewcontroller it works fine but i would be duplicating the code in all viewcontrollers which conform to the protocolanything i am doing wrong herethanks in advance,['ios'] +1030027,binding a select to an array of objects in aurelia and matching on id so i have a list of all users which populates the options of a selectoption repeatforuser of userserviceusers userfirstname userlastnameoptionand i have an incoming group record which has a list of users attached to it i follow the cheat sheat instructions and bind it to a single index of the modelselect valuebindgroupusers0 option repeatforuser of userserviceusers modelbinduser userfirstname userlastname optionselectso the incoming user in the group is identical to one of the users in the list id 123 firstname matt lastname davisbut when the group is loaded and bound to the view the correct user is not chosen from the select actually i would expect this as javascript would look for referential equalityideally i would like aurelia to find that the incoming record is as above and a search through the list of options testing equality b that i have defined in some extension maybe a filter c select it in the list and d propagate that selection back into the record so that the record is now referentially in sync i would rather not fall back to a trigger that manually does this because i will have lots and lots of these kinds of selects throughout my applicationi would settle albeit sadly for a and c,['javascript'] +1030032,how to do a recursive reduce function inside an object i am doing this on the client with javascript i want to transform id 10 name designer slug designer children id 11 name ui visual designer slug uivisualdesigner children id 1 name software engineer slug softwareengineer children id 2 name backend developer slug backenddeveloper children into this id 10 text designer id 11 text ui visual designer id 1 text software engineer id 2 text backend developer i am practicing with map and reduce so i am trying to avoid for loops first thing i did this is the current code i havevar jobnewpage buildarrayforselectarray use strict return extendtrue arrayreducefunctiontotal item if itemslug remote return total totalpush id itemid text itemname let children itemchildren if children childrenlength todo we had to call the global context jobnewpage total totalconcatjobnewpagebuildarrayforselectchildren return total so as you can see i have had to call jobnewpagebuildarrayforselectchildren to do it recursively i tried to call thisbuildarrayforselectchildren but the context is different i feel this is not the best option because i do not want to depend calling a global variable inside a function in the object how can i improve it,['javascript'] +1030101,leverage kenticos licensing to license custom module weve developed a kentico module that we would like to license on a per site basishas anyone else tried to leverage the inbuilt kentico licensing for this purposewhat i am thinking of is having a secure endpoint on our server that would validate the domainlicense of the kentico site running the moduleeg if the domainlicense does not exist in our servers the module would not run for the siteis this feasible,['c#'] +1030181,are classobjects singleton in python if we have x typea and x y does it necessarily imply that x is yhere is a counterexample but it is a cheat class brokeneqtype def eq cls other return true class ametaclassbrokeneq pass a a x typea x a x is atrue true x brokeneq x is brokeneqtrue falseand i could not create a counterexample like this a1 typea a2 typea a a1 x typea x a1 x is a1true true x a2 x is a2false falseto clarify my question without overriding equality operators to do something insane is it possible for a class to exist at two different memory locations or does the import system somehow prevent this if so how can we demonstrate this behavior for example doing weird things with reload or import if not is that guaranteed by the language or documented anywhereepilogue thingpyclass a passfinally this is what clarified the real behaviour for me and it is supporting the claims in blckknght answer import sys from thing import a a a isinstancea a typea a typea is atrue true true del sysmodulesthing from thing import a isinstancea a typea a typea is afalse false falseso although code that uses importlibreload could break type checking by class identity it will also break isinstance anyway,['python'] +1030213,how to use paginate method i have a problem with a paginatedlist in a web api projectin the repository there is a method likepublic virtual paginatedlistt paginatetkeyint pageindex int pagesize expressionfunct tkey keyselector expressionfunct bool predicate params expressionfunct object includeproperties iqueryablet query allincludingincludepropertiesorderbykeyselector query predicate null query querywherepredicate return querytopaginatedlistpageindex pagesizebut when i try to use it like thisvar a repositorypaginateregionpageno pagesize x xid nulli get this errorcannot implicitly convert type int to domainentitiesdictionariesregionwhat am i doing wrong,['c#'] +1030468,synchronize video subtitle with texttospeech voice i try to create a video of a text in which the text is narrated by texttospeechto create the video file i use the videofilewriter of aforgenet as the followingvideowriter new videofilewritervideowriteropencurvideofile intpropertiessettingsdefaultvideowidth intpropertiessettingsdefaultvideoheight 25 videocodecmpeg4 80to read aloud the text i use speechsynthesizer class and write the output to a wave streamaudiostream new filestreamcuraudiofile filemodecreatesynthsetoutputtowavestreamaudiostreami want to highlight the word is spoken in the video so i synchronize them by the speakprogress event void synth speakprogressobject sender speakprogresseventargs e curauidoposition eaudioposition using graphics g graphicsfromimagescreen gdrawstringetext videowriterwritevideoframescreen curauidoposition and finally i merge the video and audio using ffmpegusing process process new process procestartinfofilename exe path procestartinfoarguments stringformati 0 i 1 y acodec copy vcodec copy 2 avi path mp3 path output filethe problem is that for some voices like microsoft hazel zira and david in windows 81 the video is not synchronized with the audio and the audio is much faster than the shown subtitle however for the voices in windows 7 it workshow can i synchronize them so that it works for any texttospeech voices on any operating systemit seems the eaudioposition is inaccurate as it is mentioned in are the speakprogresseventargs of the speechsynthesizer inaccurate i had the same experiment and the same resulti have noticed if i adjust the audio format i can be close to the actual time however it does not work for any voice var formats curvoicevoiceinfosupportedaudioformats if formatscount 0 var format formats0 readersetoutputtowavefilecuraudiofile format else audiostream new filestreamcuraudiofile filemodecreate readerselectvoicecurvoicevoiceinfoname var fmt new speechaudioformatinfo160 audiobitspersamplesixteen audiochannelmono this is more close but not precise yet memstream new memorystream var mi readergettypegetmethodsetoutputstream bindingflagsinstance bindingflagsnonpublic miinvokereader new object memstream fmt true true,['c#'] +1030532,cloudkit cksubscription without notifications i am writing a swift app with cloudkit when a record is modified in cloudkit by a device i want the corresponding records to be updated in the local storage of the other devices without thisplaying a push notificationdo i need to call registerusernotificationsettings in didfinishlaunchingwithoptions meaning that the user has to accept the notifications for my app even if i do not plan to thisplay any push notificationapplicationregisterusernotificationsettingsuiusernotificationsettingsfortypes alert categories nil,['ios'] +1030693,rounding issue in log and exp functions i am trying to perform cumulative multiplication i am trying two methods to do this sample datadeclare test table par column int period int value numeric22 6 insert into test values 160110 160220 160330 160440 160550 160660 260110026022002603300260440026055002606600note the data in value column will never be integer and values will have decimal part to show approximation problem i have kept example values as integersmethod 1 exp log sum overorder byin this method am using exp log sum overorder by technique to find cumulative multiplication in this method values are not accurate there is some rounding and approximation issue in the resultselect expsumlogabsnullifvalue 0 over partition by par column order by period as cum mulfrom testresultpar column period value cum mul 1 601 10 101 602 20 200 10 20 200correct1 603 30 601 200 30 60 not 601 incorrect1 604 40 2401 605 50 1201 606 60 7201 120 60 720 not 7201 incorrect2 601 10 1002 602 20 202 603 30 59 20 30 60 not 59 incorrect2 604 40 239 2 605 50 1192 606 60 7198method 2 tradictional multiplication recursive ctethis method works perfectly without any rounding or approximation problemwith cte as select top 1 with ties par column period value cum mul value from test order by period union all select tpar column tperiod tvalue casttvalue ccum mul as numeric22 6 from cte c inner join test t on cpar column tpar column and tperiod cperiod 1select from cte order by par columnperiodresultpar column period value cum mul 1 601 10 101 602 20 201 603 30 601 604 40 2401 605 50 1201 606 60 7202 601 10 102 602 20 202 603 30 602 604 40 2402 605 50 1202 606 60 720can anyone tell me why in method 1 values are not accurate and how to fix it i tried by changing the data types to float and by increasing the scale in numeric but no usei really want to use method 1 which is much faster than method 2edit now i know the reason for approximation can anyone find a fix for this problem,['sql'] +1030755,when does a windows client use initiator preferred negoex for spnego attempting to authenticate a windows client iefirefox via spnego and kerberos the server side is javatomcat with jcifs for spnego authentication the sso kerberos auth works fine when hosting the server side on a win 2008 r2 server however when on a 2012 server it fails with a gssexception defective token detected digging a bit deeper with network tracing i found that in the working case the ie client sends the negotiate tokens with 4 mechtypes 1284048018122 ms krb512840113554122 krb5 1361413112230 negoex and 1361413112210 ntlmsspin this case my server side will complete the spnego selecting ms krb5 however in the problem case the ie client only sends token with 2 mechtypes negoex and ntlmssp and this is initiator preferred java does not support negoex and hence it fails some search revealed that this problem is associated with bugs in jdk or otherwise issues with dns however i am on latest jdk and dns seems to be okay so my question is when does a browser in windows switch to negoex in spnego and why the closest answer i found was in an msdn blog which says kerberos is not available since it is not in a domain environment however the client is indeed in domain environment and klist shows a valid kerberos ticket if it indeed is a domain problem what exactly could be the root cause and how can i avoid the problem footnote some background research information jdk8 has seen many fixes in the gss mechanism there were things broken in jdk8u40 and jdk8u45 then further fixes are present in jdku65 a bug report which was supposed to implement negoex was closed with a fix a fix to spnego that allows negoex be presented and bypassedhowever i am not sure if negoex is indeed working the negoex ietf standard also looks abandoned with the draft rfc in the expired state so i doubt if it will really be supported by java libraries,['java'] +1030763,constreference qualified member function the stock example of a referencequalified member function seems to be something like thisinclude stdiohinclude stdexceptinclude string easy access to literalsusing namespace stdliterals file wrapperclass file private the wrapped file file file public fileconst char name filefopenname r unable to open the file if file throw stdruntime error unable to open file s name file fclose file convert to the underlying wrapped file operator file return file todo member functions for working with the filethis works well it is not possible to retrieve the underlying file pointer from an unnamed temporary directly however if we make the casting operator also constqualified this no longer seems to workdifferent compilers simply swallow it without complaint even though it is a terribly useful idea take for example the stdstringc str member function you feel it should be referencequalified because otherwise you have an invalid pointer yet it is notis this a hole in the c11 standard am i missing something here,['c++'] +1030836,what is supposed to happen when an img cannot be thisplayed what is the browser supposed to do exactly when an img cannot be thisplayedthe official sources are deliberately vague about this they say the alt text is supposed to be used but they do not say howso unless i have not searched good enough and i did a lot of googling i even binged this information is not there and the browsers differ widely in what they doif an image cannot be loaded because it is not theremozilla thisplays the alt text inline as part of the current textie thisplays the alt text as an inlineblock preceded by the broken image icon and in a different fontchrome also thisplays an inline block and the broken image icon and it puts a border around it it does not change the font thoughpthis is my new car img srcimagesmynewcarjpg altit is a red car with four wheels and that is itpnow if you change the browsers settings to not load images the behaviour changes in most browserschrome now does not thisplay anything not even the alt textie still thisplays the alt text in a smaller font but now without the broken image icon in frontmozilla still thisplays the alt text inlineso my question is which of these browsers does the right thingand by that i do not mean what do you think is the best approach i really mean what are the official rules governing this behaviour are there w3c pages or even whatwg pages that i managed to miss or where i misinterpreted the rules,['html'] +1030949,how to copy this section of a webpage when a link is clicked i am trying to copy a section of a webpage when a link is clicked so that the section is recreated underneath the previous section just like how this works in this image as example i am doing this on google apps script and here is my codecodegsfunction dogete return htmlservicecreatehtmloutputfromfilehtml setsandboxmodehtmlservicesandboxmodeiframehtmlhtmlhtmlhead base target top style typetextcss contentbackground backgroundcolor d8d8d8 clear left width 60 margin auto height 200px thisplay block uploadfile p textalign center padding 20px color red content p textalign center color red padding 7px dropdown p textalign center padding 40px marginleft 8px height morefiles textalign center styleheadbody div classcontentbackground div classuploadwrapper div classfileupload div classuploadfile pupload file span stylecolorblackinput typefile nameuploadfield spanp div div classcontent pwidthinch input typetext stylewidth 100px heightinch input typetext stylewidth 100px quantity input typetext stylewidth 100pxp div div div div classdropdown p material select stylemaxwidth 10 option valuepaperpaperoption option valuevinyl bannervinyl banneroption option valueadhesive vinyladhesive vinyloption option valuepolyglosspolyglossoption option valuetranslucent vinyltranslucent vinyloption option valuestatic cling clearstatic cling clearoption option valuestatic cling whitestatic cling whiteoption option valuereverse static clingreverse static clingoption option valueoutdoor paperoutdoor paperoption option valuebacklit filmbacklit filmoption option valuefoamfoamoption option valuecoroplastcoroplastoption option valuecorrugated boardcorrugated boardoption option valuesintrasintraoption option valuecanvascanvasoption option valuefabricfabricoption option valueall clingall clingoption select lamination select option valuenonenoneoption option valuemattematteoption option valueglossglossoption option valuelexanlexanoption option valueerasableerasableoption select mounting select option value316quot foam316 foamoption option value316quot gator316 gatoroption option value18quot sintra18 sintraoption option value24point card24point cardoption option value50point card50point cardoption option valueadhesive backadhesive backoption option valuemdfmdfoption option valuecoroplastcoroplastoption option valuemasonitemasoniteoption option value020 styrene020 styreneoption option value040 styrene040 styreneoption option value060 styrene060 styreneoption option value080 styrene080 styreneoption option valuecorrugated boardcorrugated boardoption select ink select option valueindoorindooroption option valueoutdooroutdooroption select p div div div classmorefiles a href idaddadd another filea divbodyhtml,"['javascript', 'html', 'css']" +1031280,what is settimeout doing when set to 0 milliseconds in javascript settimeoutcallback delay means call callback after delay milliseconds but what if delay is 0 should it call callback right away i am confused because of what i see when i run the following codesettimeoutfunction consoleloga 0 call this in 0 milliseconds for i 0 i 10 i consolelogb for i 0 i 10 i consolelogc for i 0 i 10 i consolelogd for i 0 i 10 i consoleloge this logs the following to the consolei expected to see a logged much sooner than that there was time to execute 40 other calls to consolelog before a function which should have been called immediatelycan someone explain what settimeout is doing when the delay is set to 0 milliseconds,['javascript'] +1031362,how to convert column with dtype as object to string in pandas dataframe when i read a csv file to pandas dataframe each column will be casted to datatypes on it is own i have a column that was converted to object i want to perform string operations for that column like splitting the values and creating a list but no such operation is being performed because of it is dtype being object can anyone please let me know the way to convert all the items of a column to strings instead of objectsi tried all the possible ways but nothing worked i used astype str to string etcalambda x strxsplitdfcolumnapplyaordfcolumnastypestr,['python'] +1031389,progress bar while uploading a file to dropbox import dropboxclient dropboxclientdropboxclienttokenf openssdscratchabhishekbtry1mat rbresponse clientput filedata1mat fi want to upload a big file to dropbox how can i check the progress docseditthe uploader offeset is same below somehow what am i doing wrongimport ospdbdropboxsize1194304client dropboxclientdropboxclienttokenpathdbci codedatasets1mattot size ospathgetsizepathbigfile openpath rbuploader clientget chunked uploaderbigfile sizeprint uploading tot sizewhile uploaderoffset tot size try upload uploaderupload chunked print uploaderoffset except resterrorresponse e printsomething went wrongedit 2size1194304tot size ospathgetsizepathbigfile openpath rbuploader clientget chunked uploaderbigfile tot sizeprint uploading tot sizewhile uploaderoffset tot size try upload uploaderupload chunkedchunk sizesize print uploaderoffset except resterrorresponse e printsomething went wrong,['python'] +1031453,alternative to sleep inside a thread various answers suggest it is a bad idea to sleep inside a thread for example avoid sleep why exactly one reason often given is that it is difficult to gracefully exit the thread by signalling it to terminate if it is sleepinglet us say i wanted to periodically check for new files in a network folder maybe once every 10s this seems perfect for a thread with the priority set to low or lowest because i do not want the potentially timeconsuming file io to impact my main threadwhat are the alternatives code is given in delphi but would apply equally to any multithreaded applicationprocedure tnetfilesthrdexecutebegin try while not terminated do begin check for new files rest a little before spinning around again if not terminated then sleeptenseconds end finally terminated or exception so free all resources endenda minor modification might be rest a little before spinning around againnsleepcounter 0while not terminated and nsleepcounter 500 do begin sleeptwentymilliseconds incnsleepcounter endbut this still involves a sleep,"['c#', 'c++']" +1031567,how to control the language of the paypal checkout page i am using perstashop an open source eshop framework paypal plugin to implement the paypal function actually it is the php framework so it should be similar to other site implementationi would like to change the language of checkout pageand here is the codeform idpaypal payment form actionbase dir sslmodulespaypalexpress checkoutpaymentphp dataajaxfalse titlel spay with paypal modpaypal methodpost input typehidden nameexpress checkout valuepaypal payment typeescapehtmlallutf8 input typehidden namecurrent shop url valuepaypal current pageescapehtmlallutf8 input typehidden namebn valuepaypal tracking codeescapehtmlallutf8 form someone said put the line input typehidden namelc valuexx xxin the form i check the support locale code list and put it unluckly it remain the sameso i wonder1 is this correct or i need to change elsewhere2 is the language in paypal changed in paypal panel instead of code there is a default language setting but how can i dynamic change base on the eshop language3 can i control the language choice as well my eshop has english france and germany but paypal checkout can only change between english and france any idea it is classic express checkout pagethanks for helping updatefound that the language is control by the delivery address then it means i can somehow change that,"['php', 'html']" +1031843,button inside list view is creating issue on scrolling and on button click i have three button in some of list items in list view and on click of that button i wanna change layout of that list item but problem i am facing is listed below1 on click of button another listitem layout get changed2 on scroll of listview another listitems layout get changed whom i have not clickedheres code of adapter classimport javautilarraylistimport comxsinfosoldotrimport comxsinfosoldotimageloadingimageloaderimport comxsinfosoldotlibraryclassesrippleviewimport comxsinfosoldotmodeldot common modelimport androidcontentcontextimport androidgraphicsdrawabledrawableimport androidsupportv7internalwidgetbuttonbarlayoutimport androidviewgravityimport androidviewlayoutinflaterimport androidviewviewimport androidviewviewonclicklistenerimport androidviewviewgroupimport androidviewwindowmanagerlayoutparamsimport androidwidgetbaseadapterimport androidwidgetbuttonimport androidwidgetcheckboximport androidwidgetcompoundbuttonimport androidwidgetcompoundbuttononcheckedchangelistenerimport androidwidgetimageviewimport androidwidgetlinearlayoutimport androidwidgettextviewpublic class agenda adapter extends baseadapter context context arraylistdot common model arraylist viewholder viewholder public agenda adaptercontext context arraylistdot common model arraylist todo autogenerated constructor stub thiscontext context thisarraylist arraylist override public int getcount todo autogenerated method stub return arraylistsize override public object getitemint position todo autogenerated method stub return arraylistgetposition override public long getitemidint position todo autogenerated method stub return position override public view getviewint position view convertview viewgroup parent todo autogenerated method stub ifconvertviewnull viewholder new viewholder convertview layoutinflaterfrom contextinflaterlayoutagenda event list item null viewholderlinearlayout linearlayoutconvertviewfindviewbyidridagenda button layout viewholderlinearlayoutsetvisibilityviewgone viewholdercheckbox checkboxconvertviewfindviewbyidridagenda event checkbox viewholdereventname textviewconvertviewfindviewbyidridagenda event name viewholderimageview imageviewconvertviewfindviewbyidridagenda event imae viewholderplace textviewconvertviewfindviewbyidridagenda event place viewholdertime textviewconvertviewfindviewbyidridagenda event date time viewholdergoing rippleviewconvertviewfindviewbyidridagenda rippleview going viewholdernotgoing rippleviewconvertviewfindviewbyidridagenda rippleview not going viewholdermaybe rippleviewconvertviewfindviewbyidridagenda rippleview maybe viewholdergoingsetonclicklistenernew onclicklistener override public void onclickview v todo autogenerated method stub viewholdergoingsetvisibilityviewgone viewholdernotgoingsetvisibilityviewgone viewholdermaybesetvisibilityviewgone drawable tick contextgetresourcesgetdrawablerdrawableic action tick ticksetbounds00 30 30 button going new buttoncontext linearlayoutlayoutparams params new linearlayoutlayoutparamsnew layoutparamslinearlayoutlayoutparamsmatch parent 40 paramssetmargins100 10 4 goingsetlayoutparamsparams goingsetbackgroundcolorcontextgetresourcesgetcolorandroidrcolorholo green dark goingsettextgoing goingsettextsize15 goingsettextcolorrcolorwhite goingsetcompounddrawablesnull null tick null goingsetcompounddrawablepadding5 goingsetgravitygravitycenter ifviewholderlinearlayoutnull viewholderlinearlayoutremoveallviews viewholderlinearlayoutaddviewgoing viewholdernotgoingsetonclicklistenernew onclicklistener override public void onclickview v todo autogenerated method stub viewholdergoingsetvisibilityviewgone viewholdernotgoingsetvisibilityviewgone viewholdermaybesetvisibilityviewgone drawable cross contextgetresourcesgetdrawablerdrawableic action cancel crosetbounds00 30 30 button button new buttoncontext linearlayoutlayoutparams paramscross new linearlayoutlayoutparamsnew layoutparamslinearlayoutlayoutparamsmatch parent 40 paramscrosetmargins100 10 4 buttonsetlayoutparamsparamscross buttonsetbackgroundcolorcontextgetresourcesgetcolorrcolorred buttonsettextnot going buttonsettextsize15 buttonsettextcolorrcolorwhite buttonsetcompounddrawablesnull null cross null buttonsetcompounddrawablepadding5 buttonsetgravitygravitycenter ifviewholderlinearlayoutnull viewholderlinearlayoutremoveallviews viewholderlinearlayoutaddviewbutton viewholdermaybesetonclicklistenernew onclicklistener override public void onclickview v todo autogenerated method stub viewholdergoingsetvisibilityviewgone viewholdernotgoingsetvisibilityviewgone viewholdermaybesetvisibilityviewgone drawable maybe contextgetresourcesgetdrawablerdrawableic action emo err maybesetbounds00 30 30 button maybe new buttoncontext linearlayoutlayoutparams paramsmaybe new linearlayoutlayoutparamsnew layoutparamslinearlayoutlayoutparamsmatch parent 40 paramsmaybesetmargins100 10 4 maybesetlayoutparamsparamsmaybe maybesetbackgroundcolorcontextgetresourcesgetcolorrcoloryellow maybesettextmay be maybesettextsize15 maybesettextcolorrcolorwhite maybesetcompounddrawablesnull null maybe null maybesetcompounddrawablepadding5 maybesetgravitygravitycenter ifviewholderlinearlayoutnull viewholderlinearlayoutremoveallviews viewholderlinearlayoutaddviewmaybe viewholdercheckboxsetoncheckedchangelistenernew oncheckedchangelistener override public void oncheckedchangedcompoundbutton buttonview boolean ischecked todo autogenerated method stub int getposition integerbuttonviewgettag arraylistgetgetpositionsetcheckedbuttonviewischecked convertviewsettagviewholder convertviewsettagridagenda event checkbox viewholdercheckbox convertviewsettagridagenda event imae viewholderimageview convertviewsettagridagenda event name viewholdereventname convertviewsettagridagenda event place viewholderplace convertviewsettagridagenda event date time viewholdertime convertviewsettagridagenda button layout viewholderlinearlayout convertviewsettagridagenda rippleview going viewholdergoing convertviewsettagridagenda rippleview not going viewholdernotgoing convertviewsettagridagenda rippleview maybe viewholdermaybe else viewholder viewholderconvertviewgettag viewholdercheckboxsettagposition viewholdergoingsettagposition viewholdernotgoingsettagposition viewholdermaybesettagposition imageloader imageloader new imageloadercontext imageview imageview viewholderimageview imageloaderthisplayimagearraylistgetpositiongetimage imageview viewholdercheckboxsetcheckedarraylistgetpositionischecked switch arraylistgetpositiongetflag case 0 hasns seleted any option ifviewholderlinearlayoutgetvisibilityviewgone viewholderlinearlayoutsetvisibilityviewvisible ifviewholdergoinggetvisibilityviewgone viewholdergoingsetvisibilityviewvisible ifviewholdermaybegetvisibilityviewgone viewholdermaybesetvisibilityviewvisible ifviewholdernotgoinggetvisibilityviewgone viewholdernotgoingsetvisibilityviewvisible break case 1 selected going viewholdergoingsetvisibilityviewgone viewholdernotgoingsetvisibilityviewgone viewholdermaybesetvisibilityviewgone drawable tick contextgetresourcesgetdrawablerdrawableic action tick ticksetbounds00 30 30 button going new buttoncontext linearlayoutlayoutparams params new linearlayoutlayoutparamsnew layoutparamslinearlayoutlayoutparamsmatch parent 40 paramssetmargins100 10 4 goingsetlayoutparamsparams goingsetbackgroundcolorcontextgetresourcesgetcolorandroidrcolorholo green dark goingsettextgoing goingsettextsize15 goingsettextcolorcontextgetresourcesgetcolorrcolorwhite goingsetcompounddrawablesnull null tick null goingsetcompounddrawablepadding5 goingsetgravitygravitycenter ifviewholderlinearlayoutnull viewholderlinearlayoutremoveallviews viewholderlinearlayoutaddviewgoing break case 2 select not going viewholdergoingsetvisibilityviewgone viewholdernotgoingsetvisibilityviewgone viewholdermaybesetvisibilityviewgone drawable cross contextgetresourcesgetdrawablerdrawableic action cancel crosetbounds00 30 30 button button new buttoncontext linearlayoutlayoutparams paramscross new linearlayoutlayoutparamsnew layoutparamslinearlayoutlayoutparamsmatch parent 40 paramscrosetmargins100 10 4 buttonsetlayoutparamsparamscross buttonsetbackgroundcolorcontextgetresourcesgetcolorrcolorred buttonsettextnot going buttonsettextsize15 buttonsettextcolorcontextgetresourcesgetcolorrcolorwhite buttonsetcompounddrawablesnull null cross null buttonsetcompounddrawablepadding5 buttonsetgravitygravitycenter ifviewholderlinearlayoutnull viewholderlinearlayoutremoveallviews viewholderlinearlayoutaddviewbutton break case 3 selected may be viewholdergoingsetvisibilityviewgone viewholdernotgoingsetvisibilityviewgone viewholdermaybesetvisibilityviewgone drawable maybe contextgetresourcesgetdrawablerdrawableic action emo err maybesetbounds00 30 30 button maybe new buttoncontext linearlayoutlayoutparams paramsmaybe new linearlayoutlayoutparamsnew layoutparamslinearlayoutlayoutparamsmatch parent 40 paramsmaybesetmargins100 10 4 maybesetlayoutparamsparamsmaybe maybesetbackgroundcolorcontextgetresourcesgetcolorrcoloryellow maybesettextmay be maybesettextsize15 maybesettextcolorcontextgetresourcesgetcolorrcolorblack overlay maybesetcompounddrawablesnull null maybe null maybesetcompounddrawablepadding5 maybesetgravitygravitycenter ifviewholderlinearlayoutnull viewholderlinearlayoutremoveallviews viewholderlinearlayoutaddviewmaybe break case 4 event does not have any invitatin option ifviewholderlinearlayoutgetvisibilityviewvisible viewholderlinearlayoutsetvisibilityviewgone break viewholdereventnamesettextarraylistgetpositiongetname viewholderplacesettextarraylistgetpositiongetplace viewholdertimesettextarraylistgetpositiongettime return convertview static class viewholder textview eventname place time checkbox checkbox imageview imageview linearlayout linearlayout rippleview going notgoing maybeplease help me i am stuck in this very badly,['android'] +1031922,java kernel for jupyter is there a java kernel for jupyter i am using mac os el capitan i tried kernel but to no avail,['java'] +1032232,how can i keep only nonzero digits from an integer i am currently using the code below that removes all digits equal to zero from an integerint removezerosint candid int output 0 string sitoacandid for int i ssize i 0 i if si 0 output output 10 atoisi return outputthe expected output for eg 102304 would be 1234 is there a more compact way of doing this by directly working on the integer that is not string representation is it actually going to be faster,['c++'] +1032292,c getset accessors how do i avoid typing repetitive code i am writing a pretty large library and i find myself writing almost identical accessors all the time i already have several dozen accessors such as the one belowquestion how can i declareimplement accessors to save typing all this repetitive code no defines please i am looking for c constructsupdate yes i do need accessor functions because i need to take pointers to these accessors for something called property descriptors which enable huge savings in my gui code nonlibraryh fileprivate bool visiblepublic bool getvisible const return visible void setvisible bool value repeat for getsetflashing getsetcolor getsetlinewidth etccpp filevoid elementsetvisible bool value visible value thisinvalidateself call method in base class a bit more code here identical in 90 of my setters repeat for getsetflashing getsetcolor getsetlinewidth etc,['c++'] +1032305,why cannot i use array initialisation syntax separate from array declaration i can do this with an integerint aa 5but i cannot do this with an integer arrayint aa 1 2 3 4 5 why notto clarify i am not looking for the correct syntax that i can look up i know that this worksint a 1 2 3 4 5 which would be the equivalent ofint a 5what i am trying to understand is why does the code fail for arrays what is the reason behind the code failing to be recognised as valid,['c#'] +1032528,aggregate initialization of an array of objects with new which compiler is right supposedly i have the following codeclass foo int ipublic fooint const i ii int geti const return i int main foo bar new foo51 2 3 4 5gcc compiles and runs it with no problem demo while clang gives a compile error demoerror no matching constructor for initialization of fooso which compiler is right,['c++'] +1032582,working with live photos in playground i have done a fair amount of searching the web but i am currently attempting to work with live photos in playground i am aware of the framework phlivephoto i just have no clue if working with them in playground is possible due to that fact that there is not much to import as there does not seem to be any live photos available for download online any ideas,['ios'] +1032937,why sometime it throws filenotfoundexception the code works for most of the time but some time it throws exception could not figure out what could cause itwhat is does is to create a file at storageemulated0downloadthefilenamejpgand write data to it from sourcefile which does exist but got file not exist exception for the newly created fileit does have usespermission androidnameandroidpermissionwrite external storage and usespermission androidnameandroidpermissionread external storage in manifestfile sourcefile new filethesourcefilefullpathif sourcefileexists file downloaddirectory environmentgetexternalstoragepublicdirectoryenvironmentdirectory downloads string downloadpath downloaddirectorygetpath string newfilepath downloadpath filename file newfile new filenewfilepath try fileinputstream in new fileinputstreamsourcefile avaiofilenotfoundexception storageemulated0downloadthefilenamejpg open failed enoent no such file or directory exception at this line fileoutputstream out new fileoutputstreamnewfile catch exception e,['android'] +1033027,android multidex unsatisfiedlinkerror could not find so file i am trying to add some lib jar soto my multidex project in android studiowhen i add only a few jars to the project everything works fine in case i add more and more jars other libsi am getting this errorjavalangunsatisfiedlinkerror dalviksystempathclassloaderdexpathlistzip file dataappcomtestdigitalocrtest2baseapknativelibrarydirectoriesdataappcomtestdigitalocrtest2libarm dataappcomtestdigitalocrtest2baseapklibarmeabiv7a vendorlib systemlib could not find libscanovatepassportandidlsdk cppsoany idea how can i tell to the compiler to generate jar and so in same dex,['android'] +1033040,boto3 equivalent of botoconfig in boto3 or botocore how do i do the equivalent of setting the number of request retrieseg in boto2from boto import configconfigsetboto num retries 20how do i do this in boto3 i have triedconn sessionset config variablenum retries 20but when i then get config variablenum retries none is returned,['python'] +1033207,is throwing an exception from destructor safe for the vtable please consider the following exampleinclude csignalclass apublic virtual a virtual void foo 0class b public apublic virtual b throw 5 virtual void foo int mainint char a b new b try delete b catch raisesigtrap return 0i have always thought naive me that when the program gets in this case into catch section then object b at which b points will be intact because it is quite logical that the exception will have cancelled if programmed safely the effect of destructor but when i tried to run this snippet in gdb and got to the breakpoint in catch section i saw that b object was gone and only a base object left because the vtable looked like thisgdb i vtbl bvtable for a 0x400cf0 subobject 0x6030100 0x01 0x02 0x4008e0 cxa pure virtualpltmy question is there a way to avoid halfdestruction of the vtable if i passionately want to throw an exception from a destructor,['c++'] +1033229,is this time complexity actually on2 i am working on a problem out of ctcithe third problem of chapter 1 has you take a string such as mr john smith and asks you to replace the intermediary spaces with 20mr20john20smiththe author offers this solution in python calling it ondef urlifystring length function replaces single spaces with 20 and removes trailing spaces counter 0 output for char in string counter 1 if counter length return output elif char output output 20 elif char output output char return outputmy questioni understand that this is on in terms of scanning through the actual string from left to right but are not strings in python immutable if i have a string and i add another string to it with the operator does not it allocate the necessary space copy over the original and then copy over the appending stringif i have a collection of n strings each of length 1 then that takes1 2 3 4 5 and nn12or on2 time yes or am i mistaken in how python handles appendingalternatively if youd be willing to teach me how to fish how would i go about finding this out for myself i have been unsuccessful in my attempts to google an official source i found but this does not have anything on strings,['python'] +1033316,c excel interop suppress publishing dialog when invoking worksheetexportasfixedformat i am using excel interop to open an xlsx file and save that as a pdf document upon invoking the exportasfixedfileformat method a dialog titled publishing is thisplayed to indicate the progress how can i suppress or hide this dialog i have seen a few similar questions on other forums without a satisfying solution but hopefully someone has solved this since thencodeapplication application new applicationapplicationthisplayalerts false no effectapplicationvisible false no effectapplicationscreenupdating false no effectapplicationusercontrol false no effectapplicationworkbooksopenpath typemissing trueapplicationthisplaydocumentactiontaskpane false no effectapplicationworksheets1exportasfixedformatxlfixedformattypexltypepdf path,"['c#', '.net']" +1033452,error c4592 symbol will be dynamically initialized vs20151 static const stdvector field after update vs20151 next code no longer compilesclass testclastatic const stdvectorint testinitializationconst stdvectorint testclasstest 12with errorerror c4592 test symbol will be dynamically initialized implementation limitationis it bug or something has changed in the compiler,['c++'] +1033459,issue when removing the supportv4 library my app minimum version is 10and till now i am using the support library for fragments now i want to add the flip animation for few fragment transitionso as per the android guide we need to use the animator for that and it has support from the api level 11 which is no issue for mebut also need to use the getfragmentmanager instead getsupportfragmentmanagerso i removed the support library changed my minimum version 10 to 11 errors are coming because in my app i have fragmenttabhost and getchildfragmentmanagerfragmenttabhost only available on support library and to set fragmentmanager using the getchildfragmentmanager it wont allow me to do that because it requires api level 17any help appreciatedlet me know if you need more detailsthanks in advance,['android'] +1033514,stringbyaddingpercentescapesusingencoding was deprecated in 90 how to do this i am a junior developer and i got a code for thisnsstring encodedstringfromobjectidobject return object description stringbyaddingpercentescapesusingencodingnsutf8stringencoding but in 90 have to use stringbyaddingpercentencodingwithallowedcharactershow could i transfer this code i need help thanks,['objective-c'] +1033772,projected generic specialization in java 9 or later vs list how will remove work generic specialization along with value types are a projected feature of future jvms link to the valhalla project page herenow from what i understand it would then become possible to declare afinal listint mylist new arraylist for instancebut then list defines another remove method in addition to the one defined in the collection interface which takes an int as an argument which is the index in the list to remove that is why currently the content of list in the example belowfinal listinteger list new arraylistlistadd1listadd2listadd3listremove2will be 1 2 and not 1 3 the most specific overload is chosenhowever if in the future we are able to declare a listint we have a problem what overload of the remove method will be chosen,['java'] +1033966,ios launch screen in react native i am working with a react native app and i am trying to set a customize launch screen but i am not be able toreact native creates a launchscreenxib by default so i have created a launchimage inside imagesxcassetsi have also read that i have to modify the launch screen file under app icons and launch images in my optionsonce i have done that my launch screen is totally black and when the app is loaded there are both top and bottom black framesso i do not know what i have to do to set my launch screen in my react native projecti will be grateful if someone can help me out with those troublesthanks in advanced,['ios'] +1033992,domain driven design in nodejs application tl dri am looking for trite example of d nodejs applicationhii am going to create node application i wonder that i can not find any example of application with business logic separated in domainok there are some examples like but this is whole cqrs with event sourcing implementationmy idea is to do that like thatdomainbookjsfunction booktitle author this title title this author author domain methods infrastructurepersistancerepositorybookrepositoryjsfunction bookrepositorybookrepositoryprototypesavebook var bookmodel mappersmaptoormbook return bookmodelsave get getall getnextidinfrastructurepersistanceormbookjsusing var book bookshelfmodelextend tablename booksinfrastructuremappersbookmapperjsfunction maptoormbook mapping return new persistancebookfunction maptodomaindomain mapping return new domainbookbut on the other hand i have never seen any similar solution with domain model orm model repository and mappers am i thinking in the right way maybe there is no reason to separate business logic in domain in nodejs applications if so why if not can you send me an example of d implementation or improve my code,['javascript'] +1034020,babel v6 howcan i write a plugin that adds a new syntax ie a new operator note i found this question on babel issue tracker and it was rejected but afaik its author did not asked it herei have checked babel plugins like packagesbabelpluginsyntaxdoexpressions and it seemed that these es6 new syntaxoperators werent actually defined in the plugin at all but being implemented in babylon and simply being toggled on by these pluginsleaving the claim in the newest blog post that developers have built everything from debugging tools to experimental new syntaxes to enforce complex rules on their codebases dubious actually i have searched the entire plugin ecosystem but found no plugin being able to offer new operatorssyntax and only exactly one plugin that is able to offer operator overloading for a few existing operatorsso is it really true that with babel v6 well be able to see new operatorssyntax being defined in the userland and howthis is also my opportunity to thank the whole babel team for the good workps i started searching how to extend babylon parser syntax in order to implement a plugin which would implement pattern matching like in julia methods,['javascript'] +1034166,heroku rails42 cloudfront setup i am trying to setup cloudfront for my heroku app the documentation seems to be lacking to stand independentlyhere are the steps i followed 1 setup cloudfront in aws console 2 added cloudfront domain name to productionrb configaction controllerasset host xcloudfrontnet 3 set configassetscompile true in productionrb 4 verified aws secret access key is correct in heroku config 5 i have added gem rails 12factor group productionnone of assets load anymore any step i am missing in the setupupdate1in the chrome debugger the asset is correctly requested from cloudfront from this url however in the request header see a status code302 moved temporarily i am wondering if i have a redirect loop and how i can debug it update2thanks everyone for the suggestions some more infowhen i try to download the asset from my app i get a redirect to home page on browser but using curl i am able to get the asset ex curl http wmyappcomassetsapplicationc9a778bb55ad4152d956fd34fe6f7839css the app doesnt use ssl however i have still set origin protocol policy to match viewer as per omars suggestionsi tried to download the asset from my app on browser and am able to access the assets ex http wmyappcomassetsapplicationc9a778bb55ad4152d956fd34fe6f7839csshowever trying to access the assets directly on cloudfront d1ax5oefcdtdkicloudfrontnetassetsapplicationc9a778bb55ad4152d956fd34fe6f7839css redirects it to myappcomscreenshots for cloudfront ds at 202 pmpng,['ruby-on-rails'] +1034283,using css modules in react how can i pass a classname as a prop to a component if i have a react component and i want to pass in a classname how do i do this with css modules it currently just gives the classname but not the hash generated css module name which i would get for div classnamestylestile stylesbluehere is my tilejs componentimport react component from reactimport styles from tilecssclass tile extends component render return div classnamestylestile thispropscolor thispropschildren div export default tiletilecss value colors stylescolorscssvalue blue black red from colorstile position relative width 100 paddingbottom 100black backgroundcolor blackblue backgroundcolor bluered backgroundcolor redso as you can see i initialize this tile wrapper component as follows in my author tile but i want to pass a color prop into the componentauthortilejsreturn tile orientationblue pthispropstitlep img srcthispropsimage tile,['css'] +1034360,android http server not accessible from other devices on network intermittently i am using nanohttpd to present a web server in an android app i am using a wifi lock to keep the network alive and a cpu lock to keep the cpu awake and keeping it running via a foreground service so that it should never diewhat i am finding is that it will be accessible from other devices for half an hour and then not accessible for half an hour whenever it becomes inaccessible i can open safari on the android device and browse to 030 and verify that the server is indeed running and i also check to make sure the wifi is connected which it appears to beany suggestions of where to look,['android'] +1034504,running cucumber on device app immediately crashes error error while writing to fifo runloopfifonoreaderconfigurederror so i started building my local ios device environment i have got my simulator environment fully set up and runningi have got my thistribution and provisioning profile set up correctly to the app through the ios developerwhile trying to run the app i follow these stepsconnecting my iphone 4s ios 841 with usb cable to my macsearching for my device in the terminal with the following commandxcrun instruments s devicesthe output isknown devicesoveds imac 2e984c218f305b909844c49f071f8433qa1 841 7640b16200d8c553efda3de85291253e95d229ceapple tv 1080p 90 336265ece0474489989603cb47382325ipad 2 84 12a95700e2534cf8ada7d9bd4fbe51a9ipad 2 90 72d123e8814041c6b80c31f8da57dcb7ipad 2 91 7eaa1d9fc4e74232b754b5fb10a29ddeipad air 84 7210e244f1e24bd592b6f57e59b1d988ipad air 90 996aa70dbfe248f3af9698baa453b43bipad air 91 46d290b89e4f968134bde208ee793eipad air 2 90 8ea4a50bd8a744c79e9401df3cc494ipad air 2 91 77e90261fb184b7681c6cdb5d5f0206dipad pro 91 59474c514a80433f92fe4a72e6324efaipad retina 84 4a4e06123bcc4d099dfb6caebd7a39feipad retina 90 bf1499fa239948e094bcd9cb92203656ipad retina 91 5df2678bad5d4c839bcf500901e82a21iphone 4s 84 d130373e9bd646bba1194d0db572e2eeiphone 4s 90 54c0853ca2eb4056a6d169897f4e129eiphone 4s 91 13aeb0718db6433f9dee7354acb5dd66iphone 5 84 764c88bf6e684efab4f343cece650d83iphone 5 90 a6330df5123445e49c508360ad277133iphone 5 91 e1b14cc633aa430c8c7d33285f1854c5iphone 5s 84 0a27118866ab45f397a9551ead033509iphone 5s 90 bdd8a84e119349459d757c812303ba61iphone 5s 91 f540230c6ca34ac583c508646a14dbd3iphone 6 84 60724f5ff91e4358b02cc3bffc4e0d45iphone 6 90 159105bb0c5b471ab0b3c0f29433d7fciphone 6 91 bd8d0506ad7d44de861f31ae875540d3iphone 6 plus 84 0fd5216686f34a429b600bc4f0ab229fiphone 6 plus 90 b869364c9bd440eab856e92733256f90iphone 6 plus 91 76cb8d84a43c47ecadab27afa1ec35iphone 6s 90 ac299644a2214258b61e98d4c5e2db01iphone 6s 91 90b8a72bb98d497fb4eed3b57b6b4d0biphone 6s 91 apple watch 38mm 20 6d03ff3074b94dd1a90b309353f74b49iphone 6s plus 90 1d797c858848470ba0ac42d081be2dbfiphone 6s plus 91 96622df52f9440f49c0cd30adf3f0ecbiphone 6s plus 91 apple watch 42mm 20 d428e6334b423a806b6775ff8fe7bamy physical device is called qa1my next step was to build and compile my app on xamarin for testingi have searched the ipa file in my finder changed it is extension to zip and then could see my app filei have got the app file exported as my app bundle path in this commandexport app bundle pathusersroishmuelimekomimekomimekomiiosbiniphonetesting2821mekomipayloadmekomiiosappthen i unlocked my device and ran this command for running the app on the devicedebug1 bundle idcomkimaiamekomi device target7640b16200d8c553efda3de85291253e95d229ce device endpoint cucumberthe debug1 gives me additional output which isusersroishmuelimekomimekomimekomifeaturesstep definitionscalabash stepsrb7 warning insecure world writable dir androidandroidsdkmacosx in path mode 040757feature login scenario registration features1firstpagefeature3info using uia strategy hostdebug searching for runloop results with glob usersroishmuelirunloopresultsdebug found 6 previous runloop resultsdebug will delete 1 previous runloop resultsdebug deleted 1 previous results in 01425 secondsdebug searching for instruments caches with glob librarycachescomappledtinstrumentsxrtmp debug found 5 instruments cachesdebug will delete 0 instruments cachesdebug deleted 0 instruments caches in 014 seconds20151202 115055 0200 runloopdebug app comkimaiamekomi args bundle dir or bundle id comkimaiamekomi bundle id comkimaiamekomi device comkimaiamekomi device target 7640b16200d8c553efda3de85291253e95d229ce instruments instruments 711 launch method instruments launch retries 5 log file usersroishmuelirunloopresults20151202 115055run loopout no launch false no stop false relaunch simulator true reset false results dir usersroishmuelirunloopresults20151202 115055 results dir trace usersroishmuelirunloopresults20151202 115055trace script usersroishmuelirunloopresults20151202 115055 run loopjs sdk version nil udid 7640b16200d8c553efda3de85291253e95d229ce uia strategy host xcode 711 xcode path applicationsxcodeappcontentsdeveloperexec xcrun instruments s templatesstarting on 7640b16200d8c553efda3de85291253e95d229ce app comkimaiamekomi 20151202 115056 0200 runloopdebug xcrun instruments w 7640b16200d8c553efda3de85291253e95d229ce d usersroishmuelirunloopresults20151202 115055trace t automation comkimaiamekomi e uiaresultspath usersroishmuelirunloopresults20151202 115055 e uiascript usersroishmuelirunloopresults20151202 115055 run loopjs usersroishmuelirunloopresults20151202 115055run loopout20151202 115056 0200 runloopdebug preparation took 08732 secondsthen every 30 seconds i get this20151202 115126 0200 runloopdebug error while writing to fifo runloopfifonoreaderconfigurederror20151202 115126 0200 runloopdebug failed to launch error while writing to fifo runloopfifonoreaderconfigurederror error while writing to fifo runloopfifonoreaderconfigurederrori get these logs 5 times and then there is a timeout with this messageunable to start make sure youve set app bundle path to a build supported by this simulator version calabashcucumberlauncherstarterror timed out waiting for uiautomation runloop error while writing to fifo runloopfifonoreaderconfigurederror logfile usersroishmuelirunloopresults20151203 105835run loopout 20151203 105837013 instruments867576604129 failed to start instruments daemon on qa1 841 the service is invalid instruments usage error specified target process is invalid comkimaiamekomi instruments version 711 59040 usage instruments t template d document l timelimit i w device p pid application e variable value argument calabashcucumberlauncherstarterror libraryrubygems200gemscalabashcucumber0164libcalabashcucumberlauncherrb778in new run loop libraryrubygems200gemscalabashcucumber0164libcalabashcucumberlauncherrb635in relaunch usersroishmuelimekomimekomimekomifeaturessupport01 launchrb27in before then i see the first page featuresstep definitionscalabash stepsrb13 then i press on the verify button featuresstep definitionscalabash stepsrb23failing scenarioscucumber features1firstpagefeature3 scenario registration1 scenario 1 failed2 steps 2 skipped2m35735si have enabled my uiautomation on my device through the developer settings and through the instrumentsappi have tried multiple different app bundle paths but none of them seem to fix this what am i missingthanks in advance,"['ios', 'ruby']" +1034560,xamarin forms error droidresource does not contain a definition for string this is where the problem is red lines under stringia m developing a xamarin forms application and i am using the pcl storage plugin i think this is whats causing the problem somehow and i do not know how to fix it the problem occurs in my android solution public static void updateidvalues globalpclstorageresourcestringapplicationname globalxamarinclientsdroidresourcestringapplicationname globalpclstorageresourcestringhello globalxamarinclientsdroidresourcestringhelloi get this error error 6 xamarinclientsdroidresource does not contain a definition for string pathtomyapplicationresourcesresourcedesignercsanyone had this problem,"['c#', 'android']" +1034695,why are two raw pointers to the managed object needed in stdshared ptr implementation heres a quote from cppreferences implementation note section of stdshared ptr which mentions that there are two different pointersas shown in bold the one that can be returned by get and the one holding the actual data within the control blockin a typical implementation stdshared ptr holds only two pointersthe stored pointer one returned by geta pointer to control block the control block is a dynamicallyallocated object that holdseither a pointer to the managed object or the managed object itselfthe deleter typeerasedthe allocator typeerasedthe number of shared ptrs that own the managed objectthe number of weak ptrs that refer to the managed object the pointer held by the shared ptr directly is the one returned by get while the pointer or object held by the control block is the one that will be deleted when the number of shared owners reaches zero these pointers are not necessarily equal my question is why are two different pointerthe two in bold needed for the managed object in addition to the pointer to the control block does not the one returned by get suffice and why are not these pointers necessarily equal,['c++'] +1034707,linux server showing utc instead of est local showing est i am having trouble figuring out why the timezone for the code below keeps showing utc instead of est on my local computer it show est even if i am in mst time but on the actual server it keeps showing utc any cluemon nov 9 2015 15849 pm utcjsonignore public string getdatecreatedformatted calendar calendar calendargetinstance calendarsettimegetdatecreated calendarsettimezonetimezonegettimezoneest simpledateformat format new simpledateformate m d y hmmss a z return formatformatcalendargettime,['java'] +1034795,is this technically an o1 algorithm for hello world would this be classified as an o1 algorithm for hello world public class hello1 public static void main datetime twentyyearslater new datetime20350101 while datetimenow twentyyearslater systemconsolewritelineit is still not time to print the hello systemconsolewritelinehello world i am thinking of using the datetime twentyyearslater new datetime20350101while datetimenow twentyyearslater snippet of code as a busy loop to put in as a joke whenever someone asks for an algorithm of a certain complexity would this be correct,"['c#', '.net']" +1034870,python 2 map not equivalent to list comprehension in simple case length dependent in python 2 the built in function map seems to call the len when length is overwritten is that correct if so why are we computing the length of the iterable to map iterables do not need to have length overwritten eg and the map function works even when length is not predefined by the iterablemap is defined here it does specify that there is lengthdependent functionality in the event that multiple iterables are passed howeveri am interested in the case that only one iterable is passedeven if multiple iterables were passed not my question it seems like an odd design choice to explicitely check the length instead of just iterating until you run out and then returning nonei am concerned because according to several 1 2 extremely highly upvoted questions mapf iterableis basically equivalent tofx for x in iterablebut i am running into simple examples where that is not true for exampleclass iterable def iter self selfiterable 12345 iter return self def nextself return selfiterablenext def len self selfiterable none return 5def foox return xprint foox for x in iterable print mapfooiterable behaves as it should but if you uncomment the overloading of len it very much does not in this case it raises an attributeerror because the iterable is none while the unit behaviour is silly i see no requirement of invariance in the specification of len surely it is good practice to not modify the state in a call to len but the reason should not be because of unexpectable behaviour in builtin functions in more realistic cases my len function may just be slow and i do not expect to worry about it being called by map or maybe it is not thread safe etcimplementation dependentsince map is a builtin function it may have implementationspecific features outside the spec but cpython implements it on line 918 of bltinmodulec which indeed states do a first pass to obtain iterators for the arguments and set len to the largest of their lengths and then calls pyobject lengthhint which is defined in objectabstractc and indeed seems to look for an overwritten len this does not clarify to me whether this is just implementation dependent or if i am missing some reason that map purposefully looks for the iterables length against my instinctnote i have not tested this in python 3 that is why i specified python 2 in python3 map returns a generator so at least a few of my claims are not true,['python'] +1034871,how to implement communication activityservice i have the following situationi have a service that checks periodically for new data over the internetwhen new data are available they are downloaded and saved on sqlitewhen the save to db is complete the service broadcasts an intent so that the activity knows to pull the new data from the dbthe user might want to request an immediate updatein that case i use a messenger to request the service to look for new datahere is the problemthe user is notified that a request is ongoing but it might take a while can be unsuccessful could never returncurrently i get a message using a messenger back from the service to the activity informing of the result of the request or if i get no message in x seconds i inform the user that the request was unsuccessfulplease can you suggest a different approach i do not like to waitfor a message and if after x seconds none is received inform theuser is there a better way,"['java', 'android']" +1035189,owin openid connect authorization fails to authorize secured controller actions i am working on a project where a third party provider will act as an oauth2 based authorization server an aspnet mvc 5 based client which will send the user to the authorization server to authenticate using login password and the auth server will return an access token back to the mvc client any further calls to resource servers apis will be made using the access tokento achieve this i am using microsoftowinsecurityopenidconnect and the useopenidconnectauthentication extension i am able to successfully redirect and get the access token from the auth server but the client is not creating an authentication cookie every time i try to access a secured page i get the callback page with access token what am i missing here my current code is belowthe secured controller actionnamespace mvcwebappcontrollers public class securedcontroller controller get secured authorize public actionresult index return viewuser as claimsprincipalclaims the startup classpublic class startup public void configurationiappbuilder app appsetdefaultsigninasauthenticationtypeclientcookie appusecookieauthenticationnew cookieauthenticationoptions authenticationmode authenticationmodeactive authenticationtype clientcookie cookiename cookieauthenticationdefaultscookieprefix clientcookie expiretimespan timespanfromminutes5 approach 1 responsetype id token token appuseopenidconnectauthenticationnew openidconnectauthenticationoptions authenticationmode authenticationmodeactive authenticationtype openidconnectauthenticationdefaultsauthenticationtype signinasauthenticationtype appgetdefaultsigninasauthenticationtype authority clientid th4gvma0jsrj8rkczrzbcexk5ca clientsecret a3gvjjblhkrn9njrj3ignvk5egqa redirecturi responsetype id token token scope openid configuration new openidconnectconfiguration authorizationendpoint tokenendpoint userinfoendpoint notifications new openidconnectauthenticationnotifications securitytokenvalidated and var token nprotocolmessageaccesstoken persist access token in cookie if stringisnulloremptytoken nauthenticationticketidentityaddclaim new claimaccess token token return taskfromresult0 authenticationfailed notification if stringequalsnotificationprotocolmessageerror access denied stringcomparisonordinal notificationhandleresponse notificationresponseredirect return taskfromresultobjectnull approach 2 responsetype code appuseopenidconnectauthenticationnew openidconnectauthenticationoptions authenticationmode authenticationmodeactive authenticationtype openidconnectauthenticationdefaultsauthenticationtype signinasauthenticationtype appgetdefaultsigninasauthenticationtype authority clientid th4gvma0jsrj8rkczrzbcexk5ca clientsecret a3gvjjblhkrn9njrj3ignvk5egqa redirecturi responsetype code scope openid configuration new openidconnectconfiguration authorizationendpoint tokenendpoint userinfoendpoint notifications new openidconnectauthenticationnotifications authorizationcodereceived async notification using var client new httpclient var configuration await notificationoptionsconfigurationmanagergetconfigurationasyncnotificationrequestcallcancelled var request new httprequestmessagehttpmethodget configurationtokenendpoint requestcontent new formurlencodedcontentnew dictionarystring string openidconnectparameternamesclientid notificationoptionsclientid openidconnectparameternamesclientsecret notificationoptionsclientsecret openidconnectparameternamescode notificationprotocolmessagecode openidconnectparameternamesgranttype authorization code openidconnectparameternamesresponsetype token openidconnectparameternamesredirecturi notificationoptionsredirecturi var response await clientsendasyncrequest notificationrequestcallcancelled responseensuresuccestatuscode var payload jobjectparseawait responsecontentreadasstringasync add the access token to the returned claimsidentity to make it easier to retrieve notificationauthenticationticketidentityaddclaimnew claim type openidconnectparameternamesaccesstoken value payloadvaluestringopenidconnectparameternamesaccesstoken,['c#'] +1035312,can i use a cast inside a linq to entities query i have a linq to entities queryfrom item in ctxitemsselect new listprice itemcost 1m itemmarkupcan i specify to ef that i want it to apply a cast to the list price before querying and materializing it1 is there something like entityfunctionscast maybe or can i use the esql cast functioni want the linq to generate a sql query along these linesselect castcost 1 markup as decimal10 2 as listprice1my goal is to get rid of a bunch of precisionscale the query because there is decimal subtraction and division the result of the math is a decimal38 26 that is way more than net can handle and more than i need,['c#'] +1035436,android circular drawable i made this custom drawable that should clip any drawable in circle but with my implementation the drawable passed is being the output in the original form not in the circular formpublic class circulardrawable extends drawable paint mpaintxfermodepaint drawable mdrawable int vinylcenter new int2 int radius bitmap src porterduffxfermode xfermode rect rect canvas testcanvas public circulardrawabledrawable drawable mdrawable drawable mpaint new paintpaintanti alias flag mpaintsetcolor0xf mpaintsetstylepaintstylefill xfermodepaint new paintpaintanti alias flag xfermodenew porterduffxfermodeporterduffmodesrc in xfermodepaintsetxfermodexfermode testcanvasnew canvas override public void setboundsrect bounds supersetboundsbounds mdrawablesetboundsbounds override public void setboundsint left int top int right int bottom supersetboundsleft top right bottom mdrawablesetboundsleft top right bottom override protected void onboundschangerect bounds superonboundschangebounds vinylcenter0 boundswidth 2 vinylcenter1 boundsheight 2 radius boundsright boundsleft 2 src bitmapcreatebitmapboundswidth boundsheight bitmapconfigargb 8 testcanvassetbitmapsrc override public void drawcanvas canvas canvassave canvasdrawargb0 0 0 0 canvasdrawcirclevinylcenter0vinylcenter1radiusmpaint mdrawabledrawtestcanvas canvasdrawbitmapsrc0f0fxfermodepaint override public void setalphaint alpha ignored override public void setcolorfiltercolorfilter colorfilter ignored override public int getopacity ignored return 0 what is my mistake also i am using a squareimageview to thisplay this drawable that just makes the view square in onmeasurethis question is not meant for circular imageview,['android'] +1035498,automatically created c classes for xml deserialization do not work i am struggling to create deserialization classes for this xmlxml version10 encodingiso88591soapenvenvelope soapenvencodingstyle xmlnssoapenv xmlnsxsd xmlnsxsi xmlnssoapenc xmlnsstnurnresponse soapenvbody response records xsitypesoapencarray soapencarraytypestnrecord1 item xsitypestnrecord person xsitypexsdstringjohn johnosperson address xsitypexsdstringsome street 1address age xsitypexsdstring24age item records status xsitypesoapencarray soapencarraytypestnstatus1 item xsitypestnstatus status xsitypexsdstringsuccestatus message xsitypexsdstring item status response soapenvbodysoapenvenvelopei have tried to use automatically created code in visualstudio 12 edit paste special paste xml as classes remarkssystemserializableattributesystemcomponentmodeldesignercategoryattributecodesystemxmlserializationxmltypeattributeanonymoustype true namespace systemxmlserializationxmlrootattributenamespace isnullable falsepublic partial class envelope private envelopebody bodyfield private string encodingstylefield remarks public envelopebody body get return thisbodyfield set thisbodyfield value remarks systemxmlserializationxmlattributeattributeform systemxmlschemaxmlschemaformqualified public string encodingstyle get return thisencodingstylefield set thisencodingstylefield value remarkssystemserializableattributesystemcomponentmodeldesignercategoryattributecodesystemxmlserializationxmltypeattributeanonymoustype true namespace public partial class envelopebody private response responsefield remarks systemxmlserializationxmlelementattributenamespace public response response get return thisresponsefield set thisresponsefield value remarkssystemserializableattributesystemcomponentmodeldesignercategoryattributecodesystemxmlserializationxmltypeattributeanonymoustype truesystemxmlserializationxmlrootattributenamespace isnullable falsepublic partial class response private responserecords recordsfield private responsestatus statusfield remarks public responserecords records get return thisrecordsfield set thisrecordsfield value remarks public responsestatus status get return thisstatusfield set thisstatusfield value remarkssystemserializableattributesystemcomponentmodeldesignercategoryattributecodesystemxmlserializationxmltypeattributeanonymoustype truepublic partial class responserecords private responserecordsitem itemfield private string arraytypefield remarks public responserecordsitem item get return thisitemfield set thisitemfield value remarks systemxmlserializationxmlattributeattributeform systemxmlschemaxmlschemaformqualified namespace public string arraytype get return thisarraytypefield set thisarraytypefield value remarkssystemserializableattributesystemcomponentmodeldesignercategoryattributecodesystemxmlserializationxmltypeattributeanonymoustype truepublic partial class responserecordsitem private string personfield private string addressfield private byte agefield remarks public string person get return thispersonfield set thispersonfield value remarks public string address get return thisaddressfield set thisaddressfield value remarks public byte age get return thisagefield set thisagefield value remarkssystemserializableattributesystemcomponentmodeldesignercategoryattributecodesystemxmlserializationxmltypeattributeanonymoustype truepublic partial class responsestatus private responsestatusitem itemfield private string arraytypefield remarks public responsestatusitem item get return thisitemfield set thisitemfield value remarks systemxmlserializationxmlattributeattributeform systemxmlschemaxmlschemaformqualified namespace public string arraytype get return thisarraytypefield set thisarraytypefield value remarkssystemserializableattributesystemcomponentmodeldesignercategoryattributecodesystemxmlserializationxmltypeattributeanonymoustype truepublic partial class responsestatusitem private string statusfield private object messagefield remarks public string status get return thisstatusfield set thisstatusfield value remarks public object message get return thismessagefield set thismessagefield value i tried to deserialize with help of xmlserializervar serializer new xmlserializertypeofenvelopevar reader new stringreaderresponsevar flresponse envelopeserializerdeserializereaderthe error message i gotmessagethe specified type was not recognized namearray namespace at records xmlnscould you please help me to greate deserialization classes for this xml,['c#'] +1035500,use userdefined build settings in custom plist file i have different build configurations develop stage prod defined for my app and i use userdefined build settingsto set up facebook login and other stuff in infoplist file in this scenario the user defined settings notation does work then i tried to set up google signin which requires using additional plist file googleserviceinfoplist and i used userdefined settings in the same way i had done in the infoplist file but it does not workhow can i use userdefined settings in custom plist files if i cannot how can i workaround this,['ios'] +1035505,why do i get permission denied in microsoft edge when accessing parent iframe i have some problems calling a function of a specific iframe after reloading another iframe it works on all major browser but behaves a little weird on microsoft edge you will need the following constellation to get the error all files are in the same directory on the same server i have not set any content security policy if you load the frame1html everything will be fine and you will get the alert messagebut if you click the click me atag on the frame4html the frame2html will be reloaded and you will get the permission denied error because the parent object var tmpparent parent is not accessible if you click the atag again it will work without any errori think it is a edge bug because all other browser can handle it and it only occur on the first clickthe error will also occur if you use top insted of parentthe code of topframejs is used to find the topmost frame of my sitei cannot simply use top because it should be possible to embed my sitedoes anybody have a cluethanks a lotframe1htmldoctype htmlhtmlhead titleframe 1title script typetextjavascript var topframe this function myalert alertalert scriptheadbody iframe idoverallcontentwrapper namemainframe srcframe2html frameborder0iframebodyhtmlframe2htmldoctype htmlhtmlhead titleframe 2title script srctopframejs typetextjavascriptscript script typetextjavascript windowaddeventlistenerload function loadevent windowremoveeventlistenerload load false try topframemyalert catch e alerte false scriptheadbody iframe namesubframe srcframe3html frameborder0iframebodyhtmlframe3htmldoctype htmlhtmlhead titleframe 3titleheadbody iframe namesubsubframe srcframe4html frameborder0iframebodyhtmlframe4htmldoctype htmlhtmlhead titleframe 4titleheadbody a hrefframe2html targetmainframeclick meabodyhtmltopframejstry var tmpparent parent var topframe tmpparenttopframe while topframe undefined tmpparent tmpparentparent topframe tmpparenttopframe catch e alerte,['javascript'] +1035566,javascript code optimization for find i have c code that runs a query in sql and returns roughly 20 rows then a treeview control is created and added the my main page this is done almost instantly which is good var orgid selectnamectl00pagecontentfunctionsdropdownlist optionselectedval if orgid return false calls serverside get data this line happens quickly ctl00 pagecontent hiddenrulesdialogtriggerbuttonclick this part takes about 1015 minutes to finally get to the true var i setintervalfunction if ctl00 pagecontent treeviewfindtablelength 0 clearintervali startdialog return false so it takes about 1015 minutes to hit the clearintervali when it does i 978 not sure why it would take so long possibly the find is really slow does anyone recommend an alternativeedit,"['javascript', 'c#', 'jquery']" +1035615,calling static async methods from aspnet project i am wondering will this scenario be thread safe and are there issues that i am not currently seeingfrom aspnet controller i call nonstatic method from nonstatic class this class is in another project and class is injected into controllerthis method which is nonstatic does some work and calls some other static method passing it useridfinally static method does some work for which userid is neededi believe this approach is thread safe and that everything will be done properly if two users call this method at the same time let us say in same nanosecond am i correct or completely wrong if i am wrong what would be correct way of using static methods within aspnet project edithere is code this is call from the controllerawait workoutservicedeleteworkoutbyidasyncazurerethisfeedsconnectionmultiplexergetrethisdatabaseazurerethisleaderboardconnectionmultiplexergetrethisdatabase workoutid useridhere how deleteworkoutbyidasync looks likepublic async taskbool deleteworkoutbyidasyncidatabase rethisdbidatabase rethisleaderboarddb guid id string userid using var databasecontext new databasecontext var workout await databasecontexttreningsfindasyncid if workout null return false databasecontexttreningsremoveworkout await databasecontextsavechangesasync await rethisfeedservicestaticdeletefeeditemfromfeedsasyncrethisdbrethisleaderboarddb userid workouttreningidtostring return true as you can notice deleteworkoutbyidasync calls static method staticdeletefeeditemfromfeedsasync which looks like thispublic static async task staticdeletefeeditemfromfeedsasyncidatabase rethisdbidatabase rethisleaderboard string userid string workoutid var deletetasks new listtask var feedallrethisvals await rethisdblistrangeasyncfeedallworkouts userid deleteitemfromrethisasyncrethisdb feedallrethisvals feedallworkouts userid workoutid ref deletetasks await taskwhenalldeletetasks and here is static method deleteitemfromrethisasync which is called in staticdeletefeeditemfromfeedsasyncprivate static void deleteitemfromrethisasyncidatabase rethisdb rethisvalue feed string rethiskey string workoutid ref listtask deletetasks var itemtoremove foreach var f in feed if ftostringcontainsworkoutid itemtoremove f break if stringisnulloremptyitemtoremove deletetasksaddrethisdblistremoveasyncrethiskey itemtoremove,"['c#', 'asp.net']" +1035746,best way to receive the return value from a python generator since python 33 if a generator function returns a value that becomes the value for the stopiteration exception that is raised this can be collected a number of waysthe value of a yield from expression which implies the enclosing function is also a generatorwrapping a call to next or send in a tryexcept blockhowever if i am simply wanting to iterate over the generator in a for loop the easiest way there does not appear to be a way to collect the value of the stopiteration exception and thus the return value im using a simple example where the generator yields values and returns some kind of summary at the end running totals averages timing statistics etcfor i in produce values do somethingivalues summary one way is to handle the loop myselfvalues iter produce valuestry while true i nextvalues iter do somethingiexcept stopiteration as e values summary evaluebut this throws away the simplicity of the for loop i cannot use yield from since that requires the calling code to be itself a generator is there a simpler way than the rollonesown for loop shown above answer summarycombining answers from chad s and kt the simplest appears to turn my generator function into a class using the iterator protocolclass valuegenerator def iter self yield 1 yield 2 and so on selfsummary vg valuegeneratorfor i in vg do somethingivalues summary vgsummaryand ferdinand beyers answer is simplest if i cannot refactor the value producer,['python'] +1035869,java out of memory automatic heap dump file name i have several java processes and i am trying to manage the heap dumps created when oom error occur when i say manage i meanname the heap dump differently based on the originating processdelete older heap dumps to preserve thisk spacewhen dumping heap on oom with xxheapdumponoutofmemoryerror xxheapdumppathtmpthe jvm creates a file with the following name java pidxhprof in the specified tmp folder where x is the pid of the processis there anyway to specify a different format where the pid and date are used to create the file nameafter googling for an hour i tried myprefix pid dateetcthe only two things that work are not specify the file name and you get java pidxhprofspecify a static file name eg tmpoomhprofif the tmp folder does not exist it does not get created nor the heap dump gets created the one idea that could use is to add a command on oom errorxxonoutofmemoryerrordosomethingsh pbut i was trying to avoid it as i need to deploy the dosomethingsh,['java'] +1035967,rangeforloops and stdvector why does this code workstdvectorint intvector10forauto i intvector stdcout iand this does notstdvectorbool boolvector10forauto i boolvector stdcout iin the latter case i get an error error invalid initialization of nonconst reference of type astd bit referencea from an rvalue of type astd bit iteratorreference aka std bit referenceaforauto i boolvector,['c++'] +1036003,update value of an element in react component from ios uiwebview i am trying to transfer data from native ios app to a react not reactnative web app running in a uiwebviewi get a string from native viewcontroller and need to inject it into the value of an input element inside a react component class i gave the element an id like sorender div input idiccid typetext nameiccid patternd onchangethisiccidchangedbindthis autofocus divthen using javascriptcore from ios swift code i runselfcontext selfwebviewvalueforkeypathdocumentviewwebviewmainframejavascriptcontext as jscontextselfcontextevaluatescriptdocumentgetelementbyidiccidvaluebarcodevalue this seems work fine and i can see the value updated in the dom inside the webview problem is that my react onchange function that validates the value and changes component state does not fire as react does not interpret this as a change probably because of dom vs virtual dom handlingwhats the correct waybest practice to update the element value from ios and get the react component to behave like user has typed it in,"['javascript', 'ios']" +1036124,php7 laravel mcrypt issue since laravel4 requires mcrypt extension and php7 does not seem to have mcrypt extension is there any workaround for this to work,['php'] +1036218,why does heroku localrun wants to use the global python installation instead of the currently activated virtual env using heroku to deploy our django application everything seems to work by the spec except the heroku localrun commandwe oftentimes need to run commands through djangos managepy file running them on the remote as oneoff dynos works flawlesslyto run them locally we tryheroku localrun python managepy the commandwhich fails despite the fact that the current virtual env contains a django installation with importerror no module named djangocoremanagementa diagnostic through the python paththen heroku localrun which python returns usrlocalbinpythonwhereas which python returns usersmyusernamemyprojectvenvbinpython the correct valueis this a bug in heroku localrun or are we missunderstanding its expected behaviour and more importantly is there a way to have heroku localrun use the currently installed virtual env,['python'] +1036329,smtpclient cannot send thunderbird can this should be pretty routine rightpublic static smtpclient getsmtpclient var client new smtpclient host smtpserver usedefaultcredentials false credentials new networkcredential smtpusername smtppassword port smtpport port 25 enablessl smtpssl false return clientvar m new mailmessage contents of mail messageusing var server getsmtpclient serversendmbut serversend is throwing an smtpexceptionfailure sending mail systemioioexception unable to read data from the transport connection net io connectionclosedsomething wrong with my credentials ip block on the smtp server maybe my isp blocking outgoing requests to port 25 i downloaded and installed thunderbird on the same machine as my debug environment and set up identical smtp credentials there and it works perfectlyso why does it work in thunderbird but not in my codeupdate following up on tzachss suggestion i downloaded wireshark and found that the transaction progress is identical up to a pointthunderbirdtcp 62 25 a 50924 syn ack seq0 ack1 win5840 len0 mss1360 sack perm1smtp 143 s 220 smtpsomedomaincom esmtp sendmail 81388138 sat 5 dec 2015 154622 0500tcp 54 25 a 50924 ack seq90 ack18 win5840 len0smtp 289 s 250 smtpsomedomaincom hello mycomputermyispcom xx6061 pleased to meet you 250 enhancedstatuscodes 250 pipelining 250 8bitmime 250 size 250 dsn 250 etrn 250 auth login plain 250 deliverby 250 helpsmtp 82 s 235 200 ok authenticatedetcsmtpclienttcp 62 25 a 50889 syn ack seq0 ack1 win5840 len0 mss1360 sack perm1smtp 143 s 220 smtpsomedomaincom esmtp sendmail 81388138 sat 5 dec 2015 154508 0500tcp 54 25 a 50889 ack seq90 ack21 win5840 len0smtp 289 s 250 smtpsomedomaincom hello mycomputermyispcom xx6061 pleased to meet you 250 enhancedstatuscodes 250 pipelining 250 8bitmime 250 size 250 dsn 250 etrn 250 auth login plain 250 deliverby 250 helptcp 54 25 a 50889 fin ack seq325 ack62 win5840 len0tcp 54 25 a 50889 ack seq326 ack63 win5840 len0notice that after the pleased to meet you line in the smtpclient trace there is nothing about authentication not accepted not failed nothing just terminates the connectiondoes that shed any lightanother update the smtp server is running sendmail fwiw the error is specific to this particular smtp host when i point at different servers the code works fine,['c#'] +1036331,deserialize object via jsonconvert and custom typeconverter i have simple dtopublic class simpledto public int status get set public long fromdate get set public long todate get set and i have proxydto with typeconverterattributetypeconvertertypeofsimpleconvertsimpledtopublic class proxydtot public t object get set here is the implementation of simpleconvertpublic class simpleconvertt typeconverter public override bool canconvertfromitypedescriptorcontext context type sourcetype return sourcetype typeofstring basecanconvertfromcontext sourcetype public override object convertfromitypedescriptorcontext context cultureinfo culture object value var strvalue value as string return strvalue null new proxydtot object jsonconvertdeserializeobjecttstrvalue baseconvertfromcontext culture value public override object converttoitypedescriptorcontext context cultureinfo culture object value type destinationtype var val value as proxydtot return destinationtype typeofstring val null valobjecttojson baseconverttocontext culture value destinationtype also i have simple json for dtostatus3fromdate12345todate54321when i try to deserialize this object via proxyvar obj jsonconvertdeserializeobjectproxydtosimpledtostrit fails with exception newtonsoftjsonjsonserializationexception cannot deserialize the current json object eg namevalue into type detect console application exit2proxydto1detect console application exit2simpledto because the type requires a json string value to deserialize correctly to fix this error either change the json to a json string value or change the deserialized type so that it is a normal net type eg not a primitive type like integer not a collection type like an array or list that can be deserialized from a json object jsonobjectattribute can also be added to the type to force it to deserialize from a json object path status line 1 position 10but if my json has escaping jsonstatus3fromdate12345todate54321it works well i do not understand why the first json object is not correct can you help meupdatehere is tojson methodpublic static class extension public static string tojsonthis object val return jsonconvertserializeobjectval,['c#'] +1036411,how do i focus a camera in windows universal apps i am working with the windows universal sample for ocr located herespecifically the ocrcapturedimagexamlcsit seems that the camera often becomes unfocused blurry and nowhere near as good quality as the native camera app how can i set up autofocusing andor tap to fix exposurewhat i have tried so far is looking at the other camera samples which help set resolution but i cannot find anything about focusexposureupdatei thinkawait mediacapturevideodevicecontrollerfocuscontrolfocusasyncandawait mediacapturevideodevicecontrollerexposurecontrolsetautoasynctruebut this is not working does nothingstill blurry etc and could be built upon if someone knows how to tap a certain area and apply focusexposure accordinglynative cameraapp cameraupdate based on answeri must have been putting my focus methods in the wrong spot because my original update code works sergis also works i want to used the tapped event in combination with it something like thispoint tappedegetpositionnull where e is tappedroutedeventargs from a tapped event method on my preview screenawait mediacapturevideodevicecontrollerregionsofinterestcontrolclearregionsasyncawait mediacapturevideodevicecontrollerregionsofinterestcontrolsetregionsasyncnew new regionofinterest bounds new recttappedx tappedy 002 002 throws parameter incorrectbut it throws parameter incorrect also how would i show the overlay a rectangle on the preview screen so the user knows how big the region of interest isthis is a great link,['c#'] +1036420,get and set cursor position with contenteditable div i have a contenteditable div which i would like to be able to have users insert things such as links images or youtube videos at the moment this is what i havefunction addlink var link urlval editorfocus documentexeccommandcreatelink false linkscript srcscript text editor div ideditor contenteditabletruediv add link input typetext idurlbutton onclickaddlinksubmitbuttonas you can see the user has to type into a separate text box to enter the link address as a result when the link is added to the editor it is not added to the position that the pointercaret was onmy question is how i can get and set the location of the pointercaret i have seen other questions such as this for setting the pointer however i would prefer to have a solution which is supported in all modern browsers including chrome safari firefox and ie9any ideas thanksediti found the code below which gets the position however it only gets the position according to the line it is on for example if i had this where is the cursorthis is some textand some more textthen i would be returned the value 7 not 24function getposition if windowgetselection sel windowgetselection if selgetrangeat return selgetrangeat0startoffset return null,"['javascript', 'jquery', 'html']" +1036887,c11 how to observe memory order in atomicstore and atomicload update 3after understanding what memory order is i know the problem is totally not related to compilerand yes because my cpu architecture is intel x86 no matter what code i write the memory order effect will never happenupdate 2i check the thisassembly code however i find no matter how i add code the xstore always prior to ystorethe problem should come from compiler which does not reorder these code instead of cpu as far as i thinkupdateafter i read comments it seems like i have to borrow a machine whichs cpu is alpha arm or ppcdoes anyone know where i can use this kind of machine even this is not for freeorigini am testing the code belowatomicint x0atomicint y0void thr1 xstore1memory order relaxed ystore1memory order relaxedvoid thr2 whileyloadmemory order relaxed coutxloadmemory order relaxedendl may 0 or 1i know the output may be 0however no matter how much times i tried i always get 1is this because of my cpu is x86 architecture if not how to fix this problembtw i know cppmem but it cannot use loop,['c++'] +1037099,ios ld framework not found googlemaps for architecture arm64 i am developing an app using google maps i will explain what i did with google maps and maybe you can help mei was using google maps frameworks without pod but after a few errors about google map key i deleted the google map frameworks reference and i installed it using pod everything is working fine but when i hit product testnow i get this errorld framework not found googlemaps for architecture arm64any idea how fix thisthank youpodfile looks like this cocoapods v10 beta 6platform ios 80use frameworkstarget project do pod googlemaps target projecttests do inherit search paths pod mockingjay endend,['ios'] +1037130,how to add custom function to response object in nodejs in my apiapplication i have a fixed response for errors in different parts as you can see resstatus400jsonerror invalid input is repeating a lot in different files and modules actually i could create modulefunction invalidinputres which will eliminate duplication but i really want this to be global part of res object like resinvalidinput how could i make it in jsnodejsroutergetusers functionreq res if error return resstatus400jsonerror invalid input routergetitems functionreq res if error return resstatus400jsonerror invalid input etc,['javascript'] +1037252,unable to let user upload profile picture in sign up process parsecomjs sdk using parsecom and the javascript sdk the code should let a user sign up and upload a profile pictureupdated this is the code i am using that is returning an error when trying to sign up a user the console message is uncaught typeerror cannot read property length of undefined signupclickfunctione usersignup function usersignup var user new parseuser userfirstname firstnamesuval userlastname lastnamesuval userusername usernamesuval usergender gendersuval email emailsuval pwp passwordsuval usersetfirstname userfirstname usersetlastname userlastname usersetusername userusername usersetgender usergender usersetemail email usersetpassword pwp var fileuploadcontrol pic0 if fileuploadcontrolfileslength 0 var file fileuploadcontrolfiles0 var name photopng var parsefile new parsefilename file put this inside if parsefilesavethenfunction the file has been saved to parse functionerror the file either could not be read or could not be saved to parse be sure of your parameters name prod is extend of my class in parse from this var prod new products usersetprofilepic parsefile usersave runs parse after the signup button has been clicked by the user signupclickfunctione usersignup usersignupnull success functionuser if userexisted windowlocationhref user homehtml else alertno way buddy error functionuser error,['javascript'] +1037263,breakpoint hits hashmapput a simple hello world program program is simplei14public class helloworld public static void mainstring args systemoutprintlnhello world now i set a breakpoint into function putk key v value in hashmapclasspublic v putk key v value if table empty table inflatetablethreshold if key null return putfornullkeyvalue int hash hashkeyand then i start debugging the helloworldclass it will run into the breakpoint in hashmap it is strange to me that how it can run into put in hashmapi tried hashmap hashtable and they are all the same,['java'] +1037319,edit xml file in windows store app i am making an app in windows store and having a problem in writing xml in created xml filei have followed this editing xml file in windows store app but it did not work for mei want this xml to be wrote in my xml file on button clickany alternate way for this stuff drink drinkimageckpngdrinkimage drinktitlecokedrinktitle drinkdescription17931844drinkdescription drinkmy current file is this xml version10 encodingutf8 drinks drink drinkimagepepsipngdrinkimage drinktitlepepsidrinktitle drinkdescription17931844drinkdescription drinkhere i want above xml on button click drinkshere is what i have triednamespace drinksapp summary an empty page that can be used on its own or navigated to within a frame summary public sealed partial class coke page public coke thisinitializecomponent xmldocument dom new xmldocument private void button clickobject sender routedeventargs e thisframenavigatetypeofsoftdrinks private async void button click 1object sender routedeventargs e xdocument xmldoc xdocumentloadfavouritefavxml xmldocrootaddnew xelementdrink new xattributedrinkimageckpng new xattributedrinktitlepepsi new xattributedrinkdescriptionnone xmldocsavexmldoc this is not working in windows store i already have an xml file as mentioned above,['c#'] +1037471,why no default clone in cloneable in java 8 cloneable in java is inherently broken specifically my biggest problem with the interface is it expects a method behavior that does not define the method itself so if traversing through a cloneable list you must use reflection to access its defined behavior however in java 8 we now have default methods and now i ask why there is not a default clone method in cloneablei understand why interfaces cannot default object methods however this was an explicit design decision and so exceptions can be madei sort of envision deprecating objectclone and changing its interior code to something likeifthis instanceof cloneable return cloneable thiscloneelse throw new clonenotsupportedexceptionand moving on whatever magic makes clone do its thing as a default method in cloneable this does not really fix that clone can still easily be implemented incorrectly but that is another thiscussion in of itselfas far as i can still this change would be completely backwards compatibleclasses that currently override clone but did not implement cloneable why would still be technically okay even if functionally impossible but this is no different then it was beforeclasses that currently override clone but did implement cloneable would still function the same on its implementationclasses that do not currently override clone but did implement cloneable why would now follow a specification even if it is not completely functionally correctthose that used reflection and referred to objectclone would still functionally worksuperclone would still be functionally the same even if it is referencing objectclonenot to mention this would solve a huge problem that cloneable is while tedious and still easy to implement incorrectly it would solve a huge object oriented problem with the interfacethe only problem i can see with this is those that implement cloneable are not obligated to override clone but this is no different than it was beforehas this been thiscussed internally but never came to fruition if so why if it is for the reason that interfaces cannot default object methods wouldnt it make sense to make an exception in this case since all objects inheriting cloneable are expecting clone anyway,['java'] +1037535,ios google sign in error i am trying to implement a google sign in button when i add the following lines to my appdelegateswift file i get this errorcannot subscript a value of type string anyobject with an index of type stringany ideas whats wrong with this code by the way this code is just copied and pasted from google page atverswiftfunc applicationapplication uiapplication openurl url nsurl options options string anyobject bool return gidsigninsharedinstancehandleurlurl sourceapplication optionsuiapplicationopenurloptionssourceapplicationkey annotation optionsuiapplicationopenurloptionsannotationkeythanks,['ios'] +1037546,springboot 130 support hibernate 5 i am a little confused about springboots 130 support of hibernate5 the reference lists a dependency on hibernate 4311final but it also lists a dependency on springframework 423 which includes hibernate5 supportis it just a matter of adding the extra hibernate5 dependencies to override what boot bundles can someone please clarify for me,['java'] +1037577,broken create save update and destroy on join record when using postgres uuids in rails i am creating uids usingcreate table users id false do t tuuid uid default uuid generate v4 other columnsand setting selfprimary key uid in the models in general this works fine with activerecord and i write has many and belongs to associations fine however when crossing a join table ie has many through i need to write custom sql to get recordsi have figured out that i can in general do this by writing custom sql ie select from main table join join table on main tableuid castjoin tableuid as uuid where conditiontruei have just recently realized that activerecords create destroy save and update dont work on the join model i have patched the four methods so they work but it is too complex a sequence for my taste and probably unoptimal here are my patchesdef saveargs save sometimes works if it is called twice and sometimes works the first time but says theres an error superargs unless superargs rescue trueendsometimes save issues a rollback the first time with no explanation then it works the second time in other situations i am not sure why possibly when updating the first time it goes through successfully but if called a second time raises a typeerror see here for another question about this error which does not have any answers for how to save a join when using uid instead of id here are my other working patches def createargs attrs args0 raise argumenterror invalid args to bucket list create unless attrsis ahash bucket list photo selfclassnew attrs bucket list photosave bucket list photo bucketlistphotofind by bucket list uid bucket list photobucket list uid photo uid bucket list photophoto uid return bucket list photoenddef updateargs similar bug to save attrs args0 raise argumenterror invalid args to bucket list update unless attrsis ahash bucket list uid selfbucket list uid photo uid selfphoto uid due at selfdue at selfdestroy bucket list photo selfclassnew bucket list uid bucket list uid photo uid photo uid due at due at mergeattrs bucket list photosave bucket list photo selfclassfind by photo uid photo uid bucket list uid bucket list uid return bucket list photo phewenddef destroy patching to fix an error on destroy destroy all etc the problem was apparently caused by custom primary keys uids see however a custom fix is implemented here deleted uids activerecordbaseconnectionexecute delete from bucket list photos where uiduid returning uid to amap record recorduid raise bucketlistphoto not deleted unless deleted uidslength 1 deleted uidsfirst uid activerecordbaseconnectionquery cacheclear since the cache isnt updated when using activerecordbaseconnectionexecute reset the cache to ensure accurate values ie counts and associations endi even ensured that selfprimary key uid in all my models i also tried replacing uid with id everywhere and verified that all the specs were passing though i left in the patch however it still failed when i removed the patch ie renaming the uid columns to id did not fix it editin response to some comments i have tried the activeuuid gem where i got stuck on an error and decided to totally switch over to ids this is basically for simplicitys sake since i have pressure to launch this app asap still even with this fix i am required to patch save create and update actually the delete patch no longer works and i had to remove it relying on the original i would definitely like to avoid having to make these patches and i am keeping the bounty open for this reason,"['ruby-on-rails', 'ruby']" +1037617,can not open more than 11 instances of excel using excel interop on windows 10 using excel interop in c under windows 10 on a macbook pro with 16gb of memory i cannot open more than 11 instances of excel after the 11th instance i get the following error in a popupcannot use object linking and embeddinghere is the code i uselistapplication apps new listapplicationfor int i 0 i 15 i application a new application appsaddaeach excel process is about 15k of memory far from the 16gb available on the machinei am using the net framework 452 windows 10 macbook pro with 16gb of memory and excel personal,['c#'] +1037918,liskov substitution principle and proper way to use inherited classes i have some handler controller classes and they can process items in some wayinterface ihandler public function executeitem itemclass firsthandler implements ihandler public function executeitem item echo itemgettitle class secondhandler implements ihandler public function executeitem item echo itemgetid itemgettitle class item public function getid return rand public function gettitle return title at time but then i need to add some new functionality in child item classclass newitem extends item public function getauthor return author rand and use it in secondhandlerclass secondhandler implements ihandler public function executeitem item printfd s author s itemgetid itemgettitle itemgetauthor but item class actually has not getauthor method and if i try to change signature of accept method in secondhandler class i will catch e strict error about declaration compatibility and of course it is sort of lsp violationhow can i fix this problem do i need two interfaces for example inewhandler and ihandler with different signatures of execute method but it is some sort of code duplicatesalso i cannot use constructoritem item and constructnewitem item in handlers and execute method without arguments which will be seen like a better solution they must be immutable and only single instance of every strategy allowed in application lifecycle,['php'] +1037928,sql select values starting with a capital letter i have a table with a varchar type column i want to select values from this column which start with a capital letter only for example mytablecol1 col2argentina 2brasil 3uruguay 4i want my select query to returnargentinabrasil,['sql'] +1038088,how to lift a function to take an extra parameter in c i understand that c is not intended to be used in a functional way however having learned functional programming i have trouble thinking differentlygiven those restrictionsno nested functions because clang forbids it so no lamda expressionsno global variablescan we think of a way of lifting a function f to take an extra parameter to fit a prototype such as this new parameter will be ignored when f is executedhere is in detail what i want to doi want to fit a function f whose type isf void fchar sin a function g that takes an function as an argument call it arg whose type isarg void funsigned int i char sthus the type of g isg void gvoid f unsigned int charthe solution in haskell would be the followingg const fis that even possible maybe with some kind of macro wizardryedit to provide a better understanding here is the actual code the body of ft striter needs to be completed the purpose is apply the function f to every character of a string using or not using its index ivoid ft striterchar s void f char s ft striteristatic void ft striteri helperchar s unsigned int i void funsigned int char if s fi s ft striteri helpers 1 i 1 f void ft striterichar s void funsigned int char ft striteri helpers 0 f,['c'] +1038108,coordinatorlayout and appbarlayout elevation i have created an appbar layout like thisandroidsupportdesignwidgetappbarlayout xmlnsapp xmlnsandroid androidididappbar layout androidlayout heightdimenapp bar height androidlayout widthmatch parent androidfitssystemwindowstrue androidthemestylethemeoverlayappcompatdarkactionbar appelevation20dp androidsupportdesignwidgetcollapsingtoolbarlayoutandroidsupportdesignwidgetappbarlayoutit works and casts a shadow in the linearlayoutlinearlayout xmlnsandroid androidlayout widthmatch parent androidlayout heightmatch parent include layoutlayoutapp bar large linearlayouthowever when i put it into the coordinatorlayout shadow is goneandroidsupportdesignwidgetcoordinatorlayout xmlnsandroid androidlayout widthmatch parent androidlayout heightmatch parent include layoutlayoutapp bar large androidsupportdesignwidgetcoordinatorlayouthow can i make appbar to show its shadow again,['android'] +1038222,show d3 link text rightside up i have built a d3 force directed visualization with text labels along the links the one problem i am running into is these labels appearing upside down when the links are to the left of their source node example herethe code where i position the path and text looks like sovar nodes flattendatavar links d3layouttreelinksnodesvar path visselectallpathlink datalinks functiond return dtargetid pathenterinsertsvgpath attr class link id functiond return textpath dtargetid markerend urlend stylestroke cvar linktext visselectallglinktextdatalinkslinktextenter appendtext appendtextpath attrxlinkhref functiond return textpath dtargetid styletextanchor middle attrstartoffset 50 textfunctiond return dtargetcustomeridi know i will need to somehow determine the current angle of each path and then set the text position accordingly but i am not sure how tohere is a link to a block based on this issue the answer below has got me about 90 of the way there here is what my original visualization looks like with text longer than a couple digit numberand here is what it looks like utilizing the tips in the below answerso while the text is now rightside up it no longer follows the arc,['javascript'] +1038379,easeljs alpha mask filter i am fairly new to canvas i have been trying to get the images reversed in this easeljs alpha mask example so that the initial image is clear and what you paint is blurry basically the reverse of the demoi have been playing around with it for hours applying filters to the bitmap var and removing them from the blur var everything i do just does not work seems like it would be an easy fix of just switching things around but that does not seem to be the case not for me anywaydoes anybody have an example of this or know what to do i could provide code examples of what i did but it is basically just playing around with stuff like a monkey on a typewriterheres the code on githubheres the relevant code from their examplescript ideditable var stage var isdrawing var drawingcanvas var oldpt var oldmidpt var thisplaycanvas var image var bitmap var maskfilter var cursor var text var blur function init examplesshowthistractor image new image imageonload handlecomplete imagesrc assetsartflowersjpg stage new createjsstagetestcanvas text new createjstextloading 20px arial f textsetx stagecanvaswidth 2 y stagecanvasheight 40 texttextalign center function handlecomplete exampleshidethistractor createjstouchenablestage stageenablemouseover stageaddeventlistenerstagemousedown handlemousedown stageaddeventlistenerstagemouseup handlemouseup stageaddeventlistenerstagemousemove handlemousemove drawingcanvas new createjsshape bitmap new createjsbitmapimage blur new createjsbitmapimage blurfilters new createjsblurfilter24 24 2 new createjscolormatrixfilternew createjscolormatrix60 blurcache0 0 960 400 texttext click and drag to reveal the image stageaddchildblur text bitmap updatecacheimagefalse cursor new createjsshapenew createjsgraphicsbeginfillfdrawcircle0 0 25 cursorcursor pointer stageaddchildcursor function handlemousedownevent oldpt new createjspointstagemousex stagemousey oldmidpt oldpt isdrawing true function handlemousemoveevent cursorx stagemousex cursory stagemousey if isdrawing stageupdate return var midpoint new createjspointoldptx stagemousex 1 oldpty stagemousey 1 drawingcanvasgraphicssetstrokestyle40 round round beginstrokergba02 movetomidpointx midpointy curvetooldptx oldpty oldmidptx oldmidpty oldptx stagemousex oldpty stagemousey oldmidptx midpointx oldmidpty midpointy updatecacheimagetrue function handlemouseupevent updatecacheimagetrue isdrawing false function updatecacheimageupdate if update drawingcanvasupdatecache else drawingcanvascache0 0 imagewidth imageheight maskfilter new createjsalphamaskfilterdrawingcanvascachecanvas bitmapfilters maskfilter if update bitmapupdatecache0 0 imagewidth imageheight else bitmapcache0 0 imagewidth imageheight stageupdate script,['javascript'] +1038477,apache redirect all to indexphp except for existing files and folders i have indexphp that reads full path by serverarequest uria variable my task is when user enter wdomainresource7 redirect to indexphp with path resource7 and parse serverarequest uria to do some logic but i have also real files and folders likecssthemecssassetsassetsjsresourcelocalejswhen i try this configrewriteengine onrewritecond request filename drewritecond request filename frewriterule indexphp lclient could not get all css and etc files how to write correct rule in apache to achive this,['php'] +1038592,combine multiple linq where statements i have created a function to filter and sort the content of a listit is seems a bit bitty however linq is not strong point i am wondering if the function can be streamlined either from a performance perspective or even asthetic perspectiveheres the code deserialise the xml to create a class of active rows var agents xmlhelper deserialiseagentconfigspingtreexml agents wherex xisactive true first get direct agents and order them var direct agents wherex xisdirect orderbydescendingx xminprice second get indirect agents and order them var agency agents wherex xisdirect orderbyx xpriority bolt the 2 sublists together retaining the order agents directconcatagencytolistany thoughts on how this could be improved,"['c#', 'asp.net']" +1038627,get less variables list using lessjs i am using clientside lessjs is there a way to get all variables from my less file i know how to modify variableslessmodifyvars var fbut i want to get all of them like do not workvar variables lessgetvars,"['javascript', 'css']" +1038632,why preg match returns some empty elements i have written the regexp 1515 15 15 to match either standalone digit 15 or a digit separated by at least one space form the rest of the string i have tested it in online services and the result is the digit itself however when using codepreg match1515 15 15 order 12314124 5 matchesi get thisarray 0 order 12314124 5 1 2 3 5 the 0 element is a full match which is good i anticipated the 1 element be 5 but it is empty and there is another empty element why these empty elements appear,['php'] +1038753,iis express httpplatformhandler crash when launching aspnet 5 rc1 application after an upgrade from aspnet 5 beta 7 to rc1 an attempt to launch the web aplication in iis express from within visual studio ends with an error occurred attempting to determine the process id of the dnx process hosting your application in windows event log i can see following errorsprocess 1828 failed to start port 315 error code 2147024891 eventid 10 this happens alwayswarning could not create stdoutlogfile c temp httpplatformstdoutlog 6072 2015128124832log errorcode 2147024864 eventid 1004 this happens only sometimeslog files as configured in the httpplatformhandler configuration do get created but are completely empty as well as vs output windowhow can i diagnose the reason for the failurerelevant versions arevisual studio enterprise 2015 update 1 dnx sdk version 100rc1update1windows 7 enterprise sp1 64bitrelevant sections from webconfigsystemwebserver handlers add namehttpplatformhandler path verb moduleshttpplatformhandler resourcetypeunspecified handlers httpplatform processpathdnx path argumentsdnx args stdoutlogenabledtrue stdoutlogfilec temp httpplatformstdoutlog startuptimelimit3600 forwardwindowsauthtokenfalse systemwebserverwhats perhaps also interesting is that initially when i tried to run a brand new aspnet 5 web application created from template it worked now it does not eitherupdate despite the error iis express starts but returns 5023 bad gateway error,['.net'] +1038768,why deletion between start and end strings would not work properly in java i have the following file that represent booksbook isbn3titleenglish1publishdate1122015pagecount200authors12 11 johnbook isbn5titleenglish2publishdate1122015pagecount200authors12 11 john2book isbn6titleenglish3publishdate1122015pagecount200authors12 11 john3i have tried to delete the second book from the file using this functionthe funtionpublic static void removelinefromfilestring file string start string end try file infile new filefile construct the new file that will later be renamed to the original filename file tempfile new fileinfilegetabsolutepath tmp bufferedreader br new bufferedreadernew filereaderfile printwriter pw new printwriternew filewritertempfile string line null boolean flagtrue read from the original file and write to the new unless content matches data to be removed while line brreadline null if linetrimequalsstart flagfalse iflinetrimequalsend flagtrue if flag linetrimequalsend pwprintlnline pwflush pwclose brclose delete the original file if infiledelete systemoutprintlncould not delete file return rename the new file to the filename the original file had if tempfilerenametoinfile systemoutprintlncould not rename file catch filenotfoundexception ex exprintstacktrace catch ioexception ex exprintstacktrace the function callpublic static void mainstring args removelinefromfileefiletxt book isbn5the book was deleted but the other seperator are also deleted book isbn3titleenglish1publishdate1122015pagecount200authors12 11 johnbook isbn6titleenglish3publishdate1122015pagecount200authors12 11 john3what should i do to get the following result insteadbook isbn3titleenglish1publishdate1122015pagecount200authors12 11 johnbook isbn6titleenglish3publishdate1122015pagecount200authors12 11 john3,['java'] +1038795,how to debug an application running in docker with intellij i have a jetty application running in docker i would like to debug this application using my local intellij i am on v 141 so i have installed the docker integration pluginunder clouds i am using the default values that showed up when i click on the intellij docs say this should be ok here the api url certificates folder emptyi am not sure what these are used for so i dont know if these values are rightunder rundebug configurations i am using docker deployment and the following valuesdeployment docker imageimage id the docker image id container name the name of the containerwhen i try to run this i get javaxwsrsprocessingexception orgapachehttpconnhttphostconnectexception connect to 127001 failed connection refusedobviously the api url value i am using is incorrect any suggestions on what that value should bemy debugging options are xdebug xnoagent xrunjdwptransportdt socketaddress5005serverysuspendn djavacompilernone,['java'] +1038897,adding qty and addtocart in related products on product detail page for virtuemart 3 and thisplay in linear fashion i would like to know how to add qty addtocart button and thisplay them in a linear fashion on the vm3 product details pagei located a similar question here thisplay pricing and add to cart button in related products virtuemart 20 but none of that works for vm3i think i found the right files at componentscom virtuemartsublayoutsrelatedphp but none of the syntax looks like it does in the question i foundi will attach a before and after picture of what i am trying to accomplishbeforeand this is what i would like for it to look like afterif you have any ideas or hints i would be so grateful this is what i have got in componentscom virtuemartsublayoutsrelatedphpphpdefined jexec or dierestricted accessrelated viewdatarelatedcustomfield viewdatacustomfieldthumb viewdatathumbjuriroot for whatever reason we used this here maybe it was for the mailsecho jhtmllink jroute indexphpoptioncom virtuemartviewproductdetailsvirtuemart product id relatedvirtuemart product id virtuemart category id relatedvirtuemart category id thumb relatedproduct name arraytitle relatedproduct nametarget blankifcustomfieldwprice currency calculationhelpergetinstance currencythisplay echo currencycreatepricediv salesprice com virtuemart product salesprice relatedpricesifcustomfieldwdescr echo p classproduct s descrelatedproduct s descpthis is what i have in componentscom virtuemartviewsproductdetailstmpldefaultphpphp show the product details page package virtuemart subpackage author max milbers eugen stranz max galt link copyright copyright c 2004 2014 virtuemart team all rights reserved license gnugpl see licensephp virtuemart is free software this version may have been modified pursuant to the gnu general public license and as thistributed it includes or is derivative of works licensed under the gnu general public license or other free or open source software licenses version id defaultphp 9058 201510 183054z milbo check to ensure this file is included in joomladefined jexec or dierestricted access let us see if we found the product if emptythisproduct echo vmtext com virtuemart product not found echo br br thiscontinue link html returnecho shopfunctionsfrendervmsublayoutaskrecomjsarrayproductthisproductifvrequestgetintprintfalse body onloadjavascriptprintphp div classproductdetailsview productdetails php product navigation if vmconfiggetproduct navigation 1 div classproductneighbours php if emptythisproductneighbours previous0 prev link jroute indexphpoptioncom virtuemartviewproductdetailsvirtuemart product id thisproductneighbours previous0 virtuemart product id virtuemart category id thisproductvirtuemart category id false echo jhtml link prev link thisproductneighbours previous0 product name arrayrelprev class previouspagedatadynamicupdate 1 if emptythisproductneighbours next0 next link jroute indexphpoptioncom virtuemartviewproductdetailsvirtuemart product id thisproductneighbours next0 virtuemart product id virtuemart category id thisproductvirtuemart category id false echo jhtml link next link thisproductneighbours next0 product name arrayrelnextclass nextpagedatadynamicupdate 1 div classcleardiv div php product navigation end php back to category button if thisproductvirtuemart category id caturl jroute indexphpoptioncom virtuemartviewcategoryvirtuemart category idthisproductvirtuemart category id false categoryname vmtext thisproductcategory name else caturl jroute indexphpoptioncom virtuemart categoryname vmtext com virtuemart shop home div classbacktocategory a hrefphp echo caturl classproductdetails titlephp echo categoryname php echo vmtextsprintfcom virtuemart category back tocategoryname a div php product title h1 itempropnamephp echo thisproductproduct name h1 php product title end php afterthisplaytitle event echo thisproducteventafterthisplaytitle php product edit link echo thisedit link product edit link end php pdf print email icon if vmconfiggetshow emailfriend vmconfiggetshow printicon vmconfiggetpdf icon div classicons php link indexphptmplcomponentoptioncom virtuemartviewproductdetailsvirtuemart product id thisproductvirtuemart product id echo thislinkiconlink formatpdf com virtuemart pdf pdf button pdf icon false echo thislinkiconlink print1 com virtuemart print printbutton show printicon echo thislinkiconlink print1 com virtuemart print printbutton show printiconfalsetruefalseclassprintmodal maillink indexphpoptioncom virtuemartviewproductdetailstaskrecommendvirtuemart product id thisproductvirtuemart product id virtuemart category id thisproductvirtuemart category id tmplcomponent echo thislinkiconmaillink com virtuemart email emailbutton show emailfriend falsetruefalseclassrecommenedtofriend div classcleardiv div php pdf print email icon end php product short description if emptythisproductproduct s desc div classproductshortdescription php todo test if content plugins modify the product description echo nl2brthisproductproduct s desc div php product short description end echo shopfunctionsfrendervmsublayoutcustomfieldsarrayproductthisproductpositionontop div classvmproductcontainer div classvmproductmediacontainerphpecho thisloadtemplateimages div div classvmproductdetailscontainer div claspacerbuyarea php todo in multivendor not needed at the moment and just would lead to confusion link jroute index2phpoptioncom virtuemartviewvirtuemarttaskvendorinfovirtuemart vendor idthisproductvirtuemart vendor id text vmtext com virtuemart vendor form info lbl echo span classbold vmtext com virtuemart product details vendor lbl span a classmodal hrefphp echo link php echo text abr php echo shopfunctionsfrendervmsublayoutratingarrayshowratingthisshowratingproductthisproduct if is arraythisproductthisplayshipments foreach thisproductthisplayshipments as productthisplayshipment echo productthisplayshipment br if is arraythisproductthisplaypayments foreach thisproductthisplaypayments as productthisplaypayment echo productthisplaypayment br in case you are not happy using everywhere the same price thisplay fromat just create your own layout in override htmlfields and use as first parameter the name of your file echo shopfunctionsfrendervmsublayoutpricesarrayproductthisproductcurrencythiscurrency div classcleardivphp echo shopfunctionsfrendervmsublayoutaddtocartarrayproductthisproduct echo shopfunctionsfrendervmsublayoutstockhandlearrayproductthisproduct ask a question about this product if vmconfiggetask question 0 1 askquestion url jroute indexphpoptioncom virtuemartviewproductdetailstaskaskquestionvirtuemart product id thisproductvirtuemart product id virtuemart category id thisproductvirtuemart category id tmplcomponent false div classaskaquestion a classaskaquestion hrefphp echo askquestion url relnofollow php echo vmtext com virtuemart product enquiry lbl a div php php manufacturer of the product if vmconfiggetshow manufacturers 1 emptythisproductvirtuemart manufacturer id echo thisloadtemplatemanufacturer div div div classcleardiv divphp count images count thisproductimages if count images 1 echo thisloadtemplateimages additional event oncontentbeforethisplay echo thisproducteventbeforethisplaycontent php echo thisproductproduct in stock thisproductproduct ordered product description if emptythisproductproduct desc div classproductdescription php todo test if content plugins modify the product description span classtitlephp echo vmtext com virtuemart product desc title span php echo thisproductproduct desc div php product description end echo shopfunctionsfrendervmsublayoutcustomfieldsarrayproductthisproductpositionnormal product packaging product packaging if thisproductproduct box div classproductbox php echo vmtext com virtuemart product units in box thisproductproduct box div php product packaging end php echo shopfunctionsfrendervmsublayoutcustomfieldsarrayproductthisproductpositiononbot echo shopfunctionsfrendervmsublayoutcustomfieldsarrayproductthisproductpositionrelated productsclass productrelatedproductscustomtitle true echo shopfunctionsfrendervmsublayoutcustomfieldsarrayproductthisproductpositionrelated categoriesclass productrelatedcategories php oncontentafterthisplay eventecho thisproducteventafterthisplaycontentecho thisloadtemplatereviews show child categoriesif vmconfiggetshowcategory 1 echo thisloadtemplateshowcategoryj jquerydocumentreadyfunction virtuemartproductjqueryformproduct formjsrecalculateeachfunction if thisfindproductfieldslength thisfindnovmbindlength var id thisfindinputnamevirtuemart product idval virtuemartsetproducttypethisid vmjsapiaddjscriptrecalcreadyj galt notice for template developers templates must set a virtuemartcontainer variable as it takes part in dynamic content update this variable points to a topmost element that holds other content j virtuemartcontainer jqueryproductdetailsviewvirtuemartcontainerselector productdetailsviewvmjsapiaddjscriptajaxcontentjifvmconfigget jdynupdate true j jquerydocumentreadyfunction virtuemartstopvmloading var msg jqueryadatadynamicupdate1offclick virtuemartstartvmloadingonclick msgmsg virtuemartstartvmloading jquerydatadynamicupdate1offchange virtuemartstartvmloadingonchange msgmsg virtuemartstartvmloading vmjsapiaddjscriptvmpreloaderjecho vmjsapiwritejsif thisproductpricessalesprice 0 echo shopfunctionsfrendervmsublayoutsnippetsarrayproductthisproduct currencythiscurrency showratingthisshowratingdiv,['php'] +1038924,how to speed up pymc markov model is there a way to speed up this simple pymc model on 2040 data points it takes 511 seconds to fitimport pymcimport timeimport numpy as npfrom collections import ordereddict prior probability of rainp rain 05variables ordereddict rain observationsdata true true true true true false false false false false4num steps lendatap rain given rain 09p rain given norain 02p umbrella given rain 08p umbrella given norain 03for and in rangenum steps if and 0 rain node at time t 0 rain pymcbernoullirain d n p rain else rain trans pymclambdarain trans lambda prev rainvariablesrain d n1 prev rainp rain given rain 1prev rainp rain given norain rain pymcbernoullirain d n prain trans umbrella obs pymclambdaumbrella obs lambda rainrain rainp umbrella given rain 1rainp umbrella given norain umbrella pymcbernoulliumbrella d n pumbrella obs observedtrue valuedatan variablesrain d n rain variablesumbrella d n umbrellaprint running on d points lendataall vars variablesvaluest start timetimemodel pymcmodelall varsm pymcmcmcmodelmsampleiter20t end timetimeprint n2f secs to run t end t startwith only 40 data points it takes 11 seconds to runrunning on 40 points 100 20 of 20 complete in 115 sec1154 secs to runwith 80 points it takes 20 seconds this is a toy example the expressions inside lambda that determine transitions are in practice more complex this basic code structure is flexible whereas encoding the model with transition matrices is less flexible is there a way to keep a similar code structure but get better performance happy to switch to pymc3 if necessary thanks,['python'] +1039004,can stdbasic stringoperator return a thistant protected page nul terminator so operator does not directly say that size must be the character after size1 in memory it seems worded to avoid making that claimbut sdata states that sdatak sk and sdata must return a pointerignoring the seeming standard defect of using on chart above and not stdaddressof is the implementation free to return a different chart say one on a protected page or in rom for size prior to the first call to sdata clearly it could arrange the buffer to end on a readonly page with a zero on it i am talking about a different situationto be explicitas far as i can tell if sdata is never called and the compiler can prove it then size need not be contiguous with the rest of the buffercan stdaddressofsize change after a call to sdata and the implementation be standardscompliant so long as sdatak sk has data evaluated before but the compiler is free to enforce that or are there immutability requirements i cannot see,['c++'] +1039248,detecting if a character device has thisconnected in linux in with termios api c i am using the termios api in linux to communicate with a serial device i am trying to detect if the device has thisconnected so i can try to reconnect after some timeout i have the following example codewhile1 fd zerorfds fd sety fd rfds have tried checking fcntltty fd f getfl too blocking call to wait until we have data selecty fd1 rfds null null null while we have data collect it while readtty fd c 10 bytesread200 serialbufferpush backc bytesread 0 try to parse it bufferparsei am not actually seeing select or fcntl return error values 1 after the ttyusb device is physically thisconnected i could of course check to see if the file in dev exists but i was hoping there was a more elegant solutionwould appreciate any advice thanks,['c++'] +1039257,grid layout with collectionview in swift i would like to achieve this resultsearching around i found out that probably the way to do it is using uicollectionview so no problem with that since there are many tutorials and questions on stack overflow i have 3 questions i cannot find anything about the separators the line that divides all the boxes i like that it does not touch the screen borders horizontally is it done programmatically to divide the space equally in all devices 3 boxesbuttons horizontally i found this answer answer is this the right approachfor the blur effect i found this answer how to implement uivisualeffectview in uitableview with adaptive seguesfor a tableview it would beif uiaccessibilityisreducetransparencyenabled tableviewbackgroundcolor uicolorclearcolorlet blureffect uiblureffectstyle lightlet blureffectview uivisualeffectvieweffect blureffecttableviewbackgroundview blureffectviewcan i do something like this iboutlet var collectionview uicollectionview if uiaccessibilityisreducetransparencyenabled collectionviewbackgroundcolor uicolorclearcolor let blureffect uiblureffectstyle light let blureffectview uivisualeffectvieweffect blureffect collectionviewbackgroundview blureffectview,['ios'] +1039262,unity 53 how to load current level before unity 53 i could do applicationloadlevelapplicationloadedlevelbut now it is something weird with scenemanager i have read documentation but nothing how do i get the current scene and load it unity 53f4thanks,['c#'] +1039413,pyqt4 how to pause a thread until a signal is emitted i have the following pyqtmainpyusrbinpython3import sysfrom pyqt4qtcore import from pyqt4qtgui import from pyqtmeasthread import class mainwindowqmainwindow def init self parentnone selfqt app qapplicationsysargv qmainwindow init self parent buttonwidget qwidget rsltlabel qlabelresult selfrsltfiled qlineedit selfbuttonstart qpushbuttonstart verticallayout qvboxlayoutbuttonwidget verticallayoutaddwidgetrsltlabel verticallayoutaddwidgetselfrsltfiled verticallayoutaddwidgetselfbuttonstart butdw qdockwidgetcontrol self butdwsetwidgetbuttonwidget selfadockwidgetqtleftdockwidgetarea butdw selfmthread qthread new thread to run the measurement engine selfworker measurementengine measurement engine object selfworkermovetothreadselfmthread selfmthreadfinishedconnectselfworkerdeletelater cleanup after thread finished selfworkermeasure msgconnectselfshowrslt selfbuttonstartclickedconnectselfworkerrun everything configured start the worker thread selfmthreadstart def runself show the window and start the event loop selfshow selfqt appexec start event loop pyqtslotstr def showrsltself mystr selfrsltfiledsettextmystrdef main win mainwindow winrunif name main mainand another thread script performing the actual measurementfrom pyqt4qtcore import import timeclass measurementengineqobject measure msg pyqtsignalstr def init self qobject init self do not forget to call base class constructor pyqtslot def runself selfmeasure msgemitphase1 timesleep2 here i would like to make it as an interrupt selfmeasure msgemitphase2what this code does now is that after the start button is pressed the function run in the thread will be executed however actually in the function run there are two phases of the measurement right now i used an time delaybut what i would like to implement actually is that after the phase1 measurement is done a message box will be popped up and at the same time the thread will be pausedheld until the user closed the message box then the thread function will be resumed,['python'] +1039489,basic centering elements in adaptive row class in bootstrap on my page i have lots of elements which i need to show by several in a row in straight columns each element is an image of equal size when you click on it on it is place appears icon menu with three items in a row all elements should be centred horizontally and vertically there could be a different number of big images 6 7 8 or more so i want to add them in one rowclass now i think i am doing everything by bootstrap documentation but elements logic on the page steel appears to be broken what am i doing wrongcodepen examplebody div classcontainerfluid wrapper div classrow centerblock textcenter div classcenterblock colxs6 colsm4 colmd3 collg2 div classrow centerblock div classcolmd12 centerblock img src div div div div classcenterblock colxs6 colsm4 colmd3 collg2 div classrow centerblock div classcolmd12 centerblock img src div div div div classcenterblock colxs6 colsm4 colmd3 collg2 div classrow centerblock div classcolmd12 centerblock img src div div div div classcenterblock colxs6 colsm4 colmd3 collg2 div classrowfluid centerblock textcenter paginationcentered div classcolmd4 centerblock textcenter paginationcentered link a target blank hrefimg srca div div classcolmd4 centerblock textcenter paginationcentered link a target blank hrefimg srca div div classcolmd4 centerblock textcenter paginationcentered link a target blank hrefimg srca div div classcolmd4 centerblock textcenter paginationcentered link a target blank hrefimg srca div div classcolmd4 centerblock textcenter paginationcentered link a target blank hrefimg srca div div classcolmd4 centerblock textcenter paginationcentered link a target blank hrefimg srca div div classcolmd4 centerblock textcenter paginationcentered link a target blank hrefimg srca div div classcolmd4 centerblock textcenter paginationcentered link a target blank hrefimg srca div div classcolmd4 centerblock textcenter paginationcentered link a target blank hrefimg srca div div div div classcenterblock colxs6 colsm4 colmd3 collg2 div classrow centerblock div classcolmd12 centerblock img src div div div div classcenterblock colxs6 colsm4 colmd3 collg2 div classrow centerblock div classcolmd12 centerblock img src div div div div classcenterblock colxs6 colsm4 colmd3 collg2 div classrow centerblock div classcolmd12 centerblock img src div div div div classcenterblock colxs6 colsm4 colmd3 collg2 div classrow centerblock div classcolmd12 centerblock img src div div div div classcenterblock colxs6 colsm4 colmd3 collg2 div classrow centerblock div classcolmd12 centerblock img src div div div div divbodyscreenshot of what i getscreenshot of what i needplease point me in the right direction thank you in advance i was able to done it without bootstrap b i hope it could be done only by the right usage of bootstrap and elements because i want to save the adaptive layoutupd legendaryaks fixed the problem with gap by using div classclearfixdiv after icons element but problem of centering all elements for the adaptive layout and unknown number of total elements is still openupd2 centering just one element in the end is not enough because we need to know how to center from one to max number of elements on the last row sow that we could load all the elements on a page with no worry for the last row centering,"['html', 'css']" +1039586,grunt copy html files to scripts folder on build i use the angulargenerator in yeoman in gruntfilejs every html file in appviews get copied to thistviews but i like to keep my directive templates in the same folder as the directive itself exampleappscriptswidgetsmywidgetdirectivejsappscriptswidgetsmywidgettmplhtmlwhen i build the project i want the html file to end up in the same folder structure as above this should probably be done in the copy section in gruntfilejscopy thist files expand true dot true cwd yeomanapp dest yeomanthist src icopngtxt html imageswebp stylesfonts i tried to add this in the src array yeomanthist scriptstmplhtmldid not work any ideas,['javascript'] +1039603,what is the most efficient way to declare functions in javascript i have always learned that to declare a function in javascript you should do something likefunction myfunctionfruit alerti like fruit or something likevar myfunction functionfruit alerti like fruit however most recently i have noticed that some people actually define functions as constants const myfunction fruit alerti like fruit or even using the keyword letlet myfunction fruit alerti like fruit at this point i am quite confusedwhy so many ways of defining functionswhenwhere should i use each onewhich way is more efficient,['javascript'] +1039655,how can you pass an stdistream into a function in a way that allows to pass temporaries i am trying to create a constructor to load a resource from any istream given to it i cannot seem to figure out the best way to pass the istream parameter into a constructorloaderloaderistream streamthis one is obviosly bad due to object slicing so no optionloaderloaderistream streamthis is what i am using now and seems fairly alright it has one significant issue though you cannot give it a temporary since temporaries cannot bind to nonconst references for example the following would not workcontainer mloaderifstreampathfiletxt iosbinarythis is rather a limitation since i am now forced to store the ifstream as a member variable of container just to extend its lifetimesince the problem is with nonconst references one could have though of thisloaderloaderconst istream streambut since seek etc are nonconst this is not an option eitherso how can this problem be solved in a neat way,['c++'] +1039718,how do i run a python script with tensorflow running in a docker on windows imagine i manage to install tensorflow on windows using docker as in these two links for exampletensorflow on windowshow to install and run tensorflow on a windows pcin both links they are able to use tensorflow on a shell python do not know exactly what version i have anaconda installed but what if i want to run a script that i made on my local machine that has tensorflow in it how do i call the script from docker i mean how do i find the script located on my desktop for instance from docker to run it,['python'] +1039780,when implementing a linked list in c who is responsible for freeing the value i am implementing a linked list in c and i am running into the issue where c does not implement any specific scheme for memory management other than just giving you the ability to allocate and free memory by passing a pointer there is no concept of whether the value might be needed later on in the programthe typical implementation i find online for a linked list basically deallocs the deleted node but does not dealloc the nodes value whose responsibility should it be to release the memory taken up by the value when deleted from the list the linked lists or the normal flow of the program example allocate 10 byteschar text mallocsizeofchar 10 create the linked listlinkedlist list list create add the text pointer to the linked listlist appendlist text remove the pointer from the linked listlist remove lastlistin this case text would end up not getting deallocated as list remove last just frees the memory that the new node takes up what would be the proper way to release the memory taken up by text,['c'] +1039888,fast random weighted selection across all rows of a stochastic matrix numpyrandomchoice allows for weighted selection from a vector iearr numpyarray1 2 3weights numpyarray02 05 03choice numpyrandomchoicearr pweights selects 1 with probability 02 2 with probability 05 and 3 with probability 03what if we wanted to do this quickly in a vectorized fashion for a 2d array matrix for which each of the rows are a vector of probabilities that is we want a vector of choices from a stochastic matrix this is the super slow wayimport numpy as npm 10n 100 or some very large numberitems nparangemprob weights nprandomrandm nprob matrix prob weights prob weightssumaxis0 keepdimstruechoices npzerosn this is slow because of the loop in pythonfor i in rangen choicesi nprandomchoiceitems pprob matrixiprintchoicesarray 4 7 8 1 0 4 3 7 1 5 7 5 3 1 9 1 1 5 9 8 2 3 2 6 4 3 8 4 1 1 4 0 1 8 5 3 9 9 6 5 4 8 4 2 4 0 3 1 2 5 9 3 9 9 7 9 3 9 4 8 8 7 6 4 6 7 9 5 0 6 1 3 3 2 4 7 0 6 3 5 8 0 8 3 4 5 2 2 1 1 9 9 4 3 3 2 8 0 6 1this post suggests that cumsum and bisect could be a potential approach and is fast but while numpycumsumarr axis1 can do this along one axis of a numpy array the bisectbisect function only works on a single array at a time similarly numpysearchsorted only works on 1d arrays as wellis there a quick way to do this using only vectorized operations,['python'] +1040052,es6 circular dependency this is an issue i run into fairly frequently and i was hoping to thiscover the correct way to handle itso i have a setup like thisparentjsexport default x 1ajsimport parent from parentjsexport default parentextenda title a bjsimport parent from parentjsexport default parentextendb title b cool now i have got some childrenbut i decide i would like to have a function in parentjs that checks if an object is an instance of a or bso i might do thisparentjsimport a from aimport b from bexport default x 1 checktype obj if obj instanceof a return a else if obj instanceof b return b well now that is a circular dependency is there an elegant way to handle this,['javascript'] +1040071,javascript copy string to clipboard as texthtml is there a way in javascript to copy an html string ie bxxb into the clipboard as texthtml so that it can then be pasted into for example a gmail message with the formatting ie xx in boldthere exists solutions to copy to the clipboard as text textplain for example but not as texthtmli need a non flash non jquery solution that will work at least on ie11 ff42 and chromeideally i would like to store both text and html versions of the string in the clipboard so that the right one can be pasted depending if the target supports html or not,['javascript'] +1040075,optimize snmp library to search a device ip address in iphone i am using mobile snmp library in iphone app to scan devices using swift languagethe mobile snmp library is written in objectivec and with bridging header i am able to use the this library in my swift project and it works perfectlyi need to scan devices from particular range of ip address suppose17023450 to 1702345255 for this i am using getoid function from xismobile snmp ppmm snmp ppmmto get response from single ip address it approximately takes 12 seconds per responseso to reduce the time me using multithreading as suggested in the below link with maximum 20 of threads only at time since we are going to use the app in iphone and it takes 20 seconds for complete scan from 0 to 255 i need to reduce this time to around 5 secondsoptimized way to search a device ip address within a range in iphoneissue every time when search begins getoid funtion opens socket and sends data and then gets response and closes socketso cannot we keep the socket open scan all ip address and get it is respone and close the socket at last i need to reduce the search time from 20 seconds to 5 seconds so how can we do it in getoid function nsdictionary getoidnsstring oid addressnsstring hostaddress snmpversionuintversion remoteportnsnumber aport withcommunitynsstring community retryuintretries timeoutuinttimeout errornserror autoreleasingerror int status uint l retries uint l timeout nsnumber localport snmp version snmpversion version1 octetstr snmpcommunitycommunity utf8string if aport nil localport nsnumber numberwithinteger161 else localport aport if retries 100 l retries 100 else l retries retries if timeout 100 l timeout 100 else if timeout 500 l timeout 500 else l timeout timeout switch version case 1 snmpversion version1 break case 2 snmpversion version2c break default snmpversion version1 break generate a snmp generic address udpaddress udpaddresshostaddress utf8string check if it is a valid address if we got an invalid address we return a nil dictionary and an error code if udpaddressvalid error self constructerrorerr invalid destinationifdef debug nslogerror snmpcontroller getoidhostaddressoidsnmpversionremoteportwithcommunityretrytimeouterror nslogerror snmp invalid host address or ip hostaddress nslogerror endif return nil check if we got a valid oid otherwise use sysdescr oid localoidoid utf8string if localoidvalid ifdef debug nslogerror snmpcontroller getoidhostaddressoidsnmpversionremoteportwithcommunityretrytimeouterror nslogerror snmp we got an invalid oid we are using sysdescr for now 1361210 oid nslogerror endif oid localoid1361210 create the snmp session snmp snmpstatus 0 udpaddressget ip version addressversion ipv6 if status snmp class success ifdef debug nslogerror snmpcontroller getoidhostaddressoidsnmpversionremoteportwithcommunityretrytimeouterror nslogerror snmp could not create session s snmperror msgstatus nslogerror endif error self constructerrorerr no snmp session return nil we are ready to build the snmp object we need pdu pdu construct a pdu object vb vb construct a vb object vbset oidlocaloid set the oid portion of the vb pdu vb add the vb to the pdu set the port udpaddreset portlocalport integervalue ctarget ctargetudpaddress make a target using the address ctargetset versionsnmpversion set the snmp version ctargetset retryl retries set the number of retries ctargetset timeoutl timeout set the timeout for the request ctargetset readcommunitysnmpcommunity set the read community name issue the request in blocked modeifdef debug nslogdebug snmpcontroller getoidhostaddressoidsnmpversionremoteportwithcommunityretrytimeouterror nslogdebug snmp get to oid with version d on port d using community with retries d and timeout d hostaddress oid version aport integervalue community retries timeout nslogdebug snmp what is the community we are sending s snmpcommunityget printable nslogdebug endif snmptarget target target ctarget status snmpgetpdu target nsmutabledictionary resultsdict nsmutabledictionary alloc init if status snmp class success pduget vbvb 0ifdef debug nslogdebug snmpcontroller getoidhostaddressoidsnmpversionremoteportwithcommunityretrytimeouterror nslogdebug snmp oid s vbget printable oid nslogdebug snmp value s vbget printable valueendif add the results to the resultsdict resultsdict setobjectnsstring stringwithutf8stringvbget printable value forkeynsstring stringwithutf8stringvbget printable oid if vbget syntax snmp syntax endofmibview vbget syntax snmp syntax nosuchinstance vbget syntax snmp syntax nosuchobject nslogerror snmp exception found lu vbget syntax else nslogerror snmp get error s d snmperror msgstatus status ifdef debug nslogdebug endif make sure error is nil error nil return resultsdict nil nsdictionary dictionarywithdictionaryresultsdict nil,"['ios', 'iphone']" +1040206,how do websites know they are not the default home page or search provider as far as i am aware there is no public api exposure of a browsers default homepagesearch provider so how does google know to thisplay this it only comes around when googles not the default homepage default search provider on my browseri can only assume they are inferring from numerous variables such as the referrer i was not able to successfully dig down into googles compiled javascript i am not even sure if it is detected clientside or serverside i am on firefox 44 but i have seen these banners on chrome too,['javascript'] +1040541,errors with static table views i am newbie in ios development and swift trying to work out a couple of scenes in my app my i cant get the tableviews to work as they shouldim doing a settings like tableview where the user choses between two possible settings each options leads to new tableview where the user must pick one of the available options once the user has chosen one the label in the first scene will thisplay the value chosen which is stored also as nsuserdefaults so if im not mistaken this could be achieved with 3 static tableviews the code following is how im trying to do itinitial settings view controllerclass settingsvc2 uitableviewcontroller override func viewdidload superviewdidload do any additional setup after loading the viewoverride func numberofsectionsintableviewtableview uitableview int return 2override func tableviewtableview uitableview numberofrowsinsection section int int return 1override func tableviewtableview uitableview cellforrowatindexpath indexpath nsindexpath uitableviewcell if indexpathsection 0 let cell tableviewdequeuereusablecellwithidentifieroffice cell forindexpath indexpath celltextlabeltext select your office return cell else let cell tableviewdequeuereusablecellwithidentifierdept cell forindexpath indexpath celltextlabeltext select your department return cell one of the settings tableviewsclass settingsdepartmenttvc uitableviewcontrollerlet departamentos string sales presales general administration customer service profesional services regionalesoverride func viewdidload superviewdidload do any additional setup after loading the viewoverride func didreceivememorywarning superdidreceivememorywarning thispose of any resources that can be recreatedoverride func tableviewtableview uitableview numberofrowsinsection section int int return departamentoscountoverride func tableviewtableview uitableview diddeselectrowatindexpath indexpath nsindexpath override func numberofsectionsintableviewtableview uitableview int return 1override func tableviewtableview uitableview cellforrowatindexpath indexpath nsindexpath uitableviewcell let cell uitableviewcell selftableviewdequeuereusablecellwithidentifierdepartment cell forindexpath indexpath celltextlabeltext selfdepartamentosindexpathrow return celli believe all datasources and delegates are hooked right and uikit is imported even if not shownerros im getting assertion failure in uitableview dequeuereusablecellwithidentifierforindexpathterminating app due to uncaught exception nsinternalinconsistencyexception reason unable to dequeue a cell with identifier office cell must register a nib or a class for the identifier or connect a prototype cell in a storyboardi have tried a million different things to fix what specifies in the error log but none of them fixed itthanks in advancedthis is the method where i try to populate the tableviewfunc tableviewtableview uitableview cellforrowatindexpath indexpath nsindexpath uitableviewcell let cell tableviewdequeuereusablecellwithidentifiercommentsrowtvc forindexpath indexpath as commentsrowtvc let single comment selfaosindexpathrow celltitulo comentariotext single commenttitulo comment cellcuerpo comentariotext single commentcuerpo comment cellfecha comentariotext single commentfecha comment return cellclass commentsrowtvc uitableviewcell iboutlet weak var titulo comentario uilabeliboutlet weak var cuerpo comentario uilabeliboutlet weak var fecha comentario uilabeloverride func awakefromnib superawakefromnib initialization codeoverride func setselectedselected bool animated bool supersetselectedselected animated animated configure the view for the selected statehere is the connections inspector for the uiviewcontroller where the table isand this one for the uiviewcellcontrollererrors to this pointuiview tableviewnumberofrowsinsection unrecognized selector sent to instanceterminating app due to uncaught exception nsinvalidargumentexception reason uiview tableviewnumberofrowsinsection unrecognized selector sent to instance,['ios'] +1040577,entity framework cannot update database my application crashes with the following error whenever i save to the dbunable to find an entry point named setclrfeatureswitchmap in dll sqlserverspatial110dllthis error started yesterday afternoon after a windows update and pc reboot the dll is not referenced in the project and is not in the bin folderi use ef5 and i can connect to the db and pull data but when i call objectcontextsavechanges the error occursthe application does not use geometry so i have no idea where this is coming from,['c#'] +1040598,in cqrs pattern should work go in domain services or command handlers should domain services inject other domain services and do work between each other and have the commandhandler be dumb or should the domain services be dumb only be used to interface the repository barrier and the majority of work be done in commandhandlers what is best practices here,['c#'] +1040752,c random number from 1 to a very large number eg 25 million how would you make a function that generates a random number from 1 to 25 millioni have thought about using rand but am i right in thinking that the maximum number rand max is 320 there aboutis there a way around this a way that does not reduce the probability of picking very low numbers and does not increase the probability of picking high medium numbersedit jamey d s method worked perfectly independent of qt,['c++'] +1040794,semirobust newspaper column extraction this is my first opencv program so be forgiving if i seem ignorant to some basic computer vision conceptsupdate see new codenew problem at bottom thanks to the answer by sturkmeni am working on digitizing a large set of images like the ones attached as a project all images come from the same source the end goal is to pass extracted chunks of text to tesseract the ocr librarysource code at bottomi am going to explain my current approach and then state my questionsmy current approach is as followsapply inverse binary threshold dilate image and find contours create a boundingrect from each contour then filter for minimum and maximum dimensionsthis has worked okmy desired end result is to have one boundingrect around each column so for the provided pictures that would be seven of themso the problem is that the tabulated mini sections in the image are not reliably picked up best example would be the one in the far right column that does not have a boundingrect around iti can think of two possible solutions so as to not be an openended opinion type question but if you know of a better solution do share it1 combine boundingrects that are vertical neighbors to capture the columns contains possible edgecase failures2 find a different way to manipulate the image before finding the contours from my research the run length smoothing algorithm looks promisingso my question is which approach is best have i overlooked a better solution i am inexperienced in this department so no suggestion is too smallthanks for readinginclude opencv2corehppinclude opencv2highguihppinclude opencv2imgprochppinclude iostreaminclude fstreaminclude sstreaminclude vectorusing namespace cvusing namespace stdint mainint argc char argv mat image imreadpath to file mat gray cvtcolorimage gray color bgr2gray mat fin double thresh thresholdgray fin 160 255 thresh binary inv size impacts dilation mat kernel getstructuringelementmorph cross size2 4 mat dilated dilatefin dilated kernel point11 6 imwritetestbwpngdilated mat hierarchy vectorvectorpoint contours findcontoursdilated contours hierarchy cv retr tree cv chain approx none potentially sort by x for const auto c contours x y columns 850 x 5400 rect r boundingrectc if rheight 30 rwidth 875 continue if rheight 100 rwidth 500 continue rectangleimage r scalar255 0 255 2 made thicker imwritetestpng image waitkey0 return 0 original image updated codeint mainint argc char argv mat image imreadpath to file mat gray cvtcolorimage gray color bgr2gray mat fin double thresh thresholdgray fin 160 255 thresh binary inv mat kernel getstructuringelementmorph cross size2 4 mat dilated dilatefin dilated kernel point11 6 vectorvec4i hierarchy vectorvectorpoint contours findcontoursdilated contours hierarchy cv retr tree cv chain approx none vectorrect rects rect big rect rectimagecols2imagerows211 for const auto c contours x y columns 850 x 5400 rect r boundingrectc if rheight 5500 rwidth 875 continue if rheight 300 rwidth 500 continue big rect big rect r here we will find bounding box of all rects rectspush back r stores rects for size t i 0 i rectssize i sets y and height of all rects cout rectsix endl rectsiy big recty rectsiheight big rectheight grouprectanglesrects 1 did not work for size t i 0 i rectssize i rectangleimage rectsi scalar255 0 255 2 imshowtest imagenew result new problem there are many boundingrects around each column you probably cannot tell by looking at the picture this is a problem because i want to make a subimage of each column eg mat roi imagerectsi which would render much more than the desired 7 images new question how can i combine the multitude of rectangles per column into one i have seen opencvs grouprectangles but it failed to work,['c++'] +1040831,android registering security provider i am trying to understand how java security providers work in android i would like to force all calls to ciphergetinstance to return a cipher with spongy castle as the provider i am having no luckthe following code returns a cipher with provider being androidkeystorebcworkaround version 10 but i want the provider to be spongycastlethe reason i want to do this is that i have a library that calls into javaxcryptociphergetinstance multiple times i want all those calls to go to spongy castle without having to rewrite the library to explicitly specify sc as the providerpublic class mainactivity extends activity static securityinsertprovideratnew orgspongycastlejceproviderbouncycastleprovider 1 securityremoveproviderbc override protected void oncreatebundle savedinstancestate try this returns provider androidkeystorebcworkaround version 10 javaxcryptocipher cipher javaxcryptociphergetinstanceaesctrnopadding this works cipher javaxcryptociphergetinstanceaesctrnopadding sc catchexception e,"['java', 'android']" +1040889,android studio update broke my emulators i just did an update to android studio 20 and several components now whenever i try to run an emulator it gives an error sayingcpu acceleration status haxm must be updated version 114 601i have checked haxm is updated to 601 i have restarted rebuilt an emulator from scratch and none of that helps,['android'] +1040961,use storyboard to mask uiview and give rounded corners lots of questions like this explain how to programmatically create a mask and provide rounded corners to a uiviewis there a way to do it all within storyboard just asking because it seems like creating rounded corners in storyboard keeps a clearer demarcation between presentation and logic,['ios'] +1041062,tsql calculate duration in months between different years of ranges i have a table in sql server which contains the duration of a user working for different jobs i need to calculate the total number of experience for userdeclare temp tableid int fromdate datetime todate datetimeinsert into temp id fromdate todate values 1 2003108 0656 2005508 0656 2 201008 0656 2008708 0656 3 2013608 0656 2015108 0656 4 2006408 0656 2011308 0656 select from temp i want to calculate the total number of experienceid fromdate todate difference in months1 20030108 20050508 282 201008 20080708 933 20130608 20150108 194 20060408 20110308 59after removing the years overlapping like 20032005 covers up in 202008i got something like thisid fromdate todate difference in months 1 201008 20110308 1252 20130608 20150108 19so the answer would be 12519 144 monthsplease help me to find a solution,['sql'] +1041200,compress output tiff with g4 compression how to write a file as tiff with g4 compressionimwritestringcompressedtif resupdateimage processingthis is the processing of the image data before the data is sent to write fax so further processing should not be necessary have commented out the processing in write fax but the output file is completely blackresconverttores cv 32fc1 10 2550res 10 resres img resthresholdres res 085 1 thresh binary sends data to write faxcomplete code compile g txtbincpp o txtbin ltiff pkgconfig opencv cflags libs run txtbin inputjpg outputpng include stringinclude fstreaminclude usrincludeopencv2opencvhppinclude usrincludeboosttupletuplehppinclude usrincludex86 64linuxgnutiffhinclude usrincludex86 64linuxgnutiffiohinclude stdinthinclude vectorinclude stdexceptinclude cstdioinclude cassertusing namespace stdusing namespace cvusing namespace boostvoid calcblockmeanvariancemat img mat res float blockside21 float contrast001 blockside set greater for larger fonts in image contrast set smaller for lower contrast image mat i imgconverttoi cv 32fc1 res matzerosimgrows blockside imgcols blockside cv 32fc1 mat inpaintmask mat patch mat smallimg scalar m s forint i 0 i imgrows blockside i blockside forint j 0 j imgcols blockside j blockside patch irangei i blockside 1 rangej j blockside 1 meanstddevpatch m s ifs0 contrast resatfloati blockside j blockside m0 else resatfloati blockside j blockside 0 resizei smallimg ressize thresholdres inpaintmask 002 10 thresh binary mat inpainted smallimgconverttosmallimg cv 8uc1 255 inpaintmaskconverttoinpaintmask cv 8uc1 inpaintsmallimg inpaintmask inpainted 5 inpaint telea resizeinpainted res imgsize resconverttores cv 32fc1 10 2550tupleint int int int detect text boxstring input mat res bool draw contoursfalse mat large imreadinput bool test output false int top largerows bottom 0 left largecols right 0 int rect bottom rect right mat rgb downsample and use it for processing pyrdownlarge rgb mat small cvtcolorrgb small cv bgr2gray morphological gradient mat grad mat morphkernel getstructuringelementmorph ellipse size3 3 morphologyexsmall grad morph gradient morphkernel binarize mat bw thresholdgrad bw 00 2550 thresh binary thresh otsu connect horizontally oriented regions mat connected morphkernel getstructuringelementmorph rect size9 1 morphologyexbw connected morph close morphkernel find contours mat mask matzerosbwsize cv 8uc1 vectorvectorpoint contours vectorvec4i hierarchy findcontoursconnected contours hierarchy cv retr ccomp cv chain approx simple point0 0 filter contours forint idx 0 idx 0 idx hierarchyidx0 rect rect boundingrectcontoursidx mat maskroimask rect maskroi scalar0 0 0 fill the contour drawcontoursmask contours idx scalar255 255 255 cv filled ratio of nonzero pixels in the filled region double r doublecountnonzeromaskroi rectwidth rectheight assume at least 45 of the area is filled if it contains text if r 045 rectheight 8 rectwidth 8 constraints on region size these two conditions alone are not very robust better to use something like the number of significant peaks in a horizontal projection as a third condition ifdraw contours rectangleres rectrectx 2 recty 2 rectwidth 2 rectheight 2 scalar0 255 0 2 iftest output rectanglergb rect scalar0 255 0 2 ifrecty top top recty rect bottom recty rectheight ifrect bottom bottom bottom rect bottom ifrectx left left rectx rect right rectx rectwidth ifrect right right right rect right ifdraw contours rectangleres pointleft 2 top 2 pointright 2 bottom 2 scalar0 0 255 2 iftest output rectanglergb pointleft top pointright bottom scalar0 0 255 2 imwritestringtest text contoursjpg rgb return make tupleleft 2 top 2 right left 2 bottom top 2 just tiny exception generatorvoid exceptbool condition const stdstring message if condition throw stdruntime errorerror messagebool write fax const stdstring name const cvmat src uint8 t threshold 150 cvmat image if srcchannels 3 cvcvtcolorsrc image cv bgr2gray else if srcchannels 4 cvcvtcolorsrc image cv bgra2gray else srccopytoimage assertimagedepth cv 8u working only with 8bit images now int width imagecols int height imagerows do not put wb as the mode because the b means big endian mode not binary mode tiff ptiffhandle tiffopennamec str w if ptiffhandle printfcannot open tiff descriptorn return false try excepttiffsetfieldptiffhandle tifftag imagewidth width width excepttiffsetfieldptiffhandle tifftag imagelength height length excepttiffsetfieldptiffhandle tifftag bitspersample 1 bits per sample excepttiffsetfieldptiffhandle tifftag samplesperpixel 1 samples per pixel excepttiffsetfieldptiffhandle tifftag rowsperstrip 1 rows per strip excepttiffsetfieldptiffhandle tifftag compression compression ccittfax4 compression excepttiffsetfieldptiffhandle tifftag photometric photometric miniswhite photometric excepttiffsetfieldptiffhandle tifftag fillorder fillorder msb2lsb photometric excepttiffsetfieldptiffhandle tifftag planarconfig planarconfig contig planar config excepttiffsetfieldptiffhandle tifftag predictor predictor predictor excepttiffsetfieldptiffhandle tifftag stripoffsets strip offsets strip offsets not necessary excepttiffsetfieldptiffhandle tifftag xresolution 20 res x excepttiffsetfieldptiffhandle tifftag yresolution 20 res y excepttiffsetfieldptiffhandle tifftag resolutionunit resunit inch res unit stdvectoruchar bufferwidth 8 8 0 uchar buffer buffer0 int bytes intwidth 80 05 for int y 0 y height y uint8 t src row imageptry for int x 0 x width x src row uint8 t eight pixels bufferx 8 eight pixels eight pixels 1 if src row threshold eight pixels eight pixels 1 bufferx 8 eight pixels for the some reason writeencodedstrip does not work excepttiffwriteencodedstripptiffhandle y buffer bytes 1 write scanline excepttiffwritescanlineptiffhandle buffer y bytes 1 write scanline catch const stdruntime error e printftiff writing sn ewhat tiffcloseptiffhandle return false tiffcloseptiffhandle return trueint mainint argc char argv string input string output outputpng int width 0 height 0 bool crop false draw false float margin 0 return error if arguments are missing ifargc 3 cerr nusage txtbin input options outputnn optionsn tw number set max width keeps aspect ration th number set max height keeps aspect ration tc crop text content contourn tm number add margins number in n td draw text content contours debuggingn endl return 1 parse arguments forint i 1 i argc i ifi 1 input stringargvi return error if input file is invalid ifstream streaminputc str ifstreamgood cerr error input file is invalid endl return 1 else ifstringargvi w width atoiargvi else ifstringargvi h height atoiargvi else ifstringargvi c crop true else ifstringargvi m margin atoiargvi else ifstringargvi d draw true else ifi argc 1 output stringargvi mat img imreadinput cv load image grayscale mat res imgconverttoimg cv 32fc1 10 2550 calcblockmeanvarianceimg res res 10 res res img res thresholdres res 085 1 thresh binary int txt x txt y txt width txt height ifcrop draw tietxt x txt y txt width txt height detect text boxinput res draw ifcrop res resrecttxt x txt y txt width txt height ifmargin int border rescols margin 100 copymakeborderres res border border border border border constant scalar255 255 255 float width input rescols height input resrows bool resized false downscale image ifwidth 0 width input width float scale width input width width input scale height input scale resized true ifheight 0 height input height float scale height input height width input scale height input scale resized true ifresized resizeres res sizeroundwidth input roundheight input imwriteoutput res 255 write faxoutputtif res 255 return 0,['c++'] +1041447,choosing from different cost function and activation function of a neural network recently i started toying with neural network i was trying to implement an andgate with tensorflow i am having trouble understanding when to use different cost and activation functions this is a basic neural network only no hidden layers only an input layer and an output layerfirst i tried to implement it in this way as you can see this is a poor implementation but i think it gets the job done at least in some way so i tried only the real outputs no one hot true outputs for activation functions i used a sigmoid function and for cost function i used squared error cost functioni think its called that correct me if i am wrong i have tried using relu softmax as activation functionwith same cost function it doesnt work i figured out why they do not work i also tried the sigmoid function with cross entropy cost function it does not work as wellimport tensorflow as tfimport numpytrain x numpyasarray011011train y numpyasarray01x tfplaceholderfloatnone 2y tfplaceholderfloatnone 1w tfvariabletfzeros2 1b tfvariabletfzeros1 1activation tfnnsigmoidtfmatmulx wbcost tfreduce sumtfsquareactivation y4optimizer tftraingradientdescentoptimizer1minimizecostinit tfinitialize all variableswith tfsession as sess sessruninit for i in range50 train data sessrunoptimizer feed dictx train x y train y result sessrunactivation feed dictxtrain x printresultafter 50 iteration 031316 012012422 012012422 0855765question 1 is there any other activation function and cost function that can worklearn for the above network without changing the parametersmeaning without changing w x b question 2 i read from a stackoverflow post here that the selection of activation function depends on the problem so there are no cost function that can be used anywhere i mean there is no standard cost function that can be used on any neural network right please correct me on thisi also implemented the and gate with a different approach with the output as onehot true as you can see the train y 10 means that the 0th index is 1 so the answer is 0 i hope you get it here i have used a softmax activation function with cross entropy as cost function sigmoid function as activation function fails miserably import tensorflow as tfimport numpytrain x numpyasarray011011train y numpyasarray10101001x tfplaceholderfloatnone 2y tfplaceholderfloatnone 2w tfvariabletfzeros2 2b tfvariabletfzeros2activation tfnnsoftmaxtfmatmulx wbcost tfreduce sumytflogactivationoptimizer tftraingradientdescentoptimizer05minimizecostinit tfinitialize all variableswith tfsession as sess sessruninit for i in range50 train data sessrunoptimizer feed dictx train x y train y result sessrunactivation feed dictxtrain x printresultafter 50 iteration 10e00 141971401e09 998996437e01 100352429e03 998996437e01 100352429e03 140495342e03 998595059e01question 3 so in this case what cost function and activation function can i use and how do i understand what type of cost and activation functions to use is there a standard way or rule or just experience only or i have to try every cost and activation function in a brute force manner i found an answer here but i am hoping for a more elaborate explanation question 4 i have noticed that it takes a lot of iteration to converge to a near correct prediction i think the converge rate depends on the learning rateusing too much will miss the solution and the cost functioncorrect me if i am wrong so is there any optimal waymeaning the fastest or cost function for converging to a correct solution,['python'] +1041519,passing an array in the sample code below why does the call to arraymethod fail for a genric type when i do not include the class constraintpublic interface ifoo public interface ibar ifoo public class test public void classconstrainttestt where t class ifoo t variable new t0 arraymethodvariable public void generictestt where t ifoo t variable new t0 arraymethodvariable compilation error cannot convert t to ifoo public void inheritancetest ibar variable new ibar0 arraymethodvariable public void arraymethodifoo args,['c#'] +1041542,the ad size and ad unit id must be set before loadad when set programmatically i have no idea what is going on here but i am trying to set my ad unit id dynamically through code like below and removing it from the xml but still get the error the ad size and ad unit id must be set before loadad is calledrelativelayout xmlnsandroid xmlnsads comgoogleandroidgmsadsadview androidididadview androidlayout widthwrap content androidlayout heightwrap content androidlayout centerhorizontaltrue androidlayout alignparentbottomtrue adsadsizesmart banner comgoogleandroidgmsadsadview adview madview adview rootviewfindviewbyidridadview madviewsetadunitidgeteventgetadmobunitid adrequest adrequest new adrequestbuilderbuild madviewloadadadrequest,"['java', 'android']" +1041698,aspnet webapi 2 nested json i have been stuck with this for a while and i cannot seem to figure it out appreciate any helpthis is my model i have the proper c objects set up like thispublic class media public string name get set public string title get set public string album get set public string artist get set public string length get set public int bitrate get set public double size get set public string start time get set public string mimetype get set public string hash get set public class playlist public string name get set public listmedia media get set public listgraphics graphics get set public bool shuffle get set public int volume get set public string start time get set public string end time get set public class day public string name get set public listplaylist playlists get set public class schedule public listday days get set public string hash get set i need to post this whole json object directly from the mvc controller on other occasions i would like to put the schedule how can i properly handle this examples could really helpthanksi am already doing the below for postvar schedule jsonconvertdeserializeobjectschedulemodeltostringthis is working as expected however sometimes related media objects already exist in the database and it is causing an internal server error when trying to insert the same media object which already exists the key for media is the hash property,"['c#', 'asp.net']" +1041750,jquery plugin croppie to crop image error i want to use jquery croppie plugin on my site to crop image for my user but i have got this problem the code that i write not show as an example in croppie siteheres my codehtml codeinput typefile idupload valuechoose a filebutton classuploadresultresultbuttondiv classuploadmsg upload a file to start croppingdivdiv iduploaddemodivjs codeuploadcrop uploaddemocroppie viewport width 200 height 200 type circle boundary width 300 height 300 nb i have link my site with jquery croppiejs and croppiecss,"['javascript', 'jquery', 'html']" +1041797,google play store campaign tracking doesnt work with web browser install we have a play store button on our landing page which has a link tagged with all the required utm parameters to track installs from the play store so if a visitor clicks on the play store button using a web browser goes to the web version of the play store and installs to his device from there we should be able to track that install as coming from the web version of our landing pagehowever our data looks sketchy tracking less installs than we actually see on mixpaneland then we found this article it says again attributing installs based on the install referrer using direct links to google play does not work if a user chooses to open the measurement url with a web browser instead of the google play store appanybody knows if this is correct and if yes whats a comprehensive way to track play store installs source medium etc,['android'] +1041799,springsecurity shows bad credentials even before submitting the form i have following code for spring security but it does not work when i open login page and enter usernamepassword which is secret following error message will be shown once usernamepassword are entered following with be added to the address error1 even if i remove it manually and refresh the page message does not go nothing is shown in consoleyour login attempt was not successful due tobad credentialsspringsecurityxmlbeansbeans xmlns xmlnsbeans xmlnsxsi xsischemalocation beansimport resourceloginservicexml http autoconfigtrue accessdeniedpagenotfoundjsp useexpressionstrue intercepturl pattern accesspermitall intercepturl patternmember accesshasrolerole member formlogin loginpagesignin defaulttargeturlindex authenticationfailureurlsigninerror1 logout logoutsuccessurlloginlogout csrf http authenticationmanager authenticationprovider userservice user name passwordsecret authoritiesrole admin user name passwordsecret authoritiesrole user userservice authenticationprovider authenticationmanagerbeansbeansthe form has following code it seems like spring security last exceptionis not empty even before submitting the formcif testnot empty spring security last exception font colorred your login attempt was not successful due to br br cout valuespring security last exceptionmessage font cif form idformlogin roleform methodpost actioncurl valuej spring security check classrelative form formdefault input typehidden name csrfparametername value csrftoken i am not sure why but the same code returns following error nowyour login attempt was not successful due toauthentication method not supported get,['java'] +1041827,iad banner not working on ios 9 i am getting didfailtoreceiveadwitherror message in the console while running on the simulator and deviceiad banners are thisplayed successfully when running on ios 8 when running on ios 9 iad banners fail to receive an adhimport iadiadhinterface viewcontroller uiviewcontroller adbannerviewdelegateproperty retain nonatomic iboutlet adbannerview adbannerm voidviewdidload selfadbanner adbannerview allocinitwithframecgrectmake0uiscreen mainscreenboundssizeheight100 uiscreen mainscreenboundssizewidth 50 selfadbannerdelegateself selfadbanner setbackgroundcoloruicolor clearcolor selfview addsubviewselfadbanner voidbannerviewwiloadadadbannerview banner nslogbannerviewwiloadadvoidbannerviewdidloadadadbannerview banner show the ad banner nslogbannerviewdidloadad uiview animatewithduration05 animations selfadbanneralpha 10 voidbannerviewadbannerview banner didfailtoreceiveadwitherrornserror error nslogdidfailtoreceiveadwitherror hide the ad banner uiview animatewithduration05 animations selfadbanneralpha 00 voidbannerviewactiondidfinishadbannerview banner nslogad did finishwhen running on ios 9 the console prints didfailtoreceiveadwitherror every time,"['ios', 'objective-c']" +1041830,unable to create debug bridge unable to detect adb version syntax error upgrading platformtools 2301 to 2310 linux32 bit causes issue i updated platformtools from 2301 to 2310 and found some of the android integration broke i am running ubuntu 1404 32bit with androidsdk r2441 with both androidstudio 1412456560 installed while executing adb command it keeps on saying below message unable to create debug bridge unable to start adb server unable to detect adb version adb output homebhaveshandroidsdklinuxplatformtoolsadb 1 homebhaveshandroidsdklinuxplatformtoolsadb syntax error unexpectedany help would be appreciatedthanks,['android'] +1042010,android loopj image upload broken with wp api v1 v2 i am using loopj to upload files into my wordpress site and wp rest api v1 andor v2 same resultsthe authentications goes great headers goes great file uploads but when i check it in my wordpress backend the image or file is brokenthe android part goes like thisfile myfile new filefinalpathstring name utilsgetlastbitfromurlfinalpathstring extension utilsgetfileextentionfinalpathclientsetbasicauthmyusername mypassword new authscopemywebsitecom 80 authscopeany realm clientaddheadercontentthisposition filename name clientaddheadercontenttype image extension try paramsputdata myfile catch filenotfoundexception e eprintstacktrace or for v2 clientpost params new asynchttpresponsehandler int count 0 override public void onstart prgdialog new progressdialogmainactivitythis prgdialogsetmessageuploading image prgdialogsetprogrestyleprogressdialogstyle horizontal prgdialogsetmax100 prgdialogshow override public void onprogresslong byteswritten long totalsize ifcount 1 count logdsize utilsformatfilesizetotalsize long progresspercentage long100byteswrittentotalsize ifprogresspercentage 100 prgdialogsetprogressint progresspercentage override public void onsuccessint statuscode header headers byte response try prgdialogthismiss jsonobject obj new jsonobjectutilsdecodeutf8response logesuccess utilsdecodeutf8response catch jsonexception e eprintstacktrace but the image looks like this in my wordpress backenddoes anyone have any idea why this happen my file and file path are perfect i can get the image and show it on my phone before upload itedit this curl works perfectcurl i x post h contentthispositionfilenametestpng databinary homemynamedownloadsexamplepng d titletest u usernamepassword h expect the main difference is over databinary but i do not know how to do that over java,['android'] +1042269,node js login not working i have used express on top of node with hbs templating i am using passport to validate the particular user the database i have used in mongodbheres my signup routevar express requireexpressvar router expressroutervar passport requirepassportvar userservices requireservicesuserservicesrouterget functionreq res next var vm title join this web resrendersignup vmrouterpost functionreq res next userservicesadduserreqbody functionerr iferr var vm title create an account input reqbody error err delete vminputpassword return resrendersignup vm reqloginreqbody functionerr resredirectprofile routerpostlogin passportauthenticatelocal functionreq res next resredirectprofilemoduleexports routerhere is my login routevar express requireexpressvar router expressrouterrouterget functionreq res next if requser return resredirectprofile resrenderlogin title login moduleexports routeri have defined the configuration of of my passport in my passportcongig filemoduleexportsfunction var passport requirepassport var passportlocal requirepassportlocal var userservices requireservicesuserservices passportusenew passportlocalstrategyusernamefield email functionemail password next userservicesfinduseremail functionerr user iferr return nexterr ifuseruserpasswordpassword return nextnull null nextnull user passportserializeuserfunctionuser next nextnull useremail passportdeserializeuserfunctionuser next userservicesfinduseremail functionerr user nexterr user also here is my appjs with passport related codevar passportconfig requireauthpassportconfigpassportconfigvar app expressappuseexpresession secrettrawel man saveuninitialized false resave falseappusepassportinitializeappusepassportsessionhere is the stack trace of the error that i am receivingerror not foundat cusersjamesmeanappjs5615at layerhandle as handle request cusersjamesmeannode modulesexpresslibrouterlayerjs825at trim prefix cusersjamesmeannode modulesexpresslibrouterindexjs30213at cusersjamesmeannode modulesexpresslibrouterindexjs2707at functionprotoprocess params cusersjamesmeannode modulesexpresslibrouterindexjs32112at next cusersjamesmeannode modulesexpresslibrouterindexjs26110at cusersjamesmeannode modulesexpresslibrouterindexjs60315at next cusersjamesmeannode modulesexpresslibrouterindexjs24614at functionprotohandle cusersjamesmeannode modulesexpresslibrouterindexjs1663at router cusersjamesmeannode modulesexpresslibrouterindexjs3512at layerhandle as handle request cusersjamesmeannode modulesexpresslibrouterlayerjs825at trim prefix cusersjamesmeannode modulesexpresslibrouterindexjs30213at cusersjamesmeannode modulesexpresslibrouterindexjs2707at functionprotoprocess params cusersjamesmeannode modulesexpresslibrouterindexjs32112at next cusersjamesmeannode modulesexpresslibrouterindexjs26110at cusersjamesmeannode modulesexpresslibrouterindexjs60315this is what i got at my server consolepost login 404 32453 ms 2847i have no idea why this is not working i am new to node someone help me out,['javascript'] +1042484,css horizontal line animation gradient colors i have colored animated vertical line like this onekeyframes colored 0 backgroundimage webkitlineargradientleft c4e17f c4e17f 125 f7fdca 125 f7fdca 25 fecf71 25 fecf71 375 f0776c 375 f0776c 50 db9dbe 50 db9dbe 625 c49cde 625 c49cde 75 669ae1 75 669ae1 875 62c2e4 875 62c2e4 backgroundimage mozlineargradientleft c4e17f c4e17f 125 f7fdca 125 f7fdca 25 fecf71 25 fecf71 375 f0776c 375 f0776c 50 db9dbe 50 db9dbe 625 c49cde 625 c49cde 75 669ae1 75 669ae1 875 62c2e4 875 62c2e4 backgroundimage olineargradientleft c4e17f c4e17f 125 f7fdca 125 f7fdca 25 fecf71 25 fecf71 375 f0776c 375 f0776c 50 db9dbe 50 db9dbe 625 c49cde 625 c49cde 75 669ae1 75 669ae1 875 62c2e4 875 62c2e4 backgroundimage lineargradientto right c4e17f c4e17f 125 f7fdca 125 f7fdca 25 fecf71 25 fecf71 375 f0776c 375 f0776c 50 db9dbe 50 db9dbe 625 c49cde 625 c49cde 75 669ae1 75 669ae1 875 62c2e4 875 62c2e4 125 backgroundimage webkitlineargradientleft 62c2e4 62c2e4 125 c4e17f 125 c4e17f 25 f7fdca 25 f7fdca 375 fecf71 375 fecf71 50 f0776c 50 f0776c 625 db9dbe 625 db9dbe 75 c49cde 75 c49cde 875 669ae1 875 669ae1 backgroundimage mozlineargradientleft 62c2e4 62c2e4 125 c4e17f 125 c4e17f 25 f7fdca 25 f7fdca 375 fecf71 375 fecf71 50 f0776c 50 f0776c 625 db9dbe 625 db9dbe 75 c49cde 75 c49cde 875 669ae1 875 669ae1 backgroundimage olineargradientleft 62c2e4 62c2e4 125 c4e17f 125 c4e17f 25 f7fdca 25 f7fdca 375 fecf71 375 fecf71 50 f0776c 50 f0776c 625 db9dbe 625 db9dbe 75 c49cde 75 c49cde 875 669ae1 875 669ae1 backgroundimage lineargradientto right 62c2e4 62c2e4 125 c4e17f 125 c4e17f 25 f7fdca 25 f7fdca 375 fecf71 375 fecf71 50 f0776c 50 f0776c 625 db9dbe 625 db9dbe 75 c49cde 75 c49cde 875 669ae1 875 669ae1 25 backgroundimage webkitlineargradientleft 669ae1 669ae1 125 62c2e4 125 62c2e4 25 c4e17f 25 c4e17f 375 f7fdca 375 f7fdca 50 fecf71 50 fecf71 625 f0776c 625 f0776c 75 db9dbe 75 db9dbe 875 c49cde 875 c49cde backgroundimage mozlineargradientleft 669ae1 669ae1 125 62c2e4 125 62c2e4 25 c4e17f 25 c4e17f 375 f7fdca 375 f7fdca 50 fecf71 50 fecf71 625 f0776c 625 f0776c 75 db9dbe 75 db9dbe 875 c49cde 875 c49cde backgroundimage olineargradientleft 669ae1 669ae1 125 62c2e4 125 62c2e4 25 c4e17f 25 c4e17f 375 f7fdca 375 f7fdca 50 fecf71 50 fecf71 625 f0776c 625 f0776c 75 db9dbe 75 db9dbe 875 c49cde 875 c49cde backgroundimage lineargradientto right 669ae1 669ae1 125 62c2e4 125 62c2e4 25 c4e17f 25 c4e17f 375 f7fdca 375 f7fdca 50 fecf71 50 fecf71 625 f0776c 625 f0776c 75 db9dbe 75 db9dbe 875 c49cde 875 c49cde 375 backgroundimage webkitlineargradientleft c49cde c49cde 125 669ae1 125 669ae1 25 62c2e4 25 62c2e4 375 c4e17f 375 c4e17f 50 f7fdca 50 f7fdca 625 fecf71 625 fecf71 75 f0776c 75 f0776c 875 db9dbe 875 db9dbe backgroundimage mozlineargradientleft c49cde c49cde 125 669ae1 125 669ae1 25 62c2e4 25 62c2e4 375 c4e17f 375 c4e17f 50 f7fdca 50 f7fdca 625 fecf71 625 fecf71 75 f0776c 75 f0776c 875 db9dbe 875 db9dbe backgroundimage olineargradientleft c49cde c49cde 125 669ae1 125 669ae1 25 62c2e4 25 62c2e4 375 c4e17f 375 c4e17f 50 f7fdca 50 f7fdca 625 fecf71 625 fecf71 75 f0776c 75 f0776c 875 db9dbe 875 db9dbe backgroundimage lineargradientto right c49cde c49cde 125 669ae1 125 669ae1 25 62c2e4 25 62c2e4 375 c4e17f 375 c4e17f 50 f7fdca 50 f7fdca 625 fecf71 625 fecf71 75 f0776c 75 f0776c 875 db9dbe 875 db9dbe 50 backgroundimage webkitlineargradientleft db9dbe db9dbe 125 c49cde 125 c49cde 25 669ae1 25 669ae1 375 62c2e4 375 62c2e4 50 c4e17f 50 c4e17f 625 f7fdca 625 f7fdca 75 fecf71 75 fecf71 875 f0776c 875 f0776c backgroundimage mozlineargradientleft db9dbe db9dbe 125 c49cde 125 c49cde 25 669ae1 25 669ae1 375 62c2e4 375 62c2e4 50 c4e17f 50 c4e17f 625 f7fdca 625 f7fdca 75 fecf71 75 fecf71 875 f0776c 875 f0776c backgroundimage olineargradientleft db9dbe db9dbe 125 c49cde 125 c49cde 25 669ae1 25 669ae1 375 62c2e4 375 62c2e4 50 c4e17f 50 c4e17f 625 f7fdca 625 f7fdca 75 fecf71 75 fecf71 875 f0776c 875 f0776c backgroundimage lineargradientto right db9dbe db9dbe 125 c49cde 125 c49cde 25 669ae1 25 669ae1 375 62c2e4 375 62c2e4 50 c4e17f 50 c4e17f 625 f7fdca 625 f7fdca 75 fecf71 75 fecf71 875 f0776c 875 f0776c 625 backgroundimage webkitlineargradientleft f0776c f0776c 125 db9dbe 125 db9dbe 25 c49cde 25 c49cde 375 669ae1 375 669ae1 50 62c2e4 50 62c2e4 625 c4e17f 625 c4e17f 75 f7fdca 75 f7fdca 875 fecf71 875 fecf71 backgroundimage mozlineargradientleft f0776c f0776c 125 db9dbe 125 db9dbe 25 c49cde 25 c49cde 375 669ae1 375 669ae1 50 62c2e4 50 62c2e4 625 c4e17f 625 c4e17f 75 f7fdca 75 f7fdca 875 fecf71 875 fecf71 backgroundimage olineargradientleft f0776c f0776c 125 db9dbe 125 db9dbe 25 c49cde 25 c49cde 375 669ae1 375 669ae1 50 62c2e4 50 62c2e4 625 c4e17f 625 c4e17f 75 f7fdca 75 f7fdca 875 fecf71 875 fecf71 backgroundimage lineargradientto right f0776c f0776c 125 db9dbe 125 db9dbe 25 c49cde 25 c49cde 375 669ae1 375 669ae1 50 62c2e4 50 62c2e4 625 c4e17f 625 c4e17f 75 f7fdca 75 f7fdca 875 fecf71 875 fecf71 75 backgroundimage webkitlineargradientleft fecf71 fecf71 125 f0776c 125 f0776c 25 db9dbe 25 db9dbe 375 c49cde 375 c49cde 50 669ae1 50 669ae1 625 62c2e4 625 62c2e4 75 c4e17f 75 c4e17f 875 f7fdca 875 f7fdca backgroundimage mozlineargradientleft fecf71 fecf71 125 f0776c 125 f0776c 25 db9dbe 25 db9dbe 375 c49cde 375 c49cde 50 669ae1 50 669ae1 625 62c2e4 625 62c2e4 75 c4e17f 75 c4e17f 875 f7fdca 875 f7fdca backgroundimage olineargradientleft fecf71 fecf71 125 f0776c 125 f0776c 25 db9dbe 25 db9dbe 375 c49cde 375 c49cde 50 669ae1 50 669ae1 625 62c2e4 625 62c2e4 75 c4e17f 75 c4e17f 875 f7fdca 875 f7fdca backgroundimage lineargradientto right fecf71 fecf71 125 f0776c 125 f0776c 25 db9dbe 25 db9dbe 375 c49cde 375 c49cde 50 669ae1 50 669ae1 625 62c2e4 625 62c2e4 75 c4e17f 75 c4e17f 875 f7fdca 875 f7fdca 875 backgroundimage webkitlineargradientleft f7fdca f7fdca 125 fecf71 125 fecf71 25 f0776c 25 f0776c 375 db9dbe 375 db9dbe 50 c49cde 50 c49cde 625 669ae1 625 669ae1 75 62c2e4 75 62c2e4 875 c4e17f 875 c4e17f backgroundimage mozlineargradientleft f7fdca f7fdca 125 fecf71 125 fecf71 25 f0776c 25 f0776c 375 db9dbe 375 db9dbe 50 c49cde 50 c49cde 625 669ae1 625 669ae1 75 62c2e4 75 62c2e4 875 c4e17f 875 c4e17f backgroundimage olineargradientleft f7fdca f7fdca 125 fecf71 125 fecf71 25 f0776c 25 f0776c 375 db9dbe 375 db9dbe 50 c49cde 50 c49cde 625 669ae1 625 669ae1 75 62c2e4 75 62c2e4 875 c4e17f 875 c4e17f backgroundimage lineargradientto right f7fdca f7fdca 125 fecf71 125 fecf71 25 f0776c 25 f0776c 375 db9dbe 375 db9dbe 50 c49cde 50 c49cde 625 669ae1 625 669ae1 75 62c2e4 75 62c2e4 875 c4e17f 875 c4e17f 100 backgroundimage webkitlineargradientleft c4e17f c4e17f 125 f7fdca 125 f7fdca 25 fecf71 25 fecf71 375 f0776c 375 f0776c 50 db9dbe 50 db9dbe 625 c49cde 625 c49cde 75 669ae1 75 669ae1 875 62c2e4 875 62c2e4 backgroundimage mozlineargradientleft c4e17f c4e17f 125 f7fdca 125 f7fdca 25 fecf71 25 fecf71 375 f0776c 375 f0776c 50 db9dbe 50 db9dbe 625 c49cde 625 c49cde 75 669ae1 75 669ae1 875 62c2e4 875 62c2e4 backgroundimage olineargradientleft c4e17f c4e17f 125 f7fdca 125 f7fdca 25 fecf71 25 fecf71 375 f0776c 375 f0776c 50 db9dbe 50 db9dbe 625 c49cde 625 c49cde 75 669ae1 75 669ae1 875 62c2e4 875 62c2e4 backgroundimage lineargradientto right c4e17f c4e17f 125 f7fdca 125 f7fdca 25 fecf71 25 fecf71 375 f0776c 375 f0776c 50 db9dbe 50 db9dbe 625 c49cde 625 c49cde 75 669ae1 75 669ae1 875 62c2e4 875 62c2e4 colored margintop 5px marginbottom 5px height 7px bordertop 0 background c4e17f borderradius 5px backgroundimage webkitlineargradientleft c4e17f c4e17f 125 f7fdca 125 f7fdca 25 fecf71 25 fecf71 375 f0776c 375 f0776c 50 db9dbe 50 db9dbe 625 c49cde 625 c49cde 75 669ae1 75 669ae1 875 62c2e4 875 62c2e4 backgroundimage mozlineargradientleft c4e17f c4e17f 125 f7fdca 125 f7fdca 25 fecf71 25 fecf71 375 f0776c 375 f0776c 50 db9dbe 50 db9dbe 625 c49cde 625 c49cde 75 669ae1 75 669ae1 875 62c2e4 875 62c2e4 backgroundimage olineargradientleft c4e17f c4e17f 125 f7fdca 125 f7fdca 25 fecf71 25 fecf71 375 f0776c 375 f0776c 50 db9dbe 50 db9dbe 625 c49cde 625 c49cde 75 669ae1 75 669ae1 875 62c2e4 875 62c2e4 backgroundimage lineargradientto right c4e17f c4e17f 125 f7fdca 125 f7fdca 25 fecf71 25 fecf71 375 f0776c 375 f0776c 50 db9dbe 50 db9dbe 625 c49cde 625 c49cde 75 669ae1 75 669ae1 875 62c2e4 875 62c2e4 animationname colored animationduration 2s animationiterationcount infinitehr classcoloredi am wondering if it can be accomplished in some better read smarter way it cost me some time to calculate and prepare all animation steps was using excell and i feel stupidsecond question based on one of the comments is if this animation can be smoother how to accomplish it,"['html', 'css']" +1042517,how to thisplay different values without refreshing the page mvc c i have a method that is looping through a list of values what i would like to do is when i open the page to be able to see the values changing without refreshing the current view i have tried something like the code bellowpublic static int myvaluereader get set public static void valuegenerator foreach var item in mylist myvalue item threadsleep10 the actual thing is i want it to read this values even if i close the form i presume i would need to assign a task in order to do this but i was wandering if there is any better way of doing it since it is a mvc application,['c#'] +1042532,nest thermostat temperature not getting updated i am trying to change the temperature of my nest programmatically android without any luck requests work maybe 1 in 3050 tries i have tried doing it through the firebase nest sdk and the nestapicompletionlistener does not get called at all seeing how that does not work i tried it with the rest api where it worked twice and then again 1 in 30 tries i also tried it with curl from the command line with the same results until i finally got blocked because of the rate limiting before being blocked requests were returning the full thermostat object just like doing a get request instead of put when the temperature actually did get updated the response contained just the new target temperature high c and target temperature high c valueshas anyone else seen similar behavior edit added some code belowheres my code using the nest android api based on firebasenestapicompletionlistener completionlistener new nestapicompletionlistener public void oncomplete debugdnest request complete public void onerrorint errorcode debugenest error errorcode nestapigetinstancesettargettemperaturehighcmynestgetdeviceid 25 completionlistenerthis only works if i make that call once an hour if i even try to do it twice the second try does not worknext i tried with the rest interface this seems work more often worked 56 times after which it the api started acting like i was doing get requests instead of putjsonobject datatosend new jsonobjectdatatosendputtarget temperature low c 23datatosendputtarget temperature high c 26httpput httpost new httpputmynestgetdeviceidauthmyauthtokenhttpostsetheadercontenttype applicationjsonhttpostsetentitynew stringentitydatatosendtostringhttpresponse response defaulthttpclientexecutehttposthttpentity entity responsegetentitystring response convertstreamtostringentitygetcontentedit 2 just tested this with the nest home simulator and it works perfectly fine the real hardware is problematic though,['android'] +1042555,how to synchronize sqlite and mysql databases using push notifications i have an sqlite database on android and a mysql database on a server i want to synchronize these databases when a user edits data on their phone or edits data on a website i know how to update the mysql database on the server when a user makes changes on their phone but i do not know how to update the android database when a user makes changes on the websitei have read into push notification and believe this to be a good path to follow but i have a few questions about itwhen a user updates data through a website it will send a push notification to that users phone saying changes have been made can this push notification trigger to update the androids database with the new changes made on the server databasewhat if a user turns off push notifications will i still be able to trigger for their android database to be updatedi have also read up on sqlite and mysql database synchronization and found this post sqlite and mysql sync but did not find the post helpful for my situation are push notifications a good way to go or should i be using a different approach in a nutshell i want a way for the android device to detect changes on the mysql database and update its sqlite database without the user initiating the synchronization,"['android', 'mysql']" +1042598,uploading multiple images with volley i have gone through a lot of post in so and other tuts as wellbut i could not get any latest official or other post that does not contain any deprecated code for uploading multiple images using volleyi came to know apache http client removal and related in new android m and preferred to use below insteadandroid uselibrary orgapachehttplegacy so can any one help me out for doing multiple image upload with new updated deprecated less volley class,"['java', 'android']" +1042599,error when building a large codename one application during the dex phase i got an error in the build server when sending an android build during the dex phasegoogling a bit i learned that there is a hard limit of 64k functions including all libs the heaviest is google play services or you can use the multiple dex mechanismhow do i activate this for codename one i understand codename one uses ant and as far as i understand this only works for gradle fyi this is the workaround that splits google play services into sub libraries with native android,['android'] +1042601,mvc 5 bypass forms authentication for windows authenticated users i already have a website written using mvc 5 and it uses form authentication using sql servernow is it possible that i can bypass forms authentication for users that are already on office network also i want to keep track of user and apply rules similar to forms authentication thanks,"['c#', 'asp.net']" +1042645,adding lambda functions with the same operator in python i have a rather lengthy equation that i need to integrate over using scipyintegratequad and was wondering if there is a way to add lambda functions to each other what i have in mind is something like thisy lambda u u2 8x lambda u numpyexpuf y xint scipyintegratequadf 0 numpyinfthe equations that i am really using are far more complicated than i am hinting at here so for readability it would be useful to break up the equation into smaller more manageable partsis there a way to do with with lambda functions or perhaps another way which does not even require lambda functions but will give the same output,['python'] +1042734,selectoratorjs selector of all hidden elements on page i am implementing heatmap to thisplay all users click on my page using heatmapsjs by patrick wied heatmap is loaded from collection of datapoints for each element but it takes too long to loadissue desceach datapoint has xy coordinates and selector retrieved using selectoratorjs of html element on pagecurrently i am getting about 5k points for each page and i need to check if some elements are not hidden so we would not show heatmap for hidden elementscurrently i am usingelement datapointsielementelementishiddenbut this takes about 7 seconds to check all those points which is quite long i have run out of ideas how to avoidoptimize this issuedatapoint detailelement pagedata tbody treq3 tdeq4 aeq0 y06546159 x04231pseudo script flow descforeachpoint in alldatapoints calculation of some parameters needed to show on heamapat if pointelementishidden continue pointstothisplaypushpointi have also tried to get selectors of all hidden elements but getselector in selectoratorjs and then just go through that array but it takes almost same time as ishidden functioni hope this makes sensefact getting selector of an element might take a little time but reverse processgetting and element based on selector takes almost no time so i can not simply send array of selectors of hidden elements and filter those which would be a lot faster,"['javascript', 'jquery', 'html']" +1042841,most efficient way to find neighbors in list i have a list of length 2016 but only 242 contain data the rest is set to none my aim is to interpolate between the values to fill all gaps with a simple form of idw inverse thistance weightingso the task of my script is iterate over all items of mylistif the mylist contains a value that is not none just copy itif you find a none in mylist get positionvalue of the left and right neighbor by calculating the thistance to all items in mylistcalculate an interpolated value for the gap from both neighbors the farer they are away the less weight they shall getassume we have a smaller list of only 14 items 5 valid onesmylist 26 none none none 31 none none 58 none 42 none none none 79resultlist none lenmylistfor i in rangelenmylist if not mylisti is none resultlisti mylisti else thistance i j for j in rangelenmylist if not mylistj is none neighbors minn for and in thist if n0 maxn for and in thist if n0 rest of the interpolation not important for my question neighbors c 1floatn2 for and in neighbors c sum sumneighbors c neighbors c nc sum for and in neighbors c resultlist mylistineighbors0neighbors c0 mylistineighbors1neighbors c1i am doing that for many many data sets i found out that this method takes about 059sec per data set what bothers me is the fact that my list is all sorted but i will only need 2 values from it so 99 of the thistances are calculated for nothing that led me to attempt two stop the iteration after ij becomes negative because then obviously it ran into the closest valuesso instead of the list comprehensionthistance i j for j in rangelenmylist if not mylistj is nonei do a proper forloop which i quit after thistances pass zero and thus become larger againthist for j in rangelenmylist if not mylistj is none thistappendij if ij 0 breakwith this method i was able to get down to 038sec per data set when iterating over all items in mylist this second method is quick at the beginning item is hit after 2nd 3rd 4th loop and quit immediately but there is no improvement for the last items since iteration always starts at j0i wonder if you can think of any quicker way to find the two neighbors of a specific number in a data set without having to check all thistances and only taking the largest negative and smalles positive onealso i am quite new to python so please let me know if you find other unpythonic expressions in my script thank you guys very much,['python'] +1042873,why are these two strings not equal i was thinking about guids recently which led me to try this codeguid guid guidnewguidconsolewritelineguidtostring prints 6d1dc8c8cd8345b2915fc759134b93aaconsolewritelinebitconvertertostringguidtobytearray prints c8c81d6d83cdb245915fc759134b93aabool sameguidtostringbitconvertertostringguidtobytearray falseconsolewritelinesameyou can see that all of the bytes are there but half of them are in the wrong order when i use bitconvertertostring why is this,['c#'] +1042897,can a void pointer point to a lambda function assigning a function pointer to a void pointerdouble f dummydouble x return x void pv f dummy compilation erroris illegal as explained in this faq the answer however closes with the statement please do not email me if the above seems to work on your particular version of your particular compiler on your particular operating system i donat care itas illegal periodedit as a warning to others i did encounter this seems to work behavior through a case of inheritance involving class templates no compiler warning no unexpected runtime behaviorthis tickles my ocd bone and makes me wonder if what i have been doing eg auto l func double x return f dummyx void pv l func auto pl static castdecltypel funcpv cout pl5 endl which compiles and runs cleanly g stdc11 wall is truly legal is it,['c++'] +1042960,performance or php i am working on a big project in php and i need to make sure it is all fast so i am wondering what is faster to use or eg sessionexample or sessionexample,['php'] +1042994,timer in uwp app which is not linked to the ui i am working on an uwp mvvm project and would like to implement an automatic logout system if the user interaction stops for a specific timeuntil now i am using a thispatchertimer to count backwards from 200 every second timerleave 200var thispatchertimer new thispatchertimer thispatchertimertick thispatchertimer tick thispatchertimerinterval new timespan0 0 1 thispatchertimerstartbut because the thispatchertimer is linkedwith the ui and i am building a mvvm app i am looking for an alternativei searched a bit and found run a background task on a timer the problem isthat this timer can only be set to run every 15 minutes which is a little too long to automaticly logout a user in my case i found no workaround to reduce the 15 minutesso my question is is there any possibility to set up a timer in an uwp project that is not linked to the ui and can be set variable,['c#'] +1043191,why two bindings to the same function return different values when binding a function to the same context the resulting reference is different every timefunction foobar return 1var foo foobarbindthisvar bar foobarbindthisconsolelogfoo bar nopedoes that code copy the function every timewouldnt there be any benefit in caching that behavioris it implementation specificor is it specified somewhere in ecmascript specification,['javascript'] +1043256,choose luminosity exposure from hdr image i am currently stuck on a video projet from picturesproblem i am extracting pictures from ue4 due to a bug not all lights are taken into account during the rendering of the screenshotoutput are hdr images i want to get better brighteness because the exported picture are very dark like the first exposureusing the exposure bias parameter in ue4 i am able to real good luminosity of my scene but cannot apply this parameter to the screenshot rendering tries using tonemapper algorithm speciafically cvtonemapdrago i am able to get better image result the main problem for my case of the tonemap algorithm is because the global luminosity is changed depending of luminosity of areas in the second image the window add lots of light so the algorithm low all the luminosity to adjust the meanin the video rendered the light change is very brutali have tried to change brightness and saturation without successi have modified the code of the tonemapdrago trying to use constants for some steps of the algorithmquestion i would like to choose the exposure time from an hdr image tonemap is based on several exposure time of the same image not interesting in my case any other idea is welcomeeditcvmat depth is 5 type is cv 32fc3cout matstep give me 19200here are 2 samples i use to try solving my problem first imageimage with light windowedit 2 cannot open hdr picture with gimp event with the explosure blend plugini am able to get great enough result using photoshop any idea of the algorithm behind that any of the 6 tonemap algos by opencv allow to choose an exposure correctionedit 3i have followed the algorithm explain in this tuto for opengl which is giving this c code to me cvmat exposuretonemap cvmat m float gamma 22 float exposure 1 exposure tone mapping cvmat exp cvexp m exposure exp cvmat mapped cvvec3f10 exp gamma correction cvpowexp 10f gamma exp cvimshowexposure tonemap exp cvwaitkey return expapplying this algo on my hdr picture i got very bright result even with a correction of 1 and 1 for gamma and exposure reading the code there is something wrong because 1 and 1 as argument should not modify the picturefixed that the answer is posted thanks a lot to user3896254 ge saw it too in comment,['c++'] +1043497,how can i run multiple andy machines i read that i can run multiple andy machines in the following link but i cannot open andy launcheri tried to double click handyandys icon in the task bar but it does not work,['android'] +1043533,how to run karma tests from docker container i have recently moved my nodejs app into a docker image and i would like to run my tests inside the image my mochanode tests work fine but the karma tests involve starting chrome to run the tests and chrome is not installed in the containerhow do i go about addressing thisinstall chrome in the container seems less than ideal as i do not want to ship chrome to my production servers inside the containersomehow allow it to connect to chrome on the hostcreate a new image that inherits from my app image and adds chrome and other thingsgoogling docker karma reveals docker images out there but i cannot find instructions on how to think about the problem and the best approach,['javascript'] +1043636,css word wrap second line of text how can i make the text stay on it is own side when it is overflowing the first rowi have a section that holds two divsthe two divs are positioned side by side but if the first row is full it starts on a new line below the first div and that is the problemthe first div is 120px wide because that is the widest text that can be printed therethe second div isshould be the rest of the screeni created a link to jafiddle also in case the one on the page does not make it clearthe problem occures when you have a smal window phones etcthe page is generated from phpsection thisplay inlineblock width 100 float left ptrans1 float left width 120px color red ptrans2 thisplay inline sectiondiv classptrans115font colorblue1120zfontdiv div classptrans2bmeterologisk observation fran den 15e kl 1220 svensk tidfont colorgreen 32 minuter sedanfontbdivsectionbr,"['html', 'css']" +1043680,where is final parameter stored in anonymous class instance i have the following static factory method that creates a list view out of an int arraypublic static listinteger newinstancefinal int numbers return new abstractlistinteger override public integer getint index return numbersindex override public int size return numberslength public static void mainstring args int sequence 10 20 30 listinteger list listfactorynewinstancesequence systemoutprintlnlist is listin effective java joshua bloch mentioned this as an adapter that allows an int array to be viewed as a list of integer instanceshowever i remember that adapter uses composition and the instance of the anonymous list implementation should use the int as a member fieldwhere exactly is the int input parameter stored if it is not a member field of the anonymous list implementationi would appreciate if anyone could provide some insights or some links to look for more information,['java'] +1043684,ios app update size is much bigger than app size we have a problem that our app update regularly shows up way bigger than the app actually is with app thinningapp update size 142mbapp size on app store 891mbapp size on device 843mbsee the attached screenshotswhat can be causing thisscreenshots were taken on an ios 9 device but the same can be observed on ios 8i see difference for other apps as well but usually just a few mb at maxapp sizeupdate size,"['ios', 'iphone']" +1043712,why does qsharedpointercreate call destructor of incomplete object i have following code exampleinclude qcoreapplicationinclude qsharedpointerinclude qdebuginclude memoryclass apublic a throw 1 a qdebug a destr int mainint argc char argv qcoreapplication aargc argv try auto m1 stdmake shareda auto m2 qsharedpointeracreate catch qdebug catch return aexecthe output for the above code isa destrcatchbut if i uncomment the line with stdmake shared the output is followingcatchso why does qsharedpointercreate call destructor of incomplete object is that a bug or i am missing somethingi tried it with msvc2013 qt 551 and msvc2015 qt 56 built from sources the result is the same,['c++'] +1043768,one method called in several methods i have a class that looks like thisclass a public void method1 inicall do something finalcall public void method2 inicall do something different finalcall more methods like thishow can i simplify this inicall and finalcall so not to write them in every function or several functionsis it possible to do something like callmethod1 being call something like thispublic void callmethod inicall method finalcallotherwise what is a good alternative,['java'] +1044021,how to handle global state data into deeply nested components in redux so say you have a chat aplication with this component structurechatapp currentuserinfocurrentuserinfo chatspanelchatspanel selectedchatpanel messageslist messagebaloon messagetextmessagetext messageuserheadmessageuserhead messagebaloon messageslist selectedchatpanelchatappand a redux state like currentuser chatslist selectedchatindex messageslist how would you make the current user information available to the messageuserhead component that will render the current user thumbnail for each message without having to pass it along all the way from the root component thru all the intermediate componentsin the same way how would you make information like current language theme etc available to every presentationaldumb component in the component tree without resorting to exposing the whole state object,['javascript'] +1044049,is there any performance gain while incrementing char pointer over accessing elements by index i am in a process of refreshing my c knowledge i get that arrays decay to pointers and how that works in string processing i keep running in to code that looks like thisint count spacesconst char s int count 0 for s 0 s ifs count return countwhat performance gain do i get out of my string processing code instead of writing my function as thisint count spacesconst char s int count 0 i fori 0 si 0 i ifsi count return countis there an easy lexicon to go by for when to use a pointer and when not to,['c'] +1044144,apple push notifications are not working in production with my app on the app store push notifications are not workingwith my app in development push notifications are workingi guess i should have tested via an ad hoc deployment anyway here is what i knowapp idmy app id is commynamemyappit has push notifications enabled for development and thistributionapns certificatesi have both development and thistribution certificates it is the thist i care about it has the name commynamemyappexporting to a pemi have selected both the cert and private key and exported it as followsand password protected iti then ranopenssl pkcs12 in certificatesp12 out pushcertpem nodes clcertssupplying the password and successfully getting the pushcertpem outputdownloading appi cleared by server side device token for my device i download my app from the app store opened it and accepted push notifications and then logged into my server to check my device token i have my production device token now i ran this simple php script which works when i supply my development device token but fails with my production device tokenphp put your device token here without spacesdevicetoken myproductiondevicetokeninhere put your private keys passphrase herepassphrase mypassworthisinhere put your alert message heremessage testctx stream context createstream context set optionctx ssl local cert pushcertpemstream context set optionctx ssl passphrase passphrasestream context set optionctx ssl cafile entrust 2048 cacer open a connection to the apns serverfp stream socket client sslgatewaypushapplecom2195 err errstr 60 stream client connectstream client persistent ctxif fp exitfailed to connect err errstr php eolecho connected to apns php eol create the payload bodybodyaps array alert message sound default encode the payload as jsonpayload json encodebody build the binary notificationmsg chr0 packn 32 packh devicetoken packn strlenpayload payload send it to the serverresult fwritefp msg strlenmsgif result echo message not delivered php eolelse echo message successfully delivered php eol close the connection to the serverfclosefpwhy is it failing it works with my development device token but not my production device token have i not done something correctly,"['ios', 'iphone']" +1044176,does the presenter having knowledge of the activity context a bad idea in the mvp pattern i have been playing around with the mvp pattern for a few weeks now and i have come to the point where i need context to start a service and access shared preferencesi have read that the purpose of mvp is to decouple the view from the logic and having context within a presenter may defeat that purpose correct me if i am wrong on thiscurrently i have a loginactivity that looks something like thisloginactivityjavapublic class loginactivity extends activity implements iloginview private final string log tag login activity inject iloginpresenter mpresenter bindridedit login password edittext editloginpassword bindridedit login username edittext editloginusername bindridprogress progressbar mprogressbar override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity login myapplicationgetobjectgraphpresentersinjectthis mpresentersetloginviewthis getapplicationcontext override public void onstart mpresenteronstart butterknifebindthis superonstart override public void onresume mpresenteronresume superonresume override public void onpause mpresenteronpause superonpause override public void onstop mpresenteronstop superonstop override public void ondestroy butterknifeunbindthis superondestroy onclickridbutton login public void onclickloginview view mpresentervalidatecredentialseditloginusernamegettexttostring editloginpasswordgettexttostring override public void showprogress mprogressbarsetvisibilityviewvisible override public void hideprogress mprogressbarsetvisibilityviewgone override public void setusernameerror editloginusernameseterrorusername error override public void setpassworderror editloginpasswordseterrorpassword error override public void navigatetohome startactivitynew intentthis homeactivityclass finish presenter interface iloginpresenterjavapublic interface iloginpresenter public void validatecredentialsstring username string password public void onusernameerror public void onpassworderror public void onsuccessloginevent event public void setloginviewiloginview loginview context context public void onresume public void onpause public void onstart public void onstoplastly my presenterloginpresenterimpljavapublic class loginpresenterimpl implements iloginpresenter inject bus bus private final string log tag login presenter private iloginview loginview private context context private logininteractorimpl logininteractor public loginpresenterimpl myapplicationgetobjectgraphinjectthis thislogininteractor new logininteractorimpl this method is set by the activity so that way we have context of the interface for the activity while being able to inject this presenter into the activity param loginview override public void setloginviewiloginview loginview context context thisloginview loginview thiscontext context ifsessionutilisloggedinthiscontext logilog tag user logged in already thisloginviewnavigatetohome override public void validatecredentialsstring username string password loginviewshowprogress logininteractorloginusername password this override public void onusernameerror loginviewsetusernameerror loginviewhideprogress override public void onpassworderror loginviewsetpassworderror loginviewhideprogress subscribe override public void onsuccessloginevent event if eventgetissuccess sharedpreferenceseditor editor contextgetsharedpreferencessharedprefslogin preferences isloggedin 0edit editorputstringlogged in true editorcommit loginviewnavigatetohome loginviewhideprogress override public void onstart busregisterthis override public void onstop busunregisterthis override public void onpause override public void onresume as you can see i passed the context from the activity into my presenter just so i can access the shared preferences i am quite worried about passing the context into my presenter is this an okay thing to do or should i be doing it some other wayedit implemented jahnolds 3rd preferenceso let us ignore the interface and implementation because it is pretty much the entire thing so now i am injecting the interface for the sharedpreference into my presenter heres my code for the appmoduleappmodulejava modulelibrary true injects logininteractorimplclass loginpresenterimplclass homeinteractorimplclass homepresenterimplclass public class appmodule private myapplication application public appmodulemyapplication application thisapplication application provides singleton public restclient getrestclient return new restclient provides singleton public bus getbus return new busthreadenforcerany provides singleton public isharedpreferencesrepository getsharedpreferencerepository return new sharedpreferencesrepositoryimplapplicationgetbasecontext the way i get the context is from myapplicationjavawhen the application begins i make sure to create this object graph with this line of codeobjectgraph objectgraphcreatenew appmodulethisis this okay i mean i now do not have to pass the context from the activity into my presenter but i still have context of the application,['android'] +1044233,how to implement digest authentication using volley any one can help me for implement digest authentication using google volley for web service calling restbasically volley is using sha1 authenticationbasic auth but is there any way to modify with digest auth md5,['android'] +1044277,annotation processors generated resources not packaged to apk i have custom annotation processor generating factory classes and metainfservicesfactoryinterfaceclass resourceannotation processor is used in library project and all generated files are packaged correctly into aarwhen i use annotation processor in application project with library added as a dependency only classes from libraries metainfservicesfactoryinterfaceclass exist in apkmetainfservicesfactoryinterfaceclassafter some investigation i realized that mergejavaresourcestransform in androidgradleplugin150 and 200alpha3 looks for resources for merging in all explodedaars jars and intermediatessourcefolderjavaresourcesis there any way to merge metainf from intermediatesclasses it is where resource files from annotation processor get created or make annotation processor create file in sourcefolderjavaresourcesonly workaround i have found so far is to add copytask in applications buildscriptandroidapplicationvariantsall variant def variantname variantname def variantnamecapitalized variantnamecapitalize def copymetainf taskscreate copymetainfvariantnamecapitalized copy copymetainffrom projectfiletreejavacompiledestinationdir copymetainfinclude metainf copymetainfinto buildintermediatessourcefolderjavaresourcesvariantname tasksfindbynametransformresourceswithmergejavaresforvariantnamecapitalizeddependson copymetainfbut i do not wat to force compiler an library users do do anything more than adding dependencies,['android'] +1044302,swagger php how to declare property to use schema definition my apps response looks like this status success data status ready request id stringi tried to define response in swagger swgresponse response200 descriptionsuccess response swgschema swgproperty propertystatus typestring defaultsuccess swgproperty propertydata swgschema refdefinitionsservicemodelsstatus swgproperty propertyrequest id typestring but it does not use schema definition for status so my response actually looks like status success data request id stringhow can i define data property to use schema definition or can it can be done in a different way,['php'] +1044309,which boost class should i use to store a human age i have to store an age years months dayspossibly hours minutes seconds of the user i am working with c and boosti am not sure wich class of boostposix time or boostdate time i should usei tried boostposix timetime duration but it is not obvious because there is no constructor taking a year count it is only hours so i didboostposix timetime duration age boostposix timehours24365ageinyearsbut i am not sure that is a good strategy because all years does not have 365 days i also tried boostgregoriandate but that is tricky because this one does not allow to store a year before 1400 and this stores a date not a durationi do not want to store user date of birth because i need to store its age when my program ran medical datai do not want to store a regular int because it is not accurate enough 24 years old 11 months is almost 25i do not want to store a float because i do not want to reinvent the wheel with float to age conversion i would have to dois there really no class making it easy to store a number of years and optionally a number of month and days in boostideally for a guy of 30 years old and a half i would like to be able to create an object like that boost theage 30 6 0 and thenhave a function to get age in years theageyears returning 30 ignoring monthspossibly have a conversion to float that would give me 305 as an age,['c++'] +1044339,is laravel 51 compatible with php 7 according to the installation section on the laravel website 51 is compatible with php 559looking through the incompatibilities i cannot see anything that immediately flags warning signshas anyone run into issues running php 7 with laravel 51edit set kyar wa lar linked a useful resource to php 7 and laravel,['php'] +1044382,how to get three wins in a row here is the tableteamateambwindatekkrhydkkr1 kkrmummum2 rcbhydhyd3 delpubpub4 rrpubrr4 rrdelrr5rcbcskcsk6rrcskrr7cskmummum7mumdelmum8hydpunepune9pubdeldel9kkrdelkkr10kkrrcbkkr10the required answer should be the teams who are winning 3 in a row and the count here for eg rr and mum are winning once 3 in a row kkr has 3 wins however if we see the date column it is not 3 in a row hence kkr should not be in the answer and the output should berr 1mum 1,['sql'] +1044473,relationship between threads and println statements i was trying to create a few scenarios to demonstrate visibility issues while sharing variable across threads and i noticed that in almost all the cases i tested if inside run i added a systemoutprintln statement in the same block of code where i am using the shared variable the visibility issue is not producible i will provide one exampleconfiguration details oracle java6 64bit eclipse juno sr 21with visibility issuepublic class novisibility demonstration extends thread boolean keeprunning truepublic static void mainstring args throws interruptedexception novisibility demonstration t new novisibility demonstration tstart threadsleep10 tkeeprunning false systemoutprintlnkeeprunning is falsepublic void run int x 1 while keeprunning systemoutprintlnif you uncomment this line the code will work without the visibility issue x systemoutprintlnxxoutput the thread keeps running infinitely2 without visibility issuethe same code as above with the uncommented println statement in the runoutput if you uncomment this line the code will work without the visibility issueif you uncomment this line the code will work without the visibility issueif you uncomment this line the code will work without the visibility issuex19391keeprunning is falsesince i noticed similar behavior in all the examples i tried i am wondering if there is any data integrity check by jvm before any io operation,['java'] +1044578,when the static block will be executed in java while creating object class democlass public static void mainstring args systemoutprintlnstart a anew d class a static systemoutprintlnstatic a a cnew c public a systemoutprintlnconstr a class b extends a static systemoutprintlnstatic b public b systemoutprintlnconstr b class c extends b static systemoutprintlnstatic c public c systemoutprintlnconstr c class d extends c static systemoutprintlnstatic d public d systemoutprintlnconstr d the order of execution for above code isstartstatic aconstr aconstr bconstr cstatic bstatic cstatic dconstr aconstr bconstr cconstr din my view all the static blocks should be executed first then only the object will be created but here the object a cnew c in class a static block is created first and then the other static blocks are executed why,['java'] +1044597,spinner functionality not working on android 601 i am using spinner for thisplaying some values and the strange issue is thatthe dropdown is thisplaying correctly but when i select any item from dropdown is not thisplayed in the boxand the strange thing is this functionality is working on all android operating systems before 601ie 600 and previousi have also tried appcompatspinner and the result is samemainxmlspinner androidididspinner androidlayout widthwrap content androidlayout heightwrap content androidlayout weight03 androidentriesarrayvalues mainjavaspinner spinner spinner findviewbyidridspinnerspinnersetselection5 not thisplaying 5th item yes there are more than 5 itemsspinnersetonitemselectedlistenernew adapterviewonitemselectedlistener override public void onitemselectedadapterview parent view view int position long id spinnersetselectionposition override public void onnothingselectedadapterview parent spinnersetselection5,['android'] +1044762,what constitutes a valid c identifier at zaibis suggestion and related to my own answer to what are the valid characters for macro names as well as i 12i and other unicode characters in identifiers not allowed by g clang allows a lot of crazy characters although i have struggled to find much rhyme or reason as to why some are allowed i 12i i a a a a12 and others are not ai a a a for example the following all compile aok clang700176define i 12i2 ok pile of poodefine i end ok halfwidth black squaredefine i 14io interface ok negative squared latin capital letter kdefine i14 protocol ok fullwidth latin capital letter pyet the following all result in the same compiler errormacro name must be an identifierdefine a teldefine a nodefine a updefine a define i 14i12 appleclangs docs refer to the issue stating only support for extended identifiers in c99 and c this feature allows identifiers to contain certain unicode characters as specified by the active language standard these characters can be written directly in the source file using the utf8 encoding or referred to using universal character names u00e0 u0e0so i guess i am asking what is the active language standard and how can i find an authoritative source for what identifiers are legali created the following code just to see what clang would do with it out of about 63488 possible identifiers tested 23 issued warnings and 9506 generated errors that leaves almost 540 valid characters to use in identifiers certainly enough but who got cut and why,['c'] +1044814,why does the ordereddict keys view compare orderinsensitive why does the ordereddict keys view compare orderinsensitive from collections import ordereddict xy ordereddictx none y none yx ordereddicty none x none xy yxfalse xykeys yxkeystruethe ordereddict keys view should arguably behave like an orderedset but instead it behaves the same as dictkeys ie like a usual set same issue in python2 xyviewkeys yxviewkeystruethey are different types odict keys is a subclass of dict keys typexykeysodict keys typekeysdict keysand there is already an ordersensitive keys comparison available that they could have trivially used but it is apparently only used as a postcheck for the odict rich comparison is this a design decision or a bug if it is a design decision where could i find a thiscussion of the justification,['python'] +1044840,cannot load gruntsauce browsersyml on grunt thist with bootstrap 4 alpha 2 i am trying to compile a custom version of bootstrap v4 alpha2 but i keep getting 2 errors please help i am a noob at rubyi managed to install gem install bundlerin fact there is no bundle directory under bootstraprunning the following fails from node modulesbootstrap bundle installthe following also fails grunt thistloading gruntfilejs taskserror error unable to read gruntsauce browsersyml file error code enoentwarning task thist not found use force to continue,['ruby'] +1044901,in angular 2 how do you determine the active route note there are many different answers here and most have been valid at one time or another the fact is that what works has changed a number of times as the angular 2 team has changed its router the router 30 version that will eventually be the router in angular 2 breaks many of these solutions but offers a very simple solution of its own as of rc3 the preferred solution is to use routerlinkactive as shown in this answerin an angular 2 application current in the 200beta0 release as i write this how do you determine what the currently active route isi am working on an app that uses bootstrap 4 and i need a way to mark navigation linksbuttons as active when their associated component is being shown in a routeroutput tagi realize that i could maintain the state myself when one of the buttons is clicked upon but that wouldnt cover the case of having multiple paths into the same route say a main navigation menu as well as a local menu in the main componentany suggestions or links would be appreciated thanks,['javascript'] +1044921,paypal integration to flask application i am slightly misunderstand paypal flow event after reading i would like to integrate express checkout and credit card payments to my site i am using flask and paypalrestsdk without any flask extensionshere is excerpts from my appapproute methodsgetdef index page with but form pricequantityname values are stored in hidden fields buy now acts as submit return render templateindexhtmlapproutepaymentpaypal methodspostdef payment paypal here i am creating dict with required params payment template intent sale payer payment method paypal redirect urls return url url forpayment paypal execute cancel url url forpayment paypal error payment paypalrestsdkpaymentpayment if paymentcreate printpayment created successfullyformatpaymentid for link in paymentlinks if linkmethod redirect redirect url strlinkhref printredirect for approval formatredirect url return redirectredirect urlsapproutepaymentpaypalexecute methodsgetdef payment paypal execute payer id requestargsgetpayerid payment id requestargsgetpaymentid token requestargsgettoken pending payment paypalpaymentqueryfilter bytokentokenfilter bystatecreatedfirst or 404 try payment paypalrestsdkpaymentfindpending paymentpayment id except paypalrestsdkexceptionsresourcenotfound as ex printpaypal resource not found formatex abort404 if paymentexecutepayer id payer id pending paymentstate paymentstate pending paymentupdated at datetimestrptimepaymentupdate time ymdthmsz dbsessioncommit return render templatepaymentsuccesshtml payment idpaymentid statepaymentstate return render templatepaymenterrorhtml payment errorpaymenterror stepfinallizing paymentit is works fine after clicking on button payment created succesfully with state created user redirected to approval page there he click confirm and i never returned to my application event when i specifying return url ie application could never be informed that buyer approved payment and it should be updated in my own database and new license should be sent to that personproblemsi cannot find way to define some callback using pyhtonrestsdk how to do iteven if i adding callback i tried embed express checkout using pure javascript button code with datacallback my application was not called i suspect because remote server could not call user could close window with paypal confirmation immediately after click confirm so i could not trust browser redirection it it performed somehow laterfinally i suspect that i do not understand paypal workflow clear but i could not find more information about it event on developers portal,['javascript'] +1044965,updating a widget at short intervals using api 19 pre api 19 the goto method for updating a widget faster than the updateperiodmillis minimum time of 30 minutes was to use an alarmmanager and a broadcastreceiver to receive the intent after the specified interval used when setting up the alarmmanager currently using the below code the widget is updated but as of android 51 using setrepeating with a repeat interval of less than 60ms will automatically have its interval set to at least 60mssetting alarm in widgets onenabledalarmmanager am alarmmanagercontextgetsystemservicecontextalarm serviceintent intent new intentcontext alarmmanagerbroadcastreceiverclasspendingintent pi pendingintentgetbroadcastcontext 0 intent 0after after 3 secondsamsetrepeatingalarmmanagerrtc wakeup systemcurrenttimemillis 30 10 pithen in the alarmmanagerbroadcastreceivers onreceivepowermanager pm powermanager contextgetsystemservicecontextpower servicepowermanagerwakelock wl pmnewwakelockpowermanagerpartial wake lock tagacquire the lockwlacquire update widgets remoteviews wlreleasein the docs for setrepeating it saysnote as of api 19 all repeating alarms are inexact if your application needs precise delivery times then it must use onetime exact alarms rescheduling each time as described above legacy applications whose targetsdkversion is earlier than api 19 will continue to have all of their alarms including repeating alarms treated as exactit also now statesschedule a repeating alarm note for timing operations ticks timeouts etc it is easier and much more efficient to use handlerso how would you go about updating the widgets remoteviews using a handler how would you get it to stop when the device is put to sleep to conserve batteryare there any other suggested ways to update a widget,['android'] +1044987,check the connected bluetooth devices status how to know whether a bluetooth device is still connected to a laptop or not before passing data i wrote a java program using bluecove lib to thiscover and pass the data through the laptop after passing data for the first time how can i check whether the device is still connected to laptop before passing data in the next time i saw a similar question like this but they have asked how to check the bluetooth device status connected to the android,['java'] +1045008,what exactly are multipartentity and form data how are they used to upload images in android i searched the web but i could only find code related to multipart form data not explanation of what they are and how they are used,['android'] +1045036,thismiss view controller when the home button pressed i am creating an application with swift i have multiple viewcontrollers when someone in a particular viewcontroller and press the home button then i want to thismiss that viewcontroller i do not want any action in other view controllers i found out when i press the home button following appdelagate func will call func applicationdidenterbackgroundapplication uiapplication printenter my guess use this method to release shared resources save user data invalidate timers and store enough application state information to restore your application to its current state in case it is terminated later if your application supports background execution this method is called instead of applicationwillterminate when the user quits so i manage to capture this action using notifier on my view controller viewdidload like the followingnsnotificationcenterdefaultcenteraddobserverself selector selectormyobservermethod nameuiapplicationdidenterbackgroundnotification object niland func myobservermethodnotification nsnotification if let viewcontrollers navigationcontrollerviewcontrollers for viewcontroller in viewcontrollers some process if viewcontrolleriskindofclasshomevc printi am calledr thismissviewcontrolleranimatedfalse completion nil now my problem view controller not thismissing i mean no action happen how to handle thisnote whenever i press the home button myobservermethod func called and printi am calledr also called what i am doing wrongedit 1i want to thismiss if i am in homevcview controller name otherwise no need to thismiss the view controlleredit 2i found out why it always enters to that if condition the reason is always it keeps homevc in the memory so always enters into that if so i add another one condition inside of that like the following if viewcontrollerisviewloaded viewcontrollerviewwindow nil printi am calledr viewcontrollerthismissviewcontrolleranimatedfalse completion nil selfpresentingviewcontrollerthismissviewcontrolleranimatedfalse completion nil viewcontrollerthismissviewcontrolleranimatedfalse completion nil no no action happened i mean the view controller not thismissed,"['ios', 'iphone']" +1045082,put placeholder using jqueryjavascript i can put a placeholder through jquery if there is a single input on the pageinput typetextdocumentreadyfunction placeholders function placeholders inputtypetexteachfunction thisattrplaceholder hello however i have multiple input fields in a single page as belowinput typetext classfirstinput typetext clasecondi wish to add a placeholder only on the first input typetext that has classfirsthow can i add a placeholder to the first matching text input only,"['javascript', 'jquery']" +1045121,how to create custom column with autoincrement characters i want to show one custom column as alias but need to increment by using auto characterid subid dollar packetname168 355 5813 nd1169 355 359 nd1170 356 559 nd2171 362 4536 nd10172 362 484 nd10134 329 4698 nd12135 329 435 nd12125 330 6293 nd13126 330 4293 nd13127 330 693 nd13i need a output with another updated packet column with autoincrement characterid subid dollar packetname updated packet168 355 5813 nd1 nd1169 355 359 nd1 nd1a170 356 559 nd2 nd2171 362 4536 nd10 nd10172 362 484 nd10 nd10a134 329 4698 nd12 nd12135 329 435 nd12 nd12a125 330 6293 nd13 nd13126 330 4293 nd13 nd13a127 330 693 nd13 nd13b,['mysql'] +1045134,why are there stdnot1 and stdnot2 rather than a single overloaded stdnot the c std namespace contains the helper functions stdnot1 and stdnot2 they both take a unary or binary predicate functor respectively and return a stdunary negate or stdbinary negate predicate respectivelyi was wondering whether it should not be possible using some template magic to havetemplatetypename predicate inlineenable if tis unary predicatepredicatevalue unary negatepredicate not predicate constpred return unary negatepredicatepred templatetypename predicate inlineenable if tis binary predicatepredicatevalue binary negatepredicate not predicate constpred return binary negatepredicatepred which thistinguishes the argument pred passed to return the appropriate predicate of course there are the odd cases where the passed object pred has both types of operators unary and binary when this will not work but these can be dealt without the use of this helper function,['c++'] +1045155,getting nameerror uninitialized constant when trying to assign belongs to i have two models like the followingmodule mainmodule module submodule class home activerecordbase has many rooms end endendmodule mainmodule module submodule class room activerecordbase belongs to home end endendif i do the following i get an error homerooms room nameerror uninitialized constant roomfailed homerooms activerecordassociationscollectionproxy successbut if i update the home modelhas many rooms class name mainmodulesubmoduleroom homerooms room mainmodulesubmoduleroom id 1 for some reason i can get the associated rooms but cannot assign a new one what did i miss here,['ruby-on-rails'] +1045169,why absolute path constants dir and file should not be used in symfony i use sensiolabs insight to control my code qualityfor a simple file upload i have to get the absolute path of my uploads directory protected function getuploadrootdir the absolute directory path where uploaded return dir webthisgetuploaddircode directly coming from official documentation how to handle file uploads with doctrinebut slinsight raises a warning if the code analysed contains dir or file php magic constants dir and file constants may conflict with the symfony resource overriding systemhow usage of this constants can causes conflicts with symfony and how can i avoid them in my code,['php'] +1045217,run gradle test and not junit test in intellij idea 15 when choosing configuration type to run with i updated to intellij 1502 from 14 and wanted to run my tests using gradle not junit but i am not getting the options anymore like the image you see herei want to be able to choose configuration typethe thing that is happening now when i run a test is that it runs it as a junit test by defaulti have imported the gradle project with gradle by selecting the gradle file in the projecti have deleted each configuration entry at the top so everything is clean and empty when running a new test with spockmy current fix is to manually create a new config entry for the gradle test intellij is not intelligent enough to create that same junit test as a gralde testi am confused,['java'] +1045273,textfield is hiding once we click on cancel button we are using magento multi vendor sitewe are using following code to update and cancel price but once we click on cancel button textfield is hiding phtmlspan classlabel pro status php echo productsgetprice input classama1 type text id price php echo productsgetid onkeydownvalidatenumbersevent name price value php echo productsgetprice style p idupdatedprice php echo productsgetid style thisplaynonecolorred positionrelative top16pxupdatedp br button idprice update button php echo productsgetid classupdate onclickupdatefieldpricephp echo productsgetid return false spanspan stylefontsize12pxphp echo helper update spanspan button button idprice reset button php echo productsgetid typereset classcancel onclickhideresetpricephp echo productsgetid return false spanspanphp echo helper cancel spanspan button spanjavascriptfunction hideresetpriceproduct id var qtyidprice product idvar editlinkprice edit link product idvar updatebuttonprice update button product idvar valuepricevalueprice product idvar resetbuttonprice reset button product idwk jqqtyidhidewk jqvaluepriceshowwk jqeditlinkshowwk jqupdatebuttonhidewk jqresetbuttonhide,"['javascript', 'php', 'html']" +1045402,i am not getting comgoogleandroidgmsplayserviceswallet840 update for google play services in sdk i have updated my android sdk completely still i am not getting update for google play services version 840 ie comgoogleandroidgmsplayserviceswallet840 like mentioned in the link for implementing android pay whenever i add this line compile comgoogleandroidgmsplayserviceswallet840 in buildgradle i got following error failed to resolve comgoogleandroidgmsplayserviceswallet840,['android'] +1045703,efficiency on a 64bit platform pointer vs 32bit array indexing in one of his keynote andrei alexandrescu suggests that on a 64bit platform using 32bit array indexing is faster than using raw pointerpage 16 on his facebook account he is more precise and says prefer array indexing to pointers this one seems to reverse every ten yearsi have tried many things to find a difference but i have not managed to build any program that shows this difference knowing andrei i would not be surprised that the difference is no more than a few percent but i would be glad if anyone find such an examplehere is a test i have done i choose and 50 large enough to get a decent timing and small enough so that everything fits in the l1 cache i loop a few times so that the cpu frequency risesinclude iostreaminclude chronoint mainint argc const char argv const int n50 int pnew intn warm up the cache for int i0 i n i pi 1 for int j0 j 5 j auto start pointer stdchronohigh resolution clocknow for int qp q p n q q auto end pointer stdchronohigh resolution clocknow auto time pointer stdchronoduration caststdchrononanoseconds end pointer start pointer count stdcout pointer time pointer stdendl auto start pointer stdchronohigh resolution clocknow for int qp q p n q q auto end pointer stdchronohigh resolution clocknow auto time pointer stdchronoduration caststdchrononanoseconds end pointer start pointer count stdcout pointer time pointer stdendl auto start index 32 stdchronohigh resolution clocknow for int i0 i n i pi 1 auto end index 32 stdchronohigh resolution clocknow auto time index 32 stdchronoduration caststdchrononanoseconds end index 32 start index 32 count stdcout index 32 time index 32 stdendl auto start index 32 stdchronohigh resolution clocknow for int i0 i n i pi 1 auto end index 32 stdchronohigh resolution clocknow auto time index 32 stdchronoduration caststdchrononanoseconds end index 32 start index 32 count stdcout index 32 time index 32 stdendl const stdsize t and 64n auto start index 64 stdchronohigh resolution clocknow for stdsize t i0 i and 64 i pi 1 auto end index 64 stdchronohigh resolution clocknow auto time index 64 stdchronoduration caststdchrononanoseconds end index 64 start index 64 count stdcout index 64 time index 64 stdendl const stdsize t and 64n auto start index 64 stdchronohigh resolution clocknow for stdsize t i0 i and 64 i pi 1 auto end index 64 stdchronohigh resolution clocknow auto time index 64 stdchronoduration caststdchrononanoseconds end index 64 start index 64 count stdcout index 64 time index 64 stdendl stdcout stdendl delete p return 0here is the kind of result i get on my machine core i7 all i get is noise pointer 883 pointer 485index 32 436index 32 380index 64 372index 64 429 pointer 330 pointer 316index 32 336index 32 321index 64 337index 64 318 pointer 311 pointer 314index 32 318index 32 319index 64 316index 64 301 pointer 306 pointer 325index 32 323index 32 313index 64 318index 64 305 pointer 311 pointer 319index 32 313index 32 324index 64 315index 64 303,['c++'] +1045800,exception error access violation reading location 0xd i am trying to create a dynamic string array in c when trying to thisplay the contents of my dynamic string array to the console i receive this errorexception thrown at 0x0fd670b6 msvcp140ddll in assignment4exe 0xc05 access violation reading location 0xdhere is my code dynamicstringarrayhpragma onceinclude stdafxhinclude stringinclude iostreamusing namespace stdclass dynamicstringarraypublic dynamicstringarray dynamicstringarraydynamicstringarray array dynamicstringarray int getsize void thisplaycontents void addentryconst string addelement string getentryint index int deleteentryconst string deleteelementprivate string dynamicarray int sizedynamicstringarraycppinclude stdafxhinclude dynamicstringarrayhinclude stringinclude iostreamusing namespace stddynamicstringarraydynamicstringarray dynamicarray null size 0dynamicstringarraydynamicstringarraydynamicstringarray array if dynamicarray null size 0 delete dynamicarray dynamicarray null size arraygetsize dynamicarray new stringsize for int i 0 i size i dynamicarrayi arraydynamicarrayidynamicstringarraydynamicstringarray cout in destructor endl delete dynamicarray dynamicarray nullint dynamicstringarraygetsize return sizevoid dynamicstringarraythisplaycontents if size 0 for int i 0 i size i cout item i dynamicarrayi endl else cout array is empty endlvoid dynamicstringarrayaddentryconst string addelement string temp new stringsize 1 for int i 0 i size i tempi dynamicarrayi tempsize addelement size delete dynamicarray dynamicarray temp delete tempstring dynamicstringarraygetentryint index if index 0 index size return dynamicarrayindex return nullint dynamicstringarraydeleteentryconst string deleteelement ifsize 0 return false for int i 0 i size i if dynamicarrayi deleteelement string temp new stringsize 1 for int x 0 x size 1 x if x i tempx dynamicarrayx else tempx dynamicarrayx 1 delete dynamicarray dynamicarray temp delete temp size return true return falsemainint main dynamicstringarray dsarray1 cout dsarray1thisplaycontents endl dsarray1thisplaycontents should indicate array is empty cout thisplay dsarray1getsize dsarray1getsize endl dsarray1addentryentrya dsarray1thisplaycontents dsarray1addentryentryb dsarray1thisplaycontents dsarray1addentryentryc dsarray1thisplaycontents return 0can anyone tell me what i am doing wrong how can i fix this problem,['c++'] +1045803,keeping track of wins rock paper scissors i was trying to make a rock paper scissors game in javascript i have gotten to a point where the code can figure out who wins the computer or youi am stuck at the following i cannot keep track of how many times i have won and i want the game to end after 5 tries then it outputs how many times i have won out of 5 gamesmy javascript code is belowscript typetextjavascript var computerchoice mathrandom if computerchoice 033 computerchoice rock else ifcomputerchoice 066 computerchoice paper else computerchoice scissors fori1 i6 i var counter 0 documentgetelementbyidbox1onclick function ifcomputerchoice rock alertit is a tie you chose rock computer chose rock lame else ifcomputerchoice paper alertsucker you lost you chose rock computer overlord chose paper else ifcomputerchoicescissors alertdang you beat computer overlord cuz he chose scissors counter documentgetelementbyidbox2onclick function ifcomputerchoice paper alertit is a tie you chose paper computer chose paper lame else ifcomputerchoice scissors alertsucker you lost you chose paper computer overlord chose scissors else ifcomputerchoicerock alertdang you beat computer overlord cuz he chose rock counter documentgetelementbyidbox3onclick function ifcomputerchoice scissors alertit is a tie you chose scissors computer chose scissors lame else ifcomputerchoice rock alertsucker you lost you chose scissors computer overlord chose rock else ifcomputerchoicepaper alertdang you beat computer overlord cuz he chose paper counter i return countervar computerwins 5counterif computerwins counter consolelogcomputer overlord wins he is your masterelse consoleloghey computer overlord and you can be friends just dont tell anyone you lost kscript,['javascript'] +1045813,cannot resolve djangoutilslognullhandler in django 19 after upgrading to django 19 or 110 logging configurations with djangoutilslognullhandler will throw an exception saying that the nullhandler is not resolvableunable to configure handler null cannot resolve djangoutilslognullhandler no module named nullhandlerthis can also happen if copypasting commonly suggested log configurations into new projects based upon django 19 or 110,['python'] +1045848,what does x y represent in javascript what does x y represent in javascripti understand that the bitwise shift operation does thisx y as x 2yand a tilde operator doesx as x1so i assume the following5 3 as 5 24 or 5 mathpow2 4it should result in 03125but when i run 5 3 it results in 1342177280what is a stepbystep explanation how and why does this combination of operations result in 1342177280 instead of 03125this question is similar to stack overflow question what are bitwise operators about the bitwise shift operator,['javascript'] +1045871,symbol not thisplaying properly the symbol is uwhats so special about this symbol and where did it come fromwhat can be done to validate against such input or even better how can such symbols be thisplayed properly ie not letting them overlap over other elements,['css'] +1045887,php 701 could not load ini file file exist in path but php could not load ini filewhat i try change chmod chown change configuration path no results optphp7binphp iphpinfophp version 701system linux portalapp 38136813el7uekx86 64 2 smp wed apr 22 115154 pdt 2015 x86 64build date dec 18 2015 100155configure command configure prefixoptphp7 exec prefixoptphp7 enablefpm withfpmuseruser withfpmgroupnginx thisablecgi thisableshorttags withopenssl withzlib withcurl withsnmp withxmlrpc withgd withjpegdir withpngdir withzlibdir enablegdnativettf withfreetypedir withgettext enableexif enableintl enableftp enablezip withmcrypt withimapoptthistribphp7extimap2007f withimapssl withldap withldapsasl enablembstring enablesoap enablepcntl enablesockets enablebcmath enablemysqlnd withpdomysql withpdopgsql withpgsql withlibdirlib64 withfpmsystemdserver api command line interfacevirtual directory support thisabledconfiguration file phpini path optphp7libloaded configuration file nonescan this dir for additional ini files noneadditional ini files parsed nonephp api 20151012php extension 20151012zend extension 320151012 ls la optphp7libdrwxrxrx 15 root root 4096 o 8 0924 phprwxrxrx 1 php nginx 760 o 18 1012 phpini,['php'] +1045932,regular expression to extract text in reverse order until 3rd instance of a character i have a string in the format x y y yzhow can i extract the string from backwards until the thrid underscore is hitextracted value y y yzi tried this 3 and it seem to work with extra in the beginning which i can probably remove it in javais there any way i get get with out the in the beginning,['java'] +1045942,what are the differences between flexbasis and width there have been questions and articles about this but nothing conclusive as far as i can tell the best summary i could find isflexbasis allows you to specify the initialstarting size of the element before anything else is computed it can either be a percentage or an absolute valuewhich in itself does not say much about the behavior of elements with flexbasis set with my current knowledge of flexbox i do not see why that could not describe width alsoi would like to know how exactly flexbasis is different from width in practiceif i replace width with flexbasisand vice versa what will change visuallywhat happens if i set both to a different value what happens if they have the same valueare there some special cases where using either width or flexbasis would have a significant difference to using the otherhow do width and flexbasis differ when used in conjunction with other flexbox styles such as flexwrap flexgrow and flexshrinkany other significant differenceseditclarification this question has been asked in a different format in what exactly flexbasis property sets but i felt a more direct comparison or summary of the differences of flexbasis and width or height would be nice,['css'] +1045952,confusing example of strong reference cycle in swift this is an example from apples documentclass htmlelement let name string let text string lazy var ashtml void string if let text selftext return selfnametextselfname else return selfname initname string text string nil selfname name selftext text deinit printname is being deinitialized i understand why this closure property would cause strong reference cycle and i know how to resolve it and i am not going to argue thiswhat really confuses me is the follow codevar heading htmlelement htmlelementname h1let defaulttext some default textheadingashtml confusing this closure are supposed to retain heading here but it does not return headingnameheadingtext defaulttextheadingnameprintheadingashtmlheading nil we can see the deinialization message here it turns out that there is not any strong reference cycle in this snippetas far as i know from swift documentation and my own experience of objectivec variable heading will be captured by the closure thus a strong reference cycle should have been caused but it did not this really confused mei also wrote an objectivec counterpart of this example and it did have caused strong reference cycle as i expectedtypedef nsstring tagmakervoidinterface htmlelement nsobjectproperty nonatomic strong nsstring nameproperty nonatomic strong nsstring textproperty nonatomic strong tagmaker ashtmlendimplementation htmlelement voiddealloc nslog nsstring stringwithformat is being deinitialized selfnameendhtmlelement heading htmlelement alloc initheadingname h1headingtext some default textheadingashtml return nsstring stringwithformat headingname headingtext headingnamenslog headingashtmlheading nil heading has not been deinitialized hereany hint or guide will be greatly appreciated,"['ios', 'objective-c']" +1045989,php using language constructs in combination with magic methods this question made me curious about using language constructs in combination with phps magic methods i have created a demo codephpclass testing public function scopelist echo scopelist public function callmethod parameters ifmethod list thisscopelist public static function callstaticmethod parameters instance new static call user func arrayinstance method parameters testinglisttesting new testingtestinglistwhy does testinglist throw a syntax error and testinglist does not due to php reserved keywords both should fail,['php'] +1046012,where to find translated linq to entity query to sql i want to get the translated linq query programmatically and do some stuff with that sql syntaxsuppose this is my codepublic class myapicontrollerapicontroller public iqueryableobject get var objscontextobjextswheremmid10 return objs i want to find and get the sql syntax likeselect from dboobjexts where id 10,['c#'] +1046041,crash reporting in swift ios hello i am developing one ios application where i want to implement crashing reporting without using of any third party sdk or class i want to compose mail when my app will crashi have implemented nssetuncaughtexceptionhandlerexceptionhandlerptrinto didfinishlaunchingwithoptions and added objectivec code for its handler here code of my crashreportingh file volatile void exceptionhandlernsexception exceptionextern nsuncaughtexceptionhandler exceptionhandlerptrand crashreportingm codevolatile void exceptionhandlernsexception exception do stuff nslogapp is ccrasshsed exceptiondescription nslogapp is ccrasshsed exceptioncallstacksymbols here i will compose mail with error description and callstacksymbolsnsuncaughtexceptionhandler exceptionhandlerptr exceptionhandlerits works fine but its not able to handle all type errors how can i do same for fatal errors and signal errors into swift i have searched on google but nothing found helpful for swift help will be appreciate sorry for my bad english thanks,['ios'] +1046060,android 601 could not enable wifi hotspot programmatically when i tried to enable wifi tethering from the following code it throws the exception javalangreflectinvocationtargetexception at javalangreflectmethodinvokenative method at com not granted this permission androidpermissionwrite settingsbut this works fine in android 60 and below versions and also tried with giving androidpermissionwrite settings toois there any limitation in accessing wifiap in android 61follow i attached the code sample that i used to enable hotspot wificonfiguration netconfig new wificonfiguration netconfigssid ssid netconfigpresharedkey passkey netconfigallowedauthalgorithmssetwificonfigurationauthalgorithmshared netconfigallowedkeymanagementsetwificonfigurationkeymgmtwpa psk try boolean apstatus boolean methodinvokewifimanager netconfig true for method iswifiapenabledmethod wmmethods if iswifiapenabledmethodgetnameequalsiswifiapenabled while boolean iswifiapenabledmethodinvokewifimanager for method method1 wmmethods if method1getnameequalsgetwifiapstate int apstate apstate integer method1invokewifimanager logitag apstate apstate if apstatus logdtag access point created else logdtag access point creation failed catch illegalargumentexception e eprintstacktrace catch illegalaccessexception e eprintstacktrace catch invocationtargetexception e eprintstacktrace,['android'] +1046075,resizing drop zone for bubble destroy so i am replicating a similar implementation like the one with the facebook chat bubble and successfully created the drop container for the bubble to be dropped the functionality i am aiming to achieve is i should be able to drop a bubble in a deletion zone which happens to be a circular image with a cross mark when i drag the bubble inside the circular image i am hoping to resize the circular image and make it bigger so when i leave the bubble inside the enlarged image it should thisappear i am not been able to resize this image when i hover my bubble over it the functionality of deletion is in place i would like pointers on dynamic re sizing of circular drop zone imageexpanding and contracting on basis of hovered or not hovered any pointers are welcome thanks in advanceimages below for understanding,['android'] +1046131,how to thisable selected middleware in laravel tests so it is common that errors from authentication and csrf arise when running phpunitso in the testcase we useuse withoutmiddlewarethe problem with this is that when forms fail it usually comes back with a flash message and old input we have thisabled all middleware so we have no access to inputoldusername or the flash messagefurthermore our tests of this failed form post returnscaused byexception runtimeexception with message session store not set on requestis there a way to enable the session middleware and thisable everything else,['php'] +1046245,c why does passing null take the overload with object but only in some cases uncommenting the marked line below will cause a stackoverflow because the overload resolution is favoring the second method but inside the loop in the second method the code path takes the first overloadwhats going on hereprivate static void mainstring args var items new object null testtest items consolereadkeytruepublic static void teststring name object val consolewriteline1public static void teststring name object val consolewriteline2 testname null uncommenting this line will cause a stackoverflow foreach var v in val testname v,['c#'] +1046254,ios bluetooth state preservation and restorations duplicate issue 25299 i am having an issue when instantiating my cbcentralmanager i get a duplicate issue message when monitoring it from the ios console it does not show in the xcode consolei have tried updating the queue name and the restoration key id without success this is how i instantiate my central managercbcentralmanager central cbcentralmanager alloc initwithdelegate self queue thispatch queue createcommydomainmyappscanner null options cbcentralmanageroptionrestoreidentifierkey hexastringcomeshere and those are the errors i am gettingcklsiphone5s securityd78 securityd xpc dictionary handler myapp2571 add the operation couldnat be completed osstatus error 25299 duplicate item ogenpe99372e2lckx2w6m5uyj9commydomainmyapp0acctsvcev data20151218165347298588z2cae5650cklsiphone5s myapp2571 secosstatuswith error25299 the operation couldnat be completed osstatus error 25299 remote error the operation couldna t be completed osstatus error 25299 duplicate item ogenpe99372e2lckx2w6m5uyj9commydomainmyapp0acctsvcev data20151218165347298588z2cae5650any ideas,['ios'] +1046268,tensorflow create dataset from numpy array tensorflow as build it a nice way to store data this is for example used to store the mnist data in the example mnisttensorflowexamplestutorialsmnistinput dataread data setslocalsdatasets object at 0x10f930630suppose to have a input and output numpy arrays x nprandomnormal01 100 10 y nprandomrandint0 2 100how can i transform them in a tf dataset i want to use functions like next batch,['python'] +1046314,load modal after form submit relevant page here sitescansnewsphpi have been trying to load a message confirmation modal for a while after the user submits an email but cannot get it to work at allso far i have tried echoing the whole script out triggering the script and changing the hash in the url and checking for that which has worked in other areas of the siteadding functions like alerts and echoing text onto the page is working fine but when i use the show method it does not work that leads me to believe i am either escaping characters wrong or misunderstand how modals work a littlecan anyone see where i am messing upphpphpifisset postsubmit checking for blank fields if postvname postvemail postsub postmsg echo please fill out everything we need to know who you are and why you want to get in touch with us else check if the senders email input field is filled out email postvemail sanitize email address email filter varemail filter sanitize email validate email address email filter varemail filter validate email emailconfirmed postvemail if email echo do not forget to include your email adress otherwise we cannot get back to you else subject postsub message postmsg headers from emailconfirmed rn senders email headers cc emailconfirmed rn carbon copy to sender message lines should not exceed 70 characters php rule so wrap it message wordwrapmessage 70 send mail by php mail function mail subject message headers echo scriptthankyoumodalmodalshowscript html for the modaldiv classmodal fade idthankyoumodal tabindex1 roledialog div classmodaldialog div classmodalcontent div classmodalheader button typebutton classclose datathismissmodal ariahiddentruetimesbutton h4 classmodaltitle idmymodallabelthank you for preregisteringh4 div div classmodalbody pthanks for getting in touchp div div divdivedit updated code to be simpler than initial question,"['javascript', 'php', 'jquery']" +1046386,wp81 and wp10 differences with windows phone 81 next line worked well but now when users are changing to windows 10 phones devices are failingproductlicense inapplicense currentapplicenseinformationproductlicenseskeyforas mentioned worked with wp 81 nicely and license information was read and stored nicely now with windows 10 phones that line just generates exceptionexception from hresult 0x803f6107 same result with real devices as well with emulatorsso how can i check licenseinformation from windows 10 phones with wp 81 project environment ie code made with 81 projects,['c#'] +1046510,where do i get a googleservicesjson i tried clicking the get a configuration file link from the docs but the resulting page just loads and loads this happens in firefox and chrome and on my phone is there some other way to get a config file edit i am getting these errors in chrome dev consolerefused to thisplay osid1passivaed253dtrue26cntlbl3dcontinue2badding2bsignin26cntapi3dsigninhlen in a frame because it set xframeoptions to denyfailed to execute postmessage on domwindow the target origin provided does not match the recipient windows origin nullanonymous function script footjs348neventthispatch jqueryminjs3rhandle jqueryminjs3,['android'] +1046511,retrofit 2okhttp cancel all running requests i am using retrofit 2beta2 with okhttp 270to get the okhttpclient object from retrofit i am using the retrofit client method and to cancel all it is running requests i am calling it is cancelobject tag method but the requests still keep running and i get a responseeven the clients thispatchers getqueuedcallcount and getrunningcallcount return 0 after calling cancelis there anything else that i need to do for this to work or could it be a bug in okhttpas a workaround i am calling shutdownnow on the clients executorservice but i would prefer a cleaner solution,"['java', 'android']" +1046626,can two identical strings be two separate instances in c in c strings are interned that is if i create the string foobar and use it a second time c will only have one instance of the string in memory and although i will have two references they both will be pointing to the very same string instance this is one reason why strings are and have to be immutable in cnow my question is whether it is possible to somehow create two identical strings so that they are not being interned but that we end up with two different string instances in memory with two different addresses that contain the very same textif so howand is this something than can happen accidentally or do you need to construct a scenario explicitly for this caseand finally supposed there are two separate string instances in memory with the same value are they equal in terms of if so how does work first compare by reference then by value ora,['c#'] +1046658,multiple lefthand assignment with javascript really right associative in this post multiple lefthand assignment with javascript crescent fresh says javsscript lefthand assignment is right associative but the following code seems to me it breaks right associativenessvar a n 1ax a n 2consolelogax undefinedcan anyone explain why ax is undefinededitthe snippet above is to test right associativeness in real world please do not write similar code,['javascript'] +1046700,jvectormaps image markers i know this questions has been asked but the op did not provide any code and i cannot edit his answer obviously so i will start a new one my objective is to replace the dot with a custom droppin marker that i will eventually have some other action for it so as a kicker such action must be identified somehow perhaps and id so that i can call it from jquery css or javascript and give it some usebackground i extracted the map of pennsylvania from jvectormaps and the code from the section that explains how to use marker images from this link markericons this is the original codefunction var plants name kkg coords 499841308 101846373 status activeuntil2018 name k coords 534104656 104091597 status closed name kwg coords 520348748 94097793 status activeuntil2022 name kbr coords 538506 93457603 status closed offsets 0 5new jvmmap container map map de merc markers plantsmapfunctionh return name hname latlng hcoords labels markers render functionindex return plantsindexname offsets functionindex var offset plantsindexoffsets 0 0 return offset0 7 offset1 3 series markers attribute image scale closed imgiconnp3png activeuntil2018 imgiconnp2png activeuntil2022 imgiconnp1png values plantsreducefunctionp c i pi cstatus return p legend horizontal true title nuclear power station status labelrender functionv return closed closed activeuntil2018 scheduled for shut downbr before 2018 activeuntil2022 scheduled for shut downbr before 2022 v and this is my version which it does thisplay the map it does thisplay the location but only as a dot not the marker see screenshot below ps i do not care about the legend i am doing something else for thatmy code vector maps var prison name albion coords 41890611 80366454 status active offsets 0 2pamapvectormap map uspa lcc en scalecolors f7f9fe 29b6d8 normalizefunction polynomial hoveropacity 07 hovercolor false backgroundcolor f regionstyle initial fill dde1e7 fillopacity 1 stroke f7f9fe strokewidth 0 strokeopacity 0 hover fillopacity 08 selected fill yellow markers prisonmapfunctionh return name hname latlng hcoords labels markers render functionindex return prisonindexname offsets functionindex var offset prisonindexoffsets 0 0 return offset0 7 offset1 3 series markers attribute image scale active imgmapmarkericonpng values prisonreducefunctionp c i pi cstatus return p my htmldiv idpamap stylewidth 100 height 470pxdivmy css irrelevant i will design accordingly laterthank you in advance,['javascript'] +1046710,feasibility of automatic cycle breaker for stdshared ptr c11 introduced referencecounted smart pointers stdshared ptr being reference counted these pointers are unable to automatically reclaim cyclic data structures however automatic collection of reference cycles was shown to be possible for example by python and php to thistinguish this technique from garbage collection the rest of the question will refer to it as cycle breakinggiven that there seem to be no proposals to add equivalent functionality to c is there a fundamental reason why a cycle breaker similar to the ones already deployed in other languages wouldnt work for stdshared ptrnote that this question does not boil down to why is not there a gc for c which has been asked before a c gc normally refers to a system that automatically manages all dynamically allocated objects typically implemented using some form of boehms conservative collector it has been pointed out that such a collector is not a good match for raii since a garbage collector primarily manages memory and might not even be called until there is a memory shortage and c destructors manage other resources relying on the gc to run destructors would introduce nondeterminism at best and resource starvation at worst it has also bee pointed out that a fullblown gc is largely unnecessary in the presence of the more explicit and predictable smart pointershowever a librarybased cycle breaker for smart pointers analogous to the one used by referencecounted interpreters would have important differences from a generalpurpose gcit only cares about objects managed through shared ptr such objects already participate in shared ownership and thus have to handle delayed destructor invocation whose exact timing depends on ownership structuredue to its limited scope a cycle breaker is unconcerned with patterns that break or slow down boehm gc such as pointer masking or huge opaque heap blocks that contain an occasional pointerit can be optin like stdenable shared from this objects that do not use it do not have to pay for the additional space in the control block to hold the cycle breaker metadataa cycle breaker does not require a comprehensive list of root objects which is hard to obtain in c unlike a marksweep gc which finds all live objects and thiscards the rest a cycle breaker only traverses objects that can form cycles in existing implementations the type needs to provide help in the form of a function that enumerates references direct or indirect to other objects that can participate in a cycleit relies on regular destroy when reference count drops to zero semantics to destroy cyclic garbage once a cycle is identified the objects that participate in it are requested to clear their stronglyheld references for example by calling reset this is enough to break the cycle and would automatically destroy the objects asking the objects to provide and clear its stronglyheld references on request makes sure that the cycle breaker does not break encapsulationlack of proposals for automatic cycle breaking indicates that the idea was rejected for practical or philosophical reasons i am curious as what the reasons are for completeness here are some possible objectionsit would introduce nondeterministic destruction of cyclic shared ptr objects if the programmer were in control of the cycle breakers invocation it would not be nondeterministic also once invoked the cycle breakers behavior would be predictable it would destroy all currently known cycles this is akin to how shared ptr destructor destroys the underlying object once its reference count drops to zero despite the possibility of this causing a nondeterministic cascade of further destructionsa cycle breaker just like any other form of garbage collection would introduce pauses in program execution experience with runtimes that implement this feature shows that the pauses are minimal because the gc only handles cyclic garbage and all other objects are reclaimed by reference counting if the cycle detector is never invoked automatically the cycle breakers pause could be a predictable consequence of running it similar to how destroying a large stdvector might run a large number of destructors in python the cyclic gc is run automatically but there is api to thisable it temporarily in code sections where it is not needed reenabling the gc later will pick up all cyclic garbage created in the meantimea cycle breaker is unnecessary because cycles are not that frequent and they can be easily avoided using stdweak ptr cycles in fact turn up easily in many simple data structures eg a tree where children have a backpointer to the parent or a doublylinked list in some cases cycles between heterogenous objects in complex systems are formed only occasionally with certain patterns of data and are hard to predict and avoid in some cases it is far from obvious which pointer to replace with the weak variant,['c++'] +1046716,end of line gnu documentation i am reading documentation about gcc preprocessing i read the following sentence hereif the last line of any input file lacks an endofline marker the end of the file is considered to implicitly supply one the c standard says that this condition provokes undefined behavior so gcc will emit a warning messagei try to produce the warning by doing echo n int mainvoid return 0 testc gcc wall wextra werror testcbut no prob it compiles i understand endofline marker as newline char but it seems to be anything elsehow could i produce the warning,['c'] +1046826,navigation transition i am new to jquery and am teaching myself as i go but am struggling to figure out how to indicate that on up scroll the white navigation background moves up to show the white navigation text on panel 1bartailecom is what i am using as inspiration the changes i am making to bartailes navigation are after the user scrolls past the first panel the navigation hides only when the user scrolls up does the navigation show again when panel 1 comes back down the white navigation backgrouns slide up to hide and shows white textany help or tips to learn how to do this would be greatly appreciated var lastscrolltop 0windowonscroll function var header header var stage0 stage0 var scrolltop windowscrolltop if scrolltop lastscrolltop down scroll if scrolltop stage0offsettop stage0height headeraddclasshide else up scroll if scrolltop stage0offsettop stage0height headerremoveclassheaderbgchange headerlichange else headerremoveclasshideaddclassheaderbgchange headerlichange bguptranistion lastscrolltop scrolltopheader thisplay webkitbox thisplay webkitflex thisplay msflexbox thisplay flex webkitboxalign center webkitalignitems center msflexalign center alignitems center height 80px webkittransition top 5s ease transition top 5s ease position fixed width 100 top 0 backgroundcolor transparent overflow hiddenheader ul margin 20px padding 0header ul li thisplay inlineblock marginright 20px color whiteheader ul lilastchild marginright 0hide top 80pxheaderbgchange background whitebguptranistion headerheaderlichange ul li color blueheaderheaderlichange borderbottom 1px solid blackstylestage stylestylestage color f thisplay webkitbox thisplay webkitflex thisplay msflexbox thisplay flex webkitboxpack center webkitjustifycontent center msflexpack center justifycontent center webkitboxalign center webkitalignitems center msflexalign center alignitems center height 100vh backgroundcolor whiteborderbottom 1px solid black fontsize 48pxheight 200pxwidth 100stage0 background greystage24 background 433937script srcajaxgoogleapiscomajaxlibsjquery1102jqueryminjsscriptdiv classheader ul lihomeli liaboutli licontactli uldivdiv clastage stage01divdiv clastage stage23divdiv clastage stage45divdiv clastage stage67divdiv clastage stage89divdiv clastage stage1011divdiv clastage stage1213divdiv clastage stage1415divdiv clastage stage1617divdiv clastage stage1819divdiv clastage stage2021divdiv clastage stage23div,"['javascript', 'jquery', 'html', 'css']" +1046963,intellij says should probably not be passed as parameter x given this codeprivate static class building private final int left private final int right private final int height private buildingint left int right int height thisleft left thisright right thisheight height private priorityqueuebuilding createmaxheapbyheight return new priorityqueuenew comparatorbuilding override public int comparebuilding o1 building o2 return integercompareo1height o2height intellij shows a warning for the comparison line above sayingreturn integercompareo1height o2height height should probably not be passed as parameter xthe warning can be suppressed with a comment on the statementnoinspection suspiciousnamecombinationok but what is so suspicious herealso if i change the compared field to left or to right just for the sake of playing and investigating the warning shifts to the second parameter for examplereturn integercompareo1right o2right right should probably not be passed as parameter yagain what is so suspicious here why does it complain about the first parameter for the field height and about the second parameter for the fields left and right whats the logic here,['java'] +1047036,angular 2 how to get angular to detect changes made outside angular i am trying to create a simple example project to test the angular 2 change detection mechanism i create a pure javascript object in script tags on the main index page it contains the following var tryout tryouttext original text here tryoutprintme function consolelogtryouttext tryoutchangeme function tryouttext change was made one function to console log it and one to change the text propertynow in angular 2 the code looks like thisimport component from angular2corecomponent selector myapp template h1tryoutreftexth1 input typetext ngmodeltryoutreftext button clickconsolelogmeconsole logbutton button clickchangemechange me insidebutton export class myapp tryoutrefany tryout constructor changeme thistryoutrefchangeme consolelogme consolelogthistryoutreftext declare var tryoutstringwhat i am trying to do is thiswhen i call the function tryoutprintme normally with onclick completely outside of angular i want angular to detect the change and update the screeni succeeded to this point when i call tryoutprintme from the component the changeme function is calling tryoutprintme angular detects the change and updates the ui which is fine also when i change from outside angular and i call consolelogme from angular it is logging the changed text and updates the ui i guess i need to execute tryoutchangeme in the same zone that angular is running in somehow any ideas i have a big project which is done in pure javascriptjquery and now i slowly need to rewrite the handlebar templates to angular2 components without touching the model yet for that i need to force the model to execute in the same zone as angularif i wanted to do something like this in angular 1 i would just scopeapply it would workhere is a gif from the example,['javascript'] +1047061,how is a variable name stored in c i want to ask how c the variables are stored in cto be more clear consider the following codeint main int a 1 b b a 2 return 0for example here in what memory c stores the names of variable placeseg if a0x12a7suppose b0x123b1 then how and where does c stores the variable names like in which memory name a is stored,['c'] +1047138,what exactly are coutcin i know java and now want to learn c i cannot understand what are cout character output stream and cin character input are these global variables then whymy messagecout does not work but coutmy messageworks,['c++'] +1047358,how to connect the shadow of the box diagonally i am trying to create a box like this i am using the boxshadow property i have tried to skew but the whole box skewsi want to make the shadow to connect diagonally to the box i am not getting to connect the shadow of the box diagonally to the box please suggest meone width 400px height 200px backgroundcolor yellow boxshadow 10px 10px black margin 10 0 10 10 transform rotate15deg translatex10px translatey15px skewx4deg skewy4degbody div idone divbody,"['html', 'css']" +1047426,nsoperation queue behaving abnormally i have a task of uploading multiple images to the server one by one so i am using the batch operation process for this every time i start the upload procedure some operations specially the first one completes as soon as it starts and the image does not get uploaded and then the batch upoad process continues fine with a rare glitch of missing the other imagesthe code i am using is as followsvoidcallwstouploadrxs nslogthe total assets maintained are lu unsigned long arr assetsmaintainedcount nsmutablearray mutableoperations nsmutablearray array int imageuploadcount intself extractfullsizeimagestouploadcount second for loop is to initialize the operations and then queue them for int i 0 iimageuploadcount i nsdata imagedata uiimagejpegrepresentation arr originalimagestosend objectatindexi10 nsmutableurlrequest request nsmutableurlrequest alloc init request sethttpmethodpost nslogthe url constructed is nsstring stringwithformatuploadrxurl4004dd8514214992a8118e2f3b2e49f75293 arr imagenames objectatindexi request seturlnsurl urlwithstringnsstring stringwithformatjpguploadrxurl4004dd8514214992a8118e2f3b2e49f75293 arr imagenames objectatindexi request setvaluebinaryoctetstream forhttpheaderfieldcontenttype request sethttpbodyimagedata afhttprequestoperation operation afhttprequestoperation alloc initwithrequestrequest mutableoperations addobjectoperation currentuploadindex nsarray operations afurlconnectionoperation batchofrequestoperationsmutableoperations progressblocknsuinteger numberoffinishedoperations nsuinteger totalnumberofoperations nsloglu of lu complete numberoffinishedoperations totalnumberofoperations nsindexpath indexofimagetobedeleted selecteditemsindexpaths objectatindex0numberoffinishedoperations1 arr assetsmaintained removeobjectatindexindexofimagetobedeleteditem arr images removeobjectatindexindexofimagetobedeleteditem arr fullsizeimages removeobjectatindexindexofimagetobedeleteditem arr imagenames removeobjectatindexindexofimagetobedeleteditem if arr selectedcells containsobjectnsstring stringwithformatldlongindexofimagetobedeleteditem arr selectedcells removeobjectnsstring stringwithformatldlongindexofimagetobedeleteditem cellimg selctedrxs sethiddentrue countbeforeclearingassets countbeforeclearingassets 1 reload the items of uicollectionview performbatchupdates block albumimagescollection performbatchupdates albumimagescollection deleteitemsatindexpathsindexofimagetobedeleted completionnil selecteditemsindexpaths albumimagescollection indexpathsforselecteditems selecteditemsindexpaths removeobjectatindex0 nslogthe count of selected items after updation is lu unsigned long selecteditemsindexpathscount completionblocknsarray operations nslogall operations in batch complete self callwstoaddnoteforrxs arr originalimagestosend removeallobjects arr selectedcells removeallobjects currentuploadindex 0 nslogthe array of image names is arr imagenames nsoperationqueue mainqueue addoperationsoperations waituntilfinishedno third is to maintain the progress block for each image to be uploaded one after the other for afhttprequestoperation operation in mutableoperations operation setuploadprogressblocknsuinteger byteswritten long long totalbyteswritten long long totalbytesexpectedtowrite progressoverlayview setalpha07f progressview sethiddenfalse progressview setprogress totalbyteswritten10f totalbytesexpectedtowrite animated yes lbl progressupdate sethiddenfalse lbl progressupdatetext nsstring stringwithformatimage d of lu uploading currentuploadindex mutableoperationscount nslogsent lld of lld bytes and progress is f totalbyteswritten totalbytesexpectedtowrite totalbyteswritten10f totalbytesexpectedtowrite iftotalbyteswritten totalbytesexpectedtowrite progressviewhidden yes self setcomplete in this code the first operation is getting executed as soon i start uploading the images ie only 3 out of 4 are getting uploaded one image is always left out also if i do have only image in the grid that uploads successfullythanks,['ios'] +1047454,tablayout selected tab icon is not selected on start up i am using a tablayout for tabbed navigation in my app i have a really weird issue with it i have created 4 tabs using this codeprivate int tabicons rdrawablenavigation timeline icon selector rdrawablenavigation feed icon selector rdrawablenavigation messages icon selector rdrawablenavigation notification icon selector tablayout tablayout settablayout if tablayout null for int i 0 i 4 i tablayoutgettabatiseticontabiconsi each of the items in tabicon is a selector with selected and nonselected states all icon selectors are configured as followsxml version10 encodingutf8selector xmlnsandroid item androiddrawabledrawablenavigation timeline selected icon androidstate selectedtrue item androiddrawabledrawablenavigation timeline selected icon androidstate pressedtrue item androiddrawabledrawablenavigation timeline icon selectorthe problem is that when the application starts the first selected tab index 0 does not use the selected state icon instead it uses the nonselected stateto be more explanatory here is a screenshot of the issue on first start my tab looks like this when instead it should be like thisafter i change a page all the icons come back to full functionality and the selected states are selected properlyi tried to use the tablayouttab select method but the result is the same the icon that is used is the not selected icondoes some knows what can i do to fix itthanks in advance,['android'] +1047576,what is the fastest way to find nth biggest number of an int array i want a faster function to find the nth biggest number of an int array in c this function takes and and array and returns index of that numberhere is what i have already it simply sorts the array and then returns the index of that number it works perfectly but i am not sure if this is the fastest way it seems logical to be an algorithm without complete sortingstatic int myfunctionint array int n int indexes new intarraylength for int i 0 i indexeslength i indexesi i for int i 0 i arraylength i for int j i 1 j arraylength j if arrayi arrayj int m arrayj arrayj arrayi arrayi m m indexesj indexesj indexesi indexesi m return indexesnsome results myfunctionnew int 1 3 2 0 10 0 returns 4 index of 10myfunctionnew int 1 3 2 0 10 1 returns 1 index of 3myfunctionnew int 1 3 2 0 10 2 returns 2 index of 2,['c#'] +1047768,returning a function chrome dev tools this question may be answered elsewhere but i was not even sure how to begin searching for the answer i am new to javascript so this one is a struggle for me to understandgiven the following codefunction multiplen function fx return x n return fvar triple multiple3var quadruple multiple4when i pass the following into the consoleconsolelogtriple5i get what i expect that is 15 likewise with any number it will be tripled or quadrupled if i used the second functionbut when i type triple into the console i get the following codefx return x nshould not the console returnfx return x 3since 3 is coded into the function by virtue of the following codevar triple multiple3,['javascript'] +1047802,inapp purchase trouble on windows 10 uwp i am trying to enable an inapp purchase item on my app already on windows 10 store but i always receive the same error message when trying to buy this itemthis inapp purchase item is no longer available in myappnamethe code is fairly simple and just what the docs recommendvar itemname appadvanced itemsfullif currentapplicenseinformationproductlicensesitemnameisactive return truevar results await currentapprequestproductpurchaseasyncitemnameif resultsstatus productpurchasestatussucceeded resultsstatus productpurchasestatusalreadypurchased return true else return falsemore informationi created and submited the inapp item to the store before building the package as the documentation told methe name of the item is the same both on the store and the app itemname on codei tried this before submitting to the storei tried this after submitting to the store my app is currently broken there unable to buy the itemi suspect the problem might be related with the followingthe app thisplay name on packageappxmanifest is not the same app name on the store the name i wanted was not available so i made it longer but the app once installed will thisplay the original name this shorter name is the one in the error message i changed the thisplay name to the full name of the app but the error was the same i do not know if sending it to the store might change this i and do not want to deploy another buggy version just to test this theoryextrathe only resources i found online about this issue were useless and related to windows 8 linksuggestions,['c#'] +1047907,avoid forgotten promise returns when i am using promises to express dependencies between jobs where the resolved value becomes unimportant there is some danger that i might be forgetting a return somewhere examplestartsomethingthenfunction qalltasksmapfunctiontask return taskstartit thencollectoutputdonehere the qall returns a promise and i should have returned that not doing so means that by the time collectoutput gets called all tasks have been started but there are no guarantees that they finishedthis kind of error results in a race condition and may be extremely hard to reproduce and track down so i wonder is there some tool to help detect and avoid this kind of problem perhaps some promise library which warns when a function along the way returns undefined or detects promises with no listeners the way bluebird does for unhandled rejections,['javascript'] +1047947,xmlhttprequest simultaneous request not working i am trying to make many xhr request but it seems that every time it waits for the answer before making another request it is like xhr makes a queue and always wait for the previous request to finish what can i do to run more simultaneous xhr requestbodydelegatedownloadclick functionevt evtpreventdefault not related var xhr new xmlhttprequest xhropenget proxyphp thishref true xhrresponsetype blob xhronload function if thisstatus 200 var blob new blobthisresponse typeaudiomp4 consolelogblobsize ifblobsize 0 aattr download name href urlcreateobjecturlblob target blank 0click xhrsend,['javascript'] +1048040,using stanford ner for extracting address from a text document i was looking stanford ner and thinking of using java apis it to extract postal address from a text document the document may be any document where there is an postal address section eg utility bills electricity billsso what i am thinking as the approach isdefine postal address as a named entity using location and other primitive named entitiesdefine segmentation and other sub processi am trying to find a example pipeline for the same what are the steps in details required anyone has done this before suggestions welcome,['java'] +1048177,updating cart count on pressing of back button after deletion i have two activities one is useractivity and other one is cartactivity i am showing a list of products in useractivity on click of a button addtocart i am adding the products to the cart i am facing this problem when i add click the button addtocart there is a cart icon in the action bar and i have a custom layout of a textview showing cart counter on that cart icon that counter updates whenever i click the button addtocart now i move on to the cartactivity and delete some of the products from the cart when i press back button now to return to useractivity the counter text view does not update i have read about few ways of doing the updation on pressing of back as given in the question here back button and refreshing previous activity two methods given in the answer are by overriding the onresume method of useractivity or by starting activity for result i think i need to pass a variable called deletecounter from cartactivity to the useractivity when i press the back button and subtract it from the original number of products in the counter textview and update the text view here is the partial code of useractivity and i have the function to update cart counter in this code only which is called when i click a button also the code of onactivityresult in commented in this which i tried from the answer of above given so question link it is not working out public class useractivity extends appcompatactivity private int cartindex 0 private textview countertv null override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity user toolbar toolbar toolbar findviewbyidridtoolbar setsupportactionbartoolbar override protected void onactivityresultint requestcode int resultcode intent data if requestcode 1 ifresultcode result ok intent intent getintent integer deletecounter intentgetintextradeletecounter0 ifdeletecounter0 updatecartcountintegerparseintcountertvgettexttostringdeletecounter override public boolean oncreateoptionsmenumenu menu inflate the menu this adds items to the action bar if it is present getmenuinflaterinflatermenuuser menu final view menu list menufinditemridaction hawkgetactionview countertv textview menu listfindviewbyidridcartcounter updatecartcountcartindex new mymenuitemstufflistenermenu hotlist show message override public void onclickview v intent intent new intentuseractivitythiscartactivityclass intentputextraproducttitlepname intentputextraproducturlpurl intentputextraproductpricepprice intentputextrabargainpricebargainprice useractivitythisstartactivityintent return true function to update cart count public void updatecartcountfinal int new number cartindex new number if countertv null return runonuithreadnew runnable override public void run if new number 0 countertvsetvisibilityviewinvisible else countertvsetvisibilityviewvisible countertvsettextintegertostringnew number here is the code of cartactivity public class cartactivity extends appcompatactivity private listproduct mcartlist private productadapter mproductadapter private static listproduct cart private static integer deletecounter 0 override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity cart toolbar toolbar toolbar findviewbyidridtoolbar setsupportactionbartoolbar mcartlist getcart intent intent getintent string producttitle intentgetstringextraproducttitle string producturl intentgetstringextraproducturl string productprice intentgetstringextraproductprice string bargainprice intentgetstringextrabargainprice product product new productproducttitle producturl productprice bargainprice mcartlistaddproduct make sure to clear the selections for int i 0 i mcartlistsize i mcartlistgetiselected false create the list final listview listviewcatalog listview findviewbyidridcart list view mproductadapter new productadaptermcartlist getlayoutinflater true cartactivitythis listviewcatalogsetadaptermproductadapter listviewcatalogsetonitemclicklistenernew adapterviewonitemclicklistener override public void onitemclickadapterview parent view view int position long id product selectedproduct mcartlistgetposition if selectedproductselected selectedproductselected false else selectedproductselected true mproductadapternotifydatasetinvalidated floatingactionbutton delete floatingactionbutton findviewbyidridfab deletesetonclicklistenernew viewonclicklistener override public void onclickview view loop through and remove all the products that are selected loop backwards so that the remove works correctly for int i mcartlistsize 1 i 0 i if mcartlistgetiselected mcartlistremovei deletecounter this is the code i used to return data to previous activity but useractivity starts automatically after deletion of selected products as soon as i click the delete button even when there are products in the cart ifdeletecounter0 intent i new intenthawkactivitythis useractivityclass startactivityforresulti 1 intent returnintent new intent returnintentputextradeletecounter deletecounter setresultresult ok returnintent mproductadapternotifydatasetchanged snackbarmakeviewselected items deleted successfullysnackbarlength shortshow public static listproduct getcart ifcart null cart new vectorproduct return cart when i use the code which is commented out in both the activities ie use of start activity for result method this happenswhen i click on the delete button items get deleted but the cartactivity closes automatically the useractivity with counter text view is shown having 0 value even when there are products in the cartdo tell me about any other info you need from the code any other ways i can implement to update the cart counter on pressing of back button after deletion of some items in cartactivity are welcome any help is appreciated,"['java', 'android']" +1048205,connecting tables when querying in mysql i have 3 tables tco articles tco module eostext and tco articles modules my tco articles has unique id key one for each article my tco module eostext has unique instance id that belongs to each article my tco articles modules contains all article ids but have 9 times as much instance ids that are used in other tablesso i can have article id with instance id that when you query in the tco module eostext will return emptyi would like to make a query that will return correct body text for the correct articleso far i haveglobal wpdbposts arrayids wpdbget resultsselect thistinct instance id article id from tco articles modules array athis returns array with all the instances and ids likearray 0 array instance id 928615 article id 129396 1 array instance id 928616 article id 129396 2 array instance id 928617 article id 129396 3 array instance id 928618 article id 129396 you can see that the article ids are the same but instance id when you put wpdbget resultsselect body from tco module eostext where instance id928617 array ayou may get empty but for wpdbget resultsselect body from tco module eostext where instance id928618 array ayou could have some body textthis is my problem i need to go through all of them and filter out the not empty ones and assign them correct article i managed to output the articlesforeach ids as key value instance id valueinstance id article id valuearticle id article out wpdbget resultsselect from tco articles where idarticle id array a postsarticle id article out0which returns something likearray 129396 array id 129396 headline bla bla bla title intro this is cool article intro needs review 0 published 20141216 091700 unpublished hidden 0 no single page 0 permalink linkpermalinkhere internal slug type id 3 thread id 0 news id 0 header game id 0 puff hh id 0 puff title hdrcol id 900 review queued lock timeout 0 created 20141216 091700 updated 20150116 135130 created by 84142 updated by 84142 now i would like to append the body text from the tco module eostext tableis there a query i can use to do this automatically or to do this one at the time and then append to the posts arraythe foreach method of querying is kinda slow when you have 180 postsany help is appreciated,"['php', 'mysql', 'sql']" +1048251,how to create dynamic user face model in android hello i want to create the dynamic user face model in android and thisplay to the useri have searched and found that i need user different angles face frames images like 14 to 16 images and for thisplaying purpose need to change images frame using opengl for smoothness on user finger swipe so it look like 3d image but i want like some editing likewear earing in each frame and thisplay to the user as likeplease give me some suggestion or example on it,['android'] +1048581,error determining a generic return type in c11 in the context of a c14 application i use a scheme which could be resumed as follows minimal reproducible testtemplate class containerstruct locatefunctions auto get it const here is the problem auto ret typename containeriterator return ret template typename tstruct a public locatefunctionsat struct iterator int main aint athis approach compiles and runs perfectly in c14 with gcc and clang compilers now i want migrate my application to windows and for that i am using mingw unfortunately its latest version brings gcc 49 which does not compile c14 that does not seem like a serious problem because i can rewrite the c14 constructs in c11 so i rewrite the get it method as followstypename containeriterator get it const auto ret typename containeriterator return retunfortunately it does no compile both compilers produce the following errorerror no type named aiteratora in astruct ainta typename containeriterator get it const i also triedauto get it const decltypetypename containeriterator auto ret typename containeriterator return retbut i get exactly the same errorsince two compilers fail to recognize the type of return i suppose it is impossible to determine it but i do not really know whycould someone please explain me why not compile and eventually a way for refactoring in c11 that compiles,['c++'] +1048663,ptrace returning 1 on android i am trying to detect when gdb is attached to my app and i am using this in jni codelong x ptraceptrace traceme 0 1 0 char buffer24sprintfbuffer ptrace ld xreturn envnewstringutfenv bufferhowever x is always 1 regardless of whether gdb is attached or not why is that what can i do to figure out what i am doing wrong,['android'] +1048699,are different translation units allowed to define structures with the same name suppose i have ac and bc which both define types called struct foo with different definitionsinclude stdiohstruct foo int aint a funcvoid struct foo f fa 4 printfdn fa return fa 3 include stdiohstruct foo same name different members char p1 char p2void b funcvoid struct foo f fp1 hello fp2 world printfs sn fp1 fp2in c can these files both be linked together as part of a standardsconforming programin c i believe this is forbidden by the one definition rule,['c'] +1048770,attach textview to recyclerview i realize the following is incorrect but i suppose you can treat it as pseudocode i am wondering how can i attach a whole layout to my recyclerview so that when i scroll down the layout scrolls out of sight along with it presently the textview above the recyclerview is fixed on the screen whereas all the data in my recyclerview is scrollable i want the textview to move out of sight as the user scrolls down the page as well if you look at instagram all the user profile information at the top of your gallery thisappears as you scroll down the page how can i do this how can i add the textview programaticallytextview androidlayout widthmatch parent androidlayout heightmatch parent androidtexthello androidsupportv7widgetrecyclerview xmlnsandroid androidlayout widthfill parent androidlayout heightfill parent androidlayout marginbottomandroidattractionbarsize androidpaddingdimenitem margin androidididrecycler view androidcliptopaddingfalse textview androidlayout widthmatch parent androidlayout heightmatch parent androidtexthello androidsupportv7widgetrecyclerview,"['java', 'android']" +1048908,how to make tasks in overview screen looks like together like chrome these google tabs looks togetheri tried but it does not workintent flags i tried flag activity new document flag activity multiple task flag activity reorder to frontintent intent new intentmactivity classintentaddflagsactivitymanager activitymanager activitymanager getsystemservicecontextactivity servicelistactivitymanagerapptask apptasks activitymanagergetapptasksactivitymanagerapptask apptask apptasksget0apptaskstartactivitymactivity intent null,['android'] +1048938,angular 2x selecting dom element i know it should be easy but angular 20 has no many examples yetin one of my components in some case i need to add class on my body tag but my application is bootstrapped deeper than body so i need something likeangularelementbodyaddclassfixedbut in angular 20btw i know i can somehow bootstrap my application to include body tag but i think in some other cases i would need to select some elements anyway so i need a solution how to do this simple task select element and add class to it,['javascript'] +1048970,how to specify wifi network with networkrequestbuildersetnetworkspecifierstring i am searching for a way to let an android 50 tablet connect to an intranet which does not have internet connection for security reasons problem is the captive portal protection that google build in android since 4450a call is done to android connectivitycheck to check for internet connection when this call fails the wifi network is marked as not working and avoided pretty lame others have run into the same issue and some suggest using a new api introduced in android 5 see android 50 lollipop and 44 kitkat ignores my wifi network enablenetwork is uselessthe documentation on this is very vague networkrequestbuildersetnetworkspecifierstring networkspecifierthe interpretation of this string is bearer specific and bearers that use it should document their particulars for example bluetooth may use some sort of device id while wifi could used ssid andor bssid cellular may use carrier spni tried this and it does not work main problem is that once i use setnetworkspecifier no network is found i tried using the bssid mac and the ssid of the ap it looks like the filter is working but its not clear how it should work if i leave out the setnetworkspecifier call 1 network is found but it is not possible to determine which at least it shows my code worksso what should i put in here if ssid and bssid does not workhere is my code private void connectstring ssid context context logitag try connect to ssid connectivitymanager cm connectivitymanager contextgetsystemservicecontextconnectivity service networkrequest nr new networkrequestbuilderaddtransporttypenetworkcapabilitiestransport wifi removecapabilitynetworkcapabilitiesnet capability trusted removecapabilitynetworkcapabilitiesnet capability internet setnetworkspecifierssid here is the problem build connectivitymanagernetworkcallback callback new connectivitymanagernetworkcallback override public void onavailablenetwork network if buildversionsdk int buildversion codeslollipop logitag onavailable networktostring networkgetclassgetname override public void oncapabilitieschangednetwork network networkcapabilities networkcapabilities try if buildversionsdk int buildversion codeslollipop logitag oncapabilitieschanged networkcapabilitiesgetlinkdownstreambandwidthkbps catch exception e eprintstacktrace override public void onlinkpropertieschangednetwork network linkproperties linkproperties try if buildversionsdk int buildversion codeslollipop logitag onlinkpropertieschanged linkpropertiesgetinterfacename catch exception e eprintstacktrace logitag requestnetwork cmrequestnetworknr callback cmregisternetworkcallbacknr callback,['android'] +1049169,edittext hint visibile while transition in my app i am using the android activity slide transition i followed a nice tutorial and everything works as expected except for the hint of my edittext which is contained within an inputtextlayoutandroidsupportdesignwidgettextinputlayout androidlayout widthmatch parent androidlayout heightwrap content androidlayout margindimenactivity vertical margin edittext androidlayout widthmatch parent androidlayout heightmatch parent androidhintyour nameandroidsupportdesignwidgettextinputlayoutall the components are nicely animated but the hint just pops up before the animation starts and remains in the final position do i have to add some extra code to tell the framework to animate the hint tooaccording to the android developer documentation it should work or at least it is not unsupportedi am using version 2 of the support design libraryit would be great if someone could point me in the right direction,['android'] +1049201,post request to php7 with chunked encoding does not properly return result i am sending a post request from a client tested with curl and custom nodejs script and do not get the response properly back the whole thing works fine with php 56environmentthe whole thing is reduced as much as possibleeverything running inside vagrant vm ubuntu 1404 ltsnginx 197 from php7 fpm compiled from official sources with thisableall enablefpmthe minimal nginx site config i am usingserver listen 80 server name localhost location fastcgi param request method request method fastcgi pass unixvarrunphpphp70fpmapisock fastcgi param script filename vagrantindexphp example php script from vagrantindexphpphpecho str repeat 512flush not necessary only due testingcurl call i am using curl xpost httplocalhost h transferencoding chunked d nodejs script i am usinguse strictvar http requirehttpvar url requireurlvar uri urlparseprocessenvurlvar options method post protocol uriprotocol hostname urihostname port uriport path uripathvar data var httprequest httprequestoptions functionres resondata functionchunk consolelogreceived data chunklength data chunk resonend function consolelogfinal size datalength onerror functionerr consolelogerr httprequestwritehttprequestendsending my test requests to php 56 curl httplocalhostcut off curl xpost httplocalhost h transferencoding chunked d cut off urlhttplocalhost node php7testjsreceived data 512final size 512sending my test requests to php 70 curl httplocalhostcut off urlhttplocalhost node php7testjsfinal size 0 curl xpost httplocalhost h transferencoding chunked d curl 18 transfer closed with outstanding read data remainingwhy am i mucking around with chunked encodingthere is no business reason to do so however i was using a very similar nodejs code which defaults to chunked encoding which suddenly stopped working when switching to php7i have found the following to work from the nodejs side explicitly setting a contentlength header removes the implicit transferencoding chunked header sent by nodejs and thus works with both php versionshowever i would like to understand why php7 behaves differently here and whether i am in error or whats really going on hereupdate 1i compared the sapifpm sources between 56 and 70 and there is almost no difference i could spot except changes due php internal changesthe builtin server php s is not affected all tests update 2i bisected the php sources and was able to pinpoint when the behavior changedlast commit i was able to compile which worksfirst commit i was able to compile again which did not work in between output from git bisect commits i could not compile git bisect skipthere are only skipped commits left to testthe first bad commit could be any ofba5ecf355fe792a5a2a8e6582d5e081d02b16fbfe383cb4493031a7cd952cfcaed3297e583149c07fef18f4bea1980a59a9283c2197bd090aaf500cb18cf4e0a8a574034f60f4d123407c173e57e54ecwe cannot bisect morehaving a feeling this could be a bug i wrote this to internals maybe they have some insights m145090900217798w2,['php'] +1049283,microsoft edge easyxdm onmessage event not being called in microsoft edge a get request is not running i have stepped through the code to the point of the ajax request being run and set a breakpoint in the callbacks however the code never reaches the callbacksi already have a then and fail setup with callbacks and tried adding a done and always with callbacks but none of the code in the callbacks is runningi then checked the network tab in devtools and i cannot find the request at all it seems as though edge is not firing the request off for some reasonrequest functionoptions resolvescope var deferred deferred corshandlermakerequestoptions donethis wrapfunctionresponse deferredresolvewithresolvescope response never gets here this failthis wrapfunctionresponse deferredrejectwithresolvescope response never gets here this return deferredthis is what calls the request function aboveajaxfunc functiondata scope return request url pathtoserver internalurl true method get datatype json data data scopethis is the implementation used to make that requestfunction set data var return ajaxfuncdata self thenfunctionres consolelogres never gets here donefunctionres consolelogres never gets here failfunctionres consolelogres never gets here finallyfunctionres consolelogres never gets here here is the cors stuff i do not know a whole lot about this corshandlermakerequest functionoptions resolve default options defaultsoptions xhr null corsurl null url null method get data success function error function terminate false binary false headers internalurl false datatype if url is internal create absolute url from relative url if optionsinternalurl optionsurl thiscreateabsoluteinternalurloptionsurl resolve cors url or proxy url optionscorsurl optionscorsurl thisgetcorsurloptionsurl if optionscorsurl optionsurl thisgetproxyurloptionsurl optionscorsurl thisgetcorsurloptionsurl create xhr if optionsxhr optionscorsurl optionsxhr thiscreatexhroptionscorsurl create cleanup procedure var cleanupafterrequest proxyfunction if optionsterminate optionsxhrdestroy this removecachexhroptionscorsurl this prepare deffered object var deferred deferred deferred donefunction if optionssuccess optionssuccessapplynull arrayprototypeslicecallarguments failfunction if optionserror optionserrorapplynull arrayprototypeslicecallarguments make actual request if optionsxhr throw corshandler xhr object was not created or defined to make request this does not happen optionsxhrrequest url optionsurl method optionsmethod data optionsdata binary optionsbinary headers optionsheaders datatype optionsdatatype function deferredresolveapplynull arrayprototypeslicecallarguments cleanupafterrequest function deferredrejectapplynull arrayprototypeslicecallarguments cleanupafterrequest return deferred updateit looks like the issue is in easyxdm waitforready is not firing onwindow message waitforready in edge i am looking into the issue more noweasyxdm snippet targetorigin getlocationconfigremote if configishost add the event handler for listening var waitforready functionevent if eventdata configchannel ready replace the eventlistener callerwindow postmessage in framecontentwindow framecontentwindow framecontentwindowdocument unwindow message waitforready onwindow message window onmessage settimeoutfunction pubupcallbacktrue 0 onwindow message waitforready set up the iframe applyconfigprops src appendqueryparametersconfigremote xdm e getlocationlocationhref xdm c configchannel xdm p 1 1 postmessage name iframe prefix configchannel provider frame createframeconfig the above snippet runs but the waitforready method is never called the only browser it is not called in is edge works in ie8 chrome safari ff and mobile chromesafari,['javascript'] +1049383,writing bootsector in c prevent generating stack pointer initialization after tinkering with writing bootsector code in assembly i am wondering if i can do the same but in c so far the code generation in an empty function looks as suchin cvoid start halt goto haltconsequent asm generated by gcc7c00 55 push bp7c01 89 e5 mov spbp7c03 eb fe jmp 0x7c03however is it possible to specify that for this entry function in particular i do not want the base and stack pointer to be initialized the bios will transfer control directly to 0x7c00 so the first two instructions setting up the stack pointers are redundantive tried adding attribute always inline noreturn regparm0 to the function declaration but that does not seem to do anything,['c'] +1049387,python neural network reinforcement learning i want to make a neural network that is trained using reinforcement learning in python x ann yestimate score repeat until weights are optimisedi am using scikitlearn at the moment but there does not seem to be all the neural networks stuff tries to fit yestimate to ytargetare there secrets to scikitlearn or are there other libraries that i do not know about for accomplishing thisthank you,['python'] +1049410,making 2 text values show up within 1 list item okay i am having trouble making two text values showing up within the same list item one input one textarea is this possible i am trying to create a simple diarylog application in which you can add a title optional and the content of the post entry itself press submit and have it create a list item thisplaying the contenthtmlhtml head titlewriteuptitle headbodydiv idtextwrap div classborder h1start writingh1br input idtitle placeholdertitle optional textarea rows4 cols50 typetext identry maxlength500 placeholderadd stufftextareabr button idaddsubmitbutton button idremoveallremove allbutton ul idlistul divend of border div divend of textwrap bodyhtmljsjs to add text entriesvar ul documentgetelementbyidlist removeall documentgetelementbyidremoveall add documentgetelementbyidaddmake something happen when clicking on submitaddonclick function addliul documentgetelementbyidtitleheadfunction for adding itemsfunction addlitargetul var inputtext documentgetelementbyidentryvalue li documentcreateelementli textnode documentcreatetextnodeinputtext removebutton documentcreateelementbutton if inputtextsplit join length 0 check for empty inputs alert no input return false removebuttonclassname removeme add class to button for css removebuttoninnerhtml remove add text to the remove button removebuttonsetattributeonclick removemethis liappendchildtextnode liappendchildremovebutton targetulappendchildlifunction to remove entriesfunction removemeitem var parent itemparentelement parentparentelementremovechildparentremoveallonclick function ulinnerhtml demo ignore angular login stuff,"['javascript', 'jquery', 'html', 'css']" +1049414,the output of ftell in php function here is my codephp url handle fopenurl r lenget headersurltrue print rlen echo lencontentlengthn if handle while buffer fgetshandle1024 false echo ftellhandlen fseekhandle20seek cur echo ftellhandlen if feofhandle echo error unexpected fgets failn fclosehandle the result is as below array 0 http11 200 ok contenttype texthtml vary acceptencoding xpoweredby shci v103 server nginx date thu 24 dec 2015 040339 gmt lastmodified thu 24 dec 2015 040128 gmt expires thu 24 dec 2015 040439 gmt cachecontrol maxage60 age 32 contentlength 518264 xcache hit from xidan3399sinacomcn connection close518264162016205840584065518264the contentlength maybe not the same as mine518264it will be changed dynamically when you execute the codeit does no matter for the thiscussionwhy the result is not the following5182641024201024202048402048403072please explain the action of file pointer on fgets and ftell and fseek function,['php'] +1049440,in net can a finalizer be run even if an objects constructor never ran i understand that in net finalizers are run even if an object is partially constructed eg if an exception is thrown out of its constructor but what about when the constructor was never run at allbackgroundi have some ccli code that does effectively the following i do not believe this is ccli specific but this is the situation i have at the readytry classa obja functionthatreturnsaclassa classb objb gcnew classbobja classb is written in c in a referenced project catch i have a 100 repeatable case where if an exception is thrown out of functionthatreturnsaclassa and then a gc is triggered seems to be reliably triggered by running this code again but waiting a while also works classbs finalizer is callednow via trace output i can confirm that classbs constructor is not running which is of course what youd expect so somehow objb was apparently allocated and added to the finalizer list before the preconditions for calling its constructor were even met ie collecting the result from functionthatreturnsaclassathis only happens in optimized release builds running outside the debugger there are a variety of small changes i can make that result in the finalizer not running for instance inserting another method call between the two statements or tellingly i think moving the gcnew classb into a separate function that returns the objectit seems to me that somehow the allocation part of the gcnew statement is getting reordered and run before the previous statement but this reordering is not reflected in the generated msil code defeating my initial assumption that this was just another ccli code gen bug further comparing the generated msil code between the buggy state and any of the fixed states shows no unexpected structural changesi have looked at the generated x86 code in the debugger as well and it does not look strange so far but i have not analyzed it as deeply and anyway i cannot reproduce this behavior in the debugger so i am not 100 sure the code i get from the debugger is the same as the code that shows the strange behaviorso it could be an msilx86 code gen quirk or it could be a processor instruction reordering the former seems more likely but i have not confirmed by trying harder to get the exact code in memory when the behavior occurs this is my next stepquestionso is it valid for lack of a better term for the allocation of an object in net to be divorced and reordered separately from the constructor call for that object,"['c#', '.net']" +1049491,get array from list without heap allocation i have a list and i want to assign its array to a propertypublic void buildmeshlistvector3 list meshverticeslisttoarraynow the problemsthe project is game and is very tough on garbage collection so the default implementation of toarray is not an option as it creates a new array beside lists internal array the mesh object is from a closed source api and the vertices property is a vector3 so cannot assign a pointer to itdo i have any option to prevent heap allocationedit this is not a duplicate cannot use ilistvector3 the mesh is from a closed source api and needs vector3 so i cannot assign ilistvector3 to it,['c#'] +1049540,laravel session store not set on request i recently created a new laravel project and was following along the guide on authentication when i visit either my login or register route i get the following errorerrorexception in requestphp line 775session store not set on request view cusersmatthewdocumentstestresourcesviewsauthregisterbladephpi have not edited any core laravel files i have only created the views and added the routes to my routesphp file authentication routesroutegetauthlogin uses authauthcontrollergetlogin as loginroutepostauthlogin uses authauthcontrollerpostlogin as loginroutegetauthlogout uses authauthcontrollergetlogout as logout registration routesroutegetauthregister uses authauthcontrollergetregister as registerroutepostauthregister uses authauthcontrollerpostregister as logini do not have much experience with laravel so please excuse my ignorance i am aware that there is another question asking this same thing but neither of the answers seem to work for me thanks for readingeditheres my registerbladephp as requestedextendspartialsmainsectiontitle test registersectioncontent form methodpost actionauthregister csrf field div classui input input typetext namename value oldname placeholderusername div div classui input input typeemail nameemail value oldemail placeholderemail div div classui input input typepassword namepassword placeholderpassword div div classui input input typepassword namepassword confirmationplaceholderconfirm password div div button classui primary button typesubmitregisterbutton div formendsection,['php'] +1049568,get attribute name from string array i have string array that looks like thisstringarray nameusa item nameny001item item namela002item item namewa003itemstringarrayi can get those numbers byresources res getresourcesint arryid resgetidentifierusa array getpackagenamestring numbers resgetstringarrayarryidbut how can i also get the names nylawanote that i have a lot of counties maybe use different approach,['android'] +1049743,how to do auto tooltip validation msg here i created sample file for validation which is working finebut my requirement is i need to do some modification on that while validating error message need to show in auto tooltip it needs to be shown automatically when there is error and hide automatically once error cleared until error clear popup need to be stayif it is possible without jquery or else with jquery also fine var app angularmodulemyapp uservalidationmyappctrl functionscope scopeformallgood function return scopeusernamegood scopepasswordgood scopepasswordcgood angularmoduleuservalidation directivevalidusername function return require ngmodel link function scope elm attrs ctrl ctrlparsersunshiftfunction viewvalue any way to read the results of a required angular validator here var isblank viewvalue var invalidchars isblank az09testviewvalue var invalidlen isblank invalidchars viewvaluelength 5 viewvaluelength 20 ctrlsetvalidityisblank isblank ctrlsetvalidityinvalidchars invalidchars ctrlsetvalidityinvalidlen invalidlen scopeusernamegood isblank invalidchars invalidlen directivevalidpassword function return require ngmodel link function scope elm attrs ctrl ctrlparsersunshiftfunction viewvalue var isblank viewvalue var invalidlen isblank viewvaluelength 8 viewvaluelength 20 var isweak isblank invalidlen azazazaztestviewvalue ctrlsetvalidityisblank isblank ctrlsetvalidityisweak isweak ctrlsetvalidityinvalidlen invalidlen scopepasswordgood isblank isweak invalidlen directivevalidpasswordc function return require ngmodel link function scope elm attrs ctrl ctrlparsersunshiftfunction viewvalue scope var isblank viewvalue var nomatch viewvalue scopemyformpasswordviewvalue ctrlsetvalidityisblank isblank ctrlsetvaliditynomatch nomatch scopepasswordcgood isblank nomatch link href relstylesheetscript srcscriptdiv ngappmyapp form namemyform classform formhorizontal ngcontrollermyappctrl novalidate legendangular user validation with bootstrap decorationslegend div classcontrolgroup ngclasserrormyformusernamevalid label forinputusername classcontrollabelusernamelabel div classcontrols input typetext idinputusername nameusername ngmodelusername validusername div classhelpinline span ngshowmyformusernameerrorisblankusername requiredspanspan ngshowmyformusernameerrorinvalidcharsusername must contain letters amp spaces onlyspan span ngshowmyformusernameerrorinvalidlenusername must be 520 charactersspan div div div div classcontrolgroup ngclasserrormyformpasswordvalid label forinputpassword classcontrollabelpasswordlabel div classcontrols input typetext idinputpassword namepassword ngmodelpassword validpassword div classhelpinline span ngshowmyformpassworderrorisblankpassword requiredspan span ngshowmyformpassworderrorisweakmust contain one upper amp lower case letter and a nonletter number or symbolspan span ngshowmyformpassworderrorinvalidlenmust be 820 charactersspan div div div div classcontrolgroup ngclasserrormyformpassword cvalid label forpassword c classcontrollabelconfirm passwordlabel div classcontrols input typetext idpassword c namepassword c ngmodelpassword c validpasswordc div classhelpinline span ngshowmyformpassword cerrorisblankconfirmation requiredspan span ngshowmyformpassword cerrornomatchpasswords do not matchspan div div div div classformactions ngshowformallgood input typesubmit classbtn btnprimary valuesubmit div formdiv,"['javascript', 'jquery']" +1049773,cs7003 unexpected use of an unbound generic name i am getting this error in visual studioerror cs7003 unexpected use of an unbound generic name myproject cusersmynamedocumentsvisual studio 2015projectsindexcshtml 1the offending file is right here line 1 error is the reference to the model declarationmodel myprojectmodelsmyaccountdetails viewbagtitle index layout viewsshared primarylayoutcshtml page content div classcontainer more page stuff follows from herethe model class is as followsnamespace myprojectmodelsmyaccount public class details public static details selectcompany c details model new details modelsomeproperty somevalue return model public string someproperty get set the weird thing is that cleans do not make it go away rebuilds leave it there and i builddebug just fine,['c#'] +1049787,escaping characters in css class selectors i am trying to implement this w3 description of character escapes in css class selectorsi am running into problems with the abc20 def syntax that puts a space after the escape sequence to ensure def is not misread as part of the character codespecifically trying to put abcxy def into an html class attribute or into a command like jqueryaddclassabc20 def the here is part of the js string literal syntax the string value itself has one slash will both give the element two classes abc20 and defis this syntax just badly implemented and i should stick with the sixdigit leading zero form or does that document only refer to the escape format in css code and the html attribute jquery argument require some different form of escaping the space characteredit thank you very much for explaining everyonei now understand that this syntax only applies to css code not the class names themselves as set in html attributes or javascriptthis also means that characters designated as whitespace cannot occur in css class values and no kind of escape mechanism allows them to be added specifically if i understand correctly the css selector abc20 def is valid and selects elements with the class abc def but is meaningless because no element can have this classfor my concrete use case which involves mapping arbitrary values which can have white space to valid class names i need to define my own escape scheme replacing whitespace with or thanks praveen is one possibility if the mapping needs to be onetoone replacing them with sixdigit unicode hex values eg abc def abc020def is a more robust onethe important thing to keep in mind is that this replacement affects the class name itself to refer to the class abc020def in css the backslash must be escaped again to form the selector abc020def,['javascript'] +1049909,how to execute code exactly 10 times in 1 second in javascript n 0var timer setintervalfunction if n 0 consolelognew date execute some other code here n if n 10 clearintervaltimer consolelognew date 1this code executes in about 34 seconds depending on machine and browser maybe how can i make it execute in exactly 1 second,['javascript'] +1049922,basic programming exercise about logical operators i have a problem with a question in my bookincludestdiohvoid main int a5 b7 c0 d d a b c printfndabcdthe question asks me what is the output of the code i ran it and the result on the screen is 6601 i understand why a6 and b6 but i do not understand why c0 and d1,['c'] +1049957,synchronous parallel process in c c i have an array x containing data also there is an array of system states c the processfori 1 i n i a f1xi ci1 b f2xi ci1 ci a bis there any efficient way to find the values of f1 and f2 on 2core system using 2 parallel threads i mean the following in pseudocodethread 1 fori 1 i n i a f1xi ci1 thread 2 fori 1 i n i b f2xi ci1 ci a b here we somehow get ai from thread 1 f1 and f2 are not time consumptive but have to be calculated many times so desired speedup is about x2 see the diagram for graphical representationlooking for code examples for windows,"['c#', 'c++']" +1050024,how to typedef a stdarray in c i want to write some variables likestdarraydouble array num awhere array num is a const int representing the length of the array but it is long and i want to create an alias for ittypedef stdarraydouble array num my arrayis it right how can i use my array like my array3,['c++'] +1050063,define own keywords and meanings is it possible to define your keywords in ci mean something like public important form newformwhere important would be the new keyword it would mean something like for example that if the type is null when compiling an error occurrs so the example would produce an error an example with no error would be public important form newform form1,['c#'] +1050082,replace single instances of a character that is sometimes doubled i have a string with each character being separated by a pipe character including the s themselves for examplefunnyboyacati would like to replace all s which are not next to another with nothing to get the resultfunnyboyacati tried using mytextreplace but that removes everything and makes one long word,['python'] +1050104,how to test scenario where the apple watch is not connected to an iphone i am developing a watchos extension which uses wcsession to communicate with the iphone however i do not own an apple watch and therefore have to rely on the watch simulator to test my codeis there a way to test the scenario where the watch is thisconnected from the phone in the simulatorif not is there some documentation or a wellresearched blog post that gives some insight into the behavior of wcsession in this case,['ios'] +1050191,how to fetch title of an item from a database and send it to the header template in codeigniter i am writing an application in codeigniter where i specify the title metatag on every page in every controller which i have managed to send to my header template however now i have created an application that fetch credit cards and their titles from the database through an codeigniter model i would like to automatically fetch and use the credit cards name in title so that i do not need to change it manually but i am a little stuck on how to proceedthis is my code as of nowcontrollerpublic function showcard null dataquery thislisting modelget cardcard headerpage title from the model thisloadviewincludesheaderheader thisloadviewlistingslisting carddata thisloadviewincludesfootermodelfunction get cardcard false query thisdbget wherecreditcards arrayslug card 01 return queryresulti have been following the official codeigniter documentation when creating this application but so far no luck any solutions,['php'] +1050411,bittorrent download not starting i am trying to implement a bittorrent tracker in laravel however i am stuck at the moment as the download would not start there is one peer which it appears to be seeding and i am 100 sure that it is connectable but when i run a second client on a different machine the download would not start it is stuck at connecting to peers utorrentfrom the tracker i am sending the following response when the client makes an announced8intervali10e12min intervali300e5peers18i12i12ii12i12xajui126ein the downloading client i have the following dataheres my announce codephpnamespace apphttpcontrollersannounceuse apphelpersbencodehelperuse appmodelspeeruse appmodelspeertorrentuse appmodelstorrentuse appmodelsuseruse illuminatehttprequestuse illuminatehttpresponseuse illuminateroutingcontrolleruse illuminatesupportfacadesinputuse illuminatesupportfacadeslogclass announcecontroller extends controller const interval 10 const timeout 120 const interval min 60 const max ppr 20 public function announcerequest request loginforequestfullurl status 200 content passkey inputgetpasskey peer id inputgetpeer id port inputgetport info hash inputgetinfo hash downloaded inputgetuploaded intvalinputgetuploaded 0 uploaded inputgetuploaded intvalinputgetuploaded 0 left inputgetleft intvalinputgetleft 0 compact inputgetcompact intvalinputgetcompact 0 no peer id inputgetno peer id intvalinputgetno peer id 0 ipaddress check for xforwardedfor headers and use those if found if isset serverhttp x forwarded for trim serverhttp x forwarded for ipaddress trim serverhttp x forwarded for else if isset serverremote addr trim serverremote addr ipaddress trim serverremote addr port serverremote port ifport ctype digitport intvalport 1 intvalport 65535 content bencodehelpertrackinvalid client port status 401 return new responseannouncecontrollertrackcontent status headercontenttype value if port 9 substrpeer id 0 10 to01xx died8completei0e10incompletei0e8intervali600e12min intervali60e5peersld2ip127214194184port39ed2ip11721419414port39ed2ip127214194654port39e if passkey content bencodehelpertrackmissing passkey status 401 return new responseannouncecontrollertrackcontent status headercontenttype value torrent torrentgetbyinfohashsha1info hash if torrent torrent null content torrent not registered with this tracker status 404 return new responseannouncecontrollertrackcontent status headercontenttype value user userhaspasskeys passkeyget if user null content bencodehelpertrackinvalid passkey status 401 return new responseannouncecontrollertrackcontent status headercontenttype value peer peergetbyhashandpasskeybin2hexpeer id passkey if peer null peer peercreate hash bin2hexpeer id user agent serverhttp user agent ip address ipaddress passkey passkey port port if info hash strleninfo hash 20 content bencodehelpertrackinvalid info hash status 401 return new responseannouncecontrollertrackcontent status headercontenttype value peer torrent peertorrentgetbypeerandtorrentpeer torrent if peer torrent null peer torrent peertorrentcreate peer id peerid torrent id torrentid uploaded uploaded downloaded downloaded left left stopped false else peer torrentuploaded uploaded peer torrentdownloaded downloaded peer torrentleft left peer torrentsave seeders torrentgetseederscount leechers torrentgetleecherscount resp if compact 1 resp d thisbenc strinterval i announcecontroller interval e thisbenc strpeers l else resp d thisbenc strinterval i announcecontroller interval e thisbenc strmin interval i 300 e5 peers peer array peer num 0 foreach torrentgetpeersarray as row if compact 1 if rowpeer id peerhash continue resp d thisbenc strip thisbenc strrowip if no peer id 0 resp thisbenc strpeer id thisbenc strrowpeer id resp thisbenc strport i rowport e e else peer ip explode rowip peer ip packc peer ip0 peer ip1 peer ip2 peer ip3 peer port packn introwport time intvaltime 7680 60 if left 0 time 128 time packc time peer time peer ip peer port peer num if compact 1 resp ee else o for i 0 i peer num i o substrpeeri 1 6 resp strleno o e thisbenc resp rawresp public function benc respd return thisbenc resp rawthisbencarraytype dictionary value d public function benc resp rawx headercontenttype textplain headerpragma nocache if serverhttp accept encoding gzip headercontentencoding gzip echo gzencodex 9 force gzip else echo x function bencobj if is arrayobj issetobjtype issetobjvalue return c objvalue switch objtype case string return thisbenc strc case integer return thisbenc intc case list return thisbenc listc case dictionary return thisbenc dictc default return public function benc strs return strlens s public function benc inti return i i e public function benc lista s l foreach a as e s thisbence s e return s public function benc dictd s d keys array keysd sortkeys foreach keys as k v dk s thisbenc strk s thisbencv s e return s public function hex2binhex r for i 0 i strlenhex i 2 r chrhexdechexi hexi 1 return r i am not quite sure what am i missing herethanks,['php'] +1050651,turn enum into class with constants is there an intellij refactoring allowing to automatically turn an enum into a class thus transforming its enum values into static final fieldsi cannot seem to find anything about it i only find stuff about extracting constants but not what i am looking forexample of what i am looking forfor instance i would like to turn an enum like this onepublic enum planet mercury 3303e23 24397e6 venus 4869e24 60518e6 earth 5976e24 637814e6 mars 6421e23 33972e6 jupiter 19e27 71492e7 saturn 5688e26 60268e7 uranus 8686e25 259e7 neptune 1024e26 24746e7 private final double mass in kilograms private final double radius in meters planetdouble mass double radius thismass mass thisradius radius getters hereinto a class like thatpublic class planet public static final planet mercury new planet3303e23 24397e6 public static final planet venus new planet4869e24 60518e6 public static final planet earth new planet5976e24 637814e6 public static final planet mars new planet6421e23 33972e6 public static final planet jupiter new planet19e27 71492e7 public static final planet saturn new planet5688e26 60268e7 public static final planet uranus new planet8686e25 259e7 public static final planet neptune new planet1024e26 24746e7 private final double mass in kilograms private final double radius in meters planetdouble mass double radius thismass mass thisradius radius getters hereif you wonder why someone would want to do thisif the enum should not have been an enum in the first place and for whatever reason someone declared it as suchto make it extend another classto fetch the enum values from a database instead of hardcoding them in the declaration although i have to admit that in this case we just need to delete all the enum values and change the enum keyword into class no need for such a complex refactoringnote the reason why someone would make the change is offtopic of course please avoid thiscussing about it in this thread,['java'] +1050671,is it possible to add an attribute to a property in a partial class i do not think it is possible but since i have not got a definite clarity from msdn i feel that it is best to ask suppose that we have a class as followspublic partial class hazaa public int shazoo get set then i would like shazoo to be attributed as supercool but i wish to do so in another file since i am using partial classes i can add new properties as followspublic partial class hazaa supercool public int whe get set but can i attribute a property declared in the first sample by writing code in the latter i doubt it is possible but i will be glad to stand corrected if so whats the syntax,['c#'] +1050682,removing duplicates of 3d points in a vector in c i am dealing with a point cloud ie a vector of points as a result of computation which contains duplicate points up to 10 of the size of the cloudmy implementation was to sort those points according to xy and z value and then use the stdunique function the resulting cloud however still contains duplicates even though the sorting itself seems to be workingheres the crucial codebool comparepointpclpointxyzinormal p1 pclpointxyzinormal p2if p1x p2x return p1x p2xelse if p1y p2y return p1y p2yelse return p1z p2zbool equalpointpclpointxyzinormal p1 pclpointxyzinormal p2 if p1x p2x p1y p2y p1z p2z return true return falsevoid kdsearchcullduplepoints stdsortpointsbegin pointsend comparepoint stduniquepointsbegin pointsend equalpointand here is a partial extraction of the output pointcloud xy and z coordinates196828 53509515 27948391196627 63695264 29140366196627 63695264 2914036619651 10877433 2350984119651 10877433 2350984119642299 20619427 5618462919642299 20619427 56184629196386 18803784 13460654so is unique not working properly or is there a mistake in my equal conditionthe points itself also contain normal coordinates but they are not important for culling so i did not use them in the code,['c++'] +1050689,what is the new generated code this was autogenerated to implement the app indexing api backgroundi just created a new poc today about activity transitions but this is not the topic and i have noticed a new line being written in the oncreate method of the main activty attention this was autogenerated to implement the app indexing api see for more information mclient new googleapiclientbuilderthisaddapiappindexapibuildand moreoverride public void onstart superonstart attention this was autogenerated to implement the app indexing api see for more information mclientconnect action viewaction actionnewaction actiontype view todo choose an action type singlephotoviewer page todo define a title for the content shown todo if you have web page content that matches this app activitys content make sure this autogenerated web page url is correct otherwise set the url to null uriparsehttphostpath todo make sure this autogenerated app deep link uri is correct uriparseandroidappcomexampleusertransitionstesthttphostpath appindexappindexapistartmclient viewaction override public void onstop superonstop attention this was autogenerated to implement the app indexing api see for more information action viewaction actionnewaction actiontype view todo choose an action type singlephotoviewer page todo define a title for the content shown todo if you have web page content that matches this app activitys content make sure this autogenerated web page url is correct otherwise set the url to null uriparsehttphostpath todo make sure this autogenerated app deep link uri is correct uriparseandroidappcomexampleusertransitionstesthttphostpath appindexappindexapiendmclient viewaction mclientthisconnect and this was added to the manifest attention this was autogenerated to add google play services to your project for app indexing see for more information metadata androidnamecomgoogleandroidgmsversion androidvalueintegergoogle play services versionthe problemlooking at the website that was written i still do not get what it isi guess this is how to use it but i do not get how it all worksalso weird thing is that any other new project that i create does not show this new line of codethe questionswhat is this what does it dowhat should i do with itare there any customizations for it any recommendations on which cases does this line of code get generated i did not notice how and when it gets createdmy guess according to what i have read and seen on the website is that this is only used for apps that can perform some sort of searching so that google could show the user previous queries and faster results,['android'] +1050747,baseline of vertically stacked elements i have a container of vertically stacked elementsdiv divline 1div divline 2div divline 3div divline 4divdivi want the baseline of the container to be identical to the baseline of a specific one of its elements let us say the third one it should look like thishow can i do this with cssas a related question how is the baseline of such container of vertically stacked elements usually definedi want to give this container a property thisplay inlineblock this container appears next to other elements on a line and i want them to be aligned according to the baseline,"['html', 'css']" +1050859,qt settext outside of paint events not ok under qt 471 qt creator 210 os x 1068i have a qlabel in the mainwindow ui which uses courier new 13 with room for four lines of texti create four lines of text considerably shorter than the label is horizontally of the general formatmy textrni filter the text before sending it along the only characters in the cstring will be 0x0d 0x0a 0x20 space and from there up to lower case z 0x7a and of course the terminating zero no other control characters if they are received from the source i replace them with i send the four lines of text to the qlabel as a single zeroterminated cstring via settexti sometimes do this at a fairly high rate several times a second at least this is rdbs data from an fm station so it changes in real timeqdebug rbl data keeps coming to consoleuifourlinelabelsettextrbl add this thisplay soon stops updatingthis works for a while then the thisplay stops updating this is the area at issueif i leave everything else in but take out the settext the problem does not occuri know that for some things qt wants painting to be done within a paint event is this also true of a settext reading the docs on qt widgets it says that widgets do their own painting within their own paint event but the behavior here is very similar to the kind of malfappery that goes on when one actually tries to use a painter outside of a paint event and it is definitely related to that settext so mumbleas i write this the application has been running for hours without any thisplay lockup outputting the same text to the console via qdebug it takes about 5 minutes for the problem to occur if i uncomment the settext it is 100 repeatableis there something i should be doing that i am not doing paintwise or similarthanks for any assistance,['c++'] +1050935,processes resources not limited by setrlimit i wrote a simple program to restrict it is data size to 65kb and to verify the same i am allocating a dummy memory of more than 65kb and logically if i am doing all correct as below malloc call should fail is not itinclude sysresourcehinclude stdiohinclude stdlibhinclude errnohint main int argc char argv struct rlimit limit get max data size if getrlimitrlimit data limit 0 printfgetrlimit failed with errnodn errno return 1 printfthe soft limit is lun limitrlim cur printfthe hard limit is lun limitrlim max limitrlim cur 65 1024 limitrlim max 65 1024 if setrlimitrlimit data limit 0 printfsetrlimit failed with errnodn errno return 1 if getrlimitrlimit data limit 0 printfgetrlimit failed with errnodn errno return 1 printfthe soft limit is lun limitrlim cur printfthe hard limit is lun limitrlim max systembash c ulimit a int new2 null new2 malloc6 if new2 null printfmalloc failedn return else printfsuccessn return 0surprisingly the ouput is something like this the soft limit is 4294967295the hard limit is 4294967295the soft limit is 66560the hard limit is 66560core file size blocks c 0data seg size kbytes d 65scheduling priority e 0file size blocks f unlimitedpending signals i 14895max locked memory kbytes l 64max memory size kbytes m unlimitedopen files n 1024pipe size 512 bytes p 8posix message queues bytes q 819200realtime priority r 0stack size kbytes s 8192cpu time seconds t unlimitedmax user processes u 14895virtual memory kbytes v unlimitedfile locks x unlimitedsuccessam i doing wrong in any wayplease drop your inputsthanks,['c'] +1050941,hot keys ignored for custom commands i am writing my first wpf application and am trying to get my custom commands to workpublic static routeduicommand header1 get private set gestures new inputgesturecollectiongesturesaddnew keygesturekeyd1 modifierkeyscontrol ctrl1header1 new routeduicommandheader 1 header1 typeofeditcommands gesturesi then added a commandbindings section to my windows xaml local refers to my applications namespace windowcommandbindings commandbinding commandlocaleditcommandsheader1 executedcommandbinding executed canexecutecommandbinding canexecutecommandbindingwindowcommandbindingsand finally added a command entry to the associated ribbon controlribbonbutton labelheader 1 commandlocaleditcommandsheader1 smallimagesourceimagessmallpng tooltiptitleheader 1 tooltipdescription tooltipimagesourceimagessmallpngribbonbuttonclicking the ribbon button executes the handler as expected however pressing ctrl1 seems to have no effect at all how can i have my hot key recognized,['c#'] +1051125,checking if all true and reset a boolean array using oneliner lambda expression of java 8 suppose i have a huge boolean array flagsboolean flags true false true 3 means manyi want to do two things on flagscheck whether all the elements are true and return an indicatorreset all the elements to falseusing lambda expression of java 8 i can do them as followsindicator arraysstreamflagsallmatchflag flagarraysstreamflagsforeachflag flag falsereturn indicatorhowever this implementation scans flags twice since flags is huge i do not want this in addition i do prefer the lambda way is there any way of implementing this checkifalltrueandreset semantics with oneliner lambda expression which scans flags only oncerelated but not the same what is the most elegant way to check if all values in a boolean array are truenote i learn a lot from comments and answers thank you allstream is cool but it is not for thisbitset and its bitwisely atomic counterpart atomicbitset is more suitable for this so accepted as the answer thank otherssideeffects in map stream or generally functional programming are thiscouragedarraysstreamflagsforeachflag flag false in my code does not set anything,['java'] +1051172,javascript several corresponding array reducingsumup what is the cleanest way to reduce those array data id 1 1 1 3 3 4 5 5 5 v 101010 5 10 for each id there is a v corresponding what i want is sum up v for each id in this example the result should bedata id 1 3 4 5 v 30 15,['javascript'] +1051312,how can i determine if my react native app is a debug or release build from javascript code i would like to add some debugonly ui to my react native app but i cannot find any equivalent of rct debug or rct dev compiletime flags in the javascript environment is there oneuse case i want to add a status bar that shows the number of http requests initiated by my app obviously this is not part of a shipping app but it would help me check my work while in development and testing,"['javascript', 'ios']" +1051375,css select previous sibling i have a progress bar which has two childrenparts whenever each of this children is hovered the total height of the progress and its children will change i have managed to solve for the first children using the next sibling selector but i cannot find a solution for the second children the yellow part up to now i have solved this using jquery but i want to do this in pure cssfiddle starton mouseenter function thiscssheight 4px progress cssheight 4px mouseleave function thiscssheight progress cssheight progress wrap position relative height 4px max height of progress background f3f3f3progress appearance none mozappearance none webkitappearance none width 100 bordernone height 2px transitionall 25s easein cursor pointer backgroundcolor f position absolute top 0 left 0 thisplay blockprogresshover progresshover start height 4pxprogressvalue reset the default appearance webkitappearance none mozappearance none appearance none get rid of default border in firefox border none for ie10 color f8008cprogressvaluewebkitprogressbar backgroundcolor f bordernoneprogressvaluewebkitprogressvalue backgroundf8008cprogressmsprogressvalue backgroundf8008cprogressmozprogressbar backgroundf8008cprogressmsfill border nonestart height 2px transition all 25s easein cursor pointer backgroundcolor ffe232 position absolute top 0 left 0px width 30pxscript srcscriptdiv idprogress wrap progress min0 max1 value066 idprogressprogress div idstart stylethisplay inlineblock left 50pxdivdiv,"['javascript', 'jquery', 'html', 'css']" +1051813,how to debug android 60 permissions while migrating one of my apps to use the android 60 permissions system i found it very hard to debug permissions using the emulatorfindingsthisabling a permission in the app info screen does not reshow the grant permission dialog when using the requestpermissions methodreinstalling the app seems to be the only way to make the app show the grant permission dialog againwhat is the proper method to debug permission using the android emulator,['android'] +1051849,speeding up past60day mean in pandas i use data from a past kaggle challenge based on panel data across a number of stores and a period spanning 25 years each observation includes the number of customers for a given storedate for each storedate my objective is to compute the average number of customers that visited this store during the past 60 days below is code that does exactly what i need however it lasts forever it would take a night to process the c800k rows i am looking for a clever way to achieve the same objective fasteri have included 5 observations of the initial dataset with the relevant variables store id store date and number of customers customersnotefor each row in the iteration i end up writing the results using loc instead of eg rowlagged no of customers because row does not write anything in the cells i wonder why that is the casei normally populate new columns using apply axis 1 so i would really appreciate any solution based on that i found that apply works fine when for each row computation is done across columns using values at the same row level however i do not know how an apply function can involve different rows which is what this problem requires the only exception i have seen so far is diff which is not useful herethankssample datapddataframe store 0 1 1 1 2 1 3 1 4 1 customers 0 668 1 578 2 619 3 635 4 785 date 0 pdtimestamp20130102 0 1 pdtimestamp20130103 0 2 pdtimestamp20130104 0 3 pdtimestamp20130105 0 4 pdtimestamp20130107 0 code that works but is incredibly slowimport pandas as pdimport numpy as npdata pdread csvrossman no of custdatasetcsvdatadate pdto datetimedatadatedatacustomers datacustomersastypeintfor index row in dataiterrows d rowdate store rowstore time condition d datadatenptimedelta6460 d d datadate sub df dataloc time condition datastore store dataloc datadated datastore store lagged no customers sub dfcustomerssum dataloc datadated datastore store no of days lensub dfcustomers if lensub dfcustomers 0 dataloc datadated datastore store av no of customers intsub dfcustomerssumlensub dfcustomers,['python'] +1052112,force read of volatile variable an embedded project i am working on requires reading a specific location in memory but the value of that memory location is not needed currently i am reading the volatile variable into a dummy variable as in foo1 below but i am curious about the method in foo2void foo1void volatile uint32 t a volatile uint32 t 0xdeadbeef volatile uint32 t thiscard avoid foo2void volatile uint32 t a volatile uint32 t 0xdeadbeef asee the thissassembly compiled with gcc 472 and o3 foo1movl 0xdeadbeef eaxmovl eax 0x4rspret foo2movl 0xdeadbeef eaxretthe method in foo2 seems to work but i want to know if it is guaranteed to work and is not a side effect of the compiler version and optimizations i am using,['c'] +1052206,change toolbar colorstyle on searchview click i have simple question how i can change toolbars coloror theme to white when clicked on search iconi want toolbar to be whitewith back arrow colored blackgrey whenever search icon is clicked i have added searcview androidsupportv7widgetsearchview in menuitemthisto and then back to original toolbar color when back button is clicked,['android'] +1052396,open browser security info with js when i am on https the browser shows a secure icon in the address bar i can usually depending on browser click on this to see more info in a native popupsee chromes implementation hereother browsers implement equivalent featuresi want to draw attention to the security of my site by showing a picture of this icon by my buy cta and something that says check for this secure icon in your browser i want the more info section as in the screenshot to expand when my icon is clickedis this possibleapologies if question has already been answered i tried to search but not sure if this info box has a name so not sure what to search forthanksdavid,"['javascript', 'html', 'css']" +1052430,inheritance and recursion suppose we have the following classesclass a void recursiveint i systemoutprintlnarecursive i if i 0 recursivei 1 class b extends a void recursiveint i systemoutprintlnbrecursive i superrecursivei 1 now lets call recursive in class apublic class demo public static void mainstring args a a new a arecursive10 the output is as expected counting down from 10 arecursive10arecursive9arecursive8arecursive7arecursive6arecursive5arecursive4arecursive3arecursive2arecursive1arecursive0let us get to the the confusing part now we call recursive in class bexpectedbrecursive10arecursive11arecursive10arecursive9arecursive8arecursive7arecursive6arecursive5arecursive4arecursive3arecursive2arecursive1arecursive0actualbrecursive10arecursive11brecursive10arecursive11brecursive10arecursive11brecursive10infinite loophow does this happen i know this is a devised example but it makes me wonderolder question with a concrete use case,['java'] +1052467,android studio plugin is too old i was syncing fine and then suddenly when i tried to run a test on a device from android studio i started getting the error error1 0 plugin is too old please update to a more recent version or set android daily override environment variable i have looked around and i found from the gradle website that the latest version is 210 i tried adding that to my dependencies with no luck i have tried various version numbers with various errors like the following could not find comandroidtoolsbuildgradle21searched in the following locations i understand from all the searching i have done that its clearly a wrong version of gradle but what is the current version label i should be using and how do i know it is installed on my machine i have always kept android studio updatedso i currently have in the buildgradle dependencies classpath comandroidtoolsbuildgradle200alpha1,['android'] +1052557,call instead of callvirt in case of the new c 6 null check given the two methods static void m1person p if p null var p1 pname static void m2person p var p1 pname why the m1 il code use callvirtil 07 brfalses il 0012il 09 nopil 0a ldarg0il 0b callvirt instance string consoleapplication4personget nameand the m2 il use callbrtrues il 07il 04 ldnullil 05 brs il 0dil 07 ldarg0il 08 call instance string consoleapplication4personget namei just can guess that it because in m2 we know that p is not null and its likenew myclassmymethodis it trueif it is what if p will be null in other thread,['c#'] +1052613,how to initialize a web component from javascript let us say i have the following webcomponentlink relimport hrefmydialoghtmmydialog idmydialog1 headinga dialoglorem ipsummydialogsee here for more info and here however apart from attributes sometimes i would like to initialize it with some object that has a bunch of properties for examplevar obj heading hello there data1 123 name blabla this can be any type of data think some kind of data model here and maybe i get this model from the serverso i cannot send the above object within my html via attributes cause i might have alot of settings andor i might get it at a later point from the server so i need to do it in javascriptso what i have been doing is i have just been taking the object after it has been created initialize is a function i have inside my web componentmydialog1get0initializeobj and this works initialize is a function inside my web component butquestion 1 i wonder if this is the correct way to initialize a web component as it seems a bit messyalso if one instantiates a webcomponent in codebodyappendmydialog idblamydialogblaget0initializeobj question 2 can i assume on the second line that bla has been created here with all its methods funny enough this works but i thought maybe it would be better to wait for some kind of event or something that the component is ready,"['javascript', 'html']" +1052792,kotlin android extensions and fragments just have a quick problem how to use kotlin android extensions with fragmentsif i use them inside oncreateview i get this nre exception caused by javalangnullpointerexception attempt to invoke virtual method androidviewview androidviewviewfindviewbyidint on a null object referencehere is the fragment code package comobaiedtestrunfragmentimport androidosbundleimport androidsupportv4appfragmentimport androidutillogimport androidviewlayoutinflaterimport androidviewviewimport androidviewviewgroupimport comobaiedacaanrimport kotlinxandroidsyntheticmainfragment card selectorpublic class cardselectorfragment fragment val tag javaclasscanonicalname companion object fun newinstance cardselectorfragment return cardselectorfragment override fun oncreateviewinflater layoutinflater container viewgroup savedinstancestate bundle view var rootview inflaterinflaterlayoutfragment card selector container false btn ksetonclicklistener logdtag onviewcreated hello world return rootview,['android'] +1052846,why splice not work properly in angular js i am trying to make one demo in which i have one checkbox list i am able to thisplay the list using ngrepeat what i need if user click on one check boxonly one checkbox is checked it thisplay only one columns 100 width which user checked two column it thisplay two columns of equal width 50if user check three column it show three column of equal width as as if user checked four checkbox it show four column of equal width initially some of checkbox is checked checkedtrue my first step is to unchecked the checked option training 3 but after unchecked it still thisplay why i already use splice method here is my code init function init forvar i 0iselfdatalengthi var objselfdatai ifobjchecked selfselectedlistpushobj alertstarting selfselectedlistlength selfcheckboxclickfunctionobji ifobjchecked alertif selfselectedlistpushobj else alertelsei selfselectedlistsplicei1 alertselfselectedlistlength here is i am trying to thisplay div classcontainerfluid div classrow div ngrepeati in vmselectedlist classcolxs12vmselectedlistlength iname div div div,['javascript'] +1052879,numba 3x slower than numpy we have a vectorial numpy get pos neg bitwise function that use a mask132 20 192and a dfshape of 500e3 4 that we want to accelerate with numbafrom numba import jitimport numpy as npfrom time import timedef get pos neg bitwisedf mask in 1 print mask 132 20 192 in 1 print df 1 162 97 41 0 136 135 171 0 245 30 73 check npbitwise andmask df 1 maskallaxis1 pos df 0 1 check neg df 0 0 check pos npnonzeropos0 neg npnonzeroneg0 return pos negusing tips from morningsun we made this numba versionjitnopythontruedef numba get pos neg bitwisedf mask posneg npzerosdfshape0 2 for idx in rangedfshape0 vandmask npbitwise anddfidx 1 mask numba fail with if npallvandmask mask vandm equal m 1 for i val in enumeratevandmask if val maski vandm equal m 0 break if vandm equal m 1 if dfidx 0 1 posnegidx 0 1 else posnegidx 1 1 pos listnpnonzeroposneg 00 neg listnpnonzeroposneg 10 return pos negbut it still 3 times slower than the numpy one 006s vs 002sif name main df nparraynprandomrandint256 sizeint500e3 4 df 0 nprandomrandint2 size1 dfshape0 set target to 0 or 1 mask nparray132 20 192 start time pos neg get pos neg bitwisedf mask msg pos neg made p n in 4 s numpy print msgformatlenpos lenneg time start start time msg pos neg made p n in 4 s numba pos neg numba get pos neg bitwisedf mask print msgformatlenpos lenneg time start start time pos neg numba get pos neg bitwisedf mask print msgformatlenpos lenneg time startam i missing something in 1 run numba test2py pos neg made p3852 n3957 in 002306 s numpy pos neg made p3852 n3957 in 03492 s numba pos neg made p3852 n3957 in 006425 s numbain 1,['python'] +1052921,how to android dialog fullscreen embedded as in google calendar app what i would like to achivea smalarge screen behavior as it is implemented by google in its calendar appfor example when you create a new event on a large screen a dialog opensthat darkens the activity in the backgroundthe toolbar always stays at the same location and never gets pushed out of view by the onscreen keyboardin portrait mode the bottom of the dialogs toolbar is aligned with the bottom of the activitys extended toolbartoolbar alignment w activity toolbarthe contextual action bar eg for text selection is drawn over the toolbar of the activity and pushes the dialog down so it is not anchored with the activitys toolbar anymorein landscape mode it seems to be anchored below the notification bar the contextual action bar is drawn over the toolbar of the activitycontextual action bar left landscape right portraiton a small screen the dialog fills the screenthe contextual action bar gets drawn over the toolbarwhat i have tried so fara fullscreen dialogfragment expample from the android documentation cannot add anymore links bc of a lack of reputationwhen thisplayed as fullscreen dialog the background is transparent and it draws over the notification bar similar to immersive modeb added thanks to some posts on stackoverflowdialog fragment stylessetstyledialogfragmentstyle normal rstylemydialogfragmentstylestyle namemydialogfragmentstyle parentstylemytheme item nameandroidwindownotitletrueitem item nameandroidwindowfullscreenfalseitem item nameandroidwindowisfloatingfalseitemstyleremoved the window titlegetdialoggetwindowrequestfeaturewindowfeature no titleadded a custom toolbarxml version10 encodingutf8relativelayout xmlnsandroid xmlnsapp androidlayout widthmatch parent androidlayout heightmatch parent androidsupportv7widgettoolbar androidididtoolbar androidlayout widthmatch parent androidlayout heightwrap content androidbackgroundattrcolorprimary androidminheightattractionbarsize apphomeasupindicatordrawableic arrow back white 24dp appthemestylethemeoverlayappcompatdarkactionbar framelayout androidididcontent androidlayout widthmatch parent androidlayout heightmatch parent androidlayout belowidtoolbar framelayoutrelativelayoutand set the dialog to fullscreen on small devicesdialoggetwindowsetlayoutviewgrouplayoutparamsmatch parent viewgrouplayoutparamsmatch parentand this kinda works it solves some of my what i would like to achive points and a the android sample problems transparent background darkens the activity in the backgoundworksthe toolbar always stays at the same location and never gets pushed out of view by the onscreen keyboardkinda with the exception of the toolbar being pushed out of screen by the onscreen keyboardin portrait mode the bottom of the dialog toolbar is aligned with the bottom of the activitys extendedlarge toolbarthe contextual action bar eg for text selection is drawn over the toolbar of the activity and pushes the dialog down so it is not anchored with the activitys toolbar anymorenope did not put any effort into alignment bc of 2 the contextual action bar is drawn over the activitys toolbar and over part of the dialogs toolbarin landscape mode it seems to be anchored below the notification bar the contextual action bar is drawn over the toolbar of the activitynope onscreen keyboard pushes the toolbar out of screen and the contextual action bar is drawn over the activitys toolbar but also over part of the dialog bc of the dialogs toolbar being pushed outside i supposeit fills the screenworksthe contextual action bar gets drawn over the dialogs toolbarthe contextual action bar pushes the dialogs toolbar down leaving the user with two toolbars looks weird but at least it is functionalso my first post got a bit lenghty thanks to all who read along so fari have been researching this subject on and off for quite some time now some people say dialog fragments are no good for nonfullscreen thisplay and that one should style an activity to look like a dialog others say it is bad practice to style activities to look like dialogs bc that is what dialogfragments were made for there does not seem to be a broad agreement on this topicdoes anyone have any insight on how google implemented this in it is calendar app sadly in the aosp sources only the old calendar app is availableand is there a way to meet all my requirements with dialog fragmentsthanks a lotmichaelbtw large device tests on a android 41 tablet small device android 41 and 50 using support library dialogfragment but in the transition to normal dialogfragment,['android'] +1052999,checking divisibility for sort of big numbers in python i have been writing a simple program in python that encodes a string into a number using gadels encoding heres a quick overview you take the first letter of the string find its position in the alphabet a 1 b 2 z 26 and raise the first prime number 2 to this power the you take the second letter in the string and the second prime 3 and so on heres the codeimport string mathalphabet liststringascii lowercasedef primesn returns a list of primes up to n primes 2 3 i 5 while i n l mathceilmathsqrti k mathceilmathsqrti2 for p in primesl if i p 0 break else primesappendi for p in primesk if i2 p 0 break else primesappendi2 i 6 return primesdef encodestring encodes a string using godels encoding enc 1 p primes100 for i in rangelenstring enc encpialphabetindexstringi1 return encdef decodecode decodes a godels encoding into a string dec for i in primes100 count 0 while code i 0 code i count 1 if count 0 if weve found a prime that does not divide code there are no more letters to be added break else dec alphabetcount1 return decthe primes function works for my intends and purposes and so does encode now decode is the interesting part it works for encodings up to 15 digits long but starts doing some mystical stuff starting at 20 digits so for instance it gives the right output for the encoding of a but not for python for big numbers it seems to execute the while code i 0 loop too many times 176 for the first letter of python when it should be just 16 is this just a problem with the mod function in python sounds strange as 20 digits is not all that long for a computer is there a mistake in my code thanks for all the help i am not a programmer myself but i am trying to learn doing stuff like this therefore any constructive criticism is welcome,['python'] +1053082,parsing 2digit dates i am trying to read in a type of file with very old formattingin it the date format is specified at being in a yymmdd format where a 2digit year in the range 00 59 is considered to be in the 21st century and a year in the range 60 99 is considered to be in the 20th century such that 59 represents the year 2059 and 60 represents the year 1960how would i go about parsing this into a datetime in ci have tried doingstring str readdatefromfiledatetime dt datetimetryparseexactstr yymmdd cultureinfoinvariantculture datetimestylesnone out dtbut the default 2digit year rules treat values in the range 00 29 as 21st century and values in the range 30 99 as 20th centuryis there a way to modify this behaviour to do what i want or is there a different technique i could use,"['c#', '.net']" +1053134,how to get the value of multiple maximas in an array in python i have an array a 0 0 15 17 16 17 16 12 18 18i am trying to find the element value that has max count and if there is a tie i would like all of the elements that have the same max countas you can see there are two 0 two 16 two 17 two 18 one 15 and one 12so i want something that would return 0 16 17 18 order not important but i do not want the 15 or the 12i was doing npargmaxnpbincounta but argmax only returns one element per its documentation so i only get the 1st one which is 0i tried npargpartitionvalues 44 that works but in practice i would not know that there are 4 elements that have the same count number maybe i am close here the light bulb just went on,['python'] +1053264,android edittext no textselection handles are shown and no sharing option on an app screen i have a number of edittext views my app is built using the material design appcompactactivity etcwhile showing an edittext field with a long press i try to select a number of words in the text this allows me to copy or share that text selecting more than 1 word seems not possible since the migration to material design i see 2 things 1 after a long press there are no selection handles shown so on the place of the question marks i expected inverse waterdrops these are the handles you normally use to change the particular selection question why are these reverse eyedrops gone i do see them when selecting text in eg a webviewyes i use androidtextisselectabletrue below you see the edittext layout 2 the sharing option for the selected text is not available why what is the edittext field edittext androidididgeocache info hint androidlayout widthfill parent androidlayout heightwrap content androidtextsize15sp androidsinglelinefalse androidlines4 androidscrollhorizontallyfalse androidscrollbarsvertical androidlayout marginleft5dp androidellipsizenone androidtextisselectabletrue androidtextupon selection of a text in this case 1 word what i also see is that an extra bar tekstselectie textselection is put on top of the screen that is also a difference since android 4 solution in my theme i had a line that caused the problem of not showing any text selection handles item nameandroidpopupbackgroundcolorwindow backgrounditem the colorwindow background was chosen as white,['android'] +1053319,what will happen if is not put in a scanf statement in c i had gone to an interview in which i was asked the question what do you think about the followingint iscanf d iprintf i dn ii respondedthe program will compile successfullyit will print the number incorrectly but it will run till the end without crashingthe response that i made was wrong i was overwhelmedafter that they thismissed methe program would crash in some cases and lead to an core dumpi could not understand why the program would crash could anyone explain me the reason any help appreciated,['c'] +1053446,how to access type annotations on a receiver types parameters i am looking at a rather trivial class with a single method that defines an annotated receiver typeclass foot void foofoobar t this i would now like to access the type annotation on the receiver types parameter bar but the java reflection api returns an annotated raw type when accessing the receiverassert fooclassgetdeclaredmethodfoo getannotatedreceivertype instanceof annotatedparameterizedtypethe assertion fails as the annotated type that is returned is returned as a raw type foo is this intentional i can still find the bar annotation when accessing private properties of the implementation of annotatedtype that is returnedi am running a recent version of java 8,['java'] +1053459,pass a std container to a function i came up with the followingtemplate typename t inline void printcontainer stdvectort container for auto it containerbegin it containerend it stdcout it stdendl int tmainint argc tchar argv stdvectorint v vpush back5 vpush back4 vpush back3 printcontainerv return 0sorry for the push backs visual studio does not accept initializer listsughnow this function is limited to stdvector how can i make it so that i can pass other containers like stdlist arrays etc,['c++'] +1053464,android parse sdk io failure unknown format magic number 227b i am trying to recover my records from parse the class is called rating when i try to find less than 5 records there are no problems but when i try to find more records the next stack is showncomparseparserequestparserequestexception io failureat comparseparserequestnewtemporaryexceptionparserequestjava289at comparseparserequest2thenparserequestjava144at comparseparserequest2thenparserequestjava138at boltstask15runtaskjava839at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava1080at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava573at javalangthreadrunthreadjava841caused by javaioioexception unknown format magic number 227bat javautilzipgzipinputstreaminitgzipinputstreamjava101at javautilzipgzipinputstreaminitgzipinputstreamjava81at comparseparsedecompressinterceptorinterceptparsedecompressinterceptorjava40at comparseparsehttpclientparsenetworkinterceptorchainproceedparsehttpclientjava147at comparseparseplugins1interceptparsepluginsjava115at comparseparsehttpclientparsenetworkinterceptorchainproceedparsehttpclientjava147at comparseparsehttpclientexecuteparsehttpclientjava122at comparseparserequest3thenparserequestjava135at comparseparserequest3thenparserequestjava132at boltstask15runtaskjava839at boltsboltsexecutorsimmediateexecutorexecuteboltsexecutorsjava105at boltstaskcompleteaftertasktaskjava830at boltstaskcontinuewithtasktaskjava642at boltstaskcontinuewithtasktaskjava653at boltstask13thentaskjava745at boltstask13thentaskjava733 4 moreanyone has any clue why this is happening,['android'] +1053524,post multipart form data using retrofit 20 including image i am trying to do a http post to server using retrofit 20 mediatype media type text mediatypeparsetextplain mediatype media type image mediatypeparseimage bytearrayoutputstream bytearrayoutputstream new bytearrayoutputstream imagebitmapcompressbitmapcompressformatjpeg 90 bytearrayoutputstream profilepicturebyte bytearrayoutputstreamtobytearray callapiresults call serviceapiupdateprofile requestbodycreatemedia type text emailstring requestbodycreatemedia type image profilepicturebyte callenqueuethe server returns an error saying the file is not valid this is weird because i have tried to upload the same file with the same format on iosusing other library but it uploads successfullyi am wondering what is the proper way to upload an image using retrofit 20 should i save it to thisk first before uploadingthank youps i have used retrofit for other multipart request that does not include image and they completed successfully the problem is when i am trying to include a byte to the body,['android'] +1053553,core data privatequeue performblockandwait deadlock while accessing relationship this topic has been thiscussed at many forum but i am still not able to fully understand how performblockandwait actually works as per my understanding contextperformblockandwaitblock void will perform the block in its own queue while blocking the caller thread documentation says that you group astandarda messages to send to the context within a block to pass to one of these methodswhat are the standard messages it also says that setter methods on queuebased managed object contexts are threadsafe you can invoke these methods directly on any threaddoes that mean that i can set properties of a managed object which is fetched inside performblock api of a context outside performblock apis as per my understanding calling performblockandwaitblock void on context with concurrency type mainqueueconcurrencytype will create a deadlock and block ui forever when called from main thread but in my tests its not creating any deadlock the reason why i think that it should create a deadlock is that performblockandwait will first block the caller thread and then execute the block on its own thread since the thread in which context has to execute its block is the same as the caller thread which is already blocked so it will never be able to execute its block and the thread remains blocked foreverhowever i am facing deadlocks in some weird scenario i have below test codeibaction func fetchallstudentsofdepartmentsender anyobject let entity nsentitydescriptionentityfornamedepartment inmanagedobjectcontext privatecontext let request nsfetchrequest requestentity entity requestrelationshipkeypathsforprefetching students var department department privatecontextperformblockandwait void in department try selfprivatecontextexecutefetchrequestrequestfirst as department printdepartmentname guard let students departmentstudentsallobjects as student else return for student in students printstudentfirstname ibaction func fetchdepartmentsender anyobject let entity nsentitydescriptionentityfornamedepartment inmanagedobjectcontext privatecontext let request nsfetchrequest requestentity entity privatecontextperformblockandwait void in let department try selfprivatecontextexecutefetchrequestrequestfirst as department printdepartmentname privatecontextperformblockandwait void in let department try selfprivatecontextexecutefetchrequestrequestfirst as department printdepartmentname note that i accidentally pasted performblockandwait twice in fetchdepartment method in my test code it does not create any deadlock if i have not called fetchallstudentsofdepartment method but once i callfetchallstudentsofdepartment any call to fetchdepartment methodblocks the ui foreverif i remove printstudentfirstname in fetchallstudentsofdepartment method then it does not block that means it blocks ui only if i access a relationships propertyprivatecontext has concurrencytype set to privatequeueconcurrencytype the above code blocks ui only when privatecontexts parentcontext has concurrencytype set to mainqueueconcurrencytypei have tested the same code with other xcdatamodel as well and i am sure now that it only blocks if a relationships property is accessed my current xcdatamodel looks like pardon me if the information is extraneous but i am just sharing all my observations after spending like 8 hours already i can post my thread stack when ui is blocked to summarize i have three questionswhat are the standard messagescan we set properties of a managed object which is fetched inside performblock api of a context outside performblockwhy performblockandwait is misbehaving and causing ui block in my test codetest code you can download the test code from here,['ios'] +1053705,why does python allow function calls with wrong number of arguments python is my first dynamic language i recently coded a function call incorrectly supplying a wrong number of arguments this failed with an exception at the time that function was called i expected that even in a dynamic language this kind of error can be detected when the source file is parsedi understand that the type of actual arguments is not known until the function is called because the same variable may contain values of any type at different times but the number of arguments is known as soon as the source file is parsed it is not going to change while the program is runningso that this is not a philosophical questionto keep this in scope of stack overflow let me phrase the question like this is there some feature that python offers that requires it to delay checking the number of arguments in a function call until the code actually executes,['python'] +1053721,pointer to stack object without ownership i want to have a class with a pointer member variable this pointer should point to an object which may be stackallocated or heapallocated however this pointer should not have any ownership in other words no delete should be called at all when the pointer goes out of scope i think that a raw pointer could solve the problem however i am not sure if there is a better c11 approach than raw pointersexampleclass foopublic bar pntrint main bar a foo b bpntra,['c++'] +1053878,how to change default font of the android app i want to make an app in a non english language so i need the textviews strings and the toast to be in the nonenglish language setting the typeface for every text is cumbersome is there a way to set a default font when i have to refer to something in english like email id then i can use the textviewsettypefacexyz method,['android'] +1053979,how to stub exported function in es6 i have file foojsexport function bar m consolelogmand another file that uses foojs capjsimport bar from fooexport default m some logic that i need to test barmi have testjsimport cap from capdescribecap itshould bar capsome somehow i need override implementation of barm in test is there any way to do thisps i use babel webpack and mocha,['javascript'] +1054082,c union usage so far i have just used unions to store either member a or member b i do now find myself in the case where i want to change the used member during runtime union nextgen stdshared ptrtreerecord child nullptr stdvectorstdshared ptrtreerecord childrenmy current usagevoid treerecordaddchildconst stdshared ptrtreerecord newchild if childcount 0 nextgenerationchild newchild childcount else if childcount 1 this is not clear to me do i have to set child to nullptr first do i need to clear the children vecor or will it work like this nextgenerationchildrenpush back nextgenerationchild nextgenerationchildrenpush backnewchild childcount else nextgenerationchildrenpush backnewchild childcount new implementation trytypedef stdshared ptrtreerecord singlechild typetypedef stdvectorstdshared ptrtreerecord children typeunion singlechild type child children type childrenvoid treerecordaddchildconst singlechild type newchild if childcount 0 child newchild childcount 1 else if childcount 1 singlechild type currentchild child copy pointer childsinglechild type destruct old union member new children children type construct new union member childrenpush backcurrentchild add old child to vector childrenpush backnewchild add new child to vector childcount 2 else childrenpush backnewchild childcount,['c++'] +1054116,material design lite js not applied to dynamically loaded html file i want to unify the navigation layout for my website so i created a separate html file that holds the code for the navigation i use a js to load the file dynamicallynavigationloadnavigationnavigationhtml function getscriptmaterialminjsthe problem is that the materialminjs does not get executed for the dynamically loaded components inside this html and i lose some crucial functionality how do i fix that,"['javascript', 'jquery', 'html']" +1054179,understanding javascript objectvalue i understand that the following code wraps a number into an objectvar x object5i therefore expect and understand the followingalertx 5 truealertx 5 falsehowever i also understand that an object is a list of keyvalue pairs so i would have expected the following to be differentalertjsonstringify5 5alertjsonstringifyx 5what does the structure of x look like and why does it not appear to be in keyvalue pair format,['javascript'] +1054212,how can i show current location on a google map on android marshmallow i want google maps to show the location of the user i tried this code but it did not work on android 6private googlemap maplocationmanager lmlocationlistener location llatlng posoverrideprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutstart layout lm locationmanager thisgetsystemservicecontextlocation service ll new locationlistener override public void onlocationchangedlocation location l location location override public void onstatuschangedstring provider int status bundle extras override public void onproviderenabledstring provider override public void onproviderthisabledstring provider supportmapfragment mapfragment supportmapfragment getsupportfragmentmanager findfragmentbyidridnmap mapfragmentgetmapasyncthisoverridepublic void onmapreadygooglemap googlemap map googlemap ifcontextcompatcheckselfpermissionthis manifestpermissionaccess fine location packagemanagerpermission granted lmrequestlocationupdateslmnetwork provider 0 0 ll pos new latlnglgetlatitude lgetlongitude add a marker in sydney and move the camera mapsetmylocationenabledtrue mapaddmarkernew markeroptionspositionpostitlemarker in sydney mapmovecameracameraupdatefactorynewlatlngposhere are the permissions i have setusespermission androidnameandroidpermissionaccess fine location usespermission androidnameandroidpermissioninternet,['android'] +1054442,how to integrate recaptcha 20 in android is there any way i can integrate recaptcha 20 in androidi found this library and got it working however server side verification of the captcha is not supported it needs me to provide the private key in the code then verify it within the app instead of talking to my own serveris there a way to integrate recaptcha 20 in androidor is there a way for me to verify the captcha on my own server with that library,"['java', 'android']" +1054602,how do i run a compiled binary in android i have been trying to run a compiled binary in my android phone but it just keeps telling me no such file or directoryto be specific i compiled wificurse and as the description has mention to an arm command it is obvious that the source code can be compiled for an arm architecture without making any change to the makefile and so i did the followingexport cross compilearmlinuxgnueabimake cross compilearmlinuxgnueabiand then with the resulting binary wificurse i did the followingadb push wificurse datain a root adb shell i did rootandroiddata chmod 07 wificursereturns nothing works rootandroiddata chmod ux wificursereturns bad mode rootandroiddata busybox chmod 077 wificursereturns nothing works rootandroiddata busybox chmod ux wificursereturns nothing worksbut when i try to run the binary with rootandroiddata wificurseit returns systembinsh wificurse no such file or directorydid a ls in the folder and the binary is indeed therealready tried copying the binary to the internal sdcard then moving to data even tried systembin and systemxbin and it returns access denied but if i chmod the binary it will return the same error no such file or directory could someone help me please i have used the linux shell for 2 years though i am completely a noob when it comes to programming stuff i guess that i am missing something like a toolchain i do not knowi am running ubuntu 1510 x64,['android'] +1054661,how to install pillow on windows using pip i am trying to install pillow 31 on windows per the instructions i should be able to just type inpip install pillowbut i get valueerror jpeg is required unless explicitly thisabled using thisablejpeg abortingbecause now starting with versions after 30 i think libjpeg is required for pillow to be installed i do not know how to do that magic on windows maybe install ming or something but i was really hoping for a simple pip installi can thisable these options through the intuitive command pip install upgrade pillow globaloptionbuild ext globaloptionthisablejpeg globaloptionthisablezlibbut then the build fails because i do not have visual c installed yes i can install pillow by downloading it from the unofficial repository list but is there a way to do it with pip on windows without a lot of extra installs,['python'] +1054767,multipeer connectivity framework stability and recommendations i am working on a project that uses mc framework as a communication channel and after some tests i have the perception that this channel is somehow unstable to rely oni have been following apples documentations and videos in order to use the framework properly but happens thatpeers get thisconnected kinda often after paired and even more ofter if i pair more than one peersome data packages have mixed datais there any kind of recommendation to work with the frameworkie specific project settings ie is there something in the capabilities section that needs to be enabledmultithreading restrictions ie always call mc methods from the same threadrestrictions in terms of the amount of data to be senti found this link that mentions something about the framework not performing ok under stress that is the kind of advice i am looking for for the recordi am using an implementation based on this post since apples project is not working for mei am using only one mcsession for all peers i try to pair withencryption preference is set to mcencryptionnoneusing senddata and sendresourceaturl to communicate with peers,['ios'] +1054861,android google sign in is flashing a small empty white box while signing in a user basically android google sign in is flashing a small empty white box after the user presses the sign in button and before google finishes the sign in process this all happens pretty fast but i would like to get rid of the white box i assume this white box is a failed attempt to show a progress baredit adding a graphical recreation of what is happeningi am testing on samsung tab 3this problem does not include the situation where the user is signing in for the first time or after access has been revoked googlesigninoptions gso new googlesigninoptionsbuildergooglesigninoptionsdefault sign in requestemail requestidtokengetstringrstringgoogle server client id build google login stuff googlebutton comgoogleandroidgmscommonsigninbutton findviewbyidridgooglebutton googlebuttonsetonclicklistenerthis googlebuttonsetstylesigninbuttonsize standard signinbuttoncolor light build googleapiclient with access to basic profile mgoogleapiclient new googleapiclientbuilderthis enableautomanagethis fragmentactivity this onconnectionfailedlistener addapiauthgoogle sign in api gso buildand the sign in function private void gsignin intent signinintent authgooglesigninapigetsigninintentmgoogleapiclient startactivityforresultsigninintent rc sign inideally i would like to restore the normal progress bar behaviourhere is my gradleapply plugin comandroidapplicationandroid compilesdkversion 23 buildtoolsversion 2300 defaultconfig applicationid x minsdkversion 17 targetsdkversion 23 versioncode 1 versionname 10 buildtypes release minifyenabled true proguardfiles getdefaultproguardfileproguardandroidtxt proguardrulespro dependencies compile filetreedir libs include jar compile comandroidsupportappcompatv72301 compile comgoogleandroidgmsplayservicesidentity840 compile comgoogleandroidgmsplayservicesplus840 compile comgoogleandroidgmsplayservicesauth840 compile comgoogleandroidgmsplayservices840 compile comfacebookandroidfacebookandroidsdk410 compile comandroidsupportdesign2301,['android'] +1054867,how to decrease padding in numberpicker how to decrease padding in numberpicker i want something like it,['android'] +1054937,when to use an appcompatview vs a normal android view what is the difference between using them and when should they be usedan example of the documentation for an appcompatview isa tint aware edittext this will automatically be used when you use edittext in your layouts you should only need to manually use this class when writing custom viewswhy should the appcompatview only be used for custom viewsthere is a similar question but i am looking for a good explanation for why the appcompatview should only be used for custom views,['android'] +1054971,rabbitmq only listens to the first message on a queue i am having an issue with my rabbit queues that is currently only reacting to the first message in queue after that any other messages being pushed are being ignoredi start with instantiating the connection and declaring the queue in my iqueueconnectionprovidervar connectionfactory new connectionfactory hostname hostname var connection connectionfactorycreateconnectionvar channel connectioncreatemodelthat iqueueconnectionprovider is then used in my iqueuelistener as a dependency with just one methodpublic void listentoqueuestring queue var channel queueconnectionprovidergetqueue var consumer new eventingbasicconsumerchannel consumerreceived model ea string path ddebuglogtxt fileappendalinespath new liststring message received environmentnewline var body eabody var message encodingutf8getstringbody channelbasicackeadeliverytag false channelbasicconsumequeue true consumermy log file ends up being just one line message received however i can see in the rabbit ui interface that my other services are pushing the messages to that queue just fineis there something i am missing here,['c#'] +1055063,globbing using braces on ruby 193 recent versions of ruby support the use of braces in globbing if you use the filefnm extglob optionfrom the 220 documentationfilefnmatchcatubs cats filefnm extglob true is supported on fnm extglobhowever the 193 documentation says it is not supported in 193filefnmatchcatubs cats false is not supportedalso trying to use filefnm extglob gave a name erroris there any way to glob using braces in ruby 193 such as a thirdparty gemthe strings i want to match against are from s3 not a local file system so i cannot just ask the operating system to do the globbing as far as i know,['ruby'] +1055118,what is the best way to simulate javalangthread i am developing the transformer for java 6 that performs a kind of partial evaluation but let us consider for simplicity abstractsyntaxtree interpretation of a java programhow to simulate the threads behavior by an interpreted programat the moment i have in mind the followingastinterpreter should implement javalangrunnable it also should rewrite every newinstanceexpression of the javalangthread or its subclass replacing the threads target javalangrunnable with the new astinterpreter instanceedit more complex examples providedtarget programclass printdemo public void printcount try forint i 5 i 0 i systemoutprintlncounter i catch exception e systemoutprintlnthread interrupted class threaddemo extends thread private thread t private string threadname printdemo pd threaddemo string name printdemo pd threadname name pd pd public void run synchronizedpd pdprintcount systemoutprintlnthread threadname exiting public void start systemoutprintlnstarting threadname if t null t new thread this threadname tstart public class testthread public static void mainstring args printdemo pd new printdemo threaddemo t1 new threaddemo thread 1 pd threaddemo t2 new threaddemo thread 2 pd t1start t2start wait for threads to end try t1join t2join catch exception e systemoutprintlninterrupted program 1 threadtest bytecode interpretednew thread new runnable public void run threadtestmainnew string0 program 2 threadtest ast interpretedfinal comsunsourcetreetree tree parsethreadtestjavanew thread new astinterpreter public void run interpret tree public void interpretcomsunsourcetreetree javaexpression does the resulting program 2 simulate the threads behavior of the initial program 1 correctly,['java'] +1055136,swift programming style i saw some source code in github like thisfunctionalswiftwe can see there is definition of a struct called ship and therere some variable in it from the following code we can see that therere also some function in it it is written in the following stylestruct x extension x func y i can also definite the struct in the following stylestruct x func y so what the different of the two style is there a swift programming style guide,['ios'] +1055222,material design left margins for action bar title and content do not match i am trying to set screen margins following the guidelines for layout metrics and keylines specifically list content on mobile screens should have a margin of 72 dp and align with the title as shown in the guideas android studio automatically generates margin values in the resdimensxml i thought that i would get my content to align with the title by adding my own inner margindimensxmlresources default screen margins per the android design guidelines dimen nameactivity horizontal margin16dpdimen dimen nameactivity vertical margin16dpdimen 16 56 72 content left margin from screen edge dimen namecontent horizontal margin56dpdimenresourcesmyactivityxmlrelativelayout xmlnsandroid xmlnstools androidlayout widthmatch parent androidlayout heightmatch parent androidpaddingleftdimenactivity horizontal margin androidpaddingrightdimenactivity horizontal margin textview androidididtveditplaylistinfo androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentlefttrue androidlayout alignparenttoptrue androidlayout marginleftdimencontent horizontal margin androidtextappearanceandroidattrtextappearancemedium androidtexttest imagebutton androidlayout width36dp androidlayout height36dp androidsrcdrawableaction current androidlayout alignbottomidtveditplaylistinfo androidlayout torightofidtveditplaylistinfo androidlayout marginleft16dp listview androidididlvaudiofiles androidlayout widthmatch parent androidlayout heightwrap content androidlayout marginleftdimencontent horizontal margin androidlayout belowidtveditplaylistinfo listviewrelativelayoutbut somehow my content is off by about 8dp emulator lollipop 22 i am using a custom theme with parent themeappcompatlightdarkactionbar but i only changed colors so i think that is not the source of my problemwhat am i missing,['android'] +1055253,subscribing topics with google cloud messenger token invalid argument received i am following the example that google provides to register the gcm tokeni have generated correctly the googleservicesjson file and i am able to receive the push tokens but when i am trying to subscribe to any topic with the follow code register the user to the global topic this will help the device to be register on gcm gcmpubsub pubsub gcmpubsubgetinstancethis pubsubsubscribetoken topicsglobal nullit throws the invalid argument exception0105 140524435 dregintentservice 4330 javaioioexception invalid parameters0105 140524435 dregintentservice 4330 at comgoogleandroidgmsiidzzczzbunknown source0105 140524435 dregintentservice 4330 at comgoogleandroidgmsiidzzczzaunknown source0105 140524435 dregintentservice 4330 at comgoogleandroidgmsiidinstanceidzzcunknown source0105 140524435 dregintentservice 4330 at comgoogleandroidgmsiidinstanceidgettokenunknown source0105 140524435 dregintentservice 4330 at comgoogleandroidgmsgcmgcmpubsubsubscribeunknown source0105 140524435 dregintentservice 4330 at gcmplayandroidsamplescomgcmquickstartregistrationintentservicesubscribetopicsregistrationintentservicejava1050105 140524435 dregintentservice 4330 at gcmplayandroidsamplescomgcmquickstartregistrationintentserviceonhandleintentregistrationintentservicejava650105 140524435 dregintentservice 4330 at androidappintentserviceservicehandlerhandlemessageintentservicejava650105 140524435 dregintentservice 4330 at androidoshandlerthispatchmessagehandlerjava990105 140524435 dregintentservice 4330 at androidoslooperlooplooperjava1370105 140524435 dregintentservice 4330 at androidoshandlerthreadrunhandlerthreadjava60this is an example of push tokens that i receivese3r6xnfgk3eapa91bg9oy0a7qcf86bxxh8adzycct5qjuontxmh3papckcwty0a6uxo6zllx3hl3ubmgby65ldxuzzsf20nahzaq4siumrs0yystjtldk85lzroxm5kvm jigpakarn5tlb8d1opi have checked the documentation about subscribe a topic but there is nothing that says why i am receiving invalid parameter exceptionjavalangstring javalangstring androidosbundleany help is appreciatedpd there is the complete source code to register the tokensimport androidannotationsuppresslintimport androidappintentserviceimport androidcontentintentimport androidosbundleimport androidosresultreceiverimport androidutillogimport comgoogleandroidgmsgcmgcmpubsubimport comgoogleandroidgmsgcmgooglecloudmessagingimport comgoogleandroidgmsiidinstanceid intent service used to retrieve and save the registration token needed extracted from here public class registrationintentservice extends intentservice public static final string tag registrationintentservice public static final string intent key update server token callback servicesregistrationintentserviceintent key update server token callback private resultreceiver mresultreceiver public static final string bundle key gcm token servicesregistrationintentservicebundle key gcm token public registrationintentservice supertag suppresslintlonglogtag override protected void onhandleintentintent intent get the result receiver bundle extras intentgetextras if extras null extrascontainskeyintent key update server token callback mresultreceiver resultreceiverextrasgetintent key update server token callback try instanceid instanceid instanceidgetinstancethis string token instanceidgettokengetstringrstringgcm defaultsenderid googlecloudmessaginginstance id scope null logitag gcm registration token token todo send registration token to the server if mresultreceiver null bundle bundle new bundle bundleputstringbundle key gcm token token mresultreceiversend0 bundle register the user to the global topic this will help the device to be register on gcm gcmpubsub pubsub gcmpubsubgetinstancethis pubsubsubscribetoken topicsglobal null loggervtag user correctly register to the global token catch exception e logdtag faield to complete token refresh e and this is the content of the googleservicesjson project info project id not shownaa10f project number 11046079110 name not shown client client info mobilesdk app id 1046079110androidb918cc51ed907631 client id androidnot shown client type 1 android client info package name not shown oauth client api key services analytics service status 1 cloud messaging service status 2 apns config appinvite service status 1 other platform oauth client google signin service status 1 ads service status 1 client info artifact version 1,['android'] +1055469,espresso 2 on android intermediately tests fail after failing to start the activity under test while activities from previous tests are still alive i am using espresso 2 for testing my android app intermediately i see tests randomly fail with this espresso failure messagefailed testlongpressx comcompanyxteststestsuitetest begin exception androidsupporttestespressonomatchingviewexception no views in hierarchy found matching with id comcompanyxidx view idview hierarchydecorviewid1 visibilityvisible width729 height319 hasfocusfalse hasfocusablefalse haswindowfocustrue isclickablefalse isenabledtrue isfocusedfalse isfocusablefalse islayoutrequestedfalse isselectedfalse rootislayoutrequestedfalse hasinputconnectionfalse x00 y00 childcount1 every beginning of a test the espresso instrumentation prints out the number of activities that are still alive from a previous testmonitoringinstrumentation activities that are still in created to stopped numberwhenever i see a failed test i always see that the number of alive activities is not 0 which led me to believe that this is the reason for this issue even though most of the time when there are live activities before a test the test still passes successfully when this happens the device just shows the home screen for about 10 seconds before failing this of course happens only when i run more than one test at once my question is why are there live activities between tests and is there a way to make the instrumentation wait until the activities from the previous test are finished before proceeding to the next testif someone has a different idea to why the tests are failing intermediately that will also be helpful as well,['android'] +1055566,why sortable concept requires totally ordered value type while stdsort only requires less than comparable in the latest paper on concepts n3701 there is the following example with the sort algorithmtemplatetypename cont requires sortablecontvoid sortcont contwhere sortable concept is defined astemplatetypename tconcept bool sortable return permutable containert totally orderedvalue typetwhere totally ordered not surprisingly is defined as templatetypename tconstexpr bool totally ordered return weakly orderedt equality comparabletand in turn equality comparable is defined as templatetypename tconstexpr bool equality comparable return requirest a t b a b bool a b bool i did not find the definition of weakly ordered but i believe it should look like this am i righttemplatetypename tconstexpr bool weakly ordered return requirest a t b a b bool a b bool a b bool a b bool bottom line in this definition if i want to sort stdvectort i need t to provide all comparison operators however during the whole life of c stdsort only required operator to be provided here is what cppreference says about stdsortsorts the elements in the range first last in ascending order the order of equal elements is not guaranteed to be preserved the first version uses operator to compare the elements the second version uses the given comparison function object compso what does that mean that in future c with concepts for v of type stdvectort where t provides only operator stdsortvbegin vend will compile while stdsortv will not this sounds crazyi checked this in the current rangesv3 implementation by eric niebler and it works just like i described code does not compile unless all operators are providedsee also related thiscussion,['c++'] +1055638,when an anonymous class with no references to its enclosing class is returned from an instance method it has a reference to this why when an anonymous class with no references to its enclosing class is returned from an instance method it has a reference to this whyconsider the following codepackage soimport javalangreflectfieldpublic class soexample private static object getanonymousclassfromstaticcontext return new object private object getanonymousclassfrominstancecontext return new object public static void mainstring args throws nosuchfieldexception securityexception object anonymousclassfromstaticcontext getanonymousclassfromstaticcontext object anonymousclassfrominstancecontext new soexamplegetanonymousclassfrominstancecontext field fieldsfromanonymousclassfromstaticcontext anonymousclassfromstaticcontextgetclassgetdeclaredfields field fieldsfromanonymousclassfrominstancecontext anonymousclassfrominstancecontextgetclassgetdeclaredfields systemoutprintlnnumber of fields static context fieldsfromanonymousclassfromstaticcontextlength systemoutprintlnnumber of fields instance context fieldsfromanonymousclassfrominstancecontextlength systemoutprintlnfield from instance context fieldsfromanonymousclassfrominstancecontext0 this is the outputnumber of fields static context 0number of fields instance context 1field from instance context final sosoexample sosoexample2this0each method although seemingly calling the same code is doing something different it looks to me that the instance method is returning a nested class whereas the static method is returning a static nested class as a static member it obviously cannot have a reference to thisgiven the fact that there is no reference to the enclosing class i cannot see the benefit in thiswhats going on behind the scenes,['java'] +1055845,iosxmppframework cant able to login using gmail account i am developing one simple chat application using xmppframework from robbiehanson i have installed ejabberd server in my system and created some users i set hostname localhost and tried to login with that user credentials it is successfully logged in when i change the hostname ie hostnametalkgooglecom i cant able to login i got signin attempt prevented mail and failure xmlnsurnietfparamsxmlnsxmppsaslnotauthorizednotauthorizedfailurefyi boolconnectwithusernamensstringusername withpasswordnsstringpwd if xmppstream isthisconnected return yes nsstring myjid nsuserdefaults standarduserdefaults stringforkeykxmppmyjid nsstring mypassword nsuserdefaults standarduserdefaults stringforkeykxmppmypassword nsstring myjidusername nsstring mypasswordpwd if you do not want to use the settings view to set the jid uncomment the section below to hard code a jid and password replace me with the proper jid and password myjid xmppframework mypassword if myjid nil mypassword nil nslogjid and password must be set before connecting return no xmppstream setmyjidxmppjid jidwithstringmyjid password mypassword nserror error nil if xmppstream connectwithtimeout100 errorerror uialertview alertview uialertview alloc initwithtitleerror connecting messagesee console for error details delegatenil cancelbuttontitleok otherbuttontitlesnil alertview show nslogerror connecting error return no self goonline return yesam i need to register app in google developer console kindly provide me the solution to integrate gmail account in the xmppframework,"['ios', 'objective-c']" +1056073,best way to call many web services i have 30 sub companies and every one has implemented their web service with different technologiesi need to implement a web service to aggregate them for example all the sub company web services have a web method with name getuserpointint nationalcode and i need to implement my web service that will call all of them and collect all of the responses for example sum of pointsthis is my base classpublic abstract class baseclass all same attributes and methods public long getpointint nationalcodefor each of sub companies web services i implement a class that inherits this base class and define its own getpoint methodpublic class company1 implement own getpoint method call a web servicetopublic class companyn implement own getpoint method call a web serviceso this is my web method webmethod public long mycollectorstring nationalcode baseclass clients new baseclass new company1 new company1 long result 0 foreach var item in clients long resulttemp itemgetpointnationalcode result resulttemp return result ok it works but it is so slow because every sub companys web service is hosted on different servers on the interneti can use parallel programing like thisis this called parallel programing foreach var item in clients tasksaddtaskrun resultaddrangeitemgetpointmasterlogid mobilenumber i think parallel programing and threading is not good for this solution because my solution is io bound not cpu intensive call every external web service is so slow am i right many thread that are pending to get responsei think async programming is the best way but i am new to async programming and parallel programingwhat is the best way parallelforeach async tap async apm async eap threadingplease write for me an example,['c#'] +1056104,accessing element in an angular2 javascript es5 component edit as most comments so far give me the typescript solution i feel i need to repeat here using javascript es5i want to create a canvas component where i draw data based on a bound property how can i do this in angular2 using javascriptmy approach with angular 1 would be to get the element reference in the directive but i cannot find out how this is supposed to be done nowhere is an approach which seems to work but i feel like washing my hands after doing thisfunction app appdrawingcomponent ngcore component selector mydrawing template divcanvas idrandomidcanvasdiv class constructor function thisrandomid canvas mathrandom ngafterviewinit function var canvas documentgetelementbyidthisrandomid consolelogcanvas windowapp windowapp,['javascript'] +1056434,how can i split my click commands each with a set of subcommands into multiple files i have one large click application that i have developed but navigating through the different commandssubcommands is getting rough how do i organize my commands into separate files is it possible to organize commands and their subcommands into separate classesheres an example of how i would like to separate itinitimport clickclickgroupclickversion optiondef cli pass entry pointcommand cloudflarepycligroupclickpass contextdef cloudflarectx passcloudflaregroupzonedef cloudflare zone passcloudflare zonecommandaddclickoptionjumpstart j defaulttrueclickoptionorganization o defaultclickargumenturlclickpass obj cf error handlerdef cloudflare zone addctx url jumpstart organization passcloudflaregrouprecorddef cloudflare record passcloudflare recordcommandaddclickoptionttl tclickargumentdomainclickargumentnameclickargumenttypeclickargumentcontentclickpass obj cf error handlerdef cloudflare record addctx domain name type content ttl passcloudflare recordcommandeditclickoptionttl tclickargumentdomainclickargumentnameclickargumenttypeclickargumentcontentclickpass obj cf error handlerdef cloudflare record editctx domain passcommand uptimerobotpycligroupclickpass contextdef uptimerobotctx passuptimerobotcommandaddclickoptionalert a defaulttrueclickargumentnameclickargumenturlclickpass objdef uptimerobot addctx name url alert passuptimerobotcommanddeleteclickargumentnames nargs1 requiredtrueclickpass objdef uptimerobot deletectx names pass,['python'] +1056571,modifying a function to return username correctly for a wordpress plugin i have two wordpress plugins and both authors of the plugins refuse to admit the clashissue is their site but it is quite clear that both parties can fix the issue very easilyi provided one plugin author with the fix that has no negative impact on their plugin in any way it does not cause any problems if the person has the second plugin installed or not but they would not add the fix to their plugin even though it adds compatibility with a different plugini am unable to work out how to fix the second plugin but i know what needs to be donesnippet from plugin 1 one that i provided a fix to check if the user is valid if true wlm admin in admin true special bypass validuser username exists datausername if validuser validuser email exists dataemail user info get userdata validuser datausername user infouser login datapassword already assigned wishlistmember else validuser wp login datausername datapassword if validuser user thisget userdata 0 datausername check for blacklist status blacklist thischeckblacklist useruser email now if find the linevaliduser wp login datausername datapassword and replace it withvaliduser wp login datausername datapassword tmpvaliduser username exists datausername if tmpvaliduser validuser wp login datausername datapassword if validuser tmpvaliduser ifdataemail false strrposdatausername validuser email exists datausername user info get userdata validuser datausername user infouser login validuser wp login datausername datapassword then this fixes the issue because it changes the datausername variable to their actual username which means the rest of the plugin 1 will continue correctly and bind certain details to the username account rather than a username consisting of their email which obviously does not exist as a usernameif username exists they tried to login with username password then it continues like normalif username does not exist then it checks if the email exists instead if it does then it will grab the username from the email address that was entered and simply changes the entered username field with their actual username instead of their email and then continues like normalsnippet from plugin 2 one that i need a fix forfunction email login authenticate user username password if is a user wp user return user if empty username user get user by email username if isset user useruser login useruser status 0 int useruser status username useruser login result wp authenticate username password null username password if is a result wp user global wishlistmemberinstance wishlistmemberinstancewpmautologinuserid postlog username wishlistmemberinstancelogin return wp authenticate username password null username password i am not 100 sure what the above snippit does in full but i understand it good enough and i need to change it so that it returns the correct username somehow so that datausername is replaced with the username instead of the email if an email is used,['php'] +1056644,append div to td i am making snakes and ladders game i want to append player1 to the first cell in the board but it does not work as i expected i need help on how to solve itthis is the code i usedvar gameboard createboard functiondimension mount var mount documentqueryselectormount if dimension isnandimension parseintdimension 10 return false else dimension typeof dimension string parseintdimension 10 dimension var table documentcreateelementtable row documentcreateelementtr cell documentcreateelementtd rowclone cellclone var output for var r 0 r dimension r rowclone rowclonenodetrue tableappendchildrowclone for var c 0 c dimension c cellclone cellclonenodetrue rowcloneappendchildcellclone mountappendchildtable output gameboardenumerateboardtable return output enumerateboard functionboard var rows boardgetelementsbytagnametr text documentcreatetextnode rowcounter 1 size rowslength cells cellslength cellnumber odd false control 0 for var r size 1 r 0 r cells rowsrgetelementsbytagnametd cellslength cellslength rowsrclassname r 2 0 even odd odd control 2 0 true false size rowslength for var i 0 i cellslength i if odd true cellnumber size rowcounter i else cellnumber rowcounter cellsiclassname i 2 0 even odd cellsiid cellnumber cellsiappendchildtextclonenode cellsifirstchildnodevalue cellnumber rowcounter var lastrow rows0getelementsbytagnametd lastrow0id lastcell var firstrow rows9getelementsbytagnametd firstrow0id firstcell return gameboard windowonload functione gameboardcreateboard10 gridvar face1 new imageface1src d1gifvar face2 new imageface2src d2gifvar face3 new imageface3src d3gifvar face4 new imageface4src d4gifvar face5 new imageface5src d5gifvar face6 new imageface6src d6giffunction rolldice var randomdice mathfloormathrandom 6 1 documentimagesmydicesrc evalface randomdice src if randomdice 6 alertcongratulations you got 6 roll the dice again return randomdicefunction move firstcellappendplayer1movebody backgroundimage urlsnakesandladder2png backgroundrepeat norepeat backgroundsize 100 backgroundcolor 4f96cbtable width 100td borderradius 10px width 60px height 60px lineheight normal verticalalign bottom textalign left border 0px solid ftable trnthchildodd tdnthchildeventable trnthchildeven tdnthchildodd backgroundcolor powderbluetable trnthchildeven tdnthchildeventable trnthchildodd tdnthchildodd backgroundcolor skybluegame width 80 marginleft auto marginright autogameboardsection border 3px inset 0ff borderradius 10px width 65 float leftgrid zindex 1ladder position absolute top 300px left 470px webkittransform rotate30deg zindex 1 opacity 07bigsnake position absolute top 20px left 200px opacity 07 zindex 1player1 border 1px borderstyle solid position absolutediceandplayersection backgroundcolor lightgrey float left backgroundsize coverlastcell backgroundimage urlrotstar2 e0gif backgroundrepeat norepeat backgroundsize 100doctype htmlhtmlhead meta charsetutf8 titletitle link hrefstylesheet1css relstylesheet script srcjquery214minjsscriptheadbody div idgame div idgameboardsection div idgriddiv div idladder img srcoie erdoy2iqd5oqgif div div idbigsnake img srcoie 485727srn4kkbgpng div div idplayer1 styleborder 1px borderstyle solid positionabsolute styleposition absolute top 597px zindex 1 img srchumanpiecepng div div div iddiceandplayersection div idreset button typebutton nameresetnew gamebutton div div button typebutton nameresetresetbutton div div button typebutton nameaddplayeradd playerbutton div div iddicesection img srcd1gif namemydice onclickrolldice div div div script srcjavascript1jsscriptbodyhtmlthanks in advance,"['javascript', 'jquery', 'html', 'css']" +1057069,mobile safari multi select bug if found a really annoying bug on the current ios 92 mobile safari first appearing since ios 7if you using multi select fields on mobile safari like thisselect multiple option valuetest1test 1option option valuetest2test 2option option valuetest3test 3optionselectyou will have problems with automatically selectionios is automatically selecting the first option after you opened the select without any user interaction but it will not show it to you with the blue select checkso if you now select the second option the select will tell you that two options are selected but only highlighting one as selectedif you now close and open the select again ios will automatically deselect the first value if you repeat it will be selected again without any user interactionthats a really annoying system bug which is breaking the user experience,"['html', 'ios']" +1057114,should the interface define implementation specific enum values consider the following organization of classesinterface restaurant public void dineobject thishclass italianrestaurant implements restaurant public void dineobject thish eat with spoon and forks class chineserestaurant implements restaurant public void dineobject thish eat with chopsticks since both the restaurants serve completely different sets of thishes what will be the correct way designwise to represent the type of thish in the interfacewill it be a good design decision to define an enum listing all the thishes italian and chinese as a part of the interface and use that enum as type for thish,"['java', 'c#']" +1057279,force inotifydataerrorinfo validation i have implemented inotifydataerrorinfo exactly as described in the following linki have a textbox which is bound to a string property in my modelxamltextbox textbinding fullname validatesonnotifydataerrorstrue notifyonvalidationerrortrue updatesourcetriggerpropertychanged modelprivate string fullnamepublic string fullname get return fullname set set raises onpropertychanged setref fullname value if stringisnullorwhitespace fullname adderrornameoffullname name required else removeerrornameoffullname inotifydataerror codeprivate dictionarystring liststring errors new dictionarystring liststringpublic event eventhandlerdataerrorschangedeventargs errorschanged get errors by propertypublic ienumerable geterrorsstring propertyname if errorscontainskeypropertyname return errorspropertyname return nullpublic bool haserrors errorscount 0 object is validpublic bool isvalid haserrorspublic void adderrorstring propertyname string error add error to list errorspropertyname new liststring error notifyerrorschangedpropertynamepublic void removeerrorstring propertyname remove error if errorscontainskeypropertyname errorsremovepropertyname notifyerrorschangedpropertynamepublic void notifyerrorschangedstring propertyname notify if errorschanged null errorschangedthis new dataerrorschangedeventargspropertynamenow all this works fine but it only validates as soon as i type something in my textbox i would like some way to validate on demand without even touching the textbox say on a button click i have tried raising propertychanged for all my properties as described in this question but it does not detect the errors i somehow need my property setter to be called so the errors can be detected i am looking for a mvvm solution,['c#'] +1057351,c filereplace protecting against a crash does filereplace do an atomictransactional operation such that if there is a crash or power failure the destination file will never be missing nor a partial file ie will be the original or the new fileif not is there another method that would protect against this scenarionote this would be on an ntfs drive with windows 7 or later which i understand supports transactionsnote i am asking about saving in an atomic manor and not concerned about a separate process also having the file open like this question,"['c#', '.net']" +1057545,are function return values automatic objects and thus guaranteed to be destructed in exceptctor the standard n4140 guarantees thatdestructors are invoked for all automatic objects constructed since the try block was enteredhowever in the following example the empty output proves that the return value of function foo is not destructed although it has been constructed compiled using g 521 and clang 3621 and with options o0 fnoelideconstructors stdc14 struct a a cout an struct b b noexceptfalse throw 0 a foo b b return int main try foo catch is this a bug both in g and clang or are function return values notconsidered automatic objects or is it a loop hole in the c languagein none of stmtreturn exprcall or dclfct i have been able to finda clear statement whether a function return value is considered an automaticobject the closest hints i found are 633 p2a return statement can involve the construction and copy or move of a temporary objectand 522 p10a function call is an lvalue if the result type is an lvalue reference type or an rvalue reference to function type an xvalue if the result type is an rvalue reference to object type and a prvalue otherwise,['c++'] +1057596,unsupported operation android retrofit okhttp adding interceptor in okhttpclient i am trying to add token based authentication via retrofit 20beta3 and okhttpclient in android using interceptors but i get unsupportedoperationexception when i add my interceptor in okhttpclienthere is my codein apiclientjava public static trequantapiinterface getclientfinal string token if streqantapiinterface null logvretrofit log creating api client for the first time okhttpclient okclient new okhttpclient okclientinterceptorsaddnew interceptor override public response interceptinterceptorchain chain throws ioexception request original chainrequest request customization add request headers requestbuilder requestbuilder originalnewbuilder headerauthorization token methodoriginalmethod originalbody request request requestbuilderbuild return chainproceedrequest retrofit client new retrofitbuilder baseurlbaseurl clientokclient addconverterfactorygsonconverterfactorycreate build streqantapiinterface clientcreatetrequantapiinterfaceclass return streqantapiinterface and i use it like private void ampfreqtest string token getsharedpreferencesgetstringrstringpreference file key contextmode private getstringgetstringrstringkey token service apiclientgetclienttoken i get an exception on this line calistampfreq call servicegetuserampfreq1 callenqueuenew callbacklistampfreq override public void onresponseresponselistampfreq response toastmaketexthomescreenthis got result toastlength long logvapiclientretrofit log success api client responsemessage logvapiclientretrofit log success api client override public void onfailurethrowable t toastmaketexthomescreenthis tgetmessage toastlength long logvapiclientretrofit log fail api client tgetmessage but i get this errorprocess comtrequantusmantrequant android pid 14400javalangunsupportedoperationexception at javautilcollectionsunmodifiablecollectionaddcollectionsjava932 at comtrequantusmantrequant androidapiapiclientgetclientapiclientjava41it gives me error on adding a new interceptor saying that it is not modifiablecollection but the documentation for interceptors function says returns a modifiable list of interceptors that observe the full span of each call from before the connection is established if any until after the response source is selected either the origin server cache or both what am i doing wrong could it be a bug,"['java', 'android']" +1057606,pdo transaction not working i have a pdo transaction that im trying to run the first query creates a switch and the second adds information about it to another table my issue is that for some reason the 1st query does not execute correctly but the transaction is committed im using the following pdo class try insert into required tables dbbegintransaction dbqueryinsert into firewall namevaluesname dbbindnamename dbexecute dbqueryinsert into firewall switch switch id firewall idcustomer idvaluesswitchlast insert idcustomer dbbindswitchswitch dbbindcustomercustomer dbexecute dbendtransactioncatchpdoexception e dbcanceltransactionthe following is what gets run in sql from the logs 6 query start transaction6 prepare 6 insert into firewall namevalues6 prepare 7 insert into firewall switch switch id firewall idcustomer idvalueslast insert id6 execute 7 insert into firewall switch switch id firewall idcustomer idvalues2last insert id1646 query commitas you can see the first query never executes but the second does this particular transaction should have rolled back as there was a duplicate id which is not allowed if there are no duplicates then the transaction seems to complete as expected but im not sure why rollback does not workedit db class class db private static connection array public connection private dbh private error private stmt public static function getconnectionconnection ifarray key existsconnectionselfconnection classname class selfconnectionconnection new classnameconnection return selfconnectionconnection public function constructconnection global config load settings thisid uniqid thisconnection connection ifarray key existsconnectionconfigconnectionsdatabase dbconfig configconnectionsdatabaseconnection set dsn dsn mysqlhost dbconfighost portdbconfigportdbname dbconfigdatabase set options options array pdoattr persistent true pdoattr errmode pdoerrmode exception create a new pdo instantiate try thisdbh new pdodsn dbconfiguser dbconfigpassword options catch any errors catchpdoexception e thiserror egetmessage error logegetmessage create the sql query public function queryquery thisstmt thisdbhpreparequery bind sql params public function bindparam value type null if is nulltype switch true case is intvalue type pdoparam int break case is boolvalue type pdoparam bool break case is nullvalue type pdoparam null break default type pdoparam str thisstmtbindvalueparam value type execute the sql public function executearray null ifarray null return thisstmtexecute else return thisstmtexecutearray public function resultset thisexecute return thisstmtfetchallpdofetch assoc return single record public function single thisexecute return thisstmtfetchpdofetch assoc count rows in table public function rowcount return thisstmtrowcount show last id inserted into table public function lastinsertid return thisdbhlastinsertid transactions allows the tracking of multiple record inserts should one fail all will rollback public function begintransaction return thisdbhbegintransaction public function endtransaction return thisdbhcommit public function canceltransaction return thisdbhrollback debug dumps the info that was contained in a perpared statement public function debugdumpparams return thisstmtdebugdumpparams db structure create table firewall id int10 unsigned not null auto increment name varchar255 not null primary key id unique key name unique name unique key id unique id engineinnodb auto increment40 default charsetlatin1 create table firewall switch id int11 not null auto increment switch id int10 unsigned not null firewall id int10 unsigned not null customer id int11 not null primary key id unique key id unique id key fk firewall switch switch1 idx switch id key fk firewall switch firewall1 idx firewall id engineinnodb auto increment59 default charsetlatin1,"['php', 'mysql']" +1057690,how to create a restful resource controller in laravel 52 using artisan command php i am working with laravel 5 and i would like to know how to generate a restful resource controller with all predefined methods using the artisan command phpwhen i run php artisan makecontroller lessonscontroller it creates a controller with no methods as shown belowphpnamespace apphttpcontrollersuse illuminatehttprequestuse apphttprequestsclass lessonscontroller extends controllerwhat i want to create is a complete laravel restful resource controller with all predefined methods as in index create store show edit update and destroyhow can i achieve this,['php'] +1057715,what does two colons inside an angular expression mean think this may have been asked before but what is the difference betweenofficenameand officenamein angularjs,['javascript'] +1057719,array of structs in cuser input i am new to programming in general and to c in particular i am trying to write a program that uses an array of structs but i am experiencing problems if that struct contains strings somehow the compiler crashes after the user has given the last input the struct below is just a simplified version containing only one item because the problem seems to be reading strings into the array any help is much appreciated thanks in advance include stdiohinclude stdlibhinclude stringhtypedef struct char namestudentint main int size printfenter number of entriesn scanfd size student allmallocsizesizeofstudent int i fori0isizei printfenter namen scanfs alliname return 0,['c'] +1057890,choose three different values from list in python i have a list of points with their coordinates looking like this012371 and so onwhat is the pythonic way to iterate over them and choose three different every time i cannot find simpler solution than using three for loops like thisfor point1 in a for point2 in a if not point1 point2 for point3 in a if not point1 point3 and not point2 point3so i am asking for help,['python'] +1058206,react native errortimeout getting device list when running hello world on ubuntu i print reactnative runandroidand get the following outputfailure build failed with an exceptionwhat went wrong execution failed for task appinstalldebugcomandroidbuildertestingapideviceexception timeout getting device listtry run with stacktrace option to get the stack trace run with info or debug option to get more log outputbuild failedtotal time 1 mins 11385 secs could not install the app on the device read the error above for details make sure you have an android emulator running or a device connected and have set up your android development environment i have genymotion emulator running i have defined android home and pathexport android homehomejonstarkdocumentsandroidexport pathpathandroid hometoolsandroid homeplatformtoolsin sdk manager i have downloaded all required packageswhat do i do,['android'] +1058302,unable to select the value from the drop list i know question is quite simple for you people to answer but i got stuck at a drop list from where i wanted to select the birth monthi have been working on other websites but unfortunately couldnt get this to worki triedclick using different locatorsusing action class to mover hover and clickingusing java script to select the monthstrange thing is if i get the text of the webelement i am able to do so but not able to click on iturl of the application is a linkthis is when creating the account on googlei was trying to select the month from the list any monthi have got timeoutexception when i wait until the box has the desired monthapart from that i dont get any error the script always passes without making the selectioni know the question is quite easy but if anyone can help me get through itthanks in advancespan idbirthmonth class formerror ariainvalidtruediv classgooginlineblock googflatmenubutton jfkselect rolelistbox stylemozuserselect none ariaexpandedfalse tabindex0 ariahaspopuptrue ariaactivedescendant0 titlebirthdaydiv classgoogmenu googmenuvertical stylemozuserselect none visibility visible left 0px top 8223px thisplay none rolelistbox ariahaspopuptruediv id1 classgoogmenuitem roleoption stylemozuserselect nonediv id2 classgoogmenuitem roleoption stylemozuserselect nonediv classgoogmenuitemcontentfebruarydivdivdiv id3 classgoogmenuitem roleoption stylemozuserselect nonediv id4 classgoogmenuitem roleoption stylemozuserselect nonediv id5 classgoogmenuitem roleoption stylemozuserselect nonediv id6 classgoogmenuitem roleoption stylemozuserselect nonediv id7 classgoogmenuitem roleoption stylemozuserselect nonediv id8 classgoogmenuitem roleoption stylemozuserselect nonediv id9 classgoogmenuitem roleoption stylemozuserselect nonediv ida classgoogmenuitem roleoption stylemozuserselect nonediv idb classgoogmenuitem roleoption stylemozuserselect nonediv idc classgoogmenuitem roleoption stylemozuserselect nonedivinput idhiddenbirthmonth typehidden namebirthmonthspan,"['javascript', 'java']" +1058357,error in launching avd the filesystem is already 140800 4k blocks long nothing to do i got the error resize2fs 14213 17may2015the filesystem is already 140800 4k blocks long nothing to do when i try to run the avdi am using a mac and i have done all the necessary updates to the sdk managerdoes anyone know what might be,['android'] +1058522,in ruby on rails how can i create a scope for a has many relationship here is an examplelet says i have a student object which has a has many relationship with reportcard objects reportcard objects have a boolean field called graded that flags they have been graded so it looks likeclass student activerecord has many report cardsendclass reportcard activerecord graded boolean comes from db belongs to studentendnow let us say you want to create a default scope so that if a student has no graded reportcards you want to see all of them but if they have at least one graded reportcard you only want to see the graded ones finally let us say you order them by semester numberusing this scope on reportcard works correctlyscope only graded if possible student wheregraded true student studentordersemester numberpresence ordersemester number but i want it to be the default scope for student so i triedclass student activerecord has many report cards wheregraded trueordersemester numberpresence ordersemester number endbut this does not work it would not return any report cards if there is a single graded report card in the whole db looking at the queries that are run first it runs something likeselect report cards from report cards where reports cardsgraded t order by semester number asci think this must be the present check part of the presence query and notice it does not filter on student at all so if there is a single report card that is graded the check passes and then it runs the following query to get what to returnselect report cards from reports card where report cardstudent id student id here and report cardgraded t order by semester numberthis query actually would be correct if the student had a graded report card but it is always empty if he does noti assume that possibly the filtering on student is added afterwards so i tried to somehow to get it to filter student right off the bathas many report cards wheregraded true student selfordersemester numberpresence ordersemester number this does not work either because it appears that self in this scope is not the student object like i would assume but a list of all the report card ids here is the query this one runsselect report cards from report cards where report cardsgraded t and report cardsstudent id in select report cardsid from report cards order by semester number ascthat is not even close to correct how can i get this to worki think what it really comes down to is someone being able to pass self meaning the current student object as a parameter into the scope being applied in the has many maybe that is not possible,"['ruby-on-rails', 'ruby']" +1058535,how can i enforce googleapiclient to prompt account chooser ui each time i call connect whenever i run the code for the very first time at my 1st app launched cyclegoogleapiclient mgoogleapiclient new googleapiclientbuildercontext addapidriveapi addscopedrivescope appfolder required for app folder sample addconnectioncallbacksthis addonconnectionfailedlistenerthis buildmgoogleapiclientconnecti can see the following account chooserhowever if previous connect is success and i run the same code again for first time at my 2nd app launched cyclethe account chooser will not pop up again googleapiclient is going to use the account name i choose in previous app launch cyclei wish to have my account chooser pop up everytimei came across how to clear googleapiclient default account and credentialsthe proposed solution does not work for my casemgoogleapiclientcleardefaultaccountandreconnectif i had been connected for my previous app cycle and i call the above code first time in my current app cycle i will get the following exceptionjavalangillegalstateexception googleapiclient is not connected yet at comgoogleandroidgmscommoninternalzzxzzaunknown source at comgoogleandroidgmscommonapiinternalzzjcleardefaultaccountandreconnectunknown sourcethe following code would not work eitherif mgoogleapiclientisconnected no chance to execute this code if you run this code during app launch mgoogleapiclientcleardefaultaccountandreconnect else no account chooser will pop up if you had been connected in previous app life cycle mgoogleapiclientconnectmay i know how can i enforce googleapiclient to prompt account chooser ui each time i call connect,['android'] +1058549,preference subscreen not opening when using supportv7preference i am trying to implement preferences with subscreens using appcompatactivity and supportv7preferenceaccording to the docs every preferencescreen within another preferencescreen functions as a subscreen and the framework will handle thisplaying it when clickedpreferencescreen xmlnsandroid opens a subscreen of settings preferencescreen androidkeybutton voicemail category key androidtitlestringvoicemail androidpersistentfalse listpreference androidkeybutton voicemail provider key androidtitlestringvoicemail provider opens another nested subscreen preferencescreen androidkeybutton voicemail setting key androidtitlestringvoicemail settings androidpersistentfalse preferencescreen ringtonepreference androidkeybutton voicemail ringtone key androidtitlestringvoicemail ringtone title androidringtonetypenotification preferencescreen preferencescreenthis works fine using native activity preferencefragment but using appcompatactivity and preferencefragmentcompat clicking the preference element just highlights it but does not open the subscreeni could not find anything on this reading the docs and the code do i need to implement any additional callbacksedit just for completenessthis works and opens the subscreenpublic class mainactivity extends activity override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate if savedinstancestate null getfragmentmanagerbegintransaction replaceandroidridcontent new demopreferencefragment commit static public class demopreferencefragment extends preferencefragment override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate addpreferencesfromresourcerxmlpreferences this does not workopen the subscreenpublic class mainactivity extends appcompatactivity override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate if savedinstancestate null getsupportfragmentmanagerbegintransaction replaceandroidridcontent new demopreferencefragment commit static public class demopreferencefragment extends preferencefragmentcompat override public void oncreatepreferencesbundle bundle string s addpreferencesfromresourcerxmlpreferences edit 25012016after fiddling with supportv7preference for a few days i have summed up my findings here hoping it may help othershowto use supportv7preference with appcompat and potential drawbacks,['android'] +1058647,oneline if vs in javascript is there any meaningful difference betweencondition consolelogthis may runandif condition consolelogthis may runif not which is a best practice,['javascript'] +1058702,how tostringcall on object prototype is fetching the type of array i am looking at the code to find out whether an object is an array on not and i came across this answerthe code is working fine but i am not able to understand how it is performing a comparison with object array i tried to get the typeof array but it is throwing an error so i am confused with this codeif objectprototypetostringcall somevar object array i am interested to know how the tostringcall on an array method call on an object is correctly getting the type of an array object,['javascript'] +1058709,date type issue with like clause arabic string in mysql i work on old system and the search in popup was made dynamically for example if popup fields field1 field2 field3 and the user type u in the textbox for search or any arabic word the system will create a dynamic search condition like thisfield1 like u or field2 like u or field3 like uthe problem occur when one of these fields is date type in this case give me mysql error illegal mix of collations for operation likewhen i change the the word i search to be english word it give me warning but work correctly because i do not need the field of date type in this situation i search for textalso i cannot change the core of this dynamic search php function because all system was built so i cannot use like this codeor date formatfield1 ymd like ubecause i do not know which field is a date type it is a dynamic searchalso this issue occur on the hosting server only and not on my localhost my host is server version 5547cll mysql community server gpl and my localhost mysql version is 5this is show create table scriptcreate table pos quotations dept id varchar20 not null bill type int11 not null bill number int11 not null bill number to rtrn int11 not null salesperson name varchar255 not null bill date date not null pos id int11 not null stock id varchar20 not null currency id varchar3 not null exchange rate float not null salesperson type int1 not null salesperson id int10 not null client type int1 not null acc code varchar20 not null client name varchar255 not null client approval number varchar20 not null notes varchar255 not null bill value before thiscount double not null ovrall cost double default 0 sales tax double not null aditional amount double not null thiscount percentage double not null thiscount amount double not null bill value after thiscount double not null client payment decimal132 not null remaining amount decimal132 not null payment method int11 not null credit card details varchar255 not null bank operation number varchar50 not null bank details varchar255 not null bank acc code varchar20 not null payment method info varchar500 not null contract product details text not null contract rec voucher no varchar255 not null contract repayment date varchar255 not null rowid varchar255 not null year int4 not null creation user varchar10 default null creation timestamp varchar14 default null creation computer name varchar50 default null lastupdate user varchar10 default null lastupdate timestamp varchar50 default null lastupdate computer name varchar50 default null trans flag varchar10 default null record status varchar1 default null journal status tinyint1 default null process number varchar50 default null offer terms text technical specifications text offer status tinyint1 default null project description varchar500 default null pos contract agreement id varchar50 default null cost center code varchar50 default null primary key rowid engineinnodb default charsetutf8and whatever the charset of database on the hosting server it produce this error when charset is utf8 general ci or latin1 swethish ci thanks in advance,"['php', 'mysql']" +1058742,mfc toolbar how to set dropdown button width i am developing an mfcbased c application using visual studio 2010 there is a ctoolbarctrl with some dropdown buttons next to iconsa user running windows 8 has reported that they cannot see one of the icons in this toolbar they provided a screenshot which shows that they are running windows 8 at 150 ui zoom my application is currently set to not be dpiaware so this should actually not make a difference edit apparently it does make a difference after all they no longer have the problem when switching to 96 dpias can be seen in the screenshots below the toolbar dropdown buttons are much wider on their windows installation than they should be the spacing between the icons in the left toolbar is thus so big that the last icon cannot be seen anymore the right toolbar in the screenshot which does not have any dropdown buttons appears as intendedmine as it should betheirs dropdown buttons too widemy application already sets the icon 16x16 and button 27x24 sizes but that obviously does not affect the dropdown button sizeso my question is why is it possible that the dropdown buttons can be wider than on my default windows installation and how can i change them to be the default size so that all icons fit into the toolbar i did not find any api that could actually set the toolbar dropdown button widthinit code in my class derived from ctoolbarctrlsetbuttonstructsizesizeoftbbuttonsetbitmapsizecsize16 16setbuttonsizecsize27 24setimagelisticonssetthisabledimagelistthisablediconslong lstyleold getwindowlongm hwnd gwl stylelstyleold ccs noresize ccs noparentalign ccs nodivider tbstyle tooltips tbstyle flatsetwindowlongm hwnd gwl style lstyleold,['c++'] +1058750,selecting random values from dictionary let us say i have this dictionarydict a 100 b 5 c 150 d 60i get the key which has greatest value with this codemost similar maxdiciteritems keyoperatoritemgetter10it returns cbut i want to select a random key from top 3 greatest values according to this dictionary top 3 arecadit should randomly select a key from them how can i do that,['python'] +1058823,byte buddy create implementation for an abstract class i would like to create an implementation at runtime for an abstract class using byte buddy and i am facing the issue that a javalangabstractmethoderror is being thrown when invoking a method from a created instance i have an existing abstract class like this which i actually cannot modify and which actually contains more logicpublic abstract class algorithm abstract int executeusing the following minimal sample i would like my algorithm instance to return a constant valueclass type new bytebuddy subclassalgorithmclass methodelementmatchersnamedexecute interceptfixedvaluevalue42 make loadclassloader classloadingstrategydefaultwrapper getloadedalgorithm instance algorithm typenewinstancesystemoutprintlnmyinstanceexecutethis however leads to the following exceptionexception in thread main javalangabstractmethoderror packagealgorithmexecuteiwhen i experimentally change algorithm to an interface everything works fine but this does not solve my specific issue,['java'] +1058867,google calendar api when accessing domain users calendar accessrole is always freebusyreader i am trying to read a users calendar with a service account the calendar of the user is shared with the service account with accessrole reader however when i open the calendar of any user it is always opened as freebusyreaderfirst i am adding the user into the calendar list i had the impression that it is working better when it is in the list no idea if this is really neededdim calendar as calendarlistentrycalendar servicecalendarlistinsertexecutethen i am checking the access role withcalendaraccessroleand it always returns freebusyreaderthis does also match the results in the request afterwardsdim requeust as listrequest serviceeventslistemail addressrequeustmaxresults 99requeusttimemin datetimenowtostringdateformatrequeusttimemax datetimenowadaysfetchtimespantostringdateformatrequeustshowdeleted truerequeustsingleevents trueis returning a list of entries but without the summary and the events list does also have the same accessrolewhat i did on the user is sharing the calendar with the service users email address i did also verify that via the apiany ideas,['.net'] +1058876,since tuples are immutable why does slicing them make a copy instead of a view as far as i understand it tuples and strings are immutable to allow optimizations such as reusing memory that would not change however one obvious optimisation making slices of tuples refer to the same memory as the original tuple is not included in pythoni know that this optimization is not included because when i time the following function time taken goes like on2 instead of on so full copying is taking placedef testn tup tuplerangen for i in xrangen tup0iis there some behavior of python that would change if this optimization was implemented is there some performance benefit to copying even when the original is immutable,['python'] +1058913,gradle build failed on android studio old and new versions on osx i had a successfully building project when i was working on my pc and i committed and pushed it to my git repo before migrating to osxnow i installed android studio latest version on osx and tried to build the same project and it gives errors in building resources while building resources in manifest it gives multiple errors that say no resource found that matches the given namefor drawables and strings on looking through web i thought maybe the newer version of gradle has some issues so i downgraded my installation of as to as 10 and used the old gradle 22 unfortunately this version of gradle also gives the same errormy buildgradle looks like belowapply plugin comandroidapplicationandroid compilesdkversion 21buildtoolsversion 2112defaultconfig applicationid x minsdkversion 16 targetsdkversion 21 versioncode 4 versionname 13buildtypes release minifyenabled false proguardfiles getdefaultproguardfileproguardandroidtxt proguardrulespro sourcesets main ressrcdirs srcmainres dependencies compile filetreedir libs include jarcompile fileslibsthermodosdk1018jarcompile comandroidsupportappcompatv72103compile comgoogleandroidgmsplayservices6587compile comandroidsupportsupportv42103the buildgradle at top level has the following classpathdependencies classpath comandroidtoolsbuildgradle100stacktraceinformationgradle tasks appgeneratedebugsources appgeneratedebugtestsourcesaprebuildapredebugbuildappcheckdebugmanifestaprereleasebuildapreparecomandroidsupportappcompatv72103library uptodateapreparecomandroidsupportsupportv42103library uptodateapreparecomgoogleandroidgmsplayservices6587library uptodateapreparedebugdependenciesappcompiledebugaidl uptodateappcompiledebugrenderscript uptodateappgeneratedebugbuildconfig uptodateappgeneratedebugassets uptodateappmergedebugassets uptodateappgeneratedebugresvalues uptodateappgeneratedebugresources uptodateappmergedebugresources uptodateaprocessdebugmanifest uptodateaprocessdebugresourcesusersvidhigoelandroidstudioprojectsomgandroidappbuildintermediatesmanifestsfulldebugandroidmanifestxmlerror24 23 no resource found that matches the given name at icon with value drawableomg app iconerror25 24 no resource found that matches the given name at label with value stringapp nameerror27 24 no resource found that matches the given name at theme with value styleappthemeerror30 28 no resource found that matches the given name at label with value stringapp nameerror86 28 no resource found that matches the given name at label with value stringapp nameerror105 28 no resource found that matches the given name at label with value stringapp nameerror123 28 no resource found that matches the given name at label with value stringapp nameerror137 28 no resource found that matches the given name at label with value stringtitle activity register userinformationbuild failedinformationtotal time 4462 secsinformation17 errorsinformation0 warningsinformationsee complete output in consoleplease help me fix this problem,['android'] +1058949,custom checkbox using only css and html i need to create a custom checkbox using only html and css so far i havehtmlcsscheckboxcustom opacity 0 position absolutecheckboxcustomcheckboxcustomlabel thisplay inlineblock verticalalign middle margin 5px cursor pointercheckboxcustom checkboxcustomlabelbefore content background f borderradius 5px border 2px solid d thisplay inlineblock verticalalign middle width 10px height 10px padding 2px marginright 10px textalign centercheckboxcustomchecked checkboxcustomlabelbefore content thisplay inlineblock width 1px height 5px border solid blue borderwidth 0 3px 3px 0 transform rotate45deg webkittransform rotate45deg mstransform rotate45deg borderradius 0px margin 0px 15px 5px 5pxdiv input idcheckbox1 classcheckboxcustom namecheckbox1 typecheckbox label forcheckbox1 classcheckboxcustomlabelfirst choicelabeldivdiv input idcheckbox2 classcheckboxcustom namecheckbox2 typecheckbox label forcheckbox2 classcheckboxcustomlabelsecond choicelabeldivthe checked checkbox should be a checkmark with the square bordered around it instead of just a checkmark searching for answers i have only found cases where the checkmark is thisplayed using a utf8 character or an image i am not able to use either of these for what i am trying to accomplish i am only able to use plain css and html any suggestionscodepen here,"['html', 'css']" +1059008,global vs local namespace performance difference why is it that executing a set of commands in a functiondef main do stuff return somethingprintmainwill tend to run 15x to 3x times faster in python than executing commands in the top leveldo stuffprintsomething,['python'] +1059093,changing session file names in laravel 51 so laravel saves it is own session files when someone accesses the website in the storageframeworksessions folder each of these session files names are a randomly generated alpha numeric unique name but i would like to somehow rename the files and give my own custom name for it i have got two options for thatchange the file name manually once the session file is created by a create copy replacefind the function which randomly generates the alphanumeric name and change it with my own way of setting a unique name to each file this method might come with less complicationsmy main end goal is to rename each users session file to their own userid that is stored in my db so the names are still unique the only difference is that i can search through the files easier than if they had random alphanumeric namesso if anyone knows how i could do any of the above methods or if you can think of a better way to achieve the same it would be great any help is greatly appreciated edit decided to update here with what i had decided to do finally i decided not to use the built in session files generated by laravel and realized it is much easier to make my own file and just have each client access it instead thanks to all,['php'] +1059204,why does symbolmatch behave differently from stringmatch and regexpmatch stringmatch and regexpmatch return a matchdata when match succeedsmatch matchdata match matchdata match matchdata but symbolmatch returns the match position like stringmatch 0why does symbolmatch behave differently is there a use case,['ruby'] +1059378,why does the smallest int a2147483648 have type long for a school project i have to code the c function printf things are going pretty well but there is one question i cannot find a good answer to so here i amprintfprintfd t dn 2147483648tells me gcc werror wextra wall error format specifies type int but the argument has type long werrorwformat printfprintfd t dn 2147483648 ldbut if i use an int variable everything is going wellint ii 2147483648printfd iwhyedit i understood many points and were very interesting anyway i guess printf is using the stdargh librairy and so va argva list ap type should also return the right type for d and i obviously the type returned is an int does it change anything,['c'] +1059582,angular2 5 minute install bug require is not defined i am doing the angular2 5 minute quick startabout half way through the tutorial now i have the following files setup correctlyindexhtmlappcomponenttsappboottspackagejsontconfigjsonran npm start and am getting this erroruncaught referenceerror require is not definedanonymous function bootjs1angular2polyfillsjs143uncaught typeerror cannot read property split of undefinedreadmemberexpression systemsrcjs1456anonymous function systemsrcjs3224anonymous function systemsrcjs3749complete systemsrcjs2487run angular2polyfillsjs138zoneboundfn angular2polyfillsjs1i found this link about using the es6 shim and i included script srcnode moduleses6shimes6shimjsscripthowever i am still getting the uncaught referenceerror require is not defined errorappcomponenttsimport component from angular2corecomponent selector myapp template h1my first angular 2 apph1export class appcomponent appboottsimport bootstrap from angular2platformbrowserimport appcomponent from appcomponentbootstrapappcomponentindexhtmlhtml head titleangular 2 quickstarttitle 1 load libraries script srcnode moduleses6shimes6shimjsscript script srcnode modulesangular2bundlesangular2polyfillsjsscript script srcnode modulessystemjsthistsystemsrcjsscript script srcnode modulesrxjsbundlesrxjsscript script srcnode modulesangular2bundlesangular2devjsscript 2 configure systemjs script systemconfig packages app format register defaultextension js systemimportappboot thennull consoleerrorbindconsole script head 3 thisplay the application body myapploadingmyapp bodyhtmlpackagejson name angular2quickstart version 100 scripts tsc tsc tscw tsc w lite liteserver start concurrent npm run tscw npm run lite license isc dependencies angular2 200beta0 systemjs 0196 es6promise 302 es6shim 03 reflectmetadata 012 rxjs 500beta0 zonejs 0510 devdependencies concurrently 100 liteserver 131 typescript 173 tconfigjson compileroptions target es5 module system moduleresolution node sourcemap true emitdecoratormetadata true experimentaldecorators true removecomments false noimplicitany false exclude node modules the compiled appbootjslast log from npm start,['javascript'] +1059702,swift maps how to tell next intersecting street on my route i am writing an ios app in swift i need to be able to tell at any given point in time what street will be intersecting next on my users route who is drivingwalkingi am able to find the street name user is currently on the direction user is moving in and also the current coordinates but the last step stumps me which street will intersect nexti am open to using apple maps google maps osm etc as long as it if free,['ios'] +1059731,django query expression for calculated fields that require conditions and casting i am trying to run an aggregation query that is roughly equals toselect sumimpressions as impressions sumclicks as clicks sumclickssumimpressions as ctr from stats group by productorder by ctrthe database used is postgresqli made this query expression django 19statsobjectsvaluesproductannotate impressions modelssumimpressions clicks modelssumclicks ctr modelsexpressionwrapper modelsfclicksmodelsfimpressions output field modelsfloatfield order byctrthere are 2 problems with itctr is 00 because it divides integers at the database levelit throws division by zero if impressions are 0what is the proper solution,['python'] +1059745,how to use html5shiv correctly how work on ie 9 firefox safari questionhow does html5shiv work on ie9 when the conditional comment used if lt ie 9 is for ie8 and below and do safari 4x and firefox 3x read ie conditional comments if not how could html5shiv possibly work on these browsers using the conditional comments as suggested in their github instructionsthere was a question here asking if it can be used in every browser without conditional comments and what the side effects would be but that was not my question that question was asked 4 years ago html5 is now standard and microsoft no longer provides support for legacy browsers so loading it in every browser would be insane at this point and i wouldnt consider that my question has to do with the documentation on github what html5shiv provides out of the box using that documentation and how to use it today to support the browsers it claims to supportquoting the readme on github in regards to the html5shiv scriptit also applies basic styling for html5 elements for ie69 safari 4x and ff 3xuseageif lt ie 9 script srcbower componentshtml5shivthisthtml5shivjsscriptendifin the past year ie 8 and 9 combined have dropped from about 4 to about 2 in global useage according to stat counter since microsoft dropped support for legacy browsers on january 12th it seems like html5shiv might now or soon be a thing of the past it will be interesting to see how much these legacy ie browsers drop in year to comehowever depending on what you are developing you may still want to support these browsers when you include safari 4x and firefox 3 in the above stats the total browser share that html5shiv supports is 23 for most people that is nothing but if you own an ecommerce site 23 could be hugein regards to my actual question i am thinking i either overlooked something in the documentation or do not understand ie conditional comments well enough logically i would think this would be the best way to do it conditional comments in ie work through versions 5 to 9 so we should not have the script load in ie5 for no reasonif ie 5 script srcbower componentshtml5shivthisthtml5shivjsscriptendifhowever in the past 5 years i have never actually seen anyone doing it this way so i am obviously missing something plus i still do not see how this would work for ff 3 and safari 4 unless there is a bug or something that causes them not to read the comments i opened this topic on html5shiv github regarding this issue as well but have not been able to get an answer html5shiv is easily being used on millions of websites with most developers and site owners assuming it supports ie9 safari 4 and ff 3 out of the boxalso as far as i am aware in regards to ie9 this is all that html5shiv does to support it articleasidedialogfigcaptionfigurefooterheaderhgroupmainnavsectionthisplayblockmarkbackgroundff0color0if that is true it may be another reason for many to stop using it considering when you take that out the equation and include it in your css or a css reset youre down to 139 of browsers that html5shiv would actually have an impact on,['javascript'] +1059986,gae deploy pagespeed warning form this morning january 12 2016 there is a warning message appearing when we deploy to google app engine we do not use pagespeed so it is surprising that it tries to post something to its url95 closing update new version is ready to start serving98 uploading index definitionsi 12 2016 104506 dop comgoogleappenginetoolsadminabstractserverconnection send1warning error posting to url app idxversion1404 not foundyou are using a decommissioned api please upgrade to a more recent version of the app engine sdk which can be found atthis is try 0we use latest gae sdk 1930 latest gradle appengine plugin 1930 and gradle task that we run is appengineupdatewhy is that pagespeed warning appearing now and was not appearing before how can we get rid of itthanksmichal,['java'] +1059988,duplicates in ngoptions i am using angularjs version 147 and have simple angularjs controller which contains array of objects i would like to thisplay these objects as options in select by ngoptionsthe problem is that every object is duplicate and i do not know why this duplicate is presented in the select only the source object looks fine angular moduledemo controllerdemoctrl democtrlfunction democtrl var vm this vmdemooptions value 1 label demo 1 value 2 label demo 2 value 3 label demo 3 vmselected nullscript srccdnjscloudflarecomajaxlibsangularjs147angularminjsscriptdiv ngappdemo ngcontrollerdemoctrl as vm select ngoptionsitem as itemlabel for item in vmdemooptions track by itemvalue ngmodelvmselected option value selected ngifvmselected null select option select p ngifvmselected nullselected item codevmselectedcodep p ngifvmselected nullno item is selectedp prevmdemooptions vmdemooptionsjsonpredivis it a bug how can i remove duplicates without using a filternote this problem has occurred after update angularjs from version 1319 to 147 i read the changelog but it tells only about addition of track by i added it but with no effect,['javascript'] +1060284,proguard and recyclerview item decoration i am experiencing somewhat unexpected behavior with itemdecoration for recyclerview elementson some phones samsung android 5 devices my itemdecoration is not showing when proguard is applied with the build minify true without proguardminify it is working fine you can see the itemdecoration between the elements of the recycler on most phones the issue does not exist you can see the item decoration with or without proguard appliednot sure what happens there but any input is appreciatedthe item decorator codeimport androidcontentcontextimport androidgraphicscanvasimport androidgraphicsdrawabledrawableimport androidsupportv4contentcontextcompatimport androidsupportv7widgetrecyclerviewimport androidutillogimport androidviewviewpublic class divideritemdecoration extends recyclerviewitemdecoration private drawable mdivider public divideritemdecorationcontext context mdivider contextcompatgetdrawablecontext rdrawableline divider override public void ondrawovercanvas canvas recyclerview parent recyclerviewstate state int left parentgetpaddingleft int right parentgetwidth parentgetpaddingright int childcount parentgetchildcount for int i 0 i childcount i view child parentgetchildati recyclerviewlayoutparams params recyclerviewlayoutparams childgetlayoutparams int top childgetbottom paramsbottommargin int bottom top mdividergetintrinsicheight int margin 30 mdividersetboundsleft margin top right margin bottom mdividerdrawcanvas line dividerxmlxml version10 encodingutf8shape xmlnsandroid androidshaperectangle size androidwidth1dp androidheight1dp solid androidcolorffc6c6c6 shapeproguard ruleskeepclassmembers class fqcnofjavascriptinterfaceforwebview public support design librarydontwarn androidsupportdesignkeep class androidsupportdesign keep interface androidsupportdesign keep public class androidsupportdesignr retrofitdontwarn retrofitkeep class retrofit keep class commyappspackagecatalog okhttpdontwarn okiokeep class okio dontwarn orgslf4jkeep class orgslf4j keep class androidsupportv7 keep interface androidsupportv7 keepattributes signaturekeepattributes exceptionsgoogle analytics keep class comgoogleandroidgms keep public class comgoogleandroidgms dontwarn comgoogleandroidgmsgradle build logexecuting tasks clean appgeneratereleasesourcesconfiguration on demand is an incubating featureappcleanaprebuild uptodateaprereleasebuild uptodateappcheckreleasemanifestapredebugbuild uptodateapreparecomandroidsupportappcompatv72311libraryapreparecomandroidsupportcardviewv72311libraryapreparecomandroidsupportdesign2311libraryapreparecomandroidsupportrecyclerviewv72311libraryapreparecomandroidsupportsupportv42311libraryapreparecomcrashlyticssdkandroidanswers131libraryapreparecomcrashlyticssdkandroidbeta113libraryapreparecomcrashlyticssdkandroidcrashlytics251libraryapreparecomcrashlyticssdkandroidcrashlyticscore234libraryapreparecomgoogleandroidgmsplayservicesanalytics840libraryapreparecomgoogleandroidgmsplayservicesbase840libraryapreparecomgoogleandroidgmsplayservicesbasement840libraryapreparecomgoogleandroidgmsplayservicesgcm840libraryapreparecomgoogleandroidgmsplayservicesmeasurement840libraryapreparedehdodenhofcircleimageview130libraryaprepareiofabricsdkandroidfabric135libraryapreparereleasedependenciesappcompilereleaseaidlappcompilereleaserenderscriptappgeneratereleasebuildconfigappgeneratereleaseassets uptodateappmergereleaseassetsaprocessreleasemanifestappfabricgenerateresourcesreleaseappgeneratereleaseresvalues uptodateappgeneratereleaseresourcesappmergereleaseresourcesaapt usersaviranprojectsappsrcmainresdrawablexhdpiic drawerpng libpng warning iccp not recognizing known srgb profile that has been editedaapt usersaviranprojectsappsrcmainresdrawablehdpiic drawerpng libpng warning iccp not recognizing known srgb profile that has been editedaapt usersaviranprojectsappsrcmainresdrawablemdpiic drawerpng libpng warning iccp not recognizing known srgb profile that has been editedaprocessreleaseresourcesappgeneratereleasesourcesbuild successfultotal time 30549 secssuper weird solutionadding logitag decorating i inside the for loop actually makes it draw the lines for each item putting it outside the for loop does not work any idea what the heck is going on there,['android'] +1060295,should the extension of builtin javascript prototypes through symbols also be avoided it is the predominant opinion that builtin javascript prototypes should not be extended or altered in any wayarrayprototypeempty function return thislength 0 do not try thatdoes this rule also apply to es2015 symbolsconst empty symbolemptyarrayprototypeempty function empty return thislength 0 since symbol is a mix of string primitive immutable and object identity there can be no object property naming conflicts by definitionnormal object reflection is not affected by symbolsobjectgetownpropertynamesarrayprototypeindexofempty 1but es2015 reflection with reflectownkeysarrayprototype isso this question is mainly about how well use reflectownkeys and objectgetownpropertysymbols in the future,['javascript'] +1060428,how to not truncate mongoid logs this is how the mongoid log the operationsd 20160112t184219790639 7906 debug mongodb localhost27017 app testupdate started updateusers updatesq idbsonobjectid5695652bc54d2d1ee201e uaddtosetfavorite idseachbsonobjectid5695652bc54d2d1ee201f multifalse upsertfalse writeconcernw1 ordei want to be able to see the full log message is that possibleobs i am using mongoid 5,"['ruby-on-rails', 'ruby']" +1060490,using http rest apis with angular 2 so i am following angular 2 guides on their website via typescript and am stuck at http api integration i am trying to make a simple application that can search via soundcloud api for a song however i have difficulties implementing and understanding how to get going and online resources do it in so many different ways i believe do to rapid angular 2 syntax changes back in the dayso at the moment my project looks like thisapp components home homecomponentts search searchcomponentts appts services soundcloudts bootstraptsindexhtmlnothing fancy going on in the example main files would beapptsimport component view from angular2coreimport routeconfig router directives from angular2routerimport homecomponent from homehomecomponentimport searchcomponent from searchsearchcomponentcomponent selector app templateurl appcomponentsapphtml directives router directivesrouteconfig path home name home component homecomponent useasdefault true path search name search component searchcomponentexport class app bootstrapts import app from componentsappimport bootstrap from angular2platformbrowserimport router providers from angular2routerbootstrapapp router providersand i was trying to figure out soundcloudts however am not able to and there are errors in following approach ie inject is not found i assume i am using outdated syntax here essentially i would like to use soundcloud service for api calls within my app form search componentimport injectable from angular2coreimport http from angular2httpinjectableexport class soundcloudservice http http constructorinjecthttp http thishttp http soundcloud api not included here as i cannot get basics down first,['javascript'] +1060874,custom android switch track animation i have created a basic custom switch as defined belowswitch androidididavailswitch androidlayout widthwrap content androidswitchminwidth110dp androidlayout heightwrap content androidtrackdrawableswitch track androidthumbdrawablethumbthe drawablethumb is a simple png which works finethe drawableswitch track is defined below drawabletrackon and drawabletrackoff are pngsselector xmlnsandroid item androidstate checkedfalse androiddrawabledrawabletrackoff item androidstate checkedtrue androiddrawabledrawabletrackon item androiddrawabledrawabletrackoff selectorthis switch looks and works as intended for the most part but is there some way to animate the track as the thumb travels over it on user drag either fade between checked and unchecked or preferably change behind the thumbthe current behaviour is shown below,['android'] +1061078,c mongodb 20 not exist in dictionary i want to update a collection which only contains some id and a dictionary of objectid to objectidpublic class me blabla bsonid public objectid myid public dictionaryobjectid objectid idstootheridsim sorry if my names are not informative i cannot share real code now i have this queryvar filter buildersme blablafilterand buildersme blablafiltereqt tmyid id buildersme blablafilternotbuildersme blablafilterexistst tidstootheridsvalues valueid buildersme blablafilternotbuildersme blablafilterexistst tidstootheridskeys keyidso im trying to filter by the myid field but when i want to insert data to there i do not want duplication of any kind not in the keys nor in the valuesthe whole idea is that the updating must be atomic and check that neither of the provided ids are contained in the dictionaryi am still trying to understand how to use the existsfilter here so it might be the answertiaediti changed the code to something like that still not sure its working wellcannot test it atmbuildersme blablafilternotbuildersme blablafilterelemmatcht tidstootherids a akey keyidbuildersme blablafilternotbuildersme blablafilterelemmatcht tidstootherids a avalue valueid,['c#'] +1061235,int using wrong consolewriteline overload i was working with a coworker on some basic c tutorials and we came across what we though was an interesting conundrumthe following code works as expectedstring strings 1 2 3 consolewriteline0 1 2 stringsit gets the string array and prints out the string 1 2 3 to the console using the consolewritelinestring format params object arg overload of the writeline methodhowever the following code does not workint ints 1 2 3 consolewriteline0 1 2 intsyou get a formatexception with the message index zero based must be greater than or equal to zero and less than the size of the argument list using intellisense i can see that it is trying to use the consolewritelinestring format object arg0 overload and that is why we are getting that message it does not see ints as an array although it obviously isif we switch to the more obvious int ints 1 2 3 consolewriteline012 ints0 ints1 ints2it works again and uses the params object overload againis there a reason it does not see the int as an array for the method does the fact that int32 is a struct make a difference if so whyediti did a quick test with doubles in the same format and those did not work as well which makes me think that it really is the fact the type is a struct but i still do not understand why that would make a difference,['c#'] +1061454,how to parse html table in ruby with nokogiri i am trying to parse the table but i have no idea how better to save data from it i want to save data each in it is row to look likeraw name 1 2094 0017 0098 0113 0452the table is samplehtml eot table classopen tr thtable nameth thcolumn name 1th thcolumn name 2th thcolumn name 3th thcolumn name 4th thcolumn name 5th tr tr thraw name 1th td2094td td0017td td0098td td0113td td0452td tr tr thraw name 5th td2094td td0017td td0098td td0113td td0452td tr tableeotscrapers code is doc nokogirihtmlopenhtml nil utf8 tables doccssdivopen tablesarray tableseach do table title tablecsstr1 thtext cell data tablecsstr tdtext raw name tablecsstr thtext tablesarray tablenewcell data raw name end render template scrape krasecology endendnow when i try to thisplay data in html page it looks like all column names are stored in 1 arrays element and all data the same way,"['ruby-on-rails', 'ruby']" +1061572,sort at various levels in python i am trying to sort a list of tuples like thesepineapple 1 orange 3 banana 1 apple 1 cherry 2the sorted list should beorange 3 cherry 2 apple 1 banana 1 pineapple 1so here 1st the list should be sorted based on tuple1 in descending order then if the tuple values tuple1 match like forapple banana pineapple list should be further sorted based on tuple0 in ascending orderi have tried the possible waystop nsortkey operatoritemgetter1 0 reverse true output orange 3 cherry 2 pineapple 1 banana 1 apple 1as reverse true pineapple then bananai finally had to come up with a solutiontop nsortkey operatoritemgetter0 reverse falsetop nsortkey operatoritemgetter1 reverse trueis there any better way to get to the solution like my 1st approach i am trying to explore more about python thus seeking such kind of solution,['python'] +1061711,javac equivalent of d is there a way to give the java compiler some kind of variable that is accessible to the running java codein cc i can give the compile dkeyvalue and that would cause the preprocessor to have a define for key equals to value i can then check this value in compile time to effect what code is being compiledi found javas d but that puts values give the the java command line in systemgetproperty i want an argument give in compile time not invocation time,"['java', 'c++']" +1061745,error while requesting user app before its up i use nodehttp proxy module to run application with reverse proxy which is working as expected in some cases user want to run application immediately which the status of it in progress the app is not up yet and it can take about 315 sec until the app is up and running in this case user will get error from the proxy proxywebreq res target http hostname port consolelogaproxy app proxyonproxyreq functionproxyreq req res options consolelogaproxy request proxyonerror function err req res consolelogaproxy error resendsomething went wrong listen for the proxyres event on proxy proxyonproxyres function proxyres req res consolelogaproxy response var respstate resstatuscode in case of error the stack in the log is likeproxy aproxy requestproxy errorin this case user will run the app url in the browser and first will get the error and after few seconds when he refresh the browser the app will run okany suggestion how to solve this issue i thought about building some api which examine the proxyres statuslike call it every 1 sec and see if the response is 200 and not send the error before like check it with timeout and if after 10 sec there is not response maybe to send the error but not sure how to do it and if its good approachany idea or maybe via websoket but not sure how to do that this is the open source im using,['javascript'] +1061930,when does the apache kafka client throw a batch expired exception using the apache kafka java client 09 i am trying to send a long series of records to the broker using the kafka producer class the asynchronous send method returns immediately for a while then starts blocking on each call for a short time period after around thirty seconds the client starts throwing exceptions timeoutexception with the message batch expiredwhat circumstances cause this exception to be thrown,['java'] +1061945,micro service security over the last few days i have been playing with the micro service pattern and all is going well but security seems to baffle meso if i may ask a questionhow do i handle user authentication on an individual service at the moment i pass a request to the gateway api which in turns connects to the servicequestion edited please see belowbearing in mind that the individual services should not know about each other the gateway is the aggregator as such current architecturea little code to simulate the requestfrontend client apublic class entityrepositoryt private igateway gateway null public entityrepositoryigateway gateway this gateway gateway public ienumerablet findall return this gatewaygettypeoftcontentreadasasyncienumerabletresult public t findbyidint id return this gatewaygettypeoftcontentreadasasynctresult public void addt obj this gatewayposttypeoft obj public void updatet obj this gatewayposttypeoft obj public void savet obj this gatewayposttypeoft obj logic lives elsewhere public httpresponsemessage gettype type return connectgetasyncpathtyperesult public httpresponsemessage posttype type dynamic obj return connectpostasyncpathtype obj private string pathtype type var classname typename return apiservice applicationkey classname private httpclient connect var client new httpclient clientbaseaddress new urix add an accept header for json format clientdefaultrequestheadersacceptadd new mediatypewithqualityheadervalueapplicationjson return client i use generics to determine where it needs to fire once it hit is the gatewayso if the type is category it will fire the category service thus callingpublic ienumerabledynamic findallstring appkey string cls var response connecttoserviceappkey cls return appkey applicationkey responseissuccestatuscode responsecontentreadasasyncienumerabledynamicresult null nullthe gateway does not contain the physical filesclas of the typesafter a little code i was hoping someone could give me a little demonstration or the best approach to handle securityuser authentication with the current architecturecase scenario 1user hits the web app and logs in at that point the users encrypted email and password is sent to the gateway api which is then passed to the user service and decides whether the user is authenticated all well and good but now i want to fetch all messages from the message service that the user has received i cannot really say in the gateway if the user is authenticated fetch the messages because that does not solve the issue of calling the message service outside of the gateway apii also cannot add authentication to each individual service because that would require all respective services talking to the user service and that defeats the purpose of the patternfixesonly allow the gateway to call the services requests to services outside of the gateway should be blockedi know security is a broad topic but within the current context i am hoping someone could direct me with the best course of action to resolve the issuecurrently i have hardcoded a guid in all off the applications which in turn fetches data if the app is equal,['c#'] +1062061,why do springhibernate readonly database transactions run slower than readwrite i have been doing some research around the performance of readonly versus readwrite database transactions the mysql server is remote so it is easy for me to see differences between the different transaction types this is with connection pooling which i know is working based on comparing 1st versus 2nd jdbc callswhen i configure the spring aop to use a readonly transaction on my dao call the calls are 3040 slower compared to readwrite slower txmethod namefind readonlytrue propagationrequired or slowertransactionreadonly trueversus faster txmethod namefind readonlyfalse propagationrequired or fastertransactionlooking at tcpdump it seems like the readonly transaction is doing more back and forth talking to mysql heres the readonly dump versus readwritecan anyone explain why the readonly calls are taking longer is this expectedis there anything i am doing wrong or anything that i can do to improve their speed aside from improving the network just found this awesome post with some good performance recommendations any other commentsthanks much,['java'] +1062257,how to glow the minimum maximum and close button i followed below guide to create a custom aero frame using dwm apicustom window frame using dwmmy workvoid cmainframeonactivateuint nstatecwnd pwndotherbool bminimized cframewndonactivatenstatepwndotherbminimized bool fdwmenabled false if succeededdwmiscompositionenabledfdwmenabled ifnstate wa active margins margins 1 hresult hr dwmextendframeintoclientaream hwnd margins if succeededhr void cmainframeonncpaint rect rcclient getwindowrectrcclient inform the application of the frame change setwindowpos null rcclientleft rcclienttop rectwidthrcclient rectheightrcclient swp framechanged cframewndonncpaint cdc dc getwindowdc dcfillsolidrect00rectwidthrcclientrectheightrcclientrgb0 lresult cmainframeonnchittestcpoint p lresult r r cframewndonnchittest p ifr htminbutton r htmaxbutton r htclose return r else r hittestncam hwndp this function is direct copied from above link return r resulti found out the minimum maximum and close button that will not be glowed when i move the mouse on these buttonsgeneral situationhow to fix this problembest regards,['c++'] +1062297,how to convert c style cast to c style cast in vim i got hand over some legacy code and first i want to changeinta binto static castinta bthere are a lot of them and doing them manually is very time consuming is there a way to use vim to make this happeni tried something like sint static castint2gbut it does not work please advice,['c++'] +1062309,regex validation in laravel 52 below is my rule for passwordreturn password requiredmin8max100regexaz1az1091 password confirmation requiredmin8max100regexaz1az1091i am trying to add the rule such that it must haveatleast one small char atleast one small char atleast one numberatleast one special charmin 8 charsi tried this and it works requiredconfirmedmin8max100regexw1w1 on a regex tester software but not sure why it does not work in laravelam i missing something,['php'] +1062367,error installing split apks comandroidmlibinstallexception failed to finalize session install failed invalid apk android studio is not pushing my apk into a physical nexus 5x with marshmallow 601this is the output and the error0115 015148 launching mobile adb installmultiple r usersmyuserandroidstudioprojectsmyappmobilebuildoutputsapkmobiledevelopmentdebugunalignedapk usersmyuserandroidstudioprojectsmyappmobilebuildintermediatessplitapkdevelopmentdebugmainapk usersmyuserandroidstudioprojectsmyappmobilebuildintermediatessplitapkdevelopmentdebugmainapk error installing split apks comandroidmlibinstallexception failed to finalize session install failed invalid apk split lib main was defined multiple timeserror during launchdetailsdefaultconfigminsdkversion 9targetsdkversion 23multidexenabled true2 buildtypes debug and release2 productflavors development and productiondexoptions incremental falsepredexlibraries falsejumbomode truejavamaxheapsize 4096mi am using the latest android studio 20 preview 5 gradle thistributionurland the build tools are comandroidtoolsbuildgradle200alpha5is there a way to tell android studio no to use installmultiple to install the apkupdate 01152016 226 am estthe issue does not happen when running the app on a galaxy nexus emulator with jelly bean 431 nor a physical samsung galaxy s with gingerbread 236update 01152016 1130 am estran the app on a nexus 5 with kitkat 4 and it works just fine,"['java', 'android']" +1062473,orphan css how avoid headers h1 h2 on bottom page i have a large html document with headers h1 h2 h3 and paragraphs when i print the document i want that automatically headers at bottom of document go to next pagehow can i do i use orphans 3 css with paragraphs and works with p tags but with h1 or h2 do not workpage size a4p orphans3h1 h2 orphans3full example on action where12 page paragraphs orphan works fine23 page headers do not worksrequirementshtml have one main div containerdo not alter htmlbrowser support is not important on my specific jobi need some trick in css no js or jquery preferablyi cannot use pagebreakbeforealways because i want that headers only go to next page when appears at bottom of page,"['html', 'css']" +1062526,extracting mails content i need to create an app that will extract vat numbers that our clients send us for verification they send nothing more with emails that is for purpose of creating extended statisticswhat i need is to have a mails body without any headers before the content i need that is vat number as simple as thatthis is my script that creates the list of 30 recent emailsif function existsimap open dieno function if mbox imap openconfidential output messagecount imap num msgmbox x 1 for i 0 i 30 i message id messagecount i fetch message imap headermbox message id mail content quoted printable decodeimap fetchbodymboxmessage id 1 iconvmb detect encodingmail content mb detect order true utf8 mail content output tr tdxtd td fetch messagefrom0mailboxfetch messagefrom0host td td fetch messagedate td td fetch messagesubject td td textarea cols40mail contenttextarea td tr x smartyassignenquiries output smartythisplaymodule mail imap closembox else print rimap errorsi have worked with imap fetchbody imap header and so on to retrieve the desired content but it turns out that most of emails have got something else like headers before the content iedbl2ewtul0kmtj46ww1contenttype textplain nextpart 001 003a 01d14f7af25ab3d0contenttype textplainucrirgamikb0ot1aknccontenttype textplaini need to get rid of everything that is before the vat number included in the mails message but i do not know how some emails do not have these headers some do and since were working with clients from all over the europe it really confuses me and leaves powerlessanother problem is that some clients just copypaste vat numbers from various websites and that means these vat numbers are often pasted with the original style boldbackgroundchanged colour et cetera that might be the reason for my ps belowi would appreciate every help that would lead me to solving this problemthank you in advanceps just for a record with imap fetchbodymboxmessage id 1 i need to use 1 to have the whole content changing 1 to anything else results in thisplaying no email content at all literally,['php'] +1062580,how to build a fluent nested guard api i am building a simple guard api to protect against illegal parameters being passed to functions and so oni have the following codepublic static class guard public static guardargumentt ensurett value string argumentname return new guardargumenttvalue argumentname public class guardargumentt public guardargumentt value string argumentname value value name name public t value get private set public string name get private set example extension for validity checkspublic static guardargumentt isnotnulltthis guardargumentt guardargument string errormessage if guardargumentvalue null throw new argumentnullexceptionguardargumentname errormessage return guardargument at the moment the code can be used in a similar way to note this is just a dumb examplevoid dummymethodint someobject guardensuresomeobject someobject isnotnull isgreaterthan0 islessthan10this all works fine what i want to be able to do now is extend the api to include child properties in the checks in the following wayguardensuresomeobject someobject isnotnull property x xchildprop1 childprop1 isnotnull isgreaterthan10 property x xchildprop2 childprop2 isnotnull islessthan10 obviously the new property method needs to return the parent guardargument in order to chain furthermore the child property needs to be able to use the existing check methods isnotnull etc to avoid code duplicationi cannot work out how to construct the lambdaproperty function parameters or where the property method should be located ie should it be a property on the guardargument or somewhere else or even if there is a better structure to the api,['c#'] +1062623,iabhelper class not working i have implemented the iabhelper class in my android project and it says that the getbuyintenttoreplaceskus cannot be resolved the full methodbuyintentbundle mservicegetbuyintenttoreplaceskus5mcontextgetpackagenameoldskus sku itemtype extradatai implemented in app billing in my project but i have not yet created any items to be purchased though the rest of the methods do not have any problems,['android'] +1062671,list list trying to come up with a linqy way to do this but nothings coming to mei have a list of objects which include a property which is a commaseparated list of alpha codeslst0codes aabbddlst1codes aaddeelst2codes ggjji would like a list of those codes hopefully in the form of a list of stringsresult aabbddeeggjjthanks for any direction,['c#'] +1062756,different behavior running and debugging the program java eclipse i have this code put aside its appropriateness for now class cacheclass classfornamejavalangintegerintegercache field cachefield cacheclassgetdeclaredfieldcache cachefieldsetaccessibletrue field modifiersfield fieldclassgetdeclaredfieldmodifiers modifiersfieldsetaccessibletrue modifiersfieldsetintcachefield cachefieldgetmodifiers modifierfinal integer bettercache new integer255 for int i 0 i bettercachelength i bettercachei 20 cachefieldsetnull bettercache systemoutprintln10 systemoutprintlninteger 10i expect the second println to print 20 as i replaced cached integers with 20 when i debug program in eclipse it does as i expect it gets the value from the cache and prints 20 whereas it prints 10 in both cases when i just run it either from ide or by invoking java how can this behavior be explained updit works this way if compiled with 18 javac it prints 10 and 20 if compiled with 16 version,['java'] +1062768,how can i check if the user can see and click on an element it is simply possible to find all truly visible and clickable elements in the page using the documentelementfrompoint function however it returns null for elements outside of the viewportso how to find all clickable and visible elements in the full page the visible elements are not just limited to the styles just consider a container div which is now hidden behind all children elements so the parent div is not longer visibleso do you have any idea how it is possible to find all really visible elements in the page in the example above obviously aparent diva is not visible practically there are some other unpredictable situations where those elements may not be visible and the styles thisplayvisibility etc may not indicate itmy final intention i want to check if an element is really visible and clickable for the enduser or not as an example use case i want to find all possible zones a user may click on,"['javascript', 'jquery', 'html', 'css']" +1062825,how to abort fading out of jqueryui menu i want to stop the fading out of a jqueryui menu same context firefox 43 linuxdebiansid jquery22 jqueryui14 as for this question the alphastage melt monitor gpl free software on linuxdebian with recent firefox 38 or 43 on linux this is commit b505ec1 on githubjsfiddle mvce example at end of questionin my file webrootnanoeditjs i hve a global variable mom menucmdel which hold a jqueryui menu a dropdown menu the mom removecmdmenu function is clearing that global and removing that menu from the dom i want this menu to fade out and be removed in a bit more than 9 seconds if the user do not do any interaction but if the user is moving the mouse inside the menu i want the fading to abort so i coded var curmenu mom menucmdel curmenumousemove functionev consolelogmomdelayrepl movefinishing ev ev curmenu curmenu curmenufinish settimeoutfunction consolelogmom cmdkeypressdelayedreplmenudestroy curmenu curmenu curmenudelay100fadeout80075dollvalseqlength function consolelog momdelayrepl finalfaderemove curmenu curmenu mom removecmdmenu 9500near line 427 of that nanoeditjs my understanding is that finish would abort animations but it does not work the fading remains and the menu thisappears even after mouse movementsif you are brave enough to compile the melt monitor browse type e in the textearea then the esc keyjsfiddle example mvcesee this jsfiddle which is a simplified variant of above run it twice first click on the button and wait 10 seconds at least the menu is fading out and thisappears then run it again click on the button and move the mouse inside the menu perhaps even selecting some item the menu still thisappears in about 10 seconds but i want it to stay perhaps indefinitely in my nanoeditjs code the select function would remove it in this jsfiddle i do not care,"['javascript', 'jquery']" +1062951,listview selecteditems binding why the list is always null i am developing a uwp app with mvvm light and behaviours sdk i defined a multi selectable listviewlistview xnamememberstoinvitelist ismultiselectcheckboxenabledtrue selectionmodemultiple itemssourcebinding contacts itemtemplatestaticresource membertemplatelistviewi would like with a button binded to a mvvmlight relaycommand to obtain a list with the selected itemsbutton commandbinding addmemberstoevent commandparameterbinding elementnamememberstoinvitelist pathselecteditems contentokthe relaycommand of mvvmlight frameworkprivate relaycommandobject addmemberstoeventpublic relaycommandobject addmemberstoevent get return addmemberstoevent addmemberstoevent new relaycommandobject selectedmembers test selectedmembers is always null i put a breakpoint inside the command and i notice that selectedmembers is always null although i select various items by the console output i do not see any binding error or something elsealso if i pass as commandparameter the whole list and i put a breakpoint inside commands definition i notice that i cannot access to selecteditems nor selecteranges valuedatatemplate xnamemembertemplate viewbox maxwidth250 grid width250 margin5 5 5 5 backgroundstaticresource mylightgray borderbrushstaticresource shadowcolor borderthickness0 0 0 1 cornerradius4 padding5 gridcolumndefinitions columndefinition widthauto columndefinition width1 gridcolumndefinitions grid gridcolumn0 width45 height45 margin5050 verticalalignmentcenter cornerradius50 gridbackground imagebrush alignmentxcenter alignmentycenter imagesourcebinding imageurl converterstaticresource nullgroupimageplaceholderconverter stretchuniformtofill gridbackground grid textblock gridcolumn1 margin3 verticalalignmentcenter foregroundstaticresource foregroundtextoverbodycolor stylestaticresource lighttext textbinding alias grid viewboxdatatemplatewhats the reason how can i obtain such list,['c#'] +1063040,gradient with fading in css my question is about gradient with fading gradient from top to bottom and fading from left to right examplethe code isbackgroundimage lineargradient0deg rgba1988316595 0 rgba198865195 100 lineargradient90deg transparent 50 rgba095 100opacity 0949my result is belowas you see it does not fade the gradient it looks like separate layer behind this gradient is there any other method of implementing this,"['html', 'css']" +1063106,how to send post parameters dynamically or in loop in okhttp 3x in android i am using okhttp 3x version i want to post multiple parameters and would like to add the params in a loopi know that in version 2x i can use formencodingbuilder and add params to it in loop and then from it create a request bodybut in 3x the class has been removedhere is my current code requestbody formbody new formbodybuilder addparam1 value1 addparam2 value2 buildrequest request new requestbuilder urlurl postformbody buildnow i want to add 5 params but in a loop ie create request body by building formbody in a looplike i wrote above i know how to do it in okhttp version 2x but i am using version 3xany help or guidance is appreciatedthanks in advance,['android'] +1063216,change final value compiled by jit i noticed a very strange thing that after changing final field via reflection method returning that field is all the time giving old value i suppose this might be because of jit compilerhere is sample programpublic class mainprivate static final main m new mainpublic static main getm return mpublic static void mainstring args throws exception main m getm int x 0 forint i 0i10i ifgetmequalsm x field f mainclassgetdeclaredfieldm fsetaccessibletrue removefinalf main main1 new main fsetnull main1 main main2 main fgetnull main main3 getm systemoutprintlnmain1tostring systemoutprintlnmain2tostring systemoutprintlnmain3tostringprivate static void removefinalfield field throws nosuchfieldexception illegalaccessexception field modifiersfield fieldclassgetdeclaredfieldmodifiers modifiersfieldsetaccessibletrue modifiersfieldsetintfield fieldgetmodifiers modifierfinalresult ismain1be6f5c3main1be6f5c3main6b884d57i am wondering how can i make getm return updated value,['java'] +1063221,why is the maximal path length allowed for unixsockets on linux 108 when creating a unix socket the path name man 7 unix is allowed to be maximally 108 chars long for a friend this caused a bug in his program because his path was longer now we wonder how exactly that number was determinedi have the suspicion that the number was determined so that sizeof of that struct sockaddr un is unambiguous compared to the sizeof of other sockaddresses like sockaddr in but if they wanted to avoid clashes with other sizeof values why not use a prime number for example can someone please provide an authorative source for that,['c'] +1063313,whats the difference between span and array view in the gsl library in several recent conference presentation i have heard bjarne stroustrup and others mention new coding guidelines for c and some types supporting them specifically i remember the example of spant instead of t p int n as a parameter to a function at time about 3200 into the talk but i also remember the suggestion to use array viewt are they two alternatives but the same concept or am i confusing things and they are actually not so related i cannot seem to find any authoritative definition of what they are both supposed to be about,['c++'] +1063416,android memory management granularity activity or process i am seeing inconsistent documentation and thiscussion regarding what happens when android is low on memory and the steps the os takes to reclaim memory more specifically does android kill at the granularity of activityfragment or entire process for example if activity b is launched in front of activity a and both activities are part of the same aprocess can activity a be killed by the os while activity b is in the foreground and the user is interacting with activity b assume screen remains on current app remains in the foreground no orientation change occursthis so answer from 2011 by dianne hackborn on the android team at google suggests that android kills at the granularity of a process not an activityon the android developer pages on recreating an activity it saysthe system may also destroy your activity if it is currently stopped and has not been used in a long time or the foreground activity requires more resources so the system must shut down background processes to recover memorynotice the ambiguity the system must shut down background processeson the android developer pages for onsaveinstancestate it saysfor example if activity b is launched in front of activity a and at some point activity a is killed to reclaim resources activity a will have a chance to save the current state of its user interface via this methodafter reading through these and many other doc pages and online thiscussion it is not clear what the correct answer is i also have the same question regarding fragments can a backgrounded fragment be killed due to low memory without its entire process being killed,['android'] +1063471,how to get href attributes of a tags in this string in this string exist number li tag i want get href attribute of a tags such as this target blank target blankand i want that do this with c how to done thisi use this code but this is not complete int indexstartul codehtmlindexoful int indexendul codehtmlindexoful codehtml codehtmlsubstringindexstartul indexendulplease help ul classull lia href target blank o uuaspan classurbipardeh94blogfacomspanspan classdsu u u1uspanli lia href target blanku2 uuau aspan classuravaejamblogfacomspanspan classds uu uuau 2 u2 uuau a 1 spanli lia href target blanku 1u u u u 2 3u u uaspan classurprkangavarblogfacomspanspan classds u u uspanli lia href target blanku uu u1 3uu uuaspan classurbordekhounblogfacomspanspan classds uu 2 a uau u u uuspanli lia href target blanka uu uu uaspan classurmahinvareblogfacomspanspan classdsu uu uu 1u u3uu u uauu u spanli lia href target blank u u u 2uuaspan classurzanjanuniversityblogfacomspanspan classds u u u 2uu u u u u 2 2uu u 3u3au a uu u u 2uu span li ul,"['c#', 'html']" +1063568,proguard does not obfuscate jar with dependencies i have a project with the pomxml file given below when i issue the command mvn clean compile assemblysingle install i want maven to generate a jar which containsall the dependencies andobfuscated version of my codeit does not work my code is not obfuscated in the jarwithdependencies filewhen i run mvn clean compile install the resulting file contains obfuscated code of my application but no dependencieswhat can i do in order to have a jar file with all the dependencies and my obfuscated codexml version10 encodingutf8project xmlns xmlnsxsi xsischemalocation modelversion400modelversion groupidcommycompanygroupid artifactidmyproductartifactid version10snapshotversion packagingjarpackaging properties restletversion235restletversion properties dependencies dependency groupidorgspongepoweredgroupid artifactidspongeapiartifactid version300version scopeprovidedscope dependency dependency groupidjunitgroupid artifactidjunitartifactid version412version dependency dependency groupidorgeasytestinggroupid artifactidfestassertcoreartifactid version20m8version scopetestscope dependency dependency groupidorgmockitogroupid artifactidmockitocoreartifactid version11019version scopetestscope dependency dependency groupidorgrestletjsegroupid artifactidorgrestletartifactid versionrestletversionversion dependency dependency groupidorgrestletjsegroupid artifactidorgrestletextjacksonartifactid versionrestletversionversion dependency dependency groupidcomgooglecodejsonsimplegroupid artifactidjsonsimpleartifactid version1version dependency dependencies build resources resource directoryprojectbasedirsrcmainresourcesdirectory filteringtruefiltering resource resources plugins plugin groupidorgapachemavenpluginsgroupid artifactidmavencompilerpluginartifactid version33version configuration source18source target18target configuration plugin plugin groupidorgcodehausmojogroupid artifactidtemplatingmavenpluginartifactid version10alpha3version executions execution idfiltersrcid goals goalfiltersourcesgoal goals execution executions plugin plugin artifactidmavenassemblypluginartifactid configuration descriptorrefs descriptorrefjarwithdependenciesdescriptorref descriptorrefs configuration plugin plugin groupidcomgithubwvengengroupid artifactidproguardmavenpluginartifactid version208version executions execution phasepackagephase goalsgoalproguardgoalgoals execution executions configuration proguardversion52proguardversion options optionallowaccessmodificationoption optiondontoptimizeoption optiondontshrinkoption optiondontnoteoption optionkeepattributes signatureoption optionkeep class commycompanymyplugin option options libs libjavahomelibrtjarlib libs dependencies dependency groupidnetsfproguardgroupid artifactidproguardbaseartifactid version52version scoperuntimescope dependency dependencies configuration plugin plugins buildprojectupdate 1 17012016 1954 msk changed the proguard configuration like shown below but mvn clean compile assemblysingle still produces a jar with unobfuscated class filesplugin groupidcomgithubwvengengroupid artifactidproguardmavenpluginartifactid version208version executions execution phasepackagephase goalsgoalproguardgoalgoals execution executions configuration proguardversion52proguardversion options optionallowaccessmodificationoption optiondontoptimizeoption optiondontshrinkoption optiondontnoteoption optionkeepattributes signatureoption optionkeep class commycompanymyplugin option options injarprojectbuildfinalnamejarwithdependenciesjarinjar libs libjavahomelibrtjarlib libs dependencies dependency groupidnetsfproguardgroupid artifactidproguardbaseartifactid version52version scoperuntimescope dependency dependencies configurationpluginupdate 2 17012016 2029 msk mvn clean compile assemblysingle install fails the last messages can be seen here,['java'] +1063639,what design concept to use to update the ui async i am working on an app that thisplays a working schedule on a time linethis is a rough layout of how the app is designed at the momentthe data is stored in an sqlite db when the timeline a singleton object requests the data from the database helper class it gets an arraylist of events eg an event could be a duty starting at the 1st of may 2016 at 0300 and ending at the 3rd of may 2016 at 1600 the timeline then transforms these events to timelineitems a class representing part of an event for a particular daythe loading of events and the transformation of events to timelineitems both are done in asynctasks so far so goodnow comes the part i am struggling with updating the ui after a new db fetchmy first approach was to pass the updated arraylist of timelineitems to the recyclerview adapter and let the the adapter know the data has changed with notifydatasetchanged the problem with this approach is that1 a lot of unnecessary work is being done cause were recalculating all eventstimelineitems not only the ones changed and2 the scroll position on the recyclerview is reset after every db fetchin my 2nd approach i have implemented some methods to check which eventstimelineitems have changed since the last thisplay with the idea of only changing those timelineitems with notifyitemchanged less work is being done and no need to worry about scroll positions at all the tricky bit is that checking which items have changed does take some time so it needs to be done async as welli tried to do the code manipulations in doinbackground and the ui updating by posting otto bus events in onprogressupdateprivate class inserteventstask extends asynctaskvoid integer void override protected void doinbackgroundvoid params arraylistevent events mcachedevents if mchangedevents is not null and not empty if events null eventsisempty get the list of pairs for the events arraylisttimelineitemfordatetimepair listofpairs converteventstopairsevents insert the timelineitems from the pairs into the timeline for int i 0 i listofpairssize i get the last position for the datetime associated with the pair int position findlastpositionfordatelistofpairsgetidatetime if position is 1 the events started on a day before the timeline starts so keep skipping pairs until position 1 if position 1 if the item is a placeholderitem if mtimelineitemsgetpositionisplaceholderitem remove the placeholderitem mtimelineitemsremoveposition and add the timelineitem from the pair at the position the placeholderitem was at mtimelineitemsaddposition listofpairsgetitimelineitem update the ui on the ui thread publishprogressposition type changed else if the item is not a placeholderitem there is already an normal timelineitem in place place the new item at the next position on the timeline mtimelineitemsaddposition 1 listofpairsgetitimelineitem publishprogressposition type added return null onprogressupdate handles the ui changes on the ui thread for us type int available type changed type added type deleted param values value0 is the position as codeintcode value1 is the type of manipulation as codeintcode override protected void onprogressupdateinteger values int position values0 int type values1 update the ui for each changedaddeddeleted timelineitem if type type changed busprovidergetinstancepostnew timelineitemchangednotificationposition else if type type added busprovidergetinstancepostnew timelineitemaddednotificationposition else if type type deleted todo make delete work bro the problem is that somehow scrolling while this progress is being posted messes up the ui completelymy main problem is when i update a specific item in the data set timelineitems of the adapter notifyitemchanged does change the item but does not put the item at the correct positionheres my adapter a custom recyclerview adapter to thisplay a timeline in a timelinefragmentpublic class timelineadapter extends recyclerviewadaptertimelineadaptertimelineitemviewholder variables private arraylisttimelineitem mtimelineitems constructors constructor with codearraylisttimelineitemcode as data set argument param timelineitems arraylist with timelineitems to thisplay public timelineadapterarraylisttimelineitem timelineitems thismtimelineitems timelineitems create new views invoked by the layout manageroverridepublic timelineitemviewholder oncreateviewholderviewgroup parent int viewtype create a new view view v layoutinflaterfromparentgetcontext inflaterlayoutitem timeline parent false set the views size margins paddings and layout parameters return new timelineitemviewholderv replace the contents of a view invoked by the layout manageroverridepublic void onbindviewholdertimelineitemviewholder holder int position get element from your data set at this position replace the contents of the view with that element if the item is a showpreviousmonthsitem set the showpreviousmonthstext accordingly if mtimelineitemsgetpositionisshowpreviousmonthsitem holdershowpreviousmonthstextsettextmtimelineitemsgetpositionshowpreviousmonthstext else otherwise set the showpreviousmonthstext blank holdershowpreviousmonthstextsettext day of month day of week of the timelineitem if mtimelineitemsgetpositionisfirstitemofday holderdayofweeksettextmtimelineitemsgetpositiondayofweek holderdayofmonthsettextmtimelineitemsgetpositiondayofmonth else holderdayofweeksettext holderdayofmonthsettext event name for the timelineitem holdernamesettextmtimelineitemsgetpositionname place and goingto of the timelineitem if combinedplace ifmtimelineitemsgetpositioncombinedplaceequals if mtimelineitemsgetpositionisfirstdayofevent holderplacesettextmtimelineitemsgetpositionplace else holderplacesettext if mtimelineitemsgetpositionislastdayofevent holdergoingtosettextmtimelineitemsgetpositiongoingto else holdergoingtosettext holdercombinedplacesettext else holderplacesettext holdergoingtosettext holdercombinedplacesettextmtimelineitemsgetpositioncombinedplace ifmtimelineitemsgetpositionstartdatetime null holderstarttimesettextmtimelineitemsgetpositionstartdatetimetostringhhmm else holderstarttimesettext ifmtimelineitemsgetpositionenddatetime null holderendtimesettextmtimelineitemsgetpositionenddatetimetostringhhmm else holderendtimesettext if mtimelineitemsgetpositionisshowpreviousmonthsitem if mtimelineitemsgetpositiondategetdayofweek datetimeconstantssunday holderdayofweeksettextcolorcolorred holderdayofmonthsettextcolorcolorred else holderdayofweeksettypefacenull typefacenormal holderdayofmonthsettypefacenull typefacenormal holderdayofweeksettextcolorcolorgray holderdayofmonthsettextcolorcolorgray else relativelayout holderdayofweekgetparentsetbackgroundcolorcolorwhite holderbindtimelineitemmtimelineitemsgetposition return the size of the data set invoked by the layout manageroverridepublic int getitemcount return mtimelineitemssize replace the data setpublic void settimelineitemsarraylisttimelineitem timelineitems thismtimelineitems timelineitems replace an item in the data setpublic void swaptimelineitematpositiontimelineitem item int position mtimelineitemsremoveposition mtimelineitemsaddposition item notifyitemchangedposition the viewholder class containing the relevant views also binds the timeline item itself to handle onclick eventspublic class timelineitemviewholder extends recyclerviewviewholder implements viewonclicklistener protected textview dayofweek protected textview dayofmonth protected textview showpreviousmonthstext protected textview name protected textview place protected textview combinedplace protected textview goingto protected textview starttime protected textview endtime protected timelineitem timelineitem public timelineitemviewholderview view superview viewsetonclicklistenerthis thisdayofweek textview viewfindviewbyidridday of week thisdayofmonth textview viewfindviewbyidridday of month thisshowpreviousmonthstext textview viewfindviewbyidridload previous data thisname textview viewfindviewbyidridname thisplace textview viewfindviewbyidridplace thiscombinedplace textview viewfindviewbyidridcombined place thisgoingto textview viewfindviewbyidridgoing to thisstarttime textview viewfindviewbyidridstart time thisendtime textview viewfindviewbyidridend time public void bindtimelineitemtimelineitem item timelineitem item handles the onclick of a timelineitem override public void onclickview v if the timelineitem is a showpreviousmonthsitem if timelineitemisshowpreviousmonthsitem busprovidergetinstancepostnew showpreviousmonthsrequest if the timelineitem is a placeholderitem else if timelineitemisplaceholderitem toastmaketextvgetcontext no details toastlength shortshow else the timelineitem is an actual event else toastmaketextvgetcontext eventid timelineitemeventid toastlength shortshow and this is the method that is triggered in the timelinefragment when a change is posted on the event bussubscribepublic void ontimelineitemchangedtimelineitemchangednotification notification int position notificationposition logdtag timelineitemchanged detected for position position madapterswaptimelineitematpositionmtimelinemtimelineitemsgetposition position madapternotifyitemchangedposition logdtag item for position position swappeda thing to note is that the data set of the adapter seems to thisplay correctly after i scrolled away from the changed data far enough and return to the position after that initially the ui is totally messed up thoughediti found that addingmadapternotifyitemrangechangedposition madaptergetitemcountresolves the issue but unfortunately sets the scroll position to the one being changed heres my timelinefragment fragment thisplaying a timeline using a recyclerviewpublic class timelinefragment extends backhandledfragment debug flag and tag private static final boolean debug false private static final string tag timelinefragmentclassgetsimplename variablesprotected recyclerview mrecyclerviewprotected timelineadapter madapterprotected linearlayoutmanager mlinearlayoutmanagerprotected timeline mtimelineprotected menuitem mmenuitemscroll2todayprotected menuitem mmenuitemreloadprotected string mtoolbartitle todo get the value of this boolean from the shared preferencesprivate boolean musetimelineitemdividers trueoverridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate get a handle to the apps timeline singleton mtimeline timelinegetinstance sethasoptionsmenutrueoverridepublic view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate view rootview inflaterinflaterlayoutfragment timeline container false rootviewsettagtag mrecyclerview recyclerview rootviewfindviewbyidridtimeline list mrecyclerviewhasfixedsize linearlayoutmanager constructor mlinearlayoutmanager new linearlayoutmanagergetactivity set the layout manager setrecyclerviewlayoutmanager adapter constructor madapter new timelineadaptermtimelinemtimelineitems set the adapter for the recyclerview mrecyclerviewsetadaptermadapter add lines between the different items if using them if musetimelineitemdividers recyclerviewitemdecoration itemdecoration new timelineitemdividerthisgetcontext mrecyclerviewadditemdecorationitemdecoration add the onscrolistener mrecyclerviewaddonscrolistenernew timelineonscrolistenermlinearlayoutmanager when the first visible item on the timeline changes adjust the toolbar title accordingly override public void onfirstvisibleitemchangedint position mtimelinemcurrentscrollposition position try string title mtimelinemtimelineitems getpositiondate tostringtimelineconfigtoolbar date format if mtoolbartitle is null set it to the new title and post on bus if mtoolbartitle null if debug logdtag mtoolbartitle is null posting new title request on bus title mtoolbartitle title busprovidergetinstancepostnew changetoolbartitlerequestmtoolbartitle else if mtoolbartitle is not null only post on the bus if the new title is different from the previous one if titleequalsmtoolbartitle if debug logdtag mtoolbartitle is not null but new title detected posting new title request on bus title mtoolbartitle title busprovidergetinstancepostnew changetoolbartitlerequestmtoolbartitle catch nullpointerexception e if the onfirstvisibleitemchanged is called on a showpreviousmonthsitem leave the title as it is return rootview set recyclerviews layoutmanager to the one given public void setrecyclerviewlayoutmanager int scrollposition if a layout manager has already been set get current scroll position if mrecyclerviewgetlayoutmanager null scrollposition linearlayoutmanager mrecyclerviewgetlayoutmanager findfirstcompletelyvisibleitemposition else scrollposition mtimelinemfirstpositionfortoday mrecyclerviewsetlayoutmanagermlinearlayoutmanager mlinearlayoutmanagerscrolltopositionwithoffsetscrollposition 0 set additional menu items for the timeline fragmentoverridepublic void onprepareoptionsmenumenu menu scroll to today mmenuitemscroll2today menufinditemridaction scroll2today mmenuitemscroll2todaysetvisibletrue mmenuitemscroll2todayseticontimelinegeticonfordatetimenew datetime mmenuitemscroll2todaysetonmenuitemclicklistenernew menuitemonmenuitemclicklistener override public boolean onmenuitemclickmenuitem item stop scrolling mrecyclerviewstopscroll get todays position int todaysposition mtimelinemfirstpositionfortoday scroll to todays position mlinearlayoutmanagerscrolltopositionwithoffsettodaysposition 0 return false reload data from hacklberry mmenuitemreload menufinditemridaction reload from hacklberry mmenuitemreloadsetvisibletrue mmenuitemreloadsetonmenuitemclicklistenernew menuitemonmenuitemclicklistener override public boolean onmenuitemclickmenuitem item stop scrolling mrecyclerviewstopscroll mtimelinereloaddbforcurrentmonth mtimelineloadeventsfromuninfinitydbasyncmtimelinemtimelinestart mtimelinemtimelineend return false superonprepareoptionsmenumenuoverridepublic void onresume superonresume if the timeline has been invalidated let allinoneactivity know it needs to replace this fragment with a new one if mtimelineisinvalidated logdtag posting timelineinvalidatednotification on the bus busprovidergetinstancepost new timelineinvalidatednotification fetch todays menu icon if mmenuitemscroll2today null if debug logdtag fetching scroll2today menu icon mmenuitemscroll2todayseticontimelinegeticonfordatetimenew datetime from backhandledfragmentoverridepublic string gettagtext return tag from backhandledfragmentoverridepublic boolean onbackpressed return falsesubscribepublic void onhacklberryreloadedhacklberryloadednotification notification resetreloading handles showpreviousmonthsrequests posted on the bus by the timelineadapters showpreviousmonthsitem onclicksubscribepublic void onshowpreviousmonthsrequestshowpreviousmonthsrequest request create an empty onitemtouchlistener to prevent the user from manipulating the recyclerview while it loads more data would mess up the scroll position emptyonitemtouchlistener listener new emptyonitemtouchlistener add it to the recyclerview mrecyclerviewaddonitemtouchlistenerlistener load the previous months add the required timelineitems int newscrolltoposition mtimelineshowpreviousmonths pass the new data set to the timelineadapter madaptersettimelineitemsmtimelinemtimelineitems notify the adapter the data set has changed madapternotifydatasetchanged scroll to the last scroll updated position mlinearlayoutmanagerscrolltopositionwithoffsetnewscrolltoposition 0subscribepublic void ontimelineitemchangedtimelineitemchangenotification notification int position notificationposition logdtag timelineitemchanged detected for position position madapterswaptimelineitematpositionmtimelinemtimelineitemsgetposition position madapternotifyitemrangechangedposition position logdtag item for position position swappedi have taken a screenshot of the app after it first loads i will explain real quick what happens on initialisationthe timeline is built by populating all days with placeholderitems a timelineitem with just a dateevents are loaded from the db and transformed to timelineitemswhenever a new timelineitem has changed and is ready the timeline pokes the timelinefragment via the otto bus to update the data set of the adapter for that particular position with the new timelineitemheres a screenshot of what happens after the initial loadthe timeline is loaded but certain items are inserted at the wrong positionwhen scrolling away and returning to the range of days that was thisplayed incorrectly before all is good,['android'] +1064052,how to cache server results in gwt with guava in my gwt application i am often refering several times to the same server results i also do not know which code is executed first i therefore want to use caching of my asynchronous clientside resultsi want to use an existing caching library i am considering guavagwti found this example of a guava synchronous cache in guavas documentationloadingcachekey graph graphs cachebuildernewbuilder build new cacheloaderkey graph public graph loadkey key throws anyexception return createexpensivegraphkey this is how i am trying to use a guava cache asynchronously i have no clue about how to make this workloadingcachekey graph graphs cachebuildernewbuilder build new cacheloaderkey graph public graph loadkey key throws anyexception i want to do something asynchronous here i cannot use threadsleep in the browserjavascript environment servicecreateexpensivegraphkey new asynccallbackgraph public void onfailurethrowable caught how to tell the cache about the failure public void onsuccessgraph result how to fill the cache with that result return i cannot provide any result yet what can i return gwt is missing many classes from the default jre especially concerning threads and concurrancyhow can i use guavagwt to cache asynchronous results,['java'] +1064127,cannot import cv2 in python in osx i have installed opencv 31 in my mac cv2 is also installed through pip install cv2 vinllen pip install cv2you are using pip version 710 however version 712 is availableyou should consider upgrading via the pip install upgrade pip commandrequirement already satisfied use upgrade to upgrade cv2 in usrlocallibpython27sitepackagesbut it looks like cv2 and cv cannot be usedpython 2710 default jul 13 2015 120558gcc 421 compatible apple llvm 610 clang602053 on darwintype help copyright credits or license for more information import cv2traceback most recent call last file stdin line 1 in moduleimporterror no module named cv2 import cvtraceback most recent call last file stdin line 1 in moduleimporterror no module named cvi have tried almost all the solutions list online but cannot work,['python'] +1064593,building a javascript library why use an iife this way i have noticed a lot of libraries use this style below to define their library i also notice that the first self invoking function has something to do with requirejs or amd systems they always have factory as an argument i will look more into requirejs always been into browserifywhy is the main code passed into the end of the first self invoking function inside parentheses is this is a closure or just considered an anonymous function i will dig deeper into both what are the benefits to this it looks like inside the closure the author passes a string this and a callback will this give my library a clean safe way to globalize the main object in this example below pleasefunction globalname root factory if typeof define function defineamd define factory else if typeof exports object moduleexports factory else rootglobalname factory please this functioni am trying to dig really deep into javascript and create my own small mvc architecture i do not want to hear i am silly or its been done before i want to challenge myself and learn if there are any great resources for creating a javascript library or even better an mvc library i would love to know,['javascript'] +1064614,kotlin intermittent bad class file error starting today when i attempt to build my kotlin android app i am met with the following error in my gradle builderrorcannot access bazbad class file usersmeprojectssiteandroidappbuildtmpkaptdebugclassfilestubscomcompanyfoobarbazclassbad runtimeinvisibleparameterannotations attribute bazfragmentmanagerplease remove or make sure it appears in the correct subdirectory of the classpathit is pointing to an inner class baz which extends androidsupportv4appfragmentstatepageradapter i am able to temporarily get around the error by commenting out the class and any references to it in the outer class and rebuilding the error goes away but obviously the class no longer exists so other things break at runtime then if i uncomment it and build it will work for a few builds then the error comes back rinse and repeat i think closing the genymotion emulator may trigger itanyone else run into this or have any ideashere is the offending codeclass bar fragment inject lateinit var apiapirequester var data arraylistdata arraylist override fun oncreateviewinflater layoutinflater container viewgroup savedinstancestate bundle view view creation code data population code viewpageradapter bazchildfragmentmanager more view creation code inner class bazfmfragmentmanager fragmentstatepageradapterfm override fun getcount int return datacount override fun getitemposition int fragment var jf foofragment var bundle bundle bundleputparcelabledata dataposition jfarguments bundle return jf edit apologies baz extends fragmentstatepageradapter not fragment as i initially stated i am using dagger2 which could totally have an effect here,['android'] +1064768,android how to group async tasks together like in ios i have a function in ios app that uses thispatch group to group multiple rest request static func fetchcommentsandtheirrepliesarticleid string failure nserrorvoid success comments string anyobject replies string anyobject userids setstringvoid var retcomments string anyobject var retreplies string anyobject var retuserids setstring let queue thispatch get global queueqos class user initiated 0 alamofirerequestget apibaseurl apiarticlelistcreatecomment parameters apiarticlearticleid articleidresponsejson response in thispatch asyncqueue guard let comments responseresultvalue as string anyobject else failurehelpererror return printcomments retcomments comments let group thispatch group create for commentindex comment in commentsenumerate guard let id comment id as string else continue let relevantuserids helperparserelaventuseridsfromentitycomment for userid in relevantuserids retuseridsinsertuserid retrepliesappendstring anyobject thispatch group entergroup alamofirerequestget apibaseurl apiarticlelistcreatereply parameters apiarticlecommentid idresponsejson response in thispatch asyncqueue if let replies responseresultvalue as string anyobject for reply in repliesenumerate let relevantuserids helperparserelaventuseridsfromentityreply for userid in relevantuserids retuseridsinsertuserid retrepliescommentindex replies thispatch group leavegroup thispatch group waitgroup thispatch time forever successcomments retcomments replies retreplies userids retuserids as you can see from my code i fetch all the comments under the same article then fetch coresponding replies under each comment after all requests are done i invoke my success callback this can be achieved using gcds thispatch group now i am migrating the same functionality to android public static void fetchcommentsandtheirrepliescontext context string articleid final stringbuffer outerrormessage final runnable failure final arraylistjsonobject outcomments final arraylistarraylistjsonobject outreplies final hashsetstring outuserids final runnable success final requestqueue queue volleynewrequestqueuecontext hashmapstring string commentparams new hashmap commentparamsputapiarticlearticleid articleid jsonarrayrequest commentrequest new jsonarrayrequestrequestmethodget apibaseurl apiarticlelistcreatecomment new jsonobjectcommentparams new responselistenerjsonarray override public void onresponsejsonarray response try for int i 0 i responselength i jsonobject comment responsegetjsonobjecti outcommentsaddcomment outuseridsaddallhelperparserelaventuseridsfromentitycomment outrepliesaddnew arraylistjsonobject todo thispatch group string id commentgetstring id hashmapstring string replyparams new hashmap replyparamsputapiarticlecommentid id final int finali i jsonarrayrequest replyrequest new jsonarrayrequestrequestmethodget apibaseurl apiarticlelistcreatereply new jsonobjectreplyparams new responselistenerjsonarray override public void onresponsejsonarray response try for int j 0 j responselength j jsonobject reply responsegetjsonobjectj outuseridsaddallhelperparserelaventuseridsfromentityreply outrepliesgetfinaliaddreply catch jsonexception ex new responseerrorlistener override public void onerrorresponsevolleyerror error queueaddreplyrequest successrun catch jsonexception ex new responseerrorlistener override public void onerrorresponsevolleyerror error outerrormessageappenderrorgetmessage failurerun queueaddcommentrequestnote that i am using success is executed right after i get all the comments and before getting all the replies so how can i group them and delay the response i am working on the hairy implementation liketaskcountif taskcount totalcount successrun in reply block but it seems very tedious,"['java', 'android', 'ios']" +1064868,writing audio to server over tcp socket i am trying to transmit real time mic recording to server over tcp socket and server to write input stream to a filethe connection is established but after some time i am getting connection refused error at my clientsideserver code public class auserver extends thread private static serversocket serversocket private static int port 3 public void run systemoutprintlninit success whiletrue try serversocket new serversocketport serversocketsetsotimeout10 socket clientsoc serversocketaccept systemoutprintlnwaiting for client on port serversocketgetlocalport systemoutprintlnjust connected to clientsocgetremotesocketaddress inputstream in clientsocgetinputstream whileinnull writetofilein systemoutprintlnsocket clientsocclose catchsockettimeoutexception s systemoutprintlnsocket timed out break catchioexception e eprintstacktrace systemoutprintlnsome io break catch exception e systemoutprintlnsome e eprintstacktrace private void writetofileinputstream in throws ioexception write the output audio in byte string filepath 8k16bitmono1wav short sdata new short1024 byte bdata ioutilstobytearrayin fileoutputstream os null try os new fileoutputstreamfilepath catch filenotfoundexception e eprintstacktrace systemoutprintlnshort wirting to file sdatatostring try oswritebdata 0 2048 catch ioexception e eprintstacktrace try osclose catch ioexception e eprintstacktrace public static void mainstring args todo autogenerated method stub try thread serverthread new auserver serverthreadrun systemoutprintlnruning catchioexception e eprintstacktrace and client private void streamdatabyte bdata throws unknownhostexception ioexception interruptedexception bdata is byte array to transmit threadsleep500 socket client new socket1022140413 outputstream outtoserver clientgetoutputstream outtoserverwritebdata ifisrecording clientclosewhat could be the problemthanks in advance,"['java', 'android']" +1064982,basic proxy authentification for https urls returns http10 407 proxy authentication required i want to use a proxy with basic authentication username password for a connection and only this connection in java the following code works for http urls eg url url new urlhttpurlconnection httpurlconnection nullinetsocketaddress proxylocation new inetsocketaddressproxyhost proxyportproxy proxy new proxyproxytypehttp proxylocationhttpurlconnection httpurlconnection urlopenconnectionproxy works for http only does not work for httpsstring encoded new sunmiscbase64encoderencodebufferproxyusername proxypasswordgetbytesreplacern httpurlconnectionsetrequestpropertyproxyauthorization basic encodedinputstream is httpurlconnectiongetinputstreaminputstreamreader isr new inputstreamreaderis int data isrreadwhiledata 1 char c char data data isrread systemoutprintcisrclosethe code does not work for https urls eg though i get javaioioexception unable to tunnel through proxy proxy returns http10 407 proxy authentication required when i try to access an https urlthis code works for http and httpsurl url new urlhttpurlconnection httpurlconnection nullinetsocketaddress proxylocation new inetsocketaddressproxyhost proxyportproxy proxy new proxyproxytypehttp proxylocationhttpurlconnection httpurlconnection urlopenconnectionproxy works for http and https but sets a global defaultauthenticatorsetdefaultnew authenticator protected passwordauthentication getpasswordauthentication return new passwordauthenticationproxyusername proxypasswordtochararray inputstream is httpurlconnectiongetinputstreaminputstreamreader isr new inputstreamreaderis int data isrreadwhiledata 1 char c char data data isrread systemoutprintcisrclosethe problem with the 2nd code is that it sets a new default authenticator and i do not want to do that because this proxy is only used by a part of the application and a different part of the application could be using a different proxy i do not want to set a global default for the whole application is there a way to get the 1st code to work with https or a way to use an authenticator without setting it as defaulti have to use javanethttpurlconnection because i am overriding a method of a class which has to return an httpurlconnection so i cannot use apache httpclient,['java'] +1065133,split string into sentences using regex i have random text stored in sentences using regex i want to split the text into sentences seefunction splitsentencestext re split sentences on whitespace between them begin positive lookbehind either an end of sentence punct or end of sentence punct and quote end positive lookbehind begin negative lookbehind mr skip either mr mrs or mrs tva or tva or you get the idea end negative lookbehind s split on whitespace between sentences ix sentences preg splitre text 1 preg split no empty return sentencessentences splitsentencessentencesprint rsentencesit works finehowever it does not split into sentences if there are unicode characters sentences entertainment media propertiesa fairy tail and tokyo ghoulor this scenariosentences entertainment media propertiesacircnbsp fairy tail and tokyo ghoulwhat can i do to make it work when unicode characters exist in the texthere is an ideone for testingbounty infoi am looking for a complete solution to this before posting an answer please read the comment thread i had with wiktorstribia14ew for more relevant info on this issue,['php'] +1065137,freemarker creating multiple child tags given an ftl file which is structured as below just an example i am able to replace insert all elements in to level 1 which is finemy confusion arises when there maybe multiple level2s for example it could repeat many times as such my process for replacing will hit a pain pointparent level1 a b c d level1 level2 e f g h i j level2parent mapputa valuefora mapputb valueforb mapputc valueforc mapputd valueford configuration cfg new configuration cfgsetdirectoryfortemplateloadingnew filectemplates template temp cfggettemplatefreemarkerftl writer out new outputstreamwritersystemout tempprocessmap outat this point here assuming i have a list of values to have multiple level2 nodes how would i go about producing this using the style shown abovethanks,['java'] +1065144,can you dumb down es6 template strings to normal strings i have to work around the limitation of gettext to recognise es6 template strings and i thought about getting the non interpolated value of the template strings as a compilation step in order to have only normal strings in the codebasically what i would like to achieve is transform thisconst adjective wonderfulconst something look i am a adjective stringconsolelogsomething look i am a wonderful stringinto thisconst adjective wonderfulconst something look i am a adjective stringconsolelogsomething look i am a adjective stringone brutal way of achieving this is using sed but it is most certainly not the more elegant and probably also error pronesed sg filenameany better and cleaner idea comes to mind,['javascript'] +1065146,why cannot a pointer be automatically converted into a unique ptr when returning it let me pose my question through an mweinclude memorystdunique ptrint get it auto p new int return pint main auto up get it return 0this fails to compile with the following erroracpp59 error could not convert apa from ainta to astdunique ptrinta return p why is not there an automatic conversion from a raw pointer to a unique one here and what should i be doing instead motivation i understand it is supposed to be good practice to use smart pointers for ownership to be clear i am getting a pointer which i own from somewhere as an int in this case and i think i want it in a unique ptrif youre considering commenting or adding your own answer please address herbert sutters arguments for this to be possible in proposal n4029,['c++'] +1065386,gcc cannot capture this pointer to templated type using initcapture a templated class can capture its own this pointer in a lambdatemplate typename tclass foo public void foovoid auto getcallablefoovoid return this thisfoo this and all other foo examples can be tested using the following codeint main fooint f auto callable fgetcallablefoo callablehowever if instead an initcapture is used this no longer works with gcc auto getcallablefoovoid return ptr this ptrfoo error message from gcc 51error afootgetcallablefoolambda ptra has incomplete typeclang 37 appears to compile and run this code without error i am actually using a version compiled from source from before 37 was released but i do not expect this has broken since theninitcapture is supposed to behave like assignment to auto but the following code appears to work without error in gcc new method in fooauto getptrvoid return this usageauto ptr fgetptrptrfooso why is not the ptr value able to capture this in gcc is this a bugone other consideration is that according to cppreference this is treated as a separate syntactical case from every other capturelist type so that may be one hint toward why gcc treats these cases differently but it is not clear to me what if any special handling is done for this special case or why it is a special case at alledit it appears that this does workreturn ptr static castdecltypethisthis ptrfoo this makes no sense to me because decltype unlike auto infers exactly the type of its argument so the static cast should not actually be affecting anythingedits 234 heres a complete list of expressions that i have tried with both compilers with comments indicating which compilers accept each expressionthis thisfoo both workptr this ptrfoo gcc failsptr static castdecltypethisthis ptrfoo both works ptrthis ptrfoo gcc failsptrthis ptrfoo gcc works clang does not work infers initializer listptr this ptrfoo both fail infers initializer listptr this ptrfoo both workptr this ptrfoo both workfor ptrthis my version of clang a prerelease 37 warns that the interpretation will change currently it infers an initializer list but presumably later versions will or already do infer the type of this in accordance with the new auto rules from n3922it shocks me that gcc permits ptrthis but not ptrthis i have no explanation for this,['c++'] +1065750,how to identify the following code patterns i have a pattern of js promises that i want to identify for several keywordsfor example if i put code likevar deferred qdeferand in the file i have also the following respective valuedeferredrejecterrdeferredresolvereturn deferredpromisethe complete codeexample 1function writeerrorerrmessage var deferred qdefer fswritefileerrorslog errmessage function err if err deferredrejecterr else deferredresolve return deferredpromiseand i want that if i put large code file as string to find that this file contain the patternanother examplevar d qdefer or qdefer and in the file you have also the following respective valuedresolvevaldrejecterr return dpromisecomplete example 2function getstuffdoneparam var d qdefer or qdefer promisefunctionresolve reject or new deferred etc mypromisefnparam1 thenfunctionval or done dresolveval catchfunctionerr fail drejecterr return dpromise or promise there is open sources which can be used to do such analysisprovide a pattern and it will foundthere is some more complex patters with childprocess but for now this is ok,['javascript'] +1065755,why python numpydelete does not raise indexerror when outofbounds index is in np array when using npdelete an indexerror is raise when an outofbounds index is used when an outofbounds index is in a nparray used and the array is used as the argument in npdelete why doesnt this then raise an indexerrornpdeletenparray0 2 4 5 6 7 8 9 9this gives an indexerror as it should index 9 is out of boundswhile npdeletenparange05 nparray9and npdeletenparange05 9givearray0 1 2 3 4,['python'] +1065844,access restrictions in eclipse multiple projects with gradle i have a gradle project in eclipse consisting of multiple subprojects i currently have subprojects a b and cproject a should have access to project b project b should have access to project c but project a should not have access to project ca b b c but not a ci can easily test this by having a java example class in project a which tries to use a class from project ci have achieved this with gradle using the following setup in the main buildgradle file and using the transitive propertyprojectprojecta dependencies compile projectprojectb transitive false projectprojectb dependencies compile projectprojectc transitive false running gradles compilejava on project as example class gives the correct error message i would like to have this error should up as a compile error in eclipse i was also able to manually configure the classpath in a way that the desired relationship holds but a gradle refreshrebuild resets the classpath againis it possible to use gradles java compiler instead of the eclipse compiler or should i influence the classpath files when doing a gradle refreshrebuild is there maybe a different solutioni would like to hear what is the preferred approach for this situation thanks,['java'] +1065938,if i build a solution from c code how can i tell which applications were actually built i have code that will build not rebuild an entire solution from ca standard build will only compile projects which have actually changedafter the build finishes i would like to know which projects were actually builti have tried1 looking for a changedunchanged value or similar from the buidlresult after the build finishes2 attaching a custom logger and trapping every event then poring over the messages to see if there is any difference between changed and unchanged projectsi am really surprised that such a basic piece of information is not readily available for example it seems logical that the projectfinishedeventargs argument of the loggers projectfinished event would contain a boolean or status value but if it is there then i have overlooked itdoes anyone know how to tell whether the product of an msbuild was recompiled or not i hate to resort to checking timestamps on the output binaries but maybe that is what i will have to doprivate void dobuild projectcollection pc new projectcollection buildlog new crmbuildlogger parameters logfilename dictionarystring string globalproperty new dictionarystring string buildparameters bp new buildparameterspc detailedsummary true loggers new listilogger buildlog buildrequestdata buildrequest new buildrequestdatasolutionfilename globalproperty 120 new build null buildlogbuildresult buildmanagerdefaultbuildmanagerbuildbp buildrequest,['c#'] +1066022,angular 2 universal serverside rendering i was reading about angular 2 server side rendering with nodebut i cannot find an example or explain how should i do thati need to render some pages with angular from server any advice,['javascript'] +1066044,why is a type registered twice when lifetime manager is specified i am using unitys register by convention mechanism in the following scenariopublic interface iinterface public class implementation iinterface given implementation class and its interface i am running registertypes in the following wayunitycontainerregistertypes new typeofimplementation withmappingsfromallinterfaces withnamedefault withlifetimecontainercontrolledafter this call unitcontainer contains three registrationsiunitycontainer iunitycontainer okiinterface implementation okimplementation implementation when i change the call as followsunitycontainerregistertypes new typeofimplementation withmappingsfromallinterfaces withnamedefaultthe container contains only two registrationsiunitycontainer iunitycontainer okiinterface implementation okthis is the desired behaviourafter peeking into unitys source code i have noticed that there is some misunderstanding about how iunitycontainerregistertype should workthe registertypes method works as follows the comments indicate what are the values in the scenarios presented aboveforeach var type in types var fromtypes getfromtypestype iinterface var name getnametype null var lifetimemanager getlifetimemanagertype null or containercontrolled var injectionmembers getinjectionmemberstypetoarray null registertypemappingscontainer overwriteexistingmappings type name fromtypes mappings if lifetimemanager null injectionmemberslength 0 containerregistertypetype name lifetimemanager injectionmembers because fromtypes is not empty the registertypemappings adds one type mapping iinterface implementation correctthen in case when lifetimemanager is not null the code attempts to change the lifetime manager with the following callcontainerregistertypetype name lifetimemanager injectionmembersthis functions name is completely misleading because the documentation clearly states thatregistertype a lifetimemanager for the given type and name with the container no type mapping is performed for this typeunfortunately not only the name is misleading but the documentation is wrong when debugging this code i have noticed that when there is no mapping from type implementation in the scenarios presented above it is added as type type and that is why we end up with three registrations in the first scenarioi have downloaded unitys sources to fix the problem but i have found the following unit testtestmethodpublic void registersmappingandimplementationtypewithlifetimeandmixedinjectionmembers var container new unitycontainer containerregistertypesnew typeofmocklogger getname t name getfromtypes t tgettypeinfoimplementedinterfaces getlifetimemanager t new containercontrolledlifetimemanager var registrations containerregistrationswherer rmappedtotype typeofmockloggertoarray assertareequal2 registrationslength which is almost exactly my case and leads to my questionwhy is this expected is it a conceptual mistake a unit test created to match existing behaviour but not necessarily correct or am i missing something importanti am using unity v4030319,"['c#', '.net']" +1066243,avoiding blurriness at start end of video even after using setpreferredvideostabilizationmodeavcapturevideostabilizationmodeauto we capture video on ios while using setpreferredvideostabilizationmodeavcapturevideostabilizationmodeauto but the video still sometimes comes out blurry at the start and at the end fine in the middle though which is very problematic because we grab the first frame as a still image in order to enable video photo capabilities without switching camera modesplacing the device flat on a desk removes all blurriness so the whole video is sharp throughout this suggests it has something to do with video stabilization but is there another property to setdoes locking the focus mode matter any other troubleshooting tipshere is the video capture function from pbjvision which we use voidstartvideocapture if self cansessioncapturewithoutput currentoutput cameramode pbjcameramodevideo self failvideocapturewitherrorcodepbjvisionerrorsessionfailed dlogsession is not setup properly for capture return dlogstarting video capture self enqueueblockoncapturevideoqueue if flagsrecording flagspaused return nsstring guid nsuuid new uuidstring nsstring outputfile nsstring stringwithformatvideo mp4 guid if delegate respondstoselectorselectorvisionwillstartvideocapturetofile outputfile delegate visionself willstartvideocapturetofileoutputfile if outputfile self failvideocapturewitherrorcodepbjvisionerrorbadoutputfile return nsstring outputdirectory capturedirectory nil nstemporarydirectory capturedirectory nsstring outputpath outputdirectory stringbyappendingpathcomponentoutputfile nsurl outputurl nsurl fileurlwithpathoutputpath if nsfilemanager defaultmanager fileexistsatpathoutputpath nserror error nil if nsfilemanager defaultmanager removeitematpathoutputpath errorerror self failvideocapturewitherrorcodepbjvisionerroroutputfileexists dlogcould not setup an output file file exists return if outputpath outputpath length 0 self failvideocapturewitherrorcodepbjvisionerrorbadoutputfile dlogcould not setup an output file return if mediawriter mediawriterdelegate nil mediawriter nil mediawriter pbjmediawriter alloc initwithoutputurloutputurl mediawriterdelegate self avcaptureconnection videoconnection captureoutputvideo connectionwithmediatypeavmediatypevideo self setorientationforconnectionvideoconnection starttimestamp cmclockgettimecmclockgethosttimeclock timeoffset kcmtimeinvalid flagsrecording yes flagspaused no flagsinterrupted no flagsvideowritten no capturethumbnailtimes nsmutableset set capturethumbnailframes nsmutableset set if flagsthumbnailenabled flagsdefaultvideothumbnails self capturevideothumbnailatframe0 self enqueueblockonmainqueue if delegate respondstoselectorselectorvisiondidstartvideocapture delegate visiondidstartvideocaptureself this code configures pbjvision and starts video captureprivate func initpbjvision configure pbjvision pbjdelegate self pbjcameramode video pbjcameraorientation portrait pbjfocusmode autofocus pbjoutputformat preset pbjcameradevice back pbjthumbnailenabled false log status printconfigured pbjvision pbjstartvideocaptureonce pbj is ready with its preview we make the camera focus on the midpoint of the screen called when pbjvision preview beginsfunc visionsessiondidstartpreviewvision pbjvision focus screen at midpoint let focus x cgfloat05 let focus y cgfloat05,['ios'] +1066416,how to style jquery chosen select box i am using jquery chosen for my multiselect box however i do find the styles predefined in chosencss file is kind of hard to overwrite which totally getting rid of chosencss might also not be a very good option here is my fiddle htmlselect classchosen multipletrue styleheight 34px width 280px optionchooseoption optionjqueryoption option selectedselectedmootoolsoption optionprototypeoption option selectedselecteddojo toolkitoptionselectcss chosenchoices borderradius 3px boxshadow inset 0px 1px 2px rgba03 border none height 34px important cursor text margintop 12px paddingleft 15px borderbottom 1px solid d width 285px textindent 0 marginleft 30px i tried to directly write the css for chosenchoices ul some works like borderradius and boxshadow but others margin height padding border etc get overwritten by chosencss file one option is to put important for every setting which does not work this will work for most stuffs but still not the height any thoughts,"['jquery', 'css']" +1066468,semantic ui unobtrusively test form validity i have multiple form classed divs in my page and i would like to know if there is a method that i can use to unobtrusively test the validity of each form each div with the class of form has a button with the class of ok which allows the user to continue through the form divs i would like to thisable that button on page load to ensure that all relevant data is collected from the forms and only when the form is valid allow progression i have tried adding a function to each form elements change which calls semantics is valid but that highlights each and every validity issue this jsfiddle illustrates my problem when the first name field is clicked into it automatically shows all errors on the form i want the errors to only show when a required field has been blurred rather than showing all errors as a result of testing using is validanyone got any ideas,['jquery'] +1066671,selectors be specific on righthand side learn jquery saysbe specific on the righthand side of your selector and less specific on the left unoptimized divdata gonzalez optimized data tdgonzalez i understand the part with the lefthand side but what about the part to be specific on the righthand size how true is this on modern browsers as far as i am aware the sizzle engine is not used on modern browsers let us modify our unoptimized example to this to include the fact we need to be specific on the righthand side by removing the div unoptimized modification data gonzalez for our optimized example wed have for modern browsershave queryselectorall called on datahave getelementsbytagname on td from the result set from step 1call queryselectorall for gonzales from the result set from step 2vs our unoptimized modification examplehave queryselectorall called on datacall queryselectorall for gonzales from the result step from 1basically were skipping step 2 so would not data gonzalez run faster than data tdgonzalez making the principle be specific on the righthand size of your selector obsolete for modern browsers,['jquery'] +1066779,phppaypalerror 14077410ssl routinesl23 get server hellosslv3 alert handshake failure today a website with php 55 that was working fine has started to throw this errorerror14077410ssl routinesl23 get server hellosslv3 alert handshake failurei have tried many solutions from different questions but i cannot find the errormamp ssl error error14077410ssl routinesl23 get server hellosslv3 alert handshake failurehere says to change the curlopt ssl verifypeer to false but does not worki have tried with many sslversions and cipher list but does not work eitheras i said this problem was not here a few days ago maybe it is something new related with the version 164any idea,['php'] +1066947,gulp with livereload i have a website that i have built with node i can successfully start and run the site by running node serverjs from the commandline i then access the site by visiting httplocalhost30 in my browser i am now trying to improve some of the build process surrounding the site to do that i am relying on gulpi want to automatically reload the webpage when a change is made to the html or css files i stumbled upon the gulplivereload plugin i have installed it as described in the docs however when i visit httplocalhost35729 in the browser i just see the following minilr welcome version 018my gulp task is configured like thisgulptasklaunch function var towatch srchtml srccss livereloadlisten gulpwatchtowatch function consolelogreloading livereload i do not see my home page like i do when i visit httplocalhost30 after running node serverjs what am i missing,['javascript'] +1067003,why is the value of foox undefined in foox foo n 2 this codevar foo n 1var bar foofoox foo n 2can you please explain what is meant byfoox foo n 2i see that n2 is assigned to foo why is undefined assigned to foox does foo n 2 return undefined,['javascript'] +1067114,seeing the sql that linq generates if i have a linq to sql statement for examplevar query from a in thiscontextapples select anametolistwhen i want to see what sql is being generated by linq what i do is that i comment out the tolist and put a breakpoint on the command after this linq statement and then i can hover it and read the sqlmy question is that a correct way of getting the generated sql,['c#'] +1067127,why is not my vector drawable scaling as expected i am attempting to use vector drawables in my android app from emphasis minein android 50 api level 21 and above you can define vector drawables which scale without losing definitionusing this drawablevector xmlnsandroidandroidheight24dpandroidwidth24dpandroidviewportwidth24androidviewportheight24path androidfillcolorcolorcolorprimary androidpathdatam1420a22 0 01 12a22 0 01 1020h14m122a11 0 01 133v408c1584456 18703 1810v16l2119h3l616v10c6703 816456 11408v3a11 0 01 122z and this imageviewimageview androidlayout width400dp androidlayout height400dp androidsrcdrawableicon bellproduces this blurry image when attempting to thisplay the icon at 400dp on a largish highres circa 2015 mobile device running lollipopchanging the width and height in the definition of the vector drawable to 200dp significantly improves the situation at the 400dp rendered size however setting this as a drawable for a textview element ie icon to the left of the text now creates a huge iconmy questions1 why is there a widthheight specification in the vector drawable i thought the entire point of these is that they scale up and down losslessly making width and height meaningless in its definition2 is it possible to use a single vector drawable which works as a 24dp drawable on a textview but scales up well to use as much larger images too eg how do i avoid creating multiple vector drawables of different sizes and instead use one which scales to my rendered requirements3 how do i effectively use the widthheight attributes and what is the difference with viewportwidthheightadditional detailsdevice is running api 22using android studio v151 with gradle version 150manifest is compile and target level 23 min level 15 i have also tried moving min level to 21 but this made no differencedecompiling the apk with min level set to 21 shows a single xml resource in the drawable folder no rasterized images are produced,['android'] +1067216,override private method in java there something ambiguous about this idea and i need some clarificationsmy problem is when using this codepublic class b private void don systemoutprintlnhoho private public static void mainstring args b t new a tdon class a extends b public void don systemoutprintlnhoho public the output is hoho privateis this because the main function is in the same class as the method don or because of overridingi have read this idea in a book and when i put the main function in another class i get a compiler error,['java'] +1067339,what is the buttonbarlayout and how should we use it when i developed i found a new widget called androidsupportv7widgetbuttonbarlayout unexpectedly i tried to search it on the internet but nothing was found even on the official development documents site in the meantime i found two buttonbarlayout when i search buttonbarlayout everywhere in android studio one is androidsupportv7widgetbuttonbarlayout and the other is comandroidinternalwidgetbuttonbarlayout i tried to read source codes of both i found that they are the same except package name so i thought maybe androidsupportv7widgetbuttonbarlayout came from comandroidinternalwidgetbuttonbarlayout after the internal buttonbarlayout was through tests and released at the same time buttonbarlayout is inherited from linearlayoutbut there are some questionwhat can we get from buttonbarlayout literally and how should we use iti noticed the variable of private boolean mallowstacking when it changes orientation of this layout would be changed but i did not really understand what it is used forso does somebody know buttonbarlayout wellps i used android studio of 200 preview 4 and gradle plugin of 200alpha3 and android support library of 2311 and platformtools of 231 and buildtools of 2302,['android'] +1067368,lint error do not treat position as fixed only use immediately i am contributing to open source library and got lint error do not treat position as fixed only use immediately and call holdergetadapterposition to look it up later for this code override public void onbindviewholderrecyclerviewviewholder holder int position madapteronbindviewholderholder position if isfirstonly position mlastposition for animator anim getanimatorsholderitemview animsetdurationmdurationstart animsetinterpolatorminterpolator mlastposition position else viewhelperclearholderitemview i have checked that it is because the position is saved for the future use it is a question to library creator why they need this logic but issue thisappeared when i change the usage of the position to the usage holdergetadapterposition override public void onbindviewholderrecyclerviewviewholder holder int position madapteronbindviewholderholder position if isfirstonly holdergetadapterposition mlastposition for animator anim getanimatorsholderitemview animsetdurationmdurationstart animsetinterpolatorminterpolator mlastposition holdergetadapterposition else viewhelperclearholderitemview i assume that conceptually it did not change much but lint is satisfied now why,['android'] +1067615,how can i get validation messages to render on collection properties when using new guid indexes each time in this example aspnet mvc 4 program i have a user fill in details about a horse race the race has a name a well as a list of horses involved each horse has a name and an agethe form uses ajax and javascript to allow the person to add and delete horse input fields on the fly which is then submitted all at once when the submit button is pressedto make this process easy for me i am using an html helper made by matt lunnpublic static mvchtmlstring editorformanytmodel tvaluethis htmlhelpertmodel html expressionfunctmodel ienumerabletvalue expression string htmlfieldname null where tmodel class var items expressioncompilehtmlviewdatamodel var sb new stringbuilder if stringisnulloremptyhtmlfieldname var prefix htmlviewcontextviewdatatemplateinfohtmlfieldprefix htmlfieldname prefixlength 0 prefix stringempty expressionhelpergetexpressiontextexpression foreach var item in items var dummy new item item var guid guidnewguidtostring var memberexp expressionmakememberaccessexpressionconstantdummy dummygettypegetpropertyitem var singleitemexp expressionlambdafunctmodel tvaluememberexp expressionparameters sbappendstringformatinput typehidden name0index value1 htmlfieldname guid sbappendhtmleditorforsingleitemexp null stringformat01 htmlfieldname guid return new mvchtmlstringsbtostringwhile i do not understand all the details please read the blog post i do know that it changes the index values into guids rather than sequential integers this allows me to delete items in the middle of the list without needing to recalculate indexeshere is the rest of my code for my mcvehomecontrollercspublic class homecontroller controller httpget public actionresult index var model new race start with one already filled in modelhorsesinraceaddnew horse name scooby age 10 return viewmodel httppost public actionresult indexrace postedmodel if modelstateisvalid model is valid redirect to another page return redirecttoactionviewhorselisting else model is not valid show the page again with validation errors return viewpostedmodel httpget public actionresult ajaxmakehorseentry new blank horse for ajax call var model new listhorse new horse return partialviewmodel modelscspublic class race public race horsesinrace new listhorse thisplayname race name required public string racename get set thisplayname horses in race public listhorse horsesinrace get set public class horse thisplayname horses name required public string name get set thisplayname horses age required public int age get set indexcshtmlmodel collectionajaxpostingmodelsraceh1race detailsh1using htmlbeginform htmlvalidationsummary hr div htmlthisplaynameforx xracename htmleditorforx xracename htmlvalidationmessageforx xracename div hr div idhorselistinghtmleditorformanyx xhorsesinracediv button idbtnaddhorse typebuttonadd new horsebutton input typesubmit valueenter horses script typetextjavascript documentreadyfunction add button logic btnaddhorseclickfunction ajax url urlactionajaxmakehorseentry cache false method get success function html horselistingappendhtml deletehorse buttons horselistingonclick buttondeletehorse function var horseentrytoremove thisclosestdivhorse horseentrytoremoveprevinputtypehiddenremove horseentrytoremoveremove scriptviewssharededitortemplateshorsecshtmlmodel collectionajaxpostingmodelshorsediv classhorse div htmlthisplaynameforx xname htmleditorforx xname htmlvalidationmessageforx xname div div htmlthisplaynameforx xage htmleditorforx xage htmlvalidationmessageforx xage div button typebutton classdeletehorseremove horsebutton hr divviewshomeajaxmakehorseentrycshtmlmodel ienumerablecollectionajaxpostingmodelshorsehtmleditorformanyx x horsesinracethe data flow works with this code a person is able to create and delete horse entries as much as they want on the page and when the form is submitted all entered values are given to the action methodhowever if the user does not enter in the required information on a horse entry modelstateisvalid will be false showing the form again but no validation messages will be shown for the horse properties the validation error do show up in the validationsummary list thoughfor example if race name is left blank along with one horses name a validation message will be shown for the former the latter will have a validation span with the class fieldvalidationvalidi am very sure this is caused because the editorformany method creates new guids for each property each time the page is created so validation messages cannot be matched to the correct fieldwhat can i do to fix this do i need to abandon guid index creation or can an alteration be made to the editorformany method to allow validation messages to be passed along correctly,['c#'] +1067644,crash on error code 1001 error nsurlerrortimedout i am having the following crash 005 crash rate so i have yet to reproduce it0 libthispatchdylib 0x208b2028 thispatch semaphore signal slow 174 1 myproject 0x00253f39 64crnsurlsessiontaskproxy wrapdatacompletionhandlerforsession block invoke 42 cfnetwork 0x2120796d 75 nsurlsessionlocal taskforclassrequestuploadfilebodydatacompletion block invoke 143 cfnetwork 0x21216ef7 49 nscflocalsessiontask task onqueue didfinish block invoke 2764 foundation 0x2150a52d nsblockoperation is calling out to a block 65 foundation 0x2146beff nsblockoperation main 1446 foundation 0x2145e2ef nsoperationinternal start 7727 foundation 0x2150c7ed nsoqschedule f 1908 libthispatchdylib 0x208adf97 thispatch queue drain 17609 libthispatchdylib 0x208a6f2f thispatch queue invoke 28010 libthispatchdylib 0x208af325 thispatch root queue drain 39811 libthispatchdylib 0x208af193 thispatch worker thread3 9212 libsystem pthreaddylib 0x20a3ce0d pthread wqthread 102213 libsystem pthreaddylib 0x20a3c9fc start wqthread 6the crashes only appears on ios9 none whatsoever on ios8 but this could just be a coincidence i am also seeing this via crittercism breadcrumbsi am also using background fetches which do hit the network layerany idea why this is happing,"['ios', 'iphone']" +1067646,print styles overriding screen styles after airprint in ios webview i am working on a hybrid html5ios app that uses the safari webview we are using airprint to allow the user print the contents of the webview the problem i am having is that after the print dialog is opened the print styles are taking affect on the screen and even after printing is complete or canceled do not go away this does not happen in our windows or android versions of the app which use cef and android system webview respectively print styles in those versions of the application are only applied to the print out as expected anyone have any experience using airprint with safari webview that could shed some light on a solution i have considered just addingremoving the link tag containing the css with javascript before and after printing but that feels hacky and does not answer the curious question of why print styles are being applied to the screen any help appreciated sorry there is no real way to attach code to this,"['ios', 'css']" +1067683,robust endless loop for server written in python i write a server which handles events and uncaught exceptions during handling the event must not terminate the serverthe server is a single nonthreaded python processi want to terminate on these errors typeskeyboardinterruptmemoryerrorthe list of built in exceptions is long i do not want to reinvent this exception handling since i guess it was done several times beforehow to proceed have a whitelist a list of exceptions which are ok and processing the next event is the right choicehave a blacklist a list of exceptions which indicate that terminating the server is the right choicehint this question is not about running a unix daemon in background it is not about double fork and not about redirecting stdinstdout,['python'] +1067704,custom jackson httpmessageconverter no longer works in spring 42 i am updating an application from spring platform version 113release to 201release which bumps the spring framework version from 417 to 424 and jackson from 246 to 264 there does not seem to have been any significant changes in spring or jacksons handling of custom httpmessageconverter implementations but my custom json serialization is failing to occur and i have not been able to determine why the following works fine in the previous spring platform releasemodeljsonfilterfieldfilterpublic class mymodel model fields and methods model wrapperpublic class responseenvelope private setstring fieldset private setstring exclude private object entity public responseenvelopeobject entity thisentity entity public responseenvelopeobject entity setstring fieldset setstring exclude thisfieldset fieldset thisexclude exclude thisentity entity public object getentity return entity jsonignore public setstring getfieldset return fieldset jsonignore public setstring getexclude return exclude public void setexcludesetstring exclude thisexclude exclude public void setfieldsetsetstring fieldset thisfieldset fieldset public void setfieldsstring fields setstring fieldset new hashsetstring if fields null for string field fieldssplit fieldsetaddfield thisfieldset fieldset controllercontrollerpublic class mymodelcontroller autowired mymodelrepository mymodelrepository requestmappingvalue model method requestmethodget produces mediatypeapplication json value public httpentity findrequestparamrequiredfalse setstring fields requestparamrequiredfalse setstring exclude listmymodel objects mymodelrepositoryfindall responseenvelope envelope new responseenvelopeobjects fields exclude return new responseentityenvelope httpstatusok custom httpmessageconverterpublic class filteringjackson2httpmessageconverter extends mappingjackson2httpmessageconverter private boolean prefixjson false override public void setprefixjsonboolean prefixjson thisprefixjson prefixjson supersetprefixjsonprefixjson override protected void writeinternalobject object httpoutputmessage outputmessage throws ioexception httpmessagenotwritableexception objectmapper objectmapper getobjectmapper jsongenerator jsongenerator objectmappergetfactorycreategeneratoroutputmessagegetbody try if thisprefixjson jsongeneratorwriteraw if object instanceof responseenvelope responseenvelope envelope responseenvelope object object entity envelopegetentity setstring fieldset envelopegetfieldset setstring exclude envelopegetexclude filterprovider filters null if fieldset null fieldsetisempty filters new simplefilterprovider addfilterfieldfilter simplebeanpropertyfilterfilteroutallexceptfieldset setfailonunknownidfalse else if exclude null excludeisempty filters new simplefilterprovider addfilterfieldfilter simplebeanpropertyfilterserializeallexceptexclude setfailonunknownidfalse else filters new simplefilterprovider addfilterfieldfilter simplebeanpropertyfilterserializeallexcept setfailonunknownidfalse objectmappersetfilterproviderfilters objectmapperwritevaluejsongenerator entity else if object null jsongeneratorwritenull else filterprovider filters new simplefilterprovidersetfailonunknownidfalse objectmappersetfilterproviderfilters objectmapperwritevaluejsongenerator object catch jsonprocessingexception e eprintstacktrace throw new httpmessagenotwritableexceptioncould not write json egetmessage configurationconfigurationenablewebmvcpublic class webservicesconfig extends webmvcconfigureradapter override public void configuremessageconverterslisthttpmessageconverter converters filteringjackson2httpmessageconverter jsonconverter new filteringjackson2httpmessageconverter jsonconvertersetsupportedmediatypesmediatypesapplication json convertersaddjsonconverter other configurationsnow i am getting this exception which is caught by spring and logged and a 500 error when making any sort of request main warn oswsmsdefaulthandlerexceptionresolver failed to write http message orgspringframeworkhttpconverterhttpmessagenotwritableexception could not write content can not resolve propertyfilter with id fieldfilter no filterprovider configured through reference chain orgoncoblockscentromerewebcontrollerresponseenvelopeentityjavautilarraylist0 nested exception is comfasterxmljacksondatabindjsonmappingexception can not resolve propertyfilter with id fieldfilter no filterprovider configured through reference chain orgoncoblockscentromerewebcontrollerresponseenvelopeentityjavautilarraylist0the configuremessageconverters method executes but it does not look like custom converter is ever utilized during requests is it possible that another message converter could be preventing this one from reaching my response my understanding was that overriding configuremessageconverters would prevent converters other than the manually registered ones from being usedno changes have been made between the working and nonworking versions of this code besides updating dependency versions via the spring platform has there been any change in the json serialization that i am just missing in the documentation editfurther testing yields strange results i wanted to test to check the following thingsis my custom httpmessageconverter actually being registeredis another converter overridingsuperseding itis this a problem with my test setup onlyso i added an extra test and took a look at the outputautowired webapplicationcontext webapplicationcontextbeforepublic void setup mockmvc mockmvcbuilderswebappcontextsetupwebapplicationcontextbuildtestpublic void test throws exception requestmappinghandleradapter adapter requestmappinghandleradapter webapplicationcontextgetbeanrequestmappinghandleradapter listentrezgene genes entrezgenecreatedummydata setstring exclude new hashset excludeaddentrezgeneid responseenvelope envelope new responseenvelopegenes new hashsetstring exclude for httpmessageconverter converter adaptergetmessageconverters systemoutprintlnconvertergetclassgetname if convertercanwriteresponseenvelopeclass mediatypeapplication json mockhttpoutputmessage message new mockhttpoutputmessage converterwriteobject envelope mediatypeapplication json message systemoutprintlnmessagegetbodyasstring and it works fine my the envelope object and its contents are serialized and filtered correctly so either there is an issue with the request handling before it reaches the message converters or there has been a change in how mockmvc is testing requests,['java'] +1067799,pygtk color for drag highlight i am trying to change the highlight color for a gtkeventbox it has a certain background color and i want to draw a line around it with its complementary color i have found drag highlight which draws a line around the widget but i have not figured out how to change the color it is always black any ideas,['python'] +1067900,how to convert a kotlin source file to a java source file i have a kotlin source file but i want to translate it to javahow can i convert kotlin to java source,['java'] +1067919,variadic templates parameter pack and its thiscussed ambiguity in a parameter list in this question i will refer to my previous questionin that question i found that the following is not validtemplatetypename t typename a typename sclass c this is becauseit is not valid code for class templates because their arguments must always be specified which will always result in an ambiguity unless the parameter pack is at the end and slurps up any remaining template parametersthat makes sense of course and i got itthen as an alternative approach the following that involves a specialization has been proposedtemplatetypename f typename sclass ctemplatetypename t typename a typename sclass cta s actually it seems to work so thanks to the one that proposed itanyway what i do not understand is why this is valid code while the previous one was notshould it suffer from the same ambiguity of the previous solution why and how does the compiler solve that ambiguity in that caseaccording with the previous question see the link at the start of this question it seems to me that still the variadic part should slurp up any parameters to the end thus this code should not be valid as welli am wrong of course but whats wrong exactly in my reasoning,['c++'] +1068128,how can i highlight a wordterm quicker and smarter i have some textp classdraghello world attack on titan season twopcurrently if a user wants to highlight a wordterm with the cursor they will click and drag letter by letter i want this process to be quicker for example if the user starts to highlight at it should auto highlight the rest of the word attack so the empty space is the divider i am aware this is possible by dividing the words into divs but i am hoping for a solution with pure text within one p tag,"['javascript', 'jquery']" +1068516,weird situation in prime number checking code when i was solving a problem for project euler it asked me to sum up all the primes below 2 million here is my codeincludestdiohincludemathhint isprimeintint main long long int sum 0 int i index fori 2 i 20 i ifisprimei sum i printfllin sumint isprimeint num int i index int sq sqrtnum fori 2 i sq i ifnum i 0 return 0 return 1this code leads to the correct answer 142913828922but when i change the for loop in isprime tofori 2 i sq1 i or even sq2 sq3 etcit leads to incorrect results such as 142913828920 and 142913828917 etcwhy does it go wrong theoretically it does not change the number isprime sends to main does it,['c'] +1068717,inapp purchases made via promo codes return empty developer payload string i have an app published to the alpha channel with an inapp unmanaged item that costs 1when i purchase normally ie use a creditdebit card google returns the correct developer payload string but if i choose to redeem a promo code and enter said code google returns an empty developer payload string and thus authentication fails in oniabpurchasefinishedi should mention that this only occurs if i choose to redeem a code from within the apps purchase flow and everything works flawlessly if i open play store first redeem the code and then come back and open the appis this a bug on googles partedit the play store thing is expected since it cannot know your payload and the purchase is done without having to check for it,['android'] +1068773,why is not this for loop valid considerint ia34for auto row ia for auto col rowthe first for iterates through ia whose elements are arrays of size 4 because row is not a reference when the compiler initializes row it will convert each array element like any other object of array type to a pointer to that arrayas first element as a result in this loop the type of row is inti am not really sure that i understand how this auto works but if i can assume it automatically gives a type to a row based on ia array members type but i do not understand why this kind of for where row is not a reference is not valid why is this going to happen pointer to that arrayas first element because of what,['c++'] +1068864,how to reference another collection on insert i am trying to figure how to take an image a file using collectionfs and insert the images id into my items imageid fieldlibcollectionsitemsjsitems new mongocollectionitemsitemsattachschemanew simpleschema name type string label name userid type string regex simpleschemaregexid autoform type hidden label false autovalue function return meteoruserid image type string optional true autoform label false affieldinput type fileupload collection images label select photo imageid type string libcollectionsimagesjsif meteorisserver var imagestore new fsstores3images accesskeyid meteorsettingsawsaccesskeyid secretaccesskey meteorsettingsawssecretaccesskey bucket meteorsettingsawsbucket images new fscollectionimages stores imagestore filter allow contenttypes image on the client just create a generic fs store as do not have access or want access to s3 settings on clientif meteorisclient var imagestore new fsstores3images images new fscollectionimages stores imagestore filter allow contenttypes image right now my allow rules areserverallowsjsitemsallow insert functionuserid docreturn doc docuserid userid update functionuserid doc return doc docuserid userid remove functionuserid doc return doc docuserid useridimagesallow insert functionuserid doc return true update functionuseriddoc return true remove functionuseriddoc return true download functionuserid doc return truei am using autoform so my form looks like thisclientitem formhtmltemplate nameinsertitemform autoform collectionitems idinsertitemform typeinsert afquickfield namename autocompleteoff afquickfield nameimage idimagefile button typesubmitcontinuebutton autoformtemplateright now when i select browse and select an image it will be in the database and i want to take that id it has and place it in the item that is created afterwards but how do i fetch that particular image i figured this is a good way to reference an imageupdate 1find out the id is actually located hidden after a file is selectedinput typehidden classjsvalue dataschemakeyimage valuema633ffpkhyewcrm8so i am trying to get ma633ffpkhyewcrm8 to be placed as a string in the imageidupdate 2maybe one way is to use fsfile reference,['javascript'] +1068927,differences between copylist super t dest list extends t src and copylist dest list extends t src i am trying to learn java generics wildcard by reading the followingthere is one example in the materialpublic class collections public static t void copy list super t dest list extends t src for int i0 isrcsize i destsetisrcgeti i was wondering if i can change the method signature as the following public static t void copylist super t dest list extends t src a public static t void copylistt dest list extends t src are there any differences between these two method sinaturesexamples would be appreciated,['java'] +1068949,androidjava regex to remove extra zeros from substrings i have the following string as input 2030040320101003101final output will be like 2340320100103101ie all leading and trailing zeros will be removed and both positivenegative zeros will be simply zerowe can achieve this by split the string first and using regex for each part but my string size is more than 10 how can we achieve this using regexeditanalysis of answers i have tested all answers with string 0404040404014010401040100404004040404040401014040040040 and answer from wiktor stribia14ew passed all the test cases see here other answers were passed on most of the cases but not all,"['java', 'android']" +1069015,what is the difference between and in css in css will match any elementfrequently is used instead of to match all elements this is generally used for testing purposeswhat is the difference between and in css,['css'] +1069136,appdebugunalignedapk specified for property inputfile does not exist this morning when i opened my android studio project that i have been working on for a week or so it was suddenly unable to run the app on my phone it can sync with gradle without any errors but when i try to run the application i get the following errora problem was found with the configuration of task appzipaligndebug file appbuildoutputsapkappdebugunalignedapk specified for property inputfile does not existi have tried several things to fix this i have tried changing the build tools version the compilesdkversion and the gradle version without any luck i have searched the web for several hours now including all so questions about zipalign but have not found a solution yetapp gradleapply plugin comandroidapplicationandroid signingconfigs debug keyalias androiddebugkey keypassword android storefile filecusersteilmannsourceandroidandroid keystoredebugkeystore storepassword android compilesdkversion 22 buildtoolsversion 2300 defaultconfig applicationid dklivejazz minsdkversion 16 targetsdkversion 22 versioncode 10 versionname 40 buildtypes release minifyenabled false proguardfiles getdefaultproguardfileproguardandroidtxt proguardrulespro dependencies compile filetreeinclude jar dir libs testcompile junitjunit412 compile comandroidsupportappcompatv72211 compile comgoogleandroidgmsplayservicesmaps compile comandroidsupportdesign2 compile projectpath idealneedsproject gradle toplevel build file where you can add configuration options common to all subprojectsmodulesbuildscript repositories jcenter dependencies classpath comandroidtoolsbuildgradle200alpha5 note do not place your application dependencies here they belong in the individual module buildgradle files allprojects repositories jcenter task cleantype delete delete rootprojectbuilddirstacktrace exception isorggradleapitaskstaskvalidationexception a problem was found with the configuration of task appzipaligndebug at orggradleapiinternaltasksexecutionvalidatingtaskexecuterexecutevalidatingtaskexecuterjava55 at orggradleapiinternaltasksexecutionskipemptysourcefilestaskexecuterexecuteskipemptysourcefilestaskexecuterjava52 at orggradleapiinternaltasksexecutionskiptaskwithnoactionsexecuterexecuteskiptaskwithnoactionsexecuterjava52 at orggradleapiinternaltasksexecutionskiponlyiftaskexecuterexecuteskiponlyiftaskexecuterjava53 at orggradleapiinternaltasksexecutionexecuteatmostoncetaskexecuterexecuteexecuteatmostoncetaskexecuterjava43 at orggradleexecutiontaskgraphdefaulttaskgraphexecutereventfiringtaskworkerexecutedefaulttaskgraphexecuterjava203 at orggradleexecutiontaskgraphdefaulttaskgraphexecutereventfiringtaskworkerexecutedefaulttaskgraphexecuterjava185 at orggradleexecutiontaskgraphabstracttaskplanexecutortaskexecutorworkerprocesstaskabstracttaskplanexecutorjava66 at orggradleexecutiontaskgraphabstracttaskplanexecutortaskexecutorworkerrunabstracttaskplanexecutorjava50 at orggradleexecutiontaskgraphdefaulttaskplanexecutorprocessdefaulttaskplanexecutorjava25 at orggradleexecutiontaskgraphdefaulttaskgraphexecuterexecutedefaulttaskgraphexecuterjava110 at orggradleexecutionselectedtaskexecutionactionexecuteselectedtaskexecutionactionjava37 at orggradleexecutiondefaultbuildexecuterexecutedefaultbuildexecuterjava37 at orggradleexecutiondefaultbuildexecuteraccess0defaultbuildexecuterjava23 at orggradleexecutiondefaultbuildexecuter1proceeddefaultbuildexecuterjava43 at orggradleexecutiondryrunbuildexecutionactionexecutedryrunbuildexecutionactionjava32 at orggradleexecutiondefaultbuildexecuterexecutedefaultbuildexecuterjava37 at orggradleexecutiondefaultbuildexecuterexecutedefaultbuildexecuterjava30 at orggradleinitializationdefaultgradlelauncher4rundefaultgradlelauncherjava154 at orggradleinternalfactories1createfactoriesjava22 at orggradleinternalprogressdefaultbuildoperationexecutorrundefaultbuildoperationexecutorjava90 at orggradleinternalprogressdefaultbuildoperationexecutorrundefaultbuildoperationexecutorjava52 at orggradleinitializationdefaultgradlelauncherdobuildstagesdefaultgradlelauncherjava151 at orggradleinitializationdefaultgradlelauncheraccess200defaultgradlelauncherjava32 at orggradleinitializationdefaultgradlelauncher1createdefaultgradlelauncherjava99 at orggradleinitializationdefaultgradlelauncher1createdefaultgradlelauncherjava93 at orggradleinternalprogressdefaultbuildoperationexecutorrundefaultbuildoperationexecutorjava90 at orggradleinternalprogressdefaultbuildoperationexecutorrundefaultbuildoperationexecutorjava62 at orggradleinitializationdefaultgradlelauncherdobuilddefaultgradlelauncherjava93 at orggradleinitializationdefaultgradlelauncherrundefaultgradlelauncherjava82 at orggradlelauncherexecinprocessbuildactionexecuterdefaultbuildcontrollerruninprocessbuildactionexecuterjava94 at orggradletoolinginternalproviderrunnerbuildmodelactionrunnerrunbuildmodelactionrunnerjava46 at orggradlelauncherexecchainingbuildactionrunnerrunchainingbuildactionrunnerjava35 at orggradletoolinginternalproviderrunnersubscribablebuildactionrunnerrunsubscribablebuildactionrunnerjava58 at orggradlelauncherexecchainingbuildactionrunnerrunchainingbuildactionrunnerjava35 at orggradlelauncherexecinprocessbuildactionexecuterexecuteinprocessbuildactionexecuterjava43 at orggradlelauncherexecinprocessbuildactionexecuterexecuteinprocessbuildactionexecuterjava28 at orggradlelauncherexeccontinuousbuildactionexecuterexecutecontinuousbuildactionexecuterjava78 at orggradlelauncherexeccontinuousbuildactionexecuterexecutecontinuousbuildactionexecuterjava48 at orggradlelauncherdaemonserverexecexecutebuilddobuildexecutebuildjava52 at orggradlelauncherdaemonserverexecbuildcommandonlyexecutebuildcommandonlyjava36 at orggradlelauncherdaemonserverapidaemoncommandexecutionproceeddaemoncommandexecutionjava120 at orggradlelauncherdaemonserverexecwatchforthisconnectionexecutewatchforthisconnectionjava37 at orggradlelauncherdaemonserverapidaemoncommandexecutionproceeddaemoncommandexecutionjava120 at orggradlelauncherdaemonserverexecresetdeprecationloggerexecuteresetdeprecationloggerjava26 at orggradlelauncherdaemonserverapidaemoncommandexecutionproceeddaemoncommandexecutionjava120 at orggradlelauncherdaemonserverexecrequeststopifsingleuseddaemonexecuterequeststopifsingleuseddaemonjava34 at orggradlelauncherdaemonserverapidaemoncommandexecutionproceeddaemoncommandexecutionjava120 at orggradlelauncherdaemonserverexecforwardclientinput2callforwardclientinputjava74 at orggradlelauncherdaemonserverexecforwardclientinput2callforwardclientinputjava72 at orggradleutilswapperswapswapperjava38 at orggradlelauncherdaemonserverexecforwardclientinputexecuteforwardclientinputjava72 at orggradlelauncherdaemonserverapidaemoncommandexecutionproceeddaemoncommandexecutionjava120 at orggradlelauncherdaemonserverhealthdaemonhealthtrackerexecutedaemonhealthtrackerjava47 at orggradlelauncherdaemonserverapidaemoncommandexecutionproceeddaemoncommandexecutionjava120 at orggradlelauncherdaemonserverexeclogtoclientdobuildlogtoclientjava66 at orggradlelauncherdaemonserverexecbuildcommandonlyexecutebuildcommandonlyjava36 at orggradlelauncherdaemonserverapidaemoncommandexecutionproceeddaemoncommandexecutionjava120 at orggradlelauncherdaemonserverexecestablishbuildenvironmentdobuildestablishbuildenvironmentjava72 at orggradlelauncherdaemonserverexecbuildcommandonlyexecutebuildcommandonlyjava36 at orggradlelauncherdaemonserverapidaemoncommandexecutionproceeddaemoncommandexecutionjava120 at orggradlelauncherdaemonserverhealthhintgcafterbuildexecutehintgcafterbuildjava41 at orggradlelauncherdaemonserverapidaemoncommandexecutionproceeddaemoncommandexecutionjava120 at orggradlelauncherdaemonserverexecstartbuildorrespondwithbusy1runstartbuildorrespondwithbusyjava50 at orggradlelauncherdaemonserverdaemonstatecoordinator1rundaemonstatecoordinatorjava246 at orggradleinternalconcurrentexecutorpolicycatchandrecordfailuresonexecuteexecutorpolicyjava54 at orggradleinternalconcurrentstoppableexecutorimpl1runstoppableexecutorimpljava40caused by orggradleapiinvaliduserdataexception file cusersteilmannsourceandroidprojectslivejazzdanmarkappbuildoutputsapkappdebugunalignedapk specified for property inputfile does not exist at orggradleapiinternaltasksexecutionvalidatingtaskexecuterexecutevalidatingtaskexecuterjava47,['android'] +1069265,better typeinitializationexception innerexception is also null introwhen an user creates a mistake in the configuration of nlog like invalid xml we nlog throw a nlogconfigurationexception the exception contains the description what is wrongbut sometimes this nlogconfigurationexception is eaten by an systemtypeinitializationexception if the first call to nlog is from a static fieldpropertyexampleeg if the user has this programusing systemusing systemcollectionsgenericusing systemlinqusing nlognamespace typeinitializationexceptiontest class program this throws a nlogconfigurationexception because of bad config like invalid xml private static logger logger logmanagergetcurrentclasslogger static void main consolewritelinepress any key consolereadline and there is a mistake in the config nlog throwsthrow new nlogconfigurationexceptionexception occurred when loading configuration from filename exceptionbut the user will seecopy exception details to the clipboard systemtypeinitializationexception was unhandled message an unhandled exception of type systemtypeinitializationexception occurred in mscorlibdll additional information the type initializer for typeinitializationexceptiontestprogram threw an exceptionso the message is gone questionswhy is innerexception not visible tested in visual studio 2013 can i send more info to the typeinitializationexception like a message we already sending an innerexception can we use another exception or are there properties on exception so that more info is reported is there another way to give more feedback to the usernotesof course we have no influence on the program written by the user i am one of the maintainers of nlogdo you like to test it by yourself checkout and start nlogsrcnlognetfx45slneditplease note that i am the library maintainer not the user of the library i cannot change the calling code,['c#'] +1069307,css when inlineblock elements linebreak parent wrapper does not fit new width how do you get an inlineblock element to fit its content width if the content linebreaks because of screen width parent inlineblock div stylethisplay inlineblock div stylethisplay inlineblock width200pxdiv if this child line breaks two 200px wide blocks are stacked vertically that should make the parent width 200px but the parent stays much wider than that div stylethisplay inlineblock width200pxdivdivi cannot think of how to phrase the question so it sounds easy but i put together a simple jsfiddle illustratingwide position relative width 100 border 1px solid black padding 5pxnarrow position relative width 175px border 1px solid black padding 5pxwrap thisplay inlineblock border 1px solid green margin autoinlineblock thisplay inlineblock verticalalign top background red minwidth 100px minheight 100px border 1px solid blacksection idwide div classwrap div classinlineblockdiv div classinlineblockdiv divsectionp when the red inlineblocks are forced to line break how do you make a parent with thisplayinlineblock the green border snap to fit how do you get rid of all the extra horiztonal space in the lower green bordered divpsection idnarrow div classwrap div classinlineblockdiv div classinlineblockdiv divsection,"['html', 'css']" +1069372,rest call with list of headers i have the following code snippet for invoking rest call i have around 8 headers to pass on for this rest call but the problem is that it is difficult to manage if in case the list of headers are increased in future i need to change evaluatechange method signature to include the additional headers as method paramspathv1restclienturiconsumes mediatypeapplication json produces mediatypeapplication json public interface restclient post pathsamplecallevaluate response evaluatechange headerparamheader1 string header1 headerparamheader2 string header2 headerparamheader3 string header3 headerparamheader4 string header4 headerparamheader5 string header5 headerparamheader6 string header6 headerparamheader7 string header7 headerparamheader8 string header8 context httpservletresponse response request requestplease provide your thoughts or code snippet to accommodate this i tried the following code snippet but it did not workwhere headermap contains all the 8 headers in itpathv1restclienturiconsumes mediatypeapplication json produces mediatypeapplication json public interface restclient post pathsamplecallevaluate response evaluatechange requestheader mapstring string headermap context httpservletresponse response request request,['java'] +1069375,defining the size of an array using a const int when i try to run this it gives me an error saying that the value in variable a is not constant that does not make sense to me because i explicitly made the variable a constant does the size of an array have to more constant than that meaning only define a 5 or initializing it as int arr5 or using malloc what is wrong with what i didint main const int a 5 int i int arr a for i 0 i 5 i arri i 2 printfd arr1 return 0,['c'] +1069501,select row with most recent date per user with 1 condition in jpa i have this entity and i want to list for each device the last event with the property message 1entitytablename t device eventnamedqueriesvalue namedqueryname deviceeventfindwithmessageactive query from deviceevent as de1 where de1message 1 and de1received select maxde2received from deviceevent de2 where de2deviceid de1deviceid public class deviceevent but i have an assertion problem in the last test because it considers device3 as a last event and its not the caseasserttrue numdeviceswithactivemessage1 deviceeventservicefindwithactivemessagesizedeviceevent deviceevent3 newdeviceeventdeviceevent3setmessage1deviceeventservicesavedeviceevent3deviceevent deviceevent4 newdeviceeventdeviceeventservicesavedeviceevent4asserttrue numdeviceswithactivemessage1 deviceeventservicefindwithactivemessagesize,"['java', 'sql']" +1069618,java 8 update 71 is trying to install a new helper tool on mac i just was prompted to update java it tells medoes anybody know what that helper tool does if it is new i probably do not need it is there a way to opt out or at least know what it is before installing itnote that i already checked the option to suppress sponsor offers in the java control panel under system preferencesnote also that if i do not enter the admin password the update does not get installed it is not an offer that is presented besides the update and that i can accept or rejectif this is a bad question or the wrong place please commenthere is a followupi got the message again and i searched for more information about it i learned that the update process has been wrapped into an application the applications wraps the actual package and proposes additional software if you opt out i guess it just installs the java updatethe new helper tool is probably this installation wrapper or possibly the additional software that is proposed if you do not opt outif you prefer to install a clean package you can extract it form the installer after the update downloaded click cancel then go to libraryapplication supportjava you can see there all the past java update downloads choose the latest version inside the folder you see an app and a dmg rightclick on the app and select show package contents inside the app go to contentsresources there you find a package javaappletpluginpkg that is the actual package copy it to your desktop and install it as you would any package it will still ask for your a name and password but this time it is asked by osx and used for installing that package and nothing else,['java'] +1069619,function name in if statement is converted in a strange way with this code valid c11include stdiohinclude typeinfobool my awesome funcint param return param 1int mainint argc char const argv fprintfstderr type of my awesome func sn typeidmy awesome funcname if my awesome func fprintfstderr whatn return 0the question is inside of the if statement while typeid returns me something that looks like fbie which i think is gcc language for function type i do not understand why this type is being implicitly converted into bool just an example also works with intwhy does the if statement compile and evaluate true,['c++'] +1069967,detecting elevated privileges on windows server 2008 or higher i have an c net 461 windows forms application running on windows server platforms 2008 or higher which requires to be run as administrator elevated privileges are required because the application changes user access rights on various folders underneath the iis default web site root if that mattersi have no luck in detecting if the application has been run as administrator if i start the application normally that is not as administrator the following codevar isadmin windowsidentitygetcurrentowneriswellknownwellknownsidtypebuiltinadministratorssidreturns true but the code which changes some user access rights on a directory fails with a insufficient privileges errorif i run the application as administrator the above check also returns true but the changing of user access rights works just fineother attempts i have made without successusing the gettokeninformation method inside the advapi32dll as suggested hereadding a manifest file to the application where i set the requestedexecutionlevel to requireadministratorthanks in advance for any help,['c#'] +1070164,ionic 2 using angular 2 pipe breaks on iosacannot find variable intl experiencing the same problem with the date percent and currency pipes when using them in a templateafor example i am using a simple percent pipe 0237 percent122 it works when running on chrome but when i deploy to an ios device it throws this errorexception referenceerror cannot find variable intl in 0237 percent122 has anyone else run into this problem any suggestions or help would be greatly appreciated thanks,['ios'] +1070171,potential issue with one of oracles trails on java generics i was reviewing one of the oracle trails on java generics entitled effects of type erasure and bridge methods and i could not convince myself of an explanation given curious i tested the code locally and i could not even reproduce the behavior which the trail explains here is the relevant codepublic class nodet public t data public nodet data thisdata data public void setdatat data systemoutprintlnnodesetdata thisdata data public class mynode extends nodeinteger public mynodeinteger data superdata public void setdatainteger data systemoutprintlnmynodesetdata supersetdatadata the oracle trail claims the following behavior for this code snippetmynode mn new mynode5node and mn a raw type compiler throws an unchecked warningnsetdatahello integer x mndata causes a classcastexception to be thrownthis code snippet should look like the following after type erasuremynode mn new mynode5node and mynodemn a raw type compiler throws an unchecked warningnsetdatahellointeger x stringmndata causes a classcastexception to be throwni did not understand the casts being used here or the behavior when i tried running this code locally using intellij with java 7 i got this behaviormynode mn new mynode5node and mn a raw type compiler throws an unchecked warningnsetdatahello causes a classcastexception to be throwninteger x mndatain other words the jvm will not allow a string to be used with setdata this is actually intuitive to me and it agrees with my understanding of generics since mynode mn was constructed with integer the compiler should be casting every call to setdata with integer to ensure type safety ie an integer is being passed incan someone shed some light on this apparent bug in the oracle trail,['java'] +1070268,threeway cookie i am building a popup with 3 buttons each button needs to set a cookie but with different expiry timedate i am using jquerycookie for this1 button is more a session cookie so when clicking this button the popup needs to thissapear and shown again when i start a new browser screen so not when i open a page in the same browser window and same website 1 button is for do not show popup again which will set cookie to 7 days1 cookie is set in the ajax succes function and is set to 365 daysi am having trouble to get the different expiry times to set up correctly so for example when i click the button with the session cookie then the popup shows again when i open a new page inside the website i cannot see what i am doing wrong i do not get any console errors but the cookies just would not set properlywhat i have is this documentreadyfunction var my cookie cookieregnewsletter if my cookie settimeoutfunction newslettermodalshow 10 closebtnonclick function cookieregnewsletter true path domain thismissbtnonclick function cookieregnewsletter true path domain expires 7 consolelogmy cookie code for removing cookie when session ends windowonbeforeunload function removecookieregnewsletter path domain newsletter btnclickfunctione epreventdefault ajax success functiontxt status xhr some code cookieregnewsletter true path expires 365 etc etc,"['javascript', 'jquery']" +1070435,does alamofire store the cookies automatically i am new to alamofire so i am sorry if this it is a noob question this framework store automatically the cookiesthis is because i have a simple request like thisalamofirerequestpost loginurl parameters fb id fbid fb access token fbtoken responsejson response in printresponserequest original url request printresponseresponse url response printresponsedata server data printresponseresult result of response serialization if let json responseresultvalue printloginurl json json this request response with a cookie session that i need to do other requests for security reason the strange thing is that like magic i already can do the other requests after this first post without read manually the cookie and store it i am sure the other requests need the cookie session because they fail on postman for example but not hereit is just a feature because i cannot find anything on that also on the official github page,['ios'] +1070472,is there a pure virtual function in the c standard library in this lecture the speaker mentions at the beginning that there are no pure virtual functions in the standard library or he is not aware of any i believe that alex stepanov was against this language feature but since the initial stl design have any pure virtuals creeped into the standard library fwiw and correct me if i am wrong the deleters in unique pointers ultimately use virtual thispatching in most implementations but these are not pure virtuals,['c++'] +1070486,error on artisan commands when updating composer dependencies i am developing a library for laravel which contains a service provider i have added this library to another projects composerjson filethe composerjson file for the main project contains the following scriptsscripts postrootpackageinstall php r copyenvexample env postcreateprojectcmd php artisan keygenerate postinstallcmd php artisan clearcompiled php artisan optimize preupdatecmd php artisan clearcompiled postupdatecmd php artisan optimize i can include the library dependency just fine except for one thing the preupdatecmd and postupdatecmd scripts throw an error and cause me a lot of headaches when running sudo composer update to update the dependencies i get the following error sudo composer update php artisan clearcompiledphp fatal error class mynamemyprojectmyawesomeserviceprovider not found in usersmedevmyprojectvendorlaravelframeworksrcilluminatefoundationproviderrepositoryphp on line 146 symfonycomponentdebugexceptionfatalerrorexception class mynamemyprojectmyawesomeserviceprovider not found script php artisan clearcompiled handling the preupdatecmd event returned with an error runtimeexception error output php fatal error class mynamemyprojectmyawesomeserviceprovider not found in usersmedevmyprojectvendorlaravelframeworksrcilluminatefoundationproviderrepositoryphp on line 146i have googled around quite a bit before asking this question and read through pretty much everything related that i could find apparently this is a known issue that has been thiscussed in multiple github issues within the laravel repository however i have yet to find a workaround even after having tried multiple onesit appears that the issue is that the artisan commands bootstrap laravel which leads to an error because the service provider is not available at this point or something like that moving the clearcompiled command to postupdatecmd causes the same error which surprises me a bit because i thought the service provider would be available at this pointthe only thing that works for me is to manually comment out the line that includes the service provider in configaphp before running composer update and then adding it again afterwards i have been doing this for a few hours and it is already bothering the heck out of me and i really cannot believe that this issue is arounddoes anyone know how to work around this error so that i do not get the error that my service provider is not found when updating the composer dependencies for my projectedithere is the composerjson file for the library name mynamemyproject type library authors name my name email require php 550 laravelframework 52 autoload classmap psr4 mynamemyproject src,['php'] +1070702,can i run multiple control but same method in c for exampletxtunittotalqtytext txtpricetext txtunitpricetext lbltotalvaluetext to something liketxtunittotalqty txtprice txtunitprice lbltotalvaluetext,['c#'] +1070753,typedef to surrounding type in c is there a way to build a typedef inside a type declaration to the declared surrounding type itself without stating the types nameexampleclass x public typedef fill in magic here mytype backgroundthis seems silly on the first look i need this because i build compiletimereflection of my data classes using macrosso there is a macro inserted into the declaration of the data class which needs to deal with the type it is inserted intoso far i found working solutions for msvc and g which both rely on what i think are flaws in the implementation so they may not work on a newer versionclang does not eat either of these solutionsmy current solution for msvc defines a method and then takes it is address only by it is name and calls a small helper that returns the type of it is class clang and g expect the full name of the method including it is class namemy current solution for g defines a static method with return type stdremove referencedecltypethis clang and msvc do not allow this in the static contexti would absolutely prefer a standard conform solution but a special solution for clang would also be ok for the momentif nothing works i have to pass the class name to the macro but i try to avoid this since i already have plenty of code using the macroedit adding a sample on how the reflection works which may clarify what i needclass x public y public constructor and such stuff int a double b stdstring c classheady fielda fieldb fieldc classfootclasshead is the macro that should define typedef it is a var args macro where the arguments receive the base classes as said it is possible to give it the class name as it is first argument resulting in classheadx y in the example but i nearly cannot imagine that there is no solution to such a simply task as typedefing the surrounding type,['c++'] +1070812,python histograms manually normalising counts and replotting as histogram i tried searching for something similar and the closest thing i could find was this which helped me to extract and manipulate the data but now i cannot figure out how to replot the histogram i have some array of voltages and i have first plotted a histogram of occurrences of those voltages i want to instead make a histogram of events per hour so the yaxis of a normal histogram divided by the number of hours i took data and then replot the histogram with the manipulated y datai have an array which contains the number of events per hour composed of the original y axis from pyplothist divided by the number of hours data was taken and the bins from the histogram i have composed that array using the following code taken from the answer linked above import numpyimport matplotlibpyplot as pyplotmydata numpyrandomnormal15 1 500 this seems to have to be uneven on either side of 0 otherwise the code looks fine fyi my actual data is all positivepyplotfigure1hist1 pyplothistmydata bins50 alpha05 labelset 1 colorredhist1 flux hist1050 05hist1hist1pyplotfigure2pyplotbarhist1 flux1 hist1 flux0this code does not exactly match whats going on in my code my data is composed of 10 arrays of 10 data points each voltages i have made histograms of that which gives me number of occurrences of a given voltage range or bin width all i want to do is replot a histogram of the number of events per hour so yaxis of the histogram 5 hours with the same original bin width but when i divide hist105 and replot in the above way the bin width is all wrongi feel like there must be an easier way to do this rather than manually replotting my own histogramsthanks in advance and i am really sorry if i have missed something obviousthe problem illustrated in the output of my sample code and my original data is as followsupper plots code snippet outputlower plots my actual data,['python'] +1070852,why does it wrap without endl i am a c beginner and i just wrote this simple programinclude iostreamusing namespace stdint readnumber cout insert a number int x cin x return xvoid writeanswerint x cout the sum is x endlint main int x readnumber int y readnumber int z x y writeanswerz return 0i do not understand why the output is like thisinsert a number 3insert a number 4the sum is 7and not likeinsert a number 3insert a number 4the sum is 7since in the readnumber function there is no endlwhat am i missingof course i am happy with the result i get but it is unexpected for me,['c++'] +1070888,how to deploy and serve prediction using tensorflow from api from google tutorial we know how to train a model in tensorflow but what is the best way to save a trained model then serve the prediction using a basic minimal python api in production servermy question is basically for tensorflow best practices to save the model and serve prediction on live server without compromising speed and memory issue since the api server will be running on the background for forevera small snippet of python code will be appreciated,['python'] +1070945,separating application level logging and framework level logging in aspnet core if i add logging services to container in aspnet 5 rc1servicesaddsingletoniloggerfactoryservicesaddsingletontypeofilogger typeofloggeror just servicesaddloggingthen i can use logger in my app layerclass myapplogicservice public myapplogicserviceiloggermyapplogicservice logger loggerloginformationhey but in this case my loggerloginformation events will mix with unimportant framework information events according to devs up to 10 per requestaspnet 5 documentation statesit is recommended that you perform application logging at the level of your application and its apis not at the level of the framework the framework already has logging built in which can be enabled simply by setting the appropriate logging verbosity levelwhat does this mean does it mean that using iloggeriloggerfactory in client code app logic is not recommendedwhat is an elegant solution to separate app level logging from framework level loggingfor now i am using serilog and filtering by contextsource but this is far from elegant,['c#'] +1070990,net asyncawait in this case should i return something in a case like this where my task could return instantly because of certain conditionspublic async task testlistint testlist if testlistcount 0 return do something await uploadlistasynctestlistis it correct return should i use taskfromresultfalse or is there a more correct way,['c#'] +1071073,motorola devices orgthreetenbpdatetimeexception when parsing a date in threeten i have a very weird behaviour on some motorola devices where localdatetimenow is returning 0t0 with threetenabpthe code is as followoverrideprotected void onresume superonresume if textutilsisemptytimeout localdatetime savedtime localdatetimeparsetimeout datetimeformatteriso date time if localdatetimenowisaftersavedtime refresh overrideprotected void onpause superonpause localdatetime currenttime localdatetimenowplusdurationofminutes10 timeout currenttimeformatdatetimeformatteriso date timeonly on these devices only 3 motorola devices running 60i have this crashfatal exception javalangruntimeexception unable to resume activity commyappcommyappmainactivity orgthreetenbpformatdatetimeparseexception text 0t08 could not be parsed invalid value for monthofyear valid values 1 12 0 at androidappactivitythreadperformresumeactivityactivitythreadjava3121 at androidappactivitythreadhandleresumeactivityactivitythreadjava3152 at androidappactivitythreadhhandlemessageactivitythreadjava1398 at androidoshandlerthispatchmessagehandlerjava102 at androidoslooperlooplooperjava148 at androidappactivitythreadmainactivitythreadjava5443 at javalangreflectmethodinvokemethodjava at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava728 at comandroidinternaloszygoteinitmainzygoteinitjava618caused by orgthreetenbpformatdatetimeparseexception text 0t08 could not be parsed invalid value for monthofyear valid values 1 12 0 at orgthreetenbpformatdatetimeformattercreateerrordatetimeformatterjava1559 at orgthreetenbpformatdatetimeformatterparsedatetimeformatterjava1496 at orgthreetenbplocaldatetimeparselocaldatetimejava4 at commyappmainactivityonresumemainactivityjava273 at androidappactivityperformresumeactivityjava6344 at androidappactivitythreadperformresumeactivityactivitythreadjava3110 at androidappactivitythreadhandleresumeactivityactivitythreadjava3152 at androidappactivitythreadhhandlemessageactivitythreadjava1398 at androidoshandlerthispatchmessagehandlerjava102 at androidoslooperlooplooperjava148 at androidappactivitythreadmainactivitythreadjava5443 at javalangreflectmethodinvokemethodjava at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava728 at comandroidinternaloszygoteinitmainzygoteinitjava618caused by orgthreetenbpdatetimeexception invalid value for monthofyear valid values 1 12 0 at orgthreetenbptemporalvaluerangecheckvalidvaluevaluerangejava278 at orgthreetenbptemporalchronofieldcheckvalidvaluechronofieldjava557 at orgthreetenbplocaldateoflocaldatejava237 at orgthreetenbpchronoisochronologyresolvedateisochronologyjava452 at orgthreetenbpformatdatetimebuildermergedatedatetimebuilderjava297 at orgthreetenbpformatdatetimebuilderresolvedatetimebuilderjava206 at orgthreetenbpformatdatetimeformatterparsedatetimeformatterjava1491 at orgthreetenbplocaldatetimeparselocaldatetimejava4 at commyappmainactivityonpostresumemainactivityjava273 at androidappactivityperformresumeactivityjava6344 at androidappactivitythreadperformresumeactivityactivitythreadjava3110 at androidappactivitythreadhandleresumeactivityactivitythreadjava3152 at androidappactivitythreadhhandlemessageactivitythreadjava1398 at androidoshandlerthispatchmessagehandlerjava102 at androidoslooperlooplooperjava148 at androidappactivitythreadmainactivitythreadjava5443 at javalangreflectmethodinvokemethodjava at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava728 at comandroidinternaloszygoteinitmainzygoteinitjava618line 273 islocaldatetime savedtime localdatetimeparsetimeout datetimeformatteriso date timeso basically localedatetimenow is returning an invalid date time and parsing it failsthe other interesting thing is that it only happened since beginning of january anyone has ever faced that problem,['android'] +1071189,floating action button animation issue i was playing around with the fab in the support design library when i ran inti this issuei replaced the oncreate method in the default blank activity template in android studio this is what it looks likeimport androidosbundleimport androidsupportdesignwidgetfloatingactionbuttonimport androidsupportv7appappcompatactivityimport androidsupportv7widgettoolbarimport androidviewviewimport androidviewanimationtranslateanimationpublic class mainactivity extends appcompatactivity override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main toolbar toolbar toolbar findviewbyidridtoolbar setsupportactionbartoolbar final floatingactionbutton fab floatingactionbutton findviewbyidridfab fabsetonclicklistenernew viewonclicklistener override public void onclickview view translateanimation anim new translateanimation0 500 0 500 animsetduration10 animsetfillenabledtrue animsetfillaftertrue fabstartanimationanim fabsetonlongclicklistenernew viewonlongclicklistener override public boolean onlongclickview view translateanimation anim new translateanimation0 500 0 500 animsetduration10 animsetfillenabledtrue animsetfillaftertrue fabstartanimationanim return true so basically i added an onclicklistener and an onlongclicklistener that translate the fab by 500idks but the problem is that it does not work like it is supposed towhen i click on it normally nothing happens which is weird to start with heres a video of it happeningwhen i longpress on it it animates like i should but only if i keep pressing and whenever i lift my finger it goes back to the original position regardless of whether the animation is complete or not even though i set setfillenabledtrue and setfillaftertrue here are videos of what happens when i lift my finger and when i leave my finger on the screen till the end and everythingwhy is this happening,['android'] +1071529,is it possible to flash a device rom to a avd emulator or genymotion i am working on some compatibility problem on android development my android apps crashed on a rare device rom which has modified some frameworkappwidget code to cause the crashi want to reproduce the crash by my self without the device i do not own the device and cannot easily get the right device except 2hand marketbut the rom i can download from the devices forumsystemimg userdataimg can i flash the rom to the avd or genymotion directly any guide to achieve this,['android'] +1071894,using javacv and realm together causes javalangunsatisfiedlinkerror i have recently been getting the following error by attempting to start an instance of javacvs ffmpegframegrabberjavalangunsatisfiedlinkerror orgbytedecojavacppavutil at javalangclassclassfornamenative method at javalangclassfornameclassjava324 at orgbytedecojavacpploaderloadloaderjava413 at orgbytedecojavacpploaderloadloaderjava381 at orgbytedecojavacppavformatavformatcontextclinitavformatjava2597 at orgbytedecojavacvffmpegframegrabberstartunsafeffmpegframegrabberjava386 at orgbytedecojavacvffmpegframegrabberstartffmpegframegrabberjava380while solutions to this problem exist none worked for me through many trials i have thiscovered that weirdly enough if i do not include realm in my project i no longer receive this errorhere is the part of my buildgradle file in which i include all of these librariescompile group orgbytedeco name javacv version 11compile group orgbytedecojavacpresets name opencv version 30011 classifier androidarmcompile group orgbytedecojavacpresets name opencv version 30011 classifier androidx86compile group orgbytedecojavacpresets name ffmpeg version 281 classifier androidarmcompile group orgbytedecojavacpresets name ffmpeg version 281 classifier androidx86 ormcompile iorealmrealmandroid0872 tested not ok causes javacv to crashi am thinking that there may be a solution to this problem that i am not aware of i found no mention anywhere on the internet about library incompatibility or why this behaviour may occuri will edit this post with any additional details that anyone might needany help would be greatly appreciatedediti attempted to apply the fix described herenow my packaging options look like this packagingoptions exclude metainflicensetxt exclude metainfnoticetxt exclude metainfmavenorgbytedecojavacpresetsffmpegpomproperties exclude metainfmavenorgbytedecojavacpresetsffmpegpomxml exclude metainfmavenorgbytedecojavacpresetsopencvpomproperties exclude metainfmavenorgbytedecojavacpresetsopencvpomxml exclude libarm64v8alibrealmjnisounfortunately this change has no effect i am still stuck,"['java', 'android']" +1071907,direct way to generate sum of all parallel diagonals in numpy pandas i have a rectangular cannot be assumed to be square pandas dataframe of numbers say i pick a diagonal direction either upperleft to lowerright or upperright to lowerleft i would like to compute a series whose entries are the sums of the values from the original dataframe along the chosen set of parallel diagonals to fully specify the goal you need to decide whether diagonals are anchored on the left or anchored on the right for the below i assume they are anchored on the lefti can do this without too much troubleimport numpy as npimport pandas as pdrectdf pddataframenparange15reshape53 result 0 1 20 0 1 21 3 4 52 6 7 83 9 10 114 12 13 14i can compute the upperleft to lowerright diagonal sums as followsullrsums pdconcatrectdfiloc ishifti for i in rangerectdfshape1 axis1 sumaxis1 fillna0 result0 121 212 303 224 12and i can compute the upperright to lowerleft diagonal sums by flipping the shifti to shifti in the previousurllsums pdconcatrectdfiloc ishifti for i in rangerectdfshape1 axis1 sumaxis1 fillna0 result0 01 42 123 214 30these results are all correct ie this code does what i want is there a more direct way to compute these sums in pandas or numpy,['python'] +1072187,rails 4 with pundit statesman gem policy when an object is in a state i am trying to make an app in rails 4i am trying to use statesman gem for states and then pundit for policiesmy gemfile has gem statesman 13 131gem punditi have an article model and an article transitions model and an article state machine modelmy objective is to define a publish policy using pundit in my articles policy which allows a user who owns an article to publish that article if it is in state approvedi am trying this in my pundit article policyclass articlepolicy applicationpolicydef publishuserpresent user articleuser if requires approval then approved and articlein stateapprove why doesnt this work see statesman docs user userarticleexistsarticleid endendwhen i try to check if the article is in state approve as commented out above i get an error message that says undefined method in state how can i use state machine in the policy or is it intended that the policy allows the user to publish at all times but you only show the button on the article show page when the article is in state approve although i thought that was the point of punditarticlerbclass article activerecordbase include statesmanadaptersactiverecordquerieshas many transitions class name articletransition autosave false def state machine state machine articlestatemachinenewself transition class articletransition association name transitions end delegate can transition to trans def reindex articles articlereindex async end private def selftransition name transitions end def selftransition class articletransition end def selfinitial state articletransitioninitial state draft endendarticle state machine modelclass articlestatemachine include statesmanmachine state draft initial true while author is drafting state review while approver comments are being addressed really still in draft state reject not suitable for publication state approve suitable for publication state publish published state remove destroyed state spotlight transition from draft to reject approve publish remove transition from review to rejected approved removed transition from reject to draft remove transition from approve to publish remove transition from publish to removeendarticle transition modelclass articletransition activerecordbase include statesmanadaptersactiverecordtransition belongs to article inverse of article transitionsendarticle controller def approve article articlefindparamsid if articlestate machinetransition toapprove flashnotice this article has been approved for publication redirect to action show id article id add mailer to send message to article owner that article has been approved else flasherror youre not able to approve this article redirect to action show id article id end enddef publish article articlefindparamsid authorize article if articlestate machinetransition topublish redirect to action show id article id how do you catch the date the state became published else flasherror youre not able to publish this article redirect to action show id article id end endcan anyone see what i have done wrongthe entire articles controller hasclass articlescontroller applicationcontroller before action set article only show edit update destroy reject approve publish remove before action authenticate user except index show search reject approve publish remove respond to html json get articles get articlesjson def index articles policy scopearticle query paramsquerypresence articles articlesearchquery end def index if paramsquerypresent books booksearchparamsquery page paramspage else books bookallpage paramspage end end get articles1 get articles1json def show end get articlesnew def new article articlenew articlecommentsbuild end get articles1edit def edit authorize article end post articles post articlesjson def create before action authenticate user authorize article article current userarticlesnewarticle params respond to do format if articlesave formathtml redirect toarticle formatjson render show status created location article else formathtml render new formatjson render json articleerrors status unprocessable entity end end end def search if paramssearchpresent articless articlesearchparamssearch else articles articlesall end end patchput articles1 patchput articles1json def update before action authenticate user authorize article respond to do format if articleupdatearticle params formatjson render show status ok location article else formathtml render edit formatjson render json articleerrors status unprocessable entity end end if articleupdatearticle params formathtml redirect toarticle formatjson render show status ok location article else formatjson render json articleerrors status unprocessable entity end formathtml render edit end end delete articles1 delete articles1json def destroy before action authenticate user authorize article articledestroy respond to do format formatjson head no content end end def review article articlefindparamsid if articlestate machinetransition toreview flashnotice comments on this article have been made for your review redirect to action show id article id else flasherror youre not able to review this article redirect to action show id article id end end def reject end def approve article articlefindparamsid if articlestate machinetransition toapprove flashnotice this article has been approved for publication redirect to action show id article id add mailer to send message to article owner that article has been approved else flasherror youre not able to approve this article redirect to action show id article id end end def publish article articlefindparamsid if articlestate machinetransition topublish redirect to action show id article id how do you catch the date the state became published else flasherror youre not able to publish this article redirect to action show id article id end end def remove article articlefindparamsid if articlestate machinetransition toremove redirect to root path else flasherror youre not able to destroy this article redirect to action show id article id end end private use callbacks to share common setup or constraints between actions def set article article articlefindparamsid authorize article end never trust parameters from the scary internet only allow the white list through def article params paramsrequirearticlepermitbody title image tag list comment attributes opinion endend,['ruby-on-rails'] +1072329,creating a countdown timer in rails that resets on the backend i am currently creating a rails quiz application with a timer that counts down the seconds left to answer the question in my first version i did this a simple way creating a variable for the timer an instance for seconds and then making it part of the quizs javascript like so quiz function thisquizcurrent 0 thisscore 0 thisseconds 10 thistiming thisseconds thiscontainer trivia thisparticipationid null quizprototypeinit function triviaonclick btnbtnprimaryquestions thischeckanswerbindthis divtimer strongtextthisseconds thisstart i would now like to move this to the backend using rails a previous question references the countdown gem but that seems to present two issues 1 i will need to repeatedly call the datetime and validate for each question which i do not think i can do with countdown and2 i ideally could then pass this value into the javascript as a variable in the documentation for that gem it shows how you can pass the countdown time into the view directly however i am using the countdown value in other words when it hits zero to force the user to the next question while recording a wrong answer like below as part of my validation quizprototypetimer function var that this thistiming divtimer strongtextthistiming if thistiming 0 selfstop getjsonapiskip question thisparticipationid function thatnextquestion any ideas on how i can check the time on the backend while still having the quiz check to make sure time has not run out,"['javascript', 'ruby-on-rails']" +1072343,128 as binary literal in java based on the fact that a byte type in java is a signed 8 bit twos complement integer why does not the second way of declaring a byte workbyte ok 128byte notok 0b10my understanding is that 10 should be 128 but java indicates the notok variable above should be an int and not a byte,['java'] +1072445,preprocessing in scikit learn single sample depreciation warning on a fresh installation of anaconda under ubuntu i am preprocessing my data in various ways prior to a classification task using scikitlearnfrom sklearn import preprocessingscaler preprocessingminmaxscalerfittraintrain scalertransformtrain test scalertransformtestthis all works fine but if i have a new sample temp below that i want to classify and thus i want to preprocess in the same way then i gettemp 12345567temp scalertransformtempthen i get a depreciation warningdeprecationwarning passing 1d arrays as data is deprecated in 017 and willraise valueerror in 019 reshape your data either using xreshape1 1 if your data has a single feature or xreshape1 1if it contains a single sample so the question is how should i be rescaling such a single samplei suppose an alternative not very good one would betemp temp temptemp scalertransformtemptemp temp0but i am sure there are better ways,['python'] +1072658,laravel phpunit test is failing going to an unexpected page only happens in the test so i have a page with a button on it with the value create when i click that create button without filling out any of the fields it validates the form and thisplays error messages on the same page when i do that in the browser it works fine but when i do it with phpunit it has unexpected results and i do not know why here is my integration test public function testcreatevalidation thisvisitroutepatientsindexescreate thispatientid thispresscreate thisseepageisroutepatientsindexescreate thispatientid and this is the result there was 1 failure1 testsintegrationindexcontrollertesttestcreatevalidationdid not land on expected page httplocalhostpatients69indexescreatefailed asserting that two strings are equal expected actual httplocalhostpatients69indexescreatehttplocalhostpatientsvagrantvendorlaravelframeworksrcilluminatefoundationtestinginteractswithpagesphp141vagranttestsintegrationindexcontrollertestphp51i do not understand why it is being redirected to the patients page here is the laravel create method that is being testedpublic function createid index thisindexesnewinstance patient thispatientsfindorfailid return viewpatientindexcreate index index patient patient and here is the relevant section of the create view formopenroute arraypatientsindexesstore patientid class formhorizontal includepatientindex form formsubmitcreate class btn btnprimary formclose and finally the store method that it is being sent topublic function storeindexrequest request id index thisindexesnewinstance indexfillrequestall indexpatient id id indexsave patient indexpatient return redirectroutepatientsedit patient i am also using a formrequest to validate the input public function rules return index title required index description required so essentially since it is failing the validation in the indexrequest the indexrequest should kick it back to the patientsindexescreate view and thisplay errors but for some reason it is being kicked to the patients page this only happens in the test if i try it out by manually clicking the create button in the browser it works as expectedi have had this issue before but have never been able to solve it any ideas,['php'] +1072679,how to connect my swift app to my parse server i am working on connecting my parse app to my nodejs parse server with the swift language in the documentation of parse i can see this code parse initializewithconfigurationparseclientconfiguration configurationwithblockidparsemutableclientconfiguration configuration configurationapplicationid your app id configurationclientkey your app client key configurationserver httplocalhost1337parse and since i use the swift language here is my configuration until now initialize parseparsesetapplicationidapp id clientkey client keybut how can i specify the server as in the objectivec code thanks,['objective-c'] +1072714,extremely bad performance in net native compiled uwp app i encounter very bad performance when i compile my uwp app with the net native toolchain enabledi profiled the running code native and it seems that methods relying on reflection unity ioc behaviorssdk linq sqlitenet are the culpriti use the defaultrdxml so fardirectives xmlns application assembly nameapplication dynamicrequired all applicationdirectivesi have no missingmetadataexceptions so far these only start as i expected when i remove the application lineis there something i am not seeing here the app has very good performance without net native does it help if i write the defaultrdxml from scratch working through all missingmetadataexceptions which will come,['.net'] +1072931,browserify fullcalendar with external jquery i am loading jquery from a cdn and this error occurs when i try to import fullcalendar into my scriptsuncaught error cannot find module jqueryhere is my scriptuse strictimport from jqueryimport fullcalendarcalendarfullcalendari am running this command to transform my scriptbrowserify indexjs t babelify x jquery indexminjsmy html looks like thisdoctype htmldiv idcalendardivscript srcscriptscript srcindexminjsscripti have also tried browserifyshim with depends jquery moment but it does not make any differencei suspect that it is because the fullcalendar js file has a umd wrapper that does its own requirejquery and requiremoment but i thought the external flag would be smart enough to detect thisany way i can work around this problemupdate this was a minimal example of what i am trying to achieve however my actual code involves many more dependencies than fullcalendar and all thirdparty dependencies are concatenated into a vendorminjs file separated from our code such as indexjs,"['javascript', 'jquery']" +1073033,background image on mobile not fitting the screen correctly i am having problem with my website bare with me the page is in french but fortunately the code is the same with all languages i am using a samsung galaxy s5 to view the page and there is a big black box on top you can view the original page here you can see on your desktop it is all goodnow that is what happens on my galaxy s5 sorry for the big image do not know how to size it down on stack overflowon any browser from a computer or iphoneipad it is okay but on my galaxy s5 the background image is shown at the bottom and there is a black bar on topnow the code i currently have that works okay on desktopipadiphones is body margin0 padding0 fontsize13px fontfamilyarial black gadget sansserif colorf backgroundimage url backgroundrepeat norepeat backgroundattachment fixed backgroundsize cover webkitbackgroundsize cover mozbackgroundsize cover obackgroundsize cover i am not sure what i am missing if a css guru can help me out i would appreciate a lotthank you,"['android', 'html', 'css']" +1073344,how to convert map to list in java 8 how to convert a mapstring double to listpairstring double in java 8i wrote this implementation but it is not efficientmapstring double implicitdatasum new concurrenthashmaplistpairstring double mostrelevanttitles new arraylistimplicitdatasumentrysetstream sortedcomparatorcomparinge egetvalue foreachorderede mostrelevanttitlesaddnew pairegetkey egetvaluereturn mostrelevanttitlesi know that it should works using collectcollectorssomemethod but i do not understand how to do that,['java'] +1073476,xcode 7 pluginloading required plugin compatibility uuid when i tried to build project from command line i got the following message from xcodebuidxcodebuild1071312093 mt pluginloading required plugin compatibility uuid f41bd31e268344b8ae7f5f09e919790e for plugin at path libraryapplication supportdevelopersharedxcodepluginssparkinspectorxcodepluginxcplugin not present in dvtplugincompatibilityuuidsi installed spark inspector a year ago and deleted it about 6 months agois there a way to reset xcode so that it does not know there is such a pluginso far i have tried reinstall xcode delete all the reference data they did not work,['ios'] +1073483,why ie11 does not wrap the text in flexbox consider the following snippetparent thisplay flex flexdirection column width 400px border 1px solid red alignitems centerchild border 1px solid bluediv classparent div classchild lorem ipsum is simply dummy text of the printing and typesetting industry div div classchild lorem ipsum is simply dummy text of the printing and typesetting industry divdivin chrome the text is wrapping as expectedbut in ie11 the text is not wrappingis this a known bug in ie if yes a pointer will be appreciatedis there a known workaroundthis similar question does not have a definite answer and an official pointer,['css'] +1073639,linux syscall libc vdso and implementation thissection i thissects the syscall call in the last libcgit clone gitsourcewareorggitglibcgitand i have this code in sysdepsunixsysvlinuxi386sysdeph define internal syscall main inlinename err nr args loadregs nrargs asm volatile call gsp2 a resultvar a nr name i offsetof tcbhead t sysinfo asmargs nrargs memory ccif i understand well this code the loadregs nrargs macro loads the argument in the registers ebx ecx edx esi edx and ebp sysdepsunixsysvlinuxi386sysdeph define loadregs 0 define asmargs 0 define loadregs 1arg1 loadregs 0 define asmargs 1arg1 asmargs 0 b unsigned int arg1 define loadregs 2arg1 arg2 loadregs 1 arg1 define asmargs 2arg1 arg2 asmargs 1 arg1 c unsigned int arg2 define loadregs 3arg1 arg2 arg3 loadregs 2 arg1 arg2 define asmargs 3arg1 arg2 arg3 asmargs 2 arg1 arg2 d unsigned int arg3 define loadregs 4arg1 arg2 arg3 arg4 loadregs 3 arg1 arg2 arg3 define asmargs 4arg1 arg2 arg3 arg4 asmargs 3 arg1 arg2 arg3 s unsigned int arg4 define loadregs 5arg1 arg2 arg3 arg4 arg5 loadregs 4 arg1 arg2 arg3 arg4 define asmargs 5arg1 arg2 arg3 arg4 arg5 asmargs 4 arg1 arg2 arg3 arg4 d unsigned int arg5 define loadregs 6arg1 arg2 arg3 arg4 arg5 arg6 register unsigned int a6 asm ebp unsigned int arg6 loadregs 5 arg1 arg2 arg3 arg4 arg5 define asmargs 6arg1 arg2 arg3 arg4 arg5 arg6 asmargs 5 arg1 arg2 arg3 arg4 arg5 r a6endif gcc 5 enter code herewhere is the code which load the argument in the registers ebx ecx edx esi edx and ebp it is this code above i do not understand the implementationthe following code load the 6th argument in the ebx registerregister unsigned int a6 asm ebp unsigned int arg6what does this codeasmargs 0 b unsigned int arg1it loads the first argument in the ebx registerthen the call gsp2 jump to the vdso code this code correspond to call gs0x10so this following diagram for the write syscall it is goodwrite1 a 1 libc vdso kernel load reg jump to vdso user land kernel landi does not understand the vdso utility the vdso choose the syscall method sysenter or int 0x80thanks you in advance for your help and sorry my inglish is very bad,['c'] +1073809,eventlisteners impact what impact does eventlisteres have im talking about big numbers heres an examplethere is only x amount of marker at firstall children are added via js when marker is clicked eventlistenereach child does it is own thing which means each of them have their own eventlisteners final html of single marker when it has been clicked div classmarker div classremovediv div classchangediv div classadiv div classdragdivdivvar count 20 0fori 0 i count i var marker documentcreateelementdiv markerclassname marker someparentelementappendchildmarker markerclick function create child elements var remove documentcreateelementdiv removeclassname remove markerappendchildremove var change documentcreateelementdiv changeclassname change markerappendchildchange var add documentcreateelementdiv addclassname add markerappendchildadd var drag documentcreateelementdiv dragclassname drag markerappendchilddrag children eventlisteners removeclick function do it is thing changeclick function do it is thing addclick function do it is thing dragclick function do it is thing please do not mind other things eg creating 20 0 elements programmatically my question is this what would be the impact of having all these eventlisteners with all this code in them does it even matter what or how much code is inside eventlistener as long as it has not been triggered,"['javascript', 'jquery']" +1073815,reuse of characters in compiled exe file once long ago out of curiosity i have tried hexediting the executable file of the game dangerous davei have looked around the file for any strings i could find and made some random edits to see if it would actually change the text thisplayed within the gamei was surprised to see the result which i have now recreated using a hexeditor and dosboxas can be seen editing the two characters ro in the string romero resulted in 4 characters being changed with the result becoming zumezu it seems as if the program is reusing the two characters and prints them at the start and end of that stringwhat is the cause of this my first guess would be trying to make the executable smaller but just the code that reuses the characters would probably require more space than those 2 bytes to be savedis it just a trick done by the author or just some compiler voodoo,['c'] +1073828,how to pass a list as an input of a function in python i am using python and i have a function which takes a list as the argument for example i am using the following syntaxdef squarexresult for y in x resultappendmathpowy20 return resultprintsquare123and the output is 1 only where i am supposed to get 149what am i doing wrong,['python'] +1073884,crop and print image documents without thistortion in c i am using winforms in my form i have a picturebox i use to thisplay image documents the problem is when i crop the image and then print the document out the image becomes slightly thistorted if i do not crop the image document and print it regularly the image document does not become thistorted how do i crop and print the image documents without them being thistortedor is there a better way to code this so it can crop and print without the image document being thistorted if so how can i do itnotesmy picturebox is set to zoom because the images i work with is bigexample of image document dimensions 2500 x 3100my picturebox does not have a borderint cropx cropy cropwidth cropheightpublic pen croppenprivate state currentstateprivate enum state cropprivate void open btn clickobject sender eventargs e open file dialog openfiledialog open new openfiledialog if openshowdialog dialogresultok thisplay image in picture box picturebox1image new bitmapopenfilename private void picturebox1 mouseupobject sender mouseeventargs e try if crop checkboxchecked true cursor cursorsdefault if currentstate statecrop if cropwidth 1 return rectangle rect new rectangle cropx cropy cropwidth cropheight first we define a rectangle with the help of already calculated points bitmap originalimage new bitmappicturebox1image picturebox1width picturebox1height original image bitmap img new bitmap cropwidth cropheight for cropinf image graphics g graphicsfromimageimg create graphics ginterpolationmode systemdrawingdrawing2dinterpolationmodehighqualitybicubic gpixeloffsetmode systemdrawingdrawing2dpixeloffsetmodehighquality gcompositingquality systemdrawingdrawing2dcompositingqualityhighquality set image attributes gdrawimageoriginalimage 0 0 rect graphicsunitpixel picturebox1image img picturebox1width imgwidth picturebox1height imgheight else cursor cursorsdefault catch exception private void picturebox1 mousemoveobject sender mouseeventargs e if crop checkboxchecked true if currentstate statecrop cursor cursorscross if ebutton systemwindowsformsmousebuttonsleft x and y are the coordinates of crop picturebox1refresh cropwidth ex cropx cropheight ey cropy picturebox1creategraphicsdrawrectangle croppen cropx cropy cropwidth cropheight else cursor cursorsdefault private void crop checkbox checkedchangedobject sender eventargs e if crop checkboxchecked true thiscursor cursorscross private void print btn clickobject sender eventargs e systemdrawingprintingprintdocument myprintdocument1 new systemdrawingprintingprintdocument printdialog myprindialog1 new printdialog myprintdocument1printpage new systemdrawingprintingprintpageeventhandlerprintdocument1 printpage myprindialog1document myprintdocument1 if myprindialog1showdialog dialogresultok myprintdocument1print private void printdocument1 printpageobject sender printpageeventargs e egraphicsdrawimagepicturebox1image 10 10 standard paper size is 850 x 1100 or 2550 x 3300 pixelsprivate void picturebox1 mousedownobject sender mouseeventargs e if crop checkboxchecked true if currentstate statecrop if ebutton systemwindowsformsmousebuttonsleft cursor cursorscross cropx ex cropy ey croppen new pencolorfromargb153 180 209 3 2 is thickness of line croppendashstyle dashstyledashdotdot picturebox1refresh else cursor cursorsdefault test slightly thistorted test not thistorted test the picture above is a test this is what happened when i took the below code out from picturebox1 mouseupbitmap originalimage new bitmappicturebox1image picturebox1width picturebox1heightand editedreplaced originalimage to picturebox1imagegdrawimagepicturebox1image 0 0 rect graphicsunitpixel,"['c#', '.net']" +1073919,stack allocation for c green threads i am doing some research in c green threads mostly boostcoroutine2 and similar posix functions like makecontextswapcontext and planning to implement a c green thread library on top of boostcoroutine2 both require the user code to allocate a stack for every new functioncoroutine my target platform is x64linux i want my green thread library to be suitable for general use so the stacks should expand as required a reasonable upper limit is fine eg 10mb it would be great if the stacks could shrink when too much memory is unused not required i have not figured out an appropriate algorithm to allocate stacksafter some googling i figured out a few options myselfuse split stack implemented by the compiler gcc fsplitstack but split stack has performance overhead go has already moved away from split stack due to performance reasonsallocate a large chunk of memory with mmap hope the kernel is smart enough to leave the physical memory unallocated and allocate only when the stacks are accessed in this case we are at the mercy of the kernelreserve a large memory space with mmapprot none and setup a sigsegv signal handler in the signal handler when the sigsegv is caused by stack access the accessed memory is inside the large memory space reserved allocate needed memory with mmapprot read prot write here is the problem for this approach mmap is not asynchronous safe cannot be called inside a signal handler it still can be implemented very tricky though create another thread during program startup for memory allocation and use pipe readwrite to send memory allocation information from the signal handler to the thread a few more questions about option 3i am not sure the performance overhead of this approach how wellbad the kernelcpu performs when the memory space is extremely fragmented due to thousands of mmap call is this approach correct if the unallocated memory is accessed in kernel space eg when read is called are there any other better options for stack allocation for green threads how are green thread stacks allocated in other implementations eg gojava,['c++'] +1073936,wherenear query does not seem to work properly in parse i am working on an android app related to geolocations i am using parse as backend i need to thisplay results based on users current location i am using this queryparsequeryparseobject query parsequerygetqueryrestaurants parsegeopoint slatlong new parsegeopointcurrentlat currentlong querywherenearrest location slatlong but the results are not sorted thistance wise can someone help me out,['android'] +1073947,what is in python as a beginner in python i am reading a book written by bill lubanovici found something weirdin that book after saving simple code in test1py which isprintthis standalone program worksit says python can run it by typing in python test1pyhowever whenever i try to use that syntax error happensalthough i know there are other methods like using exec which i found in this website i wanna know why book uses that method which does not work at least for me,['python'] +1073967,animating an svg on hover i am trying to animate an svg file on hover by default it animates great with svg functions like animatetransform attributetypexml attributenametransform typerotate from0 16 30 to360 16 30 dur3s repeatcountindefinitebut now i want to transform it only on hoverheres the pen,"['html', 'css']" +1074047,how to implement atoi using simd i would like to try writing an atoi implementation using simd instructions to be included in rapidjson a c json readerwriter library it currently has some sse2 and sse42 optimizations in other placesif it is a speed gain multiple atoi results can be done in parallel the strings are originally coming from a buffer of json data so a multiatoi function will have to do any required swizzlingthe algorithm i came up with is the followingi can initialize a vector of length and in the following fashion10n101i convert each character in the buffer to an integer and place them in another vectori take each number in the significant digits vector and multiply it by the matching number in the numbers vector and sum the results i am targeting x86 and x8664 architecturesi know that avx2 supports three operand fused multiplyadd so i will be able to perform sum number significant digit sumthat is where i got so faris my algorithm correct is there a better wayis there a reference implementation for atoi using any simd instructions set,['c++'] +1074094,f assembly references causing build issues we have an f assembly assemblyone that references another f assembly assemblytwo in a single visual studio 2012 solution assemblytwo has a reference to a c dll mycsharpliba function defined in assemblyone calls a function defined in assemblytwonamespace assemblyonerequirequalifiedaccessmodule mymodulea let fetchresult id let result assemblytwomymodulecfetchresult id resultthe function called in assemblytwo calls another function fetchactualresult in the same assembly that takes a parameter of type mycsharptype that belongs to the referenced c dll mycsharplibnamespace assemblytworequirequalifiedaccessmodule mymoduleb let fetchactualresultmycsharptypemycsharplibmycsharptype idint return a resultrequirequalifiedaccessmodule mymodulec let fetchresult id let mycsharptype new mycsharplibmycsharptype mymodulebfetchactualresultmycsharptype idthe solution compiles and builds in visual studio however when we try to build the project from the command line using msbuild the build fails with the following error in the msbuildlogerror fs0074 the type referenced through mycsharplib is defined in an assembly that is not referenced you must add a reference to assembly mycsharplibit appears the type exposed as a parameter from mycsharplib in the fetchactualresult function signature in assemblytwo is causing the errorassemblyone now needs a reference to mycsharplib even though assemblyone does not directly use anything from mycsharplibif we remove the parameter from the function signature the solution builds with no errorswe have further explored this problem by replicating the code with the following use cases indicates assembly referencef assemblyone f assemblytwo mycsharplib c dll does not buildf assemblyone f assemblytwo myfsharplib f dll does not buildf assemblyone f assemblytwo c assemblythree assembly in same solution does not buildf assemblyone f assemblytwo f assemblythree assembly in same solution buildscan this behaviour be explained,['c#'] +1074157,property not found on type when using interface default methods in jsp el consider the following interfacepublic interface i default string getproperty return and the implementing class which just reuses the default implementationpublic final class c implements i emptywhenever an instance of c is used in jsp el scripting contextjspusebean id c class comexamplec scope requestcproperty i receive a propertynotfoundexceptionjavaxelpropertynotfoundexception property property not found on type comexamplec javaxelbeanelresolverbeanpropertiesgetbeanelresolverjava268 javaxelbeanelresolverbeanpropertiesaccess300beanelresolverjava221 javaxelbeanelresolverpropertybeanelresolverjava355 javaxelbeanelresolvergetvaluebeanelresolverjava95 orgapachejaspereljasperelresolvergetvaluejasperelresolverjava110 orgapacheelparserastvaluegetvalueastvaluejava169 orgapacheelvalueexpressionimplgetvaluevalueexpressionimpljava184 orgapachejasperruntimepagecontextimplproprietaryevaluatepagecontextimpljava943 orgapachejspindex jsp jspserviceindex jspjava225 orgapachejasperruntimehttpjspbaseservicehttpjspbasejava70 javaxservlethttphttpservletservicehttpservletjava729 orgapachejasperservletjspservletwrapperservicejspservletwrapperjava438 orgapachejasperservletjspservletservicejspfilejspservletjava396 orgapachejasperservletjspservletservicejspservletjava340 javaxservlethttphttpservletservicehttpservletjava729 orgapachetomcatwebsocketserverwsfilterdofilterwsfilterjava52my initial idea tomcat 60 was too old for java 18 features but i was surprised to see tomcat 80 is also affected of course i can work the issue around by calling the default implementation explicitly override public string getproperty return isupergetproperty but why on earth a default method could be a problem for tomcatupdate further testing reveals default properties cannot be found while default methods can so another workaround tomcat 7 isjspusebean id c class comexamplec scope request cproperty cgetproperty,['java'] +1074268,newrelic async http handler and acquirerequeststate i have a problem with one async handler in thistributed aspnet web app first let me explain a use caseapplication uses iis 8 on win 2012 machine with net framework 452application has thisabled session and authentication modules via webconfig like this systemwebserver modules remove namewindowsauthentication remove namesession remove nameformsauthentication modules systemwebserverapplication uses custom async web handler to serve the specific requestapplication has very heavy traffic about 50k requests per minute per server async handler has about 10k requests per minute per server all tracked from newrelicapplication is thistributed via multiple w3wp processes 2 w3wp processes and multiple virtual servers about 10 serversapplication has high amount of connectionsall normal sync requests are working fine but async request that does a little more work that is why we use async request is often slow but newrelic reports that it is slow because of acquirerequeststate now i have looked on google and stack overflow and this event is connected to creating a session but we have sessions thisabled in webconfig does anyone know what else could acquirerequeststate could be doing are we missing some place to remove session state adding that from webconfig to machineconfig did nothinghere is a snippet from a request in newrelic slowest components count duration acquirerequeststate 1 12600 ms 100 wtf executerequesthandler 1 501 ms 0 integrated pipeline 1 0334 ms 0 updaterequestcache 1 03 ms 0 endrequest 1 0168 ms 0 authenticaterequest 1 0161 ms 0 total time 12600 ms 100edit i have sessionstate modeoff in webconfig systemweb section so that is not it,"['c#', 'asp.net']" +1074636,read a file in javascript without blocking io how can i read a file using filereader without it blocking io while reading the following is how i am doing it nowfunction readimagefileimagefile callback var reader new filereader readeronload functione callbacketargetresult readerreadasdataurlimagefilewhich works fine except that i need to process very large images 4k resolution which takes a considerable amount of time i cannot have user input blocked from using other features on the page while reading,['javascript'] +1074672,how to install cryptography on ubuntu my ubuntu is 1404 ltswhen i install cryptography the error isinstalling eggscriptsuses namespace packages but the thistribution does not require setuptoolsgetting thistribution for cryptography021no previouslyincluded directories found matching documentation buildzip safe flag not set analyzing archive contentssix module references path installed tmpeasy installouz7eicryptography021eggssix1100py27eggsearching for cffi08reading best match cffi 150downloading processing cffi150targzwriting tmpeasy installouz7eicryptography021tempeasy installyf2yl3cffi150setupcfgrunning cffi150setuppy q bthist egg thistdir tmpeasy installouz7eicryptography021tempeasy installyf2yl3cffi150eggthisttmpa2kjmdc cffi backendc1517 fatal error ffih no such file or directory include ffih compilation terminatederror setup script exited with error command x86 64linuxgnugcc failed with exit status 1an error occurred when trying to install cryptography 021 look above this message for any errors that were output by easy installwhile installing eggscripts getting thistribution for cryptography021error could not install cryptography 021i do not know why it was failed what is the reason is there something necessary when install it on ubuntu system,['python'] +1074788,angularstrap datepicker does not thisappear on blur of trigger event in the ios safari browser my datepicker can thisappear on blur of trigger event in the windows chrome windows safari mac safari android chrome except ios safari browsermy codeinput classtitlemenuleftinput formcontrol namebirthday datadateformatymmdd datadatetypestring dataautoclose1 ngmodeldatefrom placeholderdate datatriggerfocus bsdatepickeranyone can help me to find why it does not thisappear on blur of trigger event in ios safari browser thanks in advancethere are some background which maybe help you to know more about my question you can visit this page or plunker my code is the same as it i do not know why it can thisappear on blur of trigger event in the windows chrome windows safari mac safari android chrome except ios safari browser i wonder whether i do special process in ios safari anyone has come with this quesiton,['ios'] +1075121,http request status 0 with https the situationi am working on a ionic app that receive data from an apibefore the api was on http address and everything was working finethen we have moved the api to https and it is not working anymoreor well it is still working accessing it in the browser but not in the phone or emulatori am not sure what may be the problem in the console log i see that the status of the request is 0 it may be related with the whitelist with the headers or with cors i have tried several approaches but none workedwhitelistbefore in the configxml there was this whitelistallownavigation hrefhttp i have tried to modify it in several ways but that did not fix the problemfor example i have triedallownavigation hrefhttps andallownavigation href api requestthis is one example of api requesthttpget httpsmy domaincommobilelist mobile project headers contenttype applicationxwformurlencoded charsetutf8 successfunctiondata status headers config code errorfunctiondata status headers config consolelogerror with the api list mobile project consolelogdata consolelogstatus consolelogheaders consolelogconfig api responseand this is an example of api responsepublic function list mobile project headeraccesscontrolalloworigin headeraccesscontrolallowheaders origin xrequestedwith contenttype accept code echo json encode project list the questionhow to get the api working also on httpsif it is a cors related problem how can i enable it on server side,"['android', 'ios']" +1075209,select2 multiple prevents other input from submitting form on enter i have a form with a simple input and a select2 input like so pressing enter while the first input is focused should submit the form in this case redirect to a 404 pagefor some reason the multiple select2 input prevents the form submit if i remove the select2 class or the multiple attribute the form behaves normallytested on mac os x yosemite on safari chrome and firefox and it happens consistently on all browsersi am using jquery 213 and select2 401,"['javascript', 'jquery']" +1075428,javascript profiling mystery closure variables i was testing performance with chrome timeline on cases if variable defined inside a closure so it is values would not be exposed to useras expected run proto fn run few times faster and with minimal garbage collections and low memory heapbut run proto obj happened to make exact opposite as if it was costly having nonfunction values at object prototype property propertiescan someone share some clarity here some functionsomeprototypeexe functionvvar x alorem ipsum dolor sit amet consectetur adipisicing elit ea quae repudiandae eveniet cumque consequatur vitae aut nisi perspiciatis magnam explicabo optio reprehenderit dignissimos at porro quam neque dolorum architecto oditlorem ipsum dolor sit amet consectetur adipisicing elit ea quae repudiandae eveniet cumque consequatur vitae aut nisi perspiciatis magnam explicabo optio reprehenderit dignissimos at porro quam neque dolorum architecto oditlorem ipsum dolor sit amet consectetur adipisicing elit ea quae repudiandae eveniet cumque consequatur vitae aut nisi perspiciatis magnam explicabo optio reprehenderit dignissimos at porro quam neque dolorum architecto oditlorem ipsum dolor sit amet consectetur adipisicing elit ea quae repudiandae eveniet cumque consequatur vitae aut nisi perspiciatis magnam explicabo optio reprehenderit dignissimos at porro quam neque dolorum architecto oditlorem ipsum dolor sit amet consectetur adipisicing elit ea quae repudiandae eveniet cumque consequatur vitae aut nisi perspiciatis magnam explicabo optio reprehenderit dignissimos at porro quam neque dolorum architecto oditblorem ipsum dolor sit amet consectetur adipisicing elit ea quae repudiandae eveniet cumque consequatur vitae aut nisi perspiciatis magnam explicabo optio reprehenderit dignissimos at porro quam neque dolorum architecto oditlorem ipsum dolor sit amet consectetur adipisicing elit ea quae repudiandae eveniet cumque consequatur vitae aut nisi perspiciatis magnam explicabo optio reprehenderit dignissimos at porro quam neque dolorum architecto oditlorem ipsum dolor sit amet consectetur adipisicing elit ea quae repudiandae eveniet cumque consequatur vitae aut nisi perspiciatis magnam explicabo optio reprehenderit dignissimos at porro quam neque dolorum architecto oditlorem ipsum dolor sit amet consectetur adipisicing elit ea quae repudiandae eveniet cumque consequatur vitae aut nisi perspiciatis magnam explicabo optio reprehenderit dignissimos at porro quam neque dolorum architecto oditlorem ipsum dolor sit amet consectetur adipisicing elit ea quae repudiandae eveniet cumque consequatur vitae aut nisi perspiciatis magnam explicabo optio reprehenderit dignissimos at porro quam neque dolorum architecto oditclorem ipsum dolor sit amet consectetur adipisicing elit ea quae repudiandae eveniet cumque consequatur vitae aut nisi perspiciatis magnam explicabo optio reprehenderit dignissimos at porro quam neque dolorum architecto oditlorem ipsum dolor sit amet consectetur adipisicing elit ea quae repudiandae eveniet cumque consequatur vitae aut nisi perspiciatis magnam explicabo optio reprehenderit dignissimos at porro quam neque dolorum architecto oditlorem ipsum dolor sit amet consectetur adipisicing elit ea quae repudiandae eveniet cumque consequatur vitae aut nisi perspiciatis magnam explicabo optio reprehenderit dignissimos at porro quam neque dolorum architecto oditlorem ipsum dolor sit amet consectetur adipisicing elit ea quae repudiandae eveniet cumque consequatur vitae aut nisi perspiciatis magnam explicabo optio reprehenderit dignissimos at porro quam neque dolorum architecto oditlorem ipsum dolor sit amet consectetur adipisicing elit ea quae repudiandae eveniet cumque consequatur vitae aut nisi perspiciatis magnam explicabo optio reprehenderit dignissimos at porro quam neque dolorum architecto oditreturn xvsome2 functionsome2prototypeexe functionvreturn thisexesvsome2prototypeexes alorem ipsum dolor sit amet consectetur adipisicing elit ea quae repudiandae eveniet cumque consequatur vitae aut nisi perspiciatis magnam explicabo optio reprehenderit dignissimos at porro quam neque dolorum architecto oditlorem ipsum dolor sit amet consectetur adipisicing elit ea quae repudiandae eveniet cumque consequatur vitae aut nisi perspiciatis magnam explicabo optio reprehenderit dignissimos at porro quam neque dolorum architecto oditlorem ipsum dolor sit amet consectetur adipisicing elit ea quae repudiandae eveniet cumque consequatur vitae aut nisi perspiciatis magnam explicabo optio reprehenderit dignissimos at porro quam neque dolorum architecto oditlorem ipsum dolor sit amet consectetur adipisicing elit ea quae repudiandae eveniet cumque consequatur vitae aut nisi perspiciatis magnam explicabo optio reprehenderit dignissimos at porro quam neque dolorum architecto oditlorem ipsum dolor sit amet consectetur adipisicing elit ea quae repudiandae eveniet cumque consequatur vitae aut nisi perspiciatis magnam explicabo optio reprehenderit dignissimos at porro quam neque dolorum architecto oditblorem ipsum dolor sit amet consectetur adipisicing elit ea quae repudiandae eveniet cumque consequatur vitae aut nisi perspiciatis magnam explicabo optio reprehenderit dignissimos at porro quam neque dolorum architecto oditlorem ipsum dolor sit amet consectetur adipisicing elit ea quae repudiandae eveniet cumque consequatur vitae aut nisi perspiciatis magnam explicabo optio reprehenderit dignissimos at porro quam neque dolorum architecto oditlorem ipsum dolor sit amet consectetur adipisicing elit ea quae repudiandae eveniet cumque consequatur vitae aut nisi perspiciatis magnam explicabo optio reprehenderit dignissimos at porro quam neque dolorum architecto oditlorem ipsum dolor sit amet consectetur adipisicing elit ea quae repudiandae eveniet cumque consequatur vitae aut nisi perspiciatis magnam explicabo optio reprehenderit dignissimos at porro quam neque dolorum architecto oditlorem ipsum dolor sit amet consectetur adipisicing elit ea quae repudiandae eveniet cumque consequatur vitae aut nisi perspiciatis magnam explicabo optio reprehenderit dignissimos at porro quam neque dolorum architecto oditclorem ipsum dolor sit amet consectetur adipisicing elit ea quae repudiandae eveniet cumque consequatur vitae aut nisi perspiciatis magnam explicabo optio reprehenderit dignissimos at porro quam neque dolorum architecto oditlorem ipsum dolor sit amet consectetur adipisicing elit ea quae repudiandae eveniet cumque consequatur vitae aut nisi perspiciatis magnam explicabo optio reprehenderit dignissimos at porro quam neque dolorum architecto oditlorem ipsum dolor sit amet consectetur adipisicing elit ea quae repudiandae eveniet cumque consequatur vitae aut nisi perspiciatis magnam explicabo optio reprehenderit dignissimos at porro quam neque dolorum architecto oditlorem ipsum dolor sit amet consectetur adipisicing elit ea quae repudiandae eveniet cumque consequatur vitae aut nisi perspiciatis magnam explicabo optio reprehenderit dignissimos at porro quam neque dolorum architecto oditlorem ipsum dolor sit amet consectetur adipisicing elit ea quae repudiandae eveniet cumque consequatur vitae aut nisi perspiciatis magnam explicabo optio reprehenderit dignissimos at porro quam neque dolorum architecto oditsome fn functionsome fnprototypeexe functionvvar x a functionpthisp1 preturn this bfunctionpthisp2 p3return this cfunctionpthisp3 p99return this return xvcallthis42some fn2 functionsome fn2prototypeexe functionv return thisexesvcallthis42some fn2prototypeexes a functionpthisp1 preturn this bfunctionpthisp2 p3return this cfunctionpthisp3 p99return thisvar a1 a2 a fn1 a fn2 var run local obj functionfor var i 10 1 i 0 i x1 new somex1exeaa1pushx1var run proto obj functionfor var i 10 1 i 0 i x2 new some2x2exeaa2pushx2var run local fn functionfor var i 10 1 i 0 i x1 new some fnx1exeax1exebx1execa fn1pushx1var run proto fn functionfor var i 10 1 i 0 i x2 new some fn2x2exeax2exebx2execa fn2pushx2button onclickrun local objthislocal objbuttonbutton onclickrun proto objthisproto objbuttonbutton onclickrun local fnthislocal obj fnbuttonbutton onclickrun proto fnthisproto objbuttoni have heard a phraseclosure variable is defined each time that function runsbut still its foggy,['javascript'] +1075895,how to read parse input in c the faq i have problems with my c program when i try to read parse inputhelpthis is a faq entrystackoverflow has many questions related to reading input in c with answers usually focussed on the specific problem of that particular user without really painting the whole picturethis is an attempt to cover the subject comprehensively with special attention to common mistakes so most of those questions can be answered simply by marking them as duplicates of this onewhy does the last line print twicewhy does my scanfd scanfc failwhy does gets crashthe answer is marked as community wiki feel free to improve and cautiously extend,['c'] +1076433,javalangincompatibleclasschangeerror caused by activitytestrule instantiation i added an espresso test to my android project and got an incompatibleclasschangeerror on the line that is creating an activitytestrule how do i find out what caused ithere is the line of code that has caused the error homepagescreentestjava27rulepublic activitytestrulehomepageactivity homepageactivitytestrule new activitytestrulehomepageactivityclasshere is the errorjavalangincompatibleclasschangeerror comexamplerockleemehmvphomepagehomepageactivityat dalviksystemdexfiledefineclassnativenative methodat dalviksystemdexfiledefineclassdexfilejava226at dalviksystemdexfileloadclassbinarynamedexfilejava219at dalviksystemdexpathlistfindclassdexpathlistjava321at dalviksystembasedexclassloaderfindclassbasedexclassloaderjava54at javalangclassloaderloadclassclassloaderjava511at javalangclassloaderloadclassclassloaderjava469at comexamplerockleemehmvphomepagehomepagescreentestinithomepagescreentestjava27at javalangreflectconstructornewinstancenative methodat javalangreflectconstructornewinstanceconstructorjava288at orgjunitrunnersblockjunit4classrunnercreatetestblockjunit4classrunnerjava217at orgjunitrunnersblockjunit4classrunner1runreflectivecallblockjunit4classrunnerjava266at orgjunitinternalrunnersmodelreflectivecallablerunreflectivecallablejava12at orgjunitrunnersblockjunit4classrunnermethodblockblockjunit4classrunnerjava263at orgjunitrunnersblockjunit4classrunnerrunchildblockjunit4classrunnerjava78at orgjunitrunnersblockjunit4classrunnerrunchildblockjunit4classrunnerjava57at orgjunitrunnersparentrunner3runparentrunnerjava290at orgjunitrunnersparentrunner1scheduleparentrunnerjava71at orgjunitrunnersparentrunnerrunchildrenparentrunnerjava288at orgjunitrunnersparentrunneraccess0parentrunnerjava58at orgjunitrunnersparentrunner2evaluateparentrunnerjava268at orgjunitrunnersparentrunnerrunparentrunnerjava363at orgjunitrunnerssuiterunchildsuitejava128at orgjunitrunnerssuiterunchildsuitejava27at orgjunitrunnersparentrunner3runparentrunnerjava290at orgjunitrunnersparentrunner1scheduleparentrunnerjava71at orgjunitrunnersparentrunnerrunchildrenparentrunnerjava288at orgjunitrunnersparentrunneraccess0parentrunnerjava58at orgjunitrunnersparentrunner2evaluateparentrunnerjava268at orgjunitrunnersparentrunnerrunparentrunnerjava363at orgjunitrunnerjunitcorerunjunitcorejava137at orgjunitrunnerjunitcorerunjunitcorejava115at androidsupporttestinternalrunnertestexecutorexecutetestexecutorjava54at androidsupporttestrunnerandroidjunitrunneronstartandroidjunitrunnerjava240at androidappinstrumentationinstrumentationthreadruninstrumentationjava1853,['android'] +1076728,how to configure buildout to create sphinx documentation using binsphinxbuilder in my buildoutcfg file i have such codeparts sphinxbuildernext in same fileeggs jinja2 markupsafe sphinxand then at the end of filesphinxbuilderrecipe collectiverecipesphinxbuildersource buildoutdirectorydocssrcbuild buildoutdirectorydocsi dobinbuildoutwhich gives output in general okupdating sphinxbuildercollectiverecipesphinxbuilder writing makefilecollectiverecipesphinxbuilder writing batchfilecollectiverecipesphinxbuilder writing custom sphinxbuilder scriptin eggs folder i have sphinx eegafter buildout under project directory i have one new catalog docsthen i run commandbinsphinxquickstartand as root path for the documentation i set docsthen i edit docsconfpy and uncommentsyspathinsert0 ospathabspathi run command binsphinxbuilder and get errormakefile12 the sphinxbuild command was not found make sure you have sphinx installed then set the sphinxbuild environment variable to point to the full path of the sphinxbuild executablealternatively you can add the directory with the executable to your path if you do not have sphinx installed grab it from stopmain problems1 how to get sphinx working automaticly with buildout2 how to set right path to project modules apps in rst files 3 where to put confpy file,['python'] +1076738,listview manipulationcompleted event does not work on phone i have this code in a windows 10 uwp applicationmylistviewmanipulationmode manipulationmodestranslatexmylistviewmanipulationstarted s e x1 intepositionxmylistviewmanipulationcompleted s e x2 intepositionx if x1 x2 datacontrollerpaneopenfalse if x1 x2 datacontrollerpaneopentrue the manipulationcompleted event does not work on phone in listview the code inside the handler never gets calledit is working fine on pc but does not work on phone i do not understand why,['c#'] +1076852,change bootstrap radio on click i am sure what i am trying to do is quite simple however i require some helpi have three radio buttonsactiveinactivenot foundid like to change the bootstrap v3 class of the buttons when they are clicked they all have a default class of btndefault however when clicked i would like then to have the following classesactive btnsuccessinactive btnwarningnot found btndangeronly one should be selected at any one time and only one should be coloured at any one timemy code so far is below i think i am nearly there if somebody could offer some advice that would be greathere is a link to my jsfiddledocumentreadyfunction option1changefunction thisremoveclassbtndefaultaddclassbtnsuccess option2changefunction thisremoveclassbtndefaultaddclassbtnwarning option3changefunction thisremoveclassbtndefaultaddclassbtndanger script srcscriptscript srcscriptlink href relstylesheet div classbtngroup datatogglebuttons label classbtn btndefault input typeradio nameoptions idoption1 value1 autocompleteoffactive label label classbtn btndefault input typeradio nameoptions idoption2 value2 autocompleteoffinactive label label classbtn btndefault input typeradio nameoptions idoption3 value3 autocompleteoffnot found labeldiv,"['javascript', 'jquery', 'html', 'css']" +1076919,getting use of undeclared type noerror with reactivecocoa i am trying to learn reactivecocoa and have a hard time getting started i keep hitting minor bumps as api and tutorials seems to be outdated quickly maybe i have the wrong impressionjust trying to follow this i do not seem to have noerrorit should be imported correctly since i have access to signal rac textsignal etc but i do not know why noerror is not availabletheir documentation mentions noerror as well but that leads to a 404this transition to rac4 mentions noerror as well why is noerror undeclared i am using reactivecocoa 401edit i just added public enum noerror errortype to the top of the file and it works now i am not sure if this is a proper solution to the problem though it is not mentioned in guides and tutorials that i should extend errortype myself,['ios'] +1077257,getting error object does not support property or method assign i am using this jquery popup plugin from this link on my wordpress site it is working fine on all browsers but giving the following error on ie11any help is much appreciated,['jquery'] +1077354,using plugins with cordova cli i am using cordova cli v600 to make an app for android and i cannot load the plugins cordovapluginfile and cordovaplugindialogs i know it because the next alerts are shownif navigatornotification alertplugin notification not working properlyif windowrequestfilesystem alertplugin file not working properlyplugins are used after clicking a button not before ondeviceready eventplugins have been installed withcordovapluginfile v120 cordova plugin add cordovapluginfile cordovaplugindialogs v410 cordova plugin add cordovaplugindialogsi have also added the next line in configxmlpreference nameandroidpersistentfilelocation valuecompatibility what i am doing wrong,['android'] +1077698,mkmapview fails to load tiles with http 410 error i have a problem with mkmapview map fails to load tiles when i zoom it invoidmapviewdidfailloadingmapmkmapview mapview witherrornserror error errordomaingeoerrordomain code204 null userinfosimpletilerequesterunderlyingerrors error domaingeoerrordomain code204 null userinfohttpstatus410 nserrorfailingurlstringkeystyle20size2scale0v11037825z15x6205y12336sid0246704635757302674107153038443966765357accesskey1454685602 q3bvuyvhbdxsso0a j0fk7eyq9b21npshv7grlzr4wfkkhxb4vo72blxcgsxj4zzhvhtalvwsypa3plu60cdrmrfwmwcybgrla9mchv2fhorhotu9agi72vqp9ukzw2b0gkqfrhpcw4xr2f2fttvgjz7wu4u4kna8k2rvvq2foffhjq7oo4nyectvy0ur4i9d3sxf2btn9dcxu8agdrjignb editseems like it is related to cache somehow but i am not sure this problem thisappears for some time after loading the same map region in maps applicationthanks in advance,['ios'] +1077859,send image data to android app from app engine in my app engine backend i have a method that gets an image from google cloud storageapimethod name getprofileimage path image httpmethod apimethodhttpmethodgetpublic image getprofileimagenamedimagenamestring imagename try httptransport httptransport googlenethttptransportnewtrustedtransport googlecredential credential googlecredentialgetapplicationdefault storagebuilder storagebuilder new storagebuilderhttptransportnew jacksonfactorycredential storage storage storagebuilderbuild storageobjectsget getobject storageobjectsgetmybucket imagename bytearrayoutputstream out new bytearrayoutputstream if youre not in appengine download the whole thing in one request if possible getobjectgetmediahttpdownloadersetdirectdownloadenabledfalse getobjectexecutemediaanddownloadtoout byte oldimagedata outtobytearray outclose imagesservice imagesservice imagesservicefactorygetimagesservice return imagesservicefactorymakeimageoldimagedata catchexception e loggerinfoerror getting image named imagename return nullthe issue i am having is how do i get the image data when i call that in my android appsince you cant return primitives from app engine i converted it to an image so that i could call getimagedata in my app to get the bytehowever the image object returned to the app is not the same as the one in app engine so there is no getimagedatahow can i get the image data to my android appif i create an object that had a byte variable in it then i set the byte variable with the string data and return that object from the method will that workupdatethe image gets sent from the android app this code may or may not be correct i have not debugged it yetworkerthread public string startresumablesession try file file new filemfilepath long filesize filelength file null string surl namemimgname url url new urlsurl httpurlconnection urlconnection httpurlconnectionurlopenconnection urlconnectionsetrequestpropertyauthorization urlconnectionsetrequestpropertyxuploadcontenttypeimagepng urlconnectionsetrequestpropertyxuploadcontentlengthstringvalueoffilesize urlconnectionsetrequestmethodpost ifurlconnectiongetresponsecode httpurlconnectionhttp ok return urlconnectiongetheaderfieldlocation catchexception e eprintstacktrace return null private long sendnextchunkstring surlfile filelong skip int bytesread bytesavailable buffersize byte buffer int maxbuffersize 524287 long totalbytessent 0 try long filesize filelength fileinputstream fileinputstream new fileinputstreamfile skip fileinputstreamskipskip bytesavailable fileinputstreamavailable buffersize mathminbytesavailable maxbuffersize totalbytessent skip buffersize buffer new bytebuffersize bytesread fileinputstreamreadbuffer 0 buffersize try while bytesread 0 try url url new urlsurl httpurlconnection urlconnection httpurlconnectionurlopenconnection urlconnectionsetdoinputtrue urlconnectionsetdooutputtrue urlconnectionsetusecachesfalse urlconnectionsetchunkedstreamingmode524287 urlconnectionsetrequestmethodpost urlconnectionsetrequestpropertyconnection keepalive urlconnectionsetrequestpropertycontenttypeimagepng urlconnectionsetrequestpropertycontentlengthstringvalueofbytesread urlconnectionsetrequestpropertycontentrange bytes stringvalueofskipstringvalueoftotalbytessentstringvalueoffilesize dataoutputstream outputstream new dataoutputstreamurlconnectiongetoutputstream outputstreamwritebuffer 0 buffersize int code urlconnectiongetresponsecode ifcode 308 string range urlconnectiongetheaderfieldrange return integerparseintrangesplit1 else ifcode httpurlconnectionhttp created return 1 outputstreamflush outputstreamclose outputstream null catch outofmemoryerror e eprintstacktrace response outofmemoryerror return response return 1 fileinputstreamclose catch exception e eprintstacktrace response error return response return 1 catchexception e eprintstacktrace return 1 edit 2apparently its not clear to people that i am using endpoints in my android app,['android'] +1077890,celery how to limit number of tasks in queue and stop feeding when full i am very new to celery and here is the question i havesuppose i have a script that is constantly supposed to fetch new data from db and send it to workers using celerytaskspy celery taskfrom celery import celeryapp celerytasks brokeramqpguestlocalhostapptaskdef process datax do something with x passfetch dbpy fetch new data from db and thispatch to workersfrom tasks import process datawhile true run db query here to fetch new data from db fetched data process datadelayfetched data sleep30here is my concern the data is being fetched every 30 seconds process data function could take much longer and depending on the amount of workers especially if too few the queue might get throttled as i understand i cannot increase number of workersi can modify the code to refrain from feeding the queue when it is fullthe question is how do i set queue size and how do i know it is full in general how to deal with this situation,['python'] +1078033,enzyme throws an error if the react component requires jquery i am trying to test a react components behavior using enzymes describewithdom and mountbut when the component imports jquery i get this errorerror jquery requires a window with a documenti know enzyme uses jsdom under the hood and i always thought jsdom took care of the window and document but i cannot seem to find how to get these working togetherthe test code looks like thisimport chai expect from chaiimport select from selectimport react createelement from reactimport describewithdom mount from enzymedescribeui select more shallow tests here describewithdomuser actions ittoggles the uioptions menu on button click const wrapper mountselect baseprops expectwrapperstateopentonotbeok wrapperfindbuttonsimulateclick expectwrapperstateopentobeok in the buttons onclick method a jquery function is called inputselectorfocushow can i let enzyme and jsdom use jquery in the tests,"['javascript', 'jquery']" +1078103,random but most likely 1 float i want to randomize a float that so that there is 95 chance to be about 1there is 001 chance to be 01 or 19it never becomes 0 or 2is this possible by using randomnextfloat several times for examplea visual illustration of the probability,['java'] +1078130,how can i share text in whats app on particular number using this code only open particulat numbers chat but text is not sharehow can i do thispublic class mainactivity extends appcompatactivity button wastring id 9190edittext txtoverrideprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main txt edittextfindviewbyidridedittext wa buttonfindviewbyidridbtn whatsapp wasetonclicklistenernew viewonclicklistener override public void onclickview v uri uri uriparsesmsto id intent waintent new intentintentaction sendtouri string text testing message waintentsetpackagecomwhatsapp if waintent null waintentputextraintentextra text text startactivityintentcreatechooserwaintent text else toastmaketextgetapplicationcontext whatsapp not found toastlength short show,['android'] +1078389,raising exception in a generator handle it elsewhere and vice versa in python i am thinking in a direction more advanced as well as difficult to find solutions this problem before coming to any decision i thought of asking expert advice to address this problem the enhanced generators have new methods send and throw that allow the caller to pass messages or to raise exceptions into the generator coroutinefrom python documentation this can be very handy especially the throw method that requests the generator to handle exceptions raised in the caller request 1 any example code for the above statement i did not find any code snippets for this explanationhowever i am considering the inverse problem as well can a generator raise an exception pass it to the caller let the caller repair it and continue the generators own execution that is what i would like to call a reverse throwrequest 2 any example code for the above statement i did not find any code snippets for this explanationsimply raising exceptions in the generator is not ok i tried raise someexception in the generator and that did not work because after a raise the generator can no longer be executed it simply stops and further attempts to run the generator cause the stopiteration exception in other words raise is much more deadly than yield one can resume itself after yielding to the caller but a raise sends itself to the dead endi wonder if there are simple ways to do the reverse throw in python that will enable us to write coroutines that cooperate by throwing exceptions at each other but why use exceptions well i dunno it all began as some rough ideacase study codeclass myexceptionexceptionpassdef handleerrorfunc handle an error errors def wrapperarg1 result funcarg1 for err in finderrorresult errorsappenderr print errors return result return wrapperdef finderrorresultfind an error if any print result for k v in resultiteritems error nr v 2 if error nr 0 pass elif error nr 0 yield myexceptionhandleerrordef numgeninput this function take the input and generates 10 random numbers 10 random numbers are saved in result dictionary with indices find error decorator is called based on the result dictionary from random import randint result errors for i in range9 j randint04 resulti input j return resultif name main numgen4could anyone explain please both the ideas based on case study exampleraising exception in a generator and handle it elsewhere vice versa i do expect pros and cons of both methodsthanks in advancelooking for an answer drawing from credible andor official sources,['python'] +1078489,add some basic markers to a map in mapbox via mapbox gl js i have a map styled with mapbox studio however i am having difficulty adding even a basic marker to it however text is appearing where the marker should be which suggests that the marker would be thereso heres the code with that map stylemapboxglaccesstoken pkeyj1ijoic21py2tpzsisimeioijjawtim2jkdw0wmdjudnrsety0nwdrbjfnin0wxgyl18bjjwuiniur3msavar map new mapboxglmap container map style mapboxstylessmickiecikb3fhvi0063cekqns0pk1f1 center 3050 40 zoom 2 interactive falseand here some markers being added from an example in the apimaponstyleload function mapaddsourcemarkers type geojson data type featurecollection features type feature geometry type point coordinates 7703238901390978 38913188059745586 properties title mapbox dc markersymbol monument type feature geometry type point coordinates 122414 376 properties title mapbox sf markercolor ff00ff mapaddlayer id markers type symbol source markers layout iconimage markersymbol15 textfield title textfont open sans semibold arial unicode ms bold textoffset 0 06 textanchor top however only the text and not the icons appearquestion is how would i add just a normal basic colored marker to this map not even one of the special icon onesthanks,['javascript'] +1078497,why does n create a new line even when told not to i am having a problem with n creating a line even when it is told not to when copying the fix is probably something simple that i am just not seeing for some reason i would appreciate any input or coaching on this problem please only give me javascript answers as i am not interested in jquery or other methods script typetextjavascript if pulldownresponsee else var pulldownvaluese documentgetelementbyidtaskone var pulldownresponsee pulldownvalueseoptionspulldownvalueseselectedindexvalue stufftocopy stufftocopy n pulldownresponsee if pulldownresponsef else var pulldownvaluesf documentgetelementbyidtasktwo var pulldownresponsef pulldownvaluesfoptionspulldownvaluesfselectedindexvalue stufftocopy stufftocopy n pulldownresponsef scriptas you can see pulldownresponsef and pulldownreponsee should do nothing if my dropdown value equals and this portion works for the most part it does not execute any of the else code except for the new line n partcan anyone explain what is going wrong hereedit having more code might help here i will only include the essential portions since it is so long script typetextjavascript function copynotestemplate var stufftocopy documentgetelementbyidmyformvalue ifstufftocopylength 1 var stufftocopy pt meets criteria n documentgetelementbyidmyformvalue ifdocumentgetelementbyidnoptcriteriachecked var stufftocopy documentgetelementbyidnoptcriteriavalue if pulldownresponsee else var pulldownvaluese documentgetelementbyidtaskone var pulldownresponsee pulldownvalueseoptionspulldownvalueseselectedindexvalue stufftocopy stufftocopy n pulldownresponsee if pulldownresponsef else var pulldownvaluesf documentgetelementbyidtasktwo var pulldownresponsef pulldownvaluesfoptionspulldownvaluesfselectedindexvalue stufftocopy stufftocopy n pulldownresponsef if pulldownresponseg else var pulldownvaluesg documentgetelementbyidtaskthree var pulldownresponseg pulldownvaluesgoptionspulldownvaluesgselectedindexvalue stufftocopy stufftocopy n pulldownresponseg var tempvalues documentgetelementbyidwhatupdatevalue iftempvalueslength 1 var stufftocopy stufftocopy updated documentgetelementbyidwhatupdatevalue else var tempvaluess documentgetelementbyidwhatinfovalue iftempvaluesslength 1 var stufftocopy stufftocopy per documentgetelementbyidwhatinfovalue n else var tempvalue documentgetelementbyidwhatdscrpvalue iftempvaluelength 1 var stufftocopy stufftocopy documentgetelementbyidwhatdscrpvalue dscrp on collection tube and trf was resolved using else var tempvalue documentgetelementbyidresolveitvalue iftempvaluelength 1 var stufftocopy stufftocopy documentgetelementbyidresolveitvalue else var tempvalue documentgetelementbyidtubecorrectvalue iftempvaluelength 1 var stufftocopy stufftocopy trf was documentgetelementbyidtubecorrectvalue else ifstufftocopylength 1 var stufftocopy stufftocopy n documentgetelementbyidmorenotesvalue else if pulldownresponsesu else var pulldownvaluesu documentgetelementbyidmod33apply var pulldownresponsesu pulldownvaluesuoptionspulldownvaluesuselectedindexvalue stufftocopy stufftocopy n pulldownresponsesu if pulldownresponsesb else var pulldownvaluesb documentgetelementbyidresulticr var pulldownresponsesb pulldownvaluesboptionspulldownvaluesbselectedindexvalue stufftocopy stufftocopy n pulldownresponsesb if pulldownresponsesc else var pulldownvaluesc documentgetelementbyidmoneyncis var pulldownresponsesc pulldownvaluescoptionspulldownvaluescselectedindexvalue stufftocopy stufftocopy pulldownresponsesc if pulldownresponsesd else var pulldownvaluesd documentgetelementbyidresultmmt var pulldownresponsesd pulldownvaluesdoptionspulldownvaluesdselectedindexvalue stufftocopy stufftocopy pulldownresponsesd ifstufftocopylength 1 var stufftocopy stufftocopy reason documentgetelementbyidwhynoteligiblevalue else if pulldownresponsesa else var pulldownvaluesa documentgetelementbyidtestreleased var pulldownresponsesa pulldownvaluesaoptionspulldownvaluesaselectedindexvalue stufftocopy stufftocopy n pulldownresponsesa windowclipboarddatasetdatatext stufftocopy scriptif somebody skips filling out a note field or skips a dropdown in this example then it will not execute the code like i intended but it does create a new line when copied like thistaskone selectedextra line here since task two was not selectedtaskthree selectedi would like there not to be an extra line between task one and three if task two is skipped like thistaskone selectedtaskthree selectednote i know that having else is pointless but it helps me visuallyi created snips of exactly what it looks like when copypasted from my tool that you can view here if you would likeexample 1 example 2 here is an example of my html as wellhtml langen what tasks are needed for the case br select clastyle3 idtaskone option valueoption option valueabn neededabn neededoption option valueauth neededauth neededoption select html,['javascript'] +1078541,using scikit to determine contributions of each feature to a specific class prediction i am using a scikit extra trees classifiermodel extratreesclassifiern estimators10 and jobs1 random state0once the model is fitted and used to predict classes i would like to find out the contributions of each feature to a specific class prediction how do i do that in scikit learn is it possible with extra trees classifier or do i need to use some other model,['python'] +1078569,correct way to import lodash i had a pull request feedback below just wondering which way is the correct way to import lodashyoud better do import has from lodashhas for the earlier version of lodash v3 which by itself is pretty heavy we should only import a specidic modulefunction rather than importing the whole lodash library not sure about the newer version v4import has from lodashhasvsimport has from lodashthanks,['javascript'] +1078602,c safely taking absolute value of integer consider following program c99include stdiohinclude stdlibhinclude inttypeshint mainvoid printfenter int in range jd jdn intmax min intmax max intmax t i if scanfjd i 1 printfresult jd jdn i imaxabsinow as i understand it this contains easily triggerable undefined behaviour like thisenter int in range 9223372036854775808 9223372036854775807 9223372036854775808result 9223372036854775808 9223372036854775808questionsis this really undefined behaviour as in code is allowed to trigger any code path which any code that stroke compilers fancy when user enters the bad number or is it some other flavor of notcompletelydefinedhow would a pedantic programmer go about guarding against this without making any assumptions not guaranteed by standardthere are a few related questions but i did not find one which answers question 2 above so if you suggest duplicate please make sure it answers that,['c'] +1078683,c99 what is the recomended way to handle exceptions raised by pow overflow or complex number executingdouble result powbase exponentwith arbitrary base and exponentmay result in an attempt to compute a value too big or complexfor example with base2 exponent5 square root of 2should i just check if resultnan or resulthuge val would that code be c99 compliant and cross platform,['c'] +1079396,suggestion for uitextview is under floating header for uitableview i have floating headers for my uitableview which i want but it looks quite bad when the suggestion view for the uitextview in the cell above is under the headerseems like no one has had this problem before any suggestions both the header cell and uitableviewcell is loaded from xibthe floating header have an alpha on its second topmost view so it is a bit see throughthis is how it looks in debug view hierarchy,['ios'] +1079420,how to change the value of check box when it is checked or unchecked hello guys here the problem i want to perform a different calculation based on the check box div cod input typecheckbox idtrigger namequestion divhere is the javascript for calculating the price of the itemthe problem is that i dont know how can i do the else if methodscript pricequantshipmentkeyupfunction ifmyfunction3 demoval0 else iftriggerchecked this is the problem demovalpriceval quantval else demovalpriceval quantval myfunction3 scriptadvance thank you guys,"['javascript', 'jquery', 'html']" +1079641,how do i combine these two queries to calculate rank change introductioni have a highscore table for my game which uses ranks the scores table represents current highscores and player info and the recent table represents all recently posted scores by a user which may or may not have been a new top score the rank drop is calculated by calculating the players current rank minus their rank they had at the time of reaching their latest top score the rank increase is calculated by calculating the players rank they had at the time of reaching their latest top score minus the rank they had at the time of reaching their previous top scorefinally as written in code change drop 0 drop increasequestioni am using the following two queries combined with a bit of php code to calculate rank change it works perfectly fine but is sometimes a bit slowwould there be a way to optimize or combine the two queries php codei created an sql fiddle of the first query 9308481the tables are filled with content already so their structures should not be alteredthis is the current working codeq select select coalesce select countthistinct busername from recent b where bistopscore 1 and bscore ascore and btime atime or bscore ascore and busername ausername and btime atime 0 1 rank from scores a where anickname as rank ttime tusername tscore from scores t where tnickname r time 0 if stmt mysqliprepare q stmtbind param ss nick nick stmtexecute stmtstore result stmtbind result r rank r time r username r score stmtfetch if intvalr rank 9 r rank 9 stmtclose previous rank r prevrank 1 if r rank 1 q select coalesce select countthistinct busername from recent b where bistopscore 1 and bscore ascore and btime atime or bscore ascore and busername ausername and btime atime 0 1 rank from recent a where ausername and atime and ascore order by score desc limit 1 if stmt mysqliprepare q time minus one r time 1 stmtbind param sii r username time minus one r score stmtexecute stmtstore result stmtbind result r prevrank stmtfetch if intvalr prevrank 9 r prevrank 9 stmtclose drop current rank r rank drop drop 0 drop 0 increase r prevrank r rank increase increase 0 increase 0 change increase drop change drop 0 drop increase return change,"['php', 'mysql', 'sql']" +1079660,use instanceof without knowing the type my java classes represent entities inside a database and i find it practical to override the equals method of my classes to make comparisons by id so for example in my transaction class i have this piece of codeoverridepublic boolean equalsobject other if other null return false if other this return true if other instanceof transactionreturn false transaction othertrans transaction other if id null othertransid null return false return idequalsothertransidnow it seems a bit ugly to me that every class holds the same piece of code with only the name of the class changed i thought about making my classes extend a superclass myentity where i would write the above method replacing instanceof transaction with something like instanceof thisgetclass but this does not seem to be possible i also thought about replacing it with instanceof myentity but that means two object could be considered equal even if they belonged to different classes as long as they have the same idis there any other way,['java'] +1079878,loopback connect multiple database i am using loopback framework with nodejsis it possible to connect multiple database at a timefor example i have two different database1 mysql database a2 postgresql bsome pages get data from a database and some pages need get data from b database could it be possible to do thatmore detailslets say we have two modulesone module interacted with mysql and another module interacted with postgresql,['mysql'] +1079946,google maps javascript api referernotallowedmaperror were trying to develop an geoplacement app for one of our clients and we want first to test it in out own domainwe have signed for google maps javascript api and we have a valid browser key and our domain wgrupocamaleoncom has been authorized to use that keybut we cannot make even the easiest example to run without errorwe have in our domain and with our key the following demo1 but it does not work and firebug console saysgoogle maps api error google maps api error referernotallowedmaperror link to google documentation on referernotallowedmaperror your site url to be authorized 1my credential page is missing the possibility of adding referrers to accept so solutions involving adding referrers are not possible right nowmy credential pagewhy do we get that error how can we fix it tia,['javascript'] +1079969,what are good ways existing to transmit data to multiple mobile phones without internet backgroundi have an idea for an app on vacation that needs to communicate to other phones with the same app while on vacation those phones might not all have internet as roaming can be very expensive the data is not a lot like 500 kb max would suffice in jsonevery phone has a bit of info that all the other phones would like to know but if it helps the info can be stored on 1 phone master phone from now on and shared later to the other phones when back home over internetphonesandroid iphone and windows phonewe cannot assume they have nfc ir or zigbee just the hardware almost every phone has like bluetooth camera microphone etcmy ideasqr codes that changes based on new info if the first phone is scanned the second phones qr code has data from the 1st phone and itself and the 3rd phone has data from the 1st 2nd and 3rd itself until it reaches that master phone that holds all datadata transmission trough sound that we cannot hear or we can con is that i do not know if something like this exists for mobile platforms and writing it is like a 3 year master thesis projectbluetooth can we connect like 8 devices would it work consistent connecting even my headphones can be a hassle what about 8 phones who try to connect simultaneouslyall of these ideas have big cons maybe i am overlooking a better way i will add a bounty to the question for the best solutionan answer that explains it with a little bit of code reference link is ok is always better than just use bluetooth man,"['android', 'ios']" +1080147,checking if a type is a map i sometimes find the need to write general routines that can be applied to a container of objects or a map of such containers ie process each container in the map one approach is to write separate routines for map types but i think it can be more natural and less verbose to have one routine that works for both types of inputtemplate typename tauto fooconst t items return fooitems tag thispatch to map or nonmap what is a safe clean way to do this tag thispatch,['c++'] +1080208,setting the environment for systemin i am designing a console application for a server running redhat the end users should be able to run this app with any terminal of their choosing for example gnome terminal putty ssh telnet ms telnet client and othersin most terminal applications there is nothing wrong however when i launch my program from a ms telnet session i notice my special inputs for systemin and systemconsole get totally messed up a backspace will write h to the screen and other keys write gibberish as welli have hacked at it enough that i can get it to consistently work but i am sure what i am doing is grossif systemgetenvtermequalsxterm systemoutprintlnnwarning the term type is now set to xtermn final string cmd binsh c export termxterm runtimegetruntimeexeccmdwould there be an issue here for terminals that do not support xterm i notice that the microsoft telnet client does not allow you to set the term type to xterm before you begin a session once the session is started however setting termxterm seems to solve the problem how do most console applications go about this issue,['java'] +1080212,possible to bring the app from background to foreground when running an xct ui test it is possible to put the application under test in the background withxcuidevicepressbuttonxcuidevicebuttonhomeit it possible in some way to bring the app back to foreground active state without relaunching the application,['ios'] +1080259,horizontally centering a flex container when using flex for creating a grid of images how can i horizontally center the grid itself on the page i still want the images to leftalign on each row i would like it to be dynamic to the number of elements per rowjsfiddle with what i have so fargallery thisplay flex flexdirection row flexwrap wrap justifycontent flexstart aligncontent flexstart alignitems flexstartgalleryartwork width 400px thisplay flex margin 10pxdiv classgallery div classgalleryartwork img src div div classgalleryartwork img src div div classgalleryartwork img src div div classgalleryartwork img src div div classgalleryartwork img src divdiv,"['html', 'css']" +1080308,sendkeys ctrl c to external applications text into clipboard i have an app that sits as a trayicon in the system tray i have registered a hotkey that when pressed will capture the current text selection in any application even in web browsersmy aproach is to send the key combination ctlr c to copy the text then access the clipboard and use the text in my own applicationi am programming in vbnet but any help in c or even c with win32 api would be highly appreciatedi use autohotkey and there i have a script which access the clipboard text and works finepauseclipboard start off empty to allow clipwait to detect when the text has arrivedsend cclipwait 2 wait for the clipboard to contain textif errorlevel do nothing after 2 seconds timeout returnrun returnas autohotkey is open source i downloaded the code and try to replicate the behaviour of clipwait as much as i couldmy code works most of the time but sometimes there is an important delay i cannot access the clipboard and the win32 function isclipboardformatavailable keeps returning false for a while this happens when i am trying to copy from google chrome specially in editable textboxesi tried a lot of different things including using the net framework clipboard class i read the problem could be that the thread that was running the commands was not set as sta so i did it in my desperation i also put a timer but nothing solves the problem completelyi read as well the option of putting a hook to monitor the clipboard but i would like to avoid this unless it is the only way of doing ithere is my vbnet codeimports systemruntimeinteropservicesimports systemtextimports systemthreadingimports hotkeyspublic class form1 public m hotkey as keys keysf6 private sub registerhotkeys try dim alreaydregistered as boolean false set the hotkey add an event handler for hot key pressed or could just use handles addhandler cregisterhotkeyhotkeypressed addressof hotkey pressed dim hkgettext as hotkey new hotkeyhkgettext hotkeygetkeysinmodificadoresm hotkey hotkeyformatmodificadoresm hotkeytostring hkgettext try cregisterhotkeyhotkeysaddhkgettext catch ex as hotkeyaddexception alreaydregistered true end try catch ex as exception clogfileadderrorex end try end sub private sub hotkey pressedsender as object e as hotkeypressedeventargs try timer1start catch ex as exception clogfileadderrorex end try end sub private sub form1 loadsender as object e as eventargs handles mybaseload registerhotkeys end sub function copytext as string dim result as string stringempty clipboardclear consolewritelinecontrol c sendkeyssendwaitc dim attempts as integer 100 do while attempts 0 try result gettext if result stringempty then attempts 1 consolewritelineattempts 0 attempts threadsleep100 else attempts 0 end if catch ex as exception attempts 1 consolewritelineattempts exception 0 attempts consolewritelineextostring threadingthreadsleep100 end try loop return result end functionregion win32 dllimportuser32dll setlasterrortrue private shared function isclipboardformatavailableformat as uinteger as marshalasunmanagedtypebool boolean end function dllimportuser32dll setlasterrortrue private shared function getclipboarddatauformat as uinteger as intptr end function dllimportuser32dll setlasterrortrue private shared function openclipboardhwndnewowner as intptr as marshalasunmanagedtypebool boolean end function dllimportuser32dll setlasterrortrue private shared function closeclipboard as marshalasunmanagedtypebool boolean end function dllimportkernel32dll setlasterrortrue private shared function globallockhmem as intptr as intptr end function dllimportkernel32dll setlasterrortrue private shared function globalunlockhmem as intptr as marshalasunmanagedtypebool boolean end function dllimportkernel32dll setlasterrortrue private shared function globalsizehmem as intptr as integer end function private const cf unicodetext as uinteger 13ui private const cf text as uinteger 1uiend region public shared function gettext as string if not isclipboardformatavailablecf unicodetext andalso not isclipboardformatavailablecf text then return nothing end if try if not openclipboardintptrzero then return nothing end if dim handle as intptr getclipboarddatacf unicodetext if handle intptrzero then return nothing end if dim pointer as intptr intptrzero try pointer globallockhandle if pointer intptrzero then return nothing end if dim size as integer globalsizehandle dim buff as byte new bytesize 1 marshalcopypointer buff 0 size return encodingunicodegetstringbufftrimendcontrolcharsnullchar finally if pointer intptrzero then globalunlockhandle end if end try finally closeclipboard end try end function private sub timer1 ticksender as object e as eventargs handles timer1tick try timer1stop dim threada as thread threada new threadaddressof mecopytextthread threadasetapartmentstateapartmentstatesta threadastart catch ex as exception clogfileadderrorex end try end sub sub copytextthread dim result as string copytext if result stringempty then msgboxresult end if end subend classi also searched in other similar questions without a final solution to my problemsend ctrlc to previous active windowhow do i get the selected text from the focused window using native win32 api,"['c#', 'c++']" +1080424,does the c standard support processes i know c11 added support for threads for exampleinclude iostreaminclude threadvoid bar stdcout barnint main stdthread threadbar threadjoin return 0however is there a way to execute the bar function in a separate process if not is there any thiscussion on whether such a feature should be addednote i am aware of the possibility of using platform independent libraries and i am just curious if c supports this directly or will in the future,['c++'] +1080522,pandas is it possible to filter a dataframe with arbitrarily long boolean criteria if you know exactly how you want to filter a dataframe the solution is trivialdfdfa 1 dfb 1but what if you are accepting user input and do not know beforehand how many criteria the user wants to use for example the user wants a filtered data frame where columns a b c 1 is it possible to do something likedef filteritargs value return dfdfargs valueso if the user calls filterita b c value1 it returnsdfdfa 1 dfb 1 dfc 1,['python'] +1080529,when does it matter that this is an rvalue i know that the type of this is a prvalue pure rvalue pointer and that it may be made a pointertoconst andor pointertovolatile affecting accesses to its instance variables by appending the keywords const or volatile to the end of the function definition to which it belongsi also know that this is sometimes incorrectly described as being a const pointer perhaps as a way of saying you cannot make an assignment to this as an rvalue it is inherently unassignable and so there is no need for the concept of a const rvaluei also know that in c11 there are cases where being an rvalue or an lvalue can affect call resolution but i have tried to work through the possibilities and i am not sure whether there is a case where it would actually matter to call resolution that this is an rvalue pointer rather than a const lvalue pointeris there a case where this thistinction makes a real difference from a programmers perspective such as a context where an rvalue pointer can be used that a const lvalue pointer cannot be used where a const lvalue pointer can be used that an rvalue pointer cannot or where the difference affects call resolution,['c++'] +1080563,does hiding a div stop animations css or js considering any css based loader animation as a reference typically when some callback function is executed on success the div is hidden so as to indicate that the results have arrived my question is does hiding the div actually stop the animation or do those still continue to use up cpu cycleswhat about noncss animations,"['javascript', 'css']" +1080639,does the jdk provide a dummy consumer i have a need in a block of code to consume n items from a stream then finish in essence public static t void eatstreamt stream int n consume and items of the stream and throw them away in my situation i cannot change the signature to return streamt and simply return streamskipn i have to actually throw away some elements from the stream not simple logic to be ready for a down stream consumer which does not need to know how or even that this has happenedthe simplest way to do this is to use limitn but i have to call a stream terminating method to activate the stream so in essence i havepublic static t void skipstreamt stream int n streamlimitnforeacht note this code is a gross over simplification of the actual code and is for illustrative purposes only actually limit would not work because there is logic around whathow to consume elements think of it like consuming header elements from a stream then having a consumer consume the body elementsthis question is about the do nothing lambda t is there a do nothing consumer somewhere in the jdk like the do nothing function functionidentity,['java'] +1080678,vuejs webpack vueloader bootstrapsass sassloader i am just getting started with vuejs webpack vueloader bootstrapsass sassloader and i am a little lost what i would like to do is use the sass version of bootstrap with my spa vuejs code i want to do this so my bootstrap customisations can be done using sass here is what i have donecreated a new vuejs webpack project with vuecliinstalled bootstrapsass and sassloaderadded the following to buildwebpackbaseconfjs test scss loaders style css sass test woff2ttfeotsvg loader url query limit 10 created srcstylescss with one line import bootstrapadded this line to the top of srcmainjs import stylescsswhen i now run npm run dev i get the following errorerror in srcmainjsmodule not found error cannot resolve module style in usersrstuartworkspacejavascriptkapichedemosrc srcmainjs 3025i am not sure why this is not working also related to this question how do i get access to bootstrap sass variables inside my vue components if i understand what is going on here the sass will be compiled to css before being included inline in mainjs meaning there is no access to any bootstrap variables in my components is there a way to achieve this,['javascript'] +1080819,how to show different value of input element with ngmodel in the controller if have a variable that tracks the index starting at 0 of the page for a pagination tablevar page pagenumber 0question how can i show this pagenumber variable in the html but always incremented by 1 as the index0 page is obviously the 1st page and should thus be shown as page 1input typetext ngmodelpagepagenumberalso when the model gets updated the value in the input should automatically change again also incremented by 1,['javascript'] +1080948,how to override styles of a library which has its own activity i have a library which has its own activities with colorprimary and colorprimarydark attributes in the application which is using this library there are different values for these color attributesis there a way to make the library use the style provided by the caller applicationso that in the end if the app has a green toolbar the activities in the library would have a green toolbar not the one defined in library themethis is the librarys themestyle namelibrarytheme parentthemeappcompatlightdarkactionbar item namecolorprimarycolorreditem item namecolorprimarydarkcolordark reditemstyleand this is the sample apps main themestyle namesampleapptheme parentthemeappcompatlightdarkactionbar item namecolorprimarycolorgreenitem item namecolorprimarydarkcolordark greenitem item namecoloraccentcoloraccent coloritemstyle,['android'] +1081218,syntax with missed expression for basic forloop some days ago i was talking with my colleagues about this code in javafor nothing special here just an infinite loopbut we wonder why this is syntactically correct if you take a look to jls a14141 youll see thisfor forinit expression forupdate statementi understand that forinit and forupdate can be omitted but at least i would expect that expression is mandatory like in whileloopwhile compile error expression is missedso why can expression be omitted on a forloop and even one think more why is missed expression resolved to true my expectation would be that empty expression is resolved to falsethe same think is valid for other languages i have try it with c and javascript but i believe every language with forloops behaves in that waywhy is an expression clause not mandatory in forloop but in whileloop why does empty expression resolve to true and not to false,"['java', 'c']" +1081281,hibernate associations using too much memory i have a table class which is linked to tables student and teachersa class is linked to multiple students and teachers via foriegn key relationship when i use hibernate associations and fetch large number of entitiestried for 50 i am seeing that it is taking 4 times more memory than if i just use foreign key place holdersis there something wrong in hibernate associationcan i use any memory profiler to figure out whats using too much memorythis is how the schema isclassidclassname studentidstudentnameclass idteacheridteachernameclass idclass id is foreign keycase 1 hibernate associations1in class entity mapped students and teachers as entitytablenameclasspublic class class private integer idprivate string classnameprivate setstudent students new hashsetstudentprivate setteacher teachers new hashsetteacheronetomanyfetch fetchtypeeager mappedby classrefcascade cascadetypeall fetchfetchmodeselectbatchsizesize500public setstudent getstudents return students2in students and teachers mapped class asentitytablenamestudentpublic class student private integer idprivate string studentnameprivate class classrefmanytoonejoincolumnname class idpublic class getclassref return classrefquery used sessionfactoryopensessioncreatequeryfrom class where id50this however was taking a huge amount of memory case 2 remove associations and fetch seperately1no mapping in class entityentitytablenameclasspublic class class private integer idprivate string classname2only a placeholder for foreign key in student teachersentitytablenamestudentpublic class student private integer idprivate string studentnameprivate integer class idqueries used sessionfactoryopensessioncreatequeryfrom class where id50sessionfactoryopensessioncreatequeryfrom student where class id classidsessionfactoryopensessioncreatequeryfrom teacher where class id classidnote shown only imp part of the code i am measuring memory usage of the fetched entities via jamm libraryi also tried marking the query as readonly in case 1 as below which does not improve memory usage very much just a very little so that is not the solve query query sessionfactoryopensession createqueryfrom class where id50 querysetreadonlytrue listclass classlist querylist sessionfactorygetcurrentsessionclosebelow are the heapdump snapshots sorted by sizes looks like the entity maintained by hibernate is creating the problemsnapshot of heapdump for hibernate associations programsnapshot of heapdump for fetching using separate entities,['java'] +1081330,how to post a xwformurlencoded request from reactnative i am working on a ios app using nativereact i am coming from a angular project that uses microsoft identity for token authentication in angular i am using this service call to authenticate http method post url appconstantwebapiurl token data userdata headers contenttype applicationxwformurlencoded charsetutf8 transformrequest function obj var str for var p in obj strpushencodeuricomponentp encodeuricomponentobjp return strjoin successfunction data status headers cfg works great i need to do the same thing with fetch i have seen the examples on the internet that post with a json body but that is not what is needed example that does not work with what i needi know i need to format the body or data with the encodeuricomponent but i do not know how to implement ithere is what i have var obj method post headers accept applicationjson contenttype applicationxwformurlencoded charsetutf8 origin host apiproducthuntcom body jsonstringify username password password grant type password fetch token obj thenfunctionres consolelogres return resjson thenfunctionresjson consolelogresjson return resjson i have tried many things even hardcoding the result from the transformrequest in the body to troubleshooti did remove the jsonstringify function first the error i am getting is the grant type is not valid update var str var test functionvalue for var p in value strpushencodeuricomponentp encodeuricomponentvaluep return strjoin testvalue var obj method post headers accept applicationjson contenttype applicationxwformurlencoded charsetutf8 bodydatastr fetch token obj thenfunctionres consolelogres return resjson thenfunctionresjson consolelogresjson return resjson new errorunsupported bodyinit type,['javascript'] +1081346,cannot generate webpackassetsjson with webpackisomorphictools i am trying to learn react and the whole environment built around it i do that by trying to construct my own devstackthe problem i cannot get across for a very long time is how to serve cssimages while not loosing a power of server renderingi have read a couple of tutorials and thiscovered webpackisomorphictoolsi have configured them and managed to get an images supported sass transformed to css as wellhowever i came across an issue that my webpackassetsjson file is not generated instead i see this output i managed to get it generated on a 2nd run of npm start before this commit but that was definitely not a way to go but it showed that the plugin works when a file is present npm start start usersjanvorcaklearning2016 node srcserverindexjswebpackisomorphictools waiting for the first webpack build to finishwebpackisomorphictools waiting for the first webpack build to finishwebpackisomorphictools waiting for the first webpack build to finishwebpackisomorphictools waiting for the first webpack build to finishi understand the purpose of this file but i cannot really figure out why it is not generated at allis there anything that i am missinghere are the relevant files and a repositorysassloader branch on my universalreactkit repositoryconfiguration webpackconfigjs entry file when running a server could somebody please explain what is going on i have read documentation blogs but i am missing something here thank you,['javascript'] +1081352,what is the time complexity of my function started studying about complexity i am struggling with this onevoid whatint n int i for i 1 i n i int x n while x 0 x i well the first for loop is clearly on the first iteration is on second one is on2 and like that logn times i guesswhich means on ologn on logn complexity did i get this righteditnot a duplicate i know what big o is i have asked the correct evaluation in a specific case,['c'] +1081369,is there a way to create a button or div with a border that has a gradient and has rounded corners this is what it should look like attempts so farusing a gradient background plus an inner element to cover it and leave just an outer border the background is obviously not transparent body background 242424 height 100 width 100 margin 0 padding 0 boxsizing borderbox fontfamily sansserif color fdiv thisplay flex flexdirection column justifycontent center aligncontent center alignitems center width 100 height 100vhh1 margin 2em textalign centera cursor pointer transition easeinout2scolorahover color dnested thisplay block maxwidth 20em padding 2px overflow hidden borderradius 2em background lineargradientto right 00ff00 0 00e5ff 100nested span thisplay inlineblock padding 1em textalign center background 242424 borderradius 2remnested span p padding 0 2em margin 0pseudo thisplay block margintop 20px position relative borderradius 2em padding 1em 2em background 242424pseudoafter position absolute zindex 1 top 2px bottom 2px right 2px left 2px background lineargradientto right 00ff00 0 00e5ff 100 borderradius 2em content div h1gradient border radiush1 a classnestedspanpanother onepspana a classpseudoand another oneadivusing borderimage the corners are not roundedbody background url pattern spng height 100 width 100 margin 0 padding 0 boxsizing borderbox fontfamily sansserifa padding 20px 40px borderimage lineargradientto bottom right 00aeef 0 7cc578 100 borderimageslice 1 borderradius 10pxdiv thisplay flex flexdirection column justifycontent center aligncontent center alignitems center width 100 height 100vhh1 margin 2em textalign centera textdecoration none fontweight bold color black cursor pointer transition easeinout2scolorahover color div h1gradient non working border radiush1 a hrefclick meadiv,['css'] +1081586,angularjs script tag jsonld how do you create an applicationldjson script tag with a dynamically built json object in angularjs this is what i need the script tag to look likescript typeapplicationldjson context type place geo type geocoordinates latitude 4075 longitude 7398 name empire state buildingscripti have tried the following code but i cant get it to workhtmldiv ngcontrollertestcontroller script typeapplicationldjson jsonidjson script jsonidjsondivcontrollervar myapp angularmoduleapplication myappcontrollertestcontroller scope functionscope scopejsonid context type place geo type geocoordinates latitude 4075 longitude 7398 name empire state building the expression inside the script tag does not executethe expression outside the script tag executes correctly and thisplays the jsonplease see jsfiddle,['javascript'] +1081748,optionalofnullable and method chaining i was surprised by optionalofnullable method some day i wrote a function that supposed to return an optionalprivate optionalinteger extractfirstvaluefrominsightsresponse insight return optionalofnullableinsightgetvaluesget0getvaluei mistakenly thought that optionalofnullable will prevent any nullpointerexceptions inside of argument expression now i think i know that it was very foolish idea java have to resolve arguments first to pass it to optionalofnullable invocationbut i have a question is there a nice and good way to accomplish my goal i would like to obtain from expression insightgetvaluesget0getvalue some integer value or null null can be each one of the expressions insightgetvalues or insightgetvaluesget0i know that i can just put this in trycatch block but i am wondering if there is more elegant solution,['java'] +1081780,linq expression as parameter i have to query collection like thismylistwheres myfilterscontainsscountrycodescountrycode above is an example i want to make it variable and call for different columns like thismylistwheres myfilterscontainsscitymylistwheres myfilterscontainssregionmylistwheres myfilterscontainsszipcodeso i would like to define function where the column expression is a parameter what is the signature of such functionpublic void myselect mylistwheres myfilterscontainsmylist is an observablecollection and myfilters is liststring,['c#'] +1081841,calling a singleton method within an instance method in a module that extends itself i extended kernel by itself and within the definition of the instance method kernelabort i called the singleton method kernelabortmodule kernel extend self def abort puts press enter to exit gets kernelabort endendabortwhen i call kernelabort it seems that the kernelabort call inside the method definition refers to the original kernelabort extended as kernelaborthow does ruby know that when i write kernelabort i mean the original abort method not the one i just created how would i recursively call the new abort method i just created,['ruby'] +1081931,mvc 5 webapi download files httpexception i have created a webapi controller based on mvc 5 that provides different files for our customers the tool to access the files is also self written based on net httpclient but thats an other storyin the first version of the download controller i have used the build in mechanism to provide the files like thisbut that mechanism crashed on my iis for files 4gbso i finally came to this code public class downloadcontroller apicontroller public async task getlong id string fullfilepath getfilepathbyidid string returnfilename fullfilepathsplitlast fileinfo path new fileinfofullfilepath httpcontextcurrentresponsecontenttype applicationzip httpcontextcurrentresponseaddheadercontentlength pathlengthtostring httpcontextcurrentresponseaddheadercontentthisposition attachment filename returnfilename httpcontextcurrentresponseflush try byte buffer new byte4096 using filestream fs pathopenread using bufferedstream bs new bufferedstreamfs 524288 int count 0 while count bsreadbuffer 0 bufferlength 0 if httpcontextcurrentresponseisclientconnected break httpcontextcurrentresponseoutputstreamwritebuffer 0 count httpcontextcurrentresponseflush catch exception exception exception logging here that code works very well and i got fast downloads with acceptable cpu usage and thisk io but after some time i noticed that with every single download an unhandled exception writes an entry into the application eventlog of the iis server like thisserver cannot set status after http headers have been sentexception type httpexceptionevent log id 1309i am sure that the recurring use of flush causes the problem but if i remove any of these the download stops workingin similar questions i can find responsebufferoutput true as a solution but that seems to eat all my server resources and delays the downloadany suggestions would be great,['c#'] +1082075,how to override an object array property type in raml 10 i have a generic java type like thisclass responsed listd dataand want to create something similar with raml 10 where i am new tomy first approach wastypes response type object properties data objectand when using itbody type response properties data mydatatypefrom apiworkbench i always get an illegal override of property data inherited from responsethe other idea would be to use repeattypes response type object properties data object repeat trueand respectivelybody type response properties data mydatatype repeat truenow the illegal override is gone but in the apiconsole i now get an uncaught typeerrorhow to solve that or do i need a completely different approach any idea,['java'] +1082088,can intermediate stream operations be encapsulated without breaking the pipeline with java 8 streams is it possible to encapsulate and reuse intermediate stream operations in some way that would not break the stream pipelineconsider this example from the java tutorial on streamsdouble average roster stream filterp pgetgender personsexmale maptointpersongetage average getasdoublesuppose i need to use the filter and maptoint operations in different places throughout my code i might want try and to encapsulate that logic so it can be reused for exampleintstream maleagesstreamperson stream return stream filterp pgetgender personsexmale maptointpersongetagethis is nice but to use it i might have to make a mess of the stream pipeline for example if i want the average age of men named bobdouble averagebob maleagesroster stream filterp bobequalspgetname average getasdoubleis there some better way to do it i am thinking of something along these linesdouble averagebob roster stream filterp bobequalspgetname applythismaleages does not compile average getasdouble,['java'] +1082142,strange behaviour of array element assignment today i came across some strange behaviour of array element assignmentarr abarr2 12arrunshiftarr2 1 2 a b arrpusharr2 a b 1 2 this makes sense howeverarr00 arr2 1 2 a b i know that in 00 the first zero is index and second is the number of elements to be effected in that array starting from index in my thoughts it should be the same as the unshift but it is not can any one explain the behavior,['ruby'] +1082185,is functional programming less efficient for this case i am reading the book functional programming in javascriptin chapter 2 there is the following comparison between imperativefunctional code for finding the first four words containing only letters in a stringimperativevar words count 0text mystringsplit for i0 count4 itextlength i if textimatch09 words wordsconcattexti count functionalvar words var words mystringsplit filterfunctionx return xmatch19slice04i reasoned that for any case where the length of text is greater than four the imperative version will be faster since it only runs up to finding the first four words that match the criteria while the functional version first filters the entire array and only then slices apart the first four elementsmy questions is am i right in assuming this,['javascript'] +1082257,october cms how to correctly route i have been reviewing the documentation for october cms routing but i think that i am missing something i have a page called deals that renders some basic information along with a plugin called deals component the page normally appears at the urlhowever i want to create a route so that if someone visits the urlit will automatically route them back toi know that i should create a routesphp file in my plugin directory however when i try using routegetdeals2 function return viewmakedealsit complains that it cannot find the deals view what am i doing wrongadditionally how can i route it so that my homepagewould route to,['php'] +1082326,member initializer list initialize two members from a function returning a tuple can multiple members be initialized in the member initializer list from a tuple obtained by a functionwith returning multiple values via tuples becoming more popular i hope there is a solution for this i see no reason other than a language limitation why this would not be possiblethis is a mcve for what i haveauto new foostdsize t size stdtuplestdunique ptrchar int auto buffer stdmake uniquecharsize sizeofint 8 auto begin static castintstatic castvoidbufferget 4 return stdmake tuplestdmovebuffer beginstruct x stdunique ptrchar buffer nullptr int begin nullptr stdsize t size 0 xstdsize t size size size stdtiebuffer begin new foosize can this be done xstdsize t size buffer begin size size i simply cannot call new foo once for each member initialization as it returns another tuple with every call so xstdsize t size buffer stdget0new foosize begin stdget1new foosize size size it is not possible even if it this was not the case calling multiple times to get the same result is less than optimalanother solution i thought about was to hold the members as a tuple i thiscarded that as i need the two members properly named inside the class and not accessed with get0 and get1yet another workaround would be to create a simple separate struct to hold the two members this way they would have names but add another level of qualifier and possible i would have to create a copy ctor for it because of the unique ptras reported here c1z will have structured bindings d0144r0 which will make this possibleauto xyz fas i did not find the full paper i cannot tell if this will help in the context of member initializer list i suspect not,['c++'] +1082329,odpnet oraclemanageddataacess random ora12570 errors i am trying to migrate to oraclemanageddataacess from unmanaged version and receiving randoms ora12570 tnspacket reader failure i do not know why this error starts but once it starts every subsequent request gives the same error for about 1030 minutes then it works again for another 1030 minutes and so onso it is a random of subsequent failures for some time then subsequent successalready tried a lot of things to resumethe environmentoraclemanageddataacess version 1212400 4121220150926 nuget no gac reference installed on server that could override the bin versionoracle server oracle database 12c enterprise edition release 121020 64bit productionwindows 2012 windows update okcheckedfirewall it is not a firewall problemmachine error the same problem happens on my machine azure webapp and an aws ec2 instanceinterference there is no sniffer running transparent proxy etcencryption i do not use any kind of encryption unless there is something enabled by default that i do not knowconnections string the same connection string is working perfectly with the unmanaged versionaditional informationthis is a production database it is very stablethe application is compiled to anycpu the iis app pool is restricted to 64bitsim testing exactly the same request every time just a refresh on a get url of a rest ws webapi so it is not related to data formatconfigurationserver sqlnetorasqlnetauthentication services ntsnamesdirectory path tnsnames ezconnectapplication webconfigconnectionstringsadd namex connectionstringdata sourcedescriptionaddress listaddressprotocoltcphostxcomport1521connect dataserverdedicatedservice namexuser idxpasswordx connectionstringsconfigsections section nameoraclemanageddataaccessclient typeoracleinternalcommonodpmsectionhandler oraclemanageddataaccess version412120 cultureneutral publickeytoken89b483f429c47342 configsectionsoraclemanageddataaccessclient version number datasources datasource aliassampledatasource descriptordescriptionaddressprotocoltcphostlocalhostport1521connect dataservice nameorcl datasources settings setting namesqlnetauthentication services valuenone nts setting namesqlnetcrypto checksum server valuerejected setting namesqlnetcrypto checksum client valuerejected setting namesqlnetencryption server valuerejected settings versionoraclemanageddataaccessclientsome referenceststart0odpnet managed driver throws ora12570 network session unexpected packet read errormanaged oracle client with oracle advanced security optionsodpnet error in iis ora12357 network session end of fileupdate 1after pooling changed as i described as an answer here i decided to publish a version to do some real test after 1 day and users complaining about performance i got another error value cannot be null parameter name bytearrayi changed the reference back to the unmanaged version and everything was fine again faster without bytearray error better pooling managementso i am just giving up of the managed version for now maybe i will try again on oracle next releasehere some references about this new error as you can see looks like another bug still without any answertstart0ef odpnet clob value cannot be null parameter name bytearrayso far reasons to not usepooling management bugclob nullnot null bytearray errorsperformance degradation probably related to pooling bug,['c#'] +1082406,spring mvc would not thisplay correct database value after update in my controller put a value from a mysql database into a modelandview object there is a separate program that updates the table and the mvc is supposed to grab that value so there are no forms to update that table when the table is updated and when i hit refresh on the browser the values will not update on the page controllersuppresswarningsuncheckedsecured role user role admin requestmappingvalue welcome method requestmethodgetpublic modelandview defaultpagemodelattributeuser user user collectionsimplegrantedauthority authorities collectionsimplegrantedauthority securitycontextholder getcontextgetauthenticationgetauthorities modelandview view new modelandviewhello redirects to admin page if user has admin role if authoritiestostringcontainsrole admin return new modelandviewredirectadmin authentication auth securitycontextholdergetcontextgetauthentication string username authgetname user userinfo userdaogetuserinfousername systemoutprintlnheres the thing userinfogetlastname userinfogetuserdetails details details userdaogetdetailsinfouserinfogetuserdetailsgetlastname userinfogetuserdetailsgetpostcode plugs plugs userdaogetpluginfodetailsgetmacaddress string json plugsgetjson jsonobject obj new jsonobjectjson this is the value that is not updating string name objgetjsonobjectmetagetjsonobjectlocategetstringvalue systemoutprintlnname viewaddobjectjson obj return viewi know this is pretty looked down upon but i putting that value in javascriptlike thiscset varjson valuejson var data jsonwhy would not the mvc thisplay the correct value when the database is updated i want it to update on refreshedit i have thisabled caching and cleared cache still have a problem any help,['java'] +1082479,null in android studio whenever i click on run project it is showing me nullpointerexception nulli do not know what is the reason why am i getting thisnote dont point this question as duplicate of what is a null pointer exception and how do i fix it because i am not getting null in any control or view or any line of codeedit i am using android studio 14 with following gradle configuration compilesdkversion 23buildtoolsversion 2302,['android'] +1082603,how to make jackson ignore properties if the getters throw exceptions i have a multitude of classes coming from a vendor that like to randomly throw runtimeexceptions on property accesspublic object getsomeproperty if someobscurestatecheck throw new illegalstateexcepion return calculatethevalueofpropertysomerandomstatei cannot change the classes cannot add annotations and it is unrealistic to define mixins for every single class as this part of stack changes fairly oftenhow do i make jackson ignore a property if its getter throws an exception,['java'] +1082632,how does gc work with ienumerator and yield i understand that enumerators and the yield keyword can be used to help with asyncstaggered operations as you can call movenext to run the next block of codehowever i do not really understand what that enumerator object is where does the memory in use of the scope of the enumerator go if you do not movenext an enumerator all the way does it get gcd eventuallybasically i am trying to keep my gc hits down as i am potentially using a lot of enumerators and gc can be an issue inside unity especially due to the older version of mono it usesi have tried to profile this but cannot wrap my head around them still i do not understand the scopingreferencing that happens with enumerators i also do not understand if enumerators are created as objects when you create one from a function that yieldsthe following example shows my confusion better example enumeratorienumeratorbool examplefunction someclass heavyobject new someclass whileheavyobjectprocess yield return true ifheavyobjectsuccess yield return false in this example well never get here what happens to the incomplete enumerator when does heavyobject get gcd heavyobjectdosomemorestuff example call where does this enumerator come from is something creating it with the new keyword in the backgroundienumeratorbool enumerator examplefunctionwhileenumeratormovenext ifenumeratorcurrent break if enumerator is never used after this does it get destroyed when the scope ends or is it gcd at a later date,['c#'] +1082636,how to set severityoverrides in lintoptions i have an android project definingbuildscript repositories jcenter dependencies android plugin for gradle classpath comandroidtoolsbuildgradle150 in my app i want to setandroid lintoptions severityoverrides missingtranslation warning but i get the errorerror34 0 gradle dsl method not found severityoverrides possible causes the project android may be using a version of gradle that does not contain the methodwhat is the correct way to set severityoverridesversions that did compile but do not have the desired effect on the applintvitalrelease build stepimport comandroidbuildermodellintoptions severityoverrides missingtranslation lintoptionsseverity warningandimport comandroidbuildermodellintoptions severityoverridesmissingtranslation lintoptionsseverity warning,['android'] +1082643,what is xml tag in layouts when reading source code of snackbar from design library i found this sort of xml layout view xmlnsandroid classandroidsupportdesignwidgetsnackbarsnackbarlayout androidlayout widthmatch parent androidlayout heightwrap content androidlayout gravitybottom stylestylewidgetdesignsnackbar i never saw this sort of xml with only a view tag with lower v so that is not the view classmy first guess is that it works like the fragment tag indicating that it should create a custom view according to the class attribute but why use this notation when he could just write androidsupportdesignwidgetsnackbarsnackbarlayout xmlnsandroid androidlayout widthmatch parent androidlayout heightwrap content androidlayout gravitybottom stylestylewidgetdesignsnackbar thank you very much,['android'] +1082835,how do i select text except for the first letter i know that firstletter selects the first letter of a blocklevel elementhow can i select all text except the first letteri tried notfirstletter but that did not select anything,['css'] +1082862,java generic compile time error migrating from java 6 to 7 or 8 weve started getting compile errors on code that used generics and that compiled successfully under java 6 heres a simple class to reproduceclass test static class foot t t foot t thist t t get return t static class bar extends foolong barlong t supert static class foobarn extends number extends bar foobar super5l public static void mainstring args bar bar new bar0l long b barget this works foobar foobar new foobar long fb foobarget this generates a compile time error the resulting error istestjava26 error incompatible types object cannot be converted to long long fb foobarget this generates a compile time errordoes anybody have any ideas,['java'] +1082866,why does not this stringformat return string but dynamic viewbagusername charlie brown string title1 stringformatwelcome 0 viewbagusername var title2 stringformatwelcome 0 viewbagusernamein the mvc view i use the values like thishtmlactionlinktitle1 indexhtmlactionlinktitle2 indexhere the title1 works fine but the title2 actionlink failed with a compiler errorcs1973 systemwebmvchtmlhelper has no applicable method named standardheader but appears to have an extension method by that name extension methods cannot be dynamically thispatched consider casting the dynamic arguments or calling the extension method without the extension method syntaxstringformat has quite a few overloads but the return type is always string why does the variable declaration using var fail here,"['c#', '.net']" +1082948,set or replace textcontent in facebooks chat i am developing a chrome extension which allows the user to replace the text of their facebook chat message before they send itfor example if the user types hello there i want to allow them to replace the chat input field with there hello and leave it up to the user to send the altered messagethe problem is that i am able to change the text by editing the textcontent attribute of the input but the chat widget does not know of the change probably because the right events have not fired so when i press enter to send the altered message nothing happens additionally i am not able to delete the changed text with the mouse nor the keyboardi have tried simulating keyboard input but with no success i am open to accepting a working solution that involves thatmy question is how to i replace the text in the chat input field so that the chat widget detects and accepts itnote i am not using jquery so i would prefer solutions that do not use it,['javascript'] +1082962,ios which is the better option to put images core graphicspaintcode app vs image filespng i am developing an ios app which uses quite a few images i am kind of confused about how to load the images in the app a similar question was asked around 5 years ago but a lot has changed since then so i thought it would make more sense to start a new threadthere are mainly two options that i think i haveuse paintcode app you can find it here which gives you cg code to draw images at the runtimeput png image files 1x 2x 3x the things like about the first option area the first most important and unbeatable feature draw dynamic images ie to be able to change the content and gives basic animation effects using variables and equationsa the second most important thing parametric images that behaves perfectly when frame changes no stretching or thistortiona less size as we not gonna use image files reduces the overall size of the app drastically top concern these days eg paintcode app in itself weights only 5 mb leaving out icon filesa resolution independencea very easy to use especially you do not need to remember names you simply make some function callsmy major concerns are does drawing images at the runtime affects performance and other critical parametersunder what circumstances the png files would be a better fitso here i am seeking opinions from more knowledgable people thanks in advance,['ios'] +1083117,javascript split by thisthat how can i split a string like thisvar str m50 0 l0 100 l100 100 l50 0 z m0 0 l100 0 l50 100 l0 0 zvar arr4string strsplitzzi am expecting to get an array with 3 elementsm50 0 l0 100 l100 100 l50 0 m0 0 l100 0 l50 100 l0 0,['javascript'] +1083163,check if element contains shadowroot is it possible to see if a shadow dom element exists i am not too concerned with manipulating it or even really targeting it persay i understand the reasoning of the encapsulation but i would like to be able to style other elements in the regular dom based on whether or not the shadow dom element is presentsort of likeif elementid shadowrootlength trueor if not for the shadowroot at least a specific element within like the id of a div so if that div exists then clearly that shadow dom element is on the pagei know it wouldnt be that simple from some research i have done there are things like and deep but their support seems to be lownonedeprecated buy maybe there is another way however inelegant it may be,"['javascript', 'css']" +1083222,how can i run background tasks in react native i have built a little ios app in react native that does location tracking sending the latlng regularly to a server of the users choosing however this only works when the app is in the foreground how can i run this task in the background when the user is in other apps,"['javascript', 'ios']" +1083272,assigning rvalue returned from function to another rvalue class test public int n1test func return testint main func testthis does not make sense to me how and why is this allowed is it undefined behavior if a function returns an rvalue then how is it possible to set an rvalue to another rvalue if i tried this with any primitive types it would give me an error like i expecti know that lvalues are a place in memory so is the function creating a temporary lvalue rvalue and assigning it to another lvalue can someone explain how this syntax works,['c++'] +1083540,c generics whats the point of the x where t x generic type constraint reading a book nhibernate 3 beginners guide i found a fragment that made me curioustime for action a creating a base entityadd a new class to the folder domain of the project and call it entity make the class abstract and generic in t your code should look similar to the following code snippet using system namespace orderingsystemdomain public abstract class entityt where t entityt my question is what is the point of the fragment where t entityti understand that the where section can be applied to add constraints on the type t but the code above looks like it would be never possible to instantiate such class if it werent abstract anyway,['c#'] +1083581,spring security does not allow users to sign in it does not show any errors once user navigates to signin page and regardless of using correct or wrong usernames and passwords spring security shows following error message i reviewed following questions but still have the same error 123 your login attempt was not successful due to i am using bcryptpasswordencoder to encode new users passwordsloginformcif testnot empty spring security last exception font colorred your login attempt was not successful due to br br cout valuespring security last exceptionmessage font cif cif testnot empty paramerror invalid username and password cif cif testnot empty error div classerrorerrordiv cif cif testnot empty msg div classmsgmsgdiv cif form idformlogin roleform methodpost actioncurl valuej spring security check classrelative form formdefault input typehidden name csrfparametername value csrftoken myservletxmlxml version10 encodingutf8beans xmlnsmvc xmlnsxsi xmlns xmlnscontext xmlnstx xmlnsoxm xmlnsaop xsischemalocation bean iddatasource classorgapachecommonsdbcp2basicdatasource destroymethodclose property namedriverclassname valuecommysqljdbcdriver property nameurl valuejdbcmysqllocalhost89project property nameusername valuetest1 property namepassword valuetest1 bean bean idsessionfactory classorgspringframeworkormhibernate4localsessionfactorybean dependsondatasource property namedatasource refdatasource property namepackagestoscan valuecomprojecmodel property namehibernateproperties props prop keyhibernatedialectorghibernatedialectmysqldialectprop prop keyhibernateformat sqltrueprop prop keyhibernateuse sql commentstrueprop prop keyhibernateshow sqltrueprop prop keyhibernatehbm2ddlautoupdateprop props property bean bean idtransactionmanager classorgspringframeworkormhibernate4hibernatetransactionmanager property namesessionfactory refsessionfactoryproperty bean txadvice idtxadvice transactionmanagertransactionmanager txattributes txmethod nameget readonlytrue txmethod namefind readonlytrue txmethod name txattributes txadvice aopconfig aoppointcut iduserservicepointcut expressionexecution comprojectserviceservice aopadvisor advicereftxadvice pointcutrefuserservicepointcut aopconfigspringsecurityxmlbeansbeans xmlns xmlnsbeans xmlnsxsi xsischemalocation beansimport resourceloginservicexml http autoconfigtrue useexpressionstrue intercepturl pattern accesspermitall intercepturl patternmember accesshasrolerole member intercepturl patternsignin accesspermitall accessdeniedhandler errorpage403 formlogin loginpagesignin defaulttargeturlindex authenticationfailureurlsigninerror usernameparameterusername passwordparameterpassword logout logoutsuccessurlloginlogout enable csrf protection csrf http authenticationmanager authenticationprovider userservicerefmymemberdetailsservice passwordencoder hashbcrypt authenticationprovider authenticationmanagerbeansbeansmymemberdetailsserviceservicepublic class mymemberdetailsservice implements userdetailsservice private memberrepository memberrep override public userdetails loaduserbyusernamefinal string username throws usernamenotfoundexception member member memberrepfindbyusernameusername hashsetstring roles new hashsetstring rolesaddrole member listgrantedauthority authorities builduserauthorityroles return builduserforauthenticationmember authorities private user builduserforauthenticationmember member listgrantedauthority authorities return new usermembergetusername membergetpassword memberisenabled true true true authorities private listgrantedauthority builduserauthoritysetstring userroles setgrantedauthority setauths new hashsetgrantedauthority for string userrole userroles setauthsaddnew simplegrantedauthorityuserrole listgrantedauthority result new arraylistgrantedauthority setauths return result spring version springsecurityversion323releasespringsecurityversion springversion328releasespringversion,['java'] +1084179,breaking out of a loop from within a function called in that loop i am currently trying to figure out a way to break out of a for loop from within a function called in that loop i am aware of the possibility to just have the function return a value and then check against a particular value and then break but i would like to do it from within the function directlythis is because i am using an inhouse library for a specific piece of hardware that mandates the function signature of my function to look like thisvoid foo int passv int aval long bvali am aware that not using a return value is very bad practice but alas circumstances force me to so please bear with meconsider following exampleinclude stdiohvoid foo int a printfa d a breakint mainvoid for int i 0 i 100 i fooi return 0now this does not compile instead i get a compilation error as followsprogc in function foo progc62 error break statement not within loop or switch breaki know what this means the compiler says that the break in foo is not within a for loopnow what i could find from the standard regarding the break statement is thisthe break statement causes control to pass to the statement following the innermost enclosing while do for or switch statement the syntax is simply breakconsidering my function is called from within a for loop why does not the break statement break out of said for loop furthermore is it possible to realize something like this without having the function return first,['c'] +1084269,how to order and group by count subquery from an ordered list on ruby on rails i am trying to do this on ruby on rails with postgres postgisi am trying to do a grouping and count on city of the ordered list i havei have an ordered list of nearest points to my coordinates1101862202 16031959now i want to group it by cities and count the number of items in each citieshowever the format is correct but somehow it has lost its ordering i would like the cities are ordered nearest to my coordinate the whole point is to get the nearest city but now its not ordered nearestquery problem group and count subquery scope nearestcitysubquery fromtreasureorderst thistancetreasureslocation point st geographyfromtextsrid4326point1101862202 16031959 subquery treasure nearestgroupcitycount actual outcome kuala lumpur1 null1 sungai besar1 sungai udang1 kuching1expected outcome kuching1 sungai besar1 sungai udang1 kuala lumpur1 null1my ordering query works correctlytreasureorderst thistancetreasureslocation point st geographyfromtextsrid4326point1101862202 16031959result of the ordering which is correct activerecordrelation treasure id 5 user id 1 treasure name kucing treasure image nil description kucing hint nil location jalan ke puncak serapi created at 20160108 034640 updated at 20160108 034640 treasure id trkky location point rgeogeographicsphericalpointimpl0x3fe9942b71c8 point 11018 16 city kuching state sarawak country malaysia difficulty 2 google place id chijzf irayfzermh5qt30cjjw size 2 treasure id 4 user id 1 treasure name lori treasure image nil description lori hint nil location jalan samsudin created at 20160108 034526 updated at 20160108 034526 treasure id t3ukd location point rgeogeographicsphericalpointimpl0x3fe9942bbd68 point 10214 227 city sungai udang state melaka country malaysia difficulty 2 google place id chijq6 zczx50terbdlr6v1cmdg size 2 treasure id 3 user id 1 treasure name kapal treasure image nil description kapal hint nil location unnamed road created at 20160107 092107 updated at 20160107 092107 treasure id t3xqr location point rgeogeographicsphericalpointimpl0x3fe9942ba29c point 10176 35 city null state selangor country malaysia difficulty 2 google place id chijwu xucotzdersigxbyaxof4 size 3 treasure id 1 user id 1 treasure name kelapa treasure image nil description food hint nil location jalan kiara 3 created at 20160107 060856 updated at 20160107 060856 treasure id tjkql location point rgeogeographicsphericalpointimpl0x3fe9943647d8 point 10165 317 city kuala lumpur state wilayah persekutuan kuala lumpur country malaysia difficulty 2 google place id chij8fbgm1izderphaf2dytwtc size 2 treasure id 2 user id 1 treasure name pulau treasure image nil description pulau hint nil location jalan parit 4 barat created at 20160107 092047 updated at 20160107 092047 treasure id to1br location point rgeogeographicsphericalpointimpl0x3fe9942bd744 point 1010 37 city sungai besar state selangor country malaysia difficulty 2 google place id chijafwex2lgyzeru zvy8tqaw0 size 3note i was told subquery does not order probably an outer join may work how to create such a query thanks,"['sql', 'ruby-on-rails']" +1084342,how to compare equality of lists of arrays with modern java i have two lists of arrays how do i easily compare equality of these with java 8 and its features without using external libraries i am looking for a better higherlevel shorter more efficient solution than bruteforce code like this untested code may contain typos etc not the point of the questionboolean compareliststring list1 liststring list2 tests for nulls etc omitted iflist1size list2size return false fori0 ilist1size i ifarraysequalslist1geti list2geti return false return trueor if there is not any nicer way that is a valid answer toobonus if java 9 offers an even better way what whaterver java 8 can offer feel free to mention it as welledit after looking at the comments and seeing how this question has become moderately hot i think the better should include first checking lengths of all arrays before checking array contents because that has potential to find inequality much quicker if inner arrays are long,['java'] +1084373,is it possible to use result of an sql function as a field in doctrine assume i have product entities and review entities attached to products is it possible to attach a fields to a product entity based on some result returned by an sql query like attaching a reviewscount field equal to countreviewsid as reviewscounti know it is possible to do that in a function likepublic function getreviewscount return countthisreviewsbut i want doing this with sql to minimize number of database queries and increase performance as normally i may not need to load hundreds of reviews but still need to know there number i think running sqls count would be much faster than going through 100 products and calculating 100 reviews for each moreover that is just example on practice i need more complex functions that i think mysql would process faster correct me if i am wrong,"['php', 'mysql', 'sql']" +1084485,compiling transformation the type object is defined in an assembly that is not referenced i am making some changes in an aspnet mvc5 webapp in which i used typelite to create ts definitions from c classes really handy for some reason now i have got this error when executing the t4compiling transformation the type object is defined in an assembly that is not referenced you must add a reference to assembly mscorlib version2050 cultureneutral publickeytoken7cec85d7bea7798e retargetableyesand this warningcompiling transformation assuming assembly reference mscorlib version10330 cultureneutral publickeytokenb77a5c561934e089 used by envdte matches identity mscorlib version40 cultureneutral publickeytokenb77a5c561934e089 of mscorlib you may need to supply runtime policy mairtrackingwebi guess it is something related to the envdte version used by typelite and the reference to mscorlib envdte uses should i add a bindingredirect in the webconfig i am using vs2015 with update2 ctp,"['c#', 'asp.net']" +1084486,reading variable value in play ws response scope void makepdfpagestring url pdfcontentbyte contentbyte comitextpdftextfont sans utilitymethodsgetsansseriffont14 sanssetcolor80147225 columntext ct new columntextcontentbyte ctsetsimplecolumnhello 0 780 595 830 10 elementalign center try ctgo catch documentexception e systemoutprintlne todo autogenerated catch block eprintstacktrace promisewsresponse out notificationcallurl outmapresp mapstringobject mapp jsonfromjsonrespasjsongetlist mapclass pdfservicedesignpdfmapp contentbyte return resp contentbyte is going empty to desginpdfits going async so thats why its not having the value of contentbyte can any other way so i can synchronously use or any other way to solve my problemwsresponse resp outget10getting fails,['java'] +1084664,should a range for loop be used instead of iterators on a vector given a vector vc one can iterate through the vector with a range forfor auto c vc stdcout cor with an iteratorfor auto it vccbegin it vccend it stdcout itis there a functional reason to use one method over the other or is this merely a matter of style,['c++'] +1084781,windows uwp connect to ble device after thiscovery i am using bluetoothleadvertisementwatcher to find nearby ble devices and it is working well after finding them i want to connect and readwrite data via gatt but i cannot figure out how to use the api after getting the bluetoothleadvertisement public class adapter private readonly bluetoothleadvertisementwatcher blewatcher new bluetoothleadvertisementwatcher public adapter blewatcherreceived blewatcheronreceived private void blewatcheronreceivedbluetoothleadvertisementwatcher sender bluetoothleadvertisementreceivedeventargs args how to connect i know it is the wrong place to to this but this is just an example public void startscanningfordevicesguid serviceuuids blewatcheradvertisementfilteradvertisementserviceuuidsclear foreach var uuid in serviceuuids blewatcheradvertisementfilteradvertisementserviceuuidsadduuid blewatcherstart i have found samples that are using deviceinformationfindallasync instead of bluetoothleadvertisementwatcher but these are not working finding any deviceupdateafter digging around some time i found the following way but unfortunately the pairing fails the device is just an arduino with a ble shield i can definitely connect with android and ios so it must be possible with uwp somehow private void blewatcheronreceivedbluetoothleadvertisementwatcher sender bluetoothleadvertisementreceivedeventargs args var dev await bluetoothledevicefrombluetoothaddressasyncargsbluetoothaddress devdeviceinformationpairingcanpair is true dprstatus is failed devicepairingresult dpr await devdeviceinformationpairingpairasyncdevicepairingprotectionlevelnone var service await gattdeviceservicefromidasyncdevdeviceinformationidupdate 2i am now able to thiscover and pair unstable but ok for now but var service await gattdeviceservicefromidasyncargsidthrows the following exceptionsystemiofilenotfoundexception the system cannot find the file specified exception from hresult 0x800702i have no clue why,['c#'] +1085059,java opencv extracting good matches from knnmatch i am trying to implement a very simple program for finding similarities between two imagesi am using the orb feature detector and image descriptor for this task and i am identifying the matches using knnmatchfeaturedetector detector featuredetectorcreatefeaturedetectororbdescriptorextractor descriptor descriptorextractorcreatedescriptorextractororbdescriptormatcher matcher descriptormatchercreatedescriptormatcherbruteforce hamming detection first imagemat img1 imgcodecsimreadpath1 imgcodecscv load image grayscalemat descriptors1 new matmatofkeypoint keypoints1 new matofkeypointdetectordetectimg1 keypoints1descriptorcomputeimg1 keypoints1 descriptors1 second imagemat img2 imgcodecsimreadpath2 imgcodecscv load image grayscalemat descriptors2 new matmatofkeypoint keypoints2 new matofkeypointdetectordetectimg2 keypoints2descriptorcomputeimg2 keypoints2 descriptors2 matching match these two keypoints setslistmatofdmatch matches new arraylistmatofdmatchmatcherknnmatchdescriptors1 descriptors2 matches 5i am able to draw the matches as follows drawing outputmat outputimg new mat this will draw all matches works finefeatures2ddrawmatches2img1 keypoints1 img2 keypoints2 matches outputimg save imageimgcodecsimwriteresultjpg outputimgthe problem is that there are too many matches and it includes also those that are way off i cannot seem to find how to extract only the good matches exceeding some threshold could someone point me to the right direction or redirect me to some basic working example i have spent several hours on this and seem to be lostediti tried looking at keypoint matching just works two times java opencv but the standard nonknn match uses different structures and and i could not make it work,['java'] +1085580,how to compare systemenum to enum implementation without boxing how can i compare a systemenum to an enum without boxing for example how can i make the following code work without boxing the enumenum color red green bluesystemenum myenum getenum returns a systemenum may be a color may be some other enum typeif myenum colorred error dosomethingto be specific the intent here is not to compare the underlying values in this case the underlying values are not meant to matter instead if two enums have the same underlying value they should not be considered equal if they are two different kinds of enumsenum fruit apple 0 banana 1 orange 2enum vegetable tomato 0 carrot 1 celery 2myenum vegetabletomatoif myenum fruitapple error code should reach this point even though they are the same underlying int values logworksthis is basically the same functionality as enumequalsobject unfortunately equals requires boxing the enum which in our case would be a naughty thing to dois there a nice way to compare two arbitrary enums without boxing or otherwise creating a bunch of overheadthanks for any help,['c#'] +1085767,swift struct vs class what is the allowed stack size and refactoring a class to a struct first i understand the difference between value and reference types this is not that question i am rewriting some of my code in swift and decided to also refactor some of the classes therefore i thought i would see if some of the classes make sense as structsmemory i have some model classes that hold very large arrays that are constantly growing in size unknown final size and could exist for hours first are there any guidelines about a suggested or absolute size for a struct since it lives on the stackrefactoring use since i am refactoring what right now is a mess with too much dependency i wonder how i could improve on that the views and view controllers are mostly easily it is my model and what it does that is always left me wishing for better examples to followworkermanager singleton that holds one or two workers at a time one will always be recording new data from a sensor and the other would be reviewing stored data the view controllers get the worker reference from the workermanager and ask the worker for the data to be thisplayedworker does everything on a queue to prevent memory access issues c array pointers are constantly changing as they grow listening the listening worker listens for new data sends it to a processor object that it created that cleans up the data and stores it in c arrays held by the worker then if there is valid data the worker tells the analyzer also owned by the worker to analyze the data and stores it in other c arrays to be fed to views both the processor and analyzer need state to know what has happened in the past and what to process and analyze next the pure raw data is stored in a separate record nsmanaged object reviewer takes a record and uses the pure raw data to recreate all of the analyzed data so that it can be reviewed analyzed data is massive and i do not want to store it to thisknow my second question is couldshould processor and analyzer be replaced with structs or maybe protocols for the worker they are not really objects in the normal sense just convenient groups of related methods and the necessary state and since the code is nearly a thousand lines for each and i do not want to put it all in one class or even the same filei just do not have a good sense of how to remove all of my state use pure functions for all of the complex mathematical operations that are performed on the arrays and where to put them,['ios'] +1085792,cannot upload archive to app store since yesterday 2 days before i successfully uploaded the archive for my application and my application is on app store but yesterday and today when i upload the archive i see uploading the archive message with subtitle sending api usage to itunes connect at the beggining but then i see itunes store operation failed this action could not be completed try again later when i try to upload the archive for another application everything is ok it is very strange because since 2 days ago i only changed the minimum age in the application from 17 to 18 so i did not change everything important in the application settingsmay be in happen because we use iad network and apple notified that this network will be unavailable since july,"['ios', 'objective-c', 'iphone']" +1085855,edgeeffect on appbarlayout i have a collapsingtoolbar as a parent element in my view which looks like belowxml version10 encodingutf8androidsupportdesignwidgetcoordinatorlayout xmlnstools stylestylexmatchymatch xmlnsandroid xmlnsapp androidfitssystemwindowstrue androidsupportdesignwidgetappbarlayout androidididappbar appthemestylethemeoverlayappcompatdarkactionbar androidlayout widthmatch parent androidlayout heightdimenappbar image height androidfitssystemwindowstrue androidtransitionnamestringshared element anim name androidbackgroundcolorred androidsupportdesignwidgetcollapsingtoolbarlayout androidididcollapsing toolbar stylestylexmatchymatch androidminheight0dp appstatusbarscrimcolortranslucent black appexpandedtitletextappearanceandroidcolortransparent androidfitssystemwindowstrue applayout scrollflagsscrollenteralwaysenteralwayscollapsed relativelayout androidididtoolbar content parent stylestylexmatchymatch androidfitssystemwindowstrue applayout collapsemodeparallax applayout scrollflagsscrollexituntilcollapsed imageview androidididtoolbar iv stylestylexmatchymatch androidscaletypecentercrop toolsignorecontentdescription textview androidididtoolbar title stylestyleimagetexttitle androidlayout alignparentbottomtrue androidmaxlines2 textview androidididtoolbar dm stylestyleimagetextsubtitle androidlayout aboveidtoolbar title androidmaxlines2 relativelayout include androidididtoolbar layoutlayouttoolbar androidsupportdesignwidgetcollapsingtoolbarlayout androidsupportdesignwidgetappbarlayout androidsupportv4widgetnestedscrollview xmlnsandroid stylestylexmatchymatch linearlayout androidididsection parent stylestylexmatchymatchvert androidanimatelayoutchangestrueandroidsupportv4widgetnestedscrollview framelayout stylestylexmatchywrap androidbackgroundcolordark red applayout anchoriddetail fragment applayout anchorgravitybottomrightend button androidididbutton stylestylesubhead androidlayout widthmatch parent androidbackgroundandroidattrselectableitembackground androidtextstringbutton text androidtextcolorandroidcolorwhite progressbar androidididsign progress stylestyleprogressbar androidlayout gravitycenter androidvisibilitygone framelayoutandroidsupportdesignwidgetcoordinatorlayouti have an edge effect below the toolbar when i scroll all the way to the top like thisbut i want the edge effect to be below the statusbar like thishow should i go about doing thisedit i tried making the nestedscrollview my parent and it works but thats not how i want my hierarchy to be,['android'] +1085941,extracting windows file properties custom properties c in wordexcel you have to possibility to add custom properties see imagecustom propertiesas you guys can see there is the field properties you can add any information you want therewhen you save the file and you go to the file location in the folder you can right click properties and you have all the tabs generalsecuritydetailsprevious versions with the feature you add the tab customnow i want to get this information through coding custom properties information and extract it later to notepadso far i used the shell32 but then i only get the information that is in the details tab i did some research and saw some possibilities with dsofiledll but i want to know if there is a possibility to do this without installing other dllthis is my code so far with the shell32 static void mainstring args using streamwriter writer new streamwriterfilepathhere consolesetoutwriter readproperties static void readproperties liststring arrheaders new liststring shell shell new shell folder objfolder shellnamespacefilepathhere folderitem objfolderitem objfolderparsenamefileheredoc for int i 0 i shortmaxvalue i string header objfoldergetdetailsofobjfolder i if stringisnulloremptyheader break arrheadersaddheader for int i 0 i arrheaderscount i consolewriteline0t1 2 i arrheadersi objfoldergetdetailsofobjfolderitem i consolereadkey thanks in advancedesu,['c#'] +1085949,what do i win when i implement an interface which is blank i have a question regarding interfaces in java and the question sounds like thiswhat is the use of implementing a blank empty interface in my classin order to get a better understanding of the question i will give you a concrete exampleif you go and see the implementation of arraylist class you will find out that it implements two interfaces randomaccess and cloneable which are actually totally emptywhy is that happeningwhat do i win by implementing a totally blank interface for my classin case you have any ideas please leave a commentthank you in advance,['java'] +1085952,setting wifi priority on android lollipop or later via settings ui kitkat had the settings wifi advanced wifi option to set the priority as shownthis is not present on my nexus lollipop and marshmallow devices i see there is an app available but i would like to know if there is some onboard way i missed to manage these and if not what the thinking was behind its removal,['android'] +1086012,pdf file download using blockingqueue i am trying to download a pdf file using urlconnection heres how i setup the connection objecturl serverurl new urlurlurlconnection httpurlconnection serverurlopenconnectionurlconnectionsetdoinputtrueurlconnectionsetrequestmethodgeturlconnectionsetrequestpropertycontenttype applicationpdfurlconnectionsetrequestpropertyenctype multipartformdatastring contentlength urlconnectiongetheaderfieldcontentlengthi obtained inputstream from the connection objectbufferedinputstream new bufferedinputstreamurlconnectiongetinputstreamand the output stream to write the file contentsfile dir new filecontextgetfilesdir mfolderifdirexists dirmkdirfinal file f new filedir stringvalueofdocumentnamefcreatenewfilefinal bufferedoutputstream bufferedoutputstream new bufferedoutputstreamnew fileoutputstreamf true true for appendmodeblockingqueue is created so that threads performing read and write operations can access the queuefinal blockingqueuebytearraywrapper blockingqueue new arrayblockingqueuebytearraywrappermax valuetruefinal byte databuffer new bytemax valuenow created thread to read data from inputstreamthread readerthread new threadnew runnable override public void run try int count 0 whilecount bufferedinputstreamreaddatabuffer 0 databufferlength 1 bytearraywrapper bytearraywrapper new bytearraywrapperdatabuffer bytearraywrappersetbytesreadcountcount blockingqueueputbytearraywrapper blockingqueueputnull end of file catchexception e eprintstacktrace finally try bufferedinputstreamclose catch ioexception e eprintstacktrace now the writer thread reads those file contentsthread writerthread new threadnew runnable override public void run try whiletrue bytearraywrapper bytewrapper blockingqueuetake ifnull bytewrapper break bufferedoutputstreamwritebytewrappergetbytesread 0 bytewrappergetbytesreadcount bufferedoutputstreamflush catchexception e eprintstacktrace finally try bufferedoutputstreamclose catch ioexception e eprintstacktrace finally threads are startedreaderthreadstartwriterthreadstarttheoretically it should read the file from inputstream and save it to the target file however in reality it produces blank pdf file at some other time it shows invalid pdf format exception file size matches with content length of the inputstream is there anything i am missing,"['java', 'android']" +1086176,queryexception resulttransformer is not allowed for select new queries i have the following springdata repository query queryselect new commypackagemobilecaselistcident concatcsubtype ccontactname ctype coalescecupdatetimestampcinserttimestamp from mobilecase c where cmobileuserident 1 and corigin source order by cappointmentfrom nulls last listmobilecaselist findcasesforuserstring useridentand following runtime code listmobilecaselist result caserepofindcasesforuseruseridentthis worked fine until now no idea what causes the exception now on my pc localhost it still works but on the ubuntu server the query execution fails with following error20160217 125649696 error 13397 httpnio9090exec6 oacthispatcherservlet servletservice for servlet thispatcherservlet in context with path threw exception request processing failed nested exception is orgspringframeworkdaoinvaliddataaccessapiusageexception orghibernatequeryexception resulttransformer is not allowed for select new queries nested exception is javalangillegalargumentexception orghibernatequeryexception resulttransformer is not allowed for select new queries with root causeorghibernatequeryexception resulttransformer is not allowed for select new queries at orghibernateloaderhqlqueryloadercheckqueryqueryloaderjava502 hibernatecore4311finaljarna at orghibernateloaderhqlqueryloaderlistqueryloaderjava496 hibernatecore4311finaljarna at orghibernatehqlinternalastquerytranslatorimpllistquerytranslatorimpljava387 hibernatecore4311finaljarna at orghibernateenginequeryspihqlqueryplanperformlisthqlqueryplanjava236 hibernatecore4311finaljarna at orghibernateinternalsessionimpllistsessionimpljava1300 hibernatecore4311finaljarna at orghibernateinternalqueryimpllistqueryimpljava103 hibernatecore4311finaljarna at orghibernatejpainternalqueryimpllistqueryimpljava573 hibernateentitymanager4311finaljarna at orghibernatejpainternalqueryimplgetresultlistqueryimpljava449 hibernateentitymanager4311finaljarna at orgspringframeworkdatajparepositoryqueryjpaqueryexecutioncollectionexecutiondoexecutejpaqueryexecutionjava114 springdatajpa1100m1jarna at orgspringframeworkdatajparepositoryqueryjpaqueryexecutionexecutejpaqueryexecutionjava78 springdatajpa1100m1jarna at orgspringframeworkdatajparepositoryqueryabstractjpaquerydoexecuteabstractjpaqueryjava102 springdatajpa1100m1jarna at orgspringframeworkdatajparepositoryqueryabstractjpaqueryexecuteabstractjpaqueryjava92 springdatajpa1100m1jarna at orgspringframeworkdatarepositorycoresupportrepositoryfactorysupportqueryexecutormethodinterceptordoinvokerepositoryfactorysupportjava482 springdatacommons1120m1jarna at orgspringframeworkdatarepositorycoresupportrepositoryfactorysupportqueryexecutormethodinterceptorinvokerepositoryfactorysupportjava460 springdatacommons1120m1jarna at orgspringframeworkaopframeworkreflectivemethodinvocationproceedreflectivemethodinvocationjava179 springaop424releasejarna at orgspringframeworkdataprojectiondefaultmethodinvokingmethodinterceptorinvokedefaultmethodinvokingmethodinterceptorjava61 springdatacommons1120m1jarna at orgspringframeworkaopframeworkreflectivemethodinvocationproceedreflectivemethodinvocationjava179 springaop424releasejarna at orgspringframeworktransactioninterceptortransactioninterceptor1proceedwithinvocationtransactioninterceptorjava99 springtx424releasejarna at orgspringframeworktransactioninterceptortransactionaspectsupportinvokewithintransactiontransactionaspectsupportjava281 springtx424releasejarna at orgspringframeworktransactioninterceptortransactioninterceptorinvoketransactioninterceptorjava96 springtx424releasejarna at orgspringframeworkaopframeworkreflectivemethodinvocationproceedreflectivemethodinvocationjava179 springaop424releasejarna at orgspringframeworkdaosupportpersistenceexceptiontranslationinterceptorinvokepersistenceexceptiontranslationinterceptorjava136 springtx424releasejarna at orgspringframeworkaopframeworkreflectivemethodinvocationproceedreflectivemethodinvocationjava179 springaop424releasejarna at orgspringframeworkdatajparepositorysupportcrudmethodmetadatapostprocessorcrudmethodmetadatapopulatingmethodinterceptorinvokecrudmethodmetadatapostprocessorjava131 springdatajpa1100m1jarna at orgspringframeworkaopframeworkreflectivemethodinvocationproceedreflectivemethodinvocationjava179 springaop424releasejarna at orgspringframeworkaopinterceptorexposeinvocationinterceptorinvokeexposeinvocationinterceptorjava92 springaop424releasejarna at orgspringframeworkaopframeworkreflectivemethodinvocationproceedreflectivemethodinvocationjava179 springaop424releasejarna at orgspringframeworkaopframeworkjdkdynamicaopproxyinvokejdkdynamicaopproxyjava208 springaop424releasejarna at comsunproxyproxy144findcasesforuserunknown source nanaany ideas suggestions,['java'] +1086187,control access of third party apis to android system resources when you import third party apis packet dependency injection generated libraries source code etc in your android project you assume they will behave as advertised most of the times code is not open source it is obfuscated or just compiledis there a way to control the access of this apis to important system resources such as network contacts video and audio locationthe best approach would be to provide a proxy to them for the system resources this would have the following benefitstests could be performed by providing mock data in the proxiesyour application would not have to provide all the permissions the api require if they are not necessary and the proxy would allow the api to not break because of permission by emulating permission grantedfilter possible data collected locally about user and sent to an api home repo used for advertising or malicious intent i have failed to find how one such solution can be implemented since the users defined activities and services can not control the services of the third party apis or even prevent them for making direct calls to any android public interfacethe solution should not require root access since you do not want to have this control outside the boundaries of your own appthe content of this question is linked to several questions which address particularities of this broad question log data of content providers network requests that got me to think of this problem while researching an answer for itnote the short answer is no but one can be creative enough maybe going for native level hacks may resolve this issue idk,['android'] +1086388,enable xcodes check spelling while typing option by default is there any way to enable xcodes check spelling while typing option on every xcode project and file by defaultcurrently i have to set this option on each file and the option gets reset after closing xcodeoption in question editformatspelling and grammarcheck spelling while typing,['ios'] +1086439,how to make a generic method that take a generic type i would like to write the following methodprivate void foot titemttitem param1where t must be a generic type that takes titem as its generic infocall example would be likeprivate void main listint ints new listint foolist intints editin my case i would only need to for collectionsthe actual use case is that i wanted to write a method that adds something to a icollection sadly the icollection does not have an add method only the icollectiont has iti cannot change the method toprivate footicollectiontsince with that i am losing the information what type the actual list is which is more important to me than what type the items within the listso the above idea was born which did not work,['c#'] +1086578,jquery target all elements with val less than 1 i have multiple elements in the dom with a class of blockbadge if the value of any blockbadge is 0 then i want to add a class to that element in order to style it differentlymy js adds the class to all of these elements if anyone of them equal 0 how do i make it only affect those elements which equal zerohtmlspan classblockbadge1spanspan classblockbadge0span this element should have the class zero addedspan classblockbadge4spanjsvar blockbadgeval blockbadgevalif blockbadgeval 0 blockbadgeaddclasszero,"['javascript', 'jquery']" +1086609,running espresso after proguarding app but not test i enabledtestbuildtype releaseto run the espressotests after proguard but i get a problem with mockito then can i thisable proguard for the testcode or anyone sees a reason why even when i add this to my proguardconfigdontwarn orgmockitodontwarn sunreflectdontwarn androidtestit still fails withwarning orgmockitocglibbeansbeancopiergenerator cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibbeansbeancopiergenerator cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibbeansbeancopiergenerator cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibbeansbeancopiergenerator cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibbeansbeancopiergenerator cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibbeansbeancopiergenerator cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibbeansbeancopiergenerator cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibbeansbeancopiergenerator cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibbeansbeancopiergenerator cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibbeansbeancopiergenerator cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibbeansbeancopiergenerator cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibbeansbeancopiergenerator cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibbeansbeancopiergenerator cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibbeansbeangenerator cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibbeansbeangenerator cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibbeansbeangenerator cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibbeansbeangenerator cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibbeansbeangenerator cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibbeansbeanmapemitter cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibbeansbeanmapemitter cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibbeansbeanmapemitter cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibbeansbeanmapemitter cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibbeansbeanmapemitter1 cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibbeansbeanmapemitter1 cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibbeansbeanmapemitter1 cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibbeansbeanmapemitter2 cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibbeansbeanmapemitter2 cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibbeansbeanmapemitter2 cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibbeansbeanmapemitter2 cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibbeansbeanmapemitter3 cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibbeansbeanmapemitter3 cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibbeansbeanmapemitter3 cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibbeansimmutablebeangenerator cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibcorereflectutils cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibcorereflectutils cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibcorereflectutils cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibcorereflectutils cannot find referenced class javabeansintrospectionexceptionwarning orgmockitocglibcorereflectutils cannot find referenced class javabeansintrospectorwarning orgmockitocglibcorereflectutils cannot find referenced class javabeansintrospectorwarning orgmockitocglibcorereflectutils cannot find referenced class javabeansbeaninfowarning orgmockitocglibcorereflectutils cannot find referenced class javabeansbeaninfowarning orgmockitocglibcorereflectutils cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibcorereflectutils cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibcorereflectutils cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibcorereflectutils cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibcorereflectutils cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibcorereflectutils cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibcorereflectutils cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibcorereflectutils cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibcorereflectutils cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibcorereflectutils cannot find referenced class javabeansbeaninfowarning orgmockitocglibcorereflectutils cannot find referenced class javabeanspropertydescriptorwarning orgmockitocglibcorereflectutils cannot find referenced class javabeansintrospectionexceptionwarning orgmockitocglibtransformabstractprocesstask cannot find referenced class orgapachetoolsanttaskwarning orgmockitocglibtransformabstractprocesstask cannot find referenced class orgapachetoolsanttaskwarning orgmockitocglibtransformabstractprocesstask cannot find referenced method orgapachetoolsantproject getproject in program class orgmockitocglibtransformabstractprocesstaskwarning orgmockitocglibtransformabstractprocesstask cannot find referenced class orgapachetoolsanttypesfilesetwarning orgmockitocglibtransformabstractprocesstask cannot find referenced class orgapachetoolsanttypesfilesetwarning orgmockitocglibtransformabstractprocesstask cannot find referenced class orgapachetoolsantdirectoryscannerwarning orgmockitocglibtransformabstractprocesstask cannot find referenced class orgapachetoolsantdirectoryscannerwarning orgmockitocglibtransformabstractprocesstask cannot find referenced class orgapachetoolsanttypesfilesetwarning orgmockitocglibtransformabstractprocesstask cannot find referenced class orgapachetoolsantbuildexceptionwarning orgmockitocglibtransformabstractprocesstask cannot find referenced class orgapachetoolsantbuildexceptionwarning orgmockitocglibtransformabstractprocesstask cannot find referenced class orgapachetoolsanttypesfilesetwarning orgmockitocglibtransformabstractprocesstask cannot find referenced class orgapachetoolsanttypesfilesetwarning orgmockitocglibtransformabstractprocesstask cannot find referenced class orgapachetoolsanttypesfilesetwarning orgmockitocglibtransformabstractprocesstask cannot find referenced class orgapachetoolsantdirectoryscannerwarning orgmockitocglibtransformabstractprocesstask cannot find referenced class orgapachetoolsantprojectwarning orgmockitocglibtransformabstracttransformtask cannot find referenced method void logjavalangstringint in program class orgmockitocglibtransformabstracttransformtaskwarning orgmockitocglibtransformabstracttransformtask cannot find referenced method void logjavalangstring in program class orgmockitocglibtransformabstracttransformtaskfor the record here the more of the warningswarning orghamcrestintegrationeasymock2adapter cannot find superclass or interface orgeasymockiargumentmatcherwarning orghamcrestintegrationjmock1adapter cannot find superclass or interface orgjmockcoreconstraintwarning orgmockitocglibtransformabstractprocesstask cannot find superclass or interface orgapachetoolsanttaskwarning library class androidtestandroidtestcase extends or implements program class junitframeworktestcasewarning library class androidtestandroidtestrunner extends or implements program class junitrunnerbasetestrunnerwarning library class androidtestinstrumentationtestcase extends or implements program class junitframeworktestcasewarning library class androidtestinstrumentationtestsuite extends or implements program class junitframeworktestsuitewarning library class androidtestsuitebuildertestsuitebuilderfailedtocreatetests extends or implements program class junitframeworktestcasewarning androidsupporttestespressocoredepsguavacachestriped64 cannot find referenced class sunmiscunsafewarning androidsupporttestespressocoredepsguavacachestriped64 cannot find referenced class sunmiscunsafewarning androidsupporttestespressocoredepsguavacachestriped64 cannot find referenced class sunmiscunsafewarning androidsupporttestespressocoredepsguavacachestriped64 cannot find referenced class sunmiscunsafewarning androidsupporttestespressocoredepsguavacachestriped64 cannot find referenced class sunmiscunsafewarning androidsupporttestespressocoredepsguavacachestriped64 cannot find referenced class sunmiscunsafewarning androidsupporttestespressocoredepsguavacachestriped64 cannot find referenced class sunmiscunsafewarning androidsupporttestespressocoredepsguavacachestriped64 cannot find referenced class sunmiscunsafewarning androidsupporttestespressocoredepsguavacachestriped641 cannot find referenced class sunmiscunsafewarning androidsupporttestespressocoredepsguavacachestriped641 cannot find referenced class sunmiscunsafewarning androidsupporttestespressocoredepsguavacachestriped641 cannot find referenced class sunmiscunsafewarning androidsupporttestespressocoredepsguavacachestriped641 cannot find referenced class sunmiscunsafewarning androidsupporttestespressocoredepsguavacachestriped64cell cannot find referenced class sunmiscunsafewarning androidsupporttestespressocoredepsguavacachestriped64cell cannot find referenced class sunmiscunsafewarning androidsupporttestespressocoredepsguavacachestriped64cell cannot find referenced class sunmiscunsafewarning warning androidsupporttestrunnermonitoringinstrumentation cannot find referenced method androidappinstrumentationactivityresult execstartactivityandroidcontentcontextandroidosibinderandroidosibinderandroidappactivityandroidcontentintentint in program class androidsupporttestinternalrunnerhiddenexposedinstrumentationapiwarning androidsupporttestrunnermonitoringinstrumentation cannot find referenced method androidappinstrumentationactivityresult execstartactivityandroidcontentcontextandroidosibinderandroidosibinderandroidappactivityandroidcontentintentintandroidosbundle in program class androidsupporttestinternalrunnerhiddenexposedinstrumentationapiwarning androidsupporttestrunnermonitoringinstrumentation cannot find referenced method androidappinstrumentationactivityresult execstartactivityandroidcontentcontextandroidosibinderandroidosibinderandroidappfragmentandroidcontentintentintandroidosbundle in program class androidsupporttestinternalrunnerhiddenexposedinstrumentationapiwarning comsquareupjavawriterjavawriter cannot find referenced class javaxlangmodelelementmodifierwarning comsquareupjavawriterjavawriter cannot find referenced class javaxlangmodelelementmodifierwarning comsquareupjavawriterjavawriter cannot find referenced class javaxlangmodelelementmodifierwarning comsquareupjavawriterjavawriter cannot find referenced class javaxlangmodelelementmodifierwarning comsquareupjavawriterjavawriter cannot find referenced class javaxlangmodelelementmodifierwarning comsquareupjavawriterjavawriter cannot find referenced class javaxlangmodelelementmodifierwarning comsquareupjavawriterjavawriter cannot find referenced class javaxlangmodelelementmodifierwarning comsquareupjavawriterjavawriter cannot find referenced class javaxlangmodelelementmodifierwarning comsquareupjavawriterjavawriter cannot find referenced class javaxlangmodelelementmodifierwarning comsquareupjavawriterjavawriter cannot find referenced class javaxlangmodelelementmodifierwarning comsquareupjavawriterjavawriter cannot find referenced class javaxlangmodelelementmodifierwarning comsquareupjavawriterjavawriter cannot find referenced class javaxlangmodelelementmodifierwarning comsquareupjavawriterjavawriter cannot find referenced class javaxlangmodelelementmodifierwarning comsquareupjavawriterjavawriter cannot find referenced class javaxlangmodelelementmodifierwarning comsquareupjavawriterjavawriter cannot find referenced class javaxlangmodelelementmodifierwarning comsquareupjavawriterjavawriter cannot find referenced class javaxlangmodelelementmodifierwarning comsquareupjavawriterjavawriter cannot find referenced class javaxlangmodelelementmodifierwarning comsquareupjavawriterjavawriter cannot find referenced class javaxlangmodelelementmodifierwarning comsquareupjavawriterjavawriter cannot find referenced class javaxlangmodelelementmodifierwarning comsquareupjavawriterjavawriter cannot find referenced class javaxlangmodelelementmodifierwarning comsquareupjavawriterjavawriter cannot find referenced class javaxlangmodelelementmodifierwarning comsquareupjavawriterjavawriter cannot find referenced class javaxlangmodelelementmodifierwarning comsquareupjavawriterjavawriter cannot find referenced class javaxlangmodelelementmodifierwarning comsquareupjavawriterjavawriter cannot find referenced class javaxlangmodelelementmodifierwarning comsquareupjavawriterjavawriter cannot find referenced class javaxlangmodelelementmodifierwarning comsquareupjavawriterjavawriter cannot find referenced class javaxlangmodelelementmodifierwarning comsquareupjavawriterjavawriter cannot find referenced class javaxlangmodelelementmodifierwarning comsquareupjavawriterjavawriter cannot find referenced class javaxlangmodelelementmodifierwarning orgassertjcoreinternaljavabeandescriptor cannot find referenced class javabeanspropertydescriptorwarning orgassertjcoreinternaljavabeandescriptor cannot find referenced class javabeanspropertydescriptorwarning orgassertjcoreinternaljavabeandescriptor cannot find referenced class javabeanspropertydescriptorwarning orgassertjcoreinternaljavabeandescriptor cannot find referenced class javabeanspropertydescriptorwarning orgassertjcoreinternalpropertysupport cannot find referenced class javabeanspropertydescriptorwarning orgassertjcoreinternalpropertysupport cannot find referenced class javabeanspropertydescriptorwarning orgassertjcoreinternalcglibcoredebuggingclasswriter1 cannot find referenced class orgassertjcoreinternalcglibasmutiltraceclassvisitorwarning orgassertjcoreinternalcglibcoredebuggingclasswriter1 cannot find referenced class orgassertjcoreinternalcglibasmutiltraceclassvisitorwarning orgassertjcoreinternalcglibcoredebuggingclasswriter1 cannot find referenced class orgassertjcoreinternalcglibasmutiltraceclassvisitorwarning orgassertjcoreinternalcglibcorereflectutils cannot find referenced class javabeanspropertydescriptorwarning orgassertjcoreinternalcglibcorereflectutils cannot find referenced class javabeanspropertydescriptorwarning orgassertjcoreinternalcglibcorereflectutils cannot find referenced class javabeanspropertydescriptorwarning orgassertjcoreinternalcglibcorereflectutils cannot find referenced class javabeansintrospectionexceptionwarning orgassertjcoreinternalcglibcorereflectutils cannot find referenced class javabeansintrospectorwarning orgassertjcoreinternalcglibcorereflectutils cannot find referenced class javabeansintrospectorwarning orgassertjcoreinternalcglibcorereflectutils cannot find referenced class javabeansbeaninfowarning orgassertjcoreinternalcglibcorereflectutils cannot find referenced class javabeansbeaninfowarning orgassertjcoreinternalcglibcorereflectutils cannot find referenced class javabeanspropertydescriptorwarning orgassertjcoreinternalcglibcorereflectutils cannot find referenced class javabeanspropertydescriptorwarning orgassertjcoreinternalcglibcorereflectutils cannot find referenced class javabeanspropertydescriptorwarning orgassertjcoreinternalcglibcorereflectutils cannot find referenced class javabeanspropertydescriptorwarning orgassertjcoreinternalcglibcorereflectutils cannot find referenced class javabeanspropertydescriptorwarning orgassertjcoreinternalcglibcorereflectutils cannot find referenced class javabeanspropertydescriptorwarning orgassertjcoreinternalcglibcorereflectutils cannot find referenced class javabeanspropertydescriptorwarning orgassertjcoreinternalcglibcorereflectutils cannot find referenced class javabeanspropertydescriptorwarning orgassertjcoreinternalcglibcorereflectutils cannot find referenced class javabeanspropertydescriptorwarning orgassertjcoreinternalcglibcorereflectutils cannot find referenced class javabeansbeaninfowarning orgassertjcoreinternalcglibcorereflectutils cannot find referenced class javabeanspropertydescriptorwarning orgassertjcoreinternalcglibcorereflectutils cannot find referenced class javabeansintrospectionexceptionwarning orgassertjcoreutilintrospectionintrospection cannot find referenced class javabeansintrospectorwarning orgassertjcoreutilintrospectionintrospection cannot find referenced class javabeansintrospectorwarning orgassertjcoreutilintrospectionintrospection cannot find referenced class javabeansbeaninfowarning orgassertjcoreutilintrospectionintrospection cannot find referenced class javabeansbeaninfowarning orgassertjcoreutilintrospectionintrospection cannot find referenced class javabeanspropertydescriptorwarning orgassertjcoreutilintrospectionintrospection cannot find referenced class javabeanspropertydescriptorwarning orgassertjcoreutilintrospectionintrospection cannot find referenced class javabeanspropertydescriptorwarning orgassertjcoreutilintrospectionintrospection cannot find referenced class javabeanspropertydescriptorwarning orgassertjcoreutilintrospectionintrospection cannot find referenced class javabeanspropertydescriptorwarning orgassertjcoreutilintrospectionintrospection cannot find referenced class javabeanspropertydescriptorwarning orgassertjcoreutilintrospectionintrospection cannot find referenced class javabeansbeaninfowarning orgassertjcoreutilxmlxmlstringprettyformatter cannot find referenced class orgw3cdombootstrapdomimplementationregistrywarning orgassertjcoreutilxmlxmlstringprettyformatter cannot find referenced class orgw3cdombootstrapdomimplementationregistrywarning orgassertjcoreutilxmlxmlstringprettyformatter cannot find referenced class orgw3cdombootstrapdomimplementationregistrywarning orgassertjcoreutilxmlxmlstringprettyformatter cannot find referenced class orgw3cdombootstrapdomimplementationregistrywarning orghamcrestjmock1matchers cannot find referenced class orgjmockcoreconstraintwarning orghamcrestbeanshaspropertywithvalue cannot find referenced class javabeanspropertydescriptorwarning orghamcrestbeanshaspropertywithvalue cannot find referenced class javabeanspropertydescriptorwarning orghamcrestbeanshaspropertywithvalue cannot find referenced class javabeanspropertydescriptorwarning orghamcrestbeanshaspropertywithvalue cannot find referenced class javabeanspropertydescriptorwarning orghamcrestbeanshaspropertywithvalue2 cannot find referenced class javabeanspropertydescriptorwarning orghamcrestbeanshaspropertywithvalue2 cannot find referenced class javabeanspropertydescriptorwarning orghamcrestbeanshaspropertywithvalue2 cannot find referenced class javabeanspropertydescriptorwarning orghamcrestbeanshaspropertywithvalue2 cannot find referenced class javabeanspropertydescriptorwarning orghamcrestbeanshaspropertywithvalue2 cannot find referenced class javabeanspropertydescriptorwarning orghamcrestbeanshaspropertywithvalue2 cannot find referenced class javabeanspropertydescriptorwarning orghamcrestbeanshaspropertywithvalue2 cannot find referenced class javabeanspropertydescriptorwarning orghamcrestbeanspropertyutil cannot find referenced class javabeanspropertydescriptorwarning orghamcrestbeanspropertyutil cannot find referenced class javabeansintrospectorwarning orghamcrestbeanspropertyutil cannot find referenced class javabeansbeaninfowarning orghamcrestbeanspropertyutil cannot find referenced class javabeansintrospectionexceptionwarning orghamcrestbeanspropertyutil cannot find referenced class javabeanspropertydescriptorwarning orghamcrestbeanspropertyutil cannot find referenced class javabeansintrospectorwarning orghamcrestbeanspropertyutil cannot find referenced class javabeansbeaninfowarning orghamcrestbeanspropertyutil cannot find referenced class javabeanspropertydescriptorwarning orghamcrestbeanspropertyutil cannot find referenced class javabeanspropertydescriptorwarning orghamcrestbeanspropertyutil cannot find referenced class javabeanspropertydescriptorwarning orghamcrestbeanspropertyutil cannot find referenced class javabeanspropertydescriptorwarning orghamcrestbeanspropertyutil cannot find referenced class javabeansintrospectionexceptionwarning orghamcrestbeanspropertyutil cannot find referenced class javabeanspropertydescriptorwarning orghamcrestbeanssamepropertyvaluesas cannot find referenced class javabeanspropertydescriptorwarning orghamcrestbeanssamepropertyvaluesas cannot find referenced class javabeanspropertydescriptorwarning orghamcrestbeanssamepropertyvaluesas cannot find referenced class javabeanspropertydescriptorwarning orghamcrestbeanssamepropertyvaluesas cannot find referenced class javabeanspropertydescriptorwarning orghamcrestbeanssamepropertyvaluesas cannot find referenced class javabeanspropertydescriptorwarning orghamcrestbeanssamepropertyvaluesas cannot find referenced class javabeanspropertydescriptorwarning orghamcrestbeanssamepropertyvaluesas cannot find referenced class javabeanspropertydescriptorwarning orghamcrestbeanssamepropertyvaluesas cannot find referenced class javabeanspropertydescriptorwarning orghamcrestbeanssamepropertyvaluesas cannot find referenced class javabeanspropertydescriptorwarning orghamcrestbeanssamepropertyvaluesas cannot find referenced class javabeanspropertydescriptorwarning orghamcrestbeanssamepropertyvaluesas cannot find referenced class javabeanspropertydescriptorwarning orghamcrestbeanssamepropertyvaluesas cannot find referenced class javabeanspropertydescriptorwarning orghamcrestbeanssamepropertyvaluesas cannot find referenced class javabeanspropertydescriptorwarning orghamcrestbeanssamepropertyvaluesaspropertymatcher cannot find referenced class javabeanspropertydescriptorwarning orghamcrestbeanssamepropertyvaluesaspropertymatcher cannot find referenced class javabeanspropertydescriptorwarning orghamcrestbeanssamepropertyvaluesaspropertymatcher cannot find referenced class javabeanspropertydescriptorwarning orghamcrestbeanssamepropertyvaluesaspropertymatcher cannot find referenced class javabeanspropertydescriptorwarning orghamcrestbeanssamepropertyvaluesaspropertymatcher cannot find referenced class javabeanspropertydescriptorwarning orghamcrestintegrationeasymock2adapter cannot find referenced class orgeasymockeasymockwarning orghamcrestintegrationeasymock2adapter cannot find referenced class orgeasymockiargumentmatcherwarning orghamcrestintegrationeasymock2adapter cannot find referenced class orgeasymockeasymockwarning orghamcrestintegrationeasymock2adapter cannot find referenced class orgeasymockiargumentmatcherwarning orghamcrestintegrationeasymock2adapter cannot find referenced class orgeasymockiargumentmatcherwarning orghamcrestintegrationjmock1adapter cannot find referenced class orgjmockcoreconstraintwarning orghamcrestintegrationjmock1adapter cannot find referenced class orgjmockcoreconstraintwarning orghamcrestintegrationjmock1adapter cannot find referenced class orgjmockcoreconstraintwarning orgjunitinternalrunnersstatementsfailontimeout cannot find referenced class javalangmanagementmanagementfactorywarning orgjunitinternalrunnersstatementsfailontimeout cannot find referenced class javalangmanagementthreadmxbeanwarning orgjunitinternalrunnersstatementsfailontimeout cannot find referenced class javalangmanagementthreadmxbeanwarning orgjunitinternalrunnersstatementsfailontimeout cannot find referenced class javalangmanagementmanagementfactorywarning orgjunitinternalrunnersstatementsfailontimeout cannot find referenced class javalangmanagementthreadmxbeanwarning orgjunitinternalrunnersstatementsfailontimeout cannot find referenced class javalangmanagementthreadmxbeanwarning orgjunitrulesthisableondebug cannot find referenced class javalangmanagementmanagementfactorywarning orgjunitrulesthisableondebug cannot find referenced class javalangmanagementruntimemxbeanwarning orgjunitrulesthisableondebug cannot find referenced class javalangmanagementmanagementfactorywarning orgjunitrulesthisableondebug cannot find referenced class javalangmanagementruntimemxbeanwarning orgobjenesisinstantiatorsunsunreflectionfactoryinstantiator cannot find referenced class sunreflectreflectionfactorywarning orgobjenesisinstantiatorsunsunreflectionfactoryinstantiator cannot find referenced class sunreflectreflectionfactorywarning orgobjenesisinstantiatorsunsunreflectionfactoryinstantiator cannot find referenced class sunreflectreflectionfactorywarning orgobjenesisinstantiatorsunsunreflectionfactoryinstantiator cannot find referenced class sunreflectreflectionfactorywarning orgobjenesisinstantiatorsunsunreflectionfactoryserializationinstantiator cannot find referenced class sunreflectreflectionfactorywarning orgobjenesisinstantiatorsunsunreflectionfactoryserializationinstantiator cannot find referenced class sunreflectreflectionfactorywarning orgobjenesisinstantiatorsunsunreflectionfactoryserializationinstantiator cannot find referenced class sunreflectreflectionfactorywarning orgobjenesisinstantiatorsunsunreflectionfactoryserializationinstantiator cannot find referenced class sunreflectreflectionfactoryideally i want to thisable proguarding the testcode but proguarding the appapk is important to me as this tests the proguardconfigresult,['android'] +1086630,included files all or nothing i have been writing code for a while but i am not classically trained in computer science so if this question is ridiculous please go easy on mesomething i have been trying to find a definitive answer on for a while is if i include a file in c do i get the entire contents of the file linked in or just the parts i use if it has 10 functions in it and i only use 1 of the functions does the code for the other 9 functions get included in my executable this is especially relevant for me right now as i am working on a microcontroller and memory is preciousthanks for any help with this question,['c'] +1086631,adding settings class to a uwp app i am developing a universal windows platform app but there is no settings template in visual studiohow can i implement an easy strongly typed and observable class that stores my settings in localsettings or roamingsettings,['c#'] +1086689,gmail api configuration issue in java here is my gmail service configurationfactory classimport javaiofileimport javaioioexceptionimport javasecuritygeneralsecurityexceptionimport orgspringframeworkbeansfactoryannotationautowiredimport orgspringframeworkcoreenvenvironmentimport comgoogleapiclientauthoauth2credentialimport comgoogleapiclientgoogleapisauthoauth2googlecredentialimport comgoogleapiclientgoogleapisjavanetgooglenethttptransportimport comgoogleapiclienthttphttprequestinitializerimport comgoogleapiclienthttpjavanetnethttptransportimport comgoogleapiclientjsonjackson2jacksonfactoryimport comgoogleapiservicesgmailgmailimport comgoogleapiservicesgmailgmailscopespublic class gmailservicefactorybean private autowired environment env private final nethttptransport transport private final jacksonfactory jacksonfactory public gmailservicefactorybean throws generalsecurityexception ioexception thistransport googlenethttptransportnewtrustedtransport thisjacksonfactory jacksonfactorygetdefaultinstance public gmail getgmailservice throws ioexception generalsecurityexception return new gmailbuildertransport jacksonfactory getcredential setapplicationnameenvgetpropertygmailapiapplicationnamebuild private httprequestinitializer getcredential throws ioexception generalsecurityexception file p12file new filethisgetclassgetclassloadergetresourcegooglekeyp12getfile credential credential new googlecredentialbuilder setserviceaccountidenvgetpropertygmailapiserviceaccountemail setserviceaccountprivatekeyidenvgetpropertygmailapiprivatekeyid setserviceaccountprivatekeyfromp12filep12file settransporttransport setjsonfactoryjacksonfactory setserviceaccountscopesgmailscopesall setserviceaccountuserenvgetpropertygmailapiuseremail build credentialrefreshtoken return credential here is my inner mailing service that uses previous bean under the hoodimport javaiobytearrayoutputstreamimport javaioioexceptionimport javasecuritygeneralsecurityexceptionimport javautillistimport javautilpropertiesimport javaxmailmessagingexceptionimport javaxmailsessionimport javaxmailinternetinternetaddressimport javaxmailinternetmimemessageimport javaxmailinternetmimemessagerecipienttypeimport orgspringframeworkbeansfactoryannotationautowiredimport orgspringframeworkcoreenvenvironmentimport orgspringframeworkstereotypeserviceimport comgoogleapiclientrepackagedorgapachecommonscodecbinarybase64import comgoogleapiservicesgmailgmailimport comgoogleapiservicesgmailmodelmessageimport comexamplefactorygmailservicefactorybeanimport comexampleservicemailserviceimport comexampleserviceexceptionmailserviceexceptionservicepublic class mailserviceimpl implements mailservice private autowired gmailservicefactorybean gmailservicefactorybean private autowired environment env override public void sendcomexamplemodelmessage message string recipient throws mailserviceexception try gmail gmailservice gmailservicefactorybeangetgmailservice mimemessage mimemessage createmimemessagemessage recipient message gmessage createmessagewithemailmimemessage gmailserviceusersmessagessendme gmessageexecute catchmessagingexception ioexception generalsecurityexception e throw new mailserviceexceptionegetmessage egetcause override public void sendcomexamplemodelmessage message liststring recipients throws mailserviceexception for string recipient recipients sendmessage recipient private mimemessage createmimemessagecomexamplemodelmessage message string recipient throws messagingexception session session sessiongetdefaultinstancenew properties mimemessage email new mimemessagesession internetaddress toaddress new internetaddressrecipient internetaddress fromaddress new internetaddressenvgetpropertygmailapiserviceaccountemail emailsetfromfromaddress emailaddrecipientrecipienttypeto toaddress emailsetsubjectmessagegettitle emailsettextmessagegetcontent envgetpropertyapplicationencoding return email private message createmessagewithemailmimemessage email throws messagingexception ioexception bytearrayoutputstream baos new bytearrayoutputstream emailwritetobaos return new messagesetrawbase64encodebase64urlsafestringbaostobytearray when i execute method sendmessage message string recipient of class mailserviceimpl i get following response400 bad request code 400 errors domain global message bad request reason failedprecondition message bad requestdoes anyone know whats wrong,['java'] +1086700,how to see macro expansions stepbystep it seems eclipse allows user to see the expansion stepbystep by pressing f2i like this awesome feature but can i do the same thing with just gcc or clang or any toole option makes all macros fully expanded so i have not found any alternative way to expand macros stepbystepeclipse is big i hope i do not need to install it everywhere and have it launched all the time,"['c++', 'c']" +1086916,how to bound the class type of the subclass i have this classpublic abstract class addressable abstract t extends this addressable void hardequalst tthe method hardequalst t is not bounded as i want what i want is bound t to be same class of this in other words when i extend the class addressable with the concrete class myaddressable i want that the method hardequals has the signaturevoid hardequalsmyaddressable tfor completenesspublic class myaddressable extends addressable void hardequalsmyaddressable tis it possible to achieve what i wantif the answer is no is it so stupid my class constraint,['java'] +1087010,symfony authentication with an api token request token user is null for the record i am using php 700 in a vagrant box with phpstorm oh and symfony 3i am following the api key authentication documentation my goal is to allow the user to provide a key as a get apikey parameter to authenticate for any route except the developer profiler etc obviouslyto allow the developer to write requestgetuser in a controller to get the currently logged in usermy problem is that although i believe i have followed the documentation to the letter i am still getting a null for requestgetuser in the controllernote i have removed error checking to keep the code shortapikeyauthenticatorphpthe thing that processes the part of the request to grab the api key from it it can be a header or anything but i am sticking with apikey from getdifferences from documentation pretty much 0 apart from that i am trying to keep the user authenticated in the session following this part of the docsclass apikeyauthenticator implements simplepreauthenticatorinterface public function createtokenrequest request providerkey apikey requestquerygetapikey return new preauthenticatedtoken anon apikey providerkey public function authenticatetokentokeninterface token userproviderinterface userprovider providerkey apikey tokengetcredentials username userprovidergetusernameforapikeyapikey the part where we try and keep the user in the session user tokengetuser if user instanceof apikeyuser return new preauthenticatedtoken user apikey providerkey usergetroles user userproviderloaduserbyusernameusername return new preauthenticatedtoken user apikey providerkey usergetroles public function supportstokentokeninterface token providerkey return token instanceof preauthenticatedtoken tokengetproviderkey providerkey apikeyuserproviderphpthe custom user provider to load a user object from wherever it can be loaded from i am sticking with the default db implementationdifferences only the fact that i have to inject the repository into the constructor to make calls to the db as the docs allude to but do not show and also returning user in refreshuserclass apikeyuserprovider implements userproviderinterface protected repo i am injecting the repo here docs do not help with this public function constructuserrepository repo thisrepo repo public function getusernameforapikeyapikey data thisrepofindusernamebyapikeyapikey username is nulldata datagetusername null return username public function loaduserbyusernameusername return thisrepofindonebyusername username public function refreshuseruserinterface user docs state to return here if we do not want stateless return user public function supportsclassclass return symfonycomponentsecuritycoreuseruser class apikeyuserphpthis is my custom user objectthe only difference i have here is that it contains doctrine annotations removed for your sanity and a custom field for the token also i removed serializable as it did not seem to be doing anything and apparently symfony only needs the id value to recreate the user which it can do itselfclass apikeyuser implements userinterface private id private username private password private email private salt private apikey private isactive public function constructusername password salt apikey isactive true thisusername username thispassword password thissalt salt thisapikey apikey thisisactive isactive snip getters securityyml here is my custom user provider class from aboveproviders api key user provider id api key user providerfirewalls authentication thisabled for dev default settings dev pattern profilerwdtcssimagesjs security false my new settings with stateless set to false secured area pattern stateless false simple preauth authenticator apikey authenticator provider api key user providerservicesymlobviously i need to be able to inject the repository into the providerapi key user repository class doctrineormentityrepository factory doctrineormentity manager getrepository arguments appbundlesecurityapikeyuserapi key user provider class appbundlesecurityapikeyuserprovider factory service doctrineormdefault entity manager factory method getrepository arguments api key user repositoryapikey authenticator class appbundlesecurityapikeyauthenticator public falsedebugging it is interesting to note that in apikeyauthenticatorphp the call to user tokengetuser in authenticatetoken always shows an anon user so it is clearly not being stored in the sessionalso note how at the bottom of the authenticator we do actually return a new preauthenticatedtoken with a user found from the databaseso it is clearly found me and is returning what it is supposed to here but the user call in the controller returns null what am i doing wrong is it a failure to serialise into the session because of my custom user or something i tried setting all the user properties to public as somewhere in the documentation suggested but that made no difference,['php'] +1087062,retrofit androidosnetworkonmainthreadexception i am using retrofit 2 to get json and parse it to pojo my purpose is getting one value of that objectcompile comsquareupretrofit2retrofit200beta4compile comsquareupretrofit2convertergson200beta4my rest clientpublic interface myclient getpart1part2 callmyitem getmyitemqueryparam1 string param1 queryparam2 string param2 queryparam3 string param3here i found great great tool to create servicepublic class servicegenerator public static final string api base url private static okhttpclientbuilder httpclient new okhttpclientbuilder private static retrofitbuilder builder new retrofitbuilder baseurlapi base url addconverterfactorygsonconverterfactorycreate public static s s createserviceclas serviceclass retrofit retrofit builderclienthttpclientbuildbuild return retrofitcreateserviceclass then i am creating new service using service generator classmyclient api servicegeneratorcreateservicemyclientclass callmyitem call apigetmyitemparam1 param2 param3 myitem myitem null try myitem callexecutebody logdmytag myitemgetvalue catch ioexception e eprintstacktrace when i am trying to run this code i am getting this errorandroidosnetworkonmainthreadexception at androidosstrictmodeandroidblockguardpolicyonnetworkstrictmodejava1147 at javanetinetaddresslookuphostbynameinetaddressjava418 at javanetinetaddressgetallbynameimplinetaddressjava252 at javanetinetaddressgetallbynameinetaddressjava215 at okhttp3dns1lookupdnsjava39 at okhttp3internalhttprouteselectorresetnextinetsocketaddressrouteselectorjava173 at okhttp3internalhttprouteselectornextproxyrouteselectorjava139 at okhttp3internalhttprouteselectornextrouteselectorjava81 at okhttp3internalhttpstreamallocationfindconnectionstreamallocationjava174 at okhttp3internalhttpstreamallocationfindhealthyconnectionstreamallocationjava127 at okhttp3internalhttpstreamallocationnewstreamstreamallocationjava97 at okhttp3internalhttphttpengineconnecthttpenginejava289 at okhttp3internalhttphttpenginesendrequesthttpenginejava241 at okhttp3realcallgetresponserealcalljava240 at okhttp3realcallapplicationinterceptorchainproceedrealcalljava198 at okhttp3realcallgetresponsewithinterceptorchainrealcalljava160 at okhttp3realcallexecuterealcalljava57 at retrofit2okhttpcallexecuteokhttpcalljava177 at retrofit2executorcalladapterfactoryexecutorcallbackcallexecuteexecutorcalladapterfactoryjava87 at uzcpoxdatamyrepositorygetmyitemmyrepositoryjava31 at uzcpoxpresentersmypresenterdomypresenterjava30 at uzcpoxactivitiesmyactivityonclickmyactivityjava52 at androidviewviewperformclickviewjava4756 at androidviewviewperformclickrunviewjava19749 at androidoshandlerhandlecallbackhandlerjava739 at androidoshandlerthispatchmessagehandlerjava95 at androidoslooperlooplooperjava135 at androidappactivitythreadmainactivitythreadjava5221 at javalangreflectmethodinvokenative method at javalangreflectmethodinvokemethodjava372 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava899 at comandroidinternaloszygoteinitmainzygoteinitjava694i thought that retrofit automatically does the job in the background thread or i misunderstood something what is wrong in this situation and how to solve it,"['java', 'android']" +1087138,loop multidimensional array to generate multidimensional array for google charts i am currently trying to generate a report using google chartsi am pulling information from a mysql db in my nodejs server side code and using socketio to pass it to the client side in a multidimensional array which looks like the following answered 477 728 busy 477 48 no answer 477 277 answered 478 88 busy 478 24 no answer 478 56 so i am currently looping through that array and trying to pull out the values so it is in the following format for google charts 477 728 48 277 478 24 56i cannot get it into this format and am struggling to find ways to do so so then i can then insert this information into my multidimensional array for google tables and generate a reportthe current code i have so far issocketonsql function valuearr googlechartsloadcurrent packages corechart googlechartssetonloadcallbackdrawmaterial function drawmaterial var data var header call thisposition answered datapushheader for i in valuearr var index 0 var foundindex false var agent valuearri1 var callcount valuearri2 for var i in data var dataelem datai if dataelem0 agent index i foundindex true dataindexi callcount if foundindex false var chanar new arrayagent datapushchanar consolelogdata var options title call thisposition haxis title agents minvalue 0 vaxis title thisposition number isstacked true var chartdata new googlevisualizationarraytodatatabledata var material new googlevisualizationcolumnchartdocumentgetelementbyidchart materialdrawchartdata options which outputs the following multidimensional array call thisposition answered477277 the idea is i need the multidimensional data array to eventually look likenote header can be changed in code its just due to the current amount of values am working with to build it upcall thisposition answeredbusyfailed477 728 48 277 478 24 56,"['javascript', 'mysql']" +1087386,when interface a defines interface b in its method signature how can i restrict an implementation of a to use a certain implementation of b in the method signatureuse casehere is a unit interface and two enums that implement itpublic interface unit public enum forceunit implements unit public enum massunit implements unit which is used by the property interfacepublic interface property public void setunit unit unit for examplepublic class force implements property public class mass implements property here i want to be able to enforce thatforce uses only forceunit in the setunit signaturemass uses only massunit in the setunit signaturewhen i try to do this eclipse complainsthe type mass must implement the inherited abstract method propertysetunitunitand promptly suggests two quick fixesmake the class abstract which is not an option since i want to be able to do stuff like mass mass new massadd the unimplemented methods with an override annotation i do not know if this is the right fix but to me this smacks of clumsinessquestionswhat options do i have to achieve what i want would the use of generics help herewhy does marking the class as abstract resolve the issue,['java'] +1087469,how to use hashset to find common elements in two comparable arrays edit the method signature public comparable findcommonelementscomparable collectionsis wrong it should be public comparable findcommonelementscomparable collectionsbut changing it in my ide messes everything up i almost feel like i have gone beyond my knowledge because i do not fully understand sets and the 2d array is messing me up badly i am required to write an algorithm that takes two comparable arrays iterates through them with linear time efficiency and thisplays the common elements i have read that using a hashset would give me the fastest time efficiency but i have reached an impasse heres why we were given the instructions and one single line of code which is the method signaturepublic comparable findcommonelementscomparable collectionswhich means i have to return the 2d array collections i emailed my prof on using hashsets and i was given the goahead except i have this problemyou can use hashsets inside your findcommonelements method but you will need to be able to count the number of comparisons performed although hashing is usually very efficient some comparisons will be made in the event of collisions to do this you would need to have access to the source code for the hashset you use you also need a getcomparisons method in your commonelements class to return the number of comparisons in two semesters of programming i did not learn hashsets maps tables etc i am trying to learn this myself and i do not fully understand collisions my code does take the two arrays and return the common elements but my return statement is screwy since i basically wrote it so it would compile the 2d comparable array is the parameter am i on the right path with this here is the code public class commonelements static comparable collection1 a b c d e first array static comparable collection2 a b c d e f g second array static comparable collections collection1 collection2 array to store common elements static setcomparable commonstuff new hashset instance of set containing common elements public static void mainstring args commonelements commonelements new commonelements create instance of class commonelements commonelementsfindcommonelementscollections call the find method public comparable findcommonelementscomparable collections setcomparable addset new hashset instance of set to add elements to for comparable x collection1 adding elements from first array to my addset addsetaddx for comparable x collection2 if addsetcontainsx commonstuffaddx checking for common elements add to commonstuff set systemoutprintlntostringcommonstuff print the tostring method return collections return statement otherwise java will whine at me public string tostringsetcomparable commonstuff this method gets rid of the brackets string elements commonstufftostring make a string and assign it to the set elements elementsreplaceall replaceall replace both brackets with empty space return common elements elements return the set as a new string,['java'] +1087493,is there a simple crud example app using reactjs and firebase after what felt like almost 8 years of rails development about a year ago i decided to start working with meteorjs and as of the last month have begun working with reactjs i have been through the react for beginners course which i really liked and learned a lot from and by way of the course am really interested in firebase i believe i am understanding the nature of syncing and using rebase procs and states however in searching around for sample apps i just cannot seem to find a basic crud app it seems like there should be a simple example for something like this but i cannot seem to find one in the case of a sample blog app i am looking for a barebones app that creates reads updates and deletes data from a collection pagination and authentication would be icing on the cakei have started coding a prototype as in the case of the 2 gists below appjs is the container and annoucementslistjs holds announcements just wondering if there are any other examples and if the app has to do crud this wayif anyone can share something youve built or links to a source i would appreciate it much,['javascript'] +1087496,javascript array to object i have an array that looks like sofiles dashboardlogserrors dashboardlogsother accountsmaini want to make it look like thisnavigation title dashboard dropdown title logs dropdown title errors title other title accounts dropdown title main i have the following so farvar navigation for var i 0 i fileslength i var parts filesisplit navigationpushtitle parts0 for var j 1 j partslength j i am having difficulties figuring out a decent way to do this what i have so far already does not work because it creates two objects under navigation each with title dashboard any ideas for a clever approach thanks,['javascript'] +1087867,should i use stdset or stdunordered set for a set of pointers i have a set of pointers in the first step i insert data pointers and in the second step i iterate over the whole set and do something with the elements the order is not important i just need to avoid duplicates which works fine with pointer comparisonmy question is whether it might be advantageous to use an unordered set for the same purpose is insertion faster for an unordered set,['c++'] +1087940,as far as i can tell none of these answers are correct what am i missing in compiling some interview test questions i am currently taking examples from various sources and running through them to gauge their difficulty level and correctness i have come across one that i think is broken but it is also possible i am missing something if i am i want to know not only for my own knowledge but then it would also indicate that this is potentially a good tricky question i would like you to help me regain my sanity and reaffirm the trust i have placed in myself dwhat is the correct way to cast p at the placeholder in the following codeinclude iostreamusing namespace stduint16 t hashvoid p uint32 t val return uint16 tval val 16int mainint argc char argv uint32 t a20 foruint32 t i 0 i 20 i ai i cout hasha i endl choose onestatic castuint32 tpdynamic castuint32 tpreinterpret castuint32 tpconst castuint32 tpignoring for a moment that the call to hash must be hash to guarantee thisambiguity with the standard library eg this line does not compile for me in gcc 530 c14 mode i have a problem with the questionfirstly it is not clear what the programs supposed to do hash the array values or hash the element locations because at the moment the function is receiving pointerstoelements but all the available answers assume that those pointers are to be themselves converted to uint32 t and used as the hash value if that is the case then even if you use a reinterpret cast then there is a bug because sizeofvoid may not be sizeofuint32 t val in that function should be intptr t instead the use of uint32 t for the type of the array elements themselves just confuses matters further if that is effectively a coincidenceor the function is supposed to hash the value and the correct answer is not in the list static castuint32 tpthe correct answer is apparently reinterpret castuint32 tp which makes me think the intention of the program is to hash the array element addressesam i imagining these problemsis the question clear and is the solution one of the four choices offered,['c++'] +1087965,how to thisable one transformer validation error dynamically in symfony2 i have a form with many fields and validation groups these fields contains some view data transformers tooi need suppress the validation form partially groups based on the submitted datause appbundleentityclientuse symfonycomponentformforminterfaceuse symfonycomponentoptionsresolveroptionsresolver public function configureoptionsoptionsresolver resolver resolversetdefaultsarray validation groups function forminterface form data formgetdata if clienttype person datagettype return arrayperson return arraycompany when you do that the form will still run basic integrity checks thisabling validation and validation errors coming from transformers they are thrown still creating the transformeruse the post submit event and prevent the validationlistener from being called suppressing form validationuse symfonycomponentformformbuilderinterfaceuse symfonycomponentformformeventsuse symfonycomponentformformeventpublic function buildformformbuilderinterface builder array options builderaddeventlistenerformeventspost submit function formevent event eventstoppropagation 900 always set a higher priority than validationlistener it is not a solution for me since accidentally thisable something more than just form validationthe question is how to thisable one transformer validation error dynamicallyexamplei have a form field of repeatedtype belonging to person validation group and contains a view transformer repeatedtype this transformer throws an exception when the values in the array they are not the same valuetoduplicatestransformer so even when validation group is company the form show errors belonging to repeatedtype field coming from transformer itthe question here is how to thisable the valuetoduplicatestransformer errors when validation group is not person,['php'] +1088079,python merge list with range list i have a listl a bi need create new list by concatenate original list with range from 1 to k this wayk 4l1 a1b1 a2b2a3b3a4b4i tryl1 l kprint l1a b a b a b a bl x 2 for x in range1 k 1 print l1 1 2 2 3 3 4 4l2 item for sublist in l for item in sublistprint l21 1 2 2 3 3 4 4print zipl1l2a 1 b 1 a 2 b 2 a 3 b 3 a 4 b 4print x stry for xy in zipl1l2 a1 b1 a2 b2 a3 b3 a4 b4but i think it is very complicatedwhat is the fastest and more generic solution,['python'] +1088440,error handling for fetch in aurelia i have an api that includes a useful description of what went wrong when an error is raised by the server status 500 the description comes as part of the response text my client code using aurelia calls the api via aureliafetchclient using a generic method to make the callfunction callremoteserviceapiname timeout return promiserace thishttpfetchapiname thiswaitforservertimeout 50 throws after x ms thenresponse responsejson catcherr if err instanceof response heres the problem errtextthentext consolelogerror text from callremoteservice error handler text throw new errortext else if err instanceof error throw new errorerrmessage else throw new errorunknown error encountered from callremoteservice note that i want to catch the server fetch or timeout errors in a consistent way and then throw back just a simple error message to the calling view i can invoke callremoteservice successfully catching errors when a 500 is returned withcallremoteservicethisapiname thisapitimeout thendata consolelogsuccessfully called thisapiname result isn jsonstringifydata null 2 catcherr consolelogerror from thisapiname err however i am having trouble accessing the response text because the fetch provides the text method that returns a promise and that is interfering with my otherwise happy promise chaining the code above does not work leaving me with an uncaught in promise errorhopefully there is a good way to access that response text,['javascript'] +1088945,django m2mfields through widgets are there exists any examples of django widgets which can be useful for manytomanyfields with through attributes for example i have these models got the source from django documentation from djangodb import models class personmodelsmodel name modelscharfieldmax length128 def str self unicode on python 2 return selfname class groupmodelsmodel name modelscharfieldmax length128 members modelsmanytomanyfieldperson throughmembership def str self unicode on python 2 return selfname class membershipmodelsmodel person modelsforeignkeyperson on deletemodelscascade group modelsforeignkeygroup on deletemodelscascade date joined modelsdatefield invite reason modelscharfieldmax length64obvisously standart modelmultiplechoicefield would not work here i need to populate date joined and invite reason while adding which is the simpliest way to achieve this,['python'] +1089052,how is the google maps layout animated i am trying to understand what animation is used in the google maps application the part i am trying to understand is when you click on the textbox in the toolbar the layout animates to present a completely new screen with a few items sliding in from the bottom how is this done is it a bottom sheet becoming visible is it a new activity with shared element transitions,['android'] +1089176,how to keep submenu with images centered in bootstrap navpill friends i am facing responsive problem while arranging images in submenu centered i have a container of width 1280px for all screens as you can see in fiddle i have categories as menu then when we click on categories it opens a menu with images i want these menus to be centered on all screens and its border should cover the whole screenin simple words our categories should start exactly below of left side logo and all the images should be always centered on all screen now the submenu with images always shifts to left or right i want images in submenu to take container width always and fit in container for all desktop screens by leaving left and right margin and whole submenu should cover entire screen please have a look at this code demo for reference i am adding a screenshot please refer and see if you can help me with this thank you so much for giving your time this image shows what i am getting now problem imgthis is what i want exact img this is although have some less space at right but i need something like this all content should be fit in container width and leaving same space at left and right and background black that covers entire screen size i tried with marginleft but it fits only for the screen for which i set please help me in making this menu responsive any help suggestions are appreciated updated jsfiddlethank you 1,"['jquery', 'html', 'css']" +1089192,how to place a google plus 1 button inside cordovaionic app i have added a 1 button in my appi have used this code div classgplusone datasizetall datahrefgoogle play store link to my appdivandfunction var po documentcreateelementscript potype textjavascript poasync true posrc var s documentgetelementsbytagnamescript0 sparentnodeinsertbeforepo si have also allowed the apiindexhtml meta httpequivcontentsecuritypolicy contentdefaultsrc stylesrc self unsafeinline scriptsrc self unsafeinline unsafeeval configxmlallownavigation href the problemthis works on the browser ionic serve but it does not work on the appwhen i click nothing happens no errorsanyway i can make this work on the app ionic runmore informationdebug infoif i have clicked the 1 button on the web it does not show me the red button on the app read means i have already shared that linkit does not know who i ami do not want to make a loginsignup just a 1 buttonif i addallownavigation href in configxml it asks me to login when i click the 1 button it should notthis means the 1 button does not work because is in an anonymous browser not authenticated with the osi also created a demo pure android app following this instructions it works perfectly i can 1 the linkmy possibilitessome way to make a native android view with the 1 button appear on the webviewmake a fake 1 button and when it is clicked it calls a plugin that makes some king of requestclick on the real 1 buttonany suggestion on how to do itare any of these two possibilities possiblethanks for your help,['javascript'] +1089408,how to print this pattern i cannot get the logic for eliminating the middle part write a program that asks the user for an input n assume that the user enters a positive integer and prints only the boundaries of the triangle using asterisks of height nfor example if the user enters 6 then the height of the triangle should be 6 as shown below and there should be no spaces between the asterisks on the topline i cannot understand how to print the part between top and end of pattern this is my coden intinputenter a positive integer value for i in range n 0 1 print ithe for loop is for printing the reverse asterisks triangle obstacle is to print the middle part,['python'] +1089643,xmlhttprequest cannot load httpswebsitecom i have a grunt process which initiates an instance of expressjs server this was working absolutely fine up until just now when it started serving a blank page with the following appearing in the error log in the developers console in chrome latest versionxmlhttprequest cannot load httpswebsitecom no accesscontrolalloworigin header is present on the requested resource origin httplocalhost4300 is therefore not allowed accesswhat is stopping me from accessing the page,['javascript'] +1089682,swift 2 no delegate callbacks for push notifications as opposed to objectivec i have created 2 sample single view projects to test push notifications i did not add any code except for the notifications setup code as followingproject1 swift 2 func applicationapplication uiapplication didfinishlaunchingwithoptions launchoptions nsobject anyobject bool let settings uiusernotificationsettingsfortypes alert badge sound categories nil uiapplicationsharedapplicationregisterusernotificationsettingssettings uiapplicationsharedapplicationregisterforremotenotifications return truefunc applicationapplication uiapplication didregisterusernotificationsettings notificationsettings uiusernotificationsettings printdidregisterusernotificationsettings got calledfunc applicationapplication uiapplication didregisterforremotenotificationswithdevicetoken devicetoken nsdata let trimmeddevicetoken devicetokendescription stringbytrimmingcharactersinsetnscharactersetcharactersinstring stringbyreplacingoccurrencesofstring withstring printdevice token trimmeddevicetokenfunc applicationapplication uiapplication didfailtoregisterforremotenotificationswitherror error nserror printfailed to get token error errorproject2 objectivec boolapplicationuiapplication application didfinishlaunchingwithoptionsnsdictionary launchoptions uiusernotificationsettings notificationsettings uiusernotificationsettings settingsfortypesuiusernotificationtypesound uiusernotificationtypealertuiusernotificationtypebadge categoriesnilapplication registerusernotificationsettingsnotificationsettingsapplication registerforremotenotificationsreturn yes voidapplicationuiapplication application didregisterusernotificationsettingsuiusernotificationsettings notificationsettings nslogdidregisterusernotificationsettings got called voidapplicationuiapplicationapplication didregisterforremotenotificationswithdevicetokennsdatadevicetoken nsstring newtoken devicetoken descriptionnewtoken newtoken stringbytrimmingcharactersinsetnscharacterset charactersetwithcharactersinstringnewtoken newtoken stringbyreplacingoccurrencesofstring withstringnslogdevice token newtoken voidapplicationuiapplicationapplication didfailtoregisterforremotenotificationswitherrornserrorerror nslogfailed to get token error error the objectivec project works fine on all tested devices registers itself for remote notifications and receives a device token in the delegate callback method but the swift project couldnat get any of the delegate callbacksread what iave tried before marking this question as duplicate1 appid is push notification enabled2 push certificate type is production and provisioning profile is adhoc production3 both projects use the same appid push certificate and provisioning profile4 both projects have been tested on 3 different iphones 5 6 6plus all running ios 92 deleted the app with every install and restarted all of them many times5 built both projects with xcode 72 on 2 different mac pro machines6 all 3 iphones use internet connection without a firewall and all ports are open as stated in this technical note also changed the internet connection on the 3 devices to be a 3g connection instead of a wifi7 checkedunchecked push notifications in project settings capabilities for both projects by the way this point has no effect as i tested it8 tried xcode run the top button and export ipa package for both projects9 tried both application uiapplication sharedapplication for objectivec and uiapplicationsharedapplication for swift with the method registerforremotenotifications10 tried another brand new appid push certificate and provisioning profile for both projects11 deleted both projects and created another 2 new projects with the same code as above the objectivec project after all these tries works fine and receives a device token through didregisterforremotenotificationswithdevicetoken method but the swift one does not worki have generated 3 apn log files from the iphone 6plus device using persistentconnectionloggingmobileconfig profile by apple and uploaded them here inside apsd 2016 02 24 11 36 290300log file the objectivec project bundleid is xpushnotification and the swift project bundleid is xapnsswift,"['objective-c', 'iphone']" +1089745,sectaskdiagnoseentitlements missing keychain entitlements no stored taskref found in two applications which have watchkit app extensions i receive the following error in the device log more than ten times on startupsectaskdiagnoseentitlements missing keychain entitlements no stored taskref foundfolks over at the apple developer forums have also reported this thread herebut no one has found any solution anyone have any ideasthe app does start and run fine but i am concerned that these messages errors might be slowing launch and or indicating i cont have the project configured correctly,['ios'] +1089782,my function returns a list with a single integer in it how can i make it return only the integer how do i remove the brackets from the result while keeping the function a single line of codeday list sunday monday tuesday wednesday thursday friday saturdaydef day to numberinp return day for day in rangelenday list if day listday inpprint day to numbersundayprint day to numbermondayprint day to numbertuesdayprint day to numberwednesdayprint day to numberthursdayprint day to numberfridayprint day to numbersaturdayoutput0123456,['python'] +1089873,replace text inside sql with xml output i have this queryselect content id content html date created folder id from content ct where folder id126order by content title for xml pathpressrelease root pressreleaseswhen i run this query this is the xml file that is generatedpressreleases pressrelease content id6442452927content id content htmlltrootgtltdategt20151202ltdategt ltdescriptiongtltp classcustomheadergtjobs to philadelphialtpgt ltpgtmtext in hereltpgt ltpgtmtext in hereltpgt ltdescriptiongt ltseogtlth1gtpennsylvania locationlth1gt ltdiv classbulletrightbargt the move was made possible in part by the philadelphia jobs creditltdivgtltseogtltrootgtcontent html date created20151202t094712date created folder id126folder id pressrelease pressreleaseswhat i need is this xml filepressreleases pressrelease content id6442452927content id content htmlrootdate20151202date descriptionltp classcustomheadergtjobs to philadelphialtpgt ltpgtmtext in hereltpgt ltpgtmtext in hereltpgt description seolth1gtpennsylvania locationlth1gt ltdiv classbulletrightbargt the move was made possible in part by the philadelphia jobs creditltdivgtseorootcontent html date created20151202t094712date created folder id126folder id pressrelease pressreleasesinside the content html i want to make root date and description as xml elements but leave the rest as encoded htmlheres a screenshot for the sql result,['sql'] +1090328,why requireangular returns an empty object i have configured webpack like thisresolve alias angular pathjoin dirname node modulesangularangularjs and in my file i require angular like thisvar angular requireangularbut for some reason an empty object is returned why,['javascript'] +1090341,when is keyboardinterrupt raised in python all the docs tell us israised when the user hits the interrupt key normally controlc or delete during execution a check for interrupts is made regularlybut from the point of the code when can i see this exception does it occur during statement execution only between statements can it happen in the middle of an expressionfor examplefile openfoo can a keyboardinterrupt be raised here after the successful completion of open but prior to the try try try some things with file finally cleanupwill this code leak during a welltimed keyboardinterrupt or is it raised during the execution of some statements or expressions,['python'] +1090511,fix bottom bar in coordinatorlayout i have a coordinatorlayout which contains appbarlayout and a framelayout which contains fragmentsone of this fragment contains a tablayout at top one list trough recyclerview and at the bottom one homemade toolbarthe appbarlayout is configured with applayout scrollflagsscrollenteralways my problem is that both toolbars are hiding when scroll the appbarlayout and my homemade toolbar at the bottom this is the current behaviouri would like to fix the bottom homemade toolbar to keep visible but i cannot achieve itthis is the xml of the fragment layoutxml version10 encodingutf8linearlayout xmlnsandroid xmlnsapp androidlayout widthmatch parent androidlayout heightmatch parent androidorientationvertical androidsupportdesignwidgettablayout androidididtoolbarfilter androidlayout widthmatch parent androidbackgroundcolorazul asde apptabmodefixed apptabmaxwidth0dp androidelevation4dp apptabindicatorcolorcolorverde pastel androidlayout heightwrap content androidsupportv4widgetswiperefreshlayout xmlnsandroid androidididswipecontainer androidlayout widthmatch parent androidlayout height0dp androidlayout weight1 androidsupportv7widgetrecyclerview androidididlist androidlayout widthmatch parent androidlayout heightmatch parent androidsupportv4widgetswiperefreshlayout linearlayout androidididtoolbarselection androidlayout widthmatch parent androidlayout heightwrap content androidorientationhorizontal androidpaddingtop10dp androidpaddingbottom10dp androidbackgroundcolorazul asde androidelevation4dp androidvisibilityvisible imageview androidididdelete androidlayout width0dp androidlayout heightwrap content androidlayout weight1 androidsrcdrawableic delete white 24dp androidtintcolorgris desactivado imageview androidididselect androidlayout width0dp androidlayout heightwrap content androidlayout weight1 androidsrcdrawableic bookmark border white 24dp imageview androidididsend androidlayout width0dp androidlayout heightwrap content androidlayout weight1 androidsrcdrawableic send white 24dp androidtintcolorgris desactivado linearlayoutlinearlayoutedit1 this questions seems to be the same problem,['android'] +1090515,is there a lowlevel difference between intlargesmall or intsmalarge in java this question will probably require some compiler knowledge to answer i am currently working on a project where i will be creating an array that may be eitherint2verylargenumberor int verylargenumber2it makes no difference logically but i was thinking that the form and therefore size in memory may differ perhaps the question should be are the compilers clever enough to rearrange arrays to suit them,['java'] +1090898,mapbox gl js getboundsfitbounds i am using mapbox gl js v0142 and i have searched high and low through the documentation and very little is clear about this if you use the standard js api it is very clear to fit map to markers using an example they have provided however the setup when using the gl api is quite different the gl api has getbounds but because you do not have a named layer like the standard js api so i am struggling to work out how to use getbounds at alli have found this mapbox gl js api set bounds but surely cannot be the right answerthis is the bulk of my setup excluding json setup and other optionsmapboxglaccesstoken pkeyj1ijoicmljagdjiiwiysi6imnpa3lpcwizyjawnwz3bm0wmhjvowv5enyifql55syyn9mvjen8cm3q1xdwvar markers php echo programme json var map new mapboxglmap container map style mapboxstylesrichgccikyo5bse00nqb0lxebkfn2bm center 1470085 53381129 zoom 15maponstyleload function mapaddsourcemarkers type geojson data markers mapaddlayer id markers interactive true type symbol source markers layout iconimage venuemapiconblue iconsize 05 iconallowoverlap true mapscrollzoomthisablei have tried the followingalertmapgetbounds lnglatboundslnglat14855345239256508 5337642500812015 lnglat14546354760740883 5338583247227842var bounds 14855345239256508 533764250081201514546354760740883 5338583247227842mapfitboundsboundsso i know how to fitbounds but i am unsure how to get them mapgetbounds just seems to return the set centre position lnglatmarkers jsonvar markers typefeaturecollectionfeaturestypefeaturepropertiestitlesite galleryurlfreelanceartsheffield2016programmesitegallerysummaryduis arcu tortor suscipit eget imperdiet nec imperdiet iaculis ipsum donec id justo aenean tellus metus bibendum sed posuere ac mattis non nunc suspenthisse feugiat etiam rhoncusimagefreelanceartsheffield2016siteassetsfiles1032site galleryjpgmarkersymbolvenuemapiconbluecolourbluegeometrytypepointcoordinates146643953376842typefeaturepropertiestitlemoore street substationurlfreelanceartsheffield2016programmemoorestreetsubstationsummaryimagenullmarkersymbolvenuemapicongreencolourgreengeometrytypepointcoordinates147788153374798typefeaturepropertiestitles1 artspaceurlfreelanceartsheffield2016programmes1artspacesummaryimagenullmarkersymbolvenuemapiconredcolourredgeometrytypepointcoordinates145962053380562,['javascript'] +1090976,how to make skypefriendly links preview image tags sharing certain links on skype triggers the program to show preview with image from the page on a website i work on there are big images on certain pages but skype picks up the logo of the website instead i was unable to find what meta tags would make skype pick up the intended image and preview iti have a link relimage src href that works for facebooksharing preview imgpng is used instead of the logo of the website but does not work for skypeso how would you hint skype which image should be used for preview,['html'] +1091043,how to slice a stdvector based on elements in stdset is there a good way to slice a stdvector based on elements in a stdset in other words the elements in the stdset hold the indices that i want in the vector certainly i can accomplish this with the codeinclude setinclude vectorinclude iostreaminclude iteratortemplate typename tstdvector t slice stdvector t const x stdset unsigned int const i auto y stdvector t forauto const i i ypush backxi return yint main auto x stdvector double 12 23 34 45 56 auto i stdset unsigned int 0 3 4 auto y slicexi stdcopyybeginyendstdostream iterator double stdcoutnwhich correctly returns124556however this feels a little clumsy is there a better way,['c++'] +1091080,cast std function object back to functor struct in this scenariostruct holder stdfunctionvoid fstruct functor void operator int main holder functor is there a way to later cast f back to a functor type,['c++'] +1091771,how to add new value to a list without using append and then store the value in a newly created list i have been trying this a lot x 45 y xappend7 print ynoneprint x4 5 7how is this possiblewhen i trying storing the values in the new list y and the print it it results in none and it also changes the current list xis there any other way to do this in python,['python'] +1091867,numpy octuple precision floats and 128 bit ints why and how this is mostly a question out of curiosity i noticed that the numpy test suite contains tests for 128 bit integers and the numerictypes module refers to int128 float256 octuple precision and other types that do not seem to map to numpy dtypes on my machinemy machine is 64bit yet i can use quadruple 128bit floats but not really i suppose that if it is possible to emulate quadruple floats in software one can theoretically also emulate octuple floats and 128bit ints on the other hand until just now i had never heard of either 128bit ints or octuple precision floating point before why is there a reference to 128bit ints and 256bit floats in numpys numerictypes module if there are no corresponding dtypes and how can i use those,['python'] +1091893,why does stdlistreverse have on complexity why does the reverse function for the stdlist class in the c standard library have linear runtime i would think that for doublylinked lists the reverse function should have been o1 reversing a doublylinked list should just involve switching the head and the tail pointers,['c++'] +1091946,inline definition causes unresolved symbols in program so i have the following codeinclude stdiohdefine maxab a b a bint absint a if a 0 return a else return a1inline int avgint a int b return ab2int math maxint a int b return avgababsavgabbint mainint argc char argv return 0when i compile it gcc g testc o test i gettmpcczbhejuo in function math maxtestctext0x33 undefined reference to avgtestctext0x44 undefined reference to avgcollect2 error ld returned 1 exit statusi can fix this by removing the inline notation from avg but i do not know why i am getting undefined references if its inline i thought the compiler was supposed to take care of thatanyone care to explain adding more information for those who cannot reproduce i am usinggcc version gcc gcc 530 copyright c 2015 free softwarefoundation inc this is free software see the source for copyingconditions there is no warranty not even for merchantability orfitness for a particular purposecompiling this code with without linking generates the followingishaypeledarania test gcc c testc o testoishaypeledarania test readelf s testosymbol table symtab contains 13 entries num value size type bind vis ndx name 0 0 0 notype local default und 1 0 0 file local default abs testc 2 0 0 section local default 1 3 0 0 section local default 3 4 0 0 section local default 4 5 0 0 section local default 6 6 0 0 section local default 7 7 0 0 section local default 5 8 0 25 func global default 1 abs 9 019 43 func global default 1 max 10 044 69 func global default 1 math max 11 0 0 notype global default und avg 12 089 18 func global default 1 main which clearly shows avg as notype and und this is why the linker failed i have no idea why that happens i also examined the preprocessor output from gccishaypeledarania test gcc testc e 5 testcint absint a if a 0 return a else return a1int maxint a int b return ababsab2inline int avgint a int b return ab2int math maxint a int b int avg calc avgab int thistance from avg absavg calca int res avg calcthistance from avg return resint mainint argc char argv 44 testc return 0looks perfectly fine avg appears before the usage in math maxstdc version 2012 gnuc defined,['c'] +1092083,derive key with ecdiffiehellmanp256 i am working on a project to integrate with the new push api that exists in firefox and is being developed as a w3c standardpart of this is encrypting the data the server will receive a diffie hellman p256 curve generated in js using var key subscriptiongetkeyp256dhan example of this when converted to a net base64 is boaiqzo6ucazdlzkkhf1aljnpu8r2pfsz4bqznpv145dagnxvlqyu5q2tlalk2w31rpodhe8sipo0m2jix4wahowever i ran into issues generating the derived materialvar key1 convertfrombase64stringstringfromabovetolist you can criticize my tolist inefficiencies later net does not like the key without these prefixes see here i know the bytes do not match that post but that is because the key type is different between their example and minevar keytype new byte 0x45 0x43 0x4b 0x31 var keylength new byte 0x20 0x00 0x00 0x00 key1removeat0key1 keytypeconcatkeylengthconcatkey1tolistecdiffiehellmancng a new ecdiffiehellmancngakeyderivationfunction ecdiffiehellmankeyderivationfunctionhash if i set this as cngalgorithmsha256 it works but that is not what firefox gives meahashalgorithm cngalgorithmecdiffiehellmanp256 akeysize 256 it complains if i do not add this since keys are different lengths now time to actually import the keycngkey k cngkeyimportkey1toarray cngkeyblobformateccpublicblob works successfullybyte derivedmaterial aderivekeymaterialk exception heresystemsecuritycryptographycryptographicexception the requested operation is not supportedwhat do i not understand correctly or on the more sad side what is not implemented correctly or at all in windowsnetas an alternative if somebody could explain how to port this node js library to net that would work too i think that is a bit of a reach updatei needed to keep working through the rest of the problem and not be held up by the encryption so i used a nodejs wrapper to allow for further development on the net side the node code simply generates the local public key and the shared secret and returns those values to me i still need to get this working without the node wrapperbecause of this test i can confirm that the rest of the code not included here works so the issue definitely lies in the code above and my inability to generate the derived key material if the hashalgorithm is specified as cngalgorithmecdiffiehellmanp256,['c#'] +1092199,join multiple table using relations in yii2 i am trying to list some data through kartik gridview widget in yii2 by using relationsi have these tablesstaffscreate table if not exists staffs id int11 not null auto increment name varchar250 character set utf8 default null department id int11 default null designation id int11 default null username varchar50 character set utf8 default null emailid varchar250 character set utf8 default null staffrights tinyint2 default 0 staffstatus tinyint2 default 1 primary key id engineinnodb default charsetlatin1designationscreate table if not exists designations id int11 not null auto increment designname varchar150 not null designation group id varchar250 not null primary key id engineinnodb default charsetlatin1designation group create table if not exists designation group id int11 not null auto increment group name text not null primary key id engineinnodb default charsetlatin1designations table is related to designation group by designationsdesignation group id designations table will have one or more values seperated by comma of designation groupid designations table is related to staffs table by staffsdesignation id designationsidin staffs model i have added relations like this public function getdesignations return thishasone designationsclassname id designation id and is working perfect but the relation for designation group i tried like thispublic function getdesgroupstaffs return thishasonedesignationsclassname id id fromdesignationgrouptablename but it doesnt give the expected resulthow the designation group table can be joined so that all the designation group associated with the staff can also be thisplayed i want to show like the first column of grid view will be designations while filter of the same column should be designationgroupgroup name so if any group name is selected it will show data of staffs associated with that group name,['php'] +1092307,showing error when password protected openxml word document get resaved as a password protected binary word in office 2010 in microsoft word i have created openxmldocdocx file given credentials abc as readpassword and xyz as writepasswordnow i have to convert openxmldoc to binarydocwdsaveformat0 the document is created sucessfully as binarydoc using below code convert openxmldoc into binarydoc convertctestopenxmldoc ctestbinarydoc wdsaveformatwdformatdocument convert a word docx to word 2003 docpublic static void convertstring input string output wdsaveformat format create an instance of wordexe word application oword new wordapplication make this instance of word invisible can still see it in the taskmgr owordvisible false interop requires objects object omissing systemreflectionmissingvalue object isvisible true object readonly false object oinput input object ooutput output object oformat format object onewpassword xyz object ooldpassword abc object test null try load a document into our instance of wordexe suppose password abc word document odoc oworddocumentsopenref oinput ref omissing ref readonly ref omissing ooldpassword ref omissing ref omissing onewpassword ref omissing ref omissing ref omissing ref isvisible ref omissing ref omissing ref omissing ref omissing make this document the active document odocactivate save this document in word 2003 format odocsaveasref ooutput ref oformat ref omissing ref ooldpassword ref omissing onewpassword ref omissing ref omissing ref omissing ref omissing ref omissing ref omissing ref omissing ref omissing ref omissing ref omissing consolewritelinetest always close wordexe owordquitref omissing ref omissing ref omissing catch exception throw but when try to open document manually or from code it accepts readpasswordabc as shown belowbut when tries to give writepasswordxyz it doesnt accept and shown password incorrect errorplease check below screenshots,"['c#', '.net']" +1092314,development on angular2 with ts but without npm all guides suggests to install npm but i am searching way without it there is angular2 files available but none of them are typescript code so what i must do do i need angular2ts or specific angular2xxjs and dts upd i have downloaded angular2 over npm and got full source tree where hard to find something needed searching for dts for angular2 returned no results a lot of ts and dts are linked to huge mess of code filesthat is a hell,['javascript'] +1092487,filling circle with hexagons i am trying to find a way to put as much hexagons in a circle as possible so far the best result i have obtained is by generating hexagons from the center outward in a circular shape but i think my calculation to get the maximum hexagon circles is wrong especially the part where i use the mathceil and mathfloor functions to round downup some values when using mathceil hexagons are sometimes overlapping the circlewhen using mathfloor on the other hand it sometimes leaves too much space between the last circle of hexagons and the circles border var c el documentgetelementbyidmycanvasvar ctx c elgetcontext2dvar canvas width c elclientwidthvar canvas height c elclientheightvar pimathpivar pi2pi2var hexcircle r 110 radius pos x canvas width 2y canvas height 2var hexagon r 20posx 0y 0space 1drawhexcircle hexcircle hexagon function drawhexcirclehc hex drawcirclehcvar hcr mathceil mathsqrt3 hcr 2 var hr mathceil mathsqrt3 hexr 2 hexagonspace hexradiusvar circles mathceil hcr hr 2 drawhex hcposx hcposy hexr center hex for var i 1 icircles i for var j 0 j6 j var currentx hcposxmathcosjpi26hr2ivar currenty hcposymathsinjpi26hr2idrawhex currentxcurrenty hexr for var k 1 ki k var newx currentx mathcosjpi26pi23hr2kvar newy currenty mathsinjpi26pi23hr2kdrawhex newxnewy hexr function drawhexx y r ctxbeginpath ctxmovetoxyr for var i 0 i6 i ctxlinetoxmathcosipi26pi24rymathsinipi26pi24r ctxclosepath ctxstrokefunction drawcircle circle ctxbeginpathctxarccircleposx circleposy circler 0 2 mathpictxclosepathctxstrokecanvas idmycanvas width350 height350 styleborder1px solid d3d3d3,['javascript'] +1092709,appcompat 232 use vectordrawablecompat with remoteviews appwidget on api21 i have an appwidget and i would like to use vectordrawables in it also on prelollipop devicesvectordrawablecompat would not work with the remoteviews i createto keep my app apk size down i do not want to add alternative png versions of my drawables for older api platformshow can i do that,['android'] +1092712,how can i perform an aggregate function on an expression containing an aggregate or a subquery i have a query like thisselect id sumcase when errorid not in 10 11 12 13 then 1 else 0 end errorcountfrom table group by idi do not like the hardcoded list of ids and i have a simple query that will get me what i want select id sumcase when errorid not in select errorid from errors where errorcategory ignore error then 1 else 0 end errorcountfrom table group by idhowever when i try this i getcannot perform an aggregate function on an expression containing an aggregate or a subquerywhat is my best way ahead,['sql'] +1092790,python object property sharing i have a class that keeps track of several other classes each of these other classes all need to access the value of a particular variable and any one of these other classes must also be able to modify this particular variable such that all other classes can see the changed variablei tried to accomplish this using properties an example is as followsclass a def init self state self b obj bself self state state property def stateself return self state statesetter def stateselfval self state val property def b objself return self b obj b objsetter def b objselfval self b obj valclass b def init self a obj selfa obj a obj property def stateself return selfa objstate statesetter def stateselfval selfa objstate vali want it to work as follows obja a4 objb objab obj print objastate4 print objbstate4 objastate 10 print objastate10 print objbstate10 objbstate 1 print objastate1 print objbstate1everything works as i want it to except for the last 3 commands they give objbstate 1 print objastate10 print objbstate1why do the last 3 commands return these values how can i fix this so that they return the desired valuesthanks,['python'] +1092818,rails concern method override another concern method does not work like normal modules let us say i have the following structure in ruby no railsmodule parent def f puts in parent endendmodule child def f super puts in child endendclass a include parent include childendanewf prints in parentin childnow when using rails concernsmodule parent extend activesupportconcern included do def f puts in parent end endendmodule child extend activesupportconcern included do def f super puts in child end endendclass a activerecordbase include parent include childendanewf exceptionnomethoderror super no superclass method f for a0x022490so what am i missing here i need to use super in concerns like in normal modules i searched but i could not find help on this topic,"['ruby-on-rails', 'ruby']" +1092939,including related model data in page api request i have got a relatively simple setup running using silverstripe 321 with the restfulserver addon and using a variety of widgets which are associated to a page using the elemental addonwhen i make a get request via the api to retrieve some of page 1s data i can see the associated elementareaid get apiv1page1jsonfieldstitleurlsegmentcontentelementarea title welcome urlsegment home content a bunch of html here from all the widgets in the page elementarea classname elementalarea href id 11 if i follow the links through the elementalarea api calls it will list out all of the elements in my page get apiv1elementalarea11json id 11 widgets classname widget href id 9 classname widget href id 8 and if i follow those api paths it will serve up the contents of the latest version of each of the widgetsmy question is how can i include certain fields from the widget dataobjects within the original page field listi would like ideally to have the content field from each widget be returned in an array with the initial page api requestfor referencea page has one elementareaan elementarea has many widgetsa widget contains content that i want for my page,['php'] +1092969,php mysql username with underscore if i have a the php codedb user john doedb name john doedataconn new mysqliexamplecom db user johndoespassword db nameif connconnect error dieconnection failed connconnect errorwhen i try to do a query i getconnection failed access denied for user johnexamplecom using password nothe problem is obvious php is only passing the part of the username before the underscorehow can i fixget around thisi have no control over the username so get a new username is not going to workthe using password no implies i am using the wrong password but really that is the wrong password for user john and is the correct password for user john doe,"['php', 'mysql']" +1093040,recyclerviews and swiperefreshlayout using support library 2320 has anyone figured out a way to get recyclerviews appbarlayouts and swiperefreshlayout to work together on 232 yet i am using a pretty standard method i think but the swiperefreshlayout keeps grabbing the scroll gesture when trying to move up the recyclerviewandroidsupportdesignwidgetcoordinatorlayout androidlayout widthmatch parent androidlayout heightwrap content androidsupportdesignwidgetappbarlayout androidididappbar androidlayout widthmatch parent androidlayout heightwrap content androidsupportv7widgettoolbar androidididtoolbar androidlayout widthmatch parent androidlayout heightwrap content androidthemeattrtoolbar theme applayout scrollflagsscrollenteralways androidelevation4dp androidsupportdesignwidgetappbarlayout framelayout androidididfragment container applayout behaviorstringappbar scrolling view behavior androidlayout widthmatch parent androidlayout heightmatch parent fragment goes here framelayoutandroidsupportdesignwidgetcoordinatorlayoutwith the following inside itandroidsupportv4widgetswiperefreshlayout xmlnsandroid xmlnsapp androidididswipe container androidlayout widthmatch parent androidlayout heightmatch parent androidbackgroundattrwindow backgroundframelayout androidlayout widthmatch parent androidlayout heightmatch parent progressbar androidididprogress bar androidlayout widthmatch parent androidlayout heightwrap content stylestylewidgetappcompatprogressbarhorizontal androidlayout margintop4dp androidlayout marginbottom8dp androidelevation17dp androidindeterminatetrue androidvisibilityinvisible androidsupportv7widgetrecyclerview androidididrecyclerview androidlayout widthmatch parent androidlayout heightmatch parent androidscrollbarsvertical framelayoutandroidsupportv4widgetswiperefreshlayout,['android'] +1093461,apache solr slave replicates 10 times every time it polls excessive commits were using apache solr 310 to index a lot of articles written for multiple sites we have a masterslave setup replication config at the bottom where server 1 indexes the articles and server 2 replicates the index the slave should poll the master every 60 seconds but instead we can see 10 to up to 75 consecutive replication calls nearly every timeeach solr core solrcorename in the slave config represents a different site the replication calls i see most are tied to the biggest site one of the cores only got 1 call per minute and i have been able to reproduce this there after calling updatecommittrue a few times so this leads me to think it is related to the amount of commits the master performsso my question is how do i stop the solr slave from replicating the index dozens of times and force it to replicate just once per minute i have tried playing with the commitreserveduration parameter in the master config but i do not really see any differencemaster replication config requesthandler namereplication clasolrreplicationhandler lst namemaster str namereplicateaftercommitstr str namereplicateafterstartupstr lst requesthandlerslave replication config requesthandler namereplication clasolrreplicationhandler lst nameslave str namemasterurlhttpsolrmasterserversearchsolrcorenamereplicationstr str namepollinterval060str lst requesthandler,['java'] +1093492,how to configure directories when using a symfony project in phpstorm i use phpstorm to work on a symfony projectin the file settings project a directories configuration i defined the vendor directory as a resource root in order to have autocompletion and as an excluded folder because i want to ignore vendors when performing a search in my projects codebut my problem is that vendors are still shown in search resultshere is my current configurationhere is what i am trying to avoid results from vendor are shownhere is the php configurationi can restrict search by selecting scope custom but sometimes i forget to change this i am looking for some settings that i can use in my different symfony23 projectshow should i mark the vendor directory in order to allow phpstorm to use it as a resource root and ignore it when performing a searchand what is the correct configuration for the default directories structure of a symfony2 project here are the default directories after a symfony 28 installation with composer createproject symfonyframeworkstandardedition symfony28 28app a config a cache a logs a resourcessrc a appbundlevendorwebhere is how i marked the directories at this momentidea excludedapp a config a cache excluded a logs excluded a resourcessrc source a appbundle a tests test source foldersvendor excludedwebnote i installed the symfony plugin for phpstorm i do not know if this change the ide behaviour,['php'] +1093552,c select algorithm among the functionalities found in stdalgorithm i cannot seem to find one of the most basic i can think of selected a subset of a collection for example return all the odd numbers all the employees that have status employed all items that cost less that 20 dollarsso given a list of ints likevectorint ints 1 9 3 27 5 19 3 8 2 12vectorint evens vectorint greaterthan7 how to find those that are even and those that are greater than 7,['c++'] +1093581,does python have an iterative recursion generator function for firstorder recurrence relations is there a built in function or standard library function roughly equivalent todef recur untilstart step fu stop predicatelambda false current start while not stop predicatecurrent yield current current step fucurrentordef recur whilestart step fu predicatelambda true current start while predicatecurrent yield current current step fucurrentor even justdef recurstart step fu current start while true yield current current step fucurrentin any version of python the latter is as good as the other two when combined with itertoolstakewhilea generator function like these would allow to compute certain recursively defined sequences iteratively namely firstorder recurrence relationswhile these are not too hard to implement when needed i feel like something like them should be part of itertools or maybe functools but if it is i have not been able to spot it in the documentation yetusage exampleslistrecur until2 lambda x x2 1 lambda x x 1e4 2 3 8 63 3968should also work with nonnumber elementslistrecur until lambda x formatx lenx lambda x lenx 30 0 05 0510 051016 05101622,['python'] +1093635,twoway binding in an aurelia custom attribute update it looks like this is a known bug i am leaving it here for reference searchability purposesthe codeinputmaskts full code can be seen herecustomattributeinputmaskinjectelementexport class inputmaskcustomattribute bindable defaultbindingmode bindingmodetwoway changehandler onunmaskedvaluechanged unmaskedvalue any onunmaskedvaluechangednewvalue oldvalue consolelogunmaskedvalue updated from inside the custom attribute bindable mask string attached thiseventtargetonfocusout e any thisunmaskedvalue anythiselementcleanval thisfireeventetarget input code for constructor fireevent and to setup the maskcarrierhtmlinput inputmaskmaskbind carrierairbillmask unmaskedvaluebind airbill valuebindformattedairbillupdate to work around this bug change to unmaskedvaluetwoway and the binding will workcarriertsbindable defaultbindingmode bindingmodetwowaycarrier entityinterfacesicarrierbindable defaultbindingmode bindingmodetwoway formattedairbill stringbindable defaultbindingmode bindingmodetwoway changehandler onairbillchanged airbill stringonairbillchanged consolelogairbill was setthe problemthe data seems to flow into the bindable variable just fine as the mask changes the value in the custom attribute is changedbut it does not seem to flow out if changes are made inside the customattributeexample scenario after i edit the value in the input box and exit the input the focusout event fires and the console statement that indicates that the unmasked value was updated from inside the custom attribute printsunmaskedvalue updated from inside the custom attributebut when the input looses focus the console statement saying that the airbill on the carrierts file was updated does not fire when i exit the input boxthis does not fire consolelogairbill was setthis seems to show to me that the binding is not really twowaythe questionhow can i make this binding twoway so that when i update unmaskedvalue inside the customattribute it will update the bound value in the view modelnote as a workaround i was able change unmaskedvaluebind to be a method call onunmaskedvaluechangedcallonunmaskedvaluechangedevent and update the value in that method so i do not need this to work but i would like to know if it is possible for future use,['javascript'] +1093752,realm rxjava asobservable and doonunsubscribe in my android projects i use realm as my data storage engine i love it i also use rxjava because it makes threading so much easier and i really like the whole reactive mindset i love it i use an mvp pattern some clean architecture ideas to build my apps my interactors are the only ones who know about realm i expose data with the help of observable like thisoverridepublic observablecity gethometown final realm realm realmgetdefaultinstance return realmwherecityclassequaltoname clujnapocafindallasyncasobservable doonunsubscribenew action0 override public void call realmclose composenew nullifnorealmobjectcitythe problem is my doonunsubscribe sideeffect gets called before realm can do its thing handling the exposed observablecaused by javalangillegalstateexception this realm instance has already been closed making it unusableat iorealmbaserealmcheckifvalidbaserealmjava344at iorealmrealmresultsremovechangelistenerrealmresultsjava818at iorealmrxrealmobservablefactory32callrealmobservablefactoryjava137at rxsubscriptionsbooleansubscriptionunsubscribebooleansubscriptionjava71at rxinternalutilsubscriptionlistunsubscribefromallsubscriptionlistjava124at rxinternalutilsubscriptionlistunsubscribesubscriptionlistjava113at rxsubscriberunsubscribesubscriberjava98at rxinternalutilsubscriptionlistunsubscribefromallsubscriptionlistjava124at rxinternalutilsubscriptionlistunsubscribesubscriptionlistjava113at rxsubscriberunsubscribesubscriberjava98at rxsubscriptionscompositesubscriptionunsubscribefromallcompositesubscriptionjava150at rxsubscriptionscompositesubscriptionunsubscribecompositesubscriptionjava139at rotudorlucarealmsandboxcitycitypresenterondestroycitypresenterjava62at rotudorlucarealmsandboxcitycityactivityondestroycityactivityjava35i created a sandbox project for this use casei really like using realmrxjava but i cannot seem to find a clean solution to close the realm instance when i unsubscribe i usually unsubscribe when the activity gets destroyed any ideasedit 1 edit 2 thanks to the very active realm team there is already a pull request to fix this issue,['android'] +1093828,defaultclusterrenderer getmarker returning null when zooming i want to change the background of the cluster marker on click i do this via overrideonclusterclickclustermyobject cluster marker marker renderergetmarkercluster markerseticonthis works fine expect for one case when i zoom in or out and the number of cluster markers does not change for example if i had a 15 cluster and a 5 cluster then zoom a level in or out the same two clusters remain clicking on one of these now renderergetmarkercluster returns null if they recluster after zooming getmarker is not null my defaultclusterrenderer is below i checked the marker on onclusteredrendered and it is never null is this a bug in the defaultclusterrenderer or should i do something elseprivate class myrenderer extends defaultclusterrenderermyobject private icongenerator icongenerator private float density public myrenderercontext context googlemap map clustermanagermyobject clustermanager supercontext map clustermanager density contextgetresourcesgetthisplaymetricsdensity override protected void onbeforeclusteritemrenderedmyobject item markeroptions markeroptions markeroptionsiconbitmapdescriptorfactoryfromresourcerdrawablemy pin override protected void onbeforeclusterrenderedclustermyobject cluster markeroptions markeroptions ificongenerator null icongenerator new icongeneratorgetactivity icongeneratorsetcontentviewmaketextviewgetactivity icongeneratorsetbackgroundmakebackgroundfalse markeroptionsiconbitmapdescriptorfactoryfrombitmapicongeneratormakeiconstringvalueofclustergetsize override protected void onclusterrenderedclustermyobject cluster marker marker superonclusterrenderedcluster marker marker is never null here override protected boolean shouldrenderasclusterclustermyobject cluster return clustergetsize 1 private shapedrawable makebackgroundboolean isclicked shapedrawable background new shapedrawablenew ovalshape backgroundsetcolorfiltercontextcompatgetcolorgetactivity isclicked rcolorcluster marker clicked rcolorcluster marker unclicked porterduffmodesrc atop return background private squaretextview maketextviewcontext context squaretextview squaretextview new squaretextviewcontext viewgrouplayoutparams layoutparams new viewgrouplayoutparams2 2 squaretextviewsetlayoutparamslayoutparams squaretextviewsettextcolorcontextcompatgetcolorgetactivity rcolorwhite squaretextviewsettypefaceutilsgetfontboldgetactivity squaretextviewsetidcomgooglemapsandroidridtext int twelvedpi int 120f density squaretextviewsetpaddingtwelvedpi twelvedpi twelvedpi twelvedpi return squaretextview public icongenerator geticongeneratorboolean isclicked icongeneratorsetbackgroundmakebackgroundisclicked return icongenerator initializing the clustermanager final clustermanagermyobject mclustermanager new clustermanagergetactivity googlemap mclustermanageradditemsitems renderer new customrenderergetactivity googlemap mclustermanager mclustermanagersetrendererrenderer mclustermanagercluster mclustermanagersetonclusteritemclicklistenerthis googlemapsetonmarkerclicklistenermclustermanagerantonio this initialization is working for mepublic class mapsactivity extends fragmentactivity implements clustermanageronclusterclicklistenermyobject private void setupclusterer googlemapmovecameracameraupdatefactorynewlatlngzoomnew latlng51503186 0126446 10 mclustermanager new clustermanagermyobjectthis googlemap mclustermanagersetonclusterclicklistenerthis renderer new myrendererthis googlemap mclustermanager mclustermanagersetrendererrenderer googlemapsetoncamerachangelistenermclustermanager googlemapsetonmarkerclicklistenermclustermanager additems private void additems set some latlng coordinates to start with double lat 515145160 double lng 01270060 add ten cluster items in close proximity for purposes of this example for int i 0 i 10 i double offset i 60d lat lat offset lng lng offset myobject offsetitem new myobjectlat lng mclustermanageradditemoffsetitem override public boolean onclusterclickfinal clustermyobject cluster marker marker renderergetmarkercluster markerseticonbitmapdescriptorfactoryfromresourcerdrawablemy newpin return true,['android'] +1093878,why am i getting a syntax error in php i am trying to write a new line to a file with php and i am getting the following errorparse error syntax error unexpected t encapsed and whitespace expecting identifier t string or variable t variable or number t num stringthis is my codepublic function add lineline value file ci get instance ciloadhelperfile foreachthisexisting langs as lang lang contents read filethislang pathlangfile langphp new contents lang contentsnlangline value error happens on this line write filethislang pathlangfile langphp new contents w i have pointed out the line the error occurs on with a php comment what is wrong with this lineexample of lang contentsphplang1234 restaurantsexample of new contentsphplang1234 restaurantslang1235 transportation,['php'] +1093899,make function have ellipsis for arguments in help function if you type helpvars the following is producedvars varsobject dictionary without arguments equivalent to locals with an argument equivalent to object dict when i do the followingdef funcx y passhelpfuncit thisplays thisfuncx yhow can i change it so that it shows up with between the parentheses like the builtin function vars that is funcedit it has been suggested to use a docstring but that would not do what i want here is an exampledef funcx y func nonehelpfuncresultfuncx y func noneyou see x y is still being thisplayed instead of,['python'] +1094112,is there a limit on the number of values that can be printed by a single call of printf does the number of values printed by printf depend on the memory allocated for a specific program or it can keep on printing the values,['c'] +1094434,a little hazy about stdref and stdbind with variadic templates i have read many posts about variadic templates and stdbind but i think i am still not understanding how they work together i think my concepts are a little hazy when it comes to using variadic templates what stdbind is used for and how they all tie together in the following code my lambda uses the dot operator with objects of type testclass but even when i pass in objects of type stdref they still work how is this exactly how does the implicit conversion happeninclude iostreamusing stdcoutusing stdendlinclude functionalinclude utilityusing stdforwardclass testclass public testclassconst testclass other thisinteger otherinteger cout copy constructed endl testclass integer0 cout default constructed endl testclasstestclass other cout move constructed endl thisinteger otherinteger int integertemplate typename functiontype typename argsvoid my functionfunctiontype function args args cout in function endl auto bound function stdbindfunction args bound functionint main auto my lambda const auto one const auto two cout oneinteger twointeger endl testclass test1 testclass test2 my functionmy lambda stdreftest1 stdreftest2 return 0more specifically i pass in two instances of a reference wrapper with the two testclass objects test1 and test2 but when i pass them to the lambda the operator works magically i would expect that you have use the get function in the reference wrapper to make this work but the call to the integer data member works,['c++'] +1094488,how to create custom data binding in android android studio i want to implement custom functions to download image from imageview like this appimageurlstatusimageurl in the below code xml version10 encodingutf8 layout xmlnsandroid xmlnsapp data variable namestatus typecomdatabindingdatastatus data relativelayout androidididstatus container androidlayout widthmatch parent androidlayout heightmatch parent imageview androidididstatus avatar androidlayout width64dp androidlayout height64dp androidlayout alignparentlefttrue androidlayout alignparentstarttrue androidlayout alignparenttoptrue androidcontentdescriptionnull appimageurlstatusimageurl relativelayout layouthow to write this function which can download image automate from a statusimageurl use this library comandroiddatabinding,"['java', 'android']" +1094500,which type safety would have lost had generics supported the subtyping consider the snippetnumber numbers 1 23 45f 60lit is perfectly okay to do the above number is an abstract classgoing aheadlistlong listlong new arraylistlonglistlongaddlongvalueof10listnumber listnumbers listlong compiler error line 3listnumbersadoublevalueof123had line 3 was designed to be compiled successfullywe would end up with a list of numbers iefornumber num listnumbers systemoutprintlnnum 10 123which are all numbersi came across this in a bookgenerics doesnat support subtyping because it will cause issues in achieving type safety thatas why listt is not considered as a subtype of lists where s is the supertype of twhich type safety would have lost in this specific case as thiscussed above were the line 3 was to be compile successfully,['java'] +1094881,why is refcount not working after all initial subscribers thisconnect consider the followingfactpublic void foo var result new subjectbool var startcount 0 var completioncount 0 var obs observable defer startcount return resultfirstasync do completioncount publish refcount pretend there are lots of subscribers at once var s1 obssubscribe var s2 obssubscribe var s3 obssubscribe even so we only expect to be started once assertequal1 startcount assertequal0 completioncount and we would not complete until the result ticks through resultonnexttrue assertequal1 startcount assertequal1 completioncount s1thispose s2thispose s3thispose now try exactly the same thing again s1 obssubscribe s2 obssubscribe s3 obssubscribe startcount is 4 here instead of the expected 2 assertequal2 startcount assertequal1 completioncount resultonnexttrue assertequal2 startcount assertequal2 completioncount s1thispose s2thispose s3thisposemy understanding of publish refcount is that a connection to the source is maintained as long as there is at least one subscriber once the last subscriber thisconnects any future subscriber will reinitiate the connection to the sourceas you can see in my test everything works perfectly the first time through but the second time the deferred observable inside the pipeline is executed once for every new subscriberi can see via the debugger that for the first group of subscribers obs count which counts subscribers increases for each call to subscribe but for the second group of subscribers it remains zerowhy is this happening and what can i do to rectify my pipeline,"['c#', '.net']" +1094886,tvos game control via nonsiri remote i am working on a game in objectivec the siri remote works great via gcmicrogamepad and real mfi controllers work well via gcgamepad however thirdparty ir remotes do not work at all ingame and neither does the remote app on iphone or an older apple tv 3rd gen remote how can i recognize and thistinguish these inputstwo days later i have found that a uitapgesturerecognizer can be used to detect up down left right and select events correctly when presented with a thirdparty tv remote or iphone remoteapp the directional events are actually unique to these types of remotes as wellathe siri remote does not generate directional tap events unfortunately however tapping the select button on either the siri remote or the thirdparty or iphone remoteapp will generate a select event from my tap recognizer i need some way to thistinguish the twothe only thistinguishing factor i can find is that tapping the siri remote also generates a buttona press on the gcmicrogamepadaa thirdparty remote or iphone remoteapp does not affect the gcmicrogamepad at all but it is very extremely inelegant to attempt to watch the gcmicrogamepad for taprelease events and then use that event to filter out a matching select button event certainly it is not a recommended use of the apis it does not seem like a good longterm solution if i could tell the siri remote to stop generating ui events when in gcmicrogamepad mode that would be excellent,['objective-c'] +1095197,utf8 endecode removed from php7 i recently switched to php 7 on my development server which has worked just fine until nowsince i updated to php 70310debsuryorgtrusty1 earlier today the utf8 decode and utf8 encode functions are not longer accessible they were however in previous versions of php7 when called a fatal error is raisedi read that these functions are provided by the mbstring extension which i checked with var dumpextension loadedmbstring is loadedhow can i get above functions work again,['php'] +1095211,why does parameter pack expansion work differently with different c compilers parameter pack expansion is reversed by the vs2015 compiler i have the following codeinclude iostreaminclude vectortemplate typename tvoid f swallowt template typename tstdvectorint ft arg stdvectorint result f swallow resultpush backarg return true return resultusing namespace stdint main auto vec f1234 for size t i 0 i vecsize i cout veci endlwhen i run this code in xcode clang700181 i get this result1234but the same code run in vs2015 produces this output4321why are the parameter packs expanded differently depending on the compiler is there a way to fix it without checking the platform and compiler version does not the standard guarantee anything about expansion order,['c++'] +1095368,visualing a towers of hanoi algorithm in javascript latley i am working on a school project and i have to present an algorithm which is in my case a solving algorithm for the puzzle towers of hanoi due to my knowledge in htmlcss i thought it would be quite neat to use those javascript to visualise the steps on a webpagei got the site set up as well as the basic recursive algorithmfunction moven beg aux end if n 1 consolelogbeg end n settowersbeg end else moven 1 beg end aux move1 beg aux end moven 1 aux beg end layout of the page css code wont help heresectionmainappappwrapper towerwrapper towertwra blockblcktop blockblckmiddle blockblckbottom towertwrb blockblcktop blockblckmiddle blockblckbottom towertwrc blockblcktop blockblckmiddle blockblckbottomthen i started to struggle as i had to somehow visualise it i thought of putting each tower into an arrayvar twrelemsa documentgetelementbyidtwragetelementsbyclassnameblocktowera jquerymakearraytwrelemsathen the function to actually set the color 2 things for the moment it wont erase the color if needed and it wont set the color at all because i messed up the switch statementdont know how to proper do itfunction setcolorstarget targetforeachfunction element switch element case div classblock blcktop elementcss backgroundcolor red break case div classblock blckmiddle elementcss backgroundcolor 51616f break case div classblock blckbottom elementcss backgroundcolor 394b5a break now if the move function returns for example a b setcolors should then iterate over towerb and set the backgroundcolors of all three blocks to a specific color but the switch statement does not work and i run out of ideas and time which is a devasting combomaybe someone knows what could help here i appreciate any helpregards,"['javascript', 'jquery']" +1095370,why does not gmail oauth work in my android app i am working on an app which does an oauth2 authentication which used to work but unfortunately does not work anymore as far as i know but not 100 sure nothing changed on the code so i do not know why it wouldnt work anymorethe app creates a webview and loads an url from our server which redirects it to google to authenticate on this url just changed client id and my domain typecodeclient id1234567890xappsgoogleusercontentcomredirect urihttp3a2f2fexamplecom3a502fchannel2fgmail2fcallbackscopehttps3a2f2fwgoogleapiscom2fauth2fuserinfoemailhttps3a2f2fwgoogleapiscom2fauth2fgmailreadonlyaccess typeofflinewhich immediately redirects it tocontinue type3doffline26scope3d type3dcode26redirect uri3d id3d123456789xappsgoogleusercontentcom26hl3dnl26from login3d126as3d2178738b5063e716ltmplpopupoauth1sarp1scc1the same system is used from our iosapp which works like a charm so there is nothing wrong with our server implementationafter the webview redirected to google it automatically returns back to the app without showing any google screeni am using the following code to open the webviewoverridepublic view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate view view inflaterinflaterlayoutfragment browser webview container false webview webview viewfindviewbyidridweb view webviewgetsettingssetjavascriptenabledtrue webviewgetsettingssetthisplayzoomcontrolsfalse webviewgetsettingssetloadwithoverviewmodetrue webviewgetsettingssetusewideviewporttrue webviewgetsettingssetdomstorageenabledtrue webviewsetwebviewclientnew webviewclient public void onreceivederrorwebview view int errorcode string description string failingurl logwtferror description failingurl override public boolean shouldoverrideurlloadingwebview view string url logwtfwebview url url if urlcontainsapiapi enter point we never actually get here getactivityfinish return false allow webview to load url if userid null usertoken null logdgmail login stringformatapiapi gmailuseridusertoken webviewloadurlstringformatapiapi gmailuseridusertoken return viewand the logcat output is as follows0229 185639028 2751027510comexample dgmail login 0229 185639092 2751027510comexample dcr ime imeadapterjava358 onviewfocuschanged gainfocus true0229 185639119 2751027510comexample dcr ime imeadapterjava140 oncreateinputconnection returns null0229 185639162 2751027510comexample itimeline timeline activity idle id androidosbinderproxy2b109b89 time2271993150229 185639163 2751027510comexample awebview url typecodeclient id1234567890xappsgoogleusercontentcomredirect urihttp3a2f2fexamplecom3a502fchannel2fgmail2fcallbackscopehttps3a2f2fwgoogleapiscom2fauth2fuserinfoemailhttps3a2f2fwgoogleapiscom2fauth2fgmailreadonlyaccess typeoffline0229 185639216 2751027510comexample awebview url continue type3doffline26scope3d type3dcode26redirect uri3d id3d1234567890xappsgoogleusercontentcom26hl3dnl26from login3d126as3d231b0767e02a8ca9ltmplpopupoauth1sarp1scc10229 185639283 2751027510comexample itimeline timeline activity idle id androidosbinderproxy16bf8d10 time2271994360229 185639287 2751027510comexample dcr ime imeadapterjava358 onviewfocuschanged gainfocus false0229 185639287 2751027510comexample dcr ime imeadapterjava326 hidekeyboard0229 185639288 2751027510comexample dcr ime inputmethodmanagerwrapperjava56 isactive falsesince this log does not really give an error i am unsure what could be wrong does anybody have any idea what could possible be wrong or how i can debug this all tips are welcome,"['java', 'android']" +1095646,explain the difference between these midpoint algorithms why does the midpoint algorithm for binary search uselow highlow2rather thanlow high2,['python'] +1095708,in ios how can we increase http connection limit per host using the xcode networking tool i analyzed that i am able to establish only 4 tcp connections per host at a time it seems ios has a default tcp connection limit of 4 per hosthow can we increase that limit,['ios'] +1095843,find tuple structure containing an unknown value inside a list say i have list of tuples list 15 17 23is there a way in python to write something likeif 1 in list do thingswhere means i donat care about this value so we are checking if there is a tuple with 1 at the first position and with whatever value on the second oneas far as i know there are special mechanisms in other languages but i just donat know the name of this particular problem so is there similar behavior in pythonps i know that i can use list comprehensions here i am just interested in this particular mechanism,['python'] +1095874,ioacknowledge method is not working for socketio in android i am using socketiojar to establish the connection between client and serverie from my android deviceclient to a node server as i am successfully able to connect send and receive messages to that serverthe problem is why i am not getting any acknowledgement from socket after emitting message to the server there is a callback interface ioacknowledge as parameter that never worksinvokes for me socketemit sendmessage new ioacknowledge overridepublic void ackobject arg0 systemoutprintlnsendmessage ioacknowledge arg0tostring hi how are youdoes anyone know the solution when or how that ioacknowledge will workedit docs link of socket library which i am using official and github,"['java', 'android']" +1096142,does clion ide include all features which resharper c provides under visualstudio since i have been using for some while resharper for c and other jetbrains tools and been very pleased with the experience i am oscillating regarding which would be the better option between the 2 jetbrains products from the title for c projectsone key point of decision would be if clion includes all or at least most features provided by resharper cthe only information i could find about this topic is the following quote from a jetbrains blog which does not help me muchas weave already mentioned at some point the clion and resharper c teams split giving way to two completely independent implementations of c parsers this was caused by two completely different platform architectures intellij and resharper and two different sets of ideas of how parsers can be implementedalso other aspects except feature sets regarding the comparison between the 2 optionscombinations would be welcome,['c++'] +1096279,does undefined behavior apply to asm code let us say you know your software will only run on twos complement machines where signed overflow behavior is nicely defined signed overflow is still undefined behavior in c and c and the compiler is free to replace your entire program with ret start a nuclear war format your drive or make demons fly out of your nosesuppose you have signed overflow in inline asm does your program still invoke ubif yes what about separately compiled and linked assembler,"['c++', 'c']" +1096315,direct response with nodejs sending http response with different nodejs process different than main process using nodejs servers i am wondering if it is both possible and recommended to send an http response from a delegated worker process instead of the main process these worker processes could be nodejs servers themselves or simply nodejs child processes that communicate via ipci do not think the cluster core module can do what i want to do because in that model all the workers are listening on the same port and they process all requests on behalf of the master process what i am looking for is one main nodejs process that responds to all http requests perhaps does the authentication and processes some requests but is also capable of delegating dataintensive or cpu intensive requests to a worker poolimagine that we have a get request for a large amount of data say 23mbswe have at least 3 possible scenariosthe main process receives the request asks the database for the large amount of data and then sends the data back to the requestormain process receives the request sends some data to a worker process using ipc the worker gets the data from the db does some heavy operations and then the worker uses ipc to send all of the 3mbs of data back to the main process which then sends back the responsethe main process receives the request sends as small amount of info as possible about the request stream to the worker the worker does all the work and the worker sends back the http responsei am particularly curious about making 3 possible a simple depiction of scenario 3 is belowjust to be clear i do not want 3 responses for one request i am just trying to show that a worker could possibly send the response on behalf of the main processanyone know how this might work with nodejs how it might work in other languages normally i have no problems with the nodejs concurrency model but with some types of data using the cluster module is probably not the best way to achieve the highest levels of concurrencyi believe one term for this model is direct response meaning the worker responds directly to the request and perhaps it is possible to simply use the cluster core module for this,['javascript'] +1096493,sql query for parent children relation i am trying to write a sql query on bellow table a id a name a class aparenta dob aa a 1 a david a spin a a1 aa 2 a aroon a bike a 1 a1 aa 3 a leo a yoga a a2 aa 4 a lin a cyc a 1 a2 aa 5 a stefa a yoga a a3 aa 6 a gloria a runn a 1 a3 and output for this table should be like followinga id a name a class aparenta dob aa a 1 a david a spin a a1 aa 2 a aroon a bike a 1 a1 aa 4 a lin a cyc a 1 a2 aa 6 a gloriaa runn a 1 a3 aa 3 a leo a yoga a a2 aa 5 a stefana yoga a a3 aso this is the explanation of the outputfirst parent david as his dob is 1 david three childrens sorted based on dobthen leo as his dob is 2 leo do not have childrenif he did would be here as sorted on dob then stefan as his dob is 3 stefan do not have children if he did would be here as sorted on dob so what i triedselect from user group by id parent above sql statement return items in parent children group but not does not maintain any order when i add order by sql does not seems like honoring group by anymore then i tried to do joining and end with two complete different tables where one contains all the parents and another one contains all children union all on that two query returned expected data set but not in expected order any thoughts updateoutput should bepick entry based on min time use that id and find all of its children and placed them in sorted orderrepeat for every row in the tablenoteparents are sorted based on dobchilds are also sorted based on dob dob are valid timestamp parent id field both are uuid and define as char parent reference to idsql fiddle similar on soupdate 1query bellowwith recursivetop as select from select from user where parent is null order by dob limit 1 union select username userparent userid userclass userdob from user top where userparenttopid order by userdob select from topreturning following output a id a name a class aparenta dob aa a 1 a david a spin a a1 aa 2 a aroon a bike a 1 a1 aa 4 a lin a cyc a 1 a2 aa 5 a gloriaa runn a 1 a3 aoutput is good for first parent but still could not figure out how can i iterate through rest of parents and their children in sorted order,['android'] +1096761,what is slim in fileslimjs excuse my ignorance but i just installed jquery using npm and between the jquery files there is a file called jqueryslimjs what is slim i know the min stands for minified but slim is new to mebtw i am pretty sure slim is not like min because there is another file called jqueryslimminjs and obviously it is lighter than the normal slim filealso the slim file contains the jquery 3 beta that is what the comments in the code sayagain sorry for the stupid question but i got no clueupdatei am using require to include the files would the require include this file without my knowledge or not,"['javascript', 'jquery']" +1096802,string with f prefix in python36 i am trying out python 36 going through new code i stumbled upon this new syntaxfmy formatting stringit seems we can do things like this name george print fmy cool string is called namemy cool string is called georgecan anyone shed some light on the inner workings of this in particular what is the scope of the variables that an fprefixed string can take,['python'] +1096863,how to break first foreach loop from second nested foreach loop in c how to break first for each loop from second nested for each loop in ci want to check some conditions in the second for each loop then try to break the parent for each loopforeachdo some stuff foreachdo some stuff ifcheck some condition breakbut want to break first foreach loop,['c#'] +1097154,why does the void t detection idiom not work with gcc49 consider the following codeinclude iostreaminclude type traitsstruct test test operator struct noincrement template typename using void t voidtemplate class classvoid tstruct has pre increment member stdfalse type template class tstruct has pre increment membert void tdecltype stddeclvalt public stdtrue type int main stdcout has pre increment membertestvalue stdcout has pre increment membernoincrementvalue stdendlwith g version 5 and later and the stdc14 flag of course this code outputs1 0as it should with g version 49 and the stdc14 flag however it outputs1 1both claim to be using the same language standard so whats the issue here,['c++'] +1097167,make gameobject aattacha properly this script makes a cube stick to whatever it collided with the problem is that when it is going at relatively high or medium speeds or when the device itself is slow the cube tends to get a bit inside what it collided with and then stick to it what changes do i have to make to fix thisin order for this script to work one gameobject must have bool stickstoobjects true and the other bool stickstoobjects falsei have tried turning the rigidbodys collision detection mode to either continuous or continuous dynamic i think my script depends on frame rate that may be where the problem lies normal attachabnormal attachrigidbody rigidbodytransform meshtransformbool stickstoobjects truepublic transform stuckto nullprotected vector3 offset vector3zerovoid awake gameobject cubemesh gameobjectfindwithtag cubemesh gameobject cube gameobjectfindwithtag cube rigidbody cubegetcomponentrigidbody meshtransform cubemeshgetcomponenttransform void update if stuckto null transformposition stucktoposition offset void oncollisionentercollision collision if stickstoobjects return rigidbodyiskinematic true get the approximate collision point and normal as there may be multipled collision points vector3 contactpoint vector3zero vector3 contactnormal vector3zero for int i 0 i collisioncontactslength i contactpoint collisioncontacts ipoint contactnormal collisioncontacts inormal get the final approximate point and normal of collision contactpoint collisioncontactslength contactnormal collisioncontactslength move object to the collision point this acts as setting the pivot point of the cube mesh to the collision point transformposition contactpoint adjust the local position of the cube so it is flush with the pivot point vector3 meshlocalposition vector3zero move the child so the side is at the collision point a x local position of 0 means the child is centered on the parent a value of 05 means it is to the right and a value of 05 means it to the left meshlocalpositionx 05f contactnormalx meshtransformlocalposition meshlocalposition if stuckto null stuckto collisiongameobjecttransform offset collisiongameobjecttransformposition transformposition stuckto collisiongameobjecttransform here are some screenshots of the unity editor,['c#'] +1097247,php composer openssl error before asking i have to say that i have tried every similar question here on stack and elsewhere and failedi am unable to use composer because of this errorrequires extopenssl the requested php extension openssl is missing from your systemi have xampp on ubuntuwhat i have triedi have uncommented extensionphp openssldll in phpini both cli and normal did not workinstalled openssl through terminal outside of php did not workcheck in phpinfo if openssl is loaded and activatedand few more like runing composer through php c optlamppetcphpini composerphar install where i get error php warning php startup unable to load dynamic library usrincludephp5extphp opensslso usrincludephp5extphp opensslso cannot open shared object file no such file or directory in unknown on line 0i have tried to change path in bashrc no success eitherwhat i have found strange is the location of extensionsin phpinfo extension dir is usrincludephp5ext even though i have tried to specify another dir in phpini and of course restart apache and still didnt show in phpinfobut in phpconfig command i get that extension dir is usrlocallibphpextensionsnodebugnonzts20100525i am not sure if i have multiple php on system but i tried to look for phpini files and only 2 came upetcphp5cliphpinioptlamppetcphpini,['php'] +1097479,alpine 33 python 2711 urllib2 causing ssl certificate verify failed i have this small dockerfilefrom alpine33run apk update add pythoncmd python c import urllib2 response urllib2urlopenbuilding it with docker build t alpinepy01 and then running it with docker run it rm alpinepy01 creates the following outputtraceback most recent call last file string line 1 in module file usrlibpython27urllib2py line 154 in urlopen return openeropenurl data timeout file usrlibpython27urllib2py line 431 in open response self openreq data file usrlibpython27urllib2py line 449 in open open req file usrlibpython27urllib2py line 409 in call chain result funcargs file usrlibpython27urllib2py line 1240 in https open contextself context file usrlibpython27urllib2py line 1197 in do open raise urlerrorerrurllib2urlerror urlopen error ssl certificate verify failed certificate verify failed sslc590yesterday i got bitten by the recent openssl 102g release which caused pycryptograpy to not compile luckily the guys from pycryptography released a new version on pypi a couple of hours later the issue was that a function in openssl got a new signaturecould this be related or am i missing something,['python'] +1097505,customize edittext input character to image i want to customize an edittext when user input a character and then edittext changes it to imagelook like the image note a is an image not a symbol,['android'] +1097513,problems using mysql with aws lambda in python i am trying to get up and running with aws lambda python beginner in python btw but having some problems with including mysql dependency i am trying to follow the instructions here on my macfor step number 3 i am getting some problems with doing the command at the root of my projectsudo pip install mysqlpython t error exception traceback most recent call last file librarypython27sitepackagespip156py27eggpipbasecommandpy line 122 in main status selfrunoptions args file librarypython27sitepackagespip156py27eggpipcommandsinstallpy line 311 in run ospathjoinoptionstarget dir item file systemlibraryframeworkspythonframeworkversions27libpython27shutilpy line 292 in move raise error destination path s already exists real dst error destination path mysql python125py27egginfomysql python125py27egginfo already existsi end up writing my following lambda function works fine on my mac which is import mysqldbdef lambda handlerevent context open database connection db mysqldbconnect prepare a cursor object using cursor method cursor dbcursor sql select from users try execute the sql command cursorexecutesql fetch all the rows in a list of lists results cursorfetchall for row in results fname row0 lname row1 age row2 sex row3 income row4 now print fetched result print lnames lname except print error unable to fecth data thisconnect from server dbclosewhat i went on to do is go to librarypython27sitepackages and copying over the the mysqldb foldersfiles that were downloaded when i did sudo pip install mysqlpython without t i am sure i am doing something wrong here to my lambda project and then zipped the content along with the lambda functionpy and uploaded to aws lambda then i getunable to import module lambda function no module named mysqldbgrateful for any help and suggestionseditwas able to do make sudo pip install mysqlpython t pathtoproject work thanks for the help in the comments but now i get this when runing the lambda functionunable to import module lambda function vartask mysqlso invalid elf headeri know that if i work on a linux box then it should work fine as suggested by some people but i am wondering if i can make it work from an os x box,"['python', 'mysql']" +1097615,sugar orm just would not create tables i am working on a standalone library project that requires persisting a simple model here is what my sugarrecord looks like keeping track of previously received messages by id public class messagerequestidmodel extends sugarrecord protected string messagerequestid public messagerequestidmodel public messagerequestidmodelstring messagerequestid thismessagerequestid messagerequestid public string getmessagerequestid return thismessagerequestid public static boolean existsstring id return messagerequestidmodelfind messagerequestidmodelclass messagerequestid id size 0 in a repository class i am attempting to persist it by calling this methodoverridepublic void savemessagerequestid messagerequestid new messagerequestidmodelmessagerequestidgetidsavei now attempt to test this by using an androidtestinstrumentationtestcase where i pass a context to sugar like sosugarcontextinitgetinstrumentationgetcontextthis results in this error when i run the testtruncating to keep this question a succinct readandroiddatabasesqlitesqliteexception no such table message request id model code 1 while compiling insert or replacetroubleshooting i have already attemptedkeeping a different manifest for the test package to pass the test package name to sugarorm no change in behaviouradding a messagerequestidmodelfindbyidmessagerequestidmodelclass long 1 like in the other so posts changes error to itself showing full stacktrace here in case it helpsandroiddatabasesqlitesqliteexception no such table message request id model code 1 while compiling select from message request id model where id limit 1at androiddatabasesqlitesqliteconnectionnativepreparestatementnative methodat androiddatabasesqlitesqliteconnectionacquirepreparedstatementsqliteconnectionjava889at androiddatabasesqlitesqliteconnectionpreparesqliteconnectionjava500at androiddatabasesqlitesqlitesessionpreparesqlitesessionjava588at androiddatabasesqlitesqliteprograminitsqliteprogramjava58at androiddatabasesqlitesqlitequeryinitsqlitequeryjava37at androiddatabasesqlitesqlitedirectcursordriverquerysqlitedirectcursordriverjava44at androiddatabasesqlitesqlitedatabaserawquerywithfactorysqlitedatabasejava1316at androiddatabasesqlitesqlitedatabasequerywithfactorysqlitedatabasejava1163at androiddatabasesqlitesqlitedatabasequerysqlitedatabasejava1034at androiddatabasesqlitesqlitedatabasequerysqlitedatabasejava1240at comormsugarrecordfindsugarrecordjava192at comormsugarrecordfindbyidsugarrecordjava102at pmtinappriseentitiesmessage request idsmessagerequestidmodelrepositorysavemessagerequestidmodelrepositoryjava19i have tried removing all sugar orm config from the manifest like suggested by many this changes nothingi have tried creating a sample app module and tried running it as a testcase for that app in case standalone apps did not get the right resources on the emulatordevice i have tested on bothi have tried incrementing the version number for the databasei have tried switching to an activitytestcase and using getactivitygetapplicationcontext this essentially fails with an error that suggests that this context is incomplete to be able to setup sqliteas you can see i have pushed hard at this boulder all night long but at this point it is seeming sisyphean and i have absolutely no lead for my next debug attempt other than to use a different orm than sugar which does not really seem to be the problem there is nothing more emasculating that not being able to run sqlite in a test case and i cry to the holy programmer consciousness in you for help,['android'] +1097655,serializationstore not finding references when trying to deserialize using the componentserializationservice errors are populated that references were not foundpublic icollection deserializeobject serializationdata var serializationstore serializationdata as serializationstore var componentserializationservice serviceprovidergetservicetypeofcomponentserializationservice as componentserializationservice var collection componentserializationservicedeserializeserializationstoreerrors such as could not find type systemdrawingsize please make sure that the assembly that contains this type is referenced if this type is a part of your development project make sure that the project has been successfully built using settings for your current platform or any cpuhere i have passed through a button control and set the size property,['c#'] +1097722,how to run commands on same tcl shell using python i am having all the libraries written in tcl i want to create a gui in python which will have few buttons and other options in the start tcl shell will open when i will click the buttons respective commands will be executed on the tcl shellis it possible to fire commands on the same shell of tcl without closing tcl shelli searched google and find tkniter module in python but it will open tcl shell everytime i need to execute command,['python'] +1097853,string literal reference class in c1y can i have a reference class that binds to a string literal but not to char or char or similarclass litrf const char data size t size public litrfconst char s data ssize sizeofs,['c++'] +1097897,how to achieve readwrite separation with entity framework i have a database setup using masterslave replication i have one master and at least one slave possibly a slaves for simplicity from here on i will talk about one master one slave because determining which slave to use includes some businesslogic not relevant to the actual problem at handheres a schematic of the setup with a slavesin the application currently using dapper i have the following simplified codeabstract class baserepo private readonly string readconn private readonly string writeconn public baserepostring readconnection string writeconnection readconn readconnection actually ienumerablestring for a slaves writeconn writeconnection private sqlconnection getopenconnectionstring cnstring var c new sqlconnectioncnstring copen return c public sqlconnection getopenreadconnection return thisgetopenconnection readconn actually we use some businesslogic to determine which of the slaves to use public sqlconnection getopenwriteconnection return thisgetopenconnection writeconn class customerrepo baserepo ctor left out for brevity read functions use the read connection public ienumerablecustomer listcustomers using var c thisgetopenreadconnection return cquerycustomerselect from customers order by name asenumerable write functions use the write connection public void updatecustomercustomer cust using var c thisgetopenwriteconnection cexecuteupdate customers set name name where id id cust my question is suppose i want to use entity framework code first should that be relevant instead of dapper how would i best go about achieving the same concept insertsupdatesdeletes are executed against the master database and selects are executed against a slave or any of the slaves does ef support this scenario at all what would i need to do to make this workadditional info i already use readonly and writeonly users at the sql server level as a last line of defence to prevent any mistakes in the dal what i am looking for is a method of limiting my dal to avoid having to catch sql server exceptions because of not allowed actions and having to go to the incorrect sql server in the first place before finding out the desired action is not allowed i could use the same approach as i do now instantiateuse the correct dbcontext in the method itself listcustomersupdatecustomer in the above example i get that but that would mean i would have to create a wrapper function for each crud action on each entity which was kind of why i was moving from dapper to ef in the first place simply expose a dbset and have ef take care of the changetrackingsql queries etc and now hopefully also figure out which connectionstring to use for each action,['c#'] +1098019,is there a way in css js or jquery that can change the color of text depending on position i am the developer of a corporate website that has a design for a page that incorporates the followinga body background gradient from their primarycolor to white from top to bottom statica set color of headers h1 h2 h3 etc is set to whitei would like to comply with both of these but of course headers do not always sit at the top of the page especially if they are being used as subheaders and section titlesdoes anyone know of a way in css javascript or jquery that would allow the color of the text change depending on where it sits on the page for example at the top the headers are white to contrast the primarycolor of the body gradient but further down the page the headers change to the primarycolor to contrast the white of the body gradient,"['javascript', 'jquery', 'html', 'css']" +1098060,fast absolute difference of two uint8 arrays i have two numpyarrays with dtypenpuint8 like thisimg1npuint8nprandomrandint0 255 480 640img2npuint8nprandomrandint0 255 480 640and i want to build the positive difference of these arrayshere are my first two approches and a third one for referencedef differenceimagev1img1 img2 diffnpempty likeimg1 h wimg1shape for y in rangeh for x in rangew if img1y ximg2y x diffy ximg2y ximg1y x else diffy ximg1y ximg2y x returndiffdef differenceimagev2img1 img2 returnnpuint8npabsolutenpint16img1npint16img2def differenceimagev3img1 img2 fast but wrong result returnimg1img2i get these execution times and the sums to check if they are equal 10x 189354 ms npsum26120810x 41171 ms npsum26120810x 2660 ms npsum39123624is there a way to get a correct result faster as with v2,['python'] +1098201,function declaration vs definition c i have a simple code where my functions are declared before main function like thatint function1int function2int main function1xy function2xy int function1int x float y int function2int x float y and after my main function i have definitions of functionsis there some difference when i declare functions before main like this int function1int x float yint function2int x float yint main function1xy function2xy int function1int x float y int function2int x float y,['c'] +1098504,how do i put object to amazon s3 using presigned url i am trying to use signed url to upload images to s3 bucket following is my bucket policy version 20121017 statement sid effect allow principal aws arnawsiam12345678usermyuser arnawsiam12345678root action s3list s3put s3get resource arnawss3mybucket arnawss3mybucket i am generating the signed url from the server as followsvar aws requireawssdkawsconfig accesskeyid myaccesskeyid secretaccesskey mysecretaccesskeyvar s3 new awss3s3getsignedurlputobject bucket mybucket expires 6060 key mykey function err url consolelogurli get the url but when i try to put an object i get the following error error codeaccessdeniedcode messageaccess deniedmessage requestidfxrequestid hostidfxhostiderrorupdate 1here is myusers policy version 20121017 statement sid effect allow principal aws arnawsiam2xusermyuser arnawsiam2xroot action s3 resource arnawss3mybucket arnawss3mybucket update 2i can upload only when following option is set i dont understand whats the use of bucket policy if only the manual selection of permission work update 3 the following code works now the only problem is the signed url binbash file1 bucketmybucket resourcebucketfile contenttypeimagepng datevaluedate r stringtosignputnncontenttypendatevaluenresource s3keyakx s3secretwux signatureecho en stringtosign openssl sha1 hmac s3secret binary base64 curl x put t file h host buckets3amazonawscom h date datevalue h contenttype contenttype h authorization aws s3keysignature httpsbuckets3amazonawscomfile,['javascript'] +1098541,noexcept inheriting constructors and the invalid use of an incomplete type that is actually complete i am not sure if it is a bug of the gcc compiler or the intended behavior of noexceptconsider the following examplestruct b bint noexcept virtual void f 0struct d public b using bb d noexceptnoexceptd42 b42 void f override int main b b new dif the noexcept is removed it compilesanyway as it is in the example i got this error from gcc v531testcpp831 error invalid use of incomplete type astruct da d noexceptnoexceptd42 b42 as far as i know struct d is not an incomplete type but inheriting constructors are involved in the statement and it looks like the compiler is actually considering the completeness of the base struct b more than of dis that the intended behavior or is it legal codefor the sake of clarityhere the compilation succeeds using clang 371here the compilation fails using gcc 530see this link to the bugzilla for the gcc compiler for further detailscurrently the bug is still unconfirmed i will update the question as soon as possible,['c++'] +1098706,fast way to generate pseudorandom bits with a given probability of 0 or 1 for each bit normally a random number generator returns a stream of bits for which the probability to observe a 0 or a 1 in each position is equal ie 50 let us call this an unbiased prngi need to generate a string of pseudorandom bits with the following property the probability to see a 1 in each position is p ie the probability to see a 0 is 1p the parameter p is a real number between 0 and 1 in my problem it happens that it has a resolution of 05 ie it can take the values 0 05 1 15 995 100note that p is a probability and not an exact fraction the actual number of bits set to 1 in a stream of and bits must follow the binomial thistribution bn pthere is a naive method that can use an unbiased prng to generate the value of each bit pseudocodegenerate biased streamn p result for i in 1 to n if random uniform0 1 p resultappend1 else resultappend0 return resultsuch an implementation is much slower than one generating an unbiased stream since it calls the random number generator function once per each bit while an unbiased stream generator calls it once per word size eg it can generate 32 or 64 random bits with a single calli want a faster implementation even it it sacrifices randomness slightly an idea that comes to mind is to precompute a lookup table for each of the 200 possible values of p compute c 8bit values using the slower algorithm and save them in a table then the fast algorithm would just pick one of these at random to generate 8 skewed bitsa back of the envelope calculation to see how much memory is neededc should be at least 256 the number of possible 8bit values probably more to avoid sampling effects let us say 1024 maybe the number should vary depending on p but let us keep it simple and say the average is 1024since there are 200 values of p total memory usage is 200 kb this is not bad and might fit in the l2 cache 256 kb i still need to evaluate it to see if there are sampling effects that introduce biases in which case c will have to be increaseda deficiency of this solution is that it can generate only 8 bits at once even that with a lot of work while an unbiased prng can generate 64 at once with just a few arithmetic instructions i would like to know if there is a faster method based on bit operations instead of lookup tables for example modifying the random number generation code directly to introduce a bias for each bit this would achieve the same performance as an unbiased prngedit march 5thank you all for your suggestions i got a lot of interesting ideas and suggestions here are the top oneschange the problem requirements so that p has a resolution of 1256 instead of 1200 this allows using bits more efficiently and also gives more opportunities for optimization i think i can make this changeuse arithmetic coding to efficiently consume bits from an unbiased generator with the above change of resolution this becomes much easiera few people suggested that prngs are very fast thus using arithmetic coding might actually make the code slower due to the introduced overhead instead i should always consume the worstcase number of bits and optimize that code see the benchmarks belowrici suggested using simd this is a nice idea which works only if we always consume a fixed number of bitsbenchmarks without arithmetic decodingnote as many of you have suggested i changed the resolution from 1200 to 1256i wrote several implementations of the naive method that simply takes 8 random unbiased bits and generates 1 biased bitwithout simdwith simd using the agner fogs vectorclass library as suggested by riciwith simd using intrinsicsi use two unbiased pseudorandom number generatorsxorshift128plusranvec1 mersenne twisterlike from agner fogs libraryi also measure the speed of the unbiased prng for comparison here are the resultsrng ranvec1mersenne twister for graphics processors multiply with carrymethod unbiased with 11 efficiency simdvectorclass incorrect baselinegbpss 16081 16125 16093 gbsnumber of ones 536875204 536875204 536875204theoretical 104857600method biased with 18 efficiencygbpss 0778 0783 0812 gbsnumber of ones 104867269 104867269 104867269theoretical 104857600method biased with 18 efficiency simdvectorclassgbpss 2176 2184 2145 gbsnumber of ones 104859067 104859067 104859067theoretical 104857600method biased with 18 efficiency simdintrinsicsgbpss 2129 2151 2183 gbsnumber of ones 104859067 104859067 104859067theoretical 104857600simd increases performance by a factor of 3 compared to the scalar method it is 8 times slower than the unbiased generator as expectedthe fastest biased generator achieves 21 gbsrng xorshift128plusmethod unbiased with 11 efficiency incorrect baselinegbpss 18300 21486 21483 gbsnumber of ones 536867655 536867655 536867655theoretical 104857600method unbiased with 11 efficiency simdvectorclass incorrect baselinegbpss 22660 22661 24662 gbsnumber of ones 536867655 536867655 536867655theoretical 104857600method biased with 18 efficiencygbpss 1065 1102 1078 gbsnumber of ones 104868930 104868930 104868930theoretical 104857600method biased with 18 efficiency simdvectorclassgbpss 4972 4971 4970 gbsnumber of ones 104869407 104869407 104869407theoretical 104857600method biased with 18 efficiency simdintrinsicsgbpss 4955 4971 4971 gbsnumber of ones 104869407 104869407 104869407theoretical 104857600for xorshift simd increases performance by a factor of 5 compared to the scalar method it is 4 times slower than the unbiased generator note that this is a scalar implementation of xorshiftthe fastest biased generator achieves 49 gbsrng xorshift128plus avx2method unbiased with 11 efficiency incorrect baselinegbpss 18754 21494 21878 gbsnumber of ones 536867655 536867655 536867655theoretical 104857600method unbiased with 11 efficiency simdvectorclass incorrect baselinegbpss 54126 54071 54145 gbsnumber of ones 536874540 536880718 536891316theoretical 104857600method biased with 18 efficiencygbpss 1093 1103 1063 gbsnumber of ones 104868930 104868930 104868930theoretical 104857600method biased with 18 efficiency simdvectorclassgbpss 19567 19578 195 gbsnumber of ones 104836115 104846215 104835129theoretical 104857600method biased with 18 efficiency simdintrinsicsgbpss 19551 19589 19557 gbsnumber of ones 104831396 104837429 104851100theoretical 104857600this implementation uses avx2 to run 4 unbiased xorshift generators in parallelthe fastest biased generator achieves 195 gbsbenchmarks for arithmetic decodingsimple tests show that the arithmetic decoding code is the bottleneck not the prng so i am only benchmarking the most expensive prngrng ranvec1mersenne twister for graphics processors multiply with carrymethod arithmetic decoding floating pointgbpss 0068 0068 0069 gbsnumber of ones 10235580 10235580 10235580theoretical 10240method arithmetic decoding fixed pointgbpss 0263 0263 0263 gbsnumber of ones 10239367 10239367 10239367theoretical 10240method unbiased with 11 efficiency incorrect baselinegbpss 12687 12686 12684 gbsnumber of ones 536875204 536875204 536875204theoretical 104857600method unbiased with 11 efficiency simdvectorclass incorrect baselinegbpss 14536 14536 14536 gbsnumber of ones 536875204 536875204 536875204theoretical 104857600method biased with 18 efficiencygbpss 0754 0754 0754 gbsnumber of ones 104867269 104867269 104867269theoretical 104857600method biased with 18 efficiency simdvectorclassgbpss 2094 2095 2094 gbsnumber of ones 104859067 104859067 104859067theoretical 104857600method biased with 18 efficiency simdintrinsicsgbpss 2094 2094 2095 gbsnumber of ones 104859067 104859067 104859067theoretical 104857600the simple fixed point method achieves 025 gbs while the naive scalar method is 3x faster and the naive simd method is 8x faster there might be ways to optimize andor parallelize the arithmetic decoding method further but due to its complexity i have decided to stop here and choose the naive simd implementationthank you all for the help,"['c++', 'c']" +1099258,set drawable resource id in androidsrc for imageview using data binding in android i am trying to set drawable resource id to androidsrc of imageview using data bindinghere is my objectpublic class recipe implements parcelable public final int imageresource resource id eg rdrawablesome image public final string title public recipeint imageresource string title thisimageresource imageresource thistitle title here is my layoutxml version10 encodingutf8layout xmlnsandroid xmlnsapp data variable namerecipe typecomexampleandroidfivewaystocookeggsrecipe data imageview androidididrecipe image view androidlayout widthmatch parent androidlayout height200dp androidscaletypecentercrop androidsrcrecipeimageresource layoutand finally activity class public class recipeactivity extends appcompatactivity public static final string recipe parcelable recipe parcelable private recipe mrecipe override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate mrecipe getintentgetparcelableextrarecipe parcelable activityrecipebinding binding databindingutilsetcontentviewthis rlayoutactivity recipe bindingsetrecipemrecipe it does not thisplay image at all what am i doing wrongbtw it was perfectly working with standard wayoverrideprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity recipe final imageview recipeimageview imageview findviewbyidridrecipe image view recipeimageviewsetimageresourcemrecipeimageresource,['android'] +1099412,how to create timer in angular2 hi want a timer in angular2 which is tick after a time interval and do some task may be call some functions how to do this with angular2,['javascript'] +1099579,large gap forms between recyclerview items when scrolling down i am making a todo list app and while testing it for some reason a huge gap forms between the items whenever i try to scroll down it always happens whenever i drag and drop the items but i do not see any errors with my itemtouchhelper adapter and callback class it would be awesome if you can help me outbeforeafterrecycleradapterjavapublic class recycleradapter extends recyclerviewadapterrecycleradapterrecyclervh implements itemtouchhelperadapterprivate layoutinflater layoutinflaterarraylistinfo datacontext contextpublic recycleradaptercontext context layoutinflater layoutinflaterfromcontext thiscontext contextpublic void setdataarraylistinfo data thisdata data notifydatasetchangedoverridepublic recyclervh oncreateviewholderviewgroup viewgroup int position view view layoutinflaterinflaterlayoutcustom row viewgroup false viewsetonclicklistenernew viewonclicklistener override public void onclickview v logdra onclick owen onclick method triggered recyclervh recyclervh new recyclervhview return recyclervhoverridepublic void onbindviewholderrecyclervh recyclervh int position logdrecyclerview onbindvh called position final info currentobject datagetposition current info object retrieved for current recyclerview item used for delete recyclervhlisttitlesettextcurrentobjecttitle recyclervhlistcontentsettextcurrentobjectcontent recyclervhlisttitlesetonclicklistenernew viewonclicklistener override public void onclickview v open new activity containing note content toastmaketextthis opening currentobjecttitle toastlength longshow public void deleteitemint position dbinfo dbinfo new dbinfocontext dbinfodeletenotedatagetposition deletes rv itempositions info object dataremoveposition removes info object at specified position notifyitemremovedposition notifies the rv that item has been removedoverridepublic int getitemcount return datasize this is where the swipe and draganddrog methods come into placeoverridepublic boolean onitemmoveint fromposition int toposition swapping positions attempt to understand what is going on here collectionsswapdata fromposition toposition notifyitemmovedfromposition toposition return trueoverridepublic void onitemthismissint position deleting item from rv and db deleteitempositionclass recyclervh extends recyclerviewviewholder implements viewonclicklistener onclicklistener is implemented here can also be added at onbindviewholder above textview listtitle listcontent public recyclervhview itemview superitemview listtitle textview itemviewfindviewbyidridtitle listcontent textview itemviewfindviewbyidridcontent listtitlesetonclicklistenerthis override public void onclickview v toastmaketextcontext opening note getlayoutposition toastlength shortshow ps never add listtitle variable as public variable above which is given value at onbindvh this is because the value will change if item is added or deleted activity mainxmllinearlayout xmlnsandroidxmlnsfabxmlnstoolsandroidlayout widthmatch parentandroidlayout heightmatch parenttoolscontextmainactivityandroidorientationverticalandroidweightsum1androidsupportv7widgettoolbar androidididtoolbar androidlayout widthmatch parent androidlayout heightwrap content androidbackgrounddrawablerounded corners framelayout androidlayout widthmatch parent androidlayout heightmatch parent androidsupportv7widgetrecyclerview androidididrecyclerlist androidlayout widthmatch parent androidlayout heightwrap content relativelayout androidlayout widthfill parent androidlayout heightfill parent commelnykovfabfloatingactionbutton androidididfab add androidlayout widthwrap content androidlayout heightwrap content androidlayout alignparentbottomtrue androidlayout alignparentrighttrue androidlayout alignparentendtrue androidlayout marginbottom16dp androidlayout marginright16dp androidlayout marginend16dp androidgravitybottomend androidonclickaddnote androidsrcdrawablefab ic add fabfab colornormalcolorcolorprimary fabfab colorpressedcolorcolorprimarydark fabfab colorripplecolorcolorprimarydark relativelayoutframelayoutlinearlayoutcustom rowxmlxml version10 encodingutf8relativelayout xmlnsandroidandroidlayout widthmatch parentandroidlayout heightmatch parentlinearlayout androidididmain androidlayout widthwrap content androidlayout heightwrap content textview androidididtitle androidlayout widthmatch parent androidlayout heightwrap content androidlayout gravitycenter vertical androidpadding8dp androidtextstringtest androidtextsize18sp androidtextstylebold linearlayoutlinearlayout androidlayout widthwrap content androidlayout heightwrap content androidlayout belowidmain androidpaddingleft8dp textview androidididcontent androidlayout widthmatch parent androidlayout heightwrap content androidtextstringtest androidtextsize15sp linearlayoutrelativelayoutthank you so much to whoever can help me out i am pulling my hair out as i typeedit i have confirmed that it is not my itemtouchhelper class that is the problem tried running without it being called problem still occursalso it seems that when a dialog is shown and the keyboard brought up the recyclerview in the background resolves the problem by itself after dialog is removed the problem repeats ie scrolling puts massive space between items,['android'] +1099654,invalid drawable tag vector im trying to use vector drawables on pre lollipop devices i did all as instructed here but i still get this crash buildgradlebuildscript repositories jcenter dependencies classpath comandroidtoolsbuildgradle200beta6 apply plugin comandroidapplicationrepositories maven url jcenterandroid compilesdkversion 23 buildtoolsversion 2302 defaultconfig applicationid comtestapp minsdkversion 16 targetsdkversion 22 versioncode 1 versionname 10 vectordrawablesusesupportlibrary true buildtypes release minifyenabled false proguardfiles getdefaultproguardfileproguardandroidtxt proguardrulespro dependencies compile filetreedir libs include jar testcompile junitjunit412 compile comandroidsupportappcompatv72320 compile comandroidsupportdesign2320 compile degreenroboteventbus240 compile degreenrobotgreendao210 compile comafandroidutility1009 compile projectvolleyplus compile project libvlctrianglexml xml version10 encodingutf8selector xmlnsandroid item androiddrawabledrawabletriangle vselectortriangle vxmlvector xmlnsandroid androidheight100dp androidwidth100dp androidviewportheight100 androidviewportwidth100path androidnametriangle androidfillcolorff0 androidpathdatam 500 l 50100 10 zvectorlayoutxml imageview androidlayout widthmatch parent androidlayout heightmatch parent androidbackgrounddrawabletrianglei also tried appsrccompat and in that case drawable just dont show,['android'] +1099676,itunes connect invalid swift support the watch os application has swift libraries at both after archiving and uploading my app using xcode 721 to itunes connect i receive an email from itunes connect sayinginvalid swift support the watch os application has swift libraries at both payloadtodays menuapptodaysreactivemenuwatchapptodaysreactivemenuwatch extensionappexframeworks and payloadtodays menuapptodaysreactivemenuwatchappframeworks remove all of the swift libraries from one of the locations and resubmit your appmy project contains an ios app as well as a watchos app all targets has the flag embedded content contains swift code set to yes as all of my source files are written swift my pod file has the following contentuse frameworks ignore all warnings from all podsinhibit all warningsdef shared pods pod reactivecocoa 401 pod alamofire 314 pod unbox 13endtarget todaysreactivemenu do platform ios 90 shared pods pod fabric 160 pod crashlytics 340 pod purelayout 301endtarget todaysreactivemenutests doendtarget todaysreactivemenuwatch extension do platform watchos 20 shared podsendi am using cocoapods 100beta4 any idea on how i fix this issue,['ios'] +1099793,cannot set the value of readonly property jnifolders on task androidpackagedebug i wanted to open up and project in android studio that i have not worked on in a while but when android studio tries to load the project it fails with this error messageerror21 0 cannot set the value of readonly property jnifolders on task androidpackagedebugi click on the link to the buildgradle and i guess these lines are the problem needed to add jni shared libraries to apk when compiling on clitaskswithtypecomandroidbuildgradletaskspackageapplication pkgtask pkgtaskjnifolders new hashsetfile pkgtaskjnifoldersaddnew fileprojectdir libsi see an answer here google appinvites break build that says to fixed by adding this insteadandroid sourcesets main jnilibssrcdir new filebuilddir lib but the above answer is not very clear i am not sure what line to change and the braces in the answer do not seem to match upi am at a total loss at what to do any help is appreciatedthanks,['android'] +1100455,what is a memoryefficient doubly linked list in c i had come across the term memoryefficient doubly linked list while reading a book on c data structures it just had one line saying that a memoryefficient doubly linked list uses less memory than a normal doubly linked list but does the same job nothing more was explained and no example was given just it was given that this has been taken from a journal and sinha in brackets after searching on google the closest i came to was this but i could not understand anythingcan someone explain me what is a memoryefficient doubly linked list in c how is it different from a normal doubly linked listedit okay i made a serious mistake see the link i had posted above was the second page of the article i did not see that there was a first page and thought the link given was the first page the first page of the article actually gives an explanation but i do not think it is perfect it only talks of the basics concepts of memoryefficient linked list or xor linked list,['c'] +1100752,how to handle java web start jnlp downloading progress in a preloader issuei have a preloader for my application that handles the applicationspecific initialization now i am trying to extend this so that the preloader also shows the progress of the downloaded application jarstldrwhy is the preloader not getting loaded during phase 2 as this should handle the preloaderfxhandleprogressnotification to track the downloading of the jars i supposeupdate 14 march 2016 is using downloadservicelistener the way to solve this how to connect this to a javafx stagedocumentationaccording to oracle there are 4 phases when an application gets launchedphase 1 initialization initialization of java runtime and an initial examination identifies components that must be loaded and executed before starting the applicationduring this phase a splash screen is shown default this is thisphase 2 loading and preparation the required resources are loaded from either the network or a thisk cache and validation procedures occur all execution modes see the default or a custom preloader during this phase my custom preloader should be shownphase 3 applicationspecific initialization the application is started but it may need to load additional resources or perform other lengthy preparations before it becomes fully functional at the moment my custom preloader is shownphase 4 application execution the application is thisplayed and is ready to use in my case a login window is shown and the user can proceedmy casethe first thing i notice is that in phase 2 the default javafx preloader handling the downloading of the application jars is not showing because of this the user gets the feeling the program did not start or terminated prematurely making them to open the jnlp file multiple times once the jars are downloaded we enter phase 3 and the preloader is shownhowever i would like my custom preloader to handle the downloading progress in the progressbar as well phase 2 i made everything as simple as possible to track down which events are happening during the startup of my application this is based on an example of jewelsea and on oracle examplespreloaderpublic class preloaderfx extends preloader stage stage boolean noloadingprogress true public static final string application icon public static final string splash image private pane splashlayout private progressbar loadprogress private label progresstext private static final int splash width 676 private static final int splash height 227 override public void init imageview splash new imageviewnew image splash image loadprogress new progressbar loadprogresetprefwidthsplash width 20 progresstext new labelloading splashlayout new vbox splashlayoutgetchildrenaddallsplash loadprogress progresstext progresstextsetalignmentposcenter splashlayoutsetstyle fxpadding 5 fxbackgroundcolor white fxborderwidth5 splashlayoutseteffectnew dropshadow override public void startstage stage throws exception systemoutprintlnpreloaderfxstart thisstage new stagestagestyledecorated stagesettitletitle stagegeticonsaddnew imageapplication icon stageinitstylestagestyleundecorated final rectangle2d bounds screengetprimarygetbounds stagesetscenenew scenesplashlayout stagesetxboundsgetminx boundsgetwidth 2 splash width 2 stagesetyboundsgetminy boundsgetheight 2 splash height 2 stageshow thisstage stage override public void handleprogressnotificationprogressnotification pn systemoutprintlnpreloaderfxhandleprogressnotification progress pngetprogress application loading progress is rescaled to be first 50 even if there is nothing to load 0 and 100 events can be delivered if pngetprogress 10 noloadingprogress loadprogresetprogresspngetprogress 2 if pngetprogress 0 noloadingprogress false override public void handlestatechangenotificationstatechangenotification evt ignore hide after application signals it is ready systemoutprintlnpreloaderfxhandlestatechangenotification state evtgettype override public void handleapplicationnotificationpreloadernotification pn if pn instanceof progressnotification expect application to send us progress notifications with progress ranging from 0 to 10 double v progressnotification pngetprogress systemoutprintlnpreloaderfxhandleapplicationnotification progress v if noloadingprogress if we were receiving loading progress notifications then progress is already at 50 rescale application progress to start from 50 v 05 v 2 loadprogresetprogressv else if pn instanceof statechangenotification systemoutprintlnpreloaderfxhandleapplicationnotification state statechangenotification pngettype hide after get any state update from application stagehide code that is being handled in phase 3 is from the main application who interacts with the preloader this is what is being seen in the progressbarpublic class mainapp extends application booleanproperty ready new simplebooleanpropertyfalse public static void mainstring args throws exception launchargs override public void startfinal stage initstage throws exception systemoutprintlnmainappstart thismainstage initstage longstart readyaddlistenerobservablevalue extends boolean ov boolean t boolean t1 if booleantrueequalst1 platformrunlater systemoutprintlnmainappshowmainstage showmainstage private void longstart simulate long init in background task task new taskvoid override protected void call throws exception int max 10 for int i 1 i max i threadsleep500 systemoutprintlnlongstart i send progress to preloader notifypreloadernew progressnotificationdouble imax this moves the progress bar of the preloader after init is ready the app is ready to be shown do this before hiding the preloader stage to prevent the app from exiting prematurely readysetvaluebooleantrue notifypreloadernew statechangenotification statechangenotificationtypebefore start return null new threadtaskstart private void showmainstage showing the login window jnlpjnlp spec10 xmlnsjfx codebasepreloadertestjnlp hreflaunchjnlp information information resources j2se version16 href whole bunch of jars jar hreflibpreloader1jar downloadprogress resources security allpermissions security appletdesc width1024 height768 mainclasscomjavafxmainnojavafxfallback namejavafx client param namerequiredfxversion value80 appletdesc jfxjavafxdesc width1024 height768 mainclassguimainapp namejavafx client preloaderclassguipreloaderfx update checkbackgroundjnlpdebuggingi closely watched the java console when launching the file with show logging enabled show tracing thisabled and noticed following thingsduring phase 2 nothing shows up in the java console console closes after this phaseduring phase 3 following output is generated in a new console windowpreloaderfxstartpreloaderfxhandleprogressnotification progress 10preloaderfxhandlestatechangenotification state before loadpreloaderfxhandlestatechangenotification state before initpreloaderfxhandlestatechangenotification state before startmainappstartmainapplongstartlongstart 1preloaderfxhandleapplicationnotification progress 01longstart 2preloaderfxhandleapplicationnotification progress 02longstart 3preloaderfxhandleapplicationnotification progress 03longstart 4preloaderfxhandleapplicationnotification progress 04longstart 5preloaderfxhandleapplicationnotification progress 05longstart 6preloaderfxhandleapplicationnotification progress 06longstart 7preloaderfxhandleapplicationnotification progress 07longstart 8preloaderfxhandleapplicationnotification progress 08longstart 9preloaderfxhandleapplicationnotification progress 09longstart 10preloaderfxhandleapplicationnotification progress 10mainappshowmainstagepreloaderfxhandleapplicationnotification state before startupdates 13 march 2016adjusted the code so the stage passed in the method is used rather than creating a new one and commented out everything related to the noloadingprogress boolean suggested by nhylatedadded some extra systemoutprintln in the mainappsolutionsimple adding jfxjavafxruntime version80 to the jnlp file fixed it with that line added the preloader shows in phase 2 i also took the liberty to change the j2se version16 to j2se version18 the resultthe first 50 is the handling of the jar downloads this is done by the handleprogressnotification method the second 50 is the actual initializing of the mainapp longstart which notifies the preloader done by the handleapplicationnotification,['java'] +1100754,accessing redux store from routes set up via react router i would like to make use of reactrouters onenter handler in order to prompt users to authenticate when entering a restricted routeso far my routesjs file looks something like thisimport react from reactimport route indexroute from reactrouterexport default route path componentapp indexroute componentlanding route pathlearn componentlearn route pathabout componentabout route pathdownloads componentdownloads onenterrequireauth routeideally i would like my requireauth function to be a redux action that has access to the store and current state that works like this storethispatchrequireauthunfortunately i do not have access to the store in this file i do not think i can use really use connect in this case to access the relevant actions that i want i also cannot just import store from the file where the store is created as this is undefined when the app first loads,['javascript'] +1101173,adding touchlistener to path object i have an canvas over which i set a pathpath path new pathpathmoveto1 1pathlineto90 1pathlineto90 60pathlineto1 60canvasdrawpathpathpnow i want to implment a touch listener to this path object i have implemented zooming option on a custom imageview and drawing this lines over a canvas in the ondraw method of this custom imageview so i cant do it by checking the coordinates where user have touched i know that the the path object is not a child of view class and hence i cannot implement a touchlistner in it but the thing the that i exactly need is something likepathsetontouchlistenermytouchlistnerdoes anyone have any idea about how to implement it any help is appreciated,['android'] +1101376,build angular2 html and typescript to a single file i am putting together an app large scale using angular2 and typescript it will need to be divided into numerous projects and each project will have numerous components each with a html view css stylesheet and ts logic classi would like each project to compile to a single js file and be copied to a host website which will run in iis this would be similar to how a wpf or silverlight app is built with the xaml files all getting compiled into the dlli have had a look around the web and am able to get the ts files to build to a single js file using the outfile option but this does not help me with the html files or the cssany help would be greatly appreciated even if it is to say that what i am asking is impossible stephen,"['html', 'css']" +1101444,when should i use access coarse location permission i am building an android app that will track the users geolocation and draw their route on a mapi am using the google play services location api as described hereit is intuitive that my application requires the access fine location permission which i put in the manifestusespermission androidnameandroidpermissionaccess fine locationdo i also need the access coarse location permissionwhats the use case where i need the coarse location,['android'] +1101516,is it possible to get the name of an anonymous javascript function is it possible to get the name of an anonymous function that declared as followsvar f functionat first sight the answer is no but apparently the browsers know and hold the function namevar f functionvar x new fconsolelogxconstructor function ffirefoxvar f functionvar x new fconsolelogx f chromeis this name somehow accessible i need it mainly for error logging so the solution does not have to be crossbrowseredit for clarificationi am getting an objects from external code that i need to know their types therefore obvious answers like using another declaration ways are not what i am searching,['javascript'] +1101722,whats the purpose of the casts to signed int in glibc memmove source codethere they dounsigned long int dstp long int destunsigned long int srcp long int src this test makes the forward copying code be used whenever possible reduces the working set if dstp srcp len unsigned compare copy from the beginning to the end i understand why they go through the trouble of casting to longs in the first place it is to avoid undefined behavior by comparing pointers to probably different objects and they obviously have to use unsigned longs to do the actual comparisonbut why do they cast to long int first then implicitly to unsigned long int,['c'] +1101744,how to initialize multiple variables in c to the same value would this work double a 20x y z 050would the second line of code work properly and initialize x y z each to 050,['c++'] +1101828,alias template partial specialization and the invalid parameter type void consider the following codetemplatetypename fstruct stemplatetypename ret typename argsstruct sretargs templatetypename argsusing alias svoidargsint main svoidint s aliasint aliasit works fine as expected and both the line involving s and the one involving alias define under the hood the same type svoidintnow consider the following changesint main svoidvoid s this line compiles aliasvoid alias this line does noti expected it to compile for reasons that are similar to the ones above mentionedit goes without saying that it does not compile because of the line involving alias instead i get the errorin substitution of template using alias s with args voiderror invalid parameter type voidthe question is pretty simple what i missed here,['c++'] +1102694,which are the new android and languages i am reading the change log of the new android and preview there is something interesting about localesalong with multilocale support android and also expands the range of languages available to users it offers more than 25 variants each for commonly used languages such as english spanish french and arabic it also adds partial support for more than 100 new languagessource languagesdid you guys found a list of those 100 new languages,['android'] +1102758,parentnode being lost on javascript inner closure chrome bug when i execute the below test html page in chrome i see the following in the debug consolehas parent truehas parent falseam i right in assuming that this a chrome bug it does not happen in other browsers or is chrome within its right to do this for some reason it resulted in a bug in one of my web apps and i finally isolated this snippet to repro the core issuehere is the test pagedoctype htmlhtml head meta charsetutf8 titletitle head body class script function testdoodle var testparentel documentcreateelementdiv var testchildel testparentelappendchilddocumentcreateelementdiv documentbodyinnerhtmlhas parent testchildelparentnodebr consoleloghas parent testchildelparentnode settimeoutfunction documentbodyinnerhtmlhas parent testchildelparentnodebr consoleloghas parent testchildelparentnode 20 return testdoodle script bodyhtmledit i should have mentioned that i am testing on windows 7 with chrome 490262387 m 64bit was also able to repro on osx 10112 with chrome 49also i should mention that sometimes it thisplays truetrue and sometimes truefalse you might have to reload the page a few times to witness the issue i am not sure but it is possible that the debug tools console need to be open as wellthanks much,"['javascript', 'html']" +1102801,android and preview emulator crash i am getting this crash on the new android and preview emulator right on the startqemu fatal goldfish tty read bad offset 20rax09 rbx0 rcx0 rdx0rsif817b6c7f rdif88005c3eb0c0 rbpf88005e471bf8 rspf88005e471bb8r8 f88005c6a87f4 r9 0f r10f88005c3eb0 r1101r12fc903e0 r13f88005e750810 r14f88005c3eb0 r150ripf8127a837 rfl010246 zp cpl0 ii0 a201 smm0 hlt0es 0 0 f 0cs 0010 0 f 00a09b00 dpl0 cs64 rass 0018 0 f 00c09300 dpl0 ds wads 0 0 f 0fs 0 0 f 0gs 0 f81a1f0 f 0ldt0 0 f 0tr 0040 f81a1a8c0 02087 08b00 dpl0 tss64busygdt f81a090 07fidt f5790 0fcr08005003b cr2040f6d0 cr305c2a80 cr406b0dr0 dr10 dr20 dr30 dr60f0ff0 dr70400ccs044 ccd0 ccoeflags fcw037f fsw0 st0 ftw00 mxcsr01f80fpr0 fpr10fpr20 fpr30fpr40 fpr50fpr60 fpr70xmm00f00 xmm01031xmm020 xmm030xmm0465675f6f7364765f5f00757063746567 xmm050xmm060 xmm070xmm080 xmm090xmm10 xmm110xmm120 xmm130xmm140 xmm150any thoughts how to fix thisi am on mac os x el capitan,['android'] +1102913,bootstrap date range picker get current date the mouse is hovering over this date picker has the functionality im afterbut im using this plugin how do i get current date the mouse is hovering over for an example if i hover over 23th feb 2016 how do i get the date 23rd getdate doesnt trigger until i click on a date so current date on hover thanks a lotnotei have jqueryui and bootstrap datepicker both on the same page so there was a conflict to resolve the conflict i am using bootstrapdp instead of datepicker my htmldiv classhomecheckin div clasearchformgroup calendar span class datedropdownselect div classinputdaterange inputgroup iddatepicker2 input typetext required readonly classinputgroup formcontrol placeholderddmmy idfromdate namestart span classinputgroupaddonspan input typetext required readonly classinputgroup formcontrol placeholderddmmy idtodate nameend div span divdivmy jsinputdaterangebootstrapdp startdate 0d defaultviewdate 0d format ddmy maxviewmode 3 autoclose true orientation bottom auto thisabletouchkeyboardtrueonchangedate function todatefocus popup up end date calendar var selectedfromdate fromdatebootstrapdpgetdate var selectedtodate todatebootstrapdpgetdate fromvaldateformatselectedfromdateymmdd tovaldateformatselectedtodateymmdd,['jquery'] +1103046,problems after installing java 8 android studio had a popup telling updates was available after i run the sdk manager and started the android studio again i got another popoup that toke me to androids website where it told me that i should upgrade to java jdk 8 and jre 8 after i did i got over 235 errors when try to run the debug i uninstalled version 8 and reinstalled 7u80 jdk and jre now i am down to 34 errors when i type java version i get 18073here are all 35 errors errorjavalangunsupportedclassversionerror comandroiddxcommandmain unsupported majorminor version 520errorjavalangunsupportedclassversionerror comandroiddxcommandmain unsupported majorminor version 520error at javalangclassloaderdefineclass1native methoderror at javalangclassloaderdefineclass1native methoderror at javalangclassloaderdefineclassclassloaderjava800error at javalangclassloaderdefineclassclassloaderjava800error at javasecuritysecureclassloaderdefineclasecureclassloaderjava142error at javasecuritysecureclassloaderdefineclasecureclassloaderjava142error at javaneturlclassloaderdefineclassurlclassloaderjava449error at javaneturlclassloaderdefineclassurlclassloaderjava449error at javaneturlclassloaderaccess100urlclassloaderjava71error at javaneturlclassloaderaccess100urlclassloaderjava71error at javaneturlclassloader1runurlclassloaderjava361error at javaneturlclassloader1runurlclassloaderjava361error at javaneturlclassloader1runurlclassloaderjava355error at javaneturlclassloader1runurlclassloaderjava355error at javasecurityaccesscontrollerdoprivilegednative methoderror at javasecurityaccesscontrollerdoprivilegednative methoderror at javaneturlclassloaderfindclassurlclassloaderjava354error at javaneturlclassloaderfindclassurlclassloaderjava354error at javalangclassloaderloadclassclassloaderjava425error at javalangclassloaderloadclassclassloaderjava425error at sunmisclauncherappclassloaderloadclasslauncherjava308error at sunmisclauncherappclassloaderloadclasslauncherjava308error at javalangclassloaderloadclassclassloaderjava358error at javalangclassloaderloadclassclassloaderjava358error at sunlauncherlauncherhelpercheckandloadmainlauncherhelperjava482error at sunlauncherlauncherhelpercheckandloadmainlauncherhelperjava482errorexception in thread main errorexception in thread main errorexecution failed for task apptransformclasseswithdexfordebug comandroidbuildapitransformtransformexception javalangruntimeexception comandroididecommonprocessprocessexception javautilconcurrentexecutionexception comandroididecommonprocessprocessexception orggradleprocessinternalexecexception process command cprogram filesjavajdk170 80binjavaexe finished with nonzero exit value 1here is the gradelbuildandroid compilesdkversion 23 buildtoolsversion 2400 rc1 defaultconfig applicationid comkimprinter minsdkversion 21 targetsdkversion 23 buildtypes release minifyenabled false proguardfiles getdefaultproguardfileproguardandroidtxt proguardrulestxt compileoptions sourcecompatibility javaversionversion 1 7 targetcompatibility javaversionversion 1 7 productflavors dependencies compile comgoogleandroidgmsplayservicesgcm840 compile comgooglecodegsongson24 compile comandroidsupportsupportv42310 compile comandroidsupportsupportv132310 compile comandroidsupportcardviewv72310 compile comandroidsupportappcompatv72300 compile fileslibsstarioport31jar compile fileslibsstario extensionjarthanks for any help i have been working on this for 6 hours and i can get it to compile,"['java', 'android']" +1103052,whats the difference between sameorigin and nocors for javascripts fetch api i thought same origin implies no cors and viceversa whats the difference between the two options for javascripts fetch apis mode optionalso in the specs it sayseven though the default request mode is nocors standards are highly thiscouraged from using it for new features it is rather unsafewhy is it unsafe source,['javascript'] +1103214,efficient random number generation with c11 i am trying to understand how the c11 random number generation features are meant to be used my concern is performancesuppose that we need to generate a series of random integers between 0k but k changes at every step what is the best way to proceedexamplefor int i0 i n i int k i of course this is more complicated in practice stduniform int thistribution thist0 k int random number thistengine do something with random numberthe thistributions that the random header provides are very convenient but they are opaque to the user so i cannot easily predict how they will perform it is not clear for example how much if any runtime overhead will be caused by the construction of thist aboveinstead i could have used something likestduniform real thistribution thist00 10for int i0 i n i int k i of course this is more complicated in practice int random number stdfloor k1thistengine do something with random numberwhich avoids constructing a new object in each iterationrandom numbers are often used in numerical simulations where performance is important what is the best way to use random in these situationsplease do no answer profile it profiling is part of effective optimization but so is a good understanding of how a library is meant to be used and the performance characteristics of that library if the answer is that it depends on the standard library implementation or that the only way to know is to profile it then i would rather not use the thistributions from random at all instead i can use my own implementation which will be transparent to me and much easier to optimize ifwhen necessary,['c++'] +1103438,thisabling submit button based on fields added with ngbindhtml jsfiddle here i am dynamically creating forms and buttons and want to thisable the buttons if the required form inputs are not completedhtml div ngappchoicesapp ngform namechoicesform ngcontrollerchoicesctrl div ngbindhtmltrustcustomdiv button ngrepeatbutton in buttons ngthisabledchoicesforminvalid buttontext button ngform div javascriptangularmodulechoicesapp ngsanitize controllerchoicesctrl scope sce functionscope sce scopecustom required input input required typetext scopetrustcustom function return scetrustashtmlscopecustom scopebuttons textsubmit 1 textsubmit 2choicesforminvalid is false and does not change when entering text into the input fieldsolutioni ended up using the angularbindhtmlcompile directive from here here is the relevant bit of working codengform namechoicesform div ngifchoices bindhtmlcompilechoicesdiv button ngclicksubmitform ngthisabledchoicesforminvalid submit buttonngformand choices might be a snippit of html like thisdivstrongwhat is your sexstrongdivdiv input typeradio namegender ngmodelgender valuefemale required label forfemale femalelabelbr input typeradio namegender ngmodelgender valuemale required label formale malelabeldiv,"['javascript', 'html']" +1103457,webservice change method response without notifying clients let us assume i have a webservice which returns a class on all methods informing the client the status of the process for examplepublic class wsresult string result either error or oknow wed like to add a property to this class without forcing all clients consuming our service to update their software is this possiblefor examplepublic class wsresult public string result either error or ok public guid someidentifieri am looking for answers on both wcf and asmx,['.net'] +1103513,about c3js chart data split since i am not familiar with c3js library i am bit confuse when i tried to split the array datafor instant i have some array value from a json var jsondata123455622 var jsondatanameappleorangebananapeari tried to pass the first array jsondata into the chart but these values go into the same column which is not something i would like to seei want these array value become independent data and push the name into it please see the demo i made and the result i want should looks likeupdate the json data format name apple data value 1434 name banana data value 342,"['javascript', 'jquery']" +1103533,replace dll refs with project refs for project dependencies in visual studio c solution is it possible to programmatically replace dll refs with project refs for project dependencies in visual studio cvbnet solutionbackgroundi am working with some legacy code where dependencies for each project are mostly referenced as compiled dlls instead of including project reference from corresponding project in solution or even worse referenced straight from gac right now i have to manually remove each dll reference and replace it with project reference from vs ui for each solution out of dozens projectsediting the projectsolution xml csprojsln files is not straightforward due to guidstypical dll referenceitemgroup reference includemydll version2010 cultureneutral publickeytoken1b6d1e0267e1acba processorarchitecturemsil specificversionfalsespecificversion hintpathmydlldllhintpath referenceitemgrouptypical project referenceitemgroup projectreference includemydllmydllcsproj project3cc278303d6b407185e55a4006f142project namemydllname projectreferenceitemgroup,"['c#', '.net']" +1103569,how to intercept object creation in java lower than user class level i am looking towards some approach where by using java agent or instrumenting classes preferably something at lower level than user classes to intercept all object creation in jvm new or any alternative ways to create object there is a similar question which does not focus on java agent or something lower than instrumenting user classes,['java'] +1103709,python iterate through list of list to make a new list in index sequence how would you iterate through a list of lists such as1234 56 789and construct a new list by grabbing the first item of each list then the second etc so the above becomes this1 5 7 2 6 8 3 9 4,['python'] +1103714,android and requires the ide to be running with java 18 or later my xml layout is not rendering with this error message i am already using java 8also using latest build tools in gradleandroid compilesdkversion androidn buildtoolsversion 2400 rc1 xml error,['android'] +1103748,add multiplication signs between coefficients i have a program in which a user inputs a function such as sinx1 i am using ast to try to determine if the string is safe by whitelisting components as shown in this answer now i would like to parse the string to add multiplication signs between coefficients without them for example3x 3x4x5 4x5sin3x4 sin3x4 sin is already in globals otherwise this would be sin3x4are there any efficient algorithms to accomplish this i would prefer a pythonic solution ie not complex regexes not because they are pythonic but just because i do not understand them as well and want a solution i can understand simple regexes are ok i am very open to using sympy which looks really easy for this sort of thing under one condition safety apparently sympy uses eval under the hood i have got pretty good safety with my current partial solution if anyone has a way to make sympy safer with untrusted input i would welcome this too,['python'] +1103949,how can i generate an apk that can run without server with reactnative i have built my app i can run it on my local emulator and also on my android device within the same network by changing debug serverhowever i want to build an apk that i can send to someone without access to development server and i want them to be able to test applicationi see there is a section using offline bundle on ios section of the documentation but i could not figure out how to accomplish same for android is this possible if so howupdate on the answer to this question react native android failed to load js bundle it is said that offline bundle can be downloaded from development server but when i obtain the bundle from development server the image files cannot be loaded,['android'] +1104061,convert pdf ver 17 to ver 16 by using php only i am working on api which gives me pdfver 17 in response and my project is using zend pdf library which does not support parsing of pdf version 17 so i have decided to convert pdf version to make compatible with zend pdfis there any way to convert pdf version to older version using phpthanks,['php'] +1104092,extracting attributes from images using scikitimage i have been using scikitimage to classify road features with some success see below i am having trouble doing the next step which is to classify the features for example let us say these features are located in the box 600 800 and 1400 600the code i am using to extract the information isfrom skimage import io segmentation as segcolor image ioimreadimg pltrcparamsimagecmap spectrallabels segsliccolor image and segments6 compactness4the objective is to have a table in the following formimage feature type starting pixel ending pixel001 a 600 600 1300 700 002 b 600 600 1100 702 undefined 700 700 900 800feature type would be based on colours ideally shoulders would be one colour trees and brush would be another etchow can i extract the data i need ie have scikit break the image into different components where i know the location of each component i can then pass each component to a classifier which will identify what each component is thanks,['python'] +1104130,why the enumerator of list is public what is the reason for the public access modifier on the enumerator in listi would expect private modifier instead of publiclist source code,"['c#', '.net']" +1104644,error running basic tensorflow example i have just reinstalled latest tensorflow on ubuntu sudo pip install upgrade x86 64whlsudo password for ubuntu the directory homeubuntucachepiphttp or its parent directory is not owned by the current user and the cache has been thisabled please check the permissions and owner of that directory if executing pip with sudo you may want sudos h flagthe directory homeubuntucachepip or its parent directory is not owned by the current user and caching wheels has been thisabled check the permissions and owner of that directory if executing pip with sudo you may want sudos h flagcollecting tensorflow071 from x86 64whl downloading x86 64whl 138mb 100 a 138mb 32kbs requirement already uptodate six1100 in usrlocallibpython27thistpackages from tensorflow071requirement already uptodate protobuf300b2 in usrlocallibpython27thistpackages from tensorflow071requirement already uptodate wheel in usrlocallibpython27thistpackages from tensorflow071requirement already uptodate numpy182 in usrlocallibpython27thistpackages from tensorflow071requirement already uptodate setuptools in usrlocallibpython27thistpackages from protobuf300b2tensorflow071installing collected packages tensorflow found existing installation tensorflow 071 uninstalling tensorflow071 successfully uninstalled tensorflow071successfully installed tensorflow071when following the directions to test it fails with cannot import name pywrap tensorflow ipythongittensorflowtensorflow init py in module 21 from future import print function 22 23 from tensorflowpython import gittensorflowtensorflowpython init py in module 43 default dlopen flags sysgetdlopenflags 44 syssetdlopenflags default dlopen flags ctypesrtld global 45 from tensorflowpython import pywrap tensorflow 46 syssetdlopenflags default dlopen flags 47 importerror cannot import name pywrap tensorflowis there an additional change needed to my python or ubuntubash environment,['python'] +1104689,how can a char pointer be initialized with a string array of characters but an int pointer not with an array of integer how can char pointer be initialized with a string array of characters but an int pointer not with a array of integerwhen i tried thisint a12345it gives an error saying error scalar object a requires one element in initializerbut char namemikhilworks perfectly,"['c++', 'c']" +1104862,reactnative android genymotion adb server did not ack i am working with reactnative android and genymotion on mac when i run reactnative runandroid i get this lines at the end of the launch operation045440 eadb error could not install smartsocket listener address already in use045440 eadb adb server did not ack045440 eddms userspaulbrielibraryandroidsdkplatformtoolsadbstartserver failed run manually if necessary045440 eadb failed to start daemon 045440 eadb error cannot connect to daemonappinstalldebug failedfailure build failed with an exception what went wrongexecution failed for task appinstalldebug comandroidbuildertestingapideviceexception timeout getting device listhowever adb devices returns thislist of devices attached192168591015 deviceso far i have found no solution to run my app on the emulator has anyone encountered the same issuethankspaul,['android'] +1104881,c thread safety map reading i am working on a program that needs stdmap and specifically one like this mapstringmapstringint it is meant to be something like bank change rates the first string is the original currency and the one in the second map is the desired one and the int is their rate this whole map will be read only do i still need mutexes i am a bit confused about the whole thread safety since this is my first bigger multithreaded program,['c++'] +1105133,prime factorization of a positive integer with streams i am currently trying to incorporate the stream api of java 8 into my everyday java toolbox i am trying to use streams to find the prime factors of a positive integer and then store each of the factors in an arrayor arraylist with their multiplicity in a parallel array alternatively i am trying to create a stream of say factorwithmultiplicity objects or even a map with the factor as the key and the multiplicity as the value it would be nice if the factors were sorted in ascending order and if it could even handle very large numbers such as dare i say longmax valuecurrently my code looks like this but as i am a beginner with streams i am sure there is a faster or better suited way to accomplish this task please use streams to create your solution although if you know that some nonstream solution is faster feel free to point me to that code alsoint num getpositiveintarraylistinteger factors new arraylistarraylistinteger multiplicities new arraylistboolean isprime intstreamrangeclosed2 num 2 reducenum int temp int factor int count 0 while temp factor 0 temp factor count if count 0 factorsaddfactor multiplicitiesaddcount return temp 1,['java'] +1105361,java issue initializing class with type parameters i am having an issue initializing a class with type parameter it seems to be a shortcoming of javas type inference and i would like to know if there is a way around this or a better way of achieving thispublic class parentmodel public class childmodel extends parentmodel public class servicee extends parentmodel t extends collectione private classt classoft private classe classofe public serviceclasse classofe classt classoft thisclassofe classofe thisclassoft classoft public class businesslogic public void somelogic servicechildmodel arraylistchildmodel service new servicechildmodel arraylistchildmodelchildmodelclass arraylistclass compiletime error is in businesslogicsomelogicthe constructor servicechildmodel arraylistchildmodelclasschildmodel classarraylist is undefinedcompiled to java 7,['java'] +1105507,how to calculate the index of the tile underneath the mouse in an isometric world taking into account tile elevation i have a tilebased isometric world and i can calculate which tile is underneath specific mouse coordinates by using the following calculationsfunction isoto2dptpointpoint var tempptpoint new point0 0 tempptx 2 pty ptx 2 temppty 2 pty ptx 2 returntempptfunction gettilecoordinatesptpoint tileheightnumberpoint var tempptpoint new point0 0 tempptx mathfloorptx tileheight temppty mathfloorpty tileheight returntemppttaken from this is a flash implementation but the maths is the samehowever my problem comes in when i have tiles that have different elevation levelsin these scenarios due to the height of some tiles which have a higher elevation the tiles or portions of tiles behind are covered up and should not be able to be selected by the mouse instead selecting the tile which is in front of ithow can i calculate the tile by mouse coordinates taking into account the tiles elevationi am using a javascript and canvas implementation,['javascript'] +1105547,bigger fonts on smaller screens without media queries or javascript is there an alternative for media queries to accomplish fontsize inversely proportional to the screen size eg opposite effect of 2vw where the font gets smaller on small screensmy first try was divide a value by a viewport width increment but fontsize calc10vw 2 works while fontsize calc100 2vw unfortunately does not workscodepen of my first try,['css'] +1105638,how to use group by to count a new category and old categories at once for example i have data like this group money a 100 a 200 b 100 b 300 b 110i want to use group byore something else to summarize my data like this group money average count a 300 150 2 b 510 170 3 c 810 162 5which group c means group abis there any way to get the outcome in some simple way,"['mysql', 'sql']" +1105816,javascript save ajax result in as class variable i know that javascript does not use class at least not in common sense i will like to know how to return and save an ajax return value in a class variable rather than calling multiple methods within the callbackvar reader function initialize some variables thisdata nullreaderprototypemakeajaxcall functionurlpath make and ajax call and return some value ajaxsuccessfunctiondata thisdata data readerprototypesearchdata functionparam needs access to thisdatareaderprototypefinddata functionid needs access to thisdatareaderprototypedeleteitem functionid needs access to thisdatain the above code whatever function that needs access to the data property needs to be called within the ajax success callback so if i have ten methods that need data i will have to line all of them up within the callback which i do not feel is right how do i minimise the number of functions in the callback and ensure in some other ways that the function is successful and data is saved the instance variable data,"['javascript', 'jquery']" +1106000,transaction management with spring and hibernate make inactive transactions i am managing a java web application with spring and hibernatei use spring and hibernate tools to handle the persistence level so i do not need to commitrollback my transactionsthe application is concurrent so the users can modify the same records and i decided to use read committed as isolation levelthe problem is sometimes i find jdbc errors in the log and all the next requests go in the same error blocking the application behaviourthese are the components involved in the transaction managementbean public springlocalsessionfactorybean sessionfactorydatasource datasource springlocalsessionfactorybean bean new springlocalsessionfactorybean beansetconfiglocationnew classpathresourcehibernatecfgxml beansetdatasourcedatasource return bean bean public hibernatetransactionmanager transactionmanagersessionfactory sessionfactory hibernatetransactionmanager tm new hibernatetransactionmanager tmsetsessionfactorysessionfactory return tm in the db session monitor when this stuff happens i got an inactive transactionthe error i get is the followingwarn sqlexceptionhelperjava144 sql error 0 sqlstate null14032016 154606 error sqlexceptionhelperjava146 connection oraclejdbcdrivert4cconnection1a6d7ad6 is closed14032016 154606 error autocompletercontrollerjava73 could not prepare statementorghibernateexceptiongenericjdbcexception could not prepare statement at orghibernateexceptioninternalstandardsqlexceptionconverterconvertstandardsqlexceptionconverterjava54 at orghibernateenginejdbcspisqlexceptionhelperconvertsqlexceptionhelperjava126 at orghibernateenginejdbcinternalstatementpreparerimplstatementpreparationtemplatepreparestatementstatementpreparerimpljava196 at orghibernateenginejdbcinternalstatementpreparerimplpreparequerystatementstatementpreparerimpljava160 at orghibernateloaderloaderpreparequerystatementloaderjava1885 at orghibernateloaderloaderexecutequerystatementloaderjava1862 at orghibernateloaderloaderexecutequerystatementloaderjava1839 at orghibernateloaderloaderdoqueryloaderjava910caused by javasqlsqlexception connection oraclejdbcdrivert4cconnection1a6d7ad6 is closed at orgapachetomcatdbcpdbcpdelegatingconnectioncheckopendelegatingconnectionjava398 at orgapachetomcatdbcpdbcpdelegatingconnectionpreparestatementdelegatingconnectionjava279 at orgapachetomcatdbcpdbcppoolingdatasourcepoolguardconnectionwrapperpreparestatementpoolingdatasourcejava313 at orghibernateenginejdbcinternalstatementpreparerimpl5dopreparestatementpreparerimpljava162 at orghibernateenginejdbcinternalstatementpreparerimplstatementpreparationtemplatepreparestatementstatementpreparerimpljava186 97 morethe problem is the transactions and the connections should be automatically opened and closed and i expect that transactions that should fail for concurrent modification to get a rollback but it seems they get inactivei attach my hibernate configxml version10 encodingutf8doctype hibernateconfiguration public hibernatehibernate configuration dtd 30enhibernateconfiguration sessionfactory property namehibernatedialectorghibernatedialectoracle10gdialectproperty property namehibernatehbm2ddlautoupdateproperty property namehibernateconnectionisolation2property thisable the secondlevel cache property namehibernatecacheuse second level cachefalseproperty property namehibernateidnew generator mappingstrueproperty property namehibernateconnectionautocommitfalseproperty show and print nice sql on stdout property namehibernateshow sqlfalseproperty property namehibernateformat sqlfalseproperty property namehibernateuse sql commentsfalseproperty property namehibernategenerate statisticsfalseproperty sessionfactoryhibernateconfigurationas connection library i use ojdbcany help will be appreciated i do not know where to check anymoreps i add that this error spawns like once every 2 daysedit just another integration this is what i have on my serverxml could it be related to something here resource namejdbctoolsfdb globaljdbctoolsfdb authcontainer typejavaxsqldatasource driverclassnameoraclejdbcoracledriver urljdbcoraclethinoracle01internallocal1521orcl01 usernametools passwordmypwd maxactive10 maxidle2 minidle1 suspecttimeout60 timebetweenevictionrunsmillis30 minevictableidletimemillis60 validationqueryselect 1 from dual validationinterval30 testonborrowtrue removeabandonedtrue removeabandonedtimeout60 abandonwhenpercentagefull10 maxwait10 maxage60,['java'] +1106008,cordova android error building one of the platforms error code 1 for command i have just had a cordova project land on my lap and i have been tasked with building the apps and getting them on the stores ios worked fine but now i have hit a wall with androidso every time i build by running cordova build android im getting the following errorfailure build failed with an exception what went wrongexecution failed for task processdebugresources comandroididecommonprocessprocessexception orggradleprocessinternalexecexception process command userssprincelibraryandroidsdkbuildtools2302aapt finished with nonzero exit value 1 tryrun with stacktrace option to get the stack trace run with info or debug option to get more log outputbuild failedtotal time 8432 secserror building one of the platforms error code 1 for command userssprincedocumentsprojectsprojnameplatformsandroidgradlew with args cdvbuilddebugbuserssprincedocumentsprojectsprojnameplatformsandroidbuildgradledorggradledaemontruepandroidusedeprecatedndktrueyou may not have the required environment or os to build this projecterror error code 1 for command userssprincedocumentsprojectsprojnameplatformsandroidgradlew with args cdvbuilddebugbuserssprincedocumentsprojectsprojnameplatformsandroidbuildgradledorggradledaemontruepandroidusedeprecatedndktruei have been googling around and had a good search through stack and most responses are saying do a clean and rebuild i have done this a few times now and had no luck i have checked and i have all the sdks tools etc installedany ideas any help would be much appreciated,['android'] +1106085,casting c str only works for short strings i am using a c library in c and wrote a wrapper at one point i need to convert an stdstring to a cstyle string there is a class with a function which returns a string casting the returned string works if the string is short otherwise not here is a simple and reduced example illustrating the issueinclude iostreaminclude stringclass stringbox public stdstring getstring const return text stringboxstdstring text text textprivate stdstring text int mainint argc char argv const unsigned char caststring null stdstring somestring i am a long string would not work stdstring somestring hello this one works stringbox boxsomestring caststring const unsigned char boxgetstringc str stdcout caststring caststring stdendl return 0executing the file above prints this to the consolecaststringwhereas if i swap the commenting on somestring it correctly printscaststring hellohow is this possible,['c++'] +1106107,addthis plugin can not exclude services in mobile tool box i have implemented the addthis share box following their instructions i would like to only include the following services in the share tool box which works fine on the desktop browser but is simply ignored on mobile which means that every service is shown on the mobile version of the share boxanyone else encountered this issue what can be done to fix itscript src widgetjsscriptscript srcscriptdiv clashare btnpress me to test sharingdivscriptvar addthis config services expanded facebooktwitteremailtumblrlinksinaweibowhatsappshare btnonclick function addthisupdateshare url addthis sendtomorescriptjsfiddle test link,"['javascript', 'jquery', 'html']" +1106154,systemiofileloadexception when signing application i have a wpf application that follows the mvvm pattern we recently signed the app and now i am getting a lot of first chance exceptions on startup i have traced the problem to the followingin any view if i reference another namespace with in the application when the view is initialized i get the error could not load file or assembly myapplication version30591724348 cultureneutral publickeytokenx or one of its dependencies the located assemblys manifest definition does not match the assembly reference exception from hresult 0x80131040myapplication version30591724348 cultureneutral publickeytokenxits always looking for a version that is 1 behind the version that i am actually runningif i remove the references to the other namespaces from the views the initializecomponent does not throw the errorviewusercontrol xclassmyapplicationviewdiagnosticsview xmlns xmlnsx xmlnsmc xmlnsd xmlnsconvertclrnamespacemyapplicationconverters causes error xmlnsbehaveclrnamespacemyapplicationbehaviors causes error xmlnscontrolsclrnamespacemyapplicationusercontrols causes errorif i remove these references and move my converters and behaviors into another dll and then reference them through the dll there is no problem the errors go away also if i do not sign the application i do not get the errors i do not really want to have to reference these things in a different dll it seems like this should work fine it also spends about 30 seconds throwing all of these errors as all of the views are created so i am taking a hit on performance i dont get why the application is trying to load itself and why its trying to load an older version of itself no matter how many times i build the error is always 1 version behindfusion log assembly binder log entry 3172016 103011 am the operation failedbind result hr 0x80131040 no description availableassembly manager loaded from cwindowsmicrosoftnetframeworkv4030319clrdllrunning under executable ctfsdevelopmentdevfeaturesrcmyapplicationbindebugmyapplicationexe a detailed error log follows prebind state information log thisplayname myapplication version30592015594 cultureneutral publickeytokenx fullyspecifiedlog appbase filectfsdevelopmentdevfeaturesrcmyapplicationbindebuglog initial privatepath nulog dynamic base nulog cache base nulog appname myapplicationexecalling assembly presentationframework version40 cultureneutral publickeytoken31bf3856ad364e35log this bind starts in default load contextlog using application configuration file ctfsdevelopmentdevfeaturesrcmyapplicationbindebugmyapplicationexeconfiglog using host configuration file log using machine configuration file from cwindowsmicrosoftnetframeworkv4030319configmachineconfiglog postpolicy reference myapplication version30592015594 cultureneutral publickeytoken7b0591cb18d2a932log gac lookup was unsuccessfullog attempting download of new url filectfsdevelopmentdevfeaturesrcmyapplicationbindebugmyapplicationdlog attempting download of new url filectfsdevelopmentdevfeaturesrcmyapplicationbindebugmyapplicationmyapplicationdlog attempting download of new url filectfsdevelopmentdevfeaturesrcmyapplicationbindebugbinmyapplicationdlog attempting download of new url filectfsdevelopmentdevfeaturesrcmyapplicationbindebugbinmyapplicationmyapplicationdlog attempting download of new url filectfsdevelopmentdevfeaturesrcmyapplicationbindebugmyapplicationexelog assembly download was successful attempting setup of file ctfsdevelopmentdevfeaturesrcmyapplicationbindebugmyapplicationexelog entering runfromsource setup phaselog assembly name is myapplication version30592015596 cultureneutral publickeytoken7b0591cb18d2a932wrn comparing the assembly name resulted in the mismatch revision numbererr the assembly reference did not match the assembly definition founderr runfromsource setup phase failed with hr 0x80131040err failed to complete setup of assembly hr 0x80131040 probing terminated,['c#'] +1106235,webpack loader equivalent of requirejs plugin load with xmlhttprequest i have a pair of requirejs plugins that i would like to replace with a webpack loaderdefinefirstloader load function name parentrequire onload config var xhr new xmlhttprequest xhraddeventlistenerload function onloadthisresponsetext xhraddeventlistenererror onloaderror xhraddeventlistenerabort onloaderror var url name xhropenget url xhrsend definejsonloader load function name parentrequire onload config this is the nasty part reqfirstloader name function text try onloadjsonparsetext catch err onloaderrorerr the biggest problems are the lack of promises for the async request and the dynamic require is there a way around this without transpilation with systemload or additional libraries bluebird etc editso i have taken a crack at this and now i am getting an error module not found error cannot resolve futureurlwhen i go to requirejsonloaderfutureurl does webpack allow loaders to operate at runtime heres the updated codefirstpluginjsmoduleexports function loadasync content callback var host documentlocationhost var url host name xhraddeventlistenerload function callbacknull thisresponsetext xhropenget url xhrsend jsonpluginjsmoduleexports function content callback requirefirstplugin content function result callbacknull jsonparseresult,['javascript'] +1106534,variadic template function with more than two parameters i have the following example where two parameters t1 and t2 are usedtemplatetypename tbool comparet t1 t t2 return t1 t2templatetypename t typename args bool comparet t1 t t2 args args return t1 t2 compareargsint mainvoid compare1 1 string stringfunction compare takes pairs of parameters that are the same type and can be comparedtwo pairs are compared then parameter pack is passed recursively until the last two parameters are reachedto stop recursion i use an implementation of compare function without parameter packi would like add the third argument t3 so function compare should be like thistemplatetypename tbool comparet t1 t t2 t t3 return t1 t2 t3templatetypename t typename argsbool comparet t1 t t2 t t3 args args return t1 t2 t3 compareargsint mainvoid compare1 1 1 string string stringi expect that this function takes three parameters to comparison then next three are processed recursivelywhen i try to compile this code i obtain the following errorxsourcecpp4 error c2446 no conversion from const char to int1 xsourcecpp4 note there is no context in which this conversion is possible1 xsourcecpp10 note see reference to function template instantiation bool compareconst chart being compiled1 with1 1 tconst char 1 1 xsourcecpp15 note see reference to function template instantiation bool compareintconst charconst charconst chartconst char const char const char being compiled1 with1 1 tint1 1xsourcecpp4 error c2040 int differs in levels of indirection from const char how to implement this function to compare the sets of three parameters of the same type,['c++'] +1106550,matching image and determine best match using surf i have been trying to use the emgu example surffeature to determine if an image is in a collection of images but i am having problems understanding how to determine if a match was foundoriginal image scene 1 matchscene 2 no matchi have been looking at the documentation and spent hours looking for a possible solution on how to determine if the images are the sameas you can see in the following pics a match is found for both its clear that the one i am trying to find gets more matches lines connecting but how do i check this in the code question how do i filter out the good matchmy goal is to be able to compare an input image capture from webcam with a collection of images in a database but before i can save all images to the db i need to know what values i can compare the input to eg save the objectkeypoints in the dbhere is my sample code the matching partprivate void match test long matchtime using mat modelimage cvinvokeimreadimagesinputjpg loadimagetypegrayscale using mat observedimage cvinvokeimreadimages2jpg loadimagetypegrayscale mat result drawmatchesdrawmodelimage observedimage out matchtime imageviewershowresult stringformatmatched using 0 in 1 milliseconds cudainvokehascuda gpu cpu matchtime ib outputimage result label7text stringformatmatched using 0 in 1 milliseconds cudainvokehascuda gpu cpu matchtime public static void findmatchmat modelimage mat observedimage out long matchtime out vectorofkeypoint modelkeypoints out vectorofkeypoint observedkeypoints vectorofvectorofdmatch matches out mat mask out mat homography int k 2 double uniquenessthreshold 09 double hessianthresh 800 stopwatch watch homography null modelkeypoints new vectorofkeypoint observedkeypoints new vectorofkeypoint using umat umodelimage modelimagetoumataccesstyperead using umat uobservedimage observedimagetoumataccesstyperead surf surfcpu new surfhessianthresh extract features from the object image umat modeldescriptors new umat surfcpudetectandcomputeumodelimage null modelkeypoints modeldescriptors false watch stopwatchstartnew extract features from the observed image umat observeddescriptors new umat surfcpudetectandcomputeuobservedimage null observedkeypoints observeddescriptors false match the two surf descriptors bfmatcher matcher new bfmatcherthistancetypel2 matcheraddmodeldescriptors matcherknnmatchobserveddescriptors matches k null mask new matmatchessize 1 depthtypecv8u 1 masksettonew mcvscalar255 features2dtoolboxvoteforuniquenessmatches uniquenessthreshold mask int nonzerocount cvinvokecountnonzeromask if nonzerocount 4 nonzerocount features2dtoolboxvoteforsizeandorientationmodelkeypoints observedkeypoints matches mask 15 20 if nonzerocount 4 homography features2dtoolboxgethomographymatrixfrommatchedfeaturesmodelkeypoints observedkeypoints matches mask 2 watchstop matchtime watchelapsedmillisecondsi really have the feeling i am not far from the solution hope someone can help me out,['c#'] +1106597,can i legally use a struct with overloaded operator as compare for stdupper bound i have structs like this types simplified to carry over the point living in a stdvectorstruct region int first int count struct metadata region metadatain the vector they are ordered by first if you add first and count you get the first of the next region so basically this vector of structs describes metadata for contiguous ranges of numbersnow given an integer i want to look up the metadata as the regions are sorted i can use stdupper bound i implemented it this waystruct comp inline bool operatorconst region region int index const return regionfirst index inline bool operatorint index const region region const return index regionfirst this works when calling stdupper bound withauto iter stdupper boundm regionsbegin m regionsend index compnow this happens to work because upper bound can internally pick the overload which matches its requirements as it calls both compregion int and compint region which is the reason why a const region reg int indexa would not work i actually came up with the solution by tracing down the error messages when using the lambda i mentioned before the docs for stdupper bound at cppreferencecom write about the fourth argumentcomparison function object ie an object that satisfies the requirements of compare which returns atrue if the first argument is less than the secondthe signature of the comparison function should be equivalent to the followingbool cmpconst type1 a const type2 bthe signature does not need to have const but the function object must not modify the objects passed to it the types type1 and type2 must be such that an object of type t can be implicitly converted to both type1 and type2 and an object of type forwardit can be dereferenced and then implicitly converted to both type1 and type2the type type1 must be such that an object of type t can be implicitly converted to type1 the type type2 must be such that an object of type forwardit can be dereferenced and then implicitly converted to type2 a cppreference has been fixed since i posted this question thanks tchere t is the third argument to stdupper bound and forwardit is the type of the first two arguments this quote does not talk about the function object actually being a struct which overloads its operator to cover the forward and reverse situationsso in rulesaswritten is this legal or is it an artifact of my specific compilerstandard library combination g 531i am interested in answers specific to c14 or c17full exampleinclude algorithminclude iostreaminclude vectorstruct region regionint first int count int n firstfirst countcount nn int first int count int n think struct metadatastruct comp inline bool operatorconst region region int index const return regionfirst index inline bool operatorint index const region region const return index regionfirst int main stdvectorregion regions regionsemplace back0 10 1 regionsemplace back10 10 2 regionsemplace back20 10 3 const int lookup 10 auto iter stdupper bound regionsbegin regionsend lookup comp yes i omitted error checking here with error being iter regionsbegin stdcout lookup is in region with and iter1n stdendl,['c++'] +1107533,firstletter selector ie11 has a different layout compared to firefox i am trying to style a title with firstletter css selector but i have strange layout resulting in internet explorer 11the code is quite simple jsfiddleh2titolopaginafirstletter color 1d5987 thisplay block float left fontfamily bell mt important fontsize 70px margintop 15px paddingright 3pxh2titolopagina span borderbottom 7px solid 1d5987 color 538cc3 fontfamily bell mt important fontsize 30px important letterspacing 0 marginleft 4px paddingbottom 5px normalizecss v303 mit license githubcomnecolasnormalizecss 1 set default font family to sansserif opinionated 2 prevent ios and ie text size adjust after device orientation change without thisabling user zoom html fontfamily sansserif 1 mstextsizeadjust 100 2 webkittextsizeadjust 100 2 remove default margin opinionated body margin 0 html5 thisplay definitions correct block thisplay not defined for any html5 element in ie 89 correct block thisplay not defined for details or summary in ie 1011 and firefox correct block thisplay not defined for main in ie 11 articleasidedetailsfigcaptionfigurefooterheadermainmenunavsectionsummary thisplay block 1 correct inlineblock thisplay not defined in ie 89 2 normalize vertical alignment of progress in chrome firefox and opera audiocanvasprogressvideo thisplay inlineblock 1 verticalalign baseline 2 prevent thisplaying audio without controls in mobile safari 4567 audionotcontrols thisplay none height 0 address hidden styling not present in ie 8910 hide the template element in ie 891011 safari and firefox 22 hiddentemplate thisplay none links remove the gray background color from active links in ie 10 a backgroundcolor transparent improve readability of focused elements when they are also in an activehover state opinionated aactiveahover outlinewidth 0 textlevel semantics address inconsistent styling of abbrtitle 1 correct styling in firefox 39 and opera 12 2 correct missing styling in chrome edge ie opera and safari abbrtitle borderbottom none 1 textdecoration underline 2 textdecoration underline dotted 2 address inconsistent styling of b and strong 1 correct duplicate application of bolder in safari 602 2 correct style set to bold in edge 12 safari 62 and chrome 18 bstrong fontweight inherit 1 bstrong fontweight bolder 2 address styling not present in safari and chrome dfn fontstyle italic address variable h1 fontsize and margin within section and article contexts in firefox 4 safari and chrome h1 fontsize 2em margin 067em 0 address styling not present in ie 89 mark backgroundcolor ff0 color 0 address inconsistent and variable font size in all browsers small fontsize 80 prevent sub and sup affecting lineheight in all browsers subsup fontsize 75 lineheight 0 position relative verticalalign baselinesup top 05emsub bottom 025em embedded content remove border when inside a element in ie 8910 img border 0 correct overflow not hidden in ie 91011 svgnotroot overflow hidden grouping content address margin not present in ie 89 and safari figure margin 1em 40px address inconsistent styling of hr 1 correct boxsizing set to borderbox in firefox 2 correct overflow set to hidden in ie 891011 and edge 12 hr boxsizing contentbox 1 height 0 1 overflow visible 2 contain overflow in all browsers pre overflow auto 1 correct inheritance and scaling of fontsize for preformatted text 2 address odd emunit font size rendering in all browsers codekbdpresamp fontfamily monospace monospace 1 fontsize 1em 2 forms known limitation by default chrome and safari on os x allow very limited styling of select unless a border property is set 1 correct font properties not being inherited 2 address margins set differently in firefox 4 safari and chrome buttoninputoptgroupselecttextarea font inherit 1 margin 0 2 address overflow set to hidden in ie 891011 button overflow visible address inconsistent texttransform inheritance for button and select all other form control elements do not inherit texttransform values correct button style inheritance in firefox ie 891011 and opera correct select style inheritance in firefox buttonselect texttransform none 1 avoid the webkit bug in android 40 where 2 destroys native audio and video controls 2 correct inability to style clickable input types in ios 3 improve usability and consistency of cursor style between imagetype input and others buttonhtml inputtypebutton 1 inputtyperesetinputtypesubmit webkitappearance button 2 cursor pointer 3 reset default cursor for thisabled elements buttonthisabledhtml inputthisabled cursor default remove inner padding and border in firefox 4 buttonmozfocusinnerinputmozfocusinner border 0 padding 0 restore focus style in firefox 4 unset by a rule above buttonmozfocusringinputmozfocusring outline 1px dotted buttontext address firefox 4 setting lineheight on input using important in the ua stylesheet input lineheight normal it is recommended that you do not attempt to style these elements firefoxs implementation does not respect boxsizing padding or width 1 address box sizing set to contentbox in ie 8910 2 remove excess padding in ie 8910 inputtypecheckboxinputtyperadio boxsizing borderbox 1 padding 0 2 fix the cursor style for chromes incrementdecrement buttons for certain fontsize values of the input it causes the cursor style of the decrement button to change from default to text inputtypenumberwebkitinnerspinbuttoninputtypenumberwebkitouterspinbutton height auto address appearance set to searchfield in safari and chrome inputtypesearch webkitappearance textfield remove inner padding and search cancel button in safari and chrome on os x safari but not chrome clips the cancel button when the search input has padding and textfield appearance inputtypesearchwebkitsearchcancelbuttoninputtypesearchwebkitsearchdecoration webkitappearance none define consistent border margin and padding fieldset border 1px solid c0c0c0 margin 0 2px padding 035em 0625em 075em 1 correct color not being inherited from fieldset in ie 891011 2 remove padding so people are not caught out if they zero out fieldsets legend color inherit 1 padding 0 2 remove default vertical scrollbar in ie 891011 textarea overflow auto restore font weight unset by a rule above note the default cannot safely be changed in chrome and safari on os x optgroup fontweight boldh2 classtitolopagina spantitlespanh2with mozilla firefox the first letter is base aligned with the underline while with internet explorer 11 it is 15px lowerwhat am i missing,"['html', 'css']" +1107855,casperjs why does my url change to aboutblank when my page is loaded i am a beginner at phantomjscasperjsi just want to start a session and verify that it is okheres my codevar casper requirecaspercreate verbose true loglevel debug pagesettings loadimages false loadplugins false useragent mozilla50 windows nt 100 wow64 applewebkit53736 khtml like gecko chrome390217171 safari53736 edge120 casperonremotemessage functionmsg thisechoremote message caught msgcasperonpageerror functionmsgtrace thisechopage error msg errorcasperstartcasperthenfunction consolelogpage loaded thistestasserttitlegoogle welcome to googlecasperrunwhen i run this simple script i get cusersbookydocumentsnike projectcasperjs ignoresslerrorstrue sslprotocoltlsv1 debugjscusersbookydocumentsnike projectinfo phantom startinginfo phantom running suite 3 stepsdebug phantom opening url http getdebug phantom navigation requested url typeother willnavigatetrue ismainframetruedebug phantom url changed to debug phantom successfully injected casper clientside utilitiesdebug phantom start page is loadedinfo phantom step anonymous 33 http 200page loadeddebug phantom navigation requested urlaboutblank typeother willnavigatetrue ismainframetruedebug phantom url changed to aboutblanki searched everywhere and i have not found any response to my problemenvironmentphantomjs 211casperjs 110beta5,['javascript'] +1108201,jquery objects can hold notdom objects analyzing the code showed by this so question i just noticed the way it is using jquery to iterate a json arraydataeachfunction while in my mind an array should rather be iterated this wayeachdata function indeed the jqueryeach manual page statesthe each function is not the same as selectoreach which is used to iterate exclusively over a jquery objectbut since the op seemed to have his code at least partially working i was curious to test and thiscovered that it workshere is the proofvar data key value1 key value2 key value3dataeachfunction documentwritebr thiskeyscript srcscriptso if dataeach works when data is a json array it seems to mean that this array is an acceptable content for data to return a jquery objectthen pursuing the investigation i checked the jqueryelementarray manual page and looked at the jquery elementarray section which stateselementarray type array an array containing a set of dom elements to wrap in a jquery objectaccording with the above an array of objects instead of dom elements should failso i tested to compare the objects returned by either this data and a simple body here is the resultvar data key value1 key value2 key value3function logobj init for var prop in obj if objhasownpropertyprop var row trdataprop prop if rowlength row tr dataprop prop th prop thtr appendtotable if init rowappendtdtd rowappendtd jsonstringifyobjpropsubstr025 td logbody truelogdata falsetable bordercollapse collapse border 1px solid 0th td border 1px solid 0 padding 5pxscript srcscripttable tr thpropertyth thbodyth thdatath trtableactually it appears that everything can be converted to a jquery objecti am puzzled am i reinventing the wheel,['jquery'] +1108333,why is not arraynewinstanceclass int generic i mean is there any good reason for that the methods got the following signaturepublic static object newinstanceclass componenttype int length throws negativearraysizeexceptionin my opinion it would be much more convinient to declare the method as followspublic static t t newinstanceclasst componenttype int length throws negativearraysizeexceptionthat way when creating an aray of generic type it would not be neccesary to perform additional casting egpublic class gent private t a public static t gent createbyclassclasst clazz a clazzcastarraynewintanceclazzgetcomponenttype 8 we have to invoke clazzcast here was there any good reason to declare the return value type as object to me it seems very incovinient,['java'] +1108407,laravel 52 get linux system environment variables is there a possibility to get some linux system environment variables and still use the env variableswe want to use an autogenerated database password that is set as linux environment variable but cannot get laravel to find the linux system environment variables,['php'] +1108435,deduce type from literal string i want to deduce the parameter types of a function from an string similar to what printf doescurrently i do the followinginclude utility calculate the length of a literal stringconstexpr int lengthconst char str return str 1 lengthstr 1 0struct ignore template char c1 char c2struct type typedef ignore type d inttemplate struct typed typedef int type f floattemplate struct typef typedef float type get type from stringtemplate const char const const str int pos int and lengthstrposstruct gettype typedef ignore typetemplate const char const const str int posstruct gettypestr pos 2 typedef typename typestrpos0strpos1type type my dummy classtemplate typename targsstruct foo void sendtargs const deduce type for each literal string arraytemplate const char const strs stdsize t n stdsize t indexconstexpr auto parseitstdindex sequenceindex return footypename gettypestrs indextypetemplate const char const strs stdsize t nconstexpr auto makefooconst char const an return parseitstrs 2stdmake index sequencenthe problem is i have to write ignore on my function callconstexpr const char message d hello f goodconstexpr auto foo makefoomessagemessageint main foo send10 ignore 200f ignore return 0live examplewhat i want is something like compiletime check onlymyfoo food hello world f sfoosend10 20f hello,['c++'] +1108436,integration issue to tesstwo tesseract tools for androidlibrary into an android studio and build ndk i want to import tesstwo library in android studio and after compilation it show error in ndk build i have already tries solution given on stackoverflow like execution failed for task appcompiledebugndkbut it did not resolved my issue please suggest me where i am doing wrongit show the following error errorerror undefined reference to isnanferrorerror undefined reference to isinfferrorerror undefined reference to isnanfarm64v8a install libteso libsarm64v8alibtesoerrorerror undefined reference to isnanferrorerror undefined reference to isinfferrorerror undefined reference to isnanfx86 64 install libjpgtso libsx86 64libjpgtsoerrorerror linker command failed with exit code 1 use v to see invocationerrorerror linker command failed with exit code 1 use v to see invocationmake objlocalarmeabiv7alibteso error 1make waiting for unfinished jobsmake objlocalarmeabilibteso error 1make leaving directory docrtesstwomastertesstwomastertesstwotesstwondkbuild failederrorexecution failed for task tesstwondkbuildprocess command dsdksdkndkbundlendkbuildcmd finished with nonzero exit value 2,"['android', 'c++', 'c']" +1108627,deprecated retrieve service locator in functional system zf2 i am developing a zf2 system and it was working very well but after i clone the repository in other computer this deprecated error has appearedyou are retrieving the service locator from within the class modulecontrollercontroller please be aware that servicelocatorawareinterface is deprecated and will be removed in version 30 along with the servicelocatorawareinitializer you will need to update your class to accept all dependencies at creation either via constructor arguments or setters and use a factory to perform the injections in homepathprojectvendorzendframeworkzendmvcsrccontrollerabstractcontrollerphp on line 258the composerjsonrequire php 55 extcurl extjson extmbstring zendframeworkzendframework 25 doctrinedoctrineormmodule 0 hounddogdoctrinedatafixturemodule 00 imagineimagine 050the error appears when i retrieve the service in my controllers extending zendmvccontrollerabstractactioncontrollerthisgetservicelocatorgetmoduleserviceservicein the zend core at zendmvccontrollerabstractcontroller is like thispublic function getservicelocator trigger errorsprintf you are retrieving the service locator from within the class s please be aware that servicelocatorawareinterface is deprecated and will be removed in version 30 along with the servicelocatorawareinitializer you will need to update your class to accept all dependencies at creation either via constructor arguments or setters and use a factory to perform the injections get classthis e user deprecated return thisservicelocatorbefore was only thispublic function getservicelocator return thisservicelocatori have tried everything someone know what i have to do,['php'] +1108643,lazy onetoone spring jpa and building dynamic json i am developing a relatively large project using spring boot and in a general way i am pretty happy with it but i am having some problems that in my mind shouldt be a problemfirst of all onetoone relationship it is frustrating that it does not work as it should at least in my mindi have two entities user and userprofile for example they have onetoone relationship but most of the time i only need the user data but it fetches no matter what i try and oh boy i tried the world suggestions on every post for 5 pages of googleso there is my first question is there a way to be able to lazy fetch onetoone relationship in jpa and spring because most of the posts are more than 23 years oldthe other problem i have is about to build a json response in a dynamic way i did some stuff using rails and was very happy with jbuilder or even the to json that gave me the ability to build the json response depending on the controller and my needs at the momentin spring i saw the following solutionsjackson jsonview which does not solve entirely my problem because the responses are not that static and a attribute cannot be assigned to multiple views as far as i understood the conceptsetting to null attributes that i do not want on the response using this but is just too ugly and looks like a wrong walkthroughor building hashmap like i build jsonjbuilder on rails but this kills my performance as sometimes it has relationships so a lot of for to build the json and also this looks like a ugly walkthroughi am looking for some directions from someone that someday may have encountered one of this problems because it is killing me not being able so solve problems that in my mind should not be this hardedit 1already tried to add optional false on the onetoone annotation to solve the eager load of onetoone relationship as snovelli suggested exampleonetooneoptionalfalse fetch fetchtypelazypublic userprofile getuserprofile,['java'] +1109325,tablayout crashing after updating support library to 2321 everything was working fine until i updated my gradle file and now my tablayout is crashing due to errorjavalangnoclassdeffounderror failed resolution of landroidsupportv7widgettintmanager at androidsupportdesignwidgettablayouttabviewtablayoutjava1185 at androidsupportdesignwidgettablayoutcreatetabviewtablayoutjava656 at androidsupportdesignwidgettablayoutaddtabviewtablayoutjava695 at androidsupportdesignwidgettablayoutaddtabtablayoutjava386 at androidsupportdesignwidgettablayoutaddtabtablayoutjava361 at androidsupportdesignwidgettablayoutsettabsfrompageradaptertablayoutjava645 at androidsupportdesignwidgettablayoutsetupwithviewpagertablayoutjava616 at comexamplescrollabletabsactivityoncreatescrollabletabsactivityjava307 at androidappactivityperformcreateactivityjava6033 at androidappinstrumentationcallactivityoncreateinstrumentationjava1106 at androidappactivitythreadperformlaunchactivityactivitythreadjava2288 at androidappactivitythreadhandlelaunchactivityactivitythreadjava2397 at androidappactivitythreadaccess800activitythreadjava151 at androidappactivitythreadhhandlemessageactivitythreadjava1310 at androidoshandlerthispatchmessagehandlerjava102 at androidoslooperlooplooperjava135 at androidappactivitythreadmainactivitythreadjava5268 at javalangreflectmethodinvokenative method at javalangreflectmethodinvokemethodjava372 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava902 at comandroidinternaloszygoteinitmainzygoteinitjava697 caused by javalangclassnotfoundexception did not find class androidsupportv7widgettintmanager on path dexpathlistzip file dataappcomexample1baseapknativelibrarydirectoriesvendorlib systemlib at dalviksystembasedexclassloaderfindclassbasedexclassloaderjava56 at javalangclassloaderloadclassclassloaderjava511 at javalangclassloaderloadclassclassloaderjava469 at androidsupportdesignwidgettablayouttabviewtablayoutjava1185 at androidsupportdesignwidgettablayoutcreatetabviewtablayoutjava656 at androidsupportdesignwidgettablayoutaddtabviewtablayoutjava695 at androidsupportdesignwidgettablayoutaddtabtablayoutjava386 at androidsupportdesignwidgettablayoutaddtabtablayoutjava361 at androidsupportdesignwidgettablayoutsettabsfrompageradaptertablayoutjava645 at androidsupportdesignwidgettablayoutsetupwithviewpagertablayoutjava616a here is my gradle fileapply plugin comandroidapplicationandroid compilesdkversion 23buildtoolsversion 2302defaultconfig applicationid comexample minsdkversion 11 targetsdkversion 23 versioncode 1 versionname 10buildtypes release minifyenabled false proguardfiles getdefaultproguardfileproguardandroidtxt proguardrulespro dependencies compile filetreedir libs include jartestcompile junitjunit412compile comandroidsupportappcompatv72321compile comandroidsupportdesign2320compile comandroidsupportcardviewv72321compile comandroidsupportrecyclerviewv72321compile commcxiaokevolleylibrary10aarcompile comgithubhotchemistringpicker002compile fileslibsdevsmartlibjarcompile comnineoldandroidslibrary240compile comdaimajiaeasinglibrary101aarcompile comdaimajiaandroidanimationslibrary113aarcompile projectlibplease help me where am wrong,"['java', 'android']" +1109379,how to change a part of paragraphs color i have a draggable div that is under a blue paragraph i wanna change the part of paragraph color that is on div like the image belowand here is my codeshtmlheadscript documentreadyfunction div1draggable scriptstyle div1 position absolute top 10px left 20px background black width 200px height 200px cursor move p1 position absolute top 100px left 200px color blue styleheadbody div iddiv1div p idp1some textpbodyhtmljsfiddle,"['javascript', 'jquery', 'css']" +1109897,what can be said about the value of fundamental type members of moved from object during move construction consider this codefoo f1foo f2 stdmovef1 i would expect the member values of f1 to no longer necessarily hold the values given by the default constructor however testing with multiple compilers using this implementation of foo suggests otherwiseclass foopublic foo default foofoo default stdstring s foo bool t true bool f false after the move f1t is always true and f1f is always false as described in this question i would expect the values to either be nondeterministic or that both boolean values would have the same value however they seem to get the same value they would get from the default constructorlive example with gccis this just a implementation details of my compilers by coincidence the same or is this in the standard,['c++'] +1110171,pretty url via htaccess using any number of parameters actually i have this urlparam1value1param2value2param3value3but i want to have this url formatso the contact goes to variable getsite and rest of parameters should be able to access via getparam1 getparam2 etc the problem is it has to work with any number of parameters there could be param4 or even param50 or any other name of parameter is it possible via htaccess to cover all these cases,['php'] +1110290,failed to lazily initialize a collection of role userauthorities could not initialize proxy no session in my spring bootdatajpa application i have a following entityentitynamedentitygraphname graphuser attributenodes namedattributenodeauthorities tablename userspublic class user extends baseentity implements userdetails private static final long serialversionuid 84184875433252086l id sequencegeneratorname users id seq sequencename users id seq allocationsize 1 generatedvaluestrategy generationtypeauto generator users id seq private long id jsonignore manytomanyfetch fetchtypelazy jointablename users authorities joincolumns joincolumnname user id inversejoincolumns joincolumnname authority id private setauthority authorities new hashsetauthoritythis is my spring authenticationservice servicepublic class authenticationservice implements userdetailsservice autowired private userservice userservice override public userdetails loaduserbyusernamestring username throws usernamenotfoundexception user user userservicefindbyusernameusername if user null throw new usernamenotfoundexceptionstringformatuser s does not exist username return user during the application startup i am receiving following exceptionorghibernatelazyinitializationexception failed to lazily initialize a collection of role comexamplecommonmodeluseruserauthorities could not initialize proxy no session at orghibernatecollectioninternalabstractpersistentcollectionthrowlazyinitializationexceptionabstractpersistentcollectionjava576 at orghibernatecollectioninternalabstractpersistentcollectionwithtemporarysessionifneededabstractpersistentcollectionjava215 at orghibernatecollectioninternalabstractpersistentcollectioninitializeabstractpersistentcollectionjava5 at orghibernatecollectioninternalabstractpersistentcollectionreadabstractpersistentcollectionjava143 at orghibernatecollectioninternalpersistentsetiteratorpersistentsetjava180 at orgspringframeworksecurityauthenticationabstractauthenticationtokeninitabstractauthenticationtokenjava61 at orgspringframeworksecurityauthenticationusernamepasswordauthenticationtokeninitusernamepasswordauthenticationtokenjava72 at orgspringframeworksecurityauthenticationdaoabstractuserdetailsauthenticationprovidercreatesuccessauthenticationabstractuserdetailsauthenticationproviderjava224 at orgspringframeworksecurityauthenticationdaoabstractuserdetailsauthenticationproviderauthenticateabstractuserdetailsauthenticationproviderjava196 at orgspringframeworksecurityauthenticationprovidermanagerauthenticateprovidermanagerjava167 at orgspringframeworksecurityauthenticationprovidermanagerauthenticateprovidermanagerjava192 at orgspringframeworksecuritywebauthenticationusernamepasswordauthenticationfilterattemptauthenticationusernamepasswordauthenticationfilterjava93 at orgspringframeworksecuritywebauthenticationabstractauthenticationprocessingfilterdofilterabstractauthenticationprocessingfilterjava217 at orgspringframeworksecuritywebfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava330 at orgspringframeworksecuritywebauthenticationlogoutlogoutfilterdofilterlogoutfilterjava120 at orgspringframeworksecuritywebfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava330 at orgspringframeworksecuritywebheaderheaderwriterfilterdofilterinternalheaderwriterfilterjava64 at orgspringframeworkwebfilteronceperrequestfilterdofilteronceperrequestfilterjava107 at orgspringframeworksecuritywebfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava330 at orgspringframeworksecuritywebcontextsecuritycontextpersistencefilterdofiltersecuritycontextpersistencefilterjava91 at orgspringframeworksecuritywebfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava330 at orgspringframeworksecuritywebcontextrequestasyncwebasyncmanagerintegrationfilterdofilterinternalwebasyncmanagerintegrationfilterjava53 at orgspringframeworkwebfilteronceperrequestfilterdofilteronceperrequestfilterjava107 at orgspringframeworksecuritywebfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava330 at orgspringframeworksecuritywebfilterchainproxydofilterinternalfilterchainproxyjava213 at orgspringframeworksecuritywebfilterchainproxydofilterfilterchainproxyjava176 at orgspringframeworkwebfilterdelegatingfilterproxyinvokedelegatedelegatingfilterproxyjava346 at orgspringframeworkwebfilterdelegatingfilterproxydofilterdelegatingfilterproxyjava262 at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava240 at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava207 at orgspringframeworkwebfiltercharacterencodingfilterdofilterinternalcharacterencodingfilterjava121 at orgspringframeworkwebfilteronceperrequestfilterdofilteronceperrequestfilterjava107 at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava240 at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava207 at orgspringframeworkbootactuateautoconfiguremetricsfilterdofilterinternalmetricsfilterjava103 at orgspringframeworkwebfilteronceperrequestfilterdofilteronceperrequestfilterjava107 at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava240 at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava207 at orgapachecatalinacorestandardwrappervalveinvokestandardwrappervalvejava212 at orgapachecatalinacorestandardcontextvalveinvokestandardcontextvalvejava106 at orgapachecatalinaauthenticatorauthenticatorbaseinvokeauthenticatorbasejava502 at orgapachecatalinacorestandardhostvalveinvokestandardhostvalvejava141 at orgapachecatalinavalveserrorreportvalveinvokeerrorreportvalvejava79 at orgapachecatalinacorestandardenginevalveinvokestandardenginevalvejava88 at orgapachecatalinaconnectorcoyoteadapterservicecoyoteadapterjava522 at orgapachecoyotehttp11abstracthttp11processorprocessabstracthttp11processorjava1095 at orgapachecoyoteabstractprotocolabstractconnectionhandlerprocessabstractprotocoljava672 at orgapachetomcatutilnetnioendpointsocketprocessordorunnioendpointjava1500 at orgapachetomcatutilnetnioendpointsocketprocessorrunnioendpointjava1456 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava1142 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava617 at orgapachetomcatutilthreadstaskthreadwrappingrunnableruntaskthreadjava61 at javalangthreadrunthreadjava745how to configure my application in order to correctly handle userauthorities with fetchtypelazy,['java'] +1110360,how can i detectavoid autoboxing in java i am working on a program that deals constantly with gigabytes of data mostly primitives and strings i need to avoid having the primitives converted to objects by autoboxing as this explodes the heap size and gctime currently i make changes and run the code in visualvm and see i have millions of extra integers or shorts or objects then i step through the code in a debugger into my libraries and jdk classes to find where the boxing occurs is there tooling to help with this i use intellij as my ide in intellij you can use an inspection to find the autoboxing in your own code but it does not seem to extend to library code to do so select from the menu analyzye run inspection by name then type in auto at the prompt an autoboxing inspection should appear for selectionhowever at this point i have removed essentially all autoboxing from my own code what i need is to be able to find out when i pass a primitive into a library method is the library code autoboxing the primitive at any point,['java'] +1110629,how to get corners using gpuimageharriscornerdetectionfilter i am trying to get the corner points from a still image using gpuimageharriscornerdetectionfilter i have looked at the example code from the project i have looked at the documentation and i have looked at this post that is about the same thing gpuimage harris corner detection on an existing uiimage gives a black screen outputbut i cannot make it work and i have a hard time understanding how this is supposed to work with still imageswhat i have at this point is thisfunc harriscorners cgpoint var points cgpoint let stillimagesource gpuimagepicture gpuimagepictureimage selfimage let filter gpuimageharriscornerdetectionfilter filtercornersdetectedblock cornerarrayunsafemutablepointerglfloat cornersdetecteduint frametimecmtime in for index in 0intcornersdetected pointsappendcgpointxcgfloatcornerarrayindex 2 ycgfloatcornerarrayindex 2 1 filterforceprocessingatsizeselfimagesize stillimagesourceaddtargetfilter stillimagesourceprocessimage return pointsthis function always returns so it is obviously not workingan interesting detail i compiled the filtershowcaseswift project from gpuimage examples and the filter fails to find very clear corners like on a sheet of paper on a black background,['ios'] +1110763,using custom marshaller in f i have been toying with marshalling in f recently and to my surprise i ended up with error fs0980 custom marshallers cannot be specified in f code consider using a c helper functiononly information regarding the topic that i managed to find is f 40 spec page 300 when applied to a parameter or return type specifies the marshalling attribute for a cli pinvoke stub declaration this attribute may be used in both f and imported assemblies however f does not support the specification of custom marshallersi am mostly interested in reasons behind lack of custom marshallers support as i can live with introducing c assembly to projectcan anyone clarify on thiseditsample code as requestedstructlayoutlayoutkindsequential pack1type basic struct struct marshalasattributeunmanagedtypecustommarshalermarshaltypereftypedefofdatetimemarshaller val timevardword endfrom what i noticed just setting unmanagedtypecustommarshaler is enough to cause compile time exception,['.net'] +1110968,nomethoderror undefined method on for mainobject when i try to bundle exec cap production deploy trace i get an error messagedeployh2540559wappsfoodsoft bundle exec cap production deploy trace invoke production first time execute production invoke loaddefaults first time execute loaddefaults invoke rvmhook first time execute rvmhookcap abortednomethoderror undefined method on for mainobjectusrlocalrvmgemsruby200p643gemscapistranorvm012libcapistranotasksrvmrake17in block 2 levels in top requiredusrlocalrvmgemsruby200p643gemsrake1libraketaskrb248in callusrlocalrvmgemsruby200p643gemsrake1libraketaskrb248in block in executeusrlocalrvmgemsruby200p643gemsrake1libraketaskrb243in eachusrlocalrvmgemsruby200p643gemsrake1libraketaskrb243in executeusrlocalrvmgemsruby200p643gemsrake1libraketaskrb187in block in invoke with call chainusrlocalrvmrubiesruby200p643libruby200monitorrb211in mon synchronizeusrlocalrvmgemsruby200p643gemsrake1libraketaskrb180in invoke with call chainusrlocalrvmgemsruby200p643gemsrake1libraketaskrb173in invokeusrlocalrvmgemsruby200p643gemscapistrano321libcapistranodsltask enhancementsrb12in block in afterusrlocalrvmgemsruby200p643gemsrake1libraketaskrb248in callusrlocalrvmgemsruby200p643gemsrake1libraketaskrb248in block in executeusrlocalrvmgemsruby200p643gemsrake1libraketaskrb243in eachusrlocalrvmgemsruby200p643gemsrake1libraketaskrb243in executeusrlocalrvmgemsruby200p643gemsrake1libraketaskrb187in block in invoke with call chainusrlocalrvmrubiesruby200p643libruby200monitorrb211in mon synchronizeusrlocalrvmgemsruby200p643gemsrake1libraketaskrb180in invoke with call chainusrlocalrvmgemsruby200p643gemsrake1libraketaskrb173in invokeusrlocalrvmgemsruby200p643gemsrake1librakeapplicationrb150in invoke taskusrlocalrvmgemsruby200p643gemsrake1librakeapplicationrb106in block 2 levels in top levelusrlocalrvmgemsruby200p643gemsrake1librakeapplicationrb106in eachusrlocalrvmgemsruby200p643gemsrake1librakeapplicationrb106in block in top levelusrlocalrvmgemsruby200p643gemsrake1librakeapplicationrb115in run with threadsusrlocalrvmgemsruby200p643gemsrake1librakeapplicationrb100in top levelusrlocalrvmgemsruby200p643gemsrake1librakeapplicationrb78in block in runusrlocalrvmgemsruby200p643gemsrake1librakeapplicationrb176in standard exception handlingusrlocalrvmgemsruby200p643gemsrake1librakeapplicationrb75in runusrlocalrvmgemsruby200p643gemscapistrano321libcapistranoapplicationrb15in runusrlocalrvmgemsruby200p643gemscapistrano321bincap3in top requiredusrlocalrvmgemsruby200p643bincap23in loadusrlocalrvmgemsruby200p643bincap23in mainusrlocalrvmgemsruby200p643binruby executable hooks15in evalusrlocalrvmgemsruby200p643binruby executable hooks15in maintasks top rvmhookhere is my gemfile a sample gemfilesource gem rails 42gem sassrailsgem coffeerailsgem lessrailsgem uglifier 103 see for more supported runtimesgem therubyracer platforms rubygem jqueryrailsgem select2railsgem rails tokeninputgem bootstrapdatepickerrailsgem date time attributegem railsassetslistjs 020beta4 remember to maintain listjs plugins and template engines on updategem i18njs 300rc8gem railsi18ngem mysql2gem prawngem prawntablegem hamlrailsgem kaminarigem simple formgem inherited resourcesgem localize input git gitgithubcombennibulocalize inputgitgem daemonsgem twitterbootstraprails 228gem simplenavigation 3140 3x for simple navigation bootstrapgem simplenavigationbootstrapgem ransackgem acts as treegem railssettingscachedgem resquegem whenever require false for defining cronjobs see configschedulerbgem protected attributesgem rubyunitsgem attribute normalizergem ice cube github wvengenice cube branch issues50from icalrebased fork until mergedgem recurring selectgem roo 1132gem spreadsheet we use the git version of acts as versioned and need to include it in this gemfilegem acts as versioned github technoweenieacts as versionedgem foodsoft wiki path pluginswikigem foodsoft messages path pluginsmessages plugins not enabled by defaultgem foodsoft uservoice path pluginsuservoicegroup production do gem exception notificationendgroup development do gem sqlite3 gem mailcatcher gem webconsole 20 allow to use debugger gem pryrescue gem prystack explorer better error output gem better errors gem binding of caller gem railsi18ndebug chrome debugging extension panel gem meta request get infos when not using proper eager loading gem bullet hide assets requests in log gem quiet assets deploy with capistrano gem capistrano 320 require false gem capistranorvm require false gem capistranobundler 110 require false gem capistranorails require false avoid having contentlength warnings gem thinendgroup development test do gem rubyprof require falseendgroup test do gem rspecrails gem factory girl rails gem faker gem capybara webkit and poltergeist do not seem to work yet gem seleniumwebdriver gem database cleaner gem connection pool need to include rspec components before i18nspec or rake fails in test environment gem rspeccore 32 gem rspecrerun gem rspeclegacy formatters gem i18nspec code coverage gem simplecov require false gem coveralls require falseendmy capfile load dsl and setup up stagesrequire capistranosetup includes default deployment tasksrequire capistranodeploy includes tasks from other gems included in your gemfile for documentation on these see for example require capistranorvm require capistranorbenv require capistranochruby require capistranobundlerrequire capistranorailsassetsrequire capistranorailsmigrations loads custom tasks from libcapistranotasks if you have any defineddirgloblibcapistranotaskscaprakeeach r import r and also my deployrb capistrano 3 deployment configuration defaults that can be updated from the environmentset branch envrevision envbranch name master you probably want to change theseset application foodsoft application name whatever you likeset domain biomiogiessende hostset user deploy ssh deploy userset keep releases 10set repo url gitgithubcomfoodcoopsfoodsoftgitset deploy to wappsfetch applicationfetch stage more settings which are probably okset log level infoset linked files wconfigdatabaseyml configapp configyml configinitializerssecret tokenrb configinitializerssession storerbset linked dirs wbin log tmppids tmpcache tmpsockets vendorbundle publicsystem assuming one server for everything with one user for deploy and one for resqueserver fetchdomain user fetchuser roles web app resque db if you use rvm uncomment the line in capfile and optionally uncomment rvm settings set rvm ruby string local task hooksnamespace deploy do desc restart application task restart do on rolesapp in sequence wait 5 do tell mod passenger to reload the application execute touch release pathjointmprestarttxt end end after restart resquerestart after finishing deploycleanup see libcapistranotaskspluginscap before bundlerinstall enable pluginsautoenddoes anyone know how to fix this thank you very muchmaxi,"['ruby-on-rails', 'ruby']" +1111365,android jobscheduler executing several times i am using the below code to create and schedule a job using androids jobscheduler apilogdhanif scheduling periodic job 2 hrs with 20 mins backoff linearjobinfo jobinfo new jobinfobuilderjob id new componentnamegetapplicationcontext myjobserviceclass setperiodictimeunithourstomillis2 setrequireschargingtrue setrequirednetworktypejobinfonetwork type any setbackoffcriteriatimeunitminutestomillis20 jobinfobackoff policy linear buildjobscheduler scheduler jobscheduler getsystemservicecontextjob scheduler serviceschedulerschedulejobinfoie a periodic job which executes every 2 hours and a linear back off policy which executes 20 min number fails in case the job failsmy job service code is written as belowpublic class myjobservice extends jobservice override public boolean onstartjobjobparameters jobparameters logdhanif onstartjob new myworkergetapplicationcontext this jobparametersexecute return true override public boolean onstopjobjobparameters jobparameters logdhanif onstopjob return true private static class myworker extends asynctaskvoid void boolean private final context mcontext private final myjobservice mjobservice private final jobparameters mjobparams public myworkercontext context myjobservice myjobservice jobparameters jobparameters mcontext context mjobservice myjobservice mjobparams jobparameters override protected boolean doinbackgroundvoid voids logdhanif work start for int i0 i9 i int counter prefsgetcountermcontext logdhanif work done counter counter if counter 3 logdhanif do reschedule prefsresetcountermcontext return true logdhanif do not reschedule prefsincreasecountermcontext return false override public void onpostexecuteboolean reschedule if reschedule mjobservicejobfinishedmjobparams true else mjobservicejobfinishedmjobparams false logdhanif and finally the log output is as below0327 125711677 7383 7383 d hanif scheduling periodic job 2 hrs with 20 mins backoff linear0327 125731904 7383 7383 d hanif onstartjob0327 125731909 7383 8623 d hanif work start0327 125742110 7383 8623 d hanif work done counter 00327 1257421 7383 8623 d hanif do not reschedule0327 125742125 7383 7383 d hanif 0327 145850786 7383 7383 d hanif onstartjob0327 145850789 7383 21490 d hanif work start0327 145900952 7383 21490 d hanif work done counter 10327 145900953 7383 21490 d hanif do not reschedule0327 145900962 7383 7383 d hanif 0327 165712021 7383 7383 d hanif onstartjob0327 165712045 7383 32028 d hanif work start0327 165729 7383 32028 d hanif work done counter 20327 1657230 7383 32028 d hanif do not reschedule0327 1657238 7383 7383 d hanif 0327 185711984 7383 7383 d hanif onstartjob0327 185711989 7383 13217 d hanif work start0327 185722123 7383 13217 d hanif work done counter 30327 185722124 7383 13217 d hanif do reschedule0327 185722130 7383 7383 d hanif 0327 192057468 7383 7383 d hanif onstartjob0327 192057482 7383 1913 d hanif work start0327 192107723 7383 1913 d hanif work done counter 00327 192107724 7383 1913 d hanif do not reschedule0327 192107733 7383 7383 d hanif 0327 192157669 7383 7383 d hanif onstartjob why is this called again0327 192157675 7383 3025 d hanif work start0327 192207895 7383 3025 d hanif work done counter 10327 192207896 7383 3025 d hanif do not reschedule0327 192207906 7383 7383 d hanif 0327 214053419 7383 7383 d hanif onstartjob0327 214053423 7383 31526 d hanif work start0327 214103857 7383 31526 d hanif work done counter 20327 214103858 7383 31526 d hanif do not reschedule0327 214103867 7383 7383 d hanif why is onstartjob being called two times,"['java', 'android']" +1111380,if a view is set up in ib with auto layout what happens if you try to change its frame programmatically a project i have started helping on did not use auto layout before and i am updating it to use auto layout and size classes there is a decent amount of frame manipulation code throughout the app eg setting frame directly rather than changing constraint constants and i am wondering how this affects a view that is been set up with auto layout constraints i am working on doing away with the framechanging portions of code and changing it to update constraint constants where needed but since i am not yet 100 familiar with how every piece of the code works it would be helpful to have a better understanding of how auto layout and coded frame changes can affect each other so that if a view does not appear properly at runtime i can better determine if it is something i set up or perhaps a piece of older code somewhere that needs to be found and updated,['ios'] +1111567,how to manage state without using subject or imperative manipulation in a simple rxjs example i have been experimenting with rxjs for two weeks now and although i love it in principle i just cannot seem to find and implement the correct pattern for managing state all articles and questions appear to agreesubject should be avoided where possible in favor of just pushing state through via transformationsgetvalue should be deprecated entirely anddo should perhaps be avoided except for dom manipulationthe problem with all such suggestions is that none of the literature appears to directly say what you should be using instead besides youll learn the rx way and stop using subjectbut i cannot find a direct example anywhere that specifically indicates the correct way to perform both additions and removals to a single streamobject as the consequence of multiple other stream inputs in a stateless and functional mannerbefore i get pointed in the same directions again problems with uncovered literature arethe introduction to reactive programming youve been missing great starting text but does not specifically address these questionsthe todo example for rxjs comes with react and involves explicit manipulation of subjects as proxies for react stores explicitly uses a state object for addition and removal of itemsmy perhaps 10th rewrite of the standard todo follows my prior iterations covered includestarting with a mutable items array bad as state is explicit and imperatively managedusing scan to concatenate new items to an addeditems stream then branching another stream where the removed items were deleted bad as the addeditems stream would grow indefinitelythiscovering behaviorsubjectand using that seemed bad since for each new updatedlistnext emission it requires the previous value to iterate meaning that subjectgetvalue is essentialtrying to stream the result of the inputenter addition events into filtered removal events but then every new stream creates a new list and then feeding that into the toggleitem and toggleall streams means that each new stream is dependent on the previous and so causing one of the 4 actions add remove toggle item or toggle all requires the whole chain to be unnecessarily run through againnow i have come full circle where i am back to using both subject and just how is it supposed to be successively iterated upon in any way without using getvalue and do as show below myself and my colleague agree this is the clearest way yet it of course seems the least reactive and most imperative any clear suggestions on the correct way for this would be much appreciatedimport rx from rxjsrximport h from virtualdomhimport diff from virtualdomdiffimport patch from virtualdompatchconst todolistcontainer documentqueryselectortodoitemscontainerconst newtodoinput documentqueryselectornewtodoconst todomain documentqueryselectormainconst todofooter documentqueryselectorfooterconst inputtoggleall documentqueryselectortoggleallconst enter key 13 intentsconst inputenter rxobservablefromeventnewtodoinput keyup filterevent eventkeycode enter key mapevent eventtargetvalue filtervalue valuetrimlength mapvalue return label value completed false const inputitemclick rxobservablefromeventtodolistcontainer clickconst inputtoggleall rxobservablefromeventinputtoggleall click mapevent eventtargetcheckedconst inputtoggleitem inputitemclick filterevent eventtargetclasslistcontainstoggle mapevent return label eventtargetnextelementsiblinginnertexttrim completed eventtargetchecked const inputdoubleclick rxobservablefromeventtodolistcontainer dblclick filterevent eventtargettagname label doevent eventtargetparentelementclasslisttoggleediting mapevent eventtargetinnertexttrimconst inputclickdelete inputitemclick filterevent eventtargetclasslistcontainsdestroy mapevent return label eventtargetpreviouselementsiblinginnertexttrim completed false const list new rxbehaviorsubject model operationsconst additem inputenter doitem inputtoggleallchecked false listnextlistgetvalueconcatitem const removeitem inputclickdelete doremoveitem listnextlistgetvaluefilteritem itemlabel removeitemlabel const toggleall inputtoggleall doallcomplete listnexttoggleallcompletelistgetvalue allcomplete function toggleallcompletearr allcomplete inputtoggleallchecked allcomplete return arrmapitem label itemlabel completed allcomplete const toggleitem inputtoggleitem dotoggleitem let allcomplete toggleitemcompleted let nonecomplete toggleitemcompleted const list listgetvaluemapitem if itemlabel toggleitemlabel itemcompleted toggleitemcompleted if allcomplete itemcompleted allcomplete false if nonecomplete itemcompleted nonecomplete false return item if allcomplete listnexttoggleallcompletelist true return if nonecomplete listnexttoggleallcompletelist false return listnextlist subscribe to all the events that cause the proxy list subject array to be updatedrxobservablemergeadditem removeitem toggleall toggleitemsubscribelistsubscribelist dom sideeffects based on list size todofooterstylevisibility todomainstylevisibility listlength visible hidden newtodoinputvalue renderingconst tree list mapnewlist renderlistnewlistconst patches tree buffercount2 1 mapoldtree newtree diffoldtree newtreeconst todolist patchesstartwithdocumentqueryselectortodolist scanrootnode patches patchrootnode patchestodolistsubscribefunction renderlistarr allcomplete return hultodolist arrmapval hli classname valcompleted completed null hinput classname toggle type checkbox checked valcompleted hlabel vallabel hbutton classname destroy editin relation to user37432 very helpful answer i can see how representing state as an additional input can make a function pure and thus scan is the best way to represent a collection evolving over time with a snapshot of its previous state up to that point as an additional function parameterhowever this was already how i approached my second attempt with addeditems being a scanned stream of inputs this list will now grow infinitely because nothing is ever removed from it at the same time as concatenationconst listwithitemsadded inputenter startwith scanlist additem listconcatadditemconst listwithitemsaddedandremoved inputclickdeletewithlatestfromlistwithitemsadded scanlist removeitem listfilteritem item removeitem now i have to always work from the previous list to get the incorporated amendmentsconst listwithitemsaddedandremovedandtoggled inputtoggleitemwithlatestfromlistwithitemsaddedandremoved mapitem list if itemchecked true etc and have the event triggering a bunch of previous inputs it may have nothing to do with and so if i have 400 inputs it appears at this stage to still run all the previous functions every time any input changes even if i just want to change one small part of stateconst n nminus1scanthe obvious solution would be to just have items and manipulate it directly or const items new behaviorsubject but then the only way to iterate on it appears to be using getvalue to expose the previous state which andre stalz cyclejs has commented on in the rxjs issues as something that should not really be exposed but again if not then how is it usablei guess i just had an idea that with streams you werent supposed to use subjects or represent anything via a state meatball and in the first answer i am not sure how this does not introduce mass chained streams which are orphanedgrow infinitelyhave to build on each other in exact sequence,['javascript'] +1111631,the colored image turned to have no color and just a grey vector in drawable i have created a new image assets in the drawable cus i need to insert a new image in my app but every time i create a new image asset the output turns to be no colour at all i have attached the pic of itit is confusing and whenever i import it in my layout it is just grey all over as you can see in the image why is it cus i cannot find any ready solutions let me know if i am overlooked,['android'] +1111659,what is an example usage of at css url function 34 resource locators the url type describes a urlmodifier ata url is a pointer to a resource and is a functional notation denoted by url the syntax of a url isurl url string urlmodifier in addition to the syntax defined above a can sometimes be written in other waysfor legacy reasons a url can be written without quotation marks around the url itself this syntax is speciallyparsed and produces a urltoken rather than a function syntactically css3synsome css contexts such as import allow a url to be represented by a string instead this behaves identically to writing a url function containing that string because these alternate ways of writing a url are not functional notations they cannot accept any urlmodifiersnote the special parsing rules for the legacy quotation markless url syntax means that parentheses whitespace characters single quotes and double quotes appearing in a url must be escaped with a backslash eg urlopenparens urlcloseparens depending on the type of url it might also be possible to write these characters as urlescapes eg urlopen28parens or urlclose29parens as described inurl if written as a normal function containing a string ordinary string escaping rules apply only newlines and the character used to quote the string need to be escapedat342 url modifiersthe url function supports specifying additional urlmodifiers which change the meaning or the interpretation of the url somehow a urlmodifier is either an ident or a functionthis specification does not define any urlmodifiers but other specs may do sosee also css values and units module level 3editoras draft 21 march 2016what are example usages of ident and function at url what are differences between string ident function at url,['css'] +1112034,how to fix warning init is deprecated for the code linelet bytesdecrypted unsafemutablepointerinti am getting the warning init is deprecated init will be removed in swift 3 use nil insteadwhat is the correct way to fix this warning,['ios'] +1112053,option daysofweekthisabled not working in bootstrap datetime picker here it is html i have been using for getting bootstrap datetimepicker to thisable weekend days datetimepicker4datetimepicker format ddmmy hhmm pickseconds falsedatetimepicker4datetimepickersetdate new datedatetimepicker4datetimepicker daysofweekthisabled 0 6script srcscriptlink href relstylesheet script srcscriptdiv classinputappend datetimepicker4 input dataformatymmdd typetext span classaddoni datatimeiconicontime datadateiconiconcalendarispandiv,"['javascript', 'jquery']" +1112074,regex matching imports of a class i have been trying to write a regex to match the imports of a class let the class beimport static orgjunitassertimport org package testimport mypackagemystuffthe output should be orgjunitassert orgpackagetest mypackagemystuff i have been struggling with the line breaks and with regular expressions in general since i am not that experienced with them this is my current attemptbimports azaz09,['java'] +1112166,vaadin grid cell not showing multiline rows with vaadin grid i want to generate multiline cells for every cell that have more content in cell that overlaps its widthi have allready triedjava n new line character and css stylings like whitespace pre but it does not seem to work this solution worked for tablecustom renderer setrendererhtmlrenderer with brtags and different css thisplay settingsdesired result,['java'] +1112210,cannot capture documenttagname in phonegap inside inappbrowser i open and execute this function inside the opened browser via injected javascript aka inappbrowser callbacks the function works because i see the alerts the inappbrowser is opened via windowopenvar f el tname documentbodygetelementsbytagnamethe tag0 the above alerted undefined in android browser and the correct value in the desktop rewriting variable for debug purposesf el tname documentbodygetelementsbytagnamethe tagalertf el tnamelength this gives 0 in phonegap android browser and 1 in desktop correctforvar i 0 i f el tnamesize i alertf el tname this does not even runwhy exactly is this happening with desktop and android i am referring to accessing the phonegap instance in the desktop or in android so the code and context are virtually the same any idea on whyedit i think this might be happening because document in documentbodygetelementsbytagnamethe tag is referring to the app document and not the document inside the inappbrowser how can i get the document inside the browser inside the loadstop callbackthe windows is opened by var ref windowopenedit 2 as requested here is the codevar ref windowopenurl blanklocationyestoolbarnohiddenyesclosebuttoncaptionreturnrefaddeventlistenerloadstop function var f el tname refdocumentbodygetelementbyidl fdb the above gives an error,"['javascript', 'android']" +1112343,using rethis with signalr i have a aspnet mvc application that runs on say server a and some web services that run on server b i have implemented real time notifications for which i haved used signalr on server a but now i need server b to be also able to send message to view served from server athe main web application hence i am trying tutorial here to involve rethis backplanein my startup in server a i have added the followingglobalhostdependencyresolveruserethislocalhost 6379 stringempty abcappmaphubshere i assume that myapp indicates the channel and when i run publish abc hello world on rethis console i can see the subscriber count returned as 1 but not able to figure out how a signalr hub interacts with the channel where do i receive the message on the serverview can we subscribe to only one rethis channel cannot we dynamically configure to subscribe to a particular channeledit i can see messages sent from chat application implemented using signalr on rethis console if i subscribe to abc also for now i have implemented my own rethis listener on server a which in receiving a message from rethis channel calls the signalr hub function i am sure there must be a different way to do this and i am hoping rethis backplane can help me but unsure how it works,['c#'] +1112415,how to use inverse of a genericrelation i must be really misunderstanding something with the genericrelation field from djangos content types frameworkto create a minimal self contained example i will use the polls example app from the tutorial add a generic foreign key field into the choice model and make a new thing modelclass choicemodelsmodel content type modelsforeignkeycontenttype object id modelspositiveintegerfield thing genericforeignkeycontent type object idclass thingmodelsmodel choices genericrelationchoice related query namethingswith a clean db synced up tables and create a few instances poll pollobjectscreatequestionthe question pk123 thing thingobjectscreatepk456 choice choiceobjectscreatechoice textthe choice pk789 pollpoll thingthing choicethingpk456 thingchoicesgetpk789so far so good the relation works in both directions from an instance but from a queryset the reverse relation is very weird choiceobjectsvalues listthings flat1456 thingobjectsvalues listchoices flat1456why the inverse relation gives me again the id from the thing i expected instead the primary key of the choice equivalent to the following result thingobjectsvalues listchoices pk flat1789those orm queries generate sql like this print thingobjectsvalues listchoices pk flat1queryselect polls choiceid from polls thing left outer join polls choice on polls thingid polls choiceobject id and polls choicecontent type id 10 print thingobjectsvalues listchoices flat1queryselect polls choiceobject id from polls thing left outer join polls choice on polls thingid polls choiceobject id and polls choicecontent type id 10the django docs are generally excellent but i cannot understand why the second query or find any documentation of that behaviour it seems to return data from the wrong table completely,"['python', 'sql']" +1112526,mysqlexception on executereader by selecting useridpk i try to delete a row from the database on the phpadmin the query is workingfine but when i execute it with the codemysqlcommand getuserid new mysqlcommandselect userid from user connectionmysqldatareader reader getuseridexecutereaderi get theerrordestination array is not long enough to copy all the items in the collection check array index and lengthi insert the to deleting user before without any troublethe database has an userid with properties uniqueintlength 9 and autoincrement and a username from type charmy question iswhy i cannot receive the userid and how can i receive it editi cannot receive any integer or date data only varcharhere is the database creation querycreation query,"['c#', 'mysql']" +1112666,performing two queries in a single round trip to the database i have the following code to perform a fulltext search it creates a query gets the total number of rows returned by that query and then retrieves the actual rows for only the current page create iqueryablevar query from a in articleservercontextsetarticle where aapproved orderby autcdate descending select a get total rows needed for pagination logicint totalrows querycount get rows for current pagequery queryskipcurrentpage 1 rowsperpagetakerowsperpagethis works fine but it requires two round trips to the database in the interest of optimizing the code is there any way to rework this query so it only had one round trip to the database,"['c#', 'sql']" +1112783,getting custom materials from solidworks first note i do not have solidworks installed on my computer but use the files for a projectsolidworks has the ability to make a custom tab to the file properties in this tab you can find all kind of information about a modelpart that is made in solidworksi read out all these information and store it in a txt file see image within this information you can find the material type of the part where my question comes ini know the material type however in solidworks the user can also assign custom materials to the material that is defined in the custom properties for example the material is just regular wood but the user want this wood to be pinkis it possible to read out the custom materials that are attached to the material in custom properties,['c#'] +1112795,how to ignore question mark as placeholder when using pdo with postgresql notethis question can be considered as duplicate of this questionit does point to the same problem with pdo but its workaround solution is a bit different as the target differ i will post there the workaround for jsonb and the link to the php ticketwhen i prepare the following queryselect from post where locations locationthe following warning occurwarning pdoprepare sqlstatehy093 invalid parameter number mixed named and positional parameters in pathfilephp on line xxthe question mark is an valid postgresql operator but pdo condsider it as a placeholderis there a proper way to configure pdo to ignore question mark as placeholdersi will post a workaround bellow hoping there is a better wayediti add a ticket at php bug tracing system,['php'] +1112832,prevent uinavigationbar in share extension from inheriting main application appearance settings i created a share extension for my for which i had to create my own ui in the storyboard the entire thing works great except for the fact that the navigation bar inherits the main apps appearance as exampleshere it is in the nyt app here it is in the vice apphow can i set my own appearance,['ios'] +1113355,c destructor calls a delete operator why does my msvc12 compiler not like thisinclude newclass thingpublic thing thing static void operator deletevoid ptr deleteint main int g void p g thing t1 newp thing t1thing return 0the error i get is oddly on the closing brace of mainerror 2 error c2280 void thingoperator deletevoid attempting to reference a deleted functionif i comment out the explicit destructor call the error goes away implying that the explicit destructor call is trying to call operator deletevoid this does not make intuitive sense as you can probably see from the code here i have already managed my own memory and i do not want anyone to call delete on thing ever,['c++'] +1113452,2gb table with 10 million rows late pagination select is slow i have table in mysql with 10 million rows with 2 gb data selecting in lifo format data is slow table engine is innodbtable has one primary key and one unique keyselect from link limit 9 50how i improve the performance of the table table structure id int11 no pri null auto incrementurl varchar255 no uni null website varchar100 no null state varchar10 no null type varchar100 no null prio varchar100 yes null change varchar100 yes null last varchar100 yes nullnoteselect from link limit 1 50 is taking 9ms but current sql is taking 10ms its 100 time taking more,"['mysql', 'sql']" +1113454,find all possible combinations of word with and without hyphens for a string that may have zero or more hyphens in it i need to extract all the different possibilities with and without hyphensfor example the string ab would result in ab and ab two possibilitiesthe string abc would result in abc abc abc and abc four possibilitiesthe string abcd would result in abcd abcd abcd abcd abcd abcd abcd and abcd eight possibilitiesetc etci have experimented with some nested loops but have not been able to get anywhere near the desired result i suspect i need something recursive unless there is some simple solution i am overlookingnb this is to build a sql query shame that sql server doest have mysqls regexp pattern matchinghere is one attempt i was working on this might work if i do this recursivelystring keyword abcdlistint hyphens new listintint pos keywordindexofwhile pos 1 hyphensaddpos pos keywordindexof pos 1for int i 0 i hyphenscount i string result keywordsubstring0 hyphensi keywordsubstringhyphensi 1 responsewritep resulta b c d are words of varying length,['c#'] +1113461,android 60 marshmallow how to play midi notes i am creating an app that generates live instrument sounds and i am planning on using the new midi api featured in android marshmallow version 60 i have read the package overview document here and i know how to generate midi notes but i am still unsure how do i actually play these notes after i have generated their midi datado i need a synthesizer program to play midi notes if so do i have to make my own or is one provided by android or a 3rd partyi am a novice with midi so please be as descriptive as possible with your answer what i have tried so far i have created a midi manager object and opened an input portmidimanager m midimanagercontextgetsystemservicecontextmidi service midiinputport inputport deviceopeninputportindexthen i have sent a test noteon midi message to the port byte buffer new byte32int numbytes 0int channel 3 midi channels 116 are encoded as 015buffernumbytes byte0x90 channel 1 note onbuffernumbytes byte60 pitch is middle cbuffernumbytes byte127 max velocityint offset 0 post is nonblockinginputportsendbuffer offset numbytesi have also set up a class to receive the midi note messages class myreceiver extends midireceiver public void onsendbyte data int offset int count long timestamp throws ioexception parse midi or whatever midioutputport outputport deviceopenoutputportindexoutputportconnectnew myreceivernow heres where i am most confused the use case of my app is to be an allinone composition playback tool for making music in other words my app needs to contain or use a virtual midi device like an intent of another apps midi synthesizer unless someone already made such a synthesizer i must create one myself within my apps lifecycle how do i actually actually convert a received midi noteon into sound coming out of my speakers i am especially confused because there also has to be a way to programmatically decide what type of instrument the note sounds like it is coming from is this also done in a synthesizermidi support in android marshmallow is fairly new so i have not been able to find any tutorials or sample synthesizer apps online any insight is appreciated,"['java', 'android']" +1113635,split python dictionary to result in all combinations of values my dict a12 b3 cd45 e67i need to derive all the combinations out of it as belowa1 b3 cd4 e6a1 b3 cd4 e7a1 b3 cd5 e6a1 b3 cd5 e7a2 b3 cd4 e6and so on there could be any level of nesting hereplease let me know how to achieve thissomething that i tried is pasted below but definitely was reaching nowhere def gen combinationsdata my list if isinstancedata dict for k v in dataiteritems if isinstancev dict gen combinationsv elif isinstancev list for i in rangelenv temp dict datacopy temp dictk vi print temp dictmy dict a12 b3 cd45 e67gen combinationsmy dictwhich resulted in a 1 c e 6 7 d 4 5 b 3a 2 c e 6 7 d 4 5 b 3e 6 d 4 5e 7 d 4 5e 6 7 d 4e 6 7 d 5a 1 2 c e 6 7 d 4 5 b 3,['python'] +1113662,how does bootstrap work on full hd1920a1080 mobiles the bootstrap tutorial says that include colxs for mobile devices768px my question is that if i make a website for small mobiles using colxs classes then that css rule will be applied only to those devices which have width less than 768px nowadays there are full hd mobiles which have width 1080px in 5 inch thisplay so would these mobile behave as desktop computera992px for my bootstrap css i want my css to be same for any 5 inches screen mobile device be it hd or full hd,['css'] +1113706,overriding objectequalsobject outside the class is it possible to override objectequalsobject locally when using listcontainssomeobjectexampleclass someobject private int id private string name overrdide public boolean equalsobject other return thisid otherid but what if i want another kind of equals when i use listcontainssomeobject for example i want to know if a list contains a certain name is it possible to override objectequalsobject anonymouslymore specific explanation why i would need itint objectid some event which passes me the attribute of an object but not the object itselfnow i have listsomeobject someobjects and i would like to know if this list contains an object with objectid without necessarily iterating over itone solution i could think of would be using mapinteger someobject mapping and then someobject mappinggetobjectidedit my question is not a duplicate since i am specifically asking to override objectequalsobject,['java'] +1113797,load 404 state with angularjs router i am using angularjs and uirouter and have the following code which catches 404s and loads in a 404 templateurlrouterproviderotherwisefunctioninjector location injectorinvokestate functionstate statego404 it keeps the url intact instead of redirecting but shows the 404 templatestate404 views body templateurl partials404html normally it would redirect to the root state with urlrouterproviderotherwisehowever when html5 mode is turned off and the user visits the root url eg it loads the 404 state instead of redirecting to how can i keep the 404 state code above but have it redirect to the hashbang when accessing the initial page so effectively only have the 404 load if the request is anything other than the home pagei cannot use the statenotfound or statechangesuccess and need a way to check if it is a home page request within the actual config setup itself that can toggle between the and the state404 within the otherwise statement,['javascript'] +1113853,aws sns push notification clarification i have few doubts regarding sending sns push notifications please bare with me as i am a newbie in both aws and php and could not really get things easily1 i referred this stackoverflow thiscussion where we can set sound for apns but how we do it for gcm 2 how to configure no sound alert 3 is it possible to set sound for each endpoint in php while creating them i just want to know this so that while sending message i can send to those with sound enabled and to those thisabled while sending it with topicarn4 i referred this document for getting the delivery status of push notification as logs in cloudwatch is there any api to retrieve the delivery status of those endpoints which failed to receive in php,['php'] +1113856,css3 animation does not work if divbefore is floating webkit i want my text to blink using css3 only it works fine however if i add floatleft to the divs before selector it stops the animation from working on webkit safarichromefor demonstration open jsfiddle on webkit remove the floatleft to see it working cssblink mebefore content blinkblink me webkitanimation blinker 15s linear infinite mozanimation blinker 15s linear infinite oanimation blinker 15s linear infinite animation blinker 15s linear infinite keyframes blinker 50 opacity 00 htmlspan classblink me spanhow can i make it work with the float on the selectorbounty info just rewarding an existing answer which certainly deserves more upvotes,['css'] +1113865,uicontentsizecategorydidchangenotification not working on simulator ios 93 does work on device i have an observer for uicontentsizecategorydidchangenotification that gets triggerd when a user changes the fontsize under settings accessibility nsnotificationcenterdefaultcenteraddobserverself selector preferredcontentsizechanged name uicontentsizecategorydidchangenotification object nili have never experienced any problems with this before but now i am having problems with it on the iphone simulator ios 93 it works however on a real device with ios 93the simulator returns bogus value for uipreferredcontentsizecategoryname nullhas anyone else experienced the same problem,"['ios', 'iphone']" +1113928,python send control q then control a special keys i need to send some special keystrokes and am unsure of how to do iti need to send ctrl q followed by ctrl a to a terminal i am using paramikoi have triedshell clientinvoke shellshellsendchr10timesleep5shellsendchr13shellsendx11shellsendx01print i triedi can see the two returns go in successfully but then nothing it doesnt quit the picocomalso to note i have it the wrong way round its expecting ctrla then ctrlqif it helps this is the device confightmlpgfid1069760as you can see at step 2step 2 exit the session from the switch press ctrla and ctrlq from your keyboardswitch type aqthanks for using picocomrouterupdatei have tried x01x16x11n but this returnsswitchswitch baud 9600 flow none parity none databits 8 dtr downswitchthis looks like it could be another special command,['python'] +1114126,2n itertools combinations with advanced filtering i know that i can use itertools to pump out combinations and define the size of the combination group like soimport itertoolsprint listitertoolscombinationsvmtoqkdr 4the output of this would be like a list of tuples each of length 4 in this casefrom here what i would like to do is enforce 2 parameters 1exclude any combinationstuples that contain certain pairs both v and m for instance or q and k 2force each tuple to contain only 1 instance of a letter i believe that itertools is already doing 2what should remain are only those tuple groups that do not contain any of these predetermined false pairs so if i excluded a group that contained v and m the group vmqd would be invalid but vrqd would be validwhats the best way for me to do this,['python'] +1114314,deleting a file based on thisk id as described here using setfileinformationbyhandle with file thisposition infoallows one to set a file with an open handle to be deleted upon all handles being closedhowever i am trying to delete a file based on its file index thisk id retrieved by file thisposition info andopenfilebyid in order to safely delete filesdirectories in a directory which differ only in casethis is safe to do in my use case as on an ntfs system file indexes are persistent until deletionnegating the use of replacefile which the current codebase handleshowever when attempting to delete the handle i get error 87 error invalid parameterif i delete using a handle created with createfilew i run into no problemsi cannot do this though as windows will not be able to thistinguish between two filefolders of the same case even though ntfs cani am also aware that there is an ambiguity with hardlinked files opened with openfilebyidas hardlinked files share the same thisk idthe issue of hardlinked files can be considered irrelevant for this scenarioi will only be deleting directories by id which cannot be hardlinkedis there a parameter or setting i am missing in my openfilebyid callsomehow in my setfileinformationbyhandle calladditional methods i have triedcalling duplicatehandle with the openfilebyid handle providing delete for dwdesiredaccess and using thatsame error invalid parameter resultusing reopenfile with the openfilebyid handle providing delete for dwdesiredaccess and using thatsame error invalid parameter resultusing reopenfile with the openfilebyid handle providing delete for dwdesiredaccess and providing the file flag delete on close flagno error is given but the file remains after all handles are closedhere is a minimal yet complete example which reproduces the probleminclude stdiohinclude sysstathinclude windowshdword getfileidlpcwstr path large integer id handle h createfilewpath 0 0 0 open existing file flag open reparse point file flag backup semantics file flag posix semantics 0 if h invalid handle value return getlasterror by handle file information info if getfileinformationbyhandleh info dword err getlasterror closehandleh return err idhighpart infonfileindexhigh idlowpart infonfileindexlow closehandleh return error successdword deletefilehandlehandle filehandle file thisposition info info infodeletefilew true if setfileinformationbyhandle filehandle filethispositioninfo info sizeofinfo return getlasterror return error successint wmaindword argc lpwstr argv if argc 3 fwprintfstderr larguments rootpath pathn return 1 dword err handle roothandle createfilew argv1 0 0 0 open existing file flag open reparse point file flag backup semantics file flag posix semantics 0 if roothandle invalid handle value err getlasterror fwprintfstderr lcould not open root directory s error code dn argv1 err return err large integer fileid err getfileidargv2 fileid if err error success fwprintfstderr lcould not get file id of filedirectory s error code dn argv2 err closehandleroothandle return err fwprintfstdout lthe file id of s is lldn argv2 fileidquadpart file id descriptor idstruct idstructtype fileidtype idstructfileid fileid handle filehandle openfilebyid roothandle idstruct delete file share delete 0 file flag open reparse point file flag backup semantics if filehandle invalid handle value err getlasterror closehandleroothandle fwprintfstderr lcould not open file by id lld error code dn fileidquadpart err return err err deletefilehandlefilehandle if err error success fwprintfstderr lcould not delete file by id lld error code dn fileidquadpart err closehandlefilehandle struct stat tmp fwprintfstdout lfile was ssuccessfully deletedn wstatargv2 tmp 0 lnot l closehandleroothandle return errany solution must work with vista and above suggestions for code improvement are also welcome,['c'] +1114396,merging complicated tables i am trying to merge tables where rows correspond to a many1 relationship with real thingsi am writing a blackjack simulator that stores game history in a database with a new set of tables generated each run the tables are really more like templates since each game gets its own set of the 3 mutable tables players hands and matches heres the layout where suff is a userspecified suffix to use for the current run cards id integer primary key cardvalue integer not null suit integer not null players suff whichplayer integer primary key aitype text not null hands suff id bigserial primary key whichplayer integer references players suffwhichplayer whichhand bigint not null thiscard integer references cardsid matches suff id bigserial primary key whichgame integer not null dealershand bigint not null whichplayer integer references players suffwhichplayer thisplayershand bigint not null playerresult integer not null aka who wononly one cards table is created because its values are constantso after running the simulator twice you might havehands firstrunplayers firstrunmatches firstrunhands secondrunplayers secondrunmatches secondruni want to be able to combine these tables if you used the same ai parameters for both of those runs ie players firstrun and players secondrun are exactly the same the problem is that the way i am inserting hands makes this really messy whichhand cannot be a bigserial because the relationship of hands suff rows to actual hands is many1 matches suff is handled the same way because a blackjack game actually consists of a set of games the set of pairs of each player vs the dealer so for 3 players you actually have 3 rows for each roundcurrently i select the largest whichhand in the table add 1 to it then insert all of the rows for one hand i am worried this queryandinsert will be really slow if i am merging 2 tables that might both be arbitrarily hugewhen i am merging tables i feel like i should be able to entirely in sql query the largest values in whichhand and whichgame once then use them combine the tables incrementing them for each unique whichhand and whichgame in the table being mergedi saw this question but it does not handle using a generated id in 2 different places i am using postgres and it is ok if the answer is specific to it sadly postgres does not allow parameterized table names so this had to be done by manual string substitution not the end of the world since the program is not webfacing and no one except me is likely to ever bother with it but the sql injection vulnerability does not make me happy matches suffwhichplayershand was originally going to reference hands suffwhichhand but foreign keys must reference unique values whichhand is not unique because a hand is made up of multiple rows with each row holding one card to query for a hand you select all of those rows with the same value in whichhand i could not think of a more elegant way to do this without resorting to arrayseditthis is what i have nowthomas dt list of relations schema name type owner public cards table thomas public hands first table thomas public hands second table thomas public matches first table thomas public matches second table thomas public players first table thomas public players second table thomas7 rowsthomas select from hands firstthomas g id whichplayer whichhand thiscard 1 0 0 6 2 0 0 63 3 0 0 41 4 1 1 76 5 1 1 23 6 0 2 51 7 0 2 29 8 0 2 2 9 0 2 92 10 0 2 6 11 1 3 101 12 1 3 812 rowsthomas select from hands secondthomas g id whichplayer whichhand thiscard 1 0 0 78 2 0 0 38 3 1 1 24 4 1 1 18 5 1 1 95 6 1 1 40 7 0 2 13 8 0 2 84 9 0 2 41 10 1 3 29 11 1 3 34 12 1 3 56 13 1 3 52thomas select from matches firstthomas g id whichgame dealershand whichplayer thisplayershand playerresult 1 0 0 1 1 1 2 1 2 1 3 22 rowsthomas select from matches secondthomas g id whichgame dealershand whichplayer thisplayershand playerresult 1 0 0 1 1 0 2 1 2 1 3 22 rowsi would like to combine them to havehands combined table id whichplayer whichhand thiscard 1 0 0 6 seven of spades 2 0 0 63 queen of spades 3 0 0 41 three of clubs 4 1 1 76 5 1 1 23 6 0 2 51 7 0 2 29 8 0 2 2 9 0 2 92 10 0 2 6 11 1 3 101 12 1 3 8 13 0 4 78 14 0 4 38 15 1 5 24 16 1 5 18 17 1 5 95 18 1 5 40 19 0 6 13 20 0 6 84 21 0 6 41 22 1 7 29 23 1 7 34 24 1 7 56 25 1 7 52matches combined table id whichgame dealershand whichplayer thisplayershand playerresult 1 0 0 1 1 1 2 1 2 1 3 2 3 2 4 1 5 0 4 3 6 1 7 2each value of thiscard represents a playing card in the range 110452 playing cards with an extra bit representing if it is face up or face down i did not post the actual table for space reasonsso player 0 aka the dealer had a hand of seven of spades queen of spaces 3 of clubs in the first game,['sql'] +1114646,if i move a local object into a function will it still be valid afterward so this provides the intended outputvoid fstdstring s s plus extraint mainvoid stdstring str a string f stdmovestr stdcout str stdendl return 0a string plus extrathat is it works when i run it on ideone but is it ub adding extra string initializations before and after the call to f did not change anything,['c++'] +1115122,how do i recreate powershell profile variable it is empty in a custom host if you implement a custom powershell host with systemmanagementautomation sma all of the automatic variables are avaialable except it seems that profile is empty how would one go about recreating itis it always in userprofile documentswindowspowershellmicrosoftpowershell profileps1 or do i need to be worried about it being in other placesto clarify i only care about currentusercurrenthost profiledetailsgiven this powershell scriptwriteoutput profiles writeoutput currentusercurrenthost profilecurrentusercurrenthostwriteoutput currentuserallhosts profilecurrentuserallhostswriteoutput alluserscurrenthost profilealluserscurrenthostwriteoutput allusersallhosts profileallusersallhostsrunning it against system powershell has the following output profiles currentusercurrenthost cusersrobdocumentswindowspowershellmicrosoftpowershell profileps1currentuserallhosts cuserrobdocumentswindowspowershellprofileps1alluserscurrenthost cwindowssystem32windowspowershellv10microsoftpowershell profileps1allusersallhosts cwindowssystem32windowspowershellv10profileps1running it with a custom c powershell host a systemmanagementautomationhostpshost implementation shows profiles currentusercurrenthost currentuserallhosts alluserscurrenthost allusersallhosts backgroundthis has been tested in powershell v3 systemmanagmentautomation sma v3 but it could easily be proven out in other powershell versions,['c#'] +1115436,why does not flex item shrink past content size i have 4 flexbox columns and everything works fine but when i add some text to column and set it to big font size it is making column wider than it should be due to flex box settingi tried to use wordbreak breakword and it helped but still when i resized column to very very small width letters in text are broken to multiple lines one letter per line but column does not get smaller width than one letter size try to watch this video at start first column is the smallest but when i resized window it is the widest column i just want to respect flex settings always flex sizes 1 3 4 4jsfiddle container thisplay flex width 100col minheight 200px padding 30px wordbreak breakwordcol1 flex 1 background orange fontsize 80pxcol2 flex 3 background yellowcol3 flex 4 background skybluecol4 flex 4 background reddiv classcontainer div classcol col1lorem ipsum dolordiv div classcol col2lorem ipsum dolordiv div classcol col3lorem ipsum dolordiv div classcol col4lorem ipsum dolordivdivi know setting font size and column paddings to smaller will help but is there any other solutioni can not use overflowx hiddenthank you,"['html', 'css']" +1115562,writing javascript applications with kotlin i recently started to have a look at kotlin and managed to create my first jvm applications it is so cool to have a single language that compiles both to java and js so now i started playing with kotlin2js and tried to understand the javascript interoperability and the possibilities to use js frameworks like jqueryi found a couple of blog posts and examplesis there a documentation of the kotlin js libraryit is not yet mentioned at i first compiled a simple sample app which used import kotlinbrowser with gradle as build system which finally and with some help here worked thanks again than i imported the project into idea and suddenly it did not compile anymore i had to change the import to import jsdomhtml so i guess it uses a different version of library and idea added apply plugin kotlin to my buildgradle in addition to kotlin2js and i guess this does not workidea copied kotlinjslibjar to lib which says it is implementationversion 07270 in its manifest for the compilation with gradle i used kotlin 1011 and i am pretty sure that i also selected this version in idea when creating the projectso what are the best sources of information to understand kotlin2js and the kotlinjslibespecially the javascript interoperability how to use frameworks like jquery it seems that there is jquery support in the kotlinjslib but also how i can use other frameworks that do not come with kotlin support yet i understood that kotlin has the dynamic keyword and mentioned noimpl which lead to a compile error when i tried to use itmaybe the best way for now is to look at the kotlin sourceswell this is a rather long and unstructured question covering several aspects but that is my current state of learning kotlin and maybe others experience the same problem,"['javascript', 'jquery']" +1115576,return self in python i have a class that represents object and i have a bunch of methods which modify this object state with no obvious return or obviously without any return in c i would declare all these methods as void and see no alternatives but in python i am about to make all the methods return self to give myself ability to write awesome oneliners like thisclassnamemethod1method2method3is this pythonic or otherwise acceptable in python,['python'] +1115579,retrofit 20 how to delete i am using retrofit 20 and i am implementing a delete feature in my android app however i cannot make it successfully can someone give me a suggestioni tried bothdeletebooksid void deletebookpathid int itemiddeletebooksid void deletebookpathid int bookid callbackresponse callbacki get error javalangillegalargumentexception service methods cannot return void for method libraryservicedeletebooki also gave a try on thisresponse deletebookpathid int bookidcallresponse deletebookpathid int bookidno matter i use okhttp3response or retrofit2response i will get the error response is not a valid response body type did you mean responsebodycan someone give me a successful delete example i googled online but cannot find enough information thanks a lot,"['java', 'android']" +1116002,check if a string contains a specific string using array i am new to c i would like to know if a string such as a user name contains a specific word i want to get those specific words from an arrayheres a exampleconsolewritename name consolereadlinename programpropernamemethod nameconsolewritelinestring badwordarray abadword1 abadword2 abadword3 if stringisnulloremptyname would like to check for the badwordarray aswellupdatethank you all but me learning c only for about a month could not cover lambda or regex yet i will have a look at these codes while later,['c#'] +1116205,xcode cannot parse the debug map for is a directory i am trying to link my iphone simulator project and i am getting the following error at link timenull error cannot parse the debug map for usersadminlibrarydeveloperxcodederiveddatatraintracksagvvryrtufplkxecblncwedcelckbuildproductsdebugiphonesimulatortraintracksapptraintracks is a directoryheres the linker outputgeneratedsymfile usersadminlibrarydeveloperxcodederiveddatatraintracksagvvryrtufplkxecblncwedcelckbuildproductsdebugiphonesimulatortraintracksappdsym usersadminlibrarydeveloperxcodederiveddatatraintracksagvvryrtufplkxecblncwedcelckbuildproductsdebugiphonesimulatortraintracksapptraintracks cd worktraintrackstraintracks export pathapplicationsxcodeappcontentsdeveloperplatformsiphonesimulatorplatformdeveloperusrbinapplicationsxcodeappcontentsdeveloperusrbinusrlocalbinusrbinbinusrsbinsbin applicationsxcodeappcontentsdevelopertoolchainsxcodedefaultxctoolchainusrbindsymutil usersadminlibrarydeveloperxcodederiveddatatraintracksagvvryrtufplkxecblncwedcelckbuildproductsdebugiphonesimulatortraintracksapptraintracks o usersadminlibrarydeveloperxcodederiveddatatraintracksagvvryrtufplkxecblncwedcelckbuildproductsdebugiphonesimulatortraintracksappdsymerror cannot parse the debug map for usersadminlibrarydeveloperxcodederiveddatatraintracksagvvryrtufplkxecblncwedcelckbuildproductsdebugiphonesimulatortraintracksapptraintracks is a directorywhat would cause this problemi started off with a game template xcode 721 and deleted the main story board and appdelegate files since this is an sdl crossplatform project,"['ios', 'iphone']" +1116272,bootstrap navbar flashing when clicking outside of menu to close it i am having an issue with the navbar where a flash appears when you click outside the menu to close the menu the flash persists if the mouse is held down when clicking out of the menu as shown herei am thinking it might have something to do with angular and not css mainly because others have failed to replicate it on fiddle previous question here htmlnav classnavbar navbardefaultnavbarstatictop navbarcustom div classcontainerfluid ul classnav navbarnav navbarleft lia hrefdashboardhtmldashboardali lia hrefgradesgradesali lia hrefclassesclassesali ul ul classnav navbarnav navbarright lia hrefmessagesi classfa faenvelope falgiali has to do with the link clicking it and clicking it again lia classdropdowntoggle dropdowncustom datatoggledropdown hrefprofilei classfa fauser falgia ul classdropdownmenu lia hrefprofilehtmledit profileali lia hrefsettingsedit preferencesali ul li lia hreflogouti classfa fapoweroff falgiali ul divnavcssngcloak ngcloak ngcloak thisplay none importantnavbarcustom backgroundcolor 586f7cnavbarcustom a color f4f4f9navbarcustom nav li ahover backgroundcolor 2f4550navbar navbarnav liopen a backgroundcolor 586f7cnavbar navbarnav liopen ahovernavbar navbarnav liopen afocus backgroundcolor 2f4550nav li ahover nav li afocus backgroundcolor 586f7cnginclude in the file the navbar is referenced indiv ngincludehtmlnavbarhtmldivportion of indexhtml where it references the file that the navbar is ngincluded inbody div classviewcontainer div ngview classviewframediv divbodyi am thinking the issue might be with the ngview or nginclude however so far none of the fixes in the previous question worked,"['html', 'css']" +1116291,now that vs2015 is out whats a supported way to modify roslyn with debugging support the context wed like to modify roslyn and be able to debug it while compiling with it prevs2015 release doing this was a painful process that did not flow very wellour goal is to develop a c variant compiler the dreamprevs2015 executing and debugging your modded roslyn required the opening of a second vs ide experimental set to use your modded roslyn this process was not straight forward to setup properly and oftentimes would break your vs2015 installation postvs2015 is there a better setup and process possible to modify and debug roslyni have installed visual studio 2015 but it looks like i need more required bits after that i am unsure how to run the tests and try the changes in vs2015,['c#'] +1116446,how to stream video data to a video element i have a nodejs process which outputs a video stream into my nodejs appon the client end there is a video tag i would like to stream the video from nodejs into the src attribute of the video tag my previous experience tells me that we must use the blob object for this however i am not a hundred percent certain how and why i would use itanother possible solution i am thinking of is to create some sort of a temporary file on my server then write the stream to that file then serve that file as the source for the video however that does not seem intuitive i was wondering then if there is a more established solution for an issue like this,['javascript'] +1116476,how to create flow textview working on app where user has to put some data in edittext but in front and behind this edittext i have textviews for that i use horizontal linearlayout where i put textview edittext textview i faced with problem of line transfer please help me to find a solutionit looks like this nowblabla tatata tatatai need like thisblabla tatatatatata i tried to use flowtextview but it did not help it looks ugly usable for pictures only 3rd way by using flow layoutthe problem is it moves to the second line if it does not have enough space please help me to make some correction here manifestxml version10 encodingutf8manifest xmlnsandroid packagecomexamplenikolaiapp application androidallowbackuptrue androidiconmipmapic launcher androidlabelstringapp name androidsupportsrtltrue androidthemestyleapptheme activity androidnamemainactivity intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity applicationmanifestmain activity public class mainactivity extends appcompatactivity override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main horizontalflowlayoutpublic class horizontalflowlayout extends relativelayout constructor to use when creating view from code public horizontalflowlayoutcontext context supercontext constructor that is called when inflating view from xml public horizontalflowlayoutcontext context attributeset attrs supercontext attrs perform inflation from xml and apply a claspecific base style public horizontalflowlayoutcontext context attributeset attrs int defstyle supercontext attrs defstyle override protected void onmeasureint widthmeasurespec int heightmeasurespec need to call superonmeasure otherwise get some funny behaviour superonmeasurewidthmeasurespec heightmeasurespec final int width measurespecgetsizewidthmeasurespec int height measurespecgetsizeheightmeasurespec increment the x position as we progress through a line int xpos getpaddingleft increment the y position as we progress through the lines int ypos getpaddingtop the height of the current line int line height 0 go through children to work out the height required for this view call to measure size of children not needed i think getting childs measured heightwidth seems to work okay without it measurechildrenwidthmeasurespec heightmeasurespec view child marginlayoutparams childmarginlayoutparams int childwidth childheight childmarginleft childmarginright childmargintop childmarginbottom for int i 0 i getchildcount i child getchildati if childgetvisibility gone childwidth childgetmeasuredwidth childheight childgetmeasuredheight if childgetlayoutparams null childgetlayoutparams instanceof marginlayoutparams childmarginlayoutparams marginlayoutparamschildgetlayoutparams childmarginleft childmarginlayoutparamsleftmargin childmarginright childmarginlayoutparamsrightmargin childmargintop childmarginlayoutparamstopmargin childmarginbottom childmarginlayoutparamsbottommargin else childmarginleft 0 childmarginright 0 childmargintop 0 childmarginbottom 0 if xpos childmarginleft childwidth childmarginright getpaddingright width this child will need to go on a new line xpos getpaddingleft ypos line height line height childmargintop childheight childmarginbottom else enough space for this child on the current line line height mathmax line height childmargintop childheight childmarginbottom xpos childmarginleft childwidth childmarginright ypos line height getpaddingbottom if measurespecgetmodeheightmeasurespec measurespecunspecified set height as measured since there is no height restrictions height ypos else if measurespecgetmodeheightmeasurespec measurespecat most ypos height set height as measured since it is less than the maximum allowed height ypos setmeasureddimensionwidth height override protected void onlayoutboolean changed int l int t int r int b increment the x position as we progress through a line int xpos getpaddingleft increment the y position as we progress through the lines int ypos getpaddingtop the height of the current line int line height 0 view child marginlayoutparams childmarginlayoutparams int childwidth childheight childmarginleft childmarginright childmargintop childmarginbottom for int i 0 i getchildcount i child getchildati if childgetvisibility gone childwidth childgetmeasuredwidth childheight childgetmeasuredheight if childgetlayoutparams null childgetlayoutparams instanceof marginlayoutparams childmarginlayoutparams marginlayoutparamschildgetlayoutparams childmarginleft childmarginlayoutparamsleftmargin childmarginright childmarginlayoutparamsrightmargin childmargintop childmarginlayoutparamstopmargin childmarginbottom childmarginlayoutparamsbottommargin else childmarginleft 0 childmarginright 0 childmargintop 0 childmarginbottom 0 if xpos childmarginleft childwidth childmarginright getpaddingright r l this child will need to go on a new line xpos getpaddingleft ypos line height line height childheight childmargintop childmarginbottom else enough space for this child on the current line line height mathmax line height childmargintop childheight childmarginbottom childlayout xpos childmarginleft ypos childmargintop xpos childmarginleft childwidth ypos childmargintop childheight xpos childmarginleft childwidth childmarginright my xml xml version10 encodingutf8relativelayout xmlnsandroid xmlnstools androidlayout widthmatch parent androidlayout heightmatch parent androidpaddingbottomdimenactivity vertical margin androidpaddingleftdimenactivity horizontal margin androidpaddingrightdimenactivity horizontal margin androidpaddingtopdimenactivity vertical margin toolscontextcomexamplenikolaiappmainactivity comexamplenikolaiapphorizontalflowlayout androidididhorizontal flow layout androidlayout widthfill parent androidlayout heightwrap content androidpaddingleftdimensize 5 androidpaddingrightdimensize 5 textview androidlayout widthwrap content androidlayout heightwrap content androidtextsize20dp androidtextblablabla edittext androidlayout widthwrap content androidlayout heightwrap content androidtextsize20dp androidems7 textview androidlayout widthwrap content androidlayout heightwrap content androidtextsize20dp androidtexttatatatatatatatata comexamplenikolaiapphorizontalflowlayoutrelativelayout,"['java', 'android']" +1116538,why do browsers control the input type file button i am curious about why different browsers have different input typefile button to browse the files there are many questions asking how to style them apparently some sort of hacks are used to alter them but no one really explained why do browsers control it,['html'] +1116552,delete system cache on android 60 i am using method freestorageandnotify with permission androidpermissionclear app cache to delete system cache of all installed applications but the method started throwing invocationtargetexception from android marshmallow 60 version after googling the issues i found the same issue is reported hereandroid m reflection method freestorageandnotify exceptionso here the conclusion was freestorageandnotify stopped working since google has raised the methods signature level now to signaturesystembut now the question is how other third party apps like clean master are still able to delete system cache of all installed applications by taking accessibility permission from user for 60 devices,['android'] +1116881,xceed wpf propertygrid show item for expanded collection how do i thisplay a observablecollection of custom objects in the xceed wpf propertygrid in which each list item can be expanded to thisplay the custom objects properties iepropertygridcoreclass observablecollection customclass customclassobject1property1 valueproperty2 valueapropertyn value customclassobject2property1 valueproperty2 valueapropertyn valueif i use expandableobject on the observablecollection it only shows the counts propertyeditadded codemainwindowxamlwindow xclasspropgridexamplemainwindow xmlns xmlnsx xmlnsd xmlnsxctk xmlnsmc xmlnslocalclrnamespacepropgridexample mcignorabled titlemainwindow height350 width525 grid xctkpropertygrid xnamepropertygrid selectedobjectbinding bindingitemxctkpropertygrid gridwindowmainwindowxamlcspublic partial class mainwindow window public mainwindow mainwindowviewmodel mwvm new mainwindowviewmodel thisdatacontext mwvm initializecomponent mainwindowviewmodelcspublic class mainwindowviewmodel public item bindingitem get set public mainwindowviewmodel bindingitem new item public class item public int id get set expandableobject public observablecollectioncustomclass classes get set public item id 1 classes new observablecollectioncustomclass classesaddnew customclass name customfoo public class customclass public string name get set expandableobject public observablecollectiontype types get set public customclass types new observablecollectiontype typesaddnew type name foo value bar typesaddnew type name bar value foo public class type public string name get set public string value get set,['c#'] +1117242,achieving a preview of a pdf or hiding parts of a pdf in a web page from blob format angular if i have a blob representation of a pdf file i have in my angular controller that i am exposing in my html page in the following fashion controller function data var fileback new blobdata type applicationpdf var fileurl urlcreateobjecturlfileback scopecontent scetrustasresourceurlfileurl htmlobject ngshowcontent datacontent typeapplicationpdf stylewidth 100 height 400pxobjectwhat are my options if i wanted to mask parts of the document as it is being thisplayed in the browser such cases include that i can think of just want to prove this is possible btw hiding the 2nd page of a document overlapping a image to hide some width x height spaceany ideas on how any of this could be achieved if not from a blob format is it possible at all what requirements would i have to meet to accomplish a task such as thissuccessful example in browser,['javascript'] +1117405,how do i turn off the mysql password validation it seems that i may have inadvertently loaded the password validation plugin in mysql 57 this plugin seems to force all passwords to comply to certain rulesi would like to turn this offi have tried changing the validate password length variable as suggested here to no availmysql set global validate password length4query ok 0 rows affected 0 secmysql set password for app passwordabcderror 1819 hy0 your password does not satisfy the current policy requirementsi would like to either unload the plugin or neuter it somehow,['mysql'] +1117546,java bitwise operator can someone explain why the following bitwise expressions return different resultssystemoutprintln1311 it prints 0systemoutprintln132 it prints 1,['java'] +1117560,configure spring security for ldap connection i have to configure spring security to authenticate user through ldapthis is the subtree where manager user is ldapsvldpfloal636cnadministrationcnfdamdcfgdclocaland this is where users areldapsvldpfloal636cnproxyuserscnfdamdcfgdclocalso i use this settingautowiredpublic void configureglobalauthenticationmanagerbuilder auth throws exception authldapauthentication contextsource urlldapsvldpfloal636dcfgdclocal managerdncna0x32cnadministrationcnfdamdcfgdclocal managerpasswordpassword and usersearchbasecnproxyuserscnfdam usersearchfiltercn0 ldapauthoritiespopulatormyauthpopulator the problem is exception thrown when i try to make login through user i receive this error20160325 144314 httpnio8086exec6 error osswausernamepasswordauthenticationfilter an internal error occurred while trying to authenticate the userorgspringframeworksecurityauthenticationinternalauthenticationserviceexception ldap error code 32 0208d nameerr dsid031522c9 problem 2001 no object data 0 best match of cnfdamdcfgdclocal nested exception is javaxnamingnamenotfoundexception ldap error code 32 0208d nameerr dsid031522c9 problem 2001 no object data 0 best match of cnfdamdcfgdclocal remaining name cnf67x7acnproxyuserscnfdam at orgspringframeworksecurityldapauthenticationldapauthenticationproviderdoauthenticationldapauthenticationproviderjava207 springsecurityldap402releasejar402release at orgspringframeworksecurityldapauthenticationabstractldapauthenticationproviderauthenticateabstractldapauthenticationproviderjava82 springsecurityldap402releasejar402release at orgspringframeworksecurityauthenticationprovidermanagerauthenticateprovidermanagerjava167 springsecuritycore402releasejar402release at orgspringframeworksecurityauthenticationprovidermanagerauthenticateprovidermanagerjava192 springsecuritycore402releasejar402release at orgspringframeworksecuritywebauthenticationusernamepasswordauthenticationfilterattemptauthenticationusernamepasswordauthenticationfilterjava93 springsecurityweb402releasejar402release at orgspringframeworksecuritywebauthenticationabstractauthenticationprocessingfilterdofilterabstractauthenticationprocessingfilterjava217 springsecurityweb402releasejar402release at orgspringframeworksecuritywebfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava330 springsecurityweb402releasejar402release at orgspringframeworksecuritywebauthenticationlogoutlogoutfilterdofilterlogoutfilterjava120 springsecurityweb402releasejar402release at orgspringframeworksecuritywebfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava330 springsecurityweb402releasejar402release at orgspringframeworksecuritywebcsrfcsrffilterdofilterinternalcsrffilterjava120 springsecurityweb402releasejar402release at orgspringframeworkwebfilteronceperrequestfilterdofilteronceperrequestfilterjava107 springweb421releasejar421release at orgspringframeworksecuritywebfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava330 springsecurityweb402releasejar402release at orgspringframeworksecuritywebheaderheaderwriterfilterdofilterinternalheaderwriterfilterjava64 springsecurityweb402releasejar402release at orgspringframeworkwebfilteronceperrequestfilterdofilteronceperrequestfilterjava107 springweb421releasejar421release at orgspringframeworksecuritywebfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava330 springsecurityweb402releasejar402release at orgspringframeworksecuritywebcontextsecuritycontextpersistencefilterdofiltersecuritycontextpersistencefilterjava91 springsecurityweb402releasejar402release at orgspringframeworksecuritywebfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava330 springsecurityweb402releasejar402release at orgspringframeworksecuritywebcontextrequestasyncwebasyncmanagerintegrationfilterdofilterinternalwebasyncmanagerintegrationfilterjava53 springsecurityweb402releasejar402release at orgspringframeworkwebfilteronceperrequestfilterdofilteronceperrequestfilterjava107 springweb421releasejar421release at orgspringframeworksecuritywebfilterchainproxyvirtualfilterchaindofilterfilterchainproxyjava330 springsecurityweb402releasejar402release at orgspringframeworksecuritywebfilterchainproxydofilterinternalfilterchainproxyjava213 springsecurityweb402releasejar402release at orgspringframeworksecuritywebfilterchainproxydofilterfilterchainproxyjava176 springsecurityweb402releasejar402release at orgspringframeworkwebfilterdelegatingfilterproxyinvokedelegatedelegatingfilterproxyjava346 springweb421releasejar421release at orgspringframeworkwebfilterdelegatingfilterproxydofilterdelegatingfilterproxyjava262 springweb421releasejar421release at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava239 catalinajar8026 at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava206 catalinajar8026 at orgapachecatalinacorestandardwrappervalveinvokestandardwrappervalvejava219 catalinajar8026 at orgapachecatalinacorestandardcontextvalveinvokestandardcontextvalvejava106 catalinajar8026 at orgapachecatalinaauthenticatorauthenticatorbaseinvokeauthenticatorbasejava502 catalinajar8026 at orgapachecatalinacorestandardhostvalveinvokestandardhostvalvejava142 catalinajar8026 at orgapachecatalinavalveserrorreportvalveinvokeerrorreportvalvejava79 catalinajar8026 at orgapachecatalinavalvesabstractaccesslogvalveinvokeabstractaccesslogvalvejava616 catalinajar8026 at orgapachecatalinacorestandardenginevalveinvokestandardenginevalvejava88 catalinajar8026 at orgapachecatalinaconnectorcoyoteadapterservicecoyoteadapterjava518 catalinajar8026 at orgapachecoyotehttp11abstracthttp11processorprocessabstracthttp11processorjava1091 tomcatcoyotejar8026 at orgapachecoyoteabstractprotocolabstractconnectionhandlerprocessabstractprotocoljava673 tomcatcoyotejar8026 at orgapachetomcatutilnetnioendpointsocketprocessordorunnioendpointjava1526 tomcatcoyotejar8026 at orgapachetomcatutilnetnioendpointsocketprocessorrunnioendpointjava1482 tomcatcoyotejar8026 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava1142 na180 60 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava617 na180 60 at orgapachetomcatutilthreadstaskthreadwrappingrunnableruntaskthreadjava61 tomcatutiljar8026 at javalangthreadrunthreadjava745 na180 60caused by orgspringframeworkldapnamenotfoundexception ldap error code 32 0208d nameerr dsid031522c9 problem 2001 no object data 0 best match of cnfdamdcfgdclocal nested exception is javaxnamingnamenotfoundexception ldap error code 32 0208d nameerr dsid031522c9 problem 2001 no object data 0 best match of cnfdamdcfgdclocal remaining name cnf67x7acnproxyuserscnfdam at orgspringframeworkldapsupportldaputilsconvertldapexceptionldaputilsjava183 springldapcore202releasejar202release at orgspringframeworksecurityldapauthenticationbindauthenticatorbindwithdnbindauthenticatorjava148 springsecurityldap402releasejar402release at orgspringframeworksecurityldapauthenticationbindauthenticatorauthenticatebindauthenticatorjava95 springsecurityldap402releasejar402release at orgspringframeworksecurityldapauthenticationldapauthenticationproviderdoauthenticationldapauthenticationproviderjava189 springsecurityldap402releasejar402release 41 common frames omittedcaused by javaxnamingnamenotfoundexception ldap error code 32 0208d nameerr dsid031522c9 problem 2001 no object data 0 best match of cnfdamdcfgdclocal at comsunjndildapldapctxmaperrorcodeldapctxjava3160 na180 60 at comsunjndildapldapctxprocessreturncodeldapctxjava3081 na180 60 at comsunjndildapldapctxprocessreturncodeldapctxjava28 na180 60 at comsunjndildapldapctxc getattributesldapctxjava1329 na180 60 at comsunjnditoolkitctxcomponentdircontextp getattributescomponentdircontextjava235 na180 60 at comsunjnditoolkitctxpartialcompositedircontextgetattributespartialcompositedircontextjava141 na180 60 at javaxnamingdirectoryinitialdircontextgetattributesinitialdircontextjava152 na180 60 at orgspringframeworksecurityldapauthenticationbindauthenticatorbindwithdnbindauthenticatorjava124 springsecurityldap402releasejar402release 43 common frames omittedthere is a problem with spring parameters because if i use java code to authenticate users it worksi cannot figure out where is the problem can you help mei went in debug and this is the output before the error20160330 113522 httpnio8086exec6 debug ossecuritywebfilterchainproxy login at position 6 of 12 in additional filter chain firing filter usernamepasswordauthenticationfilter20160330 113522 httpnio8086exec6 debug osswumantpathrequestmatcher checking match of request login against login20160330 113522 httpnio8086exec6 debug osswausernamepasswordauthenticationfilter request is to process authentication20160330 113522 httpnio8086exec6 debug ossauthenticationprovidermanager authentication attempt using orgspringframeworksecurityldapauthenticationldapauthenticationprovider20160330 113522 httpnio8086exec6 debug osslaldapauthenticationprovider processing authentication request for user f67x7a20160330 113522 httpnio8086exec6 debug osslsfilterbasedldapusersearch searching for user f67x7a with user search searchfilter cn0 searchbase cnfdam scope subtree searchtimelimit 0 dereflinkflag false 20160330 113523 httpnio8086exec6 debug oslcsabstractcontextsource got ldap context on server ldapsvldpfloal636dcfgdclocal20160330 113523 httpnio8086exec6 debug osslspringsecurityldaptemplate searching for entry under dn dcfgdclocal base cnfdam filter cn020160330 113523 httpnio8086exec6 debug osslspringsecurityldaptemplate found dn cnf67xx7acnproxyuserscnfdam20160330 113523 httpnio8086exec6 debug osslabindauthenticator attempting to bind as cnf67xx7acnproxyuserscnfdamdcfgdclocal20160330 113523 httpnio8086exec6 debug ossldefaultspringsecuritycontextsource removing pooling flag for user cnf67xx7acnproxyuserscnfdamdcfgdclocal20160330 113523 httpnio8086exec6 debug oslcsabstractcontextsource got ldap context on server ldapsvldpfloal636dcfgdclocal20160330 113523 httpnio8086exec6 debug osslabindauthenticator retrieving attributes20160330 113523 httpnio8086exec6 error osswausernamepasswordauthenticationfilter an internal error occurred while trying to authenticate the userps if with a ldap browser use cnf67x7acnproxyuserscnfdamdcfgdclocal it bindsupdate if i use java without spring login works i need to use spring and figure out how to configure itoverridepublic void isauthenticatedstring username string password throws ldapexception if databasematlabclientservicesgetbyusersenabledusername null throw new ldapexceptionuser does not exist into dart database please contact the administrator string dn first query to retriev dn hashtablestring object ldapenv new hashtablestring object ldapenvputcontextinitial context factory comsunjndildapldapctxfactory ldapenvputcontextprovider url envgetrequiredpropertyproperty name ldap urlwithout authentication ldapenvputcontextsecurity authentication none with authentication to access to ldap server ldapenvputcontextsecurity authentication simple ldapenvputcontextsecurity principal envgetrequiredpropertyproperty name ldap name ldapenvputcontextsecurity credentials envgetrequiredpropertyproperty name ldap password string returnattribute dn dircontext ctx null namingenumerationsearchresult results null try ctx new initialdircontextldapenv searchcontrols controls new searchcontrols controlssetreturningattributesreturnattribute controlssetsearchscopesearchcontrolssubtree scope without authentication on local server string filter uid username string filter cn username results ctxsearchenvgetrequiredpropertyproperty name ldap usersearchbase filter controls if resultshasmore dn resultsnextelementgetnameinnamespace else throw new ldapexceptionwrong username please retry catch namingexception e throw new ldapexceptione finally try if results null resultsclose if ctx null ctxclose catchexception e throw new ldapexceptione second query to try to access with obtained dn and given password hashtablestring object authenv new hashtablestring object authenvputcontextinitial context factorycomsunjndildapldapctxfactory authenvputcontextprovider url envgetrequiredpropertyproperty name ldap url authenvputcontextsecurity authentication simple authenvputcontextsecurity principal dn authenvputcontextsecurity credentials password dircontext ctx2 null try ctx2 new initialdircontextauthenv catch authenticationexception authex throw new ldapexceptionauthentication error password was wrong catchexception e throw new ldapexceptione finally try if ctx2 null ctx2close catchexception e throw new ldapexceptione update pczeus codeto set referralfollow i have used this codedefaultspringsecuritycontextsource contextsource new defaultspringsecuritycontextsourceldapsvldpfloal636contextsourcesetuserdncna0x32cnadministrationcnfdamdcfgdclocalcontextsourcesetpasswordpasswordcontextsourcesetreferralfollow contextsourceafterpropertiessetldapauthenticationproviderconfigurerauthenticationmanagerbuilder ldapauthenticationproviderconfigurer authldapauthenticationldapauthenticationproviderconfigurer ldapauthoritiespopulatormyauthpopulator usersearchfiltercn0cnproxyuserscnfdamdcfgdclocal usersearchbase contextsourcecontextsourceand i receive the classic exception20160407 093441 httpnio8086exec4 error osswausernamepasswordauthenticationfilter an internal error occurred while trying to authenticate the userorgspringframeworksecurityauthenticationinternalauthenticationserviceexception ldap error code 32 0208d nameerr dsid031001e5 problem 2001 no object data 0 best match of nested exception is javaxnamingnamenotfoundexception ldap error code 32 0208d nameerr dsid031001e5 problem 2001 no object data 0 best match of remaining name if i add usersearchbasecnproxyuserscnfgadamdcfgdclocali receive 20160407 103256 httpnio8086exec4 debug osslsfilterbasedldapusersearch searching for user f6x7a with user search searchfilter cn0cnproxyuserscnfdamdcfgdclocal searchbase cnproxyuserscnfdamdcfgdclocal scope subtree searchtimelimit 0 dereflinkflag false 20160407 103257 httpnio8086exec4 debug oslcsabstractcontextsource got ldap context on server ldapsvldpfloal63620160407 103257 httpnio8086exec4 debug osslspringsecurityldaptemplate searching for entry under dn base cnproxyuserscnfdamdcfgdclocal filter cn0cnproxyuserscnfdamdcfgdclocal20160407 103257 httpnio8086exec4 debug osswausernamepasswordauthenticationfilter authentication request failed orgspringframeworksecurityauthenticationbadcredentialsexception bad credentialswhere dn is why,['java'] +1117568,netstreamplayfailed with videotexture on ios in adobe air app i am trying to get a video to play in an away3d texture on ios it is fine on android and windows the video will play in starling on ios so i know it is not the video here is how i add the video spheregeometry new spheregeometry50 64 48 panotexturematerial new texturematerialpanotexture2dbase false false false panovideomesh new meshspheregeometry panotexturematerial panovideomeshscalex 1 panovideomeshrotatevector3dy axis90 sceneaddchildpanovideomesh panotexture2dbaseplayerplay viewrenderon ios i get this from the netstats when i try and load it as a video texturenetstreamplaystartnetstreamplayfailednetstreamplaystopi am using the away3d nativevideotexture class texture contextcreatevideotexture textureattachnetstream playernsi think it might be do with mp4 encoding and i have had a good look around and cannot find anything that works currently i am trying this in ffmegvcodec libx264 profilev main level 31 crf 23 s 1024768 movflags faststart but what i set does not seem to make a lot of difference any idea why my video is failing to load as a videotexture on ios,['ios'] +1117860,restrict references and triggers i add a pragma restrict references to a procedure in a package for example rnps that procedure implementation inserts a row in a tablethat table has a before insert trigger that trigger reads a variable from a package and puts it newmy columni can compile the package body without problems even though it seems like it is actually reading values from a package variablewhen i execute the procedure it actually works but this is the development eviroment where there are no multiple simultaneous connections usually i am afraid that this could fail in the production enviromentso should i be worried or will this actually workexample codecreate table my table id varchar220 not null user id varchar250 constraint my table pk primary key id enable create or replace package puser is procedure saveuser puserid varchar2 pragma restrict references saveuser wnds rnds rnps function getuser return varchar2 pragma restrict references getuser wnds rnds wnpsend pusercreate or replace package body puser as userid varchar250 procedure saveuser puserid varchar2 is begin userid puserid end saveuser function getuser return varchar2 is begin return userid end getuserend pusercreate or replace package my package is procedure insertmytable pid varchar2 pragma restrict references insertmytable rnpsend my packagecreate or replace package body my package as procedure insertmytable pid varchar2 is begin insert into my tableid valuespid end insertmytableend my packagecreate or replace trigger my table triggerbefore insert on my table for each rowdeclarebegin newuser id pusergetuserend my table triggeredit i know that restrict references is deprecated but knowing this would still be useful for already existing code,['sql'] +1117968,how to decode tripledescryptoservice string in php the following code decrypts a string in vbpublic function desencriptarbyval input as string as string dim iv as byte asciiencodingasciigetbytesabcdefgh dim encryptionkey as byte convertfrombase64stringheregoesthekey dim buffer as byte convertfrombase64stringinput dim des as tripledescryptoserviceprovider new tripledescryptoserviceprovider deskey encryptionkey desiv iv return encodingutf8getstringdescreatedecryptortransformfinalblockbuffer 0 bufferlength end functioni would like to know how to duplicate this process into a php script for a mobile app service thanks,['php'] +1118078,how can i overlay a phonegaps cordovawebview on top of a native view in android i am writing a phonegap application with a custom made plugin this plugin generates a fullscreen animated background essentially a video on it is own surfaceview think of it as a background video i want the regular phonegap webview to be on top of this plugin as a transparent overlay how can i do thatmy current codepublic void initializecordovainterface cordova cordovawebview webview final framelayout layout framelayout webviewgetviewgetparent final activity activity cordovagetactivity activityrunonuithreadnew runnable override public void run try here i insert the surface that i want to be placed behind the webview activitysetcontentviewrlayoutpreview mysurfaceview myview new mysurfaceviewactivity framelayout preview framelayout activityfindviewbyidridmyview previewaddviewmyview catchexception e logecamcapturetag failed egetmessage this question is the opposite of how can i overlay a native view on top of phonegaps cordovawebview in android,['android'] +1118250,ssmtp no longer works invalid response 501 554 heloehlo argument invalid closing connection as the titletags say i run ssmtp on linux for a php serverwhenever i try to send an email i get these errors that do not show up in php only in the logs sudo service sendmail status or sudo service php5fpm statusfrom varlogmaillogmar 31 033434 ip172312238 ssmtp2004 creating ssl connection to hostmar 31 033434 ip172312238 ssmtp2004 invalid response 501 554 heloelo argument invalid closing connection v74sm9147441pfa7 gsmtp mar 31 033434 ip172312238 ssmtp2004 ssl connection using nullmar 31 033434 ip172312238 ssmtp2004 cannot open smtpgmailcom587from varlogmailerr and mailwarnmar 31 033410 ip172312238 ssmtp1997 cannot open smtpgmailcom587mar 31 033434 ip172312238 ssmtp2004 invalid response 501 554 heloehlo argument invalid closing connection v74sm9147441pfa7 gsmtp mar 31 033434 ip172312238 ssmtp2004 cannot open smtpgmailcom587my etcssmtpssmtpconf config file for ssmtp sendmail the person who gets all mail for userids 10 make this empty to thisable rewritingroot the place where the mail goes the actual machine name is required no mx records are consulted commonly mailhosts are named maildomaincommailhubsmtpgmailcom587 where will the mail seem to come fromrewritedomain the full hostnamehostnameauthuserauthpassremovedusestarttlsyes are users allowed to set their own from address yes allow the user to specify their own from address no use the system generated from addressfromlineoverrideyesmy revaliasesrootsmtpgmailcom587localusernamesmtpgmailcom587,['php'] +1118312,get the earliest date in a linq expression i have the following linq in a webapi controllermydate iproductsfirstordefaultdateit works as expected but products is a collection so there can be many dates the above just selects the first onewhat i really want to do is to find the date with the earliest time and select that onehow would that look,"['c#', 'asp.net']" +1118345,sql query to linq syntax using not exist and join my sql query is like below working fine in sql i need to convert this to linq syntaxsqlselect key idfrom localizationkeys as lkwhere not exists select 1 from languages as l join localizationvalues as lv on lid lvlanguageid where ltitle enus and lvlocalizationkeyid lkidlinq syntax i triedvar result from lk in localizationkey where from l in lang join lv in localizationvalue on lid equals lvlanguageid where ltitle enus lvlocalizationkeyid lkid select 1firstordefault select lktolistgetting erroroperator cannot be applied to operand of type intany clue where i made mistake,['c#'] +1118369,consume wcf service over ssl in android i have been using a wcf svc service for a while for which request format is json and response format is xml in an android application which is working fine couple of days ago i implemented a certificate for ssl purpose on the wcf service from digicert using my wildcard capabilities the service is accessible from browser and shows no error below is the webconfigxml version10configuration configsections sectiongroup nameapplicationsettings typesystemconfigurationapplicationsettingsgroup system version40 cultureneutral publickeytokenb77a5c561934e089 section nameintermediatewebservicepropertiessettings typesystemconfigurationclientsettingssection system version40 cultureneutral publickeytokenb77a5c561934e089 requirepermissionfalse sectiongroup configsections systemweb compilation debugtrue targetframework40 customerrors modeoff systemweb systemservicemodel behaviors servicebehaviors behavior nameintermediatewebservicewebbehavior servicemetadata httpsgetenabledtrue servicedebug includeexceptiondetailinfaultstrue behavior behavior to avoid thisclosing metadata information set the value below to false and remove the metadata endpoint above before deployment servicemetadata httpsgetenabledtrue to receive exception details in faults for debugging purposes set the value below to true set to false before deployment to avoid thisclosing exception information servicedebug includeexceptiondetailinfaultsfalse behavior servicebehaviors endpointbehaviors behavior namewebbehavior behavior endpointbehaviors behaviors bindings basichttpbinding binding namesecurehttpbinding maxbufferpoolsize524288 maxreceivedmessagesize9 security modetransport transport clientcredentialtypenone security binding basichttpbinding webhttpbinding binding namewebhttpbindingconfig readerquotas maxstringcontentlength20480 binding webhttpbinding bindings services service behaviorconfigurationintermediatewebservicewebbehavior nameintermediatewebserviceservice1 host baseaddresses add baseaddresshttpsmyurl45 baseaddresses host endpoint address bindingbasichttpbinding contractintermediatewebserviceiservice1 behaviorconfigurationwebbehavior bindingconfigurationsecurehttpbinding service service nameintermediatewebserviceservice1 endpoint address bindingbasichttpbinding bindingconfigurationsecurehttpbinding contractintermediatewebserviceiservice1 service services servicehostingenvironment multiplesitebindingsenabledfalse systemservicemodel systemwebserver validation validateintegratedmodeconfigurationfalse modules runallmanagedmodulesforallrequeststrue systemwebserverconfigurationso now while using the same android code the response is alwaysthe server cannot service the request because the media type is unsupportedi have tried using ssl factory and without it as wellhttpclient client gethttpsclientnew defaulthttpclient new defaulthttpclient httppost get null commandtype params0tostring if loginequalsparams0 jsonstringer img new jsonstringer object keyvalue object keyusernamevalueparams1tostring keypwdvalueparams2tostring keychannelidvalueparams3tostring endobject endobject stringentity se new stringentityimgtostring get new httpposthttps serverip serverport service1svcauth getsetheaderuseragent comappnew getsetheaderaccept applicationjson getsetheadercontenttype applicationjson getsetentityse,"['java', 'c#', 'android']" +1118803,why does getting a member expression member name differ between c and vbnet i have the following c methodprivate static string getmembernametexpressionfunct expr memberexpression memberexpr exprbody as memberexpression if memberexpr null throw new argumentoutofrangeexceptionwrong type of lambda return memberexprmembernameand i can use it like this to print the name of a classlevel field method param or local var note this is prec 60 nameof operatorprivate static int myfieldvar 62private static void dostuffint mymethodparam int mylocalvar 2 debugprintgetmembername mymethodparam prints mymethodparam debugprintgetmembername mylocalvar prints mylocalvar debugprintgetmembername myfieldvar myfieldvariablenow i want to convert this code to vbnet so here is the getmembername methodprivate function getmembernameof texpr as expressionof funcof t as string dim memberexpr as memberexpression trycastexprbody memberexpression if memberexpr is nothing then throw new argumentoutofrangeexceptionwrong type of lambda return memberexprmembernameend functionhowever i am noticing different results when i get the method param and local variable names ie they are both prefixed with vblocal private myfieldvar as integer 62private sub dothismymethodparam as integer dim mylocalvar 2 debugprintgetmembernamefunction mymethodparam prints vblocal mymethodparam debugprintgetmembernamefunction mylocalvar prints vblocal mylocalvar debugprintgetmembernamefunction myfieldvar prints myfieldvar end subi googled vblocal and found this post which is very similar however i think my question is different because i am not getting this behavior with properties if i call thisdebugprintgetmembernamefunction mypropertyi get myproperty moreover my fundamental question is why is the behavior different between c and vbnet ie what is the meaning of vblocal and why is it absent in c whereas that post is more concerned with how to avoid that behavior in vbnet,['c#'] +1119221,find the dimensions height width of an object using camera i want to find the solution to get the dimensions of an object using camera well it sounds like duplicate one how to measure height width and thistance of object using camerabut the solution does not help me outwell from the above link i got some idea to find out the thistance measure thistancecan somebody suggest me how am i supposed to get the width as well as height of an object simple math or any idea would be really helpfulis there any possibilities to achieve the above solution using opencvmeasure height and widthwhat i have tried so farsuppose we assume the fixed thistance we can calculate angle of elevationtani2 l2dhencei 2atanl2dbut still we do not know the value of l length of the objectanother way to find the view angle double thetav mathtoradianscameragetparametersgetverticalviewangle double thetah mathtoradianscameragetparametersgethorizontalviewangleseems not working,['android'] +1119576,visual studio 2015 with update 2 the scc thisplay information package did not load correctly loading a project in visual studio 2015 with update 2 either automatically when vs start or manual load i receive an error saying the scc thisplay information package did not load correctlythe activitylog has entry record541record time20160401 134326048time typeerrortype sourcevisualstudiosource descriptionsetsite failed for package scc thisplay informationan item with the same key has already been added at microsoftvisualstudioservicesvstaskinternalgetresultboolean ignoreuithreadcheckx0dx0a at microsoftvisualstudioservicesvstaskgetresultdescription guidd7bb930558044f929cfe119f4cb0563bguid hr80070057 e invalidarghr errorinfoerrorinfo entry entry record542record time20160401 134326050time typeerrortype sourcevisualstudiosource descriptionend package load scc thisplay informationdescription guidd7bb930558044f929cfe119f4cb0563bguid hr80070057 e invalidarghr errorinfoerrorinfo entryi installed vs2015 with update 2 over vs2015 with update 1 i got the error package did no load correctlyi uninstalled vs2015 completelyi reinstalled vs2015 with update 2 completely i still have the same problem about the scc thisplay information package did not load correctlyupdate the problem seems similar to the same problem i had with vs2015 update 1 but i think it is not related to nuget because i have no package with scc in it i always associated scc with visual source safe could it be related i suspect the problem come from the registry but i cannot figure out wherei tried both solutions from this stack overflow link without successrun the command cprogram files x86microsoft visual studio140common7idedevenvexe resetskippkgsdelete folder componenmodelcachecusersxappdatalocalmicrosoftvisualstudioxxcomponentmodelcacheany idea how to fix this,['c#'] +1119613,is it possible to simplify x 0 x 1 into a single operation so i was trying to write the nth number in the fibonacci sequence in as compact a function as possiblepublic uint fibn uint and return n 0 and 1 1 fibnn1 fibnn2but i am wondering if i can make this even more compact and efficient by changing n 0 and 1into a single comparison is there some fancy bit shift operation that can do this,['c#'] +1119889,java generics type casting necessary this is the code from my textbookstackstring a stackstring new stacknmy questions arewhy is it new stacknwhy do you have to do type conversion on the new stack array created i tried it with juststackstring a new stacknand it compiled and ran fine even after pushing strings into a and printing the pop method also pushing a int in would immediately give me a compiler error so why is it necessary to type cast it to stackstring specifically,['java'] +1119987,how to get one signal users unique id in mobile i am developing a restaurant apphere i am using one signal in my app for send notification here while i place the order i need to send the unique id of the one signal for a specific user for getting notification of your order is placed successfully it is in progressplease wait for that i need users one signal idhow can we get it i am newbie to onesignalplease help me,['android'] +1120001,why does shared ptruse count return a long instead of an unsigned type shared ptr observers 208225 c14 final draft n4296 long use count const noexceptreturns the number of shared ptr objects this included that share ownership with this or 0 when this is emptynote use count is not necessarily efficient a end note,['c++'] +1120249,counting the number of occurrences of a substring within a string in postgresql how can i count the number of occurrences of a substring within a string in postgresqlexamplei have a tablecreate table testuser uid integer not null name text result integer constraint pkey primary key uidi want to write a query so that the result contains column how many occurrences of the substring o the column name contains for instance if in one row name is hello world the column result should contain 2 since there are two o in the string hello worldin other words i am trying to write a query that would take as inputand update the result columni am aware of the function regexp matches and its g option which indicates that the full g global string needs to be scanned for the presence of all occurrences of the substring exampleselect from regexp matcheshello world o greturnsooand select count from regexp matcheshello world o greturns2but i do not see how to write an update query that would update the result column in such a way that it would contain how many occurrences of the substring o the column name contains,['sql'] +1120313,cannot install thrift gem on os x el capitan trying to install thift gem after osx el capitan upgrade gem install thrift building native extensions this could take a while error error installing thrift error failed to build gem native extension usersfoorvmrubiesruby214binruby r siteconf20160402322567dzqelrb extconfrb checking for strlcpy in stringh yes creating makefile make destdir clean make destdir compiling binary protocol acceleratedc compiling bytesc compiling compact protocolc compact protocolc44241 error shifting a negative signed value is undefined werrorwshiftnegativevalue rb exc raiseget protocol exceptionint2fix1 rb str new2buf compilation fails withcompact protocolc44241 error shifting a negative signed value is undefined werrorwshiftnegativevalue,['ruby'] +1121040,how should i keep my constants in php right now i am having a big amount of constant strings and enums in my project since the beginning of it i was using the following approach pseudo php example codeclass constants implements istatuses iemailtypes interface istatuses const status new 1 cosnt status updated 2 interface iemailtypes const email type new 1 const email type updated 2 this approach allowed me to get my constants in a following way anywhere in a code since i included constants class in the indexphpthissendemailbytypeconstantsemail type newhowever i can totally see downsides of the approachconstants class is overloaded with a lots of enums and constants and it is very hard to get right constant naming convention helps to solve it but i do not like this since it requires additional thinking to identify what constant i needconstants class is too big and messyi need to keep tracking of all the interfaces being implemented by cosntants clasince my project is becoming much more bigger now and we need to merge it with another projects code it is required to have class constants approach changed however i got too many dependencies based on that class how should i restruct that approach in order not to break old code that used values of constants classplease share your thoughts and suggestions how to improve my constants approach or confirm that it is decently good and i should support itthank you in advance,['php'] +1121623,ambiguious reference with generic types when using jdk 18 i know that variants of this question have been asked before and i thought i understood the java 8 type resolution system but i am getting an ambiguous reference error for something that i really do not think should be ambiguousimport javautilarraylistimport javautilarraysimport javautilcollectionimport javautillistinterface function t e public class myfns public static e t collectione mapfunction super t e fn collectiont coll return new arraylist public static e t liste mapfunction super t extends e fn listt coll return new arraylist public static e t liste mapfunction super t extends e fn t coll return mapfn arraysaslistcoll the third overload generates two compile errors when compiled through jdk 18error18 12 java reference to map is ambiguous both method etmapfunction super tejavautilcollectiont in myfns and method etmapfunction super t extends ejavautillistt in myfns matchanderror18 15 java incompatible types javautilcollectioncapture1 of extends e cannot be converted to javautillistenow besides the fact that the return type here could be used to resolve the ambiguity and avoid both errors even without the compiler doing that why is the call itself ambiguous function super t extends e should not be castable to function super t e because the latter has a more specific type that does not include a wildcard second even if it were should not the compiler choose the more specific overload which in this case would be to take the second argument as a listt instead of a collectiont what am i missing herefurther adding to the confusion this does work if i specify type in the call to map in the third overloadpublic static e t liste mapfunction super t extends e fn t coll return myfnsetmapfn arraysaslistcollthe above compiles fine even though this type should have been inferred anywaythe first example compiled just fine under jdk 17 however if i use jdk 18 even if i specify source 17 it still causes errors even if it is ambiguous under java 8 the compiler should still work when set to language level 7 correctwhat am i doing wrong,['java'] +1121951,connectivitymanagerconnectivity action deprecated in android n it is mentioned on the official website that apps targeting android and do not receive connectivity action broadcasts and it is also mentioned that jobscheduler can be used as an alternative but the jobscheduler does not provide exactly the same behavior as connectivity action broadcast in my android application i was using this broadcast to know the network state of the device i wanted to know if this state was connecting or connected with the help of connectivity action broadcast and it was best suited for my requirement now that it is deprecated can any one suggest me the alternative approach to get current network state,['android'] +1122044,c databinding an xml to a listview wpf i have searched a lot and tried a lot but i cannot find out why it is not working i am trying to output an xml file to a listview via databinding in my xamlwindow xmlns xmlnsx xmlnsd xmlnsmc xmlnslocalclrnamespacekundenstrom xmlnspropertiesclrnamespacekundenstromproperties xclasskundenstrommainwindow mcignorabled titlekundenstrom height2325 width631 iconhopstartersleekxpbasicusergroupico windowresources xmldataprovider xkeykundenstromdaten sourcekundenxml xpathkundenstromkunden windowresources grid gridcolumndefinitions columndefinition width11 columndefinition width77 columndefinition width11 columndefinition width40 columndefinition width21 columndefinition width357 gridcolumndefinitions tabcontrol xnametabcontrol gridcolumnspan6 tabstripplacementtop margin1001010 tabitem headereintragen grid backgroundffe5e5e5 textbox xnametxtgrund height44 margin1010100 textwrappingwrap verticalalignmenttop combobox xnamecmbtyp1 horizontalalignmentleft margin105900 verticalalignmenttop width287 comboboxitem contentladen comboboxitem contenttelefon comboboxitem contentmail combobox combobox xnamecmbtyp2 margin30258100 verticalalignmenttop comboboxitem contentanfrage comboboxitem contentauftrag comboboxitem contentabholung combobox button xnamebtneintragen contenteintragen horizontalalignmentleft margin108600 verticalalignmenttop width287 height36 clickbtneintragen click grid tabitem tabitem headerkunden anzeigen grid backgroundffe5e5e5 listview margin10 itemssourcebinding sourcestaticresource kundenstromdaten listviewview gridview gridviewcolumn thisplaymemberbindingbinding xpathgrund headergrund gridviewcolumn thisplaymemberbindingbinding xpathtyp1 headerkundentyp gridviewcolumn thisplaymemberbindingbinding xpathtyp2 headeranfragetyp gridviewcolumn thisplaymemberbindingbinding xpathzeitpunkt headerzeitpunkt gridview listviewview listview grid tabitem tabcontrol gridwindowand my xml file looks like thisxml version10 encodingutf8kundenstrom kunden grundhfthgrund typ1ladentyp1 typ2auftragtyp2 zeitpunkt04042016 150138zeitpunkt kunden kunden grundtestestsetsetsegrund typ1ladentyp1 typ2anfragetyp2 zeitpunkt04042016 165759zeitpunkt kundenkundenstromthe data is not showing in the listview do i need additional cs code,['c#'] +1122126,appcelerator bomstream bomstreamwithfileandsysint off t size t int char bomsys this is the warn that with the recent updates of appcelerator appears in my consolewarn 20160405 145101391 app name5489210793 bomstream bomstreamwithfileandsysint off t size t int char bomsys read is a directoryi do not find any information related to this warnfor now does not seem to cause any problem but i do not know what cause thisupdatei found what causes this warningcode examplevar win tiuicreatewindow backgroundcolor whitevar view tiuicreateview width 100 height 100 backgroundimage var a truesetintervalfunctione a a viewbackgroundimage a defaulticonpng tiapiinfoviewbackgroundimage500winaddviewwinopenwhen set a backgroundimage i added the tiapiinfo because without it the warn does not appear,['ios'] +1122203,constexpr template argument weirdness gcc 53 clang 38 claim that the first line in test is bad but the second one is fine msvc 20152 says both are invalidtemplate typename n typename t void f and n t t stdget and t void test stdget stdintegral constant size t 0 stdmake tuple 123 not ok f stdintegral constant size t 0 stdmake tuple 123 ok for gcc clang but not msvcwhat exactly according to the standard is the difference is this code legal to begin withclang error for the first linein file included from maincpp2usrlocalbinlibgccx86 64unknownlinuxgnu530includec530tuple87434 error no matching function for call to get helper2 return stdforward tpstd get helper2 tp t maincpp1010 note in instantiation of function template specialization stdgetstdintegral constantunsigned long 0 int requested here stdgetstdintegral constantsize t 0 stdmake tuple 123 not ok usrlocalbinlibgccx86 64unknownlinuxgnu530includec530tuple8565 note candidate template ignored could not match tuple impl against tuple get helper2 tuple impl i head tail t noexcept usrlocalbinlibgccx86 64unknownlinuxgnu530includec530tuple8615 note candidate template ignored could not match tuple impl against tuple get helper2const tuple impl i head tail t noexcept 1 error generatedgcc errorin file included from maincpp20usrlocalincludec530tuple in instantiation of constexpr tp stdgetstdtuple elements with tp stdintegral constantlong unsigned int 0ul types intmaincpp1075 required from hereusrlocalincludec530tuple87457 error no matching function for call to get helper2stdtupleint return stdforward tpstd get helper2 tp t usrlocalincludec530tuple8565 note candidate templateclass head long unsigned int i class tail constexpr head std get helper2std tuple impl i head tail get helper2 tuple impl i head tail t noexcept usrlocalincludec530tuple8565 note template argument deductionsubstitution failedusrlocalincludec530tuple87457 note mismatched types stdintegral constantlong unsigned int 0ul and int return stdforward tpstd get helper2 tp t usrlocalincludec530tuple87457 note stdtupleint is not derived from std tuple impl i stdintegral constantlong unsigned int 0ul tail usrlocalincludec530tuple8615 note candidate templateclass head long unsigned int i class tail constexpr const head std get helper2const std tuple impl i head tail get helper2const tuple impl i head tail t noexcept usrlocalincludec530tuple8615 note template argument deductionsubstitution failedusrlocalincludec530tuple87457 note mismatched types stdintegral constantlong unsigned int 0ul and int return stdforward tpstd get helper2 tp t usrlocalincludec530tuple87457 note stdtupleint is not derived from const std tuple impl i stdintegral constantlong unsigned int 0ul tail,['c++'] +1122480,quicksort weird time complexity c i have been testing the time complexity of different sorting algorithms for different number sequences and it was all going well until i got quicksorts with pivot in the middle results for sequences that are one half ascending and the other descending the graphby v i mean a sequence in which the first half is descending and the other ascending and by a i mean a sequence where the first half is ascending and the other half is descendingresults for other kinds of sequences look as i would expect but maybe there is something wrong with my algorithmvoid quicksortint lint pint tabint iljpxtablp2w x pivotdo while tabix i while xtabj j if ij wtabi tabitabj tabjw i j while ijif lj quicksortljtabif ip quicksortiptabdoes anybody have an idea what caused such weird results,['c++'] +1122826,how to implement permission based access control with aspnet core i am trying to implement permission based access control with aspnet core for dynamically managing user roles and permissionscreate product delete product etc they are stored in the database data model is like before aspnet core in mvc 5 i was using custom authorizeattribute like below to handle the issuepublic class customauthorizeattribute authorizeattribute private readonly string permissionname get set inject public iaccesscontrolservice accesscontrolservice get set public customauthorizeattributestring permissionname permissionname permissionname public override void onauthorizationauthorizationcontext filtercontext baseonauthorizationfiltercontext var user accesscontrolservicegetuser if permissionname userhaspermission permissionname set error result filtercontexthttpcontextresponsestatuscode 403 return filtercontexthttpcontextitemscustom user user then i was using it in action method like belowhttpgetcustomauthorizepermissionenumperson listpublic actionresult indexpersonlistquery query additionally i was using httpcontextitemscustom user in views to show or hide html partif currentuserhaspermissionpermission namewhen i decided to switch aspnet core all my plan was failed because there was no virtual onauthorization method in the authorizeattribute i tried some ways to solve problem those are belowusing new policy based authorizationi think it is not suitable formy sceneriousing custom authorizeattribute and authorizationfilteri read thispost but i couldnat change it properlyusing custom middlewarehow to get authorizeattribute of currentactionusing actionfilteris it correct for security purposei couldnat decide which way is the best for my scenerio and how to implement itfirst question is mvc5 implementation bad practicesecond question do you have any suggest to implement aspnet core,['c#'] +1123218,animate counter when in viewport i have a counter which animates to a final number which is defined in the html however i would like this animation to happen once it is in the viewporti have a fiddle here which shows how scrolling seems to effect the counter numberdocumentreadyfunction function win fninviewport functioncb return thiseachfunctioni el function vispx var h thisheight r elgetboundingclientrect t rtop b rbottom return cbcallel mathmax0 t 0 h t b h b h vispx winonresize scroll vispx jquery window fignumberinviewportfunctionpx thiseachfunction thispropcounter 0animate counter thistext duration 10 step functionnow thistextmathceilnow i have tried multiple things but i cant seem to achieve what i am afterdocumentreadyfunction function win fninviewport functioncb return thiseachfunctioni el function vispx var h thisheight r elgetboundingclientrect t rtop b rbottom return cbcallel mathmax0 t 0 h t b h b h vispx winonresize scroll vispx jquery window fignumberinviewportfunctionpx thiseachfunction thispropcounter 0animate counter thistext duration 10 step functionnow thistextmathceilnow htmlbody height 100upperpush height 100 width 100 thisplay block background red color whitediv idupperpush scroll downdivdiv idnumbers span classfignumber25span span classfignumber78spandiv,"['jquery', 'html']" +1123563,how to add latexmath to windows 10 ink api from highlights of microsoft build 2016 i saw microsoft was pushing its new ink api what exactly are the new additions can ink understand handwriting and digitize itunderstand mathequations and digitize it ie latexare there any other apis that can do this for uwp or unityhow would i go about creating one myselfjeans link refers to custom recognition is this what i am looking for i feel like there should be an option to add symbols to the lookup dictionary,['c#'] +1123577,how to write unit test for network client i need to write simple http client it could be great to have unit tests for my class but i do not know how to write proper and testable classfor example i have a client like thisclass httpclientpublic httpclientconst stdstring host const stdstring port sessionhost port void send sessionsendrequestsomerequest response response sessionreceiveresponse private somelibraryclientsession sessionhow to test send method that i really send what i want i cannot mock it i can write that httpclient receives somelibraryclientsession object in constructor in test i would pass mock but is it good design i think that the way of implementing of session etc should by hidden in my class do you have any idea,['c++'] +1123633,implement generic get for memorycache or any cache i am trying to write a simple generic gett extension for systemruntimememorycachewhy simple because generally i know objects real type before caching it so when i retrieve it from cache i am not going to convert it in unpredictable waysfor example if boolean true value is stored in cache with cachekey id sogetstringid truegetintid 1 any result 0 is okaygetsomeunpredictabletype null just ignore these trouble conversionsheres my incomplete implementionpubic static t dogethis memorycache cache string key object value cachegetkey if value null return defaultt if value is t return tvalue todo i am not sure if following logic is okay or not 1 if t and value are both numeric type eg long double how to code it 2 if t is string call something like converttostring type t typeoft t nullablegetunderlyingtypet t if typeoficonvertibleisassignablefromvaluegettype return tconvertchangetypevalue t return defaulttany suggestions are highly appreciatedupdate 04112016for those nice suggestions given i implement my first version of gettpublic class memcache private class lazyobjectt lazyt public lazyobjectfunct valuefactory basevaluefactory public lazyobjectfunct valuefactory lazythreadsafetymode mode basevaluefactory mode private static t castvaluetobject value if value null value is dbnull return defaultt type valtype valuegettype if valtypeisgenerictype valtypegetgenerictypedefinition typeoflazyobject return castvaluetvaltypegetpropertyvaluegetvaluevalue if value is t return tvalue type t typeoft t nullablegetunderlyingtypet t if typeoficonvertibleisassignablefromt typeoficonvertibleisassignablefromvaluegettype return tconvertchangetypevalue t return defaultt private memorycache m cache public t gettstring key return castvaluetm cachegetkey public void settstring key t value cachedependency dependency m cachesetkey value dependencyascacheitempolicy public t getoraddtstring key funct fnvaluefactory cachedependency dependency lazyobjectt noo new lazyobjecttfnvaluefactory lazythreadsafetymodeexecutionandpublication lazyobjectt old m cacheaddorgetexistingkey noo dependencyascacheitempolicy as lazyobjectt try return castvaluetold noovalue catch m cacheremovekey throw removetrim,['c#'] +1123676,slick return inserted row with auto increment id i am trying to make an insert into a mysql table and to return the row with the auto increment id my code is belowprivate val log tablequerygcmlogtabledef savelog gcmlog trygcmlog try val newid log returning logmap id log logcopyid newidbut my compilation fails for my code with the below errortype mismatch found slickprofilefixedsqlactionlongslickdbionostreamslickdbioeffectwrite required longalso trieddef savelog gcmlog trygcmlog try log returning logmap id into log newid logcopyid newid logbut still fails withtype mismatchfound slickprofilefixedsqlactionmodelsgcmlogslickdbionostreamslickdbioeffectwriterequired modelsgcmlogi referred the so question how to catch slick postgres exceptions for duplicate key value violations and slick documentation here much appreciated if someone can tell me whats going on and how this can be fixedthanks,['mysql'] +1123856,cast a uint32 variable to a bit field undefined behavior i have a register definition provided by the microcontroller manufacturer that can be handled as a bit field the register is defined as followsdefine scu wdtscon0 scu wdtscon0 type 0xf00360f0uthe bit field definition looks like thistypedef volatile union unsigned uint istruct unsigned endinit 1 00 endofinitialization control bit unsigned lck 1 11 lock bit to control access to wdtxcon0 unsigned hpw0 2 32 hardware password 0 unsigned hpw1 4 74 hardware password 1 unsigned pw 8 158 userdefinable password field for access to wdtxcon0 unsigned rel 16 3116 reload value for the wdt b scu wdtscon0 typeinstead of directly writing to the register i want to use a uint32 buffer variable first but still be able to edit it in the manner of the register bit field definitionthis implementation seems to be working as the address is just replaced with buffer variablevolatile uint32 buffer variablescu wdtscon0 type register buffer scu wdtscon0 type buffer variablecould this lead to undefined behavior,['c'] +1123926,how to make multiple request and wait until data is come from all the requests in retrofit 20 android current coderetrofit retrofit new retrofitbuilder baseurlconstantbaseurl addconverterfactorygsonconverterfactorycreate buildapiservice service retrofitcreateapiserviceclasscallresponsewrap call servicegetnewsdatacallenqueuenew callbackresponsewrap override public void onresponsecallresponsewrap call1 responseresponsewrap response if responseissuccess responsewrap finalres responsebody forint i0 ifinalresgetresponsegetresultssize i string title finalresgetresponsegetresultsgetigetwebtitle news and new newstitlecategory title null newslistaddn adapterrecommendation adapter new adapterrecommendationgetapplicationcontext newslist listviewsetadapteradapter else toastmaketextgetapplicationcontext onresponse something wrong responsemessage toastlength longshow override public void onfailurecallresponsewrap call1 throwable t toastmaketextgetapplicationcontext exception tgetmessage toastlength longshow works finenow i want to make multiple calls number of call will be decided at run time and all calls gives data in same format data from all calls needs to be add to newslist once data is available from all calls and added to newslist calladapterrecommendation adapter new adapterrecommendationgetapplicationcontext newslistlistviewsetadapteradaptercan anyone help me what is the best way to get data from multiple calls and wait until all request is not over in retrofit 20,['android'] +1124045,even basic ionic project with cordova wkwebview engine plugin produces white screen my problemthe ionic app i am developing is horribly slow after finding out uiwebview is the culprit i am looking for ways to speed it up with wkwebview being the most promising solution what my project looks likewhen setting up a sample ionic project for example with the current cordova 410 cli i am using ionic 124 uiwebview is used as default however since cordova 4 the new and faster wkwebview is supported outofthebox and can be forced at least in ios 9 cordova 4 supports wkwebviewthe plugin i used configuredvia cordova plugin add cordovapluginwkwebviewengine the support is added for the ios platform 93 right now when this plugin is added and properly configured in the configxml withfeature namecdvwkwebviewengine param nameiospackage valuecdvwkwebviewengine feature preference namecordovawebviewengine valuecdvwkwebviewengine what i tried so farin the terminal ionic build ios then build succeeds and when installing the app via xcode 73 on os x el capitan 10113 in the console log the using wkwebview message is printed but then right after the splashscreen the app container fades into a white screen of death as soon as i remove that plugin uiwebview is used and the app works as expectedalternative replacing the original plugin wkwebviewenginelocalhost with one with integrated localhost works as i understood the wkwebview should be supported by cordova and ionic right out of the box without having to rely on some labs plugin with an integrated server which was developed to support ios 8 which i do not need i understand that wkwebview has quite some limitations compared to the old uiwebview especially when it comes to handling file statements known issues but there for sure must be someone out there who got ionic cordova wkwebview working without all the hassle i had right there must be better ways to achieving a simple speed improvement for the webviewi tried probably every solution config plugin combination cordova cli version downgrade minimum being 400 for wkwebview support clearing caches and resetting and restarting of my device new install and readding of platforms and update of cordova npm various plugins but all of them either did not help at all except for the apache labs plugin above or seemed like a huge mess that did not change anythingwhen remote debugging the ios app on the device via my local safari i can see in the elements tree that the body tag stays either empty or a simple ngview placeholder for an angular element is shown am i correct that there must be a problem with the retrieval of filesangular scripts through the way cordova via wkwwebview handles itnote the app itself works fine either with ionic serve or ionic emulate ios only when deploying to a real device over xcode since ionic run ios does not work but that is a different story the white screen appearsany help is very much appreciated as it seems to me i have to either use the localhostwkwebview plugin or let the users suffer from poor speedthanks a lot,['ios'] +1124830,gulpfilejs watch best practice here is my current watchlist for my gulpfilejs gulp watchlistgulptaskwatch browsersync sass function gulpwatchappscscss sass gulpwatchapphtmlonchange browsersyncreload gulpwatchappjsjsonchange browsersyncreload add more watchers hereand this works but a tutorial i am following has something slightly differentgulptaskwatch browsersync sass function gulpwatchappscscss sass reloads the browser whenever html or js files change gulpwatchapphtml browsersyncreload gulpwatchappjsjs browsersyncreload do i need the onchange browsersyncreload it works i am just curious if what i am doing is not good practice thanks,['javascript'] +1124865,uninstall mono net core and all related stuffs from osx hei guys i was following this tutorial in order to run net core in my osxif you choose to install mono select the universal installer to make sure you get the x64 version edgejs requires mono x64if you choose to install coreclr follow these stepsbrew tap aspnetdnxbrew updatebrew install dnvmsource dnvmshdnvm install latest r coreclr alias edgecoreclrthen install and build edgejsbrew install pkgconfigdnvm use edgecoreclrnpm install edgenow i would like to remove all this stuffs but i am not finding the pathsi removed the dnvm and the pkgconfig with brew uninstall what about the ordersthanks,['.net'] +1125262,converting array iteration to lambda expression i have below code which iterates over cookies to reset the cookie whose name matches cookiesessionname cookie cookies httpservletrequestgetcookies loggerinfoclearing cookies on welcome page if cookies null for cookie cookie cookies if cookiegetnameequalscookiesessionname cookiesetvaluenull cookiesetmaxage0 cookiesetpath httpservletresponseaddcookiecookie can someone simplify it using java 8 lambda expression,['java'] +1125295,how do i find the nearest common superclass of two noninterface classes to find the nearest common superclass given two noninterface classes a and b i do the followingstatic class findclosestcommonsuperfinal class a final class b iteratorclass patha pathfromobjectaiterator iteratorclass pathb pathfromobjectbiterator class res objectclass class c while pathahasnext pathbhasnext if c pathanext pathbnext res c return respathfromobject returns a listclass representing inheritance chain starting from objectclastatic listclass pathfromobjectclass cl listclass res new arraylist while cl null resaddcl cl clgetsuperclass collectionsreverseres return resmy question is does some outofthebox jdk solution exist for this maybe using classloader or some specific functionality or a better algorithm that does not require two iterations,['java'] +1125385,is it possible to thisentangle a template from its arguments in c assume i receive two arguments to a template t1 and t2 if i know t1 is itself a templated class eg a container and t2 can be anything is it possible for me to determine the base template type for t1 and rebuild it using t2 as its argumentfor example if i receive stdvectorint and stdstring i would want to automatically build stdvectorstdstring however if i were given stdsetbool and double it would produce stdsetdoubleafter reviewing type traits relevant blogs and other questions here i do not see a general approach to solving this problem the only way i can currently see to accomplish this task is to build template adapters for each type that could be passed in as t1for example if i hadtemplatetypename t inner typename t newstdlistt new adapttemplatestdlistt inner t newtemplatetypename t inner typename t newstdsett new adapttemplatestdsett inner t newtemplatetypename t inner typename t newstdvectort new adapttemplatestdvectort inner t newi should be able to use decltype and rely on operator overloading to solve my problem something along the lines oftemplate typename t1 typename t2void mytemplatedfunction using my type decltypeadapttemplatet1t2am i missing something is there a better approachwhy do i want to do thisi am building a c library where i want to simplify what users need to do to build modular templates for example if a user wants to build an agentbased simulation they might configure a world template with an organism type a population manager an environment manager and a systematics managereach of the managers also need to know the organism type so a declaration might look something likeworld neuralnetworkagent eapopneuralnetworkagent mazeenvironmentneuralnetworkagent lineagetrackerneuralnetworkagent worldi would much rather users not have to repeat neuralnetworkagent each time if i am able to change template arguments then default arguments can be used and the above can be simplified toworld neuralnetworkagent eapop mazeenvironment lineagetracker worldplus it is easier to convert from one world type to another without worrying about type errorsof course i can deal with most errors using static assert and just deal with the longer declarations but i would like to know if a better solution is possible,['c++'] +1125735,python tox creating rpm virtualenv as part of ci pipeline unsure about where in workflow i am investigating how python applications can also use a ci pipeline but i am not sure how to create the standard workflowjenkins is used to do the initial repository clone and then initiates tox basically this is where maven andor msbuild would get dependency packages and build which tox does via pip so all good herebut now for the confusing part the last part of the pipeline is creating and uploading packages devs would likely upload created packages to a local pip repository but then also possibly create a deployment package in this case it would need to be an rpm containing a virtualenv of the application i have made one manually using rpmvenev but regardless of how its made how what such a step be added to a tox config in the case if rpmvenv it creates its own virtualenv a self contained command so to speak,['python'] +1126575,algorithm to sort rows and cols by similarity i fell across a spreadsheet that explains a method to sort both rows and columns of a matrix that contains binary data so that the number of changes between consecutive rows and cols is minimzedfor example starting withafter 15 manual steps described in the tabs of the spreadsheed the following table is obtainedi would like to knowwhat is the common name of this algorithm or method how to apply it to larger table where 2n would overflowhow to generalize it to non binary data for example using levenshtein thistance if there is any link to code excel vba python already implementing this otherwise i will write it thanks,['python'] +1126593,espresso does no record any intent if there are no buttons i am trying to write a test to verify intent launching with espresso the problem is that intended does not record any intenti have this test testpublic void shoulddosomething startactivity intendedhascomponenthasclassnametemplatepicturecaptureactivityclassgetnameand in my activity i have this codeoverridepublic void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewonrequestlayout intent intent new intentthis templatepicturecaptureactivityclass startactivityintentthe test result is thisandroidsupporttestespressobasedefaultfailurehandlerassertionfailedwithcauseerror wanted to match 1 intents actually matched 0 intentsintentmatcher has component has component with class name is cathelmrecerteluitemplatepicturecapturetemplatepicturecaptureactivity package name an instance of javalangstring short class name an instance of javalangstringmatched intentsrecorded intentsi have tried to launch the intent inside onclicklisten and it worked but without it i cannot get it to work i also tried with idling resources with no luck do you know how to achieve this,['android'] +1126611,how to pip install a package that has git dependencies i have a private library called somelibrary actual names have been changed with a setup file looking somewhat like thissetup namesomelibrary omitted some less important stuff here install requires somegitdependency anothergitdependency dependency links gitsshmyorganizationsomegitdependencygiteggsomegitdependency gitsshmyorganizationanothergitdependencygitegganothergitdependency all of these git dependencies may be private so installation via http is not an option i can use python setuppy install and python setuppy develop in somelibrarys root directory without problemshowever installing over git does not workpip install v e gitsshmyorganizationeggsomelibrarythe command fails when it looks for somegitdependency mistakenly assumes it needs to get the dependency from pypi and then fails after concluding it is not on pypi my first guess was to try rerunning the command with processdependencylinks but then this happened cannot look at git url gitsshmyorganizationsomegitdependencygiteggsomegitdependency could not find a version that satisfies the requirement somegitdependency from somelibrary from versions why is it producing this vague error whats the proper way to pip install a package with git dependencies that might be private,['python'] +1126857,print whole html page including pdf file inside iframe i have got an assignment to embed relatively small pdf file inside html page and print the entire html pade including the pdf file inside the iframehere is the structure of my html pagehere is my codemedia printbody thisplayblock toprintthisplayblock border0 width100 minheight500pxbody button onclickwindowprintprintbuttonh3must be printedh3 p must be printedp iframe classtoprint src files scan create reducefilesizepdf stylewidth100 height97vhiframeh3must be printedh3 p must be printedpbodycurrently i am printing the page using css media query but unfortunately this media query prints the pdfs first page onlywhat can i do print the entire pdf file,"['javascript', 'html', 'css']" +1126874,auto properties is not working in c hello there fellow friendsi have a small problem with auto properties i am new to programming in general and i have only started learning about classes and objects when i try to use auto properties the field does not get exposed not sure if thats the right way of putting ittake a look at the commented parts of the properties in both animal classes to understand what i am talking aboutright now i have this animals class public class animals fields private string name public animalsstring name thisname name default constructor public animals this is the problematic portion public string name get set public void bark consolewriteline0 said wowow name this is my main program classclass program static void mainstring args consolewritelineenter name string name consolereadline animals dog new animalsname dogbark animals cat new animals consolewritelineenter second name catname consolereadline catbark the output is as follows the last line is my problem enter name bob bob said wowow enter second name sarah said wowow sarah is missing herehowever when i change the properties from getset to its full version in the class it outputs the correct output edited codepublic class animals fields private string name public animalsstring name thisname name public animals apparently this is the correct way of making properties public string name get return name set name value public void bark consolewriteline0 said wowow name output sarah is present in the last line enter name bob bob said wowow enter second name sarah sarah said wowowmy question is why is it when auto properties is used i do not get my desired output but when i write the properties in full i do get my desired outcomethanks for taking a look at my question hopefully it was not too long,['c#'] +1126892,bind to pgcrypto from python i would like to call some pgcrypto functions from python namely px crypt i cannot seem to figure out the right object files to link it seemsheres my codeinclude pythonhinclude postgreshinclude pgcryptopxcrypthstatic pyobjectpgcryptpyobject self pyobject args const char key const char setting if pyarg parsetupleargs ss key setting return null return py buildvalues px cryptkey setting 0static pymethoddef pgcryptmethods pgcrypt pgcrypt meth varargs call pgcryptos crypt null null 0 nullpymodinit funcinitpypgcryptovoid void py initmodulepypgcrypto pgcryptmethodsand gcc commands and outputx86 64linuxgnugcc pthread dndebug g fwrapv o2 wall wstrictprototypes fnostrictaliasing d fortify source2 g fstackprotectorstrong wformat werrorformatsecurity fpic ihomeionutgithubpostgrescontrib iusrincludepostgresql94server iusrincludepython27 c pypgcryptoc o buildtemplinuxx86 6427pypgcryptoox86 64linuxgnugcc pthread shared wlo1 wlbsymbolicfunctions wlzrelro fnostrictaliasing dndebug g fwrapv o2 wall wstrictprototypes d fortify source2 g fstackprotectorstrong wformat werrorformatsecurity wlzrelro d fortify source2 g fstackprotectorstrong wformat werrorformatsecurity buildtemplinuxx86 6427pypgcryptoo usrlibpostgresql94libpgcryptoso lpgport lpq o buildliblinuxx86 6427pypgcryptosoerror ispython c import pypgcrypto print pypgcryptopgcryptfoo bartraceback most recent call last file string line 1 in moduleimporterror usrlibpostgresql94libpgcryptoso undefined symbol interruptpending,"['python', 'c']" +1126935,check in the onreceivedsslerror method of a webviewclient if a certificate is signed from a specific selfsigned ca i would like to override the onreceivedsslerror of a webviewclient here i want to check if the errorgetcertificate certificate is signed from a selfsigned ca and only in this case call the handlerproceed in pseudocodeoverridepublic void onreceivedsslerrorwebview view sslerrorhandler handler sslerror error sslcertificate servercertificate errorgetcertificate if signed from my selfsigned ca handlerproceed else superonreceivedsslerrorview handler error the public key of my ca is saved in a bouncycastle resource called rootcabks how can i do,['android'] +1127072,bootstrap carousel make text appearing letter by letter i am using bootstrap carousel for the slider on each slide there is some text over iti would like that text over the slides to aappear letter by letteri have almost solved itbut there are 2 issueson first slide the text does not come up at allif the user goes to some other tab on the browser means if the current window is not in focus then everything gets messed uphere is my fiddlehtmlmain div classcontainer div classblockwrap div idjscarousel classcarousel slide dataridecarousel wrapper for slides div classcarouselinner rolelistbox div classitem active img src 130921474920553591main 900jpg1448476701 altchania div classcaption div classmystring hidecompanies with inbound marketingdiv h4we help div classdemotxtdiv h4 div div div classitem img src 130921474920553591main 900jpg1448476701 altchania div classcaption div classmystring hidecompanies with inbound marketingdiv h4we help div classdemotxt div h4 div div div classitem img src 130921474920553591main 900jpg1448476701 altflower div classcaption div classmystring hide2companies with inbound marketingdiv h4we help div classdemotxtdiv h4 div div div classitem img src 130921474920553591main 900jpg1448476701 altflower div classcaption div classmystring hide3companies with inbound marketingdiv h4we help div classdemotxtdiv h4 div div div classoverlayeffectdiv div div div div mainjsdocumentreadyfunction jscarouselcarousel interval 50 jscarouselonslidbscarousel function var showtext function target message index interval if index messagelength targetappendmessageindex settimeoutfunction showtexttarget message index interval interval var str thisfindactive mystringhtml active demotxthtml showtextactive demotxt str 0 100,"['javascript', 'jquery']" +1127478,sfinae not happening with stdunderlying type below sfinae code with variadic templates compiles nicely using clang 371 c14include arrayinclude iostreaminclude vectorinclude cstdintenum class bar uint8 t ay bee seestruct s static void foo stdbeginh is defined for h of type htemplatetypename h typename tstatic typename stdenable ifstdis pointerdecltypestdbeginstddeclvalhvaluetype fooconst h t t stdcout containern foostdforwardtt h is integraltemplatetypename h typename tstatic typename stdenable ifstdis integraltypename stdremove referencehtypevaluetype fooconst h t t stdcout integern foostdforwardtt h is an enum with underlying type uint8 ttemplatetypename h typename tstatic typename stdenable ifstdis sametypename stdunderlying typehtypeuint8 tvaluetype fooconst h t t stdcout enumn foostdforwardtt int main sfoostdarrayint8 5 5l stdvectorint 5li want the correct overload of foo to be called recursively based on the type h if stdbeginh is defined for an h of type h i want theoverload number 1 to be chosenif h is an integral type i want overload number 2this works as it is but if i add another overload for enum types you can try to uncomment the third overload then i geterror only enumeration types have underlying typesi agree that only enums got an underlying type hence why is not the third overload with stdunderlying type get sfinaed away,['c++'] +1127803,php failed to open stream no such file or directory in php scripts whether calling include require fopen or their derivatives such as include once require once or even move uploaded file one often runs into an error or warning failed to open stream no such file or directorywhat is a good process to quickly find the root cause of the problem,['php'] +1127891,android studio git and three ways merge on android studio i created a new branch from the master and commited the new branch two timesthen i checkedout the master and commited it one timeso i have two branches with two thistinct endpoints and a common parentnow i am trying a three ways mergeright click on the new branch click on the new branch name then merge but appears a popupcould not merge testmergebranch conflict content merge conflict in files list and nothing more happensthus i click on vcs menu git resolve conflicts then i click accept yours button to resolve the conflicts on selected files the resolve window thisappears and again nothing more happensthus i go to readd to stage the resolved files but the add option is thisabledany hintsandroid studio 20 on ubuntu 1404 it needs an androidstudiogit tag,['android'] +1128286,setting opacity to all except a child in the last tbody iditems trtditem 1tdtr trtditem 2tdtr trtditem 3tdtr trtditem 4tdtr trtditem 5tdtr trtda1a a2a a classa33a tdtrtbodyi want to set the opacity to 05 except the third anchor tag in the last td how to set,"['jquery', 'css']" +1128432,creating a php function with predefined values for a parameter let us say i have the following methodpublic function choosecarcar return you chose this car cari need to set specific values for what can be passed to choosecar in the car argument for example let the developer choose between mercedes bmw and ford is that doable in php,['php'] +1128771,getting xml from stored procedure i am getting an output of xml from a stored procedure what i am trying to do is get that xml and pass it out via aspnetpublic xmldocument getpunchlistxmlstring communitydesc try using connection new sqlconnectionconnectionstring connectionopen using sqlcommand command new sqlcommandgetpunchlist connection commandcommandtype commandtypestoredprocedure sqlparameter parameter1 new sqlparametercommunitydesc sqldbtypevarchar parameter1value communitydesc parameter1direction parameterdirectioninput commandparametersaddparameter1 var doc new xmldocument var reader commandexecutexmlreader if readerread docloadreader return doc finally connectionclose but i keep getting these errorserror messagean error has occurredmessage exceptionmessage the objectcontent1 type failed to serialize the response body for content type applicationxml charsetutf8 exceptionmessage exceptiontypesysteminvalidoperationexceptionexceptiontype stacktrace innerexception messagean error has occurredmessage exceptionmessage type systemxmlxmldocument is an invalid collection type since it does not have a valid add method with parameter of type systemobject exceptionmessage exceptiontype systemruntimeserializationinvaliddatacontractexception exceptiontype stacktrace at systemruntimeserializationdatacontractdatacontractcriticalhelperthrowinvaliddatacontractexceptionstring message type type at writearrayofanytypetoxmlxmlwriterdelegator object xmlobjectserializerwritecontext collectiondatacontract at systemruntimeserializationcollectiondatacontractwritexmlvaluexmlwriterdelegator xmlwriter object obj xmlobjectserializerwritecontext context at systemruntimeserializationxmlobjectserializerwritecontextwritedatacontractvaluedatacontract datacontract xmlwriterdelegator xmlwriter object obj runtimetypehandle declaredtypehandle at systemruntimeserializationxmlobjectserializerwritecontextserializewithoutxsitypedatacontract datacontract xmlwriterdelegator xmlwriter object obj runtimetypehandle declaredtypehandle at systemruntimeserializationdatacontractserializerinternalwriteobjectcontentxmlwriterdelegator writer object graph datacontractresolver datacontractresolver at systemruntimeserializationdatacontractserializerinternalwriteobjectxmlwriterdelegator writer object graph datacontractresolver datacontractresolver at systemruntimeserializationxmlobjectserializerwriteobjecthandleexceptionsxmlwriterdelegator writer object graph datacontractresolver datacontractresolver at systemruntimeserializationdatacontractserializerwriteobjectxmlwriter writer object graph at systemnethttpformattingxmlmediatypeformatterwritetostreamtype type object value stream writestream httpcontent content at systemnethttpformattingxmlmediatypeformatterwritetostreamasynctype type object value stream writestream httpcontent content transportcontext transportcontext cancellationtoken cancellationtoken end of stack trace from previous location where exception was thrown at systemruntimecompilerservicestaskawaiterthrowfornonsuccesstask task at systemruntimecompilerservicestaskawaiterhandlenonsuccessanddebuggernotificationtask task at systemruntimecompilerservicestaskawaitergetresult at systemwebhttpwebhosthttpcontrollerhandlerwritebufferedresponsecontentasyncd 1bmovenext stacktrace innerexceptionerrorwhat am i doing wrong is there something wrong with the way i am trying to get the xml or would be an issue with the xml itselfi have tried the followingvar doc new xmldocumentstring s using xmlreader reader commandexecutexmlreader while readerread docloadreader s readerreadouterxml docloadxmls return docand got these errorserrormessagean error has occurredmessageexceptionmessagethe objectcontent1 type failed to serialize the response body for content type applicationxml charsetutf8exceptionmessageexceptiontypesysteminvalidoperationexceptionexceptiontypestacktraceinnerexceptionmessagean error has occurredmessageexceptionmessagetype systemxmlxmldocument is an invalid collection type since it does not have a valid add method with parameter of type systemobjectexceptionmessageexceptiontypesystemruntimeserializationinvaliddatacontractexceptionexceptiontypestacktraceat systemruntimeserializationdatacontractdatacontractcriticalhelperthrowinvaliddatacontractexceptionstring message type type at writearrayofanytypetoxmlxmlwriterdelegator object xmlobjectserializerwritecontext collectiondatacontract at systemruntimeserializationcollectiondatacontractwritexmlvaluexmlwriterdelegator xmlwriter object obj xmlobjectserializerwritecontext context at systemruntimeserializationxmlobjectserializerwritecontextwritedatacontractvaluedatacontract datacontract xmlwriterdelegator xmlwriter object obj runtimetypehandle declaredtypehandle at systemruntimeserializationxmlobjectserializerwritecontextserializewithoutxsitypedatacontract datacontract xmlwriterdelegator xmlwriter object obj runtimetypehandle declaredtypehandle at systemruntimeserializationdatacontractserializerinternalwriteobjectcontentxmlwriterdelegator writer object graph datacontractresolver datacontractresolver at systemruntimeserializationdatacontractserializerinternalwriteobjectxmlwriterdelegator writer object graph datacontractresolver datacontractresolver at systemruntimeserializationxmlobjectserializerwriteobjecthandleexceptionsxmlwriterdelegator writer object graph datacontractresolver datacontractresolver at systemruntimeserializationdatacontractserializerwriteobjectxmlwriter writer object graph at systemnethttpformattingxmlmediatypeformatterwritetostreamtype type object value stream writestream httpcontent content at systemnethttpformattingxmlmediatypeformatterwritetostreamasynctype type object value stream writestream httpcontent content transportcontext transportcontext cancellationtoken cancellationtoken end of stack trace from previous location where exception was thrown at systemruntimecompilerservicestaskawaiterthrowfornonsuccesstask task at systemruntimecompilerservicestaskawaiterhandlenonsuccessanddebuggernotificationtask task at systemruntimecompilerservicestaskawaitergetresult at systemwebhttpwebhosthttpcontrollerhandlerwritebufferedresponsecontentasyncd 1bmovenextstacktraceinnerexceptionerror,"['c#', 'asp.net']" +1128830,can i use a png as a mask for this water animation instead of tag so i found this amazing codepen animation that animates a water filling effect to any text provided via the text tag using gsap i thinkcodepen screenshot belowclick here for codepenmy question how would i go about using a png image instead of html text to achieve the same resultsfor example instead of the current code text idtext transformmatrix1 0 0 1 80684 1167852 fontfamilycabin condensed fontsize161047loadingtexti was looking to do something more along the lines ofimg srcloadingpng idtext transformmatrix1 0 0 1 80684 1167852 width569 height186example of loading png img one could use same dimensions as img snippet abovethanks for any help not best with this stuff and would love to use the effecthere is an svg of the png file posted above if that works better imghusloadingpngsvg,"['jquery', 'css']" +1128843,plugin throwing typeerror after wordpress 45 update i am debugging a visual composer plugin that broke after i updated wordpress to 45 and i cannot figure out why it is throwing a typeerrorthe error message in the consolejqmigrate migrate is installed version 140 loadscriptsphpuncaught typeerror templateget is not a function composerviewjsver4173the only occurrences of template are found in the code below i understand that this is not very much context to go off of but how can i resolve this error convert html into correct element param html html2element functionhtml var attributes template if isstringhtml thistemplate templatehtml template thistemplatethismodeltojsontrim else thistemplate html template html eachtemplateget0attributes functionattr errors on this line attributesattrname attrvalue thiselattrattributeshtmltemplatehtml thissetcontent thisrendercontentupdateit looks like this might be a problem with jquery wordpress 45 includes jquery 112 which fixed a bug that allowed certain code to be run with incorrect syntax i assume that the plugin code must have had incorrect syntax but ran nonetheless until now,"['javascript', 'jquery', 'html']" +1128855,cgpdfdocument unable to read pdf i followed the following example to view a pdf in my app xamarinios everything worked fine until recently i started to notice some pdf files cannot be read using this methodi open and got info on my mac and i noticed the followingif i export the document to pdf using the mac viewer it can be read just fine but the size is increaseif i try to open the file as is nothing is viewable but a white pagethis happens for my ios app only the viewer on my android works just finei can export every file to pdf using the macs viewer but it is an extra step than what i need what can i do to fix thisoriginal encoding pdfscanlib v122 in adobe acrobat 10116export encoding mac os x 10105 quartz pdfcontexti ran additional tests to the program and i can conclude the issue is with the compression being used on the pdf files is there any way cgpdfdocument can remove or ignore the compression so i can view the pdf i upload the pdf to my mobile backend where i split the pages i am using pdfsharp to accomplish this if possible is there a way to clean out the files before being save to the server this issue is only affecting the ios version of my appafter extra testing i have come accross the following bug hereit will appear the jbig2 compression used has a known bug that causes errors when reading a jpg in a pdf i will continue further testing until i can find a solutioncorrections the pdf compression is not jbig2 but flatedecode after testing and reading the binary data i have notice that both the original and the export have the same type of compression will update with more information as i try to figure this out,"['c#', 'ios']" +1129278,foreach is picking the first checkbox only if checked i am working on the following code in order to pick checkboxes from a form if i check the first checkbox everything works great if i check another checkbox i get the undefined index error when sending bulkcopy form keep in mind that i am getting the checkboxes with post method and the submit button is above the checkboxes due to the complexity of the location of the form and the fields what i need essentially is to pick multiple checkboxes and add certain values to the databasephp bulkcopyphp session start if sessionadmin logged in true headerlocationloginhtml exit include dbphp from mysql real escape string getfrom room mysql real escape string postroom ifempty postid foreach postid as check id check sel mysql queryselect from from where id id limit 1 or diemysql error whilerow mysql fetch arraysel preview rowpreview text rowtext title rowtitle images rowimages ins mysql queryinsert into room id preview text title images values preview text title images or diemysql error headerlocationadminphp the code of the form can be found belowform classforminline namebulkcopy methodpost actionbulkcopyphpfromsights bbulk copyb select nameroom classformcontrol optionselectoption option valueorhanorhanoption option valuedenizdenizoption option valueiriniirinioption option valuekatinakatinaoption option valuegulbingulbinoption option valuemihalismihalisoption select input classbtn btnprimary typesubmit namesubmit valuegobr br divtable classtable tablebordered tablestriped thentry nameth ththisplay orderth thcopy toth thstatusth thimageth theditth thdeleteth thduplicateth php whilerow mysql fetch arraysel tr td input typecheckbox nameid valuephp echo rowid form php echo rowtitle td td form nameorder methodpost actionsightorderphpidphp echo htmlspecialcharsrowid div classcolmd4 input classformcontrol typenumber nameorder valuephp echo htmlspecialcharsrowordernum div div classcolsm3 input typesubmit namesubmit valueset order classbtn btnprimary div form td td form namecopyto methodpost actioncopytophpfromsightsidphp echo htmlspecialcharsrowid input typecheckbox nameroom valueorhan o input typecheckbox nameroom valuedeniz d input typecheckbox nameroom valueirini i input typecheckbox nameroom valuekatina k input typecheckbox nameroom valuegulbin g input typecheckbox nameroom valuemihalis m input typesubmit namesubmit valuecopy classbtn btnprimary form td td a hrefsightstatusphpidphp echo htmlspecialcharsrowid statusphp echo rowstatus php ifrowstatus 1 i classfa facheck falgiphp else i classfa fatimes falgiphp a td td a hrefsightimagesphpidphp echo rowid i classfa faimage falgia td td a hrefeditsightphpidphp echo htmlspecialcharsrowid i classfa faedit falgia td td a onclickreturn confirmdelete hrefdelsightphpidphp echo htmlspecialcharsrowid i classfa fatrash falgia td td a hrefduplicatesightphpidphp echo htmlspecialcharsrowid i classfa facopy falgia td tr php tableany help would be greatly appreciated thanks,"['php', 'html']" +1129301,reading xls file via phpexcel throws fatal error allowed memory size even with chunk reader im using phpexcel to read xls files i quite a short time i meet fatal error allowed memory size of 1073741824 bytes exhausted tried to allocate 730624 bytes in excelphpexcelsharedolereadphp on line 93after some googling i tried chunkreader to prevent this mentioned even on phpexcel homesite but im still stucked with this errormy thought is that via chunk reader i will read file part by part and my memory wont overflow but there must be some serious memoryleak or im freeing some memory bad i even tried to raise server ram to 1gb file size which i trying to read is about 700k which is not so much im also reading 20mb pdf xlsx docx doc etc files without issue so i assume there can be just some minor troll i overlookedcode looks like thisfunction parsexlsfilename require once dirname file sphider designincludeexcelphpexceliofactoryphp require once dirname file sphider designincludeexcelphpexcelchunkreadfilterphp inputfiletype excel5 create a new reader of the type defined in inputfiletype objreader phpexcel iofactorycreatereaderinputfiletype define how many rows we want to read for each chunk chunksize 20 create a new instance of our read filter chunkfilter new chunkreadfilter tell the reader that we want to use the read filter that weve instantiated objreadersetreadfilterchunkfilter loop to read our worksheet in chunk size blocks startrow is set to 2 initially because we always read the headings in row 1 for startrow 2 startrow 65536 startrow chunksize tell the read filter the limits on which rows we want to read this iteration chunkfiltersetrowsstartrowchunksize load only the rows that match our filter from inputfilename to a phpexcel object objphpexcel objreaderloadfilename do some processing here free up some of the memory objphpexcelthisconnectworksheets unsetobjphpexcel and here is code for chunkreaderclass chunkreadfilter implements phpexcel reader ireadfilter private startrow 0 private endrow 0 set the list of rows that we want to read public function setrowsstartrow chunksize this startrow startrow this endrow startrow chunksize public function readcellcolumn row worksheetname only read the heading row and the rows that are configured in this startrow and this endrow if row 1 row this startrow row this endrow return true return false,['php'] +1129419,why is there a size mismatch between structures and unions i have declared a union allocating 4100 bytes to variable sample union and made the same union declaration as part of a structure which is allocating 4104 bytesunion test size union struct uint8 t type union uint8 t count uint8 t list uint16 t rc uint16 t arr value2048 uint64 t first dword attribute packed sample union placing the above union inside structure is allocating 4104 bytesstruct test size struct union struct uint8 t type union uint8 t count uint8 t list uint16 t rc uint16 t arr value2048 uint64 t first dword attribute packed sample structwell this is not a project requirement but i would like to know why compiler is behaving differently for this two declarationgcc version gcc 492 x86 64platform linux x86 64,"['c++', 'c']" +1129479,searching through json object with ngclass angularjs i have two json objects defined in a controller notificationscontroller one with all the notifications and another one with only the id of the newest notifications last 3 daysformat of object notifications t notifications0114214apr163alert 1id1id user4date14apr16notificationalert 10211207apr163alert 2id2id user1date07apr16notificationalert 20311213apr163alert 3id3id user1date13apr16notificationalert 3format of object newest notifications newest notifications01id newnotif103id newnotif3i am thisplaying all the notifications in a view like thisdiv classpanelbody ngcontrollernotificationsctrltable datatableng classrowborder hover thead tr thbidbnbspth thbid userbnbspth thbdatebnbspth thbnotificationbnbspth tr thead tbody tr ngrepeatdata in t notifications ngclaselected dataid to complete td dataid td td dataid user td td datadate td td datanotification td tr tbodytabledivi would like to know how it is possible to select in my table only the newest notifications searching through the json object newest notifications with ngclass ps selected is already defined with a blue background color,"['javascript', 'html']" +1129513,why is stdarraysize constexpr with simple types int double but not stdvector gcc the following codestdarrayint 4 arr1stdarrayfloat arr1size arr2compiles with both gcc and clang because stdarraysize is considered constexprbut the following does not compile with gcc version 530 20151204stdarraystdvectorint 4 arr1stdarraystdvectordouble arr1size arr2for me there is no reason such code should fail to compile if the first one works but since i did not find a lot of post on this i do not know if it is a gcc bug or a clang extensionthe error from gcc that i do not really understand maincpp in function int mainmaincpp646 error call to nonconstexpr function constexpr stdarray tp nmsize type stdarray tp nmsize const with tp stdvectorint long unsigned int nm 4ul stdarray tp nmsize type long unsigned int stdarraystdvectordouble arr1size arr2 in file included from maincpp10usrlocalincludec530array1707 note constexpr stdarray tp nmsize type stdarray tp nmsize const with tp stdvectorint long unsigned int nm 4ul stdarray tp nmsize type long unsigned int is not usable as a constexpr function because size const noexcept return nm usrlocalincludec530array1707 error enclosing class of constexpr nonstatic member function constexpr stdarray tp nmsize type stdarray tp nmsize const with tp stdvectorint long unsigned int nm 4ul stdarray tp nmsize type long unsigned int is not a literal typeusrlocalincludec530array8912 note stdarraystdvectorint 4ul is not literal because struct array usrlocalincludec530array8912 note stdarraystdvectorint 4ul has a nontrivial destructormaincpp646 error call to nonconstexpr function constexpr stdarray tp nmsize type stdarray tp nmsize const with tp stdvectorint long unsigned int nm 4ul stdarray tp nmsize type long unsigned int stdarraystdvectordouble arr1size arr2 maincpp648 note in template argument for type long unsigned int stdarraystdvectordouble arr1size arr2,['c++'] +1129517,let vs var performance in nodejs and chrome when i test following code in chrome and nodejs i get followingchrome for loop with var 24058ms for loop with let 8402msnodejsfor loop with var 4329ms for loop with let 8727msas per my understanding because of block scoping let is faster in chrome but can someone help me understand why is it opposite in nodejs or am i missing somethinguse strictconsoletimefor loop with varfor var i 0 i 10 i 1 do nothingconsoletimeendfor loop with varconsoletimefor loop with letfor let i 0 i 10 i 1 do nothingconsoletimeendfor loop with let ps not sure if this is not the ideal way to test performance,['javascript'] +1129653,g optimization breaks for loops a few days ago i encountered what i believe to be a bug in g 53 concerning the nesting of for loops at higher ox optimization levels been experiencing it specifically for o2 and o3 the issue is that if you have two nested for loops that have some internal sum to keep track of total iterations once this sum exceeds its maximum value it prevents the outer loop from terminating the smallest code set that i have been able to replicate this with is int main int sum 0 value of 100 million 2047483648 less than int32 max int maxinner 10 int maxouter 30 100million 30 3 billion larger than int32 max forint i 0 i maxouter i forint j 0 j maxinner j sum stdcouti i sum sumstdendl when this is compiled using g o runme maincpp it runs just as expected outputting i 0 sum 10i 1 sum 20i 2 sum 30i 3 sum 40i 4 sum 50i 5 sum 60i 6 sum 70i 7 sum 80i 8 sum 90i 9 sum 10i 10 sum 110i 11 sum 120i 12 sum 130i 13 sum 140i 14 sum 150i 15 sum 160i 16 sum 170i 17 sum 180i 18 sum 190i 19 sum 20i 20 sum 210i 21 sum 2094967296i 22 sum 1994967296i 23 sum 1894967296i 24 sum 1794967296i 25 sum 1694967296i 26 sum 1594967296i 27 sum 1494967296i 28 sum 1394967296i 29 sum 1294967296however when this is compiled using g o2 o runme maincpp the outer loop fails to terminate this only occurs when maxinner maxouter 231 while sum continually overflows it should not in any way affect the other variables i have also tested this on ideonecom with the test case demonstrated here my question is thus twofold how is it possible for the value of sum to in some way effect the system no decisions are based upon its value it is merely utilized for the purposes of a counter and the stdcout statementwhat could possibly be causing the dramatically different outcomes at different optimization levelsthank you greatly in advance for taking the time to read and consider my questionnote this question differs from existing questions such as why does integer overflow on x86 with gcc cause an infinite loop because the issue with that problem was an overflow for the sentinal variable however both sentinal variables in this question i and j never exceed the value of 100m let alone 231,['c++'] +1129995,can i send an ajax call in react and redux without action creators and reducers i have a few ajax requests that are not directly manipulating my apps state in a reactredux application is it necessary or is there any benefit to thispatch an action for these ajax requests instead of just sending an ajax request directly in the componentto simplify my scenario i essentially have a list of objects on my redux state i am using a form to post a new object to the database upon successful post i am redirecting to the list page where a get request is sent and the list is fetched and the state is updated the ajax call to post a new object is not directly manipulating my statethe team i am working with is going through the full 3 step redux async stepsex fetch requested fetch success fetch fail along with the respective reducers for all the ajax requests and it is a big hassle to add more and the reducers do not seem to make sense,['javascript'] +1130073,java 8 type inference how reduction is done for generic constructors i was reading the java 8 language specification type inference it says thatliststring ls new arraylistwould be first reducedarraylisti liststringand then to i stringand at the end to i stringi am having a hard time understanding how the reduction of the constraint arraylisti liststring to i stringwas derived it would be a great help if anyone can point out the logic using the java 8 language spec heres the link to the reduction thanks holger for the explanation following is my take on the derivation of new arraylist liststring to arraylisti liststringplease correct me if i am wrongfirst to find the temporary method for the constructor we use 1593otherwise the arguments to the constructor are the arguments in the argument list of the class instance creation expression if any in the order they appear in the expressionif the class instance creation expression uses to elide class type arguments a list of methods m1mn is defined for the purpose of overload resolution and type argument inferencethen 1852 is used to derive arraylisti liststringbecause of being a poly expression and not having any wild card type parametersotherwise the constraint formula a1r i a tao is reduced and incorporated with b2,['java'] +1130138,django rest framework nested fields with multiple models this is django and django rest framework i have 2 models user and phone the 1st problemi want to be able to update user dataemail alongside phone dataphone numbers in 1 single api update response phone number can be 0 or many well like partialtrue actually if a user just want to update phone numbers do not update email and vice versaadditional info at the time of registering phone is not included just basic user info last name first name email password the phone can only get updated in the user profile form after registration is done the user profile form is actually linking to multiple models which is user and phonethe 2nd problem how to serialize multiple phone numbers and save to dbclass userabstractbaseuser email modelsemailfielduniquetrue default username field emailclass phonemodelsmodel phone number modelscharfieldmax length10 owner modelsforeignkeyuserclass userserializerserializersmodelserializer phone number phoneserializerrequiredfalse manytrue class meta model user fields email phone numberclass phoneserializerserializersmodelserializer class meta model phone fields phone numberthe html form would have plus sign at the phone number field to indicate a new phone number can be added example is hereemail phone number 23423432423add morephone number 3423423423add morethe expected jsonemail phone number 32432433223234or if many phone numbers are addedemail phone number 32432433223234phone number 324342322342323or maybe email phone number 32432433223234324342322342323or maybeemail phone id 1 phone number 32432433223234 id 2 phone number 324342322342323is this json possible to dohow can serializer and modelviewset do itsorry i am totally new to drf,['python'] +1130160,how does fork know when to return 0 take the following exampleint mainvoid pid t pid pid fork if pid 0 childprocess else parentproceso correct me if i am wrong once fork executes a child process is created now going by this answer fork returns twice that is once for the parent process and once for the child process which means that two separate processes come into existence during the fork call and not after it ending now i do not get it how it understands how to return 0 for the child process and the correct pid for the parent process this where it gets really confusing this answer states that fork works by copying the context information of the process and manually setting the return value to 0 first am i right in saying that the return to any function is placed in a single register since in a single processor environment a process can call only one subroutine that returns only one value correct me if i am wrong here let us say i call a function foo inside a routine and that function returns a value that value will be stored in a register say bar each time a function wants to return a value it will use a particular processor register so if i am able to manually change the return value in the process block i am able to change the value returned to the function rightso am i correct in thinking that is how fork works,['c'] +1130237,errorexecution failed for task appbuildinfo debug loader i updated few days ago to android studio 20 and everything worked fine but today when i tried to compile the project i received the following error in the logcaterrorexecution failed for task appbuildinfodebugloaderexception while doing past iteration backup source appbuildintermediatesbuildsdebug1848027347678classesdex and destination appbuildintermediatesbuildsdebug1848027347678classesdex must be differentthe error tells me that the same dexmust be different so i am quite confused how could i solve it,['android'] +1130560,how to update object in react state i have an indexed list of users in the js object not array it is part of the react state 1 id 1 name john 2 id 2 name jim 3 id 3 name james whats the best practice toadd a new user id 4 name jane with id 4 as keyremove a user with id 2change the name of user 2 to peterwithout any immutable helpers i am using coffeescript and underscore so extend is okthanks,['javascript'] +1130901,android ble oncharacteristicread and oncharacteristicchanged never called i am trying to connect to a bluetooth le thermometer connecting to the device is working good the only part hanging me up is the gattcallback and it is oncharacteristicchanged read the setnotification and descriptor setvalue and writedescriptor all return true the oncharacteristicchanged is never called to return a valuei used a pretty handy little program from the play store called ble scanner to help me to give me more information about the device and it is services and characteristicsthis is why i simply hard coded service 2 characteristic 0 i just cannot seem to figure out why after i writedescriptor i never see anything come back the interesting thing is i can use some of the other characteristics one being temperature interval and i do receive a response although the data is garbled also out of curiosity why are there 2 descriptors on this characteristicthis code is contained in my mainactivity method not sure if that would make a difference here i have looked at and tried several methods posted on here with no luckprivate final bluetoothgattcallback gattcallback new bluetoothgattcallback override public void onconnectionstatechangebluetoothgatt gatt int status int newstate override public void onservicesthiscoveredbluetoothgatt gatt int status mgatt gatt listbluetoothgattservice services mgattgetservices logionservicesthiscovered servicestostring bluetoothgattcharacteristic characteristic servicesget2getcharacteristicsget0 mgattsetcharacteristicnotificationcharacteristic true bluetoothgattdescriptor descriptor characteristicgetdescriptoruuidfromstringclient characteristic config descriptorsetvaluebluetoothgattdescriptorenable indication value mgattwritedescriptordescriptor override public void oncharacteristicreadbluetoothgatt gatt bluetoothgattcharacteristic characteristic int status override public void oncharacteristicchangedbluetoothgatt gatt bluetoothgattcharacteristic characteristic updatei decided to check the the ondescriptorwrite method and log some informationoverride public void ondescriptorwritebluetoothgatt gatt bluetoothgattdescriptor descriptor int status logidescriptorwrite integertostringstatus interesting thing here is that status is returning 13 which is a write operation exceeds the maximum length of the attributei will be looking into this further,['android'] +1130912,why does n1 0 always return false why does the expression n1 0 always return false where n is an integeri want to use bitwise operation to determine whether n is even however it always return false the clion also prompted me that it always returns falsewhats more it works when i use n1 0 to determine whether n is odd,"['c++', 'c']" +1130946,what happened to java binary compatibility i came across an old set of classes dated march 1997 it was during the time when i tried to learn java and it was jdk 102interestingly enough i have both the source files and the class files intact from that time the sources still compiles and executes as expected which was really cool but was not java supposed to retain binary compatibility as well well somewhere along the way the format no longer holds valida java 8 vm will reportexception in thread main javalangclassformaterror invalid start pc 65535 in localvariabletable in class file balicoreapplication at javalangclassloaderdefineclass1native method at javalangclassloaderdefineclassclassloaderjava760 at javasecuritysecureclassloaderdefineclasecureclassloaderjava142 at javaneturlclassloaderdefineclassurlclassloaderjava455 at javaneturlclassloaderaccess100urlclassloaderjava73 snip many classloader calls at javalangclassloaderloadclassclassloaderjava357 at sunlauncherlauncherhelpercheckandloadmainlauncherhelperjava495the offending class is the superclass of the class that i call from command lineone more detail in those days microsoft was still in the java camp and i remember that their javac was more compliant against badly written syntax the sun compiler would gladly accept public synchronized class abc and many other invalid statements so there is a big chance that these class files were generated by the ms compiler and was then run on sun jvmanyway my question is is there anyone around who has knowledge about the compatibility commitment in the early versions of java was it a big deal or was it sacrificed on purpose or was there a decision much later say java 14 or java 5 to simply drop jdk 10 support,['java'] +1131320,webstorm what does element is not exported warning mean if i write such code in webstorm export class someone constructorparam thistest param usetest return thistest consolelognew someone123usetestand mouseover on thistest i see the warning element is not exportedwhat does it meanif i change the test to test1 the warning thisappears,['javascript'] +1131364,making a sphere rotate in webgl not sure what i am missing here trying to make a planet ie sphere rotate by having the user click on a rotate button but cannot seem to figure it out i do have the following segment which rotates the sphere by way of user interaction with the mouse documentonmousemove function if mousedown return var newx eventclientx var newy eventclienty var deltax newx lastmousex var newrotationmatrix mat4create mat4identitynewrotationmatrix mat4rotatenewrotationmatrix degtoraddeltax 10 0 1 0 var deltay newy lastmousey mat4rotatenewrotationmatrix degtoraddeltay 10 1 0 0 mat4multiplynewrotationmatrix planetrotationmatrix planetrotationmatrix lastmousex newx lastmousey newythis one works fine but i also want to make the planet rotate automatically after the user clicks the button here is my onload function windowonload function onload canvas documentgetelementbyidglcanvas initglcanvas initshaders initbuffers inittexture initevthandlers glclearcolor00 00 00 10 glenablegldepth test var newrotationmatrix mat4create mat4identitynewrotationmatrix documentgetelementbyidrotateonclick function rotation code goes here render my question is how can i toggle the rotation after the user clicks the button so far what i have tried is modify the onmousemove function in an attempt to make the sphere rotate without user interaction but that is not working as an update here is a new dorotate function i addedvar myrotationmatrix mat4createmat4identitymyrotationmatrixdorotate function var dx 1 var newmatrix mat4create mat4identitynewmatrix mat4rotatenewmatrix degtoraddx 10 0 1 0 mat4multiplynewmatrix myrotationmatrix requestanimframedorotatewhich is currently not working for me this function is supposed to be called when the button is clicked toggling the rotation update for a similar demo please see this page what i am trying to do is make the sphere rotate automatically after the user clicks the relevant button this is obviously not in the demo linkedthat is only for clarification purposes update 2i have since figured it out please see my answer below for details,['javascript'] +1131487,what is portable c around the internet i see libraries that claim to be written in portable cas if it was a maybe unofficial standardis there a precise definition of what is portable c and if so what is it i am not asking for common practices for writing portable code but if there really is something we can call portable c,['c++'] +1131770,twisted logic error my twisted program works but now i have a problem with one of my reactors not passing priority to the others i want the controllistener reactor to do one iteration and then pass priority to the printstuffs reactor random class as proof of concept class printstuffsobject print counting printercount 0 def countself selfprintercount selfprintercount 1 print the counter is at strselfprintercount the control listneer class is designed to kill given reactor threads on demand from something once it recieves a signal it is supposed to do one ieteration then release class controllistenerobject counter 20 def countself if selfcounter 0 print killing process reactorstop else print selfcounter selfcounter 1 reactorcalater1 selfcount from twistedinternet import reactor print printing random stuff reactorcallwhenrunningprintstuffscount print intializing kill listner reactorcallwhenrunningcontrollistenercount reactorrun print process killedhere is the output printing random stuff intializing kill listner the counter is at 1 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 killing process process killedi want it to do something like the counter is at 1 20 the counter is at 2 the counter is at 3 19 etc any ideas,['python'] +1132095,how to remove noise from a histogram equalized image i have an image which i am equalizing and then using clahe histogram on like soselfequ cv2equalizehistselfresult arrayclahe cv2createclahecliplimit10 tilegridsize88selfcl1 claheapplyselfequthis is the result i geti want to get rid of all the black dots which is noise ultimately i am trying to extract out the blood vessels which are black in the image shown above in trying to do so the noise makes the extraction inaccurate,['python'] +1132107,detecting whether a flask app handles a url i have a case for having a preliminary frontend flask app before continuing to my main appi have implemented it using a middleware patternclass mymiddlewareobject def init self main app pre app selfmain app main app selfpre app pre app def call self environ start response check whether pre app has a rule for this url with selfpre apprequest contextenviron as ctx if ctxrequesturl rule is none return selfmain appenviron start response return selfpre appenviron start responseis there a more idiomatic way of doing this without creating a context just to check whether the url is handled by the app i want to maintain the flexibility of keeping two apps,['python'] +1132250,curl command line works c curl library does not i am trying to do some request via curl library of c i can successfully do my request and get the correct response via command line but i cannot get the correct response via c code my command line command looks like thiscurl x post h accept applicationjson h contenttype applicationjson h authorization some hash value k my full url data my json stringthat works fine now i try to do the same request in c code my code looks like thisvoid performrequestconst stdstring json const void userdata callbackfunction callback struct curl slist headers null headers curl slist appendheaders accept applicationjson headers curl slist appendheaders contenttype applicationjson headers curl slist appendheaders stdstringauthorization m authorizationc str curl curlhandle curl easy init if curlhandle stdcerr curl handler initialization failed curl easy setoptcurlhandle curlopt nosignal 1 curl easy setoptcurlhandle curlopt httpheader headers specify target url and note that this url should include a file name not only a directory curl easy setoptcurlhandle curlopt url m urlc str enable uploading curl easy setoptcurlhandle curlopt upload 1l set http method to post curl easy setoptcurlhandle curlopt customrequest post set json data i use exactly the same string as in command line curl easy setoptcurlhandle curlopt copypostfields jsonc str set data size curl easy setoptcurlhandle curlopt postfieldsize large jsonsize set user data for getting it in response curl easy setoptcurlhandle curlopt writedata userdata pointer to a custom struct set callback function for getting response curl easy setoptcurlhandle curlopt writefunction callback some callback send request curl easy performcurlhandle curl easy cleanupcurlhandle curl slist free allheadershowever for some reason i get an error in the response from the server from which i can assume that my codes request is not equivalent to command lines command it seems that body is not sent i cannot see my request json body when i use curlopt debugfunction for dumping debug infowhat is the problem here what am i doing wrong any ideas,"['c++', 'c']" +1132290,lambda casting rules i was curious why a lambda with a return type can not be casted to a runnable whereas a non void method reference canrunnable r1 1 not allowed error incompatible types bad return type in lambda expression int cannot be converted to voidrunnable r2 supplier 1get allowed,['java'] +1132459,what does it mean that java arrays are homogeneous but arraylists are not if we have a type we can only store type or its subtypes in it the same goes for arraylist so why is it said that one is homogeneous while the other is not,['java'] +1132617,noexcept promise on derived class constructor can that be used without promising noexcept on base constructor let us say i have a classclass c public b public c noexceptdoes the noexcept specifier require the same promise by the base class that is when i am considering using noexcept do i just look at the behavior of cc or do i also need to consider whether bb may throw exceptionsfor example if bb throws an exception does that propagate to cc or to the code that was asking for a new class instance if propagating to cc that would be one reason to avoid noexcept for the constructor if a base class is not noexcept for the constructor,['c++'] +1132775,how to get session time out message using spring security i want to get the session time out message when the session expiresbelow is my springsecurityxmlhttp autoconfigtrue useexpressionstrue logout logoutsuccessurl invalidatesessiontrue logouturllogout formlogin loginpagelogin usernameparametername passwordparameterpwd sessionmanagement invalidsessionurltimeouttrue concurrencycontrol maxsessions1 expiredurltimeouttimeouttrue sessionmanagementhttpaccording to my knowledge using above code when the session expired it should redirect to timeouttrue or timeouttimeouttrue and on logout it should go to but in my case on logout also its redirecting to invalidsessionurl so i am always getting timeout true for both normal logout and session timeoutplease help me to differentiate thisupdatelogout request contains session requestgetsessionsessioninvalidatesession null,['java'] +1132973,c sort float array while keeping track of indices i have an array of 3 floating point valuesfloat norms3norms0 04norms1 32norms2 17i want to sort this array in descending order while keeping track of the original indexes of the values in the arrayin other words given the array norms 04 32 17 with corresponding indices 0 1 2 i basically want to obtain an array of corresponding ints that reflects the original positions of the float values in norms following a descending sort in this case it would be 1 2 0what is the bestcleanest way to achieve this,['c'] +1132987,how can i populate c classes from an xml document that has some embedded data i have an api that has returned thisxml version10 encodingutf8worddefinition xmlnsxsi xmlnsxsd xmlns wordabandonword definitions definition wordabandonword dictionary idwnid namewordnet r 20name dictionary worddefinitionabandon and 1 the trait of lacking restraint or control freedom from inhibition or worry she danced with abandon syn wantonness unconstraint 2 a feeling of extreme emotional intensity the wildness of his anger syn wildness v 1 forsake leave behind we abandoned the old car in the empty parking lot 2 stop maintaining or insisting on of ideas claims etc he abandoned the thought of asking for her hand in marriage both sides have to give up some calims in these negociations syn give up 3 give up with the intent of never claiming again abandon your life to god she gave up her children to her exhusband when she moved to tahiti we gave the drowning victim up for dead syn give up 4 leave behind empty move out of you must vacate your office by tonight syn vacate empty 5 leave someone who needs or counts on you leave in the lurch the mother deserted her children syn forsake desolate desertworddefinition definition definitionsworddefinitionhere is the code that i used to retrieve the xml data webrequest request webrequestcreate requestmethod post string postdata dictidwnwordabandon byte bytearray encodingutf8getbytespostdata requestcontenttype applicationxwformurlencoded requestcontentlength bytearraylength stream datastream requestgetrequeststream datastreamwritebytearray 0 bytearraylength datastreamclose webresponse response requestgetresponse consolewritelinehttpwebresponseresponsestatusdescription datastream responsegetresponsestream streamreader reader new streamreaderdatastream string responsefromserver readerreadtoend consolewritelineresponsefromserver readerclose datastreamclose responseclosei would like to extract the data from the xml into a list where the definition class looks likepublic class def public string text get set public liststring synonym get set public class definition public string type get set single character and or v or a public listdef def get set can someone give me some advice on how i can do this and show what options are available to me to pick the class elements out of xml and put these into classes as i think this question could be helpful to many other people i will open a large bounty so hopefully someone can take the time to come up with a good exampleupdatesorry i made a mistake with synonym i have changed this now hope it makes more sense the synonyms are just a list i also put in bold what i am needing as the two answers so far do not seem to answer the question at all thank you,"['c#', 'asp.net']" +1133081,c using curly braces to prevent narrowing during assignment i am familiar with using curly braces initializer lists to prevent narrowing when initializing a variable but is it good practice to use it when assigning a value to a variable too for egint i1 initialize i to 1double d20 initialize d to 20i 2 assign value 2 to ii d error narrowing from double to intis there a reason not to use curly braces for assignment,['c++'] +1133285,template objects template friend functions and namespaces in the following c example code gcc 6 and clang 38 thisagree on what the correct behaviour isthis contrived example works as in the test function returns op in gcc in clang it calls the undefined function getint int float doubletemplatetypename argsclass obj bool p false templatetypename t typename args2 friend t getconst objargs2 o return op templatetypename t typename argst getconst objargs obool testconst objint float double a return getintaputting the same code in a namespace causes gcc to do the same thing clang doesnamespace ns templatetypename argsclass obj bool p false templatetypename t typename args2 friend t getconst objargs2 o return op templatetypename t typename argst getconst objargs obool testconst nsobjint float double a return nsgetinta and which compiler is correct and is there in general a way to define a friend member template function inline without having to declare it and then define it separately that is things likestruct foo friend bool bar return true declares and defines a free function bar templatetypename t t bar2 return true does not work,['c++'] +1133309,coding style of if statements lately i have been noticing the style of some programmers who write if statements backwards that is in the test they put the constant value first and then the variable that they are testing second so for example they writebar fooif my constant bar then do something to me this makes code somewhat difficult to read since we are really talking about testing the value of the variable bar and not all variables that are equal to my constant i always put the variable first its sort of a unspoken grammar anyhow i see that some programmers always do this in the opposite order further i have only noticed this in the past few years i have been programming in c for over 25 years and i have not seen this until say about the last 4 years or so so my question is is there a reason people are doing this and if so what is it is this a common standard in some languages or projects or is it taught in some universities or is that just a few people trying to be different,['c'] +1134050,black screen on chrome for android html5 video problemthe videos are placed in my site click on one of the pictureswhen i load the page on my desktop or on firefox mobile everything is finewhen the same page is loaded on chrome for android the video is black without controls the videos do not have audio so i do not know if it playsexpected resultsthe videos should be playable hml5 video tag does not start automatically on mobile but that is not a problemanalysisthe contenttype of the videos are correct and inspecting the console on the device do not provide errorsi gave webm and mp4 version of the videos ripped from the code for the video is thisvideo autoplay muted loop classimgresponsive imgcentered source srcimgportfoliocampominatovideowebm typevideowebm classimgresponsive imgcentered source srcimgportfoliocampominatovideomp4 typevideomp4 classimgresponsive imgcentered img srcimgportfoliocampominatoscreenpng classimgresponsive imgcenteredvideojsfiddle of the problem in action,['android'] +1134187,laravel 52x thisable specific middleware is it possible to thisable a specific middleware without thisabling all middlewarei will use it when running tests so i do not want to define middleware groups and then assign them to my routesthiswithoutmiddleware this will prevent all middleware thiswithoutmiddlewareweb what i want is something like this,['php'] +1134497,what is the best way to approximate classgetsimplename without loading class given a fully qualified class name that can be loaded with classforname is there a way to transform the name into what would be the result of loading the class and invoking getsimplename without actually attempting to load the classi need this capability for reflection purposes,['java'] +1134527,why chrome still keep silent when using functions inside blocks in strict mode i am pretty new to js strict mode when i use code likefunction outeruse strict var ctype function inner ifctypeundefined function hello1 consoleloghello1 hello1 else function hello2 consoleloghello2 hello2 return innervar inner outerinneri wonder why chromever 49 give no error but nodejs can give syntaxerror in strict mode code functions can only be declared at top level or immediately within another function this table points out that my chrome should report error,['javascript'] +1134913,libclang how to get token semantics libclang defines only 5 types of tokenscxtoken punctuationcxtoken keywordcxtoken identifiercxtoken literalcxtoken commentis it possible to get a more detailed information about tokens for example for the following source codestruct typevoid footype parami would expect the output to be likestruct keywordtype type name punctuationvoid typekeyword foo function name punctuationtype type of the function parameterparam function parameter name punctuation punctuationi also need to map those entities to file locations,['c++'] +1135329,how to validate phone number in laravel 52 i want to validate user input phone number where number should be exactly 11 and started with 01 and value field should be number only how do i do it using laravel validationhere is my controller public function saveuserrequest request thisvalidaterequest name requiredmax120 email requiredemailuniqueusers phone requiredmin11numeric course idrequired user new user username requestinputname useremail requestinputemail userphone requestinputphone userdate dateymd usercompleted status 0 usercourse idrequestinputcourse id usersave return redirectsuccess,['php'] +1135557,how do i combine these two linq queries into a single query how can i get this in to one query what i want is the person from the company that matches the name of the person i am searching forcurrently i get the company and then run basically the same searchvar existingcompany bidinfocompanies firstordefault c ccompanydomain null ccompanydomainpeoplefirstordefault p pname bidinfoarchitectpersonname nullperson existingpersonnullif existingcompany null existingperson existingcompanycompanydomainpeoplefirstordefaultp pname bidinfoarchitectpersonname,['c#'] +1135665,php getting out of memory i am trying to insert data from postgres database into mysql database there are about 10 records that i need to import however iam always getting out of memory issue out of memory allocated 1705508864 tried to allocate 2764 bytesi am using laravel 5 to do this here is code to avoid memory limit or time out issueini setmemory limit 1ini setmax input time 1ini setmax execution time 0set time limit0 this speeds up things a bitdbthisablequerylogimportablemodels array of table namesfailedchunks 0foreach importablemodels as postgresmodel mysqlmodel total postgresmodelcount chunksize getchunksizetotal customize chunk size in case of certain tables to avoid too many place holders error if postgresmodel applicationformspostgres chunksize 300 class appmodels mysqlmodel object new class trucate prev data eloquentunguard dbstatementset foreign key checks0 objecttruncate dbstatementset foreign key checks1 eloquentreguard postgresmodelchunkchunksize function chunk use postgresmodel mysqlmodel failedchunks object make any adjustments fixedchunk chunkmapfunction item key use postgresmodel appendableattributes postgresmodelappend fields attributes itemgetattributes replace nullno values with empty string foreach attributes as key attribute if attribute null attributeskey add customized attributes and values foreach appendableattributes as appendfield if appendfield ssn value attributesnumber attributesappendfield substrvalue 0 4 else attributesappendfield return attributes insert chunk of data in db now if objectinsertfixedchunktoarray failedchunks memory issue comes when about 80 rows are inserted not before thati suspect something is wrong with collection map function or loops inside the map function i have even tried setting memory setting and time limit settings to unlimited but to no avail may be i need to use reference variables or something but i am not sure howcan any optimizations be made in above code to reduce memory usage or how do i efficiently import large data from large postgresql database to mysql through code can anyone tell what i am doing wrong here or why whole memory gets consumed up ps i am doing this on local development machine which has 4gb ram windows 8 php version 5616,"['php', 'mysql']" +1135675,how to implement dry principle in c for looping over matrices when dealing with twodimensional arrays eg matrices you need to visit elements quite often the straight forward way to do this is by two nested loopsfor int i0 i n i for int j0 j m j do something with dataij this code principle then is often copied over and over again throughout the code how do you solve this to become dry i think the only way to solve this is to use a visitor function with function pointers rightedit to be more constructive lets assume you have matrix type typedef double matrixfor c this might be solved this way loop over matrix elements applying variable function,['c'] +1135768,how to store a const char to a char i have this code that works as expecteddefine max param name len 32const char getname return test textint main char namemax param name len strcpyname getname cout result name endlif i would like to store the result to a char because some functions within a frameworks i am using use only char as input without using the strcpy for practicality and readability of code and learning too how could i do keeping in const this works wellconst char namename getnamebut i still have const trying to just use charchar namename getnamei get invalid conversion from const char to char whats the best habit for this kind of conversion,['c++'] +1135967,percentrelativelayout inside scrollview i have created a layout using a scrollview which has a percentrelativelayout as its child it does not work on lollipop and older devices but works fine on marshmallow devices please check the code belowscrollview androidididscrollview androidlayout widthmatch parent androidlayout heightmatch parent androidfillviewporttrue androidsupportpercentpercentrelativelayout androidididscrollcontent androidlayout widthwrap content androidlayout heightwrap content applayout heightpercent100 applayout widthpercent50 textview androidididtextview1 androidlayout widthmatch parent androidlayout heightmatch parent androidbackgroundandroidcolorholo red dark androidtextkkjknadko androidtextcolorandroidcolorblack applayout heightpercent10 applayout widthpercent50 textview androidididtextview2 androidlayout widthwrap content androidlayout heightwrap content androidlayout belowidtextview1 androidtextabcaad androidtextcolorandroidcolorblack applayout heightpercent10 applayout margintoppercent10 applayout widthpercent50 textview androidididtextview3 androidlayout widthwrap content androidlayout heightwrap content androidlayout belowidtextview2 androidbackgroundandroidcolorholo red dark androidtextabcd androidtextcolorandroidcolorblack applayout heightpercent10 applayout margintoppercent10 applayout widthpercent50 textview androidididtextview4 androidlayout widthwrap content androidlayout heightwrap content androidlayout belowidtextview3 androidtextabcd androidtextcolorandroidcolorblack applayout heightpercent10 applayout margintoppercent10 applayout widthpercent50 textview androidididtextview5 androidlayout widthwrap content androidlayout heightwrap content androidlayout belowidtextview4 androidbackgroundandroidcolorholo red dark androidtextabcd androidtextcolorandroidcolorblack applayout heightpercent10 applayout margintoppercent10 applayout widthpercent50 textview androidididtextview6 androidlayout widthwrap content androidlayout heightwrap content androidlayout belowidtextview5 androidtextabcd androidtextcolorandroidcolorblack applayout heightpercent10 applayout margintoppercent10 applayout widthpercent50 textview androidididtextview7 androidlayout widthwrap content androidlayout heightwrap content androidlayout belowidtextview6 androidtextabcd androidtextcolorandroidcolorblack applayout heightpercent10 applayout margintoppercent10 applayout widthpercent50 textview androidididtextview8 androidlayout widthwrap content androidlayout heightwrap content androidlayout belowidtextview7 androidtextabcd androidtextcolorandroidcolorblack applayout heightpercent10 applayout margintoppercent10 applayout widthpercent50 androidsupportpercentpercentrelativelayoutscrollviewand also i androidfillviewporttrue it does not show anything in lollipop and older android versionsunfortunately the percent layout would not work with scrollview before m the reason for that is that they depend on the size hint being delivered in the measuring step before m most layouts would provide size hint 0 when sending unspecified measure specyou can try to fix that by creating your own subclass of scrollview and overriding measurechild and measurechildwithmargins fortunately both are protected to provide the size hintsource plusgooglecom can someone help me with creating custom scrollview to make it work,['android'] +1136030,google maps not showing route i am trying to show a route between two markers but the map is always just showing the default location of ireland and is not showing the routepublic string drawmapdirectionsstring startstring endstring waypoints string map script typetextjavascript srcsensorfalsescript script var rendereroptions draggable true var directionsthisplay new googlemapsdirectionsrendererrendereroptions var directionsservice new googlemapsdirectionsservice var map function initialize var ireland new googlemapslatlng530852 7558594 default ireland var mapoptions zoom 7 maptypeid googlemapsmaptypeidroadmap center ireland map new googlemapsmapdocumentgetelementbyidmap canvas mapoptions directionsthisplaysetmapmap directionsthisplaysetpaneldocumentgetelementbyiddirectionspanel googlemapseventaddlistenerdirectionsthisplay directions changed function computetotalthistancedirectionsthisplaydirections call calcroute calcroute function calcroute var start startreplace var end endreplace var waypts foreach string s in waypoints map wayptspush location sreplace map var request origin start destination end waypoints waypts optimizewaypoints documentgetelementbyidchkoptimizewaypointschecked durationintrafficdocumentgetelementbyidchkdurationintrafficchecked provideroutealternatives documentgetelementbyidchkprovideroutealternativeschecked avoidhighways documentgetelementbyidchkavoidhighwayschecked avoidtolls documentgetelementbyidchkavoidtollschecked travelmode googlemapsdirectionstravelmodedriving directionsservicerouterequest functionresponse status if status googlemapsdirectionsstatusok directionsthisplaysetdirectionsresponse var route responseroutes0 function computetotalthistanceresult var total 0 var myroute resultroutes0 for i 0 i myroutelegslength i total myroutelegsithistancevalue total total 10 documentgetelementbyidtotalinnerhtml total km script return mapthe start and end points get passed through this functiongooglemap gm new googlemaphtml gmdrawmapdirectionsstart end waypointstoarrayso for example the start could be something like treloggan ind est newquay tr7 2sx cornwall united kingdomi am not getting any errors so i do not know why it does not thisplay the route ok heres the what map returnsscript typetextjavascript srcsensorfalsescriptscriptvar rendereroptions draggable true var directionsthisplay new googlemapsdirectionsrendererrendereroptions var directionsservice new googlemapsdirectionsservice var map function initialize var ireland new googlemapslatlng530852 7558594 var mapoptions zoom 7 maptypeid googlemapsmaptypeidroadmap center ireland map new googlemapsmapdocumentgetelementbyidmap canvas mapoptions directionsthisplaysetmapmap directionsthisplaysetpaneldocumentgetelementbyiddirectionspanel googlemapseventaddlistenerdirectionsthisplay directions changed function computetotalthistancedirectionsthisplaydirections calcroute function calcroute var start unit 2 hendy industrial estate hendy swansea sa4 0xp west glamorgan united kingdom var end treloggan ind est newquay tr7 2sx cornwall united kingdom var waypts var request origin start destination end waypoints waypts optimizewaypoints documentgetelementbyidchkoptimizewaypointschecked durationintrafficdocumentgetelementbyidchkdurationintrafficchecked provideroutealternatives documentgetelementbyidchkprovideroutealternativeschecked avoidhighways documentgetelementbyidchkavoidhighwayscheckedavoidtolls documentgetelementbyidchkavoidtollschecked travelmode googlemapsdirectionstravelmodedriving directionsservicerouterequest functionresponse status if status googlemapsdirectionsstatusok directionsthisplaysetdirectionsresponsevar route responseroutes0 function computetotalthistanceresult var total 0 var myroute resultroutes0 for i 0 i myroutelegslength i total myroutelegsithistancevalue total total 10 documentgetelementbyidtotalinnerhtml total km script,"['javascript', 'asp.net']" +1136066,why cannot i pass constant arrays as arguments in c why cannot i do thisarrayfn10 20 30if arrayfn is some function that takes in one parameter of type double or double whichever trying this gives me a syntax erroris there a way that i could achieve something in c like this generating and immediately passing an array known at compile time that avoids having to spend a line of code predeclaring and filling it,['c'] +1136447,python recursive search of dict with nested keys i recently had to solve a problem in a real data system with a nested dictlist combination i worked on this for quite a while and came up with a solution but i am very unsatisfied i had to resort to using globals and a named temporary global parameter i do not like to use globals that is just asking for an injection vulnerability i feel that there must be a better way to perform this task without resorting to globalsproblem datasetd k1 stuffs1 lm k2 stuffs2 lnone k3 stuffs3 lm k4 stuffs4 lnone k5 stuffs5 lm k6 stuffs6 lnone desired outputk 1 stuff s1 k 2 stuff s2 k 3 stuff s3 k 4 stuff s4 k 5 stuff s5 k 6 stuff s6my solutiondef get recursive resultsd iter key get keys if not h in globals global h h happendkdgetk for k in get keys d2 dcopy for k in iter key if not d2 continue d2 d2getk for td in d2 d3 tdcopy for k in iter key if not d3 continue d3 d3getk if d3 return get recursive resultstd iter key get keys happendktdgetk for k in get keys else l k for k in h del globalsh return lcalling my function as follows returns the desired result get recursivelyd lm kstuffhow would i build a better solution,['python'] +1136526,creating an hierarchyobject with an undefined number of childs i am currently working on a code parser parsing valve map format vmf files into a java readable objectin vmf filesthere are 2 types of objects classes and propertiesclasses have a name and can contain other classes and propertiesproperties have a name and an unlimited number of valuestherefore i created a vmfclass object class and a vmfproperty object classi created a list with selfcreated hierarchyobjects containing the vmfclassvmfproperty object an uuid and the parentuuidthe vmfclass object contains 2 lists one with subvmfclasses one with propertiesmy problem is that i have no clue on how to achieve that a class contains all of its subclasses since i cannot tell how much subclasses the subclasses have and so onhere is my code githubhierachyobjectpackage netminecraftsourcecraftreloadedutilsimport javautilarraylistimport javautilhashmapimport javautillistimport javautilmappublic class hierarchyobject private static maplong long useduuids new hashmap private long parentuuid private long uuid private object object param object param parent 1 is maximum level public hierarchyobjectobject object long parent thisobject object thisparentuuid parent while true long random long mathrandom longmax value if useduuidscontainskeyrandom thisuuid random useduuidsputrandom parent break public long getuuid return uuid public long getparentuuid return parentuuid public static long getparentuuidbyuuidlong uuid if useduuidscontainskeyuuid return useduuidsgetuuid return 1 public object getobject return object public static boolean haschildlong uuid ifuseduuidscontainsvalueuuid return true ifuuid 1 return true return false public boolean haschild return haschildthisuuid public static long getchilduuidslong uuid ifhaschilduuid listlong cuuids new arraylist forint i 0 i useduuidssize i for mapentrylong long e useduuidsentryset ifegetvaluelongvalue uuid cuuidsaddegetkey return listutilstoprimitivebylistcuuids return null vmfpropertypackage netminecraftsourcecraftreloadedsourcepublic class vmfproperty private string name private string values public vmfpropertystring name string values thisname name thisvalues values public string getname return name public string getvalues return values override public boolean equalsobject paramobject ifparamobject instanceof vmfproperty return vmfpropertyparamobjectnameequalsthisname vmfpropertyparamobjectvaluesequalsthisvalues return false vmfclasspackage netminecraftsourcecraftreloadedsourceimport javautillistpublic class vmfclass private listvmfclass classes private listvmfproperty properties private string name public vmfclastring name listvmfclass classes listvmfproperty properties thisname name thisclasses classes thisproperties properties public string getname return name public listvmfclass getclasses return classes public listvmfproperty getproperties return properties public void addvmfclass vmfclass classesaddvmfclass public void addvmfproperty vmfproperty propertiesaddvmfproperty public void removevmfclass vmfclass classesremovevmfclass public void removevmfproperty vmfproperty propertiesremovevmfproperty override public boolean equalsobject paramobject ifparamobject instanceof vmfclass return vmfclassparamobjectpropertiesequalsthisproperties vmfclassparamobjectclassesequalsthisclasses vmfclassparamobjectnameequalsthisname return false vmfobject the class executing all the codepackage netminecraftsourcecraftreloadedsourceimport javaiofileimport javautilarraylistimport javautillistimport netminecraftsourcecraftreloadedutilshierarchyobjectpublic class vmfobject private string rawfile private listvmfclass toplevelclasses private static final string invalid chars a aa public vmfobjectlistvmfclass toplevelclasses thistoplevelclasses toplevelclasses public vmfobject thisnew arraylistvmfclass public void writefile file vmfwriterwritefile rawfile public vmfobject readfile file throws vmfparsingexception thisrawfile vmfreaderreadfile parse return this public listvmfclass getclasses return toplevelclasses private void parse throws vmfparsingexception evaluate get private void evaluate throws vmfparsingexception char textchars rawfiletochararray int c new int0 0 0 int line 0 int linepos 0 for int i textchars linepos if textcharsi n line linepos 0 c3 0 if c3 2 0 throw new vmfparsingexceptioninvalid quotes on line line linepos if textcharsi c1 if textcharsi c2 if textcharsi c3 if c1 c2 0 if textcharsi textcharsi 1 while true i if textcharsi n break if textcharsi textcharsi 1 throw new vmfparsingexceptioninvalid character on line line linepos if invalid charsindexoftextcharsi 1 throw new vmfparsingexceptioninvalid character textcharsi on line line linepos if c1 c2 throw new vmfparsingexceptionunbalanced brackets in vmf file public void addvmfclass vmfclass toplevelclassesaddvmfclass private void get throws vmfparsingexception listhierarchyobject content new arraylist long curparent 1 string text rawfilesplitn for int i 0 i textlength i string line textitrim if linestartswith continue else byte quotec 0 char linechar linetochararray boolean readp false liststring reads new arraylist byte creads 0 for int y 0 y linecharlength y if linechary linechary 1 break if linechary quotec if quotec 2 0 readp false creads else readp true if readp readssetcreads readsgetcreads linechary if linechary hierarchyobject object new hierarchyobjectnew vmfclasslinesubstringlinesubstring0 ylastindexof ytrim null null curparent contentaddobject curparent objectgetuuid if linechary curparent hierarchyobjectgetparentuuidbyuuidcurparent contentaddnew hierarchyobjectnew vmfpropertyreadsremove0 readstoarraynew stringreadssize curparent buildobjectcontent private void buildobjectlisthierarchyobject content long curuuid 1 forint i 0 i hierarchyobjectgetchilduuidscuruuidlength i hierarchyobjectgetchilduuidscuruuid todo implement the todo part is where the hierachy object should get converted to the actual object,['java'] +1136671,rendering html from string in 500x500 size div i have have some html contents in angularjs arrayvar htmls htmls is a string array with following html content in itpimg srchttp wpwcomemblems598e97fa05454766902650b4c01d7645jpg stylewidth 25 ppspan stylefontweight boldthis is a sample headingspanppspan stylefontweight bold textdecoration underlinesome content without any imagespanpi want to have thisplay preview image of these html texts after rendering in a div of size 500x500 for each html content from the arrayi do not want any scroll bars in the div for html rendered if the html text is too long then small portion rendering would work for me,['html'] +1136724,how to keep alive my broadcastreceiver currently i am developing a call blocker application like truecallerwhat i neededi want to detect the incoming calls even my app is removed from the recent apps listmanifestxml codereceiver androidnamephonestatereceiver intentfilter action androidnameandroidintentactionphone state intentfilter receivermy broadcast receiver codeoverridepublic void onreceivecontext context intent intent my call blocking codemy problemmy broadcastreceiver wont work in the background as if i removed from the recent apps listmy full manifest code herexml version10 encodingutf8manifest xmlnsandroidpackageranjithcallblockerusespermission androidnameandroidpermissionread phone state usespermission androidnameandroidpermissioncall phone usespermission androidnameandroidpermissionread contacts usespermission androidnameandroidpermissionget tasks application androidallowbackuptrue androidenabledtrue androidiconmipmapic launcher androidlabelstringapp name androidsupportsrtltrue androidthemestyleapptheme receiver androidnamephonestatereceiver androidenabledtrue androidexportedtrue androidprocessanotherprocess intentfilter androidpriority10 action androidnameandroidintentactionphone state intentfilter receiver activity androidnamemainactivity androidlabelstringapp name androidthemestyleappthemenoactionbar intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activityapplicationmanifestshould i use service or anything elseupdatewith suraj answer i tried this tags in my receiver androidenabledtrue androidexportedtrue androidprocessanotherprocessit works on kitkat but not works on lollipopupdated questionincase if not possible to keep alive broadcast receiver how can i detect incoming calls even my app is closed anybody give detailed answer,['android'] +1136792,how to overcome multiple selection issue i have a sample paragraph text in p tag if i select some text in the paragraph i am changing its text color to green from black and wrapping it in span tag adding a class selected for it but i am able to select the text that is already selected i do not want the selected text to be selected againi have given sample code in the link function getselectedtext t documentall documentselectioncreaterangetext documentgetselection return tbodymouseupfunction var selection getselectedtext var selection text selectiontostring var span documentcreateelementspan spantextcontent selection text spanclassname selectedtext var range selectiongetrangeat0 rangedeletecontents rangeinsertnodespanspan color greenscript srcscriptp lorem ipsum is simply dummy text of the printing and typesetting industry lorem ipsum has been the industrys standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book it has survived not only five centuries but also the leap into electronic typesetting remaining essentially unchanged p,"['javascript', 'jquery']" +1136808,why is one of these so much faster than the other i am writing c code to find the first byte in memory that is non 0xff to exploit bitscanforward i had written an inline assembly code that i like very much but for readability as well as future proofing ie simd vectorization i thought i would give g optimizer a chance g did not vectorize but it did get to nearly the same nonsimd solution i did but for some reason it is version runs much slower 260x slower ie i have to loop my version 260x more to get to the same execution time i excepted some difference but not that much can some point out why it might be i just want to know so as to make a mistake in future inline assembly codesthe c starting point is following in terms of counting accuracy there is a bug in this code but i have simplified it for this speed testuint64 t count3 const void data uint64 t const nbytes uint64 t count 0 uint64 t block do block uint64 tdatacount if block uint64 t1 count builtin ctzblock ignore this for speed test goto done count sizeofblock while count nbytes done return countnbytes nbytes countthe assembly code g came up with is z6count3pkvrkmlfb33 cfi startproc mov rdx qword ptr rsi xor eax eax jmp l19 p2align 410 p2align 3l21 add rax 8 cmp rax rdx jnb l18l19 cmp qword ptr rdirax 1 je l21l18 cmp rax rdx cmova rax rdx ret cfi endprocmy inline assembly is z6count2pkvrkmlfb32 cfi startproc push rbx cfi def cfa offset 16 cfi offset 3 16 mov rbx qword ptr rsi count trailing bytes of 0xff xor rax rax ctxff loop 69 mov r9 qword ptr rdirax xor r9 1 jnz ctxff final 69 add rax 8 cmp rax rbx jl ctxff loop 69 ctxff final 69 cmp raxrbx cmova raxrbx pop rbx cfi def cfa offset 8 ret cfi endprocas far as i can see it is substantially identical except for the method by which it compare the data byte against 0xff but i cannot believe this would cause a great difference in computation time it is conceivable my test method is causing the error but all i do is change the function name and iteration length in the following simple forloop shown below when and is 120 and all bytes of a except the last byte is 0xfftest 1 for uint64 t i0 i uint64 t115 i and count3an test 2 for uint64 t i0 i uint64 t133 i and count2an edithere are my real inline assembly codes with sse count1 x6464 count and then plainoldc versions count0 and count3 i fell down this rabbit hole hoping that i could get g to take my count0 and arrive on it is own to my count1 or even count2 but alas it did nothing absolutely no optmization i should add that my platform does not have avx2 which is why i was hoping to get g to automatically vectorize so that the code would automatically update when i update my platformin terms of the explicit register use in the inline assembly if i did not make them explicitly g would reuse the same registers for nbytes and count in terms of speedup between xmm and qword i found the real benefit is simply the loopunroll effect which i replicate in count2 uint32 t count0const uint8 t data uint64 t const nbytes for int i0 inbytes i if datai 0xff return i return nbytesuint32 t count1const void data uint64 t const nbytes uint64 t count asm count trailing bytes of 0xff n xor count count n vpcmpeqb xmm0 xmm0 xmm0 n make array of 0xff ctxff next block n vpcmpeqb xmm1 xmm0 xmmword ptr datacount n vpmovmskb r9 xmm1 n xor r9 0xf n test if all match bonus negate r9 jnz ctxff tzc n if 0 stop tzcnt negated r9 add count 16 n else inc cmp count nbytes n jl ctxff next block n while count nbytes loop jmp ctxff done n else done all bytes were 0xff ctxff tzc n tzcnt r9 r9 n count bytes up to non0xff add count r9 n ctxff done n more than nbytes could be tested cmp countnbytes n find minimum cmova countnbytes count a count nbytes b nbytes data d data r9 xmm0 xmm1 return countuint64 t count2 const void data uint64 t const nbytes uint64 t count asm count trailing bytes of 0xff n xor count count n ctxff loop n mov r9 qword ptr datacount n xor r9 1 n jnz ctxff final n add count 8 n mov r9 qword ptr datacount n loopunroll xor r9 1 n jnz ctxff final n add count 8 n cmp count nbytes n jl ctxff loop n jmp ctxff done n ctxff final n bsf r9 r9 n do tz count on r9 either of first qword bits or xmm bytes shr r9 3 n scale bsf count accordiningly add count r9 n ctxff done n more than nbytes bytes could have been tested cmp countnbytes n find minimum of count and nbytes cmova countnbytes count a count nbytes b nbytes data d data r9 return countinline static uint32 t tzcountuint64 t const qword uint64 t tzc asmtzcnt 0 1 r tzc r qword return tzcuint64 t count3 const void data uint64 t const nbytes uint64 t count 0 uint64 t block do block uint64 tdatacount if block uint64 t1 count tzcountblock goto done count sizeofblock while count nbytes done return countnbytes nbytes countuint32 t and 120int mainint argc char argv unsigned char an builtin memseta0xffn uint64 t and 0 j for uint64 t i0 i uint64 t118 i and count2an printfnn x x xnn n 0 return n,['c++'] +1136863,how do i get the superclasses node in eclipse jdt ui i have a code herepublic class testoverride int foo return 1 class b extends testoverride override int foo error quick fix to add return superfoo as you can see i have mentioned the error i am trying to create a quickfix for this in eclipse jdt ui but i am unable to get the superclass node of the class b that is class testoverridei tried the following codeifselectednode instanceof methoddeclaration astnode type selectednodegetparent iftype instanceof typedeclaration astnode parentclass typedeclaration typegetsuperclasstype in here i got parentclass as testoverride only but when i checked this is not of the type typedeclaration it is not of type simplename either my query is how i get the class testoverride nodeedit for imethodbinding parentmethodbinding superclassbindinggetdeclaredmethods if methodbindingoverridesparentmethodbinding returnstatement rs astnewreturnstatement supermethodinvocation smi astnewsupermethodinvocation rssetexpressionsmi block oldbody methoddeclgetbody listrewrite listrewrite rewritergetlistrewriteoldbody blockstatements property listrewriteinsertfirstrs null,['java'] +1136894,activitymanager exception thrown when launching activities javalangillegalargumentexception vallength 91 when launching mainactivity of application it is crashing instantly when i looked up the adb logs i was able to find only this exception thrown when launching activities in processrecord javalangillegalargumentexception vallength 91 at systempropertiessetwhen i looked up the source code of android i found that this could be the root of the problem android source code of systempropertiesjava it contains a max value limit of 91 public static final int prop value max 91 public static string getstring key if keylength prop name max throw new illegalargumentexceptionkeylength prop name max return native getkey when i give it a guess i found that my applications package name is 108 characters long and when i changed my apps package name to 60 characters it worked without any problemwhat could be the issuethis happens only on asus zenfone 2 lolipop 50 modelthere is not problem in any other devices we are receiving a lot of negative rating due to this problemour app already have 15k downloads in the play store so changing the apps package name is not an option for me please helpupdateto be more precise there is no issue in all the android phones we tested other than asus zenfone seriesas mentioned by viswanathlekshmanan in the comments i changed the location of mainacitivityjava file to a lower pathie the original full packagename was comfourbigbrothersmalayalam troll greetings maker edit movie images font seasonal photo commentsactivitiesmainactivityi changed it to comfourbigbrothersmtmactivitiesmainactivitystill not working i have put some logs in oncreate of the mainactivity but the code execution is not reaching there at all so i have no idea where to put a trycatch block as mentioned in some answerswould there be any solution using the android ndk and sorry if ita a dumb question i am completely lostthis is the relevant part of the manifestmanifest xmlnsandroidpackagecomfourbigbrothersmalayalam troll greetings maker edit movie images font seasonal photo comments usespermission androidnameandroidpermissioninternet usespermission androidnameandroidpermissionread external storage usespermission androidnameandroidpermissionwrite external storage application androidnamecomfourbigbrothersboilerplatebasefbbapplication androidallowbackuptrue androidicondrawableic launcher androidlabelstringapp name androidthemestylethemefbbapp activity androidnamecomfourbigbrothersmalayalam troll greetings maker edit movie images font seasonal photo commentsactivitiesmainactivity androidlabelstringlauncheractivityname androidscreenorientationportrait androidlaunchmodesingletop androidthemestylemainactivitytheme intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter intentfilter action androidnameandroidintentactionsend category androidnameandroidintentcategorydefault data androidmimetypeimage intentfilter activityapplication,"['java', 'android']" +1137192,what makes moving objects faster than copying i have heard scott meyers say stdmove does not move anything but i have not understood what it meansso to specify my question consider the followingclass box things box box1 some valuebox box2 box1 value of box1 is copied to box2 okwhat aboutbox box3 stdmovebox1i do understand the rules of lvalue and rvalue but what i do not understand is what is actually happening in the memory is it just copying the value in some different way sharing an address or what more specifically what makes moving faster than copyingi just feel that understanding this would make everything clear to me thanks in advanceedit please note that i am not asking about the stdmove implementation or any syntactic stuff,['c++'] +1137369,can i force python array elements to have a specific size i am using the arrays modules to store sizable numbers many gigabytes of unsigned 32 bit ints rather than using 4 bytes for each element python is using 8 bytes as indicated by arrayitemsize and verified by pymplereg arrayl range10itemsize8i have a large number of elements so i would benefit from storing them within 4 bytes numpy will let me store the values as unsigned 32 bit ints nparrayrange10 dtype npuint32itemsize4but the problem is that any operation using numpys index operator is about twice as slow so operations that are not vector operations supported by numpy are slowegpython3 m timeit s from array import array a arrayl range10 for i in rangelena ai10 loops best of 3 514 usec per loopvspython3 m timeit s import numpy as np a nparrayrange10 dtype npuint32 for i in rangelena ai10 loops best of 3 904 usec per loopso i am forced to either use twice as much memory as i would like or the program will run twice as slow as i would like is there a way around this can i force python arrays to have use specified itemsize,['python'] +1137375,why does the javac error x cannot be applied to y happen when both parameters and arguments match up innerclass calling outerclass method learning about java iterators and general data structures via means of homeworki have built a doublylinked list linkedlist which uses nodes linkedlistnode and has an iterator linkedlistlinkedlistiterator all classes make use of genericswithin linkedlistiterators overridden remove method i am making use of a method of the outerclass ie the linkedlist classi get the following compiletime errorlinkedlistjava170 deletenodelinkedlisttnodetlinkedlisttnodetlinkedlisttnodet in linkedlistt cannot be applied to linkedlisttnodetlinkedlisttnodetlinkedlisttnodet deletenodenodetoberemoved next prevmy primitive understanding is that the types do not match up however i cannot see how that is sohere is my complete class codeimport javautiliteratorimport javautilnosuchelementexceptionimport javautilconcurrentmodificationexceptionpublic class linkedlistt implements iterablet private nodet sentinel private long modcount apparently no unsigned ints in java public linkedlist modcount 0 sentinel new nodetnull sentinelsetnextsentinel sentinelsetprevsentinel public void appendt t append 1st infront sentl newnode behind nodet newnode new nodett nodet infront sentinel nodet behind sentinelprev now actually insert insertnodenewnode infront behind public void prependt t prepend infront 1st newnode behind sentl nodet newnode new nodett nodet behind sentinel nodet infront sentinelnext now actually insert insertnodenewnode infront behind public void removehead removefirst infront 1st delete behind sentl nodet infront sentinelnextnext nodet behind sentinel nodet todelete sentinelnext now actually delete deletenodetodelete infront behind private void insertnodenodet newnode nodet infront nodet behind newnodesetnextinfront newnodesetprevbehind infrontsetprevnewnode behindsetnextnewnode modcount private void deletenodenodet todelete nodet infront nodet behind infrontsetprevbehind behindsetnextinfront todeletesetnextnull todeletesetprevnull modcount override public iteratort iterator return new linkedlistiteratortsentinel myiterator private inner class public class linkedlistiteratort implements iteratort private nodet cursor private nodet lastreturned private long itermodcountperspective public linkedlistiteratornodet sentinel cursor sentinelnext lastreturned null itermodcountperspective modcount private boolean hasbodhi bodhi in buddhism bodhi is the understanding of the true nature of things return itermodcountperspective modcount override public boolean hasnext if cursor sentinel return false return true override public t next if thishasnext throw new nosuchelementexception else if hasbodhi throw new concurrentmodificationexception else t aux cursordata lastreturned cursor cursor cursornext return aux override public void remove check were allowed to remove if lastreturned null throw new illegalstateexception if hasbodhi throw new concurrentmodificationexception setup vars to perform deletion nodet nodetoberemoved lastreturned nodet next nodetoberemovednext nodet prev nodetoberemovedprev now delete deletenodenodetoberemoved next prev itermodcountperspective now setup vars for exit cursor next lastreturned null illegal to remove yetagain before first calling next node private compositional inner class interface void setnextnode n change the node in front of this node void setprevnode p change the node behind this node node next returns the node in front of this node node prev returns the node behind this node t data returns the data stored inside this node private class nodet private t data private nodet next private nodet prev public nodet d data d next null prev null method setnextnodet n this method takes the parameter node passedin and puts it in front of this node input node n output none eg node4setnextnode5 public void setnextnodet n next n method setprevnodet n this method takes the parameter node passedin and puts it behind of this node input node p output none eg node5setprevnode4 public void setprevnodet p prev p method next this method returns the node in front of this node input none output node infront of this thisnext eg node nodeinfrontofnode4 node4next public nodet next return next method prev this method returns the node behind of this node input none output node behind of this thisprev eg node nodebehindofnode4 node4prev public nodet prev return prev method data this method returns the data inside of this node input none output data inside of this node eg planarshape shape4 node4data public t data return data compsci student first time poster thank you to all so gurus youve helped my peers and i many times,['java'] +1137452,unable to autoload constant controller in production no error in development file name appcontrollersinvoiceinventorydepartmentpharmacy invoices controllerrbfile content class invoiceinventorydepartmentpharmacyinvoicescontroller applicationcontrollerendi get no error in development but in production i get this error f 20160425t130800754597 13500 fatal loaderror unable to autoload constant invoiceinventorydepartmentpharmacyinvoicescontroller expected xyappcontrollersinvoiceinventorydepartmentpharmacy invoices controllerrb to define iti did ssh and checked every file on server its the same as development which is obvious i cannot figure out why its throwing such an error in production,['ruby'] +1137488,getting outofmemoryexception in xamarin javalangoutofmemoryerror consider increasing the value of javamaximumheapsize java ran out of memory while executing javaexei am getting out of memory exception in my visualstudio xamarin project please help me how can i resolve this issue,['c#'] +1137521,hide all text except for the first letter with css is it possible to hide all letters after the first letter with css dtnotfirstletter thisplay none,['css'] +1137555,why does gmtime take a pointer according to the documentation the struct tm gmtimeconst time t timer is supposed to convert the time t pointed to by timer to a broken down timenow is there a reason why they decided to make the function take a pointer to the time t instead of passing the time t directly as far as i can see time t is of arithmetic type and should therefore have been possible to pass directly also i find it reasonable that it would have fit into a long also there seem to be any specific handling of the null pointer which could have motivated passing a pointeris there something i am missing something still relevant today,['c'] +1137613,how to interpret tensorflow output how do i interpret the tensorflow output for building and executing computational graphs on gpgpusgiven the following command that executes an arbitrary tensorflow script using the python apipython3 tensorflow testpy outthe first part stream executor seems like its loading dependenciesi tensorflowstream executordso loadercc105 successfully opened cuda library libcublasso locallyi tensorflowstream executordso loadercc105 successfully opened cuda library libcudnnso locallyi tensorflowstream executordso loadercc105 successfully opened cuda library libcufftso locallyi tensorflowstream executordso loadercc105 successfully opened cuda library libcudaso1 locallyi tensorflowstream executordso loadercc105 successfully opened cuda library libcurandso locallywhat is a numa nodei tensorflowstream executorcudacuda gpu executorcc900 successful numa node read from sysfs had negative value 1 but there must be at least one numa node so returning numa node zeroi assume this is when it finds the available gpui tensorflowcorecommon runtimegpugpu initcc102 found device 0 with properties name tesla k40cmajor 3 minor 5 memoryclockrate ghz 0745pcibusid 010total memory 1125gibfree memory 15gibsome gpu initialization what is dmai tensorflowcorecommon runtimegpugpu initcc126 dma 0 i tensorflowcorecommon runtimegpugpu initcc136 0 y i tensorflowcorecommon runtimegpugpu devicecc755 creating tensorflow device gpu0 device 0 name tesla k40c pci bus id 010why does it throw an error ee tensorflowstream executorcudacuda drivercc932 failed to allocate 15g 11976531968 bytes from device cuda error out of memorygreat answer to what the pool allocator does i tensorflowcorecommon runtimegpupool allocatorcc244 poolallocator after 3160 get requests put count2958 evicted count10 eviction rate0338066 and unsatisfied allocation rate0412025i tensorflowcorecommon runtimegpupool allocatorcc256 raising pool size limit from 100 to 110i tensorflowcorecommon runtimegpupool allocatorcc244 poolallocator after 1743 get requests put count1970 evicted count10 eviction rate0507614 and unsatisfied allocation rate0456684i tensorflowcorecommon runtimegpupool allocatorcc256 raising pool size limit from 256 to 281i tensorflowcorecommon runtimegpupool allocatorcc244 poolallocator after 1986 get requests put count2519 evicted count10 eviction rate0396983 and unsatisfied allocation rate0264854i tensorflowcorecommon runtimegpupool allocatorcc256 raising pool size limit from 655 to 720i tensorflowcorecommon runtimegpupool allocatorcc244 poolallocator after 28728 get requests put count28680 evicted count10 eviction rate00348675 and unsatisfied allocation rate00418407i tensorflowcorecommon runtimegpupool allocatorcc256 raising pool size limit from 1694 to 1863,['python'] +1138035,split the result of counter i count the occurrences of items in a list usingtimescrime counterthistricts which gives me this counter3 1575 2 1462 6 1359 4 1161 5 1159 1 868i want to separate the parts of the list items 3 and 1575 for example and store them in a list of lists how do i do this,['python'] +1138529,how to generate retrofit client library from wp rest api using swagger i am creating android client for my wordpress website is there a way to generate retrofit 2 client library from wp rest client using swagger or is there any other tool to generate the same,['android'] +1138539,return jwt token generated by oauthauthorizatioserver from controller in web api following taiseer joudeh i was able to create simple poc of web api i am able to create new account then login and call secure web api when i add jwt token to headeri would like to modify method that is responsible for creating accountsright now i am returning create 201 code with new user object but instead i would like to return access tokeni have found similar question but it requires creating httpclient and doing request to oauthauthorizatioserver tokenendpointpathsecond question i found requires generating temporary token that is returned to frontend but then frontend must do additional request to server to get real tokenwhat i would like to do is to return login response access token token type and expires in when i create user accounti want user to be authenticated when his account is createdi am using just web api and jwt without any cookiesedit my temporary solutionafter creating user i am doing thisvar validtime new timespan0 0 0 10var identity await usermanagercreateidentityasyncuser jwtvar jwtformat new customjwtformatapplicationconfigurationissuervar authenticationproperties new authenticationproperties issuedutc datetimeoffsetutcnow expiresutc datetimeoffsetutcnowaddvalidtime var authenticationticket new authenticationticketidentity authenticationpropertiesvar token jwtformatprotectauthenticationticketvar response new access token token token type bearer expires in validtimetotalsecondstointreturn okresponsewhere customjwtformat comes from this awesome article,"['c#', 'asp.net']" +1138725,phpdox file not found i was trying to run phpdox on windows server 2012 but i am getting the errorphp version 705 winntphpdox version 0811exception theseerphpdoxgeneratortokenfileexception code 1location phardhtdocsascprobinphpdox0811pharphpdoxgeneratorprojecttokenfilephp line 19file filedhtdocsascprobuildphpdoxtokensappbundleappbundlephpxmlnot foundi have checked the location the file is not missingi am running into this problem during continuous integration process with jenkins it is very strange because the same phpdox version did work for me on ubuntu maybe this is related to the fact that all programs lay on c including jenkins but the jenkins workspace lays on d,['php'] +1138825,what is special about structs i know that in c we cannot return an array from a function but a pointer to an array but i want to know what is the special thing about structs that makes them returnable by functions even though they may contain arrayswhy is the struct wrapping makes the following program validinclude stdiohstruct data char buf256struct data fooconst char bufint mainvoid struct data obj obj foothis is a sentence printfsn objbuf return 0struct data fooconst char buf struct data x strcpyxbuf buf return x,['c'] +1139465,add touch events to vrpanoramaview class of google cardboard sdk for android i am working on a panorama app i am using vrpanoramaview class of google cardboard sdk to view panorama in my app vrpanoramaview class provides gyro navigation to view panorama is it possible to attach touch events along with gyro navigation to the panoramathanks,['android'] +1139478,android studio project structure not thisplaying properly my android studio 132 was working properlybut it restart it self and then i am not able to see android type to select project structure and also i am not able to find sdk mangeravd manager icons,['android'] +1139484,automatically detect identical consecutive stdstringfind calls during a code review i found source code like thisvoid f oddstdstring classname stdstring testname if classnamefind stdstringnpos testname classnamesubstrclassnamefind 2 voidclassnameeraseclassnamefind stdstringnpos within this function stdstringfind is called three times with the same pattern here this code can of course be refactored to void fstdstring classname stdstring testname const size t endofclassnamepos classnamefind if endofclassnamepos stdstringnpos testname classnamesubstrendofclassnamepos 2 voidclassnameeraseendofclassnamepos stdstringnpos where find is called only oncequestiondoes anybody know a strategy to detecting such a pattern like this i am having a huge code base where i intend to spot this patterni plan to use a windows or a linux environment potential strategiesuseadapt a static code analysis tool like cppcheck to detect these kind of odditiessearch within the code base with regular expression useadapt clangtidy for detection of this patternwrite a custom checker in some language eg python that detects these issues in this case the checking should be performed on preprocessed codeno gosmanual reviewupdate 1i decided to start with potential strategy 1 i plan to adapt cppcheck to catch this issue cppcheck offers a possibility to write customized rules based on pcre regular expressions for this cppcheck has to be compiled with enabled pcre support since the current test environment is linuxbased the following commands can be used to download the latest version of cppcheckgit clone cd cppcheckafter that compile and install the tool as followssudo make install have rulesyesnow the basic tool setup is done in order to develop a cppcheckrule i prepared a simple test case file testcpp similar to the sample code in the first section of this article this file contains three functions and the cppcheckrule shall emit a warning on f odd and f odd1 about consecutive identical stdstringfind callstestcppinclude stringvoid fstdstring classname stdstring testname const size t endofclassnamepos classnamefind if endofclassnamepos stdstringnpos testname classnamesubstrendofclassnamepos 2 voidclassnameeraseendofclassnamepos stdstringnpos void f oddstdstring classname stdstring testname if classnamefind stdstringnpos testname classnamesubstrclassnamefind 2 voidclassnameeraseclassnamefind stdstringnpos define a define b define c void f odd1stdstring classname stdstring testname if classnamefinda stdstringnpos testname classnamesubstrclassnamefindb 2 voidclassnameeraseclassnamefindc stdstringnpos so far so good now cppcheck has to be tweaked to catch consecutive identical stdstringfind calls for this i have created a cppcheck rulefile that contains a regular expression that matches consecutive identical stdstringfind callsxml version10ruletokenlistnormaltokenlistpatterncdataazazazaz09ssfindss s n123 znpatternmessage severitystyleseverity summaryfound identical consecutive stdstringfind callssummarymessagethis file can be used to extend cppcheck about a new check lets trycppcheck rulefilerulesrulexml testtestcppand the output ischecking testtestcpptesttestcpp14 style found identical consecutive stdstringfind callstesttestcpp26 style found identical consecutive stdstringfind callsnow identical consecutive stdstringfind calls can be detected in cc codes does anybody know a bettermore efficient or more clever solutionreferencescheckout the cppcheck rule file on githubhow to write custom rules for cppcheck,['c++'] +1139505,ef returning different values than query so i just came across this very odd scenario and was wondering if anyone might know what the problem is i have the following ef linq queryvar hierarchies from hierarchy in ctxpolygonhierarchyviews where hierarchydashboardid dashboardid select hierarchywhen i inspect that query in the debugger it shows the following sqlselect extent1dashboardid as dashboardid extent1currentid as currentid extent1polygontypeid as polygontypeid extent1thisplayname as thisplayname extent1parentid as parentidfrom dbopolygonhierarchyview as extent1where extent1dashboardid p linq 0if i run that in sql server management studio substituding p linq 0 with the value of dashboardid i get these resultsdashboardid currentid type name parentid4 5 1 region null4 6 2 market null4 7 3 submarket 64 8 4 zipcode 74 6 2 market 54 7 3 submarket 64 8 4 zipcode 7however the results from iterating the ef query are as followsdashboardid currentid type name parentid4 5 1 region null4 6 2 market null4 7 3 submarket 64 8 4 zipcode 74 6 2 market null4 7 3 submarket 64 8 4 zipcode 7notice that the fifth row has a parentid of null instead of 5 this is how i worked around the problemvar hierarchies from hierarchy in ctxpolygonhierarchyviews where hierarchydashboardid dashboardid group hierarchy by hierarchyparentid into grp select grpasenumerablethe odd thing here is that this results in a igrouping with a key value of 5 but the parentid of the single object in that group is nulli am attempting to creat a lookup from that query and wanted to just dovar lookup hierarchiestolookuph hparentidbut since the actually parentid does not seem to always have the correct value and i have to do the group by i end up having to do the followingvar lookup hierarchiesselectmanyx xselecty new xkey view y tolookuph hkey h hviewto make matters even stranger if i remove the asenumerable from the end of the query before doing the selectmany and tolookup it will still result in the entity that should have a parentid of 5 being grouped under nullis this some type of bug with ef or am i just missing something here btw i am using ef 613,['c#'] +1139593,how to handle https url that ends up plaintext connection i try to get the page content of a https url that throws an exception while getting input streamstring httpsurl url myurl new urlhttpsurlhttpsurlconnection con httpsurlconnectionmyurlopenconnectioninputstream ins congetinputstreamthe exception is as belowexception in thread main javaxnetsslsslexception unrecognized ssl message plaintext connection at comsunnetsslinternalsslinputrecordhandleunknownrecordinputrecordjava523 at comsunnetsslinternalsslinputrecordreadinputrecordjava355 at comsunnetsslinternalsslsslsocketimplreadrecordsslsocketimpljava798 at comsunnetsslinternalsslsslsocketimplperforminitialhandshakesslsocketimpljava1138 at comsunnetsslinternalsslsslsocketimplstarthandshakesslsocketimpljava1165 at comsunnetsslinternalsslsslsocketimplstarthandshakesslsocketimpljava1149 at sunnetwprotocolhttpshttpsclientafterconnecthttpsclientjava434 at sunnetwprotocolhttpsabstractdelegatehttpsurlconnectionconnectabstractdelegatehttpsurlconnectionjava166 at sunnetwprotocolhttphttpurlconnectiongetinputstreamhttpurlconnectionjava1172 at sunnetwprotocolhttpshttpsurlconnectionimplgetinputstreamhttpsurlconnectionimpljava234 at urljavahttpsexamplemainjavahttpsexamplejava18 both httpurlconnection and httpsurlconnection fail i tried orgapachehttpimplclientcloseablehttpclient but getting the same exception in browser it works fine,['java'] +1139599,deprecationwarning in sklearn minibatchkmeans vectors modelsyn0n clusters kmeans 20 more for visualization 100 better for clusteringmin kmeans minibatchkmeansinitkmeans and clustersn clusters kmeans and init10min kmeansfitvectorsx reduced truncatedsvdn components50 random state0fit transformvectorsx embedded tsnen components2 perplexity40 verbose2fit transformx reducedfig pltfigurefigsize10 10ax pltaxesframeonfalsepltsetpax xticks ytickspltsubplots adjustleft00 bottom00 right10 top09 wspace00 hspace00pltscatterx embedded 0 x embedded 1 cnone markerxpltshowi want to plot vectors i am using sklearncluster minibatchkmeans above code is giving me following deprecation error usrlocallibpython35sitepackagessklearnclusterk means py1328 deprecationwarning this function is deprecated please call randint0 99 1 instead 0 and samples 1 selfbatch size any suggestions are appreciatedthanks,['python'] +1139731,chronological trace of function calls in c using etrace backgroundi have one big simulation tool and i need to understand its logical behavior in order to do that the most of help i would get if i have the chronological order of function calls for a minimal working examplei found many tools online like cygprofiler and etrace i became so miserable on finding a solution that i started to follow the craziest solution of using step into with the debugger which is a good option if you have a small program but not a complete simulation toolproblemone of the problems i face is that the abovementioned solutions are originally meant for c and they generate a static file o when compiled on the other hand the simulation tool generates a shared library so i do not have much knowledge on lower level stuff so i seem to fail when i try linking themi looked specifically at the etrace documentation and it saysto see how to modify ptracec to work with a dynamic library look at the example2 directory the sources there also create a standalone executable but the ptrace reference function macro is defined just as it would be for a dynamic libraryif you look at the repo there is no difference between the files in example and example2 folders only there is an extra h file in example2on the other hand if you look at srcptracec there it sayswhen using ptrace on a dynamic library you must set the ptrace reference function macro to be the name of a function in the library the address of this function when loaded will be the first line output to the trace file and will permit the translation of the other entry and exit pointers to their symbolic names you may set the macro ptrace include with any include directives needed for that function to be accesible to this source filea little below there is the commented code when using ptrace on a dynamic library the following must be definedinclude any files needed for ptrace reference functiondefine ptrace reference function functionnamequestionin essence the question is the following how to use etrace with a dynamic librarydo i need to include any filesto trace a standalone program there is no need to include any additional file just link your code against ptracec and use the finstrumentfunctions option as a compile option for gcc this should do ithow do i link a c code which is built via makefiles against ptracecfinal note i would appreciate if someone bears with my ignorance and provides a stepbystep solution to my questionupdate 1i managed to add the libraries related to etrace to the simulation tool and it executes fine however probably because the scripts are too old or are not meant for use with c i get the following error when using the perl script provided by default by etracehexadecimal number 0xf nonportableprobably this changes a bit the nature of this question turning it more to a perl related issue at this point if this problem is solved i hope etrace will work with a complicated project and i will provide the detailsupdate 2i took the suggestions from harry and i believe that would work in most projects however in my case i get the following from the perl scriptuse of uninitialized value within symboltable in list assignment at etrace2pl line 99 call data line 1 due to autegenerated makefiles i used the ld preload to load the shared library for etraceso which i got as followsgcc g finstrumentfunctions shared fpic ptracec o etraceso i pathtoetracei created the dummy etraceh inside the toolifndef etrace h define etrace h include stdiohvoid crumble buychar what int quantity char unitvoid crumble buychar what int quantity char unit printfbuy d s of sn quantity unit whatendifand used crumble buy for the define and the etraceh for the include,"['c++', 'c']" +1139880,how to use autotools nobase and nothist prefixs together on include headers i have some header files in a sub directory that must be copied to a samenamed sub directory in my include directory i can use the nobase prefix to make that happen i am working with heimdal code fyinobase include headers hcryptoaesh hcryptobnh hcryptocmach hcryptodesh hcryptodhh hcryptodsah etcbut some of those header files are generated during the build process since heimdal must be built before those header files exist so i need to use the nothist prefix so that the thist does not diei found an article that said i could use them both together and even provided a similar example so i did thisnobase nothist include headers hcryptoaesh hcryptobnh hcryptocmach hcryptodesh hcryptodhh hcryptodsah etci did not notice any warnings or errors but those header files do not get copied to my include directoryam i doing something wrong or is there a bug in autotoolsinteresting if i reverse the prefixes i get this errormakefileam93 error nothist nobase include headers is used but nobase includedir is undefinedthe reason for that error is explained here in the automake documentationanobase a should be specified first when used in conjunction with either athist a or anothist ai have also defined nothist include headers which is working maybe the two definitions are causing some kind of conflicti just tried removing the nothist include headers and putting all my headers under the nobase nothist include headers line but now none of my headers get installedautomake and system infoautomake gnu automake 1134 opensuse 132 x86 64,['c'] +1139882,notificationlistenerservice and doze mode and app standby i have an app that listens for phone notifications and sends a message to an android wear watch via the messageapi everything works good except for some devices with android 6 especially huawei mate 8 looks like all huawei android 6s do thishuawei has its own implementation of freezing apps background processing protected apps from the users reports i have confirmed that my app has an exception in the huaweis protected apps and also in the android 6s doze mode the app works ok but after exactly 15 minutes with thisplay off my app stops sending messages to the connected android wear watch my app can also record received notifications history and nothing arrives after the 15 minutes until the phones thisplay is turned on and my app is opened after that all the notifications that should have arrived while the phones thisplay was off arrive into my notificationlistenerservice implementation and are sent to the watch all at once this is also confirmed with the recorded historyany ideas how to fix this for these phones especially the huawei mate 8 with android 6 with doze modewhat is the correct behaviour of the notificationlistenerservice while the device is in the doze mode andor the app is in the standby modeeditusers have also confirmed that their phones are not in a power saving mode which also affects background apps and their services this bug looks like huawei exclusive because no nexus users have reported this and my oneplus one with m is not doing this either also and preview works good on nexus devicesedit 2i have added an optional foreground service startforeground so my app has a permanent notification in the notification center thus my app should be excluded from every battery optimization for the foreground service notification i used a priority of notificationcompatpriority min and i added the notificationflag ongoing event flag this helped a bit on the huawei phones but not much now the delayed notifications arrive into my notificationlistenerservice right after the screen is turnedon instead after opening my app i do not use the startforeground in my notificationlistenerservice but in another service because i have no control about its lifecycle,['android'] +1139939,is time preprocessor macro guaranteed to be constant within a file just out of curiosity i am wondering whether the value given by the standard time preprocessor macro can change within a single translation unitin other words is time determined once during preprocessing and then fixed or is it reevaluated each time it is encounteredif this is not specified by the c standard is there a de facto standard behavior among the major implementations gnu clang intel msvc,['c'] +1140071,strace a python function is it possible to strace a python function for opened files and differentiate if they were opened by python or a subprocessread python read external strace readread python read externalfunction test file openfootxt r subprocesscallcat bartxtfor file in read python printpython filefor file in read external printexternal fileso the output is as python footxt external bartxti am most interested in using a decorator differentiating is not a priorityconceptually my best guess is to replace instances of load functionopen with wrappers actually i have no idea there are too many ways to access open,['python'] +1140110,extract values which do not end by specific words i have a table with some data it could look for example like this7 gelb 8 schwarz9 weia my color10 grau16 gelb i 17 gelb ii 18 gelb i 19 gelb iv 27 schwarz i 28 schwarz ii 29 schwarz i 30 schwarz iv 31 schwarz v 32 schwarz vi 39 weia my color i 40 weia my color iv 41 weia my color v 42 weia my color vi as you can see in some records we have roman numbers in convention namespaceroman numberfor instance there are gelb weia my color and schwarz and there are also records for them in roman convention for some like grau there are no duplicatesso there will be record with unique color name without a roman number eg record grau and in the table it could contain or not some records with it and roman numbers for itroman numbers would be always at the end like namespaceromannumbermy goal is only to get unique names so out of example i want to extract only7 gelb 8 schwarz 9 weia my color 10 grau how can i achieve thati started with this would it be enoughselect id name from mytable where name not like spaceanyromancharacteri cannot change structure of the database,['sql'] +1140203,faster geometric average on ascii is it possible to speed up the following code but without using external modules numpy etc just plain python two lines of thought speeding the computation in chrintround multiplords10dlen 0 or faster building of the desired structure the aim is to find the geometric average of an ord of an ascii symbol and report it as a round value symbol the lenindict is anything above 1 the outcome of the example should be kmithe codedef ga instr0204507890 indict 0abcdefghij 1klmnopqrst 2wxyz outstr dlen lenindict for pos in zipinstr indictvalues if pos00 multiplords 1 for mul in ordchar for char in pos1 if char multiplordsmul outstr chrintround multiplords10dlen 0 return outstrif name main import timeit printtimeittimeitga setupfrom main import ga,['python'] +1140453,afnetwoking post call returns 500 internal server error but server got request parameter i am trying to upload my payment success message to my server below are my codeafhttprequestoperationmanager manager afhttprequestoperationmanager alloc initmanagerrequestserializer setvaluensstring stringwithformatbearer mytokenstring forhttpheaderfield authorizationafhttprequestoperation operation manager postmyapi parametersparamsdict successafhttprequestoperation operation id responseobject nslogresponseobject failureafhttprequestoperation operation nserror error nslogerrorlocalizeddescriptionoperation startbut i am getting error code 500 internal server error but my server has all the information and api call is success can anyone please help me understand why it is entering the error block,"['ios', 'objective-c']" +1140551,how to get the ids of nested array once the condition is met i have a nested array once the condition is met it should give all the parent ids eg i have a data array in which i should match the getparentidsdata 182 result 96 182getparentidsdata 174 result 109 219 76 174var data id 96 name test1 items id 181 name yes items id 182 name no items id 109 name test5 items id 219 name opt2 items id 76 name test3 items id 173 name yes items id 174 name no items id 100 name test2 items id 189 name yes items id 224 name opt3 items function getparentidsdata id parentids if parentids parentids datamapfunctionitem if itemid id parentidspushitemid return parentids else if itemitemslength 0 do nothing else return getparentidsitemitems id parentids consolelogarray list getparentidsdata 182 could you give me any suggestion on this,['javascript'] +1141076,avx2 what is the most efficient way to pack left based on a mask if you have an input array and an output array but you only want to write those elements which pass a certain condition what would be the most efficient way to do this in avx2i have seen in sse where it was done like thisfrom afredriksson simdpdf m128i leftpack se3 m128 mask m128 val move 4 sign bits of mask to 4bit integer value int mask mm movemask psmask select shuffle control data m128i shuf ctrl mm load si128shufmasksmask permute to move valid values to front of simd register m128i packed mm shuffle epi8 mm castps si128val shuf ctrl return packedthis seems fine for sse which is 4 wide and thus only needs a 16 entry lut but for avx which is 8 wide the lut becomes quite large256 entries each 32 bytes or 8k i am surprised that avx does not appear to have an instruction for simplifying this process such as a masked store with packing i think with some bit shuffling to count the of sign bits set to the left you could generate the necessary permutation table and then call mm256 permutevar8x32 ps but this is also quite a few instructions i thinkdoes anyone know of any tricks to do this with avx2 or what is the most efficient methodhere is an illustration of the left packing problem from the above documentthanks,['c++'] +1141191,invalid column deleted while trying to query a column i am trying to execute the following query in my android aprivate static final string projection datacontact id datamimetype datathisplay name phonenumber phonetype structurednamegiven name structurednamemiddle name structurednamefamily name datadeleted private static final string selection datamimetype and phonetype in or datamimetype in private static final string selection args phonecontent item type stringvalueofphonetype mobile stringvalueofphonetype home stringvalueofphonetype work structurednamecontent item type final cursor cursor mcontextgetcontentresolverquery datacontent uri projection selection selection args datacontact idbut i get the following error0429 110058715 8588 15565 e databaseutils writing exception to parcel 0429 110058715 8588 15565 e databaseutils javalangillegalargumentexception invalid column deleted 0429 110058715 8588 15565 e databaseutils at androiddatabasesqlitesqlitequerybuildercomputeprojectionsqlitequerybuilderjava632 0429 110058715 8588 15565 e databaseutils at androiddatabasesqlitesqlitequerybuilderbuildquerysqlitequerybuilderjava447 0429 110058715 8588 15565 e databaseutils at androiddatabasesqlitesqlitequerybuilderquerysqlitequerybuilderjava387 0429 110058715 8588 15565 e databaseutils at comandroidproviderscontactscontactsprovider2doquerycontactsprovider2java6528 0429 110058715 8588 15565 e databaseutils at comandroidproviderscontactscontactsprovider2querylocalcontactsprovider2java6479 0429 110058715 8588 15565 e databaseutils at comandroidproviderscontactscontactsprovider2querycontactsprovider2java5038 0429 110058715 8588 15565 e databaseutils at androidcontentcontentprovidertransportquerycontentproviderjava238 0429 110058715 8588 15565 e databaseutils at androidcontentcontentprovidernativeontransactcontentprovidernativejava112 0429 110058715 8588 15565 e databaseutils at androidosbinderexectransactbinderjava453i want to know if the contact that i am reading is deleted or not so the datadeleted column is needed for me and that seems to be causing the errorbut when i checked the android documentation deleted does seem to be a valid column to use with contactscontractdata,['android'] +1141475,how can i wrap text around stacked elements ie elements with negative margins i am hope someone can help me with thisi would like to wrap text around multiple stacked floated elements however when i am adding a negative margin to the second element the text does not play ball see belowdoes anyone have a solution that can help me with this thanks in advancewhat i have done so far herestyleelements floatleft padding10px width50 background039 colorf fontfamilyarial helvetica sansserif colorf padding50px boxsizingborderbox marginright 20px position relativeelementtwo margintop50px background900 marginleft30pxstylediv idpostdiv idelementone classelementselement 1divdiv idelementtwo classelementselement 2divlorem ipsum dolor sit amet consectetur adipiscing elit etiam id dictum odio interdum et malesuada fames ac ante ipsum primis in faucibus vivamus vitae leo dictum brbrbrporttitor augue ut accumsan nunc phasellus at malesuada orci quis varius nulla nullam dui purus elementum non fermentum eu laoreet ac massa maecenas dictum elit sit amet mi pretium tincidunt maecenas interdum elementum lectus eu aliquam nibh lacinia nec brbrbrquisque facilisis accumsan blandit mauris eget pulvinar lacus donec pretium posuere mattis suspenthisse et tempor orci sit amet placerat neque etiam laoreet massa eu libero posuere sit amet laoreet metus auctordivhow i would like the page to lookhow the page looks as it is,"['javascript', 'jquery', 'html', 'css']" +1141521,get a authorized token for o365 calendar i am making an app that needs to access the content of a office 365 calendarthat app should not need a direct user action to log in and retreive its data so i cannot use a standard oauth way to get this tokeni was a bit familiar of googles calendar way to do that with it is service account logic involving a non symetrical rsa key to do it so i tried to find something like that for o365i have found this blog that helped me a lot configuring an application and setting up all the keys on both side to allow the connection in the end i managed to make it work got a token and list the resourcegroupsall was fine and i exepected it to work quite easily with microsoft graph apiso i added the microsft graph api in my applications authorizations on azure management and added all the read write permissions on all users calendars in the applications authorizations and in delegated authorization i regenerated the tokens so the new rights can be added to it i used this token to get a list of the calendarsand it never worked i have the token and the request gives me the good scopes with it so i know i am on the right app and everything when i give the token to outlookofficecom i have this message i have probably missed a step somewhere but i cannot find where in my requests in my azure account any help please the requests did not blur anything just a test account anywayget token request post 6a23b9c104fc4782b08c786d2a16c95doauth2token http11host loginmicrosoftonlinecomcontenttype applicationxwformurlencodedcachecontrol nocachepostmantoken f7b2884d44e9c48a6245453be490758cgrant typeclient credentialsclient id0577ff63730e418aa68f6cbc590b6874resourcehttps3a2f2foutlookofficecom2fclient assertion typeurn3aietf3aparams3aoauth3aclientassertiontype3ajwtbearerclient assertioneyjhbgcioijsuzi1niisinr5cci6ikpxvcising1dci6imxhvkmzbed3k3hkwkpktuqrbupmdmrou1v2bz0ifqeyjhdwqioijodhrwczovl2xvz2lulm1py3jvc29mdg9ubgluzs5jb20vnmeym2i5yzetmdrmyy00nzgylwiwogmtnzg2zdjhmtzjotvkl29hdxromi90b2tlbiisimlzcyi6ija1nzdmzjyzltczmgutnde4ys1hnjhmltzjymm1otbinjg3ncisinn1yii6ija1nzdmzjyzltczmgutnde4ys1hnjhmltzjymm1otbinjg3ncisimp0asi6ijaumtgyotg1oduznjm2njm3mzmilcjuymyioiixndyxotqyodu2iiwizxhwijoimtuymjqymzg1niisimlhdci6mtq2mtk0mzg1nn0czm9ks jrevviudjfmf1uvulf5szrcsgtcmisfn3c8119kqoczlpwbpu3crjjidip2yxcsgjrscgyjpiwq2qks45 97jbe fbpojb5lni5qyt 2ep6oyaanid4vxlf9wscxffhetlqosqozwb4c6 yxdoiy82sj0slqlgzrflnqyn6umxgwthefkpr3qsolgo4wn5lthfrwf iuipg2dnjyniz2kvhqvlqqzpglze soakldiar4bazmxlndhmcnouadgfsr0paazaym0me4k7frgblpatdxu6m4v9edlm9j23dg82hokdf0gdc6pcixkmisutr8ixgfxotwget token answer token type bearer scope calendarsread calendarsreadwrite expires in 3600 expires on 1461951871 not before 1461947971 resource access token eyj0exaioijkv1qilcjhbgcioijsuzi1niising1dci6ik1uq19wwmnbvgznnxbpwwlkse1iytlnb0vlwsisimtpzci6ik1uq19wwmnbvgznnxbpwwlkse1iytlnb0vlwsj9eyjhdwqioijodhrwczovl291dgxvb2sub2zmawnllmnvbs8ilcjpc3mioijodhrwczovl3n0cy53aw5kb3dzlm5ldc82ytizyjljms0wngzjltq3odityja4yy03odzkmmexnmm5nwqviiwiawf0ijoxndyxotq3otcxlcjuymyioje0nje5ndc5nzesimv4cci6mtq2mtk1mtg3mswiyxbwawqioiiwntc3zmy2my03mzblltqxogetyty4zi02y2jjntkwyjy4nzqilcjhchbpzgfjcii6ijiilcjpzhaioijodhrwczovl3n0cy53aw5kb3dzlm5ldc82ytizyjljms0wngzjltq3odityja4yy03odzkmmexnmm5nwqviiwib2lkijoimgqyodjlmdgtzgzkoc00y2ywlwjmyzmtymq2mdzmmdeynzvhiiwic3viijoimgqyodjlmdgtzgzkoc00y2ywlwjmyzmtymq2mdzmmdeynzvhiiwidglkijoinmeym2i5yzetmdrmyy00nzgylwiwogmtnzg2zdjhmtzjotvkiiwidmvyijoims4win0l8mp4t zmxfl5vjqweaosdere81jtz9ltzxk0ta0qa hwriynvmhrydypthhqc7jv3m6hisnsvyvexx uynfkprz3sy xojmof5xslmrw1niqe6j7ohq5pepmofa0mqowmanchemdv5jcdxnootbd4xes jzg9tlmihzpqbcauo3zgn8q5pt7agpydoeahcwwdsklhlfkbjz3y nttqaddsr9ae2h6dotp5hxcphqzkzodtzcusbqrz1vcshcd8kziux ebxitlj8juzur1yjfy9jww0ntroob71xjp9iuf2njmsrqvr2ql8vflptarpgqfru9ccz4kpbvs3qcalendar list request get apiv20mecalendars http11host outlookofficecomauthorization bearer eyj0exaioijkv1qilcjhbgcioijsuzi1niising1dci6ik1uq19wwmnbvgznnxbpwwlkse1iytlnb0vlwsisimtpzci6ik1uq19wwmnbvgznnxbpwwlkse1iytlnb0vlwsj9eyjhdwqioijodhrwczovl291dgxvb2sub2zmawnllmnvbs8ilcjpc3mioijodhrwczovl3n0cy53aw5kb3dzlm5ldc82ytizyjljms0wngzjltq3odityja4yy03odzkmmexnmm5nwqviiwiawf0ijoxndyxotq3otcxlcjuymyioje0nje5ndc5nzesimv4cci6mtq2mtk1mtg3mswiyxbwawqioiiwntc3zmy2my03mzblltqxogetyty4zi02y2jjntkwyjy4nzqilcjhchbpzgfjcii6ijiilcjpzhaioijodhrwczovl3n0cy53aw5kb3dzlm5ldc82ytizyjljms0wngzjltq3odityja4yy03odzkmmexnmm5nwqviiwib2lkijoimgqyodjlmdgtzgzkoc00y2ywlwjmyzmtymq2mdzmmdeynzvhiiwic3viijoimgqyodjlmdgtzgzkoc00y2ywlwjmyzmtymq2mdzmmdeynzvhiiwidglkijoinmeym2i5yzetmdrmyy00nzgylwiwogmtnzg2zdjhmtzjotvkiiwidmvyijoims4win0l8mp4t zmxfl5vjqweaosdere81jtz9ltzxk0ta0qa hwriynvmhrydypthhqc7jv3m6hisnsvyvexx uynfkprz3sy xojmof5xslmrw1niqe6j7ohq5pepmofa0mqowmanchemdv5jcdxnootbd4xes jzg9tlmihzpqbcauo3zgn8q5pt7agpydoeahcwwdsklhlfkbjz3y nttqaddsr9ae2h6dotp5hxcphqzkzodtzcusbqrz1vcshcd8kziux ebxitlj8juzur1yjfy9jww0ntroob71xjp9iuf2njmsrqvr2ql8vflptarpgqfru9ccz4kpbvs3qcachecontrol nocachepostmantoken e85ac526c56a4d5b2f7483f4033decb4answer empty but in the headers contentlength a0date afri 29 apr 2016 164459 gmtserver amicrosoftiis85wauthenticate abearer client id020ff1ce0 trusted issuers010c0 token typesapp asserted user v1 service asserted app v1 authorization uri errorinvalid tokenbasic realmbasic realmxbeserver avi1pr08mb0910xbackendhttpstatus a401xcalculatedbetarget avi1pr08mb0910eurprd08prodoutlookcomxdiaginfo avi1pr08mb0910xfeserver aam3pr08ca0034xmsedgeref aref a b612166bb1764a45b0f3bce6df9cb639 ref b a8d71806cb57091b57fd0130aabf9d85 ref c fri apr 29 094500 2016 pstxpoweredby aaspnetrequestid a26f132cadf5e439fbd4f7d655ba7df21xmsdiagnostics a208reasonthe token contains no permissions or permissions can not be understooderror categoryinvalid grant,['javascript'] +1141525,sorting and filtering on date i have a date column and need to be able to both sort and filter on it the data comes in as strings like 20101223 and can preprocessed as needed it should be shown as 23122010 some internationalization will come lateri wonder whats the proper internal representationa string like 23122010 is bad for sorting it could be done by sorting on function result but it would be slowa string like 20101223 sorts correctly can be formatted easily but filtering for 2312 does not work it could be done but it would be slowdate would probably get sorted correctly but filtering would be slowmoment could be the solution no ideamy current idea is to create an object containing both milliseconds and the thisplayed string so that all operations can be fast but i would bet that someone was that smart before melet us assume that showing dates in the form like 20101223 is unacceptable otherwise the problem is solved to summarize the problem is that i need tothisplay and filter in the ddmmy formatsort according to the numerical value or equivalently as if it was in th iso format,['javascript'] +1141881,determine reason for odex file size bloat my apk was 13mb and on installation the occupied space is 25mb however after making a few changes adding libraries creating modules and organizing the app better the apk size had increased to 14mb while the odex file is now 56mb is there any way to determine why the size has increasedi have a rooted device so i can use more than the traditional approaches too if there are any i checked several blogs and forums all explain the odexing and deodexing related functionalitiesedit the size of the odex file increases with time 25mb to 81mb nowthis so qa explains what an odex is but i cannot find any place which explains how the odex file for the lack of a better word growsa possible option could be that when an apps resources are used the app odex files generates more references to keep the launch time constantfasteredit 2 since a lot of people are answering this by suggesting me to check my librariesdependencies and reduce themi want to stress on the observation that the file size increases after installing in the next few launches of the applicationif it were because of libraries additionthe apk size increases which is totally understandablethe rest of the filesdbshared preferences etc increase in size which is expectedwhat i cannot figure out is why does the odex increase after it is installed which keeps on increasing after every launch this increase in size is only for the odex filei have checked these files because i am using a rooted device,['android'] +1142224,batch upload videos to youtube via command line python i am using the script from youtubeupload to upload videos to my channel via the command line how can i run the code to process all files in a specific foldersonce i saw an example on the net showing how to batch upload videos to youtube using this same script and also getting the titles categories description and tags from a csv excel file each from a column corresponding to the file name in another column i forgot to save this example and now i cannot seem to find this or create it on my ownby the way i am on windows 10 environment using the command line toolto upload single video i am using this scriptyoutubeupload titleas mutter descriptionas mutter plays beethoven categorymusic tagsmutter beethoven recordingdate20110310t1532170z defaultlanguageen defaultaudiolanguageen clientsecretsclient secretsjson credentialsfileclient secretsjson testmp4updatethe csv file will have the same number of columns as i will have parameters in the youtubeupload command let us say there will be title description category tags columns only and of course the first column will be the file name if needed i will also add the location of the file,['python'] +1142249,whats the difference between the new netstandardapp and netcoreapp tfms i noticed that nuget has recently added support for several new tfms related to net core includingnetstandard 1015netstandardapp 15netcoreapp 10to the best of my knowledge netstandard is the net core equivalent of a portable profile it allows you to target multiple platforms using a single moniker instead of explicitly spelling out every platform you support eg portablenet45netcore45wp81meanwhile according to this document netstandardapp is more like a console application in net core it represents something that any net core runtime eg coreclr corertwhat then exactly is netcoreapp supposed to be i found the tracking issue for it here which includes a comment at the bottom that kinda explains what the difference is but i do not get what the difference betweennetstandardlibrary app hostsandnet core base installis could someone please explain it to me thanks,"['c#', '.net']" +1142319,theano cnn on cpu abstractconv2d theano optimization failed i am trying to train a cnn for object detection on images with the cifar10 dataset for a seminar at my university but i get the following errorassertionerror abstractconv2d theano optimization failed there is no implementation available supporting the requested options did you exclude both conv dnn and conv gemm from the optimizer if on gpu is cudnn available and does the gpu support it if on cpu do you have a blas library installed theano can link againsti am running anaconda 27 within a jupyter notebook cnn training on cpu from a windows 10 machine as i already have updated to the newest theano version using git clone i tried the following thingsexclude dnn and gemm directly from within the code theano flagsoptimizer excludingconv dnn optimizer excludingconv gemmexclude dnn and gemm directly from cmd typing theano flags python myscriptpy which not suprisingly gives an unknown command errorexclude dnn and gemm from a theanorctxt which i put into cusermyusernameunfortunately i still get the same error and when i call printteanoconfig the terms conv dnn and conv gemm do not appearfurthermore i tried to find out what blas my numpy package is using which generally works well for and if that package is static using a tool from dependencywalkercom but i failed miserablyso heres my question how on earth can i set the theano flags properly and how can i check if i suceeded in doing so if that does not help how can i check what blas i am building which one should i use and how can i change the dependency for theanoas you might have guessed i am not an expert when it comes to all this package dependency built and other fancy computer science stuff and the documentation i find only is just not noob proof so i would be most grateful i you guys could help me outbestjonas,['python'] +1142582,can an object erase itself from a standard c container the following codeinclude iostreaminclude mapstruct foo void killstdmapint foo m int i merasei int main stdmapint foo m memplace1 foo stdcout msize stdendl m1killm 1 stdcout msize stdendlcompiles without warning g executes without error and judging by the output the kill method erases the foo object from the map however i feel that this might actually be undefined behavior it seems that in the kill method after the line merasei this no longer points to a valid objectwhat does the c standard say about this,['c++'] +1142735,c char from int used as string the real equivalent of vb chr i was converting a vba macro to c and in vba chr7 can simply be concatenated to a string as if chr would yield a string why cannot this be done in ci am trying to find a clear answer to my question i have read many posts and related questions on this on so and several other sites for example this one which is the key answer many others are marked off as dulpicates and redirect to this one whats the equivalent of vbs asc and chr functions in cand unfortunately the answer is not clear and many times they state that this is a correct usestring mystringchar7yet it gives me a compiler error as it does not evaluate as a stringi had to use this to make it workstring mystringchar7tostringthis would be the equivalent of the vb chr function really as chr in vb evaluates as a stringmy question is this do i always need to cast the char over to string explicitly or there are some cases where it converts over implicitlyupdateper dirks answer this also worksstring mystring char7this does not lessen my mystery if concatenation works why there is no implicit casti would like to get a full explanation on the difference between the vb chr and its equivalents in c i would appreciate any reference where i can read up on or even examples would do thanks in advance,['c#'] +1142759,llvm optimizer cannot handle simple case i wrote a cpp file shown belowint main int a b scanf d b for int i 0 i 10 i a 0 if b 10 a 3 return athen i compiled this code by clang with o3 option the output ll file isdefine i32 main 0 entry b alloca i32 align 4 call call i32 i8 scanfi8 getelementptr inbounds 3 x i8 str i32 0 i32 0 i32 b 0 load i32 b align 4 tbaa 1 cmp1 icmp sgt i32 0 10 select i1 cmp1 i32 3 i32 0 ret i32 attributes 0 nounwind lessprecisefpmadfalse noframepointerelimfalse noinfsfpmathfalse nonansfpmathfalse stackprotectorbuffersize8 unsafefpmathfalse usesoftfloatfalse this output is good llvm optimizer stripped the meaningless forloop from the code and then assigned three or zero to return value directlynow i try another case likeint main int a b scanf d b for int i 0 i 10 i a 0 if true i modified here only a 3 return aand the output file isdefine i32 main 0 entry b alloca i32 align 4 call call i32 i8 scanfi8 getelementptr inbounds 3 x i8 str i32 0 i32 0 i32 b br label forcondforcond preds forcond entry a0 phi i32 0 entry 3 forcond i0 phi i32 0 entry inc forcond inc add nsw i32 i0 1 exitcond icmp eq i32 inc 1001 br i1 exitcond label forend label forcondforend preds forcond ret i32 a0attributes 0 nounwind lessprecisefpmadfalse noframepointerelimfalse noinfsfpmathfalse nonansfpmathfalse stackprotectorbuffersize8 unsafefpmathfalse usesoftfloatfalse even though this code is easier to analyze branch is always taken llvm optimizer does not strip meaningless forloopif i was optimizer i would like to generate this optimized code likedefine i32 main 0 entry b alloca i32 align 4 call call i32 i8 scanfi8 getelementptr inbounds 3 x i8 str i32 0 i32 0 i32 b ret i32 3can anyone tells me why the optimizer cannot analyze a simpler code,['c++'] +1142837,absolute url from base folder with rewrite i have a project running local on wampserver it is an mvclike structure it rewrites the url to indexphpurl1 full htaccessrewriteengine onrewritecond request filename drewritecond request filename frewritecond request filename lrewriterule indexphpurl1 qsalwhen i want to send the user to another page using php location location it does not do this properly because of the rewriting allthough i am technically always in indexphpfor example if i am on httplocalhostproject namecontrollermethod and this controllers constructor or method tries to send me toheaderlocation another controllermethod sends me tohttplocalhostproject namecontrollermethodanother controllermethodheaderlocation another controllermethod sends me tohttplocalhostanother controllermethodbut i want it to send me like thisheaderlocation another controllermethod sends me tohttplocalhostproject nameanother controllermethodnow the only solution i have found isdefinebase urlhttplocalhostproject nameheaderlocation base urlanother controllermethodbut this is not perfect either because it causes me to have to change this defined constant base url whenever the domain or folder name changes i could also create a method in my basecontroller that creates absolute urls but this method would basically just prepend base url toonote the same problem does not arise with htmls src and href attributes which can use relative paths without project name folder in path i do not understand why however because if the header location causes the browser to append the the relativeurl to the current location why does not it have the same behavior when looking for css or js filesso this raises a couple of questions for mewould i have this problem if i had virtual hostswhat is the best way to solve this problemis is best to just have the full absolute urlwhy do htmls src and href attributes not share this behavior,['php'] +1142861,how to ask rabbitmq to retry when business exception occurs in spring asynchronous messagelistener use case i have a spring amqp message listener runningpublic class consumerservice implements messagelistener autowired rabbittemplate rabbittemplate override public void onmessagemessage message try testserviceprocessmessage this process method can throw business exception catch businessexception e here we can just log the exception how the retry attempt is made catch exception e here we can just log the exception how the retry attempt is made as you can see there could be exception coming out during process i want to retry because of a particular error in catch block i cannot through exception in onmessage how to tell rabbitmq to there is an exception and retry,['java'] +1143181,templated class friend operator member function i am trying to get a friend function inside a templated class to compile but the error message and warning i do not understand i have made a demonstration of the issue the error i am getting isprogcpp857 error nonclass nonvariable partial specialization c operatorconst b lhs const c rhsprogcpp1559 warning friend declaration c operatorconst b const c declares a nontemplate function wnontemplatefriend friend c operatorconst b lhs const c rhsprogcpp1559 note if this is not what you intended make sure the function template has already been declared and add after the function name here include iostreamusing namespace stdtemplatetypename a typename bclass ctemplatetypename a typename bca b operatora bconst b lhs const ca b rhstemplatetypename a typename bstruct c a val c operatorconst c other const friend ca b operatorconst b lhs const ca b rhstemplatetypename a typename bca b ca boperatorconst ca b other const ca b c cval thisval otherval return ctemplatetypename a typename b ca b operatorconst b lhs const ca b rhs ca b c cval lhs rhsval return cint main cstring char c0c1 c0val c0 c1val c1 cout stuct c0 c1val n cout friend c1val endl return 0,['c++'] +1143244,rxswift misundestanding some concept i am a very beginner with rxswift and i am trying to begin with a simple login screen so i have 2 text fields and a login button which is bind to a publishsubject so every time i tap the button i will send a network request to perform authenticationsince authentication may fails i went with a driver so i could replay my request each time i click the buttoni have 2 version of what i think is the same code but one works and one does noti am trying to understand what happens behind the scenehere the first version which works request every time i touch the button let credentials drivercombinelatestemailasdriver passwordasdriver 0 1 selfsignin signintaps asdriveronerrorjustreturn withlatestfromcredentials flatmaplatest email password in returns driverresultauthenticateresponse apierror return providerrequestauthenticateemail email password password filtersuccessfulstatuscodes mapobjectauthenticateresponse map element resultauthenticateresponse apierror in return successelement asdriver error in let e apierrorfromerrorerror return driverresultauthenticateresponse apierrorjustfailuree debug and heres the one which does not work request fires only on first click let credentials observablecombinelatestemailasobservable passwordasobservable 0 1 selfsignin signintapsasobservable withlatestfromc flatmaplatest email password in returns observableauthenticateresponse return providerrequestauthenticateemail email password password filtersuccessfulstatuscodes mapobjectauthenticateresponse map element resultauthenticateresponse apierror in returns observableresultauthenticateresponse apierror return successelement asdriver error in returns driverresultauthenticateresponse apierror let e apierrorfromerrorerror return driverresultauthenticateresponse apierrorjustfailuree debugfor information heres my properties declaration let email variablelet password variablelet signintaps publishsubjectvoid let signin driverresultauthenticateresponse apierror,['ios'] +1143263,dictionaries and functions i have recently begun working with c and there is something i used to do easily in python that i would like to achieve in cfor example i have a function likedef my func return do some awesome stuffand a dictionary likemy dic do my funci have made a script in which when the user would input do the program would call my func according to the dictionaryi would like to know how i can assign functions to strings in a c dictionary,['c#'] +1143270,scroll a hidden viewlayout from bottom this is what i want to achieve i wanted to use absolutelayout but it is deprecated so i made a relativelayout beneath the blue view in the image above and then put everything inside a scrollview but the hidden view is still on the blue view and not below it also the screen scrolls but the hidden part is just cut and instead i see the my apps default backgroundany ideasedit my current try xml version10 encodingutf8scrollview xmlnsandroid androidlayout widthmatch parent androidfillviewporttrue androidlayout heightwrap contentrelativelayout androidlayout widthmatch parent androidlayout heightmatch parent androidanimatelayoutchangestrue androidorientationvertical imageview androidididimageview androidlayout widthmatch parent androidlayout heightmatch parent androidscaletypecentercrop androidsrcdrawableimageview linearlayout androidididcenterholder androidlayout width300dp androidlayout heightwrap content androidlayout centerinparenttrue androidorientationvertical linearlayout relativelayout androidlayout widthmatch parent androidlayout height10dp androidlayout belowidcousines main holder androidbackgroundcolorblack color relativelayoutrelativelayoutscrollview,['android'] +1143282,will an empty class be optimized away say i have the following classclass a and then in my code i have a functiona foo a ret do stuff return retand then i use the function laterwill an optimizing compiler like g just treat foo like a void function and skip actually allocating memory for the empty object it might not do this because even an empty class has a size of 1,['c++'] +1143670,error uitableview jump to top with uitableviewautomaticdimension i am using uitableview with estimatedrowheight and uitableviewautomaticdimension also i am using nsfetchedresultscontrollerdelegate to reflect the changes everything is work fine now the problem is when ever i add some record to coredata nsfetchedresultscontroller called the it is delegate but an unexpected things happen tableview suddenly scroll to top every time nsfetchedresultscontrollerdelegatefunc controllerwillchangecontentcontroller nsfetchedresultscontroller tableviewbeginupdatesfunc controllerdidchangecontentcontroller nsfetchedresultscontroller tableviewendupdatesfunc controllercontroller nsfetchedresultscontroller didchangeobject anobject anyobject atindexpath indexpath nsindexpath forchangetype type nsfetchedresultschangetype newindexpath nsindexpath switch type case insert tableviewinsertrowsatindexpathsnewindexpath withrowanimation none break case update tableviewreloadrowsatindexpathsindexpath withrowanimation none break case delete tableviewdeleterowsatindexpathsindexpath withrowanimation none break default break by googling i found few answers where people suggested to use tableview heightforrowatindexpath but as my cell height is dynamic so what should i do,['ios'] +1143698,android suspending all threads took ms i am having these warnings in my logcat even after a while that i left the application did not kill though just pressed back to leave it0503 134342955 1304713053package wart suspending all threads took 7873ms0503 134432458 1304713053package wart suspending all threads took 13441ms0503 134658584 1304713053package wart suspending all threads took 34462ms0503 134700574 1304713053package wart suspending all threads took 8281ms0503 134800425 1304713053package wart suspending all threads took 25929ms0503 134816019 1304713053package wart suspending all threads took 35053ms0503 135001858 1304713053package wart suspending all threads took 16160ms0503 135017975 1304713053package wart suspending all threads took 20074ms0503 135207744 1304713053package wart suspending all threads took 19814ms0503 135317668 1304713053package wart suspending all threads took 7578ms0503 135442766 1304713053package wart suspending all threads took 11316ms0503 135619314 1304713053package wart suspending all threads took 21873ms0503 135856140 1304713053package wart suspending all threads took 7860ms0503 140012084 1304713053package wart suspending all threads took 19430msthose numbers are serious and a loti saw some questions about this issue and none of them was similar to mine and i cannot accept that ignore it unless you do not have oom or freezing issue if that may cause i cannot wait until it happens to do something about it i just need to know what causes this and how can i prevent thisi use retrofit to get my webservice request done and a threadpoolexecutor to getupdatedelete data from cache while waiting for request completed i do not think any of these causing this thoughany ideas or general informations about this situation are appreciated because i find nothing specific on this suspending all threads warning,['android'] +1143728,uirouter default route based on user role i am using ui router in my project the home page of my application consists of 4 tabs each routing to a different template this is my current routing code im using a foreach to create 6 routes draftassignedinprogresscompletedrejectedallforeachfunction val stateproviderstate name rootjobslist valtolowercase url valtolowercase views currenttab templateurl adminworkspacejobs controller jobscontroller data userjobsstatus val by default when the user logs in it goes to rootjobslistdraft how do redirect to a given state based on the logged in users role admin user clerk etc if want to redirect all users that are part of the engineer or lead engineer role to rootjobslistinprogressi originally had this in the controller but as you can see it did not work because each time i clicked on a tab it always routes back to rootjobslistinprogress if user undefined if userbusinessrole engineer userbusinessrole lead engineer stategorootjobslistinprogress,['javascript'] +1143923,angular directive for affixing sidebar i am trying to affix the sidebar with respective to my main content i have tried directive here though i succeed with top affix ie it works and stick to top when scroll down but it fails to scroll incase my sidebar content is longer i want to fix it to top and move it scrollable according to main content but if its content it more then screen it should scroll to down as well and stick to bottom at same time div classbackgroundwhite sidebaraffix dataspyaffix dataoffsettop80 dataoffsetbottom10my sidebar content heredivdirectivesidebaraffix functionwindow return restrict ea link functionscope element attrs var originoffsettop element0offsettop scopecondition function return windowpageyoffset originoffsettop angularelementwindowbindscroll function scopeapplyfunction consolelogwindowpageyoffset originoffsettop if scopecondition angularelementelementremoveclassaffixtop angularelementelementaddclassaffix else angularelementelementaddclassaffixtop angularelementelementremoveclassaffix i want to be scrollable in case sidebar is longer than expected but it should stick to bottom in this case,"['javascript', 'jquery', 'html', 'css']" +1144065,what is the purpose of operator restrictedbool in qscopedpointer i have been reading through the code for qscopedpointer and came across something that i have not been able to make sense of heres the pertinent code from qscopedpointer on codeqtiotemplate typename t typename cleanup qscopedpointerdeletert class qscopedpointer typedef t qscopedpointer restrictedboolpublicif definedq qdoc inline operator bool const return isnull q nullptr qscopedpointerd else inline operator restrictedbool const return isnull q nullptr qscopedpointerd endifinline bool isnull const return dprotected t di understand the preprocessor definition that makes qdoc think qscopedpointer has an operator bool instead of operator restrictedbool what i do not understand it what purpose restrictedbool serves and how it does it for example a simpler implementation isinline operator bool const return isnullin short whats happening here why is operator restrictedbool underhandedly returning the address of d and why does it exist in the first place instead of operator bool,['c++'] +1144151,session app error installing apk i have just started exploring android studio to write and to test my first app i easily installed avd emulator and tested hello world on it but then i wanted to test app also on the real hardware i followed official instructions from here at the end android studio saw my device but i got such mistakesession app error installing apk i guess the problem probably can be in my android deviceit is chinese doogee x5 it does not have a given usb vendor id in developer docs so i decided to follow instructions with random vendor id from htc i am sure there is a way to run application on any android device but yet i did not find an answer on how to do that i am running through linux ubuntu 1404 lts,['android'] +1144351,changing text color on 2 sides of diagonal gradient line in html any idea on how to change text color for 2 parts of gradient line for example here if i want the blue part of the text s o and a part of m to be blackbutton background lineargradient140deg 00c9ff 35 transparent 35,"['html', 'css']" +1144611,how to use a union of two types i am trying to make a vector that can hold string and inti have tried the code below but i get the compilation error error use of deleted function my unionmy unionwhat am i doing wronginclude iostreaminclude vectorusing namespace stdunion my union string str int aint main vectormy union v my union u error use of deleted function my unionmy union ustr foo vpush backu return 0,['c++'] +1144737,why is this task not finishing before my code passes the wait command i have a task which runs a loop and delays for an interval each iteration once the cancellationtokensource calls cancel i want my main code to wait for the taskdelayinterval to finish and the task to exit the loop before my code continues i thought this code would work but it does not instead my main code passes the twait before the loop exits whymain method codevar cts new cancellationtokensourcecancellationtoken ct ctstokenvar t taskrun mylooptask200 ct prepare informationctscanceltwait send informationtask codeprivate async task mylooptaskint interval cancellationtoken canceltoken while canceltokeniscancellationrequested debugprint still in loop do something await taskdelayinterval debugprint cancelled clean up,['c#'] +1144796,how to extend angular2 datepipe up to angular2beta15 including the following code was working finepipe name isodateexport class isodatepipe extends datepipe implements pipetransform transformisodate string args any string return supertransformnew dateisodate args on rc1 its not working anymore even after i adjusted pipes syntaxpipe name isodateexport class isodatepipe extends datepipe implements pipetransform transformisodate string pattern string string const date new dateisodate return supertransformdate pattern the message i see in the browser is following the pipe isodate could not be foundif i remove the extends part and return some string it works againwhat has changedpscurrently changed it topipe name isodate export class isodatepipe implements pipetransform private datepipe datepipe new datepipe transformisodate string pattern string string const date new dateisodate return thisdatepipetransformdate pattern it works but looks a bit strange,['javascript'] +1144835,android thisplaying data from json to cardview in recyclerview i want to thisplay data from webservice to cardview in recycleviewer it had already success to thisplay data but it only thisplay one data although it has a lot of data to thisplaycan you help me to solve this problem thank yousellerjavapublic class seller string penjualimagealamattelp public string getpenjual return penjual public void setpenjualstring penjual thispenjual penjual public string getimage return image public void setimagestring image thisimage image public string getalamat return alamat public void setalamatstring alamat thisalamat alamat public string gettelp return telp public void settelpstring telp thistelp telp selleradapterjavaimport androidcontentcontextimport androidsupportv7widgetcardviewimport androidsupportv7widgetrecyclerviewimport androidviewlayoutinflaterimport androidviewviewimport androidviewviewgroupimport androidwidgetimageviewimport androidwidgettextviewimport comamobilomapodfixrimport comamobilomapodfixmodelsellerimport comsquareuppicassopicassoimport javautilarraylistimport javautillist created by nickypc on 542016 public class selleradapter extends recyclerviewadapterselleradapterpersonviewholder listseller sellers context context public selleradaptercontext contextlistseller sellers thissellerssellers thiscontextcontext public void setgriddatalistseller mgriddata thissellersmgriddata notifydatasetchanged override public personviewholder oncreateviewholderviewgroup parent int viewtype view v layoutinflaterfromparentgetcontextinflaterlayoutlist toko parent false personviewholder pvh new personviewholderv return pvh override public void onbindviewholderpersonviewholder holder int i holdersellersettextsellersgetigetpenjual holderaddresettextsellersgetigetalamat holdertelpsettextsellersgetigettelp picassowithcontextloadsellersgetigetimagefitintoholderimage override public int getitemcount return sellerssize public static class personviewholder extends recyclerviewviewholder cardview cv textview seller textview address textview telp imageview image personviewholderview itemview superitemview cv cardviewitemviewfindviewbyidridcv seller textviewitemviewfindviewbyidridlvseller address textviewitemviewfindviewbyidridlvalamat telp textviewitemviewfindviewbyidridlvalamat image imageviewitemviewfindviewbyidridperson photo override public void onattachedtorecyclerviewrecyclerview recyclerview superonattachedtorecyclerviewrecyclerview dogfragmentjavaimport androidaprogressdialogimport androidosasynctaskimport androidosbundleimport androidsupportv4appfragmentimport androidsupportv7widgetlinearlayoutmanagerimport androidsupportv7widgetrecyclerviewimport androidutillogimport androidviewlayoutinflaterimport androidviewviewimport androidviewviewgroupimport androidwidgetlistadapterimport androidwidgetlistviewimport androidwidgetsimpleadapterimport androidwidgettoastimport comamobilomapodfixjsonparserimport comamobilomapodfixmainactivityimport comamobilomapodfixrimport comamobilomapodfixadapterselleradapterimport comamobilomapodfixmodelsellerimport orgapachehttpnamevaluepairimport orgjsonjsonarrayimport orgjsonjsonexceptionimport orgjsonjsonobjectimport javautilarraylistimport javautilhashmapimport javautillist a simple link fragment subclass public class dogfragment extends fragment selleradapter mgridadapter jsonparser jparser new jsonparser arraylisthashmapstring string namelist jsonarray namesnull recyclerview data listseller mgriddata progressdialog pdialog private static final string url test anjing private static final string tag pesan message private static final string tag hasil result private static final string tag id id penjual private static final string tag seller nama toko private static final string tag alamat alamat toko private static final string tag telp no telp private static final string tag image image name private recyclerviewlayoutmanager layoutmanager public dogfragment required empty public constructor override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate override public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate inflate the layout for this fragment view rootviewinflaterinflaterlayoutfragment dog container false datarecyclerview rootviewfindviewbyidridrv layoutmanager new linearlayoutmanagergetactivity datasetlayoutmanagerlayoutmanager mgriddatanew arraylist mgridadapternew selleradaptergetactivitymgriddata new ambildatajsonanjingexecute return rootview public class ambildatajsonanjing extends asynctaskstringstringstring int sukses0 public ambildatajsonanjing pdialog new progressdialoggetactivity override protected void onpreexecute superonpreexecute pdialogsetmessagemengambil data silahkan tunggu pdialogsetindeterminatefalse pdialogsetcancelablefalse pdialogshow override protected string doinbackgroundstring args listnamevaluepair params new arraylistnamevaluepair try jsonobject json jparsermakehttprequesturl test anjing get params seller sellersnull ifjson null sukses jsongetinttag pesan ifsukses 1 namelist new arraylisthashmapstringstring logdsemua nama jsontostring names jsongetjsonarraytag hasil forint i 0 i nameslengthi jsonobject c namesgetjsonobjecti string id cgetstringtag id string seller cgetstringtag seller string alamatcgetstringtag alamat string telpcgetstringtag telp string imagecgetstringtag image hashmapstringstring map new hashmapstringstring sellersnew seller sellerssetpenjualseller sellerssetalamatalamat sellerssettelptelp sellerssetimageimage mapputtag id id mapputtag sellerseller mapputtag alamatalamat mapputtag telptelp namelistaddmap mgriddataaddsellers catchjsonexception e eprintstacktrace return null override protected void onpostexecutestring s pdialogthismiss recyclerviewadapter adapternew selleradaptergetactivitymgriddata ifsukses 1 mgridadaptersetgriddatamgriddata datasetadapteradapter else toastmaketextgetactivity error no data available toastlength shortshow and i get this in android monitor0504 2335874 56055668comamobilomapodfix durl 0504 2335878 56055605comamobilomapodfix wfragmentmanager movetostate fragment state for catfragmenta9c44708 1 id0x7f0d007e androidswitcher21315585261 not updated inline expected state 3 found 20504 2335938 56055605comamobilomapodfix wegl emulation eglsurfaceattrib not implemented0504 2335938 56055605comamobilomapodfix erecyclerview no adapter attached skipping layout0504 2335946 56055605comamobilomapodfix idalvikvm could not find method androidsupportv7widgetlinearlayoutcompatdrawablehotspotchanged referenced from method androidsupportdesigninternalforegroundlinearlayoutdrawablehotspotchanged0504 2335946 56055605comamobilomapodfix wdalvikvm vfy unable to resolve virtual method 15705 landroidsupportv7widgetlinearlayoutcompatdrawablehotspotchanged ffv0504 2335946 56055605comamobilomapodfix ddalvikvm vfy replacing opcode 0x6f at 0x0504 2335958 56055608comamobilomapodfix ddalvikvm gc concurrent freed 374k 8 free 55730k60500k paused 2ms1ms total 9ms0504 233556098 56055668comamobilomapodfix iinfo orgapachehttpclientmethodshttpgeta9c7a6680504 233556098 56055668comamobilomapodfix dsemuaa nama message1resultno telp08345678nama tokolomapodimage namenullid image1no rek12345emailid penjual1alamat tokojlbkotayogyakartanama bankbno telp0829417nama tokomeowimage namenullid image1no rek12345emailid penjual2alamat tokojlckotayogyakartanama bankbni0504 233556682 56055605comamobilomapodfix wegl emulation eglsurfaceattrib not implemented0504 233556702 56055605comamobilomapodfix ichoreographer skipped 42 frames the application may be doing too much work on its main thread0504 233556706 56055605comamobilomapodfix erecyclerview no adapter attached skipping layout0504 233556918 56055605comamobilomapodfix wsettings setting airplane mode on has moved from androidprovidersettingssystem to androidprovidersettingsglobal returning readonly value,"['java', 'android']" +1145010,tricky filling holes in an image i need to fill holes in images using pythonthis is the image with objects that i managed to get they are really edges of objects i want so i need to fill themit seemed very straightforward using ndimagebinary fill holesa but the problem is that it produces this manually filled with red colourbut i need thisany way this can be solvedthis is the first image without the axes if you want to give it a try,['python'] +1145302,angularjs event communication between directives with publishsubscribe i want to create a publishsubscribe mechanism with angular event system angularmoduleappangularmoduleappdirectivefirst functionrootscope return template first directive linkfunctionscopeelementattribute rootscopebroadcastonfirstdirectivecreated message i am first directive angularmoduleappdirectivesecond functionrootscope return template second directive linkfunctionscopeelementattribute var handler rootscopeononfirstdirectivecreated function event args consolelogfirst directive message argsmessage if i set html document like this no message appear in consolediv ngappapp firstfirst secondseconddivif i change order first and second message wirite on consolediv ngappapp secondsecond firstfirstdivbut i need first directive or inner directivediv ngappapp firstfirst secondseconddivdiv ngappapp first secondsecond firstdivi tried both rootscopebroadcast and rootscopeemit but did not woekedworking demo,['javascript'] +1145352,deferred and ajax reading a jsonservice like thisajax urlactiveids success functiondata data 1415 var tablerows for var dataindex0 dataindex datalength dataindex var islast dataindex datalength 1 ajax url infoid datadataindex success functiondata2 foo bar tablerowspushdata2name if islast alerttablerowslength first networktrace isactiveids 1415infoid14 takes 2 seconds fooinfoid15 takes 4 seconds barin this case the alert gives 2seconds networktrace is differentactiveids 1415infoid14 takes 20 seconds foo now takes very longinfoid15 takes 1 second barin this case the alert gives 1 after one second this is badquestionhow to use deferred instead of islast,['jquery'] +1145399,android mediastore query mediastoremediacolumnstitle column is null for some files i am making a query on the androids mediastore files database mediastorefilesgetcontenturiexternal and for some specific folders both the mediastoremediacolumnstitle and mediastoremediacolumnsthisplay name are null while for other folders this value exists i could not find any documentation about mediastoremediacolumnstitle being possibly nullthis happens for a few internal android directories such as these data storageemulated0music title null thisplay name null data storageemulated0notifications title null thisplay name null data storageemulated0pictures title null thisplay name nullhowever for some other folders the title is there data storageemulated0android title android thisplay name null data storageemulated0dcim title dcim thisplay name null data storageemulated0download title download thisplay name nullall data comes directly from the mediastore queryi am aware i could work directly with the data but i am trying to sort the query according to the title which leads to incorrect results given that some are nullis this an expected behaviour how to deal with it and retrieve all files correctly sorted by title,['android'] +1145873,pptx style inheritance does anyone know how character styles are inherited in a pptx file i know that it goes at least like thislocal run props arprlocal paragraph props appradefrprshape paragraph props alststylealvlxppradefrprparagraph props from layoutmaster slide paragraph props ptxstylesptitlestylepbodystylepotherstylealvlxppradefrprslide theme aobjectdefaultsaspdefalndefatxdefalststylealvlxppradefrprpresentation defaults pdefaulttextstylealvlxppradefrprbut when i compare it to the results of other applications it does not match due to technical reasons i cannot use a library that already does this for me i am reading the xml myself the apache poi source has some todo markings in the relevant areas and i am having trouble understanding the libreoffice codeedit to explain further i want to find the absolute run properties not the relative run properties on could think of it like this you have several transparencies for an overhead projector i want to see the image created from all of the pages not just the local one,['c#'] +1146049,how are external symbols resolved i have two files 37064544 p1cpp 37064544 p2cpp with the same content as shown below int addint xint yreturn xyi compiled them using g c 37064544 p2cpp o 37064544 p2og c 37064544 p2cpp o 37064544 p2oand added them to an archive using ar rsc lib37064544pfa 37064544 p1o 37064544 p2oand nm s lib37064544pfa gives me archive index z3addii in 37064544 p1o z3addii in 37064544 p2o37064544 p1o0 t z3addii37064544 p2o0 t z3addiiand ar t lib37064544pfa gives me37064544 p1o37064544 p2oi have a driver which calls the z3addii function which is compiled withg static 37064544drivercpp o 37064544driverelf l l37064544pfresult is sum 11questionshow is the symbol z3addii resolved is it according to archive indexis it according to the order in which we populate the archive using arhow can i change this orderhow can i prevent ar from having duplicate symbolscompiler g 463,['c++'] +1146229,routeparams in angular 2 rc1 i have been trying out angular 2 since beta and now with rc0 some things have changedone of those are routeparams which cannot be imported from angularrouter and when i try with angularrouterdeprecated i get an error messageoriginal exception no provider for routeparamsappcomponentroutes path component startcomponent path projidusername component projectlistcomponent path component startcomponent projectlistcomponentimport component oninit from angularcoreimport routeparams from angularrouterdeprecatedcomponent export class projectlistcomponent implements oninit usernamestring projidstring constructorprivate paramsrouteparams thisusername paramsgetusername thisprojid paramsgetprojid where can i import the routeparams from now or is it something else i am doing wrongthanks,['javascript'] +1146535,status of parallelization of pandasapply over the last several years there have been several posts related to the parallelization of pandasapply or posts that describe problems that could be solved by structuring the data as a dataframe and using pandasapply if parallelization was implemented my question to the community of experts here what is the status of this capability as r already has mclapply at the moment there is no clean standard solution it is incredibly tedious to recode entire functions and scripts to work with the proposed workarounds python pandas multiprocessing applyparallelize apply after pandas groupbyparallel and multicore processing in rpython multiprocessing poolmap for multiple argumentsparallel processing in pythonpassing kwargs with multiprocessingpoolmappassing arguments and managerdict to pool in multiprocessing in python 27is there a simple processbased parallel map for pythonpandas with rpy2 and multiprocessinghow to asynchronously apply function via spark to subsets of dataframeefficiently applying a function to a grouped pandas dataframe in parallelpython dask dataframe support for trivially parallelizable row applypython multiprocessing job to celery task but attributeerrorparallelizing apply function in pandas python worked on groupby,['python'] +1146768,tfshape get wrong shape in tensorflow i define a tensor like thisx tfget variablex 100but when i try to print shape of tensor print tfshapex i get tensorshape0 shape1 dtypeint32 why the result of output should not be shape100,['python'] +1147076,gulp git run first commit task then push task i am working on project and i want to commit and push on git using by gulp but i am facing some issue when i am running git task so push then task is not waiting for commitanyone can do my help i want to make the task like first run commit and then push automatically and do not run push task until complete commit taskgulp task for gulp git commit and pushvar gulp requiregulp runsequence requirerunsequence gutil requiregulputil git requiregulpgit prompt requiregulpprompt task to commit and push all file on git git commit task with gulp promptgulptaskgulpcommit function just source anything here we just want to call the prompt for now gulpsrc pipepromptprompt type input name commit message please enter commit message functionres now add all files that should be committed but make sure to exclude the gitignored ones since gulpgit tries to commit them too return gulpsrc node modules bufferfalse pipegitcommitrescommit run git push remote is the remote repo branch is the remote branch to push togulptaskgulppush gulpcommit functioncb gitpushorigin master cb functionerr if err throw err task completed notification with green colorgulptaskgulpdone gulppush function consolelog gutilloggutilcolorsgreen git push is done consolelog gulp task to commit and push data on gitgulptaskgit function runsequencegulpcommit gulppush gulpdone,['javascript'] +1147091,how can i design storage that conforms to the standards implementation of stdany the standard working draft n4582 2063 p552 states the following suggestion for implementations of stdanyimplementations should avoid the use of dynamically allocated memory for a small contained object example where the object constructed is holding only an int aend example such smallobject optimization shall only be applied to types t for which is nothrow move constructible v is trueas far as i know stdany can be easily implemented through type erasurevirtual functions and dynamically allocated memoryhow can stdany avoid dynamic allocation and still destroy such values if no compile time information is known at the time of destruction how would a solution that follows the standards suggestion be designedif anyone wants to see a possible implementation of the nondynamic part i have posted one on code review it is a little too long for an answer here it is based on the suggestions of kerrek sb on the comments below,['c++'] +1147257,alternative way for click i have been using click all the time through phantomjs engine on pageevaluate and it works just fine but sometimes it just does not work i do not know whyfor example i am trying to click the button verify herei tried this pageevaluatefunction documentgetelementbyidrecaptchaverifybuttonclickand this rect pageevaluatefunction return documentgetelementbyidrecaptchaverifybuttongetboundingclientrectconsolelogrectleft rectrightpagesendeventmousemove rectleft rectwidth 2 recttop rectheight 2pagesendeventmousedown rectleft rectwidth 2 recttop rectheight 2pagesendeventmouseup rectleft rectwidth 2 recttop rectheight 2both did not work there was no output after the click i tried the same on chrome though and it was the same any ideas or suggestions are appreciated,['javascript'] +1147416,why does assigning to nan or undefined cause a typeerror as the question is about type of error not about the phenomenonuse strict throws typeerror if system variables like nan and undefined got changedbut why is it a typeerror why not syntaxerroredit really it is not the syntaxerror here since there are no errors in syntax of the snippetbut the root of the error lies in the fact that some protected object cannot be changed manually so it is lkely the accesserror there are no such i knowthen why accesserrors appear like typeones,['javascript'] +1147428,aspnet core iis express how to view log mesages i am trying to print message vie the next ways consolewriteline hello world loggerfactoryminimumlevel logleveldebugloggerfactoryaddconsole logleveldebug var logger loggerfactorycreateloggerstartuploggerlogwarning hi but where can i see this messagesoutput window does not contain this messagesif i run project as web it run dnx console where i can see this messages but it is not convenientbut if i run project as iis express i do not see nor console nor messagesis there way to view this messages in visual studio,['asp.net'] +1147490,implementing an acquire for a release from unsafeputordered what do you think is the best correct way for implementing the acquire part of a releaseacquire pair in javai am trying to model some of the actions in an application of mine using classic releaseacquire semantics without storeload and without sequential consistency across threadsthere are a couple of ways to achieve the rough equivalent of a storerelease in the jdk javautilconcurrentatomiclazyset and the underlying sunmiscunsafeputordered are the most often cited approaches to do that however there is no obvious way to implement a loadacquirethe jdk apis which allow lazyset mostly use volatile variables internally so their storereleases are paired with volatile loads in theory volatile loads should be more expensive than loadacquires and should not provide anything more than a pure loadacquire in the context of a preceding storereleasesunmiscunsafe does not provide getacquire equivalents of the putordered methods even though such acquire methods are planned for the upcoming varhandles apisomething that sounds like it would work is a plain load followed by sunmiscunsafeloadfence it is somewhat thisconcerting that i have not seen this anywhere else this may be related to the fact that it is a pretty ugly hackps i understand well that these mechanisms are not covered by the jmm that they are not sufficient for maintaining sequential consistency and that the actions they create are not synchronization actions eg i understand that they for example break iriw i also understand that the storereleases provided by atomicunsafe are most often used either for eagerly nulling out references or in producerconsumer scenarios as an optimized message passing mechanism for some important index,['java'] +1147655,fade in each li one by one i want to fade each nav li one by one heres my current code it shows the whole div now i want to fade in each li one by one with a slight delay documentreadyfunction circlemenubtnclickfunction dropdownmenufadein500 div clasubmenu iddropdownmenu ul idnavbar li firstli lisecondli lithirdli lifourthli lififthli uldivsubmenu position absolute zindex 10 color f right 5px thisplay nonei tried for loops trying to fade in each li in one iteration but no success please share your ideasupdate rory mccrossans code is perfect unfortunately it is not compatible with my code that hides the menu when clicked outside it documentmouseupfunction e var container dropdownmenu if containerisetarget containerhasetargetlength 0 containerfadeout500 what went wrong i have just started to learn js and jquery so please forgive me if it is a lame question,"['javascript', 'jquery', 'html', 'css']" +1147678,are there any reasons why some methods in file uses boolean values to indicate its success instead of just throwing exceptions the file class in java contain methods that utilize boolean values to indicate the successfulness of the operation being carried out users of said methods are required to check the return value every time it is being calledbelow is the snippet of the documentations taken from mkdir stating the requirementpublic boolean mkdircreates the directory named by this file assuming its parents exist use mkdirs if you also want to create missing parentsnote that this method does not throw ioexception on failure callers must check the return valuethere is also a case with createnewfile which even weirder use both boolean values as well as thrown exceptions to indicate successfulnesspublic boolean createnewfile throws ioexception creates a new empty file on the file system according to the path information stored in this file this method returns true if it creates a file false if the file already existed note that it returns false even if the file is not a file because it is a directory saynote that this method does not throw ioexception if the file already exists even if it is not a regular file callers should always check the return value and may additionally want to call isfilenow this seems inconvenient at best because the user would have to anticipate two kind of error scenarios instead of just using a simple trycatch blockwhats the reason behind this fuss,['java'] +1147711,enabling strict types globally in php 7 i am currently migrating my website from php5 to php7 and i have started using the strict typing feature that was added however this requires me to begin all files with the following linephp declarestrict types1 all other code here so i was wondering is there any way to enable strict types globally using something like phpini or the apache configuration file so i do not have to write this line every time and if so how could i enable this,['php'] +1147951,avoiding const cast when calling stdsetfind is there any good way to obviate the const cast below while keeping const correctnesswithout const cast the code below does not compile setfind gets a const reference to the sets key type so in our case it guarantees not to change the passedin pointer value however nothing it guaranteed about not changing what the pointer points toclass c public stdsetint m set bool isptrinsetconst int ptr const return m setfindconst castintptr m setend,['c++'] +1148122,decide when to refresh oauth2 token with python social auth i believe this is mostly a question about best practicesi have an oauth2 provider that issues access tokens valid for 10 hours as long as refresh tokensi found here that it is pretty easy to refresh the access token but i cannot understand how to decide when it is time to refreshthe easy answer is probably when it does not work any more meaning when i get a http 401 from the backendthe problem with this solution is that it is not that efficient plus i can only assume i got a 401 because the token has expiredi my django app i found that the user social auth has an extra data field containing something like this scope read write expires 360 refresh token x access token x token type bearerbut i am not sure how to use the expires fieldso my question is how do i know if an access token has expired and i need to refresh itediti just found this comment that seems relevant but i cannot understand how to plug this new function in the pipeline in order to work during the token refresh,['python'] +1148170,java 8 omitting tedious collect method java 8 stream api is very nice feature and i absolutely like it one thing that gets on my nerves is that 90 of the time i want to have input as a collection and output as collections the consequence is i have to call stream and collect method all the timecollectionstreamfilterppiscorrectcollectcollectorstolistis there any java api that would let me skip the stream and directly operate on collections like linq in ccollectionfilterppiscorrect,['java'] +1148195,authentication with swift using joss i created an account jossmodelaccount in the configuration allowreauthenticatetruealmost immidiateley after account creation i callaccess maccess maccountauthenticate jossmodelaccessafter that i need to use the token i use it after 30 min and 15h and 24h etcby calling maccessgettoken token expatriation time is 1hcan i suppose that reauthentication will be performed and after 15h as well after 24 h the token will be valid or i need to reauthenticate manuallyie maccessgettoken will return invalid expired token after 15h and 24hhow to reauthenticate correctly in this case,['java'] +1148287,cordova wrapper app where internal links load in app external links load in browser i have a simple cordova wrapper app which points to an external webpage without defining any of its own viewsi would like all internal links from that domain to be loaded inside the app but all external links etc to be loaded in the system browser so the pages have back forward functionalityin a normal app with views i could set target system to load links in the default browser or use the cordovaplugininappbrowser to explicitly open links in a web browser view unfortunately in this case i do not have the ability to edit the server side code so need a solution that works within the appif i define the configxml as such then both internal and external links are loaded in appcontent src access origin allownavigation href if i define the configxml with allowintent then internal and external links are opened in the system browser content src access origin allownavigation href allowintent hrefhttp allowintent hrefhttps others have suggested using custom javascript to override the target to system however since i do not have my own views i cannot really do thatis it possible to define allowintent for the cordovapluginwhitelist in such a way to include all urls that are not the internal domainor will i need to somehow override shouldstartloadwithrequest in mainviewcontroller and then call uiapplication sharedapplication openurlurl,"['javascript', 'android', 'ios']" +1148330,aws s3 integration yields undefined method match i am working on a simple project using paperclip to upload images everything has been working just fine until i attempted to integrate s3 with paperclip upon uploading a users image i get a nomethoderror undefined method match for nilnilclass error this only happens when i have my s3 configuration running if i comment it out the file uploads perfectly my configurationdevelopmentrb configpaperclip defaults storage s3 s3 credentials bucket envaws bucket id access key id envaws access key id secret access key envaws secret access key my model class user activerecordbase has attached file image file default url myappimagesstylemissingpng validates attachment file name image file matches pngz jpegz tiffz bmpz jpgzentire error output from consolenomethoderror undefined method match for nilnilclass appcontrollersimages controllerrb33in block in create appcontrollersimages controllerrb32in createthings i triedi added the aws keys and bucket name directly into the code insteadof as an environmental variableas mentioned above i commented out the aws configuration in my environment file and it seemed to work perfectlyit is probably worth mentioning that i installed the fog gem earlier to start configuring for google cloud storage but decided to stick with s3 instead i used gem uninstall fog to remove the gem but it appears some dependencies stayed behind,['ruby-on-rails'] +1148448,duplicate entry comandroidvolleyauthfailureerrorclass while compiling project in android studio i am using external libraries payu money sdk and linkedinsdk both uses volley libraries which while compiling project gives duplicate entry of authfailureerrorclasserrorexecution failed for task apackagealldebugclassesformultidexjavautilzipzipexception duplicate entry comandroidvolleyauthfailureerrorclassi have also added following code to exclude module but still same errorconfigurations allexclude module comandroidvolleyplease help,['android'] +1148539,what is the correct way to report an error in a python unittest in the setup method i have read some conflicting advice on the use of assert in the setup method of a python unit test i cannot see the harm in failing a test if a precondition that test relies on fails for exampleimport unittestclass myprocessor this is the class under test def init self pass def processdataself content return someprocesseddatafromcontent imagine this could actually passclass test test2unittesttestcase def loadcontentfromtestfileself return none imagine this is actually doing something that could pass def setupself selfcontent selfloadcontentfromtestfile selfassertisnotnoneselfcontent failed to load test data selfprocessor myprocessor def test processdataself results selfprocessorprocessdataselfcontent selfassertgreaterresults 0 no results returnedif name main unittestmainthis seems like a reasonable thing to do to me ie make sure the test is able to run when this fails because of the setup condition we getffail test processdata main test test2traceback most recent call last file cprojectsexperimentstest2py line 21 in setup selfassertisnotnoneselfcontent failed to load test dataassertionerror unexpectedly none failed to load test dataran 1 test in 0sfailed failures1,['python'] +1148991,postlink of an angular componentdirective running too early update i put a bounty on this question i am not looking for hacks or workarounds i am looking for an official way to access the dom in an angular component and an explanation why the behavior i see postlink running to early seems to be contradictory to the official docsthe official docs state herepostlink called after this controllers element and its children have been linked similar to the postlink function this hook can be used to set up dom event handlers and do direct dom manipulationoriginal question i have an example of the problem here i am using an angular component and i want to modify the dom in the post link function but it does not work it seems that the function runs too early before the template is actually ready in the dom after all the angular processingin the html page i have thismygrid grididfoomygridthe component is defined asappmodulecomponentmygrid controller gridcontroller bindings gridid templateurl gridtemplatein the component template i have thistable idctrlgrididthe binding itself works there is no doubt eventually in the html the id of the table is foo as expectedin the controller i have something like thisfunction gridcontrollerscope compile attrs consolelog grid id is thisgridid foo thispostlink function var elem documentgetelementbyidthisgridid do something with elem but elem is null what i see when debugging is that when the postlink function is executed the table is in the dom but its id attribute is still ctrlgridid instead of foo so documentgetelementbyid finds nothing this seems in contrast to the documentationwhat am i missing is there a different way to access the dom in the componentupdate 2 today i realized the same problem occurs with the regular link function of directives it is not limited to components so apparently i misunderstood the meaning of do direct dom manipulation the link function runs on an element that is detached from the dom so using the document object with selectors is useless,['javascript'] +1149092,html5 audio timeupdate precision i am working with html5 audio for my usecase i need to listen on the audio duration played and once it crosses a certain threshold pause the audio so something likeaudiobindtimeupdate function if audiocurrenttime 10 audiopause what i am noticing is that by the time my handler executes audiocurrenttime is around 1012878 1034023 etc and hence some little extra audio is played before it is pausedanother question seems to have documented the same issuethe question is dated in 2012 so i am wondering if the state of the art has improved if not what other ways exist to do this with more precision i have not worked with audio much before and i would really appreciate the help,['javascript'] +1149234,writing my own shell how implement command history as an exercise in understanding my computer better and as a tool i am writing my own shell in c stephen brennans article on writing a simple shell was very helpfulhowever what has me flummoxed is how to handle pressing uparrow and downarrow to scroll through my command historyi tried ncurses but that replaces the entire screen whereas the systemprovided shell seems to just continue writing into the terminali tried using tcgetattr to turn off canonical mode but while that lets me get arrow key presses as they are typed it also turns off all processing of leftright arrow keys for text navigation and the backspace key and ctrlc while i could probably send a signal myself in response to ctrc i have no idea how to get the terminal to move the cursor back apart from outputting a return and rewriting the start of the line it also seems to give me different escape sequences for the keys depending on whether i am running in xcodes dumb terminal or in my macs terminalappi looked at the sources for fish shell and bash but there just seems to be so much going on that i cannot find the relevant partshow do the standard shells handle receiving keypresses how do they handle moving the cursor and doing backspace how do they rewrite parts of a line without having to take over the screen is there a standard somewhere that defines what a shell needs to dops i know how to record the previous commands it is the actually getting the keypresses while they are being typed as opposed to after someone presses return that i cannot get to work,['c++'] +1149261,what does intbuffer mean in a c code i am reading found the followingcan anyone help me understand what does the following statements dochar buffer4096 some codeint size intbuffer,"['c++', 'c']" +1149271,bootstrap3 mega menu change drop down width i like to know how can i change the bootstrap mega menu drop down size to fit the bootstrap container width i have attached a image below for better understanding of what i would like to doboostrap mega menu html codenav classnavbar navbardefault navbarfixedtop div classcontainer div classnavbarheader button typebutton classnavbartoggle datatogglecollapse datatargetnavbarcollapse span classiconbarspan span classiconbarspan span classiconbarspan button a classnavbarbrand hreflogoa div div classnavbarcollapse collapse ul classnav navbarnav lia hrefhomeali li classdropdown menularge a href classdropdowntoggle datatoggledropdown product listing b classcaretb a ul classdropdownmenu megamenu row li div classcolsm6 colmd3 a href classthumbnail img src a div div classcolsm6 colmd3 a href classthumbnail img src a div div classcolsm6 colmd3 a href classthumbnail img src a div div classcolsm6 colmd3 a href classthumbnail img src a div li ul li li classdropdown menularge a href classdropdowntoggle datatoggledropdowncategories b classcaretba ul classdropdownmenu megamenu row li classcolsm3 ul li classdropdownheaderglyphiconsli lia hrefavailable glyphsali li classthisableda hrefhow to useali lia hrefexamplesali li classdividerli li classdropdownheaderdropdownsli lia hrefexampleali lia hrefaligninment optionsali lia hrefheadersali lia hrefthisabled menu itemsali ul li li classcolsm3 ul li classdropdownheaderbutton groupsli lia hrefbasic exampleali lia hrefbutton toolbarali lia hrefsizingali lia hrefnestingali lia hrefvertical variationali li classdividerli li classdropdownheaderbutton dropdownsli lia hrefsingle button dropdownsali ul li li classcolsm3 ul li classdropdownheaderinput groupsli lia hrefbasic exampleali lia hrefsizingali lia hrefcheckboxes and radio addonsali li classdividerli li classdropdownheadernavsli lia hreftabsali lia hrefpillsali lia hrefjustifiedali ul li li classcolsm3 ul li classdropdownheadernavbarli lia hrefdefault navbarali lia hrefbuttonsali lia hreftextali lia hrefnonnav linksali lia hrefcomponent alignmentali lia hreffixed to topali lia hreffixed to bottomali lia hrefstatic topali lia hrefinverted navbarali ul li ul li ul div div navcss code belowmenularge position static importantmegamenu padding 20px 0px width100megamenu li ul padding 0 margin 0megamenu li ul li liststyle nonemegamenu li ul li a thisplay block padding 3px 20px clear both fontweight normal lineheight 1428571429 color 3 whitespace normalmegamenu li ul li ahovermegamenu li ul li afocus textdecoration none color 262626 backgroundcolor f5f5f5megamenuthisabled amegamenuthisabled ahovermegamenuthisabled afocus color 9megamenuthisabled ahovermegamenuthisabled afocus textdecoration none backgroundcolor transparent backgroundimage none filter progiddximagetransformmicrosoftgradientenabled false cursor notallowedmegamenudropdownheader color 428bca fontsize 18pxi did add a container class after navbar navbardefault navbarfixedtop but this container does not apply the changes to drop down menujsfiddleplease take a look at the jsfiddle belowany help would be appropriated,"['javascript', 'jquery', 'html', 'css']" +1149354,sql delete table with 372 million rows starting from first row i have a table with 372 million rows i want to delete old rows starting from the first ones without blocking the db how can i reach thatthe table haveid memberid type timestamp message 1 123 10 20140326 1317020 textupdatei deleted about 30 gb of space in db but my thisc is on 6gb space yetany suggestion to get that free spacethank you in advance,['sql'] +1149452,css3 animation image quality on scale i have downscaled images that onclick scale to the images original size the image quality is very poor when the images are in a scaled down state any way to improve thishere is a jsfiddle documentreadyfunction var zoomed false var card card0 cardclickfunction zoomfunction function zoomfunction if zoomed card flipped so front is invisible and back is visible zoomed false cardremoveclasszoom else card not flipped so front is visible and back is invisible zoomed true cardaddclasszoom html height 100zoom transform scale10img transform scale05 transformstyle preserve3d transition 1simg idcard0 src,"['javascript', 'jquery', 'html', 'css']" +1149505,merging 2 lists in multiple ways python i have been experimenting with a number of techniques but i am sure there is smoothish way to get this donesuppose i have two lists with the same amount of items in them 4 eacha a b c d b 1 2 3 4i would like to merge these lists in all possible ways while retaining order example outputsa b c d 1 2 3 4 1 2 3 4 a b c d a b 1 2 c 3 4 dthe point is each of the lists must retain its order so an item can not precede another item in the output considering its position in the list so for example the output can not bea b d c 1 d precedes c whereas c is before d in the original list1 4 a b 3 4 precedes 3 whereas 3 is before 4 in the original listi guess the idea is to merge the second list into the first list in all possible ways a fully worked example is thisa a b b 1 2desired outputab12 a1b2 a12b 1ab2 1a2b 12abhow do i go about doing this does itertools have a capability to do this in some way or is there another way to get this done please help,['python'] +1149514,java restful web service running only android 44 mobile not other i build a java restfull web service to be called by ionic apps running on android mobil devicesthe code is successfully running on android 44 mobilebut not running on any other android mobile devices with os android lollipop marshmallowwebservices webxmlxml version10 encodingutf8webapp xmlnsxsi xmlns xsischemalocation 3 1xsd idwebapp id version31 thisplaynametestthisplayname servlet servletnamejersey rest serviceservletname servletclasscomsunjerseyserverimplcontainerservletservletadaptorservletclass servletclasscomsunjerseyspicontainerservletservletcontainerservletclass initparam paramnamecomsunjerseyconfigpropertypackagesparamname paramvaluetestparamvalue initparam loadonstartup1loadonstartup servlet servletmapping servletnamejersey rest serviceservletname urlpatternurlpattern servletmappingwebapprest webservice codepackage testimport javaxwsrsconsumesimport javaxwsrspostimport javaxwsrspathpathtestpublic class test services post consumesapplicationxwformurlencoded pathinserttest public string insertteststring json systemoutprintlnpost jsonjson return jsontostring rest webservice dependencieshere is hybride application using ionic and angularjs codehttp method post url data data headers contenttype applicationxwformurlencoded thenfunction successcallbackres function errorcallbackerr deferredrejectreserr when i debug that using chrome on android lollipop and marshmallow it gives me the following errorfailed to load resource neterr name not resolvedplease help me to fix this issuei am using java using eclipse mars1,"['java', 'android']" +1149688,pygame allow clicks to go through the window i am making a pseudo transparent window in pygame with the intent of thisplaying varied info like a hudthe script uses pil to grab an image of the desktop and use it as the background of the windowa simple versionimport pygame as pyfrom ctypes import windllimport imagegrab imagesetwindowpos windlluser32setwindowpospyinitdef get image im imagegrabgrab00window xwindow y mode immode size imsize data imtobytes im pyimagefromstringdatasizemode return imwindow x 1920window y 100background pysurfacewindow xwindow ybackgroundblitget image00window pos 00screen pythisplayset modewindow xwindow ypyhwsurfacepynoframesetwindowpospythisplayget wm infowindow10x01clock pytimeclockdone falsewhile not done for event in pyeventget if eventtype pyquit done true screenblitbackground00 pythisplayflip clocktick30pyquitthis creates a pygame window at the top of the screenmy problem is that the pygame window blocks any mouse interaction with anything beneath itis there a way to allow mouse events to be ignored and go through the window like for example clicking on a desktop icon underneath a pygame window,['python'] +1150420,two divs sharing one border and hoverafter bug i need four boxes in the corners of the div when hovering on some div i want to thisplayblock a hidden div in the middle sharing one border with the box being currently hoveredhere is jsfiddle with my current solutionit almost works fine however there are some bugs regarding the corner area i thisplay there the block element with background using after it is to achieve the effect of one border for two elementsthe problem so in chrome hovering that area gives some strange interlacing effect each mouse movement by 1px hides and shows content div you can see it here in action in newest firefox it seems to be ok but in created jsfiddle there is some other bug which you can test yourself i am using grey background just for better visualization of the problem it is also suppose to work for box 1 for now tried some jquery with mouseover and hover with no successedit final solutionthe most important thing was to set pointerevents none to after block element since i got some votes up heres more advanced code on jsfiddle using sass and heres using plain csscssouter width 90 height 300px position relativeboxcontent thisplay none width 80 height 80 position absolute left 10 top 13 background white zindex 1box width 150px height 60px position absolute border 1px solid white background whiteboxhoverafter content backgroundcolor white zindex 2 position absolute width 100 height 100 left 0 top 0boxhover p zindex 3box p position absolute top 23px left 13px color black padding 0 margin 0boxone top 0 left 0boxonehover border 1px solid blueboxonehover contentone border 1px solid blue thisplay inlineblock pointerevents noneboxtwo top 0 right 0boxtwohover border 1px solid redboxtwohover contenttwo border 1px solid red thisplay inlineblock pointerevents noneboxthree bottom 0 left 0boxthreehover border 1px solid yellowboxthreehover contentthree border 1px solid yellow thisplay inlineblock pointerevents noneboxfour bottom 0 right 0boxfourhover border 1px solid greenboxfourhover contentfour border 1px solid green thisplay inlineblock pointerevents nonehtmldiv classouter div classbox boxone pbox name 1p div div classbox boxtwo pbox name 2p div div classbox boxthree pbox name 3p div div classbox boxfour pbox name 4p div div classboxcontent contentonediv div classboxcontent contenttwodiv div classboxcontent contentthreediv div classboxcontent contentfourdivdiv,['css'] +1150429,how to setup materialui for react with typescript i have run in some problems add material ui to my react project which is programmed with typescriptaccording to the tutorial i start with adding the reacttabeventplugin firstimport injecttapeventplugin from reacttapeventplugin needed for ontouchtap can go away when react 10 release check this repo injecttapeventplugindoing this i get an error about the missing default exporterror in srcindextsx48 error ts1192 module reacttapeventplugin has no default exportadding material uiimport getmuitheme from materialuistylesgetmuithemeimport muithemeprovider from materialuistylesmuithemeproviderthrows following build errorerror in srccontainersindextsx825 error ts2307 cannot find module materialuistylesgetmuithemeerror in srccontainersindextsx930 error ts2307 cannot find module materialuistylesmuithemeprovidermy webpack config is quite easy and did work with every react npm modul when i added the typings until nowvar cssnext requirepostcsscssnextvar postcssimport requirepostcssimportvar extracttextplugin requireextracttextwebpackplugin noinspection jsunresolvedvariablemoduleexports entry app srcindextsx lib node modulesreactreactjs node modulesreactdom node modulesnormalizecssnormalizecss output path thist filename namejs devtool sourcemap devserver contentbase thist inline true port 3 host 0 resolve add ts and tsx as a resolvable extension extensions webpackjs webjs ts tsx js css html modulesdirectories src node modules module loaders all files with a ts or tsx extension will be handled by tsloader test tsx loader babelloadertsloader test html loader filenamenameext test json loader json test css loader extracttextpluginextractstyleloader cssloaderpostcssloader preloaders all output js files will have any sourcemaps reprocessed by sourcemaploader test js loader sourcemaploader loaders test js exclude node modules loader babelloadertsloader query presets es2015 react plugins new extracttextpluginnamecss allchunks true postcss function webpack return postcssimport adependencyto webpack cssnext browsers last 2 versions ie 9 when importing a module whose path matches one of the following just assume a corresponding global variable exists and use that instead this is important because it allows us to avoid bundling all of our dependencies which allows browsers to cache those libraries between builds externals react react reactdom reactdom typing for both reacttapeventplugin and materialui are installedwhats wrong,['javascript'] +1150534,how would one create a dynamic html table from a one dimensional array taking into account rowspan and colspan i need to construct a html table from a one dimensional array which for abstractions sake has the following format value abc colspan 1 rowspan 2 etcthere is also a property called width which will be dynamic and represent the number of columns the code below i believe is close and can handle nonrowspan data but i am getting tripped up on how to account for cells spanning without the table exceeding the column count i feel like i need a stepper which counts up and down everytime there is a rowspan but i cannot get the maths correct at the moment any rowspan causes the next row to exit the right of the table essentially i would like it to wrap and drop each one in the next available spot in otherwords assmeble the table dynamically round 1 not workingconst input value a1 colspan 1 rowspan 1 value a2 colspan 1 rowspan 1 value a3 colspan 1 rowspan 3 value b1 colspan 1 rowspan 1 value b2 colspan 1 rowspan 1 value c1 colspan 1 rowspan 1 value c2 colspan 1 rowspan 2 value d1 colspan 1 rowspan 1 value d3 colspan 1 rowspan 1 value e1 colspan 1 rowspan 1 value e2 colspan 2 rowspan 1 const width 3const trs let tds let rowspanoffset 0 loops over entriesinputforeachcell index stock standard td tdspushtd colspancellcolspan rowspancellrowspancellvaluetd new row time ifindex width width 1 rowspanoffset 0 trspushtr tdsjoin tr reset for next row tds const letable table classtabletrsjointablebodyappendletableround 2 improved but assumes input is validconst input value a1 colspan 1 rowspan 1 1 value a2 colspan 1 rowspan 1 2 value a3 colspan 1 rowspan 3 3 value b1 colspan 1 rowspan 1 1 value b2 colspan 1 rowspan 1 1 value c1 colspan 1 rowspan 1 1 value c2 colspan 1 rowspan 2 2 value d1 colspan 1 rowspan 1 1 value d3 colspan 1 rowspan 1 1 value e1 colspan 1 rowspan 1 1 value e2 colspan 1 rowspan 1 2const width 3const totalcellcount reduceinput sum c sum ccolspan crowspan 0const grid chunk fillnew arraytotalcellcount 1 width eachinput cell let start 1 1 outerloop forlet y 0 y gridlength y forlet x 0 x width x ifgridyx 1 start x y break outerloop forlet y 0 y cellrowspan y forlet x 0 x cellcolspan x gridstart1 ystart0 x null gridstart1start0 cell let trs let tds forlet y 0 y gridlength y forlet x 0 x gridylength x const cell gridyx ifcell const value cellvalue tdspushtd colspancellcolspan rowspancellrowspancellvaluetd trspushtrtdsjointr tds tableappendtrsjoinedit bad inputan example of bad input would be splitting cellsconst input value a1 colspan 1 rowspan 1 value a2 colspan 1 rowspan 2 value a3 colspan 1 rowspan 1 value b1 colspan 3 rowspan 1 const width 3,"['javascript', 'jquery', 'html']" +1150549,string object with fixed length c i have a class wherein i want to use strings with a fixed sizethe reason for the fixed size is that the class serializes into a textfilewith values with a fixed length i want to avoid to write foreach value a guard clause and instead have the class handle thisso i have round about 30 properties which would look like this public string companynumber get return m companynumberpadleft5 set if valuelength 5 throw new stringtolongexceptionthe companynumber may only have 5 characters companynumber m companynumber value i would like to have a string that handles this by itself currently i have the followingpublic class fixedstring string m fixedstring public fixedstringstring value if valuelength 5 throw new stringtolongexceptionthe fixedstring value may consist of 5 characters value m fixedstring value public static implicit operator fixedstringstring value fixedstring fsv new fixedstringvalue return fsv public override string tostring return m fixedstringpadleft5 the problem i have with this solution is that i cannot set the string length at compile timeit would be ideal if it would look something like this in the endpublic fixedstring5 companynumber get set,"['c#', '.net']" +1150596,logo on every javadoc page i need to put a corporate logo at the top of every javadoc page i am trying to use the top option but do not know how to code the image path the path is always relative to the package subdirectory i do not want to put the same image file in every package subdirectoryjavadoc top is what i have tried but the image which is in the root of the javadoc tree only shows up on the index pageedit unfortunately this is going to be thistributed as a zip and we would not be able to access the logo via a url,['java'] +1150671,cannibalizing just some of the resources of an rvalue ref my intent is the following receive a rvalue reference ie a reference to an object i want to cannibalize remove some of its resources and then return the other resources i wrote this codestdvectorint dosomethingstdvectorint vec do something with vec eg consume some of its resources return stdmovevecbut i am not sure ifis this the correct way to achieve what i wantshould i use stdforward i believe not since this is no universal reference,['c++'] +1150681,precompile aspnet mvc views on azure web app is there a way to precompile the aspnet mvc views on an azure web app specifically when published via release management on vstsonce each view has been hit once the page subsequently renders very quickly but that first delay can be a doozy for users and there is no way to script touching each page i am not sure if i need to change something in the buildrelease processes on vsts i am using the visual studio build build step and the azure web app release task or if i need to run something on the azure web app instance after it is released or something else altogetherit seems like finding some way to call aspnet compiler after publish might be what i need and i have seen that in reference to web roles on cloud services but i cannot get that to work calling windirmicrosoftnetframeworkv4030319aspnet compiler v p dhomesitewroot via the console in the azure portal executes just fine and finds errors if there are any but does not have any impact on startup time hitting a view the first time still takes a long time so maybe that is not the right directioni have looked at razorgenerator including the msbuild nuget package and i could not quite get it to work but really i was hesitant to make so many changes to the projects just to get precompilation on releasealso note that i am currently using tfvc not git in vsts so the kudugit integration that does seem to trigger the precompilation according to some articles is not available to me as far as i can tellother ideas,['asp.net'] +1150711,refreshing googlemaps tile server works in javascript but not in gwt i am thisplaying a weather map in a gwt application i am using gwt 27 and the gwt wrapper of the googlemaps javascript api available here gwtmaps380pre1zipi use a tile server to fetch the weather which updates every 5 minutes on the 5 minute mark i refresh the map by setting the zoom to 1 and then back to the original by triggering a resize and by removing and then adding the weather layer againthis worked fine however recently i noticed that this no longer works the refresh never even goes to the tile server so no new weather is thisplayed if you leave my map up for 12 hours youll be looking at weather that is 12 hours old previously the map would automatically stay updated i have not changed any of my code so my guess is that something changed in the underlying googlemaps javascript apihowever i then created this simple purejavascript exampledoctype htmlhtml head titlemap testtitle style typetextcss html body height 100 margin 0 padding 0 map width90 height 90 thisplayinlineblock style headbodydiv idmapdivbutton typebutton onclickrefreshmaprefreshbuttonscript typetextjavascript var map var tilenex function initmap var mapoptions zoom 8 center new googlemapslatlng425 955 maptypeid googlemapsmaptypeidroadmap map new googlemapsmapdocumentgetelementbyidmap mapoptions tilenex new googlemapsimagemaptype gettileurl functiontile zoom return zoom tilex tiley png new dategettime tilesize new googlemapssize256 256 opacity060 name nexrad ispng true mapoverlaymaptypessetat0tilenex function refreshmap var zoom mapgetzoom mapsetzoom1 mapsetzoomzoom googlemapseventtriggermap resize var layer mapoverlaymaptypesgetat0 mapoverlaymaptypessetat0 null mapoverlaymaptypessetat0 layer scriptscript async defer srcscriptbodyhtmlto my surprise this still works fine whenever you click the refresh button the map goes to the tile server and fetches new tilesso i tried doing the exact same thing in gwtpackage comexampleclientimport comgooglegwtajaxloaderclientajaxloaderimport comgooglegwtajaxloaderclientajaxloaderajaxloaderoptionsimport comgooglegwtcorecliententrypointimport comgooglegwtdomclientdocumentimport comgooglegwteventdomclientclickeventimport comgooglegwteventdomclientclickhandlerimport comgooglegwtuserclientuibuttonimport comgooglegwtuserclientuirootpanelimport comgooglemapsgwtclientgooglemapimport comgooglemapsgwtclientlatlngimport comgooglemapsgwtclientmapoptionsimport comgooglemapsgwtclientmaptypeimport comgooglemapsgwtclientmaptypeidpublic class gwtmaptest implements entrypoint override public void onmoduleload ajaxloaderoptions options ajaxloaderoptionsnewinstance optionssetotherparmssensorfalse runnable callback new runnable public void run createmap ajaxloaderloadapimaps 3 callback options public void createmap mapoptions mapopts mapoptionscreate mapoptssetzoom4 mapoptssetcenterlatlngcreate3709024 95712891 mapoptssetmaptypeidmaptypeidterrain mapoptssetstreetviewcontrolfalse final googlemap map googlemapcreatedocumentgetgetelementbyidmap canvas mapopts addweatherlayermap button button new buttongwt refresh buttonaddclickhandlernew clickhandler override public void onclickclickevent event refreshweatherlayermap button nativebutton new buttonnative refresh nativebuttonaddclickhandlernew clickhandler override public void onclickclickevent event nativerefreshweatherlayermap rootpanelgetaddbutton rootpanelgetaddnativebutton public native void addweatherlayergooglemap map var imagemaptype new wndgooglemapsimagemaptype gettileurl functioncoord zoom return zoom coordx coordy png tilesize new wndgooglemapssize256 256 opacity50 ispng true mapoverlaymaptypessetat0 imagemaptype private void refreshweatherlayergooglemap map double zoom mapgetzoom mapsetzoom1 mapsetzoomzoom maptype layer mapgetoverlaymaptypesgetat0 mapgetoverlaymaptypessetat0 null mapgetoverlaymaptypessetat0 layer private native void nativerefreshweatherlayergooglemap map var zoom mapgetzoom mapsetzoom1 mapsetzoomzoom wndgooglemapseventtriggermap resize var layer mapoverlaymaptypesgetat0 mapoverlaymaptypessetat0 null mapoverlaymaptypessetat0 layer this should do the same thing as the purejavascript example instead when i click the button the map does refresh i see the weather layer blink but it does not actually go to the tile server for new tilesweirder still this sorta works in internet explorer maybe 1 out of 3 times i click the button the map actually goes to the tile server but in chrome it never goes to the tile server when i click the buttonto determine this i am looking at the network tab of the browser tools i would expect the map to hit the tile server every time i click the button that is what it does in pure javascript and that is what it used to do in gwt but sometime in the last couple months the gwt behavior has changedi do not think this is a browser caching issue the problem is not that the map tries to fetch new tiles but gets old ones it is that it never tries to fetch new tiles i click the button and i see nothing happening in the network tab of the developer toolswhy do i see a different behavior in javascript vs gwtwhy do i see a different behavior in different browsersis the gwt googlemaps library doing some kind of internal caching is there a way to thisable thiswhy has this behavior apparently changedhow can i make the gwt map refresh by going to the tile server for new tiles,"['javascript', 'java']" +1150900,android btle cannot find callback wrapper i am using android beacon library in my app and i copied word for word their example for ranging but i keep getting the error you see below the code any help would be greatly appreciated i am just now getting into btlebeaconspackage comexamplejoshbeaconsimport androidosbundleimport androidosremoteexceptionimport androidsupportv7appappcompatactivityimport androidutillogimport orgaltbeaconbeaconbeaconimport orgaltbeaconbeaconbeaconconsumerimport orgaltbeaconbeaconbeaconmanagerimport orgaltbeaconbeaconbeaconparserimport orgaltbeaconbeaconrangenotifierimport orgaltbeaconbeaconregionimport javautilcollectionpublic class mainactivity extends appcompatactivity implements beaconconsumer protected static final string tag rangingactivity private beaconmanager beaconmanager override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main beaconmanager beaconmanagergetinstanceforapplicationthis beaconmanagergetbeaconparsersaddnew beaconparsersetbeaconlayoutm23beaci419i2021i23p2424d2525 beaconmanagerbindthis override protected void ondestroy superondestroy beaconmanagerunbindthis override public void onbeaconserviceconnect beaconmanagersetrangenotifiernew rangenotifier override public void didrangebeaconsinregioncollectionbeacon beacons region region if beaconssize 0 logitag the first beacon i see is about beaconsiteratornextgetthistance meters away try beaconmanagerstartrangingbeaconsinregionnew regionmyranginguniqueid null null null catch remoteexception e errors i get0512 202144769 2577525775comexamplejoshbeacons dbluetoothadapter state on0512 202144770 2577525775comexamplejoshbeacons dbluetoothlescanner could not find callback wrapper0512 202144787 2577526783comexamplejoshbeacons drangingactivity didrangebeacons 0,['android'] +1151162,how to return the multiple lists from controller action to ajax success call back function i am creating a mvc net project in which i have the jquery ajax request is as followsajax url urlactiongetdata seatplans data seat plane id 17 type post datatype json success function data loaddatadata error function alertfailed please try again which call the following controller actionpublic jsonresult getdataint seat plane id int lid seat plane id listseatplans alluser new listseatplans alluser dbseatplanwhered dlayout id lidtolist lid listseatplans alluser1 new listseatplans alluser1 dbseatplanwhered dlayout id lidtolist return new jsonresult data alluserjsonrequestbehavior jsonrequestbehaviorallowget the code is working fine the controller action send the data in alluser to callback functionbut what i need is that i want to send both data in alluser and alluser1 to the success function of ajax call,"['javascript', 'c#']" +1151194,how to get the print as pdf result using jquery i would like to get the html page in the pdfafter some studies i found the pdfjs plugin it has some problem with bootstrap the layout will be messyhere is the fiddlei found the default print as pdf result is great var doc new jspdfvar specialelementhandlers editor function element renderer return true cmdclickfunction docfromhtmlcontenthtml 15 15 width 170 elementhandlers specialelementhandlers docsavesamplefilepdfso instead of fixing the problem for pdfjs i wonder are there html jquery way to get the pdf from the print as pdfthe html need to convert to pdf is one page application form only thanks a lot,"['javascript', 'jquery', 'html', 'css']" +1151252,cannot init an object in jquery documentready i have an javascript object named conceptfunction concept thisconceptid 0 thisname i am trying to initiate it in jquery documentreadydocumentreadyfunction var concept new conceptit returns an error uncaught typeerror concept is not a constructorif i move the object inside the documentready it is workingdocumentreadyfunction function concept thisconceptid 0 thisname var concept new concepti am still new on javascript as far as i understood documentready is run when dom is completed i do not understand why it cannot access the object which is defined out of the documentready scopehere it is the fiddle,"['javascript', 'jquery']" +1151399,make a custom ring chart in jfreechart i am currently using itextpdf to generate pdfs in addition to that i am also using jfreechart to create charts on it i have created a donut chart with a explosion effect and it looks like thishowever i want to create a donut chart that looks more like thisi want certain pieces to stand out but not completely get detached from the donut chart i would highly appreciate inputs on how to achieve thishere is my current code import javaawtcolorimport javaawtgraphics2dimport javaawtgeomrectangle2dimport javaiofileoutputstreamimport javaioioexceptionimport javatextdecimalformatimport javautillocaleimport orgjfreechartchartfactoryimport orgjfreechartjfreechartimport orgjfreechartlabelsstandardpiesectionlabelgeneratorimport orgjfreechartplotpieplotstateimport orgjfreechartplotringplotimport orgjfreedatageneraldefaultpiedatasetimport orgjfreeuirectangleinsetsimport comitextpdfawtdefaultfontmapperimport comitextpdftextbasecolorimport comitextpdftextdocumentimport comitextpdftextdocumentexceptionimport comitextpdftextelementimport comitextpdftextfontimport comitextpdftextpagesizeimport comitextpdftextphraseimport comitextpdftextpdfbasefontimport comitextpdftextpdfcolumntextimport comitextpdftextpdfpdfcontentbyteimport comitextpdftextpdfpdftemplateimport comitextpdftextpdfpdfwriterpublic class ringcharttest public static void mainstring args throws exception new ringcharttestcreatepdf private void createpdf throws exception string destination ringchartpdf document document new documentpagesizea4rotate try pdfwriter writer pdfwritergetinstancedocument new fileoutputstreamdestination documentopen create the pages pdfcontentbyte cb writergetdirectcontent addchartcb catch exception e systemoutprintlnfailure to generate the pdf eprintstacktrace finally if document null documentclose private void addchartpdfcontentbyte cb throws exception ioexception long pctpm mathround20 long pctoa mathround15 long pctwpi mathround5 long pcttdf mathround25 long pctne 100 pctpm pctoa pctwpi pcttdf long pctengaged pctpm pctoa pctwpi long numengaged 3400 string strnumengaged formatnumbernumengaged 0 jfreechart chart createchartpctpm pctoa pctwpi pcttdf pctne int width 300 int height 200 pdftemplate template cbcreatetemplatewidth height graphics2d graphics2d templatecreategraphicswidth height new defaultfontmapper rectangle2d rectangle2d new rectangle2ddouble0 0 width height chartdrawgraphics2d rectangle2d graphics2dthispose cbaddtemplatetemplate 30 185 add text inside chart font engagementfont createfontopensansboldttf 8 116 112 100 font percentfont1 createfontopensanslightf 22 116 112 100 font percentfont2 createfontopensanslightf 10 116 112 100 font numberfont createfontopensansregularttf 8 116 112 100 addphrasecb engage engagementfont 135 290 230 310 10 elementalign center addphrasecb stringvalueofpctengaged percentfont1 115 270 190 289 10 elementalign right addphrasecb percentfont2 191 275 201 299 10 elementalign left addphrasecb strnumengaged numberfont 130 258 230 278 10 elementalign center create legend 29042037052010elementalign center basefont engagedpctfont createbasefontopensansboldttf basefont engageddescfont createbasefontopensanssemiboldttf basefont nonengageddescfont createbasefontopensansregularttf basecolor pmbasecolor new basecolor31 160 200 basecolor oabasecolor new basecolor84 193 209 basecolor wpibasecolor new basecolor248 156 36 basecolor tdfbasecolor new basecolor116 112 94 basecolor nonengagedbasecolor new basecolor148 144 132 float x 330 float y 350 float radius 3 create border around legend cbsetcolorfillnew basecolor255 255 255 cbrectangle320 300 150 70 cbre cbfill basecolor bordercolor new basecolor192 189 178 cbsetcolorstrokebordercolor cbmoveto320 300 cblineto320 365 cblineto500 365 cblineto500 300 cblineto320 300 cbclosepathstroke prof mgmt cbsetcolorfillpmbasecolor cbcirclex y radius cbfill addtexttocanvascb pctpm engagedpctfont 8 new basecolor116 112 100 x20 y2 addtexttocanvascb pg engageddescfont 8 new basecolor116 112 100 x50 y2 online advice cbsetcolorfilloabasecolor cbcirclex y20 radius cbfill addtexttocanvascb pctoa engagedpctfont 8 new basecolor116 112 100 x20 y22 addtexttocanvascb oaa engageddescfont 8 new basecolor116 112 100 x50 y22 clicked wpionline guidance cbsetcolorfillwpibasecolor cbcirclex y40 radius cbfill addtexttocanvascb pctwpi engagedpctfont 8 new basecolor116 112 100 x20 y42 addtexttocanvascb ogg engageddescfont 8 new basecolor116 112 100 x50 y42 if pcttdf 0 tdf users cbsetcolorfilltdfbasecolor cbcirclex y60 radius cbfill addtexttocanvascb pcttdf engagedpctfont 8 new basecolor116 112 100 x20 y62 addtexttocanvascb pti nonengageddescfont 8 new basecolor116 112 100 x50 y62 nonengaged cbsetcolorfillnonengagedbasecolor cbcirclex y80 radius cbfill addtexttocanvascb pctne engagedpctfont 8 new basecolor116 112 100 x20 y82 addtexttocanvascb nng nonengageddescfont 8 new basecolor116 112 100 x50 y82 else nonengaged cbsetcolorfillnonengagedbasecolor cbcirclex y60 radius cbfill addtexttocanvascb pctne engagedpctfont 8 new basecolor116 112 100 x20 y62 addtexttocanvascb ngd nonengageddescfont 8 new basecolor116 112 100 x50 y62 private string formatnumberdouble value string strformat decimalformat df new decimalformat strformat return dfformatvalue private void addphrasepdfcontentbyte cb string strtext font font float llx float lly float urx float ury float leading int alignment throws documentexception phrase phrase new phrasestrtext font columntext ct new columntextcb ctsetsimplecolumnphrase llx lly urx ury leading alignment ctgo private void addtexttocanvaspdfcontentbyte cb string strtext basefont font float fontsize basecolor color float x float y cbbegintext cbsetfontandsizefont fontsize cbsetcolorfillcolor cbshowtextalignedelementalign left strtext x y 0 cbendtext private basefont createbasefontstring filename throws documentexception ioexception return basefontcreatefontpdfgenerationcontrollerlocation fonts filename basefontidentity h basefontembedded private font createfontstring filename float size int red int green int blue throws documentexception ioexception basefont basefont basefontcreatefontpdfgenerationcontrollerlocation fonts filename basefontidentity h basefontembedded font font new fontbasefont size fontsetcolorred green blue return font public jfreechart createchartlong pctpm long pctoa long pctwpi long pcttdf long pctne set up the data set for the donutring chart defaultpiedataset rdataset new defaultpiedataset rdatasetsetvaluepm pctpm rdatasetsetvalueoa pctoa rdatasetsetvaluewpi pctwpi rdatasetsetvaluetdf pcttdf rdatasetsetvaluene pctne initialize values boolean bshowlegend false string strtitle null create ring plot customdonutplot rplot new customdonutplotrdataset ringplot rplot new ringplotrdataset rplotsetlabelgeneratornew standardpiesectionlabelgeneratorlocaleenglish rplotsetinsetsnew rectangleinsets00 50 50 50 rplotsetsectiondepth030 jfreechart chart new jfreechartstrtitle jfreechartdefault title font rplot bshowlegend chartfactorygetchartthemeapplychart create the chart jfreechart rchart chartfactorycreateringchartnull rdataset false false localeenglish ringplot rplot ringplot rchartgetplot rplotsetbackgroundpaintcolorwhite rplotsetcentertextnull rplotsetlabelgeneratornull rplotsetoutlinevisiblefalse rplotsetshadowgeneratornull rplotsetseparatorsvisiblefalse rplotsetshadowpaintnull rplotsetsectionoutlinesvisiblefalse rplotsetouterseparatorextension0 rplotsetinnerseparatorextension0 set colors of the chart rplotsetsectionpaintpm new color31 160 200 rplotsetsectionpaintoa new color84 193 209 rplotsetsectionpaintwpi new color248 156 36 rplotsetsectionpainttdf new color116 112 94 rplotsetsectionpaintne new color148 144 132 rplotsetexplodepercentpm 005 rplotsetexplodepercentoa 005 rplotsetexplodepercentwpi 005 return chart public static class customdonutplot extends ringplot private static final long serialversionuid 1l public customdonutplotdefaultpiedataset dataset superdataset override protected void drawitemgraphics2d g2 int section rectangle2d dataarea pieplotstate state int currentpass if currentpass 1 section 1 section 3 rectangle2d area stategetpiearea systemoutprintln at section section passcurrentpass logdataareadataarea data area logdataareaarea pie area systemoutprintlnstategetinfo superdrawitemg2 section dataarea state currentpass private void logdataarearectangle2d dataarea string msg systemoutprintlnmsg hdataareagetheight w dataareagetwidth x dataareagetx ydataareagety this alternate version isolates the chart from the pdfimport javaawtcolorimport javaawteventqueueimport javaawtgraphics2dimport javaawtgeomrectangle2dimport javautillocaleimport javaxswingjframeimport orgjfreechartchartfactoryimport orgjfreechartchartpanelimport orgjfreechartjfreechartimport orgjfreechartlabelsstandardpiesectionlabelgeneratorimport orgjfreechartplotpieplotstateimport orgjfreechartplotringplotimport orgjfreedatageneraldefaultpiedatasetimport orgjfreeuirectangleinsets see public class test private void thisplay jframe f new jframetest fsetdefaultcloseoperationjframeexit on close long pctpm mathround20 long pctoa mathround15 long pctwpi mathround5 long pcttdf mathround25 long pctne 100 pctpm pctoa pctwpi pcttdf faddnew chartpanelcreatechartpctpm pctoa pctwpi pcttdf pctne fpack fsetlocationrelativetonull fsetvisibletrue public jfreechart createchartlong pctpm long pctoa long pctwpi long pcttdf long pctne set up the data set for the donutring chart defaultpiedataset rdataset new defaultpiedataset rdatasetsetvaluepm pctpm rdatasetsetvalueoa pctoa rdatasetsetvaluewpi pctwpi rdatasetsetvaluetdf pcttdf rdatasetsetvaluene pctne initialize values boolean bshowlegend false string strtitle null create ring plot customdonutplot rplot new customdonutplotrdataset ringplot rplot new ringplotrdataset rplotsetlabelgeneratornew standardpiesectionlabelgeneratorlocaleenglish rplotsetinsetsnew rectangleinsets00 50 50 50 rplotsetsectiondepth030 jfreechart chart new jfreechartstrtitle jfreechartdefault title font rplot bshowlegend chartfactorygetchartthemeapplychart create the chart jfreechart rchart chartfactorycreateringchartnull rdataset false false localeenglish ringplot rplot ringplot rchartgetplot rplotsetbackgroundpaintcolorwhite rplotsetcentertextnull rplotsetlabelgeneratornull rplotsetoutlinevisiblefalse rplotsetshadowgeneratornull rplotsetseparatorsvisiblefalse rplotsetshadowpaintnull rplotsetsectionoutlinesvisiblefalse rplotsetouterseparatorextension0 rplotsetinnerseparatorextension0 set colors of the chart rplotsetsectionpaintpm new color31 160 200 rplotsetsectionpaintoa new color84 193 209 rplotsetsectionpaintwpi new color248 156 36 rplotsetsectionpainttdf new color116 112 94 rplotsetsectionpaintne new color148 144 132 rplotsetexplodepercentpm 005 rplotsetexplodepercentoa 005 rplotsetexplodepercentwpi 005 return chart public static class customdonutplot extends ringplot private static final long serialversionuid 1l public customdonutplotdefaultpiedataset dataset superdataset override protected void drawitemgraphics2d g2 int section rectangle2d dataarea pieplotstate state int currentpass superdrawitemg2 section dataarea state currentpass rectangle2d area stategetpiearea systemoutprintln at section section pass currentpass logdataareadataarea data area logdataareaarea pie area private void logdataarearectangle2d dataarea string msg systemoutprintlnmsg h dataareagetheight w dataareagetwidth x dataareagetx y dataareagety public static void mainstring args eventqueueinvokelaternew testthisplay,['java'] +1151609,android 601 force wifi connection with no internet access this has many similar questions google for no internet access detected would not automatically reconnect or android force wifi connection programmaticallyi thought i had a answer here but it stopped working after installing 601 updates i have may 1 security patchesseems like this is a behaviour changei have some 2013 nexus 7s with 601 that run a kiosk type app and want to connect programmatically to a specific wireless network that has no internet connection each tablet has a unique static ip address of the form 1921680xx i use the normal java socket constructors and check to see if the interface is up using networkinterfacegetnetworkinterfacesa manual connection has been made sometimes there is a dialog that asks whether or not you want to always connect i always check yesbut the wifi says no internet access detected would not automatically reconnect after the router cycles powerdoing a thisconnect enable reconnect does not work at best it gets ip6localhost1has anyone had any luck using a request object or bindprocesstonetworkedit relatededit the problem seems to be with captive portal detection enabled this string seems to be defined in the sourcepublic static final string captive portal detection enabled captive portal detection enabled moved to globaladdsettingsglobalcaptive portal detection enabledbut throws androidprovidersettingssettingnotfoundexception captive portal detection enabled when used explicitly and is not visible to android studioalso doing a settings list global does not contain the constantedit doing a adb shell settings put global captive portal detection enabled 0 does seem to work but this can not be done in the field when the router cycles power this value seems to persist when the tablet cycles power and now this value shows up in a settings list global also using the raw string settingsglobalgetintgetcontentresolvercaptive portal detection enabled now returns 0edit looks like setting it requires androidpermissionwrite secure settings but of course this fails when put into the manifest since we are not a system appedit trying to exec the shell command throws javalangsecurityexception so it looks like you need to issue the command from adb thanks,['android'] +1151856,uitextviews content getting misplaced with extra space after resizing background and description of the problemi made a vertical text view to be used with mongolian it is a custom text view that is made of three layers of views a child uitextview a container view which is rotated 90 degrees and flipped to hold the uitextview and the parent view see here and here for more background info the view increases its size according to the content size of the underlying text view as long as it is between a minimum and maximum size however for the past few days i have been struggling to fix a bug where an extra space is added and the content is shifted left that would be up on the underlying text views coordinates this can be observed in the following image the yellow view is the custom text view called inputwindow in the view controller code belowafter i tap enter a few times to increase the size of the content view an extra space is added trying to scroll the view does nothing scrolling does work after the width reaches it is max and the content size is bigger than the frame size it is as if the content was in middle of scrolling when it got frozen in place before it could be placed in the correct position if i insert another character like a space then the content view updates itself to the correct positionquestionwhat do i need to change or how do i manually force the underlying uitextview to show its content view in the correct locationcodei have tried to cut out all of the extraneous code and just leave in the relevant parts for both the view controller and the custom vertical textview if there is anything else i should include let me knowview controllerthe view controller updates the size constraints on the custom text view when it is content view size changesimport uikitclass tempviewcontroller uiviewcontroller keyboarddelegate let minimuminputwindowsize cgsizewidth 80 height 150 let inputwindowsizeincrement cgfloat 50 mark outlets iboutlet weak var inputwindow uiverticaltextview iboutlet weak var topcontainerview uiview iboutlet weak var keyboardcontainer keyboardcontroller iboutlet weak var inputwindowheightconstraint nslayoutconstraint iboutlet weak var inputwindowwidthconstraint nslayoutconstraint override func viewdidload superviewdidload get rid of space at beginning of textview selfautomaticallyadjustsscrollviewinsets false setup keyboard keyboardcontainerdelegate self inputwindowunderlyingtextviewinputview uiview inputwindowunderlyingtextviewbecomefirstresponder keyboarddelegate protocol func keywastappedcharacter string inputwindowinsertmongoltextcharacter code omitted for brevity increaseinputwindowsizeifneeded func keybackspace inputwindowdeletebackward code omitted for brevity decreaseinputwindowsizeifneeded private func increaseinputwindowsizeifneeded if inputwindowframesize topcontainerviewframesize return width if inputwindowcontentsizewidth inputwindowframewidth inputwindowframewidth topcontainerviewframesizewidth if inputwindowcontentsizewidth topcontainerviewframesizewidth inputwindowscrollenabled true inputwindowwidthconstraintconstant topcontainerviewframesizewidth else selfinputwindowwidthconstraintconstant selfinputwindowcontentsizewidth height if inputwindowcontentsizewidth inputwindowcontentsizeheight if inputwindowframeheight topcontainerviewframeheight if inputwindowframeheight inputwindowsizeincrement topcontainerviewframeheight increase height by increment unit inputwindowheightconstraintconstant inputwindowframeheight inputwindowsizeincrement else inputwindowheightconstraintconstant topcontainerviewframeheight private func decreaseinputwindowsizeifneeded if inputwindowframesize minimuminputwindowsize return width if inputwindowcontentsizewidth inputwindowframewidth inputwindowframewidth minimuminputwindowsizewidth if inputwindowcontentsizewidth minimuminputwindowsizewidth inputwindowwidthconstraintconstant minimuminputwindowsizewidth else inputwindowwidthconstraintconstant inputwindowcontentsizewidth height if 2 inputwindowcontentsizewidth inputwindowcontentsizeheight inputwindowcontentsizewidth topcontainerviewframewidth got too high make it shorter if minimuminputwindowsizeheight inputwindowcontentsizeheight inputwindowsizeincrement inputwindowheightconstraintconstant inputwindowcontentsizeheight inputwindowsizeincrement else bump down to min height inputwindowheightconstraintconstant minimuminputwindowsizeheight custom vertical text viewthis custom view is basically a shell around a uitextview to allow it to be rotated and flipped for the proper viewing of traditional mongolian import uikitibdesignable class uiverticaltextview uiview var textview uitextview let rotationview uiview var underlyingtextview uitextview get return textview set textview newvalue var contentsize cgsize get height and width are swapped because underlying view is rotated 90 degrees return cgsizewidth textviewcontentsizeheight height textviewcontentsizewidth set textviewcontentsize cgsizewidth newvalueheight height newvaluewidth required initcoder adecoder nscoder superinitcoder adecoder override initframe cgrect superinitframe frame selfsetup override func awakefromnib superawakefromnib selfsetup func setup textviewbackgroundcolor uicoloryellowcolor selftextviewtranslatesautoresizingmaskintoconstraints false selfaddsubviewrotationview rotationviewaddsubviewtextview add constraints to pin textview to rotation view edges let leadingconstraint nslayoutconstraintitem selftextview attribute nslayoutattributeleading relatedby nslayoutrelationequal toitem rotationview attribute nslayoutattributeleading multiplier 10 constant 0 let trailingconstraint nslayoutconstraintitem selftextview attribute nslayoutattributetrailing relatedby nslayoutrelationequal toitem rotationview attribute nslayoutattributetrailing multiplier 10 constant 0 let topconstraint nslayoutconstraintitem selftextview attribute nslayoutattributetop relatedby nslayoutrelationequal toitem rotationview attribute nslayoutattributetop multiplier 10 constant 0 let bottomconstraint nslayoutconstraintitem selftextview attribute nslayoutattributebottom relatedby nslayoutrelationequal toitem rotationview attribute nslayoutattributebottom multiplier 10 constant 0 rotationviewaddconstraintsleadingconstraint trailingconstraint topconstraint bottomconstraint override func layoutsubviews superlayoutsubviews rotationviewtransform cgaffinetransformidentity rotationviewframe cgrectorigin cgpointzero size cgsizewidth selfboundsheight height selfboundswidth rotationviewuserinteractionenabled true rotationviewtransform translaterotateflip func translaterotateflip cgaffinetransform var transform cgaffinetransformidentity translate to new center transform cgaffinetransformtranslatetransform selfboundswidth 2selfboundsheight 2 selfboundsheight 2selfboundswidth 2 rotate counterclockwise around center transform cgaffinetransformrotatetransform cgfloatm pi 2 flip vertically transform cgaffinetransformscaletransform 1 1 return transform what i have triedmany of the ideas for things i have tried have come from how do i size a uitextview to its content specifically i have triedsetting the frame instead of auto layoutin the custom view layoutsubviews method i didtextviewframe rotationviewboundsand i did not add the constraints in setup there was no noticeable effectallowsnoncontiguouslayoutthis also had no effect suggested heretextviewlayoutmanagerallowsnoncontiguouslayout falsesetneedslayouti have tried various combinations of setneedslayout and setneedsthisplay on the inputwindow and the underlying text viewinputwindowsetneedslayoutinputwindowunderlyingtextviewsetneedslayouteven inside a thispatch async so that it gets run on the next run loopthispatch asyncthispatch get main queue selfinputwindowsetneedslayoutsizetofitdoing sizetofit on the next run loop after updating the width constraint looked promising at first but it still did not solve the problem at times the content would freeze and at other times it would be scrollable it does not always freeze at the same spot every timeselfinputwindowwidthconstraintconstant selfinputwindowcontentsizewidththispatch asyncthispatch get main queue selfinputwindowunderlyingtextviewsizetofitdelayi have been looking at scheduling a delayed event but this feels like a hack a duplicatea similar sounding question is uitextview gains an extra line when it should not however it is in objectivec so i cannot tell very well it is also 6 years old with no answer this answer also mentions an extra space on iphone 6 my test image above was iphone 6 not 6 however i think i tried the suggestions in that answer that is i did var f selfinputwindowunderlyingtextviewframe fsizeheight selfinputwindowunderlyingtextviewcontentsizeheightselfinputwindowunderlyingtextviewframe fto no noticeable effectupdate a basic reproducible projectin order to make this problem as reproducible as possible i made a standalone project it is available on github here the storyboard layout looks like thisthe yellow uiview class is the inputwindow and should be set to uiverticaltextview the light blue view is the topcontainerview and the buttons below replace the keyboard add the autolayout constraints shown the input windows width constrain is 80 and the height constraint is 150hook up the outlets and actions to the view controller code below this view controller code completely replaces the view controller code i used in my original example aboveview controllerimport uikitclass viewcontroller uiviewcontroller let minimuminputwindowsize cgsizewidth 80 height 150 let inputwindowsizeincrement cgfloat 50 mark outlets iboutlet weak var inputwindow uiverticaltextview iboutlet weak var topcontainerview uiview iboutlet weak var keyboardcontainer keyboardcontroller iboutlet weak var inputwindowheightconstraint nslayoutconstraint iboutlet weak var inputwindowwidthconstraint nslayoutconstraint ibaction func entertextbuttontappedsender uibutton inputwindowinsertmongoltexta increaseinputwindowsizeifneeded ibaction func newlinebuttontappedsender uibutton inputwindowinsertmongoltextn increaseinputwindowsizeifneeded ibaction func deletebackwardsbuttontappedsender uibutton inputwindowdeletebackward decreaseinputwindowsizeifneeded override func viewdidload superviewdidload get rid of space at beginning of textview selfautomaticallyadjustsscrollviewinsets false hide system keyboard but show cursor inputwindowunderlyingtextviewinputview uiview inputwindowunderlyingtextviewbecomefirstresponder private func increaseinputwindowsizeifneeded if inputwindowframesize topcontainerviewframesize return width if inputwindowcontentsizewidth inputwindowframewidth inputwindowframewidth topcontainerviewframesizewidth if inputwindowcontentsizewidth topcontainerviewframesizewidth inputwindowscrollenabled true inputwindowwidthconstraintconstant topcontainerviewframesizewidth else selfinputwindowwidthconstraintconstant selfinputwindowcontentsizewidth height if inputwindowcontentsizewidth inputwindowcontentsizeheight if inputwindowframeheight topcontainerviewframeheight if inputwindowframeheight inputwindowsizeincrement topcontainerviewframeheight increase height by increment unit inputwindowheightconstraintconstant inputwindowframeheight inputwindowsizeincrement else inputwindowheightconstraintconstant topcontainerviewframeheight private func decreaseinputwindowsizeifneeded if inputwindowframesize minimuminputwindowsize return width if inputwindowcontentsizewidth inputwindowframewidth inputwindowframewidth minimuminputwindowsizewidth if inputwindowcontentsizewidth minimuminputwindowsizewidth inputwindowwidthconstraintconstant minimuminputwindowsizewidth else inputwindowwidthconstraintconstant inputwindowcontentsizewidth height if 2 inputwindowcontentsizewidth inputwindowcontentsizeheight inputwindowcontentsizewidth topcontainerviewframewidth got too high make it shorter if minimuminputwindowsizeheight inputwindowcontentsizeheight inputwindowsizeincrement inputwindowheightconstraintconstant inputwindowcontentsizeheight inputwindowsizeincrement else bump down to min height inputwindowheightconstraintconstant minimuminputwindowsizeheight uiverticaltextviewuse the same code as for the uiverticaltextview in the original example but with the addition of the following two methodsfunc insertmongoltextunicode string textviewinserttextunicodefunc deletebackward textviewdeletebackwardtesttap insert text a few times note that the text is backwards because the actual app uses a mirrored font to compensate for the flipped text viewtap new line five timestry to scroll the viewobserve that the content is misplaced and that the view will not scrollwhat do i need to do to fix this problem,['ios'] +1151934,why does not c use stdnested exception to allow throwing from destructor the main problem with throwing exceptions from destructor is that in the moment when destructor is called another exception may be in flight stduncaught exception true and so it is not obvious what to do in that case overwriting the old exception with the new one would be the one of the possible ways to handle this situation but it was decided that stdterminate or another stdterminate handler must be called in such casesc11 introduced nested exceptions feature via stdnested exception class this feature could be used to solve the problem described above the old uncaught exception could be just nested into the new exception or vice versa and then that nested exception could be thrown but this idea was not used stdterminate is still called in such situation in c11 and c14so the questions was the idea with nested exceptions considered are there any problems with it is not the situation going to be changed in the c17,['c++'] +1152024,is there a way to stdmove stdstring into stdstringstream in the c reference i do not see a stdstringstream constructor accepting rvalue reference of stdstring is there any other helper function to move string to stringstream without an overhead or is there a particular reason behind making such limitation,['c++'] +1152241,custom generator for file filter i am writing a small wrapper class around open that will filter out particular lines from a text file and then split them into namevalue pairs before passing them back to the user naturally this process lends itself to being implemented using generatorsmy file classclass special file def init self fname selffname fname def iter self return self def next self return selfnext def nextself with openselffname r as file for line in file line linestrip if line continue namevalue linesplit02 if in name continue yield namevalue raise stopiterationuserland codefor g in special fileinputtxt for nv in g printnvmy code sadly has two enormous problems 1 special file returns a generator when it really needs to return a tuple and 2 the stopiteration exception is never raised so the file is read repeatedly ad infinitum i have a sneaking suspicion that these two issues are related but my understanding of generators and iterable sequences is fairly limited have i missed something painfully obvious about implementing a generatorediti fixed my infinite reading problem by moving the first generator outside of the loop and then just looping over itg special fileinputtxtk nextgfor nv in k printnvhowever i would like the user to be able to use it like a normal call to openfor nv in special fileinputtxt printnv,['python'] +1152712,dataadapterfill performance anomaly i have two databases db1 db2 both dbs are same db2 is created from the backup of db1 when i run a stored procedure sp1 on both dbs it takes approximately 2 seconds to give me an output select statements on both dbsnow the problem is when i point these dbs from a service and try to use dataadapterfill method it gives me different time54 63 seconds on db1 and 42 44 seconds on db2 on both dbs consistently noted that i am using same service to point dbs so it could not be service behaveperformance now my question iswhat could be the reason for this any suggestions are welcome that what should i look intohelping info both db are on different serversidentical configuration but since executing the sp on sql server management studio take the same time on both dbs so i ruled out the possibility of db server performance network delay could be a factor but higlly unlikely as both servers are on same network and infact on same physical location this is my last option to checksome other services are using sqldependency on db1 which consistently fill dataadapters could this be the reason for my dataadapter fill method to slow down less likely as i am guessingas requested in comments below is code that is filling the datasetps the time mentioned above is the execution time of the code line highlighted in the above image,['c#'] +1152734,quickblox webrtc videochat android for few days i am working on quickbloxi keep opponent view below my view like thisit works fine but when i keep views like skype opponent view is on full screen and my view is on top right corner of opponent view it renders only one view which is render at lasti look quickblox webrtc sample given on quickblox site i saw the code in that sample but it contains conference talk is given with some complex coding of recycle view for me single one to one talk is required can any one tell me the best way to keep one webrtc view above another which works in perfect mannercan any one tell me how to put one webrtc above another,['android'] +1152957,how to read a file backwards to find substring efficiently i have a huge log file in this kind of structure timestamp identifiervalue1463403600aa74421463403601aa29551463403603aa24781463403604aa8461463403605aa44841463403607aa87051463403608aa54811463403609aa9311463403611aa77641463403612aa391463403613aa692i want to extract the content after a given timestamp like stdifstream myfunc uint32 t timestamp example myfunc1463403611 returns1463403611aa77641463403612aa391463403613aa692the logfile is long too long to keep it in memory the code will run on a resource limited embedded devices 80mhz 10kb free memory so im looking for some ideas for a effective solution the logfile might have 500k entries and in 99 of the time the timestamp will be in the last 100 lines so starting at the beginnig of the file and check every line for the right timestamp would be very inefficientso i guess im looking for a solution to read the file backwards line by line i dont realy have a solution how to do that efficient without loading big chunks into memory i tried with reading in chunks of 200bytes starting from the eof but was faced with the issue that the chunk cut the timestamp into half in many cases i tried to detect that and reselect some bytes if needed but got the feeling that there must be a smarte solution,['c++'] +1153185,calling a vb6 dll function with a complex user defined type udt from c i am writing a c application to call a third party vb6 dll i have added reference to the vb6 dll in the referencescom taba particular method in the dll takes a vb6 udt user defined type as a parameter this udt is shown as a struct in the auto generated net wrapper for com the struct has lots of child udts structs as well as members of type vbacollection as shown by net metadata it also has regular data types like string short double int etci am initializing this struct in my c code asudtemployee udtempdata defaultudtemployeei also tried udtempdata new udtemployeeif i do not initialize it using default or new i am not able to compile my c code as the compiler complains about use of unassigned variablei need to pass this struct as reference i am doing it like thisclsemployeesetdataref udtempdatawhile calling this method of the vb6 dll i am getting errorerror attempted to read or write protected memory this is often an indication that other memory is corruptwhat is the reason and what is the solutionnote i can not change the vb6 dll as i do not have its source code i am using vs 2005edit 1here is a complete backgroundthere is a locally developed erp product which supports addon development using vb6 it has a configuration file which specifies the names of addon dlls to be loaded these addons are then thisplayed in a menu in the erp application on menu click the erp calls a function with the name startaddon which should be present in the vb6 dll i wanted to develop addon in c so i developed a simple vb6 addon with a startaddon method which in turn passes control to my net dllthe net dll uses the business classes exposed by the erp and passes data objects to and fro in the net dll i have added a com reference to the dll published by the erp vendorso the architecture is like thiserpvb6 addon with startaddon methodnet dlluses com dll published by the erp vendor and its data classes structs udtshow can i debug the memory error,['c#'] +1153653,getopensourcesoftwarelicenseinfo is returning null now a trivial but annoying issue has come up in the last few dayspreviously my menu option which popped up a dialog to show the legal text for using google services was very full if a little slow to load but now it is null with no change to the codegoogleapiavailability apiavailability googleapiavailabilitygetinstance int resultcode apiavailabilityisgoogleplayservicesavailablethis if resultcode connectionresultsuccess alertdialogbuilder builder new alertdialogbuildermainactivitythis buildersettitleabout buildersetmessageapiavailabilitygetopensourcesoftwarelicenseinfothis buildersetpositivebuttonok null buildershow is this a problem common to others ie a new bug introduced by a google update or some other possibility,['android'] +1153781,elementwise operations of matrix in python let us say i have a matrix like so matrix1 121314151617212324252627313234353637 414243454647515253545657616263646567 71727374757677and i want to make a function that will take in two matrices and do pointwise multiplication not using numpyi have seen some things on using zip but that does not seem to be working for me i think its because my list is of lists and not a single listmy codedef pointwise producta matrix a second matrix return mij a matrixij x a second matrixij return ij for ij in zipa matrixa second matrixmatrix1 could be plugged in as both arguments here a second function called thisplay matrix would take this function in and thisplay each element of the lists on new lines but that is beyond on the scope of this question my guess is that i will need some list comprehensions or lambda functions but i am just too new to python to full grasp them,['python'] +1153794,cordova view unresponsive after plugin returns i am trying to make auth0 lock for ios work with cordova it seems to work except i am doing something wrong when i am thismissing the view after the plugin is done it gets thismissed but i can no longer interact with the cordova view it becomes unresponsive here is the plugin codeimplementation lockpluginvoidinitcdvinvokedurlcommandcommand a0lock lock a0lock sharedlock a0lockviewcontroller controller lock newlockviewcontroller controlleronauthenticationblock a0userprofile profile a0token token cdvpluginresult result cdvpluginresult resultwithstatuscdvcommandstatus ok messageasdictionary idtokentokenidtoken refreshtokentokenrefreshtoken tokentypetokentokentype accesstokentokenaccesstoken emailprofileemail selfcommanddelegate sendpluginresultresult callbackidcommandcallbackid selfviewcontroller thismissviewcontrolleranimatedyes completionnil lock presentlockcontrollercontroller fromcontrollerselfviewcontrollerend,"['ios', 'objective-c']" +1154044,adding load balancer to a wordpress multisite installation i am trying to add a load balancer to a wordpress application which has multisite installationwordpress saves the server ip address in mysql tables since there would be two application servers and a single db server and a load balanceri am using a rackspace load balancercan anyone please suggest what should the domain current site point to in wpconfigphp and do i need to make any changes in the database to update the ip address if yes what ip address should be stored in dbalso i am using lsync utility to sync content of one server to another do i need to sycn wpconfigphp as wellalso apart from wpconfigphp and database are there any changes i need to make also apart from this most importantly how would the session be managedthanks,['mysql'] +1154247,designing redux state tree i am currently in the process of learning redux and i have more or less got the hang of the basic concepts i understand how to work with actions and reducers and all that what i am struggling with is understanding how to properly design a state tree i get caught up on the particulars of what shouldshould not be stored in the application state when is it acceptable to use component state the best way to handle state changes etcare there any good tutorials or blogs out there anyone can recommend for understanding the best practices of designing state,['javascript'] +1154255,execute multiple independent statements in sqlalchemy core i am using sqlalchemy core to run a few independent statements the statements are to separate tables and unrelated because of that i cannot use the standard tableinsert with multiple dictionaries of params passed in right now i am doing thissql connexecutequery1sql connexecutequery2is there any way i can run these in one shot instead of needing two backandforths to the db i am on mysql 57 and python 2711,"['python', 'mysql']" +1154278,why does the airbnb style guide say that relying on function name inference is thiscouraged badclass listing extends reactcomponent render return divthispropshellodiv bad relying on function name inference is thiscouragedconst listing hello divhellodiv goodfunction listing hello return divhellodivthis is taken from the airbnb react style guide can someone please explain why relying on function name inference is thiscouraged is it just a style concern,['javascript'] +1154458,how to loop through multiple audio files and play them sequentially using javascript onclick of a button i want to play 4 audios three audios from the siblings id and final one from the clicked id please help me resolve the issue i have changed the code however the audio is still not playing in sequence last audio plays first following by 2nd and 3rd without enough gap between audiosdocumentonclick phonics tab audiosmimg learn function var pid thisparentsphonics tabattrid audiofilename audio thisattrid mp3 var audioelmnt var audiofilename1 pid word box itemeachfunction inx i if inx 1 audioelmntinx 1pause audioelmntinx 1currenttime 0 audioelmntinx documentcreateelementaudio audioelmntinxsetattributeautoplay false audiofilename1inx audio thischildrenh2attrid mp3 audioelmntinxsetattributesrc audiofilename1inx audioelmntinxload in previous code your inx only run for the last item playaudioaudioelmntinx 300 here the object will be sent to the function and will be used inside the timer function playaudioaudioelmnt delay settimeoutfunction audioelmntplay delay settimeoutfunction audioelementcurrenttime 0 audioelementpause audioelementsetattributesrc audiofilename audioelementload audioelementplay 500,"['javascript', 'jquery']" +1154503,c concept with friendlike access is it possible to make this code work as i would like ie to allow the concept to have access to a private member funciontemplate typename tconcept bool writeable return requires t xstdostream os xwriteos void template writeable tvoid writestdostream osconst t x xwriteos class ttprivate void writestdostream os const os foo friend concept bool writeablettfriend void writettstdostream const tt thanks,['c++'] +1154655,android reduce file size for camera captured image to be less than 500 kb my requirement is to upload camera captured image to the server but it should be less than 500 kb in case if it is greater than 500 kb it needs to be reduced to the size less than 500 kb but somewhat closer to itfor this i am using the following code override public void onactivityresultint requestcode int resultcode intent data try superonactivityresultrequestcode resultcode data if resultcode getactivityresult ok if requestcode request code camera try photo mediastoreimagesmediagetbitmap ctxgetcontentresolver capturedimageuri string selectedimagepath getrealpathfromuricapturedimageuri img file new fileselectedimagepath logdimg file size file size in kbs initially img filelength10 ifcommonutilitiesisimagefilesizegreaterthan500kbimg file photo commonutilitiesgetresizedbitmaplessthan500kbphoto 500 photo commonutilitiesgetcorrectbitmapphoto selectedimagepath call this method to get the uri from the bitmap img file new filectxgetcachedir imagejpg img filecreatenewfileconvert bitmap to byte array bytearrayoutputstream bytes new bytearrayoutputstream photocompressbitmapcompressformatjpeg 100 byteswrite the bytes in file fileoutputstream fo new fileoutputstreamimg file fowritebytestobytearray remember close de fileoutput foclose logdimg file size file size in kbs after image manipulations img filelength10 catch exception e logssetlogexceptionclass name onactivityresult when captured from camera e catch exception e logssetlogexceptionclass name onactivityresult e catch outofmemoryerror e logssetlogerrorclass name onactivityresult e andpublic static bitmap getresizedbitmaplessthan500kbbitmap image int maxsize int width imagegetwidth int height imagegetheight float bitmapratio floatwidth float height if bitmapratio 0 width maxsize height int width bitmapratio else height maxsize width int height bitmapratio bitmap reduced bitmap bitmapcreatescaledbitmapimage width height true ifsizeofreduced bitmap 500 10 return getresizedbitmapreduced bitmap maxsize else return reduced bitmap to rotate the image if neededpublic static bitmap getcorrectbitmapbitmap bitmap string filepath exifinterface ei bitmap rotatedbitmap bitmap try ei new exifinterfacefilepath int orientation eigetattributeintexifinterfacetag orientation exifinterfaceorientation normal matrix matrix new matrix switch orientation case exifinterfaceorientation rotate 90 matrixpostrotate90 break case exifinterfaceorientation rotate 180 matrixpostrotate180 break case exifinterfaceorientation rotate 270 matrixpostrotate270 break rotatedbitmap bitmapcreatebitmapbitmap 0 0 bitmapgetwidth bitmapgetheight matrix true catch ioexception e todo autogenerated catch block eprintstacktrace return rotatedbitmap here is the output of the image file size initially and after all the operations to reduce file sizeimg file sizei1 file size in kbs initially 3294 img file sizei1 file size in kbs after image manipulations 235see the difference above in the output the initial file size without those operations and after those compression and other operations i need that size to be somewhat closer to 500 kbthe above code is working somewhat fine for me as it is reducing the image file size to make it less than 500 kbbut the following are the issues with the above code this code is reducing the file size even if its less than 500 kbin case it is more than 500 kb the reduced file size becomes too less from 500 kb though i need it somewhat closeri need to get rid off above 2 issues so need to know what should i manipulate in the above codeas i also want to correct the exiforientation rotated images along with my above mentioned requirement,['android'] +1154785,what is the django way of doing a subselect i have a versioned model which simplified looks a bit likeprojectid ref versionunique togetherref versionwhere id is the autogenerated primary key ref is a random uuid and version is an integer incremented by my application each time i save the project i create a new instance add 1 to the version and copy the ref to the new objectthe following sql will give me back the latest version of every project by doing a subselect select from myapp project where ref version inselect ref maxversion from myapp project group by refalternatively slightly simpler perhapsselect from myapp project pwhere pversion select maxversion from myapp project p1 where p1ref prefhow do i achieve the same query using djangos ormedit i have got as far as this foo projectobjectsvaluesrefannotateversionmaxversionthis gives me something that looks right if i inspect it as soon as i try to get the id out withfoovaluesidit seems to thiscard the original result and gives back all the rowsedit moreworked around it for now with extramaxids id in select id from myapp project p where pversion select maxversion from myapp project p1 where p1ref prefprojectobjectsallextrawheremaxids,['python'] +1154822,show hidden option using argparse i am using argprase to create an option and it is a very specific option to do one specific job the script currently has roughly 30 knobs and most are not used regularlyi am creating an optionoptadd argumentopthelpsome help helpargparsesuppressbut i want there to be two ways to show the help for the scriptmy script helpmy script helplongi want the helplong to also show all the hidden args i could not find a way to do thisis there a way to implement this behavior,['python'] +1154910,strategy pattern in python when a strategy consists of more than one function i understand that because python has firstclass functions using the strategy pattern is usually just a matter of passing a function as an argument and does not require futzing with classes but what if the strategies are not single functions but rather groups of related functions that logically should be selected as a setlike heres a trivial and contrived exampleclass hexformatterobject base class for strategies to format hexadecimal numbers passclass motorolahexformatter format motorola style eg 1234 staticmethod def formatbyten return 02x n staticmethod def formatwordn return 04x nclass intelhexformatter format intelstyle eg 1234h staticmethod def formatbyten return 02xh n staticmethod def formatwordn return 04xh nthe idea is you pick a strategy and you get the function for formatting bytes and the function for formatting words as a set rather than needing to specify them individually this example is akin to how youd do it in a language like c except the methods wouldnt be static because you cannot have virtual static methods in c and it is not as if it does not work in python but it involves defining a bunch of classes that only have static methods and are not meant to be instantiated which seems unpythonic somehowis there a more idiomatic way to do this in python,['python'] +1154959,how to make sequelize has many association lowercase in views everything works here the only issue is that in my handlebars file i have to get to a persons tasks like thisthistasksi would rather have it appear like thisthistaskshow would i customize sequelize to do sothis is what the root route of my app looks like it is rendering the indexhandlebars filemy routerouterget functionreq res modelspersonfindall include modelstask thenfunctionpeople resrenderindex user id reqsessionuser id email reqsessionuser email logged in reqsessionlogged in people people my indexhandlebars file each people li thisname if logged in a hrefpeoplethisiddestroy destroya if ul if logged in li form actionpeoplethisidtaskscreate methodpost stylethisplay inline input typetext nametask placeholderadd task here input typesubmit valueassign task form li if each thistasks li thistask if logged in a hrefpeoplethisperson idtasksthisiddestroydestroya if li each ul li eachmy people table migrationuse strictmoduleexports up functionqueryinterface sequelize return queryinterface createtablepeople id type sequelizeinteger autoincrement true primarykey true name sequelizestring created at sequelizedate updated at sequelizedate down functionqueryinterface sequelize return queryinterface droptablepeople my tasks table migrationuse strictmoduleexports up functionqueryinterface sequelize return queryinterface createtabletasks id type sequelizeinteger autoincrement true primarykey true person id type sequelizeinteger task sequelizestring created at sequelizedate updated at sequelizedate down functionqueryinterface sequelize return queryinterface droptabletasks my personjs modeluse strictmoduleexports functionsequelize datatypes var person sequelizedefineperson name datatypesstring underscored true freezetablename true tablename people classmethods associate functionmodels personhasmanymodelstask return personmy taskjs modeluse strictmoduleexports functionsequelize datatypes var task sequelizedefinetask task datatypesstring freezetablename true tablename tasks classmethods associate functionmodels taskbelongstomodelsperson ondelete cascade foreignkey allownull false return task,['mysql'] +1155146,incompatibleclasschangeerror after updating to android build tools 2516 gcm fcm since i updated to android sdk tools 2516 and android support repository 3200 this morning i got the following error i did not change anything in my code and it is still working on my colleague computer android sdk tools 2511 android support repository 30 javalangincompatibleclasschangeerror the method javaiofile androidsupportv4contentcontextcompatgetnobackupfilesdirandroidcontentcontext was expected to be of type virtual but instead was found to be of type direct declaration of javalangreflectartmethod appears in systemframeworkcorelibartjar at comgoogleandroidgmsiidzzdzzebunknown source at comgoogleandroidgmsiidzzdinitunknown source at comgoogleandroidgmsiidzzdinitunknown source at comgoogleandroidgmsiidinstanceidzzaunknown source at comgoogleandroidgmsiidinstanceidgetinstanceunknown source at comxutilsregistrationintentserviceonhandleintentregistrationintentservicejava55 at androidappintentserviceservicehandlerhandlemessageintentservicejava65 at androidoshandlerthispatchmessagehandlerjava102 at androidoslooperlooplooperjava145 at androidoshandlerthreadrunhandlerthreadjava61here is a the piece of code that crashinstanceid instanceid instanceidgetinstancethis crash herestring instanceidtoken instanceidgettokengetstringrstringgoogle app idgooglecloudmessaginginstance id scope nullit is when i try to get a token from google cloud messagingi am importing gcm in gradle with splited playservices compile comgoogleandroidgmsplayservicesanalytics900 compile comgoogleandroidgmsplayservicesmaps900 compile comgoogleandroidgmsplayserviceslocation900 compile comgoogleandroidgmsplayservicesgcm900 compile comgoogleandroidgmsplayservicesbase900editthisabling gcm fixed the problem so my guess is i should migrate to firebase cloud message edit2my device receive google play services 90 yesterday was 84x now it does not crash anymore but complain about module descriptor failed to load module descriptor class did not find class comgoogleandroidgmsdynamitedescriptorscomgooglefirebaseauthmoduledescriptor firebase api initialization failuredoes anyone has a similar error and how to fix it fixedspecial thanks to stegranetgradlew q appdependencies configuration compile helps you to identify what dependencies include sdk 24xmain issue is some library import the latest support library using sign instead of a version this cause the issue by including the latest available versionso avoid sign in dependencies,['android'] +1155176,fullcalendar does not load events i am using fullcalendar in my aspnet mvc application it does not load events i am getting event list by ajax call below is my code what is wrong with itdiv classrow div classcollg12 section classpanel div classpanelbody div idcalendardiv div section divdivscript typetextjavascript jqueryextend getvalues function url var result null ajax url url type get datatype json async false success function data result data error function err alertjsonstringifyerr return result var jsonevents getvaluesurlactiongetevents booking alertjsonevents var jsonevents title dhaval 46 6 start 05212016 10500 pm title mohit 2 4 start 05212016 10500 pm calendarfullcalendar header left prevnext today center title right agendaweekagendaday allday true defaultview agendaweek events jsoneventsurlactiongetevents booking scriptthe js in comment is just for example format and the geteventscontroller is as belowpublic json getevents string query query to get events columns in result table are id title date try sqlconnection connection new sqlconnectionconnectionstring connectionopen sqlcommand command new sqlcommandquery connection sqldatareader events commandexecutereader datatable dt new datatable dtloadevents string result datatabletojsonwithstringbuilderdt connectionclose return jsonresult jsonrequestbehaviorallowget catch exception ex public string datatabletojsonwithstringbuilderdatatable table var jsonstring new stringbuilder if tablerowscount 0 jsonstringappend for int i 0 i tablerowscount i jsonstringappend for int j 0 j tablecolumnscount j if j tablecolumnscount 1 jsonstringappendtablecolumnsjcolumnnametostring tablerowsijtostring else if j tablecolumnscount 1 jsonstringappendtablecolumnsjcolumnnametostring tablerowsijtostring if i tablerowscount 1 jsonstringappend else jsonstringappend jsonstringappend return jsonstringtostring this is the format i wanttitlejohn 21 6start13052016 120 amtitleolivia 114 6start11052016 120 amgetting following error when inspect element failed to load resource the server responded with a status of 400 bad request http localhoabc7btitle22john204620622start2205212016201050020pm22end22052120162013020pm227d7btitle22olivia20220422start2205212016201050020pm22end22052120162013020pm227dstart20160515end20160522 1463885539445here i have commented var jsonevents when i use predefined events the calendar shows them perfect but when i call to server there is errordoes fullcalendar only shows the events from a file stored on the server because the documentation shows only url to a file that contains json datahelp me thanks,['jquery'] +1155189,thisable lightbox with javascript i have an image that when clicked will open up in a lightbox script from and what i want to do is thisable that from happening when a button is switched to off so clicking the image does nothingi have tried to use off and unbind following some other answers on the site to thisable the lightbox but none of them are working for mei have also followed how do i dynamically enablethisable links with jquery as suggested but have had no luckbelow is the htmldiv stylemarginleft10padding1px 16px section idfour columns article classimgitem figure a hrefimglivingroomjpg datalightboxlivingroomimg idimg window1 srcimglivingroomjpg width200 height120a figcaption strongliving room div classonoffswitch input typecheckbox nameonoffswitch classonoffswitchcheckbox idwindow1 valuewindow1 checked label classonoffswitchlabel forwindow1 span classonoffswitchinnerspan span classonoffswitchswitchspan label div strong figcaption figure articleand javascriptscript typetextjavascript documentreadyfunction var full opacity 1 var faded opacity 03 var fade speed fast var objid inputnameonoffswitcheachfunction objid img thisval ifthispropchecked objidcssopacity full opacity else objidcssopacity faded opacity inputnameonoffswitchchangefunction var objid img thisval consolelogthispropchecked ifthispropchecked objidfadetofade speed full opacity else objidfadetofade speed faded opacity objidparentunbindclick here is where i want to implement the code scriptany help would be appreciated,"['javascript', 'jquery', 'html']" +1155242,android how to perform obfuscation with the jack compiler google has released a test version of their new jack compiler for android developers with android studio 21my question is how do we enable obfuscation for the apk with jack the article below says that jack performs obfuscation natively and eliminates the need for proguardcompiling withjackwhereas the following article says that jack makes use of proguard configuration files ie the pro file for performing obfuscationexperimental new android tool chain jack and jillit also says thatduring this process jack also handles any requested code minification shrinking andor obfuscationwhat exactly does this mean do we have to use the minifyenabled option and define a pro file containing the proguard optionsin summaryhow exactly do we go about enabling obfuscation with jack can webypass the use of proguard or does proguard play a defacto role inthe obfuscation process even if we compile with jackdoes jack currently support obfuscation or not and is it availablein a stable ie nonbetacanary version of android studionotei have already referred the following postshow to enable jack java android compiler kit in android studioerrorjack is required to support java 8 language featuresfurther referencesan introduction to jack and jill on x86the dark side of jack and jilljava 8 language featuresupdatethe answer by matt insko is helpful but i would like more detail and a more precise canonical answer i have marked his very good answer correct for now for lack of a better alternative,['android'] +1155480,is there a uuid validator annotation i cannot find a uuid or similar annotation for validating input parameters in a java web app i have looked so far in javaxvalidationconstraintsorghibernatevalidatorconstraints,['java'] +1155656,why is a datatype necessary for an initialization that follows a declaration consider the simple c programint a declarationint a 11 initializationint mainint argc char argv int b declaration b 10 assignmentif the initialization of a were written without the data type such as a 11 the compiler raises a warning why does the initialization of a require a data type when the declaration of a already specifies its data type,['c'] +1155673,why does the cast operation fail in case 1 but succeed in case 2 case 1 produces a type mismatch exception case 2 works as expected does anyone have insight into why or a better way to have converted from int32 as an object into an int16case 1var i int16objectint32parse1case 2 var i int16int32parse1,['c#'] +1155804,android firebase dynamitemodule failed to load module descriptor since upgrading to the newest version of firebase 900 i cannot get rid of the following two errors when authenticating a user through signinwithemailandpassword anyone an idea whats going on 0519 180949245 2355023589package edynamitemodule failed to load module descriptor class did not find class comgoogleandroidgmsdynamitedescriptorscomgooglefirebaseauthmoduledescriptor on path dexpathlistzip file dataapackage3baseapknativelibrarydirectoriesdataapackage3libx86 vendorlib systemliband 0519 180949252 2355023550package efirebaseapp firebase api initialization failurejavalangreflectinvocationtargetexception at javalangreflectmethodinvokenative method at comgooglefirebasefirebaseappzzaunknown source at comgooglefirebasefirebaseappinitializeappunknown source at comgooglefirebasefirebaseappinitializeappunknown source at comgooglefirebasefirebaseappzzbuunknown source at comgooglefirebaseproviderfirebaseinitprovideroncreateunknown source at androidcontentcontentproviderattachinfocontentproviderjava1748 at androidcontentcontentproviderattachinfocontentproviderjava1723 at comgooglefirebaseproviderfirebaseinitproviderattachinfounknown source caused by javalangincompatibleclasschangeerror the method javaiofile androidsupportv4contentcontextcompatgetnobackupfilesdirandroidcontentcontext was expected to be of type virtual but instead was found to be of type direct declaration of comgooglefirebaseiidzzg appears in datadatapackagefilesinstantrundexslicecomgooglefirebasefirebaseiid900 95503dc60ed409569d1585da411de93e6c633bf7classesdex at comgooglefirebaseiidzzgzzecunknown source at comgooglefirebaseiidzzginitunknown source at comgooglefirebaseiidzzginitunknown source at comgooglefirebaseiidzzdzzbunknown source at comgooglefirebaseiidfirebaseinstanceidgetinstanceunknown source at javalangreflectmethodinvokenative methoda at comgooglefirebasefirebaseappzzaunknown sourcea at comgooglefirebasefirebaseappinitializeappunknown sourcea at comgooglefirebasefirebaseappinitializeappunknown sourcea at comgooglefirebasefirebaseappzzbuunknown sourcea at comgooglefirebaseproviderfirebaseinitprovideroncreateunknown sourcea at androidcontentcontentproviderattachinfocontentproviderjava1748a at androidcontentcontentproviderattachinfocontentproviderjava1723a at comgooglefirebaseproviderfirebaseinitproviderattachinfounknown sourcea,['android'] +1155860,cannot call value of nonfunction type module i have a strange error when i was using firebase from googlewhen i trying to init the fire base setup the ref address for it using this code here let base url your firebase urlvar firebase ref firebaseurl base url it shows an errorcannot call value of nonfunction type modulefirebasemy pod file looks like this uncomment this line to define a global platform for your project platform ios 90target mission board do comment this line if youre not using swift and do not want to use dynamic frameworks use frameworks pod firebase 242endenvironment xcode 731 7d1014 firebase straight from the official siteswift languageplease anyone help,['ios'] +1155869,aspnet core rc2 cannot find html encoder implementation can anyone show me an example of how to html encode text with the htmlencoder class in the systemtextencodingsweb namespace i am converting an aspnet core rc1 project to rc2 in the rc1 project i am using the htmlencoder class in the microsoftextensionswebencoders namespace but there is no rc2 update for that according to this github post microsoftextensionswebencoders has been moved to systemtextencodingsweb but the htmlencoder class in this new namespace is an abstract class and i cannot find an implementation of it,"['asp.net', '.net']" +1155974,googlesignatureverifier signature not valid message google play services 900 i have recently updated to the google play services library version 900 and i keep getting the following logcat message0519 230730023 1923719508 vgooglesignatureverifier optionsdevelopercomdeveloperoptions signature not valid found while my app is not using the google maps api but it is using the analytics ads and google plus apisthe only mention in the documentation regarding the usage of the api key is when using google maps or android places apii have also tried adding the comgoogleandroidgeoapi key with a correct key but it did not helphere is my gradlebuild fileapply plugin comandroidapplicationandroid compilesdkversion 23 buildtoolsversion 2303 defaultconfig applicationid optionsdevelopercomdeveloperoptions minsdkversion 9 targetsdkversion 23 versioncode 23 versionname 106 buildtypes release minifyenabled false proguardfiles getdefaultproguardfileproguardandroidtxt proguardrulespro dependencies compile comgoogleandroidgmsplayservicesplus900 compile comandroidsupportappcompatv72320 compile comgoogleandroidgmsplayservicesanalytics900 compile comgoogleandroidgmsplayservicesads900,['android'] +1155999,notification throws error when using vector drawables i get the following exception when i use a vector drawable to set the small icon for a notification androidappremoteserviceexception bad notification posted from package comqbesx could not create icon statusbariconpkgcomqbesxuser0 id0x7f020082 level0 visibletrue num0 here is my code mnotificationbuilder new androidsupportv4appnotificationcompatbuilderthis setdefaultsandroidsupportv4appnotificationcompatdefault lights setsoundnull setsmalliconrdrawablelogo white setcolorgetresourcesgetcolorrcolorcolorprimary setcategoryandroidsupportv4appnotificationcompatcategory progress setcontenttitletrip in progress setautocancelfalse setprogress0 0 progress setongoingtrue setpriorityandroidsupportv4appnotificationcompatpriority max setonlyalertoncetrue setcontentintentpendingintentmnotificationbuildersetcontenttextbodymnotificationmanager notificationmanager getsystemservicecontextnotification servicenotification note mnotificationbuilderbuildmnotificationmanagernotifyconstantsnotification id dash noteand my buildgradle only relevant parts android compilesdkversion 23 buildtoolsversion 2303 defaultconfig applicationid comqbesx minsdkversion 16 targetsdkversion 22 versioncode 720 versionname 0720 vectordrawablesusesupportlibrary true buildtypes release minifyenabled false proguardfiles getdefaultproguardfileproguardandroidtxt proguardrulespro dependencies compile filetreedir libs include jar testcompile junitjunit412 compile comandroidsupportappcompatv72321 compile comandroidsupportdesign2321ps the code works fine when i use a png or jpg image drawable but breaks when using a vector drawable i have been searching for a whole day but could not find anything that worked for me any ideas,"['java', 'android']" +1156112,initialize firebase references in two separate files in the new api i have upgraded to the new api and do not know how to initialize firebase references in two separate files case 1 1st file var config firebaseinitializeappconfig var rootref firebasedatabaseref 2nd file initialize again var config firebaseinitializeappconfig var rootref firebasedatabaserefresult bundlejs535 uncaught error firebase app named default already exists case 2 1st file var config firebaseinitializeappconfig var rootref firebasedatabaseref 2nd file do not initialize var rootref firebasedatabaserefresult bundlejs529 uncaught error no firebase app default has been created call firebase appinitializeappbefore the new api i just calledvar myfirebaseref new firebasehttpsyourfirebaseappfirebaseiocomin each file and it worked okay,['javascript'] +1156178,which one is faster regex or endswith what would be fasterpublic string roll random rnd new random int roll rndnext1 10 if regexismatchrolltostring 11 return doubles return noneorpublic string roll random rnd new random int roll rndnext1 10 if rolltostringendswith11 rolltostringendswith22 rolltostringendswith33 rolltostringendswith44 rolltostringendswith55 rolltostringendswith66 rolltostringendswith77 rolltostringendswith88 rolltostringendswith99 rolltostringendswith00 return doubles return nonei am currently using a really long ifstatement list full with regexes to check if an int ends with doubles triples quads quints etc so i would like to know which one is faster before i change all of it,['c#'] +1156402,c postfix expression undefined vs unspecified behaviour apologies in advance i know the general topic of evaluation order has had a lot of so questions on it already however having looked at them i want to clarify a few specific points that i do not think amount to a duplication of anything suppose i have the following codeinclude iostreamauto mylambdaint n n return int param stdcout param param stdendl int main int n0 mylambdann return 0the program above outputs n 0 when i compile it here we have unspecified ordering at play it could have just as easily output n 1 had a different evaluation order taken placemy questions arewhat exactly is the sequencing relationship at play during the final function invocation above ie the lambdaexpression invocation between the postfix expression mylambda0 its argument n and the subsequent function call itselfis the above an example of undefined or unspecified behaviour and why exactly with reference to the standardif i changed the lambda code to int param stdcout hello stdendl ie made the outcome independent of its parameter and thus any evaluation order decisions making behaviour deterministic would the answer to 2 above still be the sameedit i have change the lambda parameter name from n to param because that seemed to be causing confusion,['c++'] +1156501,how to extendoverwrite default options in angular material mddialogshow tldr i need a way to overwrite default options provided my angular material especially on material dialog using providers like any other angular modules a random example i have been looking for a way to customize defaults options angular material modal but without any usable resultlike i have used on other pluginsmodules this way could be achieved using a provider having a look in the core of the material 108 i was trying to set options using setdefaults method like this let say i just want to thisable backdrop for momentappconfigmddialogprovider functionmddialogprovider consolelogmddialogprovider getaddmethodaddpresetsetdefaults var defaults options function return hasbackdrop false mddialogprovidersetdefaultsdefaultsright now when i am checking the options on oncomplete callback so as you can see the hasbackdrop option is updated but the modal is not working anymore so i think i am missing somethingdo you have any idea how the angular defaults could be extended in a proper way thanksupdate options object without having setdefaults active de initial state note i have copied from their core transformtemplate and added in my defaults object but the result is the same i can see the dom updated console has no errors but the modal is not visible,['javascript'] +1156635,how is c string interpolation compiled i know that interpolation is syntactic sugar for stringformat but does it have any special behaviorrecognition of when it is being used with a string formatting methodif i have a methodvoid printstring format params object parametersand the following call to it using interpolationprintfoo barwhich of the following calls lines is most equivalent to the compiled result of string interpolationprintstringformat0 1 new foo bar print0 1 new foo bar reasoning behind the question logging frameworks such as nlog typically defer string formatting until they have determined that a log message will actually be written in general i prefer the string interpolation syntax but i need to know if it may incur an extra performance penalty,['c#'] +1156770,ruby is efficient way to find the difference between two very large arrays i have a problem concerning efficiency and algorithms when it comes to finding the difference between two very large arrays i am hoping someone with a good understanding of algorithms can point me to the right direction in how to solve this as my current implementations is taking an extremely long amount of time problemi have two very large arrays one contains a list of emails that have invalid domain names and the other is a mixed list that i need to check against the first arrayaccounts with failed email domains 2790 records in hereunchecked account domains 1490 records in herewhat i need to do is go through the list of unchecked account domains and then compare each entry to see if there is a match in the accounts with failed email domains i need to insert all matches between the lists in a separate array to be processed laterhow can i efficiently write something that can quickly check through these accounts here is what i have tried so farunchecked account domains really big arrayunchecked account domains unchecked account domainssortaccounts with failed email domains another huge arraysortunchecked account domainskeep if do email accounts with failed email domainsany failed email email failed email end count to see how many accounts are leftputs unchecked account domainscountthis above implementation has been running forever here is the second attempt which still proved not to be any betterunchecked account domains really big arrayunchecked account domains unchecked account domainssortaccounts with failed email domains another huge arraysortunchecked account domainseach do email accounts with failed email domainsbsearch do failed email final check email if email failed email endend count to see how many accounts are leftputs final checkcountbsearch seemed to be promising but i am pretty sure i am not using this correctly also i tried looking into this question comparing large lists but this is in python and i cannot seem to find a ruby equivalent for set does anyone have any ideas on how to solve this,['ruby'] +1156881,c accessing int via void pointing to void pointing to int by typecasting and dereferencing i am fiddling around with pointers in c and am still uncertain about some very basics i came up with the following exemplary codeinclude stdiohint mainvoid int num 42 we want to access this integer void vptrb num pointer b points to the integer void vptra vptrb pointer a points to pointer b printfdn int void vptra return 0the memory should look something like thisare there alternatives to access the integer anything badunsafe with the example is int void vptra the only way to access num via vptra and vptrb,['c'] +1156933,increment in function overwritten by a method called in a ternary operator increments a variable and returns a boolean value when the function returns false the value is reverted i expected the variable to be 1 but am getting 0 instead whypublic class main public int a0variable whose value is to be increased in function boolean function a return false public static void mainstring argv main mnew main mamfunction10 systemoutprintlnmaexpected output to be 1 but got a 0,['java'] +1156960,python l2penalty for logistic regression model from statsmodels is there a way to put an l2penalty for the logistic regression model in statsmodel through a parameter or something else i just found the l1penalty in the docs but nothing for the l2penalty,['python'] +1157036,how to implement a generic factory that supports template covariance how to implement a generic factory in c14 that supports template covariancei want to achieve something like thisstdshared ptrfactorybaseclass factory stdmake sharedfactoryderivedclassauto x factorycreatearg1 arg2 arg3note that in factorycreate you can pass any arguments to derivedclass constructor it is okay to assume that the baseclass constructor and the derivedclass are identicalto avoid the xy problem the reason i need this is because i want to use dependency injection boostdi to achieve maximum testabilityfor example if there is a class a that creates socket instances i want it to depend on a factoryisocket service in the real code i would inject factorysocket and in the testing code i would inject factorymockisocket so i can test the a class without actually creating a real socketthis is my current attempttemplate typename tstruct basefactory virtual stdunique ptrt create 0template typename tinterface typename timplementationstruct factory public basefactorytinterface virtual stdunique ptrtinterface create override return stdmake uniquetimplementation the current usage is something likestdshared ptrbasefactoryisocket factory stdmake sharedfactoryisocket socketauto x factorycreatealthough not ideal you need to specify the base class in factory this usage is fine for me and it works the next thing i need to add is support for constructor arguments i have tried to add variadic template to createtemplate typename targsvirtual stdunique ptrt create 0 but it looks like you cannot have virtual methods with templatesam i going in the right direction if yes how should i add support for constructor arguments in my implementationthank you,['c++'] +1157168,android studio issue could not find adsadqualityunspecified i have updated the android studio and just opened my project and i got the following error could you please let me know how to resolve this errora problem occurred configuring project memorygamecollectionfree could not resolve all dependencies for configuration memorygamecollectionfree debugcompile could not find adsadqualityunspecified searched in the following locations filecprogram filesandroidandroid studiogradlem2repositoryadsadqualityunspecifiedadqualityunspecifiedpom filecprogram filesandroidandroid studiogradlem2repositoryadsadqualityunspecifiedadqualityunspecifiedjar filecuserssudhakarappdatalocalandroidsdkextrasandroidm2repositoryadsadqualityunspecifiedadqualityunspecifiedpom filecuserssudhakarappdatalocalandroidsdkextrasandroidm2repositoryadsadqualityunspecifiedadqualityunspecifiedjar filecuserssudhakarappdatalocalandroidsdkextrasgooglem2repositoryadsadqualityunspecifiedadqualityunspecifiedpom filecuserssudhakarappdatalocalandroidsdkextrasgooglem2repositoryadsadqualityunspecifiedadqualityunspecifiedjar required by memorygamecollectionfreememorygamecollectionfreeunspecified comfacebookandroidaudiencenetworksdk4120,['android'] +1157226,deferred longrunning timer tasks to improve scrolling smoothness i was inspecting my page and i got this warningdeferred longrunning timer tasks to improve scrolling smoothness see crbugcom574343i have also seenblink deferred a task in order to make scrolling smoother your timer tasks should take less than 50ms to run to avoid this please see and for more informationwhat is this,"['javascript', 'html']" +1157258,why this code compiles with jdk8u45 and above but not with jdk8u25 please could someone help me to figure out why the following code compiles with jdk8u45 and above but fails with jdk8u25 i looked through the jdk release notes but did not find anything related to the issue or maybe missed itthe codepublic class main static class param final int id paramint id thisid id static class subtask final param param subtaskparam param thisparam param public static void mainstring args list extends param params intstreamrange1 100maptoobjparamnewcollectcollectorstolist navigablemapstring subtask map paramsstream collectcollectorstomapp uuidrandomuuidtostring subtasknew a b a treemapnew jdk8u25 exceptionerror33 17 java no suitable method found for collectjavautilstreamcollectororgkamainparamcapture1 of javautiltreemapjavalangstringorgkamainsubtask method javautilstreamstreamrcollectjavautilfunctionsupplierrjavautilfunctionbiconsumerr super capture2 of extends orgkamainparamjavautilfunctionbiconsumer is not applicable cannot infer typevariables r actual and formal argument lists differ in length method javautilstreamstreamracollectjavautilstreamcollector super capture2 of extends orgkamainparamar is not applicable cannot infer typevariables racapture3 of tkumkv argument mismatch javautilstreamcollectorcapture2 of extends orgkamainparamcapture4 of javautiltreemapjavalangobjectorgkamainsubtask cannot be converted to javautilstreamcollector super capture2 of extends orgkamainparamcapture4 of javautiltreemapjavalangobjectorgkamainsubtask,['java'] +1157415,how can i send a firebase cloud messaging notification without use the firebase console i am starting with the new google service for the notifications firebase cloud messaging thanks to this code i was able to send notifications from my firebase user console to my android device the thing is is there any api or way to send a notification without use the firebase console i mean for example a php api or something like that to create notifications from my own server directlythanks,"['php', 'android']" +1157622,cocoapods 10 header files not found i just tried to update from cocoapods 039x to cocoapods 10runningpod installfrom the terminal causes no warnings everything seems normal however when i try to build my project it outputsafnetworkingafnetworkingh file not foundmy pod file looks like this there are a few more dependencies but i only listed a part of itplatform ios 80use frameworkssource target myapp do pod afnetworking 26 pod bemcheckbox pod actionsheetpicker30 205 pod sclalertview pod dznemptydataset pod ssziparchiveendtarget myapptests doendsince some projects are written in objectivec i created a bridging headerimport afnetworkingafnetworkinghimport actionsheetpicker 3 0actionsheetpickerhimport ssziparchivessziparchivehimport dznemptydatasetuiscrollviewemptydatasethi explicitly included inherited in the header search paths the user header search paths and the framework search paths but the error does not go awaydoes someone have an idea on how to fix this,['ios'] +1158012,no id for my android ui testing i would like to write some ui test on my android application in order to take automated screenshots my application is written with reactnative in order to write my tests in need to know the resourceid of my component but as you can see in this screenshot i cannot see any resourceid with ui automator viewer in this reactnative example app look this picturei would like to know if there is a way to give some ids to my components so i can write some test or if there is another way to select my components note i am trying to write espresso test,['android'] +1158045,how to create a virtual file in clang for codecompletion im trying to create virtual files for codecompletion in clang unfortunately my application segfaultsi have the following setupauto createvirtualfile clangcompilerinstance ci stdstring name llvmstringref input stdunique ptrllvmmemorybuffer mbllvmmemorybuffergetmembufferinput name return stdmovembonce the file is created i setup a codecompletconsumerauto setupcodecomplete clangcompilerinstance ci stdstring file int line int column auto f cigetfrontendopts fcodecompletionatfilename file fcodecompletionatline line fcodecompletionatcolumn column clangfrontendinputfile frontfilefile clangik cxx finputspush backfrontfile cicreatecodecompletionconsumer return frontfilei invoke those two functions the following way and execute a syntax only actionauto runcodecompleteat clangcompilerinstance ci stdstring filename stdstring code int line int column auto fid createvirtualfileci filename code auto file setupcodecompleteci filename line column clangsyntaxonlyaction act if actbeginsourcefileci file actexecute segfault actendsourcefile auto runexample auto ci runcodecompleteratci testcpp stdcou 1 7i appreciate any hints,['c++'] +1158114,zipping an stdtuple and variadic arguments i have the following classtemplatetypename tkeysclass cpublic stdtuplestdunordered maptkeys int maps not real function void footkeys keys mapskeys 1 how would i implement foo so that it assigns to each stdmap in maps gets called with it matching keyfor example if i havecint int float stdstring cand i calledcfoo1 2 33 qwertythen cmaps should be equivalent tom1 stdmapint intm11 1m2 stdmapint intm22 1m3 stdmapfloat intm3 1m4 stdmapstdstring intm4qwerty 1cmaps stdmake tuplem1 m2 m3 m4,['c++'] +1158429,android studio unable to run avd i am getting below erroremulator error unfortunately there is an incompatibility between haxm hypervisor and virtualbox 4330 which does not allow multiple hypervisors to coexist it is being actively worked on you can find out more about the issue at android and virtualbox internal error initial hax sync failedwhile it say work is under going i can run studio on my collegues machine with same oswin 7 and same machine specsis there a work around this issue currently,['android'] +1158542,detecting circles without using hough circles i have an image of a circle i want to find the circle but not using hough circlesi found a way linked here but i cannot find the transition coordinates from white to black as i do not know the x and y coordinates in the circle what other methods are there or how can i make that approach workthis is my test image,['c++'] +1158599,heroku not showing scss background images i have a rails app that uses background images from a stylecscss file i have found multiple ways of having the images show up on localhost but no ways to get them to thisplay on heroku i have looked at many posts on so like this and this as well as other sites like this but nothing has worked so farhere is the code i have in my stylecscsshero0 width 102 background urlassetpathhero0jpg norepeat center center fixed webkitbackgroundsize cover mozbackgroundsize cover obackgroundsize cover backgroundsize coverhowever i have also tried backgroundimage imageurl asseturl and numerous other permutations as found in the linked so postsi have this in my productionrb file configserve static files true configaction thispatchx sendfile header xaccelredirect configassetscompile true configassetsdigest trueand this in my applicationhtmlerb file to call the css sheet stylesheet link tag application media all dataturbolinkstrack true as suggested by other posts i have added this to my applicationrbconfigassetsinitialize on precompile falseany ideas on how this can be resolved would be happily receivedadditional infoheres my gemfilesource gem rails 425group production do gem pg gem rails 12factorendgroup development do gem sqlite3 gem binding of caller gem better errorsendgem sassrails 50gem uglifier 130gem coffeerails 410gem jqueryrailsgem turbolinksgem bcrypt 317gem bootstrapsassgem friendly id 510gem googleanalyticsrails 110gem paperclipgem metatagsgem bootsygem devisehere are my console errors in localhostand in heroku,"['css', 'ruby-on-rails']" +1158747,laravel 52 how to logout a user from all of his devices when a user logged out from a perticular device i want to logout from all the device he has logged in till now how i do it in laraveli have used rethis for keeping the userid in session by installing prethisprethis 10and here is my controller for signin and logout public function postsigninrequest request if authattemptemail requestemail password requestpassword rethis rethisconnection useridsessiongetid rethissadduserssessionsuseridsessiongetid return redirectroutemain return redirectback public function getlogout rethis rethisconnection useridsessiongetid usersessions rethissmembersusersessions userid currentsession sessiongetid foreach usersessions as sessionid if currentsession sessionid continue rethissremusersessions userid sessionid rethisdellaravel sessionid authlogout return redirectroutemainit is successfully get logged in and also logged out but it does not kill all the session in other deviceshow do i solve the problem,['php'] +1158760,uialertcontroller custom font does not work at ios uialertcontroller custom font does not workthe following code is a function showactionsheetasync show actionsheetat this point i want to change the font of actionsheet i have tried several ways but it did not work well is there good solution public taskbool showactionsheetasync var source new taskcompletionsourcebool var alert new uialertcontroller title title alertaddactionuialertactioncreate button1 uialertactionstyledefault sourcesetresulttrue alertaddactionuialertactioncreate cancel uialertactionstylecancel sourcesetresultfalse block 1 var viewcontroller uiapplicationsharedapplicationkeywindowrootviewcontroller viewcontrollerpresentviewcontrolleralert true delegate block 2 block 3 return sourcetaskfirst attemptthe following code does not work properlywhen i put the code on block 1 or block 2it does not work at allwhen i put the code on block 3applies only when the first show actionsheet from the second times it does not work uilabelappearancewhencontainedintypeofuiactionsheetfont uifontfromnamestyleresourcesmediumfontname 20the second attemptthe following code also does not work properlywhen i put the code on block 2after showing the default font for a short time showing the custom fontwhen i put the code on block 3it work on only cancel buttonfinddescendantviewsuilabel is a extension method for uiview and returns all child view of appropriate typevar labels alertviewfinddescendantviewsuilabelforeach var label in labels labelfont uifontfromnamestyleresourcesmediumfontname 20,"['c#', 'ios']" +1158820,minimize code repeatednesses when calling stored procedures i am using a certain method body to call stored procedures with the following sample code public void storedprocedurethatisbeingcalledint variable 1 int variable 2 out dataset ds using sqlconnection con new sqlconnectiondatabaseconnectionstring ds new datasetdstogoout using sqlcommand cmd new sqlcommandstoredprocedurethatisbeingcalled dbconnobjconn cmdcommandtype commandtypestoredprocedure cmdparametersaddnew sqlparametervariable 1 variable 1 cmdparametersaddnew sqlparametervariable 2 variable 2 try conopen sqldataadapter objdataadapter new sqldataadapter objdataadapterselectcommand cmd objdataadapterfillds conclose catch exception ex sql log err what bugs me i have most of the above code repeating time and time again in my cs file for every different procedure i callobviously i can clear it up and have the one function being called with the procedure name as a variable but how do i feed it different number of parameters with different data types intstring bool never anything else for the different procedures i use i can have few different functions with different number of parameters010 but i feel there is a better way of doing this,"['c#', 'asp.net']" +1158872,why mmap a 4gb file on 32bit armv7l succeeded i had the impression from the mmap2 man page and search results that mmap is only limited to systems available address spaces minus the system reserved address spaces so on 32bit armv7l i assume it is around 3gb 4gb 1gbbut it seemed like i could actually mmap a 5 gb file without any problemint mainint argc char argv stats char path argv1 struct stat sb statpath sb stdcout file size sbst size stdendl open int fd openpath o rdonly s irwxu stdcout file descriptor fd stdendl int i for i 0 i10 i void pa mmap nullptr sbst size prot read map private map anonymous fd 0 stdcout pa pa map failed pa map failed status strerrorerrno stdendl compile with d file offset bits64 flagg d file offset bits64 testccand the result yieldsfile size 5045966585file descriptor 3pa 0x89f80 map failed 0 status successpa 0x5d34a0 map failed 0 status successpa 0x307140 map failed 0 status successpa 0x3ade0 map failed 0 status successpa 0xf map failed 1 status cannot allocate memorypa 0xf map failed 1 status cannot allocate memorypa 0xf map failed 1 status cannot allocate memorypa 0xf map failed 1 status cannot allocate memorypa 0xf map failed 1 status cannot allocate memorypa 0xf map failed 1 status cannot allocate memoryfrom the results mmap succeeded for 4 times before going into real troubles but it should not have been succeeded since the file is 5gbmy questions would beis this behavior expected for mmapif not where did i do wrongeditwith physical addres extension pae 32bit systems can addres much more than 232 bytes if that is availablethere is no pae support for this cpu cat proccpuinfoprocessor armv7 processor rev 4 v7lprocessor 0bogomips 143646processor 1bogomips 143646features swp half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt cpu implementer 0x41cpu architecture 7cpu variant 0x0cpu part 0xc07cpu revision 4hardware sun7irevision 0serial 09c11b9d52544848804857831651664b,['c++'] +1158891,last accessed time of any file in android filelastmodified returns the last modified date file does not seem to have any method to fetch lastaccessed date is there a way to programmatically fetch the last accessed datetime of any file in android,['android'] +1159136,pdfwriter118libpdfwriterrb712 invalid multibyte char usascii i am using ruby version 193 and getting error when i start thin server usrlocallibrubygems191gemsbundler1124libbundlerruntimerb100in require usrlocallibrubygems191gemspdfwriter118libpdfwriterrb712 invalid multibyte char usascii syntaxerrorusrlocallibrubygems191gemspdfwriter118libpdfwriterrb712 invalid multibyte char usasciiusrlocallibrubygems191gemspdfwriter118libpdfwriterrb712 syntax error unexpected end expecting keyword end content pdfversionnan from usrlocallibrubygems191gemsbundler1124libbundlerruntimerb100in rescue in block in require from usrlocallibrubygems191gemsbundler1124libbundlerruntimerb77in block in require from usrlocallibrubygems191gemsbundler1124libbundlerruntimerb70in eachi got solution from here pdfwriter invalid multibyte char usascii expecting keyword end content pdfversionnaaIOn rails 3i have changed my gemfile pdfwriter to gem pdfwriter git gitgithubcommetaskillspdfwritergitnow when i run bundler to install the pdfwriter gem i get timeout error as belowgithubcom0 19230252123 errnoconnection timed outfatal unable to connect a socket connection timed outretrying git clone gitgithubcommetaskillspdfwritergit usrlocallibrubygems191cachebundlergitpdfwriterce9b6a7a72845526358421df643f35691567f bare nohardlinks quiet due to error 44 bundlersourcegitgitcommanderror git error command git clone gitgithubcommetaskillspdfwritergit usrlocallibrubygems191cachebundlergitpdfwriterce9b6a7a72845526358421df643f35691567f bare nohardlinks quiet in directory appshours report 3current has failedgithubcom0 19230252123 errnoconnection timed outfatal unable to connect a socket connection timed outgit error command git clone gitgithubcommetaskillspdfwritergitusrlocallibrubygems191cachebundlergitpdfwriterce9b6a7a72845526358421df643f35691567f bare nohardlinks quiet in directoryappsmy dashboardcurrent has failed,"['ruby-on-rails', 'ruby']" +1159280,how to preprocess source files while a sphinx run i have set up a sphinx documentation for my project and would like to extract doc strings for the source files and embed them into the final documentation unfortunately the source files language vhdl is not supported by sphinx there seems to be no sphinx domain for vhdlso my ideas is as followshook into the sphinx run and execute some python code before sphinxthe python codes extracts text blocks from each source file the topmost multiline comment block and assembles one rest file per source file consisting of this comment block and some other rest markupall source files are listed in an indexrst to generate the apropriate toctree directivethe text extraction and transformation is done recursively per source code directoryso the main question is how to hook into spinxor should i just import and run my own configuration in confpyusrbinenv python3 coding utf8 from my preprocessor import my procproc my procprocrun test documentation build configuration file created by sphinxquickstart on tue may 24 112820 2016 i cannot modify the build process files makefile and makebat because the real build process runs on readthedocsorg rtds only executes confpy,['python'] +1159492,what will be the sideloading and debugging mechanism for android apps on chromeos i have gone through everything on and also watched the io video and there does not seem to be any mention of what the sideloading and debugging mechanism available for developingtesting android apps on chromeos will bei know that arc used adb on desktops but not chromebooksgiven that the new implementation is different and its a full android framework in a linux container and has access to usb will adb be available for this prupose using adb could also be useful for remote debugging since devtools already runs an adb clienteditas of 9 aug 2016 there is now official documentation available,['android'] +1159824,deprecated struct members c gcc 611 gives me a deprecated declaration warning on the c codestruct foo attribute deprecated static const int a 1depcpp18 warning afooaa is deprecated wdeprecateddeclarations struct foo depcpp350 note declared here attribute deprecated static const int a 1the documentation says that the deprecated attribute results in a warning if the variable is used anywhere in the source fileas the warning points to the first line struct foo does that mean that the warning is raised because the struct is using the deprecated memberis there a way to use the deprecated attribute for static const struct membersgcc 493 does not seem to give this warning,['c++'] +1159948,aspnet core rc2 configure custom appsettings say i put the settings below in appsettingsjsonmysettings smtphost smtpmydomaincom webservice httplocalhost1337and i have the class below to hold those settingspublic class mysettings public string smtphost get set public string webservice get set with rc1 i would use the line of code below in the configureservices method to load those configuration settingsservicesconfiguremysettingsconfigurationgetsectionmysettingsbut in rc2 that same line of code gives me this errorcannot convert from microsoftextensionsconfigurationiconfigurationsection to systemactionmysettings,['asp.net'] +1159984,is it possible for a service worker to permanently break a website imagine you make service worker that implements an offline first strategy the typical use case for service workers and you deploy it to production but it has a bug the bug means that it never actually checks with the origin server for updates even to itself so after the service worker is registered for a given client on their first visit that client would never see any update to that website again unless the user manually unregisters the service worker using chromeserviceworkerinternals or something in other words the site is broken forever for those usersis the above scenario possible if so is there a strategy for making sure it never happens,['javascript'] +1160029,is it possible to check if const value is known at compile time currently i am rewritingextending my c utility library taking new c11 features into account one of the new additions is a template class which gives the maximum value of a set of numbers hopefully at compile timetemplatetypename t t xs class constmaxprivate templatetypename ts static constexpr t maxts xs templatetypename tx static constexpr t maxtx x return x templatetypename t1 typename t2 typename ts static constexpr t maxt1 x t2 y ts xs return y x maxt2 tsy xs maxt1 tsx xs public static const t value maxxsan example use of this classint max constmaxint 1 8 66 32 90 12 33valuehere another example which might make it harder to verify if constmaxvalue was actually evaluated during compile timetemplatetypename ts class variantpublic static const size t maxvaluesize constmaxsize t sizeoftsvaluewhich results in max 90 i stepped trough this code using gdb and it seems there is no function call executed during the assignment of maxmy questionscan i safely assume that constmaxvalue is always known at compile timeis there a way to check if constexpr functionsmethods are evaluated at compile timei understand membersmethodsfunctions defined as constexpr are not necessarily evaluated during compile time does the fact that value is defined as being static const change anything about this or am i better off implementing this specific case as a recursive template class,['c++'] +1160221,keeping function call signatures consistent for a function that accepts a superset of another functions arguments i have a function foo that is a convenience function wrapper for another function bar foo calls bar then performs another couple of tasks on the output for exampledef barbar arg bar kwnone do some stuff return retdef foobar arg foo arg bar kwnone foo kwnone ret barbar arg bar kw retsome methodfoo arg foo kwfoo kwi would like the call signature for foo to contain the keywords and arguments from bar so that a user inspecting foo knows what they can pass however i would like to avoid maintaining the full list of arguments myself since bar tends to change as the package it comes from is updated and its argument list is long since foo always calls bar with the full list of arguments and keywords that bar accepts i do not see that i should need to maintain the list myselfis there a way to build the call signature for foo based on the call signature for bar additionally is there a way to capture the inputs to foo in a dictionary or namespace so that i can easily separate the arguments and keywords used by foo from those used by barnote i know about args and kwargs they leave the function signature ambiguous though and do not inform the user of what arguments and keyword arguments are allowededit i should note that my use case is significantly more complex than this example the external function being called bar is matplotlibcolorbarcolorbarbase the calling function foo is a class method for a plotting class that is used in numerous applications of my own that others are likely to use in the future foo creates a colorbar then performs additional work on the colorbar based on additional arguments and keywords that are not accepted by colorbarbase,['python'] +1160231,ambiguity in a fully qualified static member variable in this sample code there is two sentences showing the same static variable the first one gives no ambiguity but the second one does whyinclude iostreamusing namespace stdstruct a static const char a a struct b public a struct c public a struct g public b public c int main g v cout gbaa endl cout vbaa endlgcc error according to some comments there is no ambiguity in clangmaincpp1518 error a is an ambiguous base of g cout vbaa endlcode on coliru,['c++'] +1160352,method parametrized with one type accepts two types probably i am missing something and maybe my assumptions were wrong but i thought that when i declare parametrized method with type t then no matter how much variables there are with that type it is still the same type but i see that this compiles and it oposses my viewstatic t void ft a t b public static void mainstring args fintegermin value so if my method is parametrized with one type and i am using that one type in two paramteres why does it allow me to send two objects with two totally different types i guess it comes down to treating t as object,['java'] +1160703,firebase when receive push notification did not receive the popup import firebaseimport firebaseinstanceidimport firebasemessagingfunc applicationapplication uiapplication didfinishlaunchingwithoptions launchoptions nsobject anyobject bool registerforpushnotificationsapplication firappconfigure add observer for instanceid token refresh callback nsnotificationcenter defaultcenter addobserverself selector selectorappdelegatetokenrefreshnotificaiton name kfirinstanceidtokenrefreshnotification object nil override point for customization after application launch return true func registerforpushnotificationsapplication uiapplication let settings uiusernotificationsettings uiusernotificationsettingsfortypes alert badge sound categories nil applicationregisterusernotificationsettingssettings applicationregisterforremotenotifications func applicationapplication uiapplication didreceiveremotenotification userinfo nsobject anyobject fetchcompletionhandler completionhandler uibackgroundfetchresult void print didreceiveremotenotification userinfo func tokenrefreshnotificaitonnotification nsnotification let refreshedtoken firinstanceidinstanceidtoken printinstanceid token refreshedtoken connect to fcm since connection may have failed when attempted before having a token connecttofcm func connecttofcm firmessagingmessagingconnectwithcompletion error in if error nil printunable to connect with fcm error else printconnected to fcm also to done in infoplist firebaseappdelegateproxyenabled noi do not know for now but i got the print in didreceiveremotenotification but do not get the popup i send the message from firebase console notification single device and copy here the token which i got from xcode console func tokenrefreshnotificaitonget the next in console but do not get popupfiranalyticsinfo firebase analytics enabledinstanceid token token idconnected to fcm didreceiveremotenotification notification body test e 1 collapse key compfapp from 178653764278also app configurations,['ios'] +1160858,flyway repair with spring boot i do not quite understand what i am supposed to do when a migration fails using flyway in a spring boot projecti activated flyway by simply adding the flyway dependency in my pomxml and everything works fine my database scripts are migrated when i launch the spring boot appbut i had an error in one of my scripts and my last migration failed now when i try to migrate there is a migration checksum mismatch normally i would run mvn flywayrepair but since i am using spring boot i am not supposed to use the flyway maven plugin so what am i supposed to do,['java'] +1161218,what is asymptotic complexity of listadd i have found that there is a lot of controversy about asymptotic complexity of listadd the source of it i suspect is the worst case scenario that causes underlying array to resize and would logically be on operation however the array grows twice in size each time list runs out of space that makes amount of resizes needed for n elements be proportional to logndoes not that mean that asymptotic complexity of add operation in average case will be onlognthe real benchmark for listadd is below however benchmarks are not really expressive for such operation we might be running out of memory prior to any deviation from straight in logarithmic scale line becomes visible,['c#'] +1161406,image upload not working always get the false value ui image upload part is not working i want to upload image path in database but not working and not bind correctly cannot save it can you please help me table to thisplayed upload image value is always false aspxasptemplatefield headertextimages itemtemplate aspfileupload runatserver autopostbacktrue idfileupload commandargument evalstrimage clientidmodestatic itemtemplateasptemplatefieldasptemplatefield headertext itemtemplate aspimage imageurluploaded imagesdefaultpng runatserver idimage width40 height40 itemtemplateasptemplatefieldcode region detail save1 private datatable createdetailsave datatable dtdetailsave1 new datatable datacolumn dc1 dc1 new datacolumnintarticledetailid dtdetailsave1columnsadc1 dc1 new datacolumnintsectionid dtdetailsave1columnsadc1 dc1 new datacolumnintcompoundid dtdetailsave1columnsadc1 dc1 new datacolumndecsectionweight dtdetailsave1columnsadc1 dc1 new datacolumnintmessageid dtdetailsave1columnsadc1 dc1 new datacolumnstrimage dtdetailsave1columnsadc1 foreach gridviewrow row in gvarticlerows datarow dr dtdetailsave1newrow label lblintarticledetailid labelrowfindcontrollblarticledetailid label lblsectionid labelrowfindcontrollblsectionid dropdownlist ddlcompound dropdownlistrowfindcontrolddlcompoundid textbox txtdecsectionweighte textboxrowfindcontroltxtdecsectionweighte dropdownlist intmessage dropdownlistrowfindcontrolddlmessage fileupload fileupload fileuploadrowfindcontrolfileupload drintarticledetailid currentmode add 1 converttoint32lblintarticledetailidtext drintsectionid converttoint32lblsectionidtext drintcompoundid ddlcompoundselectedvalue drdecsectionweight txtdecsectionweightetexttrim converttodecimaltxtdecsectionweightetexttrim 0 drintmessageid intmessageselectedvalue drstrimage fileuploadhasfile dtdetailsave1rowsadr return dtdetailsave1 endregion region pageload protected void page loadobject sender eventargs e if ispostback clearcontrols fillarticledetails enablecontrolsfalse sessionsearchpopup false else if sessionsearchpopup null searchpopup boolsessionsearchpopup if searchpopup false mympeshow else mympehide vadsearchparalist new listsearchparametors endregion region create article table private void createarticledatatable if dtcolumnscount 0 dtcolumnsaddnew datacolumnintarticledetailid typeofint dtcolumnsaddnew datacolumnintsectionid typeofint dtcolumnsaddnew datacolumnstrsectionname typeofstring dtcolumnsaddnew datacolumnintcompoundid typeofstring dtcolumnsaddnew datacolumndecsectionweight typeofstring dtcolumnsaddnew datacolumnintmessageid typeofstring dtcolumnsaddnew datacolumnfileupload typeofstring gvarticledatasource dt gvarticledatabind endregion region compound grid add empty row private void articlegridaddemptyrowint newid datarow newdr null newdr dtnewrow newdrintarticledetailid 1 newdrintsectionid 1 newdrstrsectionname newdrintcompoundid newdrdecsectionweight newdrintmessageid newdrstrimage dtrowsaddnewdr if dtarticledetails null dtarticledetailsrowscount 0 dtarticledetails dt else dtarticledetailsmergedt gvarticledatasource dt gvarticledatabind endregionprotected void gvarticle rowupdatingobject sender gridviewupdateeventargs e gridviewrow row gvarticlerowserowindex fileupload fu rowcells0findcontrolstrimage as fileupload if fu null fuhasfile fusaveasservermappathuploaded images fufilename full aspx aspgridview idgvarticle showheaderwhenemptytrue cssclasstable tablebordered tablecondensed tablehover autogeneratecolumnsfalse runatserver allowpagingtrue pagesize15 onrowdataboundgvarticle rowdatabound backcolorwhite bordercolorc borderstylenone borderwidth1px cellpadding4 forecolorblack gridlineshorizontal onrowupdatinggvarticle rowupdating headerstyle backcolor3d4247 forecolorwhite columns asptemplatefield headertextintarticledetail visiblefalse itemtemplate asplabel idlblarticledetailid width2 text bindintarticledetailid clientidmodestatic runatserverasplabel itemtemplate asptemplatefield asptemplatefield headertextsectionid visiblefalse itemtemplate asplabel idlblsectionid width2 text bindintsectionid clientidmodestatic runatserverasplabel itemtemplate asptemplatefield asptemplatefield headertextsection itemtemplate asplabel idlblsectionname width100 text bindstrsectionname clientidmodestatic runatserverasplabel itemtemplate asptemplatefield asptemplatefield headertextcompound edititemtemplate asplabel idlblitemtypeedit width50 text bindstrcompoundname lientidmodestatic autopostbacktrue runatserver asplabel edititemtemplate itemtemplate aspdropdownlist idlcompoundid width200 cssclassformcontrol mydropdownthin lientidmodestatic autopostbacktrue runatserver aspdropdownlist itemtemplate asptemplatefield asptemplatefield headertextweight itemtemplate asptextbox idtxtdecsectionweighte width100 text binddecsectionweight lientidmodestatic runatserver asptextbox itemtemplate asptemplatefield asptemplatefield headertextmessagers itemtemplate asptextbox idtxtmessage width100 text bindintmessageid clientidmodestatic runatserverasptextbox itemtemplate asptemplatefield asptemplatefield headertextmessagers edititemtemplate asplabel idlblmessageid width50 text bindstrmessage clientidmodestatic autopostbacktrue runatserver asplabel edititemtemplate itemtemplate aspdropdownlist idlmessage width300 cssclassformcontrol mydropdownthin lientidmodestatic autopostbacktrue runatserver aspdropdownlist itemtemplate asptemplatefield asptemplatefield headertextimages itemtemplate aspfileupload runatserver autopostbacktrue iduploadfimage commandargument evalstrimage clientidmodestatic itemtemplate asptemplatefield asptemplatefield headertext itemtemplate aspimage imageurluploaded imagesdefaultpng runatserver idbtnviewfimage width40 height40 itemtemplate asptemplatefield columns footerstyle backcolorc99 forecolorblack headerstyle backcolor3 fontboldtrue forecolorwhite pagerstyle backcolorwhite forecolorblack horizontalalignright selectedrowstyle backcolorcc3 fontboldtrue forecolorwhite sortedascendingcellstyle backcolorf7f7f7 sortedascendingheaderstyle backcolor4b4b4b sorteddescendingcellstyle backcolore5e5e5 sorteddescendingheaderstyle backcolor242121 aspgridview div contenttemplate triggers asppostbacktrigger controlidgvarticle triggers aspupdatepanel div divgvarticle rowdataboundprotected void gvarticle rowdataboundobject sender gridviewroweventargs e if erowrowtype datacontrolrowtypefooter else if erowrowtype datacontrolrowtypedatarow datatable compoundcode clsarticlecompounddataforgrid dropdownlist ddlcompoundid dropdownlisterowfindcontrolddlcompoundid if ddlcompoundid null ddlcompoundiddatatextfield compound code ddlcompoundiddatavaluefield compound id ddlcompoundiddatasource compoundcode ddlcompoundiddatabind string country erowfindcontrolddlcompoundid as dropdownlisttext ddlcompoundiditemsfindbyvaluecountryselected true datatable msgcode clsarticlemessagedataforgrid dropdownlist ddlmessage dropdownlisterowfindcontrolddlmessage if ddlmessage null ddlmessagedatatextfield message name ddlmessagedatavaluefield message id ddlmessagedatasource msgcode ddlmessagedatabind ddlmessageitemsinsert0 new listitemplease select string country erowfindcontrolddlmessage as dropdownlisttext ddlmessageitemsfindbyvaluecountryselected true,"['c#', 'asp.net']" +1161421,algolia browse function returning max 10 records using javascript i am using algolia javascript api for retrieving all records in my index using browse function but still it is returning 10 records here is my codefunction load location listvar client algoliasearchid keyvar index name locations newvar attribute list var index clientinitindexindex nameindexbrowse attributestoretrieve attribute listthenfunction search successresponse consolelogresponse,['javascript'] +1161744,android ussd which sim receive a ussd message or which sim slot receives a ussd message dual sim phone i am able to capture the incoming ussd message but how to compare the incoming ussd message in case of dual sim phone if i receive a ussd message alert how can i know that the incoming ussd message is for which sim,['android'] +1161832,can an unsigned integer addition invoke undefined behavior edit changed the value for ushrt max as it was not conformant as shown by commentsimagine you have a fancy compiler where its integer type limits as defined in limitsh aredefine int max 2147483647 typical 32bit system value define ushrt max 2147483647 edited original question had 20 and in my application i have the following codeunsigned short a 150unsigned short b 150unsigned short cc a bas far as i know what will happen in the last instruction will beintegral promotion on a as int can take all values of unsigned short a gets promoted to intfor the same reasons b gets promoted to intaddition happens on int typesthe result is not representable in int undefined behavior due to paragraph 655is my reasoning correct does this really invoke undefined behavior or where did i go wrong note that my code only works with unsigned types and a result applying the modulus for unsigned integers could be expected due to legal overflow on unsigned typesif the answer to the previous question is yes undefined behavior this happened for a legal conformant compiler so can you say that the application code i posted is incorrect do all nonexplicitlycasted small unsigned integer additions potentially invoke undefined behavior,['c'] +1161839,how to find probability thistribution and parameters for real data python 3 i have a dataset from sklearn and i plotted the thistribution of the load diabetestarget data ie the values of the regression that the load diabetesdata are used to predict i used this because it has the fewest number of variablesattributes of the regression sklearndatasetsusing python 3 how can i get the thistributiontype and parameters of the thistribution this most closely resembles all i know the target values are all positive and skewed positve skewright skew is there a way in python to provide a few thistributions and then get the best fit for the target datavector or to actually suggest a fit based on the data that is given that would be realy useful for people who have theoretical statistical knowledge but little experience with applying it to real data bonuswould it make sense to use this type of approach to figure out what your posterior thistribution would be with real data if no why notfrom sklearndatasets import load diabetesimport matplotlibpyplot as pltimport seaborn as sns snssetimport pandas as pdget datadata load diabetesx y datadata datatargetorganize datasr y pdseriesy namey target vector thistributionplot datafig ax pltsubplotssnsthistplotsr y bins25 colorg axaxpltshow,['python'] +1161990,complexity of stdcount i was in some online code quiz website where there is a complexity restriction that the code should not exceed on in both time and memory where n is the size of the vector a my code was exactly full codeint fooint x const stdvectorint a auto and asize auto total hit stdcountacbegin acend x auto k and total hit if k 0 k n return 1 return ki got a result that i exceed the time complexity is there any possibility rather than they are wrong,['c++'] +1162184,floatingactionbutton with animated icon i am trying to create a floatingactionbutton with an icon like this as you can see the button is animated it is not just two different buttons who are changedhere is my actual basic floatingactionbutton with a static icon androidsupportdesignwidgetfloatingactionbutton androidlayout heightwrap content androidlayout widthwrap content applayout anchoridappbar applayout anchorgravitybottomrightend androidsrcdrawableic favorite border white 24dp androidlayout margindimenfab margin androidclickabletruei do not want to just change the icon i would like to make an animation when i click on ithere is the button i need but in this case it is not included in the floatingactionbutton comlikelikebutton androidididlike button androidlayout height32dp androidlayout width32dp appicon typeheart appcircle start colorcolorred applike drawabledrawableic favorite white 24dp appunlike drawabledrawableic favorite border white 24dp appdots primary colorcolororange appdots secondary colorcolorred appcircle end colorcolororange appicon size24dp appanim scale factor1to sum up i know how to do a floatingactionbutton with a static iconi know how to create an animated like buttoni do not know how to mix steps 1 and 2 to create a floatingactionbutton with an animated icon on clicka famous shopping app is doing it but i do not know how,['android'] +1162376,how to create dynamic rows of records for creating xls file using list here after fetching records from database i have added data in some list and i have set some session variables for them so that i can access in another method by using getkey method of session which i am successful to do so now what i want is i want to create dynamic records by setting this list value in row but i am unable to do soit creates file but there is no record thisplayed below is my code package comcaactionsimport javaiofilenotfoundexceptionimport javaiofileoutputstreamimport javasqlconnectionimport javasqlpreparedstatementimport javasqlresultsetimport javasqlsqlexceptionimport javautilarraylistimport javautillistimport javautilmapimport orgapachepoihssfusermodelhssfrowimport orgapachepoihssfusermodelhssfsheetimport orgapachepoihssfusermodelhssfworkbookimport orgapachestruts2thispatchersessionmapimport orgapachestruts2interceptorsessionawareimport comcadatabasedatabaseimport comcapojoeventimport comitextpdftextdocumentimport comitextpdftextelementimport comitextpdftextpagesizeimport comitextpdftextparagraphimport comitextpdftextphraseimport comitextpdftextpdfpdfpcellimport comitextpdftextpdfpdfptableimport comitextpdftextpdfpdfwriterimport comopensymphonyxwork2actionsupportimport comopensymphonyxwork2preparablepublic class dataforgeneralreportsaction extends actionsupport implements preparable sessionaware private liststring eventsgeneral new arrayliststring private liststring companiesgeneral new arrayliststring private sessionmapstring object sessionmapgeneral liststring eventidlist new arrayliststring liststring eventnamelist new arrayliststring liststring eventvenuelist new arrayliststring liststring eventtimelist new arrayliststring liststring companynamelist new arrayliststring liststring totalamountlist new arrayliststring liststring receivedamountlist new arrayliststring liststring balanceamountlist new arrayliststring liststring eventtdslist new arrayliststring liststring paymentdatelist new arrayliststring liststring chequeddlist new arrayliststring private string eventgeneral null private string companygeneral null listevent dataforgeneralreports public liststring geteventidlist return eventidlist public void seteventidlistliststring eventidlist thiseventidlist eventidlist public liststring geteventnamelist return eventnamelist public void seteventnamelistliststring eventnamelist thiseventnamelist eventnamelist public liststring geteventvenuelist return eventvenuelist public void seteventvenuelistliststring eventvenuelist thiseventvenuelist eventvenuelist public liststring geteventtimelist return eventtimelist public void seteventtimelistliststring eventtimelist thiseventtimelist eventtimelist public liststring getcompanynamelist return companynamelist public void setcompanynamelistliststring companynamelist thiscompanynamelist companynamelist public liststring gettotalamountlist return totalamountlist public void settotalamountlistliststring totalamountlist thistotalamountlist totalamountlist public liststring getreceivedamountlist return receivedamountlist public void setreceivedamountlistliststring receivedamountlist thisreceivedamountlist receivedamountlist public liststring getbalanceamountlist return balanceamountlist public void setbalanceamountlistliststring balanceamountlist thisbalanceamountlist balanceamountlist public liststring geteventtdslist return eventtdslist public void seteventtdslistliststring eventtdslist thiseventtdslist eventtdslist public liststring getpaymentdatelist return paymentdatelist public void setpaymentdatelistliststring paymentdatelist thispaymentdatelist paymentdatelist public liststring getchequeddlist return chequeddlist public void setchequeddlistliststring chequeddlist thischequeddlist chequeddlist public sessionmapstring object getsessionmapgeneral return sessionmapgeneral public void setsessionmapgeneral sessionmapstring object sessionmapgeneral thissessionmapgeneral sessionmapgeneral public string geteventgeneral return eventgeneral public void seteventgeneralstring eventgeneral thiseventgeneral eventgeneral public string getcompanygeneral return companygeneral public void setcompanygeneralstring companygeneral thiscompanygeneral companygeneral public listevent getdataforgeneralreports return dataforgeneralreports public void setdataforgeneralreportslistevent dataforgeneralreports thisdataforgeneralreports dataforgeneralreports public liststring geteventsgeneral return eventsgeneral public void seteventsgeneralliststring eventsgeneral thiseventsgeneral eventsgeneral public liststring getcompaniesgeneral return companiesgeneral public void setcompaniesgeneralliststring companiesgeneral thiscompaniesgeneral companiesgeneral public dataforgeneralreportsaction todo autogenerated constructor stub override public void prepare throws exception todo autogenerated method stub connection con null try con new databaseget connection load companies preparedstatement ps con preparestatementselect thistinct company name from event resultset rs psexecutequery while rsnext companiesgeneraladdrsgetstringcompany name load events ps conpreparestatementselect thistinct event name from event rs psexecutequery while rsnext eventsgeneraladdrsgetstringevent name catch exception e eprintstacktrace finally conclose override public string execute throws exception connection con null try con new databaseget connection load the table the first time the table is loaded completely string sql select event id event name company nameevent venuetotal amountreceived amountevent tdsbalance amountcheque dd no date formatpayment datedmy as dateaspaymentevent time from event string where if instead this action has been called from the jsp page the result is filtered on event and company if eventgeneral null companygeneral null where where event name and company name load companies preparedstatement ps conpreparestatementsql where if wherelength 0 pssetstring1 eventgeneral pssetstring2 companygeneral dataforgeneralreports new arraylistevent resultset rs psexecutequery int i j 0 while rsnext dataforgeneralreportsaddnew eventrsgetstringevent id rsgetstringevent name rs getstringcompany name rs getstringevent venue rs getstringevent time rs getstringtotal amount rs getstringreceived amount rs getstringcheque dd no rs getstringdateaspayment rs getstringbalance amount rs getstringevent tds eventidlistaddrsgetstringevent id eventnamelistaddrsgetstringevent name companynamelistaddrsgetstringcompany name eventvenuelistaddrsgetstringevent venue eventtimelistaddrsgetstringevent time totalamountlistaddrsgetstringtotal amount receivedamountlistaddrsgetstringreceived amount chequeddlistaddrsgetstringcheque dd no paymentdatelistaddrsgetstringdateaspayment eventtdslistaddrsgetstringevent tds balanceamountlistaddrsgetstringbalance amount sessionmapgeneralputeventidpdf eventidlist sessionmapgeneralputeventnamepdf eventnamelist sessionmapgeneralputcompanynamepdf companynamelist sessionmapgeneralputeventvenuepdf eventvenuelist sessionmapgeneralputeventtimepdf eventtimelist sessionmapgeneralputtotalamountpdf totalamountlist sessionmapgeneralputreceivedamountpdf receivedamountlist sessionmapgeneralputchequeddpdf chequeddlist sessionmapgeneralputpaymentdatepdf paymentdatelist sessionmapgeneralputeventtdspdf eventtdslist sessionmapgeneralputbalanceamountpdf balanceamountlist catch exception e eprintstacktrace finally conclose return success public string generatepdfgeneral throws exception systemoutprintlnsessionmapgeneralgeteventidpdf document document new documentpagesizea4 landscape 50 50 50 50 float columnwidths 4 5 5 5 5 5 5 5 5 5 5 pdfwriter writer pdfwritergetinstancedocument new fileoutputstreamdgeneralreportspdf pdfptable table new pdfptable11 tablesetspacingbefore25 tablesetwidthpercentage100 tablesetspacingafter25 tablesetwidthscolumnwidths pdfpcell c1 new pdfpcellnew phraseevent id c1sethorizontalalignmentelementalign center tableaddcellc1 c1 new pdfpcellnew phraseevent name c1sethorizontalalignmentelementalign center tableaddcellc1 c1 new pdfpcellnew phraseevent time c1sethorizontalalignmentelementalign center tableaddcellc1 c1 new pdfpcellnew phraseevent venue c1sethorizontalalignmentelementalign center tableaddcellc1 c1 new pdfpcellnew phrasecompany name c1sethorizontalalignmentelementalign center tableaddcellc1 c1 new pdfpcellnew phrasetotal amount c1sethorizontalalignmentelementalign center tableaddcellc1 c1 new pdfpcellnew phrasereceived amount c1sethorizontalalignmentelementalign center tableaddcellc1 c1 new pdfpcellnew phrasechequedd number c1sethorizontalalignmentelementalign center tableaddcellc1 c1 new pdfpcellnew phrasepayment date c1sethorizontalalignmentelementalign center tableaddcellc1 c1 new pdfpcellnew phraseevent tds c1sethorizontalalignmentelementalign center tableaddcellc1 c1 new pdfpcellnew phrasebalance amount c1sethorizontalalignmentelementalign center tableaddcellc1 tablesetheaderrows1 pdfpcell cell new pdfpcell liststring list liststring sessionmapgeneralgeteventidpdf for string item list celladdelementnew paragraphitem pdfpcell cell1 new pdfpcell liststring list1 liststring sessionmapgeneral geteventnamepdf for string item list1 cell1addelementnew paragraphitem tableaddcellcell1 pdfpcell cell2 new pdfpcell liststring list2 liststring sessionmapgeneral geteventtimepdf for string item list2 cell2addelementnew paragraphitem tableaddcellcell2 pdfpcell cell3 new pdfpcell liststring list3 liststring sessionmapgeneral geteventvenuepdf for string item list1 cell3addelementnew paragraphitem tableaddcellcell3 pdfpcell cell4 new pdfpcell liststring list4 liststring sessionmapgeneralgeteventidpdf for string item list4 cell4addelementnew paragraphitem tableaddcellcell4 pdfpcell cell5 new pdfpcell liststring list5 liststring sessionmapgeneral getcompanynamepdf for string item list5 cell5addelementnew paragraphitem tableaddcellcell5 pdfpcell cell6 new pdfpcell liststring list6 liststring sessionmapgeneral gettotalamountpdf for string item list6 cell6addelementnew paragraphitem tableaddcellcell6 pdfpcell cell7 new pdfpcell liststring list7 liststring sessionmapgeneral getreceivedamountpdf for string item list7 cell7addelementnew paragraphitem tableaddcellcell7 pdfpcell cell8 new pdfpcell liststring list8 liststring sessionmapgeneral getchequeddpdf for string item list8 cell8addelementnew paragraphitem tableaddcellcell8 pdfpcell cell9 new pdfpcell liststring list9 liststring sessionmapgeneral getpaymentdatepdf for string item list9 cell9addelementnew paragraphitem tableaddcellcell9 pdfpcell cell10 new pdfpcell liststring list10 liststring sessionmapgeneral geteventtdspdf for string item list10 cell10addelementnew paragraphitem tableaddcellcell10 pdfpcell cell11 new pdfpcell liststring list11 liststring sessionmapgeneral getbalanceamountpdf for string item list11 cell11addelementnew paragraphitem tableaddcellcell11 documentopen documentaddtable documentclose return success public string generategeneralxls throws exception try hssfworkbook workbook new hssfworkbook hssfsheet sheet workbookcreatesheetfirstsheet hssfrow rowhead sheetcreaterowshort 0 rowheadcreatecell0setcellvalueevent id rowheadcreatecell1setcellvalueevent name rowheadcreatecell2setcellvalueevent time rowheadcreatecell3setcellvalueevent venue rowheadcreatecell4setcellvaluecompany name rowheadcreatecell5setcellvaluetotal amount rowheadcreatecell6setcellvaluereceived amount rowheadcreatecell7setcellvaluepayment date rowheadcreatecell8setcellvaluechequedd no rowheadcreatecell9setcellvalueevent tds rowheadcreatecell10setcellvaluebalance amount fileoutputstream fileout fileout new fileoutputstreamdsamplmgjkmxls hssfrow row1 sheetcreaterowshort 1 systemoutprintlnsessionmapgeneralsize for int i 1 i sessionmapgeneralsize i hssfrow row1 sheetcreaterowshort i row1createcelli1setcellvalue sessionmapgeneralgeteventidpdftostring row1createcellisetcellvalue sessionmapgeneralgeteventnamepdftostring row1createcell1setcellvalue sessionmapgeneralgeteventnamepdftostring row1createcell1setcellvalue sessionmapgeneralgeteventnamepdftostring row1createcell1setcellvalue sessionmapgeneralgeteventnamepdftostring row1createcell1setcellvalue sessionmapgeneralgeteventnamepdftostring row1createcell1setcellvalue sessionmapgeneralgeteventnamepdftostring row1createcell1setcellvalue sessionmapgeneralgeteventnamepdftostring row1createcell1setcellvalue sessionmapgeneralgeteventnamepdftostring row1createcell1setcellvalue sessionmapgeneralgeteventnamepdftostring row1createcell1setcellvalue sessionmapgeneralgeteventnamepdftostring workbookwritefileout fileoutclose catch exception e eprintstacktrace return success override public void setsessionmapstring object map todo autogenerated method stub sessionmapgeneral sessionmap map i have edited my code where i get result in string but all records are thisplayed in single cell i want each record in new celli have attached image of how it looks no error is thisplayed please help me to solve my problem,['java'] +1162422,creating thistinctby using expression trees i wanted to create a method extending iqueryable where a user can specify in a string a property name by which he wants to thistinct a collection i want to use a logic with a hashseti basically want to emulate this codehashsettresult set new hashsettresultforeachvar item in source var selectedvalue selectoritem if setaddselectedvalue yield return itemusing expression treesthis is where i got so farprivate expression assemblethistinctblockexpression iqueryable queryable string propertyname var propinfo queryableelementtypegetpropertypropertyname if propinfo null throw new argumentexception var loopvar expressionparameterqueryableelementtype var selectedvalue expressionvariablepropinfopropertytype selectedvalue var returnlisttype typeoflistmakegenerictypequeryableelementtype var returnlistvar expressionvariablereturnlisttype return var returnlistassign expressionassignreturnlistvar expressionconstantactivatorcreateinstancetypeoflistmakegenerictypequeryableelementtype var hashsettype typeofhashsetmakegenerictypepropinfopropertytype var hashsetvar expressionvariablehashsettype set var hashsetassign expressionassignhashsetvar expressionconstantactivatorcreateinstancetypeofhashsetmakegenerictypepropinfopropertytype var enumeratorvar expressionvariabletypeofienumeratormakegenerictypequeryableelementtype enumerator var getenumeratorcall expressioncallqueryableexpression queryablegettypegettypeinfogetdeclaredmethodgetenumerator var enumeratorassign expressionassignenumeratorvar getenumeratorcall var movenextcall expressioncallenumeratorvar typeofienumeratorgetmethodmovenext var breaklabel expressionlabelloopbreak var loopblock expressionblock new enumeratorvar hashsetvar returnlistvar enumeratorassign returnlistassign hashsetassign expressiontryfinally expressionblock expressionloop expressionifthenelse expressionequalmovenextcall expressionconstanttrue expressionblock new loopvar expressionassignloopvar expressionpropertyenumeratorvar current expressionassignselectedvalue expressionmakememberaccessloopvar propinfo expressionifthen expressioncalltypeofhashset add new type propinfopropertytype hashsetvar selectedvalue expressioncalltypeoflist add new type queryableelementtype returnlistvar loopvar expressionbreakbreaklabel breaklabel expressionreturnbreaklabel returnlistvar expressionblock expressioncallenumeratorvar typeofithisposablegetmethodthispose return loopblock i get an exception when expressionblock is called for a variable loopblock which goes like thisno method add exists on type systemcollectionsgenerichashset1t,['c#'] +1162429,retina thisplay image resolution using media queries what is the best way to use media queries to both detect a retina thisplay and also specify maxwidth i can detect retina usingmediaonly screen and webkitmindevicepixelratio 2only screen and minmozdevicepixelratio 2only screen and omindevicepixelratio 21only screen and mindevicepixelratio 2only screen and minresolution 192dpionly screen and minresolution 2dppx how do i add it to the media queries do i write mediaonly screen and webkitmindevicepixelratio 2only screen and minmozdevicepixelratio 2only screen and omindevicepixelratio 21only screen and mindevicepixelratio 2only screen and minresolution 192dpionly screen and minresolution 2dppx media screen and maxwidth 20px holer backgroundurl or is there any better method for changing images for retina thisplays adding media queries for screen size to media queries for retina thisplay,['css'] +1162437,boost variant simple call to common methods i have two pointers that only one of them can be set so i am considering using boostvariant say boostvariantshared ptrtype1 shared ptrtype2 type 1 and 2 are different but they share some functionality thay for example both have the method isunique if i have the code to check the initialization asserttype1 nullptr type2 nullptrasserttype1 nullptr type2 nullptrasserttype1 nullptr type1isuniqueasserttype2 nullptr type2isuniquei would expect to be able to replace it with something as close as possible toassertvariant nullptrassertvariantisuniquebut it seems that i have to define visitors make switching on typesdo i miss something is there a template or something that will allow me to apply something to whatever the current type is it could be c14,['c++'] +1162558,mysql showing strange result i have a table called tabela1512823699024883 that looks like thison which i run query like thisselect from tabela1512823699024883 where age malethis query does not make sense because age column is int type and i am looking for string value in my query but mysql still returns no empty rows whatsoever here is what query returnedso age row does not contains male value in neither rows returned how can this be possible,"['php', 'mysql']" +1162659,c static member variable of class member instantiated twice i have a template class which has two static member variables one int and another an stdarrayvolatile uint fast32 t 8 when i instantiate the template with two different classes which are templates themselves as template parameters for one of the instantiations everything works perfectly ie there is exactly one copy of both variables however for the other the array appears in duplicate in the symbol table and indeed my code has a bug that when i set a value in the array in one compilation unit the change does not appear in anotherthis is for an embedded system which is the reason for this weird idiom of using static templates for a kind of compiletime polymorphismin code header declaring the class itselfdacmuxhnamespace hal templatetypename dac write sequence t unsigned int chans typename sample t uint fast32 tstruct dacmux private typedef stdarrayvolatile sample t chans chans t static chans t channels static unsigned int nextchanthe static variables defined herecount on the compilerlinker to make surethere is exactly one definitiontemplatetypename dac write sequence t unsigned int chans typename sample t typename dacmuxdac write sequence t chans sample tchans t dacmuxdac write sequence t chans sample tchannels0templatetypename dac write sequence t unsigned int chans typename sample t unsigned int dacmuxdac write sequence t chans sample tnextchan 0templatetypename dac t typename addr t typename en tstruct muxed setter templatetypename dac tstruct dac setter namespace hala header which thistributes definitions of the hardwarehardware typeshmultiplexer for the internal dactypedef haldacmuxhalmuxed setterdac1 mux1 addr mux1 en 8 mux1sequencer for writing the external dac valuestypedef haldacmuxhaldac setterextdac1 8 extdac sequencerthe header hardware typesh is included in two source files maincpp debugconsolecpp both of which use both mux1 and extdac sequenceras for as i understand based on answers such as this one and many others the compiler should take care that each of the static member variables is instantiated exactly once for each instantiation of the templatehowever when i set the values of extdac sequencerchannels in debugconsolecpp the changes are not reflected in an interrupt handler declared in maincpp the same works perfectly for mux1channels indeed an excerpt from the symbol table extracted from the elf by objdump t20280 l o bss 04 zn3hal6dacmuxins 10dac setterins 6ti dacins 3spiins 5spi 2en5gpios5pin tins6 1belj12ens 12 global and 110xx68 frameensa 12command xx68ensa 12channel xx68elj8eje8nextchane20254 l o bss 020 zn3hal6dacmuxins 10dac setterins 6ti dacins 3spiins 5spi 2en5gpios5pin tins6 1belj12ens 12 global and 110xx68 frameensa 12command xx68ensa 12channel xx68elj8eje8channelse20288 l o bss 020 zn3hal6dacmuxins 10dac setterins 6ti dacins 3spiins 5spi 2en5gpios5pin tins6 1belj12ens 12 global and 110xx68 frameensa 12command xx68ensa 12channel xx68elj8eje8channelse20234 w o bss 020 zn3hal6dacmuxins 12muxed setterin4dacs11dac channelilj1en5gpios5pin tins4 1aelj4ens4 12bit stripe tins4 1celj6elj3ens5 isa lj9elj8eje8channelse2027c w o bss 04 zn3hal6dacmuxins 12muxed setterin4dacs11dac channelilj1en5gpios5pin tins4 1aelj4ens4 12bit stripe tins4 1celj6elj3ens5 isa lj9elj8eje8nextchaneso the nextchan variable appears once per instantiation as it should and for mux1 so does channels however for extdac sequencer the channels variable is repeated which i believe explains the bugam i doing something wrong or is this a compiler or linker bugcompiler gcc armnoneeabi 521 20151202linker armnoneeabild 2259020151217linker options t memld t libsld t sectionsld nostartfiles xlinker gcsections lldscripts wlmapsynth1firmwaremap xlinker cref specsnanospecsupdatei have narrowed down the conditions for this to happenif the first template parameter of dacmux is not itself a template everything works ie no duplicate symbolstruct extdac1 setter templatetypename sample t inline static void updatesample t val unsigned int addr extdac1write and updateval addr multiplexer for external dac workstypedef haldacmuxextdac1 setter 8 extdac sequencerhowever if the template parameter is templated itself i get the duplicate symbol problemtemplatetypename dac tstruct dac setter templatetypename sample t inline static void updatesample t val unsigned int addr dac twrite and updateval addr multiplexer for external dac this produces a duplicate symboltypedef haldacmuxdac setterextdac1 8 extdac sequencerhere extdac1 is itself again a templatetypedef haldac8568dacspi typename dacspinss extdac1and dacspi is a template and so on also in the case which does work with the other instantation while dac write sequence t is a template it is not anymore a template of templates so i am starting to think that this is a problem with template recursion depth ie ld is not looking deep enougha further interesting observation on exactly the same condition as having the duplicate symbol the eclipse syntax highlighter says invalid template parameters on the line declaring extdac sequencer although the actual compilation step goes through,['c++'] +1162703,pycharm unable to save settings failed to save settings please restart pycharm community edition pycharm is trowing this exception when i savewarn mponentsimplstoresstoreutil save settings failedjavalangstringindexoutofboundsexception string index out of range 0 at javalangstringcharatstringjava658 at comintellijconfigurationstoreapplicationstoragemanagerexpandmacrosapplicationstoreimplkt108 at comintellijconfigurationstorestatestoragemanagerimplcreatestatestoragestatestoragemanagerimplkt194 at comintellijconfigurationstorestatestoragemanagerimplgetorcreatestoragestatestoragemanagerimplkt150 at comintellijconfigurationstorestatestoragemanagerimplgetstatestoragestatestoragemanagerimplkt133 at comintellijconfigurationstorestatestoragemanagerimplstartexternalization1setstatestatestoragemanagerimplkt342 at comintellijconfigurationstorecomponentstoreimplcommitcomponentcomponentstoreimplkt199 at comintellijconfigurationstorecomponentstoreimplsavecomponentstoreimplkt124 at comintellijopenapicomponentsimplstoresstoreutilsavestoreutiljava49 at comintellijopenapiapplicationimplapplicationimplsavesettingsapplicationimpljava1433 at comintellijidesaveandsynchandlerimpldosavedocumentsandprojectsandappsaveandsynchandlerimpljava150 at comintellijidesaveandsynchandlerimplsaveprojectsanddocumentssaveandsynchandlerimpljava134 at comintellijidesaveandsynchandlerimpl4onframedeactivatedsaveandsynchandlerimpljava104 at comintellijideframestatemanagerimplfiredeactivationeventframestatemanagerimpljava87 at comintellijideframestatemanagerimplaccess500framestatemanagerimpljava32 at comintellijideframestatemanagerimpl21runframestatemanagerimpljava72 at comintellijutilconcurrencyqueueprocessorrunsafelyqueueprocessorjava238 at comintellijutilalarmrequest1runalarmjava352 at comintellijopenapiapplicationimpllaterinvocatorflushqueuerunnexteventlaterinvocatorjava337 at comintellijopenapiapplicationimpllaterinvocatorflushqueuerunlaterinvocatorjava321 at javaawteventinvocationeventthispatchinvocationeventjava311 at javaawteventqueuethispatcheventimpleventqueuejava756 at javaawteventqueueaccess500eventqueuejava97 at javaawteventqueue3runeventqueuejava709 at javaawteventqueue3runeventqueuejava703 at javasecurityaccesscontrollerdoprivilegednative method at javasecurityprotectiondomainjavasecurityaccessimpldointersectionprivilegeprotectiondomainjava76 at javaawteventqueuethispatcheventeventqueuejava726 at comintellijideideeventqueuedefaultthispatcheventideeventqueuejava866 at comintellijideideeventqueue thispatcheventideeventqueuejava654 at comintellijideideeventqueuethispatcheventideeventqueuejava381 at javaawteventthispatchthreadpumponeeventforfilterseventthispatchthreadjava201 at javaawteventthispatchthreadpumpeventsforfiltereventthispatchthreadjava116 at javaawteventthispatchthreadpumpeventsforhierarchyeventthispatchthreadjava105 at javaawteventthispatchthreadpumpeventseventthispatchthreadjava101 at javaawteventthispatchthreadpumpeventseventthispatchthreadjava93 at javaawteventthispatchthreadruneventthispatchthreadjava82and giving me this error messagei do not think it is a problem of permissions on the idea file or anything like that but i am really not surei get some other errors and warnings in the stack trace but this is the one that recurs when i try to save projectsthis problem persists when i run pycharm ce with sudo like thissudo u username applicationspycharm ceappcontentsmacospycharmanyone got any ideasos macos el capitanpycharm pycharm community edition 505jre 180 76releaseb162 x86 64jvm openjdk 64bit server vm by jetbrains sro,['java'] +1163148,stuck with one query in sql server i had a table named calci the following was the sample datacreate table calci rn int freq int price intinsert into calci rn freq pricevalues 1 1 3 2 2 4 3 3 5 4 4 6 5 5 7 6 6 8 7 1 5 8 2 6 9 3 9 10 4 7 11 5 5 12 6 1 13 1 3i required only 3 records based on the sum of freq 16the result should be likeprice33 sum of first 6 records 33 sum of next six records 3 sum of last six record ie last record,['sql'] +1163962,function returning struct as lvalue in the following snippet why does the line omargin m compile without fault it easily deserves a warning since it will almost invariably be a mistake i would actually have thought it to be an error since it puts an rvalue on the left side of an assignmentinclude iostreamstruct margin marginint val0 valval int valstruct option margin m int z0 margin marginconst return m int zoomlevel return z int main option o stdcout margin is omarginval stdendl margin m 3 the following line is a noop which generates no warning omargin m the following line is an error gcc 490 error lvalue required as left operand of assignment clang 38 error expression is not assignable msvc 2015 error c2106 left operand must be lvalue ozoomlevel 2 stdcout margin is omarginval stdendl return 0outputmargin is 0margin is 0,['c++'] +1164096,listen chrome custom tab progress event i have an application using chrome custom tabs to open some links i need to have event each second during all the time the user stay on chrome or know how many time he stay on chrome for me the only way to do it is to use a service is it possible to do it differently,['android'] +1164106,is it possible to register all classes within a package as spring beans i am familiar with springs java based configuration options including the usage of component and configuration in conjunction with bean annotations to register spring beanshowever when converting a decent size project to spring it can be very labor intensive to systematically touch all classes in the project and update with configuration beans or annotating each class with component we have a large groovy project to be converted and i would like to simplify the processmy question is there a facility provided in spring that allows you to tell spring to autoconfigure all valid bean candidate classes within a specific package if not what other options are available,['java'] +1164112,simple injector initialize for both mvc and web api controllers i have a web api controller that has some resources di would out of later necessity i have added an mvc controller now i need same resources di would there as well here is my original configuration assembly webactivatorpostapplicationstartmethodtypeofcineplexsearchapp startsimpleinjectorwebapiinitializer initializenamespace cineplexsearchapp start using systemwebhttp using simpleinjector using simpleinjectorintegrationwebapi public static class simpleinjectorwebapiinitializer summaryinitialize the container and register it as web api dependency resolversummary public static void initialize var container new container containeroptionsdefaultscopedlifestyle new webapirequestlifestyle initializecontainercontainer containerregisterwebapicontrollersglobalconfigurationconfiguration containerverify globalconfigurationconfigurationdependencyresolver new simpleinjectorwebapidependencyresolvercontainer private static void initializecontainercontainer container containerregistericachingmanager cachingmanagerlifestyletransient containerregisteridataaccesslayer dataaccesslayerlifestyletransient can i register di for mvc controller in the same place as well can i reuse the containerupdate i must be close but now i get an error in the web api controller that i need a parameterless constructor i tried adding it but then nothing gets injected of coursepublic static class simpleinjectorwebapiinitializer summaryinitialize the container and register it as web api dependency resolversummary public static void initialize var container new container containeroptionsdefaultscopedlifestyle new webrequestlifestyle initializecontainercontainer containerregisterwebapicontrollersglobalconfigurationconfiguration containerregistermvccontrollersassemblygetexecutingassembly containerverify globalconfigurationconfigurationdependencyresolver new simpleinjectorwebapidependencyresolvercontainer dependencyresolversetresolvernew simpleinjectordependencyresolvercontainer private static void initializecontainercontainer container containerregistericachingmanager cachingmanagerlifestyletransient containerregisteridataaccesslayer dataaccesslayerlifestyletransient,['c#'] +1164346,f list to c ienumerable most efficient method i am currently working on an f library with gui written in c and i would like to ask what is the best or correct way to pass an f generic list to a c code generic ienumerablei have found three ways so far1 2 3 4 5 listtoseq1 2 3 4 5 seqoflist 1 2 3 4 5 seqintis there any practical difference between these three methods please,"['c#', '.net']" +1164349,how do i separate the metadata and the track from a shoutcast stream without making separate request for metadata and the streaming i have made a radio app which works perfectly fine i am able to play the radio stream and fetch the metadata too the streaming service is from shoutcastthe only problem is that i am adding the url as the datasource to the media player and then fetching the title and artist every 5 secondsis there any way i can just make one http request and then split the audio and the metadata and then send it to the media playercode for fetching metadataprivate void retreivemetadata throws ioexception int metadataoffset 0 okhttpclient client new okhttpclient request request new requestbuilder addheadericymetadata 1 addheaderconnection close addheaderaccept urlstreamurl build requestheaders response response clientnewcallrequestexecute inputstream stream responsebodybytestream mapstring liststring headers responsegetheaderfields if responseheadersicymetaintequals headers are sent via http string icymetaint responseheadersicymetainttostring icymetaint icymetaintreplace icymetaint icymetaintreplace metadataoffset integerparseinticymetaint else headers are sent within a stream stringbuilder strheaders new stringbuilder char c while c charstreamread 1 strheadersappendc if strheaderslength 5 strheaderssubstringstrheaderslength 4 strheaderslengthequalsrnrn end of headers break match headers to get metadata offset within a stream pattern p patterncompilernicymetaintsrn matcher m pmatcherstrheaderstostring if mfind metadataoffset integerparseintmgroup2 in case no data was sent if metadataoffset 0 iserror true return read metadata int b int count 0 int metadatalength 4080 4080 is the max length boolean indata false stringbuilder metadata new stringbuilder stream position should be either at the beginning or right after headers while b streamread 1 count length of the metadata if count metadataoffset 1 metadatalength b 16 if count metadataoffset 1 count metadataoffset metadatalength indata true else indata false if indata if b 0 metadataappendcharb if count metadataoffset metadatalength break set the data metadata icystreammetaparsemetadatametadatatostring close streamclosepublic static mapstring string parsemetadatastring metastring mapstring string metadata new hashmap string metaparts metastringsplit pattern p patterncompileazaz matcher m for int i 0 i metapartslength i m pmatchermetapartsi if mfind metadataputstringmgroup1 stringmgroup2 return metadataand passing the url to the datasource of the media playerstring url mp new mediaplayermpsetaudiostreamtypeaudiomanagerstream musictry mpsetdatasourceurl mpprepare catch illegalargumentexception e todo autogenerated catch block eprintstacktrace toastmaketextcontext etostring toastlength shortshow catch securityexception e todo autogenerated catch block logetag securityexception toastmaketextcontext etostring toastlength shortshow catch illegalstateexception e todo autogenerated catch block logetag illegalstateexception toastmaketextcontext etostring toastlength shortshow catch ioexception e todo autogenerated catch block logetag ioexception toastmaketextcontext etostring toastlength shortshow,"['java', 'android']" +1164382,how to match both numbers and range of numbers in a csvlike string with regex usually i like the challenges of regular expressions and even better solving thembut it seems i have a case that i cannot figure outi have a string of values that are separated by a semicolon like csv line that can look like this one123234foo4564567foofoo890foo12311221231234455098567890123fooin this line i would like to match all integers and integer ranges in order to extract them later it is possible that only single value no semicolonafter a lot of searching i managed to write this expressionrangeddintegerdthe test strings i am using123123234foo4564567foofoo890foo12311221231234455098567890123foo123456123foofoo123foofoolines 1 and 3 are correctly matched and lines 45 6 are notin line 2 only one value of two is correctly matchedhere is a link to regex101com that illustrates it i would also need to select integers and the ranges separately in different groups note i found a question that could help me and tried its answer by adapting it but it did not workregular expression for matching numbers and ranges of numbershave you got any idea on what i am missingthe language that will use this regex is c but i do not know if it is a useful information for my problemadded by barlophere are the matches the current regex gives him as shown by that regex101com linkand for this test string of his 123234foo4564567foofoo890foo1231122123123445509856789 12323445678901122123098567so his regex seems to be missing out one of the 123s and the 45 and the 89 at the end,"['c#', '.net']" +1164429,understanding pdo mysql transactions the php documentation saysif youve never encountered transactions before they offer 4 major features atomicity consistency isolation and durability acid in laymans terms any work carried out in a transaction even if it is carried out in stages is guaranteed to be applied to the database safely and without interference from other connections when it is committedquestion does this mean that i can have two separate php scripts running transactions simultaneously without them interfering with one anotherelaborating on what i mean by interferingimagine we have the following employees table id name salary 1 ana 10 if i have two scripts with similarsame code and they run at the exact same timescript1php and script2php both have the same codeconnbegintransactionstmt connprepareselect from employees where name stmtexecuteanarow stmtfetchpdofetch assocsalary rowsalarysalary salary 10increasing salarystmt connprepareupdate employees set salary salary where name stmtexecuteanaconncommit and assuming the sequence of events is as followsscript1php selects datascript2php selects datascript1php updates datascript2php updates datascript1php commit happensscript2php commit happenswhat would the resulting salary of ana be in this case would it be 110 and would this then mean that 1 transaction will overlap the other because the information was obtained before either commit happenedwould it be 120 and would this then mean that regardless of the order in which data was updated and selected the commit function forced these to happen individuallyplease feel free to elaborate as much as you want on how transactions and separate scripts can interfere or do not interfere with one another,"['php', 'mysql']" +1164580,paypal payment how to get success request when loading the paypal in webview editafter paypal login i could successfully complete transactionbut i need to match the successurl in paypal to verify both url is same and then thisplay successful toast messagebut i am not getting success url from paymentso i cannot match itbelow i have posted the relevant codewebactivityjavapublic class paypalwebactivity extends activity private webview webview string payurlstr progressdialog dialog string successurl override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutpaypal web layout successurl load webview payment paypal success dialog progressdialogshowpaypalwebactivitythis please wait false loadwebviewpaypal private void loadwebviewpaypal payurlstr load webview payment paypalpage id logepayurlstr payurlstr webview webview findviewbyidridwebview webviewloadurlpayurlstr webviewgetsettingssetjavascriptenabledtrue suppresswarningsunused websettings settings webviewgetsettings if buildversionsdk int 21 webviewgetsettingssetmixedcontentmode websettingsmixed content always allow webviewsetwebviewclientnew webviewclient override public boolean shouldoverrideurlloadingwebview view string url logeloading url url viewloadurlurl string loadweburl viewgeturl logeloadweburl loadweburl return true override public void onpagefinishedwebview view string url logefinished url url string weburl viewgeturl logeweburl weburl ifweburlsubstring095equalssuccessurl logegetting success request test else logefailed to get request test ifdialogisshowing dialogthismiss override public void onreceivederrorwebview view int errorcode string description string failingurl logeerror in url description logeerror in failingurl failingurl manifestusespermission androidnameandroidpermissioninternet usespermission androidnameandroidpermissionaccess network state usespermission androidnameandroidpermissionread external storage usespermission androidnameandroidpermissionwrite external storage usespermission androidnamecomgoogleandroidprovidersgsfpermissionread gservices usespermission androidnameandroidpermissionaccess coarse location usespermission androidnameandroidpermissionaccess fine location check this thiscussionstep by step i put screenshots and added content for clear understandingi am getting this error messageso cant able to match success request0615 181259894 ichromium3273 infoconsole0 mixed content the page at thispatch5885d80a13c0db1f8e263663d3faee8dcce3e160f5b9538489e17951d2c62172 was loaded over a secure connection but contains a form which targets an insecure endpoint managementspage featured subscription payment success4 this content should also be submitted over https thispatch5885d80a13c0db1f8e263663d3faee8dcce3e160f5b9538489e17951d2c62172 0this is my success response managementspage featured subscription payment success4 changed server nameis it possible to match success request with paypal if i get any suggestion it will be helpful to me,['android'] +1164605,c aggregating attributes in a list i have an object like as shown belowpublic class sampleobject public int msfid get set public liststring pgid get set public liststring dcid get set in the above aggregation of the pgid values grouped by msfid same is the case with dcid as wellfor examplemsfid 100pgid abcdcid 123msfid 100pgid defdcid 456msfid 100pgid ghidcid 789msfid 101pgid abcdcid 123how to write a linq query to aggregate this and create a list of sampleobjects like belowmsfid 100pgid abc def ghidcid 123 456 789msfid 101pgid abcdcid 123,['c#'] +1164884,does adding a value at the end to a c enum defined in an header force recompilation backgroundthere is a complex system with several libraries and applications in it pretty much every project depends upon an header file fooh for example that defines an enum included in the several cpp files the design is far to be ideal but as usual it is a legacy systemsadly fooh changes pretty often prerequisitelet us say that we can guarantee that fooh will be updated only adding element at the end without removing existing values nor redefining themquestionsdoes such modification requires recompilation of all the code that includes the header i am aware that this is a common problem with classes typically removing an unused variable changes the memory layout and cause eventually a core dump i suspect that can be a similar situation with enums as well and in normal situation i will surely recompile everything anywaythe current situation introduce a rigidity in all code base that hugely affects the way of the system is evolving i would like to know if i have to recompile this information can be used to device the refactoring strategynotei have looked at this question but i do not think it is actually answering mine,['c++'] +1164916,argumenterror parent directory is world writable but not sticky bundle install link to github for error printoutwhen i try to bundle install i receive the above error i have tried what other posts suggest and the github community does not know the answeri am running arch and am using zsh for my shell updated environmentbundler 1125rubygems 251 ruby 231p112 20160426 revision 54768x86 64linuxgem home usrlibrubygems230 gem path usrlibrubygems230homegemruby230 git 283 open gem 150thanks in advance,"['ruby-on-rails', 'ruby']" +1165159,initializing reference to istream i am trying to write my program so that it can process either stdin or a file specified on the command linei am doing this by trying to initialize a reference to an istream to either refer to cin or an ifstream using a conditionalsimilar techniques are described here and herebut when i try with ifstream i seem to get an error that the basic istream moveconstructor is declared protectedistream reftocin cin this is okconst istream reftofile ifstreamargs1 this is okconst istream instream fileisprovided ifstreamargs1 cin this causes error stdbasic istreamcharstdchar traitscharbasic istream cannot access protected member declared in class stdbasic istreamcharstdchar traitscharprocestreaminstream this could either be a file or cincan this be reasonably done this way is there a good alternative i am overlooking,['c++'] +1165338,gae ndb datastore new feature access datastore entities from other gae app reading the new documentation of gae ndb datastore methodsget by idid parentnone appnone namespacenone ctx optionsreturns an entity by id this is really just a shorthand for keycls idgetargumentsid a string or integer key id parent parent key of the model to getapp keyword arg id of app if not specified gets data for current appnamespace keyword arg namespace if not specified gets data for default namespacectx options context options returns a model instance or none if not foundi thiscover this new app parameter this is what i needed since a long time agoi just tried to access datastore of app xdev from app xglobal but i get this errorfile applicationsgoogleappenginelauncherappcontentsresourcesgoogleappenginedefaultbundlecontentsresourcesgoogle appenginegoogleappenginedatastoredatastore rpcpy line 1373 in check rpc success raise todatastoreerrorerrbadrequesterror app sxglobal cannot access app xdevs datai added the accounts services and as admin of the each other in this linkbut i still receive the problemcan anyone help me i need to know where in the control panel i can grant datastore access to other app in app engine,['python'] +1165429,bootstrap 336 jquery 224 version exception i am trying to use bootstrap and jquery in my new aspnet core application but i encounter the error bootstraps javascript requires jquery version 191 or higher but lower than version 3 when i try to run the applicationi have used bower to add bootstrap to my application and have added version 336 of bootstrap which automatically adds jquery 224 the problem is that it seems that version 224 of jquery is actually versioned at 300rc1 which causes bootstrap validation to fail as it will only accept versions of jquery from version 191 but less than version 3how can i resolve this conflict how is it that bootstrap comes packaged with an incompatible version of jqueryhere you can see my files in my solution showing the bootstrap and jquery versions as you can see there are no other versions of jquery installed eitherhere is a snippet of my html markuphtml xmlnshead titletitle link relstylesheet hreflibbootstrapthistcssbootstrapmincss headbody h1helloh1 script typetextjavascript srclibjquerythistjqueryminjsscript script typetextjavascript srclibbootstrapthistjsbootstrapminjsscriptbodyhtmlwhich results in chrome reporting bootstraps javascript requires jquery version 191 or higher but lower than version 3any help would be greatly appreciated,['jquery'] +1165510,android gradle duplicate files copied in apk metainflicensetxt i am going to add restful web service support with spring to my android application as described here this is toplevel buildgradle config toplevel build file where you can add configuration options common to all subprojectsmodulesbuildscript repositories jcenter dependencies classpath comandroidtoolsbuildgradle210 allprojects repositories jcenter this is my appbuildgradle configapply plugin comandroidapplicationandroid compilesdkversion 23 buildtoolsversion 2303 defaultconfig applicationid comexample minsdkversion 8 targetsdkversion 17 buildtypes release minifyenabled false proguardfiles getdefaultproguardfileproguardandroidtxt proguardrulestxt dependencies compile comandroidsupportappcompatv7 compile filetreedir libs include jar compile orgspringframeworkandroidspringandroidresttemplate101release compile comfasterxmljacksoncorejacksondatabind232 packagingoptions exclude metainfnotice will not include notice file exclude metainflicense will not include license file right now it fails with a following errorfailure build failed with an exception what went wrongexecution failed for task apptransformresourceswithmergejavaresfordebug comandroidbuildapitransformtransformexception comandroidbuilderpackagingduplicatefileexception duplicate files copied in apk metainflicensetxt file1 usergradlecachesmodules2files21orgspringframeworkandroidspringandroidresttemplate101releasee132d929bd181941f79b0d63edafb8a86ae6fd33springandroidresttemplate101releasejar file2 usergradlecachesmodules2files21orgspringframeworkandroidspringandroidcore101releasee68f0e8e4b636ee30c4de58953be38d9b72a5e3bspringandroidcore101releasejarwhat am i doing wrong and how to fix it,['android'] +1165528,why does stdmap stdmap not deallocate memory in the following test program the memory allocated by the stdmap is not deallocated all in all we allocate roughly 22 gb of memory which is never released although we do a swap with an empty container when changing the stdmap stdmap to become a stdmap stdvector the memory is actually releasedi have checked the code with valgrind which obiously does not find any leakswhy is this the case and how can i change the behaviorinclude cstdlibinclude iostreaminclude vectorinclude mapinclude chronoinclude threadclass test public stdvector stdpair int int mycontainer stdmapintint mymap test for int i 0 i 10 i stdpairint int pair stdmake pairint int rand int i mycontainerpush back pair mymapinsert pair int main stdmapinttest mycontainer1 for int i 0 i 50 i mycontainer1insert stdmake pairint test rand test stdcout ready stdendl stdthis threadsleep for stdchronomilliseconds 50 stdcout cleaning stdendl stdmapinttest tmp mycontainer1swap tmp stdcout cleaning ready stdendl stdthis threadsleep for stdchronomilliseconds 150 return 0,['c++'] +1165709,android just cannot fix the 65k issue i have been at this for two days now i tried all solutions related to multidexing and so but to no avail i removed everything so that i can do a fresh startapp gradleapply plugin comandroidapplicationandroid compilesdkversion 21 buildtoolsversion 2112 defaultconfig applicationid combilboldevjoestrategy minsdkversion 15 targetsdkversion 21 versioncode 1 versionname 10 multidexenabled true buildtypes release minifyenabled false proguardfiles getdefaultproguardfileproguardandroidtxt proguardrulespro dependencies compile comandroidsupportmultidex101compile comandroidsupportappcompatv72200compile comgoogleandroidgmsplayservicesads900apply plugin comgooglegmsgoogleservicesproject gradlebuildscript repositories jcenterdependencies classpath comandroidtoolsbuildgradle110 classpath comgooglegmsgoogleservices300allprojects repositories jcenterinside manifiest metadata androidnamecomgoogleandroidgmsversion androidvalueintegergoogle play services version application androidnameandroidsupportmultidexmultidexapplication the most common solution i read was do not include all google services just the things you need and thus i only compile the ads one but it still does not worksome of the classes not being foundedalvikvmi1 could not find class androidosusermanager referenced from method comgoogleandroidgmscommonzzezzanedalvikvmi1 could not find class androidappappopsmanager referenced from method comgoogleandroidgmsinternalzzpvzzgedalvikvmi1 could not find class comgoogleandroidgmsinternalzzamq referenced from method comgoogleandroidgmsinternalzzdizzeetci tried all the approaches i found one of which is thisi also used the dexcount plugin mentioned in the end to count the methods in my app i do not know how to attach a file to a question so you can download the debugtxt from herenote i believe that this is a 65k limit issue because on a 44 android mobile the ads thisplay and the errors do not show in logcat but on two 42 android mobiles the ads do not show and the errors how however if you look at the debugtxtmethods fields packageclass name15236 5010 android14282 9575 comrest are less than 3k combinedi just do not see 65k unless android and whats under it androidsomething stackwhat am i missing here,['android'] +1165811,move td to new column i have a table like thattable tr tdsome column1td td idabc1abctd tr tr tdanother column1td td iddef1deftd tr tr tdsome column2td td idabc2abctd tr tr tdanother column2td td iddef2deftd trtablehow can i move the tds with the suffix 2 to the right so adding a 3rd column also the remaining empty td some column2 and another column2 should be removed completelythe final result should look as followsthis is the desired codetable tr tdsome column1td td idabc1abctd td idabc2abctd tr tr tdanother column1td td iddef1deftd td iddef2deftd trtablethis is my approach which does not worktable tdnthchild2id2aftertable tdnthchild2fiddle,"['javascript', 'jquery', 'html']" +1165980,kafka java simpleconsumer strange encoding i am attempting to use the simpleconsumer in kafka 9 to allow users to replay events from a time offset but the messages i am receiving back from kafka are in a very strange encoding7icftesttesteventebebf1a42911431da138f5d6db4647d7i12w8i12i12i12i12i12i12namespacetesttypetesteventebebf1a42911431da138f5d6db4647d7received1464819330373contextuserid0usernametestuseri12i12ai12i12i12i12i12namespacetesttypetesteventebebf1a42911431da138f5d6db4647d7received1464819331637contextuserid1usernametestuseri12i12i12ri12i12i12i12i12namespacetesttypetesteventebebf1a42911431da138f5d6db4647d7received1464819332754contextuserid2usernametestuseri12i12i12i12i12i12i12i12namespacetesttypetesteventebebf1a42911431da138f5d6db4647d7received14648193868contextuserid3usernametestuseri12p i12i12i12i12i12i12namespacetesttypetesteventebebf1a42911431da138f5d6db4647d7received1464819334997contextuserid4usernameusing the kafkaconsumer this messages parse just fine here is the code i am using to retrieve messages using the simpleconsumer for messageandoffset messageandoffset fetchresponsemessagesettopic partition long currentoffset messageandoffsetoffset if currentoffset readoffset logdebugfound an old offset skip continue readoffset messageandoffsetnextoffset int payloadoffset 14 messageandoffsetmessagekeysize remove first x bytes schema id byte data messageandoffsetmessagepayloadarray byte realdata arrayscopyofrangedata payloadoffset datalength payloadoffset logdebugread new stringrealdata utf8i added the code to skip the first x bytes after i kept getting utf32 errors about bytes being too high which i assume is because kafka prepends info like message size to the payload is this an avro artifact,['java'] +1166003,running ascii regex over nonascii characters with utf8 include boostregexhppinclude stringinclude vectorinclude iostreamint mainint argc char argv stdstring text argv1 stdstring patterns argv2 boostregex regex boostregexpatterns boostsmatch match stdcout boostregex searchtext match regex stdendl if i run the program over the input helloa a containing a nonascii character with utf8 encoding it returns 0 ie not found but if i run it over the input hela a again containing nonascii it returns 1 ie found my question what is the expected behavior of boostregex ie the ascii version when run over utf charactersedit thanks for all the comments i am still interested as to why exactly 1 is output since both the text and the regex contain nonascii characters my guess would be that the bytes are interpreted as ascii and thus they match,['c++'] +1166347,how to get many to many relationship items in laravel there is a data structure for a eshopseries many to many categories many to many productsfor example series is outdoor series categories is tshirt products are tshirt a tshirt b etc and here is the controller that list out products in one categorypublic function viewseries 0 cat 0 page 1 category categoryfindcat totalitems countcategoryproduct itemsperpage 30 currentpage page urlpattern umsproductviewseriescatnum thisdataproduct list categoryproductorderbycreated at descskippage 1 itemsperpagetakeitemsperpageget thisdatapaginator new paginatortotalitems itemsperpage currentpage urlpattern thisdatacategory category thisdatapage page return viewproductlistwiththisdata now the problem is i would like to rewrite the code so that instead of showing one category i would like to show one series as wellthat means if the series 0 then it shows products in one category if the cat 0 then it shows products in multi categoryin laravel how to get the products in multi category try seriescategoryproduct but no luck also how to rewrite that function to support showing of the seriesthanks a lot,"['php', 'html', 'mysql']" +1166403,using keyword to choose from multiple virtual inherited functions i have a class testc which is derived from two other classes testa and testb both of which have a virtual function with the same signatureto make the function accessible through testc i have to tell it which version to use this works if i explicitly overwrite the function in testc and call the version i wantinclude iostreamclass testapublic virtual void test stdcoutaclass testbpublic virtual void test stdcoutbclass testc public testapublic testbpublic void test testbtestint mainint argcchar argv testc c testa a static casttestac atest ctest for return exit successoutput bbthat is the expected result however i noticed that if i use the using keyword instead of overwriting the function explicitly i get some unexpected behaviorclass testc public testapublic testbpublic using testbtesteverything else is the sameoutput abcan someone explain this to me it looks like test is suddenly not virtual anymore is there any way to do this without explicitly overwriting the function something like using override,['c++'] +1166500,xcode error itms90635 invalid macho in bundle submitting to app store i just got this error when submitting an app to the app storedoes this mean i need to set enable bitcode for all dependencies i tried that but then got errors saying the dependencies were not compatible with bitcode or something like that,['ios'] +1166519,no global variable initialization when i add this code in existing cpp with one of my class implementationinclude iostreamstruct teststruct teststructint i stdcerr i stdendl x i int xteststruct t8it prints 8 before main executed but when i created new empty file testcpp and put the same code in it nothing was printed i checked that this cpp was compiled and linked all cpp files compiled as static lib and then this lib with maino linked in executable file i use g 53 only option is stdc14 why in the second case global variable initialization are missed,['c++'] +1166835,how to bound a circle inside an ellipse the title for this post was quite hard to think of so if you can think of a more descriptive title please tell me anyway my problem is quite specific and requires some simple maths knowledge i am writing a c winforms application which is a bit like the old xeyes linux application it basically is a set of eyes which follow around your mouse cursor this may sound easy at first however can get rather complicated if youre a perfectionist like me p this is my code so far only the paint method that is called on an interval of 16int lx 35int ly 50int rxint ryint wx locationx width 2int wy locationy height 2rectangle bounds screenfromcontrolthisbounds calculate xfloat tempx mx wx floatboundswidth 2 calculate yfloat tempy my wy floatboundsheight 2 draw eyesegraphicsfillellipsebrusheslightgray 10 10 70 100egraphicsfillellipsebrusheslightgray 90 10 70 100 draw pupils this only draws the left oneegraphicsfillellipsebrushesblack lx int25 tempx ly int40 tempy 20 20now this does work at a basic level however sometimes this can happen if the user puts the cursor at 00now my question is how to fix this what would the if statement be to check where the mouse pointer is and then reduce the pupil x depending on thatthanksedit this is where i get the mouse positions my and mx private void timer tickobject sender eventargs e mx cursorpositionx my cursorpositiony invalidatethe timer is started in the eyes load event and the interval is 16edit 2 final solution,['c#'] +1166941,c union in c a weird behaviour i am trying to create some vhdvhdx files using the vhd api in cthere is a c union that looks like thistypedef struct create virtual thisk parameters create virtual thisk version version union struct guid uniqueid ulonglong maximumsize ulong blocksizeinbytes ulong sectorsizeinbytes pcwstr parentpath pcwstr sourcepath version1 struct guid uniqueid ulonglong maximumsize ulong blocksizeinbytes ulong sectorsizeinbytes ulong physicalsectorsizeinbytes pcwstr parentpath pcwstr sourcepath open virtual thisk flag openflags virtual storage type parentvirtualstoragetype virtual storage type sourcevirtualstoragetype guid resiliencyguid version2 struct guid uniqueid ulonglong maximumsize ulong blocksizeinbytes ulong sectorsizeinbytes ulong physicalsectorsizeinbytes pcwstr parentpath pcwstr sourcepath open virtual thisk flag openflags virtual storage type parentvirtualstoragetype virtual storage type sourcevirtualstoragetype guid resiliencyguid pcwstr sourcelimitpath virtual storage type backingstoragetype version3 create virtual thisk parameters pcreate virtual thisk parametersi am trying to convert that to c but not having much luck i am not interested in version3 at all so am leaving that out i have tried a number of things and the best i could get to was having version2 working by doing something really bizarre but i have never managed to get version1 and version2 working at the same timethe solution that has wielded the best results so far has been this but there has to be something wrong there because version1 simply does not work and sectorsizeinbytes in version1 is a ulong rather than uint if i change it to uint like it should be i break version2 and version1 still does not workstructlayoutlayoutkindexplicit charset charsetunicodepublic struct createvirtualthiskparameters fieldoffset0 public createvirtualthiskparametersversion1 version1 fieldoffset0 public createvirtualthiskparametersversion2 version2structlayoutlayoutkindsequential charset charsetunicodepublic struct createvirtualthiskparametersversion1 public createvirtualthiskversion version public guid uniqueid public ulong maximumsize public uint blocksizeinbytes public ulong sectorsizeinbytes public string parentpath public string sourcepathstructlayoutlayoutkindsequential charset charsetunicodepublic struct createvirtualthiskparametersversion2 public createvirtualthiskversion version public guid uniqueid public ulong maximumsize public uint blocksizeinbytes public uint sectorsizeinbytes public uint physicalsectorsizeinbytes public string parentpath public string sourcepath public openvirtualthiskflags openflags public virtualstoragetype parentvirtualstoragetype public virtualstoragetype sourcevirtualstoragetype public guid resiliencyguidi know theoretically the version field should be set outside the version structs and i have tried that as well but it just breaks things even more funnily enoughso can someone advise how to properly translate the above to c leaving out the version3 struct as that is not needed,"['c#', 'c++']" +1167058,passing a numpy array to c i have some code writen in python for which the output is a numpy array and now i want to send that output to c code where the heavy part of the calculations will be performedi have tried using cythons public cdef but i am running on some issues i would appreciate your help here goes my codepymodulepyxfrom pythonmodule import result result is my numpy arrayimport numpy as npcimport numpy as npcimport cythoncythonboundscheckfalsecythonwraparoundfalsecdef public void cfunc print i am in here cdef npndarraynpfloat64 t ndim2 modec res result print resonce this is cythonized i callpymaincinclude pythonhinclude numpyarrayobjecthinclude pymodulehint main py initialize initpymodule test2 py finalizeint testint a py initialize initpymodule cfunc return 0i am getting a nameerror for the result variable at c i have tried defining it with pointers and calling it indirectly from other functions but the array remains invisible i am pretty sure the answer is quite simple but i just do not get it thanks for your help,"['python', 'c++']" +1167084,webpack require array of requirements require dynamic string i would like to require a list of requirements in webpack as soon as i replace the string parameter of the require function with a variable or a constant it cannot inject the requirement anymorehere is a perfectly working exampleconst angular requireangularbut as soon as i change this to the following it doesnt work anymoreconst angularstring angularconst angular requireangularstringmy goal is to have a static list of dependencies and inject them one by one like thisconst angulardependencies angularsocketio angularuirouterforvar i 0 i angulardependencieslength i requireangulardependenciesithis is the error message i gotwarning in appappjscritical dependencies14114 the request of a dependency is an expression appappjs 14114warning in app module not found error a dependency to an entry point is not allowed app warning in app module not found error a dependency to an entry point is not allowed app,['javascript'] +1167104,sort macedonian alphabet using collation i am trying to sort a set of strings written in macedonian alphabet i know how to do it but the end result is not what i expected here is my test programpublic class main private static final char alphabet array 2 3 n n n o n 14 12 n 34 n n n n n n n n nn n public static void mainstring args collator collator collatorgetinstancenew localemk mk liststring list new linkedlist for int i 0 i alphabet arraylength i listadd alphabet arrayi listsortcollatorcompare listforeachsystemoutprint the letters in alphabet array are in the correct alphabetical order but the program prints23n n nonn1412n34nbut it should have been23 nn non1412n34nis there a problem with the macedonian collator in java or am i doing something wrong,['java'] +1167250,python embeddable zip with the 350 release pythonorg has introduced a thistribution billed as embeddable zip fileunfortunately the zipped file comes without a help file not even a readme the download page on pythonorg just lists it among the downloads apparently this is a portable python thistribution it is anyway quite different in structure and size from the standard thistribution using the installer i realised that it is possible to install pip with getpippy and thanks to pip it is a breeze to add many other application packages though i am still unable to add tkinter adjust slashes according to your shellcurl epythonzipunzip o epythonzip d env1curl l env1getpippyenv1python env1getpippyadd what you need eg djangoenv1python m pip install django given the size 65 mega for the 351x64 i think that it can be convenient as a means to create isolated environmentsin fact the general python documentation says that the embedded thistribution is almost fully isolated from the useras system including environment variables system registry settings and installed packagegiven this in windows there are now two isolated python environments the second being the standardvirtualenv the same process in virtualenv is like followsvirtualenv env2and for django it would be env2scriptspython m pip install django comparing the contents of env1 and env2 they appear to have the same files the only significant difference is tkinter1 which is anyway not much significant for desktop appswhich is the difference between python virtualenv and python embeddablespecifically which is the difference between the isolated web app created with the embeddable zip env1 and virtualenv env2,['python'] +1167548,devise ajax sign in handling failure on rails 4 i am trying to receive login fail events on a devise ajax login form i have overriden the devise sessions controller like soclass sessionscontroller devisesessionscontroller def create resource wardenauthenticatescope resource name recall controller pathfailure sign in and redirectresource name resource end def sign in and redirectresource or scope resourcenil scope devisemappingfind scoperesource or scope resource resource or scope sign inscope resource unless wardenuserscope resource return render json success true end def failure return render json success false errors login failed endendthe json on failure never actually triggers on a 401 unauthorised response the js on sign in and redirect works fine though here is the section of my js where i expect an alert to showdocumentonclick loginbtn function loginmodaltoggleclassisactive formlogin user formbindajaxsuccess functione data status xhr if datasuccess loginmodaltoggleclassisactive else return alertfailure this never happens edit so i managed to get the desired behaviour by checking for datastatus 200 instead of datasuccess i am still wondering if this is the right way to go about it or if i am missing something,"['javascript', 'jquery', 'ruby-on-rails']" +1167663,how do python recursive generators work in a python tutorial i have learned thatlike functions generators can be recursively programmed the following example is a generator to create all the permutations of a given list of itemsdef permutationsitems and lenitems if n0 yield else for i in rangelenitems for cc in permutationsitemsiitemsi1 yield itemsiccfor p in permutationsred printjoinpfor p in permutationslistgame printjoinp endi cannot figure out how it generates the results the recursive things and yield really confused me could someone explain the whole process clearly,['python'] +1167665,faster alternative to decimalparse i noticed decimalparsenumber numberstylesallowdecimalpoint cultureinfoinvariantculture is about 100 slower than custom decimal parse method based on jeffrey saxs code from faster alternative to converttodoublepublic static decimal parsedecimalstring input bool negative false long and 0 int len inputlength int decimalposition len if len 0 int start 0 if input0 negative true start 1 for int k start k len k char c inputk if c decimalposition k 1 else and n 10 intc 0 return new decimalintn intn 32 0 negative bytelen decimalpositioni assume that is because native decimalparse is designed to struggle with number style and culture infohowever above mentioned method does not use 3rd parameter hi byte in new decimal so it would not work with larger numbersis there a faster alternative to decimalparse to convert string that consists only of numbers and decimal dot to decimal which would work with large numbersedit benchmarkvar style systemglobalizationnumberstylesallowdecimalpointvar culture systemglobalizationcultureinfoinvariantculturesystemdiagnosticsstopwatch s new systemdiagnosticsstopwatchsresetsstartfor int i0 i10 i decimalparse2011223344556 style culturesstopconsolewritelineselapsedtostringsresetsstartfor int i0 i10 i parsedecimal2011223344556sstopconsolewritelineselapsedtostringoutput042313728014464048custom parsedecimal is in this case significantly faster than decimalparse,['c#'] +1167740,android array adapter selecting the wrong id i am building an application that allows the user to connect to their local wifi network without leaving however whenever i select an item on the list the wrong network id comes up and it connects to the wrong network i have noticed that if i have three available networks and i select the top one the bottom one appears to connect to the reverse is true as wellwhen i select the middle one it actually works here is my code belowfrom oncreate methodbutton buttonscan button findviewbyidridbuttonscanwifimanager wifi wifimanager getsystemservicecontextwifi servicelistview lv listview findviewbyidridlistlvsetonitemclicklistenernew adapterviewonitemclicklistener override public void onitemclickadapterview arg0 view arg1 int arg2 long arg3 connecttowifiarg2 lvsetonitemlongclicklistenernew adapterviewonitemlongclicklistener override public boolean onitemlongclickadapterview arg0 view arg1 int arg2 long arg3 return true if wifiiswifienabled toastmaketextgetapplicationcontext enabling wifi toastlength longshow wifisetwifienabledtruesimpleadapter adapter new simpleadapter networkcalibrationthis arraylist rlayoutwifi list row new string item key new int ridlistvalue lvsetadapteradapterregisterreceivernew broadcastreceiver override public void onreceivecontext c intent intent results wifigetscanresults size resultssize new intentfilterwifimanagerscan results available actionselecterhnum vnumbuttonscansetonclicklistenernew viewonclicklistener override public void onclickview v noob false sharedpreferences settings getsharedpreferencesprefs name 0 sharedpreferenceseditor editor settingsedit editorputbooleannewbie noob editorcommit arraylistclear wifistartscan toastmaketextgetapplicationcontext scanning toastlength shortshow try size size 1 while size 0 hashmapstring string item new hashmapstring string itemputitem key resultsgetsizessidtostring resultsgetsizecapabilitiestostring arraylistadditem size adapternotifydatasetchanged catch exception e eprintstacktrace public void finallyconnectstring checkpassword int position string networkssid resultsgetpositionssid wificonfiguration wificonfiguration new wificonfiguration wificonfigurationssid networkssid wificonfigurationpresharedkey checkpassword wifimanager wifimanager wifimanager getsystemservicewifi service int netid wifimanageraddnetworkwificonfiguration if wifimanageriswifienabled wifi is turned on thisconnect it first wifimanagersetwifienabledtrue wifimanagerenablenetworknetid true wifimanagercreatewifilockwifimanagerwifi mode full networkssid wifimanagerreconnect wifimanagersaveconfiguration wificonfiguration wificonfig new wificonfiguration wificonfigssid stringformats networkssid wificonfigpresharedkey stringformats networkpass remember id int netid wifiaddnetworkwificonfig wifithisconnect wifienablenetworknetid true wifireconnect wificonfiguration conf new wificonfiguration confssid networkssid confpresharedkey networkpass wifiaddnetworkconf sharedpreferences settings getsharedpreferencesprefs name 0 sharedpreferenceseditor editor settingsedit editorputbooleanconnectedisconnected editorcommitprivate void connecttowififinal int position final dialog dialog new dialogcontext dialogsetcontentviewrlayoutwifi connect dialogsettitleconnect to network textview textssid textview dialogfindviewbyidridtextssid1 textview textbssid textview dialogfindviewbyidridtextbssid1 textview capabilities textview dialogfindviewbyidridtextcapabilities button dialogbutton button dialogfindviewbyidridokbutton pass edittext dialogfindviewbyidridtextpassword passrequestfocus inputmethodmanager inputmethodmanager inputmethodmanagergetsystemservicecontextinput method service inputmethodmanagershowsoftinputpass inputmethodmanagershow implicit textssidsettextresultsgetpositionssid textbssidsettextresultsgetpositionbssid capabilitiessettextresultsgetpositioncapabilities if button is clicked connect to the network dialogbuttonsetonclicklistenernew viewonclicklistener override public void onclickview v checkpassword passgettexttostring finallyconnectcheckpassword position statustextsettextconnecting statustextsettextcolorcolorparsecolor0 checkconnection dialogthismiss dialogshowany idea why this would be happening thanks everyone,"['java', 'android']" +1168272,calling derived class through base class function pointer can i call a derived class through a base class function pointer as shown in the example belowi understand that my example works but is it guaranteed to always do so assuming the object actually implements the function or is this just an idiosyncrasy of the compiler i am usingby this logic cannot one simply derive all their classes from cbase which in this case is empty so i guess no overhead and ignore the type in the function pointerinclude iostreamstruct cbase struct cderived cbase void myfunction stdcout called ok stdendl typedef void cbasefunctionpointerint main cderived base new cderived functionpointer pointer static castfunctionpointercderivedmyfunction basepointer delete baseexample usage scenarioa derived class that takes one or more pointers to callbacks in the base class can the callback type just be defined using the derived class and thus forgo the need for a template,['c++'] +1168864,pdf file size too big created using jspdf i am using jspdf for creating pdf inside browser i am having multiple charts having svg as chart data for adding data to pdf i am converting svg to png using canvas and then base64 data using canvastodataurl method after all this conversions size of the file created by jspdf is huge about 50 mbbelow is the code for div of chart data and canvasnewdiv documentcreateelementdivnewdivclassname big con graph big con graph0newdivstyleheight 0pxnewdivid big con graph idbelow is the dimensions for svg chart loaddocumentgetelementbyidbig con graph idstylethisplay blockvar big chartreference fusionchartsbig mychartididifbig chartreference null big chartreferencethisposevar big width 1088var big height 604now below is the code for conversion of above graph svg data and adding to pdfvar elem graph big con graphbig con graph0countclonetruesvgstring elem graphfindspanhtmlvar img documentcreateelementimgvar domurl selfurl selfwebkiturl selfvar svg new blobsvgstring type imagesvgxmlcharsetutf8var url domurlcreateobjecturlsvgimgonload pdfafterimageloadimgpdfimgloadsequencedomurltotalreportsreportnameimgsrc urlthis is the code for pdfafterimageload functionvar canvas documentgetelementbyidcanvasvar ctx canvasgetcontext2dctxdrawimageimg 0 0var png canvastodataurlimagepngpdfaddimagepng png leftmargin 120 485 270i am using png so imagequality parameter can not be usedcan anyone help me decrease the file size,['javascript'] +1169086,c adding or subtracting 0 from a value i was looking at the code below and i got the logic but i cannot seem to understand what is the use of 0 class solutionpublic string addbinarystring a string b string s int c 0 i asize 1 j bsize 1 whilei 0 j 0 c 1 c i 0 ai 0 0 c j 0 bj 0 0 s charc 2 0 s c 2 return s,['c++'] +1169570,how to profile javascript now that jsperf is down as some of you probably noticed jsperf is down for some time but i still need to profile my javascripts is there any possibility to do comparison tests ideally without the help of an external software,['javascript'] +1169667,correct approach when srp violation seems to pass complexity down the chain currently in the middle of a substantive bit of refactoring work after realising my classes were all over the place i am trying to split things up a bit to follow the srp better but i have always found it hard to evaluate the maxim of whether a class has one reason to change i am hoping this practical example might help me understandthe code in question is designed to clean data currently there are two separate processes here we clean address data by using an external application which is called via the code we clean other data fields using internal algorithms in cthis refactor started when i was told that we might want to change both these processes in the future for example to use database stored procedures to do both these jobs rather than c code and the external application so my first instinct was to take these two functions and hide them behind interfaces filerow and filecontents are just dtospublic interface iaddresscleaner string cleanaddrestringbuilder inputaddress void cleanfilefilecontents fcpublic interface ifieldcleaner string cleanphonenumberstring phonetoclean void cleanallphonefieldsfilerow row filecontents fc void matchobscentitiesfilerow row filecontents fc void cleanemailfieldsfilerow row filecontents fcwhich is fine realistically however i cannot imagine a class would ever use one of these without the other so it would seem to make sense to amalgamate them and their implementations into a single class that also makes sense given we might replace both functions with a single solution such as a databaseon the flip side it would seem that the ifieldcleaner already violates the srp because it is doing three things cleaning phone numbers emails and looking for rude words all of which are logically thistinct processes so there would seem to be reason to split it into an iphonecleaner iobscenitymatcher and iemailcleanerwhat particularly bothers me about the latter approach is that these classes are used in a service which already has a silly number of interface dependenciespublic class readfileservice iexecutableobject private ilogger log private irepository rep private ifilehelper filehelp private ifieldcleaner fieldcleaner private ifileparser fileparser private ifilewriter filewriter private iemailservice mailservice private iaddresscleaner addresscleaner public readfileserviceilogger log irepository rep ifilehelper filehelp ifileparser fileparse ifilewriter filewrite iemailservice email iaddresscleaner addresscleaner assign to privates functionsand that in turn also looks like it is violating the srp to a ludicrous degree without adding an additional two interfaces to itwhats the right approach here should i have a single icleaner interface or split it into five,['c#'] +1169713,methodhandles or lambdametafactory at my job we have a dsl for specfying mathematical formulas that we later apply to a lot of points in the millionsas of today we build an ast of the formula and visit each node to produce what we call an evaluator we then pass that evaluator the arguments of the formula and for each point it does the computingfor instance we have that formula x 3 y a amulta a a a a a ava ava a x a a add a a a a a a a ava ava a 3 a a y a a aour evaluator will emit evaluate objects for each stepthis method is easy to program but not very efficient so i started looking into method handles to build up a composed method handle to speed things up lately something along this i have my arithmetic class with public class arithmetics public static double adouble a double b return ab public static double multdouble a double b return ab and when building my ast i use methodhandleslookup to directly get a handle on those and compose them something along these lines but in a treemethod add arithmeticoperatorclassgetdeclaredmethodadd doubleclass doubleclassmethod mult arithmeticoperatorclassgetdeclaredmethodmult doubleclass doubleclassmethodhandle mh add lookupunreflectaddmethodhandle mh mult lookupunreflectmultmethodhandle mh add 3 methodhandlesinsertargumentsmh add 3 plus argmethodhandle formula methodhandlescollectargumentsmh mult 1 mh add 3 formula is fxy x 3 ysadly i am quite thisapointed by the results for instance the actual construction of the method handle is very long due to calls to methodhandlesinsertarguments and other such compositions functions and the added speedup for evaluation only starts to make a difference after over 600k iterationsat 10m iterations the method handle starts to really shine but millions of iterations is not yet a typical use case we are more around 10k1m where the result is mixedalso the actual computation is sped up but by not so much 210 times i was expecting the thing to run a bit fasterso anyway i started scouring stackoverflow again and saw the lambdametafactory threads like these and i am itching to start trying this but before that i would like your input on some questionsi need to be able to compose all those lambdas methodhandles provides lots of slowish admitedly ways to do it but i feel like lambdas have a stricter interface and i cannot yet wrap my head on how to do that do you know howlambdas and method handles are quite interconnected and i am not sure that i will get a significant speedup i see these results for simple lambdas direct 002s lambda 002s mh 035s reflection 040 but what about composed lambdasthanks guys,['java'] +1169856,how to remove string that dosnt have an html tag using css i need to remove strings that do not have an html tagfor example div classa a href classlinkkeep thisa and i want to remove this divcan i do this using only css,"['html', 'css']" +1169929,es6 default values not available in functionarguments if i have this es6 function declaration and invocationfunction myfunction arg1 arg2 bob consolelogarguments argumentsmyfunction1the consolelog statement shows only one argument with a value of 1 bob is nowhere to be seen is this expected andor desired behavior i would expect that default values would be available in the arguments object if not is there a way to dynamically get all arguments defaults in some other manner thanks in advance,['javascript'] +1170055,can i override es6s promise by bluebirds implementation in nodes global scope i want to use bluebirds implementation of the promisea open standard and override native es6 promises i also want the bluebird implementation to be available everywhere in my subsequently imported modules without having to require it in every single one of them bluebirds getting started page tells me tovar promise requirebluebird which results in overriding the native promise element because bluebird is a superset of the spec it will not break existing code and is thus supposed to be safe to usehowever because i know it is considered bad practice toextend or replace language natives anddefine globals for use in a require chain that depends on it i am wary when i want to include this in the base script of a node appimport promise from bluebirdglobalpromise promiseis this a bad practice should i stick to importing bluebird in every single file,['javascript'] +1170177,mobile app webframe authentication with rails devise i am currently working on implementing a mobile app for our site that uses ruby on rails and devise the idea here is at first create a mobile login form that on successful login opens a web frame that is authenticated and allows the normal use of the mobile optimised site theoretically that should be possiblei am having trouble with the following issueshow do you get the pure session key for the user session via a json request what methods can be used to manually generate it from devise something that the sign inuser user method doesis it even possible to take that key and put it into the browser cookie the way it normally happens in devise but on the mobile sidei know that this is not the standard method of making mobile applications for the site but i believe it should be possible,"['android', 'ios', 'ruby-on-rails', 'ruby']" +1170462,php returning array with requirements done i have a few functions here and im struggeling to get the right outputthe main idea is to use function called buildinginfo and call function avaliablebuildingbuildings to loop trough buildinginfo s arrays and loop trough requirements to find out if the requirements is complete or notin my database my main building level is 1every other table is emptywhen calling avaliablebuildingbuildings i get the output under this line that would list buildings i can create you can see that the requirements for main building are 3 then the barracks shouldnt be createdq how can i fix my code so it would acually just give me the array of buildings i can buildcurrent outputarray5 barracks array2 max int1 requirements array2 main building int3 rally point int1 blacksmith array2 max int1 requirements array3 main building int3 academy int3 barracks int3 embassy array2 max int1 requirements array1 main building int1 marketplace array2 max int1 requirements array3 warehouse int1 granary int1 main building int3 palace array2 max int1 requirements array3 main building int5 embassy int1 residence int0 full code function isbuiltvillageidname buildinginfo thisbuildinginfo thisbuilding buildinginfoname built thiscidbqueryselect from name where villageidvillageidrow return built built false function requirementsdonevillageidname buildinginfo thisbuildinginfoname canbebuilt true if issetbuildinginforequirements requirements buildinginforequirements foreach requirements as reqname level building thisisbuiltvillageid reqname if building echo needs that reqname buildinglevelis higher than level to build name brbr if buildinglevel level echo br reqname is acually higher brbr else echo i cant acually build this brbr canbebuilt false break else canbebuilt false break if canbebuilt echo result to build name is truebr else echo result to build name is falsebr return canbebuilt function existingbuildingsvillageid buildinginfo thisbuildinginfo buildings array foreachbuildinginfo as name array built thisisbuiltvillageidname if built buildingsname built return buildings function avaliablebuildingbuildingsvillageid avaliable thisavaliablebuildingsvillageid tobuild array foreachavaliable as name built if issetbuiltrequirements req builtrequirements foreach req as reqname level canbuild thisrequirementsdonevillageid reqname if canbuild echo verify to build reqname is true brbr tobuildname avaliablename else echo verify to build reqname is false brbr break else return tobuild function avaliablebuildingsvillageid buildinginfo thisbuildinginfo foreachthisexistingbuildingsvillageid as name built if array key existsnamebuildinginfo unsetbuildinginfoname echo removing name br return buildinginfo function buildinginfo info array academy arraymax 1 barracks arraymax 1 requirements array main building 3 rally point 1 main building arraymax 1 requirements array main building 1 greatbarracks arraymax 1 greatstable arraymax 1 heromansion arraymax 1 rally point arraymax 1 stable arraymax 1requirements array blacksmith 3 academy 5 blacksmith arraymax 1requirements array main building 3 academy 3 barracks 3 forge arraymax 1 tournament square arraymax 1 trapper arraymax 1 cranny arraymax 1 embassy arraymax 1 requirements array main building 1 marketplace arraymax 1requirements array warehouse 1 granary 1 main building 3 palace arraymax 1 requirements array main building 5 embassy 1 residence 0 residence arraymax 1 town hall arraymax 1 trade office arraymax 1 treasury arraymax 1 granary arraymax 99 new 20 warehouse arraymax 99 new 20 return info,['php'] +1170605,declarations in c from what i have understood declarationsinitializations in c are statements with base type followed by a comma separated list of declaratorsconsider the following declarationsint i 0 const p i legal the socalled base type is int i is an int while p is a const pointer to an intint j 0 const c 2 error c requires a type specifier for all declarations intention was to declare j as an int and c an as const intint const p1 nullptr i1 0 p1 is a const pointer to an int while i1 is just an intint const j1 0 c1 2 both j1 and c1 are const intis const int a base type or a compound typefrom the error in the second declaration above it seems to be a base type if it is so then what about the first declarationin other words if the first statement is legal why is not the second one also why does the behaviour differ among the third and fourth statements,['c++'] +1170703,create custom user control for acumatica i am attempting to create a custom user control that is usable in the acumatica framework documentation is very limited so i was hoping someone may have some experienceexamples of how best to implementit appears possible by creating a webcontrol derived from pxwebcontrol creating a global js function with a matching name,"['c#', 'asp.net']" +1170794,cannot refer to other view id in android databinding i just finished watching advanced data binding google io 2016 and would like to apply the following to reduce repetition of my expression used in different viewsbut i cannot make it work in my caseimagebutton androidididbtn list androidlayout width48dp androidlayout height48dp androidlayout gravitystart androidbackgrounddrawablebtn s01 list androidvisibilitybeanshouldhidecontrols viewgone viewvisible togglebutton androidididbtn radar androidlayout width48dp androidlayout height48dp androidbackgrounddrawablebtn radar selector androidcheckedfalse androidgravityend androidtext androidtextoff androidtexton androidvisibilitybtn listvisibilityand i got error426 39 identifiers must have user defined types from the xml file btn list is missing itediti missed an important point in the same talk the view ids are camelcasified,['android'] +1170838,are static methods with out arguments thread safe basically i have a few classes that call a static void that provides out arguments used in an asp website from my understand because the void has it is own stack it is threadsafe however i am not entirely sure if thats true when outs are used can someone clarify the issue thanksnamespace threadtestclass program static void mainstring args int helloworldint 0 bool helloworldbool false int helloworldintout 0 bool helloworldboolout false sethelloworldshelloworldint helloworldbool out helloworldintout out helloworldboolout consolewritelinehelloworldintout consolewritelinehelloworldboolout public static void sethelloworldsint helloworldint bool helloworldbool out int helloworldintout out bool helloworldboolout helloworldintout helloworldint 1 helloworldboolout true,"['c#', 'asp.net']" +1170965,how do zeroinitialization staticinitialization and valueinitialization differ ben voigt has pointed out here thatzero initialization is one of the steps of static initialization but youre right that you cannot blindly substitute the latter tag since zero initialization is also performed for value initialization however there is no need for a tag named zeroinitialization in the context of c because tags already exist for both static initialization and value initialization and those are more relevanti thought there was a case where it made sense to zeroinitialize rather than staticinitializing or valueinitializing or is zeroinitialization never going to happen in the wild and i should use more specific terms like staticinitialization or valueinitializationto be fair most of my experience on these topics comes from studying the answers to this question so i am sure ben voigt is right i would just like someone to spell out why,['c++'] +1171003,finding closest points to a certain point given its coordinates and maximum thistance query result undefined using mongoose with mean stack i have an issue that i was not able to solve in some days even looking at related stack overflow qai am developing an application reusing scotchs create a mean stack google map app tutorial by ahmed haque approachi am trying to implement an application that uses google maps api to draw points linestrings and polygons which coordinates are contained in geojson files that are stored in a mongodb instancei am using mongoose to build the schema for my data and query my mongodb database i would like to find the closest points cp to a certain points p0 given p0s latitude and longitude and given a maximum radius thistance used to find the interested pointsgiven the image over i would like that for example if i insert 20 kilometers my query will find all the points maximum 20 kilometers away from p0 in this example it should probably give me p1 and p2i was able to do it when i only had points in my mongoose schemai had this schema with only markers points pulls mongoose dependency for creating schemasvar mongoose requiremongoosevar schema mongooseschema creates a user schema var markerschema new schema username type string required true location type number required true long lat created at type date default datenow updated at type date default datenow indexes this schema in 2dsphere formatmarkerschemaindexlocation 2dspheremoduleexports mongoosemodelmeanmarkers markerschemaand this was my old query for only markersvar user requiremodeljsapostquery functionreq res grab all of the query parameters from the body var lat reqbodylatitude var long reqbodylongitude var thistance reqbodythistance var reqverified reqbodyreqverified opens a generic mongoose query var query userfind include filter by max thistance converting miles to meters if thistance using mongodbs geospatial querying features query querywherelocationnear center type point coordinates long lat converting meters to miles maxthistance thistance 160934 spherical true it worked really well and i was able to get close pointsthen i changed my schema to be more dynamic and also support polylines and polygons i am able to insert and draw new points polylines and polygons with the following schema var mongoose requiremongoosevar geojson requiregeojsonvar schema mongooseschema creates a location schemavar locationschema new schema name type string required true location type type string required true coordinates schematypesmixed created at type date default datenow updated at type date default datenowlocationschemaindexlocation 2dspheremoduleexports mongoosemodelmeanlocations locationschemaand this is my mongoose queryvar geoobjects requiremodeljsapostquery functionreq res grab all of the query parameters from the body var lat reqbodylatitude var long reqbodylongitude var thistance reqbodythistance var query if thistance query geoobjectsfindlocationtypepoint wherelocationcoordinatesnear center type point coordinates lat long converting meters to miles maxthistance thistance 160934 spherical true execute query and return the query results queryexecfunctionerr users if err ressenderr consolelogusers if no errors respond with a json of all users that meet the criteria resjsonusers consolelogusers gives me undefinedlogging query results in my queryctrljs gives me the following error messagename mongoerror message error processing query nsmeanmapappmeanlocatioaed error unable to find index for geonear query waitedms 0 ok 0 errmsg error processing query nsmeanmapappmeanlocatioaed error unable to find index for geonear querysame with a little variationapostquery functionreq res grab all of the query parameters from the body var lat reqbodylatitude var long reqbodylongitude var thistance reqbodythistance consoleloglatlongthistance var points geoobjectsfindlocationtypepoint var loc parsefloatpointslocationcoordinates consolelogjsonstringifyloc if thistance var query pointsnearloc center type point coordinates parsefloatlat parsefloatlong converting meters to miles maxthistance thistance 160934 spherical true this is an example of a marker name user01 location typepoint coordinates 1020 00 how near operator works with thistance and maxthistancefrom scotchs making mean apps with google maps part ii by ahmed haquemongodb search parameter near and its associated properties maxthistance and spherical to specify the range weare looking to cover weare multiplying the thistance of our query body by 160934 because we want to take our usersa input in miles and convert it into the units mongodb expects in meterswhy am i getting undefinedis it possible that this problem is caused by my schemahow can i fix thisif you would like to receive some clarifications just post a comment belowthanks in advance,['javascript'] +1171166,jsdom not returning document i am trying to use jsdom to load a local html file this is the code var config file filename scripts node modulesjquerythistjqueryminjs done functionerr window consolelogwindowdocumenturl consolelogwindowdocumentchildren jsdomenvconfigwindowdocumenturl thisplays the correct url but windowdocumentinnerhtml doesnt have any data ive even triedvar config text rawhtml scripts node modulesjquerythistjqueryminjs done functionerr window consolelogwindowdocumentchildren but i had the same results any helpupdatei have found that var rawhtml fsreadfilesyncfilenamehtmlutf8jsdomenv rawhtml function err window consolelogwindowhtmlhtml works as expected it logs everything inside the html tagsi then found thatconfig file filenamehtml scripts done function err window var window consoleloghtmlhtml jsdomenvconfig also works but again neither will create the document object correctlysolutionjsdom does not show the output of documentchildren in the same way a browser console would however all of the functionality you would expect is there i found this extremely confusing and the confusion was only exacerbated by the fact that i was following incorrect guides to jsdom i hope my post will help anyone experiencing the same issues i will post a final working document object belowvar func functiondocument consolelogdocumentbodyinnerhtml documentbodyinnerhtml i changed the bodyfunction getdocfile func var document jsdomenv file err window document windowdocument funcdocument getdocindexhtmlcodei use jsdomenv to get the document then pass the document to func where all the fun javascript magic is free to happen keep in mind that any changes made to the document need to be manually saved,"['javascript', 'html']" +1171177,bytecode optimization here are 2 simple examples in the first example append method produces load attr instruction inside the cycle in the second it only produced once and result saved in variable ie cached reminder i remember that there extend method for this task which is much faster that thissetup list another list i for i in range107def appenderlist anohter list for elem in anohter list listappendelemdef appender optimizedlist anohter list append method listappend for elem in anohter list append methodelemimport timeitprinttimeittimeitappenderlist another list setupsetup number10printtimeittimeitappender optimizedlist another list setupsetup number10results1192684596051036738420578558472846 seconds difference even for such a big list is no joke for my opinion such difference can not be counted as micro optimization why python does not do it for me because bytecode must be exact reflection of source code do compiler even optimize anything for example def te a 2 a 1 a 1 a 1 a 1producesload fast 0 aload const 2 1inplace addstore fast 0 a4 times instead of optimize into a 4 or do it optimize some famous things like producing bit shift instead of multiplying by 2 am i misunderstand something about basic language concepts,['python'] +1171269,how to draw two directions widths line in matplotlib how to use matplotlib or pyqtgraph draw plot like thisline ab is a twodirections street green part represents the direction from point a to point b red part represents b to a width of each part represents the traffic volume widths are measured in point will not changed at different zoom levels or dpi settingsthis is only an example in fact i have hunderds of streets this kind of plot is very common in many traffic softwares i tried to use matplotlibs patheffect but result is frustratedfrom matplotlib import pyplot as pltimport matplotlibpatheffects as path effectsx0123y1001ab width20ba width30fig axes pltsubplots11center line axesplotxycolorklinewidth2center lineset path effectspath effectssimplelineshadowoffset0 ab width2shadow colorg alpha1 linewidthab widthpath effectssimplelineshadowoffset0 ba width2 shadow colorr alpha1 linewidthba widthpath effectssimplelineshadowoffset0 ab width shadow colork alpha1 linewidth2path effectssimplelineshadowoffset0 ba width shadow colork alpha1 linewidth2path effectsnormalaxesset xlim14axesset ylim1515one idea came to me is to take each part of the line as a standalone line and recalculate it is position when changing zoom level but it is too complicated and slow if there any easy way to use matplotlib or pyqtgraph draw what i want any suggestion will be appreciated,['python'] +1171369,saveupdate fragments edittext data in a fragmentstatepageradapter introductioni have an activity with a book that contains an arraylist of type page and to handle all the pages i decided to use a fragmentstatepageradapter in which one of my fragment contains one page i created an interface for the communication between every fragment in the pager and the father activity the method that i need in this interface is for update a page showed in a fragment so i made implement to the father activity the interface for receiving the data from a fragment and store them in a page to save in the arraylistevery fragment has an edittext in which the user can write and i set an addtextchangedlistener to catch the moment when the user stops to writewhen the user stops to write in the edittext in the ontextchanged i call the function implemented in the activity father this is my activity code public class bookeditoractivity implements bookeditorfragmenteditorfrtoeditoractinterface override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutbook editor activity bundle extras getintentgetextras b book extrasgetbook setbookviewpagerb private void setbookviewpagerbook b mbookviewpager viewpager findviewbyidridbook editor pager mbookviewpageradapter new bookviewpageradaptergetsupportfragmentmanager b mbookviewpagersetadaptermbookviewpageradapter override public void savebookpagetextcontentstring textcontent int current mbookviewpagergetcurrentitem if bgetpagesgetcurrent instanceof bookpagetext bookpagetext bgetpagesgetcurrentsetcontentpagetexttextcontent override public void newbookpagetext int current mbookviewpagergetcurrentitem bookpagetext bookpagetext new bookpagetext bookpagetextsetcontentpagetext bgetpagesaddbgetpagessize 1 bookpagetext setindicatorcurrent 1 bgetpagessize mbookviewpageradapternotifydatasetchanged this is the fragment codepublic class bookeditorfragment extends fragment private editorfrtoeditoractinterface mcallback public interface editorfrtoeditoractinterface void newbookpagetext void savebookpagetextcontentstring s override public void oncreatebundle savedinstancestate superoncreatesavedinstancestate bundle pagecontent getarguments if pagecontent null page pagecontentgetparcelablepage nullable override public view oncreateviewlayoutinflater inflater viewgroup container bundle savedinstancestate if page instanceof bookpagetext bookpagetext bookpage bookpagetext page mview inflaterinflaterlayoutbook page text fragment container false contentpage edittext mviewfindviewbyidridcontent text string contentpagetext bookpagegetcontentpagetext contentpagesettextcontentpagetextisempty htmlfromhtmlcontentpagetext contentpageaddtextchangedlistenernew textwatcher public void ontextchangedcharsequence c int start int before int count mcallbacksavebookpagetextcontentctostring public void beforetextchangedcharsequence c int start int count int after public void aftertextchangededitable c return mview override public void onattachcontext context superonattachcontext try mcallback editorfrtoeditoractinterface context catch classcastexception e throw new classcastexceptioncontexttostring must implement newpageinterface override public void ondetach mcallback null superondetach override public void onclickview v switch vgetid case rideditor new text mcallbacknewbookpagetext break this is the fragmentstatepageradapter code public class bookviewpageradapter extends fragmentstatepageradapter private arraylistobject bookpages new arraylist private final sparsearrayweakreferencebookeditorfragment instantiatedfragments new sparsearray public bookviewpageradapterfragmentmanager fm book b superfm thisbookpages bgetpages override public fragment getitemint position object page bookpagesgetposition bundle pagecontent new bundle if page instanceof bookpagetext bookpagetext bookpagetext bookpagetext page pagecontentputparcelablepage bookpagetext bookeditorfragment fragment new bookeditorfragment fragmentsetargumentspagecontent return fragment override public int getcount return bookpagessize override public object instantiateitemfinal viewgroup container final int position final bookeditorfragment fragment bookeditorfragment superinstantiateitemcontainer position instantiatedfragmentsputposition new weakreferencefragment return fragment override public void destroyitemfinal viewgroup container final int position final object object instantiatedfragmentsremoveposition superdestroyitemcontainer position object nullable public fragment getfragmentfinal int position final weakreferencebookeditorfragment wr instantiatedfragmentsgetposition if wr null return wrget else return null override public int getitempositionobject object int position bookpagesindexofobject return position 1 position none position due to the code length i removed some parts like the onclicklistener onpageselectionlistener and other types of pages that i am creating right nowthe problemthis logic seems to work properly but every time that i modify the the content of an edittext in a fragment the close fragment to the left is also updated and i do not know whyas you can see in the image if i write something in the edittext2 the same content will appear in the edittext1 and this makes no senseanother problem is when i add a new page in the book the page is created correctly but with the content of the previous page and this makes no sense againmy attempts1 i tried to catch the onfocuschange instead of using the addtextchangedlistener but nothing changed2 i tried to implement a different logic using the onchangepagelistener but in this case i loose the mbookviewpagergetcurrentitem so the update goes wrong3 i tried this all this posts one two three and four how can i correct this strange behaviouris it possible that the problem is in the way i reference the pages in the arraylist of the bookthanks,['android'] +1172285,no access or ambiguity check on templated member function found in multiple base classes this compiles and runs fine on visual c 2015 update 3 rcclass a template class t void f class b a class c a class d b c int main d d dfintthere is two problems with this codef is private so dfint should fail to compilef is ambiguous as it could be bf or cfhowever there is no diagnostic with wall and bf is called reversing the order d inherits from gets cf called so i guess it is just using the first base class in the listboth g and clang get it right am i missing something or is this a bug in visual c,['c++'] +1172711,what function does the compiler perform when it first reaches the include statement in a c program i have come across this question while preparing for the interview what function does the compiler perform when it first reaches the include statement in a c program i googled about it and as far as i could understand if i am not wrong here is that it includes all the macros or definitions that are defined in the include filename into the source code at that point in the program is this correct answer and is that all the compiler does for the include statementif anybody can give some answers for the same it would be really helpfulappreciate the responsethanks,['c'] +1172928,checkbox selection in primefaces tree table not working i am creating a multi tab page by using primefaces the page may contain an add button if the person click the add button the tab dynamically addedin that dynamic tab i enclose a tree table by using with a checkbox selectionin this page every value is stored in the bean list which is the value of a tabviewthe problem isi got the selectionnode value in the first tab but not able to get the value in other tabs in log the selection node value is null in the other tabs i tried the technique of changing the scope of session and view but failedi enclosed all the code belowkindly help me over itindexxhtmluicomposition xmlns xmlnsh xmlnsf xmlnsp xmlnsui xmlnsc hhead title dynamic view in list title hhead hbody fevent listenerdynamictabinitializepageattributes typeprerendercomponent hform iddynamicformid ppanel idmainpanelid widgetvarmainpanelid pcommandbutton idaddbuttonid iconuiiconcircleplus actiondynamictabaddbuttonaction updatemainpanelid rendereddynamictabaddbuttonrendered pgrowl idmsgs showdetailtrue escapefalse ptabview idtabviewid activeindexdynamictabactiveindex valuedynamictabsamplelist varusecase dynamictrue pajax eventtabchange listenerdynamictabontabchange updateidmainpanelid pajax eventtabclose listenerdynamictabontabclose updateidmainpanelid ptab idtabid closabletrue titleusecasesstid ppanel idsampleid houtputtext valuesst id houtputtext valueusecasesstlabel pcommandbutton iduploadbuttonid iconuiiconcirclearrown actionlistenerdynamictabuploadbuttonaction updateidmainpanelid ptreetable valueusecaserootnode vardocument selectionmodecheckbox selectionusecaseselectednodes ffacet nameheader tab view ffacet pcolumn headertextname houtputtext valuedocumentname pcolumn pcolumn headertextsize houtputtext valuedocumentsize pcolumn pcolumn headertexttype houtputtext valuedocumenttype pcolumn ptreetable ppanel ptab ptabview ppanel hform hbodyuicompositionby click the add upload button action i use the java code belowdynamictabjavapublic class dynamictab private htmlform initform private int count 0 private logger logger loggergetloggergetclass private listdynamicbean samplelist new arraylistdynamicbean private short activeindex private boolean addbuttonrendered private treenode root public void initializepageattributes loggerinfoenter inside initializepage count 0 if samplelist null samplelistisempty samplelistclear addbuttonrendered true private void addvalues formtree dynamicbean dynamic new dynamicbean dynamicsetsstidsst count dynamicsetsstlabelsst0 count dynamicsettabindexstringvalueofcount dynamicsetactiveindexactiveindex dynamicsetrootnoderoot dynamicsetselectednodesnull samplelistadynamic private void formtree root new checkboxtreenodenew documentfiles folder null treenode documents new checkboxtreenodenew documentdocuments folder root treenode pictures new checkboxtreenodenew documentpictures folder root treenode movies new checkboxtreenodenew documentmovies folder root treenode work new checkboxtreenodenew documentwork folder documents treenode primefaces new checkboxtreenodenew documentprimefaces folder documents documents treenode expenses new checkboxtreenodedocument new documentexpensesdoc 30 kb word document work treenode resume new checkboxtreenodedocument new documentresumedoc 10 kb word document work treenode refdoc new checkboxtreenodedocument new documentrefdocpages 40 kb pages document primefaces pictures treenode barca new checkboxtreenodepicture new documentbarcelonajpg 30 kb jpeg image pictures treenode primelogo new checkboxtreenodepicture new documentlogojpg 45 kb jpeg image pictures treenode optimus new checkboxtreenodepicture new documentoptimusprimepng 96 kb png image pictures movies treenode pacino new checkboxtreenodenew documental pacino folder movies treenode deniro new checkboxtreenodenew documentrobert de niro folder movies treenode scarface new checkboxtreenodemp3 new documentscarface 15 gb movie file pacino treenode carlitosway new checkboxtreenodemp3 new documentcarlitos way 24 gb movie file pacino treenode goodfellas new checkboxtreenodemp3 new documentgoodfellas 23 gb movie file deniro treenode untouchables new checkboxtreenodemp3 new documentuntouchables 17 gb movie file deniro public string addbuttonaction addbuttonrendered samplelistsize 4 count count 1 addvalues return null public void ontabchangetabchangeevent event facesmessage msg new facesmessagetab changed active tab eventgettabgettitle facescontextgetcurrentinstanceaddmessagenull msg public void ontabclosetabcloseevent event facesmessage msg new facesmessagetab closed closed tab eventgettabgettitle facescontextgetcurrentinstanceaddmessagenull msg tabview tabview tabview eventgetcomponent addbuttonrendered true listdynamicbean tempbeanlist new arraylistdynamicbean tempbeanlistaddallsamplelist for dynamicbean dynamicbean tempbeanlist if dynamicbeangetsstidequalsignorecaseeventgettabgettitle samplelistremovedynamicbean public string uploadbuttonaction dynamicbean dynamic samplelistgetactiveindex if dynamic null if dynamicgetselectednodes null for treenode subtree dynamicgetselectednodes document doc document subtreegetdata loggerinfo name docgetname loggerinfo type docgettype loggerinfo size docgetsize else loggerinfothe selected node is null else loggerinfodynamic is null return null public void thisplayselectedmultipletreenode nodes if nodes null nodeslength 0 stringbuilder builder new stringbuilder for treenode node nodes builderappendnodegetdatatostring builderappendbr facesmessage message new facesmessagefacesmessageseverity info selected buildertostring facescontextgetcurrentinstanceaddmessagenull message return the initform public htmlform getinitform return initform param initform the initform to set public void setinitformhtmlform initform thisinitform initform return the samplelist public listdynamicbean getsamplelist return samplelist param samplelist the samplelist to set public void setsamplelistlistdynamicbean samplelist thissamplelist samplelist return the activeindex public short getactiveindex return activeindex param activeindex the activeindex to set public void setactiveindexshort activeindex thisactiveindex activeindex return the addbuttonrendered public boolean isaddbuttonrendered return addbuttonrendered param addbuttonrendered the addbuttonrendered to set public void setaddbuttonrenderedboolean addbuttonrendered thisaddbuttonrendered addbuttonrendered the bean class dynamic bean contains the following variables and their gettersettersdynamicbeanjavapublic class dynamicbean private string sstid private string sstlabel private string tabindex private string pagepath private short activeindex private treenode rootnode private treenode selectednodesthe tree table bean class documentjava public class document implements serializable comparabledocument private string name private string size private string type public documentstring name string size string type thisname name thissize size thistype type public string getname return name public void setnamestring name thisname name public string getsize return size public void setsizestring size thissize size public string gettype return type public void settypestring type thistype type eclipse generated hashcode and equals override public int hashcode final int prime 31 int result 1 result prime result name null 0 namehashcode result prime result size null 0 sizehashcode result prime result type null 0 typehashcode return result override public boolean equalsobject obj if this obj return true if obj null return false if getclass objgetclass return false document other document obj if name null if othername null return false else if nameequalsothername return false if size null if othersize null return false else if sizeequalsothersize return false if type null if othertype null return false else if typeequalsothertype return false return true override public string tostring return name public int comparetodocument document return thisgetnamecomparetodocumentgetname,['java'] +1173192,passing constants in a recursive function i am refactoring some code and wondering what pattern is least memory intensive and easiest to read when it comes to passing constants in a recursive functionfor example i could just pass each constant down to the next recursive function but it is not obvious that those params are constantsconst startfoo myarray isfoo isbar consolelogisfoo isbar startfoomyarray isfoo isbaralternatively i could have 2 functions and keep constants in the closure of the first but i am curious if recreating the second function every time the first is called will cause unnecessary object creation gcconst startfoo myarray isfoo isbar const foo myarray consolelogisfoo isbar foomyarray foomyarrayfinally i could keep it at one function and just cache the initial valuesconst startfoo myarray isfoo isbar if startfoocache startfoocache isfoo isbar const isfoo isbar startfoocache consolelogisfoo isbar startfoomyarrayall 3 look like they will be good candidates for the upcoming hereish tco so i do not see that playing into the decision but if it does that would be good to know as well,['javascript'] +1173202,why a button is clicked when a form is submitted say i have a form with a text input and a submit buttonif there are no buttons in the form just submit event triggers but if there is at least one button with no type attribute or with typesubmit it clicks it toonow when i enter something in the input and then press enter i see that both button click and form submit events are triggeredexampleform input typetext button onclickalertsubmittedsubmitbuttonformi suppose the form clicks the button automatically on the form submit eventi wonder the origins and the reason for such behaviorwhy do i need the button to be clicked when i submit the form,"['javascript', 'html']" +1173270,fast numpy loops how do you optimize this code without vectorizing as this leads up to using the semantics of the calculation which is quite often far from being nontrivialslow libpyimport numpy as npdef foo size 200 nprandomseed1031212 bar nprandomrandsize size moo npzerossizesize dtype npfloat for i in range0size for j in range0size val barj moo npouterval valthe point is that such kind loops correspond quite often to operations where you have double sums over some vector operationthis is quite slowt timeittimeitfoo from slow lib import foo number 10print took strttook 41165681839ok so then let us cynothize it and add type annotations likes there is no tomorrowc slow libpyximport numpy as npcimport numpy as npimport cythoncythonboundscheckfalsecythonwraparoundfalsedef foo cdef int size 200 cdef int ij nprandomseed1031212 cdef npndarraynpdouble t ndim2 bar nprandomrandsize size cdef npndarraynpdouble t ndim2 moo npzerossizesize dtype npfloat cdef npndarraynpdouble t ndim1 val for i in xrange0size for j in xrange0size val barj moo npouterval valt timeittimeitfoo from c slow lib import foo number 10print took strttook 423104710579 ehr what numba to the rescuenumba slow libpyimport numpy as npfrom numba import jitsize 200nprandomseed1031212bar nprandomrandsize sizejitdef foo bar nprandomrandsize size moo npzerossizesize dtype npfloat for i in range0size for j in range0size val barj moo npouterval valt timeittimeitfoo from numba slow lib import foo number 10printtook strttook 407327859402so is there really no way to speed this up the point isif i convert the inner loop into a vectorized version building a larger matrix representing the inner loop and then calling npouter on the larger matrix i get much faster codeif i implement something similar in matlab r2016a this performs quite well due to jit,['python'] +1173375,when a div of images wraps possible to treat the wrap like a span i have a div full of imagesspecies backgroundcolor lightblue margintop 20px thisplay inlineblockanimals thisplay inline margin 0 marginright 25px margintop 5pxanimal width 25px padding 8px 2px 0 2px thisplay inlinediv claspecies div classanimals img classanimal srcantpng img classanimal srcantpng img classanimal srcantpng img classanimal srcantpng img classanimal srcantpng img classanimal srcantpng img classanimal srcantpng imagine about 30 more ants divdivsince my content well is limited to 600px the div animals containing the ants wraps like sobut i want it to wrap like a span ending with the last ant like this created in photo editorhowever if i give the parent div an inline thisplay or change it to a span the parent does not expand to the height of the images so i get thisfiddle exampleso my question is it possible to get the best of both worlds here between divs and spans where the container sizes to the height of the images but does not expand to the width of the page on the last rowi have tried various css commands for wrapping text and whitespace to no avail,"['html', 'css']" +1173549,hide strange unwanted xcode 8 logs when using the xcode 8 beta 1 and creating a new blank project the following logs appear when running the appliation20160613 1634406093 testios108209100611 bundleid comappctestios10 enable level 0 persist level 0 propagate with activity 020160613 1634406323 testios108209100607 created db header sequence number 24820160613 1634409564 testios108209100611 subsystem comappleuikit category hidevents enable level 0 persist level 0 default ttl 0 info ttl 0 debug ttl 0 generate symptoms 0 enable oversize 0 privacy setting 020160613 1634504117 testios108209100607 created db header sequence number 24820160613 1634548023 testios108209100607 subsystem comapplebaseboard category machport enable level 0 persist level 0 default ttl 0 info ttl 0 debug ttl 0 generate symptoms 0 enable oversize 0 privacy setting 020160613 1634568458 testios108209100608 subsystem comapplefrontboard category common enable level 0 persist level 0 default ttl 0 info ttl 0 debug ttl 0 generate symptoms 0 enable oversize 0 privacy setting 0i know we are in a very early stage of ios 10 development but maybe someone already found a configuration for this to handle,['ios'] +1173795,options failed only on chrome and firefox i make a post request and the request just sits pending until it eventually fails i have monitored the nginx logs and the node server logs and the request does not even register this works for anyone else that i have had test it except one other colleague if i use the edge browser or a different computer it works finei have attempted to make post requests to other custom servers and it hangs on options there as well i have also made the post request with jquery and it fails the same wayit is maybe worth noting that i am using the withcredentials flagheadersprovisional headers are shownaccesscontrolrequestheaderscontenttypeaccesscontrolrequestmethodgetoriginhttplocalhost8080refererhttplocalhost8080pathuseragentmozilla50 windows nt 100 wow64 applewebkit53736 khtml like gecko chrome510270484 safari53736the request public loginuser const endpoint httpurl let headers new headers headersappendcontenttype applicationjson return thishttp postendpoint jsonstringifyuser headers headers i subscribe to the call in my componentthis accountserviceloginthisuser subscriberes consoleloglogged in if resjsonstatus success windowlocationhref homethisorgthisproduct else what other options are there consolelogdo something else maybe err thisinvalidlogin true consolelogye shall not pass successful users headersacceptacceptencodinggzip deflate sdchacceptlanguageenusenq08accesscontrolrequestheaderscontenttypeaccesscontrolrequestmethodpostconnectionkeepalivehosturloriginurlrefererurluseragentmozilla50 windows nt 100 win64 x64 applewebkit53736 khtml like gecko chrome5202743 safari53736from chromenetinternalseventst61869793 st 0 request alive dt60162 has upload false is pending true load flags 34624 do not save cookies do not send auth data do not send cookies maybe user gesture verify ev cert load state 14 waiting for response method options net error 1 err io pending status io pending url urlt61929955 st60162 http stream parser read headers net error 324 err empty responset61929955 st60162 http transaction read headers net error 324 err empty responset61929955 st60162 url request start job net error 324 err empty responset61929955 st60162 url request delegate dt0t61929955 st60162 request alive net error 324 err empty responsei am really guessing this is related to something that is cached in my browsers but i really cannot find what i have cleared all cookies and anything that could be stored where else can i check to clear things this is clearly something local to my computerbrowser and one other unfortunate person,['javascript'] +1173828,thisable viewport zooming ios 10 safari i have update my iphone6 plus to ios 10 beta version and just found that in mobile safari you can zoom any webpages by double tapping or pinching ignoring the userscalableno code in the meta tag i do not know whether it is a bug or feature if it is considered as a feature how do we thisable viewport zooming ios 10 safari,"['ios', 'css']" +1173833,javascript how to add getter to an existing object i can have getter in javascript object like thisvar member firstnamexyz lastnamez get fullname return thisfirstname thislastname and i can even add more properties on the fly like thismemberisguest truebut is there any way we can add getters to already existing object something like thismemberisguest get isguest return thisfirstnameguest,['javascript'] +1173869,case when a value is different to other value sql server i have this table structure for table pricescreate table prices id int pricefrom int priceup intinsert into prices id pricefrom priceupvalues 1 23 23 2 0 0 3 12 13 4 40 40 5 15 15 6 0 0this is the result i have this queryselect pricefrom priceup case when pricefrom 0 then null when pricefrom priceup then pricefrom priceup when pricefrom priceup then pricefrom end as finalpricefrom priceswhat i need is to do a case when pricefrom 0 then show null pricefrom priceup then show the priceat least if pricefrom priceup i want to show for example this 12pricefrom 13priceupbut in my query in this linei try to do this with but in the result appears the sum for both numbershow can i fix this,['sql'] +1174353,saving and loading a linked list to a binary file c i am trying to write and read a linked list from a binary file in cmy aim is saving and loading resident data for a nursing home actually i am a nurse in order to classify each resident via the resource utilization groups i have already done it for a fixed amount of residents 32 that is the capacity of the facility using an array of structures but now i need to do so for a variable set of residents in order to do a statistic study obviously for this first attempt i simplified the structure to the minimum as the actual structure contains 109 datai am very close to the solution but something does not work that is each element of the saved list is alternated with a void onethis code should read the list from the binary file show it on the terminal add a new element save the list of course each procedure should be put in a functioninclude stdiohinclude stdlibhinclude stringhinclude ncurseshstruct pat char surn 16 char name 16 struct pat nextstatic file hstatic struct pat ospstatic struct pat firststruct pat make structure voidint main initscr raw keypad stdscr true noecho clear ospmake structure firstosp hfopen archivior if hnull printw archivio inesistenten else while feofh printw lungh nome dnsizeof ospname fread ospsurnsizeof ospsurn1h fread ospnamesizeof ospname1h printw cognome stnome snospsurnospname ospnextmake structure ospospnext getch echo printw surname scanw sospsurn printw nname scanw sospname noecho ospfirst hfopen archiviow while osp null fwrite ospsurnsizeof ospsurn1h fwrite ospnamesizeof ospname1h ospospnext return 0struct pat make structurevoid struct pat a a struct pat mallocsizeofstruct pat return a,['c'] +1174439,xcode 7 or 8 issue with pods cannot run at all getting this error for pods in xcode when trying to run apperror a cryptographic verification failure has occurredtried reinstalling podsreporeinstalling xcodesalso does not run on simulatorsalso running sierra at the moment yes i know,['ios'] +1175220,deeply assign javascript object literal i am trying to deeply assign a value in an object for exampleconst errors iferroronspecificfield typeerror cannot read property subsubcategory of undefineda errorssubcategorysubsubcategoryfieldwitherror error messageright now without lodash i can doconst errors iferroronspecificfield errorssubcategory errorssubcategory errorssubcategorysubsubcategory errorssubcategorysubsubcategory errorssubcategorysubsubcategoryfieldwitherror error messagewith lodash i can do thisconst errors iferroronspecificfield seterrors subcategorysubsubcategoryfieldwitherror error messagei am trying to avoid using a third party library is there a more elegant solution especially now that es2015 has object destructuring the inverse operation is easy let subcategory subsubcategory fieldwitherror errorswhat is an elegant solution to deep object assignment thanks,['javascript'] +1175866,what language standards allow ignoring null terminators on fixed size arrays we are transitioning c code into ci noticed that the following code is well defined in c int main length is valid 0 is ignored char str3abcas it is stated in array initialization that if the size of the array is known it may be one less than the size of the string literal in which case the terminating null character is ignoredhowever if i were to build the same code in c i get the following c error error initializerstring for array of chars is too longfpermissive char str3abci am hoping someone can expound on this questionsis the code example valid in all c language standardsis it invalid in all c language standardsis there a reason that is valid in one language but not another,"['c++', 'c']" +1175891,calling an associative function with c macros not to be confused with having anything to do with associative arraysi know how to vectorize a function in c with macros to give results similar to the mathematicas map or apply functionality namely apply a function to a list of arguments define apply type function void stop int0 type list type va args stop for int i 0 listi stop i function listi i can then do something likedefine freeallatonce apply void free va args which has the effect thatfree array1 free array2 free array3 is equivalent tofreeallatonce array1 array2 array3 i did not make that up i read about it in a book and have used it heavily since my question is can i do something similar to associatively combine an array via some binary function for example take the gcd function i want a function likegcd all a b c d e that has the same effect asgcd gcd gcd gcd a b c d e for any number of argumentsi have tried to do this and have not been able to properly make it work i am also interested in the case where there may be additional parameters passed to the function in the most generic sense i am looking to do this with functions likeatype binarycombine atype a atype b othertype z othertype y so that i have a functionatype binarycombineall atype a atype b atype c atype d othertype z othertype y i hope that makes sense any ideas or help would be very appreciatedthanks,['c'] +1175928,check value of input field and add a class i have two input fields and a submit button thisplayed inline i am trying to add a class to the next sibling after a input field is filled out so if the first name input field is filled out add a class to the email input field if the email input field is filled out add a class to the next input field and so onthis is my code so farformthisplay mcefnameblurfunction iftrimthisvaluelength mceemailtoggleclassanimated pulse else if my html looks like thisdiv classformthisplay div classmcfieldgroup label formcefnamefirst name label input typetext value namefname class idmcefname div div classmcfieldgroup label formceemailemail address label input typeemail value nameemail classrequired email idmceemail div input typesubmit valuesubscribe namesubscribe idmcembeddedsubscribe classbuttondiv,"['javascript', 'jquery', 'html', 'css']" +1176019,is changing the size of a struct a breaking change in c just curious is changing the size of a structvalue type a breaking change in c structs tend to be more sensitive in terms of memory layout since altering them directly affects the size of arraysother structs are there any examples of code that breaks either binarywise or sourcewise after the layout of a struct in a library it uses is changednote by breaks i mean it fails to compile at all or the il is invalidated so for example i wouldnt consider this a breaking change mylibrary v1public struct mystruct mylibrary v2public struct mystruct int field app codeusing mylibraryusing systemruntimeinteropservicesconsolewritelinemarshalsizeofmystruct before printed 1 now prints 4because it still runs,"['c#', '.net']" +1176074,how to unregister phone from firebase cloud messaging hello i am developing an test app using fcm i go through docs and also search on net but unable to find the option that how can a device token can be deleted from firebase database i have tried firebasegetinstanceiddeletetoken but it did not help thank you,['android'] +1176477,argument context cannot be null i used to have a facebook login button for 5 months in my application and it worked just as intended until today this nullpointerexception came up javalangnullpointerexception argument context cannot be null at comfacebookinternalvalidatenotnullvalidatejava76 at comfacebookinternalutilitygetmetadataapplicationidutilityjava594 at comfacebookappeventsappeventsloggerinitappeventsloggerjava757 at comfacebookappeventsappeventsloggerinitappeventsloggerjava732 at comfacebookappeventsappeventsloggernewloggerappeventsloggerjava400 at comfacebookfacebookbuttonbaselogbuttoncreatedfacebookbuttonbasejava225 at comfacebookfacebookbuttonbaseonattachedtowindowfacebookbuttonbasejava136 at comfacebookloginwidgetloginbuttononattachedtowindowloginbuttonjava452 at androidviewviewthispatchattachedtowindowviewjava14514 at androidviewviewgroupthispatchattachedtowindowviewgroupjava2843 at androidviewviewgroupthispatchattachedtowindowviewgroupjava2843 at androidviewviewgroupthispatchattachedtowindowviewgroupjava2843 at androidviewviewgroupthispatchattachedtowindowviewgroupjava2843 at androidviewviewgroupthispatchattachedtowindowviewgroupjava2843 at androidviewviewgroupthispatchattachedtowindowviewgroupjava2843 at androidviewviewgroupthispatchattachedtowindowviewgroupjava2843 at androidviewviewrootimplperformtraversalsviewrootimpljava1364 at androidviewviewrootimpldotraversalviewrootimpljava1107 at androidviewviewrootimpltraversalrunnablerunviewrootimpljava6013 at androidviewchoreographercallbackrecordrunchoreographerjava858 at androidviewchoreographerdocallbackschoreographerjava670 at androidviewchoreographerdoframechoreographerjava606 at androidviewchoreographerframethisplayeventreceiverrunchoreographerjava844 at androidoshandlerhandlecallbackhandlerjava739 at androidoshandlerthispatchmessagehandlerjava95 at androidoslooperlooplooperjava148 at androidappactivitythreadmainactivitythreadjava5417 at javalangreflectmethodinvokenative method at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava726 at comandroidinternaloszygoteinitmainzygoteinitjava616i suspect it is caused by the below manifest filexml version10 encodingutf8manifest xmlnsandroidpackageorangeoacausespermission androidnameandroidpermissionaccess network state usespermission androidnameandroidpermissionchange network state usespermission androidnameandroidpermissionget accounts usespermission androidnameandroidpermissionuse credentials usespermission androidnameandroidpermissioninternet usespermission androidnameandroidpermissionread phone stateusespermission androidnamecomgoogleandroidprovidersgsfpermissionread gservices usespermission androidnameandroidpermissionaccess coarse location usespermission androidnameandroidpermissionaccess fine location application androidallowbackuptrue androidiconmipmaplogooaca androidlabelstringapp name androidsupportsrtltrue androidthemestyleapptheme androidnameconfigsappcontroller notice this tag which provides the database name metadata androidnameoaca androidvalueoacadb notice this tag which provides the database version metadata androidnamedb version androidvalue1 metadata androidnameaa models androidvalueorangeoacamodeluserorangeoacamodelvolorangeoacamodelairportorangeoacamodelcategorieservicein metadata androidnamecomfacebooksdkapplicationid androidvaluestringfacebook app id metadata androidnamecomgoogleandroidgmsversion androidvalueintegergoogle play services version metadata androidnamecomgoogleandroidgeoapi key androidvalueaizasycumumhgrrtdt44y2xz5hwnpo9cqelbxsm activity androidnamesignup androidlabelstringapp name androidthemestyleappthemenoactionbar activity androidnamehomeactivity androidlabelstringapp name androidthemestyleappthemenoactionbar activity androidnamecomfacebookfacebookactivity androidconfigchangeskeyboardkeyboardhiddenscreenlayoutscreensizeorientation androidlabelstringapp name androidthemeandroidstylethemetranslucentnotitlebar activity androidnamecreercompte androidlabelstringtitle activity creer compte androidthemestyleappthemenoactionbar activity androidnamesplashscreen intentfilter action androidnameandroidintentactionmain category androidnameandroidintentcategorylauncher intentfilter activity activity androidnameflightlistview androidlabelstringtitle activity flight list view androidthemestyleappthemenoactionbar activity androidnameairportlistview androidlabelstringtitle activity airport list view androidthemestyleappthemenoactionbar activity androidnamedetailvol androidlabelstringtitle activity detail vol androidthemestyleappthemenoactionbaractivity applicationin addition android studio is making an unusual claim that there is no context whats going on here,['android'] +1176571,multiplication of two positive numbers gives a negative output in python 3 i have a dataframe df1 df1head wght num links id y id x 3 133 0203 2 186 0203 2 5 6 0203 2 98 0203 2 184 0203 2i need to calculate a variable called thr thr nn12where nis the number of rows of df1the problem is that when i calculate thrpython throws a negative valuealthough all of the inputs are positiveipdb df1wghtcountdf1wghtcount12712569744 possible hintthe number of rows and isipdb df1wghtcount 137736 thereforeipdb 137736137735237942135920taking into account that the max value that can be assigned to a int32 is 2147483647 i suspect that numpy considers typethr int32 when it should be int64 does this make sense please note that i have not written the code that generates df1 becauseipdb df1wghtcount 137736however if it is needed to reproduce the error let me know thanks in advance,['python'] +1176586,what is const void the description of stdis void states thatprovides the member constant value that is equal to true if t is the type void const void volatile void or const volatile voidthen what could be const void or a volatile void this answer states that const void return type would be invalid however compiles on vc 2015const void foo if by standard const void is invalid vc being wrong then what is const void,['c++'] +1176637,special donut chart with different ringsarcs for positive and negative values i am trying to create a special kind of donut chart in d3 which will contain different rings for positive and negative values the values can be greater than 100 or less than 100 so there will be an arc representing the remaining value below is the sample image of the chartthe first positive category category 1 gray value is 80 so it is 80 filling the the circle with gray leaving the 20 for next positive category the next positive category value category 2 orange is 160 so it is first using the 20 left by category 1 140 value left now then it is filling the next circle upward 100 40 value left now and for the remaining value 40 it is creating partialcircle upwardnow we have category 3 darkred as negative 120 so it if creating an inward circle and filling it 100 20 value left now and then it is creating an inward arc for remaining value 20 we have another negative category category 4 red so it will start from where the previous negative category category 3 ended and fill 20 area from thereedit 3 i have created a very basic arcbased donut chart and when total value is exceeding 100 i am able to create outer rings for the remaining values below is the jsfiddle linkdata 20 240var startangle 0var previousdata 0var exceedingdatavar cumulativedata 0var remainder 100var innerradius 60var outerradius 40var filledflagvar arc d3svgarc innerradiusinnerradius outerradiusouterradiusfor var i 0 i datalength i filledflag 0 exceedingdata 0 consolelog iteration i 1 if datai remainder filledflag 1 exceedingdata datai remainder consolelogexceeding exceedingdata datai datai exceedingdata datasplicei 1 0 exceedingdata if filledflag 1 cumulativedata 0 else cumulativedata datai consolelogprevious previousdata consolelogdata data current data datai var endangle previousdata datai 50 mathpi consolelogstart startangle end endangle previousdata previousdata datai 50 ifi1 endangle 14 mathpi ifi2 endangle 2 mathpi var vis d3selectsvg donut arcstartanglestartangleendangleendangle visappendpath attrd arc attrtransform translate200200 stylefill functiond if i 0 return red if i 1 return green if i 2 return blue if i 3 return orange if i 4 return yellow if exceedingdata 0 consolelogincreasing radius from outerradius to outerradius 40 outerradius outerradius 22 innerradius innerradius 22 arcinnerradiusinnerradiusouterradiusouterradius consolelogouter outerradius if remainder 100 remainder 100 datai else remainder 100 cumulativedata if filledflag 1 remainder 100 consolelogremainder remainder startangle endangleplease share some ideas for implementation,"['javascript', 'html']" +1176776,ios 10 does not print nslogs nothing prints from nslog on xcode 80 beta 8s128d printf is unchangedheres my codensloghello from nslogprintfhello from printfheres the output on ios 9 simulator20160617 094910887 calmappdev28517567025 hello from nsloghello from printfheres the output on ios 10 simulatorhello from printf,['ios'] +1177222,how to set a long click listener on a menuitem on a navigationview how can i set a long click listener on a menuitem i tried this answer but the method does not exist for me any solutionscode menu menu navigationviewgetmenumenuitem menuitem menufinditemridmenu item todo set a long click listener on the menuitemmenuitemsetonlongclicklistener method does not exist any other solutionsedit i do not want to set a custom actionview i want the long click listener to the whole menuitem without a custom view,['android'] +1177351,got unsupported class file version 520 after including a module to a project after creating an empty project within android studio and including a pure java module which compiles and works perfectly on its own i get the following error on every single class within that moduleerrorparse error errorunsupported class file version 520i tried to run the project using the embedded jdk and the one that i have on my system jdk 8 180 91 the result is the samenote this that i do not include the module as jar library it is source code which is importing with following instructioninclude app mymoduleprojectmymoduleprojectdir new filesettingsdir mymodulejava,"['java', 'android']" +1177388,bundler is removing ruby version from gemfilelock i am having the opposite issue to this one the gemfile hassource ruby 231at the end of my gemfilelock file isruby version ruby 231p112 bundled with 1124but when i run bundle install is always deleting ruby version regardless i am using the same as the development teams version even i am using a more recent bundler version than the used to generate the original gemfilelock file bundle vbundler version 1125 ruby vruby 231p112 20160426 revision 54768 x86 64linuxany ideas how can i stop this,"['ruby-on-rails', 'ruby']" +1177464,is boolean interned in java the following code for integer uses object interningintegervalueof1it is not clear from api documentation whether this code for boolean also uses interned objectbooleanvalueoftrueobviously it may but does it have toupdatei agree that source code can explain what actually happens btw thanks for the answers to make the question less trivial is there any part of java api spec or jsl which tells what must happenit was natural to ask the question against the code like thisstring str trueif booleanvalueofstr booleantrue the outcome depends on whether object interning is guaranteed or not it is better to avoid this code altogether and use true instead of booleantrue rather than looking up details in any specs or sources but it is a valid reason to ask the questionnote in fact i did not see guarantees of object interning for integer in any googled specs so it may all be just an implementation detail nobody should rely on,['java'] +1177558,is this a possible bug in net native compilation and optimization i thiscovered an issue with what might be overoptimization in net native and structs i am not sure if the compiler is too aggressive or i am too blind to see what i have done wrong to reproduce this follow these stepsstep 1 create a new blank universal win10 app in visual studio 2015 update 2 targeting build 10586 with a min build of 10240 call the project nativebug so we have the same namespacestep 2 open mainpagexaml and insert this labelpage xclassnativebugmainpage xmlns xmlnsx xmlnsd xmlnsmc mcignorabled grid backgroundthemeresource applicationpagebackgroundthemebrush insert this label textblock xname label horizontalalignmentcenter verticalalignmentcenter gridpagestep 3 copypaste the following into mainpagexamlcsusing systemusing systemcollectionsgenericnamespace nativebug public sealed partial class mainpage public mainpage initializecomponent var startpoint new point2d50 50 var points new new point2d100 100 new point2d100 50 new point2d50 100 var bounds computeboundsstartpoint points 15 labeltext boundsminx boundsminy boundsmaxx boundsmaxy private static rectangle2d computeboundspoint2d startpoint ienumerablepoint2d points double strokethickness 0 var lastpoint startpoint var cumulativebounds new rectangle2d foreach var point in points var bounds computeboundslastpoint point strokethickness cumulativebounds cumulativeboundsunionbounds lastpoint point return cumulativebounds private static rectangle2d computeboundspoint2d frompoint point2d topoint double strokethickness var bounds new rectangle2dfrompointx frompointy topointx topointy uncomment the line below to see the difference return strokethickness 0 bounds boundsinflate2strokethickness return strokethickness 0 bounds boundsinflate1strokethickness public struct point2d public readonly double x public readonly double y public point2ddouble x double y x x y y public struct rectangle2d public readonly double minx public readonly double miny public readonly double maxx public readonly double maxy private bool isempty minx 0 miny 0 maxx 0 maxy 0 public rectangle2ddouble x1 double y1 double x2 double y2 minx mathminx1 x2 miny mathminy1 y2 maxx mathmaxx1 x2 maxy mathmaxy1 y2 public rectangle2d unionrectangle2d rectangle if isempty return rectangle var newminx mathminminx rectangleminx var newminy mathminminy rectangleminy var newmaxx mathmaxmaxx rectanglemaxx var newmaxy mathmaxmaxy rectanglemaxy return new rectangle2dnewminx newminy newmaxx newmaxy public rectangle2d inflate1double value var halfvalue value 5 return new rectangle2dminx halfvalue miny halfvalue maxx halfvalue maxy halfvalue public rectangle2d inflate2double value var halfvalue value 5 var x1 minx halfvalue var y1 miny halfvalue var x2 maxx halfvalue var y2 maxy halfvalue return new rectangle2dx1 y1 x2 y2 step 4 run the application in debug x64 you should see this label425 425 1075 1075step 5 run the application in release x64 you should see this label75 75 75 75step 6 uncomment line 45 in mainpagexamlcs and repeat step 5 now you see the original label425 425 1075 1075by commenting out line 45 the code will use rectangle2dinflate2 which is exactly the same as rectangle2dinflate1 except it creates a local copy of the computations before sending them to the constructor of rectangle2d in debug mode these two function exactly the same in release however something is getting optimized outthis was a nasty bug in our app the code you see here was stripped from a much larger library and i am afraid there might be more before i report this to microsoft i would appreciate it if you could take a look and let me know why inflate1 does not work in release mode why do we have to create local copies,['c#'] +1177866,how to write unittests for an optional dependency in a python package based on availability of pandas package in working environment a method returns two different outputs a pandasdataframe if pandas is availableotherwise a numpyrecarray objecthow should i write unittest for this class one solution i can think of is to write tests for both cases with and without pandas installation and skip test accordingly something like thistry import pandas have pandas trueexcept importerror have pandas falseimport unittestclass testclassunittesttestcase unittestskipunlesshave pandas requires pandas def tests using pandasself do something unittestskipunlessnot have pandas does not require pandas def tests without pandasself do somethingbut i do not like this solution very much due to decrease in test coverage and skipping tests i want to run my tests for both cases it would be helpful if someone can suggest a better alternative solution for this,['python'] +1177938,why the compiler does not issue a warning when an object stdvector is declared but never used include vectorclass objectint main object myobject stdvectorint myvectorcompiler emitswarning unused variable myobject wunusedvariableno warning for myvector why is there any way to enable this,['c++'] +1177998,how to move from googleanalytics to firebaseanalytics backgroundin the recent months google has published a new analytics alternative called firebase analytics the problemas the app already does have googleanalytics i find some obstacles that i cannot see how to best handlethe questionspreviously newtracker function needed a propertyid now i do not see it does it mean it does not need onepreviously enableadvertisingidcollection was available to collect ads info too i cannot find it in new apis is it automatically collectedsetdryrun was available to thisable sending the data to the servers and now i do not see it does it mean it is automatically this way for debug versions of the app do all functions write to the logspreviously i could track a screen public void setscreennamestring name mgoogleanalyticstrackersetscreennamename mgoogleanalyticstrackersendnew hitbuildersscreenviewbuilderbuildnow i do not see it but as i have read i think it is automatic so it sends data of the activity lifecycle anyway is it trueprobably the most important thing previously i could track using category action label and valuepublic void trackeventfinal string category final string action final string label final long value mgoogleanalyticstrackersendnew hitbuilderseventbuilder setcategorycategorysetactionaction setlabellabelsetvaluevaluebuildand now i see a completely different way to track events custom events using bundles example bundle bundle new bundlebundleputstringfirebaseanalyticsparamitem id idbundleputstringfirebaseanalyticsparamitem name namebundleputstringfirebaseanalyticsparamcontent type imagemfirebaseanalyticslogeventfirebaseanalyticseventselect content bundlehow does it work how is it shown in the website of firebase analytics i suppose i could have the first parameter of logevent behave like the category parameter of the googleanalytics but what canshould i do for the rest according to the docs this should be okpublic void trackeventfinal string category final string action final string label final long value bundle bundle new bundle bundleputstringaction action bundleputstringlabel label bundleputlongvalue value mfirebaseanalyticslogeventcategory bundlewhich events are actually automatically being tracked i ask this because some are said that i should not use here do they include purchases appinvites ads where do i see them in the console website about logs it says that the new sdk does it by you can enable verbose logging with a series of adb commandsadb shell setprop logtagfa verbose adb shell setprop logtagfasvc verbose adb logcat v time s fa fasvcwhat do those commands do how can i thisable it i have noticed it even gets shown in release version of the appis the new sdk supposed to replace googleanalytics is it suggested to fully move to it will googleanalytics have any updates,['android'] +1178148,concatenating template parameter packs for a unary argument although say stdadd pointer is unary the following code is accepted by both gcc 700 20160608 and clang 390template typename tsstruct tc1 using a stdadd pointertshowever while the following code is accepted by clang it is rejected by gcctemplate typename tsstruct tc2 template typename us using b stdadd pointertsusis this valid c syntactically i could imagine that the comma is a problem when packs are empty but presumably it is elided on other occasions for example stdcommon type accepts zero or more arguments and the following presents no problem for either compilertemplate typename tsstruct tc3 template typename us using c stdcommon typetsus,['c++'] +1178484,how to capture window contents of a windows store app in c i have a bit of code to capture windows desktop app contents and save to a bitmap object in net it uses user32dll and gdi32dll bitblt and works just fine however the code produces allblack bitmaps when i give the code a handle to a window that holds a windows store app i am not sure if this is a security feature or what i cannot use the screencapture api as the contents of the window after being resized are almost always tallerlarger than the screen has anyone had any luck capturing window contents even when they are larger than the screen for a windows store appedit just as a note i am trying to capture a different programs window not my own program my program can be assumed to be a windows console application in net 461 calso i know that this must be possible somehow in windows apis because the aero peek feature where if you hover over the taskbar on the running programs icon shows the full height of the window including offscreen components see tall window on right set to 60px much higher than my thisplay,['c#'] +1178588,should i implement ithisposable when class has ithisposable member but no unmanaged resources the msdn documentation and many answers here on stackoverflow go to lengths to thisucss correctly implementing ithisposable eg msdn ithisposable msdn implementing ithisposable an excellent stackoverflow qa however none of them seem to cover a more common usecase i have what to do when my class has an ithisposable member that lives longer than one method for example class fantasticfileservice private filesystemwatcher filewatch filesystemwatcher is ithisposable public fantasticfileservicestring path filewatch new filesystemwatcherpath filewatchchanged onfilechanged private void onfilechangedobject sender filesystemeventargs e blah blah the closest msdn gets to addressing this problem only covers the usecase when the instance of ithisposable is short lived so says call thispose eg by using usingimplement ithisposable only if you are using unmanaged resources directly if your app simply uses an object that implements ithisposable do not provide an ithisposable implementation instead you should call the objects ithisposablethispose implementation when you are finished using itof course that is not possible here where we need the instance to survive longer than a method calli suspect the correct way to do this would be to implement ithisposable passing the responsibility to creator of my class to thispose it but without all finalizer and protected virtual void thisposebool thisposing logic becuase i do not have any unmanged resources ie class fantasticfileservice ithisposable private filesystemwatcher filewatch filesystemwatcher is ithisposable public fantasticfileservicestring watch filewatch new filesystemwatcherwatch filewatchchanged onfilechanged public void thispose filewatchthispose but why is this usecase not explicitly covered in any official documentation and the fact it explicitly says do not implement ithisposable if your class does not have unmanaged resources makes me hesitant to do so what is a poor programmer to do,"['c#', '.net']" +1179299,is it possible to wrap a flow type in an immutable container for example given the following recordtype userrecord id string name string age numberis there some way to do the equivalent of the following flow import list map from immutableconst users listmapuserrecord list let user mapuserrecorduser map id 6 age 30 userspushuserotherwise i end up simply using something like mapstring any which i think takes away from using immutablejs with the flow type system,['javascript'] +1179505,how to create managedobjectcontext using swift 3 in xcode 8 facing issue value of type appdelegate has no member managedobjectcontext in new xcode 8 using swift 3 ios 10 when trying to create new context in view controller let context uiapplicationshareddelegate as appdelegatemanagedobjectcontextin xcode 8 there is no code for managedobjectcontext inside appdelegateswift file core data stack code inside appdelegateswift presented only with lazy var persistentcontainer nspersistentcontainer property and func savecontext there is no managedobjectcontext propertyhow to create managedobjectcontext using swift 3 in xcode 8 or maybe there is no need to do it using swift 3,['ios'] +1180356,google firebase serializedeserialize i am new to firebase and i have 2 problems with it that might be connected first one is when saving my list of eventscreating eventtvevent tvevent new tveventettitlegettexttostringuser host resourcemanagergetuserstring date etdategettexttostringstring location etlocationgettexttostringtvset tvset resourcemanagergetusergettvsetsget0event ev new eventtvevent host date location tvsetresourcemanageraddeventevmdatabasechildeventschildhostgetidsetvalueresourcemanagergetevents getevents returns a list of eventsthis is what i get in the consolethe problem is that tvevent and tv set have more attributes than these ones when i debugged to find out why is that tvevent was created with all of its attributes which was a little strange for now however i do not know whether this is a problem as i cannot retrieve the tvset and tvevent from the database when i do the following i get the to be nullmdatabasechildeventsaddlistenerforsinglevalueevent new valueeventlistener override public void ondatachangedatasnapshot datasnapshot systemoutprintlncheking for events generictypeindicatorlistevent t new generictypeindicatorlistevent listevent e datasnapshotgetvaluet for datasnapshot messagesnapshot datasnapshotgetchildren generictypeindicatorlistevent t new generictypeindicatorlistevent listevent list messagesnapshotgetvaluet if list null for event ev list systemoutprintlnevent found resourcemanageraddeventev override public void oncancelleddatabaseerror databaseerror i do not know why these values are null as i can see that they are not in the firebase console so what is the problemignoreextrapropertiespublic class event private tvevent tveventprivate user hostprivate date dateprivate string locationprivate tvset tvsetprivate listuser attendingpublic eventpublic eventtvevent tvevent user host string date string location tvset tvset thistvset tvset thistvevent tvevent thishost host try thisdate new simpledateformatddmmyparsedate catch parseexception e eprintstacktrace thislocation location attending new arraylistpublic user gethost return hostpublic string getlocation return locationpublic tvset gettvset return tvsetpublic date getdate return datepublic tvevent gettvevent return tveventpublic void addattendinguser user attendingadduserpublic listuser getattending return attendingas both tvset and tvevent does not get deserialised properly i will post only one of themignoreextrapropertiespublic class tvset private string titleprivate string imagefileprivate bitmap picturepublic tvsetpublic tvsetstring title thistitle titlepublic tvsetbitmap picture imagefile compressimagepicturepublic void settitlestring title thistitle titlepublic string gettitle return titleprivate string compressimagebitmap image bytearrayoutputstream byte new bytearrayoutputstream imagecompressbitmapcompressformatpng 100 byte imagerecycle byte bytearray bytetobytearray string imagefile base64encodetostringbytearray base64default return imagefileexcludepublic bitmap getimage byte decodedstring base64decodeimagefile base64default bitmap bitmap bitmapfactorydecodebytearraydecodedstring 0 decodedstringlength return bitmappublic string getimagefile return imagefilesorry for the bad formatting any help is appreciated,['android'] +1180383,using a mutex to block execution from outside the critical section i am not sure i got the terminology right but here goes i have this function that is used by multiple threads to write data using pseudo code in comments to illustrate what i wantthese are initiated in the constructorint data stdatomicsize t sizevoid writeint value wait here while read lock set write lock to write lock 1 auto slot sizefetch add1 stdmemory order acquire dataslot value set write lock to write lock 1the order of the writes is not important all i need here is for each write to go to a unique slotevery once in a while though i need one thread to read the data using this functionint read set read lock to true wait here while write lock int ret data data new intcapacity size 0 set read lock to false return retso it basically swaps out the buffer and returns the old one i have removed capacity logic to make the snippets shorterin theory this should lead to 2 operating scenarios1 just a bunch of threads writing into the container2 when some thread executes the read function all new writers will have to wait the reader will wait until all existing writes are finished it will then do the read logic and scenario 1 can continuethe question part is that i do not know what kind of a barrier to use for the locks a spinlock would be wasteful since there are many containers like this and they all need cpu cyclesi do not know how to apply stdmutex since i only want the write function to be in a critical section if the read function is triggered wrapping the whole write function in a mutex would cause unnecessary slowdown for operating scenario 1so what would be the optimal solution here,['c++'] +1180740,how to parse timezone with datetime to a datetime parameter i am using saber soap api for flight bookingi have an datetime object which requires a parameter with the timezone the input should be like 20160301t10600at the moment i am getting the value like datetime dt datetimeutcnowstring date dttostringstring tstamp dttostringmmddythhmmsszdatetimeoffset tstamp datetimeoffsetparsedatedatetime datetime tstampdatetimebut when i convert it back to datetime the timezone gets removed automatically i cannot convert the object to datetimeoffset because the api requires it in the datetime format,['c#'] +1181089,c pointer to const array of const pointers i have created a const array of const pointers like soconst char const sessionlist datatable0 datatable1 datatable2 datatable3what is the correct syntax for a regular nonconst pointer to this array i thought it would be const char but the compiler thinks otherwise,['c++'] +1181325,references to getcurrentactivity make it impossible to build an inputmethodservice on android i am trying to build a custom keyboard with reactnative on android they are implemented with a inputmethodservice and thus it is really hard to provide an rnplay for i have tracked things down to the following code in the dialogmoduleclass filepublic void onhostresume thismisinforeground true dialogmodulefragmentmanagerhelper fragmentmanagerhelper thisgetfragmentmanagerhelper assertionsassertnotnullfragmentmanagerhelper attached dialogmodule to host with pending alert but no fragmentmanager not attached to an activity fragmentmanagerhelpershowpendingalert nullable private dialogmodulefragmentmanagerhelper getfragmentmanagerhelper activity activity thisgetcurrentactivity return activity nullnullactivity instanceof fragmentactivitynew dialogmodulefragmentmanagerhelperfragmentactivityactivitygetsupportfragmentmanagernew dialogmodulefragmentmanagerhelperactivitygetfragmentmanager here is how i am setting up my simpleimepackage comcustomkeyboardimport androidcontentcontextimport androidinputmethodserviceinputmethodserviceimport androidinputmethodservicekeyboardimport androidinputmethodservicekeyboardviewimport androidmediaaudiomanagerimport androidosbundleimport androidsupportannotationnullableimport androidviewkeyeventimport androidviewviewimport androidviewviewgroupimport androidviewinputmethodinputconnectionimport androidviewinputmethodinputmethodmanagerimport comfacebookreactlifecyclestateimport comfacebookreactreactinstancemanagerimport comfacebookreactreactpackageimport comfacebookreactreactrootviewimport comfacebookreactmodulescoredefaulthardwarebackbtnhandlerimport comfacebookreactshellmainreactpackageimport comgithubyamillorientationorientationpackageimport javautilarraysimport javautillistpublic class simpleime extends inputmethodservice implements keyboardviewonkeyboardactionlistenerdefaulthardwarebackbtnhandler private nullable reactinstancemanager mreactinstancemanager private nullable reactrootview mreactrootview private lifecyclestate mlifecyclestate lifecyclestatebefore resume private keyboardview kv private view v private keyboard keyboard private boolean caps false override public view oncreateinputview androidosdebugwaitfordebugger try v getlayoutinflaterinflaterlayoutkeyboard null kv keyboardview vfindviewbyidridkeyboard keyboard new keyboardthis rxmlqwerty kvsetkeyboardkeyboard kvsetonkeyboardactionlistenerthis inputmethodmanager imm inputmethodmanager getsystemservicecontextinput method service imm mreactinstancemanager createreactinstancemanager mreactrootview createrootview mreactrootviewstartreactapplicationmreactinstancemanager getmaincomponentname getlaunchoptions thisgetwindowsetcontentviewmreactrootview insert into main view viewgroup insertpoint viewgroup vfindviewbyidridlinview insertpointaddviewmreactrootview new viewgrouplayoutparamsviewgrouplayoutparamsmatch parent viewgrouplayoutparamsmatch parent vinvalidate catch exception e int z 1 int y 2 return v returns the launchoptions which will be passed to the link reactinstancemanager when the application is started by default this will return null and an empty object will be passed to your top level component as its initial props if your react native application requires props set outside of js override this method to return the androidosbundle of your desired initial props protected nullable bundle getlaunchoptions bundle b new bundle bputstringmode keyboard return b a subclass may override this method if it needs to use a custom link reactrootview protected reactrootview createrootview return new reactrootviewthis protected reactinstancemanager createreactinstancemanager reactinstancemanagerbuilder builder reactinstancemanagerbuilder setapplicationgetapplication setjsmainmodulenamegetjsmainmodulename setusedevelopersupportgetusedevelopersupport setinitiallifecyclestatelifecyclestateresumed for reactpackage reactpackage getpackages builderaddpackagereactpackage string jsbundlefile getjsbundlefile if jsbundlefile null buildersetjsbundlefilejsbundlefile else buildersetbundleassetnamegetbundleassetname return builderbuild returns a custom path of the bundle file this is used in cases the bundle should be loaded from a custom path by default it is loaded from android assets from a path specified by link getbundleassetname eg filesdcardmyapp cacheindexandroidbundle protected nullable string getjsbundlefile return null protected nullable string getbundleassetname return indexandroidbundle protected listreactpackage getpackages return arraysreactpackageaslist new mainreactpackage new orientationpackage protected boolean getusedevelopersupport return buildconfigdebug protected string getjsmainmodulename return indexandroid protected string getmaincomponentname return customkeyboard override public void onpressint primarycode override public void onreleaseint primarycode override public void ontextcharsequence text override public void swipedown override public void swipeleft override public void swiperight override public void swipeup private void playclickint keycode audiomanager am audiomanagergetsystemserviceaudio service switchkeycode case 32 amplaysoundeffectaudiomanagerfx keypress spacebar break case keyboardkeycode done case 10 amplaysoundeffectaudiomanagerfx keypress return break case keyboardkeycode delete amplaysoundeffectaudiomanagerfx keypress delete break default amplaysoundeffectaudiomanagerfx keypress standard override public void onkeyint primarycode int keycodes inputconnection ic getcurrentinputconnection playclickprimarycode switchprimarycode case keyboardkeycode delete icdeletesurroundingtext1 0 break case keyboardkeycode shift caps caps keyboardsetshiftedcaps kvinvalidateallkeys break case keyboardkeycode done icsendkeyeventnew keyeventkeyeventaction down keyeventkeycode enter break default char code charprimarycode ifcharacterislettercode caps code charactertouppercasecode iccommittextstringvalueofcode1 override public void invokedefaultonbackpressed,['android'] +1181473,is list the common parent of list and list from this oracle tutorialalthough integer is a subtype of number listinteger is not a subtype of listnumber and in fact these two types are not relatedthe common parent of listnumber and listinteger is listmy question is about the second sentence how can we say that list is the common parent of listnumber and listinteger stands for an unknown type which could be any reference type even if i say that would be object here object being the common parent of integer and number does not mean that listobject becomes a common parent of listinteger and listnumber,['java'] +1181477,println method in java for strings equality and how it works exactly i am trying to understand the working of systemoutprintln in java in following 2 code snippet why the answer is different and why it do not print hello string inside println method public static void mainstring args string x abc string y abc systemoutprintlnhello x y systemoutprintlnxequalsy xequalsy ifx y systemoutprintlnhello xy answer is falsexequalsy truefalseand for second code snippet public static void mainstring args string x abc string y abc systemoutprintln x y systemoutprintlnxequalsy xequalsy ifx y systemoutprintlnxy the answer istruexequalsy truetrue,['java'] +1181783,scrolling content inside a fixed position div on mobile safari suddenly stops a and starts scrolling the container itself i have a container which has positionfixed with scrolling content inside i am thisplaying this as a chat feature on mobile devices but on mobile safari the scrolling content inside the positionfixed container stops scrolling suddenly and starts to scroll the container itselfopen this link on mobile safari to see the effect editable example here the question why does my container div start to scroll its position suddenly and stop scrolling the content on chrome on android it works without issuenote if youre having trouble triggering this bug keep scrolling the content up and down quickly for 10 seconds or so eventually it will suddenly stop scrolling,"['html', 'css']" +1181868,java lambdas have different variable requirements than anonymous inner classes i have an anonymous inner class and an equivalent lambda why are the variable initialization rules stricter for the lambda and is there a solution cleaner than an anonymous inner class or initializing it in the constructorimport javautilconcurrentcallablepublic class immutable private final int val public immutableint val thisval val works fine private final callablestring anoninnergetvalstring new callablestring override public string call throws exception return stringvalueofval does not compile variable val might not have been initialized private final callablestring lambdagetvalstring stringvalueofvaledit i did run across one workaround using a getter for val,['java'] +1182528,how to set iframe src in angular 2 without causing unsafe value exception i am new to angular 2 without angularjs experience and working on a tutorial involving the setting of an iframe src attribute iframe width100 height300 srcvideourliframethis throws an exceptionerror unsafe value used in a resource url contextat domsanitizationserviceimplsanitizei have already tried using bindings with src with no success i am probably missing something and i have had a hard time finding a solution to this,['javascript'] +1182668,intentmigrateextrastreamtoclipdata on a null object reference started getting this error in the production version of my appjavalangnullpointerexception attempt to invoke virtual method boolean androidcontentintentmigrateextrastreamtoclipdata on a null object referencethere is no clear line at which this actually occurs but i recently changed my support library version to 2400 heres the full stacktracefatal exception javalangnullpointerexception attempt to invoke virtual method boolean androidcontentintentmigrateextrastreamtoclipdata on a null object reference at androidappinstrumentationexecstartactivityinstrumentationjava1494 at androidappactivitystartactivityforresultactivityjava3745 at androidsupportv4appbasefragmentactivityjbstartactivityforresultbasefragmentactivityjbjava48 at androidsupportv4appfragmentactivitystartactivityforresultfragmentactivityjava75 at androidappactivitystartactivityforresultactivityjava3706 at androidsupportv4appfragmentactivitystartactivityforresultfragmentactivityjava871 at comgoogleandroidgmscommoninternalzzi1zztdunknown source at comgoogleandroidgmscommoninternalzzionclickunknown source at comandroidinternalappalertcontrollerbuttonhandlerhandlemessagealertcontrollerjava162 at androidoshandlerthispatchmessagehandlerjava102 at androidoslooperlooplooperjava135 at androidappactivitythreadmainactivitythreadjava5254 at javalangreflectmethodinvokemethodjava at javalangreflectmethodinvokemethodjava372 at comandroidinternaloszygoteinitmethodandargscallerrunzygoteinitjava903 at comandroidinternaloszygoteinitmainzygoteinitjava698edit i also want to note that 100 of the users getting this error are also rooted this also occurs on 2340 i also have a potential related error which popped up at the same time which has to do with the base64decode function in relation to firebaseedit 2 i received some help from an android dev the other day they suggested that i update my projects google play services version and it seems to have helped so far i will wait a few more days to get the results from my users but the initial logs are promisingi was previously using 902 but i am now on 920edit 3 updating to 920 did not help the crashes i am still getting the same error from rooted users i have noted that at the users getting crashes are below android 60 so i will be testing on a live device and update asap,['android'] +1182712,embedding jqueryprettyphoto causes script to show on page when i movescript srcjsjqueryprettyphotojsscripttoscript typetextjavascript scriptthen the script starts showing on the page from the bold part onwardsstylebordernone overflowhidden width500px height23px allowtransparencytruesvar othisufalseaflchpdewindowheightvethe script is attributed with this informationclass prettyphotouse lightbox clone for jqueryauthor stephane caron version 315how can i move the script from a js file to the page correctly,"['javascript', 'jquery', 'html']" +1182763,how do i integrate travis ci with codeclimate test coverage in python i am trying to make my travis ci send test coverage data to code climate service but documentation on code climate and travis ci do not describe in detail how to do this using python still its supported feature according code climate and travis documentations i have tried to find any working examples on this without luck and cannot make it work on my owncode climate documentationsetting up test coveragereadme codeclimatetestreporter travis ci documentationusing code climate with travis cii have set the codeclimate repo token in travis ci as described in this answermy travisyml filelanguage pythonpython 27install pip install r requirementstxt pip install coverage pip install codeclimatetestreportercommands to run testsscript python mytestspy coverage run mytestspyafter success codeclimatetestreporteras the after success line is excecuted in travis it gives me this in logviewhometravisbuildsh line 45 codeclimatetest reporter command not found,['python'] +1182980,send sms between android emulators before android studio 20 i could send sms messages between emulators using their emulator ids see however this method is not working on new emulators with the panel on the right side is it possible to send sms messages between new android emulators2x note i want to send the message from emulator to emulator not through telnet or adm,['android'] +1183033,are c standard library implementations allowed to strengthen noexcept specifications according to the c standard are implementations of the c standard library allowed to strengthen noexcept specifications of methods and other functions of the c standard library as defined by the standardfor example if the c standard specifies some function stdf as void f are standard library implementations allowed to implement it as void f noexcept instead,['c++'] +1183254,ccache cache miss slow down compilation a lot just started using ccache based on this tutorial and so far i like it however caches miss are being extremely slow here are my results regular clean build without ccache 1m40sfirst build with ccache 4m36ssecond build with ccache 30siam not sure where to start debugging the performance page mentions how complexity of the make file can slow down compilation but in this context i use xcode so call of ccache should be relatively quick i was expecting some performance decrease but not this muchthere are my current settings using version 325 export ccache maxsize3gexport ccache hardlinktrueexport ccache sloppinesspch definesfile macrotime macrosinclude file mtimeinclude file ctimefile stat matchesnote that i do use a pch if that changes something,"['c++', 'ios']" +1183391,c sieve of eratosthenes bitfield i am about to implement the sieve of eratosthenes and have a general question regarding the sievearray i have implemented the sieve quite a few times now in c and always used an array of uint8 t out of stdinth as the sieve this is pretty memory inefficient since 8 bits are used for each number to sieve even though one bit should be sufficient how would i go about this in c i need an array of bits i could pretty much create an array of any type uint8 t uint16 t uint32 t uint64 t and access the single bits with bit masks etc what data type should i prefer and what operations should i use to access the bits without performance lossps i do not think this is a duplicate of just a bitarray implementation since it the question is specific about the sieve of eratosthenes since it is main nature needs to be efficient not only in memory usage but in access i was thinking that maybe different tricks can be used to make the sieving process more efficient,['c'] +1183733,how to create a multipart http response with aspnet core i would like to create an action method in my aspnet core controller which returns a multipart http response containing several files i know that using a zip file is the recommended approach for websites but i am considering using such a request for an apithe examples i have been able to find in the aspnet core samples are to do with multipart http requests when uploading files in my case i want to download filesupdatei have raised the following github issue 4933,['asp.net'] +1183902,android robolectric and vector drawables i am using some vector drawables in my app but only for v21 and up they are in the resource folder drawableanydpiv21 and also have fallback bitmap versions for the other api levels drawablehdpimdpiwhen i run a robolectric with this configconfigsdk 16 application myappclass constants buildconfigclass packagename comcompanyappi get the following error on inflate of the views using these drawablescaused by androidcontentresresourcesnotfoundexception file appbuildintermediatesdatabindinglayoutoutdevdebugdrawableanydpiv21ic info outline white 24dpxml from drawable resource id 0x7f02010ecaused by orgxmlpullv1xmlpullparserexception xml file appbuildintermediatesdatabindinglayoutoutdevdebugdrawableanydpiv21ic info outline white 24dpxml line 1 sorry not yet implemented invalid drawable tag vectorthe relevant parts of the buildgradle are android compilesdkversion 23 buildtoolsversion 2303 defaultconfig applicationid comexampleapp minsdkversion 16 targetsdkversion 23 versioncode 79 versionname 039 enabling multidex support multidexenabled true vectordrawablesusesupportlibrary true testapplicationid comexampleapptest testinstrumentationrunner androidsupporttestrunnerandroidjunitrunner testoptions unittestsreturndefaultvalues true dependencies compile comandroidsupportsupportvectordrawable2340 testcompile orgrobolectricrobolectric31 testcompile orgrobolectricshadowsmultidex31 testcompile orgrobolectricshadowssupportv431 so it looks as though even though i have specified sdk16 robolectric seems to take the drawables from drawableanydpiv21 is this a bug is roboelectric oris there a better way to specify what the apk level is oris there a way to let roboelectric read the vector tag orsome other way of doing it,['android'] +1184128,why do we prefer using q in angular instead of http i am currently using q service from angular to make api calls like thisvar deferred qdeferhttpgetconfigapihost detailsurl successfunction data deferredresolvedata errorfunction msg deferredrejectmsg return deferredpromisebut we can also use this approach also without using qreturn httpgetconfigapihost detailsurl successfunction data return data errorfunction msg return msg and as http itself returns the promise i can also use more simplified approachhttpgetconfigapihost posts successfunction data consolelogdata errorfunction msg consolelogmsg so what is the difference between all these specially between q and http as both returns promise and both are async does angular provides some additional functionality with q i am not able to find any good answer,['javascript'] +1184448,is it better to return an immutablemap or a map let us say i am writing a method that should return a map for instancepublic mapstring integer foo return new hashmapstring integerafter thinking about it for a while i have decided that there is no reason to modify this map once it is created thus i would like to return an immutablemappublic mapstring integer foo return immutablemapof should i leave the return type as a generic map or should i specify that i am returning an immutablemap from one side this is exactly why interfaces were created for to hide the implementation details on the other hand if i will leave it like this other developers might miss the fact that this object is immutable thus i would not achieve a major goal of immutable objects to make the code more clear by minimizing the number of objects that can change even worst after a while someone might try to change this object and this will result in a runtime error the compiler will not warn about it,['java'] +1184669,android alarmmanager setexact is not exact i need to plan sheduled task every 10 minutesas in lollipop and higher version setrepeating is inexact i use setexact and on alarm firing i set new exact alarm in 10 minutesprivate void setalarmlong triggertime pendingintent pendingintent int alarm type alarmmanagerelapsed realtime wakeup if buildversionsdk int buildversion codeskitkat alarmmanagersetexactalarm type triggertime pendingintent else alarmmanagersetalarm type triggertime pendingintent triggertime is calculated systemclockelapsedrealtime 600 0when alarm fires firstly i plan new one only after that i run my sheduled tasksetalarmmysheduledtaski do have wake lock permission in my manifestwhen i test this on android 4 it works perfect deviation might be 1215 millisecondsbut when i run app on xiaomi redmi note 3 pro 511 deviation can be up to 15 secondsfor example i see in my log file first run was at 1467119934477 of rtc time second at 1467120541683 difference is 607 206 milliseconds not 600 0 as it was plannedwhat am i missing what is a way to simulate behaviour of system alarm it is the most close usecase that can describe my tackps i use intentservice for pendingintent pendingintentgetservicecontext 0 myintent 0,['android'] +1184874,i do not understand why we need the new keyword i am new to c from a c background in c you can do thisclass myclassint main myclass object this will create object in memory myclass object new myclass this does same thingwhereas in cclass program static void mainstring args car x xi 2 xj 3 consolewritelinexi consolereadline class car public int i public int jyou cannot do this i wonder why car x would not do its work,['c#'] +1184934,how to make embeded videos only available to a specific player i am trying to figure out how to make an embedded video only readable by a specific player heres the contexti have a website that hosts videos for streaming all videos are private my clients would like to be able to generate an embedding code snippet that would allow him to post this video to whichever site he desires ultimately this means that the video stream is no longer private but now made public now this is the tricky part the client does not want these videos to be scannable via their urls meaning that if the video url is any botsusersprograms hitting that url will not see the video however the player needs to load the video from that same urlanyone know what secure options i have for implementing this there are some drm solutions out there are those of any help for this use casethanks in advance ps if this is not possible for whatever reason whats the next closest thing,['php'] +1184937,is it possible to remove fields with recursion when using toarray in propel i am using propel 2 i am hydrating objects through the relations like soreturn orderquerycreate joinwithcustomer joinwithstatus find toarraytablemaptype phpname true truethe resulting array would look something like this id 1 customerid 1 statusid 1 initiated 20160101t0101010 customer id 1 forname test surname smith orders recursion status id 1 title title 1 priority 1 orders recursion i want to remove the fields where the value is recursion i tried using the alreadydumpedobjects 3rd parameter to toarray but that did not seem to help i could also do some form of array walking with unset calls but i am hoping there is a better way maybe with a formatter or somethingfor bonus points i would quite like to remove the columns which define the foreign key relationship for instance customerid would go but customer would remain,['php'] +1185065,how can i read files from directory and send as json to client i have logs files in server directory i wanted to thisplay file names to client side so i have created readdirectoryjs that is reading names correctly now i am very new to nodejs and i am trying to send json data to client but its not happening how can i send log files name to client using express readdirectoryjsvar fs requirefsvar path logsvar logs function readdirectory fsreaddirpath functionerr items logspushitems consolelogitems for var i0 iitemslength i consolelogitemsi return logsexportsreaddirectory readdirectoryappjs var express requireexpress var app express var readdirectory requirereaddirectory appuseexprestatic dirname public appgetlogsfunctionreqres ressendreaddirectoryreaddirectory angularfactoryjsangularmoduleappfactoryditfactory function http use strict var data return datadata from factory getlogs function return httpgetlogs thenfunction response return responsedata,['javascript'] +1185587,thread synchronization on integer instance variable public class main public static void mainstring args throws exception creating objects for class check2 different objects check c new checks1 check c1 new checks2 cstartc1start class check extends thread checkstring namesupername private integer ab 2 public void run synchronized ab systemoutprintlnthreadcurrentthreadgetname forint i0i10isystemoutprinti here i have synchronized on the variable ab and i have created two different instances of class check also but i am always getting output for s1 followed by s2 or vice versa but not mixed why is that so when i have already created two separate objectsin main so two different threads two different ab variables so how it becomes a shared resource for the two different objects,['java'] +1185757,set grayscale on output of avcapturedevice in ios i want to implement custom camera into my app so i am creating this camera using avcapturedevice now i want to show only gray output into my custom camera so i am trying to getting this using setwhitebalancemodelockedwithdevicewhitebalancegains and avcapturewhitebalancegains i am using avcammanual extending avcam to use manual capture for this voidsetwhitebalancegainsavcapturewhitebalancegainsgains nserror error nil if videodevice lockforconfigurationerror avcapturewhitebalancegains normalizedgains self normalizedgainsgains conversion can yield outofbound values cap to limits videodevice setwhitebalancemodelockedwithdevicewhitebalancegainsnormalizedgains completionhandlernil videodevice unlockforconfiguration else nslog could not lock device for configuration error but for that i must have to pass rgb gain values between 1 to 4 so i am creating this method for checking max and min values avcapturewhitebalancegainsnormalizedgainsavcapturewhitebalancegains gains avcapturewhitebalancegains g gains gredgain max 10 gredgain ggreengain max 10 ggreengain gbluegain max 10 gbluegain gredgain min videodevicemaxwhitebalancegain gredgain ggreengain min videodevicemaxwhitebalancegain ggreengain gbluegain min videodevicemaxwhitebalancegain gbluegain return galso i am trying to get different effects like passing rgb gain static values avcapturewhitebalancegainsnormalizedgainsavcapturewhitebalancegains gains avcapturewhitebalancegains g gains gredgain 3 ggreengain 2 gbluegain 1 return gnow i want to set this gray scale formula pixel 030078125f r 05859375f g 011328125f b on my custom camera i have tried this for this formula avcapturewhitebalancegainsnormalizedgainsavcapturewhitebalancegains gains avcapturewhitebalancegains g gains gredgain gredgain 030078125 ggreengain ggreengain 05859375 gbluegain gbluegain 011328125 float grayscale gredgain ggreengain gbluegain gredgain max 10 grayscale ggreengain max 10 grayscale gbluegain max 10 grayscale gredgain min videodevicemaxwhitebalancegain gredgain ggreengain min videodevicemaxwhitebalancegain ggreengain gbluegain min videodevicemaxwhitebalancegain gbluegain return gso how can i pass this value in between 1 to 4is there any way or scale to compare this thingsany help would be appreciated,"['ios', 'objective-c']" +1185903,c is function redeclaration a undefined behavior codeinclude iostreamusing namespace stdint fint x 0 cout x x endl return 0int main f int fint x 1 f return 0outputtested on g 51x0x1my questionis int fint x 1 a declaration or definitionis function redeclaration like that a undefined behavior,['c++'] +1186227,in mysql what do i put inside mycnf so that all tables are utf8 that works with emojis by default i would like every table and database to be created to be utf8 that works with emojis i understand that there are a few variables i need to define inside mycnfinit connectset collation connection init connectset names charactersetserver collationserver however i am not sure what to put in the what do i put inside mycnf,['mysql'] +1186332,what is the difference between servicesaddtransient serviceaddscope and serviceaddsingleton methods in aspnet core 1 i want to implement dependency injection in aspnet core 1 so after adding this codes to configureservices method both ways work what is the difference between servicesaddtransient and serviceaddscope methods is aspnet core 1public void configureservicesiservicecollection services add framework services add application services servicesaddtransientiemailsender authmessagesender servicesaddscopeiemailsender authmessagesender,['c#'] +1186545,when should a script element that got styled as thisplayblock appears visible why is it possible and is there any real use case where it is desiredtd thisplay blocktable tr td script typetextjavascript var test 1 scriptvon 1 td trtable,"['html', 'css']" +1186553,spring mvc annotation based configuration for multimodule project i implemented two maven based independent web project implemented using spring mvc hibernate and jaxrsbut my requirement changed and now i need to combine both the project as a sub project into another project which is our parent project so i use maven multimodule configurationproject 1 parent projectpackagingpompackaging modules modulechild1module modulechild2module moduleschild 1packagingjarpackaging parent groupidcomxyzalphagroupid artifactidparentartifactid version001snapshotversion relativepathparentrelativepath parentchild 2 packagingjarpackaging dependency groupidcomxyzalphagroupid artifactidchild1artifactid version202version dependency parent groupidcomxyzalphagroupid artifactidparentartifactid version001snapshotversion relativepathparentrelativepath parentbut i need to configure project in java in such a way that it will scan component of parent and both the child project and execute projectcurrently i have separate configuration for each project as appintializerjavapublic class appinitializer extends abstractannotationconfigthispatcherservletinitializer override protected class getrootconfigclasses return new class appconfigclass override protected class getservletconfigclasses return null override protected string getservletmappings return new string appconfigjavaconfigurationenablewebmvccomponentscanbasepackages comxypublic class appconfig extends webmvcconfigureradapter bean public viewresolver viewresolver internalresourceviewresolver viewresolver new internalresourceviewresolver viewresolversetviewclassjstlviewclass viewresolversetprefixwebinfviews viewresolversetsuffixjsp return viewresolver override public void addcorsmappingscorsregistry registry registryaddmapping override public void configuredefaultservlethandlingdefaultservlethandlerconfigurer configurer configurerenable override public void addresourcehandlersresourcehandlerregistry registry registryaddresourcehandlerresourcesaddresourcelocationsresources hibernateconfigurationjavaconfigurationenabletransactionmanagementcomponentscan comxyconfiguration propertysourcevalue classpathapplicationproperties public class hibernateconfiguration autowired private environment environment bean public localsessionfactorybean sessionfactory localsessionfactorybean sessionfactory new localsessionfactorybean sessionfactorysetdatasourcedatasource sessionfactorysetpackagestoscannew string comxymodel sessionfactorysethibernatepropertieshibernateproperties return sessionfactory bean public datasource datasource drivermanagerdatasource datasource new drivermanagerdatasource datasourcesetdriverclassnameenvironmentgetrequiredpropertyjdbcdriverclassname datasourceseturlenvironmentgetrequiredpropertyjdbcurl datasourcesetusernameenvironmentgetrequiredpropertyjdbcusername datasourcesetpasswordenvironmentgetrequiredpropertyjdbcpassword return datasource private properties hibernateproperties properties properties new properties propertiesputhibernatedialect environmentgetrequiredpropertyhibernatedialect propertiesputhibernateshow sql environmentgetrequiredpropertyhibernateshow sql propertiesputhibernateformat sql environmentgetrequiredpropertyhibernateformat sql propertiesputhibernatehbm2ddlauto environmentgetrequiredpropertyhibernatehbm2ddlauto return properties bean autowired public hibernatetransactionmanager transactionmanagersessionfactory s hibernatetransactionmanager txmanager new hibernatetransactionmanager txmanagersetsessionfactorys return txmanager,['java'] +1186571,variable string that crashes browser i found something very strange when you place something like this in your html page the browser tested on ff and chrome just stops rendering the page at this place script typetextjavascript var crash script scriptobviously you can also do script typetextjavascript var crash script scriptor script typetextjavascript var crash whatever you want here script scriptany ideas why this happens,['javascript'] +1186730,submit button from outside redux form v600 this question relates to redux form v600 in time of writing this question it is v600alpha15how can i get form validation status like pristine submitting invalid from outside of form component let me give an example this is classical reduxform pseudostructureformmyexampleform myexampleform input nametitle submitbutton where submitbutton in jsx looks like thisbutton typesubmit thisabledpristine submitting invalid savebuttonbut in my application my submit button must be outside of the form placed on different place in the application let us say in application header on the top of whole applicationhow can i get those pristine submitting invalid from outside of reduxform without really nasty hacking if possible how can i submit that form,['javascript'] +1186766,how do i reliably split a string in python in perl i can domy x y split strand it will work whether or not the string contains the patternin python however this would not worka b foosplit valueerror not enough values to unpackwhats the canonical way to prevent errors in such cases,['python'] +1186891,audiomanageradjuststreamvolume no longer functioning on 6 devices so i am encountering a strange issue where calling audiomanageradjuststreamvolumeaudiomanagerstream music audiomanageradjust lower audiomanagerflag show ui no longer triggers a system volume change on the device i just updated to 60on all pre6 devices this code works as expected i did notice the changes to audiomanager where setstreamvolume has been deprecated but the suggested alternative is what i was already usingat first i believed it might be a permission issue since modify audio settings is listed as a dangerous permission but i have checked and contextcompatcheckselfpermissionthis manifestpermissionmodify audio settings packagemanagerpermission granted and there is also no audiorelated permissions in the permission settings page so i am assuming this is not the casei have tried the other recommended method adjustvolumeaudiomanageradjust lower audiomanagerflag show ui but that also yielded no resultsso to clarifynothing visually occurs when calling adjuststreamvolumeadjustvolume and audiomanagergetstreamvolumeaudiomanagerstream music returns the unchanged value as if it were never calledif anyone has any thoughts on this i would really love to hear them right about noweditsince posting this i have switched to using setstreamvolumeaudiomanagerstream music value audiomanagerflag show ui which works even though the docs say it no longer should would love some thoughts on thisedit 2opened an issue since i was able to replicate on another device,"['java', 'android']" +1186992,how to compress hdf5 file when resizing here is my coden 10 this is what makes it tricky lots of files going into this hdf5 filewith h5pyfileimage1h5w as f dset x fcreate datasetx1960224224maxshapenone960224224chunkstruecompressiongzip dset y fcreate datasety124224maxshapenone1124224chunkstruecompressiongzip and images 0 for fl in filesn x chunky chunk get arraysfl dset xresizen images1axis0 dset yresizen images1axis0 print dset xshapedset yshape dset xn imagesn images1x chunk dset yn imagesn images1y chunk and images1this works fine and dandy however with 1 file the size of the hdf5 is 67mb with 2 files its 37mb should be 12 mb right with 10 its all the way up to 388mb should be 67 rightso clearly adding the compression flag to the end of the 2nd and third line is not working as intended how can i achieve something like this,['python'] +1187021,how to download a file behind a semibroken javascript asp function with r i am trying to fix a download automation script that i provide publicly so that anyone can easily download the world values survey with ron this web page the pdf link wvs 20 questionnaire root easily downloads in firefox and chromei cannot figure out how to automate the download with httr or rcurl or any other r package screenshot below of the chrome internet behavior that pdf link needs to follow through to the ultimate source of 20 questionnaire rootpdf but if you click their directly there is a connectivity error i am unclear if this is related to the request header upgradeinsecurerequests1 or the response header status code 302clicking around the new worldvaluessurveyorg website with chromes inspect element windows open makes me think there were some hacky coding decisions made here hence the title semibroken,"['javascript', 'asp.net']" +1187069,are ios android apps with webview only considered hybrid or web apps my confusion is whether an app created in java or swift with just a webview is considered a hybrid or web app i understand that a web app use the web almost exclusively but if it is a webview through a java webview is it really considered a web app or is it a hybrid app because it has the potential to use both native and web app features i get mixed definitions about this particular definition google says this about web appthere are essentially two ways to deliver an application on android as a clientside application developed using the android sdk and installed on user devices in an apk or as a web application developed using web standards and accessed through a web browserathere is nothing to install on user devicesapple says this about web appsa web application is designed to look and behave in a way similar to a native applicationafor example it is scaled to fit the entire screen on ios you can tailor your web application for safari on ios even further by making it appear like a native application when the user adds it to the home screen you do this by using settings for ios that are ignored by other platformswhy is this important to me why do i bother askingi need to explain to people the differences and importance between these three when talking about future development of a new app i am creating i am new to the app world and do not quite understand the consensus on this and i want to sound competent when i explain it i would consider an java or swift made app with a webview just a web app and not a hybrid app but it could become a hybrid app if more was added however i can see it being a hybrid app from the start,"['java', 'android', 'ios']" +1187499,how can i develop crossplatform gui application using net core aspnet core application run on windows linux and macos but it is web application the net core application is a class libraryhow can i develop crossplatform gui application on net framework or net core,['c#'] +1187541,static property in c 6 i am writing a small code to more understand about property and static property like theseclass useridentity public static idictionarystring datetime onlineusers get set public useridentity onlineusers new dictionarystring datetime orclass useridentity public idictionarystring datetime onlineusers get public useridentity onlineusers new dictionarystring datetime since i changed it toclass useridentity public static idictionarystring datetime onlineusers get public useridentity onlineusers new dictionarystring datetime it gave me error messageproperty or indexer useridentityonlineusers cannot be assigned to it is read onlyi knew the property onlineusers was read only but in c 6 i can assign it via constructor so what am i missing,['c#'] +1187626,curl works fine except if i call it with subprocess i have a curl that looks a bit like thiscurl 1 x post user xy d statusnewcontentissuedetailsat3ahttp3a2f2flocalhost3a65432ftest2fsubmit2f160703h2018kindbugtitleqafailresponsiblexprioritycritical if i open up a terminal and just execute it it works fine an issue is created in bitbucketif i try to execute the same curl via subprocess it just failsscmd curletclcmd s for s in scmdsplit if ssubprocesscalcmdi get the error messagecurl 1 protocol https not supported or thisabled in libcurli do not get why the exact same command works so differently in python any ideasthis is without use of a virtualenv by the way and i know for a fact that the contents of lcmd are validps yes i know i should be using requests unfortunately requests was giving me similar problems,['python'] +1187702,c static inline parameter evaluation optimization assume an api in which every function returns an error code which is zero in case of no error and nonzero for error valuesletint fooint barbe functions in this api let there be a code fragment in which foo and bar have to be called in order and foo and bar should always be called regardless of previous error but the first returned nonzero error code is to be propagated ieint foobar int rc 0 rc rc foo rc rc rc rc rc bar rc rc rc rc return rcwriting the rcrc multiplexing is tiring and error prone no matter if a ternary operator ifelse or something else is usedlet there be an error propagating helper functionstatic inlineint rc propagateint r int p return p p r this could be used in foobar like thisint foobar int rc 0 rc rc propagatefoo rc rc rc propagatebar rc return rcdoes the c standard allow to optimize by pulling the evaluation of the first parameter of rc propagate a static inline function into the ternary so that it may not get executed due to the ternary operator evaluation rules if the second parameter p were nonzero,['c'] +1187735,handle download intents in my app my webview app already handles external urls fine opens links from external apps like viber browsers etc like this i got this code from here get url from browsable intent filter textview uri textview findviewbyidridurlfield get the url url getintentgetdatastring uri data getintentgetdata if data null urisettext else urisettextgetintentgetdatatostring fadeout in my webview settings load url from browsable intent filter if there is a valid url pasted if urilength 0 webviewloadurlurl else dont loadthis is how i handle downloads within my webview download manager webviewsetdownloadlistenernew downloadlistener override public void ondownloadstartstring url string useragent string contentthisposition string mimetype long contentlength downloadmanagerrequest request new downloadmanagerrequest uriparseurl requestsetmimetypemimetype string cookies cookiemanagergetinstancegetcookieurl requestaddrequestheadercookie cookies requestaddrequestheaderuseragent useragent requestsetdescriptiondownloading file requestsettitleurlutilguessfilenameurl contentthisposition mimetype requestallowscanningbymediascanner requestsetnotificationvisibilitydownloadmanagerrequestvisibility visible notify completed requestsetdestinationinexternalpublicdir environmentdirectory downloads urlutilguessfilename url contentthisposition mimetype downloadmanager dm downloadmanager getsystemservicedownload service dmenqueuerequest toastmaketextgetapplicationcontext downloading file toastlength longshow download managerhowever i would like to handle that download intents passed by other apps as well how do i do thatthis is what i use to open the system default app chooser from another appmy app is listed here download via webviewsetdownloadlistenernew downloadlistener public void ondownloadstartstring url string useragent string contentthisposition string mimetype long contentlength intent i new intentintentaction view isetdatauriparseurl startactivityi toastmaketextgetapplicationcontext do not choose our app as it cannot handle download intents i have posted a question on stackoverflow though toastlength shortshow download viawhenever i click a download link my app opens but just sits still instead of opening the url i want it to act like a downloader app,['android'] +1187941,copy a bit matrix from bitmap image in android programming i am developing an android app that helps user to copy a part of a bitmap by sketching or drawing i mean the the user will draw some shapes on a canvas that has the bitmap as background and then i have the points that are colored as a bitmap bit matrix 2d bit array until here every hitng sounds goodnow the problem is how can i copy the part of the image that has a corresponding true bit in the matrixask for additional information if neededadding explanation1 main image2 image as canvas background3 some paintings on canvas4 bit matrix representation of painted area5 expected outputthanks in advance,['android'] +1188080,rntn implementation in java i want to implement a recursive neural tensor networkrntn in javai have used deeplearning4j for word2vec pipeline to vectorize a corpus of wordsfor nlp pipeline i have used opennlp for tokenizing postaging and parsingnow i figured out that i need an rntn for my purpose and i did not find much support any references would be helpful many libraries are written in r or python or even in scala and the nlp pipeline most of the people used is stanfordnlp but i want to do this with opennlp and javaafter that i would like to combine the word vectors with neural net and then do the task i want to do something like sentiment analysishow can i proceed any input will be helpfulthanks,['java'] +1188249,two variables in python have same id but not lists or tuples two variables in python have the same ida 10b 10a is b trueif i take two listsa 1 2 3b 1 2 3a is b falseaccording to this link senderle answered that immutable object references have the same id and mutable objects like lists have different idsso now according to his answer tuples should have the same ids meaninga 1 2 3b 1 2 3a is b falseideally as tuples are not mutable it should return true but it is returning falsewhat is the explanation,['python'] +1188341,how to unapply a migration in aspnet core with ef core when i run pm removemigration context bloggingcontext in vs2015 with an aspnet core project using ef core i get the following errorsysteminvalidoperationexception the migration 20160703192724 myfirstmigration has already been applied to the database unapply it and try again if the migration has been applied to other databases consider reverting its changes using a new migration at microsoftentityframeworkcoremigrationsdesignmigrationsscaffolderremovemigrationstring projectdir string rootnamespace boolean force at microsoftentityframeworkcoredesignmigrationsoperationsremovemigrationstring contexttype boolean force at microsoftentityframeworkcoretoolsclimigrationsremovecommandc thisplayclass0 0configureb 0 at microsoftextensionscommandlineutilscommandlineapplicationexecutestring args at microsoftentityframeworkcoretoolscliprogrammainstring args the migration 20160703192724 myfirstmigration has already been applied to the database unapply it and try again if the migration has been applied to other databases consider reverting its changes using a new migrationhow can i unapply it i am using latest release of aspnet core 10 ef core and vs2015 update 3,['c#'] +1188566,reactnative change responder dynamically i am using reactnative for android development i have a view on which if user does longpress i want to show an animated view which can be dragged i could achieve this using panresponder which works fine but what i want to do is when user does longpress user should be able to continue the same touchpress and drag the newly shown animatedview if you are familiar with google drive app it has similar functionality when user longpresses any item in the list it shows draggable item user can drag the item straight away i think if i could change the responder dynamically to the draggable item after it starts showing then this would work the question is does reactnative provide a way to change the responder dynamicallywhat i have tried so fari tried with changing logic of onstartshouldsetpanrespondercapture onmoveshouldsetpanrespondercapture onmoveshouldsetpanresponder onpanresponderterminationrequest so that as soon as the draggable item starts showing the container view should not capture the start and move and accept the termination request also returning false to termination request of draggable item and returning true to it is should capture events one workaround which is working for me is to show the draggable item on the top of container with less opacity and keep the capture of it as false as soon as user longpresses on it i am changing the opacity of it so that it is visible clearly with this approach user can continue the touch to drag the item but the container is actually a list row thus i would need to create many draggables as user can longpress on any row but i think this is not a good solution and if i could change the responder it would be great,['android'] +1189037,which python classes allow assignment to notyetexistent attributes and which do not in python the dict of an instance seems to be open for some classes closed for others closed type examplex objectxeggs spam raises an attributeerrorwhereas open type example ix exceptionxeggs spam does not raise an attributeerror open type example ii subclassesclass thingobject passx thingxeggs spam does not raise an attributeerrori would like to understand wherehowwhy this difference in behaviour is implemented why is object closed but thing open why is exception open i have two reasons for the questionin pure python the only way i have found of replicating the closed behaviour is to implement setattr myself and raise the attributeerror in it composing its appropriatelyformatted error message by hand is there a lessverbose moredry way and one which does not generate a potentially misleading backtrace to setattr in an ipc module i have written i want to document an example of usage and the most concise and universal way would be to find an example of a builtin type failing that one from the standard library a which can be pickled and sent to another process and b whose instances exhibit the open behaviour so far the best one i have found is exception but that looks a little misleading in the documentation people will think it is specifically about exceptions a more generic object would be nicer but object is closed and a subclass like thing in the example above is not pickleable unless you save its definition in a file on the path maybe there is a standard container somewhere that is open the classics tuplelistdict are all closed,['python'] +1189048,generics and abstract methods i have come across something i find odd in java and have not been able to find much information on it consider the following codepublic class testclass private static abstract class abstractclass abstract list extends object getlist abstract maplong list extends object getmap private static final class concreteclass extends abstractclass override liststring getlist return null override maplong liststring getmap return null the compiler shows an error on the getmap method getmap in concreteclass cannot override getmap in abstractclass return type maplong liststring is not compatible with maplong list extends objectbut the same error is not present for the getlist method yet i would expect either both to work or both to fail in both cases the overriding method is delcaring liststring in place of list extends object can someone explain this,['java'] +1189239,xcode unit testing with cocoapods i have been banging my head against a wall with this for the last few days but despite multiple googlesogithub searches i cannot find a resolution to the issues i am havingall i am trying to do is create some unit tests for my app which makes use of firebase podsi am using xcode 731 cocoapods 101 update issue remains with xcode 80with this podfileplatform ios 90use frameworksinhibit all warningstarget myapp do pod firebase pod firebaseauth pod firebasedatabase pod firebasestorage target myapptests do inherit search paths endendin my xctest class i getmissing required module firebaseerror at testable import myappalternatively with this podfileplatform ios 90use frameworksinhibit all warningsdef common pods pod swiftytimer pod firebase pod firebaseauth pod firebasedatabase pod firebasestorageendtarget myapp do common podsendtarget myapptests do common podsendthe tests build but my console is littered with warnings egclass firebaseclassname is implemented in both myapp and myapptests one of the two will be used which one is undefined,['ios'] +1189304,what is the difference when comparing with parentheses where a b12 i stumbled across the follwoing valid query in mysql also works in oraclemssql when replacing with inselect from mytable where a b12it is the same asselect from mytable where a1 and b2i think the definition in the mysql docs is heresimple expr expr expr what is this called are there any pros and cons for using it,"['mysql', 'sql']" +1189333,quartz compiling job scripts after runtime i want to use quartz to act as a script scheduler you write the vb from a gui and then select a trigger the code is then compiled and executed on the trigger the difficult bit is how do i handle it so that it runs this script with in the application context so it can access my entity framework models etc how would i achieve this,['.net'] +1189611,ion slide box how to slide full width iframe videos in ion slide on my page i am having an ionslidebox for images since in my app users will be able to embed videos i should also add iframes with videos to the same slider this is how my code looks like nowthis is my htmlionslidebox ngifsliderlength 1 ionslide ngrepeatitem in slider img ngifitemimage ngsrc fileserver imagecachecover itemimage classcover iframe ngifitemvideo src itemvideo safeurl iframe ionslideionslideboxthis works fine with only images but when i have videos i cannot slide them if they take up 100 width which i have set up in my css i can only slide them if they are wide less than that and if i slide them only on that part where the iframe is not taking up space in the slider since i need to have iframe taking up 100 width i wonder how to make it work,['javascript'] +1189820,ierrorhandler returning wrong message body when http status code is 401 unauthorized i have implemented ierrorhandler to handle authorization exceptions thrown within the constructor of my restful wcf service when a general exception is caught my custom type is returned as expected but the contenttype header is incorrecthttp11 500 internal server errorcontenttype applicationxmlerrormessageerrorhowever when the error handler tries to return a 401 unauthorized http status code the message body is overridden to the default type but the contenttype header is as it should be http11 401 unauthorizedcontenttype applicationjson messageauthentication failedstacktracenullexceptiontypesysteminvalidoperationexceptionobviously something is wrong here but i am not sure whathow do i implement ierrorhandler such that it returns my custom type in json with the correct headersbasedataresponsecontract objectserializabledatacontract name basedataresponsecontract public class basedataresponsecontract datamember public string errormessage get set endthis is the object i want to return all of the other objects in my application inherit from this object when an exception is thrown all we really care about is the http status code and the error messageierrorhandler implementation logging is not shown for brevitynamespace webservicesbehaviorsandinspectors public class errorhandler ierrorhandler public bool handleerrorexception error return true end public void providefaultexception ex messageversion version ref message fault create a new instance of the object i would like to return with a default message var basedataresponsecontract new basedataresponsecontract errormessage error get the outgoing response portion of the current context var response weboperationcontextcurrentoutgoingresponse set the http status code responsestatuscode httpstatuscodeinternalservererror if the exception is a specific type change the default settings if exgettype typeofusernotfoundexception basedataresponsecontracterrormessage invalid username responsestatuscode httpstatuscodeunauthorized create the fault message that is returned note the ref parameter fault messagecreatemessageversion basedataresponsecontract new datacontractjsonserializertypeofbasedataresponsecontract tell wcf to use json encoding rather than default xml var webbodyformatmessageproperty new webbodyformatmessagepropertywebcontentformatjson faultpropertiesaddwebbodyformatmessagepropertyname webbodyformatmessageproperty add contenttype header that specifies we are using json var httpresponsemessageproperty new httpresponsemessageproperty httpresponsemessagepropertyheadershttpresponseheadercontenttype applicationjson faultpropertiesaddhttpresponsemessagepropertyname httpresponsemessageproperty end end class end namespaceiservicebehavior implementationnamespace webservicesbehaviorsandinspectors public class errorhandlerextensionbehavior behaviorextensionelement iservicebehavior public override type behaviortype get return gettype protected override object createbehavior return this private ierrorhandler getinstance return new errorhandler void iservicebehavioraddbindingparametersservicedescription servicedescription servicehostbase servicehostbase collectionserviceendpoint endpoints bindingparametercollection bindingparameters end void iservicebehaviorapplythispatchbehaviorservicedescription servicedescription servicehostbase servicehostbase var errorhandlerinstance getinstance foreach channelthispatcher thispatcher in servicehostbasechannelthispatchers thispatchererrorhandlersadderrorhandlerinstance void iservicebehaviorvalidateservicedescription servicedescription servicehostbase servicehostbase end end class end namespacewebconfigsystemservicemodel services service namewebservicesmyservice endpoint bindingwebhttpbinding contractwebservicesimyservice service services extensions behaviorextensions this extension if for the wcf error handling add nameerrorhandlerbehavior typewebservicesbehaviorsandinspectorserrorhandlerextensionbehavior webservices version10 cultureneutral publickeytokennull behaviorextensions extensions behaviors servicebehaviors behavior servicemetadata httpgetenabledtrue servicedebug includeexceptiondetailinfaultstrue errorhandlerbehavior behavior servicebehaviors behaviors systemservicemodelfinally i am seeing similar behavior when using webfaultexception my thought is that this is the result of some deeply buried net shenanigans i am choosing to implement ierrorhandler so that i can catch any other exceptions that may not be handled referencevvs100aspxother examplesierrorhandler doesnt seem to be handling my errors in wcf any ideashow to make custom wcf error handler return json response with nonok http codehow do you set the contenttype header for an httpclient request,['c#'] +1189962,waiting threads resource consumption my problemdoes large numbers of threads in jvm consume a lot of resources memory cpu when the threads are timed wait state not sleeping 9 of the time when the threads are waiting how much cpu overhead does it cost to maintain them if any are needed at alldoes the answer also apply to nonjvm related environments like linux kernelscontextmy program receives a large number of space consuming packages it store counts of similar attributes within the different packages after a given period of time after receiving a packagecould be hours or days that specific package expires and any count the package contributed to should be decrementedcurrently i achieve these functionalities by storing all the packages in memory or thisk every 5 minutes i delete the expired packages from storage and scan through the remaining packages to count the attributes this method uses up a lot of memory and has bad time complexity on for time and memory where and is the number of unexpired packages this makes scalability of the program terribleone alternative way to approach this problem is to increment the attribute count every time a package comes by and start a timer thread that decrements the attribute count after the package expires this eliminates the need to store all the bulky packages and cut the time complexity to o1 however this creates another problem as my program will start having on number of threads which could cut into performance since most of the threads will be in the timed wait state javaas timer invokes the objectwaitlong method the vast majority of their lifecycle does it still impact the cpu in a very large way,['java'] +1190027,django channels echo example not working i am following the instructions in the documentation site but i got stuck in the echo example the websocket is created correctly and it is connected to the server but when i send anything to the server i am not getting any response in the example says i should see an alert window with the same message that i send into the socket but i do not although i have changed the alert for a consolelog but still what i am doing wrongin settingspyinstalled apps channels myapp channels settingschannel layers default backend asgirefinmemorychannellayer routing myapproutingchannel routing in routingpyfrom channelsrouting import routefrom myappconsumers import channel routing routewebsocketreceive ws receivein consumerspydef ws receivemessage asgi websocket packetreceived and sendpacket message types both have a text key for their textual data messagereply channelsend text messagecontenttext in asgipyimport osfrom channelsasgi import get channel layerosenvironsetdefaultdjango settings module myappsettingschannel layer get channel layerthen i run python managepy runserver and in my browser i go to the server url and in the console i put the following socket new websocketws windowlocationhost chatsocketonmessage functione alertedatasocketonopen function socketsendhello worldagain at this point i should see an alert window or the consolelog message but i get nothingthe requests that i made have a status of pending although i read here and the first comment says it is normal and the server output looks like thisevery time that i have tried to send something through the websocket in the browser the server just print connect but no log from the js console is showing edit i have tested websockets in my browser against echowebsocketorg and i got the answer as expected,"['javascript', 'python']" +1190393,using razor outside of mvc in net core i would like to use razor as a templating engine in a net console application that i am writing in net corethe standalone razor engines i have come across razorengine razortemplates all require full net i am looking for a solution that works with net core,"['c#', '.net']" +1190399,facebook nativeadsmanager getting out of memory exception in recyclerview i am creating an application that is using nativeadsmanager within a recyclerview when i load the ads i am getting an out of memory exception this is where i initialise the nativeadsmanager nativeadsmanager manager new nativeadsmanagermainactivitythisplacement id5managersetlistenermainactivitythis managerloadadsnativeadmediacacheflagallthis is my log when i get the error0707 164437513 1483315332comexamplefbads edalvikvmheap out of memory on a 1324560byte allocation0707 164437528 1483315332comexamplefbads ek error downloading image imagephpdaqaugfkrap5pyho4w796h416urlhttp3a2f2fwfacebookcom2fads2fimage2f3fd3daqjm1zvey2ilc4oqvu3hf63ustwvitc5xbvqrlwjcwengkxran5sbb9j6cfydl0sqpnmwqmdehxuxprwbackycgekskx1q8 jpylyb4sfhcxsrphm 5n9za8xhlczvxlrs9dt4i5qely6kezxosqgcfs1extjpgjavalangoutofmemoryerror at androidgraphicsbitmapfactorynativedecodestreamnative method at androidgraphicsbitmapfactorydecodestreaminternalbitmapfactoryjava620 at androidgraphicsbitmapfactorydecodestreambitmapfactoryjava596 at androidgraphicsbitmapfactorydecodefilebitmapfactoryjava376 at androidgraphicsbitmapfactorydecodefilebitmapfactoryjava402 at comfacebookadsinternalutilmaunknown source at comfacebookadsinternalutilkbunknown source at comfacebookadsinternalutilkdoinbackgroundunknown source at androidosasynctask2callasynctaskjava288 at javautilconcurrentfuturetaskrunfuturetaskjava237 at androidosasynctaskserialexecutor1runasynctaskjava231 at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava12 at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava587 at javalangthreadrunthreadjava841any reasons why this is happening any suggestions on how to fix this problem,['android'] +1190402,emulators location simulation not working i would like to lower the minimum api level of my application to 44kitkat from 50lollipopsadly i could not get any real devices so i have to work with an emulatormy app is heavily based on users location so the main testing must be target the location changing featurei try to use location simulation with the official google android emulator x86i have made a 44 emulator and is working fine my app works fine but when i try to send locations via the extended control panel nothing happensif i load a gpx file the locations appear on the table of the extended control panel inside the gps data playback but the device does not get any locationsi fill the lat and longitude click on send but nothing happensi have also tried to simulate location changing from the android device monitors emulator control tabthe send button is not clickable at all the long and lat fields are thisabled and i cannot fill anything the gpx and kml tabs are also thisabledi have also tried to use the gps emulator plugin as the followingthe progress bar do increases so not like the first 2 methods i have tried this is finally looks like actually doing something but the emulator still not getting the location changes not at alli have tried a fourth method via command linetelnet localhost 54but i have connection refused error messageso i cannot try to send locations viageo fix longitude value latitude valuetelnes is enabled on my windows,['android'] +1190458,replace uiselect style to original style i have two dropdown menus on packagehomethe left one is applied angularuiselectthistselectmincssbut i would like the right one style what is the quickest get itbecause it seems angularuiselect will modify the dom elementi do not know which approach can make the left one has the same style as the right onecurrent style packagehomethis is desired style homehtmlthanks,['css'] +1190531,how to split data into 3 sets train validation and test i have a pandas dataframe and i wish to divide it to 3 seprate sets i know that using train test split from sklearncross validation one can divide the data in two sets train and test however i could not find any solution about splitting the data into three sets preferably i would like to have the indices of the original data i know that a workaround would be to use train test split two times and somehow adjust the indices but is there a more standard builtin way to split the data into 3 sets instead of 2,['python'] +1190563,why does stdforward return static cast and not static cast let us have a function called y that overloadsvoid yint lvalue cout lvalue endl void yint rvalue cout rvalue endl now let us define a template function that acts like stdforwardtemplateclass tvoid ft x y static casttx using static casttx like in stdforwardnow look at the mainint main int i 10 fi lvalue t int f10 rvalue t intas expected the output islvaluervaluenow come back to the template function f and replace static casttx with static casttx let us see the outputlvaluervalueit is the same why if they are the same then why stdforward returns a cast from x to t,['c++'] +1191159,is there a shorthand way to return values that might be null how can i write a shorthand of the following scenarioget if rows null rows new listrow return rows,['c#'] +1191371,efficient way to find out if two sorted lists contain same element java i have a tight loop that searches coprimes a list primefactors its nth element contains a sorted list of prime decomposition of n i am checking if c and d are coprimes using checkifprimesboolean checkifprimesint c int d listlistinteger primefactors listinteger common new arraylistprimefactorsgetd slow commonretainallprimefactorsgetc return commonisemptyprimefactorsgetdretainallprimefactorsgetc looks promising but it will alter my reusable primefactors objectcreating a new object is relatively slow is there a way to speed up this step can i somehow utilize the fact that lists are sorted should i use arrays instead,['java'] +1191456,genymotion virtualbox error i have installed genymotion and virtualbox on my computer and set up a samsung galaxy s6 device through genymotion however when i try to start the device genymotion gives me this errorunable to start the virtual devicevirtualbox cannot start the virtual deviceto find out the cause the problem start the virtual device from virtualboxfor more information check the log files please refer towgenymotioncomfaqlogsi try to start the device in virtualbox and get this errorvirtualbox errorfailed to open a session for the virtual machine samsung galaxy s6 600 api 23 1440x2560a14 detailsthe configured driver was not found either the necessary driver modules was not loaded the name was misspelled or it was a misconfiguration verr pdm driver not foundresult code e fail 0x804005 component consolewrap interface iconsole 872da6454a9b1727bee25585105b9eedi have tried to delete the network drivers and have genymotion reinstall them i have also checked all of the drivers for the network interface drivers but nothing seems to help what should i do,['android'] +1191685,using retrywhen to update tokens based on http error code i found this example on how to refresh oauth token using moya and rxswift which i had to alter slightly to get to compile this code works 80 for my scenario the problem with it is that it will run for all http errors and not just 401 errors what i want is to have all my other http errors passed on as errors so that i can handle them else where and not swallow them herewith this code if i get a httpstatus 500 it will run the authentication code 3 times which is obviously not what i wantive tried to alter this code to handle only handle 401 errors but it seem that no matter what i do i cannot get the code to compile it is always complaining about wrong return type cannot convert return expression of type observableresponse to return type observableresponse which makes no sense to mewhat i want handle 401 but stop on all other errorsimport rxswiftimport keychainaccessimport moyapublic extension observabletype where e response tries to refresh auth token on 401 errors and retry the request if the refresh fails the signal errors public func retrywithauthifneeded observablee return selfretrywhen e observableerrortype in return observablezipe observablerangestart 1 count 3 resultselector 1 flatmap i in return authprovidersharedinstancerequest loginfacebookuser accesstoken authenticationmanagerdefaultinstancegetlogintokenfromkeychain usefacebooklogin authenticationmanagerdefaultinstanceisfacebooklogin filtersuccessfulstatuscodes mapobjectaccesstokenself catcherror error in logdebugreauth error error if case errorstatuscodelet response error if responsestatuscode 401 force logout after failed attempt logdebug401 force user logout nsnotificationcenterdefaultcenterpostnotificationnameconstantsnotificationsusernotauthenticated object nil userinfo nil return observableerrorerror flatmaplatest token observableaccesstoken in authenticationmanagerdefaultinstancestoreservicetokeninkeychaintoken return observablejusttoken,['ios'] +1191878,comparator breaching general contract the below code is a edited version of dave koelles alphanumcomparator the edit contains code which sorts empty strings to the end of the list or bottom of the jtable in my case the problem is a javalangillegalargumentexception comparison method violates its general contract occursto fix my problem i looked into it and found reasons such as the comparator does not have a return 0 in the correct place i also found a comment in the java bug database which readthe sorting algorithm used by javautilarrayssort and indirectly by javautilcollectionssort has been replaced the new sort implementation may throw an illegalargumentexception if it detects a comparable that violates the comparable contract the previous implementation silently ignored such a situation if the previous behavior is desired you can use the new system property javautilarraysuselegacymergesort to restore previous mergesort behaviorimport javautilcomparatorimport javaxswingjtableimport javaxswingsortorderpublic class alphanumcomparator implements comparatorstring jtable table public alphanumcomparatorjtable table thistable table private final boolean isdigitchar ch return ch 48 ch 57 private final string getchunkstring s int slength int marker stringbuilder chunk new stringbuilder char c scharatmarker chunkappendc marker if isdigitc while marker slength c scharatmarker if isdigitc break chunkappendc marker else while marker slength c scharatmarker if isdigitc break chunkappendc marker return chunktostring public int comparestring s1 string s2 boolean swapint tablegetrowsortergetsortkeysget0getsortorder sortorderascending int thismarker 0 int thatmarker 0 int s1length s1length int s2length s2length ifs1length 0 s2length 0 while thismarker s1length thatmarker s2length string thischunk getchunks1 s1length thismarker thismarker thischunklength string thatchunk getchunks2 s2length thatmarker thatmarker thatchunklength int result 0 if isdigitthischunkcharat0 isdigitthatchunkcharat0 int thischunklength thischunklength result thischunklength thatchunklength if result 0 for int i 0 i thischunklength i result thischunkcharati thatchunkcharati if result 0 return result else result thischunkcomparetothatchunk if result 0 return result return s1length s2length else ifswapint ifs1length 0 return 1 else return 1 else ifs1length 0 return 1 else return 1 would someone be able to help fix my problem and explain why this comparator is violating the comparable contractexception stack trace if neededexception in thread awteventqueue0 javalangillegalargumentexception comparison method violates its general contract at javautilcomparabletimsortmergelocomparabletimsortjava744 at javautilcomparabletimsortmergeatcomparabletimsortjava481 at javautilcomparabletimsortmergeforcecollapsecomparabletimsortjava422 at javautilcomparabletimsortsortcomparabletimsortjava2 at javautilarrayssortarraysjava1246 at javaxswingdefaultrowsortersortdefaultrowsorterjava607 at javaxswingdefaultrowsortersetsortkeysdefaultrowsorterjava319 at javaxswingdefaultrowsortertogglesortorderdefaultrowsorterjava480 at javaxswingplafbasicbasictableheaderuimouseinputhandlermouseclickedbasictableheaderuijava112 at javaawtawteventmulticastermouseclickedawteventmulticasterjava270 at javaawtcomponentprocessmouseeventcomponentjava6538 at javaxswingjcomponentprocessmouseeventjcomponentjava3324 at javaawtcomponentprocesseventcomponentjava6300 at javaawtcontainerprocesseventcontainerjava2236 at javaawtcomponentthispatcheventimplcomponentjava4891 at javaawtcontainerthispatcheventimplcontainerjava2294 at javaawtcomponentthispatcheventcomponentjava4713 at javaawtlightweightthispatcherretargetmouseeventcontainerjava48 at javaawtlightweightthispatcherprocessmouseeventcontainerjava4534 at javaawtlightweightthispatcherthispatcheventcontainerjava4466 at javaawtcontainerthispatcheventimplcontainerjava2280 at javaawtwindowthispatcheventimplwindowjava2750 at javaawtcomponentthispatcheventcomponentjava4713 at javaawteventqueuethispatcheventimpleventqueuejava758 at javaawteventqueueaccess500eventqueuejava97 at javaawteventqueue3runeventqueuejava709 at javaawteventqueue3runeventqueuejava703 at javasecurityaccesscontrollerdoprivilegednative method at javasecurityprotectiondomainjavasecurityaccessimpldointersectionprivilegeprotectiondomainjava76 at javasecurityprotectiondomainjavasecurityaccessimpldointersectionprivilegeprotectiondomainjava86 at javaawteventqueue4runeventqueuejava731 at javaawteventqueue4runeventqueuejava729 at javasecurityaccesscontrollerdoprivilegednative method at javasecurityprotectiondomainjavasecurityaccessimpldointersectionprivilegeprotectiondomainjava76 at javaawteventqueuethispatcheventeventqueuejava728 at javaawteventthispatchthreadpumponeeventforfilterseventthispatchthreadjava201 at javaawteventthispatchthreadpumpeventsforfiltereventthispatchthreadjava116 at javaawteventthispatchthreadpumpeventsforhierarchyeventthispatchthreadjava105 at javaawteventthispatchthreadpumpeventseventthispatchthreadjava101 at javaawteventthispatchthreadpumpeventseventthispatchthreadjava93 at javaawteventthispatchthreadruneventthispatchthreadjava82,['java'] +1191965,create an array in a function in c without a global variable so i would like to create an array in a function with the size set by a number coming in as the parameter here is an examplevoid temp arr const int array size int temp arrarray size error array size needs to be a constant value then do something with the temp arreven if the parameter is a const int it will not work i would like to not use a global const and not use vectors i am just curious as i am learning c i would like for it to make it so that the array size is different each time the function is called is there a solution to this or am i to create a const variable and the array before the function is called,['c++'] +1192050,how to handle race conditions in web service i implemented a web service with java servletsi got the following setupthere is a database which handles jobentries each job has a status like executing or in queue or finished if a user starts a new job there is made an entry in the database with a job and the status in queuethe job should only be executed if less than five other jobs are already executed if there are five others already executing the status needs to stay in queue and a cronjob will handle the execution of this job laternow i just wonder that if there are less than five jobs executing at the moment my script will execute this job but what if at the same time between my script asking the database how many jobs are being executed and the script starting to execute the job another request from another user creates a job and also gets four executing jobs as a result from the databasethen there would be a race condition and 6 jobs would be executedhow can i prevent something like thatany advice thank you very very much,['java'] +1192248,why does upcasting child pointer to base class sometimes change pointer value i found a few other questions that seem to implicate my question but none directly answered it even the one with almost the same namei have a c child class derived from two parents i create an object of that class then cast its reference to each of its two parents the cast values are not the same though one remains the value of the child reference heres the codeclass mompublic int a 1class dadpublic int b 2class child public mom public dadpublic int c 3int main child c new child 0x00c5a618 mom m c 0x00c5a618 dad d c 0x00c5a61c return 0now i am guessing that the addresses obtained by applying static cast are those of the actual subobjects as it happens mom is the first subobject so it actually has the same address as child dad is the second subobject so it resides at a different addressas i understand it cstyle casts like thismom m momcdad d dadcwill apply a static cast when it would be legal to do so indeed when i actually compile and execute that version i see the same behavior as beforecontinuing this scintillating saga using implicit casts like thismom m cdad d cexhibit the same behavior as well from which i infer that implicit casts also apply static cast when the equivalent explicit cast would be legaldowncasting back to child does the same thingchild k static castchildd 0x00c5a618the value in k is different from the value in d having been set back to the value orginally in ci am guessing that in this case there is a runtime check to see if indeed d points to a dad subobject of a child objectso far this all makes sense but i am surprised that there is no such address adjustment if that is the right thing to call it for singly derived hierarchies that is if my hierarchy is simply momdadchild casting a reference to a child into a pointer to either a mom or a dad never changes the valueclass mompublic int a 1class dad public mompublic int b 2class child public dadpublic int c 3int main child c new child 0x00c5a618 mom m c 0x00c5a618 dad d c 0x00c5a618 child k static castchildd 0x00c5a618 return 0i would have expected it to change by the size of the the storage needed for each additional subclass or four bytes the size of an int but they do not all of the pointers in the above example c m d and k have the same value so now i am guessing that the objects were laid out in memory with the mom object at the lowest address the additional space needed for the dad object coming next and the additional space needed for the child coming last since a dad isa mom the dad address would be the same as the mom address wouldnt it likewise a child isa mom too so its address would also be the same as its own mom subobjects addresoi think it is working like this in memory the objects follow each other such that in purely singly derived hierarchy upcasting and downcasting always yields the same address while in a multiply derived hierarchy some upcasts yield a different address because not all subobjects will start at the same address as the derived object like thispossible memory layout for a singly derived hierarchy child dad mom a b c possible memory layout for a multiply derived hierarchy child mom a dad b c sorry that i have rambled a bit but my question is this is the fact that an upcast to some base classes of a multiply derived object changes the value of the reference a result of the fact that the postcast value is the address of the base object in memory,['c++'] +1192249,how is nullptr rvalue while looking at the implementation of nullptr here what got my attention is that nullptr is rvalue which means we can do something like this stdnullptr t nullref nullptrbut how could nullptr be rvalue since the implementations is something like this const class nullptr is this core feature what am i missing,['c++'] +1192345,avmutableaudiomixinputparameters not applied correctly to audiomix i am working on application that combines the multiple videos along with background audio track it also need to set different audio level for different videos following is the code for assetitem class assetmanager class assetitem class class assetitem nsobject var asset assetvar asseteffect asseteffecttype enum var assetscenetype scenetype enumvar videolength cmtimevar animationlayer anyobjectvar volumeofvideovoice float 00var volumeofbgmusic float 00override init superinit assetmanager class implementation class assetmanager var assetlist assetitem var composition avmutablecomposition avmutablecomposition var videocomposition avmutablevideocomposition avmutablevideocomposition var audiomix avmutableaudiomix avmutableaudiomix var transitionduration cmtimemakewithseconds1 600 default transitionduration is 1 secvar compositiontimeranges nsvalue nsvaluevar passthroughtimerangevalue nsvalue nsvaluevar transitiontimerangevalue nsvalue nsvaluevar videotracks avmutablecompositiontrackvar audiotracks avmutablecompositiontrack mark constructoroverride init superinit let compositiontracka selfcompositionaddmutabletrackwithmediatypeavmediatypevideo preferredtrackid cmpersistenttrackidkcmpersistenttrackid invalid let compositiontrackb selfcompositionaddmutabletrackwithmediatypeavmediatypevideo preferredtrackid cmpersistenttrackidkcmpersistenttrackid invalid let compositiontrackaudioa selfcompositionaddmutabletrackwithmediatypeavmediatypeaudio preferredtrackid cmpersistenttrackidkcmpersistenttrackid invalid let compositiontrackaudiob selfcompositionaddmutabletrackwithmediatypeavmediatypeaudio preferredtrackid cmpersistenttrackidkcmpersistenttrackid invalid selfvideotracks compositiontracka compositiontrackb selfaudiotracks compositiontrackaudioa compositiontrackaudiob func buildcompositiontrackforexport bool this is the method to build compositions following is the method for buildingcompositions func buildcompositiontrackforexport bool var cursortime kcmtimezero var transitiondurationforeffect kcmtimezero create a mutable composition instructions object var videocompositioninstructions avmutablevideocompositioninstruction var audiomixinputparameters avmutableaudiomixinputparameters let timeranges calculatetimerangeforassetlayer selfpassthroughtimerangevalue timerangespassthroughtimerangevalue selftransitiontimerangevalue timerangestransitiontimerangevalue let defaultmutesoundtrackurl nsurl bundleurlforresource30sec withextension mp3 let mutesoundtrackasset avurlasseturl defaultmutesoundtrackurl options nil let mutesoundtrack mutesoundtrackassettrackswithmediatypeavmediatypeaudio0 for indexassetitem in selfassetslistenumerate let trackindex index 2 let assetvideotrack assetitemassetmovieassettrackswithmediatypeavmediatypevideo0 let timerange cmtimerangemakekcmtimezero assetitemvideolength do try selfvideotrackstrackindexinserttimerangetimerange oftrack assetvideotrack attime cursortime catch let error1 as nserror error error1 if error nil printerror buildcompositiontracks for video with parameter index and videocounts error index selfassetslistcount errordescription error nil if assetitemassetmovieassettrackswithmediatypeavmediatypeaudiocount 0 let clipaudiotrack assetitemassetmovieassettrackswithmediatypeavmediatypeaudio0 do try audiotrackstrackindexinserttimerangetimerange oftrack clipaudiotrack attime cursortime catch let error1 as nserror error error1 else do try audiotrackstrackindexinserttimerangetimerange oftrack mutesoundtrack attime cursortime catch let error1 as nserror error error1 the end of this clip will overlap the start of the next by transitionduration note this arithmetic falls apart if timerangeinassetduration 2 transitionduration if assetitemasseteffect flixasseteffecttypedefault transitiondurationforeffect kcmtimezero let timerange cmtimerangemakecursortime assetitemvideolength selfcompositiontimerangesappendnsvaluecmtimerange timerange cursortime cmtimeaddcursortime assetitemvideolength else transitiondurationforeffect selftransitionduration let timerange cmtimerangemakecursortime cmtimesubtractassetitemvideolength transitiondurationforeffect selfcompositiontimerangesappendnsvaluecmtimerange timerange cursortime cmtimeaddcursortime assetitemvideolength cursortime cmtimesubtractcursortime transitiondurationforeffect videocompositioninstructionsappendcontentsofselfbuildcompositioninstructions index assetitem assetitem if selfprojecthasprojectmusictrack selfbackgroundmusictrack nil let url nsurl bundleurlforresourcemusic9 withextension mp3 bgmusicsound avurlasseturl url options nil backgroundaudiotrack bgmusicsoundtrackswithmediatypeavmediatypeaudio0 let compositionbackgroundtrack selfcompositionaddmutabletrackwithmediatypeavmediatypeaudio preferredtrackid cmpersistenttrackidkcmpersistenttrackid invalid let soundduration cmtimecomparebgmusicsoundduration selfcompositionduration if soundduration 1 let bgmusicsoundtimerange cmtimerangemakekcmtimezero bgmusicsoundduration let nooftimes intcmtimegetsecondsselfcompositionduration cmtimegetsecondsbgmusicsoundduration let remainingtime cmtimegetsecondsselfcompositionduration cmtimegetsecondsbgmusicsoundduration var musiccursortime kcmtimezero for in 0nooftimes do try compositionbackgroundtrackinserttimerangebgmusicsoundtimerange oftrack backgroundaudiotrack attime musiccursortime catch let error1 as nserror error error1 musiccursortime cmtimeaddbgmusicsoundduration musiccursortime let backgroundmuscimixinputparameters avmutableaudiomixinputparameterstrack compositionbackgroundtrack backgroundmuscimixinputparameterstrackid compositionbackgroundtracktrackid setting up music levels for background music track for index in 0 intselfcompositiontimerangescount let timerange selfcompositiontimerangesindexcmtimerangevalue let scene selfassetslistindexassetscenetype let volumeofbgmusic selfassetslistindexvolumeofbgmusic var nextvolumeofbgmusic float 00 if let nextasset selfassetslistsafe index 1 nextvolumeofbgmusic nextassetvolumeofbgmusic backgroundmuscimixinputparameterssetvolumevolumeofbgmusic attime timerangestart backgroundmuscimixinputparameterssetvolumerampfromstartvolumevolumeofbgmusic toendvolume nextvolumeofbgmusic timerange cmtimerangemakecmtimesubtracttimerangeendcmtimemake2 1 cmtimemake2 1 audiomixinputparametersappendbackgroundmuscimixinputparameters end of if for projectmusic check for index assetitem in selfassetslistenumerate let trackindex index 2 let timerange selfcompositiontimerangesindexcmtimerangevalue let scenetype assetitemassetscenetype let volumnofvideomusic assetitemvolumeofvideovoice let audiotrackparamater avmutableaudiomixinputparameterstrack selfaudiotrackstrackindex audiotrackparamatertrackid selfaudiotrackstrackindextrackid audiotrackparamatersetvolume00 attime kcmtimezero statement 1 audiotrackparamatersetvolumevolumnofvideomusic attime timerangestart statement 2 audiotrackparamatersetvolume00 attime timerangeend statement 3 audiomixinputparametersappendaudiotrackparamater selfaudiomixinputparameters audiomixinputparameters selfcompositionnaturalsize selfvideorendersize selfvideocompositioninstructions videocompositioninstructions selfvideocompositionrendersize selfvideorendersize selfvideocompositionframeduration cmtimemake1 30 selfvideocompositionrenderscale 10 this is a iphone only option in above code background music levels are set properly but something is going wrong for audio levels of video tracks i have added debugview to help debug compositions everything looks perfect in debug view but other than background music track audio of video is no more audible is there is something i am doing wrong if i remove statement 1 from above code then its audible but now they are all audible at level 10 and dont respect the levels set,['ios'] +1192375,fcm with aws sns i am using aws resources for my android project i am planning to add push notification service for my project with aws snsthere are few questions bothering me much i did not find any questions regarding these except one or two but with unclear explanations1does aws support fcm sns work with gcm but google recommends to use fcm instead of gcm i did not find aws supporting fcm2do aws store messages or data into their databases even after sending push notifications3i tried putting fcm api key in sns application platform it is showing invalid parameters why,['android'] +1192422,how to configure aspectj in android studio i am trying to configure aspectj in android studio but after all trial and error its not working surprisingly i am able to make it work with eclipse kepler version the steps i followed for android studiocreated sample android projectfile settings searched for aspectj in plugin sectionassuming nothing more to be done in studio except configuration of buildgradle filesadded compile orgaspectjaspectjrt181 to the to the buildgradle moduleappcreated analytics onbackpressedaj for back button press detectioncreated analytics onclickaj for click events detectioncreated analytics oncreateaj for components oncreate event detectioncreated necessary dependency classes which the above mentioned aj classes will internally calladded required permissions in manifestrunning the project is not detecting any of the events button click oncreate or back button clickfollowed these links referencelinkone referencelinktwo and referencelinkthreemy question is what is more required to make aspectj working with android studiosteps followed in eclipse and got aspectj workingdownloaded eclipse kepler versionthrough install new software option searched for installed aspectj development tools required created sample android projectcreated analytics onbackpressedaj for back button press detectioncreated analytics onclickaj for click events detectioncreated analytics oncreateaj for components oncreate event detectionadded required permissions in manifest fileright clicked in project and converted project to aspectj by the followingconfigured java build path with aspectj runtime librarynow while running the project i am able to detect components oncreate back button pressenvironment usedandroid studio 212jre 180windows 7 enterpriseany help is highly appreciatededit 1 from the output still aspectj is not properly configured as per this link i created jar file from eclipse including aj files and corresponding dependency excluded androidmanifestxml while creating jar file and created jarcreated project in android studio placed this jar file in libs file apps libs i have enabled aspectj waving as shown belownow searched the properties for aspectj and enabled now running the project should be creating logs i had put in aj files which is in plugin unfortunately these logs are not printed in android studio logs form which i am concluding still aspectj is not enabled in this project or there is a configuration error,['android'] +1192735,position an image view as overlay image on camera preview hello there i am coding a camera app using android camera apiit has the following functionsthe app has an image view over the camera previewthe user can drag and drop that image view on the camera previewthe drop event catch the position of the image view where it droppedthe user captures an image and the image view is being added on the photo on the users desired drag then dropped locationhere is the code that is used for the image view drag and dropoverridepublic boolean ontouchview view motionevent event final int x int eventgetrawx final int y int eventgetrawy switch eventgetaction motioneventaction mask case motioneventaction down relativelayoutlayoutparams lparams relativelayoutlayoutparams viewgetlayoutparams xdelta x lparamsleftmargin ydelta y lparamstopmargin break case motioneventaction up xlocx ylocy toastmaketextgetcontext locationintegertostringxlocintegertostringyloc toastlength shortshow break case motioneventaction pointer down break case motioneventaction pointer up break case motioneventaction move relativelayoutlayoutparams layoutparams relativelayoutlayoutparams view getlayoutparams layoutparamsleftmargin x xdelta layoutparamstopmargin y ydelta layoutparamsrightmargin 250 layoutparamsbottommargin 250 viewsetlayoutparamslayoutparams break mrrootlayoutinvalidate return truethe xloc and yloc contains the postion where the user will drop that image viewthis is the code i am using to determine the device orientation it is being done by the sensor because the activity is set to portrait in manifestxml by default override public void onsensorchangedsensorevent event float x eventvalues0 float y eventvalues1 if x 5 x 5 y 5 portrait up a cam orientation 0 image watermarksetrotation0 rotating the water mark with screen orientation else if x5 y5 y5 landscape right a cam orientation 3 image watermarksetrotation270 else if x5 x5 y5 portrait down a cam orientation 4 image watermarksetrotation0 else if x5 y5 y5 landscape left a cam orientation 1 image watermarksetrotation90 here is the code for capturing the image private camerapicturecallback mpicture new camerapicturecallback override public void onpicturetakenbyte data camera camera file picturefile getoutputmediafile1 if picturefile null logilogtag picexception return try rotate the image view as expected bitmapfactoryoptions options new bitmapfactoryoptions bitmap mbitmap bitmapfactorydecodebytearraydata 0 datalength options ifcam orientation0 portrait up a ifcam id1 this is front camera id1 mbitmap rotatembitmap 270 mbitmapflipmbitmap ifcam id0 mbitmap rotatembitmap 90 ifcam orientation1 landscape left a ifcam id1 this is front camera id1 mbitmap rotatembitmap 0 mbitmapflipmbitmap ifcam id0 this is back camera id0 mbitmap rotatembitmap 0 ifcam orientation3 landscape right a ifcam id1 this is front camera id1 mbitmap rotatembitmap 180 mbitmapflipmbitmap ifcam id0 this is back camera id0 mbitmap rotatembitmap 180 ifcam orientation4 portrait down a ifcam id1 this is front camera id1 mbitmap rotatembitmap 90 mbitmapflipmbitmap ifcam id0 this is back camera id0 mbitmap rotatembitmap 270 add the water mark to the camera photo bitmap here bitmap mutablebitmap mbitmapcopybitmapconfigargb 8 true image watermarkbuilddrawingcache bitmap bmap image watermarkgetdrawingcache bitmap final imagebitmapcreatescaledbitmapbmapimage watermarkgetmeasuredwidth2image watermarkgetmeasuredwidth2false canvas canvas new canvasmutablebitmap ifcam id1 canvasdrawbitmapiconintxloc15intyloc15 null setting the location of the water mark image view on front cameraphoto ifcam id0 canvasdrawbitmapiconxloc2yloc2 null setting the location of the water mark image view on back cameraphoto fileoutputstream fos new fileoutputstreampicturefile mutablebitmapcompressbitmapcompressformatjpeg100fos fosclosei have a problem of setting up the location of water mark image view on the captured photo from the camera i just want to set the location of the water mark image view to be set where the user dragged and dropped that water mark image viewthough the code works alright but there is a lack of precision and accuracy in setting up the water mark image view location on captured photo for different devicesi have been trying on different devices but each device thistorts the accurate positioncan somebody give me any idea or a better approach to add a water mark image on the camera captured photoplease note that the ids for camera are cam id1 for the from camera cam id0 for the back camerai need an approach so that i could able to position my water mark image on all device orientation modes and for at least some multiple devicesthanks suppose that if i drag my image view on this blue button when the screen is in portrait position the image should be save on the camera captured photo on the same location that is on the blue buttonsimilarly if i placed it on that box the camera captured photo should position this image view same on that box in landscape modehere is the used xml below relativelayoutxmlnsandroidxmlnstoolsandroidlayout widthmatch parentandroidlayout heightmatch parenttoolscontextlinearlayout androidlayout widthmatch parent androidlayout heightmatch parent androidorientationvertical linearlayout androidlayout widthmatch parent androidlayout heightwrap content androidorientationhorizontal androidbackgroundcolorcoloraccent togglebutton androidididflipper androidlayout widthwrap content androidlayout heightwrap content androidtext androidbackgrounddrawablemy btn toggle androidtextoff androidtexton linearlayout relativelayout androidlayout widthmatch parent androidlayout height0dp androidlayout weight10 androidididroot framelayout androidlayout widthmatch parent androidlayout heightmatch parent androidididcamera preview framelayout imageview androidlayout width0dp androidlayout height0dp androidididwatermark relativelayoutlinearlayout androidlayout widthmatch parent androidlayout height0dp androidlayout weight1 androidbackground0 androidlayout alignparentbottomtrue androidgravitycenter androidididcapture layout button androidlayout widthwrap content androidlayout heightwrap content androidididcapture androidtextcapture androidlayout alignparentbottomtrue androidlayout alignparentrighttrue button androidlayout widthwrap content androidlayout heightwrap content androidididneg androidtextcancel para androidlayout alignparentbottomtrue androidlayout alignparentrighttrue linearlayout linearlayoutrelativelayout,['android'] +1193072,what are list comprehension scoping rules within a python class in the following code the mc assigment works fine in python 2 and 3 the cc assignment which uses the same list comprehension within a class works in python 2 but fails with python 3what explains this behaviorml1 a b csplitml2 1 2 3splitmc i1 i2 for i1 in ml1 for i2 in ml2 class fobject cl1 ml1 cl2 ml2 cc1 i1 for i1 in cl1 cc2 i2 for i2 in cl2 cc i1 i2 for i1 in cl1 for i2 in cl2 printmc mcfoo fooprintcc foocci get thisdefault35 snafu python2 tmpzpy mc a1 a2 a3 b1 b2 b3 c1 c2 c3cc a1 a2 a3 b1 b2 b3 c1 c2 c3default35 snafu python3 tmpzpy traceback most recent call last file tmpzpy line 5 in module class fobject file tmpzpy line 11 in foo cc i1 i2 for i1 in cl1 for i2 in cl2 file tmpzpy line 11 in listcomp cc i1 i2 for i1 in cl1 for i2 in cl2 nameerror name cl2 is not definedwhy is the class variable cl2 not defined note that the cc2 assignment works fine as does cc1 swapping cl1 and cl2 in the comprehension shows that the second loop is the one that triggers the exception not cl2 per seversionsdefault35 snafu python2 versionpython 2711default35 snafu python3 versionpython 351,['python'] +1193190,how to change height of iframe when it loads songlinkchangefunction var link songlinkval scoembedlink element documentgetelementbyidputthewidgethere script srcscriptscript srcscriptinput idsonglink placeholderpaste soundcloud link here namesong link typetextdiv idputthewidgetheredivcode helps me to preview the link of soundcloud you can test its works fine but i want to change its height from 400px to 200px i have tried adding addclass and css but it did not work i could not figure which event will trigger these functions since the height must be set after the link is pasted on input text and loads on the iframe that soundcloud loads,"['jquery', 'html', 'css']" +1193347,is there a way to know whether a certain dependency is compiled in the gradle file by returning a boolean so the case is this in the buildgradle file in the dependency structure i havedependencies compile a compile bhowever i want people to be able to compile either just a or just b is there a way to know for instance whether the dependency a was used by returning a global boolean that can be used somewhere else in a gradle taskso in other wordsif a was compiled compile a else exclude a,['android'] +1193349,why does auto return type deduction work with not fully defined types consider the followingtemplatetypename derstruct base note if i replace the decltype below with auto code compiles decltypederoperator getcalloperator const return deroperator struct foo basefoo double operatorint int const return 00 int main foo f auto callop fgetcalloperatori want to create a member function in crtp base class with a return type depending on signature of the operator in the derived class however decltypederoperator fails to compile the operator member function in foo is not visible i assume that this is because the base class template is instantiated before foo is fully definedsurprisingly if i place auto for the return type it compiles i assumed that auto would make the compiler deduce the return type from the function body and fail because the body uses the not fully defined foo typethis behavior is the same for both msvc 20153 and clang 38why did the code start to work with auto does auto type deduction somehow delay the instantiation or use a different context than a handwritten return type expression,['c++'] +1193485,without javascript can i show a different text when a longer one would not fit what i am trying to doi have a sizelimited box which is supposed to contain some textbox width 100px height 40px backgroundcolor yellowdiv classbox some text goes heredivhowever if the text becomes too long to fit in the box i want to replace that text with a different shorter version which i have prepared in advanceso for example if i want to populate two boxes with these two namesshort version long versionrudolf e raspe rudolf erich raspebaron munchausen hieronymus karl friedrich von munchhausenthen the first box will contain rudolf erich raspe since it is short enough to fit inside but the second box will contain baron munchausen since the barons full name is too long to fithow can i set up such a box using just html5 and css3 browser compatibility is important but i do not need to accommodate really old versions or internet explorer prior to 11alternativesi can choose any of the standard options for handling toolong text letting it overflow or cutting it via overflow hidden or adding scrollbars or adding ellipses or any of the other standard solutions but since i already have short versions of every possible text there i would like to use these insteadi can do this in javascript by for example using a wrapper and comparing its size with the boxs but i would like a nonjavascript solution if possiblewhat i have triedso far i thought about making the text somehow push itself down if it is too long some combination of whitespace and wordwrap making the container overflow hidden to hide it when it is down there and placing the short version of the text behind it but i could not get it to work while still allowing the text to occupy more than one lineanother approach is to place an element with the short text just below the element with the long text and use some transform which makes that short element take over when it is pushed down too much but i could not get it to work eitherso any other ideas,"['html', 'css']" +1193626,what would the big o be of a nested for loop with an any inside it this questions is basically a followon from my answer here i really wanted to say what the bigo of this algorithm would be but i was not sure my claim was completely soundso given two arraysb hello world hello stack overflow foo bar food is nice hej a world foo what is the big o ofliststring results new liststringforeach string test in b if aanya testcontainsa resultsaddtesti believe it to be somewhere between on and on2 as it depends where in the result the any matches,['c#'] +1193758,why is domparser not preserving inline styles of parsed dom i am simply trying to parse and append a javascript string as a dom element i have found two quick ways to do this one of which is using domparser as seen in this popular so answer both methods work however the domparser approach for some reason is not respecting the inline styles i define even though both methods inject the exact same dynamic markup consider the followingdivdivvar parent documentgetelementsbytagnamediv0 case 1 var parser new domparservar node parserparsefromstringp stylecolor redfoop textxmlfirstchildparentappendchildnode case 2 var wrapper documentcreateelementdivwrapperinnerhtml p stylecolor redfoopvar node2 wrapperfirstchildparentappendchildnode2each method injects the node accordingly and the dom reflects the followingdiv p stylecolor redfoop p stylecolor redfoopdivhowever only the last is red any idea what can possibly be going on herejsfiddle reproduction demo,"['javascript', 'html']" +1193831,grunt code coverage does not work i have the following grunt file which runs the mocha tests ok i get results of the test after running gruntjsnow i want to add a code and i use the module but when i run the gruntjs nothing happenany ideawhat i want is simply after that mocha test are running it will run the code coverage with some reports any new code coverage will be greatthis is my project structuremyapp serverjs appjs test test1spec test2spec testreports gruntjs utils file1js file2js controller file1js file2jsthis is the code inside the grunt for what i have triedmoduleexports function grunt var path requirepath processenvresource path prefix var d new date var datestring dgetdate dgetmonth 1 dgetfullyear dgethours dgetminutes var npmcommand pathdirnameprocessexecpathconcatnpm var reportdir testreports datestring gruntinitconfig jasmine nodejs task specific default options options specnamesuffix specjs helpernamesuffix helperjs usehelpers false stoponfailure false reporters console colors true junit savepath testreports fileprefix testresult test specs test makereport src testreportscoveragejsonshould i create this fileor its created automatically options type lcov html dir reportdir print detail coverage app dir for code coverage utilsjshere is the path of the utils folder which all the js login which i want to test there clean build instrument files taskswhat is tasks options lazy true basepath buildinstrumenti dont know what it is reloadtasks rootpath buildinstrumenttasksshould i use it storecoverage options dir reportdir gruntloadnpmtasksgruntjasminenodejs gruntloadnpmtasksgruntistanbul gruntregistertaskdefault jasmine nodejs gruntregistertaskcover instrument test storecoverage makereportif there is mocha code coverage which can help it will be great either i want that after i run the test i will able to see report with all the code coveragei want that the coverage will be done for folder utils and controller all the files there how should i config thatupdatethis is what i use for jasmin and i think i should change to mocha jasmine nodejs task specific default options options specnamesuffix specjs also accepts an array helpernamesuffix helperjs usehelpers false stoponfailure false reporters console colors true cleanstack 1 0false1true23 verbosity 4 0false1234true liststyle indent flatindent activity false junit savepath testreports fileprefix testresult consolidate true usedotnotation true test target specific options options usehelpers false spec files specs test how should i change itthe syntax of my test are similarjasminemocha and what i want is simply to run my test and after run the code coverage,['javascript'] +1194019,is there a better way to determine multiple ranges of character i am currently writing code in c which selects symbols and numbers from whole asciiavailable charactersas a beginner of programmer i usually didif i 25 i 50 i 100 i 200 contents for the variable i being between 2550 100200 exclusive to fit the conditionif i want to set multiple ranges like 3264 to and 9196 to and 123126 to then would there be any better meaning shorter or simpler code or should i stick with this method keep adding each range as in the code above,['c'] +1194257,why does googlepubsubv1 beta01 not work with dotnet cli projects i have created a very simple program which should list the topics available in a google cloud project the code is trivialusing systemusing googlepubsubv1public class test static void main var projectid fill in project id here var projectname publisherclientformatprojectnameprojectid var client publisherclientcreate foreach var topic in clientlisttopicsprojectname consolewritelinetopicname when i run this from a regular msbuild project targeting net 45 it works fine when i try to use dotnet cli 100preview2003121 with the following projectjson file buildoptions emitentrypoint true dependencies googlepubsubv1 100beta01 frameworks net45 i see an exceptionunhandled exception systemiofilenotfoundexception error loading native librarynot found in any of the possible locations cpubsubdemobindebugnet45win7x64nativelibswindows x64grpc csharp extdll at grpccoreinternalunmanagedlibraryfirstvalidlibrarypathstring librarypathalternatives at grpccoreinternalunmanagedlibraryctorstring librarypathalternatives at i am not trying to target net core so should not this be supported,['c#'] +1194268,open generic type arguments cannot be inferred from the usage in this question when mentioning the compiler i am actually referring to the roslyn compiler the problem arises when using intellisense which is presumed to be the same compilerfor demonstration purposes and completeness the following classes are used using visual studio 2015 with c 60 and net 461public class a public ienumerableb b get set public class b public ienumerablec c get set public class c public class helpert behold the following extension methodpublic static void foobart1 t2 this helperienumerablet1 helper expressionfunct1 ienumerablet2 expression the compiler is able to infer it while consuming like thishelperienumerableb helper helperfoobarl lc t1 is b and t2 is calso behold this overloaded extension methodpublic static void foobart1 t2 t3 this helpert1 helper expressionfunct1 ienumerablet2 expression1 expressionfunct2 ienumerablet3 expression2 the compiler is not able to infer t1 when typing it like thishelpera helper helperfoobarl l compilerintellisense cannot infer that t1 is athis screenshot example will describe more of what i mean with not able to infer also i am getting this error message when hovering over the extension method with my mouse i have replaced the and characters with and respectively because stackoverflow cannot format those in a quotethe type arguments for method foobart1t2this helperienumerablet1 expressionfunct1 ienumerablet2 cannot be inferred from the usage try specifying the type arguments explicitlybut when completing it manually like thishelperfoobarl lb l lc compiler infers that t1 is a t2 is b and t3 is cthe compiler is happywhy cannot the compilerintellisense or the autocomplete feature of visual studio figure out t1 and wants me to specify the type arguments explicitly when i start typingnote that if i omit ienumerable everywhere in my examples the compiler can happily infer everything while typingthe compiler is also happy after you manually type in l lb it then knows t1 is a so you can express the last argument with the help of intellisense,"['c#', '.net']" +1194415,check existence of global function in swift is it possible to detect if some global function not class method is defined in ios something like respondstoselector in a class,['ios'] +1194773,longest substring that matches a string in an array assume i have the following input and that my implementation language is javaan array a with the contents brown fox jumped over the lazy dog dog the fish quantum burrito ox jumped over the laz and ate ate piea string s with the contents the quick brown fox jumped over the lazy dog and ate pie first character index 0 last character index 55i need to as efficiently as is practical on a typical computer assemble a list of substrings of the string s that are contained entirely within an element of the array a and get those in descending order i also need to know the starting and ending character index within the string s of each match but with some constraintsthe following constraints and peculiarities apply to this problemnot all elements in the array a may be contained within the string s in the example fish and quantum burrito are not in sthe string s may contain lengths of characters that do not match any elements within the array in the example quick in s does not match anything in arespect word boundaries within s words are guaranteed to be delimited by exactly one space in both a and s meaning it is not a match if a length of characters within s matches a but violates word boundaries by not capturing one or more whole wordswhen there is a tie on length sort order in the result array is irrelevantonce a range of characters within s is matched that range will only be captured in one result element even if it could match multiple elements within aif there are two possible matches pick one arbitrarily depending on the order the algorithm processes the elements in the arrayi need to keep track of which ranges of characters do not get matched after the algorithm is doneworking this out manually just by looking at the string and array in this example the solution would be the following given in the correct descending order zerobased indexingthe range of characters 2034 jumped over the is in index 1 of the array length 15the range of characters 1018 brown fox is in index 0 of the array length 9the range of characters 3643 lazy dog is in index 2 of the array length 8the range of characters 4955 ate pie is in index 9 of the array arbitrary match matching and ate is equally valid but we do not match both because ate is already consumed no pun intended length 7the range of characters 02 the is in index 4 of the array length 3the word quick was not matched to any element in the arraythe word and was not matched to any element in the arraynote specifically that ox jumped over the laz although it is the longest substring in a that is within s is not matched in the result set because it violates the word boundaries of fox and lazyquestion am i describing a fairly standard algorithm that may exist in a library in part or in whole i am willing to build this out of simpler primitive building blocks or is this something so custom that i need to implement it from scratchif i implement it from scratch i think i need to take an approach broadly sketched out like the followingsplit string s on word boundariesconstruct a list l of all orderrespecting word sequences within the string s in descendinglength order for example the quick brown fox jumped over the lazy dog and ate pie the quick brown fox jumped over the lazy dog and ate quick brown fox jumped over the lazy dog and ate pie the quick brown fox jumped brown fox jumped jumped quick brown pieconstruct a suffix tree t from the array as contentsiterate over the list l in order and try to find each element in tonce an element is found note down the substring range from s the match index from a then continue iteratingeach time an element is matched if the character range indexes of the element match overlaps with an element already matched skip it and keep goingsounds slow and probably moderately difficult to do right,['java'] +1195041,lambdas from a list comprehension are returning a lambda when called i am trying to iterate the lambda func over a list as in testpy and i want to get the call result of the lambda not the function object itself however the following output really confused me testpybinenv pythoncoding utf8a lambda i for i in range5for i in a print ioutputfunction lambda at 0x7f489e542e60function lambda at 0x7f489e542ed8function lambda at 0x7f489e542f50function lambda at 0x7f489e54a050function lambda at 0x7f489e54a0c8i modified the variable name when print the call result to t as following and everything goes well i am wondering what is all about of that testpyupdatea lambda i for i in range5for t in a print toutput4,['python'] +1195484,in 7392 swift how to thisable rotation animation when device rotates this question is strictly about ios9say you have an ordinary modern app autolayout storyboard universal which does allow all four rotation positionsyou want it to autorotate in the normal way so it will change to your new constraintbased layouts when user rotates device from landscape to portraitbut you simply want no animation during the user rotating the device you want it to just click to the new sideways or upright layoutthe only way i have been able to achieve this is by addingoverride func viewwilltransitiontosizesizecgsize withtransitioncoordinator coordinatoruiviewcontrollertransitioncoordinator coordinatoranimatealongsidetransitionnil completion in uiviewsetanimationsenabledtrue uiviewsetanimationsenabledfalse superviewwilltransitiontosizesize withtransitioncoordinator coordinator to one view controller a highest or nearhighest vc which holds the rest of the container views or whatever in the scenethis is basically the same ancient idea of using willrotatetointerfaceorientationdidrotatefrominterfaceorientation both now unusable in modern ios to turn animations onoffhowever there are many problems this does not work appwide it is a mess it is scenebasedit seems very bad to just turn off all animationsyou can see all sorts of racetrackthis question is strictly about ios9these days is there any better way to turn off the rotation animations in an app which supports landscapeportrait this question is strictly about ios9,['ios'] +1195755,end up activity on swipe right i have to finish activity when user offer a right swipe anywhere in the screen i have tried with gesturedetector and that is works fine if there is neither scrollview nor rescyclerview exists in the activity and in addition views that have onclicklistener also does not allow to detect swipe over them so i had tried a different way by overlaying a view into the layout at the top of all them programmatically then tried to detect the swipe event over itprivate void swipeovertoexitviewgroup rootview overlaylayout child new overlaylayoutthis viewgrouplayoutparams layoutparams new viewgrouplayoutparamsviewgrouplayoutparamsmatch parent viewgrouplayoutparamsmatch parent childsetlayoutparamslayoutparams rootviewaddviewchildoverlaylayout public class overlaylayout extends relativelayout private float x1 x2 private final int min thistance 150 public overlaylayoutcontext context supercontext public overlaylayoutcontext context attributeset attrs supercontext attrs public overlaylayoutcontext context attributeset attrs int defstyleattr supercontext attrs defstyleattr targetapibuildversion codeslollipop public overlaylayoutcontext context attributeset attrs int defstyleattr int defstyleres supercontext attrs defstyleattr defstyleres override public boolean onintercepttoucheventmotionevent event this method just determines whether we want to intercept the motion if we return true ontouchevent will be called and we do the actual logic there final int action motioneventcompatgetactionmaskedevent loggerlogdintercept action always handle the case of the touch gesture being complete if action motioneventaction down return true intercept touch event let the parent handle swipe loggerlogd out side action in general we do not want to intercept touch events they should be handled by the child view return false override public boolean ontoucheventmotionevent event switch eventgetaction case motioneventaction down x1 eventgetx break case motioneventaction up x2 eventgetx float deltax x2 x1 if mathabsdeltax min thistance loggerlogdswipe right min thistance return true else loggerlogdtap tap return superontoucheventevent return true the logic is to intercept touch event to other view if swipe action performs over the overlaylayout then further end up the activity however now i can detect the swipe event on overlaylayout but other views could not respond even though i had return return superontoucheventevent in else condition of ontouchevent as you can figure out there in my code any one please help me to make it i am pinned here and super excited to learn the trick,['android'] +1196506,extending stringprototype performance shows that function calls are 10x faster i wanted to extend string object prototype with some utility method it worked but the performance was surprisingly low passing a string to a function is 10x times faster than overriding the stringprototype method that is doing the same thing to make sure this really happens i created a very simple count function and the corresponding methodsi was experimenting and created three different versions of the methodfunction countstr char var and 0 for var i 0 i strlength i if stri char n return nstringprototypecount function char var and 0 for var i 0 i thislength i if thisi char n return nstringprototypecount reuse function char return countthis charstringprototypecount var function char var str this var and 0 for var i 0 i strlength i if stri char n return n here is how i measued speed using nodejs 610var str 011010100101101001010010101010101010110010101010110101010101010var rep 1e36consoletimefuncfor var i 0 i rep i countstr1consoletimeendfuncconsoletimeprotofor var i 0 i rep i strcount1consoletimeendprotoconsoletimeprotoreusefor var i 0 i rep i strcount reuse1consoletimeendprotoreuseconsoletimeprotovarfor var i 0 i rep i strcount var1consoletimeendprotovarresultsfunc 705 msproto 10011 msprotoreuse 10366 msprotovar 9703 msas you can see the difference is dramaticthe below proves that performance of method calls is neglectably slower and that the function code it self is slower for methodsfunction count dummystr char return 1234stringprototypecount dummy function char return 1234 just to prove that accessing the method is not the bottleneckconsoletimefuncdummyfor var i 0 i rep i count dummystr1consoletimeendfuncdummyconsoletimeprotodummyfor var i 0 i rep i strcount dummy1consoletimeendprotodummyconsoletimefuncdummyfor var i 0 i rep i count dummystr1consoletimeendfuncdummyresultsfuncdummy 0165msprotodummy 0247msalthough on huge repetitions like 1e8 prototyped methods proves to be 10x times slower than functions this can be ignored for this caseall this may be related only to a string object because simple generic objects perform about the same when you pass them to functions or call their methodsvar a count 1234 function getcountobj return objcount agetcount function return thiscount consoletimefuncfor var i 0 i 1e9 i getcountaconsoletimeendfuncconsoletimemethodfor var i 0 i 1e9 i agetcountconsoletimeendmethodresultsfunc 1689942msmethod 1674639msi have been searching on stackoverflow and binging but other that the recommendation do not extend string or array because you pollute the name space which is not a problem for my particular project i cannot find anything related to performance of methods compared to functions so should i simply forget about extending the string object due to performance drop of added methods or there is more about it,['javascript'] +1196586,sql server passing identifiers to stored proceduresdynamic sql backgroundsql server management studio allows to define own query shortcuts tools options environment keyboard query shortcutsimage from my schemamy table highlight it press ctrl 3 and you will get the number of rows in tableit works ok but it concatenates query in basic form as far as i know only at the end queryselect count from my schemamy tableattempt 1now i want to write something more specific for example passconcatenate table name to following query this is just exampleselect from syscolumns where object id object idso when i write in query shortcutsselect from syscolumns where object id object idi have to usemy schemamy table highlight it press ctrl 3the additional is very ugly and inconvenientattempt 2the second trial is to use dynamicsqlexec dbosp executesql nselect from syscolumns where object id object idobj name nobj name sysname executing my table highligt it and run livedemoworks also when table name is quoted my table as long as object is in dbodefault schemathe problem is that when table has schema it would not workexec dbosp executesql nselect from syscolumns where object id object idobj name nobj name sysname executingmy schemamy tablemy schemamy tablelivedemo2incorrect syntax near of course i could writeexec dbosp executesql nselect from syscolumns where object id object idobj name nobj name sysname and call it as my schemamy tablebut additional is also ugly and inconvenientquestionsis it possible to pass value to query shortcuts window in the middle positional or even more than one valueis it possible to pass do stored proceduredynamicsql qualified identifier without wraping it with remarksi do not search for plugins to ssmsi do not want to wrap object name as my schemamy tablei know there is sp helptext this is just example i search for methodfirst question is tool specific i am aware of it but second is about sql servereditto clarify passing identifier to sp without or create table dbomy tablecol intgocreate procedure dbomy proc a sysnameasselect from syscolumnswhere object id object idagoexec dbomy proc a my tableexec dbomy proc a dbomy table incorrect syntax near livedemo3,['sql'] +1196685,how is the ee in hexadecimal differentiated from the ee in exponential form in a hexadecimal floating point literal in c if i want a floating point literal x to be in hexadecimal form and have an exponential value it will be denoted as thisfloat x 0x2ae10where the 0x is used to denote it is in hexadecimal and the 2a for the hexadecimal characters and the e10 for the number into ten to the power tenhowever will the compiler know it is not 2ae that is representing the hexadecimal digits since hexadecimal uses a to e for 1015 and 10 is just adding ten to the number and if it does not whats the fix,['c'] +1196959,how to accurately filter rgb value for chromakey effect i just read this tutorial and tried this example so i downloaded a video from web for my own testing all i have to do is tweak rgb values in if conditionshere is the sample code from examplecomputeframe function thisctx1drawimagethisvideo 0 0 thiswidth thisheight let frame thisctx1getimagedata0 0 thiswidth thisheight let l framedatalength 4 for let i 0 i l i let r framedatai 4 0 let g framedatai 4 1 let b framedatai 4 2 if g 100 r 100 b 43 framedatai 4 3 0 thisctx2putimagedataframe 0 0 return in the tutorial example its filtering out yellownot yellow i guess color the sample video i downloaded uses green background so i tweaked rgb value in if condition to get desired resultsafter multiple tries i managed to get this now what i want to know is how can i accurately filter out green screen or any other screenperfectly without guessing or randomly tweaking valueswith just guessing it take hours to get it perfectly right and this is just a sample with a real world application it can take maybe morenote the example is working in firefox for now,['javascript'] +1197346,reset jquery animation when it stops animating i got an amazing ripple effect implementation from this website that uses the svgcircle element and a jquery animation function to create the ripple effect on userclick although i have a knowledge of basic programming i know less about javascript and jquery methodsfunctions so i did read a lot from my research about js and jqueryi found the ripple effect implementation useful lightweight and easy so i want to explore and expand the code to fit onto my projectsokay so the first thing i need to know here is how can i reset the changes made by the animation when it stops animating i know this is a simple question for you but as a beginner at js and jquery how can i achive thatheres the demo code to see what is actually happening herei tried adding the function as seen on the codecomplete functioncremoveattrstylebut nothing has changed and it still remains after the animation endsany idea what i am missin,"['javascript', 'jquery']" +1197492,collector returning singletonlist if tolist returned empty list i have quite a large stream pipeline and therefore would like to keep it clean i have the following part of larger pipelineinteger defaultintstreaminteger intsintsfilter predicate goes here collecttosingletonifemptycollectorwhere tosingletonifemptycollector is supposed to act the same as collectorstolist does if it returns nonemtpy list and collectionssingletonlistdefaultint if collectorstolist returned emptyis there a shorter way to implement it eg by composing standard collectors provided in jdk rather then implementing all collectors method from scratch,['java'] +1197612,does timesleep help the processor recently i was surfing on stack overflow python and saw this post where aaron hall claims that constantly running while loops can consume a lot of processing power adding a sleep period even only a second can greatly reduce that usageis it really true and if so how come does the same rule apply to other programming languages as well ie c,"['python', 'c++']" +1197748,write pdf files from webapp to usbstick i am concerned with the feasibility of thison a preconfigured machine i will have a webapplication preinstalled next to an apachesuite so client and server are the same in this webapplication users can drag and drop pdffiles to an usbiconthen the webapp should write the dropped pdf to an attached usbsticki have never done something like this writing to usb so i am fairly insecure and i am well aware of the browserrestrictions concerning javascript and filesystemaccess butafter researching a bit i found out that there might be some possible andrelevant i am a webplatformguy solutions to this make a chrome app with usbpermission does this really workuse php to find the usb and then write to it how would that work under windowsuse some flash as middle man not preferred now i would like to know has anyone some good experience with before mentioned possibilities has anybody ever done something similar did it work which path did you choose how would i know which drive the usb is mounted and how would i get surewhat other possible solutions to this problem are there,['javascript'] +1197749,iterating over a single lvalue i would like to pass a single lvalue to a function which expects a pair of iterators and for it to act as if i would passed a pair of iterators to a range containing just this valuemy approach is as followsinclude iostreaminclude vectortemplatetypename itervoid iterate overiter begin iter end forauto i begin i end i stdcout i stdendl int main stdvectorint a1234 iterate overacbegin acend int b 5 iterate overb stdnextbthis appears to work correctly in g52 but i am wondering if this is actually defined behaviour and if there are any potential issues,['c++'] +1198502,internet explorer inputchecked labelbefore styling is not rendered i am having some trouble getting the checked styling for my custom checkboxes to thisplay in internet explorerthey work perfectly fine in chrome but in ieheres the relevant stylinginputtyperadio inputtypecheckbox opacity 1 position absolute top 9 label verticalalign middle inputtyperadio labelbeforeinputtypecheckbox labelbefore content f3fd fontfamily ionicons width 26px height 20px border 2px solid 45f fontsize 24px color transparent thisplay tablecell textalign center transition all 03s linear webkittransition all 03s linear moztransition all 03s linear mstransition all 03s linear otransition all 03s linear padding 0 2pxinputtyperadiochecked labelbeforeinputtypecheckboxchecked labelbefore content f383 fontfamily ionicons fontsize 24px width 26px height 20px textalign center thisplay tablecell padding 0 2px border 2px solid 45f color 8ec549inputtyperadio labelbefore borderradius 50 importanti did also notice that internet explorer simply removes the styling on loadthanks for any helpedit codepen demo this demo does not work in ie either,['css'] +1198707,zipline using pandasdatareader to feed in google finance dataframe for nonus based financial markets please note this question was successfully answered ptrj below i have also written a blog post on my blog about my experiences with zipline which you can find here i am based in south africa and i am trying to load south african shares into a dataframe so that it will feed zipline with share price information let us say i am looking at adcorp holdings limited as listed on the jse johannesburg stock exchangegoogle finance gives me the historical price infoei5g6ov4ibbii8ucpnfgbyahoo finance has no information on the companytyping in the following code within ipython notebook gets me the dataframe for the information from google financestart datetimedatetime201671end datetimedatetime2016718 f webdatareaderjseadr googlestartendif i thisplay f i see that the information actually corresponds to the info off google finance as wellthis is the price exactly off google finance you can see the info for the 20160718 on the google finance website matches exactly to my dataframehowever i am not sure how to load this dataframe so that it can be used by zipline as a data bundle if you look at the example given for buyapplepy you can see that it just pulls the data of apple shares appl from the ingested data bundle quantopianquandl the challenge here is to replace appl with jseadr so that it will order 10 jseadr shares a day as fed from the dataframe instead of the data bundle quantopianquandl and plot it on a graph does anyone know how to do this there are almost no examples on the net that deals with thisthis is the buyapplepy code as supplied in ziplines example folderfrom ziplineapi import order record symboldef initializecontext passdef handle datacontext data ordersymbolaapl 10 recordaapldatacurrentsymbolaapl price note this function can be removed if running this algorithm on quantopiancomdef analyzecontextnone resultsnone import matplotlibpyplot as plt plot the portfolio and asset data ax1 pltsubplot211 resultsportfolio valueplotaxax1 ax1set ylabelportfolio value usd ax2 pltsubplot212 sharexax1 resultsaaplplotaxax2 ax2set ylabelaapl price usd show the plot pltgcfset size inches18 8 pltshowdef test args extra arguments to use when ziplines automated tests run this example import pandas as pd return start pdtimestamp20140101 tzutc end pdtimestamp20141101 tzutc editi looked at the code for ingesting the data from yahoo finance and modified it a little to make it take on google finance data the code for the yahoo finance can be found here modulesziplinedatabundlesyahoohtmlthis is my code to ingest google finance sadly it is not working can someone more fluent in python assist meimport osimport numpy as npimport pandas as pdfrom pandas datareaderdata import datareaderimport requestsfrom ziplineutilscli import maybe show progressdef cachpathsymbol type return joinsymbolreplaceospathsep type def google equitiessymbols startnone endnone create a data bundle ingest function from a set of symbols loaded from yahoo parameters symbols iterablestr the ticker symbols to load data for start datetime optional the start date to query for by default this pulls the full history for the calendar end datetime optional the end date to query for by default this pulls the full history for the calendar returns ingest callable the bundle ingest function for the given set of symbols examples this code should be added to ziplineextensionpy codeblock python from ziplinedatabundles import yahoo equities register symbols aapl ibm msft registermy bundle yahoo equitiessymbols notes the sids for each symbol will be the index into the symbols sequence strict this in memory so that we can reiterate over it symbols tuplesymbols def ingestenviron asset db writer minute bar writer unused daily bar writer adjustment writer calendar cache show progress output dir pass these as defaults to make them nonlocal in py2 startstart endend if start is none start calendar0 if end is none end none metadata pddataframenpemptylensymbols dtype start date datetime64ns end date datetime64ns auto close date datetime64ns symbol object def pricing iter sid 0 with maybe show progress symbols show progress labeldownloading google pricing data as it requestssession as session for symbol in it path cachpathsymbol ohlcv try df cachepath except keyerror df cachepath datareader symbol google start end sessionsession sort index the start date is the date of the first trade and the end date is the date of the last trade start date dfindex0 end date dfindex1 the auto close date is the day after the last trade ac date end date pdtimedeltadays1 metadatailocsid start date end date ac date symbol dfrename columns open open high high low low close close volume volume inplacetrue yield sid df sid 1 daily bar writerwrite pricing iter show progresstrue symbol map pdseriesmetadatasymbolindex metadatasymbol asset db writerwriteequitiesmetadata adjustment writerwritesplitspddataframe dividendspddataframe adjustments with maybe show progress symbols show progress labeldownloading google adjustment data as it requestssession as session for symbol in it path cachpathsymbol adjustment try df cachepath except keyerror df cachepath datareader symbol googleactions start end sessionsession sort index dfsid symbol mapsymbol adjustmentsappenddf adj df pdconcatadjustments adj dfindexname date adj dfreset indexinplacetrue splits adj dfadj dfaction split splits splitsrename columnsvalue ratio date effective date splitsdropaction axis1 inplacetrue dividends adj dfadj dfaction dividend dividends dividendsrename columnsvalue amount date ex date dividendsdropaction axis1 inplacetrue we do not have this data in the yahoo dataset dividendsrecord date pdnat dividendsdeclared date pdnat dividendspay date pdnat adjustment writerwritesplitssplits dividendsdividends return ingest,['python'] +1198808,are superscary iterators legal i understand that the standard allows stdvectorint a to have the same type of iterators for different allocators a this is called scary iteratorsnow the question is does the standard allow stdvectorint aiterator be simply a typedef of apointer thus making it just an int for the default allocator or is there some implicit requirement for it to be a separate class type per container if there is no such requirement then why all major implementations including the scary ones do not use this approach it would presumably reduce compiler work even further though now code that overloads on int and vectoriterator will not compile,['c++'] +1198886,why is a sum of strings converted to floats setupconsider the following dataframe note the stringsdf pddataframe3 11 0 2 columnslistabdfdfinfoclass pandascoreframedataframerangeindex 2 entries 0 to 1data columns total 2 columnsa 2 nonnull objectb 2 nonnull objectdtypes object2memory usage 1040 bytesquestioni am going to sum i expect the strings to be concatenateddfsuma 300b 1120dtype float64it looks as though the strings were concatenated then converted to float is there a good reason for this is this a bug anything enlightening will be up voted,['python'] +1199285,multiple underline colors in one anchor i would like to within one anchor a have two different underline colors like soa hrefsomehref spanthis text should underline red on a hoverspan spanthis text should underline grey on a hoverspanai can add textdecoration to each span on hover but this causes each line to hover individually i want it so that when i hover over anywhere in the a both spans underline with their font color inheritedis this possiblenote i am aware of textdecorationcolor but due to limit support i cannot use it,"['html', 'css']" +1199468,rails 5 controller test changes devisetesthelpers is deprecated and will be removed from devise i am working on my first app since i installed rails 5 when i ran my specs for controller actions i got the warning message below even though all my tests were passingdevise including devisetesthelpers is deprecated and will be removed from devise for controller tests please include devisetestcontrollerhelpers insteadso in specrails helperrb i change this lineconfiginclude devisetesthelpers type controllertoconfiginclude devisetestcontrollerhelpersthis change made the warning go away but now the specs for models are failing they were passing before the change how should i fix this thanks,['ruby-on-rails'] +1199641,how to query amount of allocated memory on linux and osx while this might look like a duplicate from other questions let me explain why it is noti am looking to get a specific part of my application to degrade gracefully when a certain memory limit has been reached i could have used criteria based on remaining available physical memory but this wouldnt be safe because the os could start paging out memory used by my application before reaching the criteria which would think there is still some physical memory left and keep allocating etc for the same reason i cannot used the amount of physical memory currently used by the process because as soon as the os would start swapping me out i would keep allocating as the os pages memory so the number would not grow anymorefor this reason i chose a criteria based on the amount of memory allocated by my application ie very close to virtual memory sizethis question how to determine cpu and memory consumption from inside a process provides great ways of querying the amount of virtual memory used by the current process which i thought was what i neededon windows i am using getprocessmemoryinfo and the privateusage field which works greaton linux i tried several things listed below that did not work the reason why virtual memory usage does not work for me is because of something that happens with opencl context creation on nvidia hardware on linux the driver reserves a region of the virtual memory space big enough to hold all ram all swap and all video memory my guess is it does so for unified address space and everything but it also means that the process reports using enormous amounts of memory on my system for instance top will report 233 gb in the virt column 12 gb of ram 6 gb of swap 2 gb of video memory which gives 20 gb reserved by the nvidia driveron osx by using task info and the virtual size field i also get a bigger than expected number a few gb for an app that takes not even close to 1 gb on windows but not as big as linuxso here is the big question how can i get the amount of memory allocated by my application i know that this is a somewhat vague question what does allocated memory means but i am flexiblei would prefer to include the application static data code section and everything but i can live withouti would prefer to include the memory allocated for stacks but i can live withouti would prefer to include the memory used by shared libraries but i can live withouti do not really care for mmap stuff i can do with or without at that pointetcwhat is really important is that the number grows with dynamic allocation new malloc anything and shrinks when the memory is released which i know can be implementationdependentthings i have triedhere are a couple of solutions i have tried andor thought of but that would not work for meread from procselfstatusthis is the approach suggested by howtodeterminecpuandmemoryconsumptionfrominsideaprocess however as stated above this returns the amount of virtual memory which does not work for meread from procselfstatmvery slightly worst according to which refers to linux kernel code the only difference between those two values is that the second one does not substract reserved vm to the amount of virtual memory i would have hoped that reserved vm would include the memory reserved by the opencl driver but it does notuse mallinfo and the uordblks fieldthis does not seem to include all the allocations i am guessing the news are missing since for an 2gb growth in virtual memory space after doing some memoryheavy work and still holding the memory i am only seeing about 01gb growth in the number returned by mallinforead the heap section size from procselfsmapsthis value started at around 336760 kb and peaked at 1019496 kb for work that grew virtual memory space by 2gb and then it never gets down so i am not sure i cannot really rely on this numbermonitor all memory allocations in my applicationyes in an ideal world i would have control over everybody who allocates memory however this is a legacy application using tons of different allocators some mallocs some news some osspecific routines etc there are some plugins that could do whatever they want they could be compiled with a different compiler etc so while this would be great to really control memory this does not work in my contextread the virtual memory size before and after the opencl context initializationwhile this could be a hacky way to solve the problem and i might have to fallback to it i would really wish for a more reliable way to query memory because opencl context could be initialized somewhere out of my control and other similar but nonopencl specific issues could creep in and i wouldnt know about itso that is pretty much all i have got there is one more thing i have not tried yet because it only works on osx but it is to use the approach described in why does mstats and malloc zone statistics not show recovered memory after free ie use malloc get all zones and malloc zone statistics but i think this might be the same problem as mallinfo ie not take all allocations into accountso can anyone suggest a way to query memory usage as vague of a term as this is see above for precision of a given process in linux and also osx even if it is a different method,"['c++', 'c']" +1199744,camera2basic app has very dark preview in android 60 lgg3 the new api perhaps only on lg g3 seems to have something changedi am using the sample codeon my nexus 4 the code runs perfectly but on lgg3 updated to android 60 it does not any ideasi played with the settings but no luck this still works fine on nexus 4mpreviewrequestbuildersetcapturerequestblack level lock falsempreviewrequestbuildersetcapturerequestcontrol awb lock falsempreviewrequestbuildersetcapturerequestcontrol awb mode capturerequestcontrol awb mode autompreviewrequestbuildersetcapturerequestcontrol ae lock falsempreviewrequestbuildersetcapturerequestcontrol ae mode capturerequestcontrol ae mode onmpreviewrequestbuildersetcapturerequestcontrol ae antibanding mode capturerequestcontrol ae antibanding mode autompreviewrequestbuildersetcapturerequestcontrol ae exposure compensation 0mpreviewrequestbuildersetcapturerequestcontrol ae target fps range rangecreate1010mpreviewrequestbuildersetcapturerequestcontrol ae precapture trigger 0mpreviewrequestbuildersetcapturerequestcontrol mode capturerequestcontrol mode autompreviewrequestbuildersetcapturerequestcolor correction mode capturerequestcontrol mode autompreviewrequestbuildersetcapturerequestcontrol capture intent capturerequestcontrol capture intent previewmpreviewrequestbuildersetcapturerequestcontrol af mode capturerequestcontrol af mode continuous picture,['android'] +1199881,how can i extrapolate farther along a road given realtime location data of a moving device over a short period of time how can i get a latlong pair further along this road say 2 miles or even better 5 minutes worth of drivingi see that i can use googles roads api to snap to a road given a latlong pair but that only gets me part way therethis will be in an android app,['android'] +1200155,audio playing from uri inside listview but seekbar is not updating in android listview item i am playing a audio from uri its working fineclicking a button from each listview itemproblem audio is playing in the listview but still seekbar is not movingupdatingedit11audio is playing in the each listview item perfectlybut seekbar is not workingnot updatingplease help me top solve this issuemy listview array adapter classadapterclass private static final int update frequency 500 int progress0 public view getviewfinal int position view view viewgroup parent layoutinflater inflater contextgetlayoutinflater view rowview inflaterinflaterlayoutaudio listview null true listenaudiobutton button rowviewfindviewbyidridlistenaudiobuttonxml seek bar view seekbar rowviewfindviewbyidridseek bar listenaudiobuttonsetonclicklistenernew viewonclicklistener public void onclickview v text shownsettextplaying try try get internet status isinternetpresent cd1isconnectingtointernet check for internet status if isinternetpresent if itemname3 audio filepositionequals itemname3 audio filepositionequalsnull systemoutprintln audio file itemname3 audio fileposition player new mediaplayer playersetaudiostreamtypeaudiomanagerstream music playersetdatasourcecontext uriparseitemname3 audio fileposition playerprepareasync playersetonpreparedlistenernew mediaplayeronpreparedlistener override public void onpreparedmediaplayer mp try mpstart seek bar viewsetmaxplayergetduration updateposition catch exception e eprintstacktrace playersetoncompletionlistenernew mediaplayeroncompletionlistener override public void oncompletionmediaplayer mp stopplay mediaplayeronerrorlistener onerror new mediaplayeronerrorlistener override public boolean onerrormediaplayer mp int what int extra returning false will call the oncompletionlistener return false else toastmaketextgetcontext audio not found toastlength shortshow else toastmaketextgetcontext please check your internet connection toastlength shortshow catch exception e eprintstacktrace toastmaketextgetcontext audio not found toastlength shortshow catch exception e eprintstacktrace return rowview private void stopplay playerstop playerreset playbuttonsetimageresourceandroidrdrawableic media play handlerremovecallbacksupdatepositionrunnable seek bar viewsetprogress0 isstarted false private final handler handler new handler private final runnable updatepositionrunnable new runnable public void run updateposition private void updateposition handlerremovecallbacksupdatepositionrunnable seek bar viewsetprogressprogressprogressgetprogresspercentageplayergetcurrentpositionplayergetduration notifydatasetchanged handlerpostdelayedupdatepositionrunnable update frequency,['android'] +1200573,explicit loading nm with filtering i am trying to filter the results from an explicit load in entityframeworkthe explicit loading works when i do not apply any filter but it does not load results once the filter is appliedclassespublic partial class student public int studentid get set public int courseid get set public string name get set public string status get set public virtual icollectiongrade grades get set public partial class grade public int gradeid get set public string value get set public string status get set public virtual icollectionstudent students get set fluent api mappingmodelbuilderentitygrade hasmanye estudents withmanyx xgrades mapm mtotablestudentgradesmapleftkeygradeidmaprightkeystudentidusagethis works and populates the studentgrades propertyusing var context new model1 contextconfigurationlazyloadingenabled false var student contextstudentssinglex xstudentid 1 contextentrystudentcollectionx xgradesloadthe sql that is generated looks like thisselect extent2gradeid as gradeid extent2value as value extent2status as statusfrom dbostudentgrades as extent1inner join dbogrades as extent2 on extent1gradeid extent2gradeidwhere extent1studentid 1 this is parameterized in the actual hitwhen i run this query i get the full resultshowever when i apply filtering and use the following line it does not populate studentgradescontextentrystudentcollectionx xgradesquerywherex xstatus aloadthis line generates this queryselect extent2gradeid as gradeid extent2value as value extent2status as statusfrom dbostudentgrades as extent1inner join dbogrades as extent2 on extent1gradeid extent2gradeidwhere extent1studentid 1 and a extent2statusthe 1 is parameterized in the actual hitwhen i run this manually against the db i get the correctly filtered results within sql server the problem is that this does not populate studentgrades in the c object,['c#'] +1200618,bootstrap3 css style input i am trying to make a search field with a dropdown inside i have been trying to use bootstraps input group to give the illusion that the button is inside the fieldthis is what i am trying to accomplish in the screenshot belowthis is what i have so fari am trying to figure out how to get the dropdown menu to move over to the far right of the search field and get that carrot to show as wellany tips on adjusting the position of the menu as well as making that dropdown button have no color on hoverdiv classcontainer divcntr div classformgroup div classinputgroup input typetext classformcontrol inputlg idtoolsearch nametoolsearch placeholderwhat are you looking for div classinputgroupbtn button ariaexpandedfalse ariahaspopuptrue datatoggledropdown classbtn btndefault btnlg dropdowntoggle filteroptions typebutton span classcaretspan span clasronlytoggle dropdownspan button ul classdropdownmenu lia href clasmall datavalueoption1 tabindex1input typecheckboxnbspoption 1ali lia href clasmall datavalueoption2 tabindex1input typecheckboxnbspoption 2ali ul div div br button typebutton classbtn btndefault btnlgsearchbutton divdivdivcntr left 50 marginleft 350px margintop 150px minheight 150px position absolute textalign center top 50 width 700pxfilteroptions borderleft 0pxbtnlg lineheight 122toolsearchfocus outlinenonehere is a fiddle i have set up,['css'] +1200717,python filter does not work i have an algorithm that can generate a prime list as a generatordef odd iter n3 while true yield n nn2def not divisiblen return lambda x x and 0def primes yield 2 l odd iter while true nnextl yield n lfilter not divisiblen lx1for t in primes printt xx1 if x10 breakbut if i put the lambda function into the filter function directly like belowdef primes yield 2 l odd iter while true nnextl yield n lfilterlambda x xn0 li can get only an odd list not a prime list it seems the filter function does not workwhat can i do,['python'] +1201049,namespaces for net jwt token validation system vs microsoft i am trying to use jwt to authenticate a node application to an aspnet web apiin aspnet i am using net 451 and nuget package systemidentitymodeltokensjwt 500what i do not understand is why the namespaces are mixed between microsoft and system for examplevar tokenreader new jwtsecuritytokenhandlertokenreadervalidatetokentoken new tokenvalidationparameters validateaudience false out validatedtoken the main jwtsecuritytokenhandler is in the systemidentitymodeltokensjwt namespace but the tokenvalidationparameters class and its dependencies are in the microsoftidentitymodeltokens namespace and possibly collide with similar classes in the systemidentitymodeltokens namespaceis this by design or is this a possible sign of a version mismatch somewhere else,"['c#', 'asp.net']" +1201250,does short circuiting make execution of the program faster and is analysing which statement to put first in the condition statement worth it for instance lets say we are talking about c if that makes a differncein an operator if i know that one statement will result to 0 more oftenhas a higher chance then the other statement should i put that on the left side and the other statement on the rightsame goes for operator if i know that one statement will result to 1 more oftenhas a higher chance then the other statement should i put that on the left side and the other statement on the rightnow doing all this would cause a lot of time analysing the program but if this does speed up execution time for the program is it worth doing it and is this something that embeddedrealtime system programmers look into to speeding up their application if necessary,['c++'] +1201449,why should i ever overload methods i found two examples in my book of overloading methods but it does not explain clearly exactly why it is usefulpackage keepopublic class main public static void mainstring args int newscore calculatescoretim 500 systemoutprintlnnew score is newscore calculatescore75 public static int calculatescorestring playername int score systemoutprintlnplayer playername has score score return score 10 public static int calculatescoreint score systemoutprintlnunnamed player scored score points return score 10 this is pretty straightforward but honestly it seems pretty useless to method overload here and it seems just doing it for the sake of doing itthe next example in the book does method overloading which seems a bit more useful because that program calculates feet to centimeters and there is one method where you can put in feet and inches and one method where you can put inches however it still seems just as easy to make two separate methods for thisthat being said are there any real benefits to doing this i read this but i am not really to satisfied it seems just as easy to make new methods,['java'] +1201835,errorcould not find property assembledebug on project app i am using comandroidtoolsbuildgradle220alpha6 and android studio 22 preview 6 the build runs perfectly fine on gradle 210 but to enable instant run it asks me to update gradle pluginon updating gradle plugin the build shows errorcould not find property assembledebug on project app i already tried cleaning gradle and idea and reloading the project but nothing worksplease help,['android'] +1202419,command failed tar xzf androidsdk r20linuxtgz i was trying to build kivy app to android and got this error check configuration tokens ensure build layout check configuration tokens preparing build check requirements for android install platform apache ant found at homealibuildozerandroidplatformapacheant194 android sdk is missing downloading unpacking android sdk command failed tar xzf androidsdk r20linuxtgz buildozer failed to execute the last command if the error is not obvious please raise the log level to 2 and retry the latest command in case of a bug report please add a full log with log level 2command buildozer android new debuglogwant any details request in the comments,"['android', 'python']" +1202760,can division by nonzero still create a nan infinity i have a number which might be zeros i divide by that number so i want to test if it is zero to prevent nans and infinitys is it possible that i still create nans infinity because of rounding errors within the division double x might be zerodouble yifx 0 return y xeditthanks for the responses i will add some subquestions then1 assuming neither x nor y is nan inf or inf would a division that results in inf inf result in more cpu cycles or any other unwanted behaviour could it crash 2 is there a way to prevent the division from resulting in infinity using offsets and so on,['c++'] +1202942,python npmean giving wrong means the issueso i have 50 netcdf4 data files that contain decades of monthly temperature predictions on a global grid i am using npmean to make an ensemble average of all 50 data files together while preserving time length spatial scale but npmean gives me two different answers the first time i run its block of code it gives me a number that when averaged over latitude longitude plotted against the individual runs is slightly lower than what the ensemble mean should be if i rerun the block it gives me a different mean which looks correctthe codei cannot copy every line here since it is long but heres what i do for each runhistorical 19502020 datancin 1 datasetprojectwcaar5canesm2monthlyhistr1tas amon canesm2 historicalr1 r1i1p1 195001202012nc import data filetash1 ncin 1variablestas extract tas temperature variablencin 1close close to save memoryrepeat for future 20212100 datancin 1 datasetprojectwcaar5canesm2monthlyhistr1tas amon canesm2 historicalr1 r1i1p1 202101210012nctasr1 ncin 1variablestasncin 1closeconcatenate historical future files together to make one time series arraytas11 npconcatenatetash1tasr1axis0subtract the 19501979 mean to obtain anomaliestas11 tas11 npmeantas110359axis0dtypenpfloat64and i repeat that 49 times more for other datasets each tas11 tas12 etc file has the shape 1812 64 128 corresponding to time length in months latitude and longitudeto get the ensemble mean i do the followingmove all tas data to one arrayalltas npzeros18126412851 years lat lon members no ensemble mean value yetalltas0 tas11alltas49 tas50calculate ensemble mean fill into 51st slot in axis 3alltas50 npmeanalltasaxis3dtypenpfloat64when i check a coordinate month the ensemble mean is off from what it should be heres what a plot of globally averaged temperatures from 19502100 looks like with the first mean with monhly values averaged into annual values black line is ensemble mean colored lines are individual runsobviously that deviated below the real ensemble mean heres what the plot looks like when i run alltas50npmeanalltasaxis3dtypenpfloat64 a second time keep everything else the samemuch betterthe questionwhy does npmean calculate the wrong value the first time i tried specifying the data type as a float when using npmean like in this question wrong numpy mean valuebut it did not work any way i can fix it so it works correctly the first time i do not want this problem to occur on a calculation where it is not so easy to notice a math error,['python'] +1203020,3 or more consecutive layout passes to prepare to be shown error when i open an nspopover i am getting the following error warning nspopover 0x6180120780 needed 3 or more consecutive layoutpasses to prepare to be shown verify that nothing in your view hierarchyis aggressively dirtying layout during layout as this will likelycause problems elsewherethis has only just started appearing in a recent build and i can not find what is causing it i have removed all prep code before the popover is shown so it basically calls ibactionaddclickedidsender self addpopover showrelativetorectsender bounds ofviewsender preferrededgensmaxyedgei have removed all constraints from the window in ib too so i should not be doing anything during layout that requires a repaint searching the web comes up with very little info what i could find anyway my popover is used for a form input so has 4 nstextfields an nsoutlineview and an nsimage it also creates a hidden webview which is not visible to the user and used for server processingosx 107any ideasthanksgeoff,['objective-c'] +1203211,box flip 3d animation for side menu i have scrollview and inside scrollview i have 2 views as mainview and another as sidemenuviewwhat i want to make animation like belowany idea what needs to be done to get this working,"['ios', 'objective-c']" +1203219,scala jar read external properties file i have written some code and exported it as a jar file in this jar there is a file named automationproperties with defaults that i am loading usingval automationpropertiesfileurl getclassgetresourceautomationproperties if automationpropertiesfileurl null val source sourcefromurlautomationpropertiesfileurl config new properties configloadsourcebufferedreader but when this jar file gets added as a gradle dependency in cuserabcgradle and i want to read automationproperties from my current project how can i override the location and read the file from my project and not from the jar file itself,['java'] +1203425,fade out div as it is dragged near another div i have a draggable div that can be dropped into a droppable div this works fine the draggable div contains a span element i would like this span element to fade out as it approaches the droppable divi have a draggable fadeoutin example based on another answer which applies to when you drag the element to the side of the window i tried modifying this to fit my needs but it does not sem to be working for some reasondrag the red sqaure to the right handside you will notice it fades inout as you drag itdemo fiddle draggabledraggable drag functionevent ui consoleloguihelperfindspan uihelperfindspancssopacity 1 uipositionleft windowwidth my attempt of modifying this to have the behaviour explained abovedemo draggabledraggable drag functionevent ui consoleloguihelperfindspan el droppableblue var bottom elpositiontop elouterheighttrue var span uihelperfindspan spancssopacity 1 spantop bottom,"['javascript', 'jquery']" +1203490,file system changes in android nougat ever since the first release of the android and developer preview i get permission denied errors when attempting to list the root directory or other system directories the permissions on these directories did not seem to change as far as i can tellquestionwhat changes in android and caused these permission denied errorshow to replicatein adb shell run the following commandsrunas comdebuggablepackagenamels this gives permission denied errors on android nwhy list system directoriesi noticed this behavior on android and with several file managers they could no longer list the root directory or other system files this also is limiting the output of running ps in a shell the changes also caused this library to stop working on android n,['android'] +1203771,how can i overload the new operator for multiple heaps in an embedded system with two separate ram memory areas i have two thistinct heaps one is a custom implementation from freertos in the lower memory area another is the heap generated by gcc in the upper memory area and i would like to be able to choose which heap new uses,['c++'] +1203909,can memcpy be used for type punning this is a quote from the c11 standard65 expressions6 the effective type of an object for an access to its stored value is the declared type of the object if any if a value is stored into an object having no declared type through an lvalue having a type that is not a character type then the type of the lvalue becomes the effective type of the object for that access and for subsequent accesses that do not modify the stored value if a value is copied into an object having no declared type using memcpy or memmove or is copied as an array of character type then the effective type of the modified object for that access and for subsequent accesses that do not modify the value is the effective type of the object from which the value is copied if it has one for all other accesses to an object having no declared type the effective type of the object is simply the type of the lvalue used for the access7 an object shall have its stored value accessed only by an lvalue expression that has one of the following typesa a type compatible with the effective type of the objecta a qualified version of a type compatible with the effective type of the objecta a type that is the signed or unsigned type corresponding to the effective type of the objecta a type that is the signed or unsigned type corresponding to a qualified version of the effective type of the objecta an aggregate or union type that includes one of the aforementioned types among its members including recursively a member of a subaggregate or contained union ora a character typedoes this imply that memcpy cannot be used for type punning this waydouble d 12345678uint64 t bitsmemcpybits d sizeof bitsprintfthe representation of g is 08prix64n d bitswhy would it not give the same output asunion double d uint64 t i uud 12345678printfthe representation of g is 08prix64n d uiwhat if i use my version of memcpy using character typesvoid my memcpyvoid dst const void src size t n unsigned char d dst const unsigned char s src for size t i 0 i n i di si return dstedit eof commented that the part about memcpy in paragraph 6 does not apply in this situation since uint64 t bits has a declared type i agree but unfortunately this does not help answer the question whether memcpy can be used for type punning it just makes paragraph 6 irrelevant to assess the validity of the above exampleshere here is another attempt at type punning with memcpy that i believe would be covered by paragraph 6double d 12345678void p mallocsizeofdoubleif p null uint64 t pbits memcpyp d sizeofdouble uint64 t bits pbits printfthe representation of g is 08prix64n d bitsassuming sizeofdouble sizeofuint64 t does the above code have defined behavior under paragraph 6 and 7edit some answers point to the potential for undefined behavior coming from reading a trap representation this is not relevant as the c standard explicitly excludes this possibility72011 exactwidth integer types1 the typedef name intn t designates a signed integer type with width n no padding bits and a twoas complement representation thus int8 t denotes such a signed integer type with a width of exactly 8 bits2 the typedef name uintn t designates an unsigned integer type with width n and no padding bits thus uint24 t denotes such an unsigned integer type with a width of exactly 24 bitsthese types are optional however if an implementation provides integer types with widths of 8 16 32 or 64 bits no padding bits and for the signed types that have a twoas complement representation it shall define the corresponding typedef namestype uint64 t has exactly 64 value bits and no padding bits thus there cannot be any trap representations,['c'] +1204363,ado recordset data not showing on form i have got a frustrating issue on ms access 2010 that i would at this stage qualify as a bug and after having tried all possible workarounds i am out of ideas and rely on youcontexthuge ms access 2010 application with 25k lines of vba and 50 forms it has a client server architecture with a frontend compiled and an access backend on the network it makes connections to a twentish of different databases oraclesql serversybase iqthe problemsometimes when i assign an adodb recordset to a subform its data is not shown in bound fields i have got name everywherethe data is there i can debugprint it i can see it in the watches browser i can read or manipulate it while looping on the recordset object with code it just not appear in the subformit can work flawlessly during months and suddenly one form will start having this issue without any apparent reason it might happen even on forms that i have not changed when it happens it does for all users so this is really something wrong in the frontend accdbaccdethe issue is not related to a specific dbmsdriver it can happen with oracle or sybase datai have created my own class abstracting everything related to ado connections and queries and use the same technique everywhere i have got several tenth of forms based on it and most of them works perfectlyi have this issue in several parts of my application and especially in a highly complicated form with lots of subforms and codeon this main form a few subforms have the issue while others do not and they have the exact same parametersthe codethis is how i populate a forms recordset set rst nothing set rst new adodbrecordset set rst oracle conqueryrssql if not rst is nothing then set rstactiveconnection nothing set form the form namerecordset rst end ifthe code called with oracle conqueryrssql ispublic function queryrsbyval sql as string optional strtitle as string as adodbrecordset dim dbquery as adodbcommand dim output as adodbrecordset dim dttemp as date dim strerrnumber as long dim strerrdesc as string dim intseconds as long dim param as variant if dbconstate adstateopen then set queryrs nothing else docmdhourglass true plastrows 0 plastsql sql plasterror plastseconds 0 set dbquery new adodbcommand dbqueryactiveconnection dbcon dbquerycommandtext sql dbquerycommandtimeout ptimeout set output new adodbrecordset logit sql strtitle dttemp now on error goto query error with output locktype adlockpessimistic cursortype aduseclient cursorlocation aduseclient open dbquery end with intseconds datediffs dttemp now if outputeof then logit formatnow hhnnss executed in intseconds second iifintseconds 1 s now rows returned set queryrs nothing else outputmovelast plastrows outputrecordcount logit formatnow hhnnss executed in intseconds second iifintseconds 1 s outputrecordcount row iifoutputrecordcount 1 s returned outputmovefirst set queryrs output end if end ifexit sub plastseconds intseconds set output nothing set parameter nothing set dbquery nothing docmdhourglass false exit functionquery error intseconds datediffs dttemp now strerrnumber errnumber strerrdesc errdescription plasterror strerrdesc msgbox strerrdesc vbcritical error pdsn logit strerrdesc error set queryrs nothing resume exit sub resumeend functionthings i tried so farfor the recordsets i tried every possible variation of locktype adlockpessimistic cursortype aduseclient cursorlocation aduseclientthe subforms handling the recordsets have all a snapshot recordsettype problem remains if i try dynaset dataentry addition deletion edits are all thisabled it is pure readonlyi have a habit of thisconnecting the recordsets using rstactiveconnection nothing so i can manipulate them afterwards but this does not impact the problem eitherit can happens with very simple queries with only one field in the select clause and only one field bound to it on a subformreimporting all objects in a fresh accdb does not solve the problem eitherthe solution proposed by random answer guy worked at first glance which accreditate the bug hypothesis unfortunately my problems reappeared after some totaly unrelated changes in the main form i am back with 4 or 5 subforms not showing data and addingremoving a load event on all or part of them does not make any difference anymoreif you want more information about how weird is this issue i advise you to read my comment on random answer guys answerto concludewhat is extremely frustrating is that i can have 2 different forms with exactly the same properties and same fields same sql instruction over the same db same recordset management code one is showing the data and the other does not when the problem happens i have no other choice than erasing all objects manipulated and reimporting them from an older version or recreate them from scratchif this is not a bug i am still looking for the proper word to qualify it does anyone ever experienced the issue and has an explanation andor a workaround to propose,['sql'] +1204505,apache2 and context path for virtual host with django and angularjs i had the following working django configurationwsgiscriptalias mydjangoprojectfoldermydjangoprojectwsgipywsgipythonpath mydjangoprojectfolderdirectory mydjangoprojectfoldermydjangoproject files wsgipy order denyallow require all granted filesdirectoryalias base context pathstatic mydjangoprojectfolderstaticdirectory mydjangoprojectfolderstatic require all granteddirectorydjango responds on ipbase context pathrest for rest apis invoked by the frontend and ipbase context pathadmin for administration which uses base context pathstaticso everything needed by django is on ipbase context pathnow i need to deploy a website developed in angular on this same apache2 so i am trying to understand how to make it work i have a domain name for this website mydomainnameorg but not a dedicated one for the django application when visiting my domain name i would expect my website to appearthis is my attempt for my websitevirtualhost 80 servername mydomainnameorg documentroot mywebsitefolder directoryindex indexhtml directory mywebsitefolder redirect rules for managing angularjs directoryvirtualhostit does not work 403for my django application this is the virtual host i created which does not work as well 403virtualhost 80servername mydomainnamealias base context pathstatic mydjangoprojectfolderstaticwsgiscriptalias mydjangoprojectfoldermydjangoprojectwsgipywsgidaemonprocess mydjangoproject pythonpathmydjangoprojectfolderusrlocallibpython27sitepackageswsgiprocessgroup mydjangoprojectdirectory mydjangoprojectfolderstatic options indexes require all granteddirectoryso i am kind of stuck,['python'] +1205521,what is the difference between an array and an observable array in typescript what is the main difference between any and observableanywhat are the cons and pros of using each of them,['javascript'] +1205596,table legend with header in matplotlib i would like to make a complex legend in matplotlib i made the following codeimport matplotlibpylab as pltimport numpy as npn 25y nprandomrandnnx nparangeny2 nprandomrandn25 serie ap1a pltplotx y ro ms10 mfcr mew2 mecrp1b pltplotx5 y5 w ms10 mecw mew2 p1c pltplotx510 y510 w ms10 mecw mew2 serie bp2a pltplotx y2 bo ms10 mfcb mew2 mecbp2b pltplotx1520 y21520 w ms10 mecw mew2 p2c pltplotx1015 y21015 w ms10 mecw mew2 pltlegendp1a p2a p1a p1b p2ap2b p1a p1c p2ap2c no prop no prop prop prop prop prop ncol3 numpoints1pltshowit produces plot like thatbut i would like to plot complex legend like herei also tried to do the legend with table function but i can not put a patch object into the table to a proper position of a cell,['python'] +1205620,issue setting cabasicanimation delegate in swift 3 i am getting the following errorcannot assign value of type starbutton to type caanimationdelegateon the last line of this cabasicanimation block let fillcircle cabasicanimationkeypath opacity fillcircletovalue 0 fillcircleduration 03 fillcirclesetvaluenotfavoritekey forkey starkey fillcircledelegate self this is where the error is thrownself is a custom uibutton class this was not an issue in previous versions of swift any suggestions on a solutionupdatehere is a downloadable link to the source file for the starbutton class for best reference,['ios'] +1205648,why does numpy least squares result diverge from using the direct formula i want to calculate the least squares estimate for given datathere are a few ways to do this one is to use numpys least squaresimport numpynplinalglstsqxy0where x is a matrix and y a vector of compatible dimension type float64 second way is to calculate the result directly using the formulaimport numpynumpylinalginvxtdotxdotxtdotymy problem there are cases where the different formulas give radically different results although there may be no difference sometimes the coefficients grow to be extremely large using one formula while the other is much more well behaved the formulas are the same so why can the results diverge so much is this some type of rounding error and how do i minimize it,['python'] +1205822,nested loops unrolling using metaprogramming i have a number of nested loops with small sizes i j known at compile time eg forint i 0 i i i forint j 0 j j j do sth with ij i need to unroll the loops using the sizes i j in such a way that i can use each coordinate combination at compile time to clarify consider the following structure and take 2 nested loops with sizes i 2 j 3templateint istruct c static void f do sth i can not use the indices i j similar to above to index the structure c since they are not known at compile time however what i would like to generate is exactly what would have been the case had i been allowed to use the indices egc00fc01fc02fc10fc11fc12fi am not particularly concerned with the order of call generations as long as all combinations are produced the generation mechanism should generalize to arbitrary number of nested loops,['c++'] +1205900,java null arguments when chaining constructors let us say i have a class with multiple constructors one of which is a copyconstructor to copy an objectpublic class rectangle int width height public rectangleint width int height thiswidth width thisheight height public rectanglerectangle source thissourcewidth sourceheight is there any way i can make check if source is null in the copyconstructor and throw an illegalargumentexception if it is because the other constructor call has to be the first statement in my constructor,['java'] +1205937,datepickerpopup formatting not working when value set initially in scope i am using the angular ui bootstrap date picker popup using this custom directive on plunker modulevar usermodule angularmoduleusermoduleuibootstrapcontrollerusermodulecontrollersamplecontroller scope function scope scopemindate new datedirective codeusermoduledirectivedatepicker function datefilter return restrict e require ngmodel scope ngmodel ngreadonly mindate maxdate dtprequired dateoptions template p classinputgroup input typetext stylecursorpointer classformcontrol datepickerpopupformat ngmodelngmodel isopenopened mindatemindate maxdatemaxdate datepickeroptionsdateoptions datethisabledthisableddate mode ngrequireddtprequired closetextclose ngreadonlyngreadonly ngclickopenpopup span classinputgroupbtn button typebutton classbtn btndefault ngclickopenpopupevent i classfa facalendaributton span p controller function scope check if it was defined if not set a default scopedateoptions scopedateoptions formatyear yy startingday 1 showweeks false scopeopenpopup function event if event undefined eventstoppropagation scopeopened true scopeformat dd m y link function scope element attrs controller remove the default formatter from the input directive to prevent conflict controllerformattersshift this is working fine and the date is formatted fine when selecting a date from the calendar popup however if i set a date of the ngmodel in the controller the date is not formatted as dd m y and is returned as a date string like sat oct 01 2016 010 gmt0100 gmt daylight time however in the plunker i am able to set a date in the controller and it is formatted fine here is my html for the date pickerdatepicker ngmodelstartdatevalue datepickeroptionsdateoptions mindatemindate ngreadonlytruedatepickerin my controller startdatevalue new datei am not sure where the problem could be the image below shows what i am getting back,"['javascript', 'html']" +1206018,changing iterable variable during loop let it be an iterable element in pythonin what cases is a change of it inside a loop over it reflected or more straightforward when does something like this workit range6for i in it itremovei1 print ileads to 024 being printed showing the loop runs 3 timeson the other hand does it range6for i in it it it2 print itlead to the output012301showing the loop runs 6 times i guess it has something to do with inplace operations or variable scope but cannot wrap my head around it 100 sureclearification one example that does not workit range6for i in it it itremovei1 print itleads to none being printed and an error nonetype has no attribute remove to be thrown,['python'] +1206384,c11 reinterpreting array of structs as array of structs member consider the following typestruct s char vgiven an array of const s is it possible to in a standard conformant way reinterpret it as an array of const char whose elements correspond to the value of the member v for each of the original arrays elements and viceversa for exampleconst s a1 a 4 2 0 const char a2 reinterpret cast const char a1for int i 0 i 4 i stdcout stdboolalpha a1iv a2i is the code above portable and would it print true true true true if not is there any other way of achieving thisobviously it is possible to create a new array and initialize it with the member v of each element of the original array but the whole idea is to avoid creating a new array,['c++'] +1206455,is it bad practice to use the same method for save and update i am using laravel but it is not important when you create a controller with laravel command line tool it puts 4 default function in there for create and updatecreate and store for saveedit and update for well updatethis is what laravel suggest for shop controllerclass shopcontroller extends controller public function create return create view public function storerequest request save a shop public function editid find a shop return edit view public function updaterequest request id find the shop with id update the shop but i like to use the same methods for showing view and storeupdate my row and avoid writing lots of extra codeclass shopcontroller extends controller public function createid 0 return viewshopcreate edit shopfindid public function storerequest request id 0 whitelist titlerequired phonepresentnumeric addresspresent thisvalidaterequest whitelist shop shopfindornewid find a shop with given id or create a new shop instance foreachwhitelist as kv shopk requestk shopsave naturally i go with what i like second option but since laravel suggest the first way just out of curiosity is there any reason why i should not do it like this is this considered bad practice in any way,['php'] +1206748,will params in c always cause a new array to be allocated on every call cnet has variadic function parameters by passing an array type byreference as opposed to cc which just places all of the values directly on the stack for better and for worsein the c world this has a neat advantage of allowing you to call the same function with either raw arguments or a reusable array instancestring formatted0 stringformat cultureinfoinvariantculture 0 1 2 1 2 3 int32 third 3string formatted0 stringformat cultureinfoinvariantculture 0 1 2 1 2 third int32 values new int32 1 2 3 string formatted1 stringformat cultureinfoinvariantculture 0 1 2 values this means that the generated cil is equivalent tostring formatted0 stringformat cultureinfoinvariantculture 0 1 2 new object 1 2 3 int32 third 3string formatted0 stringformat cultureinfoinvariantculture 0 1 2 new object 1 2 third int32 values new int32 1 2 3 string formatted1 stringformat cultureinfoinvariantculture 0 1 2 values which means that in a nonoptimizing jit compiler every call will allocate a new object instance though in the third example youre able to store the array as a field or other reusable value to eliminate the new allocation on every call to stringformatbut in the official clr runtime and jit are any optimizations done to eliminate this allocation or perhaps is the array tagged specially so that it will be deallocated as soon as execution leaves the scope of the callsiteor perhaps because the c or jit compiler knows the number of arguments when used raw could it do the same thing as the stackalloc keyword and place the array on the stack and thus not need to deallocate it,"['c#', '.net']" +1207318,thisplay all tables describelike functionality how can i thisplay all tables in a database similar to the output like describe mytable adding functionality forall tables at oncetablesize character set and collation information sort capabilitiesnote describe output is simple and for a single table at a timeeditnice feedback from rick james i was at a loss and needed that brainstormif anyone wants to add functionality to my selfanswer such as an indented row at the bottom of each table for indexes perhaps 1 line per index showing name and column names separated by a commacardinality on that index line aboveforeign key constraints anything else in arms reach your peers might find usefulhave this whole block called extended info conceptually and a switch a parameter for yay or nay for producing it if n then do not produce iti would be most pleased naturally that information would not hang under the column headers already shown in the selfanswer below by me so some visual like an indentation is what immediately comes to mind not having it exactly part of the table rough output is fineconsider the following as rough notes that may be of assistancecreate schema x99use x99create table parent assume your have only one parent ok bad example it is early id int auto increment primary key fullname varchar100 not nullengineinnodb drop table childcreate table child id int auto increment primary key fullname varchar100 not null myparent int not null constraint mommy daddy foreign key myparent references parentid on delete cascade on update cascade engineinnodbcreate table t3 id int auto increment primary key myd date not null myi int not null key t3 001 mydmyicreate table t4 somecode char4 primary key codedescr varchar500 not nullcreate table t5 id int auto increment primary key thecode char4 not null d1 date not null i1 int not null someother datetime not null foreign key cd 2 t4 thecode references t4somecode foreign key cd 2 t3 d1i1 references t3mydmyi the below 2 lines are merely to show cardinality which i am sure is read from info schema tooshow indexes in child to pick up cardinality or from info schemashow indexes in t5 ditto so i am not suggesting to actually call show indexes james goatcherselect concat table name column name referenced table name referenced column name as list of fks from information schemakey column usage where referenced table schema x99 and referenced table name is not null order by table name column name list of fks childmyparent parentid t5d1 t3myd t5i1 t3myi t5thecode t4somecode despite the output suggested by james goatcher on that webpage perhaps what would look better under table t5 as 2 linest5d1i1 t3mydmyi that there would be swellt5thecode t4somecode you may make the assumption that all tables are in the same schema if they are not and it blows up that is finedrop schema x99i would like to award this bounty,['mysql'] +1207458,how to traverse through all possible paths to a solution and pick the optimum path i am not good at programmatically implementing a heuristic search algorithm dijkstras algorithm a search algorithm mentioned however while solving a problem mentioned in one of my post matrix manipulation logic not fetching correct answer for higher order nxn matrix data i found a flaw in my approach to solve the problem the problem statement is as belowproblem statementthere is a nxn matrixdivided into and and cells each cell has a predefined value which would be given as an input iteration has to happen k number of times which is also given in the test input we have to make sure that we pick the optimummin value of rowscolumns at each iteration final output is the cumulative sum of optimum value saved at the end of each iterationsteps 1 sum up the individual row and column and find the min sum of rows and columns it could be a row or a column just need the minimum row or a columnstep 2 store the sum found above separatelystep 3 increment elements of the min sum row or column by 1repeat steps 123 from 1 to kth valueadd the sum at each iterationspecified in step2output is the sum obtained on on the kth iterationsample data2 4 input data nk1 3 matrix first row2 4 matrix second rowoutput data22my codevoid matrixmanipulation throws ioexception int and readernextint int matrix new intnn int k readernextint for int i 0 i n i for int j 0 j n j matrixij readernextint int row new intn int row clone new intn int col new intn int col clone new intn int test 0 for int kk 0 kk k kk row calculatesumcalculaterowsummatrix n row clone rowclone col calculatesumcalculatecolsummatrix n col clone colclone arrayssortcol arrayssortrow int pick 0 boolean rowflag false int rownumber 0 int colnumber 0 if row0 col0 pick row0 value rowflag true for int i 0 i n i if pick row clonei rownumber i else if row0 col0 pick col0 value rowflag false for int i 0 i n i if pick col clonei colnumber i else ifrow0 col0 pick col0 rowflag false for int i 0 i n i if pick col clonei colnumber i test test pick if rowflag matrix rowupdatematrix n rownumber else matrix columnupdatematrix n colnumber systemoutprintlntest issue with my codethis solution was working for some lower order matrix and simple scenarios however when i tried test cases that involved 100x100 sized matrix many test cases failed initially i thought it was some memory issuestack overflow when the array size increases but now i have worked out that it is a flaw in the code that i am not able to anticipate the correct path that would eventually guides me to the optimum solution i would like to achieve the flaw that i found in my code is say in one scenario when the optimum value from both rows and columns is equal i am free to choose row or column however the problem here is say if i go with row first it may update the values of row to some nonoptimum value i believe only i would know all the optimum paths beforehand would help me get the correct answerany help in this regard would be highly appreciatedthis question has a reference to question asked here matrix manipulation logic not fetching correct answer for higher order nxn matrix dataonly when higher order matrix is used i get the below difference in output when i apply the above approachedit output expected output 1 5499 1 5499 2 30050 2 30050 3 50778 3 50708 4 36589 4 36509 5 19259 5 19259 6 21367 6 21367 case 3 my output was 50778 and the expected was 50708case 2 sample data below my output was 30066 and the expected was 30050100 575 6 5 10 6 3 9 2 4 7 6 6 8 6 5 6 1 6 9 1 6 8 3 7 3 2 4 8 7 8 3 6 3 9 4 2 1 8 5 5 1 5 8 6 6 10 5 3 4 7 3 3 10 10 3 1 7 3 8 4 4 9 3 7 6 7 9 3 2 2 2 4 8 9 8 1 10 6 6 10 7 5 5 7 9 8 3 2 3 3 9 6 3 7 5 5 10 3 3 37 6 2 3 8 8 3 10 1 8 4 7 5 2 9 5 3 5 4 6 4 10 1 6 1 5 1 6 4 9 6 4 10 1 2 4 8 10 5 9 1 9 1 9 3 10 9 9 6 5 6 5 9 4 1 4 9 8 6 9 1 3 1 4 9 2 3 4 1 6 4 1 1 8 2 5 10 1 1 10 7 8 7 3 9 3 10 3 10 5 8 3 7 9 10 5 7 3 2 34 5 4 6 9 6 6 3 6 3 2 4 9 3 3 6 10 6 3 6 7 7 9 8 9 3 6 6 3 4 9 6 2 5 9 9 9 1 5 1 7 4 9 7 10 3 1 8 1 9 9 3 1 4 6 1 8 10 3 1 10 5 9 4 3 6 8 8 1 3 5 9 1 9 9 4 3 5 1 7 1 1 9 2 1 9 7 4 7 8 7 3 3 9 6 9 10 7 10 52 9 4 3 4 5 6 8 5 5 8 2 3 2 1 2 5 1 10 6 5 6 6 8 4 8 3 6 6 3 3 1 6 3 3 7 6 4 2 7 1 5 9 8 9 5 8 8 10 8 8 8 10 7 3 1 8 6 7 2 2 5 9 8 10 10 10 3 2 6 8 9 6 10 6 10 5 10 9 7 6 4 5 6 4 8 7 10 3 5 9 1 5 7 5 5 9 9 3 1010 2 1 8 2 2 7 3 6 8 10 8 4 1 3 9 3 8 4 8 7 5 4 1 5 3 2 1 6 3 8 8 8 9 10 4 8 10 9 1 4 1 5 5 9 2 1 2 4 1 3 7 5 8 7 2 5 1 2 2 5 4 4 2 3 2 9 6 5 3 6 5 2 6 9 3 4 7 9 4 1 8 5 10 3 1 3 6 8 8 6 3 1 4 8 6 2 6 6 12 7 3 9 10 8 5 8 1 1 7 6 2 3 4 1 2 3 9 2 2 1 2 2 7 10 8 4 4 9 9 6 3 9 9 4 8 2 5 3 1 2 9 1 2 3 1 9 4 7 7 1 10 8 9 9 6 7 5 2 8 3 1 1 7 4 8 7 10 9 10 7 9 4 10 8 4 10 1 1 10 2 2 9 8 8 1 3 4 2 10 2 2 3 3 7 4 6 6 14 1 5 9 2 7 3 9 5 8 8 5 1 7 1 10 1 3 1 4 2 3 7 1 4 3 5 5 8 5 6 10 2 10 6 2 1 10 9 2 3 8 2 6 9 3 2 1 4 9 6 6 7 1 6 1 8 6 1 4 10 10 2 3 1 9 9 2 9 1 5 8 8 1 10 10 8 1 1 7 4 7 7 2 9 8 1 5 10 10 3 5 6 10 4 2 10 6 10 95 3 3 7 7 4 10 4 6 4 3 4 5 6 4 1 4 3 3 2 1 5 1 1 10 3 3 8 6 9 9 6 10 3 3 1 6 9 2 8 7 1 7 10 8 4 7 5 8 4 9 10 9 8 4 4 3 2 4 3 10 10 5 7 8 1 9 3 8 1 4 9 3 5 9 1 3 4 8 10 5 2 4 5 2 7 5 5 1 2 9 6 1 2 3 10 4 5 9 910 10 2 7 10 9 2 1 3 4 6 10 5 1 10 7 3 5 7 9 8 9 4 7 6 4 8 3 9 10 9 1 5 5 7 7 10 8 6 3 9 4 2 6 6 7 5 2 1 4 6 9 3 5 9 5 8 6 8 2 1 3 6 2 2 4 5 1 1 10 2 1 6 2 10 8 3 3 6 1 2 1 4 10 4 6 6 9 7 6 7 8 2 7 9 3 9 10 1 59 3 4 4 8 4 9 1 1 9 7 4 8 1 5 3 2 3 5 4 7 2 6 6 9 5 8 5 2 4 1 3 2 5 7 6 2 8 3 6 10 10 3 3 8 2 4 10 3 4 10 8 2 3 5 2 10 9 3 4 3 4 6 7 6 8 7 3 7 3 1 4 2 4 5 2 5 5 10 4 1 1 7 1 9 6 5 5 7 2 8 2 6 2 10 10 4 3 1 106 2 4 7 3 7 4 4 8 1 6 1 9 5 3 2 6 1 7 1 4 8 4 4 1 1 4 8 1 4 5 2 4 2 6 7 3 2 9 5 5 3 3 1 7 10 4 9 10 4 2 4 6 3 4 1 1 7 3 1 2 10 7 9 3 2 8 7 1 1 5 8 7 9 7 8 9 5 1 6 7 6 6 2 10 4 4 8 10 7 4 4 10 5 6 1 9 4 5 45 1 2 3 4 6 10 8 1 3 2 3 7 10 4 2 5 10 5 10 8 4 8 5 2 3 2 7 10 6 8 2 1 6 9 1 3 6 8 9 8 7 3 7 2 5 2 7 3 2 5 3 1 5 1 5 4 2 4 4 6 7 5 1 9 6 1 6 5 6 6 7 4 3 1 9 8 6 2 1 8 5 7 7 7 9 1 1 10 6 4 4 1 8 3 10 6 7 1 54 6 7 3 8 1 1 7 8 10 8 4 9 7 7 3 4 2 10 6 5 6 2 9 8 2 9 7 10 6 3 3 1 1 3 3 2 7 4 8 4 5 3 7 9 1 5 7 2 4 9 5 4 4 1 10 3 7 6 9 3 8 10 5 5 5 1 4 2 10 4 9 5 5 1 7 6 3 3 8 6 6 10 6 5 10 9 4 10 10 10 6 6 7 8 3 4 1 10 98 2 8 2 3 2 4 1 8 3 5 9 8 6 6 9 1 4 2 1 7 3 5 9 1 8 2 5 1 1 5 7 5 9 9 1 10 3 6 1 2 10 9 3 1 10 2 4 10 6 8 6 9 10 7 5 10 10 9 6 8 2 5 9 3 2 4 9 8 8 9 3 5 10 8 1 3 3 2 7 2 1 5 10 10 3 10 7 4 8 9 4 6 2 5 4 8 9 10 49 7 3 9 9 9 2 3 6 6 2 1 9 10 6 4 2 10 8 7 8 9 3 10 9 5 6 2 5 1 10 1 4 4 10 6 6 8 4 6 8 9 3 1 4 4 10 1 3 7 6 7 5 6 7 9 4 6 6 6 8 2 8 9 7 4 6 9 7 10 8 6 9 3 6 6 5 3 3 8 10 3 9 1 3 8 5 2 8 10 8 7 5 6 10 7 6 5 9 97 9 6 1 8 4 8 8 9 2 10 7 1 4 6 4 5 5 5 10 3 10 8 3 7 1 4 9 10 6 10 3 9 2 8 3 8 4 6 4 8 3 4 4 10 1 1 5 10 2 8 8 4 2 4 6 5 5 9 1 5 10 1 3 5 5 10 9 7 1 1 5 4 6 4 3 10 5 3 2 3 2 10 1 3 7 10 6 8 2 8 8 8 7 6 10 9 4 5 62 4 9 1 1 7 2 3 6 10 5 3 9 4 9 1 1 2 8 7 3 2 8 6 4 2 10 7 7 5 1 5 8 9 7 5 8 2 10 8 8 8 9 10 7 1 2 2 5 4 9 10 1 4 4 9 8 6 8 7 2 3 4 1 8 8 1 3 4 7 4 10 2 10 7 7 6 8 7 9 4 6 10 8 2 6 2 7 5 5 4 7 9 10 2 7 3 3 3 410 7 9 5 7 10 3 7 6 10 7 4 3 3 1 1 1 7 1 2 8 9 5 2 7 6 6 5 5 5 10 3 4 9 6 9 2 3 3 5 1 9 2 2 5 9 5 7 3 6 4 7 5 1 10 2 3 5 6 6 5 4 1 4 9 3 3 7 8 2 1 7 1 6 1 10 4 6 1 6 10 6 7 2 9 7 4 2 8 2 2 7 6 3 3 3 5 2 1 103 9 4 1 8 1 1 3 5 6 7 3 4 8 1 7 6 2 2 3 7 1 7 1 7 8 10 8 7 6 10 7 9 10 9 9 9 2 10 3 8 5 10 7 9 10 7 8 9 4 3 5 7 10 10 6 4 10 1 9 8 1 6 5 9 8 10 4 9 10 7 9 8 8 1 7 4 7 9 3 4 5 7 1 3 6 5 1 9 3 3 10 4 2 5 10 7 9 5 21 6 8 8 4 7 6 5 6 6 3 6 10 4 6 5 7 9 1 1 2 4 3 6 10 1 10 8 7 1 1 7 9 1 4 7 7 4 6 6 6 7 10 3 5 5 8 3 4 10 7 1 1 1 6 4 5 1 9 6 7 2 8 3 8 3 1 2 7 7 4 6 8 9 7 4 7 3 6 1 5 4 10 5 6 3 4 10 8 6 8 8 5 3 10 1 4 1 8 54 3 2 2 10 4 7 10 6 8 9 2 2 7 7 10 3 6 9 6 3 1 5 10 8 4 10 2 9 3 1 5 9 4 7 8 5 1 1 1 5 2 9 4 7 4 4 6 6 1 8 10 6 5 10 9 9 10 5 5 4 3 9 2 9 3 3 4 4 8 2 1 9 8 10 1 2 7 4 4 9 2 9 2 4 9 8 6 6 8 7 3 10 6 7 1 2 7 5 64 3 10 5 4 6 6 1 3 7 5 5 2 4 9 6 3 7 4 7 1 10 7 10 5 6 9 2 3 6 6 3 6 8 5 7 1 5 5 6 2 7 8 4 5 4 2 7 1 5 6 4 6 7 8 3 3 7 8 10 1 4 9 10 2 1 9 5 8 8 8 4 1 9 4 4 10 4 4 4 3 10 9 7 9 4 3 7 10 7 7 9 4 10 6 5 6 6 9 73 8 7 1 7 2 9 5 5 6 2 10 10 8 3 10 3 1 4 6 1 8 6 10 9 7 5 3 9 10 3 5 5 1 5 10 4 4 6 3 7 8 9 4 1 10 10 5 6 10 10 1 9 9 1 9 9 3 9 10 9 3 5 1 9 9 4 8 4 3 4 6 10 10 7 6 8 9 2 9 6 7 5 3 8 7 4 7 8 2 5 4 6 8 7 1 8 9 2 68 7 7 2 6 7 1 2 4 10 3 1 2 5 10 8 6 9 9 6 4 10 5 4 3 2 10 9 2 9 5 5 4 5 9 8 10 7 8 3 8 4 7 1 10 2 2 7 1 7 8 9 7 9 2 6 3 5 5 3 6 1 2 10 4 2 5 5 4 8 4 1 4 3 10 1 1 8 8 4 5 2 3 4 6 3 7 9 4 5 7 8 4 5 3 5 10 7 8 81 6 9 9 8 6 4 9 8 2 2 1 10 6 7 4 8 8 2 2 1 4 3 3 5 7 6 6 5 9 9 10 1 5 7 3 6 4 1 9 10 4 10 8 8 5 7 10 7 8 7 10 6 8 6 6 10 3 9 9 5 3 3 9 5 1 5 8 5 5 7 1 2 7 5 9 9 6 9 3 10 1 1 2 5 9 7 5 3 6 8 4 1 3 3 10 1 10 6 58 7 10 8 1 1 5 10 2 9 6 4 8 7 8 3 6 3 2 5 8 2 2 6 6 9 9 4 8 1 8 9 2 4 3 4 2 8 6 1 5 10 4 10 3 3 5 2 1 9 3 5 3 6 7 10 1 5 10 3 3 6 4 9 1 6 4 4 8 7 1 7 9 9 6 3 4 6 5 4 4 4 1 3 9 5 2 2 9 8 7 6 5 10 3 6 4 8 7 81 1 9 9 9 9 8 4 7 1 4 5 9 9 9 1 5 7 3 4 6 6 7 4 5 4 9 2 7 10 7 9 8 2 7 8 9 10 8 10 5 8 5 9 10 3 2 5 5 9 4 8 3 8 3 10 10 9 7 5 6 10 10 10 4 3 1 5 9 1 9 3 6 3 1 4 7 10 10 10 8 7 10 6 1 2 6 7 2 10 4 2 5 3 9 6 9 6 5 210 2 9 4 9 4 9 1 6 1 5 3 5 10 6 7 1 4 1 7 9 1 1 4 7 7 8 10 7 3 5 3 5 5 4 8 7 1 7 4 8 7 10 3 7 3 2 6 8 9 4 9 2 6 6 4 3 7 6 5 3 2 1 4 6 1 6 3 6 4 1 4 4 5 8 1 7 2 3 6 10 1 4 3 4 3 5 1 6 1 3 9 5 8 2 3 3 3 8 28 3 5 7 6 6 6 4 8 9 8 10 7 4 5 10 4 9 10 2 2 5 6 4 10 6 6 2 4 8 9 2 10 3 5 5 7 1 7 6 8 4 2 3 5 5 3 5 7 2 4 3 8 5 9 1 4 8 5 5 7 4 2 4 10 1 2 7 10 3 7 10 6 9 8 3 2 7 2 2 5 3 5 8 10 7 3 5 3 9 3 10 9 1 2 8 4 2 1 107 3 5 8 8 6 5 5 9 8 4 2 2 8 2 6 7 8 8 6 6 10 8 6 3 4 5 1 3 10 5 8 2 4 6 5 7 9 7 10 9 4 1 3 2 1 3 10 9 3 8 7 9 1 2 1 10 8 3 1 3 7 2 10 10 8 9 4 4 5 1 2 6 6 9 2 8 7 5 7 9 7 6 5 7 1 4 6 10 4 7 3 8 5 10 8 4 8 8 71 2 1 2 6 8 4 2 1 6 7 5 7 9 7 8 9 9 1 10 6 9 2 4 10 1 9 8 7 3 7 3 3 6 4 4 5 6 10 4 9 6 9 9 4 1 3 8 4 2 3 5 4 7 7 1 10 2 1 4 5 2 4 10 4 10 1 6 2 6 3 9 8 4 4 8 3 1 7 10 9 5 5 2 1 6 3 4 4 8 7 9 9 6 6 10 8 7 8 104 1 9 4 5 6 6 10 9 6 7 5 8 1 3 9 5 10 6 7 7 10 8 8 9 4 3 4 3 6 1 9 5 10 5 8 4 10 7 4 2 6 6 10 6 4 4 3 5 8 6 4 2 4 8 3 7 4 2 9 1 1 6 2 6 1 5 6 7 10 6 2 6 6 3 4 10 2 1 1 8 5 6 7 5 3 8 10 2 10 6 2 6 9 1 8 5 7 1 13 3 2 1 7 2 4 1 3 2 2 8 4 7 1 2 2 10 4 9 8 9 10 8 2 9 9 6 10 2 5 2 8 8 10 7 6 10 1 7 3 8 4 7 9 7 1 7 2 4 6 5 4 1 2 10 8 4 9 7 10 5 8 2 8 7 6 2 9 8 5 6 3 5 10 10 9 6 6 3 1 7 9 10 10 1 3 8 3 3 9 1 2 3 8 6 5 7 10 89 8 6 2 10 4 4 4 10 9 2 5 1 1 9 7 3 8 9 8 6 10 5 9 5 4 1 6 2 9 9 4 9 6 10 5 6 3 3 2 2 2 4 4 2 5 5 6 10 7 10 5 1 5 10 9 9 2 6 10 2 5 7 5 8 3 4 3 4 8 4 5 7 7 10 4 7 7 2 6 8 9 4 5 6 9 3 9 3 8 1 10 4 3 5 7 4 5 1 103 1 2 9 7 5 1 1 8 4 7 6 7 10 1 6 7 3 4 2 7 10 8 4 7 8 10 5 1 9 4 3 10 9 9 9 1 5 7 8 10 6 5 2 10 9 4 2 6 4 5 9 10 8 10 2 1 4 5 10 7 2 3 9 9 9 2 9 4 3 2 10 6 1 9 8 5 1 5 2 7 1 3 1 9 4 7 1 4 6 8 8 10 9 1 8 7 1 5 27 7 7 10 2 10 3 7 1 4 7 1 7 6 6 6 10 4 5 2 1 9 3 1 10 2 1 7 7 1 10 3 3 1 1 2 3 8 2 8 7 6 3 6 6 10 5 8 6 1 10 7 7 1 10 8 4 4 1 7 3 2 10 8 6 2 1 4 4 5 6 7 4 9 1 5 5 1 1 9 5 5 8 1 3 3 9 8 2 10 8 9 2 9 6 8 3 3 3 32 8 4 9 5 7 10 5 9 10 2 7 8 1 2 4 10 2 4 1 8 4 3 2 9 7 8 7 10 8 1 5 9 4 5 10 5 10 2 10 10 2 2 2 1 3 1 3 4 1 6 9 7 4 8 4 10 9 8 3 2 8 1 10 4 8 1 8 6 1 5 8 4 2 2 7 7 2 2 5 4 1 7 1 8 7 10 1 10 1 10 9 9 10 1 7 6 1 6 76 2 1 6 5 7 2 9 6 10 6 4 3 7 7 9 9 8 7 1 7 7 8 2 5 7 1 10 7 6 2 1 5 10 10 7 2 8 9 10 9 9 1 1 3 10 2 6 3 8 4 2 9 6 7 5 5 2 7 4 7 9 5 1 7 1 5 3 1 4 5 10 7 6 7 8 6 5 8 2 1 10 8 2 9 4 3 10 10 8 5 8 6 3 2 1 4 4 9 33 10 6 5 3 9 10 8 5 1 3 4 9 4 8 10 2 7 6 8 6 1 1 3 3 8 5 7 10 4 7 5 2 2 4 10 5 4 9 6 4 5 9 6 10 7 6 7 6 7 1 3 8 5 1 1 4 2 4 10 1 4 5 10 5 9 2 6 7 2 3 1 3 1 1 9 2 5 1 10 10 2 4 10 3 6 2 6 4 5 9 8 7 9 8 9 8 2 3 97 10 4 1 3 6 10 7 1 2 6 8 9 9 4 2 3 6 2 1 4 6 9 1 6 7 6 10 4 6 6 4 7 8 6 7 5 8 6 10 10 7 5 7 10 10 7 1 10 10 4 2 10 9 2 5 3 9 8 2 2 7 9 4 8 4 10 3 8 9 9 1 8 4 9 4 3 7 7 9 1 8 7 8 3 6 6 1 2 1 6 5 9 5 3 1 6 2 6 1010 5 5 3 9 10 6 5 3 6 5 4 7 9 6 10 7 5 5 2 10 9 6 9 7 9 9 3 5 5 9 3 4 4 7 3 9 8 1 6 3 2 8 5 6 6 8 3 6 8 7 7 4 2 4 6 10 4 6 8 5 4 7 5 1 2 9 9 6 5 10 9 4 10 4 8 6 4 9 2 1 5 1 7 3 3 5 1 3 7 8 1 2 10 9 2 4 5 3 29 5 1 3 7 10 10 9 9 3 8 3 8 5 4 5 3 3 5 7 9 7 5 8 3 6 5 2 6 3 8 6 8 10 8 2 8 3 2 7 1 8 9 3 4 3 3 4 1 5 2 10 4 7 7 7 3 5 8 3 1 2 8 8 7 5 9 4 6 9 5 3 7 8 1 1 1 5 2 1 10 7 3 8 8 4 3 6 3 6 4 1 8 3 7 4 8 10 10 31 10 10 7 3 3 10 3 8 2 5 2 8 4 9 3 8 9 10 5 7 1 6 10 9 2 2 2 10 7 8 2 6 1 8 4 7 3 6 3 7 6 8 5 4 5 5 7 8 9 5 9 8 4 6 9 5 9 8 5 7 7 3 10 1 9 10 3 4 9 10 9 6 4 9 6 6 5 7 4 7 4 6 10 3 9 4 5 7 3 2 9 3 1 1 3 1 10 7 106 10 4 9 6 8 3 9 1 6 7 9 1 7 6 5 1 1 3 2 10 7 9 5 8 8 8 8 9 3 3 6 4 8 2 4 3 9 5 1 8 5 9 9 8 2 5 10 10 6 4 4 6 9 9 3 1 5 8 1 7 7 6 4 10 2 3 5 8 8 8 2 10 1 5 2 4 2 2 9 4 7 9 4 3 1 3 9 7 6 6 7 8 2 2 5 5 6 4 45 10 2 9 9 7 7 6 3 4 2 6 7 3 6 3 4 3 1 4 9 5 4 6 9 8 8 5 4 4 1 9 6 10 8 8 2 2 8 7 5 3 2 6 3 6 2 5 2 9 5 8 2 9 10 5 6 1 2 5 8 6 2 10 8 2 9 5 10 3 10 6 3 3 1 10 8 9 5 2 1 9 2 3 6 5 5 8 10 9 2 10 7 2 8 5 7 4 7 98 9 4 1 6 1 3 9 10 8 7 1 5 8 9 2 7 6 3 6 3 5 8 7 6 1 3 6 7 2 6 8 7 6 8 8 4 4 8 9 5 3 9 1 5 4 6 5 9 1 8 2 7 1 9 6 5 7 9 7 1 1 6 3 1 6 2 6 10 2 4 7 2 3 9 8 7 9 2 6 7 6 8 7 9 4 4 8 8 4 4 2 10 7 8 5 1 7 1 15 3 4 7 4 4 4 9 10 4 8 5 2 6 4 5 2 9 5 10 5 8 10 2 7 7 2 2 4 10 2 8 6 4 7 1 2 3 2 1 6 6 10 4 3 9 5 1 4 3 6 7 1 10 10 10 3 4 9 4 2 4 2 8 10 5 8 7 5 2 9 2 2 1 8 4 8 2 9 8 5 5 6 5 2 7 4 2 2 6 9 6 5 4 3 5 6 4 6 82 7 5 10 10 8 10 6 4 10 10 2 8 9 8 5 1 4 2 2 4 10 4 8 7 8 10 8 7 4 5 7 10 3 5 5 6 4 10 4 10 4 6 7 3 6 6 7 3 10 2 3 6 1 5 1 2 2 6 4 4 1 7 6 6 7 8 1 8 3 9 4 7 10 7 1 6 7 5 6 4 7 3 3 10 3 4 7 2 1 6 2 5 9 7 7 3 7 1 85 2 10 8 2 4 1 5 6 2 7 6 2 2 10 2 9 8 1 5 2 5 8 1 9 10 3 3 2 3 2 5 4 6 4 1 5 6 5 5 8 9 9 8 3 2 5 3 10 9 5 3 4 9 8 3 10 5 5 6 2 1 1 8 9 1 6 9 4 10 1 1 10 8 9 8 2 5 2 4 10 6 3 10 10 6 6 7 2 7 7 9 10 7 7 7 10 9 10 108 7 4 10 6 3 7 3 7 6 4 9 10 4 7 4 8 6 2 9 5 4 6 2 3 5 1 6 10 2 5 7 7 8 2 1 3 3 9 6 3 2 10 3 5 4 7 1 2 5 9 5 9 7 10 8 10 6 9 8 3 6 8 10 2 9 1 4 5 7 1 10 7 2 1 3 6 9 2 1 6 1 9 8 9 3 4 3 2 1 2 6 9 3 1 10 3 7 9 31 9 8 10 4 5 1 9 6 4 1 5 7 8 4 1 7 5 8 1 5 7 6 2 2 5 3 2 2 8 4 9 1 9 2 8 6 3 6 8 2 2 2 8 8 6 9 7 5 4 4 10 5 8 7 2 7 10 2 4 7 10 4 5 3 1 8 9 5 9 4 10 7 6 3 5 7 3 8 9 5 10 1 5 2 4 6 5 7 10 8 1 5 10 10 5 3 7 3 38 9 6 6 9 10 5 8 1 1 2 9 9 9 2 6 1 3 2 9 4 4 1 9 5 2 8 1 5 10 3 8 3 7 10 5 4 10 8 5 10 4 4 9 6 7 1 10 10 2 6 4 5 1 1 10 10 8 2 5 1 1 3 7 5 6 2 8 4 9 8 3 10 6 2 5 3 3 8 10 2 7 9 5 9 7 9 2 1 3 10 7 1 9 7 10 1 1 2 66 10 1 5 10 1 4 5 10 5 4 2 2 8 4 2 4 7 7 9 1 5 7 5 2 1 3 6 6 5 5 5 10 7 7 6 10 9 10 3 9 3 2 10 8 9 9 3 5 9 8 4 3 9 3 1 4 1 9 4 3 3 3 2 1 3 1 4 1 5 3 4 5 5 10 2 7 10 9 2 5 6 1 9 4 6 4 10 1 9 4 8 6 1 10 6 7 4 5 51 6 6 9 5 3 3 6 5 9 1 2 1 4 9 4 7 9 2 7 10 9 7 6 4 2 5 3 9 6 7 2 5 3 1 3 5 4 5 3 3 7 10 7 3 7 7 5 7 7 6 3 3 9 1 10 7 3 10 7 4 4 3 6 8 1 8 4 7 9 8 10 3 2 6 2 6 8 5 1 7 2 8 2 2 5 5 5 7 6 8 3 10 1 8 9 7 5 8 38 2 5 2 9 6 8 2 10 8 2 10 3 9 9 7 6 1 1 3 7 3 2 10 5 1 5 7 4 1 3 6 9 6 9 3 8 3 6 10 2 4 9 9 10 7 5 8 7 2 1 5 9 2 1 2 2 8 5 10 8 6 8 7 7 9 6 6 1 6 3 5 9 8 1 1 5 10 8 9 9 4 2 5 4 7 7 3 3 8 6 3 4 9 10 8 4 7 8 1010 10 3 5 7 4 6 7 10 2 6 3 8 9 8 3 10 5 9 2 6 9 4 3 6 3 10 1 7 2 9 4 7 4 8 2 7 8 4 8 8 2 4 5 4 10 7 9 1 2 3 9 2 4 6 2 10 7 3 9 6 4 3 6 6 4 6 9 8 2 2 2 7 2 6 6 6 4 9 8 2 1 7 5 5 10 10 9 10 6 10 3 7 7 8 3 6 4 6 88 7 3 4 1 6 9 7 6 10 10 10 10 2 9 1 10 10 9 9 2 6 9 4 5 6 3 6 1 5 1 3 2 5 2 6 9 4 5 4 6 9 10 5 5 2 9 1 8 10 8 6 7 6 7 10 1 10 9 5 9 6 8 7 10 7 10 6 10 1 1 4 3 4 2 5 2 10 10 7 9 7 7 3 6 8 4 1 1 5 3 10 7 3 8 5 3 5 5 13 2 3 8 5 8 2 10 6 9 8 9 7 7 8 4 10 2 5 4 4 5 8 4 8 5 1 6 3 9 8 6 6 1 1 1 8 9 5 7 8 8 8 3 9 5 10 7 5 2 7 4 4 4 8 8 10 9 6 1 8 5 10 9 1 6 4 4 2 3 6 9 5 4 8 6 4 1 5 2 7 5 8 2 1 1 10 1 5 7 9 9 5 1 5 8 10 10 5 110 6 8 10 9 4 8 3 4 10 8 6 4 6 7 6 10 7 10 4 7 6 7 9 3 1 9 2 5 4 2 5 7 1 3 5 5 2 1 7 8 8 1 7 2 9 5 6 3 1 2 10 1 1 7 3 5 8 9 6 7 9 9 8 2 7 3 10 1 8 5 3 7 3 4 6 4 1 2 8 3 9 2 9 1 8 7 6 1 6 4 2 7 7 9 5 10 1 2 21 1 4 4 8 1 1 8 5 8 5 4 4 10 1 1 4 10 10 5 8 6 3 8 8 4 3 9 1 9 2 6 9 6 4 1 1 1 5 10 5 3 1 10 4 8 7 3 9 2 1 3 4 10 5 6 4 9 5 2 1 4 4 6 8 6 10 10 6 8 4 4 3 1 4 2 5 9 1 2 4 4 2 6 10 1 7 4 9 4 8 3 5 4 1 1 5 4 10 17 1 5 2 10 5 8 2 1 9 7 4 6 1 6 9 1 8 7 3 9 3 5 5 3 2 7 8 5 7 3 2 1 9 3 10 8 9 1 3 1 1 8 1 9 1 8 2 3 1 5 7 8 6 8 6 10 4 8 3 2 3 8 3 7 9 1 6 7 2 7 3 1 10 8 3 7 6 6 8 3 10 5 4 8 1 2 1 2 8 6 9 3 10 7 10 1 4 9 38 9 10 1 7 5 9 10 5 4 6 4 7 1 1 5 1 8 6 7 10 10 4 9 1 5 3 10 2 5 9 1 6 1 4 7 2 4 1 9 1 9 5 9 6 10 3 6 2 4 9 1 6 5 10 8 5 10 7 10 5 8 1 9 3 10 5 6 1 8 6 1 7 8 10 7 1 8 8 2 5 4 9 1 10 6 4 6 6 3 4 7 10 6 7 9 3 7 3 14 4 8 7 10 5 2 5 7 1 10 7 10 7 9 3 3 10 2 7 5 4 4 2 1 8 9 4 5 9 6 10 7 5 5 6 2 2 1 8 2 3 4 2 10 6 3 2 3 3 5 7 7 4 4 4 10 2 10 9 4 5 8 8 8 8 3 1 3 9 10 10 7 6 7 10 4 10 1 9 8 9 8 2 10 6 5 4 8 5 10 10 8 3 1 9 10 10 3 24 8 6 5 4 1 5 4 5 8 9 10 7 10 2 5 5 7 9 4 6 5 8 3 2 8 4 2 5 4 2 2 9 4 6 8 9 3 6 10 8 6 3 7 9 5 1 6 5 4 7 5 5 8 3 1 3 1 1 9 5 3 1 3 8 10 10 4 5 5 4 6 1 2 6 7 8 9 10 2 6 2 9 7 1 4 10 8 7 6 6 4 1 10 8 6 8 2 7 87 10 5 9 10 5 6 4 6 9 1 10 4 7 6 1 5 6 3 6 1 7 7 5 6 3 8 6 5 5 2 6 4 6 4 7 1 5 1 10 8 4 4 4 9 5 4 1 6 7 7 3 8 1 5 10 10 2 10 2 10 10 10 6 8 3 3 8 7 7 4 10 1 2 5 9 5 1 7 10 4 1 9 10 7 2 7 3 2 9 2 7 1 3 1 9 2 4 7 65 8 9 8 2 9 2 10 4 2 5 5 1 9 7 2 7 3 1 5 9 10 6 10 5 10 2 8 7 1 7 2 1 4 1 9 10 3 4 5 1 2 6 4 9 3 5 3 7 4 10 5 9 3 3 7 8 2 3 3 6 3 9 4 4 7 7 1 4 4 10 2 3 6 5 4 7 9 1 4 7 7 8 5 7 7 10 10 7 10 6 8 9 6 5 5 2 6 5 43 6 4 10 5 4 9 8 10 6 7 5 9 6 10 3 5 5 6 7 6 10 1 9 5 3 5 3 9 2 10 7 2 8 1 5 9 9 5 10 10 7 5 9 5 6 9 9 6 2 9 5 7 8 10 3 6 7 5 2 8 5 1 9 6 8 2 6 7 1 7 9 7 6 7 5 5 5 2 8 9 9 5 3 5 1 5 10 8 5 4 5 2 10 3 8 8 4 4 53 4 9 6 3 8 9 1 3 4 9 10 8 1 4 1 5 6 10 8 9 2 4 1 9 4 1 6 8 8 9 10 2 5 2 9 4 5 2 7 1 1 6 10 6 8 10 6 4 10 10 10 6 3 6 4 4 8 6 2 7 1 9 2 6 7 8 3 10 6 4 9 5 6 3 6 1 5 9 7 4 9 6 1 8 8 2 5 1 5 5 10 7 5 5 1 9 3 1 107 6 8 10 3 6 5 10 3 2 7 5 8 9 10 6 7 2 9 7 6 2 7 1 6 5 1 8 7 8 2 10 5 5 9 8 1 7 5 2 8 7 9 6 5 4 5 6 10 2 4 9 10 4 9 6 7 2 2 5 1 5 9 3 9 4 5 4 9 5 3 6 9 1 3 5 1 1 9 1 4 7 6 8 5 10 5 5 1 1 2 10 2 4 2 4 10 1 9 46 4 8 5 6 6 1 6 7 2 3 4 4 2 8 6 5 10 4 10 2 2 10 3 6 5 10 3 10 7 3 5 10 4 4 3 10 7 6 4 4 3 6 8 5 10 3 2 1 1 7 6 1 6 10 5 2 9 7 3 2 7 1 10 6 2 10 10 3 10 5 3 7 1 8 9 7 5 1 4 5 3 6 4 1 6 10 10 10 10 9 3 6 6 4 4 10 1 4 56 8 8 1 8 4 6 1 4 5 3 7 10 5 3 4 10 10 10 5 3 7 5 10 3 4 1 4 5 6 5 4 6 7 7 6 6 2 8 10 1 7 9 1 1 4 10 4 7 1 5 10 1 3 5 1 5 5 2 3 5 1 2 8 1 8 3 8 5 8 5 9 5 10 4 1 7 10 5 7 5 9 5 5 1 8 7 5 6 2 1 6 4 2 7 7 1 8 1 46 3 3 3 1 10 10 5 7 1 2 2 3 3 6 9 4 4 2 4 7 4 6 9 8 7 5 2 4 5 9 1 9 7 2 5 10 10 4 10 7 6 5 9 2 7 1 2 2 10 9 10 2 10 3 6 5 10 3 5 2 1 3 10 7 5 10 5 5 4 8 9 10 7 4 2 9 10 1 7 5 5 1 3 7 3 2 9 6 4 1 7 4 7 5 10 4 7 10 105 3 2 8 10 3 3 1 4 1 4 10 3 10 6 10 8 9 5 7 9 4 5 4 3 3 3 10 3 7 9 10 7 3 9 3 4 6 6 10 10 10 5 6 7 3 4 1 1 1 7 2 3 5 4 7 4 8 4 8 2 1 6 1 5 6 8 5 8 4 2 10 10 8 4 5 4 5 6 3 8 7 1 1 1 3 9 10 1 10 5 1 7 5 6 1 9 10 10 27 3 10 2 10 4 9 4 5 3 5 10 10 8 1 4 5 2 1 4 1 9 9 7 1 5 6 7 4 9 4 9 6 4 5 9 2 5 8 8 2 10 9 4 10 4 10 6 3 5 1 4 2 7 6 3 4 8 1 9 10 1 4 7 3 5 4 8 2 1 8 8 5 3 10 8 4 9 7 1 3 6 5 1 2 4 7 1 6 8 5 5 8 7 5 6 9 7 7 37 5 7 10 5 2 8 8 6 2 10 7 9 2 6 10 7 8 3 3 10 4 5 9 8 10 9 10 6 5 6 1 10 3 4 6 5 6 8 3 7 7 9 7 7 10 4 3 7 2 3 3 3 5 10 3 3 10 1 4 7 1 8 2 9 8 7 9 4 10 1 7 1 9 7 6 3 9 3 10 3 3 10 4 4 8 6 10 4 9 7 6 2 3 7 6 3 5 4 96 6 3 7 5 4 2 1 5 10 6 9 9 3 3 5 6 9 10 6 5 1 6 1 3 1 5 7 8 3 1 3 4 10 5 2 1 8 6 2 3 6 1 7 5 7 4 5 4 3 9 1 10 4 9 4 4 7 8 6 1 9 6 1 1 7 10 3 8 6 5 10 10 10 9 10 3 5 8 7 3 2 9 4 9 6 3 2 5 3 10 4 9 8 3 9 3 6 9 82 8 1 3 5 10 1 6 7 5 6 10 4 6 1 8 5 1 7 3 4 1 6 4 10 6 3 6 9 8 2 5 4 7 7 1 7 4 8 1 4 7 7 2 10 5 7 3 9 2 3 4 3 4 2 2 5 6 8 10 2 1 6 1 10 2 9 10 5 10 4 8 8 10 2 5 3 4 8 6 7 9 1 5 8 6 5 9 7 5 2 1 6 2 6 9 10 2 5 73 2 4 9 8 4 3 4 2 7 3 4 7 8 7 1 9 8 5 5 7 10 8 4 4 8 5 1 7 10 2 8 2 6 10 1 7 2 6 1 10 6 9 6 5 1 4 5 5 6 3 3 1 9 7 5 8 9 8 4 1 4 8 4 8 10 7 9 2 3 9 4 7 7 8 10 4 1 3 9 9 9 2 5 4 3 4 6 5 6 8 4 7 3 5 2 9 1 5 105 9 4 1 1 5 6 9 5 5 3 6 9 10 6 6 6 10 9 5 4 7 2 10 7 2 6 9 10 6 1 4 1 9 1 9 1 6 9 5 5 1 5 5 1 8 7 10 5 3 9 6 3 3 4 6 8 7 5 9 3 3 4 7 6 8 6 9 6 7 7 2 8 4 3 7 9 8 2 6 10 10 10 7 7 7 1 8 3 7 2 2 7 10 7 8 9 6 2 95 3 10 1 8 2 4 10 1 9 10 2 4 10 5 5 1 6 4 5 3 4 5 3 1 2 5 6 7 1 6 1 3 6 8 3 4 4 10 1 6 4 8 2 1 4 7 1 9 9 2 7 3 4 6 10 8 6 1 2 6 7 6 8 5 1 7 8 8 8 5 7 6 8 4 4 5 8 8 3 5 8 2 1 6 3 7 4 6 3 6 7 4 4 2 5 4 2 9 74 6 5 6 2 5 4 4 8 9 3 7 9 8 5 5 9 9 3 3 2 7 6 1 2 7 9 7 1 8 3 8 2 8 10 9 5 2 10 6 3 8 1 7 8 4 8 8 7 3 5 3 4 7 3 5 3 5 3 5 1 5 2 3 9 5 6 9 1 7 6 2 6 10 8 10 4 4 3 5 6 3 10 2 10 1 3 8 10 8 8 5 1 9 4 10 1 2 3 27 3 1 1 1 4 8 8 9 5 8 10 2 10 1 5 6 1 1 5 9 2 8 8 2 6 4 1 1 1 10 9 4 9 7 5 6 4 6 7 2 10 6 1 3 6 2 2 8 3 6 2 7 10 2 1 8 3 6 3 8 2 4 1 3 9 8 8 2 1 9 10 8 9 3 10 7 6 1 2 6 5 1 2 7 8 6 10 10 1 8 9 1 9 3 3 7 9 2 57 3 3 7 10 5 6 7 4 10 8 8 3 7 5 9 4 5 4 7 8 4 5 10 4 9 5 10 3 5 9 3 9 8 1 4 6 6 9 8 7 4 5 8 5 7 6 5 2 8 5 9 1 9 8 6 8 9 8 1 4 8 3 2 4 1 7 3 3 3 8 1 4 10 4 6 7 7 10 1 1 4 8 10 2 4 9 6 5 9 8 4 2 6 3 5 6 2 9 39 8 4 6 1 2 5 7 2 3 3 10 10 10 9 5 7 6 10 3 6 7 2 9 3 10 10 5 3 1 5 8 1 7 9 8 3 2 1 3 4 7 6 7 10 7 7 1 10 7 1 10 4 5 5 9 10 9 10 6 3 7 8 1 3 5 2 10 5 2 8 7 9 10 10 2 2 8 9 7 1 1 9 10 3 10 6 2 9 1 4 8 8 8 5 5 1 1 10 96 2 3 1 8 8 6 1 8 1 4 6 10 7 5 5 5 2 8 10 3 3 2 7 5 5 10 8 9 1 4 1 2 5 7 8 10 8 5 3 9 5 3 6 10 5 10 1 6 3 5 1 10 3 6 8 3 3 4 1 8 3 6 5 4 7 10 1 10 5 10 3 10 1 8 5 3 3 8 10 8 1 5 3 9 8 2 6 8 3 1 6 6 3 3 6 5 8 3 47 3 1 10 10 9 5 7 4 6 8 2 6 1 1 9 6 1 7 7 2 2 9 9 1 3 3 6 8 2 3 2 8 7 7 7 5 7 6 4 10 4 7 5 1 5 2 1 5 2 1 5 10 10 7 3 7 8 10 5 7 1 1 2 2 3 1 7 2 4 4 4 4 9 4 1 6 6 9 6 6 7 8 7 2 5 7 2 6 4 3 10 9 9 1 1 8 8 7 27 3 6 6 3 9 4 5 7 9 6 3 10 1 7 1 7 4 6 4 2 1 7 3 3 1 7 10 6 7 5 2 7 9 8 8 2 6 6 6 7 1 10 10 6 6 9 5 5 2 2 3 8 5 1 9 7 1 4 7 1 3 4 3 5 10 1 5 10 7 7 6 8 2 9 1 10 1 1 8 1 3 1 4 7 5 7 6 8 7 5 6 1 5 3 10 8 4 1 74 5 6 4 5 6 6 1 2 9 7 1 2 5 6 9 2 3 2 5 1 1 1 9 3 1 6 5 3 1 3 10 6 1 2 8 1 3 6 9 3 7 1 5 2 1 5 5 2 4 10 7 6 1 3 3 7 3 10 6 9 9 4 7 2 10 8 4 3 3 8 1 2 1 4 9 8 5 1 7 3 5 6 10 4 8 3 7 9 7 4 4 9 10 6 3 4 2 8 107 7 10 10 4 4 2 5 8 6 6 2 2 3 2 3 6 1 4 7 5 1 9 6 3 3 4 10 5 5 1 5 8 2 10 9 3 7 2 2 3 1 5 7 5 2 6 10 4 1 10 10 5 4 8 6 7 7 7 6 3 4 9 4 10 10 10 7 3 1 1 10 3 6 10 5 8 5 4 6 8 3 2 6 5 2 9 3 7 3 2 4 1 7 9 10 4 5 2 62 1 6 10 2 3 9 5 4 5 4 8 4 6 3 4 5 2 5 3 3 4 3 4 5 9 7 2 6 3 3 9 9 1 7 7 3 7 7 10 8 8 2 5 10 4 2 3 1 8 5 1 6 3 8 5 8 8 6 5 4 1 2 6 6 7 10 10 4 2 3 9 8 5 10 6 2 3 1 6 4 2 7 4 5 7 2 3 4 5 8 6 8 6 4 1 6 3 3 68 8 6 6 6 7 1 2 6 4 4 1 5 5 5 1 9 3 9 2 6 6 5 4 2 3 1 7 5 10 3 9 3 8 8 7 5 4 5 8 7 3 10 1 5 10 7 2 2 9 7 9 2 6 6 2 3 6 7 1 1 2 5 3 4 10 10 4 8 5 9 7 5 8 6 1 7 9 3 10 4 5 6 5 3 9 1 3 9 2 7 2 7 8 9 2 4 3 4 14 7 4 3 3 4 7 4 8 6 5 6 4 10 5 10 7 10 8 9 10 6 7 7 9 3 7 4 7 6 3 4 8 6 9 4 7 8 8 4 10 7 10 6 2 4 7 7 3 7 3 3 6 6 8 6 5 10 1 1 8 1 2 4 2 6 4 1 6 4 6 6 5 4 5 6 7 1 5 3 6 8 8 1 10 7 6 7 10 5 2 4 7 4 9 3 3 8 3 66 7 2 7 9 9 8 6 1 5 10 9 7 6 6 9 8 3 6 3 3 9 7 1 10 5 2 8 4 5 9 10 8 7 5 7 9 9 1 1 10 5 9 4 6 9 6 1 8 10 2 1 8 3 8 10 8 9 3 3 10 3 2 4 8 3 3 3 8 1 8 7 2 6 3 1 7 9 6 1 10 1 1 7 10 9 7 1 1 10 6 1 3 3 6 8 1 4 5 103 5 9 8 7 8 7 5 10 5 9 4 9 8 8 1 4 5 3 4 6 5 10 4 1 10 5 1 8 3 5 5 2 5 10 8 4 5 6 10 10 6 3 6 1 5 9 8 2 10 3 1 2 7 7 8 3 4 9 9 10 5 2 7 1 7 9 3 1 3 3 3 1 3 1 10 1 9 1 7 1 3 2 6 5 3 9 1 2 6 2 8 1 4 6 9 4 3 6 94 5 3 3 10 7 1 2 4 4 9 2 10 3 7 3 2 8 5 8 7 7 6 1 3 5 8 1 1 2 9 4 8 10 1 6 1 2 5 6 5 5 7 6 5 2 1 7 9 10 8 8 3 9 1 6 6 3 8 3 7 2 10 7 4 7 8 10 1 9 9 7 9 10 4 5 8 8 2 7 10 6 6 2 1 1 10 9 6 1 6 1 10 3 2 7 9 4 7 37 1 4 8 1 6 8 10 9 10 8 2 4 1 4 7 1 5 4 7 8 8 8 5 4 5 8 8 1 5 6 2 1 3 9 4 7 1 2 1 8 8 10 2 5 6 4 1 3 5 10 1 10 6 9 3 7 5 9 3 1 8 1 1 2 7 1 2 1 9 4 8 5 1 6 9 3 8 6 1 5 9 6 9 9 10 1 1 3 7 1 3 6 9 3 4 8 4 10 101 7 7 9 3 4 3 3 10 7 1 10 2 10 5 1 4 9 4 8 5 4 10 10 2 1 5 6 7 3 7 9 8 3 10 5 6 5 1 3 5 10 7 2 6 4 3 3 5 2 7 7 2 10 4 9 4 1 7 8 3 6 4 2 8 8 6 2 2 10 7 10 5 7 3 6 5 1 4 7 9 9 2 2 8 5 8 7 9 4 8 3 8 4 10 10 4 7 6 66 4 10 9 5 3 7 10 4 8 9 3 1 8 4 3 8 10 6 3 3 2 2 9 5 6 3 10 8 3 10 3 7 9 3 4 2 3 4 8 5 6 7 7 8 7 6 10 6 4 9 10 1 2 1 8 5 3 4 3 9 1 1 5 2 7 9 2 8 9 7 2 5 1 7 1 7 1 2 2 4 8 8 7 10 2 7 8 2 6 7 6 4 6 7 4 9 10 8 68 6 7 8 10 9 3 3 10 10 4 9 2 10 3 8 2 7 10 4 4 6 2 5 10 3 10 5 3 7 9 10 6 3 5 8 3 2 9 8 5 9 8 2 9 6 4 5 6 2 10 5 1 7 5 2 4 1 8 1 9 4 1 8 8 3 9 6 3 3 6 6 7 2 6 10 4 1 9 10 2 10 5 4 4 2 3 8 8 2 3 4 7 4 3 5 6 4 10 97 10 9 6 9 2 9 1 4 5 8 10 1 5 6 6 2 4 1 1 7 9 7 7 8 10 3 2 5 2 3 9 7 3 8 8 7 7 3 7 1 5 6 8 6 8 8 1 5 3 3 5 6 4 5 4 9 1 9 9 1 4 8 7 4 4 8 6 2 5 9 10 7 3 7 7 4 9 8 10 2 9 1 5 7 7 10 4 5 2 1 6 2 3 5 9 3 8 2 4,['java'] +1207561,how to filter haystack results with db query i need to textsearch across my model and filter with db queries at the same timefor exampleclass mymodelmodelsmodel text modelstextfield users modelsmanytomanyuserclass mymodelindexindexindexessearchindex indexesindexable text indexescharfielddocumenttrue model attrtext def get modelself return mymodelso i want to filter all mymodel objects by user and by some text via fulltext search smth like theseqs mymodelobjectsfilterusersrequestusersqs mymodelindexobjectsfiltertextrequestgetqintersection some magic functionqs sqsor intersection some other magic function qs kwargsusers requestuser sqs kwargstext requestgetqof course desired db queries could be much more complicatedi see some possible solutions all with major flawsmake intersection in django extract ids from qs and use them in sqs filter or vice versa problem performance we can workaround itby using pagination and do intersection only for given page and its predecessors in this case we lose total count index all m2m related fields problem performance duplicate functionality i believe db will do such queries much better dbfeatures such as annotations etcdo not use haystack go for mysql or posgresql builtin fulltext searchi believe i miss something obvious case seems to be quite common is there a conventional solution,['python'] +1208039,how do i turn a dataframe into a series of lists i have had to do this several times and i am always frustrated i have a dataframedf pddataframe1 2 3 4 5 6 7 8 a b a b c dprint df a b c da 1 2 3 4b 5 6 7 8i want to turn df intopdseries1 2 3 4 5 6 7 8 a ba 1 2 3 4b 5 6 7 8dtype objecti have trieddfapplylist axis1which just gets me back the same dfwhat is a convenienteffective way to do this,['python'] +1208215,huge number of files generated for every angularjs 2 project i wanted to start a simple hello world app for angularjs 2when i followed the instructions in the official quickstart the installation created 320 files in my projecti figured this is some mistake or i missed something so i decided to use angularcli but after setting up the project i counted 410 fileswhere did i go wrong am i missing something really really obvious,['javascript'] +1208220,what does struct type1 mean i found some code that gets the size of struct like thissizeofstruct struct type1i tested and it does return the size of struct type andsizeofstruct struct type2returns twice the struct size edit struct type is a struct not an arraystruct struct type int a int bwhat does struct type1 actually mean,['c'] +1208250,is there a way to store clang compiletime flags in the output binary is there a way to store the compiletime flags in the output binary when using clangfor example after running clang o3 c maincthe resulting maino file should somewhere contain o3 gcc has frecordgccswitches but i am unable to find an equivalent for clang,"['c++', 'c']" +1208498,styling wysiwyg editor i have an html page in that page i am trying to add a wysiwyg editor i have decided to use this one i have it working in my app however i cannot seem to get it styled the way i want i believe the problem is because i am using this theme i would really like to be able to have the toolbar floating above the control to the right of the textbox label at the same time i would like to keep the paper look instead of the bulky boxat this point i have tried whats in this fiddle still the styling is all wrong the main code looks like thisdiv classcontainerdiv classformgroup labelstatic isempty div classrow div classcolxs3label classcontrollabel fordescriptiondescriptionlabel div div classcolxs9 div idtoolbar classpullright styleverticalaligntop margintop0 paddingtop0toolbardiv div div input classformcontrol rows3 iddescription namedescription onfocussetmoderich onblursetmodenulldivdivwhile i am using the following javascriptfunction materialinitfunction setmodename if name rich descriptionsummernote focus true else descriptionsummernotedestroy any help is appreciated this is really frustrating,"['javascript', 'css']" +1208618,reproducing encrypted video using exoplayer i am using exoplayer in android and i am trying to reproduce an encrypted video stored locally the modularity of exoplayer allows to create custom components that can be injected in the exoplayer and this seems the case indeed after some researches i realized that for achive that task i could create a custom datasource and overriding open read and closei also find this solution but actually here the entire file is decrypted in one step and stored in a clear inputstream this can be good in many situation but what if i need to reproduce big file so the question is how can i reproduce encrypted video in exoplayer decrypting content onfly without decrypting the entire file is this possibilei tried creating a custom datasource that has the open methodoverride public long opendataspec dataspec throws filedatasourceexception try file file new filedataspecurigetpath clearinputstream new cipherinputstreamnew fileinputstreamfile mcipher long skipped clearinputstreamskipdataspecposition if skipped dataspecposition throw new eofexception if dataspeclength clength unbounded bytesremaining dataspeclength else bytesremaining clearinputstreamavailable if bytesremaining 0 bytesremaining clength unbounded catch eofexception e eprintstacktrace catch ioexception e eprintstacktrace opened true if listener null listenerontransferstart return bytesremaining and this is the read methodoverridepublic int readbyte buffer int offset int readlength throws filedatasourceexception if bytesremaining 0 return 1 else int bytesread 0 int bytestoread bytesremaining clength unbounded readlength int mathminbytesremaining readlength try bytesread clearinputstreamreadbuffer offset bytestoread catch ioexception e eprintstacktrace if bytesread 0 if bytesremaining clength unbounded bytesremaining bytesread if listener null listeneronbytestransferredbytesread return bytesread if instead of an encoded file i pass a clear file and just remove the cipherinputstream part then it works fine instead with encrypted file i obtain this error unexpected exception loading streamjavalangillegalstateexception top bit not zero 1195853062at comgoogleandroidexoplayerutilparsablebytearrayreadunsignedinttointparsablebytearrayjava240at comgoogleandroidexoplayerextractormp4mp4extractorreadsamplemp4extractorjava331at comgoogleandroidexoplayerextractormp4mp4extractorreadmp4extractorjava122at comgoogleandroidexoplayerextractorextractorsamplesourceextractingloadableloadextractorsamplesourcejava745at comgoogleandroidexoplayerupstreamloaderloadtaskrunloaderjava209at javautilconcurrentexecutorsrunnableadaptercallexecutorsjava423at javautilconcurrentfuturetaskrunfuturetaskjava237at javautilconcurrentthreadpoolexecutorrunworkerthreadpoolexecutorjava13at javautilconcurrentthreadpoolexecutorworkerrunthreadpoolexecutorjava588at javalangthreadrunthreadjava818editthe encrypted video is generated in this waycipher cipher ciphergetinstanceaescbcpkcs5paddingsecretkeyspec keyspec new secretkeyspec0123456789012345getbytes aesivparameterspec ivspec new ivparameterspec0123459876543210getbytescipherinitcipherencrypt mode keyspec ivspecoutputstream new cipheroutputstreamoutput stream cipherthen the outputstream is saved into a file,['android'] +1208626,webpack 2 react nested routes when code splitting with systemimport i have an app that is based of article i have added some children routes and now my router config is as suchfunction errorloadingerr consoleerrordynamic page loading failed errfunction loadroutecb consolelogload route called return module cbnull moduledefaultconst obj component app childroutes path getcomponentlocation cb systemimportpageshome thenloadroutecb catcherrorloading path gsgs getcomponentlocation cb systemimportpagesgsgs thenloadroutecb catcherrorloading childroutes path go getcomponentlocation cb systemimportpagesgsgshomejs thenloadroutecb catcherrorloading path about getcomponentlocation cb systemimportpagesabout thenloadroutecb catcherrorloading index about and gsgs routes trigger dynamic code loading just fine but gsgsgo triggers a 404 with bundlejs2 dynamic page loading failed error loading chunk 0 failedawhat am i doing wrong im using webpack 210beta4webpackdevserver 200beta,['javascript'] +1208667,is there a specific range of unicode code points which can be checked for emojis do emojis occupy a welldefined unicode rangeand is there a definitive way to check whether a code point is an emoji in python 27i cannot seem to find any information on this a couple of sources have pointed to the rangeu01f600u01f650but for example i 34i has the code pointu01f918which lies outside this rangethanks,['python'] +1208745,native javascript sort performing slower than implemented mergesort and quicksort i have implemented a mergesort and a quicksort to compare them with the native javascript sort for the quicksort i have tried to use this algorithm view algorithm on youtube both algorithms use as less memory as possible for the merge sort an auxiliary array is passed for each recursive call to avoid overheads and for the quicksort positions of the starting and ending positions i am using sorts to manage large amounts of data in a nodejs appbelow you have the mergesort quicksort and native javascript sort and you can test the performance the question is why is the native javascript performing slower in my case chrome merge sort measure 1997920ms quicksort measure 1755740ms native measure 4988105msnode merge sort measure 2233413ms quicksort measure 1876055ms native measure 6317118msmerge sortvar length 10 ten millionsvar arr for let i length i 0 i random array arrpushparseintmathrandom 10var mergesort functionarray function mergearr aux lo mid hi for var k lo k hi k auxk arrk var i lo var j mid 1 for var k lo k hi k if i mid arrk auxj else if j hi arrk auxi else if auxi auxj arrk auxi else arrk auxj function sortarray aux lo hi if hi lo return var mid mathfloorlo hi lo 2 sortarray aux lo mid sortarray aux mid 1 hi mergearray aux lo mid hi function merge sortarray var aux arrayslice0 sortarray aux 0 arraylength 1 return array return merge sortarrayconsoletimemeasuremergesortarrconsoletimeendmeasureconsolelogarr0 arr1quicksortvar length 10 ten millionsvar arr for let i length i 0 i random array arrpushparseintmathrandom 10function quicksortarr leftpos rightpos arrlength let initialleftpos leftpos let initialrightpos rightpos let direction true let pivot rightpos while leftpos rightpos 0 if direction if arrpivot arrleftpos quicksortswaparr pivot leftpos pivot leftpos rightpos direction direction else leftpos else if arrpivot arightpos rightpos else quicksortswaparr pivot rightpos leftpos pivot rightpos direction direction if pivot 1 initialleftpos quicksortarr initialleftpos pivot 1 arrlength if pivot 1 initialrightpos quicksortarr pivot 1 initialrightpos arrlength quicksortswap arr el1 el2 let swapedelem arrel1 arrel1 arrel2 arrel2 swapedelemarrlength arrlengthconsoletimemeasurequicksortarr 0 arrlength 1 arrlengthconsolelogarr0 arr1consoletimeendmeasurenative javascript sortvar length 10 ten millionsvar arr for let i length i 0 i random array arrpushparseintmathrandom 10consoletimemeasurearrsortfunction comparenumbersa b return a bconsoletimeendmeasureconsolelogarr0 arr1,['javascript'] +1208777,c when to use which standard exception the header stdexcept defines a couple of standard exceptions however i have troubles determining when to use which exception are there good guidelines to be found online i try to illustrate my problem with an examplea function takes the length of a physical vector and an angle between 0 and pi to return a new vector if the angle is negative is thata stdinvalid argument as negative angles are invalida stdlogic error as negative angles do not make sense in this casea stdout of range as negative angles are outside the allowed range for anglesa stddomain error as the mathematical function is not defined on negative anglesor should i define a custom exceptionin case anybody wonders i am trying to transform coordinates in a triclinic simulation box which are actually three lengths and three angles see here if you are interested,['c++'] +1208894,use stdexperimentaloptional to implement a list i was wondering if it is possible to implement a single and possible double linked list using stdexperimentaloptionaltemplate typename tstruct node stdexperimentaloptionalnodet next t datawhat are the advantagesthisadvantages of such a design could new c1z features be used to implement sentinels or getting rid of them alltogether would this scale up to nary trees as well,['c++'] +1209074,not defined error for some variables in angular i am using the following code in codepen and facing this issue for conctact i am getting the following errorwhy is it giving error for contact and not for namehow can i solve this angularjs13550 referenceerror contact is not defined at new anonymous penjs8 at objectinvoke angularjs4665 at rinstance angularjs10115 at and angularjs9033 at g angularjs8397 at g angularjs8400 at angularjs8277 at angularjs1751 at neval angularjs17229 at napply angularjs17329here is js filevar app angularmodulecrud appcontrollerctrl scope functionscope scopedata 3 4 5 34 34 debugger scopename name scopecontact contact scopeobj name scopename contact scopecontact consolelogscopeobjhere is the html file that i am usingbody ngappcrud div ngcontrollerctrl div table tr ngrepeatx in data track by index tdxtd tdindextd tr table div divbodyplease answer these questionswhy is it failing at contact and not at name contact is number data what should i give the default value to it,"['javascript', 'html']" +1209150,deprecated pluspeopleapiload now that plusapi is deprecated in google play services 94 what is correct way to get google plus circles for authenticated user on android application now we have deprecated method of loading plus users pluspeopleapiloadnew documentation says if your app needs social information and more extensive profile data check out the android contacts provider or the crossplatform people apiso i should go with android contacts provider that seems to be a hard alternative because i have to filter contacts with cursors and also manage runtime permissionsany easy alternatives of previous deprecated method to just get list of g circles for user,['android'] +1209176,how to enable trace output in nunit 3 visual studio adapter testpublic void test1 tracetraceinformationhellowhen running it from vs 2015 the output window tests shows no trace lines thiscover test started nunit adapter 3400 test thiscovery startingnunit adapter 3400 test thiscovery complete thiscover test finished 9 found 013258 run test started nunit adapter 3400 test execution startedrunning selected tests in cprojectsblabladllnunit3testexecutor converted 9 of 9 nunit test casesnunit adapter 3400 test execution complete run test finished 1 run 035445181 i remember it was working fine with nunit 2 and vs 2013 do i need to somehow turn it on my appconfig has no overrides to default systemdiagnostics,['.net'] +1209193,wrap image around a circle what i am trying to do in this example is wrap an image around a circle like belowto wrap the image i simply calculated the xy coordinates using trigthe problem is the calculated x and y positions are rounded to make them integers this causes the blank pixels in seen the wrapped image above the xy positions have to be an integer because they are positions in listsi have done this again in the code following but without any images to make things easier to see all i have done is create two arrays with binary values one array is black the other white then wrapped one onto the otherthe output of the code is import math as mfrom pil import image only used for showing output as imagewidth 2540height 240ro 400img 1 for x in rangeintwidth for y in rangeintheightcir 0 for x in rangeintro 2 for y in rangeintro 2def shom imimg for showing data as image list image item for sublist in img for item in sublist new image imagenew1 lenimg0 lenimg new imageputdatalist image new imageshowincrement mradians360 widthrad ro 05for i row in enumerateimg hyp rad i for j column in enumeraterow alpha j increment x mcosalpha hyp rad y msinalpha hyp rad put value from original image to its position in new image cirintroundyintroundx imgijshom imciri later found out about the midpoint circle algorithm but i had worse result with thatfrom pil import image only used for showing output as imagewidth height 254 24ro 40img 0 0 0 1 for x in rangeintwidth for y in rangeintheightcir 0 0 0 255 for x in rangeintro 2 for y in rangeintro 2def shom imimg for showing data as image list image item for sublist in img for item in sublist new image imagenewrgba lenimg0 lenimg new imageputdatalist image new imageshowdef putpixelx0 y0 global cir ciry0x0 255 255 255 255def drawcirclex0 y0 radius x radius y 0 err 0 while x y putpixelx0 x y0 y putpixelx0 y y0 x putpixelx0 y y0 x putpixelx0 x y0 y putpixelx0 x y0 y putpixelx0 y y0 x putpixelx0 y y0 x putpixelx0 x y0 y y 1 err 1 2 y if 2 err x 1 0 x 1 err 1 2 xfor i row in enumerateimg rad ro i drawcircleintro 1 intro 1 radshom imcircan anybody suggest a way to eliminate the blank pixels,['python'] +1209398,absolute positioning within inline elements is this behaviour correct consider the following simple html and cssarel positionrelativebutton positionabsolute top0 left0lorem ipsum dolor sit ameta classrel href img src color 272x92dppng buttoni am a buttonbuttonanow consider css2 10141if the element has position absolute the containing block is established by the nearest ancestor with a position of absolute relative or fixed in the following wayin the case that the ancestor is an inline element the containing block is the bounding box around the padding boxes of the first and the last inline boxes generated for that element in css 21 if the inline element is split across multiple lines the containing block is undefinedor css3 3122if the element has position absolute the containing block is established by the nearest ancestor with a position other than static in the following way in the case that the ancestor is inlinelevel the containing block depends on the direction property of the ancestorif the direction is ltr the top and left of the containing block are the top and left content edges of the first box generated by the ancestor and the bottom and right are the bottom and right content edges of the last box of the ancestor does not this mean that the button should appear on top of the image to the top left what part of the spec have i failed to understand when the button appears below the image,"['html', 'css']" +1209444,why does not except object catch everything in python the python language reference states in section 74 for an except clause with an expression that expression is evaluated and the clause matches the exception if the resulting object is acompatiblea with the exception an object is compatible with an exception if it is the class or a base class of the exception object or a tuple containing an item compatible with the exceptionso why does not except object catch everything object is the base class of all exception classes so except object should be able to catch every exception for example this should catch the assertionerrorprint isinstanceassertionerror object prints truetry raise assertionerrorexcept object this block should execute but it never does print caught exception,['python'] +1209744,defragment h264 nal stream originally 1722 avb packets task at hand capture 1722 avb video packets coming through ethernet port and play them as live video in android the video packets are of nal h264 streamwhat is already available the code to read the data from ethernet port and capture the packets is ready so in short i have the payload data with mewhat i am looking for c code that can analyze these nal h264 packetsidentify the start intermediate and end frames from the continuous stream of payloads combine all the related h264 nal payloads to form a video framei guess the above process is called defragmentation once defragmented i will then send this video frame to android video view and thisplay them on the screenany helpful resources will be really appreciated,['android'] +1209848,pdf not merge greater than pdf15 version using mpdf i try to merge pdf using mpdf plugin with latest version but the error coming pdf merging working when using pdf version 13 but not done for 15i have try below codephpmihirhtmlbody generate pdfs with mergebodyhtml require oncempdfmpdfphpmpdfnew mpdf mpdfsetthisplaymodefullpagempdflist indent first level 0 mpdfwritehtmlmihirmpdfaddpagempdfsetimportusepagecount mpdfsetsourcefileorder form instructions energy supplypdftplid mpdfimportpagepagecountmpdfusetemplatetplidmpdfoutputtestpdfdi am getting this errormpdf error unable to find xref table maybe a problem with auto detect line endingsthanks in advance,['php'] +1210034,visual studio c compiler generates 3x slower code when changing completely unrelated code i have a nested for loop which generates the following assembly branch target labels manually added for readability002e20f8 mov ebxesi 002e20fa mov dword ptr ebp10h3b9aca00h 002e2101 sub ebxedi 002e2103 add ebx7 002e2106 shr ebx3 002e2109 nop dword ptr eax outer loop002e2110 xor eaxeax 002e2112 xor ecxecx 002e2114 cmp ediesi 002e2116 mov edxebx 002e2118 cmova edxeax 002e211b mov eaxedi 002e211d test edxedx 002e211f je main107h 02e2137h end innerloop inner loop 002e2121 movsd xmm0mmword ptr eax 002e2125 inc ecx incaddsd swapped002e2126 addsd xmm0mmword ptr k 002e212b add eax8 002e212e movsd mmword ptr kxmm0 002e2133 cmp ecxedx 002e2135 jne main0f1h 02e2121h inner loop end innerloop 002e2137 sub dword ptr ebp10h1 002e213b jne main0e0h 02e2110h outer loopif i change a line of code before the nested for loop to simply declare an int and then print it out after the for loop this makes the compiler pull the storereload of k out of the loopthe first version of the question described this as generate the instructions in a slightly different order editors note perhaps i should leave this analysis correction for the answer003520f8 mov ebxesi 003520fa mov dword ptr ebp10h3b9aca00h 00352101 sub ebxedi 00352103 add ebx7 00352106 shr ebx3 00352109 nop dword ptr eax outer loop00352110 xor eaxeax 00352112 xor ecxecx 00352114 cmp ediesi 00352116 mov edxebx 00352118 cmova edxeax 0035211b mov eaxedi 0035211d test edxedx 0035211f je main107h 0352137h end innerloop00352121 movsd xmm0mmword ptr k load of k hoisted out of the loop strangely not optimized to xorpd xmm0xmm0 inner loop00352126 addsd xmm0mmword ptr eax0035212a inc ecx 0035212b add eax8 0035212e cmp ecxedx 00352130 jne main0f6h 0352126h inner loop00352132 movsd mmword ptr kxmm0 movsd in different place end innerloop00352137 sub dword ptr ebp10h1 0035213b jne main0e0h 0352110h outer loopthis second arrangement by the compiler is 3x faster i am slightly shocked by this does anyone know what is going onthis was compiled with visual studio 2015compiler flags i can add more if requestedoptimization maximize speed o2the codeinclude iostreaminclude vectorinclude stopwatchhstatic constexpr int and 10int main stdvectordouble buffer bufferresize10 for auto i buffer i 1e100 double k 0 int h 0 removing this line and swapping the lines stdcout time results in 3x slower code stopwatch watch for int i 0 i n i for auto j buffer k j stdcout time watchelapsedmilliseconds k stdendl stdcout time watchelapsedmilliseconds k h stdendl stdcout done stdgetchar return exit succestopwatch classpragma onceinclude chronoclass stopwatchprivate typedef stdchronohigh resolution clock clock typedef stdchronomicroseconds microseconds typedef stdchronomilliseconds milliseconds clocktime point startpublic stopwatch restart void restart start clocknow double elapsedmilliseconds return elapsedmicroseconds 1e3 double elapsedseconds return elapsedmicroseconds 1e6 stopwatchconst stopwatch delete stopwatch operatorconst stopwatch deleteprivate double elapsedmicroseconds return static castdoublestdchronoduration castmicrosecondsclocknow startcount,['c++'] +1210312,how can i change what a class inherits from at compiletime in my quest to create a crossplatform gui framework i have hit the following snagsuppose i have a central window class in the projects general platformindependent include folderincludewindowhppclass window public interfacei then have several platformdependent implementation classes like sosrcplatformwindowhppclass winwindow windowsclass osxwindow osxclass x11window unixfinally there is the original window class cpp file where i want to bind the implementation class to the general class purely conceptually this is what i want to be able to dosrcwindowcppsuppose were on windowsinclude includewindowhppinclude srcwinwindowhppclass window private winwindow redefine windows inheritancei know this is by no means valid c and that is the point i have thought of two possible ways to solve this problem and i have problems with bothpimplstyle implementationmake window hold a void pointer to an implementing class and assign that to a different window class for each platform however i would have to upcast the pointer every time i want to perform a platform dependentoperation not to mention include the platform dependent file everywherepreprocessor directivesclass window ifdef win32private winwindowelse ifdef x11private x11window etcthis however sounds more like a hack than an actual solution to the problemwhat to do should i change my design completely do any of my possible solutions hold a little bit of water,['c++'] +1210327,how can i make html5 imports work properly on firefox and ie11 i am using some features of the web platform such html imports on chrome 52 everything works fine as expected i know that there are issues with html imports on ie11 and ff 47however i have been requested to deploy my web app on ie11 for some users and here begins the pain as suggested by the few articles one can find on internet i called webcomponents polyfills in the head of my indexhtml which is the importer file script srccdnjscloudflarecomajaxlibspolymer033platformjsscriptalso in the head itselfmeta httpequivxuacompatible contentieedgeff3otherua4 the code to instantiate the link selector with dynamic content based on the app statevar link documentcreateelementlinklinkrel importlinkhrefubicacionlinkonload functione consolelogloaded import etargethreflinkonerror functione error loading import etargethrefdocumentheadappendchildlinkand when loading on ie11 i get thre error messages in console loaded import script5007 cannot get queryselector property of null reference or undefined cannot set property innerhtml of reference null or undefinedat the end of the indexhtml file i put the following codevar div documentgetelementbyidvistavar view documentqueryselectorlinkrelimportvar content viewimportvar el contentqueryselectorviewdivappendchildelclonenodetruethe funny thing is that the polyfill works because the onload message is printed instead of the onerror however there is an issue when getting the content of the imported file var el contentqueryselectorviewwhich by the way has the following code at the beginning div classview script document currentscript document currentscript documentcurrentscript var importdoc documentcurrentscriptownerdocument var maindoc documentas i stated before this works fine on chrome the problem is on ie11 and even on firefox 47 even in ff i enabled the domwebcomponentsenabled to truewhat can be improved in order to make html5 imports work fine on ie11 and ff47please note that the users require ie11 edge is not a possibilityi appreciate your answers relating to vanillajs i am not using jquery or any js wrapper thanks,['javascript'] +1210390,use of beginreceivingremotecontrolevents i saw people use uiapplication sharedapplication beginreceivingremotecontrolevents to handle remote control event when managing audio sessionmy questiondoes this code only can be used in either a uiviewcontroller class or appdelegate class because i see everyone in internet using it in one of the two classes can i use it in a class which is not subclass of uiviewcontroller or appdelegate,"['ios', 'objective-c']" +1210443,jsjquery better to run event handler in documentready or in called function note the following question is not meant to be for peoples opinion but is being asked in terms of best processing speed for the webpage jquery etci currently have code which follows the below test code formatdocumentreadyfunction myclassonclick if myclasshasclassactive myclassremoveclassactive return myclassaddclassactive my question is should the event handler not the event listener be in the same code structure as documentready or should it look like thisfunction togglerobj if objhasclassactive objremoveclassactive return objaddclassactivedocumentreadyfunction myclassonclick togglerthis ie should documentready only have the listeners which reference the handlers or should the entire action of listening and handling be in documentreadywhat is the proper way of doing this so as to maximize the usabilitypower of jquery js etc,"['javascript', 'jquery']" +1210497,collection comparison is reflexive yet does not short circuit why in python the built in collections compare elements with the explicit assumption that they are reflexivein enforcing reflexivity of elements the comparison of collections assumes that for a collection element x x x is always true based on that assumption element identity is compared first and element comparison is performed only for thistinct elements logically this means that for any list l l l must be true given this why does not the implementation check for identity to short circuit the evaluationin 1 x listrange10in 2 y listrangeintlenx 10in 3 z 1 evaluation time likes onin 4 timeit x x10 loops best of 3 218 ms per loopin 5 timeit y y100 loops best of 3 22 ms per loopin 6 timeit z z10 loops best of 3 364 ns per loopclearly child classes could choose to make an identity check and clearly an identity check would add a very small overhead to every such comparison was a historical decision explicitly made not to make such a check in the built in sequences to avoid this expense,['python'] +1210724,cannot read property tolowercase of undefined anglarjsjavascriptjson i am building angularexpress app i load data with controller and try to work with data in a function but i get error in consolecannot read property tolowercase of undefinedwhen i manually write json data it works just fineanyone had this error and why is it happeningedit also i want function to work on click when i want it not when it is loaded also i use data from listdata in view so i know it is loadedcontrollervar self this selflistdata var self this selflistdata httpgetmylistsuccessfunction data selflistdata data consolelogdataerrorfunction data consolelogerror dataselfmyfunc function var map selflistdatareducefunction p c psetcnametolowercase csurname return p new map consolelogmap,['javascript'] +1210803,drawmatching between two images image recognition i was trying to show the matched keypoints between two images one that is captured from my camera and the other from the databasecan anyone help me out in writing drawmatches function in my code in order to show the matched lines between 2 imageshere is my codepublic final class imagedetectionfilter flag draw target image cornerprivate boolean flagdraw the reference image this detectors targetprivate final mat mreferenceimage features of the reference imageprivate final matofkeypoint mreferencekeypoints new matofkeypoint descriptors of the reference images featuresprivate final mat mreferencedescriptors new mat the corner coordinates of the reference image in pixels cvtype defines the color depth number of channels and channel layout in the image here each point is represented by two 32bit floatsprivate final mat mreferencecorners new mat4 1 cvtypecv 32fc2 features of the scene the current frameprivate final matofkeypoint mscenekeypoints new matofkeypoint descriptors of the scenes featuresprivate final mat mscenedescriptors new mat tentative corner coordinates detected in the scene in pixelsprivate final mat mcandidatescenecorners new mat4 1 cvtypecv 32fc2 good corner coordinates detected in the scene in pixelsprivate final mat mscenecorners new mat4 1 cvtypecv 32fc2 the good detected corner coordinates in pixels as integersprivate final matofpoint mintscenecorners new matofpoint a grayscale version of the sceneprivate final mat mgraysrc new mat tentative matches of scene features and reference featuresprivate final matofdmatch mmatches new matofdmatch a feature detector which finds features in imagesprivate final featuredetector mfeaturedetector featuredetectorcreatefeaturedetectororb a descriptor extractor which creates descriptors of featuresprivate final descriptorextractor mdescriptorextractor descriptorextractorcreatedescriptorextractororb a descriptor matcher which matches features based on their descriptorsprivate final descriptormatcher mdescriptormatcher descriptormatcher createdescriptormatcherbruteforce hamminglut the color of the outline drawn around the detected imageprivate final scalar mlinecolor new scalar0 255 0public imagedetectionfilterfinal context context final int referenceimageresourceid throws ioexception load the reference image from the apps resources it is loaded in bgr blue green red formatmreferenceimage utilsloadresourcecontext referenceimageresourceid imgcodecscv load image color create grayscale and rgba versions of the reference imagefinal mat referenceimagegray new matimgproccvtcolormreferenceimage referenceimagegray imgproccolor bgr2grayimgproccvtcolormreferenceimage mreferenceimage imgproccolor bgr2rgba store the reference images corner coordinates in pixelsmreferencecornersput0 0 new double 00 00 mreferencecornersput1 0 new double referenceimagegraycols00 mreferencecornersput2 0 new double referenceimagegraycols referenceimagegrayrows mreferencecornersput3 0 new double 00 referenceimagegrayrows detect the reference features and compute their descriptorsmfeaturedetectordetectreferenceimagegray mreferencekeypointsmdescriptorextractorcomputereferenceimagegray mreferencekeypointsmreferencedescriptorspublic void applymat src mat dst convert the scene to grayscaleimgproccvtcolorsrc mgraysrc imgproccolor rgba2gray detect the same features compute their descriptors and match the scene descriptors to reference descriptorsmfeaturedetectordetectmgraysrc mscenekeypointsmdescriptorextractorcomputemgraysrc mscenekeypoints mscenedescriptorsmdescriptormatchermatchmscenedescriptors mreferencedescriptorsmmatchesfindscenecorners if the corners have been found draw an outline around the target image else draw a thumbnail of the target imagedrawsrc dstprivate void findscenecorners flagdraw falsefinal listdmatch matcheslist mmatchestolistif matcheslistsize 4 there are too few matches to find the homography returnfinal listkeypoint referencekeypointslist mreferencekeypointstolistfinal listkeypoint scenekeypointslist mscenekeypointstolist calculate the max and min thistances between keypointsdouble maxthist 00double minthist doublemax valuefor final dmatch match matcheslist final double thist matchthistance if thist minthist minthist thist if thist maxthist maxthist thist the thresholds for minthist are chosen subjectively based on testing the unit is not related to pixel thistances it is related to the number of failed tests for similarity between the matched descriptorsif minthist 500 the target is completely lost thiscard any previously found corners mscenecornerscreate0 0 mscenecornerstype return else if minthist 250 the target is lost but maybe it is still close keep any previously found corners return identify good keypoints and on match thistancefinal arraylistpoint goodreferencepointslist new arraylistpointfinal arraylistpoint goodscenepointslist new arraylistpointfinal double maxgoodmatchthist 175 minthistfor final dmatch match matcheslist if matchthistance maxgoodmatchthist goodreferencepointslistadd referencekeypointslistgetmatchtrainidxpt goodscenepointslist addscenekeypointslistgetmatchqueryidxpt if goodreferencepointslistsize 4 goodscenepointslistsize 4 there are too few good points to find the homography return there are enough good points to find the homography otherwise the method would have already returned convert the matched points to matofpoint2f format as required by the calib3dfindhomography functionfinal matofpoint2f goodreferencepoints new matofpoint2fgoodreferencepointsfromlistgoodreferencepointslistfinal matofpoint2f goodscenepoints new matofpoint2fgoodscenepointsfromlistgoodscenepointslist find the homographyfinal mat homography calib3dfindhomography goodreferencepointsgoodscenepoints use the homography to project the reference corner coordinates into scene coordinatescoreperspectivetransformmreferencecorners mcandidatescenecornershomography convert the scene corners to integer format as required by the imgprociscontourconvex functionmcandidatescenecornersconverttomintscenecorners cvtypecv 32s check whether the corners form a convex polygon if not that is if the corners form a concave polygon the detection result is invalid because no real perspective can make the corners of a rectangular image look like a concave polygonif imgprociscontourconvexmintscenecorners the corners form a convex polygon so record them as valid scene corners mcandidatescenecornerscopytomscenecorners flagdraw trueprotected void drawfinal mat src final mat dst if dst src srccopytodst outline the found target in greenimgproclinedst new pointmscenecornersget0 0 new point mscenecornersget1 0 mlinecolor 4imgproclinedst new pointmscenecornersget1 0 new point mscenecornersget2 0 mlinecolor 4imgproclinedst new pointmscenecornersget2 0 new point mscenecornersget3 0 mlinecolor 4imgproclinedst new pointmscenecornersget3 0 new point mscenecornersget0 0 mlinecolor 4public boolean getflagdrawreturn flagdraw,"['java', 'android']" +1211038,normalizing the data from denormalized table i have data in my table like thisrepidrolestatusstartdate enddate 101r1 active0101201501312015101r1 leavee0201201502122015101r1 active0213201502282015101r2 active0301201503182015101r2 leave 0319201504102015101r2 active0411201505102015101r1 active0511201506132015101r1 leave 06142015123198i am looking for the output like thisrepidrolestartdate enddate 101r1 0101201502282015 101r2 0301201505102015 101r1 05112015123198whenever only the role change happens i need to capture the start and enddate i tried different ways but could not get the outputany help is appreciatedbelow is the sql i tried with but it doesnt helpselect t1repid t1role mint1startdate as startdate maxt1enddate as enddatefrom select rd1repid rd1role rd1startdate rd1enddate from repdetails rd1inner join repdetails rd2 on rd2repid rd1repid and rd2startdate dateadd day 1 rd1enddate and rd2role rd1role or rd2role is null and rd1role is null or rd2role and rd1role unionselect rd2repid rd2role rd2startdate rd2enddate from repdetails rd1inner join repdetails rd2 on rd2repid rd1repid and rd2startdate dateadd day 1 rd1enddate and rd2role rd1role or rd2role is null and rd1role is null or rd2role and rd1role t1group by t1repid t1roleunionselect eprepid eprole as datavalue epstartdate ependdatefrom repdetails epleft outer join select rd1repid rd1role rd1startdate rd1enddate from repdetails rd1inner join repdetails rd2 on rd2repid rd1repid and rd2startdate dateadd day 1 rd1enddate and rd2role rd1role or rd2role is null and rd1role is null or rd2role and rd1role unionselect rd2repid rd2role rd2startdate rd2enddate from repdetails rd1inner join repdetails rd2 on rd2repid rd1repid and rd2startdate dateadd day 1 rd1enddate and rd2role rd1role or rd2role is null and rd1role is null or rd2role and rd1role t1on eprepid t1repid and epstartdate t1startdatewhere t1repid is null,['sql'] +1211188,is the strict aliasing rule incorrectly specified as previously established a union of the formunion some union type a member a type b member b with n members comprises n 1 objects in overlapping storage one object for the union itself and one object for each union member it is clear that you may freely read and write to any union member in any order even if reading a union member that was not the last one written to the strict aliasing rule is never violated as the lvalue through which you access the storage has the correct effective typethis is further supported by footnote 95 which explains how type punning is an intended use of unionsa typical example of the optimizations enabled by the strict aliasing rule is this functionint strict aliasing exampleint i float f i 1 f 10 return iwhich the compiler may optimize to something likeint strict aliasing exampleint i float f i 1 f 10 return 1because it can safely assume that the write to f does not affect the value of ihowever what happens when we pass two pointers to members of the same union consider this example assuming a typical platform where float is an ie 754 single precision floating point number and int is a 32 bit twos complement integerint breaking examplevoid union int i float f fi return strict aliasing examplefii fifas previously established fii and fif refer to an overlapping memory region reading and writing them is unconditionally legal writing is only legal once the union has been initialized in any order in my opinion the previously thiscussed optimization performed by all major compilers yields incorrect code as the two pointers of different type legally point to the same locationi somehow cannot believe that my interpretation of the strict aliasing rule is correct it does not seem plausible that the very optimization the strict aliasing was designed for is not possible due to the aforementioned corner caseplease tell me why i am wronga related question turned up during researchplease read all existing answers and their comments before adding your own to make sure that your answer adds a new argument,['c'] +1211440,find integer solutions to a set of equations with more unkowns than equations i am trying to build a system for which i need to find a solution to a set of linear equations with much more variables than equations the problem boils down to the followingimagine a set of equationsa a1x1 a2x2 anxnb b1x1 b2x2 bnxnhow can i find one or multiple positive integer solutions to this system note i have been looking at the apachecommonsmath library but i could not find any directions on how to solvefind a solution of a system with free variables,['java'] +1211678,how to use volatile correctly in java i am studying java thread and the keyword volatile confuses me when i analyse the following code modified from example 8314public class volatile public static void mainstring args myrunnable1 myrunnable1 new myrunnable1 myrunnable2 myrunnable2 new myrunnable2 thread t1 new threadmyrunnable1 thread t2 new threadmyrunnable2 t1start t2start class myrunnable1 implements runnable public void run whiletrue test1one class myrunnable2 implements runnable public void run whiletrue test1two class test1 static volatile int i 0 static volatile int j 0 static void one i j static void two systemoutprintlni i j j an output segment i 60778110 j 60778116i 60778402 j 60778407i 60778630 j 60778636i 60779062 j 60779079i 60779492 j 60779497i 60779784 j 60779789i 60780161 j 60780169i 60780625 j 60780632i 60780936 j 60780942my thought is that because of the volatile the i happens before j their initial values are zero and the modified values will be flushed to the main memory immediately so anytime the i thread t2 sees should be greater than j however the output shows the i is always lower than jthen i modify the two function as followstatic void two systemoutprintlnj j i ithe change is that j outputs prior to i then output segment as followj 47324409 i 47324412j 47324587 i 47324593j 47324808 i 47324813j 47324991 i 47324996j 47325193 i 47325196j 47325347 i 47325353it surprises me that j is always lower than imy thought is that the j is lower because it is connected first and after a while the i is connected during the time gap the one function executes which causes i increasedso the first connected value will be lower than the second connected one is it right thanks in advance,['java'] +1211842,transpose javascript array and object how is a javascript array and object transposed specifically i am trying to convert the follow x and y arrayobjects to the new desired x new and y new arrayobjectsgivenvar xx1x2x3var y namey1datax1y1x2y1x3y1 namey2datax1y2x2y2x3y2consolelogxydesiredvar new x namex1datax1y1x1y2 namex2datax2y1x2y2 namex3datax3y1x3y2var new yy1y2consolelognew xnew ybelow is what i attemptedvar x yfor var i 0 i ylength i ypushyiname var data for var j 0 j yidatalength j datapushyidataj xpushnameyinamedatadataconsolelog x y,['javascript'] +1211944,how do we authenticate against a secured nuget server with cake build we are working on automating our builds using cake build and we use nuget packages from nugetorg but we also have our own nuget feed server which has a usernamepassword authentication to access how do we utilize cake build with a custom nuget feed server with authentication,['c#'] +1211997,use requests module in python to log in to barclays premier league fantasy football i am trying to write a python script to let me log in to my fantasy football account at but something is not quite right with my log in when i login through my browser and check the details using chrome developer tools i find that the request url is and the form data sent iscsrfmiddlewaretokenmy tokenloginmy usernamepasswordmy passwordaplfplwebredirect urithere are also a number of request headersaccepttexthtmlapplicationxhtmlxmlapplicationxmlq09imagewebpq08acceptencodinggzip deflate bracceptlanguageenusenq08cachecontrolmaxage0connectionkeepalivecontentlength185contenttypeapplicationxwformurlencodedcookiemy cookieshostuserspremierleaguecomoriginrefererupgradeinsecurerequests1useragentmozilla50 windows nt 61 wow64 applewebkit53736 khtml like gecko chrome5202743116 safari53736so i have written a short python script using the request library to try to log in and navigate to a page as followsimport requestswith requestssession as sessionurl home html home sessiongeturl homecsrftoken sessioncookiescsrftokenvalues csrfmiddlewaretoken csrftoken login my username password my password app plfplweb redirect uri head hostuserspremierleaguecom referer sessionpost data values headers headurl transfers html transfers sessiongeturl transfersprinthtml transferscontenton printing out the content of my post request i get a html response code 500 error withbnhtmlnheadntitlefastly error unknown domain userspremierleaguecomtitlenheadnbodynfastly error unknown domain userspremierleaguecom please check that this domain has been added to a servicebodyhtml if i remove the host from my head dict i get a html response code 405 error withbi have tried including various combinations of the request headers in my head dict and nothing seems to work,['python'] +1212093,how to write directive on class in angular js the restrict option is typically set toa only matches attribute namee only matches element namec only matches class namem only matches comment c only matches class name is not working classformcontrol validvehicleyear ngnotempty ngdirty ngvalidparse ngvalid ngvalidrequired ngtouchedi created a directive on class associated with element on change of value i want to call a api and change value of other element but no change is observed on changecontroldirectivejs function validvehicleyearscope http return restrict c scope ngmodel link function scope element attrs ngmodel elementbindchange function consoleloghere in validvehicleyear httpgetapiphpscopengmodel thenfunction response scopeanswersvehiclemake responsedata vehicle year question has a class validvehicleyear what i am missing here or is there any other to this on change of answersvehicleyeari wrote a directive validvehicleyear on class at vehicle year question this i want to call on change of year and set new options for vehicle make but it not workingplnkrcoeditbfgxr7lnae0kvqipj9jjppreviewi checked around and found that outerinner directive concept can work here but not getting how to apply for the dynamic classes,"['javascript', 'jquery']" +1212154,upload multiple images to server in a queue use case upload images in a queue in background to the server images can be web urls or image file stored on the phones memorywhat i want limit the number of items in queue to 3 and show blurred images as placeholders for the actual images being uploaded in a recyclerview in an activity with a progress bar on each placeholder indicating how much of it has been uploaded on top of every placeholder are three buttons to either pause cancel or resume the upload of the imagecurrent situation right now i was using multipart in retrofit 190 to upload images and this service call was being done inside the activityi am not able to figure out how to cancel pause or resume a multipartpost request using retrofit or any other library in general and how to tie a ui event with an api service thread i can update the ui from service but how do i update something in the service from an event in ui pauseresumecancelhow should i proceed with this use case do i need to use service can i show progress indicators in another activity based on the requests being executed in the service what should be the architecture for this processi do not need the code for it but if there are some useful references related to this i would like to read and test it out to finally derive my approach,['android'] +1212296,const member function and typedef c suppose we want to declare const member function via typedeftypedef int fc consttypedef int fstruct a fc fc fine we have int fc const const f fc not fine const is ignored so we have int fcsince const is ignored the program compiles fine why const is ignored for function since we can form const pointer in this way the only thing i can think of is c heritage does standard say anything about it,['c++'] +1212518,how to do the conditional variable initialization at compiler time c11 standard have stdconditional template for the type selection by the some boolean condition at compiler time how to do the same operation but for select the init value for variable initialization similar to type a exp first value second valuei use my templatetemplatebool b typename tinline constexpr t conditional initializet i1 t i2 return b stdmovei1 stdmovei2but it can be used only for pod types int a conditional initializetrue1 2for array initialization this template is compiled with error wrong compile example int a conditional initializetrue1 2 345 error message no matching function for call to conditional initializebraceenclosed initializer list braceenclosed initializer listwho can help me with template,['c++'] +1212615,is operator behaves unexpectedly with floats i came across a confusing problem when unit testing a module the module is actually casting values and i want to compare this valuesthere is a difference in comparison with and is partly i am beware of the difference 00 is 00true as expected float00 is 00true as expectedas expected till now but here is my problem float0 is 00false float0 is float0falsewhy at least the last one is really confusing to me the internal representation of float0 and float00 should be equal comparison with is working as expected,['python'] +1212665,is there a shorthand for stdlock guard lockm exactly what the question states in c ideally 11 but curious about 14 and later too is there a shorthand syntax forstdmutex somemutexstdlock guardstdmutex lgsomemutexideally something that infers the type of mutex to avoid the refactoring if i ever wanted to change to a stdrecursive mutexin other words a way to do thisstdmutex somemutexstdlock guard lgsomemutexorauto lg make lock guardsomemutexfor all the type deduction powers of modern c it just seems awfully redundant to go typing stdlock guardstdmutex every time i want to make one,['c++'] +1212692,c function argument safety in a function that takes several arguments of the same type how can we guarantee that the caller does not mess up the orderingfor examplevoid allocate thingsint num buffers int pages per buffer int default value and later uhmm lets see which was which uhhallocate things402280,['c++'] +1212914,how to get parse the values of itunes eq presets we are trying to implement a music player app with equalizer presets we are successful in getting presets from ipod and applying it through audio unit but now we need to thisplay sliders and set frequency with respect to the selected preset but we are not aware of the values which need to be set to sliders for a particular frequency we need to achieve this kind of ui the slider need to update with preset value changethanks in advance,"['ios', 'iphone']" +1213028,gcc fails to compile generic lambda with this capture i cannot compile the following program with gcc 61include iostreaminclude stringinclude vectorinclude iteratorinclude algorithmclass foopublic void apply const stdfor eachstdcbeginbars stdcendbars this const auto x printx private stdvectorstdstring bars void printconst stdstring x const stdcout x int main foo foo fooapply return 0the error message iserror cannot call member function void fooprintconst string const without object stdfor eachstdcbeginbars stdcendbars this const auto x printx changing const auto x to const stdstring x makes the program compilechanging printx to thisprintx makes the program compileall versions compile with clang apple llvm version 730 clang703031is this a compiler bug,['c++'] +1213112,convert float to string without scientific notation and false precision i want to print some floating point numbers so that they are always written in decimal form eg 123450 or 012345 not in scientific notation yet i would want to keep the 157 decimal digits of precision and no moreit is wellknown that the repr of a float is written in scientific notation if the exponent is greater than 15 or less than 4 and 054321654321 n54321654321e08 scientific notationif str is used the resulting string again is in scientific notation strn54321654321e08it has been suggested that i can use format with f flag and sufficient precision to get rid of the scientific notation format05 20f050it works for that number though it has some extra trailing zeroes but then the same format fails for 1 which gives decimal digits beyond the actual machine precision of float format01 20f0105and if my number is 45678e20 using 20f would still lose relative precision format45678e20 20f05thus these approaches do not match my requirementsthis leads to the question what is the easiest and also wellperforming way to print arbitrary floating point number in decimal format having the same digits as in reprn or strn on python 3 but always using the decimal format not the scientific notationthat is a function or operation that for example converts the float value 05 to string 05 01 to 01 420 to 420 or 420 and formats the float value 45678e5 as 045678after the bounty period it seems that there are at least 2 viable approaches as karin demonstrated that using string manipulation one can achieve significant speed boost compared to my initial algorithm on python 2thusif performance is important and python 2 compatibility is required or if the decimal module cannot be used for some reason then karins approach using string manipulation is the way to do iton python 3 my somewhat shorter code will also be fastersince i am primarily developing on python 3 i will accept my own answer and shall award karin the bounty,['python'] +1213134,combine two language text i have two text one in hebrew language and one in englishin first text i have date that is in hebrew nsdateformatter dateformatter nsdateformatter alloc init nslocale hebrew nslocale alloc initwithlocaleidentifierhe il hebrew dateformatter setdateformatymmddthhmmsz nsdate date dateformatter datefromstringmodelstartdate nslog date dateformatter setdateformateddmmy dateformatterlocale hebrew nsstring strdate dateformatter stringfromdatedateand start date is 19082016 in nstring object strdateon other hand i have text 07 0016 00 in nsstring object timeforrequest my needed format is 15012016 1600 0700and when i try to do same with following code nsstring stringwithformat strdatetimeforrequestit shows me like this 19082016 07 0016 00observe the time is not correct please help me to come out from this wired situation thanks in advance,['ios'] +1213182,where are the nullterminated strings when converting from c to assembly i made two programs to output two strings one in assembly and the other one in cthis is the program in assemblysection datastring1ascii hola0string2ascii adios0section textglobl start startpushl string1call putsaddl 4 esppushl string2call putsaddl 4 espmovl 1 eaxmovl 0 ebxint 0x80i build the program withas tests o testold dynamiclinker libldlinuxso2 o test testo lcand the output is as expectedholaadiosthis is the c programinclude stdiohint mainvoid putshola putsadios return 0and i get the expected output but when converting this c program to assembly with gcc s os is debian 32 bit the output assembly source code does not include the null character in both strings as you can see here file testcc section rodatalc0 string holalc1 string adios text globl main type main functionmainlfb0 cfi startproc leal 4esp ecx cfi def cfa 1 0 andl 16 esp pushl 4ecx pushl ebp cfi escape 0x100x50x20x750 movl esp ebp pushl ecx cfi escape 0xf0x30x750x7c0x6 subl 4 esp subl 12 esp pushl lc0 call puts addl 16 esp subl 12 esp pushl lc1 call puts addl 16 esp movl 0 eax movl 4ebp ecx cfi def cfa 1 0 leave cfi restore 5 leal 4ecx esp cfi def cfa 4 4 ret cfi endproclfe0 size main main ident gcc debian 49210 492 section notegnustackprogbitsmy two questions are1 why the gcc generated assembly code does not append the null character at the end of both strings i thought that c did this automatically2 if i skip the null characters in my hand made assembly code i get this outputholaadiosadiosi understand why i get the holaadios part at the first line but why does the program end successfully after the adios part if it is not nullterminated,['c'] +1213187,how to sort sql query alphabetically but ignoring leading numbers i am unable to find the right query for my problem i have a table in the db and i need to sort it in a very specific manner the column i am sorting is an address and it starts with the number but i need to sort it ignoring the numberhere is my data setid address1 23 bridge road2 14 kennington street3 7 bridge road4 12 oxford street5 9 bridge roadi need to sort this likeid address1 7 bridge road2 9 bridge road 3 23 bridge road4 14 kennington street5 12 oxford streetso far i got only thisselect id addressfrom propertysearchorder by address asc can anyone help me out on this,['sql'] +1213239,paste from word to extjs editor and i found one more issue with extjs editorwhen i copy the ol typea stylemargintop 0pt marginbottom 0pt li stylelineheight 115 fontsize 11pt margintop 0pt marginbottom 10ptspan stylefontfamily calibri fontsize 11ptmain heading 1spanli ol p stylemargin 0pt 0pt 10pt 72pt lineheight 115 textindent 18pt fontsize 11ptspan stylefontfamily calibri fontsize 11pt1spanspan stylefont 7ptnormal times new roman fontsizeadjust none fontstretch normalnbspnbspnbspnbspnbspnbsp spanspan stylefontfamily calibri fontsize 11ptitem 1spanp p stylemargin 0pt 0pt 10pt 72pt lineheight 115 textindent 18pt fontsize 11ptspan stylefontfamily calibri fontsize 11pt2spanspan stylefont 7ptnormal times new roman fontsizeadjust none fontstretch normalnbspnbspnbspnbspnbspnbsp spanspan stylefontfamily calibri fontsize 11ptitem 2spanp p stylemargin 0pt 0pt 10pt 72pt lineheight 115 textindent 18pt fontsize 11ptspan stylefontfamily calibri fontsize 11pt3spanspan stylefont 7ptnormal times new roman fontsizeadjust none fontstretch normalnbspnbspnbspnbspnbspnbsp spanspan stylefontfamily calibri fontsize 11ptitem 3spanp ol typea stylemargintop 0pt marginbottom 0pt start2 li stylelineheight 115 fontsize 11pt margintop 0pt marginbottom 10ptspan stylefontfamily calibri fontsize 11ptmain heading 2spanli ol p stylemargin 0pt 0pt 10pt 72pt lineheight 115 textindent 18pt fontsize 11ptspan stylefontfamily calibri fontsize 11pt1spanspan stylefont 7ptnormal times new roman fontsizeadjust none fontstretch normalnbspnbspnbspnbspnbspnbsp spanspan stylefontfamily calibri fontsize 11ptitem 1spanp p stylemargin 0pt 0pt 10pt 72pt lineheight 115 textindent 18pt fontsize 11ptspan stylefontfamily calibri fontsize 11pt2spanspan stylefont 7ptnormal times new roman fontsizeadjust none fontstretch normalnbspnbspnbspnbspnbspnbsp spanspan stylefontfamily calibri fontsize 11ptitem 2spanp p stylemargin 0pt 0pt 10pt 72pt lineheight 115 textindent 18pt fontsize 11ptspan stylefontfamily calibri fontsize 11pt3spanspan stylefont 7ptnormal times new roman fontsizeadjust none fontstretch normalnbspnbspnbspnbspnbspnbsp spanspan stylefontfamily calibri fontsize 11ptitem 3spanpand pasted in extjs htmleditor its converted as ol styleliststyletype upperalpha direction ltr li stylecolor rgb0 0 0 fontstyle normal fontweight normal p stylecolor rgb0 0 0 fontstyle normal fontweight normal margintop 0in marginbottom 0pt msolist l2 level1 lfo1main heading 1 p li ol pfont facetimes new roman size3 brfont p ol styleliststyletype decimal direction ltr li stylecolor rgb0 0 0 fontstyle normal fontweight normal p stylecolor rgb0 0 0 fontstyle normal fontweight normal margintop 0in marginbottom 0pt msolist l5 level1 lfo2 msoaddspace autoitem 1 p li li stylecolor rgb0 0 0 fontfamily calibrisansserif fontsize 11pt fontstyle normal fontweight normal p stylecolor rgb0 0 0 fontfamily calibrisansserif fontsize 11pt fontstyle normal fontweight normal margintop 0in marginbottom 0pt msolist l5 level1 lfo2 msoaddspace autoitem 2 p li li stylecolor rgb0 0 0 fontfamily calibrisansserif fontsize 11pt fontstyle normal fontweight normal p stylecolor rgb0 0 0 fontfamily calibrisansserif fontsize 11pt fontstyle normal fontweight normal margintop 0in marginbottom 0pt msolist l5 level1 lfo2 msoaddspace autoitem 3 p li ol pfont facetimes new roman size3 brfont p ol styleliststyletype upperalpha direction ltr li stylecolor rgb0 0 0 fontstyle normal fontweight normal p stylecolor rgb0 0 0 fontstyle normal fontweight normal margintop 0in marginbottom 0pt msolist l2 level1 lfo1main heading 2 p li ol pfont facetimes new roman size3 brfont p ol styleliststyletype decimal direction ltr li stylecolor rgb0 0 0 fontstyle normal fontweight normal p stylecolor rgb0 0 0 fontstyle normal fontweight normal margintop 0in marginbottom 0pt msolist l7 level1 lfo3 msoaddspace autoitem 1 p li li stylecolor rgb0 0 0 fontfamily calibrisansserif fontsize 11pt fontstyle normal fontweight normal p stylecolor rgb0 0 0 fontfamily calibrisansserif fontsize 11pt fontstyle normal fontweight normal margintop 0in marginbottom 0pt msolist l7 level1 lfo3 msoaddspace autoitem 2 p li li stylecolor rgb0 0 0 fontfamily calibrisansserif fontsize 11pt fontstyle normal fontweight normal p stylecolor rgb0 0 0 fontfamily calibrisansserif fontsize 11pt fontstyle normal fontweight normal margintop 0in marginbottom 0pt msolist l7 level1 lfo3 msoaddspace autoitem 3 p li olplease suggest me for this as well to get rid of formatting issues while copy paste from word to editor,['javascript'] +1213405,flot labels overlapping with my line graph iam using the line graph feature of flot but iam having some difficulty keeping my x and yaxis labels from overlapping onto the graph my graph looks like thisideally i would like to move the labels to the left and bottom so that they donat overlap with the graph iam constructing the graph like sofunction js data ids user my objectseach do user my object idspush user my objectid my object day time in ms user my objectmy objectdaystrftimeq js datapush my object day time in ms user my objecttime in ms end ids var data h js datajoin div idtooltipdivcss position absolute thisplay none border 1px solid fdd padding 2px backgroundcolor fee opacity 080 appendtobody plotplaceholder data yaxis tickformatter formattime xaxis mode time points show true lines show true grid hoverable true clickable true tickcolor efefef borderwidth 0 bordercolor efefef tooltip true placeholderbindplothover function event pos item if item var x itemdatapoint0tofixed2 y itemdatapoint1tofixed2 consolelogx x dateobj new dateparseintx var datestr datepickerformatdatemm dd yy dateobj tooltiphtml datestr formattimey csstop itempagey5 left itempagex5 fadein200 else tooltiphide edit alas the elusive fiddle,['jquery'] +1213512,how to apply css changes in order i sometimes come across cases where i want to apply several changes to the css in immediate succession making sure that each one is registered by the rendererheres a simplified examplethe height of the element is auto so it cannot be transitioned from so i would want to set the elements height to the current computed height and then immediately change the class to start the transition if that happens in the next line of code the cssrenderer does not have time to react to the first change and it is as if only the class was changed no transitionvar foo foofoo0addeventlistenerclick functionev foocssheightfooheightpx fooaddclassactive this does not work foocssa is ignoredwe can delay to the smallest animatable timestep with windowrequestanimationframe however due to browser differences these already need two nested calls to support firefoxvar dan dandan0addeventlistenerclick functionev windowrequestanimationframefunction dancssheightdanheightpx windowrequestanimationframefunction danaddclassactive this does work afai can tell but feels overdone with all that nestingtechnically this code works i am just wondering if this is really the best way to chain css changes like this or if there are other methods,"['javascript', 'css']" +1213902,editing json search results from within angular i am now pulling data from a external json url properly to the master page but my detail page does not seem to pass on the object initallt received from httpget this master part of the app can be viewed in a code pen at codepenlabel classitem iteminputi classicon ionsearch placeholdericoniinput typesearch ngmodelquery placeholdersearch slugnamebutton classbutton buttondark ngclickgetorderssubmitbuttonlabelif my user wanted to change the dateorderdatevalue manually to say 10816 how can i accessedit any of the json values that are returned from the external apii eventually wish to edit the returned json data within my app and then post that revised data back to a php api server,['javascript'] +1214007,error could not get batchedbridge make sure your bundle is packaged properly on start of app trying to create a reactnative project on android 442 i get this error screenand could not find any way to resolve it i tried restarting packager reconnecting device even reinstalling react native and starting new project on 600 and later versions it works just fine,['android'] +1214163,css resizing images keeping formation i have a formation of images as seen herethe following is the html secondpanel is the main wrapper which has the background image of the building each diamondshaped image is positioned absolutely using css with pixel values second panel div idsecondpanel classparallaxwrapper div idsecondpaneldiamonds img clasecondpaneldiamond srcimagesfurnitureminpng altfurniture img clasecondpaneldiamond srcimagesautomobileminpng altautomobile img clasecondpaneldiamond srcimagesjewelryminpng altjewelry img clasecondpaneldiamond srcimagesantiqueminpng altantique div div classparallaxpanel not relevant div divcsecondpaneldiamonds position absolute left 1 top 5pxsecondpanel secondpaneldiamond position absolute width 22 width auto height auto maxwidth 350pxsecondpaneldiamondfirstchild top 250px left 90pxsecondpaneldiamondnthchild2 top 80px left 260pxsecondpaneldiamondlastchild left 337px top 337pxthe problem is when it comes to smaller screen sizes as the images will obviously start to overflow since they are given a fixed width and height i tried setting them to a percentage width and height auto but then of course they break formation as they get smaller i tried setting their positions using percentage values as well but it does not scale properly according to the resizing of the images and the resizing of the windowis there any way to maintain this formation while scaling the images down or will i have to just redesign it for smaller screens,"['javascript', 'html', 'css']" +1214250,what does stdcout stdcin do i am new to c and was messing around with some of the things that i have learntso i tried the following codeinclude iostreamint main stdcout stdcinso i expected the code to return an error but instead got what i think is a memory address 0x6fc408 also when running it multiple times i got the same memory address even after restarting cmd what exactly does this memory address signify,['c++'] +1214426,specyfing java version in maven differences beetwen properties and compiler plugin i am not very experienced with maven and while experimenting with multimodule project i started wondering how can i specify java version for all my child modules in parent maven pom until today i was using justproperties javaversion18javaversionpropertiesbut when researching i found that you can also specify java version in maven compiler plugin like thatplugins plugin artifactidmavencompilerpluginartifactid configuration source18source target18target configuration pluginpluginsand then wrap this into plugin management tag to enable child poms usage of this so the first question is what are the differences beetwen setting java version in properties and in maven compiler plugini could not find clear answer but in process of researching i found that you can also specify java version in this wayproperties mavencompilersource18mavencompilersource mavencompilertarget18mavencompilertargetpropertieswhich suggest that compiler plugin is there even if i dont explicit declare it running mvn package outputs with mavencompilerplugin31compile defaultcompile testproj and some other plugins that i did not declare so are those plugins default hidden part of maven pom are there any differences beetwen setting sourcetarget in properties and in maven plugin configuration elementsome other questions are which way should be used and when if they are not equal which one is best for multimodule project and what happens if java version specified in pom is different than version pointed in java home,['java'] +1214462,scss nthchild mixin with array so i was hoping someone could help me out with something that seemed simple i have a grid template set up with ads coming in in various locations causing the structure of the code to be a bit complicated basically right now for me to get it looking just right i am using quite a bit of nthchild selectors to remove ad margins at various breakpoints instead of me writing out things such asnthchild 3 nthchild 10 nthchild 13 nthchild 17 nthchild 20 nthchild 23 nthchild 26 nthchild 30 nthchild 33 nthchild 37 nthchild 43 marginright gutterwidth i have been trying to create a mixing that would allow me to pass an array of integers and for the css to spit out what i showed above by calling something along the lines of include nthchildren 3 10 13 17 20 marginright gutterwidththe only issue is that i also would need to be able to pass an equation as part of that list 20n 5 or whatever the case may bei have tried a few things but cannot seem to even get it closemixin nthchildrennths for i from 1 through lengthnths nthchildi content i want to prevent of creating a list first since the values will be ever changing on multiple different screen sizes and page layouts thanks in advanced,['css'] +1214519,what should happen with await when the expression after the keyword does not evaluate to promise i have a es7 code like thisasync function returnsfive var three 3 var threep await three return threep2returnsfivethenkconsolelogk econsoleerrorerr ewhat should happen at the var threep await three lineshould the code continue as expected or fail because three is not a promisein this repo it is mentioned as debatable syntax semantics i am not able to read through the official documentation to find the exact definition since it is too technicaldefault babeljs transformation logs 5 as expected however nodent a different transform prints typeerror threethen is not a function which is correct and why,['javascript'] +1214778,search icon in edit control overlapped by input area i am trying to make a search edit control in mfc that has an icon thisplayed in the control window all the time regardless the state and text of the control i have written something like this many years ago and worked very well but the code no longer works on windows 7 and newer maybe even vista but did not try that what happens is that the image shown in the control is overlapped with the input area see the picture belowthe idea behind the codehave a class derived from cedit that handles painting in onpaintthe icon is thisplayed on the right and the edit area is shrunk based on the size of the iconresizing is done differently for singleline and multiline edits for single line i call setmargins and for multiline edits i call setrectthis edit resizing is applied in presubclasswindow onsize and onsetfontthis is how the edit input size is appliedvoid csymboleditrecalclayout int width getsystemmetrics sm cxsmicon ifm hsymbolicon if getstyle es multiline crect editrect getrecteditrect editrectright width 6 setrecteditrect else dword dwmargins getmargins setmarginsloworddwmargins width 6 the following image shows the problem with the single line edits the images have been zoomed in for a better view the yellow background is for highlighting purposes only in real code i am using the color window system color you can see that when the single line edit has text and has the input the left side image is painted over this does not happen with the multiline edit where setrect correctly sets the formatting rectanglei have tried using excludecliprect to remove the area of the edit where the image is being thisplayedcrect rcgetclientrectrccpaintdc dcthisexcludecliprectdcm hdc rcright width 6 rctop rcright rcbottomdword dwmargins getmarginssetmarginsloworddwmargins width 6this does not seem to have any effect on the resultfor reference this is the painting method written years ago and used to work well on windows xp but not correct any morevoid csymboleditonpaint cpaintdc dcthis crect rect getclientrect rect clearing the background dcfillsolidrect rect getsyscolorcolor window dword dwmargins getmargins if m hsymbolicon drawing the icon int width getsystemmetrics sm cxsmicon int height getsystemmetrics sm cysmicon drawiconex dcm hdc rectright width 1 1 m hsymbolicon width height 0 null di normal rectleft loworddwmargins 1 rectright width 7 else rectleft loworddwmargins 1 rectright hiworddwmargins 1 cstring text getwindowtexttext cfont oldfont null recttop 1 iftextgetlength 0 ifthis getfocus m strprompttextgetlength 0 oldfont dcselectobjectm fontprompt colorref color dcgettextcolor dcsettextcolorm colorprompttext dcdrawtextm strprompttext rect dt leftdt singlelinedt editcontrol dcsettextcolorcolor dcselectobjectoldfont else ifgetstyle es multiline ceditonpaint else oldfont dcselectobjectgetfont dcdrawtexttext rect dt singleline dt internal dt editcontrol dcselectobjectoldfont i have looked at other implementations of similar edit controls and they all have the same fault now obviously the question is how do i exclude the image area from the input area of the control,['c++'] +1214787,packet loss while receiving udp broadcast in android device for receiving udp broadcast packets from the server to an android device i used a service class and listen for packets in a thread it receives the packet successfully the problem is that if multiple packets are being sent from the server in the same time then packet loss will be the resulti even tried with a queue and processing the received packets in separate thread then also i am not getting the packet i am completely new to network programming any help would be widely appreciatedvoid startlistenforudpbroadcast udpbroadcastthread new threadnew runnable public void run try inetaddress broadcastip inetaddressgetbynameudpconstantsip address integer port udpconstantsreceiver port while shouldrestartsocketlisten listenandwaitandthrowintentbroadcastip port catch exception e logiudp no longer listening for udp broadcasts cause of error egetmessage udpbroadcastthreadsetprioritythreadmax priority setting the listener thread to max priority to minimize packet loss udpbroadcastthreadstart this code listens for new packets and pushes to queueprivate void listenandwaitandthrowintentinetaddress broadcastip integer port throws exception byte recvbuf new byte640 if socket null socketisclosed socket new datagramsocketport broadcastip socketsetbroadcasttrue socketsetsotimeout10 datagrampacket packet new datagrampacketrecvbuf recvbuflength socketreceivepacket messqueueaddpacket this checks the queue for new messages and process it purpose checking queue and if anything is added to the queue then broadcast it to ui private void checkqueue queuethread new threadnew runnable public void run try while shouldrestartsocketlisten if messqueueisempty broadcastintentmessqueuepoll catch exception e queuethreadstart,['android'] +1215104,process request thread error with flask application this might be a long shot but heres the error that i am getting file homemy nameanacondalibpython27socketserverpy line 596 in process request thread selffinish requestrequest client address file homemy nameanacondalibpython27socketserverpy line 331 in finish request selfrequesthandlerclassrequest client address self file homemy nameanacondalibpython27socketserverpy line 654 in init selffinish file homemy nameanacondalibpython27socketserverpy line 713 in finish selfwfileclose file homemy nameanacondalibpython27socketpy line 283 in close selfflush file homemy nameanacondalibpython27socketpy line 307 in flush self socksendallviewwrite offsetwrite offsetbuffer sizeerror errno 32 broken pipei have built a flask application that takes addresses as input and performs some string formatting manipulation etc then sends them to bing maps to geocode through the geopy external modulei am using this application to clean very large data sets the application works for inputs of usually 1500 addresses inputted 1 per line by that i mean that it will process the address and send it to bing maps to be geocoded and then returned after around 1500 addresses the application becomes unresponsive if this happens while i am at work my proxy tells me that there is a tcp error if i am on a non work computer it just does not load the page if i restart the application then it functions perfectly fine because of this i am forced to run my program with batches of about 10 addresses just to be safe because i am not sure yet of the exact number that the program crashes atdoes anyone have any idea what might be causing it i was thinking something along the lines of me hitting my bing api key limit for the day which is 30 but that cannot be accurate as i rarely use more than 150 requests per daymy second thought was that maybe it is because i am still using the standard flask server to run my application would switching to gunicorn or uwsgi solve thismy third thought was maybe it was getting overloaded with the amount of requests i tried to sleep the program for 15 seconds or so after the first 10 addresses but that did not solve anythingif anyone needs further clarification please let me knowhere is my code for the backend of the flask application i am getting the input from this functionapprouteclean methodspostdef dothing addresses requestformaddresses return cleanaddressaddresseshere is the cleanaddress function it is a bit cluttered right now with all of the if statements to check for specific typos in the address but i plan on moving a lot of this code into other functions in another file and just passing the address though those functions to clean it up a bitdef cleanaddressaddresses counter 0 nested helper function to fix addresses such as 30 w 60th def check staddress if broadway in address return address has th st nd rd recompilerpnumberd14thstndrdspfollowing has number has th st nd rdsearchaddress if has number is not none if rematchrstreetstfloor has numbergroupfollowing return address else new address resubpnumberd14stndrdths rgnumberstreet address 1 return new address else return address addresses addressessplitn cleaned success 0 fail 0 cleanedappendbody bgcolorfacc2ecenterimg src altsmiley face height100 width350brp cleanedappendbrh3note everything before the first comma is the old address everything after the first comma is the new addressh13 cleanedappendph3to format the output in excel split the columns using as the delimiter ph3 cleanedappendph2font colorredold address font font colorblacknew address fontph2 for address in addresses dirty addrestrip if in address dirty dirtyreplace cleanedappendfont colorred dirty font address addresslower address resubazaz09 addresslstrip pattern rd d joinpatterns address resubpattern 1 address address check staddress if one in address address addressreplaceone 1 if two in address address addressreplacetwo 2 if three in address address addressreplacethree 3 if four in address address addressreplacefour 4 if five in address address addressreplacefive 5 if eight in address address addressreplaceeight 8 if nine in address address addressreplacenine 9 if fith in address address addressreplacefith fifth if aveneu in address address addressreplaceaveneu avenue if united states of america in address address addressreplaceunited states of america if ave americas in address address addressreplaceave americas avenue of the americas if americas avenue in address address addressreplaceamericas avenue avenue of the americas if avenue of americas in address address addressreplaceavenue of americas avenue of the americas if avenue of america in address address addressreplaceavenue of america avenue of the americas if ave of the americ in address address addressreplaceave of the americ avenue of the americas if avenue america in address address addressreplaceavenue america avenue of the americas if americaz in address address addressreplaceamericaz americas if ave of america in address address addressreplaceave of america avenue of the americas if amrica in address address addressreplaceamrica americas if americans in address address addressreplaceamericans americas if walk street in address address addressreplacewalk street wall street if northend in address address addressreplacenorthend north end if inth in address address addressreplaceinth ninth if aprk in address address addressreplaceaprk park if eleven in address address addressreplaceeleven 11 if av in address address addressreplace av avenue if avnue in address address addressreplaceavnue avenue if ofthe americas in address address addressreplaceofthe americas of the americas if aj the in address address addressreplaceaj the of the if fifht in address address addressreplacefifht fifth if w46 in address address addressreplacew46 w 46 if w42 in address address addressreplacew42 w 42 if 95st in address address addressreplace95st 95th st if e61 st in address address addressreplacee61 st e 61st if driver information in address address addressreplacedriver information if e87 in address address addressreplacee87 e 87 if thrd avenus in address address addressreplacethrd avenus third avenue if 3r in address address addressreplace3r 3rd if st ates in address address addressreplacest ates if east52nd in address address addressreplaceeast52nd east 52nd if authority to leave in address address addressreplaceauthority to leave if sreet in address address addressreplacesreet street if w47 in address address addressreplacew47 w 47 if signature required in address address addressreplacesignature required if direct in address address addressreplacedirect if streetapr in address address addressreplacestreetapr street if steet in address address addressreplacesteet street if w39 in address address addressreplacew39 w 39 if ave of new york in address address addressreplaceave of new york avenue of the americas if avenue of new york in address address addressreplaceavenue of new york avenue of the americas if brodway in address address addressreplacebrodway broadway if w 31 in address address addressreplacew 31 w 31th if w 34 in address address addressreplacew 34 w 34th if w38 in address address addressreplacew38 w 38 if broadeay in address address addressreplacebroadeay broadway if w37 in address address addressreplacew37 w 37 if 35street in address address addressreplace35street 35th street if eighth avenue in address address addressreplaceeighth avenue 8th avenue if west 33 in address address addressreplacewest 33 west 33rd if 34t in address address addressreplace34t 34th if street ave in address address addressreplacestreet ave ave if avenue of york in address address addressreplaceavenue of york avenue of the americas if avenue aj new york in address address addressreplaceavenue aj new york avenue of the americas if avenue ofthe new york in address address addressreplaceavenue ofthe new york avenue of the americas if e4 in address address addressreplacee4 e 4 if avenue of nueva york in address address addressreplaceavenue of nueva york avenue of the americas if avenue of new york in address address addressreplaceavenue of new york avenue of the americas if west end new york in address address addressreplacewest end new york west end avenue print address address addresplit for pattern in patterns try if address0isdigit continue else location addressindexpattern 1 number location addresslocation print addresslocation if th in addresslocation 1 or floor in addresslocation 1 or in addresslocation continue except valueerror indexerror continue if number locationisdigit and lennumber location 4 address number location addresslocation addresslocation1 break address joinaddress if in address address addressreplace print address i 0 for char in address if charisdigit address addressi break i 1 print address if plz in address address addressreplaceplz plaza 1 if hstreet in address address addressreplacehstreet h street if dstreet in address address addressreplacedstreet d street if hst in address address addressreplacehst h st if dst in address address addressreplacedst d st if have in address address addressreplacehave h ave if dave in address address addressreplacedave d ave if havenue in address address addressreplacehavenue h avenue if davenue in address address addressreplacedavenue d avenue print address regex r joinpatterns r address resubregex r12 addresslstrip nyc print address if americasas st in address address addressreplaceamericasas st americas try clean geolocatorgeocodeaddress x cleanaddress address city zipcode country xsplit address addresslower if first in address address addressreplacefirst 1st if second in address address addressreplacesecond 2nd if third in address address addressreplacethird 3rd if fourth in address address addressreplacefourth 4th if fifth in address address addressreplacefifth 5th if sixth a in address address addressreplaceave address addressreplaceavenue address addressreplace sixth avenue of the americas if 6th a in address address addressreplaceave address addressreplaceavenue address addressreplace 6th avenue of the americas if seventh in address address addressreplaceseventh 7th if fashion in address address addressreplacefashion 7th if eighth in address address addressreplaceeighth 8th if ninth in address address addressreplaceninth 9th if tenth in address address addressreplacetenth 10th if eleventh in address address addressreplaceeleventh 11th zipcode zipcode3 to write straddress strzipcodelstrip strcleanlatitude strcleanlongitude to find straddress print to write returns can not be cleaned if street address has no numbers if anyiisdigit for i in straddress with openhomemy nameaddress databasetxt a as database if to find not in databaseread databasewritedirty to write n if ncy rd in address cleanedappendfont colorred can not be cleaned font br fail 1 elif nye rd in address cleanedappendfont colorred can not be cleaned font br fail 1 elif nye c in address cleanedappendfont colorred can not be cleaned font br fail 1 else cleanedappendto write br success 1 else cleanedappendfont colorred can not be cleaned font br fail 1 except attributeerror cleanedappendfont colorred can not be cleaned font br fail 1 except valueerror cleanedappendfont colorred can not be cleaned font br fail 1 except geocodertimedout as e cleanedappendfont colorred can not be cleaned font br fail 1 total success fail percent floatsuccess floattotal 100 percent roundpercent 2 print percent cleanedappendbraccuracy strpercent cleanedappendpcenterbody return njoincleanedupdate i have switched to running the application using gunicorn and this is solving the issue when i am accessing the application from my home network however i am still receiving the tcp error from my work proxy i am not getting any error message in my console the browser just thisplays the tcp error i can tell that the tool is still working in the background because i have a print statement in the loop telling me that each address is still being geocoded could this be something along the lines of my work network not liking that the page remains loading for a long period of time and then just thisplays the proxy error page,['python'] +1215165,how do i send a photo email attachment in ios using post request to sendgrid i am using nsmutableurlrequest to send post data to a serverside php script that sends emails using sendgrid this works just fine however i have no idea how to package uiimagedata properly to send as an attachment here is my current code choose an image from your photo library voidimagepickercontrolleruiimagepickercontroller picker didfinishpickingmediawithinfonsdictionary info chosenimage infouiimagepickercontrollereditedimage chosenimage uiimage pickeddata uiimagepngrepresentationchosenimage pickeddata nsdata attachment true picker thismissviewcontrolleranimatedyes completionnullvoidsendmail toemailaddress subject some subject message some message fullname mister bla bla if attachment true create nsdata object as png image data from camera image nsstring picattachment nsstring stringwithformatluunsigned longpickeddata length nsstring picname photo post nsstring stringwithformattoemailaddresubjectmessagefullnamepicattachmentpicname toemailaddress subject message fullname picattachment picname else post nsstring stringwithformattoemailaddresubjectmessagefullname toemailaddress subject message fullname nsdata postdata post datausingencodingnsasciistringencoding allowlossyconversionno nsstring postlength nsstring stringwithformatluunsigned longpostdata length nsmutableurlrequest request nsmutableurlrequest alloc init autorelease request seturlnsurl urlwithstringnsstring stringwithformat request sethttpmethodpost request setvaluepostlength forhttpheaderfieldcontentlength request setvalueapplicationxwformurlencoded forhttpheaderfieldcontenttype request sethttpbodypostdata send the post request and read the reply by creating a new nsurlsession nsurlsession conn nsurlsession sessionwithconfigurationnsurlsessionconfiguration defaultsessionconfiguration conn datataskwithrequestrequest completionhandlernsdata data nsurlresponse response nserror error nsstring requestreply nsstring alloc initwithdatadata encodingnsasciistringencoding nslogrequestreply requestreply return response from php script on server resumeif you research this question you may find that there is an existing ios sendgrid lib unfortunately this is not the answer the folks at sendgrid tell me not to use the lib because of a security concern,"['php', 'ios']" +1215487,firebase fcm failed to fetch apns token error domaincomfirebaseiid code1001 i am trying to use fcm for notificationbut firinstanceidwarning failed to fetch apns token error domaincomfirebaseiid code1001 null occurs so i cannot get notificationwhats the problemat the console failed to fetch apns token error domaincomfirebaseiid code1001 nulland below is my code on appdelegateimport uikitimport coredataimport alamofireimport firebaseimport firebaseinstanceidimport firebasemessaginguiapplicationmainclass appdelegate uiresponder uiapplicationdelegate var window uiwindow var badgecount int 0 enum basicvalidity string case success basicinfo case fail oauthauthentificationerror func applicationapplication uiapplication didfinishlaunchingwithoptions launchoptions nsobject anyobject bool override point for customization after application launch let uns uiusernotificationsettings uiusernotificationsettingsfortypes alert badge sound categories nil applicationregisterusernotificationsettingsuns applicationregisterforremotenotifications firappconfigure nsnotificationcenterdefaultcenteraddobserverself selector selectorselftokenrefreshnotification name kfirinstanceidtokenrefreshnotification object nil if let token firinstanceidinstanceidtoken sendtokentoservertoken printtoken is token return true func applicationapplication uiapplication didregisterforremotenotificationswithdevicetoken devicetoken nsdata printdidregisterforremotenotificationswithdevicetoken if firebaseappdelegateproxyenabled no firinstanceidinstanceidsetapnstokendevicetoken type sandbox printapns devicetoken func applicationapplication uiapplication didfailtoregisterforremotenotificationswitherror error nserror printregistration for remote notification failed with error errorlocalizeddescription func applicationapplication uiapplication didreceiveremotenotification userinfo nsobject anyobject printdidreceiveremotenotification if firebaseappdelegateproxyenabled no firmessagingmessagingappdidreceivemessageuserinfo handlernodata start refresh token func tokenrefreshnotificationnotification nsnotification printtokenrefreshnotification if let token firinstanceidinstanceidtoken printinstanceid token token sendtokentoservertoken firmessagingmessagingsubscribetotopictopicsglobal printsubscribed to topicsglobal connecttofcm end refresh token func sendtokentoservercurrenttoken string printsendtokentoserver token currenttoken send token to server only if necessary start connect to fcm func connecttofcm firmessagingmessagingconnectwithcompletion error in if error nil printunable to connect with fcm error else printconnected to fcm end connect to fcm func applicationwillresignactiveapplication uiapplication sent when the application is about to move from active to inactive state this can occur for certain types of temporary interruptions such as an incoming phone call or sms message or when the user quits the application and it begins the transition to the background state use this method to pause ongoing tasks thisable timers and throttle down opengl es frame rates games should use this method to pause the game start thisconnect from fcm func applicationdidenterbackgroundapplication uiapplication use this method to release shared resources save user data invalidate timers and store enough application state information to restore your application to its current state in case it is terminated later if your application supports background execution this method is called instead of applicationwillterminate when the user quits firmessagingmessagingthisconnect printthisconnected from fcm func applicationwillenterforegroundapplication uiapplication called as part of the transition from the background to the inactive state here you can undo many of the changes made on entering the background func applicationdidbecomeactiveapplication uiapplication restart any tasks that were paused or not yet started while the application was inactive if the application was previously in the background optionally refresh the user interface uiapplicationsharedapplicationapplicationiconbadgenumber 0 connecttofcm func applicationwillterminateapplication uiapplication called when the application is about to terminate save data if appropriate see also applicationdidenterbackground saves changes in the applications managed object context before the application terminates selfsavecontext i can get notification from firebase consol if i send notifications by using bundle id but i cannot get if our server send notification to specific device with token,['ios'] +1215676,drawing freely by fingers on google map i want to implement a custom module for free drawing on google map when it comes to the implementation i have found that the google map ondrag callback and always overrides my custom ondrag function i am not so sure how to use my framelayout ondrag to override the map click and drag motionhere is my working xmlxml version10 encodingutf8linearlayout xmlnsandroid xmlnstools androidlayout widthmatch parent androidlayout heightmatch parent androidorientationvertical toolscontextmainactivity textview androidididlocinfo androidlayout widthmatch parent androidlayout heightwrap content fragment androidididmap androidlayout widthmatch parent androidlayout heightmatch parent classcomexampleandroidmapsv2custommapfragment fragment framelayout androidididfram map androidlayout widthmatch parent androidlayout heightmatch parent framelayoutlinearlayoutcustommapfragmentjavapackage comexampleandroidmapsv2import comgoogleandroidgmsmapsmapfragmentimport androidosbundleimport androidviewlayoutinflaterimport androidviewviewimport androidviewviewgrouppublic class custommapfragment extends mapfragment public view moriginalcontentview public mapwrapperlayout mmapwrapperlayout override public view oncreateviewlayoutinflater inflater viewgroup parent bundle savedinstancestate moriginalcontentview superoncreateviewinflater parent savedinstancestate mmapwrapperlayout new mapwrapperlayoutgetactivity mmapwrapperlayoutaddviewmoriginalcontentview return mmapwrapperlayout override public view getview return moriginalcontentview public void setondraglistenermapwrapperlayoutondraglistener ondraglistener mmapwrapperlayoutsetondraglistenerondraglistener mapwrapperlayoutjavapublic class mapwrapperlayout extends framelayout private ondraglistener mondraglistener public mapwrapperlayoutcontext context supercontext public interface ondraglistener public void ondragmotionevent motionevent override public boolean thispatchtoucheventmotionevent ev if mondraglistener null mondraglistenerondragev return superthispatchtoucheventev public void setondraglistenerondraglistener mondraglistener thismondraglistener mondraglistener mainactivityjava package comexampleandroidmapsv2import javautilarraylistimport comgoogleandroidgmscommonconnectionresultimport comgoogleandroidgmscommongoogleplayservicesutilimport comgoogleandroidgmsmapsgooglemapimport comgoogleandroidgmsmapsgooglemaponmapclicklistenerimport comgoogleandroidgmsmapsgooglemaponmaplongclicklistenerimport comgoogleandroidgmsmapsgooglemaponmarkerclicklistenerimport comgoogleandroidgmsmapsonmapreadycallbackimport comgoogleandroidgmsmapsprojectionimport comgoogleandroidgmsmapsmodellatlngimport comgoogleandroidgmsmapsmodelmarkerimport comgoogleandroidgmsmapsmodelmarkeroptionsimport comgoogleandroidgmsmapsmodelpolygonimport comgoogleandroidgmsmapsmodelpolygonoptionsimport comgoogleandroidgmsmapsmodelpolylineoptionsimport androidappactivityimport androidappfragmentmanagerimport androidgraphicscolorimport androidgraphicspointimport androidlocationlocationimport androidosbundleimport androidviewmenuimport androidviewmotioneventimport androidviewviewimport androidwidgetframelayoutimport androidwidgettextviewimport androidwidgettoastpublic class mainactivity extends activity implements onmapclicklistener final int rqs googleplayservices 1 private googlemap mymap location mylocation textview tvlocinfo arraylistlatlng val new arraylistlatlng boolean markerclicked polygonoptions polygonoptions polygon polygon framelayout fram map custommapfragment mymapfragment boolean is map moveable projection projection public double latitude public double longitude override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main tvlocinfo textviewfindviewbyidridlocinfo fragmentmanager myfragmentmanager getfragmentmanager mymapfragment custommapfragmentmyfragmentmanagerfindfragmentbyidridmap if mymapfragment null mymapfragmentgetmapasyncnew onmapreadycallback override public void onmapreadygooglemap map loadmapmap fram map framelayout findviewbyidridfram map is map moveable false to detect map is movable else toastmaketextthis error map fragment was null toastlength shortshow public void draw map mymapaddpolylinenew polylineoptions addallval colorcolorparsecolor 0971b2width10f protected void loadmapgooglemap map todo autogenerated method stub mymap map mymapsetmylocationenabledtrue mymapsetmaptypegooglemapmap type hybrid mymapsetonmapclicklistenerthis mymapsetonmaplongclicklistenerthis mymapsetonmarkerclicklistenerthis markerclicked false fram mapsetontouchlistenernew viewontouchlistener override public boolean ontouchview v motionevent event float x eventgetx float y eventgety int x co mathroundx int y co mathroundy projection mymapgetprojection point x y points new pointx co y co latlng latlng mymapgetprojectionfromscreenlocationx y points latitude latlnglatitude longitude latlnglongitude switch eventgetaction case motioneventaction down finger touches the screen valaddnew latlnglatitude longitude case motioneventaction move finger moves on the screen valaddnew latlnglatitude longitude case motioneventaction up vperformclick finger leaves the screen draw map break if is map moveable true return true else return false override public boolean oncreateoptionsmenumenu menu inflate the menu this adds items to the action bar if it is present getmenuinflaterinflatermenuactivity main menu return true override protected void onresume superonresume int resultcode googleplayservicesutilisgoogleplayservicesavailablegetapplicationcontext if resultcode connectionresultsuccess toastmaketextgetapplicationcontext isgoogleplayservicesavailable success toastlength longshow else googleplayservicesutilgeterrordialogresultcode this rqs googleplayservices override public void onmapclicklatlng point is map moveable is map moveable toastmaketextgetapplicationcontext is map moveable drawing activated drawing thisabled toastlength shortshow tvlocinfosettextpointtostring mymapanimatecameracameraupdatefactorynewlatlngpoint markerclicked false override public void onmaplongclicklatlng point tvlocinfosettextnew marker added pointtostring mymapaddmarkernew markeroptionspositionpointtitlepointtostring markerclicked false override public boolean onmarkerclickmarker marker ifmarkerclicked ifpolygon null polygonremove polygon null polygonoptionsaddmarkergetposition polygonoptionsstrokecolorcolorred polygonoptionsfillcolorcolorblue polygon mymapaddpolygonpolygonoptions else ifpolygon null polygonremove polygon null polygonoptions new polygonoptionsaddmarkergetposition markerclicked true return true,"['java', 'android']" +1215769,how to select last element that do not have specific class how can i select last li that does not have the hidden classi have html and css like thisul lilastchildnotfirstchildnothidden button backgroundcolor red ul li button1button li li button2button li li classhidden button3button li ul,"['html', 'css']" +1215881,visitor pattern implementation in case of source code unavailability one of the reasons to consider the visitor patterna practical result of this separation is the ability to add new operations to existing object structures without modifying those structuresassume that you do not have the source code of third party libraries and you have added one operation on related objects since you do not have object your elements third party classes cannot be modified to add visitor in this case double thispatch is not possibleso which option is generally preferredoption 1 extend one more inheritance hierarchy on top of third party class and implement pattern as show in picture with double thispatchfor a given hierarchy of class b which extends class a i will addelementa extends aelementb extends bnow concreteelements are derived from elementa instead of class acons the number of classes will grow option 2 use visitor class a central helper class and get the work done with single thispatch cons we are not really following visitor patter as per uml diagramcorrect if i am wrong,['java'] +1216200,automatic constructor in explicitly instantiated class template i have a templatebool var struct obj template declared in a header file objh with explicit automatic move constructor default objhpragma onceinclude vectortemplatebool varstruct obj stdvectorint member objint m memberm objobj default int member fun constextern template struct objfalseextern template struct objtruethe member function of the template is defined in another file objcpp with explicit instantiation of the template objcppinclude objhtemplatebool varint objvarmember fun const return 42template struct objfalsetemplate struct objtruethis template is then used from the main file maincpp maincppinclude utilityinclude objhint main objtrue o120 objtrue o2stdmoveo1 return o2member funthe cpps are then compiled and linked together with the following makefilecxxclangcxxgcxxflagswall wextra stdc14aout objo maino cxx cxxflags o aoutobjo objcpp objh cxx cxxflags c o maino maincpp objh cxx cxxflags c o however i get a linker error undefined reference to objtrueobjobjtrue the compiler apparently did not instantiate the constructor objtruemember fun is defined and the program indeed links successfully if i remove the reference to the move constructor from maincppif i remove extern template from the header the program compilesif i use int instead of stdvectorint for the type of member the program also compilescppreferencecom claims that the compiler will declare a move constructor as a nonexplicit inline public member of its class however the manually defined objint constructor is also inline but it is correctly instantiatedi received this error with clang in a project that compiled fine with gcc so i thought this was a clang bug however when i reduced the problem to this simple case both gcc 540 and clang 380 produce the same results,['c++'] +1216496,how to return a null from a templated method without using a pointer i have some code that looks like thistemplate class tt foot a if a do somethin returns object of type t else return null but of course it would not compile since null is not of type t someone suggested this solution to me but i do not like ittemplate class tt foot a if a do somethin returns object of type t else return nullptr i am wondering how to make this function able to return a null value if possible without the use of a pointerdanke auf wiedersehen,['c++'] +1216543,formatting timers without losing accuracy i have an array of startstop times i basically want to thisplay the time it took for each entry as well as the total time for all of them here is the code i wrote to try to do thatfunction timeformatter milliseconds const padzero time 0timeslice2 const minutes padzeromilliseconds 60 0 const seconds padzeromilliseconds 10 0 60 const centiseconds padzeromilliseconds 10 0 100 return minutes seconds centiseconds example stopwatch timesconst timeintervals starttime 1470679294008 stoptime 1470679300609 starttime 1470679306278 stoptime 1470679314647 starttime 1470679319718 stoptime 1470679326693 starttime 1470679331229 stoptime 1470679336420 calculate time it took for each entryconst times timeintervalsmaptime timestoptime timestarttime run the timeformatter on each individual timeconst individualtimes timesmaptimeformatter run the timeformatter on the sum of all the timesconst maintimer timeformattertimesreducea b a b 00 06 60 00 08 36 00 06 97 00 05 19 consolelogindividualtimes 00 27 13 consolelogmaintimerhowever i am losing accuracy as you can see the individual times do not add up to the maintimer value it is always off by 01 03 no matter what the times are is there a way i can make sure that the times only thisplay two places but still add up correctly any help would be appreciatedi also have this on a jsfiddle where it is easier to runedit the current answer did work for the case i provided above but it does not work for all cases like this one,['javascript'] +1216728,adjusting thickness of text overline i have an element with the following css propertiestextdecoration overlinetextdecorationcolor bluethe problem is the overline is very small and not very thick at all i would like to increase the thickness of this overlinei have done some research and it looks like there is no css property to increase the thickness of the overlinei have read certain things about adding a top border but that top border does not sit right above the text and it moves the entire element down on the pagesince i am doing this within a bootstrap nav bar the element moving down is a pretty big problemany ideas on how to make the overline more visible and increase the thickness of the linebelow is the full snippet of code including the html i am usingactive textdecoration overline textdecorationcolor df3e38link href relstylesheet script srcscriptscript srcscriptnav classnavbar navbardefault div classcontainerfluid div classnavbarheader button typebutton classnavbartoggle datatogglecollapse datatargetmynavbar span classiconbarspan span classiconbarspan span classiconbarspan button a classnavbarbrand hrefmy sitea div div classcollapse navbarcollapse idmynavbar ul classnav navbarnav navbarright li classactivea hrefsign upa li lia hreflogina li ul div divnav,"['html', 'css']" +1216807,select elements in sequence by group class name how do i select elements created dinamicamentes by groups i want to select msgpvtstyleme and work on them then select msgpvtstyle again and work on them goal is to get grouped elements and insert them classes i want to simulate chat balloonsresult final thank you all,"['javascript', 'jquery', 'css']" +1216844,efficiency of postincrement vs preincrement in c i usually think that preincrement is more efficient than postincrement in c but when i read the book game engine architecture2nd ed recently there is a section says that postincrement is prefered than preincrement in for loop because as i quote preincrement introduces a data dependency into your code the cpu must wait for the increment operation to be completed before its value can be used in the expression is this true it is really subverted my idea about this problemhere is the quote from the section in case you are interested5321 preincrement versus postincrementnotice in the above example that we are using cas postincrement operator p rather than the preincrement operator p this is a subtle but sometimes important optimization the preincrement operator increments the contents of the variable before its now modified value is used in the expression the postincrement operator increments the contents of the variable after it has been used this means that writing p introduces a data dependency into your code the cpu must wait for the increment operation to be completed before its value can be used in the expression on a deeply pipelined cpu this introduces a stall on the other hand with p there is no data dependency the value of the variable can be used immediately and the increment operation can happen later or in parallel with its use either way no stall is introduced into the pipelineof course within the aupdatea expression of a for loop forinit expr test expr update expr there should be no difference between pre and postincrement this is because any good compiler will recognize that the value of the variable isnat used in update expr but in cases where the value is used postincrement is superior because it doesnat introduce a stall in the cpuas pipeline therefore itas good to get in the habit of always using postincrement unless you absolutely need the semantics of preincrementedit add the above examplevoid processarrayint container int numelements int pbegin container0 int pend containernumelements for int p pbegin p pend p int element p process element void processliststdlistint container stdlistintiterator pbegin containerbegin stdlistintiterator pend containerend stdlistinfiterator p for p pbegin p pend p int element p process element,['c++'] +1216848,conditional comprehension in julia in python there is the option to provide a condition for whether or not to include a specific item in a comprehensionx2 for x in range10 if x 5 36 49 64 81it is possible to conditionally use function but i have not yet found a way to entirely exclude values other than filtering them outside of the comprehensionl collect09filterx x 5 ll x2 for x in l alternatively mapx x2 l 36 49 64 81is this possible in julia,['python'] +1216858,why do some java library methods delegate to a native method with a similar signature after delving into the source code for the jre library i noticed a strangely common code structure like thispublic int foodouble bar return foo0barprivate native int foo0double barwhy is it so much more common than simply having the native method as the public methodpublic native int foodouble bar,['java'] +1217092,does standard c11 guarantee that temporary object passed to a function will have been destroyed after the end of the function as known that standard c11 guarantees that temporary object passed to a function will have been created before function call does standard c11 guarantee that temporary object passed to a function will have been created before function callbut does standard c11 guarantee that temporary object passed to a function will have been destroyed after the end of the function not beforeworking draft standard for programming language c 20160712 a 122 temporary objectsa 122 5there are three contexts in which temporaries are destroyed at a different point than the end of the full expression the first context is when a default constructor is called to initialize an element of an array with no corresponding initializer 86 the second context is when a copy constructor is called to copy an element of an array while the entire array is copied 515 128 in either case if the constructor has one or more default arguments the destruction of every temporary created in a default argument is sequenced before the construction of the next array element if any the third context is when a reference is bound to a temporaryalsoa 19 10a fullexpression is an expression that is not a subexpression of another expression note in some contexts such as unevaluated operands a syntactic subexpression is considered a fullexpression clause 5 a end note if a language construct is defined to produce an implicit call of a function a use of the language construct is considered to be an expression for the purposes of this definition a call to a destructor generated at the end of the lifetime of an object other than a temporary object is an implicit fullexpression conversions applied to the result of an expression in order to satisfy the requirements of the language construct in which the expression appears are also considered to be part of the fullexpressiondoes it mean that standard c11 guarantees that temporary object passed to a function will have been destroyed not before the function will end and exactly at the end of the full expressioninclude iostreamusing namespace stdstruct t t stdcout t created n int val 0 t stdcout t destroyed n void functiont t obj t t int val stdcout funcstart n stdcout t objval tval val stdendl stdcout funcend nint main functiont t tval return 0outputt created t created t created funcstart 0 0 0funcend t destroyed t destroyed t destroyed can we say that the t destroyed will always be after the funcendand thisfunctiont t tvalis always equal to this t tmp1 t tmp2 t tmp3 functiontmp1 tmp2 tmp3val,['c++'] +1217196,key stores from websphere how can i get key stores from ibm websphere in spring that is located in webspheresecurity ssl certificate and key management key stores and certificateswhether it is possible to create the bean and use it or use it as something differentcan i use it through the jndi,['java'] +1217279,reading ascii vtk with xtk i am trying to use xtk to thisplay 3d cfd data on my webpage i can generate ascii vtk files containing my data mesh points velocity pressure following the format guide here and i can visualize it it visit when i try loading into xtk however by changing the file name in their skull tutorial i get the error typeerror f is nullin xtkjs and nothing thisplays has anyone had similar problemshere is a sample vtk file of mineps i know that paraview has trouble reading the fielddata so i tried removing that for xtk but with no luck,['javascript'] +1217468,boxgeometry not aligning with spheregeometry properly i am trying to create spikes on earthsphere geometry though everything works fines but spikes dont align with globe i want spike to align something like below image but my spikes dont lookatnew threevector30 despite mentioned please help me outi purposefully mentioned code required for debugging let me know if you need more code for this below image is how i want my spikes to align with spherebut this is how it looksmy main js initialization filedocumentreadyfunction initializing camera influxcamera new influxcamera fov 60 aspectratio windowinnerwidth windowinnerheight near 1 far 10 position x 0 y 0 z 750 initializing scene influxscene new influxscene initializing renderer influxrenderer new influxrenderer clearcolor 0x0 size width windowinnerwidth height windowinnerheight influxglobe new influxglobe radius 300 width 50 height 50 influxstars new influxstars particlecount 150 particle color 0xf size 1 influxmovetracker new influxmovetracker influxeventlistener new influxeventlistener function animate requestanimationframe animate render controlsupdate function render cameralookatsceneposition grouprotationy 01 rendererrender scene camera below is code responsible for generating spikes on globeinfluxspikes function lat long convert the positions from a lat lon to a position on a sphere var latlongtovector3 functionlat lon radius heigth var phi lat mathpi180 theta lon180 mathpi180 var x radiusheigth mathcosphi mathcostheta y radiusheigth mathsinphi z radiusheigth mathcosphi mathsintheta return new threevector3x y z var geom new threegeometry var boxgeometry new threeboxgeometry1 100 1 iterates through the data points and makes boxes with the coordinates var position latlongtovector3lat long 300 2 var box new threemesh boxgeometry each position axis needs to be set separately otherwise the box will instantiate at 0 boxpositionx positionx boxpositiony positiony boxpositionz positionz boxlookatnew threevector30 0 0 boxupdatematrix merges the geometry to speed up rendering time do not use threegeometryutilsmerge because it is deprecated geommergeboxgeometry boxmatrix var total new threemeshgeom new threemeshbasicmaterial color getrandomcolor morphtargets true function getrandomcolor var letters 0123456789abcdef var color for var i 0 i 6 i color lettersmathfloormathrandom 16 return color add boxes to the group groupaddtotal sceneaddgroupinfluxcamera functionparams if isemptyobjectparams windowcamera new threeperspectivecameraparamsfov paramsaspectratio paramsnear paramsfar camerapositionsetparamspositionx paramspositiony paramspositionz cameralookatnew threevector30 else consolelogtrouble with initializing camera return,['javascript'] +1217522,could not find microsoftdiasymreadernativex86dll i am trying to build a project in rider using mono and i can keep on getting this errorerror cs0041 unexpected error writing debug information windows pdb writer is not available could not find microsoftdiasymreadernativex86dlldoes anybody have any idea why i am getting this error i have tried searching for it online and all i could find was a previous so question that never got answered monodevelop fails to build cant find microsoftdiasymreadernativex86dlli have no idea where to start any help would be appreciated,['c#'] +1217661,trying to avoid duplicate users session records in session table laravel sample data in this table looks like below there are multiple duplicate users session records present in the tablevendorlaravelframeworksrcilluminatesessiondatabasesessionhandlerphpin the above file path we have below methodpublic function writesessionid data payload thisgetdefaultpayloaddata if thisexists thisreadsessionid if thisexists thisgetquerywhereid sessionidupdatepayload else payloadid sessionid thisgetqueryinsertpayload thisexists trueit checks for session idquestioncan i avoid creation of duplicate user session records in session table is there any flag that do so in session config file,['php'] +1217769,application didfinishlaunchingwithoptions nearly matches optional requirement after installing xcode 8 beta 6 i am getting a warning saying instance method application didfinishlaunchingwithoptions nearly matches optional requirement application didfinishlaunchingwithoptions of protocol uiapplicationdelegatein my app delegatethere are 2 suggested fixits to silence the warningmark the method as privateadd nonobjc to the methoddoing either silences the warning but why does this need to be done,['ios'] +1217905,what exactly does documentnormalize do i read that documentnormalize removes empty text nodes and joins adjacent nodeswhat does that mean exactly,['javascript'] +1218249,gcc label address return current eip rather than real label address in an attempt to write an os i need to get the address of the current functions end right before epilogue for task switchingconcretely my problem is to get an eip to assign to my newly created task process inside the copied stack i have already managed to saverestore registers for a process but i need to find what value the child process will have in it is eipi used gccs extensions to c standard labels as values and local labelsfrom the documentation you can get the address of a label defined in the current function or a containing function with the unary operator aa the value has type void and gcc allows you to declare local labels in any nested block scope a local label is just like an ordinary label but you can only reference it with a goto statement or by taking its address within the block in which it is declaredpid t forkvoid label fork end taskregseip uintptr tfork end return taskpid fork endgcc does compile it with just warnings about nonstandard codehowever when thisassembled gdb shows taskregseip uintptr tfork end0x00105008 87 mov 0x105008edx0x0010500d 92 mov 0xcebpeax0x00105010 95 mov edx0x40eax fork end 0x00105096 229 leave 0x00105097 230 ret i expect taskregseip uintptr tfork endl to save0x00105096 rather than 0x00105008cflags are o0 stdgnu99 fgnu89inline ddebug ggdb3 ffreestanding fbuiltin warnings related options not shown herecommenting label fork end changes nothing,['c'] +1218296,how to make sql memory optimized native compiled function deterministic here is a really really simple function it comes back deterministic if i compile it native it is no longer deterministic how can i make it native compiled and deterministiccreate function hashhashdelimiter2returns nchar1with schemabindingas begin return nendgo this does indeed result in yes select is deterministicfrom information schemaroutineswhere routine name hashdelimiter2 but then compile it native and it is no longer deterministic create function hashhashdelimiter3returns nchar1with native compilation schemabindingas begin atomic with transaction isolation level snapshot language nenglish return nendgo this results in no select is deterministicfrom information schemaroutineswhere routine name hashdelimiter3,['sql'] +1218622,how to implement a test that checks the reliability of the internet connection i am working on a project that needs to test some feature of android and mobile networksone of them is to check reliability of the internet connection to do that i should first check the internet connection itself and then check the reliabilityis there any algorithm or library to find out the reliability of internet connection,['android'] +1218738,how to find out detected face is real or fake i am developing one security related project there is need to check any face is detected or not if face is detected then do some action if face is not detected then close appeverything is perfect working i am using surfaceview which is implemented surfaceholdercallback and in that open camera and camera have one method name is startfacedetection using this method i detect facecode for referencepublic class surfaceviewpreview extends surfaceview implements surfaceholdercallback private surfaceholder mholder private camera mcamera public surfaceviewpreviewcontext context attributeset attrs supercontext attrs setwillnotdrawfalse mholder getholder mholderaddcallbackthis mholdersettypesurfaceholdersurface type push buffers public void surfacecreatedsurfaceholder holder try if cameragetnumberofcameras 0 contextcompatcheckselfpermissiongetcontext manifestpermissionwrite external storage packagemanagerpermission granted return mcamera cameraopen0 mcamerasetpreviewthisplaymholder catch exception e eprintstacktrace if thismcamera null thismcamerarelease thismcamera null public void surfacedestroyedsurfaceholder holder if cameragetnumberofcameras 0 contextcompatcheckselfpermissiongetcontext manifestpermissionwrite external storage packagemanagerpermission granted return mcamerastoppreview mcamerarelease mcamera null public void surfacechangedsurfaceholder holder int format int w int h if cameragetnumberofcameras 0 contextcompatcheckselfpermissiongetcontext manifestpermissionwrite external storage packagemanagerpermission granted return mcamerastartpreview mcamerasetfacedetectionlistenernew camerafacedetectionlistener override public void onfacedetectioncameraface faces camera camera face is detected mcamerastartfacedetection now problem if any human post if i shown to camera then detected as human but i want real human face detection not fake poster facepossible way to handle my requirement1 capture 10 images periodically and check all variation is same then it means static face is there like poster which is mounted in wall2 write any proper algorithm which tell to detected face is real human or fake face3 any library is available which is said human face is really available or notif anyone have idea please suggest how to solve above issue any code is available then share with me response is appreciated how can use adapting learning ways to conclude real vs fake picturevideo frame,"['java', 'android']" +1219053,list initialization of aggregates when can it invoke copy constructor consider the following codestruct a int xint main a a a bais this program wellformed at c11 standard in my copy of n3797 it says854 list initialization dclinitlist 3 listinitialization of an object or reference of type t is defined as follows if t is an aggregate aggregate initialization is performed 851 otherwise if t is a specialization of stdinitializer liste otherwise if t is a class type constructors are considered the applicable constructors are enumerated and the best one is chosen using overload resolution if a narrowing conversion is required to convert any of the types the program is illformed otherwise if the initializer list has a single element of type e and either t is not a reference type or it is referencerelated to e the object or reference is initialized from that element if a narrowing conversion is required to convert the element to t the program is illformed otherwise if t is a reference type a prvalue temporary of the type reference by t is copylistinitialized or directlistinitialized depending on the kind of initialization for the reference and the reference is bound to that temporary otherwise if the initializer list has no elements the object is valueinitialized otherwise the program is illformed the point of the example is the type is an aggregate but listinitialization is supposed to invoke the copy constructor on gcc 48 and gcc 49 at c11 standard it failsmaincpp in function aint mainamaincpp78 error cannot convert a to ainta in initialization a ba and says a is not convertible to int or similar because aggregate initialization fails on gcc 54 it works fine at c11 standardon clang you get similar errors with clang35 36 and it starts working at clang37i understand that it is wellformed at c14 standard and that it was mentioned in a defect report herehowever what i do not understand is why this was considered a defect in the standardwhen the standard writes if x fooinitialization is performed otherwise if y barinitialization is performed otherwise the program is illformed does not this mean that if x holds but fooinitialization cannot be performed then we should check if y holds and then attempt barinitialization this would make the example work because when aggregate initialization fails we do not match stdinitializer list and the next condition we match is t is a class type and then we consider constructorsnote that this does seem to be how it works in this modified examplestruct a int xint main a a const a ref a brefall the same compilers treat this the same way as the earlier example at c11 and c14 standards but it seems that the modified wording from the cwg defect record does not apply to this case it readsif t is a class type and the initializer list has a single element of type cv t or a class type derived from t the object is initialized from that element defectshtml1467but in the second code example the initializer list technically contains const t so i do not see how it would work unless after aggregate initialization fails we are supposed to attempt constructorsam i wrong is it not supposed to attempt constructors after aggregate initialization failsheres a related exampleinclude iostreamstruct b int x operator int const return 2 int main b b1 b cb stdcout cx stdendlin clang36 gcc48 gcc49 it prints 2 and in clang37 gcc50 it prints 1assuming i am wrong and at c11 standard list initialization of an aggregate is supposed to be aggregate initialization and nothing else until the new wording in the defect report is introduced is it a bug that this happens even when i select stdc11 on the newer compilers,['c++'] +1219356,hiding implementation details by reducing number of populated headers i am developing a library i have interface class that would be called from outsidei have also an internal engine that should not be called from outsideas i read here and there i should hide the internal engine class and not even populate its header since i have the following structureinterfacehppinclude enginehpp class interfaceprivate enigne enginterfacecppinclude enginehppcode that uses member variables and functions from eninge enginehppclass engineto solve the problem of populating enginehpp i should change the code tointerfacehppclass engineclass interfaceprivate some smart pointerenigne eng ptrinterfacecppinclude enginehppcode that uses member variables and functions from eninge enignehppclass enginethis solved the problem however from now engine is allocated dynamically all its member variables are in the free storei can not understand that i have to change my design and allocate engine on the free store for solving the problem of hiding implementation details is there a better solutionps i am not asking about why this solution works i know it is about knowing the size of engine class is mandatory if i would leave it on stack my question is about asking for a different design that may solve the problemeditboth interface and engine have member variables,['c++'] +1219615,aws authentication to amazon cognito i am a newbie on mobile dev i am trying to authenticate to amazon cognitoi first login to credentials provider using a username pin platform and devicetoken using custom services model i then get identityid endpoint and token back i am told that i need to swap the token i got back and refresh my credentials in order for me to be authenticated to aws cognito and s3 but all the process is confusing and have a lot of examples that are differenti have created a signinprovider extending awssigninprovider to access the void login void id result nserror error completionhanlder i have my token endpoint and identityid inside my login methodwhat do i do with the completion handler and whats next afterimplementation signinproviderinstancetype sharedinstance nsstring identityprovidername awstasknsstring token bool isloggedin nssting username void reloadsession void login void id result nserror error completionhanlderauthrequest impcldmobileauthenticationrequest new authrequest settoken930fc1b56d8ca19a84500f9a79af71b65f60331f0242ce4395cdf41186443692 authrequest setpasswordpin authrequest setusername authrequest setplatformios serviceclient impcldimpressioninternalmicroserviceclient defaultclient serviceclient mobileauthenticationpostauthrequest continuewithblockidawstask logintask what to do here with my logintask results token endpoint identityid return nil,"['ios', 'objective-c']" +1219856,change windowprint paper orientation i want to change paper mode orientation on the window print i want to change it programatically but i could not find anythingwindowprintbut i do not know how can i do itmedia printpage size landscapei dont need it function printwindow windowprint some code here,"['javascript', 'jquery', 'css']" +1220059,how could i apply visited pseudoclass for tel url i got a problem with tag i have list of clickable phone numbers on the page and i want to mark used urlsi created small example and tried to use visited selector to change color for clicked urls but it does not worklet me show the codedoctype htmlhtml head style typetextcss phonevisited color red phone color blue style head body h1hih1 a classphone hreftelcall mea bodyhtmli found in google chrome inspector that css works correctly i manually added visited class and urls color was changed but browser does not mark url as visited after clickis there any chance to fix this behaviorthank you,"['javascript', 'html', 'css']" +1220138,cythons prange not improving performance i am trying to improve the performance of some metric computations with cythons prange here are my codesdef shausdorfloat64 t1 xa not none float64 t1 xb not none cdef py ssize t i py ssize t and xbshape2 float64 t1 hthist npzerosn arrangement to fix contiguity xb npasanyarraynpascontiguousarrayxbi for i in rangen for i in rangen hthisti hausdorffxa xbi return hthistdef phausdorfloat64 t1 xa not none float64 t1 xb not none cdef py ssize t i py ssize t and xbshape2 float64 t1 hthist npzerosn arrangement to fix contiguity edited cdef float64 t1 xc npasanyarraynpascontiguousarrayxbi for i in rangen with nogil parallelnum threads4 for i in prangen schedulestatic chunksize1 hthisti hausdorffxa xci return hthistbasically in each iteration the hausdorff metric is computed between xa and each xbi here is the signature of the hausdorff functioncdef inline float64 t hausdorfloat64 t1 xa float64 t1 xb nogil my problem is that both the sequential shausdorff and the parallel phausdorff have the same timings furthermore it seems that phausdorff is not creating any thread at allso my question is what is wrong with my code and how can i fix it to get threading workinghere is my setuppyfrom thistutilscore import setupfrom thistutilsextension import extensionfrom cythonbuild import cythonizefrom cythonthistutils import build extext modules extensioncustom metric custom metricpyx librariesm extra compile args o3 ffastmath marchnative fopenmp extra link argsfopenmp setup name custom metric cmdclass build ext build ext ext modules ext modules edit 1 here is a link to the html generated by cython a custom metrichtmledit 2 here is an example on how to call the corresponding functions you need to compile the cython file firstimport custom metric as cmimport numpy as npxa nprandomrandom90 210xb nprandomrandom10 210 9timing parallel versiontimeit cmphausdorffxa xbtiming sequential versiontimeit cmshausdorffxa xb,['python'] +1220335,java jbossdeploymentstructurexml add jaxp exclusion i am implementing xml validation which prevents xxe external xml entity injection i borrowed some code from owasp xxe prevention cheat sheet my code looks like this schemafactory factory schemafactorynewinstancexmlconstantsw3c xml schema ns uri schema schema factorynewschemaxsdfileurl validator validator schemanewvalidator validatorsetpropertyxmlconstantsaccess external dtd validatorsetpropertyxmlconstantsaccess external schema validatorvalidatenew streamsourcenew stringreaderxmlthe code runs correctly on my local windows machine jdk 180 92 wildfly 82 but on a qa red hat machine with similar config jdk 180 101 wildfly 82 it throws an exception with the message property is not recognizedafter some reading my suspiscion is that during runtime incorrect class definition is being read for the validator class how do i fix this updateturns out jboss comes with its own implementation of jaxp and my code needs to pick the jaxp implementation from jdk and not from jboss i can do this easily by passing jaxpmodule argument in standalonesh using this my code picked the correct jaxp implementation as well java jar jbossmodulesjar jaxpmodule javaxxmljaxpproviderbut i would like to do this using jbossdeploymentstructurexml and add an exclusion like this jbossdeploymentstructure xmlnsurnjbossdeploymentstructure12 xmlnsxsi deployment exclusions module namejavaxapi is the module name correct exclusions deploymentjbossdeploymentstructurebut this isnt working how can i fix this,['java'] +1220466,why is a public const method not called when the nonconst one is private consider this codestruct a void foo const stdcout const stdendl private void foo stdcout non const stdendl int main a a afoothe compiler error iserror void afoo is privatebut when i delete the private one it just works why is the public const method not called when the nonconst one is privatein other words why does overload resolution come before access control this is strange do you think it is consistent my code works and then i add a method and my working code does not compile at all,['c++'] +1220778,why does as const forbid rvalue arguments i wanted to ask why as const forbids rvalue arguments according to cppreferencecom ie why the standards folks made it so not why cppreferencecom specifically quoted them on that and also not where in the spec the intent of the committee is codified just for making sure this artificial example would yield an error user wants to make it const to keep cow quietqchar c as constgetqstring0another questions answer notes that if we just remove the deletion of the rvalue reference overload it would silently transform rvalues to lvalues right but why not handle rvalues gracefully and return const rvalues for rvalue input and const lvalues for lvalue input,['c++'] +1220860,does standard c11 guarantee that memory order seq cst prevents storeload reordering of nonatomic around an atomic does standard c11 guarantee that memory order seq cst prevents storeload reordering around an atomic operation for nonatomic memory accessesas known there are 6 stdmemory orders in c11 and its specifies how regular nonatomic memory accesses are to be ordered around an atomic operation working draft standard for programming language c 20160712 a 293 order and consistencya 293 1the enumeration memory order specifies the detailed regular nonatomic memory synchronization order as defined in 110 and may provide for operation ordering its enumerated values and their meanings are as followsalso known that these 6 memory orders prevent some of these reorderingbut does memory order seq cst prevent storeload reordering around an atomic operation for regular nonatomic memory accesses or only for other atomic with the same memory order seq cstie to prevent this storeloadreordering should we use stdmemory order seq cst for both store and load or only for one of itstdatomicint a bbstore1 stdmemory order seq cst sequential consistencyaloadstdmemory order seq cst sequential consistencyabout acquirerelease semantic is all clear it specifies exactly nonatomic memoryaccess reordering across atomic operations orderto prevent storeloadreordering we should use stdmemory order seq csttwo examplesstdmemory order seq cst for both store and load there is mfence storeload cannot be reordered gcc 610 x86 64 stdatomicint a bbstore1 stdmemory order seq cst cannot be executed after loadaloadstdmemory order seq cst cannot be executed before storestdmemory order seq cst for load only there is not mfencestoreload can be reordered gcc 610 x86 64 stdatomicint a bbstore1 stdmemory order release can be executed after loadaloadstdmemory order seq cst can be executed before storealso if compiler used alternative mapping of cc11 to x86 which flushes the store buffer before the load mfencemov from memory so we must use stdmemory order seq cst for load too as this example is thiscussed in another question as approach 3 does it make any sense instruction lfence in processors x86x86 64 ie we should use stdmemory order seq cst for both store and load to generate mfence guaranteed that prevents storeload reorderingis it true that memory order seq cst for atomic load or storespecifi acquirerelease semantic prevent loadload loadstore storestore reordering around an atomic operation for regular nonatomic memory accesses but prevent storeload reordering around an atomic operation only for other atomic operations with the same memory order seq cst,['c++'] +1220861,can a program call fflush on the same file concurrently can anything bad happen like undefined behavior file corruption etc if several threads concurrently call fflush on the same file variableclarification i do not mean writing the file concurrently i only mean flushing it concurrentlythe threads do not read or write the file concurrently they only write the file inside a critical section one thread at a time they only flush outside of the critical section to release the critical section sooner so to let the others do the other work except file writingthough it may happen that one thread is writing the file inside the critical section while another threads is flushing the file outside the critical section,['c'] +1221014,liking feature implementation using two apis via client side as ios app swift we are trying to build a simple follow feature for our ios app we have two apis our brand api with an array of objects containing unique brand ids for our brands within each object and our firebase api where we store users within the firebase api it has a key called followingbrands with and array of objects called composed of the unique brand ids from ourbrand api as keys with the value true the objects are created once a user has followed the brand from liking the brand on our appwhen the app loads we check to see if firebase apis brand ids keys matches the brand apis brand id then show a star to indicate the user is already following the brandour problem is brand api is implemented with pagination ie offset so how will we verify all brands they are following if not all the unique brand ids will be available to compare with our firebase api we use swift on the ios side and the brand api is built using djangotastypiefirebase apiuser id currentfollowingcount 0 thisplayname email followingbrands unique brand id true provider facebook userid user idbrand api labels id unique brand id meta limit 10 next apilimit10offset10 offset 0 previous null total count 33,['ios'] +1221037,how to align stdarray contained data since stdarray does not allow changing its allocator is there a way to ensure that the pointer to the data address is alignedfor instance in gnu g 484 and 610 the code belowinclude arrayinclude iostreamint mainvoid stdarraybool 10 a stdarraychar 10 b stdarrayint10 c stdarraylong long 10 d stdarrayfloat 10 e stdarraydouble 10 f stdcout arraybool10data adata stdendl stdcout arraychar10data void bdata stdendl stdcout arrayint10data cdata stdendl stdcout arraylong long 10data ddata stdendl stdcout arrayfloat 10data edata stdendl stdcout arraydouble 10data fdata stdendl return 0provides the following output that shows that the container data is aligned to 16byte addresses no matter the datatype contained when compiling for an x8664 bit architecture arraybool10data 0x7ffe660a2e40arraychar10data 0x7ffe660a2e30arrayint10data 0x7ffe660a2e00arraylong long 10data 0x7ffe660a2db0arrayfloat 10data 0x7ffe660a2d80arraydouble 10data 0x7ffe660a2d30however for intels icpc v1603 the result is shown below even using align while most of containers are aligned to 16byte addresses some char and float arrays are aligned to smaller byte addresses 2byte and 8byte respectivelyarraybool10data 0x7ffdedcb6bf0arraychar10data 0x7ffdedcb6bfaarrayint10data 0x7ffdedcb6ba0arraylong long 10data 0x7ffdedcb6b00arrayfloat 10data 0x7ffdedcb6bc8arraydouble 10data 0x7ffdedcb6b50editjust to exemplify the proposal from rustyx this is the changed codeinclude arrayinclude iostreamint mainvoid alignas16 stdarraybool 10 a alignas16 stdarraychar 10 b alignas16 stdarrayint10 c alignas16 stdarraylong long 10 d alignas16 stdarrayfloat 10 e alignas16 stdarraydouble 10 f stdcout arraybool10data adata stdendl stdcout arraychar10data void bdata stdendl stdcout arrayint10data cdata stdendl stdcout arraylong long 10data ddata stdendl stdcout arrayfloat 10data edata stdendl stdcout arraydouble 10data fdata stdendl return 0and this is the result when compiling it with intels icpc v1603arraybool10data 0x7ffe42433500arraychar10data 0x7ffe42433510arrayint10data 0x7ffe424334a0arraylong long 10data 0x7ffe42433400arrayfloat 10data 0x7ffe424334d0arraydouble 10data 0x7ffe42433450,['c++'] +1221431,mocha unit tests for firebase app i use firebase 330 and i want to use signinwithemailandpassword function in my mocha unit test but i get error authnetworkrequestfailedunhandled rejection error a network error such as timeout interrupted connection or unreachable host has occurred testjsconst firebase config apikey aizasydda1pouwy9eid1adbyumdxch k8ob7qrg authdomain myappfirebaseappcom databaseurl storagebucket myappappspotcomconst firebase api ref firebaseinitializeappfirebase configbeforefunction done promise new promisefunction resolve reject return firebase api refauthsigninwithemailandpasswordfirstuseremail firstuserpassword thenfunction userdata firstuserid userdatauid resolveuserdata done function error return rejecterror packagejsonscripts test mocha grep e2ejs invert compilers jsbabelregister r spec ui bdd timeout 70,['javascript'] +1222042,workaround for bug id4806603 regarding getbounds and setbounds on linux on the linux platform framegetbounds and framesetbounds do not work consistently this has already been reported in 2003 see here bugdobug id4806603for convenience i have simplified the stated code that results in a bug and paste it asimport javaawtbuttonimport javaawtframeimport javaawtrectangleimport javaawteventactioneventimport javaawteventactionlistener demonstrates a bug in the javaawtframegetbounds method author mirko raner ptsc version 10 20030122 public class getboundsbug extends frame implements actionlistener public static void mainstring arg getboundsbug frame new getboundsbug button button new buttonclick here buttonaddactionlistenerframe frameaddbutton framesetsize300 300 framesetvisibletrue override public void actionperformedactionevent event rectangle bounds getbounds boundsy setboundsbounds boundsy setboundsbounds unexpected behavior upon clicking the button the window is shifted slightly below on my system by 28 pixels each clickhere is a screen recording this behavior has been around for 13 years so probably there would not be any change from the official sidedoes anybody have a workaround for this bug specifically i would like to store and restore the windowframedialog at the previous location reliably on all platformsps my java installation is jdk180 102 for amd64 by oracle on ubuntu 16 linux since i recently migrated from windows to ubuntu i know that on windows the code above works as expectedthe adaptation to swing using swingworker produces the same effectimport javaawtrectangleimport javaawteventactioneventimport javaawteventactionlistenerimport javaxswingjbuttonimport javaxswingjframeimport javaxswingswingworkerpublic class getboundsbug extends jframe implements actionlistener public static void mainstring arg getboundsbug myjframe new getboundsbug jbutton myjbutton new jbuttonclick here myjbuttonaddactionlistenermyjframe myjframesetcontentpanemyjbutton myjframesetsize300 300 myjframesetvisibletrue override public void actionperformedactionevent event swingworkervoid void myswingworker new swingworkervoid void override public void doinbackground rectangle myrectangle getbounds myrectangley setboundsmyrectangle myrectangley setboundsmyrectangle return null myswingworkerexecute,['java'] +1222214,dynamic location based local notifications swift ios i am trying to fetch some arrival times for buses when a user approaches a stop i have tested to ensure that the regions are correctly being trigged by sending a basic local notification and i have also tested my web service call to ensure it is working properlyhowever i am having a hard time fetching the info then sending a notificationhere is my code var bgtask uibackgroundtaskidentifier uibackgroundtaskidentifier bgtask uiapplicationsharedbeginbackgroundtask selfwebservicegetstopestimatesroutestopids stoprouteidset routenamedict routenamedict completion result in if result error return let notification uilocalnotification notificationfiredate datetimeintervalsincenow 1 notificationalerttitle regionidentifier stop details notificationalertbody result notificationsoundname uilocalnotificationdefaultsoundname uiapplicationsharedschedulelocalnotificationnotification uiapplicationsharedendbackgroundtaskbgtask any one see why it might not be sending i have enabled background fetch and location services this is inside didenterregion,['ios'] +1222304,instant tostring prepends plus we have records in our datastore that have effective expiry time this information is stored using the string representation of instantthere are some records that would never expire but since the value for expiry date is mandatory we decided to store string representation of instantmaxso far so good we have search usecase to return all the records that are active within the input time range se we query the datastore and return all such records si ei which satisfy the condition si s e ei note that string representations are being compared herenow the problem is that is being prepended to the string representation of instantmax this is failing the condition e ei since ascii asciidigiti have written a piece of code to know after which second the starts getting prependedlong e instantnowgetepochsecond10for int i 0 i 5 i systemoutprintlne instantofepochmillie e 10which prints1471925168020160823t040608z1471925168024360607t170120z1471925168066340507t021320z14719251680486130614t221320z147192516804684040708t061320zi have the option of truncating the before persisting in datastore i am more interested in why this is happening and how can we explicitly avoid it,['java'] +1222439,what is the type of commandline argument argv in c i am reading a section from c primer plus about commandline argument argv and i am having difficulty understanding this sentence it says that the program stores the command line strings in memory and stores the address of each string in an array of pointers the address of this array is stored in the second argument by convention this pointer to pointers is called argv for argument values does this mean that the command line strings are stored in memory as an array of pointers to array of char,['c'] +1222440,how to connect to mysql using utf8 within a perl script in a nutshellwithin a perlscript how do i connect to mysql in a way that allows to transmit the fourbyte unicode character u1f61c i 12i from the perl script to a mysqltable where this character should be storedusing mysql enable utf8 1 does not solve the problemin detaili have exactly the same problem as described in the question error 1366 hy0 incorrect string value xf0x9fx98x9c for column comment at row 1 and even with the same unicode character i 12i u1f61c face with stuckout tongue and winking eye which produces the error messagedbdmysqlst execute failed incorrect string value xf0x9fx98x9c for column but i do not use php i use perlthe accepted answer in the other question saysrun mysql 55 or lateri check the versionmysql select version version 57130ubuntu016042 so it is 57 which is later than 55acheckedset tables character to utf8mb4i check the character set of my database my table and even of the reported columnmysql select default character set name from information schemaschemata where schema name mydatabase default character set name utf8mb4 mysql select ccsacharacter set name from information schematables t information schemacollation character set applicability ccsa where ccsacollation name ttable collation and ttable schema mydatabase and ttable name mytable character set name utf8mb4 mysql select character set name from information schemacolumns where table schema mydatabase and table name mytable and column name mycolumn character set name utf8mb4 so my database my table and the reported column all use the character set utf8mb4acheckedenable utf8 on your mysql connectionthis seems to be the problem the answer to the other question says set names utf8 or use an option when connecting that similarly enables iti do not know how to set names utf8 within a perl script so i did it how i did it over the last years i think that this is an option when connecting that similarly enables itit is at the end of the long line that begins with my dbh dbiconnectusrbinperl wuse strictuse warningsuse utf8use encodeuse dbibinmode stdout utf8here i connect using the parameter mysql enable utf8 create database handlemy dbh dbiconnectdbimysqldatabasemydatabasehostlocalhostauserapasswordmysql enable utf8 1prepare the statement create statement handlemy sth dbhprepareinsert into mytable mycolumn valuesthis does not work sthexecutei 12i ithis does not work either sthexecuteencode utf8i 12i iend processingdbhthisconnectexit0both executes throw the same error only the line number at the end changesdbdmysqlst execute failed incorrect string value xf0x9fx98x9c for column mycolumn at row 1 at mytestscriptpl line 16what am i doing wronghow can i do it better,['mysql'] +1222542,how to rotate uialertcontroller in swift i have a working uialertcontroller but i want to rotate the alertview by 90 degrees lefthow can i do it my code is here belowlet alert uialertcontrollertitle message message sample preferredstyle alertalertaddactionuialertactiontitle okay style defaultaction in presentviewcontrolleralert animated true i tried to add alertviewtransform cgaffinetransformmakerotationcgfloatm pi 2but it does not workthank you,['ios'] +1222773,meaning of const stdstring const after the function definition reading the answer for one exercise in c primer 5th edition i found this codeifndef cp5 ex7 04 hdefine cp5 ex7 04 hinclude stringclass person stdstring namestdstring addresspublicauto get name const stdstring const return name auto get addr const stdstring const return address endifwhat does const stdstring const mean in this case,['c++'] +1223029,bluetoothadapter actionthiscoveryfinished i just started to take a look at xamarin and now i want to scan for bluetoothdevices therefor i use the following codebluetoothadapter bluetoothadapter bluetoothadapterdefaultadapterbluetoothadapterstartthiscoveryand i have the following class for getting the resultbroadcastreceiverintentfilternew bluetoothadapteractionthiscoveryfinishedpublic class bluetoothreceiver broadcastreceiver public bluetoothreceiver public override void onreceivecontext context intent intent if bluetoothadapteractionthiscoveryfinishedequalsintentaction i have also set the permissions for my app to bluetooth and bluetooth admin everything just works fine and the onreceivemethod is called correctly my problem now is how do i get the found devices from the parameters of the onreceivemethod,"['c#', 'android']" +1223246,how the new rangebased for loop in c17 helps ranges ts the committee changed the rangebased for loop fromc11 auto range range expression for auto begin begin expr end end expr begin end begin range declaration begin loop statement to c17 auto range range expression auto begin begin expr auto end end expr for begin end begin range declaration begin loop statement and people said that this will make implementing ranges ts easier can you give me some examples,['c++'] +1223277,live streaming from ipcamera to wowza server via android device rtsp android i am sending live streaming from ip camera to wowza server via android device here i am stream in device then want to send on server using rtspso please provide useful link,['android'] +1223475,vectorassign with value in sequence is the following welldefinedstdvectorstdstring vtestvassign1 vat0if the old sequence was destroyed before the new one is constructedthe reference passed to assign would be invalidated and hence theprogram would be illformeddoes the standard mention this case thevalue being part of the old sequence or something similar anywheremaking this construct wellformed i could not find anythingfrom the copy of dinkumwares standard library implementation shippedwith vs2010 assign n is whats called internally by assignvoid assign nsize type count const ty val assign count val ty tmp val in case val is in sequence erasebegin end insertbegin count tmpthe commentin case val is in sequencesuggests that either thestandard explicitly states that assigning an element that is part ofthe current sequence is wellformed or that dinkumwares implementationjust tries to be smart which one is it,['c++'] +1223704,how to get the name of from generic type and pass it into jsonproperty i get the following error with the code belowan object reference is required for the nonstatic field method or property responsepropnamecode public class responset response private string propname get return typeoftname jsonpropertypropname public t data get set,['c#'] +1223761,hides isnan in in c14 c11 i have here a small test app which uses isnan from mathhinclude iostreaminclude mathhint main double d nan stdcout isnand n return 0build and run under 3 different standards g stdc98 maincpp aout1 g stdc11 maincpp aout1 g stdc14 maincpp aout1now we also include cmath and test with both isnan and stdisnaninclude iostreaminclude cmathinclude mathhint main double d nan stdcout stdisnand n stdcout isnand n return 0build and runc98 works g stdc98 maincpp aout11c11 and c14 do not isnan is not found g stdc11 maincppmaincpp in function aint mainamaincpp1025 error aisnana was not declared in this scope stdcout isnand n maincpp1025 note suggested alternativein file included from maincpp30usrincludec5cmath6415 note astdisnana isnan tp x g stdc14 maincppmaincpp in function aint mainamaincpp1025 error aisnana was not declared in this scope stdcout isnand n maincpp1025 note suggested alternativein file included from maincpp30usrincludec5cmath6415 note astdisnana isnan tp x note the order of inclusion is not important if i include cmath before mathh or after the result is the samequestionswhy is isnan gone without having to go back and change old code to compile under the new standard is there any way to fix this,['c++'] +1223801,why does the spec prohibit passing class types to variableargument c functions passing nonpods to variable argument functions such as printf is undefined behaviour 1 2 but i do not understand why the c standard was set this way is there anything inherent in variable arg functions that prevents them from accepting classes as argumentsthe variablearg callee indeed knows nothing about their type but nor does it know anything about builtin types or plain pods it acceptsalso these are necessarily cdecl functions so the caller can be responsible eg for copying them upon passing and destroying them on returnany insight would be appreciatededit i still see no reason why the suggested variadic semantics would not work but zneaks answer demonstrates well what it would take to adjust compilers to it so i accepted it ultimately it might be some historical glitch,['c++'] +1224070,what is the alternate of headerctgetmenu in ext js 3 i am using ext js 3 and i need to get ahold of the menu of my column header i tried to use afterrender of gridmy code is somewhat likelisteners afterrender function var menu thisheaderctgetmenu wrong but apparently headerct is not available in ext js 3 what other possible options can i use i did not get any ideas from the docs,['javascript'] +1224102,retrieve google user from ios extension i am trying to create a share extension for my application which requires to login to google from the extension i have setup the sharing group keychain and am able to write from the main application and read the extension target but i cannot login to google from the extension because gidsigninsharedinstancehasauthinkeychain always returns falseis there any way to login to google from an extension and how do i do that any help would be appreciated,['ios'] +1224114,windowactivitybarfalse not working i am writing an app which will be on embedded device and i need to remove actionbar alongside the titlebar and contentoverlayi found a solution and inserted the following in my stylesstyle namenoactionbar parentandroidstylethemehololight item nameandroidwindowactionbarfalseitem item nameandroidwindownotitletrueitem item nameandroidwindowfullscreentrueitem item nameandroidwindowcontentoverlaynullitem styleand also add the line to my activity in androidmanifestandroidthemestylenoactionbarand in the end i got no title bar no content overlay however the actionbar is still there please advice i use androidthemeandroidstylethemehololight and my targetsdkversion is 18,['android'] +1224154,js promise instantly retrieve some data from a function that returns a promise can anyone recommend a pattern for instantly retrieving data from a function that returns a promisemy simplified example is an ajax preloaderloadpageindexhtmlthenthisplaypageif this is downloading a large page i want to be able to check whats happening and perhaps cancel the process with an xhr abort at a later stagemy loadpage function used to before promises return an id that let me do this latervar loadpageid loadpageindexhtmlthisplaypagedosomethingloadpageidcancelloadpageloadpageidin my new promise based version i would imagine that cancelloadpage would reject the original loadpage promisei have considered a few options all of which i do not like is there a generally accepted method to achieve this,['javascript'] +1224156,chrome debugger does not work on typescript files i am using webstorm 20162 angularcli webpack2in the photo i cannot create a breaking point on lines 192023when i create on line 21 the console does not print what i told him in line 19i am seeing ts file that should be debugged but it seems i am debugging other file or the js file that i do not have any access toi would like to debug the ts file if possible and if not the js fileangularclijson project version 100beta11webpack2 name storeapp02 apps main srcmaints tsconfig srctsconfigjson mobile false addons packages e2e protractor config configprotractorconfjs test karma config configkarmaconfjs defaults prefix app sourcedir src styleext css prefixinterfaces false lazyrouteprefix styles node modulesbootstrapthistcssbootstrapmincss tsconfigjson compileroptions declaration false emitdecoratormetadata true experimentaldecorators true maproot module es6 moduleresolution node outdir thistouttsc sourcemap true target es5 typeroots node modulestypes types corejs,['javascript'] +1224583,sequence of logical or in es6unicode regular expression in chrome a vs firefox a consider the following unicodeheavy regular expression emoji standing in for nonascii and extrabmp charactersi 14i12i 14i12i 14i12i 14i12i 14i12i 14i12matchi 14i12i 14i12i 14i12ugfirefox returns i 14i12 i 14i12 i 14i12 i 14i12 i 14i12 i 14i12 i 34i chrome 5202743116 and node 640 both return null it doesnat seem to care if i put the string in a variable and do strmatcha nor if i build a regexp object via new regexpi 14i12i 14i12i 14i12 guchrome is ok with just oring two sequences i 14i12i 14i12i 14i12i 14i12i 14i12i 14i12matchi 14i12i 14i12ug is ok itas also ok with nonunicode aakkzzkkaamatchaakkzzug worksam i doing something wrong is this a chrome bug the ecmascript compatibility table says i should be ok with unicode regexpsps the three emoji used in this example are just standins in my application theyall be arbitrary but thistinct strings but i wonder if the fact that i 14i12i 14i12i 14i12i 14i12i 14i12i 14i12matchi 14i12i 14i12i 14i12ug works in chrome is relevant,['javascript'] +1224746,d3 animating a bubble chart within a given radius bubble chart basei am trying to animate the bubbles via changing their scale and if possible fade them in and out at some stage i need to cluster them with some kind of gravity to occupy more of a containing circumferencefunction var diameter 250 var svg d3selectgraphappendsvg attrwidth diameter attrheight diameter var bubble d3layoutpack sizediameter diameter valuefunctiond return dsize padding3 var color d3scaleordinal domainlorem ipsum dolor sit amet consectetur adipisicing range98abc5 8a89a6 7b68 6b486b a05d56 function randomdata var data1 children name aa classname aa size 170 name bb classname bb size 393 name cc classname cc size 293 name dd classname dd size 89 var data2 children name aa classname aa size 120 name bb classname bb size 123 name cc classname cc size 193 name dd classname dd size 289 var j mathfloormathrandom 2 1 consolelogj j if j 1 return data1 else return data2 changerandomdata d3selectrandomize onclick function changerandomdata function changedata consolelogdata data generate data with calculated layout values var nodes bubblenodesdata filterfunctiond return dchildren filter out the outer bubble var vis svgselectallcircle datanodes visenter insertcircle attrtransform functiond return translate dx dy attrr functiond return dr stylefill functiond return colordname attrclass functiond return dclassname vis transitionduration10 visexit remove,['javascript'] +1224927,show div on hover of direct parent only i am trying to make a div appear when you only hover its direct parent div right now the div will show when you hover any div of that type see this simple example of the problemhow can i make a menu div only show when the mouse hovers directly over that div and not it is child divswidget width 150px height 150px backgroundcolor d position relativemenu backgroundcolor 4 thisplay flex position absolute top 0 thisplay nonewidgethover menu thisplay flexdiv classwidget stylewidth 500px height 500px backgroundcolor e div classmenu pi should only be visible when you hover the big outer widget and not when you are hovering the small inner widgetp div div classwidget styleleft 200px top 200px div classmenu pi should only be visible when you hover the small inner widgetp div divdiv,"['html', 'css']" +1224997,sfinae constexpr with stdget this is a followup question to detecting constexpr with sfinaei want to detect if an element of a tuple or anything which can be used with stdget is constexpr so i wrote the following helpers similar to what xeo gavetemplatesize t struct sfinae true stdtrue typetemplatesize t n class tauto checkconst t arg sfinae truestdgetnargntemplatesize t n clastdfalse type checknow my test driver codeint main constexpr stdtuplesize t size t arg45 typedef decltypecheck0decltypeargarg is cexpr stdcout is constexpr is cexprvalue nhowever this always prints out false for me to check that for some reason the false overload is not always being called i commented out the false overload and get the compiler errornote candidate template ignored substitution failure with and 0 t const std tuple nontype template argument is not a constant expression auto checkconst t arg sfinae truestdgetarg0however i do know that i can call stdgetnarg and get a constexpr valuetemplatesize t nclass aint main constexpr stdtuplesize t size t arg45 astdget0arg a valthis compiles just finewhy does the check function not detect the constexprness correctlyhow do i fix thisi tested this with clang 380 on ubuntu 1604editas a further test based on sams answer i tried the formtemplatesize t n class tauto checkconst t arg return sfinae truestdgetnarg0this gets rid of the comma operator entirely which gcc 540 compiles just fine but clang 380 still complains about interestingly clang highlights that arg itself is not constexprwhy is this problematic still what are the rules for constexpr function arguments,['c++'] +1225098,how to metaprogram a generic list extraction for building a function call i have a family of classes with methods with the following signaturedouble computelistt parsthis method performs a calculation with the parameters received through pars for each computelist method i have another computex1 x2 xn which is the method implementing the real calculation thus computepars should do some such asdouble computelistt pars t x1 listpop back t x2 listpop back so on until last parameter xn t xn listpop back return computex1 x2 xn here the real implementation is calledthis pattern repeats many times the only thing that could change is the size of pars list and of course the implementation of computex1 x1 i would like to find a way for driying this repetitive process concretely extracting the parameters in pars list and building the call to computex1 x2 xn i have been trying without success to do some macro tricks my question is if it exists some way based on metaprogramming that allows me to implement computelistt pars once and simply reuse it and order to perform the call to computex1 x2 xnedit this is the signature of the other computex1 vtlquantity computeconst vtlquantity x1 const vtlquantity x2 any number of pars according the class const vtlquantity xn constvtlquantityis a class representingdoubles their units and other stuff,['c++'] +1225286,shuffling a string so that no two adjacent letters are the same i have been trying to solve this interview problem which asks to shuffle a string so that no two adjacent letters are identical for example abcc acbc the approach i am thinking of is to1 iterate over the input string and store the letter frequency pairs in some collection2 now build a result string by pulling the highest frequency that is 0 letter that we did not just pull3 update decrement the frequency whenever we pull a letter4 return the result string if all letters have zero frequency5 return error if were left with only one letter with frequency greater than 1with this approach we can save the more precious less frequent letters for last but for this to work we need a collection that lets us efficiently query a key and at the same time efficiently sort it by values something like this would work except we need to keep the collection sorted after every letter retrievali am assuming unicode charactersany ideas on what collection to use or an alternative approach,['c#'] +1225344,passing temporary struct as template argument i am in the process of creating a vector class and am trying to figure out ways to reuse the maximum amount of code for different size vectorsheres a basic exampletemplatetypename t unsigned int dclass vectorpublic union t vd struct t x t y t z t w vector forunsigned int i0 id i thisi t0 vectort scalar forunsigned int i0 id i thisi scalar inline t operatorint i return thisvi i want the member variables to be publicly accessible exvectorfloat2 vecprintfx 2f y 2fn vecx vecywhat i would like to do is something along the lines of thistemplatetypename tclass vector2 public vectort2 struct t x t y templatetypename tclass vector3 public vectort2 struct t x t y t z and have it override a struct in the uniontemplatetypename t unsigned int d struct cclass vectorpublic union t vd place the passed struct here is there any feasible way to do this i do not want to use anything other than the standard library if possible thanks in advanceedit after reading upon all of the answers i have understood that the way i am using unions is incorrect thank you to mm for pointing this out i have since chosen to go a different route but i have selected the answer that best fit what i was looking for at the time once again thank you for all of the welcomed responses below,['c++'] +1225645,why c standard requires stdpartition to meet different complexities for different types of iterator the c standard requires stdpartition to have different numbers of predicate applications between forwarditerator and bidirectionaliterator for the forwarditerator version the number of predicate applications shall be n where n stdthistancefirst last but for the bidirectionaliterator version the number of predicate applications shall be n2 obviously both versions have time complexity on my question is why does it bother to provide different requirements for different type of iterators such requirement forces a lot of compilerseg msvc implement the function stdpartition in two ways to meet such requirement which does not seem to be very eleganta further question are there any algorithm that relies on this coefficient such that when n2 becomes n the asymptotic complexity will be different for my understanding if we consider the masters theorem for the form in tn atnb fn the coefficient in fn does not matter muchcf an equivalent implementation of msvcs partitiontemplateclass bidirit class unarypredbidirit partitionbidirit first bidirit last unarypred pred stdbidirectional iterator tag while true while first last predfirst first if first last break last while first last predlast last if first last break stditer swapfirst last first return firsttemplateclass forwardit class unarypred forwardit partitionforwardit first forwardit last unarypred pred stdforward iterator tag first stdfind if notfirst last pred if first last return first for forwardit src stdnextfirst src last src if predsrc stditer swapfirst src src return firsttemplateclass forwardit class unarypredforwardit partitionforwardit first forwardit last unarypred pred return partitionfirst last pred typename stditerator traitsforwardititerator category,['c++'] +1225653,find all ndimensional lines and diagonals with numpy using numpy i would like to produce a list of all lines and diagonals of an ndimensional array with lengths of ktake the case of the following threedimensional array with lengths of threearray 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26for this case i would like to obtain all of the following types of sequences for any given case i would like to obtain all of the possible sequences of each type examples of desired sequences are given in parentheses below for each case1d linesx axis 0 1 2y axis 0 3 6z axis 0 9 182d diagonalsxy axes 0 4 8 2 4 6xz axes 0 10 20 2 10 18yz axes 0 12 24 6 12 183d diagonalsxyz axes 0 13 26 2 13 24the solution should be generalized so that it will generate all lines and diagonals for an array regardless of the arrays number of dimensions or length which is constant across all dimensions,['python'] +1225921,using css calc with step we have used a pure css base progress bar the main css part is as belowcontainer width 600px margin 20px autoprogressbar margin 0 padding 0 counterreset stepprogressbar li liststyletype none width 25 float left fontsize 12px position relative textalign center texttransform uppercase color 7d7d7dprogressbar libefore width 30px height 30px content counterstep counterincrement step lineheight 30px border 2px solid 7d7d7d thisplay block textalign center margin 0 auto 10px auto borderradius 50 backgroundcolor whiteprogressbar liafter width 100 height 2px content position absolute backgroundcolor 7d7d7d top 15px left 50 zindex 1the htmldiv classcontainer ul classprogressbar li classactiveloginli lichoose interestli complete sample could be found at as you can see it mess up for seven step the reason is progressbar li width which is fixed to 25 we wanted to make it dynamic base on number of steps so we tried width calc 100 steps or calc 100 countersteps but none of them worked any idea please consider that we are building a component which build a progress bar on the fly so we can not find the actual number of steps,"['html', 'css']" +1226180,ring allocator for lockfree update of member variable i have a class that stores the latest value of some incoming realtime data around 150 million eventssecondsuppose it looks like thisclass datastate event latest event public pushes event atomically void push eventconst event restrict e pulls event atomically event pull eventi need to be able to push events atomically and pull them with strict ordering guarantees now i know i can use a spinlock but given the massive event rate over 100 millionsecond and high degree of concurrency i would prefer to use lockfree operationsthe problem is that event is 64 bytes in size there is no cmpxchg64b instruction on any current x86 cpu as of august 16 so if i use stdatomicevent i would have to link to libatomic which uses mutexes under the hood too slowso my solution was to instead atomically swap pointers to the value problem is dynamic memory allocation becomes a bottleneck with these event rates so i define something i call a ring allocator brief lockfree static shortlived allocator used for a ringbuffer elements are guaranteed to persist only for size calls to get nexttemplatetypename t class ringallocator t arena stdatomic size t arena idx const stdsize t arena size public brief creates a new ringallocator param size the number of elements in the underlying arena make this large enough to avoid overwriting fresh data ringallocatortstdsize t size arena sizesize allocate pool arena new tsize zero out pool stdmemsetarena 0 sizeoft size arena idx 0 ringallocator delete arena brief return next elements pointer threadsafe return pointer to next available element t get next return arenaarena idxexchangearena idx arena size then i could have my datastate class look like thisclass datastate stdatomicevent latest event ringallocatorevent event allocator public pushes event atomically void push eventconst event restrict e store event event new ptr event allocatorget next new ptr e swap event pointers latest eventstorenew ptr stdmemory order release pulls event atomically event pull event return latest eventloadstdmemory order acquire as long as i size my ring allocator to the max of threads that may concurrently call the functions there is no risk of overwriting data that pull event could return plus everythings super localized so indirection would not cause bad cache performance any possible pitfalls with this approach,['c++'] +1226964,android how to exclude devices with webview that does not support webgl ie are on the gpu blacklist i have an app containing a webview that runs very poorly on devices where hardware acceleration does not work eg some samsung s4s running 501 i know from heresupporting webgl on android 5s webviewthat i can use crosswalk and ignore the gpu blacklist so that it will run smoothlyhowever this library causes other problems in the app and the blacklist is there for a reason rightwhat i would like to do is exclude devices where webgl does not work for whatever reason i have looked herebut i am not sure if there is a way to specify this,['android'] +1227061,method overloading with optional parameter i have a class as follows with two overload methodclass a public string xstring a string b return hello a b public string xstring a string b string c bye return c a b if i call the method x from another class with two parameters then which method is going to execute and why iestring result new axfname lnamei have tested this in my console application and the method with 2 parameters execute can someone explain this,['c#'] +1227289,how to check if ienumerable covariant to ienumerable what is common rule to check if ienumerablet1 covariant to ienumerablet2 i have made some experiments1object obj test stringienumerableobject objs new string100works because ienumerableout t is covariant and string inherits object 2interface myinterfacestruct mystructmyinterfaceobject v new mystructconsolewritelinenew mystruct is object output true ienumerableobject vs new mystruct100 compilation error heremystruct is actually an object but it does not work because object is reference type and mystruct is value type ok i see some logic here3consolewritelinenew mystruct is valuetype output truevaluetype v2 new mystructienumerablevaluetype vs2 new mystruct100 compilation error hereshould work because ienumerableout t is covariant and mystruct is valuetype but does not work ok maybe mystruct does not actually inheritst valuetype4myinterface v3 new mystruct consolewritelinev3 is myinterface output true ienumerablemyinterface vs3 new mystruct100 compilation error hereeven this way cannot convert mystruct to myinterface oh really you just did it one line beforei have tried to formulate common rulepublic static bool iscovariantienumerabletype t1 type t2 return t2isassignablefromt1 t2isvaluetype is this correctso questions is how to actually determine if ienumerablet1 covariant to ienumerablet2 is my iscovariantienumerable function correct if yes is there any simplier way to check it if not how to fix itsee also these articles 1 2,['c#'] +1227655,how do i keep my input fields on one line while centering the div that contains them i gave this css class to some input fields searchfield thisplay inlineblockthis is their underlying html div idsearchformsearch for resultsbr form idsearchform actionracessearch acceptcharsetutf8 methodgetinput nameutf8 typehidden valuea input typetext namefirst name idfirst name placeholderfirst name clasearchfield input typetext namelast name idlast name placeholderlast name clasearchfield input typetext namemy object idmy object placeholderevent size50 clasearchfield input altsearch typeimage srcassetsmagnifyingglass0220f37269f90a370c3bb60229240f2a4e15b335cd42e64563ba65e4f22e4png clasearch buttonform divhowever despite the fact that there is enough horizontal screen real estate one of them keeps wrapping to teh next line as this fiddle illustrates how do i keep these items on one line assuming there is enough browser width note i also want to keep the div they are within vertically and horizontally centerededit this is what i see in the fiddle this is on firefox note the text fields are not on one lineedit 2per monicas fiddle this is what i see note that the first naem and last name are on one line but the event text box is on the next line i would like all three to be on the same line even if the black box containing them has to expand,"['html', 'css']" +1227660,rails active record has many foreign key after custom function consider following modelsclass user ar has many resourcesendclass resource ar belongs to userend i have a requirement where the foreign key is saved after applying some function on it so the value of user id in resources table does not match id in users table but it can be calculate again from idhow can i define the association let us say that function is dummy func,['ruby-on-rails'] +1227787,quicklookqlpreviewcontroller delegate methods are not calling in ios 10 xcode 8 currently i am testing my current version in ios10 i am using xcode 8 beta 6 for testing here quicklookqlpreviewcontroller delegate methods are not calling this code set had been worked with xcode 7 and ios 93 versions i checked this issue in apple developer forum but could not find a answer anyone have fixed this issue i am using objectivechow to use quicklookqlpreviewcontroller in xcode 8 ios 10 solution for ios 10 previewer as a subview this issue is occurred when you add the the previewer as a subview then we are using below code lines mainly in ios 93 and below versionsself addchildviewcontrollerpreviewerselfview addsubviewpreviewerviewpreviewer didmovetoparentviewcontrollerselfin ios 10 issue comes due to the below code lineself addchildviewcontrollerpreviewerfor ios 10 we need to check the version and add above code line below is the working code set qlpreviewcontroller previewer qlpreviewcontroller alloc init previewerdatasource self previewerdelegate self to avoid ios 10 previewer issue if system version less than100 self addchildviewcontrollerpreviewer cgfloat width selfviewframesizewidth cgfloat height selfviewframesizeheight previewerviewframe cgrectmake0 102 width height300 selfview addsubviewpreviewerview previewer didmovetoparentviewcontrollerself,['objective-c'] +1228008,propagate property changes through multiple classes i am trying to figure out how to properly pass properties through multiple classes i know i can just implement inotifypropertychanged in each class and listen for changes on the property but this seems to be quite a lot of unnecessary codethe situationi have a class let us call it class1 with two dependency properties filterstatement string and filter filter class setting the statement affects the filter and vice versa the conversion logic between statement and filter however is not located in class1 but in class3 which class1 does not know directly in between there is class2 which just has to pass through the changes you can imagine class 1 to 3 beeing viewmodel model and repository though in the real situation this does not completly match public class class1 public static readonly dependencyproperty filterproperty dependencypropertyregister filter typeoffilter typeofclass1 new frameworkpropertymetadatanull public static readonly dependencyproperty filterstatementproperty dependencypropertyregister filterstatement typeofstring typeofclass1 new frameworkpropertymetadatanull public filter filter get return filtergetvaluefilterproperty set setvaluefilterproperty value public string filterstatement get return stringgetvaluefilterstatementproperty set setvaluefilterstatementproperty value public class2 myclass2instance get set public class class2 public class3 myclass3instance get set public void changeclass3instanceobject someparam this can change the instance of myclass3instance and is called frome somewhere else when changed the new class3 instance has to get the property values of class1 public class class3 private filter filter here is where the filter set in class 1 or determined by the statement set in class 1 has to be put public string myfiltertostatementconversionmemberfunctionfilter filter public filter mystatementtofilterconversionmemberfunctionstring statement my naive solution would be to duplicate the properties across all three classes implement inotifypropertychanged in class2 and class3 and listen to the changes propagating everything down to class3 and in result back up to class1 is not there a better solution to this,['c#'] +1228489,overflowx hidden causing responsive nav menu positing issue question backgroundi am using jasny bootstrap to implement a responsive offcanvas reveal style menuthe issuewhen the menu is opened on a mobile device the scrolling element of the menu is not enablingi have wrapped the entire app where my angularjs view is injected with a div style overflowyhidden as shownbody ngappapp div styleoverflowxhidden div uiview styleheight100 view is injected here based on routing div divbodythis overflow styling means i can now scroll the menu on a mobile device but i now have an issue where and when the menu is scrolled to the top there is a gap showing the menu underneath as shown hereonce the page is scrolled down slightly the responsive navbar showsthe codethe following is as shown above this is the main view div where the page is injected depending on its routingbody ngappapp div styleoverflowxhidden div uiview styleheight100 view is injected here based on routing div divbodythis is the results view of the app which contains the navbar elementsdiv ngcontrollerresultscontroller ngshowhidesearch styleheight100 div classnavmenu navmenudefault navmenufixedleft idupdatemenu div classtextcenter headerpadh3compzee img srcimagescompzeelogosmallpng classlogosize h3div div classcollg12 pullinmenu form ngsubmitsearch novalidatenovalidate div classformgroup label forsearchsearch termlabel input typetext classformcontrol ngmodelitem iditemupdate required div div classformgroup label forsearchproduct categorylabel select classformcontrol ngmodelcatagory required option value thisabled selectedselect a product categoryoption optionalloption optionbabyoption optionbusiness office amp industrialoption optioncameras amp photographyoption optionclothes amp accessoriesoption optioncomics books amp magazinesoption optioncomputers amp tabletsoption optionconsolesoption optiondvds films amp tvoption optiongarden amp patiooption optionhealth amp beautyoption optionholiday amp traveloption optionhomeoption optionkitchenoption optionjewelleryoption optionmobile phones amp accessoriesoption optionmusical instrumentsoption optionmusicoption optionpet suppliesoption optionshoesoption optionsporting goodsoption optiontoys amp gamesoption optionvehicle parts amp accessoriesoption optionvideo gamesoption optionwatchesoption select div div classformgroup label forsearchcountrylabel select classformcontrol ngmodelselectedcountry required option value thisabled selectedselect a countryoption optionukoption optionusoption optionfroption optiondeoption select div div classformgroup div classtextcenter img ngsrccountryimg div div div classformgroup label forsearchmarketplacelabel select classformcontrol ngmodelselectedmarketplace required option value thisabled selectedselect a marketplaceoption optionebay amazonoption optionebayoption optionamazonoption select div div classformgroup div classtextcenter img classmarketplaces ngsrcimage img classmarketplaces ngshow showimg ngsrcimagesecond div div div classformgroup div classcontent rzslider rzslidermodelminrangesliderminvalue rzsliderhighminrangeslidermaxvalue rzslideroptionsminrangeslideroptionsrzslider div div div classformgroup label forsearchmin pricelabel input typetext classformcontrol ngmodelmintextval idslidermarginvaluemin readonly div div classformgroup label forsearchmax pricelabel input typetext classformcontrol ngmodelmaxtextval idslidermarginvaluemax readonly div div classformgroup textcenter label forsearchprices high to lowlabel input idhightolowbox typeradio ngvaluetrue ngmodelpriceorder div div classformgroup textcenter label forsearchprices low to highlabel input idlowtohighbox typeradio ngvaluefalse ngmodelpriceorder div div classformgroup button classbtn btnsuccess laddasearchingserviceupdating typesubmit datastylezoomin stylewidth100 spanupdatespan button div form div div div classcanvas idresultsview div classnavbar navbardefault navbarfixedtop button idmenubtn typebutton ngclickscrollup classnavbartoggle datatoggleoffcanvas datarecalcfalse datatargetnavmenu datacanvascanvas span classiconbarspan span classiconbarspan span classiconbarspan button div div idcontainerid classcontainer div classtopoffset div classcollg12 textcenter div iditemholder h4bsearchingservicesearchlistlength results found from your search criteriabh4 div classpanel paneldefault collg12 textcenter ngshowsearchingservicenoresults div classpanelbodyimg srcimagescompzeelogosmallpng classlogosize pwe could not find any results to match your search criteriaplease review your search terms and try againpdiv div div ngrepeatitem in searchingservicefiltereditems classcollg4 div classpanel paneldefault maxpanelheight div classpanelheading textoverflow idpanelheading h3 classpaneltitle textcenterbitemtitlebh3 div div classpanelbody a hrefitemurl target blankimg srcitemimage classpicheight imgrounded imgresponsive centerblock a h4 classtextcenterbitempricebh4 h4 classtextcentera hrefitemurl classbtn btnsuccess target blanksee moreah4 div classtextcenterimg classoriginpic srcitemmarketplaceimg div div div div div div div div classcollg12 textcenter uibpagination totalitemsitemslength ngmodelcurrentpage maxsizemaxsize classpaginationmd boundarylinkstrue rotatefalse uibpagination div div divdiv,"['html', 'css']" +1228605,edittext cursor still blinks after closing the soft keyboard is an edittext cursor supposed to continue blinking after the soft keyboard is closed or is this a result of testing on an emulator and wouldnt happen on an actual device as pointed out by the second post in this thiscussionupdatei know that the edittexts still have the cursor blinking because they are still in focus logged a message whenever edittext lost focus but message was never logged when soft keyboard closedupdatei have tried doingoverridepublic void onbackpressed superonbackpressed getcurrentfocusclearfocusso that every time the keyboard is closed the edittext currently in focus loses that focus and onfocuschanged is called the problem is that onbackpressed is not called when the back button is pressed when the keyboard is up i know this because i put a toast in onbackpressed and no toast shows when the back button is pressed whilst the keyboard is up,['android'] +1228681,collision detection on multiple canvas layers i am struggling on figuring out how to detect collisions on assets drawn on different canvas layers i have made two arrays that hold the stuff i want to collide with called collidable objects layer1 and collidable objects layer2 these arrays basically draw the tables and the wall in the back which the character should not be able to pass throughbarjs basically holds the whole bar scene you see in the link below and mainjs is the loop that makes my player move i think my architecture is all messed up cause i do not see an easy way to tie these two together so any advice on thatare modules necessary here or are they just hurting me the way it is now i am not sure how i add more scenes with different collision testingi am assuming the collision testing happens in the main loopfunction main var now datenow var dt now last time 10 clearcanvas drawcharacter frame last time now requestanimframemainso a couple questions really what would the algorithmpsuedocode look like to have my player detect these collidable objects in barjs second is my architecture appropriate to handle multiple scenes for example once the player leaves the bar to outside outsidejs how can i handle that transition so my player can detect objects regardless of its scene i was thinking i end up with a scene class or something i am not surethanks in advance find the plunk link here,['javascript'] +1229066,set default value to null when converting to double in c i want to pass the null if the string is empty while converting from string to double can somebody help me with the syntax as where i going wrongcurrent syntaxingredientminrange stringisnulloremptyminrange converttodoubleminrange null,['c#'] +1229146,why necessary to make copy first when using iterator on implicitly shared container the qts documentation says the followingthanks to implicit sharing it is very inexpensive for a function to return a container per value the qt api contains dozens of functions that return a qlist or qstringlist per value eg qsplittersizes if you want to iterate over these using an stl iterator you should always take a copy of the container and iterate over the copy for example rightconst qlistint sizes splittersizesqlistintconst iterator ifor i sizesbegin i sizesend i wrongqlistintconst iterator ifor i splittersizesbegin i splittersizesend i what will happen if the wrong method is applied,['c++'] +1229184,splitting a list into uneven tuples i am trying to split a list of strings into a list of tuples of uneven length containing these strings with each tuple containing strings initially separated with blank strings basically i would need the parameterized split that i could apply to lists if my initial list looks likeinit a b c d e fgh ij k l the last element of this list is always a closing there can be consecutive s which shall be considered as singlesthe result i need isend a b c d e fgh ij k li already have ugly code that does the job and gets out of range once the list is fully popped outend while init1 u initpop l while init1 u lappendinitpop endappendtupleli would like to use comprehensions but having unsuccessfully tried unpacking argument lists reversing selfreferenced lists using deque queues and various code smells i am now doubting whether it makes sense looking for a nested comprehension solution,['python'] +1229240,is sizeofvoid a legal expression from 5331 i found thatthea sizeofa operator shall not be applied to an expression that has function or incomplete typefrom 395 i found thatincompletelydefined object types anda cv voida area incomplete typesanyway for sizeof does not evaluate it is operands i would have said that sizeofvoid was a legal expression actually gcc compiles it and the result is 1on the other side from here void is not mentioned while thiscussing sizeof neither when the types having size 1 are mentioned nor in the list of the ones having an implementation defined sizethe question is thus is sizeofvoid a legal expressionis it guaranteed to have size equal to 1or is it a legal expression resulting in an ub and that is all,['c++'] +1229395,swift how to access player object of full screen html video i want to be able to hold a reference to the avplayer instance that takes over the screen when playing html videos full screen from embedded browsers my first approach was thisextension avplayerviewcontroller override public func viewdidappearanimated bool superviewdidappearanimated printherez prints correctly printselfplayer prints nil however it always returns nil so i am trying a different approach i want to override either the initializer or play method of avplayer but i cannot seem to do it without getting objectivec selector conflictsimport avkitimport mediaplayerextension avplayer override func play this does not work just an example of what i want superplay printdo stuff here is there a way to override one of avplayers instance methods so i can store a reference to self or is it not even an avplayer,['ios'] +1229436,react native component dependency which requires rnpm link i just created a component for reactnative that i will push soon to npm as a package although i am facing an issuethe component is dependent of another npm package called reactnativeimageresizer this package needs to be linked with rnpm in order to workalthough when i just install my component in a brand new project the dependency would not be linked automatically and the native library would not appear in the project of course when i run rnpm link it would not add it to the project either so i am wondering what would be the best way to install and link this dependencymacbookproexample npm install reactnativeimagecrop preinstall usersalexmngnworkreactnativeimagecropexamplenode modulesstagingreactnativeimagecrop95365d1b npm install save reactnativeimageresizer gitsshalexmngnreactnativeimagecropgit90e002c7d0f01c9d61277c30cad375560f09a94a usersalexmngnworkreactnativeimagecropexamplenode modulesstagingreactnativeimagecrop95365d1ba unmet dependency reactnative0310a npm warn requires a peer of reactnativev0142 but none was installednpm warn no repository field node modulesreactnativeimagecropnode modulesreactnativeimageresizer usersalexmngnworkreactnativeimagecropexamplea gitsshalexmngnreactnativeimagecropgit90e002c7d0f01c9d61277c30cad375560f09a94amacbookproexample rnpm linkmacbookproexample nothing gets linked herealso as you can see up there i have an unmet peer dependencies issue with reactnative when i install my component in my example project even though it is listed properly with the right version in my dependencies in packagejson name example version 001 private true scripts start node node modulesreactnativelocalcliclijs start dependencies react 1521 reactnative 0310 reactnativeimagecrop git any idea why it complainsrepo of the component available here thanks,['javascript'] +1229554,sql server query why am i getting deadlock i have the following codeset transaction isolation level read committed this is for clarity onlydeclare jobname nvarchar128begin tran select jobname jobname from dbojobdetails where executionstate status 1 waitfor delay 010 update dbojobdetails set executionstate status 10 where jobname jobnamecommit and second piece that is almost the sameset transaction isolation level read committeddeclare jobname nvarchar128begin tran select jobname jobname from dbojobdetails where executionstate status 1 waitfor delay 015 update dbojobdetails set executionstate status 20 where jobname jobnamecommit the difference is in the status to which were setting 10 vs 20 and delay 10s vs 15si am executing them in parallel in management studio two tabs now the problem with read committed transaction isolation level it works as expected the last modification is applied and both scripts execute successfully however that is not what i want i want to execute just one and the second should do nothing that is why i tried to change the level to repeatable read according to my knowledge which i want to challenge right now it should behave like thisfirst transaction starts and locks the rows it readsfirst transaction is then waiting for 10 secondssecond transaction starts in the meantime and cannot execute the select since it is locked by the first onefirst transaction finishes the wait updates the table commitssecond transaction can then proceed and does nothing since all the rows with status 1 were already updated unfortunately the results that i am seeing are far from that the transactions are deadlocked and one of them is killed by sql server i do not really understand why this is happening since they are accessing resources in the same orderhere are scripts necessary for testingcreate table dbojobdetails jobname nvarchar128 not null executionstate status int null default 0 constraint pk dbojobdetails primary key clustered jobname asc goinsert into jobdetails values my job 1update jobdetails set executionstate status 1additional notesi am testing this with only one row in the tablechanging the level to serializable also results in deadlockthe reason why this code looks like this is because i am trying to simulate what orm is going to do first get the entity then check in code if the status is 1 and then send the update with where based on pk i know i could write that code without orm having the update with where executionstate status 1,['sql'] +1229598,converting some values of a json string to an integer in php i have the following php codedata arrayid postidname postnamecountry postcountrycurrency postcurrencydescription postdescriptiondata string json encodedatathe sample json is as follows id7 namedean countryus currency840 descriptiontest i need to make the id field an integer only and keep currency as a string so that the json becomes this id7 namedean countryus currency840 descriptiontest i tried usingdata string json encodedata json numeric checkbut it also turns currency to an integeris there any way that i can make id an integer and leave currency as a string,['php'] +1229670,ios remove word from uitextview suppose i have a string in a uitextview that is nsstring str hello world what are you doing when i tap on the text i can delete the character by character but what i want is if any word starts with like are then when i tap on that word and press backspace the entire word ie areshould be deleted instead of a character is it possible that when i tap on any word that has a prefix like are it will be highlighted and press backspace will delete that word how can i do that,"['ios', 'objective-c']" +1229704,documenton click handler and standard click handler behaving differently on ios i generally bind click handlers using the formdocumentonclick element function to avoid issues with elements being loaded later this was working correctly on desktop browsers and chrome emulating iphone but on an actual iphone this was not working and i tried solutions like cursor pointeri noticed that another button was working using the standard click handler i changed my new button to use elementclickfunction and it started working why are these two methods of applying a click handler operating differently on ios,"['jquery', 'ios', 'iphone']" +1229757,how to initialize const member requiring computations to be performed i understand that for a classclass a const int myint public a const int yourint a const stdstring yourstringi could initialize myint in the initializer list like soaa const int yourint myint yourint however what is the proper way of initializing myint from the second constructor if the the data required to compute it comes say from a string and the computations may be involved,['c++'] +1229959,allure integration with multimodule test suite we have an test suite which is based on maven framework and consists of multimodule modules used project no codetest test classes are included under srcmainjava testngxml in srcmainresourcescore configured to execute basic utilities for environment setupdriver configures test buckets and modulates report generation using testngtrying to integrate the report generation using allure i have added the following to the project pomxml build pluginmanagement plugins plugin groupidorgapachemavenpluginsgroupid artifactidmavensurefirepluginartifactid versionmavensurefirepluginversionversion configuration testfailureignorefalsetestfailureignore argline javaagentsettingslocalrepositoryorgaspectjaspectjweaveraspectjversionaspectjweaveraspectjversionjar argline properties property namelistenername valueruyandexqatoolsallurejunitallurerunlistenervalue property properties configuration dependencies dependency groupidorgaspectjgroupid artifactidaspectjweaverartifactid versionaspectjversionversion dependency dependencies plugin plugin groupidorgapachemavenpluginsgroupid artifactidmavencompilerpluginartifactid versionmavencompilerpluginversionversion configuration sourcejdkversionsource targetjdkversiontarget configuration plugin plugin groupidorgapachemavenpluginsgroupid artifactidmavendeploypluginartifactid versionmavendeploypluginversionversion plugin plugin groupidorgeclipsejettygroupid artifactidjettymavenpluginartifactid version9210v20150310version configuration webappsourcedirectoryprojectbuilddirectorysitealluremavenpluginwebappsourcedirectory stopkeystopstopkey stopport1234stopport configuration plugin plugins pluginmanagementbuildreporting excludedefaultstrueexcludedefaults plugins plugin groupidruyandexqatoolsalluregroupid artifactidalluremavenpluginartifactid version22version plugin pluginsreportingalso the dependencies for the same to the test pomxml as allure related dependencies dependency groupidruyandexqatoolsalluregroupid artifactidalluretestngadaptorartifactid version1416version exclusions exclusion groupidjunitgroupid artifactidjunitartifactid exclusion exclusions dependency dependency groupidcomgithubdetroghostdrivergroupid artifactidphantomjsdriverartifactid version104version dependency dependency groupidorghamcrestgroupid artifactidhamcrestallartifactid version13version dependency dependency groupidruyandexqatoolsalluregroupid artifactidallurejavaannotationsartifactid version150rc2version dependencystep 1 after executing the tests mvn execjava pl driver i can see a targetallureresults folder generated step 2 mvn jettyrun reads started jetty serverstep 3 but when i go to localhost8080 on my browser it just has a headingdirectory question i doubt the path specified by me is incorrect somewhere so jetty is unable to locate the reports but could not figure out where is it for the tests that are executed or for the testngxml in resources or do i need to correct the path somewhere in the pom onlyalso is the way i am trying to use the dependenciesin parent project pom correctupdate 1the exec configuration used is as follows build plugins plugin groupidorgcodehausmojogroupid artifactidexecmavenpluginartifactid version150version configuration mainclasscomdriverdrivermainclass configuration plugin pluginsbuildappreciate any response,['java'] +1230229,string gets assigned to a list without a compilation error as i know one of the main purposes of generics in java is providing compiletime type safety if it gets compiled the code will run without issuesthen why is the following code being compiledpublic static void mainstring args string s getlistprivate static t extends list t getlist return tnew arraylistit compiles fine where is my typesafe compilation the getlist method has nothing in common with the string class,['java'] +1230301,catching and debugging invalid use of reference to local variable inside moved lambda i have come across an hardtodebug situation in one of my real projects where i was accidentally accessing a reference to a local variable inside a lambda that had been moved the access was being done from another thread but the moved lambda was kept alive until the second thread was finishedthe bug only occurred with optimizations thisabled and was caused by careless refactoringi have created a minimal example available here on wandbox that reproduces the issuestruct state int x 100template typename tfvoid eat1tf f call the lambda f simulate waiting for the second thread to finish stdthis threadsleep for10mstemplate typename tfvoid eat0tf f move the lambda to some other handler eat1stdforwardtffvoid use statestate s will print 100 stdcout sx n separate thread note that s is captured by reference stdthread ts simulate computation delay stdthis threadsleep for500ms will print garbage stdcout sx n tdetachint main eat0 local lambda variable that will be accessed after the lambda is moved state s function that takes s by reference and accesses it in a separate thread after the lambda is moved use states surprisingly none of the sanitizers and warning flags managed to help herei have tried the following combinations of compilers and sanitizers with wall wextra wpedantic g o0flags always enabledcompilers g 611 on arch linux x64 clang 380 on arch linux x64 g 531 on fedora x64 clang 370 on fedora x64sanitizers fsanitizeaddress fsanitizeundefined fsanitizethreadnone of the combinations produced any helpful diagnostic i expected either addresanitizer to tell me i was accessing a dangling reference or undefinedsanitizer to catch ub while accessing it or threadsanitizer to tell me a separate thread was accessing an invalid memory locationis there a reliable way to diagnose this problem should i post this example to any of the sanitizers bug trackers as a feature requestdefect,['c++'] +1230763,overload resolution and explicit template arguments the following code prints func 2why does the compiler treat the second template as a better match in presence of explicit not deduced template arguments why is there no ambiguity i would appreciate quotations from the c standardinclude iostreamtemplateclass tstruct identity typedef t typetemplateclass tvoid funct stdcout func 1ntemplateclass tvoid functypename identityttype stdcout func 2nint main funcint1,['c++'] +1230826,fastest way to produce a mask with and ones starting at position i what is the fastest way in terms of cpu cycles on common modern architecture to produce a mask with len bits set to 1 starting at position postemplate class uinttypeconstexpr t make maskstdsize t pos stdsize t len body of the function call of the functionauto mask make maskuint32 t4 10 mask 0 0 001 10 in binary with msb on the left and lsb on the rightplus is there any compiler intrinsics or bmi function that can help,['c++'] +1230880,how to set up popup positions anchor for element in kendo column template i use kenod ui to create my web ui i have a column template like belowvar template input iddetailsbutton typeimage srcimagesdetail buttonpng ngclickshowdetalsthisdataitem contact i want to popup a window every time i click the details button and the popups position should be at the bottom right of the button which i click heres what i do currentlyvar popup detailspopuppopupkendopopup anchor detailsbutton origin bottom rightbut it does not work every time the popup thisplay at the bottom right of the button in the first row not the bottom right of the button which i clickchecking the generated html all of the buttons id are samedetailsbutton so the popup always thisplay related to the first detailsbuttonupdatedthis is my changed solution but still does not workfunction popupdetailsitem detailsgridkendogrid columns datasource itemdetails var anchor detailsbutton itemid var popup detailspopup popuppkendopopup anchor anchor origin bottom right popupdatakendopopupopen anyone can help,"['javascript', 'jquery']" +1231004,recyclerview scrolling on insert i am trying to use recyclerview to create a chat application i am using a linearlayoutmanager with setreverselayouttrue when i am scrolled all the way to the bottom which is the dataset start newest message and a new message is inserted into the dataset the item appears at the bottom of the list as expected the view is scrolled up to make room for the new itemthe problem i have is when i have scrolled up to see the older messages when a new message is inserted to the beginning of the dataset the view is scrolled up by approximately one message height even though that message is not even rendered since it is out of the viewports rangehow can i keep the scrolling behavior when the view is scrolled to the bottom but thisable it when i have scrolled to the older messagesupdatei also made a small app where this problem is reproducedupdate 2 i committed the fix that worked to the repo i made as wellrelevant code hopefullycompile comandroidsupportrecyclerviewv72420xml androidsupportv7widgetrecyclerview androidlayout widthmatch parent androidlayout heightmatch parent androidcliptopaddingfalse androidpaddingbottom8dp androidpaddingtop8dp applayout behaviorstringappbar scrolling view behaviorrecyclerview init codelayoutmanager new linearlayoutmanagercontextlayoutmanagersetorientationlinearlayoutmanagerverticallayoutmanagersetreverselayouttruerecyclerviewsetlayoutmanagerlayoutmanagerrecyclerviewsetscrollcontainertruerecyclerviewsetlayoutanimationnullrecyclerviewsetitemanimatornulladapter new chatadapterrecyclerviewsetadapteradapteradapterpublic class chatadapter extends recyclerviewadapterchatviewholder private listmessagewrapper dataset public chatadapterlistmessagewrapper dataset thisdataset dataset sethasstableidstrue override public long getitemidint position return datasetgetpositiongetid override public int getitemcount return datasetsize public void datasetchangedlistmessagewrapper dataset thisdataset dataset notifydatasetchanged when a new item is added to the dataset i just call the datasetchanged method in the adapter,['android'] +1231027,user defined runtime attributes ibinspectable set after predefined attributes i am looking to add a new ibinspectable attribute computed property to uilabel via a category method ideally i want this attribute to be set after the labels text is set via setvalueforkey as this ibinspectable attribute may result in the the uilabels text being updated and we do not want the text in the uilabel to later replace it looking at the documentation there is no mention if predefined attributes are always set set before user defined attributes during the nibstoryboard load for attributes configured in interface builderare custom attributes added to an object in interface builder using ibinspectable or user defined runtime attributes guaranteed to be set after the standard predefined objects propertiesattributes,['ios'] +1231031,different behaviors for mouse click and touch wrong functionality with touchable screen but using mouse stackoverflow helped me too much with current version but currently i am completely lost as i do not know how to solve one issue i will be really thankful for any advicei have product container with parameters they show up on mouse hover done with css problem is that if somebody will tap on mobile it will fire both events click and mouseover but i need different behavior for mobile devices so i used solution from stackoverflow where i can check if browser knows touchstart event it works fine until somebody will come with touchable screen but using mouse so this user will click on container and parameters will show up without redirecting to product detail but it is wrong for mouse behaviorwhat i need is that if somebody will tap on image it will first show up parameters and on second tap it will redirect to product detail different behavior is only on tap on button which automatically redirects user to product detail but if somebody will use mouse we have hover effect so even first click on image can redirect user to product detail pagecurrent javascript code is commented so there is workaround what works fine on desktop and mobiles but it does not work on hybrid devices with touchable screen with mouse commented code is how i thought about solution as i added there workaround with mouseentermouseleave functions this does not work for mobile devices as they also fire those events same problem is with touchstarttouchend eventscan anybody help pleasevar usedmouse falseproductsgrid containernotovermouseenterfunction usedmouse trueproductsgrid containernotovertapfunctione if ontouchstart in window usedmouse location change if already hovered or tap target is button if thishasclassover etargethasclassbutton thisaddclassdetail add detail thisable hover effect on actual container return true epreventdefault estoppropagation productsgrid containerremoveclassover remove all over effects thisaddclassover add over effect to actual container return false do nothing because script made over effect productsgrid containernotovermouseleavefunction usedmouse falseproductsgrid width 100 textalign centerproductsgrid rowstd productsgrid row margin 0 0 0 22px textalign leftproductsgrid row leftcolumn float left webkitboxsizing borderbox mozboxsizing borderbox boxsizing borderbox width 3 margin 0 padding 0 0 0 22pxproductsgrid row productimage overflow hidden thisplay block webkitboxsizing borderbox mozboxsizing borderbox boxsizing borderbox width 100 height auto border 1px solid c9d5d8productsgrid row productimage img thisplay block width 100 important height auto important margin 0productsgrid clearstd productsgrid clear clear both margin 0productsgrid container position relative margin 0 0 50pxproductsgrid optionswrapper position relative overflow hidden width 100 margin 0 paddingtop 5pxproductsgrid parametersproductsgrid containerdetail optionswrapper parametersproductsgrid containerdetailhover optionswrapper parameters position absolute left 0 right 0 webkittransition all 250ms linear moztransition all 250ms linear mstransition all 250ms linear otransition all 250ms linear transition all 250ms linear webkittransform translatex100 moztransform translatex100 mstransform translatex100 otransform translatex100 transform translatex100 margintop 5px paddingtop 66px background eff9ffproductsgrid containerhover optionswrapper parametersproductsgrid containerover optionswrapper parameters webkittransform translatex0 moztransform translatex0 mstransform translatex0 otransform translatex0 transform translatex0productsgrid parameters sizewrapper height auto borderbottom 0 noneproductsgrid parameters span overflow hidden float left webkitboxsizing borderbox mozboxsizing borderbox boxsizing borderbox width 50 height 33px borderbottom 1px solid bdccd4 paddingleft 10px whitespace nowrap fontsize 13px color 5f727c lineheight 30pxproductsgrid nameboxstd productsgrid namebox position relative margin 0productsgrid h3std productsgrid h3 overflow hidden height 42px margin 15px 12px 18px whitespace normal fontsize 18px fontweight 700 color 0 lineheight 21pxproductsgrid h3 a textdecoration none fontweight bold color 0productsgrid h3 ahover textdecoration noneproductsgrid description overflow hidden height 40px margin 0 12px 11px fontsize 14px fontweight 400 color 81929c lineheight 20pxproductsgrid description p margin 0 padding 0price wrapperstd price wrapper margin 0 bordertop 1px solid bdccd4 borderbottom 1px solid bdccd4 padding 9px 8px 10pxprice wrapperafter content clear both thisplay blockprice wrapper addtocart float rightprice wrapper abutton float right width 136px height 39px backgroundcolor a5c82d textalign center textdecoration none fontsize 14px fontweight 700 color f lineheight 39pxscript srcscriptscript srcscriptdiv classproductsgrid div classrow div classleftcolumn div classcontainer a classproductimage href img src altproduct name titleproduct name a div classoptionswrapper div classparameters div clasizewrapper span classheightheight 952 cmspan span classwidthwidth 2105 cmspan span classlengthlength 1875 cmspan span classcolorspan div div div classnamebox h3 classproductnamea href titleproduct nameproduct nameah3 div div classdescriptiondescriptiondiv div div classprice wrapper a classbutton hrefdetaila div div div divdiv,"['javascript', 'jquery']" +1231039,share image element transition thisplay incorrect size i have a recycle view to show all photo thumbnail items when click on item i use transition for imageview in this item to detail activity the problem is that image source is gotten from internet by uil and sometime not always the images not reload correct size like this on view holder item click final pairview string pairs transitionhelpercreatesafetransitionparticipantsthis false new pairitemviewholder viewholderthumbnail getstringrstringtransitionname profile image new pairitemviewholder viewholdertvname getstringrstringtransitionname profile name activityoptionscompat transitionactivityoptions activityoptionscompatmakescenetransitionanimationthis pairs startactivityforresultintent requestcode transitionactivityoptionstobundledetail activity try to post pone transition until uil load finishactivitycompatpostponeentertransitionthisgetsupportfragmentmanagerbegintransactionreplaceridlayoutcontent new detailfragmentcommitfragment detailimageloadergetinstancethisplayimageurl imageviewdetail new imageloadinglistener override public void onloadingstartedstring imageuri view view override public void onloadingfailedstring imageuri view view failreason failreason finishanimation override public void onloadingcompletestring imageuri view view bitmap loadedimage finishanimation override public void onloadingcancelledstring imageuri view view finishanimation private void finishanimation activitycompatstartpostponedentertransitiongetactivity imageviewdetailinvalidate fragment detailxml framelayout androidlayout widthmatch parent androidlayout heightmatch parent imageview androidtransitionnamestringtransitionnameprofileimage androidididimageviewdetail androidlayout widthmatch parent androidlayout heightmatch parent androidadjustviewboundstrue androidscaletypecentercropframelayouti even wait views are laid out before load image but still not workimageviewdetailgetviewtreeobserveraddonpredrawlistenernew viewtreeobserveronpredrawlistener override public boolean onpredraw code load image from uil return false is there any way to avoid this issue,['android'] +1231513,incrementing a variable used twice in an initializer list undefined behavior edit not already answered the linked question was about ordinary rvalues initializer lists are a separate if related conceptis this statement welldefined or is using the prefix increment operator in an initializer list on a variable that appears twice in the list undefined behaviorstruct t t i i i am most interested in ansi c but it would also be useful to know if other versions of c andor c differ and if similar constructs like the following are legalstruct t t i i struct t t i i struct t t i i struct t t i i,"['c++', 'c']" +1231539,why do not lambda expressions require but function does i have some code use lambda expression like itinclude vectorinclude algorithmint main stdvectorint vi31 stdsortvibeginviendint xint y return xy return 0which does not require include functional to compile but if i use a variable to store the lambda functioninclude vectorinclude algorithminclude functionalint main stdvectorint vi31 stdfunctionvoid compfint xint y return xy stdsortvibeginviendcompf return 0then i need to include functional to compile why and why sort does not also include functional already,['c++'] +1231614,android fragment back stack i have used multiple fragments in my project i want to save a fragments state and restore this state when i come back to this in this fragment i show multiple images which change on button click i use the following code for this string backstatename fragmentgetclassgetnamefragmentmanager fragmentmanager getsupportfragmentmanagerboolean fragmentpopped fragmentmanagerpopbackstackimmediatebackstatename 0if fragmentpopped fragmenttransaction fragmenttransaction fragmentmanagerbegintransaction fragmenttransactionreplaceridcontainer body fragment fragmenttransactionaddtobackstackbackstatename fragmenttransactioncommitit works fine it saves state but it does not show previous images any help suggestion or tutorials would be highly appreciated thank you,['android'] +1232206,how to show steps in sympy are there any way to get the step by step solution in sympy for example solving x25 4 step 1 x25545 step 2 x29 step 3 x 3 or x 3,['python'] +1232276,thisable anchor tag first click on devices and need to work second click i have a dom like this when i click the anchor tag first time on devices i want to thisable the anchor tag and second click it will go to the url good answers must be appreciatedfunctionvar oreintedwidth windowwidthif oreintedwidth 1200 var clicklinks socialfindulchildrenliclicklinksonclick a functioneventsclicklinkseachfunctionindex element thisclosestliremoveclaselected thisclosestliaddclaselectedifthisclosestlihasclaselectedeventspreventdefaultelse div clasocialul lia hrefabouthtml target blankoneali lia hrefabouthtml target blanktwoali lia hrefabouthtml target blankthreeali ul ul div,"['javascript', 'jquery', 'html']" +1232326,initializing javamathbiginteger sorry cause this might look like a stupid yes or no question but i am very new to this so i need an answerbiginteger i bigintegervalueof0andbiginteger i new biginteger0are they the same,['java'] +1232709,i get the type initializer for microsoftcctcctprojectnode threw an exception when opening ccproj files after installing azure sdk 29 i have a solution with an azure cloud project in it that is targeting the 27 version of the microsoft azure sdk which i could openbuild and deploy without problems since visual studio was nagging me to update i went ahead and installed the new azure sdk version of 29 after that update i cannot open the cloud project files and visual studio 2015 community edition now fully updated to the latest as of the time i am writing this gives me this error messagemytestccproj error the type initializer for microsoftcctcctprojectnode threw an exceptioni am able to open the project if i manually edit the ccproj file and change theproductversion27productversionvalue to 29 however i can not use that since other people are working on this project and they still want to remain on the 27 version of the azure sdk which is also currently deployed to productionis there a way to allow visual studio to open older versions of cloud projects do i have to uninstall the azure sdk updatesthank you all,['c#'] +1232729,does roleenvironmentgetconfigurationsettingvalue read everytime from cfg file the azure role setting is very useful since it lets you change values onthefly while iis is running but the problem is if you have plenty users and if it reads every time the config value from file it is not best practice to use it without putting it in a static variable the next problem if you put it in a static variable then you have to reset iis every time you change it i did some research and found similar question on stackoverflow which tells that only first time reads conf on file then it stores it on cache but that question which was answered was for configurationmanager mine is about rolemanager from azurethis is the line which gets the current setting on azureroleenvironmentgetconfigurationsettingvalueappnamesettingkeythis is the one that saves it in cache which i know how it works and gets current setting ex connectionstring in webconfigconfigurationmanagerconnectionstringssettingkeyconnectionstring,"['c#', '.net']" +1232875,how can i polymorphically store and access different types from the same inheritance hierarchy in contiguous memory for polymorphism the usual approach is to use stdvectorbase however i have to provide the addresses myself that is to manage the memory myself whether i use stdunique ptr or raw pointersi would like to have a polymorphic storagebase type that accepts any type that inherits from base i also want the types to be stored in contiguous memory for faster traversal and for cache related concernshowever there is a pretty big issue in the absence of type information at the storage level the correct movecopy operations must be called on resizefeature requestany type that inherits from the base class can be added to the storage no fixed inheritance hierarchiesthe inheriting types must be correctly aligned inside of the storage typethe correct move and copy operations must be called since i am not dealing with pod typeswhat mechanism can i use to achieve thiswhile i provide an answer i would welcome anyone to post their solution,['c++'] +1233058,use keypress to initiate action in nodejs i am using nodejs v45i wrote the function below to send repeated messages with a delayfunction send messages promiseresolve then send msg then delay10 then send msg then delay10 then send msg function delayduration return new promiseresolve settimeout resolve duration instead of delay i would like to activate the sending of messages using a keypress something like the function belowfunction send messages keystroke promiseresolve then send msg then keypressctrlb run subsequent line of code send msg if keystroke ctrlb is pressed then send msg then keypressctrlb then send msg,['javascript'] +1233100, i am using the following codeimport urllib2setting proxymyproxy httpsproxy urllib2proxyhandlermyproxyopener urllib2build openerproxyurllib2install openeropeneraccess urlauth token really long authenication tokenheaderscontenttypeapplicationjson charset utf8 authorization bearer s auth tokenurl req urllib2requesturl none headersreply urllib2urlopenreqprint replygetcodei am running the above as a jython script in ngrinder when i run the same script on my system with jython it works fine and returns 200ok status code when i run it on ngrinder i get the error1 ssl exception differences between the ssl socket behaviour of cpython vs jython are explained on the wiki supportany ideas why this is happeningedit i have been trying and the issue is definitely with the long authentication token i have a feeling it might be some encoding issue there was a similar question posted here before i read it but it was not described properly but it could be a good reference to think off of,['python'] +1233111,jquery datepicker convert select dropdown into ul i am using the jqueryui datepicker component however the month and year dropdowns are select tagsi need to style them in ways that are not possible with select elements so i would like to convert them to ul elements any help would be appreciated here is a starter jsfiddle with the jqueryui datepicker,"['javascript', 'jquery', 'html', 'css']" +1233496,can num be atomic for int num in general for int num num or num as a readmodifywrite operation is not atomic but i often see compilers for example gcc generate the following code for it try heresince line 5 which corresponds to num is one instruction can we conclude that num is atomic in this caseand if so does it mean that sogenerated num can be used in concurrent multithreaded scenarios without any danger of data races ie we do not need to make it for example stdatomicint and impose the associated costs since it is atomic anywayupdatenotice that this question is not whether increment is atomic it is not and that was and is the opening line of the question it is whether it can be in particular scenarios ie whether oneinstruction nature can in certain cases be exploited to avoid the overhead of the lock prefix and as the accepted answer mentions in the section about uniprocessor machines as well as this answer the conversation in its comments and others explain it can although not with c or c,"['c++', 'c']" +1233846,create gantt chart with hlines i have tried for several hours to make this work i tried using pythongantt package without luck i also tried plotly which was beautiful but i cannot host my sensitive data on their site so that would not work my starting point is code from herehow to plot stacked event duration gantt charts using python pandas three requirementsinclude the name on the y axis rather than the numbers if someone has multiple events put all the event periods on one line this will make pattern identification easier eg lisa will only have one line on the visualinclude the event listed on top of the corresponding line if possible eg lisas first line would say hirethe code will need to be dynamic to accommodate many more people and more possible event typesi am open to suggestions to visualize i want to show the duration for various staffing events throughout the year as to help identify patternsfrom datetime import datetimeimport pandas as pdimport matplotlibpyplot as pltimport matplotlibdates as dtdf pddataframename joejoelisalisalisaalice event hiretermhiretransfertermterm start date 201401012014020120150101201502012015030120160101 end date 201401312014031520150131201502282015050120160901 df dfnameeventstart dateend datedfstart date pdto datetimedfstart dateastypedatetimedfend date pdto datetimedfend dateastypedatetimefig pltfigureax figadd subplot1ax axxaxis dateax plthlinesdfindex dtdate2numdfstart date dtdate2numdfend date,['python'] +1233849,scrollrevealjs a reveal all items on click or event is there a way to reveal all items with scroll reveal with a click event perhaps a reveal all function problemi am using scroll reveal as well as isotope the sorting functionality of isotope reacts strange with scroll revealwhen i click a filter button i am calling the isotope function filter gridisotopefilter fishfilter examplehowever if i scroll down after clicking said filer button there are holes in my grid and i have to reclick the button after all items have been revealed via scrollinghere is a link to the webpage for reference thanks updatei have added the layout call here this at least fixes holes that were present beforewindowsr scrollreveal beforereveal function domel gridisotope layout fixes holes afterreveal function domel gridisotopelayout however the newly filtered items do not fade in as they do with scroll reveal they tile in as with the styling from isotope the ideal situation would be a reveal all and layout scenario that way you cannot notice any differences in animations or another situation could be just the simple constant fading in regardless of filters clicked thanks,"['javascript', 'jquery']" +1233933,mocking method calls using power mockito orgpowermockapimockitoclassnotpreparedexception i have an image loader class and i need to test some static methods in it since mockito does not support static methods i switched to power mockito but the static method i am testing has a method call base64encodetostringbytearray base64defaultto mock this i am using mockstatic method as below with preparefortest annotation powermockitomockstaticbase64classbut android studio is returning me still returning me an error as beloworgpowermockapimockitoclassnotpreparedexception the class androidutilbase64 not prepared for test to prepare this class add class to the preparefortest annotationbelow is my complete codecode to be testedimport androidgraphicsbitmapimport androidgraphicsbitmapfactoryimport androidutilbase64import androidwidgetimageview public static string convertbitmaptobase64bitmap imagebitmap boolean withcompression bytearrayoutputstream bytearrayoutputstream new bytearrayoutputstream imagebitmapcompressbitmapcompressformatpng 120 bytearrayoutputstream byte bytearray bytearrayoutputstreamtobytearray return base64encodetostringbytearray base64defaulttest class codeimport androidgraphicsbitmapimport androidutilbase64import orgjunitbeforeimport orgjunitrunnerrunwithimport orgmockitomockitoannotationsimport orgpowermockapimockitopowermockitoimport orgpowermockcoreclassloaderannotationspreparefortestimport orgpowermockmodulesjunit4powermockrunnerimport orgtestngannotationstestrunwithpowermockrunnerclasspreparefortestbase64classpublic class imageloadertest test public void testconvertbitmap byte array new byte20 powermockitomockstaticbase64class powermockitowhenbase64encodetostringarray base64defaultthenreturnasdfghjkl bitmap mockedbitmap powermockitomockbitmapclass string output imageloaderutilsconvertbitmaptobase64mockedbitmap assert outputisemptygradle dependenciestestcompile junitjunit412testcompile orgpowermockpowermock165testcompile orgpowermockpowermockmodulejunit4165testcompile orgpowermockpowermockapimockito165,['android'] +1233991,are map filter etc methods optimized to operate on a single intermediary array when possible consider the below snippet which converts an array of objects to an array of numbers with negative values filtered out and then doubled by 2var objects new array400fill value mathrandom 10 5var positiveobjectvaluesdoubled objectsmap item itemvaluefilter value value 0map value value 2when chained together like this how many actual array objects are created in total 1 or 3 excluding the initial objects arrayin particular i am talking about the intermediary array objects created by filter and then by the second map call in the chain are javascript runtimes smart enough to optimize where possible in this case to use the same memory areaif this cannot be answered with a clear yesorno how could i determine this in various browsers to the best of my knowledge the array constructor can no longer be overridden so that is not an option,['javascript'] +1234096,app is crashing after capturing picture using intents my app is crashing after capturing 5 to 6 photos using intentslog cat shows nothing am unable to find the reason why it is crashing please help me out private void capturephoto file root new fileenvironmentgetexternalstoragedirectory feedback if rootexists rootmkdirs file file new fileroot constantsprofile image name jpeg uri outputfileuri urifromfilefile intent photopickerintent new intentmediastoreaction image capture photopickerintentputextramediastoreextra output outputfileuri photopickerintentputextraoutputformat bitmapcompressformatjpegtostring photopickerintentputextrareturndata true photopickerintentputextraandroidintentextrascamera facing 1 startactivityforresultphotopickerintent requestcode override protected void onactivityresultint requestcode int resultcode intent data superonactivityresultrequestcode resultcode data if thisrequestcode requestcode resultcode result ok file root new fileenvironmentgetexternalstoragedirectory feedback if rootexists rootmkdirs file file new fileroot constantsprofile image namejpeg checkflowithispresentfile thisplaypic private void thisplaypic string filepath environmentgetexternalstoragedirectory getabsolutepath fileseparator feedback constantsprofile image name jpeg bitmap bmp bitmapfactorydecodefilefilepath bitmap scaled bitmapcreatescaledbitmapbmp 300 300 true file imgfile new filefilepath bitmap bmp decodefileimgfile if imgfileexists thispprofilepicsetimagebitmapbmp else thispprofilepicsetbackgroundresourcerdrawableuser image private bitmap decodefilefile f try decode image size bitmapfactoryoptions o new bitmapfactoryoptions oinjustdecodebounds true bitmapfactorydecodestreamnew fileinputstreamf null o the new size we want to scale to final int required size 70 find the correct scale value it should be the power of 2 int scale 1 while ooutwidth scale 2 required size ooutheight scale 2 required size scale 2 decode with insamplesize bitmapfactoryoptions o2 new bitmapfactoryoptions o2insamplesize scale return bitmapfactorydecodestreamnew fileinputstreamf null o2 catch filenotfoundexception e return null and above code is for capturing photo and thisplaying captured picture in imageview and am using mi tabedit actually app is not crashingit becomes white screen and if i press any button then it is crashing and onactivityresult is not executed when it become white screennew edit am able to replicate this i clicked on android monitor in that i clicked monitor then it shows memory utilization of the app when i interacting with app now in left side bar i clicked terminate application icon now the interesting thing is it destroys current activity and moves to previous activity that previous activity become white screenplease help me out guys,['android'] +1234261,why are are stdallocators construct and destroy functions deprecated in c17 the c17 specification deprecates the construct and destroy members of the stdallocator object the working group provided rationale for deprecating other member functions here under the heading deprecate the redundant members of stdallocatorhowever they do not mention specifically why those two members are deprecated or what the recommendation is for replacing that functionality i am assuming the implication is to use stdallocator traitsconstruct insteadi am a bit confused about whether implementing construct may actually still be necessary in some cases though because of this comment about stdallocator traitsconstructbecause this function provides the automatic fall back to placement new the member function construct is an optional allocator requirement since c11 for custom allocators eg for pagealigned memory using memalign will falling back to placement new always produce the correct behavior,['c++'] +1234477,edit existing pm2 process i have an existing pm2 process that i would like to add the maxmemoryrestart setting to how can i do that the process was created from the command line without a json fileif i were creating a new process i would just runpm2 start process name maxmemoryrestart 700m or whateverhow can i do the same for an existing process how can i confirm that it worksthanks,['javascript'] +1234550,understanding caching yesterday we had no power at home thus no internet so i assumed that i wouldnt be able to have my webapp work locally since at the end of indexhtml i havescript srcscriptscript windowjquery documentwritescript srcassetsjsvendorjqueryminjsscriptscriptscript srcscriptscript srcscriptscript srcscriptscript srcscripthowever that was not the case it would work smoothly so i guessed that the browser remembered the last time it downloaded these js fileswhen i reloaded my wepapp though it would fail to load the js files since there was no internet connection this behavior would happen again and againin both cases it would fail to downloadlink relstylesheet hrefbut that is not a critical error notice that the css of twitterbootstrap was locally in my project file that is why it is irrelevanti am trying to understand why any thoughtsi am using chrome version 5202743116 64bit in a macbook pro el capitanmine the browser used the cached versions of the js files but even on normal reload it would try to redownload them,"['javascript', 'jquery', 'html']" +1234675,convert variable string value to expression in javascript i am trying to convert a string value to expression so that i can use it in if condition likevar stringval 20 18 yes yesifstringval is it possible to do this please suggest methanks,['javascript'] +1234827,unable to run application via terminal but application working fine in xcode i am working on lilgp which is a c language based tool for genetic programming the problem that i am facing is that i am using xcode for the project and it is working fine and shows correct output via terminal but when i try to run the same application in deriveddata of my project in xcode i get segmentation fault 11then i have checked the console in utilities for errors which shows error like this process theisis 9325path usersuserlibrarydeveloperxcodederiveddatatheisisgszeehddtmnlkqdbicpeffygvkcwbuildproductsreleasetheisisidentifier theisisversion 0code type x8664 nativeparent process bash 8987responsible terminal 299user id 501datetime 20160911 010525158 0500os version mac os x 10116 15g31report version 11anonymous uuid 4063b9c3f525d9bdef5e358810571673sleepwake uuid ca5341a7c2524c76b6947f2dae196f79time awake since boot 570 secondstime since wake 1600 secondssystem integrity protection enabledcrashed thread 0 thispatch queue comapplemainthreadexception type exc bad access sigsegvexception codes kern invalid address at 0x068vm regions near 0x68 text 0100c4e0100c6a0 112k rxrwx smcow usersuserlibrarydeveloperxcodederiveddatatheisisgszeehddtmnlkqdbicpeffygvkcwbuildproductsreleasetheisis thread 0 crashed thispatch queue comapplemainthread0 libsystem cdylib 0x07f93a8b09e flockfile 41 libsystem cdylib 0x07f93a8d463 fscanf 1562 theisis 0x0100c57853 app initialize 195 appm6143 theisis 0x0100c4f245 main 453 mainm2054 libdylddylib 0x07f8e0575ad start 1thread 0 crashed with x86 thread state 64bit rax 0x07f5efb1970 rbx 0x0 rcx 0x0b0 rdx 0x0100c6aa8c rdi 0x0 rsi 0x0100c675d4 rbp 0x07f5efb1860 rsp 0x07f5efb1860 r8 0x0fc r9 0x07f740b1c10 r10 0x07f97709e01 r11 0x07f93a8d3c7 r12 0x450022575a4d98d4 r13 0x0 r14 0x0100c675d4 r15 0x0 rip 0x07f93a8b09e rfl 0x010246 cr2 0x068logical cpu 4error code 0x04trap number 14vm region summaryreadonly portion of libraries total1761m resident0k0 swapped out or unallocated1761m100writable regions total196m written0k0 resident0k0 swapped out0k0 unallocated196m100 virtual region region type size count noncoalesced activity tracing 2048k 2 kernel alloc once 4k 2 malloc 9604k 17 stack 640m 3 vm allocate 4k 2 data 8300k 141 linkedit 914m 4 text 847m 146 unicode 552k 2 shared memory 8k 3 total 2602m 312 however when i checked appm614 it has if strcmpc regress asim 0 where c is a chracter array and this array is working fine from last couple of months and in xcode too can anybody tell me what am i missingupdate1 the resolved project settings for both debug and release are same except for the binary paths for sure2 code not only works in xcode but is also working in eclipse and creating a working binary3 the part of the code that crashes in that the array c isdeclared as char c100initillized as strncpyc equation default datacsv sizeofcthe code block where it crashes if startfromcheckpoint oprintf out prg 50 not starting from checkpoint filen param get parameterappfitness cases if param null fitness cases 200 else fitness cases atoiparam if fitness cases 0 error e fatal error invalid value for appfitness cases file in file fopenc r fscanfin file d fitness cases if strcmpc regress asim 0 line 614 app y desired double mallocfitness cases sizeofdouble app fitness cases0 double malloc fitness cases sizeofdouble app fitness cases1 double malloc fitness cases sizeofdouble app fitness cases2 double malloc fitness cases sizeofdouble app fitness cases3 double malloc fitness cases sizeofdouble memsetapp fitness cases2 0 fitness cases sizeofdouble memsetapp fitness cases3 0 fitness cases sizeofdouble memsetapp y desired 0 fitness cases sizeofdouble app fitness importance int mallocfitness cases sizeofint asim code double x y for i 0 i fitness cases i fscanfin file lf x fscanfin file lf y app fitness cases0i x app fitness cases1i y if strcmpc regress asim 0 app y desiredi y app fitness importancei checkimportancex fclosein file datapointsperimportance int mallocmax datapoint importance1sizeofint memsetdatapointsperimportance 0 max datapoint importance1sizeofint for i 0 i fitness cases i printfd dnicheckimportanceapp fitness cases0i datapointsperimportancecheckimportanceapp fitness cases0idatapointsperimportancecheckimportanceapp fitness cases0i1 forint i0imax datapoint importancei printfimportance d dnidatapointsperimportancei oprintf out prg 50 d fitness casesn fitness cases for i 0 i fitness cases i x random double 20 10 change this line to modify the goal function y x x x x x x x x x x app fitness cases0i x app fitness cases1i y oprintf out prg 50 x 125lf y 125lfn x y else oprintf out prg 50 started from checkpoint filen,"['c++', 'c']" +1234866,add an alias for a property in javascript i think this is fairly simpleis there a simple way to add a secondary name for a property i think this one is string specific a i am not sure iec length this line pseudo codehello worldlength returns 11hello worldc this line is pseudo code meant to return 11in the example above there is an alias created for the property length is that possible to do in javascriptthanks,['javascript'] +1234874,corona sdk thisplay multi line notification i have some notifications in corona the problem is the text is too big and i would need to show bigger multi line notifications like the gmail app for example here is what the notifications look like nowhere is my codelocal notificationoptions alert text badge 2 sound alarmcaf custom foo bar local notification notificationsschedulenotification nextscheduletime day mathfloorday7 24 60 60 notificationoptions any idea how to do thisthanksserban,['android'] +1234953,voldemort types in c as you probably know in d language we have an ability called voldemort types and they are used as internal types that implement particular range functionauto createvoldemorttypeint value struct theunnameable int getvalue return value return theunnameablehere is how the voldemort type can be usedauto voldemort createvoldemorttype123writelnvoldemortgetvalue prints 123now i want to make sure that is this the equivalent to delegate in cpublic static void main var voldemort createvoldemorttype123 consolewritelinevoldemortpublic static funcint createvoldemorttypeint value funcint theunnameable delegate return value return theunnameable,['c#'] +1235053,menu content does not overflow it is parent in safari for ios i have created a menu using bootstrap 3 on a website this menu works fine in every browser i have tested in and at any screen size except safari on ios where the menu did not appear at all using css i forced the container of the menu to fill the width and to be 640px tall then i could see the menu so the problem seems to be with overflow however the containers parent and grandparent has an accumulated padding which makes no difference in any browser that i have tested except for in safari on ios this can be seen in screetshot number 2clearifying some termsthe menu is refering to the ul element with id headermenu this is marked red in the screenshot below the parent is refering to the immidiate parent with class navbarex1collapse this is marked blue in the screenshot below recreating the problemi was finally able to recreate the same problem in chrome by adding position absolute to the parent screenshots check out the code snippetfunctionheadermenu menuitemhaschildren a headermenu menuitemhaschildren spanafteronclick functione epreventdefaultif thisparenthasclasshidesub thisparentaddclashowsubremoveclasshidesubelsethisparentaddclasshidesubremoveclashowsubheadermenu closemenubutton spanbeforeonclick functione epreventdefaultif thisparentparentparenthasclasshidesub thisparentparentparentaddclashowsubremoveclasshidesubelsethisparentparentparentaddclasshidesubremoveclashowsubjquerycharset utf8import urlheadermenu float rightmedia maxwidth 991px navbardefault navbartoggle background rgba255 255 255 005 border 0 none borderradius 0 navbardefault navbartoggle iconbar backgroundcolor d23479 navbardefault navbartogglehover iconbar navbardefault navbartogglefocus iconbar backgroundcolor f navbardefault navbartogglehover navbardefault navbartogglefocus backgroundcolor d23479 navbardefault navbarcollapse navbardefault navbarform background rgba255 255 255 025 border 0 boxshadow none navbarcollapse margintop 10px mediamaxwidth991px navbarnavlia lineheight 70px navli fontsize 35px navbarnav width 100 textalign center margin 0px menymedia minwidth 992px headermenu onlymobile headermenu a span thisplay none important headermenu li position static headermenu li a thisplay inlineblock headermenu li aactive color d23479 headermenu li afocus color white headermenu li ulsubmenu thisplay block backgroundcolor white padding 30px width 100 height 100vh minheight 640px maxheight 768px position absolute zindex 100 left 0 headermenu li ulsubmenu li thisplay table width 100 headermenu li ulsubmenu li ulsubmenu thisplay tablerow headermenu li ulsubmenu li ulsubmenu li thisplay tablecell width 25 padding 15px headermenu li ulsubmenu li ulsubmenu lifirstoftype padding 15px 15px 15px 0 headermenu li ulsubmenu li ulsubmenu lilastoftype padding 15px 0 15px 15px headermenu li ulsubmenu lisubmenurowfirstoftype ulsubmenu li a thisplay block padding 5px headermenu li ulsubmenu li ulsubmenu li a fontsize 14px color black borderwidth 0 0 1px 0 borderstyle solid margin 0 0 10px 0 fontweight 600 bordercolor d23479 texttransform uppercase headermenu li ulsubmenu li ulsubmenu li ulsubmenu li width 100 headermenu li ulsubmenu li ulsubmenu li ulsubmenu li a color gray fontsize 12px headermenu submenurow thisplay block width 100 headermenu submenurownthoftype2 margintop 50px borderwidth 1px 0 0 0 bordercolor lightgray borderstyle solid headermenu submenurownthoftype2 ulsubmenu li a texttransform none fontweight 300 important border none headermenu contact a color d23479 important headermenu classiconbefore fontsize 26px color d23479 float left margin 0 10px position relative headermenu menuitemhaschildren span cursor pointer headermenu menuitemhaschildren spanafter margin 0 0 0 5px thisplay inlineblock headermenu menuitemhaschildrenhidesub spanafterbefore content backgroundimage url backgroundsize contain backgroundrepeat norepeat backgroundposition center center thisplay inlineblock width 15px height 15px headermenu menuitemhaschildrenshowsub spanafterbefore background none content a fontsize 27px fontweight 300 lineheight 12em fontfamily serif verticalalign middle color d23479 headermenu menuitemhaschildrenhidesub submenu thisplay none headermenu menuitemhaschildrenshowsub submenu thisplay block headermenu submenu closemenubutton thisplay block position absolute bottom 130px headermenu submenu closemenubutton spanbefore thisplay block width 100px marginleft auto marginright auto textalign center cursor pointer headermenu submenu closemenubutton spanbeforebefore content a color d23479 fontsize 42px fontfamily serif fontweight bold lineheight 32px thisplay block width 100px marginleft auto marginright auto textalign center headermenu submenu closemenubutton spanbeforeafter content lukk meny texttransform uppercase color c fontsize 12px thisplay block width 100px marginleft auto marginright auto textalign center media maxwidth 991px headermenu buttonnavbartoggle thisplay inlineblock width 42px height 32px backgroundcolor d23479 position absolute top 15px right 30px headermenu buttonnavbartogglebefore content a color white fontfamily serif fontsize 32px verticalalign top lineheight 16px headermenu backgroundcolor white position fixed top 0 left 0 width 100 minheight 100 height 100 zindex 10 overflow scroll margintop 0 padding 102px 20px 20px 20px headermenu onlycomputer thisplay none important headermenu li headermenu submenu li textalign left bordertop 1px solid c headermenu showsub ulsubmenu bordertop 1px solid c headermenu a thisplay inlineblock lineheight 14em texttransform uppercase fontweight 400 padding 0 color 2 fontsize 18px headermenu ulsubmenu li ulsubmenu li a color 4 fontsize 15px headermenu ulsubmenu li ulsubmenu li ulsubmenu li a color 6 fontsize 13px fontweight 300 headermenu li aactive headermenu lishowsub a color d23479 headermenu ulsubmenu paddingleft 15px headermenu menuitem1350 submenu padding 0 headermenu submenurow thisplay block width 100 headermenu submenu lifirstoftype headermenu submenurow headermenu bottomcontactinfo headermenu bottomcontactinfo li border none important headermenu menuitemhaschildrenhidesub span thisplay none headermenu menuitemhaschildrenhidesub a headermenu menuitemhaschildren a width 100 thisplay inlineblock backgroundrepeat norepeat backgroundsize 22px 22px backgroundposition 98 50 headermenu menuitemhaschildrenhidesub a backgroundimage url headermenu menuitemhaschildrenshowsub a backgroundimage url headermenu menuitemhaschildrenhidesub submenu thisplay none headermenu menuitemhaschildrenshowsub submenu thisplay block headermenu lifirstoftype headermenu bottomcontactinfo submenu bordertop 1px solid d23479 padding 0 headermenu bottomcontactinfo a color 3 headermenu classiconbefore fontsize 20px color d23479 margin 0 10px position relative texttransform none headermenu menuitemhaschildren span cursor pointer headermenu menuitemhaschildren spanafter margin 0 0 0 5px thisplay inlineblock headermenu inactive a headermenu inactive span headermenu a span thisplay none headermenu logo position absolute top 10px left 30px border 0 headermenu logo a backgroundimage url backgroundrepeat norepeat backgroundsize 100 100 height 34px width 167px fixing the menu for safari on ios dropdownbackdrop position static importantnavbarex1collapse zindex 9collapsein backgroundcolor white width 100 height 640px position fixed thisplay block overflow scroll position static importantheadermenu zindex 9 important thisplay blockscript srcscriptscript src integritysha384tc5iqib027qvyjsmfhjomalkfuwvxzxupncja7l2mcwnipg9mgcd8wgnicpd7txa crossoriginanonymousscriptnav classnavbar navbardefault rolenavigation div classnavbarheader a href classnavbartoggle collapsed datatogglecollapse datatargetnavbarex1collapse ariaexpandedfalse span clasronlytoggle navigationspanspan classiconbarspanspan classiconbarspanspan classiconbarspan a div div classnavbarcollapse navbarex1collapse collapse ariaexpandedfalse styleheight 0px ul idheadermenu classnav navbarnav main menu button typebutton classnavbartoggle datatogglecollapse datatargetnavbarex1collapsebutton li idmenuitem956 classmenuitem menuitemtypepost type menuitemobjectpage menuitem956span classbeforespana hrefprosjekterprosjekteraspan classafterspan li li idmenuitem1502 classhidesub menuitem menuitemtypepost type menuitemobjectpage menuitemhaschildren menuitem1502span classbeforespana hreftjenestertjenesteraspan classafterspan ul clasubmenu li idmenuitem1350 clasubmenurow inactive menuitem menuitemtypecustom menuitemobjectcustom menuitemhaschildren menuitem1350span classbeforespana hrefspanundermenyspanaspan classafterspan ul clasubmenu li idmenuitem1317 classhidesub menuitem menuitemtypecustom menuitemobjectcustom menuitemhaschildren menuitem1317span classbeforespana hrefnettstederaspan classafterspan ul clasubmenu li idmenuitem1503 classmenuitem menuitemtypepost type menuitemobjectpage menuitem1503span classbeforespana hrefresponsivhjemmesideresponsiv hjemmesideaspan classafterspan li li idmenuitem1504 classmenuitem menuitemtypepost type menuitemobjectpage menuitem1504span classbeforespana hrefnettbutikknettbutikkaspan classafterspan li li idmenuitem1318 classmenuitem menuitemtypepost type menuitemobjectpage menuitem1318span classbeforespana hreflandingsiderlandingsideraspan classafterspan li li idmenuitem1332 classmenuitem menuitemtypecustom menuitemobjectcustom menuitem1332span classbeforespana hrefwordpressaspan classafterspan li li idmenuitem13 classmenuitem menuitemtypecustom menuitemobjectcustom menuitem13span classbeforespana hrefwebdesignaspan classafterspan li ul li li idmenuitem1314 classhidesub menuitem menuitemtypecustom menuitemobjectcustom menuitemhaschildren menuitem1314span classbeforespana hrefsynlighetaspan classafterspan ul clasubmenu li idmenuitem1505 classmenuitem menuitemtypepost type menuitemobjectpage menuitem1505span classbeforespana hrefgoogleannonseringgoogle annonseringaspan classafterspan li li idmenuitem1335 classmenuitem menuitemtypecustom menuitemobjectcustom menuitem1335span classbeforespana hreffacebook annonseringaspan classafterspan li li idmenuitem1316 classmenuitem menuitemtypepost type menuitemobjectpage menuitem1316span classbeforespana hrefsokemotoroptimaliseringsa kemotoroptimaliseringaspan classafterspan li li idmenuitem1507 classmenuitem menuitemtypepost type menuitemobjectpage menuitem1507span classbeforespana hreffaflerehenvendelserfa flere henvendelseraspan classafterspan li li idmenuitem1315 classmenuitem menuitemtypepost type menuitemobjectpage menuitem1315span classbeforespana hrefkonverteringsoptimaliseringkonverteringsoptimaliseringaspan classafterspan li li idmenuitem1509 classmenuitem menuitemtypepost type menuitemobjectpage menuitem1509span classbeforespana hrefforbedringavinnholdforbedring av innholdaspan classafterspan li ul li li idmenuitem1338 classhidesub menuitem menuitemtypecustom menuitemobjectcustom menuitemhaschildren menuitem1338span classbeforespana hrefhostingaspan classafterspan ul clasubmenu li idmenuitem1500 classmenuitem menuitemtypepost type menuitemobjectpage menuitem1500span classbeforespana hrefhostingwebserver webhotell epostaspan classafterspan li ul li li idmenuitem1340 classhidesub menuitem menuitemtypecustom menuitemobjectcustom menuitemhaschildren menuitem1340span classbeforespana hrefsupportaspan classafterspan ul clasubmenu li idmenuitem1341 classmenuitem menuitemtypecustom menuitemobjectcustom menuitem1341span classbeforespana hrefdriftsstatus serveraspan classafterspan li li idmenuitem1342 classmenuitem menuitemtypecustom menuitemobjectcustom menuitem1342span classbeforespana hrefsupportaspan classafterspan li ul li ul li li idmenuitem1349 clasubmenurow inactive onlycomputer menuitem menuitemtypecustom menuitemobjectcustom menuitemhaschildren menuitem1349span classbeforespana hrefspankontaktinfo pcspanaspan classafterspan ul clasubmenu li idmenuitem1344 classcontact inactive menuitem menuitemtypecustom menuitemobjectcustom menuitem1344span classbeforespana hrefkontakt ossaspan classafterspan li li idmenuitem1345 classiconphone menuitem menuitemtypecustom menuitemobjectcustom menuitem1345span classbeforespana hreftel47988947 9 88 9aspan classafterspan li li idmenuitem1346 classiconmail menuitem menuitemtypecustom menuitemobjectcustom menuitem1346span classbeforespana hrefmailtoaspan classafterspan li li idmenuitem1347 classiconmapmarker menuitem menuitemtypecustom menuitemobjectcustom menuitem1347span classbeforespana hrefcompany address 9 ziptownaspan classafterspan li ul li li idmenuitem1528 classonlycomputer closemenubutton menuitem menuitemtypecustom menuitemobjectcustom menuitem1528span classbeforespana hrefspanlukk menyspanaspan classafterspan li ul li li idmenuitem24 classmenuitem menuitemtypepost type menuitemobjectpage menuitem24span classbeforespana hrefhvemerboxmediahvem er box mediaaspan classafterspan li li idmenuitem1501 classmenuitem menuitemtypepost type menuitemobjectpage menuitem1501span classbeforespana hrefaktueltaktueltaspan classafterspan li li idmenuitem100 classmenuitem menuitemtypepost type menuitemobjectpage menuitem100span classbeforespana hrefkontaktosskontakt ossaspan classafterspan li li idmenuitem1527 classbottomcontactinfo onlymobile menuitem menuitemtypecustom menuitemobjectcustom menuitemhaschildren menuitem1527span classbeforespana hrefspankontaktinfo mobilspanaspan classafterspan ul clasubmenu li idmenuitem1522 classiconphone menuitem menuitemtypecustom menuitemobjectcustom menuitem1522span classbeforespana hreftel47988947 9 88 9aspan classafterspan li li idmenuitem1523 classiconmail menuitem menuitemtypecustom menuitemobjectcustom menuitem1523span classbeforespana hrefmailtoaspan classafterspan li ul li li idmenuitem1525 classlogo onlymobile menuitem menuitemtypepost type menuitemobjectpage currentmenuitem page item pageitem36 current page item menuitem1525span classbeforespana hrefspanhjemspanaspan classafterspan li ul divnav,"['ios', 'css']" +1235079,why drag and drop is not working in selenium webdriver i am trying to drag an element into another element using selenium webdriver but it is not working i tried all the solutions which i can find on internet but none of the solutions seems to be working for me webelement sourceelement driverfindelementbycselectorxwebelement destelement driverfindelementbycselectorycode1actions builder new actions controlsgetdriverbuilderdraganddropsourceelement destelementcode2 actions builder new actions controlsgetdriveraction draganddrop builderclickandholdsourceelementmovetoelementdestelementreleasedestelementbuildthreadsleep20draganddropperformcode3point coordinates1 sourceelementgetlocationpoint coordinates2 destelementgetlocation robot robot new robot robotmousemovecoordinates1getx coordinates1getyrobotmousepressinputeventbutton1 maskrobotmousemovecoordinates2getx coordinates2getyrobotmousereleaseinputeventbutton1 maskthreadsleep20code4final string java script var srcarguments0tgtarguments1var datatransferdropeffe cteffectallowedallfilesitemstypessetdatafun ctionformatdatathisitemsformatdatathistypesappendfor matgetdatafunctionformatreturn thisitemsformatclea rdatafunctionformatvar emitfunctioneventtargetvar ev tdocumentcreateeventeventevtiniteventeventtruefalse evtdatatransferdatatransfertargetthispatcheventevtemit dragstartsrcemitdragentertgtemitdragovertgtemit droptgtemitdragendsrc javascriptexecutor controlsgetdriverexecutescriptjava script sourceelement destelement threadsleep20none of the above code is working for me all the above runs without any error but drag and drop is not happening in the application anyone having any other solution thanks,['java'] +1235124,why is ruby failing to connect to my tor network iam using ruby on rails 427 on mac el capitan and just installed the tor browser v 604 i fired up my tor browser have verified its running by viewing a couple of web pages but using this gem a when i run my script ruby doesnat believe tor is running require tor puts avaailble toravailable puts version torversionreturns avaailble falseversionindeed when i try and make a tor request using the requests gem the web page request returns immediately leading me to believe the tor network isnat being used because in a tor browser it takes much longer here is the code iam using to amen a web page request a uri uriparseurl nethttpsocksproxy127001 9150starturihost uriport do http f httpgeturipath endhow do i make my rubyrails code connect to my locally running tor networkedit in respnse to the answer given here is what i set my path and dyld library path variables to alocalhostmyproject davea echo pathusrlocaloptcoreutilslibexecgnubinoptlocalbinoptlocalsbinusersdavearvmgemsruby230binusersdavearvmgemsruby230globalbinusersdavearvmrubiesruby230binusrlocalbinusrbinbinusrsbinsbinusrlocalmysqlbinoptgradle27binoptapachemaven3binusers davearvmbinusrlocalmysqlbinapplicationstorbrowserappcontentsmacostorusersdavearvmbinusrlocalmysqlbinapplicationstorbrowserappcontentsmacostorlocalhostmyproject davea echo dyld library pathapplicationstorbrowserappcontentsmacostorusrlocalmysqllibusrlocalmysqlliband here is ht output in my rails console trying the commands listed alocalhostmyproject davea rails consolerunning via spring preloader in process 49987loading development environment rails 4271230 001 230 002 torconfigconfdir applicationstorbrowserappcontentsmacostorirb2 warning already initialized constant torconfigconfdirusersdavearvmgemsruby230gemstor012libtorconfigrb21 warning previous definition of confdir was here applicationstorbrowserappcontentsmacostor 230 003 toravailable,"['ruby-on-rails', 'ruby']" +1235166,how to preview multiple images before upload i have a page with four images for the user to select i want the user to be able to preview each image on the site before uploadthe javascript code below works for only one image but i would like it to work for multiple images uploaded via input typefilewhat will be the best way to do thisfunction readurlinput if inputfiles inputfiles0 var reader new filereader readeronload function e outputattrsrc etargetresult readerreadasdataurlinputfiles0 fileinputchangefunction readurlthis,"['javascript', 'jquery', 'html']" +1235231,how is androidmanifestxml validated in android studio how does android studio validate androidmanifestxml and any activity xml i have read this post and this and know that there is not an actual schema for android manifest but how does android studio or any tool that validates androidmanifestxml knows what tags and elements are legal,['android'] +1235424,recognizing clang gcc and tcc by implementationdefined macros i use clang gcc and tcc and i would like to be able to differentiate between the three in a common headerjudging by their macro dumps i expect that the presence of the clang macro will uniquely identify clangi am unable to get a macro dump with tcc compiler x c e dm devnull does not work in its case what is the macros if any that will uniquely identify gcc and possibly tcc,['c'] +1235494,strange java behaviour with static and final qualifiers in our team we found some strange behaviour where we used both static and final qualifiers this is our test classpublic class test public static final test me new test public static final integer i 4 public static final string s abc public test systemoutprintlni systemoutprintlns public static test getinstance return me public static void mainstring args testgetinstance when we run the main method we get a result ofnullabci would understand if it wrote null values both times since the code of static class members is executed from top to bottomcan anyone explain why this behaviour is happening,['java'] +1235523,facebook login in laravel 52 cannot hold the session after redirect i am using facebook php sdk to log my useri created a guard called login for thishere is my config file of authphpguards web driver session provider users api driver token provider users admin driversession provideradminusers verify driversession providerverify login driversession providerusers to access facebook api i created a class in appservices namespace called it facebook appservicesfacbookphpphpnamespace appservicesuse illuminatesupportfacadescacheuse illuminatesupportfacadesconfiguse appextensionsfacebookfacebooklaravelpersistentdatahandler use facebookfacebook as fbuse appclass facebookprotected fbprotected helperprotected permissionprotected logprotected canvashelperprotected persistentdatahandlerfunction construct thisfb new fb app idconfiggetfacebookapp id app secretconfiggetfacebookapp secret default graph version configgetfacebookdefault graph version persistent data handler new facebooklaravelpersistentdatahandler thishelper thisfbgetredirectloginhelper thispermission configgetfacebookpermission thislog new loggingconfiggetfacebooklogfilefacebook log thiscanvashelper thisfbgetcanvashelper thispersistentdatahandler new facebooklaravelpersistentdatahandlerpublic function fbauthurl ifthisisfbauth return thishelpergetlogouturlthispersistentdatahandlergetfacebook access tokenroutefacebooklogout else return thishelpergetloginurlroutefacebookcallbackthispermission public function logincallback accesstoken thishelpergetaccesstoken ifissetaccesstoken thispersistentdatahandlersetfacebook access tokenstring accesstoken public function isfbauth return thispersistentdatahandlerhasfacebook access tokenpublic function getfbuser ifthisisfbauth thisfbsetdefaultaccesstokenthispersistentdatahandlergetfacebook access token user birthdayuser tagged places response thisfbgetmefieldsidnamefirst namelast nameage rangelinkgenderlocalepicturetimezoneupdated timeverifiedemail return responsegetgraphuser else return false public function logout thispersistentdatahandlerdeletefacebook access token thispersistentdatahandlerdeletestateand here is my usercontroller where i write my login logic class usercontroller extends controller facebook login callback function param object appservicesfacebook return redirect public function fbloginfacebook facebook facebooklogincallback get the usergraphnode from facebook fbuser facebookgetfbuser convert usergraphnode user to eloquent user user thisgetfbloggeduserfbuser here log the user in laravel system authguardloginloginuser dumpauthguardthisguarduser dumpsessionall return reidrectpublic function getfbloggeduserfbuser ifuserwhereemailfbusergetfieldemailcount user userwhereemailfbusergetfieldemailfirst ifuserfb app id userfb app id fbusergetfieldid usersave else user thisfbregisterfbuser return user register the user logged in from facebook param facebookgraphnodesgraphuser return appmodelsuser public function fbregisterfbuser user new user userfname fbusergetfieldfirst name userlname fbusergetfieldlast name usergender fbusergetfieldgender useremail fbusergetfieldemail userfb app id fbusergetfieldid picture fbusergetfieldpicture ifpictureissilhouette userprofile image picturegeturl usersave return useron successful facebook login redirect i am calling usercontrollerfbloginafter calling authguardlogin i dump session it successfully show a login login randomstringuserid i session but when i redirect it all session data lostbut the weird thing is that it only happen when it calling through facebook redirect if i use this function like normal login routes it works perfactaly like this in routephp routegetloginusercontrollerloginand in usercontrollerfunction login user userfind12 authguardloginloginuser return redirectusing this method i can easily access session data after redirecting from here but in facebook case it does not happeningi stuck here for two days please anyone can help menote please do not mention in your answer that i should grouped my routes in web middleware,['php'] +1235876,is it possible to add a custom hover color to raised buttons working on a project that is using the materialui library of components and i have gotten a request for a custom button hover color that is outside of the normal convention of the mui themei found this relevant block of code in the raised button source setting a custom labelcolor does change the hover state but that still does not satisfy my current need to have the button hover color something different than that of the label coloroverlay height buttonheight borderradius borderradius backgroundcolor statekeyboardfocused statehovered thisabled fadelabelcolor amount transition transitionseaseout top 0is there a way to override the overlay background color some other way so that i can use a separate custom colorto clarify i am looking to do this using inline styling or through overriding a prop on the button appending a class and using external css is not an option,['javascript'] +1235957,alias template for reference type passed as template template argument in sfinae context i encountered the following problem with g 610 stdc14 switch and i do not understand why the compiler rejects the codei have a helper struct is well formed which checks if a supplied template template argument is well formed when substituting another supplied type into ittemplatetemplatetypename typename r typename t typename voidstruct is well formed stdfalse type templatetemplatetypename typename r typename tstruct is well formedr t void trt stdtrue type i want to check whether a type is referenceable so my idea was to write the following 1templateclass tusing reference t tstatic assertis well formedreference t voidvalue reference to voidbut i get a compiler errormaincpp in instantiation of struct is well formedreference t doublemaincpp6251 required from heremaincpp5420 error typevalue mismatch at argument 1 in template parameter list for templatetemplateclass class r class t class struct is well formed stdfalse type maincpp5420 note expected a class template got reference tmaincpp5420 error typevalue mismatch at argument 1 in template parameter list for is well formedr t templateparameter13 is well formedmaincpp5420 note expected a class template got reference talternatively the following works with the same static assert 2templateclass tusing reference t void ttfurthermore the following works which really puzzles me 3templateclass tusing pointer t tstatic assertis well formedpointer t voidvalue no pointer to voidwhat is the difference between the three aliases is the void tt solution the most elegant or is it possible to modify the is well formed helper struct to support the first reference versionedit i tested the code with msvc15 preview 4 and 1 and 3 work including the asserts but when i try 2 the assert for the void reference does not work ie information gets lost during substitution and the false type overload is never selected which compiler is rightthe is well formed helper corresponds to the can apply struct from the stack overflow documentation page on sfinae i just removed the parameter packs full example codeinclude utility only defined in std for c17template classusing void t void 1 compiler error during substitution in is well formedtemplateclass tusing reference t t 2 ok asserts worktemplateclass tusing reference t void tt 3 ok asserts worktemplateclass tusing pointer t ttemplatetemplatetypename typename r typename t typename voidstruct is well formed stdfalse type templatetemplatetypename typename r typename tstruct is well formedr t void trt stdtrue type int mainint char static assertis well formedreference t doublevalue no reference to double static assertis well formedreference t voidvalue reference to void static assertis well formedpointer t doublevalue no pointer to double static assertis well formedpointer t voidvalue no pointer to void return 0,['c++'] +1236070,does deep nesting flexbox layout cause performance issue i have been working on a reactjs project where i create most of the components using flexbox layout since with react we can have deeply nested components so my layout is having nested flexbox layout now my question is does this have any issue with performance on a single page there are many components and each component have 3 to 4 level nested flexbox layout will that cause a performance issue,['css'] +1236165,how to write integration tests with springcloudnetflix and feign i use springcloudnetflix for communication between micro services let us say i have two services foo and bar and foo consumes one of bars rest endpoints i use an interface annotated with feignclientfeignclientpublic interface barclient requestmappingvalue someurl method post void bazzlerequestbody bazzlerequestthen i have a service class someservice in foo which calls the barclientcomponentpublic class someservice autowired barclient barclient public string dosomething try barclientbazzlenew bazzlerequest return so bazzle my eyes dazzle catchfeignexception e return not bazzle today now to make sure the communication between services works i want to build a test that fires a real http request against a fake bar server using something like wiremock the test should make sure that feign correctly decodes the service response and reports it to someservicepublic class someserviceintegrationtest autowired someservice someservice test public void shouldsucceed stubforgeturlequaltosomeurl willreturnaresponse withstatus204 string result someservicedosomething assertthatresult isso bazzle my eyes dazzle test public void shouldfail stubforgeturlequaltosomeurl willreturnaresponse withstatus404 string result someservicedosomething assertthatresult isnot bazzle today how can i inject such a wiremock server into eureka so that feign is able to find it and communicate with it what kind of annotation magic do i need,['java'] +1236259,automatic properties documentation for java application are there javadoclike instruments for configuration properties in java applicationi am currently working on java application which uses usual java properties files for configuration this is an enterprise app so we have dozens of properties and it is really difficult to support documentation for themso i want to find a tool or framework which makes it possible to describe properties in code for example with annotations and then export the documentation to a file we already use javadoc and swagger for documentation it is quite convenient it would be helpful to have something similar for properties,['java'] +1236337,nodejs detect when two mongoose find are finished i am trying to initialize two input with autocomplete with this library when i load my page i will trigger an ajax to initialize two input textbut i do not know how i can detect when all my mongoose find are completedhere is my server side code apostinitautocomplete functionreq res var autocomplete companies offices find all companies companyfind functionerr companies if err throw err companiesforeachfunctioncompany autocompletecompaniespushvalue companyname consolelogone find all offices officefind functionerr offices if err throw err officesforeachfunctionoffice autocompleteofficespushvalue officename consolelogtwo consolelogthree resjsonautocompletei know than the find method is async that is why i see my consolelog in this order threeonetwohow can i do to trigger consolelogthree when the companyfind and officefind are finished i want to see the consolelogthree at the last positionedit i think i can do this way apostinitautocomplete functionreq res var autocomplete companies offices find all companies companyfind functionerr companies if err throw err companiesforeachfunctioncompany autocompletecompaniespushvalue companyname find all offices officefind functionerr offices if err throw err officesforeachfunctionoffice autocompleteofficespushvalue officename resjsonautocomplete but i do not know if it is the good way maybe using promise will be better i am open for all suggestions,['javascript'] +1236452,what is untrackoutstandingtimeouts setting for in protractor in the protractor reference configuration there is the untrackoutstandingtimeouts setting mentioned protractor will track outstanding timeouts by default and report them in the error message if protractor fails to synchronize with angular in time in order to do this protractor needs to decorate timeout caution if your app decorates timeout you must turn on this flag this is false by defaultuntrackoutstandingtimeouts falsei have never seen anyone changing the setting what is the practical usage of the setting when should i set it to true,['javascript'] +1236597,how to insert several unique ptrs into vector at once i have a vector stdvectorstdunique ptrintand would like to insert several new unique ptrints into it at a specified location there is the member function stdvectorinsertiterator position size type n const value type val but alas the restrictions on copying unique ptrs does not allow the use of this overloadi have read this question however that is for inserting unique ptrs that already exist in another vector i want to create new onesi realize i can do it with a loop for example to insert 3 new items to the beginning of the vectorfor int and 0 and 3 n vecinsertvecbegin stdmake uniqueint0however i am wondering if there is a cleaner way to do this and possibly one that allocates the new memory upfrontedit for clarification the number of items to add to the vector is completely arbitrary i wrote 3 in my example code but it could be any value and not necessarily one that is known at compile time,['c++'] +1236865,sql how to add if else conditions in sql table a consists of firstname secondname lastname msisdn registrationdate table b have firstname secondname lastname msisdn registrationdate and a few other columns but i only want to consider these mentioned 5 columnsi have something like thisselect select amsisdnafirstnameasecondnamealastnamearegdate bmsisdnbfirstnamebsecondnameblastnamebregdate from table1 ainner join table2 b on amsisdn bmsisdnwhere afirstname bfirstname or alastname blastnamepreviously i only considered firstname lastname from table a and checked for mismatch in table b but i am getting thousands of records as results and i wanted narrow down the searchhow do i include an if else case here so that if afirstname bfirstname asecondname blastname ignore this recordif afirstname bfirstname alastname blastname ignore this recordif afirstname bfirstname alastname bsecondname ignore this recordif afirstname not equal to bfirstname show this record as resultif afirstname bfirstname asecondname not equal to blastname show this record as resultelse show all the records as results that does not fall into any of these above cases also if it is possible please include a solution to ignore capital letters and small letters while checking for mismatchesthe problem here is after executing the query from sagi in the results i am getting the rows which has perfect match between firstsecond and lastnames but has a different registration date as we are not considering registration date in the query will it impact the results,"['mysql', 'sql']" +1236931,xcode 8 some buttons border removed i just updated my xcode ver from 73 to 80 and some buttons borders thisappearedthe code looks fine so i really do not know what happened to the layersbtw in some other controllers i can see the layers bordersselfbuttonlayerbordercolor bordercolorcgcolorselfbuttonlayerborderwidth 2selfbuttonlayercornerradius cgrectgetheightselfbuttonframe 2before the image is only for example the borders looks different at real timenow,"['ios', 'iphone']" +1237096,poco openssl ca pem unacceptable certificate error for 1 out of 2 identical sites i am trying to do a ssl handshake with w1filemailcom i am using curls cacertpem but i am getting this errorunacceptable certificate from 1881388130 application verification failuremaking the handshake against any other https website works including w2filemailcom w1 and w2 should be identically configured and they both work fine in all browsers they also test fine here identical certificates and intermediary certificates are sent out for both sitesl labs w1filemailcomssl labs w2filemailcomwhy am i getting this problem with w1 using openssl and the cacertpem filethere has to be a difference in the certificate setup of w1 and w2 i have tested with a myriad of tools openssl ssllabs etc to try to pinpoint the difference but i always get the exact same results for both sites except when running my codewhat am i missing here whats the difference between the sitesit should be noted that we are using a relatively cheap wildcard certificate provided by rapidssl so i am guessing it has something to do with intermediate or crossroot certificates but everything seems to be in order when testing with the tools mentioned abovecodepocosharedptrpoconetinvalidcertificatehandler pcert new poconetconsolecertificatehandlerfalsepoconetcontextptr pcontext new poconetcontextpoconetcontextclient use ccacertpem poconetcontextverify relaxed 9 false alladhlowexpmd5strengthpoconetsslmanagerinstanceinitializeclient0 pcert pcontexturi uripoconetsecurestreamsocket sspoconetsocketaddressurigethostc str urigetportsscompletehandshake,['c++'] +1237172,cqengine optimize for small datasets i have an application which needs to apply flexible queries against millions of smaller collections ranging in size from 10 to 10 items per collection cqengine is working great in terms of providing the flexibility to query these collections but is much slower than the previous more rigid implementation which worked by pre computing aggregates over certain attributes of the items in the collection problem with that method is it was not flexible enough to easily handle the addition of new attributesmy question is for processing millions of smaller collections is there anything i can do to tune cqengine to make it fastershould i add indexes or maybe only add indexes if the collection is over some sizei am currently using a navigable on the record timestamp and hashindex on the other attributes which are things like category or tagany ideas would be greatly appreciated,['java'] +1237370,puts and times method on numbers this codeputs 1times puts 2times puts 3times puts 4 outputs this4 4 4 3 4 4 4 3 2 1i would expect ruby to output the return value of the times method but it does not seem to do that it prints out the number that times is being called on what is happening,['ruby'] +1237453,code sign error on xcode 8 and ios 10 cordova project i have a cordova project which i build and run locally deploying it on my iphone and android devicehowever after i have upgraded to xcode 8 and my iphone ios to ios 10 i cant build ipas locally it fails with the following error build target of project with configuration debug check dependencies signing for requires a development team select a development team in the project editor code signing is required for product type application in sdk ios 100this was working perfectly before the update after the update the build for ios fails the relevant version numbers for the project areiosdeploy v 186xcodebuild version xcode 80 build version 8a218ai have got my xcode setup with proper certificates and provisioning profiles,['ios'] +1237671,how to read data from specific buffer with glreadpixels based on gles30 on android as i understood from gles30 there is no more gl fragcolor buffer i saw it heresince i cannot read a special variables how can i read an out bufferthis is my codeprivate static final string fragment shader version 300 esn extension gl oes egl image external essl3 requiren precision mediump floatn highp here does not seem to matter in vec2 vtexturecoordn uniform sampler2d stexturen out vec4 fragcolor n void main n vec4 tc texturestexture vtexturecoordn fragcolorr tcr 03 tcg 059 tcb 011n fragcolorg tcr 03 tcg 059 tcb 011n fragcolorb tcr 03 tcg 059 tcb 011n nhere i tried to read the data bytebuffer mpixelbuf bytebufferallocatedirectmwidth mheight 4 mpixelbuforderbyteorderlittle endiangles30glreadpixelsstartx starty framewidth frameheight gles30gl rgba gles30gl unsigned byte mpixelbufthere are no gl errors in the codethe output mpixelbuf only zeroeshow can i make sure that fragcolor is reading thanksupdate1 full texture render codepackage commesyotmanalyzingadapterimport javaniobytebufferimport javaniobyteorderimport javaniofloatbufferimport androidgraphicssurfacetextureimport androidopenglgles11extimport androidopenglgles30import androidopenglmatriximport androidutillog code for rendering a texture onto a surface using opengl es 20 public class stexturerender private static final string tag myopengl private int zoom private static final int float size bytes 4 private static final int triangle vertices data stride bytes 5 float size bytes private static final int triangle vertices data pos offset 0 private static final int triangle vertices data uv offset 3 private final float mtriangleverticesdata x y z u v 10f 10f 0 0f 0f 10f 10f 0 1f 0f 10f 10f 0 0f 1f 10f 10f 0 1f 1f private floatbuffer mtrianglevertices private static final string vertex shader version 300 esn uniform mat4 umvpmatrixn uniform mat4 ustmatrixn in vec4 apositionn in vec4 atexturecoordn out vec2 vtexturecoordn void main n gl position umvpmatrix apositionn vtexturecoord ustmatrix atexturecoordxyn nsmapler2d private static final string fragment shader version 300 esn extension gl oes egl image external essl3 requiren precision mediump floatn highp here does not seem to matter in vec2 vtexturecoordn uniform mediump sampler2d stexturen layoutlocation 0 out mediump vec4 fragcolor n void main n vec4 tc texturestexture vtexturecoordn fragcolorr tcr 03 tcg 059 tcb 011n fragcolorg tcr 03 tcg 059 tcb 011n fragcolorb tcr 03 tcg 059 tcb 011n n private float mmvpmatrix new float16 private float mstmatrix new float16 private int mprogram private int mtextureid 12345 private int mumvpmatrixhandle private int mustmatrixhandle private int mapositionhandle private int matexturehandle public stexturerenderint zoom logvmy error start stexturerender constructor try mtrianglevertices bytebufferallocatedirect mtriangleverticesdatalength float size bytes orderbyteordernativeorderasfloatbuffer mtriangleverticesputmtriangleverticesdataposition0 matrixsetidentitymmstmatrix 0 zoom zoom catchexception ex logvmy error stexturerender error extostring logvmy error end stexturerender constructor public int gettextureid return mtextureid draws the external texture in surfacetexture onto the current egl surface public void drawframesurfacetexture st boolean invert checkglerrorondrawframe start try stgettransformmatrixmstmatrix if invert mstmatrix5 mstmatrix5 mstmatrix13 10f mstmatrix13 gles30glclearcolor00f 10f 00f 10f gles30glcleargles30gl color buffer bit gles30gluseprogrammprogram checkglerrorgluseprogram gles30glactivetexturegles30gl texture0 gles30glbindtexturegles11extgl texture external oes mtextureid mtriangleverticespositiontriangle vertices data pos offset gles30glvertexattribpointermapositionhandle 3 gles30gl float false triangle vertices data stride bytes mtrianglevertices checkglerrorglvertexattribpointer maposition gles30glenablevertexattribarraymapositionhandle checkglerrorglenablevertexattribarray mapositionhandle mtriangleverticespositiontriangle vertices data uv offset gles30glvertexattribpointermatexturehandle 2 gles30gl float false triangle vertices data stride bytes mtrianglevertices checkglerrorglvertexattribpointer matexturehandle gles30glenablevertexattribarraymatexturehandle checkglerrorglenablevertexattribarray matexturehandle matrixsetidentitymvpmatrix 0 gles30gluniformmatrix4fvmumvpmatrixhandle 1 false mmvpmatrix 0 gles30gluniformmatrix4fvmustmatrixhandle 1 false mstmatrix 0 gles30gldrawarraysgles30gl triangle strip 0 4 checkglerrorgldrawarrays catchexception ex logvmy error drawframe error extostring initializes gl state call this after the egl surface has been created and made current public void surfacecreated try mprogram createprogramvertex shader fragment shader if mprogram 0 throw new runtimeexceptionfailed creating program mapositionhandle gles30glgetattriblocationmprogram aposition checkglerrorglgetattriblocation aposition if mapositionhandle 1 throw new runtimeexceptioncould not get attrib location for aposition matexturehandle gles30glgetattriblocationmprogram atexturecoord checkglerrorglgetattriblocation atexturecoord if matexturehandle 1 throw new runtimeexceptioncould not get attrib location for atexturecoord mumvpmatrixhandle gles30glgetuniformlocationmprogram umvpmatrix checkglerrorglgetuniformlocation umvpmatrix if mumvpmatrixhandle 1 throw new runtimeexceptioncould not get attrib location for umvpmatrix mustmatrixhandle gles30glgetuniformlocationmprogram ustmatrix checkglerrorglgetuniformlocation ustmatrix if mustmatrixhandle 1 throw new runtimeexceptioncould not get attrib location for ustmatrix int textures new int1 gles30glgentextures1 textures 0 mtextureid textures0 gles30glbindtexturegles11extgl texture external oes mtextureid checkglerrorglbindtexture mtextureid gles30gltexparameterfgles11extgl texture external oes gles30gl texture min filter gles30gl nearest gles30gltexparameterfgles11extgl texture external oes gles30gl texture mag filter gles30gl linear gles30gltexparameterigles11extgl texture external oes gles30gl texture wrap s gles30gl clamp to edge gles30gltexparameterigles11extgl texture external oes gles30gl texture wrap t gles30gl clamp to edge checkglerrorgltexparameter catchexception ex logvmy error surfacecreated error extostring replaces the fragment shader pass in null to reset to default public void changementshaderstring fragmentshader try if fragmentshader null fragmentshader fragment shader gles30gldeleteprogrammprogram mprogram createprogramvertex shader fragmentshader if mprogram 0 logvmy error failed creating program throw new runtimeexceptionfailed creating program catchexception ex logvmy error changementshader error extostring private int loadshaderint shadertype string source try int shader gles30glcreateshadershadertype checkglerrorglcreateshader type shadertype gles30glshadersourceshader source gles30glcompileshadershader int compiled new int1 gles30glgetshaderivshader gles30gl compile status compiled 0 if compiled0 0 logetag could not compile shader shadertype logetag gles30glgetshaderinfologshader gles30gldeleteshadershader shader 0 return shader catchexception ex logvmy error loadshader error extostring return 0 private int createprogramstring vertexsource string fragmentsource try int vertexshader loadshadergles30gl vertex shader vertexsource if vertexshader 0 return 0 int pixelshader loadshadergles30gl fragment shader fragmentsource if pixelshader 0 return 0 int program gles30glcreateprogram checkglerrorglcreateprogram if program 0 logetag could not create program gles30glattachshaderprogram vertexshader checkglerrorglattachshader gles30glattachshaderprogram pixelshader checkglerrorglattachshader gles30gllinkprogramprogram int linkstatus new int1 gles30glgetprogramivprogram gles30gl link status linkstatus 0 if linkstatus0 gles30gl true logetag could not link program logetag gles30glgetprograminfologprogram gles30gldeleteprogramprogram program 0 return program catchexception ex logvmy error createprogram error extostring return 0 public void checkglerrorstring op int error while error gles30glgeterror gles30gl no error logetag op glerror error throw new runtimeexceptionop glerror error,['android'] +1237883,exception when getting attribute constructor arguments with multiple enum arrays i was playing with attributes and reflection when i found a strange case the following code gave me an exception at runtime when i try to get constructor arguments of custom attributesusing systemusing systemreflectionclass program testnew testfoo null static void mainstring args var type typeofprogram var method typegetmethodmain bindingflagsstatic bindingflagsnonpublic var attribute methodgetcustomattributesdata0constructorarguments consolereadkey public enum test foo barattributeusageattributetargetsmethod allowmultiple truepublic class testattribute attribute public testattributetest valuesone test valuestwo the problem seems to be the parameters passed to the test attribute constructor if one of them is null constructorarguments throw an exception the exception is argumentexception with name as exception message here is the stack trace from constructorarguments callsystemruntimetypehandlegettypebynameusingcarulesstring name runtimemodule scopesystemreflectioncustomattributetypedargumentresolvetyperuntimemodule scope string typenamesystemreflectioncustomattributetypedargumentctorruntimemodule scope customattributeencodedargument encodedargsystemreflectioncustomattributedataget constructorargumentsif i set a non null value to each parameters there is no exception it seems to only happen with enum array if i add another parameter such as string and set them to null there is no problema solution could be to always pass a value such as an empty array but here i would like to keep the ability to pass null value because it has a special meaning in my case,"['c#', '.net']" +1237929,selenium or coypu wait for element show and get time before show i using selenium for ui testingwhat i want to when i click on a button once then i will wait until an element exists and take time on how long it takes if it takes longer than timeout ms so it will give 0 or not existi have try this using coypu browserfindcssnamesearchbtnclickdim vstopwatch stopwatchstartnew browsertryuntilfunction browserfindxpathidblockdocumentssearchhover function browserfindcssrepsearchdocuments listgroupitemexists timespanfrommilliseconds500 new options with timeout timespanfrommilliseconds10 if not browserfindcssrepsearchdocuments listgroupitemexists then ptcherrorcurrentstepnot showing any documents or timeout browser return 0 end if return vstopwatchelapsedmillisecondsbut it does not quite seem to give right result,['.net'] +1237985,function return a tuple made of vectors i am trying avoid output arguments in my functions the old function isvoid getallblockmeanerror const vectorint vec vectorint fact vectorint mean vectorint errhere vec is input argument fact mean and err are output argument i tried to group output argument to one tupletuple vectorint vectorint vectorint getallblockmeanerrortupleconst vectorint vec vectorint fact mean err return make tuplefact mean errnow i can call the new function withtiefact mean err getallblockmeanerrortuplevecit looks cleaner to me while i have a question how does equal assignment of tiefact mean err work does it do a deep copy or a move since fact mean and err inside getallblockmeanerrortuple will be destroyed i hope it is doing a move instead of a deep copy,['c++'] +1238361,how to detect if date changes in select query i am using the following sql query to select rows from through an inner join sorted by the dateselect from clubnights inner join club on clubnightsclub clubclub id where visibility 0and date curdateorder by clubnightsdate asci then load all the data in my html via a php while loop my aim is to echo an html header above every section of any given date therefore i am looking to detect either via php or sql when a change in date is detected via the select query basically i want to compare the last date column to the current one and if they do not match i will echo something via phpan example assuming the following are rows20160916 row 1 detect change here as it is the first row20160916 row 220160916 row 320160916 row 420160916 row 520160917 row 6 detect change here as date has changed20160917 row 720160917 row 8edit i am using mysql,"['php', 'mysql', 'sql']" +1238365,smtp configuration not working in production i am trying to send an email when a form is submitted i am using phpmailer to send the mail using the below configurationmail new phpmailermailissmtpmailhost mailexamplein mailport 25 mailsmtpauth truemailusername mailpassword password mailsetfrom usermailaddaddress receivermailaddbcc another usermailaddreplyto usermailishtmltruemailsubject subjectmailbody messageifmailsend echo your request has been received we will soon contact youelse echo unable to send your request please try againthis works fine in localhost but when i deploy it to my server examplein i get the below exceptionsmtp error failed to connect to server connection timed out 110smtp connect failed editi tried connecting to the smtp server using telnet command but i am unable to add the recipient i get the below errorlast login fri sep 16 110806 on ttys0admin admin telnet mailexamplein 25trying 191153112connected to mailexampleinescape character is 220 fbshomailserverexamplein esmtp service lotus domino release 853fp3 ready at fri 16 sep 2016 113601 0530helo examplein250 fbshomailserverexamplein hello examplein 1911272 pleased to meet youmail from 250 sender okrcpt to 554 relay rejected for policy reasons edit i was able to setup this account in outlook i am really confused whats happening,['php'] +1238671,apk update from different keystore reading the apk must be signed with the same certificates as the previous versioni see the problem described asupload failedyou uploaded an apk that is signed with a different certificate to your previous apks you must use the same certificatethe accepted answer states from the android websitethe apk must be signed with the same private key if the package name and signing certificate do not match those of the existing version market will consider it a new application and will not offer it to users as an updateother answers additionally claim that you have to have the original keystorethat is 3 different statements which one is itdo the keystores have to be the same and how would that be checkedcan i use a different keystore as long as they include an identical certificatecan i use a different certificate as long as it is derived from the same keypair,['android'] +1238729,multiselect from ax 2012 listpage ep to downloaddocumentaspx peoplei have been struggling with this for a while now and cannot seem to find a solution for my problem i would really like some help here if possible it would mean a great deal to meim currently running a listpage from ax 2012 on a enterprise portal site that allows users to select an invoice and then click a button that starts downloading a generated pdf of the invoiceit looks like thisthe button epdocugetmenuitem output menu item refers to a url webmenuitem that starts the static file downloaddocumentaspxdownloaddocumentaspx gets the websession and axaptasession and extracts a single record that was selected in the ax listpagedownloaddocumentaspx has the following code page languagec tracefalse assembly namemicrosoftdynamicsframeworkportal version6200 cultureneutral publickeytoken31bf3856ad364e35 customnull assembly namemicrosoftdynamicsframeworkdataax version6200 cultureneutral publickeytoken31bf3856ad364e35 customnull assembly namemicrosoftdynamicsframeworkbusinessconnector version6200 cultureneutral publickeytoken31bf3856ad364e35 customnull assembly namemicrosoftdynamicsframeworkbusinessconnectorproxy version6200 cultureneutral publickeytoken31bf3856ad364e35 customnull assembly namemicrosoftdynamicsframeworkmetadataax version6200 cultureneutral publickeytoken31bf3856ad364e35 customnull import namespacemicrosoftdynamicsframeworkportal import namespacemicrosoftdynamicsframeworkportalui import namespacemicrosoftdynamicsaxframeworkportaldata import namespacemicrosoftdynamicsframeworkbusinessconnectorproxy import namespacemicrosoftdynamicsframeworkbusinessconnectorsession import namespacemicrosoftdynamicsframeworkbusinessconnectoradapter import namespacemicrosoftdynamicsaxframeworkservicesclient register tagprefixdynamics tagnameepsecuritycontrol srcepsecuritycontrolascx dynamicsepsecuritycontrol idaxepsecurity runatserver script runatserver void page loadobject sender eventargs e axsharepointwebsession session null try session sessionhelperinstancegetsharepointsession if session null using epdocuget doc new epdocugetsessionaxaptaadapter epdocuget writes directly to the output stream axquerystring query new axquerystringthisrequest if queryrecordcontext null axtablecontext tablecontext axtablecontextcreatesession query iftablecontext null tablecontextdatakey null using iaxaptarecordadapter record tablecontextdatakeygetrecordssession if tablecontexttableid tablemetadatatablenumdocuref docrundownloadrecord else run a report using the client sdk userimpersonationcontext to revert the credentials from ep application pool to the authenticated user using new userimpersonationcontext docrundownloadrecord responseflush catch systemexception current design is to not thisplay errors to the user errors are stored in the event log for review by the site operator finally if session null sessionhelperinstancereleasesharepointsessionsession scriptand the interesting part of the file is this code using epdocuget doc new epdocugetsessionaxaptaadapter epdocuget writes directly to the output stream axquerystring query new axquerystringthisrequest if queryrecordcontext null axtablecontext tablecontext axtablecontextcreatesession query if tablecontext null tablecontextdatakey null using iaxaptarecordadapter record tablecontextdatakeygetrecordsession if tablecontexttableid tablemetadatatablenumdocuref docrundownloadrecord else run a report using the client sdk userimpersonationcontext to revert the credentials from ep application pool to the authenticated user using new userimpersonationcontext docrundownloadrecord the goal here is to get all the selected records accessible in downloaddocumentaspx i have enabled multiselect in ax so i guess it should be possible to get all the records somehowi assume this snippet should be different somehowiaxaptarecordadapter record tablecontextdatakeygetrecordsessionbut i cannot figure it outif i can get all the records in the downloaddocumentaspx file i could send a string back to ax to create the nescessary documents and send them to the userany suggestions on how to do this,"['c#', 'asp.net']" +1239359,significant change location delegate methods not being called all of my code is in appdelegatem boolapplicationuiapplication application didfinishlaunchingwithoptionsnsdictionary launchoptions selfwindow uiwindow allocinitwithframeuiscreen mainscreenbounds locationmgr cllocationmanager alloc init locationmgr setdelegateself if locationmgr respondstoselectorselectorsetallowsbackgroundlocationupdates locationmgr setallowsbackgroundlocationupdatesyes clauthorizationstatus authorizationstatus cllocationmanager authorizationstatus iflaunchoptions valueforkeyuiapplicationlaunchoptionslocationkey nil nslogrelaunching because of significant location change restarting slc locationmgr startmonitoringsignificantlocationchanges else if authorizationstatus kclauthorizationstatusauthorizedalways nsloglaunching with authorization to always use location starting slc locationmgr startmonitoringsignificantlocationchanges else nsloglaunching with no authorization to always use location requesting authorization if locationmgr respondstoselectorselectorrequestalwaysauthorization locationmgr requestalwaysauthorization ifuserdefaults objectforkeypfuser nil nslogin delegate signup signupcontroller signup signupcontroller alloc init selfwindow setrootviewcontrollersignup else viewcontroller map viewcontroller alloc init selfwindow setrootviewcontrollermap selfwindow makekeyandvisible return yes voidstartsignificantchangeupdates devicenotfoundalertcontroller uialertcontroller alertcontrollerwithtitlestart messagestartsignificantchangeupdates called preferredstyleuialertcontrollerstylealert devicenotfoundalertcontroller addactiondevicenotfoundalert create the location manager if this object does not already have one if nil locationmgr locationmgr cllocationmanager alloc init locationmgrdelegate self cllocationmanager significantlocationchangemonitoringavailable locationmgr startmonitoringsignificantlocationchangesvoidlocationmangercllocationmanager manager didfailwitherrornserror error nslogdidfailwitherror error devicenotfoundalertcontroller uialertcontroller alertcontrollerwithtitlelocation fail messagedidfailwitherror preferredstyleuialertcontrollerstylealert devicenotfoundalertcontroller addactiondevicenotfoundalert delegate method from the cllocationmanagerdelegate protocol void locationmanagercllocationmanager manager didupdatelocationsnsarray locations devicenotfoundalertcontroller uialertcontroller alertcontrollerwithtitlelocation update messagedidupdatelocations called preferredstyleuialertcontrollerstylealert devicenotfoundalertcontroller addactiondevicenotfoundalert if it is a relatively recent event turn off updates to save power cllocation location locations lastobject nsdate eventdate locationtimestamp nstimeinterval howrecent eventdate timeintervalsincenow if fabshowrecent 150 if the event is recent do something with it nsloglatitude 6f longitude 6fn locationcoordinatelatitude locationcoordinatelongitude none of the alerts happen it seems like the delegate methods are not being calledupdatenow i have boolapplicationuiapplication application didfinishlaunchingwithoptionsnsdictionary launchoptions selfwindow uiwindow allocinitwithframeuiscreen mainscreenbounds devicenotfoundalert uialertaction actionwithtitleok styleuialertactionstyledefault handlernil delegate method from the cllocationmanagerdelegate protocol voidlocationmanagercllocationmanager manager didupdatelocationsnsarray locations devicenotfoundalertcontroller uialertcontroller alertcontrollerwithtitlelocation update messagedidupdatelocations called preferredstyleuialertcontrollerstylealert devicenotfoundalertcontroller addactiondevicenotfoundalert if it is a relatively recent event turn off updates to save power cllocation location locations lastobject nsdate eventdate locationtimestamp nstimeinterval howrecent eventdate timeintervalsincenow if fabshowrecent 150 if the event is recent do something with it nsloglatitude 6f longitude 6fn locationcoordinatelatitude locationcoordinatelongitude when i test the app i open it at my house and then close it so that when i leave my house it should send an alert or 3 at some point but i am not getting alerts from any of the delegate methods where i placed alertsi just had an idea maybe i have to thisplay the alerts from the main uiviewcontroller not the appdelegatethis may be why i am not seeing the alerts how do i add a uialertcontroller in app delegate objcupdatethis is how i am doing the alerts nowdevicenotfoundalertcontroller uialertcontroller alertcontrollerwithtitlestart messagestartsignificantchangeupdates called preferredstyleuialertcontrollerstylealertdevicenotfoundalertcontroller addactiondevicenotfoundalertalertwindow uiwindow alloc initwithframeuiscreen mainscreenboundsalertwindowrootviewcontroller uiviewcontroller alloc initalertwindowwindowlevel uiwindowlevelalert 1alertwindow makekeyandvisiblealertwindowrootviewcontroller presentviewcontrollerdevicenotfoundalertcontroller animatedyes completionnilupdatethe alerts did not seem to be the issue the alert in startsignificantchangeupdates never appears should it appear once i am 500m from my initial locationupdatecan anyone help me understand thisthe methods of your delegate object are called from the thread in which you started the corresponding location services that thread must itself have an active run loop like the one found in your applicationas main threadupdatei think i figured out what the above quote is sayingand i have this now i will test tomorrowiflaunchoptions valueforkeyuiapplicationlaunchoptionslocationkey nil nslogrelaunching because of significant location change restarting slc thispatch asyncthispatch get global queuethispatch queue priority default 0 locationmgr startmonitoringsignificantlocationchanges else if authorizationstatus kclauthorizationstatusauthorizedalways nsloglaunching with authorization to always use location starting slc thispatch asyncthispatch get global queuethispatch queue priority default 0 locationmgr startmonitoringsignificantlocationchanges else nsloglaunching with no authorization to always use location requesting authorization if locationmgr respondstoselectorselectorrequestalwaysauthorization locationmgr requestalwaysauthorization i think that code is starting the location services on its own thread one thing i noticed already is that when i exit the app the location in the top right goes away i just updated to ios 10 in ios 9 the location arrow in the top right would stay there but it would only be a black outline when the app was not running this could just be something they changed with ios 10 or now because i updated to 10 something else is not working now or that is what happens when the location services are run on their own thread from here ios start background threadupdatemaybe i am not using the thread correctly but as i said now when i close the app location services quits when i was doing it without the thread the location service arrow would stay in the top right as an outlineupdatei read that the service should be started on the main thread so now i haveclauthorizationstatus authorizationstatus cllocationmanager authorizationstatus nsloglaunching with no authorization to always use location requesting authorization if locationmgr respondstoselectorselectorrequestalwaysauthorization locationmgr requestalwaysauthorization iflaunchoptions valueforkeyuiapplicationlaunchoptionslocationkey nil nslogrelaunching because of significant location change restarting slc thispatch asyncthispatch get global queuethispatch queue priority default 0 locationmgr startmonitoringsignificantlocationchanges else if authorizationstatus kclauthorizationstatusauthorizedalways nsloglaunching with authorization to always use location starting slc thispatch asyncthispatch get global queuethispatch queue priority default 0 locationmgr startmonitoringsignificantlocationchanges else the arrow in the right does not show up when the app is closed is this something new to ios 10 where they do not show it anymoreupdate i accidentally deleted locationmgr cllocationmanager alloc init i put in and now the arrow is always there going to test todayupdatei tested it still no alerts,"['ios', 'objective-c']" +1239787,python numpy scientific notation limit decimals i am trying to reduce the number of decimals that i am getting after some calculations the print where my problem arises looks like thisprintmean resistivity res ohm mformatresnpmeanresistivityand it outputs thismean resistivity 16628449915450776e08 ohm mnow i want to reduce the number of decimal places that are printed to 3 i tried doing it with string formatting like thisprintmean resistivity res3f ohm mformatresnpmeanresistivityhowever this code printsmean resistivity 0 ohm mwhat i actually want is thismean resistivity 1663e8 ohm mhow can i format res to only be thisplayed as scientific notation but with only 3 decimal places,['python'] +1239853,generating list of lists with custom value limitations with hypothesis the storycurrently i have a functionundertest that expects a list of lists of integers with the following rulesnumber of sublists let us call it n can be from 1 to 50number of values inside sublists is the same for all sublists rectangular form and should be 0 and 5values inside sublists cannot be more than or equal to the total number of sublists in other words each value inside a sublist is an integer 0 and nsample valid inputs02 1 2 0 3 1 1 01 0sample invalid inputs2 2 is more than n1 total number of sublists0 1 2 0 2 is equal to n2 total number of sublistsi am trying to approach it with propertybasedtesting and generate different valid inputs with hypothesis library and trying to wrap my head around lists and integers but cannot make it workthe condition 1 is easy to approach with lists and min size and max size argumentsthe condition 2 is covered under chaining strategies togetherthe condition 3 is what i am struggling with cause if we use the rectangle lists from the above example we do not have a reference to the length of the parent list inside integers the questionhow can i limit the integer values inside sublists to be less than the total number of sublistssome of my attemptsfrom hypothesis import givenfrom hypothesisstrategies import lists integersgivenlistslistsintegersmin value0 max value5 min size1 max size5 min size1 max size50def testl this one was very far from meeting the requirements list is not strictly of a rectangular form and generated integer values can go over the generated size of the listfrom hypothesis import givenfrom hypothesisstrategies import lists integersgivenintegersmin value0 max value5flatmaplambda n listslistsintegersmin value1 max value5 min sizen max sizen min size1 max size50def testl here the 1 and 2 are requirements were being met but the integer values can go larger than the size of the list requirement 3 is not met,['python'] +1240005,google chrome clears css styles for current page when opening link in new tab or opening a new window this is odd one i was troubleshooting for 3 daysonly happening in chrome version 5302785116 m 64bit on windowsweb server must have header set meta tag does not work in this caseapache is htaccess header set cachecontrol nocacheor nginx add header cachecontrol nocache you cannot recreate it using jsfiddle or builtin code snippet because css file must be loaded separately using link hrefstylecss relstylesheet typetextcss but i will include code in snippet anywayssteps to recreatevisit click on link 1 should reload the pageclick on link 2 should bring up new tab with the same pageswitch to the original tab and repeat same stepsall css styles are gone from the original tabif not repeat same steps againplease assist to make sure where is nothing wrong with the code before i submit it to googlethanksps there is another way or recreating it that is why i mentioned new window in my title visit same page reload it right click inspect new development tools window opens switch back to the page repeat if not able to recreatemenu div thisplay inlineblockwidth 15emheight 15emred backgroundcolor redyellow backgroundcolor yellowgreen backgroundcolor greendoctype htmlhtmlheadmeta httpequivcontenttype contenttexthtml charsetutf8titlechrome bugtitlelink hrefstylecss relstylesheet typetextcssheadbodydiv classmenu div classredreddiv div classyellowyellowdiv div classgreengreendivdiva href1 reload this pageabra href target blank2 open same page in new tababodyhtml,"['html', 'css']" +1240069,how to fit in an image inside span tag when onclick i have an image inside a span tag but the problem is the image does not fit inside the span tag instead a part of the image goes out of the span tagi want to have when onclick on the word span it change the image color while when i onclick on that image it will change the color of the text i guess something wrong on my codehow can i achieve itmy html div classgamesplatformitem ptitemul classgamessubmenu clearfixli classtab1 current img srcimagesabc11jpg classtopimgg1 input typeradio nameimgswap idrdoimg1 label classtopimgg1 forrdoimg1label spanc14e34c234espanlili classtab2 div img srcimagesabc2jpg classtopimgg2 input typeradio nameimgswap idrdoimg2 label classtopimgg2 forrdoimg2label spaneeospan divlili classtab3 img srcimagesabc3jpg classtopimgg3 input typeradio nameimgswap idrdoimg3 label classtopimgg3 forrdoimg3label spane spanlili classtab4 img srcimagesabc4jpg classtopimgg4 input typeradio nameimgswap idrdoimg4 label classtopimgg4 forrdoimg4label spanc eaaspanlili classtab5 img srcimagesabc5jpg classtopimgg5 input typeradio nameimgswap idrdoimg5 label classtopimgg5 forrdoimg5label spana spanlili classtab6 img srcimagesabc6jpg classtopimgg6 input typeradio nameimgswap idrdoimg6 label classtopimgg6 forrdoimg6label spaneeaspanlili classtab7 img srcimagesabc7jpg classtopimgg7 input typeradio nameimgswap idrdoimg7 label classtopimgg7 forrdoimg7label span spanlimy css hide the radio buttongamessubmenu inputtyperadio thisplay noneset a box for the label this is what is clicked ongamessubmenu label thisplay block width 150px height 100pxset imagesthis would work better with spritesgamessubmenu labeltopimgg1 backgroundimage urlimagesabc1jpg backgroundrepeat norepeat width 80px height 40px right 820px top 0px position absolute zindex 9gamessubmenu inputtyperadiochecked labeltopimgg1 backgroundimage urlimagesabc1 onclickjpggamessubmenu labeltopimgg2 backgroundimage urlimagesabc2jpg backgroundrepeat norepeat width 80px height 40px right 690px top 0px position absolute zindex 9gamessubmenu inputtyperadiochecked labeltopimgg2 backgroundimage urlimagesabc2 onclickjpggamessubmenu labeltopimgg3 backgroundimage urlimagesabc3jpg backgroundrepeat norepeat width 80px height 40px right 560px top 0px position absolute zindex 9 clear bothgamessubmenu inputtyperadiochecked labeltopimgg3 backgroundimage urlimagesabc3 onclickjpggamessubmenu labeltopimgg4 backgroundimage urlimagesabc4jpg backgroundrepeat norepeat width 80px height 40px right 430px top 0px position absolute zindex 9gamessubmenu inputtyperadiochecked labeltopimgg4 backgroundimage urlimagesabc4 onclickjpggamessubmenu labeltopimgg5 backgroundimage urlimagesabc5jpg backgroundrepeat norepeat width 80px height 40px right 305px top 0px position absolute zindex 9gamessubmenu inputtyperadiochecked labeltopimgg5 backgroundimage urlimagesabc5 onclickjpggamessubmenu labeltopimgg6 backgroundimage urlimagesabc6jpg backgroundrepeat norepeat width 80px height 40px right 18 5px top 0px position absolute zindex 9gamessubmenu inputtyperadiochecked labeltopimgg6 backgroundimage urlimagesabc6 onclickjpggamessubmenu labeltopimgg7 backgroundimage urlimagesabc7jpg backgroundrepeat norepeat width 80px height 40px right 43px top 5px position absolute zindex 9gamessubmenu inputtyperadiochecked labeltopimgg7 backgroundimage urlimagesabc7 onclickjpg,"['jquery', 'html', 'css']" +1240145,truncate video with mediacodec i have used android mediacodec library to transcode video files mainly change the resolution sample code hereanother thing i want to achieve is to truncate the video to only take the beginning 15 seconds the logic is to check videoextractorgetsampletime if it is greater than the 15 seconds i will just write an eos to the decoder bufferbut i get an exception caused by androidmediamediacodeccodecexception error 0xf3here is my code while videoencoderdone audioencoderdone while videoextractordone encoderoutputvideoformat null muxing int decoderinputbufferindex videodecoderdequeueinputbuffertimeout usec if decoderinputbufferindex mediacodecinfo try again later break bytebuffer decoderinputbuffer videodecoderinputbuffersdecoderinputbufferindex int size videoextractorreadsampledatadecoderinputbuffer 0 long presentationtime videoextractorgetsampletime if size 0 videodecoderqueueinputbuffer decoderinputbufferindex 0 size presentationtime videoextractorgetsampleflags videoextractordone videoextractoradvance if videoextractordone videoextractorgetsampletime mvideodurationlimit 10 videoextractordone true if videoextractordone videodecoderqueueinputbufferdecoderinputbufferindex 0 0 0 mediacodecbuffer flag end of stream break the full source code can be found here,['android'] +1240566,since xcode 8 and ios10 views are not sized properly on viewdidlayoutsubviews it seems that with xcode 8 on viewdidload all viewcontroller subviews have the same size of 10x10 strange thing but okay viewdidload has never been the better place to correctly size the viewsbut viewdidlayoutsubviews is and on my current projet my i do voidviewdidlayoutsubviews super viewdidlayoutsubviews nslog selfmybuttonthe log shows a size of 10x10 for mybutton then if i log on a button clic for example the log shows a normal sizei am using autolayoutis it a bug,['ios'] +1240886,android autocompletetextview onitemselectedlistener not triggered with a bluetooth keyboard i have a simple app that contains just an autocompletetextview code below i have the onitemclicklistener and onitemselectedlistener defined clicking on the individual items from the dropdown suggestions triggers the onitemclick event however with a bluetooth keyboard using the arrows keys to navigate to a given item does not seem to trigger the onitemselected event the logs are not seen for this eventwhat triggers this onitemselected event i was under the impression that a highlight on one of the dropdown items does it but that does not seem to be the caseif onitemselectedlistener is not the correct event listener for the highlighted item is there any that satisfies this requirementactivity mainxmlxml version10 encodingutf8relativelayout xmlnsandroid xmlnstools androidididactivity main androidlayout widthmatch parent androidlayout heightmatch parent autocompletetextview androidididautocompletetextview androidlayout widthmatch parent androidlayout heightwrap content relativelayoutmainactivityjavapublic class mainactivity extends activity string options a1 a2 a3 b1 b2 b3 b4 b5 override protected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main an adapter object arrayadapterstring adapter new arrayadapterstringthis androidrlayoutselect dialog item options autocompletetextview autocompletetextview autocompletetextviewfindviewbyidridautocompletetextview autocompletetextviewsetadapteradapter autocompletetextviewsetthreshold1 set the listeners autocompletetextviewsetonitemclicklistenernew adapterviewonitemclicklistener override public void onitemclickadapterview parent view view int position long id logdonitemclick autocompletetextview item clicked autocompletetextviewsetonitemselectedlistenernew adapterviewonitemselectedlistener override public void onitemselectedadapterview parent view view int position long id logdonitemselected autocompletetextview item selected override public void onnothingselectedadapterview parent logdonnothingselected autocompletetextview nothing here,['android'] +1240979,system group container for systemgroupcomappleconfigurationprofiles path when i run my application in ios 10 using xcode 8 i am getting below message in debug console but everything is working fine my application is using camera and photo library and i had added privacy camera usage description and privacy photo library usage descriptionin infoplist can any one tell me why this message in comming mc system group container for systemgroupcomappleconfigurationprofiles path is privatevarcontainerssharedsystemgroupsystemgroupcomappleconfigurationprofiles,"['ios', 'iphone']" +1241571,when do i need androidhardwarelocationgps and androidhardwarelocationnetwork google is informing by email of changes to the android location permissionsweare making a change on october 15th 2016 that will affect apps targeting api version 21 android 50 lollipop or higher that use access fine location but do not explicitly have the androidhardwarelocationgps usesfeature going forward these apps will be available to install on devices that do not have gps hardware in most cases this would not be an issue since wifi and cellid based location provides high enough fidelity for the typical operation of these apps however any apps that require gps hardware such as gps navigators should explicitly add the androidhardwarelocationgps usesfeature to their manifestif your app requires gps to function properly and you do not include in your manifest declaration your users may have a poor app experiencealso if youare using the fused location provider and wish to receive the most accurate location samples from gps ie with priority high accuracy you must include the androidhardwarelocationgps feature in your appas manifest to ensure that google play only thistributes your app to devices with gps sensorsyou can read more about this change in the android developers help centerfrom the android developers help centerin order to receive location updates from network provider or gps provider you must request the users permission by declaring either the access coarse location or access fine location permission respectively in your android manifest file without these permissions your application will fail at runtime when requesting location updatesif you are using both network provider and gps provider then you need to request only the access fine location permission because it includes permission for both providers permission for access coarse location allows access only to network providercaution if your app targets android 50 api level 21 or higher you must declare that your app uses the androidhardwarelocationnetwork or androidhardwarelocationgps hardware feature in the manifest file depending on whether your app receives location updates from network provider or from gps provider if your app receives location information from either of these location provider sources you need to declare that the app uses these hardware features in your app manifest on devices running verions prior to android 50 api 21 requesting the access fine location or access coarse location permission includes an implied request for location hardware features however requesting those permissions does not automatically request location hardware features on android 50 api level 21 and higheri am using the fused location provider targeting api 21 and using access fine location i do not specifically care whether gps is available only that the most accurate location is reported based on the first quotation i think i do not have to make any changes based on the second quotation i think i need both androidhardwarelocationgps and androidhardwarelocationnetwork or is this only for locationmanager and not fused location do i need androidhardwarelocationgps and androidhardwarelocationnetwork or not,['android'] +1241596,jackson custom filter with full pojo data bind this question extends this questionwhile the previous solution works great if you only have a couple of fields it becomes unmaintainable when you have more than a dozen of fields right now my current set up uses full data binding so i have a pojo that will be used by jackson to automatically deserialize json however as before certain fields have constraints that need to pass essentially i am looking for an answer similar to this but without the need to set any properties just a custom deserializer that will act as a filter and throw a custom exception if a field does not meet the constraint if no exception has been thrown by the end of the filter jackson should automatically bind json to pojo,['java'] +1241671,compiler dropping my type conversion i am puzzled by what i had to do to get this code to work it seems as if the compiler optimized away a type conversion that i needed or there is something else i do not understand herei have various objects that are stored in the database that implement the interface foo i have an object bar which holds data i am using to retrieve my foo objects bar has these methodsclass getfooclasslong getfooidi pass the class and id to a method with this signature which delegates to hibernate which retrieves the subject based on its class and idpublic t t getclasst clazz serializable idthere are different implementers of foo and some of these hibernate objects have a long id and others have an integer id although this method accepts either farther down it had better have the right one so when i tried to call get on an object with an integer id as follows i understandably got an error complaining that i had provided a long where an integer was required getbargetfooclass bargetfooidthere is no hibernate problem here i just need to provide an integer where an integer id is required and a long where a long id is required so i added a method to bar haslongid and tried this at this point you may be thinking this is not a good design but that is not my question right nowgetbargetfooclass barhaslongid bargetfooid bargetfooidintvalueand it still complained that i had provided a long that seemed strange then i tried thisgetbargetfooclass barhaslongid bargetfooid new integerbargetfooidintvaluesame error how can this be so i stepped through in the debugger and yes it stepped through intvalue and also through the integer constructor but then in the get method the passed parameter was in fact a longathe same long object that was returned from getfooidi do not understand whats happening so i just try various thingsinteger intid bargetfooidintvaluegetbargetfooclass barhaslongid bargetfooid intid same errorandserializable id barhaslongid bargetfooid new integerbargetfooidintvaluegetbargetfooclass id same errorand finallyserializable idif barhaslongid id bargetfooid else id bargetfooidintvaluegetbargetfooclass idthis one works so apparently it has something to do with the ternary operator but why can someone explain what happened here,['java'] +1241957,custom shortcode in wordpress nav bar i just want to add a shortcode button to my wordpress theme menu bar for handle the bootstrap modal view function i tried shortcodes in menus plugin but it does not work i could not find alternative plugin for shortcodes in menu so i installed bootstrap 3 shortcodes plugin it created button and modal view content as i want but i could not add shortcode to my menubari did hard try to find some answer about my problem but unfortunately could not thats my modal shortcode generated by bootstrap 3 shortcodes pluginmodal textdownload now titleveteriner hekimlere ulaamanan en kolay yolu xclassbtn btnprimary btnlgp styletextalign centerimg src altlogo width200 height300 ph4 styletextalign centervetmappi cihazanaza gare adaki platformlardan cep telefonunuza a14cretsiz olarak indirebilir ve hemen kullanmaya baalayabilirsinizh4p styletextalign center a href target blankimg src altapp storedan indir width135 height40 a a hrefamphltr target blankimg src playpngpagespeedic31v8jamtbipng altgoogle playden indir width135 height40 a a href target blankimg src phonepngpagespeedicxvoiaciudppng altwindows storedan indir width135 height40 apmodalfooter button typeprimary styleborder solid 1px 18bda3 backgroundcolor f color 18bda3 link datathismissmodalkapatbutton modalfooter modali just want to use modal textdownload now titleveteriner hekimlere ulaamanan en kolay yolu xclassbtn btnprimary btnlg into wp navigation barhow can i do this i can write a function in functionsphp for this or try some another approach thank you,"['php', 'jquery']" +1242234,instant run issue on android studio 22 i have updated my android studio to 22 since then i get this strange issue when running the studio gives me error instant run requires that the platform corresponding to your target device android 10 is installed i am using note 4 on android 601 why is this error happening,['android'] +1242308,warning frame for navigation bar will be different at the run time appears in xcode 8 swift 3 before i have upgraded to xcode 8 i have not seen this error in such case i have different navigation controllers for all of them i see an error frame for navigation bar will be different at the run time navigation bar expected width384 actual width375 in reality these navigation controllers does not have navigation bar navigation bar exists for subviews anyway i could solve it by tick and untick the checkbox shows navigation bar in attributes inspector but unfortunately every time i reopen mainstoryboard this warning appears again also if i click on yellow triangle and then on update frames nothing happen any ideas,['ios'] +1242350,using a dll exported from d i have created a simple encryption program in d and i had the idea to make a dll from it and try to import it to for example pythoni have could simply call my main function becouse it dosnt need any params but when i get to my encrytion method it uses dynamiclenght ubyte arrays but as far as i know they do not exist in other cc based langsfor example there is the first line of one of my funcsubyte encodeubyte data ubyte keybut i cannot use an array without fixed lenght in other languageshow can i import that function for example in pythonediti know that i can create a wrapper that takes a pointer and the lenght of the array but is not there a more elegant solutionwhere i do not need to use d to use a lib written in d,['python'] +1243077,what precautions should i take to make a memory pool that does not invoke undefined behavior my initial problem is that i have on a project several objects which share a lifetime ie once i free one of them i will free them all then i wanted to allocate a single block of memory i have arrays of three different object types struct foo void and char at first i wanted to malloc a block like this struct foon padding void m padding charo but then how could i accomplish this without invoking undefined behavior ie respecting type aliasing rules aligment how to properly calculate the memory block size declare the memory block with its effective type and how to properly get pointers to all three sections within it portablyi do understand i could malloc 3 blocks which would result in three free but i would like to know how to do it with a single block while still wellbehavedi would like to extend my problem to a more general question what precautions should one take to implement a memory pool for objects with arbitrary sizes and alignment while keeping the program wellbehaved assuming it is possible to implement it without invoking undefined behavior,['c'] +1243135,eclipse to android studio import i am moving all my source codes to as as suggested by android official website however the experience is not very good it is very sluggish as described here but this is not my ultimate problem for now i have resolved many problems such as updating the compilesdkversion to 23 so that 99 errors of this kind error13 error retrieving parent for item no resource found that matches the given name androidtextappearancematerialinversecould be rectified but the problems keep on shooting up as i go now i have this 64k dex issue errorthe number of method references in a dex file cannot exceed 64k learn how to resolve this issue at i never had this dex issue while using eclipse the source code i have in as is exactly the same as when it was in eclipse the only differences are those gradle changes needed only to work on as any idea why this sudden dex issue if i set multidexenabled to true what are the implications,['android'] +1243295,stdregex to match beginend of string in js regular expressions symbols and designate start and end of the string and only with m modifier multiline mode they match start and end of line position before and after crlfbut in stdregexecmascript mode symbols and match start and end of line alwaysis there any way in stdregex to define start and end of the string match points in other words to support javascript multiline mode,['c++'] +1244264,compiler error error cs0307 the variable int cannot be used with type arguments if i have the following codeprivate void checkbool a bool bprivate void checkint a int b int c bool flag checka b a flag c b 10i get a compiletime error on the call to checkint interror cs0307 the variable int cannot be used with type argumentsi also get these errorserror cs0118 b is a variable but is used like a type error cs0118 a is a variable but is used like a typewhy do these errors occur what is wrong with the code,"['c#', '.net']" +1244574,the driver could not establish a secure connection to sql server by using ssl i am having problems connecting to sql databases whenever i try to connect to a sql server i get the following errorcaused by orghibernateexceptionjdbcconnectionexception error calling driverconnect at orghibernateexceptioninternalsqlstateconversiondelegateconvertsqlstateconversiondelegatejava132 at orghibernateenginejdbcconnectionsinternalbasicconnectioncreator11convertbasicconnectioncreatorjava118 at orghibernateenginejdbcconnectionsinternalbasicconnectioncreatorconvertsqlexceptionbasicconnectioncreatorjava140 at orghibernateenginejdbcconnectionsinternaldriverconnectioncreatormakeconnectiondriverconnectioncreatorjava58 at orghibernateenginejdbcconnectionsinternalbasicconnectioncreatorcreateconnectionbasicconnectioncreatorjava75 at orghibernateenginejdbcconnectionsinternaldrivermanagerconnectionproviderimplconfiguredrivermanagerconnectionproviderimpljava106 at orghibernatebootregistryinternalstandardserviceregistryimplconfigureservicestandardserviceregistryimpljava1 at orghibernateserviceinternalabstractserviceregistryimplinitializeserviceabstractserviceregistryimpljava234 at orghibernateserviceinternalabstractserviceregistryimplgetserviceabstractserviceregistryimpljava206 at orghibernateenginejdbcinternaljdbcservicesimplbuildjdbcconnectionaccessjdbcservicesimpljava260 at orghibernateenginejdbcinternaljdbcservicesimplconfigurejdbcservicesimpljava94 at orghibernatebootregistryinternalstandardserviceregistryimplconfigureservicestandardserviceregistryimpljava1 at orghibernateserviceinternalabstractserviceregistryimplinitializeserviceabstractserviceregistryimpljava234 at orghibernateserviceinternalabstractserviceregistryimplgetserviceabstractserviceregistryimpljava206 at orghibernatecfgconfigurationbuildtyperegistrationsconfigurationjava1887 at orghibernatecfgconfigurationbuildsessionfactoryconfigurationjava1845 at orghibernatejpabootinternalentitymanagerfactorybuilderimpl4performentitymanagerfactorybuilderimpljava857 at orghibernatejpabootinternalentitymanagerfactorybuilderimpl4performentitymanagerfactorybuilderimpljava850 at orghibernatebootregistryclassloadinginternalclassloaderserviceimplwithtcclclassloaderserviceimpljava425 at orghibernatejpabootinternalentitymanagerfactorybuilderimplbuildentitymanagerfactorybuilderimpljava849 at orghibernatejpahibernatepersistenceprovidercreateentitymanagerfactoryhibernatepersistenceproviderjava75 143 morecaused by commicrosoftsqlserverjdbcsqlserverexception the driver could not establish a secure connection to sql server by using secure sockets layer ssl encryption error sql server did not return a response the connection has been closed clientconnectionid at commicrosoftsqlserverjdbcsqlserverconnectionterminatesqlserverconnectionjava1667 at commicrosoftsqlserverjdbctdschannelenablessliobufferjava1668 at commicrosoftsqlserverjdbcsqlserverconnectionconnecthelpersqlserverconnectionjava1323 at commicrosoftsqlserverjdbcsqlserverconnectionloginsqlserverconnectionjava991 at commicrosoftsqlserverjdbcsqlserverconnectionconnectsqlserverconnectionjava827 at commicrosoftsqlserverjdbcsqlserverdriverconnectsqlserverdriverjava1012 at orghibernateenginejdbcconnectionsinternaldriverconnectioncreatormakeconnectiondriverconnectioncreatorjava55 160 morecaused by javaioioexception sql server did not return a response the connection has been closed clientconnectionid at commicrosoftsqlserverjdbctdschannelsslhandshakeinputstreamensuresslpayloadiobufferjava651 at commicrosoftsqlserverjdbctdschannelsslhandshakeinputstreamreadinternaliobufferjava708 at commicrosoftsqlserverjdbctdschannelsslhandshakeinputstreamreadiobufferjava700 at commicrosoftsqlserverjdbctdschannelproxyinputstreamreadinternaliobufferjava895 at commicrosoftsqlserverjdbctdschannelproxyinputstreamreadiobufferjava883 at sunsecuritysslinputrecordreadfullyinputrecordjava465 at sunsecuritysslinputrecordreadinputrecordjava503 at sunsecuritysslsslsocketimplreadrecordsslsocketimpljava973 at sunsecuritysslsslsocketimplperforminitialhandshakesslsocketimpljava1375 at sunsecuritysslsslsocketimplstarthandshakesslsocketimpljava1403 at sunsecuritysslsslsocketimplstarthandshakesslsocketimpljava1387 at commicrosoftsqlserverjdbctdschannelenablessliobufferjava1618 165 morethis is using commicrosoftsqlserverjdbcsqlserverdriverwhenever i use the jtds driver suggested by eg this post i am still not able to connect to the sql server and i get the following errorcaused by orghibernateexceptionjdbcconnectionexception error calling driverconnect at orghibernateexceptioninternalsqlstateconversiondelegateconvertsqlstateconversiondelegatejava132 at orghibernateenginejdbcconnectionsinternalbasicconnectioncreator11convertbasicconnectioncreatorjava118 at orghibernateenginejdbcconnectionsinternalbasicconnectioncreatorconvertsqlexceptionbasicconnectioncreatorjava140 at orghibernateenginejdbcconnectionsinternaldriverconnectioncreatormakeconnectiondriverconnectioncreatorjava58 at orghibernateenginejdbcconnectionsinternalbasicconnectioncreatorcreateconnectionbasicconnectioncreatorjava75 at orghibernateenginejdbcconnectionsinternaldrivermanagerconnectionproviderimplconfiguredrivermanagerconnectionproviderimpljava106 at orghibernatebootregistryinternalstandardserviceregistryimplconfigureservicestandardserviceregistryimpljava1 at orghibernateserviceinternalabstractserviceregistryimplinitializeserviceabstractserviceregistryimpljava234 at orghibernateserviceinternalabstractserviceregistryimplgetserviceabstractserviceregistryimpljava206 at orghibernateenginejdbcinternaljdbcservicesimplbuildjdbcconnectionaccessjdbcservicesimpljava260 at orghibernateenginejdbcinternaljdbcservicesimplconfigurejdbcservicesimpljava94 at orghibernatebootregistryinternalstandardserviceregistryimplconfigureservicestandardserviceregistryimpljava1 at orghibernateserviceinternalabstractserviceregistryimplinitializeserviceabstractserviceregistryimpljava234 at orghibernateserviceinternalabstractserviceregistryimplgetserviceabstractserviceregistryimpljava206 at orghibernatecfgconfigurationbuildtyperegistrationsconfigurationjava1887 at orghibernatecfgconfigurationbuildsessionfactoryconfigurationjava1845 at orghibernatejpabootinternalentitymanagerfactorybuilderimpl4performentitymanagerfactorybuilderimpljava857 at orghibernatejpabootinternalentitymanagerfactorybuilderimpl4performentitymanagerfactorybuilderimpljava850 at orghibernatebootregistryclassloadinginternalclassloaderserviceimplwithtcclclassloaderserviceimpljava425 at orghibernatejpabootinternalentitymanagerfactorybuilderimplbuildentitymanagerfactorybuilderimpljava849 at orghibernatejpahibernatepersistenceprovidercreateentitymanagerfactoryhibernatepersistenceproviderjava75 143 morecaused by javasqlsqlexception io error db server closed connection at netsourceforgejtdsjdbctdscorenexttokentdscorejava2481 at netsourceforgejtdsjdbctdscorelogintdscorejava632 at netsourceforgejtdsjdbcjtdsconnectioninitjtdsconnectionjava371 at netsourceforgejtdsjdbcdriverconnectdriverjava184 at orghibernateenginejdbcconnectionsinternaldriverconnectioncreatormakeconnectiondriverconnectioncreatorjava55 160 morecaused by javaioioexception db server closed connection at netsourceforgejtdsjdbcsharedsocketreadpacketsharedsocketjava852 at netsourceforgejtdsjdbcsharedsocketgetnetpacketsharedsocketjava731 at netsourceforgejtdsjdbcresponsestreamgetpacketresponsestreamjava477 at netsourceforgejtdsjdbcresponsestreamreadresponsestreamjava114 at netsourceforgejtdsjdbctdscorenexttokentdscorejava2368 164 morethe connection string i use using jtdsjdbcjtdssqlserverurldatabasewindowsnetportdatabasenameor when not using jtdsjdbcsqlserverurldatabasewindowsnetportdatabasenamei also have a server that is actually able to run and connect to the database using these configurations i just keep getting these errors trying to connect to the database locallyi am running macos sierra version 1021jtds versiondependency groupidnetsourceforgejtdsgroupid artifactidjtdsartifactid version131versiondependencysqlserver versiondependency groupidcommicrosoftsqlservergroupid artifactidsqljdbc4artifactid version40versiondependencyediti am able to connect to the database using the same configuration and same laptop on a different network it is only on my network at home that i get this error,['java'] +1244604,layout interface builder constraints issue since xcode 8 since i have updated my swift project to swift 23 and xcode 8 release version i cannot get my interface done anymore i am setting perfectly all the constraints everything works fine i am reopening xcode the next day and all my views look like thatalso i am getting tons of warningsif i click on update frame the warning thisappears and the view looks normal again but as soon as i restart xcode or sometimes even just build the project it is undone againimportant all the views look perfect and as wanted inside any devices but it is really hard to keep the overview i have spend a whole night replacing all the elements of my current project everything was fine without any warnings next day warnings back and i changed literally nothing how do i get rid of this help is very appreciatedi can update the frame everything looks good again after a couple of builds or at the very latest after reopening xcode it looks like that againlatest example extreme simple screen uiviewcontroller uinavigationbar uitableview no segues one prototype celldid set all the constraints perfectly last night reopened xcode found thisedit the suggested workaround to switch desired controllers simulated size to freeform in inspector and then update frames is just a temporary solution as soon as i reopen xcode all the warnings are back again i can change the value to fixed then all the elements pop back to their desired position and the warnings thisappear reopen xcode and all the warnings are back and the controllers elements are all in a tumble againalso the suggestion to change the storyboard file type to 7x did not had any effect i pressed 7x it asked me if i want to change pressed ok loaded i opened the mainstoryboard and it asked me in what device i want to open the storyboard xcode 80 was reselected then,"['ios', 'objective-c']" +1244880,how to lockunlock the screen with patternpassword mode in android i was successful to lockunlock my screen using devicepolicymanager and keyguardmanager in android l it worked well when i lockunlock screen using swipe mode no security however i cannot lockunlock it when i lockunlock screen by using pattern and password mode higher security is it possible to lockunlock screen with high security using devicepolicymanager and keyguardmanager this is what i didprotected static final int request enable 0devicepolicymanager devicepolicymanagercomponentname admincomponentoverrideprotected void oncreatebundle savedinstancestate superoncreatesavedinstancestate setcontentviewrlayoutactivity main button button button findviewbyidridbtn buttonsetonclicklistenerbtnlistenerlockbuttononclicklistener btnlistener new buttononclicklistener public void onclickview v admincomponent new componentnamemainactivitythis darclassclass devicepolicymanager devicepolicymanager getsystemservicecontextdevice policy service if devicepolicymanagerisadminactiveadmincomponent intent intent new intentdevicepolicymanageraction add device admin intentputextradevicepolicymanagerextra device admin admincomponent startactivityforresultintent request enable else devicepolicymanagerlocknow unlock private keyguardmanager keyguardmanager keyguardmanagerkeyguardlock kl keyguardmanager keyguardmanager getsystemservicekeyguard service kl keyguardmanagernewkeyguardlockmykeyguardlock klthisablekeyguardnote that i am using it in a service,['android'] +1245037,warn establishing ssl connection without servers identity verification is not recommended hello i am trying to connect to a mysql database via a java servlet using eclipse and tomcat but i take the following error warn establishing ssl connection without servers identity verification is not recommendedi added usesslfalse to the connection url but still get the same errorany suggestions the servlet us code is package comsimplewebapplicationservletimport javaioioexceptionimport javaioprintwriterimport javasqlconnectionimport javasqldrivermanagerimport javasqlpreparedstatementimport javaxservletservletexceptionimport javaxservletannotationwebservletimport javaxservlethttphttpservletimport javaxservlethttphttpservletrequestimport javaxservlethttphttpservletresponsewebservletregisterpublic class registerservlet extends httpservlet private static final long serialversionuid 1l see httpservlethttpservlet public registerservlet super todo autogenerated constructor stubprotected void doposthttpservletrequest request httpservletresponseresponse throws servletexception ioexception dogetrequest response responsesetcontenttypetexthtml printwriter out responsegetwriter string idusers requestgetparameter0 string name requestgetparametername string surname requestgetparametersurname string gender requestgetparametergender string birthdate requestgetparameterbirthdate string workaddress requestgetparameterworkaddress string homeaddress requestgetparameterhomeaddress try classfornamecommysqljdbcdriver connection con drivermanagergetconnectionjdbcmysqllocalhost3306mysysautoreconnecttrueusesslfalserootpass preparedstatement ps conpreparestatementinsert into users values pssetstring1 idusers pssetstring2 name pssetstring3 surname pssetstring4 gender pssetstring5 birthday pssetstring6 workaddress pssetstring7 homeaddress int ipsexecuteupdate ifi0 outprintlnyou are sucessfully registered catchexception se seprintstacktrace and here is registerjsp page that is connected with the servlet page languagejava contenttypetexthtml charsetiso88591 pageencodingiso88591 doctype html public w3cdtd html 401 transitionalen html head meta httpequivcontenttype contenttexthtml charsetiso88591 titleregister new usertitle head body form actionregister methodpost table aligncenter bgcolorf border1 width70 tr td colspan2 aligncenteruser details td tr tr tdname td tdinput typetext namename maxlength25td tr tr tdsurname td tdinput typetext namesurname maxlength40td tr tr tdgender td tdselect option valuemalemaleoption option valuefemalefemaleoption selecttd tr tr tdbirthdate td tdinput typedate namebirthdate maxlength30td tr tr tr tdwork address td tdinput typetext nameworkaddress maxlength30td tr tr tdhome address td tdinput typetext namehomeaddress maxlength30td tr td colspan2 aligncenterinput typesubmit valuesubmittd tr table form body htmlstack error wed sep 28 085853 eest 2016 warn establishing ssl connection without servers identity verification is not recommended according to mysql 5545 5626 and 576 requirements ssl connection must be established by default if explicit option is not set for compliance with existing applications not using ssl the verifyservercertificate property is set to false you need either to explicitly thisable ssl by setting usesslfalse or set usessltrue and provide truststore for server certificate verificationjavasqlsqlexception access denied for user usernamelocalhost using password yes at commysqljdbcsqlerrorcreatesqlexceptionsqlerrorjava963 at commysqljdbcmysqliocheckerrorpacketmysqliojava3966 at commysqljdbcmysqliocheckerrorpacketmysqliojava3902 at commysqljdbcmysqliocheckerrorpacketmysqliojava875 at commysqljdbcmysqlioproceedhandshakewithpluggableauthenticationmysqliojava1712 at commysqljdbcmysqliodohandshakemysqliojava1228 at commysqljdbcconnectionimplcoreconnectconnectionimpljava2253 at commysqljdbcconnectionimplconnectonetryonlyconnectionimpljava2284 at commysqljdbcconnectionimplcreatenewioconnectionimpljava2083 at commysqljdbcconnectionimplinitconnectionimpljava806 at commysqljdbcjdbc4connectioninitjdbc4connectionjava47 at sunreflectnativeconstructoraccessorimplnewinstance0native method at sunreflectnativeconstructoraccessorimplnewinstanceunknown source at sunreflectdelegatingconstructoraccessorimplnewinstanceunknown source at javalangreflectconstructornewinstanceunknown source at commysqljdbcutilhandlenewinstanceutiljava404 at commysqljdbcconnectionimplgetinstanceconnectionimpljava410 at commysqljdbcnonregisteringdriverconnectnonregisteringdriverjava328 at javasqldrivermanagergetconnectionunknown source at javasqldrivermanagergetconnectionunknown source at comsimplewebapplicationservletregisterservletdopostregisterservletjava47 at javaxservlethttphttpservletservicehttpservletjava650 at javaxservlethttphttpservletservicehttpservletjava731 at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava303 at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava208 at orgapachetomcatwebsocketserverwsfilterdofilterwsfilterjava52 at orgapachecatalinacoreapplicationfilterchaininternaldofilterapplicationfilterchainjava241 at orgapachecatalinacoreapplicationfilterchaindofilterapplicationfilterchainjava208 at orgapachecatalinacorestandardwrappervalveinvokestandardwrappervalvejava218 at orgapachecatalinacorestandardcontextvalveinvokestandardcontextvalvejava122 at orgapachecatalinaauthenticatorauthenticatorbaseinvokeauthenticatorbasejava505 at orgapachecatalinacorestandardhostvalveinvokestandardhostvalvejava169 at orgapachecatalinavalveserrorreportvalveinvokeerrorreportvalvejava103 at orgapachecatalinavalvesaccesslogvalveinvokeaccesslogvalvejava956 at orgapachecatalinacorestandardenginevalveinvokestandardenginevalvejava116 at orgapachecatalinaconnectorcoyoteadapterservicecoyoteadapterjava442 at orgapachecoyotehttp11abstracthttp11processorprocessabstracthttp11processorjava1082 at orgapachecoyoteabstractprotocolabstractconnectionhandlerprocessabstractprotocoljava623 at orgapachetomcatutilnetjioendpointsocketprocessorrunjioendpointjava318 at javautilconcurrentthreadpoolexecutorrunworkerunknown source at javautilconcurrentthreadpoolexecutorworkerrununknown source at orgapachetomcatutilthreadstaskthreadwrappingrunnableruntaskthreadjava61 at javalangthreadrununknown source,"['java', 'mysql']" +1245269,implement css3 style for drag and drop angularjs after click a button i had done an angularjs drag and drop method in my project i do not have any problems in drag and drop however i got problems on how to make style for draggable element after next action was takenfor my case if user drag goose and rabbit to box labelled animals that give birth the user will click the button check answer there will be correct or wrong symbol above each draggble divi try to inspect the element but i have seen only these stylesngdrag width 50px height 50px background rgba255 255 255 05 color 131313 textalign center paddingtop 12px thisplay inlineblock margin 5px 5px cursor move border 1px solid c borderradius 4pxthe ngdrag directive was applied to each draggable element how i can differentiate it each element and make it individual style this thing was make me so confuse and need help from you all guys can anyone help mei do really appreciate for any suggestion or helpmy expected outputsnippet for your referencevar myapp angularmodulemyappngdraggablecontrollermyctrlfunctionscope scopecheckanswer function scopecenteranchor true scopetogglecenteranchor function scopecenteranchor scopecenteranchor var ondraggableevent function evt data consolelog128 ondraggableevent evt data scopeondraggablestart ondraggableevent scopeondraggableend ondraggableevent scopedroppedobjects0 namegoosenamerabbitnamechicknamecat scopedroppedobjects1 answer cat rabbit scopedroppedobjects2 answer chicken goose scopeansweroject1 namearnabnamekucing scopeansweroject2 nameangsanameayam scopeondropcomplete0 function data evt consolelog127 scope ondropcomplete0 data evt var index scopedroppedobjects0indexofdata if index 1 scopedroppedobjects0pushdata scopeondropcomplete1 function data evt consolelog127 scope ondropcomplete1 data evt var index scopedroppedobjects1indexofdata if index 1 scopedroppedobjects1pushdata scopeondragsuccess0 function data evt consolelog133 scope ondragsuccess0 evt var index scopedroppedobjects0indexofdata if index 1 scopedroppedobjects0spliceindex 1 scopeondragsuccess1 function data evt consolelog133 scope ondragsuccess1 evt var index scopedroppedobjects1indexofdata if index 1 scopedroppedobjects1spliceindex 1 scopeondragsuccess2 function data evt var index scopedroppedobjects2indexofdata if index 1 scopedroppedobjects2spliceindex 1 scopeondropcomplete2 function data evt var index scopedroppedobjects2indexofdata if index 1 scopedroppedobjects2pushdata var inarray function array obj var index arrayindexofobj body width500px marginleftauto marginrightautongdrag mozuserselect moznone khtmluserselect none webkituserselect none msuserselect none userselect nonengdrag width 50px height 50px background rgba255 255 255 05 color 131313 textalign center paddingtop 12px thisplay inlineblock margin 5px 5px cursor move border 1px solid c borderradius 4pxuldraggableobjectsafter thisplay block content clear bothdraggableobjects li float left thisplay block width 50px height 50px margin2pxngdragdragover border solid 1px redngdragdragging opacity 05ngdrop background rgba198 255 198 05 textalign center height 150px paddingtop 10px thisplay block margin 20px auto position relative border 1px solid c3c3c3 borderradius 8pxngdropdragenter border solid 5px redngdrop spantitle thisplay block position absolute top 50 left 50 width 200px height 20px marginleft 100px margintop 10pxngdrop div position relative zindex 2listofdragitem height 83px backgroundcolor f7f7f7link href relstylesheetscript srcscriptscript srcscriptscript srcscriptdiv ngappmyapp ngcontrollermyctrl classbodycategorize the animals based on their reproductive systemdiv classrow div classcol div classlistofdragitem ngdroptrue ngdropsuccessondropcomplete0dataevent div ngrepeatobj in droppedobjects0 ngdragtrue ngdragdataobj ngdragsuccessondragsuccess0dataevent ngcenteranchorcenteranchor objname div div divdivdiv classrow styletextalign center div classcol divleft span classtitleanimals that give birth div ngdroptrue ngdropsuccessondropcomplete1dataevent div ngrepeatobj in droppedobjects1 ngdragtrue ngdragdataobj ngdragsuccessondragsuccess1dataevent ngcenteranchorcenteranchor objname div div div div classcol divright span classtitleanimals that laying eggsspan div ngdroptrue ngdropsuccessondropcomplete2dataevent div ngrepeatobj in droppedobjects2 ngdragtrue ngdragdataobj ngdragsuccessondragsuccess2dataevent ngcenteranchorcenteranchor objname div div divdiv div styletextaligncenter button ngclickcheckanswercheck answerbutton div div,"['javascript', 'css']" +1245586,memory issue in angular js application i am facing memory leak issue in angular js application i have tried all the possible solutions like profile tool timeline and some other tools related to angular jsmy work till now profile toolin profile tool js heap is keep on getting increased but cannot able to find the reason for ittimeline it shows there is a possibility of memory leaks but still i do not know how to debug and fix ittask manager it keep on increasing the memory sizesome time it is getting garbage collected but not significantly please let me know how to debug and find out what could be the issueor share your experience if you have faced the same issue,['javascript'] +1245672,gradle building takes forever after upgrading to java 8 i tried to enable java 8 features in android studio like suggested in defaultconfig jackoptions enabled true compileoptions sourcecompatibility javaversionversion 1 8 targetcompatibility javaversionversion 1 8after that i added compile netsourceforgestreamsupportstreamsupport151 and was able to use lambdas since i have done that the gradle build takes forever i killed the process after 20 minutes to try other solutions my hardware is not pretty good but still this is not an acceptable time for a build and it never finished i also tried to remove this changes but i face related compilations errorsi can pull the previous app version from git but i rather solve these issues to be able to us java 8 features did anyone face this problem and managed to solve it thanks,"['java', 'android']" +1246002,how to test android pay with a debug apk by default android pay refuses to work in debug builds which makes testing tricky what weve done so far is to actually merge new code into a develop or hotfix branch so our build environment will make a signed apk which can be tested this is not ideal statesnote our test environment will not return live chargeable tokens in the fullwallet response but will allow us to test your prepurchase flow you will see an unrecognized app error on the android pay chooser until your app has production accesswhich is not too promising testinghtml suggests testing with specially configured static responses for reserved product ids which would be a nuisance to set up and not a true test the other option they offer is to publish the app to an alpha or beta channel which would of course be a signed apk has a suggestion about test gateway token but is not really helpful in learning how to use android pay in testwe even talked to a google developer advocate who did nothing but cut and paste some of the same documentationis there any way to do a good test using an unsigned build it would be wonderful to test android pay functionality successfully on a local developer machine,['android'] +1246221,how to wrap checked exceptions but keep the original runtime exceptions in java i have some code that might throw both checked and runtime exceptionsi would like to catch the checked exception and wrap it with a runtime exception but if a runtimeexception is thrown i do not have to wrap it as it is already a runtime exceptionthe solution i have has a bit overhead and is not neattry some code that can throw both checked and runtime exception catch runtimeexception e throw e catch exception e throw new runtimeexceptioneany idea for a more elegant way,['java'] +1246369,cordova fingerprint authentication on server i am trying to create a authentication mechanism in my cordova app for android that will allow my users to sign in using a password and username or allow them to scan their finger in order to sign in how can one verify a fingerprint registered on a client server side is this even possible at all using cordova i tried transmitting the result of a finger scan to my server this looked like fingerprintauthisavailablefunctionresult if resultisavailable ifresulthasenrolledfingerprints fingerprintauthshow clientid client id clientsecret client secret function result alertjsonstringifyresult httppost resultthenfunctionresponse if resultwithfingerprint scopeparentloggedin true alertsuccessfully authenticated using a fingerprint locationpath home else if resultwithpassword alertauthenticated with backup password functionerror consolelogerror fingerprint authentication not available else alertfingerprint auth available but no fingerprint registered on the device functionmessage alertcannot detect fingerprint device message server side i am receiving the following data 3 seperate scans withfingerprint t8hayq36fmbpuepbvjiwoabljmpbeunpbtokovtz2zix20ebvzzas3dn6pwr4en withfingerprint ra9hmioqr3au9pqglaieocra9b0wx1avzctagiuc8ccedfzfidzkxny5u4jobn withfingerprint mmyjm46o8mtxsa9aofkus9fzw3ozvg7ojdxspo71lwvy4tzh2ftvptfjjfnj7syn the patterns seems to vary every time is there a way one can link the finger print to for example a pattern saved under a user on a database,"['javascript', 'android']" +1246451,monad interface in c i am currently learning a little bit haskell and started to figure out how monads worksince i normaly code c and i think the monad pattern would be as fas as i understand it right now be realy awesome to use in c too for example for futures etci wonder if there is a way to implement an interface or a base class to enforce a correct overload of the functions bind and return of cause with another name than return for c for derived typesto make more clear what i am thinking ofconsider we have the following non member functionauto fooconst int x const stdstringand a member function bar which has different overloads in for different classesauto bar const const monadintif we now want to do something like this foosomememberbarthis simply doesnt work so if have to know what bar returns and for example if it returns a futureint we have to call barget which blocks even if we dont need to block herein haskell we could do something like bar fooso i am asking myself if we could achieve such a behaviour in c because when calling foox we dont care if x is a object which boxes an int and in what kind of class the int is boxed we just want to apply function foo on the boxed typei am sorry i have some problem formulating my thoughts in english since i am not a native speaker,['c++'] +1246538,dynamic partial arguments in angularjs routing i am working with an angularjs site and have a background with working with routes in rails and also laravel in php with routes in laravel we could dynamically create a set of routes similar to foreachcities as city routegetcityhotels routegetcityslug endforeach here we defined series of seperate routes in laravel which technically do look the same except for the value of city and slugi am finding angularjs a bit limited in defining routes in this case frankly am a bit lost hereupdatei have made some modifications here basically i set up a service which retrieves assets from my database such as in this case a list of cities and categories i am trying to do thisif slug is in the array of categories retrieved from my api then use my listcontroller and list view but if its not then instead use my singlevenuecontroller and single view heres my code at the moment but its not working approuteproviderwhencityslug templateurl functionsharedparams routeparams t sharedparamsgetcurrentpagetyperouteparams iftlist return apptemplateslisthtml iftsingle return apptemplatessinglehtml controller functionsharedparams routeparams t sharedparamsgetcurrentpagetyperouteparams iftlist return listscontroller iftsingle return singlecontroller resolve sharedparamsdatafunctionsharedparams return sharedparamspromise in the above sharedparams is a service and the getcurrentpagetype just checks the url slug to decide what controller to send back but its not really working at all,"['javascript', 'php']" +1246672,connecting to mysql in c i am trying to learn c and i am having a bit of nightmare doing a test where i connect to a mysql database i have had issues with the mysql connector not linking properly then was getting issues related to relocation truncated to fitr x86 64 32 against symbol i think i have fixed that by adding a compiler flag and now the app successfully builds and links when i run the app it gets as far as calling get driver instance but then it exits no exception is thrown no errors nothing just exit code 0 below is my dbmanager classinclude dbconnectionmanagerhusing namespace stddbconnectionmanagerdbconnectionmanager cout starting dbconnectionmanager updated endl try cout getting driver instance endl driver get driver instance cout got driver instance endl conn driverconnecttcp1270013306 root password connsetschemabugs cout connected to database endl catch sqlexception ex cout error connecting to db exwhat endl catch cout something has gone wrong endl below is the header fileifndef mysqltest dbconnectionmanager hdefine mysqltest dbconnectionmanager hinclude driverhinclude exceptionhinclude resultsethinclude statementhusing namespace sqlclass dbconnectionmanagerprivate sqldriver driver sqlconnection conn sqlstatement statement sqlresultset respublic dbconnectionmanager void performsqlendif mysqltest dbconnectionmanager hbelow is my main methodinclude dbconnectionmanagerhint main dbconnectionmanager dbconnectionmanager dbconnectionmanagerperformsql return 0below is my cmakeliststxt filecmake minimum requiredversion 36projectmysqltestinclude directoriescprogram filesmysqlmysql connector c 117includecppconn cprogram filesmysqlmysql connector c 117liboptsetgcc coverage link flags m64 wlimagebase wl0x10 lpthread pthreadsetcmake cxx flags cmake cxx flags stdc11 m64 wlimagebase wl0x10 lpthread pthread setsource files maincpp dbconnectionmanagercppadd executablemysqltest source filesadd librarymysqlcppconnlibset target propertiesmysqltest properties linker language cxxset target propertiesmysqlcppconnlib properties linker language cxxtarget link librariesmysqltest cprogram filesmysqlmysql connector c 117liboptmysqlcppconnlibwhen i create the instance of my dbconnectionmanager class it successfully calls the query and prints starting dbconnectionmanager updated followed by getting driver instance but then it exits with process finished with exit code 0 with no clues as to what went wrong thanks for any help you can provide updatei am finally getting somewhere i found there are some mysql client libraries within cygwin so i have download them and referenced them in the cmake file my cmake file now looks like thiscmake minimum requiredversion 36projectmysqltestsetcppconn public funcsetgcc coverage link flags g m64 dcppconn public func dmysqlcppconn exports lpthread pthread wlimagebase wl0x10 lzsetcmake cxx flags cmake cxx flags dcppconn public func dmysqlcppconn exports stdc11 g m64 wlimagebase wl0x10 lpthread pthread lzinclude directoriescmysql connectorincludeinclude directoriescboost 1 61 0setboost include dir cboost 1 61 0setboost library dir cboost 1 61 0libssetsource files maincpp dbconnectionmanagercppadd executablemysqltest source filesfind packageboost components requiredlink directoriescmysql connectorlibtarget link librariesmysqltest cmysql connectorlibmysqlcppconndll cprogram filesmysqlmysql server 57liblibmysqldll cmysql connectorliblibmysqlclientdlla cmysql connectorliblibmysqlclient rdlla boost library dirnotice how i have linked the libraries libmysqlclientdlla and libmysqlclient rdlla which is what i got from cygwin when i run the app now it successfully gets the driver instance and to the console is outputtedstarting dbconnectionmanaged updatedgetting driver instancegot driver instancebut when i try and connect with driverconnect i then get the following error0 main mysqltest 2976 cuserschrisclion20162systemcmakegeneratedmysqltest8702ae138702ae13debugmysqltestexe fatal error internal error tp num c bufs too small 50when i put it through the debugger it fails on the driverconnect withgdb unknown target exception 0xe06d7363 at 0x7f11347788program received signal unknown signal0x07f11347788 in raiseexception from cygdrivecwindowssystem32kernelbasedllupdate 2everything i have read points the mysql connector binaries should work fine so i started again below is now the contents of my cmake file cmake minimum requiredversion 36projectmysqltestadd compile optionsvsetgcc coverage link flags setcmake cxx flags cmake cxx flags stdc11setboost include dir cboost 1 61 0setboost library dir cboost 1 61 0libsinclude directoriescprogram filesmysqlmysql connector c 117include cprogram filesmysqlmysql connector c 117includecppconn boost include dirsetsource files maincpp dbconnectionmanagercppadd executablemysqltest source filesfind packageboost components requiredlink directoriescprogram filesmysqlmysql connector c 117libopttarget link librariesmysqltest cprogram filesmysqlmysql connector c 117liboptmysqlcppconnlib boost library dirnow when i compile i get the original errorcprogram filesmysqlmysql connector c 117liboptmysqlcppconnlibmysqlcppconndllbtext0x2 relocation truncated to fit r x86 64 32 against symbol imp get driver instance defined in idata5 section in cprogram filesmysqlmysql connector c 117liboptmysqlcppconnlibmysqlcppconndllbthat sounds like to me like my app is compiling as 32 bit instead of 64 bit as a test i ran the following codecout int size is sizeofint endlthe code above prints 4 should not it be 8 if it was compiled as 64 bit if my thinking is correct why is not it compiling it as 64 bit i have tried setting the compiler flag m64 but makes no difference i have installed the cygwinx64 as well which clion is using,"['c++', 'mysql']" +1246930,ios asset sizes and design method the code for my first ios 2d game is written now when it comes to assets i feel lost one reason is the feeling of imperfection due to outdated articlesi need to know the image sizes to begin designing the device orientation of the game is portrait only the status bar is hidden game the devices is universal primary iphone but i have of course no objections if the sizes are well with ipads too what is the best image size to start designing for this intentionif i did not have your help i would have started creating the background fullscreen image at 1242 x 2208 and 401ppi then scale the final image down in photoshop to 750 x 1334 47a and to 640 x 1136 4a am i right with my method especially is it best to start with 1242 x 2208 or is 1080 x 1920 fine,['ios'] +1246981,activity onstop not called when home button is pressed in android and multi window mode i am trying to make our video app to support android and multiwindow mode i have thiscovered that activity lifecycle becomes confused in multiwindow mode the phenomenon is when our app layouts on the top screen with the whole screen in portrait then i click the home button the upper app onpause called but onstop not calledaccording to the google guideline video app should pause video playback in onstop callback rather than onpause callbackin this situation home button is pressed the activity go background and become not visible to user our app should pause video playback but we cannot get onstop callback meanwhile the activity do not fire onmultiwindowchanged callback this means the activity is still in multiwindow mode though it is in background the isinmultiwindowmode will return true in this casethe same issue will occur when the app is in the left screen with the whole screen in landscapei have searched for this question and find someone has alreay post issues to google but not handled in the android nougat releasecan1qmulti20window20onstopcolspecid20status20priority20owner20summary20stars20reporter20openedso when is the right time to pause our video playback in such situation if we pause the video in the onpause callback but the activity may be visible to user in multiwindow mode if we not do we cannot get the onstop callback in this caseare there some proper workaround for such cases,['android'] +1247068,is this layout possible with divs this should be the home view on larger screens the divs are all regions in my drupal 7 theme but i am having trouble with div3thanks for any help on this,"['html', 'css']" +1247459,how to dynamically build a form based on treebuilder object i want to define configuration schema for my class and override them with admin choicesin order to do this i need a form to capture data from adminin symfony configuration component the treebuilder class is responsible for defining configuration schema and as you know form component has tree like structure similar to treebuilder how can dynamically make a form object based on treebuilder instance,['php'] +1247633,how to solve facebook toolsreplaceandroidtheme i havecompile comfacebookandroidfacebookandroidsdk4160my manifestmanifest xmlnsandroid xmlnstools application androidnameyandexprovider androidallowbackuptrue androidicondrawableic launcher androidlabelstringapp name androidthemestyleautotheme toolsreplaceandroidthemehow to solve compile error errorexecution failed for task aprocessdebugmanifest manifest merger failed attribute activitycomfacebookfacebookactivitytheme valueandroidstylethemetranslucentnotitlebar from androidmanifestxml691372 is also present at comfacebookandroidfacebookandroidsdk4160 androidmanifestxml321363 valuestylecom facebook activity theme suggestion add toolsreplaceandroidtheme to activity element at androidmanifestxml6697047 to override,['android'] +1247866,create a new object in angular i am new to programming and i am having an issue with a memory concepti have a users page thisplaying the users in the database through an ngrepeat and each user has an option to edit or deletei also have a button on that page to add a new user my issue is that when i edit a user the information for that user remains in memory therefore when i click new the fields populate with the latest user i editedbelow is my code how can i make it create a new object when i click to add a new user var app angularmoduledico appservicesrvusuarios functionhttpvar usuarios var usuario idfullnameusernamepassword role idemailthisgetusuarios function return usuariosthisgetusuario function return usuariothisnuevo function usuarionew object usuarioid usuariofullname usuariousername usuariopassword usuariorole id usuarioemail thiseditar functionusuarioeditar usuarionew object consolelogusuario usuarioid usuarioeditarid usuariofullname usuarioeditarfullname usuariousername usuarioeditarusername usuariopassword usuarioeditarpassword usuariorole descripcion usuarioeditarrole descripcion usuarioemail usuarioeditaremail consolelogusuario appcontrollerusuarios functionscopehttp srvusuariosscopeusuarios srvusuariosgetusuariosconsolelogscopeusuariosscopeusuario srvusuariosgetusuarioconsolelogscopeusuariohttpgetrootusuarioslistarthen functionresponse scopeusuarios responsedata scopeusuariospushscopeusuario consolelogscopeusuarios function errorcallbackresponse consolelogerror responsescopefilalimite 100scopesortcolumn namescopereversesort falsescopesortdata functioncolumn scopereversesort scopesortcolumn column scopereversesort false scopesortcolumn columnscopegetsortclass functioncolumn ifscopesortcolumn column return scopereversesort arrowdown arrowup return scopenuevo function srvusuariosnuevoscopeeditar functionusuario srvusuarioseditarusuarioscopeeliminar functionusuario var index scopeusuariosindexofusuario if index 1 httppostrootusuarioseliminaridusuarioidthen functionresponse if responsedatatrue scopeusuariosspliceindex 1 function errorcallbackresponse consolelogerror response scopemyvar falsescopetoggle function scopemyvar scopemyvarscopeshow functionid ifid scopemostrar 0 consolelogscopemostrar else scopemostrar 1 appcontrollerusuario functionscope http srvusuariosscopeusuario srvusuariosgetusuarioscopeusuarios srvusuariosgetusuariosscopeaccion functionid ifid return nuevo else return editar scopeguardar functionusuario ifusuarioid httppostrootusuariosinsertar fullnameusuariofullname usernameusuariousername emailusuarioemail thenfunctionresponse consolelogresponse locationreloadtrue function errorcallbackresponse consolelogerror response else consoleclear consolelogscopeusuarios httppostrootusuarioseditaridusuarioid fullnameusuariofullname emailusuarioemail thenfunctionresponse consolelog usuarioid locationreloadtrue function errorcallbackresponse consolelogscopeusuarios consolelogerror responsedata,['javascript'] +1247925,placeholder auto wrap inside a input field i need to put a long placeholder text inside a input fieldhowever the placeholder will be cut due to its long textscript src integritysha384tc5iqib027qvyjsmfhjomalkfuwvxzxupncja7l2mcwnipg9mgcd8wgnicpd7txa crossoriginanonymousscriptlink href relstylesheet integritysha384bvyiisifek1dgmjrakycuhahrg32omucww7on3rydg4vapmstszk68vbdejh4u crossoriginanonymouslabel forpassword input idpassword nameuserpassword placeholderpassword at least 8 letters numbers or punctuation marks size30 typepasswordlabelis there any way to make it become this,"['html', 'css']" +1248414,cannot initialize an array of struct within a struct i am trying to create an rpgesque inventory my inventory contains a type sword which is an array heres the code for my sword structtypedef struct char weaponname35 int damage int rarity float price swordheres the one for the inventorytypedef struct sword swordinventsize inventoryi tried to initialize the swordinvent array in the main function but it ends up with an error error expected expression before tokenmain inventory inv invswordinvent0 paper sword 1 1 1can anyone be kind enough to help me get out of this hole editi could not thank you all enough i was not really expecting to get this much of help seriously thank you,['c'] +1248483,jquery datatables aspnet issue i am building a report dashboard using c and jquery datatables one of the reports on the page contains an update panel with a drop down list when the user changes the selection the data refreshes based on the ddl selection within each block there is also a link that makes a server side call to export the data to excel the problem is that after i click on the excel export link the drop down lists lose any functionality as do the other excel download links heres my codediv iddtopproducts classdashboarddiv styleheight400px width485px margintop 15px marginbottom15px marginright 15px runatserver aspupdatepanel idupproducts runatserver triggers aspasyncpostbacktrigger controlidlproductssector eventnameselectedindexchanged triggers contenttemplate div stylefloat left h2top productsnbspnbspnbspnbspnbspnbspnbspnbsph2 div div stylefloat left aspdropdownlist idlproductssector autopostbacktrue enableviewstatetrue onselectedindexchangedlproductssector selectedindexchanged runatserver div aspupdateprogress idprgproducts associatedupdatepanelidupproducts runatserver progresstemplate epriloaderloader runatserver progresstemplate aspupdateprogress asplistview idlvtopproducts runatserver itemtemplate tr stylepaddingtop 5px paddingbottom 5px td stylepaddingleft 0px evalproductid td td evalproductdesc td td styletextalign right evalquantity td tr itemtemplate emptydatatemplate div stylefloat left paddingtop 25px there are no product records found for the criteria provided div emptydatatemplate layouttemplate table idtbltopproducts stylewidth 100 thead tr stylepaddingbottom 10px border none th styletextalign left border none paddingleft 0pxidth th styletextalign left border none paddingleft 0pxnameth th styletextalign right border nonequantityth tr thead tfoot tr td styleborder nonetd td styleborder nonetd td styleborder nonetd tr tfoot tbody runatserver aspplaceholder iditemplaceholder runatserver tbody table layouttemplate asplistview contenttemplate aspupdatepanel link that calls full export from funding page a idatopproducts classinvoiceslink titleclick here to download full report onserverclickexporttopproductstoexcel runatserverdownload full reportadivheres the jqueryfunction bindtopproductstable var topproductstable tbltopproductsdatatable scrolly 225px scrollcollapse true bsort true order 2 desc paging false dom toolbarrtfloatrightbclear buttons buttons extend excel text export to excel exportoption page current footer true classname productsexportbutton this code is in place to handle the update panelfunction bindtopproductstable bind data table on first page load syswebformspagerequestmanagergetinstanceadd endrequestbindtopproductstable bind data table on every updatepanel refreshthe error i am getting isunable to get property style of undefined or null reference this is the full error from the ie js debuggerjfindthead tfootremovejappendhantheadcloneappendhantfootclonejfindtfoot th tfoot tdcsswidthnqaajfindthead0form0milengthmocimnmstylewidthnulloswidthorigoswidthorigxoswidthorigoswidthorigfhnmappendhdivcsswidthoswidthorigmargin0padding0border0height1ifaaodatalengthform0milengthmtimocthgbatclone1appendoscontentpaddingappendtorhnamenot surprisingly this works perfectly fine in chrome blows up in ie,"['javascript', 'c#', 'jquery', 'asp.net']" +1248820,is it possible to write a function template which returns whether the number of arguments is divisible by n i have been learning about variadic templates and with the help of this excellent blog post i have managed to write a function template even number of args which returns whether the number of arguments it receives is divisible by 2 include iostreambool even number of args return truetemplate typename tbool even number of argst return falsetemplatetypename t typename u typename vsbool even number of argst you vs vs return even number of argsvsint main stdcout even number of args stdendl true stdcout even number of args1 stdendl false stdcout even number of args1 two stdendl true stdcout even number of args1 two 30 stdendl false stdcout even number of args1 two 30 4 stdendl truei was wondering if it was possible to write a function template that takes as a template argument a number n and returns whether the number of arguments it receives is a multiple of n for example the function may look something like this number of args divisible by n11 two 30 4 truenumber of args divisible by n21 two 30 4 truenumber of args divisible by n31 two 30 4 falsenumber of args divisible by n41 two 30 4 true,['c++'] +1249156,swipeup on xcuiapplication breaks the xcuiapplication in uitest we got a test where we need to swipeup to see a cell inside of a tableview after the swipeup we cant event print out the apptables if we do not swipe everything works as expected so what has changed in swift 3 compared to swift 2 here how do we fix that issueexamplefunc testsomethinginapp let app xcuiapplication applaunch appswipeup after this we cant get apptables anymore befor everything is fine xctassertequalapptablescellselementboundbyindex5 something something like this,['ios'] +1249384,custom animation of segue is not played the first time tapping the button i encountered an unusual behavior on which i am stuck a little the problem is the followingi am using bwwalkthrough library in order to have a 4 slides as launch screen so in my appdelegate i have the following code which initialize the viewcontrollerslet storyboard uistoryboardname slidesflow bundle nillet walkthrough storyboardinstantiateviewcontrollerwithidentifier slidesview as bwwalkthroughviewcontrollerlet page zero storyboardinstantiateviewcontrollerwithidentifier page 1let page one storyboardinstantiateviewcontrollerwithidentifier page 2let page two storyboardinstantiateviewcontrollerwithidentifier page 3let page three storyboardinstantiateviewcontrollerwithidentifier page 4walkthroughdelegate selfwalkthroughaddviewcontrollerpage zerowalkthroughaddviewcontrollerpage onewalkthroughaddviewcontrollerpage twowalkthroughaddviewcontrollerpage threverything works as intended so no problem here on the viewcontroller page three i have a button which redirect me to an other view controller using a custom segue animationclass sentseguefromright uistoryboardsegue override func perform let src selfsource as uiviewcontroller let dst selfdestination as uiviewcontroller srcviewsuperviewinsertsubviewdstview abovesubview srcview dstviewtransform cgaffinetransformtranslationx srcviewframesizewidth y 0 uiviewanimatewithduration 025 delay 00 options uiviewanimationoptionscurveeaseinout animations dstviewtransform cgaffinetransformtranslationx 0 y 0 completion finished in srcpresentdst animated false completion nil now the problem is if i use the same code on a normal viewcontroller the button and the animation work without issues the problem is when i use the segue defined above from the last slide of my bwwalkthrough the first time i tapp the button the viewcontroller which should appear does appear but without the corresponding animation after closing it and taping on the button again the animation is played but an error is returnedpresenting view controllers on detached view controllers is thiscouragedif i use the button with the standard animation without using my custom animation code i get no error and the default animation is played i cannot seem to find a solution to this problem does anybody stumbled upon something like this,['ios'] +1249431,logwtf vs unhandled exception i just learned about logwtf what a terrible failure lol and i am wondering when i should use itwhat is the difference between calling logwtf with an exception and letting an exception go unhandled crashhow does it affect crash reports in the google play developer consolei usually throw an illegalstateexception for unexpected conditions should i consider calling logwtf insteadeditsee also under what circumstances will androids logwtf terminate my app,['android'] +1249637,how to use the pos argument in networkx to create a flowchartstyle graph python 3 i am trying create a linear network graph using python preferably with matplotlib and networkx although would be interested in bokeh similar in concept to the one below how can this graph plot be constructed efficiently pos in python using networkx i want to use this for more complicated examples so i feel that hard coding the positions for this simple example would not be useful does networkx have a solution to this pos dictionary optional a a dictionary with nodes as keys and positions as values if not specified a spring layout positioning will be computed see networkxlayout for functions that compute node positions i have not seen any tutorials on how this can be achieved in networkx which is why i believe this question will be a reliable resource for the community i have extensively gone through the networkx tutorials and nothing like this is on there the layouts for networkx would make this type of network impossible to interpret without careful use of the pos argument which i believe is my only option none of the precomputed layouts on the documentation seem to handle this type of network structure well simple examplea every outer key is the iteration in the graph moving from left to the right eg iteration 0 represents samples iteration 1 has groups 1 3 same with iteration 2 iteration 3 has groups 1 2 etc b the inner dictionary contains the current grouping at that particular iteration and the weights for the previous groups merging that represent the current group eg iteration 3 has group 1 and group 2 and for iteration 4 all of iteration 3s group 2 has gone into iteration 4s group 2 but iteration 3s group 1 has been split up the weights always sum to 1 my code for the connections w weights for the plot aboved iter current previous 1 group 1sample 005 sample 105 sample 20 sample 30 sample 40 group 2sample 00 sample 10 sample 21 sample 30 sample 40 group 3sample 00 sample 10 sample 20 sample 305 sample 405 2 group 1group 11 group 20 group 30 group 2group 10 group 21 group 30 group 3group 10 group 20 group 31 3 group 1group 1025 group 20 group 3075 group 2group 1025 group 2075 group 30 4 group 1group 11 group 20 group 2group 1025 group 2075 this is what happened when i made the graph in networkximport networkximport matplotlibpyplot as plt create directed graphg nxdigraph iterate through all connectionsfor iter n d current previous in d iter current previousitems for current group d previous weights in d current previousitems for previous group weight in d previous weightsitems if weight 0 define connections using as a delimiter for the names previous node d siter and 1 previous group current node d siter n current group connection previous node current node gadd edgeconnection weightweight draw graph with labels and width thicknessnxdrawg with labelstrue widthguvweight for uv in gedgesnote the only other way i could think of to do this would be in matplotlib creating a scatter plot with every tick representing a iteration 5 including the initial samples then connecting the points to each other with different weights this would be some pretty messy code especially trying to line up the edges of the markers w the connectionshowever i am not sure if this and networkx is the best way to do it or if there is a tool eg bokeh or plotly that is designed for this type of plotting,['python'] +1249850,when jumping over a declaration why is trivial destructor required goto or switch can jump over a declarationstatement given that it has no initializer and the construction is trivial a and that the object is also trivially destructiblewhats the rationale for the constraint on the destructorstruct trivial trivial default trivial defaultstruct semi trivial semi trivial default semi trivial noexcept do something void foo goto good label ok trivial foogood label goto bad label error this goto statement semi trivial bar cannot jump over this declarationbad label stdcout hin,['c++'] +1249985,how to force error branch in jasminenode test i am testing the controller logic behind api endpoints in my node server with jasminenode here is what this controller logic typically looks likevar getsummary functionreq res var playerid reqparamsplayerid dbplayersgetaccountsummaryplayerid functionerr summary if err loggerwarnerror while retrieving summary for player d playerid err return resstatus500json message errmessage error while retrieving summary success false else resjsonsuccess true summary summary below is how i successfully test the else blockdescribeget apiplayersplayeridsummary function itshould return an object summarizing the player account functiondone request getapiplayers playerid summary setcontenttype applicationjson setcookie cookie expect200 expectcontenttype json endfunctionerr res expecterrtobenullerr errmessage null expectresbodysuccesstobetrue expectresbodysummarytobedefined done this works nicely but leaves me with poor branch coverage as the if block is never tested my question is how do i force the error block to run in a test can i mock a response which is set to return an error so that i can test the correct warning is logged and correct data is passed back,['javascript'] +1250356,with client request entity processing set to chunked i lose documents i have a rest web service that runs on jetty i want to write a java client that chunks along a huge batch of documents to that rest service using the same web connectioni was able to establish an iterator based streaming approach heresending a stream of documents to a jersey post endpointthis does not work unless you set clientconfigpropertyclientpropertiesrequest entity processing requestentityprocessingchunked because the contentlength is unknownwhile somewhat working the chunked transfer seems to lose a few documents for examplenum docs 50numfound 499249maybe it is sending chunks likesomedoc somedoc somedoc somedoc somedoc somedoc somedoso i am losing some each time at the ends update i was wrong about thishow do i make it not do that any ideas what else might be happening clientconfig clientconfig new clientconfig clientconfigpropertyclientpropertiesconnect timeout inttimeunitsecondstomillis60 clientconfigpropertyclientpropertiesrequest entity processing requestentityprocessingchunked clientconfigpropertyclientpropertiesasync threadpool size 100 clientconfigpropertyapacheclientpropertiesconnection manager httpclientfactorycreateconnectionmanagername metricregistry configuration apacheconnectorprovider connector new apacheconnectorprovider clientconfigconnectorproviderconnector clientconfigregisternew clientrequestfilter override public void filterclientrequestcontext requestcontext throws ioexception listobject orig requestcontextgetheadersremovehttpheaderscontent length if orig null origisempty requestcontextgetheadersaddalength orig clientconfigregisternew clientrequestfilter override public void filterclientrequestcontext requestcontext throws ioexception if requestcontextgetmediatype null requestcontextgetmediatypegettype null requestcontextgetmediatypegettypeequalsignorecasemultipart final mediatype boundarymediatype boundaryaddboundaryrequestcontextgetmediatype if boundarymediatype requestcontextgetmediatype requestcontextgetheadersputsinglehttpheaderscontent type boundarymediatypetostring if requestcontextgetheaderscontainskeymimeversion requestcontextgetheadersputsinglemimeversion 10,['java'] +1250471,appcelerator 4 cannot find android sdk on mac appcelerator studio 471201609100950 on mac os x cannot find android sdk i have downloaded it with the button on the appcelerator studio dashboard after download was successfully finished the appcelerator studio was not able to recognise it i was getting the following error android sdk home no android sdks were found under the specified sdk location,['android'] +1250711,swift 3 weird crashes type inference i could not find a more appropriate title for this this is the scenariofinal class something uiviewcontroller fileprivate var tableview uitableview override func viewdidload superviewdidload selftableview uitableviewframe cgrectzero style plain selftableviewtranslatesautoresizingmaskintoconstraints false delegate register cell selfviewaddsubviewselftableview let views string any table selftableview this line now will crash selfviewaddconstraintsnslayoutconstraintconstraintswithvisualformat 0table0 options metrics nil views views selfviewaddconstraintsnslayoutconstraintconstraintswithvisualformat v0table0 options metrics nil views views edit if you do not put an explicit type annotation the compiler will infer string uitableview in this particular casenow if i do not explicitly let the compiler know that views are of type string any like the commented out thingie this code crashes and i get a neat little crash giving me a middle finger along with this message swiftvalue nsli superitem unrecognized selector sent to instance 0x6044a560things like this are happening all over the place after migrating from swift 2x can someone please shed some light on the subject why is this happening how to avoid things like this how do thiscover origins of such crashes some are very hard to track down,['ios'] +1250781,fieldset child with height 100 is too big i am trying to stretch a fieldset child to 100 but the child ul is too big and some overflow appears is cut in my case how can i stretch the fieldset child to 100 but without overflowfieldset height 300px overflow hiddenul thisplay flex flexdirection column height 100 justifycontent spacearound backgroundcolor fbbfieldset legendhow to stretch childlegend ul liitem 1li liitem 2li liitem 3li liitem 4li liitem 5li liitem 6li liitem 7li liitem 8li ulfieldsetjust in case here is also external fiddle example in fiddleeditedsetting height to specific pixel is necessary i get form layout design through websocket from c windows application every component is position absolute with exact same properties as in c application that means left top width and height,"['html', 'css']" +1250791,jquery navbar hover did not show i am building simple web template from scratchi use old style jquery to make a hover on navbar to show list li but it is working only on about us column and is not working on product columnwhat is wrong how should i do ithtml pagedoctype htmlhtmlhead meta charsetutf8 titletemplatetitle meta nameviewport contentwidthdevicewidth script srcphp echo base urljsjquery300minjsscript link relstylesheet typetextcss hrefphp echo base urlcstylecss script documentreadyfunction nav ol lihoverfunction olthisshow when onmouseover ol a1a nav ol li a a a a a a1a a a a function when mouseout olthishide scriptheadbody div idwrapper div classtoptext span stylemarginleft 85php echo anchorlogina1a a1a 2a aa 1a1a a a a span span stylefloatrightphp echo anchorregisterindexa aa a a a a aa a 2a a a span div div idheader h1pph1 div div idnav ol lia hrefphp echo base urlindexphphomehomeali lia hrefabout usa ol lia hrefa a a a a a a ali lia hrefxali lia hrefxali ol lia hrefproductali ol lia hrefxali lia hrefxali lia hrefxali ol lia hrefcontact usali ol div div idcontent div idleftside p1homepagep1 div div idrightside div clasearchbox php echo form opensearch h3 styletextaligncenter a a1a a a 2a aa a a a1a 2 h3 div clasearchbar input typetext size20 clasfield namesearchterm valuesearch input typeimage clasearchbutton namesearch src altsearch div php echo form close div div div classfa fasearchdiv div div idfooterpfooterpdiv divbodycsshtmlbodymargin0pxpadding0pxfontsize1vw bodybackgroundcceefontfamilyverdana wrappermarginautopadding0pxwidth75 toptextmargintop1vhmarginbottom 1vh toptext span apadding3pxcolor0textdecorationnone toptext span ahoverbackground0052cc webkittransition backgroundcolor 03s easeout moztransition backgroundcolor 03s easeout otransition backgroundcolor 03s easeout transition backgroundcolor 03s easeout colorwhite headermargin0pxpadding0pxwidth100height18vhfloatleft background 99d6ff backgroundimage url onepiecethousandstrommainjpg fallback backgroundimage url onepiecethousandstrommainjpg lineargradient99d6ff 006bb3 w3c backgroundblendmode multiply header h1margin0pxpadding0pxborderbottom1px solid efontsize20pxpaddingbottom10px navmargin0pxpadding0pxwidth100floatleft background 80ffe5 for browsers that do not support gradients background webkitlineargradient80ffe5 00b38f for safari 51 to 60 background olineargradient80ffe5 00b38f for opera 1 to 120 background mozlineargradient80ffe5 00b38f for firefox 36 to 15 background lineargradient80ffe500b38f standard syntax nav olliststylenonemargin0pxpadding0px nav ol lithisplayblockpadding6px 10pxfloatleftpositionrelative nav ol athisplayblockpadding5px 10pxcolor0textdecorationnone nav ol ahoverbackgroundf2f2f2 webkittransition backgroundcolor 03s easeout moztransition backgroundcolor 03s easeout otransition backgroundcolor 03s easeout transition backgroundcolor 03s easeout nav ol olpositionabsolutetop35pxleft0pxthisplaynone background 80ffe5 for browsers that do not support gradients background webkitlineargradient80ffe5 00b38f for safari 51 to 60 background olineargradient80ffe5 00b38f for opera 1 to 120 background mozlineargradient80ffe5 00b38f for firefox 36 to 15 background lineargradient80ffe500b38f standard syntax nav ol ol liborderbottom1px contentfloatleftmargintop2vhpadding0pxwidth100thisplayflexminheight70vhwordbreak breakall rightsidefloatleftmarginleft2vhwidth30border solid 1px greybackgroundwhite rightside olliststylenone leftsidefloatleftwidth70border solid 1px greybackgroundwhite footerfloatleftmargintop2vhpadding2vhwidth100 webkitboxsizingborderbox mozboxsizingborderbox boxsizingborderbox background 99d6ff for browsers that do not support gradients background webkitlineargradient99d6ff 006bb3 for safari 51 to 60 background olineargradient99d6ff 006bb3 for opera 1 to 120 background mozlineargradient99d6ff 006bb3 for firefox 36 to 15 background lineargradient99d6ff006bb3 standard syntax searchbox background 9ff margin 10px margintop20px padding 5px borderradius 5px loginbox background 9ff margin 10px margintop20px padding 5px borderradius 5px width 40 loginbox ul li liststylenone marginleft10px searchbar height 29px backgroundcolor e1e1e1 mozborderradius 100px webkitborderradius 100px borderradius 100px marginleft20px marginright20px marginbottom10px width230 positionrelative searchbar searchbutton positionabsolute top23 right5px sfield float left margin 5px 0 0 8px font 8pt verdana color 8 height 20px lineheight 18px padding 0 background transparent border 0 maxwidth 100px,"['javascript', 'jquery', 'html', 'css']" +1251020,optimizing the use of arguments inside a function in an interview test for the following code void getpositiondummyclass a dummyclass b a getorigin b a getaxistoforward thistancethe interviewer wrote the following comment if you return value using out argument then do not use the arguments inside the function the compiler will generally write the variables to memory and read it right back from memory use a local stack variable this allows the compiler to optimize better and only write the data to memory when absolutely neededi never heard about the fact that i should avoid using reference parameters inside the function is that a common practice when doing c or some really specific optimization and if so is there some specific documentation that i could read that would cover that case,['c++'] +1251163,jaxws slow on appengine i am working on a client app which communicated with the third party api though soap the app runs fine on my local machine but becomes slow by 10x on uploading to appengine on further investigation it was found that its the underlying jaxws used by the client library which is causing the slow downone important thing was on increasing the number of instances the performance increases significantly but in that case the instance consumes more resourcesi cannot find any solution to this problem any guidance would be helpfulps the client library i am using is this,['java'] +1251423,how can i write a c function that takes either an int or a float i want to create a function in c that extends python that can take inputs of either float or int type so basically i want f5 and f55 to be acceptable inputsi do not think i can use if pyarg parsetupleargs i value because it only takes only int or only floathow can i make my function allow inputs that are either ints or floatsi am wondering if i should just take the input and put it into a pyobject and somehow take the type of the pyobject is that the right approach,"['python', 'c']" +1251637,stop setting up several avaudioplayers with playattime in a for loop when selecting a row the following code sets up a set of avaudioplayers to playback at a certain date in this case 50 players playing in the interval of 1 secondsince i want the whole process to restart when touching again i need to break the setup in the for loop since it takes a few seconds to setup the playersapart from that each player is being removed after finishing playback using the audiodidfinishplaying delegate method of avaudioplayerdelegate i did not include this in the code since it is not relevant to the questioni have tried using a flag inside the for loop to check whether setup is allowed but that does not workvar players avaudioplayer var loaderror nserroroverride func tableviewtableview uitableview cellforrowatindexpath indexpath nsindexpath uitableviewcell removes the players that have been setup already playersremoveall the for loop from the previous row selection should be stopped here for i in 050 do let player try avaudioplayercontentsofurl soundurlsi players player the process of setting these up takes a few seconds i need to break it printfiring timer playerplayattimeplayerdevicecurrenttime nstimeintervali catch let error as nserror loaderror error what happens is that the setup triggered by the previous row selection will continue until it is finished and only then the new for loop startsi need to break it earlieri cannot figure out how to tackle this maybe by removing the processes from the main threadhow any help much appreciated,['ios'] +1251734,android studio 22 and jack are getting blocked by avira antivirus so i update my project to use the new jack compiler but for some unknown reason my antivir blocks the task transformclasseswithprejackpackagedlibrariesfordebugit works if i thisable antivir realtime protection i really do not want to do that and i do not want to start putting my android project in the exception listi am using android studio 22 and this is my buildgradleandroid compilesdkversion 24 buildtoolsversion 2402 defaultconfig minsdkversion 21 targetsdkversion 24 testinstrumentationrunner androidsupporttestrunnerandroidjunitrunner jackoptions enabled true compileoptions sourcecompatibility javaversionversion 1 8 targetcompatibility javaversionversion 1 8 my projectgradlebuildscript dependencies classpath comandroidtoolsbuildgradle220 and the error when i try to run the app on my hardware deviceerrorexecution failed for task apptransformclasseswithprejackpackagedlibrariesfordebug failed to delete temporary file cusersuserappdatalocaltempjill14755792650830jack,"['java', 'android']" +1253188,most efficient way to determine overlapping timeseries in python i am trying to determine what percentage of the time that two time series overlap using pythons pandas library the data is nonsynchronous so the times for each data point do not line up here is an exampletime series 120161005 1150020734 05020161005 115003033 02520161005 115010479 05020161005 1150150234 02520161005 1150370199 05020161005 1150490401 05020161005 1150510362 02520161005 1150530424 07520161005 1150530982 02520161005 1150580606 075time series 220161005 1150070537 05020161005 1150110994 05020161005 1150190181 05020161005 1150350578 05020161005 1150460761 05020161005 1150490295 07520161005 1150510835 07520161005 1150550792 02520161005 1150550904 07520161005 11505704 075assuming the series holds its value until the next change what is the most efficient way to determine the percentage of time that they have the same value examplelets calculate the time that these series overlap starting at 1150070537 and ending at 20161005 11505704 075 since we have data for both series for that period time that there is overlap115010479 1150150234 both have a value of 05 49755 seconds1150370199 1150490295 both have a value of 05 12096 seconds1150530424 1150530982 both have a value of 075 0558 seconds1150550792 1150550904 both have a value of 025 0112 secondsthe result 497551209605580112 4907 34one of the issues is my actual timeseries has much more data such as 10 10 observations and i need to run many more pairs i thought about forward filling a series and then simply comparing the rows and dividing the total number of matches over the total number of rows but i do not think this would be very efficient,['python'] +1253577,connecting rounded squares how do i create the div logo as per the attached image belowthis is what i have created in jsfiddlemain issue is how do i connect the two boxes with the shape as below image can anybody please suggestbodyhtml width 100 height 100 margin 0body backgroundcolor efefefwrapper height 40px width 40px position absolute top 50 left 50 margintop 225px marginleft 225pxul liststyletype none margin 0 auto padding 0 width 80px height 80px position relative moztransform rotate45deg mstransform rotate45deg webkittransform rotate45deg transform rotate45degul li width 2em height 2em position absolute animation dance 8ms infinite alternate animationtimingfunction cubicbezier05 0 05 1 moztransform rotate45deg mstransform rotate45deg webkittransform rotate45deg transform rotate45deg animation dance 8ms infinite alternateblock1 top 0 left 0 background 0076aa borderradius 4pxblock2 top 0 right 0 background 98bd81 borderradius 4pxblock3 bottom 0 right 0 background 98bd81 borderradius 4pxblock4 bottom 0 left 0 background 0076aa borderradius 4pxdiv classwrapper ul classblocks li classblock1li li classblock2li li classblock3li li classblock4li uldiv,"['html', 'css']" +1253820,does the java 9 module system support optional dependencies backgroundin maven an artifact can declare a dependency withoptionaltrueoptionalwhich means that the dependency is not required but can be used if presentthe state of the module system seems to specify that a module can only read modules it has requiredquestionsdoes the java 9 module system indeed not support optional dependencieswhy notwhat alternatives to optional dependencies does the java 9 module system provide use casei have a framework that integrates various libraries that may or may not be used by an application currently this framework is a single jar that reflects upon the classpath to skip integration code for absent libraries i guess we could split this into a separate module for each configuration but this would cause a combinatorial explosion in the number of jars because wed not only need a separate jar for each optional dependency but also a separate jar for most pairs of optional dependencies,['java'] +1254396,empty return in nonvoid function is undefined behaviour after reading answers about the topic of control reaches end of nonvoid functions i did not see any answer adressing specifically the the case of exiting a nonvoid function with an empty return statementint return integer return empty return in nonvoid functionwhat i have found so far in the c standard is6864 the return statementconstraintsa return statement with an expression shall not appear in a function whose return type is void a return statement without an expression shall only appear in a function whose return type is voidthe standard quote states what should we do with our return statements for void and nonvoid functions what happens when we ignore the constraint is mentioned in other part of the document691 function definitionsif the that terminates a function is reached and the value of the function call is used by the caller the behavior is undefinedprevious standard quote states that ub happens if we use the returned value from a function which ends after reaching the closing curly braces so we have ub in the code belowint ubint x if x return x printfd ub1 correctprintfd ub0 undefined behaviorin the ub1 call the function returns 1 through the return x instruction under the if x in the ub0 call the if x condition is not passed so function ends reaching to use the return value in this case is ub but is not in ub1 but what happens in this caseint ubint x if x return empty return statementprintfd ub1 undefined behaviorprintfd ub0 undefined behaviorin the code above the call ub1 does not meet the a69112 requirements to lead to ub because the function ends without reaching and also does not return any valuein which part of the c standard is this situation described,['c'] +1254605,nodejs read and download all files in directory from server and save locally i have a node webkit desktop app and need to download files from the server and save locally for when users are offline i can download and save a file when i know what the file name is but how do i read the contents of a directory on the server so i can download each filefunction cachefilesfilelink filepath cb var path array filelinksplit var foldername path arraypath arraylength 2create new folder for locally html filesvar newdir filepath foldernameif fsexistssyncnewdir alertfile already exists cannot cache this file else fsmkdirsyncnewdirdownload and save indexhtml this worksvar indexfile fscreatewritestreamnewdirindexhtmlvar request httpgetfilelink functionresponse responsepipeindexfile indexfileonfinish function indexfileclosecb read contents of data folder this does not workvar datafolder filelinkreplaceindexhtmlfsreaddir datafolder function err datafiles if err consolelogdatafiles else consolelogerr the error i get in my console is enoent no such file or directory scandir cusersmynamedesktopappapphttpwmysitecoukwpcontentuploadswifi corp2datathe above is looking for the files locally and not at the online link i supplied in filelink eg corp2data,['javascript'] +1254742,how to resize webview height based on html content in windows 10 uwp i am currently working on windows 10 uwp app and facing an issue with webview that when i have less html content i am getting more height in javascript my code is as followswebview webview new webview ishittestvisible true string notifyjs script typetextjavascript languagejavascript function setupbrowser documenttouchmovefunctionreturn false documentonmousemovefunctionreturn false documentonselectstartfunctionreturn false documentondragstartfunctionreturn false windowexternalnotifycontentheightdocumentbodyfirstchildoffsetheight windowexternalnotifycontentheightdocumentgetelementbyidpagewrapperoffsetheight var links documentgetelementsbytagnamea forvar i0ilinkslengthi linksionclick function windowexternalnotifythishref return false script string htmlcontent if hexcolor null htmlcontent stringformathtmlhead0head body onloadsetupbrowser stylemargin0pxpadding0pxbackgroundcolor2 div idpagewrapper stylewidth100wordwrapbreakwordpadding0px 25px 0px 25px1divbodyhtml notifyjs formitemi default value hexcolor here formitemi default value ishtml without htmlhead and body tags and its value is pspan stylefontsize 14pxto help us investigate your query please can you make a sheet using the followingnbspspana href stylefontsize 14px target blankdocumentaspan stylefontsize 14pxspanppstrongspan stylefontsize 14pxtesting webview heightspanstrongphexcolor is background color that needs to be applied and my script notify method is as followswebviewscriptnotify async sender e if evaluestartswithcontentheight sender as webviewheight converttodoubleevaluesplit1 return if stringisnulloremptyevalue string href evaluetolower if hrefstartswithmailto launcheroptions options new launcheroptions optionsthisplayapplicationpicker true optionstreatasuntrusted true var success await launcherlaunchuriasyncnew urievalue options else if hrefstartswithtel launcheroptions options new launcheroptions optionsthisplayapplicationpicker true optionstreatasuntrusted true var success await launcherlaunchuriasyncnew urievalue options else launcheroptions options new launcheroptions optionsthisplayapplicationpicker true optionstreatasuntrusted true var success await launcherlaunchuriasyncnew urievalue options can someone suggest why i am getting very large height even if content is small,"['javascript', 'c#']" +1254759,how to add voiceover accessibility to an apps icon badge number questionhow do i add a custom voiceover accessibility label or hint to an app icon badge number a a a a a a a a a a a a a a a a a a a a for example when the ios setting accessibility voiceover is turned on voiceover reads aloud items touched on screen for the app store and mail icons the following is read out aloudapp store icon voiceover says app store 2 updates available double tap to openmail icon voiceover says mail 1 unread message double tap to openbut for the project i am working on the voiceover read out is generic and not entirely helpfulmy app icon voiceover says my app 123 new items double tap to openthe phrase new items is too vague not accurate and i am certain there must be a way to change this with a custom string to make it read better through setting an accessibilitylabel accessibilityhint or something similarbut how exactly in swift codemany thanksadditional observationusing the simulator accessibility inspector it appears the voiceover values come from label my app and value 123 new items so updated in the code i have tried setting the accessibilityvalue to something custom 123 custom description but still no luck voiceover continues to read my app 123 new items double tap to openwhy is not voiceover reading the custom badge value as expectedcodethe below method adds a red circle app icon badge number to my apps iconimport uikitclass viewcontroller uiviewcontroller override func viewdidload superviewdidload let badgecount int 123 let application uiapplicationsharedapplication if availableios 80 ios 8 ios 9 ios 10 applicationregisterusernotificationsettingsuiusernotificationsettingsfortypes badge categories nil else ios 7 applicationapplicationiconbadgenumber badgecount applicationaccessibilityvalue 123 custom description,['ios'] +1254885,how can i filter columns rather than rows in epplus filtering rows in a particular column are easy as pie in epplusprivate excelworksheet produsageworksheet produsageworksheetcellsa6a6autofilter truethis allows me to filter the rows in column ai also need to filter certain columns out such as the month columns in the screenshot sep 15 and oct 15 but are usually several more for example i want to generate the following programmatically with epplusdeselecting select all selecting a subset of months and then the ok button makes the ones not selected collapse looking at some legacy excel interop code it would seem that is done this way therefld pivotfield pvtpivotfieldsmonthfldorientation xlpivotfieldorientationxlcolumnfieldfldnumberformat m yyspecifically the second block of code with the orientation set to xlcolumnfield is the column that sports the sortfilter button that when manipulated conditionally showshides various columnsdoes it determine which columns are showablehideable based on the number format that is to say if the value is sep 15 or oct 16 i do not know but i cannot see anything else in the code that is more specifically setting the limits of the column filteringat any rate if this is how excel interop accomplishes it what is the equivalent in epplus,['c#'] +1255445,how to implement an abstract method when abstract class is used in a variadic context how to implement in the following code the abstract base class in a generic case the code is simplified from a library i am working on so an explicit implementation for int and double is not an option template typename tstruct foo virtual void sendt t 0template typenametstruct bar foot void sendt t override does not compile because abstract method not implemented int main example usage barint double b bsend1 bsend23many thanks in advanceedit added virtual to abstract method,['c++'] +1255643,add another timer on already running loop given the following program include iostreaminclude uvhint main uv loop t loop uv loop initloop stdcout libuv version uv version major uv version minor stdendl int r 0 uv timer t t1 handle r uv timer initloop t1 handle uv timer startt1 handle uv timer t t stdcout timer1 calledn 0 20 uv runloop uv run default second timer uv timer t t2 handle r uv timer initloop t2 handle uv timer startt2 handle uv timer t t stdcout timer2 calledn 0 10 uv loop closeloopthe second timer handle is never run on the loop since the loop is already running and timer2 called is never printed so i tried stopping the loop temporarily after running it and then adding the second timer uv runloop uv run default some workuv stoploop now add second timeruv runloop uv run default run againbut this again did not work probably because the later lines would not be executed after 1st loop starts running with an repeating timer so how should i add a new timer handle to already running uvloop,['c++'] +1255755,c text file with matrix divide all entries i have a text file with a 1122 x 1122 matrix of precipitation measurementseach measurement is represented with 4 decimal digitsexample lines look like this00234 023 00123 03223 01234 032 01236 0 and this 1122 values long and 1122 lines downi need this same text file but with all values divided by 6and i have to do this for 920 files like thati managed to do this but in a no doubt atrociously ineffective and memory exhaustive wayi open the textfiles one by one and read each text file line by linei split each line into a string array with the separate values as membersi go through the array converting each value to double divide by 6 and convert the result back to string formatted with 4 decimal digits and store as member in a new string arrayi join the array back to a linei write this line to a new text filevoila after an hour or so i have my 920 new text filesi am sure there is a much faster and professional way to do this i have looked at endless sites about matrixdivide but do not see or understand a solution there for this problemany help will be appreciatedthis is a code snippet as used for each file foreach string inputline in inputfile int count 0 string str precip inputlinesplit holds string measurements string str divided precip new stringstr preciplength will hold string measurements divided by divider 6 foreach string measurements in str precip str divided precipcount converttodoublemeasurements 6tostringf4 cultureinfocreatespecificcultureenus count string divline stringjoin str divided precip using systemiostreamwriter newfile new systemiostreamwriterasc filesdivfiletxt true newfilewritelinedivline,['c#'] +1255937,eleminating left recursion in parser rule of spirit x3 i am currently stuck with a rule i am trying to parse using boost spirit x3here is te ebnfusing the operator from spirit for lists for what i am trying to parsetype class type lambda typelambda type more arg lambda one arg lambdamore arg lambda type typeone arg lambda type type here is the left recursionclass type identifier type usng boost spirit x3 i am trying to parse into the following structvarianttypedef x3variant nil x3forward astlambdatype x3forward astclasstype typestruct lambdatype stdvectortype parameters type return type struct classtype stdvectorstdstring name stdvectortype template args i have a live example of what i am currently trying here which is not working i also tried to change the order of the variant parser wich doesnt help i get endless recusion or not the behaviour i would expector wishcan anybody help me debugging this parser i think i have some type of leftrecursion in the parser is there a chance to avoid this or is there no chance to rewrite the grammaris this gramar even parsable with boost spirit x3editi managed to eleminate the left recursion in this grammarnow te grammar is the followingtype class type lambda type lambda type more arg lambda one arg lambda more arg lambda type type one arg lambda class type type a type type type a class type identifier type a type a epsbut now there is the next problem how can i make boost spirit x3 to parse these rules into the given structs i cannot imagine what the a or the one arg lambda parsers are returning now the one arg lambda parser should parse into a lambdatype struct but depending on what a parses into thats not necessary true now so the question is now how can i get a nonleft recursive parser which parses the grammar above into my structs using boostspiritx3edit i would like to be right associative so foo bar baz bahammeans foo bar baz bahama,['c++'] +1256569,is using single as an assert a bad practice i am testing a method that manipulates a collection given a set of parameters it should contain exactly one element that matches a condition edit the collection might have several other elements not matching the condition aswelli am using single to test that behaviour which works fine as it will fail the test by throwing an exception if there is no match at all or more than one match but there is no actual assert which somehow violates arrange act assert so i am wondering if this is a bad practice and if there is a better way to do thisfollowing pseudo code to demonstrate my question testmethodpublic void testmethod list list methodtotestparam1 param2 listsingles smatchescondition no actual assert,['c#'] +1256873,make an object that behaves like a slice how can we make a class represent itself as a slice when appropriatethis did not workclass mythingobject def init self start stop otherstuff selfstart start selfstop stop selfotherstuff otherstuff def index self return sliceselfstart selfstopexpected output thing mything1 3 potato hello worldthingelactual outputtypeerror index returned nonintlong type sliceinheriting from slice does not work either,['python'] +1256924,how does a java if statement work when it has an assignment and an equality check or d together why does this if statement with an assignment and equality check evaluate to falsepublic static void test boolean test1 true if test1 false test1 false systemoutprintlnyes else systemoutprintlnno why is this printing no,['java'] +1256972,button of a fragment inside viewpager trigger onclicklistener on wrong reference sorry about my dumb title i will describe it clearly belowsituationi have a viewpager with 4 onboardingfragments inside each fragment have exactly same layout which was inflatedfrom same xml file this layout contain a button which i called btnnext and i set the onclicklistener for itfunction getitem of my pageradapteroverridepublic fragment getitemint position string title description button int resource boolean end false switch position case 0 title contextgetstringrstringon boarding title 1 description contextgetstringrstringon boarding description 1 resource rdrawableon boarding bg 0 button contextgetstringrstringon boarding button 1 break case 1 title contextgetstringrstringon boarding title 2 description contextgetstringrstringon boarding description 2 resource rdrawableon boarding bg 1 button contextgetstringrstringon boarding button 2 break case 2 title contextgetstringrstringon boarding title 3 description contextgetstringrstringon boarding description 3 resource rdrawableon boarding bg 2 button contextgetstringrstringon boarding button 3 break default title contextgetstringrstringon boarding title 4 description contextgetstringrstringon boarding description 4 resource rdrawableon boarding bg 3 button contextgetstringrstringon boarding button 4 end true return onboardingfragmentnewinstancetitle description resource button endoverridepublic int getcount return 4functions of onboardingfragmentpublic static onboardingfragment newinstancestring title string description int resource string button boolean end bundle bundle new bundle bundleputstringextra title title bundleputstringextra description description bundleputintextra image resource bundleputstringextra button button bundleputbooleanextra end end onboardingfragment fragment new onboardingfragment fragmentsetargumentsbundle return fragmentoverridepublic void oncreatenullable bundle savedinstancestate superoncreatesavedinstancestate bundle bundle getarguments if bundle null title bundlegetstringextra title description bundlegetstringextra description button bundlegetstringextra button end bundlegetbooleanextra end imageresource bundlegetintextra image show log logethistostring end title nullableoverridepublic view oncreateviewlayoutinflater inflater nullable viewgroup container nullable bundle savedinstancestate view rootview inflaterinflaterlayouton boarding fragment container false textview tvtitle textview rootviewfindviewbyidridtv title textview tvdescription textview rootviewfindviewbyidridtv description textview btnthiscovery textview rootviewfindviewbyidridtv thiscovery imageview imageview rootviewfindviewbyidridiv image final button btnnext button rootviewfindviewbyidridbtn next if end btnthiscoverysetvisibilityviewvisible btnthiscoverysetonclicklistenernew viewonclicklistener override public void onclickview v startregionactivity btnnextsettextbutton btnnextsetonclicklistenernew viewonclicklistener override public void onclickview v show log logeonboardingfragmentthistostring end title buttonvgettext if end splashactivity getactivitygotonextpage else startloginactivity tvtitlesettexttitle tvdescriptionsettextdescription imageutilsloadbitmapgetactivity imageresource imageview 08f new imageutilsloadbitmapcallback override public void onloadcompleteimageview imageview override public void onloadfail return rootviewthe problem iswhen my app started it show the first fragment then i pressed the button and trigger onitemclick method and the method was referenced to the last fragmentlog when create fragmentonboardingfragmenta8ede47 id0x7f10013bfalsexin chaoonboardingfragment8787674 0 id0x7f10013bfalseban lian tay kiao34m tian ngayonboardingfragment119f79d 1 id0x7f10013bfalsechat mian phaonboardingfragment1ee7412 2 id0x7f10013btrueng ai thaot hang thaotlog when onclicklistener was triggeredonboardingfragment1ee7412 2 id0x7f10013btrueng ai thaot hang thaotai cha ngay na olog when the btnnext was initializedbutton androidsupportv7widgetappcompatbutton17c69e97 vfedc i 0 7f1002c8 appidbtn nextbutton androidsupportv7widgetappcompatbutton31941c vfedc i 0 7f1002c8 appidbtn nextbutton androidsupportv7widgetappcompatbutton30765b87 vfedc i 0 7f1002c8 appidbtn nextbutton androidsupportv7widgetappcompatbutton9cf19e vfedc i 0 7f1002c8 appidbtn nextquestionwhy it happen and how to resolve,['android'] +1257356,how to achieve test isolation with symfony forms and data transformers note this is symfony 26 but i believe the same overall issue applies regardless of versionto start consider this form type that is designed to represent oneormore entities as a hidden field namespace stuff omitted for brevityclass hiddenentitytype extends abstracttype var entitymanager protected em public function constructentitymanager em thisem em public function buildformformbuilderinterface builder array options if optionsmultiple builderaddviewtransformer new entitiestoprimarykeystransformer thisemgetrepositoryoptionsclass optionsget pk callback optionsidentifier else builderaddviewtransformer new entitytoprimarykeytransformer thisemgetrepositoryoptionsclass optionsget pk callback see class docblock for description of options inheritdoc public function setdefaultoptionsoptionsresolverinterface resolver resolversetdefaultsarray get pk callback functionentity return entitygetid multiple false identifier id data class null resolversetrequiredarrayclass public function getname return hidden entity inheritdoc public function getparent return hidden this works it is straightforward and for the most part looks like like all the examples you see for adding data transformers to a form type until you get to unit testing see the problem the transformers cannot be mocked but wait you say unit tests for symfony forms are integration tests they are supposed to make sure the transformers do not fail even says so in the documentationthis test checks that none of your data transformers used by the form failed the issynchronized method is only set to false if a data transformer throws an exceptionok so then you live with the fact you cannot isolate the transformers no big deal now consider what happens when unit testing a form that has a field of this type assume that hiddenentitytype has been defined tagged in the service containerclass someotherformtype extends abstracttype public function buildformformbuilderinterface builder array options builder addfield hidden entity array class appbundleentityname multiple true now enters the problem the unit test for someotherformtype now needs to implement getextensions in order for the hidden entity type to function so how does that lookprotected function getextensions mockentitymanager this getmockbuilderdoctrineormentitymanager thisableoriginalconstructor getmock expectations go here return array new preloadedextension arrayhidden entity new hiddenentitytypemockentitymanager array see where that comment is in the middle yeah so for this to work correctly all of the mocks and expectations that are in the unit test class for the hiddenentitytype now effectively need to be duplicated here i am not ok with this so what are my optionsinject the transformer as one of the optionsthis would be very straightforward and would make mocking simpler but ultimately just kicks the can down the road because in this scenario new entitytoprimarykeytransformer would just move from one form type class to another not to mention that i feel form types should hide their internal complexity from the rest of the system this option means pushing that complexity outside the boundary of the form typeinject a transformer factory of sorts into the form typethis is a more typical approach to removing newables from within a method but i cannot shake the feeling that this is being done just to make the code testable and is not actually making the code better but if that was done it would look something like thisclass hiddenentitytype extends abstracttype var datatransformerfactory protected transformerfactory public function constructdatatransformerfactory transformerfactory thistransformerfactory transformerfactory public function buildformformbuilderinterface builder array options builderaddviewtransformer thistransformerfactorycreatetransfomerfortypethis options rest of type unchanged this feels ok until i consider what the factory will actually look like it will need the entity manager injected for starters but what then if i look further down the road this supposedlygeneric factory could need all sorts of dependencies for creating data transformers of different kinds that is clearly not a good longterm design decision so then what relabel this as an entitymanagerawaredatatransformerfactory it is starting to feel messy in herestuff i am not thinking ofthoughts experiences solid advice,['php'] +1257677,how to hide navbar when when overlay appears using code from w3schools sidenav overlay i am trying to create the same effect in bootstrap i have the navbartoggle floating left and the navbartoggle still shows when the overlay moves right not sure how to hide the navbartoggle when the overlay appears first post thankscss navbar webkitboxshadow 0px 2px 3px rgba100 100 100 049 mozboxshadow 0px 2px 3px rgba100 100 100 049 boxshadow 0px 2px 3px rgba100 100 100 049 backgroundcolor white padding 5pxnavbarbrand position absolute width 100 left 0 top 5px textalign center margin autonavbartoggle zindex3 border none cursor pointer float leftnavbartoggle ahover border none backgroundcolor none cursor pointer the side navigation menu sidenav height 100 100 fullheight width 0 0 width change this with javascript position fixed stay in place zindex 1 stay on top top 0 left 0 backgroundcolor 1 black overflowx hidden thisable horizontal scroll paddingtop 60px place content 60px from the top transition 05s 05 second transition effect to slide in the sidenav the navigation menu links sidenav a padding 8px 8px 8px 32px textdecoration none fontsize 25px color 818181 thisplay block transition 03s when you mouse over the navigation links change their color sidenav ahover offcanvas afocus color f1f1f1 position and style the close button top right corner sidenav closebtn position absolute top 0 right 25px fontsize 36px marginleft 50px style page content use this if you want to push the page content to the right when you open the side navigation main transition marginleft 5s padding 20px on smaller screens where height is less than 450px change the style of the sidenav less padding and a smaller font size media screen and maxheight 450px sidenav paddingtop 15px sidenav a fontsize 18pxhtmlheader div classnavbar navbardefault navbarfixedtop rolenavigation idslidenav div classcontainer div classnavbarheader a classnavbartoggle onclickopennav span clasronly toggle navigationspan span classiconbarspan span classiconbarspan span classiconbarspan a a classnavbarbrand hreftest nava div idmysidenav clasidenav a hrefjavascriptvoid0 classclosebtn onclickclosenavtimesa a hrefabouta a hrefservicesa a hrefclientsa a hrefcontacta div div div div headerjavascript set the width of the side navigation to 250px function opennav documentgetelementbyidmysidenavstylewidth 250px set the width of the side navigation to 0 function closenav documentgetelementbyidmysidenavstylewidth 0,"['javascript', 'html', 'css']" +1260719,why can yield be indexed i thought i could make my python 2710 code simpler by directly accessing the index of a value passed to a generator via send and was surprised the code ran i then thiscovered an index applied to yield does not really do anything nor does it throw an exceptiondef gen1 t yield0 assert t yield falseg gen1nextggsendchar strhowever if i try to index yield thrice or more i get an exceptiondef gen1 t yield0 assert t yield falseg gen1nextggsendchar strwhich throwstypeerror int object has no attribute getitem this was unusually inconsistent behavior and i was wondering if there is an intuitive explanation for what indexing yield is actually doing,['python'] +1261621,inherited constructors default constructor and visibility as stated by namespaceudecl18 a usingdeclaration that names a constructor does not create a synonym instead the additional constructors are accessible if they would be accessible when used to construct an object of the corresponding base class and the accessibility of the usingdeclaration is ignored because of that the following code does not compileclass b protected bint class d b using bb int main d d0 it returns an error that is more or less the same with all the major compilersdeclared protected hereon the other side the following code compilesclass b protected b class d b using bb int main d d should not it fail to compile instead for the same reasons that lead to an error in the previous examplewhat does it allow it to compile,['c++'] +1262332,if multiple classes have a static variable in common are they shared within the same scope i have the following example codeclass a public static int aint aa 0class b public static a a1a ba1class c public static a a1a ca1int mainint argc const char argv ca1a ba1a stdcout ba1a ca1a stdendl return 0class b and c have class a as a static member variablei expected the program to print 1 1 however it prints 2 2if multiple classes have a static variable in common are they shared within the same scope,['c++'] +1262668,using lambda in default initializer gcc vs clang include cassertint main struct point of parabaloid double x y double z return x x y y point of parabaloid p 10 20 assertpz 50works fine for clang from trunk but for g from trunk fails with error message linkerror this was not captured for this lambda functiondefinition of point of parabaloid in namespace scope works fine for bothslightly modified definition with this lambda capture works fine also for both in either global or local scopewhich compiler is right,['c++'] +1262834,stl list very bad performance it is supposed that push back and pop front methods of a stl list implemented as a double linked list should be constant o1 however we were having cpu issues in an application running on linux and we found that pop front method is incredibly inefficient when using lists is this a list implementaion issue or is the expected behaviourthis is the example codeclass a public a ma rand mb rand mc rand md rand u32 ma u32 mb u32 mc u32 mddefine deltat1 t0 t1tv sec t0tv sec10 t1tv usec t0tv usec10int mainint argc char argv stdlista l stdqueuea q stddequea dq printfcreating nodes stdvectora v for int i 0 i 10 i a a vpush backa printfokn timeval t0 t1 printfstddeque test push back gettimeofdayt0 null for stdvectoraconst iterator iter vbegin iter vend iter dqpush backiter gettimeofdayt1 null printfdone in d ms size dn deltat1 t0 dqsize printfstddeque test pop front gettimeofdayt0 null while dqsize 0 a a dqfront dqpop front gettimeofdayt1 null printfdone in d ms size dn deltat1 t0 dqsize printfstdqueue test push back gettimeofdayt0 null for stdvectoraconst iterator iter vbegin iter vend iter qpushiter gettimeofdayt1 null printfdone in d ms size dn deltat1 t0 qsize printfstdqueue test pop front gettimeofdayt0 null while qsize 0 a a qfront qpop gettimeofdayt1 null printfdone in d ms size dn deltat1 t0 qsize printfstdlist test push back gettimeofdayt0 null for stdvectoraconst iterator iter vbegin iter vend iter lpush backiter gettimeofdayt1 null printfdone in d ms size dn deltat1 t0 lsize printfstdlist test pop front gettimeofdayt0 null while lsize 0 a a lfront lpop front gettimeofdayt1 null printfdone in d ms size dn deltat1 t0 lsize return 0for different number of nodes we get50 nodesstddeque test push backdone in 0 ms size 50stddeque test pop frontdone in 0 ms size 0stdqueue test push backdone in 0 ms size 50stdqueue test pop frontdone in 0 ms size 0stdlist test push backdone in 0 ms size 50stdlist test pop frontdone in 202 ms size 010 nodesstddeque test push backdone in 0 ms size 10stddeque test pop frontdone in 0 ms size 0stdqueue test push backdone in 0 ms size 10stdqueue test pop frontdone in 0 ms size 0stdlist test push backdone in 1 ms size 10stdlist test pop frontdone in 279 ms size 010 nodesstddeque test push backdone in 5 ms size 10stddeque test pop frontdone in 4 ms size 0stdqueue test push backdone in 3 ms size 10stdqueue test pop frontdone in 4 ms size 0stdlist test push backdone in 12 ms size 10stdlist test pop frontdone in 31148 ms size 0thanksvicente,['c++'] +1262915,how to use a dict to subset a dataframe say i have given a dataframe with most of the columns being categorical data datahead age risk sex smoking0 28 no male no1 58 no female no2 27 no male yes3 26 no male no4 29 yes female yesand i would like to subset this data by a dict of keyvalue pairs for those categorical variablestmp riskno smokingyes sexfemalehence i would like to have the following subsetdata datarisk no datasmoking yes datasex femalewhat i want to do isdatatmpwhat is the most python pandas way of doing thisminimal exampleimport numpy as npimport pandas as pdfrom pandas import series dataframex seriesrandomrandint0250 dtypecategoryxcatcategories no yesy seriesrandomrandint0250 dtypecategoryycatcategories no yesz seriesrandomrandint0250 dtypecategoryzcatcategories male femalea seriesrandomrandint206050 dtypecategorydata dataframeriskx smokingy sexz ageatmp riskno smokingyes sexfemale,['python'] +1263065,is there a way to use itertools in python to clean up nested iterations let us say i have the following codea 123b 246c 357for i in a for j in b for k in c print i j kis there a way i can consolidate an iterator in one line instead of making it nested,['python'] +1263454,why does my result data returned as void gets broken i am working in a project with a huge legacy code base and have been trying to redesign parts of it to get away from old cstyle codei have run into a problem and have prepared a short program to explain the legacy interface i am using needs me to pass a pointer to the result data as void and i would like to avoid having to change thisthe unique ptr in the example just goes to demonstrate that in my real code base everything working on the data is using smart pointers to manage memorymy problem is that the result data gets broken see last output line last call to printpayload everything is 0 at the end but it does not seem to be a problem with converting to the void and back as shown by the 2nd and 3rd output lineis this a problem related to temporariesi do not get iti hope this kind of problem has relevance for some of youinclude iostreaminclude memorystruct payload long a int b int c payload a b c payloadlong seta int setb int setc aseta bsetb csetc void printpayloadconst payload printthis stdcout payload a printthisa b printthisb c printthisc stdendlvoid dosomethingpayload sourcedata void targetdata if sourcedata return stdunique ptrpayload sourcedatauniquesourcedata sourcedatauniquea 2 sourcedatauniqueb 3 sourcedatauniquec 4 printpayloadsourcedataunique targetdata reinterpret castvoidsourcedatauniquerelease printpayloadreinterpret castpayloadtargetdataint mainvoid payload mypayload new payload14 8 1982 payload myresult printpayloadmypayload dosomethingmypayload myresult printpayloadmyresultoutputpayload a 14 b 8 c 1982payload a 2 b 3 c 4payload a 2 b 3 c 4payload a 0 b 0 c 0,['c++'] diff --git a/functions.py b/functions.py new file mode 100644 index 0000000..cfa1625 --- /dev/null +++ b/functions.py @@ -0,0 +1,86 @@ +import torch +import numpy as np +import scipy + +# Define the hyperparameters +num_layers = 2 +batch_size = 32 +hidden_dim = 256 + +def random_rotation(inputs): + angle = np.random.uniform(-180, 180) + inputs = scipy.ndimage.rotate(inputs, angle, reshape=False) + return inputs + +def random_scaling(inputs): + scale = np.random.uniform(0.8, 1.2) + inputs = scipy.ndimage.zoom(inputs, scale) + return inputs + +def random_translation(inputs): + shift = np.random.uniform(-0.2, 0.2) + inputs = scipy.ndimage.shift(inputs, shift) + return inputs + +def random_shearing(inputs): + shear = np.random.uniform(-0.2, 0.2) + inputs = scipy.ndimage.shear(inputs, shear) + return inputs + +def random_flipping(inputs): + inputs = scipy.ndimage.flip(inputs, axis=1) + return inputs + +def data_augmentation(inputs): + # Apply random rotation + inputs = random_rotation(inputs) + # Apply random scaling + inputs = random_scaling(inputs) + # Apply random translation + inputs = random_translation(inputs) + # Apply random shearing + inputs = random_shearing(inputs) + # Apply random flipping + inputs = random_flipping(inputs) + return inputs + +def evaluate(model, test_data, hyperparameters, recurrent_network=False, pre_trained_model=False, fine_tuning=False): + # Use GPU for training if available + device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + + # Define the hidden state + hidden = (torch.zeros(num_layers, batch_size, hidden_dim).to(device), + torch.zeros(num_layers, batch_size, hidden_dim).to(device)) + model.eval() + with torch.no_grad(): + correct = 0 + total = 0 + for data in test_data: + inputs, labels = data + # Use data augmentation + inputs = data_augmentation(inputs) + # Use GPU for training + inputs = inputs.to(device) + labels = labels.to(device) + # Use recurrent network + if recurrent_network: + outputs = model(inputs, hidden) + else: + outputs = model(inputs) + # Use pre-trained model + if pre_trained_model: + outputs = model.forward_from_pretrained(inputs) + # Use fine-tuning + if fine_tuning: + outputs = model.fine_tune(inputs, hyperparameters) + _, predicted = torch.max(outputs.data, 1) + total += labels.size(0) + correct += (predicted == labels).sum().item() + accuracy = 100 * correct / total + return accuracy + +def adjust_learning_rate(optimizer, epoch): + """Sets the learning rate to the initial LR decayed by 10 every 30 epochs""" + lr = 0.001 * (0.1 ** (epoch // 30)) + for param_group in optimizer.param_groups: + param_group['lr'] = lr \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000..d7a8e9b --- /dev/null +++ b/main.py @@ -0,0 +1,83 @@ +import torch +import torch.nn as nn +import torch.optim as optim +from torchtext import data +from gensim.corpora import WikiCorpus +from transformers import GPT2Tokenizer, GPT2Model +from functions import * + +# Define the hyperparameters +num_layers = 2 +batch_size = 32 +hidden_dim = 256 + +# Load the GPT2 model +tokenizer = GPT2Tokenizer.from_pretrained('gpt2') +model = GPT2Model.from_pretrained('gpt2') + +# Load the data +wiki_corpus = WikiCorpus('enwiki-latest-pages-articles.xml.bz2') +stackoverflow_corpus = data.TabularDataset('stackoverflow.csv', format='csv', fields=['text']) + +# Preprocess the data +wiki_data = [text for text in wiki_corpus] +stackoverflow_data = [text for text in stackoverflow_corpus] + +# Convert the data to a format compatible with PyTorch +wiki_data = torch.tensor(wiki_data) +stackoverflow_data = torch.tensor(stackoverflow_data) + +# Define the Adam optimizer +optimizer = optim.Adam(model.parameters(), lr=0.001) + +# Define the loss function +criterion = nn.CrossEntropyLoss() + +# Train the model +num_epochs=10 +labels = torch.tensor([0, 1, 1, 0, 0, 1, 0, 1, 0, 1]) + +def adjust_learning_rate(optimizer, epoch): + """Sets the learning rate to the initial LR decayed by 10 every 30 epochs""" + lr = 0.001 * (0.1 ** (epoch // 30)) + for param_group in optimizer.param_groups: + param_group['lr'] = lr + +for epoch in range(num_epochs): + # Forward pass + outputs = model(wiki_data, stackoverflow_data) + # Calculate the loss + loss = criterion(outputs, labels) + # Backward pass + loss.backward() + # Update the parameters + optimizer.step() + # Reset the gradients + optimizer.zero_grad() + # Evaluate the model + accuracy = evaluate(model, wiki_data) + # Save the model weights and states + torch.save(model.state_dict(), 'model.pth') + # Adjust the learning rate + adjust_learning_rate(optimizer, epoch) + + +# Define the model +class GPT(nn.Module): + def __init__(self, vocab_size, embedding_dim, hidden_dim, num_layers): + super().__init__() + self.embedding = nn.Embedding(vocab_size, embedding_dim) + self.lstm = nn.LSTM(embedding_dim, hidden_dim, num_layers, batch_first=True) + self.fc = nn.Linear(hidden_dim, vocab_size) + self.gpt2 = model + + def forward(self, x): + # Embed the input + x = self.embedding(x) + # Pass through the GPT2 model + x = self.gpt2(x) + # Pass through the LSTM + x, _ = self.lstm(x) + # Pass through the fully connected layer + x = self.fc(x) + return x \ No newline at end of file diff --git a/main2.py b/main2.py new file mode 100644 index 0000000..81dae95 --- /dev/null +++ b/main2.py @@ -0,0 +1,77 @@ +import torch +import torch.nn as nn +import torch.optim as optim +from torchtext import data +from gensim.corpora import WikiCorpus +from transformers import GPT2Tokenizer, GPT2Model +from functions import * + +# Define the model +class GPT(nn.Module): + def __init__(self, vocab_size, embedding_dim, hidden_dim, num_layers): + super().__init__() + self.embedding = nn.Embedding(vocab_size, embedding_dim) + self.lstm = nn.LSTM(embedding_dim, hidden_dim, num_layers, batch_first=True) + self.fc = nn.Linear(hidden_dim, vocab_size) + self.gpt2 = model + + def forward(self, x): + # Embed the input + x = self.embedding(x) + # Pass through the GPT2 model + x = self.gpt2(x) + # Pass through the LSTM + x, _ = self.lstm(x) + # Pass through the fully connected layer + x = self.fc(x) + return x + +# Load the GPT2 model +tokenizer = GPT2Tokenizer.from_pretrained('gpt2') +model = GPT2Model.from_pretrained('gpt2') + +# Load the data +wiki_corpus_en = WikiCorpus('data/enwiki-latest-pages-articles.xml.bz2') +wiki_corpus_fr = WikiCorpus('data/frwiki-latest-pages-articles.xml.bz2') +# stackoverflow_corpus = data.TabularDataset('data/stackoverflow.csv', format='csv', fields=['text']) + +# Preprocess the data +wiki_data_en = [text for text in wiki_corpus_en] +wiki_data_fr = [text for text in wiki_corpus_fr] +# stackoverflow_data = [text for text in stackoverflow_corpus] + +# Convert the data to a format compatible with PyTorch +wiki_data_en = torch.tensor(wiki_data_en) +wiki_data_fr = torch.tensor(wiki_data_fr) +# stackoverflow_data = torch.tensor(stackoverflow_data) + +# Define the Adam optimizer +optimizer = optim.Adam(model.parameters(), lr=0.001) + +# Define the loss function +criterion = nn.CrossEntropyLoss() + +# Train the model +num_epochs=10 +labels = torch.tensor([0, 1, 1, 0, 0, 1, 0, 1, 0, 1]) + +for epoch in range(num_epochs): + # Forward pass + # outputs = model(wiki_data, stackoverflow_data) + outputs = model(wiki_data_en, wiki_data_fr) + # Calculate the loss + loss = criterion(outputs, labels) + # Backward pass + loss.backward() + # Update the parameters + optimizer.step() + # Reset the gradients + optimizer.zero_grad() + # Evaluate the model + accuracy = evaluate(model, wiki_data_en) + # Save the model weights and states + torch.save(model.state_dict(), 'model.pth') + # Adjust the learning rate + adjust_learning_rate(optimizer, epoch) + # Print the loss and accuracy + print('Epoch: {}, Loss: {:.4f}, Accuracy: {:.4f}'.format(epoch+1, loss.item(), accuracy)) \ No newline at end of file